[
  {
    "path": ".changeset/config.json",
    "content": "{\n  \"$schema\": \"https://unpkg.com/@changesets/config@1.6.4/schema.json\",\n  \"changelog\": [\"@changesets/changelog-github\", { \"repo\": \"Effect-TS/effect\" }],\n  \"commit\": false,\n  \"linked\": [],\n  \"access\": \"restricted\",\n  \"baseBranch\": \"main\",\n  \"updateInternalDependencies\": \"patch\",\n  \"ignore\": [\"scratchpad\"],\n  \"snapshot\": {\n    \"useCalculatedVersion\": false,\n    \"prereleaseTemplate\": \"{tag}-{commit}\"\n  }\n}\n"
  },
  {
    "path": ".github/CODEOWNERS",
    "content": "/packages/effect/ @mikearnaldi\n\n/packages/effect/src/Arbitrary.ts @gcanti\n/packages/effect/src/JSONSchema.ts @gcanti\n/packages/effect/src/ParseResult.ts @gcanti\n/packages/effect/src/Pretty.ts @gcanti\n/packages/effect/src/Schema.ts @gcanti\n/packages/effect/src/SchemaAST.ts @gcanti\n/packages/effect/src/internal/schema/ @gcanti\n/packages/effect/test/Schema/ @gcanti\n\n/packages/ai/ @IMax153\n\n/packages/cli/ @IMax153\n\n/packages/cluster/ @tim-smart\n\n/packages/experimental/ @tim-smart\n\n/packages/opentelemetry/ @tim-smart\n\n/packages/platform/ @tim-smart\n/packages/platform-browser/ @tim-smart\n/packages/platform-bun/ @tim-smart\n/packages/platform-node/ @tim-smart\n/packages/platform-node-shared/ @tim-smart\n\n/packages/printer/ @IMax153\n/packages/printer-ansi/ @IMax153\n\n/packages/rpc/ @tim-smart\n\n/packages/sql/ @tim-smart\n/packages/sql-clickhouse/ @tim-smart\n/packages/sql-d1/ @tim-smart\n/packages/sql-drizzle/ @tim-smart\n/packages/sql-kysely/ @tim-smart\n/packages/sql-libsql/ @tim-smart\n/packages/sql-mssql/ @tim-smart\n/packages/sql-mysql2/ @tim-smart\n/packages/sql-pg/ @tim-smart\n/packages/sql-sqlite-bun/ @tim-smart\n/packages/sql-sqlite-do/ @tim-smart\n/packages/sql-sqlite-node/ @tim-smart\n/packages/sql-sqlite-react-native/ @tim-smart\n/packages/sql-sqlite-wasm/ @tim-smart\n\n/packages/typeclass/ @gcanti\n\n/packages/vitest/ @mikearnaldi\n"
  },
  {
    "path": ".github/actions/setup/action.yml",
    "content": "name: Setup\ndescription: Perform standard setup and install dependencies using pnpm.\ninputs:\n  node-version:\n    description: The version of Node.js to install\n    required: true\n    default: 23.7.0\n  registry-url:\n    description: Optional registry to set up for auth.\n\nruns:\n  using: composite\n  steps:\n    - name: Install pnpm\n      uses: pnpm/action-setup@v3\n    - name: Install node\n      uses: actions/setup-node@v4\n      with:\n        cache: pnpm\n        node-version: ${{ inputs.node-version }}\n        registry-url: ${{ inputs.registry-url }}\n    - name: Install dependencies\n      shell: bash\n      run: pnpm install\n"
  },
  {
    "path": ".github/workflows/check.yml",
    "content": "name: Check\non:\n  workflow_dispatch:\n  pull_request:\n    branches: [main, next-minor, next-major]\n  push:\n    branches: [main, next-minor, next-major]\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\npermissions: {}\n\njobs:\n  types:\n    name: Types\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    steps:\n      - uses: actions/checkout@v4\n      - name: Install dependencies\n        uses: ./.github/actions/setup\n      - run: pnpm check\n      - run: pnpm test-types --target '>=5.4'\n\n  lint:\n    name: Lint\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    steps:\n      - uses: actions/checkout@v4\n      - name: Install dependencies\n        uses: ./.github/actions/setup\n      - run: pnpm circular\n      - run: pnpm lint\n      - run: pnpm codegen\n      - name: Check for codegen changes\n        run: git diff --exit-code\n\n  test:\n    name: Test (${{ matrix.runtime }} ${{ matrix.shard }})\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n      matrix:\n        shard: [1/4, 2/4, 3/4, 4/4]\n        # runtime: [Node, Bun] # TODO: Re-enable bun test suite after https://github.com/oven-sh/bun/issues/4145 is resolved\n        runtime: [Node]\n    steps:\n      - uses: actions/checkout@v4\n      - name: Install dependencies\n        uses: ./.github/actions/setup\n      - uses: oven-sh/setup-bun@v1\n        if: matrix.runtime == 'Bun'\n        with:\n          bun-version: 1.0.25\n      - name: Test\n        run: pnpm vitest --shard ${{ matrix.shard }}\n        if: matrix.runtime == 'Node'\n      - name: Test\n        run: bun vitest --shard ${{ matrix.shard }}\n        if: matrix.runtime == 'Bun'\n"
  },
  {
    "path": ".github/workflows/pages.yml",
    "content": "name: Pages\non:\n  workflow_dispatch:\n  pull_request:\n    branches: [main, next-minor, next-major]\n  push:\n    branches: [main, next-minor, next-major]\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\npermissions: {}\n\njobs:\n  build:\n    name: Build\n    runs-on: ubuntu-latest\n    timeout-minutes: 30\n    steps:\n      - uses: actions/checkout@v4\n      - name: Install dependencies\n        uses: ./.github/actions/setup\n      - run: pnpm docgen\n      - name: Build pages Jekyll\n        if: github.repository_owner == 'Effect-Ts' && github.event_name == 'push' && github.ref == 'refs/heads/main'\n        uses: actions/jekyll-build-pages@v1\n        with:\n          source: ./docs\n          destination: ./_site\n      - name: Upload pages artifact\n        if: github.repository_owner == 'Effect-Ts' && github.event_name == 'push' && github.ref == 'refs/heads/main'\n        uses: actions/upload-pages-artifact@v3\n\n  deploy:\n    if: github.repository_owner == 'Effect-Ts' && github.event_name == 'push' && github.ref == 'refs/heads/main'\n    name: Deploy\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    needs: build\n    permissions:\n      pages: write # To deploy to GitHub Pages\n      id-token: write # To verify the deployment originates from an appropriate source\n    environment:\n      name: github-pages\n      url: ${{ steps.deployment.outputs.page_url }}\n    steps:\n      - name: Deploy to GitHub Pages\n        id: deployment\n        uses: actions/deploy-pages@v4\n"
  },
  {
    "path": ".github/workflows/release-queue.yml",
    "content": "name: Release queue\non:\n  issue_comment:\n    types: [created]\n  pull_request_target:\n    branches: [main, next-minor, next-major]\n  push:\n    branches: [main, next-minor, next-major]\n\npermissions: {}\n\njobs:\n  update:\n    if: github.repository_owner == 'Effect-Ts'\n    name: Update\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    permissions:\n      contents: write\n      pull-requests: write\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          fetch-depth: 0\n          token: ${{ secrets.EFFECT_BOT_GH }}\n      - run: gh pr checkout ${{ github.event.pull_request.number }}\n        if: github.event.pull_request\n        env:\n          GITHUB_TOKEN: ${{ secrets.EFFECT_BOT_GH }}\n      - uses: tim-smart/next-release-action@main\n        with:\n          github_token: ${{ secrets.EFFECT_BOT_GH }}\n          packages: effect,@effect/platform\n          git_user: effect-bot\n          git_email: tech-ops@effectful.co\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: Release\non:\n  push:\n    branches: [main]\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n\npermissions: {}\n\njobs:\n  release:\n    if: github.repository_owner == 'Effect-Ts'\n    name: Release\n    runs-on: ubuntu-latest\n    timeout-minutes: 30\n    permissions:\n      contents: write\n      id-token: write\n      pull-requests: write\n    steps:\n      - uses: actions/checkout@v4\n      - name: Install dependencies\n        uses: ./.github/actions/setup\n        with:\n          registry-url: \"https://registry.npmjs.org\"\n      - name: Upgrade npm for OIDC support\n        run: npm install -g npm@latest\n      - name: Create Release Pull Request or Publish\n        uses: changesets/action@v1\n        with:\n          version: pnpm changeset-version\n          publish: pnpm changeset-publish\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/snapshot.yml",
    "content": "name: Snapshot\non:\n  pull_request:\n    branches: [main, next-minor, next-major]\n  workflow_dispatch:\n\npermissions: {}\n\njobs:\n  snapshot:\n    name: Snapshot\n    if: github.repository_owner == 'Effect-Ts'\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    steps:\n      - uses: actions/checkout@v4\n      - name: Install dependencies\n        uses: ./.github/actions/setup\n      - name: Run codemods\n        run: pnpm codemod\n      - name: Build package\n        run: pnpm build\n      - name: Create snapshot\n        id: snapshot\n        run: pnpx pkg-pr-new@0.0.28 publish --pnpm --comment=off ./packages/* ./packages/ai/*\n"
  },
  {
    "path": ".github/workflows/ts-nightly.yml",
    "content": "name: TypeScript's nightly\non:\n  workflow_dispatch:\n  schedule:\n    - cron: \"0 12 * * *\"\n\npermissions: {}\n\njobs:\n  types:\n    name: Types\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    permissions:\n      issues: write\n    steps:\n      - uses: actions/checkout@v4\n      - name: Install dependencies\n        uses: ./.github/actions/setup\n      - name: Run type tests\n        run: pnpm test-types --target next\n      - name: Notify on failed run\n        uses: actions/github-script@v7\n        if: failure()\n        with:\n          script: |\n            github.rest.issues.create({\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              title: \"Failed TypeScript's nightly type test run\",\n              body: `The following type test run against TypeScript's nightly build failed: [#${context.runNumber}](https://github.com/Effect-TS/effect/actions/runs/${context.runId}).`\n            })\n"
  },
  {
    "path": ".gitignore",
    "content": "coverage/\n*.tsbuildinfo\nnode_modules/\n.DS_Store\ntmp/\ndist/\nbuild/\ndocs/\nscratchpad/\n.direnv/\n.idea/\n.env*\n.lalph/\n.repos/\n"
  },
  {
    "path": ".madgerc",
    "content": "{\n  \"detectiveOptions\": {\n    \"ts\": {\n      \"skipTypeImports\": true\n    }\n  }\n}\n"
  },
  {
    "path": ".prettierignore",
    "content": "*.js\n*.ts\n*.cjs\n"
  },
  {
    "path": ".prettierrc.json",
    "content": "{\n  \"semi\": false,\n  \"trailingComma\": \"none\"\n}\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n  \"typescript.tsdk\": \"node_modules/typescript/lib\",\n  \"typescript.preferences.importModuleSpecifier\": \"relative\",\n  \"typescript.enablePromptUseWorkspaceTsdk\": true,\n  \"deno.enable\": false,\n  \"biome.enabled\": false,\n  \"editor.formatOnSave\": true,\n  \"eslint.format.enable\": true,\n  \"[json]\": {\n    \"editor.defaultFormatter\": \"vscode.json-language-features\"\n  },\n  \"[markdown]\": {\n    \"editor.defaultFormatter\": \"esbenp.prettier-vscode\",\n    \"prettier.semi\": false,\n    \"prettier.trailingComma\": \"none\"\n  },\n  \"[javascript]\": {\n    \"editor.defaultFormatter\": \"dbaeumer.vscode-eslint\"\n  },\n  \"[javascriptreact]\": {\n    \"editor.defaultFormatter\": \"dbaeumer.vscode-eslint\"\n  },\n  \"[typescript]\": {\n    \"editor.defaultFormatter\": \"dbaeumer.vscode-eslint\"\n  },\n  \"[typescriptreact]\": {\n    \"editor.defaultFormatter\": \"dbaeumer.vscode-eslint\"\n  },\n  \"eslint.validate\": [\"markdown\", \"javascript\", \"typescript\"],\n  \"editor.codeActionsOnSave\": {\n    \"source.fixAll.eslint\": \"explicit\"\n  },\n  \"editor.quickSuggestions\": {\n    \"other\": true,\n    \"comments\": false,\n    \"strings\": false\n  },\n  \"editor.acceptSuggestionOnCommitCharacter\": true,\n  \"editor.acceptSuggestionOnEnter\": \"on\",\n  \"editor.quickSuggestionsDelay\": 10,\n  \"editor.suggestOnTriggerCharacters\": true,\n  \"editor.tabCompletion\": \"off\",\n  \"editor.suggest.localityBonus\": true,\n  \"editor.suggestSelection\": \"recentlyUsed\",\n  \"editor.wordBasedSuggestions\": \"matchingDocuments\",\n  \"editor.parameterHints.enabled\": true,\n  \"files.insertFinalNewline\": true\n}\n"
  },
  {
    "path": ".vscode/tasks.json",
    "content": "{\n  \"version\": \"2.0.0\",\n  \"tasks\": [\n    {\n      \"label\": \"Watch\",\n      \"type\": \"shell\",\n      \"command\": \"pnpm check -w\",\n      \"options\": {\n        \"cwd\": \"${workspaceRoot}\"\n      },\n      \"group\": {\n        \"kind\": \"build\",\n        \"isDefault\": true\n      },\n      \"isBackground\": true,\n      \"presentation\": {\n        \"group\": \"watch-build\"\n      },\n      \"problemMatcher\": [\n        {\n          \"base\": \"$tsc-watch\",\n          \"fileLocation\": [\n            \"relative\",\n            \"${workspaceRoot}\",\n          ],\n        }\n      ]\n    }\n  ]\n}\n"
  },
  {
    "path": "AGENTS.md",
    "content": "# Agent Instructions\n\nThis is the Effect library repository, focusing on functional programming patterns and effect systems in TypeScript.\n\n## Development Workflow\n\n- The git base branch is `main`\n- Use `pnpm` as the package manager\n\n### Core Principles\n\n- **Zero Tolerance for Errors**: All automated checks must pass\n- **Clarity over Cleverness**: Choose clear, maintainable solutions\n- **Conciseness**: Keep code and any wording concise and to the point. Sacrifice grammar for the sake of concision.\n- **Reduce comments**: Avoid comments unless absolutely required to explain unusual or complex logic. Comments in jsdocs are acceptable.\n\n### Mandatory Validation Steps\n\n- Run `pnpm lint-fix` after editing files\n- Always run tests after making changes: `pnpm test run <test_file.ts>`\n- Run type checking: `pnpm check`\n  - If type checking continues to fail, run `pnpm clean` to clear caches, then re-run `pnpm check`\n- Build the project: `pnpm build`\n- Check JSDoc examples compile: `pnpm docgen`\n\n## Code Style Guidelines\n\n**Always** look at existing code in the repository to learn and follow\nestablished patterns before writing new code.\n\nDo not worry about getting code formatting perfect while writing. Use `pnpm lint-fix`\nto automatically format code according to the project's style guidelines.\n\n### Barrel files\n\nThe `index.ts` files are automatically generated. Do not manually edit them. Use\n`pnpm codegen` to regenerate barrel files after adding or removing modules.\n\n## Changesets\n\nAll pull requests must include a changeset in the `.changeset/` directory.\nThis is important for maintaining a clear changelog and ensuring proper versioning of packages.\n\n## Running test code\n\nIf you need to run some code for testing or debugging purposes, create a new\nfile in the `scratchpad/` directory at the root of the repository. You can then\nrun the file with `tsx scratchpad/your-file.ts`.\n\nMake sure to delete the file after you are done testing.\n\n## Testing\n\nBefore writing tests, look at existing tests in the codebase for similar\nfunctionality to follow established patterns.\n\n- Test files are located in `packages/*/test/` directories for each package\n- Main Effect library tests: `packages/effect/test/`\n- Always verify implementations with tests\n- Run specific tests with: `pnpm test <filename>`\n\n### it.effect Testing Pattern\n\n- Use `it.effect` for all Effect-based tests, not `Effect.runSync` with regular `it`\n- Import `{ assert, describe, it }` from `@effect/vitest`\n- Never use `expect` from vitest in Effect tests - use `assert` methods instead\n- All tests should use `it.effect(\"description\", () => Effect.gen(function*() { ... }))`\n\nBefore writing tests, look at existing tests in the codebase for similar\nfunctionality to follow established patterns.\n\n## Learning about \"effect\" v4\n\nIf you need to learn more about the new version of effect (version 4), you can\naccess the repository here:\n\n\\`.repos/effect-v4\\`\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Effectful Technologies Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "![npm version](https://img.shields.io/npm/v/effect)\n\n# Effect Monorepo\n\n> An ecosystem of tools to build robust applications in TypeScript\n\n## Introduction\n\nWelcome to Effect, a powerful TypeScript framework that provides a fully-fledged functional effect system with a rich standard library.\n\nEffect consists of several packages that work together to help build robust TypeScript applications. The core package, `effect`, serves as the foundation of the framework, offering primitives for managing side effects, ensuring type safety, and supporting concurrency.\n\n## Monorepo Structure\n\nThe Effect monorepo is organized into multiple packages, each extending the core functionality. Below is an overview of the packages included:\n\n| Package                           | Description                                                                                 |                                                                                                    |\n| --------------------------------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |\n| `effect`                          | Core package                                                                                | [README](https://github.com/Effect-TS/effect/blob/main/packages/effect/README.md)                  |\n| `@effect/ai`                      | AI utilities                                                                                | [README](https://github.com/Effect-TS/effect/blob/main/packages/ai/ai/README.md)                   |\n| `@effect/ai-openai`               | OpenAI utilities                                                                            | [README](https://github.com/Effect-TS/effect/blob/main/packages/ai/openai/README.md)               |\n| `@effect/ai-anthropic`            | Anthropic utilities                                                                         | [README](https://github.com/Effect-TS/effect/blob/main/packages/ai/anthropic/README.md)            |\n| `@effect/ai-amazon-bedrock`       | Effect modules for working with Amazon Bedrock AI apis                                      | [README](https://github.com/Effect-TS/effect/blob/main/packages/ai/amazon-bedrock/README.md)       |\n| `@effect/ai-google`               | Effect modules for working with Google AI apis                                              | [README](https://github.com/Effect-TS/effect/blob/main/packages/ai/google/README.md)               |\n| `@effect/cli`                     | CLI utilities                                                                               | [README](https://github.com/Effect-TS/effect/blob/main/packages/cli/README.md)                     |\n| `@effect/cluster`                 | Distributed computing tools                                                                 | [README](https://github.com/Effect-TS/effect/blob/main/packages/cluster/README.md)                 |\n| `@effect/experimental`            | Experimental features and APIs                                                              | [README](https://github.com/Effect-TS/effect/blob/main/packages/experimental/README.md)            |\n| `@effect/opentelemetry`           | [OpenTelemetry](https://opentelemetry.io/) integration                                      | [README](https://github.com/Effect-TS/effect/blob/main/packages/opentelemetry/README.md)           |\n| `@effect/platform`                | Cross-platform runtime utilities                                                            | [README](https://github.com/Effect-TS/effect/blob/main/packages/platform/README.md)                |\n| `@effect/platform-browser`        | Platform utilities for the browser                                                          | [README](https://github.com/Effect-TS/effect/blob/main/packages/platform-browser/README.md)        |\n| `@effect/platform-bun`            | Platform utilities for [Bun](https://bun.sh/)                                               | [README](https://github.com/Effect-TS/effect/blob/main/packages/platform-bun/README.md)            |\n| `@effect/platform-node`           | Platform utilities for [Node.js](https://nodejs.org)                                        | [README](https://github.com/Effect-TS/effect/blob/main/packages/platform-node/README.md)           |\n| `@effect/platform-node-shared`    | Shared utilities for [Node.js](https://nodejs.org)                                          | [README](https://github.com/Effect-TS/effect/blob/main/packages/platform-node-shared/README.md)    |\n| `@effect/printer`                 | General-purpose printing utilities                                                          | [README](https://github.com/Effect-TS/effect/blob/main/packages/printer/README.md)                 |\n| `@effect/printer-ansi`            | ANSI-compatible printing utilities                                                          | [README](https://github.com/Effect-TS/effect/blob/main/packages/printer-ansi/README.md)            |\n| `@effect/rpc`                     | Remote procedure call (RPC) utilities                                                       | [README](https://github.com/Effect-TS/effect/blob/main/packages/rpc/README.md)                     |\n| `@effect/sql`                     | SQL database utilities                                                                      | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql/README.md)                     |\n| `@effect/sql-clickhouse`          | An `@effect/sql` implementation for [ClickHouse](https://clickhouse.com/).                  | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-clickhouse/README.md)          |\n| `@effect/sql-d1`                  | An `@effect/sql` implementation for [Cloudflare D1](https://developers.cloudflare.com/d1/). | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-d1/README.md)                  |\n| `@effect/sql-drizzle`             | An `@effect/sql` implementation for [Drizzle](https://orm.drizzle.team/).                   | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-drizzle/README.md)             |\n| `@effect/sql-kysely`              | An `@effect/sql` implementation for [Kysely](https://kysely.dev/).                          | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-kysely/README.md)              |\n| `@effect/sql-libsql`              | An `@effect/sql` implementation using the `@libsql/client` library.                         | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-libsql/README.md)              |\n| `@effect/sql-mssql`               | An `@effect/sql` implementation using the mssql `tedious` library.                          | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-mssql/README.md)               |\n| `@effect/sql-mysql2`              | An `@effect/sql` implementation using the `mysql2` library.                                 | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-mysql2/README.md)              |\n| `@effect/sql-pg`                  | An `@effect/sql` implementation using the `postgres.js` library.                            | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-pg/README.md)                  |\n| `@effect/sql-sqlite-bun`          | An `@effect/sql` implementation using the `bun:sqlite` library.                             | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-sqlite-bun/README.md)          |\n| `@effect/sql-sqlite-do`           | An `@effect/sql` implementation for Cloudflare Durable Objects sqlite storage.              | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-sqlite-do/README.md)           |\n| `@effect/sql-sqlite-node`         | An `@effect/sql` implementation using the `better-sqlite3` library.                         | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-sqlite-node/README.md)         |\n| `@effect/sql-sqlite-react-native` | An `@effect/sql` implementation using the `react-native-quick-sqlite` library.              | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-sqlite-react-native/README.md) |\n| `@effect/sql-sqlite-wasm`         | An `@effect/sql` implementation using the `@sqlite.org/sqlite-wasm` library.                | [README](https://github.com/Effect-TS/effect/blob/main/packages/sql-sqlite-wasm/README.md)         |\n| `@effect/typeclass`               | Functional programming type classes                                                         | [README](https://github.com/Effect-TS/effect/blob/main/packages/typeclass/README.md)               |\n| `@effect/vitest`                  | Testing utilities for [Vitest](https://vitest.dev/)                                         | [README](https://github.com/Effect-TS/effect/blob/main/packages/vitest/README.md)                  |\n| `@effect/workflow`                | Durable workflows for Effect                                                                | [README](https://github.com/Effect-TS/effect/blob/main/packages/workflow/README.md)                |\n\n# Documentation\n\n## Website\n\nFor detailed information and usage examples, visit the [Effect website](https://www.effect.website/).\n\n## API Reference\n\nFor a complete API reference of the core package `effect`, see the [Effect API documentation](https://effect-ts.github.io/effect/).\n\n## Introduction to Effect\n\nGet started with Effect by watching our introductory video on YouTube. This video provides an overview of Effect and its key features:\n\n[![Introduction to Effect](https://img.youtube.com/vi/ViSiXfBKElQ/maxresdefault.jpg)](https://youtu.be/ViSiXfBKElQ)\n\n# Connect with Our Community\n\nJoin the Effect community on Discord to connect with other developers, ask questions, and share insights: [Join Effect's Discord Community](https://discord.gg/hdt7t7jpvn).\n\n# Contributing via Pull Requests\n\nWe welcome contributions via pull requests! Here are some guidelines to help you get started:\n\n## Setting Up Your Environment\n\nBegin by forking the repository and clone it to your local machine.\n\nNavigate into the cloned repository and create a new branch for your changes:\n\n```bash\ngit checkout -b my-branch\n```\n\nEnsure all required dependencies are installed by running:\n\n```bash\npnpm install  # Requires pnpm version 10.4.0\n```\n\n## Making Changes\n\n### Implement Your Changes\n\nMake the changes you propose to the codebase. If your changes impact functionality, please **add corresponding tests** to validate your updates.\n\n### Validate Your Changes\n\nRun the following commands to ensure your changes do not introduce any issues:\n\n- `pnpm codegen` (optional): Re-generate the package entrypoints in case you have changed the structure of a package or introduced a new module.\n- `pnpm check`: Confirm that the code compiles without errors.\n- `pnpm test`: Execute all unit tests to ensure your changes haven't broken existing functionality.\n- `pnpm circular`: Check for any circular dependencies in imports.\n- `pnpm lint`: Ensure the code adheres to our coding standards.\n  - If you encounter style issues, use `pnpm lint-fix` to automatically correct some of these.\n- `pnpm test-types`: Run type-level tests. Tests are written using [tstyche](https://tstyche.org/).\n- `pnpm docgen`: Ensure the documentation generates correctly and reflects any changes made.\n\n### Document Your Changes\n\n#### JSDoc Comments\n\nWhen adding a new feature, it's important to document your code using JSDoc comments. This helps other developers understand the purpose and usage of your changes. Include at least the following in your JSDoc comments:\n\n- **A Short Description**: Summarize the purpose and functionality of the feature.\n- **Example**: Provide a usage example under the `@example` tag to demonstrate how to use the feature.\n- **Since Version**: Use the `@since` tag to indicate the version in which the feature was introduced. If you're unsure about the version, please consult with a project maintainer.\n- **Category (Optional)**: You can categorize the feature with the `@category` tag to help organize the documentation. If you're unsure about what category to assign, ask a project maintainer.\n\n**Note**: A HTML utility file, [`code2jsdoc-example.html`](/scripts/jsdocs/code2jsdoc-example.html), has been added to assist with creating JSDoc `@example` comments. This web-based interface includes two text areas:\n\n1. An input textarea for pasting example code.\n2. An output textarea that dynamically generates formatted JSDoc `@example` comments.\n\nThis utility helps ensure consistent formatting and streamlines the process of documenting examples. See the following example of its usage:\n\nExample Input:\n\n```ts\nimport { Effect } from \"effect\"\n\nconsole.log(Effect.runSyncExit(Effect.succeed(1)))\n/*\nOutput:\n{\n  _id: \"Exit\",\n  _tag: \"Success\",\n  value: 1\n}\n*/\n```\n\nOutput:\n\n````\n*\n* @example\n* ```ts\n* import { Effect } from \"effect\"\n*\n* console.log(Effect.runSyncExit(Effect.succeed(1)))\n* // Output:\n* // {\n* //   _id: \"Exit\",\n* //   _tag: \"Success\",\n* //   value: 1\n* // }\n* ```\n*\n````\n\nBy using this utility, you can save time and maintain consistency in your JSDoc comments, especially for complex examples.\n\n#### Changeset Documentation\n\nBefore committing your changes, document them with a changeset. This process helps in tracking modifications and effectively communicating them to the project team and users:\n\n```bash\npnpm changeset\n```\n\nDuring the changeset creation process, you will be prompted to select the appropriate level for your changes:\n\n- **patch**: Opt for this if you are making small fixes or minor changes that do not affect the library's overall functionality.\n- **minor**: Choose this for new features that enhance functionality but do not disrupt existing features.\n- **major**: Select this for any changes that result in backward-incompatible modifications to the library.\n\n## Finalizing Your Contribution\n\n### Commit Your Changes\n\nOnce you have documented your changes with a changeset, it’s time to commit them to the repository. Use a clear and descriptive commit message, which could be the same message you used in your changeset:\n\n```bash\ngit commit -am 'Add some feature'\n```\n\n#### Linking to Issues\n\nIf your commit addresses an open issue, reference the issue number directly in your commit message. This helps to link your contribution clearly to specific tasks or bug reports. Additionally, if your commit resolves the issue, you can indicate this by adding a phrase like `\", closes #<issue-number>\"`. For example:\n\n```bash\ngit commit -am 'Add some feature, closes #123'\n```\n\nThis practice not only helps in tracking the progress of issues but also automatically closes the issue when the commit is merged, streamlining project management.\n\n### Push to Your Fork\n\nPush the changes up to your GitHub fork:\n\n```bash\ngit push origin my-branch\n```\n\n### Create a Pull Request\n\nOpen a pull request against the appropriate branch on the original repository:\n\n- `main` branch: For minor patches or bug fixes.\n- `next-minor` branch: For new features that are non-breaking.\n- `next-major` branch: For changes that introduce breaking modifications.\n\nPlease be patient! We will do our best to review your pull request as soon as possible.\n"
  },
  {
    "path": "docker-compose.yaml",
    "content": "services:\n  pg:\n    image: postgres:alpine # Using a lightweight Postgres image\n    environment:\n      POSTGRES_DB: effect_cluster\n      POSTGRES_USER: cluster\n      POSTGRES_PASSWORD: cluster\n    ports:\n      - \"5432:5432\" # Map host port 5432 to container port 5432\n    volumes:\n      - db_data:/var/lib/postgresql/data # Persist data in a named volume\n  redis:\n    image: redis:alpine\n    ports:\n      - \"6379:6379\"\n\nvolumes:\n  db_data: # Define the named volume\n"
  },
  {
    "path": "eslint.config.mjs",
    "content": "import * as effectEslint from \"@effect/eslint-plugin\"\nimport { fixupPluginRules } from \"@eslint/compat\"\nimport { FlatCompat } from \"@eslint/eslintrc\"\nimport js from \"@eslint/js\"\nimport tsParser from \"@typescript-eslint/parser\"\nimport codegen from \"eslint-plugin-codegen\"\nimport _import from \"eslint-plugin-import\"\nimport simpleImportSort from \"eslint-plugin-simple-import-sort\"\nimport sortDestructureKeys from \"eslint-plugin-sort-destructure-keys\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = path.dirname(__filename)\nconst compat = new FlatCompat({\n  baseDirectory: __dirname,\n  recommendedConfig: js.configs.recommended,\n  allConfig: js.configs.all\n})\n\nexport default [\n  {\n    ignores: [\n      \"**/dist\",\n      \"**/build\",\n      \"**/docs\",\n      \"**/.repos/**\",\n      \"**/.lalph/**\",\n      \"**/*.md\"\n    ]\n  },\n  ...compat.extends(\n    \"eslint:recommended\",\n    \"plugin:@typescript-eslint/eslint-recommended\",\n    \"plugin:@typescript-eslint/recommended\"\n  ),\n  ...effectEslint.configs.dprint,\n  {\n    plugins: {\n      import: fixupPluginRules(_import),\n      \"sort-destructure-keys\": sortDestructureKeys,\n      \"simple-import-sort\": simpleImportSort,\n      codegen\n    },\n\n    languageOptions: {\n      parser: tsParser,\n      ecmaVersion: 2018,\n      sourceType: \"module\"\n    },\n\n    settings: {\n      \"import/parsers\": {\n        \"@typescript-eslint/parser\": [\".ts\", \".tsx\"]\n      },\n\n      \"import/resolver\": {\n        typescript: {\n          alwaysTryTypes: true\n        }\n      }\n    },\n\n    rules: {\n      \"codegen/codegen\": \"error\",\n      \"no-fallthrough\": \"off\",\n      \"no-irregular-whitespace\": \"off\",\n      \"object-shorthand\": \"error\",\n      \"prefer-destructuring\": \"off\",\n      \"sort-imports\": \"off\",\n\n      \"no-restricted-syntax\": [\n        \"error\",\n        {\n          selector:\n            \"CallExpression[callee.property.name='push'] > SpreadElement.arguments\",\n          message: \"Do not use spread arguments in Array.push\"\n        }\n      ],\n\n      \"no-unused-vars\": \"off\",\n      \"require-yield\": \"off\",\n      \"prefer-rest-params\": \"off\",\n      \"prefer-spread\": \"off\",\n      \"import/first\": \"error\",\n      \"import/newline-after-import\": \"error\",\n      \"import/no-duplicates\": \"error\",\n      \"import/no-unresolved\": \"off\",\n      \"import/order\": \"off\",\n      \"simple-import-sort/imports\": \"off\",\n      \"sort-destructure-keys/sort-destructure-keys\": \"error\",\n      \"deprecation/deprecation\": \"off\",\n\n      \"@typescript-eslint/array-type\": [\n        \"warn\",\n        {\n          default: \"generic\",\n          readonly: \"generic\"\n        }\n      ],\n\n      \"@typescript-eslint/member-delimiter-style\": 0,\n      \"@typescript-eslint/no-non-null-assertion\": \"off\",\n      \"@typescript-eslint/ban-types\": \"off\",\n      \"@typescript-eslint/no-explicit-any\": \"off\",\n      \"@typescript-eslint/no-empty-object-type\": \"off\",\n      \"@typescript-eslint/no-unsafe-function-type\": \"off\",\n      \"@typescript-eslint/no-wrapper-object-types\": \"off\",\n      \"@typescript-eslint/consistent-type-imports\": \"warn\",\n\n      \"@typescript-eslint/no-unused-vars\": [\n        \"error\",\n        {\n          argsIgnorePattern: \"^_\",\n          varsIgnorePattern: \"^_\"\n        }\n      ],\n\n      \"@typescript-eslint/ban-ts-comment\": \"off\",\n      \"@typescript-eslint/camelcase\": \"off\",\n      \"@typescript-eslint/explicit-function-return-type\": \"off\",\n      \"@typescript-eslint/explicit-module-boundary-types\": \"off\",\n      \"@typescript-eslint/interface-name-prefix\": \"off\",\n      \"@typescript-eslint/no-array-constructor\": \"off\",\n      \"@typescript-eslint/no-use-before-define\": \"off\",\n      \"@typescript-eslint/no-namespace\": \"off\",\n\n      \"@effect/dprint\": [\n        \"error\",\n        {\n          config: {\n            indentWidth: 2,\n            lineWidth: 120,\n            semiColons: \"asi\",\n            quoteStyle: \"alwaysDouble\",\n            trailingCommas: \"never\",\n            operatorPosition: \"maintain\",\n            \"arrowFunction.useParentheses\": \"force\"\n          }\n        }\n      ]\n    }\n  },\n  {\n    files: [\"packages/*/src/**/*\", \"packages/*/test/**/*\"],\n    rules: {\n      \"no-console\": \"error\"\n    }\n  },\n  {\n    files: [\"packages/*/src/**/*\"],\n    rules: {\n      \"@effect/no-import-from-barrel-package\": [\n        \"error\",\n        {\n          packageNames: [\"effect\", \"@effect/platform\", \"@effect/sql\"]\n        }\n      ]\n    }\n  }\n]\n"
  },
  {
    "path": "flake.nix",
    "content": "{\n  inputs = {\n    nixpkgs.url = \"github:nixos/nixpkgs/nixpkgs-unstable\";\n  };\n  outputs =\n    { nixpkgs, ... }:\n    let\n      forAllSystems =\n        function:\n        nixpkgs.lib.genAttrs nixpkgs.lib.systems.flakeExposed (\n          system: function nixpkgs.legacyPackages.${system}\n        );\n    in\n    {\n      formatter = forAllSystems (pkgs: pkgs.alejandra);\n      devShells = forAllSystems (pkgs: {\n        default = pkgs.mkShell {\n          packages = with pkgs; [\n            bun\n            corepack\n            deno\n            nodejs_24\n            python3\n            yq-go\n          ];\n        };\n      });\n    };\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"private\": true,\n  \"type\": \"module\",\n  \"packageManager\": \"pnpm@10.17.1+sha512.17c560fca4867ae9473a3899ad84a88334914f379be46d455cbf92e5cf4b39d34985d452d2583baf19967fa76cb5c17bc9e245529d0b98745721aa7200ecaf7a\",\n  \"scripts\": {\n    \"clean\": \"node scripts/clean.mjs\",\n    \"codegen\": \"pnpm --recursive --parallel --filter \\\"./packages/**/*\\\" run codegen\",\n    \"codemod\": \"node scripts/codemod.mjs\",\n    \"build\": \"tsc -b tsconfig.build.json && pnpm --recursive --parallel --filter \\\"./packages/**/*\\\" run build\",\n    \"circular\": \"node scripts/circular.mjs\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"check-recursive\": \"pnpm --recursive --filter \\\"./packages/**/*\\\" exec tsc -b tsconfig.json\",\n    \"lint\": \"eslint \\\"**/{src,test,examples,scripts,dtslint}/**/*.{ts,mjs}\\\"\",\n    \"lint-fix\": \"pnpm lint --fix\",\n    \"docgen\": \"pnpm --recursive --filter \\\"./packages/**/*\\\" exec docgen && node scripts/docs.mjs\",\n    \"test-types\": \"tstyche\",\n    \"changeset-version\": \"changeset version && node scripts/version.mjs\",\n    \"changeset-publish\": \"pnpm codemod && pnpm build && TEST_DIST= pnpm vitest && changeset publish\"\n  },\n  \"resolutions\": {\n    \"dependency-tree\": \"^10.0.9\",\n    \"detective-amd\": \"^5.0.2\",\n    \"detective-cjs\": \"^5.0.1\",\n    \"detective-es6\": \"^4.0.1\",\n    \"detective-less\": \"^1.0.2\",\n    \"detective-postcss\": \"^6.1.3\",\n    \"detective-sass\": \"^5.0.3\",\n    \"detective-scss\": \"^4.0.3\",\n    \"detective-stylus\": \"^4.0.0\",\n    \"detective-typescript\": \"^11.1.0\"\n  },\n  \"devDependencies\": {\n    \"@babel/cli\": \"^7.27.2\",\n    \"@babel/core\": \"^7.27.1\",\n    \"@babel/plugin-transform-export-namespace-from\": \"^7.27.1\",\n    \"@babel/plugin-transform-modules-commonjs\": \"^7.27.1\",\n    \"@changesets/changelog-github\": \"^0.5.1\",\n    \"@changesets/cli\": \"^2.29.4\",\n    \"@edge-runtime/vm\": \"^5.0.0\",\n    \"@effect/build-utils\": \"^0.8.3\",\n    \"@effect/docgen\": \"https://pkg.pr.new/Effect-TS/docgen/@effect/docgen@e7fe055\",\n    \"@effect/eslint-plugin\": \"^0.3.2\",\n    \"@effect/language-service\": \"^0.23.3\",\n    \"@effect/vitest\": \"workspace:^\",\n    \"@eslint/compat\": \"^1.2.9\",\n    \"@eslint/eslintrc\": \"^3.3.1\",\n    \"@eslint/js\": \"^9.26.0\",\n    \"@types/jscodeshift\": \"^17.3.0\",\n    \"@types/node\": \"^22.15.18\",\n    \"@typescript-eslint/eslint-plugin\": \"^8.32.1\",\n    \"@typescript-eslint/parser\": \"^8.32.1\",\n    \"@vitest/browser\": \"^3.2.4\",\n    \"@vitest/coverage-v8\": \"^3.2.4\",\n    \"@vitest/expect\": \"^3.2.4\",\n    \"@vitest/web-worker\": \"^3.2.4\",\n    \"ast-types\": \"^0.14.2\",\n    \"babel-plugin-annotate-pure-calls\": \"^0.5.0\",\n    \"eslint\": \"^9.26.0\",\n    \"eslint-import-resolver-typescript\": \"^4.3.4\",\n    \"eslint-plugin-codegen\": \"^0.30.0\",\n    \"eslint-plugin-import\": \"^2.31.0\",\n    \"eslint-plugin-simple-import-sort\": \"^12.1.1\",\n    \"eslint-plugin-sort-destructure-keys\": \"^2.0.0\",\n    \"glob\": \"^11.0.2\",\n    \"jscodeshift\": \"^17.3.0\",\n    \"madge\": \"^8.0.0\",\n    \"playwright\": \"^1.52.0\",\n    \"prettier\": \"^3.5.3\",\n    \"rimraf\": \"^6.0.1\",\n    \"tstyche\": \"^6.0.0-beta.5\",\n    \"tsx\": \"^4.19.4\",\n    \"typescript\": \"^5.8.3\",\n    \"vite\": \"^6.1.1\",\n    \"vitest\": \"^3.2.4\"\n  },\n  \"pnpm\": {\n    \"patchedDependencies\": {\n      \"@changesets/assemble-release-plan\": \"patches/@changesets__assemble-release-plan.patch\",\n      \"@changesets/get-github-info@0.6.0\": \"patches/@changesets__get-github-info@0.6.0.patch\"\n    },\n    \"ignoredBuiltDependencies\": [\n      \"cpu-features\",\n      \"esbuild\",\n      \"lmdb\",\n      \"msgpackr-extract\",\n      \"msw\",\n      \"protobufjs\",\n      \"ssh2\",\n      \"workerd\"\n    ],\n    \"onlyBuiltDependencies\": [\n      \"@parcel/watcher\",\n      \"better-sqlite3\",\n      \"sharp\",\n      \"unrs-resolver\"\n    ]\n  }\n}\n"
  },
  {
    "path": "packages/ai/ai/CHANGELOG.md",
    "content": "# @effect/ai\n\n## 0.35.0\n\n### Patch Changes\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n  - @effect/experimental@0.60.0\n  - @effect/platform@0.96.0\n  - @effect/rpc@0.75.0\n\n## 0.34.0\n\n### Patch Changes\n\n- [#6094](https://github.com/Effect-TS/effect/pull/6094) [`88a5260`](https://github.com/Effect-TS/effect/commit/88a5260788d57bb0c31a645fa44b5a68f5c73c38) Thanks @IMax153! - Remove superfluous / defensive check from tool call json schema generation\n\n- [#6101](https://github.com/Effect-TS/effect/pull/6101) [`cf74940`](https://github.com/Effect-TS/effect/commit/cf749405214282edc916a783b3417c766d2bbfe3) Thanks @IMax153! - Prevent schema validation when directly constructing an `AiError.HttpRequestError` / `AiError.HttpResponseError`\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n  - @effect/experimental@0.59.0\n  - @effect/platform@0.95.0\n  - @effect/rpc@0.74.0\n\n## 0.33.2\n\n### Patch Changes\n\n- [#5944](https://github.com/Effect-TS/effect/pull/5944) [`f21f034`](https://github.com/Effect-TS/effect/commit/f21f03477ea9b6fd4662a93097290cb940ce9c2b) Thanks @IMax153! - Fix Prompt.fromResponseParts when input contains a provider executed tool\n\n## 0.33.1\n\n### Patch Changes\n\n- [#5931](https://github.com/Effect-TS/effect/pull/5931) [`ba9e790`](https://github.com/Effect-TS/effect/commit/ba9e7908a80a55f24217c88af4f7d89a4f7bc0e4) Thanks @IMax153! - Fix the accumulation logic for response parts in the AI `Chat` module\n\n- Updated dependencies [[`65e9e35`](https://github.com/Effect-TS/effect/commit/65e9e35157cbdfb40826ddad34555c4ebcf7c0b0), [`ee69cd7`](https://github.com/Effect-TS/effect/commit/ee69cd796feb3d8d1046f52edd8950404cd4ed0e), [`488d6e8`](https://github.com/Effect-TS/effect/commit/488d6e870eda3dfc137f4940bb69416f61ed8fe3)]:\n  - @effect/platform@0.94.1\n  - effect@3.19.14\n\n## 0.33.0\n\n### Patch Changes\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n  - @effect/platform@0.94.0\n  - @effect/experimental@0.58.0\n  - @effect/rpc@0.73.0\n\n## 0.32.1\n\n### Patch Changes\n\n- [#5685](https://github.com/Effect-TS/effect/pull/5685) [`fb53370`](https://github.com/Effect-TS/effect/commit/fb533705e058500a7192810f5373f663c33f0ca4) Thanks @janglad! - Fix Response.Part, AllParts, StreamPart not inferring Schema properly if toolkit is WithHandler\n\n- Updated dependencies [[`7d28a90`](https://github.com/Effect-TS/effect/commit/7d28a908f965854cff386a19515141aea5b39eb7)]:\n  - effect@3.19.3\n\n## 0.32.0\n\n### Patch Changes\n\n- Updated dependencies [[`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - effect@3.19.0\n  - @effect/rpc@0.72.0\n  - @effect/platform@0.93.0\n  - @effect/experimental@0.57.0\n\n## 0.31.1\n\n### Patch Changes\n\n- [#5634](https://github.com/Effect-TS/effect/pull/5634) [`a5d0f2b`](https://github.com/Effect-TS/effect/commit/a5d0f2bd54ec4a791a2ea5b31493bd55882066e0) Thanks @IMax153! - Ensure that tool calls are emitted as soon as possible when streaming\n\n## 0.31.0\n\n### Minor Changes\n\n- [#5621](https://github.com/Effect-TS/effect/pull/5621) [`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825) Thanks @IMax153! - Remove `Either` / `EitherEncoded` from tool call results.\n\n  Specifically, the encoding of tool call results as an `Either` / `EitherEncoded` has been removed and is replaced by encoding the tool call success / failure directly into the `result` property.\n\n  To allow type-safe discrimination between a tool call result which was a success vs. one that was a failure, an `isFailure` property has also been added to the `\"tool-result\"` part. If `isFailure` is `true`, then the tool call handler result was an error.\n\n  ```ts\n  import * as AnthropicClient from \"@effect/ai-anthropic/AnthropicClient\"\n  import * as AnthropicLanguageModel from \"@effect/ai-anthropic/AnthropicLanguageModel\"\n  import * as LanguageModel from \"@effect/ai/LanguageModel\"\n  import * as Tool from \"@effect/ai/Tool\"\n  import * as Toolkit from \"@effect/ai/Toolkit\"\n  import * as NodeHttpClient from \"@effect/platform-node/NodeHttpClient\"\n  import { Config, Effect, Layer, Schema, Stream } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"An example of a tool with success and failure types\",\n    failureMode: \"return\", // Return errors in the response\n    parameters: { bar: Schema.Number },\n    success: Schema.Number,\n    failure: Schema.Struct({ reason: Schema.Literal(\"reason-1\", \"reason-2\") })\n  })\n\n  const MyToolkit = Toolkit.make(MyTool)\n\n  const MyToolkitLayer = MyToolkit.toLayer({\n    MyTool: () => Effect.succeed(42)\n  })\n\n  const program = LanguageModel.streamText({\n    prompt: \"Tell me about the meaning of life\",\n    toolkit: MyToolkit\n  }).pipe(\n    Stream.runForEach((part) => {\n      if (part.type === \"tool-result\" && part.name === \"MyTool\") {\n        // The `isFailure` property can be used to discriminate whether the result\n        // of a tool call is a success or a failure\n        if (part.isFailure) {\n          part.result\n          //   ^? { readonly reason: \"reason-1\" | \"reason-2\"; }\n        } else {\n          part.result\n          //   ^? number\n        }\n      }\n      return Effect.void\n    }),\n    Effect.provide(Claude)\n  )\n\n  const Anthropic = AnthropicClient.layerConfig({\n    apiKey: Config.redacted(\"ANTHROPIC_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(Effect.provide([Anthropic, MyToolkitLayer]), Effect.runPromise)\n  ```\n\n## 0.30.0\n\n### Minor Changes\n\n- [#5614](https://github.com/Effect-TS/effect/pull/5614) [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652) Thanks @IMax153! - Previously, tool call handler errors were _always_ raised as an expected error in the Effect `E` channel at the point of execution of the tool call handler (i.e. when a `generate*` method is invoked on a `LanguageModel`).\n\n  With this PR, the end user now has control over whether tool call handler errors should be raised as an Effect error, or returned by the SDK to allow, for example, sending that error information to another application.\n\n  ### Tool Call Specification\n\n  The `Tool.make` and `Tool.providerDefined` constructors now take an extra optional parameter called `failureMode`, which can be set to either `\"error\"` or `\"return\"`.\n\n  ```ts\n  import { Tool } from \"@effect/ai\"\n  import { Schema } from \"effect\"\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"My special tool\",\n    failureMode: \"return\" // \"error\" (default) or \"return\"\n    parameters: {\n      myParam: Schema.String\n    },\n    success: Schema.Struct({\n      mySuccess: Schema.String\n    }),\n    failure: Schema.Struct({\n      myFailure: Schema.String\n    })\n  })\n\n  ```\n\n  The semantics of `failureMode` are as follows:\n  - If set to `\"error\"` (the default), errors that occur during tool call handler execution will be returned in the error channel of the calling effect\n  - If set to `\"return\"`, errors that occur during tool call handler execution will be captured and returned as part of the tool call result\n\n  ### Response - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a large language model provider response is now represented as an `Either`.\n  - If the `result` is a `Left`, the `result` will be the `failure` specified in the tool call specification\n  - If the `result` is a `Right`, the `result` will be the `success` specified in the tool call specification\n\n  This is only relevant if the end user sets `failureMode` to `\"return\"`. If set to `\"error\"` (the default), then the `result` property will always be a `Right` with the successful result of the tool call handler.\n\n  Similarly the `encodedResult` field of a `\"tool-result\"` part will be represented as an `EitherEncoded`, where:\n  - `{ _tag: \"Left\", left: <failure> }` represents a tool call handler failure\n  - `{ _tag: \"Right\", right: <success> }` represents a tool call handler success\n\n  ### Prompt - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a prompt will now only accept an `EitherEncoded` as specified above.\n\n### Patch Changes\n\n- Updated dependencies [[`6ae2f5d`](https://github.com/Effect-TS/effect/commit/6ae2f5da45a9ed9832605eca12b3e2bf2e2a1a67)]:\n  - effect@3.18.4\n\n## 0.29.1\n\n### Patch Changes\n\n- [#5587](https://github.com/Effect-TS/effect/pull/5587) [`d628c15`](https://github.com/Effect-TS/effect/commit/d628c1527898dc13176185d52e5ea9ee68fd3934) Thanks @IMax153! - Ensure response schema includes toolkit tools even when tool call resolution is disabled\n\n## 0.29.0\n\n### Minor Changes\n\n- [#5302](https://github.com/Effect-TS/effect/pull/5302) [`f8b93ac`](https://github.com/Effect-TS/effect/commit/f8b93ac6446efd3dd790778b0fc71d299a38f272) Thanks @timurrakhimzhan! - Added \"oneOf\" property for generateText and streamText \"toolChoice\" to be able to pick a subset of tools, which are going to be passed to LLM\n\n### Patch Changes\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2)]:\n  - effect@3.18.0\n  - @effect/platform@0.92.0\n  - @effect/experimental@0.56.0\n  - @effect/rpc@0.71.0\n\n## 0.28.4\n\n### Patch Changes\n\n- [#5570](https://github.com/Effect-TS/effect/pull/5570) [`bc83015`](https://github.com/Effect-TS/effect/commit/bc83015e2546957520a91ff6f5728e40c75605b7) Thanks @IMax153! - Redact headers where possible in AiError\n\n- [#5570](https://github.com/Effect-TS/effect/pull/5570) [`bc83015`](https://github.com/Effect-TS/effect/commit/bc83015e2546957520a91ff6f5728e40c75605b7) Thanks @IMax153! - Fix return type of `Response.AllParts`\n\n- [#5568](https://github.com/Effect-TS/effect/pull/5568) [`6c2d586`](https://github.com/Effect-TS/effect/commit/6c2d586ae4dab17d9622424f0e95808131888a1a) Thanks @IMax153! - Support expiration of persisted chats via time to live\n\n## 0.28.3\n\n### Patch Changes\n\n- [#5566](https://github.com/Effect-TS/effect/pull/5566) [`ab57b7a`](https://github.com/Effect-TS/effect/commit/ab57b7af5349fcf22e6c702b793d01079dba69a6) Thanks @IMax153! - Support generation of persistence identifiers for ai chat\n\n- [#5540](https://github.com/Effect-TS/effect/pull/5540) [`5b13482`](https://github.com/Effect-TS/effect/commit/5b134824c1ce7d754deba0a76ac9e2a37d156ef1) Thanks @IMax153! - ensure decoded response metadata is always set\n\n- [#5566](https://github.com/Effect-TS/effect/pull/5566) [`ab57b7a`](https://github.com/Effect-TS/effect/commit/ab57b7af5349fcf22e6c702b793d01079dba69a6) Thanks @IMax153! - fix prompt construction from response parts\n\n## 0.28.2\n\n### Patch Changes\n\n- [#5554](https://github.com/Effect-TS/effect/pull/5554) [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a) Thanks @IMax153! - Accept `Prompt.RawInput` in `Prompt.merge`\n\n- [#5554](https://github.com/Effect-TS/effect/pull/5554) [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a) Thanks @IMax153! - Add `Prompt.setSystem`, `Prompt.prependSystem`, and `Prompt.appendSystem` methods\n\n- [#5554](https://github.com/Effect-TS/effect/pull/5554) [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a) Thanks @IMax153! - Improve the information available to the user following a model response error\n\n- [#5554](https://github.com/Effect-TS/effect/pull/5554) [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a) Thanks @IMax153! - Allow raw user and assistant prompt messages to accept plain strings\n\n- [#5554](https://github.com/Effect-TS/effect/pull/5554) [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a) Thanks @IMax153! - Make `Prompt` pipeable\n\n- [#5554](https://github.com/Effect-TS/effect/pull/5554) [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a) Thanks @IMax153! - Fix leakage of provider-defined tool handler requirements\n\n## 0.28.1\n\n### Patch Changes\n\n- [#5555](https://github.com/Effect-TS/effect/pull/5555) [`aacd472`](https://github.com/Effect-TS/effect/commit/aacd472a9bab389269f74d923ac20cc895c638ee) Thanks @IMax153! - Add support for persisting a `Chat` via `Persistence`\n\n## 0.28.0\n\n### Patch Changes\n\n- Updated dependencies [[`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a)]:\n  - @effect/platform@0.91.0\n  - @effect/rpc@0.70.0\n  - @effect/experimental@0.55.0\n\n## 0.27.1\n\n### Patch Changes\n\n- [#5521](https://github.com/Effect-TS/effect/pull/5521) [`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80) Thanks @IMax153! - Fix provider metadata and parse tool call parameters safely\n\n## 0.27.0\n\n### Minor Changes\n\n- [#5469](https://github.com/Effect-TS/effect/pull/5469) [`42b914a`](https://github.com/Effect-TS/effect/commit/42b914a0e8750350ce17d434afaec7d655ddf4b7) Thanks @IMax153! - Refactor the Effect AI SDK and associated provider packages\n\n  This pull request contains a complete refactor of the base Effect AI SDK package\n  as well as the associated provider integration packages to improve flexibility\n  and enhance ergonomics. Major changes are outlined below.\n\n  ## Modules\n\n  All modules in the base Effect AI SDK have had the leading `Ai` prefix dropped\n  from their name (except for the `AiError` module).\n\n  For example, the `AiLanguageModel` module is now the `LanguageModel` module.\n\n  In addition, the `AiInput` module has been renamed to the `Prompt` module.\n\n  ## Prompts\n\n  The `Prompt` module has been completely redesigned with flexibility in mind.\n\n  The `Prompt` module now supports building a prompt using either the constructors\n  exposed from the `Prompt` module, or using raw prompt content parts / messages,\n  which should be familiar to those coming from other AI SDKs.\n\n  In addition, the `system` option has been removed from all `LanguageModel` methods\n  and must now be provided as part of the prompt.\n\n  **Prompt Constructors**\n\n  ```ts\n  import { LanguageModel, Prompt } from \"@effect/ai\"\n\n  const textPart = Prompt.makePart(\"text\", {\n    text: \"What is machine learning?\"\n  })\n\n  const userMessage = Prompt.makeMessage(\"user\", {\n    content: [textPart]\n  })\n\n  const systemMessage = Prompt.makeMessage(\"system\", {\n    content: \"You are an expert in machine learning\"\n  })\n\n  const program = LanguageModel.generateText({\n    prompt: Prompt.fromMessages([systemMessage, userMessage])\n  })\n  ```\n\n  **Raw Prompt Input**\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n\n  const program = LanguageModel.generateText({\n    prompt: [\n      { role: \"system\", content: \"You are an expert in machine learning\" },\n      {\n        role: \"user\",\n        content: [{ type: \"text\", text: \"What is machine learning?\" }]\n      }\n    ]\n  })\n  ```\n\n  **NOTE**: Providing a plain string as a prompt is still supported, and will be converted\n  internally into a user message with a single text content part.\n\n  ### Provider-Specific Options\n\n  To support specification of provider-specific options when interacting with large\n  language model providers, support has been added for adding provider-specific\n  options to the parts of a `Prompt`.\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-sonnet-4-20250514\")\n\n  const program = LanguageModel.generateText({\n    prompt: [\n      {\n        role: \"user\",\n        content: [{ type: \"text\", text: \"What is machine learning?\" }],\n        options: {\n          anthropic: { cacheControl: { type: \"ephemeral\", ttl: \"1h\" } }\n        }\n      }\n    ]\n  }).pipe(Effect.provide(Claude))\n  ```\n\n  ## Responses\n\n  The `Response` module has also been completely redesigned to support a wider\n  variety of response parts, particularly when streaming.\n\n  ### Streaming Responses\n\n  When streaming text via the `LanguageModel.streamText` method, you will now\n  receive a stream of content parts instead of a stream of responses, which should\n  make it much simpler to filter down the stream to the parts you are interested in.\n\n  In addition, additional content parts will be present in the stream to allow you to track,\n  for example, when a text content part starts / ends.\n\n  ### Tool Calls / Tool Call Results\n\n  The decoded parts of a `Response` (as returned by the methods of `LanguageModel`)\n  are now fully type-safe on tool calls / tool call results. Filtering the content parts of a\n  response to tool calls will narrow the type of the tool call `params` based on the tool\n  `name`. Similarly, filtering the response to tool call results will narrow the type of the\n  tool call `result` based on the tool `name`.\n\n  ```ts\n  import { LanguageModel, Tool, Toolkit } from \"@effect/ai\"\n  import { Effect, Schema } from \"effect\"\n\n  const DadJokeTool = Tool.make(\"DadJokeTool\", {\n    parameters: { topic: Schema.String },\n    success: Schema.Struct({ joke: Schema.String })\n  })\n\n  const FooTool = Tool.make(\"FooTool\", {\n    parameters: { foo: Schema.Number },\n    success: Schema.Struct({ bar: Schema.Boolean })\n  })\n\n  const MyToolkit = Toolkit.make(DadJokeTool, FooTool)\n\n  const program = Effect.gen(function* () {\n    const response = yield* LanguageModel.generateText({\n      prompt: \"Tell me a dad joke\",\n      toolkit: MyToolkit\n    })\n\n    for (const toolCall of response.toolCalls) {\n      if (toolCall.name === \"DadJokeTool\") {\n        //         ^? \"DadJokeTool\" | \"FooTool\"\n        toolCall.params\n        //       ^? { readonly topic: string }\n      }\n    }\n\n    for (const toolResult of response.toolResults) {\n      if (toolResult.name === \"DadJokeTool\") {\n        //           ^? \"DadJokeTool\" | \"FooTool\"\n        toolResult.result\n        //         ^? { readonly joke: string }\n      }\n    }\n  })\n  ```\n\n  ### Provider Metadata\n\n  As with provider-specific options, provider-specific metadata is now returned as\n  part of the response from the large language model provider.\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n  import { Effect } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const program = Effect.gen(function* () {\n    const response = yield* LanguageModel.generateText({\n      prompt: \"What is the meaning of life?\"\n    })\n\n    for (const part of response.content) {\n      // When metadata **is not** defined for a content part, accessing the\n      // provider's key on the part's metadata will return an untyped record\n      if (part.type === \"text\") {\n        const metadata = part.metadata.anthropic\n        //    ^? { readonly [x: string]: unknown } | undefined\n      }\n      // When metadata **is** defined for a content part, accessing the\n      // provider's key on the part's metadata will return typed metadata\n      if (part.type === \"reasoning\") {\n        const metadata = part.metadata.anthropic\n        //    ^? AnthropicReasoningInfo | undefined\n      }\n    }\n  }).pipe(Effect.provide(Claude))\n  ```\n\n  ## Tool Calls\n\n  The `Tool` module has been enhanced to support provider-defined tools (e.g.\n  web search, computer use, etc.). Large language model providers which support\n  calling their own tools now have a separate module present in their provider\n  integration packages which contain definitions for their tools.\n\n  These provider-defined tools can be included alongside user-defined tools in\n  existing `Toolkit`s. Provider-defined tools that require a user-space handler\n  will be raise a type error in the associated `Toolkit` layer if no such handler\n  is defined.\n\n  ```ts\n  import { LanguageModel, Tool, Toolkit } from \"@effect/ai\"\n  import { AnthropicTool } from \"@effect/ai-anthropic\"\n  import { Schema } from \"effect\"\n\n  const DadJokeTool = Tool.make(\"DadJokeTool\", {\n    parameters: { topic: Schema.String },\n    success: Schema.Struct({ joke: Schema.String })\n  })\n\n  const MyToolkit = Toolkit.make(\n    DadJokeTool,\n    AnthropicTool.WebSearch_20250305({ max_uses: 1 })\n  )\n\n  const program = LanguageModel.generateText({\n    prompt: \"Search the web for a dad joke\",\n    toolkit: MyToolkit\n  })\n  ```\n\n  ## AiError\n\n  The `AiError` type has been refactored into a union of different error types\n  which can be raised by the Effect AI SDK. The goal of defining separate error\n  types is to allow providing the end-user with more granular information about\n  the error that occurred.\n\n  For now, the following errors have been defined. More error types may be added\n  over time based upon necessity / use case.\n\n  ```ts\n  type AiError =\n    | HttpRequestError,\n    | HttpResponseError,\n    | MalformedInput,\n    | MalformedOutput,\n    | UnknownError\n  ```\n\n## 0.26.1\n\n### Patch Changes\n\n- [#5453](https://github.com/Effect-TS/effect/pull/5453) [`d6887d5`](https://github.com/Effect-TS/effect/commit/d6887d54a6ec57778cf536b69c2cf96123cb38a6) Thanks @tim-smart! - wait for client to initialize before sending notifications\n\n- Updated dependencies [[`d6887d5`](https://github.com/Effect-TS/effect/commit/d6887d54a6ec57778cf536b69c2cf96123cb38a6)]:\n  - @effect/rpc@0.69.2\n\n## 0.26.0\n\n### Patch Changes\n\n- Updated dependencies [[`3e163b2`](https://github.com/Effect-TS/effect/commit/3e163b24cc2b647e25566ba29ef25c3f57609042)]:\n  - @effect/rpc@0.69.0\n  - @effect/experimental@0.54.6\n\n## 0.25.2\n\n### Patch Changes\n\n- [#5361](https://github.com/Effect-TS/effect/pull/5361) [`292a7c5`](https://github.com/Effect-TS/effect/commit/292a7c54050e3d06a203130f3545207ec5ac633d) Thanks @IMax153! - Add `AiEmbeddingModel.embedMany`\n\n## 0.25.1\n\n### Patch Changes\n\n- [#5351](https://github.com/Effect-TS/effect/pull/5351) [`fd86f93`](https://github.com/Effect-TS/effect/commit/fd86f93217751363c60f3916d391f71c08ec4a72) Thanks @richburdon! - fixes bug where stream currently ignores disableToolCallResolution flag\n\n- Updated dependencies [[`a949539`](https://github.com/Effect-TS/effect/commit/a94953971c2e908890dfda00f8560d317306c328)]:\n  - effect@3.17.7\n  - @effect/experimental@0.54.4\n\n## 0.25.0\n\n### Patch Changes\n\n- Updated dependencies [[`5a0f4f1`](https://github.com/Effect-TS/effect/commit/5a0f4f176687a39d9fa46bb894bb7ac3175b0e87), [`e9cbd26`](https://github.com/Effect-TS/effect/commit/e9cbd2673401723aa811b0535202e4f57baf6d2c)]:\n  - effect@3.17.1\n  - @effect/rpc@0.68.0\n  - @effect/experimental@0.54.0\n\n## 0.24.0\n\n### Patch Changes\n\n- Updated dependencies [[`7813640`](https://github.com/Effect-TS/effect/commit/7813640279d9e3a3e7fc0a29bfb5c6d5fb3c270f)]:\n  - @effect/platform@0.90.0\n  - @effect/experimental@0.54.0\n  - @effect/rpc@0.67.0\n\n## 0.23.0\n\n### Patch Changes\n\n- Updated dependencies [[`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9), [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104), [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63), [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c), [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989), [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636), [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2), [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d)]:\n  - effect@3.17.0\n  - @effect/experimental@0.53.0\n  - @effect/platform@0.89.0\n  - @effect/rpc@0.66.0\n\n## 0.22.2\n\n### Patch Changes\n\n- [#5240](https://github.com/Effect-TS/effect/pull/5240) [`e43b1fd`](https://github.com/Effect-TS/effect/commit/e43b1fd9c4e0897bbf97037fe7cce90448340c29) Thanks @tim-smart! - expose the AiChat history Ref\n\n## 0.22.1\n\n### Patch Changes\n\n- Updated dependencies [[`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec), [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38), [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48)]:\n  - effect@3.16.14\n  - @effect/platform@0.88.1\n  - @effect/experimental@0.52.1\n  - @effect/rpc@0.65.1\n\n## 0.22.0\n\n### Patch Changes\n\n- Updated dependencies [[`27206d7`](https://github.com/Effect-TS/effect/commit/27206d7f0558d7fe28de57bf54f1d0cc83acc92e), [`dbabf5e`](https://github.com/Effect-TS/effect/commit/dbabf5e76fa63b050d2b6c466713c7dc59f07d3c)]:\n  - @effect/platform@0.88.0\n  - @effect/experimental@0.52.0\n  - @effect/rpc@0.65.0\n\n## 0.21.17\n\n### Patch Changes\n\n- Updated dependencies [[`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7), [`5b7cd92`](https://github.com/Effect-TS/effect/commit/5b7cd923e786c38a0802faf0fe75498ab3cccf28), [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db)]:\n  - effect@3.16.13\n  - @effect/rpc@0.64.14\n  - @effect/experimental@0.51.14\n  - @effect/platform@0.87.13\n\n## 0.21.16\n\n### Patch Changes\n\n- Updated dependencies [[`32ba77a`](https://github.com/Effect-TS/effect/commit/32ba77ae304d2161362a73e8b61965332626cf2d), [`d5e25b2`](https://github.com/Effect-TS/effect/commit/d5e25b237f05670ee42b386cb40b2cb448fc11d7)]:\n  - @effect/platform@0.87.12\n  - @effect/experimental@0.51.13\n  - @effect/rpc@0.64.13\n\n## 0.21.15\n\n### Patch Changes\n\n- Updated dependencies [[`79a1947`](https://github.com/Effect-TS/effect/commit/79a1947359cbd89a47ea315cdd86a3d250f28f43), [`001392b`](https://github.com/Effect-TS/effect/commit/001392ba8bfcad101bb034348a7415012fb12f72), [`7bfb099`](https://github.com/Effect-TS/effect/commit/7bfb099cb5528511b8d63045c4fbb4dc9cb18528)]:\n  - @effect/rpc@0.64.12\n  - @effect/platform@0.87.11\n  - @effect/experimental@0.51.12\n\n## 0.21.14\n\n### Patch Changes\n\n- Updated dependencies [[`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0), [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0)]:\n  - @effect/platform@0.87.10\n  - @effect/experimental@0.51.11\n  - @effect/rpc@0.64.11\n\n## 0.21.13\n\n### Patch Changes\n\n- Updated dependencies [[`54514a2`](https://github.com/Effect-TS/effect/commit/54514a2f53166de27ad7e756dbf12194691fd4af)]:\n  - @effect/platform@0.87.9\n  - @effect/experimental@0.51.10\n  - @effect/rpc@0.64.10\n\n## 0.21.12\n\n### Patch Changes\n\n- Updated dependencies [[`4ce4f82`](https://github.com/Effect-TS/effect/commit/4ce4f824f6fdef492be1d35c05a490ffce518c89)]:\n  - @effect/platform@0.87.8\n  - @effect/experimental@0.51.9\n  - @effect/rpc@0.64.9\n\n## 0.21.11\n\n### Patch Changes\n\n- [#5029](https://github.com/Effect-TS/effect/pull/5029) [`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778) Thanks @IMax153! - Add support for generating tool call identifiers when none are returned by the LLM provider\n\n- [#5165](https://github.com/Effect-TS/effect/pull/5165) [`25ca0cf`](https://github.com/Effect-TS/effect/commit/25ca0cf141139cd44ff53081b1c877f8f3ab5e41) Thanks @IMax153! - Ensure that tool call parts are properly merged when combining `AiResponse`s\n\n- [#5029](https://github.com/Effect-TS/effect/pull/5029) [`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778) Thanks @IMax153! - Cleanup AiLanguageModel construction and finish basic support for gemini\n\n## 0.21.10\n\n### Patch Changes\n\n- Updated dependencies [[`a9b617f`](https://github.com/Effect-TS/effect/commit/a9b617f125171ed76cd79ab46d7a924daf3b0e70), [`7e26e86`](https://github.com/Effect-TS/effect/commit/7e26e86524abcc93713d6ad7eee486638c98f7c2)]:\n  - @effect/platform@0.87.7\n  - @effect/experimental@0.51.8\n  - @effect/rpc@0.64.8\n\n## 0.21.9\n\n### Patch Changes\n\n- [#5154](https://github.com/Effect-TS/effect/pull/5154) [`030ac21`](https://github.com/Effect-TS/effect/commit/030ac217eac167d345a095bff26d9c95827fa64c) Thanks @IMax153! - Support disabling tool call resolution to give users more control over resolver execution\n\n- [#5133](https://github.com/Effect-TS/effect/pull/5133) [`aaae9b1`](https://github.com/Effect-TS/effect/commit/aaae9b10345ab5f867b08e1c6eb21685cfc2b078) Thanks @IMax153! - Support extracting tool call results from `AiResponse.WithToolCallResults`\n\n- Updated dependencies [[`905da99`](https://github.com/Effect-TS/effect/commit/905da996aad665057b4ca6dba1a4af44fb8835bd)]:\n  - effect@3.16.12\n  - @effect/experimental@0.51.7\n  - @effect/platform@0.87.6\n  - @effect/rpc@0.64.7\n\n## 0.21.8\n\n### Patch Changes\n\n- Updated dependencies [[`96c1292`](https://github.com/Effect-TS/effect/commit/96c129262835410b311a51d0bf7f58b8f6fc9a12)]:\n  - @effect/experimental@0.51.6\n\n## 0.21.7\n\n### Patch Changes\n\n- Updated dependencies [[`2fd8676`](https://github.com/Effect-TS/effect/commit/2fd8676c803cd40000dfc3231f5daecaa0e0ebd2)]:\n  - @effect/platform@0.87.5\n  - @effect/experimental@0.51.5\n  - @effect/rpc@0.64.6\n\n## 0.21.6\n\n### Patch Changes\n\n- Updated dependencies [[`e82a4fd`](https://github.com/Effect-TS/effect/commit/e82a4fd60f6528d08cef1a4aba0abe0d3ba741ad)]:\n  - @effect/platform@0.87.4\n  - @effect/experimental@0.51.4\n  - @effect/rpc@0.64.5\n\n## 0.21.5\n\n### Patch Changes\n\n- Updated dependencies [[`1b6e396`](https://github.com/Effect-TS/effect/commit/1b6e396d699f3cbbc56b68f99055cf746529bb9e)]:\n  - @effect/platform@0.87.3\n  - @effect/experimental@0.51.3\n  - @effect/rpc@0.64.4\n\n## 0.21.4\n\n### Patch Changes\n\n- Updated dependencies [[`4fea68c`](https://github.com/Effect-TS/effect/commit/4fea68ca7a25a3c39a1ab68b3885534513ab0c81), [`b927954`](https://github.com/Effect-TS/effect/commit/b9279543cf5688dd8a577af80456959c615217d0), [`99590a6`](https://github.com/Effect-TS/effect/commit/99590a6ca9128eb1ede265b6670b655311995614), [`6c3e24c`](https://github.com/Effect-TS/effect/commit/6c3e24c2308f7d4a29b8f4270ab81bca22ac6bb4)]:\n  - @effect/platform@0.87.2\n  - effect@3.16.11\n  - @effect/experimental@0.51.2\n  - @effect/rpc@0.64.3\n\n## 0.21.3\n\n### Patch Changes\n\n- Updated dependencies [[`faad30e`](https://github.com/Effect-TS/effect/commit/faad30ec8742916be59f9db642d0fc98225b636c)]:\n  - effect@3.16.10\n  - @effect/experimental@0.51.1\n  - @effect/platform@0.87.1\n  - @effect/rpc@0.64.2\n\n## 0.21.2\n\n### Patch Changes\n\n- Updated dependencies [[`112a93a`](https://github.com/Effect-TS/effect/commit/112a93a9bab73e95e79f7b3502d1a7b1acd668fc)]:\n  - @effect/rpc@0.64.1\n  - @effect/experimental@0.51.0\n\n## 0.21.1\n\n### Patch Changes\n\n- [#5088](https://github.com/Effect-TS/effect/pull/5088) [`f667373`](https://github.com/Effect-TS/effect/commit/f667373da3471f1e907366780f8c3ea7f52cc5c8) Thanks @tim-smart! - expose system option in AiChat constructors\n\n- Updated dependencies []:\n  - @effect/experimental@0.51.0\n\n## 0.21.0\n\n### Patch Changes\n\n- Updated dependencies [[`b5bac9a`](https://github.com/Effect-TS/effect/commit/b5bac9ac2913fcd11b02322624f03b544eef53ba)]:\n  - @effect/rpc@0.64.0\n  - @effect/platform@0.87.0\n  - @effect/experimental@0.51.0\n\n## 0.20.0\n\n### Patch Changes\n\n- Updated dependencies [[`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`c23d25c`](https://github.com/Effect-TS/effect/commit/c23d25c3e7c541f1f63b28484d8c461d86c67e99), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07)]:\n  - effect@3.16.9\n  - @effect/platform@0.86.0\n  - @effect/experimental@0.50.0\n  - @effect/rpc@0.63.0\n\n## 0.19.4\n\n### Patch Changes\n\n- [#5056](https://github.com/Effect-TS/effect/pull/5056) [`a8d99b2`](https://github.com/Effect-TS/effect/commit/a8d99b2ec2f55d9aa6e7d00a5138e80380716877) Thanks @tim-smart! - add support for mcp 2025-06-18\n\n- Updated dependencies [[`a8d99b2`](https://github.com/Effect-TS/effect/commit/a8d99b2ec2f55d9aa6e7d00a5138e80380716877)]:\n  - @effect/rpc@0.62.4\n  - @effect/experimental@0.49.2\n\n## 0.19.3\n\n### Patch Changes\n\n- Updated dependencies [[`914a191`](https://github.com/Effect-TS/effect/commit/914a191e7cb6341a3d0e965bccd27c336cf22e44)]:\n  - @effect/platform@0.85.2\n  - @effect/experimental@0.49.2\n  - @effect/rpc@0.62.3\n\n## 0.19.2\n\n### Patch Changes\n\n- Updated dependencies [[`ddfd1e4`](https://github.com/Effect-TS/effect/commit/ddfd1e43db60e3b779d18a221344423c5f3c7416)]:\n  - @effect/rpc@0.62.2\n  - @effect/experimental@0.49.1\n\n## 0.19.1\n\n### Patch Changes\n\n- Updated dependencies [[`8cb98d5`](https://github.com/Effect-TS/effect/commit/8cb98d53e68330228287ce2a2e0d8a4c86bcab3b), [`db2dd3c`](https://github.com/Effect-TS/effect/commit/db2dd3c3a8a77d791eae19e66153527e1cde4e6e)]:\n  - effect@3.16.8\n  - @effect/experimental@0.49.1\n  - @effect/platform@0.85.1\n  - @effect/rpc@0.62.1\n\n## 0.19.0\n\n### Patch Changes\n\n- Updated dependencies [[`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e)]:\n  - @effect/platform@0.85.0\n  - @effect/experimental@0.49.0\n  - @effect/rpc@0.62.0\n\n## 0.18.16\n\n### Patch Changes\n\n- [#5040](https://github.com/Effect-TS/effect/pull/5040) [`daed158`](https://github.com/Effect-TS/effect/commit/daed158f2cf00175633284f075cf611c52aa2a1c) Thanks @tim-smart! - allow undefined mcp payloads\n\n## 0.18.15\n\n### Patch Changes\n\n- [#5038](https://github.com/Effect-TS/effect/pull/5038) [`c315989`](https://github.com/Effect-TS/effect/commit/c315989cade6c2a5c9cb157ad85f56b492675add) Thanks @tim-smart! - remove McpServer requirement from McpServer.resource\n\n## 0.18.14\n\n### Patch Changes\n\n- [#5036](https://github.com/Effect-TS/effect/pull/5036) [`cbac1ac`](https://github.com/Effect-TS/effect/commit/cbac1ac61a4e15ad15828563b39eef412bcee66e) Thanks @tim-smart! - add .of helpers to RpcGroup, Entity and AiToolkit\n\n- [#5037](https://github.com/Effect-TS/effect/pull/5037) [`dd4d380`](https://github.com/Effect-TS/effect/commit/dd4d3802f714d59171b1e9226a7babf9723ea952) Thanks @tim-smart! - eliminate McpServer requirement from resource layers\n\n- Updated dependencies [[`1bb0d8a`](https://github.com/Effect-TS/effect/commit/1bb0d8ab96782e99434356266b38251554ea0294), [`cbac1ac`](https://github.com/Effect-TS/effect/commit/cbac1ac61a4e15ad15828563b39eef412bcee66e)]:\n  - effect@3.16.7\n  - @effect/rpc@0.61.15\n  - @effect/experimental@0.48.12\n  - @effect/platform@0.84.11\n\n## 0.18.13\n\n### Patch Changes\n\n- [#4961](https://github.com/Effect-TS/effect/pull/4961) [`aa3a819`](https://github.com/Effect-TS/effect/commit/aa3a819707c15dd39b6d9ae4b4293bd87b74e175) Thanks @IMax153! - add McpServer module\n\n  The McpServer module provides a way to implement a MCP server using Effect.\n\n  Here's an example of how to use the McpServer module to create a simple MCP\n  server with a resource template and a test prompt:\n\n  ```ts\n  import { McpSchema, McpServer } from \"@effect/ai\"\n  import { NodeRuntime, NodeSink, NodeStream } from \"@effect/platform-node\"\n  import { Effect, Layer, Logger, Schema } from \"effect\"\n\n  const idParam = McpSchema.param(\"id\", Schema.NumberFromString)\n\n  // Define a resource template for a README file\n  const ReadmeTemplate = McpServer.resource`file://readme/${idParam}`({\n    name: \"README Template\",\n    // You can add auto-completion for the ID parameter\n    completion: {\n      id: (_) => Effect.succeed([1, 2, 3, 4, 5])\n    },\n    content: Effect.fn(function* (_uri, id) {\n      return `# MCP Server Demo - ID: ${id}`\n    })\n  })\n\n  // Define a test prompt with parameters\n  const TestPrompt = McpServer.prompt({\n    name: \"Test Prompt\",\n    description: \"A test prompt to demonstrate MCP server capabilities\",\n    parameters: Schema.Struct({\n      flightNumber: Schema.String\n    }),\n    completion: {\n      flightNumber: () => Effect.succeed([\"FL123\", \"FL456\", \"FL789\"])\n    },\n    content: ({ flightNumber }) =>\n      Effect.succeed(\n        `Get the booking details for flight number: ${flightNumber}`\n      )\n  })\n\n  // Merge all the resources and prompts into a single server layer\n  const ServerLayer = Layer.mergeAll(ReadmeTemplate, TestPrompt).pipe(\n    // Provide the MCP server implementation\n    Layer.provide(\n      McpServer.layerStdio({\n        name: \"Demo Server\",\n        version: \"1.0.0\",\n        stdin: NodeStream.stdin,\n        stdout: NodeSink.stdout\n      })\n    ),\n    // add a stderr logger\n    Layer.provide(Logger.add(Logger.prettyLogger({ stderr: true })))\n  )\n\n  Layer.launch(ServerLayer).pipe(NodeRuntime.runMain)\n  ```\n\n- Updated dependencies [[`a5f7595`](https://github.com/Effect-TS/effect/commit/a5f75956ef9a15a83c416517ef493f0ee2f5ee8a), [`a02470c`](https://github.com/Effect-TS/effect/commit/a02470c75579e91525a25adb3f21b3650d042fdd), [`bf369b2`](https://github.com/Effect-TS/effect/commit/bf369b2902a0e0b195d957c18b9efd180942cf8b), [`f891d45`](https://github.com/Effect-TS/effect/commit/f891d45adffdafd3f94a2eca23faa354e3a409a8)]:\n  - effect@3.16.6\n  - @effect/platform@0.84.10\n  - @effect/experimental@0.48.11\n  - @effect/rpc@0.61.14\n\n## 0.18.12\n\n### Patch Changes\n\n- Updated dependencies [[`bf418ef`](https://github.com/Effect-TS/effect/commit/bf418ef14a0f2ec965535793d5cea8fa8ba177ac)]:\n  - effect@3.16.5\n  - @effect/experimental@0.48.10\n  - @effect/platform@0.84.9\n\n## 0.18.11\n\n### Patch Changes\n\n- [#5011](https://github.com/Effect-TS/effect/pull/5011) [`2dc5f93`](https://github.com/Effect-TS/effect/commit/2dc5f932f89d260e2f6139c9b89e0548d11d94c2) Thanks @IMax153! - disallow excess options in `AiLanguageModel.generateText` / `AiLanguageModel.streamText`\n\n- Updated dependencies []:\n  - @effect/experimental@0.48.9\n\n## 0.18.10\n\n### Patch Changes\n\n- Updated dependencies [[`8b9db77`](https://github.com/Effect-TS/effect/commit/8b9db7742846af0f58fd8e8b7acb7f4f5ff487ec)]:\n  - @effect/platform@0.84.8\n  - @effect/experimental@0.48.9\n\n## 0.18.9\n\n### Patch Changes\n\n- Updated dependencies [[`74ab9a0`](https://github.com/Effect-TS/effect/commit/74ab9a0a9e16d6e019369d256e1e24175c8bc3f3), [`770008e`](https://github.com/Effect-TS/effect/commit/770008eca3aad2899a2ed951236e575793294b28)]:\n  - effect@3.16.4\n  - @effect/experimental@0.48.8\n  - @effect/platform@0.84.7\n\n## 0.18.8\n\n### Patch Changes\n\n- Updated dependencies [[`a2d57c9`](https://github.com/Effect-TS/effect/commit/a2d57c9ac596445009ca12859b78e00e5d89b936)]:\n  - @effect/experimental@0.48.7\n\n## 0.18.7\n\n### Patch Changes\n\n- Updated dependencies [[`ceea77a`](https://github.com/Effect-TS/effect/commit/ceea77a13055f145520f763e3fce5b8ff15d728f)]:\n  - @effect/platform@0.84.6\n  - @effect/experimental@0.48.6\n\n## 0.18.6\n\n### Patch Changes\n\n- [#4968](https://github.com/Effect-TS/effect/pull/4968) [`85f54ed`](https://github.com/Effect-TS/effect/commit/85f54ed1ecf2f191de8c907247066e3631b5d7e1) Thanks @IMax153! - fix the type of `AiToolkit.Any`\n\n- Updated dependencies [[`ec52c6a`](https://github.com/Effect-TS/effect/commit/ec52c6a2211e76972462b15b9d5a9d6d56761b7a)]:\n  - @effect/platform@0.84.5\n  - @effect/experimental@0.48.5\n\n## 0.18.5\n\n### Patch Changes\n\n- [#4959](https://github.com/Effect-TS/effect/pull/4959) [`4ddb28d`](https://github.com/Effect-TS/effect/commit/4ddb28d230d572735fe34539c1c59005d4932d8a) Thanks @tim-smart! - improve @effect/ai llm schema compatibility\n\n## 0.18.4\n\n### Patch Changes\n\n- Updated dependencies [[`87722fc`](https://github.com/Effect-TS/effect/commit/87722fce693a9b49284bbddbf82d30714c688261), [`36217ee`](https://github.com/Effect-TS/effect/commit/36217eeb1337edd9ac3f9a635b80a6385d22ae8f)]:\n  - effect@3.16.3\n  - @effect/experimental@0.48.4\n  - @effect/platform@0.84.4\n\n## 0.18.3\n\n### Patch Changes\n\n- [#4947](https://github.com/Effect-TS/effect/pull/4947) [`52c88c4`](https://github.com/Effect-TS/effect/commit/52c88c4b7d20ea819b9f2efaf112d03de0a4627b) Thanks @tim-smart! - fix AiToolkit handlers type extraction\n\n- Updated dependencies [[`ab7684f`](https://github.com/Effect-TS/effect/commit/ab7684f1c2a0671bf091f255d220e3a4cc7f528e)]:\n  - @effect/platform@0.84.3\n  - @effect/experimental@0.48.3\n\n## 0.18.2\n\n### Patch Changes\n\n- Updated dependencies [[`0ddf148`](https://github.com/Effect-TS/effect/commit/0ddf148a247aa87af043d276b8453a714a400897)]:\n  - effect@3.16.2\n  - @effect/experimental@0.48.2\n  - @effect/platform@0.84.2\n\n## 0.18.1\n\n### Patch Changes\n\n- Updated dependencies [[`71174d0`](https://github.com/Effect-TS/effect/commit/71174d09691314a9b6b66189e456fd21e3eb6543), [`d615e6e`](https://github.com/Effect-TS/effect/commit/d615e6e5b944f6fd5e627e31752c7ca7e4e1c17d)]:\n  - @effect/platform@0.84.1\n  - effect@3.16.1\n  - @effect/experimental@0.48.1\n\n## 0.18.0\n\n### Minor Changes\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`0552674`](https://github.com/Effect-TS/effect/commit/055267461a3076b06dea896258f4bb2154211fcb) Thanks @IMax153! - Make `AiModel` a plain `Layer` and remove `AiPlan` in favor of `ExecutionPlan`\n\n  This release substantially simplifies and improves the ergonomics of using `AiModel` for various providers. With these changes, an `AiModel` now returns a plain `Layer` which can be used to provide services to a program that interacts with large language models.\n\n  **Before**\n\n  ```ts\n  import { AiLanguageModel } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { NodeHttpClient } from \"@effect/platform-node\"\n  import { Config, Console, Effect, Layer } from \"effect\"\n\n  // Produces an `AiModel<AiLanguageModel, OpenAiClient>`\n  const Gpt4o = OpenAiLanguageModel.model(\"gpt-4o\")\n\n  // Generate a dad joke\n  const getDadJoke = AiLanguageModel.generateText({\n    prompt: \"Tell me a dad joke\"\n  })\n\n  const program = Effect.gen(function* () {\n    // Build the `AiModel` into a `Provider`\n    const gpt4o = yield* Gpt4o\n    // Use the built `AiModel` to run the program\n    const response = yield* gpt4o.use(getDadJoke)\n    // Log the response\n    yield* Console.log(response.text)\n  })\n\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(Effect.provide(OpenAi), Effect.runPromise)\n  ```\n\n  **After**\n\n  ```ts\n  import { AiLanguageModel } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { NodeHttpClient } from \"@effect/platform-node\"\n  import { Config, Console, Effect, Layer } from \"effect\"\n\n  // Produces a `Layer<AiLanguageModel, never, OpenAiClient>`\n  const Gpt4o = OpenAiLanguageModel.model(\"gpt-4o\")\n\n  const program = Effect.gen(function*() {\n    // Generate a dad joke\n    const response = yield* AiLanguageModel.generateText({\n      prompt: \"Tell me a dad joke\"\n    })\n    // Log the response\n    yield* Console.log(response.text)\n  ).pipe(Effect.provide(Gpt4o))\n\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(\n    Effect.provide(OpenAi),\n    Effect.runPromise\n  )\n  ```\n\n  In addition, `AiModel` can be `yield*`'ed to produce a layer with no requirements.\n\n  This shifts the requirements of building the layer into the calling effect, which is particularly useful for creating AI-powered services.\n\n  ```ts\n  import { AiLanguageModel } from \"@effect/ai\"\n  import { OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { Effect } from \"effect\"\n\n  class DadJokes extends Effect.Service<DadJokes>()(\"DadJokes\", {\n    effect: Effect.gen(function* () {\n      // Yielding the model will return a layer with no requirements\n      //\n      //      ┌─── Layer<AiLanguageModel>\n      //      ▼\n      const model = yield* OpenAiLanguageModel.model(\"gpt-4o\")\n\n      const getDadJoke = AiLanguageModel.generateText({\n        prompt: \"Generate a dad joke\"\n      }).pipe(Effect.provide(model))\n\n      return { getDadJoke } as const\n    })\n  }) {}\n\n  // The requirements are lifted into the service constructor\n  //\n  //          ┌─── Layer<DadJokes, never, OpenAiClient>\n  //          ▼\n  DadJokes.Default\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`ee0bd5d`](https://github.com/Effect-TS/effect/commit/ee0bd5d24864752c54cb359f67a67dd903971ec4), [`5189800`](https://github.com/Effect-TS/effect/commit/51898004e11766b8cf6d95e960b636f6d5db79ec), [`58bfeaa`](https://github.com/Effect-TS/effect/commit/58bfeaa64ded8c88f772b184311c0c0dbac10960), [`194d748`](https://github.com/Effect-TS/effect/commit/194d7486943f56f3267ef415395ac220a4b3e634), [`918c9ea`](https://github.com/Effect-TS/effect/commit/918c9ea1a57facb154f0fb26792021f337054dee), [`9198e6f`](https://github.com/Effect-TS/effect/commit/9198e6fcc1a3ff4fefb3363004de558d8de01f40), [`2a370bf`](https://github.com/Effect-TS/effect/commit/2a370bf625fdeede5659721468eb0d527e403279), [`58ccb91`](https://github.com/Effect-TS/effect/commit/58ccb91328c8df5d49808b673738bc09df355201), [`fd47834`](https://github.com/Effect-TS/effect/commit/fd478348203fa89462b0a1d067ce4de034353df4)]:\n  - effect@3.16.0\n  - @effect/experimental@0.48.0\n  - @effect/platform@0.84.0\n\n## 0.17.0\n\n### Patch Changes\n\n- Updated dependencies [[`5522520`](https://github.com/Effect-TS/effect/commit/55225206ab9af0ad60b1c0654690a8a096d625cd), [`cc5bb2b`](https://github.com/Effect-TS/effect/commit/cc5bb2b918a9450a975f702dabcea891bda382cb)]:\n  - @effect/platform@0.83.0\n  - effect@3.15.5\n  - @effect/experimental@0.47.0\n\n## 0.16.9\n\n### Patch Changes\n\n- Updated dependencies [[`0617b9d`](https://github.com/Effect-TS/effect/commit/0617b9dc365f1963b36949ad7f9023ab6eb94524)]:\n  - @effect/platform@0.82.8\n  - @effect/experimental@0.46.8\n\n## 0.16.8\n\n### Patch Changes\n\n- Updated dependencies [[`f570554`](https://github.com/Effect-TS/effect/commit/f57055459524587b041340577dad85476bb35f81), [`78047e8`](https://github.com/Effect-TS/effect/commit/78047e8dfc8005b66f87afe50bb95981fea51561), [`c20b95a`](https://github.com/Effect-TS/effect/commit/c20b95a99ffe452b4774c844d397a905f713b6d6), [`94ada43`](https://github.com/Effect-TS/effect/commit/94ada430928d5685bdbef513e87562c20774a3a2)]:\n  - effect@3.15.4\n  - @effect/platform@0.82.7\n  - @effect/experimental@0.46.7\n\n## 0.16.7\n\n### Patch Changes\n\n- Updated dependencies [[`618903b`](https://github.com/Effect-TS/effect/commit/618903ba9ae96e2bfe6ee31f61c4359b915f2a36)]:\n  - @effect/platform@0.82.6\n  - @effect/experimental@0.46.6\n\n## 0.16.6\n\n### Patch Changes\n\n- Updated dependencies [[`7764a07`](https://github.com/Effect-TS/effect/commit/7764a07d960c60df81f14e1dc949518f4bbe494a), [`4577f54`](https://github.com/Effect-TS/effect/commit/4577f548d67273e576cdde423bdd34a4b910766a), [`30a0d9c`](https://github.com/Effect-TS/effect/commit/30a0d9cb51c84290d51b1361d72ff5cee33c13c7)]:\n  - @effect/platform@0.82.5\n  - effect@3.15.3\n  - @effect/experimental@0.46.5\n\n## 0.16.5\n\n### Patch Changes\n\n- Updated dependencies [[`d45e8a8`](https://github.com/Effect-TS/effect/commit/d45e8a8ac8227192f504e39e6d04fdcf4fb1d225), [`d13b68e`](https://github.com/Effect-TS/effect/commit/d13b68e3a9456d0bfee9bca8273a7b44a9c69087)]:\n  - @effect/platform@0.82.4\n  - @effect/experimental@0.46.4\n\n## 0.16.4\n\n### Patch Changes\n\n- Updated dependencies [[`b8722b8`](https://github.com/Effect-TS/effect/commit/b8722b817e2306fe8c8245f3f9e32d85b824b961), [`a328f4b`](https://github.com/Effect-TS/effect/commit/a328f4b4fe717dd53e5b04a30f387433c32f7328)]:\n  - effect@3.15.2\n  - @effect/platform@0.82.3\n  - @effect/experimental@0.46.3\n\n## 0.16.3\n\n### Patch Changes\n\n- Updated dependencies [[`739a3d4`](https://github.com/Effect-TS/effect/commit/739a3d4a4565915fe2e690003f4f9085cb4422fc)]:\n  - @effect/platform@0.82.2\n  - @effect/experimental@0.46.2\n\n## 0.16.2\n\n### Patch Changes\n\n- Updated dependencies [[`787ce70`](https://github.com/Effect-TS/effect/commit/787ce7042e35b657963473c6efe47752868cd811), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348)]:\n  - effect@3.15.1\n  - @effect/experimental@0.46.1\n  - @effect/platform@0.82.1\n\n## 0.16.1\n\n### Patch Changes\n\n- [#4866](https://github.com/Effect-TS/effect/pull/4866) [`cb3c30f`](https://github.com/Effect-TS/effect/commit/cb3c30f540a83dafcd6d841375073b5e069fa417) Thanks @tim-smart! - preserve tool call results in AiResponse.merge\n\n- Updated dependencies []:\n  - @effect/experimental@0.46.0\n\n## 0.16.0\n\n### Patch Changes\n\n- Updated dependencies [[`c654595`](https://github.com/Effect-TS/effect/commit/c65459587b51da140b78098e81fdbfece65d53e2), [`d9f5dea`](https://github.com/Effect-TS/effect/commit/d9f5deae0f02f5de2b9fcb1cca8b142ba4bc2bba), [`49aa723`](https://github.com/Effect-TS/effect/commit/49aa7236a15e13f818c86edbca08c4af67c8dfaf), [`74c14d0`](https://github.com/Effect-TS/effect/commit/74c14d01d0cb48cf517a1b6e29a373a96ed0ff5b), [`e4f49b6`](https://github.com/Effect-TS/effect/commit/e4f49b66857e01b74ab6a9a0bc7132f44cd04cbb), [`6f02224`](https://github.com/Effect-TS/effect/commit/6f02224b3fc46a682ad2defb1a260841956c6780), [`1dcfd41`](https://github.com/Effect-TS/effect/commit/1dcfd41ff96abd706901293a00c1893cb29dd8fd), [`b21ab16`](https://github.com/Effect-TS/effect/commit/b21ab16b6f773e7ec4369db4e752c35e719f7870), [`fcf1822`](https://github.com/Effect-TS/effect/commit/fcf1822f98fcda60351d64e9d2c2c13563d7e6db), [`0061dd1`](https://github.com/Effect-TS/effect/commit/0061dd140740165e91569a684cce27a77b23229e), [`8421e6e`](https://github.com/Effect-TS/effect/commit/8421e6e49332bca8f96f482dfd48680e238b3a89), [`a9b3fb7`](https://github.com/Effect-TS/effect/commit/a9b3fb78abcfdb525318a956fd02fcadeb56143e), [`fa10f56`](https://github.com/Effect-TS/effect/commit/fa10f56b96bd9af070ba99ebc3279aa93954261e)]:\n  - effect@3.15.0\n  - @effect/platform@0.82.0\n  - @effect/experimental@0.46.0\n\n## 0.15.0\n\n### Minor Changes\n\n- [#4766](https://github.com/Effect-TS/effect/pull/4766) [`a4d42c5`](https://github.com/Effect-TS/effect/commit/a4d42c55669eff56963d06323d155a5bf3082a70) Thanks @IMax153! - This release includes a complete refactor of the internals of the base `@effect/ai` library, with a focus on flexibility for the end user and incorporation of more information from model providers.\n\n  ## Notable Changes\n\n  ### `AiLanguageModel` and `AiEmbeddingModel`\n\n  The `Completions` service from `@effect/ai` has been renamed to `AiLanguageModel`, and the `Embeddings` service has similarly been renamed to `AiEmbeddingModel`. In addition, `Completions.create` and `Completions.toolkit` have been unified into `AiLanguageModel.generateText`. Similarly, `Completions.stream` and `Completions.toolkitStream` have been unified into `AiLanguageModel.streamText`.\n\n  ### Structured Outputs\n\n  `Completions.structured` has been renamed to `AiLanguageModel.generateObject`, and this method now returns a specialized `AiResponse.WithStructuredOutput` type, which contains a `value` property with the result of the structured output call. This enhancement prevents the end user from having to unnecessarily unwrap an `Option`.\n\n  ### `AiModel` and `AiPlan`\n\n  The `.provide` method on a built `AiModel` / `AiPlan` has been renamed to `.use` to improve clarity given that a user is _using_ the services provided by the model / plan to run a particular piece of code.\n\n  In addition, the `AiPlan.fromModel` constructor has been simplified into `AiPlan.make`, which allows you to create an initial `AiPlan` with multiple steps incorporated.\n\n  For example:\n\n  ```ts\n  import { AiPlan } from \"@effect/ai\"\n  import { OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n  import { Effect } from \"effect\"\n\n  const main = Effect.gen(function* () {\n    const plan = yield* AiPlan.make(\n      {\n        model: OpenAiLanguageModel.model(\"gpt-4\"),\n        attempts: 1\n      },\n      {\n        model: AnthropicLanguageModel.model(\"claude-3-7-sonnet-latest\"),\n        attempts: 1\n      },\n      {\n        model: AnthropicLanguageModel.model(\"claude-3-5-sonnet-latest\"),\n        attempts: 1\n      }\n    )\n\n    yield* plan.use(program)\n  })\n  ```\n\n  ### `AiInput` and `AiResponse`\n\n  The `AiInput` and `AiResponse` types have been refactored to allow inclusion of more information and metadata from model providers where possible, such as reasoning output and prompt cache token utilization.\n\n  In addition, for an `AiResponse` you can now access metadata that is specific to a given provider. For example, when using OpenAi to generate audio, you can check the input and output audio tokens used:\n\n  ```ts\n  import { OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { Effect, Option } from \"effect\"\n\n  const getDadJoke = OpenAiLanguageModel.generateText({\n    prompt: \"Generate a hilarious dad joke\"\n  })\n\n  Effect.gen(function* () {\n    const model = yield* OpenAiLanguageModel.model(\"gpt-4o\")\n    const response = yield* model.use(getDadJoke)\n    const metadata = response.getProviderMetadata(\n      OpenAiLanguageModel.ProviderMetadata\n    )\n    if (Option.isSome(metadata)) {\n      console.log(metadata.value)\n    }\n  })\n  ```\n\n  ### `AiTool` and `AiToolkit`\n\n  The `AiToolkit` has been completely refactored to simplify creating a collection of tools and using those tools in requests to model providers. A new `AiTool` data type has also been introduced to simplify defining tools for a toolkit. `AiToolkit.implement` has been renamed to `AiToolkit.toLayer` for clarity, and defining handlers is now very similar to the way handlers are defined in the `@effect/rpc` library.\n\n  A complete example of an `AiToolkit` implementation and usage can be found below:\n\n  ```ts\n  import { AiLanguageModel, AiTool, AiToolkit } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import {\n    FetchHttpClient,\n    HttpClient,\n    HttpClientRequest,\n    HttpClientResponse\n  } from \"@effect/platform\"\n  import { NodeHttpClient, NodeRuntime } from \"@effect/platform-node\"\n  import { Array, Config, Console, Effect, Layer, Schema } from \"effect\"\n\n  // =============================================================================\n  // Domain Models\n  // =============================================================================\n\n  const DadJoke = Schema.Struct({\n    id: Schema.String,\n    joke: Schema.String\n  })\n\n  const SearchResponse = Schema.Struct({\n    current_page: Schema.Int,\n    limit: Schema.Int,\n    next_page: Schema.Int,\n    previous_page: Schema.Int,\n    search_term: Schema.String,\n    results: Schema.Array(DadJoke),\n    status: Schema.Int,\n    total_jokes: Schema.Int,\n    total_pages: Schema.Int\n  })\n\n  // =============================================================================\n  // Service Definitions\n  // =============================================================================\n\n  export class ICanHazDadJoke extends Effect.Service<ICanHazDadJoke>()(\n    \"ICanHazDadJoke\",\n    {\n      dependencies: [FetchHttpClient.layer],\n      effect: Effect.gen(function* () {\n        const httpClient = (yield* HttpClient.HttpClient).pipe(\n          HttpClient.mapRequest(\n            HttpClientRequest.prependUrl(\"https://icanhazdadjoke.com\")\n          )\n        )\n        const httpClientOk = HttpClient.filterStatusOk(httpClient)\n\n        const search = Effect.fn(\"ICanHazDadJoke.search\")(function (\n          term: string\n        ) {\n          return httpClientOk\n            .get(\"/search\", {\n              acceptJson: true,\n              urlParams: { term }\n            })\n            .pipe(\n              Effect.flatMap(HttpClientResponse.schemaBodyJson(SearchResponse)),\n              Effect.orDie\n            )\n        })\n\n        return {\n          search\n        } as const\n      })\n    }\n  ) {}\n\n  // =============================================================================\n  // Toolkit Definition\n  // =============================================================================\n\n  export class DadJokeTools extends AiToolkit.make(\n    AiTool.make(\"GetDadJoke\", {\n      description:\n        \"Fetch a dad joke based on a search term from the ICanHazDadJoke API\",\n      success: DadJoke,\n      parameters: Schema.Struct({\n        searchTerm: Schema.String\n      })\n    })\n  ) {}\n\n  // =============================================================================\n  // Toolkit Handlers\n  // =============================================================================\n\n  export const DadJokeToolHandlers = DadJokeTools.toLayer(\n    Effect.gen(function* () {\n      const icanhazdadjoke = yield* ICanHazDadJoke\n      return {\n        GetDadJoke: (params) =>\n          icanhazdadjoke.search(params.searchTerm).pipe(\n            Effect.flatMap((response) => Array.head(response.results)),\n            Effect.orDie\n          )\n      }\n    })\n  ).pipe(Layer.provide(ICanHazDadJoke.Default))\n\n  // =============================================================================\n  // Toolkit Usage\n  // =============================================================================\n\n  const makeDadJoke = Effect.gen(function* () {\n    const languageModel = yield* AiLanguageModel.AiLanguageModel\n    const toolkit = yield* DadJokeTools\n\n    const response = yield* languageModel.generateText({\n      prompt: \"Come up with a dad joke about pirates\",\n      toolkit\n    })\n\n    return yield* languageModel.generateText({\n      prompt: response\n    })\n  })\n\n  const program = Effect.gen(function* () {\n    const model = yield* OpenAiLanguageModel.model(\"gpt-4o\")\n    const result = yield* model.provide(makeDadJoke)\n    yield* Console.log(result.text)\n  })\n\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(\n    Effect.provide([OpenAi, DadJokeToolHandlers]),\n    Effect.tapErrorCause(Effect.logError),\n    NodeRuntime.runMain\n  )\n  ```\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/experimental@0.45.1\n\n## 0.14.1\n\n### Patch Changes\n\n- Updated dependencies [[`24a9ebb`](https://github.com/Effect-TS/effect/commit/24a9ebbb5af598f0bfd6ecc45307e528043fe011)]:\n  - effect@3.14.22\n  - @effect/experimental@0.45.1\n  - @effect/platform@0.81.1\n\n## 0.14.0\n\n### Patch Changes\n\n- Updated dependencies [[`672920f`](https://github.com/Effect-TS/effect/commit/672920f85da8abd5f9d4ad85e29248a2aca57ed8)]:\n  - @effect/platform@0.81.0\n  - @effect/experimental@0.45.0\n\n## 0.13.21\n\n### Patch Changes\n\n- Updated dependencies [[`2f3b7d4`](https://github.com/Effect-TS/effect/commit/2f3b7d4e1fa1ef8790b0ca4da22eb88872ee31df)]:\n  - effect@3.14.21\n  - @effect/experimental@0.44.21\n  - @effect/platform@0.80.21\n\n## 0.13.20\n\n### Patch Changes\n\n- Updated dependencies [[`17e2f30`](https://github.com/Effect-TS/effect/commit/17e2f3091408cf0fca9414d4af3bdf7b2765b378)]:\n  - effect@3.14.20\n  - @effect/experimental@0.44.20\n  - @effect/platform@0.80.20\n\n## 0.13.19\n\n### Patch Changes\n\n- Updated dependencies [[`056a910`](https://github.com/Effect-TS/effect/commit/056a910d0a0b8b00b0dc9df4a070466b2b5c2f6c), [`e25e7bb`](https://github.com/Effect-TS/effect/commit/e25e7bbc1797733916f48f501425d9f2ef310d9f), [`3273d57`](https://github.com/Effect-TS/effect/commit/3273d572c2b3175a842677f19efeea4cd65ab016)]:\n  - effect@3.14.19\n  - @effect/platform@0.80.19\n  - @effect/experimental@0.44.19\n\n## 0.13.18\n\n### Patch Changes\n\n- Updated dependencies [[`b1164d4`](https://github.com/Effect-TS/effect/commit/b1164d49a1dfdf299e9971367b6fc6be4df0ddff)]:\n  - effect@3.14.18\n  - @effect/experimental@0.44.18\n  - @effect/platform@0.80.18\n\n## 0.13.17\n\n### Patch Changes\n\n- Updated dependencies [[`0b54681`](https://github.com/Effect-TS/effect/commit/0b54681cd89245e211d8f49272be0f1bf2f81813), [`41a59d5`](https://github.com/Effect-TS/effect/commit/41a59d5916a296b12b0d5ead9e859e05f40b4cce)]:\n  - effect@3.14.17\n  - @effect/experimental@0.44.17\n  - @effect/platform@0.80.17\n\n## 0.13.16\n\n### Patch Changes\n\n- Updated dependencies [[`ee14444`](https://github.com/Effect-TS/effect/commit/ee144441021ec77039e43396eaf90714687bb495), [`f1c8583`](https://github.com/Effect-TS/effect/commit/f1c8583f8c3ea9415f813795ca2940a897c9ba9a)]:\n  - effect@3.14.16\n  - @effect/platform@0.80.16\n  - @effect/experimental@0.44.16\n\n## 0.13.15\n\n### Patch Changes\n\n- Updated dependencies [[`239cc99`](https://github.com/Effect-TS/effect/commit/239cc995ce645946210a3c3d2cb52bd3547c0687), [`8b6c947`](https://github.com/Effect-TS/effect/commit/8b6c947eaa8e45a67ecb3c37d45cd27f3e41d165), [`c50a63b`](https://github.com/Effect-TS/effect/commit/c50a63bbecb9f560b9cae349c447eed877d1b9b6)]:\n  - effect@3.14.15\n  - @effect/experimental@0.44.15\n  - @effect/platform@0.80.15\n\n## 0.13.14\n\n### Patch Changes\n\n- Updated dependencies [[`6ed8d15`](https://github.com/Effect-TS/effect/commit/6ed8d1589beb181d30abc79afebdaabc1d101538)]:\n  - effect@3.14.14\n  - @effect/experimental@0.44.14\n  - @effect/platform@0.80.14\n\n## 0.13.13\n\n### Patch Changes\n\n- Updated dependencies [[`ee77788`](https://github.com/Effect-TS/effect/commit/ee77788747e7ebbde6bfa88256cde49dbbad3608), [`5fce6ba`](https://github.com/Effect-TS/effect/commit/5fce6ba19c3cc63cc0104e737e581ad989dedbf0), [`570e45f`](https://github.com/Effect-TS/effect/commit/570e45f8cb936e42ec48f67f21bb2b7252f36c0c)]:\n  - effect@3.14.13\n  - @effect/experimental@0.44.13\n  - @effect/platform@0.80.13\n\n## 0.13.12\n\n### Patch Changes\n\n- Updated dependencies [[`c2ad9ee`](https://github.com/Effect-TS/effect/commit/c2ad9ee9f3c4c743390edf35ed9e85a20be33811), [`9c68654`](https://github.com/Effect-TS/effect/commit/9c686542b6eb3ea188cb70673ef2e41223633e89)]:\n  - effect@3.14.12\n  - @effect/experimental@0.44.12\n  - @effect/platform@0.80.12\n\n## 0.13.11\n\n### Patch Changes\n\n- Updated dependencies [[`e536127`](https://github.com/Effect-TS/effect/commit/e536127c1e6f2fb3a542c73ae919435a629a346b)]:\n  - effect@3.14.11\n  - @effect/experimental@0.44.11\n  - @effect/platform@0.80.11\n\n## 0.13.10\n\n### Patch Changes\n\n- Updated dependencies [[`bc7efa3`](https://github.com/Effect-TS/effect/commit/bc7efa3b031bb25e1ed3c8f2d3fb5e8da166cadc)]:\n  - effect@3.14.10\n  - @effect/experimental@0.44.10\n  - @effect/platform@0.80.10\n\n## 0.13.9\n\n### Patch Changes\n\n- Updated dependencies [[`d78249f`](https://github.com/Effect-TS/effect/commit/d78249f0b67f63cf4baf806ff090cba33293daf0)]:\n  - effect@3.14.9\n  - @effect/experimental@0.44.9\n  - @effect/platform@0.80.9\n\n## 0.13.8\n\n### Patch Changes\n\n- Updated dependencies [[`b3a2d32`](https://github.com/Effect-TS/effect/commit/b3a2d32772e6f7f20eacf2e18128e99324c4d378)]:\n  - effect@3.14.8\n  - @effect/experimental@0.44.8\n  - @effect/platform@0.80.8\n\n## 0.13.7\n\n### Patch Changes\n\n- Updated dependencies [[`b542a4b`](https://github.com/Effect-TS/effect/commit/b542a4bf195be0c9af1523e1ba96c953decc4d25)]:\n  - effect@3.14.7\n  - @effect/experimental@0.44.7\n  - @effect/platform@0.80.7\n\n## 0.13.6\n\n### Patch Changes\n\n- Updated dependencies [[`47618c1`](https://github.com/Effect-TS/effect/commit/47618c1ad84ebcc5a51133a3fff5aa5012d49d45), [`6077882`](https://github.com/Effect-TS/effect/commit/60778824a4794336c33807801f813f8751d1c7e4)]:\n  - effect@3.14.6\n  - @effect/experimental@0.44.6\n  - @effect/platform@0.80.6\n\n## 0.13.5\n\n### Patch Changes\n\n- Updated dependencies [[`40dbfef`](https://github.com/Effect-TS/effect/commit/40dbfeff239b6e567706752114f31b2fce7de4e3), [`85fba81`](https://github.com/Effect-TS/effect/commit/85fba815ac07eb13d4227a69ac76a18e4b94df18), [`5a5ebdd`](https://github.com/Effect-TS/effect/commit/5a5ebdddfaddd259538b4599a6676281faca778e)]:\n  - effect@3.14.5\n  - @effect/platform@0.80.5\n  - @effect/experimental@0.44.5\n\n## 0.13.4\n\n### Patch Changes\n\n- Updated dependencies [[`e4ba2c6`](https://github.com/Effect-TS/effect/commit/e4ba2c66a878e81b5e295d6d49aaf724b80a28ef)]:\n  - effect@3.14.4\n  - @effect/experimental@0.44.4\n  - @effect/platform@0.80.4\n\n## 0.13.3\n\n### Patch Changes\n\n- Updated dependencies [[`37aa8e1`](https://github.com/Effect-TS/effect/commit/37aa8e137725a902e70cd1e468ea98b873aa5056), [`34f03d6`](https://github.com/Effect-TS/effect/commit/34f03d66875f21f266f102223a03cd14c2ed6ea6)]:\n  - effect@3.14.3\n  - @effect/experimental@0.44.3\n  - @effect/platform@0.80.3\n\n## 0.13.2\n\n### Patch Changes\n\n- Updated dependencies [[`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`0a3e3e1`](https://github.com/Effect-TS/effect/commit/0a3e3e18eea5e0d1882f1a6c906198e6ef226a41)]:\n  - effect@3.14.2\n  - @effect/experimental@0.44.2\n  - @effect/platform@0.80.2\n\n## 0.13.1\n\n### Patch Changes\n\n- Updated dependencies [[`4a274fe`](https://github.com/Effect-TS/effect/commit/4a274fe9f623182b6b902827e0e83bd89ca3b05c)]:\n  - effect@3.14.1\n  - @effect/experimental@0.44.1\n  - @effect/platform@0.80.1\n\n## 0.13.0\n\n### Patch Changes\n\n- Updated dependencies [[`1f47e4e`](https://github.com/Effect-TS/effect/commit/1f47e4e12546ab691b29bfb7b5128bb17b93baa5), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`3131f8f`](https://github.com/Effect-TS/effect/commit/3131f8fd12ba9eb31b90fa2f42bf88b12309133c), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`04dff2d`](https://github.com/Effect-TS/effect/commit/04dff2d01ac68c260f29a6d4743381825c353c86), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`c7fac0c`](https://github.com/Effect-TS/effect/commit/c7fac0cd7eadcd5cc0c3a987051c5b57ad271638), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`ffaa3f3`](https://github.com/Effect-TS/effect/commit/ffaa3f3969df26610fcc02ad537340641d44e803), [`ab957c1`](https://github.com/Effect-TS/effect/commit/ab957c1fee714868f56c7ab4e802b9d449e9b666), [`35db9ce`](https://github.com/Effect-TS/effect/commit/35db9ce228f1416c8abacc6dc9c36fbd0f33ef0f), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`cf77ea9`](https://github.com/Effect-TS/effect/commit/cf77ea9ab4fc89e66a43f682a9926ccdee6c57ed), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`baaab60`](https://github.com/Effect-TS/effect/commit/baaab60b737f35dfab8e4a21bce28a195d19e899)]:\n  - effect@3.14.0\n  - @effect/experimental@0.44.0\n  - @effect/platform@0.80.0\n\n## 0.12.4\n\n### Patch Changes\n\n- Updated dependencies [[`5662363`](https://github.com/Effect-TS/effect/commit/566236361e270e575ef1cbf308ad1967c82a362c), [`5f1fd15`](https://github.com/Effect-TS/effect/commit/5f1fd15308ab154791580059b89877d19a2055c2), [`8bb1460`](https://github.com/Effect-TS/effect/commit/8bb1460c824f66f0f25ebd899c5e74e388089c37)]:\n  - @effect/platform@0.79.4\n  - @effect/experimental@0.43.4\n\n## 0.12.3\n\n### Patch Changes\n\n- Updated dependencies [[`0c4803f`](https://github.com/Effect-TS/effect/commit/0c4803fcc69262d11a97ce49d0e9b4288df0651f), [`6f65ac4`](https://github.com/Effect-TS/effect/commit/6f65ac4eac1489cd6ea390e18b0908670722adad)]:\n  - effect@3.13.12\n  - @effect/experimental@0.43.3\n  - @effect/platform@0.79.3\n\n## 0.12.2\n\n### Patch Changes\n\n- Updated dependencies [[`fad8cca`](https://github.com/Effect-TS/effect/commit/fad8cca9bbfcc2eaeb44b97c15dbe0a1eda75315), [`4296293`](https://github.com/Effect-TS/effect/commit/4296293049414d0cf2d915a26c552b09f946b9a0), [`9c241ab`](https://github.com/Effect-TS/effect/commit/9c241abe47ccf7a5257b98a4a64a63054a12741d), [`082b0c1`](https://github.com/Effect-TS/effect/commit/082b0c1b9f4252bcdd69608f2e4a9226f953ac3f), [`be12983`](https://github.com/Effect-TS/effect/commit/be12983bc7e7537b41cd8910fc4eb7d1da56ab07), [`de88127`](https://github.com/Effect-TS/effect/commit/de88127a5a5906ccece98af74787b5ae0e65e431)]:\n  - effect@3.13.11\n  - @effect/experimental@0.43.2\n  - @effect/platform@0.79.2\n\n## 0.12.1\n\n### Patch Changes\n\n- Updated dependencies [[`527c964`](https://github.com/Effect-TS/effect/commit/527c9645229f5be9714a7e60a38a9e753c4bbfb1)]:\n  - effect@3.13.10\n  - @effect/experimental@0.43.1\n  - @effect/platform@0.79.1\n\n## 0.12.0\n\n### Patch Changes\n\n- Updated dependencies [[`88fe129`](https://github.com/Effect-TS/effect/commit/88fe12923740765c0335a6e6203fdcc6a463edca), [`d630249`](https://github.com/Effect-TS/effect/commit/d630249426113088abe8b382db4f14d80f2160c2), [`2976e52`](https://github.com/Effect-TS/effect/commit/2976e52538d9dc9ffdcbc84d4ac748cff9305971)]:\n  - @effect/platform@0.79.0\n  - effect@3.13.9\n  - @effect/experimental@0.43.0\n\n## 0.11.1\n\n### Patch Changes\n\n- Updated dependencies [[`c65d336`](https://github.com/Effect-TS/effect/commit/c65d3362d07ec815ff3b46278314e8a31706ddc2), [`22d2ebb`](https://github.com/Effect-TS/effect/commit/22d2ebb4b11f5a44351a4736e65da391a3b647d0)]:\n  - effect@3.13.8\n  - @effect/experimental@0.42.1\n  - @effect/platform@0.78.1\n\n## 0.11.0\n\n### Patch Changes\n\n- Updated dependencies [[`c5bcf53`](https://github.com/Effect-TS/effect/commit/c5bcf53b7cb49dacffdd2a6cd8eb48cc452b417e)]:\n  - @effect/platform@0.78.0\n  - @effect/experimental@0.42.0\n\n## 0.10.7\n\n### Patch Changes\n\n- [#4545](https://github.com/Effect-TS/effect/pull/4545) [`a95108a`](https://github.com/Effect-TS/effect/commit/a95108acac7f25fc5e1c0dcdf16bcc638dca5c00) Thanks @IMax153! - Avoid inclusion of `_tag` in tool call JSONSchema\n\n- Updated dependencies [[`840cc73`](https://github.com/Effect-TS/effect/commit/840cc7329908db7ca693ef47b07d4f845c29cadd), [`9bf8a74`](https://github.com/Effect-TS/effect/commit/9bf8a74b967f18d931743dd5196af326c9118e9c), [`87ba23c`](https://github.com/Effect-TS/effect/commit/87ba23c41c193503ed0c612b0d32d0b253794c64), [`f910880`](https://github.com/Effect-TS/effect/commit/f91088069057f3b4529753f5bc5532b028d726df), [`0d01480`](https://github.com/Effect-TS/effect/commit/0d014803e4f688f74386a80abd65485e1a319244)]:\n  - @effect/platform@0.77.7\n  - effect@3.13.7\n  - @effect/experimental@0.41.7\n\n## 0.10.6\n\n### Patch Changes\n\n- Updated dependencies [[`3154ce4`](https://github.com/Effect-TS/effect/commit/3154ce4692fa18b804982158d3c4c8a8a5fae386)]:\n  - effect@3.13.6\n  - @effect/experimental@0.41.6\n  - @effect/platform@0.77.6\n\n## 0.10.5\n\n### Patch Changes\n\n- [#4549](https://github.com/Effect-TS/effect/pull/4549) [`3d6d323`](https://github.com/Effect-TS/effect/commit/3d6d323c2a1028f3caba45453187b9374bac2c36) Thanks @IMax153! - Fix `AiPlan` builder to return correct shape\n\n- [#4537](https://github.com/Effect-TS/effect/pull/4537) [`975c20e`](https://github.com/Effect-TS/effect/commit/975c20e446186e9bb975f77e7c6ac7b248f7b5f6) Thanks @IMax153! - Allow defects to pass through predicates in `AiPlan`\n\n- Updated dependencies [[`367bb35`](https://github.com/Effect-TS/effect/commit/367bb35f4c2a254e1fb211d96db2474a7aed9020), [`6cf11c3`](https://github.com/Effect-TS/effect/commit/6cf11c3a75773ceec2877c85ddc760f381f0866d), [`a0acec8`](https://github.com/Effect-TS/effect/commit/a0acec851f72e19466363d24b9cc218acd00006a)]:\n  - effect@3.13.5\n  - @effect/experimental@0.41.5\n  - @effect/platform@0.77.5\n\n## 0.10.4\n\n### Patch Changes\n\n- Updated dependencies [[`e0746f9`](https://github.com/Effect-TS/effect/commit/e0746f9aa398b69c6542e375910683bf17f49f46), [`17d9e89`](https://github.com/Effect-TS/effect/commit/17d9e89f9851663bdbb6c1e685601d97806114a4)]:\n  - @effect/platform@0.77.4\n  - effect@3.13.4\n  - @effect/experimental@0.41.4\n\n## 0.10.3\n\n### Patch Changes\n\n- [#4504](https://github.com/Effect-TS/effect/pull/4504) [`a67a8a1`](https://github.com/Effect-TS/effect/commit/a67a8a1a4979fb7a039a060d067d805879da4d4b) Thanks @IMax153! - Introduce `AiModel` and `AiPlan` for describing retry / fallback logic between\n  models and providers\n\n  For example, the following program builds an `AiPlan` which will attempt to use\n  OpenAi's chat completions API, and if after three attempts the operation\n  is still failing, the plan will fallback to utilizing Anthropic's messages API\n  to resolve the request.\n\n  ```ts\n  import { AiPlan, Completions } from \"@effect/ai\"\n  import { AnthropicClient, AnthropicCompletions } from \"@effect/ai-anthropic\"\n  import { OpenAiClient, OpenAiCompletions } from \"@effect/ai-openai\"\n  import { NodeHttpClient, NodeRuntime } from \"@effect/platform-node\"\n  import { Config, Console, Effect, Layer } from \"effect\"\n\n  // Create Anthropic client\n  const Anthropic = AnthropicClient.layerConfig({\n    apiKey: Config.redacted(\"ANTHROPIC_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  // Create OpenAi client\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  // Create a plan of request execution\n  const Plan = AiPlan.fromModel(OpenAiCompletions.model(\"gpt-4o-mini\"), {\n    attempts: 3\n  }).pipe(\n    AiPlan.withFallback({\n      model: AnthropicCompletions.model(\"claude-3-5-haiku-latest\")\n    })\n  )\n\n  const program = Effect.gen(function* () {\n    // Build the plan of execution\n    const plan = yield* Plan\n\n    // Create a program which uses the services provided by the plan\n    const getDadJoke = Effect.gen(function* () {\n      const completions = yield* Completions.Completions\n      const response = yield* completions.create(\"Tell me a dad joke\")\n      yield* Console.log(response.text)\n    })\n\n    // Provide the plan to whichever programs need it\n    yield* plan.provide(getDadJoke)\n  })\n\n  program.pipe(Effect.provide([Anthropic, OpenAi]), NodeRuntime.runMain)\n  ```\n\n- Updated dependencies [[`cc5588d`](https://github.com/Effect-TS/effect/commit/cc5588df07f9103513547cb429ce041b9436a8bd), [`623c8cd`](https://github.com/Effect-TS/effect/commit/623c8cd053ed6ee3d353aaa8778d484670fca2bb), [`00b4eb1`](https://github.com/Effect-TS/effect/commit/00b4eb1ece12a16e222e6220965bb4024d6752ac), [`f2aee98`](https://github.com/Effect-TS/effect/commit/f2aee989b0a600900ce83e7f460d02908620c80f), [`fb798eb`](https://github.com/Effect-TS/effect/commit/fb798eb9061f1191badc017d1aa649360254da20), [`2251b15`](https://github.com/Effect-TS/effect/commit/2251b1528810bb695b37ce388b653cec0c5bf80c), [`2e15c1e`](https://github.com/Effect-TS/effect/commit/2e15c1e33648add0b29fe274fbcb7294b7515085), [`a4979db`](https://github.com/Effect-TS/effect/commit/a4979db021aef16e731be64df196b72088fc4376), [`b74255a`](https://github.com/Effect-TS/effect/commit/b74255a304ad49d60bedb1a260fd697f370af27a), [`d7f6a5c`](https://github.com/Effect-TS/effect/commit/d7f6a5c7d26c1963dcd864ca62360d20d08c7b49), [`9dd8979`](https://github.com/Effect-TS/effect/commit/9dd8979e940915b1cc1b1f264f3d019c77a65a02), [`477b488`](https://github.com/Effect-TS/effect/commit/477b488284f47c5469d7fba3e4065fb7e3b6556e), [`10932cb`](https://github.com/Effect-TS/effect/commit/10932cbf58fc721ada631cebec42f773ce96d3cc), [`9f6c784`](https://github.com/Effect-TS/effect/commit/9f6c78468b3b5e9ebfc38ffdfb70702901ee977b), [`2c639ec`](https://github.com/Effect-TS/effect/commit/2c639ecee332de4266e36022c989c35ae4e02105), [`886aaa8`](https://github.com/Effect-TS/effect/commit/886aaa81e06dfd3cd9391e8ea987d8cd5ada1124)]:\n  - effect@3.13.3\n  - @effect/experimental@0.41.3\n  - @effect/platform@0.77.3\n\n## 0.10.2\n\n### Patch Changes\n\n- Updated dependencies [[`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f), [`3e7ce97`](https://github.com/Effect-TS/effect/commit/3e7ce97f8a41756a039cf635d0b3d9a75d781097), [`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f)]:\n  - effect@3.13.2\n  - @effect/platform@0.77.2\n  - @effect/experimental@0.41.2\n\n## 0.10.1\n\n### Patch Changes\n\n- [#4446](https://github.com/Effect-TS/effect/pull/4446) [`9375c28`](https://github.com/Effect-TS/effect/commit/9375c28ca808325577da6c67cc92af25931027c8) Thanks @IMax153! - Add Anthropic AI provider integration\n\n- Updated dependencies [[`b56a211`](https://github.com/Effect-TS/effect/commit/b56a2110569fd0ec0b57ac137743e926d49f51cc)]:\n  - effect@3.13.1\n  - @effect/experimental@0.41.1\n  - @effect/platform@0.77.1\n\n## 0.10.0\n\n### Patch Changes\n\n- Updated dependencies [[`8baef83`](https://github.com/Effect-TS/effect/commit/8baef83e7ff0b7bc0738b680e1ef013065386cff), [`655bfe2`](https://github.com/Effect-TS/effect/commit/655bfe29e44cc3f0fb9b4e53038f50b891c188df), [`d90cbc2`](https://github.com/Effect-TS/effect/commit/d90cbc274e2742d18671fe65aa4764c057eb6cba), [`75632bd`](https://github.com/Effect-TS/effect/commit/75632bd44b8025101d652ccbaeef898c7086c91c), [`c874a2e`](https://github.com/Effect-TS/effect/commit/c874a2e4b17e9d71904ca8375bb77b020975cb1d), [`bf865e5`](https://github.com/Effect-TS/effect/commit/bf865e5833f77fd8f6c06944ca9d507b54488301), [`f98b2b7`](https://github.com/Effect-TS/effect/commit/f98b2b7592cf20f9d85313e7f1e964cb65878138), [`de8ce92`](https://github.com/Effect-TS/effect/commit/de8ce924923eaa4e1b761a97eb45ec967389f3d5), [`cf8b2dd`](https://github.com/Effect-TS/effect/commit/cf8b2dd112f8e092ed99d78fd728db0f91c29050), [`db426a5`](https://github.com/Effect-TS/effect/commit/db426a5fb41ab84d18e3c8753a7329b4de544245), [`6862444`](https://github.com/Effect-TS/effect/commit/6862444094906ad4f2cb077ff3b9cc0b73880c8c), [`5fc8a90`](https://github.com/Effect-TS/effect/commit/5fc8a90ba46a5fd9f3b643f0b5aeadc69d717339), [`546a492`](https://github.com/Effect-TS/effect/commit/546a492e60eb2b8b048a489a474b934ea0877005), [`65c4796`](https://github.com/Effect-TS/effect/commit/65c47966ce39055f02cf5c808daabb3ea6442b0b), [`9760fdc`](https://github.com/Effect-TS/effect/commit/9760fdc37bdaef9da8b150e46b86ddfbe2ad9221), [`5b471e7`](https://github.com/Effect-TS/effect/commit/5b471e7d4317e8ee5d72bbbd3e0c9775160949ab), [`4f810cc`](https://github.com/Effect-TS/effect/commit/4f810cc2770e9f1f266851d2cb6257112c12af49)]:\n  - effect@3.13.0\n  - @effect/experimental@0.41.0\n  - @effect/platform@0.77.0\n\n## 0.9.1\n\n### Patch Changes\n\n- Updated dependencies [[`4018eae`](https://github.com/Effect-TS/effect/commit/4018eaed2733241676ddb8c52416f463a8c32e35), [`543d36d`](https://github.com/Effect-TS/effect/commit/543d36d1a11452560b01ab966a82529ad5fee8c9), [`c407726`](https://github.com/Effect-TS/effect/commit/c407726f79df4a567a9631cddd8effaa16b3535d), [`f70a65a`](https://github.com/Effect-TS/effect/commit/f70a65ac80c6635d80b12beaf4d32a9cc59fa143), [`ba409f6`](https://github.com/Effect-TS/effect/commit/ba409f69c41aeaa29e475c0630735726eaf4dbac), [`3d2e356`](https://github.com/Effect-TS/effect/commit/3d2e3565e8a43d1bdb5daee8db3b90f56d71d859)]:\n  - effect@3.12.12\n  - @effect/platform@0.76.1\n  - @effect/experimental@0.40.1\n\n## 0.9.0\n\n### Patch Changes\n\n- Updated dependencies [[`b6a032f`](https://github.com/Effect-TS/effect/commit/b6a032f07bffa020a848c813881879395134fa20), [`42ddd5f`](https://github.com/Effect-TS/effect/commit/42ddd5f144ce9f9d94a036679ebbd626446d37f5), [`2fe447c`](https://github.com/Effect-TS/effect/commit/2fe447c6354d334f9c591b8a8481818f5f0e797e), [`2473ad5`](https://github.com/Effect-TS/effect/commit/2473ad5cf23582e3a41338091fa526ffe611288d)]:\n  - effect@3.12.11\n  - @effect/platform@0.76.0\n  - @effect/experimental@0.40.0\n\n## 0.8.4\n\n### Patch Changes\n\n- Updated dependencies [[`e30f132`](https://github.com/Effect-TS/effect/commit/e30f132c336c9d0760bad39f82a55c7ce5159eb7), [`33fa667`](https://github.com/Effect-TS/effect/commit/33fa667c2623be1026e1ccee91bd44f73b09020a), [`87f5f28`](https://github.com/Effect-TS/effect/commit/87f5f2842e4196cb88d13f10f443ff0567e82832), [`7d57ecd`](https://github.com/Effect-TS/effect/commit/7d57ecdaf5da2345ebbf9c22df50317578bde0f5), [`4dbd170`](https://github.com/Effect-TS/effect/commit/4dbd170538e8fb7a36aa7c469c6f93b6c7000091)]:\n  - effect@3.12.10\n  - @effect/platform@0.75.4\n  - @effect/experimental@0.39.4\n\n## 0.8.3\n\n### Patch Changes\n\n- Updated dependencies [[`1b4a4e9`](https://github.com/Effect-TS/effect/commit/1b4a4e904ef5227ec7d9114d4e417eca19eed940)]:\n  - effect@3.12.9\n  - @effect/experimental@0.39.3\n  - @effect/platform@0.75.3\n\n## 0.8.2\n\n### Patch Changes\n\n- [#4378](https://github.com/Effect-TS/effect/pull/4378) [`f5e3b1b`](https://github.com/Effect-TS/effect/commit/f5e3b1bcdf24b440251ce8425d750353cf022e96) Thanks @IMax153! - Support non-identified schemas in `AiChat.structured` and `Completions.structured`.\n\n  Instead of requiring a `Schema` with either an `identifier` or `_tag` property\n  for AI APIs that allow for returning structured outputs, you can now optionally\n  pass a `correlationId` to `AiChat.structured` and `Completions.structured` when\n  you want to either use a simple schema or inline the schema.\n\n  Example:\n\n  ```ts\n  import { Completions } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiCompletions } from \"@effect/ai-openai\"\n  import { NodeHttpClient } from \"@effect/platform-node\"\n  import { Config, Effect, Layer, Schema, String } from \"effect\"\n\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  const Gpt4oCompletions = OpenAiCompletions.layer({\n    model: \"gpt-4o\"\n  }).pipe(Layer.provide(OpenAi))\n\n  const program = Effect.gen(function* () {\n    const completions = yield* Completions.Completions\n\n    const CalendarEvent = Schema.Struct({\n      name: Schema.String,\n      date: Schema.DateFromString,\n      participants: Schema.Array(Schema.String)\n    })\n\n    yield* completions.structured({\n      correlationId: \"CalendarEvent\",\n      schema: CalendarEvent,\n      input: String.stripMargin(`\n        |Extract event information from the following prose:\n        |\n        |Alice and Bob are going to a science fair on Friday.\n      `)\n    })\n  })\n\n  program.pipe(Effect.provide(Gpt4oCompletions), Effect.runPromise)\n  ```\n\n- [#4388](https://github.com/Effect-TS/effect/pull/4388) [`fcf3b7c`](https://github.com/Effect-TS/effect/commit/fcf3b7cc07a28635a5b53243b01cdeb6592dab3c) Thanks @IMax153! - Rename correlationId to toolCallId\n\n- [#4389](https://github.com/Effect-TS/effect/pull/4389) [`f089470`](https://github.com/Effect-TS/effect/commit/f0894708e9d591b70eccf3a50ae91ac6e0f6d6e3) Thanks @IMax153! - Add support for [GenAI telemetry annotations](https://opentelemetry.io/docs/specs/semconv/attributes-registry/gen-ai/).\n\n- [#4368](https://github.com/Effect-TS/effect/pull/4368) [`a0c85e6`](https://github.com/Effect-TS/effect/commit/a0c85e6601fd3e10d08085969f7453b7b517347b) Thanks @IMax153! - Support creation of embeddings from the AI integration packages.\n\n  For example, the following program will create an OpenAI `Embeddings` service\n  that will aggregate all embedding requests received within a `500` millisecond\n  window into a single batch.\n\n  ```ts\n  import { Embeddings } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiEmbeddings } from \"@effect/ai-openai\"\n  import { NodeHttpClient } from \"@effect/platform-node\"\n  import { Config, Effect, Layer } from \"effect\"\n\n  // Create the OpenAI client\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  // Create an embeddings service for the `text-embedding-3-large` model\n  const TextEmbeddingsLarge = OpenAiEmbeddings.layerDataLoader({\n    model: \"text-embedding-3-large\",\n    window: \"500 millis\",\n    maxBatchSize: 2048\n  }).pipe(Layer.provide(OpenAi))\n\n  // Use the generic `Embeddings` service interface in your program\n  const program = Effect.gen(function* () {\n    const embeddings = yield* Embeddings.Embeddings\n    const result = yield* embeddings.embed(\"The input to embed\")\n  })\n\n  // Provide the specific implementation to use\n  program.pipe(Effect.provide(TextEmbeddingsLarge), Effect.runPromise)\n  ```\n\n- Updated dependencies [[`59b3cfb`](https://github.com/Effect-TS/effect/commit/59b3cfbbd5713dd9475998e95fad5534c0b21466), [`766113c`](https://github.com/Effect-TS/effect/commit/766113c0ea3512cdb887650ead8ba314236e22ee), [`bb05fb8`](https://github.com/Effect-TS/effect/commit/bb05fb83457355b1ca567228a9e041edfb6fd85d), [`712277f`](https://github.com/Effect-TS/effect/commit/712277f949052a24b46e4aa234063a6abf395c90), [`f269122`](https://github.com/Effect-TS/effect/commit/f269122508693b111142994dd48698ddc75f3d69), [`8f6006a`](https://github.com/Effect-TS/effect/commit/8f6006a610fb6d6c7b8d14209a7323338a8964ff), [`c45b559`](https://github.com/Effect-TS/effect/commit/c45b5592b5fd1189a5c932cfe05bd7d5f6d68508), [`430c846`](https://github.com/Effect-TS/effect/commit/430c846cbac05b187e3d24ac8dfee0cf22506f7c), [`7b03057`](https://github.com/Effect-TS/effect/commit/7b03057507d2dab5e6793beb9c578dedaaeb15fe), [`a9c94c8`](https://github.com/Effect-TS/effect/commit/a9c94c807755610831211a686d2fad849ab38eb4), [`107e6f0`](https://github.com/Effect-TS/effect/commit/107e6f0557a1e2d3b0dce25d62fa1e2601521752), [`c9175ae`](https://github.com/Effect-TS/effect/commit/c9175aef41cb1e3b689d0ac0a4f53d8107376b58), [`65c11b9`](https://github.com/Effect-TS/effect/commit/65c11b9266ec9447c31c26fe3ed35c73bd3b81fd), [`e386d2f`](https://github.com/Effect-TS/effect/commit/e386d2f1b3ab3ac2c14ee76de11f5963d32a3df4), [`9172efb`](https://github.com/Effect-TS/effect/commit/9172efba98bc6a82353e6ec2af61ac08f038ba64)]:\n  - @effect/platform@0.75.2\n  - effect@3.12.8\n  - @effect/experimental@0.39.2\n\n## 0.8.1\n\n### Patch Changes\n\n- Updated dependencies [[`8dff1d1`](https://github.com/Effect-TS/effect/commit/8dff1d1bff76cdba643cad7f0bf864300f08bc61)]:\n  - effect@3.12.7\n  - @effect/platform@0.75.1\n\n## 0.8.0\n\n### Minor Changes\n\n- [#4306](https://github.com/Effect-TS/effect/pull/4306) [`5e43ce5`](https://github.com/Effect-TS/effect/commit/5e43ce50bae116865906112e7f88d390739d778b) Thanks @tim-smart! - eliminate Scope by default in some layer apis\n\n### Patch Changes\n\n- Updated dependencies [[`5e43ce5`](https://github.com/Effect-TS/effect/commit/5e43ce50bae116865906112e7f88d390739d778b), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`76eb7d0`](https://github.com/Effect-TS/effect/commit/76eb7d0fbce3c009c8f77e84c178cb15bbed9709), [`8b4e75d`](https://github.com/Effect-TS/effect/commit/8b4e75d35daea807c447ca760948a717aa66bb52), [`fc5e0f0`](https://github.com/Effect-TS/effect/commit/fc5e0f0d357a0051cfa01c1ede83ffdd3cb41ab1), [`004fd2b`](https://github.com/Effect-TS/effect/commit/004fd2bbd1459e64fb1b57f02eeb791ca5ea1ea5), [`b2a31be`](https://github.com/Effect-TS/effect/commit/b2a31be85c35d891351ce4f9a2cc93ece0c257f6), [`5514d05`](https://github.com/Effect-TS/effect/commit/5514d05b5cd586ff5868b8bd41c959e95e6c33cd), [`bf5f0ae`](https://github.com/Effect-TS/effect/commit/bf5f0ae9daa0170471678e22585e8ec14ce667bb), [`3b19bcf`](https://github.com/Effect-TS/effect/commit/3b19bcfd3aaadb6c9253428622df524537c8e626), [`b064b3b`](https://github.com/Effect-TS/effect/commit/b064b3b293615fd268cc5a5647d0981eb67750b8), [`eb264ed`](https://github.com/Effect-TS/effect/commit/eb264ed8a6e8c92a9dc7006f766c6ca2e5d29e03), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`f474678`](https://github.com/Effect-TS/effect/commit/f474678bf10b8f1c80e3dc096ddc7ecf20b2b23e), [`ee187d0`](https://github.com/Effect-TS/effect/commit/ee187d098007a402844c94d04f0cd8f07695377a)]:\n  - @effect/platform@0.75.0\n  - effect@3.12.6\n\n## 0.7.0\n\n### Patch Changes\n\n- Updated dependencies [[`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8653072`](https://github.com/Effect-TS/effect/commit/86530720d7a03e118d2c5a8bf5a997cee7e7f3d6), [`507d546`](https://github.com/Effect-TS/effect/commit/507d546bd49db31000425fb5da88c434e4291bea), [`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8db239b`](https://github.com/Effect-TS/effect/commit/8db239b9c869a3707f6566b9d9dbdf53c4df03fc), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`3179a9f`](https://github.com/Effect-TS/effect/commit/3179a9f65d23369a6a9a1f80f7750566dd28df22), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e), [`1fcbe55`](https://github.com/Effect-TS/effect/commit/1fcbe55345042d8468f6a98c84081bd00b6bcf5a), [`d9a63d9`](https://github.com/Effect-TS/effect/commit/d9a63d9d385653865954cac895065360d54cc56b), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e)]:\n  - effect@3.12.5\n  - @effect/platform@0.74.0\n\n## 0.6.1\n\n### Patch Changes\n\n- Updated dependencies [[`5b50ea4`](https://github.com/Effect-TS/effect/commit/5b50ea4a10cf9acd51f9624b2474d9d5ded74019), [`c170a68`](https://github.com/Effect-TS/effect/commit/c170a68b6266100774461fcd6c0e0fabb60112f2), [`a66c2eb`](https://github.com/Effect-TS/effect/commit/a66c2eb473245092cd41f04c2eb2b7b02cf53718), [`c9e5e1b`](https://github.com/Effect-TS/effect/commit/c9e5e1be17c0c84d3d4e2abc3c60215cdb56bbbe), [`7b3d58d`](https://github.com/Effect-TS/effect/commit/7b3d58d7aec2152ec282460871d3e9de45ed254d)]:\n  - effect@3.12.4\n  - @effect/platform@0.73.1\n\n## 0.6.0\n\n### Patch Changes\n\n- Updated dependencies [[`d7dac48`](https://github.com/Effect-TS/effect/commit/d7dac48a477cdfeec509dbe9f33fce6a1b02b63d), [`c110032`](https://github.com/Effect-TS/effect/commit/c110032322450a8824ba38ae24335a538cd2ce9a), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`23ac740`](https://github.com/Effect-TS/effect/commit/23ac740c7dd4610b7d265c2071b88b0968419e9a), [`8cd7319`](https://github.com/Effect-TS/effect/commit/8cd7319b6568bfc7a30ca16c104d189e37eac3a0)]:\n  - effect@3.12.3\n  - @effect/platform@0.73.0\n\n## 0.5.2\n\n### Patch Changes\n\n- Updated dependencies [[`734af82`](https://github.com/Effect-TS/effect/commit/734af82138e78b9c57a8355b1c6b80e80d38b222), [`b63c780`](https://github.com/Effect-TS/effect/commit/b63c78010893101520448ddda7019c487cf7eedd), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`f852cb0`](https://github.com/Effect-TS/effect/commit/f852cb02040ea2f165e9b449615b8b1366add5d5), [`7276ae2`](https://github.com/Effect-TS/effect/commit/7276ae21062896adbb7508ac5b2dece95316322f), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`c640d77`](https://github.com/Effect-TS/effect/commit/c640d77b33ad417876f4e8ffe8574ee6cbe5607f), [`0def088`](https://github.com/Effect-TS/effect/commit/0def0887cfdb6755729a64dfd52b3b9f46b0576c)]:\n  - effect@3.12.2\n  - @effect/platform@0.72.2\n\n## 0.5.1\n\n### Patch Changes\n\n- Updated dependencies [[`302b57d`](https://github.com/Effect-TS/effect/commit/302b57d2cbf9b9ccc17450945aeebfb33cfe8d43), [`0988083`](https://github.com/Effect-TS/effect/commit/0988083d4594938590df5a287e5b27d38526dd07), [`8b46be6`](https://github.com/Effect-TS/effect/commit/8b46be6a3b8160362ab5ea9171c5e6932505125c), [`bfe8027`](https://github.com/Effect-TS/effect/commit/bfe802734b450a4b4ee069d1125dd37995db2bff), [`16dd657`](https://github.com/Effect-TS/effect/commit/16dd657033d8afac2ffea567b3c8bb27c9b249b6), [`39db211`](https://github.com/Effect-TS/effect/commit/39db211414e90c8db8fdad7dc8ce5b4661bcfaef)]:\n  - effect@3.12.1\n  - @effect/platform@0.72.1\n\n## 0.5.0\n\n### Patch Changes\n\n- Updated dependencies [[`abb22a4`](https://github.com/Effect-TS/effect/commit/abb22a429b9c52c31e84856294f175d2064a9b4d), [`f369a89`](https://github.com/Effect-TS/effect/commit/f369a89e98bc682969803b9304adaf4557bb36c2), [`642376c`](https://github.com/Effect-TS/effect/commit/642376c63fd7d78754db991631a4d50a5dc79aa3), [`3d2b7a7`](https://github.com/Effect-TS/effect/commit/3d2b7a7e942a7157afae5b1cdbc6f3fef116428e), [`ef64c6f`](https://github.com/Effect-TS/effect/commit/ef64c6fec0d47da573c04230dde9ea729366d871), [`73f9c6f`](https://github.com/Effect-TS/effect/commit/73f9c6f2ff091512cf904cc54ab59965b86e87c8), [`17cb451`](https://github.com/Effect-TS/effect/commit/17cb4514590e8a86263f7aed009f24da8a237342), [`d801820`](https://github.com/Effect-TS/effect/commit/d80182060c2ee945d7e0e4728812abf9465a0d6a), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1), [`c11f3a6`](https://github.com/Effect-TS/effect/commit/c11f3a60a05c3b5fc8e7ce90136728154dc505b0), [`618f7e0`](https://github.com/Effect-TS/effect/commit/618f7e092a1011e5090dca1e69b5e9285689654b), [`c0ba834`](https://github.com/Effect-TS/effect/commit/c0ba834d1995cf5a8b250e4780fd43f3e3881151), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1)]:\n  - effect@3.12.0\n  - @effect/platform@0.72.0\n\n## 0.4.8\n\n### Patch Changes\n\n- Updated dependencies [[`39457d4`](https://github.com/Effect-TS/effect/commit/39457d4897d9bc7df8af5c05d352866bbeae82eb), [`a475cc2`](https://github.com/Effect-TS/effect/commit/a475cc25fd7c9f26b27a8e98f8fbe43cc9e6ee3e), [`199214e`](https://github.com/Effect-TS/effect/commit/199214e21c616d8a0ccd7ed5f92e944e6c580193), [`b3c160d`](https://github.com/Effect-TS/effect/commit/b3c160d7a1fdfc2d3fb2440530f1ab80efc65133)]:\n  - effect@3.11.10\n  - @effect/platform@0.71.7\n\n## 0.4.7\n\n### Patch Changes\n\n- Updated dependencies [[`1c08a0b`](https://github.com/Effect-TS/effect/commit/1c08a0b8505badcffb4d9cade5a746ea90c9557e), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd)]:\n  - effect@3.11.9\n  - @effect/platform@0.71.6\n\n## 0.4.6\n\n### Patch Changes\n\n- Updated dependencies [[`05d71f8`](https://github.com/Effect-TS/effect/commit/05d71f85622305705d8316817694a09762e60865), [`e66b920`](https://github.com/Effect-TS/effect/commit/e66b9205f25ab425d30640886eb3fb2c4715bc26)]:\n  - @effect/platform@0.71.5\n\n## 0.4.5\n\n### Patch Changes\n\n- Updated dependencies [[`909181a`](https://github.com/Effect-TS/effect/commit/909181a9ce9052a80432ccf52187e0723004bf7f), [`909181a`](https://github.com/Effect-TS/effect/commit/909181a9ce9052a80432ccf52187e0723004bf7f), [`1a6b52d`](https://github.com/Effect-TS/effect/commit/1a6b52dcf020d36e38a7bc90b648152cf5a8ccba)]:\n  - @effect/platform@0.71.4\n  - effect@3.11.8\n\n## 0.4.4\n\n### Patch Changes\n\n- Updated dependencies [[`6984508`](https://github.com/Effect-TS/effect/commit/6984508c87f1bd91213b44c19b25ab5e2dcc1ce0), [`883639c`](https://github.com/Effect-TS/effect/commit/883639cc8ce47757f1cd39439391a8028c0812fe)]:\n  - @effect/platform@0.71.3\n\n## 0.4.3\n\n### Patch Changes\n\n- [#4139](https://github.com/Effect-TS/effect/pull/4139) [`1237ae8`](https://github.com/Effect-TS/effect/commit/1237ae847f6f0ff57eb7dcb4723ae6f5073fb925) Thanks @tim-smart! - fix json schema output for Ai completions\n\n## 0.4.2\n\n### Patch Changes\n\n- Updated dependencies [[`2408616`](https://github.com/Effect-TS/effect/commit/24086163b60b09cc6d0885bd565ef080dcbe866b), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`8d978c5`](https://github.com/Effect-TS/effect/commit/8d978c53f6fcc98d9d645ecba3e4b55d4297dd36), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e)]:\n  - effect@3.11.7\n  - @effect/platform@0.71.2\n\n## 0.4.1\n\n### Patch Changes\n\n- Updated dependencies [[`1d3df5b`](https://github.com/Effect-TS/effect/commit/1d3df5bc4324e88a392c348db35fd9d029c7b25e)]:\n  - @effect/platform@0.71.1\n\n## 0.4.0\n\n### Patch Changes\n\n- Updated dependencies [[`662d1ce`](https://github.com/Effect-TS/effect/commit/662d1ce6fb7da384a95888d5b2bb5605bdf3208d), [`c99a0f3`](https://github.com/Effect-TS/effect/commit/c99a0f376d049d3793ed33e146d9873b8a5e5b78), [`11fc401`](https://github.com/Effect-TS/effect/commit/11fc401f436f99bf4be95f56d50b0e4bdfe5edea), [`c99a0f3`](https://github.com/Effect-TS/effect/commit/c99a0f376d049d3793ed33e146d9873b8a5e5b78), [`31c62d8`](https://github.com/Effect-TS/effect/commit/31c62d83cbdcf9850a8b5331faa239601c60f78a)]:\n  - effect@3.11.6\n  - @effect/platform@0.71.0\n\n## 0.3.7\n\n### Patch Changes\n\n- Updated dependencies [[`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`22905cf`](https://github.com/Effect-TS/effect/commit/22905cf5addfb1ff3d2a6135c52036be958ae911), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`1e59e4f`](https://github.com/Effect-TS/effect/commit/1e59e4fd778da18296812a2a32f36ca8ae50f60d), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`8d914e5`](https://github.com/Effect-TS/effect/commit/8d914e504e7a22d0ea628e8af265ee450ff9530f), [`03bb00f`](https://github.com/Effect-TS/effect/commit/03bb00faa74f9e168a54a8cc0828a664fbb1ab05), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`14e1149`](https://github.com/Effect-TS/effect/commit/14e1149f1af5a022f06eb8c2e4ba9fec17fe7426), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8)]:\n  - effect@3.11.5\n  - @effect/platform@0.70.7\n\n## 0.3.6\n\n### Patch Changes\n\n- Updated dependencies [[`9a5b8e3`](https://github.com/Effect-TS/effect/commit/9a5b8e36d184bd4967a88752cb6e755e1be263af)]:\n  - @effect/platform@0.70.6\n\n## 0.3.5\n\n### Patch Changes\n\n- Updated dependencies [[`415f4c9`](https://github.com/Effect-TS/effect/commit/415f4c98321868531727a83cbaad70164f5e4c40), [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f), [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f)]:\n  - @effect/platform@0.70.5\n  - effect@3.11.4\n\n## 0.3.4\n\n### Patch Changes\n\n- Updated dependencies [[`90906f7`](https://github.com/Effect-TS/effect/commit/90906f7f154b12c7182e8f39e3c55ef3937db857), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`343b6aa`](https://github.com/Effect-TS/effect/commit/343b6aa6ac4a74276bfc7c63ccbf4a1d72bc1bed), [`afba339`](https://github.com/Effect-TS/effect/commit/afba339adc11dad56b5a3b7ca94487e58f34d613)]:\n  - effect@3.11.3\n  - @effect/platform@0.70.4\n\n## 0.3.3\n\n### Patch Changes\n\n- [#4071](https://github.com/Effect-TS/effect/pull/4071) [`da3a607`](https://github.com/Effect-TS/effect/commit/da3a607bea16d4f08c5937cadfde0447c4123f40) Thanks @tim-smart! - use openai response_format for structured completions\n\n- Updated dependencies [[`7044730`](https://github.com/Effect-TS/effect/commit/70447306be1aeeb7d87c230b2a96ec87b993ede9)]:\n  - @effect/platform@0.70.3\n\n## 0.3.2\n\n### Patch Changes\n\n- Updated dependencies [[`01cee56`](https://github.com/Effect-TS/effect/commit/01cee560b58d94b24cc20e98083251b73e658b41), [`c2249ea`](https://github.com/Effect-TS/effect/commit/c2249ea13fd98ab7d9aa628787931356d8ec2860), [`1358aa5`](https://github.com/Effect-TS/effect/commit/1358aa5326eaa85ef13ee8d1fed0b4a4288ed3eb), [`1de3fe7`](https://github.com/Effect-TS/effect/commit/1de3fe7d1cbafd6391eaa38c2300b99e332cc2aa)]:\n  - effect@3.11.2\n  - @effect/platform@0.70.2\n\n## 0.3.1\n\n### Patch Changes\n\n- Updated dependencies [[`dd8a2d8`](https://github.com/Effect-TS/effect/commit/dd8a2d8e80d33b16719fc69361eaedf0b59d4620), [`a71bfef`](https://github.com/Effect-TS/effect/commit/a71bfef46f5061bb2502a61a333638a987b62273)]:\n  - effect@3.11.1\n  - @effect/platform@0.70.1\n\n## 0.3.0\n\n### Patch Changes\n\n- Updated dependencies [[`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`6e69493`](https://github.com/Effect-TS/effect/commit/6e694930048bbaf98110f35f41566aeb9752d471), [`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`5eff3f6`](https://github.com/Effect-TS/effect/commit/5eff3f6fa3aae7e86948a62cbfd63b8d6c3bdf92), [`d9fe79b`](https://github.com/Effect-TS/effect/commit/d9fe79bb5a3fe105d8e7a3bc2922a8ad936a5d10), [`251d189`](https://github.com/Effect-TS/effect/commit/251d189420bbba71990574e91098c499065f9a9b), [`5a259f3`](https://github.com/Effect-TS/effect/commit/5a259f3711b4369f55d885b568bdb21136155261), [`b4ce4ea`](https://github.com/Effect-TS/effect/commit/b4ce4ea7fd514a7e572f2dcd879c98f334981b0e), [`15fcc5a`](https://github.com/Effect-TS/effect/commit/15fcc5a0ea4bbf40ab48fa6a04fdda74f76f4c07), [`9bc9a47`](https://github.com/Effect-TS/effect/commit/9bc9a476800dc645903c888a68bb1d3baa3383c6), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb), [`1e2747c`](https://github.com/Effect-TS/effect/commit/1e2747c63a4820d1459cbbc88c71212983bd68bd), [`9264162`](https://github.com/Effect-TS/effect/commit/9264162a82783a651776fb7b87604564a63e7070), [`e0b9b09`](https://github.com/Effect-TS/effect/commit/e0b9b09e70c386b2da17d1f0a15b0511861c89e8), [`c36f3b9`](https://github.com/Effect-TS/effect/commit/c36f3b95df5ce9d71b66f22f26ce12eda8d3e848), [`672bde5`](https://github.com/Effect-TS/effect/commit/672bde5bec51c7d6f9862828e6a654cb2cb6f93d), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb)]:\n  - effect@3.11.0\n  - @effect/platform@0.70.0\n\n## 0.2.32\n\n### Patch Changes\n\n- Updated dependencies [[`3069614`](https://github.com/Effect-TS/effect/commit/30696149271129fc618f6f2ccd1d8f2f6c0f9cd7), [`09a5e52`](https://github.com/Effect-TS/effect/commit/09a5e522fd9b221f05d85b1d1c8a740d4973c302)]:\n  - effect@3.10.20\n  - @effect/platform@0.69.32\n\n## 0.2.31\n\n### Patch Changes\n\n- Updated dependencies [[`e6d4a37`](https://github.com/Effect-TS/effect/commit/e6d4a37c1d7e657b5ea44063a1cf586808228fe5)]:\n  - @effect/platform@0.69.31\n\n## 0.2.30\n\n### Patch Changes\n\n- Updated dependencies [[`270f199`](https://github.com/Effect-TS/effect/commit/270f199b31810fd643e4c22818698adcbdb5d396)]:\n  - @effect/platform@0.69.30\n\n## 0.2.29\n\n### Patch Changes\n\n- Updated dependencies [[`24cc35e`](https://github.com/Effect-TS/effect/commit/24cc35e26d6ed4a076470bc687ffd99cc50991b3)]:\n  - @effect/platform@0.69.29\n\n## 0.2.28\n\n### Patch Changes\n\n- Updated dependencies [[`edd72be`](https://github.com/Effect-TS/effect/commit/edd72be57b904d60c9cbffc2537901821a9da537), [`a3e2771`](https://github.com/Effect-TS/effect/commit/a3e277170a1f7cf61fd629acb60304c7e81d9498), [`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1), [`54addee`](https://github.com/Effect-TS/effect/commit/54addee438a644bf010646c52042c7b89c5fc0a7), [`a9e00e4`](https://github.com/Effect-TS/effect/commit/a9e00e43f0b5dd22c1f9d5b78be6383daea09c20)]:\n  - @effect/platform@0.69.28\n  - effect@3.10.19\n\n## 0.2.27\n\n### Patch Changes\n\n- Updated dependencies [[`af409cf`](https://github.com/Effect-TS/effect/commit/af409cf1d2ff973be11cc079ea373eaeedca25de), [`beaccae`](https://github.com/Effect-TS/effect/commit/beaccae2d15931e9fe475fb50a0b3638243fe3f7)]:\n  - effect@3.10.18\n  - @effect/platform@0.69.27\n\n## 0.2.26\n\n### Patch Changes\n\n- Updated dependencies [[`c963886`](https://github.com/Effect-TS/effect/commit/c963886d5817986fcbd6bfa4ddf50aca8b6c8184), [`42c4ce6`](https://github.com/Effect-TS/effect/commit/42c4ce6f8d8c7d847e97757650a8ad9419a829d7)]:\n  - @effect/platform@0.69.26\n  - effect@3.10.17\n\n## 0.2.25\n\n### Patch Changes\n\n- Updated dependencies [[`320557a`](https://github.com/Effect-TS/effect/commit/320557ab18d13c5e22fc7dc0d2a157eae461012f), [`4dca30c`](https://github.com/Effect-TS/effect/commit/4dca30cfcdafe4542e236489f71d6f171a5b4e38), [`1d99867`](https://github.com/Effect-TS/effect/commit/1d998671be3cd11043f232822e91dd8c98fccfa9), [`6dae414`](https://github.com/Effect-TS/effect/commit/6dae4147991a97ec14a99289bd25fadae7541e8d), [`6b0d737`](https://github.com/Effect-TS/effect/commit/6b0d737078bf63b97891e6bc47affc04b28f9cf7), [`d8356aa`](https://github.com/Effect-TS/effect/commit/d8356aad428a0c2290db52380220f81d9ec94232), [`7b93dd6`](https://github.com/Effect-TS/effect/commit/7b93dd622e2ab79c7072d79d0d9611e446202201)]:\n  - @effect/platform@0.69.25\n  - effect@3.10.16\n\n## 0.2.24\n\n### Patch Changes\n\n- Updated dependencies [[`3cc6514`](https://github.com/Effect-TS/effect/commit/3cc6514d2dd64e010cb760cc29bfce98c349bb10)]:\n  - @effect/platform@0.69.24\n\n## 0.2.23\n\n### Patch Changes\n\n- Updated dependencies [[`3aff4d3`](https://github.com/Effect-TS/effect/commit/3aff4d38837c213bb2987973dc4b98febb9f92d2)]:\n  - @effect/platform@0.69.23\n\n## 0.2.22\n\n### Patch Changes\n\n- Updated dependencies [[`8398b32`](https://github.com/Effect-TS/effect/commit/8398b3208242a88239d4449910b7baf923cfe3b6), [`72e55b7`](https://github.com/Effect-TS/effect/commit/72e55b7c610784fcebdbadc592c876e23e76a986)]:\n  - effect@3.10.15\n  - @effect/platform@0.69.22\n\n## 0.2.21\n\n### Patch Changes\n\n- Updated dependencies [[`f983946`](https://github.com/Effect-TS/effect/commit/f9839467b4cad6e788297764ef9f9f0b9fd203f9), [`2d8a750`](https://github.com/Effect-TS/effect/commit/2d8a75081eb83a0a81f817fdf6f428369c5064ab)]:\n  - effect@3.10.14\n  - @effect/platform@0.69.21\n\n## 0.2.20\n\n### Patch Changes\n\n- [#3916](https://github.com/Effect-TS/effect/pull/3916) [`72b0272`](https://github.com/Effect-TS/effect/commit/72b02726d62000756577464273c0dd0876cbe0b5) Thanks @tim-smart! - use effect/JSONSchema for effect/ai & allow http client transforms\n\n- Updated dependencies [[`995bbdf`](https://github.com/Effect-TS/effect/commit/995bbdffea2e332f203cd5b474cd6a1c77dfa6ae)]:\n  - effect@3.10.13\n  - @effect/platform@0.69.20\n\n## 0.2.19\n\n### Patch Changes\n\n- Updated dependencies [[`eb8c52d`](https://github.com/Effect-TS/effect/commit/eb8c52d8b4c5e067ebf0a81eb742f5822e6439b5)]:\n  - @effect/platform@0.69.19\n\n## 0.2.18\n\n### Patch Changes\n\n- Updated dependencies [[`a0584ec`](https://github.com/Effect-TS/effect/commit/a0584ece92ed784bfb139e9c5a699f02d1e71c2d), [`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6), [`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6)]:\n  - @effect/platform@0.69.18\n  - effect@3.10.12\n\n## 0.2.17\n\n### Patch Changes\n\n- Updated dependencies [[`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a), [`8240b1c`](https://github.com/Effect-TS/effect/commit/8240b1c10d45312fc863cb679b1a1e8441af0c1a), [`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a)]:\n  - effect@3.10.11\n  - @effect/platform@0.69.17\n\n## 0.2.16\n\n### Patch Changes\n\n- Updated dependencies [[`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`b631f40`](https://github.com/Effect-TS/effect/commit/b631f40abbe649b2a089764585b5c39f6a695ac6), [`7d89650`](https://github.com/Effect-TS/effect/commit/7d8965036cd2ea435c8441ffec3345488baebf85)]:\n  - effect@3.10.10\n  - @effect/platform@0.69.16\n\n## 0.2.15\n\n### Patch Changes\n\n- Updated dependencies [[`8a30e1d`](https://github.com/Effect-TS/effect/commit/8a30e1dfa3a7103bf5414fc6a7fca3088d8c8c00)]:\n  - @effect/platform@0.69.15\n\n## 0.2.14\n\n### Patch Changes\n\n- Updated dependencies [[`a123e80`](https://github.com/Effect-TS/effect/commit/a123e80f111a625428a5b5622b7f55ee1073566b), [`bd5fcd3`](https://github.com/Effect-TS/effect/commit/bd5fcd3e6b603b1e505af90d6a00627c8eca6d41), [`0289d3b`](https://github.com/Effect-TS/effect/commit/0289d3b6391031d00329365bab9791b355031fe3), [`7386b71`](https://github.com/Effect-TS/effect/commit/7386b710e5be570e17f468928a6ed19d549a3e12), [`07c493a`](https://github.com/Effect-TS/effect/commit/07c493a598e096c7810cd06def8cfa43493c46b1), [`257ab1b`](https://github.com/Effect-TS/effect/commit/257ab1b539fa6e930b7ae2583a188376372200d7), [`4211a23`](https://github.com/Effect-TS/effect/commit/4211a2355bb3af3f0e756e2aae9d293379f25662)]:\n  - effect@3.10.9\n  - @effect/platform@0.69.14\n\n## 0.2.13\n\n### Patch Changes\n\n- Updated dependencies [[`68b5c9e`](https://github.com/Effect-TS/effect/commit/68b5c9e44f34192cef26e1cadda5e661a027df41), [`9c9928d`](https://github.com/Effect-TS/effect/commit/9c9928dfeacd9ac33dc37eb0ca3d7d8c39175ada), [`6306e66`](https://github.com/Effect-TS/effect/commit/6306e6656092b350d4ede5746da6f245ec9f7e07), [`361c7f3`](https://github.com/Effect-TS/effect/commit/361c7f39a2c10ede9324847c3d3ba192a6f9b20a)]:\n  - effect@3.10.8\n  - @effect/platform@0.69.13\n\n## 0.2.12\n\n### Patch Changes\n\n- Updated dependencies [[`33f5b9f`](https://github.com/Effect-TS/effect/commit/33f5b9ffaebea4f1bd0e391b44c41fb6230e743a), [`50f0281`](https://github.com/Effect-TS/effect/commit/50f0281b0d2116726b8927a6217622d5f394f3e4)]:\n  - effect@3.10.7\n  - @effect/platform@0.69.12\n\n## 0.2.11\n\n### Patch Changes\n\n- Updated dependencies [[`ce1c21f`](https://github.com/Effect-TS/effect/commit/ce1c21ffc11902ac9ab453a51904207859d38552), [`81ddd45`](https://github.com/Effect-TS/effect/commit/81ddd45fc074b98206fafab416d9a5a28b31e07a)]:\n  - effect@3.10.6\n  - @effect/platform@0.69.11\n\n## 0.2.10\n\n### Patch Changes\n\n- Updated dependencies [[`3a6d757`](https://github.com/Effect-TS/effect/commit/3a6d757badeebe00d8ef4d67530d073c8264dcfa), [`59d813a`](https://github.com/Effect-TS/effect/commit/59d813aa4973d1115cfc70cc3667508335f49693)]:\n  - effect@3.10.5\n  - @effect/platform@0.69.10\n\n## 0.2.9\n\n### Patch Changes\n\n- Updated dependencies [[`2367708`](https://github.com/Effect-TS/effect/commit/2367708be449f9526a2047e321302d7bfb16f18e)]:\n  - @effect/platform@0.69.9\n  - effect@3.10.4\n\n## 0.2.8\n\n### Patch Changes\n\n- Updated dependencies [[`522f7c5`](https://github.com/Effect-TS/effect/commit/522f7c518a5acfb55ef96d6796869f002cc3eaf8)]:\n  - @effect/platform@0.69.8\n\n## 0.2.7\n\n### Patch Changes\n\n- Updated dependencies [[`690d6c5`](https://github.com/Effect-TS/effect/commit/690d6c54d2145adb0af545c447db7d4755bf3c6b), [`b9423d8`](https://github.com/Effect-TS/effect/commit/b9423d8bf8181a2389fdbce1e3c14ac6fe8d54f5), [`279fe3a`](https://github.com/Effect-TS/effect/commit/279fe3a7168fe84e520c2cc88ba189a15f03a2bc)]:\n  - @effect/platform@0.69.7\n  - effect@3.10.3\n\n## 0.2.6\n\n### Patch Changes\n\n- Updated dependencies [[`714e119`](https://github.com/Effect-TS/effect/commit/714e11945e45e5a2554ee058e6c43f82a8e309cf), [`c1afd55`](https://github.com/Effect-TS/effect/commit/c1afd55c54e61f9c432823d21b3d016f79160a37), [`42cd72a`](https://github.com/Effect-TS/effect/commit/42cd72a44ca9593e4d81fbb50e8111625fd0fb81)]:\n  - effect@3.10.2\n  - @effect/platform@0.69.6\n\n## 0.2.5\n\n### Patch Changes\n\n- Updated dependencies [[`9604d6b`](https://github.com/Effect-TS/effect/commit/9604d6b616435103dafea8b53637a9d1450b4750)]:\n  - effect@3.10.1\n  - @effect/platform@0.69.5\n\n## 0.2.4\n\n### Patch Changes\n\n- Updated dependencies [[`c86b1d7`](https://github.com/Effect-TS/effect/commit/c86b1d7cd47b66df190ef9775a475467c1abdbd6)]:\n  - @effect/platform@0.69.4\n\n## 0.2.3\n\n### Patch Changes\n\n- Updated dependencies [[`d5fba63`](https://github.com/Effect-TS/effect/commit/d5fba6391e1005e374aa0238f13edfbd65848313), [`1eb2c30`](https://github.com/Effect-TS/effect/commit/1eb2c30ba064398db5790e376dedcfad55b7b005), [`02d413e`](https://github.com/Effect-TS/effect/commit/02d413e7b6bc1c64885969c37cc3e4e690c94d7d)]:\n  - @effect/platform@0.69.3\n\n## 0.2.2\n\n### Patch Changes\n\n- Updated dependencies [[`e7afc47`](https://github.com/Effect-TS/effect/commit/e7afc47ce83e381c3f4aed2b2974e3b3d86a2340)]:\n  - @effect/platform@0.69.2\n\n## 0.2.1\n\n### Patch Changes\n\n- Updated dependencies [[`7564f56`](https://github.com/Effect-TS/effect/commit/7564f56bb2844cf39d2b0d2d9e93cf9b2205e9a8), [`7564f56`](https://github.com/Effect-TS/effect/commit/7564f56bb2844cf39d2b0d2d9e93cf9b2205e9a8)]:\n  - @effect/platform@0.69.1\n\n## 0.2.0\n\n### Patch Changes\n\n- Updated dependencies [[`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`6d9de6b`](https://github.com/Effect-TS/effect/commit/6d9de6b871c5c08e6509a4e830c3d74758faa198), [`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`c79c4c1`](https://github.com/Effect-TS/effect/commit/c79c4c178390fe61ff6dda88c9e058862349343a), [`38d30f0`](https://github.com/Effect-TS/effect/commit/38d30f08b8da62f9c3e308b9250738cb8d17bdb5), [`5821ce3`](https://github.com/Effect-TS/effect/commit/5821ce3455b47d25e0a40cae6ce22af9db5fa556)]:\n  - effect@3.10.0\n  - @effect/platform@0.69.0\n\n## 0.1.4\n\n### Patch Changes\n\n- Updated dependencies [[`382556f`](https://github.com/Effect-TS/effect/commit/382556f8930780c0634de681077706113a8c8239), [`97cb014`](https://github.com/Effect-TS/effect/commit/97cb0145114b2cd2f378e98f6c4ff5bf2c1865f5)]:\n  - @effect/schema@0.75.5\n  - @effect/platform@0.68.6\n\n## 0.1.3\n\n### Patch Changes\n\n- Updated dependencies [[`2036402`](https://github.com/Effect-TS/effect/commit/20364020b8b75a684791aa93d90626758023e9e9)]:\n  - @effect/platform@0.68.5\n\n## 0.1.2\n\n### Patch Changes\n\n- Updated dependencies [[`1b1ef29`](https://github.com/Effect-TS/effect/commit/1b1ef29ae302322f69dc938f9337aa97b4c63266)]:\n  - @effect/platform@0.68.4\n\n## 0.1.1\n\n### Patch Changes\n\n- Updated dependencies [[`61a99b2`](https://github.com/Effect-TS/effect/commit/61a99b2bf9d757870ef0c2ec9d4c877cdd364a3d), [`8c33087`](https://github.com/Effect-TS/effect/commit/8c330879425e80bed2f65e407cd59e991f0d7bec)]:\n  - effect@3.9.2\n  - @effect/platform@0.68.3\n  - @effect/schema@0.75.4\n\n## 0.1.0\n\n### Minor Changes\n\n- [#3631](https://github.com/Effect-TS/effect/pull/3631) [`bd160a4`](https://github.com/Effect-TS/effect/commit/bd160a4f714b0f1cb5867e458fd70f9131b060d6) Thanks @tim-smart! - add @effect/ai packages\n\n  Experimental modules for working with LLMs, currently only from OpenAI.\n\n### Patch Changes\n\n- Updated dependencies [[`360ec14`](https://github.com/Effect-TS/effect/commit/360ec14dd4102c526aef7433a8881ad4d9beab75)]:\n  - @effect/schema@0.75.3\n  - @effect/platform@0.68.2\n"
  },
  {
    "path": "packages/ai/ai/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Effectful Technologies Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/ai/ai/README.md",
    "content": "# `@effect/ai`\n\n## Documentation\n\n- **Introduction**: [Read the introduction and usage guide on our website](https://effect.website/docs/ai/introduction)\n- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/ai/ai).\n"
  },
  {
    "path": "packages/ai/ai/docgen.json",
    "content": "{\n  \"$schema\": \"../../../node_modules/@effect/docgen/schema.json\",\n  \"exclude\": [\"src/internal/**/*.ts\"],\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/ai/ai/src/\",\n  \"examplesCompilerOptions\": {\n    \"noEmit\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"module\": \"ES2022\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n    \"paths\": {\n      \"effect\": [\"../../../../effect/src/index.js\"],\n      \"effect/*\": [\"../../../../effect/src/*.js\"],\n      \"@effect/platform\": [\"../../../../platform/src/index.js\"],\n      \"@effect/platform/*\": [\"../../../../platform/src/*.js\"],\n      \"@effect/platform-node\": [\"../../../../platform-node/src/index.js\"],\n      \"@effect/platform-node/*\": [\"../../../../platform-node/src/*.js\"],\n      \"@effect/ai\": [\"../../../ai/src/index.js\"],\n      \"@effect/ai/*\": [\"../../../ai/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/ai/ai/package.json",
    "content": "{\n  \"name\": \"@effect/ai\",\n  \"type\": \"module\",\n  \"version\": \"0.35.0\",\n  \"license\": \"MIT\",\n  \"description\": \"Effect modules for working with AI apis\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/ai/ai\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"keywords\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"peerDependencies\": {\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/rpc\": \"workspace:^\",\n    \"effect\": \"workspace:^\"\n  },\n  \"devDependencies\": {\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/rpc\": \"workspace:^\",\n    \"effect\": \"workspace:^\"\n  },\n  \"dependencies\": {\n    \"find-my-way-ts\": \"^0.1.6\"\n  }\n}\n"
  },
  {
    "path": "packages/ai/ai/src/AiError.ts",
    "content": "/**\n * The `AiError` module provides comprehensive error handling for AI operations.\n *\n * This module defines a hierarchy of error types that can occur when working\n * with AI services, including HTTP request/response errors, input/output\n * validation errors, and general runtime errors. All errors follow Effect's\n * structured error patterns and provide detailed context for debugging.\n *\n * ## Error Types\n *\n * - **HttpRequestError**: Errors occurring during HTTP request processing\n * - **HttpResponseError**: Errors occurring during HTTP response processing\n * - **MalformedInput**: Errors when input data doesn't match expected format\n * - **MalformedOutput**: Errors when output data can't be parsed or validated\n * - **UnknownError**: Catch-all for unexpected runtime errors\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import { Effect, Match } from \"effect\"\n *\n * const handleAiError = Match.type<AiError.AiError>().pipe(\n *   Match.tag(\"HttpRequestError\", (err) =>\n *     Effect.logError(`Request failed: ${err.message}`)\n *   ),\n *   Match.tag(\"HttpResponseError\", (err) =>\n *     Effect.logError(`Response error (${err.response.status}): ${err.message}`)\n *   ),\n *   Match.tag(\"MalformedInput\", (err) =>\n *     Effect.logError(`Invalid input: ${err.message}`)\n *   ),\n *   Match.tag(\"MalformedOutput\", (err) =>\n *     Effect.logError(`Invalid output: ${err.message}`)\n *   ),\n *   Match.orElse((err) =>\n *     Effect.logError(`Unknown error: ${err.message}`)\n *   )\n * )\n * ```\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import { Effect, Option } from \"effect\"\n *\n * const aiOperation = Effect.gen(function* () {\n *   // Some AI operation that might fail\n *   return yield* new AiError.HttpRequestError({\n *     module: \"OpenAI\",\n *     method: \"completion\",\n *     reason: \"Transport\",\n *     request: {\n *       method: \"POST\",\n *       url: \"https://api.openai.com/v1/completions\",\n *       urlParams: [],\n *       hash: Option.none(),\n *       headers: { \"Content-Type\": \"application/json\" }\n *     }\n *   })\n * })\n *\n * const program = aiOperation.pipe(\n *   Effect.catchTag(\"HttpRequestError\", (error) => {\n *     console.log(\"Request failed:\", error.message)\n *     return Effect.succeed(\"fallback response\")\n *   })\n * )\n * ```\n *\n * @since 1.0.0\n */\nimport type * as HttpClientError from \"@effect/platform/HttpClientError\"\nimport * as Effect from \"effect/Effect\"\nimport * as Inspectable from \"effect/Inspectable\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\n\n/**\n * Unique identifier for AI errors.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport const TypeId = \"~@effect/ai/AiError\"\n\n/**\n * Type-level representation of the AI error identifier.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * Type guard to check if a value is an AI error.\n *\n * @param u - The value to check\n * @returns `true` if the value is an `AiError`, `false` otherwise\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n *\n * const someError = new Error(\"generic error\")\n * const aiError = new AiError.UnknownError({\n *   module: \"Test\",\n *   method: \"example\"\n * })\n *\n * console.log(AiError.isAiError(someError)) // false\n * console.log(AiError.isAiError(aiError))   // true\n * ```\n *\n * @since 1.0.0\n * @category Guards\n */\nexport const isAiError = (u: unknown): u is AiError => Predicate.hasProperty(u, TypeId)\n\n// =============================================================================\n// Http Request Error\n// =============================================================================\n\n/**\n * Schema for HTTP request details used in error reporting.\n *\n * Captures comprehensive information about HTTP requests that failed,\n * enabling detailed error analysis and debugging.\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import { Option } from \"effect\"\n *\n * const requestDetails: typeof AiError.HttpRequestDetails.Type = {\n *   method: \"POST\",\n *   url: \"https://api.openai.com/v1/completions\",\n *   urlParams: [[\"model\", \"gpt-4\"], [\"stream\", \"false\"]],\n *   hash: Option.some(\"#section1\"),\n *   headers: { \"Content-Type\": \"application/json\" }\n * }\n * ```\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const HttpRequestDetails = Schema.Struct({\n  method: Schema.Literal(\"GET\", \"POST\", \"PATCH\", \"PUT\", \"DELETE\", \"HEAD\", \"OPTIONS\"),\n  url: Schema.String,\n  urlParams: Schema.Array(Schema.Tuple(Schema.String, Schema.String)),\n  hash: Schema.Option(Schema.String),\n  headers: Schema.Record({ key: Schema.String, value: Schema.String })\n}).annotations({ identifier: \"HttpRequestDetails\" })\n\n/**\n * Error that occurs during HTTP request processing.\n *\n * This error is raised when issues arise before receiving an HTTP response,\n * such as network connectivity problems, request encoding issues, or invalid\n * URLs.\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import * as Effect from \"effect/Effect\"\n * import * as Option from \"effect/Option\"\n *\n * const handleNetworkError = Effect.gen(function* () {\n *   const error = new AiError.HttpRequestError({\n *     module: \"OpenAI\",\n *     method: \"createCompletion\",\n *     reason: \"Transport\",\n *     request: {\n *       method: \"POST\",\n *       url: \"https://api.openai.com/v1/completions\",\n *       urlParams: [],\n *       hash: Option.none(),\n *       headers: { \"Content-Type\": \"application/json\" }\n *     },\n *     description: \"Connection timeout after 30 seconds\"\n *   })\n *\n *   console.log(error.message)\n *   // \"Transport: Connection timeout after 30 seconds (POST https://api.openai.com/v1/completions)\"\n * })\n * ```\n *\n * @since 1.0.0\n * @category Errors\n */\nexport class HttpRequestError extends Schema.TaggedError<HttpRequestError>(\n  \"@effect/ai/AiError/HttpRequestError\"\n)(\"HttpRequestError\", {\n  module: Schema.String,\n  method: Schema.String,\n  reason: Schema.Literal(\"Transport\", \"Encode\", \"InvalidUrl\"),\n  request: HttpRequestDetails,\n  description: Schema.optional(Schema.String),\n  cause: Schema.optional(Schema.Defect)\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId]: TypeId = TypeId\n\n  /**\n   * Creates an HttpRequestError from a platform HttpClientError.RequestError.\n   *\n   * @example\n   * ```ts\n   * import { AiError } from \"@effect/ai\"\n   * import { HttpClientError } from \"@effect/platform\"\n   * import { Option } from \"effect\"\n   *\n   * declare const platformError: HttpClientError.RequestError\n   *\n   * const aiError = AiError.HttpRequestError.fromRequestError({\n   *   module: \"ChatGPT\",\n   *   method: \"sendMessage\",\n   *   error: platformError\n   * })\n   * ```\n   *\n   * @since 1.0.0\n   * @category Constructors\n   */\n  static fromRequestError({ error, ...params }: {\n    readonly module: string\n    readonly method: string\n    readonly error: HttpClientError.RequestError\n  }): HttpRequestError {\n    return new HttpRequestError({\n      ...params,\n      cause: error,\n      description: error.description,\n      reason: error.reason,\n      request: {\n        hash: error.request.hash,\n        headers: Inspectable.redact(error.request.headers) as any,\n        method: error.request.method,\n        url: error.request.url,\n        urlParams: error.request.urlParams\n      }\n    }, { disableValidation: true })\n  }\n\n  get message(): string {\n    const methodAndUrl = `${this.request.method} ${this.request.url}`\n\n    let baseMessage = this.description\n      ? `${this.reason}: ${this.description}`\n      : `${this.reason}: An HTTP request error occurred.`\n\n    baseMessage += ` (${methodAndUrl})`\n\n    let suggestion = \"\"\n    switch (this.reason) {\n      case \"Encode\": {\n        suggestion += \"Check that the request body data is properly formatted and matches the expected content type.\"\n        break\n      }\n\n      case \"InvalidUrl\": {\n        suggestion += \"Verify that the URL format is correct and that all required parameters have been provided.\"\n        suggestion += \" Check for any special characters that may need encoding.\"\n        break\n      }\n\n      case \"Transport\": {\n        suggestion += \"Check your network connection and verify that the requested URL is accessible.\"\n        break\n      }\n    }\n\n    baseMessage += `\\n\\nSuggestion: ${suggestion}`\n\n    return baseMessage\n  }\n}\n\n// =============================================================================\n// Http Response Error\n// =============================================================================\n\n/**\n * Schema for HTTP response details used in error reporting.\n *\n * Captures essential information about HTTP responses that caused errors,\n * including status codes and headers for debugging purposes.\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n *\n * const responseDetails: typeof AiError.HttpResponseDetails.Type = {\n *   status: 429,\n *   headers: {\n *     \"Content-Type\": \"application/json\",\n *     \"X-RateLimit-Remaining\": \"0\",\n *     \"Retry-After\": \"60\"\n *   }\n * }\n * ```\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const HttpResponseDetails = Schema.Struct({\n  status: Schema.Number,\n  headers: Schema.Record({ key: Schema.String, value: Schema.String })\n}).annotations({ identifier: \"HttpResponseDetails\" })\n\n/**\n * Error that occurs during HTTP response processing.\n *\n * This error is thrown when issues arise after receiving an HTTP response,\n * such as unexpected status codes, response decoding failures, or empty\n * response bodies.\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import { Option } from \"effect\"\n *\n * const responseError = new AiError.HttpResponseError({\n *   module: \"OpenAI\",\n *   method: \"createCompletion\",\n *   reason: \"StatusCode\",\n *   request: {\n *     method: \"POST\",\n *     url: \"https://api.openai.com/v1/completions\",\n *     urlParams: [],\n *     hash: Option.none(),\n *     headers: { \"Content-Type\": \"application/json\" }\n *   },\n *   response: {\n *     status: 429,\n *     headers: { \"X-RateLimit-Remaining\": \"0\" }\n *   },\n *   description: \"Rate limit exceeded\"\n * })\n *\n * console.log(responseError.message)\n * // \"StatusCode: Rate limit exceeded (429 POST https://api.openai.com/v1/completions)\"\n * ```\n *\n * @since 1.0.0\n * @category Errors\n */\nexport class HttpResponseError extends Schema.TaggedError<HttpResponseError>(\n  \"@effect/ai/AiError/HttpResponseError\"\n)(\"HttpResponseError\", {\n  module: Schema.String,\n  method: Schema.String,\n  request: HttpRequestDetails,\n  response: HttpResponseDetails,\n  body: Schema.optional(Schema.String),\n  reason: Schema.Literal(\"StatusCode\", \"Decode\", \"EmptyBody\"),\n  description: Schema.optional(Schema.String)\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId]: TypeId = TypeId\n\n  /**\n   * Creates an HttpResponseError from a platform HttpClientError.ResponseError.\n   *\n   * @example\n   * ```ts\n   * import { AiError } from \"@effect/ai\"\n   * import { Headers, HttpClientError } from \"@effect/platform\"\n   * import { Option } from \"effect\"\n   *\n   * declare const platformError: HttpClientError.ResponseError\n   *\n   * const aiError = AiError.HttpResponseError.fromResponseError({\n   *   module: \"OpenAI\",\n   *   method: \"completion\",\n   *   error: platformError\n   * })\n   * ```\n   *\n   * @since 1.0.0\n   * @category Constructors\n   */\n  static fromResponseError({ error, ...params }: {\n    readonly module: string\n    readonly method: string\n    readonly error: HttpClientError.ResponseError\n  }): Effect.Effect<never, HttpResponseError> {\n    let body: Effect.Effect<unknown, HttpClientError.ResponseError> = Effect.void\n    const contentType = error.response.headers[\"content-type\"] ?? \"\"\n    if (contentType.includes(\"application/json\")) {\n      body = error.response.json\n    } else if (contentType.includes(\"text/\") || contentType.includes(\"urlencoded\")) {\n      body = error.response.text\n    }\n    return Effect.flatMap(Effect.merge(body), (body) =>\n      new HttpResponseError({\n        ...params,\n        description: error.description,\n        reason: error.reason,\n        request: {\n          hash: error.request.hash,\n          headers: Inspectable.redact(error.request.headers) as any,\n          method: error.request.method,\n          url: error.request.url,\n          urlParams: error.request.urlParams\n        },\n        response: {\n          headers: Inspectable.redact(error.response.headers) as any,\n          status: error.response.status\n        },\n        body: Inspectable.format(body)\n      }, { disableValidation: true }))\n  }\n\n  get message(): string {\n    const methodUrlStatus = `${this.response.status} ${this.request.method} ${this.request.url}`\n\n    let baseMessage = this.description\n      ? `${this.reason}: ${this.description}`\n      : `${this.reason}: An HTTP response error occurred.`\n\n    baseMessage += ` (${methodUrlStatus})`\n\n    let suggestion = \"\"\n    switch (this.reason) {\n      case \"Decode\": {\n        suggestion += \"The response format does not match what is expected. \" +\n          \"Verify API version compatibility, check response content-type, \" +\n          \"and/or examine if the endpoint schema has changed.\"\n        break\n      }\n      case \"EmptyBody\": {\n        suggestion += \"The response body was empty. This may indicate a server \" +\n          \"issue, API version mismatch, or the endpoint may have changed its response format.\"\n        break\n      }\n      case \"StatusCode\": {\n        suggestion += getStatusCodeSuggestion(this.response.status)\n        break\n      }\n    }\n\n    baseMessage += `\\n\\n${suggestion}`\n\n    if (Predicate.isNotUndefined(this.body)) {\n      baseMessage += `\\n\\nResponse Body: ${this.body}`\n    }\n\n    return baseMessage\n  }\n}\n\n// =============================================================================\n// Malformed Input Error\n// =============================================================================\n\n/**\n * Error thrown when input data doesn't match the expected format or schema.\n *\n * This error occurs when the data provided to an AI operation fails validation,\n * is missing required fields, or doesn't conform to the expected structure.\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import * as Effect from \"effect/Effect\"\n *\n * const validateInput = (data: unknown): Effect.Effect<string, AiError.MalformedInput> =>\n *   typeof data === \"string\" && data.length > 0\n *     ? Effect.succeed(data)\n *     : Effect.fail(new AiError.MalformedInput({\n *         module: \"ChatBot\",\n *         method: \"processMessage\",\n *         description: \"Input must be a non-empty string\"\n *       }))\n *\n * const program = validateInput(\"\").pipe(\n *   Effect.catchTag(\"MalformedInput\", (error) => {\n *     console.log(`Input validation failed: ${error.description}`)\n *     return Effect.succeed(\"Please provide a valid message\")\n *   })\n * )\n * ```\n *\n * @since 1.0.0\n * @category Errors\n */\nexport class MalformedInput extends Schema.TaggedError<MalformedInput>(\n  \"@effect/ai/AiError/MalformedInput\"\n)(\"MalformedInput\", {\n  module: Schema.String,\n  method: Schema.String,\n  description: Schema.optional(Schema.String),\n  cause: Schema.optional(Schema.Defect)\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId]: TypeId = TypeId\n}\n\n// =============================================================================\n// Malformed Output Error\n// =============================================================================\n\n/**\n * Error thrown when output data can't be parsed or validated.\n *\n * This error occurs when AI service responses don't match the expected format,\n * contain invalid data structures, or fail schema validation during parsing.\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import { Effect, Schema } from \"effect\"\n *\n * const ResponseSchema = Schema.Struct({\n *   message: Schema.String,\n *   tokens: Schema.Number\n * })\n *\n * const parseResponse = (data: unknown) =>\n *   Schema.decodeUnknown(ResponseSchema)(data).pipe(\n *     Effect.mapError(parseError =>\n *       new AiError.MalformedOutput({\n *         module: \"OpenAI\",\n *         method: \"completion\",\n *         description: \"Response doesn't match expected schema\",\n *         cause: parseError\n *       })\n *     )\n *   )\n *\n * const program = parseResponse({ invalid: \"data\" }).pipe(\n *   Effect.catchTag(\"MalformedOutput\", (error) => {\n *     console.log(`Parsing failed: ${error.description}`)\n *     return Effect.succeed({ message: \"Error\", tokens: 0 })\n *   })\n * )\n * ```\n *\n * @since 1.0.0\n * @category Errors\n */\nexport class MalformedOutput extends Schema.TaggedError<MalformedOutput>(\n  \"@effect/ai/AiError/MalformedOutput\"\n)(\"MalformedOutput\", {\n  module: Schema.String,\n  method: Schema.String,\n  description: Schema.optional(Schema.String),\n  cause: Schema.optional(Schema.Defect)\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId]: TypeId = TypeId\n\n  /**\n   * Creates a MalformedOutput error from a Schema ParseError.\n   *\n   * @example\n   * ```ts\n   * import { AiError } from \"@effect/ai\"\n   * import { Effect, Schema } from \"effect\"\n   *\n   * const UserSchema = Schema.Struct({\n   *   name: Schema.String,\n   *   age: Schema.Number\n   * })\n   *\n   * const parseUser = (data: unknown) =>\n   *   Schema.decodeUnknown(UserSchema)(data).pipe(\n   *     Effect.mapError((parseError) =>\n   *       AiError.MalformedOutput.fromParseError({\n   *         module: \"UserService\",\n   *         method: \"parseUserData\",\n   *         error: parseError\n   *       })\n   *     )\n   *   )\n   * ```\n   *\n   * @since 1.0.0\n   * @category Constructors\n   */\n  static fromParseError({ error, ...params }: {\n    readonly module: string\n    readonly method: string\n    readonly description?: string\n    readonly error: ParseError\n  }): MalformedOutput {\n    // TODO(Max): enhance\n    return new MalformedOutput({\n      ...params,\n      cause: error\n    })\n  }\n}\n\n// =============================================================================\n// Unknown Error\n// =============================================================================\n\n/**\n * Catch-all error for unexpected runtime errors in AI operations.\n *\n * This error is used when an unexpected exception occurs that doesn't fit\n * into the other specific error categories. It provides context about where\n * the error occurred and preserves the original cause for debugging.\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const riskyOperation = () => {\n *   try {\n *     // Some operation that might throw\n *     throw new Error(\"Unexpected network issue\")\n *   } catch (cause) {\n *     return Effect.fail(new AiError.UnknownError({\n *       module: \"ChatService\",\n *       method: \"sendMessage\",\n *       description: \"An unexpected error occurred during message processing\",\n *       cause\n *     }))\n *   }\n * }\n *\n * const program = riskyOperation().pipe(\n *   Effect.catchTag(\"UnknownError\", (error) => {\n *     console.log(error.message)\n *     // \"ChatService.sendMessage: An unexpected error occurred during message processing\"\n *     return Effect.succeed(\"Service temporarily unavailable\")\n *   })\n * )\n * ```\n *\n * @since 1.0.0\n * @category Errors\n */\nexport class UnknownError extends Schema.TaggedError<UnknownError>(\n  \"@effect/ai/UnknownError\"\n)(\"UnknownError\", {\n  module: Schema.String,\n  method: Schema.String,\n  description: Schema.optional(Schema.String),\n  cause: Schema.optional(Schema.Defect)\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId]: TypeId = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  get message(): string {\n    const moduleMethod = `${this.module}.${this.method}`\n    return Predicate.isUndefined(this.description)\n      ? `${moduleMethod}: An error occurred`\n      : `${moduleMethod}: ${this.description}`\n  }\n}\n\n// =============================================================================\n// AiError\n// =============================================================================\n\n/**\n * Union type representing all possible AI operation errors.\n *\n * This type encompasses all error cases that can occur during AI operations,\n * providing a comprehensive error handling surface for applications.\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import { Effect, Match } from \"effect\"\n *\n * const handleAnyAiError = Match.type<AiError.AiError>().pipe(\n *   Match.tag(\"HttpRequestError\", (err) =>\n *     `Network error: ${err.reason}`\n *   ),\n *   Match.tag(\"HttpResponseError\", (err) =>\n *     `Server error: HTTP ${err.response.status}`\n *   ),\n *   Match.tag(\"MalformedInput\", (err) =>\n *     `Invalid input: ${err.description || \"Data validation failed\"}`\n *   ),\n *   Match.tag(\"MalformedOutput\", (err) =>\n *     `Invalid response: ${err.description || \"Response parsing failed\"}`\n *   ),\n *   Match.orElse((err) =>\n *     `Unknown error: ${err.message}`\n *   )\n * )\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport type AiError =\n  | HttpRequestError\n  | HttpResponseError\n  | MalformedInput\n  | MalformedOutput\n  | UnknownError\n\n/**\n * Schema for validating and parsing AI errors.\n *\n * This schema can be used to decode unknown values into properly typed AI\n * errors, ensuring type safety when handling errors from external sources or\n * serialized data.\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import { Schema, Effect } from \"effect\"\n *\n * const parseAiError = (data: unknown) =>\n *   Schema.decodeUnknown(AiError.AiError)(data).pipe(\n *     Effect.map(error => {\n *       console.log(`Parsed AI error: ${error._tag}`)\n *       return error\n *     }),\n *     Effect.catchAll(() =>\n *       Effect.succeed(new AiError.UnknownError({\n *         module: \"Parser\",\n *         method: \"parseAiError\",\n *         description: \"Failed to parse error data\"\n *       }))\n *     )\n *   )\n * ```\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const AiError: Schema.Union<[\n  typeof HttpRequestError,\n  typeof HttpResponseError,\n  typeof MalformedInput,\n  typeof MalformedOutput,\n  typeof UnknownError\n]> = Schema.Union(\n  HttpRequestError,\n  HttpResponseError,\n  MalformedInput,\n  MalformedOutput,\n  UnknownError\n)\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nconst getStatusCodeSuggestion = (statusCode: number): string => {\n  if (statusCode >= 400 && statusCode < 500) {\n    switch (statusCode) {\n      case 400:\n        return \"Bad Request - Check request parameters, headers, and body format against API documentation.\"\n      case 401:\n        return \"Unauthorized - Verify API key, authentication credentials, or token expiration.\"\n      case 403:\n        return \"Forbidden - Check API permissions, usage limits, or resource access rights.\"\n      case 404:\n        return \"Not Found - Verify the endpoint URL, API version, and resource identifiers.\"\n      case 408:\n        return \"Request Timeout - Consider increasing timeout duration or implementing retry logic.\"\n      case 422:\n        return \"Unprocessable Entity - Check request data validation, required fields, and data formats.\"\n      case 429:\n        return \"Rate Limited - Implement exponential backoff or reduce request frequency.\"\n      default:\n        return \"Client error - Review request format, parameters, and API documentation.\"\n    }\n  } else if (statusCode >= 500) {\n    return \"Server error - This is likely temporary. Implement retry logic with exponential backoff.\"\n  } else {\n    return \"Check API documentation for this status code.\"\n  }\n}\n"
  },
  {
    "path": "packages/ai/ai/src/Chat.ts",
    "content": "/**\n * The `Chat` module provides a stateful conversation interface for AI language\n * models.\n *\n * This module enables persistent chat sessions that maintain conversation\n * history, support tool calling, and offer both streaming and non-streaming\n * text generation. It integrates seamlessly with the Effect AI ecosystem,\n * providing type-safe conversational AI capabilities.\n *\n * @example\n * ```ts\n * import { Chat, LanguageModel } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * // Create a new chat session\n * const program = Effect.gen(function* () {\n *   const chat = yield* Chat.empty\n *\n *   // Send a message and get response\n *   const response = yield* chat.generateText({\n *     prompt: \"Hello! What can you help me with?\"\n *   })\n *\n *   console.log(response.content)\n *\n *   return response\n * })\n * ```\n *\n * @example\n * ```ts\n * import { Chat, LanguageModel } from \"@effect/ai\"\n * import { Effect, Stream } from \"effect\"\n *\n * // Streaming chat with tool support\n * const streamingChat = Effect.gen(function* () {\n *   const chat = yield* Chat.empty\n *\n *   yield* chat.streamText({\n *     prompt: \"Generate a creative story\"\n *   }).pipe(Stream.runForEach((part) =>\n *     Effect.sync(() => console.log(part))\n *   ))\n * })\n * ```\n *\n * @since 1.0.0\n */\nimport type { PersistenceBackingError } from \"@effect/experimental/Persistence\"\nimport { BackingPersistence } from \"@effect/experimental/Persistence\"\nimport * as Channel from \"effect/Channel\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schema from \"effect/Schema\"\nimport * as Stream from \"effect/Stream\"\nimport type { NoExcessProperties } from \"effect/Types\"\nimport * as AiError from \"./AiError.js\"\nimport * as IdGenerator from \"./IdGenerator.js\"\nimport * as LanguageModel from \"./LanguageModel.js\"\nimport * as Prompt from \"./Prompt.js\"\nimport type * as Response from \"./Response.js\"\nimport type * as Tool from \"./Tool.js\"\n\n/**\n * The `Chat` service tag for dependency injection.\n *\n * This tag provides access to chat functionality throughout your application,\n * enabling persistent conversational AI interactions with full context\n * management.\n *\n * @example\n * ```ts\n * import { Chat } from \"@effect/ai\"\n * import * as Effect from \"effect/Effect\"\n *\n * const useChat = Effect.gen(function* () {\n *   const chat = yield* Chat.Chat\n *   const response = yield* chat.generateText({\n *     prompt: \"Explain quantum computing in simple terms\"\n *   })\n *   return response.content\n * })\n * ```\n *\n * @since 1.0.0\n * @category Context\n */\nexport class Chat extends Context.Tag(\"@effect/ai/Chat\")<\n  Chat,\n  Service\n>() {}\n\n/**\n * Represents the interface that the `Chat` service provides.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Service {\n  /**\n   * Reference to the chat history.\n   *\n   * Provides direct access to the conversation history for advanced use cases\n   * like custom history manipulation or inspection.\n   *\n   * @example\n   * ```ts\n   * import { Chat } from \"@effect/ai\"\n   * import { Effect, Ref } from \"effect\"\n   *\n   * const inspectHistory = Effect.gen(function* () {\n   *   const chat = yield* Chat.empty\n   *   const currentHistory = yield* Ref.get(chat.history)\n   *   console.log(\"Current conversation:\", currentHistory)\n   *   return currentHistory\n   * })\n   * ```\n   */\n  readonly history: Ref.Ref<Prompt.Prompt>\n\n  /**\n   * Exports the chat history into a structured format.\n   *\n   * Returns the complete conversation history as a structured object\n   * that can be stored, transmitted, or processed by other systems.\n   *\n   * @example\n   * ```ts\n   * import { Chat } from \"@effect/ai\"\n   * import { Effect } from \"effect\"\n   *\n   * const saveChat = Effect.gen(function* () {\n   *   const chat = yield* Chat.empty\n   *   yield* chat.generateText({ prompt: \"Hello!\" })\n   *\n   *   const exportedData = yield* chat.export\n   *\n   *   // Save to database or file system\n   *   return exportedData\n   * })\n   * ```\n   */\n  readonly export: Effect.Effect<unknown, AiError.AiError>\n\n  /**\n   * Exports the chat history as a JSON string.\n   *\n   * Provides a convenient way to serialize the entire conversation\n   * for storage or transmission in JSON format.\n   *\n   * @example\n   * ```ts\n   * import { Chat } from \"@effect/ai\"\n   * import { Effect } from \"effect\"\n   *\n   * const backupChat = Effect.gen(function* () {\n   *   const chat = yield* Chat.empty\n   *   yield* chat.generateText({ prompt: \"Explain photosynthesis\" })\n   *\n   *   const jsonBackup = yield* chat.exportJson\n   *\n   *   yield* Effect.sync(() =>\n   *     localStorage.setItem(\"chat-backup\", jsonBackup)\n   *   )\n   *\n   *   return jsonBackup\n   * })\n   * ```\n   */\n  readonly exportJson: Effect.Effect<string, AiError.MalformedOutput>\n\n  /**\n   * Generate text using a language model for the specified prompt.\n   *\n   * If a toolkit is specified, the language model will have access to tools\n   * for function calling and enhanced capabilities. Both input and output\n   * messages are automatically added to the chat history.\n   *\n   * @example\n   * ```ts\n   * import { Chat } from \"@effect/ai\"\n   * import { Effect } from \"effect\"\n   *\n   * const chatWithAI = Effect.gen(function* () {\n   *   const chat = yield* Chat.empty\n   *\n   *   const response1 = yield* chat.generateText({\n   *     prompt: \"What is the capital of France?\"\n   *   })\n   *\n   *   const response2 = yield* chat.generateText({\n   *     prompt: \"What's the population of that city?\",\n   *   })\n   *\n   *   return [response1.content, response2.content]\n   * })\n   * ```\n   */\n  readonly generateText: <\n    Options extends NoExcessProperties<LanguageModel.GenerateTextOptions<any>, Options>,\n    Tools extends Record<string, Tool.Any> = {}\n  >(options: Options & LanguageModel.GenerateTextOptions<Tools>) => Effect.Effect<\n    LanguageModel.GenerateTextResponse<Tools>,\n    LanguageModel.ExtractError<Options>,\n    LanguageModel.LanguageModel | LanguageModel.ExtractContext<Options>\n  >\n\n  /**\n   * Generate text using a language model with streaming output.\n   *\n   * Returns a stream of response parts that are emitted as soon as they're\n   * available from the model. Supports tool calling and maintains chat history.\n   *\n   * @example\n   * ```ts\n   * import { Chat } from \"@effect/ai\"\n   * import { Effect, Stream, Console } from \"effect\"\n   *\n   * const streamingChat = Effect.gen(function* () {\n   *   const chat = yield* Chat.empty\n   *\n   *   const stream = yield* chat.streamText({\n   *     prompt: \"Write a short story about space exploration\"\n   *   })\n   *\n   *   yield* Stream.runForEach(stream, (part) =>\n   *     part.type === \"text-delta\"\n   *       ? Effect.sync(() => process.stdout.write(part.delta))\n   *       : Effect.void\n   *   )\n   * })\n   * ```\n   */\n  readonly streamText: <\n    Options extends NoExcessProperties<LanguageModel.GenerateTextOptions<any>, Options>,\n    Tools extends Record<string, Tool.Any> = {}\n  >(options: Options & LanguageModel.GenerateTextOptions<Tools>) => Stream.Stream<\n    Response.StreamPart<Tools>,\n    LanguageModel.ExtractError<Options>,\n    LanguageModel.LanguageModel | LanguageModel.ExtractContext<Options>\n  >\n\n  /**\n   * Generate a structured object using a language model and schema.\n   *\n   * Forces the model to return data that conforms to the specified schema,\n   * enabling structured data extraction and type-safe responses. The\n   * conversation history is maintained across calls.\n   *\n   * @example\n   * ```ts\n   * import { Chat } from \"@effect/ai\"\n   * import { Effect, Schema } from \"effect\"\n   *\n   * const ContactSchema = Schema.Struct({\n   *   name: Schema.String,\n   *   email: Schema.String,\n   *   phone: Schema.optional(Schema.String)\n   * })\n   *\n   * const extractContact = Effect.gen(function* () {\n   *   const chat = yield* Chat.empty\n   *\n   *   const contact = yield* chat.generateObject({\n   *     prompt: \"Extract contact info: John Doe, john@example.com, 555-1234\",\n   *     schema: ContactSchema\n   *   })\n   *\n   *   console.log(contact.object)\n   *   // { name: \"John Doe\", email: \"john@example.com\", phone: \"555-1234\" }\n   *\n   *   return contact.object\n   * })\n   * ```\n   */\n  readonly generateObject: <\n    A,\n    I extends Record<string, unknown>,\n    R,\n    Options extends NoExcessProperties<LanguageModel.GenerateObjectOptions<any, A, I, R>, Options>,\n    Tools extends Record<string, Tool.Any> = {}\n  >(options: Options & LanguageModel.GenerateObjectOptions<Tools, A, I, R>) => Effect.Effect<\n    LanguageModel.GenerateObjectResponse<Tools, A>,\n    LanguageModel.ExtractError<Options>,\n    LanguageModel.LanguageModel | R | LanguageModel.ExtractContext<Options>\n  >\n}\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\n/**\n * Creates a new Chat service with empty conversation history.\n *\n * This is the most common way to start a fresh chat session without\n * any initial context or system prompts.\n *\n * @example\n * ```ts\n * import { Chat } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const freshChat = Effect.gen(function* () {\n *   const chat = yield* Chat.empty\n *\n *   const response = yield* chat.generateText({\n *     prompt: \"Hello! Can you introduce yourself?\"\n *   })\n *\n *   console.log(response.content)\n *\n *   return chat\n * })\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const empty: Effect.Effect<Service> = Effect.gen(function*() {\n  const history = yield* Ref.make(Prompt.empty)\n  const context = yield* Effect.context<never>()\n  const semaphore = yield* Effect.makeSemaphore(1)\n\n  const provideContext = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n    Effect.mapInputContext(effect, (input) => Context.merge(context, input))\n  const provideContextStream = <A, E, R>(stream: Stream.Stream<A, E, R>): Stream.Stream<A, E, R> =>\n    Stream.mapInputContext(stream, (input) => Context.merge(context, input))\n\n  const encodeHistory = Schema.encode(Prompt.Prompt)\n  const encodeHistoryJson = Schema.encode(Prompt.FromJson)\n\n  return Chat.of({\n    history,\n    export: Ref.get(history).pipe(\n      Effect.flatMap(encodeHistory),\n      Effect.catchTag(\"ParseError\", (error) =>\n        AiError.MalformedOutput.fromParseError({\n          module: \"Chat\",\n          method: \"exportJson\",\n          description: \"Failed to encode chat history\",\n          error\n        })),\n      Effect.withSpan(\"Chat.export\")\n    ),\n    exportJson: Ref.get(history).pipe(\n      Effect.flatMap(encodeHistoryJson),\n      Effect.catchTag(\"ParseError\", (error) =>\n        AiError.MalformedOutput.fromParseError({\n          module: \"Chat\",\n          method: \"exportJson\",\n          description: \"Failed to encode chat history into JSON\",\n          error\n        })),\n      Effect.withSpan(\"Chat.exportJson\")\n    ),\n    generateText: Effect.fnUntraced(\n      function*(options) {\n        const newPrompt = Prompt.make(options.prompt)\n        const oldPrompt = yield* Ref.get(history)\n        const prompt = Prompt.merge(oldPrompt, newPrompt)\n\n        const response = yield* LanguageModel.generateText({ ...options, prompt })\n\n        const newHistory = Prompt.merge(prompt, Prompt.fromResponseParts(response.content))\n        yield* Ref.set(history, newHistory)\n\n        return response\n      },\n      provideContext,\n      semaphore.withPermits(1),\n      Effect.withSpan(\"Chat.generateText\", { captureStackTrace: false })\n    ),\n    streamText: Effect.fnUntraced(\n      function*(options) {\n        let parts = Chunk.empty<Response.AnyPart>()\n        return Stream.fromChannel(Channel.acquireUseRelease(\n          semaphore.take(1).pipe(\n            Effect.zipRight(Ref.get(history)),\n            Effect.map((history) => Prompt.merge(history, Prompt.make(options.prompt)))\n          ),\n          (prompt) =>\n            LanguageModel.streamText({ ...options, prompt }).pipe(\n              Stream.mapChunks((chunk) => {\n                parts = Chunk.appendAll(parts, chunk)\n                return chunk\n              }),\n              Stream.toChannel\n            ),\n          (prompt) =>\n            Effect.zipRight(\n              Ref.set(\n                history,\n                Prompt.merge(prompt, Prompt.fromResponseParts(Array.from(parts)))\n              ),\n              semaphore.release(1)\n            )\n        )).pipe(\n          provideContextStream,\n          Stream.withSpan(\"Chat.streamText\", {\n            captureStackTrace: false\n          })\n        )\n      },\n      Stream.unwrap\n    ),\n    generateObject: Effect.fnUntraced(\n      function*(options) {\n        const newPrompt = Prompt.make(options.prompt)\n        const oldPrompt = yield* Ref.get(history)\n        const prompt = Prompt.merge(oldPrompt, newPrompt)\n\n        const response = yield* LanguageModel.generateObject({ ...options, prompt })\n\n        const newHistory = Prompt.merge(prompt, Prompt.fromResponseParts(response.content))\n        yield* Ref.set(history, newHistory)\n\n        return response\n      },\n      provideContext,\n      semaphore.withPermits(1),\n      (effect, options) =>\n        Effect.withSpan(effect, \"Chat.generateObject\", {\n          attributes: {\n            objectName: \"objectName\" in options\n              ? options.objectName\n              : \"_tag\" in options.schema\n              ? options.schema._tag\n              : (options.schema as any).identifier ?? \"generateObject\"\n          },\n          captureStackTrace: false\n        })\n    )\n  })\n})\n\n/**\n * Creates a new Chat service from an initial prompt.\n *\n * This is the primary constructor for creating chat instances. It initializes\n * a new conversation with the provided prompt as the starting context.\n *\n * @example\n * ```ts\n * import { Chat, Prompt } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const chatWithSystemPrompt = Effect.gen(function* () {\n *   const chat = yield* Chat.fromPrompt([{\n *     role: \"system\",\n *     content: \"You are a helpful assistant specialized in mathematics.\"\n *   }])\n *\n *   const response = yield* chat.generateText({\n *     prompt: \"What is 2+2?\"\n *   })\n *\n *   return response.content\n * })\n * ```\n *\n * @example\n * ```ts\n * import { Chat, Prompt } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Initialize with conversation history\n * const existingChat = Effect.gen(function* () {\n *   const chat = yield* Chat.fromPrompt([\n *     { role: \"user\", content: [{ type: \"text\", text: \"What's the weather like?\" }] },\n *     { role: \"assistant\", content: [{ type: \"text\", text: \"I don't have access to weather data.\" }] },\n *     { role: \"user\", content: [{ type: \"text\", text: \"Can you help me with coding?\" }] }\n *   ])\n *\n *   const response = yield* chat.generateText({\n *     prompt: \"I need help with TypeScript\"\n *   })\n *\n *   return response\n * })\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const fromPrompt = Effect.fnUntraced(\n  function*(prompt: Prompt.RawInput) {\n    const chat = yield* empty\n    yield* Ref.set(chat.history, Prompt.make(prompt))\n    return chat\n  }\n)\n\nconst decodeUnknown = Schema.decodeUnknown(Prompt.Prompt)\n\n/**\n * Creates a Chat service from previously exported chat data.\n *\n * Restores a chat session from structured data that was previously exported\n * using the `export` method. Useful for persisting and restoring conversation\n * state.\n *\n * @example\n * ```ts\n * import { Chat } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * declare const loadFromDatabase: (sessionId: string) => Effect.Effect<unknown>\n *\n * const restoreChat = Effect.gen(function* () {\n *   // Assume we have previously exported data\n *   const savedData = yield* loadFromDatabase(\"chat-session-123\")\n *\n *   const restoredChat = yield* Chat.fromExport(savedData)\n *\n *   // Continue the conversation from where it left off\n *   const response = yield* restoredChat.generateText({\n *     prompt: \"Let's continue our discussion\"\n *   })\n * }).pipe(\n *   Effect.catchTag(\"ParseError\", (error) => {\n *     console.log(\"Failed to restore chat:\", error.message)\n *     return Effect.void\n *   })\n * )\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const fromExport = (data: unknown): Effect.Effect<Service, ParseError, LanguageModel.LanguageModel> =>\n  Effect.flatMap(decodeUnknown(data), fromPrompt)\n\nconst decodeHistoryJson = Schema.decodeUnknown(Prompt.FromJson)\n\n/**\n * Creates a Chat service from previously exported JSON chat data.\n *\n * Restores a chat session from JSON string that was previously exported\n * using the `exportJson` method. This is the most convenient way to\n * persist and restore chat sessions to/from storage systems.\n *\n * @example\n * ```ts\n * import { Chat } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const restoreFromJson = Effect.gen(function* () {\n *   // Load JSON from localStorage or file system\n *   const jsonData = localStorage.getItem(\"my-chat-backup\")\n *   if (!jsonData) return yield* Chat.empty\n *\n *   const restoredChat = yield* Chat.fromJson(jsonData)\n *\n *   // Chat history is now restored\n *   const response = yield* restoredChat.generateText({\n *     prompt: \"What were we talking about?\"\n *   })\n *\n *   return response\n * }).pipe(\n *   Effect.catchTag(\"ParseError\", (error) => {\n *     console.log(\"Invalid JSON format:\", error.message)\n *     return Chat.empty // Fallback to empty chat\n *   })\n * )\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const fromJson = (data: string): Effect.Effect<Service, ParseError, LanguageModel.LanguageModel> =>\n  Effect.flatMap(decodeHistoryJson(data), fromPrompt)\n\n// =============================================================================\n// Chat Persistence\n// =============================================================================\n\n/**\n * An error that occurs when attempting to retrieve a persisted `Chat` that\n * does not exist in the backing persistence store.\n *\n * @since 1.0.0\n * @category Errors\n */\nexport class ChatNotFoundError extends Schema.TaggedError<ChatNotFoundError>(\n  \"@effect/ai/Chat/ChatNotFoundError\"\n)(\"ChatNotFoundError\", { chatId: Schema.String }) {}\n\n// @effect-diagnostics effect/leakingRequirements:off\n/**\n * The context tag for chat persistence.\n *\n * @since 1.0.0\n * @category Context\n */\nexport class Persistence extends Context.Tag(\"@effect/ai/Chat/Persisted\")<\n  Persistence,\n  Persistence.Service\n>() {}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport declare namespace Persistence {\n  /**\n   * Represents the backing persistence for a persisted `Chat`. Allows for\n   * creating and retrieving chats that have been saved to a persistence store.\n   *\n   * @since 1.0.0\n   * @category Models\n   */\n  export interface Service {\n    /**\n     * Attempts to retrieve the persisted chat from the backing persistence\n     * store with the specified chat identifer. If the chat does not exist in\n     * the persistence store, a `ChatNotFoundError` will be returned.\n     */\n    readonly get: (chatId: string, options?: {\n      readonly timeToLive?: Duration.DurationInput | undefined\n    }) => Effect.Effect<\n      Persisted,\n      ChatNotFoundError | PersistenceBackingError\n    >\n\n    /**\n     * Attempts to retrieve the persisted chat from the backing persistence\n     * store with the specified chat identifer. If the chat does not exist in\n     * the persistence store, an empty chat will be created, saved, and\n     * returned.\n     */\n    readonly getOrCreate: (chatId: string, options?: {\n      readonly timeToLive?: Duration.DurationInput | undefined\n    }) => Effect.Effect<\n      Persisted,\n      AiError.MalformedOutput | PersistenceBackingError\n    >\n  }\n}\n\n/**\n * Represents a `Chat` that is backed by persistence.\n *\n * When calling a text generation method (e.g. `generateText`), the previous\n * chat history as well as the relevent response parts will be saved to the\n * backing persistence store.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Persisted extends Service {\n  /**\n   * The identifier for the chat in the backing persistence store.\n   */\n  readonly id: string\n\n  /**\n   * Saves the current chat history into the backing persistence store.\n   */\n  readonly save: Effect.Effect<void, AiError.MalformedOutput | PersistenceBackingError>\n}\n\n/**\n * Creates a new chat persistence service.\n *\n * The provided store identifier will be used to indicate which \"store\" the\n * backing persistence should load chats from.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const makePersisted = Effect.fnUntraced(function*(options: {\n  readonly storeId: string\n}) {\n  const persistence = yield* BackingPersistence\n  const store = yield* persistence.make(options.storeId)\n\n  const toPersisted = Effect.fnUntraced(\n    function*(chatId: string, chat: Service, ttl: Option.Option<Duration.Duration>) {\n      const idGenerator = yield* Effect.serviceOption(IdGenerator.IdGenerator).pipe(\n        Effect.map(Option.getOrElse(() => IdGenerator.defaultIdGenerator))\n      )\n\n      const saveChat = Effect.fnUntraced(\n        function*(prevHistory: Prompt.Prompt) {\n          // Get the current chat history\n          const history = yield* Ref.get(chat.history)\n          // Get the most recent message stored in the previous chat history\n          const lastMessage = prevHistory.content[prevHistory.content.length - 1]\n          // Determine the correct message identifier to use:\n          let messageId: string | undefined = undefined\n          // If the most recent message in the chat history is an assistant message,\n          // use the message identifer stored in that message\n          if (Predicate.isNotUndefined(lastMessage) && lastMessage.role === \"assistant\") {\n            messageId = lastMessage.options[Persistence.key]?.messageId as string | undefined\n          }\n          // If the chat history is empty or a message identifier did not exist on\n          // the most recent message in the chat history, generate a new identifier\n          if (Predicate.isUndefined(messageId)) {\n            messageId = yield* idGenerator.generateId()\n          }\n          // Mutate the new messages to add the generated message identifier\n          for (let i = prevHistory.content.length; i < history.content.length; i++) {\n            const message = history.content[i]\n            ;(message.options as any)[Persistence.key] = { messageId }\n          }\n          // Save the mutated history back to the ref\n          yield* Ref.set(chat.history, history)\n          // Export the chat to JSON\n          const json = yield* chat.exportJson\n          // Save the chat to the backing store\n          yield* store.set(chatId, json, ttl)\n        },\n        Effect.catchTag(\"PersistenceError\", (error) => {\n          // Should never happen because we are using the backing persistence\n          // store directly, and parse errors can only occur when using result\n          // persistence\n          if (error.reason === \"ParseError\") return Effect.die(error)\n          return Effect.fail(error)\n        })\n      )\n\n      const persisted: Persisted = {\n        ...chat,\n        id: chatId,\n        save: Effect.flatMap(Ref.get(chat.history), saveChat),\n        generateText: Effect.fnUntraced(function*(options) {\n          const history = yield* Ref.get(chat.history)\n          return yield* chat.generateText(options).pipe(\n            Effect.ensuring(Effect.orDie(saveChat(history)))\n          )\n        }),\n        generateObject: Effect.fnUntraced(function*(options) {\n          const history = yield* Ref.get(chat.history)\n          return yield* chat.generateObject(options).pipe(\n            Effect.ensuring(Effect.orDie(saveChat(history)))\n          )\n        }),\n        streamText: Effect.fnUntraced(function*(options) {\n          const history = yield* Ref.get(chat.history)\n          const stream = chat.streamText(options).pipe(\n            Stream.ensuring(Effect.orDie(saveChat(history)))\n          )\n          return stream\n        }, Stream.unwrap)\n      }\n\n      return persisted\n    }\n  )\n\n  const createChat = Effect.fnUntraced(\n    function*(chatId: string, ttl: Option.Option<Duration.Duration>) {\n      // Create an empty chat\n      const chat = yield* empty\n\n      // Save the history for the newly created chat\n      const history = yield* chat.exportJson\n      yield* store.set(chatId, history, ttl)\n\n      // Convert the chat to a persisted chat\n      return yield* toPersisted(chatId, chat, ttl)\n    },\n    Effect.catchTag(\"PersistenceError\", (error) => {\n      // Should never happen because we are using the backing persistence\n      // store directly, and parse errors can only occur when using result\n      // persistence\n      if (error.reason === \"ParseError\") return Effect.die(error)\n      return Effect.fail(error)\n    })\n  )\n\n  const getChat = Effect.fnUntraced(\n    function*(chatId: string, ttl: Option.Option<Duration.Duration>) {\n      // Create an empty chat\n      const chat = yield* empty\n\n      // Hydrate the chat history\n      yield* store.get(chatId).pipe(\n        Effect.flatMap(Effect.transposeMapOption(decodeHistoryJson)),\n        Effect.flatten,\n        Effect.catchTag(\"NoSuchElementException\", () => new ChatNotFoundError({ chatId })),\n        Effect.flatMap((history) => Ref.set(chat.history, history))\n      )\n\n      // Convert the chat to a persisted chat\n      return yield* toPersisted(chatId, chat, ttl)\n    },\n    Effect.catchTags({\n      ParseError: (error) => Effect.die(error),\n      PersistenceError: (error) => {\n        // Should never happen because we are using the backing persistence\n        // store directly, and parse errors can only occur when using result\n        // persistence\n        if (error.reason === \"ParseError\") return Effect.die(error)\n        return Effect.fail(error)\n      }\n    })\n  )\n\n  const makeTTL = (\n    timeToLive?: Duration.DurationInput | undefined\n  ): Option.Option<Duration.Duration> =>\n    Option.fromNullable(timeToLive).pipe(\n      Option.map(Duration.decode)\n    )\n\n  const get = Effect.fn(\"PersistedChat.get\")(\n    function*(chatId: string, options?: {\n      readonly timeToLive?: Duration.DurationInput | undefined\n    }) {\n      const ttl = makeTTL(options?.timeToLive)\n      return yield* getChat(chatId, ttl)\n    }\n  )\n\n  const getOrCreate = Effect.fn(\"PersistedChat.getOrCreate\")(\n    function*(chatId: string, options?: {\n      readonly timeToLive?: Duration.DurationInput | undefined\n    }) {\n      const ttl = makeTTL(options?.timeToLive)\n      return yield* getChat(chatId, ttl).pipe(\n        Effect.catchTag(\"ChatNotFoundError\", () => createChat(chatId, ttl))\n      )\n    }\n  )\n\n  return Persistence.of({\n    get,\n    getOrCreate\n  })\n})\n\n/**\n * Creates a `Layer` new chat persistence service.\n *\n * The provided store identifier will be used to indicate which \"store\" the\n * backing persistence should load chats from.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const layerPersisted = (options: {\n  readonly storeId: string\n}): Layer.Layer<Persistence, never, BackingPersistence> => Layer.scoped(Persistence, makePersisted(options))\n"
  },
  {
    "path": "packages/ai/ai/src/EmbeddingModel.ts",
    "content": "/**\n * The `EmbeddingModel` module provides vector embeddings for text using AI\n * models.\n *\n * This module enables efficient conversion of text into high-dimensional vector\n * representations that capture semantic meaning. It supports batching, caching,\n * and request optimization for production use cases like semantic search,\n * document similarity, and clustering.\n *\n * @example\n * ```ts\n * import { EmbeddingModel } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Basic embedding usage\n * const program = Effect.gen(function* () {\n *   const embedding = yield* EmbeddingModel.EmbeddingModel\n *\n *   const vector = yield* embedding.embed(\"Hello world!\")\n *   console.log(vector) // [0.123, -0.456, 0.789, ...]\n *\n *   return vector\n * })\n * ```\n *\n * @example\n * ```ts\n * import { EmbeddingModel } from \"@effect/ai\"\n * import { Effect, Duration } from \"effect\"\n *\n * declare const generateVectorFor: (text: string) => Array<number>\n *\n * // Create embedding service with batching and caching\n * const embeddingService = EmbeddingModel.make({\n *   embedMany: (texts) => Effect.succeed(\n *     texts.map((text, index) => ({\n *       index,\n *       embeddings: generateVectorFor(text)\n *     }))\n *   ),\n *   maxBatchSize: 50,\n *   cache: {\n *     capacity: 1000,\n *     timeToLive: Duration.minutes(30)\n *   }\n * })\n * ```\n *\n * @since 1.0.0\n */\nimport { dataLoader } from \"@effect/experimental/RequestResolver\"\nimport * as Context from \"effect/Context\"\nimport type * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Request from \"effect/Request\"\nimport * as RequestResolver from \"effect/RequestResolver\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Types from \"effect/Types\"\nimport * as AiError from \"./AiError.js\"\n\n/**\n * The `EmbeddingModel` service tag for dependency injection.\n *\n * This tag provides access to vector embedding functionality throughout your application,\n * enabling conversion of text to high-dimensional vectors for semantic analysis.\n *\n * @example\n * ```ts\n * import { EmbeddingModel } from \"@effect/ai\"\n * import * as Effect from \"effect/Effect\"\n *\n * const cosineSimilarity = (a: ReadonlyArray<number>, b: ReadonlyArray<number>): number => {\n *   const dot = a.reduce((sum, ai, i) => sum + ai * (b[i] ?? 0), 0)\n *   const normA = Math.sqrt(a.reduce((sum, ai) => sum + ai * ai, 0))\n *   const normB = Math.sqrt(b.reduce((sum, bi) => sum + bi * bi, 0))\n *   return normA === 0 || normB === 0 ? 0 : dot / (normA * normB)\n * }\n *\n * const useEmbeddings = Effect.gen(function* () {\n *   const embedder = yield* EmbeddingModel.EmbeddingModel\n *\n *   const documentVector = yield* embedder.embed(\"This is a sample document\")\n *   const queryVector = yield* embedder.embed(\"sample query\")\n *\n *   const similarity = cosineSimilarity(documentVector, queryVector)\n *   return similarity\n * })\n * ```\n *\n * @since 1.0.0\n * @category Context\n */\nexport class EmbeddingModel extends Context.Tag(\"@effect/ai/EmbeddingModel\")<\n  EmbeddingModel,\n  Service\n>() {}\n\n/**\n * The service interface for vector embedding operations.\n *\n * Defines the contract that all embedding model implementations must fulfill.\n * The service provides text-to-vector conversion functionality.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Service {\n  /**\n   * Converts a text string into a vector embedding.\n   */\n  readonly embed: (input: string) => Effect.Effect<Array<number>, AiError.AiError>\n  /**\n   * Converts a batch of text strings into a chunk of vector embeddings.\n   */\n  readonly embedMany: (input: ReadonlyArray<string>, options?: {\n    /**\n     * The concurrency level to use while batching requests.\n     */\n    readonly concurrency?: Types.Concurrency | undefined\n  }) => Effect.Effect<Array<Array<number>>, AiError.AiError>\n}\n\n/**\n * Represents the result of a batch embedding operation.\n *\n * Used internally by the batching system to associate embeddings with their\n * original request positions in the batch.\n *\n * @example\n * ```ts\n * import { EmbeddingModel } from \"@effect/ai\"\n *\n * const batchResults: EmbeddingModel.Result[] = [\n *   { index: 0, embeddings: [0.1, 0.2, 0.3] },\n *   { index: 1, embeddings: [0.4, 0.5, 0.6] },\n *   { index: 2, embeddings: [0.7, 0.8, 0.9] }\n * ]\n *\n * // Results correspond to input texts at positions 0, 1, 2\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Result {\n  /**\n   * The position index of this result in the original batch request.\n   */\n  readonly index: number\n\n  /**\n   * The vector embedding for the text at this index.\n   */\n  readonly embeddings: Array<number>\n}\n\nclass EmbeddingRequest extends Schema.TaggedRequest<EmbeddingRequest>(\n  \"@effect/ai/EmbeddingModel/Request\"\n)(\"EmbeddingRequest\", {\n  failure: AiError.AiError,\n  success: Schema.mutable(Schema.Array(Schema.Number)),\n  payload: { input: Schema.String }\n}) {}\n\nconst makeBatchedResolver = (\n  embedMany: (input: ReadonlyArray<string>) => Effect.Effect<Array<Result>, AiError.AiError>\n) =>\n  RequestResolver.makeBatched(\n    (requests: ReadonlyArray<EmbeddingRequest>) =>\n      embedMany(requests.map((request) => request.input)).pipe(\n        Effect.flatMap(\n          Effect.forEach(\n            ({ embeddings, index }) => Request.succeed(requests[index], embeddings),\n            { discard: true }\n          )\n        ),\n        Effect.catchAll((error) =>\n          Effect.forEach(\n            requests,\n            (request) => Request.fail(request, error),\n            { discard: true }\n          )\n        )\n      )\n  )\n\n/**\n * Creates an EmbeddingModel service with batching and caching capabilities.\n *\n * This is the primary constructor for creating embedding services. It supports\n * automatic batching of requests for efficiency and optional caching to reduce\n * redundant API calls.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (options: {\n  /**\n   * A method which processes a batch of text inputs and returns embedding\n   * results.\n   */\n  readonly embedMany: (input: ReadonlyArray<string>) => Effect.Effect<Array<Result>, AiError.AiError>\n  /**\n   * Optional maximum number of text inputs to process in one batch.\n   */\n  readonly maxBatchSize?: number\n  /**\n   * Optional configuration to control how batch request results are cached.\n   */\n  readonly cache?: {\n    /**\n     * The capacity of the cache.\n     */\n    readonly capacity: number\n    /**\n     * The time-to-live for items in the cache.\n     */\n    readonly timeToLive: Duration.DurationInput\n  }\n}) =>\n  Effect.gen(function*() {\n    const cache = yield* Option.fromNullable(options.cache).pipe(\n      Effect.flatMap((config) => Request.makeCache(config)),\n      Effect.optionFromOptional\n    )\n\n    const resolver = makeBatchedResolver(options.embedMany).pipe(\n      options.maxBatchSize ? RequestResolver.batchN(options.maxBatchSize) : identity\n    )\n\n    const embed = (input: string) => {\n      const request = Effect.request(new EmbeddingRequest({ input }), resolver)\n      return Option.match(cache, {\n        onNone: () => request,\n        onSome: (cache) =>\n          request.pipe(\n            Effect.withRequestCaching(true),\n            Effect.withRequestCache(cache)\n          )\n      })\n    }\n\n    const embedMany = (inputs: ReadonlyArray<string>, options?: {\n      readonly concurrency?: Types.Concurrency | undefined\n    }) =>\n      Effect.forEach(inputs, embed, {\n        batching: true,\n        concurrency: options?.concurrency\n      })\n\n    return EmbeddingModel.of({\n      embed: (input) =>\n        embed(input).pipe(\n          Effect.withSpan(\"EmbeddingModel.embed\", { captureStackTrace: false })\n        ),\n      embedMany: (inputs) =>\n        embedMany(inputs).pipe(\n          Effect.withSpan(\"EmbeddingModel.embedMany\", { captureStackTrace: false })\n        )\n    })\n  })\n\n/**\n * Creates an EmbeddingModel service with time-window based batching.\n *\n * This constructor creates a service that uses a data loader pattern to batch\n * embedding requests within a specified time window. This is optimal for\n * high-throughput scenarios where you want to automatically batch requests that\n * arrive within a short time period.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const makeDataLoader = (options: {\n  /**\n   * A method which processes a batch of text inputs and returns embedding\n   * results.\n   */\n  readonly embedMany: (input: ReadonlyArray<string>) => Effect.Effect<Array<Result>, AiError.AiError>\n  /**\n   * The duration between batch requests during which requests are collected and\n   * added to the current batch.\n   */\n  readonly window: Duration.DurationInput\n  /**\n   * Optional maximum number of requests to add to the batch before a batch\n   * request must be sent.\n   */\n  readonly maxBatchSize?: number\n}) =>\n  Effect.gen(function*() {\n    const resolver = makeBatchedResolver(options.embedMany)\n    const resolverDelayed = yield* dataLoader(resolver, {\n      window: options.window,\n      maxBatchSize: options.maxBatchSize\n    })\n\n    function embed(input: string) {\n      return Effect.request(new EmbeddingRequest({ input }), resolverDelayed).pipe(\n        Effect.withSpan(\"EmbeddingModel.embed\", { captureStackTrace: false })\n      )\n    }\n\n    function embedMany(inputs: ReadonlyArray<string>, options?: {\n      readonly concurrency?: Types.Concurrency | undefined\n    }) {\n      return Effect.forEach(inputs, embed, { batching: true, concurrency: options?.concurrency }).pipe(\n        Effect.withSpan(\"EmbeddingModel.embedMany\", { captureStackTrace: false })\n      )\n    }\n\n    return EmbeddingModel.of({\n      embed,\n      embedMany\n    })\n  })\n"
  },
  {
    "path": "packages/ai/ai/src/IdGenerator.ts",
    "content": "/**\n * The `IdGenerator` module provides a pluggable system for generating unique identifiers\n * for tool calls and other items in the Effect AI SDKs.\n *\n * This module offers a flexible and configurable approach to ID generation, supporting\n * custom alphabets, prefixes, separators, and sizes.\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * // Using the default ID generator\n * const program = Effect.gen(function* () {\n *   const idGen = yield* IdGenerator.IdGenerator\n *   const toolCallId = yield* idGen.generateId()\n *   console.log(toolCallId) // \"id_A7xK9mP2qR5tY8uV\"\n *   return toolCallId\n * }).pipe(\n *   Effect.provide(Layer.succeed(\n *     IdGenerator.IdGenerator,\n *     IdGenerator.defaultIdGenerator\n *   ))\n * )\n * ```\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * // Creating a custom ID generator for AI tool calls\n * const customLayer = IdGenerator.layer({\n *   alphabet: \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\",\n *   prefix: \"tool_call\",\n *   separator: \"-\",\n *   size: 12\n * })\n *\n * const program = Effect.gen(function* () {\n *   const idGen = yield* IdGenerator.IdGenerator\n *   const id = yield* idGen.generateId()\n *   console.log(id) // \"tool_call-A7XK9MP2QR5T\"\n *   return id\n * }).pipe(\n *   Effect.provide(customLayer)\n * )\n * ```\n *\n * @since 1.0.0\n */\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Random from \"effect/Random\"\n\n/**\n * The `IdGenerator` service tag for dependency injection.\n *\n * This tag is used to provide and access ID generation functionality throughout\n * the application. It follows Effect's standard service pattern for type-safe\n * dependency injection.\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const useIdGenerator = Effect.gen(function* () {\n *   const idGenerator = yield* IdGenerator.IdGenerator\n *   const newId = yield* idGenerator.generateId()\n *   return newId\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport class IdGenerator extends Context.Tag(\"@effect/ai/IdGenerator\")<\n  IdGenerator,\n  Service\n>() {}\n\n/**\n * The service interface for ID generation.\n *\n * Defines the contract that all ID generator implementations must fulfill.\n * The service provides a single method for generating unique identifiers\n * in an effectful context.\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Custom implementation\n * const customService: IdGenerator.Service = {\n *   generateId: () => Effect.succeed(`custom_${Date.now()}`)\n * }\n *\n * const program = Effect.gen(function* () {\n *   const id = yield* customService.generateId()\n *   console.log(id) // \"custom_1234567890\"\n *   return id\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Service {\n  readonly generateId: () => Effect.Effect<string>\n}\n\n/**\n * Configuration options for creating custom ID generators.\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n *\n * // Configuration for tool call IDs\n * const toolCallOptions: IdGenerator.MakeOptions = {\n *   alphabet: \"0123456789ABCDEF\",\n *   prefix: \"tool\",\n *   separator: \"_\",\n *   size: 8\n * }\n *\n * // This will generate IDs like: \"tool_A1B2C3D4\"\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface MakeOptions {\n  /**\n   * The character set to use for generating the random portion of IDs.\n   */\n  readonly alphabet: string\n  /**\n   * Optional prefix to prepend to generated IDs.\n   */\n  readonly prefix?: string | undefined\n  /**\n   * Character used to separate the prefix from the random portion.\n   */\n  readonly separator: string\n  /**\n   * Length of the random portion of the generated ID.\n   */\n  readonly size: number\n}\n\nconst DEFAULT_ALPHABET = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\nconst DEFAULT_SEPARATOR = \"_\"\nconst DEFAULT_SIZE = 16\n\nconst makeGenerator = ({\n  alphabet = DEFAULT_ALPHABET,\n  prefix,\n  separator = DEFAULT_SEPARATOR,\n  size = DEFAULT_SIZE\n}: Partial<MakeOptions>) => {\n  const alphabetLength = alphabet.length\n  return Effect.fnUntraced(function*() {\n    const chars = new Array(size)\n    for (let i = 0; i < size; i++) {\n      chars[i] = alphabet[((yield* Random.next) * alphabetLength) | 0]\n    }\n    const identifier = chars.join(\"\")\n    if (Predicate.isUndefined(prefix)) {\n      return identifier\n    }\n    return `${prefix}${separator}${identifier}`\n  })\n}\n\n/**\n * Default ID generator service implementation.\n *\n * Uses the standard configuration with \"id\" prefix and generates IDs in the\n * format \"id_XXXXXXXXXXXXXXXX\" where X represents random alphanumeric\n * characters.\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   const id = yield* IdGenerator.defaultIdGenerator.generateId()\n *   console.log(id) // \"id_A7xK9mP2qR5tY8uV\"\n *   return id\n * })\n *\n * // Or provide it as a service\n * const withDefault = program.pipe(\n *   Effect.provideService(\n *     IdGenerator.IdGenerator,\n *     IdGenerator.defaultIdGenerator\n *   )\n * )\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const defaultIdGenerator: Service = {\n  generateId: makeGenerator({ prefix: \"id\" })\n}\n\n/**\n * Creates a custom ID generator service with the specified options.\n *\n * Validates the configuration to ensure the separator is not part of the\n * alphabet, which would cause ambiguity in parsing generated IDs.\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   // Create a generator for AI assistant message IDs\n *   const messageIdGen = yield* IdGenerator.make({\n *     alphabet: \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n *     prefix: \"msg\",\n *     separator: \"-\",\n *     size: 10\n *   })\n *\n *   const messageId = yield* messageIdGen.generateId()\n *   console.log(messageId) // \"msg-A7X9K2M5P8\"\n *   return messageId\n * })\n * ```\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // This will fail with IllegalArgumentException\n * const invalidConfig = IdGenerator.make({\n *   alphabet: \"ABC123\",\n *   prefix: \"test\",\n *   separator: \"A\", // Error: separator is part of alphabet\n *   size: 8\n * })\n *\n * const program = Effect.gen(function* () {\n *   const generator = yield* invalidConfig\n *   return generator\n * }).pipe(\n *   Effect.catchAll(error =>\n *     Effect.succeed(`Configuration error: ${error.message}`)\n *   )\n * )\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.fnUntraced(function*({\n  alphabet = DEFAULT_ALPHABET,\n  prefix,\n  separator = DEFAULT_SEPARATOR,\n  size = DEFAULT_SIZE\n}: MakeOptions) {\n  if (alphabet.includes(separator)) {\n    const message = `The separator \"${separator}\" must not be part of the alphabet \"${alphabet}\".`\n    return yield* new Cause.IllegalArgumentException(message)\n  }\n\n  const generateId = makeGenerator({ alphabet, prefix, separator, size })\n\n  return {\n    generateId\n  } as const\n})\n\n/**\n * Creates a Layer that provides the IdGenerator service with custom\n * configuration.\n *\n * This is the recommended way to provide ID generation capabilities to your\n * application. The layer will fail during construction if the configuration is\n * invalid.\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * // Create a layer for generating AI tool call IDs\n * const toolCallIdLayer = IdGenerator.layer({\n *   alphabet: \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\n *   prefix: \"tool_call\",\n *   separator: \"_\",\n *   size: 12\n * })\n *\n * const program = Effect.gen(function* () {\n *   const idGen = yield* IdGenerator.IdGenerator\n *   const toolCallId = yield* idGen.generateId()\n *   console.log(toolCallId) // \"tool_call_A7XK9MP2QR5T\"\n *   return toolCallId\n * }).pipe(\n *   Effect.provide(toolCallIdLayer)\n * )\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const layer = (options: MakeOptions): Layer.Layer<IdGenerator, Cause.IllegalArgumentException> =>\n  Layer.effect(IdGenerator, make(options))\n"
  },
  {
    "path": "packages/ai/ai/src/LanguageModel.ts",
    "content": "/**\n * The `LanguageModel` module provides AI text generation capabilities with tool\n * calling support.\n *\n * This module offers a comprehensive interface for interacting with large\n * language models, supporting both streaming and non-streaming text generation,\n * structured output generation, and tool calling functionality. It provides a\n * unified API that can be implemented by different AI providers while\n * maintaining type safety and effect management.\n *\n * @example\n * ```ts\n * import { LanguageModel } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Basic text generation\n * const program = Effect.gen(function* () {\n *   const response = yield* LanguageModel.generateText({\n *     prompt: \"Explain quantum computing\"\n *   })\n *\n *   console.log(response.text)\n *\n *   return response\n * })\n * ```\n *\n * @example\n * ```ts\n * import { LanguageModel } from \"@effect/ai\"\n * import { Effect, Schema } from \"effect\"\n *\n * // Structured output generation\n * const ContactSchema = Schema.Struct({\n *   name: Schema.String,\n *   email: Schema.String\n * })\n *\n * const extractContact = Effect.gen(function* () {\n *   const response = yield* LanguageModel.generateObject({\n *     prompt: \"Extract contact: John Doe, john@example.com\",\n *     schema: ContactSchema\n *   })\n *\n *   return response.value\n * })\n * ```\n *\n * @since 1.0.0\n */\nimport * as Chunk from \"effect/Chunk\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type { Span } from \"effect/Tracer\"\nimport type { Concurrency, Mutable, NoExcessProperties } from \"effect/Types\"\nimport * as AiError from \"./AiError.js\"\nimport { defaultIdGenerator, IdGenerator } from \"./IdGenerator.js\"\nimport * as Prompt from \"./Prompt.js\"\nimport * as Response from \"./Response.js\"\nimport type { SpanTransformer } from \"./Telemetry.js\"\nimport { CurrentSpanTransformer } from \"./Telemetry.js\"\nimport type * as Tool from \"./Tool.js\"\nimport * as Toolkit from \"./Toolkit.js\"\n\n// =============================================================================\n// Service Definition\n// =============================================================================\n\n/**\n * The `LanguageModel` service tag for dependency injection.\n *\n * This tag provides access to language model functionality throughout your\n * application, enabling text generation, streaming, and structured output\n * capabilities.\n *\n * @example\n * ```ts\n * import { LanguageModel } from \"@effect/ai\"\n * import * as Effect from \"effect/Effect\"\n *\n * const useLanguageModel = Effect.gen(function* () {\n *   const model = yield* LanguageModel.LanguageModel\n *   const response = yield* model.generateText({\n *     prompt: \"What is machine learning?\"\n *   })\n *   return response.text\n * })\n * ```\n *\n * @since 1.0.0\n * @category Context\n */\nexport class LanguageModel extends Context.Tag(\"@effect/ai/LanguageModel\")<\n  LanguageModel,\n  Service\n>() {}\n\n/**\n * The service interface for language model operations.\n *\n * Defines the contract that all language model implementations must fulfill,\n * providing text generation, structured output, and streaming capabilities.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Service {\n  /**\n   * Generate text using the language model.\n   */\n  readonly generateText: <\n    Options extends NoExcessProperties<GenerateTextOptions<any>, Options>,\n    Tools extends Record<string, Tool.Any> = {}\n  >(options: Options & GenerateTextOptions<Tools>) => Effect.Effect<\n    GenerateTextResponse<Tools>,\n    ExtractError<Options>,\n    ExtractContext<Options>\n  >\n\n  /**\n   * Generate a structured object from a schema using the language model.\n   */\n  readonly generateObject: <\n    A,\n    I extends Record<string, unknown>,\n    R,\n    Options extends NoExcessProperties<GenerateObjectOptions<any, A, I, R>, Options>,\n    Tools extends Record<string, Tool.Any> = {}\n  >(options: Options & GenerateObjectOptions<Tools, A, I, R>) => Effect.Effect<\n    GenerateObjectResponse<Tools, A>,\n    ExtractError<Options>,\n    R | ExtractContext<Options>\n  >\n\n  /**\n   * Generate text using the language model with streaming output.\n   */\n  readonly streamText: <\n    Options extends NoExcessProperties<GenerateTextOptions<any>, Options>,\n    Tools extends Record<string, Tool.Any> = {}\n  >(options: Options & GenerateTextOptions<Tools>) => Stream.Stream<\n    Response.StreamPart<Tools>,\n    ExtractError<Options>,\n    ExtractContext<Options>\n  >\n}\n\n/**\n * Configuration options for text generation.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface GenerateTextOptions<Tools extends Record<string, Tool.Any>> {\n  /**\n   * The prompt input to use to generate text.\n   */\n  readonly prompt: Prompt.RawInput\n\n  /**\n   * A toolkit containing both the tools and the tool call handler to use to\n   * augment text generation.\n   */\n  readonly toolkit?: Toolkit.WithHandler<Tools> | Effect.Effect<Toolkit.WithHandler<Tools>, any, any> | undefined\n\n  /**\n   * The tool choice mode for the language model.\n   * - `auto` (default): The model can decide whether or not to call tools, as\n   *   well as which tools to call.\n   * - `required`: The model **must** call a tool but can decide which tool will\n   *   be called.\n   * - `none`: The model **must not** call a tool.\n   * - `{ tool: <tool_name> }`: The model must call the specified tool.\n   * - `{ mode?: \"auto\" (default) | \"required\", \"oneOf\": [<tool-names>] }`: The\n   *   model is restricted to the subset of tools specified by `oneOf`. When\n   *   `mode` is `\"auto\"` or omitted, the model can decide whether or not a tool\n   *   from the allowed subset of tools can be called. When `mode` is\n   *   `\"required\"`, the model **must** call one tool from the allowed subset of\n   *   tools.\n   */\n  readonly toolChoice?:\n    | ToolChoice<{ [Name in keyof Tools]: Tools[Name][\"name\"] }[keyof Tools]>\n    | undefined\n\n  /**\n   * The concurrency level for resolving tool calls.\n   */\n  readonly concurrency?: Concurrency | undefined\n\n  /**\n   * When set to `true`, tool calls requested by the large language model\n   * will not be auto-resolved by the framework.\n   *\n   * This option is useful when:\n   *   1. The user wants to include tool call definitions from an `AiToolkit`\n   *      in requests to the large language model so that the model has the\n   *      capability to call tools\n   *   2. The user wants to control the execution of tool call resolvers\n   *      instead of having the framework handle tool call resolution\n   */\n  readonly disableToolCallResolution?: boolean | undefined\n}\n\n/**\n * Configuration options for structured object generation.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface GenerateObjectOptions<Tools extends Record<string, Tool.Any>, A, I extends Record<string, unknown>, R>\n  extends GenerateTextOptions<Tools>\n{\n  /**\n   * The name of the structured output that should be generated. Used by some\n   * large language model providers to provide additional guidance to the model.\n   */\n  readonly objectName?: string | undefined\n\n  /**\n   * The schema to be used to specify the structure of the object to generate.\n   */\n  readonly schema: Schema.Schema<A, I, R>\n}\n\n/**\n * The tool choice mode for the language model.\n * - `auto` (default): The model can decide whether or not to call tools, as\n *   well as which tools to call.\n * - `required`: The model **must** call a tool but can decide which tool will\n *   be called.\n * - `none`: The model **must not** call a tool.\n * - `{ tool: <tool_name> }`: The model must call the specified tool.\n * - `{ mode?: \"auto\" (default) | \"required\", \"oneOf\": [<tool-names>] }`: The\n *   model is restricted to the subset of tools specified by `oneOf`. When\n *   `mode` is `\"auto\"` or omitted, the model can decide whether or not a tool\n *   from the allowed subset of tools can be called. When `mode` is\n *   `\"required\"`, the model **must** call one tool from the allowed subset of\n *   tools.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type ToolChoice<Tools extends string> = \"auto\" | \"none\" | \"required\" | {\n  readonly tool: Tools\n} | {\n  readonly mode?: \"auto\" | \"required\"\n  readonly oneOf: ReadonlyArray<Tools>\n}\n\n/**\n * Response class for text generation operations.\n *\n * Contains the generated content and provides convenient accessors for\n * extracting different types of response parts like text, tool calls, and usage\n * information.\n *\n * @example\n * ```ts\n * import { LanguageModel } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   const response = yield* LanguageModel.generateText({\n *     prompt: \"Explain photosynthesis\"\n *   })\n *\n *   console.log(response.text) // Generated text content\n *   console.log(response.finishReason) // \"stop\", \"length\", etc.\n *   console.log(response.usage) // Usage information\n *\n *   return response\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport class GenerateTextResponse<Tools extends Record<string, Tool.Any>> {\n  readonly content: Array<Response.Part<Tools>>\n\n  constructor(content: Array<Response.Part<Tools>>) {\n    this.content = content\n  }\n\n  /**\n   * Extracts and concatenates all text parts from the response.\n   */\n  get text(): string {\n    const text: Array<string> = []\n    for (const part of this.content) {\n      if (part.type === \"text\") {\n        text.push(part.text)\n      }\n    }\n    return text.join(\"\")\n  }\n\n  /**\n   * Returns all reasoning parts from the response.\n   */\n  get reasoning(): Array<Response.ReasoningPart> {\n    return this.content.filter((part) => part.type === \"reasoning\")\n  }\n\n  /**\n   * Extracts and concatenates all reasoning text, or undefined if none exists.\n   */\n  get reasoningText(): string | undefined {\n    const text: Array<string> = []\n    for (const part of this.content) {\n      if (part.type === \"reasoning\") {\n        text.push(part.text)\n      }\n    }\n    return text.length === 0 ? undefined : text.join(\"\")\n  }\n\n  /**\n   * Returns all tool call parts from the response.\n   */\n  get toolCalls(): Array<Response.ToolCallParts<Tools>> {\n    return this.content.filter((part) => part.type === \"tool-call\")\n  }\n\n  /**\n   * Returns all tool result parts from the response.\n   */\n  get toolResults(): Array<Response.ToolResultParts<Tools>> {\n    return this.content.filter((part) => part.type === \"tool-result\")\n  }\n\n  /**\n   * The reason why text generation finished.\n   */\n  get finishReason(): Response.FinishReason {\n    const finishPart = this.content.find((part) => part.type === \"finish\")\n    return Predicate.isUndefined(finishPart) ? \"unknown\" : finishPart.reason\n  }\n\n  /**\n   * Token usage statistics for the generation request.\n   */\n  get usage(): Response.Usage {\n    const finishPart = this.content.find((part) => part.type === \"finish\")\n    if (Predicate.isUndefined(finishPart)) {\n      return new Response.Usage({\n        inputTokens: undefined,\n        outputTokens: undefined,\n        totalTokens: undefined,\n        reasoningTokens: undefined,\n        cachedInputTokens: undefined\n      })\n    }\n    return finishPart.usage\n  }\n}\n\n/**\n * Response class for structured object generation operations.\n *\n * @example\n * ```ts\n * import { LanguageModel } from \"@effect/ai\"\n * import { Effect, Schema } from \"effect\"\n *\n * const UserSchema = Schema.Struct({\n *   name: Schema.String,\n *   email: Schema.String\n * })\n *\n * const program = Effect.gen(function* () {\n *   const response = yield* LanguageModel.generateObject({\n *     prompt: \"Create user: John Doe, john@example.com\",\n *     schema: UserSchema\n *   })\n *\n *   console.log(response.value) // { name: \"John Doe\", email: \"john@example.com\" }\n *   console.log(response.text) // Raw generated text\n *\n *   return response.value\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport class GenerateObjectResponse<Tools extends Record<string, Tool.Any>, A> extends GenerateTextResponse<Tools> {\n  /**\n   * The parsed structured object that conforms to the provided schema.\n   */\n  readonly value: A\n\n  constructor(value: A, content: Array<Response.Part<Tools>>) {\n    super(content)\n    this.value = value\n  }\n}\n\n// =============================================================================\n// Utility Types\n// =============================================================================\n\n/**\n * Utility type that extracts the error type from LanguageModel options.\n *\n * Automatically infers the possible error types based on toolkit configuration\n * and tool call resolution settings.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type ExtractError<Options> = Options extends {\n  readonly toolkit: Toolkit.WithHandler<infer _Tools>\n  readonly disableToolCallResolution: true\n} ? AiError.AiError\n  : Options extends {\n    readonly toolkit: Effect.Effect<Toolkit.WithHandler<infer _Tools>, infer _E, infer _R>\n    readonly disableToolCallResolution: true\n  } ? AiError.AiError | _E\n  : Options extends {\n    readonly toolkit: Toolkit.WithHandler<infer _Tools>\n  } ? AiError.AiError | Tool.HandlerError<_Tools[keyof _Tools]>\n  : Options extends {\n    readonly toolkit: Effect.Effect<Toolkit.WithHandler<infer _Tools>, infer _E, infer _R>\n  } ? AiError.AiError | Tool.HandlerError<_Tools[keyof _Tools]> | _E :\n  AiError.AiError\n\n/**\n * Utility type that extracts the context requirements from LanguageModel options.\n *\n * Automatically infers the required services based on the toolkit configuration.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type ExtractContext<Options> = Options extends {\n  readonly toolkit: Toolkit.WithHandler<infer _Tools>\n} ? Tool.Requirements<_Tools[keyof _Tools]>\n  : Options extends {\n    readonly toolkit: Effect.Effect<Toolkit.WithHandler<infer _Tools>, infer _E, infer _R>\n  } ? Tool.Requirements<_Tools[keyof _Tools]> | _R\n  : never\n\n// =============================================================================\n// Service Constructor\n// =============================================================================\n\n/**\n * Configuration options passed along to language model provider\n * implementations.\n *\n * This interface defines the normalized options that are passed to the\n * underlying provider implementation, regardless of the specific provider being\n * used.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ProviderOptions {\n  /**\n   * The prompt messages to use to generate text.\n   */\n  readonly prompt: Prompt.Prompt\n\n  /**\n   * The tools that the large language model will have available to provide\n   * additional information which can be incorporated into its text generation.\n   */\n  readonly tools: ReadonlyArray<Tool.Any>\n\n  /**\n   * The format which the response should be provided in.\n   *\n   * If `\"text\"` is specified, the large language model response will be\n   * returned as text.\n   *\n   * If `\"json\"` is specified, the large language model respose will be provided\n   * as an JSON object that conforms to the shape of the specified schema.\n   *\n   * Defaults to `{ type: \"text\" }`.\n   */\n  readonly responseFormat:\n    | {\n      readonly type: \"text\"\n    }\n    | {\n      readonly type: \"json\"\n      readonly objectName: string\n      readonly schema: Schema.Schema.Any\n    }\n\n  /**\n   * The tool choice mode for the language model.\n   * - `auto` (default): The model can decide whether or not to call tools, as\n   *   well as which tools to call.\n   * - `required`: The model **must** call a tool but can decide which tool will\n   *   be called.\n   * - `none`: The model **must not** call a tool.\n   * - `{ tool: <tool_name> }`: The model must call the specified tool.\n   * - `{ mode?: \"auto\" (default) | \"required\", \"oneOf\": [<tool-names>] }`: The\n   *   model is restricted to the subset of tools specified by `oneOf`. When\n   *   `mode` is `\"auto\"` or omitted, the model can decide whether or not a tool\n   *   from the allowed subset of tools can be called. When `mode` is\n   *   `\"required\"`, the model **must** call one tool from the allowed subset of\n   *   tools.\n   */\n  readonly toolChoice: ToolChoice<any>\n\n  /**\n   * The span to use to trace interactions with the large language model.\n   */\n  readonly span: Span\n}\n\n/**\n * Parameters required to construct a LanguageModel service.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ConstructorParams {\n  /**\n   * A method which requests text generation from the large language model\n   * provider.\n   *\n   * The final result is returned when the large language model provider\n   * finishes text generation.\n   */\n  readonly generateText: (options: ProviderOptions) => Effect.Effect<\n    Array<Response.PartEncoded>,\n    AiError.AiError,\n    IdGenerator\n  >\n\n  /**\n   * A method which requests text generation from the large language model\n   * provider.\n   *\n   * Intermediate results are streamed from the large language model provider.\n   */\n  readonly streamText: (options: ProviderOptions) => Stream.Stream<\n    Response.StreamPartEncoded,\n    AiError.AiError,\n    IdGenerator\n  >\n}\n\n/**\n * Creates a LanguageModel service from provider-specific implementations.\n *\n * This constructor takes provider-specific implementations for text generation\n * and streaming text generation and returns a LanguageModel service.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const make: (params: ConstructorParams) => Effect.Effect<Service> = Effect.fnUntraced(\n  function*(params) {\n    const parentSpanTransformer = yield* Effect.serviceOption(CurrentSpanTransformer)\n    const getSpanTransformer = Effect.serviceOption(CurrentSpanTransformer).pipe(\n      Effect.map(Option.orElse(() => parentSpanTransformer))\n    )\n\n    const idGenerator = yield* Effect.serviceOption(IdGenerator).pipe(\n      Effect.map(Option.getOrElse(() => defaultIdGenerator))\n    )\n\n    const generateText = <\n      Options extends NoExcessProperties<GenerateTextOptions<any>, Options>,\n      Tools extends Record<string, Tool.Any> = {}\n    >(options: Options & GenerateTextOptions<Tools>): Effect.Effect<\n      GenerateTextResponse<Tools>,\n      ExtractError<Options>,\n      ExtractContext<Options>\n    > =>\n      Effect.useSpan(\n        \"LanguageModel.generateText\",\n        {\n          captureStackTrace: false,\n          attributes: {\n            concurrency: options.concurrency,\n            toolChoice: options.toolChoice\n          }\n        },\n        Effect.fnUntraced(\n          function*(span) {\n            const spanTransformer = yield* getSpanTransformer\n\n            const providerOptions: Mutable<ProviderOptions> = {\n              prompt: Prompt.make(options.prompt),\n              tools: [],\n              toolChoice: \"none\",\n              responseFormat: { type: \"text\" },\n              span\n            }\n            const content = yield* generateContent(options, providerOptions)\n\n            applySpanTransformer(spanTransformer, content as any, providerOptions)\n\n            return new GenerateTextResponse(content)\n          },\n          Effect.catchTag(\"ParseError\", (error) =>\n            AiError.MalformedOutput.fromParseError({\n              module: \"LanguageModel\",\n              method: \"generateText\",\n              error\n            })),\n          (effect, span) => Effect.withParentSpan(effect, span),\n          Effect.provideService(IdGenerator, idGenerator)\n        )\n      ) as any\n\n    const generateObject = <\n      A,\n      I extends Record<string, unknown>,\n      R,\n      Options extends NoExcessProperties<GenerateObjectOptions<any, A, I, R>, Options>,\n      Tools extends Record<string, Tool.Any> = {}\n    >(options: Options & GenerateObjectOptions<Tools, A, I, R>): Effect.Effect<\n      GenerateObjectResponse<Tools, A>,\n      ExtractError<Options>,\n      R | ExtractContext<Options>\n    > => {\n      const schema: Schema.Schema<A, I, R> = options.schema\n      const objectName = getObjectName(options.objectName, schema)\n      return Effect.useSpan(\n        \"LanguageModel.generateObject\",\n        {\n          captureStackTrace: false,\n          attributes: {\n            objectName,\n            concurrency: options.concurrency,\n            toolChoice: options.toolChoice\n          }\n        },\n        Effect.fnUntraced(\n          function*(span) {\n            const spanTransformer = yield* getSpanTransformer\n\n            const providerOptions: Mutable<ProviderOptions> = {\n              prompt: Prompt.make(options.prompt),\n              tools: [],\n              toolChoice: \"none\",\n              responseFormat: { type: \"json\", objectName, schema },\n              span\n            }\n\n            const content = yield* generateContent(options, providerOptions)\n\n            applySpanTransformer(spanTransformer, content as any, providerOptions)\n\n            const value = yield* resolveStructuredOutput(content as any, schema)\n\n            return new GenerateObjectResponse(value, content)\n          },\n          Effect.catchTag(\"ParseError\", (error) =>\n            AiError.MalformedOutput.fromParseError({\n              module: \"LanguageModel\",\n              method: \"generateText\",\n              error\n            })),\n          (effect, span) => Effect.withParentSpan(effect, span),\n          Effect.provideService(IdGenerator, idGenerator)\n        )\n      ) as any\n    }\n\n    const streamText: <\n      Options extends NoExcessProperties<GenerateTextOptions<any>, Options>,\n      Tools extends Record<string, Tool.Any> = {}\n    >(options: Options & GenerateTextOptions<Tools>) => Stream.Stream<\n      Response.StreamPart<Tools>,\n      ExtractError<Options>,\n      ExtractContext<Options>\n    > = Effect.fnUntraced(\n      function*<\n        Tools extends Record<string, Tool.Any>,\n        Options extends NoExcessProperties<GenerateTextOptions<Tools>, Options>\n      >(options: Options & GenerateTextOptions<Tools>) {\n        const span = yield* Effect.makeSpanScoped(\"LanguageModel.streamText\", {\n          captureStackTrace: false,\n          attributes: { concurrency: options.concurrency, toolChoice: options.toolChoice }\n        })\n\n        const providerOptions: Mutable<ProviderOptions> = {\n          prompt: Prompt.make(options.prompt),\n          tools: [],\n          toolChoice: \"none\",\n          responseFormat: { type: \"text\" },\n          span\n        }\n\n        // Resolve the content stream for the request\n        const stream = yield* streamContent(options, providerOptions)\n\n        // Return the stream immediately if there is no span transformer\n        const spanTransformer = yield* getSpanTransformer\n        if (Option.isNone(spanTransformer)) {\n          return stream\n        }\n\n        // Otherwise aggregate generated content and apply the span transformer\n        // when the stream is finished\n        let content: Array<Response.StreamPart<Tools>> = []\n        return stream.pipe(\n          Stream.mapChunks((chunk) => {\n            content = [...content, ...chunk]\n            return chunk\n          }),\n          Stream.ensuring(Effect.sync(() => {\n            spanTransformer.value({ ...providerOptions, response: content as any })\n          }))\n        )\n      },\n      Stream.unwrapScoped,\n      Stream.mapError((error) =>\n        ParseResult.isParseError(error)\n          ? AiError.MalformedOutput.fromParseError({\n            module: \"LanguageModel\",\n            method: \"streamText\",\n            error\n          })\n          : error\n      ),\n      Stream.provideService(IdGenerator, idGenerator)\n    ) as any\n\n    const generateContent: <\n      Options extends NoExcessProperties<GenerateTextOptions<any>, Options>,\n      Tools extends Record<string, Tool.Any> = {}\n    >(options: Options & GenerateTextOptions<Tools>, providerOptions: Mutable<ProviderOptions>) => Effect.Effect<\n      Array<Response.Part<Tools>>,\n      AiError.AiError | ParseResult.ParseError,\n      IdGenerator\n    > = Effect.fnUntraced(\n      function*<\n        Tools extends Record<string, Tool.Any>,\n        Options extends NoExcessProperties<GenerateTextOptions<Tools>, Options>\n      >(options: Options & GenerateTextOptions<Tools>, providerOptions: Mutable<ProviderOptions>) {\n        const toolChoice = options.toolChoice ?? \"auto\"\n\n        // If there is no toolkit, the generated content can be returned immediately\n        if (Predicate.isUndefined(options.toolkit)) {\n          const ResponseSchema = Schema.mutable(Schema.Array(Response.Part(Toolkit.empty)))\n          const rawContent = yield* params.generateText(providerOptions)\n          const content = yield* Schema.decodeUnknown(ResponseSchema)(rawContent)\n          return content as Array<Response.Part<Tools>>\n        }\n\n        // If there is a toolkit resolve and apply it to the provider options\n        const toolkit = yield* resolveToolkit<Tools, any, any>(options.toolkit)\n\n        // If the resolved toolkit is empty, return the generated content immediately\n        if (Object.values(toolkit.tools).length === 0) {\n          const ResponseSchema = Schema.mutable(Schema.Array(Response.Part(Toolkit.empty)))\n          const rawContent = yield* params.generateText(providerOptions)\n          const content = yield* Schema.decodeUnknown(ResponseSchema)(rawContent)\n          return content as Array<Response.Part<Tools>>\n        }\n\n        const tools = typeof toolChoice === \"object\" && \"oneOf\" in toolChoice\n          ? Object.values(toolkit.tools).filter((tool) => toolChoice.oneOf.includes(tool.name))\n          : Object.values(toolkit.tools)\n        providerOptions.tools = tools\n        providerOptions.toolChoice = toolChoice\n\n        // Construct the response schema with the tools from the toolkit\n        const ResponseSchema = Schema.mutable(Schema.Array(Response.Part(toolkit)))\n\n        // If tool call resolution is disabled, return the response without\n        // resolving the tool calls that were generated\n        if (options.disableToolCallResolution === true) {\n          const rawContent = yield* params.generateText(providerOptions)\n          const content = yield* Schema.decodeUnknown(ResponseSchema)(rawContent)\n          return content as Array<Response.Part<Tools>>\n        }\n\n        const rawContent = yield* params.generateText(providerOptions)\n\n        // Resolve the generated tool calls\n        const toolResults = yield* resolveToolCalls(rawContent, toolkit, options.concurrency)\n        const content = yield* Schema.decodeUnknown(ResponseSchema)(rawContent)\n\n        // Return the content merged with the tool call results\n        return [...content, ...toolResults] as Array<Response.Part<Tools>>\n      }\n    )\n\n    const streamContent: <\n      Options extends NoExcessProperties<GenerateTextOptions<any>, Options>,\n      Tools extends Record<string, Tool.Any> = {}\n    >(options: Options & GenerateTextOptions<Tools>, providerOptions: Mutable<ProviderOptions>) => Effect.Effect<\n      Stream.Stream<Response.StreamPart<Tools>, AiError.AiError | ParseResult.ParseError, IdGenerator>,\n      Options extends { readonly toolkit: Effect.Effect<Toolkit.WithHandler<Tools>, infer _E, infer _R> } ? _E : never,\n      | (Options extends { readonly toolkit: Effect.Effect<Toolkit.WithHandler<Tools>, infer _E, infer _R> } ? _R\n        : never)\n      | Scope.Scope\n    > = Effect.fnUntraced(\n      function*<\n        Tools extends Record<string, Tool.Any>,\n        Options extends NoExcessProperties<GenerateTextOptions<Tools>, Options>\n      >(options: Options & GenerateTextOptions<Tools>, providerOptions: Mutable<ProviderOptions>) {\n        const toolChoice = options.toolChoice ?? \"auto\"\n\n        // If there is no toolkit, return immediately\n        if (Predicate.isUndefined(options.toolkit)) {\n          const schema = Schema.ChunkFromSelf(Response.StreamPart(Toolkit.empty))\n          const decode = Schema.decode(schema)\n          return params.streamText(providerOptions).pipe(\n            Stream.mapChunksEffect(decode)\n          ) as Stream.Stream<Response.StreamPart<Tools>, AiError.AiError | ParseResult.ParseError, IdGenerator>\n        }\n\n        // If there is a toolkit resolve and apply it to the provider options\n        const toolkit = Effect.isEffect(options.toolkit) ? yield* options.toolkit : options.toolkit\n\n        // If the toolkit is empty, return immediately\n        if (Object.values(toolkit.tools).length === 0) {\n          const schema = Schema.ChunkFromSelf(Response.StreamPart(Toolkit.empty))\n          const decode = Schema.decode(schema)\n          return params.streamText(providerOptions).pipe(\n            Stream.mapChunksEffect(decode)\n          ) as Stream.Stream<Response.StreamPart<Tools>, AiError.AiError | ParseResult.ParseError, IdGenerator>\n        }\n\n        const tools = typeof toolChoice === \"object\" && \"oneOf\" in toolChoice\n          ? Object.values(toolkit.tools).filter((tool) => toolChoice.oneOf.includes(tool.name))\n          : Object.values(toolkit.tools)\n        providerOptions.tools = tools\n        providerOptions.toolChoice = toolChoice\n\n        // If tool call resolution is disabled, return the response without\n        // resolving the tool calls that were generated\n        if (options.disableToolCallResolution === true) {\n          const schema = Schema.ChunkFromSelf(Response.StreamPart(toolkit))\n          const decode = Schema.decode(schema)\n          return params.streamText(providerOptions).pipe(\n            Stream.mapChunksEffect(decode)\n          ) as Stream.Stream<Response.StreamPart<Tools>, AiError.AiError | ParseResult.ParseError, IdGenerator>\n        }\n\n        const mailbox = yield* Mailbox.make<Response.StreamPart<Tools>, AiError.AiError | ParseResult.ParseError>()\n        const ResponseSchema = Schema.Array(Response.StreamPart(toolkit))\n        const decode = Schema.decode(ResponseSchema)\n        yield* params.streamText(providerOptions).pipe(\n          Stream.runForEachChunk(Effect.fnUntraced(function*(chunk) {\n            const rawContent = Chunk.toArray(chunk)\n            const content = yield* decode(rawContent)\n            yield* mailbox.offerAll(content)\n            const toolResults = yield* resolveToolCalls(rawContent, toolkit, options.concurrency)\n            yield* mailbox.offerAll(toolResults as any)\n          })),\n          Mailbox.into(mailbox),\n          Effect.forkScoped\n        )\n        return Mailbox.toStream(mailbox)\n      }\n    )\n\n    return {\n      generateText,\n      generateObject,\n      streamText\n    } as const\n  }\n)\n\n// =============================================================================\n// Accessors\n// =============================================================================\n\n/**\n * Generate text using a language model.\n *\n * @example\n * ```ts\n * import { LanguageModel } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   const response = yield* LanguageModel.generateText({\n *     prompt: \"Write a haiku about programming\",\n *     toolChoice: \"none\"\n *   })\n *\n *   console.log(response.text)\n *   console.log(response.usage.totalTokens)\n *\n *   return response\n * })\n * ```\n *\n * @since 1.0.0\n * @category Functions\n */\nexport const generateText: <\n  Options extends NoExcessProperties<GenerateTextOptions<any>, Options>,\n  Tools extends Record<string, Tool.Any> = {}\n>(options: Options & GenerateTextOptions<Tools>) => Effect.Effect<\n  GenerateTextResponse<Tools>,\n  ExtractError<Options>,\n  LanguageModel | ExtractContext<Options>\n> = Effect.serviceFunctionEffect(LanguageModel, (model) => model.generateText)\n\n/**\n * Generate a structured object from a schema using a language model.\n *\n * @example\n * ```ts\n * import { LanguageModel } from \"@effect/ai\"\n * import { Effect, Schema } from \"effect\"\n *\n * const EventSchema = Schema.Struct({\n *   title: Schema.String,\n *   date: Schema.String,\n *   location: Schema.String\n * })\n *\n * const program = Effect.gen(function* () {\n *   const response = yield* LanguageModel.generateObject({\n *     prompt: \"Extract event info: Tech Conference on March 15th in San Francisco\",\n *     schema: EventSchema,\n *     objectName: \"event\"\n *   })\n *\n *   console.log(response.value)\n *   // { title: \"Tech Conference\", date: \"March 15th\", location: \"San Francisco\" }\n *\n *   return response.value\n * })\n * ```\n *\n * @since 1.0.0\n * @category Functions\n */\nexport const generateObject: <\n  A,\n  I extends Record<string, unknown>,\n  R,\n  Options extends NoExcessProperties<GenerateObjectOptions<any, A, I, R>, Options>,\n  Tools extends Record<string, Tool.Any> = {}\n>(options: Options & GenerateObjectOptions<Tools, A, I, R>) => Effect.Effect<\n  GenerateObjectResponse<Tools, A>,\n  ExtractError<Options>,\n  LanguageModel | R | ExtractContext<Options>\n> = Effect.serviceFunctionEffect(LanguageModel, (model) => model.generateObject)\n\n/**\n * Generate text using a language model with streaming output.\n *\n * Returns a stream of response parts that are emitted as soon as they are\n * available from the model, enabling real-time text generation experiences.\n *\n * @example\n * ```ts\n * import { LanguageModel } from \"@effect/ai\"\n * import { Effect, Stream, Console } from \"effect\"\n *\n * const program = LanguageModel.streamText({\n *   prompt: \"Write a story about a space explorer\"\n * }).pipe(Stream.runForEach((part) => {\n *   if (part.type === \"text-delta\") {\n *     return Console.log(part.delta)\n *   }\n *   return Effect.void\n * }))\n * ```\n *\n * @since 1.0.0\n * @category Functions\n */\nexport const streamText = <\n  Options extends NoExcessProperties<GenerateTextOptions<any>, Options>,\n  Tools extends Record<string, Tool.Any> = {}\n>(options: Options & GenerateTextOptions<Tools>): Stream.Stream<\n  Response.StreamPart<Tools>,\n  ExtractError<Options>,\n  LanguageModel | ExtractContext<Options>\n> => Stream.unwrap(LanguageModel.pipe(Effect.map((model) => model.streamText(options))))\n\n// =============================================================================\n// Tool Call Resolution\n// =============================================================================\n\nconst resolveToolCalls = <Tools extends Record<string, Tool.Any>>(\n  content: ReadonlyArray<Response.AllPartsEncoded>,\n  toolkit: Toolkit.WithHandler<Tools>,\n  concurrency: Concurrency | undefined\n): Effect.Effect<\n  ReadonlyArray<\n    Response.ToolResultPart<\n      Tool.Name<Tools[keyof Tools]>,\n      Tool.Success<Tools[keyof Tools]>,\n      Tool.Failure<Tools[keyof Tools]>\n    >\n  >,\n  Tool.HandlerError<Tools[keyof Tools]>,\n  Tool.Requirements<Tools[keyof Tools]>\n> => {\n  const toolNames: Array<string> = []\n  const toolCalls: Array<Response.ToolCallPartEncoded> = []\n\n  for (const part of content) {\n    if (part.type === \"tool-call\") {\n      toolNames.push(part.name)\n      if (part.providerExecuted === true) {\n        continue\n      }\n      toolCalls.push(part)\n    }\n  }\n\n  return Effect.forEach(toolCalls, (toolCall) => {\n    return toolkit.handle(toolCall.name, toolCall.params as any).pipe(\n      Effect.map(({ encodedResult, isFailure, result }) =>\n        Response.makePart(\"tool-result\", {\n          id: toolCall.id,\n          name: toolCall.name,\n          result,\n          encodedResult,\n          isFailure,\n          providerExecuted: false,\n          ...(toolCall.providerName !== undefined\n            ? { providerName: toolCall.providerName }\n            : {})\n        })\n      )\n    )\n  }, { concurrency })\n}\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nconst resolveToolkit = <Tools extends Record<string, Tool.Any>, E, R>(\n  toolkit: Toolkit.WithHandler<Tools> | Effect.Effect<Toolkit.WithHandler<Tools>, E, R>\n): Effect.Effect<Toolkit.WithHandler<Tools>, E, R> => Effect.isEffect(toolkit) ? toolkit : Effect.succeed(toolkit)\n\nconst getObjectName = <A, I extends Record<string, unknown>, R>(\n  objectName: string | undefined,\n  schema: Schema.Schema<A, I, R>\n): string =>\n  Predicate.isNotUndefined(objectName)\n    ? objectName\n    : \"_tag\" in schema\n    ? schema._tag as string\n    : \"identifier\" in schema\n    ? schema.identifier as string\n    : \"generateObject\"\n\nconst resolveStructuredOutput = Effect.fnUntraced(\n  function*<A, I, R>(response: ReadonlyArray<Response.AllParts<any>>, ResultSchema: Schema.Schema<A, I, R>) {\n    const text: Array<string> = []\n    for (const part of response) {\n      if (part.type === \"text\") {\n        text.push(part.text)\n      }\n    }\n\n    if (text.length === 0) {\n      return yield* new AiError.MalformedOutput({\n        module: \"LanguageModel\",\n        method: \"generateObject\",\n        description: \"No object was generated by the large language model\"\n      })\n    }\n\n    const decode = Schema.decode(Schema.parseJson(ResultSchema))\n    return yield* Effect.mapError(decode(text.join(\"\")), (cause) =>\n      new AiError.MalformedOutput({\n        module: \"LanguageModel\",\n        method: \"generateObject\",\n        description: \"Generated object failed to conform to provided schema\",\n        cause\n      }))\n  }\n)\n\nconst applySpanTransformer = (\n  transformer: Option.Option<SpanTransformer>,\n  response: ReadonlyArray<Response.AllParts<any>>,\n  options: ProviderOptions\n): void => {\n  if (Option.isSome(transformer)) {\n    transformer.value({ ...options, response: response as any })\n  }\n}\n"
  },
  {
    "path": "packages/ai/ai/src/McpSchema.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Rpc from \"@effect/rpc/Rpc\"\nimport type * as RpcClient from \"@effect/rpc/RpcClient\"\nimport type { RpcClientError } from \"@effect/rpc/RpcClientError\"\nimport * as RpcGroup from \"@effect/rpc/RpcGroup\"\nimport * as RpcMiddleware from \"@effect/rpc/RpcMiddleware\"\nimport * as Context from \"effect/Context\"\nimport type * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\n\n// =============================================================================\n// Common\n// =============================================================================\n\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n *\n * @since 1.0.0\n * @category Common\n */\nexport const RequestId: Schema.Union<[\n  typeof Schema.String,\n  typeof Schema.Number\n]> = Schema.Union(Schema.String, Schema.Number)\n\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n *\n * @since 1.0.0\n * @category Common\n */\nexport type RequestId = typeof RequestId.Type\n\n/**\n * A progress token, used to associate progress notifications with the original\n * request.\n *\n * @since 1.0.0\n * @category Common\n */\nexport const ProgressToken: Schema.Union<[\n  typeof Schema.String,\n  typeof Schema.Number\n]> = Schema.Union(Schema.String, Schema.Number)\n\n/**\n * A progress token, used to associate progress notifications with the original\n * request.\n *\n * @since 1.0.0\n * @category Common\n */\nexport type ProgressToken = typeof ProgressToken.Type\n\n/**\n * @since 1.0.0\n * @category Common\n */\nexport class RequestMeta extends Schema.Struct({\n  _meta: Schema.optional(Schema.Struct({\n    /**\n     * If specified, the caller is requesting out-of-band progress notifications\n     * for this request (as represented by notifications/progress). The value of\n     * this parameter is an opaque token that will be attached to any subsequent\n     * notifications. The receiver is not obligated to provide these\n     * notifications.\n     */\n    progressToken: Schema.optional(ProgressToken)\n  }))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Common\n */\nexport class ResultMeta extends Schema.Struct({\n  /**\n   * This result property is reserved by the protocol to allow clients and\n   * servers to attach additional metadata to their responses.\n   */\n  _meta: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.Unknown }))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Common\n */\nexport class NotificationMeta extends Schema.Struct({\n  /**\n   * This parameter name is reserved by MCP to allow clients and servers to\n   * attach additional metadata to their notifications.\n   */\n  _meta: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.Unknown }))\n}) {}\n\n/**\n * An opaque token used to represent a cursor for pagination.\n *\n * @since 1.0.0\n * @category Common\n */\nexport const Cursor: typeof Schema.String = Schema.String\n\n/**\n * @since 1.0.0\n * @category Common\n */\nexport type Cursor = typeof Cursor.Type\n\n/**\n * @since 1.0.0\n * @category Common\n */\nexport class PaginatedRequestMeta extends Schema.Struct({\n  ...RequestMeta.fields,\n  /**\n   * An opaque token representing the current pagination position.\n   * If provided, the server should return results starting after this cursor.\n   */\n  cursor: Schema.optional(Cursor)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Common\n */\nexport class PaginatedResultMeta extends Schema.Struct({\n  ...ResultMeta.fields,\n  /**\n   * An opaque token representing the pagination position after the last returned result.\n   * If present, there may be more results available.\n   */\n  nextCursor: Schema.optional(Cursor)\n}) {}\n\n/**\n * The sender or recipient of messages and data in a conversation.\n * @since 1.0.0\n * @category Common\n */\nexport const Role: Schema.Literal<[\"user\", \"assistant\"]> = Schema.Literal(\"user\", \"assistant\")\n\n/**\n * @since 1.0.0\n * @category Common\n */\nexport type Role = typeof Role.Type\n\n/**\n * Optional annotations for the client. The client can use annotations to\n * inform how objects are used or displayed\n *\n * @since 1.0.0\n * @category Common\n */\nexport class Annotations extends Schema.Struct({\n  /**\n   * Describes who the intended customer of this object or data is.\n   *\n   * It can include multiple entries to indicate content useful for multiple\n   * audiences (e.g., `[\"user\", \"assistant\"]`).\n   */\n  audience: Schema.optional(Schema.Array(Role)),\n  /**\n   * Describes how important this data is for operating the server.\n   *\n   * A value of 1 means \"most important,\" and indicates that the data is\n   * effectively required, while 0 means \"least important,\" and indicates that\n   * the data is entirely optional.\n   */\n  priority: Schema.optional(Schema.Number.pipe(Schema.between(0, 1)))\n}) {}\n\n/**\n * Describes the name and version of an MCP implementation.\n *\n * @since 1.0.0\n * @category Common\n */\nexport class Implementation extends Schema.Struct({\n  name: Schema.String,\n  title: Schema.optional(Schema.String),\n  version: Schema.String\n}) {}\n\n/**\n * Capabilities a client may support. Known capabilities are defined here, in\n * this schema, but this is not a closed set: any client can define its own,\n * additional capabilities.\n *\n * @since 1.0.0\n * @category Common\n */\nexport class ClientCapabilities extends Schema.Class<ClientCapabilities>(\n  \"@effect/ai/McpSchema/ClientCapabilities\"\n)({\n  /**\n   * Experimental, non-standard capabilities that the client supports.\n   */\n  experimental: Schema.optional(Schema.Record({\n    key: Schema.String,\n    value: Schema.Struct({})\n  })),\n  /**\n   * Present if the client supports listing roots.\n   */\n  roots: Schema.optional(Schema.Struct({\n    /**\n     * Whether the client supports notifications for changes to the roots list.\n     */\n    listChanged: Schema.optional(Schema.Boolean)\n  })),\n  /**\n   * Present if the client supports sampling from an LLM.\n   */\n  sampling: Schema.optional(Schema.Struct({})),\n  /**\n   * Present if the client supports elicitation from the server.\n   */\n  elicitation: Schema.optional(Schema.Struct({}))\n}) {}\n\n/**\n * Capabilities that a server may support. Known capabilities are defined\n * here, in this schema, but this is not a closed set: any server can define\n * its own, additional capabilities.\n *\n * @since 1.0.0\n * @category Common\n */\nexport class ServerCapabilities extends Schema.Struct({\n  /**\n   * Experimental, non-standard capabilities that the server supports.\n   */\n  experimental: Schema.optional(Schema.Record({\n    key: Schema.String,\n    value: Schema.Struct({})\n  })),\n  /**\n   * Present if the server supports sending log messages to the client.\n   */\n  logging: Schema.optional(Schema.Struct({})),\n  /**\n   * Present if the server supports argument autocompletion suggestions.\n   */\n  completions: Schema.optional(Schema.Struct({})),\n  /**\n   * Present if the server offers any prompt templates.\n   */\n  prompts: Schema.optional(Schema.Struct({\n    /**\n     * Whether this server supports notifications for changes to the prompt list.\n     */\n    listChanged: Schema.optional(Schema.Boolean)\n  })),\n  /**\n   * Present if the server offers any resources to read.\n   */\n  resources: Schema.optional(Schema.Struct({\n    /**\n     * Whether this server supports subscribing to resource updates.\n     */\n    subscribe: Schema.optional(Schema.Boolean),\n    /**\n     * Whether this server supports notifications for changes to the resource list.\n     */\n    listChanged: Schema.optional(Schema.Boolean)\n  })),\n  /**\n   * Present if the server offers any tools to call.\n   */\n  tools: Schema.optional(Schema.Struct({\n    /**\n     * Whether this server supports notifications for changes to the tool list.\n     */\n    listChanged: Schema.optional(Schema.Boolean)\n  }))\n}) {}\n\n// =============================================================================\n// Errors\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport class McpError extends Schema.Class<McpError>(\n  \"@effect/ai/McpSchema/McpError\"\n)({\n  /**\n   * The error type that occurred.\n   */\n  code: Schema.Number,\n  /**\n   * A short description of the error. The message SHOULD be limited to a\n   * concise single sentence.\n   */\n  message: Schema.String,\n  /**\n   * Additional information about the error. The value of this member is\n   * defined by the sender (e.g. detailed error information, nested errors etc.).\n   */\n  data: Schema.optional(Schema.Unknown)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport const INVALID_REQUEST_ERROR_CODE = -32600 as const\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport const METHOD_NOT_FOUND_ERROR_CODE = -32601 as const\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport const INVALID_PARAMS_ERROR_CODE = -32602 as const\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport const INTERNAL_ERROR_CODE = -32603 as const\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport const PARSE_ERROR_CODE = -32700 as const\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport class ParseError extends Schema.TaggedError<ParseError>()(\"ParseError\", {\n  ...McpError.fields,\n  code: Schema.tag(PARSE_ERROR_CODE)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport class InvalidRequest extends Schema.TaggedError<InvalidRequest>()(\"InvalidRequest\", {\n  ...McpError.fields,\n  code: Schema.tag(INVALID_REQUEST_ERROR_CODE)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport class MethodNotFound extends Schema.TaggedError<MethodNotFound>()(\"MethodNotFound\", {\n  ...McpError.fields,\n  code: Schema.tag(METHOD_NOT_FOUND_ERROR_CODE)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport class InvalidParams extends Schema.TaggedError<InvalidParams>()(\"InvalidParams\", {\n  ...McpError.fields,\n  code: Schema.tag(INVALID_PARAMS_ERROR_CODE)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport class InternalError extends Schema.TaggedError<InternalError>()(\"InternalError\", {\n  ...McpError.fields,\n  code: Schema.tag(INTERNAL_ERROR_CODE)\n}) {\n  static readonly notImplemented = new InternalError({ message: \"Not implemented\" })\n}\n\n// =============================================================================\n// Ping\n// =============================================================================\n\n/**\n * A ping, issued by either the server or the client, to check that the other\n * party is still alive. The receiver must promptly respond, or else may be\n * disconnected.\n *\n * @since 1.0.0\n * @category Ping\n */\nexport class Ping extends Rpc.make(\"ping\", {\n  success: Schema.Struct({}),\n  error: McpError,\n  payload: Schema.UndefinedOr(RequestMeta)\n}) {}\n\n// =============================================================================\n// Initialization\n// =============================================================================\n\n/**\n * After receiving an initialize request from the client, the server sends this\n * response.\n *\n * @since 1.0.0\n * @category Initialization\n */\nexport class InitializeResult extends Schema.Class<InitializeResult>(\n  \"@effect/ai/McpSchema/InitializeResult\"\n)({\n  ...ResultMeta.fields,\n  /**\n   * The version of the Model Context Protocol that the server wants to use.\n   * This may not match the version that the client requested. If the client\n   * cannot support this version, it MUST disconnect.\n   */\n  protocolVersion: Schema.String,\n  capabilities: ServerCapabilities,\n  serverInfo: Implementation,\n  /**\n   * Instructions describing how to use the server and its features.\n   *\n   * This can be used by clients to improve the LLM's understanding of available\n   * tools, resources, etc. It can be thought of like a \"hint\" to the model.\n   * For example, this information MAY be added to the system prompt.\n   */\n  instructions: Schema.optional(Schema.String)\n}) {}\n\n/**\n * This request is sent from the client to the server when it first connects,\n * asking it to begin initialization.\n *\n * @since 1.0.0\n * @category Initialization\n */\nexport class Initialize extends Rpc.make(\"initialize\", {\n  success: InitializeResult,\n  error: McpError,\n  payload: {\n    ...RequestMeta.fields,\n    /**\n     * The latest version of the Model Context Protocol that the client\n     * supports. The client MAY decide to support older versions as well.\n     */\n    protocolVersion: Schema.String,\n    /**\n     * Capabilities a client may support. Known capabilities are defined here,\n     * in this schema, but this is not a closed set: any client can define its\n     * own, additional capabilities.\n     */\n    capabilities: ClientCapabilities,\n    /**\n     * Describes the name and version of an MCP implementation.\n     */\n    clientInfo: Implementation\n  }\n}) {}\n\n/**\n * This notification is sent from the client to the server after initialization\n * has finished.\n *\n * @since 1.0.0\n * @category Initialization\n */\nexport class InitializedNotification extends Rpc.make(\"notifications/initialized\", {\n  payload: Schema.UndefinedOr(NotificationMeta)\n}) {}\n\n// =============================================================================\n// Cancellation\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Cancellation\n */\nexport class CancelledNotification extends Rpc.make(\"notifications/cancelled\", {\n  payload: {\n    ...NotificationMeta.fields,\n    /**\n     * The ID of the request to cancel.\n     *\n     * This MUST correspond to the ID of a request previously issued in the\n     * same direction.\n     */\n    requestId: RequestId,\n    /**\n     * An optional string describing the reason for the cancellation. This MAY\n     * be logged or presented to the user.\n     */\n    reason: Schema.optional(Schema.String)\n  }\n}) {}\n\n// =============================================================================\n// Progress\n// =============================================================================\n\n/**\n * An out-of-band notification used to inform the receiver of a progress update\n * for a long-running request.\n *\n * @since 1.0.0\n * @category Progress\n */\nexport class ProgressNotification extends Rpc.make(\"notifications/progress\", {\n  payload: {\n    ...NotificationMeta.fields,\n    /**\n     * The progress token which was given in the initial request, used to\n     * associate this notification with the request that is proceeding.\n     */\n    progressToken: ProgressToken,\n    /**\n     * The progress thus far. This should increase every time progress is made,\n     * even if the total is unknown.\n     */\n    progress: Schema.optional(Schema.Number),\n    /**\n     * Total number of items to process (or total progress required), if known.\n     */\n    total: Schema.optional(Schema.Number),\n    /**\n     * An optional message describing the current progress.\n     */\n    message: Schema.optional(Schema.String)\n  }\n}) {}\n\n// =============================================================================\n// Resources\n// =============================================================================\n\n/**\n * A known resource that the server is capable of reading.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class Resource extends Schema.Class<Resource>(\n  \"@effect/ai/McpSchema/Resource\"\n)({\n  /**\n   * The URI of this resource.\n   */\n  uri: Schema.String,\n  /**\n   * A human-readable name for this resource.\n   *\n   * This can be used by clients to populate UI elements.\n   */\n  name: Schema.String,\n  title: Schema.optional(Schema.String),\n  /**\n   * A description of what this resource represents.\n   *\n   * This can be used by clients to improve the LLM's understanding of available\n   * resources. It can be thought of like a \"hint\" to the model.\n   */\n  description: Schema.optional(Schema.String),\n  /**\n   * The MIME type of this resource, if known.\n   */\n  mimeType: Schema.optional(Schema.String),\n  /**\n   * Optional annotations for the client.\n   */\n  annotations: Schema.optional(Annotations),\n  /**\n   * The size of the raw resource content, in bytes (i.e., before base64\n   * encoding or any tokenization), if known.\n   *\n   * This can be used by Hosts to display file sizes and estimate context\n   * window usage.\n   */\n  size: Schema.optional(Schema.Number)\n}) {}\n\n/**\n * A template description for resources available on the server.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class ResourceTemplate extends Schema.Class<ResourceTemplate>(\n  \"@effect/ai/McpSchema/ResourceTemplate\"\n)({\n  /**\n   * A URI template (according to RFC 6570) that can be used to construct\n   * resource URIs.\n   */\n  uriTemplate: Schema.String,\n  /**\n   * A human-readable name for the type of resource this template refers to.\n   *\n   * This can be used by clients to populate UI elements.\n   */\n  name: Schema.String,\n  title: Schema.optional(Schema.String),\n  /**\n   * A description of what this template is for.\n   *\n   * This can be used by clients to improve the LLM's understanding of available\n   * resources. It can be thought of like a \"hint\" to the model.\n   */\n  description: Schema.optional(Schema.String),\n\n  /**\n   * The MIME type for all resources that match this template. This should only\n   * be included if all resources matching this template have the same type.\n   */\n  mimeType: Schema.optional(Schema.String),\n\n  /**\n   * Optional annotations for the client.\n   */\n  annotations: Schema.optional(Annotations)\n}) {}\n\n/**\n * The contents of a specific resource or sub-resource.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class ResourceContents extends Schema.Struct({\n  /**\n   * The URI of this resource.\n   */\n  uri: Schema.String,\n  /**\n   * The MIME type of this resource, if known.\n   */\n  mimeType: Schema.optional(Schema.String)\n}) {}\n\n/**\n * The contents of a text resource, which can be represented as a string.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class TextResourceContents extends Schema.Struct({\n  ...ResourceContents.fields,\n  /**\n   * The text of the item. This must only be set if the item can actually be\n   * represented as text (not binary data).\n   */\n  text: Schema.String\n}) {}\n\n/**\n * The contents of a binary resource, which can be represented as an Uint8Array\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class BlobResourceContents extends Schema.Struct({\n  ...ResourceContents.fields,\n  /**\n   * The binary data of the item decoded from a base64-encoded string.\n   */\n  blob: Schema.Uint8ArrayFromBase64\n}) {}\n\n/**\n * The server's response to a resources/list request from the client.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class ListResourcesResult extends Schema.Class<ListResourcesResult>(\n  \"@effect/ai/McpSchema/ListResourcesResult\"\n)({\n  ...PaginatedResultMeta.fields,\n  resources: Schema.Array(Resource)\n}) {}\n\n/**\n * Sent from the client to request a list of resources the server has.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class ListResources extends Rpc.make(\"resources/list\", {\n  success: ListResourcesResult,\n  error: McpError,\n  payload: Schema.UndefinedOr(PaginatedRequestMeta)\n}) {}\n\n/**\n * The server's response to a resources/templates/list request from the client.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class ListResourceTemplatesResult extends Schema.Class<ListResourceTemplatesResult>(\n  \"@effect/ai/McpSchema/ListResourceTemplatesResult\"\n)({\n  ...PaginatedResultMeta.fields,\n  resourceTemplates: Schema.Array(ResourceTemplate)\n}) {}\n\n/**\n * Sent from the client to request a list of resource templates the server has.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class ListResourceTemplates extends Rpc.make(\"resources/templates/list\", {\n  success: ListResourceTemplatesResult,\n  error: McpError,\n  payload: Schema.UndefinedOr(PaginatedRequestMeta)\n}) {}\n\n/**\n * The server's response to a resources/read request from the client.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class ReadResourceResult extends Schema.Struct({\n  ...ResultMeta.fields,\n  contents: Schema.Array(Schema.Union(\n    TextResourceContents,\n    BlobResourceContents\n  ))\n}) {}\n\n/**\n * Sent from the client to the server, to read a specific resource URI.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class ReadResource extends Rpc.make(\"resources/read\", {\n  success: ReadResourceResult,\n  error: McpError,\n  payload: {\n    ...RequestMeta.fields,\n    /**\n     * The URI of the resource to read. The URI can use any protocol; it is up\n     * to the server how to interpret it.\n     */\n    uri: Schema.String\n  }\n}) {}\n\n/**\n * An optional notification from the server to the client, informing it that the\n * list of resources it can read from has changed. This may be issued by servers\n * without any previous subscription from the client.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class ResourceListChangedNotification extends Rpc.make(\"notifications/resources/list_changed\", {\n  payload: Schema.UndefinedOr(NotificationMeta)\n}) {}\n\n/**\n * Sent from the client to request resources/updated notifications from the\n * server whenever a particular resource changes.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class Subscribe extends Rpc.make(\"resources/subscribe\", {\n  error: McpError,\n  payload: {\n    ...RequestMeta.fields,\n    /**\n     * The URI of the resource to subscribe to. The URI can use any protocol;\n     * it is up to the server how to interpret it.\n     */\n    uri: Schema.String\n  }\n}) {}\n\n/**\n * Sent from the client to request cancellation of resources/updated\n * notifications from the server. This should follow a previous\n * resources/subscribe request.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport class Unsubscribe extends Rpc.make(\"resources/unsubscribe\", {\n  error: McpError,\n  payload: {\n    ...RequestMeta.fields,\n    /**\n     * The URI of the resource to subscribe to. The URI can use any protocol;\n     * it is up to the server how to interpret it.\n     */\n    uri: Schema.String\n  }\n}) {}\n\n/**\n * @since 1.0.0\n * @category Resources\n */\nexport class ResourceUpdatedNotification extends Rpc.make(\"notifications/resources/updated\", {\n  payload: {\n    ...NotificationMeta.fields,\n    /**\n     * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n     */\n    uri: Schema.String\n  }\n}) {}\n\n// =============================================================================\n// Prompts\n// =============================================================================\n\n/**\n * Describes an argument that a prompt can accept.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class PromptArgument extends Schema.Struct({\n  /**\n   * The name of the argument.\n   */\n  name: Schema.String,\n  title: Schema.optional(Schema.String),\n  /**\n   * A human-readable description of the argument.\n   */\n  description: Schema.optional(Schema.String),\n  /**\n   * Whether this argument must be provided.\n   */\n  required: Schema.optional(Schema.Boolean)\n}) {}\n\n/**\n * A prompt or prompt template that the server offers.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class Prompt extends Schema.Class<Prompt>(\n  \"@effect/ai/McpSchema/Prompt\"\n)({\n  /**\n   * The name of the prompt or prompt template.\n   */\n  name: Schema.String,\n  title: Schema.optional(Schema.String),\n  /**\n   * An optional description of what this prompt provides\n   */\n  description: Schema.optional(Schema.String),\n  /**\n   * A list of arguments to use for templating the prompt.\n   */\n  arguments: Schema.optional(Schema.Array(PromptArgument))\n}) {}\n\n/**\n * Text provided to or from an LLM.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class TextContent extends Schema.Struct({\n  type: Schema.tag(\"text\"),\n  /**\n   * The text content of the message.\n   */\n  text: Schema.String,\n  /**\n   * Optional annotations for the client.\n   */\n  annotations: Schema.optional(Annotations)\n}) {}\n\n/**\n * An image provided to or from an LLM.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class ImageContent extends Schema.Struct({\n  type: Schema.tag(\"image\"),\n  /**\n   * The image data.\n   */\n  data: Schema.Uint8ArrayFromBase64,\n  /**\n   * The MIME type of the image. Different providers may support different\n   * image types.\n   */\n  mimeType: Schema.String,\n  /**\n   * Optional annotations for the client.\n   */\n  annotations: Schema.optional(Annotations)\n}) {}\n\n/**\n * Audio provided to or from an LLM.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class AudioContent extends Schema.Struct({\n  type: Schema.tag(\"audio\"),\n  /**\n   * The audio data.\n   */\n  data: Schema.Uint8ArrayFromBase64,\n  /**\n   * The MIME type of the audio. Different providers may support different\n   * audio types.\n   */\n  mimeType: Schema.String,\n  /**\n   * Optional annotations for the client.\n   */\n  annotations: Schema.optional(Annotations)\n}) {}\n\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n *\n * It is up to the client how best to render embedded resources for the benefit\n * of the LLM and/or the user.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class EmbeddedResource extends Schema.Struct({\n  type: Schema.tag(\"resource\"),\n  resource: Schema.Union(TextResourceContents, BlobResourceContents),\n  /**\n   * Optional annotations for the client.\n   */\n  annotations: Schema.optional(Annotations)\n}) {}\n\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class ResourceLink extends Schema.Struct({\n  ...Resource.fields,\n  type: Schema.tag(\"resource_link\")\n}) {}\n\n/**\n * @since 1.0.0\n * @category Prompts\n */\nexport class ContentBlock extends Schema.Union(\n  TextContent,\n  ImageContent,\n  AudioContent,\n  EmbeddedResource,\n  ResourceLink\n) {}\n\n/**\n * Describes a message returned as part of a prompt.\n *\n * This is similar to `SamplingMessage`, but also supports the embedding of\n * resources from the MCP server.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class PromptMessage extends Schema.Struct({\n  role: Role,\n  content: ContentBlock\n}) {}\n\n/**\n * The server's response to a prompts/list request from the client.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class ListPromptsResult extends Schema.Class<ListPromptsResult>(\n  \"@effect/ai/McpSchema/ListPromptsResult\"\n)({\n  ...PaginatedResultMeta.fields,\n  prompts: Schema.Array(Prompt)\n}) {}\n\n/**\n * Sent from the client to request a list of prompts and prompt templates the\n * server has.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class ListPrompts extends Rpc.make(\"prompts/list\", {\n  success: ListPromptsResult,\n  error: McpError,\n  payload: Schema.UndefinedOr(PaginatedRequestMeta)\n}) {}\n\n/**\n * The server's response to a prompts/get request from the client.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class GetPromptResult extends Schema.Class<GetPromptResult>(\n  \"@effect/ai/McpSchema/GetPromptResult\"\n)({\n  ...ResultMeta.fields,\n  messages: Schema.Array(PromptMessage),\n  /**\n   * An optional description for the prompt.\n   */\n  description: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Used by the client to get a prompt provided by the server.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class GetPrompt extends Rpc.make(\"prompts/get\", {\n  success: GetPromptResult,\n  error: McpError,\n  payload: {\n    ...RequestMeta.fields,\n    /**\n     * The name of the prompt or prompt template.\n     */\n    name: Schema.String,\n    title: Schema.optional(Schema.String),\n    /**\n     * Arguments to use for templating the prompt.\n     */\n    arguments: Schema.optional(Schema.Record({\n      key: Schema.String,\n      value: Schema.String\n    }))\n  }\n}) {}\n\n/**\n * An optional notification from the server to the client, informing it that\n * the list of prompts it offers has changed. This may be issued by servers\n * without any previous subscription from the client.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport class PromptListChangedNotification extends Rpc.make(\"notifications/prompts/list_changed\", {\n  payload: Schema.UndefinedOr(NotificationMeta)\n}) {}\n\n// =============================================================================\n// Tools\n// =============================================================================\n\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**. They are not\n * guaranteed to provide a faithful description of tool behavior (including\n * descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport class ToolAnnotations extends Schema.Class<ToolAnnotations>(\n  \"@effect/ai/McpSchema/ToolAnnotations\"\n)({\n  /**\n   * A human-readable title for the tool.\n   */\n  title: Schema.optional(Schema.String),\n  /**\n   * If true, the tool does not modify its environment.\n   *\n   * Default: `false`\n   */\n  readOnlyHint: Schema.optionalWith(Schema.Boolean, { default: () => false }),\n  /**\n   * If true, the tool may perform destructive updates to its environment.\n   * If false, the tool performs only additive updates.\n   *\n   * (This property is meaningful only when `readOnlyHint == false`)\n   *\n   * Default: `true`\n   */\n  destructiveHint: Schema.optionalWith(Schema.Boolean, { default: () => true }),\n  /**\n   * If true, calling the tool repeatedly with the same arguments\n   * will have no additional effect on the its environment.\n   *\n   * (This property is meaningful only when `readOnlyHint == false`)\n   *\n   * Default: `false`\n   */\n  idempotentHint: Schema.optionalWith(Schema.Boolean, { default: () => false }),\n  /**\n   * If true, this tool may interact with an \"open world\" of external\n   * entities. If false, the tool's domain of interaction is closed.\n   * For example, the world of a web search tool is open, whereas that\n   * of a memory tool is not.\n   *\n   * Default: `true`\n   */\n  openWorldHint: Schema.optionalWith(Schema.Boolean, { default: () => true })\n}) {}\n\n/**\n * Definition for a tool the client can call.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport class Tool extends Schema.Class<Tool>(\n  \"@effect/ai/McpSchema/Tool\"\n)({\n  /**\n   * The name of the tool.\n   */\n  name: Schema.String,\n  title: Schema.optional(Schema.String),\n  /**\n   * A human-readable description of the tool.\n   *\n   * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a \"hint\" to the model.\n   */\n  description: Schema.optional(Schema.String),\n  /**\n   * A JSON Schema object defining the expected parameters for the tool.\n   */\n  inputSchema: Schema.Unknown,\n  /**\n   * Optional additional tool information.\n   */\n  annotations: Schema.optional(ToolAnnotations)\n}) {}\n\n/**\n * The server's response to a tools/list request from the client.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport class ListToolsResult extends Schema.Class<ListToolsResult>(\n  \"@effect/ai/McpSchema/ListToolsResult\"\n)({\n  ...PaginatedResultMeta.fields,\n  tools: Schema.Array(Tool)\n}) {}\n\n/**\n * Sent from the client to request a list of tools the server has.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport class ListTools extends Rpc.make(\"tools/list\", {\n  success: ListToolsResult,\n  error: McpError,\n  payload: Schema.UndefinedOr(PaginatedRequestMeta)\n}) {}\n\n/**\n * The server's response to a tool call.\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport class CallToolResult extends Schema.Class<CallToolResult>(\"@effect/ai/McpSchema/CallToolResult\")({\n  ...ResultMeta.fields,\n  content: Schema.Array(ContentBlock),\n  structuredContent: Schema.optional(Schema.Unknown),\n  /**\n   * Whether the tool call ended in an error.\n   *\n   * If not set, this is assumed to be false (the call was successful).\n   */\n  isError: Schema.optional(Schema.Boolean)\n}) {}\n\n/**\n * Used by the client to invoke a tool provided by the server.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport class CallTool extends Rpc.make(\"tools/call\", {\n  success: CallToolResult,\n  error: McpError,\n  payload: {\n    ...RequestMeta.fields,\n    name: Schema.String,\n    arguments: Schema.Record({\n      key: Schema.String,\n      value: Schema.Unknown\n    })\n  }\n}) {}\n\n/**\n * An optional notification from the server to the client, informing it that\n * the list of tools it offers has changed. This may be issued by servers\n * without any previous subscription from the client.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport class ToolListChangedNotification extends Rpc.make(\"notifications/tools/list_changed\", {\n  payload: Schema.UndefinedOr(NotificationMeta)\n}) {}\n\n// =============================================================================\n// Logging\n// =============================================================================\n\n/**\n * The severity of a log message.\n *\n * These map to syslog message severities, as specified in RFC-5424:\n * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1\n *\n * @since 1.0.0\n * @category Logging\n */\nexport const LoggingLevel: Schema.Literal<[\n  \"debug\",\n  \"info\",\n  \"notice\",\n  \"warning\",\n  \"error\",\n  \"critical\",\n  \"alert\",\n  \"emergency\"\n]> = Schema.Literal(\n  \"debug\",\n  \"info\",\n  \"notice\",\n  \"warning\",\n  \"error\",\n  \"critical\",\n  \"alert\",\n  \"emergency\"\n)\n\n/**\n * The severity of a log message.\n *\n * These map to syslog message severities, as specified in RFC-5424:\n * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1\n *\n * @since 1.0.0\n * @category Logging\n */\nexport type LoggingLevel = typeof LoggingLevel.Type\n\n/**\n * A request from the client to the server, to enable or adjust logging.\n *\n * @since 1.0.0\n * @category Logging\n */\nexport class SetLevel extends Rpc.make(\"logging/setLevel\", {\n  payload: {\n    ...RequestMeta.fields,\n    /**\n     * The level of logging that the client wants to receive from the server.\n     * The server should send all logs at this level and higher (i.e., more\n     * severe) to the client as notifications/message.\n     */\n    level: LoggingLevel\n  },\n  error: McpError\n}) {}\n\n/**\n * @since 1.0.0\n * @category Logging\n */\nexport class LoggingMessageNotification extends Rpc.make(\"notifications/message\", {\n  payload: Schema.Struct({\n    ...NotificationMeta.fields,\n    /**\n     * The severity of this log message.\n     */\n    level: LoggingLevel,\n    /**\n     * An optional name of the logger issuing this message.\n     */\n    logger: Schema.optional(Schema.String),\n    /**\n     * The data to be logged, such as a string message or an object. Any JSON\n     * serializable type is allowed here.\n     */\n    data: Schema.Unknown\n  })\n}) {}\n\n// =============================================================================\n// Sampling\n// =============================================================================\n\n/**\n * Describes a message issued to or received from an LLM API.\n *\n * @since 1.0.0\n * @category Sampling\n */\nexport class SamplingMessage extends Schema.Struct({\n  role: Role,\n  content: Schema.Union(TextContent, ImageContent, AudioContent)\n}) {}\n\n/**\n * Hints to use for model selection.\n *\n * Keys not declared here are currently left unspecified by the spec and are up\n * to the client to interpret.\n *\n * @since 1.0.0\n * @category Sampling\n */\nexport class ModelHint extends Schema.Struct({\n  /**\n   * A hint for a model name.\n   *\n   * The client SHOULD treat this as a substring of a model name; for example:\n   *  - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`\n   *  - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.\n   *  - `claude` should match any Claude model\n   *\n   * The client MAY also map the string to a different provider's model name or\n   * a different model family, as long as it fills a similar niche; for example:\n   *  - `gemini-1.5-flash` could match `claude-3-haiku-20240307`\n   */\n  name: Schema.optional(Schema.String)\n}) {}\n\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n *\n * Because LLMs can vary along multiple dimensions, choosing the \"best\" model is\n * rarely straightforward.  Different models excel in different areas—some are\n * faster but less capable, others are more capable but more expensive, and so\n * on. This interface allows servers to express their priorities across multiple\n * dimensions to help clients make an appropriate selection for their use case.\n *\n * These preferences are always advisory. The client MAY ignore them. It is also\n * up to the client to decide how to interpret these preferences and how to\n * balance them against other considerations.\n *\n * @since 1.0.0\n * @category Sampling\n */\nexport class ModelPreferences extends Schema.Class<ModelPreferences>(\n  \"@effect/ai/McpSchema/ModelPreferences\"\n)({\n  /**\n   * Optional hints to use for model selection.\n   *\n   * If multiple hints are specified, the client MUST evaluate them in order\n   * (such that the first match is taken).\n   *\n   * The client SHOULD prioritize these hints over the numeric priorities, but\n   * MAY still use the priorities to select from ambiguous matches.\n   */\n  hints: Schema.optional(Schema.Array(ModelHint)),\n  /**\n   * How much to prioritize cost when selecting a model. A value of 0 means cost\n   * is not important, while a value of 1 means cost is the most important\n   * factor.\n   */\n  costPriority: Schema.optional(Schema.Number.pipe(Schema.between(0, 1))),\n  /**\n   * How much to prioritize sampling speed (latency) when selecting a model. A\n   * value of 0 means speed is not important, while a value of 1 means speed is\n   * the most important factor.\n   */\n  speedPriority: Schema.optional(Schema.Number.pipe(Schema.between(0, 1))),\n  /**\n   * How much to prioritize intelligence and capabilities when selecting a\n   * model. A value of 0 means intelligence is not important, while a value of 1\n   * means intelligence is the most important factor.\n   */\n  intelligencePriority: Schema.optional(Schema.Number.pipe(Schema.between(0, 1)))\n}) {}\n\n/**\n * The client's response to a sampling/create_message request from the server.\n * The client should inform the user before returning the sampled message, to\n * allow them to inspect the response (human in the loop) and decide whether to\n * allow the server to see it.\n *\n * @since 1.0.0\n * @category Sampling\n */\nexport class CreateMessageResult extends Schema.Class<CreateMessageResult>(\n  \"@effect/ai/McpSchema/CreateMessageResult\"\n)({\n  /**\n   * The name of the model that generated the message.\n   */\n  model: Schema.String,\n  /**\n   * The reason why sampling stopped, if known.\n   */\n  stopReason: Schema.optional(Schema.String)\n}) {}\n\n/**\n * A request from the server to sample an LLM via the client. The client has\n * full discretion over which model to select. The client should also inform the\n * user before beginning sampling, to allow them to inspect the request (human\n * in the loop) and decide whether to approve it.\n *\n * @since 1.0.0\n * @category Sampling\n */\nexport class CreateMessage extends Rpc.make(\"sampling/createMessage\", {\n  success: CreateMessageResult,\n  error: McpError,\n  payload: {\n    messages: Schema.Array(SamplingMessage),\n    /**\n     * The server's preferences for which model to select. The client MAY ignore\n     * these preferences.\n     */\n    modelPreferences: Schema.optional(ModelPreferences),\n    /**\n     * An optional system prompt the server wants to use for sampling. The\n     * client MAY modify or omit this prompt.\n     */\n    systemPrompt: Schema.optional(Schema.String),\n    /**\n     * A request to include context from one or more MCP servers (including the\n     * caller), to be attached to the prompt. The client MAY ignore this request.\n     */\n    includeContext: Schema.optional(Schema.Literal(\"none\", \"thisServer\", \"allServers\")),\n    temperature: Schema.optional(Schema.Number),\n    /**\n     * The maximum number of tokens to sample, as requested by the server. The\n     * client MAY choose to sample fewer tokens than requested.\n     */\n    maxTokens: Schema.Number,\n    stopSequences: Schema.optional(Schema.Array(Schema.String)),\n    /**\n     * Optional metadata to pass through to the LLM provider. The format of\n     * this metadata is provider-specific.\n     */\n    metadata: Schema.Unknown\n  }\n}) {}\n\n// =============================================================================\n// Autocomplete\n// =============================================================================\n\n/**\n * A reference to a resource or resource template definition.\n *\n * @since 1.0.0\n * @category Autocomplete\n */\nexport class ResourceReference extends Schema.Struct({\n  type: Schema.tag(\"ref/resource\"),\n  /**\n   * The URI or URI template of the resource.\n   */\n  uri: Schema.String\n}) {}\n\n/**\n * Identifies a prompt.\n *\n * @since 1.0.0\n * @category Autocomplete\n */\nexport class PromptReference extends Schema.Struct({\n  type: Schema.tag(\"ref/prompt\"),\n  /**\n   * The name of the prompt or prompt template\n   */\n  name: Schema.String,\n  title: Schema.optional(Schema.String)\n}) {}\n\n/**\n * The server's response to a completion/complete request\n *\n * @since 1.0.0\n * @category Autocomplete\n */\nexport class CompleteResult extends Schema.Class<CompleteResult>(\"@effect/ai/McpSchema/CompleteResult\")({\n  completion: Schema.Struct({\n    /**\n     * An array of completion values. Must not exceed 100 items.\n     */\n    values: Schema.Array(Schema.String),\n    /**\n     * The total number of completion options available. This can exceed the\n     * number of values actually sent in the response.\n     */\n    total: Schema.optional(Schema.Number),\n    /**\n     * Indicates whether there are additional completion options beyond those\n     * provided in the current response, even if the exact total is unknown.\n     */\n    hasMore: Schema.optional(Schema.Boolean)\n  })\n}) {\n  /**\n   * @since 1.0.0\n   */\n  static readonly empty = CompleteResult.make({\n    completion: {\n      values: [],\n      total: 0,\n      hasMore: false\n    }\n  })\n}\n\n/**\n * A request from the client to the server, to ask for completion options.\n *\n * @since 1.0.0\n * @category Autocomplete\n */\nexport class Complete extends Rpc.make(\"completion/complete\", {\n  success: CompleteResult,\n  error: McpError,\n  payload: Schema.Struct({\n    ref: Schema.Union(PromptReference, ResourceReference),\n    /**\n     * The argument's information\n     */\n    argument: Schema.Struct({\n      /**\n       * The name of the argument\n       */\n      name: Schema.String,\n      /**\n       * The value of the argument to use for completion matching.\n       */\n      value: Schema.String\n    }),\n    /**\n     * Additional, optional context for completions\n     */\n    context: Schema.optionalWith(\n      Schema.Struct({\n        /**\n         * Previously-resolved variables in a URI template or prompt.\n         */\n        arguments: Schema.optionalWith(\n          Schema.Record({\n            key: Schema.String,\n            value: Schema.String\n          }),\n          { default: () => ({}) }\n        )\n      }),\n      { default: () => ({ arguments: {} }) }\n    )\n  })\n}) {}\n\n// =============================================================================\n// Roots\n// =============================================================================\n\n/**\n * Represents a root directory or file that the server can operate on.\n *\n * @since 1.0.0\n * @category Roots\n */\nexport class Root extends Schema.Class<Root>(\n  \"@effect/ai/McpSchema/Root\"\n)({\n  /**\n   * The URI identifying the root. This *must* start with file:// for now.\n   * This restriction may be relaxed in future versions of the protocol to allow\n   * other URI schemes.\n   */\n  uri: Schema.String,\n  /**\n   * An optional name for the root. This can be used to provide a human-readable\n   * identifier for the root, which may be useful for display purposes or for\n   * referencing the root in other parts of the application.\n   */\n  name: Schema.optional(Schema.String)\n}) {}\n\n/**\n * The client's response to a roots/list request from the server. This result\n * contains an array of Root objects, each representing a root directory or file\n * that the server can operate on.\n *\n * @since 1.0.0\n * @category Roots\n */\nexport class ListRootsResult extends Schema.Class<ListRootsResult>(\n  \"@effect/ai/McpSchema/ListRootsResult\"\n)({\n  roots: Schema.Array(Root)\n}) {}\n\n/**\n * Sent from the server to request a list of root URIs from the client. Roots\n * allow servers to ask for specific directories or files to operate on. A\n * common example for roots is providing a set of repositories or directories a\n * server should operate\n * on.\n *\n * This request is typically used when the server needs to understand the file\n * system structure or access specific locations that the client has permission\n * to read from.\n *\n * @since 1.0.0\n * @category Roots\n */\nexport class ListRoots extends Rpc.make(\"roots/list\", {\n  success: ListRootsResult,\n  error: McpError,\n  payload: Schema.UndefinedOr(RequestMeta)\n}) {}\n\n/**\n * A notification from the client to the server, informing it that the list of\n * roots has changed. This notification should be sent whenever the client adds,\n * removes, or modifies any root. The server should then request an updated list\n * of roots using the ListRootsRequest.\n *\n * @since 1.0.0\n * @category Roots\n */\nexport class RootsListChangedNotification extends Rpc.make(\"notifications/roots/list_changed\", {\n  payload: Schema.UndefinedOr(NotificationMeta)\n}) {}\n\n// =============================================================================\n// Elicitation\n// =============================================================================\n\n/**\n * The client's response to an elicitation request\n *\n * @since 1.0.0\n * @category Elicitation\n */\nexport class ElicitAcceptResult extends Schema.Class<ElicitAcceptResult>(\n  \"@effect/ai/McpSchema/ElicitAcceptResult\"\n)({\n  ...ResultMeta.fields,\n  /**\n   * The user action in response to the elicitation.\n   * - \"accept\": User submitted the form/confirmed the action\n   * - \"decline\": User explicitly declined the action\n   * - \"cancel\": User dismissed without making an explicit choice\n   */\n  action: Schema.Literal(\"accept\"),\n  /**\n   * The submitted form data, only present when action is \"accept\".\n   * Contains values matching the requested schema.\n   */\n  content: Schema.Unknown\n}) {}\n\n/**\n * The client's response to an elicitation request\n *\n * @since 1.0.0\n * @category Elicitation\n */\nexport class ElicitDeclineResult extends Schema.Class<ElicitDeclineResult>(\n  \"@effect/ai/McpSchema/ElicitDeclineResult\"\n)({\n  ...ResultMeta.fields,\n  /**\n   * The user action in response to the elicitation.\n   * - \"accept\": User submitted the form/confirmed the action\n   * - \"decline\": User explicitly declined the action\n   * - \"cancel\": User dismissed without making an explicit choice\n   */\n  action: Schema.Literal(\"cancel\", \"decline\")\n}) {}\n\n/**\n * The client's response to an elicitation request\n *\n * @since 1.0.0\n * @category Elicitation\n */\nexport const ElicitResult = Schema.Union(\n  ElicitAcceptResult,\n  ElicitDeclineResult\n)\n\n/**\n * @since 1.0.0\n * @category Elicitation\n */\nexport class Elicit extends Rpc.make(\"elicitation/create\", {\n  success: ElicitResult,\n  error: McpError,\n  payload: {\n    /**\n     * A message to display to the user, explaining what they are being\n     * elicited for.\n     */\n    message: Schema.String,\n    /**\n     * A restricted subset of JSON Schema.\n     * Only top-level properties are allowed, without nesting.\n     */\n    requestedSchema: Schema.Unknown\n  }\n}) {}\n\n/**\n * @since 1.0.0\n * @category Elicitation\n */\nexport class ElicitationDeclined\n  extends Schema.TaggedError<ElicitationDeclined>(\"@effect/ai/McpSchema/ElicitationDeclined\")(\"ElicitationDeclined\", {\n    request: Elicit.payloadSchema,\n    cause: Schema.optional(Schema.Defect)\n  })\n{}\n\n// =============================================================================\n// McpServerClient\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category McpServerClient\n */\nexport class McpServerClient extends Context.Tag(\"@effect/ai/McpSchema/McpServerClient\")<\n  McpServerClient,\n  {\n    readonly clientId: number\n    readonly getClient: Effect.Effect<\n      RpcClient.RpcClient<RpcGroup.Rpcs<typeof ServerRequestRpcs>, RpcClientError>,\n      never,\n      Scope.Scope\n    >\n  }\n>() {}\n\n/**\n * @since 1.0.0\n * @category McpServerClient\n */\nexport class McpServerClientMiddleware\n  extends RpcMiddleware.Tag<McpServerClientMiddleware>()(\"@effect/ai/McpSchema/McpServerClientMiddleware\", {\n    provides: McpServerClient\n  })\n{}\n\n// =============================================================================\n// Protocol\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type RequestEncoded<Group extends RpcGroup.Any> = RpcGroup.Rpcs<\n  Group\n> extends infer Rpc ? Rpc extends Rpc.Rpc<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error,\n    infer _Middleware\n  > ? {\n      readonly _tag: \"Request\"\n      readonly id: string | number\n      readonly method: _Tag\n      readonly payload: _Payload[\"Encoded\"]\n    }\n  : never\n  : never\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type NotificationEncoded<Group extends RpcGroup.Any> = RpcGroup.Rpcs<\n  Group\n> extends infer Rpc ? Rpc extends Rpc.Rpc<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error,\n    infer _Middleware\n  > ? {\n      readonly _tag: \"Notification\"\n      readonly method: _Tag\n      readonly payload: _Payload[\"Encoded\"]\n    }\n  : never\n  : never\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type SuccessEncoded<Group extends RpcGroup.Any> = RpcGroup.Rpcs<\n  Group\n> extends infer Rpc ? Rpc extends Rpc.Rpc<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error,\n    infer _Middleware\n  > ? {\n      readonly _tag: \"Success\"\n      readonly id: string | number\n      readonly result: _Success[\"Encoded\"]\n    }\n  : never\n  : never\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type FailureEncoded<Group extends RpcGroup.Any> = RpcGroup.Rpcs<\n  Group\n> extends infer Rpc ? Rpc extends Rpc.Rpc<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error,\n    infer _Middleware\n  > ? {\n      readonly _tag: \"Failure\"\n      readonly id: string | number\n      readonly error: _Error[\"Encoded\"]\n    }\n  : never\n  : never\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport class ClientRequestRpcs extends RpcGroup.make(\n  Ping,\n  Initialize,\n  Complete,\n  SetLevel,\n  GetPrompt,\n  ListPrompts,\n  ListResources,\n  ListResourceTemplates,\n  ReadResource,\n  Subscribe,\n  Unsubscribe,\n  CallTool,\n  ListTools\n).middleware(McpServerClientMiddleware) {}\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type ClientRequestEncoded = RequestEncoded<typeof ClientRequestRpcs>\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport class ClientNotificationRpcs extends RpcGroup.make(\n  CancelledNotification,\n  ProgressNotification,\n  InitializedNotification,\n  RootsListChangedNotification\n) {}\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type ClientNotificationEncoded = NotificationEncoded<typeof ClientNotificationRpcs>\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport class ClientRpcs extends ClientRequestRpcs.merge(ClientNotificationRpcs) {}\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type ClientSuccessEncoded = SuccessEncoded<typeof ServerRequestRpcs>\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type ClientFailureEncoded = FailureEncoded<typeof ServerRequestRpcs>\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport class ServerRequestRpcs extends RpcGroup.make(\n  Ping,\n  CreateMessage,\n  ListRoots,\n  Elicit\n) {}\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type ServerRequestEncoded = RequestEncoded<typeof ServerRequestRpcs>\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport class ServerNotificationRpcs extends RpcGroup.make(\n  CancelledNotification,\n  ProgressNotification,\n  LoggingMessageNotification,\n  ResourceUpdatedNotification,\n  ResourceListChangedNotification,\n  ToolListChangedNotification,\n  PromptListChangedNotification\n) {}\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type ServerNotificationEncoded = NotificationEncoded<typeof ServerNotificationRpcs>\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type ServerSuccessEncoded = SuccessEncoded<typeof ClientRequestRpcs>\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type ServerFailureEncoded = FailureEncoded<typeof ClientRequestRpcs>\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type ServerResultEncoded = ServerSuccessEncoded | ServerFailureEncoded\n\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type FromClientEncoded = ClientRequestEncoded | ClientNotificationEncoded\n/**\n * @since 1.0.0\n * @category Protocol\n */\nexport type FromServerEncoded = ServerResultEncoded | ServerNotificationEncoded\n\n/**\n * @since 1.0.0\n * @category Parameters\n */\nexport const ParamAnnotation: unique symbol = Symbol.for(\"@effect/ai/McpSchema/ParamNameId\")\n\n/**\n * @since 1.0.0\n * @category Parameters\n */\nexport interface Param<Id extends string, S extends Schema.Schema.Any>\n  extends Schema.Schema<S[\"Type\"], S[\"Encoded\"], S[\"Context\"]>\n{\n  readonly [ParamAnnotation]: Id\n}\n\n/**\n * Helper to create a param for a resource URI template.\n *\n * @since 1.0.0\n * @category Parameters\n */\nexport const param = <const Id extends string, S extends Schema.Schema.Any>(id: Id, schema: S): Param<Id, S> =>\n  schema.annotations({\n    [ParamAnnotation]: id\n  }) as any\n"
  },
  {
    "path": "packages/ai/ai/src/McpServer.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Headers from \"@effect/platform/Headers\"\nimport type * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\nimport type * as HttpRouter from \"@effect/platform/HttpRouter\"\nimport type { RpcMessage } from \"@effect/rpc\"\nimport type * as Rpc from \"@effect/rpc/Rpc\"\nimport * as RpcClient from \"@effect/rpc/RpcClient\"\nimport type * as RpcGroup from \"@effect/rpc/RpcGroup\"\nimport * as RpcSerialization from \"@effect/rpc/RpcSerialization\"\nimport * as RpcServer from \"@effect/rpc/RpcServer\"\nimport * as Arr from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as JsonSchema from \"effect/JSONSchema\"\nimport * as Layer from \"effect/Layer\"\nimport * as Logger from \"effect/Logger\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as Option from \"effect/Option\"\nimport * as RcMap from \"effect/RcMap\"\nimport * as Schema from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport type { Sink } from \"effect/Sink\"\nimport type { Stream } from \"effect/Stream\"\nimport type * as Types from \"effect/Types\"\nimport * as FindMyWay from \"find-my-way-ts\"\nimport type {\n  Annotations,\n  CallTool,\n  Complete,\n  GetPrompt,\n  Param,\n  PromptArgument,\n  PromptMessage,\n  ReadResourceResult,\n  ServerCapabilities\n} from \"./McpSchema.js\"\nimport {\n  CallToolResult,\n  ClientNotificationRpcs,\n  ClientRpcs,\n  CompleteResult,\n  Elicit,\n  ElicitationDeclined,\n  GetPromptResult,\n  InternalError,\n  InvalidParams,\n  ListPromptsResult,\n  ListResourcesResult,\n  ListResourceTemplatesResult,\n  ListToolsResult,\n  McpServerClient,\n  McpServerClientMiddleware,\n  ParamAnnotation,\n  Prompt,\n  Resource,\n  ResourceTemplate,\n  ServerNotificationRpcs,\n  ServerRequestRpcs,\n  TextContent,\n  Tool,\n  ToolAnnotations\n} from \"./McpSchema.js\"\nimport * as AiTool from \"./Tool.js\"\nimport type * as Toolkit from \"./Toolkit.js\"\n\n/**\n * @since 1.0.0\n * @category McpServer\n */\nexport class McpServer extends Context.Tag(\"@effect/ai/McpServer\")<\n  McpServer,\n  {\n    readonly notifications: RpcClient.RpcClient<RpcGroup.Rpcs<typeof ServerNotificationRpcs>>\n    readonly notificationsMailbox: Mailbox.ReadonlyMailbox<RpcMessage.Request<any>>\n    readonly initializedClients: Set<number>\n\n    readonly tools: ReadonlyArray<Tool>\n    readonly addTool: (options: {\n      readonly tool: Tool\n      readonly handle: (payload: any) => Effect.Effect<CallToolResult, never, McpServerClient>\n    }) => Effect.Effect<void>\n    readonly callTool: (\n      requests: typeof CallTool.payloadSchema.Type\n    ) => Effect.Effect<CallToolResult, InternalError | InvalidParams, McpServerClient>\n\n    readonly resources: ReadonlyArray<Resource>\n    readonly addResource: (\n      resource: Resource,\n      handle: Effect.Effect<typeof ReadResourceResult.Type, InternalError, McpServerClient>\n    ) => Effect.Effect<void>\n\n    readonly resourceTemplates: ReadonlyArray<ResourceTemplate>\n    readonly addResourceTemplate: (options: {\n      readonly template: ResourceTemplate\n      readonly routerPath: string\n      readonly completions: Record<string, (input: string) => Effect.Effect<CompleteResult, InternalError>>\n      readonly handle: (uri: string, params: Array<string>) => Effect.Effect<\n        typeof ReadResourceResult.Type,\n        InvalidParams | InternalError,\n        McpServerClient\n      >\n    }) => Effect.Effect<void>\n\n    readonly findResource: (uri: string) => Effect.Effect<\n      typeof ReadResourceResult.Type,\n      InvalidParams | InternalError,\n      McpServerClient\n    >\n\n    readonly prompts: ReadonlyArray<Prompt>\n    readonly addPrompt: (options: {\n      readonly prompt: Prompt\n      readonly completions: Record<\n        string,\n        (input: string) => Effect.Effect<CompleteResult, InternalError, McpServerClient>\n      >\n      readonly handle: (\n        params: Record<string, string>\n      ) => Effect.Effect<GetPromptResult, InternalError | InvalidParams, McpServerClient>\n    }) => Effect.Effect<void>\n    readonly getPromptResult: (\n      request: typeof GetPrompt.payloadSchema.Type\n    ) => Effect.Effect<GetPromptResult, InternalError | InvalidParams, McpServerClient>\n\n    readonly completion: (\n      complete: typeof Complete.payloadSchema.Type\n    ) => Effect.Effect<CompleteResult, InternalError, McpServerClient>\n  }\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly make = Effect.gen(function*() {\n    const matcher = makeUriMatcher<\n      | {\n        readonly _tag: \"ResourceTemplate\"\n        readonly handle: (\n          uri: string,\n          params: Array<string>\n        ) => Effect.Effect<typeof ReadResourceResult.Type, InternalError | InvalidParams, McpServerClient>\n      }\n      | {\n        readonly _tag: \"Resource\"\n        readonly effect: Effect.Effect<typeof ReadResourceResult.Type, InternalError, McpServerClient>\n      }\n    >()\n    const tools = Arr.empty<Tool>()\n    const toolMap = new Map<\n      string,\n      (payload: any) => Effect.Effect<CallToolResult, InternalError, McpServerClient>\n    >()\n    const resources: Array<Resource> = []\n    const resourceTemplates: Array<ResourceTemplate> = []\n    const prompts: Array<Prompt> = []\n    const promptMap = new Map<\n      string,\n      (params: Record<string, string>) => Effect.Effect<GetPromptResult, InternalError | InvalidParams, McpServerClient>\n    >()\n    const completionsMap = new Map<\n      string,\n      (input: string) => Effect.Effect<CompleteResult, InternalError, McpServerClient>\n    >()\n    const notificationsMailbox = yield* Mailbox.make<RpcMessage.Request<any>>()\n    const listChangedHandles = new Map<string, any>()\n    const notifications = yield* RpcClient.makeNoSerialization(ServerNotificationRpcs, {\n      spanPrefix: \"McpServer/Notifications\",\n      onFromClient(options): Effect.Effect<void> {\n        const message = options.message\n        if (message._tag !== \"Request\") {\n          return Effect.void\n        }\n        if (message.tag.includes(\"list_changed\")) {\n          if (!listChangedHandles.has(message.tag)) {\n            listChangedHandles.set(\n              message.tag,\n              setTimeout(() => {\n                notificationsMailbox.unsafeOffer(message)\n                listChangedHandles.delete(message.tag)\n              }, 0)\n            )\n          }\n        } else {\n          notificationsMailbox.unsafeOffer(message)\n        }\n        return notifications.write({\n          clientId: 0,\n          requestId: message.id,\n          _tag: \"Exit\",\n          exit: Exit.void as any\n        })\n      }\n    })\n\n    return McpServer.of({\n      notifications: notifications.client,\n      notificationsMailbox,\n      initializedClients: new Set<number>(),\n      get tools() {\n        return tools\n      },\n      addTool: (options) =>\n        Effect.suspend(() => {\n          tools.push(options.tool)\n          toolMap.set(options.tool.name, options.handle)\n          return notifications.client[\"notifications/tools/list_changed\"]({})\n        }),\n      callTool: (request) =>\n        Effect.suspend((): Effect.Effect<CallToolResult, InternalError | InvalidParams, McpServerClient> => {\n          const handle = toolMap.get(request.name)\n          if (!handle) {\n            return Effect.fail(\n              new InvalidParams({\n                message: `Tool '${request.name}' not found`\n              })\n            )\n          }\n          return handle(request.arguments)\n        }),\n      get resources() {\n        return resources\n      },\n      get resourceTemplates() {\n        return resourceTemplates\n      },\n      addResource: (resource, effect) =>\n        Effect.suspend(() => {\n          resources.push(resource)\n          matcher.add(resource.uri, { _tag: \"Resource\", effect })\n          return notifications.client[\"notifications/resources/list_changed\"](\n            {}\n          )\n        }),\n      addResourceTemplate: ({ completions, handle, routerPath, template }) =>\n        Effect.suspend(() => {\n          resourceTemplates.push(template)\n          matcher.add(routerPath, { _tag: \"ResourceTemplate\", handle })\n          for (const [param, handle] of Object.entries(completions)) {\n            completionsMap.set(\n              `ref/resource/${template.uriTemplate}/${param}`,\n              handle\n            )\n          }\n          return notifications.client[\"notifications/resources/list_changed\"](\n            {}\n          )\n        }),\n      findResource: (uri) =>\n        Effect.suspend(() => {\n          const match = matcher.find(uri)\n          if (!match) {\n            return Effect.succeed({ contents: [] })\n          } else if (match.handler._tag === \"Resource\") {\n            return match.handler.effect\n          }\n          const params: Array<string> = []\n          for (const key of Object.keys(match.params)) {\n            params[Number(key)] = match.params[key]!\n          }\n          return match.handler.handle(uri, params)\n        }),\n      get prompts() {\n        return prompts\n      },\n      addPrompt: (options) =>\n        Effect.suspend(() => {\n          prompts.push(options.prompt)\n          promptMap.set(options.prompt.name, options.handle)\n          for (const [param, handle] of Object.entries(options.completions)) {\n            completionsMap.set(\n              `ref/prompt/${options.prompt.name}/${param}`,\n              handle\n            )\n          }\n          return notifications.client[\"notifications/prompts/list_changed\"]({})\n        }),\n      getPromptResult: Effect.fnUntraced(function*({ arguments: params, name }) {\n        const handler = promptMap.get(name)\n        if (!handler) {\n          return yield* new InvalidParams({\n            message: `Prompt '${name}' not found`\n          })\n        }\n        return yield* handler(params ?? {})\n      }),\n      completion: Effect.fnUntraced(function*(complete) {\n        const ref = complete.ref\n        const key = ref.type === \"ref/resource\"\n          ? `ref/resource/${ref.uri}/${complete.argument.name}`\n          : `ref/prompt/${ref.name}/${complete.argument.name}`\n        const handler = completionsMap.get(key)\n        return handler\n          ? yield* handler(complete.argument.value)\n          : CompleteResult.empty\n      })\n    })\n  })\n\n  /**\n   * @since 1.0.0\n   */\n  static readonly layer: Layer.Layer<McpServer | McpServerClient> = Layer.scoped(McpServer, McpServer.make) as any\n}\n\nconst LATEST_PROTOCOL_VERSION = \"2025-06-18\"\nconst SUPPORTED_PROTOCOL_VERSIONS = [\n  LATEST_PROTOCOL_VERSION,\n  \"2025-03-26\",\n  \"2024-11-05\",\n  \"2024-10-07\"\n]\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const run: (options: {\n  readonly name: string\n  readonly version: string\n}) => Effect.Effect<never, never, McpServer | RpcServer.Protocol> = Effect.fnUntraced(function*(options: {\n  readonly name: string\n  readonly version: string\n}) {\n  const protocol = yield* RpcServer.Protocol\n  const handlers = yield* Layer.build(layerHandlers(options))\n  const server = yield* McpServer\n\n  const clients = yield* RcMap.make({\n    lookup: Effect.fnUntraced(function*(clientId: number) {\n      let write!: (\n        message: RpcMessage.FromServerEncoded\n      ) => Effect.Effect<void>\n      const client = yield* RpcClient.make(ServerRequestRpcs, {\n        spanPrefix: \"McpServer/Client\"\n      }).pipe(\n        Effect.provideServiceEffect(\n          RpcClient.Protocol,\n          RpcClient.Protocol.make(\n            Effect.fnUntraced(function*(writeResponse) {\n              write = writeResponse\n              return {\n                send(request, _transferables) {\n                  return protocol.send(clientId, {\n                    ...request,\n                    headers: undefined,\n                    traceId: undefined,\n                    spanId: undefined,\n                    sampled: undefined\n                  } as any)\n                },\n                supportsAck: true,\n                supportsTransferables: false\n              }\n            })\n          )\n        )\n      )\n\n      return { client, write } as const\n    }),\n    idleTimeToLive: 10000\n  })\n\n  const clientMiddleware = McpServerClientMiddleware.of(({ clientId }) =>\n    Effect.sync(() =>\n      McpServerClient.of({\n        clientId,\n        getClient: RcMap.get(clients, clientId).pipe(\n          Effect.map(({ client }) => client)\n        )\n      })\n    )\n  )\n\n  const patchedProtocol = RpcServer.Protocol.of({\n    ...protocol,\n    run: (f) =>\n      protocol.run((clientId, request_) => {\n        const request = request_ as any as\n          | RpcMessage.FromServerEncoded\n          | RpcMessage.FromClientEncoded\n        switch (request._tag) {\n          case \"Request\": {\n            if (ClientNotificationRpcs.requests.has(request.tag)) {\n              if (request.tag === \"notifications/cancelled\") {\n                return f(clientId, {\n                  _tag: \"Interrupt\",\n                  requestId: String((request.payload as any).requestId)\n                })\n              }\n              const handler = handlers.unsafeMap.get(\n                request.tag\n              ) as Rpc.Handler<string>\n              return handler\n                ? handler.handler(request.payload, {\n                  clientId,\n                  headers: Headers.fromInput(request.headers)\n                }) as Effect.Effect<void>\n                : Effect.void\n            }\n            return f(clientId, request)\n          }\n          case \"Ping\":\n          case \"Ack\":\n          case \"Interrupt\":\n          case \"Eof\":\n            return f(clientId, request)\n          case \"Pong\":\n          case \"Exit\":\n          case \"Chunk\":\n          case \"ClientProtocolError\":\n          case \"Defect\":\n            return RcMap.get(clients, clientId).pipe(\n              Effect.flatMap(({ write }) => write(request)),\n              Effect.scoped\n            )\n        }\n      })\n  })\n\n  const encodeNotification = Schema.encode(\n    Schema.Union(\n      ...Array.from(\n        ServerNotificationRpcs.requests.values(),\n        (rpc) => rpc.payloadSchema\n      )\n    )\n  )\n  yield* server.notificationsMailbox.take.pipe(\n    Effect.flatMap(Effect.fnUntraced(function*(request) {\n      const encoded = yield* encodeNotification(request.payload)\n      const message: RpcMessage.RequestEncoded = {\n        _tag: \"Request\",\n        tag: request.tag,\n        payload: encoded\n      } as any\n      const clientIds = yield* patchedProtocol.clientIds\n      for (const clientId of server.initializedClients) {\n        if (!clientIds.has(clientId)) {\n          server.initializedClients.delete(clientId)\n          continue\n        }\n        yield* patchedProtocol.send(clientId, message as any)\n      }\n    })),\n    Effect.catchAllCause(() => Effect.void),\n    Effect.forever,\n    Effect.forkScoped\n  )\n\n  return yield* RpcServer.make(ClientRpcs, {\n    spanPrefix: \"McpServer\",\n    disableFatalDefects: true\n  }).pipe(\n    Effect.provideService(RpcServer.Protocol, patchedProtocol),\n    Effect.provideService(McpServerClientMiddleware, clientMiddleware),\n    Effect.provide(handlers)\n  )\n}, Effect.scoped)\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly name: string\n  readonly version: string\n}): Layer.Layer<McpServer | McpServerClient, never, RpcServer.Protocol> =>\n  Layer.scopedDiscard(Effect.forkScoped(run(options))).pipe(\n    Layer.provideMerge(McpServer.layer)\n  )\n\n/**\n * Run the McpServer, using stdio for input and output.\n *\n * ```ts\n * import { McpSchema, McpServer } from \"@effect/ai\"\n * import { NodeRuntime, NodeSink, NodeStream } from \"@effect/platform-node\"\n * import { Effect, Layer, Logger, Schema } from \"effect\"\n *\n * const idParam = McpSchema.param(\"id\", Schema.NumberFromString)\n *\n * // Define a resource template for a README file\n * const ReadmeTemplate = McpServer.resource`file://readme/${idParam}`({\n *   name: \"README Template\",\n *   // You can add auto-completion for the ID parameter\n *   completion: {\n *     id: (_) => Effect.succeed([1, 2, 3, 4, 5])\n *   },\n *   content: Effect.fn(function*(_uri, id) {\n *     return `# MCP Server Demo - ID: ${id}`\n *   })\n * })\n *\n * // Define a test prompt with parameters\n * const TestPrompt = McpServer.prompt({\n *   name: \"Test Prompt\",\n *   description: \"A test prompt to demonstrate MCP server capabilities\",\n *   parameters: Schema.Struct({\n *     flightNumber: Schema.String\n *   }),\n *   completion: {\n *     flightNumber: () => Effect.succeed([\"FL123\", \"FL456\", \"FL789\"])\n *   },\n *   content: ({ flightNumber }) => Effect.succeed(`Get the booking details for flight number: ${flightNumber}`)\n * })\n *\n * // Merge all the resources and prompts into a single server layer\n * const ServerLayer = Layer.mergeAll(\n *   ReadmeTemplate,\n *   TestPrompt\n * ).pipe(\n *   // Provide the MCP server implementation\n *   Layer.provide(McpServer.layerStdio({\n *     name: \"Demo Server\",\n *     version: \"1.0.0\",\n *     stdin: NodeStream.stdin,\n *     stdout: NodeSink.stdout\n *   })),\n *   // add a stderr logger\n *   Layer.provide(Logger.add(Logger.prettyLogger({ stderr: true })))\n * )\n *\n * Layer.launch(ServerLayer).pipe(NodeRuntime.runMain)\n * ```\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layerStdio = <EIn, RIn, EOut, ROut>(options: {\n  readonly name: string\n  readonly version: string\n  readonly stdin: Stream<Uint8Array, EIn, RIn>\n  readonly stdout: Sink<unknown, Uint8Array | string, unknown, EOut, ROut>\n}): Layer.Layer<McpServer | McpServerClient, never, RIn | ROut> =>\n  layer(options).pipe(\n    Layer.provide(\n      RpcServer.layerProtocolStdio({\n        stdin: options.stdin,\n        stdout: options.stdout\n      })\n    ),\n    Layer.provide(RpcSerialization.layerNdJsonRpc()),\n    // remove stdout loggers\n    Layer.provideMerge(Logger.remove(Logger.defaultLogger)),\n    Layer.provideMerge(Logger.remove(Logger.prettyLoggerDefault))\n  )\n\n/**\n * Run the McpServer, using HTTP for input and output.\n *\n * ```ts\n * import { McpSchema, McpServer } from \"@effect/ai\"\n * import { HttpRouter } from \"@effect/platform\"\n * import { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\n * import { Effect, Layer, Schema } from \"effect\"\n * import { createServer } from \"node:http\"\n *\n * const idParam = McpSchema.param(\"id\", Schema.NumberFromString)\n *\n * // Define a resource template for a README file\n * const ReadmeTemplate = McpServer.resource`file://readme/${idParam}`({\n *   name: \"README Template\",\n *   // You can add auto-completion for the ID parameter\n *   completion: {\n *     id: (_) => Effect.succeed([1, 2, 3, 4, 5])\n *   },\n *   content: Effect.fn(function*(_uri, id) {\n *     return `# MCP Server Demo - ID: ${id}`\n *   })\n * })\n *\n * // Define a test prompt with parameters\n * const TestPrompt = McpServer.prompt({\n *   name: \"Test Prompt\",\n *   description: \"A test prompt to demonstrate MCP server capabilities\",\n *   parameters: Schema.Struct({\n *     flightNumber: Schema.String\n *   }),\n *   completion: {\n *     flightNumber: () => Effect.succeed([\"FL123\", \"FL456\", \"FL789\"])\n *   },\n *   content: ({ flightNumber }) => Effect.succeed(`Get the booking details for flight number: ${flightNumber}`)\n * })\n *\n * // Merge all the resources and prompts into a single server layer\n * const ServerLayer = Layer.mergeAll(\n *   ReadmeTemplate,\n *   TestPrompt,\n *   HttpRouter.Default.serve()\n * ).pipe(\n *   // Provide the MCP server implementation\n *   Layer.provide(McpServer.layerHttp({\n *     name: \"Demo Server\",\n *     version: \"1.0.0\",\n *     path: \"/mcp\"\n *   })),\n *   Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n * )\n *\n * Layer.launch(ServerLayer).pipe(NodeRuntime.runMain)\n * ```\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layerHttp = <I = HttpRouter.Default>(options: {\n  readonly name: string\n  readonly version: string\n  readonly path: HttpRouter.PathInput\n  readonly routerTag?: HttpRouter.HttpRouter.TagClass<I, string, any, any>\n}): Layer.Layer<McpServer | McpServerClient> =>\n  layer(options).pipe(\n    Layer.provide(RpcServer.layerProtocolHttp(options)),\n    Layer.provide(RpcSerialization.layerJsonRpc())\n  )\n\n/**\n * Run the McpServer, using HTTP for input and output.\n *\n * Uses a `HttpLayerRouter` to register the McpServer routes.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layerHttpRouter = (options: {\n  readonly name: string\n  readonly version: string\n  readonly path: HttpRouter.PathInput\n}): Layer.Layer<\n  McpServer | McpServerClient,\n  never,\n  HttpLayerRouter.HttpRouter\n> =>\n  layer(options).pipe(\n    Layer.provide(RpcServer.layerProtocolHttpRouter(options)),\n    Layer.provide(RpcSerialization.layerJsonRpc())\n  )\n\n/**\n * Register an AiToolkit with the McpServer.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport const registerToolkit: <Tools extends Record<string, AiTool.Any>>(\n  toolkit: Toolkit.Toolkit<Tools>\n) => Effect.Effect<\n  void,\n  never,\n  | McpServer\n  | AiTool.HandlersFor<Tools>\n  | Exclude<AiTool.Requirements<Tools>, McpServerClient>\n> = Effect.fnUntraced(function*<Tools extends Record<string, AiTool.Any>>(\n  toolkit: Toolkit.Toolkit<Tools>\n) {\n  const registry = yield* McpServer\n  const built = yield* toolkit as any as Effect.Effect<\n    Toolkit.WithHandler<Tools>,\n    never,\n    Exclude<AiTool.HandlersFor<Tools>, McpServerClient>\n  >\n  const context = yield* Effect.context<never>()\n  for (const tool of Object.values(built.tools)) {\n    const mcpTool = new Tool({\n      name: tool.name,\n      description: tool.description,\n      inputSchema: makeJsonSchema(tool.parametersSchema.ast),\n      annotations: new ToolAnnotations({\n        ...Context.getOption(tool.annotations, AiTool.Title).pipe(\n          Option.map((title) => ({ title })),\n          Option.getOrUndefined\n        ),\n        readOnlyHint: Context.get(tool.annotations, AiTool.Readonly),\n        destructiveHint: Context.get(tool.annotations, AiTool.Destructive),\n        idempotentHint: Context.get(tool.annotations, AiTool.Idempotent),\n        openWorldHint: Context.get(tool.annotations, AiTool.OpenWorld)\n      })\n    })\n    yield* registry.addTool({\n      tool: mcpTool,\n      handle(payload) {\n        return built.handle(tool.name as any, payload).pipe(\n          Effect.provide(context as Context.Context<any>),\n          Effect.match({\n            onFailure: (error) =>\n              new CallToolResult({\n                isError: true,\n                structuredContent: typeof error === \"object\" ? error : undefined,\n                content: [\n                  {\n                    type: \"text\",\n                    text: JSON.stringify(error)\n                  }\n                ]\n              }),\n            onSuccess: (result) =>\n              new CallToolResult({\n                isError: false,\n                structuredContent: typeof result.encodedResult === \"object\"\n                  ? result.encodedResult\n                  : undefined,\n                content: [\n                  {\n                    type: \"text\",\n                    text: JSON.stringify(result.encodedResult)\n                  }\n                ]\n              })\n          })\n        ) as any\n      }\n    })\n  }\n})\n\n/**\n * Register an AiToolkit with the McpServer.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport const toolkit = <Tools extends Record<string, AiTool.Any>>(\n  toolkit: Toolkit.Toolkit<Tools>\n): Layer.Layer<\n  never,\n  never,\n  | AiTool.HandlersFor<Tools>\n  | Exclude<AiTool.Requirements<Tools>, McpServerClient>\n> =>\n  Layer.effectDiscard(registerToolkit(toolkit)).pipe(\n    Layer.provide(McpServer.layer)\n  )\n\n/**\n * @since 1.0.0\n */\nexport type ValidateCompletions<\n  Completions,\n  Keys extends string\n> =\n  & Completions\n  & {\n    readonly [K in keyof Completions]: K extends Keys ? (input: string) => any\n      : never\n  }\n\n/**\n * @since 1.0.0\n */\nexport type ResourceCompletions<\n  Schemas extends ReadonlyArray<Schema.Schema.Any>\n> = {\n  readonly [\n    K in Extract<\n      keyof Schemas,\n      `${number}`\n    > as Schemas[K] extends Param<infer Id, infer _S> ? Id : `param${K}`\n  ]: (\n    input: string\n  ) => Effect.Effect<Array<Schema.Schema.Type<Schemas[K]>>, any, any>\n}\n\n/**\n * Register a resource with the McpServer.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport const registerResource: {\n  <E, R>(options: {\n    readonly uri: string\n    readonly name: string\n    readonly description?: string | undefined\n    readonly mimeType?: string | undefined\n    readonly audience?: ReadonlyArray<\"user\" | \"assistant\"> | undefined\n    readonly priority?: number | undefined\n    readonly content: Effect.Effect<\n      typeof ReadResourceResult.Type | string | Uint8Array,\n      E,\n      R\n    >\n  }): Effect.Effect<void, never, Exclude<R, McpServerClient> | McpServer>\n  <const Schemas extends ReadonlyArray<Schema.Schema.Any>>(\n    segments: TemplateStringsArray,\n    ...schemas:\n      & Schemas\n      & {\n        readonly [K in keyof Schemas]: Schema.Schema.Encoded<\n          Schemas[K]\n        > extends string ? unknown\n          : \"Schema must be encodable to a string\"\n      }\n  ): <\n    E,\n    R,\n    const Completions extends Partial<ResourceCompletions<Schemas>> = {}\n  >(options: {\n    readonly name: string\n    readonly description?: string | undefined\n    readonly mimeType?: string | undefined\n    readonly audience?: ReadonlyArray<\"user\" | \"assistant\"> | undefined\n    readonly priority?: number | undefined\n    readonly completion?:\n      | ValidateCompletions<Completions, keyof ResourceCompletions<Schemas>>\n      | undefined\n    readonly content: (\n      uri: string,\n      ...params: { readonly [K in keyof Schemas]: Schemas[K][\"Type\"] }\n    ) => Effect.Effect<\n      typeof ReadResourceResult.Type | string | Uint8Array,\n      E,\n      R\n    >\n  }) => Effect.Effect<\n    void,\n    never,\n    | Exclude<\n      | R\n      | (Completions[keyof Completions] extends (input: string) => infer Ret\n        ? Ret extends Effect.Effect<infer _A, infer _E, infer _R> ? _R\n        : never\n        : never),\n      McpServerClient\n    >\n    | McpServer\n  >\n} = function() {\n  if (arguments.length === 1) {\n    const options = arguments[0] as\n      & Resource\n      & typeof Annotations.Type\n      & {\n        readonly content: Effect.Effect<\n          typeof ReadResourceResult.Type | string | Uint8Array\n        >\n      }\n    return Effect.gen(function*() {\n      const context = yield* Effect.context<any>()\n      const registry = yield* McpServer\n      yield* registry.addResource(\n        new Resource({\n          ...options,\n          annotations: options\n        }),\n        options.content.pipe(\n          Effect.provide(context),\n          Effect.map((content) => resolveResourceContent(options.uri, content)),\n          Effect.catchAllCause((cause) => {\n            const prettyError = Cause.prettyErrors(cause)[0]\n            return new InternalError({ message: prettyError.message })\n          })\n        )\n      )\n    })\n  }\n  const { params, routerPath, schema, uriPath } = compileUriTemplate(\n    ...(arguments as any as [any, any])\n  )\n  return Effect.fnUntraced(function*<E, R>(options: {\n    readonly name: string\n    readonly description?: string | undefined\n    readonly mimeType?: string | undefined\n    readonly audience?: ReadonlyArray<\"user\" | \"assistant\"> | undefined\n    readonly priority?: number | undefined\n    readonly completion?:\n      | Record<string, (input: string) => Effect.Effect<any>>\n      | undefined\n    readonly content: (\n      uri: string,\n      ...params: Array<any>\n    ) => Effect.Effect<\n      typeof ReadResourceResult.Type | string | Uint8Array,\n      E,\n      R\n    >\n  }) {\n    const context = yield* Effect.context<any>()\n    const registry = yield* McpServer\n    const decode = Schema.decodeUnknown(schema)\n    const template = new ResourceTemplate({\n      ...options,\n      uriTemplate: uriPath,\n      annotations: options\n    })\n    const completions: Record<\n      string,\n      (input: string) => Effect.Effect<CompleteResult, InternalError>\n    > = {}\n    for (const [param, handle] of Object.entries(options.completion ?? {})) {\n      const encodeArray = Schema.encodeUnknown(Schema.Array(params[param]))\n      const handler = (input: string) =>\n        handle(input).pipe(\n          Effect.flatMap(encodeArray),\n          Effect.map(\n            (values) =>\n              new CompleteResult({\n                completion: {\n                  values: values as Array<string>,\n                  total: values.length,\n                  hasMore: false\n                }\n              })\n          ),\n          Effect.catchAllCause((cause) => {\n            const prettyError = Cause.prettyErrors(cause)[0]\n            return new InternalError({ message: prettyError.message })\n          }),\n          Effect.provide(context)\n        )\n      completions[param] = handler\n    }\n    yield* registry.addResourceTemplate({\n      template,\n      routerPath,\n      completions,\n      handle: (uri, params) =>\n        decode(params).pipe(\n          Effect.mapError(\n            (error) => new InvalidParams({ message: error.message })\n          ),\n          Effect.flatMap((params) =>\n            options.content(uri, ...params).pipe(\n              Effect.map((content) => resolveResourceContent(uri, content)),\n              Effect.catchAllCause((cause) => {\n                const prettyError = Cause.prettyErrors(cause)[0]\n                return new InternalError({ message: prettyError.message })\n              })\n            )\n          ),\n          Effect.provide(context)\n        )\n    })\n  })\n} as any\n\n/**\n * Register a resource with the McpServer.\n *\n * @since 1.0.0\n * @category Resources\n */\nexport const resource: {\n  <E, R>(options: {\n    readonly uri: string\n    readonly name: string\n    readonly description?: string | undefined\n    readonly mimeType?: string | undefined\n    readonly audience?: ReadonlyArray<\"user\" | \"assistant\"> | undefined\n    readonly priority?: number | undefined\n    readonly content: Effect.Effect<\n      typeof ReadResourceResult.Type | string | Uint8Array,\n      E,\n      R\n    >\n  }): Layer.Layer<never, never, Exclude<R, McpServerClient>>\n  <const Schemas extends ReadonlyArray<Schema.Schema.Any>>(\n    segments: TemplateStringsArray,\n    ...schemas:\n      & Schemas\n      & {\n        readonly [K in keyof Schemas]: Schema.Schema.Encoded<\n          Schemas[K]\n        > extends string ? unknown\n          : \"Schema must be encodable to a string\"\n      }\n  ): <\n    E,\n    R,\n    const Completions extends Partial<ResourceCompletions<Schemas>> = {}\n  >(options: {\n    readonly name: string\n    readonly description?: string | undefined\n    readonly mimeType?: string | undefined\n    readonly audience?: ReadonlyArray<\"user\" | \"assistant\"> | undefined\n    readonly priority?: number | undefined\n    readonly completion?:\n      | ValidateCompletions<Completions, keyof ResourceCompletions<Schemas>>\n      | undefined\n    readonly content: (\n      uri: string,\n      ...params: { readonly [K in keyof Schemas]: Schemas[K][\"Type\"] }\n    ) => Effect.Effect<\n      typeof ReadResourceResult.Type | string | Uint8Array,\n      E,\n      R\n    >\n  }) => Layer.Layer<\n    never,\n    never,\n    Exclude<\n      | R\n      | (Completions[keyof Completions] extends (input: string) => infer Ret\n        ? Ret extends Effect.Effect<infer _A, infer _E, infer _R> ? _R\n        : never\n        : never),\n      McpServerClient\n    >\n  >\n} = function() {\n  if (arguments.length === 1) {\n    return Layer.effectDiscard(registerResource(arguments[0])).pipe(\n      Layer.provide(McpServer.layer)\n    )\n  }\n  const register = registerResource(...(arguments as any as [any, any]))\n  return (options: any) => Layer.effectDiscard(register(options)).pipe(Layer.provide(McpServer.layer))\n} as any\n\n/**\n * Register a prompt with the McpServer.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport const registerPrompt = <\n  E,\n  R,\n  Params = {},\n  ParamsI extends Record<string, string> = {},\n  ParamsR = never,\n  const Completions extends {\n    readonly [K in keyof Params]?: (\n      input: string\n    ) => Effect.Effect<Array<Params[K]>, any, any>\n  } = {}\n>(options: {\n  readonly name: string\n  readonly description?: string | undefined\n  readonly parameters?: Schema.Schema<Params, ParamsI, ParamsR> | undefined\n  readonly completion?:\n    | ValidateCompletions<Completions, Extract<keyof Params, string>>\n    | undefined\n  readonly content: (\n    params: Params\n  ) => Effect.Effect<Array<typeof PromptMessage.Type> | string, E, R>\n}): Effect.Effect<\n  void,\n  never,\n  Exclude<ParamsR | R, McpServerClient> | McpServer\n> => {\n  const args = Arr.empty<typeof PromptArgument.Type>()\n  const props: Record<string, Schema.Schema.Any> = {}\n  const propSignatures = options.parameters\n    ? AST.getPropertySignatures(options.parameters.ast)\n    : []\n  for (const prop of propSignatures) {\n    args.push({\n      name: prop.name as string,\n      description: Option.getOrUndefined(AST.getDescriptionAnnotation(prop)),\n      required: !prop.isOptional\n    })\n    props[prop.name as string] = Schema.make(prop.type)\n  }\n  const prompt = new Prompt({\n    name: options.name,\n    description: options.description,\n    arguments: args\n  })\n  const decode = options.parameters\n    ? Schema.decodeUnknown(options.parameters)\n    : () => Effect.succeed({} as Params)\n  const completion: Record<string, (input: string) => Effect.Effect<any>> = options.completion ?? {}\n  return Effect.gen(function*() {\n    const registry = yield* McpServer\n    const context = yield* Effect.context<Exclude<R | ParamsR, McpServerClient>>()\n    const completions: Record<\n      string,\n      (\n        input: string\n      ) => Effect.Effect<CompleteResult, InternalError, McpServerClient>\n    > = {}\n    for (const [param, handle] of Object.entries(completion)) {\n      const encodeArray = Schema.encodeUnknown(Schema.Array(props[param]))\n      const handler = (input: string) =>\n        handle(input).pipe(\n          Effect.flatMap(encodeArray),\n          Effect.map((values) => ({\n            completion: {\n              values: values as Array<string>,\n              total: values.length,\n              hasMore: false\n            }\n          })),\n          Effect.catchAllCause((cause) => {\n            const prettyError = Cause.prettyErrors(cause)[0]\n            return new InternalError({ message: prettyError.message })\n          }),\n          Effect.provide(context)\n        )\n      completions[param] = handler as any\n    }\n    yield* registry.addPrompt({\n      prompt,\n      completions,\n      handle: (params) =>\n        decode(params).pipe(\n          Effect.mapError(\n            (error) => new InvalidParams({ message: error.message })\n          ),\n          Effect.flatMap((params) => options.content(params)),\n          Effect.map((messages) => {\n            messages = typeof messages === \"string\"\n              ? [\n                {\n                  role: \"user\",\n                  content: TextContent.make({ text: messages })\n                }\n              ]\n              : messages\n            return new GetPromptResult({\n              messages,\n              description: prompt.description\n            })\n          }),\n          Effect.catchAllCause((cause) => {\n            const prettyError = Cause.prettyErrors(cause)[0]\n            return new InternalError({ message: prettyError.message })\n          }),\n          Effect.provide(context as Context.Context<ParamsR | R>)\n        )\n    })\n  })\n}\n\n/**\n * Register a prompt with the McpServer.\n *\n * @since 1.0.0\n * @category Prompts\n */\nexport const prompt = <\n  E,\n  R,\n  Params = {},\n  ParamsI extends Record<string, string> = {},\n  ParamsR = never,\n  const Completions extends {\n    readonly [K in keyof Params]?: (\n      input: string\n    ) => Effect.Effect<Array<Params[K]>, any, any>\n  } = {}\n>(options: {\n  readonly name: string\n  readonly description?: string | undefined\n  readonly parameters?: Schema.Schema<Params, ParamsI, ParamsR> | undefined\n  readonly completion?:\n    | ValidateCompletions<Completions, Extract<keyof Params, string>>\n    | undefined\n  readonly content: (\n    params: Params\n  ) => Effect.Effect<Array<typeof PromptMessage.Type> | string, E, R>\n}): Layer.Layer<never, never, Exclude<ParamsR | R, McpServerClient>> =>\n  Layer.effectDiscard(registerPrompt(options)).pipe(\n    Layer.provide(McpServer.layer)\n  )\n\n/**\n * Create an elicitation request\n *\n * @since 1.0.0\n * @category Elicitation\n */\nexport const elicit: <A, I extends Record<string, any>, R>(options: {\n  readonly message: string\n  readonly schema: Schema.Schema<A, I, R>\n}) => Effect.Effect<A, ElicitationDeclined, McpServerClient | R> = Effect.fnUntraced(\n  function*<A, I extends Record<string, any>, R>(options: {\n    readonly message: string\n    readonly schema: Schema.Schema<A, I, R>\n  }) {\n    const { getClient } = yield* McpServerClient\n    const client = yield* getClient\n    const request = Elicit.payloadSchema.make({\n      message: options.message,\n      requestedSchema: makeJsonSchema(options.schema.ast)\n    })\n    const res = yield* client[\"elicitation/create\"](request).pipe(\n      Effect.catchAllCause((cause) =>\n        Effect.fail(\n          new ElicitationDeclined({ cause: Cause.squash(cause), request })\n        )\n      )\n    )\n    switch (res.action) {\n      case \"accept\":\n        return yield* Effect.orDie(\n          Schema.decodeUnknown(options.schema)(res.content)\n        )\n      case \"cancel\":\n        return yield* Effect.interrupt\n      case \"decline\":\n        return yield* Effect.fail(new ElicitationDeclined({ request }))\n    }\n  },\n  Effect.scoped\n)\n\n// -----------------------------------------------------------------------------\n// Internal\n// -----------------------------------------------------------------------------\n\nconst makeUriMatcher = <A>() => {\n  const router = FindMyWay.make<A>({\n    ignoreTrailingSlash: true,\n    ignoreDuplicateSlashes: true,\n    caseSensitive: true\n  })\n  const add = (uri: string, value: A) => {\n    router.on(\"GET\", uri as any, value)\n  }\n  const find = (uri: string) => router.find(\"GET\", uri)\n\n  return { add, find } as const\n}\n\nconst compileUriTemplate = (\n  segments: TemplateStringsArray,\n  ...schemas: ReadonlyArray<Schema.Schema.Any>\n) => {\n  let routerPath = segments[0].replace(\":\", \"::\")\n  let uriPath = segments[0]\n  const params: Record<string, Schema.Schema.Any> = {}\n  let pathSchema = Schema.Tuple() as Schema.Schema.Any\n  if (schemas.length > 0) {\n    const arr: Array<Schema.Schema.Any> = []\n    for (let i = 0; i < schemas.length; i++) {\n      const schema = schemas[i]\n      const segment = segments[i + 1]\n      const key = String(i)\n      arr.push(schema)\n      routerPath += `:${key}${segment.replace(\":\", \"::\")}`\n      const paramName = AST.getAnnotation(ParamAnnotation)(schema.ast).pipe(\n        Option.getOrElse(() => `param${key}`)\n      )\n      params[paramName as string] = schema\n      uriPath += `{${paramName}}${segment}`\n    }\n    pathSchema = Schema.Tuple(...arr)\n  }\n  return {\n    routerPath,\n    uriPath,\n    schema: pathSchema,\n    params\n  } as const\n}\n\nconst layerHandlers = (serverInfo: {\n  readonly name: string\n  readonly version: string\n}) =>\n  ClientRpcs.toLayer(\n    Effect.gen(function*() {\n      const server = yield* McpServer\n\n      return {\n        // Requests\n        ping: () => Effect.succeed({}),\n        initialize(params, { clientId }) {\n          const requestedVersion = params.protocolVersion\n          const capabilities: Types.DeepMutable<\n            typeof ServerCapabilities.Type\n          > = {\n            completions: {}\n          }\n          if (server.tools.length > 0) {\n            capabilities.tools = { listChanged: true }\n          }\n          if (\n            server.resources.length > 0 ||\n            server.resourceTemplates.length > 0\n          ) {\n            capabilities.resources = {\n              listChanged: true,\n              subscribe: false\n            }\n          }\n          if (server.prompts.length > 0) {\n            capabilities.prompts = { listChanged: true }\n          }\n          server.initializedClients.add(clientId)\n          return Effect.succeed({\n            capabilities,\n            serverInfo,\n            protocolVersion: SUPPORTED_PROTOCOL_VERSIONS.includes(\n                requestedVersion\n              )\n              ? requestedVersion\n              : LATEST_PROTOCOL_VERSION\n          })\n        },\n        \"completion/complete\": server.completion,\n        \"logging/setLevel\": () => InternalError.notImplemented,\n        \"prompts/get\": server.getPromptResult,\n        \"prompts/list\": () => Effect.sync(() => new ListPromptsResult({ prompts: server.prompts })),\n        \"resources/list\": () =>\n          Effect.sync(\n            () => new ListResourcesResult({ resources: server.resources })\n          ),\n        \"resources/read\": ({ uri }) => server.findResource(uri),\n        \"resources/subscribe\": () => InternalError.notImplemented,\n        \"resources/unsubscribe\": () => InternalError.notImplemented,\n        \"resources/templates/list\": () =>\n          Effect.sync(\n            () =>\n              new ListResourceTemplatesResult({\n                resourceTemplates: server.resourceTemplates\n              })\n          ),\n        \"tools/call\": server.callTool,\n        \"tools/list\": () => Effect.sync(() => new ListToolsResult({ tools: server.tools })),\n\n        // Notifications\n        \"notifications/cancelled\": (_) => Effect.void,\n        \"notifications/initialized\": (_) => Effect.void,\n        \"notifications/progress\": (_) => Effect.void,\n        \"notifications/roots/list_changed\": (_) => Effect.void\n      }\n    })\n  )\n\nconst makeJsonSchema = (ast: AST.AST): JsonSchema.JsonSchema7 => {\n  const props = AST.getPropertySignatures(ast)\n  if (props.length === 0) {\n    return {\n      type: \"object\",\n      properties: {},\n      required: [],\n      additionalProperties: false\n    }\n  }\n  const $defs = {}\n  const schema = JsonSchema.fromAST(ast, {\n    definitions: $defs,\n    topLevelReferenceStrategy: \"skip\"\n  })\n  if (Object.keys($defs).length === 0) return schema\n  ;(schema as any).$defs = $defs\n  return schema\n}\n\nconst resolveResourceContent = (\n  uri: string,\n  content: typeof ReadResourceResult.Type | string | Uint8Array\n): typeof ReadResourceResult.Type => {\n  if (typeof content === \"string\") {\n    return {\n      contents: [\n        {\n          uri,\n          text: content\n        }\n      ]\n    }\n  } else if (content instanceof Uint8Array) {\n    return {\n      contents: [\n        {\n          uri,\n          blob: content\n        }\n      ]\n    }\n  }\n  return content\n}\n"
  },
  {
    "path": "packages/ai/ai/src/Model.ts",
    "content": "/**\n * The `Model` module provides a unified interface for AI service providers.\n *\n * This module enables creation of provider-specific AI models that can be used\n * interchangeably within the Effect AI ecosystem. It combines Layer\n * functionality with provider identification, allowing for seamless switching\n * between different AI service providers while maintaining type safety.\n *\n * @example\n * ```ts\n * import { Model, LanguageModel } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * declare const myAnthropicLayer: Layer.Layer<LanguageModel.LanguageModel>\n *\n * const anthropicModel = Model.make(\"anthropic\", myAnthropicLayer)\n *\n * const program = Effect.gen(function* () {\n *   const response = yield* LanguageModel.generateText({\n *     prompt: \"Hello, world!\"\n *   })\n *   return response.text\n * }).pipe(\n *   Effect.provide(anthropicModel)\n * )\n * ```\n *\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { CommitPrototype } from \"effect/Effectable\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\n\n/**\n * Unique identifier for Model instances.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport const TypeId = \"~@effect/ai/Model\"\n\n/**\n * Type-level representation of the Model identifier.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * A Model represents a provider-specific AI service.\n *\n * A Model can be used directly as a Layer to provide a particular model\n * implementation to an Effect program.\n *\n * A Model can also be used as an Effect to \"lift\" dependencies of the Model\n * constructor into the parent Effect. This is particularly useful when you\n * want to use a Model from within an Effect service.\n *\n * @template Provider - String literal type identifying the AI provider.\n * @template Provides - Services that this model provides.\n * @template Requires - Services that this model requires.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Model<in out Provider, in out Provides, in out Requires>\n  extends\n    Layer.Layer<Provides | ProviderName, never, Requires>,\n    Effect.Effect<Layer.Layer<Provides | ProviderName>, never, Requires>\n{\n  readonly [TypeId]: TypeId\n  /**\n   * The provider identifier (e.g., \"openai\", \"anthropic\", \"amazon-bedrock\").\n   */\n  readonly provider: Provider\n}\n\n/**\n * Service tag that provides the current large language model provider name.\n *\n * This tag is automatically provided by Model instances and can be used to\n * access the name of the provider that is currently in use within a given\n * Effect program.\n *\n * @since 1.0.0\n * @category Context\n */\nexport class ProviderName extends Context.Tag(\"@effect/ai/Model/ProviderName\")<\n  ProviderName,\n  string\n>() {}\n\nconst ModelProto = {\n  ...CommitPrototype,\n  [TypeId]: TypeId,\n  [Layer.LayerTypeId]: {\n    _ROut: identity,\n    _E: identity,\n    _RIn: identity\n  },\n  commit(this: Model<any, any, any>) {\n    return Effect.contextWith((context: Context.Context<never>) => {\n      return Layer.provide(this, Layer.succeedContext(context))\n    })\n  }\n}\n\n/**\n * Creates a Model from a provider name and a Layer that constructs AI services.\n *\n * @example\n * ```ts\n * import { Model, LanguageModel } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * declare const bedrockLayer: Layer.Layer<LanguageModel.LanguageModel>\n *\n * // Model automatically provides ProviderName service\n * const checkProviderAndGenerate = Effect.gen(function* () {\n *   const provider = yield* Model.ProviderName\n *\n *   console.log(`Generating with: ${provider}`)\n *\n *   return yield* LanguageModel.generateText({\n *     prompt: `Hello from ${provider}!`\n *   })\n * })\n *\n * const program = checkProviderAndGenerate.pipe(\n *   Effect.provide(Model.make(\"amazon-bedrock\", bedrockLayer))\n * )\n * // Will log: \"Generating with: amazon-bedrock\"\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = <const Provider extends string, Provides, Requires>(\n  /**\n   * Provider identifier (e.g., \"openai\", \"anthropic\", \"amazon-bedrock\").\n   */\n  provider: Provider,\n  /**\n   * Layer that provides the AI services for this provider.\n   */\n  layer: Layer.Layer<Provides, never, Requires>\n): Model<Provider, Provides, Requires> =>\n  Object.assign(\n    Object.create(ModelProto),\n    { provider },\n    Layer.merge(Layer.succeed(ProviderName, provider), layer)\n  )\n"
  },
  {
    "path": "packages/ai/ai/src/Prompt.ts",
    "content": "/**\n * The `Prompt` module provides several data structures to simplify creating and\n * combining prompts.\n *\n * This module defines the complete structure of a conversation with a large\n * language model, including messages, content parts, and provider-specific\n * options. It supports rich content types like text, files, tool calls, and\n * reasoning.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * // Create a structured conversation\n * const conversation = Prompt.make([\n *   {\n *     role: \"system\",\n *     content: \"You are a helpful assistant specialized in mathematics.\"\n *   },\n *   {\n *     role: \"user\",\n *     content: [{\n *       type: \"text\",\n *       text: \"What is the derivative of x²?\"\n *     }]\n *   },\n *   {\n *     role: \"assistant\",\n *     content: [{\n *       type: \"text\",\n *       text: \"The derivative of x² is 2x.\"\n *     }]\n *   }\n * ])\n * ```\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * // Merge multiple prompts\n * const systemPrompt = Prompt.make([{\n *   role: \"system\",\n *   content: \"You are a coding assistant.\"\n * }])\n *\n * const userPrompt = Prompt.make(\"Help me write a function\")\n *\n * const combined = Prompt.merge(systemPrompt, userPrompt)\n * ```\n *\n * @since 1.0.0\n */\nimport * as Arbitrary from \"effect/Arbitrary\"\nimport * as Arr from \"effect/Array\"\nimport { constFalse, dual } from \"effect/Function\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as AST from \"effect/SchemaAST\"\nimport type * as Response from \"./Response.js\"\n\nconst constEmptyObject = () => ({})\n\n// =============================================================================\n// Options\n// =============================================================================\n\n/**\n * Schema for provider-specific options which can be attached to both content\n * parts and messages, enabling provider-specific behavior.\n *\n * Provider-specific options are namespaced by provider and have the structure:\n *\n * ```\n * {\n *   \"<provider-specific-key>\": {\n *     // Provider-specific options\n *   }\n * }\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport const ProviderOptions = Schema.Record({\n  key: Schema.String,\n  value: Schema.UndefinedOr(\n    Schema.Record({\n      key: Schema.String,\n      value: Schema.Unknown\n    })\n  )\n})\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type ProviderOptions = typeof ProviderOptions.Type\n\n// =============================================================================\n// Base Part\n// =============================================================================\n\n/**\n * Unique identifier for Part instances.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport const PartTypeId = \"~effect/ai/Prompt/Part\"\n\n/**\n * Type-level representation of the Part identifier.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport type PartTypeId = typeof PartTypeId\n\n/**\n * Type guard to check if a value is a Part.\n *\n * @since 1.0.0\n * @category Guards\n */\nexport const isPart = (u: unknown): u is Part => Predicate.hasProperty(u, PartTypeId)\n\n/**\n * Union type representing all possible content parts within messages.\n *\n * Parts are the building blocks of message content, supporting text, files,\n * reasoning, tool calls, and tool results.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type Part = TextPart | ReasoningPart | FilePart | ToolCallPart | ToolResultPart\n\n/**\n * Encoded representation of a Part.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type PartEncoded =\n  | TextPartEncoded\n  | ReasoningPartEncoded\n  | FilePartEncoded\n  | ToolCallPartEncoded\n  | ToolResultPartEncoded\n\n/**\n * Base interface for all content parts.\n *\n * Provides common structure including type and provider options.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface BasePart<Type extends string, Options extends ProviderOptions> {\n  readonly [PartTypeId]: PartTypeId\n  /**\n   * The type of this content part.\n   */\n  readonly type: Type\n  /**\n   * Provider-specific options for this part.\n   */\n  readonly options: Options\n}\n\n/**\n * Base interface for encoded content parts.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface BasePartEncoded<Type extends string, Options extends ProviderOptions> {\n  /**\n   * The type of this content part.\n   */\n  readonly type: Type\n  /**\n   * Provider-specific options for this part.\n   */\n  readonly options?: Options | undefined\n}\n\n/**\n * Creates a new content part of the specified type.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const textPart = Prompt.makePart(\"text\", {\n *   text: \"Hello, world!\"\n * })\n *\n * const filePart = Prompt.makePart(\"file\", {\n *   mediaType: \"image/png\",\n *   fileName: \"screenshot.png\",\n *   data: new Uint8Array([1, 2, 3])\n * })\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const makePart = <const Type extends Part[\"type\"]>(\n  /**\n   * The type of part to create.\n   */\n  type: Type,\n  /**\n   * Parameters specific to the part type being created.\n   */\n  params: Omit<Extract<Part, { type: Type }>, PartTypeId | \"type\" | \"options\"> & {\n    /**\n     * Optional provider-specific options for this part.\n     */\n    readonly options?: Extract<Part, { type: Type }>[\"options\"] | undefined\n  }\n): Extract<Part, { type: Type }> =>\n  ({\n    ...params,\n    [PartTypeId]: PartTypeId,\n    type,\n    options: params.options ?? {}\n  }) as any\n\n/**\n * A utility type for specifying the parameters required to construct a\n * specific part of a prompt.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type PartConstructorParams<P extends Part> = Omit<P, PartTypeId | \"type\" | \"options\"> & {\n  /**\n   * Optional provider-specific options for this part.\n   */\n  readonly options?: Part[\"options\"] | undefined\n}\n\n// =============================================================================\n// Text Part\n// =============================================================================\n\n/**\n * Content part representing plain text.\n *\n * The most basic content type used for textual information in messages.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const textPart: Prompt.TextPart = Prompt.makePart(\"text\", {\n *   text: \"Hello, how can I help you today?\",\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TextPart extends BasePart<\"text\", TextPartOptions> {\n  /**\n   * The text content.\n   */\n  readonly text: string\n}\n\n/**\n * Encoded representation of text parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TextPartEncoded extends BasePartEncoded<\"text\", TextPartOptions> {\n  /**\n   * The text content.\n   */\n  readonly text: string\n}\n\n/**\n * Represents provider-specific options that can be associated with a\n * `TextPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface TextPartOptions extends ProviderOptions {}\n\n/**\n * Schema for validation and encoding of text parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const TextPart: Schema.Schema<TextPart, TextPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"text\"),\n  text: Schema.String,\n  options: Schema.optionalWith(ProviderOptions, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"TextPart\" })\n)\n\n/**\n * Constructs a new text part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const textPart = (params: PartConstructorParams<TextPart>): TextPart => makePart(\"text\", params)\n\n// =============================================================================\n// Reasoning Part\n// =============================================================================\n\n/**\n * Content part representing reasoning or chain-of-thought.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const reasoningPart: Prompt.ReasoningPart = Prompt.makePart(\"reasoning\", {\n *   text: \"Let me think step by step: First I need to understand the user's question...\",\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ReasoningPart extends BasePart<\"reasoning\", ReasoningPartOptions> {\n  /**\n   * The reasoning or thought process text.\n   */\n  readonly text: string\n}\n\n/**\n * Encoded representation of reasoning parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ReasoningPartEncoded extends BasePartEncoded<\"reasoning\", ReasoningPartOptions> {\n  /**\n   * The reasoning or thought process text.\n   */\n  readonly text: string\n}\n\n/**\n * Represents provider-specific options that can be associated with a\n * `ReasoningPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ReasoningPartOptions extends ProviderOptions {}\n\n/**\n * Schema for validation and encoding of reasoning parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ReasoningPart: Schema.Schema<ReasoningPart, ReasoningPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"reasoning\"),\n  text: Schema.String,\n  options: Schema.optionalWith(ProviderOptions, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ReasoningPart\" })\n)\n\n/**\n * Constructs a new reasoning part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const reasoningPart = (params: PartConstructorParams<ReasoningPart>): ReasoningPart =>\n  makePart(\"reasoning\", params)\n\n// =============================================================================\n// File Part\n// =============================================================================\n\n/**\n * Content part representing a file attachment. Files can be provided as base64\n * strings of data, byte arrays, or URLs.\n *\n * Supports various file types including images, documents, and binary data.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const imagePart: Prompt.FilePart = Prompt.makePart(\"file\", {\n *   mediaType: \"image/jpeg\",\n *   fileName: \"photo.jpg\",\n *   data: \"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...\"\n * })\n *\n * const documentPart: Prompt.FilePart = Prompt.makePart(\"file\", {\n *   mediaType: \"application/pdf\",\n *   fileName: \"report.pdf\",\n *   data: new Uint8Array([1, 2, 3])\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface FilePart extends BasePart<\"file\", FilePartOptions> {\n  /**\n   * MIME type of the file (e.g., \"image/jpeg\", \"application/pdf\").\n   */\n  readonly mediaType: string\n  /**\n   * Optional filename for the file.\n   */\n  readonly fileName?: string | undefined\n  /**\n   * File data as base64 string of data, a byte array, or a URL.\n   */\n  readonly data: string | Uint8Array | URL\n}\n\n/**\n * Encoded representation of file parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface FilePartEncoded extends BasePartEncoded<\"file\", FilePartOptions> {\n  /**\n   * MIME type of the file (e.g., \"image/jpeg\", \"application/pdf\").\n   */\n  readonly mediaType: string\n  /**\n   * Optional filename for the file.\n   */\n  readonly fileName?: string | undefined\n  /**\n   * File data as base64 string of data, a byte array, or a URL.\n   */\n  readonly data: string | Uint8Array | URL\n}\n\n/**\n * Represents provider-specific options that can be associated with a\n * `FilePart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface FilePartOptions extends ProviderOptions {}\n\n/**\n * Schema for validation and encoding of file parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const FilePart: Schema.Schema<FilePart, FilePartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"file\"),\n  mediaType: Schema.String,\n  fileName: Schema.optional(Schema.String),\n  data: Schema.Union(Schema.String, Schema.Uint8ArrayFromSelf, Schema.URLFromSelf),\n  options: Schema.optionalWith(ProviderOptions, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"FilePart\" })\n)\n\n/**\n * Constructs a new file part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const filePart = (params: PartConstructorParams<FilePart>): FilePart => makePart(\"file\", params)\n\n// =============================================================================\n// Tool Call Part\n// =============================================================================\n\n/**\n * Content part representing a tool call request.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const toolCallPart: Prompt.ToolCallPart = Prompt.makePart(\"tool-call\", {\n *   id: \"call_123\",\n *   name: \"get_weather\",\n *   params: { city: \"San Francisco\", units: \"celsius\" },\n *   providerExecuted: false,\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolCallPart extends BasePart<\"tool-call\", ToolCallPartOptions> {\n  /**\n   * Unique identifier for this tool call.\n   */\n  readonly id: string\n  /**\n   * Name of the tool to invoke.\n   */\n  readonly name: string\n  /**\n   * Parameters to pass to the tool.\n   */\n  readonly params: unknown\n  /**\n   * Whether the tool was executed by the provider (true) or framework (false).\n   */\n  readonly providerExecuted: boolean\n}\n\n/**\n * Encoded representation of tool call parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolCallPartEncoded extends BasePartEncoded<\"tool-call\", ToolCallPartOptions> {\n  /**\n   * Unique identifier for this tool call.\n   */\n  readonly id: string\n  /**\n   * Name of the tool to invoke.\n   */\n  readonly name: string\n  /**\n   * Parameters to pass to the tool.\n   */\n  readonly params: unknown\n  /**\n   * Whether the tool was executed by the provider (true) or framework (false).\n   */\n  readonly providerExecuted?: boolean | undefined\n}\n\n/**\n * Represents provider-specific options that can be associated with a\n * `ToolCallPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ToolCallPartOptions extends ProviderOptions {}\n\n/**\n * Schema for validation and encoding of tool call parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ToolCallPart: Schema.Schema<ToolCallPart, ToolCallPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"tool-call\"),\n  id: Schema.String,\n  name: Schema.String,\n  params: Schema.Unknown,\n  providerExecuted: Schema.optionalWith(Schema.Boolean, { default: constFalse }),\n  options: Schema.optionalWith(ProviderOptions, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ToolCallPart\" })\n)\n\n/**\n * Constructs a new tool call part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const toolCallPart = (params: PartConstructorParams<ToolCallPart>): ToolCallPart => makePart(\"tool-call\", params)\n\n// =============================================================================\n// Tool Result Part\n// =============================================================================\n\n/**\n * Content part representing the result of a tool call.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const toolResultPart: Prompt.ToolResultPart = Prompt.makePart(\"tool-result\", {\n *   id: \"call_123\",\n *   name: \"get_weather\",\n *   isFailure: false,\n *   result: {\n *     temperature: 22,\n *     condition: \"sunny\",\n *     humidity: 65\n *   },\n *   providerExecuted: false\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolResultPart extends BasePart<\"tool-result\", ToolResultPartOptions> {\n  /**\n   * Unique identifier matching the original tool call.\n   */\n  readonly id: string\n  /**\n   * Name of the tool that was executed.\n   */\n  readonly name: string\n  /**\n   * Whether or not the result of executing the tool call handler was an error.\n   */\n  readonly isFailure: boolean\n  /**\n   * The result returned by the tool execution.\n   */\n  readonly result: unknown\n  /**\n   * Whether the tool was executed by the provider (true) or framework (false).\n   */\n  readonly providerExecuted: boolean\n}\n\n/**\n * Encoded representation of tool result parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolResultPartEncoded extends BasePartEncoded<\"tool-result\", ToolResultPartOptions> {\n  /**\n   * Unique identifier matching the original tool call.\n   */\n  readonly id: string\n  /**\n   * Name of the tool that was executed.\n   */\n  readonly name: string\n  /**\n   * Whether or not the result of executing the tool call handler was an error.\n   */\n  readonly isFailure: boolean\n  /**\n   * The result returned by the tool execution.\n   */\n  readonly result: unknown\n  /**\n   * Whether the tool was executed by the provider (true) or framework (false).\n   */\n  readonly providerExecuted: boolean\n}\n\n/**\n * Represents provider-specific options that can be associated with a\n * `ToolResultPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ToolResultPartOptions extends ProviderOptions {}\n\n/**\n * Schema for validation and encoding of tool result parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ToolResultPart: Schema.Schema<ToolResultPart, ToolResultPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"tool-result\"),\n  id: Schema.String,\n  name: Schema.String,\n  isFailure: Schema.Boolean,\n  result: Schema.Unknown,\n  providerExecuted: Schema.Boolean,\n  options: Schema.optionalWith(ProviderOptions, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ToolResultPart\" })\n)\n\n/**\n * Constructs a new tool result part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const toolResultPart = (params: PartConstructorParams<ToolResultPart>): ToolResultPart =>\n  makePart(\"tool-result\", params)\n\n// =============================================================================\n// Base Message\n// =============================================================================\n\n/**\n * Unique identifier for Message instances.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport const MessageTypeId = \"~effect/ai/Prompt/Message\"\n\n/**\n * Type-level representation of the Message identifier.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport type MessageTypeId = typeof MessageTypeId\n\n/**\n * Type guard to check if a value is a Message.\n *\n * @since 1.0.0\n * @category Guards\n */\nexport const isMessage = (u: unknown): u is Message => Predicate.hasProperty(u, MessageTypeId)\n\n/**\n * Base interface for all message types.\n *\n * Provides common structure including role and provider options.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface BaseMessage<Role extends string, Options extends ProviderOptions> {\n  readonly [MessageTypeId]: MessageTypeId\n  /**\n   * The role of the message participant.\n   */\n  readonly role: Role\n  /**\n   * Provider-specific options for this message.\n   */\n  readonly options: Options\n}\n\n/**\n * Base interface for encoded message types.\n *\n * @template Role - String literal type for the message role\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface BaseMessageEncoded<Role extends string, Options extends ProviderOptions> {\n  /**\n   * The role of the message participant.\n   */\n  readonly role: Role\n  /**\n   * Provider-specific options for this message.\n   */\n  readonly options?: Options | undefined\n}\n\n/**\n * Creates a new message with the specified role.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const textPart = Prompt.makePart(\"text\", {\n *   text: \"Hello, world!\"\n * })\n *\n * const filePart = Prompt.makeMessage(\"user\", {\n *   content: [textPart]\n * })\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const makeMessage = <const Role extends Message[\"role\"]>(\n  role: Role,\n  params: Omit<Extract<Message, { role: Role }>, MessageTypeId | \"role\" | \"options\"> & {\n    readonly options?: Extract<Message, { role: Role }>[\"options\"]\n  }\n): Extract<Message, { role: Role }> =>\n  ({\n    ...params,\n    [MessageTypeId]: MessageTypeId,\n    role,\n    options: params.options ?? {}\n  }) as any\n\n/**\n * A utility type for specifying the parameters required to construct a\n * specific message for a prompt.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type MessageConstructorParams<M extends Message> = Omit<M, MessageTypeId | \"role\" | \"options\"> & {\n  /**\n   * Optional provider-specific options for this message.\n   */\n  readonly options?: Part[\"options\"] | undefined\n}\n\n/**\n * Schema for decoding message content (i.e. an array containing a single\n * `TextPart`) from a string.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const MessageContentFromString: Schema.Schema<\n  Arr.NonEmptyReadonlyArray<TextPart>,\n  string\n> = Schema.transform(Schema.String, Schema.NonEmptyArray(Schema.typeSchema(TextPart)), {\n  strict: true,\n  decode: (text) => Arr.of(makePart(\"text\", { text })),\n  encode: (content) => content[0].text\n})\n\n// =============================================================================\n// System Message\n// =============================================================================\n\n/**\n * Message representing system instructions or context.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const systemMessage: Prompt.SystemMessage = Prompt.makeMessage(\"system\", {\n *   content: \"You are a helpful assistant specialized in mathematics. \" +\n *    \"Always show your work step by step.\"\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface SystemMessage extends BaseMessage<\"system\", SystemMessageOptions> {\n  /**\n   * The system instruction or context as plain text.\n   */\n  readonly content: string\n}\n\n/**\n * Encoded representation of system messages for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface SystemMessageEncoded extends BaseMessageEncoded<\"system\", SystemMessageOptions> {\n  /**\n   * The system instruction or context as plain text.\n   */\n  readonly content: string\n}\n\n/**\n * Represents provider-specific options that can be associated with a\n * `SystemMessage` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface SystemMessageOptions extends ProviderOptions {}\n\n/**\n * Schema for validation and encoding of system messages.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const SystemMessage: Schema.Schema<SystemMessage, SystemMessageEncoded> = Schema.Struct({\n  role: Schema.Literal(\"system\"),\n  content: Schema.String,\n  options: Schema.optionalWith(ProviderOptions, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(MessageTypeId, MessageTypeId),\n  Schema.annotations({ identifier: \"SystemMessage\" })\n)\n\n/**\n * Constructs a new system message.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const systemMessage = (params: MessageConstructorParams<SystemMessage>): SystemMessage =>\n  makeMessage(\"system\", params)\n\n// =============================================================================\n// User Message\n// =============================================================================\n\n/**\n * Message representing user input or questions.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const textUserMessage: Prompt.UserMessage = Prompt.makeMessage(\"user\", {\n *   content: [\n *     Prompt.makePart(\"text\", {\n *       text: \"Can you analyze this image for me?\"\n *     })\n *   ]\n * })\n *\n * const multimodalUserMessage: Prompt.UserMessage = Prompt.makeMessage(\"user\", {\n *   content: [\n *     Prompt.makePart(\"text\", {\n *       text: \"What do you see in this image?\"\n *     }),\n *     Prompt.makePart(\"file\", {\n *       mediaType: \"image/jpeg\",\n *       fileName: \"vacation.jpg\",\n *       data: \"data:image/jpeg;base64,...\"\n *     })\n *   ]\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface UserMessage extends BaseMessage<\"user\", UserMessageOptions> {\n  /**\n   * Array of content parts that make up the user's message.\n   */\n  readonly content: ReadonlyArray<UserMessagePart>\n}\n\n/**\n * Union type of content parts allowed in user messages.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type UserMessagePart = TextPart | FilePart\n\n/**\n * Encoded representation of user messages for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface UserMessageEncoded extends BaseMessageEncoded<\"user\", UserMessageOptions> {\n  /**\n   * Array of content parts that make up the user's message.\n   */\n  readonly content: string | ReadonlyArray<UserMessagePartEncoded>\n}\n\n/**\n * Union type of encoded content parts for user messages.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type UserMessagePartEncoded = TextPartEncoded | FilePartEncoded\n\n/**\n * Represents provider-specific options that can be associated with a\n * `UserMessage` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface UserMessageOptions extends ProviderOptions {}\n\n/**\n * Schema for validation and encoding of user messages.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const UserMessage: Schema.Schema<UserMessage, UserMessageEncoded> = Schema.Struct({\n  role: Schema.Literal(\"user\"),\n  content: Schema.Union(\n    MessageContentFromString,\n    Schema.Array(Schema.Union(TextPart, FilePart))\n  ),\n  options: Schema.optionalWith(ProviderOptions, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(MessageTypeId, MessageTypeId),\n  Schema.annotations({ identifier: \"UserMessage\" })\n)\n\n/**\n * Constructs a new user message.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const userMessage = (params: MessageConstructorParams<UserMessage>): UserMessage => makeMessage(\"user\", params)\n\n// =============================================================================\n// Assistant Message\n// =============================================================================\n\n/**\n * Message representing large language model assistant responses.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const assistantMessage: Prompt.AssistantMessage = Prompt.makeMessage(\"assistant\", {\n *   content: [\n *     Prompt.makePart(\"text\", {\n *       text: \"The user is asking about the weather. I should use the weather tool.\"\n *     }),\n *     Prompt.makePart(\"tool-call\", {\n *       id: \"call_123\",\n *       name: \"get_weather\",\n *       params: { city: \"San Francisco\" },\n *       providerExecuted: false\n *     }),\n *     Prompt.makePart(\"tool-result\", {\n *       id: \"call_123\",\n *       name: \"get_weather\",\n *       isFailure: false,\n *       result: {\n *         temperature: 72,\n *         condition: \"sunny\"\n *       },\n *       providerExecuted: false\n *     }),\n *     Prompt.makePart(\"text\", {\n *       text: \"The weather in San Francisco is currently 72°F and sunny.\"\n *     })\n *   ]\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface AssistantMessage extends BaseMessage<\"assistant\", AssistantMessageOptions> {\n  /**\n   * Array of content parts that make up the assistant's response.\n   */\n  readonly content: ReadonlyArray<AssistantMessagePart>\n}\n\n/**\n * Union type of content parts allowed in assistant messages.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type AssistantMessagePart =\n  | TextPart\n  | FilePart\n  | ReasoningPart\n  | ToolCallPart\n  | ToolResultPart\n\n/**\n * Encoded representation of assistant messages for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface AssistantMessageEncoded extends BaseMessageEncoded<\"assistant\", AssistantMessageOptions> {\n  readonly content: string | ReadonlyArray<AssistantMessagePartEncoded>\n}\n\n/**\n * Union type of encoded content parts for assistant messages.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type AssistantMessagePartEncoded =\n  | TextPartEncoded\n  | FilePartEncoded\n  | ReasoningPartEncoded\n  | ToolCallPartEncoded\n  | ToolResultPartEncoded\n\n/**\n * Represents provider-specific options that can be associated with a\n * `AssistantMessage` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface AssistantMessageOptions extends ProviderOptions {}\n\n/**\n * Schema for validation and encoding of assistant messages.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const AssistantMessage: Schema.Schema<AssistantMessage, AssistantMessageEncoded> = Schema.Struct({\n  role: Schema.Literal(\"assistant\"),\n  content: Schema.Union(\n    MessageContentFromString,\n    Schema.Array(Schema.Union(TextPart, FilePart, ReasoningPart, ToolCallPart, ToolResultPart))\n  ),\n  options: Schema.optionalWith(ProviderOptions, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(MessageTypeId, MessageTypeId),\n  Schema.annotations({ identifier: \"AssistantMessage\" })\n)\n\n/**\n * Constructs a new assistant message.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const assistantMessage = (params: MessageConstructorParams<AssistantMessage>): AssistantMessage =>\n  makeMessage(\"assistant\", params)\n\n// =============================================================================\n// Tool Message\n// =============================================================================\n\n/**\n * Message representing tool execution results.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const toolMessage: Prompt.ToolMessage = Prompt.makeMessage(\"tool\", {\n *   content: [\n *     Prompt.makePart(\"tool-result\", {\n *       id: \"call_123\",\n *       name: \"search_web\",\n *       isFailure: false,\n *       result: {\n *         query: \"TypeScript best practices\",\n *         results: [\n *           { title: \"TypeScript Handbook\", url: \"https://...\" },\n *           { title: \"Effective TypeScript\", url: \"https://...\" }\n *         ]\n *       },\n *       providerExecuted: false\n *     })\n *   ]\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolMessage extends BaseMessage<\"tool\", ToolMessageOptions> {\n  /**\n   * Array of tool result parts.\n   */\n  readonly content: ReadonlyArray<ToolMessagePart>\n}\n\n/**\n * Union type of content parts allowed in tool messages.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type ToolMessagePart = ToolResultPart\n\n/**\n * Encoded representation of tool messages for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolMessageEncoded extends BaseMessageEncoded<\"tool\", ToolMessageOptions> {\n  /**\n   * Array of tool result parts.\n   */\n  readonly content: ReadonlyArray<ToolMessagePartEncoded>\n}\n\n/**\n * Union type of encoded content parts for tool messages.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type ToolMessagePartEncoded = ToolResultPartEncoded\n\n/**\n * Represents provider-specific options that can be associated with a\n * `ToolMessage` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ToolMessageOptions extends ProviderOptions {}\n\n/**\n * Schema for validation and encoding of tool messages.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ToolMessage: Schema.Schema<ToolMessage, ToolMessageEncoded> = Schema.Struct({\n  role: Schema.Literal(\"tool\"),\n  content: Schema.Array(ToolResultPart),\n  options: Schema.optionalWith(ProviderOptions, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(MessageTypeId, MessageTypeId),\n  Schema.annotations({ identifier: \"ToolMessage\" })\n)\n\n/**\n * Constructs a new tool message.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const toolMessage = (params: MessageConstructorParams<ToolMessage>): ToolMessage => makeMessage(\"tool\", params)\n\n// =============================================================================\n// Message\n// =============================================================================\n\n/**\n * A type representing all possible message types in a conversation.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type Message =\n  | SystemMessage\n  | UserMessage\n  | AssistantMessage\n  | ToolMessage\n\n/**\n * A type representing all possible encoded message types for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type MessageEncoded =\n  | SystemMessageEncoded\n  | UserMessageEncoded\n  | AssistantMessageEncoded\n  | ToolMessageEncoded\n\n/**\n * Schema for validation and encoding of messages.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const Message: Schema.Schema<Message, MessageEncoded> = Schema.Union(\n  SystemMessage,\n  UserMessage,\n  AssistantMessage,\n  ToolMessage\n)\n\n// =============================================================================\n// Prompt\n// =============================================================================\n\n/**\n * Unique identifier for Prompt instances.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport const TypeId = \"~@effect/ai/Prompt\"\n\n/**\n * Type-level representation of the Prompt identifier.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * Type guard to check if a value is a Prompt.\n *\n * @since 1.0.0\n * @category Guards\n */\nexport const isPrompt = (u: unknown): u is Prompt => Predicate.hasProperty(u, TypeId)\n\n/**\n * A Prompt contains a sequence of messages that form the context of a\n * conversation with a large language model.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Prompt extends Pipeable {\n  readonly [TypeId]: TypeId\n  /**\n   * Array of messages that make up the conversation.\n   */\n  readonly content: ReadonlyArray<Message>\n}\n\n/**\n * Encoded representation of prompts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface PromptEncoded {\n  /**\n   * Array of messages that make up the conversation.\n   */\n  readonly content: ReadonlyArray<MessageEncoded>\n}\n\n/**\n * Describes a schema that represents a `Prompt` instance.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class PromptFromSelf extends Schema.declare(\n  (u) => isPrompt(u),\n  {\n    typeConstructor: { _tag: \"effect/ai/Prompt\" },\n    identifier: \"PromptFromSelf\",\n    description: \"a Prompt instance\",\n    arbitrary: (): Arbitrary.LazyArbitrary<Prompt> => (fc) =>\n      fc.array(\n        Arbitrary.makeLazy(Message)(fc)\n      ).map(makePrompt)\n  }\n) {}\n\n/**\n * Schema for validation and encoding of prompts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const Prompt: Schema.Schema<Prompt, PromptEncoded> = Schema.transformOrFail(\n  Schema.Struct({ content: Schema.Array(Schema.encodedSchema(Message)) }),\n  PromptFromSelf,\n  {\n    strict: true,\n    decode: (i, _, ast) => decodePrompt(i, ast),\n    encode: (a, _, ast) => encodePrompt(a, ast)\n  }\n).annotations({ identifier: \"Prompt\" })\n\nconst decodeMessages = ParseResult.decodeEither(Schema.Array(Message))\nconst encodeMessages = ParseResult.encodeEither(Schema.Array(Message))\n\nconst decodePrompt = (input: PromptEncoded, ast: AST.AST) =>\n  ParseResult.mapBoth(decodeMessages(input.content), {\n    onFailure: () => new ParseResult.Type(ast, input, `Unable to decode ${JSON.stringify(input)} into a Prompt`),\n    onSuccess: makePrompt\n  })\n\nconst encodePrompt = (input: Prompt, ast: AST.AST) =>\n  ParseResult.mapBoth(encodeMessages(input.content), {\n    onFailure: () => new ParseResult.Type(ast, input, `Failed to encode Prompt`),\n    onSuccess: (messages) => ({ content: messages })\n  })\n\n/**\n * Schema for parsing a Prompt from JSON strings.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const FromJson = Schema.parseJson(Prompt)\n\n/**\n * Raw input types that can be converted into a Prompt.\n *\n * Supports various input formats for convenience, including simple strings,\n * message arrays, response parts, and existing prompts.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * // String input - creates a user message\n * const stringInput: Prompt.RawInput = \"Hello, world!\"\n *\n * // Message array input\n * const messagesInput: Prompt.RawInput = [\n *   { role: \"system\", content: \"You are helpful.\" },\n *   { role: \"user\", content: [{ type: \"text\", text: \"Hi!\" }] }\n * ]\n *\n * // Existing prompt\n * declare const existingPrompt: Prompt.Prompt\n * const promptInput: Prompt.RawInput = existingPrompt\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport type RawInput =\n  | string\n  | Iterable<MessageEncoded>\n  | Prompt\n\nconst Proto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makePrompt = (content: ReadonlyArray<Message>): Prompt =>\n  Object.assign(Object.create(Proto), {\n    content\n  })\n\nconst decodeMessagesSync = Schema.decodeSync(Schema.Array(Message))\n\n/**\n * An empty prompt with no messages.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const emptyPrompt = Prompt.empty\n * console.log(emptyPrompt.content) // []\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const empty: Prompt = makePrompt([])\n\n/**\n * Creates a Prompt from an input.\n *\n * This is the primary constructor for creating prompts, supporting multiple\n * input formats for convenience and flexibility.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * // From string - creates a user message\n * const textPrompt = Prompt.make(\"Hello, how are you?\")\n *\n * // From messages array\n * const structuredPrompt = Prompt.make([\n *   { role: \"system\", content: \"You are a helpful assistant.\" },\n *   { role: \"user\", content: [{ type: \"text\", text: \"Hi!\" }] }\n * ])\n *\n * // From existing prompt\n * declare const existingPrompt: Prompt.Prompt\n * const copiedPrompt = Prompt.make(existingPrompt)\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (input: RawInput): Prompt => {\n  if (Predicate.isString(input)) {\n    const part = makePart(\"text\", { text: input })\n    const message = makeMessage(\"user\", { content: [part] })\n    return makePrompt([message])\n  }\n\n  if (Predicate.isIterable(input)) {\n    return makePrompt(decodeMessagesSync(Arr.fromIterable(input), {\n      errors: \"all\"\n    }))\n  }\n\n  return input\n}\n\n/**\n * Creates a Prompt from an array of messages.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const messages: ReadonlyArray<Prompt.Message> = [\n *   Prompt.makeMessage(\"system\", {\n *     content: \"You are a coding assistant.\"\n *   }),\n *   Prompt.makeMessage(\"user\", {\n *     content: [Prompt.makePart(\"text\", { text: \"Help me with TypeScript\" })]\n *   })\n * ]\n *\n * const prompt = Prompt.fromMessages(messages)\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const fromMessages = (messages: ReadonlyArray<Message>): Prompt => makePrompt(messages)\n\n/**\n * Creates a Prompt from the response parts of a previous interaction with a\n * large language model.\n *\n * Converts streaming or non-streaming AI response parts into a structured\n * prompt, typically for use in conversation history or further processing.\n *\n * @example\n * ```ts\n * import { Either } from \"effect\"\n * import { Prompt, Response } from \"@effect/ai\"\n *\n * const responseParts: ReadonlyArray<Response.AnyPart> = [\n *   Response.makePart(\"text\", {\n *     text: \"Hello there!\"\n *   }),\n *   Response.makePart(\"tool-call\", {\n *     id: \"call_1\",\n *     name: \"get_time\",\n *     params: {},\n *     providerExecuted: false\n *   }),\n *   Response.makePart(\"tool-result\", {\n *     id: \"call_1\",\n *     name: \"get_time\",\n *     isFailure: false,\n *     result: \"10:30 AM\",\n *     encodedResult: \"10:30 AM\",\n *     providerExecuted: false\n *   })\n * ]\n *\n * const prompt = Prompt.fromResponseParts(responseParts)\n * // Creates an assistant message with the response content\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const fromResponseParts = (parts: ReadonlyArray<Response.AnyPart>): Prompt => {\n  if (parts.length === 0) {\n    return empty\n  }\n\n  const assistantParts: Array<AssistantMessagePart> = []\n  const toolParts: Array<ToolMessagePart> = []\n\n  const activeTextDeltas = new Map<string, { text: string }>()\n  const activeReasoningDeltas = new Map<string, { text: string }>()\n\n  for (const part of parts) {\n    switch (part.type) {\n      // Text Parts\n      case \"text\": {\n        assistantParts.push(makePart(\"text\", { text: part.text }))\n        break\n      }\n\n      // Text Parts (streaming)\n      case \"text-start\": {\n        activeTextDeltas.set(part.id, { text: \"\" })\n        break\n      }\n      case \"text-delta\": {\n        if (activeTextDeltas.has(part.id)) {\n          activeTextDeltas.get(part.id)!.text += part.delta\n        }\n        break\n      }\n      case \"text-end\": {\n        if (activeTextDeltas.has(part.id)) {\n          assistantParts.push(makePart(\"text\", activeTextDeltas.get(part.id)!))\n        }\n        break\n      }\n\n      // Reasoning Parts\n      case \"reasoning\": {\n        assistantParts.push(makePart(\"reasoning\", { text: part.text }))\n        break\n      }\n\n      // Reasoning Parts (streaming)\n      case \"reasoning-start\": {\n        activeReasoningDeltas.set(part.id, { text: \"\" })\n        break\n      }\n      case \"reasoning-delta\": {\n        if (activeReasoningDeltas.has(part.id)) {\n          activeReasoningDeltas.get(part.id)!.text += part.delta\n        }\n        break\n      }\n      case \"reasoning-end\": {\n        if (activeReasoningDeltas.has(part.id)) {\n          assistantParts.push(makePart(\"reasoning\", activeReasoningDeltas.get(part.id)!))\n        }\n        break\n      }\n\n      // Tool Call Parts\n      case \"tool-call\": {\n        assistantParts.push(makePart(\"tool-call\", {\n          id: part.id,\n          name: part.providerName ?? part.name,\n          params: part.params,\n          providerExecuted: part.providerExecuted ?? false\n        }))\n        break\n      }\n\n      // Tool Result Parts\n      case \"tool-result\": {\n        const toolPart = makePart(\"tool-result\", {\n          id: part.id,\n          name: part.providerName ?? part.name,\n          isFailure: part.isFailure,\n          result: part.encodedResult,\n          providerExecuted: part.providerExecuted ?? false\n        })\n        if (part.providerExecuted) {\n          assistantParts.push(toolPart)\n        } else {\n          toolParts.push(toolPart)\n        }\n      }\n    }\n  }\n\n  if (assistantParts.length === 0 && toolParts.length === 0) {\n    return empty\n  }\n\n  const messages: Array<Message> = []\n\n  if (assistantParts.length > 0) {\n    messages.push(makeMessage(\"assistant\", { content: assistantParts }))\n  }\n\n  if (toolParts.length > 0) {\n    messages.push(makeMessage(\"tool\", { content: toolParts }))\n  }\n\n  return makePrompt(messages)\n}\n\n// =============================================================================\n// Merging Prompts\n// =============================================================================\n\n/**\n * Merges a prompt with additional raw input by concatenating messages.\n *\n * Creates a new prompt containing all messages from both the original prompt,\n * and the provided raw input, maintaining the order of messages.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const systemPrompt = Prompt.make([{\n *   role: \"system\",\n *   content: \"You are a helpful assistant.\"\n * }])\n *\n * const merged = Prompt.merge(systemPrompt, \"Hello, world!\")\n * ```\n *\n * @since 1.0.0\n * @category Combinators\n */\nexport const merge: {\n  (input: RawInput): (self: Prompt) => Prompt\n  (self: Prompt, input: RawInput): Prompt\n} = dual(2, (self: Prompt, input: RawInput): Prompt => {\n  const other = make(input)\n  if (self.content.length === 0) {\n    return other\n  }\n  if (other.content.length === 0) {\n    return self\n  }\n  return fromMessages([...self.content, ...other.content])\n})\n\n// =============================================================================\n// Manipulating Prompts\n// =============================================================================\n\n/**\n * Creates a new prompt from the specified prompt with the system message set\n * to the specified text content.\n *\n * **NOTE**: This method will remove and replace any previous system message\n * from the prompt.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const systemPrompt = Prompt.make([{\n *   role: \"system\",\n *   content: \"You are a helpful assistant.\"\n * }])\n *\n * const userPrompt = Prompt.make(\"Hello, world!\")\n *\n * const prompt = Prompt.merge(systemPrompt, userPrompt)\n *\n * const replaced = Prompt.setSystem(\n *   prompt,\n *   \"You are an expert in programming\"\n * )\n * ```\n *\n * @since 1.0.0\n * @category Combinators\n */\nexport const setSystem: {\n  (content: string): (self: Prompt) => Prompt\n  (self: Prompt, content: string): Prompt\n} = dual(2, (self: Prompt, content: string): Prompt => {\n  const messages: Array<Message> = [makeMessage(\"system\", { content })]\n  for (const message of self.content) {\n    if (message.role !== \"system\") {\n      messages.push(message)\n    }\n  }\n  return makePrompt(messages)\n})\n\n/**\n * Creates a new prompt from the specified prompt with the provided text content\n * prepended to the start of existing system message content.\n *\n * If no system message exists in the specified prompt, the provided content\n * will be used to create a system message.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const systemPrompt = Prompt.make([{\n *   role: \"system\",\n *   content: \"You are an expert in programming.\"\n * }])\n *\n * const userPrompt = Prompt.make(\"Hello, world!\")\n *\n * const prompt = Prompt.merge(systemPrompt, userPrompt)\n *\n * const replaced = Prompt.prependSystem(\n *   prompt,\n *   \"You are a helpful assistant. \"\n * )\n * // result content: \"You are a helpful assistant. You are an expert in programming.\"\n * ```\n *\n * @since 1.0.0\n * @category Combinators\n */\nexport const prependSystem: {\n  (content: string): (self: Prompt) => Prompt\n  (self: Prompt, content: string): Prompt\n} = dual(2, (self: Prompt, content: string): Prompt => {\n  let system: SystemMessage | undefined = undefined\n  for (const message of self.content) {\n    if (message.role === \"system\") {\n      system = makeMessage(\"system\", {\n        content: content + message.content\n      })\n      break\n    }\n  }\n  if (Predicate.isUndefined(system)) {\n    system = makeMessage(\"system\", { content })\n  }\n  return makePrompt([system, ...self.content])\n})\n\n/**\n * Creates a new prompt from the specified prompt with the provided text content\n * appended to the end of existing system message content.\n *\n * If no system message exists in the specified prompt, the provided content\n * will be used to create a system message.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * const systemPrompt = Prompt.make([{\n *   role: \"system\",\n *   content: \"You are an expert in programming.\"\n * }])\n *\n * const userPrompt = Prompt.make(\"Hello, world!\")\n *\n * const prompt = Prompt.merge(systemPrompt, userPrompt)\n *\n * const replaced = Prompt.appendSystem(\n *   prompt,\n *   \" You are a helpful assistant.\"\n * )\n * // result content: \"You are an expert in programming. You are a helpful assistant.\"\n * ```\n *\n * @since 1.0.0\n * @category Combinators\n */\nexport const appendSystem: {\n  (content: string): (self: Prompt) => Prompt\n  (self: Prompt, content: string): Prompt\n} = dual(2, (self: Prompt, content: string): Prompt => {\n  let system: SystemMessage | undefined = undefined\n  for (const message of self.content) {\n    if (message.role === \"system\") {\n      system = makeMessage(\"system\", {\n        content: message.content + content\n      })\n      break\n    }\n  }\n  if (Predicate.isUndefined(system)) {\n    system = makeMessage(\"system\", { content })\n  }\n  return makePrompt([system, ...self.content])\n})\n"
  },
  {
    "path": "packages/ai/ai/src/Response.ts",
    "content": "/**\n * The `Response` module provides data structures to represent responses from\n * large language models.\n *\n * This module defines the complete structure of AI model responses, including\n * various content parts for text, reasoning, tool calls, files, and metadata,\n * supporting both streaming and non-streaming responses.\n *\n * @example\n * ```ts\n * import { Response } from \"@effect/ai\"\n *\n * // Create a simple text response part\n * const textResponse = Response.makePart(\"text\", {\n *   text: \"The weather is sunny today!\"\n * })\n *\n * // Create a tool call response part\n * const toolCallResponse = Response.makePart(\"tool-call\", {\n *   id: \"call_123\",\n *   name: \"get_weather\",\n *   params: { city: \"San Francisco\" },\n *   providerExecuted: false\n * })\n * ```\n *\n * @since 1.0.0\n */\nimport type * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport { constFalse } from \"effect/Function\"\nimport type * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Tool from \"./Tool.js\"\nimport type * as Toolkit from \"./Toolkit.js\"\n\nconst constEmptyObject = () => ({})\n\n// =============================================================================\n// All Parts\n// =============================================================================\n\n/**\n * Unique identifier for Response Part instances.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport const PartTypeId = \"~effect/ai/Content/Part\"\n\n/**\n * Type-level representation of the Response Part identifier.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport type PartTypeId = typeof PartTypeId\n\n/**\n * Type guard to check if a value is a Response Part.\n *\n * @since 1.0.0\n * @category Guards\n */\nexport const isPart = (u: unknown): u is AnyPart => Predicate.hasProperty(u, PartTypeId)\n\n/**\n * Union type representing all possible response content parts.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type AnyPart =\n  | TextPart\n  | TextStartPart\n  | TextDeltaPart\n  | TextEndPart\n  | ReasoningPart\n  | ReasoningStartPart\n  | ReasoningDeltaPart\n  | ReasoningEndPart\n  | ToolParamsStartPart\n  | ToolParamsDeltaPart\n  | ToolParamsEndPart\n  | ToolCallPart<any, any>\n  | ToolResultPart<any, any, any>\n  | FilePart\n  | DocumentSourcePart\n  | UrlSourcePart\n  | ResponseMetadataPart\n  | FinishPart\n  | ErrorPart\n\n/**\n * Encoded representation of all possible response content parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type AnyPartEncoded =\n  | TextPartEncoded\n  | TextStartPartEncoded\n  | TextDeltaPartEncoded\n  | TextEndPartEncoded\n  | ReasoningPartEncoded\n  | ReasoningStartPartEncoded\n  | ReasoningDeltaPartEncoded\n  | ReasoningEndPartEncoded\n  | ToolParamsStartPartEncoded\n  | ToolParamsDeltaPartEncoded\n  | ToolParamsEndPartEncoded\n  | ToolCallPartEncoded\n  | ToolResultPartEncoded\n  | FilePartEncoded\n  | DocumentSourcePartEncoded\n  | UrlSourcePartEncoded\n  | ResponseMetadataPartEncoded\n  | FinishPartEncoded\n  | ErrorPartEncoded\n\n/**\n * Union type for all response parts with tool-specific typing.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type AllParts<Tools extends Record<string, Tool.Any>> =\n  | TextPart\n  | TextStartPart\n  | TextDeltaPart\n  | TextEndPart\n  | ReasoningPart\n  | ReasoningStartPart\n  | ReasoningDeltaPart\n  | ReasoningEndPart\n  | ToolParamsStartPart\n  | ToolParamsDeltaPart\n  | ToolParamsEndPart\n  | ToolCallParts<Tools>\n  | ToolResultParts<Tools>\n  | FilePart\n  | DocumentSourcePart\n  | UrlSourcePart\n  | ResponseMetadataPart\n  | FinishPart\n  | ErrorPart\n\n/**\n * Encoded representation of all response parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type AllPartsEncoded =\n  | TextPartEncoded\n  | TextStartPartEncoded\n  | TextDeltaPartEncoded\n  | TextEndPartEncoded\n  | ReasoningPartEncoded\n  | ReasoningStartPartEncoded\n  | ReasoningDeltaPartEncoded\n  | ReasoningEndPartEncoded\n  | ToolParamsStartPartEncoded\n  | ToolParamsDeltaPartEncoded\n  | ToolParamsEndPartEncoded\n  | ToolCallPartEncoded\n  | ToolResultPartEncoded\n  | FilePartEncoded\n  | DocumentSourcePartEncoded\n  | UrlSourcePartEncoded\n  | ResponseMetadataPartEncoded\n  | FinishPartEncoded\n  | ErrorPartEncoded\n\n/**\n * Creates a Schema for all response parts based on a toolkit.\n *\n * Generates a schema that includes all possible response parts, with tool call\n * and tool result parts dynamically created based on the provided toolkit.\n *\n * @example\n * ```ts\n * import { Response, Tool, Toolkit } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * const myToolkit = Toolkit.make(\n *   Tool.make(\"GetWeather\", {\n *     parameters: { city: Schema.String },\n *     success: Schema.Struct({ temperature: Schema.Number })\n *   })\n * )\n *\n * const allPartsSchema = Response.AllParts(myToolkit)\n * ```\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const AllParts = <T extends Toolkit.Any | Toolkit.WithHandler<any>>(\n  toolkit: T\n): Schema.Schema<AllParts<T extends Toolkit.Any ? Toolkit.Tools<T> : Toolkit.WithHandlerTools<T>>, AllPartsEncoded> => {\n  const toolCalls: Array<Schema.Schema<ToolCallPart<string, any>, ToolCallPartEncoded>> = []\n  const toolCallResults: Array<Schema.Schema<ToolResultPart<string, any, any>, ToolResultPartEncoded>> = []\n  for (const tool of Object.values(toolkit.tools as Record<string, Tool.Any>)) {\n    toolCalls.push(ToolCallPart(tool.name, tool.parametersSchema as any))\n    toolCallResults.push(ToolResultPart(tool.name, tool.successSchema, tool.failureSchema))\n  }\n  return Schema.Union(\n    TextPart,\n    TextStartPart,\n    TextDeltaPart,\n    TextEndPart,\n    ReasoningPart,\n    ReasoningStartPart,\n    ReasoningDeltaPart,\n    ReasoningEndPart,\n    ToolParamsStartPart,\n    ToolParamsDeltaPart,\n    ToolParamsEndPart,\n    FilePart,\n    DocumentSourcePart,\n    UrlSourcePart,\n    ResponseMetadataPart,\n    FinishPart,\n    ErrorPart,\n    ...toolCalls,\n    ...toolCallResults\n  ) as any\n}\n\n// =============================================================================\n// Generate Parts\n// =============================================================================\n\n/**\n * A type for representing non-streaming response parts with tool-specific\n * typing.\n *\n * @template Tools - Record of tools with their schemas\n *\n * @since 1.0.0\n * @category Models\n */\nexport type Part<Tools extends Record<string, Tool.Any>> =\n  | TextPart\n  | ReasoningPart\n  | ToolCallParts<Tools>\n  | ToolResultParts<Tools>\n  | FilePart\n  | DocumentSourcePart\n  | UrlSourcePart\n  | ResponseMetadataPart\n  | FinishPart\n\n/**\n * Encoded representation of non-streaming response parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type PartEncoded =\n  | TextPartEncoded\n  | ReasoningPartEncoded\n  | ReasoningDeltaPartEncoded\n  | ReasoningEndPartEncoded\n  | ToolCallPartEncoded\n  | ToolResultPartEncoded\n  | FilePartEncoded\n  | DocumentSourcePartEncoded\n  | UrlSourcePartEncoded\n  | ResponseMetadataPartEncoded\n  | FinishPartEncoded\n\n/**\n * Creates a Schema for non-streaming response parts based on a toolkit.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const Part = <T extends Toolkit.Any | Toolkit.WithHandler<any>>(\n  toolkit: T\n): Schema.Schema<Part<T extends Toolkit.Any ? Toolkit.Tools<T> : Toolkit.WithHandlerTools<T>>, PartEncoded> => {\n  const toolCalls: Array<Schema.Schema<ToolCallPart<string, any>, ToolCallPartEncoded>> = []\n  const toolCallResults: Array<Schema.Schema<ToolResultPart<string, any, any>, ToolResultPartEncoded>> = []\n  for (const tool of Object.values(toolkit.tools as Record<string, Tool.Any>)) {\n    toolCalls.push(ToolCallPart(tool.name, tool.parametersSchema as any))\n    toolCallResults.push(ToolResultPart(tool.name, tool.successSchema, tool.failureSchema))\n  }\n  return Schema.Union(\n    TextPart,\n    ReasoningPart,\n    FilePart,\n    DocumentSourcePart,\n    UrlSourcePart,\n    ResponseMetadataPart,\n    FinishPart,\n    ...toolCalls,\n    ...toolCallResults\n  ) as any\n}\n\n// =============================================================================\n// Stream Parts\n// =============================================================================\n\n/**\n * A type for representing streaming response parts with tool-specific typing.\n *\n * @template Tools - Record of tools with their schemas\n *\n * @since 1.0.0\n * @category Models\n */\nexport type StreamPart<Tools extends Record<string, Tool.Any>> =\n  | TextStartPart\n  | TextDeltaPart\n  | TextEndPart\n  | ReasoningStartPart\n  | ReasoningDeltaPart\n  | ReasoningEndPart\n  | ToolParamsStartPart\n  | ToolParamsDeltaPart\n  | ToolParamsEndPart\n  | ToolCallParts<Tools>\n  | ToolResultParts<Tools>\n  | FilePart\n  | DocumentSourcePart\n  | UrlSourcePart\n  | ResponseMetadataPart\n  | FinishPart\n  | ErrorPart\n\n/**\n * Encoded representation of streaming response parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type StreamPartEncoded =\n  | TextStartPartEncoded\n  | TextDeltaPartEncoded\n  | TextEndPartEncoded\n  | ReasoningStartPartEncoded\n  | ReasoningDeltaPartEncoded\n  | ReasoningEndPartEncoded\n  | ToolParamsStartPartEncoded\n  | ToolParamsDeltaPartEncoded\n  | ToolParamsEndPartEncoded\n  | ToolCallPartEncoded\n  | ToolResultPartEncoded\n  | FilePartEncoded\n  | DocumentSourcePartEncoded\n  | UrlSourcePartEncoded\n  | ResponseMetadataPartEncoded\n  | FinishPartEncoded\n  | ErrorPartEncoded\n\n/**\n * Creates a Schema for streaming response parts based on a toolkit.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const StreamPart = <T extends Toolkit.Any | Toolkit.WithHandler<any>>(\n  toolkit: T\n): Schema.Schema<\n  StreamPart<\n    T extends Toolkit.Any ? Toolkit.Tools<T> : Toolkit.WithHandlerTools<T>\n  >,\n  StreamPartEncoded\n> => {\n  const toolCalls: Array<Schema.Schema<ToolCallPart<string, any>, ToolCallPartEncoded>> = []\n  const toolCallResults: Array<Schema.Schema<ToolResultPart<string, any, any>, ToolResultPartEncoded>> = []\n  for (const tool of Object.values(toolkit.tools as Record<string, Tool.Any>)) {\n    toolCalls.push(ToolCallPart(tool.name, tool.parametersSchema as any))\n    toolCallResults.push(ToolResultPart(tool.name, tool.successSchema, tool.failureSchema))\n  }\n  return Schema.Union(\n    TextStartPart,\n    TextDeltaPart,\n    TextEndPart,\n    ReasoningStartPart,\n    ReasoningDeltaPart,\n    ReasoningEndPart,\n    ToolParamsStartPart,\n    ToolParamsDeltaPart,\n    ToolParamsEndPart,\n    FilePart,\n    DocumentSourcePart,\n    UrlSourcePart,\n    ResponseMetadataPart,\n    FinishPart,\n    ErrorPart,\n    ...toolCalls,\n    ...toolCallResults\n  ) as any\n}\n\n// =============================================================================\n// Utility Types\n// =============================================================================\n\n/**\n * Utility type that extracts tool call parts from a set of tools.\n *\n * @template Tools - Record of tools with their schemas\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type ToolCallParts<Tools extends Record<string, Tool.Any>> = {\n  [Name in keyof Tools]: Name extends string ?\n    ToolCallPart<Name, Schema.Struct.Type<Tool.ParametersSchema<Tools[Name]>[\"fields\"]>>\n    : never\n}[keyof Tools]\n\n/**\n * Utility type that extracts tool result parts from a set of tools.\n *\n * @template Tools - Record of tools with their schemas\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type ToolResultParts<Tools extends Record<string, Tool.Any>> = {\n  [Name in keyof Tools]: Name extends string ? ToolResultPart<\n      Name,\n      Tool.Success<Tools[Name]>,\n      Tool.Failure<Tools[Name]>\n    >\n    : never\n}[keyof Tools]\n\n// =============================================================================\n// Base Part\n// =============================================================================\n\n/**\n * Schema for provider-specific metadata which can be attached to response parts.\n *\n * Provider-specific metadata is namespaced by provider and has the structure:\n *\n * ```\n * {\n *   \"<provider-specific-key>\": {\n *     // Provider-specific metadata\n *   }\n * }\n * ```\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ProviderMetadata = Schema.Record({\n  key: Schema.String,\n  value: Schema.UndefinedOr(Schema.Record({\n    key: Schema.String,\n    value: Schema.Unknown\n  }))\n})\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type ProviderMetadata = typeof ProviderMetadata.Type\n\n/**\n * Base interface for all response content parts.\n *\n * Provides common structure including type identifier and optional metadata.\n *\n * @template Type - String literal type for the part type\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface BasePart<Type extends string, Metadata extends ProviderMetadata> {\n  readonly [PartTypeId]: PartTypeId\n  /**\n   * The type of this response part.\n   */\n  readonly type: Type\n  /**\n   * Optional provider-specific metadata for this part.\n   */\n  readonly metadata: Metadata\n}\n\n/**\n * Base interface for encoded response content parts.\n *\n * @template Type - String literal type for the part type\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface BasePartEncoded<Type extends string, Metadata extends ProviderMetadata> {\n  /**\n   * The type of this response part.\n   */\n  readonly type: Type\n  /**\n   * Optional provider-specific metadata for this part.\n   */\n  readonly metadata?: Metadata | undefined\n}\n\n/**\n * Creates a new response content part of the specified type.\n *\n * @example\n * ```ts\n * import { Response } from \"@effect/ai\"\n *\n * const textPart = Response.makePart(\"text\", {\n *   text: \"Hello, world!\"\n * })\n *\n * const toolCallPart = Response.makePart(\"tool-call\", {\n *   id: \"call_123\",\n *   name: \"get_weather\",\n *   params: { city: \"San Francisco\" },\n *   providerExecuted: false\n * })\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const makePart = <const Type extends AnyPart[\"type\"]>(\n  /**\n   * The type of part to create.\n   */\n  type: Type,\n  /**\n   * Parameters specific to the part type being created.\n   */\n  params: Omit<Extract<AnyPart, { type: Type }>, PartTypeId | \"type\" | \"metadata\"> & {\n    /**\n     * Optional provider-specific metadata for this part.\n     */\n    readonly metadata?: Extract<AnyPart, { type: Type }>[\"metadata\"] | undefined\n  }\n): Extract<AnyPart, { type: Type }> =>\n  ({\n    ...params,\n    [PartTypeId]: PartTypeId,\n    type,\n    metadata: params.metadata ?? {}\n  }) as any\n\n/**\n * A utility type for specifying the parameters required to construct a\n * specific response part.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type ConstructorParams<Part extends AnyPart> = Omit<Part, PartTypeId | \"type\" | \"sourceType\" | \"metadata\"> & {\n  /**\n   * Optional provider-specific metadata for this part.\n   */\n  readonly metadata?: Part[\"metadata\"] | undefined\n}\n\n// =============================================================================\n// Text Part\n// =============================================================================\n\n/**\n * Response part representing plain text content.\n *\n * @example\n * ```ts\n * import { Response } from \"@effect/ai\"\n *\n * const textPart: Response.TextPart = Response.makePart(\"text\", {\n *   text: \"The answer to your question is 42.\",\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TextPart extends BasePart<\"text\", TextPartMetadata> {\n  /**\n   * The text content.\n   */\n  readonly text: string\n}\n\n/**\n * Encoded representation of text parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TextPartEncoded extends BasePartEncoded<\"text\", TextPartMetadata> {\n  /**\n   * The text content.\n   */\n  readonly text: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `TextPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface TextPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of text parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const TextPart: Schema.Schema<TextPart, TextPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"text\"),\n  text: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"TextPart\" })\n)\n\n/**\n * Constructs a new text part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const textPart = (params: ConstructorParams<TextPart>): TextPart => makePart(\"text\", params)\n\n// =============================================================================\n// Text Start Part\n// =============================================================================\n\n/**\n * Response part indicating the start of streaming text content.\n *\n * Marks the beginning of a text chunk with a unique identifier.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TextStartPart extends BasePart<\"text-start\", TextStartPartMetadata> {\n  /**\n   * Unique identifier for this text chunk.\n   */\n  readonly id: string\n}\n\n/**\n * Encoded representation of text start parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TextStartPartEncoded extends BasePartEncoded<\"text-start\", TextStartPartMetadata> {\n  /**\n   * Unique identifier for this text chunk.\n   */\n  readonly id: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `TextStartPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface TextStartPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of text start parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const TextStartPart: Schema.Schema<TextStartPart, TextStartPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"text-start\"),\n  id: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"TextStartPart\" })\n)\n\n/**\n * Constructs a new text start part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const textStartPart = (params: ConstructorParams<TextStartPart>): TextStartPart => makePart(\"text-start\", params)\n\n// =============================================================================\n// Text Delta Part\n// =============================================================================\n\n/**\n * Response part containing incremental text content to be added to the existing\n * text chunk with the same unique identifier.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TextDeltaPart extends BasePart<\"text-delta\", TextDeltaPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding text chunk.\n   */\n  readonly id: string\n  /**\n   * The incremental text content to add.\n   */\n  readonly delta: string\n}\n\n/**\n * Encoded representation of text delta parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TextDeltaPartEncoded extends BasePartEncoded<\"text-delta\", TextDeltaPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding text chunk.\n   */\n  readonly id: string\n  /**\n   * The incremental text content to add.\n   */\n  readonly delta: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `TextDeltaPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface TextDeltaPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of text delta parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const TextDeltaPart: Schema.Schema<TextDeltaPart, TextDeltaPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"text-delta\"),\n  id: Schema.String,\n  delta: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"TextDeltaPart\" })\n)\n\n/**\n * Constructs a new text delta part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const textDeltaPart = (params: ConstructorParams<TextDeltaPart>): TextDeltaPart => makePart(\"text-delta\", params)\n\n// =============================================================================\n// Text End Part\n// =============================================================================\n\n/**\n * Response part indicating the end of streaming text content.\n *\n * Marks the completion of a text chunk.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TextEndPart extends BasePart<\"text-end\", TextEndPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding text chunk.\n   */\n  readonly id: string\n}\n\n/**\n * Encoded representation of text end parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TextEndPartEncoded extends BasePartEncoded<\"text-end\", TextEndPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding text chunk.\n   */\n  readonly id: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `TextEndPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface TextEndPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of text end parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const TextEndPart: Schema.Schema<TextEndPart, TextEndPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"text-end\"),\n  id: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"TextEndPart\" })\n)\n\n/**\n * Constructs a new text end part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const textEndPart = (params: ConstructorParams<TextEndPart>): TextEndPart => makePart(\"text-end\", params)\n\n// =============================================================================\n// Reasoning Part\n// =============================================================================\n\n/**\n * Response part representing reasoning or chain-of-thought content.\n *\n * Contains the internal reasoning process or explanation from the large\n * language model.\n *\n * @example\n * ```ts\n * import { Response } from \"@effect/ai\"\n *\n * const reasoningPart: Response.ReasoningPart = Response.makePart(\"reasoning\", {\n *   text: \"Let me think step by step: First I need to analyze the user's question...\",\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ReasoningPart extends BasePart<\"reasoning\", ReasoningPartMetadata> {\n  /**\n   * The reasoning or thought process text.\n   */\n  readonly text: string\n}\n\n/**\n * Encoded representation of reasoning parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ReasoningPartEncoded extends BasePartEncoded<\"reasoning\", ReasoningPartMetadata> {\n  /**\n   * The reasoning or thought process text.\n   */\n  readonly text: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ReasoningPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ReasoningPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of reasoning parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ReasoningPart: Schema.Schema<ReasoningPart, ReasoningPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"reasoning\"),\n  text: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ReasoningPart\" })\n)\n\n/**\n * Constructs a new reasoning part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const reasoningPart = (params: ConstructorParams<ReasoningPart>): ReasoningPart => makePart(\"reasoning\", params)\n\n// =============================================================================\n// Reasoning Start Part\n// =============================================================================\n\n/**\n * Response part indicating the start of streaming reasoning content.\n *\n * Marks the beginning of a reasoning chunk with a unique identifier.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ReasoningStartPart extends BasePart<\"reasoning-start\", ReasoningStartPartMetadata> {\n  /**\n   * Unique identifier for this reasoning chunk.\n   */\n  readonly id: string\n}\n\n/**\n * Encoded representation of reasoning start parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ReasoningStartPartEncoded extends BasePartEncoded<\"reasoning-start\", ReasoningStartPartMetadata> {\n  /**\n   * Unique identifier for this reasoning stream.\n   */\n  readonly id: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ReasoningStartPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ReasoningStartPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of reasoning start parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ReasoningStartPart: Schema.Schema<ReasoningStartPart, ReasoningStartPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"reasoning-start\"),\n  id: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ReasoningStartPart\" })\n)\n\n/**\n * Constructs a new reasoning start part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const reasoningStartPart = (params: ConstructorParams<ReasoningStartPart>): ReasoningStartPart =>\n  makePart(\"reasoning-start\", params)\n\n// =============================================================================\n// Reasoning Delta Part\n// =============================================================================\n\n/**\n * Response part containing incremental reasoning content to be added to the\n * existing chunk of reasoning text with the same unique identifier.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ReasoningDeltaPart extends BasePart<\"reasoning-delta\", ReasoningDeltaPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding reasoning chunk.\n   */\n  readonly id: string\n  /**\n   * The incremental reasoning content to add.\n   */\n  readonly delta: string\n}\n\n/**\n * Encoded representation of reasoning delta parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ReasoningDeltaPartEncoded extends BasePartEncoded<\"reasoning-delta\", ReasoningDeltaPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding reasoning chunk.\n   */\n  readonly id: string\n  /**\n   * The incremental reasoning content to add.\n   */\n  readonly delta: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ReasoningDeltaPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ReasoningDeltaPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of reasoning delta parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ReasoningDeltaPart: Schema.Schema<ReasoningDeltaPart, ReasoningDeltaPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"reasoning-delta\"),\n  id: Schema.String,\n  delta: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ReasoningDeltaPart\" })\n)\n\n/**\n * Constructs a new reasoning delta part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const reasoningDeltaPart = (params: ConstructorParams<ReasoningDeltaPart>): ReasoningDeltaPart =>\n  makePart(\"reasoning-delta\", params)\n\n// =============================================================================\n// Reasoning End Part\n// =============================================================================\n\n/**\n * Response part indicating the end of streaming reasoning content.\n *\n * Marks the completion of a chunk of reasoning content.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ReasoningEndPart extends BasePart<\"reasoning-end\", ReasoningEndPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding reasoning chunk.\n   */\n  readonly id: string\n}\n\n/**\n * Encoded representation of reasoning end parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ReasoningEndPartEncoded extends BasePartEncoded<\"reasoning-end\", ReasoningEndPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding reasoning chunk.\n   */\n  readonly id: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ReasoningEndPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ReasoningEndPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of reasoning end parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ReasoningEndPart: Schema.Schema<ReasoningEndPart, ReasoningEndPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"reasoning-end\"),\n  id: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ReasoningEndPart\" })\n)\n\n/**\n * Constructs a new reasoning end part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const reasoningEndPart = (params: ConstructorParams<ReasoningEndPart>): ReasoningEndPart =>\n  makePart(\"reasoning-end\", params)\n\n// =============================================================================\n// Tool Params Start Part\n// =============================================================================\n\n/**\n * Response part indicating the start of streaming tool parameters.\n *\n * Marks the beginning of tool parameter streaming with metadata about the tool\n * call.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolParamsStartPart extends BasePart<\"tool-params-start\", ToolParamsStartPartMetadata> {\n  /**\n   * Unique identifier for this tool parameter chunk.\n   */\n  readonly id: string\n  /**\n   * Name of the tool being called, which corresponds to the name of the tool\n   * in the `Toolkit` included with the request.\n   */\n  readonly name: string\n  /**\n   * Optional provider-specific name for the tool, which can be useful when the\n   * name of the tool in the `Toolkit` and the name of the tool used by the\n   * model are different.\n   *\n   * This is usually happens only with provider-defined tools which require a\n   * user-space handler.\n   */\n  readonly providerName?: string | undefined\n  /**\n   * Whether the tool was executed by the provider (true) or framework (false).\n   */\n  readonly providerExecuted: boolean\n}\n\n/**\n * Encoded representation of tool params start parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolParamsStartPartEncoded extends BasePartEncoded<\"tool-params-start\", ToolParamsStartPartMetadata> {\n  /**\n   * Unique identifier for this tool parameter chunk.\n   */\n  readonly id: string\n  /**\n   * Name of the tool being called, which corresponds to the name of the tool\n   * in the `Toolkit` included with the request.\n   */\n  readonly name: string\n  /**\n   * Optional provider-specific name for the tool, which can be useful when the\n   * name of the tool in the `Toolkit` and the name of the tool used by the\n   * model are different.\n   *\n   * This is usually happens only with provider-defined tools which require a\n   * user-space handler.\n   */\n  readonly providerName?: string | undefined\n  /**\n   * Whether the tool was executed by the provider (true) or framework (false).\n   */\n  readonly providerExecuted?: boolean\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ToolParamsStartPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ToolParamsStartPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of tool params start parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ToolParamsStartPart: Schema.Schema<ToolParamsStartPart, ToolParamsStartPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"tool-params-start\"),\n  id: Schema.String,\n  name: Schema.String,\n  providerName: Schema.optional(Schema.String),\n  providerExecuted: Schema.optionalWith(Schema.Boolean, { default: constFalse }),\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ToolParamsStartPart\" })\n)\n\n/**\n * Constructs a new tool params start part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const toolParamsStartPart = (params: ConstructorParams<ToolParamsStartPart>): ToolParamsStartPart =>\n  makePart(\"tool-params-start\", params)\n\n// =============================================================================\n// Tool Params Delta Part\n// =============================================================================\n\n/**\n * Response part containing incremental tool parameter content.\n *\n * Represents a chunk of tool parameters being streamed, containing the\n * incremental JSON content that forms the tool parameters.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolParamsDeltaPart extends BasePart<\"tool-params-delta\", ToolParamsDeltaPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding tool parameter chunk.\n   */\n  readonly id: string\n  /**\n   * The incremental parameter content (typically JSON fragment) to add.\n   */\n  readonly delta: string\n}\n\n/**\n * Encoded representation of tool params delta parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolParamsDeltaPartEncoded extends BasePartEncoded<\"tool-params-delta\", ToolParamsDeltaPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding tool parameter chunk.\n   */\n  readonly id: string\n  /**\n   * The incremental parameter content (typically JSON fragment) to add.\n   */\n  readonly delta: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ToolParamsDeltaPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ToolParamsDeltaPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of tool params delta parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ToolParamsDeltaPart: Schema.Schema<ToolParamsDeltaPart, ToolParamsDeltaPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"tool-params-delta\"),\n  id: Schema.String,\n  delta: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ToolParamsDeltaPart\" })\n)\n\n/**\n * Constructs a new tool params delta part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const toolParamsDeltaPart = (params: ConstructorParams<ToolParamsDeltaPart>): ToolParamsDeltaPart =>\n  makePart(\"tool-params-delta\", params)\n\n// =============================================================================\n// Tool Params End Part\n// =============================================================================\n\n/**\n * Response part indicating the end of streaming tool parameters.\n *\n * Marks the completion of a tool parameter stream, indicating that all\n * parameter data has been sent and the tool call is ready to be executed.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolParamsEndPart extends BasePart<\"tool-params-end\", ToolParamsEndPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding tool parameter chunk.\n   */\n  readonly id: string\n}\n\n/**\n * Encoded representation of tool params end parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolParamsEndPartEncoded extends BasePartEncoded<\"tool-params-end\", ToolParamsEndPartMetadata> {\n  /**\n   * Unique identifier matching the corresponding tool parameter stream.\n   */\n  readonly id: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ToolParamsEndPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ToolParamsEndPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of tool params end parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ToolParamsEndPart: Schema.Schema<ToolParamsEndPart, ToolParamsEndPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"tool-params-end\"),\n  id: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ToolParamsEndPart\" })\n)\n\n/**\n * Constructs a new tool params end part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const toolParamsEndPart = (params: ConstructorParams<ToolParamsEndPart>): ToolParamsEndPart =>\n  makePart(\"tool-params-end\", params)\n\n// =============================================================================\n// Tool Call Part\n// =============================================================================\n\n/**\n * Response part representing a tool call request.\n *\n * @example\n * ```ts\n * import { Response } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * const weatherParams = Schema.Struct({\n *   city: Schema.String,\n *   units: Schema.optional(Schema.Literal(\"celsius\", \"fahrenheit\"))\n * })\n *\n * const toolCallPart: Response.ToolCallPart<\n *   \"get_weather\",\n *   typeof weatherParams.fields\n * > = Response.makePart(\"tool-call\", {\n *   id: \"call_123\",\n *   name: \"get_weather\",\n *   params: { city: \"San Francisco\", units: \"celsius\" },\n *   providerExecuted: false,\n * })\n * ```\n *\n * @template Name - String literal type for the tool name\n * @template Params - Schema fields type for the tool parameters\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolCallPart<Name extends string, Params> extends BasePart<\"tool-call\", ToolCallPartMetadata> {\n  /**\n   * Unique identifier for this tool call.\n   */\n  readonly id: string\n  /**\n   * Name of the tool being called, which corresponds to the name of the tool\n   * in the `Toolkit` included with the request.\n   */\n  readonly name: Name\n  /**\n   * Parameters to pass to the tool.\n   */\n  readonly params: Params\n  /**\n   * Optional provider-specific name for the tool, which can be useful when the\n   * name of the tool in the `Toolkit` and the name of the tool used by the\n   * model are different.\n   *\n   * This is usually happens only with provider-defined tools which require a\n   * user-space handler.\n   */\n  readonly providerName?: string | undefined\n  /**\n   * Whether the tool was executed by the provider (true) or framework (false).\n   */\n  readonly providerExecuted: boolean\n}\n\n/**\n * Encoded representation of tool call parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolCallPartEncoded extends BasePartEncoded<\"tool-call\", ToolCallPartMetadata> {\n  /**\n   * Unique identifier for this tool call.\n   */\n  readonly id: string\n  /**\n   * Name of the tool being called, which corresponds to the name of the tool\n   * in the `Toolkit` included with the request.\n   */\n  readonly name: string\n  /**\n   * Parameters to pass to the tool.\n   */\n  readonly params: unknown\n  /**\n   * Optional provider-specific name for the tool, which can be useful when the\n   * name of the tool in the `Toolkit` and the name of the tool used by the\n   * model are different.\n   *\n   * This is usually happens only with provider-defined tools which require a\n   * user-space handler.\n   */\n  readonly providerName?: string | undefined\n  /**\n   * Whether the tool was executed by the provider (true) or framework (false).\n   */\n  readonly providerExecuted?: boolean | undefined\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ToolCallPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ToolCallPartMetadata extends ProviderMetadata {}\n\n/**\n * Creates a Schema for tool call parts with specific tool name and parameters.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ToolCallPart = <const Name extends string, Params extends Schema.Struct.Fields>(\n  /**\n   * Name of the tool.\n   */\n  name: Name,\n  /**\n   * Schema for the tool parameters.\n   */\n  params: Schema.Struct<Params>\n): Schema.Schema<ToolCallPart<Name, Params>, ToolCallPartEncoded> =>\n  Schema.Struct({\n    type: Schema.Literal(\"tool-call\"),\n    id: Schema.String,\n    name: Schema.Literal(name),\n    params,\n    providerName: Schema.optional(Schema.String),\n    providerExecuted: Schema.optionalWith(Schema.Boolean, { default: constFalse }),\n    metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n  }).pipe(\n    Schema.attachPropertySignature(PartTypeId, PartTypeId),\n    Schema.annotations({ identifier: \"ToolCallPart\" })\n  ) as any\n\n/**\n * Constructs a new tool call part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const toolCallPart = <const Name extends string, Params>(\n  params: ConstructorParams<ToolCallPart<Name, Params>>\n): ToolCallPart<Name, Params> => makePart(\"tool-call\", params)\n\n// =============================================================================\n// Tool Call Result Part\n// =============================================================================\n\n/**\n * The base fields of a tool result part.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface BaseToolResult<Name extends string> extends BasePart<\"tool-result\", ToolResultPartMetadata> {\n  /**\n   * Unique identifier matching the original tool call.\n   */\n  readonly id: string\n  /**\n   * Name of the tool being called, which corresponds to the name of the tool\n   * in the `Toolkit` included with the request.\n   */\n  readonly name: Name\n  /**\n   * The encoded result for serialization purposes.\n   */\n  readonly encodedResult: unknown\n  /**\n   * Optional provider-specific name for the tool, which can be useful when the\n   * name of the tool in the `Toolkit` and the name of the tool used by the\n   * model are different.\n   *\n   * This is usually happens only with provider-defined tools which require a\n   * user-space handler.\n   */\n  readonly providerName?: string | undefined\n  /**\n   * Whether the tool was executed by the provider (true) or framework (false).\n   */\n  readonly providerExecuted: boolean\n}\n\n/**\n * Represents a successful tool call result.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolResultSuccess<Name extends string, Success> extends BaseToolResult<Name> {\n  /**\n   * The decoded success returned by the tool execution.\n   */\n  readonly result: Success\n  /**\n   * Whether or not the result of executing the tool call handler was an error.\n   */\n  readonly isFailure: false\n}\n\n/**\n * Represents a failed tool call result.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolResultFailure<Name extends string, Failure> extends BaseToolResult<Name> {\n  /**\n   * The decoded failure returned by the tool execution.\n   */\n  readonly result: Failure\n  /**\n   * Whether or not the result of executing the tool call handler was an error.\n   */\n  readonly isFailure: true\n}\n\n/**\n * Response part representing the result of a tool call.\n *\n * @example\n * ```ts\n * import { Either } from \"effect\"\n * import { Response } from \"@effect/ai\"\n *\n * interface WeatherData {\n *   temperature: number\n *   condition: string\n *   humidity: number\n * }\n *\n * const toolResultPart: Response.ToolResultPart<\n *   \"get_weather\",\n *   WeatherData,\n *   never\n * > = Response.toolResultPart({\n *   id: \"call_123\",\n *   name: \"get_weather\",\n *   isFailure: false,\n *   result: {\n *     temperature: 22,\n *     condition: \"sunny\",\n *     humidity: 65\n *   },\n *   encodedResult: {\n *     temperature: 22,\n *     condition: \"sunny\",\n *     humidity: 65\n *   },\n *   providerExecuted: false\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport type ToolResultPart<Name extends string, Success, Failure> =\n  | ToolResultSuccess<Name, Success>\n  | ToolResultFailure<Name, Failure>\n\n/**\n * Encoded representation of tool result parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ToolResultPartEncoded extends BasePartEncoded<\"tool-result\", ToolResultPartMetadata> {\n  /**\n   * Unique identifier matching the original tool call.\n   */\n  readonly id: string\n  /**\n   * Name of the tool being called, which corresponds to the name of the tool\n   * in the `Toolkit` included with the request.\n   */\n  readonly name: string\n  /**\n   * The result returned by the tool execution.\n   */\n  readonly result: unknown\n  /**\n   * Whether or not the result of executing the tool call handler was an error.\n   */\n  readonly isFailure: boolean\n  /**\n   * Optional provider-specific name for the tool, which can be useful when the\n   * name of the tool in the `Toolkit` and the name of the tool used by the\n   * model are different.\n   *\n   * This is usually happens only with provider-defined tools which require a\n   * user-space handler.\n   */\n  readonly providerName?: string | undefined\n  /**\n   * Whether the tool was executed by the provider (true) or framework (false).\n   */\n  readonly providerExecuted?: boolean | undefined\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ToolResultPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ToolResultPartMetadata extends ProviderMetadata {}\n\n/**\n * Creates a Schema for tool result parts with specific tool name and result type.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ToolResultPart = <\n  const Name extends string,\n  Success extends Schema.Schema.Any,\n  Failure extends Schema.Schema.All\n>(\n  name: Name,\n  success: Success,\n  failure: Failure\n): Schema.Schema<\n  ToolResultPart<Name, Schema.Schema.Type<Success>, Schema.Schema.Type<Failure>>,\n  ToolResultPartEncoded\n> => {\n  const Base = Schema.Struct({\n    id: Schema.String,\n    type: Schema.Literal(\"tool-result\"),\n    providerName: Schema.optional(Schema.String),\n    isFailure: Schema.Boolean\n  })\n  const ResultSchema = Schema.Union(success, failure)\n  const Encoded = Schema.Struct({\n    ...Base.fields,\n    name: Schema.String,\n    result: Schema.encodedSchema(ResultSchema),\n    providerExecuted: Schema.optional(Schema.Boolean),\n    metadata: Schema.optional(ProviderMetadata)\n  })\n  const Decoded = Schema.Struct({\n    ...Base.fields,\n    [PartTypeId]: Schema.Literal(PartTypeId),\n    name: Schema.Literal(name),\n    result: Schema.typeSchema(ResultSchema),\n    encodedResult: Schema.encodedSchema(ResultSchema),\n    providerExecuted: Schema.Boolean,\n    metadata: ProviderMetadata\n  })\n  const decodeResult = ParseResult.decode<any, any, never>(ResultSchema as any)\n  const encodeResult = ParseResult.encode<any, any, never>(ResultSchema as any)\n  return Schema.transformOrFail(\n    Encoded,\n    Decoded,\n    {\n      strict: true,\n      decode: Effect.fnUntraced(function*(encoded) {\n        const decoded = yield* decodeResult(encoded.result)\n        const providerExecuted = encoded.providerExecuted ?? false\n        return {\n          ...encoded,\n          [PartTypeId]: PartTypeId,\n          name: encoded.name as Name,\n          result: decoded,\n          encodedResult: encoded.result as any,\n          metadata: encoded.metadata ?? {},\n          providerExecuted\n        } as const\n      }),\n      encode: Effect.fnUntraced(function*(decoded) {\n        const encoded = yield* encodeResult(decoded.result)\n        return {\n          ...decoded,\n          result: encoded,\n          ...(decoded.metadata ?? {}),\n          ...(decoded.providerName ? { providerName: decoded.providerName } : {}),\n          ...(decoded.providerExecuted ? { providerExecuted: true } : {})\n        }\n      })\n    }\n  ).annotations({ identifier: `ToolResultPart(${name})` }) as any\n}\n\n/**\n * Constructs a new tool result part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const toolResultPart = <\n  const Params extends ConstructorParams<ToolResultPart<string, any, any>>\n>(\n  params: Params\n): Params extends {\n  readonly name: infer Name extends string\n  readonly isFailure: false\n  readonly result: infer Success\n} ? ToolResultPart<Name, Success, never>\n  : Params extends {\n    readonly name: infer Name extends string\n    readonly isFailure: true\n    readonly result: infer Failure\n  } ? ToolResultPart<Name, never, Failure>\n  : never => makePart(\"tool-result\", params) as any\n\n// =============================================================================\n// File Part\n// =============================================================================\n\n/**\n * Response part representing a file attachment.\n *\n * Supports various file types including images, documents, and binary data.\n *\n * @example\n * ```ts\n * import { Response } from \"@effect/ai\"\n *\n * const imagePart: Response.FilePart = Response.makePart(\"file\", {\n *   mediaType: \"image/jpeg\",\n *   data: new Uint8Array([1, 2, 3]),\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface FilePart extends BasePart<\"file\", FilePartMetadata> {\n  /**\n   * MIME type of the file (e.g., \"image/jpeg\", \"application/pdf\").\n   */\n  readonly mediaType: string\n  /**\n   * File data as a byte array.\n   */\n  readonly data: Uint8Array\n}\n\n/**\n * Encoded representation of file parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface FilePartEncoded extends BasePartEncoded<\"file\", FilePartMetadata> {\n  /**\n   * MIME type of the file (e.g., \"image/jpeg\", \"application/pdf\").\n   */\n  readonly mediaType: string\n  /**\n   * File data as a base64 string.\n   */\n  readonly data: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `FilePart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface FilePartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of file parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const FilePart: Schema.Schema<FilePart, FilePartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"file\"),\n  mediaType: Schema.String,\n  data: Schema.Uint8ArrayFromBase64,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"FilePart\" })\n)\n\n/**\n * Constructs a new file part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const filePart = (params: ConstructorParams<FilePart>): FilePart => makePart(\"file\", params)\n\n// =============================================================================\n// Document Source Part\n// =============================================================================\n\n/**\n * Response part representing a document source reference.\n *\n * Used to reference documents that were used in generating the response.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface DocumentSourcePart extends BasePart<\"source\", DocumentSourcePartMetadata> {\n  /**\n   * Type discriminator for document sources.\n   */\n  readonly sourceType: \"document\"\n  /**\n   * Unique identifier for the document.\n   */\n  readonly id: string\n  /**\n   * MIME type of the document.\n   */\n  readonly mediaType: string\n  /**\n   * Display title of the document.\n   */\n  readonly title: string\n  /**\n   * Optional filename of the document.\n   */\n  readonly fileName?: string\n}\n\n/**\n * Encoded representation of document source parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface DocumentSourcePartEncoded extends BasePartEncoded<\"source\", DocumentSourcePartMetadata> {\n  /**\n   * Type discriminator for document sources.\n   */\n  readonly sourceType: \"document\"\n  /**\n   * Unique identifier for the document.\n   */\n  readonly id: string\n  /**\n   * MIME type of the document.\n   */\n  readonly mediaType: string\n  /**\n   * Display title of the document.\n   */\n  readonly title: string\n  /**\n   * Optional filename of the document.\n   */\n  readonly fileName?: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `DocumentSourcePart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface DocumentSourcePartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of document source parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const DocumentSourcePart: Schema.Schema<DocumentSourcePart, DocumentSourcePartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"source\"),\n  sourceType: Schema.Literal(\"document\"),\n  id: Schema.String,\n  mediaType: Schema.String,\n  title: Schema.String,\n  fileName: Schema.optional(Schema.String),\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"DocumentSourcePart\" })\n)\n\n/**\n * Constructs a new document source part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const documentSourcePart = (params: ConstructorParams<DocumentSourcePart>): DocumentSourcePart =>\n  makePart(\"source\", { ...params, sourceType: \"document\" }) as any\n\n// =============================================================================\n// Url Source Part\n// =============================================================================\n\n/**\n * Response part representing a URL source reference.\n *\n * Used to reference web URLs that were used in generating the response.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface UrlSourcePart extends BasePart<\"source\", UrlSourcePartMetadata> {\n  /**\n   * Type discriminator for URL sources.\n   */\n  readonly sourceType: \"url\"\n  /**\n   * Unique identifier for the URL.\n   */\n  readonly id: string\n  /**\n   * The URL that was referenced.\n   */\n  readonly url: URL\n  /**\n   * Display title of the URL content.\n   */\n  readonly title: string\n}\n\n/**\n * Encoded representation of URL source parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface UrlSourcePartEncoded extends BasePartEncoded<\"source\", UrlSourcePartMetadata> {\n  /**\n   * Type discriminator for URL sources.\n   */\n  readonly sourceType: \"url\"\n  /**\n   * Unique identifier for the URL.\n   */\n  readonly id: string\n  /**\n   * The URL that was referenced as a string.\n   */\n  readonly url: string\n  /**\n   * Display title of the URL content.\n   */\n  readonly title: string\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `UrlSourcePart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface UrlSourcePartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of url source parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const UrlSourcePart: Schema.Schema<UrlSourcePart, UrlSourcePartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"source\"),\n  sourceType: Schema.Literal(\"url\"),\n  id: Schema.String,\n  url: Schema.URL,\n  title: Schema.String,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"UrlSourcePart\" })\n)\n\n/**\n * Constructs a new URL source part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const urlSourcePart = (params: ConstructorParams<UrlSourcePart>): UrlSourcePart =>\n  makePart(\"source\", { ...params, sourceType: \"url\" }) as any\n\n// =============================================================================\n// Response Metadata Part\n// =============================================================================\n\n/**\n * Response part containing metadata about the large language model response.\n *\n * @example\n * ```ts\n * import { Response } from \"@effect/ai\"\n * import { Option, DateTime } from \"effect\"\n *\n * const metadataPart: Response.ResponseMetadataPart = Response.makePart(\"response-metadata\", {\n *   id: Option.some(\"resp_123\"),\n *   modelId: Option.some(\"gpt-4\"),\n *   timestamp: Option.some(DateTime.unsafeNow())\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ResponseMetadataPart extends BasePart<\"response-metadata\", ResponseMetadataPartMetadata> {\n  /**\n   * Optional unique identifier for this specific response.\n   */\n  readonly id: Option.Option<string>\n  /**\n   * Optional identifier of the AI model that generated the response.\n   */\n  readonly modelId: Option.Option<string>\n  /**\n   * Optional timestamp when the response was generated.\n   */\n  readonly timestamp: Option.Option<DateTime.Utc>\n}\n\n/**\n * Encoded representation of response metadata parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ResponseMetadataPartEncoded\n  extends BasePartEncoded<\"response-metadata\", ResponseMetadataPartMetadata>\n{\n  /**\n   * Optional unique identifier for this specific response.\n   */\n  readonly id?: string | undefined\n  /**\n   * Optional identifier of the AI model that generated the response.\n   */\n  readonly modelId?: string | undefined\n  /**\n   * Optional timestamp when the response was generated.\n   */\n  readonly timestamp?: string | undefined\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ResponseMetadataPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ResponseMetadataPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of response metadata parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ResponseMetadataPart: Schema.Schema<ResponseMetadataPart, ResponseMetadataPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"response-metadata\"),\n  id: Schema.optionalWith(Schema.String, { as: \"Option\" }),\n  modelId: Schema.optionalWith(Schema.String, { as: \"Option\" }),\n  timestamp: Schema.optionalWith(Schema.DateTimeUtc, { as: \"Option\" }),\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ResponseMetadataPart\" })\n)\n\n/**\n * Constructs a new response metadata part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const responseMetadataPart = (params: ConstructorParams<ResponseMetadataPart>): ResponseMetadataPart =>\n  makePart(\"response-metadata\", params)\n\n// =============================================================================\n// Finish Part\n// =============================================================================\n\n/**\n * Represents the reason why a model finished generation of a response.\n *\n * Possible finish reasons:\n * - `\"stop\"`: The model generated a stop sequence.\n * - `\"length\"`: The model exceeded its token budget.\n * - `\"content-filter\"`: The model generated content which violated a content filter.\n * - `\"tool-calls\"`: The model triggered a tool call.\n * - `\"error\"`: The model encountered an error.\n * - `\"pause\"`: The model requested to pause execution.\n * - `\"other\"`: The model stopped for a reason not supported by this protocol.\n * - `\"unknown\"`: The model did not specify a finish reason.\n *\n * @since 1.0.0\n * @category Models\n */\nexport const FinishReason: Schema.Literal<[\n  \"stop\",\n  \"length\",\n  \"content-filter\",\n  \"tool-calls\",\n  \"error\",\n  \"pause\",\n  \"other\",\n  \"unknown\"\n]> = Schema.Literal(\n  \"stop\",\n  \"length\",\n  \"content-filter\",\n  \"tool-calls\",\n  \"error\",\n  \"pause\",\n  \"other\",\n  \"unknown\"\n)\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type FinishReason = typeof FinishReason.Type\n\n/**\n * Represents usage information for a request to a large language model provider.\n *\n * If the model provider returns additional usage information than what is\n * specified here, you can generally find that information under the provider\n * metadata of the finish part of the response.\n *\n * @since 1.0.0\n * @category Models\n */\nexport class Usage extends Schema.Class<Usage>(\"@effect/ai/AiResponse/Usage\")({\n  /**\n   * The number of tokens sent in the request to the model.\n   */\n  inputTokens: Schema.UndefinedOr(Schema.Number),\n  /**\n   * The number of tokens that the model generated for the request.\n   */\n  outputTokens: Schema.UndefinedOr(Schema.Number),\n  /**\n   * The total of number of input tokens and output tokens as reported by the\n   * large language model provider.\n   *\n   * **NOTE**: This value may differ from the sum of `inputTokens` and\n   * `outputTokens` due to inclusion of reasoning tokens or other\n   * provider-specific overhead.\n   */\n  totalTokens: Schema.UndefinedOr(Schema.Number),\n  /**\n   * The number of reasoning tokens that the model used to generate the output\n   * for the request.\n   */\n  reasoningTokens: Schema.optional(Schema.Number),\n  /**\n   * The number of input tokens read from the prompt cache for the request.\n   */\n  cachedInputTokens: Schema.optional(Schema.Number)\n}) {}\n\n/**\n * Response part indicating the completion of a response generation.\n *\n * @example\n * ```ts\n * import { Response } from \"@effect/ai\"\n *\n * const finishPart: Response.FinishPart = Response.makePart(\"finish\", {\n *   reason: \"stop\",\n *   usage: {\n *     inputTokens: 50,\n *     outputTokens: 25,\n *     totalTokens: 75\n *   }\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface FinishPart extends BasePart<\"finish\", FinishPartMetadata> {\n  /**\n   * The reason why the model finished generating the response.\n   */\n  readonly reason: FinishReason\n  /**\n   * Token usage statistics for the request.\n   */\n  readonly usage: Usage\n}\n\n/**\n * Encoded representation of finish parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface FinishPartEncoded extends BasePartEncoded<\"finish\", FinishPartMetadata> {\n  /**\n   * The reason why the model finished generating the response.\n   */\n  readonly reason: typeof FinishReason.Encoded\n  /**\n   * Token usage statistics for the request.\n   */\n  readonly usage: typeof Usage.Encoded\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `FinishPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface FinishPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of finish parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const FinishPart: Schema.Schema<FinishPart, FinishPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"finish\"),\n  reason: FinishReason,\n  usage: Usage,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"FinishPart\" })\n)\n\n/**\n * Constructs a new finish part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const finishPart = (params: ConstructorParams<FinishPart>): FinishPart => makePart(\"finish\", params)\n\n// =============================================================================\n// Error Part\n// =============================================================================\n\n/**\n * Response part indicating that an error occurred generating the response.\n *\n * @example\n * ```ts\n * import { Response } from \"@effect/ai\"\n *\n * const errorPart: Response.ErrorPart = Response.makePart(\"error\", {\n *   error: new Error(\"boom\")\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ErrorPart extends BasePart<\"error\", ErrorPartMetadata> {\n  readonly error: unknown\n}\n\n/**\n * Encoded representation of error parts for serialization.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ErrorPartEncoded extends BasePartEncoded<\"error\", ErrorPartMetadata> {\n  readonly error: unknown\n}\n\n/**\n * Represents provider-specific metadata that can be associated with a\n * `ErrorPart` through module augmentation.\n *\n * @since 1.0.0\n * @category ProviderOptions\n */\nexport interface ErrorPartMetadata extends ProviderMetadata {}\n\n/**\n * Schema for validation and encoding of error parts.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ErrorPart: Schema.Schema<ErrorPart, ErrorPartEncoded> = Schema.Struct({\n  type: Schema.Literal(\"error\"),\n  error: Schema.Unknown,\n  metadata: Schema.optionalWith(ProviderMetadata, { default: constEmptyObject })\n}).pipe(\n  Schema.attachPropertySignature(PartTypeId, PartTypeId),\n  Schema.annotations({ identifier: \"ErrorPart\" })\n)\n\n/**\n * Constructs a new error part.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const errorPart = (params: ConstructorParams<ErrorPart>): ErrorPart => makePart(\"error\", params)\n"
  },
  {
    "path": "packages/ai/ai/src/Telemetry.ts",
    "content": "/**\n * The `Telemetry` module provides OpenTelemetry integration for operations\n * performed against a large language model provider by defining telemetry\n * attributes and utilities that follow the OpenTelemetry GenAI semantic\n * conventions.\n *\n * @example\n * ```ts\n * import { Telemetry } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Add telemetry attributes to a span\n * const addTelemetry = Effect.gen(function* () {\n *   const span = yield* Effect.currentSpan\n *\n *   Telemetry.addGenAIAnnotations(span, {\n *     system: \"openai\",\n *     operation: { name: \"chat\" },\n *     request: {\n *       model: \"gpt-4\",\n *       temperature: 0.7,\n *       maxTokens: 1000\n *     },\n *     usage: {\n *       inputTokens: 100,\n *       outputTokens: 50\n *     }\n *   })\n * })\n * ```\n *\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport { dual } from \"effect/Function\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as String from \"effect/String\"\nimport type { Span } from \"effect/Tracer\"\nimport type { Simplify } from \"effect/Types\"\nimport type { ProviderOptions } from \"./LanguageModel.js\"\nimport type * as Response from \"./Response.js\"\n\n/**\n * The attributes used to describe telemetry in the context of Generative\n * Artificial Intelligence (GenAI) Models requests and responses.\n *\n * {@see https://opentelemetry.io/docs/specs/semconv/attributes-registry/gen-ai/}\n *\n * @since 1.0.0\n * @category Models\n */\nexport type GenAITelemetryAttributes = Simplify<\n  & AttributesWithPrefix<BaseAttributes, \"gen_ai\">\n  & AttributesWithPrefix<OperationAttributes, \"gen_ai.operation\">\n  & AttributesWithPrefix<TokenAttributes, \"gen_ai.token\">\n  & AttributesWithPrefix<UsageAttributes, \"gen_ai.usage\">\n  & AttributesWithPrefix<RequestAttributes, \"gen_ai.request\">\n  & AttributesWithPrefix<ResponseAttributes, \"gen_ai.response\">\n>\n\n/**\n * All telemetry attributes which are part of the GenAI specification.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type AllAttributes =\n  & BaseAttributes\n  & OperationAttributes\n  & TokenAttributes\n  & UsageAttributes\n  & RequestAttributes\n  & ResponseAttributes\n\n/**\n * Telemetry attributes which are part of the GenAI specification and are\n * namespaced by `gen_ai`.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface BaseAttributes {\n  /**\n   * The Generative AI product as identified by the client or server\n   * instrumentation.\n   */\n  readonly system?: (string & {}) | WellKnownSystem | null | undefined\n}\n\n/**\n * Telemetry attributes which are part of the GenAI specification and are\n * namespaced by `gen_ai.operation`.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface OperationAttributes {\n  readonly name?: (string & {}) | WellKnownOperationName | null | undefined\n}\n\n/**\n * Telemetry attributes which are part of the GenAI specification and are\n * namespaced by `gen_ai.token`.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface TokenAttributes {\n  readonly type?: string | null | undefined\n}\n\n/**\n * Telemetry attributes which are part of the GenAI specification and are\n * namespaced by `gen_ai.usage`.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface UsageAttributes {\n  readonly inputTokens?: number | null | undefined\n  readonly outputTokens?: number | null | undefined\n}\n\n/**\n * Telemetry attributes which are part of the GenAI specification and are\n * namespaced by `gen_ai.request`.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface RequestAttributes {\n  /**\n   * The name of the GenAI model a request is being made to.\n   */\n  readonly model?: string | null | undefined\n  /**\n   * The temperature setting for the GenAI request.\n   */\n  readonly temperature?: number | null | undefined\n  /**\n   * The temperature setting for the GenAI request.\n   */\n  readonly topK?: number | null | undefined\n  /**\n   * The top_k sampling setting for the GenAI request.\n   */\n  readonly topP?: number | null | undefined\n  /**\n   * The top_p sampling setting for the GenAI request.\n   */\n  readonly maxTokens?: number | null | undefined\n  /**\n   * The encoding formats requested in an embeddings operation, if specified.\n   */\n  readonly encodingFormats?: ReadonlyArray<string> | null | undefined\n  /**\n   * List of sequences that the model will use to stop generating further\n   * tokens.\n   */\n  readonly stopSequences?: ReadonlyArray<string> | null | undefined\n  /**\n   * The frequency penalty setting for the GenAI request.\n   */\n  readonly frequencyPenalty?: number | null | undefined\n  /**\n   * The presence penalty setting for the GenAI request.\n   */\n  readonly presencePenalty?: number | null | undefined\n  /**\n   * The seed setting for the GenAI request. Requests with same seed value\n   * are more likely to return same result.\n   */\n  readonly seed?: number | null | undefined\n}\n\n/**\n * Telemetry attributes which are part of the GenAI specification and are\n * namespaced by `gen_ai.response`.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ResponseAttributes {\n  /**\n   * The unique identifier for the completion.\n   */\n  readonly id?: string | null | undefined\n  /**\n   * The name of the model that generated the response.\n   */\n  readonly model?: string | null | undefined\n  /**\n   * Array of reasons the model stopped generating tokens, corresponding to\n   * each generation received.\n   */\n  readonly finishReasons?: ReadonlyArray<string> | null | undefined\n}\n\n/**\n * The `gen_ai.operation.name` attribute has the following list of well-known\n * values.\n *\n * If one of them applies, then the respective value **MUST** be used;\n * otherwise, a custom value **MAY** be used.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type WellKnownOperationName = \"chat\" | \"embeddings\" | \"text_completion\"\n\n/**\n * The `gen_ai.system` attribute has the following list of well-known values.\n *\n * If one of them applies, then the respective value **MUST** be used;\n * otherwise, a custom value **MAY** be used.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type WellKnownSystem =\n  | \"anthropic\"\n  | \"aws.bedrock\"\n  | \"az.ai.inference\"\n  | \"az.ai.openai\"\n  | \"cohere\"\n  | \"deepseek\"\n  | \"gemini\"\n  | \"groq\"\n  | \"ibm.watsonx.ai\"\n  | \"mistral_ai\"\n  | \"openai\"\n  | \"perplexity\"\n  | \"vertex_ai\"\n  | \"xai\"\n\n/**\n * Utility type for prefixing attribute names with a namespace.\n *\n * Transforms attribute keys by adding a prefix and formatting them according to\n * OpenTelemetry conventions (camelCase to snake_case).\n *\n * @template Attributes - Record type containing the attributes to prefix\n * @template Prefix - String literal type for the prefix to add\n *\n * @example\n * ```ts\n * import { Telemetry } from \"@effect/ai\"\n *\n * type RequestAttrs = {\n *   modelName: string\n *   maxTokens: number\n * }\n *\n * type PrefixedAttrs = Telemetry.AttributesWithPrefix<RequestAttrs, \"gen_ai.request\">\n * // Results in: {\n * //   \"gen_ai.request.model_name\": string\n * //   \"gen_ai.request.max_tokens\": number\n * // }\n * ```\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type AttributesWithPrefix<Attributes extends Record<string, any>, Prefix extends string> = {\n  [Name in keyof Attributes as `${Prefix}.${FormatAttributeName<Name>}`]: Attributes[Name]\n}\n\n/**\n * Utility type for converting camelCase names to snake_case format.\n *\n * This type recursively transforms string literal types from camelCase to\n * snake_case, which is the standard format for OpenTelemetry attributes.\n *\n * @template T - String literal type to format\n *\n * @example\n * ```ts\n * import { Telemetry } from \"@effect/ai\"\n *\n * type Formatted1 = Telemetry.FormatAttributeName<\"modelName\">    // \"model_name\"\n * type Formatted2 = Telemetry.FormatAttributeName<\"maxTokens\">    // \"max_tokens\"\n * type Formatted3 = Telemetry.FormatAttributeName<\"temperature\">  // \"temperature\"\n * ```\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type FormatAttributeName<T extends string | number | symbol> = T extends string ?\n  T extends `${infer First}${infer Rest}`\n    ? `${First extends Uppercase<First> ? \"_\" : \"\"}${Lowercase<First>}${FormatAttributeName<Rest>}`\n  : T :\n  never\n\n/**\n * Creates a function to add attributes to a span with a given prefix and key transformation.\n *\n * This utility function is used internally to create specialized functions for adding\n * different types of telemetry attributes to OpenTelemetry spans.\n *\n * @example\n * ```ts\n * import { Telemetry } from \"@effect/ai\"\n * import { String, Tracer } from \"effect\"\n *\n * const addCustomAttributes = Telemetry.addSpanAttributes(\n *   \"custom.ai\",\n *   String.camelToSnake\n * )\n *\n * // Usage with a span\n * declare const span: Tracer.Span\n * addCustomAttributes(span, {\n *   modelName: \"gpt-4\",\n *   maxTokens: 1000\n * })\n * // Results in attributes: \"custom.ai.model_name\" and \"custom.ai.max_tokens\"\n * ```\n *\n * @since 1.0.0\n * @category Utilities\n */\nexport const addSpanAttributes = (\n  /**\n   * The prefix to add to all attribute keys.\n   */\n  keyPrefix: string,\n  /**\n   * Function to transform attribute keys (e.g., camelCase to snake_case).\n   */\n  transformKey: (key: string) => string\n) =>\n<Attributes extends Record<string, any>>(\n  /**\n   * The OpenTelemetry span to add attributes to.\n   */\n  span: Span,\n  /**\n   * The attributes to add to the span.\n   */\n  attributes: Attributes\n): void => {\n  for (const [key, value] of Object.entries(attributes)) {\n    if (Predicate.isNotNullable(value)) {\n      span.attribute(`${keyPrefix}.${transformKey(key)}`, value)\n    }\n  }\n}\n\nconst addSpanBaseAttributes = addSpanAttributes(\"gen_ai\", String.camelToSnake)<BaseAttributes>\nconst addSpanOperationAttributes = addSpanAttributes(\"gen_ai.operation\", String.camelToSnake)<OperationAttributes>\nconst addSpanRequestAttributes = addSpanAttributes(\"gen_ai.request\", String.camelToSnake)<RequestAttributes>\nconst addSpanResponseAttributes = addSpanAttributes(\"gen_ai.response\", String.camelToSnake)<ResponseAttributes>\nconst addSpanTokenAttributes = addSpanAttributes(\"gen_ai.token\", String.camelToSnake)<TokenAttributes>\nconst addSpanUsageAttributes = addSpanAttributes(\"gen_ai.usage\", String.camelToSnake)<UsageAttributes>\n\n/**\n * Configuration options for GenAI telemetry attributes.\n *\n * Combines base attributes with optional grouped attributes for comprehensive\n * telemetry coverage of AI operations.\n *\n * @example\n * ```ts\n * import { Telemetry } from \"@effect/ai\"\n *\n * const telemetryOptions: Telemetry.GenAITelemetryAttributeOptions = {\n *   system: \"openai\",\n *   operation: {\n *     name: \"chat\"\n *   },\n *   request: {\n *     model: \"gpt-4-turbo\",\n *     temperature: 0.7,\n *     maxTokens: 2000\n *   },\n *   response: {\n *     id: \"chatcmpl-123\",\n *     model: \"gpt-4-turbo-2024-04-09\",\n *     finishReasons: [\"stop\"]\n *   },\n *   usage: {\n *     inputTokens: 50,\n *     outputTokens: 25\n *   }\n * }\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport type GenAITelemetryAttributeOptions = BaseAttributes & {\n  /**\n   * Operation-specific attributes (e.g., operation name).\n   */\n  readonly operation?: OperationAttributes | undefined\n  /**\n   * Request-specific attributes (e.g., model parameters).\n   */\n  readonly request?: RequestAttributes | undefined\n  /**\n   * Response-specific attributes (e.g., response metadata).\n   */\n  readonly response?: ResponseAttributes | undefined\n  /**\n   * Token-specific attributes.\n   */\n  readonly token?: TokenAttributes | undefined\n  /**\n   * Usage statistics attributes (e.g., token counts).\n   */\n  readonly usage?: UsageAttributes | undefined\n}\n\n/**\n * Applies GenAI telemetry attributes to an OpenTelemetry span.\n *\n * This function adds standardized GenAI attributes to a span following OpenTelemetry\n * semantic conventions. It supports both curried and direct application patterns.\n *\n * **Note**: This function mutates the provided span in-place.\n *\n * @example\n * ```ts\n * import { Telemetry } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const directUsage = Effect.gen(function* () {\n *   const span = yield* Effect.currentSpan\n *\n *   Telemetry.addGenAIAnnotations(span, {\n *     system: \"openai\",\n *     request: { model: \"gpt-4\", temperature: 0.7 },\n *     usage: { inputTokens: 100, outputTokens: 50 }\n *   })\n * })\n * ```\n *\n * @since 1.0.0\n * @category Utilities\n */\nexport const addGenAIAnnotations: {\n  (\n    /**\n     * Telemetry attribute options to apply to the span.\n     */\n    options: GenAITelemetryAttributeOptions\n  ): (\n    /**\n     * OpenTelemetry span to add attributes to.\n     */\n    span: Span\n  ) => void\n  (\n    /**\n     * OpenTelemetry span to add attributes to.\n     */\n    span: Span,\n    /**\n     * Telemetry attribute options to apply to the span.\n     */\n    options: GenAITelemetryAttributeOptions\n  ): void\n} = dual<\n  (options: GenAITelemetryAttributeOptions) => (span: Span) => void,\n  (span: Span, options: GenAITelemetryAttributeOptions) => void\n>(2, (span, options) => {\n  addSpanBaseAttributes(span, { system: options.system })\n  if (Predicate.isNotNullable(options.operation)) addSpanOperationAttributes(span, options.operation)\n  if (Predicate.isNotNullable(options.request)) addSpanRequestAttributes(span, options.request)\n  if (Predicate.isNotNullable(options.response)) addSpanResponseAttributes(span, options.response)\n  if (Predicate.isNotNullable(options.token)) addSpanTokenAttributes(span, options.token)\n  if (Predicate.isNotNullable(options.usage)) addSpanUsageAttributes(span, options.usage)\n})\n\n/**\n * A function that can transform OpenTelemetry spans based on AI operation data.\n *\n * Span transformers receive the complete request/response context from AI operations\n * and can add custom telemetry attributes, metrics, or other observability data.\n *\n * @example\n * ```ts\n * import { Telemetry } from \"@effect/ai\"\n *\n * const customTransformer: Telemetry.SpanTransformer = (options) => {\n *   // Add custom attributes based on the response\n *   const textParts = options.response.filter(part => part.type === \"text\")\n *   const totalTextLength = textParts.reduce((sum, part) =>\n *     sum + (part.type === \"text\" ? part.text.length : 0), 0\n *   )\n *\n *   // Add custom metrics\n *   console.log(`Generated ${totalTextLength} characters of text`)\n * }\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface SpanTransformer {\n  (\n    options: ProviderOptions & {\n      /**\n       * Array of response parts generated by the AI model.\n       */\n      readonly response: ReadonlyArray<Response.AllParts<any>>\n    }\n  ): void\n}\n\n/**\n * Context tag for providing a span transformer to large langauge model\n * operations.\n *\n * The CurrentSpanTransformer allows you to inject custom span transformation\n * logic into AI operations, enabling application-specific telemetry and\n * observability patterns.\n *\n * @example\n * ```ts\n * import { Telemetry } from \"@effect/ai\"\n * import * as Effect from \"effect/Effect\"\n *\n * declare const myAIOperation: Effect.Effect<void>\n *\n * // Create a custom span transformer\n * const loggingTransformer: Telemetry.SpanTransformer = (options) => {\n *   console.log(`AI request completed: ${options.response.length} part(s)`)\n *   options.response.forEach((part, index) => {\n *     console.log(`Part ${index}: ${part.type}`)\n *   })\n * }\n *\n * // Provide the transformer to your AI operations\n * const program = myAIOperation.pipe(\n *   Effect.provideService(\n *     Telemetry.CurrentSpanTransformer,\n *     Telemetry.CurrentSpanTransformer.of(loggingTransformer)\n *   )\n * )\n * ```\n *\n * @since 1.0.0\n * @category Context\n */\nexport class CurrentSpanTransformer extends Context.Tag(\"@effect/ai/Telemetry/CurrentSpanTransformer\")<\n  CurrentSpanTransformer,\n  SpanTransformer\n>() {}\n"
  },
  {
    "path": "packages/ai/ai/src/Tokenizer.ts",
    "content": "/**\n * The `Tokenizer` module provides tokenization and text truncation capabilities\n * for large language model text processing workflows.\n *\n * This module offers services for converting text into tokens and truncating\n * prompts based on token limits, essential for managing context length\n * constraints in large language models.\n *\n * @example\n * ```ts\n * import { Tokenizer, Prompt } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const tokenizeText = Effect.gen(function* () {\n *   const tokenizer = yield* Tokenizer.Tokenizer\n *   const tokens = yield* tokenizer.tokenize(\"Hello, world!\")\n *   console.log(`Token count: ${tokens.length}`)\n *   return tokens\n * })\n * ```\n *\n * @example\n * ```ts\n * import { Tokenizer, Prompt } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Truncate a prompt to fit within token limits\n * const truncatePrompt = Effect.gen(function* () {\n *   const tokenizer = yield* Tokenizer.Tokenizer\n *   const longPrompt = \"This is a very long prompt...\"\n *   const truncated = yield* tokenizer.truncate(longPrompt, 100)\n *   return truncated\n * })\n * ```\n *\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Predicate from \"effect/Predicate\"\nimport type * as AiError from \"./AiError.js\"\nimport * as Prompt from \"./Prompt.js\"\n\n/**\n * The `Tokenizer` service tag for dependency injection.\n *\n * This tag provides access to tokenization functionality throughout your\n * application, enabling token counting and prompt truncation capabilities.\n *\n * @example\n * ```ts\n * import { Tokenizer } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const useTokenizer = Effect.gen(function* () {\n *   const tokenizer = yield* Tokenizer.Tokenizer\n *   const tokens = yield* tokenizer.tokenize(\"Hello, world!\")\n *   return tokens.length\n * })\n * ```\n *\n * @since 1.0.0\n * @category Context\n */\nexport class Tokenizer extends Context.Tag(\"@effect/ai/Tokenizer\")<\n  Tokenizer,\n  Service\n>() {}\n\n/**\n * Tokenizer service interface providing text tokenization and truncation\n * operations.\n *\n * This interface defines the core operations for converting text to tokens and\n * managing content length within token limits for AI model compatibility.\n *\n * @example\n * ```ts\n * import { Tokenizer, Prompt } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const customTokenizer: Tokenizer.Service = {\n *   tokenize: (input) =>\n *     Effect.succeed(input.toString().split(' ').map((_, i) => i)),\n *   truncate: (input, maxTokens) =>\n *     Effect.succeed(Prompt.make(input.toString().slice(0, maxTokens * 5)))\n * }\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Service {\n  /**\n   * Converts text input into an array of token numbers.\n   */\n  readonly tokenize: (\n    /**\n     * The text input to tokenize.\n     */\n    input: Prompt.RawInput\n  ) => Effect.Effect<Array<number>, AiError.AiError>\n  /**\n   * Truncates text input to fit within the specified token limit.\n   */\n  readonly truncate: (\n    /**\n     * The text input to truncate.\n     */\n    input: Prompt.RawInput,\n    /**\n     * Maximum number of tokens to retain.\n     */\n    tokens: number\n  ) => Effect.Effect<Prompt.Prompt, AiError.AiError>\n}\n\n/**\n * Creates a Tokenizer service implementation from tokenization options.\n *\n * This function constructs a complete Tokenizer service by providing a\n * tokenization function. The service handles both tokenization and\n * truncation operations using the provided tokenizer.\n *\n * @example\n * ```ts\n * import { Tokenizer, Prompt } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Simple word-based tokenizer\n * const wordTokenizer = Tokenizer.make({\n *   tokenize: (prompt) =>\n *     Effect.succeed(\n *       prompt.content\n *         .flatMap(msg =>\n *           typeof msg.content === \"string\"\n *             ? msg.content.split(' ')\n *             : msg.content.flatMap(part =>\n *                 part.type === \"text\" ? part.text.split(' ') : []\n *               )\n *         )\n *         .map((_, index) => index)\n *     )\n * })\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (options: {\n  /**\n   * Function to tokenize a prompt into an array of token numbers.\n   */\n  readonly tokenize: (\n    /**\n     * The prompt to tokenize.\n     */\n    content: Prompt.Prompt\n  ) => Effect.Effect<Array<number>, AiError.AiError>\n}): Service =>\n  Tokenizer.of({\n    tokenize(input) {\n      return options.tokenize(Prompt.make(input))\n    },\n    truncate(input, tokens) {\n      return truncate(Prompt.make(input), options.tokenize, tokens)\n    }\n  })\n\nconst truncate = (\n  self: Prompt.Prompt,\n  tokenize: (input: Prompt.Prompt) => Effect.Effect<Array<number>, AiError.AiError>,\n  maxTokens: number\n): Effect.Effect<Prompt.Prompt, AiError.AiError> =>\n  Effect.suspend(() => {\n    let count = 0\n    let inputMessages = self.content\n    let outputMessages: Array<Prompt.Message> = []\n    const loop: Effect.Effect<Prompt.Prompt, AiError.AiError> = Effect.suspend(() => {\n      const message = inputMessages[inputMessages.length - 1]\n      if (Predicate.isUndefined(message)) {\n        return Effect.succeed(Prompt.fromMessages(outputMessages))\n      }\n      inputMessages = inputMessages.slice(0, inputMessages.length - 1)\n      return Effect.flatMap(tokenize(Prompt.fromMessages([message])), (tokens) => {\n        count += tokens.length\n        if (count > maxTokens) {\n          return Effect.succeed(Prompt.fromMessages(outputMessages))\n        }\n        outputMessages = [message, ...outputMessages]\n        return loop\n      })\n    })\n    return loop\n  })\n"
  },
  {
    "path": "packages/ai/ai/src/Tool.ts",
    "content": "/**\n * The `Tool` module provides functionality for defining and managing tools\n * that language models can call to augment their capabilities.\n *\n * This module enables creation of both user-defined and provider-defined tools,\n * with full schema validation, type safety, and handler support. Tools allow\n * AI models to perform actions like searching databases, calling APIs, or\n * executing code within your application context.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * // Define a simple calculator tool\n * const Calculator = Tool.make(\"Calculator\", {\n *   description: \"Performs basic arithmetic operations\",\n *   parameters: {\n *     operation: Schema.Literal(\"add\", \"subtract\", \"multiply\", \"divide\"),\n *     a: Schema.Number,\n *     b: Schema.Number\n *   },\n *   success: Schema.Number\n * })\n * ```\n *\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport type * as Effect from \"effect/Effect\"\nimport { constFalse, constTrue, identity } from \"effect/Function\"\nimport * as JsonSchema from \"effect/JSONSchema\"\nimport * as Option from \"effect/Option\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport { pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport type { Covariant } from \"effect/Types\"\nimport type * as AiError from \"./AiError.js\"\n\n// =============================================================================\n// Type Ids\n// =============================================================================\n\n/**\n * Unique identifier for user-defined tools.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport const TypeId = \"~@effect/ai/Tool\"\n\n/**\n * Type-level representation of the user-defined tool identifier.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * Unique identifier for provider-defined tools.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport const ProviderDefinedTypeId = \"~@effect/ai/Tool/ProviderDefined\"\n\n/**\n * Type-level representation of the provider-defined tool identifier.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport type ProviderDefinedTypeId = typeof ProviderDefinedTypeId\n\n// =============================================================================\n// Models\n// =============================================================================\n\n/**\n * A user-defined tool that language models can call to perform actions.\n *\n * Tools represent actionable capabilities that large language models can invoke\n * to extend their functionality beyond text generation. Each tool has a defined\n * schema for parameters, results, and failures.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * // Create a weather lookup tool\n * const GetWeather = Tool.make(\"GetWeather\", {\n *   description: \"Get current weather for a location\",\n *   parameters: {\n *     location: Schema.String,\n *     units: Schema.Literal(\"celsius\", \"fahrenheit\")\n *   },\n *   success: Schema.Struct({\n *     temperature: Schema.Number,\n *     condition: Schema.String,\n *     humidity: Schema.Number\n *   })\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Tool<\n  Name extends string,\n  Config extends {\n    readonly parameters: AnyStructSchema\n    readonly success: Schema.Schema.Any\n    readonly failure: Schema.Schema.All\n    readonly failureMode: FailureMode\n  },\n  Requirements = never\n> extends Tool.Variance<Requirements> {\n  /**\n   * The tool identifier which is used to uniquely identify the tool.\n   */\n  readonly id: string\n\n  /**\n   * The name of the tool.\n   */\n  readonly name: Name\n\n  /**\n   * The optional description of the tool.\n   */\n  readonly description?: string | undefined\n\n  /**\n   * The strategy used for handling errors returned from tool call handler\n   * execution.\n   *\n   * If set to `\"error\"` (the default), errors that occur during tool call\n   * handler execution will be returned in the error channel of the calling\n   * effect.\n   *\n   * If set to `\"return\"`, errors that occur during tool call handler execution\n   * will be captured and returned as part of the tool call result.\n   */\n  readonly failureMode: FailureMode\n\n  /**\n   * A `Schema` representing the parameters that a tool must be called with.\n   */\n  readonly parametersSchema: Config[\"parameters\"]\n\n  /**\n   * A `Schema` representing the value that a tool must return when called if\n   * the tool call is successful.\n   */\n  readonly successSchema: Config[\"success\"]\n\n  /**\n   * A `Schema` representing the value that a tool must return when called if\n   * it fails.\n   */\n  readonly failureSchema: Config[\"failure\"]\n\n  /**\n   * A `Context` object containing tool annotations which can store metadata\n   * about the tool.\n   */\n  readonly annotations: Context.Context<never>\n\n  /**\n   * Adds a _request-level_ dependency which must be provided before the tool\n   * call handler can be executed.\n   *\n   * This can be useful when you want to enforce that a particular dependency\n   * **MUST** be provided to each request to the large language model provider\n   * instead of being provided when creating the tool call handler layer.\n   */\n  addDependency<Identifier, Service>(\n    tag: Context.Tag<Identifier, Service>\n  ): Tool<Name, Config, Identifier | Requirements>\n\n  /**\n   * Set the schema to use to validate the result of a tool call when successful.\n   */\n  setParameters<\n    ParametersSchema extends Schema.Struct<any> | Schema.Struct.Fields\n  >(\n    schema: ParametersSchema\n  ): Tool<\n    Name,\n    {\n      readonly parameters: ParametersSchema extends Schema.Struct<infer _> ? ParametersSchema\n        : ParametersSchema extends Schema.Struct.Fields ? Schema.Struct<ParametersSchema>\n        : never\n      readonly success: Config[\"success\"]\n      readonly failure: Config[\"failure\"]\n      readonly failureMode: Config[\"failureMode\"]\n    },\n    Requirements\n  >\n\n  /**\n   * Set the schema to use to validate the result of a tool call when successful.\n   */\n  setSuccess<SuccessSchema extends Schema.Schema.Any>(\n    schema: SuccessSchema\n  ): Tool<\n    Name,\n    {\n      readonly parameters: Config[\"parameters\"]\n      readonly success: SuccessSchema\n      readonly failure: Config[\"failure\"]\n      readonly failureMode: Config[\"failureMode\"]\n    },\n    Requirements\n  >\n\n  /**\n   * Set the schema to use to validate the result of a tool call when it fails.\n   */\n  setFailure<FailureSchema extends Schema.Schema.Any>(\n    schema: FailureSchema\n  ): Tool<\n    Name,\n    {\n      readonly parameters: Config[\"parameters\"]\n      readonly success: Config[\"success\"]\n      readonly failure: FailureSchema\n      readonly failureMode: Config[\"failureMode\"]\n    },\n    Requirements\n  >\n\n  /**\n   * Add an annotation to the tool.\n   */\n  annotate<I, S>(\n    tag: Context.Tag<I, S>,\n    value: S\n  ): Tool<Name, Config, Requirements>\n\n  /**\n   * Add many annotations to the tool.\n   */\n  annotateContext<I>(\n    context: Context.Context<I>\n  ): Tool<Name, Config, Requirements>\n}\n\n/**\n * A provider-defined tool is a tool which is built into a large language model\n * provider (e.g. web search, code execution).\n *\n * These tools are executed by the large language model provider rather than\n * by your application. However, they can optionally require custom handlers\n * implemented in your application to process provider generated results.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * // Define a web search tool provided by OpenAI\n * const WebSearch = Tool.providerDefined({\n *   id: \"openai.web_search\",\n *   toolkitName: \"WebSearch\",\n *   providerName: \"web_search\",\n *   args: {\n *     query: Schema.String\n *   },\n *   success: Schema.Struct({\n *     results: Schema.Array(Schema.Struct({\n *       title: Schema.String,\n *       url: Schema.String,\n *       snippet: Schema.String\n *     }))\n *   })\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ProviderDefined<\n  Name extends string,\n  Config extends {\n    readonly args: AnyStructSchema\n    readonly parameters: AnyStructSchema\n    readonly success: Schema.Schema.Any\n    readonly failure: Schema.Schema.All\n    readonly failureMode: FailureMode\n  } = {\n    readonly args: Schema.Struct<{}>\n    readonly parameters: Schema.Struct<{}>\n    readonly success: typeof Schema.Void\n    readonly failure: typeof Schema.Never\n    readonly failureMode: \"error\"\n  },\n  RequiresHandler extends boolean = false\n> extends\n  Tool<\n    Name,\n    {\n      readonly parameters: Config[\"parameters\"]\n      readonly success: Config[\"success\"]\n      readonly failure: Config[\"failure\"]\n      readonly failureMode: Config[\"failureMode\"]\n    }\n  >,\n  Tool.ProviderDefinedProto\n{\n  /**\n   * The arguments passed to the provider-defined tool.\n   */\n  readonly args: Config[\"args\"][\"Encoded\"]\n\n  /**\n   * A `Schema` representing the arguments provided by the end-user which will\n   * be used to configure the behavior of the provider-defined tool.\n   */\n  readonly argsSchema: Config[\"args\"]\n\n  /**\n   * Name of the tool as recognized by the large language model provider.\n   */\n  readonly providerName: string\n\n  /**\n   * If set to `true`, this provider-defined tool will require a user-defined\n   * tool call handler to be provided when converting the `Toolkit` containing\n   * this tool into a `Layer`.\n   */\n  readonly requiresHandler: RequiresHandler\n}\n\n/**\n * The strategy used for handling errors returned from tool call handler\n * execution.\n *\n * If set to `\"error\"` (the default), errors that occur during tool call handler\n * execution will be returned in the error channel of the calling effect.\n *\n * If set to `\"return\"`, errors that occur during tool call handler execution\n * will be captured and returned as part of the tool call result.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type FailureMode = \"error\" | \"return\"\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Tool {\n  /**\n   * @since 1.0.0\n   * @category Models\n   */\n  export interface Variance<out Requirements> extends Pipeable {\n    readonly [TypeId]: VarianceStruct<Requirements>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category Models\n   */\n  export interface VarianceStruct<out Requirements> {\n    readonly _Requirements: Covariant<Requirements>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category Models\n   */\n  export interface ProviderDefinedProto {\n    readonly [ProviderDefinedTypeId]: ProviderDefinedTypeId\n  }\n}\n\n// =============================================================================\n// Type Guards\n// =============================================================================\n\n/**\n * Type guard to check if a value is a user-defined tool.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * const UserDefinedTool = Tool.make(\"Calculator\", {\n *   description: \"Performs basic arithmetic operations\",\n *   parameters: {\n *     operation: Schema.Literal(\"add\", \"subtract\", \"multiply\", \"divide\"),\n *     a: Schema.Number,\n *     b: Schema.Number\n *   },\n *   success: Schema.Number\n * })\n *\n * const ProviderDefinedTool = Tool.providerDefined({\n *   id: \"openai.web_search\",\n *   toolkitName: \"WebSearch\",\n *   providerName: \"web_search\",\n *   args: {\n *     query: Schema.String\n *   },\n *   success: Schema.Struct({\n *     results: Schema.Array(Schema.Struct({\n *       title: Schema.String,\n *       url: Schema.String,\n *       snippet: Schema.String\n *     }))\n *   })\n * })\n *\n * console.log(Tool.isUserDefined(UserDefinedTool))      // true\n * console.log(Tool.isUserDefined(ProviderDefinedTool))  // false\n * ```\n *\n * @since 1.0.0\n * @category Guards\n */\nexport const isUserDefined = (u: unknown): u is Tool<string, any, any> =>\n  Predicate.hasProperty(u, TypeId) && !isProviderDefined(u)\n\n/**\n * Type guard to check if a value is a provider-defined tool.\n *\n * @param u - The value to check\n * @returns `true` if the value is a provider-defined `Tool`, `false` otherwise\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * const UserDefinedTool = Tool.make(\"Calculator\", {\n *   description: \"Performs basic arithmetic operations\",\n *   parameters: {\n *     operation: Schema.Literal(\"add\", \"subtract\", \"multiply\", \"divide\"),\n *     a: Schema.Number,\n *     b: Schema.Number\n *   },\n *   success: Schema.Number\n * })\n *\n * const ProviderDefinedTool = Tool.providerDefined({\n *   id: \"openai.web_search\",\n *   toolkitName: \"WebSearch\",\n *   providerName: \"web_search\",\n *   args: {\n *     query: Schema.String\n *   },\n *   success: Schema.Struct({\n *     results: Schema.Array(Schema.Struct({\n *       title: Schema.String,\n *       url: Schema.String,\n *       snippet: Schema.String\n *     }))\n *   })\n * })\n *\n * console.log(Tool.isUserDefined(UserDefinedTool))      // false\n * console.log(Tool.isUserDefined(ProviderDefinedTool))  // true\n * ```\n *\n * @since 1.0.0\n * @category Guards\n */\nexport const isProviderDefined = (\n  u: unknown\n): u is ProviderDefined<string, any> => Predicate.hasProperty(u, ProviderDefinedTypeId)\n\n// =============================================================================\n// Utility Types\n// =============================================================================\n\n/**\n * A type which represents any `Tool`.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport interface Any extends Pipeable {\n  readonly [TypeId]: {\n    readonly _Requirements: Covariant<any>\n  }\n  readonly id: string\n  readonly name: string\n  readonly description?: string | undefined\n  readonly parametersSchema: AnyStructSchema\n  readonly successSchema: Schema.Schema.Any\n  readonly failureSchema: Schema.Schema.All\n  readonly failureMode: FailureMode\n  readonly annotations: Context.Context<never>\n}\n\n/**\n * A type which represents any provider-defined `Tool`.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport interface AnyProviderDefined extends Any {\n  readonly args: any\n  readonly argsSchema: AnyStructSchema\n  readonly requiresHandler: boolean\n  readonly providerName: string\n  readonly decodeResult: (\n    result: unknown\n  ) => Effect.Effect<any, AiError.AiError>\n}\n\n/**\n * @since 1.0.0\n * @category Utility Types\n */\nexport interface AnyStructSchema extends Pipeable {\n  readonly [Schema.TypeId]: any\n  readonly make: any\n  readonly Type: any\n  readonly Encoded: any\n  readonly Context: any\n  readonly ast: AST.AST\n  readonly fields: Schema.Struct.Fields\n  readonly annotations: any\n}\n\n/**\n * @since 1.0.0\n * @category Utility Types\n */\nexport interface AnyTaggedRequestSchema extends AnyStructSchema {\n  readonly _tag: string\n  readonly success: Schema.Schema.Any\n  readonly failure: Schema.Schema.All\n}\n\n/**\n * A utility type to convert a `Schema.TaggedRequest` into an `Tool`.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport interface FromTaggedRequest<S extends AnyTaggedRequestSchema> extends\n  Tool<\n    S[\"_tag\"],\n    {\n      readonly parameters: S\n      readonly success: S[\"success\"]\n      readonly failure: S[\"failure\"]\n      readonly failureMode: \"error\"\n    }\n  >\n{}\n\n/**\n * A utility type to extract the `Name` type from an `Tool`.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type Name<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? _Name\n  : never\n\n/**\n * A utility type to extract the type of the tool call parameters.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type Parameters<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? Schema.Struct.Type<_Config[\"parameters\"][\"fields\"]>\n  : never\n\n/**\n * A utility type to extract the encoded type of the tool call parameters.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type ParametersEncoded<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? Schema.Schema.Encoded<_Config[\"parameters\"]>\n  : never\n\n/**\n * A utility type to extract the schema for the parameters which an `Tool`\n * must be called with.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type ParametersSchema<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? _Config[\"parameters\"]\n  : never\n\n/**\n * A utility type to extract the type of the tool call result when it succeeds.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type Success<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? Schema.Schema.Type<_Config[\"success\"]>\n  : never\n\n/**\n * A utility type to extract the encoded type of the tool call result when\n * it succeeds.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type SuccessEncoded<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? Schema.Schema.Encoded<_Config[\"success\"]>\n  : never\n\n/**\n * A utility type to extract the schema for the return type of a tool call when\n * the tool call succeeds.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type SuccessSchema<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? _Config[\"success\"]\n  : never\n\n/**\n * A utility type to extract the type of the tool call result when it fails.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type Failure<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? Schema.Schema.Type<_Config[\"failure\"]>\n  : never\n\n/**\n * A utility type to extract the encoded type of the tool call result when\n * it fails.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type FailureEncoded<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? Schema.Schema.Encoded<_Config[\"failure\"]>\n  : never\n\n/**\n * A utility type to extract the type of the tool call result whether it\n * succeeds or fails.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type Result<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? Success<T> | Failure<T>\n  : never\n\n/**\n * A utility type to extract the encoded type of the tool call result whether\n * it succeeds or fails.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type ResultEncoded<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? SuccessEncoded<T> | FailureEncoded<T>\n  : never\n\n/**\n * A utility type to extract the requirements of an `Tool`.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type Requirements<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ?\n    | _Config[\"parameters\"][\"Context\"]\n    | _Config[\"success\"][\"Context\"]\n    | _Config[\"failure\"][\"Context\"]\n    | _Requirements\n  : never\n\n/**\n * Represents an `Tool` that has been implemented within the application.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Handler<Name extends string> {\n  readonly _: unique symbol\n  readonly name: Name\n  readonly context: Context.Context<never>\n  readonly handler: (params: any) => Effect.Effect<any, any>\n}\n\n/**\n * Represents the result of calling the handler for a particular `Tool`.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface HandlerResult<Tool extends Any> {\n  /**\n   * Whether the result of executing the tool call handler was an error or not.\n   */\n  readonly isFailure: boolean\n  /**\n   * The result of executing the handler for a particular tool.\n   */\n  readonly result: Result<Tool>\n  /**\n   * The pre-encoded tool call result of executing the handler for a particular\n   * tool as a JSON-serializable value. The encoded result can be incorporated\n   * into subsequent requests to the large language model.\n   */\n  readonly encodedResult: unknown\n}\n\n/**\n * A utility type which represents the possible errors that can be raised by\n * a tool call's handler.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type HandlerError<T> = T extends Tool<\n  infer _Name,\n  infer _Config,\n  infer _Requirements\n> ? _Config[\"failureMode\"] extends \"error\" ? _Config[\"failure\"][\"Type\"]\n  : never\n  : never\n\n/**\n * A utility type to create a union of `Handler` types for all tools in a\n * record.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type HandlersFor<Tools extends Record<string, Any>> = {\n  [Name in keyof Tools]: RequiresHandler<Tools[Name]> extends true ? Handler<Tools[Name][\"name\"]>\n    : never\n}[keyof Tools]\n\n/**\n * A utility type to determine if the specified tool requires a user-defined\n * handler to be implemented.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type RequiresHandler<Tool extends Any> = Tool extends ProviderDefined<\n  infer _Name,\n  infer _Config,\n  infer _RequiresHandler\n> ? _RequiresHandler\n  : true\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\nconst Proto = {\n  [TypeId]: { _Requirements: identity },\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  addDependency(this: Any) {\n    return userDefinedProto({ ...this })\n  },\n  setParameters(\n    this: Any,\n    parametersSchema: Schema.Struct<any> | Schema.Struct.Fields\n  ) {\n    return userDefinedProto({\n      ...this,\n      parametersSchema: Schema.isSchema(parametersSchema)\n        ? (parametersSchema as any)\n        : Schema.Struct(parametersSchema as any)\n    })\n  },\n  setSuccess(this: Any, successSchema: Schema.Schema.Any) {\n    return userDefinedProto({\n      ...this,\n      successSchema\n    })\n  },\n  setFailure(this: Any, failureSchema: Schema.Schema.All) {\n    return userDefinedProto({\n      ...this,\n      failureSchema\n    })\n  },\n  annotate<I, S>(this: Any, tag: Context.Tag<I, S>, value: S) {\n    return userDefinedProto({\n      ...this,\n      annotations: Context.add(this.annotations, tag, value)\n    })\n  },\n  annotateContext<I>(this: Any, context: Context.Context<I>) {\n    return userDefinedProto({\n      ...this,\n      annotations: Context.merge(this.annotations, context)\n    })\n  }\n}\n\nconst ProviderDefinedProto = {\n  ...Proto,\n  [ProviderDefinedTypeId]: ProviderDefinedTypeId\n}\n\nconst userDefinedProto = <\n  const Name extends string,\n  Parameters extends AnyStructSchema,\n  Success extends Schema.Schema.Any,\n  Failure extends Schema.Schema.All,\n  Mode extends FailureMode\n>(options: {\n  readonly name: Name\n  readonly description?: string | undefined\n  readonly parametersSchema: Parameters\n  readonly successSchema: Success\n  readonly failureSchema: Failure\n  readonly annotations: Context.Context<never>\n  readonly failureMode: Mode\n}): Tool<\n  Name,\n  {\n    readonly parameters: Parameters\n    readonly success: Success\n    readonly failure: Failure\n    readonly failureMode: Mode\n  }\n> => {\n  const self = Object.assign(Object.create(Proto), options)\n  self.id = `@effect/ai/Tool/${options.name}`\n  return self\n}\n\nconst providerDefinedProto = <\n  const Name extends string,\n  Args extends AnyStructSchema,\n  Parameters extends AnyStructSchema,\n  Success extends Schema.Schema.Any,\n  Failure extends Schema.Schema.All,\n  RequiresHandler extends boolean,\n  Mode extends FailureMode\n>(options: {\n  readonly id: string\n  readonly name: Name\n  readonly providerName: string\n  readonly args: Args[\"Encoded\"]\n  readonly argsSchema: Args\n  readonly requiresHandler: RequiresHandler\n  readonly parametersSchema: Parameters\n  readonly successSchema: Success\n  readonly failureSchema: Failure\n  readonly failureMode: FailureMode\n}): ProviderDefined<\n  Name,\n  {\n    readonly args: Args\n    readonly parameters: Parameters\n    readonly success: Success\n    readonly failure: Failure\n    readonly failureMode: Mode\n  },\n  RequiresHandler\n> => Object.assign(Object.create(ProviderDefinedProto), options)\n\nconst constEmptyStruct = Schema.Struct({})\n\n/**\n * Creates a user-defined tool with the specified name and configuration.\n *\n * This is the primary constructor for creating custom tools that AI models\n * can call. The tool definition includes parameter validation, success/failure\n * schemas, and optional service dependencies.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * // Simple tool with no parameters\n * const GetCurrentTime = Tool.make(\"GetCurrentTime\", {\n *   description: \"Returns the current timestamp\",\n *   success: Schema.Number\n * })\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = <\n  const Name extends string,\n  Parameters extends Schema.Struct.Fields = {},\n  Success extends Schema.Schema.Any = typeof Schema.Void,\n  Failure extends Schema.Schema.All = typeof Schema.Never,\n  Mode extends FailureMode | undefined = undefined,\n  Dependencies extends Array<Context.Tag<any, any>> = []\n>(\n  /**\n   * The unique name identifier for this tool.\n   */\n  name: Name,\n  options?: {\n    /**\n     * An optional description explaining what the tool does.\n     */\n    readonly description?: string | undefined\n    /**\n     * Schema defining the parameters this tool accepts.\n     */\n    readonly parameters?: Parameters | undefined\n    /**\n     * Schema for successful tool execution results.\n     */\n    readonly success?: Success | undefined\n    /**\n     * Schema for tool execution failures.\n     */\n    readonly failure?: Failure | undefined\n    /**\n     * The strategy used for handling errors returned from tool call handler\n     * execution.\n     *\n     * If set to `\"error\"` (the default), errors that occur during tool call handler\n     * execution will be returned in the error channel of the calling effect.\n     *\n     * If set to `\"return\"`, errors that occur during tool call handler execution\n     * will be captured and returned as part of the tool call result.\n     */\n    readonly failureMode?: Mode\n    /**\n     * Service dependencies required by the tool handler.\n     */\n    readonly dependencies?: Dependencies | undefined\n  }\n): Tool<\n  Name,\n  {\n    readonly parameters: Schema.Struct<Parameters>\n    readonly success: Success\n    readonly failure: Failure\n    readonly failureMode: Mode extends undefined ? \"error\" : Mode\n  },\n  Context.Tag.Identifier<Dependencies[number]>\n> => {\n  const successSchema = options?.success ?? Schema.Void\n  const failureSchema = options?.failure ?? Schema.Never\n  return userDefinedProto({\n    name,\n    description: options?.description,\n    parametersSchema: options?.parameters\n      ? Schema.Struct(options?.parameters as any)\n      : constEmptyStruct,\n    successSchema,\n    failureSchema,\n    failureMode: options?.failureMode ?? \"error\",\n    annotations: Context.empty()\n  }) as any\n}\n\n/**\n * Creates a provider-defined tool which leverages functionality built into a\n * large language model provider (e.g. web search, code execution).\n *\n * These tools are executed by the large language model provider rather than\n * by your application. However, they can optionally require custom handlers\n * implemented in your application to process provider generated results.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * // Web search tool provided by OpenAI\n * const WebSearch = Tool.providerDefined({\n *   id: \"openai.web_search\",\n *   toolkitName: \"WebSearch\",\n *   providerName: \"web_search\",\n *   args: {\n *     query: Schema.String\n *   },\n *   success: Schema.Struct({\n *     results: Schema.Array(Schema.Struct({\n *       title: Schema.String,\n *       url: Schema.String,\n *       content: Schema.String\n *     }))\n *   })\n * })\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const providerDefined = <\n  const Name extends string,\n  Args extends Schema.Struct.Fields = {},\n  Parameters extends Schema.Struct.Fields = {},\n  Success extends Schema.Schema.Any = typeof Schema.Void,\n  Failure extends Schema.Schema.All = typeof Schema.Never,\n  RequiresHandler extends boolean = false\n>(options: {\n  /**\n   * Unique identifier following format `<provider>.<tool-name>`.\n   */\n  readonly id: `${string}.${string}`\n  /**\n   * Name used by the Toolkit to identify this tool.\n   */\n  readonly toolkitName: Name\n  /**\n   * Name of the tool as recognized by the AI provider.\n   */\n  readonly providerName: string\n  /**\n   * Schema for user-provided configuration arguments.\n   */\n  readonly args: Args\n  /**\n   * Whether this tool requires a custom handler implementation.\n   */\n  readonly requiresHandler?: RequiresHandler | undefined\n  /**\n   * Schema for parameters the provider sends when calling the tool.\n   */\n  readonly parameters?: Parameters | undefined\n  /**\n   * Schema for successful tool execution results.\n   */\n  readonly success?: Success | undefined\n  /**\n   * Schema for failed tool execution results.\n   */\n  readonly failure?: Failure | undefined\n}) =>\n<Mode extends FailureMode | undefined = undefined>(\n  args: RequiresHandler extends true ? Schema.Simplify<\n      Schema.Struct.Encoded<Args> & {\n        /**\n         * The strategy used for handling errors returned from tool call handler\n         * execution.\n         *\n         * If set to `\"error\"` (the default), errors that occur during tool call handler\n         * execution will be returned in the error channel of the calling effect.\n         *\n         * If set to `\"return\"`, errors that occur during tool call handler execution\n         * will be captured and returned as part of the tool call result.\n         */\n        readonly failureMode?: Mode\n      }\n    >\n    : Schema.Simplify<Schema.Struct.Encoded<Args>>\n): ProviderDefined<\n  Name,\n  {\n    readonly args: Schema.Struct<Args>\n    readonly parameters: Schema.Struct<Parameters>\n    readonly success: Success\n    readonly failure: Failure\n    readonly failureMode: Mode extends undefined ? \"error\" : Mode\n  },\n  RequiresHandler\n> => {\n  const failureMode = \"failureMode\" in args ? args.failureMode : undefined\n  const successSchema = options?.success ?? Schema.Void\n  const failureSchema = options?.failure ?? Schema.Never\n  return providerDefinedProto({\n    id: options.id,\n    name: options.toolkitName,\n    providerName: options.providerName,\n    args,\n    argsSchema: Schema.Struct(options.args as any),\n    requiresHandler: options.requiresHandler ?? false,\n    parametersSchema: options?.parameters\n      ? Schema.Struct(options?.parameters as any)\n      : constEmptyStruct,\n    successSchema,\n    failureSchema,\n    failureMode: failureMode ?? \"error\"\n  }) as any\n}\n\n/**\n * Creates a Tool from a Schema.TaggedRequest.\n *\n * This utility function converts Effect's TaggedRequest schemas into Tool\n * definitions, automatically mapping the request parameters, success, and\n * failure schemas.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * // Define a tagged request for user operations\n * class GetUser extends Schema.TaggedRequest<GetUser>()(\"GetUser\", {\n *   success: Schema.Struct({\n *     id: Schema.Number,\n *     name: Schema.String,\n *     email: Schema.String\n *   }),\n *   failure: Schema.Struct({\n *     error: Schema.Literal(\"UserNotFound\", \"DatabaseError\"),\n *     message: Schema.String\n *   }),\n *   payload: {\n *     userId: Schema.Number\n *   }\n * }) {}\n *\n * // Convert to a Tool\n * const getUserTool = Tool.fromTaggedRequest(GetUser)\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const fromTaggedRequest = <S extends AnyTaggedRequestSchema>(\n  schema: S\n): FromTaggedRequest<S> =>\n  userDefinedProto({\n    name: schema._tag,\n    description: Option.getOrUndefined(\n      AST.getDescriptionAnnotation((schema.ast as any).to)\n    ),\n    parametersSchema: schema,\n    successSchema: schema.success,\n    failureSchema: schema.failure,\n    failureMode: \"error\",\n    annotations: Context.empty()\n  }) as any\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\n/**\n * Extracts the description from a tool's metadata.\n *\n * Returns the tool's description if explicitly set, otherwise attempts to\n * extract it from the parameter schema's AST annotations.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n *\n * const myTool = Tool.make(\"example\", {\n *   description: \"This is an example tool\"\n * })\n *\n * const description = Tool.getDescription(myTool)\n * console.log(description) // \"This is an example tool\"\n * ```\n *\n * @since 1.0.0\n * @category Utilities\n */\nexport const getDescription = <\n  Name extends string,\n  Config extends {\n    readonly parameters: AnyStructSchema\n    readonly success: Schema.Schema.Any\n    readonly failure: Schema.Schema.All\n    readonly failureMode: FailureMode\n  }\n>(\n  /**\n   * The tool to get the description from.\n   */\n  tool: Tool<Name, Config>\n): string | undefined => {\n  if (Predicate.isNotUndefined(tool.description)) {\n    return tool.description\n  }\n  return getDescriptionFromSchemaAst(tool.parametersSchema.ast)\n}\n\n/**\n * @since 1.0.0\n * @category Utilities\n */\nexport const getDescriptionFromSchemaAst = (\n  ast: AST.AST\n): string | undefined => {\n  const annotations = ast._tag === \"Transformation\"\n    ? {\n      ...ast.to.annotations,\n      ...ast.annotations\n    }\n    : ast.annotations\n  return AST.DescriptionAnnotationId in annotations\n    ? (annotations[AST.DescriptionAnnotationId] as string)\n    : undefined\n}\n\n/**\n * Generates a JSON Schema for a tool.\n *\n * This function creates a JSON Schema representation that can be used by\n * large language models to indicate the structure and type of the parameters\n * that a given tool call should receive.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * const weatherTool = Tool.make(\"get_weather\", {\n *   parameters: {\n *     location: Schema.String,\n *     units: Schema.optional(Schema.Literal(\"celsius\", \"fahrenheit\"))\n *   }\n * })\n *\n * const jsonSchema = Tool.getJsonSchema(weatherTool)\n * console.log(jsonSchema)\n * // {\n * //   type: \"object\",\n * //   properties: {\n * //     location: { type: \"string\" },\n * //     units: { type: \"string\", enum: [\"celsius\", \"fahrenheit\"] }\n * //   },\n * //   required: [\"location\"]\n * // }\n * ```\n *\n * @since 1.0.0\n * @category Utilities\n */\nexport const getJsonSchema = <\n  Name extends string,\n  Config extends {\n    readonly parameters: AnyStructSchema\n    readonly success: Schema.Schema.Any\n    readonly failure: Schema.Schema.All\n    readonly failureMode: FailureMode\n  }\n>(\n  tool: Tool<Name, Config>\n): JsonSchema.JsonSchema7 => getJsonSchemaFromSchemaAst(tool.parametersSchema.ast)\n\n/**\n * @since 1.0.0\n * @category Utilities\n */\nexport const getJsonSchemaFromSchemaAst = (\n  ast: AST.AST\n): JsonSchema.JsonSchema7 => {\n  const $defs = {}\n  const schema = JsonSchema.fromAST(ast, {\n    definitions: $defs,\n    topLevelReferenceStrategy: \"skip\"\n  })\n  if (Object.keys($defs).length === 0) return schema\n  ;(schema as any).$defs = $defs\n  return schema\n}\n\n// =============================================================================\n// Annotations\n// =============================================================================\n\n/**\n * Annotation for providing a human-readable title for tools.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n *\n * const myTool = Tool.make(\"calculate_tip\")\n *   .annotate(Tool.Title, \"Tip Calculator\")\n * ```\n *\n * @since 1.0.0\n * @category Annotations\n */\nexport class Title extends Context.Tag(\"@effect/ai/Tool/Title\")<\n  Title,\n  string\n>() {}\n\n/**\n * Annotation indicating whether a tool only reads data without making changes.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n *\n * const readOnlyTool = Tool.make(\"get_user_info\")\n *   .annotate(Tool.Readonly, true)\n * ```\n *\n * @since 1.0.0\n * @category Annotations\n */\nexport class Readonly extends Context.Reference<Readonly>()(\n  \"@effect/ai/Tool/Readonly\",\n  {\n    defaultValue: constFalse\n  }\n) {}\n\n/**\n * Annotation indicating whether a tool performs destructive operations.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n *\n * const safeTool = Tool.make(\"search_database\")\n *   .annotate(Tool.Destructive, false)\n * ```\n *\n * @since 1.0.0\n * @category Annotations\n */\nexport class Destructive extends Context.Reference<Destructive>()(\n  \"@effect/ai/Tool/Destructive\",\n  {\n    defaultValue: constTrue\n  }\n) {}\n\n/**\n * Annotation indicating whether a tool can be called multiple times safely.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n *\n * const idempotentTool = Tool.make(\"get_current_time\")\n *   .annotate(Tool.Idempotent, true)\n * ```\n *\n * @since 1.0.0\n * @category Annotations\n */\nexport class Idempotent extends Context.Reference<Idempotent>()(\n  \"@effect/ai/Tool/Idempotent\",\n  {\n    defaultValue: constFalse\n  }\n) {}\n\n/**\n * Annotation indicating whether a tool can handle arbitrary external data.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n *\n * const restrictedTool = Tool.make(\"internal_operation\")\n *   .annotate(Tool.OpenWorld, false)\n * ```\n *\n * @since 1.0.0\n * @category Annotations\n */\nexport class OpenWorld extends Context.Reference<OpenWorld>()(\n  \"@effect/ai/Tool/OpenWorld\",\n  {\n    defaultValue: constTrue\n  }\n) {}\n\n// Licensed under BSD-3-Clause (below code only)\n// Code adapted from https://github.com/fastify/secure-json-parse/blob/783fcb1b5434709466759847cec974381939673a/index.js\n//\n// Copyright (c) Effectful Technologies, Inc (https://effectful.co)\n// Copyright (c) 2019 The Fastify Team\n// Copyright (c) 2019, Sideway Inc, and project contributors\n// All rights reserved.\n//\n// The complete list of contributors can be found at:\n// - https://github.com/hapijs/bourne/graphs/contributors\n// - https://github.com/fastify/secure-json-parse/graphs/contributors\n// - https://github.com/Effect-TS/effect/commits/main/packages/ai/ai/src/Tool.ts\n//\n// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n//\n// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nconst suspectProtoRx = /\"__proto__\"\\s*:/\nconst suspectConstructorRx = /\"constructor\"\\s*:/\n\nfunction _parse(text: string) {\n  // Parse normally\n  const obj = JSON.parse(text)\n\n  // Ignore null and non-objects\n  if (obj === null || typeof obj !== \"object\") {\n    return obj\n  }\n\n  if (\n    suspectProtoRx.test(text) === false &&\n    suspectConstructorRx.test(text) === false\n  ) {\n    return obj\n  }\n\n  // Scan result for proto keys\n  return filter(obj)\n}\n\nfunction filter(obj: any) {\n  let next = [obj]\n\n  while (next.length) {\n    const nodes = next\n    next = []\n\n    for (const node of nodes) {\n      if (Object.prototype.hasOwnProperty.call(node, \"__proto__\")) {\n        throw new SyntaxError(\"Object contains forbidden prototype property\")\n      }\n\n      if (\n        Object.prototype.hasOwnProperty.call(node, \"constructor\") &&\n        Object.prototype.hasOwnProperty.call(node.constructor, \"prototype\")\n      ) {\n        throw new SyntaxError(\"Object contains forbidden prototype property\")\n      }\n\n      for (const key in node) {\n        const value = node[key]\n        if (value && typeof value === \"object\") {\n          next.push(value)\n        }\n      }\n    }\n  }\n  return obj\n}\n\n/**\n * **Unsafe**: This function will throw an error if an insecure property is\n * found in the parsed JSON or if the provided JSON text is not parseable.\n *\n * @since 1.0.0\n * @category Utilities\n */\nexport const unsafeSecureJsonParse = (text: string): unknown => {\n  // Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90\n  const { stackTraceLimit } = Error\n  Error.stackTraceLimit = 0\n  try {\n    return _parse(text)\n  } finally {\n    Error.stackTraceLimit = stackTraceLimit\n  }\n}\n"
  },
  {
    "path": "packages/ai/ai/src/Toolkit.ts",
    "content": "/**\n * The `Toolkit` module allows for creating and implementing a collection of\n * `Tool`s which can be used to enhance the capabilities of a large language\n * model beyond simple text generation.\n *\n * @example\n * ```ts\n * import { Toolkit, Tool } from \"@effect/ai\"\n * import { Effect, Schema } from \"effect\"\n *\n * // Create individual tools\n * const GetCurrentTime = Tool.make(\"GetCurrentTime\", {\n *   description: \"Get the current timestamp\",\n *   success: Schema.Number\n * })\n *\n * const GetWeather = Tool.make(\"GetWeather\", {\n *   description: \"Get weather for a location\",\n *   parameters: { location: Schema.String },\n *   success: Schema.Struct({\n *     temperature: Schema.Number,\n *     condition: Schema.String\n *   })\n * })\n *\n * // Create a toolkit with multiple tools\n * const MyToolkit = Toolkit.make(GetCurrentTime, GetWeather)\n *\n * const MyToolkitLayer = MyToolkit.toLayer({\n *   GetCurrentTime: () => Effect.succeed(Date.now()),\n *   GetWeather: ({ location }) => Effect.succeed({\n *     temperature: 72,\n *     condition: \"sunny\"\n *   })\n * })\n * ```\n *\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { CommitPrototype } from \"effect/Effectable\"\nimport { identity } from \"effect/Function\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport { BaseProto as InspectableProto } from \"effect/Inspectable\"\nimport * as Layer from \"effect/Layer\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as AiError from \"./AiError.js\"\nimport * as Tool from \"./Tool.js\"\n\n/**\n * Unique identifier for toolkit instances.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport const TypeId = \"~@effect/ai/Toolkit\"\n\n/**\n * Type-level representation of the toolkit identifier.\n *\n * @since 1.0.0\n * @category Type Ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * Represents a collection of tools which can be used to enhance the\n * capabilities of a large language model.\n *\n * @example\n * ```ts\n * import { Toolkit, Tool } from \"@effect/ai\"\n * import { Effect, Schema } from \"effect\"\n *\n * // Create individual tools\n * const GetCurrentTime = Tool.make(\"GetCurrentTime\", {\n *   description: \"Get the current timestamp\",\n *   success: Schema.Number\n * })\n *\n * const GetWeather = Tool.make(\"GetWeather\", {\n *   description: \"Get weather for a location\",\n *   parameters: { location: Schema.String },\n *   success: Schema.Struct({\n *     temperature: Schema.Number,\n *     condition: Schema.String\n *   })\n * })\n *\n * // Create a toolkit with multiple tools\n * const MyToolkit = Toolkit.make(GetCurrentTime, GetWeather)\n *\n * const MyToolkitLayer = MyToolkit.toLayer({\n *   GetCurrentTime: () => Effect.succeed(Date.now()),\n *   GetWeather: ({ location }) => Effect.succeed({\n *     temperature: 72,\n *     condition: \"sunny\"\n *   })\n * })\n * ```\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Toolkit<in out Tools extends Record<string, Tool.Any>> extends\n  Effect.Effect<\n    WithHandler<Tools>,\n    never,\n    Tool.HandlersFor<Tools>\n  >,\n  Inspectable,\n  Pipeable\n{\n  readonly [TypeId]: TypeId\n\n  new(_: never): {}\n\n  /**\n   * A record containing all tools in this toolkit.\n   */\n  readonly tools: Tools\n\n  /**\n   * A helper method which can be used for type-safe handler declarations.\n   */\n  of<Handlers extends HandlersFrom<Tools>>(handlers: Handlers): Handlers\n\n  /**\n   * Converts a toolkit into an Effect Context containing handlers for each tool\n   * in the toolkit.\n   */\n  toContext<Handlers extends HandlersFrom<Tools>, EX = never, RX = never>(\n    build: Handlers | Effect.Effect<Handlers, EX, RX>\n  ): Effect.Effect<Context.Context<Tool.HandlersFor<Tools>>, EX, RX>\n\n  /**\n   * Converts a toolkit into a Layer containing handlers for each tool in the\n   * toolkit.\n   */\n  toLayer<Handlers extends HandlersFrom<Tools>, EX = never, RX = never>(\n    /**\n     * Handler functions or Effect that produces handlers.\n     */\n    build: Handlers | Effect.Effect<Handlers, EX, RX>\n  ): Layer.Layer<Tool.HandlersFor<Tools>, EX, Exclude<RX, Scope.Scope>>\n}\n\n/**\n * A utility type which structurally represents any toolkit instance.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport interface Any {\n  readonly [TypeId]: TypeId\n  readonly tools: Record<string, Tool.Any>\n}\n\n/**\n * A utility type which can be used to extract the tool definitions from a\n * toolkit.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type Tools<T> = T extends Toolkit<infer Tools> ? Tools : never\n\n/**\n * A utility type which can transforms either a record or an array of tools into\n * a record where keys are tool names and values are the tool instances.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type ToolsByName<Tools> = Tools extends Record<string, Tool.Any> ?\n  { readonly [Name in keyof Tools]: Tools[Name] }\n  : Tools extends ReadonlyArray<Tool.Any> ? { readonly [Tool in Tools[number] as Tool[\"name\"]]: Tool }\n  : never\n\n/**\n * A utility type that maps tool names to their required handler functions.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type HandlersFrom<Tools extends Record<string, Tool.Any>> = {\n  readonly [Name in keyof Tools as Tool.RequiresHandler<Tools[Name]> extends true ? Name : never]: (\n    params: Tool.Parameters<Tools[Name]>\n  ) => Effect.Effect<\n    Tool.Success<Tools[Name]>,\n    Tool.Failure<Tools[Name]>,\n    Tool.Requirements<Tools[Name]>\n  >\n}\n\n/**\n * A utility type which can be used to extract the tools from a toolkit with handlers.\n *\n * @since 1.0.0\n * @category Utility Types\n */\n\nexport type WithHandlerTools<T> = T extends WithHandler<infer Tools> ? Tools : never\n\n/**\n * A toolkit instance with registered handlers ready for tool execution.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface WithHandler<in out Tools extends Record<string, Tool.Any>> {\n  /**\n   * The tools available in this toolkit instance.\n   */\n  readonly tools: Tools\n\n  /**\n   * Handler function for executing tool calls.\n   *\n   * Receives a tool name and parameters, validates the input, executes the\n   * corresponding handler, and returns both the typed result and encoded result.\n   */\n  readonly handle: <Name extends keyof Tools>(\n    /**\n     * The name of the tool to execute.\n     */\n    name: Name,\n    /**\n     * Parameters to pass to the tool handler.\n     */\n    params: Tool.Parameters<Tools[Name]>\n  ) => Effect.Effect<\n    Tool.HandlerResult<Tools[Name]>,\n    Tool.Failure<Tools[Name]>,\n    Tool.Requirements<Tools[Name]>\n  >\n}\n\nconst Proto = {\n  ...CommitPrototype,\n  ...InspectableProto,\n  of: identity,\n  toContext(\n    this: Toolkit<Record<string, Tool.Any>>,\n    build: Record<string, (params: any) => any> | Effect.Effect<Record<string, (params: any) => any>>\n  ) {\n    return Effect.gen(this, function*() {\n      const context = yield* Effect.context<never>()\n      const handlers = Effect.isEffect(build) ? yield* build : build\n      const contextMap = new Map<string, unknown>()\n      for (const [name, handler] of Object.entries(handlers)) {\n        const tool = this.tools[name]!\n        contextMap.set(tool.id, { handler, context })\n      }\n      return Context.unsafeMake(contextMap)\n    })\n  },\n  toLayer(\n    this: Toolkit<Record<string, Tool.Any>>,\n    build: Record<string, (params: any) => any> | Effect.Effect<Record<string, (params: any) => any>>\n  ) {\n    return Layer.scopedContext(this.toContext(build))\n  },\n  commit(this: Toolkit<Record<string, Tool.Any>>) {\n    return Effect.gen(this, function*() {\n      const tools = this.tools\n      const context = yield* Effect.context<never>()\n      const schemasCache = new WeakMap<any, {\n        readonly context: Context.Context<never>\n        readonly handler: (params: any) => Effect.Effect<any, any>\n        readonly decodeParameters: (u: unknown) => Effect.Effect<Tool.Parameters<any>, ParseError>\n        readonly validateResult: (u: unknown) => Effect.Effect<unknown, ParseError>\n        readonly encodeResult: (u: unknown) => Effect.Effect<unknown, ParseError>\n      }>()\n      const getSchemas = (tool: Tool.Any) => {\n        let schemas = schemasCache.get(tool)\n        if (Predicate.isUndefined(schemas)) {\n          const handler = context.unsafeMap.get(tool.id)! as Tool.Handler<any>\n          const decodeParameters = Schema.decodeUnknown(tool.parametersSchema) as any\n          const resultSchema = Schema.Union(tool.successSchema, tool.failureSchema)\n          const validateResult = Schema.validate(resultSchema) as any\n          const encodeResult = Schema.encodeUnknown(resultSchema) as any\n          schemas = {\n            context: handler.context,\n            handler: handler.handler,\n            decodeParameters,\n            validateResult,\n            encodeResult\n          }\n          schemasCache.set(tool, schemas)\n        }\n        return schemas\n      }\n      const handle = Effect.fn(\"Toolkit.handle\", { captureStackTrace: false })(\n        function*(name: string, params: unknown) {\n          yield* Effect.annotateCurrentSpan({ tool: name, parameters: params })\n          const tool = tools[name]\n          if (Predicate.isUndefined(tool)) {\n            const toolNames = Object.keys(tools).join(\",\")\n            return yield* new AiError.MalformedOutput({\n              module: \"Toolkit\",\n              method: `${name}.handle`,\n              description: `Failed to find tool with name '${name}' in toolkit - available tools: ${toolNames}`\n            })\n          }\n          const schemas = getSchemas(tool)\n          const decodedParams = yield* Effect.mapError(\n            schemas.decodeParameters(params),\n            (cause) =>\n              new AiError.MalformedOutput({\n                module: \"Toolkit\",\n                method: `${name}.handle`,\n                description: `Failed to decode tool call parameters for tool '${name}' from:\\n'${\n                  JSON.stringify(params, undefined, 2)\n                }'`,\n                cause\n              })\n          )\n          const { isFailure, result } = yield* schemas.handler(decodedParams).pipe(\n            Effect.map((result) => ({ result, isFailure: false })),\n            Effect.catchAll((error) =>\n              // If the tool handler failed, check the tool's failure mode to\n              // determine how the result should be returned to the end user\n              tool.failureMode === \"error\"\n                ? Effect.fail(error)\n                : Effect.succeed({ result: error, isFailure: true })\n            ),\n            Effect.tap(({ result }) => schemas.validateResult(result)),\n            Effect.mapInputContext((input) => Context.merge(schemas.context, input)),\n            Effect.mapError((cause) =>\n              ParseResult.isParseError(cause)\n                ? new AiError.MalformedInput({\n                  module: \"Toolkit\",\n                  method: `${name}.handle`,\n                  description: `Failed to validate tool call result for tool '${name}'`,\n                  cause\n                })\n                : cause\n            )\n          )\n          const encodedResult = yield* Effect.mapError(\n            schemas.encodeResult(result),\n            (cause) =>\n              new AiError.MalformedInput({\n                module: \"Toolkit\",\n                method: `${name}.handle`,\n                description: `Failed to encode tool call result for tool '${name}'`,\n                cause\n              })\n          )\n          return {\n            isFailure,\n            result,\n            encodedResult\n          } satisfies Tool.HandlerResult<any>\n        }\n      )\n      return {\n        tools,\n        handle\n      } satisfies WithHandler<Record<string, any>>\n    })\n  },\n  toJSON(this: Toolkit<any>): unknown {\n    return {\n      _id: \"@effect/ai/Toolkit\",\n      tools: Array.from(Object.values(this.tools)).map((tool) => (tool as Tool.Any).name)\n    }\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makeProto = <Tools extends Record<string, Tool.Any>>(tools: Tools): Toolkit<Tools> =>\n  Object.assign(function() {}, Proto, { tools }) as any\n\nconst resolveInput = <Tools extends ReadonlyArray<Tool.Any>>(\n  ...tools: Tools\n): Record<string, Tools[number]> => {\n  const output = {} as Record<string, Tools[number]>\n  for (const tool of tools) {\n    const value = (Schema.isSchema(tool) ? Tool.fromTaggedRequest(tool as any) : tool) as any\n    output[tool.name] = value\n  }\n  return output\n}\n\n/**\n * An empty toolkit with no tools.\n *\n * Useful as a starting point for building toolkits or as a default value. Can\n * be extended using the merge function to add tools.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const empty: Toolkit<{}> = makeProto({})\n\n/**\n * Creates a new toolkit from the specified tools.\n *\n * This is the primary constructor for creating toolkits. It accepts multiple tools\n * and organizes them into a toolkit that can be provided to AI language models.\n * Tools can be either Tool instances or TaggedRequest schemas.\n *\n * @example\n * ```ts\n * import { Toolkit, Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * const GetCurrentTime = Tool.make(\"GetCurrentTime\", {\n *   description: \"Get the current timestamp\",\n *   success: Schema.Number\n * })\n *\n * const GetWeather = Tool.make(\"get_weather\", {\n *   description: \"Get weather information\",\n *   parameters: { location: Schema.String },\n *   success: Schema.Struct({\n *     temperature: Schema.Number,\n *     condition: Schema.String\n *   })\n * })\n *\n * const toolkit = Toolkit.make(GetCurrentTime, GetWeather)\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = <Tools extends ReadonlyArray<Tool.Any>>(\n  ...tools: Tools\n): Toolkit<ToolsByName<Tools>> => makeProto(resolveInput(...tools)) as any\n\n/**\n * A utility type which simplifies a record type.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type SimplifyRecord<T> = { [K in keyof T]: T[K] } & {}\n\n/**\n * A utility type which merges two records of tools together.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type MergeRecords<U> = {\n  readonly [K in Extract<U extends unknown ? keyof U : never, string>]: Extract<\n    U extends Record<K, infer V> ? V : never,\n    Tool.Any\n  >\n}\n\n/**\n * A utility type which merges the tool calls of two toolkits into a single\n * toolkit.\n *\n * @since 1.0.0\n * @category Utility Types\n */\nexport type MergedTools<Toolkits extends ReadonlyArray<Any>> = SimplifyRecord<\n  MergeRecords<Tools<Toolkits[number]>>\n>\n\n/**\n * Merges multiple toolkits into a single toolkit.\n *\n * Combines all tools from the provided toolkits into one unified toolkit.\n * If there are naming conflicts, tools from later toolkits will override\n * tools from earlier ones.\n *\n * @example\n * ```ts\n * import { Toolkit, Tool } from \"@effect/ai\"\n *\n * const mathToolkit = Toolkit.make(\n *   Tool.make(\"add\"),\n *   Tool.make(\"subtract\")\n * )\n *\n * const utilityToolkit = Toolkit.make(\n *   Tool.make(\"get_time\"),\n *   Tool.make(\"get_weather\")\n * )\n *\n * const combined = Toolkit.merge(mathToolkit, utilityToolkit)\n * // combined now has: add, subtract, get_time, get_weather\n * ```\n *\n * @example\n * ```ts\n * import { Toolkit, Tool } from \"@effect/ai\"\n *\n * // Incremental toolkit building\n * const baseToolkit = Toolkit.make(Tool.make(\"base_tool\"))\n * const extendedToolkit = Toolkit.merge(\n *   baseToolkit,\n *   Toolkit.make(Tool.make(\"additional_tool\")),\n *   Toolkit.make(Tool.make(\"another_tool\"))\n * )\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const merge = <const Toolkits extends ReadonlyArray<Any>>(\n  /**\n   * The toolkits to merge together.\n   */\n  ...toolkits: Toolkits\n): Toolkit<MergedTools<Toolkits>> => {\n  const tools = {} as Record<string, any>\n  for (const toolkit of toolkits) {\n    for (const [name, tool] of Object.entries(toolkit.tools)) {\n      tools[name] = tool\n    }\n  }\n  return makeProto(tools) as any\n}\n"
  },
  {
    "path": "packages/ai/ai/src/index.ts",
    "content": "/**\n * The `AiError` module provides comprehensive error handling for AI operations.\n *\n * This module defines a hierarchy of error types that can occur when working\n * with AI services, including HTTP request/response errors, input/output\n * validation errors, and general runtime errors. All errors follow Effect's\n * structured error patterns and provide detailed context for debugging.\n *\n * ## Error Types\n *\n * - **HttpRequestError**: Errors occurring during HTTP request processing\n * - **HttpResponseError**: Errors occurring during HTTP response processing\n * - **MalformedInput**: Errors when input data doesn't match expected format\n * - **MalformedOutput**: Errors when output data can't be parsed or validated\n * - **UnknownError**: Catch-all for unexpected runtime errors\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import { Effect, Match } from \"effect\"\n *\n * const handleAiError = Match.type<AiError.AiError>().pipe(\n *   Match.tag(\"HttpRequestError\", (err) =>\n *     Effect.logError(`Request failed: ${err.message}`)\n *   ),\n *   Match.tag(\"HttpResponseError\", (err) =>\n *     Effect.logError(`Response error (${err.response.status}): ${err.message}`)\n *   ),\n *   Match.tag(\"MalformedInput\", (err) =>\n *     Effect.logError(`Invalid input: ${err.message}`)\n *   ),\n *   Match.tag(\"MalformedOutput\", (err) =>\n *     Effect.logError(`Invalid output: ${err.message}`)\n *   ),\n *   Match.orElse((err) =>\n *     Effect.logError(`Unknown error: ${err.message}`)\n *   )\n * )\n * ```\n *\n * @example\n * ```ts\n * import { AiError } from \"@effect/ai\"\n * import { Effect, Option } from \"effect\"\n *\n * const aiOperation = Effect.gen(function* () {\n *   // Some AI operation that might fail\n *   return yield* new AiError.HttpRequestError({\n *     module: \"OpenAI\",\n *     method: \"completion\",\n *     reason: \"Transport\",\n *     request: {\n *       method: \"POST\",\n *       url: \"https://api.openai.com/v1/completions\",\n *       urlParams: [],\n *       hash: Option.none(),\n *       headers: { \"Content-Type\": \"application/json\" }\n *     }\n *   })\n * })\n *\n * const program = aiOperation.pipe(\n *   Effect.catchTag(\"HttpRequestError\", (error) => {\n *     console.log(\"Request failed:\", error.message)\n *     return Effect.succeed(\"fallback response\")\n *   })\n * )\n * ```\n *\n * @since 1.0.0\n */\nexport * as AiError from \"./AiError.js\"\n\n/**\n * The `Chat` module provides a stateful conversation interface for AI language\n * models.\n *\n * This module enables persistent chat sessions that maintain conversation\n * history, support tool calling, and offer both streaming and non-streaming\n * text generation. It integrates seamlessly with the Effect AI ecosystem,\n * providing type-safe conversational AI capabilities.\n *\n * @example\n * ```ts\n * import { Chat, LanguageModel } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * // Create a new chat session\n * const program = Effect.gen(function* () {\n *   const chat = yield* Chat.empty\n *\n *   // Send a message and get response\n *   const response = yield* chat.generateText({\n *     prompt: \"Hello! What can you help me with?\"\n *   })\n *\n *   console.log(response.content)\n *\n *   return response\n * })\n * ```\n *\n * @example\n * ```ts\n * import { Chat, LanguageModel } from \"@effect/ai\"\n * import { Effect, Stream } from \"effect\"\n *\n * // Streaming chat with tool support\n * const streamingChat = Effect.gen(function* () {\n *   const chat = yield* Chat.empty\n *\n *   yield* chat.streamText({\n *     prompt: \"Generate a creative story\"\n *   }).pipe(Stream.runForEach((part) =>\n *     Effect.sync(() => console.log(part))\n *   ))\n * })\n * ```\n *\n * @since 1.0.0\n */\nexport * as Chat from \"./Chat.js\"\n\n/**\n * The `EmbeddingModel` module provides vector embeddings for text using AI\n * models.\n *\n * This module enables efficient conversion of text into high-dimensional vector\n * representations that capture semantic meaning. It supports batching, caching,\n * and request optimization for production use cases like semantic search,\n * document similarity, and clustering.\n *\n * @example\n * ```ts\n * import { EmbeddingModel } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Basic embedding usage\n * const program = Effect.gen(function* () {\n *   const embedding = yield* EmbeddingModel.EmbeddingModel\n *\n *   const vector = yield* embedding.embed(\"Hello world!\")\n *   console.log(vector) // [0.123, -0.456, 0.789, ...]\n *\n *   return vector\n * })\n * ```\n *\n * @example\n * ```ts\n * import { EmbeddingModel } from \"@effect/ai\"\n * import { Effect, Duration } from \"effect\"\n *\n * declare const generateVectorFor: (text: string) => Array<number>\n *\n * // Create embedding service with batching and caching\n * const embeddingService = EmbeddingModel.make({\n *   embedMany: (texts) => Effect.succeed(\n *     texts.map((text, index) => ({\n *       index,\n *       embeddings: generateVectorFor(text)\n *     }))\n *   ),\n *   maxBatchSize: 50,\n *   cache: {\n *     capacity: 1000,\n *     timeToLive: Duration.minutes(30)\n *   }\n * })\n * ```\n *\n * @since 1.0.0\n */\nexport * as EmbeddingModel from \"./EmbeddingModel.js\"\n\n/**\n * The `IdGenerator` module provides a pluggable system for generating unique identifiers\n * for tool calls and other items in the Effect AI SDKs.\n *\n * This module offers a flexible and configurable approach to ID generation, supporting\n * custom alphabets, prefixes, separators, and sizes.\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * // Using the default ID generator\n * const program = Effect.gen(function* () {\n *   const idGen = yield* IdGenerator.IdGenerator\n *   const toolCallId = yield* idGen.generateId()\n *   console.log(toolCallId) // \"id_A7xK9mP2qR5tY8uV\"\n *   return toolCallId\n * }).pipe(\n *   Effect.provide(Layer.succeed(\n *     IdGenerator.IdGenerator,\n *     IdGenerator.defaultIdGenerator\n *   ))\n * )\n * ```\n *\n * @example\n * ```ts\n * import { IdGenerator } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * // Creating a custom ID generator for AI tool calls\n * const customLayer = IdGenerator.layer({\n *   alphabet: \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\",\n *   prefix: \"tool_call\",\n *   separator: \"-\",\n *   size: 12\n * })\n *\n * const program = Effect.gen(function* () {\n *   const idGen = yield* IdGenerator.IdGenerator\n *   const id = yield* idGen.generateId()\n *   console.log(id) // \"tool_call-A7XK9MP2QR5T\"\n *   return id\n * }).pipe(\n *   Effect.provide(customLayer)\n * )\n * ```\n *\n * @since 1.0.0\n */\nexport * as IdGenerator from \"./IdGenerator.js\"\n\n/**\n * The `LanguageModel` module provides AI text generation capabilities with tool\n * calling support.\n *\n * This module offers a comprehensive interface for interacting with large\n * language models, supporting both streaming and non-streaming text generation,\n * structured output generation, and tool calling functionality. It provides a\n * unified API that can be implemented by different AI providers while\n * maintaining type safety and effect management.\n *\n * @example\n * ```ts\n * import { LanguageModel } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Basic text generation\n * const program = Effect.gen(function* () {\n *   const response = yield* LanguageModel.generateText({\n *     prompt: \"Explain quantum computing\"\n *   })\n *\n *   console.log(response.text)\n *\n *   return response\n * })\n * ```\n *\n * @example\n * ```ts\n * import { LanguageModel } from \"@effect/ai\"\n * import { Effect, Schema } from \"effect\"\n *\n * // Structured output generation\n * const ContactSchema = Schema.Struct({\n *   name: Schema.String,\n *   email: Schema.String\n * })\n *\n * const extractContact = Effect.gen(function* () {\n *   const response = yield* LanguageModel.generateObject({\n *     prompt: \"Extract contact: John Doe, john@example.com\",\n *     schema: ContactSchema\n *   })\n *\n *   return response.value\n * })\n * ```\n *\n * @since 1.0.0\n */\nexport * as LanguageModel from \"./LanguageModel.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as McpSchema from \"./McpSchema.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as McpServer from \"./McpServer.js\"\n\n/**\n * The `Model` module provides a unified interface for AI service providers.\n *\n * This module enables creation of provider-specific AI models that can be used\n * interchangeably within the Effect AI ecosystem. It combines Layer\n * functionality with provider identification, allowing for seamless switching\n * between different AI service providers while maintaining type safety.\n *\n * @example\n * ```ts\n * import { Model, LanguageModel } from \"@effect/ai\"\n * import { Effect, Layer } from \"effect\"\n *\n * declare const myAnthropicLayer: Layer.Layer<LanguageModel.LanguageModel>\n *\n * const anthropicModel = Model.make(\"anthropic\", myAnthropicLayer)\n *\n * const program = Effect.gen(function* () {\n *   const response = yield* LanguageModel.generateText({\n *     prompt: \"Hello, world!\"\n *   })\n *   return response.text\n * }).pipe(\n *   Effect.provide(anthropicModel)\n * )\n * ```\n *\n * @since 1.0.0\n */\nexport * as Model from \"./Model.js\"\n\n/**\n * The `Prompt` module provides several data structures to simplify creating and\n * combining prompts.\n *\n * This module defines the complete structure of a conversation with a large\n * language model, including messages, content parts, and provider-specific\n * options. It supports rich content types like text, files, tool calls, and\n * reasoning.\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * // Create a structured conversation\n * const conversation = Prompt.make([\n *   {\n *     role: \"system\",\n *     content: \"You are a helpful assistant specialized in mathematics.\"\n *   },\n *   {\n *     role: \"user\",\n *     content: [{\n *       type: \"text\",\n *       text: \"What is the derivative of x²?\"\n *     }]\n *   },\n *   {\n *     role: \"assistant\",\n *     content: [{\n *       type: \"text\",\n *       text: \"The derivative of x² is 2x.\"\n *     }]\n *   }\n * ])\n * ```\n *\n * @example\n * ```ts\n * import { Prompt } from \"@effect/ai\"\n *\n * // Merge multiple prompts\n * const systemPrompt = Prompt.make([{\n *   role: \"system\",\n *   content: \"You are a coding assistant.\"\n * }])\n *\n * const userPrompt = Prompt.make(\"Help me write a function\")\n *\n * const combined = Prompt.merge(systemPrompt, userPrompt)\n * ```\n *\n * @since 1.0.0\n */\nexport * as Prompt from \"./Prompt.js\"\n\n/**\n * The `Response` module provides data structures to represent responses from\n * large language models.\n *\n * This module defines the complete structure of AI model responses, including\n * various content parts for text, reasoning, tool calls, files, and metadata,\n * supporting both streaming and non-streaming responses.\n *\n * @example\n * ```ts\n * import { Response } from \"@effect/ai\"\n *\n * // Create a simple text response part\n * const textResponse = Response.makePart(\"text\", {\n *   text: \"The weather is sunny today!\"\n * })\n *\n * // Create a tool call response part\n * const toolCallResponse = Response.makePart(\"tool-call\", {\n *   id: \"call_123\",\n *   name: \"get_weather\",\n *   params: { city: \"San Francisco\" },\n *   providerExecuted: false\n * })\n * ```\n *\n * @since 1.0.0\n */\nexport * as Response from \"./Response.js\"\n\n/**\n * The `Telemetry` module provides OpenTelemetry integration for operations\n * performed against a large language model provider by defining telemetry\n * attributes and utilities that follow the OpenTelemetry GenAI semantic\n * conventions.\n *\n * @example\n * ```ts\n * import { Telemetry } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Add telemetry attributes to a span\n * const addTelemetry = Effect.gen(function* () {\n *   const span = yield* Effect.currentSpan\n *\n *   Telemetry.addGenAIAnnotations(span, {\n *     system: \"openai\",\n *     operation: { name: \"chat\" },\n *     request: {\n *       model: \"gpt-4\",\n *       temperature: 0.7,\n *       maxTokens: 1000\n *     },\n *     usage: {\n *       inputTokens: 100,\n *       outputTokens: 50\n *     }\n *   })\n * })\n * ```\n *\n * @since 1.0.0\n */\nexport * as Telemetry from \"./Telemetry.js\"\n\n/**\n * The `Tokenizer` module provides tokenization and text truncation capabilities\n * for large language model text processing workflows.\n *\n * This module offers services for converting text into tokens and truncating\n * prompts based on token limits, essential for managing context length\n * constraints in large language models.\n *\n * @example\n * ```ts\n * import { Tokenizer, Prompt } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * const tokenizeText = Effect.gen(function* () {\n *   const tokenizer = yield* Tokenizer.Tokenizer\n *   const tokens = yield* tokenizer.tokenize(\"Hello, world!\")\n *   console.log(`Token count: ${tokens.length}`)\n *   return tokens\n * })\n * ```\n *\n * @example\n * ```ts\n * import { Tokenizer, Prompt } from \"@effect/ai\"\n * import { Effect } from \"effect\"\n *\n * // Truncate a prompt to fit within token limits\n * const truncatePrompt = Effect.gen(function* () {\n *   const tokenizer = yield* Tokenizer.Tokenizer\n *   const longPrompt = \"This is a very long prompt...\"\n *   const truncated = yield* tokenizer.truncate(longPrompt, 100)\n *   return truncated\n * })\n * ```\n *\n * @since 1.0.0\n */\nexport * as Tokenizer from \"./Tokenizer.js\"\n\n/**\n * The `Tool` module provides functionality for defining and managing tools\n * that language models can call to augment their capabilities.\n *\n * This module enables creation of both user-defined and provider-defined tools,\n * with full schema validation, type safety, and handler support. Tools allow\n * AI models to perform actions like searching databases, calling APIs, or\n * executing code within your application context.\n *\n * @example\n * ```ts\n * import { Tool } from \"@effect/ai\"\n * import { Schema } from \"effect\"\n *\n * // Define a simple calculator tool\n * const Calculator = Tool.make(\"Calculator\", {\n *   description: \"Performs basic arithmetic operations\",\n *   parameters: {\n *     operation: Schema.Literal(\"add\", \"subtract\", \"multiply\", \"divide\"),\n *     a: Schema.Number,\n *     b: Schema.Number\n *   },\n *   success: Schema.Number\n * })\n * ```\n *\n * @since 1.0.0\n */\nexport * as Tool from \"./Tool.js\"\n\n/**\n * The `Toolkit` module allows for creating and implementing a collection of\n * `Tool`s which can be used to enhance the capabilities of a large language\n * model beyond simple text generation.\n *\n * @example\n * ```ts\n * import { Toolkit, Tool } from \"@effect/ai\"\n * import { Effect, Schema } from \"effect\"\n *\n * // Create individual tools\n * const GetCurrentTime = Tool.make(\"GetCurrentTime\", {\n *   description: \"Get the current timestamp\",\n *   success: Schema.Number\n * })\n *\n * const GetWeather = Tool.make(\"GetWeather\", {\n *   description: \"Get weather for a location\",\n *   parameters: { location: Schema.String },\n *   success: Schema.Struct({\n *     temperature: Schema.Number,\n *     condition: Schema.String\n *   })\n * })\n *\n * // Create a toolkit with multiple tools\n * const MyToolkit = Toolkit.make(GetCurrentTime, GetWeather)\n *\n * const MyToolkitLayer = MyToolkit.toLayer({\n *   GetCurrentTime: () => Effect.succeed(Date.now()),\n *   GetWeather: ({ location }) => Effect.succeed({\n *     temperature: 72,\n *     condition: \"sunny\"\n *   })\n * })\n * ```\n *\n * @since 1.0.0\n */\nexport * as Toolkit from \"./Toolkit.js\"\n"
  },
  {
    "path": "packages/ai/ai/test/Chat.test.ts",
    "content": "import * as Chat from \"@effect/ai/Chat\"\nimport * as IdGenerator from \"@effect/ai/IdGenerator\"\nimport * as Prompt from \"@effect/ai/Prompt\"\nimport * as Persistence from \"@effect/experimental/Persistence\"\nimport { assert, describe, it } from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schema from \"effect/Schema\"\nimport * as TestClock from \"effect/TestClock\"\nimport * as TestUtils from \"./utilities.js\"\n\nconst withConstantIdGenerator = (id: string) =>\n  Effect.provideService(IdGenerator.IdGenerator, {\n    generateId: () => Effect.succeed(id)\n  })\n\nconst PersistenceLayer = Layer.provideMerge(\n  Chat.layerPersisted({ storeId: \"chat\" }),\n  Persistence.layerMemory\n)\n\ndescribe(\"Chat\", () => {\n  it.scoped(\"should persist chat history to the backing persistence store\", () =>\n    Effect.gen(function*() {\n      const storeId = \"chat\"\n      const chatId = \"1\"\n\n      const backing = yield* Persistence.BackingPersistence\n      const persistence = yield* Chat.Persistence\n\n      const store = yield* backing.make(storeId)\n      const chat = yield* persistence.getOrCreate(chatId)\n\n      yield* chat.generateText({ prompt: \"test user message\" }).pipe(\n        TestUtils.withLanguageModel({\n          generateText: [{\n            type: \"text\",\n            text: \"test assistant message\"\n          }]\n        })\n      )\n\n      const chatHistory = yield* chat.history\n      const storeHistory = yield* store.get(chatId).pipe(\n        Effect.flatten,\n        Effect.flatMap(Schema.decodeUnknown(Prompt.FromJson))\n      )\n      const options = { [Chat.Persistence.key]: { messageId: \"msg_abc123\" } }\n      const expectedHistory = Prompt.make([\n        { role: \"user\", content: [{ type: \"text\", text: \"test user message\" }], options },\n        { role: \"assistant\", content: [{ type: \"text\", text: \"test assistant message\" }], options }\n      ])\n\n      assert.deepStrictEqual(chatHistory, expectedHistory)\n      assert.deepStrictEqual(chatHistory, storeHistory)\n    }).pipe(withConstantIdGenerator(\"msg_abc123\"), Effect.provide(PersistenceLayer)))\n\n  it.scoped(\"should respect the specified time to live\", () =>\n    Effect.gen(function*() {\n      const storeId = \"chat\"\n      const chatId = \"1\"\n\n      const backing = yield* Persistence.BackingPersistence\n      const persistence = yield* Chat.Persistence\n\n      const store = yield* backing.make(storeId)\n      const chat = yield* persistence.getOrCreate(chatId, {\n        timeToLive: \"30 days\"\n      })\n\n      yield* chat.generateText({ prompt: \"test user message\" }).pipe(\n        TestUtils.withLanguageModel({\n          generateText: [{\n            type: \"text\",\n            text: \"test assistant message\"\n          }]\n        })\n      )\n\n      const chatHistory = yield* store.get(chatId).pipe(\n        Effect.flatten,\n        Effect.flatMap(Schema.decodeUnknown(Prompt.FromJson))\n      )\n      const options = { [Chat.Persistence.key]: { messageId: \"msg_abc123\" } }\n      const expectedHistory = Prompt.make([\n        { role: \"user\", content: [{ type: \"text\", text: \"test user message\" }], options },\n        { role: \"assistant\", content: [{ type: \"text\", text: \"test assistant message\" }], options }\n      ])\n\n      assert.deepStrictEqual(chatHistory, expectedHistory)\n\n      // Simulate chat expiration\n      yield* TestClock.adjust(\"30 days\")\n\n      const afterExpiration = yield* store.get(chatId)\n\n      assert.deepStrictEqual(afterExpiration, Option.none())\n    }).pipe(withConstantIdGenerator(\"msg_abc123\"), Effect.provide(PersistenceLayer)))\n\n  it.scoped(\"should prefer the message identifier of the most recent assistant message\", () =>\n    Effect.gen(function*() {\n      const storeId = \"chat\"\n      const chatId = \"2\"\n\n      const backing = yield* Persistence.BackingPersistence\n      const persistence = yield* Chat.Persistence\n\n      const store = yield* backing.make(storeId)\n      const chat = yield* persistence.getOrCreate(chatId)\n\n      const options = { [Chat.Persistence.key]: { messageId: \"msg_123abc\" } }\n      const history = Prompt.make([\n        { role: \"user\", content: \"first user message\", options },\n        { role: \"assistant\", content: \"first assistant message\", options }\n      ])\n      yield* Ref.set(chat.history, history)\n      yield* chat.save\n\n      yield* chat.generateText({ prompt: \"second user message\" }).pipe(\n        TestUtils.withLanguageModel({\n          generateText: [{\n            type: \"text\",\n            text: \"second assistant message\"\n          }]\n        })\n      )\n\n      const storeHistory = yield* store.get(chatId).pipe(\n        Effect.flatten,\n        Effect.flatMap(Schema.decodeUnknown(Prompt.FromJson))\n      )\n      const expectedHistory = Prompt.merge(history, [\n        { role: \"user\", content: \"second user message\", options },\n        { role: \"assistant\", content: \"second assistant message\", options }\n      ])\n\n      assert.deepStrictEqual(storeHistory, expectedHistory)\n    }).pipe(withConstantIdGenerator(\"msg_abc123\"), Effect.provide(PersistenceLayer)))\n\n  it.scoped(\"should raise an error when retrieving a chat that does not exist\", () =>\n    Effect.gen(function*() {\n      const persistence = yield* Chat.Persistence\n\n      const result = yield* Effect.flip(persistence.get(\"chat-321\"))\n\n      assert.instanceOf(result, Chat.ChatNotFoundError)\n      assert.strictEqual(result.chatId, \"chat-321\")\n    }).pipe(Effect.provide(PersistenceLayer)))\n})\n"
  },
  {
    "path": "packages/ai/ai/test/LanguageModel.test.ts",
    "content": "import * as LanguageModel from \"@effect/ai/LanguageModel\"\nimport * as Response from \"@effect/ai/Response\"\nimport * as Tool from \"@effect/ai/Tool\"\nimport * as Toolkit from \"@effect/ai/Toolkit\"\nimport { assert, describe, it } from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\nimport * as TestUtils from \"./utilities.js\"\n\nconst MyTool = Tool.make(\"MyTool\", {\n  parameters: { testParam: Schema.String },\n  success: Schema.Struct({ testSuccess: Schema.String })\n})\n\nconst MyToolkit = Toolkit.make(MyTool)\n\nconst MyToolkitLayer = MyToolkit.toLayer({\n  MyTool: () =>\n    Effect.succeed({ testSuccess: \"test-success\" }).pipe(\n      Effect.delay(\"10 seconds\")\n    )\n})\n\ndescribe(\"LanguageModel\", () => {\n  describe(\"streamText\", () => {\n    it.effect(\"should emit tool calls before executing tool handlers\", () =>\n      Effect.gen(function*() {\n        const parts: Array<Response.StreamPart<Toolkit.Tools<typeof MyToolkit>>> = []\n        const latch = yield* Effect.makeLatch()\n\n        const toolCallId = \"tool-abc123\"\n        const toolName = \"MyTool\"\n        const toolParams = { testParam: \"test-param\" }\n        const toolResult = { testSuccess: \"test-success\" }\n\n        yield* LanguageModel.streamText({\n          prompt: [],\n          toolkit: MyToolkit\n        }).pipe(\n          Stream.runForEach((part) =>\n            Effect.andThen(latch.open, () => {\n              parts.push(part)\n            })\n          ),\n          TestUtils.withLanguageModel({\n            streamText: [\n              {\n                type: \"tool-call\",\n                id: toolCallId,\n                name: toolName,\n                params: toolParams\n              }\n            ]\n          }),\n          Effect.provide(MyToolkitLayer),\n          Effect.fork\n        )\n\n        yield* latch.await\n\n        const toolCallPart = Response.makePart(\"tool-call\", {\n          id: toolCallId,\n          name: toolName,\n          params: toolParams,\n          providerExecuted: false\n        })\n\n        const toolResultPart = Response.toolResultPart({\n          id: toolCallId,\n          name: toolName,\n          result: toolResult,\n          encodedResult: toolResult,\n          isFailure: false,\n          providerExecuted: false\n        })\n\n        assert.deepStrictEqual(parts, [toolCallPart])\n\n        yield* TestClock.adjust(\"10 seconds\")\n\n        assert.deepStrictEqual(parts, [toolCallPart, toolResultPart])\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/ai/ai/test/Prompt.test.ts",
    "content": "import * as Prompt from \"@effect/ai/Prompt\"\nimport * as Response from \"@effect/ai/Response\"\nimport { assert, describe, it } from \"@effect/vitest\"\n\ndescribe(\"Prompt\", () => {\n  describe(\"fromResponseParts\", () => {\n    it(\"should handle interspersed text and response deltas\", () => {\n      const parts = [\n        Response.makePart(\"text-start\", { id: \"1\" }),\n        Response.makePart(\"text-delta\", { id: \"1\", delta: \"Hello\" }),\n        Response.makePart(\"text-delta\", { id: \"1\", delta: \", \" }),\n        Response.makePart(\"text-delta\", { id: \"1\", delta: \"World!\" }),\n        Response.makePart(\"text-end\", { id: \"1\" }),\n        Response.makePart(\"reasoning-start\", { id: \"2\" }),\n        Response.makePart(\"reasoning-delta\", { id: \"2\", delta: \"I \" }),\n        Response.makePart(\"reasoning-delta\", { id: \"2\", delta: \"am \" }),\n        Response.makePart(\"reasoning-delta\", { id: \"2\", delta: \"thinking\" }),\n        Response.makePart(\"reasoning-end\", { id: \"2\" })\n      ]\n      const prompt = Prompt.fromResponseParts(parts)\n      const expected = Prompt.make([\n        {\n          role: \"assistant\",\n          content: [\n            { type: \"text\", text: \"Hello, World!\" },\n            { type: \"reasoning\", text: \"I am thinking\" }\n          ]\n        }\n      ])\n      assert.deepStrictEqual(prompt, expected)\n    })\n  })\n\n  describe(\"merge\", () => {\n    it(\"should sequentially combine the content of two Prompts\", () => {\n      const leftMessages = [\n        Prompt.makeMessage(\"user\", {\n          content: [Prompt.makePart(\"text\", { text: \"a\" })]\n        }),\n        Prompt.makeMessage(\"assistant\", {\n          content: [Prompt.makePart(\"text\", { text: \"b\" })]\n        })\n      ]\n      const rightMessages = [\n        Prompt.makeMessage(\"user\", {\n          content: [Prompt.makePart(\"text\", { text: \"c\" })]\n        }),\n        Prompt.makeMessage(\"assistant\", {\n          content: [Prompt.makePart(\"text\", { text: \"d\" })]\n        })\n      ]\n      const left = Prompt.fromMessages(leftMessages)\n      const right = Prompt.fromMessages(rightMessages)\n      const merged = Prompt.merge(left, right)\n      assert.deepStrictEqual(\n        merged,\n        Prompt.fromMessages([\n          ...leftMessages,\n          ...rightMessages\n        ])\n      )\n    })\n\n    it(\"should return an empty prompt if there are no messages\", () => {\n      const merged = Prompt.merge(Prompt.empty, [])\n      assert.deepStrictEqual(merged, Prompt.empty)\n    })\n\n    it(\"should handle an empty prompt\", () => {\n      const prompt = Prompt.empty\n      const merged = Prompt.merge(prompt, [\n        { role: \"user\", content: \"a\" },\n        { role: \"assistant\", content: \"b\" }\n      ])\n      assert.deepStrictEqual(\n        merged,\n        Prompt.make([\n          Prompt.makeMessage(\"user\", {\n            content: [Prompt.makePart(\"text\", { text: \"a\" })]\n          }),\n          Prompt.makeMessage(\"assistant\", {\n            content: [Prompt.makePart(\"text\", { text: \"b\" })]\n          })\n        ])\n      )\n    })\n\n    it(\"should handle empty prompt input\", () => {\n      const messages = [\n        Prompt.makeMessage(\"user\", {\n          content: [Prompt.makePart(\"text\", { text: \"a\" })]\n        }),\n        Prompt.makeMessage(\"assistant\", {\n          content: [Prompt.makePart(\"text\", { text: \"b\" })]\n        })\n      ]\n      const prompt = Prompt.fromMessages(messages)\n      const merged = Prompt.merge(prompt, [])\n      assert.deepStrictEqual(merged, prompt)\n    })\n  })\n\n  describe(\"appendSystem\", () => {\n    it(\"should append text to existing system message\", () => {\n      const prompt = Prompt.make([\n        { role: \"system\", content: \"You are an expert in programming.\" },\n        { role: \"user\", content: \"Hello, world!\" }\n      ])\n\n      const result = Prompt.appendSystem(prompt, \" You are a helpful assistant.\")\n\n      assert.deepStrictEqual(\n        result.content[0],\n        Prompt.makeMessage(\"system\", {\n          content: \"You are an expert in programming. You are a helpful assistant.\"\n        })\n      )\n    })\n\n    it(\"should create a new system message if none exists\", () => {\n      const prompt = Prompt.make([\n        { role: \"user\", content: \"Hello, world!\" }\n      ])\n\n      const result = Prompt.appendSystem(prompt, \"You are a helpful assistant.\")\n\n      assert.deepStrictEqual(\n        result.content[0],\n        Prompt.makeMessage(\"system\", {\n          content: \"You are a helpful assistant.\"\n        })\n      )\n    })\n\n    it(\"should work with empty prompt\", () => {\n      const prompt = Prompt.empty\n\n      const result = Prompt.appendSystem(prompt, \"You are a helpful assistant.\")\n\n      assert.deepStrictEqual(\n        result.content[0],\n        Prompt.makeMessage(\"system\", { content: \"You are a helpful assistant.\" })\n      )\n    })\n  })\n\n  describe(\"prependSystem\", () => {\n    it(\"should prepend text to existing system message\", () => {\n      const prompt = Prompt.make([\n        {\n          role: \"system\",\n          content: \"You are an expert in programming.\"\n        },\n        {\n          role: \"user\",\n          content: \"Hello, world!\"\n        }\n      ])\n\n      const result = Prompt.prependSystem(prompt, \"You are a helpful assistant. \")\n\n      assert.deepStrictEqual(\n        result.content[0],\n        Prompt.makeMessage(\"system\", {\n          content: \"You are a helpful assistant. You are an expert in programming.\"\n        })\n      )\n    })\n\n    it(\"should create a new system message if none exists\", () => {\n      const prompt = Prompt.make([\n        {\n          role: \"user\",\n          content: \"Hello, world!\"\n        }\n      ])\n\n      const result = Prompt.prependSystem(prompt, \"You are a helpful assistant.\")\n\n      assert.deepStrictEqual(\n        result.content[0],\n        Prompt.makeMessage(\"system\", {\n          content: \"You are a helpful assistant.\"\n        })\n      )\n    })\n\n    it(\"should work with empty prompt\", () => {\n      const prompt = Prompt.empty\n\n      const result = Prompt.prependSystem(prompt, \"You are a helpful assistant.\")\n\n      assert.deepStrictEqual(\n        result.content[0],\n        Prompt.makeMessage(\"system\", { content: \"You are a helpful assistant.\" })\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/ai/ai/test/Tool.test.ts",
    "content": "import * as LanguageModel from \"@effect/ai/LanguageModel\"\nimport * as Response from \"@effect/ai/Response\"\nimport * as Tool from \"@effect/ai/Tool\"\nimport * as Toolkit from \"@effect/ai/Toolkit\"\nimport { assert, describe, it } from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\nimport * as TestUtils from \"./utilities.js\"\n\nconst FailureModeError = Tool.make(\"FailureModeError\", {\n  description: \"A test tool\",\n  parameters: {\n    testParam: Schema.String\n  },\n  success: Schema.Struct({\n    testSuccess: Schema.String\n  }),\n  failure: Schema.Struct({\n    testFailure: Schema.String\n  })\n})\n\nconst FailureModeReturn = Tool.make(\"FailureModeReturn\", {\n  description: \"A test tool\",\n  failureMode: \"return\",\n  parameters: {\n    testParam: Schema.String\n  },\n  success: Schema.Struct({\n    testSuccess: Schema.String\n  }),\n  failure: Schema.Struct({\n    testFailure: Schema.String\n  })\n})\n\nconst NoHandlerRequired = Tool.providerDefined({\n  id: \"provider.no-handler-required\",\n  toolkitName: \"NoHandlerRequired\",\n  providerName: \"no_handler_required\",\n  args: {\n    testArg: Schema.String\n  },\n  parameters: {\n    testParam: Schema.String\n  },\n  success: Schema.Struct({\n    testSuccess: Schema.String\n  }),\n  failure: Schema.Struct({\n    testFailure: Schema.String\n  })\n})\n\nconst HandlerRequired = Tool.providerDefined({\n  id: \"provider.handler-required\",\n  toolkitName: \"HandlerRequired\",\n  providerName: \"handler_required\",\n  requiresHandler: true,\n  args: {\n    testArg: Schema.String\n  },\n  parameters: {\n    testParam: Schema.String\n  },\n  success: Schema.Struct({\n    testSuccess: Schema.String\n  }),\n  failure: Schema.Struct({\n    testFailure: Schema.String\n  })\n})\n\ndescribe(\"Tool\", () => {\n  describe(\"User Defined\", () => {\n    it.effect(\"should return tool call handler success as a Right\", () =>\n      Effect.gen(function*() {\n        const toolkit = Toolkit.make(FailureModeReturn)\n\n        const toolResult = { testSuccess: \"failure-mode-return-tool\" }\n        const handlers = toolkit.toLayer({\n          FailureModeReturn: () => Effect.succeed(toolResult)\n        })\n\n        const toolCallId = \"tool-123\"\n        const toolName = \"FailureModeReturn\"\n\n        const response = yield* LanguageModel.generateText({\n          prompt: \"Test\",\n          toolkit\n        }).pipe(\n          TestUtils.withLanguageModel({\n            generateText: [{\n              type: \"tool-call\",\n              id: toolCallId,\n              name: toolName,\n              params: { testParam: \"test-param\" }\n            }]\n          }),\n          Effect.provide(handlers)\n        )\n\n        const expected = Response.makePart(\"tool-result\", {\n          id: toolCallId,\n          isFailure: false,\n          name: toolName,\n          result: toolResult,\n          encodedResult: toolResult,\n          providerExecuted: false\n        })\n\n        assert.deepInclude(response.toolResults, expected)\n      }))\n\n    it.effect(\"should return tool call handler failure as a Left\", () =>\n      Effect.gen(function*() {\n        const toolkit = Toolkit.make(FailureModeReturn)\n\n        const toolResult = { testFailure: \"failure-mode-return-tool\" }\n        const handlers = toolkit.toLayer({\n          FailureModeReturn: () => Effect.fail(toolResult)\n        })\n\n        const toolCallId = \"tool-123\"\n        const toolName = \"FailureModeReturn\"\n\n        const response = yield* LanguageModel.generateText({\n          prompt: \"Test\",\n          toolkit\n        }).pipe(\n          TestUtils.withLanguageModel({\n            generateText: [{\n              type: \"tool-call\",\n              id: toolCallId,\n              name: toolName,\n              params: { testParam: \"test-param\" }\n            }]\n          }),\n          Effect.provide(handlers)\n        )\n\n        const expected = Response.makePart(\"tool-result\", {\n          id: toolCallId,\n          name: toolName,\n          isFailure: true,\n          result: toolResult,\n          encodedResult: toolResult,\n          providerExecuted: false\n        })\n\n        assert.deepInclude(response.toolResults, expected)\n      }))\n\n    it.effect(\"should raise an error on tool call handler failure\", () =>\n      Effect.gen(function*() {\n        const toolkit = Toolkit.make(FailureModeError)\n\n        const toolResult = { testFailure: \"failure-mode-error-tool\" }\n        const handlers = toolkit.toLayer({\n          FailureModeError: () => Effect.fail(toolResult)\n        })\n\n        const toolCallId = \"tool-123\"\n        const toolName = \"FailureModeError\"\n\n        const response = yield* LanguageModel.generateText({\n          prompt: \"Test\",\n          toolkit\n        }).pipe(\n          TestUtils.withLanguageModel({\n            generateText: [{\n              type: \"tool-call\",\n              id: toolCallId,\n              name: toolName,\n              params: { testParam: \"test-param\" }\n            }]\n          }),\n          Effect.provide(handlers),\n          Effect.flip\n        )\n\n        assert.deepStrictEqual(response, toolResult)\n      }))\n\n    it.effect(\"should raise an error on invalid tool call parameters\", () =>\n      Effect.gen(function*() {\n        const toolkit = Toolkit.make(FailureModeReturn)\n\n        const toolResult = { testSuccess: \"failure-mode-return-tool\" }\n        const handlers = toolkit.toLayer({\n          FailureModeReturn: () => Effect.succeed(toolResult)\n        })\n\n        const toolCallId = \"tool-123\"\n        const toolName = \"FailureModeReturn\"\n\n        const response = yield* LanguageModel.generateText({\n          prompt: \"Test\",\n          toolkit\n        }).pipe(\n          TestUtils.withLanguageModel({\n            generateText: [{\n              type: \"tool-call\",\n              id: toolCallId,\n              name: toolName,\n              params: {}\n            }]\n          }),\n          Effect.provide(handlers),\n          Effect.flip\n        )\n\n        assert.strictEqual(response._tag, \"MalformedOutput\")\n        assert.strictEqual(\n          response.description,\n          \"Failed to decode tool call parameters for tool 'FailureModeReturn' from:\\n'{}'\"\n        )\n      }))\n  })\n\n  describe(\"Provider Defined\", () => {\n    it.effect(\"should return tool call successes from the model as a Right\", () =>\n      Effect.gen(function*() {\n        const tool = NoHandlerRequired({\n          testArg: \"test-arg\"\n        })\n        const toolkit = Toolkit.make(tool)\n\n        const toolCallId = \"tool-123\"\n        const toolResult = { testSuccess: \"provider-defined-tool\" }\n\n        const response = yield* LanguageModel.generateText({\n          prompt: \"Test\",\n          toolkit\n        }).pipe(\n          TestUtils.withLanguageModel({\n            generateText: [\n              {\n                type: \"tool-call\",\n                id: toolCallId,\n                name: tool.name,\n                providerName: tool.providerName,\n                providerExecuted: true,\n                params: { testParam: \"test-param\" }\n              },\n              {\n                type: \"tool-result\",\n                id: toolCallId,\n                name: tool.name,\n                isFailure: false,\n                result: toolResult,\n                providerName: tool.providerName,\n                providerExecuted: true\n              }\n            ]\n          })\n        )\n\n        const expected = Response.makePart(\"tool-result\", {\n          id: toolCallId,\n          name: tool.name,\n          isFailure: false,\n          result: toolResult,\n          encodedResult: toolResult,\n          providerName: tool.providerName,\n          providerExecuted: true\n        })\n\n        assert.deepInclude(response.toolResults, expected)\n      }))\n\n    it.effect(\"should return tool call errors from the model as a Left\", () =>\n      Effect.gen(function*() {\n        const tool = NoHandlerRequired({\n          testArg: \"test-arg\"\n        })\n        const toolkit = Toolkit.make(tool)\n\n        const toolCallId = \"tool-123\"\n        const toolResult = { testFailure: \"provider-defined-tool\" }\n\n        const response = yield* LanguageModel.generateText({\n          prompt: \"Test\",\n          toolkit\n        }).pipe(\n          TestUtils.withLanguageModel({\n            generateText: [\n              {\n                type: \"tool-call\",\n                id: toolCallId,\n                name: tool.name,\n                providerName: tool.providerName,\n                providerExecuted: true,\n                params: { testParam: \"test-param\" }\n              },\n              {\n                type: \"tool-result\",\n                id: toolCallId,\n                isFailure: true,\n                name: tool.name,\n                result: toolResult,\n                providerName: tool.providerName,\n                providerExecuted: true\n              }\n            ]\n          })\n        )\n\n        const expected = Response.makePart(\"tool-result\", {\n          id: toolCallId,\n          name: tool.name,\n          isFailure: true,\n          result: toolResult,\n          encodedResult: toolResult,\n          providerName: tool.providerName,\n          providerExecuted: true\n        })\n\n        assert.deepInclude(response.toolResults, expected)\n      }))\n\n    it.effect(\"should return tool call handler success as a Right\", () =>\n      Effect.gen(function*() {\n        const tool = HandlerRequired({\n          testArg: \"test-arg\"\n        })\n\n        const toolCallId = \"tool-123\"\n        const toolResult = { testSuccess: \"provider-defined-tool\" }\n\n        const toolkit = Toolkit.make(tool)\n        const handlers = toolkit.toLayer({\n          HandlerRequired: () => Effect.succeed(toolResult)\n        })\n\n        const response = yield* LanguageModel.generateText({\n          prompt: \"Test\",\n          toolkit\n        }).pipe(\n          TestUtils.withLanguageModel({\n            generateText: [\n              {\n                type: \"tool-call\",\n                id: toolCallId,\n                name: tool.name,\n                providerName: tool.providerName,\n                // Given this provider-defined tool requires a user-space\n                // handler, it is not considered `providerExecuted`\n                providerExecuted: false,\n                params: { testParam: \"test-param\" }\n              }\n            ]\n          }),\n          Effect.provide(handlers)\n        )\n\n        const expected = Response.makePart(\"tool-result\", {\n          id: toolCallId,\n          name: tool.name,\n          isFailure: false,\n          result: toolResult,\n          encodedResult: toolResult,\n          providerName: tool.providerName,\n          providerExecuted: false\n        })\n\n        assert.deepInclude(response.toolResults, expected)\n      }))\n\n    it.effect(\"should return tool call handler failure as a Left\", () =>\n      Effect.gen(function*() {\n        const tool = HandlerRequired({\n          failureMode: \"return\",\n          testArg: \"test-arg\"\n        })\n\n        const toolCallId = \"tool-123\"\n        const toolResult = { testFailure: \"provider-defined-tool\" }\n\n        const toolkit = Toolkit.make(tool)\n        const handlers = toolkit.toLayer({\n          HandlerRequired: () => Effect.fail(toolResult)\n        })\n\n        const response = yield* LanguageModel.generateText({\n          prompt: \"Test\",\n          toolkit\n        }).pipe(\n          TestUtils.withLanguageModel({\n            generateText: [\n              {\n                type: \"tool-call\",\n                id: toolCallId,\n                name: tool.name,\n                providerName: tool.providerName,\n                // Given this provider-defined tool requires a user-space\n                // handler, it is not considered `providerExecuted`\n                providerExecuted: false,\n                params: { testParam: \"test-param\" }\n              }\n            ]\n          }),\n          Effect.provide(handlers)\n        )\n\n        const expected = Response.makePart(\"tool-result\", {\n          id: toolCallId,\n          name: tool.name,\n          isFailure: true,\n          result: toolResult,\n          encodedResult: toolResult,\n          providerName: tool.providerName,\n          providerExecuted: false\n        })\n\n        assert.deepInclude(response.toolResults, expected)\n      }))\n\n    it.effect(\"should raise an error on tool call handler failure\", () =>\n      Effect.gen(function*() {\n        const tool = HandlerRequired({\n          testArg: \"test-arg\"\n        })\n\n        const toolCallId = \"tool-123\"\n        const toolResult = { testFailure: \"provider-defined-tool\" }\n\n        const toolkit = Toolkit.make(tool)\n        const handlers = toolkit.toLayer({\n          HandlerRequired: () => Effect.fail(toolResult)\n        })\n\n        const response = yield* LanguageModel.generateText({\n          prompt: \"Test\",\n          toolkit\n        }).pipe(\n          TestUtils.withLanguageModel({\n            generateText: [\n              {\n                type: \"tool-call\",\n                id: toolCallId,\n                name: tool.name,\n                providerName: tool.providerName,\n                // Given this provider-defined tool requires a user-space\n                // handler, it is not considered `providerExecuted`\n                providerExecuted: false,\n                params: { testParam: \"test-param\" }\n              }\n            ]\n          }),\n          Effect.provide(handlers),\n          Effect.flip\n        )\n\n        assert.deepStrictEqual(response, toolResult)\n      }))\n\n    it.effect(\"should raise an error on invalid tool call parameters\", () =>\n      Effect.gen(function*() {\n        const tool = HandlerRequired({\n          failureMode: \"return\",\n          testArg: \"test-arg\"\n        })\n\n        const toolCallId = \"tool-123\"\n        const toolResult = { testSuccess: \"provider-defined-tool\" }\n\n        const toolkit = Toolkit.make(tool)\n        const handlers = toolkit.toLayer({\n          HandlerRequired: () => Effect.succeed(toolResult)\n        })\n\n        const response = yield* LanguageModel.generateText({\n          prompt: \"Test\",\n          toolkit\n        }).pipe(\n          TestUtils.withLanguageModel({\n            generateText: [\n              {\n                type: \"tool-call\",\n                id: toolCallId,\n                name: tool.name,\n                providerName: tool.providerName,\n                // Given this provider-defined tool requires a user-space\n                // handler, it is not considered `providerExecuted`\n                providerExecuted: false,\n                params: {}\n              }\n            ]\n          }),\n          Effect.provide(handlers),\n          Effect.flip\n        )\n\n        assert.strictEqual(response._tag, \"MalformedOutput\")\n        assert.strictEqual(\n          response.description,\n          \"Failed to decode tool call parameters for tool 'HandlerRequired' from:\\n'{}'\"\n        )\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/ai/ai/test/utilities.ts",
    "content": "import * as LanguageModel from \"@effect/ai/LanguageModel\"\nimport type * as Response from \"@effect/ai/Response\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Stream from \"effect/Stream\"\n\nexport const withLanguageModel: {\n  (options: {\n    readonly generateText?:\n      | Array<Response.PartEncoded>\n      | ((options: LanguageModel.ProviderOptions) =>\n        | Array<Response.PartEncoded>\n        | Effect.Effect<Array<Response.PartEncoded>>)\n    readonly streamText?:\n      | Array<Response.StreamPartEncoded>\n      | ((options: LanguageModel.ProviderOptions) =>\n        | Array<Response.StreamPartEncoded>\n        | Stream.Stream<Response.StreamPartEncoded>)\n  }): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, LanguageModel.LanguageModel>>\n  <A, E, R>(effect: Effect.Effect<A, E, R>, options: {\n    readonly generateText?:\n      | Array<Response.PartEncoded>\n      | ((options: LanguageModel.ProviderOptions) =>\n        | Array<Response.PartEncoded>\n        | Effect.Effect<Array<Response.PartEncoded>>)\n    readonly streamText?:\n      | Array<Response.StreamPartEncoded>\n      | ((options: LanguageModel.ProviderOptions) =>\n        | Array<Response.StreamPartEncoded>\n        | Stream.Stream<Response.StreamPartEncoded>)\n  }): Effect.Effect<A, E, Exclude<R, LanguageModel.LanguageModel>>\n} = dual(2, <A, E, R>(effect: Effect.Effect<A, E, R>, options: {\n  readonly generateText?:\n    | Array<Response.PartEncoded>\n    | ((options: LanguageModel.ProviderOptions) =>\n      | Array<Response.PartEncoded>\n      | Effect.Effect<Array<Response.PartEncoded>>)\n  readonly streamText?:\n    | Array<Response.StreamPartEncoded>\n    | ((options: LanguageModel.ProviderOptions) =>\n      | Array<Response.StreamPartEncoded>\n      | Stream.Stream<Response.StreamPartEncoded>)\n}): Effect.Effect<A, E, Exclude<R, LanguageModel.LanguageModel>> =>\n  Effect.provideServiceEffect(\n    effect,\n    LanguageModel.LanguageModel,\n    LanguageModel.make({\n      generateText: (opts) => {\n        if (Predicate.isUndefined(options.generateText)) {\n          return Effect.succeed([])\n        }\n        if (Array.isArray(options.generateText)) {\n          return Effect.succeed(options.generateText)\n        }\n        const result = options.generateText(opts)\n        return Effect.isEffect(result) ? result : Effect.succeed(result)\n      },\n      streamText: (opts) => {\n        if (Predicate.isUndefined(options.streamText)) {\n          return Stream.empty\n        }\n        if (Array.isArray(options.streamText)) {\n          return Stream.fromIterable(options.streamText)\n        }\n        const result = options.streamText(opts)\n        return Array.isArray(result) ? Stream.fromIterable(result) : result\n      }\n    })\n  ))\n"
  },
  {
    "path": "packages/ai/ai/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"references\": [\n    { \"path\": \"../../effect/tsconfig.build.json\" },\n    { \"path\": \"../../experimental/tsconfig.build.json\" },\n    { \"path\": \"../../platform/tsconfig.build.json\" },\n    { \"path\": \"../../rpc/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/ai/tsconfig.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/ai/ai/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"references\": [\n    { \"path\": \"../../effect/tsconfig.src.json\" },\n    { \"path\": \"../../experimental/tsconfig.src.json\" },\n    { \"path\": \"../../platform/tsconfig.src.json\" },\n    { \"path\": \"../../rpc/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\",\n    \"outDir\": \"build/src\",\n    \"exactOptionalPropertyTypes\": false,\n    \"types\": [\"node\"]\n  }\n}\n"
  },
  {
    "path": "packages/ai/ai/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../../vitest/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"noEmit\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/ai/vitest.config.ts",
    "content": "import { mergeConfig, type ViteUserConfig } from \"vitest/config\"\nimport shared from \"../../../vitest.shared.js\"\n\nconst config: ViteUserConfig = {}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/CHANGELOG.md",
    "content": "# @effect/ai-amazon-bedrock\n\n## 0.15.0\n\n### Patch Changes\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n  - @effect/ai@0.35.0\n  - @effect/ai-anthropic@0.25.0\n  - @effect/experimental@0.60.0\n  - @effect/platform@0.96.0\n\n## 0.14.0\n\n### Patch Changes\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n  - @effect/ai@0.34.0\n  - @effect/ai-anthropic@0.24.0\n  - @effect/experimental@0.59.0\n  - @effect/platform@0.95.0\n\n## 0.13.0\n\n### Patch Changes\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n  - @effect/platform@0.94.0\n  - @effect/ai@0.33.0\n  - @effect/ai-anthropic@0.23.0\n  - @effect/experimental@0.58.0\n\n## 0.12.1\n\n### Patch Changes\n\n- [#5891](https://github.com/Effect-TS/effect/pull/5891) [`b1ffd22`](https://github.com/Effect-TS/effect/commit/b1ffd223ab4abc0be3f56bf4d16d99d0f5b4c4b8) Thanks @sbking! - fix cache point support for user and tool messages\n\n- Updated dependencies [[`65bff45`](https://github.com/Effect-TS/effect/commit/65bff451fc54d47b32995b3bc898ccc5f8b1beb6)]:\n  - @effect/platform@0.93.7\n\n## 0.12.0\n\n### Patch Changes\n\n- Updated dependencies [[`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - effect@3.19.0\n  - @effect/platform@0.93.0\n  - @effect/ai@0.32.0\n  - @effect/ai-anthropic@0.22.0\n  - @effect/experimental@0.57.0\n\n## 0.11.0\n\n### Minor Changes\n\n- [#5621](https://github.com/Effect-TS/effect/pull/5621) [`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825) Thanks @IMax153! - Remove `Either` / `EitherEncoded` from tool call results.\n\n  Specifically, the encoding of tool call results as an `Either` / `EitherEncoded` has been removed and is replaced by encoding the tool call success / failure directly into the `result` property.\n\n  To allow type-safe discrimination between a tool call result which was a success vs. one that was a failure, an `isFailure` property has also been added to the `\"tool-result\"` part. If `isFailure` is `true`, then the tool call handler result was an error.\n\n  ```ts\n  import * as AnthropicClient from \"@effect/ai-anthropic/AnthropicClient\"\n  import * as AnthropicLanguageModel from \"@effect/ai-anthropic/AnthropicLanguageModel\"\n  import * as LanguageModel from \"@effect/ai/LanguageModel\"\n  import * as Tool from \"@effect/ai/Tool\"\n  import * as Toolkit from \"@effect/ai/Toolkit\"\n  import * as NodeHttpClient from \"@effect/platform-node/NodeHttpClient\"\n  import { Config, Effect, Layer, Schema, Stream } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"An example of a tool with success and failure types\",\n    failureMode: \"return\", // Return errors in the response\n    parameters: { bar: Schema.Number },\n    success: Schema.Number,\n    failure: Schema.Struct({ reason: Schema.Literal(\"reason-1\", \"reason-2\") })\n  })\n\n  const MyToolkit = Toolkit.make(MyTool)\n\n  const MyToolkitLayer = MyToolkit.toLayer({\n    MyTool: () => Effect.succeed(42)\n  })\n\n  const program = LanguageModel.streamText({\n    prompt: \"Tell me about the meaning of life\",\n    toolkit: MyToolkit\n  }).pipe(\n    Stream.runForEach((part) => {\n      if (part.type === \"tool-result\" && part.name === \"MyTool\") {\n        // The `isFailure` property can be used to discriminate whether the result\n        // of a tool call is a success or a failure\n        if (part.isFailure) {\n          part.result\n          //   ^? { readonly reason: \"reason-1\" | \"reason-2\"; }\n        } else {\n          part.result\n          //   ^? number\n        }\n      }\n      return Effect.void\n    }),\n    Effect.provide(Claude)\n  )\n\n  const Anthropic = AnthropicClient.layerConfig({\n    apiKey: Config.redacted(\"ANTHROPIC_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(Effect.provide([Anthropic, MyToolkitLayer]), Effect.runPromise)\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825)]:\n  - @effect/ai-anthropic@0.21.0\n  - @effect/ai@0.31.0\n\n## 0.10.0\n\n### Minor Changes\n\n- [#5614](https://github.com/Effect-TS/effect/pull/5614) [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652) Thanks @IMax153! - Previously, tool call handler errors were _always_ raised as an expected error in the Effect `E` channel at the point of execution of the tool call handler (i.e. when a `generate*` method is invoked on a `LanguageModel`).\n\n  With this PR, the end user now has control over whether tool call handler errors should be raised as an Effect error, or returned by the SDK to allow, for example, sending that error information to another application.\n\n  ### Tool Call Specification\n\n  The `Tool.make` and `Tool.providerDefined` constructors now take an extra optional parameter called `failureMode`, which can be set to either `\"error\"` or `\"return\"`.\n\n  ```ts\n  import { Tool } from \"@effect/ai\"\n  import { Schema } from \"effect\"\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"My special tool\",\n    failureMode: \"return\" // \"error\" (default) or \"return\"\n    parameters: {\n      myParam: Schema.String\n    },\n    success: Schema.Struct({\n      mySuccess: Schema.String\n    }),\n    failure: Schema.Struct({\n      myFailure: Schema.String\n    })\n  })\n\n  ```\n\n  The semantics of `failureMode` are as follows:\n  - If set to `\"error\"` (the default), errors that occur during tool call handler execution will be returned in the error channel of the calling effect\n  - If set to `\"return\"`, errors that occur during tool call handler execution will be captured and returned as part of the tool call result\n\n  ### Response - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a large language model provider response is now represented as an `Either`.\n  - If the `result` is a `Left`, the `result` will be the `failure` specified in the tool call specification\n  - If the `result` is a `Right`, the `result` will be the `success` specified in the tool call specification\n\n  This is only relevant if the end user sets `failureMode` to `\"return\"`. If set to `\"error\"` (the default), then the `result` property will always be a `Right` with the successful result of the tool call handler.\n\n  Similarly the `encodedResult` field of a `\"tool-result\"` part will be represented as an `EitherEncoded`, where:\n  - `{ _tag: \"Left\", left: <failure> }` represents a tool call handler failure\n  - `{ _tag: \"Right\", right: <success> }` represents a tool call handler success\n\n  ### Prompt - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a prompt will now only accept an `EitherEncoded` as specified above.\n\n### Patch Changes\n\n- Updated dependencies [[`1d2e92d`](https://github.com/Effect-TS/effect/commit/1d2e92de9a20f39765bd0b338ffc936ba2fd9463), [`6ae2f5d`](https://github.com/Effect-TS/effect/commit/6ae2f5da45a9ed9832605eca12b3e2bf2e2a1a67), [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652)]:\n  - @effect/ai-anthropic@0.20.0\n  - effect@3.18.4\n  - @effect/ai@0.30.0\n\n## 0.9.0\n\n### Patch Changes\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2), [`f8b93ac`](https://github.com/Effect-TS/effect/commit/f8b93ac6446efd3dd790778b0fc71d299a38f272)]:\n  - effect@3.18.0\n  - @effect/ai@0.29.0\n  - @effect/platform@0.92.0\n  - @effect/ai-anthropic@0.19.0\n  - @effect/experimental@0.56.0\n\n## 0.8.1\n\n### Patch Changes\n\n- [#5571](https://github.com/Effect-TS/effect/pull/5571) [`122aa53`](https://github.com/Effect-TS/effect/commit/122aa53058ff008cf605cc2f0f0675a946c3cae9) Thanks @IMax153! - Ensure that AI provider clients filter response status for stream requests\n\n- Updated dependencies [[`122aa53`](https://github.com/Effect-TS/effect/commit/122aa53058ff008cf605cc2f0f0675a946c3cae9)]:\n  - @effect/ai-anthropic@0.18.2\n\n## 0.8.0\n\n### Patch Changes\n\n- Updated dependencies [[`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a)]:\n  - @effect/platform@0.91.0\n  - @effect/ai@0.28.0\n  - @effect/ai-anthropic@0.18.0\n  - @effect/experimental@0.55.0\n\n## 0.7.1\n\n### Patch Changes\n\n- [#5521](https://github.com/Effect-TS/effect/pull/5521) [`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80) Thanks @IMax153! - Fix provider metadata and parse tool call parameters safely\n\n- Updated dependencies [[`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80)]:\n  - @effect/ai-anthropic@0.17.1\n  - @effect/ai@0.27.1\n\n## 0.7.0\n\n### Minor Changes\n\n- [#5469](https://github.com/Effect-TS/effect/pull/5469) [`42b914a`](https://github.com/Effect-TS/effect/commit/42b914a0e8750350ce17d434afaec7d655ddf4b7) Thanks @IMax153! - Refactor the Effect AI SDK and associated provider packages\n\n  This pull request contains a complete refactor of the base Effect AI SDK package\n  as well as the associated provider integration packages to improve flexibility\n  and enhance ergonomics. Major changes are outlined below.\n\n  ## Modules\n\n  All modules in the base Effect AI SDK have had the leading `Ai` prefix dropped\n  from their name (except for the `AiError` module).\n\n  For example, the `AiLanguageModel` module is now the `LanguageModel` module.\n\n  In addition, the `AiInput` module has been renamed to the `Prompt` module.\n\n  ## Prompts\n\n  The `Prompt` module has been completely redesigned with flexibility in mind.\n\n  The `Prompt` module now supports building a prompt using either the constructors\n  exposed from the `Prompt` module, or using raw prompt content parts / messages,\n  which should be familiar to those coming from other AI SDKs.\n\n  In addition, the `system` option has been removed from all `LanguageModel` methods\n  and must now be provided as part of the prompt.\n\n  **Prompt Constructors**\n\n  ```ts\n  import { LanguageModel, Prompt } from \"@effect/ai\"\n\n  const textPart = Prompt.makePart(\"text\", {\n    text: \"What is machine learning?\"\n  })\n\n  const userMessage = Prompt.makeMessage(\"user\", {\n    content: [textPart]\n  })\n\n  const systemMessage = Prompt.makeMessage(\"system\", {\n    content: \"You are an expert in machine learning\"\n  })\n\n  const program = LanguageModel.generateText({\n    prompt: Prompt.fromMessages([systemMessage, userMessage])\n  })\n  ```\n\n  **Raw Prompt Input**\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n\n  const program = LanguageModel.generateText({\n    prompt: [\n      { role: \"system\", content: \"You are an expert in machine learning\" },\n      {\n        role: \"user\",\n        content: [{ type: \"text\", text: \"What is machine learning?\" }]\n      }\n    ]\n  })\n  ```\n\n  **NOTE**: Providing a plain string as a prompt is still supported, and will be converted\n  internally into a user message with a single text content part.\n\n  ### Provider-Specific Options\n\n  To support specification of provider-specific options when interacting with large\n  language model providers, support has been added for adding provider-specific\n  options to the parts of a `Prompt`.\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-sonnet-4-20250514\")\n\n  const program = LanguageModel.generateText({\n    prompt: [\n      {\n        role: \"user\",\n        content: [{ type: \"text\", text: \"What is machine learning?\" }],\n        options: {\n          anthropic: { cacheControl: { type: \"ephemeral\", ttl: \"1h\" } }\n        }\n      }\n    ]\n  }).pipe(Effect.provide(Claude))\n  ```\n\n  ## Responses\n\n  The `Response` module has also been completely redesigned to support a wider\n  variety of response parts, particularly when streaming.\n\n  ### Streaming Responses\n\n  When streaming text via the `LanguageModel.streamText` method, you will now\n  receive a stream of content parts instead of a stream of responses, which should\n  make it much simpler to filter down the stream to the parts you are interested in.\n\n  In addition, additional content parts will be present in the stream to allow you to track,\n  for example, when a text content part starts / ends.\n\n  ### Tool Calls / Tool Call Results\n\n  The decoded parts of a `Response` (as returned by the methods of `LanguageModel`)\n  are now fully type-safe on tool calls / tool call results. Filtering the content parts of a\n  response to tool calls will narrow the type of the tool call `params` based on the tool\n  `name`. Similarly, filtering the response to tool call results will narrow the type of the\n  tool call `result` based on the tool `name`.\n\n  ```ts\n  import { LanguageModel, Tool, Toolkit } from \"@effect/ai\"\n  import { Effect, Schema } from \"effect\"\n\n  const DadJokeTool = Tool.make(\"DadJokeTool\", {\n    parameters: { topic: Schema.String },\n    success: Schema.Struct({ joke: Schema.String })\n  })\n\n  const FooTool = Tool.make(\"FooTool\", {\n    parameters: { foo: Schema.Number },\n    success: Schema.Struct({ bar: Schema.Boolean })\n  })\n\n  const MyToolkit = Toolkit.make(DadJokeTool, FooTool)\n\n  const program = Effect.gen(function* () {\n    const response = yield* LanguageModel.generateText({\n      prompt: \"Tell me a dad joke\",\n      toolkit: MyToolkit\n    })\n\n    for (const toolCall of response.toolCalls) {\n      if (toolCall.name === \"DadJokeTool\") {\n        //         ^? \"DadJokeTool\" | \"FooTool\"\n        toolCall.params\n        //       ^? { readonly topic: string }\n      }\n    }\n\n    for (const toolResult of response.toolResults) {\n      if (toolResult.name === \"DadJokeTool\") {\n        //           ^? \"DadJokeTool\" | \"FooTool\"\n        toolResult.result\n        //         ^? { readonly joke: string }\n      }\n    }\n  })\n  ```\n\n  ### Provider Metadata\n\n  As with provider-specific options, provider-specific metadata is now returned as\n  part of the response from the large language model provider.\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n  import { Effect } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const program = Effect.gen(function* () {\n    const response = yield* LanguageModel.generateText({\n      prompt: \"What is the meaning of life?\"\n    })\n\n    for (const part of response.content) {\n      // When metadata **is not** defined for a content part, accessing the\n      // provider's key on the part's metadata will return an untyped record\n      if (part.type === \"text\") {\n        const metadata = part.metadata.anthropic\n        //    ^? { readonly [x: string]: unknown } | undefined\n      }\n      // When metadata **is** defined for a content part, accessing the\n      // provider's key on the part's metadata will return typed metadata\n      if (part.type === \"reasoning\") {\n        const metadata = part.metadata.anthropic\n        //    ^? AnthropicReasoningInfo | undefined\n      }\n    }\n  }).pipe(Effect.provide(Claude))\n  ```\n\n  ## Tool Calls\n\n  The `Tool` module has been enhanced to support provider-defined tools (e.g.\n  web search, computer use, etc.). Large language model providers which support\n  calling their own tools now have a separate module present in their provider\n  integration packages which contain definitions for their tools.\n\n  These provider-defined tools can be included alongside user-defined tools in\n  existing `Toolkit`s. Provider-defined tools that require a user-space handler\n  will be raise a type error in the associated `Toolkit` layer if no such handler\n  is defined.\n\n  ```ts\n  import { LanguageModel, Tool, Toolkit } from \"@effect/ai\"\n  import { AnthropicTool } from \"@effect/ai-anthropic\"\n  import { Schema } from \"effect\"\n\n  const DadJokeTool = Tool.make(\"DadJokeTool\", {\n    parameters: { topic: Schema.String },\n    success: Schema.Struct({ joke: Schema.String })\n  })\n\n  const MyToolkit = Toolkit.make(\n    DadJokeTool,\n    AnthropicTool.WebSearch_20250305({ max_uses: 1 })\n  )\n\n  const program = LanguageModel.generateText({\n    prompt: \"Search the web for a dad joke\",\n    toolkit: MyToolkit\n  })\n  ```\n\n  ## AiError\n\n  The `AiError` type has been refactored into a union of different error types\n  which can be raised by the Effect AI SDK. The goal of defining separate error\n  types is to allow providing the end-user with more granular information about\n  the error that occurred.\n\n  For now, the following errors have been defined. More error types may be added\n  over time based upon necessity / use case.\n\n  ```ts\n  type AiError =\n    | HttpRequestError,\n    | HttpResponseError,\n    | MalformedInput,\n    | MalformedOutput,\n    | UnknownError\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`42b914a`](https://github.com/Effect-TS/effect/commit/42b914a0e8750350ce17d434afaec7d655ddf4b7)]:\n  - @effect/ai-anthropic@0.17.0\n  - @effect/ai@0.27.0\n\n## 0.6.2\n\n### Patch Changes\n\n- [#5438](https://github.com/Effect-TS/effect/pull/5438) [`0065a12`](https://github.com/Effect-TS/effect/commit/0065a12bb82e05cb7766de3c6c9c30fabf883fd9) Thanks @IMax153! - Fix the InferenceConfiguration schema in the Amazon Bedrock AI provider package\n\n- Updated dependencies [[`3b26094`](https://github.com/Effect-TS/effect/commit/3b2609409ac1e8c6939d699584f00b1b99c47e2e), [`a33e491`](https://github.com/Effect-TS/effect/commit/a33e49153d944abd183fed93267fa7e52abae68b)]:\n  - effect@3.17.10\n\n## 0.6.1\n\n### Patch Changes\n\n- [#5424](https://github.com/Effect-TS/effect/pull/5424) [`3a8ba9b`](https://github.com/Effect-TS/effect/commit/3a8ba9b5e894a28e1724a5d5f3a965348caec2f1) Thanks @IMax153! - Fix system content block structure for Amazon Bedrock `AiLanguageModel`\n\n- Updated dependencies [[`0271f14`](https://github.com/Effect-TS/effect/commit/0271f1450c0c861f589e26ff534a73dea7ea97b7)]:\n  - effect@3.17.9\n\n## 0.6.0\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/ai@0.26.0\n  - @effect/experimental@0.54.6\n\n## 0.5.0\n\n### Patch Changes\n\n- Updated dependencies [[`5a0f4f1`](https://github.com/Effect-TS/effect/commit/5a0f4f176687a39d9fa46bb894bb7ac3175b0e87)]:\n  - effect@3.17.1\n  - @effect/ai@0.25.0\n  - @effect/experimental@0.54.0\n\n## 0.4.0\n\n### Patch Changes\n\n- Updated dependencies [[`7813640`](https://github.com/Effect-TS/effect/commit/7813640279d9e3a3e7fc0a29bfb5c6d5fb3c270f)]:\n  - @effect/platform@0.90.0\n  - @effect/ai@0.24.0\n  - @effect/experimental@0.54.0\n\n## 0.3.0\n\n### Patch Changes\n\n- Updated dependencies [[`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9), [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104), [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63), [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c), [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989), [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636), [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2), [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d)]:\n  - effect@3.17.0\n  - @effect/ai@0.23.0\n  - @effect/experimental@0.53.0\n  - @effect/platform@0.89.0\n\n## 0.2.1\n\n### Patch Changes\n\n- Updated dependencies [[`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec), [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38), [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48)]:\n  - effect@3.16.14\n  - @effect/platform@0.88.1\n  - @effect/experimental@0.52.1\n  - @effect/ai@0.22.1\n\n## 0.2.0\n\n### Patch Changes\n\n- Updated dependencies [[`27206d7`](https://github.com/Effect-TS/effect/commit/27206d7f0558d7fe28de57bf54f1d0cc83acc92e), [`dbabf5e`](https://github.com/Effect-TS/effect/commit/dbabf5e76fa63b050d2b6c466713c7dc59f07d3c)]:\n  - @effect/platform@0.88.0\n  - @effect/ai@0.22.0\n  - @effect/experimental@0.52.0\n\n## 0.1.14\n\n### Patch Changes\n\n- Updated dependencies [[`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7), [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db)]:\n  - effect@3.16.13\n  - @effect/ai@0.21.17\n  - @effect/experimental@0.51.14\n  - @effect/platform@0.87.13\n\n## 0.1.13\n\n### Patch Changes\n\n- [#5186](https://github.com/Effect-TS/effect/pull/5186) [`e5692ab`](https://github.com/Effect-TS/effect/commit/e5692ab2be157b885f449ffb5c5f022eca04a59e) Thanks @IMax153! - Do not use `Config.Wrap` for AI provider `layerConfig`\n\n- Updated dependencies [[`32ba77a`](https://github.com/Effect-TS/effect/commit/32ba77ae304d2161362a73e8b61965332626cf2d), [`d5e25b2`](https://github.com/Effect-TS/effect/commit/d5e25b237f05670ee42b386cb40b2cb448fc11d7)]:\n  - @effect/platform@0.87.12\n  - @effect/ai@0.21.16\n  - @effect/experimental@0.51.13\n\n## 0.1.12\n\n### Patch Changes\n\n- Updated dependencies [[`001392b`](https://github.com/Effect-TS/effect/commit/001392ba8bfcad101bb034348a7415012fb12f72), [`7bfb099`](https://github.com/Effect-TS/effect/commit/7bfb099cb5528511b8d63045c4fbb4dc9cb18528)]:\n  - @effect/platform@0.87.11\n  - @effect/ai@0.21.15\n  - @effect/experimental@0.51.12\n\n## 0.1.11\n\n### Patch Changes\n\n- Updated dependencies [[`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0), [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0)]:\n  - @effect/platform@0.87.10\n  - @effect/ai@0.21.14\n  - @effect/experimental@0.51.11\n\n## 0.1.10\n\n### Patch Changes\n\n- Updated dependencies [[`54514a2`](https://github.com/Effect-TS/effect/commit/54514a2f53166de27ad7e756dbf12194691fd4af)]:\n  - @effect/platform@0.87.9\n  - @effect/ai@0.21.13\n  - @effect/experimental@0.51.10\n\n## 0.1.9\n\n### Patch Changes\n\n- Updated dependencies [[`4ce4f82`](https://github.com/Effect-TS/effect/commit/4ce4f824f6fdef492be1d35c05a490ffce518c89)]:\n  - @effect/platform@0.87.8\n  - @effect/experimental@0.51.9\n  - @effect/ai@0.21.12\n\n## 0.1.8\n\n### Patch Changes\n\n- Updated dependencies [[`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778), [`25ca0cf`](https://github.com/Effect-TS/effect/commit/25ca0cf141139cd44ff53081b1c877f8f3ab5e41), [`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778)]:\n  - @effect/ai@0.21.11\n\n## 0.1.7\n\n### Patch Changes\n\n- Updated dependencies [[`a9b617f`](https://github.com/Effect-TS/effect/commit/a9b617f125171ed76cd79ab46d7a924daf3b0e70), [`7e26e86`](https://github.com/Effect-TS/effect/commit/7e26e86524abcc93713d6ad7eee486638c98f7c2)]:\n  - @effect/platform@0.87.7\n  - @effect/ai@0.21.10\n  - @effect/experimental@0.51.8\n\n## 0.1.6\n\n### Patch Changes\n\n- Updated dependencies [[`030ac21`](https://github.com/Effect-TS/effect/commit/030ac217eac167d345a095bff26d9c95827fa64c), [`905da99`](https://github.com/Effect-TS/effect/commit/905da996aad665057b4ca6dba1a4af44fb8835bd), [`aaae9b1`](https://github.com/Effect-TS/effect/commit/aaae9b10345ab5f867b08e1c6eb21685cfc2b078)]:\n  - @effect/ai@0.21.9\n  - effect@3.16.12\n  - @effect/experimental@0.51.7\n  - @effect/platform@0.87.6\n\n## 0.1.5\n\n### Patch Changes\n\n- Updated dependencies [[`96c1292`](https://github.com/Effect-TS/effect/commit/96c129262835410b311a51d0bf7f58b8f6fc9a12)]:\n  - @effect/experimental@0.51.6\n  - @effect/ai@0.21.8\n\n## 0.1.4\n\n### Patch Changes\n\n- Updated dependencies [[`2fd8676`](https://github.com/Effect-TS/effect/commit/2fd8676c803cd40000dfc3231f5daecaa0e0ebd2)]:\n  - @effect/platform@0.87.5\n  - @effect/ai@0.21.7\n  - @effect/experimental@0.51.5\n\n## 0.1.3\n\n### Patch Changes\n\n- Updated dependencies [[`e82a4fd`](https://github.com/Effect-TS/effect/commit/e82a4fd60f6528d08cef1a4aba0abe0d3ba741ad)]:\n  - @effect/platform@0.87.4\n  - @effect/ai@0.21.6\n  - @effect/experimental@0.51.4\n\n## 0.1.2\n\n### Patch Changes\n\n- Updated dependencies [[`1b6e396`](https://github.com/Effect-TS/effect/commit/1b6e396d699f3cbbc56b68f99055cf746529bb9e)]:\n  - @effect/platform@0.87.3\n  - @effect/ai@0.21.5\n  - @effect/experimental@0.51.3\n\n## 0.1.1\n\n### Patch Changes\n\n- Updated dependencies [[`4fea68c`](https://github.com/Effect-TS/effect/commit/4fea68ca7a25a3c39a1ab68b3885534513ab0c81), [`b927954`](https://github.com/Effect-TS/effect/commit/b9279543cf5688dd8a577af80456959c615217d0), [`99590a6`](https://github.com/Effect-TS/effect/commit/99590a6ca9128eb1ede265b6670b655311995614), [`6c3e24c`](https://github.com/Effect-TS/effect/commit/6c3e24c2308f7d4a29b8f4270ab81bca22ac6bb4)]:\n  - @effect/platform@0.87.2\n  - effect@3.16.11\n  - @effect/ai@0.21.4\n  - @effect/experimental@0.51.2\n\n## 0.1.0\n\n### Minor Changes\n\n- [#5020](https://github.com/Effect-TS/effect/pull/5020) [`530aa65`](https://github.com/Effect-TS/effect/commit/530aa6561b68ea591cef44e30e8629082e42fda2) Thanks @IMax153! - add Amazon Bedrock AI provider package\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Effectful Technologies Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/README.md",
    "content": "# `@effect/ai-amazon-bedrock`\n\n## Documentation\n\n- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/ai/amazon-bedrock).\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/docgen.json",
    "content": "{\n  \"$schema\": \"../../../node_modules/@effect/docgen/schema.json\",\n  \"exclude\": [\"src/Generated.ts\", \"src/internal/**/*.ts\"],\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/ai/amazon-bedrock/src/\",\n  \"examplesCompilerOptions\": {\n    \"noEmit\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"module\": \"ES2022\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n    \"paths\": {\n      \"effect\": [\"../../../../effect/src/index.js\"],\n      \"effect/*\": [\"../../../../effect/src/*.js\"],\n      \"@effect/experimental\": [\"../../../../experimental/src/index.js\"],\n      \"@effect/experimental/*\": [\"../../../../experimental/src/*.js\"],\n      \"@effect/platform\": [\"../../../../platform/src/index.js\"],\n      \"@effect/platform/*\": [\"../../../../platform/src/*.js\"],\n      \"@effect/ai\": [\"../../../ai/src/index.js\"],\n      \"@effect/ai/*\": [\"../../../ai/src/*.js\"],\n      \"@effect/ai-anthropic\": [\"../../../anthropic/src/index.js\"],\n      \"@effect/ai-anthropic/*\": [\"../../../anthropic/src/*.js\"],\n      \"@effect/ai-amazon-bedrock\": [\"../../../amazon-bedrock/src/index.js\"],\n      \"@effect/ai-amazon-bedrock/*\": [\"../../../amazon-bedrock/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/package.json",
    "content": "{\n  \"name\": \"@effect/ai-amazon-bedrock\",\n  \"type\": \"module\",\n  \"version\": \"0.15.0\",\n  \"license\": \"MIT\",\n  \"description\": \"Effect modules for working with Amazon Bedrock AI apis\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/ai/amazon-bedrock\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"keywords\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"peerDependencies\": {\n    \"@effect/ai\": \"workspace:^\",\n    \"@effect/ai-anthropic\": \"workspace:^\",\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"effect\": \"workspace:^\"\n  },\n  \"devDependencies\": {\n    \"@effect/ai\": \"workspace:^\",\n    \"@effect/ai-anthropic\": \"workspace:^\",\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/platform-node\": \"workspace:^\",\n    \"@tim-smart/openapi-gen\": \"^0.3.18\",\n    \"effect\": \"workspace:^\"\n  },\n  \"dependencies\": {\n    \"@smithy/eventstream-codec\": \"^4.0.4\",\n    \"@smithy/util-utf8\": \"^4.0.0\",\n    \"aws4fetch\": \"^1.0.20\",\n    \"gpt-tokenizer\": \"^2.9.0\"\n  }\n}\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/src/AmazonBedrockClient.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AiError from \"@effect/ai/AiError\"\nimport * as Headers from \"@effect/platform/Headers\"\nimport * as HttpBody from \"@effect/platform/HttpBody\"\nimport * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientError from \"@effect/platform/HttpClientError\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as HttpClientResponse from \"@effect/platform/HttpClientResponse\"\nimport { AwsV4Signer } from \"aws4fetch\"\nimport * as Arr from \"effect/Array\"\nimport * as Config from \"effect/Config\"\nimport type { ConfigError } from \"effect/ConfigError\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport * as Redacted from \"effect/Redacted\"\nimport type * as Schema from \"effect/Schema\"\nimport * as Stream from \"effect/Stream\"\nimport { AmazonBedrockConfig } from \"./AmazonBedrockConfig.js\"\nimport type { ConverseRequest } from \"./AmazonBedrockSchema.js\"\nimport { ConverseResponse, ConverseResponseStreamEvent } from \"./AmazonBedrockSchema.js\"\nimport * as EventStreamEncoding from \"./EventStreamEncoding.js\"\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class AmazonBedrockClient extends Context.Tag(\n  \"@effect/ai-amazon-bedrock/AmazonBedrockClient\"\n)<AmazonBedrockClient, Service>() {}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface Service {\n  readonly client: Client\n\n  readonly streamRequest: <A, I, R>(\n    request: HttpClientRequest.HttpClientRequest,\n    schema: Schema.Schema<A, I, R>\n  ) => Stream.Stream<A, AiError.AiError, R>\n\n  readonly converse: (options: {\n    readonly params?: { \"anthropic-beta\"?: string | undefined } | undefined\n    readonly payload: typeof ConverseRequest.Encoded\n  }) => Effect.Effect<ConverseResponse, AiError.AiError>\n\n  readonly converseStream: (options: {\n    readonly params?: { \"anthropic-beta\"?: string | undefined } | undefined\n    readonly payload: typeof ConverseRequest.Encoded\n  }) => Stream.Stream<ConverseResponseStreamEvent, AiError.AiError>\n}\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (options: {\n  readonly apiUrl?: string | undefined\n  readonly accessKeyId: string\n  readonly secretAccessKey: Redacted.Redacted<string>\n  readonly sessionToken?: Redacted.Redacted<string> | undefined\n  readonly region?: string | undefined\n  readonly transformClient?: (\n    client: HttpClient.HttpClient\n  ) => HttpClient.HttpClient\n}) =>\n  Effect.gen(function*() {\n    const region = options.region ?? \"us-east-1\"\n\n    const redactedHeaders = [\"X-Amz-Security-Token\"]\n\n    yield* Effect.locallyScopedWith(Headers.currentRedactedNames, Arr.appendAll(redactedHeaders))\n\n    const httpClient = (yield* HttpClient.HttpClient).pipe(\n      HttpClient.mapRequest((request) =>\n        request.pipe(\n          HttpClientRequest.prependUrl(options.apiUrl ?? `https://bedrock-runtime.${region}.amazonaws.com`),\n          HttpClientRequest.acceptJson\n        )\n      ),\n      HttpClient.mapRequestEffect(Effect.fnUntraced(function*(request) {\n        const originalHeaders = request.headers\n        const signer = new AwsV4Signer({\n          service: \"bedrock\",\n          url: request.url,\n          method: request.method,\n          headers: Object.entries(originalHeaders),\n          body: prepareBody(request.body),\n          region,\n          accessKeyId: options.accessKeyId,\n          secretAccessKey: Redacted.value(options.secretAccessKey),\n          ...(options.sessionToken ? { sessionToken: Redacted.value(options.sessionToken) } : {})\n        })\n        const { headers: signedHeaders } = yield* Effect.promise(() => signer.sign())\n        const headers = Headers.merge(originalHeaders, Headers.fromInput(signedHeaders))\n        return HttpClientRequest.setHeaders(request, headers)\n      })),\n      options.transformClient ? options.transformClient : identity\n    )\n\n    const httpClientOk = HttpClient.filterStatusOk(httpClient)\n\n    const client = makeClient(httpClient, {\n      transformClient: (client) =>\n        AmazonBedrockConfig.getOrUndefined.pipe(\n          Effect.map((config) => config?.transformClient ? config.transformClient(client) : client)\n        )\n    })\n\n    const converse: (options: {\n      readonly params?: { \"anthropic-beta\"?: string | undefined } | undefined\n      readonly payload: typeof ConverseRequest.Encoded\n    }) => Effect.Effect<ConverseResponse, AiError.AiError> = Effect.fnUntraced(\n      function*(request) {\n        return yield* client.converse(request).pipe(\n          Effect.catchTags({\n            RequestError: (error) =>\n              AiError.HttpRequestError.fromRequestError({\n                module: \"AmazonBedrockClient\",\n                method: \"converse\",\n                error\n              }),\n            ResponseError: (error) =>\n              AiError.HttpResponseError.fromResponseError({\n                module: \"AmazonBedrockClient\",\n                method: \"converse\",\n                error\n              }),\n            ParseError: (error) =>\n              AiError.MalformedOutput.fromParseError({\n                module: \"AmazonBedrockClient\",\n                method: \"converse\",\n                error\n              })\n          })\n        )\n      }\n    )\n\n    const streamRequest = <A, I, R>(\n      request: HttpClientRequest.HttpClientRequest,\n      schema: Schema.Schema<A, I, R>\n    ): Stream.Stream<A, AiError.AiError, R> =>\n      httpClientOk.execute(request).pipe(\n        Effect.map((r) => r.stream),\n        Stream.unwrapScoped,\n        Stream.pipeThroughChannel(EventStreamEncoding.makeChannel(schema)),\n        Stream.catchTags({\n          RequestError: (error) =>\n            AiError.HttpRequestError.fromRequestError({\n              module: \"AmazonBedrockClient\",\n              method: \"streamRequest\",\n              error\n            }),\n          ResponseError: (error) =>\n            AiError.HttpResponseError.fromResponseError({\n              module: \"AmazonBedrockClient\",\n              method: \"streamRequest\",\n              error\n            }),\n          ParseError: (error) =>\n            AiError.MalformedOutput.fromParseError({\n              module: \"AmazonBedrockClient\",\n              method: \"streamRequest\",\n              error\n            })\n        })\n      )\n\n    const converseStream = (options: {\n      readonly params?: { \"anthropic-beta\"?: string | undefined } | undefined\n      readonly payload: typeof ConverseRequest.Encoded\n    }): Stream.Stream<ConverseResponseStreamEvent, AiError.AiError> => {\n      const { modelId, ...body } = options.payload\n      const request = HttpClientRequest.post(`/model/${modelId}/converse-stream`, {\n        headers: Headers.fromInput({\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"]\n        }),\n        body: HttpBody.unsafeJson(body)\n      })\n      return streamRequest(request, ConverseResponseStreamEvent)\n    }\n\n    return AmazonBedrockClient.of({\n      client,\n      streamRequest,\n      converse,\n      converseStream\n    })\n  })\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer = (options: {\n  readonly apiUrl?: string | undefined\n  readonly accessKeyId: string\n  readonly secretAccessKey: Redacted.Redacted<string>\n  readonly sessionToken?: Redacted.Redacted<string> | undefined\n  readonly region?: string | undefined\n  readonly transformClient?: (\n    client: HttpClient.HttpClient\n  ) => HttpClient.HttpClient\n}): Layer.Layer<AmazonBedrockClient, never, HttpClient.HttpClient> => Layer.scoped(AmazonBedrockClient, make(options))\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerConfig = (\n  options: {\n    readonly apiUrl?: Config.Config<string> | undefined\n    readonly accessKeyId: Config.Config<string>\n    readonly secretAccessKey: Config.Config<Redacted.Redacted>\n    readonly sessionToken?: Config.Config<Redacted.Redacted> | undefined\n    readonly region?: Config.Config<string> | undefined\n    readonly transformClient?: (\n      client: HttpClient.HttpClient\n    ) => HttpClient.HttpClient\n  }\n): Layer.Layer<AmazonBedrockClient, ConfigError, HttpClient.HttpClient> => {\n  const { transformClient, ...configs } = options\n  return Config.all(configs).pipe(\n    Effect.flatMap((configs) => make({ ...configs, transformClient })),\n    Layer.scoped(AmazonBedrockClient)\n  )\n}\n\n// =============================================================================\n// Client\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Client {\n  readonly converse: (options: {\n    readonly params?: { \"anthropic-beta\"?: string | undefined }\n    readonly payload: typeof ConverseRequest.Encoded\n  }) => Effect.Effect<typeof ConverseResponse.Type, HttpClientError.HttpClientError | ParseError>\n}\n\nconst makeClient = (\n  httpClient: HttpClient.HttpClient,\n  options: {\n    readonly transformClient?: ((client: HttpClient.HttpClient) => Effect.Effect<HttpClient.HttpClient>) | undefined\n  }\n): Client => {\n  const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) =>\n    Effect.flatMap(\n      Effect.orElseSucceed(response.json, () => \"Unexpected status code\"),\n      (description) =>\n        Effect.fail(\n          new HttpClientError.ResponseError({\n            request: response.request,\n            response,\n            reason: \"StatusCode\",\n            description: typeof description === \"string\" ? description : JSON.stringify(description)\n          })\n        )\n    )\n  const withResponse: <A, E>(\n    f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E>\n  ) => (\n    request: HttpClientRequest.HttpClientRequest\n  ) => Effect.Effect<any, any> = options.transformClient\n    ? (f) => (request) =>\n      Effect.flatMap(\n        Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)),\n        f\n      )\n    : (f) => (request) => Effect.flatMap(httpClient.execute(request), f)\n  const decodeSuccess =\n    <A, I, R>(schema: Schema.Schema<A, I, R>) => (response: HttpClientResponse.HttpClientResponse) =>\n      HttpClientResponse.schemaBodyJson(schema)(response)\n  return {\n    converse: ({ params, payload: { modelId, ...payload } }) =>\n      HttpClientRequest.post(`/model/${modelId}/converse`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": params?.[\"anthropic-beta\"] ?? undefined\n        }),\n        HttpClientRequest.bodyUnsafeJson(payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ConverseResponse),\n          orElse: unexpectedStatus\n        }))\n      )\n  }\n}\n\nconst prepareBody = (body: HttpBody.HttpBody): string => {\n  switch (body._tag) {\n    case \"Raw\":\n    case \"Uint8Array\": {\n      if (typeof body.body === \"string\") {\n        return body.body\n      }\n      if (body.body instanceof Uint8Array) {\n        return new TextDecoder().decode(body.body)\n      }\n      if (body.body instanceof ArrayBuffer) {\n        return new TextDecoder().decode(body.body)\n      }\n      return JSON.stringify(body.body)\n    }\n  }\n  throw new Error(\"Unsupported HttpBody: \" + body._tag)\n}\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/src/AmazonBedrockConfig.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { HttpClient } from \"@effect/platform/HttpClient\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class AmazonBedrockConfig extends Context.Tag(\"@effect/ai-google/AmazonBedrockConfig\")<\n  AmazonBedrockConfig,\n  AmazonBedrockConfig.Service\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<typeof AmazonBedrockConfig.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(AmazonBedrockConfig.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace AmazonBedrockConfig {\n  /**\n   * @since 1.0.\n   * @category Models\n   */\n  export interface Service {\n    readonly transformClient?: (client: HttpClient) => HttpClient\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport const withClientTransform: {\n  (transform: (client: HttpClient) => HttpClient): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient): Effect.Effect<A, E, R>\n} = dual<\n  (transform: (client: HttpClient) => HttpClient) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient) => Effect.Effect<A, E, R>\n>(\n  2,\n  (self, transformClient) =>\n    Effect.flatMap(\n      AmazonBedrockConfig.getOrUndefined,\n      (config) => Effect.provideService(self, AmazonBedrockConfig, { ...config, transformClient })\n    )\n)\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/src/AmazonBedrockLanguageModel.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport { prepareTools as prepareAnthropicTools } from \"@effect/ai-anthropic/AnthropicLanguageModel\"\nimport * as AnthropicTool from \"@effect/ai-anthropic/AnthropicTool\"\nimport * as AiError from \"@effect/ai/AiError\"\nimport type * as IdGenerator from \"@effect/ai/IdGenerator\"\nimport * as LanguageModel from \"@effect/ai/LanguageModel\"\nimport * as AiModel from \"@effect/ai/Model\"\nimport type * as Prompt from \"@effect/ai/Prompt\"\nimport type * as Response from \"@effect/ai/Response\"\nimport { addGenAIAnnotations } from \"@effect/ai/Telemetry\"\nimport * as Tool from \"@effect/ai/Tool\"\nimport * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport { dual } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Stream from \"effect/Stream\"\nimport type { Span } from \"effect/Tracer\"\nimport type { Mutable, Simplify } from \"effect/Types\"\nimport { AmazonBedrockClient } from \"./AmazonBedrockClient.js\"\nimport type {\n  BedrockFoundationModelId,\n  CachePointBlock,\n  ContentBlock,\n  ConverseRequest,\n  ConverseResponse,\n  ConverseResponseStreamEvent,\n  ConverseTrace,\n  DocumentFormat,\n  Message,\n  SystemContentBlock,\n  Tool as AmazonBedrockTool,\n  ToolChoice,\n  ToolConfiguration\n} from \"./AmazonBedrockSchema.js\"\nimport { ImageFormat } from \"./AmazonBedrockSchema.js\"\nimport * as InternalUtilities from \"./internal/utilities.js\"\n\nconst BEDROCK_CACHE_POINT: {\n  readonly cachePoint: typeof CachePointBlock.Encoded\n} = { cachePoint: { type: \"default\" } }\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type Model = typeof BedrockFoundationModelId.Encoded\n\n// =============================================================================\n// Configuration\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class Config extends Context.Tag(\n  \"@effect/ai-amazon-bedrock/AmazonBedrockLanguageModel/Config\"\n)<Config, Config.Service>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<typeof Config.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(Config.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Config {\n  /**\n   * @since 1.0.0\n   * @category Configuration\n   */\n  export interface Service extends\n    Simplify<\n      Partial<\n        Omit<\n          typeof ConverseRequest.Encoded,\n          \"messages\" | \"system\" | \"toolConfig\"\n        >\n      >\n    >\n  {}\n}\n\n// =============================================================================\n// Amazon Bedrock Provider Options / Metadata\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Provider Options\n */\nexport type AmazonBedrockReasoningInfo = {\n  readonly type: \"thinking\"\n  /**\n   * Thinking content as an encrypted string, which is used to verify\n   * that thinking content was indeed generated by Amazon Bedrock's API.\n   */\n  readonly signature: string\n} | {\n  readonly type: \"redacted_thinking\"\n  /**\n   * Thinking content which was flagged by Amazon Bedrock's safety systems, and\n   * was therefore encrypted.\n   */\n  readonly redactedData: string\n}\n\ndeclare module \"@effect/ai/Prompt\" {\n  export interface SystemMessageOptions extends ProviderOptions {\n    readonly bedrock?: {\n      /**\n       * Defines a section of content to be cached for reuse in subsequent API\n       * calls.\n       */\n      readonly cachePoint?: typeof CachePointBlock.Encoded | undefined\n    } | undefined\n  }\n\n  export interface UserMessageOptions extends ProviderOptions {\n    readonly bedrock?: {\n      /**\n       * Defines a section of content to be cached for reuse in subsequent API\n       * calls.\n       */\n      readonly cachePoint?: typeof CachePointBlock.Encoded | undefined\n    } | undefined\n  }\n\n  export interface AssistantMessageOptions extends ProviderOptions {\n    readonly bedrock?: {\n      /**\n       * Defines a section of content to be cached for reuse in subsequent API\n       * calls.\n       */\n      readonly cachePoint?: typeof CachePointBlock.Encoded | undefined\n    } | undefined\n  }\n\n  export interface ToolMessageOptions extends ProviderOptions {\n    readonly bedrock?: {\n      /**\n       * Defines a section of content to be cached for reuse in subsequent API\n       * calls.\n       */\n      readonly cachePoint?: typeof CachePointBlock.Encoded | undefined\n    } | undefined\n  }\n\n  export interface ReasoningPartOptions extends ProviderOptions {\n    readonly bedrock?: AmazonBedrockReasoningInfo | undefined\n  }\n}\n\ndeclare module \"@effect/ai/Response\" {\n  export interface ReasoningPartMetadata extends ProviderMetadata {\n    readonly bedrock?: AmazonBedrockReasoningInfo | undefined\n  }\n\n  export interface FinishPartMetadata extends ProviderMetadata {\n    readonly bedrock?: {\n      readonly trace?: ConverseTrace | undefined\n      readonly usage: {\n        readonly cacheWriteInputTokens?: number | undefined\n      }\n    } | undefined\n  }\n}\n\n// =============================================================================\n// Amazon Bedrock Language Model\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category AiModels\n */\nexport const model = (\n  model: (string & {}) | Model,\n  config?: Omit<Config.Service, \"model\">\n): AiModel.Model<\"amazon-bedrock\", LanguageModel.LanguageModel, AmazonBedrockClient> =>\n  AiModel.make(\"amazon-bedrock\", layer({ model, config }))\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.fnUntraced(function*(options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Omit<Config.Service, \"model\">\n}) {\n  const client = yield* AmazonBedrockClient\n\n  const makeRequest = Effect.fnUntraced(\n    function*(providerOptions: LanguageModel.ProviderOptions) {\n      const context = yield* Effect.context<never>()\n      const config = { modelId: options.model, ...options.config, ...context.unsafeMap.get(Config.key) }\n      const { messages, system } = yield* prepareMessages(providerOptions)\n      const { additionalTools, betas, toolConfig } = yield* prepareTools(providerOptions, config)\n      const responseFormat = providerOptions.responseFormat\n      const request: typeof ConverseRequest.Encoded = {\n        ...config,\n        system,\n        messages,\n        // Handle tool configuration\n        ...(responseFormat.type === \"json\"\n          ? {\n            toolConfig: {\n              tools: [{\n                toolSpec: {\n                  name: responseFormat.objectName,\n                  description: Tool.getDescriptionFromSchemaAst(responseFormat.schema.ast) ??\n                    \"Respond with a JSON object\",\n                  inputSchema: {\n                    json: Tool.getJsonSchemaFromSchemaAst(responseFormat.schema.ast) as any\n                  }\n                }\n              }],\n              toolChoice: { tool: { name: responseFormat.objectName } }\n            }\n          }\n          : Predicate.isNotUndefined(toolConfig.tools) && toolConfig.tools.length > 0\n          ? { toolConfig }\n          : {}),\n        // Handle additional model request fields\n        ...(Predicate.isNotUndefined(additionalTools)\n          ? {\n            additionalModelRequestFields: {\n              ...config.additionalModelRequestFields,\n              ...additionalTools\n            }\n          }\n          : {})\n      }\n      return { betas, request }\n    }\n  )\n\n  return yield* LanguageModel.make({\n    generateText: Effect.fnUntraced(\n      function*(options) {\n        const { betas, request } = yield* makeRequest(options)\n        annotateRequest(options.span, request)\n        const anthropicBeta = betas.size > 0 ? Array.from(betas).join(\",\") : undefined\n        const rawResponse = yield* client.converse({\n          params: { \"anthropic-beta\": anthropicBeta },\n          payload: request\n        })\n        annotateResponse(options.span, request, rawResponse)\n        return yield* makeResponse(request, rawResponse, options)\n      }\n    ),\n    streamText: Effect.fnUntraced(\n      function*(options) {\n        const { betas, request } = yield* makeRequest(options)\n        annotateRequest(options.span, request)\n        const anthropicBeta = betas.size > 0 ? Array.from(betas).join(\",\") : undefined\n        const stream = client.converseStream({\n          params: { \"anthropic-beta\": anthropicBeta },\n          payload: request\n        })\n        return { request, stream }\n      },\n      (effect, options) =>\n        effect.pipe(\n          Effect.flatMap(({ request, stream }) => makeStreamResponse(request, stream, options)),\n          Stream.unwrap,\n          Stream.map((response) => {\n            annotateStreamResponse(options.span, response)\n            return response\n          })\n        )\n    )\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Omit<Config.Service, \"model\">\n}): Layer.Layer<LanguageModel.LanguageModel, never, AmazonBedrockClient> =>\n  Layer.effect(LanguageModel.LanguageModel, make({ model: options.model, config: options.config }))\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport const withConfigOverride: {\n  (config: Config.Service): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, config: Config.Service): Effect.Effect<A, E, R>\n} = dual<\n  (config: Config.Service) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, config: Config.Service) => Effect.Effect<A, E, R>\n>(2, (self, overrides) =>\n  Effect.flatMap(\n    Config.getOrUndefined,\n    (config) => Effect.provideService(self, Config, { ...config, ...overrides })\n  ))\n\n// =============================================================================\n// Prompt Conversion\n// =============================================================================\n\nconst prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect<{\n  readonly system: ReadonlyArray<typeof SystemContentBlock.Encoded>\n  readonly messages: ReadonlyArray<typeof Message.Encoded>\n}, AiError.AiError> = Effect.fnUntraced(\n  function*(options) {\n    const groups = groupMessages(options.prompt)\n\n    const system: Array<typeof SystemContentBlock.Encoded> = []\n    const messages: Array<typeof Message.Encoded> = []\n\n    let documentCounter = 0\n    const nextDocumentName = () => `document-${++documentCounter}`\n\n    for (let i = 0; i < groups.length; i++) {\n      const group = groups[i]\n      const isLastGroup = i === groups.length - 1\n\n      switch (group.type) {\n        case \"system\": {\n          if (messages.length > 0) {\n            return yield* new AiError.MalformedInput({\n              module: \"AmazonBedrockLanguageModel\",\n              method: \"prepareMessages\",\n              description: \"Multiple system messages separated by user / assistant messages\"\n            })\n          }\n          for (const message of group.messages) {\n            system.push({ text: message.content })\n            if (Predicate.isNotUndefined(getCachePoint(message))) {\n              system.push(BEDROCK_CACHE_POINT)\n            }\n          }\n          break\n        }\n\n        case \"user\": {\n          const content: Array<typeof ContentBlock.Encoded> = []\n\n          for (const message of group.messages) {\n            switch (message.role) {\n              case \"user\": {\n                for (let j = 0; j < message.content.length; j++) {\n                  const part = message.content[j]\n\n                  switch (part.type) {\n                    case \"text\": {\n                      content.push({ text: part.text })\n                      break\n                    }\n\n                    case \"file\": {\n                      if (part.data instanceof URL) {\n                        // TODO(Max): support this\n                        return yield* new AiError.MalformedInput({\n                          module: \"AmazonBedrockLanguageModel\",\n                          method: \"prepareMessages\",\n                          description: \"File URL inputs are not supported at this time\"\n                        })\n                      }\n                      if (part.mediaType.startsWith(\"image/\")) {\n                        content.push({\n                          image: {\n                            format: yield* getImageFormat(part.mediaType),\n                            source: { bytes: convertToBase64(part.data) }\n                          }\n                        })\n                      } else {\n                        content.push({\n                          document: {\n                            format: yield* getDocumentFormat(part.mediaType),\n                            name: nextDocumentName(),\n                            source: { bytes: convertToBase64(part.data) }\n                          }\n                        })\n                      }\n                      break\n                    }\n                  }\n                }\n                break\n              }\n\n              case \"tool\": {\n                for (const part of message.content) {\n                  content.push({\n                    toolResult: {\n                      toolUseId: part.id,\n                      content: [{ text: JSON.stringify(part.result) }]\n                    }\n                  })\n                }\n                break\n              }\n            }\n\n            if (getCachePoint(message)) {\n              content.push(BEDROCK_CACHE_POINT)\n            }\n          }\n\n          messages.push({ role: \"user\", content })\n\n          break\n        }\n\n        case \"assistant\": {\n          const content: Array<typeof ContentBlock.Encoded> = []\n\n          for (let j = 0; j < group.messages.length; j++) {\n            const message = group.messages[j]\n            const isLastMessage = j === group.messages.length - 1\n\n            for (let k = 0; k < message.content.length; k++) {\n              const part = message.content[k]\n              const isLastPart = k === message.content.length - 1\n\n              switch (part.type) {\n                case \"text\": {\n                  // Skip empty text blocks\n                  if (part.text.trim().length === 0) {\n                    break\n                  }\n                  content.push({\n                    // Amazon Bedrock does not allow trailing whitespace in\n                    // assistant content blocks\n                    text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.text)\n                  })\n                  break\n                }\n\n                case \"reasoning\": {\n                  const options = part.options.bedrock\n                  if (Predicate.isNotUndefined(options)) {\n                    if (options.type === \"thinking\") {\n                      content.push({\n                        reasoningContent: {\n                          reasoningText: {\n                            // Amazon Bedrock does not allow trailing whitespace in\n                            // assistant content blocks\n                            text: trimIfLast(isLastGroup, isLastMessage, isLastPart, part.text),\n                            signature: options.signature\n                          }\n                        }\n                      })\n                    }\n                    if (options.type === \"redacted_thinking\") {\n                      content.push({\n                        reasoningContent: {\n                          redactedContent: options.redactedData\n                        }\n                      })\n                    }\n                  }\n                  break\n                }\n\n                case \"tool-call\": {\n                  content.push({\n                    toolUse: {\n                      toolUseId: part.id,\n                      name: part.name,\n                      input: part.params\n                    }\n                  })\n                  break\n                }\n              }\n            }\n\n            if (getCachePoint(message)) {\n              content.push(BEDROCK_CACHE_POINT)\n            }\n          }\n\n          messages.push({ role: \"assistant\", content })\n\n          break\n        }\n      }\n    }\n\n    return { system, messages }\n  }\n)\n\n// =============================================================================\n// Response Conversion\n// =============================================================================\n\nconst makeResponse: (\n  request: typeof ConverseRequest.Encoded,\n  response: ConverseResponse,\n  options: LanguageModel.ProviderOptions\n) => Effect.Effect<\n  Array<Response.PartEncoded>,\n  never,\n  IdGenerator.IdGenerator\n> = Effect.fnUntraced(function*(request, response, options) {\n  const parts: Array<Response.PartEncoded> = []\n\n  parts.push({\n    type: \"response-metadata\",\n    modelId: request.modelId,\n    timestamp: DateTime.formatIso(yield* DateTime.now)\n  })\n\n  for (const part of response.output.message.content) {\n    switch (part.type) {\n      case \"text\": {\n        // The text parts should only be added to the response here if the\n        // response format is `\"text\"`. If the response format is `\"json\"`,\n        // then the text parts must instead be added to the response when a\n        // tool call is received.\n        if (options.responseFormat.type === \"text\") {\n          parts.push({\n            type: \"text\",\n            text: part.text\n          })\n        }\n        break\n      }\n\n      case \"reasoningContent\": {\n        if (part.reasoningContent.type === \"reasoning\") {\n          const signature = part.reasoningContent.reasoningText.signature\n          parts.push({\n            type: \"reasoning\",\n            text: part.reasoningContent.reasoningText.text,\n            metadata: Predicate.isNotUndefined(signature) ?\n              { bedrock: { type: \"thinking\", signature } }\n              : undefined\n          })\n        }\n        if (part.reasoningContent.type === \"redacted-reasoning\") {\n          parts.push({\n            type: \"reasoning\",\n            text: \"\",\n            metadata: {\n              bedrock: {\n                type: \"redacted_thinking\",\n                redactedData: part.reasoningContent.redactedContent\n              }\n            }\n          })\n        }\n        break\n      }\n\n      case \"toolUse\": {\n        // When a `\"json\"` response format is requested, the JSON that we need\n        // will be returned by the tool call injected into the request\n        if (options.responseFormat.type === \"json\") {\n          parts.push({\n            type: \"text\",\n            text: JSON.stringify(part.toolUse.input)\n          })\n        } else {\n          const providerTool = AnthropicTool.getProviderDefinedToolName(part.toolUse.name)\n          const name = Predicate.isNotUndefined(providerTool) ? providerTool : part.toolUse.name\n          const providerName = Predicate.isNotUndefined(providerTool) ? part.toolUse.name : undefined\n          parts.push({\n            type: \"tool-call\",\n            id: part.toolUse.toolUseId,\n            name,\n            params: part.toolUse.input,\n            providerName,\n            providerExecuted: false\n          })\n        }\n        break\n      }\n    }\n  }\n\n  const finishReason = InternalUtilities.resolveFinishReason(response.stopReason)\n\n  parts.push({\n    type: \"finish\",\n    reason: finishReason,\n    usage: {\n      inputTokens: response.usage.inputTokens,\n      outputTokens: response.usage.outputTokens,\n      totalTokens: response.usage.totalTokens,\n      cachedInputTokens: response.usage.cacheReadInputTokens\n    },\n    metadata: {\n      bedrock: {\n        trace: response.trace,\n        usage: { cacheWriteInputTokens: response.usage.cacheWriteInputTokens }\n      }\n    }\n  })\n\n  return parts\n})\n\nconst makeStreamResponse: (\n  request: typeof ConverseRequest.Encoded,\n  stream: Stream.Stream<ConverseResponseStreamEvent, AiError.AiError>,\n  options: LanguageModel.ProviderOptions\n) => Effect.Effect<\n  Stream.Stream<Response.StreamPartEncoded, AiError.AiError>,\n  never,\n  IdGenerator.IdGenerator\n> = Effect.fnUntraced(\n  function*(request, stream, options) {\n    const contentBlocks: Record<\n      number,\n      | {\n        readonly type: \"text\"\n      }\n      | {\n        readonly type: \"reasoning\"\n      }\n      | {\n        readonly type: \"tool-call\"\n        readonly id: string\n        readonly name: string\n        params: string\n        readonly providerName?: string | undefined\n        readonly providerExecuted: boolean\n      }\n    > = {}\n\n    let trace: ConverseTrace | undefined = undefined\n    let cacheWriteInputTokens: number | undefined = undefined\n    const usage: Mutable<typeof Response.Usage.Encoded> = {\n      inputTokens: undefined,\n      outputTokens: undefined,\n      totalTokens: undefined\n    }\n\n    return stream.pipe(\n      Stream.mapEffect(Effect.fnUntraced(function*(event) {\n        const parts: Array<Response.StreamPartEncoded> = []\n\n        switch (event.type) {\n          case \"messageStart\": {\n            parts.push({\n              type: \"response-metadata\",\n              modelId: request.modelId,\n              timestamp: DateTime.formatIso(yield* DateTime.now)\n            })\n            break\n          }\n\n          case \"messageStop\": {\n            const reason = InternalUtilities.resolveFinishReason(event.messageStop.stopReason)\n            parts.push({\n              type: \"finish\",\n              reason,\n              usage,\n              metadata: {\n                bedrock: { trace, usage: { cacheWriteInputTokens } }\n              }\n            })\n\n            break\n          }\n\n          case \"contentBlockStart\": {\n            const index = event.contentBlockStart.contentBlockIndex\n            const block = event.contentBlockStart\n            if (Predicate.isNotUndefined(block.start.toolUse)) {\n              const toolUse = block.start.toolUse\n              const toolName = toolUse.name\n              const providerTool = AnthropicTool.getProviderDefinedToolName(toolName)\n              const name = Predicate.isNotUndefined(providerTool) ? providerTool : toolName\n              const providerName = Predicate.isNotUndefined(providerTool) ? toolName : undefined\n\n              contentBlocks[index] = {\n                type: \"tool-call\",\n                id: toolUse.toolUseId,\n                name,\n                params: \"\",\n                providerName,\n                providerExecuted: false\n              }\n              // Only emit tool param delta events for text responses\n              if (options.responseFormat.type === \"text\") {\n                parts.push({\n                  type: \"tool-params-start\",\n                  id: toolUse.toolUseId,\n                  name: toolUse.name,\n                  providerExecuted: false\n                })\n              }\n            } else {\n              contentBlocks[index] = { type: \"text\" }\n              parts.push({\n                type: \"text-start\",\n                id: index.toString()\n              })\n            }\n            break\n          }\n\n          case \"contentBlockDelta\": {\n            const index = event.contentBlockDelta.contentBlockIndex\n            const delta = event.contentBlockDelta.delta\n\n            switch (delta.type) {\n              case \"text\": {\n                const block = contentBlocks[index]\n                if (Predicate.isUndefined(block)) {\n                  contentBlocks[index] = { type: \"text\" }\n                  // Only emit text delta events for text responses\n                  if (options.responseFormat.type === \"text\") {\n                    parts.push({\n                      type: \"text-start\",\n                      id: index.toString()\n                    })\n                  }\n                }\n                // Only emit text delta events for text responses\n                if (options.responseFormat.type === \"text\") {\n                  parts.push({\n                    type: \"text-delta\",\n                    id: index.toString(),\n                    delta: delta.text\n                  })\n                }\n                break\n              }\n\n              case \"reasoningContent\": {\n                if (\"text\" in delta.reasoningContent) {\n                  const block = contentBlocks[index]\n                  if (Predicate.isUndefined(block)) {\n                    contentBlocks[index] = { type: \"reasoning\" }\n                    parts.push({\n                      type: \"reasoning-start\",\n                      id: index.toString()\n                    })\n                  }\n                  parts.push({\n                    type: \"reasoning-delta\",\n                    id: index.toString(),\n                    delta: delta.reasoningContent.text\n                  })\n                } else if (\"signature\" in delta.reasoningContent) {\n                  parts.push({\n                    type: \"reasoning-delta\",\n                    id: index.toString(),\n                    delta: \"\",\n                    metadata: {\n                      bedrock: {\n                        type: \"thinking\",\n                        signature: delta.reasoningContent.signature\n                      }\n                    }\n                  })\n                } else {\n                  parts.push({\n                    type: \"reasoning-delta\",\n                    id: index.toString(),\n                    delta: \"\",\n                    metadata: {\n                      bedrock: {\n                        type: \"redacted_thinking\",\n                        redactedData: delta.reasoningContent.redactedContent\n                      }\n                    }\n                  })\n                }\n                break\n              }\n\n              case \"toolUse\": {\n                const block = contentBlocks[index]\n                if (Predicate.isNotUndefined(block) && block.type === \"tool-call\") {\n                  const params = delta.toolUse.input\n                  // Only emit tool params delta events for text responses\n                  if (options.responseFormat.type === \"text\") {\n                    parts.push({\n                      type: \"tool-params-delta\",\n                      id: block.id,\n                      delta: params\n                    })\n                  }\n                  block.params += params\n                }\n                break\n              }\n            }\n            break\n          }\n\n          case \"contentBlockStop\": {\n            const index = event.contentBlockStop.contentBlockIndex\n            const block = contentBlocks[index]\n            if (Predicate.isNotUndefined(block)) {\n              switch (block.type) {\n                case \"text\": {\n                  // Only emit text end events for text responses\n                  if (options.responseFormat.type === \"text\") {\n                    parts.push({\n                      type: \"text-end\",\n                      id: index.toString()\n                    })\n                  }\n                  break\n                }\n\n                case \"reasoning\": {\n                  parts.push({\n                    type: \"reasoning-end\",\n                    id: index.toString()\n                  })\n                  break\n                }\n\n                case \"tool-call\": {\n                  // Only emit tool param events for text responses - for JSON\n                  // responses, the structured output will be emitted as text\n                  if (options.responseFormat.type === \"text\") {\n                    parts.push({\n                      type: \"tool-params-end\",\n                      id: block.id\n                    })\n\n                    const toolName = block.name\n                    const toolParams = block.params\n\n                    const params = yield* Effect.try({\n                      try: () => Tool.unsafeSecureJsonParse(toolParams),\n                      catch: (cause) =>\n                        new AiError.MalformedOutput({\n                          module: \"AmazonBedrockLanguageModel\",\n                          method: \"makeStreamResponse\",\n                          description: \"Failed to securely parse tool call parameters \" +\n                            `for tool '${toolName}':\\nParameters: ${toolParams}`,\n                          cause\n                        })\n                    })\n\n                    parts.push({\n                      type: \"tool-call\",\n                      id: block.id,\n                      name: toolName,\n                      params,\n                      providerName: block.providerName,\n                      providerExecuted: block.providerExecuted\n                    })\n                  } else {\n                    parts.push({\n                      type: \"text-start\",\n                      id: index.toString()\n                    })\n                    parts.push({\n                      type: \"text-delta\",\n                      id: index.toString(),\n                      delta: block.params\n                    })\n                    parts.push({\n                      type: \"text-end\",\n                      id: index.toString()\n                    })\n                  }\n                  break\n                }\n              }\n              delete contentBlocks[index]\n            }\n            break\n          }\n\n          case \"metadata\": {\n            usage.inputTokens = event.metadata.usage.inputTokens\n            usage.outputTokens = event.metadata.usage.outputTokens\n            usage.totalTokens = event.metadata.usage.totalTokens\n            usage.cachedInputTokens = event.metadata.usage.cacheReadInputTokens\n            if (Predicate.isNotUndefined(event.metadata.usage.cacheWriteInputTokens)) {\n              cacheWriteInputTokens = event.metadata.usage.cacheWriteInputTokens\n            }\n            if (Predicate.isNotUndefined(event.metadata.trace)) {\n              trace = event.metadata.trace\n            }\n            break\n          }\n\n          case \"internalServerException\": {\n            parts.push({ type: \"error\", error: event.internalServerException })\n            break\n          }\n\n          case \"modelStreamErrorException\": {\n            parts.push({ type: \"error\", error: event.modelStreamErrorException })\n            break\n          }\n\n          case \"serviceUnavailableException\": {\n            parts.push({ type: \"error\", error: event.serviceUnavailableException })\n            break\n          }\n\n          case \"throttlingException\": {\n            parts.push({ type: \"error\", error: event.throttlingException })\n            break\n          }\n\n          case \"validationException\": {\n            parts.push({ type: \"error\", error: event.validationException })\n            break\n          }\n        }\n\n        return parts\n      })),\n      Stream.flattenIterables\n    )\n  }\n)\n\n// =============================================================================\n// Tool Calling\n// =============================================================================\n\nconst prepareTools: (\n  options: LanguageModel.ProviderOptions,\n  config: Config.Service\n) => Effect.Effect<{\n  readonly betas: ReadonlySet<string>\n  readonly toolConfig: Partial<typeof ToolConfiguration.Encoded>\n  readonly additionalTools?: Record<string, unknown> | undefined\n}, AiError.AiError> = Effect.fnUntraced(function*(options, config) {\n  const betas = new Set<string>()\n\n  if (options.tools.length === 0) {\n    return { toolConfig: {}, betas }\n  }\n\n  const isAnthropicModel = config.modelId!.includes(\"anthropic.\")\n  const userDefinedTools: Array<Tool.Any> = []\n  const providerDefinedTools: Array<Tool.AnyProviderDefined> = []\n  for (const tool of options.tools) {\n    if (Tool.isUserDefined(tool)) {\n      userDefinedTools.push(tool)\n    } else {\n      providerDefinedTools.push(tool as Tool.AnyProviderDefined)\n    }\n  }\n\n  const hasAnthropicTools = isAnthropicModel && providerDefinedTools.length > 0\n\n  let tools: Array<typeof AmazonBedrockTool.Encoded> = []\n  let additionalTools: Record<string, unknown> | undefined = undefined\n\n  // Handle Anthropic provider-defined tools for Anthropic models on Bedrock\n  if (hasAnthropicTools) {\n    const prepared = yield* prepareAnthropicTools(options, {})\n\n    prepared.betas.forEach((beta) => betas.add(beta))\n\n    if (Predicate.isNotUndefined(prepared.toolChoice)) {\n      // For Anthropic tools on Bedrock, only the 'tool_choice' goes into\n      // the `additionalModelRequestFields` parameter of the request, while\n      // the tool definitions themselves are sent in the usual `toolConfig`\n      additionalTools = {\n        tool_choice: prepared.toolChoice\n      }\n    }\n\n    // Handle conversion of provider-defined tools to Amazon Bedrock tool definitions\n    for (const providerDefinedTool of providerDefinedTools) {\n      tools.push({\n        toolSpec: {\n          name: providerDefinedTool.providerName,\n          description: Tool.getDescription(providerDefinedTool as any),\n          inputSchema: {\n            json: Tool.getJsonSchema(providerDefinedTool as any) as any\n          }\n        }\n      })\n    }\n  }\n\n  // Handle conversion of user-defined tools to Amazon Bedrock tool definitions\n  for (const tool of userDefinedTools) {\n    tools.push({\n      toolSpec: {\n        name: tool.name,\n        description: Tool.getDescription(tool as any),\n        inputSchema: {\n          json: Tool.getJsonSchema(tool as any) as any\n        }\n      }\n    })\n  }\n\n  // Handle resolution of tool choice for **Amazon Bedrock** user-defined tools.\n  // The tool choice for Anthropic provider-defined tools is resolved above and\n  // inserted into the additional tool configuration object.\n  let toolChoice: typeof ToolChoice.Encoded | undefined = undefined\n  if (!hasAnthropicTools && tools.length > 0 && Predicate.isNotUndefined(options.toolChoice)) {\n    if (options.toolChoice === \"none\") {\n      tools.length = 0\n      toolChoice = undefined\n    } else if (options.toolChoice === \"auto\") {\n      toolChoice = { auto: {} }\n    } else if (options.toolChoice === \"required\") {\n      toolChoice = { any: {} }\n    } else if (\"tool\" in options.toolChoice) {\n      toolChoice = { tool: { name: options.toolChoice.tool } }\n    } else {\n      const allowedTools = new Set(options.toolChoice.oneOf)\n      tools = tools.filter((tool) => allowedTools.has(tool.toolSpec?.name))\n      toolChoice = options.toolChoice.mode === \"auto\" ? { auto: {} } : { any: {} }\n    }\n  }\n\n  const toolConfig: Partial<typeof ToolConfiguration.Encoded> = tools.length > 0\n    ? { tools, toolChoice }\n    : {}\n\n  return { additionalTools, betas, toolConfig }\n})\n\n// =============================================================================\n// Telemetry\n// =============================================================================\n\nconst annotateRequest = (\n  span: Span,\n  request: typeof ConverseRequest.Encoded\n): void => {\n  addGenAIAnnotations(span, {\n    system: \"anthropic\",\n    operation: { name: \"chat\" },\n    request: {\n      model: request.modelId,\n      temperature: request.inferenceConfig?.temperature,\n      topP: request.inferenceConfig?.topP,\n      maxTokens: request.inferenceConfig?.maxTokens,\n      stopSequences: request.inferenceConfig?.stopSequences ?? []\n    }\n  })\n}\n\nconst annotateResponse = (\n  span: Span,\n  request: typeof ConverseRequest.Encoded,\n  response: ConverseResponse\n): void => {\n  addGenAIAnnotations(span, {\n    response: {\n      model: request.modelId,\n      finishReasons: response.stopReason ? [response.stopReason] : undefined\n    },\n    usage: {\n      inputTokens: response.usage.inputTokens,\n      outputTokens: response.usage.outputTokens\n    }\n  })\n}\n\nconst annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded) => {\n  if (part.type === \"response-metadata\") {\n    addGenAIAnnotations(span, {\n      response: {\n        id: part.id,\n        model: part.modelId\n      }\n    })\n  }\n  if (part.type === \"finish\") {\n    addGenAIAnnotations(span, {\n      response: {\n        finishReasons: [part.reason]\n      },\n      usage: {\n        inputTokens: part.usage.inputTokens,\n        outputTokens: part.usage.outputTokens\n      }\n    })\n  }\n}\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\ntype ContentGroup = SystemMessageGroup | AssistantMessageGroup | UserMessageGroup\n\ninterface SystemMessageGroup {\n  readonly type: \"system\"\n  readonly messages: Array<Prompt.SystemMessage>\n}\n\ninterface AssistantMessageGroup {\n  readonly type: \"assistant\"\n  readonly messages: Array<Prompt.AssistantMessage>\n}\n\ninterface UserMessageGroup {\n  readonly type: \"user\"\n  readonly messages: Array<Prompt.ToolMessage | Prompt.UserMessage>\n}\n\nconst groupMessages = (prompt: Prompt.Prompt): Array<ContentGroup> => {\n  const messages: Array<ContentGroup> = []\n  let current: ContentGroup | undefined = undefined\n  for (const message of prompt.content) {\n    switch (message.role) {\n      case \"system\": {\n        if (current?.type !== \"system\") {\n          current = { type: \"system\", messages: [] }\n          messages.push(current)\n        }\n        current.messages.push(message)\n        break\n      }\n      case \"assistant\": {\n        if (current?.type !== \"assistant\") {\n          current = { type: \"assistant\", messages: [] }\n          messages.push(current)\n        }\n        current.messages.push(message)\n        break\n      }\n      case \"tool\":\n      case \"user\": {\n        if (current?.type !== \"user\") {\n          current = { type: \"user\", messages: [] }\n          messages.push(current)\n        }\n        current.messages.push(message)\n        break\n      }\n    }\n  }\n  return messages\n}\n\n/**\n * Amazon Bedrock does not allow trailing whitespace in pre-fillled assistant\n * responses, so we trim the final text part here if it's the last message in\n * the group.\n */\nconst trimIfLast = (\n  isLastGroup: boolean,\n  isLastMessage: boolean,\n  isLastPart: boolean,\n  text: string\n) => isLastGroup && isLastMessage && isLastPart ? text.trim() : text\n\nconst getCachePoint = (\n  part:\n    | Prompt.SystemMessage\n    | Prompt.UserMessage\n    | Prompt.AssistantMessage\n    | Prompt.ToolMessage\n): typeof CachePointBlock.Encoded | undefined => part.options.bedrock?.cachePoint\n\nconst convertToBase64 = (data: string | Uint8Array): string =>\n  typeof data === \"string\" ? data : Encoding.encodeBase64(data)\n\nconst DOCUMENT_MIME_TYPES: Record<string, typeof DocumentFormat.Encoded> = {\n  \"application/pdf\": \"pdf\",\n  \"text/csv\": \"csv\",\n  \"application/msword\": \"doc\",\n  \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\": \"docx\",\n  \"application/vnd.ms-excel\": \"xls\",\n  \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": \"xlsx\",\n  \"text/html\": \"html\",\n  \"text/plain\": \"txt\",\n  \"text/markdown\": \"md\"\n}\n\nconst getDocumentFormat: (\n  mediaType: string\n) => Effect.Effect<typeof DocumentFormat.Encoded, AiError.AiError> = Effect.fnUntraced(\n  function*(mediaType) {\n    const format = DOCUMENT_MIME_TYPES[mediaType]\n\n    if (Predicate.isUndefined(format)) {\n      return yield* new AiError.MalformedInput({\n        module: \"AmazonBedrockLanguageModel\",\n        method: \"getDocumentFormat\",\n        description: `Unsupported document MIME type: ${mediaType} - expected ` +\n          `one of: ${Object.keys(DOCUMENT_MIME_TYPES)}`\n      })\n    }\n\n    return format\n  }\n)\n\nconst getImageFormat: (\n  mediaType: string\n) => Effect.Effect<typeof ImageFormat.Encoded, AiError.AiError> = Effect.fnUntraced(\n  function*(mediaType) {\n    const format = ImageFormat.literals.find((format) => mediaType === `image/${format}`)\n\n    if (Predicate.isUndefined(format)) {\n      return yield* new AiError.MalformedInput({\n        module: \"AmazonBedrockLanguageModel\",\n        method: \"getImageFormat\",\n        description: `Unsupported image MIME type: ${mediaType} - expected ` +\n          `one of: ${ImageFormat.literals.map((format) => `image/${format}`).join(\",\")}`\n      })\n    }\n\n    return format\n  }\n)\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/src/AmazonBedrockSchema.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Schema from \"effect/Schema\"\n\nconst prefix = \"@effect/ai-amazon-bedrock\"\n\nconst makeIdentifier = (name: string) => `${prefix}/${name}`\n\n/**\n * The foundation models supported by Amazon Bedrock.\n *\n * An up-to-date list can be generated with the following command:\n *\n * ```sh\n * aws bedrock list-foundation-models --output json | jq '[.modelSummaries[].modelId]'\n * ```\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class BedrockFoundationModelId extends Schema.Literal(\n  \"amazon.titan-tg1-large\",\n  \"amazon.titan-image-generator-v1:0\",\n  \"amazon.titan-image-generator-v1\",\n  \"amazon.titan-image-generator-v2:0\",\n  \"amazon.nova-premier-v1:0:8k\",\n  \"amazon.nova-premier-v1:0:20k\",\n  \"amazon.nova-premier-v1:0:1000k\",\n  \"amazon.nova-premier-v1:0:mm\",\n  \"amazon.nova-premier-v1:0\",\n  \"amazon.titan-text-premier-v1:0\",\n  \"amazon.nova-pro-v1:0:24k\",\n  \"amazon.nova-pro-v1:0:300k\",\n  \"amazon.nova-pro-v1:0\",\n  \"amazon.nova-lite-v1:0:24k\",\n  \"amazon.nova-lite-v1:0:300k\",\n  \"amazon.nova-lite-v1:0\",\n  \"amazon.nova-canvas-v1:0\",\n  \"amazon.nova-reel-v1:0\",\n  \"amazon.nova-reel-v1:1\",\n  \"amazon.nova-micro-v1:0:24k\",\n  \"amazon.nova-micro-v1:0:128k\",\n  \"amazon.nova-micro-v1:0\",\n  \"amazon.nova-sonic-v1:0\",\n  \"amazon.titan-embed-g1-text-02\",\n  \"amazon.titan-text-lite-v1:0:4k\",\n  \"amazon.titan-text-lite-v1\",\n  \"amazon.titan-text-express-v1:0:8k\",\n  \"amazon.titan-text-express-v1\",\n  \"amazon.titan-embed-text-v1:2:8k\",\n  \"amazon.titan-embed-text-v1\",\n  \"amazon.titan-embed-text-v2:0:8k\",\n  \"amazon.titan-embed-text-v2:0\",\n  \"amazon.titan-embed-image-v1:0\",\n  \"amazon.titan-embed-image-v1\",\n  \"stability.stable-diffusion-xl-v1:0\",\n  \"stability.stable-diffusion-xl-v1\",\n  \"ai21.jamba-instruct-v1:0\",\n  \"ai21.jamba-1-5-large-v1:0\",\n  \"ai21.jamba-1-5-mini-v1:0\",\n  \"anthropic.claude-instant-v1:2:100k\",\n  \"anthropic.claude-instant-v1\",\n  \"anthropic.claude-v2:0:18k\",\n  \"anthropic.claude-v2:0:100k\",\n  \"anthropic.claude-v2:1:18k\",\n  \"anthropic.claude-v2:1:200k\",\n  \"anthropic.claude-v2:1\",\n  \"anthropic.claude-v2\",\n  \"anthropic.claude-3-sonnet-20240229-v1:0:28k\",\n  \"anthropic.claude-3-sonnet-20240229-v1:0:200k\",\n  \"anthropic.claude-3-sonnet-20240229-v1:0\",\n  \"anthropic.claude-3-haiku-20240307-v1:0:48k\",\n  \"anthropic.claude-3-haiku-20240307-v1:0:200k\",\n  \"anthropic.claude-3-haiku-20240307-v1:0\",\n  \"anthropic.claude-3-opus-20240229-v1:0:12k\",\n  \"anthropic.claude-3-opus-20240229-v1:0:28k\",\n  \"anthropic.claude-3-opus-20240229-v1:0:200k\",\n  \"anthropic.claude-3-opus-20240229-v1:0\",\n  \"anthropic.claude-3-5-sonnet-20240620-v1:0\",\n  \"anthropic.claude-3-5-sonnet-20241022-v2:0\",\n  \"anthropic.claude-3-7-sonnet-20250219-v1:0\",\n  \"anthropic.claude-3-5-haiku-20241022-v1:0\",\n  \"anthropic.claude-opus-4-20250514-v1:0\",\n  \"anthropic.claude-sonnet-4-20250514-v1:0\",\n  \"cohere.command-text-v14:7:4k\",\n  \"cohere.command-text-v14\",\n  \"cohere.command-r-v1:0\",\n  \"cohere.command-r-plus-v1:0\",\n  \"cohere.command-light-text-v14:7:4k\",\n  \"cohere.command-light-text-v14\",\n  \"cohere.embed-english-v3:0:512\",\n  \"cohere.embed-english-v3\",\n  \"cohere.embed-multilingual-v3:0:512\",\n  \"cohere.embed-multilingual-v3\",\n  \"deepseek.r1-v1:0\",\n  \"meta.llama3-8b-instruct-v1:0\",\n  \"meta.llama3-70b-instruct-v1:0\",\n  \"meta.llama3-1-8b-instruct-v1:0\",\n  \"meta.llama3-1-70b-instruct-v1:0\",\n  \"meta.llama3-2-11b-instruct-v1:0\",\n  \"meta.llama3-2-90b-instruct-v1:0\",\n  \"meta.llama3-2-1b-instruct-v1:0\",\n  \"meta.llama3-2-3b-instruct-v1:0\",\n  \"meta.llama3-3-70b-instruct-v1:0\",\n  \"meta.llama4-scout-17b-instruct-v1:0\",\n  \"meta.llama4-maverick-17b-instruct-v1:0\",\n  \"mistral.mistral-7b-instruct-v0:2\",\n  \"mistral.mixtral-8x7b-instruct-v0:1\",\n  \"mistral.mistral-large-2402-v1:0\",\n  \"mistral.mistral-small-2402-v1:0\",\n  \"mistral.pixtral-large-2502-v1:0\"\n) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class CachePointBlock extends Schema.Class<CachePointBlock>(makeIdentifier(\"CachePointBlock\"))({\n  type: Schema.Literal(\"default\")\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const DocumentFormat = Schema.Literal(\n  \"csv\",\n  \"doc\",\n  \"docx\",\n  \"html\",\n  \"md\",\n  \"pdf\",\n  \"txt\",\n  \"xls\",\n  \"xlsx\"\n)\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport type DocumentFormat = typeof DocumentFormat.Type\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class DocumentBlock extends Schema.Class<DocumentBlock>(makeIdentifier(\"DocumentBlock\"))({\n  name: Schema.String.pipe(\n    Schema.pattern(/^[a-zA-Z0-9()[\\]-]+(?: [a-zA-Z0-9()[\\]-]+)*$/),\n    Schema.minLength(1),\n    Schema.maxLength(200)\n  ),\n  format: DocumentFormat,\n  source: Schema.Struct({\n    bytes: Schema.NonEmptyString\n  })\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailConverseImageBlock extends Schema.Class<GuardrailConverseImageBlock>(\n  makeIdentifier(\"GuardrailConverseImageBlock\")\n)({\n  format: Schema.Literal(\"png\", \"jpg\"),\n  source: Schema.Struct({\n    bytes: Schema.NonEmptyString\n  })\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailConverseTextBlock extends Schema.Class<GuardrailConverseTextBlock>(\n  makeIdentifier(\"GuardrailConverseTextBlock\")\n)({\n  text: Schema.String,\n  qualifiers: Schema.optional(Schema.Array(Schema.Literal(\"guard_content\", \"grounding_source\", \"query\")))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailConverseContentBlock extends Schema.Union(\n  GuardrailConverseImageBlock,\n  GuardrailConverseTextBlock\n) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const ImageFormat = Schema.Literal(\"gif\", \"jpeg\", \"png\", \"webp\")\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport type ImageFormat = typeof ImageFormat.Type\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ImageBlock extends Schema.Class<ImageBlock>(makeIdentifier(\"ImageBlock\"))({\n  format: ImageFormat,\n  source: Schema.Struct({\n    bytes: Schema.NonEmptyString\n  })\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class JsonBlock extends Schema.Class<JsonBlock>(makeIdentifier(\"JsonBlock\"))({\n  json: Schema.Unknown\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ReasoningContentBlock extends Schema.Union(\n  Schema.Struct({\n    reasoningText: Schema.Struct({\n      text: Schema.String,\n      signature: Schema.optional(Schema.String)\n    })\n  }).pipe(\n    Schema.attachPropertySignature(\"type\", \"reasoning\"),\n    Schema.annotations({ identifier: \"ReasoningTextContentBlock\" })\n  ),\n  Schema.Struct({\n    redactedContent: Schema.String\n  }).pipe(\n    Schema.attachPropertySignature(\"type\", \"redacted-reasoning\"),\n    Schema.annotations({ identifier: \"RedactedReasoningContentBlock\" })\n  )\n) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class VideoBlock extends Schema.Class<VideoBlock>(makeIdentifier(\"VideoBlock\"))({\n  format: Schema.Literal(\"flv\", \"mkv\", \"mov\", \"mp4\", \"mpg\", \"mpeg\", \"three_gp\", \"webm\"),\n  source: Schema.Union(\n    Schema.Struct({\n      bytes: Schema.NonEmptyString\n    }),\n    Schema.Struct({\n      s3Location: Schema.Struct({\n        uri: Schema.String.pipe(\n          Schema.pattern(/^s3:\\/\\/[a-z0-9][.\\-a-z0-9]{1,61}[a-z0-9](\\/.*)?$/),\n          Schema.minLength(1),\n          Schema.maxLength(1024)\n        ),\n        bucketOwner: Schema.String.pipe(\n          Schema.pattern(/^[0-9]{12}$/),\n          Schema.optional\n        )\n      })\n    })\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ToolResultBlock extends Schema.Class<ToolResultBlock>(makeIdentifier(\"ToolResultBlock\"))({\n  content: Schema.Array(Schema.Union(\n    Schema.Struct({ document: DocumentBlock }),\n    Schema.Struct({ image: ImageBlock }),\n    Schema.Struct({ text: Schema.String }),\n    Schema.Struct({ json: JsonBlock }),\n    Schema.Struct({ video: VideoBlock })\n  )),\n  toolUseId: Schema.String.pipe(\n    Schema.pattern(/^[a-zA-Z0-9_-]+$/),\n    Schema.minLength(1),\n    Schema.maxLength(64)\n  ),\n  status: Schema.optional(Schema.Literal(\"success\", \"error\"))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ToolUseBlock extends Schema.Class<ToolUseBlock>(makeIdentifier(\"ToolUseBlock\"))({\n  name: Schema.String.pipe(\n    Schema.pattern(/^[a-zA-Z0-9_-]+$/),\n    Schema.minLength(1),\n    Schema.maxLength(64)\n  ),\n  input: Schema.Unknown,\n  toolUseId: Schema.String.pipe(\n    Schema.pattern(/^[a-zA-Z0-9_-]+$/),\n    Schema.minLength(1),\n    Schema.maxLength(64)\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ContentBlock extends Schema.Union(\n  Schema.Struct({ cachePoint: CachePointBlock }).pipe(\n    Schema.attachPropertySignature(\"type\", \"cachePoint\"),\n    Schema.annotations({ identifier: \"CachePointContentBlock\" })\n  ),\n  Schema.Struct({ document: DocumentBlock }).pipe(\n    Schema.attachPropertySignature(\"type\", \"document\"),\n    Schema.annotations({ identifier: \"DocumentContentBlock\" })\n  ),\n  Schema.Struct({ guardContent: GuardrailConverseContentBlock }).pipe(\n    Schema.attachPropertySignature(\"type\", \"guardContent\"),\n    Schema.annotations({ identifier: \"GuardrailContentBlock\" })\n  ),\n  Schema.Struct({ image: ImageBlock }).pipe(\n    Schema.attachPropertySignature(\"type\", \"image\"),\n    Schema.annotations({ identifier: \"ImageContentBlock\" })\n  ),\n  Schema.Struct({ reasoningContent: ReasoningContentBlock }).pipe(\n    Schema.attachPropertySignature(\"type\", \"reasoningContent\"),\n    Schema.annotations({ identifier: \"ResponseContentBlock\" })\n  ),\n  Schema.Struct({ text: Schema.String }).pipe(\n    Schema.attachPropertySignature(\"type\", \"text\"),\n    Schema.annotations({ identifier: \"TextContentBlock\" })\n  ),\n  Schema.Struct({ toolResult: ToolResultBlock }).pipe(\n    Schema.attachPropertySignature(\"type\", \"toolResult\"),\n    Schema.annotations({ identifier: \"ToolResultContentBlock\" })\n  ),\n  Schema.Struct({ toolUse: ToolUseBlock }).pipe(\n    Schema.attachPropertySignature(\"type\", \"toolUse\"),\n    Schema.annotations({ identifier: \"ToolUseContentBlock\" })\n  ),\n  Schema.Struct({ video: VideoBlock }).pipe(\n    Schema.attachPropertySignature(\"type\", \"video\"),\n    Schema.annotations({ identifier: \"VideoContentBlock\" })\n  )\n) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class Message extends Schema.Class<Message>(makeIdentifier(\"Message\"))({\n  role: Schema.Literal(\"user\", \"assistant\"),\n  content: Schema.Array(ContentBlock)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ConverseOutput extends Schema.Class<ConverseOutput>(makeIdentifier(\"ConverseOutput\"))({\n  message: Message\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ConverseMetrics extends Schema.Class<ConverseMetrics>(makeIdentifier(\"ConverseMetrics\"))({\n  latencyMs: Schema.DurationFromMillis\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailContentFilter extends Schema.Class<GuardrailContentFilter>(\n  makeIdentifier(\"GuardrailContentFilter\")\n)({\n  type: Schema.Literal(\"HATE\", \"INSULTS\", \"MISCONDUCT\", \"PROMPT_ATTACK\", \"SEXUAL\", \"VIOLENCE\"),\n  action: Schema.Literal(\"BLOCKED\", \"NONE\"),\n  confidence: Schema.Literal(\"NONE\", \"LOW\", \"MEDIUM\", \"HIGH\"),\n  detected: Schema.optional(Schema.Boolean),\n  filterStrength: Schema.optional(Schema.Literal(\"NONE\", \"LOW\", \"MEDIUM\", \"HIGH\"))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailContentPolicyAssessment extends Schema.Class<GuardrailContentPolicyAssessment>(\n  makeIdentifier(\"GuardrailContentPolicyAssessment\")\n)({\n  filters: Schema.Array(GuardrailContentFilter)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailContextualGroundingFilter extends Schema.Class<GuardrailContextualGroundingFilter>(\n  makeIdentifier(\"GuardrailContextualGroundingFilter\")\n)({\n  type: Schema.Literal(\"GROUNDING\", \"RELEVANCE\"),\n  action: Schema.Literal(\"BLOCKED\", \"NONE\"),\n  score: Schema.Number.pipe(Schema.between(0, 1)),\n  threshold: Schema.Number.pipe(Schema.between(0, 1)),\n  detected: Schema.optional(Schema.Boolean)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailContextualGroundingPolicyAssessment\n  extends Schema.Class<GuardrailContextualGroundingPolicyAssessment>(\n    makeIdentifier(\"GuardrailContextualGroundingPolicyAssessment\")\n  )({\n    filters: Schema.optional(Schema.Array(GuardrailContextualGroundingFilter))\n  })\n{}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailImageCoverage extends Schema.Class<GuardrailImageCoverage>(\n  makeIdentifier(\"GuardrailImageCoverage\")\n)({\n  guarded: Schema.optional(Schema.Int),\n  total: Schema.optional(Schema.Int)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailTextCharactersCoverage extends Schema.Class<GuardrailTextCharactersCoverage>(\n  makeIdentifier(\"GuardrailTextCharactersCoverage\")\n)({\n  guarded: Schema.optional(Schema.Int),\n  total: Schema.optional(Schema.Int)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailCoverage extends Schema.Class<GuardrailCoverage>(makeIdentifier(\"GuardrailCoverage\"))({\n  images: Schema.optional(GuardrailImageCoverage),\n  textCharacters: Schema.optional(GuardrailTextCharactersCoverage)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailUsage extends Schema.Class<GuardrailUsage>(makeIdentifier(\"GuardrailUsage\"))({\n  contentPolicyUnits: Schema.Int,\n  contextualGroundingPolicyUnits: Schema.Int,\n  sensitiveInformationPolicyFreeUnits: Schema.Int,\n  sensitiveInformationPolicyUnits: Schema.Int,\n  topicPolicyUnits: Schema.Int,\n  wordPolicyUnits: Schema.Int,\n  contentPolicyImageUnits: Schema.optional(Schema.Int)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailInvocationMetrics extends Schema.Class<GuardrailInvocationMetrics>(\n  makeIdentifier(\"GuardrailInvocationMetrics\")\n)({\n  guardrailCoverage: Schema.optional(GuardrailCoverage),\n  guardrailProcessingLatency: Schema.optional(Schema.Number),\n  usage: Schema.optional(GuardrailUsage)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailPiiEntityFilter extends Schema.Class<GuardrailPiiEntityFilter>(\n  makeIdentifier(\"GuardrailPiiEntityFilter\")\n)({\n  type: Schema.Literal(\n    \"ADDRESS\",\n    \"AGE\",\n    \"AWS_ACCESS_KEY\",\n    \"AWS_SECRET_KEY\",\n    \"CA_HEALTH_NUMBER\",\n    \"CA_SOCIAL_INSURANCE_NUMBER\",\n    \"CREDIT_DEBIT_CARD_CVV\",\n    \"CREDIT_DEBIT_CARD_EXPIRY\",\n    \"CREDIT_DEBIT_CARD_NUMBER\",\n    \"DRIVER_ID\",\n    \"EMAIL\",\n    \"INTERNATIONAL_BANK_ACCOUNT_NUMBER\",\n    \"IP_ADDRESS\",\n    \"LICENSE_PLATE\",\n    \"MAC_ADDRESS\",\n    \"NAME\",\n    \"PASSWORD\",\n    \"PHONE\",\n    \"PIN\",\n    \"SWIFT_CODE\",\n    \"UK_NATIONAL_HEALTH_SERVICE_NUMBER\",\n    \"UK_NATIONAL_INSURANCE_NUMBER\",\n    \"UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER\",\n    \"URL\",\n    \"USERNAME\",\n    \"US_BANK_ACCOUNT_NUMBER\",\n    \"US_BANK_ROUTING_NUMBER\",\n    \"US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER\",\n    \"US_PASSPORT_NUMBER\",\n    \"US_SOCIAL_SECURITY_NUMBER\",\n    \"VEHICLE_IDENTIFICATION_NUMBER\"\n  ),\n  action: Schema.Literal(\"ANONYMIZED\", \"BLOCKED\", \"NONE\"),\n  match: Schema.String,\n  detected: Schema.optional(Schema.Boolean)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailRegexFilter extends Schema.Class<GuardrailRegexFilter>(\n  makeIdentifier(\"GuardrailRegexFilter\")\n)({\n  action: Schema.Literal(\"ANONYMIZED\", \"BLOCKED\", \"NONE\"),\n  name: Schema.optional(Schema.String),\n  match: Schema.optional(Schema.String),\n  regex: Schema.optional(Schema.String),\n  detected: Schema.optional(Schema.Boolean)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailSensitiveInformationPolicyAssessment\n  extends Schema.Class<GuardrailSensitiveInformationPolicyAssessment>(\n    makeIdentifier(\"GuardrailSensitiveInformationPolicyAssessment\")\n  )({\n    piiEntities: Schema.Array(GuardrailPiiEntityFilter),\n    regexes: Schema.Array(GuardrailRegexFilter)\n  })\n{}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailTopic extends Schema.Class<GuardrailTopic>(makeIdentifier(\"GuardrailTopic\"))({\n  action: Schema.Literal(\"BLOCKED\", \"NONE\"),\n  name: Schema.String,\n  type: Schema.Literal(\"DENY\"),\n  detected: Schema.optional(Schema.Boolean)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailTopicPolicyAssessment extends Schema.Class<GuardrailTopicPolicyAssessment>(\n  makeIdentifier(\"GuardrailTopicPolicyAssessment\")\n)({\n  topics: Schema.Array(GuardrailTopic)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailCustomWord extends Schema.Class<GuardrailCustomWord>(\n  makeIdentifier(\"GuardrailCustomWord\")\n)({\n  action: Schema.Literal(\"BLOCKED\", \"NONE\"),\n  match: Schema.String,\n  detected: Schema.optional(Schema.Boolean)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailManagedWord extends Schema.Class<GuardrailManagedWord>(\n  makeIdentifier(\"GuardrailManagedWord\")\n)({\n  action: Schema.Literal(\"BLOCKED\", \"NONE\"),\n  match: Schema.String,\n  type: Schema.Literal(\"PROFANITY\"),\n  detected: Schema.optional(Schema.Boolean)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailWordPolicyAssessment extends Schema.Class<GuardrailWordPolicyAssessment>(\n  makeIdentifier(\"GuardrailWordPolicyAssessment\")\n)({\n  customWords: GuardrailCustomWord,\n  managedWordLists: GuardrailManagedWord\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailAssessment extends Schema.Class<GuardrailAssessment>(makeIdentifier(\"GuardrailAssessment\"))({\n  contentPolicy: Schema.optional(GuardrailContentPolicyAssessment),\n  contextualGroundingPolicy: Schema.optional(GuardrailContextualGroundingPolicyAssessment),\n  invocationMetrics: Schema.optional(GuardrailInvocationMetrics),\n  sensitiveInformationPolicy: Schema.optional(GuardrailSensitiveInformationPolicyAssessment),\n  topicPolicy: Schema.optional(GuardrailTopicPolicyAssessment),\n  wordPolicy: Schema.optional(GuardrailWordPolicyAssessment)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailTraceAssessment extends Schema.Class<GuardrailTraceAssessment>(\n  makeIdentifier(\"GuardrailTraceAssessment\")\n)({\n  actionReason: Schema.optional(Schema.String),\n  inputAssessment: Schema.optional(Schema.Record({\n    key: Schema.String,\n    value: GuardrailAssessment\n  })),\n  modelOutput: Schema.optional(Schema.Array(Schema.String)),\n  outputAssessments: Schema.optional(Schema.Record({\n    key: Schema.String,\n    value: GuardrailAssessment\n  }))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class PromptRouterTrace extends Schema.Class<PromptRouterTrace>(makeIdentifier(\"PromptRouterTrace\"))({\n  invokedModelId: Schema.String.pipe(\n    Schema.pattern(\n      /^(arn:aws(-[^:]+)?:bedrock:[a-z0-9-]{1,20}::foundation-model\\/[a-z0-9-]{1,63}[.]{1}[a-z0-9-]{1,63}([a-z0-9-]{1,63}[.]){0,2}[a-z0-9-]{1,63}([:][a-z0-9-]{1,63}){0,2})|(arn:aws(|-us-gov|-cn|-iso|-iso-b):bedrock:(|[0-9a-z-]{1,20}):(|[0-9]{12}):inference-profile\\/[a-zA-Z0-9-:.]+)$/\n    ),\n    Schema.optional\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ConverseTrace extends Schema.Class<ConverseTrace>(makeIdentifier(\"ConverseTrace\"))({\n  guardrail: Schema.optional(GuardrailTraceAssessment),\n  promptRouter: Schema.optional(PromptRouterTrace)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const IntZeroOrGreater = Schema.Int.pipe(Schema.greaterThanOrEqualTo(0))\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class TokenUsage extends Schema.Class<TokenUsage>(makeIdentifier(\"TokenUsage\"))({\n  inputTokens: IntZeroOrGreater,\n  outputTokens: IntZeroOrGreater,\n  totalTokens: IntZeroOrGreater,\n  cacheReadInputTokens: Schema.optional(IntZeroOrGreater),\n  cacheWriteInputTokens: Schema.optional(IntZeroOrGreater)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class SystemContentBlock extends Schema.Union(\n  Schema.Struct({ cachePoint: CachePointBlock }),\n  Schema.Struct({ guardContent: GuardrailConverseContentBlock }),\n  Schema.Struct({ text: Schema.String.pipe(Schema.minLength(1)) })\n) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class GuardrailConfiguration extends Schema.Class<GuardrailConfiguration>(\n  makeIdentifier(\"GuardrailConfiguration\")\n)({\n  guardrailIdentifier: Schema.String.pipe(\n    Schema.minLength(0),\n    Schema.maxLength(2048),\n    Schema.pattern(/^(([a-z0-9]+)|(arn:aws(-[^:]+)?:bedrock:[a-z0-9-]{1,20}:[0-9]{12}:guardrail\\/[a-z0-9]+))$/)\n  ),\n  guardrailVersion: Schema.String.pipe(\n    Schema.pattern(/^(([1-9][0-9]{0,7})|(DRAFT))$/)\n  ),\n  trace: Schema.optional(Schema.Literal(\"enabled\", \"disabled\", \"enabled_full\"))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class InferenceConfiguration extends Schema.Class<InferenceConfiguration>(\n  makeIdentifier(\"InferenceConfiguration\")\n)({\n  maxTokens: Schema.optional(Schema.Int.pipe(Schema.greaterThanOrEqualTo(1))),\n  stopSequences: Schema.optional(\n    Schema.Array(Schema.String.pipe(\n      Schema.minLength(1)\n    )).pipe(\n      Schema.maxItems(4)\n    )\n  ),\n  temperature: Schema.optional(Schema.Number.pipe(Schema.between(0, 1))),\n  topP: Schema.optional(Schema.Number.pipe(Schema.between(0, 1)))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class PerformanceConfiguration extends Schema.Class<PerformanceConfiguration>(\n  makeIdentifier(\"PerformanceConfiguration\")\n)({\n  latency: Schema.optional(Schema.Literal(\"standard\", \"optimized\"))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ToolSpecification extends Schema.Class<ToolSpecification>(\n  makeIdentifier(\"ToolSpecification\")\n)({\n  name: Schema.String.pipe(\n    Schema.minLength(1),\n    Schema.maxLength(64),\n    Schema.pattern(/^[a-zA-Z0-9_-]+$/)\n  ),\n  inputSchema: Schema.Struct({\n    json: Schema.Record({\n      key: Schema.String,\n      value: Schema.Unknown\n    })\n  }),\n  description: Schema.optional(Schema.String.pipe(\n    Schema.minLength(1)\n  ))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class Tool extends Schema.Class<Tool>(\n  makeIdentifier(\"Tool\")\n)({\n  cachePoint: Schema.optional(CachePointBlock),\n  toolSpec: Schema.optional(ToolSpecification)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ToolChoice extends Schema.Union(\n  Schema.Struct({ any: Schema.Struct({}) }),\n  Schema.Struct({ auto: Schema.Struct({}) }),\n  Schema.Struct({\n    tool: Schema.Struct({\n      name: Schema.String.pipe(\n        Schema.minLength(1),\n        Schema.maxLength(64),\n        Schema.pattern(/^[a-zA-Z0-9_-]+$/)\n      )\n    })\n  })\n) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ToolConfiguration extends Schema.Class<ToolConfiguration>(\n  makeIdentifier(\"ToolConfiguration\")\n)({\n  tools: Schema.Array(Tool).pipe(Schema.minItems(1)),\n  toolChoice: Schema.optional(ToolChoice)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ConverseRequest extends Schema.Class<ConverseRequest>(makeIdentifier(\"ConverseRequest\"))({\n  modelId: Schema.String,\n  messages: Schema.Array(Message),\n  system: Schema.optional(Schema.Array(SystemContentBlock)),\n  toolConfig: Schema.optional(ToolConfiguration),\n  guardrailConfig: Schema.optional(GuardrailConfiguration),\n  inferenceConfig: Schema.optional(InferenceConfiguration),\n  performanceConfig: Schema.optional(PerformanceConfiguration),\n  promptVariables: Schema.optional(Schema.Record({\n    key: Schema.String,\n    value: Schema.Struct({ text: Schema.String })\n  })),\n  requestMetadata: Schema.optional(Schema.Record({\n    key: Schema.String.pipe(\n      Schema.minLength(1),\n      Schema.maxLength(256),\n      Schema.pattern(/^[a-zA-Z0-9\\s:_@$#=/+,-.]{1,256}$/)\n    ),\n    value: Schema.String.pipe(\n      Schema.minLength(0),\n      Schema.maxLength(256),\n      Schema.pattern(/^[a-zA-Z0-9\\s:_@$#=/+,-.]{0,256}$/)\n    )\n  })),\n  additionalModelRequestFields: Schema.optional(Schema.Record({\n    key: Schema.String,\n    value: Schema.Unknown\n  })),\n  additionalModelResponseFieldPaths: Schema.optional(\n    Schema.Array(Schema.String.pipe(\n      Schema.minLength(1),\n      Schema.maxLength(256)\n    )).pipe(\n      Schema.maxItems(10)\n    )\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ConverseResponse extends Schema.Class<ConverseResponse>(makeIdentifier(\"ConverseResponse\"))({\n  output: ConverseOutput,\n  metrics: ConverseMetrics,\n  usage: TokenUsage,\n  stopReason: Schema.Literal(\n    \"content_filtered\",\n    \"end_turn\",\n    \"tool_use\",\n    \"max_tokens\",\n    \"stop_sequence\",\n    \"guardrail_intervened\"\n  ),\n  trace: Schema.optional(ConverseTrace),\n  performanceConfig: Schema.optional(Schema.Struct({\n    latency: Schema.Literal(\"standard\", \"optimized\")\n  })),\n  additionalModelResponseFields: Schema.optional(Schema.Record({\n    key: Schema.String,\n    value: Schema.Unknown\n  }))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ReasoningContentBlockDelta extends Schema.Union(\n  Schema.Struct({ redactedContent: Schema.String }),\n  Schema.Struct({ signature: Schema.String }),\n  Schema.Struct({ text: Schema.String })\n) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ToolUseBlockStart extends Schema.Class<ToolUseBlockStart>(\n  makeIdentifier(\"ToolUseBlockStart\")\n)({\n  name: Schema.String.pipe(\n    Schema.minLength(1),\n    Schema.maxLength(64),\n    Schema.pattern(/^[a-zA-Z0-9_-]+$/)\n  ),\n  toolUseId: Schema.String.pipe(\n    Schema.minLength(1),\n    Schema.maxLength(64),\n    Schema.pattern(/^[a-zA-Z0-9_-]+$/)\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ContentBlockStart extends Schema.Class<ContentBlockStart>(\n  makeIdentifier(\"ContentBlockStart\")\n)({\n  toolUse: Schema.optional(ToolUseBlockStart)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ContentBlockStartEvent extends Schema.Class<ContentBlockStartEvent>(\n  makeIdentifier(\"ContentBlockStartEvent\")\n)({\n  contentBlockIndex: Schema.Int.pipe(Schema.greaterThanOrEqualTo(0)),\n  start: ContentBlockStart\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ContentBlockStopEvent extends Schema.Class<ContentBlockStopEvent>(\n  makeIdentifier(\"ContentBlockStopEvent\")\n)({\n  contentBlockIndex: Schema.Int.pipe(Schema.greaterThanOrEqualTo(0))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ToolUseBlockDelta extends Schema.Class<ToolUseBlockDelta>(\n  makeIdentifier(\"ToolUseBlockDelta\")\n)({\n  input: Schema.String\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ContentBlockDelta extends Schema.Union(\n  Schema.Struct({ reasoningContent: ReasoningContentBlockDelta }).pipe(\n    Schema.attachPropertySignature(\"type\", \"reasoningContent\")\n  ),\n  Schema.Struct({ text: Schema.String }).pipe(\n    Schema.attachPropertySignature(\"type\", \"text\")\n  ),\n  Schema.Struct({ toolUse: ToolUseBlockDelta }).pipe(\n    Schema.attachPropertySignature(\"type\", \"toolUse\")\n  )\n) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ContentBlockDeltaEvent extends Schema.Class<ContentBlockDeltaEvent>(\n  makeIdentifier(\"ContentBlockDeltaEvent\")\n)({\n  contentBlockIndex: Schema.Int.pipe(Schema.greaterThanOrEqualTo(0)),\n  delta: ContentBlockDelta\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class MessageStartEvent extends Schema.Class<MessageStartEvent>(\n  makeIdentifier(\"MessageStartEvent\")\n)({\n  role: Schema.Literal(\"user\", \"assistant\")\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const StopReason = Schema.Literal(\n  \"end_turn\",\n  \"tool_use\",\n  \"max_tokens\",\n  \"stop_sequence\",\n  \"guardrail_intervened\",\n  \"content_filtered\"\n)\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport type StopReason = typeof StopReason.Type\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class MessageStopEvent extends Schema.Class<MessageStopEvent>(\n  makeIdentifier(\"MessageStopEvent\")\n)({\n  stopReason: StopReason,\n  additionalModelResponseFields: Schema.optional(Schema.Record({\n    key: Schema.String,\n    value: Schema.Unknown\n  }))\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ConverseStreamMetrics extends Schema.Class<ConverseStreamMetrics>(\n  makeIdentifier(\"ConverseStreamMetrics\")\n)({\n  latencyMs: Schema.DurationFromMillis\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ConverseStreamTrace extends Schema.Class<ConverseStreamTrace>(\n  makeIdentifier(\"ConverseStreamTrace\")\n)({\n  guardrail: Schema.optional(GuardrailTraceAssessment),\n  promptRouter: Schema.optional(PromptRouterTrace)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ConverseStreamMetadataEvent extends Schema.Class<ConverseStreamMetadataEvent>(\n  makeIdentifier(\"ConverseStreamMetadataEvent\")\n)({\n  metrics: ConverseStreamMetrics,\n  usage: TokenUsage,\n  performanceConfig: Schema.optional(PerformanceConfiguration),\n  trace: Schema.optional(ConverseStreamTrace)\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const ConverseResponseStreamEvent = Schema.Union(\n  Schema.Struct({ messageStart: MessageStartEvent }).pipe(\n    Schema.attachPropertySignature(\"type\", \"messageStart\"),\n    Schema.annotations({ identifier: \"MessageStartEvent\" })\n  ),\n  Schema.Struct({ messageStop: MessageStopEvent }).pipe(\n    Schema.attachPropertySignature(\"type\", \"messageStop\"),\n    Schema.annotations({ identifier: \"MessageStopEvent\" })\n  ),\n  Schema.Struct({ contentBlockStart: ContentBlockStartEvent }).pipe(\n    Schema.attachPropertySignature(\"type\", \"contentBlockStart\"),\n    Schema.annotations({ identifier: \"ContentBlockStartEvent\" })\n  ),\n  Schema.Struct({ contentBlockDelta: ContentBlockDeltaEvent }).pipe(\n    Schema.attachPropertySignature(\"type\", \"contentBlockDelta\"),\n    Schema.annotations({ identifier: \"ContentBlockDeltaEvent\" })\n  ),\n  Schema.Struct({ contentBlockStop: ContentBlockStopEvent }).pipe(\n    Schema.attachPropertySignature(\"type\", \"contentBlockStop\"),\n    Schema.annotations({ identifier: \"ContentBlockDeltaEvent\" })\n  ),\n  Schema.Struct({ metadata: ConverseStreamMetadataEvent }).pipe(\n    Schema.attachPropertySignature(\"type\", \"metadata\"),\n    Schema.annotations({ identifier: \"ConverseStreamMetadataEvent\" })\n  ),\n  Schema.Struct({\n    internalServerException: Schema.Record({\n      key: Schema.String,\n      value: Schema.Unknown\n    })\n  }).pipe(\n    Schema.attachPropertySignature(\"type\", \"internalServerException\"),\n    Schema.annotations({ identifier: \"InternalServerException\" })\n  ),\n  Schema.Struct({\n    modelStreamErrorException: Schema.Record({\n      key: Schema.String,\n      value: Schema.Unknown\n    })\n  }).pipe(\n    Schema.attachPropertySignature(\"type\", \"modelStreamErrorException\"),\n    Schema.annotations({ identifier: \"ModelStreamErrorException\" })\n  ),\n  Schema.Struct({\n    serviceUnavailableException: Schema.Record({\n      key: Schema.String,\n      value: Schema.Unknown\n    })\n  }).pipe(\n    Schema.attachPropertySignature(\"type\", \"serviceUnavailableException\"),\n    Schema.annotations({ identifier: \"ServiceUnavailableException\" })\n  ),\n  Schema.Struct({\n    throttlingException: Schema.Record({\n      key: Schema.String,\n      value: Schema.Unknown\n    })\n  }).pipe(\n    Schema.attachPropertySignature(\"type\", \"throttlingException\"),\n    Schema.annotations({ identifier: \"ThrottlingException\" })\n  ),\n  Schema.Struct({\n    validationException: Schema.Record({\n      key: Schema.String,\n      value: Schema.Unknown\n    })\n  }).pipe(\n    Schema.attachPropertySignature(\"type\", \"validationException\"),\n    Schema.annotations({ identifier: \"ValidationException\" })\n  )\n).pipe(Schema.asSchema).annotations({ identifier: \"ConverseResponseStreamEvent\" })\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type ConverseResponseStreamEvent = typeof ConverseResponseStreamEvent.Type\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/src/AmazonBedrockTool.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AnthropicTool from \"@effect/ai-anthropic/AnthropicTool\"\nimport type * as Generated from \"@effect/ai-anthropic/Generated\"\nimport type * as Tool from \"@effect/ai/Tool\"\nimport type * as Schema from \"effect/Schema\"\n\n/**\n * @since 1.0.0\n * @catgory Tools\n */\nexport const AnthropicBash_20241022: <Mode extends Tool.FailureMode | undefined = undefined>(\n  args: {} & { readonly failureMode?: Mode | undefined }\n) => Tool.ProviderDefined<\n  \"AnthropicBash\",\n  {\n    readonly args: Schema.Struct<{}>\n    readonly parameters: Schema.Struct<\n      {\n        command: typeof Schema.NonEmptyString\n        restart: Schema.optional<typeof Schema.Boolean>\n      }\n    >\n    readonly success: typeof Schema.String\n    readonly failure: typeof Schema.Never\n    readonly failureMode: Mode extends undefined ? \"error\" : Mode\n  },\n  true\n> = AnthropicTool.Bash_20241022\n\n/**\n * @since 1.0.0\n * @catgory Tools\n */\nexport const AnthropicBash_20250124: <Mode extends Tool.FailureMode | undefined = undefined>(\n  args: {} & { readonly failureMode?: Mode | undefined }\n) => Tool.ProviderDefined<\n  \"AnthropicBash\",\n  {\n    readonly args: Schema.Struct<{}>\n    readonly parameters: Schema.Struct<\n      {\n        command: typeof Schema.NonEmptyString\n        restart: Schema.optional<typeof Schema.Boolean>\n      }\n    >\n    readonly success: typeof Schema.String\n    readonly failure: typeof Schema.Never\n    readonly failureMode: Mode extends undefined ? \"error\" : Mode\n  },\n  true\n> = AnthropicTool.Bash_20250124\n\n/**\n * @since 1.0.0\n * @catgory Tools\n */\nexport const AnthropicComputerUse_20241022: <Mode extends Tool.FailureMode | undefined = undefined>(\n  args: {\n    readonly display_height_px: number\n    readonly display_width_px: number\n    readonly cache_control?:\n      | {\n        readonly type: \"ephemeral\"\n        readonly ttl?: \"5m\" | \"1h\" | null | undefined\n      }\n      | null\n      | undefined\n    readonly display_number?: number | null | undefined\n    readonly failureMode?: Mode | undefined\n  }\n) => Tool.ProviderDefined<\n  \"AnthropicComputerUse\",\n  {\n    readonly args: Schema.Struct<\n      {\n        readonly cache_control: Schema.optionalWith<typeof Generated.BetaCacheControlEphemeral, { nullable: true }>\n        readonly display_height_px: Schema.filter<typeof Schema.Int>\n        readonly display_number: Schema.optionalWith<Schema.filter<typeof Schema.Int>, { nullable: true }>\n        readonly display_width_px: Schema.filter<typeof Schema.Int>\n      }\n    >\n    readonly parameters: Schema.Struct<\n      {\n        action: Schema.Literal<[\"screenshot\", \"left_click\", \"type\", \"key\", \"mouse_move\"]>\n        coordinate: Schema.optional<Schema.Tuple2<typeof Schema.Number, typeof Schema.Number>>\n        text: Schema.optional<typeof Schema.String>\n      }\n    >\n    readonly success: typeof Schema.String\n    readonly failure: typeof Schema.Never\n    readonly failureMode: Mode extends undefined ? \"error\" : Mode\n  },\n  true\n> = AnthropicTool.ComputerUse_20241022\n\n/**\n * @since 1.0.0\n * @catgory Tools\n */\nexport const AnthropicComputerUse_20250124: <Mode extends Tool.FailureMode | undefined = undefined>(\n  args: {\n    readonly display_height_px: number\n    readonly display_width_px: number\n    readonly cache_control?:\n      | {\n        readonly type: \"ephemeral\"\n        readonly ttl?: \"5m\" | \"1h\" | null | undefined\n      }\n      | null\n      | undefined\n    readonly display_number?: number | null | undefined\n    readonly failureMode?: Mode | undefined\n  }\n) => Tool.ProviderDefined<\n  \"AnthropicComputerUse\",\n  {\n    readonly args: Schema.Struct<\n      {\n        readonly cache_control: Schema.optionalWith<typeof Generated.BetaCacheControlEphemeral, { nullable: true }>\n        readonly display_height_px: Schema.filter<typeof Schema.Int>\n        readonly display_number: Schema.optionalWith<Schema.filter<typeof Schema.Int>, { nullable: true }>\n        readonly display_width_px: Schema.filter<typeof Schema.Int>\n      }\n    >\n    readonly parameters: Schema.Struct<\n      {\n        action: Schema.Literal<\n          [\n            \"screenshot\",\n            \"left_click\",\n            \"type\",\n            \"key\",\n            \"mouse_move\",\n            \"scroll\",\n            \"left_click_drag\",\n            \"middle_click\",\n            \"right_click\",\n            \"double_click\",\n            \"triple_click\",\n            \"left_mouse_down\",\n            \"left_mouse_up\",\n            \"hold_key\",\n            \"wait\"\n          ]\n        >\n        coordinate: Schema.optional<Schema.Tuple2<typeof Schema.Number, typeof Schema.Number>>\n        start_coordinate: Schema.optional<Schema.Tuple2<typeof Schema.Number, typeof Schema.Number>>\n        text: Schema.optional<typeof Schema.String>\n        scroll_direction: Schema.optional<Schema.Literal<[\"up\", \"down\", \"left\", \"right\"]>>\n        scroll_amount: Schema.optional<typeof Schema.Number>\n        duration: Schema.optional<typeof Schema.Number>\n      }\n    >\n    readonly success: typeof Schema.String\n    readonly failure: typeof Schema.Never\n    readonly failureMode: Mode extends undefined ? \"error\" : Mode\n  },\n  true\n> = AnthropicTool.ComputerUse_20250124\n\n/**\n * @since 1.0.0\n * @catgory Tools\n */\nexport const AnthropicTextEditor_20241022: <Mode extends Tool.FailureMode | undefined = undefined>(\n  args: { readonly failureMode?: Mode | undefined }\n) => Tool.ProviderDefined<\n  \"AnthropicTextEditor\",\n  {\n    readonly args: Schema.Struct<{}>\n    readonly parameters: Schema.Struct<\n      {\n        command: Schema.Literal<[\"view\", \"create\", \"str_replace\", \"insert\", \"undo_edit\"]>\n        path: typeof Schema.String\n        file_text: Schema.optional<typeof Schema.String>\n        insert_line: Schema.optional<typeof Schema.Number>\n        new_str: Schema.optional<typeof Schema.String>\n        old_str: Schema.optional<typeof Schema.String>\n        view_range: Schema.optional<Schema.Array$<typeof Schema.Number>>\n      }\n    >\n    readonly success: typeof Schema.Void\n    readonly failure: typeof Schema.Never\n    readonly failureMode: Mode extends undefined ? \"error\" : Mode\n  },\n  true\n> = AnthropicTool.TextEditor_20241022\n\n/**\n * @since 1.0.0\n * @catgory Tools\n */\nexport const AnthropicTextEditor_20250124: <Mode extends Tool.FailureMode | undefined = undefined>(\n  args: { readonly failureMode?: Mode | undefined }\n) => Tool.ProviderDefined<\n  \"AnthropicTextEditor\",\n  {\n    readonly args: Schema.Struct<{}>\n    readonly parameters: Schema.Struct<\n      {\n        command: Schema.Literal<[\"view\", \"create\", \"str_replace\", \"insert\", \"undo_edit\"]>\n        path: typeof Schema.String\n        file_text: Schema.optional<typeof Schema.String>\n        insert_line: Schema.optional<typeof Schema.Number>\n        new_str: Schema.optional<typeof Schema.String>\n        old_str: Schema.optional<typeof Schema.String>\n        view_range: Schema.optional<Schema.Array$<typeof Schema.Number>>\n      }\n    >\n    readonly success: typeof Schema.Void\n    readonly failure: typeof Schema.Never\n    readonly failureMode: Mode extends undefined ? \"error\" : Mode\n  },\n  true\n> = AnthropicTool.TextEditor_20250124\n\n/**\n * @since 1.0.0\n * @catgory Tools\n */\nexport const AnthropicTextEditor_20250429: <Mode extends Tool.FailureMode | undefined = undefined>(\n  args: { readonly failureMode?: Mode | undefined }\n) => Tool.ProviderDefined<\n  \"AnthropicTextEditor\",\n  {\n    readonly args: Schema.Struct<{}>\n    readonly parameters: Schema.Struct<\n      {\n        command: Schema.Literal<[\"view\", \"create\", \"str_replace\", \"insert\"]>\n        path: typeof Schema.String\n        file_text: Schema.optional<typeof Schema.String>\n        insert_line: Schema.optional<typeof Schema.Number>\n        new_str: Schema.optional<typeof Schema.String>\n        old_str: Schema.optional<typeof Schema.String>\n        view_range: Schema.optional<Schema.Array$<typeof Schema.Number>>\n      }\n    >\n    readonly success: typeof Schema.Void\n    readonly failure: typeof Schema.Never\n    readonly failureMode: Mode extends undefined ? \"error\" : Mode\n  },\n  true\n> = AnthropicTool.TextEditor_20250429\n\n/**\n * @since 1.0.0\n * @catgory Tools\n */\nexport const AnthropicTextEditor_20250728: <Mode extends Tool.FailureMode | undefined = undefined>(\n  args: { readonly failureMode?: Mode | undefined }\n) => Tool.ProviderDefined<\n  \"AnthropicTextEditor\",\n  {\n    readonly args: Schema.Struct<{}>\n    readonly parameters: Schema.Struct<\n      {\n        command: Schema.Literal<[\"view\", \"create\", \"str_replace\", \"insert\"]>\n        path: typeof Schema.String\n        file_text: Schema.optional<typeof Schema.String>\n        insert_line: Schema.optional<typeof Schema.Number>\n        new_str: Schema.optional<typeof Schema.String>\n        old_str: Schema.optional<typeof Schema.String>\n        view_range: Schema.optional<Schema.Array$<typeof Schema.Number>>\n      }\n    >\n    readonly success: typeof Schema.Void\n    readonly failure: typeof Schema.Never\n    readonly failureMode: Mode extends undefined ? \"error\" : Mode\n  },\n  true\n> = AnthropicTool.TextEditor_20250728\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/src/EventStreamEncoding.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport { EventStreamCodec } from \"@smithy/eventstream-codec\"\nimport { fromUtf8, toUtf8 } from \"@smithy/util-utf8\"\nimport * as Channel from \"effect/Channel\"\nimport type * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport * as Schema from \"effect/Schema\"\nimport type * as AsyncInput from \"effect/SingleProducerAsyncInput\"\n\n/**\n * An event stream encoding parser.\n *\n * See the [AWS Documentation](https://docs.aws.amazon.com/lexv2/latest/dg/event-stream-encoding.html)\n * for more information.\n *\n * @since 1.0.0\n */\nexport const makeChannel: <A, I, R, IE, Done>(schema: Schema.Schema<A, I, R>, options?: {\n  readonly bufferSize?: number\n}) => Channel.Channel<\n  Chunk.Chunk<A>,\n  Chunk.Chunk<Uint8Array<ArrayBufferLike>>,\n  IE | ParseError,\n  IE,\n  void,\n  Done,\n  R\n> = Effect.fnUntraced(\n  function*<A, I, R, IE, Done>(schema: Schema.Schema<A, I, R>, options?: {\n    readonly bufferSize?: number\n  }) {\n    const context = yield* Effect.context<R>()\n\n    const mailbox = yield* Mailbox.make<A, IE | ParseError>(options?.bufferSize ?? 16)\n\n    const codec = new EventStreamCodec(toUtf8, fromUtf8)\n    const decodeMessage = Schema.decodeUnknown(schema, {\n      onExcessProperty: \"ignore\"\n    })\n    const textDecoder = new TextDecoder()\n\n    let messages: Array<A> = []\n    let buffer = new Uint8Array(0)\n\n    const input: AsyncInput.AsyncInputProducer<\n      IE | ParseError,\n      Chunk.Chunk<Uint8Array>,\n      Done\n    > = {\n      awaitRead() {\n        return Effect.void\n      },\n      emit(chunks) {\n        return Effect.forEach(\n          chunks,\n          Effect.fnUntraced(function*(chunk) {\n            // Append new chunk to buffer\n            const newBuffer = new Uint8Array(buffer.length + chunk.length)\n            newBuffer.set(buffer)\n            newBuffer.set(chunk, buffer.length)\n            buffer = newBuffer\n\n            // Try to decode messages from the buffer\n            while (buffer.length >= 4) {\n              // The first four bytes are the total length of the message (big-endian)\n              const totalLength = new DataView(\n                buffer.buffer,\n                buffer.byteOffset,\n                buffer.byteLength\n              ).getUint32(0, false)\n\n              // If we don't have the full message yet, keep looping\n              if (buffer.length < totalLength) {\n                break\n              }\n\n              // Decode exactly the sub-slice for this event\n              const subView = buffer.subarray(0, totalLength)\n              const decoded = codec.decode(subView)\n\n              // Slice the used bytes off the buffer, removing this message\n              buffer = buffer.slice(totalLength)\n\n              // Process the message\n              if (decoded.headers[\":message-type\"]?.value === \"event\") {\n                const data = textDecoder.decode(decoded.body)\n\n                // Wrap the data in the `\":event-type\"` field to match the\n                // expected schema\n                const message = yield* decodeMessage({\n                  [decoded.headers[\":event-type\"]?.value as string]: JSON.parse(data)\n                }).pipe(Effect.provide(context))\n\n                messages.push(message)\n              }\n            }\n            yield* mailbox.offerAll(messages)\n            messages = []\n          }),\n          { discard: true }\n        ).pipe(Effect.catchAll((error) => mailbox.fail(error)))\n      },\n      error(cause) {\n        return mailbox.failCause(cause)\n      },\n      done() {\n        return mailbox.end\n      }\n    }\n\n    return Channel.embedInput(Mailbox.toChannel(mailbox), input)\n  },\n  Channel.unwrap\n) as any\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/src/index.ts",
    "content": "/**\n * @since 1.0.0\n */\nexport * as AmazonBedrockClient from \"./AmazonBedrockClient.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as AmazonBedrockConfig from \"./AmazonBedrockConfig.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as AmazonBedrockLanguageModel from \"./AmazonBedrockLanguageModel.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as AmazonBedrockSchema from \"./AmazonBedrockSchema.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as AmazonBedrockTool from \"./AmazonBedrockTool.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EventStreamEncoding from \"./EventStreamEncoding.js\"\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/src/internal/utilities.ts",
    "content": "import type * as Response from \"@effect/ai/Response\"\nimport * as Predicate from \"effect/Predicate\"\nimport type { StopReason } from \"../AmazonBedrockSchema.js\"\n\n/** @internal */\nexport const ProviderOptionsKey = \"@effect/ai-amazon-bedrock/AmazonBedrockLanguageModel/ProviderOptions\"\n\n/** @internal */\nexport const ProviderMetadataKey = \"@effect/ai-amazon-bedrock/AmazonBedrockLanguageModel/ProviderMetadata\"\n\nconst finishReasonMap: Record<StopReason, Response.FinishReason> = {\n  content_filtered: \"content-filter\",\n  end_turn: \"stop\",\n  guardrail_intervened: \"content-filter\",\n  max_tokens: \"length\",\n  stop_sequence: \"stop\",\n  tool_use: \"tool-calls\"\n}\n\n/** @internal */\nexport const resolveFinishReason = (stopReason: StopReason): Response.FinishReason => {\n  const reason = finishReasonMap[stopReason]\n  return Predicate.isUndefined(reason) ? \"unknown\" : reason\n}\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"references\": [\n    { \"path\": \"../ai/tsconfig.build.json\" },\n    { \"path\": \"../anthropic/tsconfig.build.json\" },\n    { \"path\": \"../../effect/tsconfig.build.json\" },\n    { \"path\": \"../../experimental/tsconfig.build.json\" },\n    { \"path\": \"../../platform/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/tsconfig.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"references\": [\n    { \"path\": \"../ai/tsconfig.src.json\" },\n    { \"path\": \"../anthropic/tsconfig.src.json\" },\n    { \"path\": \"../../effect/tsconfig.src.json\" },\n    { \"path\": \"../../experimental/tsconfig.src.json\" },\n    { \"path\": \"../../platform/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\",\n    \"outDir\": \"build/src\",\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../../vitest/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"noEmit\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/amazon-bedrock/vitest.config.ts",
    "content": "import { mergeConfig, type ViteUserConfig } from \"vitest/config\"\nimport shared from \"../../../vitest.shared.js\"\n\nconst config: ViteUserConfig = {}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/ai/anthropic/CHANGELOG.md",
    "content": "# @effect/ai-anthropic\n\n## 0.25.0\n\n### Patch Changes\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n  - @effect/ai@0.35.0\n  - @effect/experimental@0.60.0\n  - @effect/platform@0.96.0\n\n## 0.24.0\n\n### Patch Changes\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n  - @effect/ai@0.34.0\n  - @effect/experimental@0.59.0\n  - @effect/platform@0.95.0\n\n## 0.23.0\n\n### Patch Changes\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n  - @effect/platform@0.94.0\n  - @effect/ai@0.33.0\n  - @effect/experimental@0.58.0\n\n## 0.22.0\n\n### Patch Changes\n\n- Updated dependencies [[`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - effect@3.19.0\n  - @effect/platform@0.93.0\n  - @effect/ai@0.32.0\n  - @effect/experimental@0.57.0\n\n## 0.21.1\n\n### Patch Changes\n\n- [#5644](https://github.com/Effect-TS/effect/pull/5644) [`7de0bfc`](https://github.com/Effect-TS/effect/commit/7de0bfc57f9a1d69c342224ab26402752677efcb) Thanks @IMax153! - Ensure that model accepts a string in Anthropic request schemas\n\n## 0.21.0\n\n### Minor Changes\n\n- [#5621](https://github.com/Effect-TS/effect/pull/5621) [`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825) Thanks @IMax153! - Remove `Either` / `EitherEncoded` from tool call results.\n\n  Specifically, the encoding of tool call results as an `Either` / `EitherEncoded` has been removed and is replaced by encoding the tool call success / failure directly into the `result` property.\n\n  To allow type-safe discrimination between a tool call result which was a success vs. one that was a failure, an `isFailure` property has also been added to the `\"tool-result\"` part. If `isFailure` is `true`, then the tool call handler result was an error.\n\n  ```ts\n  import * as AnthropicClient from \"@effect/ai-anthropic/AnthropicClient\"\n  import * as AnthropicLanguageModel from \"@effect/ai-anthropic/AnthropicLanguageModel\"\n  import * as LanguageModel from \"@effect/ai/LanguageModel\"\n  import * as Tool from \"@effect/ai/Tool\"\n  import * as Toolkit from \"@effect/ai/Toolkit\"\n  import * as NodeHttpClient from \"@effect/platform-node/NodeHttpClient\"\n  import { Config, Effect, Layer, Schema, Stream } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"An example of a tool with success and failure types\",\n    failureMode: \"return\", // Return errors in the response\n    parameters: { bar: Schema.Number },\n    success: Schema.Number,\n    failure: Schema.Struct({ reason: Schema.Literal(\"reason-1\", \"reason-2\") })\n  })\n\n  const MyToolkit = Toolkit.make(MyTool)\n\n  const MyToolkitLayer = MyToolkit.toLayer({\n    MyTool: () => Effect.succeed(42)\n  })\n\n  const program = LanguageModel.streamText({\n    prompt: \"Tell me about the meaning of life\",\n    toolkit: MyToolkit\n  }).pipe(\n    Stream.runForEach((part) => {\n      if (part.type === \"tool-result\" && part.name === \"MyTool\") {\n        // The `isFailure` property can be used to discriminate whether the result\n        // of a tool call is a success or a failure\n        if (part.isFailure) {\n          part.result\n          //   ^? { readonly reason: \"reason-1\" | \"reason-2\"; }\n        } else {\n          part.result\n          //   ^? number\n        }\n      }\n      return Effect.void\n    }),\n    Effect.provide(Claude)\n  )\n\n  const Anthropic = AnthropicClient.layerConfig({\n    apiKey: Config.redacted(\"ANTHROPIC_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(Effect.provide([Anthropic, MyToolkitLayer]), Effect.runPromise)\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825)]:\n  - @effect/ai@0.31.0\n\n## 0.20.0\n\n### Minor Changes\n\n- [#5614](https://github.com/Effect-TS/effect/pull/5614) [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652) Thanks @IMax153! - Previously, tool call handler errors were _always_ raised as an expected error in the Effect `E` channel at the point of execution of the tool call handler (i.e. when a `generate*` method is invoked on a `LanguageModel`).\n\n  With this PR, the end user now has control over whether tool call handler errors should be raised as an Effect error, or returned by the SDK to allow, for example, sending that error information to another application.\n\n  ### Tool Call Specification\n\n  The `Tool.make` and `Tool.providerDefined` constructors now take an extra optional parameter called `failureMode`, which can be set to either `\"error\"` or `\"return\"`.\n\n  ```ts\n  import { Tool } from \"@effect/ai\"\n  import { Schema } from \"effect\"\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"My special tool\",\n    failureMode: \"return\" // \"error\" (default) or \"return\"\n    parameters: {\n      myParam: Schema.String\n    },\n    success: Schema.Struct({\n      mySuccess: Schema.String\n    }),\n    failure: Schema.Struct({\n      myFailure: Schema.String\n    })\n  })\n\n  ```\n\n  The semantics of `failureMode` are as follows:\n  - If set to `\"error\"` (the default), errors that occur during tool call handler execution will be returned in the error channel of the calling effect\n  - If set to `\"return\"`, errors that occur during tool call handler execution will be captured and returned as part of the tool call result\n\n  ### Response - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a large language model provider response is now represented as an `Either`.\n  - If the `result` is a `Left`, the `result` will be the `failure` specified in the tool call specification\n  - If the `result` is a `Right`, the `result` will be the `success` specified in the tool call specification\n\n  This is only relevant if the end user sets `failureMode` to `\"return\"`. If set to `\"error\"` (the default), then the `result` property will always be a `Right` with the successful result of the tool call handler.\n\n  Similarly the `encodedResult` field of a `\"tool-result\"` part will be represented as an `EitherEncoded`, where:\n  - `{ _tag: \"Left\", left: <failure> }` represents a tool call handler failure\n  - `{ _tag: \"Right\", right: <success> }` represents a tool call handler success\n\n  ### Prompt - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a prompt will now only accept an `EitherEncoded` as specified above.\n\n### Patch Changes\n\n- [#5615](https://github.com/Effect-TS/effect/pull/5615) [`1d2e92d`](https://github.com/Effect-TS/effect/commit/1d2e92de9a20f39765bd0b338ffc936ba2fd9463) Thanks @janglad! - Remove accidental commit of debug console.dir\n\n- Updated dependencies [[`6ae2f5d`](https://github.com/Effect-TS/effect/commit/6ae2f5da45a9ed9832605eca12b3e2bf2e2a1a67), [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652)]:\n  - effect@3.18.4\n  - @effect/ai@0.30.0\n\n## 0.19.2\n\n### Patch Changes\n\n- [#5608](https://github.com/Effect-TS/effect/pull/5608) [`215ed46`](https://github.com/Effect-TS/effect/commit/215ed4642b0c991d47e86fabb62f2118bf5f0231) Thanks @IMax153! - Fix incorrect detection of either result\n\n- Updated dependencies [[`8ba4757`](https://github.com/Effect-TS/effect/commit/8ba47576c75b8b91be4bf9c1dae13995b37018af)]:\n  - effect@3.18.2\n\n## 0.19.1\n\n### Patch Changes\n\n- [#5599](https://github.com/Effect-TS/effect/pull/5599) [`d7eba97`](https://github.com/Effect-TS/effect/commit/d7eba977288f0a97a1dac5cadb1f16253220b82a) Thanks @IMax153! - Fix provider defined tool results in prompt input\n\n## 0.19.0\n\n### Patch Changes\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2), [`f8b93ac`](https://github.com/Effect-TS/effect/commit/f8b93ac6446efd3dd790778b0fc71d299a38f272)]:\n  - effect@3.18.0\n  - @effect/ai@0.29.0\n  - @effect/platform@0.92.0\n  - @effect/experimental@0.56.0\n\n## 0.18.2\n\n### Patch Changes\n\n- [#5571](https://github.com/Effect-TS/effect/pull/5571) [`122aa53`](https://github.com/Effect-TS/effect/commit/122aa53058ff008cf605cc2f0f0675a946c3cae9) Thanks @IMax153! - Ensure that AI provider clients filter response status for stream requests\n\n## 0.18.1\n\n### Patch Changes\n\n- [#5554](https://github.com/Effect-TS/effect/pull/5554) [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a) Thanks @IMax153! - Improve the information available to the user following a model response error\n\n- Updated dependencies [[`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a), [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a), [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a), [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a), [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a), [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a)]:\n  - @effect/ai@0.28.2\n\n## 0.18.0\n\n### Patch Changes\n\n- Updated dependencies [[`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a)]:\n  - @effect/platform@0.91.0\n  - @effect/ai@0.28.0\n  - @effect/experimental@0.55.0\n\n## 0.17.1\n\n### Patch Changes\n\n- [#5521](https://github.com/Effect-TS/effect/pull/5521) [`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80) Thanks @IMax153! - Fix provider metadata and parse tool call parameters safely\n\n- Updated dependencies [[`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80)]:\n  - @effect/ai@0.27.1\n\n## 0.17.0\n\n### Minor Changes\n\n- [#5469](https://github.com/Effect-TS/effect/pull/5469) [`42b914a`](https://github.com/Effect-TS/effect/commit/42b914a0e8750350ce17d434afaec7d655ddf4b7) Thanks @IMax153! - Refactor the Effect AI SDK and associated provider packages\n\n  This pull request contains a complete refactor of the base Effect AI SDK package\n  as well as the associated provider integration packages to improve flexibility\n  and enhance ergonomics. Major changes are outlined below.\n\n  ## Modules\n\n  All modules in the base Effect AI SDK have had the leading `Ai` prefix dropped\n  from their name (except for the `AiError` module).\n\n  For example, the `AiLanguageModel` module is now the `LanguageModel` module.\n\n  In addition, the `AiInput` module has been renamed to the `Prompt` module.\n\n  ## Prompts\n\n  The `Prompt` module has been completely redesigned with flexibility in mind.\n\n  The `Prompt` module now supports building a prompt using either the constructors\n  exposed from the `Prompt` module, or using raw prompt content parts / messages,\n  which should be familiar to those coming from other AI SDKs.\n\n  In addition, the `system` option has been removed from all `LanguageModel` methods\n  and must now be provided as part of the prompt.\n\n  **Prompt Constructors**\n\n  ```ts\n  import { LanguageModel, Prompt } from \"@effect/ai\"\n\n  const textPart = Prompt.makePart(\"text\", {\n    text: \"What is machine learning?\"\n  })\n\n  const userMessage = Prompt.makeMessage(\"user\", {\n    content: [textPart]\n  })\n\n  const systemMessage = Prompt.makeMessage(\"system\", {\n    content: \"You are an expert in machine learning\"\n  })\n\n  const program = LanguageModel.generateText({\n    prompt: Prompt.fromMessages([systemMessage, userMessage])\n  })\n  ```\n\n  **Raw Prompt Input**\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n\n  const program = LanguageModel.generateText({\n    prompt: [\n      { role: \"system\", content: \"You are an expert in machine learning\" },\n      {\n        role: \"user\",\n        content: [{ type: \"text\", text: \"What is machine learning?\" }]\n      }\n    ]\n  })\n  ```\n\n  **NOTE**: Providing a plain string as a prompt is still supported, and will be converted\n  internally into a user message with a single text content part.\n\n  ### Provider-Specific Options\n\n  To support specification of provider-specific options when interacting with large\n  language model providers, support has been added for adding provider-specific\n  options to the parts of a `Prompt`.\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-sonnet-4-20250514\")\n\n  const program = LanguageModel.generateText({\n    prompt: [\n      {\n        role: \"user\",\n        content: [{ type: \"text\", text: \"What is machine learning?\" }],\n        options: {\n          anthropic: { cacheControl: { type: \"ephemeral\", ttl: \"1h\" } }\n        }\n      }\n    ]\n  }).pipe(Effect.provide(Claude))\n  ```\n\n  ## Responses\n\n  The `Response` module has also been completely redesigned to support a wider\n  variety of response parts, particularly when streaming.\n\n  ### Streaming Responses\n\n  When streaming text via the `LanguageModel.streamText` method, you will now\n  receive a stream of content parts instead of a stream of responses, which should\n  make it much simpler to filter down the stream to the parts you are interested in.\n\n  In addition, additional content parts will be present in the stream to allow you to track,\n  for example, when a text content part starts / ends.\n\n  ### Tool Calls / Tool Call Results\n\n  The decoded parts of a `Response` (as returned by the methods of `LanguageModel`)\n  are now fully type-safe on tool calls / tool call results. Filtering the content parts of a\n  response to tool calls will narrow the type of the tool call `params` based on the tool\n  `name`. Similarly, filtering the response to tool call results will narrow the type of the\n  tool call `result` based on the tool `name`.\n\n  ```ts\n  import { LanguageModel, Tool, Toolkit } from \"@effect/ai\"\n  import { Effect, Schema } from \"effect\"\n\n  const DadJokeTool = Tool.make(\"DadJokeTool\", {\n    parameters: { topic: Schema.String },\n    success: Schema.Struct({ joke: Schema.String })\n  })\n\n  const FooTool = Tool.make(\"FooTool\", {\n    parameters: { foo: Schema.Number },\n    success: Schema.Struct({ bar: Schema.Boolean })\n  })\n\n  const MyToolkit = Toolkit.make(DadJokeTool, FooTool)\n\n  const program = Effect.gen(function* () {\n    const response = yield* LanguageModel.generateText({\n      prompt: \"Tell me a dad joke\",\n      toolkit: MyToolkit\n    })\n\n    for (const toolCall of response.toolCalls) {\n      if (toolCall.name === \"DadJokeTool\") {\n        //         ^? \"DadJokeTool\" | \"FooTool\"\n        toolCall.params\n        //       ^? { readonly topic: string }\n      }\n    }\n\n    for (const toolResult of response.toolResults) {\n      if (toolResult.name === \"DadJokeTool\") {\n        //           ^? \"DadJokeTool\" | \"FooTool\"\n        toolResult.result\n        //         ^? { readonly joke: string }\n      }\n    }\n  })\n  ```\n\n  ### Provider Metadata\n\n  As with provider-specific options, provider-specific metadata is now returned as\n  part of the response from the large language model provider.\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n  import { Effect } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const program = Effect.gen(function* () {\n    const response = yield* LanguageModel.generateText({\n      prompt: \"What is the meaning of life?\"\n    })\n\n    for (const part of response.content) {\n      // When metadata **is not** defined for a content part, accessing the\n      // provider's key on the part's metadata will return an untyped record\n      if (part.type === \"text\") {\n        const metadata = part.metadata.anthropic\n        //    ^? { readonly [x: string]: unknown } | undefined\n      }\n      // When metadata **is** defined for a content part, accessing the\n      // provider's key on the part's metadata will return typed metadata\n      if (part.type === \"reasoning\") {\n        const metadata = part.metadata.anthropic\n        //    ^? AnthropicReasoningInfo | undefined\n      }\n    }\n  }).pipe(Effect.provide(Claude))\n  ```\n\n  ## Tool Calls\n\n  The `Tool` module has been enhanced to support provider-defined tools (e.g.\n  web search, computer use, etc.). Large language model providers which support\n  calling their own tools now have a separate module present in their provider\n  integration packages which contain definitions for their tools.\n\n  These provider-defined tools can be included alongside user-defined tools in\n  existing `Toolkit`s. Provider-defined tools that require a user-space handler\n  will be raise a type error in the associated `Toolkit` layer if no such handler\n  is defined.\n\n  ```ts\n  import { LanguageModel, Tool, Toolkit } from \"@effect/ai\"\n  import { AnthropicTool } from \"@effect/ai-anthropic\"\n  import { Schema } from \"effect\"\n\n  const DadJokeTool = Tool.make(\"DadJokeTool\", {\n    parameters: { topic: Schema.String },\n    success: Schema.Struct({ joke: Schema.String })\n  })\n\n  const MyToolkit = Toolkit.make(\n    DadJokeTool,\n    AnthropicTool.WebSearch_20250305({ max_uses: 1 })\n  )\n\n  const program = LanguageModel.generateText({\n    prompt: \"Search the web for a dad joke\",\n    toolkit: MyToolkit\n  })\n  ```\n\n  ## AiError\n\n  The `AiError` type has been refactored into a union of different error types\n  which can be raised by the Effect AI SDK. The goal of defining separate error\n  types is to allow providing the end-user with more granular information about\n  the error that occurred.\n\n  For now, the following errors have been defined. More error types may be added\n  over time based upon necessity / use case.\n\n  ```ts\n  type AiError =\n    | HttpRequestError,\n    | HttpResponseError,\n    | MalformedInput,\n    | MalformedOutput,\n    | UnknownError\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`42b914a`](https://github.com/Effect-TS/effect/commit/42b914a0e8750350ce17d434afaec7d655ddf4b7)]:\n  - @effect/ai@0.27.0\n\n## 0.16.2\n\n### Patch Changes\n\n- [#5476](https://github.com/Effect-TS/effect/pull/5476) [`18ec398`](https://github.com/Effect-TS/effect/commit/18ec39853b493795fd0bff01a67f36e142cb6f4e) Thanks @richburdon! - fix total token count\n\n## 0.16.1\n\n### Patch Changes\n\n- [#5474](https://github.com/Effect-TS/effect/pull/5474) [`5f5ae17`](https://github.com/Effect-TS/effect/commit/5f5ae1730510a372f229426aff832ba1c5c5145b) Thanks @IMax153! - Ensure that the finish part is emitted when streaming text from Anthropic\n\n## 0.16.0\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/ai@0.26.0\n  - @effect/experimental@0.54.6\n\n## 0.15.1\n\n### Patch Changes\n\n- [`4bcf799`](https://github.com/Effect-TS/effect/commit/4bcf799275bfc38932c5c5c5947afc271a283fac) Thanks @dmaretskyi! - Fix tools with no parameters not being called\n\n## 0.15.0\n\n### Patch Changes\n\n- Updated dependencies [[`5a0f4f1`](https://github.com/Effect-TS/effect/commit/5a0f4f176687a39d9fa46bb894bb7ac3175b0e87)]:\n  - effect@3.17.1\n  - @effect/ai@0.25.0\n  - @effect/experimental@0.54.0\n\n## 0.14.0\n\n### Patch Changes\n\n- Updated dependencies [[`7813640`](https://github.com/Effect-TS/effect/commit/7813640279d9e3a3e7fc0a29bfb5c6d5fb3c270f)]:\n  - @effect/platform@0.90.0\n  - @effect/ai@0.24.0\n  - @effect/experimental@0.54.0\n\n## 0.13.0\n\n### Patch Changes\n\n- Updated dependencies [[`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9), [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104), [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63), [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c), [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989), [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636), [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2), [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d)]:\n  - effect@3.17.0\n  - @effect/ai@0.23.0\n  - @effect/experimental@0.53.0\n  - @effect/platform@0.89.0\n\n## 0.12.2\n\n### Patch Changes\n\n- Updated dependencies [[`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec), [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38), [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48)]:\n  - effect@3.16.14\n  - @effect/platform@0.88.1\n  - @effect/experimental@0.52.1\n  - @effect/ai@0.22.1\n\n## 0.12.1\n\n### Patch Changes\n\n- [#5209](https://github.com/Effect-TS/effect/pull/5209) [`3deaa66`](https://github.com/Effect-TS/effect/commit/3deaa66e022e361a2036ce6bfc9d76f77d9cc948) Thanks @tim-smart! - fix ai layerConfig regression, to allow for conditional Config variables\n\n## 0.12.0\n\n### Patch Changes\n\n- Updated dependencies [[`27206d7`](https://github.com/Effect-TS/effect/commit/27206d7f0558d7fe28de57bf54f1d0cc83acc92e), [`dbabf5e`](https://github.com/Effect-TS/effect/commit/dbabf5e76fa63b050d2b6c466713c7dc59f07d3c)]:\n  - @effect/platform@0.88.0\n  - @effect/ai@0.22.0\n  - @effect/experimental@0.52.0\n\n## 0.11.19\n\n### Patch Changes\n\n- Updated dependencies [[`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7), [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db)]:\n  - effect@3.16.13\n  - @effect/ai@0.21.17\n  - @effect/experimental@0.51.14\n  - @effect/platform@0.87.13\n\n## 0.11.18\n\n### Patch Changes\n\n- [#5186](https://github.com/Effect-TS/effect/pull/5186) [`e5692ab`](https://github.com/Effect-TS/effect/commit/e5692ab2be157b885f449ffb5c5f022eca04a59e) Thanks @IMax153! - Do not use `Config.Wrap` for AI provider `layerConfig`\n\n- Updated dependencies [[`32ba77a`](https://github.com/Effect-TS/effect/commit/32ba77ae304d2161362a73e8b61965332626cf2d), [`d5e25b2`](https://github.com/Effect-TS/effect/commit/d5e25b237f05670ee42b386cb40b2cb448fc11d7)]:\n  - @effect/platform@0.87.12\n  - @effect/ai@0.21.16\n  - @effect/experimental@0.51.13\n\n## 0.11.17\n\n### Patch Changes\n\n- Updated dependencies [[`001392b`](https://github.com/Effect-TS/effect/commit/001392ba8bfcad101bb034348a7415012fb12f72), [`7bfb099`](https://github.com/Effect-TS/effect/commit/7bfb099cb5528511b8d63045c4fbb4dc9cb18528)]:\n  - @effect/platform@0.87.11\n  - @effect/ai@0.21.15\n  - @effect/experimental@0.51.12\n\n## 0.11.16\n\n### Patch Changes\n\n- Updated dependencies [[`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0), [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0)]:\n  - @effect/platform@0.87.10\n  - @effect/ai@0.21.14\n  - @effect/experimental@0.51.11\n\n## 0.11.15\n\n### Patch Changes\n\n- Updated dependencies [[`54514a2`](https://github.com/Effect-TS/effect/commit/54514a2f53166de27ad7e756dbf12194691fd4af)]:\n  - @effect/platform@0.87.9\n  - @effect/ai@0.21.13\n  - @effect/experimental@0.51.10\n\n## 0.11.14\n\n### Patch Changes\n\n- Updated dependencies [[`4ce4f82`](https://github.com/Effect-TS/effect/commit/4ce4f824f6fdef492be1d35c05a490ffce518c89)]:\n  - @effect/platform@0.87.8\n  - @effect/experimental@0.51.9\n  - @effect/ai@0.21.12\n\n## 0.11.13\n\n### Patch Changes\n\n- [#5029](https://github.com/Effect-TS/effect/pull/5029) [`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778) Thanks @IMax153! - Cleanup AiLanguageModel construction and finish basic support for gemini\n\n- Updated dependencies [[`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778), [`25ca0cf`](https://github.com/Effect-TS/effect/commit/25ca0cf141139cd44ff53081b1c877f8f3ab5e41), [`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778)]:\n  - @effect/ai@0.21.11\n\n## 0.11.12\n\n### Patch Changes\n\n- Updated dependencies [[`a9b617f`](https://github.com/Effect-TS/effect/commit/a9b617f125171ed76cd79ab46d7a924daf3b0e70), [`7e26e86`](https://github.com/Effect-TS/effect/commit/7e26e86524abcc93713d6ad7eee486638c98f7c2)]:\n  - @effect/platform@0.87.7\n  - @effect/ai@0.21.10\n  - @effect/experimental@0.51.8\n\n## 0.11.11\n\n### Patch Changes\n\n- Updated dependencies [[`030ac21`](https://github.com/Effect-TS/effect/commit/030ac217eac167d345a095bff26d9c95827fa64c), [`905da99`](https://github.com/Effect-TS/effect/commit/905da996aad665057b4ca6dba1a4af44fb8835bd), [`aaae9b1`](https://github.com/Effect-TS/effect/commit/aaae9b10345ab5f867b08e1c6eb21685cfc2b078)]:\n  - @effect/ai@0.21.9\n  - effect@3.16.12\n  - @effect/experimental@0.51.7\n  - @effect/platform@0.87.6\n\n## 0.11.10\n\n### Patch Changes\n\n- Updated dependencies [[`96c1292`](https://github.com/Effect-TS/effect/commit/96c129262835410b311a51d0bf7f58b8f6fc9a12)]:\n  - @effect/experimental@0.51.6\n  - @effect/ai@0.21.8\n\n## 0.11.9\n\n### Patch Changes\n\n- Updated dependencies [[`2fd8676`](https://github.com/Effect-TS/effect/commit/2fd8676c803cd40000dfc3231f5daecaa0e0ebd2)]:\n  - @effect/platform@0.87.5\n  - @effect/ai@0.21.7\n  - @effect/experimental@0.51.5\n\n## 0.11.8\n\n### Patch Changes\n\n- Updated dependencies [[`e82a4fd`](https://github.com/Effect-TS/effect/commit/e82a4fd60f6528d08cef1a4aba0abe0d3ba741ad)]:\n  - @effect/platform@0.87.4\n  - @effect/ai@0.21.6\n  - @effect/experimental@0.51.4\n\n## 0.11.7\n\n### Patch Changes\n\n- Updated dependencies [[`1b6e396`](https://github.com/Effect-TS/effect/commit/1b6e396d699f3cbbc56b68f99055cf746529bb9e)]:\n  - @effect/platform@0.87.3\n  - @effect/ai@0.21.5\n  - @effect/experimental@0.51.3\n\n## 0.11.6\n\n### Patch Changes\n\n- Updated dependencies [[`4fea68c`](https://github.com/Effect-TS/effect/commit/4fea68ca7a25a3c39a1ab68b3885534513ab0c81), [`b927954`](https://github.com/Effect-TS/effect/commit/b9279543cf5688dd8a577af80456959c615217d0), [`99590a6`](https://github.com/Effect-TS/effect/commit/99590a6ca9128eb1ede265b6670b655311995614), [`6c3e24c`](https://github.com/Effect-TS/effect/commit/6c3e24c2308f7d4a29b8f4270ab81bca22ac6bb4)]:\n  - @effect/platform@0.87.2\n  - effect@3.16.11\n  - @effect/ai@0.21.4\n  - @effect/experimental@0.51.2\n\n## 0.11.5\n\n### Patch Changes\n\n- [#5121](https://github.com/Effect-TS/effect/pull/5121) [`8e3c565`](https://github.com/Effect-TS/effect/commit/8e3c565aad2b888badb0b62f109d9b4ec4049305) Thanks @IMax153! - Fix several issues in the generated OpenAPI models for the Anthropic AI provider\n  package.\n\n  The OpenAPI specification that Anthropic maintains for its API is apparently\n  [incorrect](https://github.com/anthropics/anthropic-sdk-typescript/issues/605).\n  Some properties which are marked as nullable but required are sometimes not\n  returned by the API. This fixes the schemas associated with some of those\n  properties, though others may exist / be found that require manual adjustment.\n\n## 0.11.4\n\n### Patch Changes\n\n- [#5020](https://github.com/Effect-TS/effect/pull/5020) [`530aa65`](https://github.com/Effect-TS/effect/commit/530aa6561b68ea591cef44e30e8629082e42fda2) Thanks @IMax153! - add Amazon Bedrock AI provider package\n\n## 0.11.3\n\n### Patch Changes\n\n- Updated dependencies [[`faad30e`](https://github.com/Effect-TS/effect/commit/faad30ec8742916be59f9db642d0fc98225b636c)]:\n  - effect@3.16.10\n  - @effect/ai@0.21.3\n  - @effect/experimental@0.51.1\n  - @effect/platform@0.87.1\n\n## 0.11.2\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/ai@0.21.2\n  - @effect/experimental@0.51.0\n\n## 0.11.1\n\n### Patch Changes\n\n- Updated dependencies [[`f667373`](https://github.com/Effect-TS/effect/commit/f667373da3471f1e907366780f8c3ea7f52cc5c8)]:\n  - @effect/ai@0.21.1\n  - @effect/experimental@0.51.0\n\n## 0.11.0\n\n### Patch Changes\n\n- Updated dependencies [[`b5bac9a`](https://github.com/Effect-TS/effect/commit/b5bac9ac2913fcd11b02322624f03b544eef53ba)]:\n  - @effect/platform@0.87.0\n  - @effect/ai@0.21.0\n  - @effect/experimental@0.51.0\n\n## 0.10.0\n\n### Patch Changes\n\n- Updated dependencies [[`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`c23d25c`](https://github.com/Effect-TS/effect/commit/c23d25c3e7c541f1f63b28484d8c461d86c67e99), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07)]:\n  - effect@3.16.9\n  - @effect/platform@0.86.0\n  - @effect/ai@0.20.0\n  - @effect/experimental@0.50.0\n\n## 0.9.5\n\n### Patch Changes\n\n- Updated dependencies [[`a8d99b2`](https://github.com/Effect-TS/effect/commit/a8d99b2ec2f55d9aa6e7d00a5138e80380716877)]:\n  - @effect/ai@0.19.4\n  - @effect/experimental@0.49.2\n\n## 0.9.4\n\n### Patch Changes\n\n- Updated dependencies [[`914a191`](https://github.com/Effect-TS/effect/commit/914a191e7cb6341a3d0e965bccd27c336cf22e44)]:\n  - @effect/platform@0.85.2\n  - @effect/ai@0.19.3\n  - @effect/experimental@0.49.2\n\n## 0.9.3\n\n### Patch Changes\n\n- [#5051](https://github.com/Effect-TS/effect/pull/5051) [`0945c0d`](https://github.com/Effect-TS/effect/commit/0945c0d0a20df456c0b0ec53f5e7487480aa62e1) Thanks @IMax153! - Fix the generated Anthropic OpenAPI schemas\n\n## 0.9.2\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/ai@0.19.2\n  - @effect/experimental@0.49.1\n\n## 0.9.1\n\n### Patch Changes\n\n- Updated dependencies [[`8cb98d5`](https://github.com/Effect-TS/effect/commit/8cb98d53e68330228287ce2a2e0d8a4c86bcab3b), [`db2dd3c`](https://github.com/Effect-TS/effect/commit/db2dd3c3a8a77d791eae19e66153527e1cde4e6e)]:\n  - effect@3.16.8\n  - @effect/ai@0.19.1\n  - @effect/experimental@0.49.1\n  - @effect/platform@0.85.1\n\n## 0.9.0\n\n### Patch Changes\n\n- Updated dependencies [[`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e)]:\n  - @effect/platform@0.85.0\n  - @effect/ai@0.19.0\n  - @effect/experimental@0.49.0\n\n## 0.8.16\n\n### Patch Changes\n\n- Updated dependencies [[`daed158`](https://github.com/Effect-TS/effect/commit/daed158f2cf00175633284f075cf611c52aa2a1c)]:\n  - @effect/ai@0.18.16\n\n## 0.8.15\n\n### Patch Changes\n\n- Updated dependencies [[`c315989`](https://github.com/Effect-TS/effect/commit/c315989cade6c2a5c9cb157ad85f56b492675add)]:\n  - @effect/ai@0.18.15\n\n## 0.8.14\n\n### Patch Changes\n\n- Updated dependencies [[`1bb0d8a`](https://github.com/Effect-TS/effect/commit/1bb0d8ab96782e99434356266b38251554ea0294), [`cbac1ac`](https://github.com/Effect-TS/effect/commit/cbac1ac61a4e15ad15828563b39eef412bcee66e), [`dd4d380`](https://github.com/Effect-TS/effect/commit/dd4d3802f714d59171b1e9226a7babf9723ea952)]:\n  - effect@3.16.7\n  - @effect/ai@0.18.14\n  - @effect/experimental@0.48.12\n  - @effect/platform@0.84.11\n\n## 0.8.13\n\n### Patch Changes\n\n- Updated dependencies [[`a5f7595`](https://github.com/Effect-TS/effect/commit/a5f75956ef9a15a83c416517ef493f0ee2f5ee8a), [`a02470c`](https://github.com/Effect-TS/effect/commit/a02470c75579e91525a25adb3f21b3650d042fdd), [`aa3a819`](https://github.com/Effect-TS/effect/commit/aa3a819707c15dd39b6d9ae4b4293bd87b74e175), [`bf369b2`](https://github.com/Effect-TS/effect/commit/bf369b2902a0e0b195d957c18b9efd180942cf8b), [`f891d45`](https://github.com/Effect-TS/effect/commit/f891d45adffdafd3f94a2eca23faa354e3a409a8)]:\n  - effect@3.16.6\n  - @effect/ai@0.18.13\n  - @effect/platform@0.84.10\n  - @effect/experimental@0.48.11\n\n## 0.8.12\n\n### Patch Changes\n\n- Updated dependencies [[`bf418ef`](https://github.com/Effect-TS/effect/commit/bf418ef14a0f2ec965535793d5cea8fa8ba177ac)]:\n  - effect@3.16.5\n  - @effect/ai@0.18.12\n  - @effect/experimental@0.48.10\n  - @effect/platform@0.84.9\n\n## 0.8.11\n\n### Patch Changes\n\n- Updated dependencies [[`2dc5f93`](https://github.com/Effect-TS/effect/commit/2dc5f932f89d260e2f6139c9b89e0548d11d94c2)]:\n  - @effect/ai@0.18.11\n  - @effect/experimental@0.48.9\n\n## 0.8.10\n\n### Patch Changes\n\n- Updated dependencies [[`8b9db77`](https://github.com/Effect-TS/effect/commit/8b9db7742846af0f58fd8e8b7acb7f4f5ff487ec)]:\n  - @effect/platform@0.84.8\n  - @effect/experimental@0.48.9\n  - @effect/ai@0.18.10\n\n## 0.8.9\n\n### Patch Changes\n\n- Updated dependencies [[`74ab9a0`](https://github.com/Effect-TS/effect/commit/74ab9a0a9e16d6e019369d256e1e24175c8bc3f3), [`770008e`](https://github.com/Effect-TS/effect/commit/770008eca3aad2899a2ed951236e575793294b28)]:\n  - effect@3.16.4\n  - @effect/ai@0.18.9\n  - @effect/experimental@0.48.8\n  - @effect/platform@0.84.7\n\n## 0.8.8\n\n### Patch Changes\n\n- Updated dependencies [[`a2d57c9`](https://github.com/Effect-TS/effect/commit/a2d57c9ac596445009ca12859b78e00e5d89b936)]:\n  - @effect/experimental@0.48.7\n  - @effect/ai@0.18.8\n\n## 0.8.7\n\n### Patch Changes\n\n- Updated dependencies [[`ceea77a`](https://github.com/Effect-TS/effect/commit/ceea77a13055f145520f763e3fce5b8ff15d728f)]:\n  - @effect/platform@0.84.6\n  - @effect/ai@0.18.7\n  - @effect/experimental@0.48.6\n\n## 0.8.6\n\n### Patch Changes\n\n- Updated dependencies [[`85f54ed`](https://github.com/Effect-TS/effect/commit/85f54ed1ecf2f191de8c907247066e3631b5d7e1), [`ec52c6a`](https://github.com/Effect-TS/effect/commit/ec52c6a2211e76972462b15b9d5a9d6d56761b7a)]:\n  - @effect/ai@0.18.6\n  - @effect/platform@0.84.5\n  - @effect/experimental@0.48.5\n\n## 0.8.5\n\n### Patch Changes\n\n- Updated dependencies [[`4ddb28d`](https://github.com/Effect-TS/effect/commit/4ddb28d230d572735fe34539c1c59005d4932d8a)]:\n  - @effect/ai@0.18.5\n\n## 0.8.4\n\n### Patch Changes\n\n- Updated dependencies [[`87722fc`](https://github.com/Effect-TS/effect/commit/87722fce693a9b49284bbddbf82d30714c688261), [`36217ee`](https://github.com/Effect-TS/effect/commit/36217eeb1337edd9ac3f9a635b80a6385d22ae8f)]:\n  - effect@3.16.3\n  - @effect/ai@0.18.4\n  - @effect/experimental@0.48.4\n  - @effect/platform@0.84.4\n\n## 0.8.3\n\n### Patch Changes\n\n- Updated dependencies [[`52c88c4`](https://github.com/Effect-TS/effect/commit/52c88c4b7d20ea819b9f2efaf112d03de0a4627b), [`ab7684f`](https://github.com/Effect-TS/effect/commit/ab7684f1c2a0671bf091f255d220e3a4cc7f528e)]:\n  - @effect/ai@0.18.3\n  - @effect/platform@0.84.3\n  - @effect/experimental@0.48.3\n\n## 0.8.2\n\n### Patch Changes\n\n- Updated dependencies [[`0ddf148`](https://github.com/Effect-TS/effect/commit/0ddf148a247aa87af043d276b8453a714a400897)]:\n  - effect@3.16.2\n  - @effect/ai@0.18.2\n  - @effect/experimental@0.48.2\n  - @effect/platform@0.84.2\n\n## 0.8.1\n\n### Patch Changes\n\n- Updated dependencies [[`71174d0`](https://github.com/Effect-TS/effect/commit/71174d09691314a9b6b66189e456fd21e3eb6543), [`d615e6e`](https://github.com/Effect-TS/effect/commit/d615e6e5b944f6fd5e627e31752c7ca7e4e1c17d)]:\n  - @effect/platform@0.84.1\n  - effect@3.16.1\n  - @effect/ai@0.18.1\n  - @effect/experimental@0.48.1\n\n## 0.8.0\n\n### Minor Changes\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`0552674`](https://github.com/Effect-TS/effect/commit/055267461a3076b06dea896258f4bb2154211fcb) Thanks @IMax153! - Make `AiModel` a plain `Layer` and remove `AiPlan` in favor of `ExecutionPlan`\n\n  This release substantially simplifies and improves the ergonomics of using `AiModel` for various providers. With these changes, an `AiModel` now returns a plain `Layer` which can be used to provide services to a program that interacts with large language models.\n\n  **Before**\n\n  ```ts\n  import { AiLanguageModel } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { NodeHttpClient } from \"@effect/platform-node\"\n  import { Config, Console, Effect, Layer } from \"effect\"\n\n  // Produces an `AiModel<AiLanguageModel, OpenAiClient>`\n  const Gpt4o = OpenAiLanguageModel.model(\"gpt-4o\")\n\n  // Generate a dad joke\n  const getDadJoke = AiLanguageModel.generateText({\n    prompt: \"Tell me a dad joke\"\n  })\n\n  const program = Effect.gen(function* () {\n    // Build the `AiModel` into a `Provider`\n    const gpt4o = yield* Gpt4o\n    // Use the built `AiModel` to run the program\n    const response = yield* gpt4o.use(getDadJoke)\n    // Log the response\n    yield* Console.log(response.text)\n  })\n\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(Effect.provide(OpenAi), Effect.runPromise)\n  ```\n\n  **After**\n\n  ```ts\n  import { AiLanguageModel } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { NodeHttpClient } from \"@effect/platform-node\"\n  import { Config, Console, Effect, Layer } from \"effect\"\n\n  // Produces a `Layer<AiLanguageModel, never, OpenAiClient>`\n  const Gpt4o = OpenAiLanguageModel.model(\"gpt-4o\")\n\n  const program = Effect.gen(function*() {\n    // Generate a dad joke\n    const response = yield* AiLanguageModel.generateText({\n      prompt: \"Tell me a dad joke\"\n    })\n    // Log the response\n    yield* Console.log(response.text)\n  ).pipe(Effect.provide(Gpt4o))\n\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(\n    Effect.provide(OpenAi),\n    Effect.runPromise\n  )\n  ```\n\n  In addition, `AiModel` can be `yield*`'ed to produce a layer with no requirements.\n\n  This shifts the requirements of building the layer into the calling effect, which is particularly useful for creating AI-powered services.\n\n  ```ts\n  import { AiLanguageModel } from \"@effect/ai\"\n  import { OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { Effect } from \"effect\"\n\n  class DadJokes extends Effect.Service<DadJokes>()(\"DadJokes\", {\n    effect: Effect.gen(function* () {\n      // Yielding the model will return a layer with no requirements\n      //\n      //      ┌─── Layer<AiLanguageModel>\n      //      ▼\n      const model = yield* OpenAiLanguageModel.model(\"gpt-4o\")\n\n      const getDadJoke = AiLanguageModel.generateText({\n        prompt: \"Generate a dad joke\"\n      }).pipe(Effect.provide(model))\n\n      return { getDadJoke } as const\n    })\n  }) {}\n\n  // The requirements are lifted into the service constructor\n  //\n  //          ┌─── Layer<DadJokes, never, OpenAiClient>\n  //          ▼\n  DadJokes.Default\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`ee0bd5d`](https://github.com/Effect-TS/effect/commit/ee0bd5d24864752c54cb359f67a67dd903971ec4), [`5189800`](https://github.com/Effect-TS/effect/commit/51898004e11766b8cf6d95e960b636f6d5db79ec), [`58bfeaa`](https://github.com/Effect-TS/effect/commit/58bfeaa64ded8c88f772b184311c0c0dbac10960), [`194d748`](https://github.com/Effect-TS/effect/commit/194d7486943f56f3267ef415395ac220a4b3e634), [`0552674`](https://github.com/Effect-TS/effect/commit/055267461a3076b06dea896258f4bb2154211fcb), [`918c9ea`](https://github.com/Effect-TS/effect/commit/918c9ea1a57facb154f0fb26792021f337054dee), [`9198e6f`](https://github.com/Effect-TS/effect/commit/9198e6fcc1a3ff4fefb3363004de558d8de01f40), [`2a370bf`](https://github.com/Effect-TS/effect/commit/2a370bf625fdeede5659721468eb0d527e403279), [`58ccb91`](https://github.com/Effect-TS/effect/commit/58ccb91328c8df5d49808b673738bc09df355201), [`fd47834`](https://github.com/Effect-TS/effect/commit/fd478348203fa89462b0a1d067ce4de034353df4)]:\n  - effect@3.16.0\n  - @effect/ai@0.18.0\n  - @effect/experimental@0.48.0\n  - @effect/platform@0.84.0\n\n## 0.7.0\n\n### Patch Changes\n\n- Updated dependencies [[`5522520`](https://github.com/Effect-TS/effect/commit/55225206ab9af0ad60b1c0654690a8a096d625cd), [`cc5bb2b`](https://github.com/Effect-TS/effect/commit/cc5bb2b918a9450a975f702dabcea891bda382cb)]:\n  - @effect/platform@0.83.0\n  - effect@3.15.5\n  - @effect/ai@0.17.0\n  - @effect/experimental@0.47.0\n\n## 0.6.9\n\n### Patch Changes\n\n- Updated dependencies [[`0617b9d`](https://github.com/Effect-TS/effect/commit/0617b9dc365f1963b36949ad7f9023ab6eb94524)]:\n  - @effect/platform@0.82.8\n  - @effect/ai@0.16.9\n  - @effect/experimental@0.46.8\n\n## 0.6.8\n\n### Patch Changes\n\n- Updated dependencies [[`f570554`](https://github.com/Effect-TS/effect/commit/f57055459524587b041340577dad85476bb35f81), [`78047e8`](https://github.com/Effect-TS/effect/commit/78047e8dfc8005b66f87afe50bb95981fea51561), [`c20b95a`](https://github.com/Effect-TS/effect/commit/c20b95a99ffe452b4774c844d397a905f713b6d6), [`94ada43`](https://github.com/Effect-TS/effect/commit/94ada430928d5685bdbef513e87562c20774a3a2)]:\n  - effect@3.15.4\n  - @effect/platform@0.82.7\n  - @effect/ai@0.16.8\n  - @effect/experimental@0.46.7\n\n## 0.6.7\n\n### Patch Changes\n\n- Updated dependencies [[`618903b`](https://github.com/Effect-TS/effect/commit/618903ba9ae96e2bfe6ee31f61c4359b915f2a36)]:\n  - @effect/platform@0.82.6\n  - @effect/ai@0.16.7\n  - @effect/experimental@0.46.6\n\n## 0.6.6\n\n### Patch Changes\n\n- Updated dependencies [[`7764a07`](https://github.com/Effect-TS/effect/commit/7764a07d960c60df81f14e1dc949518f4bbe494a), [`4577f54`](https://github.com/Effect-TS/effect/commit/4577f548d67273e576cdde423bdd34a4b910766a), [`30a0d9c`](https://github.com/Effect-TS/effect/commit/30a0d9cb51c84290d51b1361d72ff5cee33c13c7)]:\n  - @effect/platform@0.82.5\n  - effect@3.15.3\n  - @effect/ai@0.16.6\n  - @effect/experimental@0.46.5\n\n## 0.6.5\n\n### Patch Changes\n\n- [#4899](https://github.com/Effect-TS/effect/pull/4899) [`0a8c0e7`](https://github.com/Effect-TS/effect/commit/0a8c0e762af96d5dbf323d495a06647f39797674) Thanks @alex-dixon! - fix: anthropic tag name\n\n- Updated dependencies [[`d45e8a8`](https://github.com/Effect-TS/effect/commit/d45e8a8ac8227192f504e39e6d04fdcf4fb1d225), [`d13b68e`](https://github.com/Effect-TS/effect/commit/d13b68e3a9456d0bfee9bca8273a7b44a9c69087)]:\n  - @effect/platform@0.82.4\n  - @effect/ai@0.16.5\n  - @effect/experimental@0.46.4\n\n## 0.6.4\n\n### Patch Changes\n\n- Updated dependencies [[`b8722b8`](https://github.com/Effect-TS/effect/commit/b8722b817e2306fe8c8245f3f9e32d85b824b961), [`a328f4b`](https://github.com/Effect-TS/effect/commit/a328f4b4fe717dd53e5b04a30f387433c32f7328)]:\n  - effect@3.15.2\n  - @effect/platform@0.82.3\n  - @effect/ai@0.16.4\n  - @effect/experimental@0.46.3\n\n## 0.6.3\n\n### Patch Changes\n\n- Updated dependencies [[`739a3d4`](https://github.com/Effect-TS/effect/commit/739a3d4a4565915fe2e690003f4f9085cb4422fc)]:\n  - @effect/platform@0.82.2\n  - @effect/ai@0.16.3\n  - @effect/experimental@0.46.2\n\n## 0.6.2\n\n### Patch Changes\n\n- Updated dependencies [[`787ce70`](https://github.com/Effect-TS/effect/commit/787ce7042e35b657963473c6efe47752868cd811), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348)]:\n  - effect@3.15.1\n  - @effect/ai@0.16.2\n  - @effect/experimental@0.46.1\n  - @effect/platform@0.82.1\n\n## 0.6.1\n\n### Patch Changes\n\n- Updated dependencies [[`cb3c30f`](https://github.com/Effect-TS/effect/commit/cb3c30f540a83dafcd6d841375073b5e069fa417)]:\n  - @effect/ai@0.16.1\n  - @effect/experimental@0.46.0\n\n## 0.6.0\n\n### Patch Changes\n\n- Updated dependencies [[`c654595`](https://github.com/Effect-TS/effect/commit/c65459587b51da140b78098e81fdbfece65d53e2), [`d9f5dea`](https://github.com/Effect-TS/effect/commit/d9f5deae0f02f5de2b9fcb1cca8b142ba4bc2bba), [`49aa723`](https://github.com/Effect-TS/effect/commit/49aa7236a15e13f818c86edbca08c4af67c8dfaf), [`74c14d0`](https://github.com/Effect-TS/effect/commit/74c14d01d0cb48cf517a1b6e29a373a96ed0ff5b), [`e4f49b6`](https://github.com/Effect-TS/effect/commit/e4f49b66857e01b74ab6a9a0bc7132f44cd04cbb), [`6f02224`](https://github.com/Effect-TS/effect/commit/6f02224b3fc46a682ad2defb1a260841956c6780), [`1dcfd41`](https://github.com/Effect-TS/effect/commit/1dcfd41ff96abd706901293a00c1893cb29dd8fd), [`b21ab16`](https://github.com/Effect-TS/effect/commit/b21ab16b6f773e7ec4369db4e752c35e719f7870), [`fcf1822`](https://github.com/Effect-TS/effect/commit/fcf1822f98fcda60351d64e9d2c2c13563d7e6db), [`0061dd1`](https://github.com/Effect-TS/effect/commit/0061dd140740165e91569a684cce27a77b23229e), [`8421e6e`](https://github.com/Effect-TS/effect/commit/8421e6e49332bca8f96f482dfd48680e238b3a89), [`a9b3fb7`](https://github.com/Effect-TS/effect/commit/a9b3fb78abcfdb525318a956fd02fcadeb56143e), [`fa10f56`](https://github.com/Effect-TS/effect/commit/fa10f56b96bd9af070ba99ebc3279aa93954261e)]:\n  - effect@3.15.0\n  - @effect/platform@0.82.0\n  - @effect/ai@0.16.0\n  - @effect/experimental@0.46.0\n\n## 0.5.0\n\n### Minor Changes\n\n- [#4766](https://github.com/Effect-TS/effect/pull/4766) [`a4d42c5`](https://github.com/Effect-TS/effect/commit/a4d42c55669eff56963d06323d155a5bf3082a70) Thanks @IMax153! - Refactor `@effect/ai-anthropic` to align with changes to `@effect/ai`\n\n### Patch Changes\n\n- Updated dependencies [[`a4d42c5`](https://github.com/Effect-TS/effect/commit/a4d42c55669eff56963d06323d155a5bf3082a70)]:\n  - @effect/ai@0.15.0\n  - @effect/experimental@0.45.1\n\n## 0.4.1\n\n### Patch Changes\n\n- Updated dependencies [[`24a9ebb`](https://github.com/Effect-TS/effect/commit/24a9ebbb5af598f0bfd6ecc45307e528043fe011)]:\n  - effect@3.14.22\n  - @effect/ai@0.14.1\n  - @effect/experimental@0.45.1\n  - @effect/platform@0.81.1\n\n## 0.4.0\n\n### Patch Changes\n\n- Updated dependencies [[`672920f`](https://github.com/Effect-TS/effect/commit/672920f85da8abd5f9d4ad85e29248a2aca57ed8)]:\n  - @effect/platform@0.81.0\n  - @effect/ai@0.14.0\n  - @effect/experimental@0.45.0\n\n## 0.3.22\n\n### Patch Changes\n\n- Updated dependencies [[`2f3b7d4`](https://github.com/Effect-TS/effect/commit/2f3b7d4e1fa1ef8790b0ca4da22eb88872ee31df)]:\n  - effect@3.14.21\n  - @effect/ai@0.13.21\n  - @effect/experimental@0.44.21\n  - @effect/platform@0.80.21\n\n## 0.3.21\n\n### Patch Changes\n\n- Updated dependencies [[`17e2f30`](https://github.com/Effect-TS/effect/commit/17e2f3091408cf0fca9414d4af3bdf7b2765b378)]:\n  - effect@3.14.20\n  - @effect/ai@0.13.20\n  - @effect/experimental@0.44.20\n  - @effect/platform@0.80.20\n\n## 0.3.20\n\n### Patch Changes\n\n- Updated dependencies [[`056a910`](https://github.com/Effect-TS/effect/commit/056a910d0a0b8b00b0dc9df4a070466b2b5c2f6c), [`e25e7bb`](https://github.com/Effect-TS/effect/commit/e25e7bbc1797733916f48f501425d9f2ef310d9f), [`3273d57`](https://github.com/Effect-TS/effect/commit/3273d572c2b3175a842677f19efeea4cd65ab016)]:\n  - effect@3.14.19\n  - @effect/platform@0.80.19\n  - @effect/ai@0.13.19\n  - @effect/experimental@0.44.19\n\n## 0.3.19\n\n### Patch Changes\n\n- Updated dependencies [[`b1164d4`](https://github.com/Effect-TS/effect/commit/b1164d49a1dfdf299e9971367b6fc6be4df0ddff)]:\n  - effect@3.14.18\n  - @effect/ai@0.13.18\n  - @effect/experimental@0.44.18\n  - @effect/platform@0.80.18\n\n## 0.3.18\n\n### Patch Changes\n\n- Updated dependencies [[`0b54681`](https://github.com/Effect-TS/effect/commit/0b54681cd89245e211d8f49272be0f1bf2f81813), [`41a59d5`](https://github.com/Effect-TS/effect/commit/41a59d5916a296b12b0d5ead9e859e05f40b4cce)]:\n  - effect@3.14.17\n  - @effect/ai@0.13.17\n  - @effect/experimental@0.44.17\n  - @effect/platform@0.80.17\n\n## 0.3.17\n\n### Patch Changes\n\n- Updated dependencies [[`ee14444`](https://github.com/Effect-TS/effect/commit/ee144441021ec77039e43396eaf90714687bb495), [`f1c8583`](https://github.com/Effect-TS/effect/commit/f1c8583f8c3ea9415f813795ca2940a897c9ba9a)]:\n  - effect@3.14.16\n  - @effect/platform@0.80.16\n  - @effect/ai@0.13.16\n  - @effect/experimental@0.44.16\n\n## 0.3.16\n\n### Patch Changes\n\n- Updated dependencies [[`239cc99`](https://github.com/Effect-TS/effect/commit/239cc995ce645946210a3c3d2cb52bd3547c0687), [`8b6c947`](https://github.com/Effect-TS/effect/commit/8b6c947eaa8e45a67ecb3c37d45cd27f3e41d165), [`c50a63b`](https://github.com/Effect-TS/effect/commit/c50a63bbecb9f560b9cae349c447eed877d1b9b6)]:\n  - effect@3.14.15\n  - @effect/ai@0.13.15\n  - @effect/experimental@0.44.15\n  - @effect/platform@0.80.15\n\n## 0.3.15\n\n### Patch Changes\n\n- Updated dependencies [[`6ed8d15`](https://github.com/Effect-TS/effect/commit/6ed8d1589beb181d30abc79afebdaabc1d101538)]:\n  - effect@3.14.14\n  - @effect/ai@0.13.14\n  - @effect/experimental@0.44.14\n  - @effect/platform@0.80.14\n\n## 0.3.14\n\n### Patch Changes\n\n- Updated dependencies [[`ee77788`](https://github.com/Effect-TS/effect/commit/ee77788747e7ebbde6bfa88256cde49dbbad3608), [`5fce6ba`](https://github.com/Effect-TS/effect/commit/5fce6ba19c3cc63cc0104e737e581ad989dedbf0), [`570e45f`](https://github.com/Effect-TS/effect/commit/570e45f8cb936e42ec48f67f21bb2b7252f36c0c)]:\n  - effect@3.14.13\n  - @effect/ai@0.13.13\n  - @effect/experimental@0.44.13\n  - @effect/platform@0.80.13\n\n## 0.3.13\n\n### Patch Changes\n\n- Updated dependencies [[`c2ad9ee`](https://github.com/Effect-TS/effect/commit/c2ad9ee9f3c4c743390edf35ed9e85a20be33811), [`9c68654`](https://github.com/Effect-TS/effect/commit/9c686542b6eb3ea188cb70673ef2e41223633e89)]:\n  - effect@3.14.12\n  - @effect/ai@0.13.12\n  - @effect/experimental@0.44.12\n  - @effect/platform@0.80.12\n\n## 0.3.12\n\n### Patch Changes\n\n- Updated dependencies [[`e536127`](https://github.com/Effect-TS/effect/commit/e536127c1e6f2fb3a542c73ae919435a629a346b)]:\n  - effect@3.14.11\n  - @effect/ai@0.13.11\n  - @effect/experimental@0.44.11\n  - @effect/platform@0.80.11\n\n## 0.3.11\n\n### Patch Changes\n\n- Updated dependencies [[`bc7efa3`](https://github.com/Effect-TS/effect/commit/bc7efa3b031bb25e1ed3c8f2d3fb5e8da166cadc)]:\n  - effect@3.14.10\n  - @effect/ai@0.13.10\n  - @effect/experimental@0.44.10\n  - @effect/platform@0.80.10\n\n## 0.3.10\n\n### Patch Changes\n\n- Updated dependencies [[`d78249f`](https://github.com/Effect-TS/effect/commit/d78249f0b67f63cf4baf806ff090cba33293daf0)]:\n  - effect@3.14.9\n  - @effect/ai@0.13.9\n  - @effect/experimental@0.44.9\n  - @effect/platform@0.80.9\n\n## 0.3.9\n\n### Patch Changes\n\n- [#4726](https://github.com/Effect-TS/effect/pull/4726) [`b8b0703`](https://github.com/Effect-TS/effect/commit/b8b070382b3290eff922b76125f0d06732b74155) Thanks @dearlordylord! - AnthropicClient.layerConfig has the same ROut as AnthropicClient.layer - specifically, AiModels.AiModels was missing\n\n## 0.3.8\n\n### Patch Changes\n\n- Updated dependencies [[`b3a2d32`](https://github.com/Effect-TS/effect/commit/b3a2d32772e6f7f20eacf2e18128e99324c4d378)]:\n  - effect@3.14.8\n  - @effect/ai@0.13.8\n  - @effect/experimental@0.44.8\n  - @effect/platform@0.80.8\n\n## 0.3.7\n\n### Patch Changes\n\n- Updated dependencies [[`b542a4b`](https://github.com/Effect-TS/effect/commit/b542a4bf195be0c9af1523e1ba96c953decc4d25)]:\n  - effect@3.14.7\n  - @effect/ai@0.13.7\n  - @effect/experimental@0.44.7\n  - @effect/platform@0.80.7\n\n## 0.3.6\n\n### Patch Changes\n\n- Updated dependencies [[`47618c1`](https://github.com/Effect-TS/effect/commit/47618c1ad84ebcc5a51133a3fff5aa5012d49d45), [`6077882`](https://github.com/Effect-TS/effect/commit/60778824a4794336c33807801f813f8751d1c7e4)]:\n  - effect@3.14.6\n  - @effect/ai@0.13.6\n  - @effect/experimental@0.44.6\n  - @effect/platform@0.80.6\n\n## 0.3.5\n\n### Patch Changes\n\n- Updated dependencies [[`40dbfef`](https://github.com/Effect-TS/effect/commit/40dbfeff239b6e567706752114f31b2fce7de4e3), [`85fba81`](https://github.com/Effect-TS/effect/commit/85fba815ac07eb13d4227a69ac76a18e4b94df18), [`5a5ebdd`](https://github.com/Effect-TS/effect/commit/5a5ebdddfaddd259538b4599a6676281faca778e)]:\n  - effect@3.14.5\n  - @effect/platform@0.80.5\n  - @effect/ai@0.13.5\n  - @effect/experimental@0.44.5\n\n## 0.3.4\n\n### Patch Changes\n\n- Updated dependencies [[`e4ba2c6`](https://github.com/Effect-TS/effect/commit/e4ba2c66a878e81b5e295d6d49aaf724b80a28ef)]:\n  - effect@3.14.4\n  - @effect/ai@0.13.4\n  - @effect/experimental@0.44.4\n  - @effect/platform@0.80.4\n\n## 0.3.3\n\n### Patch Changes\n\n- Updated dependencies [[`37aa8e1`](https://github.com/Effect-TS/effect/commit/37aa8e137725a902e70cd1e468ea98b873aa5056), [`34f03d6`](https://github.com/Effect-TS/effect/commit/34f03d66875f21f266f102223a03cd14c2ed6ea6)]:\n  - effect@3.14.3\n  - @effect/ai@0.13.3\n  - @effect/experimental@0.44.3\n  - @effect/platform@0.80.3\n\n## 0.3.2\n\n### Patch Changes\n\n- Updated dependencies [[`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`0a3e3e1`](https://github.com/Effect-TS/effect/commit/0a3e3e18eea5e0d1882f1a6c906198e6ef226a41)]:\n  - effect@3.14.2\n  - @effect/ai@0.13.2\n  - @effect/experimental@0.44.2\n  - @effect/platform@0.80.2\n\n## 0.3.1\n\n### Patch Changes\n\n- Updated dependencies [[`4a274fe`](https://github.com/Effect-TS/effect/commit/4a274fe9f623182b6b902827e0e83bd89ca3b05c)]:\n  - effect@3.14.1\n  - @effect/ai@0.13.1\n  - @effect/experimental@0.44.1\n  - @effect/platform@0.80.1\n\n## 0.3.0\n\n### Patch Changes\n\n- Updated dependencies [[`1f47e4e`](https://github.com/Effect-TS/effect/commit/1f47e4e12546ab691b29bfb7b5128bb17b93baa5), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`3131f8f`](https://github.com/Effect-TS/effect/commit/3131f8fd12ba9eb31b90fa2f42bf88b12309133c), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`04dff2d`](https://github.com/Effect-TS/effect/commit/04dff2d01ac68c260f29a6d4743381825c353c86), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`c7fac0c`](https://github.com/Effect-TS/effect/commit/c7fac0cd7eadcd5cc0c3a987051c5b57ad271638), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`ffaa3f3`](https://github.com/Effect-TS/effect/commit/ffaa3f3969df26610fcc02ad537340641d44e803), [`ab957c1`](https://github.com/Effect-TS/effect/commit/ab957c1fee714868f56c7ab4e802b9d449e9b666), [`35db9ce`](https://github.com/Effect-TS/effect/commit/35db9ce228f1416c8abacc6dc9c36fbd0f33ef0f), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`cf77ea9`](https://github.com/Effect-TS/effect/commit/cf77ea9ab4fc89e66a43f682a9926ccdee6c57ed), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`baaab60`](https://github.com/Effect-TS/effect/commit/baaab60b737f35dfab8e4a21bce28a195d19e899)]:\n  - effect@3.14.0\n  - @effect/experimental@0.44.0\n  - @effect/platform@0.80.0\n  - @effect/ai@0.13.0\n\n## 0.2.4\n\n### Patch Changes\n\n- [#4592](https://github.com/Effect-TS/effect/pull/4592) [`5662363`](https://github.com/Effect-TS/effect/commit/566236361e270e575ef1cbf308ad1967c82a362c) Thanks @tim-smart! - update generated ai clients\n\n- Updated dependencies [[`5662363`](https://github.com/Effect-TS/effect/commit/566236361e270e575ef1cbf308ad1967c82a362c), [`5f1fd15`](https://github.com/Effect-TS/effect/commit/5f1fd15308ab154791580059b89877d19a2055c2), [`8bb1460`](https://github.com/Effect-TS/effect/commit/8bb1460c824f66f0f25ebd899c5e74e388089c37)]:\n  - @effect/platform@0.79.4\n  - @effect/ai@0.12.4\n  - @effect/experimental@0.43.4\n\n## 0.2.3\n\n### Patch Changes\n\n- Updated dependencies [[`0c4803f`](https://github.com/Effect-TS/effect/commit/0c4803fcc69262d11a97ce49d0e9b4288df0651f), [`6f65ac4`](https://github.com/Effect-TS/effect/commit/6f65ac4eac1489cd6ea390e18b0908670722adad)]:\n  - effect@3.13.12\n  - @effect/ai@0.12.3\n  - @effect/experimental@0.43.3\n  - @effect/platform@0.79.3\n\n## 0.2.2\n\n### Patch Changes\n\n- Updated dependencies [[`fad8cca`](https://github.com/Effect-TS/effect/commit/fad8cca9bbfcc2eaeb44b97c15dbe0a1eda75315), [`4296293`](https://github.com/Effect-TS/effect/commit/4296293049414d0cf2d915a26c552b09f946b9a0), [`9c241ab`](https://github.com/Effect-TS/effect/commit/9c241abe47ccf7a5257b98a4a64a63054a12741d), [`082b0c1`](https://github.com/Effect-TS/effect/commit/082b0c1b9f4252bcdd69608f2e4a9226f953ac3f), [`be12983`](https://github.com/Effect-TS/effect/commit/be12983bc7e7537b41cd8910fc4eb7d1da56ab07), [`de88127`](https://github.com/Effect-TS/effect/commit/de88127a5a5906ccece98af74787b5ae0e65e431)]:\n  - effect@3.13.11\n  - @effect/ai@0.12.2\n  - @effect/experimental@0.43.2\n  - @effect/platform@0.79.2\n\n## 0.2.1\n\n### Patch Changes\n\n- Updated dependencies [[`527c964`](https://github.com/Effect-TS/effect/commit/527c9645229f5be9714a7e60a38a9e753c4bbfb1)]:\n  - effect@3.13.10\n  - @effect/ai@0.12.1\n  - @effect/experimental@0.43.1\n  - @effect/platform@0.79.1\n\n## 0.2.0\n\n### Patch Changes\n\n- Updated dependencies [[`88fe129`](https://github.com/Effect-TS/effect/commit/88fe12923740765c0335a6e6203fdcc6a463edca), [`d630249`](https://github.com/Effect-TS/effect/commit/d630249426113088abe8b382db4f14d80f2160c2), [`2976e52`](https://github.com/Effect-TS/effect/commit/2976e52538d9dc9ffdcbc84d4ac748cff9305971)]:\n  - @effect/platform@0.79.0\n  - effect@3.13.9\n  - @effect/experimental@0.43.0\n  - @effect/ai@0.12.0\n\n## 0.1.1\n\n### Patch Changes\n\n- Updated dependencies [[`c65d336`](https://github.com/Effect-TS/effect/commit/c65d3362d07ec815ff3b46278314e8a31706ddc2), [`22d2ebb`](https://github.com/Effect-TS/effect/commit/22d2ebb4b11f5a44351a4736e65da391a3b647d0)]:\n  - effect@3.13.8\n  - @effect/ai@0.11.1\n  - @effect/experimental@0.42.1\n  - @effect/platform@0.78.1\n\n## 0.1.0\n\n### Patch Changes\n\n- Updated dependencies [[`c5bcf53`](https://github.com/Effect-TS/effect/commit/c5bcf53b7cb49dacffdd2a6cd8eb48cc452b417e)]:\n  - @effect/platform@0.78.0\n  - @effect/ai@0.11.0\n  - @effect/experimental@0.42.0\n\n## 0.0.7\n\n### Patch Changes\n\n- Updated dependencies [[`840cc73`](https://github.com/Effect-TS/effect/commit/840cc7329908db7ca693ef47b07d4f845c29cadd), [`9bf8a74`](https://github.com/Effect-TS/effect/commit/9bf8a74b967f18d931743dd5196af326c9118e9c), [`87ba23c`](https://github.com/Effect-TS/effect/commit/87ba23c41c193503ed0c612b0d32d0b253794c64), [`f910880`](https://github.com/Effect-TS/effect/commit/f91088069057f3b4529753f5bc5532b028d726df), [`0d01480`](https://github.com/Effect-TS/effect/commit/0d014803e4f688f74386a80abd65485e1a319244), [`a95108a`](https://github.com/Effect-TS/effect/commit/a95108acac7f25fc5e1c0dcdf16bcc638dca5c00)]:\n  - @effect/platform@0.77.7\n  - effect@3.13.7\n  - @effect/ai@0.10.7\n  - @effect/experimental@0.41.7\n\n## 0.0.6\n\n### Patch Changes\n\n- Updated dependencies [[`3154ce4`](https://github.com/Effect-TS/effect/commit/3154ce4692fa18b804982158d3c4c8a8a5fae386)]:\n  - effect@3.13.6\n  - @effect/ai@0.10.6\n  - @effect/experimental@0.41.6\n  - @effect/platform@0.77.6\n\n## 0.0.5\n\n### Patch Changes\n\n- Updated dependencies [[`3d6d323`](https://github.com/Effect-TS/effect/commit/3d6d323c2a1028f3caba45453187b9374bac2c36), [`367bb35`](https://github.com/Effect-TS/effect/commit/367bb35f4c2a254e1fb211d96db2474a7aed9020), [`6cf11c3`](https://github.com/Effect-TS/effect/commit/6cf11c3a75773ceec2877c85ddc760f381f0866d), [`a0acec8`](https://github.com/Effect-TS/effect/commit/a0acec851f72e19466363d24b9cc218acd00006a), [`975c20e`](https://github.com/Effect-TS/effect/commit/975c20e446186e9bb975f77e7c6ac7b248f7b5f6)]:\n  - @effect/ai@0.10.5\n  - effect@3.13.5\n  - @effect/experimental@0.41.5\n  - @effect/platform@0.77.5\n\n## 0.0.4\n\n### Patch Changes\n\n- Updated dependencies [[`e0746f9`](https://github.com/Effect-TS/effect/commit/e0746f9aa398b69c6542e375910683bf17f49f46), [`17d9e89`](https://github.com/Effect-TS/effect/commit/17d9e89f9851663bdbb6c1e685601d97806114a4)]:\n  - @effect/platform@0.77.4\n  - effect@3.13.4\n  - @effect/ai@0.10.4\n  - @effect/experimental@0.41.4\n\n## 0.0.3\n\n### Patch Changes\n\n- [#4504](https://github.com/Effect-TS/effect/pull/4504) [`a67a8a1`](https://github.com/Effect-TS/effect/commit/a67a8a1a4979fb7a039a060d067d805879da4d4b) Thanks @IMax153! - Introduce `AiModel` and `AiPlan` for describing retry / fallback logic between\n  models and providers\n\n  For example, the following program builds an `AiPlan` which will attempt to use\n  OpenAi's chat completions API, and if after three attempts the operation\n  is still failing, the plan will fallback to utilizing Anthropic's messages API\n  to resolve the request.\n\n  ```ts\n  import { AiPlan, Completions } from \"@effect/ai\"\n  import { AnthropicClient, AnthropicCompletions } from \"@effect/ai-anthropic\"\n  import { OpenAiClient, OpenAiCompletions } from \"@effect/ai-openai\"\n  import { NodeHttpClient, NodeRuntime } from \"@effect/platform-node\"\n  import { Config, Console, Effect, Layer } from \"effect\"\n\n  // Create Anthropic client\n  const Anthropic = AnthropicClient.layerConfig({\n    apiKey: Config.redacted(\"ANTHROPIC_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  // Create OpenAi client\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  // Create a plan of request execution\n  const Plan = AiPlan.fromModel(OpenAiCompletions.model(\"gpt-4o-mini\"), {\n    attempts: 3\n  }).pipe(\n    AiPlan.withFallback({\n      model: AnthropicCompletions.model(\"claude-3-5-haiku-latest\")\n    })\n  )\n\n  const program = Effect.gen(function* () {\n    // Build the plan of execution\n    const plan = yield* Plan\n\n    // Create a program which uses the services provided by the plan\n    const getDadJoke = Effect.gen(function* () {\n      const completions = yield* Completions.Completions\n      const response = yield* completions.create(\"Tell me a dad joke\")\n      yield* Console.log(response.text)\n    })\n\n    // Provide the plan to whichever programs need it\n    yield* plan.provide(getDadJoke)\n  })\n\n  program.pipe(Effect.provide([Anthropic, OpenAi]), NodeRuntime.runMain)\n  ```\n\n- Updated dependencies [[`cc5588d`](https://github.com/Effect-TS/effect/commit/cc5588df07f9103513547cb429ce041b9436a8bd), [`623c8cd`](https://github.com/Effect-TS/effect/commit/623c8cd053ed6ee3d353aaa8778d484670fca2bb), [`00b4eb1`](https://github.com/Effect-TS/effect/commit/00b4eb1ece12a16e222e6220965bb4024d6752ac), [`f2aee98`](https://github.com/Effect-TS/effect/commit/f2aee989b0a600900ce83e7f460d02908620c80f), [`fb798eb`](https://github.com/Effect-TS/effect/commit/fb798eb9061f1191badc017d1aa649360254da20), [`2251b15`](https://github.com/Effect-TS/effect/commit/2251b1528810bb695b37ce388b653cec0c5bf80c), [`2e15c1e`](https://github.com/Effect-TS/effect/commit/2e15c1e33648add0b29fe274fbcb7294b7515085), [`a4979db`](https://github.com/Effect-TS/effect/commit/a4979db021aef16e731be64df196b72088fc4376), [`b74255a`](https://github.com/Effect-TS/effect/commit/b74255a304ad49d60bedb1a260fd697f370af27a), [`d7f6a5c`](https://github.com/Effect-TS/effect/commit/d7f6a5c7d26c1963dcd864ca62360d20d08c7b49), [`9dd8979`](https://github.com/Effect-TS/effect/commit/9dd8979e940915b1cc1b1f264f3d019c77a65a02), [`477b488`](https://github.com/Effect-TS/effect/commit/477b488284f47c5469d7fba3e4065fb7e3b6556e), [`10932cb`](https://github.com/Effect-TS/effect/commit/10932cbf58fc721ada631cebec42f773ce96d3cc), [`9f6c784`](https://github.com/Effect-TS/effect/commit/9f6c78468b3b5e9ebfc38ffdfb70702901ee977b), [`2c639ec`](https://github.com/Effect-TS/effect/commit/2c639ecee332de4266e36022c989c35ae4e02105), [`886aaa8`](https://github.com/Effect-TS/effect/commit/886aaa81e06dfd3cd9391e8ea987d8cd5ada1124), [`a67a8a1`](https://github.com/Effect-TS/effect/commit/a67a8a1a4979fb7a039a060d067d805879da4d4b)]:\n  - effect@3.13.3\n  - @effect/ai@0.10.3\n  - @effect/experimental@0.41.3\n  - @effect/platform@0.77.3\n\n## 0.0.2\n\n### Patch Changes\n\n- Updated dependencies [[`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f), [`3e7ce97`](https://github.com/Effect-TS/effect/commit/3e7ce97f8a41756a039cf635d0b3d9a75d781097), [`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f)]:\n  - effect@3.13.2\n  - @effect/platform@0.77.2\n  - @effect/ai@0.10.2\n  - @effect/experimental@0.41.2\n\n## 0.0.1\n\n### Patch Changes\n\n- [#4446](https://github.com/Effect-TS/effect/pull/4446) [`9375c28`](https://github.com/Effect-TS/effect/commit/9375c28ca808325577da6c67cc92af25931027c8) Thanks @IMax153! - Add Anthropic AI provider integration\n\n- Updated dependencies [[`b56a211`](https://github.com/Effect-TS/effect/commit/b56a2110569fd0ec0b57ac137743e926d49f51cc), [`9375c28`](https://github.com/Effect-TS/effect/commit/9375c28ca808325577da6c67cc92af25931027c8)]:\n  - effect@3.13.1\n  - @effect/ai@0.10.1\n  - @effect/experimental@0.41.1\n  - @effect/platform@0.77.1\n"
  },
  {
    "path": "packages/ai/anthropic/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Effectful Technologies Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/ai/anthropic/README.md",
    "content": "# `@effect/ai-anthropic`\n\n## Documentation\n\n- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/ai/ai-anthropic).\n"
  },
  {
    "path": "packages/ai/anthropic/docgen.json",
    "content": "{\n  \"$schema\": \"../../../node_modules/@effect/docgen/schema.json\",\n  \"exclude\": [\"src/Generated.ts\", \"src/internal/**/*.ts\"],\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/ai/anthropic/src/\",\n  \"examplesCompilerOptions\": {\n    \"noEmit\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"module\": \"ES2022\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n    \"paths\": {\n      \"effect\": [\"../../../../effect/src/index.js\"],\n      \"effect/*\": [\"../../../../effect/src/*.js\"],\n      \"@effect/experimental\": [\"../../../../experimental/src/index.js\"],\n      \"@effect/experimental/*\": [\"../../../../experimental/src/*.js\"],\n      \"@effect/platform\": [\"../../../../platform/src/index.js\"],\n      \"@effect/platform/*\": [\"../../../../platform/src/*.js\"],\n      \"@effect/ai\": [\"../../../ai/src/index.js\"],\n      \"@effect/ai/*\": [\"../../../ai/src/*.js\"],\n      \"@effect/ai-anthropic\": [\"../../../ai-anthropic/src/index.js\"],\n      \"@effect/ai-anthropic/*\": [\"../../../ai-anthropic/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/ai/anthropic/package.json",
    "content": "{\n  \"name\": \"@effect/ai-anthropic\",\n  \"type\": \"module\",\n  \"version\": \"0.25.0\",\n  \"license\": \"MIT\",\n  \"description\": \"Effect modules for working with AI apis\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/ai/anthropic\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"keywords\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"peerDependencies\": {\n    \"@effect/ai\": \"workspace:^\",\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"effect\": \"workspace:^\"\n  },\n  \"devDependencies\": {\n    \"@effect/ai\": \"workspace:^\",\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/platform-node\": \"workspace:^\",\n    \"@tim-smart/openapi-gen\": \"^0.4.10\",\n    \"effect\": \"workspace:^\"\n  },\n  \"dependencies\": {\n    \"@anthropic-ai/tokenizer\": \"^0.0.4\"\n  }\n}\n"
  },
  {
    "path": "packages/ai/anthropic/scripts/generate.sh",
    "content": "#!/usr/bin/env bash\n\nset -euo pipefail\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &> /dev/null && pwd)\n\ntemp_dir=$(mktemp -d)\n\ncleanup() {\n  rm -rf \"${temp_dir}\"\n}\n\ntrap cleanup EXIT\n\nanthropic_stats_url=\"https://raw.githubusercontent.com/anthropics/anthropic-sdk-typescript/refs/heads/main/.stats.yml\"\n\nopenapi_spec_url=\"$(curl -sSL $anthropic_stats_url | yq \".openapi_spec_url\")\"\n\ncurl \"${openapi_spec_url}\" > \"${temp_dir}/anthropic.yaml\"\n\necho \"/**\n * @since 1.0.0\n */\" > src/Generated.ts\n\npnpm openapi-gen -s \"${temp_dir}/anthropic.yaml\" >> src/Generated.ts\n\npnpm eslint --fix src/Generated.ts\n\n# No patch required at this time\ngit apply --reject --whitespace=fix \"${SCRIPT_DIR}/generated.patch\"\n"
  },
  {
    "path": "packages/ai/anthropic/scripts/generated.patch",
    "content": "diff --git a/packages/ai/anthropic/src/Generated.ts b/packages/ai/anthropic/src/Generated.ts\nindex 9015e6427..dcb4afdad 100644\n--- a/packages/ai/anthropic/src/Generated.ts\n+++ b/packages/ai/anthropic/src/Generated.ts\n@@ -641,7 +641,7 @@ export class WebSearchTool20250305 extends S.Class<WebSearchTool20250305>(\"WebSe\n }) {}\n \n export class CreateMessageParams extends S.Class<CreateMessageParams>(\"CreateMessageParams\")({\n-  \"model\": Model,\n+  \"model\": S.Union(S.String, Model),\n   /**\n    * Input messages.\n    *\n@@ -1114,7 +1114,7 @@ export class Message extends S.Class<Message>(\"Message\")({\n    * ```\n    */\n   \"content\": S.Array(ContentBlock),\n-  \"model\": Model,\n+  \"model\": S.Union(S.String, Model),\n   /**\n    * The reason that we stopped.\n    *\n@@ -1244,7 +1244,7 @@ export class CompletePostParams extends S.Struct({\n }) {}\n \n export class CompletionRequest extends S.Class<CompletionRequest>(\"CompletionRequest\")({\n-  \"model\": Model,\n+  \"model\": S.Union(S.String, Model),\n   /**\n    * The prompt that you want Claude to complete.\n    *\n@@ -1316,7 +1316,7 @@ export class CompletionResponse extends S.Class<CompletionResponse>(\"CompletionR\n    * The format and length of IDs may change over time.\n    */\n   \"id\": S.String,\n-  \"model\": Model,\n+  \"model\": S.Union(S.String, Model),\n   /**\n    * The reason that we stopped.\n    *\n@@ -1730,7 +1730,7 @@ export class CountMessageTokensParams extends S.Class<CountMessageTokensParams>(\n    * There is a limit of 100,000 messages in a single request.\n    */\n   \"messages\": S.Array(InputMessage),\n-  \"model\": Model,\n+  \"model\": S.Union(S.String, Model),\n   /**\n    * System prompt.\n    *\n@@ -3659,7 +3659,7 @@ export class BetaWebFetchTool20250910 extends S.Class<BetaWebFetchTool20250910>(\n }) {}\n \n export class BetaCreateMessageParams extends S.Class<BetaCreateMessageParams>(\"BetaCreateMessageParams\")({\n-  \"model\": Model,\n+  \"model\": S.Union(S.String, Model),\n   /**\n    * Input messages.\n    *\n@@ -4517,7 +4517,7 @@ export class BetaMessage extends S.Class<BetaMessage>(\"BetaMessage\")({\n    * ```\n    */\n   \"content\": S.Array(BetaContentBlock),\n-  \"model\": Model,\n+  \"model\": S.Union(S.String, Model),\n   /**\n    * The reason that we stopped.\n    *\n@@ -5099,7 +5099,7 @@ export class BetaCountMessageTokensParams\n      * There is a limit of 100,000 messages in a single request.\n      */\n     \"messages\": S.Array(BetaInputMessage),\n-    \"model\": Model,\n+    \"model\": S.Union(S.String, Model),\n     /**\n      * System prompt.\n      *\n"
  },
  {
    "path": "packages/ai/anthropic/src/AnthropicClient.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AiError from \"@effect/ai/AiError\"\nimport * as Sse from \"@effect/experimental/Sse\"\nimport * as Headers from \"@effect/platform/Headers\"\nimport * as HttpBody from \"@effect/platform/HttpBody\"\nimport * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientError from \"@effect/platform/HttpClientError\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as Arr from \"effect/Array\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Config from \"effect/Config\"\nimport type { ConfigError } from \"effect/ConfigError\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport { AnthropicConfig } from \"./AnthropicConfig.js\"\nimport * as Generated from \"./Generated.js\"\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class AnthropicClient extends Context.Tag(\n  \"@effect/ai-anthropic/AnthropicClient\"\n)<AnthropicClient, Service>() {}\n\n/**\n * Represents the interface that the `AnthropicClient` service provides.\n *\n * This service abstracts the complexity of communicating with Anthropic's API,\n * providing both high-level text generation methods and low-level HTTP access\n * for advanced use cases.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface Service {\n  /**\n   * The underlying HTTP client capable of communicating with the Anthropic API.\n   *\n   * This client is pre-configured with authentication, base URL, and standard\n   * headers required for Anthropic API communication. It provides direct access\n   * to the generated Anthropic API client for operations not covered by the\n   * higher-level methods.\n   *\n   * Use this when you need to:\n   * - Access provider-specific API endpoints not available through the AI SDK\n   * - Implement custom request/response handling\n   * - Use Anthropic API features not yet supported by the Effect AI abstractions\n   * - Perform batch operations or non-streaming requests\n   *\n   * The client automatically handles authentication and follows Anthropic's\n   * API conventions for request formatting and error handling.\n   */\n  readonly client: Generated.Client\n\n  readonly streamRequest: <A, I, R>(\n    request: HttpClientRequest.HttpClientRequest,\n    schema: Schema.Schema<A, I, R>\n  ) => Stream.Stream<A, AiError.AiError, R>\n\n  readonly createMessage: (options: {\n    readonly params?: typeof Generated.BetaMessagesPostParams.Encoded | undefined\n    readonly payload: typeof Generated.BetaCreateMessageParams.Encoded\n  }) => Effect.Effect<Generated.BetaMessage, AiError.AiError>\n\n  readonly createMessageStream: (options: {\n    readonly params?: typeof Generated.BetaMessagesPostParams.Encoded | undefined\n    readonly payload: Omit<typeof Generated.BetaCreateMessageParams.Encoded, \"stream\">\n  }) => Stream.Stream<MessageStreamEvent, AiError.AiError>\n}\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make: (options: {\n  /**\n   * The API key that will be used to authenticate with Anthropic's API.\n   *\n   * The key is wrapped in a `Redacted` type to prevent accidental logging or\n   * exposure in debugging output, helping maintain security best practices.\n   *\n   * The key is automatically included in the `x-api-key` header for all API\n   * requests made through this client, which is automatically redacted in logs\n   * output by Effect loggers.\n   *\n   * Leave `undefined` if authentication will be handled through other means\n   * (e.g., environment-based authentication, proxy authentication, or when\n   * using a mock server that doesn't require authentication).\n   */\n  readonly apiKey?: Redacted.Redacted | undefined\n\n  /**\n   * The base URL endpoint used to communicate with Anthropic's API.\n   *\n   * This property determines the HTTP destination for all API requests made by\n   * this client.\n   *\n   * Defaults to `\"https://api.anthropic.com\"`.\n   *\n   * Override this value when you need to:\n   * - Point to a different Anthropic environment (e.g., staging or sandbox\n   *   servers).\n   * - Use a proxy between your application and Anthropic's API for security,\n   *   caching, or logging.\n   * - Employ a mock server for local development or testing.\n   *\n   * You may leave this property `undefined` to accept the default value.\n   */\n  readonly apiUrl?: string | undefined\n\n  /**\n   * The Anthropic API version to use for requests.\n   *\n   * This version string determines which API schema and features are available\n   * for your requests. Different versions may have different capabilities,\n   * request/response formats, or available models.\n   *\n   * Defaults to `\"2023-06-01\"`.\n   *\n   * You should specify a version that:\n   * - Supports the features and models you need\n   * - Is stable and well-tested for your use case\n   * - Matches your application's integration requirements\n   *\n   * Consult Anthropic's API documentation for available versions and their\n   * differences.\n   */\n  readonly anthropicVersion?: string | undefined\n\n  /**\n   * The organization ID to associate with API requests.\n   *\n   * This identifier links requests to a specific organization within your\n   * Anthropic account, enabling proper billing, usage tracking, and access\n   * control at the organizational level.\n   *\n   * Provide this when:\n   * - Your account belongs to multiple organizations\n   * - You need to ensure requests are billed to the correct organization\n   * - Organization-level access policies apply to your use case\n   *\n   * Leave `undefined` if you're using a personal account or the default\n   * organization.\n   */\n  readonly organizationId?: Redacted.Redacted | undefined\n\n  /**\n   * The project ID to associate with API requests.\n   *\n   * This identifier scopes requests to a specific project within your\n   * organization, enabling granular resource management, billing allocation,\n   * and access control at the project level.\n   *\n   * Specify this when:\n   * - You have multiple projects and need to separate their API usage\n   * - Project-level billing or quota management is required\n   * - Access policies are configured at the project level\n   *\n   * Leave `undefined` to use the default project or when project-level\n   * scoping is not needed.\n   */\n  readonly projectId?: Redacted.Redacted | undefined\n\n  /**\n   * A function to transform the underlying HTTP client before it's used to send\n   * API requests.\n   *\n   * This transformation function receives the configured HTTP client and returns\n   * a modified version. It's applied after all standard client configuration\n   * (authentication, base URL, headers) but before any requests are made.\n   *\n   * Use this for:\n   * - Adding custom middleware (logging, metrics, caching)\n   * - Modifying request/response processing behavior\n   * - Adding custom retry logic or error handling\n   * - Integrating with monitoring or debugging tools\n   * - Applying organization-specific HTTP client policies\n   *\n   * The transformation is applied once during client initialization and affects\n   * all subsequent API requests made through this client instance.\n   *\n   * Leave absent or set to `undefined` if no custom HTTP client behavior is\n   * needed.\n   */\n  readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n}) => Effect.Effect<\n  Service,\n  never,\n  HttpClient.HttpClient | Scope.Scope\n> = Effect.fnUntraced(function*(options) {\n  const apiKeyHeader = \"x-api-key\"\n\n  yield* Effect.locallyScopedWith(Headers.currentRedactedNames, Arr.append(apiKeyHeader))\n\n  const httpClient = (yield* HttpClient.HttpClient).pipe(\n    HttpClient.mapRequest((request) =>\n      request.pipe(\n        HttpClientRequest.prependUrl(options.apiUrl ?? \"https://api.anthropic.com\"),\n        options.apiKey\n          ? HttpClientRequest.setHeader(apiKeyHeader, Redacted.value(options.apiKey))\n          : identity,\n        HttpClientRequest.setHeader(\"anthropic-version\", options.anthropicVersion ?? \"2023-06-01\"),\n        HttpClientRequest.acceptJson\n      )\n    ),\n    options.transformClient ? options.transformClient : identity\n  )\n\n  const httpClientOk = HttpClient.filterStatusOk(httpClient)\n\n  const client = Generated.make(httpClient, {\n    transformClient: (client) =>\n      AnthropicConfig.getOrUndefined.pipe(\n        Effect.map((config) => config?.transformClient ? config.transformClient(client) : client)\n      )\n  })\n\n  const streamRequest = <A, I, R>(\n    request: HttpClientRequest.HttpClientRequest,\n    schema: Schema.Schema<A, I, R>\n  ): Stream.Stream<A, AiError.AiError, R> => {\n    const decodeEvents = Schema.decode(Schema.ChunkFromSelf(Schema.parseJson(schema)))\n    return httpClientOk.execute(request).pipe(\n      Effect.map((r) => r.stream),\n      Stream.unwrapScoped,\n      Stream.decodeText(),\n      Stream.pipeThroughChannel(Sse.makeChannel()),\n      Stream.mapChunksEffect((chunk) => decodeEvents(Chunk.map(chunk, (event) => event.data))),\n      Stream.catchTags({\n        RequestError: (error) =>\n          AiError.HttpRequestError.fromRequestError({\n            module: \"AnthropicClient\",\n            method: \"streamRequest\",\n            error\n          }),\n        ResponseError: (error) =>\n          AiError.HttpResponseError.fromResponseError({\n            module: \"AnthropicClient\",\n            method: \"streamRequest\",\n            error\n          }),\n        ParseError: (error) =>\n          AiError.MalformedOutput.fromParseError({\n            module: \"AnthropicClient\",\n            method: \"streamRequest\",\n            error\n          })\n      })\n    )\n  }\n\n  const createMessage: (options: {\n    readonly params?: typeof Generated.BetaMessagesPostParams.Encoded | undefined\n    readonly payload: typeof Generated.BetaCreateMessageParams.Encoded\n  }) => Effect.Effect<Generated.BetaMessage, AiError.AiError> = Effect.fnUntraced(\n    function*(options) {\n      return yield* client.betaMessagesPost(options).pipe(\n        Effect.catchTags({\n          RequestError: (error) =>\n            AiError.HttpRequestError.fromRequestError({\n              module: \"AnthropicClient\",\n              method: \"createMessage\",\n              error\n            }),\n          ResponseError: (error) =>\n            AiError.HttpResponseError.fromResponseError({\n              module: \"AnthropicClient\",\n              method: \"createMessage\",\n              error\n            }),\n          BetaErrorResponse: (error) =>\n            AiError.HttpResponseError.fromResponseError({\n              module: \"AnthropicClient\",\n              method: \"createMessage\",\n              error: new HttpClientError.ResponseError({\n                reason: \"StatusCode\",\n                request: error.request,\n                response: error.response\n              })\n            }),\n          ParseError: (error) =>\n            AiError.MalformedOutput.fromParseError({\n              module: \"AnthropicClient\",\n              method: \"createMessage\",\n              error\n            })\n        })\n      )\n    }\n  )\n\n  const createMessageStream = (options: {\n    readonly params?: typeof Generated.BetaMessagesPostParams.Encoded | undefined\n    readonly payload: Omit<typeof Generated.BetaCreateMessageParams.Encoded, \"stream\">\n  }): Stream.Stream<MessageStreamEvent, AiError.AiError> => {\n    const request = HttpClientRequest.post(\"/v1/messages\", {\n      headers: Headers.fromInput({\n        \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined\n      }),\n      body: HttpBody.unsafeJson({ ...options.payload, stream: true })\n    })\n    return streamRequest(request, MessageStreamEvent).pipe(\n      Stream.takeUntil((event) => event.type === \"message_stop\")\n    )\n  }\n\n  return AnthropicClient.of({\n    client,\n    streamRequest,\n    createMessage,\n    createMessageStream\n  })\n})\n\n// =============================================================================\n// Message Stream Schema\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class PingEvent extends Schema.Class<PingEvent>(\n  \"@effect/ai-anthropic/PingEvent\"\n)({\n  type: Schema.Literal(\"ping\")\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ErrorEvent extends Schema.Class<ErrorEvent>(\n  \"@effect/ai-anthropic/ErrorEvent\"\n)({\n  type: Schema.Literal(\"error\"),\n  error: Schema.Struct({\n    type: Schema.Literal(\n      \"invalid_request_error\",\n      \"authentication_error\",\n      \"permission_error\",\n      \"not_found_error\",\n      \"request_too_large\",\n      \"rate_limit_error\",\n      \"api_error\",\n      \"overloaded_error\"\n    ),\n    message: Schema.String\n  })\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class MessageStartEvent extends Schema.Class<MessageStartEvent>(\n  \"@effect/ai-anthropic/MessageStartEvent\"\n)({\n  type: Schema.Literal(\"message_start\"),\n  message: Generated.BetaMessage\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ServerToolUsage extends Schema.Class<ServerToolUsage>(\n  \"@effect/ai-anthropic/ServerToolUsage\"\n)({\n  /**\n   * The number of web search tool requests.\n   */\n  web_search_requests: Schema.optionalWith(\n    Schema.NullOr(Schema.Int.pipe(Schema.greaterThanOrEqualTo(0))),\n    { default: () => 0 }\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class MessageDelta extends Schema.Class<MessageDelta>(\n  \"@effect/ai-anthropic/MessageDelta\"\n)({\n  stop_reason: Schema.optionalWith(\n    Schema.NullOr(\n      Schema.Literal(\n        \"end_turn\",\n        \"max_tokens\",\n        \"stop_sequence\",\n        \"tool_use\",\n        \"pause_turn\",\n        \"refusal\"\n      )\n    ),\n    { default: () => null }\n  ),\n  stop_sequence: Schema.optionalWith(\n    Schema.NullOr(Schema.String),\n    { default: () => null }\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class MessageDeltaUsage extends Schema.Class<MessageDeltaUsage>(\n  \"@effect/ai-anthropic/MessageDeltaUsage\"\n)({\n  /**\n   * The cumulative number of input tokens which were used.\n   */\n  input_tokens: Schema.optionalWith(\n    Schema.NullOr(Schema.Int.pipe(Schema.greaterThanOrEqualTo(0))),\n    { default: () => null }\n  ),\n  /**\n   * The cumulative number of output tokens which were used.\n   */\n  output_tokens: Schema.optionalWith(\n    Schema.NullOr(Schema.Int.pipe(Schema.greaterThanOrEqualTo(0))),\n    { default: () => null }\n  ),\n  /**\n   * The cumulative number of input tokens used to create the cache entry.\n   */\n  cache_creation_input_tokens: Schema.optionalWith(\n    Schema.NullOr(Schema.Int.pipe(Schema.greaterThanOrEqualTo(0))),\n    { default: () => null }\n  ),\n  /**\n   * The cumulative number of input tokens read from the cache.\n   */\n  cache_read_input_tokens: Schema.optionalWith(\n    Schema.NullOr(Schema.Int.pipe(Schema.greaterThanOrEqualTo(0))),\n    { default: () => null }\n  ),\n  /**\n   * The number of server tool requests.\n   */\n  server_tool_use: Schema.optionalWith(\n    Schema.NullOr(ServerToolUsage),\n    { default: () => null }\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class MessageDeltaEvent extends Schema.Class<MessageDeltaEvent>(\n  \"@effect/ai-anthropic/MessageDeltaEvent\"\n)({\n  type: Schema.Literal(\"message_delta\"),\n  delta: MessageDelta,\n  /**\n   * Billing and rate-limit usage.\n   *\n   * Anthropic's API bills and rate-limits by token counts, as tokens represent\n   * the underlying cost to our systems.\n   *\n   * Under the hood, the API transforms requests into a format suitable for the\n   * model. The model's output then goes through a parsing stage before becoming\n   * an API response. As a result, the token counts in `usage` will not match\n   * one-to-one with the exact visible content of an API request or response.\n   *\n   * For example, `output_tokens` will be non-zero, even for an empty string\n   * response from Claude.\\n\\nTotal input tokens in a request is the summation\n   * of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n   */\n  usage: MessageDeltaUsage\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class MessageStopEvent extends Schema.Class<MessageStopEvent>(\n  \"@effect/ai-anthropic/MessageStopEvent\"\n)({\n  type: Schema.Literal(\"message_stop\")\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ContentBlockStartEvent extends Schema.Class<ContentBlockStartEvent>(\n  \"@effect/ai-anthropic/ContentBlockStartEvent\"\n)({\n  type: Schema.Literal(\"content_block_start\"),\n  index: Schema.Int,\n  content_block: Generated.BetaContentBlock\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class CitationsDelta extends Schema.Class<CitationsDelta>(\n  \"@effect/ai-anthropic/CitationsDelta\"\n)({\n  type: Schema.Literal(\"citations_delta\"),\n  citation: Schema.Union(\n    Generated.BetaResponseCharLocationCitation,\n    Generated.BetaResponsePageLocationCitation,\n    Generated.BetaResponseContentBlockLocationCitation,\n    Generated.BetaResponseWebSearchResultLocationCitation,\n    Generated.BetaResponseSearchResultLocationCitation\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class InputJsonContentBlockDelta extends Schema.Class<InputJsonContentBlockDelta>(\n  \"@effect/ai-anthropic/InputJsonContentBlockDelta\"\n)({\n  type: Schema.Literal(\"input_json_delta\"),\n  partial_json: Schema.String\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class SignatureContentBlockDelta extends Schema.Class<SignatureContentBlockDelta>(\n  \"@effect/ai-anthropic/SignatureContentBlockDelta\"\n)({\n  type: Schema.Literal(\"signature_delta\"),\n  signature: Schema.String\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class TextContentBlockDelta extends Schema.Class<TextContentBlockDelta>(\n  \"@effect/ai-anthropic/TextContentBlockDelta\"\n)({\n  type: Schema.Literal(\"text_delta\"),\n  text: Schema.String\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ThinkingContentBlockDelta extends Schema.Class<ThinkingContentBlockDelta>(\n  \"@effect/ai-anthropic/ThinkingContentBlockDelta\"\n)({\n  type: Schema.Literal(\"thinking_delta\"),\n  thinking: Schema.String\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ContentBlockDeltaEvent extends Schema.Class<ContentBlockDeltaEvent>(\n  \"@effect/ai-anthropic/ContentBlockDeltaEvent\"\n)({\n  type: Schema.Literal(\"content_block_delta\"),\n  index: Schema.Int,\n  delta: Schema.Union(\n    CitationsDelta,\n    InputJsonContentBlockDelta,\n    SignatureContentBlockDelta,\n    TextContentBlockDelta,\n    ThinkingContentBlockDelta\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ContentBlockStopEvent extends Schema.Class<ContentBlockStopEvent>(\n  \"@effect/ai-anthropic/ContentBlockStopEvent\"\n)({\n  type: Schema.Literal(\"content_block_stop\"),\n  index: Schema.Int\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const MessageStreamEvent = Schema.Union(\n  PingEvent,\n  ErrorEvent,\n  MessageStartEvent,\n  MessageDeltaEvent,\n  MessageStopEvent,\n  ContentBlockStartEvent,\n  ContentBlockDeltaEvent,\n  ContentBlockStopEvent\n)\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type MessageStreamEvent = typeof MessageStreamEvent.Type\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  /**\n   * The API key that will be used to authenticate with Anthropic's API.\n   *\n   * The key is wrapped in a `Redacted` type to prevent accidental logging or\n   * exposure in debugging output, helping maintain security best practices.\n   *\n   * The key is automatically included in the `x-api-key` header for all API\n   * requests made through this client, which is automatically redacted in logs\n   * output by Effect loggers.\n   *\n   * Leave `undefined` if authentication will be handled through other means\n   * (e.g., environment-based authentication, proxy authentication, or when\n   * using a mock server that doesn't require authentication).\n   */\n  readonly apiKey?: Redacted.Redacted | undefined\n  /**\n   * The base URL endpoint used to communicate with Anthropic's API.\n   *\n   * This property determines the HTTP destination for all API requests made by\n   * this client.\n   *\n   * Defaults to `\"https://api.anthropic.com\"`.\n   *\n   * Override this value when you need to:\n   * - Point to a different Anthropic environment (e.g., staging or sandbox\n   *   servers).\n   * - Use a proxy between your application and Anthropic's API for security,\n   *   caching, or logging.\n   * - Employ a mock server for local development or testing.\n   *\n   * You may leave this property `undefined` to accept the default value.\n   */\n  readonly apiUrl?: string | undefined\n  /**\n   * The Anthropic API version to use for requests.\n   *\n   * This version string determines which API schema and features are available\n   * for your requests. Different versions may have different capabilities,\n   * request/response formats, or available models.\n   *\n   * Defaults to `\"2023-06-01\"`.\n   *\n   * You should specify a version that:\n   * - Supports the features and models you need\n   * - Is stable and well-tested for your use case\n   * - Matches your application's integration requirements\n   *\n   * Consult Anthropic's API documentation for available versions and their\n   * differences.\n   */\n  readonly anthropicVersion?: string | undefined\n  /**\n   * A function to transform the underlying HTTP client before it's used for API requests.\n   *\n   * This transformation function receives the configured HTTP client and returns\n   * a modified version. It's applied after all standard client configuration\n   * (authentication, base URL, headers) but before any requests are made.\n   *\n   * Use this for:\n   * - Adding custom middleware (logging, metrics, caching)\n   * - Modifying request/response processing behavior\n   * - Adding custom retry logic or error handling\n   * - Integrating with monitoring or debugging tools\n   * - Applying organization-specific HTTP client policies\n   *\n   * The transformation is applied once during client initialization and affects\n   * all subsequent API requests made through this client instance.\n   *\n   * Leave `undefined` if no custom HTTP client behavior is needed.\n   */\n  readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n}): Layer.Layer<AnthropicClient, never, HttpClient.HttpClient> => Layer.scoped(AnthropicClient, make(options))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerConfig = (options: {\n  /**\n   * The API key that will be used to authenticate with Anthropic's API.\n   *\n   * The key is wrapped in a `Redacted` type to prevent accidental logging or\n   * exposure in debugging output, helping maintain security best practices.\n   *\n   * The key is automatically included in the `x-api-key` header for all API\n   * requests made through this client, which is automatically redacted in logs\n   * output by Effect loggers.\n   *\n   * Leave `undefined` if authentication will be handled through other means\n   * (e.g., environment-based authentication, proxy authentication, or when\n   * using a mock server that doesn't require authentication).\n   */\n  readonly apiKey?: Config.Config<Redacted.Redacted | undefined> | undefined\n  /**\n   * The base URL endpoint used to communicate with Anthropic's API.\n   *\n   * This property determines the HTTP destination for all API requests made by\n   * this client.\n   *\n   * Defaults to `\"https://api.anthropic.com\"`.\n   *\n   * Override this value when you need to:\n   * - Point to a different Anthropic environment (e.g., staging or sandbox\n   *   servers).\n   * - Use a proxy between your application and Anthropic's API for security,\n   *   caching, or logging.\n   * - Employ a mock server for local development or testing.\n   *\n   * You may leave this property `undefined` to accept the default value.\n   */\n  readonly apiUrl?: Config.Config<string | undefined> | undefined\n  /**\n   * The Anthropic API version to use for requests.\n   *\n   * This version string determines which API schema and features are available\n   * for your requests. Different versions may have different capabilities,\n   * request/response formats, or available models.\n   *\n   * Defaults to `\"2023-06-01\"`.\n   *\n   * You should specify a version that:\n   * - Supports the features and models you need\n   * - Is stable and well-tested for your use case\n   * - Matches your application's integration requirements\n   *\n   * Consult Anthropic's API documentation for available versions and their\n   * differences.\n   */\n  readonly anthropicVersion?: Config.Config<string | undefined> | undefined\n  /**\n   * A function to transform the underlying HTTP client before it's used for API requests.\n   *\n   * This transformation function receives the configured HTTP client and returns\n   * a modified version. It's applied after all standard client configuration\n   * (authentication, base URL, headers) but before any requests are made.\n   *\n   * Use this for:\n   * - Adding custom middleware (logging, metrics, caching)\n   * - Modifying request/response processing behavior\n   * - Adding custom retry logic or error handling\n   * - Integrating with monitoring or debugging tools\n   * - Applying organization-specific HTTP client policies\n   *\n   * The transformation is applied once during client initialization and affects\n   * all subsequent API requests made through this client instance.\n   *\n   * Leave `undefined` if no custom HTTP client behavior is needed.\n   */\n  readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n}): Layer.Layer<AnthropicClient, ConfigError, HttpClient.HttpClient> => {\n  const { transformClient, ...configs } = options\n  return Config.all(configs).pipe(\n    Effect.flatMap((configs) => make({ ...configs, transformClient })),\n    Layer.scoped(AnthropicClient)\n  )\n}\n"
  },
  {
    "path": "packages/ai/anthropic/src/AnthropicConfig.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { HttpClient } from \"@effect/platform/HttpClient\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class AnthropicConfig extends Context.Tag(\"@effect/ai-anthropic/AnthropicConfig\")<\n  AnthropicConfig,\n  AnthropicConfig.Service\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<typeof AnthropicConfig.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(AnthropicConfig.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace AnthropicConfig {\n  /**\n   * @since 1.0.0\n   * @category Models\n   */\n  export interface Service {\n    readonly transformClient?: (client: HttpClient) => HttpClient\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport const withClientTransform: {\n  (transform: (client: HttpClient) => HttpClient): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient): Effect.Effect<A, E, R>\n} = dual<\n  (transform: (client: HttpClient) => HttpClient) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient) => Effect.Effect<A, E, R>\n>(\n  2,\n  (self, transformClient) =>\n    Effect.flatMap(\n      AnthropicConfig.getOrUndefined,\n      (config) => Effect.provideService(self, AnthropicConfig, { ...config, transformClient })\n    )\n)\n"
  },
  {
    "path": "packages/ai/anthropic/src/AnthropicLanguageModel.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AiError from \"@effect/ai/AiError\"\nimport * as IdGenerator from \"@effect/ai/IdGenerator\"\nimport * as LanguageModel from \"@effect/ai/LanguageModel\"\nimport * as AiModel from \"@effect/ai/Model\"\nimport type * as Prompt from \"@effect/ai/Prompt\"\nimport type * as Response from \"@effect/ai/Response\"\nimport { addGenAIAnnotations } from \"@effect/ai/Telemetry\"\nimport type * as Tokenizer from \"@effect/ai/Tokenizer\"\nimport * as Tool from \"@effect/ai/Tool\"\nimport * as Arr from \"effect/Array\"\nimport * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport { dual } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Stream from \"effect/Stream\"\nimport type { Span } from \"effect/Tracer\"\nimport type { Mutable, Simplify } from \"effect/Types\"\nimport { AnthropicClient, type MessageStreamEvent } from \"./AnthropicClient.js\"\nimport * as AnthropicTokenizer from \"./AnthropicTokenizer.js\"\nimport * as AnthropicTool from \"./AnthropicTool.js\"\nimport type * as Generated from \"./Generated.js\"\nimport * as InternalUtilities from \"./internal/utilities.js\"\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type Model = typeof Generated.Model.Encoded\n\n// =============================================================================\n// Configuration\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class Config extends Context.Tag(\"@effect/ai-anthropic/AnthropicLanguageModel/Config\")<\n  Config,\n  Config.Service\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<typeof Config.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(Config.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Config {\n  /**\n   * @since 1.0.0\n   * @category Configuration\n   */\n  export interface Service extends\n    Simplify<\n      Partial<\n        Omit<\n          typeof Generated.CreateMessageParams.Encoded,\n          \"messages\" | \"tools\" | \"tool_choice\" | \"stream\"\n        >\n      >\n    >\n  {\n    readonly disableParallelToolCalls?: boolean\n  }\n}\n\n// =============================================================================\n// Anthropic Provider Options / Metadata\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Provider Metadata\n */\nexport type AnthropicReasoningInfo = {\n  readonly type: \"thinking\"\n  /**\n   * Thinking content as an encrypted string, which is used to verify\n   * that thinking content was indeed generated by Anthropic's API.\n   */\n  readonly signature: typeof Generated.ResponseThinkingBlock.fields.thinking.Encoded\n} | {\n  readonly type: \"redacted_thinking\"\n  /**\n   * Thinking content which was flagged by Anthropic's safety systems, and\n   * was therefore encrypted.\n   */\n  readonly redactedData: typeof Generated.RequestRedactedThinkingBlock.fields.data.Encoded\n}\n\n/**\n * @since 1.0.0\n * @category Provider Options\n */\ndeclare module \"@effect/ai/Prompt\" {\n  export interface SystemMessageOptions extends ProviderOptions {\n    readonly anthropic?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface UserMessageOptions extends ProviderOptions {\n    readonly anthropic?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface AssistantMessageOptions extends ProviderOptions {\n    readonly anthropic?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface ToolMessageOptions extends ProviderOptions {\n    readonly anthropic?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface TextPartOptions extends ProviderOptions {\n    readonly anthropic?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface ReasoningPartOptions extends ProviderOptions {\n    readonly anthropic?:\n      | Simplify<\n        AnthropicReasoningInfo & {\n          /**\n           * A breakpoint which marks the end of reusable content eligible for caching.\n           */\n          readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n        }\n      >\n      | undefined\n  }\n\n  export interface FilePartOptions extends ProviderOptions {\n    readonly anthropic?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n      /**\n       * Whether or not citations should be enabled for the file part.\n       */\n      readonly citations?: typeof Generated.RequestCitationsConfig.Encoded | undefined\n      /**\n       * A custom title to provide to the document. If omitted, the file part's\n       * `fileName` property will be used.\n       */\n      readonly documentTitle?: string | undefined\n      /**\n       * Additional context about the document that will be forwarded to the\n       * large language model, but will not be used towards cited content.\n       *\n       * Useful for storing additional document metadata as text or stringified JSON.\n       */\n      readonly documentContext?: string | undefined\n    } | undefined\n  }\n\n  export interface ToolCallPartOptions extends ProviderOptions {\n    readonly anthropic?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface ToolResultPartOptions extends ProviderOptions {\n    readonly anthropic?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n}\n\ndeclare module \"@effect/ai/Response\" {\n  export interface ReasoningPartMetadata extends ProviderMetadata {\n    readonly anthropic?: AnthropicReasoningInfo | undefined\n  }\n\n  export interface ReasoningStartPartMetadata extends ProviderMetadata {\n    readonly anthropic?: AnthropicReasoningInfo | undefined\n  }\n\n  export interface ReasoningDeltaPartMetadata extends ProviderMetadata {\n    readonly anthropic?: AnthropicReasoningInfo | undefined\n  }\n\n  export interface FinishPartMetadata extends ProviderMetadata {\n    readonly anthropic?: {\n      /**\n       * Additional usage information provided by the Anthropic API.\n       */\n      readonly usage?: Generated.BetaUsage | undefined\n      /**\n       * Which custom stop sequence was generated, if any.\n       *\n       * If one of the custom user-defined stop sequences was generated, the\n       * value will be a `string` with that stop sequence.\n       */\n      readonly stopSequence?: string | undefined\n    } | undefined\n  }\n\n  export interface DocumentSourcePartMetadata extends ProviderMetadata {\n    readonly anthropic?: {\n      readonly source: \"document\"\n      readonly type: \"char_location\"\n      /**\n       * The text that was cited in the response.\n       */\n      readonly citedText: string\n      /**\n       * The 0-indexed starting position of the characters that were cited.\n       */\n      readonly startCharIndex: number\n      /**\n       * The exclusive ending position of the characters that were cited.\n       */\n      readonly endCharIndex: number\n    } | {\n      readonly source: \"document\"\n      readonly type: \"page_location\"\n      /**\n       * The text that was cited in the response.\n       */\n      readonly citedText: string\n      /**\n       * The 1-indexed starting page of pages that were cited.\n       */\n      readonly startPageNumber: number\n      /**\n       * The exclusive ending position of the pages that were cited.\n       */\n      readonly endPageNumber: number\n    } | undefined\n  }\n\n  export interface UrlSourcePartMetadata extends ProviderMetadata {\n    readonly anthropic?: {\n      readonly source: \"url\"\n      /**\n       * Up to 150 characters of the text content that was referenced from the\n       * URL source material.\n       */\n      readonly citedText: string\n      /**\n       * An internal reference that must be passed back to the Anthropic API\n       * during multi-turn conversations.\n       */\n      readonly encryptedIndex: string\n    } | undefined\n  }\n}\n\n// =============================================================================\n// Anthropic Language Model\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Ai Models\n */\nexport const model = (\n  model: (string & {}) | Model,\n  config?: Omit<Config.Service, \"model\">\n): AiModel.Model<\"anthropic\", LanguageModel.LanguageModel, AnthropicClient> =>\n  AiModel.make(\"anthropic\", layer({ model, config }))\n\n/**\n * @since 1.0.0\n * @category Ai Models\n */\nexport const modelWithTokenizer = (\n  model: (string & {}) | Model,\n  config?: Omit<Config.Service, \"model\">\n): AiModel.Model<\"anthropic\", LanguageModel.LanguageModel | Tokenizer.Tokenizer, AnthropicClient> =>\n  AiModel.make(\"anthropic\", layerWithTokenizer({ model, config }))\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.fnUntraced(function*(options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Omit<Config.Service, \"model\">\n}) {\n  const client = yield* AnthropicClient\n\n  const makeRequest = Effect.fnUntraced(\n    function*(providerOptions: LanguageModel.ProviderOptions) {\n      const context = yield* Effect.context<never>()\n      const config = { model: options.model, ...options.config, ...context.unsafeMap.get(Config.key) }\n      const { betas: messageBetas, messages, system } = yield* prepareMessages(providerOptions)\n      const { betas: toolBetas, toolChoice, tools } = yield* prepareTools(providerOptions, config)\n      const responseFormat = providerOptions.responseFormat\n      const request: typeof Generated.BetaCreateMessageParams.Encoded = {\n        max_tokens: 4096,\n        ...config,\n        system,\n        messages,\n        tools: responseFormat.type === \"text\"\n          ? tools\n          : [{\n            name: responseFormat.objectName,\n            description: Tool.getDescriptionFromSchemaAst(responseFormat.schema.ast) ?? \"Respond with a JSON object\",\n            input_schema: Tool.getJsonSchemaFromSchemaAst(responseFormat.schema.ast) as any\n          }],\n        tool_choice: responseFormat.type === \"text\"\n          ? toolChoice\n          : {\n            type: \"tool\",\n            name: responseFormat.objectName,\n            disable_parallel_tool_use: true\n          }\n      }\n      return { betas: new Set([...messageBetas, ...toolBetas]), request }\n    }\n  )\n\n  return yield* LanguageModel.make({\n    generateText: Effect.fnUntraced(\n      function*(options) {\n        const { betas, request } = yield* makeRequest(options)\n        annotateRequest(options.span, request)\n        const anthropicBeta = betas.size > 0 ? Array.from(betas).join(\",\") : undefined\n        const rawResponse = yield* client.createMessage({\n          params: { \"anthropic-beta\": anthropicBeta },\n          payload: request\n        })\n        annotateResponse(options.span, rawResponse)\n        return yield* makeResponse(rawResponse, options)\n      }\n    ),\n    streamText: Effect.fnUntraced(\n      function*(options) {\n        const { betas, request } = yield* makeRequest(options)\n        annotateRequest(options.span, request)\n        const anthropicBeta = betas.size > 0 ? Array.from(betas).join(\",\") : undefined\n        return client.createMessageStream({\n          params: { \"anthropic-beta\": anthropicBeta },\n          payload: request\n        })\n      },\n      (effect, options) =>\n        effect.pipe(\n          Effect.flatMap((stream) => makeStreamResponse(stream, options)),\n          Stream.unwrap,\n          Stream.map((response) => {\n            annotateStreamResponse(options.span, response)\n            return response\n          })\n        )\n    )\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Omit<Config.Service, \"model\">\n}): Layer.Layer<LanguageModel.LanguageModel, never, AnthropicClient> =>\n  Layer.effect(LanguageModel.LanguageModel, make({ model: options.model, config: options.config }))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerWithTokenizer = (options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Omit<Config.Service, \"model\">\n}): Layer.Layer<LanguageModel.LanguageModel | Tokenizer.Tokenizer, never, AnthropicClient> =>\n  Layer.merge(layer(options), AnthropicTokenizer.layer)\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport const withConfigOverride: {\n  (config: Config.Service): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, config: Config.Service): Effect.Effect<A, E, R>\n} = dual<\n  (config: Config.Service) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, config: Config.Service) => Effect.Effect<A, E, R>\n>(2, (self, overrides) =>\n  Effect.flatMap(\n    Config.getOrUndefined,\n    (config) => Effect.provideService(self, Config, { ...config, ...overrides })\n  ))\n\n// =============================================================================\n// Prompt Conversion\n// =============================================================================\n\nconst prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect<{\n  readonly betas: ReadonlySet<string>\n  readonly system: ReadonlyArray<typeof Generated.BetaRequestTextBlock.Encoded> | undefined\n  readonly messages: ReadonlyArray<typeof Generated.BetaInputMessage.Encoded>\n}, AiError.AiError> = Effect.fnUntraced(function*(options) {\n  const betas = new Set<string>()\n  const groups = groupMessages(options.prompt)\n\n  let system: Array<typeof Generated.BetaRequestTextBlock.Encoded> | undefined = undefined\n  const messages: Array<typeof Generated.BetaInputMessage.Encoded> = []\n\n  for (let i = 0; i < groups.length; i++) {\n    const group = groups[i]\n    const isLastGroup = i === groups.length - 1\n\n    switch (group.type) {\n      case \"system\": {\n        system = group.messages.map((message) => ({\n          type: \"text\",\n          text: message.content,\n          cache_control: getCacheControl(message)\n        }))\n        break\n      }\n\n      case \"user\": {\n        const content: Array<typeof Generated.BetaInputContentBlock.Encoded> = []\n\n        for (const message of group.messages) {\n          switch (message.role) {\n            case \"user\": {\n              for (let j = 0; j < message.content.length; j++) {\n                const part = message.content[j]\n                const isLastPart = j === message.content.length - 1\n\n                // Attempt to get the cache control from the part first. If\n                // the part does not have cache control defined and we are\n                // evaluating the last part for this message, also check the\n                // message for cache control.\n                const cacheControl = getCacheControl(part) ?? (\n                  isLastPart ? getCacheControl(message) : undefined\n                )\n\n                switch (part.type) {\n                  case \"text\": {\n                    content.push({\n                      type: \"text\",\n                      text: part.text,\n                      cache_control: cacheControl\n                    })\n                    break\n                  }\n\n                  case \"file\": {\n                    if (part.mediaType.startsWith(\"image/\")) {\n                      const source = part.data instanceof URL ?\n                        {\n                          type: \"url\",\n                          url: part.data.toString()\n                        } as const :\n                        {\n                          type: \"base64\",\n                          media_type: part.mediaType === \"image/*\"\n                            ? \"image/jpeg\"\n                            : (part.mediaType as typeof Generated.Base64ImageSourceMediaType.Encoded),\n                          data: typeof part.data === \"string\" ? part.data : Encoding.encodeBase64(part.data)\n                        } as const\n\n                      content.push({\n                        type: \"image\",\n                        source,\n                        cache_control: cacheControl\n                      })\n                    } else if (part.mediaType === \"application/pdf\" || part.mediaType === \"text/plain\") {\n                      if (part.mediaType === \"application/pdf\") {\n                        betas.add(\"pdfs-2024-09-25\")\n                      }\n\n                      const enableCitations = shouldEnableCitations(part)\n                      const documentOptions = getDocumentMetadata(part)\n\n                      const source = part.data instanceof URL\n                        ? {\n                          type: \"url\",\n                          url: part.data.toString()\n                        } as const\n                        : part.mediaType === \"application/pdf\"\n                        ? {\n                          type: \"base64\",\n                          media_type: \"application/pdf\",\n                          data: typeof part.data === \"string\"\n                            ? part.data\n                            : Encoding.encodeBase64(part.data)\n                        } as const\n                        : {\n                          type: \"text\",\n                          media_type: \"text/plain\",\n                          data: typeof part.data === \"string\"\n                            ? part.data\n                            : Encoding.encodeBase64(part.data)\n                        } as const\n\n                      content.push({\n                        type: \"document\",\n                        source,\n                        title: documentOptions?.title ?? part.fileName,\n                        ...(documentOptions?.context ? { context: documentOptions.context } : undefined),\n                        ...(enableCitations ? { citations: { enabled: true } } : undefined),\n                        cache_control: cacheControl\n                      })\n                    } else {\n                      return yield* new AiError.MalformedInput({\n                        module: \"AnthropicLanguageModel\",\n                        method: \"prepareMessages\",\n                        description: `Detected unsupported media type for file: '${part.mediaType}'`\n                      })\n                    }\n                    break\n                  }\n                }\n              }\n\n              break\n            }\n\n            // TODO: advanced tool result content parts\n            case \"tool\": {\n              for (let j = 0; j < message.content.length; j++) {\n                const part = message.content[j]\n                const isLastPart = j === message.content.length - 1\n\n                // Attempt to get the cache control from the part first. If\n                // the part does not have cache control defined and we are\n                // evaluating the last part for this message, also check the\n                // message for cache control.\n                const cacheControl = getCacheControl(part) ?? (\n                  isLastPart ? getCacheControl(message) : undefined\n                )\n\n                content.push({\n                  type: \"tool_result\",\n                  tool_use_id: part.id,\n                  content: JSON.stringify(part.result),\n                  is_error: part.isFailure,\n                  cache_control: cacheControl\n                })\n              }\n\n              break\n            }\n          }\n        }\n\n        messages.push({ role: \"user\", content })\n\n        break\n      }\n\n      case \"assistant\": {\n        const content: Array<typeof Generated.BetaInputContentBlock.Encoded> = []\n\n        for (let j = 0; j < group.messages.length; j++) {\n          const message = group.messages[j]\n          const isLastMessage = j === group.messages.length - 1\n\n          for (let k = 0; k < message.content.length; k++) {\n            const part = message.content[k]\n            const isLastPart = k === message.content.length - 1\n\n            // Attempt to get the cache control from the part first. If\n            // the part does not have cache control defined and we are\n            // evaluating the last part for this message, also check the\n            // message for cache control.\n            const cacheControl = getCacheControl(part) ?? (\n              isLastPart ? getCacheControl(message) : undefined\n            )\n\n            switch (part.type) {\n              case \"text\": {\n                content.push({\n                  type: \"text\",\n                  // Anthropic does not allow trailing whitespace in assistant\n                  // content blocks\n                  text: isLastGroup && isLastMessage && isLastPart\n                    ? part.text.trim()\n                    : part.text\n                })\n                break\n              }\n\n              case \"reasoning\": {\n                const options = part.options.anthropic\n                if (Predicate.isNotUndefined(options)) {\n                  if (options.type === \"thinking\") {\n                    content.push({\n                      type: \"thinking\",\n                      thinking: part.text,\n                      signature: options.signature\n                    })\n                  } else {\n                    content.push({\n                      type: \"redacted_thinking\",\n                      data: options.redactedData\n                    })\n                  }\n                }\n                break\n              }\n\n              case \"tool-call\": {\n                if (part.providerExecuted) {\n                  if (part.name === \"AnthropicCodeExecution\") {\n                    content.push({\n                      type: \"server_tool_use\",\n                      id: part.id,\n                      name: \"code_execution\",\n                      input: part.params as any,\n                      cache_control: cacheControl\n                    })\n                  }\n                  if (part.name === \"AnthropicWebSearch\") {\n                    content.push({\n                      type: \"server_tool_use\",\n                      id: part.id,\n                      name: \"web_search\",\n                      input: part.params as any,\n                      cache_control: cacheControl\n                    })\n                  }\n                } else {\n                  content.push({\n                    type: \"tool_use\",\n                    id: part.id,\n                    name: part.name,\n                    input: part.params as any,\n                    cache_control: cacheControl\n                  })\n                }\n                break\n              }\n\n              case \"tool-result\": {\n                if (part.name === \"AnthropicCodeExecution\") {\n                  content.push({\n                    type: \"code_execution_tool_result\",\n                    tool_use_id: part.id,\n                    content: part.result as any,\n                    cache_control: cacheControl\n                  })\n                } else if (part.name === \"AnthropicWebSearch\") {\n                  content.push({\n                    type: \"web_search_tool_result\",\n                    tool_use_id: part.id,\n                    content: part.result as any,\n                    cache_control: cacheControl\n                  })\n                } else {\n                  return yield* new AiError.MalformedInput({\n                    module: \"AnthropicLanguageModel\",\n                    method: \"prepareMessages\",\n                    description: `Provider executed tool result for tool ${part.name} is not supported in prompt`\n                  })\n                }\n              }\n            }\n          }\n        }\n\n        messages.push({ role: \"assistant\", content })\n\n        break\n      }\n    }\n  }\n\n  return {\n    system,\n    messages,\n    betas\n  }\n})\n\n// =============================================================================\n// Response Conversion\n// =============================================================================\n\nconst makeResponse: (\n  response: Generated.BetaMessage,\n  options: LanguageModel.ProviderOptions\n) => Effect.Effect<\n  Array<Response.PartEncoded>,\n  never,\n  IdGenerator.IdGenerator\n> = Effect.fnUntraced(\n  function*(response, options) {\n    const idGenerator = yield* IdGenerator.IdGenerator\n    const parts: Array<Response.PartEncoded> = []\n    const citableDocuments = extractCitableDocuments(options.prompt)\n\n    parts.push({\n      type: \"response-metadata\",\n      id: response.id,\n      modelId: response.model,\n      timestamp: DateTime.formatIso(yield* DateTime.now)\n    })\n\n    for (const part of response.content) {\n      switch (part.type) {\n        case \"text\": {\n          // The text parts should only be added to the response here if the\n          // response format is `\"text\"`. If the response format is `\"json\"`,\n          // then the text parts must instead be added to the response when a\n          // tool call is received.\n          if (options.responseFormat.type === \"text\") {\n            parts.push({\n              type: \"text\",\n              text: part.text\n            })\n\n            if (Predicate.isNotNullable(part.citations)) {\n              for (const citation of part.citations) {\n                const source = yield* processCitation(citation, citableDocuments, idGenerator)\n                if (Predicate.isNotUndefined(source)) {\n                  parts.push(source)\n                }\n              }\n            }\n          }\n\n          break\n        }\n\n        case \"thinking\": {\n          parts.push({\n            type: \"reasoning\",\n            text: part.thinking,\n            metadata: { anthropic: { type: \"thinking\", signature: part.signature } }\n          })\n          break\n        }\n\n        case \"redacted_thinking\": {\n          parts.push({\n            type: \"reasoning\",\n            text: \"\",\n            metadata: { anthropic: { type: \"redacted_thinking\", redactedData: part.data } }\n          })\n          break\n        }\n\n        case \"tool_use\": {\n          // When a `\"json\"` response format is requested, the JSON that we need\n          // will be returned by the tool call injected into the request\n          if (options.responseFormat.type === \"json\") {\n            parts.push({\n              type: \"text\",\n              text: JSON.stringify(part.input)\n            })\n          } else {\n            const providerTool = AnthropicTool.getProviderDefinedToolName(part.name)\n            const name = Predicate.isNotUndefined(providerTool) ? providerTool : part.name\n            const providerName = Predicate.isNotUndefined(providerTool) ? part.name : undefined\n            parts.push({\n              type: \"tool-call\",\n              id: part.id,\n              name,\n              params: part.input,\n              providerName,\n              providerExecuted: false\n            })\n          }\n\n          break\n        }\n\n        case \"server_tool_use\": {\n          const providerTool = AnthropicTool.getProviderDefinedToolName(part.name)\n          if (Predicate.isNotUndefined(providerTool)) {\n            parts.push({\n              type: \"tool-call\",\n              id: part.id,\n              name: providerTool,\n              params: part.input,\n              providerName: part.name,\n              providerExecuted: true\n            })\n          }\n\n          break\n        }\n\n        case \"bash_code_execution_tool_result\": {\n          const isFailure = part.content.type === \"bash_code_execution_tool_result_error\"\n          parts.push({\n            type: \"tool-result\",\n            id: part.tool_use_id,\n            name: \"AnthropicCodeExecution\",\n            isFailure,\n            result: part.content,\n            providerName: \"code_execution\",\n            providerExecuted: true\n          })\n          break\n        }\n\n        case \"code_execution_tool_result\": {\n          const isFailure = part.content.type === \"code_execution_tool_result_error\"\n          parts.push({\n            type: \"tool-result\",\n            id: part.tool_use_id,\n            name: \"AnthropicCodeExecution\",\n            isFailure,\n            result: part.content,\n            providerName: \"code_execution\",\n            providerExecuted: true\n          })\n          break\n        }\n\n        case \"text_editor_code_execution_tool_result\": {\n          const isFailure = part.content.type === \"text_editor_code_execution_tool_result_error\"\n          parts.push({\n            type: \"tool-result\",\n            id: part.tool_use_id,\n            name: \"AnthropicCodeExecution\",\n            isFailure,\n            result: part.content,\n            providerName: \"code_execution\",\n            providerExecuted: true\n          })\n          break\n        }\n\n        case \"web_search_tool_result\": {\n          const isFailure = !Array.isArray(part.content)\n          parts.push({\n            type: \"tool-result\",\n            id: part.tool_use_id,\n            name: \"AnthropicWebSearch\",\n            isFailure,\n            result: part.content,\n            providerName: \"web_search\",\n            providerExecuted: true\n          })\n          break\n        }\n      }\n    }\n\n    // Anthropic always returns a non-null `stop_reason` for non-streaming responses\n    const finishReason = InternalUtilities.resolveFinishReason(\n      response.stop_reason!,\n      options.responseFormat.type === \"json\"\n    )\n\n    parts.push({\n      type: \"finish\",\n      reason: finishReason,\n      usage: {\n        inputTokens: response.usage.input_tokens,\n        outputTokens: response.usage.output_tokens,\n        totalTokens: response.usage.input_tokens + response.usage.output_tokens,\n        cachedInputTokens: response.usage.cache_read_input_tokens ?? undefined\n      },\n      metadata: {\n        anthropic: {\n          usage: response.usage,\n          stopSequence: response.stop_sequence ?? undefined\n        }\n      }\n    })\n\n    return parts\n  }\n)\n\nconst makeStreamResponse: (\n  stream: Stream.Stream<MessageStreamEvent, AiError.AiError>,\n  options: LanguageModel.ProviderOptions\n) => Effect.Effect<\n  Stream.Stream<Response.StreamPartEncoded, AiError.AiError>,\n  never,\n  IdGenerator.IdGenerator\n> = Effect.fnUntraced(\n  function*(stream, options) {\n    const idGenerator = yield* IdGenerator.IdGenerator\n    const citableDocuments = extractCitableDocuments(options.prompt)\n\n    // Setup all requisite state for the streaming response\n    let finishReason: Response.FinishReason = \"unknown\"\n    const contentBlocks: Record<\n      number,\n      | {\n        readonly type: \"text\"\n      }\n      | {\n        readonly type: \"reasoning\"\n      }\n      | {\n        readonly type: \"tool-call\"\n        readonly id: string\n        readonly name: string\n        params: string\n        readonly providerName: string | undefined\n        readonly providerExecuted: boolean\n      }\n    > = {}\n    let blockType:\n      | \"text\"\n      | \"thinking\"\n      | \"redacted_thinking\"\n      | \"tool_use\"\n      | \"server_tool_use\"\n      | \"web_fetch_tool_result\"\n      | \"web_search_tool_result\"\n      | \"code_execution_tool_result\"\n      | \"bash_code_execution_tool_result\"\n      | \"text_editor_code_execution_tool_result\"\n      | \"mcp_tool_use\"\n      | \"mcp_tool_result\"\n      | \"container_upload\"\n      | undefined = undefined\n    const usage: Mutable<typeof Response.Usage.Encoded> = {\n      inputTokens: undefined,\n      outputTokens: undefined,\n      totalTokens: undefined\n    }\n    let metaUsage: Generated.BetaUsage | undefined = undefined\n    let stopSequence: string | undefined = undefined\n\n    return stream.pipe(\n      Stream.mapEffect(Effect.fnUntraced(function*(event) {\n        const parts: Array<Response.StreamPartEncoded> = []\n\n        switch (event.type) {\n          case \"ping\": {\n            break\n          }\n\n          case \"message_start\": {\n            // Track usage metadata\n            usage.inputTokens = event.message.usage.input_tokens\n            metaUsage = event.message.usage\n\n            // Track response metadata\n            parts.push({\n              type: \"response-metadata\",\n              id: event.message.id,\n              modelId: event.message.model,\n              timestamp: DateTime.formatIso(yield* DateTime.now)\n            })\n\n            break\n          }\n\n          case \"message_delta\": {\n            // Track usage metadata\n            if (Predicate.isNotNullable(event.usage.output_tokens)) {\n              usage.outputTokens = event.usage.output_tokens\n            }\n            usage.totalTokens = (usage.inputTokens ?? 0) + (event.usage.output_tokens ?? 0)\n\n            // Track stop sequence metadata\n            if (Predicate.isNotNullable(event.delta.stop_sequence)) {\n              stopSequence = event.delta.stop_sequence\n            }\n\n            // Track the response finish reason\n            if (Predicate.isNotNullable(event.delta.stop_reason)) {\n              finishReason = InternalUtilities.resolveFinishReason(event.delta.stop_reason)\n            }\n\n            break\n          }\n\n          case \"message_stop\": {\n            parts.push({\n              type: \"finish\",\n              reason: finishReason,\n              usage,\n              metadata: { anthropic: { usage: metaUsage, stopSequence } }\n            })\n\n            break\n          }\n\n          case \"content_block_start\": {\n            blockType = event.content_block.type\n\n            switch (event.content_block.type) {\n              case \"text\": {\n                contentBlocks[event.index] = { type: \"text\" }\n\n                parts.push({\n                  type: \"text-start\",\n                  id: event.index.toString()\n                })\n\n                break\n              }\n\n              case \"thinking\": {\n                contentBlocks[event.index] = { type: \"reasoning\" }\n\n                parts.push({\n                  type: \"reasoning-start\",\n                  id: event.index.toString()\n                })\n\n                break\n              }\n\n              case \"redacted_thinking\": {\n                contentBlocks[event.index] = { type: \"reasoning\" }\n\n                parts.push({\n                  type: \"reasoning-start\",\n                  id: event.index.toString(),\n                  metadata: {\n                    anthropic: {\n                      type: \"redacted_thinking\",\n                      redactedData: event.content_block.data\n                    }\n                  }\n                })\n\n                break\n              }\n\n              case \"tool_use\": {\n                const toolName = event.content_block.name\n                const providerTool = AnthropicTool.getProviderDefinedToolName(toolName)\n                const name = Predicate.isNotUndefined(providerTool) ? providerTool : toolName\n                const providerName = Predicate.isNotUndefined(providerTool) ? toolName : undefined\n\n                contentBlocks[event.index] = {\n                  type: \"tool-call\",\n                  id: event.content_block.id,\n                  name,\n                  params: \"\",\n                  providerName,\n                  providerExecuted: false\n                }\n\n                parts.push({\n                  type: \"tool-params-start\",\n                  id: event.content_block.id,\n                  name: toolName,\n                  providerName,\n                  providerExecuted: false\n                })\n\n                break\n              }\n\n              case \"server_tool_use\": {\n                const toolName = event.content_block.name\n                const providerTool = AnthropicTool.getProviderDefinedToolName(toolName)\n                if (Predicate.isNotUndefined(providerTool)) {\n                  contentBlocks[event.index] = {\n                    type: \"tool-call\",\n                    id: event.content_block.id,\n                    name: providerTool,\n                    params: \"\",\n                    providerName: toolName,\n                    providerExecuted: true\n                  }\n\n                  parts.push({\n                    type: \"tool-params-start\",\n                    id: event.content_block.id,\n                    name: providerTool,\n                    providerName: toolName,\n                    providerExecuted: true\n                  })\n                }\n\n                break\n              }\n\n              case \"bash_code_execution_tool_result\": {\n                const toolUseId = event.content_block.tool_use_id\n                const content = event.content_block.content\n                const isFailure = content.type === \"bash_code_execution_tool_result_error\"\n                parts.push({\n                  type: \"tool-result\",\n                  id: toolUseId,\n                  name: \"AnthropicCodeExecution\",\n                  isFailure,\n                  result: content,\n                  providerName: \"code_execution\",\n                  providerExecuted: true\n                })\n                break\n              }\n\n              case \"code_execution_tool_result\": {\n                const toolUseId = event.content_block.tool_use_id\n                const content = event.content_block.content\n                const isFailure = content.type === \"code_execution_tool_result_error\"\n                parts.push({\n                  type: \"tool-result\",\n                  id: toolUseId,\n                  name: \"AnthropicCodeExecution\",\n                  isFailure,\n                  result: content,\n                  providerName: \"code_execution\",\n                  providerExecuted: true\n                })\n                break\n              }\n\n              case \"text_editor_code_execution_tool_result\": {\n                const toolUseId = event.content_block.tool_use_id\n                const content = event.content_block.content\n                const isFailure = content.type === \"text_editor_code_execution_tool_result_error\"\n                parts.push({\n                  type: \"tool-result\",\n                  id: toolUseId,\n                  name: \"AnthropicCodeExecution\",\n                  isFailure,\n                  result: content,\n                  providerName: \"code_execution\",\n                  providerExecuted: true\n                })\n                break\n              }\n\n              case \"web_search_tool_result\": {\n                const toolUseId = event.content_block.tool_use_id\n                const content = event.content_block.content\n                const isFailure = !Array.isArray(content)\n                parts.push({\n                  type: \"tool-result\",\n                  id: toolUseId,\n                  name: \"AnthropicWebSearch\",\n                  isFailure,\n                  result: content,\n                  providerName: \"web_search\",\n                  providerExecuted: true\n                })\n                break\n              }\n            }\n\n            break\n          }\n\n          case \"content_block_delta\": {\n            switch (event.delta.type) {\n              case \"text_delta\": {\n                parts.push({\n                  type: \"text-delta\",\n                  id: event.index.toString(),\n                  delta: event.delta.text\n                })\n\n                break\n              }\n\n              case \"thinking_delta\": {\n                parts.push({\n                  type: \"reasoning-delta\",\n                  id: event.index.toString(),\n                  delta: event.delta.thinking\n                })\n\n                break\n              }\n\n              case \"signature_delta\": {\n                if (blockType === \"thinking\") {\n                  parts.push({\n                    type: \"reasoning-delta\",\n                    id: event.index.toString(),\n                    delta: \"\",\n                    metadata: {\n                      anthropic: {\n                        type: \"thinking\",\n                        signature: event.delta.signature\n                      }\n                    }\n                  })\n                }\n\n                break\n              }\n\n              case \"input_json_delta\": {\n                const contentBlock = contentBlocks[event.index]\n                const delta = event.delta.partial_json\n\n                if (contentBlock.type === \"tool-call\") {\n                  parts.push({\n                    type: \"tool-params-delta\",\n                    id: contentBlock.id,\n                    delta\n                  })\n\n                  contentBlock.params += delta\n                }\n\n                break\n              }\n\n              case \"citations_delta\": {\n                const citation = event.delta.citation\n\n                const source = yield* processCitation(citation, citableDocuments, idGenerator)\n                if (Predicate.isNotUndefined(source)) {\n                  parts.push(source)\n                }\n              }\n            }\n\n            break\n          }\n\n          case \"content_block_stop\": {\n            if (Predicate.isNotNullable(contentBlocks[event.index])) {\n              const contentBlock = contentBlocks[event.index]\n\n              switch (contentBlock.type) {\n                case \"text\": {\n                  parts.push({\n                    type: \"text-end\",\n                    id: event.index.toString()\n                  })\n                  break\n                }\n\n                case \"reasoning\": {\n                  parts.push({\n                    type: \"reasoning-end\",\n                    id: event.index.toString()\n                  })\n                  break\n                }\n\n                case \"tool-call\": {\n                  parts.push({\n                    type: \"tool-params-end\",\n                    id: contentBlock.id\n                  })\n\n                  const toolName = contentBlock.name\n                  // If the tool call has no parameters, an empty string is returned\n                  const toolParams = contentBlock.params.length === 0 ? \"{}\" : contentBlock.params\n\n                  const parsedParams = yield* Effect.try({\n                    try: () => Tool.unsafeSecureJsonParse(toolParams),\n                    catch: (cause) =>\n                      new AiError.MalformedOutput({\n                        module: \"AnthropicLanguageModel\",\n                        method: \"makeStreamResponse\",\n                        description: \"Failed to securely parse tool call parameters \" +\n                          `for tool '${toolName}':\\nParameters: ${toolParams}`,\n                        cause\n                      })\n                  })\n\n                  parts.push({\n                    type: \"tool-call\",\n                    id: contentBlock.id,\n                    name: toolName,\n                    params: parsedParams,\n                    providerName: contentBlock.providerName,\n                    providerExecuted: contentBlock.providerExecuted\n                  })\n\n                  break\n                }\n              }\n\n              delete contentBlocks[event.index]\n            }\n\n            blockType = undefined\n\n            break\n          }\n\n          case \"error\": {\n            parts.push({ type: \"error\", error: event.error })\n\n            break\n          }\n        }\n\n        return parts\n      })),\n      Stream.flattenIterables\n    )\n  }\n)\n\n// =============================================================================\n// Telemetry\n// =============================================================================\n\nconst annotateRequest = (\n  span: Span,\n  request: typeof Generated.BetaCreateMessageParams.Encoded\n): void => {\n  addGenAIAnnotations(span, {\n    system: \"anthropic\",\n    operation: { name: \"chat\" },\n    request: {\n      model: request.model,\n      temperature: request.temperature,\n      topK: request.top_k,\n      topP: request.top_p,\n      maxTokens: request.max_tokens,\n      stopSequences: Arr.ensure(request.stop_sequences).filter(\n        Predicate.isNotNullable\n      )\n    }\n  })\n}\n\nconst annotateResponse = (span: Span, response: Generated.BetaMessage): void => {\n  addGenAIAnnotations(span, {\n    response: {\n      id: response.id,\n      model: response.model,\n      finishReasons: response.stop_reason ? [response.stop_reason] : undefined\n    },\n    usage: {\n      inputTokens: response.usage.input_tokens,\n      outputTokens: response.usage.output_tokens\n    }\n  })\n}\n\nconst annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded) => {\n  if (part.type === \"response-metadata\") {\n    addGenAIAnnotations(span, {\n      response: {\n        id: part.id,\n        model: part.modelId\n      }\n    })\n  }\n  if (part.type === \"finish\") {\n    addGenAIAnnotations(span, {\n      response: {\n        finishReasons: [part.reason]\n      },\n      usage: {\n        inputTokens: part.usage.inputTokens,\n        outputTokens: part.usage.outputTokens\n      }\n    })\n  }\n}\n\n// =============================================================================\n// Tool Calling\n// =============================================================================\n\n/**\n * Represents all possible Anthropic provider-defined tools.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type AnthropicTools =\n  | typeof Generated.BetaTool.Encoded\n  | typeof Generated.BetaBashTool20241022.Encoded\n  | typeof Generated.BetaBashTool20250124.Encoded\n  | typeof Generated.BetaComputerUseTool20241022.Encoded\n  | typeof Generated.BetaComputerUseTool20250124.Encoded\n  | typeof Generated.BetaTextEditor20241022.Encoded\n  | typeof Generated.BetaTextEditor20250124.Encoded\n  | typeof Generated.BetaTextEditor20250429.Encoded\n  | typeof Generated.BetaTextEditor20250728.Encoded\n\n/**\n * A helper method which takes in large language model provider options from\n * the base Effect AI SDK as well as Anthropic request configuration options\n * and returns the prepared tools, tool choice, and Anthropic betas to include\n * in a request.\n *\n * This method is primarily exposed for use by other Effect provider\n * integrations which can utilize Anthropic models (i.e. Amazon Bedrock).\n *\n * @since 1.0.0\n * @category Tool Calling\n */\nexport const prepareTools: (options: LanguageModel.ProviderOptions, config: Config.Service) => Effect.Effect<{\n  readonly betas: ReadonlySet<string>\n  readonly tools: ReadonlyArray<AnthropicTools> | undefined\n  readonly toolChoice: typeof Generated.BetaToolChoice.Encoded | undefined\n}, AiError.AiError> = Effect.fnUntraced(function*(options, config) {\n  // Return immediately if no tools are in the toolkit or a tool choice of\n  // \"none\" was specified\n  if (options.tools.length === 0 || options.toolChoice === \"none\") {\n    return { betas: new Set(), tools: undefined, toolChoice: undefined }\n  }\n\n  const betas = new Set<string>()\n  let tools: Array<AnthropicTools> = []\n  let toolChoice: typeof Generated.BetaToolChoice.Encoded | undefined = undefined\n\n  // Convert the tools in the toolkit to the provider-defined format\n  for (const tool of options.tools) {\n    if (Tool.isUserDefined(tool)) {\n      tools.push({\n        name: tool.name,\n        description: Tool.getDescription(tool as any),\n        input_schema: Tool.getJsonSchema(tool as any) as any\n      })\n    }\n\n    if (Tool.isProviderDefined(tool)) {\n      switch (tool.id) {\n        case \"anthropic.bash_20241022\": {\n          betas.add(\"computer-use-2024-10-22\")\n          tools.push({\n            name: \"bash\",\n            type: \"bash_20241022\"\n          })\n          break\n        }\n        case \"anthropic.bash_20250124\": {\n          betas.add(\"computer-use-2025-01-24\")\n          tools.push({\n            name: \"bash\",\n            type: \"bash_20250124\"\n          })\n          break\n        }\n        case \"anthropic.code_execution_20250522\": {\n          betas.add(\"code-execution-2025-05-22\")\n          tools.push({\n            ...tool.args,\n            name: \"code_execution\",\n            type: \"code_execution_2025522\"\n          })\n          break\n        }\n        case \"anthropic.code_execution_20250825\": {\n          betas.add(\"code-execution-2025-08-25\")\n          tools.push({\n            ...tool.args,\n            name: \"code_execution\",\n            type: \"code_execution_20250825\"\n          })\n          break\n        }\n        case \"anthropic.computer_use_20241022\": {\n          betas.add(\"computer-use-2025-10-22\")\n          tools.push({\n            ...tool.args,\n            name: \"computer\",\n            type: \"computer_20241022\"\n          })\n          break\n        }\n        case \"anthropic.computer_use_20250124\": {\n          betas.add(\"computer-use-2025-01-24\")\n          tools.push({\n            ...tool.args,\n            name: \"computer\",\n            type: \"computer_20250124\"\n          })\n          break\n        }\n        case \"anthropic.text_editor_20241022\": {\n          betas.add(\"computer-use-2024-10-22\")\n          tools.push({\n            name: \"str_replace_editor\",\n            type: \"text_editor_20241022\"\n          })\n          break\n        }\n        case \"anthropic.text_editor_20250124\": {\n          betas.add(\"computer-use-2025-01-24\")\n          tools.push({\n            name: \"str_replace_editor\",\n            type: \"text_editor_20250124\"\n          })\n          break\n        }\n        case \"anthropic.text_editor_20250429\": {\n          betas.add(\"computer-use-2025-01-24\")\n          tools.push({\n            name: \"str_replace_based_edit_tool\",\n            type: \"text_editor_20250429\"\n          })\n          break\n        }\n        case \"anthropic.text_editor_20250728\": {\n          tools.push({\n            name: \"str_replace_based_edit_tool\",\n            type: \"text_editor_20250728\"\n          })\n          break\n        }\n        case \"anthropic.web_search_20250305\": {\n          tools.push({\n            ...tool.args,\n            name: \"web_search\",\n            type: \"web_search_20250305\"\n          })\n          break\n        }\n        default: {\n          return yield* new AiError.MalformedInput({\n            module: \"AnthropicLanguageModel\",\n            method: \"prepareTools\",\n            description: `Received request to call unknown provider-defined tool '${tool.name}'`\n          })\n        }\n      }\n    }\n  }\n\n  // Convert the tool choice to the provider-defined format\n  if (options.toolChoice === \"auto\") {\n    toolChoice = {\n      type: \"auto\",\n      disable_parallel_tool_use: config.disableParallelToolCalls\n    }\n  } else if (options.toolChoice === \"required\") {\n    toolChoice = {\n      type: \"any\",\n      disable_parallel_tool_use: config.disableParallelToolCalls\n    }\n  } else if (\"tool\" in options.toolChoice) {\n    toolChoice = {\n      type: \"tool\",\n      name: options.toolChoice.tool,\n      disable_parallel_tool_use: config.disableParallelToolCalls\n    }\n  } else {\n    const allowedTools = new Set(options.toolChoice.oneOf)\n    tools = tools.filter((tool) => allowedTools.has(tool.name))\n    toolChoice = {\n      type: options.toolChoice.mode === \"required\" ? \"any\" : \"auto\",\n      disable_parallel_tool_use: config.disableParallelToolCalls\n    }\n  }\n\n  return { betas, tools, toolChoice }\n})\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\ntype ContentGroup = SystemMessageGroup | AssistantMessageGroup | UserMessageGroup\n\ninterface SystemMessageGroup {\n  readonly type: \"system\"\n  readonly messages: Array<Prompt.SystemMessage>\n}\n\ninterface AssistantMessageGroup {\n  readonly type: \"assistant\"\n  readonly messages: Array<Prompt.AssistantMessage>\n}\n\ninterface UserMessageGroup {\n  readonly type: \"user\"\n  readonly messages: Array<Prompt.ToolMessage | Prompt.UserMessage>\n}\n\nconst groupMessages = (prompt: Prompt.Prompt): Array<ContentGroup> => {\n  const messages: Array<ContentGroup> = []\n  let current: ContentGroup | undefined = undefined\n  for (const message of prompt.content) {\n    switch (message.role) {\n      case \"system\": {\n        if (current?.type !== \"system\") {\n          current = { type: \"system\", messages: [] }\n          messages.push(current)\n        }\n        current.messages.push(message)\n        break\n      }\n      case \"assistant\": {\n        if (current?.type !== \"assistant\") {\n          current = { type: \"assistant\", messages: [] }\n          messages.push(current)\n        }\n        current.messages.push(message)\n        break\n      }\n      case \"tool\":\n      case \"user\": {\n        if (current?.type !== \"user\") {\n          current = { type: \"user\", messages: [] }\n          messages.push(current)\n        }\n        current.messages.push(message)\n        break\n      }\n    }\n  }\n  return messages\n}\n\nconst isCitationPart = (part: Prompt.UserMessage[\"content\"][number]): part is Prompt.FilePart => {\n  if (part.type === \"file\" && (part.mediaType === \"application/pdf\" || part.mediaType === \"text/plain\")) {\n    return part.options.anthropic?.citations?.enabled ?? false\n  }\n  return false\n}\n\ninterface CitableDocument {\n  readonly title: string\n  readonly fileName: string | undefined\n  readonly mediaType: string\n}\n\nconst extractCitableDocuments = (prompt: Prompt.Prompt): ReadonlyArray<CitableDocument> => {\n  const citableDocuments: Array<CitableDocument> = []\n  for (const message of prompt.content) {\n    if (message.role === \"user\") {\n      for (const part of message.content) {\n        if (isCitationPart(part)) {\n          citableDocuments.push({\n            title: part.fileName ?? \"Untitled Document\",\n            fileName: part.fileName,\n            mediaType: part.mediaType\n          })\n        }\n      }\n    }\n  }\n  return citableDocuments\n}\n\nconst getCacheControl = (\n  part:\n    | Prompt.SystemMessage\n    | Prompt.UserMessage\n    | Prompt.AssistantMessage\n    | Prompt.ToolMessage\n    | Prompt.UserMessagePart\n    | Prompt.AssistantMessagePart\n    | Prompt.ToolMessagePart\n): typeof Generated.CacheControlEphemeral.Encoded | undefined => part.options.anthropic?.cacheControl\n\nconst getDocumentMetadata = (part: Prompt.FilePart): {\n  readonly title: string | undefined\n  readonly context: string | undefined\n} | undefined => {\n  const options = part.options.anthropic\n  if (Predicate.isNotUndefined(options)) {\n    return {\n      title: options.documentTitle,\n      context: options.documentContext\n    }\n  }\n  return undefined\n}\n\nconst shouldEnableCitations = (part: Prompt.FilePart): boolean => part.options.anthropic?.citations?.enabled ?? false\n\nconst processCitation: (\n  citation:\n    | Generated.ResponseCharLocationCitation\n    | Generated.ResponsePageLocationCitation\n    | Generated.ResponseContentBlockLocationCitation\n    | Generated.ResponseWebSearchResultLocationCitation\n    | Generated.ResponseSearchResultLocationCitation,\n  citableDocuments: ReadonlyArray<CitableDocument>,\n  idGenerator: IdGenerator.Service\n) => Effect.Effect<Response.DocumentSourcePartEncoded | Response.UrlSourcePartEncoded | undefined> = Effect.fnUntraced(\n  function*(citation, citableDocuments, idGenerator) {\n    if (citation.type === \"page_location\" || citation.type === \"char_location\") {\n      const citedDocument = citableDocuments[citation.document_index]\n      if (Predicate.isNotUndefined(citedDocument)) {\n        const id = yield* idGenerator.generateId()\n\n        const metadata = citation.type === \"char_location\"\n          ? {\n            source: \"document\",\n            type: citation.type,\n            citedText: citation.cited_text,\n            startCharIndex: citation.start_char_index,\n            endCharIndex: citation.end_char_index\n          } as const\n          : {\n            source: \"document\",\n            type: citation.type,\n            citedText: citation.cited_text,\n            startPageNumber: citation.start_page_number,\n            endPageNumber: citation.end_page_number\n          } as const\n\n        return {\n          type: \"source\",\n          sourceType: \"document\",\n          id,\n          mediaType: citedDocument.mediaType,\n          title: citation.document_title ?? citedDocument.title,\n          fileName: citedDocument.fileName,\n          metadata: { anthropic: metadata }\n        }\n      }\n    }\n\n    if (citation.type === \"web_search_result_location\") {\n      const id = yield* idGenerator.generateId()\n\n      const metadata = {\n        source: \"url\",\n        citedText: citation.cited_text,\n        encryptedIndex: citation.encrypted_index\n      } as const\n\n      return {\n        type: \"source\",\n        sourceType: \"url\",\n        id,\n        url: citation.url,\n        title: citation.title ?? \"Untitled\",\n        metadata: { anthropic: metadata }\n      }\n    }\n  }\n)\n"
  },
  {
    "path": "packages/ai/anthropic/src/AnthropicTokenizer.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport { getTokenizer } from \"@anthropic-ai/tokenizer\"\nimport * as AiError from \"@effect/ai/AiError\"\nimport type * as Prompt from \"@effect/ai/Prompt\"\nimport * as Tokenizer from \"@effect/ai/Tokenizer\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Tokenizer.make({\n  tokenize(prompt) {\n    return Effect.try({\n      try: () => {\n        const tokenizer = getTokenizer()\n        const text = Arr.flatMap(prompt.content, (message) =>\n          Arr.filterMap(\n            message.content as Array<\n              | Prompt.AssistantMessagePart\n              | Prompt.ToolMessagePart\n              | Prompt.UserMessagePart\n            >,\n            (part) => {\n              if (part.type === \"file\" || part.type === \"reasoning\") {\n                return Option.none()\n              }\n              return Option.some(\n                part.type === \"text\"\n                  ? part.text\n                  : JSON.stringify(part.type === \"tool-call\" ? part.params : part.result)\n              )\n            }\n          )).join(\"\")\n        const encoded = tokenizer.encode(text.normalize(\"NFKC\"), \"all\")\n        tokenizer.free()\n        return Array.from(encoded)\n      },\n      catch: (cause) =>\n        new AiError.UnknownError({\n          module: \"AnthropicTokenizer\",\n          method: \"tokenize\",\n          description: \"Could not tokenize\",\n          cause\n        })\n    })\n  }\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer: Layer.Layer<Tokenizer.Tokenizer> = Layer.succeed(Tokenizer.Tokenizer, make)\n"
  },
  {
    "path": "packages/ai/anthropic/src/AnthropicTool.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Tool from \"@effect/ai/Tool\"\nimport * as Schema from \"effect/Schema\"\nimport * as Struct from \"effect/Struct\"\nimport * as Generated from \"./Generated.js\"\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const ProviderDefinedTools: Schema.Union<[\n  typeof Generated.BetaBashTool20241022,\n  typeof Generated.BetaBashTool20250124,\n  typeof Generated.BetaCodeExecutionTool20250522,\n  typeof Generated.BetaComputerUseTool20241022,\n  typeof Generated.BetaComputerUseTool20250124,\n  typeof Generated.BetaTextEditor20241022,\n  typeof Generated.BetaTextEditor20250124,\n  typeof Generated.BetaTextEditor20250429,\n  typeof Generated.BetaTextEditor20250728,\n  typeof Generated.BetaWebSearchTool20250305\n]> = Schema.Union(\n  Generated.BetaBashTool20241022,\n  Generated.BetaBashTool20250124,\n  Generated.BetaCodeExecutionTool20250522,\n  Generated.BetaComputerUseTool20241022,\n  Generated.BetaComputerUseTool20250124,\n  Generated.BetaTextEditor20241022,\n  Generated.BetaTextEditor20250124,\n  Generated.BetaTextEditor20250429,\n  Generated.BetaTextEditor20250728,\n  Generated.BetaWebSearchTool20250305\n)\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport type ProviderDefinedTools = typeof ProviderDefinedTools.Type\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const Bash_20241022 = Tool.providerDefined({\n  id: \"anthropic.bash_20241022\",\n  toolkitName: \"AnthropicBash\",\n  providerName: \"bash\",\n  args: {},\n  requiresHandler: true,\n  success: Schema.String,\n  parameters: {\n    /**\n     * The Bash command to run.\n     */\n    command: Schema.NonEmptyString,\n    /**\n     * If `true`, restart the Bash session.\n     */\n    restart: Schema.optional(Schema.Boolean)\n  }\n})\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const Bash_20250124 = Tool.providerDefined({\n  id: \"anthropic.bash_20250124\",\n  toolkitName: \"AnthropicBash\",\n  providerName: \"bash\",\n  args: {},\n  requiresHandler: true,\n  success: Schema.String,\n  parameters: {\n    /**\n     * The Bash command to run.\n     */\n    command: Schema.NonEmptyString,\n    /**\n     * If `true`, restart the Bash session.\n     */\n    restart: Schema.optional(Schema.Boolean)\n  }\n})\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const CodeExecution_20250522 = Tool.providerDefined({\n  id: \"anthropic.code_execution_20250522\",\n  toolkitName: \"AnthropicCodeExecution\",\n  providerName: \"code_execution\",\n  args: Struct.omit(Generated.BetaCodeExecutionTool20250522.fields, \"name\", \"type\"),\n  success: Generated.BetaResponseCodeExecutionResultBlock,\n  failure: Generated.BetaResponseCodeExecutionToolResultError\n})\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const CodeExecution_20250825 = Tool.providerDefined({\n  id: \"anthropic.code_execution_20250825\",\n  toolkitName: \"AnthropicCodeExecution\",\n  providerName: \"code_execution\",\n  args: Struct.omit(Generated.BetaCodeExecutionTool20250825.fields, \"name\", \"type\"),\n  success: Schema.Union(\n    Generated.BetaResponseBashCodeExecutionResultBlock,\n    Generated.BetaResponseTextEditorCodeExecutionViewResultBlock,\n    Generated.BetaResponseTextEditorCodeExecutionCreateResultBlock,\n    Generated.BetaResponseTextEditorCodeExecutionStrReplaceResultBlock\n  ),\n  failure: Schema.Union(\n    Generated.BetaResponseCodeExecutionToolResultError,\n    Generated.BetaResponseTextEditorCodeExecutionToolResultError\n  )\n})\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport const Coordinate = Schema.Tuple(Schema.Number, Schema.Number)\n\n/**\n * Allow Claude to interact with computer environments through the computer use\n * tool, which provides screenshot capabilities and mouse/keyboard control for\n * autonomous desktop interaction.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport const ComputerUse_20241022 = Tool.providerDefined({\n  id: \"anthropic.computer_use_20241022\",\n  toolkitName: \"AnthropicComputerUse\",\n  providerName: \"computer\",\n  args: Struct.omit(Generated.BetaComputerUseTool20241022.fields, \"name\", \"type\"),\n  requiresHandler: true,\n  success: Schema.String,\n  parameters: {\n    /**\n     * The action to perform. The available actions are:\n     * - `screenshot`: Take a screenshot of the screen.\n     * - `left_click`: Click the left mouse button at the specified (x, y) pixel\n     *   coordinate on the screen. You can also include a key combination to\n     *   hold down while clicking using the `text` parameter.\n     * - `type`: Type a string of text on the keyboard.\n     * - `key`: Press a key or key-combination on the keyboard.\n     *   - This supports xdotool's `key` syntax.\n     *   - Examples: \"a\", \"Return\", \"alt+Tab\", \"ctrl+s\", \"Up\", \"KP_0\" (for the\n     *     numpad 0 key).\n     * - `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on\n     *   the screen.\n     */\n    action: Schema.Literal(\n      \"screenshot\",\n      \"left_click\",\n      \"type\",\n      \"key\",\n      \"mouse_move\"\n    ),\n    /**\n     * The x (pixels from the left edge) and y (pixels from the top edge)\n     * coordinates to move the mouse to. Required only by `action=mouse_move`.\n     */\n    coordinate: Schema.optional(Coordinate),\n    /**\n     * Required only by `action=type` and `action=key`.\n     */\n    text: Schema.optional(Schema.String)\n  }\n})\n\n/**\n * Allow Claude to interact with computer environments through the computer use\n * tool, which provides screenshot capabilities and mouse/keyboard control for\n * autonomous desktop interaction.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport const ComputerUse_20250124 = Tool.providerDefined({\n  id: \"anthropic.computer_use_20250124\",\n  toolkitName: \"AnthropicComputerUse\",\n  providerName: \"computer\",\n  args: Struct.omit(Generated.BetaComputerUseTool20241022.fields, \"name\", \"type\"),\n  requiresHandler: true,\n  success: Schema.String,\n  parameters: {\n    /**\n     * The action to perform. The available actions are:\n     * - `screenshot`: Take a screenshot of the screen.\n     * - `left_click`: Click the left mouse button at the specified (x, y) pixel\n     *   coordinate on the screen. You can also include a key combination to\n     *   hold down while clicking using the `text` parameter.\n     * - `type`: Type a string of text on the keyboard.\n     * - `key`: Press a key or key-combination on the keyboard.\n     *   - This supports xdotool's `key` syntax.\n     *   - Examples: \"a\", \"Return\", \"alt+Tab\", \"ctrl+s\", \"Up\", \"KP_0\" (for the\n     *     numpad 0 key).\n     * - `mouse_move`: Move the cursor to a specified (x, y) pixel coordinate on\n     * - `scroll`: Scroll the screen in a specified direction by a specified\n     *   amount of clicks of the scroll wheel, at the specified (x, y) pixel\n     *   coordinate. DO NOT use PageUp/PageDown to scroll.\n     * - `left_click_drag`: Click and drag the cursor from `start_coordinate`\n     *   to a specified (x, y) pixel coordinate on the screen.\n     *   the screen.\n     * - `middle_click`: Click the middle mouse button at the specified (x, y)\n     *   pixel coordinate on the screen.\n     * - `right_click`: Click the right mouse button at the specified (x, y)\n     *   pixel coordinate on the screen.\n     * - `double_click`: Double-click the left mouse button at the specified\n     *   (x, y) pixel coordinate on the screen.\n     * - `triple_click`: Triple-click the left mouse button at the specified\n     *   (x, y) pixel coordinate on the screen.\n     * - `left_mouse_down`: Press the left mouse button.\n     * - `left_mouse_up`: Release the left mouse button.\n     * - `hold_key`: Hold down a key or multiple keys for a specified duration\n     *   (in seconds). Supports the same syntax as `key`.\n     * - `wait`: Wait for a specified duration (in seconds).\n     */\n    action: Schema.Literal(\n      \"screenshot\",\n      \"left_click\",\n      \"type\",\n      \"key\",\n      \"mouse_move\",\n      \"scroll\",\n      \"left_click_drag\",\n      \"middle_click\",\n      \"right_click\",\n      \"double_click\",\n      \"triple_click\",\n      \"left_mouse_down\",\n      \"left_mouse_up\",\n      \"hold_key\",\n      \"wait\"\n    ),\n    /**\n     * The x (pixels from the left edge) and y (pixels from the top edge)\n     * coordinates to move the mouse to. Required only by `action=mouse_move`\n     * and `action=left_click_drag`.\n     */\n    coordinate: Schema.optional(Coordinate),\n    /**\n     * The x (pixels from the left edge) and y (pixels from the top edge)\n     * coordinates to start the drag from. Required only by\n     * `action=left_click_drag`.\n     */\n    start_coordinate: Schema.optional(Coordinate),\n    /**\n     * Required only by `action=type`, `action=key`, and `action=hold_key`. Can\n     * also be used by click or scroll actions to hold down keys while clicking\n     * or scrolling.\n     */\n    text: Schema.optional(Schema.String),\n    /**\n     * The direction to scroll the screen. Required only by `action=scroll`.\n     */\n    scroll_direction: Schema.optional(Schema.Literal(\"up\", \"down\", \"left\", \"right\")),\n    /**\n     * The number of \"clicks\" of the scroll wheel to scroll. Required only by\n     * `action=scroll`.\n     */\n    scroll_amount: Schema.optional(Schema.Number),\n    /**\n     * The duration to hold the key down for. Required only by `action=hold_key`\n     * and `action=wait`.\n     */\n    duration: Schema.optional(Schema.Number)\n  }\n})\n\n/**\n * Allow Claude to directly interact with your files, providing hands-on\n * assistance rather than just suggesting changes.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport const TextEditor_20241022 = Tool.providerDefined({\n  id: \"anthropic.text_editor_20241022\",\n  toolkitName: \"AnthropicTextEditor\",\n  providerName: \"str_replace_editor\",\n  args: {},\n  requiresHandler: true,\n  parameters: {\n    /**\n     * The command to run.\n     */\n    command: Schema.Literal(\n      \"view\",\n      \"create\",\n      \"str_replace\",\n      \"insert\",\n      \"undo_edit\"\n    ),\n    /**\n     * Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.\n     */\n    path: Schema.String,\n    /**\n     * Required parameter of `create` command, with the content of the file to\n     * be created.\n     */\n    file_text: Schema.optional(Schema.String),\n    /**\n     * Required parameter of `insert` command. The `new_str` will be inserted\n     * AFTER the line `insert_line` of `path`.\n     */\n    insert_line: Schema.optional(Schema.Number),\n    /**\n     * Optional parameter of `str_replace` command containing the new string (if\n     * not given, no string will be added). Required parameter of `insert`\n     * command containing the string to insert.\n     */\n    new_str: Schema.optional(Schema.String),\n    /**\n     * Required parameter of `str_replace` command containing the string in\n     * `path` to replace.\n     */\n    old_str: Schema.optional(Schema.String),\n    /**\n     * Optional parameter of `view` command when `path` points to a file. If\n     * none is given, the full file is shown. If provided, the file will be\n     * shown in the indicated line number range, e.g. [11, 12] will show lines\n     * 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all\n     * lines from `start_line` to the end of the file.\n     */\n    view_range: Schema.optional(Schema.Array(Schema.Number))\n  }\n})\n\n/**\n * Allow Claude to directly interact with your files, providing hands-on\n * assistance rather than just suggesting changes.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport const TextEditor_20250124 = Tool.providerDefined({\n  id: \"anthropic.text_editor_20250124\",\n  toolkitName: \"AnthropicTextEditor\",\n  providerName: \"str_replace_editor\",\n  args: {},\n  requiresHandler: true,\n  parameters: {\n    /**\n     * The command to run.\n     */\n    command: Schema.Literal(\n      \"view\",\n      \"create\",\n      \"str_replace\",\n      \"insert\",\n      \"undo_edit\"\n    ),\n    /**\n     * Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.\n     */\n    path: Schema.String,\n    /**\n     * Required parameter of `create` command, with the content of the file to\n     * be created.\n     */\n    file_text: Schema.optional(Schema.String),\n    /**\n     * Required parameter of `insert` command. The `new_str` will be inserted\n     * AFTER the line `insert_line` of `path`.\n     */\n    insert_line: Schema.optional(Schema.Number),\n    /**\n     * Optional parameter of `str_replace` command containing the new string (if\n     * not given, no string will be added). Required parameter of `insert`\n     * command containing the string to insert.\n     */\n    new_str: Schema.optional(Schema.String),\n    /**\n     * Required parameter of `str_replace` command containing the string in\n     * `path` to replace.\n     */\n    old_str: Schema.optional(Schema.String),\n    /**\n     * Optional parameter of `view` command when `path` points to a file. If\n     * none is given, the full file is shown. If provided, the file will be\n     * shown in the indicated line number range, e.g. [11, 12] will show lines\n     * 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all\n     * lines from `start_line` to the end of the file.\n     */\n    view_range: Schema.optional(Schema.Array(Schema.Number))\n  }\n})\n\n/**\n * Allow Claude to directly interact with your files, providing hands-on\n * assistance rather than just suggesting changes.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport const TextEditor_20250429 = Tool.providerDefined({\n  id: \"anthropic.text_editor_20250429\",\n  toolkitName: \"AnthropicTextEditor\",\n  providerName: \"str_replace_based_edit_tool\",\n  args: {},\n  requiresHandler: true,\n  parameters: {\n    /**\n     * The command to run.\n     */\n    command: Schema.Literal(\n      \"view\",\n      \"create\",\n      \"str_replace\",\n      \"insert\"\n    ),\n    /**\n     * Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.\n     */\n    path: Schema.String,\n    /**\n     * Required parameter of `create` command, with the content of the file to\n     * be created.\n     */\n    file_text: Schema.optional(Schema.String),\n    /**\n     * Required parameter of `insert` command. The `new_str` will be inserted\n     * AFTER the line `insert_line` of `path`.\n     */\n    insert_line: Schema.optional(Schema.Number),\n    /**\n     * Optional parameter of `str_replace` command containing the new string (if\n     * not given, no string will be added). Required parameter of `insert`\n     * command containing the string to insert.\n     */\n    new_str: Schema.optional(Schema.String),\n    /**\n     * Required parameter of `str_replace` command containing the string in\n     * `path` to replace.\n     */\n    old_str: Schema.optional(Schema.String),\n    /**\n     * Optional parameter of `view` command when `path` points to a file. If\n     * none is given, the full file is shown. If provided, the file will be\n     * shown in the indicated line number range, e.g. [11, 12] will show lines\n     * 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all\n     * lines from `start_line` to the end of the file.\n     */\n    view_range: Schema.optional(Schema.Array(Schema.Number))\n  }\n})\n\n/**\n * Allow Claude to directly interact with your files, providing hands-on\n * assistance rather than just suggesting changes.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport const TextEditor_20250728 = Tool.providerDefined({\n  id: \"anthropic.text_editor_20250728\",\n  toolkitName: \"AnthropicTextEditor\",\n  providerName: \"str_replace_based_edit_tool\",\n  args: {},\n  requiresHandler: true,\n  parameters: {\n    /**\n     * The command to run.\n     */\n    command: Schema.Literal(\n      \"view\",\n      \"create\",\n      \"str_replace\",\n      \"insert\"\n    ),\n    /**\n     * Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`.\n     */\n    path: Schema.String,\n    /**\n     * Required parameter of `create` command, with the content of the file to\n     * be created.\n     */\n    file_text: Schema.optional(Schema.String),\n    /**\n     * Required parameter of `insert` command. The `new_str` will be inserted\n     * AFTER the line `insert_line` of `path`.\n     */\n    insert_line: Schema.optional(Schema.Number),\n    /**\n     * Optional parameter of `str_replace` command containing the new string (if\n     * not given, no string will be added). Required parameter of `insert`\n     * command containing the string to insert.\n     */\n    new_str: Schema.optional(Schema.String),\n    /**\n     * Required parameter of `str_replace` command containing the string in\n     * `path` to replace.\n     */\n    old_str: Schema.optional(Schema.String),\n    /**\n     * Optional parameter of `view` command when `path` points to a file. If\n     * none is given, the full file is shown. If provided, the file will be\n     * shown in the indicated line number range, e.g. [11, 12] will show lines\n     * 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all\n     * lines from `start_line` to the end of the file.\n     */\n    view_range: Schema.optional(Schema.Array(Schema.Number))\n  }\n})\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const WebSearch_20250305 = Tool.providerDefined({\n  id: \"anthropic.web_search_20250305\",\n  toolkitName: \"AnthropicWebSearch\",\n  providerName: \"web_search\",\n  args: Struct.omit(Generated.WebSearchTool20250305.fields, \"name\", \"type\"),\n  success: Schema.Array(Generated.RequestWebSearchResultBlock),\n  failure: Generated.ResponseWebSearchToolResultError\n})\n\nconst ProviderToolNamesMap: Map<ProviderDefinedTools[\"name\"] | (string & {}), string> = new Map([\n  [\"bash\", \"AnthropicBash\"],\n  [\"code_execution\", \"AnthropicCodeExecution\"],\n  [\"computer\", \"AnthropicComputerUse\"],\n  [\"str_replace_based_edit_tool\", \"AnthropicTextEditor\"],\n  [\"str_replace_editor\", \"AnthropicTextEditor\"],\n  [\"web_search\", \"AnthropicWebSearch\"]\n])\n\n/**\n * A helper method which takes in the name of a tool as returned in the response\n * from a large language model provider, and returns either the provider-defined\n * name for of the tool as found in the corresponding `Toolkit`, or `undefined`\n * if the tool name is not a provider-defined tool.\n *\n * For example, if the large language model provider returns the tool name\n * `\"web_search\"` in a response, calling this method would return `\"AnthropicWebSearch\"`.\n *\n * This method is primarily exposed for use by other Effect provider\n * integrations which can utilize Anthropic tools (i.e. Amazon Bedrock).\n *\n * @since 1.0.0\n * @category Tool Calling\n */\nexport const getProviderDefinedToolName = (name: string): string | undefined => ProviderToolNamesMap.get(name)\n"
  },
  {
    "path": "packages/ai/anthropic/src/Generated.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientError from \"@effect/platform/HttpClientError\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as HttpClientResponse from \"@effect/platform/HttpClientResponse\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\n\nexport class MessagesPostParams extends S.Struct({\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The model that will complete your prompt.\\n\\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.\n */\nexport class Model extends S.Union(\n  /**\n   * High-performance model with early extended thinking\n   */\n  S.Literal(\"claude-3-7-sonnet-latest\"),\n  /**\n   * High-performance model with early extended thinking\n   */\n  S.Literal(\"claude-3-7-sonnet-20250219\"),\n  /**\n   * Fastest and most compact model for near-instant responsiveness\n   */\n  S.Literal(\"claude-3-5-haiku-latest\"),\n  /**\n   * Our fastest model\n   */\n  S.Literal(\"claude-3-5-haiku-20241022\"),\n  /**\n   * Hybrid model, capable of near-instant responses and extended thinking\n   */\n  S.Literal(\"claude-haiku-4-5\"),\n  /**\n   * Hybrid model, capable of near-instant responses and extended thinking\n   */\n  S.Literal(\"claude-haiku-4-5-20251001\"),\n  /**\n   * High-performance model with extended thinking\n   */\n  S.Literal(\"claude-sonnet-4-20250514\"),\n  /**\n   * High-performance model with extended thinking\n   */\n  S.Literal(\"claude-sonnet-4-0\"),\n  /**\n   * High-performance model with extended thinking\n   */\n  S.Literal(\"claude-4-sonnet-20250514\"),\n  /**\n   * Our best model for real-world agents and coding\n   */\n  S.Literal(\"claude-sonnet-4-5\"),\n  /**\n   * Our best model for real-world agents and coding\n   */\n  S.Literal(\"claude-sonnet-4-5-20250929\"),\n  /**\n   * Our previous most intelligent model\n   */\n  S.Literal(\"claude-3-5-sonnet-latest\"),\n  /**\n   * Our previous most intelligent model\n   */\n  S.Literal(\"claude-3-5-sonnet-20241022\"),\n  S.Literal(\"claude-3-5-sonnet-20240620\"),\n  /**\n   * Our most capable model\n   */\n  S.Literal(\"claude-opus-4-0\"),\n  /**\n   * Our most capable model\n   */\n  S.Literal(\"claude-opus-4-20250514\"),\n  /**\n   * Our most capable model\n   */\n  S.Literal(\"claude-4-opus-20250514\"),\n  /**\n   * Our most capable model\n   */\n  S.Literal(\"claude-opus-4-1-20250805\"),\n  /**\n   * Excels at writing and complex tasks\n   */\n  S.Literal(\"claude-3-opus-latest\"),\n  /**\n   * Excels at writing and complex tasks\n   */\n  S.Literal(\"claude-3-opus-20240229\"),\n  /**\n   * Our previous most fast and cost-effective\n   */\n  S.Literal(\"claude-3-haiku-20240307\")\n) {}\n\n/**\n * The time-to-live for the cache control breakpoint.\n *\n * This may be one the following values:\n * - `5m`: 5 minutes\n * - `1h`: 1 hour\n *\n * Defaults to `5m`.\n */\nexport class CacheControlEphemeralTtl extends S.Literal(\"5m\", \"1h\") {}\n\nexport class CacheControlEphemeral extends S.Class<CacheControlEphemeral>(\"CacheControlEphemeral\")({\n  /**\n   * The time-to-live for the cache control breakpoint.\n   *\n   * This may be one the following values:\n   * - `5m`: 5 minutes\n   * - `1h`: 1 hour\n   *\n   * Defaults to `5m`.\n   */\n  \"ttl\": S.optionalWith(CacheControlEphemeralTtl, { nullable: true }),\n  \"type\": S.Literal(\"ephemeral\")\n}) {}\n\nexport class RequestCharLocationCitation extends S.Class<RequestCharLocationCitation>(\"RequestCharLocationCitation\")({\n  \"cited_text\": S.String,\n  \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n  \"document_title\": S.NullOr(S.String.pipe(S.minLength(1), S.maxLength(255))),\n  \"end_char_index\": S.Int,\n  \"start_char_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n  \"type\": S.Literal(\"char_location\")\n}) {}\n\nexport class RequestPageLocationCitation extends S.Class<RequestPageLocationCitation>(\"RequestPageLocationCitation\")({\n  \"cited_text\": S.String,\n  \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n  \"document_title\": S.NullOr(S.String.pipe(S.minLength(1), S.maxLength(255))),\n  \"end_page_number\": S.Int,\n  \"start_page_number\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n  \"type\": S.Literal(\"page_location\")\n}) {}\n\nexport class RequestContentBlockLocationCitation\n  extends S.Class<RequestContentBlockLocationCitation>(\"RequestContentBlockLocationCitation\")({\n    \"cited_text\": S.String,\n    \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"document_title\": S.NullOr(S.String.pipe(S.minLength(1), S.maxLength(255))),\n    \"end_block_index\": S.Int,\n    \"start_block_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"type\": S.Literal(\"content_block_location\")\n  })\n{}\n\nexport class RequestWebSearchResultLocationCitation\n  extends S.Class<RequestWebSearchResultLocationCitation>(\"RequestWebSearchResultLocationCitation\")({\n    \"cited_text\": S.String,\n    \"encrypted_index\": S.String,\n    \"title\": S.NullOr(S.String.pipe(S.minLength(1), S.maxLength(512))),\n    \"type\": S.Literal(\"web_search_result_location\"),\n    \"url\": S.String.pipe(S.minLength(1), S.maxLength(2048))\n  })\n{}\n\nexport class RequestSearchResultLocationCitation\n  extends S.Class<RequestSearchResultLocationCitation>(\"RequestSearchResultLocationCitation\")({\n    \"cited_text\": S.String,\n    \"end_block_index\": S.Int,\n    \"search_result_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"source\": S.String,\n    \"start_block_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"title\": S.NullOr(S.String),\n    \"type\": S.Literal(\"search_result_location\")\n  })\n{}\n\nexport class RequestTextBlock extends S.Class<RequestTextBlock>(\"RequestTextBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  \"citations\": S.optionalWith(\n    S.Array(\n      S.Union(\n        RequestCharLocationCitation,\n        RequestPageLocationCitation,\n        RequestContentBlockLocationCitation,\n        RequestWebSearchResultLocationCitation,\n        RequestSearchResultLocationCitation\n      )\n    ),\n    { nullable: true }\n  ),\n  \"text\": S.String.pipe(S.minLength(1)),\n  \"type\": S.Literal(\"text\")\n}) {}\n\nexport class Base64ImageSourceMediaType extends S.Literal(\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\") {}\n\nexport class Base64ImageSource extends S.Class<Base64ImageSource>(\"Base64ImageSource\")({\n  \"data\": S.String,\n  \"media_type\": Base64ImageSourceMediaType,\n  \"type\": S.Literal(\"base64\")\n}) {}\n\nexport class URLImageSource extends S.Class<URLImageSource>(\"URLImageSource\")({\n  \"type\": S.Literal(\"url\"),\n  \"url\": S.String\n}) {}\n\nexport class RequestImageBlock extends S.Class<RequestImageBlock>(\"RequestImageBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  \"source\": S.Union(Base64ImageSource, URLImageSource),\n  \"type\": S.Literal(\"image\")\n}) {}\n\nexport class RequestCitationsConfig extends S.Class<RequestCitationsConfig>(\"RequestCitationsConfig\")({\n  \"enabled\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class Base64PDFSource extends S.Class<Base64PDFSource>(\"Base64PDFSource\")({\n  \"data\": S.String,\n  \"media_type\": S.Literal(\"application/pdf\"),\n  \"type\": S.Literal(\"base64\")\n}) {}\n\nexport class PlainTextSource extends S.Class<PlainTextSource>(\"PlainTextSource\")({\n  \"data\": S.String,\n  \"media_type\": S.Literal(\"text/plain\"),\n  \"type\": S.Literal(\"text\")\n}) {}\n\nexport class ContentBlockSource extends S.Class<ContentBlockSource>(\"ContentBlockSource\")({\n  \"content\": S.Union(S.String, S.Array(S.Union(RequestTextBlock, RequestImageBlock))),\n  \"type\": S.Literal(\"content\")\n}) {}\n\nexport class URLPDFSource extends S.Class<URLPDFSource>(\"URLPDFSource\")({\n  \"type\": S.Literal(\"url\"),\n  \"url\": S.String\n}) {}\n\nexport class RequestDocumentBlock extends S.Class<RequestDocumentBlock>(\"RequestDocumentBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  \"citations\": S.optionalWith(RequestCitationsConfig, { nullable: true }),\n  \"context\": S.optionalWith(S.String.pipe(S.minLength(1)), { nullable: true }),\n  \"source\": S.Union(Base64PDFSource, PlainTextSource, ContentBlockSource, URLPDFSource),\n  \"title\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(500)), { nullable: true }),\n  \"type\": S.Literal(\"document\")\n}) {}\n\nexport class RequestSearchResultBlock extends S.Class<RequestSearchResultBlock>(\"RequestSearchResultBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  \"citations\": S.optionalWith(RequestCitationsConfig, { nullable: true }),\n  \"content\": S.Array(RequestTextBlock),\n  \"source\": S.String,\n  \"title\": S.String,\n  \"type\": S.Literal(\"search_result\")\n}) {}\n\nexport class RequestThinkingBlock extends S.Class<RequestThinkingBlock>(\"RequestThinkingBlock\")({\n  \"signature\": S.String,\n  \"thinking\": S.String,\n  \"type\": S.Literal(\"thinking\")\n}) {}\n\nexport class RequestRedactedThinkingBlock\n  extends S.Class<RequestRedactedThinkingBlock>(\"RequestRedactedThinkingBlock\")({\n    \"data\": S.String,\n    \"type\": S.Literal(\"redacted_thinking\")\n  })\n{}\n\nexport class RequestToolUseBlock extends S.Class<RequestToolUseBlock>(\"RequestToolUseBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  \"id\": S.String.pipe(S.pattern(new RegExp(\"^[a-zA-Z0-9_-]+$\"))),\n  \"input\": S.Record({ key: S.String, value: S.Unknown }),\n  \"name\": S.String.pipe(S.minLength(1), S.maxLength(200)),\n  \"type\": S.Literal(\"tool_use\")\n}) {}\n\nexport class RequestToolResultBlock extends S.Class<RequestToolResultBlock>(\"RequestToolResultBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  \"content\": S.optionalWith(\n    S.Union(\n      S.String,\n      S.Array(S.Union(RequestTextBlock, RequestImageBlock, RequestSearchResultBlock, RequestDocumentBlock))\n    ),\n    { nullable: true }\n  ),\n  \"is_error\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^[a-zA-Z0-9_-]+$\"))),\n  \"type\": S.Literal(\"tool_result\")\n}) {}\n\nexport class RequestServerToolUseBlock extends S.Class<RequestServerToolUseBlock>(\"RequestServerToolUseBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  \"id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n  \"input\": S.Record({ key: S.String, value: S.Unknown }),\n  \"name\": S.Literal(\"web_search\"),\n  \"type\": S.Literal(\"server_tool_use\")\n}) {}\n\nexport class RequestWebSearchResultBlock extends S.Class<RequestWebSearchResultBlock>(\"RequestWebSearchResultBlock\")({\n  \"encrypted_content\": S.String,\n  \"page_age\": S.optionalWith(S.String, { nullable: true }),\n  \"title\": S.String,\n  \"type\": S.Literal(\"web_search_result\"),\n  \"url\": S.String\n}) {}\n\nexport class WebSearchToolResultErrorCode\n  extends S.Literal(\"invalid_tool_input\", \"unavailable\", \"max_uses_exceeded\", \"too_many_requests\", \"query_too_long\")\n{}\n\nexport class RequestWebSearchToolResultError\n  extends S.Class<RequestWebSearchToolResultError>(\"RequestWebSearchToolResultError\")({\n    \"error_code\": WebSearchToolResultErrorCode,\n    \"type\": S.Literal(\"web_search_tool_result_error\")\n  })\n{}\n\nexport class RequestWebSearchToolResultBlock\n  extends S.Class<RequestWebSearchToolResultBlock>(\"RequestWebSearchToolResultBlock\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n    \"content\": S.Union(S.Array(RequestWebSearchResultBlock), RequestWebSearchToolResultError),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"web_search_tool_result\")\n  })\n{}\n\nexport class InputContentBlock extends S.Union(\n  /**\n   * Regular text content.\n   */\n  RequestTextBlock,\n  /**\n   * Image content specified directly as base64 data or as a reference via a URL.\n   */\n  RequestImageBlock,\n  /**\n   * Document content, either specified directly as base64 data, as text, or as a reference via a URL.\n   */\n  RequestDocumentBlock,\n  /**\n   * A search result block containing source, title, and content from search operations.\n   */\n  RequestSearchResultBlock,\n  /**\n   * A block specifying internal thinking by the model.\n   */\n  RequestThinkingBlock,\n  /**\n   * A block specifying internal, redacted thinking by the model.\n   */\n  RequestRedactedThinkingBlock,\n  /**\n   * A block indicating a tool use by the model.\n   */\n  RequestToolUseBlock,\n  /**\n   * A block specifying the results of a tool use by the model.\n   */\n  RequestToolResultBlock,\n  RequestServerToolUseBlock,\n  RequestWebSearchToolResultBlock\n) {}\n\nexport class InputMessageRole extends S.Literal(\"user\", \"assistant\") {}\n\nexport class InputMessage extends S.Class<InputMessage>(\"InputMessage\")({\n  \"content\": S.Union(S.String, S.Array(InputContentBlock)),\n  \"role\": InputMessageRole\n}) {}\n\nexport class Metadata extends S.Class<Metadata>(\"Metadata\")({\n  /**\n   * An external identifier for the user who is associated with the request.\n   *\n   * This should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number.\n   */\n  \"user_id\": S.optionalWith(S.String.pipe(S.maxLength(256)), { nullable: true })\n}) {}\n\n/**\n * Determines whether to use priority capacity (if available) or standard capacity for this request.\n *\n * Anthropic offers different levels of service for your API requests. See [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.\n */\nexport class CreateMessageParamsServiceTier extends S.Literal(\"auto\", \"standard_only\") {}\n\nexport class ThinkingConfigEnabled extends S.Class<ThinkingConfigEnabled>(\"ThinkingConfigEnabled\")({\n  /**\n   * Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality.\n   *\n   * Must be ≥1024 and less than `max_tokens`.\n   *\n   * See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.\n   */\n  \"budget_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(1024)),\n  \"type\": S.Literal(\"enabled\")\n}) {}\n\nexport class ThinkingConfigDisabled extends S.Class<ThinkingConfigDisabled>(\"ThinkingConfigDisabled\")({\n  \"type\": S.Literal(\"disabled\")\n}) {}\n\n/**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's thinking process before the final answer. Requires a minimum budget of 1,024 tokens and counts towards your `max_tokens` limit.\n *\n * See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.\n */\nexport class ThinkingConfigParam extends S.Union(ThinkingConfigEnabled, ThinkingConfigDisabled) {}\n\n/**\n * The model will automatically decide whether to use tools.\n */\nexport class ToolChoiceAuto extends S.Class<ToolChoiceAuto>(\"ToolChoiceAuto\")({\n  /**\n   * Whether to disable parallel tool use.\n   *\n   * Defaults to `false`. If set to `true`, the model will output at most one tool use.\n   */\n  \"disable_parallel_tool_use\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"type\": S.Literal(\"auto\")\n}) {}\n\n/**\n * The model will use any available tools.\n */\nexport class ToolChoiceAny extends S.Class<ToolChoiceAny>(\"ToolChoiceAny\")({\n  /**\n   * Whether to disable parallel tool use.\n   *\n   * Defaults to `false`. If set to `true`, the model will output exactly one tool use.\n   */\n  \"disable_parallel_tool_use\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"type\": S.Literal(\"any\")\n}) {}\n\n/**\n * The model will use the specified tool with `tool_choice.name`.\n */\nexport class ToolChoiceTool extends S.Class<ToolChoiceTool>(\"ToolChoiceTool\")({\n  /**\n   * Whether to disable parallel tool use.\n   *\n   * Defaults to `false`. If set to `true`, the model will output exactly one tool use.\n   */\n  \"disable_parallel_tool_use\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * The name of the tool to use.\n   */\n  \"name\": S.String,\n  \"type\": S.Literal(\"tool\")\n}) {}\n\n/**\n * The model will not be allowed to use tools.\n */\nexport class ToolChoiceNone extends S.Class<ToolChoiceNone>(\"ToolChoiceNone\")({\n  \"type\": S.Literal(\"none\")\n}) {}\n\n/**\n * How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all.\n */\nexport class ToolChoice extends S.Union(ToolChoiceAuto, ToolChoiceAny, ToolChoiceTool, ToolChoiceNone) {}\n\nexport class InputSchema extends S.Class<InputSchema>(\"InputSchema\")({\n  \"properties\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"required\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"type\": S.Literal(\"object\")\n}) {}\n\nexport class Tool extends S.Class<Tool>(\"Tool\")({\n  \"type\": S.optionalWith(S.Literal(\"custom\"), { nullable: true }),\n  /**\n   * Description of what this tool does.\n   *\n   * Tool descriptions should be as detailed as possible. The more information that the model has about what the tool is and how to use it, the better it will perform. You can use natural language descriptions to reinforce important aspects of the tool input JSON schema.\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.String.pipe(S.minLength(1), S.maxLength(128), S.pattern(new RegExp(\"^[a-zA-Z0-9_-]{1,128}$\"))),\n  /**\n   * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n   *\n   * This defines the shape of the `input` that your tool accepts and that the model will produce.\n   */\n  \"input_schema\": InputSchema,\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true })\n}) {}\n\nexport class BashTool20250124 extends S.Class<BashTool20250124>(\"BashTool20250124\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"bash\"),\n  \"type\": S.Literal(\"bash_20250124\")\n}) {}\n\nexport class TextEditor20250124 extends S.Class<TextEditor20250124>(\"TextEditor20250124\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"str_replace_editor\"),\n  \"type\": S.Literal(\"text_editor_20250124\")\n}) {}\n\nexport class TextEditor20250429 extends S.Class<TextEditor20250429>(\"TextEditor20250429\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"str_replace_based_edit_tool\"),\n  \"type\": S.Literal(\"text_editor_20250429\")\n}) {}\n\nexport class TextEditor20250728 extends S.Class<TextEditor20250728>(\"TextEditor20250728\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  /**\n   * Maximum number of characters to display when viewing a file. If not specified, defaults to displaying the full file.\n   */\n  \"max_characters\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"str_replace_based_edit_tool\"),\n  \"type\": S.Literal(\"text_editor_20250728\")\n}) {}\n\nexport class UserLocation extends S.Class<UserLocation>(\"UserLocation\")({\n  /**\n   * The city of the user.\n   */\n  \"city\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(255)), { nullable: true }),\n  /**\n   * The two letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the user.\n   */\n  \"country\": S.optionalWith(S.String.pipe(S.minLength(2), S.maxLength(2)), { nullable: true }),\n  /**\n   * The region of the user.\n   */\n  \"region\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(255)), { nullable: true }),\n  /**\n   * The [IANA timezone](https://nodatime.org/TimeZones) of the user.\n   */\n  \"timezone\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(255)), { nullable: true }),\n  \"type\": S.Literal(\"approximate\")\n}) {}\n\nexport class WebSearchTool20250305 extends S.Class<WebSearchTool20250305>(\"WebSearchTool20250305\")({\n  /**\n   * If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`.\n   */\n  \"allowed_domains\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`.\n   */\n  \"blocked_domains\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(CacheControlEphemeral, { nullable: true }),\n  /**\n   * Maximum number of times the tool can be used in the API request.\n   */\n  \"max_uses\": S.optionalWith(S.Int.pipe(S.greaterThan(0)), { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"web_search\"),\n  \"type\": S.Literal(\"web_search_20250305\"),\n  /**\n   * Parameters for the user's location. Used to provide more relevant search results.\n   */\n  \"user_location\": S.optionalWith(UserLocation, { nullable: true })\n}) {}\n\nexport class CreateMessageParams extends S.Class<CreateMessageParams>(\"CreateMessageParams\")({\n  \"model\": S.Union(S.String, Model),\n  /**\n   * Input messages.\n   *\n   * Our models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.\n   *\n   * Each input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.\n   *\n   * If the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.\n   *\n   * Example with a single `user` message:\n   *\n   * ```json\n   * [{\"role\": \"user\", \"content\": \"Hello, Claude\"}]\n   * ```\n   *\n   * Example with multiple conversational turns:\n   *\n   * ```json\n   * [\n   *   {\"role\": \"user\", \"content\": \"Hello there.\"},\n   *   {\"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\"},\n   *   {\"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\"},\n   * ]\n   * ```\n   *\n   * Example with a partially-filled response from Claude:\n   *\n   * ```json\n   * [\n   *   {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n   *   {\"role\": \"assistant\", \"content\": \"The best answer is (\"},\n   * ]\n   * ```\n   *\n   * Each input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `\"text\"`. The following input messages are equivalent:\n   *\n   * ```json\n   * {\"role\": \"user\", \"content\": \"Hello, Claude\"}\n   * ```\n   *\n   * ```json\n   * {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, Claude\"}]}\n   * ```\n   *\n   * See [input examples](https://docs.claude.com/en/api/messages-examples).\n   *\n   * Note that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `\"system\"` role for input messages in the Messages API.\n   *\n   * There is a limit of 100,000 messages in a single request.\n   */\n  \"messages\": S.Array(InputMessage),\n  /**\n   * The maximum number of tokens to generate before stopping.\n   *\n   * Note that our models may stop _before_ reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate.\n   *\n   * Different models have different maximum values for this parameter.  See [models](https://docs.claude.com/en/docs/models-overview) for details.\n   */\n  \"max_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n  /**\n   * An object describing metadata about the request.\n   */\n  \"metadata\": S.optionalWith(Metadata, { nullable: true }),\n  /**\n   * Determines whether to use priority capacity (if available) or standard capacity for this request.\n   *\n   * Anthropic offers different levels of service for your API requests. See [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.\n   */\n  \"service_tier\": S.optionalWith(CreateMessageParamsServiceTier, { nullable: true }),\n  /**\n   * Custom text sequences that will cause the model to stop generating.\n   *\n   * Our models will normally stop when they have naturally completed their turn, which will result in a response `stop_reason` of `\"end_turn\"`.\n   *\n   * If you want the model to stop generating when it encounters custom strings of text, you can use the `stop_sequences` parameter. If the model encounters one of the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"` and the response `stop_sequence` value will contain the matched stop sequence.\n   */\n  \"stop_sequences\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Whether to incrementally stream the response using server-sent events.\n   *\n   * See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.\n   */\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * System prompt.\n   *\n   * A system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).\n   */\n  \"system\": S.optionalWith(S.Union(S.String, S.Array(RequestTextBlock)), { nullable: true }),\n  /**\n   * Amount of randomness injected into the response.\n   *\n   * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for analytical / multiple choice, and closer to `1.0` for creative and generative tasks.\n   *\n   * Note that even with `temperature` of `0.0`, the results will not be fully deterministic.\n   */\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  \"thinking\": S.optionalWith(ThinkingConfigParam, { nullable: true }),\n  \"tool_choice\": S.optionalWith(ToolChoice, { nullable: true }),\n  /**\n   * Definitions of tools that the model may use.\n   *\n   * If you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.\n   *\n   * There are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview\\#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n   *\n   * Each tool definition includes:\n   *\n   * * `name`: Name of the tool.\n   * * `description`: Optional, but strongly-recommended description of the tool.\n   * * `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.\n   *\n   * For example, if you defined `tools` as:\n   *\n   * ```json\n   * [\n   *   {\n   *     \"name\": \"get_stock_price\",\n   *     \"description\": \"Get the current stock price for a given ticker symbol.\",\n   *     \"input_schema\": {\n   *       \"type\": \"object\",\n   *       \"properties\": {\n   *         \"ticker\": {\n   *           \"type\": \"string\",\n   *           \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n   *         }\n   *       },\n   *       \"required\": [\"ticker\"]\n   *     }\n   *   }\n   * ]\n   * ```\n   *\n   * And then asked the model \"What's the S&P 500 at today?\", the model might produce `tool_use` content blocks in the response like this:\n   *\n   * ```json\n   * [\n   *   {\n   *     \"type\": \"tool_use\",\n   *     \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n   *     \"name\": \"get_stock_price\",\n   *     \"input\": { \"ticker\": \"^GSPC\" }\n   *   }\n   * ]\n   * ```\n   *\n   * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an input, and return the following back to the model in a subsequent `user` message:\n   *\n   * ```json\n   * [\n   *   {\n   *     \"type\": \"tool_result\",\n   *     \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n   *     \"content\": \"259.75 USD\"\n   *   }\n   * ]\n   * ```\n   *\n   * Tools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.\n   *\n   * See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.\n   */\n  \"tools\": S.optionalWith(\n    S.Array(\n      S.Union(Tool, BashTool20250124, TextEditor20250124, TextEditor20250429, TextEditor20250728, WebSearchTool20250305)\n    ),\n    { nullable: true }\n  ),\n  /**\n   * Only sample from the top K options for each subsequent token.\n   *\n   * Used to remove \"long tail\" low probability responses. [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n   *\n   * Recommended for advanced use cases only. You usually only need to use `temperature`.\n   */\n  \"top_k\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0)), { nullable: true }),\n  /**\n   * Use nucleus sampling.\n   *\n   * In nucleus sampling, we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by `top_p`. You should either alter `temperature` or `top_p`, but not both.\n   *\n   * Recommended for advanced use cases only. You usually only need to use `temperature`.\n   */\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true })\n}) {}\n\nexport class ResponseCharLocationCitation\n  extends S.Class<ResponseCharLocationCitation>(\"ResponseCharLocationCitation\")({\n    \"cited_text\": S.String,\n    \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"document_title\": S.NullOr(S.String),\n    \"end_char_index\": S.Int,\n    \"file_id\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"start_char_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"type\": S.Literal(\"char_location\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"char_location\" as const)\n    )\n  })\n{}\n\nexport class ResponsePageLocationCitation\n  extends S.Class<ResponsePageLocationCitation>(\"ResponsePageLocationCitation\")({\n    \"cited_text\": S.String,\n    \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"document_title\": S.NullOr(S.String),\n    \"end_page_number\": S.Int,\n    \"file_id\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"start_page_number\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n    \"type\": S.Literal(\"page_location\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"page_location\" as const)\n    )\n  })\n{}\n\nexport class ResponseContentBlockLocationCitation\n  extends S.Class<ResponseContentBlockLocationCitation>(\"ResponseContentBlockLocationCitation\")({\n    \"cited_text\": S.String,\n    \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"document_title\": S.NullOr(S.String),\n    \"end_block_index\": S.Int,\n    \"file_id\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"start_block_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"type\": S.Literal(\"content_block_location\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"content_block_location\" as const)\n    )\n  })\n{}\n\nexport class ResponseWebSearchResultLocationCitation\n  extends S.Class<ResponseWebSearchResultLocationCitation>(\"ResponseWebSearchResultLocationCitation\")({\n    \"cited_text\": S.String,\n    \"encrypted_index\": S.String,\n    \"title\": S.NullOr(S.String.pipe(S.maxLength(512))),\n    \"type\": S.Literal(\"web_search_result_location\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_search_result_location\" as const)\n    ),\n    \"url\": S.String\n  })\n{}\n\nexport class ResponseSearchResultLocationCitation\n  extends S.Class<ResponseSearchResultLocationCitation>(\"ResponseSearchResultLocationCitation\")({\n    \"cited_text\": S.String,\n    \"end_block_index\": S.Int,\n    \"search_result_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"source\": S.String,\n    \"start_block_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"title\": S.NullOr(S.String),\n    \"type\": S.Literal(\"search_result_location\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"search_result_location\" as const)\n    )\n  })\n{}\n\nexport class ResponseTextBlock extends S.Class<ResponseTextBlock>(\"ResponseTextBlock\")({\n  /**\n   * Citations supporting the text block.\n   *\n   * The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.\n   */\n  \"citations\": S.optionalWith(\n    S.NullOr(\n      S.Array(\n        S.Union(\n          ResponseCharLocationCitation,\n          ResponsePageLocationCitation,\n          ResponseContentBlockLocationCitation,\n          ResponseWebSearchResultLocationCitation,\n          ResponseSearchResultLocationCitation\n        )\n      )\n    ),\n    { default: () => null }\n  ),\n  \"text\": S.String.pipe(S.minLength(0), S.maxLength(5000000)),\n  \"type\": S.Literal(\"text\").pipe(S.propertySignature, S.withConstructorDefault(() => \"text\" as const))\n}) {}\n\nexport class ResponseThinkingBlock extends S.Class<ResponseThinkingBlock>(\"ResponseThinkingBlock\")({\n  \"signature\": S.String,\n  \"thinking\": S.String,\n  \"type\": S.Literal(\"thinking\").pipe(S.propertySignature, S.withConstructorDefault(() => \"thinking\" as const))\n}) {}\n\nexport class ResponseRedactedThinkingBlock\n  extends S.Class<ResponseRedactedThinkingBlock>(\"ResponseRedactedThinkingBlock\")({\n    \"data\": S.String,\n    \"type\": S.Literal(\"redacted_thinking\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"redacted_thinking\" as const)\n    )\n  })\n{}\n\nexport class ResponseToolUseBlock extends S.Class<ResponseToolUseBlock>(\"ResponseToolUseBlock\")({\n  \"id\": S.String.pipe(S.pattern(new RegExp(\"^[a-zA-Z0-9_-]+$\"))),\n  \"input\": S.Record({ key: S.String, value: S.Unknown }),\n  \"name\": S.String.pipe(S.minLength(1)),\n  \"type\": S.Literal(\"tool_use\").pipe(S.propertySignature, S.withConstructorDefault(() => \"tool_use\" as const))\n}) {}\n\nexport class ResponseServerToolUseBlock extends S.Class<ResponseServerToolUseBlock>(\"ResponseServerToolUseBlock\")({\n  \"id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n  \"input\": S.Record({ key: S.String, value: S.Unknown }),\n  \"name\": S.Literal(\"web_search\"),\n  \"type\": S.Literal(\"server_tool_use\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"server_tool_use\" as const)\n  )\n}) {}\n\nexport class ResponseWebSearchToolResultError\n  extends S.Class<ResponseWebSearchToolResultError>(\"ResponseWebSearchToolResultError\")({\n    \"error_code\": WebSearchToolResultErrorCode,\n    \"type\": S.Literal(\"web_search_tool_result_error\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_search_tool_result_error\" as const)\n    )\n  })\n{}\n\nexport class ResponseWebSearchResultBlock\n  extends S.Class<ResponseWebSearchResultBlock>(\"ResponseWebSearchResultBlock\")({\n    \"encrypted_content\": S.String,\n    \"page_age\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"title\": S.String,\n    \"type\": S.Literal(\"web_search_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_search_result\" as const)\n    ),\n    \"url\": S.String\n  })\n{}\n\nexport class ResponseWebSearchToolResultBlock\n  extends S.Class<ResponseWebSearchToolResultBlock>(\"ResponseWebSearchToolResultBlock\")({\n    \"content\": S.Union(ResponseWebSearchToolResultError, S.Array(ResponseWebSearchResultBlock)),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"web_search_tool_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_search_tool_result\" as const)\n    )\n  })\n{}\n\nexport class ContentBlock extends S.Union(\n  ResponseTextBlock,\n  ResponseThinkingBlock,\n  ResponseRedactedThinkingBlock,\n  ResponseToolUseBlock,\n  ResponseServerToolUseBlock,\n  ResponseWebSearchToolResultBlock\n) {}\n\nexport class StopReason\n  extends S.Literal(\"end_turn\", \"max_tokens\", \"stop_sequence\", \"tool_use\", \"pause_turn\", \"refusal\")\n{}\n\nexport class CacheCreation extends S.Class<CacheCreation>(\"CacheCreation\")({\n  /**\n   * The number of input tokens used to create the 1 hour cache entry.\n   */\n  \"ephemeral_1h_input_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(0)).pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => 0 as const)\n  ),\n  /**\n   * The number of input tokens used to create the 5 minute cache entry.\n   */\n  \"ephemeral_5m_input_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(0)).pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => 0 as const)\n  )\n}) {}\n\nexport class ServerToolUsage extends S.Class<ServerToolUsage>(\"ServerToolUsage\")({\n  /**\n   * The number of web search tool requests.\n   */\n  \"web_search_requests\": S.Int.pipe(S.greaterThanOrEqualTo(0)).pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => 0 as const)\n  )\n}) {}\n\nexport class UsageServiceTierEnum extends S.Literal(\"standard\", \"priority\", \"batch\") {}\n\nexport class Usage extends S.Class<Usage>(\"Usage\")({\n  /**\n   * Breakdown of cached tokens by TTL\n   */\n  \"cache_creation\": S.optionalWith(S.NullOr(CacheCreation), { default: () => null }),\n  /**\n   * The number of input tokens used to create the cache entry.\n   */\n  \"cache_creation_input_tokens\": S.optionalWith(S.NullOr(S.Int.pipe(S.greaterThanOrEqualTo(0))), {\n    default: () => null\n  }),\n  /**\n   * The number of input tokens read from the cache.\n   */\n  \"cache_read_input_tokens\": S.optionalWith(S.NullOr(S.Int.pipe(S.greaterThanOrEqualTo(0))), { default: () => null }),\n  /**\n   * The number of input tokens which were used.\n   */\n  \"input_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n  /**\n   * The number of output tokens which were used.\n   */\n  \"output_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n  /**\n   * The number of server tool requests.\n   */\n  \"server_tool_use\": S.optionalWith(S.NullOr(ServerToolUsage), { default: () => null }),\n  /**\n   * If the request used the priority, standard, or batch tier.\n   */\n  \"service_tier\": S.optionalWith(S.NullOr(UsageServiceTierEnum), { default: () => null })\n}) {}\n\nexport class Message extends S.Class<Message>(\"Message\")({\n  /**\n   * Unique object identifier.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Object type.\n   *\n   * For Messages, this is always `\"message\"`.\n   */\n  \"type\": S.Literal(\"message\").pipe(S.propertySignature, S.withConstructorDefault(() => \"message\" as const)),\n  /**\n   * Conversational role of the generated message.\n   *\n   * This will always be `\"assistant\"`.\n   */\n  \"role\": S.Literal(\"assistant\").pipe(S.propertySignature, S.withConstructorDefault(() => \"assistant\" as const)),\n  /**\n   * Content generated by the model.\n   *\n   * This is an array of content blocks, each of which has a `type` that determines its shape.\n   *\n   * Example:\n   *\n   * ```json\n   * [{\"type\": \"text\", \"text\": \"Hi, I'm Claude.\"}]\n   * ```\n   *\n   * If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output.\n   *\n   * For example, if the input `messages` were:\n   * ```json\n   * [\n   *   {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n   *   {\"role\": \"assistant\", \"content\": \"The best answer is (\"}\n   * ]\n   * ```\n   *\n   * Then the response `content` might be:\n   *\n   * ```json\n   * [{\"type\": \"text\", \"text\": \"B)\"}]\n   * ```\n   */\n  \"content\": S.Array(ContentBlock),\n  \"model\": S.Union(S.String, Model),\n  /**\n   * The reason that we stopped.\n   *\n   * This may be one the following values:\n   * * `\"end_turn\"`: the model reached a natural stopping point\n   * * `\"max_tokens\"`: we exceeded the requested `max_tokens` or the model's maximum\n   * * `\"stop_sequence\"`: one of your provided custom `stop_sequences` was generated\n   * * `\"tool_use\"`: the model invoked one or more tools\n   * * `\"pause_turn\"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.\n   * * `\"refusal\"`: when streaming classifiers intervene to handle potential policy violations\n   *\n   * In non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise.\n   */\n  \"stop_reason\": S.NullOr(StopReason),\n  /**\n   * Which custom stop sequence was generated, if any.\n   *\n   * This value will be a non-null string if one of your custom stop sequences was generated.\n   */\n  \"stop_sequence\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n  /**\n   * Billing and rate-limit usage.\n   *\n   * Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.\n   *\n   * Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.\n   *\n   * For example, `output_tokens` will be non-zero, even for an empty string response from Claude.\n   *\n   * Total input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n   */\n  \"usage\": Usage\n}) {}\n\nexport class InvalidRequestError extends S.Class<InvalidRequestError>(\"InvalidRequestError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Invalid request\" as const)),\n  \"type\": S.Literal(\"invalid_request_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"invalid_request_error\" as const)\n  )\n}) {}\n\nexport class AuthenticationError extends S.Class<AuthenticationError>(\"AuthenticationError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Authentication error\" as const)),\n  \"type\": S.Literal(\"authentication_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"authentication_error\" as const)\n  )\n}) {}\n\nexport class BillingError extends S.Class<BillingError>(\"BillingError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Billing error\" as const)),\n  \"type\": S.Literal(\"billing_error\").pipe(S.propertySignature, S.withConstructorDefault(() => \"billing_error\" as const))\n}) {}\n\nexport class PermissionError extends S.Class<PermissionError>(\"PermissionError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Permission denied\" as const)),\n  \"type\": S.Literal(\"permission_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"permission_error\" as const)\n  )\n}) {}\n\nexport class NotFoundError extends S.Class<NotFoundError>(\"NotFoundError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Not found\" as const)),\n  \"type\": S.Literal(\"not_found_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"not_found_error\" as const)\n  )\n}) {}\n\nexport class RateLimitError extends S.Class<RateLimitError>(\"RateLimitError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Rate limited\" as const)),\n  \"type\": S.Literal(\"rate_limit_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"rate_limit_error\" as const)\n  )\n}) {}\n\nexport class GatewayTimeoutError extends S.Class<GatewayTimeoutError>(\"GatewayTimeoutError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Request timeout\" as const)),\n  \"type\": S.Literal(\"timeout_error\").pipe(S.propertySignature, S.withConstructorDefault(() => \"timeout_error\" as const))\n}) {}\n\nexport class APIError extends S.Class<APIError>(\"APIError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Internal server error\" as const)),\n  \"type\": S.Literal(\"api_error\").pipe(S.propertySignature, S.withConstructorDefault(() => \"api_error\" as const))\n}) {}\n\nexport class OverloadedError extends S.Class<OverloadedError>(\"OverloadedError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Overloaded\" as const)),\n  \"type\": S.Literal(\"overloaded_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"overloaded_error\" as const)\n  )\n}) {}\n\nexport class ErrorResponse extends S.Class<ErrorResponse>(\"ErrorResponse\")({\n  \"error\": S.Union(\n    InvalidRequestError,\n    AuthenticationError,\n    BillingError,\n    PermissionError,\n    NotFoundError,\n    RateLimitError,\n    GatewayTimeoutError,\n    APIError,\n    OverloadedError\n  ),\n  \"request_id\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n  \"type\": S.Literal(\"error\").pipe(S.propertySignature, S.withConstructorDefault(() => \"error\" as const))\n}) {}\n\nexport class CompletePostParams extends S.Struct({\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class CompletionRequest extends S.Class<CompletionRequest>(\"CompletionRequest\")({\n  \"model\": S.Union(S.String, Model),\n  /**\n   * The prompt that you want Claude to complete.\n   *\n   * For proper response generation you will need to format your prompt using alternating `\\n\\nHuman:` and `\\n\\nAssistant:` conversational turns. For example:\n   *\n   * ```\n   * \"\\n\\nHuman: {userQuestion}\\n\\nAssistant:\"\n   * ```\n   *\n   * See [prompt validation](https://docs.claude.com/en/api/prompt-validation) and our guide to [prompt design](https://docs.claude.com/en/docs/intro-to-prompting) for more details.\n   */\n  \"prompt\": S.String.pipe(S.minLength(1)),\n  /**\n   * The maximum number of tokens to generate before stopping.\n   *\n   * Note that our models may stop _before_ reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate.\n   */\n  \"max_tokens_to_sample\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n  /**\n   * Sequences that will cause the model to stop generating.\n   *\n   * Our models stop on `\"\\n\\nHuman:\"`, and may include additional built-in stop sequences in the future. By providing the stop_sequences parameter, you may include additional strings that will cause the model to stop generating.\n   */\n  \"stop_sequences\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Amount of randomness injected into the response.\n   *\n   * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for analytical / multiple choice, and closer to `1.0` for creative and generative tasks.\n   *\n   * Note that even with `temperature` of `0.0`, the results will not be fully deterministic.\n   */\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  /**\n   * Use nucleus sampling.\n   *\n   * In nucleus sampling, we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by `top_p`. You should either alter `temperature` or `top_p`, but not both.\n   *\n   * Recommended for advanced use cases only. You usually only need to use `temperature`.\n   */\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  /**\n   * Only sample from the top K options for each subsequent token.\n   *\n   * Used to remove \"long tail\" low probability responses. [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n   *\n   * Recommended for advanced use cases only. You usually only need to use `temperature`.\n   */\n  \"top_k\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0)), { nullable: true }),\n  /**\n   * An object describing metadata about the request.\n   */\n  \"metadata\": S.optionalWith(Metadata, { nullable: true }),\n  /**\n   * Whether to incrementally stream the response using server-sent events.\n   *\n   * See [streaming](https://docs.claude.com/en/api/streaming) for details.\n   */\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class CompletionResponse extends S.Class<CompletionResponse>(\"CompletionResponse\")({\n  /**\n   * The resulting completion up to and excluding the stop sequences.\n   */\n  \"completion\": S.String,\n  /**\n   * Unique object identifier.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  \"model\": S.Union(S.String, Model),\n  /**\n   * The reason that we stopped.\n   *\n   * This may be one the following values:\n   * * `\"stop_sequence\"`: we reached a stop sequence — either provided by you via the `stop_sequences` parameter, or a stop sequence built into the model\n   * * `\"max_tokens\"`: we exceeded `max_tokens_to_sample` or the model's maximum\n   */\n  \"stop_reason\": S.NullOr(S.String),\n  /**\n   * Object type.\n   *\n   * For Text Completions, this is always `\"completion\"`.\n   */\n  \"type\": S.Literal(\"completion\").pipe(S.propertySignature, S.withConstructorDefault(() => \"completion\" as const))\n}) {}\n\nexport class ModelsListParams extends S.Struct({\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.\n   */\n  \"before_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.\n   */\n  \"after_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of items to return per page.\n   *\n   * Defaults to `20`. Ranges from `1` to `1000`.\n   */\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(1000)), {\n    nullable: true,\n    default: () => 20 as const\n  }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ModelInfo extends S.Class<ModelInfo>(\"ModelInfo\")({\n  /**\n   * RFC 3339 datetime string representing the time at which the model was released. May be set to an epoch value if the release date is unknown.\n   */\n  \"created_at\": S.String,\n  /**\n   * A human-readable name for the model.\n   */\n  \"display_name\": S.String,\n  /**\n   * Unique model identifier.\n   */\n  \"id\": S.String,\n  /**\n   * Object type.\n   *\n   * For Models, this is always `\"model\"`.\n   */\n  \"type\": S.Literal(\"model\").pipe(S.propertySignature, S.withConstructorDefault(() => \"model\" as const))\n}) {}\n\nexport class ListResponseModelInfo extends S.Class<ListResponseModelInfo>(\"ListResponseModelInfo\")({\n  \"data\": S.Array(ModelInfo),\n  /**\n   * First ID in the `data` list. Can be used as the `before_id` for the previous page.\n   */\n  \"first_id\": S.NullOr(S.String),\n  /**\n   * Indicates if there are more results in the requested page direction.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Last ID in the `data` list. Can be used as the `after_id` for the next page.\n   */\n  \"last_id\": S.NullOr(S.String)\n}) {}\n\nexport class ModelsGetParams extends S.Struct({\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class MessageBatchesListParams extends S.Struct({\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.\n   */\n  \"before_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.\n   */\n  \"after_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of items to return per page.\n   *\n   * Defaults to `20`. Ranges from `1` to `1000`.\n   */\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(1000)), {\n    nullable: true,\n    default: () => 20 as const\n  }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Processing status of the Message Batch.\n */\nexport class MessageBatchProcessingStatus extends S.Literal(\"in_progress\", \"canceling\", \"ended\") {}\n\nexport class RequestCounts extends S.Class<RequestCounts>(\"RequestCounts\")({\n  /**\n   * Number of requests in the Message Batch that have been canceled.\n   *\n   * This is zero until processing of the entire Message Batch has ended.\n   */\n  \"canceled\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Number of requests in the Message Batch that encountered an error.\n   *\n   * This is zero until processing of the entire Message Batch has ended.\n   */\n  \"errored\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Number of requests in the Message Batch that have expired.\n   *\n   * This is zero until processing of the entire Message Batch has ended.\n   */\n  \"expired\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Number of requests in the Message Batch that are processing.\n   */\n  \"processing\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Number of requests in the Message Batch that have completed successfully.\n   *\n   * This is zero until processing of the entire Message Batch has ended.\n   */\n  \"succeeded\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const))\n}) {}\n\nexport class MessageBatch extends S.Class<MessageBatch>(\"MessageBatch\")({\n  /**\n   * RFC 3339 datetime string representing the time at which the Message Batch was archived and its results became unavailable.\n   */\n  \"archived_at\": S.NullOr(S.String),\n  /**\n   * RFC 3339 datetime string representing the time at which cancellation was initiated for the Message Batch. Specified only if cancellation was initiated.\n   */\n  \"cancel_initiated_at\": S.NullOr(S.String),\n  /**\n   * RFC 3339 datetime string representing the time at which the Message Batch was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * RFC 3339 datetime string representing the time at which processing for the Message Batch ended. Specified only once processing ends.\n   *\n   * Processing ends when every request in a Message Batch has either succeeded, errored, canceled, or expired.\n   */\n  \"ended_at\": S.NullOr(S.String),\n  /**\n   * RFC 3339 datetime string representing the time at which the Message Batch will expire and end processing, which is 24 hours after creation.\n   */\n  \"expires_at\": S.String,\n  /**\n   * Unique object identifier.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Processing status of the Message Batch.\n   */\n  \"processing_status\": MessageBatchProcessingStatus,\n  /**\n   * Tallies requests within the Message Batch, categorized by their status.\n   *\n   * Requests start as `processing` and move to one of the other statuses only once processing of the entire batch ends. The sum of all values always matches the total number of requests in the batch.\n   */\n  \"request_counts\": RequestCounts,\n  /**\n   * URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only once processing ends.\n   *\n   * Results in the file are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.\n   */\n  \"results_url\": S.NullOr(S.String),\n  /**\n   * Object type.\n   *\n   * For Message Batches, this is always `\"message_batch\"`.\n   */\n  \"type\": S.Literal(\"message_batch\").pipe(S.propertySignature, S.withConstructorDefault(() => \"message_batch\" as const))\n}) {}\n\nexport class ListResponseMessageBatch extends S.Class<ListResponseMessageBatch>(\"ListResponseMessageBatch\")({\n  \"data\": S.Array(MessageBatch),\n  /**\n   * First ID in the `data` list. Can be used as the `before_id` for the previous page.\n   */\n  \"first_id\": S.NullOr(S.String),\n  /**\n   * Indicates if there are more results in the requested page direction.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Last ID in the `data` list. Can be used as the `after_id` for the next page.\n   */\n  \"last_id\": S.NullOr(S.String)\n}) {}\n\nexport class MessageBatchesPostParams extends S.Struct({\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class MessageBatchIndividualRequestParams\n  extends S.Class<MessageBatchIndividualRequestParams>(\"MessageBatchIndividualRequestParams\")({\n    /**\n     * Developer-provided ID created for each request in a Message Batch. Useful for matching results to requests, as results may be given out of request order.\n     *\n     * Must be unique for each request within the Message Batch.\n     */\n    \"custom_id\": S.String.pipe(S.minLength(1), S.maxLength(64), S.pattern(new RegExp(\"^[a-zA-Z0-9_-]{1,64}$\"))),\n    /**\n     * Messages API creation parameters for the individual request.\n     *\n     * See the [Messages API reference](/en/api/messages) for full documentation on available parameters.\n     */\n    \"params\": CreateMessageParams\n  })\n{}\n\nexport class CreateMessageBatchParams extends S.Class<CreateMessageBatchParams>(\"CreateMessageBatchParams\")({\n  /**\n   * List of requests for prompt completion. Each is an individual request to create a Message.\n   */\n  \"requests\": S.NonEmptyArray(MessageBatchIndividualRequestParams).pipe(S.minItems(1), S.maxItems(10000))\n}) {}\n\nexport class MessageBatchesRetrieveParams extends S.Struct({\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class MessageBatchesDeleteParams extends S.Struct({\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class DeleteMessageBatchResponse extends S.Class<DeleteMessageBatchResponse>(\"DeleteMessageBatchResponse\")({\n  /**\n   * ID of the Message Batch.\n   */\n  \"id\": S.String,\n  /**\n   * Deleted object type.\n   *\n   * For Message Batches, this is always `\"message_batch_deleted\"`.\n   */\n  \"type\": S.Literal(\"message_batch_deleted\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"message_batch_deleted\" as const)\n  )\n}) {}\n\nexport class MessageBatchesCancelParams extends S.Struct({\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class MessageBatchesResultsParams extends S.Struct({\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class MessagesCountTokensPostParams extends S.Struct({\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class CountMessageTokensParams extends S.Class<CountMessageTokensParams>(\"CountMessageTokensParams\")({\n  /**\n   * Input messages.\n   *\n   * Our models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.\n   *\n   * Each input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.\n   *\n   * If the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.\n   *\n   * Example with a single `user` message:\n   *\n   * ```json\n   * [{\"role\": \"user\", \"content\": \"Hello, Claude\"}]\n   * ```\n   *\n   * Example with multiple conversational turns:\n   *\n   * ```json\n   * [\n   *   {\"role\": \"user\", \"content\": \"Hello there.\"},\n   *   {\"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\"},\n   *   {\"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\"},\n   * ]\n   * ```\n   *\n   * Example with a partially-filled response from Claude:\n   *\n   * ```json\n   * [\n   *   {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n   *   {\"role\": \"assistant\", \"content\": \"The best answer is (\"},\n   * ]\n   * ```\n   *\n   * Each input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `\"text\"`. The following input messages are equivalent:\n   *\n   * ```json\n   * {\"role\": \"user\", \"content\": \"Hello, Claude\"}\n   * ```\n   *\n   * ```json\n   * {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, Claude\"}]}\n   * ```\n   *\n   * See [input examples](https://docs.claude.com/en/api/messages-examples).\n   *\n   * Note that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `\"system\"` role for input messages in the Messages API.\n   *\n   * There is a limit of 100,000 messages in a single request.\n   */\n  \"messages\": S.Array(InputMessage),\n  \"model\": S.Union(S.String, Model),\n  /**\n   * System prompt.\n   *\n   * A system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).\n   */\n  \"system\": S.optionalWith(S.Union(S.String, S.Array(RequestTextBlock)), { nullable: true }),\n  \"thinking\": S.optionalWith(ThinkingConfigParam, { nullable: true }),\n  \"tool_choice\": S.optionalWith(ToolChoice, { nullable: true }),\n  /**\n   * Definitions of tools that the model may use.\n   *\n   * If you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.\n   *\n   * There are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview\\#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n   *\n   * Each tool definition includes:\n   *\n   * * `name`: Name of the tool.\n   * * `description`: Optional, but strongly-recommended description of the tool.\n   * * `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.\n   *\n   * For example, if you defined `tools` as:\n   *\n   * ```json\n   * [\n   *   {\n   *     \"name\": \"get_stock_price\",\n   *     \"description\": \"Get the current stock price for a given ticker symbol.\",\n   *     \"input_schema\": {\n   *       \"type\": \"object\",\n   *       \"properties\": {\n   *         \"ticker\": {\n   *           \"type\": \"string\",\n   *           \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n   *         }\n   *       },\n   *       \"required\": [\"ticker\"]\n   *     }\n   *   }\n   * ]\n   * ```\n   *\n   * And then asked the model \"What's the S&P 500 at today?\", the model might produce `tool_use` content blocks in the response like this:\n   *\n   * ```json\n   * [\n   *   {\n   *     \"type\": \"tool_use\",\n   *     \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n   *     \"name\": \"get_stock_price\",\n   *     \"input\": { \"ticker\": \"^GSPC\" }\n   *   }\n   * ]\n   * ```\n   *\n   * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an input, and return the following back to the model in a subsequent `user` message:\n   *\n   * ```json\n   * [\n   *   {\n   *     \"type\": \"tool_result\",\n   *     \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n   *     \"content\": \"259.75 USD\"\n   *   }\n   * ]\n   * ```\n   *\n   * Tools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.\n   *\n   * See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.\n   */\n  \"tools\": S.optionalWith(\n    S.Array(\n      S.Union(Tool, BashTool20250124, TextEditor20250124, TextEditor20250429, TextEditor20250728, WebSearchTool20250305)\n    ),\n    { nullable: true }\n  )\n}) {}\n\nexport class CountMessageTokensResponse extends S.Class<CountMessageTokensResponse>(\"CountMessageTokensResponse\")({\n  /**\n   * The total number of tokens across the provided list of messages, system prompt, and tools.\n   */\n  \"input_tokens\": S.Int\n}) {}\n\nexport class ListFilesV1FilesGetParams extends S.Struct({\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.\n   */\n  \"before_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.\n   */\n  \"after_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of items to return per page.\n   *\n   * Defaults to `20`. Ranges from `1` to `1000`.\n   */\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(1000)), {\n    nullable: true,\n    default: () => 20 as const\n  }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class FileMetadataSchema extends S.Class<FileMetadataSchema>(\"FileMetadataSchema\")({\n  /**\n   * RFC 3339 datetime string representing when the file was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Whether the file can be downloaded.\n   */\n  \"downloadable\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  /**\n   * Original filename of the uploaded file.\n   */\n  \"filename\": S.String.pipe(S.minLength(1), S.maxLength(500)),\n  /**\n   * Unique object identifier.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * MIME type of the file.\n   */\n  \"mime_type\": S.String.pipe(S.minLength(1), S.maxLength(255)),\n  /**\n   * Size of the file in bytes.\n   */\n  \"size_bytes\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n  /**\n   * Object type.\n   *\n   * For files, this is always `\"file\"`.\n   */\n  \"type\": S.Literal(\"file\")\n}) {}\n\nexport class FileListResponse extends S.Class<FileListResponse>(\"FileListResponse\")({\n  /**\n   * List of file metadata objects.\n   */\n  \"data\": S.Array(FileMetadataSchema),\n  /**\n   * ID of the first file in this page of results.\n   */\n  \"first_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Whether there are more results available.\n   */\n  \"has_more\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  /**\n   * ID of the last file in this page of results.\n   */\n  \"last_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UploadFileV1FilesPostParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UploadFileV1FilesPostRequest\n  extends S.Class<UploadFileV1FilesPostRequest>(\"UploadFileV1FilesPostRequest\")({\n    /**\n     * The file to upload\n     */\n    \"file\": S.instanceOf(globalThis.Blob)\n  })\n{}\n\nexport class GetFileMetadataV1FilesFileIdGetParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class DeleteFileV1FilesFileIdDeleteParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class FileDeleteResponse extends S.Class<FileDeleteResponse>(\"FileDeleteResponse\")({\n  /**\n   * ID of the deleted file.\n   */\n  \"id\": S.String,\n  /**\n   * Deleted object type.\n   *\n   * For file deletion, this is always `\"file_deleted\"`.\n   */\n  \"type\": S.optionalWith(S.Literal(\"file_deleted\"), { nullable: true, default: () => \"file_deleted\" as const })\n}) {}\n\nexport class DownloadFileV1FilesFileIdContentGetParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListSkillsV1SkillsGetParams extends S.Struct({\n  /**\n   * Pagination token for fetching a specific page of results.\n   *\n   * Pass the value from a previous response's `next_page` field to get the next page of results.\n   */\n  \"page\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of results to return per page.\n   *\n   * Maximum value is 100. Defaults to 20.\n   */\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  /**\n   * Filter skills by source.\n   *\n   * If provided, only skills from the specified source will be returned:\n   * * `\"custom\"`: only return user-created skills\n   * * `\"anthropic\"`: only return Anthropic-created skills\n   */\n  \"source\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class Skill extends S.Class<Skill>(\"Skill\")({\n  /**\n   * ISO 8601 timestamp of when the skill was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Display title for the skill.\n   *\n   * This is a human-readable label that is not included in the prompt sent to the model.\n   */\n  \"display_title\": S.NullOr(S.String),\n  /**\n   * Unique identifier for the skill.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * The latest version identifier for the skill.\n   *\n   * This represents the most recent version of the skill that has been created.\n   */\n  \"latest_version\": S.NullOr(S.String),\n  /**\n   * Source of the skill.\n   *\n   * This may be one of the following values:\n   * * `\"custom\"`: the skill was created by a user\n   * * `\"anthropic\"`: the skill was created by Anthropic\n   */\n  \"source\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skills, this is always `\"skill\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill\" as const)),\n  /**\n   * ISO 8601 timestamp of when the skill was last updated.\n   */\n  \"updated_at\": S.String\n}) {}\n\nexport class ListSkillsResponse extends S.Class<ListSkillsResponse>(\"ListSkillsResponse\")({\n  /**\n   * List of skills.\n   */\n  \"data\": S.Array(Skill),\n  /**\n   * Whether there are more results available.\n   *\n   * If `true`, there are additional results that can be fetched using the `next_page` token.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Token for fetching the next page of results.\n   *\n   * If `null`, there are no more results available. Pass this value to the `page_token` parameter in the next request to get the next page.\n   */\n  \"next_page\": S.NullOr(S.String)\n}) {}\n\nexport class CreateSkillV1SkillsPostParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BodyCreateSkillV1SkillsPost extends S.Class<BodyCreateSkillV1SkillsPost>(\"BodyCreateSkillV1SkillsPost\")({\n  /**\n   * Display title for the skill.\n   *\n   * This is a human-readable label that is not included in the prompt sent to the model.\n   */\n  \"display_title\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Files to upload for the skill.\n   *\n   * All files must be in the same top-level directory and must include a SKILL.md file at the root of that directory.\n   */\n  \"files\": S.optionalWith(S.Array(S.instanceOf(globalThis.Blob)), { nullable: true })\n}) {}\n\nexport class CreateSkillResponse extends S.Class<CreateSkillResponse>(\"CreateSkillResponse\")({\n  /**\n   * ISO 8601 timestamp of when the skill was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Display title for the skill.\n   *\n   * This is a human-readable label that is not included in the prompt sent to the model.\n   */\n  \"display_title\": S.NullOr(S.String),\n  /**\n   * Unique identifier for the skill.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * The latest version identifier for the skill.\n   *\n   * This represents the most recent version of the skill that has been created.\n   */\n  \"latest_version\": S.NullOr(S.String),\n  /**\n   * Source of the skill.\n   *\n   * This may be one of the following values:\n   * * `\"custom\"`: the skill was created by a user\n   * * `\"anthropic\"`: the skill was created by Anthropic\n   */\n  \"source\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skills, this is always `\"skill\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill\" as const)),\n  /**\n   * ISO 8601 timestamp of when the skill was last updated.\n   */\n  \"updated_at\": S.String\n}) {}\n\nexport class GetSkillV1SkillsSkillIdGetParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class GetSkillResponse extends S.Class<GetSkillResponse>(\"GetSkillResponse\")({\n  /**\n   * ISO 8601 timestamp of when the skill was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Display title for the skill.\n   *\n   * This is a human-readable label that is not included in the prompt sent to the model.\n   */\n  \"display_title\": S.NullOr(S.String),\n  /**\n   * Unique identifier for the skill.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * The latest version identifier for the skill.\n   *\n   * This represents the most recent version of the skill that has been created.\n   */\n  \"latest_version\": S.NullOr(S.String),\n  /**\n   * Source of the skill.\n   *\n   * This may be one of the following values:\n   * * `\"custom\"`: the skill was created by a user\n   * * `\"anthropic\"`: the skill was created by Anthropic\n   */\n  \"source\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skills, this is always `\"skill\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill\" as const)),\n  /**\n   * ISO 8601 timestamp of when the skill was last updated.\n   */\n  \"updated_at\": S.String\n}) {}\n\nexport class DeleteSkillV1SkillsSkillIdDeleteParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class DeleteSkillResponse extends S.Class<DeleteSkillResponse>(\"DeleteSkillResponse\")({\n  /**\n   * Unique identifier for the skill.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Deleted object type.\n   *\n   * For Skills, this is always `\"skill_deleted\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill_deleted\" as const))\n}) {}\n\nexport class ListSkillVersionsV1SkillsSkillIdVersionsGetParams extends S.Struct({\n  /**\n   * Optionally set to the `next_page` token from the previous response.\n   */\n  \"page\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of items to return per page.\n   *\n   * Defaults to `20`. Ranges from `1` to `1000`.\n   */\n  \"limit\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class SkillVersion extends S.Class<SkillVersion>(\"SkillVersion\")({\n  /**\n   * ISO 8601 timestamp of when the skill version was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Description of the skill version.\n   *\n   * This is extracted from the SKILL.md file in the skill upload.\n   */\n  \"description\": S.String,\n  /**\n   * Directory name of the skill version.\n   *\n   * This is the top-level directory name that was extracted from the uploaded files.\n   */\n  \"directory\": S.String,\n  /**\n   * Unique identifier for the skill version.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Human-readable name of the skill version.\n   *\n   * This is extracted from the SKILL.md file in the skill upload.\n   */\n  \"name\": S.String,\n  /**\n   * Identifier for the skill that this version belongs to.\n   */\n  \"skill_id\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skill Versions, this is always `\"skill_version\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill_version\" as const)),\n  /**\n   * Version identifier for the skill.\n   *\n   * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n   */\n  \"version\": S.String\n}) {}\n\nexport class ListSkillVersionsResponse extends S.Class<ListSkillVersionsResponse>(\"ListSkillVersionsResponse\")({\n  /**\n   * List of skill versions.\n   */\n  \"data\": S.Array(SkillVersion),\n  /**\n   * Indicates if there are more results in the requested page direction.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Token to provide in as `page` in the subsequent request to retrieve the next page of data.\n   */\n  \"next_page\": S.NullOr(S.String)\n}) {}\n\nexport class CreateSkillVersionV1SkillsSkillIdVersionsPostParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BodyCreateSkillVersionV1SkillsSkillIdVersionsPost\n  extends S.Class<BodyCreateSkillVersionV1SkillsSkillIdVersionsPost>(\n    \"BodyCreateSkillVersionV1SkillsSkillIdVersionsPost\"\n  )({\n    /**\n     * Files to upload for the skill.\n     *\n     * All files must be in the same top-level directory and must include a SKILL.md file at the root of that directory.\n     */\n    \"files\": S.optionalWith(S.Array(S.instanceOf(globalThis.Blob)), { nullable: true })\n  })\n{}\n\nexport class CreateSkillVersionResponse extends S.Class<CreateSkillVersionResponse>(\"CreateSkillVersionResponse\")({\n  /**\n   * ISO 8601 timestamp of when the skill version was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Description of the skill version.\n   *\n   * This is extracted from the SKILL.md file in the skill upload.\n   */\n  \"description\": S.String,\n  /**\n   * Directory name of the skill version.\n   *\n   * This is the top-level directory name that was extracted from the uploaded files.\n   */\n  \"directory\": S.String,\n  /**\n   * Unique identifier for the skill version.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Human-readable name of the skill version.\n   *\n   * This is extracted from the SKILL.md file in the skill upload.\n   */\n  \"name\": S.String,\n  /**\n   * Identifier for the skill that this version belongs to.\n   */\n  \"skill_id\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skill Versions, this is always `\"skill_version\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill_version\" as const)),\n  /**\n   * Version identifier for the skill.\n   *\n   * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n   */\n  \"version\": S.String\n}) {}\n\nexport class GetSkillVersionV1SkillsSkillIdVersionsVersionGetParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class GetSkillVersionResponse extends S.Class<GetSkillVersionResponse>(\"GetSkillVersionResponse\")({\n  /**\n   * ISO 8601 timestamp of when the skill version was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Description of the skill version.\n   *\n   * This is extracted from the SKILL.md file in the skill upload.\n   */\n  \"description\": S.String,\n  /**\n   * Directory name of the skill version.\n   *\n   * This is the top-level directory name that was extracted from the uploaded files.\n   */\n  \"directory\": S.String,\n  /**\n   * Unique identifier for the skill version.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Human-readable name of the skill version.\n   *\n   * This is extracted from the SKILL.md file in the skill upload.\n   */\n  \"name\": S.String,\n  /**\n   * Identifier for the skill that this version belongs to.\n   */\n  \"skill_id\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skill Versions, this is always `\"skill_version\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill_version\" as const)),\n  /**\n   * Version identifier for the skill.\n   *\n   * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n   */\n  \"version\": S.String\n}) {}\n\nexport class DeleteSkillVersionV1SkillsSkillIdVersionsVersionDeleteParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class DeleteSkillVersionResponse extends S.Class<DeleteSkillVersionResponse>(\"DeleteSkillVersionResponse\")({\n  /**\n   * Version identifier for the skill.\n   *\n   * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n   */\n  \"id\": S.String,\n  /**\n   * Deleted object type.\n   *\n   * For Skill Versions, this is always `\"skill_version_deleted\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill_version_deleted\" as const))\n}) {}\n\nexport class BetaMessagesPostParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The time-to-live for the cache control breakpoint.\n *\n * This may be one the following values:\n * - `5m`: 5 minutes\n * - `1h`: 1 hour\n *\n * Defaults to `5m`.\n */\nexport class BetaCacheControlEphemeralTtl extends S.Literal(\"5m\", \"1h\") {}\n\nexport class BetaCacheControlEphemeral extends S.Class<BetaCacheControlEphemeral>(\"BetaCacheControlEphemeral\")({\n  /**\n   * The time-to-live for the cache control breakpoint.\n   *\n   * This may be one the following values:\n   * - `5m`: 5 minutes\n   * - `1h`: 1 hour\n   *\n   * Defaults to `5m`.\n   */\n  \"ttl\": S.optionalWith(BetaCacheControlEphemeralTtl, { nullable: true }),\n  \"type\": S.Literal(\"ephemeral\")\n}) {}\n\nexport class BetaRequestCharLocationCitation\n  extends S.Class<BetaRequestCharLocationCitation>(\"BetaRequestCharLocationCitation\")({\n    \"cited_text\": S.String,\n    \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"document_title\": S.NullOr(S.String.pipe(S.minLength(1), S.maxLength(255))),\n    \"end_char_index\": S.Int,\n    \"start_char_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"type\": S.Literal(\"char_location\")\n  })\n{}\n\nexport class BetaRequestPageLocationCitation\n  extends S.Class<BetaRequestPageLocationCitation>(\"BetaRequestPageLocationCitation\")({\n    \"cited_text\": S.String,\n    \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"document_title\": S.NullOr(S.String.pipe(S.minLength(1), S.maxLength(255))),\n    \"end_page_number\": S.Int,\n    \"start_page_number\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n    \"type\": S.Literal(\"page_location\")\n  })\n{}\n\nexport class BetaRequestContentBlockLocationCitation\n  extends S.Class<BetaRequestContentBlockLocationCitation>(\"BetaRequestContentBlockLocationCitation\")({\n    \"cited_text\": S.String,\n    \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"document_title\": S.NullOr(S.String.pipe(S.minLength(1), S.maxLength(255))),\n    \"end_block_index\": S.Int,\n    \"start_block_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"type\": S.Literal(\"content_block_location\")\n  })\n{}\n\nexport class BetaRequestWebSearchResultLocationCitation\n  extends S.Class<BetaRequestWebSearchResultLocationCitation>(\"BetaRequestWebSearchResultLocationCitation\")({\n    \"cited_text\": S.String,\n    \"encrypted_index\": S.String,\n    \"title\": S.NullOr(S.String.pipe(S.minLength(1), S.maxLength(512))),\n    \"type\": S.Literal(\"web_search_result_location\"),\n    \"url\": S.String.pipe(S.minLength(1), S.maxLength(2048))\n  })\n{}\n\nexport class BetaRequestSearchResultLocationCitation\n  extends S.Class<BetaRequestSearchResultLocationCitation>(\"BetaRequestSearchResultLocationCitation\")({\n    \"cited_text\": S.String,\n    \"end_block_index\": S.Int,\n    \"search_result_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"source\": S.String,\n    \"start_block_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"title\": S.NullOr(S.String),\n    \"type\": S.Literal(\"search_result_location\")\n  })\n{}\n\nexport class BetaRequestTextBlock extends S.Class<BetaRequestTextBlock>(\"BetaRequestTextBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  \"citations\": S.optionalWith(\n    S.Array(\n      S.Union(\n        BetaRequestCharLocationCitation,\n        BetaRequestPageLocationCitation,\n        BetaRequestContentBlockLocationCitation,\n        BetaRequestWebSearchResultLocationCitation,\n        BetaRequestSearchResultLocationCitation\n      )\n    ),\n    { nullable: true }\n  ),\n  \"text\": S.String.pipe(S.minLength(1)),\n  \"type\": S.Literal(\"text\")\n}) {}\n\nexport class BetaBase64ImageSourceMediaType extends S.Literal(\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\") {}\n\nexport class BetaBase64ImageSource extends S.Class<BetaBase64ImageSource>(\"BetaBase64ImageSource\")({\n  \"data\": S.String,\n  \"media_type\": BetaBase64ImageSourceMediaType,\n  \"type\": S.Literal(\"base64\")\n}) {}\n\nexport class BetaURLImageSource extends S.Class<BetaURLImageSource>(\"BetaURLImageSource\")({\n  \"type\": S.Literal(\"url\"),\n  \"url\": S.String\n}) {}\n\nexport class BetaFileImageSource extends S.Class<BetaFileImageSource>(\"BetaFileImageSource\")({\n  \"file_id\": S.String,\n  \"type\": S.Literal(\"file\")\n}) {}\n\nexport class BetaRequestImageBlock extends S.Class<BetaRequestImageBlock>(\"BetaRequestImageBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  \"source\": S.Union(BetaBase64ImageSource, BetaURLImageSource, BetaFileImageSource),\n  \"type\": S.Literal(\"image\")\n}) {}\n\nexport class BetaRequestCitationsConfig extends S.Class<BetaRequestCitationsConfig>(\"BetaRequestCitationsConfig\")({\n  \"enabled\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class BetaBase64PDFSource extends S.Class<BetaBase64PDFSource>(\"BetaBase64PDFSource\")({\n  \"data\": S.String,\n  \"media_type\": S.Literal(\"application/pdf\"),\n  \"type\": S.Literal(\"base64\")\n}) {}\n\nexport class BetaPlainTextSource extends S.Class<BetaPlainTextSource>(\"BetaPlainTextSource\")({\n  \"data\": S.String,\n  \"media_type\": S.Literal(\"text/plain\"),\n  \"type\": S.Literal(\"text\")\n}) {}\n\nexport class BetaContentBlockSource extends S.Class<BetaContentBlockSource>(\"BetaContentBlockSource\")({\n  \"content\": S.Union(S.String, S.Array(S.Union(BetaRequestTextBlock, BetaRequestImageBlock))),\n  \"type\": S.Literal(\"content\")\n}) {}\n\nexport class BetaURLPDFSource extends S.Class<BetaURLPDFSource>(\"BetaURLPDFSource\")({\n  \"type\": S.Literal(\"url\"),\n  \"url\": S.String\n}) {}\n\nexport class BetaFileDocumentSource extends S.Class<BetaFileDocumentSource>(\"BetaFileDocumentSource\")({\n  \"file_id\": S.String,\n  \"type\": S.Literal(\"file\")\n}) {}\n\nexport class BetaRequestDocumentBlock extends S.Class<BetaRequestDocumentBlock>(\"BetaRequestDocumentBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  \"citations\": S.optionalWith(BetaRequestCitationsConfig, { nullable: true }),\n  \"context\": S.optionalWith(S.String.pipe(S.minLength(1)), { nullable: true }),\n  \"source\": S.Union(\n    BetaBase64PDFSource,\n    BetaPlainTextSource,\n    BetaContentBlockSource,\n    BetaURLPDFSource,\n    BetaFileDocumentSource\n  ),\n  \"title\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(500)), { nullable: true }),\n  \"type\": S.Literal(\"document\")\n}) {}\n\nexport class BetaRequestSearchResultBlock\n  extends S.Class<BetaRequestSearchResultBlock>(\"BetaRequestSearchResultBlock\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    \"citations\": S.optionalWith(BetaRequestCitationsConfig, { nullable: true }),\n    \"content\": S.Array(BetaRequestTextBlock),\n    \"source\": S.String,\n    \"title\": S.String,\n    \"type\": S.Literal(\"search_result\")\n  })\n{}\n\nexport class BetaRequestThinkingBlock extends S.Class<BetaRequestThinkingBlock>(\"BetaRequestThinkingBlock\")({\n  \"signature\": S.String,\n  \"thinking\": S.String,\n  \"type\": S.Literal(\"thinking\")\n}) {}\n\nexport class BetaRequestRedactedThinkingBlock\n  extends S.Class<BetaRequestRedactedThinkingBlock>(\"BetaRequestRedactedThinkingBlock\")({\n    \"data\": S.String,\n    \"type\": S.Literal(\"redacted_thinking\")\n  })\n{}\n\nexport class BetaRequestToolUseBlock extends S.Class<BetaRequestToolUseBlock>(\"BetaRequestToolUseBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  \"id\": S.String.pipe(S.pattern(new RegExp(\"^[a-zA-Z0-9_-]+$\"))),\n  \"input\": S.Record({ key: S.String, value: S.Unknown }),\n  \"name\": S.String.pipe(S.minLength(1), S.maxLength(200)),\n  \"type\": S.Literal(\"tool_use\")\n}) {}\n\nexport class BetaRequestToolResultBlock extends S.Class<BetaRequestToolResultBlock>(\"BetaRequestToolResultBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  \"content\": S.optionalWith(\n    S.Union(\n      S.String,\n      S.Array(\n        S.Union(BetaRequestTextBlock, BetaRequestImageBlock, BetaRequestSearchResultBlock, BetaRequestDocumentBlock)\n      )\n    ),\n    { nullable: true }\n  ),\n  \"is_error\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^[a-zA-Z0-9_-]+$\"))),\n  \"type\": S.Literal(\"tool_result\")\n}) {}\n\nexport class BetaRequestServerToolUseBlockName\n  extends S.Literal(\"web_search\", \"web_fetch\", \"code_execution\", \"bash_code_execution\", \"text_editor_code_execution\")\n{}\n\nexport class BetaRequestServerToolUseBlock\n  extends S.Class<BetaRequestServerToolUseBlock>(\"BetaRequestServerToolUseBlock\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    \"id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"input\": S.Record({ key: S.String, value: S.Unknown }),\n    \"name\": BetaRequestServerToolUseBlockName,\n    \"type\": S.Literal(\"server_tool_use\")\n  })\n{}\n\nexport class BetaRequestWebSearchResultBlock\n  extends S.Class<BetaRequestWebSearchResultBlock>(\"BetaRequestWebSearchResultBlock\")({\n    \"encrypted_content\": S.String,\n    \"page_age\": S.optionalWith(S.String, { nullable: true }),\n    \"title\": S.String,\n    \"type\": S.Literal(\"web_search_result\"),\n    \"url\": S.String\n  })\n{}\n\nexport class BetaWebSearchToolResultErrorCode\n  extends S.Literal(\"invalid_tool_input\", \"unavailable\", \"max_uses_exceeded\", \"too_many_requests\", \"query_too_long\")\n{}\n\nexport class BetaRequestWebSearchToolResultError\n  extends S.Class<BetaRequestWebSearchToolResultError>(\"BetaRequestWebSearchToolResultError\")({\n    \"error_code\": BetaWebSearchToolResultErrorCode,\n    \"type\": S.Literal(\"web_search_tool_result_error\")\n  })\n{}\n\nexport class BetaRequestWebSearchToolResultBlock\n  extends S.Class<BetaRequestWebSearchToolResultBlock>(\"BetaRequestWebSearchToolResultBlock\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    \"content\": S.Union(S.Array(BetaRequestWebSearchResultBlock), BetaRequestWebSearchToolResultError),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"web_search_tool_result\")\n  })\n{}\n\nexport class BetaWebFetchToolResultErrorCode extends S.Literal(\n  \"invalid_tool_input\",\n  \"url_too_long\",\n  \"url_not_allowed\",\n  \"url_not_accessible\",\n  \"unsupported_content_type\",\n  \"too_many_requests\",\n  \"max_uses_exceeded\",\n  \"unavailable\"\n) {}\n\nexport class BetaRequestWebFetchToolResultError\n  extends S.Class<BetaRequestWebFetchToolResultError>(\"BetaRequestWebFetchToolResultError\")({\n    \"error_code\": BetaWebFetchToolResultErrorCode,\n    \"type\": S.Literal(\"web_fetch_tool_result_error\")\n  })\n{}\n\nexport class BetaRequestWebFetchResultBlock\n  extends S.Class<BetaRequestWebFetchResultBlock>(\"BetaRequestWebFetchResultBlock\")({\n    \"content\": BetaRequestDocumentBlock,\n    /**\n     * ISO 8601 timestamp when the content was retrieved\n     */\n    \"retrieved_at\": S.optionalWith(S.String, { nullable: true }),\n    \"type\": S.Literal(\"web_fetch_result\"),\n    /**\n     * Fetched content URL\n     */\n    \"url\": S.String\n  })\n{}\n\nexport class BetaRequestWebFetchToolResultBlock\n  extends S.Class<BetaRequestWebFetchToolResultBlock>(\"BetaRequestWebFetchToolResultBlock\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    \"content\": S.Union(BetaRequestWebFetchToolResultError, BetaRequestWebFetchResultBlock),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"web_fetch_tool_result\")\n  })\n{}\n\nexport class BetaCodeExecutionToolResultErrorCode\n  extends S.Literal(\"invalid_tool_input\", \"unavailable\", \"too_many_requests\", \"execution_time_exceeded\")\n{}\n\nexport class BetaRequestCodeExecutionToolResultError\n  extends S.Class<BetaRequestCodeExecutionToolResultError>(\"BetaRequestCodeExecutionToolResultError\")({\n    \"error_code\": BetaCodeExecutionToolResultErrorCode,\n    \"type\": S.Literal(\"code_execution_tool_result_error\")\n  })\n{}\n\nexport class BetaRequestCodeExecutionOutputBlock\n  extends S.Class<BetaRequestCodeExecutionOutputBlock>(\"BetaRequestCodeExecutionOutputBlock\")({\n    \"file_id\": S.String,\n    \"type\": S.Literal(\"code_execution_output\")\n  })\n{}\n\nexport class BetaRequestCodeExecutionResultBlock\n  extends S.Class<BetaRequestCodeExecutionResultBlock>(\"BetaRequestCodeExecutionResultBlock\")({\n    \"content\": S.Array(BetaRequestCodeExecutionOutputBlock),\n    \"return_code\": S.Int,\n    \"stderr\": S.String,\n    \"stdout\": S.String,\n    \"type\": S.Literal(\"code_execution_result\")\n  })\n{}\n\nexport class BetaRequestCodeExecutionToolResultBlock\n  extends S.Class<BetaRequestCodeExecutionToolResultBlock>(\"BetaRequestCodeExecutionToolResultBlock\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    \"content\": S.Union(BetaRequestCodeExecutionToolResultError, BetaRequestCodeExecutionResultBlock),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"code_execution_tool_result\")\n  })\n{}\n\nexport class BetaBashCodeExecutionToolResultErrorCode extends S.Literal(\n  \"invalid_tool_input\",\n  \"unavailable\",\n  \"too_many_requests\",\n  \"execution_time_exceeded\",\n  \"output_file_too_large\"\n) {}\n\nexport class BetaRequestBashCodeExecutionToolResultError\n  extends S.Class<BetaRequestBashCodeExecutionToolResultError>(\"BetaRequestBashCodeExecutionToolResultError\")({\n    \"error_code\": BetaBashCodeExecutionToolResultErrorCode,\n    \"type\": S.Literal(\"bash_code_execution_tool_result_error\")\n  })\n{}\n\nexport class BetaRequestBashCodeExecutionOutputBlock\n  extends S.Class<BetaRequestBashCodeExecutionOutputBlock>(\"BetaRequestBashCodeExecutionOutputBlock\")({\n    \"file_id\": S.String,\n    \"type\": S.Literal(\"bash_code_execution_output\")\n  })\n{}\n\nexport class BetaRequestBashCodeExecutionResultBlock\n  extends S.Class<BetaRequestBashCodeExecutionResultBlock>(\"BetaRequestBashCodeExecutionResultBlock\")({\n    \"content\": S.Array(BetaRequestBashCodeExecutionOutputBlock),\n    \"return_code\": S.Int,\n    \"stderr\": S.String,\n    \"stdout\": S.String,\n    \"type\": S.Literal(\"bash_code_execution_result\")\n  })\n{}\n\nexport class BetaRequestBashCodeExecutionToolResultBlock\n  extends S.Class<BetaRequestBashCodeExecutionToolResultBlock>(\"BetaRequestBashCodeExecutionToolResultBlock\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    \"content\": S.Union(BetaRequestBashCodeExecutionToolResultError, BetaRequestBashCodeExecutionResultBlock),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"bash_code_execution_tool_result\")\n  })\n{}\n\nexport class BetaTextEditorCodeExecutionToolResultErrorCode extends S.Literal(\n  \"invalid_tool_input\",\n  \"unavailable\",\n  \"too_many_requests\",\n  \"execution_time_exceeded\",\n  \"file_not_found\"\n) {}\n\nexport class BetaRequestTextEditorCodeExecutionToolResultError\n  extends S.Class<BetaRequestTextEditorCodeExecutionToolResultError>(\n    \"BetaRequestTextEditorCodeExecutionToolResultError\"\n  )({\n    \"error_code\": BetaTextEditorCodeExecutionToolResultErrorCode,\n    \"error_message\": S.optionalWith(S.String, { nullable: true }),\n    \"type\": S.Literal(\"text_editor_code_execution_tool_result_error\")\n  })\n{}\n\nexport class BetaRequestTextEditorCodeExecutionViewResultBlockFileType extends S.Literal(\"text\", \"image\", \"pdf\") {}\n\nexport class BetaRequestTextEditorCodeExecutionViewResultBlock\n  extends S.Class<BetaRequestTextEditorCodeExecutionViewResultBlock>(\n    \"BetaRequestTextEditorCodeExecutionViewResultBlock\"\n  )({\n    \"content\": S.String,\n    \"file_type\": BetaRequestTextEditorCodeExecutionViewResultBlockFileType,\n    \"num_lines\": S.optionalWith(S.Int, { nullable: true }),\n    \"start_line\": S.optionalWith(S.Int, { nullable: true }),\n    \"total_lines\": S.optionalWith(S.Int, { nullable: true }),\n    \"type\": S.Literal(\"text_editor_code_execution_view_result\")\n  })\n{}\n\nexport class BetaRequestTextEditorCodeExecutionCreateResultBlock\n  extends S.Class<BetaRequestTextEditorCodeExecutionCreateResultBlock>(\n    \"BetaRequestTextEditorCodeExecutionCreateResultBlock\"\n  )({\n    \"is_file_update\": S.Boolean,\n    \"type\": S.Literal(\"text_editor_code_execution_create_result\")\n  })\n{}\n\nexport class BetaRequestTextEditorCodeExecutionStrReplaceResultBlock\n  extends S.Class<BetaRequestTextEditorCodeExecutionStrReplaceResultBlock>(\n    \"BetaRequestTextEditorCodeExecutionStrReplaceResultBlock\"\n  )({\n    \"lines\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    \"new_lines\": S.optionalWith(S.Int, { nullable: true }),\n    \"new_start\": S.optionalWith(S.Int, { nullable: true }),\n    \"old_lines\": S.optionalWith(S.Int, { nullable: true }),\n    \"old_start\": S.optionalWith(S.Int, { nullable: true }),\n    \"type\": S.Literal(\"text_editor_code_execution_str_replace_result\")\n  })\n{}\n\nexport class BetaRequestTextEditorCodeExecutionToolResultBlock\n  extends S.Class<BetaRequestTextEditorCodeExecutionToolResultBlock>(\n    \"BetaRequestTextEditorCodeExecutionToolResultBlock\"\n  )({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    \"content\": S.Union(\n      BetaRequestTextEditorCodeExecutionToolResultError,\n      BetaRequestTextEditorCodeExecutionViewResultBlock,\n      BetaRequestTextEditorCodeExecutionCreateResultBlock,\n      BetaRequestTextEditorCodeExecutionStrReplaceResultBlock\n    ),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"text_editor_code_execution_tool_result\")\n  })\n{}\n\nexport class BetaRequestMCPToolUseBlock extends S.Class<BetaRequestMCPToolUseBlock>(\"BetaRequestMCPToolUseBlock\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  \"id\": S.String.pipe(S.pattern(new RegExp(\"^[a-zA-Z0-9_-]+$\"))),\n  \"input\": S.Record({ key: S.String, value: S.Unknown }),\n  \"name\": S.String,\n  /**\n   * The name of the MCP server\n   */\n  \"server_name\": S.String,\n  \"type\": S.Literal(\"mcp_tool_use\")\n}) {}\n\nexport class BetaRequestMCPToolResultBlock\n  extends S.Class<BetaRequestMCPToolResultBlock>(\"BetaRequestMCPToolResultBlock\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    \"content\": S.optionalWith(S.Union(S.String, S.Array(BetaRequestTextBlock)), { nullable: true }),\n    \"is_error\": S.optionalWith(S.Boolean, { nullable: true }),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^[a-zA-Z0-9_-]+$\"))),\n    \"type\": S.Literal(\"mcp_tool_result\")\n  })\n{}\n\n/**\n * A content block that represents a file to be uploaded to the container\n * Files uploaded via this block will be available in the container's input directory.\n */\nexport class BetaRequestContainerUploadBlock\n  extends S.Class<BetaRequestContainerUploadBlock>(\"BetaRequestContainerUploadBlock\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    \"file_id\": S.String,\n    \"type\": S.Literal(\"container_upload\")\n  })\n{}\n\nexport class BetaInputContentBlock extends S.Union(\n  /**\n   * Regular text content.\n   */\n  BetaRequestTextBlock,\n  /**\n   * Image content specified directly as base64 data or as a reference via a URL.\n   */\n  BetaRequestImageBlock,\n  /**\n   * Document content, either specified directly as base64 data, as text, or as a reference via a URL.\n   */\n  BetaRequestDocumentBlock,\n  /**\n   * A search result block containing source, title, and content from search operations.\n   */\n  BetaRequestSearchResultBlock,\n  /**\n   * A block specifying internal thinking by the model.\n   */\n  BetaRequestThinkingBlock,\n  /**\n   * A block specifying internal, redacted thinking by the model.\n   */\n  BetaRequestRedactedThinkingBlock,\n  /**\n   * A block indicating a tool use by the model.\n   */\n  BetaRequestToolUseBlock,\n  /**\n   * A block specifying the results of a tool use by the model.\n   */\n  BetaRequestToolResultBlock,\n  BetaRequestServerToolUseBlock,\n  BetaRequestWebSearchToolResultBlock,\n  BetaRequestWebFetchToolResultBlock,\n  BetaRequestCodeExecutionToolResultBlock,\n  BetaRequestBashCodeExecutionToolResultBlock,\n  BetaRequestTextEditorCodeExecutionToolResultBlock,\n  BetaRequestMCPToolUseBlock,\n  BetaRequestMCPToolResultBlock,\n  BetaRequestContainerUploadBlock\n) {}\n\nexport class BetaInputMessageRole extends S.Literal(\"user\", \"assistant\") {}\n\nexport class BetaInputMessage extends S.Class<BetaInputMessage>(\"BetaInputMessage\")({\n  \"content\": S.Union(S.String, S.Array(BetaInputContentBlock)),\n  \"role\": BetaInputMessageRole\n}) {}\n\n/**\n * Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)\n */\nexport class BetaSkillParamsType extends S.Literal(\"anthropic\", \"custom\") {}\n\n/**\n * Specification for a skill to be loaded in a container (request model).\n */\nexport class BetaSkillParams extends S.Class<BetaSkillParams>(\"BetaSkillParams\")({\n  /**\n   * Skill ID\n   */\n  \"skill_id\": S.String.pipe(S.minLength(1), S.maxLength(64)),\n  /**\n   * Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)\n   */\n  \"type\": BetaSkillParamsType,\n  /**\n   * Skill version or 'latest' for most recent version\n   */\n  \"version\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(64)), { nullable: true })\n}) {}\n\n/**\n * Container parameters with skills to be loaded.\n */\nexport class BetaContainerParams extends S.Class<BetaContainerParams>(\"BetaContainerParams\")({\n  /**\n   * Container id\n   */\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * List of skills to load in the container\n   */\n  \"skills\": S.optionalWith(S.Array(BetaSkillParams).pipe(S.maxItems(8)), { nullable: true })\n}) {}\n\nexport class BetaInputTokensClearAtLeast extends S.Class<BetaInputTokensClearAtLeast>(\"BetaInputTokensClearAtLeast\")({\n  \"type\": S.Literal(\"input_tokens\"),\n  \"value\": S.Int.pipe(S.greaterThanOrEqualTo(0))\n}) {}\n\nexport class BetaToolUsesKeep extends S.Class<BetaToolUsesKeep>(\"BetaToolUsesKeep\")({\n  \"type\": S.Literal(\"tool_uses\"),\n  \"value\": S.Int.pipe(S.greaterThanOrEqualTo(0))\n}) {}\n\nexport class BetaInputTokensTrigger extends S.Class<BetaInputTokensTrigger>(\"BetaInputTokensTrigger\")({\n  \"type\": S.Literal(\"input_tokens\"),\n  \"value\": S.Int.pipe(S.greaterThanOrEqualTo(1))\n}) {}\n\nexport class BetaToolUsesTrigger extends S.Class<BetaToolUsesTrigger>(\"BetaToolUsesTrigger\")({\n  \"type\": S.Literal(\"tool_uses\"),\n  \"value\": S.Int.pipe(S.greaterThanOrEqualTo(1))\n}) {}\n\nexport class BetaClearToolUses20250919 extends S.Class<BetaClearToolUses20250919>(\"BetaClearToolUses20250919\")({\n  /**\n   * Minimum number of tokens that must be cleared when triggered. Context will only be modified if at least this many tokens can be removed.\n   */\n  \"clear_at_least\": S.optionalWith(BetaInputTokensClearAtLeast, { nullable: true }),\n  /**\n   * Whether to clear all tool inputs (bool) or specific tool inputs to clear (list)\n   */\n  \"clear_tool_inputs\": S.optionalWith(S.Union(S.Boolean, S.Array(S.String)), { nullable: true }),\n  /**\n   * Tool names whose uses are preserved from clearing\n   */\n  \"exclude_tools\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Number of tool uses to retain in the conversation\n   */\n  \"keep\": S.optionalWith(BetaToolUsesKeep, { nullable: true }),\n  /**\n   * Condition that triggers the context management strategy\n   */\n  \"trigger\": S.optionalWith(S.Union(BetaInputTokensTrigger, BetaToolUsesTrigger), { nullable: true }),\n  \"type\": S.Literal(\"clear_tool_uses_20250919\")\n}) {}\n\nexport class BetaContextManagementConfig extends S.Class<BetaContextManagementConfig>(\"BetaContextManagementConfig\")({\n  /**\n   * List of context management edits to apply\n   */\n  \"edits\": S.optionalWith(S.Array(BetaClearToolUses20250919), { nullable: true })\n}) {}\n\nexport class BetaRequestMCPServerToolConfiguration\n  extends S.Class<BetaRequestMCPServerToolConfiguration>(\"BetaRequestMCPServerToolConfiguration\")({\n    \"allowed_tools\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    \"enabled\": S.optionalWith(S.Boolean, { nullable: true })\n  })\n{}\n\nexport class BetaRequestMCPServerURLDefinition\n  extends S.Class<BetaRequestMCPServerURLDefinition>(\"BetaRequestMCPServerURLDefinition\")({\n    \"authorization_token\": S.optionalWith(S.String, { nullable: true }),\n    \"name\": S.String,\n    \"tool_configuration\": S.optionalWith(BetaRequestMCPServerToolConfiguration, { nullable: true }),\n    \"type\": S.Literal(\"url\"),\n    \"url\": S.String\n  })\n{}\n\nexport class BetaMetadata extends S.Class<BetaMetadata>(\"BetaMetadata\")({\n  /**\n   * An external identifier for the user who is associated with the request.\n   *\n   * This should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number.\n   */\n  \"user_id\": S.optionalWith(S.String.pipe(S.maxLength(256)), { nullable: true })\n}) {}\n\n/**\n * Determines whether to use priority capacity (if available) or standard capacity for this request.\n *\n * Anthropic offers different levels of service for your API requests. See [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.\n */\nexport class BetaCreateMessageParamsServiceTier extends S.Literal(\"auto\", \"standard_only\") {}\n\nexport class BetaThinkingConfigEnabled extends S.Class<BetaThinkingConfigEnabled>(\"BetaThinkingConfigEnabled\")({\n  /**\n   * Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality.\n   *\n   * Must be ≥1024 and less than `max_tokens`.\n   *\n   * See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.\n   */\n  \"budget_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(1024)),\n  \"type\": S.Literal(\"enabled\")\n}) {}\n\nexport class BetaThinkingConfigDisabled extends S.Class<BetaThinkingConfigDisabled>(\"BetaThinkingConfigDisabled\")({\n  \"type\": S.Literal(\"disabled\")\n}) {}\n\n/**\n * Configuration for enabling Claude's extended thinking.\n *\n * When enabled, responses include `thinking` content blocks showing Claude's thinking process before the final answer. Requires a minimum budget of 1,024 tokens and counts towards your `max_tokens` limit.\n *\n * See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details.\n */\nexport class BetaThinkingConfigParam extends S.Union(BetaThinkingConfigEnabled, BetaThinkingConfigDisabled) {}\n\n/**\n * The model will automatically decide whether to use tools.\n */\nexport class BetaToolChoiceAuto extends S.Class<BetaToolChoiceAuto>(\"BetaToolChoiceAuto\")({\n  /**\n   * Whether to disable parallel tool use.\n   *\n   * Defaults to `false`. If set to `true`, the model will output at most one tool use.\n   */\n  \"disable_parallel_tool_use\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"type\": S.Literal(\"auto\")\n}) {}\n\n/**\n * The model will use any available tools.\n */\nexport class BetaToolChoiceAny extends S.Class<BetaToolChoiceAny>(\"BetaToolChoiceAny\")({\n  /**\n   * Whether to disable parallel tool use.\n   *\n   * Defaults to `false`. If set to `true`, the model will output exactly one tool use.\n   */\n  \"disable_parallel_tool_use\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"type\": S.Literal(\"any\")\n}) {}\n\n/**\n * The model will use the specified tool with `tool_choice.name`.\n */\nexport class BetaToolChoiceTool extends S.Class<BetaToolChoiceTool>(\"BetaToolChoiceTool\")({\n  /**\n   * Whether to disable parallel tool use.\n   *\n   * Defaults to `false`. If set to `true`, the model will output exactly one tool use.\n   */\n  \"disable_parallel_tool_use\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * The name of the tool to use.\n   */\n  \"name\": S.String,\n  \"type\": S.Literal(\"tool\")\n}) {}\n\n/**\n * The model will not be allowed to use tools.\n */\nexport class BetaToolChoiceNone extends S.Class<BetaToolChoiceNone>(\"BetaToolChoiceNone\")({\n  \"type\": S.Literal(\"none\")\n}) {}\n\n/**\n * How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all.\n */\nexport class BetaToolChoice\n  extends S.Union(BetaToolChoiceAuto, BetaToolChoiceAny, BetaToolChoiceTool, BetaToolChoiceNone)\n{}\n\nexport class BetaInputSchema extends S.Class<BetaInputSchema>(\"BetaInputSchema\")({\n  \"properties\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"required\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"type\": S.Literal(\"object\")\n}) {}\n\nexport class BetaTool extends S.Class<BetaTool>(\"BetaTool\")({\n  \"type\": S.optionalWith(S.Literal(\"custom\"), { nullable: true }),\n  /**\n   * Description of what this tool does.\n   *\n   * Tool descriptions should be as detailed as possible. The more information that the model has about what the tool is and how to use it, the better it will perform. You can use natural language descriptions to reinforce important aspects of the tool input JSON schema.\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.String.pipe(S.minLength(1), S.maxLength(128), S.pattern(new RegExp(\"^[a-zA-Z0-9_-]{1,128}$\"))),\n  /**\n   * [JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n   *\n   * This defines the shape of the `input` that your tool accepts and that the model will produce.\n   */\n  \"input_schema\": BetaInputSchema,\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true })\n}) {}\n\nexport class BetaBashTool20241022 extends S.Class<BetaBashTool20241022>(\"BetaBashTool20241022\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"bash\"),\n  \"type\": S.Literal(\"bash_20241022\")\n}) {}\n\nexport class BetaBashTool20250124 extends S.Class<BetaBashTool20250124>(\"BetaBashTool20250124\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"bash\"),\n  \"type\": S.Literal(\"bash_20250124\")\n}) {}\n\nexport class BetaCodeExecutionTool20250522\n  extends S.Class<BetaCodeExecutionTool20250522>(\"BetaCodeExecutionTool20250522\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    /**\n     * Name of the tool.\n     *\n     * This is how the tool will be called by the model and in `tool_use` blocks.\n     */\n    \"name\": S.Literal(\"code_execution\"),\n    \"type\": S.Literal(\"code_execution_20250522\")\n  })\n{}\n\nexport class BetaCodeExecutionTool20250825\n  extends S.Class<BetaCodeExecutionTool20250825>(\"BetaCodeExecutionTool20250825\")({\n    /**\n     * Create a cache control breakpoint at this content block.\n     */\n    \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n    /**\n     * Name of the tool.\n     *\n     * This is how the tool will be called by the model and in `tool_use` blocks.\n     */\n    \"name\": S.Literal(\"code_execution\"),\n    \"type\": S.Literal(\"code_execution_20250825\")\n  })\n{}\n\nexport class BetaComputerUseTool20241022 extends S.Class<BetaComputerUseTool20241022>(\"BetaComputerUseTool20241022\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * The height of the display in pixels.\n   */\n  \"display_height_px\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n  /**\n   * The X11 display number (e.g. 0, 1) for the display.\n   */\n  \"display_number\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0)), { nullable: true }),\n  /**\n   * The width of the display in pixels.\n   */\n  \"display_width_px\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"computer\"),\n  \"type\": S.Literal(\"computer_20241022\")\n}) {}\n\nexport class BetaMemoryTool20250818 extends S.Class<BetaMemoryTool20250818>(\"BetaMemoryTool20250818\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"memory\"),\n  \"type\": S.Literal(\"memory_20250818\")\n}) {}\n\nexport class BetaComputerUseTool20250124 extends S.Class<BetaComputerUseTool20250124>(\"BetaComputerUseTool20250124\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * The height of the display in pixels.\n   */\n  \"display_height_px\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n  /**\n   * The X11 display number (e.g. 0, 1) for the display.\n   */\n  \"display_number\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0)), { nullable: true }),\n  /**\n   * The width of the display in pixels.\n   */\n  \"display_width_px\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"computer\"),\n  \"type\": S.Literal(\"computer_20250124\")\n}) {}\n\nexport class BetaTextEditor20241022 extends S.Class<BetaTextEditor20241022>(\"BetaTextEditor20241022\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"str_replace_editor\"),\n  \"type\": S.Literal(\"text_editor_20241022\")\n}) {}\n\nexport class BetaTextEditor20250124 extends S.Class<BetaTextEditor20250124>(\"BetaTextEditor20250124\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"str_replace_editor\"),\n  \"type\": S.Literal(\"text_editor_20250124\")\n}) {}\n\nexport class BetaTextEditor20250429 extends S.Class<BetaTextEditor20250429>(\"BetaTextEditor20250429\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"str_replace_based_edit_tool\"),\n  \"type\": S.Literal(\"text_editor_20250429\")\n}) {}\n\nexport class BetaTextEditor20250728 extends S.Class<BetaTextEditor20250728>(\"BetaTextEditor20250728\")({\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * Maximum number of characters to display when viewing a file. If not specified, defaults to displaying the full file.\n   */\n  \"max_characters\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"str_replace_based_edit_tool\"),\n  \"type\": S.Literal(\"text_editor_20250728\")\n}) {}\n\nexport class BetaUserLocation extends S.Class<BetaUserLocation>(\"BetaUserLocation\")({\n  /**\n   * The city of the user.\n   */\n  \"city\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(255)), { nullable: true }),\n  /**\n   * The two letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the user.\n   */\n  \"country\": S.optionalWith(S.String.pipe(S.minLength(2), S.maxLength(2)), { nullable: true }),\n  /**\n   * The region of the user.\n   */\n  \"region\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(255)), { nullable: true }),\n  /**\n   * The [IANA timezone](https://nodatime.org/TimeZones) of the user.\n   */\n  \"timezone\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(255)), { nullable: true }),\n  \"type\": S.Literal(\"approximate\")\n}) {}\n\nexport class BetaWebSearchTool20250305 extends S.Class<BetaWebSearchTool20250305>(\"BetaWebSearchTool20250305\")({\n  /**\n   * If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`.\n   */\n  \"allowed_domains\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`.\n   */\n  \"blocked_domains\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * Maximum number of times the tool can be used in the API request.\n   */\n  \"max_uses\": S.optionalWith(S.Int.pipe(S.greaterThan(0)), { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"web_search\"),\n  \"type\": S.Literal(\"web_search_20250305\"),\n  /**\n   * Parameters for the user's location. Used to provide more relevant search results.\n   */\n  \"user_location\": S.optionalWith(BetaUserLocation, { nullable: true })\n}) {}\n\nexport class BetaWebFetchTool20250910 extends S.Class<BetaWebFetchTool20250910>(\"BetaWebFetchTool20250910\")({\n  /**\n   * List of domains to allow fetching from\n   */\n  \"allowed_domains\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * List of domains to block fetching from\n   */\n  \"blocked_domains\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Create a cache control breakpoint at this content block.\n   */\n  \"cache_control\": S.optionalWith(BetaCacheControlEphemeral, { nullable: true }),\n  /**\n   * Citations configuration for fetched documents. Citations are disabled by default.\n   */\n  \"citations\": S.optionalWith(BetaRequestCitationsConfig, { nullable: true }),\n  /**\n   * Maximum number of tokens used by including web page text content in the context. The limit is approximate and does not apply to binary content such as PDFs.\n   */\n  \"max_content_tokens\": S.optionalWith(S.Int.pipe(S.greaterThan(0)), { nullable: true }),\n  /**\n   * Maximum number of times the tool can be used in the API request.\n   */\n  \"max_uses\": S.optionalWith(S.Int.pipe(S.greaterThan(0)), { nullable: true }),\n  /**\n   * Name of the tool.\n   *\n   * This is how the tool will be called by the model and in `tool_use` blocks.\n   */\n  \"name\": S.Literal(\"web_fetch\"),\n  \"type\": S.Literal(\"web_fetch_20250910\")\n}) {}\n\nexport class BetaCreateMessageParams extends S.Class<BetaCreateMessageParams>(\"BetaCreateMessageParams\")({\n  \"model\": S.Union(S.String, Model),\n  /**\n   * Input messages.\n   *\n   * Our models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.\n   *\n   * Each input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.\n   *\n   * If the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.\n   *\n   * Example with a single `user` message:\n   *\n   * ```json\n   * [{\"role\": \"user\", \"content\": \"Hello, Claude\"}]\n   * ```\n   *\n   * Example with multiple conversational turns:\n   *\n   * ```json\n   * [\n   *   {\"role\": \"user\", \"content\": \"Hello there.\"},\n   *   {\"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\"},\n   *   {\"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\"},\n   * ]\n   * ```\n   *\n   * Example with a partially-filled response from Claude:\n   *\n   * ```json\n   * [\n   *   {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n   *   {\"role\": \"assistant\", \"content\": \"The best answer is (\"},\n   * ]\n   * ```\n   *\n   * Each input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `\"text\"`. The following input messages are equivalent:\n   *\n   * ```json\n   * {\"role\": \"user\", \"content\": \"Hello, Claude\"}\n   * ```\n   *\n   * ```json\n   * {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, Claude\"}]}\n   * ```\n   *\n   * See [input examples](https://docs.claude.com/en/api/messages-examples).\n   *\n   * Note that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `\"system\"` role for input messages in the Messages API.\n   *\n   * There is a limit of 100,000 messages in a single request.\n   */\n  \"messages\": S.Array(BetaInputMessage),\n  /**\n   * Container identifier for reuse across requests.\n   */\n  \"container\": S.optionalWith(S.Union(BetaContainerParams, S.String), { nullable: true }),\n  /**\n   * Context management configuration.\n   *\n   * This allows you to control how Claude manages context across multiple requests, such as whether to clear function results or not.\n   */\n  \"context_management\": S.optionalWith(BetaContextManagementConfig, { nullable: true }),\n  /**\n   * The maximum number of tokens to generate before stopping.\n   *\n   * Note that our models may stop _before_ reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate.\n   *\n   * Different models have different maximum values for this parameter.  See [models](https://docs.claude.com/en/docs/models-overview) for details.\n   */\n  \"max_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n  /**\n   * MCP servers to be utilized in this request\n   */\n  \"mcp_servers\": S.optionalWith(S.Array(BetaRequestMCPServerURLDefinition).pipe(S.maxItems(20)), { nullable: true }),\n  /**\n   * An object describing metadata about the request.\n   */\n  \"metadata\": S.optionalWith(BetaMetadata, { nullable: true }),\n  /**\n   * Determines whether to use priority capacity (if available) or standard capacity for this request.\n   *\n   * Anthropic offers different levels of service for your API requests. See [service-tiers](https://docs.claude.com/en/api/service-tiers) for details.\n   */\n  \"service_tier\": S.optionalWith(BetaCreateMessageParamsServiceTier, { nullable: true }),\n  /**\n   * Custom text sequences that will cause the model to stop generating.\n   *\n   * Our models will normally stop when they have naturally completed their turn, which will result in a response `stop_reason` of `\"end_turn\"`.\n   *\n   * If you want the model to stop generating when it encounters custom strings of text, you can use the `stop_sequences` parameter. If the model encounters one of the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"` and the response `stop_sequence` value will contain the matched stop sequence.\n   */\n  \"stop_sequences\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Whether to incrementally stream the response using server-sent events.\n   *\n   * See [streaming](https://docs.claude.com/en/api/messages-streaming) for details.\n   */\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * System prompt.\n   *\n   * A system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).\n   */\n  \"system\": S.optionalWith(S.Union(S.String, S.Array(BetaRequestTextBlock)), { nullable: true }),\n  /**\n   * Amount of randomness injected into the response.\n   *\n   * Defaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for analytical / multiple choice, and closer to `1.0` for creative and generative tasks.\n   *\n   * Note that even with `temperature` of `0.0`, the results will not be fully deterministic.\n   */\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  \"thinking\": S.optionalWith(BetaThinkingConfigParam, { nullable: true }),\n  \"tool_choice\": S.optionalWith(BetaToolChoice, { nullable: true }),\n  /**\n   * Definitions of tools that the model may use.\n   *\n   * If you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.\n   *\n   * There are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview\\#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n   *\n   * Each tool definition includes:\n   *\n   * * `name`: Name of the tool.\n   * * `description`: Optional, but strongly-recommended description of the tool.\n   * * `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.\n   *\n   * For example, if you defined `tools` as:\n   *\n   * ```json\n   * [\n   *   {\n   *     \"name\": \"get_stock_price\",\n   *     \"description\": \"Get the current stock price for a given ticker symbol.\",\n   *     \"input_schema\": {\n   *       \"type\": \"object\",\n   *       \"properties\": {\n   *         \"ticker\": {\n   *           \"type\": \"string\",\n   *           \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n   *         }\n   *       },\n   *       \"required\": [\"ticker\"]\n   *     }\n   *   }\n   * ]\n   * ```\n   *\n   * And then asked the model \"What's the S&P 500 at today?\", the model might produce `tool_use` content blocks in the response like this:\n   *\n   * ```json\n   * [\n   *   {\n   *     \"type\": \"tool_use\",\n   *     \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n   *     \"name\": \"get_stock_price\",\n   *     \"input\": { \"ticker\": \"^GSPC\" }\n   *   }\n   * ]\n   * ```\n   *\n   * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an input, and return the following back to the model in a subsequent `user` message:\n   *\n   * ```json\n   * [\n   *   {\n   *     \"type\": \"tool_result\",\n   *     \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n   *     \"content\": \"259.75 USD\"\n   *   }\n   * ]\n   * ```\n   *\n   * Tools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.\n   *\n   * See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.\n   */\n  \"tools\": S.optionalWith(\n    S.Array(\n      S.Union(\n        BetaTool,\n        BetaBashTool20241022,\n        BetaBashTool20250124,\n        BetaCodeExecutionTool20250522,\n        BetaCodeExecutionTool20250825,\n        BetaComputerUseTool20241022,\n        BetaMemoryTool20250818,\n        BetaComputerUseTool20250124,\n        BetaTextEditor20241022,\n        BetaTextEditor20250124,\n        BetaTextEditor20250429,\n        BetaTextEditor20250728,\n        BetaWebSearchTool20250305,\n        BetaWebFetchTool20250910\n      )\n    ),\n    { nullable: true }\n  ),\n  /**\n   * Only sample from the top K options for each subsequent token.\n   *\n   * Used to remove \"long tail\" low probability responses. [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n   *\n   * Recommended for advanced use cases only. You usually only need to use `temperature`.\n   */\n  \"top_k\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0)), { nullable: true }),\n  /**\n   * Use nucleus sampling.\n   *\n   * In nucleus sampling, we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by `top_p`. You should either alter `temperature` or `top_p`, but not both.\n   *\n   * Recommended for advanced use cases only. You usually only need to use `temperature`.\n   */\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true })\n}) {}\n\nexport class BetaResponseCharLocationCitation\n  extends S.Class<BetaResponseCharLocationCitation>(\"BetaResponseCharLocationCitation\")({\n    \"cited_text\": S.String,\n    \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"document_title\": S.NullOr(S.String),\n    \"end_char_index\": S.Int,\n    \"file_id\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"start_char_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"type\": S.Literal(\"char_location\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"char_location\" as const)\n    )\n  })\n{}\n\nexport class BetaResponsePageLocationCitation\n  extends S.Class<BetaResponsePageLocationCitation>(\"BetaResponsePageLocationCitation\")({\n    \"cited_text\": S.String,\n    \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"document_title\": S.NullOr(S.String),\n    \"end_page_number\": S.Int,\n    \"file_id\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"start_page_number\": S.Int.pipe(S.greaterThanOrEqualTo(1)),\n    \"type\": S.Literal(\"page_location\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"page_location\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseContentBlockLocationCitation\n  extends S.Class<BetaResponseContentBlockLocationCitation>(\"BetaResponseContentBlockLocationCitation\")({\n    \"cited_text\": S.String,\n    \"document_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"document_title\": S.NullOr(S.String),\n    \"end_block_index\": S.Int,\n    \"file_id\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"start_block_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"type\": S.Literal(\"content_block_location\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"content_block_location\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseWebSearchResultLocationCitation\n  extends S.Class<BetaResponseWebSearchResultLocationCitation>(\"BetaResponseWebSearchResultLocationCitation\")({\n    \"cited_text\": S.String,\n    \"encrypted_index\": S.String,\n    \"title\": S.NullOr(S.String.pipe(S.maxLength(512))),\n    \"type\": S.Literal(\"web_search_result_location\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_search_result_location\" as const)\n    ),\n    \"url\": S.String\n  })\n{}\n\nexport class BetaResponseSearchResultLocationCitation\n  extends S.Class<BetaResponseSearchResultLocationCitation>(\"BetaResponseSearchResultLocationCitation\")({\n    \"cited_text\": S.String,\n    \"end_block_index\": S.Int,\n    \"search_result_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"source\": S.String,\n    \"start_block_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"title\": S.NullOr(S.String),\n    \"type\": S.Literal(\"search_result_location\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"search_result_location\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseTextBlock extends S.Class<BetaResponseTextBlock>(\"BetaResponseTextBlock\")({\n  /**\n   * Citations supporting the text block.\n   *\n   * The type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.\n   */\n  \"citations\": S.optionalWith(\n    S.NullOr(\n      S.Array(\n        S.Union(\n          BetaResponseCharLocationCitation,\n          BetaResponsePageLocationCitation,\n          BetaResponseContentBlockLocationCitation,\n          BetaResponseWebSearchResultLocationCitation,\n          BetaResponseSearchResultLocationCitation\n        )\n      )\n    ),\n    { default: () => null }\n  ),\n  \"text\": S.String.pipe(S.minLength(0), S.maxLength(5000000)),\n  \"type\": S.Literal(\"text\").pipe(S.propertySignature, S.withConstructorDefault(() => \"text\" as const))\n}) {}\n\nexport class BetaResponseThinkingBlock extends S.Class<BetaResponseThinkingBlock>(\"BetaResponseThinkingBlock\")({\n  \"signature\": S.String,\n  \"thinking\": S.String,\n  \"type\": S.Literal(\"thinking\").pipe(S.propertySignature, S.withConstructorDefault(() => \"thinking\" as const))\n}) {}\n\nexport class BetaResponseRedactedThinkingBlock\n  extends S.Class<BetaResponseRedactedThinkingBlock>(\"BetaResponseRedactedThinkingBlock\")({\n    \"data\": S.String,\n    \"type\": S.Literal(\"redacted_thinking\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"redacted_thinking\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseToolUseBlock extends S.Class<BetaResponseToolUseBlock>(\"BetaResponseToolUseBlock\")({\n  \"id\": S.String.pipe(S.pattern(new RegExp(\"^[a-zA-Z0-9_-]+$\"))),\n  \"input\": S.Record({ key: S.String, value: S.Unknown }),\n  \"name\": S.String.pipe(S.minLength(1)),\n  \"type\": S.Literal(\"tool_use\").pipe(S.propertySignature, S.withConstructorDefault(() => \"tool_use\" as const))\n}) {}\n\nexport class BetaResponseServerToolUseBlockName\n  extends S.Literal(\"web_search\", \"web_fetch\", \"code_execution\", \"bash_code_execution\", \"text_editor_code_execution\")\n{}\n\nexport class BetaResponseServerToolUseBlock\n  extends S.Class<BetaResponseServerToolUseBlock>(\"BetaResponseServerToolUseBlock\")({\n    \"id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"input\": S.Record({ key: S.String, value: S.Unknown }),\n    \"name\": BetaResponseServerToolUseBlockName,\n    \"type\": S.Literal(\"server_tool_use\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"server_tool_use\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseWebSearchToolResultError\n  extends S.Class<BetaResponseWebSearchToolResultError>(\"BetaResponseWebSearchToolResultError\")({\n    \"error_code\": BetaWebSearchToolResultErrorCode,\n    \"type\": S.Literal(\"web_search_tool_result_error\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_search_tool_result_error\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseWebSearchResultBlock\n  extends S.Class<BetaResponseWebSearchResultBlock>(\"BetaResponseWebSearchResultBlock\")({\n    \"encrypted_content\": S.String,\n    \"page_age\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"title\": S.String,\n    \"type\": S.Literal(\"web_search_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_search_result\" as const)\n    ),\n    \"url\": S.String\n  })\n{}\n\nexport class BetaResponseWebSearchToolResultBlock\n  extends S.Class<BetaResponseWebSearchToolResultBlock>(\"BetaResponseWebSearchToolResultBlock\")({\n    \"content\": S.Union(BetaResponseWebSearchToolResultError, S.Array(BetaResponseWebSearchResultBlock)),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"web_search_tool_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_search_tool_result\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseWebFetchToolResultError\n  extends S.Class<BetaResponseWebFetchToolResultError>(\"BetaResponseWebFetchToolResultError\")({\n    \"error_code\": BetaWebFetchToolResultErrorCode,\n    \"type\": S.Literal(\"web_fetch_tool_result_error\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_fetch_tool_result_error\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseCitationsConfig extends S.Class<BetaResponseCitationsConfig>(\"BetaResponseCitationsConfig\")({\n  \"enabled\": S.Boolean.pipe(S.propertySignature, S.withConstructorDefault(() => false as const))\n}) {}\n\nexport class BetaResponseDocumentBlock extends S.Class<BetaResponseDocumentBlock>(\"BetaResponseDocumentBlock\")({\n  /**\n   * Citation configuration for the document\n   */\n  \"citations\": S.optionalWith(S.NullOr(BetaResponseCitationsConfig), { default: () => null }),\n  \"source\": S.Union(BetaBase64PDFSource, BetaPlainTextSource),\n  /**\n   * The title of the document\n   */\n  \"title\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n  \"type\": S.Literal(\"document\").pipe(S.propertySignature, S.withConstructorDefault(() => \"document\" as const))\n}) {}\n\nexport class BetaResponseWebFetchResultBlock\n  extends S.Class<BetaResponseWebFetchResultBlock>(\"BetaResponseWebFetchResultBlock\")({\n    \"content\": BetaResponseDocumentBlock,\n    /**\n     * ISO 8601 timestamp when the content was retrieved\n     */\n    \"retrieved_at\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"type\": S.Literal(\"web_fetch_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_fetch_result\" as const)\n    ),\n    /**\n     * Fetched content URL\n     */\n    \"url\": S.String\n  })\n{}\n\nexport class BetaResponseWebFetchToolResultBlock\n  extends S.Class<BetaResponseWebFetchToolResultBlock>(\"BetaResponseWebFetchToolResultBlock\")({\n    \"content\": S.Union(BetaResponseWebFetchToolResultError, BetaResponseWebFetchResultBlock),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"web_fetch_tool_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"web_fetch_tool_result\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseCodeExecutionToolResultError\n  extends S.Class<BetaResponseCodeExecutionToolResultError>(\"BetaResponseCodeExecutionToolResultError\")({\n    \"error_code\": BetaCodeExecutionToolResultErrorCode,\n    \"type\": S.Literal(\"code_execution_tool_result_error\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"code_execution_tool_result_error\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseCodeExecutionOutputBlock\n  extends S.Class<BetaResponseCodeExecutionOutputBlock>(\"BetaResponseCodeExecutionOutputBlock\")({\n    \"file_id\": S.String,\n    \"type\": S.Literal(\"code_execution_output\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"code_execution_output\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseCodeExecutionResultBlock\n  extends S.Class<BetaResponseCodeExecutionResultBlock>(\"BetaResponseCodeExecutionResultBlock\")({\n    \"content\": S.Array(BetaResponseCodeExecutionOutputBlock),\n    \"return_code\": S.Int,\n    \"stderr\": S.String,\n    \"stdout\": S.String,\n    \"type\": S.Literal(\"code_execution_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"code_execution_result\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseCodeExecutionToolResultBlock\n  extends S.Class<BetaResponseCodeExecutionToolResultBlock>(\"BetaResponseCodeExecutionToolResultBlock\")({\n    \"content\": S.Union(BetaResponseCodeExecutionToolResultError, BetaResponseCodeExecutionResultBlock),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"code_execution_tool_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"code_execution_tool_result\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseBashCodeExecutionToolResultError\n  extends S.Class<BetaResponseBashCodeExecutionToolResultError>(\"BetaResponseBashCodeExecutionToolResultError\")({\n    \"error_code\": BetaBashCodeExecutionToolResultErrorCode,\n    \"type\": S.Literal(\"bash_code_execution_tool_result_error\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"bash_code_execution_tool_result_error\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseBashCodeExecutionOutputBlock\n  extends S.Class<BetaResponseBashCodeExecutionOutputBlock>(\"BetaResponseBashCodeExecutionOutputBlock\")({\n    \"file_id\": S.String,\n    \"type\": S.Literal(\"bash_code_execution_output\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"bash_code_execution_output\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseBashCodeExecutionResultBlock\n  extends S.Class<BetaResponseBashCodeExecutionResultBlock>(\"BetaResponseBashCodeExecutionResultBlock\")({\n    \"content\": S.Array(BetaResponseBashCodeExecutionOutputBlock),\n    \"return_code\": S.Int,\n    \"stderr\": S.String,\n    \"stdout\": S.String,\n    \"type\": S.Literal(\"bash_code_execution_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"bash_code_execution_result\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseBashCodeExecutionToolResultBlock\n  extends S.Class<BetaResponseBashCodeExecutionToolResultBlock>(\"BetaResponseBashCodeExecutionToolResultBlock\")({\n    \"content\": S.Union(BetaResponseBashCodeExecutionToolResultError, BetaResponseBashCodeExecutionResultBlock),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"bash_code_execution_tool_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"bash_code_execution_tool_result\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseTextEditorCodeExecutionToolResultError\n  extends S.Class<BetaResponseTextEditorCodeExecutionToolResultError>(\n    \"BetaResponseTextEditorCodeExecutionToolResultError\"\n  )({\n    \"error_code\": BetaTextEditorCodeExecutionToolResultErrorCode,\n    \"error_message\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"type\": S.Literal(\"text_editor_code_execution_tool_result_error\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"text_editor_code_execution_tool_result_error\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseTextEditorCodeExecutionViewResultBlockFileType extends S.Literal(\"text\", \"image\", \"pdf\") {}\n\nexport class BetaResponseTextEditorCodeExecutionViewResultBlock\n  extends S.Class<BetaResponseTextEditorCodeExecutionViewResultBlock>(\n    \"BetaResponseTextEditorCodeExecutionViewResultBlock\"\n  )({\n    \"content\": S.String,\n    \"file_type\": BetaResponseTextEditorCodeExecutionViewResultBlockFileType,\n    \"num_lines\": S.optionalWith(S.NullOr(S.Int), { default: () => null }),\n    \"start_line\": S.optionalWith(S.NullOr(S.Int), { default: () => null }),\n    \"total_lines\": S.optionalWith(S.NullOr(S.Int), { default: () => null }),\n    \"type\": S.Literal(\"text_editor_code_execution_view_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"text_editor_code_execution_view_result\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseTextEditorCodeExecutionCreateResultBlock\n  extends S.Class<BetaResponseTextEditorCodeExecutionCreateResultBlock>(\n    \"BetaResponseTextEditorCodeExecutionCreateResultBlock\"\n  )({\n    \"is_file_update\": S.Boolean,\n    \"type\": S.Literal(\"text_editor_code_execution_create_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"text_editor_code_execution_create_result\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseTextEditorCodeExecutionStrReplaceResultBlock\n  extends S.Class<BetaResponseTextEditorCodeExecutionStrReplaceResultBlock>(\n    \"BetaResponseTextEditorCodeExecutionStrReplaceResultBlock\"\n  )({\n    \"lines\": S.optionalWith(S.NullOr(S.Array(S.String)), { default: () => null }),\n    \"new_lines\": S.optionalWith(S.NullOr(S.Int), { default: () => null }),\n    \"new_start\": S.optionalWith(S.NullOr(S.Int), { default: () => null }),\n    \"old_lines\": S.optionalWith(S.NullOr(S.Int), { default: () => null }),\n    \"old_start\": S.optionalWith(S.NullOr(S.Int), { default: () => null }),\n    \"type\": S.Literal(\"text_editor_code_execution_str_replace_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"text_editor_code_execution_str_replace_result\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseTextEditorCodeExecutionToolResultBlock\n  extends S.Class<BetaResponseTextEditorCodeExecutionToolResultBlock>(\n    \"BetaResponseTextEditorCodeExecutionToolResultBlock\"\n  )({\n    \"content\": S.Union(\n      BetaResponseTextEditorCodeExecutionToolResultError,\n      BetaResponseTextEditorCodeExecutionViewResultBlock,\n      BetaResponseTextEditorCodeExecutionCreateResultBlock,\n      BetaResponseTextEditorCodeExecutionStrReplaceResultBlock\n    ),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^srvtoolu_[a-zA-Z0-9_]+$\"))),\n    \"type\": S.Literal(\"text_editor_code_execution_tool_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"text_editor_code_execution_tool_result\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseMCPToolUseBlock extends S.Class<BetaResponseMCPToolUseBlock>(\"BetaResponseMCPToolUseBlock\")({\n  \"id\": S.String.pipe(S.pattern(new RegExp(\"^[a-zA-Z0-9_-]+$\"))),\n  \"input\": S.Record({ key: S.String, value: S.Unknown }),\n  /**\n   * The name of the MCP tool\n   */\n  \"name\": S.String,\n  /**\n   * The name of the MCP server\n   */\n  \"server_name\": S.String,\n  \"type\": S.Literal(\"mcp_tool_use\").pipe(S.propertySignature, S.withConstructorDefault(() => \"mcp_tool_use\" as const))\n}) {}\n\nexport class BetaResponseMCPToolResultBlock\n  extends S.Class<BetaResponseMCPToolResultBlock>(\"BetaResponseMCPToolResultBlock\")({\n    \"content\": S.Union(S.String, S.Array(BetaResponseTextBlock)),\n    \"is_error\": S.Boolean.pipe(S.propertySignature, S.withConstructorDefault(() => false as const)),\n    \"tool_use_id\": S.String.pipe(S.pattern(new RegExp(\"^[a-zA-Z0-9_-]+$\"))),\n    \"type\": S.Literal(\"mcp_tool_result\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"mcp_tool_result\" as const)\n    )\n  })\n{}\n\n/**\n * Response model for a file uploaded to the container.\n */\nexport class BetaResponseContainerUploadBlock\n  extends S.Class<BetaResponseContainerUploadBlock>(\"BetaResponseContainerUploadBlock\")({\n    \"file_id\": S.String,\n    \"type\": S.Literal(\"container_upload\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"container_upload\" as const)\n    )\n  })\n{}\n\nexport class BetaContentBlock extends S.Union(\n  BetaResponseTextBlock,\n  BetaResponseThinkingBlock,\n  BetaResponseRedactedThinkingBlock,\n  BetaResponseToolUseBlock,\n  BetaResponseServerToolUseBlock,\n  BetaResponseWebSearchToolResultBlock,\n  BetaResponseWebFetchToolResultBlock,\n  BetaResponseCodeExecutionToolResultBlock,\n  BetaResponseBashCodeExecutionToolResultBlock,\n  BetaResponseTextEditorCodeExecutionToolResultBlock,\n  BetaResponseMCPToolUseBlock,\n  BetaResponseMCPToolResultBlock,\n  BetaResponseContainerUploadBlock\n) {}\n\nexport class BetaStopReason extends S.Literal(\n  \"end_turn\",\n  \"max_tokens\",\n  \"stop_sequence\",\n  \"tool_use\",\n  \"pause_turn\",\n  \"refusal\",\n  \"model_context_window_exceeded\"\n) {}\n\nexport class BetaCacheCreation extends S.Class<BetaCacheCreation>(\"BetaCacheCreation\")({\n  /**\n   * The number of input tokens used to create the 1 hour cache entry.\n   */\n  \"ephemeral_1h_input_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(0)).pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => 0 as const)\n  ),\n  /**\n   * The number of input tokens used to create the 5 minute cache entry.\n   */\n  \"ephemeral_5m_input_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(0)).pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => 0 as const)\n  )\n}) {}\n\nexport class BetaServerToolUsage extends S.Class<BetaServerToolUsage>(\"BetaServerToolUsage\")({\n  /**\n   * The number of web fetch tool requests.\n   */\n  \"web_fetch_requests\": S.Int.pipe(S.greaterThanOrEqualTo(0)).pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => 0 as const)\n  ),\n  /**\n   * The number of web search tool requests.\n   */\n  \"web_search_requests\": S.Int.pipe(S.greaterThanOrEqualTo(0)).pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => 0 as const)\n  )\n}) {}\n\nexport class BetaUsageServiceTierEnum extends S.Literal(\"standard\", \"priority\", \"batch\") {}\n\nexport class BetaUsage extends S.Class<BetaUsage>(\"BetaUsage\")({\n  /**\n   * Breakdown of cached tokens by TTL\n   */\n  \"cache_creation\": S.optionalWith(S.NullOr(BetaCacheCreation), { default: () => null }),\n  /**\n   * The number of input tokens used to create the cache entry.\n   */\n  \"cache_creation_input_tokens\": S.optionalWith(S.NullOr(S.Int.pipe(S.greaterThanOrEqualTo(0))), {\n    default: () => null\n  }),\n  /**\n   * The number of input tokens read from the cache.\n   */\n  \"cache_read_input_tokens\": S.optionalWith(S.NullOr(S.Int.pipe(S.greaterThanOrEqualTo(0))), { default: () => null }),\n  /**\n   * The number of input tokens which were used.\n   */\n  \"input_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n  /**\n   * The number of output tokens which were used.\n   */\n  \"output_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n  /**\n   * The number of server tool requests.\n   */\n  \"server_tool_use\": S.optionalWith(S.NullOr(BetaServerToolUsage), { default: () => null }),\n  /**\n   * If the request used the priority, standard, or batch tier.\n   */\n  \"service_tier\": S.optionalWith(S.NullOr(BetaUsageServiceTierEnum), { default: () => null })\n}) {}\n\nexport class BetaResponseClearToolUses20250919Edit\n  extends S.Class<BetaResponseClearToolUses20250919Edit>(\"BetaResponseClearToolUses20250919Edit\")({\n    /**\n     * Number of input tokens cleared by this edit.\n     */\n    \"cleared_input_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    /**\n     * Number of tool uses that were cleared.\n     */\n    \"cleared_tool_uses\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    /**\n     * The type of context management edit applied.\n     */\n    \"type\": S.Literal(\"clear_tool_uses_20250919\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"clear_tool_uses_20250919\" as const)\n    )\n  })\n{}\n\nexport class BetaResponseContextManagement\n  extends S.Class<BetaResponseContextManagement>(\"BetaResponseContextManagement\")({\n    /**\n     * List of context management edits that were applied.\n     */\n    \"applied_edits\": S.Array(BetaResponseClearToolUses20250919Edit)\n  })\n{}\n\n/**\n * Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)\n */\nexport class BetaSkillType extends S.Literal(\"anthropic\", \"custom\") {}\n\n/**\n * A skill that was loaded in a container (response model).\n */\nexport class BetaSkill extends S.Class<BetaSkill>(\"BetaSkill\")({\n  /**\n   * Skill ID\n   */\n  \"skill_id\": S.String.pipe(S.minLength(1), S.maxLength(64)),\n  /**\n   * Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)\n   */\n  \"type\": BetaSkillType,\n  /**\n   * Skill version or 'latest' for most recent version\n   */\n  \"version\": S.String.pipe(S.minLength(1), S.maxLength(64))\n}) {}\n\n/**\n * Information about the container used in the request (for the code execution tool)\n */\nexport class BetaContainer extends S.Class<BetaContainer>(\"BetaContainer\")({\n  /**\n   * The time at which the container will expire.\n   */\n  \"expires_at\": S.String,\n  /**\n   * Identifier for the container used in this request\n   */\n  \"id\": S.String,\n  /**\n   * Skills loaded in the container\n   */\n  \"skills\": S.optionalWith(S.NullOr(S.Array(BetaSkill)), { default: () => null })\n}) {}\n\nexport class BetaMessage extends S.Class<BetaMessage>(\"BetaMessage\")({\n  /**\n   * Unique object identifier.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Object type.\n   *\n   * For Messages, this is always `\"message\"`.\n   */\n  \"type\": S.Literal(\"message\").pipe(S.propertySignature, S.withConstructorDefault(() => \"message\" as const)),\n  /**\n   * Conversational role of the generated message.\n   *\n   * This will always be `\"assistant\"`.\n   */\n  \"role\": S.Literal(\"assistant\").pipe(S.propertySignature, S.withConstructorDefault(() => \"assistant\" as const)),\n  /**\n   * Content generated by the model.\n   *\n   * This is an array of content blocks, each of which has a `type` that determines its shape.\n   *\n   * Example:\n   *\n   * ```json\n   * [{\"type\": \"text\", \"text\": \"Hi, I'm Claude.\"}]\n   * ```\n   *\n   * If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output.\n   *\n   * For example, if the input `messages` were:\n   * ```json\n   * [\n   *   {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n   *   {\"role\": \"assistant\", \"content\": \"The best answer is (\"}\n   * ]\n   * ```\n   *\n   * Then the response `content` might be:\n   *\n   * ```json\n   * [{\"type\": \"text\", \"text\": \"B)\"}]\n   * ```\n   */\n  \"content\": S.Array(BetaContentBlock),\n  \"model\": S.Union(S.String, Model),\n  /**\n   * The reason that we stopped.\n   *\n   * This may be one the following values:\n   * * `\"end_turn\"`: the model reached a natural stopping point\n   * * `\"max_tokens\"`: we exceeded the requested `max_tokens` or the model's maximum\n   * * `\"stop_sequence\"`: one of your provided custom `stop_sequences` was generated\n   * * `\"tool_use\"`: the model invoked one or more tools\n   * * `\"pause_turn\"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.\n   * * `\"refusal\"`: when streaming classifiers intervene to handle potential policy violations\n   *\n   * In non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise.\n   */\n  \"stop_reason\": S.NullOr(BetaStopReason),\n  /**\n   * Which custom stop sequence was generated, if any.\n   *\n   * This value will be a non-null string if one of your custom stop sequences was generated.\n   */\n  \"stop_sequence\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n  /**\n   * Billing and rate-limit usage.\n   *\n   * Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.\n   *\n   * Under the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.\n   *\n   * For example, `output_tokens` will be non-zero, even for an empty string response from Claude.\n   *\n   * Total input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n   */\n  \"usage\": BetaUsage,\n  /**\n   * Context management response.\n   *\n   * Information about context management strategies applied during the request.\n   */\n  \"context_management\": S.optionalWith(S.NullOr(BetaResponseContextManagement), { default: () => null }),\n  /**\n   * Information about the container used in this request.\n   *\n   * This will be non-null if a container tool (e.g. code execution) was used.\n   */\n  \"container\": S.optionalWith(S.NullOr(BetaContainer), { default: () => null })\n}) {}\n\nexport class BetaInvalidRequestError extends S.Class<BetaInvalidRequestError>(\"BetaInvalidRequestError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Invalid request\" as const)),\n  \"type\": S.Literal(\"invalid_request_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"invalid_request_error\" as const)\n  )\n}) {}\n\nexport class BetaAuthenticationError extends S.Class<BetaAuthenticationError>(\"BetaAuthenticationError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Authentication error\" as const)),\n  \"type\": S.Literal(\"authentication_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"authentication_error\" as const)\n  )\n}) {}\n\nexport class BetaBillingError extends S.Class<BetaBillingError>(\"BetaBillingError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Billing error\" as const)),\n  \"type\": S.Literal(\"billing_error\").pipe(S.propertySignature, S.withConstructorDefault(() => \"billing_error\" as const))\n}) {}\n\nexport class BetaPermissionError extends S.Class<BetaPermissionError>(\"BetaPermissionError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Permission denied\" as const)),\n  \"type\": S.Literal(\"permission_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"permission_error\" as const)\n  )\n}) {}\n\nexport class BetaNotFoundError extends S.Class<BetaNotFoundError>(\"BetaNotFoundError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Not found\" as const)),\n  \"type\": S.Literal(\"not_found_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"not_found_error\" as const)\n  )\n}) {}\n\nexport class BetaRateLimitError extends S.Class<BetaRateLimitError>(\"BetaRateLimitError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Rate limited\" as const)),\n  \"type\": S.Literal(\"rate_limit_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"rate_limit_error\" as const)\n  )\n}) {}\n\nexport class BetaGatewayTimeoutError extends S.Class<BetaGatewayTimeoutError>(\"BetaGatewayTimeoutError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Request timeout\" as const)),\n  \"type\": S.Literal(\"timeout_error\").pipe(S.propertySignature, S.withConstructorDefault(() => \"timeout_error\" as const))\n}) {}\n\nexport class BetaAPIError extends S.Class<BetaAPIError>(\"BetaAPIError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Internal server error\" as const)),\n  \"type\": S.Literal(\"api_error\").pipe(S.propertySignature, S.withConstructorDefault(() => \"api_error\" as const))\n}) {}\n\nexport class BetaOverloadedError extends S.Class<BetaOverloadedError>(\"BetaOverloadedError\")({\n  \"message\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"Overloaded\" as const)),\n  \"type\": S.Literal(\"overloaded_error\").pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"overloaded_error\" as const)\n  )\n}) {}\n\nexport class BetaErrorResponse extends S.Class<BetaErrorResponse>(\"BetaErrorResponse\")({\n  \"error\": S.Union(\n    BetaInvalidRequestError,\n    BetaAuthenticationError,\n    BetaBillingError,\n    BetaPermissionError,\n    BetaNotFoundError,\n    BetaRateLimitError,\n    BetaGatewayTimeoutError,\n    BetaAPIError,\n    BetaOverloadedError\n  ),\n  \"request_id\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n  \"type\": S.Literal(\"error\").pipe(S.propertySignature, S.withConstructorDefault(() => \"error\" as const))\n}) {}\n\nexport class BetaModelsListParams extends S.Struct({\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.\n   */\n  \"before_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.\n   */\n  \"after_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of items to return per page.\n   *\n   * Defaults to `20`. Ranges from `1` to `1000`.\n   */\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(1000)), {\n    nullable: true,\n    default: () => 20 as const\n  }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaModelInfo extends S.Class<BetaModelInfo>(\"BetaModelInfo\")({\n  /**\n   * RFC 3339 datetime string representing the time at which the model was released. May be set to an epoch value if the release date is unknown.\n   */\n  \"created_at\": S.String,\n  /**\n   * A human-readable name for the model.\n   */\n  \"display_name\": S.String,\n  /**\n   * Unique model identifier.\n   */\n  \"id\": S.String,\n  /**\n   * Object type.\n   *\n   * For Models, this is always `\"model\"`.\n   */\n  \"type\": S.Literal(\"model\").pipe(S.propertySignature, S.withConstructorDefault(() => \"model\" as const))\n}) {}\n\nexport class BetaListResponseModelInfo extends S.Class<BetaListResponseModelInfo>(\"BetaListResponseModelInfo\")({\n  \"data\": S.Array(BetaModelInfo),\n  /**\n   * First ID in the `data` list. Can be used as the `before_id` for the previous page.\n   */\n  \"first_id\": S.NullOr(S.String),\n  /**\n   * Indicates if there are more results in the requested page direction.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Last ID in the `data` list. Can be used as the `after_id` for the next page.\n   */\n  \"last_id\": S.NullOr(S.String)\n}) {}\n\nexport class BetaModelsGetParams extends S.Struct({\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaMessageBatchesListParams extends S.Struct({\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.\n   */\n  \"before_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.\n   */\n  \"after_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of items to return per page.\n   *\n   * Defaults to `20`. Ranges from `1` to `1000`.\n   */\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(1000)), {\n    nullable: true,\n    default: () => 20 as const\n  }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Processing status of the Message Batch.\n */\nexport class BetaMessageBatchProcessingStatus extends S.Literal(\"in_progress\", \"canceling\", \"ended\") {}\n\nexport class BetaRequestCounts extends S.Class<BetaRequestCounts>(\"BetaRequestCounts\")({\n  /**\n   * Number of requests in the Message Batch that have been canceled.\n   *\n   * This is zero until processing of the entire Message Batch has ended.\n   */\n  \"canceled\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Number of requests in the Message Batch that encountered an error.\n   *\n   * This is zero until processing of the entire Message Batch has ended.\n   */\n  \"errored\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Number of requests in the Message Batch that have expired.\n   *\n   * This is zero until processing of the entire Message Batch has ended.\n   */\n  \"expired\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Number of requests in the Message Batch that are processing.\n   */\n  \"processing\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Number of requests in the Message Batch that have completed successfully.\n   *\n   * This is zero until processing of the entire Message Batch has ended.\n   */\n  \"succeeded\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const))\n}) {}\n\nexport class BetaMessageBatch extends S.Class<BetaMessageBatch>(\"BetaMessageBatch\")({\n  /**\n   * RFC 3339 datetime string representing the time at which the Message Batch was archived and its results became unavailable.\n   */\n  \"archived_at\": S.NullOr(S.String),\n  /**\n   * RFC 3339 datetime string representing the time at which cancellation was initiated for the Message Batch. Specified only if cancellation was initiated.\n   */\n  \"cancel_initiated_at\": S.NullOr(S.String),\n  /**\n   * RFC 3339 datetime string representing the time at which the Message Batch was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * RFC 3339 datetime string representing the time at which processing for the Message Batch ended. Specified only once processing ends.\n   *\n   * Processing ends when every request in a Message Batch has either succeeded, errored, canceled, or expired.\n   */\n  \"ended_at\": S.NullOr(S.String),\n  /**\n   * RFC 3339 datetime string representing the time at which the Message Batch will expire and end processing, which is 24 hours after creation.\n   */\n  \"expires_at\": S.String,\n  /**\n   * Unique object identifier.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Processing status of the Message Batch.\n   */\n  \"processing_status\": BetaMessageBatchProcessingStatus,\n  /**\n   * Tallies requests within the Message Batch, categorized by their status.\n   *\n   * Requests start as `processing` and move to one of the other statuses only once processing of the entire batch ends. The sum of all values always matches the total number of requests in the batch.\n   */\n  \"request_counts\": BetaRequestCounts,\n  /**\n   * URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only once processing ends.\n   *\n   * Results in the file are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.\n   */\n  \"results_url\": S.NullOr(S.String),\n  /**\n   * Object type.\n   *\n   * For Message Batches, this is always `\"message_batch\"`.\n   */\n  \"type\": S.Literal(\"message_batch\").pipe(S.propertySignature, S.withConstructorDefault(() => \"message_batch\" as const))\n}) {}\n\nexport class BetaListResponseMessageBatch\n  extends S.Class<BetaListResponseMessageBatch>(\"BetaListResponseMessageBatch\")({\n    \"data\": S.Array(BetaMessageBatch),\n    /**\n     * First ID in the `data` list. Can be used as the `before_id` for the previous page.\n     */\n    \"first_id\": S.NullOr(S.String),\n    /**\n     * Indicates if there are more results in the requested page direction.\n     */\n    \"has_more\": S.Boolean,\n    /**\n     * Last ID in the `data` list. Can be used as the `after_id` for the next page.\n     */\n    \"last_id\": S.NullOr(S.String)\n  })\n{}\n\nexport class BetaMessageBatchesPostParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaMessageBatchIndividualRequestParams\n  extends S.Class<BetaMessageBatchIndividualRequestParams>(\"BetaMessageBatchIndividualRequestParams\")({\n    /**\n     * Developer-provided ID created for each request in a Message Batch. Useful for matching results to requests, as results may be given out of request order.\n     *\n     * Must be unique for each request within the Message Batch.\n     */\n    \"custom_id\": S.String.pipe(S.minLength(1), S.maxLength(64), S.pattern(new RegExp(\"^[a-zA-Z0-9_-]{1,64}$\"))),\n    /**\n     * Messages API creation parameters for the individual request.\n     *\n     * See the [Messages API reference](/en/api/messages) for full documentation on available parameters.\n     */\n    \"params\": BetaCreateMessageParams\n  })\n{}\n\nexport class BetaCreateMessageBatchParams\n  extends S.Class<BetaCreateMessageBatchParams>(\"BetaCreateMessageBatchParams\")({\n    /**\n     * List of requests for prompt completion. Each is an individual request to create a Message.\n     */\n    \"requests\": S.NonEmptyArray(BetaMessageBatchIndividualRequestParams).pipe(S.minItems(1), S.maxItems(10000))\n  })\n{}\n\nexport class BetaMessageBatchesRetrieveParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaMessageBatchesDeleteParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaDeleteMessageBatchResponse\n  extends S.Class<BetaDeleteMessageBatchResponse>(\"BetaDeleteMessageBatchResponse\")({\n    /**\n     * ID of the Message Batch.\n     */\n    \"id\": S.String,\n    /**\n     * Deleted object type.\n     *\n     * For Message Batches, this is always `\"message_batch_deleted\"`.\n     */\n    \"type\": S.Literal(\"message_batch_deleted\").pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"message_batch_deleted\" as const)\n    )\n  })\n{}\n\nexport class BetaMessageBatchesCancelParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaMessageBatchesResultsParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaMessagesCountTokensPostParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaCountMessageTokensParams\n  extends S.Class<BetaCountMessageTokensParams>(\"BetaCountMessageTokensParams\")({\n    /**\n     * Context management configuration.\n     *\n     * This allows you to control how Claude manages context across multiple requests, such as whether to clear function results or not.\n     */\n    \"context_management\": S.optionalWith(BetaContextManagementConfig, { nullable: true }),\n    /**\n     * MCP servers to be utilized in this request\n     */\n    \"mcp_servers\": S.optionalWith(S.Array(BetaRequestMCPServerURLDefinition).pipe(S.maxItems(20)), { nullable: true }),\n    /**\n     * Input messages.\n     *\n     * Our models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.\n     *\n     * Each input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.\n     *\n     * If the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.\n     *\n     * Example with a single `user` message:\n     *\n     * ```json\n     * [{\"role\": \"user\", \"content\": \"Hello, Claude\"}]\n     * ```\n     *\n     * Example with multiple conversational turns:\n     *\n     * ```json\n     * [\n     *   {\"role\": \"user\", \"content\": \"Hello there.\"},\n     *   {\"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\"},\n     *   {\"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\"},\n     * ]\n     * ```\n     *\n     * Example with a partially-filled response from Claude:\n     *\n     * ```json\n     * [\n     *   {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n     *   {\"role\": \"assistant\", \"content\": \"The best answer is (\"},\n     * ]\n     * ```\n     *\n     * Each input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `\"text\"`. The following input messages are equivalent:\n     *\n     * ```json\n     * {\"role\": \"user\", \"content\": \"Hello, Claude\"}\n     * ```\n     *\n     * ```json\n     * {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, Claude\"}]}\n     * ```\n     *\n     * See [input examples](https://docs.claude.com/en/api/messages-examples).\n     *\n     * Note that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `\"system\"` role for input messages in the Messages API.\n     *\n     * There is a limit of 100,000 messages in a single request.\n     */\n    \"messages\": S.Array(BetaInputMessage),\n    \"model\": S.Union(S.String, Model),\n    /**\n     * System prompt.\n     *\n     * A system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts).\n     */\n    \"system\": S.optionalWith(S.Union(S.String, S.Array(BetaRequestTextBlock)), { nullable: true }),\n    \"thinking\": S.optionalWith(BetaThinkingConfigParam, { nullable: true }),\n    \"tool_choice\": S.optionalWith(BetaToolChoice, { nullable: true }),\n    /**\n     * Definitions of tools that the model may use.\n     *\n     * If you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.\n     *\n     * There are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview\\#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n     *\n     * Each tool definition includes:\n     *\n     * * `name`: Name of the tool.\n     * * `description`: Optional, but strongly-recommended description of the tool.\n     * * `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.\n     *\n     * For example, if you defined `tools` as:\n     *\n     * ```json\n     * [\n     *   {\n     *     \"name\": \"get_stock_price\",\n     *     \"description\": \"Get the current stock price for a given ticker symbol.\",\n     *     \"input_schema\": {\n     *       \"type\": \"object\",\n     *       \"properties\": {\n     *         \"ticker\": {\n     *           \"type\": \"string\",\n     *           \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n     *         }\n     *       },\n     *       \"required\": [\"ticker\"]\n     *     }\n     *   }\n     * ]\n     * ```\n     *\n     * And then asked the model \"What's the S&P 500 at today?\", the model might produce `tool_use` content blocks in the response like this:\n     *\n     * ```json\n     * [\n     *   {\n     *     \"type\": \"tool_use\",\n     *     \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n     *     \"name\": \"get_stock_price\",\n     *     \"input\": { \"ticker\": \"^GSPC\" }\n     *   }\n     * ]\n     * ```\n     *\n     * You might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an input, and return the following back to the model in a subsequent `user` message:\n     *\n     * ```json\n     * [\n     *   {\n     *     \"type\": \"tool_result\",\n     *     \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n     *     \"content\": \"259.75 USD\"\n     *   }\n     * ]\n     * ```\n     *\n     * Tools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.\n     *\n     * See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.\n     */\n    \"tools\": S.optionalWith(\n      S.Array(\n        S.Union(\n          BetaTool,\n          BetaBashTool20241022,\n          BetaBashTool20250124,\n          BetaCodeExecutionTool20250522,\n          BetaCodeExecutionTool20250825,\n          BetaComputerUseTool20241022,\n          BetaMemoryTool20250818,\n          BetaComputerUseTool20250124,\n          BetaTextEditor20241022,\n          BetaTextEditor20250124,\n          BetaTextEditor20250429,\n          BetaTextEditor20250728,\n          BetaWebSearchTool20250305,\n          BetaWebFetchTool20250910\n        )\n      ),\n      { nullable: true }\n    )\n  })\n{}\n\nexport class BetaContextManagementResponse\n  extends S.Class<BetaContextManagementResponse>(\"BetaContextManagementResponse\")({\n    /**\n     * The original token count before context management was applied\n     */\n    \"original_input_tokens\": S.Int\n  })\n{}\n\nexport class BetaCountMessageTokensResponse\n  extends S.Class<BetaCountMessageTokensResponse>(\"BetaCountMessageTokensResponse\")({\n    /**\n     * Information about context management applied to the message.\n     */\n    \"context_management\": S.NullOr(BetaContextManagementResponse),\n    /**\n     * The total number of tokens across the provided list of messages, system prompt, and tools.\n     */\n    \"input_tokens\": S.Int\n  })\n{}\n\nexport class BetaListFilesV1FilesGetParams extends S.Struct({\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object.\n   */\n  \"before_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object.\n   */\n  \"after_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of items to return per page.\n   *\n   * Defaults to `20`. Ranges from `1` to `1000`.\n   */\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(1000)), {\n    nullable: true,\n    default: () => 20 as const\n  }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaFileMetadataSchema extends S.Class<BetaFileMetadataSchema>(\"BetaFileMetadataSchema\")({\n  /**\n   * RFC 3339 datetime string representing when the file was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Whether the file can be downloaded.\n   */\n  \"downloadable\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  /**\n   * Original filename of the uploaded file.\n   */\n  \"filename\": S.String.pipe(S.minLength(1), S.maxLength(500)),\n  /**\n   * Unique object identifier.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * MIME type of the file.\n   */\n  \"mime_type\": S.String.pipe(S.minLength(1), S.maxLength(255)),\n  /**\n   * Size of the file in bytes.\n   */\n  \"size_bytes\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n  /**\n   * Object type.\n   *\n   * For files, this is always `\"file\"`.\n   */\n  \"type\": S.Literal(\"file\")\n}) {}\n\nexport class BetaFileListResponse extends S.Class<BetaFileListResponse>(\"BetaFileListResponse\")({\n  /**\n   * List of file metadata objects.\n   */\n  \"data\": S.Array(BetaFileMetadataSchema),\n  /**\n   * ID of the first file in this page of results.\n   */\n  \"first_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Whether there are more results available.\n   */\n  \"has_more\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  /**\n   * ID of the last file in this page of results.\n   */\n  \"last_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaUploadFileV1FilesPostParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaUploadFileV1FilesPostRequest\n  extends S.Class<BetaUploadFileV1FilesPostRequest>(\"BetaUploadFileV1FilesPostRequest\")({\n    /**\n     * The file to upload\n     */\n    \"file\": S.instanceOf(globalThis.Blob)\n  })\n{}\n\nexport class BetaGetFileMetadataV1FilesFileIdGetParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaDeleteFileV1FilesFileIdDeleteParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaFileDeleteResponse extends S.Class<BetaFileDeleteResponse>(\"BetaFileDeleteResponse\")({\n  /**\n   * ID of the deleted file.\n   */\n  \"id\": S.String,\n  /**\n   * Deleted object type.\n   *\n   * For file deletion, this is always `\"file_deleted\"`.\n   */\n  \"type\": S.optionalWith(S.Literal(\"file_deleted\"), { nullable: true, default: () => \"file_deleted\" as const })\n}) {}\n\nexport class BetaDownloadFileV1FilesFileIdContentGetParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaListSkillsV1SkillsGetParams extends S.Struct({\n  /**\n   * Pagination token for fetching a specific page of results.\n   *\n   * Pass the value from a previous response's `next_page` field to get the next page of results.\n   */\n  \"page\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of results to return per page.\n   *\n   * Maximum value is 100. Defaults to 20.\n   */\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  /**\n   * Filter skills by source.\n   *\n   * If provided, only skills from the specified source will be returned:\n   * * `\"custom\"`: only return user-created skills\n   * * `\"anthropic\"`: only return Anthropic-created skills\n   */\n  \"source\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaapiSchemasSkillsSkill extends S.Class<BetaapiSchemasSkillsSkill>(\"BetaapiSchemasSkillsSkill\")({\n  /**\n   * ISO 8601 timestamp of when the skill was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Display title for the skill.\n   *\n   * This is a human-readable label that is not included in the prompt sent to the model.\n   */\n  \"display_title\": S.NullOr(S.String),\n  /**\n   * Unique identifier for the skill.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * The latest version identifier for the skill.\n   *\n   * This represents the most recent version of the skill that has been created.\n   */\n  \"latest_version\": S.NullOr(S.String),\n  /**\n   * Source of the skill.\n   *\n   * This may be one of the following values:\n   * * `\"custom\"`: the skill was created by a user\n   * * `\"anthropic\"`: the skill was created by Anthropic\n   */\n  \"source\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skills, this is always `\"skill\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill\" as const)),\n  /**\n   * ISO 8601 timestamp of when the skill was last updated.\n   */\n  \"updated_at\": S.String\n}) {}\n\nexport class BetaListSkillsResponse extends S.Class<BetaListSkillsResponse>(\"BetaListSkillsResponse\")({\n  /**\n   * List of skills.\n   */\n  \"data\": S.Array(BetaapiSchemasSkillsSkill),\n  /**\n   * Whether there are more results available.\n   *\n   * If `true`, there are additional results that can be fetched using the `next_page` token.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Token for fetching the next page of results.\n   *\n   * If `null`, there are no more results available. Pass this value to the `page_token` parameter in the next request to get the next page.\n   */\n  \"next_page\": S.NullOr(S.String)\n}) {}\n\nexport class BetaCreateSkillV1SkillsPostParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaBodyCreateSkillV1SkillsPost\n  extends S.Class<BetaBodyCreateSkillV1SkillsPost>(\"BetaBodyCreateSkillV1SkillsPost\")({\n    /**\n     * Display title for the skill.\n     *\n     * This is a human-readable label that is not included in the prompt sent to the model.\n     */\n    \"display_title\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Files to upload for the skill.\n     *\n     * All files must be in the same top-level directory and must include a SKILL.md file at the root of that directory.\n     */\n    \"files\": S.optionalWith(S.Array(S.instanceOf(globalThis.Blob)), { nullable: true })\n  })\n{}\n\nexport class BetaCreateSkillResponse extends S.Class<BetaCreateSkillResponse>(\"BetaCreateSkillResponse\")({\n  /**\n   * ISO 8601 timestamp of when the skill was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Display title for the skill.\n   *\n   * This is a human-readable label that is not included in the prompt sent to the model.\n   */\n  \"display_title\": S.NullOr(S.String),\n  /**\n   * Unique identifier for the skill.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * The latest version identifier for the skill.\n   *\n   * This represents the most recent version of the skill that has been created.\n   */\n  \"latest_version\": S.NullOr(S.String),\n  /**\n   * Source of the skill.\n   *\n   * This may be one of the following values:\n   * * `\"custom\"`: the skill was created by a user\n   * * `\"anthropic\"`: the skill was created by Anthropic\n   */\n  \"source\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skills, this is always `\"skill\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill\" as const)),\n  /**\n   * ISO 8601 timestamp of when the skill was last updated.\n   */\n  \"updated_at\": S.String\n}) {}\n\nexport class BetaGetSkillV1SkillsSkillIdGetParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaGetSkillResponse extends S.Class<BetaGetSkillResponse>(\"BetaGetSkillResponse\")({\n  /**\n   * ISO 8601 timestamp of when the skill was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Display title for the skill.\n   *\n   * This is a human-readable label that is not included in the prompt sent to the model.\n   */\n  \"display_title\": S.NullOr(S.String),\n  /**\n   * Unique identifier for the skill.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * The latest version identifier for the skill.\n   *\n   * This represents the most recent version of the skill that has been created.\n   */\n  \"latest_version\": S.NullOr(S.String),\n  /**\n   * Source of the skill.\n   *\n   * This may be one of the following values:\n   * * `\"custom\"`: the skill was created by a user\n   * * `\"anthropic\"`: the skill was created by Anthropic\n   */\n  \"source\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skills, this is always `\"skill\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill\" as const)),\n  /**\n   * ISO 8601 timestamp of when the skill was last updated.\n   */\n  \"updated_at\": S.String\n}) {}\n\nexport class BetaDeleteSkillV1SkillsSkillIdDeleteParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaDeleteSkillResponse extends S.Class<BetaDeleteSkillResponse>(\"BetaDeleteSkillResponse\")({\n  /**\n   * Unique identifier for the skill.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Deleted object type.\n   *\n   * For Skills, this is always `\"skill_deleted\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill_deleted\" as const))\n}) {}\n\nexport class BetaListSkillVersionsV1SkillsSkillIdVersionsGetParams extends S.Struct({\n  /**\n   * Optionally set to the `next_page` token from the previous response.\n   */\n  \"page\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of items to return per page.\n   *\n   * Defaults to `20`. Ranges from `1` to `1000`.\n   */\n  \"limit\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaSkillVersion extends S.Class<BetaSkillVersion>(\"BetaSkillVersion\")({\n  /**\n   * ISO 8601 timestamp of when the skill version was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Description of the skill version.\n   *\n   * This is extracted from the SKILL.md file in the skill upload.\n   */\n  \"description\": S.String,\n  /**\n   * Directory name of the skill version.\n   *\n   * This is the top-level directory name that was extracted from the uploaded files.\n   */\n  \"directory\": S.String,\n  /**\n   * Unique identifier for the skill version.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Human-readable name of the skill version.\n   *\n   * This is extracted from the SKILL.md file in the skill upload.\n   */\n  \"name\": S.String,\n  /**\n   * Identifier for the skill that this version belongs to.\n   */\n  \"skill_id\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skill Versions, this is always `\"skill_version\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill_version\" as const)),\n  /**\n   * Version identifier for the skill.\n   *\n   * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n   */\n  \"version\": S.String\n}) {}\n\nexport class BetaListSkillVersionsResponse\n  extends S.Class<BetaListSkillVersionsResponse>(\"BetaListSkillVersionsResponse\")({\n    /**\n     * List of skill versions.\n     */\n    \"data\": S.Array(BetaSkillVersion),\n    /**\n     * Indicates if there are more results in the requested page direction.\n     */\n    \"has_more\": S.Boolean,\n    /**\n     * Token to provide in as `page` in the subsequent request to retrieve the next page of data.\n     */\n    \"next_page\": S.NullOr(S.String)\n  })\n{}\n\nexport class BetaCreateSkillVersionV1SkillsSkillIdVersionsPostParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaBodyCreateSkillVersionV1SkillsSkillIdVersionsPost\n  extends S.Class<BetaBodyCreateSkillVersionV1SkillsSkillIdVersionsPost>(\n    \"BetaBodyCreateSkillVersionV1SkillsSkillIdVersionsPost\"\n  )({\n    /**\n     * Files to upload for the skill.\n     *\n     * All files must be in the same top-level directory and must include a SKILL.md file at the root of that directory.\n     */\n    \"files\": S.optionalWith(S.Array(S.instanceOf(globalThis.Blob)), { nullable: true })\n  })\n{}\n\nexport class BetaCreateSkillVersionResponse\n  extends S.Class<BetaCreateSkillVersionResponse>(\"BetaCreateSkillVersionResponse\")({\n    /**\n     * ISO 8601 timestamp of when the skill version was created.\n     */\n    \"created_at\": S.String,\n    /**\n     * Description of the skill version.\n     *\n     * This is extracted from the SKILL.md file in the skill upload.\n     */\n    \"description\": S.String,\n    /**\n     * Directory name of the skill version.\n     *\n     * This is the top-level directory name that was extracted from the uploaded files.\n     */\n    \"directory\": S.String,\n    /**\n     * Unique identifier for the skill version.\n     *\n     * The format and length of IDs may change over time.\n     */\n    \"id\": S.String,\n    /**\n     * Human-readable name of the skill version.\n     *\n     * This is extracted from the SKILL.md file in the skill upload.\n     */\n    \"name\": S.String,\n    /**\n     * Identifier for the skill that this version belongs to.\n     */\n    \"skill_id\": S.String,\n    /**\n     * Object type.\n     *\n     * For Skill Versions, this is always `\"skill_version\"`.\n     */\n    \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill_version\" as const)),\n    /**\n     * Version identifier for the skill.\n     *\n     * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n     */\n    \"version\": S.String\n  })\n{}\n\nexport class BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGetParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaGetSkillVersionResponse extends S.Class<BetaGetSkillVersionResponse>(\"BetaGetSkillVersionResponse\")({\n  /**\n   * ISO 8601 timestamp of when the skill version was created.\n   */\n  \"created_at\": S.String,\n  /**\n   * Description of the skill version.\n   *\n   * This is extracted from the SKILL.md file in the skill upload.\n   */\n  \"description\": S.String,\n  /**\n   * Directory name of the skill version.\n   *\n   * This is the top-level directory name that was extracted from the uploaded files.\n   */\n  \"directory\": S.String,\n  /**\n   * Unique identifier for the skill version.\n   *\n   * The format and length of IDs may change over time.\n   */\n  \"id\": S.String,\n  /**\n   * Human-readable name of the skill version.\n   *\n   * This is extracted from the SKILL.md file in the skill upload.\n   */\n  \"name\": S.String,\n  /**\n   * Identifier for the skill that this version belongs to.\n   */\n  \"skill_id\": S.String,\n  /**\n   * Object type.\n   *\n   * For Skill Versions, this is always `\"skill_version\"`.\n   */\n  \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill_version\" as const)),\n  /**\n   * Version identifier for the skill.\n   *\n   * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n   */\n  \"version\": S.String\n}) {}\n\nexport class BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDeleteParams extends S.Struct({\n  /**\n   * Optional header to specify the beta version(s) you want to use.\n   *\n   * To use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta.\n   */\n  \"anthropic-beta\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The version of the Claude API you want to use.\n   *\n   * Read more about versioning and our version history [here](https://docs.claude.com/en/api/versioning).\n   */\n  \"anthropic-version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Your unique API key for authentication.\n   *\n   * This key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace.\n   */\n  \"x-api-key\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BetaDeleteSkillVersionResponse\n  extends S.Class<BetaDeleteSkillVersionResponse>(\"BetaDeleteSkillVersionResponse\")({\n    /**\n     * Version identifier for the skill.\n     *\n     * Each version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\").\n     */\n    \"id\": S.String,\n    /**\n     * Deleted object type.\n     *\n     * For Skill Versions, this is always `\"skill_version_deleted\"`.\n     */\n    \"type\": S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"skill_version_deleted\" as const))\n  })\n{}\n\nexport const make = (\n  httpClient: HttpClient.HttpClient,\n  options: {\n    readonly transformClient?: ((client: HttpClient.HttpClient) => Effect.Effect<HttpClient.HttpClient>) | undefined\n  } = {}\n): Client => {\n  const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) =>\n    Effect.flatMap(\n      Effect.orElseSucceed(response.json, () => \"Unexpected status code\"),\n      (description) =>\n        Effect.fail(\n          new HttpClientError.ResponseError({\n            request: response.request,\n            response,\n            reason: \"StatusCode\",\n            description: typeof description === \"string\" ? description : JSON.stringify(description)\n          })\n        )\n    )\n  const withResponse: <A, E>(\n    f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E>\n  ) => (\n    request: HttpClientRequest.HttpClientRequest\n  ) => Effect.Effect<any, any> = options.transformClient\n    ? (f) => (request) =>\n      Effect.flatMap(\n        Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)),\n        f\n      )\n    : (f) => (request) => Effect.flatMap(httpClient.execute(request), f)\n  const decodeSuccess = <A, I, R>(schema: S.Schema<A, I, R>) => (response: HttpClientResponse.HttpClientResponse) =>\n    HttpClientResponse.schemaBodyJson(schema)(response)\n  const decodeError =\n    <const Tag extends string, A, I, R>(tag: Tag, schema: S.Schema<A, I, R>) =>\n    (response: HttpClientResponse.HttpClientResponse) =>\n      Effect.flatMap(\n        HttpClientResponse.schemaBodyJson(schema)(response),\n        (cause) => Effect.fail(ClientError(tag, cause, response))\n      )\n  return {\n    httpClient,\n    \"messagesPost\": (options) =>\n      HttpClientRequest.post(`/v1/messages`).pipe(\n        HttpClientRequest.setHeaders({ \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Message),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"completePost\": (options) =>\n      HttpClientRequest.post(`/v1/complete`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined,\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined\n        }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CompletionResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modelsList\": (options) =>\n      HttpClientRequest.get(`/v1/models`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"before_id\": options?.[\"before_id\"] as any,\n          \"after_id\": options?.[\"after_id\"] as any,\n          \"limit\": options?.[\"limit\"] as any\n        }),\n        HttpClientRequest.setHeaders({\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined,\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListResponseModelInfo),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modelsGet\": (modelId, options) =>\n      HttpClientRequest.get(`/v1/models/${modelId}`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined,\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ModelInfo),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"messageBatchesList\": (options) =>\n      HttpClientRequest.get(`/v1/messages/batches`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"before_id\": options?.[\"before_id\"] as any,\n          \"after_id\": options?.[\"after_id\"] as any,\n          \"limit\": options?.[\"limit\"] as any\n        }),\n        HttpClientRequest.setHeaders({\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListResponseMessageBatch),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"messageBatchesPost\": (options) =>\n      HttpClientRequest.post(`/v1/messages/batches`).pipe(\n        HttpClientRequest.setHeaders({ \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(MessageBatch),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"messageBatchesRetrieve\": (messageBatchId, options) =>\n      HttpClientRequest.get(`/v1/messages/batches/${messageBatchId}`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(MessageBatch),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"messageBatchesDelete\": (messageBatchId, options) =>\n      HttpClientRequest.del(`/v1/messages/batches/${messageBatchId}`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteMessageBatchResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"messageBatchesCancel\": (messageBatchId, options) =>\n      HttpClientRequest.post(`/v1/messages/batches/${messageBatchId}/cancel`).pipe(\n        HttpClientRequest.setHeaders({ \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(MessageBatch),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"messageBatchesResults\": (messageBatchId, options) =>\n      HttpClientRequest.get(`/v1/messages/batches/${messageBatchId}/results`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"messagesCountTokensPost\": (options) =>\n      HttpClientRequest.post(`/v1/messages/count_tokens`).pipe(\n        HttpClientRequest.setHeaders({ \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CountMessageTokensResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listFilesV1FilesGet\": (options) =>\n      HttpClientRequest.get(`/v1/files`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"before_id\": options?.[\"before_id\"] as any,\n          \"after_id\": options?.[\"after_id\"] as any,\n          \"limit\": options?.[\"limit\"] as any\n        }),\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FileListResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"uploadFileV1FilesPost\": (options) =>\n      HttpClientRequest.post(`/v1/files`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined\n        }),\n        HttpClientRequest.bodyFormDataRecord(options.payload as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FileMetadataSchema),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getFileMetadataV1FilesFileIdGet\": (fileId, options) =>\n      HttpClientRequest.get(`/v1/files/${fileId}`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FileMetadataSchema),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteFileV1FilesFileIdDelete\": (fileId, options) =>\n      HttpClientRequest.del(`/v1/files/${fileId}`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FileDeleteResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"downloadFileV1FilesFileIdContentGet\": (fileId, options) =>\n      HttpClientRequest.get(`/v1/files/${fileId}/content`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listSkillsV1SkillsGet\": (options) =>\n      HttpClientRequest.get(`/v1/skills`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"page\": options?.[\"page\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"source\": options?.[\"source\"] as any\n        }),\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListSkillsResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createSkillV1SkillsPost\": (options) =>\n      HttpClientRequest.post(`/v1/skills`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined\n        }),\n        HttpClientRequest.bodyFormDataRecord(options.payload as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateSkillResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getSkillV1SkillsSkillIdGet\": (skillId, options) =>\n      HttpClientRequest.get(`/v1/skills/${skillId}`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GetSkillResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteSkillV1SkillsSkillIdDelete\": (skillId, options) =>\n      HttpClientRequest.del(`/v1/skills/${skillId}`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteSkillResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listSkillVersionsV1SkillsSkillIdVersionsGet\": (skillId, options) =>\n      HttpClientRequest.get(`/v1/skills/${skillId}/versions`).pipe(\n        HttpClientRequest.setUrlParams({ \"page\": options?.[\"page\"] as any, \"limit\": options?.[\"limit\"] as any }),\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListSkillVersionsResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createSkillVersionV1SkillsSkillIdVersionsPost\": (skillId, options) =>\n      HttpClientRequest.post(`/v1/skills/${skillId}/versions`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined\n        }),\n        HttpClientRequest.bodyFormDataRecord(options.payload as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateSkillVersionResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getSkillVersionV1SkillsSkillIdVersionsVersionGet\": (skillId, version, options) =>\n      HttpClientRequest.get(`/v1/skills/${skillId}/versions/${version}`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GetSkillVersionResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteSkillVersionV1SkillsSkillIdVersionsVersionDelete\": (skillId, version, options) =>\n      HttpClientRequest.del(`/v1/skills/${skillId}/versions/${version}`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteSkillVersionResponse),\n          \"4xx\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaMessagesPost\": (options) =>\n      HttpClientRequest.post(`/v1/messages?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined\n        }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaMessage),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaModelsList\": (options) =>\n      HttpClientRequest.get(`/v1/models?beta=true`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"before_id\": options?.[\"before_id\"] as any,\n          \"after_id\": options?.[\"after_id\"] as any,\n          \"limit\": options?.[\"limit\"] as any\n        }),\n        HttpClientRequest.setHeaders({\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined,\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaListResponseModelInfo),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaModelsGet\": (modelId, options) =>\n      HttpClientRequest.get(`/v1/models/${modelId}?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined,\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaModelInfo),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaMessageBatchesList\": (options) =>\n      HttpClientRequest.get(`/v1/messages/batches?beta=true`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"before_id\": options?.[\"before_id\"] as any,\n          \"after_id\": options?.[\"after_id\"] as any,\n          \"limit\": options?.[\"limit\"] as any\n        }),\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaListResponseMessageBatch),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaMessageBatchesPost\": (options) =>\n      HttpClientRequest.post(`/v1/messages/batches?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined\n        }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaMessageBatch),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaMessageBatchesRetrieve\": (messageBatchId, options) =>\n      HttpClientRequest.get(`/v1/messages/batches/${messageBatchId}?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaMessageBatch),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaMessageBatchesDelete\": (messageBatchId, options) =>\n      HttpClientRequest.del(`/v1/messages/batches/${messageBatchId}?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaDeleteMessageBatchResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaMessageBatchesCancel\": (messageBatchId, options) =>\n      HttpClientRequest.post(`/v1/messages/batches/${messageBatchId}/cancel?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaMessageBatch),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaMessageBatchesResults\": (messageBatchId, options) =>\n      HttpClientRequest.get(`/v1/messages/batches/${messageBatchId}/results?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaMessagesCountTokensPost\": (options) =>\n      HttpClientRequest.post(`/v1/messages/count_tokens?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined\n        }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaCountMessageTokensResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaListFilesV1FilesGet\": (options) =>\n      HttpClientRequest.get(`/v1/files?beta=true`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"before_id\": options?.[\"before_id\"] as any,\n          \"after_id\": options?.[\"after_id\"] as any,\n          \"limit\": options?.[\"limit\"] as any\n        }),\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaFileListResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaUploadFileV1FilesPost\": (options) =>\n      HttpClientRequest.post(`/v1/files?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined\n        }),\n        HttpClientRequest.bodyFormDataRecord(options.payload as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaFileMetadataSchema),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaGetFileMetadataV1FilesFileIdGet\": (fileId, options) =>\n      HttpClientRequest.get(`/v1/files/${fileId}?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaFileMetadataSchema),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaDeleteFileV1FilesFileIdDelete\": (fileId, options) =>\n      HttpClientRequest.del(`/v1/files/${fileId}?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaFileDeleteResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaDownloadFileV1FilesFileIdContentGet\": (fileId, options) =>\n      HttpClientRequest.get(`/v1/files/${fileId}/content?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaListSkillsV1SkillsGet\": (options) =>\n      HttpClientRequest.get(`/v1/skills?beta=true`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"page\": options?.[\"page\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"source\": options?.[\"source\"] as any\n        }),\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaListSkillsResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaCreateSkillV1SkillsPost\": (options) =>\n      HttpClientRequest.post(`/v1/skills?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined\n        }),\n        HttpClientRequest.bodyFormDataRecord(options.payload as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaCreateSkillResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaGetSkillV1SkillsSkillIdGet\": (skillId, options) =>\n      HttpClientRequest.get(`/v1/skills/${skillId}?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaGetSkillResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaDeleteSkillV1SkillsSkillIdDelete\": (skillId, options) =>\n      HttpClientRequest.del(`/v1/skills/${skillId}?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaDeleteSkillResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaListSkillVersionsV1SkillsSkillIdVersionsGet\": (skillId, options) =>\n      HttpClientRequest.get(`/v1/skills/${skillId}/versions?beta=true`).pipe(\n        HttpClientRequest.setUrlParams({ \"page\": options?.[\"page\"] as any, \"limit\": options?.[\"limit\"] as any }),\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaListSkillVersionsResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaCreateSkillVersionV1SkillsSkillIdVersionsPost\": (skillId, options) =>\n      HttpClientRequest.post(`/v1/skills/${skillId}/versions?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options.params?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options.params?.[\"anthropic-version\"] ?? undefined\n        }),\n        HttpClientRequest.bodyFormDataRecord(options.payload as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaCreateSkillVersionResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaGetSkillVersionV1SkillsSkillIdVersionsVersionGet\": (skillId, version, options) =>\n      HttpClientRequest.get(`/v1/skills/${skillId}/versions/${version}?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaGetSkillVersionResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"betaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete\": (skillId, version, options) =>\n      HttpClientRequest.del(`/v1/skills/${skillId}/versions/${version}?beta=true`).pipe(\n        HttpClientRequest.setHeaders({\n          \"anthropic-beta\": options?.[\"anthropic-beta\"] ?? undefined,\n          \"anthropic-version\": options?.[\"anthropic-version\"] ?? undefined,\n          \"x-api-key\": options?.[\"x-api-key\"] ?? undefined\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BetaDeleteSkillVersionResponse),\n          \"4xx\": decodeError(\"BetaErrorResponse\", BetaErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      )\n  }\n}\n\nexport interface Client {\n  readonly httpClient: HttpClient.HttpClient\n  /**\n   * Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.\n   *\n   * The Messages API can be used for either single queries or stateless multi-turn conversations.\n   *\n   * Learn more about the Messages API in our [user guide](/en/docs/initial-setup)\n   */\n  readonly \"messagesPost\": (\n    options: {\n      readonly params?: typeof MessagesPostParams.Encoded | undefined\n      readonly payload: typeof CreateMessageParams.Encoded\n    }\n  ) => Effect.Effect<\n    typeof Message.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * [Legacy] Create a Text Completion.\n   *\n   * The Text Completions API is a legacy API. We recommend using the [Messages API](https://docs.claude.com/en/api/messages) going forward.\n   *\n   * Future models and features will not be compatible with Text Completions. See our [migration guide](https://docs.claude.com/en/api/migrating-from-text-completions-to-messages) for guidance in migrating from Text Completions to Messages.\n   */\n  readonly \"completePost\": (\n    options: {\n      readonly params?: typeof CompletePostParams.Encoded | undefined\n      readonly payload: typeof CompletionRequest.Encoded\n    }\n  ) => Effect.Effect<\n    typeof CompletionResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * List available models.\n   *\n   * The Models API response can be used to determine which models are available for use in the API. More recently released models are listed first.\n   */\n  readonly \"modelsList\": (\n    options?: typeof ModelsListParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ListResponseModelInfo.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Get a specific model.\n   *\n   * The Models API response can be used to determine information about a specific model or resolve a model alias to a model ID.\n   */\n  readonly \"modelsGet\": (\n    modelId: string,\n    options?: typeof ModelsGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ModelInfo.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * List all Message Batches within a Workspace. Most recently created batches are returned first.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"messageBatchesList\": (\n    options?: typeof MessageBatchesListParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ListResponseMessageBatch.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Send a batch of Message creation requests.\n   *\n   * The Message Batches API can be used to process multiple Messages API requests at once. Once a Message Batch is created, it begins processing immediately. Batches can take up to 24 hours to complete.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"messageBatchesPost\": (\n    options: {\n      readonly params?: typeof MessageBatchesPostParams.Encoded | undefined\n      readonly payload: typeof CreateMessageBatchParams.Encoded\n    }\n  ) => Effect.Effect<\n    typeof MessageBatch.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * This endpoint is idempotent and can be used to poll for Message Batch completion. To access the results of a Message Batch, make a request to the `results_url` field in the response.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"messageBatchesRetrieve\": (\n    messageBatchId: string,\n    options?: typeof MessageBatchesRetrieveParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof MessageBatch.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Delete a Message Batch.\n   *\n   * Message Batches can only be deleted once they've finished processing. If you'd like to delete an in-progress batch, you must first cancel it.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"messageBatchesDelete\": (\n    messageBatchId: string,\n    options?: typeof MessageBatchesDeleteParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof DeleteMessageBatchResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Batches may be canceled any time before processing ends. Once cancellation is initiated, the batch enters a `canceling` state, at which time the system may complete any in-progress, non-interruptible requests before finalizing cancellation.\n   *\n   * The number of canceled requests is specified in `request_counts`. To determine which requests were canceled, check the individual results within the batch. Note that cancellation may not result in any canceled requests if they were non-interruptible.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"messageBatchesCancel\": (\n    messageBatchId: string,\n    options?: typeof MessageBatchesCancelParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof MessageBatch.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Streams the results of a Message Batch as a `.jsonl` file.\n   *\n   * Each line in the file is a JSON object containing the result of a single request in the Message Batch. Results are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"messageBatchesResults\": (\n    messageBatchId: string,\n    options?: typeof MessageBatchesResultsParams.Encoded | undefined\n  ) => Effect.Effect<\n    void,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Count the number of tokens in a Message.\n   *\n   * The Token Count API can be used to count the number of tokens in a Message, including tools, images, and documents, without creating it.\n   *\n   * Learn more about token counting in our [user guide](/en/docs/build-with-claude/token-counting)\n   */\n  readonly \"messagesCountTokensPost\": (\n    options: {\n      readonly params?: typeof MessagesCountTokensPostParams.Encoded | undefined\n      readonly payload: typeof CountMessageTokensParams.Encoded\n    }\n  ) => Effect.Effect<\n    typeof CountMessageTokensResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * List Files\n   */\n  readonly \"listFilesV1FilesGet\": (\n    options?: typeof ListFilesV1FilesGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof FileListResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Upload File\n   */\n  readonly \"uploadFileV1FilesPost\": (\n    options: {\n      readonly params?: typeof UploadFileV1FilesPostParams.Encoded | undefined\n      readonly payload: typeof UploadFileV1FilesPostRequest.Encoded\n    }\n  ) => Effect.Effect<\n    typeof FileMetadataSchema.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Get File Metadata\n   */\n  readonly \"getFileMetadataV1FilesFileIdGet\": (\n    fileId: string,\n    options?: typeof GetFileMetadataV1FilesFileIdGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof FileMetadataSchema.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Delete File\n   */\n  readonly \"deleteFileV1FilesFileIdDelete\": (\n    fileId: string,\n    options?: typeof DeleteFileV1FilesFileIdDeleteParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof FileDeleteResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Download File\n   */\n  readonly \"downloadFileV1FilesFileIdContentGet\": (\n    fileId: string,\n    options?: typeof DownloadFileV1FilesFileIdContentGetParams.Encoded | undefined\n  ) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List Skills\n   */\n  readonly \"listSkillsV1SkillsGet\": (\n    options?: typeof ListSkillsV1SkillsGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ListSkillsResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Create Skill\n   */\n  readonly \"createSkillV1SkillsPost\": (\n    options: {\n      readonly params?: typeof CreateSkillV1SkillsPostParams.Encoded | undefined\n      readonly payload: typeof BodyCreateSkillV1SkillsPost.Encoded\n    }\n  ) => Effect.Effect<\n    typeof CreateSkillResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Get Skill\n   */\n  readonly \"getSkillV1SkillsSkillIdGet\": (\n    skillId: string,\n    options?: typeof GetSkillV1SkillsSkillIdGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof GetSkillResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Delete Skill\n   */\n  readonly \"deleteSkillV1SkillsSkillIdDelete\": (\n    skillId: string,\n    options?: typeof DeleteSkillV1SkillsSkillIdDeleteParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof DeleteSkillResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * List Skill Versions\n   */\n  readonly \"listSkillVersionsV1SkillsSkillIdVersionsGet\": (\n    skillId: string,\n    options?: typeof ListSkillVersionsV1SkillsSkillIdVersionsGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ListSkillVersionsResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Create Skill Version\n   */\n  readonly \"createSkillVersionV1SkillsSkillIdVersionsPost\": (\n    skillId: string,\n    options: {\n      readonly params?: typeof CreateSkillVersionV1SkillsSkillIdVersionsPostParams.Encoded | undefined\n      readonly payload: typeof BodyCreateSkillVersionV1SkillsSkillIdVersionsPost.Encoded\n    }\n  ) => Effect.Effect<\n    typeof CreateSkillVersionResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Get Skill Version\n   */\n  readonly \"getSkillVersionV1SkillsSkillIdVersionsVersionGet\": (\n    skillId: string,\n    version: string,\n    options?: typeof GetSkillVersionV1SkillsSkillIdVersionsVersionGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof GetSkillVersionResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Delete Skill Version\n   */\n  readonly \"deleteSkillVersionV1SkillsSkillIdVersionsVersionDelete\": (\n    skillId: string,\n    version: string,\n    options?: typeof DeleteSkillVersionV1SkillsSkillIdVersionsVersionDeleteParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof DeleteSkillVersionResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation.\n   *\n   * The Messages API can be used for either single queries or stateless multi-turn conversations.\n   *\n   * Learn more about the Messages API in our [user guide](/en/docs/initial-setup)\n   */\n  readonly \"betaMessagesPost\": (\n    options: {\n      readonly params?: typeof BetaMessagesPostParams.Encoded | undefined\n      readonly payload: typeof BetaCreateMessageParams.Encoded\n    }\n  ) => Effect.Effect<\n    typeof BetaMessage.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * List available models.\n   *\n   * The Models API response can be used to determine which models are available for use in the API. More recently released models are listed first.\n   */\n  readonly \"betaModelsList\": (\n    options?: typeof BetaModelsListParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaListResponseModelInfo.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Get a specific model.\n   *\n   * The Models API response can be used to determine information about a specific model or resolve a model alias to a model ID.\n   */\n  readonly \"betaModelsGet\": (\n    modelId: string,\n    options?: typeof BetaModelsGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaModelInfo.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * List all Message Batches within a Workspace. Most recently created batches are returned first.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"betaMessageBatchesList\": (\n    options?: typeof BetaMessageBatchesListParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaListResponseMessageBatch.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Send a batch of Message creation requests.\n   *\n   * The Message Batches API can be used to process multiple Messages API requests at once. Once a Message Batch is created, it begins processing immediately. Batches can take up to 24 hours to complete.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"betaMessageBatchesPost\": (\n    options: {\n      readonly params?: typeof BetaMessageBatchesPostParams.Encoded | undefined\n      readonly payload: typeof BetaCreateMessageBatchParams.Encoded\n    }\n  ) => Effect.Effect<\n    typeof BetaMessageBatch.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * This endpoint is idempotent and can be used to poll for Message Batch completion. To access the results of a Message Batch, make a request to the `results_url` field in the response.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"betaMessageBatchesRetrieve\": (\n    messageBatchId: string,\n    options?: typeof BetaMessageBatchesRetrieveParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaMessageBatch.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Delete a Message Batch.\n   *\n   * Message Batches can only be deleted once they've finished processing. If you'd like to delete an in-progress batch, you must first cancel it.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"betaMessageBatchesDelete\": (\n    messageBatchId: string,\n    options?: typeof BetaMessageBatchesDeleteParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaDeleteMessageBatchResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Batches may be canceled any time before processing ends. Once cancellation is initiated, the batch enters a `canceling` state, at which time the system may complete any in-progress, non-interruptible requests before finalizing cancellation.\n   *\n   * The number of canceled requests is specified in `request_counts`. To determine which requests were canceled, check the individual results within the batch. Note that cancellation may not result in any canceled requests if they were non-interruptible.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"betaMessageBatchesCancel\": (\n    messageBatchId: string,\n    options?: typeof BetaMessageBatchesCancelParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaMessageBatch.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Streams the results of a Message Batch as a `.jsonl` file.\n   *\n   * Each line in the file is a JSON object containing the result of a single request in the Message Batch. Results are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests.\n   *\n   * Learn more about the Message Batches API in our [user guide](/en/docs/build-with-claude/batch-processing)\n   */\n  readonly \"betaMessageBatchesResults\": (\n    messageBatchId: string,\n    options?: typeof BetaMessageBatchesResultsParams.Encoded | undefined\n  ) => Effect.Effect<\n    void,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Count the number of tokens in a Message.\n   *\n   * The Token Count API can be used to count the number of tokens in a Message, including tools, images, and documents, without creating it.\n   *\n   * Learn more about token counting in our [user guide](/en/docs/build-with-claude/token-counting)\n   */\n  readonly \"betaMessagesCountTokensPost\": (\n    options: {\n      readonly params?: typeof BetaMessagesCountTokensPostParams.Encoded | undefined\n      readonly payload: typeof BetaCountMessageTokensParams.Encoded\n    }\n  ) => Effect.Effect<\n    typeof BetaCountMessageTokensResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * List Files\n   */\n  readonly \"betaListFilesV1FilesGet\": (\n    options?: typeof BetaListFilesV1FilesGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaFileListResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Upload File\n   */\n  readonly \"betaUploadFileV1FilesPost\": (\n    options: {\n      readonly params?: typeof BetaUploadFileV1FilesPostParams.Encoded | undefined\n      readonly payload: typeof BetaUploadFileV1FilesPostRequest.Encoded\n    }\n  ) => Effect.Effect<\n    typeof BetaFileMetadataSchema.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Get File Metadata\n   */\n  readonly \"betaGetFileMetadataV1FilesFileIdGet\": (\n    fileId: string,\n    options?: typeof BetaGetFileMetadataV1FilesFileIdGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaFileMetadataSchema.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Delete File\n   */\n  readonly \"betaDeleteFileV1FilesFileIdDelete\": (\n    fileId: string,\n    options?: typeof BetaDeleteFileV1FilesFileIdDeleteParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaFileDeleteResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Download File\n   */\n  readonly \"betaDownloadFileV1FilesFileIdContentGet\": (\n    fileId: string,\n    options?: typeof BetaDownloadFileV1FilesFileIdContentGetParams.Encoded | undefined\n  ) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List Skills\n   */\n  readonly \"betaListSkillsV1SkillsGet\": (\n    options?: typeof BetaListSkillsV1SkillsGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaListSkillsResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Create Skill\n   */\n  readonly \"betaCreateSkillV1SkillsPost\": (\n    options: {\n      readonly params?: typeof BetaCreateSkillV1SkillsPostParams.Encoded | undefined\n      readonly payload: typeof BetaBodyCreateSkillV1SkillsPost.Encoded\n    }\n  ) => Effect.Effect<\n    typeof BetaCreateSkillResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Get Skill\n   */\n  readonly \"betaGetSkillV1SkillsSkillIdGet\": (\n    skillId: string,\n    options?: typeof BetaGetSkillV1SkillsSkillIdGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaGetSkillResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Delete Skill\n   */\n  readonly \"betaDeleteSkillV1SkillsSkillIdDelete\": (\n    skillId: string,\n    options?: typeof BetaDeleteSkillV1SkillsSkillIdDeleteParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaDeleteSkillResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * List Skill Versions\n   */\n  readonly \"betaListSkillVersionsV1SkillsSkillIdVersionsGet\": (\n    skillId: string,\n    options?: typeof BetaListSkillVersionsV1SkillsSkillIdVersionsGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaListSkillVersionsResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Create Skill Version\n   */\n  readonly \"betaCreateSkillVersionV1SkillsSkillIdVersionsPost\": (\n    skillId: string,\n    options: {\n      readonly params?: typeof BetaCreateSkillVersionV1SkillsSkillIdVersionsPostParams.Encoded | undefined\n      readonly payload: typeof BetaBodyCreateSkillVersionV1SkillsSkillIdVersionsPost.Encoded\n    }\n  ) => Effect.Effect<\n    typeof BetaCreateSkillVersionResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Get Skill Version\n   */\n  readonly \"betaGetSkillVersionV1SkillsSkillIdVersionsVersionGet\": (\n    skillId: string,\n    version: string,\n    options?: typeof BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGetParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaGetSkillVersionResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n  /**\n   * Delete Skill Version\n   */\n  readonly \"betaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete\": (\n    skillId: string,\n    version: string,\n    options?: typeof BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDeleteParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof BetaDeleteSkillVersionResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"BetaErrorResponse\", typeof BetaErrorResponse.Type>\n  >\n}\n\nexport interface ClientError<Tag extends string, E> {\n  readonly _tag: Tag\n  readonly request: HttpClientRequest.HttpClientRequest\n  readonly response: HttpClientResponse.HttpClientResponse\n  readonly cause: E\n}\n\nclass ClientErrorImpl extends Data.Error<{\n  _tag: string\n  cause: any\n  request: HttpClientRequest.HttpClientRequest\n  response: HttpClientResponse.HttpClientResponse\n}> {}\n\nexport const ClientError = <Tag extends string, E>(\n  tag: Tag,\n  cause: E,\n  response: HttpClientResponse.HttpClientResponse\n): ClientError<Tag, E> =>\n  new ClientErrorImpl({\n    _tag: tag,\n    cause,\n    response,\n    request: response.request\n  }) as any\n"
  },
  {
    "path": "packages/ai/anthropic/src/index.ts",
    "content": "/**\n * @since 1.0.0\n */\nexport * as AnthropicClient from \"./AnthropicClient.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as AnthropicConfig from \"./AnthropicConfig.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as AnthropicLanguageModel from \"./AnthropicLanguageModel.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as AnthropicTokenizer from \"./AnthropicTokenizer.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as AnthropicTool from \"./AnthropicTool.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Generated from \"./Generated.js\"\n"
  },
  {
    "path": "packages/ai/anthropic/src/internal/utilities.ts",
    "content": "import type * as Response from \"@effect/ai/Response\"\nimport * as Predicate from \"effect/Predicate\"\n\nconst finishReasonMap: Record<string, Response.FinishReason> = {\n  end_turn: \"stop\",\n  max_tokens: \"length\",\n  pause_turn: \"pause\",\n  refusal: \"content-filter\",\n  stop_sequence: \"stop\",\n  tool_use: \"tool-calls\"\n}\n\n/** @internal */\nexport const resolveFinishReason = (\n  finishReason: string,\n  isJsonResponse: boolean = false\n): Response.FinishReason => {\n  const reason = finishReasonMap[finishReason]\n  if (Predicate.isUndefined(reason)) {\n    return \"unknown\"\n  }\n  if (isJsonResponse && reason === \"tool-calls\") {\n    return \"stop\"\n  }\n  return reason\n}\n"
  },
  {
    "path": "packages/ai/anthropic/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"references\": [\n    { \"path\": \"../ai/tsconfig.build.json\" },\n    { \"path\": \"../../effect/tsconfig.build.json\" },\n    { \"path\": \"../../experimental/tsconfig.build.json\" },\n    { \"path\": \"../../platform/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/anthropic/tsconfig.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/ai/anthropic/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"references\": [\n    { \"path\": \"../ai/tsconfig.src.json\" },\n    { \"path\": \"../../effect/tsconfig.src.json\" },\n    { \"path\": \"../../experimental/tsconfig.src.json\" },\n    { \"path\": \"../../platform/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\",\n    \"outDir\": \"build/src\",\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/anthropic/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../../vitest/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"noEmit\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/anthropic/vitest.config.ts",
    "content": "import { mergeConfig, type ViteUserConfig } from \"vitest/config\"\nimport shared from \"../../../vitest.shared.js\"\n\nconst config: ViteUserConfig = {}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/ai/google/CHANGELOG.md",
    "content": "# @effect/ai-google\n\n## 0.14.0\n\n### Patch Changes\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n  - @effect/ai@0.35.0\n  - @effect/experimental@0.60.0\n  - @effect/platform@0.96.0\n\n## 0.13.0\n\n### Patch Changes\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n  - @effect/ai@0.34.0\n  - @effect/experimental@0.59.0\n  - @effect/platform@0.95.0\n\n## 0.12.1\n\n### Patch Changes\n\n- [#5958](https://github.com/Effect-TS/effect/pull/5958) [`c0a43bd`](https://github.com/Effect-TS/effect/commit/c0a43bd1456b2141a5383782091260e1c801c068) Thanks @izakfilmalter! - - `thinkingLevel` field on `ThinkingConfig` with values: `THINKING_LEVEL_UNSPECIFIED`, `MINIMAL`, `LOW`, `MEDIUM`, `HIGH`\n  - New `CandidateFinishReason` enum values: `IMAGE_PROHIBITED_CONTENT`, `IMAGE_OTHER`, `NO_IMAGE`, `IMAGE_RECITATION`, `MISSING_THOUGHT_SIGNATURE`\n  - Updated `finishReasonMap` in utilities to handle the new finish reason values\n\n## 0.12.0\n\n### Patch Changes\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n  - @effect/platform@0.94.0\n  - @effect/ai@0.33.0\n  - @effect/experimental@0.58.0\n\n## 0.11.1\n\n### Patch Changes\n\n- [#5834](https://github.com/Effect-TS/effect/pull/5834) [`59760c1`](https://github.com/Effect-TS/effect/commit/59760c1d10b72a539ba174a3ca78d29821b01818) Thanks @timurrakhimzhan! - Fixed \"oneOf\" toolChoice for google language model\n\n- Updated dependencies [[`65bff45`](https://github.com/Effect-TS/effect/commit/65bff451fc54d47b32995b3bc898ccc5f8b1beb6)]:\n  - @effect/platform@0.93.7\n\n## 0.11.0\n\n### Patch Changes\n\n- Updated dependencies [[`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - effect@3.19.0\n  - @effect/platform@0.93.0\n  - @effect/ai@0.32.0\n  - @effect/experimental@0.57.0\n\n## 0.10.0\n\n### Minor Changes\n\n- [#5621](https://github.com/Effect-TS/effect/pull/5621) [`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825) Thanks @IMax153! - Remove `Either` / `EitherEncoded` from tool call results.\n\n  Specifically, the encoding of tool call results as an `Either` / `EitherEncoded` has been removed and is replaced by encoding the tool call success / failure directly into the `result` property.\n\n  To allow type-safe discrimination between a tool call result which was a success vs. one that was a failure, an `isFailure` property has also been added to the `\"tool-result\"` part. If `isFailure` is `true`, then the tool call handler result was an error.\n\n  ```ts\n  import * as AnthropicClient from \"@effect/ai-anthropic/AnthropicClient\"\n  import * as AnthropicLanguageModel from \"@effect/ai-anthropic/AnthropicLanguageModel\"\n  import * as LanguageModel from \"@effect/ai/LanguageModel\"\n  import * as Tool from \"@effect/ai/Tool\"\n  import * as Toolkit from \"@effect/ai/Toolkit\"\n  import * as NodeHttpClient from \"@effect/platform-node/NodeHttpClient\"\n  import { Config, Effect, Layer, Schema, Stream } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"An example of a tool with success and failure types\",\n    failureMode: \"return\", // Return errors in the response\n    parameters: { bar: Schema.Number },\n    success: Schema.Number,\n    failure: Schema.Struct({ reason: Schema.Literal(\"reason-1\", \"reason-2\") })\n  })\n\n  const MyToolkit = Toolkit.make(MyTool)\n\n  const MyToolkitLayer = MyToolkit.toLayer({\n    MyTool: () => Effect.succeed(42)\n  })\n\n  const program = LanguageModel.streamText({\n    prompt: \"Tell me about the meaning of life\",\n    toolkit: MyToolkit\n  }).pipe(\n    Stream.runForEach((part) => {\n      if (part.type === \"tool-result\" && part.name === \"MyTool\") {\n        // The `isFailure` property can be used to discriminate whether the result\n        // of a tool call is a success or a failure\n        if (part.isFailure) {\n          part.result\n          //   ^? { readonly reason: \"reason-1\" | \"reason-2\"; }\n        } else {\n          part.result\n          //   ^? number\n        }\n      }\n      return Effect.void\n    }),\n    Effect.provide(Claude)\n  )\n\n  const Anthropic = AnthropicClient.layerConfig({\n    apiKey: Config.redacted(\"ANTHROPIC_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(Effect.provide([Anthropic, MyToolkitLayer]), Effect.runPromise)\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825)]:\n  - @effect/ai@0.31.0\n\n## 0.9.0\n\n### Minor Changes\n\n- [#5614](https://github.com/Effect-TS/effect/pull/5614) [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652) Thanks @IMax153! - Previously, tool call handler errors were _always_ raised as an expected error in the Effect `E` channel at the point of execution of the tool call handler (i.e. when a `generate*` method is invoked on a `LanguageModel`).\n\n  With this PR, the end user now has control over whether tool call handler errors should be raised as an Effect error, or returned by the SDK to allow, for example, sending that error information to another application.\n\n  ### Tool Call Specification\n\n  The `Tool.make` and `Tool.providerDefined` constructors now take an extra optional parameter called `failureMode`, which can be set to either `\"error\"` or `\"return\"`.\n\n  ```ts\n  import { Tool } from \"@effect/ai\"\n  import { Schema } from \"effect\"\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"My special tool\",\n    failureMode: \"return\" // \"error\" (default) or \"return\"\n    parameters: {\n      myParam: Schema.String\n    },\n    success: Schema.Struct({\n      mySuccess: Schema.String\n    }),\n    failure: Schema.Struct({\n      myFailure: Schema.String\n    })\n  })\n\n  ```\n\n  The semantics of `failureMode` are as follows:\n  - If set to `\"error\"` (the default), errors that occur during tool call handler execution will be returned in the error channel of the calling effect\n  - If set to `\"return\"`, errors that occur during tool call handler execution will be captured and returned as part of the tool call result\n\n  ### Response - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a large language model provider response is now represented as an `Either`.\n  - If the `result` is a `Left`, the `result` will be the `failure` specified in the tool call specification\n  - If the `result` is a `Right`, the `result` will be the `success` specified in the tool call specification\n\n  This is only relevant if the end user sets `failureMode` to `\"return\"`. If set to `\"error\"` (the default), then the `result` property will always be a `Right` with the successful result of the tool call handler.\n\n  Similarly the `encodedResult` field of a `\"tool-result\"` part will be represented as an `EitherEncoded`, where:\n  - `{ _tag: \"Left\", left: <failure> }` represents a tool call handler failure\n  - `{ _tag: \"Right\", right: <success> }` represents a tool call handler success\n\n  ### Prompt - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a prompt will now only accept an `EitherEncoded` as specified above.\n\n### Patch Changes\n\n- Updated dependencies [[`6ae2f5d`](https://github.com/Effect-TS/effect/commit/6ae2f5da45a9ed9832605eca12b3e2bf2e2a1a67), [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652)]:\n  - effect@3.18.4\n  - @effect/ai@0.30.0\n\n## 0.8.0\n\n### Patch Changes\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2), [`f8b93ac`](https://github.com/Effect-TS/effect/commit/f8b93ac6446efd3dd790778b0fc71d299a38f272)]:\n  - effect@3.18.0\n  - @effect/ai@0.29.0\n  - @effect/platform@0.92.0\n  - @effect/experimental@0.56.0\n\n## 0.7.1\n\n### Patch Changes\n\n- [#5571](https://github.com/Effect-TS/effect/pull/5571) [`122aa53`](https://github.com/Effect-TS/effect/commit/122aa53058ff008cf605cc2f0f0675a946c3cae9) Thanks @IMax153! - Ensure that AI provider clients filter response status for stream requests\n\n## 0.7.0\n\n### Patch Changes\n\n- Updated dependencies [[`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a)]:\n  - @effect/platform@0.91.0\n  - @effect/ai@0.28.0\n  - @effect/experimental@0.55.0\n\n## 0.6.1\n\n### Patch Changes\n\n- [#5521](https://github.com/Effect-TS/effect/pull/5521) [`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80) Thanks @IMax153! - Fix provider metadata and parse tool call parameters safely\n\n- [#5523](https://github.com/Effect-TS/effect/pull/5523) [`3128917`](https://github.com/Effect-TS/effect/commit/3128917009e639555f684668825e5d93a97618dd) Thanks @IMax153! - Fix handling of anyOf conversion from JSONSchema to OpenAPI schema\n\n- Updated dependencies [[`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80)]:\n  - @effect/ai@0.27.1\n\n## 0.6.0\n\n### Minor Changes\n\n- [#5469](https://github.com/Effect-TS/effect/pull/5469) [`42b914a`](https://github.com/Effect-TS/effect/commit/42b914a0e8750350ce17d434afaec7d655ddf4b7) Thanks @IMax153! - Refactor the Effect AI SDK and associated provider packages\n\n  This pull request contains a complete refactor of the base Effect AI SDK package\n  as well as the associated provider integration packages to improve flexibility\n  and enhance ergonomics. Major changes are outlined below.\n\n  ## Modules\n\n  All modules in the base Effect AI SDK have had the leading `Ai` prefix dropped\n  from their name (except for the `AiError` module).\n\n  For example, the `AiLanguageModel` module is now the `LanguageModel` module.\n\n  In addition, the `AiInput` module has been renamed to the `Prompt` module.\n\n  ## Prompts\n\n  The `Prompt` module has been completely redesigned with flexibility in mind.\n\n  The `Prompt` module now supports building a prompt using either the constructors\n  exposed from the `Prompt` module, or using raw prompt content parts / messages,\n  which should be familiar to those coming from other AI SDKs.\n\n  In addition, the `system` option has been removed from all `LanguageModel` methods\n  and must now be provided as part of the prompt.\n\n  **Prompt Constructors**\n\n  ```ts\n  import { LanguageModel, Prompt } from \"@effect/ai\"\n\n  const textPart = Prompt.makePart(\"text\", {\n    text: \"What is machine learning?\"\n  })\n\n  const userMessage = Prompt.makeMessage(\"user\", {\n    content: [textPart]\n  })\n\n  const systemMessage = Prompt.makeMessage(\"system\", {\n    content: \"You are an expert in machine learning\"\n  })\n\n  const program = LanguageModel.generateText({\n    prompt: Prompt.fromMessages([systemMessage, userMessage])\n  })\n  ```\n\n  **Raw Prompt Input**\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n\n  const program = LanguageModel.generateText({\n    prompt: [\n      { role: \"system\", content: \"You are an expert in machine learning\" },\n      {\n        role: \"user\",\n        content: [{ type: \"text\", text: \"What is machine learning?\" }]\n      }\n    ]\n  })\n  ```\n\n  **NOTE**: Providing a plain string as a prompt is still supported, and will be converted\n  internally into a user message with a single text content part.\n\n  ### Provider-Specific Options\n\n  To support specification of provider-specific options when interacting with large\n  language model providers, support has been added for adding provider-specific\n  options to the parts of a `Prompt`.\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-sonnet-4-20250514\")\n\n  const program = LanguageModel.generateText({\n    prompt: [\n      {\n        role: \"user\",\n        content: [{ type: \"text\", text: \"What is machine learning?\" }],\n        options: {\n          anthropic: { cacheControl: { type: \"ephemeral\", ttl: \"1h\" } }\n        }\n      }\n    ]\n  }).pipe(Effect.provide(Claude))\n  ```\n\n  ## Responses\n\n  The `Response` module has also been completely redesigned to support a wider\n  variety of response parts, particularly when streaming.\n\n  ### Streaming Responses\n\n  When streaming text via the `LanguageModel.streamText` method, you will now\n  receive a stream of content parts instead of a stream of responses, which should\n  make it much simpler to filter down the stream to the parts you are interested in.\n\n  In addition, additional content parts will be present in the stream to allow you to track,\n  for example, when a text content part starts / ends.\n\n  ### Tool Calls / Tool Call Results\n\n  The decoded parts of a `Response` (as returned by the methods of `LanguageModel`)\n  are now fully type-safe on tool calls / tool call results. Filtering the content parts of a\n  response to tool calls will narrow the type of the tool call `params` based on the tool\n  `name`. Similarly, filtering the response to tool call results will narrow the type of the\n  tool call `result` based on the tool `name`.\n\n  ```ts\n  import { LanguageModel, Tool, Toolkit } from \"@effect/ai\"\n  import { Effect, Schema } from \"effect\"\n\n  const DadJokeTool = Tool.make(\"DadJokeTool\", {\n    parameters: { topic: Schema.String },\n    success: Schema.Struct({ joke: Schema.String })\n  })\n\n  const FooTool = Tool.make(\"FooTool\", {\n    parameters: { foo: Schema.Number },\n    success: Schema.Struct({ bar: Schema.Boolean })\n  })\n\n  const MyToolkit = Toolkit.make(DadJokeTool, FooTool)\n\n  const program = Effect.gen(function* () {\n    const response = yield* LanguageModel.generateText({\n      prompt: \"Tell me a dad joke\",\n      toolkit: MyToolkit\n    })\n\n    for (const toolCall of response.toolCalls) {\n      if (toolCall.name === \"DadJokeTool\") {\n        //         ^? \"DadJokeTool\" | \"FooTool\"\n        toolCall.params\n        //       ^? { readonly topic: string }\n      }\n    }\n\n    for (const toolResult of response.toolResults) {\n      if (toolResult.name === \"DadJokeTool\") {\n        //           ^? \"DadJokeTool\" | \"FooTool\"\n        toolResult.result\n        //         ^? { readonly joke: string }\n      }\n    }\n  })\n  ```\n\n  ### Provider Metadata\n\n  As with provider-specific options, provider-specific metadata is now returned as\n  part of the response from the large language model provider.\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n  import { Effect } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const program = Effect.gen(function* () {\n    const response = yield* LanguageModel.generateText({\n      prompt: \"What is the meaning of life?\"\n    })\n\n    for (const part of response.content) {\n      // When metadata **is not** defined for a content part, accessing the\n      // provider's key on the part's metadata will return an untyped record\n      if (part.type === \"text\") {\n        const metadata = part.metadata.anthropic\n        //    ^? { readonly [x: string]: unknown } | undefined\n      }\n      // When metadata **is** defined for a content part, accessing the\n      // provider's key on the part's metadata will return typed metadata\n      if (part.type === \"reasoning\") {\n        const metadata = part.metadata.anthropic\n        //    ^? AnthropicReasoningInfo | undefined\n      }\n    }\n  }).pipe(Effect.provide(Claude))\n  ```\n\n  ## Tool Calls\n\n  The `Tool` module has been enhanced to support provider-defined tools (e.g.\n  web search, computer use, etc.). Large language model providers which support\n  calling their own tools now have a separate module present in their provider\n  integration packages which contain definitions for their tools.\n\n  These provider-defined tools can be included alongside user-defined tools in\n  existing `Toolkit`s. Provider-defined tools that require a user-space handler\n  will be raise a type error in the associated `Toolkit` layer if no such handler\n  is defined.\n\n  ```ts\n  import { LanguageModel, Tool, Toolkit } from \"@effect/ai\"\n  import { AnthropicTool } from \"@effect/ai-anthropic\"\n  import { Schema } from \"effect\"\n\n  const DadJokeTool = Tool.make(\"DadJokeTool\", {\n    parameters: { topic: Schema.String },\n    success: Schema.Struct({ joke: Schema.String })\n  })\n\n  const MyToolkit = Toolkit.make(\n    DadJokeTool,\n    AnthropicTool.WebSearch_20250305({ max_uses: 1 })\n  )\n\n  const program = LanguageModel.generateText({\n    prompt: \"Search the web for a dad joke\",\n    toolkit: MyToolkit\n  })\n  ```\n\n  ## AiError\n\n  The `AiError` type has been refactored into a union of different error types\n  which can be raised by the Effect AI SDK. The goal of defining separate error\n  types is to allow providing the end-user with more granular information about\n  the error that occurred.\n\n  For now, the following errors have been defined. More error types may be added\n  over time based upon necessity / use case.\n\n  ```ts\n  type AiError =\n    | HttpRequestError,\n    | HttpResponseError,\n    | MalformedInput,\n    | MalformedOutput,\n    | UnknownError\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`42b914a`](https://github.com/Effect-TS/effect/commit/42b914a0e8750350ce17d434afaec7d655ddf4b7)]:\n  - @effect/ai@0.27.0\n\n## 0.5.0\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/ai@0.26.0\n  - @effect/experimental@0.54.6\n\n## 0.4.0\n\n### Patch Changes\n\n- Updated dependencies [[`5a0f4f1`](https://github.com/Effect-TS/effect/commit/5a0f4f176687a39d9fa46bb894bb7ac3175b0e87)]:\n  - effect@3.17.1\n  - @effect/ai@0.25.0\n  - @effect/experimental@0.54.0\n\n## 0.3.0\n\n### Patch Changes\n\n- Updated dependencies [[`7813640`](https://github.com/Effect-TS/effect/commit/7813640279d9e3a3e7fc0a29bfb5c6d5fb3c270f)]:\n  - @effect/platform@0.90.0\n  - @effect/ai@0.24.0\n  - @effect/experimental@0.54.0\n\n## 0.2.0\n\n### Patch Changes\n\n- Updated dependencies [[`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9), [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104), [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63), [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c), [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989), [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636), [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2), [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d)]:\n  - effect@3.17.0\n  - @effect/ai@0.23.0\n  - @effect/experimental@0.53.0\n  - @effect/platform@0.89.0\n\n## 0.1.2\n\n### Patch Changes\n\n- Updated dependencies [[`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec), [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38), [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48)]:\n  - effect@3.16.14\n  - @effect/platform@0.88.1\n  - @effect/experimental@0.52.1\n  - @effect/ai@0.22.1\n\n## 0.1.1\n\n### Patch Changes\n\n- [#5209](https://github.com/Effect-TS/effect/pull/5209) [`3deaa66`](https://github.com/Effect-TS/effect/commit/3deaa66e022e361a2036ce6bfc9d76f77d9cc948) Thanks @tim-smart! - fix ai layerConfig regression, to allow for conditional Config variables\n\n## 0.1.0\n\n### Patch Changes\n\n- Updated dependencies [[`27206d7`](https://github.com/Effect-TS/effect/commit/27206d7f0558d7fe28de57bf54f1d0cc83acc92e), [`dbabf5e`](https://github.com/Effect-TS/effect/commit/dbabf5e76fa63b050d2b6c466713c7dc59f07d3c)]:\n  - @effect/platform@0.88.0\n  - @effect/ai@0.22.0\n  - @effect/experimental@0.52.0\n\n## 0.0.7\n\n### Patch Changes\n\n- Updated dependencies [[`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7), [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db)]:\n  - effect@3.16.13\n  - @effect/ai@0.21.17\n  - @effect/experimental@0.51.14\n  - @effect/platform@0.87.13\n\n## 0.0.6\n\n### Patch Changes\n\n- [#5186](https://github.com/Effect-TS/effect/pull/5186) [`e5692ab`](https://github.com/Effect-TS/effect/commit/e5692ab2be157b885f449ffb5c5f022eca04a59e) Thanks @IMax153! - Do not use `Config.Wrap` for AI provider `layerConfig`\n\n- Updated dependencies [[`32ba77a`](https://github.com/Effect-TS/effect/commit/32ba77ae304d2161362a73e8b61965332626cf2d), [`d5e25b2`](https://github.com/Effect-TS/effect/commit/d5e25b237f05670ee42b386cb40b2cb448fc11d7)]:\n  - @effect/platform@0.87.12\n  - @effect/ai@0.21.16\n  - @effect/experimental@0.51.13\n\n## 0.0.5\n\n### Patch Changes\n\n- Updated dependencies [[`001392b`](https://github.com/Effect-TS/effect/commit/001392ba8bfcad101bb034348a7415012fb12f72), [`7bfb099`](https://github.com/Effect-TS/effect/commit/7bfb099cb5528511b8d63045c4fbb4dc9cb18528)]:\n  - @effect/platform@0.87.11\n  - @effect/ai@0.21.15\n  - @effect/experimental@0.51.12\n\n## 0.0.4\n\n### Patch Changes\n\n- Updated dependencies [[`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0), [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0)]:\n  - @effect/platform@0.87.10\n  - @effect/ai@0.21.14\n  - @effect/experimental@0.51.11\n\n## 0.0.3\n\n### Patch Changes\n\n- Updated dependencies [[`54514a2`](https://github.com/Effect-TS/effect/commit/54514a2f53166de27ad7e756dbf12194691fd4af)]:\n  - @effect/platform@0.87.9\n  - @effect/ai@0.21.13\n  - @effect/experimental@0.51.10\n\n## 0.0.2\n\n### Patch Changes\n\n- Updated dependencies [[`4ce4f82`](https://github.com/Effect-TS/effect/commit/4ce4f824f6fdef492be1d35c05a490ffce518c89)]:\n  - @effect/platform@0.87.8\n  - @effect/experimental@0.51.9\n  - @effect/ai@0.21.12\n\n## 0.0.1\n\n### Patch Changes\n\n- [#5029](https://github.com/Effect-TS/effect/pull/5029) [`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778) Thanks @IMax153! - Cleanup AiLanguageModel construction and finish basic support for gemini\n\n- Updated dependencies [[`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778), [`25ca0cf`](https://github.com/Effect-TS/effect/commit/25ca0cf141139cd44ff53081b1c877f8f3ab5e41), [`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778)]:\n  - @effect/ai@0.21.11\n"
  },
  {
    "path": "packages/ai/google/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Effectful Technologies Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/ai/google/README.md",
    "content": "# `@effect/ai-google`\n\n## Documentation\n\n- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/ai/google).\n"
  },
  {
    "path": "packages/ai/google/docgen.json",
    "content": "{\n  \"$schema\": \"../../../node_modules/@effect/docgen/schema.json\",\n  \"exclude\": [\"src/Generated.ts\", \"src/internal/**/*.ts\"],\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/ai/google/src/\",\n  \"examplesCompilerOptions\": {\n    \"noEmit\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"module\": \"ES2022\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n    \"paths\": {\n      \"effect\": [\"../../../../effect/src/index.js\"],\n      \"effect/*\": [\"../../../../effect/src/*.js\"],\n      \"@effect/experimental\": [\"../../../../experimental/src/index.js\"],\n      \"@effect/experimental/*\": [\"../../../../experimental/src/*.js\"],\n      \"@effect/platform\": [\"../../../../platform/src/index.js\"],\n      \"@effect/platform/*\": [\"../../../../platform/src/*.js\"],\n      \"@effect/ai\": [\"../../../ai/src/index.js\"],\n      \"@effect/ai/*\": [\"../../../ai/src/*.js\"],\n      \"@effect/ai-google\": [\"../../../ai-google/src/index.js\"],\n      \"@effect/ai-google/*\": [\"../../../ai-google/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/ai/google/package.json",
    "content": "{\n  \"name\": \"@effect/ai-google\",\n  \"type\": \"module\",\n  \"version\": \"0.14.0\",\n  \"license\": \"MIT\",\n  \"description\": \"Effect modules for working with AI apis\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/ai/google\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"keywords\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"peerDependencies\": {\n    \"@effect/ai\": \"workspace:^\",\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"effect\": \"workspace:^\"\n  },\n  \"devDependencies\": {\n    \"@effect/ai\": \"workspace:^\",\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/platform-node\": \"workspace:^\",\n    \"@tim-smart/openapi-gen\": \"^0.4.10\",\n    \"effect\": \"workspace:^\"\n  }\n}\n"
  },
  {
    "path": "packages/ai/google/scripts/generate.sh",
    "content": "#!/usr/bin/env bash\n\nset -euo pipefail\n\nSCRIPT_DIR=$(cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd)\n\nif [[ -z \"${GOOGLE_API_KEY:-}\" ]]; then\n  echo \"Error: GOOGLE_API_KEY environment variable is not set.\"\n  exit 1\nfi\n\nbase_url=\"https://generativelanguage.googleapis.com/\"\ntemp_dir=$(mktemp -d)\n\ncleanup() {\n  rm -rf \"${temp_dir}\"\n}\n\ntrap cleanup EXIT\n\ncurl \"${base_url}\\$discovery/OPENAPI3_0?version=v1beta&key=${GOOGLE_API_KEY}\" > \"${temp_dir}/openapi.json\"\n\necho \"/**\n * @since 1.0.0\n */\" > src/Generated.ts\n\npnpm openapi-gen -s \"${temp_dir}/openapi.json\" >> src/Generated.ts\n\ngit apply --reject --whitespace=fix \"${SCRIPT_DIR}/generated.patch\"\n\npnpm eslint --fix src/Generated.ts\n"
  },
  {
    "path": "packages/ai/google/scripts/generated.patch",
    "content": "diff --git a/packages/ai/google/src/Generated.ts b/packages/ai/google/src/Generated.ts\nindex 52b1a4a9e..47b58417a 100644\n--- a/packages/ai/google/src/Generated.ts\n+++ b/packages/ai/google/src/Generated.ts\n@@ -383,102 +383,123 @@ export class Content extends S.Class<Content>(\"Content\")({\n \n export class Type extends S.Literal(\"TYPE_UNSPECIFIED\", \"STRING\", \"NUMBER\", \"INTEGER\", \"BOOLEAN\", \"ARRAY\", \"OBJECT\", \"NULL\") {}\n \n+const schemaFields = {\n+  /**\n+   * Optional. Maximum value of the Type.INTEGER and Type.NUMBER\n+   */\n+  \"maximum\": S.optionalWith(S.Number, { nullable: true }),\n+  /**\n+   * Optional. Minimum number of the properties for Type.OBJECT.\n+   */\n+  \"minProperties\": S.optionalWith(S.String, { nullable: true }),\n+  /**\n+   * Required. Data type.\n+   */\n+  \"type\": Type,\n+  /**\n+   * Optional. A brief description of the parameter. This could contain examples of use.\n+   * Parameter description may be formatted as Markdown.\n+   */\n+  \"description\": S.optionalWith(S.String, { nullable: true }),\n+  /**\n+   * Optional. Maximum number of the elements for Type.ARRAY.\n+   */\n+  \"maxItems\": S.optionalWith(S.String, { nullable: true }),\n+  /**\n+   * Optional. The order of the properties.\n+   * Not a standard field in open api spec. Used to determine the order of the\n+   * properties in the response.\n+   */\n+  \"propertyOrdering\": S.optionalWith(S.Array(S.String), { nullable: true }),\n+  /**\n+   * Optional. The format of the data. This is used only for primitive datatypes.\n+   * Supported formats:\n+   *  for NUMBER type: float, double\n+   *  for INTEGER type: int32, int64\n+   *  for STRING type: enum, date-time\n+   */\n+  \"format\": S.optionalWith(S.String, { nullable: true }),\n+  /**\n+   * Optional. Maximum length of the Type.STRING\n+   */\n+  \"maxLength\": S.optionalWith(S.String, { nullable: true }),\n+  /**\n+   * Optional. The title of the schema.\n+   */\n+  \"title\": S.optionalWith(S.String, { nullable: true }),\n+  /**\n+   * Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER\n+   * Minimum value of the Type.INTEGER and Type.NUMBER\n+   */\n+  \"minimum\": S.optionalWith(S.Number, { nullable: true }),\n+  /**\n+   * Optional. Maximum number of the properties for Type.OBJECT.\n+   */\n+  \"maxProperties\": S.optionalWith(S.String, { nullable: true }),\n+  /**\n+   * Optional. Possible values of the element of Type.STRING with enum format.\n+   * For example we can define an Enum Direction as :\n+   * {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]}\n+   */\n+  \"enum\": S.optionalWith(S.Array(S.String), { nullable: true }),\n+  /**\n+   * Optional. Required properties of Type.OBJECT.\n+   */\n+  \"required\": S.optionalWith(S.Array(S.String), { nullable: true }),\n+  /**\n+   * Optional. Indicates if the value may be null.\n+   */\n+  \"nullable\": S.optionalWith(S.Boolean, { nullable: true }),\n+  /**\n+   * Optional. Properties of Type.OBJECT.\n+   */\n+  \"properties\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n+  /**\n+   * Optional. Minimum number of the elements for Type.ARRAY.\n+   */\n+  \"minItems\": S.optionalWith(S.String, { nullable: true }),\n+  /**\n+   * Optional. SCHEMA FIELDS FOR TYPE STRING\n+   * Minimum length of the Type.STRING\n+   */\n+  \"minLength\": S.optionalWith(S.String, { nullable: true }),\n+  /**\n+   * Optional. Pattern of the Type.STRING to restrict a string to a regular expression.\n+   */\n+  \"pattern\": S.optionalWith(S.String, { nullable: true })\n+}\n+\n /**\n-* The `Schema` object allows the definition of input and output data types.\n-* These types can be objects, but also primitives and arrays.\n-* Represents a select subset of an [OpenAPI 3.0 schema\n-* object](https://spec.openapis.org/oas/v3.0.3#schema).\n-*/\n-export class Schema extends S.Class<Schema>(\"Schema\")({\n-  /**\n-* Required. Data type.\n-*/\n-\"type\": Type,\n-  /**\n-* Optional. The format of the data. Any value is allowed, but most do not trigger any\n-* special functionality.\n-*/\n-\"format\": S.optionalWith(S.String, { nullable: true }),\n-  /**\n-* Optional. The title of the schema.\n-*/\n-\"title\": S.optionalWith(S.String, { nullable: true }),\n-  /**\n-* Optional. A brief description of the parameter. This could contain examples of use.\n-* Parameter description may be formatted as Markdown.\n-*/\n-\"description\": S.optionalWith(S.String, { nullable: true }),\n-  /**\n-* Optional. Indicates if the value may be null.\n-*/\n-\"nullable\": S.optionalWith(S.Boolean, { nullable: true }),\n-  /**\n-* Optional. Possible values of the element of Type.STRING with enum format.\n-* For example we can define an Enum Direction as :\n-* {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]}\n-*/\n-\"enum\": S.optionalWith(S.Array(S.String), { nullable: true }),\n-  /**\n-* Optional. Schema of the elements of Type.ARRAY.\n-*/\n-\"items\": S.optionalWith(Schema, { nullable: true }),\n-  /**\n-* Optional. Maximum number of the elements for Type.ARRAY.\n-*/\n-\"maxItems\": S.optionalWith(S.String, { nullable: true }),\n-  /**\n-* Optional. Minimum number of the elements for Type.ARRAY.\n-*/\n-\"minItems\": S.optionalWith(S.String, { nullable: true }),\n-  /**\n-* Optional. Properties of Type.OBJECT.\n-*/\n-\"properties\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n-  /**\n-* Optional. Required properties of Type.OBJECT.\n-*/\n-\"required\": S.optionalWith(S.Array(S.String), { nullable: true }),\n-  /**\n-* Optional. Minimum number of the properties for Type.OBJECT.\n-*/\n-\"minProperties\": S.optionalWith(S.String, { nullable: true }),\n-  /**\n-* Optional. Maximum number of the properties for Type.OBJECT.\n-*/\n-\"maxProperties\": S.optionalWith(S.String, { nullable: true }),\n-  /**\n-* Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER\n-* Minimum value of the Type.INTEGER and Type.NUMBER\n-*/\n-\"minimum\": S.optionalWith(S.Number, { nullable: true }),\n-  /**\n-* Optional. Maximum value of the Type.INTEGER and Type.NUMBER\n-*/\n-\"maximum\": S.optionalWith(S.Number, { nullable: true }),\n-  /**\n-* Optional. SCHEMA FIELDS FOR TYPE STRING\n-* Minimum length of the Type.STRING\n-*/\n-\"minLength\": S.optionalWith(S.String, { nullable: true }),\n-  /**\n-* Optional. Maximum length of the Type.STRING\n-*/\n-\"maxLength\": S.optionalWith(S.String, { nullable: true }),\n+ * The \\`Schema\\` object allows the definition of input and output data types.\n+ * These types can be objects, but also primitives and arrays.\n+ * Represents a select subset of an [OpenAPI 3.0 schema\n+ * object](https://spec.openapis.org/oas/v3.0.3#schema).\n+ */\n+export interface SchemaEncoded extends S.Struct.Encoded<typeof schemaFields> {\n   /**\n-* Optional. Pattern of the Type.STRING to restrict a string to a regular expression.\n-*/\n-\"pattern\": S.optionalWith(S.String, { nullable: true }),\n+   * Optional. The value should be validated against any (one or more) of the subschemas\n+   * in the list.\n+   */\n+  readonly \"anyOf\"?: ReadonlyArray<SchemaEncoded> | undefined | null\n   /**\n-* Optional. The value should be validated against any (one or more) of the subschemas\n-* in the list.\n-*/\n-\"anyOf\": S.optionalWith(S.Array(Schema), { nullable: true }),\n+   * Optional. Schema of the elements of Type.ARRAY.\n+   */\n+  readonly \"items\"?: SchemaEncoded | undefined | null\n+}\n+\n+/**\n+ * The \\`Schema\\` object allows the definition of input and output data types.\n+ * These types can be objects, but also primitives and arrays.\n+ * Represents a select subset of an [OpenAPI 3.0 schema\n+ * object](https://spec.openapis.org/oas/v3.0.3#schema).\n+ */\n+export class Schema extends S.Class<Schema>(\"Schema\")({\n+  ...schemaFields,\n+  \"anyOf\": S.optionalWith(S.Array(S.suspend((): S.Schema<Schema, SchemaEncoded> => Schema)), { nullable: true }),\n   /**\n-* Optional. The order of the properties.\n-* Not a standard field in open api spec. Used to determine the order of the\n-* properties in the response.\n-*/\n-\"propertyOrdering\": S.optionalWith(S.Array(S.String), { nullable: true })\n+   * Optional. Schema of the elements of Type.ARRAY.\n+   */\n+  \"items\": S.optionalWith(S.suspend((): S.Schema<Schema, SchemaEncoded> => Schema), { nullable: true })\n }) {}\n \n /**\n@@ -4237,6 +4258,8 @@ export const make = (\n     <A, I, R>(schema: S.Schema<A, I, R>) =>\n     (response: HttpClientResponse.HttpClientResponse) =>\n       HttpClientResponse.schemaBodyJson(schema)(response)\n+  // @ts-expect-error\n+  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n   const decodeError =\n     <const Tag extends string, A, I, R>(tag: Tag, schema: S.Schema<A, I, R>) =>\n     (response: HttpClientResponse.HttpClientResponse) =>\n"
  },
  {
    "path": "packages/ai/google/src/Generated.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientError from \"@effect/platform/HttpClientError\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as HttpClientResponse from \"@effect/platform/HttpClientResponse\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\n\nexport class ListOperationsParams extends S.Struct({\n  \"filter\": S.optionalWith(S.String, { nullable: true }),\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true }),\n  \"returnPartialSuccess\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * The `Status` type defines a logical error model that is suitable for\n * different programming environments, including REST APIs and RPC APIs. It is\n * used by [gRPC](https://github.com/grpc). Each `Status` message contains\n * three pieces of data: error code, error message, and error details.\n *\n * You can find out more about this error model and how to work with it in the\n * [API Design Guide](https://cloud.google.com/apis/design/errors).\n */\nexport class Status extends S.Class<Status>(\"Status\")({\n  /**\n   * The status code, which should be an enum value of google.rpc.Code.\n   */\n  \"code\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * A developer-facing error message, which should be in English. Any\n   * user-facing error message should be localized and sent in the\n   * google.rpc.Status.details field, or localized by the client.\n   */\n  \"message\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * A list of messages that carry the error details.  There is a common set of\n   * message types for APIs to use.\n   */\n  \"details\": S.optionalWith(S.Array(S.Record({ key: S.String, value: S.Unknown })), { nullable: true })\n}) {}\n\n/**\n * This resource represents a long-running operation that is the result of a\n * network API call.\n */\nexport class Operation extends S.Class<Operation>(\"Operation\")({\n  /**\n   * Service-specific metadata associated with the operation.  It typically\n   * contains progress information and common metadata such as create time.\n   * Some services might not provide such metadata.  Any method that returns a\n   * long-running operation should document the metadata type, if any.\n   */\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * The normal, successful response of the operation.  If the original\n   * method returns no data on success, such as `Delete`, the response is\n   * `google.protobuf.Empty`.  If the original method is standard\n   * `Get`/`Create`/`Update`, the response should be the resource.  For other\n   * methods, the response should have the type `XxxResponse`, where `Xxx`\n   * is the original method name.  For example, if the original method name\n   * is `TakeSnapshot()`, the inferred response type is\n   * `TakeSnapshotResponse`.\n   */\n  \"response\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * The server-assigned name, which is only unique within the same service that\n   * originally returns it. If you use the default HTTP mapping, the\n   * `name` should be a resource name ending with `operations/{unique_id}`.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * If the value is `false`, it means the operation is still in progress.\n   * If `true`, the operation is completed, and either `error` or `response` is\n   * available.\n   */\n  \"done\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * The error result of the operation in case of failure or cancellation.\n   */\n  \"error\": S.optionalWith(Status, { nullable: true })\n}) {}\n\n/**\n * The response message for Operations.ListOperations.\n */\nexport class ListOperationsResponse extends S.Class<ListOperationsResponse>(\"ListOperationsResponse\")({\n  /**\n   * A list of operations that matches the specified filter in the request.\n   */\n  \"operations\": S.optionalWith(S.Array(Operation), { nullable: true }),\n  /**\n   * The standard List next-page token.\n   */\n  \"nextPageToken\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Unordered list. Unreachable resources. Populated when the request sets\n   * `ListOperationsRequest.return_partial_success` and reads across\n   * collections. For example, when attempting to list all resources across all\n   * supported locations.\n   */\n  \"unreachable\": S.optionalWith(S.Array(S.String), { nullable: true })\n}) {}\n\nexport class ListOperationsByParams extends S.Struct({\n  \"filter\": S.optionalWith(S.String, { nullable: true }),\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true }),\n  \"returnPartialSuccess\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class ListOperationsByModelParams extends S.Struct({\n  \"filter\": S.optionalWith(S.String, { nullable: true }),\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true }),\n  \"returnPartialSuccess\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * A generic empty message that you can re-use to avoid defining duplicated\n * empty messages in your APIs. A typical example is to use it as the request\n * or the response type of an API method. For instance:\n *\n *     service Foo {\n *       rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);\n *     }\n */\nexport class Empty extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * Raw media bytes.\n *\n * Text should not be sent as raw bytes, use the 'text' field.\n */\nexport class Blob extends S.Class<Blob>(\"Blob\")({\n  /**\n   * The IANA standard MIME type of the source data.\n   * Examples:\n   *   - image/png\n   *   - image/jpeg\n   * If an unsupported MIME type is provided, an error will be returned. For a\n   * complete list of supported types, see [Supported file\n   * formats](https://ai.google.dev/gemini-api/docs/prompting_with_media#supported_file_formats).\n   */\n  \"mimeType\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Raw bytes for media formats.\n   */\n  \"data\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A predicted `FunctionCall` returned from the model that contains\n * a string representing the `FunctionDeclaration.name` with the\n * arguments and their values.\n */\nexport class FunctionCall extends S.Class<FunctionCall>(\"FunctionCall\")({\n  /**\n   * Optional. The unique id of the function call. If populated, the client to execute the\n   * `function_call` and return the response with the matching `id`.\n   */\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. The name of the function to call.\n   * Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum\n   * length of 64.\n   */\n  \"name\": S.String,\n  /**\n   * Optional. The function parameters and values in JSON object format.\n   */\n  \"args\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * Raw media bytes for function response.\n *\n * Text should not be sent as raw bytes, use the 'FunctionResponse.response'\n * field.\n */\nexport class FunctionResponseBlob extends S.Class<FunctionResponseBlob>(\"FunctionResponseBlob\")({\n  /**\n   * The IANA standard MIME type of the source data.\n   * Examples:\n   *   - image/png\n   *   - image/jpeg\n   * If an unsupported MIME type is provided, an error will be returned. For a\n   * complete list of supported types, see [Supported file\n   * formats](https://ai.google.dev/gemini-api/docs/prompting_with_media#supported_file_formats).\n   */\n  \"mimeType\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Raw bytes for media formats.\n   */\n  \"data\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A datatype containing media that is part of a `FunctionResponse` message.\n *\n * A `FunctionResponsePart` consists of data which has an associated datatype. A\n * `FunctionResponsePart` can only contain one of the accepted types in\n * `FunctionResponsePart.data`.\n *\n * A `FunctionResponsePart` must have a fixed IANA MIME type identifying the\n * type and subtype of the media if the `inline_data` field is filled with raw\n * bytes.\n */\nexport class FunctionResponsePart extends S.Class<FunctionResponsePart>(\"FunctionResponsePart\")({\n  /**\n   * Inline media bytes.\n   */\n  \"inlineData\": S.optionalWith(FunctionResponseBlob, { nullable: true })\n}) {}\n\n/**\n * Optional. Specifies how the response should be scheduled in the conversation.\n * Only applicable to NON_BLOCKING function calls, is ignored otherwise.\n * Defaults to WHEN_IDLE.\n */\nexport class FunctionResponseScheduling\n  extends S.Literal(\"SCHEDULING_UNSPECIFIED\", \"SILENT\", \"WHEN_IDLE\", \"INTERRUPT\")\n{}\n\n/**\n * The result output from a `FunctionCall` that contains a string\n * representing the `FunctionDeclaration.name` and a structured JSON\n * object containing any output from the function is used as context to\n * the model. This should contain the result of a`FunctionCall` made\n * based on model prediction.\n */\nexport class FunctionResponse extends S.Class<FunctionResponse>(\"FunctionResponse\")({\n  /**\n   * Optional. The id of the function call this response is for. Populated by the client\n   * to match the corresponding function call `id`.\n   */\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. The name of the function to call.\n   * Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum\n   * length of 64.\n   */\n  \"name\": S.String,\n  /**\n   * Required. The function response in JSON object format.\n   * Callers can use any keys of their choice that fit the function's syntax\n   * to return the function output, e.g. \"output\", \"result\", etc.\n   * In particular, if the function call failed to execute, the response can\n   * have an \"error\" key to return error details to the model.\n   */\n  \"response\": S.Record({ key: S.String, value: S.Unknown }),\n  /**\n   * Optional. Ordered `Parts` that constitute a function response. Parts may have\n   * different IANA MIME types.\n   */\n  \"parts\": S.optionalWith(S.Array(FunctionResponsePart), { nullable: true }),\n  /**\n   * Optional. Signals that function call continues, and more responses will be\n   * returned, turning the function call into a generator.\n   * Is only applicable to NON_BLOCKING function calls, is ignored otherwise.\n   * If set to false, future responses will not be considered.\n   * It is allowed to return empty `response` with `will_continue=False` to\n   * signal that the function call is finished. This may still trigger the model\n   * generation. To avoid triggering the generation and finish the function\n   * call, additionally set `scheduling` to `SILENT`.\n   */\n  \"willContinue\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * Optional. Specifies how the response should be scheduled in the conversation.\n   * Only applicable to NON_BLOCKING function calls, is ignored otherwise.\n   * Defaults to WHEN_IDLE.\n   */\n  \"scheduling\": S.optionalWith(FunctionResponseScheduling, { nullable: true })\n}) {}\n\n/**\n * URI based data.\n */\nexport class FileData extends S.Class<FileData>(\"FileData\")({\n  /**\n   * Optional. The IANA standard MIME type of the source data.\n   */\n  \"mimeType\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. URI.\n   */\n  \"fileUri\": S.String\n}) {}\n\n/**\n * Required. Programming language of the `code`.\n */\nexport class ExecutableCodeLanguage extends S.Literal(\"LANGUAGE_UNSPECIFIED\", \"PYTHON\") {}\n\n/**\n * Code generated by the model that is meant to be executed, and the result\n * returned to the model.\n *\n * Only generated when using the `CodeExecution` tool, in which the code will\n * be automatically executed, and a corresponding `CodeExecutionResult` will\n * also be generated.\n */\nexport class ExecutableCode extends S.Class<ExecutableCode>(\"ExecutableCode\")({\n  /**\n   * Required. Programming language of the `code`.\n   */\n  \"language\": ExecutableCodeLanguage,\n  /**\n   * Required. The code to be executed.\n   */\n  \"code\": S.String\n}) {}\n\n/**\n * Required. Outcome of the code execution.\n */\nexport class CodeExecutionResultOutcome\n  extends S.Literal(\"OUTCOME_UNSPECIFIED\", \"OUTCOME_OK\", \"OUTCOME_FAILED\", \"OUTCOME_DEADLINE_EXCEEDED\")\n{}\n\n/**\n * Result of executing the `ExecutableCode`.\n *\n * Only generated when using the `CodeExecution`, and always follows a `part`\n * containing the `ExecutableCode`.\n */\nexport class CodeExecutionResult extends S.Class<CodeExecutionResult>(\"CodeExecutionResult\")({\n  /**\n   * Required. Outcome of the code execution.\n   */\n  \"outcome\": CodeExecutionResultOutcome,\n  /**\n   * Optional. Contains stdout when code execution is successful, stderr or other\n   * description otherwise.\n   */\n  \"output\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Metadata describes the input video content.\n */\nexport class VideoMetadata extends S.Class<VideoMetadata>(\"VideoMetadata\")({\n  /**\n   * Optional. The start offset of the video.\n   */\n  \"startOffset\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. The end offset of the video.\n   */\n  \"endOffset\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. The frame rate of the video sent to the model. If not specified, the\n   * default value will be 1.0.\n   * The fps range is (0.0, 24.0].\n   */\n  \"fps\": S.optionalWith(S.Number, { nullable: true })\n}) {}\n\nexport class MediaResolutionLevel extends S.Literal(\n  \"MEDIA_RESOLUTION_UNSPECIFIED\",\n  \"MEDIA_RESOLUTION_LOW\",\n  \"MEDIA_RESOLUTION_MEDIUM\",\n  \"MEDIA_RESOLUTION_HIGH\",\n  \"MEDIA_RESOLUTION_ULTRA_HIGH\"\n) {}\n\n/**\n * Media resolution for the input media.\n */\nexport class MediaResolution extends S.Class<MediaResolution>(\"MediaResolution\")({\n  \"level\": S.optionalWith(MediaResolutionLevel, { nullable: true })\n}) {}\n\n/**\n * A datatype containing media that is part of a multi-part `Content` message.\n *\n * A `Part` consists of data which has an associated datatype. A `Part` can only\n * contain one of the accepted types in `Part.data`.\n *\n * A `Part` must have a fixed IANA MIME type identifying the type and subtype\n * of the media if the `inline_data` field is filled with raw bytes.\n */\nexport class Part extends S.Class<Part>(\"Part\")({\n  /**\n   * Inline text.\n   */\n  \"text\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Inline media bytes.\n   */\n  \"inlineData\": S.optionalWith(Blob, { nullable: true }),\n  /**\n   * A predicted `FunctionCall` returned from the model that contains\n   * a string representing the `FunctionDeclaration.name` with the\n   * arguments and their values.\n   */\n  \"functionCall\": S.optionalWith(FunctionCall, { nullable: true }),\n  /**\n   * The result output of a `FunctionCall` that contains a string\n   * representing the `FunctionDeclaration.name` and a structured JSON\n   * object containing any output from the function is used as context to\n   * the model.\n   */\n  \"functionResponse\": S.optionalWith(FunctionResponse, { nullable: true }),\n  /**\n   * URI based data.\n   */\n  \"fileData\": S.optionalWith(FileData, { nullable: true }),\n  /**\n   * Code generated by the model that is meant to be executed.\n   */\n  \"executableCode\": S.optionalWith(ExecutableCode, { nullable: true }),\n  /**\n   * Result of executing the `ExecutableCode`.\n   */\n  \"codeExecutionResult\": S.optionalWith(CodeExecutionResult, { nullable: true }),\n  /**\n   * Optional. Video metadata. The metadata should only be specified while the video\n   * data is presented in inline_data or file_data.\n   */\n  \"videoMetadata\": S.optionalWith(VideoMetadata, { nullable: true }),\n  /**\n   * Optional. Indicates if the part is thought from the model.\n   */\n  \"thought\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * Optional. An opaque signature for the thought so it can be reused in subsequent\n   * requests.\n   */\n  \"thoughtSignature\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Custom metadata associated with the Part.\n   * Agents using genai.Part as content representation may need to keep track\n   * of the additional information. For example it can be name of a file/source\n   * from which the Part originates or a way to multiplex multiple Part streams.\n   */\n  \"partMetadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * Optional. Media resolution for the input media.\n   */\n  \"mediaResolution\": S.optionalWith(MediaResolution, { nullable: true })\n}) {}\n\n/**\n * The base structured datatype containing multi-part content of a message.\n *\n * A `Content` includes a `role` field designating the producer of the `Content`\n * and a `parts` field containing multi-part data that contains the content of\n * the message turn.\n */\nexport class Content extends S.Class<Content>(\"Content\")({\n  /**\n   * Ordered `Parts` that constitute a single message. Parts may have different\n   * MIME types.\n   */\n  \"parts\": S.optionalWith(S.Array(Part), { nullable: true }),\n  /**\n   * Optional. The producer of the content. Must be either 'user' or 'model'.\n   *\n   * Useful to set for multi-turn conversations, otherwise can be left blank\n   * or unset.\n   */\n  \"role\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class Type\n  extends S.Literal(\"TYPE_UNSPECIFIED\", \"STRING\", \"NUMBER\", \"INTEGER\", \"BOOLEAN\", \"ARRAY\", \"OBJECT\", \"NULL\")\n{}\n\nconst schemaFields = {\n  /**\n   * Optional. Maximum value of the Type.INTEGER and Type.NUMBER\n   */\n  \"maximum\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. Minimum number of the properties for Type.OBJECT.\n   */\n  \"minProperties\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. Data type.\n   */\n  \"type\": Type,\n  /**\n   * Optional. A brief description of the parameter. This could contain examples of use.\n   * Parameter description may be formatted as Markdown.\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Maximum number of the elements for Type.ARRAY.\n   */\n  \"maxItems\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. The order of the properties.\n   * Not a standard field in open api spec. Used to determine the order of the\n   * properties in the response.\n   */\n  \"propertyOrdering\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Optional. The format of the data. This is used only for primitive datatypes.\n   * Supported formats:\n   *  for NUMBER type: float, double\n   *  for INTEGER type: int32, int64\n   *  for STRING type: enum, date-time\n   */\n  \"format\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Maximum length of the Type.STRING\n   */\n  \"maxLength\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. The title of the schema.\n   */\n  \"title\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER\n   * Minimum value of the Type.INTEGER and Type.NUMBER\n   */\n  \"minimum\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. Maximum number of the properties for Type.OBJECT.\n   */\n  \"maxProperties\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Possible values of the element of Type.STRING with enum format.\n   * For example we can define an Enum Direction as :\n   * {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]}\n   */\n  \"enum\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Optional. Required properties of Type.OBJECT.\n   */\n  \"required\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Optional. Indicates if the value may be null.\n   */\n  \"nullable\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * Optional. Properties of Type.OBJECT.\n   */\n  \"properties\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * Optional. Minimum number of the elements for Type.ARRAY.\n   */\n  \"minItems\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. SCHEMA FIELDS FOR TYPE STRING\n   * Minimum length of the Type.STRING\n   */\n  \"minLength\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Pattern of the Type.STRING to restrict a string to a regular expression.\n   */\n  \"pattern\": S.optionalWith(S.String, { nullable: true })\n}\n\n/**\n * The \\`Schema\\` object allows the definition of input and output data types.\n * These types can be objects, but also primitives and arrays.\n * Represents a select subset of an [OpenAPI 3.0 schema\n * object](https://spec.openapis.org/oas/v3.0.3#schema).\n */\nexport interface SchemaEncoded extends S.Struct.Encoded<typeof schemaFields> {\n  /**\n   * Optional. The value should be validated against any (one or more) of the subschemas\n   * in the list.\n   */\n  readonly \"anyOf\"?: ReadonlyArray<SchemaEncoded> | undefined | null\n  /**\n   * Optional. Schema of the elements of Type.ARRAY.\n   */\n  readonly \"items\"?: SchemaEncoded | undefined | null\n}\n\n/**\n * The \\`Schema\\` object allows the definition of input and output data types.\n * These types can be objects, but also primitives and arrays.\n * Represents a select subset of an [OpenAPI 3.0 schema\n * object](https://spec.openapis.org/oas/v3.0.3#schema).\n */\nexport class Schema extends S.Class<Schema>(\"Schema\")({\n  ...schemaFields,\n  \"anyOf\": S.optionalWith(S.Array(S.suspend((): S.Schema<Schema, SchemaEncoded> => Schema)), { nullable: true }),\n  /**\n   * Optional. Schema of the elements of Type.ARRAY.\n   */\n  \"items\": S.optionalWith(S.suspend((): S.Schema<Schema, SchemaEncoded> => Schema), { nullable: true })\n}) {}\n\n/**\n * Optional. Specifies the function Behavior.\n * Currently only supported by the BidiGenerateContent method.\n */\nexport class FunctionDeclarationBehavior extends S.Literal(\"UNSPECIFIED\", \"BLOCKING\", \"NON_BLOCKING\") {}\n\n/**\n * Structured representation of a function declaration as defined by the\n * [OpenAPI 3.03 specification](https://spec.openapis.org/oas/v3.0.3). Included\n * in this declaration are the function name and parameters. This\n * FunctionDeclaration is a representation of a block of code that can be used\n * as a `Tool` by the model and executed by the client.\n */\nexport class FunctionDeclaration extends S.Class<FunctionDeclaration>(\"FunctionDeclaration\")({\n  /**\n   * Required. The name of the function.\n   * Must be a-z, A-Z, 0-9, or contain underscores, colons, dots, and dashes,\n   * with a maximum length of 64.\n   */\n  \"name\": S.String,\n  /**\n   * Required. A brief description of the function.\n   */\n  \"description\": S.String,\n  /**\n   * Optional. Describes the parameters to this function. Reflects the Open API 3.03\n   * Parameter Object string Key: the name of the parameter. Parameter names are\n   * case sensitive. Schema Value: the Schema defining the type used for the\n   * parameter.\n   */\n  \"parameters\": S.optionalWith(Schema, { nullable: true }),\n  /**\n   * Optional. Describes the output from this function in JSON Schema format. Reflects the\n   * Open API 3.03 Response Object. The Schema defines the type used for the\n   * response value of the function.\n   */\n  \"response\": S.optionalWith(Schema, { nullable: true }),\n  /**\n   * Optional. Specifies the function Behavior.\n   * Currently only supported by the BidiGenerateContent method.\n   */\n  \"behavior\": S.optionalWith(FunctionDeclarationBehavior, { nullable: true })\n}) {}\n\n/**\n * The mode of the predictor to be used in dynamic retrieval.\n */\nexport class DynamicRetrievalConfigMode extends S.Literal(\"MODE_UNSPECIFIED\", \"MODE_DYNAMIC\") {}\n\n/**\n * Describes the options to customize dynamic retrieval.\n */\nexport class DynamicRetrievalConfig extends S.Class<DynamicRetrievalConfig>(\"DynamicRetrievalConfig\")({\n  /**\n   * The mode of the predictor to be used in dynamic retrieval.\n   */\n  \"mode\": S.optionalWith(DynamicRetrievalConfigMode, { nullable: true }),\n  /**\n   * The threshold to be used in dynamic retrieval.\n   * If not set, a system default value is used.\n   */\n  \"dynamicThreshold\": S.optionalWith(S.Number, { nullable: true })\n}) {}\n\n/**\n * Tool to retrieve public web data for grounding, powered by Google.\n */\nexport class GoogleSearchRetrieval extends S.Class<GoogleSearchRetrieval>(\"GoogleSearchRetrieval\")({\n  /**\n   * Specifies the dynamic retrieval configuration for the given source.\n   */\n  \"dynamicRetrievalConfig\": S.optionalWith(DynamicRetrievalConfig, { nullable: true })\n}) {}\n\n/**\n * Tool that executes code generated by the model, and automatically returns\n * the result to the model.\n *\n * See also `ExecutableCode` and `CodeExecutionResult` which are only generated\n * when using this tool.\n */\nexport class CodeExecution extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * Represents a time interval, encoded as a Timestamp start (inclusive) and a\n * Timestamp end (exclusive).\n *\n * The start must be less than or equal to the end.\n * When the start equals the end, the interval is empty (matches no time).\n * When both start and end are unspecified, the interval matches any time.\n */\nexport class Interval extends S.Class<Interval>(\"Interval\")({\n  /**\n   * Optional. Inclusive start of the interval.\n   *\n   * If specified, a Timestamp matching this interval will have to be the same\n   * or after the start.\n   */\n  \"startTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Exclusive end of the interval.\n   *\n   * If specified, a Timestamp matching this interval will have to be before the\n   * end.\n   */\n  \"endTime\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * GoogleSearch tool type.\n * Tool to support Google Search in Model. Powered by Google.\n */\nexport class GoogleSearch extends S.Class<GoogleSearch>(\"GoogleSearch\")({\n  /**\n   * Optional. Filter search results to a specific time range.\n   * If customers set a start time, they must set an end time (and vice\n   * versa).\n   */\n  \"timeRangeFilter\": S.optionalWith(Interval, { nullable: true })\n}) {}\n\n/**\n * Required. The environment being operated.\n */\nexport class ComputerUseEnvironment extends S.Literal(\"ENVIRONMENT_UNSPECIFIED\", \"ENVIRONMENT_BROWSER\") {}\n\n/**\n * Computer Use tool type.\n */\nexport class ComputerUse extends S.Class<ComputerUse>(\"ComputerUse\")({\n  /**\n   * Required. The environment being operated.\n   */\n  \"environment\": ComputerUseEnvironment,\n  /**\n   * Optional. By default, predefined functions are included in the final model\n   * call.\n   * Some of them can be explicitly excluded from being automatically\n   * included. This can serve two purposes:\n   * 1. Using a more restricted / different action space.\n   * 2. Improving the definitions / instructions of predefined functions.\n   */\n  \"excludedPredefinedFunctions\": S.optionalWith(S.Array(S.String), { nullable: true })\n}) {}\n\n/**\n * Tool to support URL context retrieval.\n */\nexport class UrlContext extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * The FileSearch tool that retrieves knowledge from Semantic Retrieval corpora.\n * Files are imported to Semantic Retrieval corpora using the ImportFile API.\n */\nexport class FileSearch extends S.Class<FileSearch>(\"FileSearch\")({\n  /**\n   * Required. The names of the file_search_stores to retrieve from.\n   * Example: `fileSearchStores/my-file-search-store-123`\n   */\n  \"fileSearchStoreNames\": S.Array(S.String),\n  /**\n   * Optional. The number of semantic retrieval chunks to retrieve.\n   */\n  \"topK\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. Metadata filter to apply to the semantic retrieval documents and chunks.\n   */\n  \"metadataFilter\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A transport that can stream HTTP requests and responses.\n * Next ID: 6\n */\nexport class StreamableHttpTransport extends S.Class<StreamableHttpTransport>(\"StreamableHttpTransport\")({\n  /**\n   * The full URL for the MCPServer endpoint.\n   * Example: \"https://api.example.com/mcp\"\n   */\n  \"url\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional: Fields for authentication headers, timeouts, etc., if needed.\n   */\n  \"headers\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * HTTP timeout for regular operations.\n   */\n  \"timeout\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Timeout for SSE read operations.\n   */\n  \"sseReadTimeout\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Whether to close the client session when the transport closes.\n   */\n  \"terminateOnClose\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * A MCPServer is a server that can be called by the model to perform actions.\n * It is a server that implements the MCP protocol.\n * Next ID: 5\n */\nexport class McpServer extends S.Class<McpServer>(\"McpServer\")({\n  /**\n   * A transport that can stream HTTP requests and responses.\n   */\n  \"streamableHttpTransport\": S.optionalWith(StreamableHttpTransport, { nullable: true }),\n  /**\n   * The name of the MCPServer.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The GoogleMaps Tool that provides geospatial context for the user's query.\n */\nexport class GoogleMaps extends S.Class<GoogleMaps>(\"GoogleMaps\")({\n  /**\n   * Optional. Whether to return a widget context token in the GroundingMetadata of the\n   * response. Developers can use the widget context token to render a Google\n   * Maps widget with geospatial context related to the places that the model\n   * references in the response.\n   */\n  \"enableWidget\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * Tool details that the model may use to generate response.\n *\n * A `Tool` is a piece of code that enables the system to interact with\n * external systems to perform an action, or set of actions, outside of\n * knowledge and scope of the model.\n *\n * Next ID: 14\n */\nexport class Tool extends S.Class<Tool>(\"Tool\")({\n  /**\n   * Optional. A list of `FunctionDeclarations` available to the model that can be used\n   * for function calling.\n   *\n   * The model or system does not execute the function. Instead the defined\n   * function may be returned as a FunctionCall\n   * with arguments to the client side for execution. The model may decide to\n   * call a subset of these functions by populating\n   * FunctionCall in the response. The next\n   * conversation turn may contain a\n   * FunctionResponse\n   * with the Content.role \"function\" generation context for the next model\n   * turn.\n   */\n  \"functionDeclarations\": S.optionalWith(S.Array(FunctionDeclaration), { nullable: true }),\n  /**\n   * Optional. Retrieval tool that is powered by Google search.\n   */\n  \"googleSearchRetrieval\": S.optionalWith(GoogleSearchRetrieval, { nullable: true }),\n  /**\n   * Optional. Enables the model to execute code as part of generation.\n   */\n  \"codeExecution\": S.optionalWith(CodeExecution, { nullable: true }),\n  /**\n   * Optional. GoogleSearch tool type.\n   * Tool to support Google Search in Model. Powered by Google.\n   */\n  \"googleSearch\": S.optionalWith(GoogleSearch, { nullable: true }),\n  /**\n   * Optional. Tool to support the model interacting directly with the computer.\n   * If enabled, it automatically populates computer-use specific Function\n   * Declarations.\n   */\n  \"computerUse\": S.optionalWith(ComputerUse, { nullable: true }),\n  /**\n   * Optional. Tool to support URL context retrieval.\n   */\n  \"urlContext\": S.optionalWith(UrlContext, { nullable: true }),\n  /**\n   * Optional. FileSearch tool type.\n   * Tool to retrieve knowledge from Semantic Retrieval corpora.\n   */\n  \"fileSearch\": S.optionalWith(FileSearch, { nullable: true }),\n  /**\n   * Optional. MCP Servers to connect to.\n   */\n  \"mcpServers\": S.optionalWith(S.Array(McpServer), { nullable: true }),\n  /**\n   * Optional. Tool that allows grounding the model's response with geospatial context\n   * related to the user's query.\n   */\n  \"googleMaps\": S.optionalWith(GoogleMaps, { nullable: true })\n}) {}\n\n/**\n * Optional. Specifies the mode in which function calling should execute. If\n * unspecified, the default value will be set to AUTO.\n */\nexport class FunctionCallingConfigMode extends S.Literal(\"MODE_UNSPECIFIED\", \"AUTO\", \"ANY\", \"NONE\", \"VALIDATED\") {}\n\n/**\n * Configuration for specifying function calling behavior.\n */\nexport class FunctionCallingConfig extends S.Class<FunctionCallingConfig>(\"FunctionCallingConfig\")({\n  /**\n   * Optional. Specifies the mode in which function calling should execute. If\n   * unspecified, the default value will be set to AUTO.\n   */\n  \"mode\": S.optionalWith(FunctionCallingConfigMode, { nullable: true }),\n  /**\n   * Optional. A set of function names that, when provided, limits the functions the model\n   * will call.\n   *\n   * This should only be set when the Mode is ANY or VALIDATED. Function names\n   * should match [FunctionDeclaration.name]. When set, model will\n   * predict a function call from only allowed function names.\n   */\n  \"allowedFunctionNames\": S.optionalWith(S.Array(S.String), { nullable: true })\n}) {}\n\n/**\n * An object that represents a latitude/longitude pair. This is expressed as a\n * pair of doubles to represent degrees latitude and degrees longitude. Unless\n * specified otherwise, this object must conform to the\n * WGS84 standard. Values must be within normalized ranges.\n */\nexport class LatLng extends S.Class<LatLng>(\"LatLng\")({\n  /**\n   * The latitude in degrees. It must be in the range [-90.0, +90.0].\n   */\n  \"latitude\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * The longitude in degrees. It must be in the range [-180.0, +180.0].\n   */\n  \"longitude\": S.optionalWith(S.Number, { nullable: true })\n}) {}\n\n/**\n * Retrieval config.\n */\nexport class RetrievalConfig extends S.Class<RetrievalConfig>(\"RetrievalConfig\")({\n  /**\n   * Optional. The location of the user.\n   */\n  \"latLng\": S.optionalWith(LatLng, { nullable: true }),\n  /**\n   * Optional. The language code of the user.\n   * Language code for content. Use language tags defined by\n   * [BCP47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt).\n   */\n  \"languageCode\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The Tool configuration containing parameters for specifying `Tool` use\n * in the request.\n */\nexport class ToolConfig extends S.Class<ToolConfig>(\"ToolConfig\")({\n  /**\n   * Optional. Function calling config.\n   */\n  \"functionCallingConfig\": S.optionalWith(FunctionCallingConfig, { nullable: true }),\n  /**\n   * Optional. Retrieval config.\n   */\n  \"retrievalConfig\": S.optionalWith(RetrievalConfig, { nullable: true })\n}) {}\n\nexport class HarmCategory extends S.Literal(\n  \"HARM_CATEGORY_UNSPECIFIED\",\n  \"HARM_CATEGORY_DEROGATORY\",\n  \"HARM_CATEGORY_TOXICITY\",\n  \"HARM_CATEGORY_VIOLENCE\",\n  \"HARM_CATEGORY_SEXUAL\",\n  \"HARM_CATEGORY_MEDICAL\",\n  \"HARM_CATEGORY_DANGEROUS\",\n  \"HARM_CATEGORY_HARASSMENT\",\n  \"HARM_CATEGORY_HATE_SPEECH\",\n  \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\n  \"HARM_CATEGORY_DANGEROUS_CONTENT\",\n  \"HARM_CATEGORY_CIVIC_INTEGRITY\"\n) {}\n\n/**\n * Required. Controls the probability threshold at which harm is blocked.\n */\nexport class SafetySettingThreshold extends S.Literal(\n  \"HARM_BLOCK_THRESHOLD_UNSPECIFIED\",\n  \"BLOCK_LOW_AND_ABOVE\",\n  \"BLOCK_MEDIUM_AND_ABOVE\",\n  \"BLOCK_ONLY_HIGH\",\n  \"BLOCK_NONE\",\n  \"OFF\"\n) {}\n\n/**\n * Safety setting, affecting the safety-blocking behavior.\n *\n * Passing a safety setting for a category changes the allowed probability that\n * content is blocked.\n */\nexport class SafetySetting extends S.Class<SafetySetting>(\"SafetySetting\")({\n  /**\n   * Required. The category for this setting.\n   */\n  \"category\": HarmCategory,\n  /**\n   * Required. Controls the probability threshold at which harm is blocked.\n   */\n  \"threshold\": SafetySettingThreshold\n}) {}\n\n/**\n * The configuration for the prebuilt speaker to use.\n */\nexport class PrebuiltVoiceConfig extends S.Class<PrebuiltVoiceConfig>(\"PrebuiltVoiceConfig\")({\n  /**\n   * The name of the preset voice to use.\n   */\n  \"voiceName\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The configuration for the voice to use.\n */\nexport class VoiceConfig extends S.Class<VoiceConfig>(\"VoiceConfig\")({\n  /**\n   * The configuration for the prebuilt voice to use.\n   */\n  \"prebuiltVoiceConfig\": S.optionalWith(PrebuiltVoiceConfig, { nullable: true })\n}) {}\n\n/**\n * The configuration for a single speaker in a multi speaker setup.\n */\nexport class SpeakerVoiceConfig extends S.Class<SpeakerVoiceConfig>(\"SpeakerVoiceConfig\")({\n  /**\n   * Required. The name of the speaker to use. Should be the same as in the prompt.\n   */\n  \"speaker\": S.String,\n  /**\n   * Required. The configuration for the voice to use.\n   */\n  \"voiceConfig\": VoiceConfig\n}) {}\n\n/**\n * The configuration for the multi-speaker setup.\n */\nexport class MultiSpeakerVoiceConfig extends S.Class<MultiSpeakerVoiceConfig>(\"MultiSpeakerVoiceConfig\")({\n  /**\n   * Required. All the enabled speaker voices.\n   */\n  \"speakerVoiceConfigs\": S.Array(SpeakerVoiceConfig)\n}) {}\n\n/**\n * The speech generation config.\n */\nexport class SpeechConfig extends S.Class<SpeechConfig>(\"SpeechConfig\")({\n  /**\n   * The configuration in case of single-voice output.\n   */\n  \"voiceConfig\": S.optionalWith(VoiceConfig, { nullable: true }),\n  /**\n   * Optional. The configuration for the multi-speaker setup.\n   * It is mutually exclusive with the voice_config field.\n   */\n  \"multiSpeakerVoiceConfig\": S.optionalWith(MultiSpeakerVoiceConfig, { nullable: true }),\n  /**\n   * Optional. Language code (in BCP 47 format, e.g. \"en-US\") for speech synthesis.\n   *\n   * Valid values are: de-DE, en-AU, en-GB, en-IN, en-US, es-US, fr-FR, hi-IN,\n   * pt-BR, ar-XA, es-ES, fr-CA, id-ID, it-IT, ja-JP, tr-TR, vi-VN, bn-IN,\n   * gu-IN, kn-IN, ml-IN, mr-IN, ta-IN, te-IN, nl-NL, ko-KR, cmn-CN, pl-PL,\n   * ru-RU, and th-TH.\n   */\n  \"languageCode\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Optional. Controls the maximum depth of the model's internal reasoning process before\n * it produces a response. If not specified, the default is HIGH. Recommended\n * for Gemini 3 or later models. Use with earlier models results in an error.\n */\nexport class ThinkingConfigThinkingLevel\n  extends S.Literal(\"THINKING_LEVEL_UNSPECIFIED\", \"MINIMAL\", \"LOW\", \"MEDIUM\", \"HIGH\")\n{}\n\n/**\n * Config for thinking features.\n */\nexport class ThinkingConfig extends S.Class<ThinkingConfig>(\"ThinkingConfig\")({\n  /**\n   * Indicates whether to include thoughts in the response.\n   * If true, thoughts are returned only when available.\n   */\n  \"includeThoughts\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * The number of thoughts tokens that the model should generate.\n   */\n  \"thinkingBudget\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. Controls the maximum depth of the model's internal reasoning process before\n   * it produces a response. If not specified, the default is HIGH. Recommended\n   * for Gemini 3 or later models. Use with earlier models results in an error.\n   */\n  \"thinkingLevel\": S.optionalWith(ThinkingConfigThinkingLevel, { nullable: true })\n}) {}\n\n/**\n * Config for image generation features.\n */\nexport class ImageConfig extends S.Class<ImageConfig>(\"ImageConfig\")({\n  /**\n   * Optional. The aspect ratio of the image to generate. Supported aspect ratios: 1:1,\n   * 2:3, 3:2, 3:4, 4:3, 9:16, 16:9, 21:9.\n   *\n   * If not specified, the model will choose a default aspect ratio based on any\n   * reference images provided.\n   */\n  \"aspectRatio\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Specifies the size of generated images. Supported values are `1K`, `2K`,\n   * `4K`. If not specified, the model will use default value `1K`.\n   */\n  \"imageSize\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Optional. If specified, the media resolution specified will be used.\n */\nexport class GenerationConfigMediaResolution extends S.Literal(\n  \"MEDIA_RESOLUTION_UNSPECIFIED\",\n  \"MEDIA_RESOLUTION_LOW\",\n  \"MEDIA_RESOLUTION_MEDIUM\",\n  \"MEDIA_RESOLUTION_HIGH\"\n) {}\n\n/**\n * Configuration options for model generation and outputs. Not all parameters\n * are configurable for every model.\n */\nexport class GenerationConfig extends S.Class<GenerationConfig>(\"GenerationConfig\")({\n  /**\n   * Optional. Number of generated responses to return. If unset, this will default\n   * to 1. Please note that this doesn't work for previous generation\n   * models (Gemini 1.0 family)\n   */\n  \"candidateCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. The set of character sequences (up to 5) that will stop output generation.\n   * If specified, the API will stop at the first appearance of a\n   * `stop_sequence`. The stop sequence will not be included as part of the\n   * response.\n   */\n  \"stopSequences\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Optional. The maximum number of tokens to include in a response candidate.\n   *\n   * Note: The default value varies by model, see the `Model.output_token_limit`\n   * attribute of the `Model` returned from the `getModel` function.\n   */\n  \"maxOutputTokens\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. Controls the randomness of the output.\n   *\n   * Note: The default value varies by model, see the `Model.temperature`\n   * attribute of the `Model` returned from the `getModel` function.\n   *\n   * Values can range from [0.0, 2.0].\n   */\n  \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. The maximum cumulative probability of tokens to consider when sampling.\n   *\n   * The model uses combined Top-k and Top-p (nucleus) sampling.\n   *\n   * Tokens are sorted based on their assigned probabilities so that only the\n   * most likely tokens are considered. Top-k sampling directly limits the\n   * maximum number of tokens to consider, while Nucleus sampling limits the\n   * number of tokens based on the cumulative probability.\n   *\n   * Note: The default value varies by `Model` and is specified by\n   * the`Model.top_p` attribute returned from the `getModel` function. An empty\n   * `top_k` attribute indicates that the model doesn't apply top-k sampling\n   * and doesn't allow setting `top_k` on requests.\n   */\n  \"topP\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. The maximum number of tokens to consider when sampling.\n   *\n   * Gemini models use Top-p (nucleus) sampling or a combination of Top-k and\n   * nucleus sampling. Top-k sampling considers the set of `top_k` most probable\n   * tokens. Models running with nucleus sampling don't allow top_k setting.\n   *\n   * Note: The default value varies by `Model` and is specified by\n   * the`Model.top_p` attribute returned from the `getModel` function. An empty\n   * `top_k` attribute indicates that the model doesn't apply top-k sampling\n   * and doesn't allow setting `top_k` on requests.\n   */\n  \"topK\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. Seed used in decoding. If not set, the request uses a randomly generated\n   * seed.\n   */\n  \"seed\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. MIME type of the generated candidate text.\n   * Supported MIME types are:\n   * `text/plain`: (default) Text output.\n   * `application/json`: JSON response in the response candidates.\n   * `text/x.enum`: ENUM as a string response in the response candidates.\n   * Refer to the\n   * [docs](https://ai.google.dev/gemini-api/docs/prompting_with_media#plain_text_formats)\n   * for a list of all supported text MIME types.\n   */\n  \"responseMimeType\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Output schema of the generated candidate text. Schemas must be a\n   * subset of the [OpenAPI schema](https://spec.openapis.org/oas/v3.0.3#schema)\n   * and can be objects, primitives or arrays.\n   *\n   * If set, a compatible `response_mime_type` must also be set.\n   * Compatible MIME types:\n   * `application/json`: Schema for JSON response.\n   * Refer to the [JSON text generation\n   * guide](https://ai.google.dev/gemini-api/docs/json-mode) for more details.\n   */\n  \"responseSchema\": S.optionalWith(Schema, { nullable: true }),\n  /**\n   * Optional. Presence penalty applied to the next token's logprobs if the token has\n   * already been seen in the response.\n   *\n   * This penalty is binary on/off and not dependant on the number of times the\n   * token is used (after the first). Use\n   * frequency_penalty\n   * for a penalty that increases with each use.\n   *\n   * A positive penalty will discourage the use of tokens that have already\n   * been used in the response, increasing the vocabulary.\n   *\n   * A negative penalty will encourage the use of tokens that have already been\n   * used in the response, decreasing the vocabulary.\n   */\n  \"presencePenalty\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. Frequency penalty applied to the next token's logprobs, multiplied by the\n   * number of times each token has been seen in the respponse so far.\n   *\n   * A positive penalty will discourage the use of tokens that have already\n   * been used, proportional to the number of times the token has been used:\n   * The more a token is used, the more difficult it is for the model to use\n   * that token again increasing the vocabulary of responses.\n   *\n   * Caution: A _negative_ penalty will encourage the model to reuse tokens\n   * proportional to the number of times the token has been used. Small\n   * negative values will reduce the vocabulary of a response. Larger negative\n   * values will cause the model to start repeating a common token  until it\n   * hits the max_output_tokens\n   * limit.\n   */\n  \"frequencyPenalty\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. If true, export the logprobs results in response.\n   */\n  \"responseLogprobs\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * Optional. Only valid if response_logprobs=True.\n   * This sets the number of top logprobs to return at each decoding step in the\n   * Candidate.logprobs_result. The number must be in the range of [0, 20].\n   */\n  \"logprobs\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. Enables enhanced civic answers. It may not be available for all models.\n   */\n  \"enableEnhancedCivicAnswers\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * Optional. The requested modalities of the response. Represents the set of modalities\n   * that the model can return, and should be expected in the response. This is\n   * an exact match to the modalities of the response.\n   *\n   * A model may have multiple combinations of supported modalities. If the\n   * requested modalities do not match any of the supported combinations, an\n   * error will be returned.\n   *\n   * An empty list is equivalent to requesting only text.\n   */\n  \"responseModalities\": S.optionalWith(S.Array(S.Literal(\"MODALITY_UNSPECIFIED\", \"TEXT\", \"IMAGE\", \"AUDIO\")), {\n    nullable: true\n  }),\n  /**\n   * Optional. The speech generation config.\n   */\n  \"speechConfig\": S.optionalWith(SpeechConfig, { nullable: true }),\n  /**\n   * Optional. Config for thinking features.\n   * An error will be returned if this field is set for models that don't\n   * support thinking.\n   */\n  \"thinkingConfig\": S.optionalWith(ThinkingConfig, { nullable: true }),\n  /**\n   * Optional. Config for image generation.\n   * An error will be returned if this field is set for models that don't\n   * support these config options.\n   */\n  \"imageConfig\": S.optionalWith(ImageConfig, { nullable: true }),\n  /**\n   * Optional. If specified, the media resolution specified will be used.\n   */\n  \"mediaResolution\": S.optionalWith(GenerationConfigMediaResolution, { nullable: true })\n}) {}\n\n/**\n * Request to generate a completion from the model.\n */\nexport class GenerateContentRequest extends S.Class<GenerateContentRequest>(\"GenerateContentRequest\")({\n  /**\n   * Required. The name of the `Model` to use for generating the completion.\n   *\n   * Format: `models/{model}`.\n   */\n  \"model\": S.String,\n  /**\n   * Optional. Developer set [system\n   * instruction(s)](https://ai.google.dev/gemini-api/docs/system-instructions).\n   * Currently, text only.\n   */\n  \"systemInstruction\": S.optionalWith(Content, { nullable: true }),\n  /**\n   * Required. The content of the current conversation with the model.\n   *\n   * For single-turn queries, this is a single instance. For multi-turn queries\n   * like [chat](https://ai.google.dev/gemini-api/docs/text-generation#chat),\n   * this is a repeated field that contains the conversation history and the\n   * latest request.\n   */\n  \"contents\": S.Array(Content),\n  /**\n   * Optional. A list of `Tools` the `Model` may use to generate the next response.\n   *\n   * A `Tool` is a piece of code that enables the system to interact with\n   * external systems to perform an action, or set of actions, outside of\n   * knowledge and scope of the `Model`. Supported `Tool`s are `Function` and\n   * `code_execution`. Refer to the [Function\n   * calling](https://ai.google.dev/gemini-api/docs/function-calling) and the\n   * [Code execution](https://ai.google.dev/gemini-api/docs/code-execution)\n   * guides to learn more.\n   */\n  \"tools\": S.optionalWith(S.Array(Tool), { nullable: true }),\n  /**\n   * Optional. Tool configuration for any `Tool` specified in the request. Refer to the\n   * [Function calling\n   * guide](https://ai.google.dev/gemini-api/docs/function-calling#function_calling_mode)\n   * for a usage example.\n   */\n  \"toolConfig\": S.optionalWith(ToolConfig, { nullable: true }),\n  /**\n   * Optional. A list of unique `SafetySetting` instances for blocking unsafe content.\n   *\n   * This will be enforced on the `GenerateContentRequest.contents` and\n   * `GenerateContentResponse.candidates`. There should not be more than one\n   * setting for each `SafetyCategory` type. The API will block any contents and\n   * responses that fail to meet the thresholds set by these settings. This list\n   * overrides the default settings for each `SafetyCategory` specified in the\n   * safety_settings. If there is no `SafetySetting` for a given\n   * `SafetyCategory` provided in the list, the API will use the default safety\n   * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH,\n   * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT,\n   * HARM_CATEGORY_HARASSMENT, HARM_CATEGORY_CIVIC_INTEGRITY are supported.\n   * Refer to the [guide](https://ai.google.dev/gemini-api/docs/safety-settings)\n   * for detailed information on available safety settings. Also refer to the\n   * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to\n   * learn how to incorporate safety considerations in your AI applications.\n   */\n  \"safetySettings\": S.optionalWith(S.Array(SafetySetting), { nullable: true }),\n  /**\n   * Optional. Configuration options for model generation and outputs.\n   */\n  \"generationConfig\": S.optionalWith(GenerationConfig, { nullable: true }),\n  /**\n   * Optional. The name of the content\n   * [cached](https://ai.google.dev/gemini-api/docs/caching) to use as context\n   * to serve the prediction. Format: `cachedContents/{cachedContent}`\n   */\n  \"cachedContent\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Optional. Output only. The reason why the model stopped generating tokens.\n *\n * If empty, the model has not stopped generating tokens.\n */\nexport class CandidateFinishReason extends S.Literal(\n  \"FINISH_REASON_UNSPECIFIED\",\n  \"STOP\",\n  \"MAX_TOKENS\",\n  \"SAFETY\",\n  \"RECITATION\",\n  \"LANGUAGE\",\n  \"OTHER\",\n  \"BLOCKLIST\",\n  \"PROHIBITED_CONTENT\",\n  \"SPII\",\n  \"MALFORMED_FUNCTION_CALL\",\n  \"IMAGE_SAFETY\",\n  \"IMAGE_PROHIBITED_CONTENT\",\n  \"IMAGE_OTHER\",\n  \"NO_IMAGE\",\n  \"IMAGE_RECITATION\",\n  \"UNEXPECTED_TOOL_CALL\",\n  \"TOO_MANY_TOOL_CALLS\",\n  \"MISSING_THOUGHT_SIGNATURE\"\n) {}\n\n/**\n * Required. The probability of harm for this content.\n */\nexport class SafetyRatingProbability\n  extends S.Literal(\"HARM_PROBABILITY_UNSPECIFIED\", \"NEGLIGIBLE\", \"LOW\", \"MEDIUM\", \"HIGH\")\n{}\n\n/**\n * Safety rating for a piece of content.\n *\n * The safety rating contains the category of harm and the\n * harm probability level in that category for a piece of content.\n * Content is classified for safety across a number of\n * harm categories and the probability of the harm classification is included\n * here.\n */\nexport class SafetyRating extends S.Class<SafetyRating>(\"SafetyRating\")({\n  /**\n   * Required. The category for this rating.\n   */\n  \"category\": HarmCategory,\n  /**\n   * Required. The probability of harm for this content.\n   */\n  \"probability\": SafetyRatingProbability,\n  /**\n   * Was this content blocked because of this rating?\n   */\n  \"blocked\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * A citation to a source for a portion of a specific response.\n */\nexport class CitationSource extends S.Class<CitationSource>(\"CitationSource\")({\n  /**\n   * Optional. Start of segment of the response that is attributed to this source.\n   *\n   * Index indicates the start of the segment, measured in bytes.\n   */\n  \"startIndex\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. End of the attributed segment, exclusive.\n   */\n  \"endIndex\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. URI that is attributed as a source for a portion of the text.\n   */\n  \"uri\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. License for the GitHub project that is attributed as a source for segment.\n   *\n   * License info is required for code citations.\n   */\n  \"license\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A collection of source attributions for a piece of content.\n */\nexport class CitationMetadata extends S.Class<CitationMetadata>(\"CitationMetadata\")({\n  /**\n   * Citations to sources for a specific response.\n   */\n  \"citationSources\": S.optionalWith(S.Array(CitationSource), { nullable: true })\n}) {}\n\n/**\n * Identifier for a part within a `GroundingPassage`.\n */\nexport class GroundingPassageId extends S.Class<GroundingPassageId>(\"GroundingPassageId\")({\n  /**\n   * Output only. ID of the passage matching the `GenerateAnswerRequest`'s\n   * `GroundingPassage.id`.\n   */\n  \"passageId\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. Index of the part within the `GenerateAnswerRequest`'s\n   * `GroundingPassage.content`.\n   */\n  \"partIndex\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * Identifier for a `Chunk` retrieved via Semantic Retriever specified in the\n * `GenerateAnswerRequest` using `SemanticRetrieverConfig`.\n */\nexport class SemanticRetrieverChunk extends S.Class<SemanticRetrieverChunk>(\"SemanticRetrieverChunk\")({\n  /**\n   * Output only. Name of the source matching the request's\n   * `SemanticRetrieverConfig.source`. Example: `corpora/123` or\n   * `corpora/123/documents/abc`\n   */\n  \"source\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. Name of the `Chunk` containing the attributed text.\n   * Example: `corpora/123/documents/abc/chunks/xyz`\n   */\n  \"chunk\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Identifier for the source contributing to this attribution.\n */\nexport class AttributionSourceId extends S.Class<AttributionSourceId>(\"AttributionSourceId\")({\n  /**\n   * Identifier for an inline passage.\n   */\n  \"groundingPassage\": S.optionalWith(GroundingPassageId, { nullable: true }),\n  /**\n   * Identifier for a `Chunk` fetched via Semantic Retriever.\n   */\n  \"semanticRetrieverChunk\": S.optionalWith(SemanticRetrieverChunk, { nullable: true })\n}) {}\n\n/**\n * Attribution for a source that contributed to an answer.\n */\nexport class GroundingAttribution extends S.Class<GroundingAttribution>(\"GroundingAttribution\")({\n  /**\n   * Output only. Identifier for the source contributing to this attribution.\n   */\n  \"sourceId\": S.optionalWith(AttributionSourceId, { nullable: true }),\n  /**\n   * Grounding source content that makes up this attribution.\n   */\n  \"content\": S.optionalWith(Content, { nullable: true })\n}) {}\n\n/**\n * Google search entry point.\n */\nexport class SearchEntryPoint extends S.Class<SearchEntryPoint>(\"SearchEntryPoint\")({\n  /**\n   * Optional. Web content snippet that can be embedded in a web page or an app webview.\n   */\n  \"renderedContent\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Base64 encoded JSON representing array of  tuple.\n   */\n  \"sdkBlob\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Chunk from the web.\n */\nexport class Web extends S.Class<Web>(\"Web\")({\n  /**\n   * URI reference of the chunk.\n   */\n  \"uri\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Title of the chunk.\n   */\n  \"title\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Chunk from context retrieved by the file search tool.\n */\nexport class RetrievedContext extends S.Class<RetrievedContext>(\"RetrievedContext\")({\n  /**\n   * Optional. URI reference of the semantic retrieval document.\n   */\n  \"uri\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Title of the document.\n   */\n  \"title\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Text of the chunk.\n   */\n  \"text\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Name of the `FileSearchStore` containing the document.\n   * Example: `fileSearchStores/123`\n   */\n  \"fileSearchStore\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Encapsulates a snippet of a user review that answers a question about\n * the features of a specific place in Google Maps.\n */\nexport class ReviewSnippet extends S.Class<ReviewSnippet>(\"ReviewSnippet\")({\n  /**\n   * The ID of the review snippet.\n   */\n  \"reviewId\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * A link that corresponds to the user review on Google Maps.\n   */\n  \"googleMapsUri\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Title of the review.\n   */\n  \"title\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Collection of sources that provide answers about the features of a given\n * place in Google Maps. Each PlaceAnswerSources message corresponds to a\n * specific place in Google Maps. The Google Maps tool used these sources in\n * order to answer questions about features of the place (e.g: \"does Bar Foo\n * have Wifi\" or \"is Foo Bar wheelchair accessible?\"). Currently we only\n * support review snippets as sources.\n */\nexport class PlaceAnswerSources extends S.Class<PlaceAnswerSources>(\"PlaceAnswerSources\")({\n  /**\n   * Snippets of reviews that are used to generate answers about the\n   * features of a given place in Google Maps.\n   */\n  \"reviewSnippets\": S.optionalWith(S.Array(ReviewSnippet), { nullable: true })\n}) {}\n\n/**\n * A grounding chunk from Google Maps. A Maps chunk corresponds to a single\n * place.\n */\nexport class Maps extends S.Class<Maps>(\"Maps\")({\n  /**\n   * URI reference of the place.\n   */\n  \"uri\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Title of the place.\n   */\n  \"title\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Text description of the place answer.\n   */\n  \"text\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * This ID of the place, in `places/{place_id}` format. A user can use this\n   * ID to look up that place.\n   */\n  \"placeId\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Sources that provide answers about the features of a given place in\n   * Google Maps.\n   */\n  \"placeAnswerSources\": S.optionalWith(PlaceAnswerSources, { nullable: true })\n}) {}\n\n/**\n * Grounding chunk.\n */\nexport class GroundingChunk extends S.Class<GroundingChunk>(\"GroundingChunk\")({\n  /**\n   * Grounding chunk from the web.\n   */\n  \"web\": S.optionalWith(Web, { nullable: true }),\n  /**\n   * Optional. Grounding chunk from context retrieved by the file search tool.\n   */\n  \"retrievedContext\": S.optionalWith(RetrievedContext, { nullable: true }),\n  /**\n   * Optional. Grounding chunk from Google Maps.\n   */\n  \"maps\": S.optionalWith(Maps, { nullable: true })\n}) {}\n\n/**\n * Segment of the content.\n */\nexport class GoogleAiGenerativelanguageV1BetaSegment\n  extends S.Class<GoogleAiGenerativelanguageV1BetaSegment>(\"GoogleAiGenerativelanguageV1BetaSegment\")({\n    /**\n     * The index of a Part object within its parent Content object.\n     */\n    \"partIndex\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * Start index in the given Part, measured in bytes. Offset from the start of\n     * the Part, inclusive, starting at zero.\n     */\n    \"startIndex\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * End index in the given Part, measured in bytes. Offset from the start of\n     * the Part, exclusive, starting at zero.\n     */\n    \"endIndex\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * The text corresponding to the segment from the response.\n     */\n    \"text\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * Grounding support.\n */\nexport class GoogleAiGenerativelanguageV1BetaGroundingSupport\n  extends S.Class<GoogleAiGenerativelanguageV1BetaGroundingSupport>(\"GoogleAiGenerativelanguageV1BetaGroundingSupport\")(\n    {\n      /**\n       * Segment of the content this support belongs to.\n       */\n      \"segment\": S.optionalWith(GoogleAiGenerativelanguageV1BetaSegment, { nullable: true }),\n      /**\n       * Optional. A list of indices (into 'grounding_chunk') specifying the\n       * citations associated with the claim. For instance [1,3,4] means\n       * that grounding_chunk[1], grounding_chunk[3],\n       * grounding_chunk[4] are the retrieved content attributed to the claim.\n       */\n      \"groundingChunkIndices\": S.optionalWith(S.Array(S.Int), { nullable: true }),\n      /**\n       * Optional. Confidence score of the support references. Ranges from 0 to 1. 1 is the\n       * most confident. This list must have the same size as the\n       * grounding_chunk_indices.\n       */\n      \"confidenceScores\": S.optionalWith(S.Array(S.Number), { nullable: true })\n    }\n  )\n{}\n\n/**\n * Metadata related to retrieval in the grounding flow.\n */\nexport class RetrievalMetadata extends S.Class<RetrievalMetadata>(\"RetrievalMetadata\")({\n  /**\n   * Optional. Score indicating how likely information from google search could help\n   * answer the prompt. The score is in the range [0, 1], where 0 is the least\n   * likely and 1 is the most likely. This score is only populated when\n   * google search grounding and dynamic retrieval is enabled. It will be\n   * compared to the threshold to determine whether to trigger google search.\n   */\n  \"googleSearchDynamicRetrievalScore\": S.optionalWith(S.Number, { nullable: true })\n}) {}\n\n/**\n * Metadata returned to client when grounding is enabled.\n */\nexport class GroundingMetadata extends S.Class<GroundingMetadata>(\"GroundingMetadata\")({\n  /**\n   * Optional. Google search entry for the following-up web searches.\n   */\n  \"searchEntryPoint\": S.optionalWith(SearchEntryPoint, { nullable: true }),\n  /**\n   * List of supporting references retrieved from specified grounding source.\n   */\n  \"groundingChunks\": S.optionalWith(S.Array(GroundingChunk), { nullable: true }),\n  /**\n   * List of grounding support.\n   */\n  \"groundingSupports\": S.optionalWith(S.Array(GoogleAiGenerativelanguageV1BetaGroundingSupport), { nullable: true }),\n  /**\n   * Metadata related to retrieval in the grounding flow.\n   */\n  \"retrievalMetadata\": S.optionalWith(RetrievalMetadata, { nullable: true }),\n  /**\n   * Web search queries for the following-up web search.\n   */\n  \"webSearchQueries\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Optional. Resource name of the Google Maps widget context token that can be used\n   * with the PlacesContextElement widget in order to render contextual data.\n   * Only populated in the case that grounding with Google Maps is enabled.\n   */\n  \"googleMapsWidgetContextToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Candidate for the logprobs token and score.\n */\nexport class LogprobsResultCandidate extends S.Class<LogprobsResultCandidate>(\"LogprobsResultCandidate\")({\n  /**\n   * The candidate’s token string value.\n   */\n  \"token\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The candidate’s token id value.\n   */\n  \"tokenId\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The candidate's log probability.\n   */\n  \"logProbability\": S.optionalWith(S.Number, { nullable: true })\n}) {}\n\n/**\n * Candidates with top log probabilities at each decoding step.\n */\nexport class TopCandidates extends S.Class<TopCandidates>(\"TopCandidates\")({\n  /**\n   * Sorted by log probability in descending order.\n   */\n  \"candidates\": S.optionalWith(S.Array(LogprobsResultCandidate), { nullable: true })\n}) {}\n\n/**\n * Logprobs Result\n */\nexport class LogprobsResult extends S.Class<LogprobsResult>(\"LogprobsResult\")({\n  /**\n   * Sum of log probabilities for all tokens.\n   */\n  \"logProbabilitySum\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Length = total number of decoding steps.\n   */\n  \"topCandidates\": S.optionalWith(S.Array(TopCandidates), { nullable: true }),\n  /**\n   * Length = total number of decoding steps.\n   * The chosen candidates may or may not be in top_candidates.\n   */\n  \"chosenCandidates\": S.optionalWith(S.Array(LogprobsResultCandidate), { nullable: true })\n}) {}\n\n/**\n * Status of the url retrieval.\n */\nexport class UrlMetadataUrlRetrievalStatus extends S.Literal(\n  \"URL_RETRIEVAL_STATUS_UNSPECIFIED\",\n  \"URL_RETRIEVAL_STATUS_SUCCESS\",\n  \"URL_RETRIEVAL_STATUS_ERROR\",\n  \"URL_RETRIEVAL_STATUS_PAYWALL\",\n  \"URL_RETRIEVAL_STATUS_UNSAFE\"\n) {}\n\n/**\n * Context of the a single url retrieval.\n */\nexport class UrlMetadata extends S.Class<UrlMetadata>(\"UrlMetadata\")({\n  /**\n   * Retrieved url by the tool.\n   */\n  \"retrievedUrl\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Status of the url retrieval.\n   */\n  \"urlRetrievalStatus\": S.optionalWith(UrlMetadataUrlRetrievalStatus, { nullable: true })\n}) {}\n\n/**\n * Metadata related to url context retrieval tool.\n */\nexport class UrlContextMetadata extends S.Class<UrlContextMetadata>(\"UrlContextMetadata\")({\n  /**\n   * List of url context.\n   */\n  \"urlMetadata\": S.optionalWith(S.Array(UrlMetadata), { nullable: true })\n}) {}\n\n/**\n * A response candidate generated from the model.\n */\nexport class Candidate extends S.Class<Candidate>(\"Candidate\")({\n  /**\n   * Output only. Index of the candidate in the list of response candidates.\n   */\n  \"index\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Output only. Generated content returned from the model.\n   */\n  \"content\": S.optionalWith(Content, { nullable: true }),\n  /**\n   * Optional. Output only. The reason why the model stopped generating tokens.\n   *\n   * If empty, the model has not stopped generating tokens.\n   */\n  \"finishReason\": S.optionalWith(CandidateFinishReason, { nullable: true }),\n  /**\n   * Optional. Output only. Details the reason why the model stopped generating tokens.\n   * This is populated only when `finish_reason` is set.\n   */\n  \"finishMessage\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * List of ratings for the safety of a response candidate.\n   *\n   * There is at most one rating per category.\n   */\n  \"safetyRatings\": S.optionalWith(S.Array(SafetyRating), { nullable: true }),\n  /**\n   * Output only. Citation information for model-generated candidate.\n   *\n   * This field may be populated with recitation information for any text\n   * included in the `content`. These are passages that are \"recited\" from\n   * copyrighted material in the foundational LLM's training data.\n   */\n  \"citationMetadata\": S.optionalWith(CitationMetadata, { nullable: true }),\n  /**\n   * Output only. Token count for this candidate.\n   */\n  \"tokenCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Output only. Attribution information for sources that contributed to a grounded answer.\n   *\n   * This field is populated for `GenerateAnswer` calls.\n   */\n  \"groundingAttributions\": S.optionalWith(S.Array(GroundingAttribution), { nullable: true }),\n  /**\n   * Output only. Grounding metadata for the candidate.\n   *\n   * This field is populated for `GenerateContent` calls.\n   */\n  \"groundingMetadata\": S.optionalWith(GroundingMetadata, { nullable: true }),\n  /**\n   * Output only. Average log probability score of the candidate.\n   */\n  \"avgLogprobs\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Output only. Log-likelihood scores for the response tokens and top tokens\n   */\n  \"logprobsResult\": S.optionalWith(LogprobsResult, { nullable: true }),\n  /**\n   * Output only. Metadata related to url context retrieval tool.\n   */\n  \"urlContextMetadata\": S.optionalWith(UrlContextMetadata, { nullable: true })\n}) {}\n\n/**\n * Optional. If set, the prompt was blocked and no candidates are returned.\n * Rephrase the prompt.\n */\nexport class PromptFeedbackBlockReason\n  extends S.Literal(\"BLOCK_REASON_UNSPECIFIED\", \"SAFETY\", \"OTHER\", \"BLOCKLIST\", \"PROHIBITED_CONTENT\", \"IMAGE_SAFETY\")\n{}\n\n/**\n * A set of the feedback metadata the prompt specified in\n * `GenerateContentRequest.content`.\n */\nexport class PromptFeedback extends S.Class<PromptFeedback>(\"PromptFeedback\")({\n  /**\n   * Optional. If set, the prompt was blocked and no candidates are returned.\n   * Rephrase the prompt.\n   */\n  \"blockReason\": S.optionalWith(PromptFeedbackBlockReason, { nullable: true }),\n  /**\n   * Ratings for safety of the prompt.\n   * There is at most one rating per category.\n   */\n  \"safetyRatings\": S.optionalWith(S.Array(SafetyRating), { nullable: true })\n}) {}\n\nexport class GenerativeLanguageModality\n  extends S.Literal(\"MODALITY_UNSPECIFIED\", \"TEXT\", \"IMAGE\", \"VIDEO\", \"AUDIO\", \"DOCUMENT\")\n{}\n\n/**\n * Represents token counting info for a single modality.\n */\nexport class ModalityTokenCount extends S.Class<ModalityTokenCount>(\"ModalityTokenCount\")({\n  /**\n   * The modality associated with this token count.\n   */\n  \"modality\": S.optionalWith(GenerativeLanguageModality, { nullable: true }),\n  /**\n   * Number of tokens.\n   */\n  \"tokenCount\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * Metadata on the generation request's token usage.\n */\nexport class UsageMetadata extends S.Class<UsageMetadata>(\"UsageMetadata\")({\n  /**\n   * Number of tokens in the prompt. When `cached_content` is set, this is\n   * still the total effective prompt size meaning this includes the number of\n   * tokens in the cached content.\n   */\n  \"promptTokenCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Number of tokens in the cached part of the prompt (the cached content)\n   */\n  \"cachedContentTokenCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Total number of tokens across all the generated response candidates.\n   */\n  \"candidatesTokenCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Output only. Number of tokens present in tool-use prompt(s).\n   */\n  \"toolUsePromptTokenCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Output only. Number of tokens of thoughts for thinking models.\n   */\n  \"thoughtsTokenCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Total token count for the generation request (prompt + response\n   * candidates).\n   */\n  \"totalTokenCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Output only. List of modalities that were processed in the request input.\n   */\n  \"promptTokensDetails\": S.optionalWith(S.Array(ModalityTokenCount), { nullable: true }),\n  /**\n   * Output only. List of modalities of the cached content in the request input.\n   */\n  \"cacheTokensDetails\": S.optionalWith(S.Array(ModalityTokenCount), { nullable: true }),\n  /**\n   * Output only. List of modalities that were returned in the response.\n   */\n  \"candidatesTokensDetails\": S.optionalWith(S.Array(ModalityTokenCount), { nullable: true }),\n  /**\n   * Output only. List of modalities that were processed for tool-use request inputs.\n   */\n  \"toolUsePromptTokensDetails\": S.optionalWith(S.Array(ModalityTokenCount), { nullable: true })\n}) {}\n\n/**\n * Response from the model supporting multiple candidate responses.\n *\n * Safety ratings and content filtering are reported for both\n * prompt in `GenerateContentResponse.prompt_feedback` and for each candidate\n * in `finish_reason` and in `safety_ratings`. The API:\n *  - Returns either all requested candidates or none of them\n *  - Returns no candidates at all only if there was something wrong with the\n *    prompt (check `prompt_feedback`)\n *  - Reports feedback on each candidate in `finish_reason` and\n *    `safety_ratings`.\n */\nexport class GenerateContentResponse extends S.Class<GenerateContentResponse>(\"GenerateContentResponse\")({\n  /**\n   * Candidate responses from the model.\n   */\n  \"candidates\": S.optionalWith(S.Array(Candidate), { nullable: true }),\n  /**\n   * Returns the prompt's feedback related to the content filters.\n   */\n  \"promptFeedback\": S.optionalWith(PromptFeedback, { nullable: true }),\n  /**\n   * Output only. Metadata on the generation requests' token usage.\n   */\n  \"usageMetadata\": S.optionalWith(UsageMetadata, { nullable: true }),\n  /**\n   * Output only. The model version used to generate the response.\n   */\n  \"modelVersion\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. response_id is used to identify each response.\n   */\n  \"responseId\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Passage included inline with a grounding configuration.\n */\nexport class GroundingPassage extends S.Class<GroundingPassage>(\"GroundingPassage\")({\n  /**\n   * Identifier for the passage for attributing this passage in grounded\n   * answers.\n   */\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Content of the passage.\n   */\n  \"content\": S.optionalWith(Content, { nullable: true })\n}) {}\n\n/**\n * A repeated list of passages.\n */\nexport class GroundingPassages extends S.Class<GroundingPassages>(\"GroundingPassages\")({\n  /**\n   * List of passages.\n   */\n  \"passages\": S.optionalWith(S.Array(GroundingPassage), { nullable: true })\n}) {}\n\n/**\n * Required. Operator applied to the given key-value pair to trigger the condition.\n */\nexport class ConditionOperation extends S.Literal(\n  \"OPERATOR_UNSPECIFIED\",\n  \"LESS\",\n  \"LESS_EQUAL\",\n  \"EQUAL\",\n  \"GREATER_EQUAL\",\n  \"GREATER\",\n  \"NOT_EQUAL\",\n  \"INCLUDES\",\n  \"EXCLUDES\"\n) {}\n\n/**\n * Filter condition applicable to a single key.\n */\nexport class Condition extends S.Class<Condition>(\"Condition\")({\n  /**\n   * The string value to filter the metadata on.\n   */\n  \"stringValue\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The numeric value to filter the metadata on.\n   */\n  \"numericValue\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Required. Operator applied to the given key-value pair to trigger the condition.\n   */\n  \"operation\": ConditionOperation\n}) {}\n\n/**\n * User provided filter to limit retrieval based on `Chunk` or `Document` level\n * metadata values.\n * Example (genre = drama OR genre = action):\n *   key = \"document.custom_metadata.genre\"\n *   conditions = [{string_value = \"drama\", operation = EQUAL},\n *                 {string_value = \"action\", operation = EQUAL}]\n */\nexport class MetadataFilter extends S.Class<MetadataFilter>(\"MetadataFilter\")({\n  /**\n   * Required. The key of the metadata to filter on.\n   */\n  \"key\": S.String,\n  /**\n   * Required. The `Condition`s for the given key that will trigger this filter. Multiple\n   * `Condition`s are joined by logical ORs.\n   */\n  \"conditions\": S.Array(Condition)\n}) {}\n\n/**\n * Configuration for retrieving grounding content from a `Corpus` or\n * `Document` created using the Semantic Retriever API.\n */\nexport class SemanticRetrieverConfig extends S.Class<SemanticRetrieverConfig>(\"SemanticRetrieverConfig\")({\n  /**\n   * Required. Name of the resource for retrieval. Example: `corpora/123` or\n   * `corpora/123/documents/abc`.\n   */\n  \"source\": S.String,\n  /**\n   * Required. Query to use for matching `Chunk`s in the given resource by similarity.\n   */\n  \"query\": Content,\n  /**\n   * Optional. Filters for selecting `Document`s and/or `Chunk`s from the resource.\n   */\n  \"metadataFilters\": S.optionalWith(S.Array(MetadataFilter), { nullable: true }),\n  /**\n   * Optional. Maximum number of relevant `Chunk`s to retrieve.\n   */\n  \"maxChunksCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. Minimum relevance score for retrieved relevant `Chunk`s.\n   */\n  \"minimumRelevanceScore\": S.optionalWith(S.Number, { nullable: true })\n}) {}\n\n/**\n * Required. Style in which answers should be returned.\n */\nexport class GenerateAnswerRequestAnswerStyle\n  extends S.Literal(\"ANSWER_STYLE_UNSPECIFIED\", \"ABSTRACTIVE\", \"EXTRACTIVE\", \"VERBOSE\")\n{}\n\n/**\n * Request to generate a grounded answer from the `Model`.\n */\nexport class GenerateAnswerRequest extends S.Class<GenerateAnswerRequest>(\"GenerateAnswerRequest\")({\n  /**\n   * Passages provided inline with the request.\n   */\n  \"inlinePassages\": S.optionalWith(GroundingPassages, { nullable: true }),\n  /**\n   * Content retrieved from resources created via the Semantic Retriever\n   * API.\n   */\n  \"semanticRetriever\": S.optionalWith(SemanticRetrieverConfig, { nullable: true }),\n  /**\n   * Required. The content of the current conversation with the `Model`. For single-turn\n   * queries, this is a single question to answer. For multi-turn queries, this\n   * is a repeated field that contains conversation history and the last\n   * `Content` in the list containing the question.\n   *\n   * Note: `GenerateAnswer` only supports queries in English.\n   */\n  \"contents\": S.Array(Content),\n  /**\n   * Required. Style in which answers should be returned.\n   */\n  \"answerStyle\": GenerateAnswerRequestAnswerStyle,\n  /**\n   * Optional. A list of unique `SafetySetting` instances for blocking unsafe content.\n   *\n   * This will be enforced on the `GenerateAnswerRequest.contents` and\n   * `GenerateAnswerResponse.candidate`. There should not be more than one\n   * setting for each `SafetyCategory` type. The API will block any contents and\n   * responses that fail to meet the thresholds set by these settings. This list\n   * overrides the default settings for each `SafetyCategory` specified in the\n   * safety_settings. If there is no `SafetySetting` for a given\n   * `SafetyCategory` provided in the list, the API will use the default safety\n   * setting for that category. Harm categories HARM_CATEGORY_HATE_SPEECH,\n   * HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT,\n   * HARM_CATEGORY_HARASSMENT are supported.\n   * Refer to the\n   * [guide](https://ai.google.dev/gemini-api/docs/safety-settings)\n   * for detailed information on available safety settings. Also refer to the\n   * [Safety guidance](https://ai.google.dev/gemini-api/docs/safety-guidance) to\n   * learn how to incorporate safety considerations in your AI applications.\n   */\n  \"safetySettings\": S.optionalWith(S.Array(SafetySetting), { nullable: true }),\n  /**\n   * Optional. Controls the randomness of the output.\n   *\n   * Values can range from [0.0,1.0], inclusive. A value closer to 1.0 will\n   * produce responses that are more varied and creative, while a value closer\n   * to 0.0 will typically result in more straightforward responses from the\n   * model. A low temperature (~0.2) is usually recommended for\n   * Attributed-Question-Answering use cases.\n   */\n  \"temperature\": S.optionalWith(S.Number, { nullable: true })\n}) {}\n\n/**\n * Optional. If set, the input was blocked and no candidates are returned.\n * Rephrase the input.\n */\nexport class InputFeedbackBlockReason extends S.Literal(\"BLOCK_REASON_UNSPECIFIED\", \"SAFETY\", \"OTHER\") {}\n\n/**\n * Feedback related to the input data used to answer the question, as opposed\n * to the model-generated response to the question.\n */\nexport class InputFeedback extends S.Class<InputFeedback>(\"InputFeedback\")({\n  /**\n   * Optional. If set, the input was blocked and no candidates are returned.\n   * Rephrase the input.\n   */\n  \"blockReason\": S.optionalWith(InputFeedbackBlockReason, { nullable: true }),\n  /**\n   * Ratings for safety of the input.\n   * There is at most one rating per category.\n   */\n  \"safetyRatings\": S.optionalWith(S.Array(SafetyRating), { nullable: true })\n}) {}\n\n/**\n * Response from the model for a grounded answer.\n */\nexport class GenerateAnswerResponse extends S.Class<GenerateAnswerResponse>(\"GenerateAnswerResponse\")({\n  /**\n   * Candidate answer from the model.\n   *\n   * Note: The model *always* attempts to provide a grounded answer, even when\n   * the answer is unlikely to be answerable from the given passages.\n   * In that case, a low-quality or ungrounded answer may be provided, along\n   * with a low `answerable_probability`.\n   */\n  \"answer\": S.optionalWith(Candidate, { nullable: true }),\n  /**\n   * Output only. The model's estimate of the probability that its answer is correct and\n   * grounded in the input passages.\n   *\n   * A low `answerable_probability` indicates that the answer might not be\n   * grounded in the sources.\n   *\n   * When `answerable_probability` is low, you may want to:\n   *\n   * * Display a message to the effect of \"We couldn’t answer that question\" to\n   * the user.\n   * * Fall back to a general-purpose LLM that answers the question from world\n   * knowledge. The threshold and nature of such fallbacks will depend on\n   * individual use cases. `0.5` is a good starting threshold.\n   */\n  \"answerableProbability\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Output only. Feedback related to the input data used to answer the question, as opposed\n   * to the model-generated response to the question.\n   *\n   * The input data can be one or more of the following:\n   *\n   * - Question specified by the last entry in `GenerateAnswerRequest.content`\n   * - Conversation history specified by the other entries in\n   * `GenerateAnswerRequest.content`\n   * - Grounding sources (`GenerateAnswerRequest.semantic_retriever` or\n   * `GenerateAnswerRequest.inline_passages`)\n   */\n  \"inputFeedback\": S.optionalWith(InputFeedback, { nullable: true })\n}) {}\n\nexport class TaskType extends S.Literal(\n  \"TASK_TYPE_UNSPECIFIED\",\n  \"RETRIEVAL_QUERY\",\n  \"RETRIEVAL_DOCUMENT\",\n  \"SEMANTIC_SIMILARITY\",\n  \"CLASSIFICATION\",\n  \"CLUSTERING\",\n  \"QUESTION_ANSWERING\",\n  \"FACT_VERIFICATION\",\n  \"CODE_RETRIEVAL_QUERY\"\n) {}\n\n/**\n * Request containing the `Content` for the model to embed.\n */\nexport class EmbedContentRequest extends S.Class<EmbedContentRequest>(\"EmbedContentRequest\")({\n  /**\n   * Required. The model's resource name. This serves as an ID for the Model to use.\n   *\n   * This name should match a model name returned by the `ListModels` method.\n   *\n   * Format: `models/{model}`\n   */\n  \"model\": S.String,\n  /**\n   * Required. The content to embed. Only the `parts.text` fields will be counted.\n   */\n  \"content\": Content,\n  /**\n   * Optional. Optional task type for which the embeddings will be used. Not supported on\n   * earlier models (`models/embedding-001`).\n   */\n  \"taskType\": S.optionalWith(TaskType, { nullable: true }),\n  /**\n   * Optional. An optional title for the text. Only applicable when TaskType is\n   * `RETRIEVAL_DOCUMENT`.\n   *\n   * Note: Specifying a `title` for `RETRIEVAL_DOCUMENT` provides better quality\n   * embeddings for retrieval.\n   */\n  \"title\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Optional reduced dimension for the output embedding. If set, excessive\n   * values in the output embedding are truncated from the end. Supported by\n   * newer models since 2024 only. You cannot set this value if using the\n   * earlier model (`models/embedding-001`).\n   */\n  \"outputDimensionality\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * A list of floats representing an embedding.\n */\nexport class ContentEmbedding extends S.Class<ContentEmbedding>(\"ContentEmbedding\")({\n  /**\n   * The embedding values. This is for 3P users only and will not be populated\n   * for 1P calls.\n   */\n  \"values\": S.optionalWith(S.Array(S.Number), { nullable: true }),\n  /**\n   * This field stores the soft tokens tensor frame shape\n   * (e.g. [1, 1, 256, 2048]).\n   */\n  \"shape\": S.optionalWith(S.Array(S.Int), { nullable: true })\n}) {}\n\n/**\n * The response to an `EmbedContentRequest`.\n */\nexport class EmbedContentResponse extends S.Class<EmbedContentResponse>(\"EmbedContentResponse\")({\n  /**\n   * Output only. The embedding generated from the input content.\n   */\n  \"embedding\": S.optionalWith(ContentEmbedding, { nullable: true })\n}) {}\n\n/**\n * Batch request to get embeddings from the model for a list of prompts.\n */\nexport class BatchEmbedContentsRequest extends S.Class<BatchEmbedContentsRequest>(\"BatchEmbedContentsRequest\")({\n  /**\n   * Required. Embed requests for the batch. The model in each of these requests must\n   * match the model specified `BatchEmbedContentsRequest.model`.\n   */\n  \"requests\": S.Array(EmbedContentRequest)\n}) {}\n\n/**\n * The response to a `BatchEmbedContentsRequest`.\n */\nexport class BatchEmbedContentsResponse extends S.Class<BatchEmbedContentsResponse>(\"BatchEmbedContentsResponse\")({\n  /**\n   * Output only. The embeddings for each request, in the same order as provided in the batch\n   * request.\n   */\n  \"embeddings\": S.optionalWith(S.Array(ContentEmbedding), { nullable: true })\n}) {}\n\n/**\n * Counts the number of tokens in the `prompt` sent to a model.\n *\n * Models may tokenize text differently, so each model may return a different\n * `token_count`.\n */\nexport class CountTokensRequest extends S.Class<CountTokensRequest>(\"CountTokensRequest\")({\n  /**\n   * Optional. The input given to the model as a prompt. This field is ignored when\n   * `generate_content_request` is set.\n   */\n  \"contents\": S.optionalWith(S.Array(Content), { nullable: true }),\n  /**\n   * Optional. The overall input given to the `Model`. This includes the prompt as well as\n   * other model steering information like [system\n   * instructions](https://ai.google.dev/gemini-api/docs/system-instructions),\n   * and/or function declarations for [function\n   * calling](https://ai.google.dev/gemini-api/docs/function-calling).\n   * `Model`s/`Content`s and `generate_content_request`s are mutually\n   * exclusive. You can either send `Model` + `Content`s or a\n   * `generate_content_request`, but never both.\n   */\n  \"generateContentRequest\": S.optionalWith(GenerateContentRequest, { nullable: true })\n}) {}\n\n/**\n * A response from `CountTokens`.\n *\n * It returns the model's `token_count` for the `prompt`.\n */\nexport class CountTokensResponse extends S.Class<CountTokensResponse>(\"CountTokensResponse\")({\n  /**\n   * The number of tokens that the `Model` tokenizes the `prompt` into. Always\n   * non-negative.\n   */\n  \"totalTokens\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Number of tokens in the cached part of the prompt (the cached content).\n   */\n  \"cachedContentTokenCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Output only. List of modalities that were processed in the request input.\n   */\n  \"promptTokensDetails\": S.optionalWith(S.Array(ModalityTokenCount), { nullable: true }),\n  /**\n   * Output only. List of modalities that were processed in the cached content.\n   */\n  \"cacheTokensDetails\": S.optionalWith(S.Array(ModalityTokenCount), { nullable: true })\n}) {}\n\n/**\n * The request to be processed in the batch.\n */\nexport class InlinedRequest extends S.Class<InlinedRequest>(\"InlinedRequest\")({\n  /**\n   * Required. The request to be processed in the batch.\n   */\n  \"request\": GenerateContentRequest,\n  /**\n   * Optional. The metadata to be associated with the request.\n   */\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * The requests to be processed in the batch if provided as part of the\n * batch creation request.\n */\nexport class InlinedRequests extends S.Class<InlinedRequests>(\"InlinedRequests\")({\n  /**\n   * Required. The requests to be processed in the batch.\n   */\n  \"requests\": S.Array(InlinedRequest)\n}) {}\n\n/**\n * Configures the input to the batch request.\n */\nexport class InputConfig extends S.Class<InputConfig>(\"InputConfig\")({\n  /**\n   * The name of the `File` containing the input requests.\n   */\n  \"fileName\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The requests to be processed in the batch.\n   */\n  \"requests\": S.optionalWith(InlinedRequests, { nullable: true })\n}) {}\n\n/**\n * The response to a single request in the batch.\n */\nexport class InlinedResponse extends S.Class<InlinedResponse>(\"InlinedResponse\")({\n  /**\n   * Output only. The error encountered while processing the request.\n   */\n  \"error\": S.optionalWith(Status, { nullable: true }),\n  /**\n   * Output only. The response to the request.\n   */\n  \"response\": S.optionalWith(GenerateContentResponse, { nullable: true }),\n  /**\n   * Output only. The metadata associated with the request.\n   */\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * The responses to the requests in the batch.\n */\nexport class InlinedResponses extends S.Class<InlinedResponses>(\"InlinedResponses\")({\n  /**\n   * Output only. The responses to the requests in the batch.\n   */\n  \"inlinedResponses\": S.optionalWith(S.Array(InlinedResponse), { nullable: true })\n}) {}\n\n/**\n * The output of a batch request. This is returned in the\n * `BatchGenerateContentResponse` or the `GenerateContentBatch.output` field.\n */\nexport class GenerateContentBatchOutput extends S.Class<GenerateContentBatchOutput>(\"GenerateContentBatchOutput\")({\n  /**\n   * Output only. The file ID of the file containing the responses.\n   * The file will be a JSONL file with a single response per line.\n   * The responses will be `GenerateContentResponse` messages formatted as\n   * JSON.\n   * The responses will be written in the same order as the input requests.\n   */\n  \"responsesFile\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The responses to the requests in the batch. Returned when the batch was\n   * built using inlined requests. The responses will be in the same order as\n   * the input requests.\n   */\n  \"inlinedResponses\": S.optionalWith(InlinedResponses, { nullable: true })\n}) {}\n\n/**\n * Stats about the batch.\n */\nexport class BatchStats extends S.Class<BatchStats>(\"BatchStats\")({\n  /**\n   * Output only. The number of requests in the batch.\n   */\n  \"requestCount\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The number of requests that were successfully processed.\n   */\n  \"successfulRequestCount\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The number of requests that failed to be processed.\n   */\n  \"failedRequestCount\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The number of requests that are still pending processing.\n   */\n  \"pendingRequestCount\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class BatchState extends S.Literal(\n  \"BATCH_STATE_UNSPECIFIED\",\n  \"BATCH_STATE_PENDING\",\n  \"BATCH_STATE_RUNNING\",\n  \"BATCH_STATE_SUCCEEDED\",\n  \"BATCH_STATE_FAILED\",\n  \"BATCH_STATE_CANCELLED\",\n  \"BATCH_STATE_EXPIRED\"\n) {}\n\n/**\n * A resource representing a batch of `GenerateContent` requests.\n */\nexport class GenerateContentBatch extends S.Class<GenerateContentBatch>(\"GenerateContentBatch\")({\n  /**\n   * Required. The name of the `Model` to use for generating the completion.\n   *\n   * Format: `models/{model}`.\n   */\n  \"model\": S.String,\n  /**\n   * Output only. Identifier. Resource name of the batch.\n   *\n   * Format: `batches/{batch_id}`.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. The user-defined name of this batch.\n   */\n  \"displayName\": S.String,\n  /**\n   * Required. Input configuration of the instances on which batch processing\n   * are performed.\n   */\n  \"inputConfig\": InputConfig,\n  /**\n   * Output only. The output of the batch request.\n   */\n  \"output\": S.optionalWith(GenerateContentBatchOutput, { nullable: true }),\n  /**\n   * Output only. The time at which the batch was created.\n   */\n  \"createTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The time at which the batch processing completed.\n   */\n  \"endTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The time at which the batch was last updated.\n   */\n  \"updateTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. Stats about the batch.\n   */\n  \"batchStats\": S.optionalWith(BatchStats, { nullable: true }),\n  /**\n   * Output only. The state of the batch.\n   */\n  \"state\": S.optionalWith(BatchState, { nullable: true }),\n  /**\n   * Optional. The priority of the batch. Batches with a higher priority value will be\n   * processed before batches with a lower priority value. Negative values are\n   * allowed. Default is 0.\n   */\n  \"priority\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Request for a `BatchGenerateContent` operation.\n */\nexport class BatchGenerateContentRequest extends S.Class<BatchGenerateContentRequest>(\"BatchGenerateContentRequest\")({\n  /**\n   * Required. The batch to create.\n   */\n  \"batch\": GenerateContentBatch\n}) {}\n\n/**\n * Response for a `BatchGenerateContent` operation.\n */\nexport class BatchGenerateContentResponse\n  extends S.Class<BatchGenerateContentResponse>(\"BatchGenerateContentResponse\")({\n    /**\n     * Output only. The output of the batch request.\n     */\n    \"output\": S.optionalWith(GenerateContentBatchOutput, { nullable: true })\n  })\n{}\n\n/**\n * This resource represents a long-running operation that is the result of a\n * network API call.\n */\nexport class BatchGenerateContentOperation\n  extends S.Class<BatchGenerateContentOperation>(\"BatchGenerateContentOperation\")({\n    \"metadata\": S.optionalWith(GenerateContentBatch, { nullable: true }),\n    \"response\": S.optionalWith(BatchGenerateContentResponse, { nullable: true }),\n    /**\n     * The server-assigned name, which is only unique within the same service that\n     * originally returns it. If you use the default HTTP mapping, the\n     * `name` should be a resource name ending with `operations/{unique_id}`.\n     */\n    \"name\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * If the value is `false`, it means the operation is still in progress.\n     * If `true`, the operation is completed, and either `error` or `response` is\n     * available.\n     */\n    \"done\": S.optionalWith(S.Boolean, { nullable: true }),\n    /**\n     * The error result of the operation in case of failure or cancellation.\n     */\n    \"error\": S.optionalWith(Status, { nullable: true })\n  })\n{}\n\n/**\n * The request to be processed in the batch.\n */\nexport class InlinedEmbedContentRequest extends S.Class<InlinedEmbedContentRequest>(\"InlinedEmbedContentRequest\")({\n  /**\n   * Required. The request to be processed in the batch.\n   */\n  \"request\": EmbedContentRequest,\n  /**\n   * Optional. The metadata to be associated with the request.\n   */\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * The requests to be processed in the batch if provided as part of the\n * batch creation request.\n */\nexport class InlinedEmbedContentRequests extends S.Class<InlinedEmbedContentRequests>(\"InlinedEmbedContentRequests\")({\n  /**\n   * Required. The requests to be processed in the batch.\n   */\n  \"requests\": S.Array(InlinedEmbedContentRequest)\n}) {}\n\n/**\n * Configures the input to the batch request.\n */\nexport class InputEmbedContentConfig extends S.Class<InputEmbedContentConfig>(\"InputEmbedContentConfig\")({\n  /**\n   * The name of the `File` containing the input requests.\n   */\n  \"fileName\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The requests to be processed in the batch.\n   */\n  \"requests\": S.optionalWith(InlinedEmbedContentRequests, { nullable: true })\n}) {}\n\n/**\n * The response to a single request in the batch.\n */\nexport class InlinedEmbedContentResponse extends S.Class<InlinedEmbedContentResponse>(\"InlinedEmbedContentResponse\")({\n  /**\n   * Output only. The error encountered while processing the request.\n   */\n  \"error\": S.optionalWith(Status, { nullable: true }),\n  /**\n   * Output only. The response to the request.\n   */\n  \"response\": S.optionalWith(EmbedContentResponse, { nullable: true }),\n  /**\n   * Output only. The metadata associated with the request.\n   */\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * The responses to the requests in the batch.\n */\nexport class InlinedEmbedContentResponses\n  extends S.Class<InlinedEmbedContentResponses>(\"InlinedEmbedContentResponses\")({\n    /**\n     * Output only. The responses to the requests in the batch.\n     */\n    \"inlinedResponses\": S.optionalWith(S.Array(InlinedEmbedContentResponse), { nullable: true })\n  })\n{}\n\n/**\n * The output of a batch request. This is returned in the\n * `AsyncBatchEmbedContentResponse` or the `EmbedContentBatch.output` field.\n */\nexport class EmbedContentBatchOutput extends S.Class<EmbedContentBatchOutput>(\"EmbedContentBatchOutput\")({\n  /**\n   * Output only. The file ID of the file containing the responses.\n   * The file will be a JSONL file with a single response per line.\n   * The responses will be `EmbedContentResponse` messages formatted as JSON.\n   * The responses will be written in the same order as the input requests.\n   */\n  \"responsesFile\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The responses to the requests in the batch. Returned when the batch was\n   * built using inlined requests. The responses will be in the same order as\n   * the input requests.\n   */\n  \"inlinedResponses\": S.optionalWith(InlinedEmbedContentResponses, { nullable: true })\n}) {}\n\n/**\n * Stats about the batch.\n */\nexport class EmbedContentBatchStats extends S.Class<EmbedContentBatchStats>(\"EmbedContentBatchStats\")({\n  /**\n   * Output only. The number of requests in the batch.\n   */\n  \"requestCount\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The number of requests that were successfully processed.\n   */\n  \"successfulRequestCount\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The number of requests that failed to be processed.\n   */\n  \"failedRequestCount\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The number of requests that are still pending processing.\n   */\n  \"pendingRequestCount\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A resource representing a batch of `EmbedContent` requests.\n */\nexport class EmbedContentBatch extends S.Class<EmbedContentBatch>(\"EmbedContentBatch\")({\n  /**\n   * Required. The name of the `Model` to use for generating the completion.\n   *\n   * Format: `models/{model}`.\n   */\n  \"model\": S.String,\n  /**\n   * Output only. Identifier. Resource name of the batch.\n   *\n   * Format: `batches/{batch_id}`.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. The user-defined name of this batch.\n   */\n  \"displayName\": S.String,\n  /**\n   * Required. Input configuration of the instances on which batch processing\n   * are performed.\n   */\n  \"inputConfig\": InputEmbedContentConfig,\n  /**\n   * Output only. The output of the batch request.\n   */\n  \"output\": S.optionalWith(EmbedContentBatchOutput, { nullable: true }),\n  /**\n   * Output only. The time at which the batch was created.\n   */\n  \"createTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The time at which the batch processing completed.\n   */\n  \"endTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The time at which the batch was last updated.\n   */\n  \"updateTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. Stats about the batch.\n   */\n  \"batchStats\": S.optionalWith(EmbedContentBatchStats, { nullable: true }),\n  /**\n   * Output only. The state of the batch.\n   */\n  \"state\": S.optionalWith(BatchState, { nullable: true }),\n  /**\n   * Optional. The priority of the batch. Batches with a higher priority value will be\n   * processed before batches with a lower priority value. Negative values are\n   * allowed. Default is 0.\n   */\n  \"priority\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Request for an `AsyncBatchEmbedContent` operation.\n */\nexport class AsyncBatchEmbedContentRequest\n  extends S.Class<AsyncBatchEmbedContentRequest>(\"AsyncBatchEmbedContentRequest\")({\n    /**\n     * Required. The batch to create.\n     */\n    \"batch\": EmbedContentBatch\n  })\n{}\n\n/**\n * Response for a `BatchGenerateContent` operation.\n */\nexport class AsyncBatchEmbedContentResponse\n  extends S.Class<AsyncBatchEmbedContentResponse>(\"AsyncBatchEmbedContentResponse\")({\n    /**\n     * Output only. The output of the batch request.\n     */\n    \"output\": S.optionalWith(EmbedContentBatchOutput, { nullable: true })\n  })\n{}\n\n/**\n * This resource represents a long-running operation that is the result of a\n * network API call.\n */\nexport class AsyncBatchEmbedContentOperation\n  extends S.Class<AsyncBatchEmbedContentOperation>(\"AsyncBatchEmbedContentOperation\")({\n    \"metadata\": S.optionalWith(EmbedContentBatch, { nullable: true }),\n    \"response\": S.optionalWith(AsyncBatchEmbedContentResponse, { nullable: true }),\n    /**\n     * The server-assigned name, which is only unique within the same service that\n     * originally returns it. If you use the default HTTP mapping, the\n     * `name` should be a resource name ending with `operations/{unique_id}`.\n     */\n    \"name\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * If the value is `false`, it means the operation is still in progress.\n     * If `true`, the operation is completed, and either `error` or `response` is\n     * available.\n     */\n    \"done\": S.optionalWith(S.Boolean, { nullable: true }),\n    /**\n     * The error result of the operation in case of failure or cancellation.\n     */\n    \"error\": S.optionalWith(Status, { nullable: true })\n  })\n{}\n\nexport class UpdateGenerateContentBatchParams extends S.Struct({\n  \"updateMask\": S.optionalWith(S.String.pipe(S.pattern(new RegExp(\"^(\\\\s*[^,\\\\s.]+(\\\\s*[,.]\\\\s*[^,\\\\s.]+)*)?$\"))), {\n    nullable: true\n  })\n}) {}\n\nexport class UpdateEmbedContentBatchParams extends S.Struct({\n  \"updateMask\": S.optionalWith(S.String.pipe(S.pattern(new RegExp(\"^(\\\\s*[^,\\\\s.]+(\\\\s*[,.]\\\\s*[^,\\\\s.]+)*)?$\"))), {\n    nullable: true\n  })\n}) {}\n\nexport class ListCachedContentsParams extends S.Struct({\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Metadata on the usage of the cached content.\n */\nexport class CachedContentUsageMetadata extends S.Class<CachedContentUsageMetadata>(\"CachedContentUsageMetadata\")({\n  /**\n   * Total number of tokens that the cached content consumes.\n   */\n  \"totalTokenCount\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * Content that has been preprocessed and can be used in subsequent request\n * to GenerativeService.\n *\n * Cached content can be only used with model it was created for.\n */\nexport class CachedContent extends S.Class<CachedContent>(\"CachedContent\")({\n  /**\n   * Timestamp in UTC of when this resource is considered expired.\n   * This is *always* provided on output, regardless of what was sent\n   * on input.\n   */\n  \"expireTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Input only. New TTL for this resource, input only.\n   */\n  \"ttl\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. Identifier. The resource name referring to the cached content.\n   * Format: `cachedContents/{id}`\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Immutable. The user-generated meaningful display name of the cached content. Maximum\n   * 128 Unicode characters.\n   */\n  \"displayName\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. Immutable. The name of the `Model` to use for cached content\n   * Format: `models/{model}`\n   */\n  \"model\": S.String,\n  /**\n   * Optional. Input only. Immutable. Developer set system instruction. Currently text only.\n   */\n  \"systemInstruction\": S.optionalWith(Content, { nullable: true }),\n  /**\n   * Optional. Input only. Immutable. The content to cache.\n   */\n  \"contents\": S.optionalWith(S.Array(Content), { nullable: true }),\n  /**\n   * Optional. Input only. Immutable. A list of `Tools` the model may use to generate the next response\n   */\n  \"tools\": S.optionalWith(S.Array(Tool), { nullable: true }),\n  /**\n   * Optional. Input only. Immutable. Tool config. This config is shared for all tools.\n   */\n  \"toolConfig\": S.optionalWith(ToolConfig, { nullable: true }),\n  /**\n   * Output only. Creation time of the cache entry.\n   */\n  \"createTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. When the cache entry was last updated in UTC time.\n   */\n  \"updateTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. Metadata on the usage of the cached content.\n   */\n  \"usageMetadata\": S.optionalWith(CachedContentUsageMetadata, { nullable: true })\n}) {}\n\n/**\n * Response with CachedContents list.\n */\nexport class ListCachedContentsResponse extends S.Class<ListCachedContentsResponse>(\"ListCachedContentsResponse\")({\n  /**\n   * List of cached contents.\n   */\n  \"cachedContents\": S.optionalWith(S.Array(CachedContent), { nullable: true }),\n  /**\n   * A token, which can be sent as `page_token` to retrieve the next page.\n   * If this field is omitted, there are no subsequent pages.\n   */\n  \"nextPageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UpdateCachedContentParams extends S.Struct({\n  \"updateMask\": S.optionalWith(S.String.pipe(S.pattern(new RegExp(\"^(\\\\s*[^,\\\\s.]+(\\\\s*[,.]\\\\s*[^,\\\\s.]+)*)?$\"))), {\n    nullable: true\n  })\n}) {}\n\n/**\n * The base unit of structured text.\n *\n * A `Message` includes an `author` and the `content` of\n * the `Message`.\n *\n * The `author` is used to tag messages when they are fed to the\n * model as text.\n */\nexport class Message extends S.Class<Message>(\"Message\")({\n  /**\n   * Optional. The author of this Message.\n   *\n   * This serves as a key for tagging\n   * the content of this Message when it is fed to the model as text.\n   *\n   * The author can be any alphanumeric string.\n   */\n  \"author\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. The text content of the structured `Message`.\n   */\n  \"content\": S.String,\n  /**\n   * Output only. Citation information for model-generated `content` in this `Message`.\n   *\n   * If this `Message` was generated as output from the model, this field may be\n   * populated with attribution information for any text included in the\n   * `content`. This field is used only on output.\n   */\n  \"citationMetadata\": S.optionalWith(CitationMetadata, { nullable: true })\n}) {}\n\n/**\n * An input/output example used to instruct the Model.\n *\n * It demonstrates how the model should respond or format its response.\n */\nexport class Example extends S.Class<Example>(\"Example\")({\n  /**\n   * Required. An example of an input `Message` from the user.\n   */\n  \"input\": Message,\n  /**\n   * Required. An example of what the model should output given the input.\n   */\n  \"output\": Message\n}) {}\n\n/**\n * All of the structured input text passed to the model as a prompt.\n *\n * A `MessagePrompt` contains a structured set of fields that provide context\n * for the conversation, examples of user input/model output message pairs that\n * prime the model to respond in different ways, and the conversation history\n * or list of messages representing the alternating turns of the conversation\n * between the user and the model.\n */\nexport class MessagePrompt extends S.Class<MessagePrompt>(\"MessagePrompt\")({\n  /**\n   * Optional. Text that should be provided to the model first to ground the response.\n   *\n   * If not empty, this `context` will be given to the model first before the\n   * `examples` and `messages`. When using a `context` be sure to provide it\n   * with every request to maintain continuity.\n   *\n   * This field can be a description of your prompt to the model to help provide\n   * context and guide the responses. Examples: \"Translate the phrase from\n   * English to French.\" or \"Given a statement, classify the sentiment as happy,\n   * sad or neutral.\"\n   *\n   * Anything included in this field will take precedence over message history\n   * if the total input size exceeds the model's `input_token_limit` and the\n   * input request is truncated.\n   */\n  \"context\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Examples of what the model should generate.\n   *\n   * This includes both user input and the response that the model should\n   * emulate.\n   *\n   * These `examples` are treated identically to conversation messages except\n   * that they take precedence over the history in `messages`:\n   * If the total input size exceeds the model's `input_token_limit` the input\n   * will be truncated. Items will be dropped from `messages` before `examples`.\n   */\n  \"examples\": S.optionalWith(S.Array(Example), { nullable: true }),\n  /**\n   * Required. A snapshot of the recent conversation history sorted chronologically.\n   *\n   * Turns alternate between two authors.\n   *\n   * If the total input size exceeds the model's `input_token_limit` the input\n   * will be truncated: The oldest items will be dropped from `messages`.\n   */\n  \"messages\": S.Array(Message)\n}) {}\n\n/**\n * Request to generate a message response from the model.\n */\nexport class GenerateMessageRequest extends S.Class<GenerateMessageRequest>(\"GenerateMessageRequest\")({\n  /**\n   * Required. The structured textual input given to the model as a prompt.\n   *\n   * Given a\n   * prompt, the model will return what it predicts is the next message in the\n   * discussion.\n   */\n  \"prompt\": MessagePrompt,\n  /**\n   * Optional. Controls the randomness of the output.\n   *\n   * Values can range over `[0.0,1.0]`,\n   * inclusive. A value closer to `1.0` will produce responses that are more\n   * varied, while a value closer to `0.0` will typically result in\n   * less surprising responses from the model.\n   */\n  \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. The number of generated response messages to return.\n   *\n   * This value must be between\n   * `[1, 8]`, inclusive. If unset, this will default to `1`.\n   */\n  \"candidateCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. The maximum cumulative probability of tokens to consider when sampling.\n   *\n   * The model uses combined Top-k and nucleus sampling.\n   *\n   * Nucleus sampling considers the smallest set of tokens whose probability\n   * sum is at least `top_p`.\n   */\n  \"topP\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. The maximum number of tokens to consider when sampling.\n   *\n   * The model uses combined Top-k and nucleus sampling.\n   *\n   * Top-k sampling considers the set of `top_k` most probable tokens.\n   */\n  \"topK\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * The reason content was blocked during request processing.\n */\nexport class ContentFilterReason extends S.Literal(\"BLOCKED_REASON_UNSPECIFIED\", \"SAFETY\", \"OTHER\") {}\n\n/**\n * Content filtering metadata associated with processing a single request.\n *\n * ContentFilter contains a reason and an optional supporting string. The reason\n * may be unspecified.\n */\nexport class ContentFilter extends S.Class<ContentFilter>(\"ContentFilter\")({\n  /**\n   * The reason content was blocked during request processing.\n   */\n  \"reason\": S.optionalWith(ContentFilterReason, { nullable: true }),\n  /**\n   * A string that describes the filtering behavior in more detail.\n   */\n  \"message\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The response from the model.\n *\n * This includes candidate messages and\n * conversation history in the form of chronologically-ordered messages.\n */\nexport class GenerateMessageResponse extends S.Class<GenerateMessageResponse>(\"GenerateMessageResponse\")({\n  /**\n   * Candidate response messages from the model.\n   */\n  \"candidates\": S.optionalWith(S.Array(Message), { nullable: true }),\n  /**\n   * The conversation history used by the model.\n   */\n  \"messages\": S.optionalWith(S.Array(Message), { nullable: true }),\n  /**\n   * A set of content filtering metadata for the prompt and response\n   * text.\n   *\n   * This indicates which `SafetyCategory`(s) blocked a\n   * candidate from this response, the lowest `HarmProbability`\n   * that triggered a block, and the HarmThreshold setting for that category.\n   */\n  \"filters\": S.optionalWith(S.Array(ContentFilter), { nullable: true })\n}) {}\n\n/**\n * Counts the number of tokens in the `prompt` sent to a model.\n *\n * Models may tokenize text differently, so each model may return a different\n * `token_count`.\n */\nexport class CountMessageTokensRequest extends S.Class<CountMessageTokensRequest>(\"CountMessageTokensRequest\")({\n  /**\n   * Required. The prompt, whose token count is to be returned.\n   */\n  \"prompt\": MessagePrompt\n}) {}\n\n/**\n * A response from `CountMessageTokens`.\n *\n * It returns the model's `token_count` for the `prompt`.\n */\nexport class CountMessageTokensResponse extends S.Class<CountMessageTokensResponse>(\"CountMessageTokensResponse\")({\n  /**\n   * The number of tokens that the `model` tokenizes the `prompt` into.\n   *\n   * Always non-negative.\n   */\n  \"tokenCount\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\nexport class ListFilesParams extends S.Struct({\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Metadata for a video `File`.\n */\nexport class VideoFileMetadata extends S.Class<VideoFileMetadata>(\"VideoFileMetadata\")({\n  /**\n   * Duration of the video.\n   */\n  \"videoDuration\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Output only. Processing state of the File.\n */\nexport class FileState extends S.Literal(\"STATE_UNSPECIFIED\", \"PROCESSING\", \"ACTIVE\", \"FAILED\") {}\n\n/**\n * Source of the File.\n */\nexport class FileSource extends S.Literal(\"SOURCE_UNSPECIFIED\", \"UPLOADED\", \"GENERATED\", \"REGISTERED\") {}\n\n/**\n * A file uploaded to the API.\n * Next ID: 15\n */\nexport class File extends S.Class<File>(\"File\")({\n  /**\n   * Output only. Metadata for a video.\n   */\n  \"videoMetadata\": S.optionalWith(VideoFileMetadata, { nullable: true }),\n  /**\n   * Immutable. Identifier. The `File` resource name. The ID (name excluding the \"files/\" prefix) can\n   * contain up to 40 characters that are lowercase alphanumeric or dashes (-).\n   * The ID cannot start or end with a dash. If the name is empty on create, a\n   * unique name will be generated.\n   * Example: `files/123-456`\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. The human-readable display name for the `File`. The display name must be\n   * no more than 512 characters in length, including spaces.\n   * Example: \"Welcome Image\"\n   */\n  \"displayName\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. MIME type of the file.\n   */\n  \"mimeType\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. Size of the file in bytes.\n   */\n  \"sizeBytes\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The timestamp of when the `File` was created.\n   */\n  \"createTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The timestamp of when the `File` was last updated.\n   */\n  \"updateTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is\n   * scheduled to expire.\n   */\n  \"expirationTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. SHA-256 hash of the uploaded bytes.\n   */\n  \"sha256Hash\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The uri of the `File`.\n   */\n  \"uri\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The download uri of the `File`.\n   */\n  \"downloadUri\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. Processing state of the File.\n   */\n  \"state\": S.optionalWith(FileState, { nullable: true }),\n  /**\n   * Source of the File.\n   */\n  \"source\": S.optionalWith(FileSource, { nullable: true }),\n  /**\n   * Output only. Error status if File processing failed.\n   */\n  \"error\": S.optionalWith(Status, { nullable: true })\n}) {}\n\n/**\n * Response for `ListFiles`.\n */\nexport class ListFilesResponse extends S.Class<ListFilesResponse>(\"ListFilesResponse\")({\n  /**\n   * The list of `File`s.\n   */\n  \"files\": S.optionalWith(S.Array(File), { nullable: true }),\n  /**\n   * A token that can be sent as a `page_token` into a subsequent `ListFiles`\n   * call.\n   */\n  \"nextPageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Request for `CreateFile`.\n */\nexport class CreateFileRequest extends S.Class<CreateFileRequest>(\"CreateFileRequest\")({\n  /**\n   * Optional. Metadata for the file to create.\n   */\n  \"file\": S.optionalWith(File, { nullable: true })\n}) {}\n\n/**\n * Response for `CreateFile`.\n */\nexport class CreateFileResponse extends S.Class<CreateFileResponse>(\"CreateFileResponse\")({\n  /**\n   * Metadata for the created file.\n   */\n  \"file\": S.optionalWith(File, { nullable: true })\n}) {}\n\n/**\n * Response for `DownloadFile`.\n */\nexport class DownloadFileResponse extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * Output only. The state of the GeneratedFile.\n */\nexport class GeneratedFileState extends S.Literal(\"STATE_UNSPECIFIED\", \"GENERATING\", \"GENERATED\", \"FAILED\") {}\n\n/**\n * A file generated on behalf of a user.\n */\nexport class GeneratedFile extends S.Class<GeneratedFile>(\"GeneratedFile\")({\n  /**\n   * Identifier. The name of the generated file.\n   * Example: `generatedFiles/abc-123`\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * MIME type of the generatedFile.\n   */\n  \"mimeType\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The state of the GeneratedFile.\n   */\n  \"state\": S.optionalWith(GeneratedFileState, { nullable: true }),\n  /**\n   * Error details if the GeneratedFile ends up in the STATE_FAILED state.\n   */\n  \"error\": S.optionalWith(Status, { nullable: true })\n}) {}\n\nexport class ListGeneratedFilesParams extends S.Struct({\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Response for `ListGeneratedFiles`.\n */\nexport class ListGeneratedFilesResponse extends S.Class<ListGeneratedFilesResponse>(\"ListGeneratedFilesResponse\")({\n  /**\n   * The list of `GeneratedFile`s.\n   */\n  \"generatedFiles\": S.optionalWith(S.Array(GeneratedFile), { nullable: true }),\n  /**\n   * A token that can be sent as a `page_token` into a subsequent\n   * `ListGeneratedFiles` call.\n   */\n  \"nextPageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Information about a Generative Language Model.\n */\nexport class Model extends S.Class<Model>(\"Model\")({\n  /**\n   * Required. The resource name of the `Model`. Refer to [Model\n   * variants](https://ai.google.dev/gemini-api/docs/models/gemini#model-variations)\n   * for all allowed values.\n   *\n   * Format: `models/{model}` with a `{model}` naming convention of:\n   *\n   * * \"{base_model_id}-{version}\"\n   *\n   * Examples:\n   *\n   * * `models/gemini-1.5-flash-001`\n   */\n  \"name\": S.String,\n  /**\n   * Required. The name of the base model, pass this to the generation request.\n   *\n   * Examples:\n   *\n   * * `gemini-1.5-flash`\n   */\n  \"baseModelId\": S.String,\n  /**\n   * Required. The version number of the model.\n   *\n   * This represents the major version (`1.0` or `1.5`)\n   */\n  \"version\": S.String,\n  /**\n   * The human-readable name of the model. E.g. \"Gemini 1.5 Flash\".\n   *\n   * The name can be up to 128 characters long and can consist of any UTF-8\n   * characters.\n   */\n  \"displayName\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * A short description of the model.\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Maximum number of input tokens allowed for this model.\n   */\n  \"inputTokenLimit\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Maximum number of output tokens available for this model.\n   */\n  \"outputTokenLimit\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The model's supported generation methods.\n   *\n   * The corresponding API method names are defined as Pascal case\n   * strings, such as `generateMessage` and `generateContent`.\n   */\n  \"supportedGenerationMethods\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Controls the randomness of the output.\n   *\n   * Values can range over `[0.0,max_temperature]`, inclusive. A higher value\n   * will produce responses that are more varied, while a value closer to `0.0`\n   * will typically result in less surprising responses from the model.\n   * This value specifies default to be used by the backend while making the\n   * call to the model.\n   */\n  \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * The maximum temperature this model can use.\n   */\n  \"maxTemperature\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * For [Nucleus\n   * sampling](https://ai.google.dev/gemini-api/docs/prompting-strategies#top-p).\n   *\n   * Nucleus sampling considers the smallest set of tokens whose probability\n   * sum is at least `top_p`.\n   * This value specifies default to be used by the backend while making the\n   * call to the model.\n   */\n  \"topP\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * For Top-k sampling.\n   *\n   * Top-k sampling considers the set of `top_k` most probable tokens.\n   * This value specifies default to be used by the backend while making the\n   * call to the model.\n   * If empty, indicates the model doesn't use top-k sampling, and `top_k` isn't\n   * allowed as a generation parameter.\n   */\n  \"topK\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Whether the model supports thinking.\n   */\n  \"thinking\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class ListModelsParams extends S.Struct({\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Response from `ListModel` containing a paginated list of Models.\n */\nexport class ListModelsResponse extends S.Class<ListModelsResponse>(\"ListModelsResponse\")({\n  /**\n   * The returned Models.\n   */\n  \"models\": S.optionalWith(S.Array(Model), { nullable: true }),\n  /**\n   * A token, which can be sent as `page_token` to retrieve the next page.\n   *\n   * If this field is omitted, there are no more pages.\n   */\n  \"nextPageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Tuned model as a source for training a new model.\n */\nexport class TunedModelSource extends S.Class<TunedModelSource>(\"TunedModelSource\")({\n  /**\n   * Immutable. The name of the `TunedModel` to use as the starting point for\n   * training the new model.\n   * Example: `tunedModels/my-tuned-model`\n   */\n  \"tunedModel\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The name of the base `Model` this `TunedModel` was tuned from.\n   * Example: `models/gemini-1.5-flash-001`\n   */\n  \"baseModel\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Output only. The state of the tuned model.\n */\nexport class TunedModelState extends S.Literal(\"STATE_UNSPECIFIED\", \"CREATING\", \"ACTIVE\", \"FAILED\") {}\n\n/**\n * Record for a single tuning step.\n */\nexport class TuningSnapshot extends S.Class<TuningSnapshot>(\"TuningSnapshot\")({\n  /**\n   * Output only. The tuning step.\n   */\n  \"step\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Output only. The epoch this step was part of.\n   */\n  \"epoch\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Output only. The mean loss of the training examples for this step.\n   */\n  \"meanLoss\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Output only. The timestamp when this metric was computed.\n   */\n  \"computeTime\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A single example for tuning.\n */\nexport class TuningExample extends S.Class<TuningExample>(\"TuningExample\")({\n  /**\n   * Optional. Text model input.\n   */\n  \"textInput\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. The expected model output.\n   */\n  \"output\": S.String\n}) {}\n\n/**\n * A set of tuning examples. Can be training or validation data.\n */\nexport class TuningExamples extends S.Class<TuningExamples>(\"TuningExamples\")({\n  /**\n   * The examples. Example input can be for text or discuss, but all examples\n   * in a set must be of the same type.\n   */\n  \"examples\": S.optionalWith(S.Array(TuningExample), { nullable: true })\n}) {}\n\n/**\n * Dataset for training or validation.\n */\nexport class Dataset extends S.Class<Dataset>(\"Dataset\")({\n  /**\n   * Optional. Inline examples with simple input/output text.\n   */\n  \"examples\": S.optionalWith(TuningExamples, { nullable: true })\n}) {}\n\n/**\n * Hyperparameters controlling the tuning process. Read more at\n * https://ai.google.dev/docs/model_tuning_guidance\n */\nexport class Hyperparameters extends S.Class<Hyperparameters>(\"Hyperparameters\")({\n  /**\n   * Optional. Immutable. The learning rate hyperparameter for tuning.\n   * If not set, a default of 0.001 or 0.0002 will be calculated based on the\n   * number of training examples.\n   */\n  \"learningRate\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. Immutable. The learning rate multiplier is used to calculate a final learning_rate\n   * based on the default (recommended) value.\n   * Actual learning rate := learning_rate_multiplier * default learning rate\n   * Default learning rate is dependent on base model and dataset size.\n   * If not set, a default of 1.0 will be used.\n   */\n  \"learningRateMultiplier\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Immutable. The number of training epochs. An epoch is one pass through the training\n   * data.\n   * If not set, a default of 5 will be used.\n   */\n  \"epochCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Immutable. The batch size hyperparameter for tuning.\n   * If not set, a default of 4 or 16 will be used based on the number of\n   * training examples.\n   */\n  \"batchSize\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * Tuning tasks that create tuned models.\n */\nexport class TuningTask extends S.Class<TuningTask>(\"TuningTask\")({\n  /**\n   * Output only. The timestamp when tuning this model started.\n   */\n  \"startTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The timestamp when tuning this model completed.\n   */\n  \"completeTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. Metrics collected during tuning.\n   */\n  \"snapshots\": S.optionalWith(S.Array(TuningSnapshot), { nullable: true }),\n  /**\n   * Required. Input only. Immutable. The model training data.\n   */\n  \"trainingData\": Dataset,\n  /**\n   * Immutable. Hyperparameters controlling the tuning process. If not provided, default\n   * values will be used.\n   */\n  \"hyperparameters\": S.optionalWith(Hyperparameters, { nullable: true })\n}) {}\n\n/**\n * A fine-tuned model created using ModelService.CreateTunedModel.\n */\nexport class TunedModel extends S.Class<TunedModel>(\"TunedModel\")({\n  /**\n   * Optional. TunedModel to use as the starting point for training the new model.\n   */\n  \"tunedModelSource\": S.optionalWith(TunedModelSource, { nullable: true }),\n  /**\n   * Immutable. The name of the `Model` to tune.\n   * Example: `models/gemini-1.5-flash-001`\n   */\n  \"baseModel\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The tuned model name. A unique name will be generated on create.\n   * Example: `tunedModels/az2mb0bpw6i`\n   * If display_name is set on create, the id portion of the name will be set\n   * by concatenating the words of the display_name with hyphens and adding a\n   * random portion for uniqueness.\n   *\n   * Example:\n   *\n   *  * display_name = `Sentence Translator`\n   *  * name = `tunedModels/sentence-translator-u3b7m`\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. The name to display for this model in user interfaces.\n   * The display name must be up to 40 characters including spaces.\n   */\n  \"displayName\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. A short description of this model.\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Controls the randomness of the output.\n   *\n   * Values can range over `[0.0,1.0]`, inclusive. A value closer to `1.0` will\n   * produce responses that are more varied, while a value closer to `0.0` will\n   * typically result in less surprising responses from the model.\n   *\n   * This value specifies default to be the one used by the base model while\n   * creating the model.\n   */\n  \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. For Nucleus sampling.\n   *\n   * Nucleus sampling considers the smallest set of tokens whose probability\n   * sum is at least `top_p`.\n   *\n   * This value specifies default to be the one used by the base model while\n   * creating the model.\n   */\n  \"topP\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. For Top-k sampling.\n   *\n   * Top-k sampling considers the set of `top_k` most probable tokens.\n   * This value specifies default to be used by the backend while making the\n   * call to the model.\n   *\n   * This value specifies default to be the one used by the base model while\n   * creating the model.\n   */\n  \"topK\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Output only. The state of the tuned model.\n   */\n  \"state\": S.optionalWith(TunedModelState, { nullable: true }),\n  /**\n   * Output only. The timestamp when this model was created.\n   */\n  \"createTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The timestamp when this model was updated.\n   */\n  \"updateTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. The tuning task that creates the tuned model.\n   */\n  \"tuningTask\": TuningTask,\n  /**\n   * Optional. List of project numbers that have read access to the tuned model.\n   */\n  \"readerProjectNumbers\": S.optionalWith(S.Array(S.String), { nullable: true })\n}) {}\n\nexport class UpdateTunedModelParams extends S.Struct({\n  \"updateMask\": S.optionalWith(S.String.pipe(S.pattern(new RegExp(\"^(\\\\s*[^,\\\\s.]+(\\\\s*[,.]\\\\s*[^,\\\\s.]+)*)?$\"))), {\n    nullable: true\n  })\n}) {}\n\nexport class ListTunedModelsParams extends S.Struct({\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true }),\n  \"filter\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Response from `ListTunedModels` containing a paginated list of Models.\n */\nexport class ListTunedModelsResponse extends S.Class<ListTunedModelsResponse>(\"ListTunedModelsResponse\")({\n  /**\n   * The returned Models.\n   */\n  \"tunedModels\": S.optionalWith(S.Array(TunedModel), { nullable: true }),\n  /**\n   * A token, which can be sent as `page_token` to retrieve the next page.\n   *\n   * If this field is omitted, there are no more pages.\n   */\n  \"nextPageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class CreateTunedModelParams extends S.Struct({\n  \"tunedModelId\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Metadata about the state and progress of creating a tuned model returned from\n * the long-running operation\n */\nexport class CreateTunedModelMetadata extends S.Class<CreateTunedModelMetadata>(\"CreateTunedModelMetadata\")({\n  /**\n   * Name of the tuned model associated with the tuning operation.\n   */\n  \"tunedModel\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The total number of tuning steps.\n   */\n  \"totalSteps\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The number of steps completed.\n   */\n  \"completedSteps\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The completed percentage for the tuning operation.\n   */\n  \"completedPercent\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Metrics collected during tuning.\n   */\n  \"snapshots\": S.optionalWith(S.Array(TuningSnapshot), { nullable: true })\n}) {}\n\n/**\n * This resource represents a long-running operation that is the result of a\n * network API call.\n */\nexport class CreateTunedModelOperation extends S.Class<CreateTunedModelOperation>(\"CreateTunedModelOperation\")({\n  \"metadata\": S.optionalWith(CreateTunedModelMetadata, { nullable: true }),\n  \"response\": S.optionalWith(TunedModel, { nullable: true }),\n  /**\n   * The server-assigned name, which is only unique within the same service that\n   * originally returns it. If you use the default HTTP mapping, the\n   * `name` should be a resource name ending with `operations/{unique_id}`.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * If the value is `false`, it means the operation is still in progress.\n   * If `true`, the operation is completed, and either `error` or `response` is\n   * available.\n   */\n  \"done\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * The error result of the operation in case of failure or cancellation.\n   */\n  \"error\": S.optionalWith(Status, { nullable: true })\n}) {}\n\nexport class ListPermissionsParams extends S.Struct({\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Optional. Immutable. The type of the grantee.\n */\nexport class PermissionGranteeType extends S.Literal(\"GRANTEE_TYPE_UNSPECIFIED\", \"USER\", \"GROUP\", \"EVERYONE\") {}\n\n/**\n * Required. The role granted by this permission.\n */\nexport class PermissionRole extends S.Literal(\"ROLE_UNSPECIFIED\", \"OWNER\", \"WRITER\", \"READER\") {}\n\n/**\n * Permission resource grants user, group or the rest of the world access to the\n * PaLM API resource (e.g. a tuned model, corpus).\n *\n * A role is a collection of permitted operations that allows users to perform\n * specific actions on PaLM API resources. To make them available to users,\n * groups, or service accounts, you assign roles. When you assign a role, you\n * grant permissions that the role contains.\n *\n * There are three concentric roles. Each role is a superset of the previous\n * role's permitted operations:\n *\n * - reader can use the resource (e.g. tuned model, corpus) for inference\n * - writer has reader's permissions and additionally can edit and share\n * - owner has writer's permissions and additionally can delete\n */\nexport class Permission extends S.Class<Permission>(\"Permission\")({\n  /**\n   * Output only. Identifier. The permission name. A unique name will be generated on create.\n   * Examples:\n   *     tunedModels/{tuned_model}/permissions/{permission}\n   *     corpora/{corpus}/permissions/{permission}\n   * Output only.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. Immutable. The type of the grantee.\n   */\n  \"granteeType\": S.optionalWith(PermissionGranteeType, { nullable: true }),\n  /**\n   * Optional. Immutable. The email address of the user of group which this permission refers.\n   * Field is not set when permission's grantee type is EVERYONE.\n   */\n  \"emailAddress\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Required. The role granted by this permission.\n   */\n  \"role\": PermissionRole\n}) {}\n\n/**\n * Response from `ListPermissions` containing a paginated list of\n * permissions.\n */\nexport class ListPermissionsResponse extends S.Class<ListPermissionsResponse>(\"ListPermissionsResponse\")({\n  /**\n   * Returned permissions.\n   */\n  \"permissions\": S.optionalWith(S.Array(Permission), { nullable: true }),\n  /**\n   * A token, which can be sent as `page_token` to retrieve the next page.\n   *\n   * If this field is omitted, there are no more pages.\n   */\n  \"nextPageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListPermissionsByCorpusParams extends S.Struct({\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UpdatePermissionParams extends S.Struct({\n  \"updateMask\": S.String.pipe(S.pattern(new RegExp(\"^(\\\\s*[^,\\\\s.]+(\\\\s*[,.]\\\\s*[^,\\\\s.]+)*)?$\")))\n}) {}\n\nexport class UpdatePermissionByCorpusAndPermissionParams extends S.Struct({\n  \"updateMask\": S.String.pipe(S.pattern(new RegExp(\"^(\\\\s*[^,\\\\s.]+(\\\\s*[,.]\\\\s*[^,\\\\s.]+)*)?$\")))\n}) {}\n\n/**\n * Request to transfer the ownership of the tuned model.\n */\nexport class TransferOwnershipRequest extends S.Class<TransferOwnershipRequest>(\"TransferOwnershipRequest\")({\n  /**\n   * Required. The email address of the user to whom the tuned model is being transferred\n   * to.\n   */\n  \"emailAddress\": S.String\n}) {}\n\n/**\n * Response from `TransferOwnership`.\n */\nexport class TransferOwnershipResponse extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * Request message for PredictionService.Predict.\n */\nexport class PredictRequest extends S.Class<PredictRequest>(\"PredictRequest\")({}) {}\n\n/**\n * Response message for [PredictionService.Predict].\n */\nexport class PredictResponse extends S.Class<PredictResponse>(\"PredictResponse\")({}) {}\n\n/**\n * Request message for [PredictionService.PredictLongRunning].\n */\nexport class PredictLongRunningRequest extends S.Class<PredictLongRunningRequest>(\"PredictLongRunningRequest\")({}) {}\n\n/**\n * Metadata for PredictLongRunning long running operations.\n */\nexport class PredictLongRunningMetadata extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * Representation of a video.\n */\nexport class Video extends S.Class<Video>(\"Video\")({\n  /**\n   * Raw bytes.\n   */\n  \"video\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Path to another storage.\n   */\n  \"uri\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A proto encapsulate various type of media.\n */\nexport class Media extends S.Class<Media>(\"Media\")({\n  /**\n   * Video as the only one for now.  This is mimicking Vertex proto.\n   */\n  \"video\": S.optionalWith(Video, { nullable: true })\n}) {}\n\n/**\n * Veo response.\n */\nexport class PredictLongRunningGeneratedVideoResponse\n  extends S.Class<PredictLongRunningGeneratedVideoResponse>(\"PredictLongRunningGeneratedVideoResponse\")({\n    /**\n     * The generated samples.\n     */\n    \"generatedSamples\": S.optionalWith(S.Array(Media), { nullable: true }),\n    /**\n     * Returns if any videos were filtered due to RAI policies.\n     */\n    \"raiMediaFilteredCount\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * Returns rai failure reasons if any.\n     */\n    \"raiMediaFilteredReasons\": S.optionalWith(S.Array(S.String), { nullable: true })\n  })\n{}\n\n/**\n * Response message for [PredictionService.PredictLongRunning]\n */\nexport class PredictLongRunningResponse extends S.Class<PredictLongRunningResponse>(\"PredictLongRunningResponse\")({\n  /**\n   * The response of the video generation prediction.\n   */\n  \"generateVideoResponse\": S.optionalWith(PredictLongRunningGeneratedVideoResponse, { nullable: true })\n}) {}\n\n/**\n * This resource represents a long-running operation that is the result of a\n * network API call.\n */\nexport class PredictLongRunningOperation extends S.Class<PredictLongRunningOperation>(\"PredictLongRunningOperation\")({\n  \"metadata\": S.optionalWith(PredictLongRunningMetadata, { nullable: true }),\n  \"response\": S.optionalWith(PredictLongRunningResponse, { nullable: true }),\n  /**\n   * The server-assigned name, which is only unique within the same service that\n   * originally returns it. If you use the default HTTP mapping, the\n   * `name` should be a resource name ending with `operations/{unique_id}`.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * If the value is `false`, it means the operation is still in progress.\n   * If `true`, the operation is completed, and either `error` or `response` is\n   * available.\n   */\n  \"done\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * The error result of the operation in case of failure or cancellation.\n   */\n  \"error\": S.optionalWith(Status, { nullable: true })\n}) {}\n\nexport class ListFileSearchStoresParams extends S.Struct({\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A `FileSearchStore` is a collection of `Document`s.\n */\nexport class FileSearchStore extends S.Class<FileSearchStore>(\"FileSearchStore\")({\n  /**\n   * Output only. Immutable. Identifier. The `FileSearchStore` resource name. It is an ID (name excluding the\n   * \"fileSearchStores/\" prefix) that can contain up to 40 characters that are\n   * lowercase alphanumeric or dashes\n   * (-). It is output only. The unique name will be derived from\n   * `display_name` along with a 12 character random suffix. Example:\n   * `fileSearchStores/my-awesome-file-search-store-123a456b789c`\n   * If `display_name` is not provided, the name will be randomly generated.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. The human-readable display name for the `FileSearchStore`. The display name\n   * must be no more than 512 characters in length, including spaces. Example:\n   * \"Docs on Semantic Retriever\"\n   */\n  \"displayName\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The Timestamp of when the `FileSearchStore` was created.\n   */\n  \"createTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The Timestamp of when the `FileSearchStore` was last updated.\n   */\n  \"updateTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The number of documents in the `FileSearchStore` that are active and ready\n   * for retrieval.\n   */\n  \"activeDocumentsCount\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The number of documents in the `FileSearchStore` that are being processed.\n   */\n  \"pendingDocumentsCount\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The number of documents in the `FileSearchStore` that have failed\n   * processing.\n   */\n  \"failedDocumentsCount\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The size of raw bytes ingested into the `FileSearchStore`. This is the\n   * total size of all the documents in the `FileSearchStore`.\n   */\n  \"sizeBytes\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Response from `ListFileSearchStores` containing a paginated list of\n * `FileSearchStores`. The results are sorted by ascending\n * `file_search_store.create_time`.\n */\nexport class ListFileSearchStoresResponse\n  extends S.Class<ListFileSearchStoresResponse>(\"ListFileSearchStoresResponse\")({\n    /**\n     * The returned rag_stores.\n     */\n    \"fileSearchStores\": S.optionalWith(S.Array(FileSearchStore), { nullable: true }),\n    /**\n     * A token, which can be sent as `page_token` to retrieve the next page.\n     * If this field is omitted, there are no more pages.\n     */\n    \"nextPageToken\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\nexport class ListCorporaParams extends S.Struct({\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A `Corpus` is a collection of `Document`s.\n * A project can create up to 10 corpora.\n */\nexport class Corpus extends S.Class<Corpus>(\"Corpus\")({\n  /**\n   * Output only. Immutable. Identifier. The `Corpus` resource name. The ID (name excluding the \"corpora/\" prefix)\n   * can contain up to 40 characters that are lowercase alphanumeric or dashes\n   * (-). The ID cannot start or end with a dash. If the name is empty on\n   * create, a unique name will be derived from `display_name` along with a 12\n   * character random suffix.\n   * Example: `corpora/my-awesome-corpora-123a456b789c`\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. The human-readable display name for the `Corpus`. The display name must be\n   * no more than 512 characters in length, including spaces.\n   * Example: \"Docs on Semantic Retriever\"\n   */\n  \"displayName\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The Timestamp of when the `Corpus` was created.\n   */\n  \"createTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The Timestamp of when the `Corpus` was last updated.\n   */\n  \"updateTime\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Response from `ListCorpora` containing a paginated list of `Corpora`.\n * The results are sorted by ascending `corpus.create_time`.\n */\nexport class ListCorporaResponse extends S.Class<ListCorporaResponse>(\"ListCorporaResponse\")({\n  /**\n   * The returned corpora.\n   */\n  \"corpora\": S.optionalWith(S.Array(Corpus), { nullable: true }),\n  /**\n   * A token, which can be sent as `page_token` to retrieve the next page.\n   * If this field is omitted, there are no more pages.\n   */\n  \"nextPageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class DeleteFileSearchStoreParams extends S.Struct({\n  \"force\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class DeleteCorpusParams extends S.Struct({\n  \"force\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * User provided string values assigned to a single metadata key.\n */\nexport class StringList extends S.Class<StringList>(\"StringList\")({\n  /**\n   * The string values of the metadata to store.\n   */\n  \"values\": S.optionalWith(S.Array(S.String), { nullable: true })\n}) {}\n\n/**\n * User provided metadata stored as key-value pairs.\n */\nexport class CustomMetadata extends S.Class<CustomMetadata>(\"CustomMetadata\")({\n  /**\n   * The string value of the metadata to store.\n   */\n  \"stringValue\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The StringList value of the metadata to store.\n   */\n  \"stringListValue\": S.optionalWith(StringList, { nullable: true }),\n  /**\n   * The numeric value of the metadata to store.\n   */\n  \"numericValue\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Required. The key of the metadata to store.\n   */\n  \"key\": S.String\n}) {}\n\n/**\n * Output only. Current state of the `Document`.\n */\nexport class DocumentState extends S.Literal(\"STATE_UNSPECIFIED\", \"STATE_PENDING\", \"STATE_ACTIVE\", \"STATE_FAILED\") {}\n\n/**\n * A `Document` is a collection of `Chunk`s.\n */\nexport class Document extends S.Class<Document>(\"Document\")({\n  /**\n   * Immutable. Identifier. The `Document` resource name. The ID (name excluding the\n   * \"fileSearchStores/ * /documents/\" prefix) can contain up to 40 characters\n   * that are lowercase alphanumeric or dashes (-). The ID cannot start or end\n   * with a dash. If the name is empty on create, a unique name will be derived\n   * from `display_name` along with a 12 character random suffix. Example:\n   * `fileSearchStores/{file_search_store_id}/documents/my-awesome-doc-123a456b789c`\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. The human-readable display name for the `Document`. The display name must\n   * be no more than 512 characters in length, including spaces.\n   * Example: \"Semantic Retriever Documentation\"\n   */\n  \"displayName\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional. User provided custom metadata stored as key-value pairs used for querying.\n   * A `Document` can have a maximum of 20 `CustomMetadata`.\n   */\n  \"customMetadata\": S.optionalWith(S.Array(CustomMetadata), { nullable: true }),\n  /**\n   * Output only. The Timestamp of when the `Document` was last updated.\n   */\n  \"updateTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The Timestamp of when the `Document` was created.\n   */\n  \"createTime\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. Current state of the `Document`.\n   */\n  \"state\": S.optionalWith(DocumentState, { nullable: true }),\n  /**\n   * Output only. The size of raw bytes ingested into the Document.\n   */\n  \"sizeBytes\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Output only. The mime type of the Document.\n   */\n  \"mimeType\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class DeleteDocumentParams extends S.Struct({\n  \"force\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class ListDocumentsParams extends S.Struct({\n  \"pageSize\": S.optionalWith(S.Int, { nullable: true }),\n  \"pageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Response from `ListDocuments` containing a paginated list of `Document`s.\n * The `Document`s are sorted by ascending `document.create_time`.\n */\nexport class ListDocumentsResponse extends S.Class<ListDocumentsResponse>(\"ListDocumentsResponse\")({\n  /**\n   * The returned `Document`s.\n   */\n  \"documents\": S.optionalWith(S.Array(Document), { nullable: true }),\n  /**\n   * A token, which can be sent as `page_token` to retrieve the next page.\n   * If this field is omitted, there are no more pages.\n   */\n  \"nextPageToken\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Configuration for a white space chunking algorithm [white space delimited].\n */\nexport class WhiteSpaceConfig extends S.Class<WhiteSpaceConfig>(\"WhiteSpaceConfig\")({\n  /**\n   * Maximum number of tokens per chunk.\n   * Tokens are defined as words for this chunking algorithm.\n   * Note: we are defining tokens as words split by whitespace as opposed to\n   * the output of a tokenizer. The context window of the latest gemini\n   * embedding model as of 2025-04-17 is currently 8192 tokens. We assume that\n   * the average word is 5 characters. Therefore, we set the upper limit to\n   * 2**9, which is 512 words, or 2560 tokens, assuming worst case a\n   * character per token. This is a conservative estimate meant to prevent\n   * context window overflow.\n   */\n  \"maxTokensPerChunk\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Maximum number of overlapping tokens between two adjacent chunks.\n   */\n  \"maxOverlapTokens\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * Parameters for telling the service how to chunk the file.\n * inspired by\n * google3/cloud/ai/platform/extension/lib/retrieval/config/chunker_config.proto\n */\nexport class ChunkingConfig extends S.Class<ChunkingConfig>(\"ChunkingConfig\")({\n  /**\n   * White space chunking configuration.\n   */\n  \"whiteSpaceConfig\": S.optionalWith(WhiteSpaceConfig, { nullable: true })\n}) {}\n\n/**\n * Request for `ImportFile` to import a File API file with a `FileSearchStore`.\n * LINT.IfChange(ImportFileRequest)\n */\nexport class ImportFileRequest extends S.Class<ImportFileRequest>(\"ImportFileRequest\")({\n  /**\n   * Required. The name of the `File` to import.\n   * Example: `files/abc-123`\n   */\n  \"fileName\": S.String,\n  /**\n   * Custom metadata to be associated with the file.\n   */\n  \"customMetadata\": S.optionalWith(S.Array(CustomMetadata), { nullable: true }),\n  /**\n   * Optional. Config for telling the service how to chunk the file.\n   * If not provided, the service will use default parameters.\n   */\n  \"chunkingConfig\": S.optionalWith(ChunkingConfig, { nullable: true })\n}) {}\n\n/**\n * Metadata for LongRunning ImportFile Operations.\n */\nexport class ImportFileMetadata extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * Response for `ImportFile` to import a File API file with a `FileSearchStore`.\n */\nexport class ImportFileResponse extends S.Class<ImportFileResponse>(\"ImportFileResponse\")({\n  /**\n   * The name of the `FileSearchStore` containing `Document`s.\n   * Example: `fileSearchStores/my-file-search-store-123`\n   */\n  \"parent\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Immutable. Identifier. The identifier for the `Document` imported.\n   * Example:\n   * `fileSearchStores/my-file-search-store-123/documents/my-awesome-doc-123a456b789c`\n   */\n  \"documentName\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * This resource represents a long-running operation that is the result of a\n * network API call.\n */\nexport class ImportFileOperation extends S.Class<ImportFileOperation>(\"ImportFileOperation\")({\n  \"metadata\": S.optionalWith(ImportFileMetadata, { nullable: true }),\n  \"response\": S.optionalWith(ImportFileResponse, { nullable: true }),\n  /**\n   * The server-assigned name, which is only unique within the same service that\n   * originally returns it. If you use the default HTTP mapping, the\n   * `name` should be a resource name ending with `operations/{unique_id}`.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * If the value is `false`, it means the operation is still in progress.\n   * If `true`, the operation is completed, and either `error` or `response` is\n   * available.\n   */\n  \"done\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * The error result of the operation in case of failure or cancellation.\n   */\n  \"error\": S.optionalWith(Status, { nullable: true })\n}) {}\n\n/**\n * Request for `UploadToFileSearchStore`.\n */\nexport class UploadToFileSearchStoreRequest\n  extends S.Class<UploadToFileSearchStoreRequest>(\"UploadToFileSearchStoreRequest\")({\n    /**\n     * Optional. Display name of the created document.\n     */\n    \"displayName\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Custom metadata to be associated with the data.\n     */\n    \"customMetadata\": S.optionalWith(S.Array(CustomMetadata), { nullable: true }),\n    /**\n     * Optional. Config for telling the service how to chunk the data.\n     * If not provided, the service will use default parameters.\n     */\n    \"chunkingConfig\": S.optionalWith(ChunkingConfig, { nullable: true }),\n    /**\n     * Optional. MIME type of the data. If not provided, it will be inferred from the\n     * uploaded content.\n     */\n    \"mimeType\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * Metadata for LongRunning UploadToFileSearchStore Operations.\n */\nexport class UploadToFileSearchStoreMetadata extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * Response from UploadToFileSearchStore.\n */\nexport class UploadToFileSearchStoreResponse\n  extends S.Class<UploadToFileSearchStoreResponse>(\"UploadToFileSearchStoreResponse\")({\n    /**\n     * The name of the `FileSearchStore` containing `Document`s.\n     * Example: `fileSearchStores/my-file-search-store-123`\n     */\n    \"parent\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Immutable. Identifier. The identifier for the `Document` imported.\n     * Example: `fileSearchStores/my-file-search-store-123a456b789c`\n     */\n    \"documentName\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * MIME type of the file.\n     */\n    \"mimeType\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Size of the file in bytes.\n     */\n    \"sizeBytes\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * This resource represents a long-running operation that is the result of a\n * network API call.\n */\nexport class UploadToFileSearchStoreOperation\n  extends S.Class<UploadToFileSearchStoreOperation>(\"UploadToFileSearchStoreOperation\")({\n    \"metadata\": S.optionalWith(UploadToFileSearchStoreMetadata, { nullable: true }),\n    \"response\": S.optionalWith(UploadToFileSearchStoreResponse, { nullable: true }),\n    /**\n     * The server-assigned name, which is only unique within the same service that\n     * originally returns it. If you use the default HTTP mapping, the\n     * `name` should be a resource name ending with `operations/{unique_id}`.\n     */\n    \"name\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * If the value is `false`, it means the operation is still in progress.\n     * If `true`, the operation is completed, and either `error` or `response` is\n     * available.\n     */\n    \"done\": S.optionalWith(S.Boolean, { nullable: true }),\n    /**\n     * The error result of the operation in case of failure or cancellation.\n     */\n    \"error\": S.optionalWith(Status, { nullable: true })\n  })\n{}\n\n/**\n * Text given to the model as a prompt.\n *\n * The Model will use this TextPrompt to Generate a text completion.\n */\nexport class TextPrompt extends S.Class<TextPrompt>(\"TextPrompt\")({\n  /**\n   * Required. The prompt text.\n   */\n  \"text\": S.String\n}) {}\n\n/**\n * Request to generate a text completion response from the model.\n */\nexport class GenerateTextRequest extends S.Class<GenerateTextRequest>(\"GenerateTextRequest\")({\n  /**\n   * Required. The free-form input text given to the model as a prompt.\n   *\n   * Given a prompt, the model will generate a TextCompletion response it\n   * predicts as the completion of the input text.\n   */\n  \"prompt\": TextPrompt,\n  /**\n   * Optional. Controls the randomness of the output.\n   * Note: The default value varies by model, see the `Model.temperature`\n   * attribute of the `Model` returned the `getModel` function.\n   *\n   * Values can range from [0.0,1.0],\n   * inclusive. A value closer to 1.0 will produce responses that are more\n   * varied and creative, while a value closer to 0.0 will typically result in\n   * more straightforward responses from the model.\n   */\n  \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. Number of generated responses to return.\n   *\n   * This value must be between [1, 8], inclusive. If unset, this will default\n   * to 1.\n   */\n  \"candidateCount\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. The maximum number of tokens to include in a candidate.\n   *\n   * If unset, this will default to output_token_limit specified in the `Model`\n   * specification.\n   */\n  \"maxOutputTokens\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. The maximum cumulative probability of tokens to consider when sampling.\n   *\n   * The model uses combined Top-k and nucleus sampling.\n   *\n   * Tokens are sorted based on their assigned probabilities so that only the\n   * most likely tokens are considered. Top-k sampling directly limits the\n   * maximum number of tokens to consider, while Nucleus sampling limits number\n   * of tokens based on the cumulative probability.\n   *\n   * Note: The default value varies by model, see the `Model.top_p`\n   * attribute of the `Model` returned the `getModel` function.\n   */\n  \"topP\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional. The maximum number of tokens to consider when sampling.\n   *\n   * The model uses combined Top-k and nucleus sampling.\n   *\n   * Top-k sampling considers the set of `top_k` most probable tokens.\n   * Defaults to 40.\n   *\n   * Note: The default value varies by model, see the `Model.top_k`\n   * attribute of the `Model` returned the `getModel` function.\n   */\n  \"topK\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Optional. A list of unique `SafetySetting` instances for blocking unsafe content.\n   *\n   * that will be enforced on the `GenerateTextRequest.prompt` and\n   * `GenerateTextResponse.candidates`. There should not be more than one\n   * setting for each `SafetyCategory` type. The API will block any prompts and\n   * responses that fail to meet the thresholds set by these settings. This list\n   * overrides the default settings for each `SafetyCategory` specified in the\n   * safety_settings. If there is no `SafetySetting` for a given\n   * `SafetyCategory` provided in the list, the API will use the default safety\n   * setting for that category. Harm categories HARM_CATEGORY_DEROGATORY,\n   * HARM_CATEGORY_TOXICITY, HARM_CATEGORY_VIOLENCE, HARM_CATEGORY_SEXUAL,\n   * HARM_CATEGORY_MEDICAL, HARM_CATEGORY_DANGEROUS are supported in text\n   * service.\n   */\n  \"safetySettings\": S.optionalWith(S.Array(SafetySetting), { nullable: true }),\n  /**\n   * The set of character sequences (up to 5) that will stop output generation.\n   * If specified, the API will stop at the first appearance of a stop\n   * sequence. The stop sequence will not be included as part of the response.\n   */\n  \"stopSequences\": S.optionalWith(S.Array(S.String), { nullable: true })\n}) {}\n\n/**\n * Output text returned from a model.\n */\nexport class TextCompletion extends S.Class<TextCompletion>(\"TextCompletion\")({\n  /**\n   * Output only. The generated text returned from the model.\n   */\n  \"output\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Ratings for the safety of a response.\n   *\n   * There is at most one rating per category.\n   */\n  \"safetyRatings\": S.optionalWith(S.Array(SafetyRating), { nullable: true }),\n  /**\n   * Output only. Citation information for model-generated `output` in this\n   * `TextCompletion`.\n   *\n   * This field may be populated with attribution information for any text\n   * included in the `output`.\n   */\n  \"citationMetadata\": S.optionalWith(CitationMetadata, { nullable: true })\n}) {}\n\n/**\n * Safety feedback for an entire request.\n *\n * This field is populated if content in the input and/or response is blocked\n * due to safety settings. SafetyFeedback may not exist for every HarmCategory.\n * Each SafetyFeedback will return the safety settings used by the request as\n * well as the lowest HarmProbability that should be allowed in order to return\n * a result.\n */\nexport class SafetyFeedback extends S.Class<SafetyFeedback>(\"SafetyFeedback\")({\n  /**\n   * Safety rating evaluated from content.\n   */\n  \"rating\": S.optionalWith(SafetyRating, { nullable: true }),\n  /**\n   * Safety settings applied to the request.\n   */\n  \"setting\": S.optionalWith(SafetySetting, { nullable: true })\n}) {}\n\n/**\n * The response from the model, including candidate completions.\n */\nexport class GenerateTextResponse extends S.Class<GenerateTextResponse>(\"GenerateTextResponse\")({\n  /**\n   * Candidate responses from the model.\n   */\n  \"candidates\": S.optionalWith(S.Array(TextCompletion), { nullable: true }),\n  /**\n   * A set of content filtering metadata for the prompt and response\n   * text.\n   *\n   * This indicates which `SafetyCategory`(s) blocked a\n   * candidate from this response, the lowest `HarmProbability`\n   * that triggered a block, and the HarmThreshold setting for that category.\n   * This indicates the smallest change to the `SafetySettings` that would be\n   * necessary to unblock at least 1 response.\n   *\n   * The blocking is configured by the `SafetySettings` in the request (or the\n   * default `SafetySettings` of the API).\n   */\n  \"filters\": S.optionalWith(S.Array(ContentFilter), { nullable: true }),\n  /**\n   * Returns any safety feedback related to content filtering.\n   */\n  \"safetyFeedback\": S.optionalWith(S.Array(SafetyFeedback), { nullable: true })\n}) {}\n\n/**\n * Request to get a text embedding from the model.\n */\nexport class EmbedTextRequest extends S.Class<EmbedTextRequest>(\"EmbedTextRequest\")({\n  /**\n   * Required. The model name to use with the format model=models/{model}.\n   */\n  \"model\": S.String,\n  /**\n   * Optional. The free-form input text that the model will turn into an embedding.\n   */\n  \"text\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A list of floats representing the embedding.\n */\nexport class Embedding extends S.Class<Embedding>(\"Embedding\")({\n  /**\n   * The embedding values.\n   */\n  \"value\": S.optionalWith(S.Array(S.Number), { nullable: true })\n}) {}\n\n/**\n * The response to a EmbedTextRequest.\n */\nexport class EmbedTextResponse extends S.Class<EmbedTextResponse>(\"EmbedTextResponse\")({\n  /**\n   * Output only. The embedding generated from the input text.\n   */\n  \"embedding\": S.optionalWith(Embedding, { nullable: true })\n}) {}\n\n/**\n * Batch request to get a text embedding from the model.\n */\nexport class BatchEmbedTextRequest extends S.Class<BatchEmbedTextRequest>(\"BatchEmbedTextRequest\")({\n  /**\n   * Optional. The free-form input texts that the model will turn into an embedding. The\n   * current limit is 100 texts, over which an error will be thrown.\n   */\n  \"texts\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Optional. Embed requests for the batch. Only one of `texts` or `requests` can be set.\n   */\n  \"requests\": S.optionalWith(S.Array(EmbedTextRequest), { nullable: true })\n}) {}\n\n/**\n * The response to a EmbedTextRequest.\n */\nexport class BatchEmbedTextResponse extends S.Class<BatchEmbedTextResponse>(\"BatchEmbedTextResponse\")({\n  /**\n   * Output only. The embeddings generated from the input text.\n   */\n  \"embeddings\": S.optionalWith(S.Array(Embedding), { nullable: true })\n}) {}\n\n/**\n * Counts the number of tokens in the `prompt` sent to a model.\n *\n * Models may tokenize text differently, so each model may return a different\n * `token_count`.\n */\nexport class CountTextTokensRequest extends S.Class<CountTextTokensRequest>(\"CountTextTokensRequest\")({\n  /**\n   * Required. The free-form input text given to the model as a prompt.\n   */\n  \"prompt\": TextPrompt\n}) {}\n\n/**\n * A response from `CountTextTokens`.\n *\n * It returns the model's `token_count` for the `prompt`.\n */\nexport class CountTextTokensResponse extends S.Class<CountTextTokensResponse>(\"CountTextTokensResponse\")({\n  /**\n   * The number of tokens that the `model` tokenizes the `prompt` into.\n   *\n   * Always non-negative.\n   */\n  \"tokenCount\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\nexport const make = (\n  httpClient: HttpClient.HttpClient,\n  options: {\n    readonly transformClient?: ((client: HttpClient.HttpClient) => Effect.Effect<HttpClient.HttpClient>) | undefined\n  } = {}\n): Client => {\n  const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) =>\n    Effect.flatMap(\n      Effect.orElseSucceed(response.json, () => \"Unexpected status code\"),\n      (description) =>\n        Effect.fail(\n          new HttpClientError.ResponseError({\n            request: response.request,\n            response,\n            reason: \"StatusCode\",\n            description: typeof description === \"string\" ? description : JSON.stringify(description)\n          })\n        )\n    )\n  const withResponse: <A, E>(\n    f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E>\n  ) => (\n    request: HttpClientRequest.HttpClientRequest\n  ) => Effect.Effect<any, any> = options.transformClient\n    ? (f) => (request) =>\n      Effect.flatMap(\n        Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)),\n        f\n      )\n    : (f) => (request) => Effect.flatMap(httpClient.execute(request), f)\n  const decodeSuccess = <A, I, R>(schema: S.Schema<A, I, R>) => (response: HttpClientResponse.HttpClientResponse) =>\n    HttpClientResponse.schemaBodyJson(schema)(response)\n  // @ts-expect-error\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  const decodeError =\n    <const Tag extends string, A, I, R>(tag: Tag, schema: S.Schema<A, I, R>) =>\n    (response: HttpClientResponse.HttpClientResponse) =>\n      Effect.flatMap(\n        HttpClientResponse.schemaBodyJson(schema)(response),\n        (cause) => Effect.fail(ClientError(tag, cause, response))\n      )\n  return {\n    httpClient,\n    \"ListOperations\": (tunedModel, options) =>\n      HttpClientRequest.get(`/v1beta/tunedModels/${tunedModel}/operations`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"filter\": options?.[\"filter\"] as any,\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any,\n          \"returnPartialSuccess\": options?.[\"returnPartialSuccess\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListOperationsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListOperationsBy\": (options) =>\n      HttpClientRequest.get(`/v1beta/batches`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"filter\": options?.[\"filter\"] as any,\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any,\n          \"returnPartialSuccess\": options?.[\"returnPartialSuccess\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListOperationsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListOperationsByModel\": (model, options) =>\n      HttpClientRequest.get(`/v1beta/models/${model}/operations`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"filter\": options?.[\"filter\"] as any,\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any,\n          \"returnPartialSuccess\": options?.[\"returnPartialSuccess\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListOperationsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetOperation\": (tunedModel, operation) =>\n      HttpClientRequest.get(`/v1beta/tunedModels/${tunedModel}/operations/${operation}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Operation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetOperationByGeneratedFileAndOperation\": (generatedFile, operation) =>\n      HttpClientRequest.get(`/v1beta/generatedFiles/${generatedFile}/operations/${operation}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Operation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetOperationByGenerateContentBatch\": (generateContentBatch) =>\n      HttpClientRequest.get(`/v1beta/batches/${generateContentBatch}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Operation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteOperation\": (generateContentBatch) =>\n      HttpClientRequest.del(`/v1beta/batches/${generateContentBatch}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Empty),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetOperationByModelAndOperation\": (model, operation) =>\n      HttpClientRequest.get(`/v1beta/models/${model}/operations/${operation}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Operation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetOperationByCorpusAndOperation\": (corpus, operation) =>\n      HttpClientRequest.get(`/v1beta/corpora/${corpus}/operations/${operation}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Operation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetOperationByFileSearchStoreAndOperation\": (fileSearchStore, operation) =>\n      HttpClientRequest.get(`/v1beta/fileSearchStores/${fileSearchStore}/operations/${operation}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Operation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetOperationByFileSearchStoresIdAndOperationsId\": (fileSearchStoresId, operationsId) =>\n      HttpClientRequest.get(`/v1beta/fileSearchStores/${fileSearchStoresId}/upload/operations/${operationsId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Operation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CancelOperation\": (generateContentBatch) =>\n      HttpClientRequest.post(`/v1beta/batches/${generateContentBatch}:cancel`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Empty),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GenerateContent\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:generateContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateContentResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GenerateContentByTunedModel\": (tunedModel, options) =>\n      HttpClientRequest.post(`/v1beta/tunedModels/${tunedModel}:generateContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateContentResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GenerateContentByDynamicId\": (dynamicId, options) =>\n      HttpClientRequest.post(`/v1beta/dynamic/${dynamicId}:generateContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateContentResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GenerateAnswer\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:generateAnswer`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateAnswerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"StreamGenerateContent\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:streamGenerateContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateContentResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"StreamGenerateContentByTunedModel\": (tunedModel, options) =>\n      HttpClientRequest.post(`/v1beta/tunedModels/${tunedModel}:streamGenerateContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateContentResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"StreamGenerateContentByDynamicId\": (dynamicId, options) =>\n      HttpClientRequest.post(`/v1beta/dynamic/${dynamicId}:streamGenerateContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateContentResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"EmbedContent\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:embedContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(EmbedContentResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"BatchEmbedContents\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:batchEmbedContents`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BatchEmbedContentsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CountTokens\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:countTokens`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CountTokensResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"BatchGenerateContent\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:batchGenerateContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BatchGenerateContentOperation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"BatchGenerateContentByTunedModel\": (tunedModel, options) =>\n      HttpClientRequest.post(`/v1beta/tunedModels/${tunedModel}:batchGenerateContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BatchGenerateContentOperation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"AsyncBatchEmbedContent\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:asyncBatchEmbedContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(AsyncBatchEmbedContentOperation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"AsyncBatchEmbedContentByTunedModel\": (tunedModel, options) =>\n      HttpClientRequest.post(`/v1beta/tunedModels/${tunedModel}:asyncBatchEmbedContent`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(AsyncBatchEmbedContentOperation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"UpdateGenerateContentBatch\": (generateContentBatch, options) =>\n      HttpClientRequest.patch(`/v1beta/batches/${generateContentBatch}:updateGenerateContentBatch`).pipe(\n        HttpClientRequest.setUrlParams({ \"updateMask\": options.params?.[\"updateMask\"] as any }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateContentBatch),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"UpdateEmbedContentBatch\": (generateContentBatch, options) =>\n      HttpClientRequest.patch(`/v1beta/batches/${generateContentBatch}:updateEmbedContentBatch`).pipe(\n        HttpClientRequest.setUrlParams({ \"updateMask\": options.params?.[\"updateMask\"] as any }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(EmbedContentBatch),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListCachedContents\": (options) =>\n      HttpClientRequest.get(`/v1beta/cachedContents`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListCachedContentsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreateCachedContent\": (options) =>\n      HttpClientRequest.post(`/v1beta/cachedContents`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CachedContent),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetCachedContent\": (id) =>\n      HttpClientRequest.get(`/v1beta/cachedContents/${id}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CachedContent),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteCachedContent\": (id) =>\n      HttpClientRequest.del(`/v1beta/cachedContents/${id}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Empty),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"UpdateCachedContent\": (id, options) =>\n      HttpClientRequest.patch(`/v1beta/cachedContents/${id}`).pipe(\n        HttpClientRequest.setUrlParams({ \"updateMask\": options.params?.[\"updateMask\"] as any }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CachedContent),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GenerateMessage\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:generateMessage`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateMessageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CountMessageTokens\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:countMessageTokens`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CountMessageTokensResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListFiles\": (options) =>\n      HttpClientRequest.get(`/v1beta/files`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListFilesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreateFile\": (options) =>\n      HttpClientRequest.post(`/v1beta/files`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateFileResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetFile\": (file) =>\n      HttpClientRequest.get(`/v1beta/files/${file}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(File),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteFile\": (file) =>\n      HttpClientRequest.del(`/v1beta/files/${file}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Empty),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DownloadFile\": (file) =>\n      HttpClientRequest.get(`/v1beta/files/${file}:download`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DownloadFileResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetGeneratedFile\": (generatedFile) =>\n      HttpClientRequest.get(`/v1beta/generatedFiles/${generatedFile}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GeneratedFile),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListGeneratedFiles\": (options) =>\n      HttpClientRequest.get(`/v1beta/generatedFiles`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListGeneratedFilesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetModel\": (model) =>\n      HttpClientRequest.get(`/v1beta/models/${model}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Model),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListModels\": (options) =>\n      HttpClientRequest.get(`/v1beta/models`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListModelsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetTunedModel\": (tunedModel) =>\n      HttpClientRequest.get(`/v1beta/tunedModels/${tunedModel}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(TunedModel),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteTunedModel\": (tunedModel) =>\n      HttpClientRequest.del(`/v1beta/tunedModels/${tunedModel}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Empty),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"UpdateTunedModel\": (tunedModel, options) =>\n      HttpClientRequest.patch(`/v1beta/tunedModels/${tunedModel}`).pipe(\n        HttpClientRequest.setUrlParams({ \"updateMask\": options.params?.[\"updateMask\"] as any }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(TunedModel),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListTunedModels\": (options) =>\n      HttpClientRequest.get(`/v1beta/tunedModels`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any,\n          \"filter\": options?.[\"filter\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListTunedModelsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreateTunedModel\": (options) =>\n      HttpClientRequest.post(`/v1beta/tunedModels`).pipe(\n        HttpClientRequest.setUrlParams({ \"tunedModelId\": options.params?.[\"tunedModelId\"] as any }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateTunedModelOperation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListPermissions\": (tunedModel, options) =>\n      HttpClientRequest.get(`/v1beta/tunedModels/${tunedModel}/permissions`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListPermissionsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreatePermission\": (tunedModel, options) =>\n      HttpClientRequest.post(`/v1beta/tunedModels/${tunedModel}/permissions`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Permission),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListPermissionsByCorpus\": (corpus, options) =>\n      HttpClientRequest.get(`/v1beta/corpora/${corpus}/permissions`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListPermissionsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreatePermissionByCorpus\": (corpus, options) =>\n      HttpClientRequest.post(`/v1beta/corpora/${corpus}/permissions`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Permission),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetPermission\": (tunedModel, permission) =>\n      HttpClientRequest.get(`/v1beta/tunedModels/${tunedModel}/permissions/${permission}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Permission),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeletePermission\": (tunedModel, permission) =>\n      HttpClientRequest.del(`/v1beta/tunedModels/${tunedModel}/permissions/${permission}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Empty),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"UpdatePermission\": (tunedModel, permission, options) =>\n      HttpClientRequest.patch(`/v1beta/tunedModels/${tunedModel}/permissions/${permission}`).pipe(\n        HttpClientRequest.setUrlParams({ \"updateMask\": options.params?.[\"updateMask\"] as any }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Permission),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetPermissionByCorpusAndPermission\": (corpus, permission) =>\n      HttpClientRequest.get(`/v1beta/corpora/${corpus}/permissions/${permission}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Permission),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeletePermissionByCorpusAndPermission\": (corpus, permission) =>\n      HttpClientRequest.del(`/v1beta/corpora/${corpus}/permissions/${permission}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Empty),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"UpdatePermissionByCorpusAndPermission\": (corpus, permission, options) =>\n      HttpClientRequest.patch(`/v1beta/corpora/${corpus}/permissions/${permission}`).pipe(\n        HttpClientRequest.setUrlParams({ \"updateMask\": options.params?.[\"updateMask\"] as any }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Permission),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"TransferOwnership\": (tunedModel, options) =>\n      HttpClientRequest.post(`/v1beta/tunedModels/${tunedModel}:transferOwnership`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(TransferOwnershipResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"Predict\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:predict`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(PredictResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"PredictLongRunning\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:predictLongRunning`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(PredictLongRunningOperation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListFileSearchStores\": (options) =>\n      HttpClientRequest.get(`/v1beta/fileSearchStores`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListFileSearchStoresResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreateFileSearchStore\": (options) =>\n      HttpClientRequest.post(`/v1beta/fileSearchStores`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FileSearchStore),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListCorpora\": (options) =>\n      HttpClientRequest.get(`/v1beta/corpora`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListCorporaResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreateCorpus\": (options) =>\n      HttpClientRequest.post(`/v1beta/corpora`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Corpus),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetFileSearchStore\": (fileSearchStore) =>\n      HttpClientRequest.get(`/v1beta/fileSearchStores/${fileSearchStore}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FileSearchStore),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteFileSearchStore\": (fileSearchStore, options) =>\n      HttpClientRequest.del(`/v1beta/fileSearchStores/${fileSearchStore}`).pipe(\n        HttpClientRequest.setUrlParams({ \"force\": options?.[\"force\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Empty),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetCorpus\": (corpus) =>\n      HttpClientRequest.get(`/v1beta/corpora/${corpus}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Corpus),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteCorpus\": (corpus, options) =>\n      HttpClientRequest.del(`/v1beta/corpora/${corpus}`).pipe(\n        HttpClientRequest.setUrlParams({ \"force\": options?.[\"force\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Empty),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetDocument\": (fileSearchStore, document) =>\n      HttpClientRequest.get(`/v1beta/fileSearchStores/${fileSearchStore}/documents/${document}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Document),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteDocument\": (fileSearchStore, document, options) =>\n      HttpClientRequest.del(`/v1beta/fileSearchStores/${fileSearchStore}/documents/${document}`).pipe(\n        HttpClientRequest.setUrlParams({ \"force\": options?.[\"force\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Empty),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListDocuments\": (fileSearchStore, options) =>\n      HttpClientRequest.get(`/v1beta/fileSearchStores/${fileSearchStore}/documents`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"pageSize\": options?.[\"pageSize\"] as any,\n          \"pageToken\": options?.[\"pageToken\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListDocumentsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ImportFile\": (fileSearchStore, options) =>\n      HttpClientRequest.post(`/v1beta/fileSearchStores/${fileSearchStore}:importFile`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ImportFileOperation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"UploadToFileSearchStore\": (fileSearchStore, options) =>\n      HttpClientRequest.post(`/v1beta/fileSearchStores/${fileSearchStore}:uploadToFileSearchStore`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UploadToFileSearchStoreOperation),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GenerateText\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:generateText`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateTextResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GenerateTextByTunedModel\": (tunedModel, options) =>\n      HttpClientRequest.post(`/v1beta/tunedModels/${tunedModel}:generateText`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GenerateTextResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"EmbedText\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:embedText`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(EmbedTextResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"BatchEmbedText\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:batchEmbedText`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BatchEmbedTextResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CountTextTokens\": (model, options) =>\n      HttpClientRequest.post(`/v1beta/models/${model}:countTextTokens`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CountTextTokensResponse),\n          orElse: unexpectedStatus\n        }))\n      )\n  }\n}\n\nexport interface Client {\n  readonly httpClient: HttpClient.HttpClient\n  /**\n   * Lists operations that match the specified filter in the request. If the\n   * server doesn't support this method, it returns `UNIMPLEMENTED`.\n   */\n  readonly \"ListOperations\": (\n    tunedModel: string,\n    options?: typeof ListOperationsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListOperationsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists operations that match the specified filter in the request. If the\n   * server doesn't support this method, it returns `UNIMPLEMENTED`.\n   */\n  readonly \"ListOperationsBy\": (\n    options?: typeof ListOperationsByParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListOperationsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists operations that match the specified filter in the request. If the\n   * server doesn't support this method, it returns `UNIMPLEMENTED`.\n   */\n  readonly \"ListOperationsByModel\": (\n    model: string,\n    options?: typeof ListOperationsByModelParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListOperationsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets the latest state of a long-running operation.  Clients can use this\n   * method to poll the operation result at intervals as recommended by the API\n   * service.\n   */\n  readonly \"GetOperation\": (\n    tunedModel: string,\n    operation: string\n  ) => Effect.Effect<typeof Operation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets the latest state of a long-running operation.  Clients can use this\n   * method to poll the operation result at intervals as recommended by the API\n   * service.\n   */\n  readonly \"GetOperationByGeneratedFileAndOperation\": (\n    generatedFile: string,\n    operation: string\n  ) => Effect.Effect<typeof Operation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets the latest state of a long-running operation.  Clients can use this\n   * method to poll the operation result at intervals as recommended by the API\n   * service.\n   */\n  readonly \"GetOperationByGenerateContentBatch\": (\n    generateContentBatch: string\n  ) => Effect.Effect<typeof Operation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a long-running operation. This method indicates that the client is\n   * no longer interested in the operation result. It does not cancel the\n   * operation. If the server doesn't support this method, it returns\n   * `google.rpc.Code.UNIMPLEMENTED`.\n   */\n  readonly \"DeleteOperation\": (\n    generateContentBatch: string\n  ) => Effect.Effect<typeof Empty.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets the latest state of a long-running operation.  Clients can use this\n   * method to poll the operation result at intervals as recommended by the API\n   * service.\n   */\n  readonly \"GetOperationByModelAndOperation\": (\n    model: string,\n    operation: string\n  ) => Effect.Effect<typeof Operation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets the latest state of a long-running operation.  Clients can use this\n   * method to poll the operation result at intervals as recommended by the API\n   * service.\n   */\n  readonly \"GetOperationByCorpusAndOperation\": (\n    corpus: string,\n    operation: string\n  ) => Effect.Effect<typeof Operation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets the latest state of a long-running operation.  Clients can use this\n   * method to poll the operation result at intervals as recommended by the API\n   * service.\n   */\n  readonly \"GetOperationByFileSearchStoreAndOperation\": (\n    fileSearchStore: string,\n    operation: string\n  ) => Effect.Effect<typeof Operation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets the latest state of a long-running operation.  Clients can use this\n   * method to poll the operation result at intervals as recommended by the API\n   * service.\n   */\n  readonly \"GetOperationByFileSearchStoresIdAndOperationsId\": (\n    fileSearchStoresId: string,\n    operationsId: string\n  ) => Effect.Effect<typeof Operation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Starts asynchronous cancellation on a long-running operation.  The server\n   * makes a best effort to cancel the operation, but success is not\n   * guaranteed.  If the server doesn't support this method, it returns\n   * `google.rpc.Code.UNIMPLEMENTED`.  Clients can use\n   * Operations.GetOperation or\n   * other methods to check whether the cancellation succeeded or whether the\n   * operation completed despite cancellation. On successful cancellation,\n   * the operation is not deleted; instead, it becomes an operation with\n   * an Operation.error value with a google.rpc.Status.code of `1`,\n   * corresponding to `Code.CANCELLED`.\n   */\n  readonly \"CancelOperation\": (\n    generateContentBatch: string\n  ) => Effect.Effect<typeof Empty.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a model response given an input `GenerateContentRequest`.\n   * Refer to the [text generation\n   * guide](https://ai.google.dev/gemini-api/docs/text-generation) for detailed\n   * usage information. Input capabilities differ between models, including\n   * tuned models. Refer to the [model\n   * guide](https://ai.google.dev/gemini-api/docs/models/gemini) and [tuning\n   * guide](https://ai.google.dev/gemini-api/docs/model-tuning) for details.\n   */\n  readonly \"GenerateContent\": (\n    model: string,\n    options: typeof GenerateContentRequest.Encoded\n  ) => Effect.Effect<typeof GenerateContentResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a model response given an input `GenerateContentRequest`.\n   * Refer to the [text generation\n   * guide](https://ai.google.dev/gemini-api/docs/text-generation) for detailed\n   * usage information. Input capabilities differ between models, including\n   * tuned models. Refer to the [model\n   * guide](https://ai.google.dev/gemini-api/docs/models/gemini) and [tuning\n   * guide](https://ai.google.dev/gemini-api/docs/model-tuning) for details.\n   */\n  readonly \"GenerateContentByTunedModel\": (\n    tunedModel: string,\n    options: typeof GenerateContentRequest.Encoded\n  ) => Effect.Effect<typeof GenerateContentResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a model response given an input `GenerateContentRequest`.\n   * Refer to the [text generation\n   * guide](https://ai.google.dev/gemini-api/docs/text-generation) for detailed\n   * usage information. Input capabilities differ between models, including\n   * tuned models. Refer to the [model\n   * guide](https://ai.google.dev/gemini-api/docs/models/gemini) and [tuning\n   * guide](https://ai.google.dev/gemini-api/docs/model-tuning) for details.\n   */\n  readonly \"GenerateContentByDynamicId\": (\n    dynamicId: string,\n    options: typeof GenerateContentRequest.Encoded\n  ) => Effect.Effect<typeof GenerateContentResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a grounded answer from the model given an input\n   * `GenerateAnswerRequest`.\n   */\n  readonly \"GenerateAnswer\": (\n    model: string,\n    options: typeof GenerateAnswerRequest.Encoded\n  ) => Effect.Effect<typeof GenerateAnswerResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a [streamed\n   * response](https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream)\n   * from the model given an input `GenerateContentRequest`.\n   */\n  readonly \"StreamGenerateContent\": (\n    model: string,\n    options: typeof GenerateContentRequest.Encoded\n  ) => Effect.Effect<typeof GenerateContentResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a [streamed\n   * response](https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream)\n   * from the model given an input `GenerateContentRequest`.\n   */\n  readonly \"StreamGenerateContentByTunedModel\": (\n    tunedModel: string,\n    options: typeof GenerateContentRequest.Encoded\n  ) => Effect.Effect<typeof GenerateContentResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a [streamed\n   * response](https://ai.google.dev/gemini-api/docs/text-generation?lang=python#generate-a-text-stream)\n   * from the model given an input `GenerateContentRequest`.\n   */\n  readonly \"StreamGenerateContentByDynamicId\": (\n    dynamicId: string,\n    options: typeof GenerateContentRequest.Encoded\n  ) => Effect.Effect<typeof GenerateContentResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a text embedding vector from the input `Content` using the\n   * specified [Gemini Embedding\n   * model](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding).\n   */\n  readonly \"EmbedContent\": (\n    model: string,\n    options: typeof EmbedContentRequest.Encoded\n  ) => Effect.Effect<typeof EmbedContentResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates multiple embedding vectors from the input `Content` which\n   * consists of a batch of strings represented as `EmbedContentRequest`\n   * objects.\n   */\n  readonly \"BatchEmbedContents\": (\n    model: string,\n    options: typeof BatchEmbedContentsRequest.Encoded\n  ) => Effect.Effect<typeof BatchEmbedContentsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Runs a model's tokenizer on input `Content` and returns the token count.\n   * Refer to the [tokens guide](https://ai.google.dev/gemini-api/docs/tokens)\n   * to learn more about tokens.\n   */\n  readonly \"CountTokens\": (\n    model: string,\n    options: typeof CountTokensRequest.Encoded\n  ) => Effect.Effect<typeof CountTokensResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Enqueues a batch of `GenerateContent` requests for batch processing.\n   */\n  readonly \"BatchGenerateContent\": (\n    model: string,\n    options: typeof BatchGenerateContentRequest.Encoded\n  ) => Effect.Effect<typeof BatchGenerateContentOperation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Enqueues a batch of `GenerateContent` requests for batch processing.\n   */\n  readonly \"BatchGenerateContentByTunedModel\": (\n    tunedModel: string,\n    options: typeof BatchGenerateContentRequest.Encoded\n  ) => Effect.Effect<typeof BatchGenerateContentOperation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Enqueues a batch of `EmbedContent` requests for batch processing.\n   * We have a `BatchEmbedContents` handler in `GenerativeService`, but it was\n   * synchronized. So we name this one to be `Async` to avoid confusion.\n   */\n  readonly \"AsyncBatchEmbedContent\": (\n    model: string,\n    options: typeof AsyncBatchEmbedContentRequest.Encoded\n  ) => Effect.Effect<typeof AsyncBatchEmbedContentOperation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Enqueues a batch of `EmbedContent` requests for batch processing.\n   * We have a `BatchEmbedContents` handler in `GenerativeService`, but it was\n   * synchronized. So we name this one to be `Async` to avoid confusion.\n   */\n  readonly \"AsyncBatchEmbedContentByTunedModel\": (\n    tunedModel: string,\n    options: typeof AsyncBatchEmbedContentRequest.Encoded\n  ) => Effect.Effect<typeof AsyncBatchEmbedContentOperation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Updates a batch of GenerateContent requests for batch processing.\n   */\n  readonly \"UpdateGenerateContentBatch\": (\n    generateContentBatch: string,\n    options: {\n      readonly params?: typeof UpdateGenerateContentBatchParams.Encoded | undefined\n      readonly payload: typeof GenerateContentBatch.Encoded\n    }\n  ) => Effect.Effect<typeof GenerateContentBatch.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Updates a batch of EmbedContent requests for batch processing.\n   */\n  readonly \"UpdateEmbedContentBatch\": (\n    generateContentBatch: string,\n    options: {\n      readonly params?: typeof UpdateEmbedContentBatchParams.Encoded | undefined\n      readonly payload: typeof EmbedContentBatch.Encoded\n    }\n  ) => Effect.Effect<typeof EmbedContentBatch.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists CachedContents.\n   */\n  readonly \"ListCachedContents\": (\n    options?: typeof ListCachedContentsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListCachedContentsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates CachedContent resource.\n   */\n  readonly \"CreateCachedContent\": (\n    options: typeof CachedContent.Encoded\n  ) => Effect.Effect<typeof CachedContent.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Reads CachedContent resource.\n   */\n  readonly \"GetCachedContent\": (\n    id: string\n  ) => Effect.Effect<typeof CachedContent.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes CachedContent resource.\n   */\n  readonly \"DeleteCachedContent\": (\n    id: string\n  ) => Effect.Effect<typeof Empty.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Updates CachedContent resource (only expiration is updatable).\n   */\n  readonly \"UpdateCachedContent\": (\n    id: string,\n    options: {\n      readonly params?: typeof UpdateCachedContentParams.Encoded | undefined\n      readonly payload: typeof CachedContent.Encoded\n    }\n  ) => Effect.Effect<typeof CachedContent.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a response from the model given an input `MessagePrompt`.\n   */\n  readonly \"GenerateMessage\": (\n    model: string,\n    options: typeof GenerateMessageRequest.Encoded\n  ) => Effect.Effect<typeof GenerateMessageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Runs a model's tokenizer on a string and returns the token count.\n   */\n  readonly \"CountMessageTokens\": (\n    model: string,\n    options: typeof CountMessageTokensRequest.Encoded\n  ) => Effect.Effect<typeof CountMessageTokensResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the metadata for `File`s owned by the requesting project.\n   */\n  readonly \"ListFiles\": (\n    options?: typeof ListFilesParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListFilesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates a `File`.\n   */\n  readonly \"CreateFile\": (\n    options: typeof CreateFileRequest.Encoded\n  ) => Effect.Effect<typeof CreateFileResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets the metadata for the given `File`.\n   */\n  readonly \"GetFile\": (file: string) => Effect.Effect<typeof File.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes the `File`.\n   */\n  readonly \"DeleteFile\": (\n    file: string\n  ) => Effect.Effect<typeof Empty.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Download the `File`.\n   */\n  readonly \"DownloadFile\": (\n    file: string\n  ) => Effect.Effect<typeof DownloadFileResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets a generated file. When calling this method via REST, only the metadata\n   * of the generated file is returned. To retrieve the file content via REST,\n   * add alt=media as a query parameter.\n   */\n  readonly \"GetGeneratedFile\": (\n    generatedFile: string\n  ) => Effect.Effect<typeof GeneratedFile.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the generated files owned by the requesting project.\n   */\n  readonly \"ListGeneratedFiles\": (\n    options?: typeof ListGeneratedFilesParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListGeneratedFilesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets information about a specific `Model` such as its version number, token\n   * limits,\n   * [parameters](https://ai.google.dev/gemini-api/docs/models/generative-models#model-parameters)\n   * and other metadata. Refer to the [Gemini models\n   * guide](https://ai.google.dev/gemini-api/docs/models/gemini) for detailed\n   * model information.\n   */\n  readonly \"GetModel\": (model: string) => Effect.Effect<typeof Model.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the [`Model`s](https://ai.google.dev/gemini-api/docs/models/gemini)\n   * available through the Gemini API.\n   */\n  readonly \"ListModels\": (\n    options?: typeof ListModelsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListModelsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets information about a specific TunedModel.\n   */\n  readonly \"GetTunedModel\": (\n    tunedModel: string\n  ) => Effect.Effect<typeof TunedModel.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a tuned model.\n   */\n  readonly \"DeleteTunedModel\": (\n    tunedModel: string\n  ) => Effect.Effect<typeof Empty.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Updates a tuned model.\n   */\n  readonly \"UpdateTunedModel\": (\n    tunedModel: string,\n    options: {\n      readonly params?: typeof UpdateTunedModelParams.Encoded | undefined\n      readonly payload: typeof TunedModel.Encoded\n    }\n  ) => Effect.Effect<typeof TunedModel.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists created tuned models.\n   */\n  readonly \"ListTunedModels\": (\n    options?: typeof ListTunedModelsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListTunedModelsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates a tuned model.\n   * Check intermediate tuning progress (if any) through the\n   * [google.longrunning.Operations] service.\n   *\n   * Access status and results through the Operations service.\n   * Example:\n   *   GET /v1/tunedModels/az2mb0bpw6i/operations/000-111-222\n   */\n  readonly \"CreateTunedModel\": (\n    options: {\n      readonly params?: typeof CreateTunedModelParams.Encoded | undefined\n      readonly payload: typeof TunedModel.Encoded\n    }\n  ) => Effect.Effect<typeof CreateTunedModelOperation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists permissions for the specific resource.\n   */\n  readonly \"ListPermissions\": (\n    tunedModel: string,\n    options?: typeof ListPermissionsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListPermissionsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a permission to a specific resource.\n   */\n  readonly \"CreatePermission\": (\n    tunedModel: string,\n    options: typeof Permission.Encoded\n  ) => Effect.Effect<typeof Permission.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists permissions for the specific resource.\n   */\n  readonly \"ListPermissionsByCorpus\": (\n    corpus: string,\n    options?: typeof ListPermissionsByCorpusParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListPermissionsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a permission to a specific resource.\n   */\n  readonly \"CreatePermissionByCorpus\": (\n    corpus: string,\n    options: typeof Permission.Encoded\n  ) => Effect.Effect<typeof Permission.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets information about a specific Permission.\n   */\n  readonly \"GetPermission\": (\n    tunedModel: string,\n    permission: string\n  ) => Effect.Effect<typeof Permission.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes the permission.\n   */\n  readonly \"DeletePermission\": (\n    tunedModel: string,\n    permission: string\n  ) => Effect.Effect<typeof Empty.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Updates the permission.\n   */\n  readonly \"UpdatePermission\": (\n    tunedModel: string,\n    permission: string,\n    options: { readonly params: typeof UpdatePermissionParams.Encoded; readonly payload: typeof Permission.Encoded }\n  ) => Effect.Effect<typeof Permission.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets information about a specific Permission.\n   */\n  readonly \"GetPermissionByCorpusAndPermission\": (\n    corpus: string,\n    permission: string\n  ) => Effect.Effect<typeof Permission.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes the permission.\n   */\n  readonly \"DeletePermissionByCorpusAndPermission\": (\n    corpus: string,\n    permission: string\n  ) => Effect.Effect<typeof Empty.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Updates the permission.\n   */\n  readonly \"UpdatePermissionByCorpusAndPermission\": (\n    corpus: string,\n    permission: string,\n    options: {\n      readonly params: typeof UpdatePermissionByCorpusAndPermissionParams.Encoded\n      readonly payload: typeof Permission.Encoded\n    }\n  ) => Effect.Effect<typeof Permission.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Transfers ownership of the tuned model.\n   * This is the only way to change ownership of the tuned model.\n   * The current owner will be downgraded to writer role.\n   */\n  readonly \"TransferOwnership\": (\n    tunedModel: string,\n    options: typeof TransferOwnershipRequest.Encoded\n  ) => Effect.Effect<typeof TransferOwnershipResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Performs a prediction request.\n   */\n  readonly \"Predict\": (\n    model: string,\n    options: typeof PredictRequest.Encoded\n  ) => Effect.Effect<typeof PredictResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Same as Predict but returns an LRO.\n   */\n  readonly \"PredictLongRunning\": (\n    model: string,\n    options: typeof PredictLongRunningRequest.Encoded\n  ) => Effect.Effect<typeof PredictLongRunningOperation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists all `FileSearchStores` owned by the user.\n   */\n  readonly \"ListFileSearchStores\": (\n    options?: typeof ListFileSearchStoresParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListFileSearchStoresResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates an empty `FileSearchStore`.\n   */\n  readonly \"CreateFileSearchStore\": (\n    options: typeof FileSearchStore.Encoded\n  ) => Effect.Effect<typeof FileSearchStore.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists all `Corpora` owned by the user.\n   */\n  readonly \"ListCorpora\": (\n    options?: typeof ListCorporaParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListCorporaResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates an empty `Corpus`.\n   */\n  readonly \"CreateCorpus\": (\n    options: typeof Corpus.Encoded\n  ) => Effect.Effect<typeof Corpus.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets information about a specific `FileSearchStore`.\n   */\n  readonly \"GetFileSearchStore\": (\n    fileSearchStore: string\n  ) => Effect.Effect<typeof FileSearchStore.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a `FileSearchStore`.\n   */\n  readonly \"DeleteFileSearchStore\": (\n    fileSearchStore: string,\n    options?: typeof DeleteFileSearchStoreParams.Encoded | undefined\n  ) => Effect.Effect<typeof Empty.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets information about a specific `Corpus`.\n   */\n  readonly \"GetCorpus\": (\n    corpus: string\n  ) => Effect.Effect<typeof Corpus.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a `Corpus`.\n   */\n  readonly \"DeleteCorpus\": (\n    corpus: string,\n    options?: typeof DeleteCorpusParams.Encoded | undefined\n  ) => Effect.Effect<typeof Empty.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Gets information about a specific `Document`.\n   */\n  readonly \"GetDocument\": (\n    fileSearchStore: string,\n    document: string\n  ) => Effect.Effect<typeof Document.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a `Document`.\n   */\n  readonly \"DeleteDocument\": (\n    fileSearchStore: string,\n    document: string,\n    options?: typeof DeleteDocumentParams.Encoded | undefined\n  ) => Effect.Effect<typeof Empty.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists all `Document`s in a `Corpus`.\n   */\n  readonly \"ListDocuments\": (\n    fileSearchStore: string,\n    options?: typeof ListDocumentsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListDocumentsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Imports a `File` from File Service to a `FileSearchStore`.\n   */\n  readonly \"ImportFile\": (\n    fileSearchStore: string,\n    options: typeof ImportFileRequest.Encoded\n  ) => Effect.Effect<typeof ImportFileOperation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Uploads data to a FileSearchStore, preprocesses and chunks before storing\n   * it in a FileSearchStore Document.\n   */\n  readonly \"UploadToFileSearchStore\": (\n    fileSearchStore: string,\n    options: typeof UploadToFileSearchStoreRequest.Encoded\n  ) => Effect.Effect<typeof UploadToFileSearchStoreOperation.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a response from the model given an input message.\n   */\n  readonly \"GenerateText\": (\n    model: string,\n    options: typeof GenerateTextRequest.Encoded\n  ) => Effect.Effect<typeof GenerateTextResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates a response from the model given an input message.\n   */\n  readonly \"GenerateTextByTunedModel\": (\n    tunedModel: string,\n    options: typeof GenerateTextRequest.Encoded\n  ) => Effect.Effect<typeof GenerateTextResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates an embedding from the model given an input message.\n   */\n  readonly \"EmbedText\": (\n    model: string,\n    options: typeof EmbedTextRequest.Encoded\n  ) => Effect.Effect<typeof EmbedTextResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates multiple embeddings from the model given input text in a\n   * synchronous call.\n   */\n  readonly \"BatchEmbedText\": (\n    model: string,\n    options: typeof BatchEmbedTextRequest.Encoded\n  ) => Effect.Effect<typeof BatchEmbedTextResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Runs a model's tokenizer on a text and returns the token count.\n   */\n  readonly \"CountTextTokens\": (\n    model: string,\n    options: typeof CountTextTokensRequest.Encoded\n  ) => Effect.Effect<typeof CountTextTokensResponse.Type, HttpClientError.HttpClientError | ParseError>\n}\n\nexport interface ClientError<Tag extends string, E> {\n  readonly _tag: Tag\n  readonly request: HttpClientRequest.HttpClientRequest\n  readonly response: HttpClientResponse.HttpClientResponse\n  readonly cause: E\n}\n\nclass ClientErrorImpl extends Data.Error<{\n  _tag: string\n  cause: any\n  request: HttpClientRequest.HttpClientRequest\n  response: HttpClientResponse.HttpClientResponse\n}> {}\n\nexport const ClientError = <Tag extends string, E>(\n  tag: Tag,\n  cause: E,\n  response: HttpClientResponse.HttpClientResponse\n): ClientError<Tag, E> =>\n  new ClientErrorImpl({\n    _tag: tag,\n    cause,\n    response,\n    request: response.request\n  }) as any\n"
  },
  {
    "path": "packages/ai/google/src/GoogleClient.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AiError from \"@effect/ai/AiError\"\nimport * as Sse from \"@effect/experimental/Sse\"\nimport * as Headers from \"@effect/platform/Headers\"\nimport * as HttpBody from \"@effect/platform/HttpBody\"\nimport * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as UrlParams from \"@effect/platform/UrlParams\"\nimport * as Arr from \"effect/Array\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Config from \"effect/Config\"\nimport type { ConfigError } from \"effect/ConfigError\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport * as Generated from \"./Generated.js\"\nimport { GoogleConfig } from \"./GoogleConfig.js\"\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class GoogleClient extends Context.Tag(\n  \"@effect/ai-google/GoogleClient\"\n)<GoogleClient, Service>() {}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface Service {\n  readonly client: Generated.Client\n\n  readonly streamRequest: <A, I, R>(\n    request: HttpClientRequest.HttpClientRequest,\n    schema: Schema.Schema<A, I, R>\n  ) => Stream.Stream<A, AiError.AiError, R>\n\n  readonly generateContent: (\n    request: typeof Generated.GenerateContentRequest.Encoded\n  ) => Effect.Effect<Generated.GenerateContentResponse, AiError.AiError>\n\n  readonly generateContentStream: (\n    request: typeof Generated.GenerateContentRequest.Encoded\n  ) => Stream.Stream<Generated.GenerateContentResponse, AiError.AiError>\n}\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (options: {\n  /**\n   * The API key to use to communicate with the Google Generative AI API.\n   */\n  readonly apiKey?: Redacted.Redacted | undefined\n\n  /**\n   * The URL to use to communicate with the Google Generative AI API.\n   *\n   * Defaults to `\"https://generativelanguage.googleapis.com\"`.\n   */\n  readonly apiUrl?: string | undefined\n\n  /**\n   * A method which can be used to transform the underlying `HttpClient` which\n   * will be used to communicate with the Google Generative AI API.\n   */\n  readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n}): Effect.Effect<Service, never, HttpClient.HttpClient | Scope.Scope> =>\n  Effect.gen(function*() {\n    const apiKeyHeader = \"x-goog-api-key\"\n\n    yield* Effect.locallyScopedWith(Headers.currentRedactedNames, Arr.append(apiKeyHeader))\n\n    const httpClient = (yield* HttpClient.HttpClient).pipe(\n      HttpClient.mapRequest((request) =>\n        request.pipe(\n          HttpClientRequest.prependUrl(options.apiUrl ?? \"https://generativelanguage.googleapis.com\"),\n          options.apiKey ? HttpClientRequest.setHeader(apiKeyHeader, Redacted.value(options.apiKey)) : identity,\n          HttpClientRequest.acceptJson\n        )\n      ),\n      options.transformClient ? options.transformClient : identity\n    )\n\n    const httpClientOk = HttpClient.filterStatusOk(httpClient)\n\n    const client = Generated.make(httpClient, {\n      transformClient: (client) =>\n        GoogleConfig.getOrUndefined.pipe(\n          Effect.map((config) => config?.transformClient ? config.transformClient(client) : client)\n        )\n    })\n\n    const streamRequest = <A, I, R>(\n      request: HttpClientRequest.HttpClientRequest,\n      schema: Schema.Schema<A, I, R>\n    ): Stream.Stream<A, AiError.AiError, R> => {\n      const decodeEvents = Schema.decode(Schema.ChunkFromSelf(Schema.parseJson(schema)))\n      return httpClientOk.execute(request).pipe(\n        Effect.map((r) => r.stream),\n        Stream.unwrap,\n        Stream.decodeText(),\n        Stream.pipeThroughChannel(Sse.makeChannel()),\n        Stream.mapChunksEffect((chunk) => decodeEvents(Chunk.map(chunk, (event) => event.data))),\n        Stream.catchTags({\n          RequestError: (error) =>\n            AiError.HttpRequestError.fromRequestError({\n              module: \"GoogleClient\",\n              method: \"streamRequest\",\n              error\n            }),\n          ResponseError: (error) =>\n            AiError.HttpResponseError.fromResponseError({\n              module: \"GoogleClient\",\n              method: \"streamRequest\",\n              error\n            }),\n          ParseError: (error) =>\n            AiError.MalformedOutput.fromParseError({\n              module: \"GoogleClient\",\n              method: \"streamRequest\",\n              error\n            })\n        })\n      )\n    }\n\n    const generateContent: (\n      request: typeof Generated.GenerateContentRequest.Encoded\n    ) => Effect.Effect<Generated.GenerateContentResponse, AiError.AiError> = Effect.fnUntraced(\n      function*(request) {\n        return yield* client.GenerateContent(request.model, request).pipe(\n          Effect.catchTags({\n            RequestError: (error) =>\n              AiError.HttpRequestError.fromRequestError({\n                module: \"GoogleClient\",\n                method: \"generateContent\",\n                error\n              }),\n            ResponseError: (error) =>\n              AiError.HttpResponseError.fromResponseError({\n                module: \"GoogleClient\",\n                method: \"generateContent\",\n                error\n              }),\n            ParseError: (error) =>\n              AiError.MalformedOutput.fromParseError({\n                module: \"GoogleClient\",\n                method: \"generateContent\",\n                error\n              })\n          })\n        )\n      }\n    )\n\n    const generateContentStream = (\n      request: typeof Generated.GenerateContentRequest.Encoded\n    ): Stream.Stream<Generated.GenerateContentResponse, AiError.AiError> => {\n      const url = `/v1beta/models/${request.model}:streamGenerateContent`\n      const httpRequest = HttpClientRequest.post(url, {\n        urlParams: UrlParams.fromInput({ \"alt\": \"sse\" }),\n        body: HttpBody.unsafeJson(request)\n      })\n      return streamRequest(httpRequest, Generated.GenerateContentResponse).pipe(\n        Stream.takeUntil(hasFinishReason)\n      )\n    }\n\n    return GoogleClient.of({\n      client,\n      streamRequest,\n      generateContent,\n      generateContentStream\n    })\n  })\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  /**\n   * The API key to use to communicate with the Google Generative AI API.\n   */\n  readonly apiKey?: Redacted.Redacted | undefined\n\n  /**\n   * The URL to use to communicate with the Google Generative AI API.\n   *\n   * Defaults to `\"https://generativelanguage.googleapis.com/v1beta\"`.\n   */\n  readonly apiUrl?: string | undefined\n\n  /**\n   * A method which can be used to transform the underlying `HttpClient` which\n   * will be used to communicate with the Google Generative AI API.\n   */\n  readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n}): Layer.Layer<\n  GoogleClient,\n  never,\n  HttpClient.HttpClient\n> => Layer.scoped(GoogleClient, make(options))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerConfig = (\n  options: {\n    /**\n     * The API key to use to communicate with the Google Generative AI API.\n     */\n    readonly apiKey?: Config.Config<Redacted.Redacted | undefined> | undefined\n\n    /**\n     * The URL to use to communicate with the Google Generative AI API.\n     *\n     * Defaults to `\"https://generativelanguage.googleapis.com/v1beta\"`.\n     */\n    readonly apiUrl?: Config.Config<string | undefined> | undefined\n\n    /**\n     * A method which can be used to transform the underlying `HttpClient` which\n     * will be used to communicate with the Google Generative AI API.\n     */\n    readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n  }\n): Layer.Layer<GoogleClient, ConfigError, HttpClient.HttpClient> => {\n  const { transformClient, ...configs } = options\n  return Config.all(configs).pipe(\n    Effect.flatMap((configs) => make({ ...configs, transformClient })),\n    Layer.scoped(GoogleClient)\n  )\n}\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nconst hasFinishReason = (event: Generated.GenerateContentResponse): boolean =>\n  Predicate.isNotUndefined(event.candidates) &&\n  event.candidates.some((candidate) => Predicate.isNotUndefined(candidate.finishReason))\n"
  },
  {
    "path": "packages/ai/google/src/GoogleConfig.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { HttpClient } from \"@effect/platform/HttpClient\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class GoogleConfig extends Context.Tag(\"@effect/ai-google/GoogleConfig\")<\n  GoogleConfig,\n  GoogleConfig.Service\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<typeof GoogleConfig.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(GoogleConfig.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace GoogleConfig {\n  /**\n   * @since 1.0.\n   * @category Models\n   */\n  export interface Service {\n    readonly transformClient?: (client: HttpClient) => HttpClient\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport const withClientTransform: {\n  (transform: (client: HttpClient) => HttpClient): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient): Effect.Effect<A, E, R>\n} = dual<\n  (transform: (client: HttpClient) => HttpClient) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient) => Effect.Effect<A, E, R>\n>(\n  2,\n  (self, transformClient) =>\n    Effect.flatMap(\n      GoogleConfig.getOrUndefined,\n      (config) => Effect.provideService(self, GoogleConfig, { ...config, transformClient })\n    )\n)\n"
  },
  {
    "path": "packages/ai/google/src/GoogleLanguageModel.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AiError from \"@effect/ai/AiError\"\nimport * as IdGenerator from \"@effect/ai/IdGenerator\"\nimport * as LanguageModel from \"@effect/ai/LanguageModel\"\nimport * as AiModel from \"@effect/ai/Model\"\nimport type * as Response from \"@effect/ai/Response\"\nimport { addGenAIAnnotations } from \"@effect/ai/Telemetry\"\nimport * as Tool from \"@effect/ai/Tool\"\nimport * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Stream from \"effect/Stream\"\nimport type { Span } from \"effect/Tracer\"\nimport type { Mutable, Simplify } from \"effect/Types\"\nimport type * as Generated from \"./Generated.js\"\nimport { GoogleClient } from \"./GoogleClient.js\"\nimport * as InternalUtilities from \"./internal/utilities.js\"\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type Model = string\n\n// =============================================================================\n// Google Ai Language Model Configuration\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class Config extends Context.Tag(\"@effect/ai-google/GoogleLanguageModel/Config\")<\n  Config,\n  Config.Service\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<Config.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(Config.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Config {\n  /**\n   * @since 1.0.0\n   * @category Models\n   */\n  export interface Service extends\n    Simplify<\n      Partial<\n        Omit<\n          typeof Generated.GenerateContentRequest.Encoded,\n          \"contents\" | \"tools\" | \"toolConfig\" | \"systemInstruction\"\n        >\n      >\n    >\n  {\n    readonly toolConfig: Partial<{\n      readonly functionCallingConfig: Omit<\n        typeof Generated.FunctionCallingConfig.Encoded,\n        \"mode\"\n      >\n    }>\n  }\n}\n\n// =============================================================================\n// Google Ai Provider Options / Metadata\n// =============================================================================\n\ndeclare module \"@effect/ai/Prompt\" {\n  export interface ReasoningPartOptions extends ProviderOptions {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n\n  export interface TextPartOptions extends ProviderOptions {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n\n  export interface ToolCallPartOptions extends ProviderOptions {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n}\n\ndeclare module \"@effect/ai/Response\" {\n  export interface TextStartPartMetadata extends ProviderMetadata {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n\n  export interface TextDeltaPartMetadata extends ProviderMetadata {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n\n  export interface ReasoningPartMetadata extends ProviderMetadata {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n\n  export interface ReasoningStartPartMetadata extends ProviderMetadata {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n\n  export interface ReasoningDeltaPartMetadata extends ProviderMetadata {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n\n  export interface ToolParamsStartPartMetadata extends ProviderMetadata {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n\n  export interface ToolParamsDeltaPartMetadata extends ProviderMetadata {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n\n  export interface ToolCallPartMetadata extends ProviderMetadata {\n    readonly google?: {\n      readonly thoughtSignature?: string | undefined\n    } | undefined\n  }\n\n  export interface FinishPartMetadata extends ProviderMetadata {\n    readonly google?: {\n      readonly groundingMetadata?: Generated.GroundingMetadata | undefined\n      readonly safetyRatings?: ReadonlyArray<Generated.SafetyRating> | undefined\n      readonly urlContextMetadata?: Generated.UrlContextMetadata | undefined\n      readonly usageMetadata?: Generated.UsageMetadata | undefined\n    } | undefined\n  }\n}\n\n// =============================================================================\n// Google Ai Language Model\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category AiModel\n */\nexport const model = (\n  model: (string & {}) | Model,\n  config?: Omit<Config.Service, \"model\">\n): AiModel.Model<\"google\", LanguageModel.LanguageModel, GoogleClient> =>\n  AiModel.make(\"google\", layer({ model, config }))\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.fnUntraced(function*(options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Omit<Config.Service, \"model\">\n}) {\n  const client = yield* GoogleClient\n\n  const makeRequest = Effect.fnUntraced(\n    function*(providerOptions: LanguageModel.ProviderOptions) {\n      const context = yield* Effect.context<never>()\n      const config = { model: options.model, ...options.config, ...context.unsafeMap.get(Config.key) }\n      const { messages, system } = yield* prepareMessages(providerOptions, config)\n      const { toolConfig, tools } = yield* prepareTools(providerOptions, config)\n      const responseFormat = providerOptions.responseFormat\n      const responseMimeType = responseFormat.type === \"json\" ? \"application/json\" : undefined\n      const responseSchema = responseFormat.type === \"json\"\n        ? InternalUtilities.jsonSchemaToOpenApiSchema(Tool.getJsonSchemaFromSchemaAst(responseFormat.schema.ast))\n        : undefined\n      const request: typeof Generated.GenerateContentRequest.Encoded = {\n        ...config,\n        systemInstruction: system,\n        contents: messages,\n        tools,\n        toolConfig,\n        generationConfig: {\n          ...config.generationConfig,\n          responseMimeType,\n          responseSchema\n        }\n      }\n      return request\n    }\n  )\n\n  return yield* LanguageModel.make({\n    generateText: Effect.fnUntraced(\n      function*(options) {\n        const request = yield* makeRequest(options)\n        annotateRequest(options.span, request)\n        const rawResponse = yield* client.generateContent(request)\n        annotateResponse(options.span, rawResponse)\n        return yield* makeResponse(rawResponse)\n      }\n    ),\n    streamText: Effect.fnUntraced(\n      function*(options) {\n        const request = yield* makeRequest(options)\n        annotateRequest(options.span, request)\n        return client.generateContentStream(request)\n      },\n      (effect, options) =>\n        effect.pipe(\n          Effect.flatMap((stream) => makeStreamResponse(stream)),\n          Stream.unwrap,\n          Stream.map((response) => {\n            annotateStreamResponse(options.span, response)\n            return response\n          })\n        )\n    )\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Omit<Config.Service, \"model\">\n}): Layer.Layer<LanguageModel.LanguageModel, never, GoogleClient> =>\n  Layer.effect(LanguageModel.LanguageModel, make({ model: options.model, config: options.config }))\n\n// =============================================================================\n// Prompt Conversion\n// =============================================================================\n\nconst prepareMessages: (\n  options: LanguageModel.ProviderOptions,\n  config: Config.Service\n) => Effect.Effect<{\n  readonly system: typeof Generated.Content.Encoded | undefined\n  readonly messages: ReadonlyArray<typeof Generated.Content.Encoded>\n}, AiError.AiError> = Effect.fnUntraced(\n  function*(options, config) {\n    const system: Array<typeof Generated.Part.Encoded> = []\n    const messages: Array<typeof Generated.Content.Encoded> = []\n\n    for (const message of options.prompt.content) {\n      switch (message.role) {\n        case \"system\": {\n          if (messages.length > 0) {\n            return yield* new AiError.MalformedInput({\n              module: \"GoogleLanguageModel\",\n              method: \"prepareMessages\",\n              description: `System messages are only supported at the beginning of a conversation`\n            })\n          }\n          system.push({ text: message.content })\n          break\n        }\n\n        case \"user\": {\n          const parts: Array<typeof Generated.Part.Encoded> = []\n\n          for (const part of message.content) {\n            switch (part.type) {\n              case \"text\": {\n                parts.push({ text: part.text })\n                break\n              }\n              case \"file\": {\n                const mediaType = part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType\n                if (part.data instanceof URL) {\n                  parts.push({\n                    fileData: {\n                      mimeType: mediaType,\n                      fileUri: part.data.toString()\n                    }\n                  })\n                } else {\n                  parts.push({\n                    inlineData: {\n                      mimeType: mediaType,\n                      data: typeof part.data === \"string\" ? part.data : Encoding.encodeBase64(part.data)\n                    }\n                  })\n                }\n                break\n              }\n            }\n          }\n\n          messages.push({ role: \"user\", parts })\n\n          break\n        }\n\n        case \"assistant\": {\n          const parts: Array<typeof Generated.Part.Encoded> = []\n\n          for (const part of message.content) {\n            switch (part.type) {\n              case \"text\": {\n                if (part.text.length > 0) {\n                  parts.push({\n                    text: part.text,\n                    thoughtSignature: part.options.google?.thoughtSignature\n                  })\n                }\n                break\n              }\n\n              case \"file\": {\n                if (part.mediaType !== \"image/png\") {\n                  return yield* new AiError.MalformedInput({\n                    module: \"GoogleLanguageModel\",\n                    method: \"prepareMessages\",\n                    description: `Unsupported image media type '${part.mediaType}'` +\n                      \"- only PNG images are supported in assistant messages\"\n                  })\n                }\n                if (part.data instanceof URL) {\n                  return yield* new AiError.MalformedInput({\n                    module: \"GoogleLanguageModel\",\n                    method: \"prepareMessages\",\n                    description: \"File data URLs are unsupported in assistant messages\"\n                  })\n                }\n                parts.push({\n                  inlineData: {\n                    mimeType: part.mediaType,\n                    data: typeof part.data === \"string\" ? part.data : Encoding.encodeBase64(part.data)\n                  }\n                })\n                break\n              }\n\n              case \"reasoning\": {\n                if (part.text.length > 0) {\n                  parts.push({\n                    text: part.text,\n                    thought: true,\n                    thoughtSignature: part.options.google?.thoughtSignature\n                  })\n                }\n                break\n              }\n\n              case \"tool-call\": {\n                parts.push({\n                  functionCall: {\n                    name: part.name,\n                    args: part.params as any\n                  },\n                  thoughtSignature: part.options.google?.thoughtSignature\n                })\n                break\n              }\n            }\n          }\n\n          messages.push({ role: \"model\", parts })\n\n          break\n        }\n\n        case \"tool\": {\n          const parts: Array<typeof Generated.Part.Encoded> = []\n\n          for (const part of message.content) {\n            parts.push({\n              functionResponse: {\n                id: part.id,\n                name: part.name,\n                response: part.result as any\n              }\n            })\n          }\n\n          messages.push({ role: \"user\", parts })\n\n          break\n        }\n      }\n    }\n\n    const isGemmaModel = config.model!.toLowerCase().startsWith(\"gemma-\")\n\n    if (isGemmaModel && system.length > 0 && messages.length > 0 && messages[0].role === \"user\") {\n      const systemText = system.map((part) => part.text).join(\"\\n\\n\")\n      ;(messages[0].parts as Array<typeof Generated.Part.Encoded>).unshift({ text: `${systemText}\\n\\n` })\n      return { system: undefined, messages }\n    }\n\n    return { system: !isGemmaModel && system.length > 0 ? { parts: system } : undefined, messages }\n  }\n)\n\n// =============================================================================\n// Response Conversion\n// =============================================================================\n\nconst makeResponse: (response: Generated.GenerateContentResponse) => Effect.Effect<\n  Array<Response.PartEncoded>,\n  AiError.AiError,\n  IdGenerator.IdGenerator\n> = Effect.fnUntraced(\n  function*(response) {\n    const idGenerator = yield* IdGenerator.IdGenerator\n    const parts: Array<Response.PartEncoded> = []\n\n    parts.push({\n      type: \"response-metadata\",\n      id: response.responseId,\n      modelId: response.modelVersion,\n      timestamp: DateTime.formatIso(yield* DateTime.now)\n    })\n\n    const candidate = response.candidates?.[0]\n\n    if (Predicate.isUndefined(candidate)) {\n      return yield* new AiError.MalformedOutput({\n        module: \"GoogleLanguageModel\",\n        method: \"makeResponse\",\n        description: \"Received response with no valid candidates\"\n      })\n    }\n\n    let hasToolCalls = false\n    let lastCodeExecutionToolCallId: string | undefined = undefined\n    const contentParts = candidate.content?.parts ?? []\n\n    for (const part of contentParts) {\n      if (\"text\" in part && Predicate.isNotUndefined(part.text) && part.text.length > 0) {\n        if (part.thought === true) {\n          parts.push({\n            type: \"reasoning\",\n            text: part.text,\n            metadata: { google: { thoughtSignature: part.thoughtSignature } }\n          })\n        } else {\n          parts.push({\n            type: \"text\",\n            text: part.text\n          })\n        }\n      }\n\n      if (\"functionCall\" in part && Predicate.isNotUndefined(part.functionCall)) {\n        hasToolCalls = true\n        parts.push({\n          type: \"tool-call\",\n          id: yield* idGenerator.generateId(),\n          name: part.functionCall.name,\n          params: part.functionCall.args,\n          metadata: { google: { thoughtSignature: part.thoughtSignature } }\n        })\n      }\n\n      if (\n        \"inlineData\" in part &&\n        Predicate.isNotUndefined(part.inlineData) &&\n        Predicate.isNotUndefined(part.inlineData.data)\n      ) {\n        if (Predicate.isUndefined(part.inlineData.mimeType)) {\n          return yield* new AiError.MalformedOutput({\n            module: \"GoogleLanguageModel\",\n            method: \"makeResponse\",\n            description: \"Received inline data without a valid MIME type\"\n          })\n        }\n        parts.push({\n          type: \"file\",\n          data: part.inlineData.data,\n          mediaType: part.inlineData.mimeType\n        })\n      }\n\n      if (\"executableCode\" in part && Predicate.isNotUndefined(part.executableCode)) {\n        const toolCallId = yield* idGenerator.generateId()\n        lastCodeExecutionToolCallId = toolCallId\n        parts.push({\n          type: \"tool-call\",\n          id: toolCallId,\n          name: \"GoogleCodeExecution\",\n          params: part.executableCode,\n          providerName: \"code_execution\",\n          providerExecuted: true\n        })\n      }\n\n      if (\"codeExecutionResult\" in part && Predicate.isNotUndefined(part.codeExecutionResult)) {\n        if (Predicate.isUndefined(lastCodeExecutionToolCallId)) {\n          return yield* new AiError.MalformedOutput({\n            module: \"GoogleLanguageModel\",\n            method: \"makeResponse\",\n            description: \"Received code_execution tool call result without \" +\n              \"preceding code_execution tool call\"\n          })\n        }\n        parts.push({\n          type: \"tool-result\",\n          id: lastCodeExecutionToolCallId,\n          name: \"GoogleCodeExecution\",\n          isFailure: false,\n          result: part.codeExecutionResult,\n          providerName: \"code_execution\",\n          providerExecuted: true\n        })\n        lastCodeExecutionToolCallId = undefined\n      }\n    }\n\n    const sources = yield* extractSources(candidate.groundingMetadata)\n    for (const source of sources) {\n      parts.push(source)\n    }\n\n    const finishReason = InternalUtilities.resolveFinishReason(candidate.finishReason, hasToolCalls)\n\n    parts.push({\n      type: \"finish\",\n      reason: finishReason,\n      usage: {\n        inputTokens: response.usageMetadata?.promptTokenCount,\n        outputTokens: response.usageMetadata?.candidatesTokenCount,\n        totalTokens: response.usageMetadata?.totalTokenCount,\n        reasoningTokens: response.usageMetadata?.thoughtsTokenCount,\n        cachedInputTokens: response.usageMetadata?.cachedContentTokenCount\n      },\n      metadata: {\n        google: {\n          groundingMetadata: candidate.groundingMetadata,\n          safetyRatings: candidate.safetyRatings,\n          urlContextMetadata: candidate.urlContextMetadata,\n          usageMetadata: response.usageMetadata\n        }\n      }\n    })\n\n    return parts\n  }\n)\n\nconst makeStreamResponse: (\n  stream: Stream.Stream<Generated.GenerateContentResponse, AiError.AiError>\n) => Effect.Effect<\n  Stream.Stream<Response.StreamPartEncoded, AiError.AiError>,\n  AiError.AiError,\n  IdGenerator.IdGenerator\n> = Effect.fnUntraced(\n  function*(stream) {\n    const idGenerator = yield* IdGenerator.IdGenerator\n\n    let blockCounter = 0\n    let currentTextBlockId: string | undefined = undefined\n    let currentReasoningBlockId: string | undefined = undefined\n\n    let hasToolCalls = false\n    let lastCodeExecutionToolCallId: string | undefined = undefined\n\n    // Prevent emission of duplicate sources\n    const emittedSourceUrls = new Set<string>()\n\n    return stream.pipe(\n      Stream.mapEffect(Effect.fnUntraced(function*(event) {\n        const parts: Array<Response.StreamPartEncoded> = []\n\n        const candidate = event.candidates?.[0]\n\n        if (Predicate.isUndefined(candidate)) {\n          return parts\n        }\n\n        if (Predicate.isUndefined(candidate.content)) {\n          return parts\n        }\n\n        const contentParts = candidate.content.parts ?? []\n\n        for (const part of contentParts) {\n          if (\"text\" in part && Predicate.isNotUndefined(part.text) && part.text.length > 0) {\n            if (part.thought === true) {\n              // End any active text block before starting reasoning\n              if (Predicate.isNotUndefined(currentTextBlockId)) {\n                parts.push({\n                  type: \"text-end\",\n                  id: currentTextBlockId\n                })\n                currentTextBlockId = undefined\n              }\n              // Start new reasoning block if not already active\n              if (Predicate.isUndefined(currentReasoningBlockId)) {\n                currentReasoningBlockId = (blockCounter++).toString()\n                parts.push({\n                  type: \"reasoning-start\",\n                  id: currentReasoningBlockId,\n                  metadata: { google: { thoughtSignature: part.thoughtSignature } }\n                })\n              }\n              parts.push({\n                type: \"reasoning-delta\",\n                id: currentReasoningBlockId,\n                delta: part.text,\n                metadata: { google: { thoughtSignature: part.thoughtSignature } }\n              })\n            } else {\n              // End any active reasoning block before starting text\n              if (Predicate.isNotUndefined(currentReasoningBlockId)) {\n                parts.push({\n                  type: \"reasoning-end\",\n                  id: currentReasoningBlockId\n                })\n                currentReasoningBlockId = undefined\n              }\n              // Start new text block if not already active\n              if (Predicate.isUndefined(currentTextBlockId)) {\n                currentTextBlockId = (blockCounter++).toString()\n                parts.push({\n                  type: \"text-start\",\n                  id: currentTextBlockId,\n                  metadata: { google: { thoughtSignature: part.thoughtSignature } }\n                })\n              }\n              parts.push({\n                type: \"text-delta\",\n                id: currentTextBlockId,\n                delta: part.text,\n                metadata: { google: { thoughtSignature: part.thoughtSignature } }\n              })\n            }\n          }\n\n          if (\"executableCode\" in part && Predicate.isNotUndefined(part.executableCode)) {\n            const toolCallId = yield* idGenerator.generateId()\n            lastCodeExecutionToolCallId = toolCallId\n            parts.push({\n              type: \"tool-call\",\n              id: toolCallId,\n              name: \"GoogleCodeExecution\",\n              params: part.executableCode,\n              providerName: \"code_execution\",\n              providerExecuted: true\n            })\n          }\n\n          if (\"codeExecutionResult\" in part && Predicate.isNotUndefined(part.codeExecutionResult)) {\n            if (Predicate.isUndefined(lastCodeExecutionToolCallId)) {\n              return yield* new AiError.MalformedOutput({\n                module: \"GoogleLanguageModel\",\n                method: \"makeStreamResponse\",\n                description: \"Received code_execution tool call result without \" +\n                  \"preceding code_execution tool call\"\n              })\n            }\n            parts.push({\n              type: \"tool-result\",\n              id: lastCodeExecutionToolCallId,\n              name: \"GoogleCodeExecution\",\n              isFailure: false,\n              result: part.codeExecutionResult,\n              providerName: \"code_execution\",\n              providerExecuted: true\n            })\n            lastCodeExecutionToolCallId = undefined\n          }\n        }\n\n        const toolCalls = yield* getToolCalls(contentParts).pipe(\n          Effect.provideService(IdGenerator.IdGenerator, idGenerator)\n        )\n\n        for (const toolCall of toolCalls) {\n          hasToolCalls = true\n          parts.push({\n            type: \"tool-params-start\",\n            id: toolCall.id,\n            name: toolCall.name,\n            providerName: toolCall.providerName,\n            providerExecuted: toolCall.providerExecuted,\n            metadata: toolCall.metadata\n          })\n          parts.push({\n            type: \"tool-params-delta\",\n            id: toolCall.id,\n            delta: JSON.stringify(toolCall.params),\n            metadata: toolCall.metadata\n          })\n          parts.push({\n            type: \"tool-params-end\",\n            id: toolCall.id,\n            metadata: toolCall.metadata\n          })\n          parts.push(toolCall)\n        }\n\n        const sources = yield* extractSources(candidate.groundingMetadata).pipe(\n          Effect.provideService(IdGenerator.IdGenerator, idGenerator)\n        )\n        for (const source of sources) {\n          if (source.sourceType === \"url\" && !emittedSourceUrls.has(source.url)) {\n            emittedSourceUrls.add(source.url)\n            parts.push(source)\n          }\n        }\n\n        if (Predicate.isNotUndefined(candidate.finishReason)) {\n          if (Predicate.isNotUndefined(currentTextBlockId)) {\n            parts.push({\n              type: \"text-end\",\n              id: currentTextBlockId\n            })\n          }\n\n          if (Predicate.isNotUndefined(currentReasoningBlockId)) {\n            parts.push({\n              type: \"reasoning-end\",\n              id: currentReasoningBlockId\n            })\n          }\n\n          const finishReason = InternalUtilities.resolveFinishReason(candidate.finishReason, hasToolCalls)\n\n          parts.push({\n            type: \"finish\",\n            reason: finishReason,\n            usage: {\n              inputTokens: event.usageMetadata?.promptTokenCount,\n              outputTokens: event.usageMetadata?.candidatesTokenCount,\n              totalTokens: event.usageMetadata?.totalTokenCount,\n              reasoningTokens: event.usageMetadata?.thoughtsTokenCount,\n              cachedInputTokens: event.usageMetadata?.cachedContentTokenCount\n            },\n            metadata: {\n              google: {\n                groundingMetadata: candidate.groundingMetadata,\n                safetyRatings: candidate.safetyRatings,\n                urlContextMetadata: candidate.urlContextMetadata,\n                usageMetadata: event.usageMetadata\n              }\n            }\n          })\n        }\n\n        return parts\n      })),\n      Stream.flattenIterables\n    )\n  }\n)\n\n// =============================================================================\n// Telemetry\n// =============================================================================\n\nconst annotateRequest = (span: Span, request: typeof Generated.GenerateContentRequest.Encoded): void => {\n  addGenAIAnnotations(span, {\n    system: \"gcp.gemini\",\n    operation: { name: \"chat\" },\n    request: {\n      model: request.model,\n      temperature: request.generationConfig?.temperature,\n      topP: request.generationConfig?.topP,\n      maxTokens: request.generationConfig?.maxOutputTokens,\n      stopSequences: request.generationConfig?.stopSequences ?? []\n    }\n  })\n}\n\nconst annotateResponse = (span: Span, response: typeof Generated.GenerateContentResponse.Type): void => {\n  const finishReasons: Array<string> = []\n  if (Predicate.isNotNullable(response.candidates)) {\n    for (const candidate of response.candidates) {\n      if (Predicate.isNotNullable(candidate.finishReason)) {\n        finishReasons.push(candidate.finishReason)\n      }\n    }\n  }\n  addGenAIAnnotations(span, {\n    response: {\n      model: response.modelVersion,\n      finishReasons: finishReasons.length > 0 ? finishReasons : undefined\n    },\n    usage: {\n      inputTokens: response.usageMetadata?.promptTokenCount,\n      outputTokens: response.usageMetadata?.candidatesTokenCount\n    }\n  })\n}\n\nconst annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded): void => {\n  if (part.type === \"response-metadata\") {\n    addGenAIAnnotations(span, {\n      response: {\n        id: part.id,\n        model: part.modelId\n      }\n    })\n  }\n  if (part.type === \"finish\") {\n    addGenAIAnnotations(span, {\n      response: {\n        finishReasons: [part.reason]\n      },\n      usage: {\n        inputTokens: part.usage.inputTokens,\n        outputTokens: part.usage.outputTokens\n      }\n    })\n  }\n}\n\n// =============================================================================\n// Tool Calling\n// =============================================================================\n\nconst prepareTools: (options: LanguageModel.ProviderOptions, config: Config.Service) => Effect.Effect<{\n  readonly tools: typeof Generated.Tool.Encoded | undefined\n  readonly toolConfig: typeof Generated.ToolConfig.Encoded | undefined\n}, AiError.AiError> = Effect.fnUntraced(function*(options, config) {\n  if (options.tools.length === 0) {\n    return { tools: undefined, toolConfig: undefined }\n  }\n\n  const userDefinedTools = options.tools.filter((tool) => Tool.isUserDefined(tool))\n  const providerDefinedTools = options.tools.filter((tool) => Tool.isProviderDefined(tool))\n\n  if (userDefinedTools.length > 0 && providerDefinedTools.length > 0) {\n    return yield* new AiError.MalformedInput({\n      module: \"GoogleLanguageModel\",\n      method: \"prepareTools\",\n      description: \"Unsupported Functionality: cannot mix provider-defined tools \" +\n        \"with user-defined tools in the same request\"\n    })\n  }\n\n  // Handle provider-defined tools\n  if (providerDefinedTools.length > 0) {\n    const model = config.model!\n    const isGemini2 = model.includes(\"gemini-2\")\n    const googleTools: Mutable<Omit<typeof Generated.Tool.Encoded, \"functionDeclarations\">> = {}\n\n    for (const tool of providerDefinedTools) {\n      switch (tool.id) {\n        case \"google.code_execution\": {\n          if (isGemini2) {\n            googleTools.codeExecution = {}\n          } else {\n            return yield* new AiError.MalformedInput({\n              module: \"GoogleLanguageModel\",\n              method: \"prepareTools\",\n              description: `The code_execution tool is not supported with \" +\n                \"Gemini models other than Gemini 2`\n            })\n          }\n          break\n        }\n\n        case \"google.google_search\": {\n          googleTools.googleSearch = {}\n          break\n        }\n\n        case \"google.google_search_retrieval\": {\n          googleTools.googleSearchRetrieval = { dynamicRetrievalConfig: tool.args }\n          break\n        }\n\n        case \"google.url_context\": {\n          if (isGemini2) {\n            googleTools.urlContext = {}\n          } else {\n            return yield* new AiError.MalformedInput({\n              module: \"GoogleLanguageModel\",\n              method: \"prepareTools\",\n              description: `The url_context tool is not supported with \" +\n                \"Gemini models other than Gemini 2`\n            })\n          }\n        }\n      }\n    }\n\n    return { tools: googleTools, toolConfig: undefined }\n  }\n\n  let tools: Array<typeof Generated.FunctionDeclaration.Encoded> = []\n  let toolConfig: typeof Generated.ToolConfig.Encoded | undefined = undefined\n\n  // Handle user-defined tools\n  for (const tool of userDefinedTools) {\n    tools.push({\n      name: tool.name,\n      description: Tool.getDescription(tool as any) ?? \"\",\n      parameters: InternalUtilities.jsonSchemaToOpenApiSchema(Tool.getJsonSchema(tool as any))\n    })\n  }\n\n  if (options.toolChoice === \"none\") {\n    toolConfig = {\n      functionCallingConfig: {\n        mode: \"NONE\"\n      }\n    }\n  } else if (options.toolChoice === \"auto\") {\n    toolConfig = {\n      functionCallingConfig: {\n        mode: \"AUTO\"\n      }\n    }\n  } else if (options.toolChoice === \"required\") {\n    toolConfig = {\n      functionCallingConfig: {\n        mode: \"ANY\"\n      }\n    }\n  } else if (\"tool\" in options.toolChoice) {\n    toolConfig = {\n      functionCallingConfig: {\n        mode: \"ANY\",\n        allowedFunctionNames: [options.toolChoice.tool]\n      }\n    }\n  } else {\n    const allowedTools = new Set(options.toolChoice.oneOf)\n    tools = tools.filter((tool) => allowedTools.has(tool.name))\n    toolConfig = {\n      functionCallingConfig: {\n        mode: options.toolChoice.mode === \"auto\" ? \"AUTO\" : \"ANY\",\n        allowedFunctionNames: options.toolChoice.mode === \"auto\" ? undefined : Array.from(allowedTools)\n      }\n    }\n  }\n\n  return { tools: { functionDeclarations: tools }, toolConfig }\n})\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nconst extractSources = Effect.fnUntraced(\n  function*(groundingMetadata: Generated.GroundingMetadata | undefined) {\n    const idGenerator = yield* IdGenerator.IdGenerator\n    const sources: Array<Response.UrlSourcePartEncoded> = []\n\n    if (Predicate.isUndefined(groundingMetadata)) {\n      return sources\n    }\n\n    const chunks = groundingMetadata.groundingChunks ?? []\n    for (const chunk of chunks) {\n      if (\n        Predicate.isNotUndefined(chunk.web) &&\n        Predicate.isNotUndefined(chunk.web.uri) &&\n        Predicate.isNotUndefined(chunk.web.title)\n      ) {\n        sources.push({\n          type: \"source\",\n          sourceType: \"url\",\n          id: yield* idGenerator.generateId(),\n          url: chunk.web.uri,\n          title: chunk.web.title\n        })\n      }\n    }\n\n    return sources\n  }\n)\n\nconst getToolCalls = Effect.fnUntraced(\n  function*(contentParts: ReadonlyArray<Generated.Part>) {\n    const idGenerator = yield* IdGenerator.IdGenerator\n    const parts: Array<Response.ToolCallPartEncoded> = []\n\n    for (const part of contentParts) {\n      if (\"functionCall\" in part && Predicate.isNotUndefined(part.functionCall)) {\n        parts.push({\n          type: \"tool-call\",\n          id: yield* idGenerator.generateId(),\n          name: part.functionCall.name,\n          params: part.functionCall.args,\n          metadata: { google: { thoughtSignature: part.thoughtSignature } }\n        })\n      }\n    }\n\n    return parts\n  }\n)\n"
  },
  {
    "path": "packages/ai/google/src/GoogleTool.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Tool from \"@effect/ai/Tool\"\nimport * as Generated from \"./Generated.js\"\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const CodeExecution = Tool.providerDefined({\n  id: \"google.code_execution\",\n  toolkitName: \"GoogleCodeExecution\",\n  providerName: \"code_execution\",\n  args: {},\n  parameters: Generated.ExecutableCode.fields,\n  success: Generated.CodeExecutionResult\n})\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const GoogleSearch = Tool.providerDefined({\n  id: \"google.google_search\",\n  toolkitName: \"GoogleSearch\",\n  providerName: \"google_search\",\n  args: {}\n})\n\n/**\n * Gemini 1.5 support a legacy tool named `google_search_retrieval`. This tool\n * provides a dynamic mode that allows the model to decide whether to perform a\n * search based on its confidence that the prompt requires fresh information.\n *\n * If the model's confidence is above a `dynamic_threshold` you set (a value\n * between `0.0` and `1.0`), it will perform a search.\n *\n * **Note**: The `google_search` tool is recommended for Gemini 2.0 and later.\n *\n * @since 1.0.0\n * @category Tools\n */\nexport const GoogleSearchRetrieval = Tool.providerDefined({\n  id: \"google.google_search_retrieval\",\n  toolkitName: \"GoogleSearchRetrieval\",\n  providerName: \"google_search_retrieval\",\n  args: Generated.DynamicRetrievalConfig.fields\n})\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const UrlContext = Tool.providerDefined({\n  id: \"google.url_context\",\n  toolkitName: \"GoogleUrlContext\",\n  providerName: \"url_context\",\n  args: {}\n})\n"
  },
  {
    "path": "packages/ai/google/src/index.ts",
    "content": "/**\n * @since 1.0.0\n */\nexport * as Generated from \"./Generated.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as GoogleClient from \"./GoogleClient.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as GoogleConfig from \"./GoogleConfig.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as GoogleLanguageModel from \"./GoogleLanguageModel.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as GoogleTool from \"./GoogleTool.js\"\n"
  },
  {
    "path": "packages/ai/google/src/internal/utilities.ts",
    "content": "import type * as Response from \"@effect/ai/Response\"\nimport type {\n  JsonSchema7,\n  JsonSchema7AnyOf,\n  JsonSchema7Array,\n  JsonSchema7Enum,\n  JsonSchema7Integer,\n  JsonSchema7Number,\n  JsonSchema7Object,\n  JsonSchema7String,\n  JsonSchemaAnnotations\n} from \"effect/JSONSchema\"\nimport * as Predicate from \"effect/Predicate\"\nimport type { Mutable } from \"effect/Types\"\nimport type { CandidateFinishReason, Schema, Type } from \"../Generated.js\"\n\n/** @internal */\nexport const ProviderOptionsKey = \"@effect/ai-google/GoogleLanguageModel/ProviderOptions\"\n\n/** @internal */\nexport const ProviderMetadataKey = \"@effect/ai-google/GoogleLanguageModel/ProviderMetadata\"\n\nconst finishReasonMap: Record<typeof CandidateFinishReason.Type, Response.FinishReason> = {\n  BLOCKLIST: \"content-filter\",\n  FINISH_REASON_UNSPECIFIED: \"other\",\n  IMAGE_OTHER: \"other\",\n  IMAGE_PROHIBITED_CONTENT: \"content-filter\",\n  IMAGE_RECITATION: \"content-filter\",\n  IMAGE_SAFETY: \"content-filter\",\n  LANGUAGE: \"content-filter\",\n  MALFORMED_FUNCTION_CALL: \"error\",\n  MAX_TOKENS: \"length\",\n  MISSING_THOUGHT_SIGNATURE: \"error\",\n  NO_IMAGE: \"other\",\n  OTHER: \"other\",\n  PROHIBITED_CONTENT: \"content-filter\",\n  RECITATION: \"content-filter\",\n  SAFETY: \"content-filter\",\n  SPII: \"content-filter\",\n  STOP: \"stop\",\n  TOO_MANY_TOOL_CALLS: \"error\",\n  UNEXPECTED_TOOL_CALL: \"error\"\n}\n\n/** @internal */\nexport const resolveFinishReason = (\n  finishReason: typeof CandidateFinishReason.Type | undefined,\n  hasToolCalls: boolean\n): Response.FinishReason => {\n  if (Predicate.isUndefined(finishReason)) {\n    return \"unknown\"\n  }\n  if (finishReason === \"STOP\" && hasToolCalls) {\n    return \"tool-calls\"\n  }\n  const reason = finishReasonMap[finishReason]\n  return Predicate.isUndefined(reason) ? \"unknown\" : reason\n}\n\n/** @internal */\nexport const jsonSchemaToOpenApiSchema = (schema: JsonSchema7): typeof Schema.Encoded => {\n  // Handle special $id types\n  if (\"$id\" in schema) {\n    switch (schema.$id) {\n      case \"/schemas/never\":\n        // Gemini doesn't have a direct \"never\" type, but we can simulate it\n        // by creating a schema that can never be satisfied\n        return {\n          type: \"OBJECT\",\n          properties: {},\n          required: [\"impossible_required_field\"]\n        }\n\n      case \"/schemas/any\":\n      case \"/schemas/unknown\":\n        // For any/unknown, we create a schema that accepts any type\n        return {\n          type: \"OBJECT\",\n          description: schema.description || \"Any value\"\n        }\n\n      case \"/schemas/void\":\n        return {\n          type: \"NULL\",\n          description: schema.description || \"Void\"\n        }\n\n      case \"/schemas/object\":\n        return {\n          type: \"OBJECT\",\n          description: schema.description\n        }\n    }\n  }\n\n  // Handle $ref\n  if (\"$ref\" in schema) {\n    // In a real implementation, you would resolve the reference\n    // For now, we'll throw an error indicating this needs to be resolved\n    throw new Error(`Reference resolution not implemented: ${schema.$ref}`)\n  }\n\n  // Handle enum\n  if (\"enum\" in schema) {\n    const enumSchema = schema as JsonSchema7Enum\n    const result: typeof Schema.Encoded = {\n      type: determineEnumType(enumSchema.enum),\n      enum: enumSchema.enum.map(String), // Convert to strings for Gemini\n      ...extractAnnotations(enumSchema)\n    }\n\n    return result\n  }\n\n  // Handle null type\n  if (\"type\" in schema && schema.type === \"null\") {\n    return {\n      type: \"NULL\",\n      ...extractAnnotations(schema)\n    }\n  }\n\n  // Handle string type\n  if (\"type\" in schema && schema.type === \"string\") {\n    const stringSchema = schema as JsonSchema7String\n    const result: Mutable<typeof Schema.Encoded> = {\n      type: \"STRING\",\n      ...extractAnnotations(stringSchema)\n    }\n\n    if (stringSchema.minLength !== undefined) result.minLength = stringSchema.minLength.toString()\n    if (stringSchema.maxLength !== undefined) result.maxLength = stringSchema.maxLength.toString()\n    if (stringSchema.pattern !== undefined) result.pattern = stringSchema.pattern\n    if (stringSchema.format !== undefined) result.format = stringSchema.format\n\n    return result\n  }\n\n  // Handle number type\n  if (\"type\" in schema && schema.type === \"number\") {\n    const numberSchema = schema as JsonSchema7Number\n    const result: Mutable<typeof Schema.Encoded> = {\n      type: \"NUMBER\",\n      ...extractAnnotations(numberSchema)\n    }\n\n    if (numberSchema.minimum !== undefined) result.minimum = numberSchema.minimum\n    if (numberSchema.maximum !== undefined) result.maximum = numberSchema.maximum\n\n    return result\n  }\n\n  // Handle integer type\n  if (\"type\" in schema && schema.type === \"integer\") {\n    const integerSchema = schema as JsonSchema7Integer\n    const result: Mutable<typeof Schema.Encoded> = {\n      type: \"INTEGER\",\n      ...extractAnnotations(integerSchema)\n    }\n\n    if (integerSchema.minimum !== undefined) result.minimum = integerSchema.minimum\n    if (integerSchema.maximum !== undefined) result.maximum = integerSchema.maximum\n\n    return result\n  }\n\n  // Handle boolean type\n  if (\"type\" in schema && schema.type === \"boolean\") {\n    return {\n      type: \"BOOLEAN\",\n      ...extractAnnotations(schema)\n    }\n  }\n\n  // Handle array type\n  if (\"type\" in schema && schema.type === \"array\") {\n    const arraySchema = schema as JsonSchema7Array\n    const result: Mutable<typeof Schema.Encoded> = {\n      type: \"ARRAY\",\n      ...extractAnnotations(arraySchema)\n    }\n\n    if (arraySchema.minItems !== undefined) result.minItems = arraySchema.minItems.toString()\n    if (arraySchema.maxItems !== undefined) result.maxItems = arraySchema.maxItems.toString()\n\n    if (arraySchema.items) {\n      if (Array.isArray(arraySchema.items)) {\n        // Tuple validation - Gemini doesn't directly support this\n        // We'll use the first item type as a simplification\n        if (arraySchema.items.length > 0) {\n          result.items = jsonSchemaToOpenApiSchema(arraySchema.items[0])\n        }\n      } else {\n        result.items = jsonSchemaToOpenApiSchema(arraySchema.items)\n      }\n    }\n\n    return result\n  }\n\n  // Handle anyOf\n  if (\"anyOf\" in schema) {\n    const anyOfSchema = schema as JsonSchema7AnyOf\n    const result: typeof Schema.Encoded = {\n      anyOf: anyOfSchema.anyOf.map((s) => jsonSchemaToOpenApiSchema(s)),\n      ...extractAnnotations(anyOfSchema)\n    } as any\n\n    return result\n  }\n\n  // Handle object type\n  if (\"type\" in schema && schema.type === \"object\") {\n    const objectSchema = schema as JsonSchema7Object\n    const result: Mutable<typeof Schema.Encoded> = {\n      type: \"OBJECT\",\n      ...extractAnnotations(objectSchema)\n    }\n\n    if (objectSchema.properties) {\n      result.properties = {}\n      for (const [key, value] of Object.entries(objectSchema.properties)) {\n        ;(result.properties as any)[key] = jsonSchemaToOpenApiSchema(value)\n      }\n    }\n\n    if (objectSchema.required && objectSchema.required.length > 0) {\n      result.required = objectSchema.required\n    }\n\n    // Note: Gemini doesn't directly support additionalProperties, patternProperties, or propertyNames\n    // These would need special handling in a production implementation\n\n    return result\n  }\n\n  // Default fallback\n  return {\n    type: \"OBJECT\",\n    ...extractAnnotations(schema)\n  }\n}\n\n/**\n * Extracts common annotations from JsonSchema7 to Gemini format\n */\nconst extractAnnotations = (schema: JsonSchemaAnnotations): Partial<typeof Schema.Encoded> => {\n  const result: Partial<Mutable<typeof Schema.Encoded>> = {}\n  if (schema.title) result.title = schema.title\n  if (schema.description) result.description = schema.description\n  return result\n}\n\n/**\n * Determines the Gemini type for an enum based on its values\n */\nconst determineEnumType = (enumValues: Array<string | number | boolean>): typeof Type.Encoded => {\n  if (enumValues.every((v) => typeof v === \"string\")) return \"STRING\"\n  if (enumValues.every((v) => typeof v === \"number\")) return \"NUMBER\"\n  if (enumValues.every((v) => typeof v === \"boolean\")) return \"BOOLEAN\"\n  // Mixed types default to STRING\n  return \"STRING\"\n}\n"
  },
  {
    "path": "packages/ai/google/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"references\": [\n    { \"path\": \"../ai/tsconfig.build.json\" },\n    { \"path\": \"../../effect/tsconfig.build.json\" },\n    { \"path\": \"../../experimental/tsconfig.build.json\" },\n    { \"path\": \"../../platform/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/google/tsconfig.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/ai/google/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"references\": [\n    { \"path\": \"../ai/tsconfig.src.json\" },\n    { \"path\": \"../../effect/tsconfig.src.json\" },\n    { \"path\": \"../../experimental/tsconfig.src.json\" },\n    { \"path\": \"../../platform/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\",\n    \"outDir\": \"build/src\",\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/google/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../../vitest/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"noEmit\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/google/vitest.config.ts",
    "content": "import { mergeConfig, type ViteUserConfig } from \"vitest/config\"\nimport shared from \"../../../vitest.shared.js\"\n\nconst config: ViteUserConfig = {}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/ai/openai/CHANGELOG.md",
    "content": "# @effect/ai-openai\n\n## 0.39.0\n\n### Patch Changes\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n  - @effect/ai@0.35.0\n  - @effect/experimental@0.60.0\n  - @effect/platform@0.96.0\n\n## 0.38.0\n\n### Patch Changes\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n  - @effect/ai@0.34.0\n  - @effect/experimental@0.59.0\n  - @effect/platform@0.95.0\n\n## 0.37.2\n\n### Patch Changes\n\n- [#5949](https://github.com/Effect-TS/effect/pull/5949) [`577f839`](https://github.com/Effect-TS/effect/commit/577f839e00bc74bccb96444e53b9d710310b50e3) Thanks @thewilkybarkid! - Ensure OpenAI headers are redacted\n\n## 0.37.1\n\n### Patch Changes\n\n- [#5938](https://github.com/Effect-TS/effect/pull/5938) [`72f61be`](https://github.com/Effect-TS/effect/commit/72f61be280fdda98eb3835b3d559d6d5031699dc) Thanks @tensor2077! - Fix streaming decode: response.output_item.added may emit web_search_call without action (when status=\"in_progress\").\n\n- Updated dependencies [[`65e9e35`](https://github.com/Effect-TS/effect/commit/65e9e35157cbdfb40826ddad34555c4ebcf7c0b0), [`ee69cd7`](https://github.com/Effect-TS/effect/commit/ee69cd796feb3d8d1046f52edd8950404cd4ed0e), [`488d6e8`](https://github.com/Effect-TS/effect/commit/488d6e870eda3dfc137f4940bb69416f61ed8fe3), [`ba9e790`](https://github.com/Effect-TS/effect/commit/ba9e7908a80a55f24217c88af4f7d89a4f7bc0e4)]:\n  - @effect/platform@0.94.1\n  - effect@3.19.14\n  - @effect/ai@0.33.1\n\n## 0.37.0\n\n### Patch Changes\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n  - @effect/platform@0.94.0\n  - @effect/ai@0.33.0\n  - @effect/experimental@0.58.0\n\n## 0.36.0\n\n### Minor Changes\n\n- [#5850](https://github.com/Effect-TS/effect/pull/5850) [`1ddd4e4`](https://github.com/Effect-TS/effect/commit/1ddd4e477a9677fb3820f80450a378d3550d31a7) Thanks @IMax153! - Update the generated OpenAI schema definitions\n\n### Patch Changes\n\n- Updated dependencies [[`96c9537`](https://github.com/Effect-TS/effect/commit/96c9537f73a87a651c348488bdce7efbfd8360d1)]:\n  - @effect/experimental@0.57.10\n\n## 0.35.0\n\n### Patch Changes\n\n- Updated dependencies [[`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - effect@3.19.0\n  - @effect/platform@0.93.0\n  - @effect/ai@0.32.0\n  - @effect/experimental@0.57.0\n\n## 0.34.0\n\n### Minor Changes\n\n- [#5621](https://github.com/Effect-TS/effect/pull/5621) [`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825) Thanks @IMax153! - Remove `Either` / `EitherEncoded` from tool call results.\n\n  Specifically, the encoding of tool call results as an `Either` / `EitherEncoded` has been removed and is replaced by encoding the tool call success / failure directly into the `result` property.\n\n  To allow type-safe discrimination between a tool call result which was a success vs. one that was a failure, an `isFailure` property has also been added to the `\"tool-result\"` part. If `isFailure` is `true`, then the tool call handler result was an error.\n\n  ```ts\n  import * as AnthropicClient from \"@effect/ai-anthropic/AnthropicClient\"\n  import * as AnthropicLanguageModel from \"@effect/ai-anthropic/AnthropicLanguageModel\"\n  import * as LanguageModel from \"@effect/ai/LanguageModel\"\n  import * as Tool from \"@effect/ai/Tool\"\n  import * as Toolkit from \"@effect/ai/Toolkit\"\n  import * as NodeHttpClient from \"@effect/platform-node/NodeHttpClient\"\n  import { Config, Effect, Layer, Schema, Stream } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"An example of a tool with success and failure types\",\n    failureMode: \"return\", // Return errors in the response\n    parameters: { bar: Schema.Number },\n    success: Schema.Number,\n    failure: Schema.Struct({ reason: Schema.Literal(\"reason-1\", \"reason-2\") })\n  })\n\n  const MyToolkit = Toolkit.make(MyTool)\n\n  const MyToolkitLayer = MyToolkit.toLayer({\n    MyTool: () => Effect.succeed(42)\n  })\n\n  const program = LanguageModel.streamText({\n    prompt: \"Tell me about the meaning of life\",\n    toolkit: MyToolkit\n  }).pipe(\n    Stream.runForEach((part) => {\n      if (part.type === \"tool-result\" && part.name === \"MyTool\") {\n        // The `isFailure` property can be used to discriminate whether the result\n        // of a tool call is a success or a failure\n        if (part.isFailure) {\n          part.result\n          //   ^? { readonly reason: \"reason-1\" | \"reason-2\"; }\n        } else {\n          part.result\n          //   ^? number\n        }\n      }\n      return Effect.void\n    }),\n    Effect.provide(Claude)\n  )\n\n  const Anthropic = AnthropicClient.layerConfig({\n    apiKey: Config.redacted(\"ANTHROPIC_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(Effect.provide([Anthropic, MyToolkitLayer]), Effect.runPromise)\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825)]:\n  - @effect/ai@0.31.0\n\n## 0.33.0\n\n### Minor Changes\n\n- [#5614](https://github.com/Effect-TS/effect/pull/5614) [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652) Thanks @IMax153! - Previously, tool call handler errors were _always_ raised as an expected error in the Effect `E` channel at the point of execution of the tool call handler (i.e. when a `generate*` method is invoked on a `LanguageModel`).\n\n  With this PR, the end user now has control over whether tool call handler errors should be raised as an Effect error, or returned by the SDK to allow, for example, sending that error information to another application.\n\n  ### Tool Call Specification\n\n  The `Tool.make` and `Tool.providerDefined` constructors now take an extra optional parameter called `failureMode`, which can be set to either `\"error\"` or `\"return\"`.\n\n  ```ts\n  import { Tool } from \"@effect/ai\"\n  import { Schema } from \"effect\"\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"My special tool\",\n    failureMode: \"return\" // \"error\" (default) or \"return\"\n    parameters: {\n      myParam: Schema.String\n    },\n    success: Schema.Struct({\n      mySuccess: Schema.String\n    }),\n    failure: Schema.Struct({\n      myFailure: Schema.String\n    })\n  })\n\n  ```\n\n  The semantics of `failureMode` are as follows:\n  - If set to `\"error\"` (the default), errors that occur during tool call handler execution will be returned in the error channel of the calling effect\n  - If set to `\"return\"`, errors that occur during tool call handler execution will be captured and returned as part of the tool call result\n\n  ### Response - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a large language model provider response is now represented as an `Either`.\n  - If the `result` is a `Left`, the `result` will be the `failure` specified in the tool call specification\n  - If the `result` is a `Right`, the `result` will be the `success` specified in the tool call specification\n\n  This is only relevant if the end user sets `failureMode` to `\"return\"`. If set to `\"error\"` (the default), then the `result` property will always be a `Right` with the successful result of the tool call handler.\n\n  Similarly the `encodedResult` field of a `\"tool-result\"` part will be represented as an `EitherEncoded`, where:\n  - `{ _tag: \"Left\", left: <failure> }` represents a tool call handler failure\n  - `{ _tag: \"Right\", right: <success> }` represents a tool call handler success\n\n  ### Prompt - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a prompt will now only accept an `EitherEncoded` as specified above.\n\n### Patch Changes\n\n- Updated dependencies [[`6ae2f5d`](https://github.com/Effect-TS/effect/commit/6ae2f5da45a9ed9832605eca12b3e2bf2e2a1a67), [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652)]:\n  - effect@3.18.4\n  - @effect/ai@0.30.0\n\n## 0.32.1\n\n### Patch Changes\n\n- [#5601](https://github.com/Effect-TS/effect/pull/5601) [`8048b44`](https://github.com/Effect-TS/effect/commit/8048b443170f0a24873dc1f1043e8ab9ee111435) Thanks @janglad! - Fix FilePart validation always returning an MalformedInput error\n\n## 0.32.0\n\n### Patch Changes\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2), [`f8b93ac`](https://github.com/Effect-TS/effect/commit/f8b93ac6446efd3dd790778b0fc71d299a38f272)]:\n  - effect@3.18.0\n  - @effect/ai@0.29.0\n  - @effect/platform@0.92.0\n  - @effect/experimental@0.56.0\n\n## 0.31.1\n\n### Patch Changes\n\n- [#5554](https://github.com/Effect-TS/effect/pull/5554) [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a) Thanks @IMax153! - Improve the information available to the user following a model response error\n\n- Updated dependencies [[`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a), [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a), [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a), [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a), [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a), [`800ab2e`](https://github.com/Effect-TS/effect/commit/800ab2e6d983ed424deb10aebee720cfc666df7a)]:\n  - @effect/ai@0.28.2\n\n## 0.31.0\n\n### Patch Changes\n\n- Updated dependencies [[`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a)]:\n  - @effect/platform@0.91.0\n  - @effect/ai@0.28.0\n  - @effect/experimental@0.55.0\n\n## 0.30.2\n\n### Patch Changes\n\n- [#5545](https://github.com/Effect-TS/effect/pull/5545) [`f71a731`](https://github.com/Effect-TS/effect/commit/f71a7319c52ae2a66f1266d8777d8de94e7db3cb) Thanks @timurrakhimzhan! - fixed message shape of tool call result being sent to openai for tool call result\n\n## 0.30.1\n\n### Patch Changes\n\n- [#5521](https://github.com/Effect-TS/effect/pull/5521) [`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80) Thanks @IMax153! - Fix provider metadata and parse tool call parameters safely\n\n- Updated dependencies [[`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80)]:\n  - @effect/ai@0.27.1\n\n## 0.30.0\n\n### Minor Changes\n\n- [#5469](https://github.com/Effect-TS/effect/pull/5469) [`42b914a`](https://github.com/Effect-TS/effect/commit/42b914a0e8750350ce17d434afaec7d655ddf4b7) Thanks @IMax153! - Refactor the Effect AI SDK and associated provider packages\n\n  This pull request contains a complete refactor of the base Effect AI SDK package\n  as well as the associated provider integration packages to improve flexibility\n  and enhance ergonomics. Major changes are outlined below.\n\n  ## Modules\n\n  All modules in the base Effect AI SDK have had the leading `Ai` prefix dropped\n  from their name (except for the `AiError` module).\n\n  For example, the `AiLanguageModel` module is now the `LanguageModel` module.\n\n  In addition, the `AiInput` module has been renamed to the `Prompt` module.\n\n  ## Prompts\n\n  The `Prompt` module has been completely redesigned with flexibility in mind.\n\n  The `Prompt` module now supports building a prompt using either the constructors\n  exposed from the `Prompt` module, or using raw prompt content parts / messages,\n  which should be familiar to those coming from other AI SDKs.\n\n  In addition, the `system` option has been removed from all `LanguageModel` methods\n  and must now be provided as part of the prompt.\n\n  **Prompt Constructors**\n\n  ```ts\n  import { LanguageModel, Prompt } from \"@effect/ai\"\n\n  const textPart = Prompt.makePart(\"text\", {\n    text: \"What is machine learning?\"\n  })\n\n  const userMessage = Prompt.makeMessage(\"user\", {\n    content: [textPart]\n  })\n\n  const systemMessage = Prompt.makeMessage(\"system\", {\n    content: \"You are an expert in machine learning\"\n  })\n\n  const program = LanguageModel.generateText({\n    prompt: Prompt.fromMessages([systemMessage, userMessage])\n  })\n  ```\n\n  **Raw Prompt Input**\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n\n  const program = LanguageModel.generateText({\n    prompt: [\n      { role: \"system\", content: \"You are an expert in machine learning\" },\n      {\n        role: \"user\",\n        content: [{ type: \"text\", text: \"What is machine learning?\" }]\n      }\n    ]\n  })\n  ```\n\n  **NOTE**: Providing a plain string as a prompt is still supported, and will be converted\n  internally into a user message with a single text content part.\n\n  ### Provider-Specific Options\n\n  To support specification of provider-specific options when interacting with large\n  language model providers, support has been added for adding provider-specific\n  options to the parts of a `Prompt`.\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-sonnet-4-20250514\")\n\n  const program = LanguageModel.generateText({\n    prompt: [\n      {\n        role: \"user\",\n        content: [{ type: \"text\", text: \"What is machine learning?\" }],\n        options: {\n          anthropic: { cacheControl: { type: \"ephemeral\", ttl: \"1h\" } }\n        }\n      }\n    ]\n  }).pipe(Effect.provide(Claude))\n  ```\n\n  ## Responses\n\n  The `Response` module has also been completely redesigned to support a wider\n  variety of response parts, particularly when streaming.\n\n  ### Streaming Responses\n\n  When streaming text via the `LanguageModel.streamText` method, you will now\n  receive a stream of content parts instead of a stream of responses, which should\n  make it much simpler to filter down the stream to the parts you are interested in.\n\n  In addition, additional content parts will be present in the stream to allow you to track,\n  for example, when a text content part starts / ends.\n\n  ### Tool Calls / Tool Call Results\n\n  The decoded parts of a `Response` (as returned by the methods of `LanguageModel`)\n  are now fully type-safe on tool calls / tool call results. Filtering the content parts of a\n  response to tool calls will narrow the type of the tool call `params` based on the tool\n  `name`. Similarly, filtering the response to tool call results will narrow the type of the\n  tool call `result` based on the tool `name`.\n\n  ```ts\n  import { LanguageModel, Tool, Toolkit } from \"@effect/ai\"\n  import { Effect, Schema } from \"effect\"\n\n  const DadJokeTool = Tool.make(\"DadJokeTool\", {\n    parameters: { topic: Schema.String },\n    success: Schema.Struct({ joke: Schema.String })\n  })\n\n  const FooTool = Tool.make(\"FooTool\", {\n    parameters: { foo: Schema.Number },\n    success: Schema.Struct({ bar: Schema.Boolean })\n  })\n\n  const MyToolkit = Toolkit.make(DadJokeTool, FooTool)\n\n  const program = Effect.gen(function* () {\n    const response = yield* LanguageModel.generateText({\n      prompt: \"Tell me a dad joke\",\n      toolkit: MyToolkit\n    })\n\n    for (const toolCall of response.toolCalls) {\n      if (toolCall.name === \"DadJokeTool\") {\n        //         ^? \"DadJokeTool\" | \"FooTool\"\n        toolCall.params\n        //       ^? { readonly topic: string }\n      }\n    }\n\n    for (const toolResult of response.toolResults) {\n      if (toolResult.name === \"DadJokeTool\") {\n        //           ^? \"DadJokeTool\" | \"FooTool\"\n        toolResult.result\n        //         ^? { readonly joke: string }\n      }\n    }\n  })\n  ```\n\n  ### Provider Metadata\n\n  As with provider-specific options, provider-specific metadata is now returned as\n  part of the response from the large language model provider.\n\n  ```ts\n  import { LanguageModel } from \"@effect/ai\"\n  import { AnthropicLanguageModel } from \"@effect/ai-anthropic\"\n  import { Effect } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const program = Effect.gen(function* () {\n    const response = yield* LanguageModel.generateText({\n      prompt: \"What is the meaning of life?\"\n    })\n\n    for (const part of response.content) {\n      // When metadata **is not** defined for a content part, accessing the\n      // provider's key on the part's metadata will return an untyped record\n      if (part.type === \"text\") {\n        const metadata = part.metadata.anthropic\n        //    ^? { readonly [x: string]: unknown } | undefined\n      }\n      // When metadata **is** defined for a content part, accessing the\n      // provider's key on the part's metadata will return typed metadata\n      if (part.type === \"reasoning\") {\n        const metadata = part.metadata.anthropic\n        //    ^? AnthropicReasoningInfo | undefined\n      }\n    }\n  }).pipe(Effect.provide(Claude))\n  ```\n\n  ## Tool Calls\n\n  The `Tool` module has been enhanced to support provider-defined tools (e.g.\n  web search, computer use, etc.). Large language model providers which support\n  calling their own tools now have a separate module present in their provider\n  integration packages which contain definitions for their tools.\n\n  These provider-defined tools can be included alongside user-defined tools in\n  existing `Toolkit`s. Provider-defined tools that require a user-space handler\n  will be raise a type error in the associated `Toolkit` layer if no such handler\n  is defined.\n\n  ```ts\n  import { LanguageModel, Tool, Toolkit } from \"@effect/ai\"\n  import { AnthropicTool } from \"@effect/ai-anthropic\"\n  import { Schema } from \"effect\"\n\n  const DadJokeTool = Tool.make(\"DadJokeTool\", {\n    parameters: { topic: Schema.String },\n    success: Schema.Struct({ joke: Schema.String })\n  })\n\n  const MyToolkit = Toolkit.make(\n    DadJokeTool,\n    AnthropicTool.WebSearch_20250305({ max_uses: 1 })\n  )\n\n  const program = LanguageModel.generateText({\n    prompt: \"Search the web for a dad joke\",\n    toolkit: MyToolkit\n  })\n  ```\n\n  ## AiError\n\n  The `AiError` type has been refactored into a union of different error types\n  which can be raised by the Effect AI SDK. The goal of defining separate error\n  types is to allow providing the end-user with more granular information about\n  the error that occurred.\n\n  For now, the following errors have been defined. More error types may be added\n  over time based upon necessity / use case.\n\n  ```ts\n  type AiError =\n    | HttpRequestError,\n    | HttpResponseError,\n    | MalformedInput,\n    | MalformedOutput,\n    | UnknownError\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`42b914a`](https://github.com/Effect-TS/effect/commit/42b914a0e8750350ce17d434afaec7d655ddf4b7)]:\n  - @effect/ai@0.27.0\n\n## 0.29.1\n\n### Patch Changes\n\n- [#5450](https://github.com/Effect-TS/effect/pull/5450) [`e7aa8c2`](https://github.com/Effect-TS/effect/commit/e7aa8c2bf95bd36294e4549afbface1aac0fe879) Thanks @IMax153! - Ensure that the verbose json transcription schema is tried before the standard json schema\n\n## 0.29.0\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/ai@0.26.0\n  - @effect/experimental@0.54.6\n\n## 0.28.2\n\n### Patch Changes\n\n- [#5361](https://github.com/Effect-TS/effect/pull/5361) [`292a7c5`](https://github.com/Effect-TS/effect/commit/292a7c54050e3d06a203130f3545207ec5ac633d) Thanks @IMax153! - Add support for new options related to OpenAi GPT-5\n\n- Updated dependencies [[`292a7c5`](https://github.com/Effect-TS/effect/commit/292a7c54050e3d06a203130f3545207ec5ac633d)]:\n  - @effect/ai@0.25.2\n\n## 0.28.1\n\n### Patch Changes\n\n- [#5314](https://github.com/Effect-TS/effect/pull/5314) [`a656185`](https://github.com/Effect-TS/effect/commit/a656185b967fc51632f42b5081ab78e4e41752bd) Thanks @dmaretskyi! - Allow `completion_tokens_details` field to be missing in the generation response for compatibility with Ollama and LMStudio\n\n## 0.28.0\n\n### Patch Changes\n\n- Updated dependencies [[`5a0f4f1`](https://github.com/Effect-TS/effect/commit/5a0f4f176687a39d9fa46bb894bb7ac3175b0e87)]:\n  - effect@3.17.1\n  - @effect/ai@0.25.0\n  - @effect/experimental@0.54.0\n\n## 0.27.0\n\n### Patch Changes\n\n- Updated dependencies [[`7813640`](https://github.com/Effect-TS/effect/commit/7813640279d9e3a3e7fc0a29bfb5c6d5fb3c270f)]:\n  - @effect/platform@0.90.0\n  - @effect/ai@0.24.0\n  - @effect/experimental@0.54.0\n\n## 0.26.1\n\n### Patch Changes\n\n- [#5251](https://github.com/Effect-TS/effect/pull/5251) [`eb197b2`](https://github.com/Effect-TS/effect/commit/eb197b2cca3debdd17da77715311e1849aaa5d05) Thanks @IMax153! - Add `\"scale\"` as an option for the OpenAI `service_tier` field\n\n## 0.26.0\n\n### Patch Changes\n\n- Updated dependencies [[`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9), [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104), [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63), [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c), [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989), [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636), [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2), [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d)]:\n  - effect@3.17.0\n  - @effect/ai@0.23.0\n  - @effect/experimental@0.53.0\n  - @effect/platform@0.89.0\n\n## 0.25.3\n\n### Patch Changes\n\n- [#5227](https://github.com/Effect-TS/effect/pull/5227) [`c639456`](https://github.com/Effect-TS/effect/commit/c6394569196c073c00887caba8882bbc40ce708f) Thanks @IMax153! - Update the generated openapi specification for OpenAI\n\n## 0.25.2\n\n### Patch Changes\n\n- Updated dependencies [[`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec), [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38), [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48)]:\n  - effect@3.16.14\n  - @effect/platform@0.88.1\n  - @effect/experimental@0.52.1\n  - @effect/ai@0.22.1\n\n## 0.25.1\n\n### Patch Changes\n\n- [#5209](https://github.com/Effect-TS/effect/pull/5209) [`3deaa66`](https://github.com/Effect-TS/effect/commit/3deaa66e022e361a2036ce6bfc9d76f77d9cc948) Thanks @tim-smart! - fix ai layerConfig regression, to allow for conditional Config variables\n\n## 0.25.0\n\n### Patch Changes\n\n- Updated dependencies [[`27206d7`](https://github.com/Effect-TS/effect/commit/27206d7f0558d7fe28de57bf54f1d0cc83acc92e), [`dbabf5e`](https://github.com/Effect-TS/effect/commit/dbabf5e76fa63b050d2b6c466713c7dc59f07d3c)]:\n  - @effect/platform@0.88.0\n  - @effect/ai@0.22.0\n  - @effect/experimental@0.52.0\n\n## 0.24.17\n\n### Patch Changes\n\n- Updated dependencies [[`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7), [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db)]:\n  - effect@3.16.13\n  - @effect/ai@0.21.17\n  - @effect/experimental@0.51.14\n  - @effect/platform@0.87.13\n\n## 0.24.16\n\n### Patch Changes\n\n- [#5186](https://github.com/Effect-TS/effect/pull/5186) [`e5692ab`](https://github.com/Effect-TS/effect/commit/e5692ab2be157b885f449ffb5c5f022eca04a59e) Thanks @IMax153! - Do not use `Config.Wrap` for AI provider `layerConfig`\n\n- Updated dependencies [[`32ba77a`](https://github.com/Effect-TS/effect/commit/32ba77ae304d2161362a73e8b61965332626cf2d), [`d5e25b2`](https://github.com/Effect-TS/effect/commit/d5e25b237f05670ee42b386cb40b2cb448fc11d7)]:\n  - @effect/platform@0.87.12\n  - @effect/ai@0.21.16\n  - @effect/experimental@0.51.13\n\n## 0.24.15\n\n### Patch Changes\n\n- Updated dependencies [[`001392b`](https://github.com/Effect-TS/effect/commit/001392ba8bfcad101bb034348a7415012fb12f72), [`7bfb099`](https://github.com/Effect-TS/effect/commit/7bfb099cb5528511b8d63045c4fbb4dc9cb18528)]:\n  - @effect/platform@0.87.11\n  - @effect/ai@0.21.15\n  - @effect/experimental@0.51.12\n\n## 0.24.14\n\n### Patch Changes\n\n- Updated dependencies [[`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0), [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0)]:\n  - @effect/platform@0.87.10\n  - @effect/ai@0.21.14\n  - @effect/experimental@0.51.11\n\n## 0.24.13\n\n### Patch Changes\n\n- Updated dependencies [[`54514a2`](https://github.com/Effect-TS/effect/commit/54514a2f53166de27ad7e756dbf12194691fd4af)]:\n  - @effect/platform@0.87.9\n  - @effect/ai@0.21.13\n  - @effect/experimental@0.51.10\n\n## 0.24.12\n\n### Patch Changes\n\n- Updated dependencies [[`4ce4f82`](https://github.com/Effect-TS/effect/commit/4ce4f824f6fdef492be1d35c05a490ffce518c89)]:\n  - @effect/platform@0.87.8\n  - @effect/experimental@0.51.9\n  - @effect/ai@0.21.12\n\n## 0.24.11\n\n### Patch Changes\n\n- [#5029](https://github.com/Effect-TS/effect/pull/5029) [`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778) Thanks @IMax153! - Cleanup AiLanguageModel construction and finish basic support for gemini\n\n- Updated dependencies [[`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778), [`25ca0cf`](https://github.com/Effect-TS/effect/commit/25ca0cf141139cd44ff53081b1c877f8f3ab5e41), [`d92d12a`](https://github.com/Effect-TS/effect/commit/d92d12acb6097a4fa6c9c918faa3cd5c3fb6c778)]:\n  - @effect/ai@0.21.11\n\n## 0.24.10\n\n### Patch Changes\n\n- Updated dependencies [[`a9b617f`](https://github.com/Effect-TS/effect/commit/a9b617f125171ed76cd79ab46d7a924daf3b0e70), [`7e26e86`](https://github.com/Effect-TS/effect/commit/7e26e86524abcc93713d6ad7eee486638c98f7c2)]:\n  - @effect/platform@0.87.7\n  - @effect/ai@0.21.10\n  - @effect/experimental@0.51.8\n\n## 0.24.9\n\n### Patch Changes\n\n- Updated dependencies [[`030ac21`](https://github.com/Effect-TS/effect/commit/030ac217eac167d345a095bff26d9c95827fa64c), [`905da99`](https://github.com/Effect-TS/effect/commit/905da996aad665057b4ca6dba1a4af44fb8835bd), [`aaae9b1`](https://github.com/Effect-TS/effect/commit/aaae9b10345ab5f867b08e1c6eb21685cfc2b078)]:\n  - @effect/ai@0.21.9\n  - effect@3.16.12\n  - @effect/experimental@0.51.7\n  - @effect/platform@0.87.6\n\n## 0.24.8\n\n### Patch Changes\n\n- Updated dependencies [[`96c1292`](https://github.com/Effect-TS/effect/commit/96c129262835410b311a51d0bf7f58b8f6fc9a12)]:\n  - @effect/experimental@0.51.6\n  - @effect/ai@0.21.8\n\n## 0.24.7\n\n### Patch Changes\n\n- Updated dependencies [[`2fd8676`](https://github.com/Effect-TS/effect/commit/2fd8676c803cd40000dfc3231f5daecaa0e0ebd2)]:\n  - @effect/platform@0.87.5\n  - @effect/ai@0.21.7\n  - @effect/experimental@0.51.5\n\n## 0.24.6\n\n### Patch Changes\n\n- Updated dependencies [[`e82a4fd`](https://github.com/Effect-TS/effect/commit/e82a4fd60f6528d08cef1a4aba0abe0d3ba741ad)]:\n  - @effect/platform@0.87.4\n  - @effect/ai@0.21.6\n  - @effect/experimental@0.51.4\n\n## 0.24.5\n\n### Patch Changes\n\n- Updated dependencies [[`1b6e396`](https://github.com/Effect-TS/effect/commit/1b6e396d699f3cbbc56b68f99055cf746529bb9e)]:\n  - @effect/platform@0.87.3\n  - @effect/ai@0.21.5\n  - @effect/experimental@0.51.3\n\n## 0.24.4\n\n### Patch Changes\n\n- Updated dependencies [[`4fea68c`](https://github.com/Effect-TS/effect/commit/4fea68ca7a25a3c39a1ab68b3885534513ab0c81), [`b927954`](https://github.com/Effect-TS/effect/commit/b9279543cf5688dd8a577af80456959c615217d0), [`99590a6`](https://github.com/Effect-TS/effect/commit/99590a6ca9128eb1ede265b6670b655311995614), [`6c3e24c`](https://github.com/Effect-TS/effect/commit/6c3e24c2308f7d4a29b8f4270ab81bca22ac6bb4)]:\n  - @effect/platform@0.87.2\n  - effect@3.16.11\n  - @effect/ai@0.21.4\n  - @effect/experimental@0.51.2\n\n## 0.24.3\n\n### Patch Changes\n\n- Updated dependencies [[`faad30e`](https://github.com/Effect-TS/effect/commit/faad30ec8742916be59f9db642d0fc98225b636c)]:\n  - effect@3.16.10\n  - @effect/ai@0.21.3\n  - @effect/experimental@0.51.1\n  - @effect/platform@0.87.1\n\n## 0.24.2\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/ai@0.21.2\n  - @effect/experimental@0.51.0\n\n## 0.24.1\n\n### Patch Changes\n\n- Updated dependencies [[`f667373`](https://github.com/Effect-TS/effect/commit/f667373da3471f1e907366780f8c3ea7f52cc5c8)]:\n  - @effect/ai@0.21.1\n  - @effect/experimental@0.51.0\n\n## 0.24.0\n\n### Patch Changes\n\n- Updated dependencies [[`b5bac9a`](https://github.com/Effect-TS/effect/commit/b5bac9ac2913fcd11b02322624f03b544eef53ba)]:\n  - @effect/platform@0.87.0\n  - @effect/ai@0.21.0\n  - @effect/experimental@0.51.0\n\n## 0.23.0\n\n### Patch Changes\n\n- Updated dependencies [[`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`c23d25c`](https://github.com/Effect-TS/effect/commit/c23d25c3e7c541f1f63b28484d8c461d86c67e99), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07)]:\n  - effect@3.16.9\n  - @effect/platform@0.86.0\n  - @effect/ai@0.20.0\n  - @effect/experimental@0.50.0\n\n## 0.22.4\n\n### Patch Changes\n\n- Updated dependencies [[`a8d99b2`](https://github.com/Effect-TS/effect/commit/a8d99b2ec2f55d9aa6e7d00a5138e80380716877)]:\n  - @effect/ai@0.19.4\n  - @effect/experimental@0.49.2\n\n## 0.22.3\n\n### Patch Changes\n\n- Updated dependencies [[`914a191`](https://github.com/Effect-TS/effect/commit/914a191e7cb6341a3d0e965bccd27c336cf22e44)]:\n  - @effect/platform@0.85.2\n  - @effect/ai@0.19.3\n  - @effect/experimental@0.49.2\n\n## 0.22.2\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/ai@0.19.2\n  - @effect/experimental@0.49.1\n\n## 0.22.1\n\n### Patch Changes\n\n- Updated dependencies [[`8cb98d5`](https://github.com/Effect-TS/effect/commit/8cb98d53e68330228287ce2a2e0d8a4c86bcab3b), [`db2dd3c`](https://github.com/Effect-TS/effect/commit/db2dd3c3a8a77d791eae19e66153527e1cde4e6e)]:\n  - effect@3.16.8\n  - @effect/ai@0.19.1\n  - @effect/experimental@0.49.1\n  - @effect/platform@0.85.1\n\n## 0.22.0\n\n### Patch Changes\n\n- Updated dependencies [[`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e)]:\n  - @effect/platform@0.85.0\n  - @effect/ai@0.19.0\n  - @effect/experimental@0.49.0\n\n## 0.21.16\n\n### Patch Changes\n\n- Updated dependencies [[`daed158`](https://github.com/Effect-TS/effect/commit/daed158f2cf00175633284f075cf611c52aa2a1c)]:\n  - @effect/ai@0.18.16\n\n## 0.21.15\n\n### Patch Changes\n\n- Updated dependencies [[`c315989`](https://github.com/Effect-TS/effect/commit/c315989cade6c2a5c9cb157ad85f56b492675add)]:\n  - @effect/ai@0.18.15\n\n## 0.21.14\n\n### Patch Changes\n\n- Updated dependencies [[`1bb0d8a`](https://github.com/Effect-TS/effect/commit/1bb0d8ab96782e99434356266b38251554ea0294), [`cbac1ac`](https://github.com/Effect-TS/effect/commit/cbac1ac61a4e15ad15828563b39eef412bcee66e), [`dd4d380`](https://github.com/Effect-TS/effect/commit/dd4d3802f714d59171b1e9226a7babf9723ea952)]:\n  - effect@3.16.7\n  - @effect/ai@0.18.14\n  - @effect/experimental@0.48.12\n  - @effect/platform@0.84.11\n\n## 0.21.13\n\n### Patch Changes\n\n- Updated dependencies [[`a5f7595`](https://github.com/Effect-TS/effect/commit/a5f75956ef9a15a83c416517ef493f0ee2f5ee8a), [`a02470c`](https://github.com/Effect-TS/effect/commit/a02470c75579e91525a25adb3f21b3650d042fdd), [`aa3a819`](https://github.com/Effect-TS/effect/commit/aa3a819707c15dd39b6d9ae4b4293bd87b74e175), [`bf369b2`](https://github.com/Effect-TS/effect/commit/bf369b2902a0e0b195d957c18b9efd180942cf8b), [`f891d45`](https://github.com/Effect-TS/effect/commit/f891d45adffdafd3f94a2eca23faa354e3a409a8)]:\n  - effect@3.16.6\n  - @effect/ai@0.18.13\n  - @effect/platform@0.84.10\n  - @effect/experimental@0.48.11\n\n## 0.21.12\n\n### Patch Changes\n\n- Updated dependencies [[`bf418ef`](https://github.com/Effect-TS/effect/commit/bf418ef14a0f2ec965535793d5cea8fa8ba177ac)]:\n  - effect@3.16.5\n  - @effect/ai@0.18.12\n  - @effect/experimental@0.48.10\n  - @effect/platform@0.84.9\n\n## 0.21.11\n\n### Patch Changes\n\n- Updated dependencies [[`2dc5f93`](https://github.com/Effect-TS/effect/commit/2dc5f932f89d260e2f6139c9b89e0548d11d94c2)]:\n  - @effect/ai@0.18.11\n  - @effect/experimental@0.48.9\n\n## 0.21.10\n\n### Patch Changes\n\n- Updated dependencies [[`8b9db77`](https://github.com/Effect-TS/effect/commit/8b9db7742846af0f58fd8e8b7acb7f4f5ff487ec)]:\n  - @effect/platform@0.84.8\n  - @effect/experimental@0.48.9\n  - @effect/ai@0.18.10\n\n## 0.21.9\n\n### Patch Changes\n\n- Updated dependencies [[`74ab9a0`](https://github.com/Effect-TS/effect/commit/74ab9a0a9e16d6e019369d256e1e24175c8bc3f3), [`770008e`](https://github.com/Effect-TS/effect/commit/770008eca3aad2899a2ed951236e575793294b28)]:\n  - effect@3.16.4\n  - @effect/ai@0.18.9\n  - @effect/experimental@0.48.8\n  - @effect/platform@0.84.7\n\n## 0.21.8\n\n### Patch Changes\n\n- Updated dependencies [[`a2d57c9`](https://github.com/Effect-TS/effect/commit/a2d57c9ac596445009ca12859b78e00e5d89b936)]:\n  - @effect/experimental@0.48.7\n  - @effect/ai@0.18.8\n\n## 0.21.7\n\n### Patch Changes\n\n- Updated dependencies [[`ceea77a`](https://github.com/Effect-TS/effect/commit/ceea77a13055f145520f763e3fce5b8ff15d728f)]:\n  - @effect/platform@0.84.6\n  - @effect/ai@0.18.7\n  - @effect/experimental@0.48.6\n\n## 0.21.6\n\n### Patch Changes\n\n- Updated dependencies [[`85f54ed`](https://github.com/Effect-TS/effect/commit/85f54ed1ecf2f191de8c907247066e3631b5d7e1), [`ec52c6a`](https://github.com/Effect-TS/effect/commit/ec52c6a2211e76972462b15b9d5a9d6d56761b7a)]:\n  - @effect/ai@0.18.6\n  - @effect/platform@0.84.5\n  - @effect/experimental@0.48.5\n\n## 0.21.5\n\n### Patch Changes\n\n- Updated dependencies [[`4ddb28d`](https://github.com/Effect-TS/effect/commit/4ddb28d230d572735fe34539c1c59005d4932d8a)]:\n  - @effect/ai@0.18.5\n\n## 0.21.4\n\n### Patch Changes\n\n- Updated dependencies [[`87722fc`](https://github.com/Effect-TS/effect/commit/87722fce693a9b49284bbddbf82d30714c688261), [`36217ee`](https://github.com/Effect-TS/effect/commit/36217eeb1337edd9ac3f9a635b80a6385d22ae8f)]:\n  - effect@3.16.3\n  - @effect/ai@0.18.4\n  - @effect/experimental@0.48.4\n  - @effect/platform@0.84.4\n\n## 0.21.3\n\n### Patch Changes\n\n- Updated dependencies [[`52c88c4`](https://github.com/Effect-TS/effect/commit/52c88c4b7d20ea819b9f2efaf112d03de0a4627b), [`ab7684f`](https://github.com/Effect-TS/effect/commit/ab7684f1c2a0671bf091f255d220e3a4cc7f528e)]:\n  - @effect/ai@0.18.3\n  - @effect/platform@0.84.3\n  - @effect/experimental@0.48.3\n\n## 0.21.2\n\n### Patch Changes\n\n- Updated dependencies [[`0ddf148`](https://github.com/Effect-TS/effect/commit/0ddf148a247aa87af043d276b8453a714a400897)]:\n  - effect@3.16.2\n  - @effect/ai@0.18.2\n  - @effect/experimental@0.48.2\n  - @effect/platform@0.84.2\n\n## 0.21.1\n\n### Patch Changes\n\n- Updated dependencies [[`71174d0`](https://github.com/Effect-TS/effect/commit/71174d09691314a9b6b66189e456fd21e3eb6543), [`d615e6e`](https://github.com/Effect-TS/effect/commit/d615e6e5b944f6fd5e627e31752c7ca7e4e1c17d)]:\n  - @effect/platform@0.84.1\n  - effect@3.16.1\n  - @effect/ai@0.18.1\n  - @effect/experimental@0.48.1\n\n## 0.21.0\n\n### Minor Changes\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`0552674`](https://github.com/Effect-TS/effect/commit/055267461a3076b06dea896258f4bb2154211fcb) Thanks @IMax153! - Make `AiModel` a plain `Layer` and remove `AiPlan` in favor of `ExecutionPlan`\n\n  This release substantially simplifies and improves the ergonomics of using `AiModel` for various providers. With these changes, an `AiModel` now returns a plain `Layer` which can be used to provide services to a program that interacts with large language models.\n\n  **Before**\n\n  ```ts\n  import { AiLanguageModel } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { NodeHttpClient } from \"@effect/platform-node\"\n  import { Config, Console, Effect, Layer } from \"effect\"\n\n  // Produces an `AiModel<AiLanguageModel, OpenAiClient>`\n  const Gpt4o = OpenAiLanguageModel.model(\"gpt-4o\")\n\n  // Generate a dad joke\n  const getDadJoke = AiLanguageModel.generateText({\n    prompt: \"Tell me a dad joke\"\n  })\n\n  const program = Effect.gen(function* () {\n    // Build the `AiModel` into a `Provider`\n    const gpt4o = yield* Gpt4o\n    // Use the built `AiModel` to run the program\n    const response = yield* gpt4o.use(getDadJoke)\n    // Log the response\n    yield* Console.log(response.text)\n  })\n\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(Effect.provide(OpenAi), Effect.runPromise)\n  ```\n\n  **After**\n\n  ```ts\n  import { AiLanguageModel } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { NodeHttpClient } from \"@effect/platform-node\"\n  import { Config, Console, Effect, Layer } from \"effect\"\n\n  // Produces a `Layer<AiLanguageModel, never, OpenAiClient>`\n  const Gpt4o = OpenAiLanguageModel.model(\"gpt-4o\")\n\n  const program = Effect.gen(function*() {\n    // Generate a dad joke\n    const response = yield* AiLanguageModel.generateText({\n      prompt: \"Tell me a dad joke\"\n    })\n    // Log the response\n    yield* Console.log(response.text)\n  ).pipe(Effect.provide(Gpt4o))\n\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(\n    Effect.provide(OpenAi),\n    Effect.runPromise\n  )\n  ```\n\n  In addition, `AiModel` can be `yield*`'ed to produce a layer with no requirements.\n\n  This shifts the requirements of building the layer into the calling effect, which is particularly useful for creating AI-powered services.\n\n  ```ts\n  import { AiLanguageModel } from \"@effect/ai\"\n  import { OpenAiLanguageModel } from \"@effect/ai-openai\"\n  import { Effect } from \"effect\"\n\n  class DadJokes extends Effect.Service<DadJokes>()(\"DadJokes\", {\n    effect: Effect.gen(function* () {\n      // Yielding the model will return a layer with no requirements\n      //\n      //      ┌─── Layer<AiLanguageModel>\n      //      ▼\n      const model = yield* OpenAiLanguageModel.model(\"gpt-4o\")\n\n      const getDadJoke = AiLanguageModel.generateText({\n        prompt: \"Generate a dad joke\"\n      }).pipe(Effect.provide(model))\n\n      return { getDadJoke } as const\n    })\n  }) {}\n\n  // The requirements are lifted into the service constructor\n  //\n  //          ┌─── Layer<DadJokes, never, OpenAiClient>\n  //          ▼\n  DadJokes.Default\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`ee0bd5d`](https://github.com/Effect-TS/effect/commit/ee0bd5d24864752c54cb359f67a67dd903971ec4), [`5189800`](https://github.com/Effect-TS/effect/commit/51898004e11766b8cf6d95e960b636f6d5db79ec), [`58bfeaa`](https://github.com/Effect-TS/effect/commit/58bfeaa64ded8c88f772b184311c0c0dbac10960), [`194d748`](https://github.com/Effect-TS/effect/commit/194d7486943f56f3267ef415395ac220a4b3e634), [`0552674`](https://github.com/Effect-TS/effect/commit/055267461a3076b06dea896258f4bb2154211fcb), [`918c9ea`](https://github.com/Effect-TS/effect/commit/918c9ea1a57facb154f0fb26792021f337054dee), [`9198e6f`](https://github.com/Effect-TS/effect/commit/9198e6fcc1a3ff4fefb3363004de558d8de01f40), [`2a370bf`](https://github.com/Effect-TS/effect/commit/2a370bf625fdeede5659721468eb0d527e403279), [`58ccb91`](https://github.com/Effect-TS/effect/commit/58ccb91328c8df5d49808b673738bc09df355201), [`fd47834`](https://github.com/Effect-TS/effect/commit/fd478348203fa89462b0a1d067ce4de034353df4)]:\n  - effect@3.16.0\n  - @effect/ai@0.18.0\n  - @effect/experimental@0.48.0\n  - @effect/platform@0.84.0\n\n## 0.20.0\n\n### Patch Changes\n\n- Updated dependencies [[`5522520`](https://github.com/Effect-TS/effect/commit/55225206ab9af0ad60b1c0654690a8a096d625cd), [`cc5bb2b`](https://github.com/Effect-TS/effect/commit/cc5bb2b918a9450a975f702dabcea891bda382cb)]:\n  - @effect/platform@0.83.0\n  - effect@3.15.5\n  - @effect/ai@0.17.0\n  - @effect/experimental@0.47.0\n\n## 0.19.9\n\n### Patch Changes\n\n- Updated dependencies [[`0617b9d`](https://github.com/Effect-TS/effect/commit/0617b9dc365f1963b36949ad7f9023ab6eb94524)]:\n  - @effect/platform@0.82.8\n  - @effect/ai@0.16.9\n  - @effect/experimental@0.46.8\n\n## 0.19.8\n\n### Patch Changes\n\n- Updated dependencies [[`f570554`](https://github.com/Effect-TS/effect/commit/f57055459524587b041340577dad85476bb35f81), [`78047e8`](https://github.com/Effect-TS/effect/commit/78047e8dfc8005b66f87afe50bb95981fea51561), [`c20b95a`](https://github.com/Effect-TS/effect/commit/c20b95a99ffe452b4774c844d397a905f713b6d6), [`94ada43`](https://github.com/Effect-TS/effect/commit/94ada430928d5685bdbef513e87562c20774a3a2)]:\n  - effect@3.15.4\n  - @effect/platform@0.82.7\n  - @effect/ai@0.16.8\n  - @effect/experimental@0.46.7\n\n## 0.19.7\n\n### Patch Changes\n\n- [#4914](https://github.com/Effect-TS/effect/pull/4914) [`eef6052`](https://github.com/Effect-TS/effect/commit/eef605278e41b3b0a2218ac799f907f7a97db91c) Thanks @IMax153! - Fix an issue where passing a file input part when using OpenAI would always result in an error\n\n- Updated dependencies [[`618903b`](https://github.com/Effect-TS/effect/commit/618903ba9ae96e2bfe6ee31f61c4359b915f2a36)]:\n  - @effect/platform@0.82.6\n  - @effect/ai@0.16.7\n  - @effect/experimental@0.46.6\n\n## 0.19.6\n\n### Patch Changes\n\n- Updated dependencies [[`7764a07`](https://github.com/Effect-TS/effect/commit/7764a07d960c60df81f14e1dc949518f4bbe494a), [`4577f54`](https://github.com/Effect-TS/effect/commit/4577f548d67273e576cdde423bdd34a4b910766a), [`30a0d9c`](https://github.com/Effect-TS/effect/commit/30a0d9cb51c84290d51b1361d72ff5cee33c13c7)]:\n  - @effect/platform@0.82.5\n  - effect@3.15.3\n  - @effect/ai@0.16.6\n  - @effect/experimental@0.46.5\n\n## 0.19.5\n\n### Patch Changes\n\n- Updated dependencies [[`d45e8a8`](https://github.com/Effect-TS/effect/commit/d45e8a8ac8227192f504e39e6d04fdcf4fb1d225), [`d13b68e`](https://github.com/Effect-TS/effect/commit/d13b68e3a9456d0bfee9bca8273a7b44a9c69087)]:\n  - @effect/platform@0.82.4\n  - @effect/ai@0.16.5\n  - @effect/experimental@0.46.4\n\n## 0.19.4\n\n### Patch Changes\n\n- Updated dependencies [[`b8722b8`](https://github.com/Effect-TS/effect/commit/b8722b817e2306fe8c8245f3f9e32d85b824b961), [`a328f4b`](https://github.com/Effect-TS/effect/commit/a328f4b4fe717dd53e5b04a30f387433c32f7328)]:\n  - effect@3.15.2\n  - @effect/platform@0.82.3\n  - @effect/ai@0.16.4\n  - @effect/experimental@0.46.3\n\n## 0.19.3\n\n### Patch Changes\n\n- [#4880](https://github.com/Effect-TS/effect/pull/4880) [`b86c1fc`](https://github.com/Effect-TS/effect/commit/b86c1fc63b70e6536c691a0fde718f5f276abc7c) Thanks @IMax153! - Ensure that multiple tool calls are handled properly\n\n- [#4878](https://github.com/Effect-TS/effect/pull/4878) [`8b32eb5`](https://github.com/Effect-TS/effect/commit/8b32eb5f1267b012a261170c4fb704806e80ddea) Thanks @IMax153! - Ensure that `AiResponse.finishReason` is set properly when streaming responses from OpenAi\n\n- Updated dependencies [[`739a3d4`](https://github.com/Effect-TS/effect/commit/739a3d4a4565915fe2e690003f4f9085cb4422fc)]:\n  - @effect/platform@0.82.2\n  - @effect/ai@0.16.3\n  - @effect/experimental@0.46.2\n\n## 0.19.2\n\n### Patch Changes\n\n- Updated dependencies [[`787ce70`](https://github.com/Effect-TS/effect/commit/787ce7042e35b657963473c6efe47752868cd811), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348)]:\n  - effect@3.15.1\n  - @effect/ai@0.16.2\n  - @effect/experimental@0.46.1\n  - @effect/platform@0.82.1\n\n## 0.19.1\n\n### Patch Changes\n\n- Updated dependencies [[`cb3c30f`](https://github.com/Effect-TS/effect/commit/cb3c30f540a83dafcd6d841375073b5e069fa417)]:\n  - @effect/ai@0.16.1\n  - @effect/experimental@0.46.0\n\n## 0.19.0\n\n### Patch Changes\n\n- Updated dependencies [[`c654595`](https://github.com/Effect-TS/effect/commit/c65459587b51da140b78098e81fdbfece65d53e2), [`d9f5dea`](https://github.com/Effect-TS/effect/commit/d9f5deae0f02f5de2b9fcb1cca8b142ba4bc2bba), [`49aa723`](https://github.com/Effect-TS/effect/commit/49aa7236a15e13f818c86edbca08c4af67c8dfaf), [`74c14d0`](https://github.com/Effect-TS/effect/commit/74c14d01d0cb48cf517a1b6e29a373a96ed0ff5b), [`e4f49b6`](https://github.com/Effect-TS/effect/commit/e4f49b66857e01b74ab6a9a0bc7132f44cd04cbb), [`6f02224`](https://github.com/Effect-TS/effect/commit/6f02224b3fc46a682ad2defb1a260841956c6780), [`1dcfd41`](https://github.com/Effect-TS/effect/commit/1dcfd41ff96abd706901293a00c1893cb29dd8fd), [`b21ab16`](https://github.com/Effect-TS/effect/commit/b21ab16b6f773e7ec4369db4e752c35e719f7870), [`fcf1822`](https://github.com/Effect-TS/effect/commit/fcf1822f98fcda60351d64e9d2c2c13563d7e6db), [`0061dd1`](https://github.com/Effect-TS/effect/commit/0061dd140740165e91569a684cce27a77b23229e), [`8421e6e`](https://github.com/Effect-TS/effect/commit/8421e6e49332bca8f96f482dfd48680e238b3a89), [`a9b3fb7`](https://github.com/Effect-TS/effect/commit/a9b3fb78abcfdb525318a956fd02fcadeb56143e), [`fa10f56`](https://github.com/Effect-TS/effect/commit/fa10f56b96bd9af070ba99ebc3279aa93954261e)]:\n  - effect@3.15.0\n  - @effect/platform@0.82.0\n  - @effect/ai@0.16.0\n  - @effect/experimental@0.46.0\n\n## 0.18.0\n\n### Minor Changes\n\n- [#4766](https://github.com/Effect-TS/effect/pull/4766) [`a4d42c5`](https://github.com/Effect-TS/effect/commit/a4d42c55669eff56963d06323d155a5bf3082a70) Thanks @IMax153! - Refactor `@effect/ai-openai` to align with changes to `@effect/ai`\n\n### Patch Changes\n\n- Updated dependencies [[`a4d42c5`](https://github.com/Effect-TS/effect/commit/a4d42c55669eff56963d06323d155a5bf3082a70)]:\n  - @effect/ai@0.15.0\n  - @effect/experimental@0.45.1\n\n## 0.17.1\n\n### Patch Changes\n\n- Updated dependencies [[`24a9ebb`](https://github.com/Effect-TS/effect/commit/24a9ebbb5af598f0bfd6ecc45307e528043fe011)]:\n  - effect@3.14.22\n  - @effect/ai@0.14.1\n  - @effect/experimental@0.45.1\n  - @effect/platform@0.81.1\n\n## 0.17.0\n\n### Patch Changes\n\n- Updated dependencies [[`672920f`](https://github.com/Effect-TS/effect/commit/672920f85da8abd5f9d4ad85e29248a2aca57ed8)]:\n  - @effect/platform@0.81.0\n  - @effect/ai@0.14.0\n  - @effect/experimental@0.45.0\n\n## 0.16.22\n\n### Patch Changes\n\n- Updated dependencies [[`2f3b7d4`](https://github.com/Effect-TS/effect/commit/2f3b7d4e1fa1ef8790b0ca4da22eb88872ee31df)]:\n  - effect@3.14.21\n  - @effect/ai@0.13.21\n  - @effect/experimental@0.44.21\n  - @effect/platform@0.80.21\n\n## 0.16.21\n\n### Patch Changes\n\n- Updated dependencies [[`17e2f30`](https://github.com/Effect-TS/effect/commit/17e2f3091408cf0fca9414d4af3bdf7b2765b378)]:\n  - effect@3.14.20\n  - @effect/ai@0.13.20\n  - @effect/experimental@0.44.20\n  - @effect/platform@0.80.20\n\n## 0.16.20\n\n### Patch Changes\n\n- Updated dependencies [[`056a910`](https://github.com/Effect-TS/effect/commit/056a910d0a0b8b00b0dc9df4a070466b2b5c2f6c), [`e25e7bb`](https://github.com/Effect-TS/effect/commit/e25e7bbc1797733916f48f501425d9f2ef310d9f), [`3273d57`](https://github.com/Effect-TS/effect/commit/3273d572c2b3175a842677f19efeea4cd65ab016)]:\n  - effect@3.14.19\n  - @effect/platform@0.80.19\n  - @effect/ai@0.13.19\n  - @effect/experimental@0.44.19\n\n## 0.16.19\n\n### Patch Changes\n\n- Updated dependencies [[`b1164d4`](https://github.com/Effect-TS/effect/commit/b1164d49a1dfdf299e9971367b6fc6be4df0ddff)]:\n  - effect@3.14.18\n  - @effect/ai@0.13.18\n  - @effect/experimental@0.44.18\n  - @effect/platform@0.80.18\n\n## 0.16.18\n\n### Patch Changes\n\n- Updated dependencies [[`0b54681`](https://github.com/Effect-TS/effect/commit/0b54681cd89245e211d8f49272be0f1bf2f81813), [`41a59d5`](https://github.com/Effect-TS/effect/commit/41a59d5916a296b12b0d5ead9e859e05f40b4cce)]:\n  - effect@3.14.17\n  - @effect/ai@0.13.17\n  - @effect/experimental@0.44.17\n  - @effect/platform@0.80.17\n\n## 0.16.17\n\n### Patch Changes\n\n- Updated dependencies [[`ee14444`](https://github.com/Effect-TS/effect/commit/ee144441021ec77039e43396eaf90714687bb495), [`f1c8583`](https://github.com/Effect-TS/effect/commit/f1c8583f8c3ea9415f813795ca2940a897c9ba9a)]:\n  - effect@3.14.16\n  - @effect/platform@0.80.16\n  - @effect/ai@0.13.16\n  - @effect/experimental@0.44.16\n\n## 0.16.16\n\n### Patch Changes\n\n- Updated dependencies [[`239cc99`](https://github.com/Effect-TS/effect/commit/239cc995ce645946210a3c3d2cb52bd3547c0687), [`8b6c947`](https://github.com/Effect-TS/effect/commit/8b6c947eaa8e45a67ecb3c37d45cd27f3e41d165), [`c50a63b`](https://github.com/Effect-TS/effect/commit/c50a63bbecb9f560b9cae349c447eed877d1b9b6)]:\n  - effect@3.14.15\n  - @effect/ai@0.13.15\n  - @effect/experimental@0.44.15\n  - @effect/platform@0.80.15\n\n## 0.16.15\n\n### Patch Changes\n\n- Updated dependencies [[`6ed8d15`](https://github.com/Effect-TS/effect/commit/6ed8d1589beb181d30abc79afebdaabc1d101538)]:\n  - effect@3.14.14\n  - @effect/ai@0.13.14\n  - @effect/experimental@0.44.14\n  - @effect/platform@0.80.14\n\n## 0.16.14\n\n### Patch Changes\n\n- Updated dependencies [[`ee77788`](https://github.com/Effect-TS/effect/commit/ee77788747e7ebbde6bfa88256cde49dbbad3608), [`5fce6ba`](https://github.com/Effect-TS/effect/commit/5fce6ba19c3cc63cc0104e737e581ad989dedbf0), [`570e45f`](https://github.com/Effect-TS/effect/commit/570e45f8cb936e42ec48f67f21bb2b7252f36c0c)]:\n  - effect@3.14.13\n  - @effect/ai@0.13.13\n  - @effect/experimental@0.44.13\n  - @effect/platform@0.80.13\n\n## 0.16.13\n\n### Patch Changes\n\n- Updated dependencies [[`c2ad9ee`](https://github.com/Effect-TS/effect/commit/c2ad9ee9f3c4c743390edf35ed9e85a20be33811), [`9c68654`](https://github.com/Effect-TS/effect/commit/9c686542b6eb3ea188cb70673ef2e41223633e89)]:\n  - effect@3.14.12\n  - @effect/ai@0.13.12\n  - @effect/experimental@0.44.12\n  - @effect/platform@0.80.12\n\n## 0.16.12\n\n### Patch Changes\n\n- Updated dependencies [[`e536127`](https://github.com/Effect-TS/effect/commit/e536127c1e6f2fb3a542c73ae919435a629a346b)]:\n  - effect@3.14.11\n  - @effect/ai@0.13.11\n  - @effect/experimental@0.44.11\n  - @effect/platform@0.80.11\n\n## 0.16.11\n\n### Patch Changes\n\n- Updated dependencies [[`bc7efa3`](https://github.com/Effect-TS/effect/commit/bc7efa3b031bb25e1ed3c8f2d3fb5e8da166cadc)]:\n  - effect@3.14.10\n  - @effect/ai@0.13.10\n  - @effect/experimental@0.44.10\n  - @effect/platform@0.80.10\n\n## 0.16.10\n\n### Patch Changes\n\n- Updated dependencies [[`d78249f`](https://github.com/Effect-TS/effect/commit/d78249f0b67f63cf4baf806ff090cba33293daf0)]:\n  - effect@3.14.9\n  - @effect/ai@0.13.9\n  - @effect/experimental@0.44.9\n  - @effect/platform@0.80.9\n\n## 0.16.9\n\n### Patch Changes\n\n- Updated dependencies [[`b3a2d32`](https://github.com/Effect-TS/effect/commit/b3a2d32772e6f7f20eacf2e18128e99324c4d378)]:\n  - effect@3.14.8\n  - @effect/ai@0.13.8\n  - @effect/experimental@0.44.8\n  - @effect/platform@0.80.8\n\n## 0.16.8\n\n### Patch Changes\n\n- Updated dependencies [[`b542a4b`](https://github.com/Effect-TS/effect/commit/b542a4bf195be0c9af1523e1ba96c953decc4d25)]:\n  - effect@3.14.7\n  - @effect/ai@0.13.7\n  - @effect/experimental@0.44.7\n  - @effect/platform@0.80.7\n\n## 0.16.7\n\n### Patch Changes\n\n- Updated dependencies [[`47618c1`](https://github.com/Effect-TS/effect/commit/47618c1ad84ebcc5a51133a3fff5aa5012d49d45), [`6077882`](https://github.com/Effect-TS/effect/commit/60778824a4794336c33807801f813f8751d1c7e4)]:\n  - effect@3.14.6\n  - @effect/ai@0.13.6\n  - @effect/experimental@0.44.6\n  - @effect/platform@0.80.6\n\n## 0.16.6\n\n### Patch Changes\n\n- [#4630](https://github.com/Effect-TS/effect/pull/4630) [`3ed0b56`](https://github.com/Effect-TS/effect/commit/3ed0b56ae69c20c4bd82dc9c0280b56768dfdd2a) Thanks @mattrossman! - Handle arbitrary length StreamChunkPart in OpenAiClient\n\n- [#4638](https://github.com/Effect-TS/effect/pull/4638) [`d46d2c6`](https://github.com/Effect-TS/effect/commit/d46d2c6f4084dfc45c8cc78da0e89b92aeedf261) Thanks @IMax153! - Manually fix schema for `CreateChatCompletionResponse.logprobs` until https://github.com/openai/openai-openapi/issues/433 is addressed\n\n- Updated dependencies [[`40dbfef`](https://github.com/Effect-TS/effect/commit/40dbfeff239b6e567706752114f31b2fce7de4e3), [`85fba81`](https://github.com/Effect-TS/effect/commit/85fba815ac07eb13d4227a69ac76a18e4b94df18), [`5a5ebdd`](https://github.com/Effect-TS/effect/commit/5a5ebdddfaddd259538b4599a6676281faca778e)]:\n  - effect@3.14.5\n  - @effect/platform@0.80.5\n  - @effect/ai@0.13.5\n  - @effect/experimental@0.44.5\n\n## 0.16.5\n\n### Patch Changes\n\n- Updated dependencies [[`e4ba2c6`](https://github.com/Effect-TS/effect/commit/e4ba2c66a878e81b5e295d6d49aaf724b80a28ef)]:\n  - effect@3.14.4\n  - @effect/ai@0.13.4\n  - @effect/experimental@0.44.4\n  - @effect/platform@0.80.4\n\n## 0.16.4\n\n### Patch Changes\n\n- Updated dependencies [[`37aa8e1`](https://github.com/Effect-TS/effect/commit/37aa8e137725a902e70cd1e468ea98b873aa5056), [`34f03d6`](https://github.com/Effect-TS/effect/commit/34f03d66875f21f266f102223a03cd14c2ed6ea6)]:\n  - effect@3.14.3\n  - @effect/ai@0.13.3\n  - @effect/experimental@0.44.3\n  - @effect/platform@0.80.3\n\n## 0.16.3\n\n### Patch Changes\n\n- Updated dependencies [[`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`0a3e3e1`](https://github.com/Effect-TS/effect/commit/0a3e3e18eea5e0d1882f1a6c906198e6ef226a41)]:\n  - effect@3.14.2\n  - @effect/ai@0.13.2\n  - @effect/experimental@0.44.2\n  - @effect/platform@0.80.2\n\n## 0.16.2\n\n### Patch Changes\n\n- [#4624](https://github.com/Effect-TS/effect/pull/4624) [`9517601`](https://github.com/Effect-TS/effect/commit/9517601586318b70849963aeeec5adff8118d2dd) Thanks @IMax153! - Upgrade the version of gpt-tokenizer to be compatible with new models\n\n## 0.16.1\n\n### Patch Changes\n\n- Updated dependencies [[`4a274fe`](https://github.com/Effect-TS/effect/commit/4a274fe9f623182b6b902827e0e83bd89ca3b05c)]:\n  - effect@3.14.1\n  - @effect/ai@0.13.1\n  - @effect/experimental@0.44.1\n  - @effect/platform@0.80.1\n\n## 0.16.0\n\n### Patch Changes\n\n- Updated dependencies [[`1f47e4e`](https://github.com/Effect-TS/effect/commit/1f47e4e12546ab691b29bfb7b5128bb17b93baa5), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`3131f8f`](https://github.com/Effect-TS/effect/commit/3131f8fd12ba9eb31b90fa2f42bf88b12309133c), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`04dff2d`](https://github.com/Effect-TS/effect/commit/04dff2d01ac68c260f29a6d4743381825c353c86), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`c7fac0c`](https://github.com/Effect-TS/effect/commit/c7fac0cd7eadcd5cc0c3a987051c5b57ad271638), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`ffaa3f3`](https://github.com/Effect-TS/effect/commit/ffaa3f3969df26610fcc02ad537340641d44e803), [`ab957c1`](https://github.com/Effect-TS/effect/commit/ab957c1fee714868f56c7ab4e802b9d449e9b666), [`35db9ce`](https://github.com/Effect-TS/effect/commit/35db9ce228f1416c8abacc6dc9c36fbd0f33ef0f), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`cf77ea9`](https://github.com/Effect-TS/effect/commit/cf77ea9ab4fc89e66a43f682a9926ccdee6c57ed), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`baaab60`](https://github.com/Effect-TS/effect/commit/baaab60b737f35dfab8e4a21bce28a195d19e899)]:\n  - effect@3.14.0\n  - @effect/experimental@0.44.0\n  - @effect/platform@0.80.0\n  - @effect/ai@0.13.0\n\n## 0.15.4\n\n### Patch Changes\n\n- [#4592](https://github.com/Effect-TS/effect/pull/4592) [`5662363`](https://github.com/Effect-TS/effect/commit/566236361e270e575ef1cbf308ad1967c82a362c) Thanks @tim-smart! - update generated ai clients\n\n- Updated dependencies [[`5662363`](https://github.com/Effect-TS/effect/commit/566236361e270e575ef1cbf308ad1967c82a362c), [`5f1fd15`](https://github.com/Effect-TS/effect/commit/5f1fd15308ab154791580059b89877d19a2055c2), [`8bb1460`](https://github.com/Effect-TS/effect/commit/8bb1460c824f66f0f25ebd899c5e74e388089c37)]:\n  - @effect/platform@0.79.4\n  - @effect/ai@0.12.4\n  - @effect/experimental@0.43.4\n\n## 0.15.3\n\n### Patch Changes\n\n- Updated dependencies [[`0c4803f`](https://github.com/Effect-TS/effect/commit/0c4803fcc69262d11a97ce49d0e9b4288df0651f), [`6f65ac4`](https://github.com/Effect-TS/effect/commit/6f65ac4eac1489cd6ea390e18b0908670722adad)]:\n  - effect@3.13.12\n  - @effect/ai@0.12.3\n  - @effect/experimental@0.43.3\n  - @effect/platform@0.79.3\n\n## 0.15.2\n\n### Patch Changes\n\n- Updated dependencies [[`fad8cca`](https://github.com/Effect-TS/effect/commit/fad8cca9bbfcc2eaeb44b97c15dbe0a1eda75315), [`4296293`](https://github.com/Effect-TS/effect/commit/4296293049414d0cf2d915a26c552b09f946b9a0), [`9c241ab`](https://github.com/Effect-TS/effect/commit/9c241abe47ccf7a5257b98a4a64a63054a12741d), [`082b0c1`](https://github.com/Effect-TS/effect/commit/082b0c1b9f4252bcdd69608f2e4a9226f953ac3f), [`be12983`](https://github.com/Effect-TS/effect/commit/be12983bc7e7537b41cd8910fc4eb7d1da56ab07), [`de88127`](https://github.com/Effect-TS/effect/commit/de88127a5a5906ccece98af74787b5ae0e65e431)]:\n  - effect@3.13.11\n  - @effect/ai@0.12.2\n  - @effect/experimental@0.43.2\n  - @effect/platform@0.79.2\n\n## 0.15.1\n\n### Patch Changes\n\n- Updated dependencies [[`527c964`](https://github.com/Effect-TS/effect/commit/527c9645229f5be9714a7e60a38a9e753c4bbfb1)]:\n  - effect@3.13.10\n  - @effect/ai@0.12.1\n  - @effect/experimental@0.43.1\n  - @effect/platform@0.79.1\n\n## 0.15.0\n\n### Patch Changes\n\n- Updated dependencies [[`88fe129`](https://github.com/Effect-TS/effect/commit/88fe12923740765c0335a6e6203fdcc6a463edca), [`d630249`](https://github.com/Effect-TS/effect/commit/d630249426113088abe8b382db4f14d80f2160c2), [`2976e52`](https://github.com/Effect-TS/effect/commit/2976e52538d9dc9ffdcbc84d4ac748cff9305971)]:\n  - @effect/platform@0.79.0\n  - effect@3.13.9\n  - @effect/experimental@0.43.0\n  - @effect/ai@0.12.0\n\n## 0.14.1\n\n### Patch Changes\n\n- Updated dependencies [[`c65d336`](https://github.com/Effect-TS/effect/commit/c65d3362d07ec815ff3b46278314e8a31706ddc2), [`22d2ebb`](https://github.com/Effect-TS/effect/commit/22d2ebb4b11f5a44351a4736e65da391a3b647d0)]:\n  - effect@3.13.8\n  - @effect/ai@0.11.1\n  - @effect/experimental@0.42.1\n  - @effect/platform@0.78.1\n\n## 0.14.0\n\n### Patch Changes\n\n- Updated dependencies [[`c5bcf53`](https://github.com/Effect-TS/effect/commit/c5bcf53b7cb49dacffdd2a6cd8eb48cc452b417e)]:\n  - @effect/platform@0.78.0\n  - @effect/ai@0.11.0\n  - @effect/experimental@0.42.0\n\n## 0.13.7\n\n### Patch Changes\n\n- Updated dependencies [[`840cc73`](https://github.com/Effect-TS/effect/commit/840cc7329908db7ca693ef47b07d4f845c29cadd), [`9bf8a74`](https://github.com/Effect-TS/effect/commit/9bf8a74b967f18d931743dd5196af326c9118e9c), [`87ba23c`](https://github.com/Effect-TS/effect/commit/87ba23c41c193503ed0c612b0d32d0b253794c64), [`f910880`](https://github.com/Effect-TS/effect/commit/f91088069057f3b4529753f5bc5532b028d726df), [`0d01480`](https://github.com/Effect-TS/effect/commit/0d014803e4f688f74386a80abd65485e1a319244), [`a95108a`](https://github.com/Effect-TS/effect/commit/a95108acac7f25fc5e1c0dcdf16bcc638dca5c00)]:\n  - @effect/platform@0.77.7\n  - effect@3.13.7\n  - @effect/ai@0.10.7\n  - @effect/experimental@0.41.7\n\n## 0.13.6\n\n### Patch Changes\n\n- Updated dependencies [[`3154ce4`](https://github.com/Effect-TS/effect/commit/3154ce4692fa18b804982158d3c4c8a8a5fae386)]:\n  - effect@3.13.6\n  - @effect/ai@0.10.6\n  - @effect/experimental@0.41.6\n  - @effect/platform@0.77.6\n\n## 0.13.5\n\n### Patch Changes\n\n- Updated dependencies [[`3d6d323`](https://github.com/Effect-TS/effect/commit/3d6d323c2a1028f3caba45453187b9374bac2c36), [`367bb35`](https://github.com/Effect-TS/effect/commit/367bb35f4c2a254e1fb211d96db2474a7aed9020), [`6cf11c3`](https://github.com/Effect-TS/effect/commit/6cf11c3a75773ceec2877c85ddc760f381f0866d), [`a0acec8`](https://github.com/Effect-TS/effect/commit/a0acec851f72e19466363d24b9cc218acd00006a), [`975c20e`](https://github.com/Effect-TS/effect/commit/975c20e446186e9bb975f77e7c6ac7b248f7b5f6)]:\n  - @effect/ai@0.10.5\n  - effect@3.13.5\n  - @effect/experimental@0.41.5\n  - @effect/platform@0.77.5\n\n## 0.13.4\n\n### Patch Changes\n\n- Updated dependencies [[`e0746f9`](https://github.com/Effect-TS/effect/commit/e0746f9aa398b69c6542e375910683bf17f49f46), [`17d9e89`](https://github.com/Effect-TS/effect/commit/17d9e89f9851663bdbb6c1e685601d97806114a4)]:\n  - @effect/platform@0.77.4\n  - effect@3.13.4\n  - @effect/ai@0.10.4\n  - @effect/experimental@0.41.4\n\n## 0.13.3\n\n### Patch Changes\n\n- [#4504](https://github.com/Effect-TS/effect/pull/4504) [`a67a8a1`](https://github.com/Effect-TS/effect/commit/a67a8a1a4979fb7a039a060d067d805879da4d4b) Thanks @IMax153! - Introduce `AiModel` and `AiPlan` for describing retry / fallback logic between\n  models and providers\n\n  For example, the following program builds an `AiPlan` which will attempt to use\n  OpenAi's chat completions API, and if after three attempts the operation\n  is still failing, the plan will fallback to utilizing Anthropic's messages API\n  to resolve the request.\n\n  ```ts\n  import { AiPlan, Completions } from \"@effect/ai\"\n  import { AnthropicClient, AnthropicCompletions } from \"@effect/ai-anthropic\"\n  import { OpenAiClient, OpenAiCompletions } from \"@effect/ai-openai\"\n  import { NodeHttpClient, NodeRuntime } from \"@effect/platform-node\"\n  import { Config, Console, Effect, Layer } from \"effect\"\n\n  // Create Anthropic client\n  const Anthropic = AnthropicClient.layerConfig({\n    apiKey: Config.redacted(\"ANTHROPIC_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  // Create OpenAi client\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  // Create a plan of request execution\n  const Plan = AiPlan.fromModel(OpenAiCompletions.model(\"gpt-4o-mini\"), {\n    attempts: 3\n  }).pipe(\n    AiPlan.withFallback({\n      model: AnthropicCompletions.model(\"claude-3-5-haiku-latest\")\n    })\n  )\n\n  const program = Effect.gen(function* () {\n    // Build the plan of execution\n    const plan = yield* Plan\n\n    // Create a program which uses the services provided by the plan\n    const getDadJoke = Effect.gen(function* () {\n      const completions = yield* Completions.Completions\n      const response = yield* completions.create(\"Tell me a dad joke\")\n      yield* Console.log(response.text)\n    })\n\n    // Provide the plan to whichever programs need it\n    yield* plan.provide(getDadJoke)\n  })\n\n  program.pipe(Effect.provide([Anthropic, OpenAi]), NodeRuntime.runMain)\n  ```\n\n- Updated dependencies [[`cc5588d`](https://github.com/Effect-TS/effect/commit/cc5588df07f9103513547cb429ce041b9436a8bd), [`623c8cd`](https://github.com/Effect-TS/effect/commit/623c8cd053ed6ee3d353aaa8778d484670fca2bb), [`00b4eb1`](https://github.com/Effect-TS/effect/commit/00b4eb1ece12a16e222e6220965bb4024d6752ac), [`f2aee98`](https://github.com/Effect-TS/effect/commit/f2aee989b0a600900ce83e7f460d02908620c80f), [`fb798eb`](https://github.com/Effect-TS/effect/commit/fb798eb9061f1191badc017d1aa649360254da20), [`2251b15`](https://github.com/Effect-TS/effect/commit/2251b1528810bb695b37ce388b653cec0c5bf80c), [`2e15c1e`](https://github.com/Effect-TS/effect/commit/2e15c1e33648add0b29fe274fbcb7294b7515085), [`a4979db`](https://github.com/Effect-TS/effect/commit/a4979db021aef16e731be64df196b72088fc4376), [`b74255a`](https://github.com/Effect-TS/effect/commit/b74255a304ad49d60bedb1a260fd697f370af27a), [`d7f6a5c`](https://github.com/Effect-TS/effect/commit/d7f6a5c7d26c1963dcd864ca62360d20d08c7b49), [`9dd8979`](https://github.com/Effect-TS/effect/commit/9dd8979e940915b1cc1b1f264f3d019c77a65a02), [`477b488`](https://github.com/Effect-TS/effect/commit/477b488284f47c5469d7fba3e4065fb7e3b6556e), [`10932cb`](https://github.com/Effect-TS/effect/commit/10932cbf58fc721ada631cebec42f773ce96d3cc), [`9f6c784`](https://github.com/Effect-TS/effect/commit/9f6c78468b3b5e9ebfc38ffdfb70702901ee977b), [`2c639ec`](https://github.com/Effect-TS/effect/commit/2c639ecee332de4266e36022c989c35ae4e02105), [`886aaa8`](https://github.com/Effect-TS/effect/commit/886aaa81e06dfd3cd9391e8ea987d8cd5ada1124), [`a67a8a1`](https://github.com/Effect-TS/effect/commit/a67a8a1a4979fb7a039a060d067d805879da4d4b)]:\n  - effect@3.13.3\n  - @effect/ai@0.10.3\n  - @effect/experimental@0.41.3\n  - @effect/platform@0.77.3\n\n## 0.13.2\n\n### Patch Changes\n\n- Updated dependencies [[`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f), [`3e7ce97`](https://github.com/Effect-TS/effect/commit/3e7ce97f8a41756a039cf635d0b3d9a75d781097), [`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f)]:\n  - effect@3.13.2\n  - @effect/platform@0.77.2\n  - @effect/ai@0.10.2\n  - @effect/experimental@0.41.2\n\n## 0.13.1\n\n### Patch Changes\n\n- [#4446](https://github.com/Effect-TS/effect/pull/4446) [`9375c28`](https://github.com/Effect-TS/effect/commit/9375c28ca808325577da6c67cc92af25931027c8) Thanks @IMax153! - Add Anthropic AI provider integration\n\n- Updated dependencies [[`b56a211`](https://github.com/Effect-TS/effect/commit/b56a2110569fd0ec0b57ac137743e926d49f51cc), [`9375c28`](https://github.com/Effect-TS/effect/commit/9375c28ca808325577da6c67cc92af25931027c8)]:\n  - effect@3.13.1\n  - @effect/ai@0.10.1\n  - @effect/experimental@0.41.1\n  - @effect/platform@0.77.1\n\n## 0.13.0\n\n### Patch Changes\n\n- Updated dependencies [[`8baef83`](https://github.com/Effect-TS/effect/commit/8baef83e7ff0b7bc0738b680e1ef013065386cff), [`655bfe2`](https://github.com/Effect-TS/effect/commit/655bfe29e44cc3f0fb9b4e53038f50b891c188df), [`d90cbc2`](https://github.com/Effect-TS/effect/commit/d90cbc274e2742d18671fe65aa4764c057eb6cba), [`75632bd`](https://github.com/Effect-TS/effect/commit/75632bd44b8025101d652ccbaeef898c7086c91c), [`c874a2e`](https://github.com/Effect-TS/effect/commit/c874a2e4b17e9d71904ca8375bb77b020975cb1d), [`bf865e5`](https://github.com/Effect-TS/effect/commit/bf865e5833f77fd8f6c06944ca9d507b54488301), [`f98b2b7`](https://github.com/Effect-TS/effect/commit/f98b2b7592cf20f9d85313e7f1e964cb65878138), [`de8ce92`](https://github.com/Effect-TS/effect/commit/de8ce924923eaa4e1b761a97eb45ec967389f3d5), [`cf8b2dd`](https://github.com/Effect-TS/effect/commit/cf8b2dd112f8e092ed99d78fd728db0f91c29050), [`db426a5`](https://github.com/Effect-TS/effect/commit/db426a5fb41ab84d18e3c8753a7329b4de544245), [`6862444`](https://github.com/Effect-TS/effect/commit/6862444094906ad4f2cb077ff3b9cc0b73880c8c), [`5fc8a90`](https://github.com/Effect-TS/effect/commit/5fc8a90ba46a5fd9f3b643f0b5aeadc69d717339), [`546a492`](https://github.com/Effect-TS/effect/commit/546a492e60eb2b8b048a489a474b934ea0877005), [`65c4796`](https://github.com/Effect-TS/effect/commit/65c47966ce39055f02cf5c808daabb3ea6442b0b), [`9760fdc`](https://github.com/Effect-TS/effect/commit/9760fdc37bdaef9da8b150e46b86ddfbe2ad9221), [`5b471e7`](https://github.com/Effect-TS/effect/commit/5b471e7d4317e8ee5d72bbbd3e0c9775160949ab), [`4f810cc`](https://github.com/Effect-TS/effect/commit/4f810cc2770e9f1f266851d2cb6257112c12af49)]:\n  - effect@3.13.0\n  - @effect/ai@0.10.0\n  - @effect/experimental@0.41.0\n  - @effect/platform@0.77.0\n\n## 0.12.1\n\n### Patch Changes\n\n- Updated dependencies [[`4018eae`](https://github.com/Effect-TS/effect/commit/4018eaed2733241676ddb8c52416f463a8c32e35), [`543d36d`](https://github.com/Effect-TS/effect/commit/543d36d1a11452560b01ab966a82529ad5fee8c9), [`c407726`](https://github.com/Effect-TS/effect/commit/c407726f79df4a567a9631cddd8effaa16b3535d), [`f70a65a`](https://github.com/Effect-TS/effect/commit/f70a65ac80c6635d80b12beaf4d32a9cc59fa143), [`ba409f6`](https://github.com/Effect-TS/effect/commit/ba409f69c41aeaa29e475c0630735726eaf4dbac), [`3d2e356`](https://github.com/Effect-TS/effect/commit/3d2e3565e8a43d1bdb5daee8db3b90f56d71d859)]:\n  - effect@3.12.12\n  - @effect/platform@0.76.1\n  - @effect/ai@0.9.1\n  - @effect/experimental@0.40.1\n\n## 0.12.0\n\n### Patch Changes\n\n- Updated dependencies [[`b6a032f`](https://github.com/Effect-TS/effect/commit/b6a032f07bffa020a848c813881879395134fa20), [`42ddd5f`](https://github.com/Effect-TS/effect/commit/42ddd5f144ce9f9d94a036679ebbd626446d37f5), [`2fe447c`](https://github.com/Effect-TS/effect/commit/2fe447c6354d334f9c591b8a8481818f5f0e797e), [`2473ad5`](https://github.com/Effect-TS/effect/commit/2473ad5cf23582e3a41338091fa526ffe611288d)]:\n  - effect@3.12.11\n  - @effect/platform@0.76.0\n  - @effect/ai@0.9.0\n  - @effect/experimental@0.40.0\n\n## 0.11.5\n\n### Patch Changes\n\n- [#4418](https://github.com/Effect-TS/effect/pull/4418) [`cdc82e4`](https://github.com/Effect-TS/effect/commit/cdc82e4ae880bf54cf35e5a68d8103840f49001b) Thanks @IMax153! - Support per-request HTTP client transformations in the OpenAi AI integration package.\n\n  For example:\n\n  ```ts\n  import { Completions } from \"@effect/ai\"\n  import {\n    OpenAiClient,\n    OpenAiCompletions,\n    OpenAiConfig\n  } from \"@effect/ai-openai\"\n  import { HttpClient, HttpClientRequest } from \"@effect/platform\"\n  import { NodeHttpClient } from \"@effect/platform-node\"\n  import { Config, Effect, Layer } from \"effect\"\n\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  const Gpt4oCompletions = OpenAiCompletions.layer({\n    model: \"gpt-4o\"\n  }).pipe(Layer.provide(OpenAi))\n\n  const program = Effect.gen(function* () {\n    const completions = yield* Completions.Completions\n\n    yield* completions.create(\"Tell me a dad joke\").pipe(\n      // Per-request HTTP client transforms which are only applied if\n      // the OpenAi provider is in use\n      OpenAiConfig.withClientTransform(\n        HttpClient.mapRequest(\n          HttpClientRequest.setHeader(\"x-dad-jokes\", \"are-awesome\")\n        )\n      )\n    )\n  })\n\n  program.pipe(Effect.provide(Gpt4oCompletions), Effect.runPromise)\n  ```\n\n## 0.11.4\n\n### Patch Changes\n\n- Updated dependencies [[`e30f132`](https://github.com/Effect-TS/effect/commit/e30f132c336c9d0760bad39f82a55c7ce5159eb7), [`33fa667`](https://github.com/Effect-TS/effect/commit/33fa667c2623be1026e1ccee91bd44f73b09020a), [`87f5f28`](https://github.com/Effect-TS/effect/commit/87f5f2842e4196cb88d13f10f443ff0567e82832), [`7d57ecd`](https://github.com/Effect-TS/effect/commit/7d57ecdaf5da2345ebbf9c22df50317578bde0f5), [`4dbd170`](https://github.com/Effect-TS/effect/commit/4dbd170538e8fb7a36aa7c469c6f93b6c7000091)]:\n  - effect@3.12.10\n  - @effect/platform@0.75.4\n  - @effect/ai@0.8.4\n  - @effect/experimental@0.39.4\n\n## 0.11.3\n\n### Patch Changes\n\n- Updated dependencies [[`1b4a4e9`](https://github.com/Effect-TS/effect/commit/1b4a4e904ef5227ec7d9114d4e417eca19eed940)]:\n  - effect@3.12.9\n  - @effect/ai@0.8.3\n  - @effect/experimental@0.39.3\n  - @effect/platform@0.75.3\n\n## 0.11.2\n\n### Patch Changes\n\n- [#4389](https://github.com/Effect-TS/effect/pull/4389) [`f089470`](https://github.com/Effect-TS/effect/commit/f0894708e9d591b70eccf3a50ae91ac6e0f6d6e3) Thanks @IMax153! - Add support for [GenAI telemetry annotations](https://opentelemetry.io/docs/specs/semconv/attributes-registry/gen-ai/).\n\n- [#4368](https://github.com/Effect-TS/effect/pull/4368) [`a0c85e6`](https://github.com/Effect-TS/effect/commit/a0c85e6601fd3e10d08085969f7453b7b517347b) Thanks @IMax153! - Support creation of embeddings from the AI integration packages.\n\n  For example, the following program will create an OpenAI `Embeddings` service\n  that will aggregate all embedding requests received within a `500` millisecond\n  window into a single batch.\n\n  ```ts\n  import { Embeddings } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiEmbeddings } from \"@effect/ai-openai\"\n  import { NodeHttpClient } from \"@effect/platform-node\"\n  import { Config, Effect, Layer } from \"effect\"\n\n  // Create the OpenAI client\n  const OpenAi = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  // Create an embeddings service for the `text-embedding-3-large` model\n  const TextEmbeddingsLarge = OpenAiEmbeddings.layerDataLoader({\n    model: \"text-embedding-3-large\",\n    window: \"500 millis\",\n    maxBatchSize: 2048\n  }).pipe(Layer.provide(OpenAi))\n\n  // Use the generic `Embeddings` service interface in your program\n  const program = Effect.gen(function* () {\n    const embeddings = yield* Embeddings.Embeddings\n    const result = yield* embeddings.embed(\"The input to embed\")\n  })\n\n  // Provide the specific implementation to use\n  program.pipe(Effect.provide(TextEmbeddingsLarge), Effect.runPromise)\n  ```\n\n- Updated dependencies [[`f5e3b1b`](https://github.com/Effect-TS/effect/commit/f5e3b1bcdf24b440251ce8425d750353cf022e96), [`59b3cfb`](https://github.com/Effect-TS/effect/commit/59b3cfbbd5713dd9475998e95fad5534c0b21466), [`766113c`](https://github.com/Effect-TS/effect/commit/766113c0ea3512cdb887650ead8ba314236e22ee), [`fcf3b7c`](https://github.com/Effect-TS/effect/commit/fcf3b7cc07a28635a5b53243b01cdeb6592dab3c), [`bb05fb8`](https://github.com/Effect-TS/effect/commit/bb05fb83457355b1ca567228a9e041edfb6fd85d), [`712277f`](https://github.com/Effect-TS/effect/commit/712277f949052a24b46e4aa234063a6abf395c90), [`f269122`](https://github.com/Effect-TS/effect/commit/f269122508693b111142994dd48698ddc75f3d69), [`8f6006a`](https://github.com/Effect-TS/effect/commit/8f6006a610fb6d6c7b8d14209a7323338a8964ff), [`f089470`](https://github.com/Effect-TS/effect/commit/f0894708e9d591b70eccf3a50ae91ac6e0f6d6e3), [`c45b559`](https://github.com/Effect-TS/effect/commit/c45b5592b5fd1189a5c932cfe05bd7d5f6d68508), [`430c846`](https://github.com/Effect-TS/effect/commit/430c846cbac05b187e3d24ac8dfee0cf22506f7c), [`7b03057`](https://github.com/Effect-TS/effect/commit/7b03057507d2dab5e6793beb9c578dedaaeb15fe), [`a9c94c8`](https://github.com/Effect-TS/effect/commit/a9c94c807755610831211a686d2fad849ab38eb4), [`107e6f0`](https://github.com/Effect-TS/effect/commit/107e6f0557a1e2d3b0dce25d62fa1e2601521752), [`c9175ae`](https://github.com/Effect-TS/effect/commit/c9175aef41cb1e3b689d0ac0a4f53d8107376b58), [`65c11b9`](https://github.com/Effect-TS/effect/commit/65c11b9266ec9447c31c26fe3ed35c73bd3b81fd), [`e386d2f`](https://github.com/Effect-TS/effect/commit/e386d2f1b3ab3ac2c14ee76de11f5963d32a3df4), [`9172efb`](https://github.com/Effect-TS/effect/commit/9172efba98bc6a82353e6ec2af61ac08f038ba64), [`a0c85e6`](https://github.com/Effect-TS/effect/commit/a0c85e6601fd3e10d08085969f7453b7b517347b)]:\n  - @effect/ai@0.8.2\n  - @effect/platform@0.75.2\n  - effect@3.12.8\n  - @effect/experimental@0.39.2\n\n## 0.11.1\n\n### Patch Changes\n\n- Updated dependencies [[`8dff1d1`](https://github.com/Effect-TS/effect/commit/8dff1d1bff76cdba643cad7f0bf864300f08bc61)]:\n  - effect@3.12.7\n  - @effect/ai@0.8.1\n  - @effect/experimental@0.39.1\n  - @effect/platform@0.75.1\n\n## 0.11.0\n\n### Patch Changes\n\n- [#4316](https://github.com/Effect-TS/effect/pull/4316) [`5c5612f`](https://github.com/Effect-TS/effect/commit/5c5612fa9472cde547ad182664e7173403ef0511) Thanks @IMax153! - Allow configuring OpenAI API URL and API key in OpenAI client constructor\n\n- Updated dependencies [[`5e43ce5`](https://github.com/Effect-TS/effect/commit/5e43ce50bae116865906112e7f88d390739d778b), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`76eb7d0`](https://github.com/Effect-TS/effect/commit/76eb7d0fbce3c009c8f77e84c178cb15bbed9709), [`8b4e75d`](https://github.com/Effect-TS/effect/commit/8b4e75d35daea807c447ca760948a717aa66bb52), [`fc5e0f0`](https://github.com/Effect-TS/effect/commit/fc5e0f0d357a0051cfa01c1ede83ffdd3cb41ab1), [`004fd2b`](https://github.com/Effect-TS/effect/commit/004fd2bbd1459e64fb1b57f02eeb791ca5ea1ea5), [`b2a31be`](https://github.com/Effect-TS/effect/commit/b2a31be85c35d891351ce4f9a2cc93ece0c257f6), [`5514d05`](https://github.com/Effect-TS/effect/commit/5514d05b5cd586ff5868b8bd41c959e95e6c33cd), [`bf5f0ae`](https://github.com/Effect-TS/effect/commit/bf5f0ae9daa0170471678e22585e8ec14ce667bb), [`3b19bcf`](https://github.com/Effect-TS/effect/commit/3b19bcfd3aaadb6c9253428622df524537c8e626), [`b064b3b`](https://github.com/Effect-TS/effect/commit/b064b3b293615fd268cc5a5647d0981eb67750b8), [`eb264ed`](https://github.com/Effect-TS/effect/commit/eb264ed8a6e8c92a9dc7006f766c6ca2e5d29e03), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`f474678`](https://github.com/Effect-TS/effect/commit/f474678bf10b8f1c80e3dc096ddc7ecf20b2b23e), [`ee187d0`](https://github.com/Effect-TS/effect/commit/ee187d098007a402844c94d04f0cd8f07695377a)]:\n  - @effect/experimental@0.39.0\n  - @effect/platform@0.75.0\n  - @effect/ai@0.8.0\n  - effect@3.12.6\n\n## 0.10.0\n\n### Patch Changes\n\n- Updated dependencies [[`bd0d489`](https://github.com/Effect-TS/effect/commit/bd0d4892b098bc4c589444af9f50259c2c02ec0f), [`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8653072`](https://github.com/Effect-TS/effect/commit/86530720d7a03e118d2c5a8bf5a997cee7e7f3d6), [`507d546`](https://github.com/Effect-TS/effect/commit/507d546bd49db31000425fb5da88c434e4291bea), [`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8db239b`](https://github.com/Effect-TS/effect/commit/8db239b9c869a3707f6566b9d9dbdf53c4df03fc), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`3179a9f`](https://github.com/Effect-TS/effect/commit/3179a9f65d23369a6a9a1f80f7750566dd28df22), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e), [`1fcbe55`](https://github.com/Effect-TS/effect/commit/1fcbe55345042d8468f6a98c84081bd00b6bcf5a), [`bd0d489`](https://github.com/Effect-TS/effect/commit/bd0d4892b098bc4c589444af9f50259c2c02ec0f), [`d9a63d9`](https://github.com/Effect-TS/effect/commit/d9a63d9d385653865954cac895065360d54cc56b), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e)]:\n  - @effect/experimental@0.38.0\n  - effect@3.12.5\n  - @effect/platform@0.74.0\n  - @effect/ai@0.7.0\n\n## 0.9.1\n\n### Patch Changes\n\n- Updated dependencies [[`5b50ea4`](https://github.com/Effect-TS/effect/commit/5b50ea4a10cf9acd51f9624b2474d9d5ded74019), [`c170a68`](https://github.com/Effect-TS/effect/commit/c170a68b6266100774461fcd6c0e0fabb60112f2), [`a66c2eb`](https://github.com/Effect-TS/effect/commit/a66c2eb473245092cd41f04c2eb2b7b02cf53718), [`c9e5e1b`](https://github.com/Effect-TS/effect/commit/c9e5e1be17c0c84d3d4e2abc3c60215cdb56bbbe), [`7b3d58d`](https://github.com/Effect-TS/effect/commit/7b3d58d7aec2152ec282460871d3e9de45ed254d)]:\n  - effect@3.12.4\n  - @effect/platform@0.73.1\n  - @effect/ai@0.6.1\n  - @effect/experimental@0.37.1\n\n## 0.9.0\n\n### Patch Changes\n\n- Updated dependencies [[`d7dac48`](https://github.com/Effect-TS/effect/commit/d7dac48a477cdfeec509dbe9f33fce6a1b02b63d), [`c110032`](https://github.com/Effect-TS/effect/commit/c110032322450a8824ba38ae24335a538cd2ce9a), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`23ac740`](https://github.com/Effect-TS/effect/commit/23ac740c7dd4610b7d265c2071b88b0968419e9a), [`8cd7319`](https://github.com/Effect-TS/effect/commit/8cd7319b6568bfc7a30ca16c104d189e37eac3a0)]:\n  - effect@3.12.3\n  - @effect/platform@0.73.0\n  - @effect/ai@0.6.0\n  - @effect/experimental@0.37.0\n\n## 0.8.2\n\n### Patch Changes\n\n- Updated dependencies [[`734af82`](https://github.com/Effect-TS/effect/commit/734af82138e78b9c57a8355b1c6b80e80d38b222), [`b63c780`](https://github.com/Effect-TS/effect/commit/b63c78010893101520448ddda7019c487cf7eedd), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`f852cb0`](https://github.com/Effect-TS/effect/commit/f852cb02040ea2f165e9b449615b8b1366add5d5), [`7276ae2`](https://github.com/Effect-TS/effect/commit/7276ae21062896adbb7508ac5b2dece95316322f), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`c640d77`](https://github.com/Effect-TS/effect/commit/c640d77b33ad417876f4e8ffe8574ee6cbe5607f), [`0def088`](https://github.com/Effect-TS/effect/commit/0def0887cfdb6755729a64dfd52b3b9f46b0576c)]:\n  - effect@3.12.2\n  - @effect/platform@0.72.2\n  - @effect/ai@0.5.2\n  - @effect/experimental@0.36.2\n\n## 0.8.1\n\n### Patch Changes\n\n- Updated dependencies [[`302b57d`](https://github.com/Effect-TS/effect/commit/302b57d2cbf9b9ccc17450945aeebfb33cfe8d43), [`0988083`](https://github.com/Effect-TS/effect/commit/0988083d4594938590df5a287e5b27d38526dd07), [`8b46be6`](https://github.com/Effect-TS/effect/commit/8b46be6a3b8160362ab5ea9171c5e6932505125c), [`bfe8027`](https://github.com/Effect-TS/effect/commit/bfe802734b450a4b4ee069d1125dd37995db2bff), [`16dd657`](https://github.com/Effect-TS/effect/commit/16dd657033d8afac2ffea567b3c8bb27c9b249b6), [`39db211`](https://github.com/Effect-TS/effect/commit/39db211414e90c8db8fdad7dc8ce5b4661bcfaef)]:\n  - effect@3.12.1\n  - @effect/ai@0.5.1\n  - @effect/experimental@0.36.1\n  - @effect/platform@0.72.1\n\n## 0.8.0\n\n### Patch Changes\n\n- Updated dependencies [[`abb22a4`](https://github.com/Effect-TS/effect/commit/abb22a429b9c52c31e84856294f175d2064a9b4d), [`f369a89`](https://github.com/Effect-TS/effect/commit/f369a89e98bc682969803b9304adaf4557bb36c2), [`642376c`](https://github.com/Effect-TS/effect/commit/642376c63fd7d78754db991631a4d50a5dc79aa3), [`3d2b7a7`](https://github.com/Effect-TS/effect/commit/3d2b7a7e942a7157afae5b1cdbc6f3fef116428e), [`ef64c6f`](https://github.com/Effect-TS/effect/commit/ef64c6fec0d47da573c04230dde9ea729366d871), [`73f9c6f`](https://github.com/Effect-TS/effect/commit/73f9c6f2ff091512cf904cc54ab59965b86e87c8), [`17cb451`](https://github.com/Effect-TS/effect/commit/17cb4514590e8a86263f7aed009f24da8a237342), [`d801820`](https://github.com/Effect-TS/effect/commit/d80182060c2ee945d7e0e4728812abf9465a0d6a), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1), [`c11f3a6`](https://github.com/Effect-TS/effect/commit/c11f3a60a05c3b5fc8e7ce90136728154dc505b0), [`618f7e0`](https://github.com/Effect-TS/effect/commit/618f7e092a1011e5090dca1e69b5e9285689654b), [`c0ba834`](https://github.com/Effect-TS/effect/commit/c0ba834d1995cf5a8b250e4780fd43f3e3881151), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1)]:\n  - effect@3.12.0\n  - @effect/platform@0.72.0\n  - @effect/ai@0.5.0\n  - @effect/experimental@0.36.0\n\n## 0.7.3\n\n### Patch Changes\n\n- Updated dependencies [[`39457d4`](https://github.com/Effect-TS/effect/commit/39457d4897d9bc7df8af5c05d352866bbeae82eb), [`a475cc2`](https://github.com/Effect-TS/effect/commit/a475cc25fd7c9f26b27a8e98f8fbe43cc9e6ee3e), [`199214e`](https://github.com/Effect-TS/effect/commit/199214e21c616d8a0ccd7ed5f92e944e6c580193), [`b3c160d`](https://github.com/Effect-TS/effect/commit/b3c160d7a1fdfc2d3fb2440530f1ab80efc65133)]:\n  - effect@3.11.10\n  - @effect/ai@0.4.8\n  - @effect/experimental@0.35.3\n  - @effect/platform@0.71.7\n\n## 0.7.2\n\n### Patch Changes\n\n- Updated dependencies [[`1c08a0b`](https://github.com/Effect-TS/effect/commit/1c08a0b8505badcffb4d9cade5a746ea90c9557e), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd)]:\n  - effect@3.11.9\n  - @effect/ai@0.4.7\n  - @effect/experimental@0.35.2\n  - @effect/platform@0.71.6\n\n## 0.7.1\n\n### Patch Changes\n\n- Updated dependencies [[`05d71f8`](https://github.com/Effect-TS/effect/commit/05d71f85622305705d8316817694a09762e60865), [`e66b920`](https://github.com/Effect-TS/effect/commit/e66b9205f25ab425d30640886eb3fb2c4715bc26)]:\n  - @effect/platform@0.71.5\n  - @effect/ai@0.4.6\n  - @effect/experimental@0.35.1\n\n## 0.7.0\n\n### Patch Changes\n\n- Updated dependencies [[`909181a`](https://github.com/Effect-TS/effect/commit/909181a9ce9052a80432ccf52187e0723004bf7f), [`909181a`](https://github.com/Effect-TS/effect/commit/909181a9ce9052a80432ccf52187e0723004bf7f), [`1a6b52d`](https://github.com/Effect-TS/effect/commit/1a6b52dcf020d36e38a7bc90b648152cf5a8ccba)]:\n  - @effect/platform@0.71.4\n  - effect@3.11.8\n  - @effect/ai@0.4.5\n  - @effect/experimental@0.35.0\n\n## 0.6.4\n\n### Patch Changes\n\n- Updated dependencies [[`6984508`](https://github.com/Effect-TS/effect/commit/6984508c87f1bd91213b44c19b25ab5e2dcc1ce0), [`883639c`](https://github.com/Effect-TS/effect/commit/883639cc8ce47757f1cd39439391a8028c0812fe)]:\n  - @effect/platform@0.71.3\n  - @effect/ai@0.4.4\n  - @effect/experimental@0.34.3\n\n## 0.6.3\n\n### Patch Changes\n\n- Updated dependencies [[`1237ae8`](https://github.com/Effect-TS/effect/commit/1237ae847f6f0ff57eb7dcb4723ae6f5073fb925)]:\n  - @effect/ai@0.4.3\n\n## 0.6.2\n\n### Patch Changes\n\n- Updated dependencies [[`2408616`](https://github.com/Effect-TS/effect/commit/24086163b60b09cc6d0885bd565ef080dcbe866b), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`8d978c5`](https://github.com/Effect-TS/effect/commit/8d978c53f6fcc98d9d645ecba3e4b55d4297dd36), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e)]:\n  - effect@3.11.7\n  - @effect/platform@0.71.2\n  - @effect/ai@0.4.2\n  - @effect/experimental@0.34.2\n\n## 0.6.1\n\n### Patch Changes\n\n- Updated dependencies [[`1d3df5b`](https://github.com/Effect-TS/effect/commit/1d3df5bc4324e88a392c348db35fd9d029c7b25e)]:\n  - @effect/platform@0.71.1\n  - @effect/ai@0.4.1\n  - @effect/experimental@0.34.1\n\n## 0.6.0\n\n### Patch Changes\n\n- Updated dependencies [[`662d1ce`](https://github.com/Effect-TS/effect/commit/662d1ce6fb7da384a95888d5b2bb5605bdf3208d), [`c99a0f3`](https://github.com/Effect-TS/effect/commit/c99a0f376d049d3793ed33e146d9873b8a5e5b78), [`11fc401`](https://github.com/Effect-TS/effect/commit/11fc401f436f99bf4be95f56d50b0e4bdfe5edea), [`c99a0f3`](https://github.com/Effect-TS/effect/commit/c99a0f376d049d3793ed33e146d9873b8a5e5b78), [`31c62d8`](https://github.com/Effect-TS/effect/commit/31c62d83cbdcf9850a8b5331faa239601c60f78a)]:\n  - effect@3.11.6\n  - @effect/platform@0.71.0\n  - @effect/ai@0.4.0\n  - @effect/experimental@0.34.0\n\n## 0.5.7\n\n### Patch Changes\n\n- Updated dependencies [[`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`ef70ffc`](https://github.com/Effect-TS/effect/commit/ef70ffc417ec035ede40c62b7316e447cc7c1932), [`22905cf`](https://github.com/Effect-TS/effect/commit/22905cf5addfb1ff3d2a6135c52036be958ae911), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`1e59e4f`](https://github.com/Effect-TS/effect/commit/1e59e4fd778da18296812a2a32f36ca8ae50f60d), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`8d914e5`](https://github.com/Effect-TS/effect/commit/8d914e504e7a22d0ea628e8af265ee450ff9530f), [`03bb00f`](https://github.com/Effect-TS/effect/commit/03bb00faa74f9e168a54a8cc0828a664fbb1ab05), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`14e1149`](https://github.com/Effect-TS/effect/commit/14e1149f1af5a022f06eb8c2e4ba9fec17fe7426), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8)]:\n  - effect@3.11.5\n  - @effect/experimental@0.33.7\n  - @effect/platform@0.70.7\n  - @effect/ai@0.3.7\n\n## 0.5.6\n\n### Patch Changes\n\n- Updated dependencies [[`9a5b8e3`](https://github.com/Effect-TS/effect/commit/9a5b8e36d184bd4967a88752cb6e755e1be263af)]:\n  - @effect/platform@0.70.6\n  - @effect/ai@0.3.6\n  - @effect/experimental@0.33.6\n\n## 0.5.5\n\n### Patch Changes\n\n- Updated dependencies [[`415f4c9`](https://github.com/Effect-TS/effect/commit/415f4c98321868531727a83cbaad70164f5e4c40), [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f), [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f)]:\n  - @effect/platform@0.70.5\n  - effect@3.11.4\n  - @effect/experimental@0.33.5\n  - @effect/ai@0.3.5\n\n## 0.5.4\n\n### Patch Changes\n\n- Updated dependencies [[`90906f7`](https://github.com/Effect-TS/effect/commit/90906f7f154b12c7182e8f39e3c55ef3937db857), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`343b6aa`](https://github.com/Effect-TS/effect/commit/343b6aa6ac4a74276bfc7c63ccbf4a1d72bc1bed), [`afba339`](https://github.com/Effect-TS/effect/commit/afba339adc11dad56b5a3b7ca94487e58f34d613)]:\n  - effect@3.11.3\n  - @effect/ai@0.3.4\n  - @effect/experimental@0.33.4\n  - @effect/platform@0.70.4\n\n## 0.5.3\n\n### Patch Changes\n\n- [#4071](https://github.com/Effect-TS/effect/pull/4071) [`da3a607`](https://github.com/Effect-TS/effect/commit/da3a607bea16d4f08c5937cadfde0447c4123f40) Thanks @tim-smart! - use openai response_format for structured completions\n\n- Updated dependencies [[`7044730`](https://github.com/Effect-TS/effect/commit/70447306be1aeeb7d87c230b2a96ec87b993ede9), [`da3a607`](https://github.com/Effect-TS/effect/commit/da3a607bea16d4f08c5937cadfde0447c4123f40)]:\n  - @effect/platform@0.70.3\n  - @effect/ai@0.3.3\n  - @effect/experimental@0.33.3\n\n## 0.5.2\n\n### Patch Changes\n\n- Updated dependencies [[`01cee56`](https://github.com/Effect-TS/effect/commit/01cee560b58d94b24cc20e98083251b73e658b41), [`c2249ea`](https://github.com/Effect-TS/effect/commit/c2249ea13fd98ab7d9aa628787931356d8ec2860), [`1358aa5`](https://github.com/Effect-TS/effect/commit/1358aa5326eaa85ef13ee8d1fed0b4a4288ed3eb), [`1de3fe7`](https://github.com/Effect-TS/effect/commit/1de3fe7d1cbafd6391eaa38c2300b99e332cc2aa)]:\n  - effect@3.11.2\n  - @effect/platform@0.70.2\n  - @effect/ai@0.3.2\n  - @effect/experimental@0.33.2\n\n## 0.5.1\n\n### Patch Changes\n\n- Updated dependencies [[`dd8a2d8`](https://github.com/Effect-TS/effect/commit/dd8a2d8e80d33b16719fc69361eaedf0b59d4620), [`a71bfef`](https://github.com/Effect-TS/effect/commit/a71bfef46f5061bb2502a61a333638a987b62273)]:\n  - effect@3.11.1\n  - @effect/ai@0.3.1\n  - @effect/experimental@0.33.1\n  - @effect/platform@0.70.1\n\n## 0.5.0\n\n### Patch Changes\n\n- Updated dependencies [[`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`6e69493`](https://github.com/Effect-TS/effect/commit/6e694930048bbaf98110f35f41566aeb9752d471), [`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`5eff3f6`](https://github.com/Effect-TS/effect/commit/5eff3f6fa3aae7e86948a62cbfd63b8d6c3bdf92), [`d9fe79b`](https://github.com/Effect-TS/effect/commit/d9fe79bb5a3fe105d8e7a3bc2922a8ad936a5d10), [`251d189`](https://github.com/Effect-TS/effect/commit/251d189420bbba71990574e91098c499065f9a9b), [`5a259f3`](https://github.com/Effect-TS/effect/commit/5a259f3711b4369f55d885b568bdb21136155261), [`b4ce4ea`](https://github.com/Effect-TS/effect/commit/b4ce4ea7fd514a7e572f2dcd879c98f334981b0e), [`15fcc5a`](https://github.com/Effect-TS/effect/commit/15fcc5a0ea4bbf40ab48fa6a04fdda74f76f4c07), [`9bc9a47`](https://github.com/Effect-TS/effect/commit/9bc9a476800dc645903c888a68bb1d3baa3383c6), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb), [`1e2747c`](https://github.com/Effect-TS/effect/commit/1e2747c63a4820d1459cbbc88c71212983bd68bd), [`9264162`](https://github.com/Effect-TS/effect/commit/9264162a82783a651776fb7b87604564a63e7070), [`e0b9b09`](https://github.com/Effect-TS/effect/commit/e0b9b09e70c386b2da17d1f0a15b0511861c89e8), [`c36f3b9`](https://github.com/Effect-TS/effect/commit/c36f3b95df5ce9d71b66f22f26ce12eda8d3e848), [`672bde5`](https://github.com/Effect-TS/effect/commit/672bde5bec51c7d6f9862828e6a654cb2cb6f93d), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb)]:\n  - effect@3.11.0\n  - @effect/platform@0.70.0\n  - @effect/ai@0.3.0\n  - @effect/experimental@0.33.0\n\n## 0.4.17\n\n### Patch Changes\n\n- Updated dependencies [[`3069614`](https://github.com/Effect-TS/effect/commit/30696149271129fc618f6f2ccd1d8f2f6c0f9cd7), [`09a5e52`](https://github.com/Effect-TS/effect/commit/09a5e522fd9b221f05d85b1d1c8a740d4973c302)]:\n  - effect@3.10.20\n  - @effect/ai@0.2.32\n  - @effect/experimental@0.32.17\n  - @effect/platform@0.69.32\n\n## 0.4.16\n\n### Patch Changes\n\n- Updated dependencies [[`e6d4a37`](https://github.com/Effect-TS/effect/commit/e6d4a37c1d7e657b5ea44063a1cf586808228fe5)]:\n  - @effect/platform@0.69.31\n  - @effect/experimental@0.32.16\n  - @effect/ai@0.2.31\n\n## 0.4.15\n\n### Patch Changes\n\n- Updated dependencies [[`5e17400`](https://github.com/Effect-TS/effect/commit/5e1740017cb97026e7f583c5fe71847c606df388)]:\n  - @effect/experimental@0.32.15\n\n## 0.4.14\n\n### Patch Changes\n\n- Updated dependencies [[`270f199`](https://github.com/Effect-TS/effect/commit/270f199b31810fd643e4c22818698adcbdb5d396)]:\n  - @effect/platform@0.69.30\n  - @effect/experimental@0.32.14\n  - @effect/ai@0.2.30\n\n## 0.4.13\n\n### Patch Changes\n\n- Updated dependencies [[`e9dfea3`](https://github.com/Effect-TS/effect/commit/e9dfea3f394444ebd8929e5cfe05ce740cf84d6e), [`24cc35e`](https://github.com/Effect-TS/effect/commit/24cc35e26d6ed4a076470bc687ffd99cc50991b3)]:\n  - @effect/experimental@0.32.13\n  - @effect/platform@0.69.29\n  - @effect/ai@0.2.29\n\n## 0.4.12\n\n### Patch Changes\n\n- Updated dependencies [[`edd72be`](https://github.com/Effect-TS/effect/commit/edd72be57b904d60c9cbffc2537901821a9da537), [`a3e2771`](https://github.com/Effect-TS/effect/commit/a3e277170a1f7cf61fd629acb60304c7e81d9498), [`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1), [`54addee`](https://github.com/Effect-TS/effect/commit/54addee438a644bf010646c52042c7b89c5fc0a7), [`a9e00e4`](https://github.com/Effect-TS/effect/commit/a9e00e43f0b5dd22c1f9d5b78be6383daea09c20)]:\n  - @effect/platform@0.69.28\n  - @effect/experimental@0.32.12\n  - effect@3.10.19\n  - @effect/ai@0.2.28\n\n## 0.4.11\n\n### Patch Changes\n\n- Updated dependencies [[`af409cf`](https://github.com/Effect-TS/effect/commit/af409cf1d2ff973be11cc079ea373eaeedca25de), [`beaccae`](https://github.com/Effect-TS/effect/commit/beaccae2d15931e9fe475fb50a0b3638243fe3f7)]:\n  - effect@3.10.18\n  - @effect/platform@0.69.27\n  - @effect/ai@0.2.27\n  - @effect/experimental@0.32.11\n\n## 0.4.10\n\n### Patch Changes\n\n- Updated dependencies [[`c963886`](https://github.com/Effect-TS/effect/commit/c963886d5817986fcbd6bfa4ddf50aca8b6c8184), [`42c4ce6`](https://github.com/Effect-TS/effect/commit/42c4ce6f8d8c7d847e97757650a8ad9419a829d7)]:\n  - @effect/platform@0.69.26\n  - effect@3.10.17\n  - @effect/ai@0.2.26\n  - @effect/experimental@0.32.10\n\n## 0.4.9\n\n### Patch Changes\n\n- Updated dependencies [[`320557a`](https://github.com/Effect-TS/effect/commit/320557ab18d13c5e22fc7dc0d2a157eae461012f), [`4dca30c`](https://github.com/Effect-TS/effect/commit/4dca30cfcdafe4542e236489f71d6f171a5b4e38), [`1d99867`](https://github.com/Effect-TS/effect/commit/1d998671be3cd11043f232822e91dd8c98fccfa9), [`6dae414`](https://github.com/Effect-TS/effect/commit/6dae4147991a97ec14a99289bd25fadae7541e8d), [`6b0d737`](https://github.com/Effect-TS/effect/commit/6b0d737078bf63b97891e6bc47affc04b28f9cf7), [`d8356aa`](https://github.com/Effect-TS/effect/commit/d8356aad428a0c2290db52380220f81d9ec94232), [`7b93dd6`](https://github.com/Effect-TS/effect/commit/7b93dd622e2ab79c7072d79d0d9611e446202201)]:\n  - @effect/platform@0.69.25\n  - effect@3.10.16\n  - @effect/ai@0.2.25\n  - @effect/experimental@0.32.9\n\n## 0.4.8\n\n### Patch Changes\n\n- [#3949](https://github.com/Effect-TS/effect/pull/3949) [`52c4b89`](https://github.com/Effect-TS/effect/commit/52c4b89da69fa88a0fb2debe038c009c19b34573) Thanks @tim-smart! - add transformClient option to OpenAiClient layer\n\n- Updated dependencies [[`3cc6514`](https://github.com/Effect-TS/effect/commit/3cc6514d2dd64e010cb760cc29bfce98c349bb10)]:\n  - @effect/platform@0.69.24\n  - @effect/ai@0.2.24\n  - @effect/experimental@0.32.8\n\n## 0.4.7\n\n### Patch Changes\n\n- Updated dependencies [[`3aff4d3`](https://github.com/Effect-TS/effect/commit/3aff4d38837c213bb2987973dc4b98febb9f92d2)]:\n  - @effect/platform@0.69.23\n  - @effect/ai@0.2.23\n  - @effect/experimental@0.32.7\n\n## 0.4.6\n\n### Patch Changes\n\n- Updated dependencies [[`8398b32`](https://github.com/Effect-TS/effect/commit/8398b3208242a88239d4449910b7baf923cfe3b6), [`4e9e256`](https://github.com/Effect-TS/effect/commit/4e9e256e9f0b4a9e9b202d3bb703b5a4622e75cb), [`72e55b7`](https://github.com/Effect-TS/effect/commit/72e55b7c610784fcebdbadc592c876e23e76a986)]:\n  - effect@3.10.15\n  - @effect/experimental@0.32.6\n  - @effect/ai@0.2.22\n  - @effect/platform@0.69.22\n\n## 0.4.5\n\n### Patch Changes\n\n- Updated dependencies [[`f983946`](https://github.com/Effect-TS/effect/commit/f9839467b4cad6e788297764ef9f9f0b9fd203f9), [`2d8a750`](https://github.com/Effect-TS/effect/commit/2d8a75081eb83a0a81f817fdf6f428369c5064ab)]:\n  - effect@3.10.14\n  - @effect/ai@0.2.21\n  - @effect/experimental@0.32.5\n  - @effect/platform@0.69.21\n\n## 0.4.4\n\n### Patch Changes\n\n- [#3916](https://github.com/Effect-TS/effect/pull/3916) [`72b0272`](https://github.com/Effect-TS/effect/commit/72b02726d62000756577464273c0dd0876cbe0b5) Thanks @tim-smart! - use effect/JSONSchema for effect/ai & allow http client transforms\n\n- Updated dependencies [[`72b0272`](https://github.com/Effect-TS/effect/commit/72b02726d62000756577464273c0dd0876cbe0b5), [`995bbdf`](https://github.com/Effect-TS/effect/commit/995bbdffea2e332f203cd5b474cd6a1c77dfa6ae)]:\n  - @effect/ai@0.2.20\n  - effect@3.10.13\n  - @effect/experimental@0.32.4\n  - @effect/platform@0.69.20\n\n## 0.4.3\n\n### Patch Changes\n\n- Updated dependencies [[`eb8c52d`](https://github.com/Effect-TS/effect/commit/eb8c52d8b4c5e067ebf0a81eb742f5822e6439b5)]:\n  - @effect/platform@0.69.19\n  - @effect/experimental@0.32.3\n  - @effect/ai@0.2.19\n\n## 0.4.2\n\n### Patch Changes\n\n- Updated dependencies [[`a0584ec`](https://github.com/Effect-TS/effect/commit/a0584ece92ed784bfb139e9c5a699f02d1e71c2d), [`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6), [`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6)]:\n  - @effect/platform@0.69.18\n  - effect@3.10.12\n  - @effect/ai@0.2.18\n  - @effect/experimental@0.32.2\n\n## 0.4.1\n\n### Patch Changes\n\n- Updated dependencies [[`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a), [`8240b1c`](https://github.com/Effect-TS/effect/commit/8240b1c10d45312fc863cb679b1a1e8441af0c1a), [`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a)]:\n  - effect@3.10.11\n  - @effect/platform@0.69.17\n  - @effect/ai@0.2.17\n  - @effect/experimental@0.32.1\n\n## 0.4.0\n\n### Patch Changes\n\n- Updated dependencies [[`12b3275`](https://github.com/Effect-TS/effect/commit/12b32753afbf252d156ff613f9e88662b160a7e5)]:\n  - @effect/experimental@0.32.0\n\n## 0.3.0\n\n### Patch Changes\n\n- Updated dependencies [[`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`b631f40`](https://github.com/Effect-TS/effect/commit/b631f40abbe649b2a089764585b5c39f6a695ac6), [`7d89650`](https://github.com/Effect-TS/effect/commit/7d8965036cd2ea435c8441ffec3345488baebf85)]:\n  - @effect/experimental@0.31.0\n  - effect@3.10.10\n  - @effect/platform@0.69.16\n  - @effect/ai@0.2.16\n\n## 0.2.16\n\n### Patch Changes\n\n- Updated dependencies [[`8a30e1d`](https://github.com/Effect-TS/effect/commit/8a30e1dfa3a7103bf5414fc6a7fca3088d8c8c00)]:\n  - @effect/platform@0.69.15\n  - @effect/experimental@0.30.16\n  - @effect/ai@0.2.15\n\n## 0.2.15\n\n### Patch Changes\n\n- Updated dependencies [[`a123e80`](https://github.com/Effect-TS/effect/commit/a123e80f111a625428a5b5622b7f55ee1073566b), [`bd5fcd3`](https://github.com/Effect-TS/effect/commit/bd5fcd3e6b603b1e505af90d6a00627c8eca6d41), [`0289d3b`](https://github.com/Effect-TS/effect/commit/0289d3b6391031d00329365bab9791b355031fe3), [`7386b71`](https://github.com/Effect-TS/effect/commit/7386b710e5be570e17f468928a6ed19d549a3e12), [`07c493a`](https://github.com/Effect-TS/effect/commit/07c493a598e096c7810cd06def8cfa43493c46b1), [`257ab1b`](https://github.com/Effect-TS/effect/commit/257ab1b539fa6e930b7ae2583a188376372200d7), [`4211a23`](https://github.com/Effect-TS/effect/commit/4211a2355bb3af3f0e756e2aae9d293379f25662)]:\n  - effect@3.10.9\n  - @effect/platform@0.69.14\n  - @effect/experimental@0.30.15\n  - @effect/ai@0.2.14\n\n## 0.2.14\n\n### Patch Changes\n\n- Updated dependencies [[`6f86821`](https://github.com/Effect-TS/effect/commit/6f8682184ac7a7e8eec61c93b028af034c2c7254), [`68b5c9e`](https://github.com/Effect-TS/effect/commit/68b5c9e44f34192cef26e1cadda5e661a027df41), [`9c9928d`](https://github.com/Effect-TS/effect/commit/9c9928dfeacd9ac33dc37eb0ca3d7d8c39175ada), [`6306e66`](https://github.com/Effect-TS/effect/commit/6306e6656092b350d4ede5746da6f245ec9f7e07), [`361c7f3`](https://github.com/Effect-TS/effect/commit/361c7f39a2c10ede9324847c3d3ba192a6f9b20a)]:\n  - @effect/experimental@0.30.14\n  - effect@3.10.8\n  - @effect/ai@0.2.13\n  - @effect/platform@0.69.13\n\n## 0.2.13\n\n### Patch Changes\n\n- Updated dependencies [[`33f5b9f`](https://github.com/Effect-TS/effect/commit/33f5b9ffaebea4f1bd0e391b44c41fb6230e743a), [`50f0281`](https://github.com/Effect-TS/effect/commit/50f0281b0d2116726b8927a6217622d5f394f3e4)]:\n  - effect@3.10.7\n  - @effect/ai@0.2.12\n  - @effect/experimental@0.30.13\n  - @effect/platform@0.69.12\n\n## 0.2.12\n\n### Patch Changes\n\n- Updated dependencies [[`ce1c21f`](https://github.com/Effect-TS/effect/commit/ce1c21ffc11902ac9ab453a51904207859d38552), [`81ddd45`](https://github.com/Effect-TS/effect/commit/81ddd45fc074b98206fafab416d9a5a28b31e07a)]:\n  - effect@3.10.6\n  - @effect/platform@0.69.11\n  - @effect/ai@0.2.11\n  - @effect/experimental@0.30.12\n\n## 0.2.11\n\n### Patch Changes\n\n- [#3854](https://github.com/Effect-TS/effect/pull/3854) [`b521577`](https://github.com/Effect-TS/effect/commit/b521577501370e34b0672cc7a69291c7e8670c6f) Thanks @tim-smart! - update OpenAI schemas\n\n- Updated dependencies [[`3a6d757`](https://github.com/Effect-TS/effect/commit/3a6d757badeebe00d8ef4d67530d073c8264dcfa), [`59d813a`](https://github.com/Effect-TS/effect/commit/59d813aa4973d1115cfc70cc3667508335f49693)]:\n  - effect@3.10.5\n  - @effect/ai@0.2.10\n  - @effect/experimental@0.30.11\n  - @effect/platform@0.69.10\n\n## 0.2.10\n\n### Patch Changes\n\n- Updated dependencies [[`2367708`](https://github.com/Effect-TS/effect/commit/2367708be449f9526a2047e321302d7bfb16f18e)]:\n  - @effect/platform@0.69.9\n  - effect@3.10.4\n  - @effect/ai@0.2.9\n  - @effect/experimental@0.30.10\n\n## 0.2.9\n\n### Patch Changes\n\n- Updated dependencies [[`522f7c5`](https://github.com/Effect-TS/effect/commit/522f7c518a5acfb55ef96d6796869f002cc3eaf8)]:\n  - @effect/platform@0.69.8\n  - @effect/ai@0.2.8\n  - @effect/experimental@0.30.9\n\n## 0.2.8\n\n### Patch Changes\n\n- Updated dependencies [[`690d6c5`](https://github.com/Effect-TS/effect/commit/690d6c54d2145adb0af545c447db7d4755bf3c6b), [`b9423d8`](https://github.com/Effect-TS/effect/commit/b9423d8bf8181a2389fdbce1e3c14ac6fe8d54f5), [`279fe3a`](https://github.com/Effect-TS/effect/commit/279fe3a7168fe84e520c2cc88ba189a15f03a2bc)]:\n  - @effect/platform@0.69.7\n  - effect@3.10.3\n  - @effect/ai@0.2.7\n  - @effect/experimental@0.30.8\n\n## 0.2.7\n\n### Patch Changes\n\n- Updated dependencies [[`714e119`](https://github.com/Effect-TS/effect/commit/714e11945e45e5a2554ee058e6c43f82a8e309cf), [`c1afd55`](https://github.com/Effect-TS/effect/commit/c1afd55c54e61f9c432823d21b3d016f79160a37), [`42cd72a`](https://github.com/Effect-TS/effect/commit/42cd72a44ca9593e4d81fbb50e8111625fd0fb81)]:\n  - effect@3.10.2\n  - @effect/platform@0.69.6\n  - @effect/ai@0.2.6\n  - @effect/experimental@0.30.7\n\n## 0.2.6\n\n### Patch Changes\n\n- Updated dependencies [[`9604d6b`](https://github.com/Effect-TS/effect/commit/9604d6b616435103dafea8b53637a9d1450b4750), [`9604d6b`](https://github.com/Effect-TS/effect/commit/9604d6b616435103dafea8b53637a9d1450b4750)]:\n  - @effect/experimental@0.30.6\n  - effect@3.10.1\n  - @effect/ai@0.2.5\n  - @effect/platform@0.69.5\n\n## 0.2.5\n\n### Patch Changes\n\n- Updated dependencies [[`c86b1d7`](https://github.com/Effect-TS/effect/commit/c86b1d7cd47b66df190ef9775a475467c1abdbd6)]:\n  - @effect/platform@0.69.4\n  - @effect/ai@0.2.4\n  - @effect/experimental@0.30.5\n\n## 0.2.4\n\n### Patch Changes\n\n- Updated dependencies [[`d5fba63`](https://github.com/Effect-TS/effect/commit/d5fba6391e1005e374aa0238f13edfbd65848313), [`1eb2c30`](https://github.com/Effect-TS/effect/commit/1eb2c30ba064398db5790e376dedcfad55b7b005), [`02d413e`](https://github.com/Effect-TS/effect/commit/02d413e7b6bc1c64885969c37cc3e4e690c94d7d)]:\n  - @effect/platform@0.69.3\n  - @effect/ai@0.2.3\n  - @effect/experimental@0.30.4\n\n## 0.2.3\n\n### Patch Changes\n\n- Updated dependencies [[`e7afc47`](https://github.com/Effect-TS/effect/commit/e7afc47ce83e381c3f4aed2b2974e3b3d86a2340)]:\n  - @effect/platform@0.69.2\n  - @effect/ai@0.2.2\n  - @effect/experimental@0.30.3\n\n## 0.2.2\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/experimental@0.30.2\n\n## 0.2.1\n\n### Patch Changes\n\n- Updated dependencies [[`7564f56`](https://github.com/Effect-TS/effect/commit/7564f56bb2844cf39d2b0d2d9e93cf9b2205e9a8), [`7564f56`](https://github.com/Effect-TS/effect/commit/7564f56bb2844cf39d2b0d2d9e93cf9b2205e9a8)]:\n  - @effect/platform@0.69.1\n  - @effect/ai@0.2.1\n  - @effect/experimental@0.30.1\n\n## 0.2.0\n\n### Patch Changes\n\n- Updated dependencies [[`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`6d9de6b`](https://github.com/Effect-TS/effect/commit/6d9de6b871c5c08e6509a4e830c3d74758faa198), [`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`c79c4c1`](https://github.com/Effect-TS/effect/commit/c79c4c178390fe61ff6dda88c9e058862349343a), [`38d30f0`](https://github.com/Effect-TS/effect/commit/38d30f08b8da62f9c3e308b9250738cb8d17bdb5), [`5821ce3`](https://github.com/Effect-TS/effect/commit/5821ce3455b47d25e0a40cae6ce22af9db5fa556)]:\n  - effect@3.10.0\n  - @effect/platform@0.69.0\n  - @effect/experimental@0.30.0\n  - @effect/ai@0.2.0\n\n## 0.1.4\n\n### Patch Changes\n\n- Updated dependencies [[`382556f`](https://github.com/Effect-TS/effect/commit/382556f8930780c0634de681077706113a8c8239), [`97cb014`](https://github.com/Effect-TS/effect/commit/97cb0145114b2cd2f378e98f6c4ff5bf2c1865f5)]:\n  - @effect/schema@0.75.5\n  - @effect/ai@0.1.4\n  - @effect/experimental@0.29.6\n  - @effect/platform@0.68.6\n\n## 0.1.3\n\n### Patch Changes\n\n- Updated dependencies [[`2036402`](https://github.com/Effect-TS/effect/commit/20364020b8b75a684791aa93d90626758023e9e9)]:\n  - @effect/platform@0.68.5\n  - @effect/ai@0.1.3\n  - @effect/experimental@0.29.5\n\n## 0.1.2\n\n### Patch Changes\n\n- Updated dependencies [[`1b1ef29`](https://github.com/Effect-TS/effect/commit/1b1ef29ae302322f69dc938f9337aa97b4c63266)]:\n  - @effect/platform@0.68.4\n  - @effect/ai@0.1.2\n  - @effect/experimental@0.29.4\n\n## 0.1.1\n\n### Patch Changes\n\n- Updated dependencies [[`61a99b2`](https://github.com/Effect-TS/effect/commit/61a99b2bf9d757870ef0c2ec9d4c877cdd364a3d), [`8c33087`](https://github.com/Effect-TS/effect/commit/8c330879425e80bed2f65e407cd59e991f0d7bec)]:\n  - effect@3.9.2\n  - @effect/platform@0.68.3\n  - @effect/ai@0.1.1\n  - @effect/experimental@0.29.3\n  - @effect/schema@0.75.4\n\n## 0.1.0\n\n### Minor Changes\n\n- [#3631](https://github.com/Effect-TS/effect/pull/3631) [`bd160a4`](https://github.com/Effect-TS/effect/commit/bd160a4f714b0f1cb5867e458fd70f9131b060d6) Thanks @tim-smart! - add @effect/ai packages\n\n  Experimental modules for working with LLMs, currently only from OpenAI.\n\n### Patch Changes\n\n- Updated dependencies [[`bd160a4`](https://github.com/Effect-TS/effect/commit/bd160a4f714b0f1cb5867e458fd70f9131b060d6), [`bd160a4`](https://github.com/Effect-TS/effect/commit/bd160a4f714b0f1cb5867e458fd70f9131b060d6), [`360ec14`](https://github.com/Effect-TS/effect/commit/360ec14dd4102c526aef7433a8881ad4d9beab75)]:\n  - @effect/experimental@0.29.2\n  - @effect/ai@0.1.0\n  - @effect/schema@0.75.3\n  - @effect/platform@0.68.2\n"
  },
  {
    "path": "packages/ai/openai/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Effectful Technologies Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/ai/openai/README.md",
    "content": "# `@effect/ai-openai`\n\n## Documentation\n\n- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/ai/openai).\n"
  },
  {
    "path": "packages/ai/openai/docgen.json",
    "content": "{\n  \"$schema\": \"../../../node_modules/@effect/docgen/schema.json\",\n  \"exclude\": [\"src/Generated.ts\", \"src/internal/**/*.ts\"],\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/ai/openai/src/\",\n  \"examplesCompilerOptions\": {\n    \"noEmit\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"module\": \"ES2022\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n    \"paths\": {\n      \"effect\": [\"../../../../effect/src/index.js\"],\n      \"effect/*\": [\"../../../../effect/src/*.js\"],\n      \"@effect/experimental\": [\"../../../../experimental/src/index.js\"],\n      \"@effect/experimental/*\": [\"../../../../experimental/src/*.js\"],\n      \"@effect/platform\": [\"../../../../platform/src/index.js\"],\n      \"@effect/platform/*\": [\"../../../../platform/src/*.js\"],\n      \"@effect/ai\": [\"../../../ai/src/index.js\"],\n      \"@effect/ai/*\": [\"../../../ai/src/*.js\"],\n      \"@effect/ai-openai\": [\"../../../ai-openai/src/index.js\"],\n      \"@effect/ai-openai/*\": [\"../../../ai-openai/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/ai/openai/package.json",
    "content": "{\n  \"name\": \"@effect/ai-openai\",\n  \"type\": \"module\",\n  \"version\": \"0.39.0\",\n  \"license\": \"MIT\",\n  \"description\": \"Effect modules for working with AI apis\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/ai/openai\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"keywords\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"peerDependencies\": {\n    \"@effect/ai\": \"workspace:^\",\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"effect\": \"workspace:^\"\n  },\n  \"devDependencies\": {\n    \"@effect/ai\": \"workspace:^\",\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/platform-node\": \"workspace:^\",\n    \"@tim-smart/openapi-gen\": \"^0.4.10\",\n    \"effect\": \"workspace:^\"\n  },\n  \"dependencies\": {\n    \"gpt-tokenizer\": \"^2.9.0\"\n  }\n}\n"
  },
  {
    "path": "packages/ai/openai/scripts/generate.sh",
    "content": "#!/usr/bin/env bash\n\nset -euo pipefail\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &> /dev/null && pwd)\n\ntemp_dir=$(mktemp -d)\n\ncleanup() {\n  rm -rf \"${temp_dir}\"\n}\n\ntrap cleanup EXIT\n\nopenapi_spec_url=\"https://app.stainless.com/api/spec/documented/openai/openapi.documented.yml\"\ntemp_file=\"${temp_dir}/openai.yaml\"\n\ntouch \"${temp_file}\"\ncurl \"${openapi_spec_url}\" > \"${temp_file}\"\n\necho \"/**\n * @since 1.0.0\n */\" > src/Generated.ts\n\npnpm openapi-gen -s \"${temp_file}\" >> src/Generated.ts\n\npnpm eslint --fix src/Generated.ts\n\ngit apply --reject --whitespace=fix \"${SCRIPT_DIR}/generated.patch\"\n"
  },
  {
    "path": "packages/ai/openai/scripts/generated.patch",
    "content": "diff --git a/packages/ai/openai/src/Generated.ts b/packages/ai/openai/src/Generated.ts\nindex 1f2580576..a24c4f359 100644\n--- a/packages/ai/openai/src/Generated.ts\n+++ b/packages/ai/openai/src/Generated.ts\n@@ -915,9 +915,9 @@ export class CreateTranscriptionResponseVerboseJson\n {}\n \n export class CreateTranscription200 extends S.Union(\n-  CreateTranscriptionResponseJson,\n+  CreateTranscriptionResponseVerboseJson,\n   CreateTranscriptionResponseDiarizedJson,\n-  CreateTranscriptionResponseVerboseJson\n+  CreateTranscriptionResponseJson\n ) {}\n \n export class CreateTranslationRequestModelEnum extends S.Literal(\"whisper-1\") {}\n"
  },
  {
    "path": "packages/ai/openai/src/Generated.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientError from \"@effect/platform/HttpClientError\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as HttpClientResponse from \"@effect/platform/HttpClientResponse\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\n\nexport class ListAssistantsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListAssistantsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListAssistantsParamsOrder, { nullable: true, default: () => \"desc\" as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"before\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `assistant`.\n */\nexport class AssistantObjectObject extends S.Literal(\"assistant\") {}\n\n/**\n * The type of tool being defined: `code_interpreter`\n */\nexport class AssistantToolsCodeType extends S.Literal(\"code_interpreter\") {}\n\nexport class AssistantToolsCode extends S.Class<AssistantToolsCode>(\"AssistantToolsCode\")({\n  /**\n   * The type of tool being defined: `code_interpreter`\n   */\n  \"type\": AssistantToolsCodeType\n}) {}\n\n/**\n * The type of tool being defined: `file_search`\n */\nexport class AssistantToolsFileSearchType extends S.Literal(\"file_search\") {}\n\n/**\n * The ranker to use for the file search. If not specified will use the `auto` ranker.\n */\nexport class FileSearchRanker extends S.Literal(\"auto\", \"default_2024_08_21\") {}\n\n/**\n * The ranking options for the file search. If not specified, the file search tool will use the `auto` ranker and a score_threshold of 0.\n *\n * See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n */\nexport class FileSearchRankingOptions extends S.Class<FileSearchRankingOptions>(\"FileSearchRankingOptions\")({\n  \"ranker\": S.optionalWith(FileSearchRanker, { nullable: true }),\n  /**\n   * The score threshold for the file search. All values must be a floating point number between 0 and 1.\n   */\n  \"score_threshold\": S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1))\n}) {}\n\nexport class AssistantToolsFileSearch extends S.Class<AssistantToolsFileSearch>(\"AssistantToolsFileSearch\")({\n  /**\n   * The type of tool being defined: `file_search`\n   */\n  \"type\": AssistantToolsFileSearchType,\n  /**\n   * Overrides for the file search tool.\n   */\n  \"file_search\": S.optionalWith(\n    S.Struct({\n      /**\n       * The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive.\n       *\n       * Note that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n       */\n      \"max_num_results\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(50)), {\n        nullable: true\n      }),\n      \"ranking_options\": S.optionalWith(FileSearchRankingOptions, { nullable: true })\n    }),\n    { nullable: true }\n  )\n}) {}\n\n/**\n * The type of tool being defined: `function`\n */\nexport class AssistantToolsFunctionType extends S.Literal(\"function\") {}\n\n/**\n * The parameters the functions accepts, described as a JSON Schema object. See the [guide](https://platform.openai.com/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.\n *\n * Omitting `parameters` defines a function with an empty parameter list.\n */\nexport class FunctionParameters extends S.Record({ key: S.String, value: S.Unknown }) {}\n\nexport class FunctionObject extends S.Class<FunctionObject>(\"FunctionObject\")({\n  /**\n   * A description of what the function does, used by the model to choose when and how to call the function.\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.\n   */\n  \"name\": S.String,\n  \"parameters\": S.optionalWith(FunctionParameters, { nullable: true }),\n  \"strict\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class AssistantToolsFunction extends S.Class<AssistantToolsFunction>(\"AssistantToolsFunction\")({\n  /**\n   * The type of tool being defined: `function`\n   */\n  \"type\": AssistantToolsFunctionType,\n  \"function\": FunctionObject\n}) {}\n\nexport class AssistantTool extends S.Union(AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction) {}\n\nexport class Metadata extends S.Union(\n  /**\n   * Set of 16 key-value pairs that can be attached to an object. This can be\n   * useful for storing additional information about the object in a structured\n   * format, and querying for objects via API or the dashboard.\n   *\n   * Keys are strings with a maximum length of 64 characters. Values are strings\n   * with a maximum length of 512 characters.\n   */\n  S.Record({ key: S.String, value: S.Unknown }),\n  S.Null\n) {}\n\n/**\n * `auto` is the default value\n */\nexport class AssistantsApiResponseFormatOptionEnum extends S.Literal(\"auto\") {}\n\n/**\n * The type of response format being defined. Always `text`.\n */\nexport class ResponseFormatTextType extends S.Literal(\"text\") {}\n\n/**\n * Default response format. Used to generate text responses.\n */\nexport class ResponseFormatText extends S.Class<ResponseFormatText>(\"ResponseFormatText\")({\n  /**\n   * The type of response format being defined. Always `text`.\n   */\n  \"type\": ResponseFormatTextType\n}) {}\n\n/**\n * The type of response format being defined. Always `json_object`.\n */\nexport class ResponseFormatJsonObjectType extends S.Literal(\"json_object\") {}\n\n/**\n * JSON object response format. An older method of generating JSON responses.\n * Using `json_schema` is recommended for models that support it. Note that the\n * model will not generate JSON without a system or user message instructing it\n * to do so.\n */\nexport class ResponseFormatJsonObject extends S.Class<ResponseFormatJsonObject>(\"ResponseFormatJsonObject\")({\n  /**\n   * The type of response format being defined. Always `json_object`.\n   */\n  \"type\": ResponseFormatJsonObjectType\n}) {}\n\n/**\n * The type of response format being defined. Always `json_schema`.\n */\nexport class ResponseFormatJsonSchemaType extends S.Literal(\"json_schema\") {}\n\n/**\n * The schema for the response format, described as a JSON Schema object.\n * Learn how to build JSON schemas [here](https://json-schema.org/).\n */\nexport class ResponseFormatJsonSchemaSchema extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * JSON Schema response format. Used to generate structured JSON responses.\n * Learn more about [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs).\n */\nexport class ResponseFormatJsonSchema extends S.Class<ResponseFormatJsonSchema>(\"ResponseFormatJsonSchema\")({\n  /**\n   * The type of response format being defined. Always `json_schema`.\n   */\n  \"type\": ResponseFormatJsonSchemaType,\n  /**\n   * Structured Outputs configuration options, including a JSON Schema.\n   */\n  \"json_schema\": S.Struct({\n    /**\n     * A description of what the response format is for, used by the model to\n     * determine how to respond in the format.\n     */\n    \"description\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The name of the response format. Must be a-z, A-Z, 0-9, or contain\n     * underscores and dashes, with a maximum length of 64.\n     */\n    \"name\": S.String,\n    \"schema\": S.optionalWith(ResponseFormatJsonSchemaSchema, { nullable: true }),\n    \"strict\": S.optionalWith(S.Boolean, { nullable: true })\n  })\n}) {}\n\n/**\n * Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n *\n * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * Setting to `{ \"type\": \"json_object\" }` enables JSON mode, which ensures the message the model generates is valid JSON.\n *\n * **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly \"stuck\" request. Also note that the message content may be partially cut off if `finish_reason=\"length\"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.\n */\nexport class AssistantsApiResponseFormatOption extends S.Union(\n  /**\n   * `auto` is the default value\n   */\n  AssistantsApiResponseFormatOptionEnum,\n  ResponseFormatText,\n  ResponseFormatJsonObject,\n  ResponseFormatJsonSchema\n) {}\n\n/**\n * Represents an `assistant` that can call the model and use tools.\n */\nexport class AssistantObject extends S.Class<AssistantObject>(\"AssistantObject\")({\n  /**\n   * The identifier, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `assistant`.\n   */\n  \"object\": AssistantObjectObject,\n  /**\n   * The Unix timestamp (in seconds) for when the assistant was created.\n   */\n  \"created_at\": S.Int,\n  \"name\": S.NullOr(S.String.pipe(S.maxLength(256))),\n  \"description\": S.NullOr(S.String.pipe(S.maxLength(512))),\n  /**\n   * ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n   */\n  \"model\": S.String,\n  \"instructions\": S.NullOr(S.String.pipe(S.maxLength(256000))),\n  /**\n   * A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n   */\n  \"tools\": S.Array(AssistantTool).pipe(S.maxItems(128)).pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => [] as const)\n  ),\n  \"tool_resources\": S.optionalWith(\n    S.Struct({\n      \"code_interpreter\": S.optionalWith(\n        S.Struct({\n          /**\n           * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool.\n           */\n          \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(20)), {\n            nullable: true,\n            default: () => [] as const\n          })\n        }),\n        { nullable: true }\n      ),\n      \"file_search\": S.optionalWith(\n        S.Struct({\n          /**\n           * The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n           */\n          \"vector_store_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(1)), { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown })),\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  \"response_format\": S.optionalWith(AssistantsApiResponseFormatOption, { nullable: true })\n}) {}\n\nexport class ListAssistantsResponse extends S.Class<ListAssistantsResponse>(\"ListAssistantsResponse\")({\n  \"object\": S.String,\n  \"data\": S.Array(AssistantObject),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\nexport class AssistantSupportedModels extends S.Literal(\n  \"gpt-5\",\n  \"gpt-5-mini\",\n  \"gpt-5-nano\",\n  \"gpt-5-2025-08-07\",\n  \"gpt-5-mini-2025-08-07\",\n  \"gpt-5-nano-2025-08-07\",\n  \"gpt-4.1\",\n  \"gpt-4.1-mini\",\n  \"gpt-4.1-nano\",\n  \"gpt-4.1-2025-04-14\",\n  \"gpt-4.1-mini-2025-04-14\",\n  \"gpt-4.1-nano-2025-04-14\",\n  \"o3-mini\",\n  \"o3-mini-2025-01-31\",\n  \"o1\",\n  \"o1-2024-12-17\",\n  \"gpt-4o\",\n  \"gpt-4o-2024-11-20\",\n  \"gpt-4o-2024-08-06\",\n  \"gpt-4o-2024-05-13\",\n  \"gpt-4o-mini\",\n  \"gpt-4o-mini-2024-07-18\",\n  \"gpt-4.5-preview\",\n  \"gpt-4.5-preview-2025-02-27\",\n  \"gpt-4-turbo\",\n  \"gpt-4-turbo-2024-04-09\",\n  \"gpt-4-0125-preview\",\n  \"gpt-4-turbo-preview\",\n  \"gpt-4-1106-preview\",\n  \"gpt-4-vision-preview\",\n  \"gpt-4\",\n  \"gpt-4-0314\",\n  \"gpt-4-0613\",\n  \"gpt-4-32k\",\n  \"gpt-4-32k-0314\",\n  \"gpt-4-32k-0613\",\n  \"gpt-3.5-turbo\",\n  \"gpt-3.5-turbo-16k\",\n  \"gpt-3.5-turbo-0613\",\n  \"gpt-3.5-turbo-1106\",\n  \"gpt-3.5-turbo-0125\",\n  \"gpt-3.5-turbo-16k-0613\"\n) {}\n\n/**\n * Constrains effort on reasoning for\n * [reasoning models](https://platform.openai.com/docs/guides/reasoning).\n * Currently supported values are `none`, `minimal`, `low`, `medium`, and `high`. Reducing\n * reasoning effort can result in faster responses and fewer tokens used\n * on reasoning in a response.\n *\n * - `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported reasoning values for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool calls are supported for all reasoning values in gpt-5.1.\n * - All models before `gpt-5.1` default to `medium` reasoning effort, and do not support `none`.\n * - The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort.\n */\nexport class ReasoningEffortEnum extends S.Literal(\"none\", \"minimal\", \"low\", \"medium\", \"high\") {}\n\nexport class ReasoningEffort extends S.Union(\n  /**\n   * Constrains effort on reasoning for\n   * [reasoning models](https://platform.openai.com/docs/guides/reasoning).\n   * Currently supported values are `none`, `minimal`, `low`, `medium`, and `high`. Reducing\n   * reasoning effort can result in faster responses and fewer tokens used\n   * on reasoning in a response.\n   *\n   * - `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported reasoning values for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool calls are supported for all reasoning values in gpt-5.1.\n   * - All models before `gpt-5.1` default to `medium` reasoning effort, and do not support `none`.\n   * - The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort.\n   */\n  ReasoningEffortEnum,\n  S.Null\n) {}\n\nexport class CreateAssistantRequest extends S.Class<CreateAssistantRequest>(\"CreateAssistantRequest\")({\n  /**\n   * ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n   */\n  \"model\": S.Union(S.String, AssistantSupportedModels),\n  \"name\": S.optionalWith(S.String.pipe(S.maxLength(256)), { nullable: true }),\n  \"description\": S.optionalWith(S.String.pipe(S.maxLength(512)), { nullable: true }),\n  \"instructions\": S.optionalWith(S.String.pipe(S.maxLength(256000)), { nullable: true }),\n  \"reasoning_effort\": S.optionalWith(S.Literal(\"none\", \"minimal\", \"low\", \"medium\", \"high\"), { nullable: true }),\n  /**\n   * A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n   */\n  \"tools\": S.optionalWith(S.Array(AssistantTool).pipe(S.maxItems(128)), { nullable: true, default: () => [] as const }),\n  \"tool_resources\": S.optionalWith(\n    S.Struct({\n      \"code_interpreter\": S.optionalWith(\n        S.Struct({\n          /**\n           * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n           */\n          \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(20)), {\n            nullable: true,\n            default: () => [] as const\n          })\n        }),\n        { nullable: true }\n      ),\n      \"file_search\": S.optionalWith(\n        S.Struct({\n          /**\n           * The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n           */\n          \"vector_store_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(1)), { nullable: true }),\n          /**\n           * A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n           */\n          \"vector_stores\": S.optionalWith(\n            S.Array(S.Struct({\n              /**\n               * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n               */\n              \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(10000)), { nullable: true }),\n              /**\n               * The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.\n               */\n              \"chunking_strategy\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n              \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n            })).pipe(S.maxItems(1)),\n            { nullable: true }\n          )\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  \"response_format\": S.optionalWith(AssistantsApiResponseFormatOption, { nullable: true })\n}) {}\n\nexport class ModifyAssistantRequest extends S.Class<ModifyAssistantRequest>(\"ModifyAssistantRequest\")({\n  /**\n   * ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n   */\n  \"model\": S.optionalWith(S.Union(S.String, AssistantSupportedModels), { nullable: true }),\n  \"reasoning_effort\": S.optionalWith(S.Literal(\"none\", \"minimal\", \"low\", \"medium\", \"high\"), { nullable: true }),\n  \"name\": S.optionalWith(S.String.pipe(S.maxLength(256)), { nullable: true }),\n  \"description\": S.optionalWith(S.String.pipe(S.maxLength(512)), { nullable: true }),\n  \"instructions\": S.optionalWith(S.String.pipe(S.maxLength(256000)), { nullable: true }),\n  /**\n   * A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n   */\n  \"tools\": S.optionalWith(S.Array(AssistantTool).pipe(S.maxItems(128)), { nullable: true, default: () => [] as const }),\n  \"tool_resources\": S.optionalWith(\n    S.Struct({\n      \"code_interpreter\": S.optionalWith(\n        S.Struct({\n          /**\n           * Overrides the list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n           */\n          \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(20)), {\n            nullable: true,\n            default: () => [] as const\n          })\n        }),\n        { nullable: true }\n      ),\n      \"file_search\": S.optionalWith(\n        S.Struct({\n          /**\n           * Overrides the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n           */\n          \"vector_store_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(1)), { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  \"response_format\": S.optionalWith(AssistantsApiResponseFormatOption, { nullable: true })\n}) {}\n\nexport class DeleteAssistantResponseObject extends S.Literal(\"assistant.deleted\") {}\n\nexport class DeleteAssistantResponse extends S.Class<DeleteAssistantResponse>(\"DeleteAssistantResponse\")({\n  \"id\": S.String,\n  \"deleted\": S.Boolean,\n  \"object\": DeleteAssistantResponseObject\n}) {}\n\nexport class CreateSpeechRequestModelEnum extends S.Literal(\"tts-1\", \"tts-1-hd\", \"gpt-4o-mini-tts\") {}\n\nexport class VoiceIdsSharedEnum\n  extends S.Literal(\"alloy\", \"ash\", \"ballad\", \"coral\", \"echo\", \"sage\", \"shimmer\", \"verse\", \"marin\", \"cedar\")\n{}\n\nexport class VoiceIdsShared extends S.Union(S.String, VoiceIdsSharedEnum) {}\n\n/**\n * The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`.\n */\nexport class CreateSpeechRequestResponseFormat extends S.Literal(\"mp3\", \"opus\", \"aac\", \"flac\", \"wav\", \"pcm\") {}\n\n/**\n * The format to stream the audio in. Supported formats are `sse` and `audio`. `sse` is not supported for `tts-1` or `tts-1-hd`.\n */\nexport class CreateSpeechRequestStreamFormat extends S.Literal(\"sse\", \"audio\") {}\n\nexport class CreateSpeechRequest extends S.Class<CreateSpeechRequest>(\"CreateSpeechRequest\")({\n  /**\n   * One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`.\n   */\n  \"model\": S.Union(S.String, CreateSpeechRequestModelEnum),\n  /**\n   * The text to generate audio for. The maximum length is 4096 characters.\n   */\n  \"input\": S.String.pipe(S.maxLength(4096)),\n  /**\n   * Control the voice of your generated audio with additional instructions. Does not work with `tts-1` or `tts-1-hd`.\n   */\n  \"instructions\": S.optionalWith(S.String.pipe(S.maxLength(4096)), { nullable: true }),\n  /**\n   * The voice to use when generating the audio. Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options).\n   */\n  \"voice\": VoiceIdsShared,\n  /**\n   * The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`.\n   */\n  \"response_format\": S.optionalWith(CreateSpeechRequestResponseFormat, {\n    nullable: true,\n    default: () => \"mp3\" as const\n  }),\n  /**\n   * The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default.\n   */\n  \"speed\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0.25), S.lessThanOrEqualTo(4)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * The format to stream the audio in. Supported formats are `sse` and `audio`. `sse` is not supported for `tts-1` or `tts-1-hd`.\n   */\n  \"stream_format\": S.optionalWith(CreateSpeechRequestStreamFormat, { nullable: true, default: () => \"audio\" as const })\n}) {}\n\nexport class CreateTranscriptionRequestModelEnum\n  extends S.Literal(\"whisper-1\", \"gpt-4o-transcribe\", \"gpt-4o-mini-transcribe\", \"gpt-4o-transcribe-diarize\")\n{}\n\n/**\n * The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, `vtt`, or `diarized_json`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is `json`. For `gpt-4o-transcribe-diarize`, the supported formats are `json`, `text`, and `diarized_json`, with `diarized_json` required to receive speaker annotations.\n */\nexport class AudioResponseFormat extends S.Literal(\"json\", \"text\", \"srt\", \"verbose_json\", \"vtt\", \"diarized_json\") {}\n\nexport class TranscriptionInclude extends S.Literal(\"logprobs\") {}\n\n/**\n * Automatically set chunking parameters based on the audio. Must be set to `\"auto\"`.\n */\nexport class TranscriptionChunkingStrategyEnum extends S.Literal(\"auto\") {}\n\n/**\n * Must be set to `server_vad` to enable manual chunking using server side VAD.\n */\nexport class VadConfigType extends S.Literal(\"server_vad\") {}\n\nexport class VadConfig extends S.Class<VadConfig>(\"VadConfig\")({\n  /**\n   * Must be set to `server_vad` to enable manual chunking using server side VAD.\n   */\n  \"type\": VadConfigType,\n  /**\n   * Amount of audio to include before the VAD detected speech (in\n   * milliseconds).\n   */\n  \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true, default: () => 300 as const }),\n  /**\n   * Duration of silence to detect speech stop (in milliseconds).\n   * With shorter values the model will respond more quickly,\n   * but may jump in on short pauses from the user.\n   */\n  \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true, default: () => 200 as const }),\n  /**\n   * Sensitivity threshold (0.0 to 1.0) for voice activity detection. A\n   * higher threshold will require louder audio to activate the model, and\n   * thus might perform better in noisy environments.\n   */\n  \"threshold\": S.optionalWith(S.Number, { nullable: true, default: () => 0.5 as const })\n}) {}\n\nexport class TranscriptionChunkingStrategy extends S.Union(\n  /**\n   * Controls how the audio is cut into chunks. When set to `\"auto\"`, the server first normalizes loudness and then uses voice activity detection (VAD) to choose boundaries. `server_vad` object can be provided to tweak VAD detection parameters manually. If unset, the audio is transcribed as a single block. Required when using `gpt-4o-transcribe-diarize` for inputs longer than 30 seconds.\n   */\n  S.Union(\n    /**\n     * Automatically set chunking parameters based on the audio. Must be set to `\"auto\"`.\n     */\n    S.Literal(\"auto\"),\n    VadConfig\n  ),\n  S.Null\n) {}\n\nexport class CreateTranscriptionRequest extends S.Class<CreateTranscriptionRequest>(\"CreateTranscriptionRequest\")({\n  /**\n   * The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n   */\n  \"file\": S.instanceOf(globalThis.Blob),\n  /**\n   * ID of the model to use. The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, `whisper-1` (which is powered by our open source Whisper V2 model), and `gpt-4o-transcribe-diarize`.\n   */\n  \"model\": S.Union(S.String, CreateTranscriptionRequestModelEnum),\n  /**\n   * The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format will improve accuracy and latency.\n   */\n  \"language\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * An optional text to guide the model's style or continue a previous audio segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should match the audio language. This field is not supported when using `gpt-4o-transcribe-diarize`.\n   */\n  \"prompt\": S.optionalWith(S.String, { nullable: true }),\n  \"response_format\": S.optionalWith(AudioResponseFormat, { nullable: true, default: () => \"json\" as const }),\n  /**\n   * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n   */\n  \"temperature\": S.optionalWith(S.Number, { nullable: true, default: () => 0 as const }),\n  /**\n   * Additional information to include in the transcription response.\n   * `logprobs` will return the log probabilities of the tokens in the\n   * response to understand the model's confidence in the transcription.\n   * `logprobs` only works with response_format set to `json` and only with\n   * the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`. This field is not supported when using `gpt-4o-transcribe-diarize`.\n   */\n  \"include\": S.optionalWith(S.Array(TranscriptionInclude), { nullable: true }),\n  /**\n   * The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency.\n   * This option is not available for `gpt-4o-transcribe-diarize`.\n   */\n  \"timestamp_granularities\": S.optionalWith(S.Array(S.Literal(\"word\", \"segment\")), {\n    nullable: true,\n    default: () => [\"segment\"] as const\n  }),\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"chunking_strategy\": S.optionalWith(\n    S.Union(\n      /**\n       * Automatically set chunking parameters based on the audio. Must be set to `\"auto\"`.\n       */\n      S.Literal(\"auto\"),\n      VadConfig\n    ),\n    { nullable: true }\n  ),\n  /**\n   * Optional list of speaker names that correspond to the audio samples provided in `known_speaker_references[]`. Each entry should be a short identifier (for example `customer` or `agent`). Up to 4 speakers are supported.\n   */\n  \"known_speaker_names\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(4)), { nullable: true }),\n  /**\n   * Optional list of audio samples (as [data URLs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs)) that contain known speaker references matching `known_speaker_names[]`. Each sample must be between 2 and 10 seconds, and can use any of the same input audio formats supported by `file`.\n   */\n  \"known_speaker_references\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(4)), { nullable: true })\n}) {}\n\n/**\n * The type of the usage object. Always `tokens` for this variant.\n */\nexport class TranscriptTextUsageTokensType extends S.Literal(\"tokens\") {}\n\n/**\n * Usage statistics for models billed by token usage.\n */\nexport class TranscriptTextUsageTokens extends S.Class<TranscriptTextUsageTokens>(\"TranscriptTextUsageTokens\")({\n  /**\n   * The type of the usage object. Always `tokens` for this variant.\n   */\n  \"type\": TranscriptTextUsageTokensType,\n  /**\n   * Number of input tokens billed for this request.\n   */\n  \"input_tokens\": S.Int,\n  /**\n   * Details about the input tokens billed for this request.\n   */\n  \"input_token_details\": S.optionalWith(\n    S.Struct({\n      /**\n       * Number of text tokens billed for this request.\n       */\n      \"text_tokens\": S.optionalWith(S.Int, { nullable: true }),\n      /**\n       * Number of audio tokens billed for this request.\n       */\n      \"audio_tokens\": S.optionalWith(S.Int, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * Number of output tokens generated.\n   */\n  \"output_tokens\": S.Int,\n  /**\n   * Total number of tokens used (input + output).\n   */\n  \"total_tokens\": S.Int\n}) {}\n\n/**\n * The type of the usage object. Always `duration` for this variant.\n */\nexport class TranscriptTextUsageDurationType extends S.Literal(\"duration\") {}\n\n/**\n * Usage statistics for models billed by audio input duration.\n */\nexport class TranscriptTextUsageDuration extends S.Class<TranscriptTextUsageDuration>(\"TranscriptTextUsageDuration\")({\n  /**\n   * The type of the usage object. Always `duration` for this variant.\n   */\n  \"type\": TranscriptTextUsageDurationType,\n  /**\n   * Duration of the input audio in seconds.\n   */\n  \"seconds\": S.Number\n}) {}\n\n/**\n * Represents a transcription response returned by model, based on the provided input.\n */\nexport class CreateTranscriptionResponseJson\n  extends S.Class<CreateTranscriptionResponseJson>(\"CreateTranscriptionResponseJson\")({\n    /**\n     * The transcribed text.\n     */\n    \"text\": S.String,\n    /**\n     * The log probabilities of the tokens in the transcription. Only returned with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added to the `include` array.\n     */\n    \"logprobs\": S.optionalWith(\n      S.Array(S.Struct({\n        /**\n         * The token in the transcription.\n         */\n        \"token\": S.optionalWith(S.String, { nullable: true }),\n        /**\n         * The log probability of the token.\n         */\n        \"logprob\": S.optionalWith(S.Number, { nullable: true }),\n        /**\n         * The bytes of the token.\n         */\n        \"bytes\": S.optionalWith(S.Array(S.Number), { nullable: true })\n      })),\n      { nullable: true }\n    ),\n    /**\n     * Token usage statistics for the request.\n     */\n    \"usage\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * The type of task that was run. Always `transcribe`.\n */\nexport class CreateTranscriptionResponseDiarizedJsonTask extends S.Literal(\"transcribe\") {}\n\n/**\n * The type of the segment. Always `transcript.text.segment`.\n */\nexport class TranscriptionDiarizedSegmentType extends S.Literal(\"transcript.text.segment\") {}\n\n/**\n * A segment of diarized transcript text with speaker metadata.\n */\nexport class TranscriptionDiarizedSegment\n  extends S.Class<TranscriptionDiarizedSegment>(\"TranscriptionDiarizedSegment\")({\n    /**\n     * The type of the segment. Always `transcript.text.segment`.\n     */\n    \"type\": TranscriptionDiarizedSegmentType,\n    /**\n     * Unique identifier for the segment.\n     */\n    \"id\": S.String,\n    /**\n     * Start timestamp of the segment in seconds.\n     */\n    \"start\": S.Number,\n    /**\n     * End timestamp of the segment in seconds.\n     */\n    \"end\": S.Number,\n    /**\n     * Transcript text for this segment.\n     */\n    \"text\": S.String,\n    /**\n     * Speaker label for this segment. When known speakers are provided, the label matches `known_speaker_names[]`. Otherwise speakers are labeled sequentially using capital letters (`A`, `B`, ...).\n     */\n    \"speaker\": S.String\n  })\n{}\n\n/**\n * Represents a diarized transcription response returned by the model, including the combined transcript and speaker-segment annotations.\n */\nexport class CreateTranscriptionResponseDiarizedJson\n  extends S.Class<CreateTranscriptionResponseDiarizedJson>(\"CreateTranscriptionResponseDiarizedJson\")({\n    /**\n     * The type of task that was run. Always `transcribe`.\n     */\n    \"task\": CreateTranscriptionResponseDiarizedJsonTask,\n    /**\n     * Duration of the input audio in seconds.\n     */\n    \"duration\": S.Number,\n    /**\n     * The concatenated transcript text for the entire audio input.\n     */\n    \"text\": S.String,\n    /**\n     * Segments of the transcript annotated with timestamps and speaker labels.\n     */\n    \"segments\": S.Array(TranscriptionDiarizedSegment),\n    /**\n     * Token or duration usage statistics for the request.\n     */\n    \"usage\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\nexport class TranscriptionWord extends S.Class<TranscriptionWord>(\"TranscriptionWord\")({\n  /**\n   * The text content of the word.\n   */\n  \"word\": S.String,\n  /**\n   * Start time of the word in seconds.\n   */\n  \"start\": S.Number,\n  /**\n   * End time of the word in seconds.\n   */\n  \"end\": S.Number\n}) {}\n\nexport class TranscriptionSegment extends S.Class<TranscriptionSegment>(\"TranscriptionSegment\")({\n  /**\n   * Unique identifier of the segment.\n   */\n  \"id\": S.Int,\n  /**\n   * Seek offset of the segment.\n   */\n  \"seek\": S.Int,\n  /**\n   * Start time of the segment in seconds.\n   */\n  \"start\": S.Number,\n  /**\n   * End time of the segment in seconds.\n   */\n  \"end\": S.Number,\n  /**\n   * Text content of the segment.\n   */\n  \"text\": S.String,\n  /**\n   * Array of token IDs for the text content.\n   */\n  \"tokens\": S.Array(S.Int),\n  /**\n   * Temperature parameter used for generating the segment.\n   */\n  \"temperature\": S.Number,\n  /**\n   * Average logprob of the segment. If the value is lower than -1, consider the logprobs failed.\n   */\n  \"avg_logprob\": S.Number,\n  /**\n   * Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed.\n   */\n  \"compression_ratio\": S.Number,\n  /**\n   * Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent.\n   */\n  \"no_speech_prob\": S.Number\n}) {}\n\n/**\n * Represents a verbose json transcription response returned by model, based on the provided input.\n */\nexport class CreateTranscriptionResponseVerboseJson\n  extends S.Class<CreateTranscriptionResponseVerboseJson>(\"CreateTranscriptionResponseVerboseJson\")({\n    /**\n     * The language of the input audio.\n     */\n    \"language\": S.String,\n    /**\n     * The duration of the input audio.\n     */\n    \"duration\": S.Number,\n    /**\n     * The transcribed text.\n     */\n    \"text\": S.String,\n    /**\n     * Extracted words and their corresponding timestamps.\n     */\n    \"words\": S.optionalWith(S.Array(TranscriptionWord), { nullable: true }),\n    /**\n     * Segments of the transcribed text and their corresponding details.\n     */\n    \"segments\": S.optionalWith(S.Array(TranscriptionSegment), { nullable: true }),\n    \"usage\": S.optionalWith(TranscriptTextUsageDuration, { nullable: true })\n  })\n{}\n\nexport class CreateTranscription200 extends S.Union(\n  CreateTranscriptionResponseVerboseJson,\n  CreateTranscriptionResponseDiarizedJson,\n  CreateTranscriptionResponseJson\n) {}\n\nexport class CreateTranslationRequestModelEnum extends S.Literal(\"whisper-1\") {}\n\n/**\n * The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`.\n */\nexport class CreateTranslationRequestResponseFormat extends S.Literal(\"json\", \"text\", \"srt\", \"verbose_json\", \"vtt\") {}\n\nexport class CreateTranslationRequest extends S.Class<CreateTranslationRequest>(\"CreateTranslationRequest\")({\n  /**\n   * The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n   */\n  \"file\": S.instanceOf(globalThis.Blob),\n  /**\n   * ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available.\n   */\n  \"model\": S.Union(S.String, CreateTranslationRequestModelEnum),\n  /**\n   * An optional text to guide the model's style or continue a previous audio segment. The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should be in English.\n   */\n  \"prompt\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`.\n   */\n  \"response_format\": S.optionalWith(CreateTranslationRequestResponseFormat, {\n    nullable: true,\n    default: () => \"json\" as const\n  }),\n  /**\n   * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n   */\n  \"temperature\": S.optionalWith(S.Number, { nullable: true, default: () => 0 as const })\n}) {}\n\nexport class CreateTranslationResponseJson\n  extends S.Class<CreateTranslationResponseJson>(\"CreateTranslationResponseJson\")({\n    \"text\": S.String\n  })\n{}\n\nexport class CreateTranslationResponseVerboseJson\n  extends S.Class<CreateTranslationResponseVerboseJson>(\"CreateTranslationResponseVerboseJson\")({\n    /**\n     * The language of the output translation (always `english`).\n     */\n    \"language\": S.String,\n    /**\n     * The duration of the input audio.\n     */\n    \"duration\": S.Number,\n    /**\n     * The translated text.\n     */\n    \"text\": S.String,\n    /**\n     * Segments of the translated text and their corresponding details.\n     */\n    \"segments\": S.optionalWith(S.Array(TranscriptionSegment), { nullable: true })\n  })\n{}\n\nexport class CreateTranslation200\n  extends S.Union(CreateTranslationResponseJson, CreateTranslationResponseVerboseJson)\n{}\n\nexport class ListBatchesParams extends S.Struct({\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const })\n}) {}\n\n/**\n * The object type, which is always `batch`.\n */\nexport class BatchObject extends S.Literal(\"batch\") {}\n\nexport class BatchError extends S.Class<BatchError>(\"BatchError\")({\n  /**\n   * An error code identifying the error type.\n   */\n  \"code\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * A human-readable message providing more details about the error.\n   */\n  \"message\": S.optionalWith(S.String, { nullable: true }),\n  \"param\": S.optionalWith(S.String, { nullable: true }),\n  \"line\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * The current status of the batch.\n */\nexport class BatchStatus extends S.Literal(\n  \"validating\",\n  \"failed\",\n  \"in_progress\",\n  \"finalizing\",\n  \"completed\",\n  \"expired\",\n  \"cancelling\",\n  \"cancelled\"\n) {}\n\n/**\n * The request counts for different statuses within the batch.\n */\nexport class BatchRequestCounts extends S.Class<BatchRequestCounts>(\"BatchRequestCounts\")({\n  /**\n   * Total number of requests in the batch.\n   */\n  \"total\": S.Int,\n  /**\n   * Number of requests that have been completed successfully.\n   */\n  \"completed\": S.Int,\n  /**\n   * Number of requests that have failed.\n   */\n  \"failed\": S.Int\n}) {}\n\nexport class Batch extends S.Class<Batch>(\"Batch\")({\n  \"id\": S.String,\n  /**\n   * The object type, which is always `batch`.\n   */\n  \"object\": BatchObject,\n  /**\n   * The OpenAI API endpoint used by the batch.\n   */\n  \"endpoint\": S.String,\n  /**\n   * Model ID used to process the batch, like `gpt-5-2025-08-07`. OpenAI\n   * offers a wide range of models with different capabilities, performance\n   * characteristics, and price points. Refer to the [model\n   * guide](https://platform.openai.com/docs/models) to browse and compare available models.\n   */\n  \"model\": S.optionalWith(S.String, { nullable: true }),\n  \"errors\": S.optionalWith(\n    S.Struct({\n      /**\n       * The object type, which is always `list`.\n       */\n      \"object\": S.optionalWith(S.String, { nullable: true }),\n      \"data\": S.optionalWith(S.Array(BatchError), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The ID of the input file for the batch.\n   */\n  \"input_file_id\": S.String,\n  /**\n   * The time frame within which the batch should be processed.\n   */\n  \"completion_window\": S.String,\n  /**\n   * The current status of the batch.\n   */\n  \"status\": BatchStatus,\n  /**\n   * The ID of the file containing the outputs of successfully executed requests.\n   */\n  \"output_file_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The ID of the file containing the outputs of requests with errors.\n   */\n  \"error_file_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The Unix timestamp (in seconds) for when the batch was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The Unix timestamp (in seconds) for when the batch started processing.\n   */\n  \"in_progress_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The Unix timestamp (in seconds) for when the batch will expire.\n   */\n  \"expires_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The Unix timestamp (in seconds) for when the batch started finalizing.\n   */\n  \"finalizing_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The Unix timestamp (in seconds) for when the batch was completed.\n   */\n  \"completed_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The Unix timestamp (in seconds) for when the batch failed.\n   */\n  \"failed_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The Unix timestamp (in seconds) for when the batch expired.\n   */\n  \"expired_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The Unix timestamp (in seconds) for when the batch started cancelling.\n   */\n  \"cancelling_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The Unix timestamp (in seconds) for when the batch was cancelled.\n   */\n  \"cancelled_at\": S.optionalWith(S.Int, { nullable: true }),\n  \"request_counts\": S.optionalWith(BatchRequestCounts, { nullable: true }),\n  /**\n   * Represents token usage details including input tokens, output tokens, a\n   * breakdown of output tokens, and the total tokens used. Only populated on\n   * batches created after September 7, 2025.\n   */\n  \"usage\": S.optionalWith(\n    S.Struct({\n      /**\n       * The number of input tokens.\n       */\n      \"input_tokens\": S.Int,\n      /**\n       * A detailed breakdown of the input tokens.\n       */\n      \"input_tokens_details\": S.Struct({\n        /**\n         * The number of tokens that were retrieved from the cache. [More on\n         * prompt caching](https://platform.openai.com/docs/guides/prompt-caching).\n         */\n        \"cached_tokens\": S.Int\n      }),\n      /**\n       * The number of output tokens.\n       */\n      \"output_tokens\": S.Int,\n      /**\n       * A detailed breakdown of the output tokens.\n       */\n      \"output_tokens_details\": S.Struct({\n        /**\n         * The number of reasoning tokens.\n         */\n        \"reasoning_tokens\": S.Int\n      }),\n      /**\n       * The total number of tokens used.\n       */\n      \"total_tokens\": S.Int\n    }),\n    { nullable: true }\n  ),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class ListBatchesResponseObject extends S.Literal(\"list\") {}\n\nexport class ListBatchesResponse extends S.Class<ListBatchesResponse>(\"ListBatchesResponse\")({\n  \"data\": S.Array(Batch),\n  \"first_id\": S.optionalWith(S.String, { nullable: true }),\n  \"last_id\": S.optionalWith(S.String, { nullable: true }),\n  \"has_more\": S.Boolean,\n  \"object\": ListBatchesResponseObject\n}) {}\n\n/**\n * The endpoint to be used for all requests in the batch. Currently `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, `/v1/completions`, and `/v1/moderations` are supported. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch.\n */\nexport class CreateBatchRequestEndpoint\n  extends S.Literal(\"/v1/responses\", \"/v1/chat/completions\", \"/v1/embeddings\", \"/v1/completions\", \"/v1/moderations\")\n{}\n\n/**\n * The time frame within which the batch should be processed. Currently only `24h` is supported.\n */\nexport class CreateBatchRequestCompletionWindow extends S.Literal(\"24h\") {}\n\n/**\n * Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. Note that the anchor is the file creation time, not the time the batch is created.\n */\nexport class BatchFileExpirationAfterAnchor extends S.Literal(\"created_at\") {}\n\n/**\n * The expiration policy for the output and/or error file that are generated for a batch.\n */\nexport class BatchFileExpirationAfter extends S.Class<BatchFileExpirationAfter>(\"BatchFileExpirationAfter\")({\n  /**\n   * Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. Note that the anchor is the file creation time, not the time the batch is created.\n   */\n  \"anchor\": BatchFileExpirationAfterAnchor,\n  /**\n   * The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days).\n   */\n  \"seconds\": S.Int.pipe(S.greaterThanOrEqualTo(3600), S.lessThanOrEqualTo(2592000))\n}) {}\n\nexport class CreateBatchRequest extends S.Class<CreateBatchRequest>(\"CreateBatchRequest\")({\n  /**\n   * The ID of an uploaded file that contains requests for the new batch.\n   *\n   * See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file.\n   *\n   * Your input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 200 MB in size.\n   */\n  \"input_file_id\": S.String,\n  /**\n   * The endpoint to be used for all requests in the batch. Currently `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, `/v1/completions`, and `/v1/moderations` are supported. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch.\n   */\n  \"endpoint\": CreateBatchRequestEndpoint,\n  /**\n   * The time frame within which the batch should be processed. Currently only `24h` is supported.\n   */\n  \"completion_window\": CreateBatchRequestCompletionWindow,\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"output_expires_after\": S.optionalWith(BatchFileExpirationAfter, { nullable: true })\n}) {}\n\nexport class ListChatCompletionsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListChatCompletionsParams extends S.Struct({\n  \"model\": S.optionalWith(S.String, { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListChatCompletionsParamsOrder, { nullable: true, default: () => \"asc\" as const })\n}) {}\n\n/**\n * The type of this object. It is always set to \"list\".\n */\nexport class ChatCompletionListObject extends S.Literal(\"list\") {}\n\n/**\n * The type of the tool. Currently, only `function` is supported.\n */\nexport class ChatCompletionMessageToolCallType extends S.Literal(\"function\") {}\n\n/**\n * A call to a function tool created by the model.\n */\nexport class ChatCompletionMessageToolCall\n  extends S.Class<ChatCompletionMessageToolCall>(\"ChatCompletionMessageToolCall\")({\n    /**\n     * The ID of the tool call.\n     */\n    \"id\": S.String,\n    /**\n     * The type of the tool. Currently, only `function` is supported.\n     */\n    \"type\": ChatCompletionMessageToolCallType,\n    /**\n     * The function that the model called.\n     */\n    \"function\": S.Struct({\n      /**\n       * The name of the function to call.\n       */\n      \"name\": S.String,\n      /**\n       * The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.\n       */\n      \"arguments\": S.String\n    })\n  })\n{}\n\n/**\n * The type of the tool. Always `custom`.\n */\nexport class ChatCompletionMessageCustomToolCallType extends S.Literal(\"custom\") {}\n\n/**\n * A call to a custom tool created by the model.\n */\nexport class ChatCompletionMessageCustomToolCall\n  extends S.Class<ChatCompletionMessageCustomToolCall>(\"ChatCompletionMessageCustomToolCall\")({\n    /**\n     * The ID of the tool call.\n     */\n    \"id\": S.String,\n    /**\n     * The type of the tool. Always `custom`.\n     */\n    \"type\": ChatCompletionMessageCustomToolCallType,\n    /**\n     * The custom tool that the model called.\n     */\n    \"custom\": S.Struct({\n      /**\n       * The name of the custom tool to call.\n       */\n      \"name\": S.String,\n      /**\n       * The input for the custom tool call generated by the model.\n       */\n      \"input\": S.String\n    })\n  })\n{}\n\n/**\n * The tool calls generated by the model, such as function calls.\n */\nexport class ChatCompletionMessageToolCalls\n  extends S.Array(S.Union(ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall))\n{}\n\n/**\n * The role of the author of this message.\n */\nexport class ChatCompletionResponseMessageRole extends S.Literal(\"assistant\") {}\n\n/**\n * A chat completion message generated by the model.\n */\nexport class ChatCompletionResponseMessage\n  extends S.Class<ChatCompletionResponseMessage>(\"ChatCompletionResponseMessage\")({\n    \"content\": S.NullOr(S.String),\n    \"refusal\": S.NullOr(S.String),\n    \"tool_calls\": S.optionalWith(ChatCompletionMessageToolCalls, { nullable: true }),\n    /**\n     * Annotations for the message, when applicable, as when using the\n     * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n     */\n    \"annotations\": S.optionalWith(\n      S.Array(S.Struct({\n        /**\n         * The type of the URL citation. Always `url_citation`.\n         */\n        \"type\": S.Literal(\"url_citation\"),\n        /**\n         * A URL citation when using web search.\n         */\n        \"url_citation\": S.Struct({\n          /**\n           * The index of the last character of the URL citation in the message.\n           */\n          \"end_index\": S.Int,\n          /**\n           * The index of the first character of the URL citation in the message.\n           */\n          \"start_index\": S.Int,\n          /**\n           * The URL of the web resource.\n           */\n          \"url\": S.String,\n          /**\n           * The title of the web resource.\n           */\n          \"title\": S.String\n        })\n      })),\n      { nullable: true }\n    ),\n    /**\n     * The role of the author of this message.\n     */\n    \"role\": ChatCompletionResponseMessageRole,\n    /**\n     * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.\n     */\n    \"function_call\": S.optionalWith(\n      S.Struct({\n        /**\n         * The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.\n         */\n        \"arguments\": S.String,\n        /**\n         * The name of the function to call.\n         */\n        \"name\": S.String\n      }),\n      { nullable: true }\n    ),\n    \"audio\": S.optionalWith(\n      S.Struct({\n        /**\n         * Unique identifier for this audio response.\n         */\n        \"id\": S.String,\n        /**\n         * The Unix timestamp (in seconds) for when this audio response will\n         * no longer be accessible on the server for use in multi-turn\n         * conversations.\n         */\n        \"expires_at\": S.Int,\n        /**\n         * Base64 encoded audio bytes generated by the model, in the format\n         * specified in the request.\n         */\n        \"data\": S.String,\n        /**\n         * Transcript of the audio generated by the model.\n         */\n        \"transcript\": S.String\n      }),\n      { nullable: true }\n    )\n  })\n{}\n\nexport class ChatCompletionTokenLogprob extends S.Class<ChatCompletionTokenLogprob>(\"ChatCompletionTokenLogprob\")({\n  /**\n   * The token.\n   */\n  \"token\": S.String,\n  /**\n   * The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely.\n   */\n  \"logprob\": S.Number,\n  \"bytes\": S.NullOr(S.Array(S.Int)),\n  /**\n   * List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested `top_logprobs` returned.\n   */\n  \"top_logprobs\": S.Array(S.Struct({\n    /**\n     * The token.\n     */\n    \"token\": S.String,\n    /**\n     * The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely.\n     */\n    \"logprob\": S.Number,\n    \"bytes\": S.NullOr(S.Array(S.Int))\n  }))\n}) {}\n\n/**\n * Specifies the processing type used for serving the request.\n *   - If set to 'auto', then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use 'default'.\n *   - If set to 'default', then the request will be processed with the standard pricing and performance for the selected model.\n *   - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or '[priority](https://openai.com/api-priority-processing/)', then the request will be processed with the corresponding service tier.\n *   - When not set, the default behavior is 'auto'.\n *\n *   When the `service_tier` parameter is set, the response body will include the `service_tier` value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter.\n */\nexport class ServiceTierEnum extends S.Literal(\"auto\", \"default\", \"flex\", \"scale\", \"priority\") {}\n\nexport class ServiceTier extends S.Union(\n  /**\n   * Specifies the processing type used for serving the request.\n   *   - If set to 'auto', then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use 'default'.\n   *   - If set to 'default', then the request will be processed with the standard pricing and performance for the selected model.\n   *   - If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or '[priority](https://openai.com/api-priority-processing/)', then the request will be processed with the corresponding service tier.\n   *   - When not set, the default behavior is 'auto'.\n   *\n   *   When the `service_tier` parameter is set, the response body will include the `service_tier` value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter.\n   */\n  ServiceTierEnum,\n  S.Null\n) {}\n\n/**\n * The object type, which is always `chat.completion`.\n */\nexport class CreateChatCompletionResponseObject extends S.Literal(\"chat.completion\") {}\n\n/**\n * Usage statistics for the completion request.\n */\nexport class CompletionUsage extends S.Class<CompletionUsage>(\"CompletionUsage\")({\n  /**\n   * Number of tokens in the generated completion.\n   */\n  \"completion_tokens\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Number of tokens in the prompt.\n   */\n  \"prompt_tokens\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Total number of tokens used in the request (prompt + completion).\n   */\n  \"total_tokens\": S.Int.pipe(S.propertySignature, S.withConstructorDefault(() => 0 as const)),\n  /**\n   * Breakdown of tokens used in a completion.\n   */\n  \"completion_tokens_details\": S.optionalWith(\n    S.Struct({\n      /**\n       * When using Predicted Outputs, the number of tokens in the\n       * prediction that appeared in the completion.\n       */\n      \"accepted_prediction_tokens\": S.optionalWith(S.Int, { nullable: true, default: () => 0 as const }),\n      /**\n       * Audio input tokens generated by the model.\n       */\n      \"audio_tokens\": S.optionalWith(S.Int, { nullable: true, default: () => 0 as const }),\n      /**\n       * Tokens generated by the model for reasoning.\n       */\n      \"reasoning_tokens\": S.optionalWith(S.Int, { nullable: true, default: () => 0 as const }),\n      /**\n       * When using Predicted Outputs, the number of tokens in the\n       * prediction that did not appear in the completion. However, like\n       * reasoning tokens, these tokens are still counted in the total\n       * completion tokens for purposes of billing, output, and context window\n       * limits.\n       */\n      \"rejected_prediction_tokens\": S.optionalWith(S.Int, { nullable: true, default: () => 0 as const })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * Breakdown of tokens used in the prompt.\n   */\n  \"prompt_tokens_details\": S.optionalWith(\n    S.Struct({\n      /**\n       * Audio input tokens present in the prompt.\n       */\n      \"audio_tokens\": S.optionalWith(S.Int, { nullable: true, default: () => 0 as const }),\n      /**\n       * Cached tokens present in the prompt.\n       */\n      \"cached_tokens\": S.optionalWith(S.Int, { nullable: true, default: () => 0 as const })\n    }),\n    { nullable: true }\n  )\n}) {}\n\n/**\n * Represents a chat completion response returned by model, based on the provided input.\n */\nexport class CreateChatCompletionResponse\n  extends S.Class<CreateChatCompletionResponse>(\"CreateChatCompletionResponse\")({\n    /**\n     * A unique identifier for the chat completion.\n     */\n    \"id\": S.String,\n    /**\n     * A list of chat completion choices. Can be more than one if `n` is greater than 1.\n     */\n    \"choices\": S.Array(S.Struct({\n      /**\n       * The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n       * `length` if the maximum number of tokens specified in the request was reached,\n       * `content_filter` if content was omitted due to a flag from our content filters,\n       * `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n       */\n      \"finish_reason\": S.Literal(\"stop\", \"length\", \"tool_calls\", \"content_filter\", \"function_call\"),\n      /**\n       * The index of the choice in the list of choices.\n       */\n      \"index\": S.Int,\n      \"message\": ChatCompletionResponseMessage,\n      \"logprobs\": S.NullOr(S.Struct({\n        \"content\": S.NullOr(S.Array(ChatCompletionTokenLogprob)),\n        \"refusal\": S.NullOr(S.Array(ChatCompletionTokenLogprob))\n      }))\n    })),\n    /**\n     * The Unix timestamp (in seconds) of when the chat completion was created.\n     */\n    \"created\": S.Int,\n    /**\n     * The model used for the chat completion.\n     */\n    \"model\": S.String,\n    \"service_tier\": S.optionalWith(S.Literal(\"auto\", \"default\", \"flex\", \"scale\", \"priority\"), { nullable: true }),\n    /**\n     * This fingerprint represents the backend configuration that the model runs with.\n     *\n     * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n     */\n    \"system_fingerprint\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The object type, which is always `chat.completion`.\n     */\n    \"object\": CreateChatCompletionResponseObject,\n    \"usage\": S.optionalWith(CompletionUsage, { nullable: true })\n  })\n{}\n\n/**\n * An object representing a list of Chat Completions.\n */\nexport class ChatCompletionList extends S.Class<ChatCompletionList>(\"ChatCompletionList\")({\n  /**\n   * The type of this object. It is always set to \"list\".\n   */\n  \"object\": ChatCompletionListObject.pipe(S.propertySignature, S.withConstructorDefault(() => \"list\" as const)),\n  /**\n   * An array of chat completion objects.\n   */\n  \"data\": S.Array(CreateChatCompletionResponse),\n  /**\n   * The identifier of the first chat completion in the data array.\n   */\n  \"first_id\": S.String,\n  /**\n   * The identifier of the last chat completion in the data array.\n   */\n  \"last_id\": S.String,\n  /**\n   * Indicates whether there are more Chat Completions available.\n   */\n  \"has_more\": S.Boolean\n}) {}\n\n/**\n * The type of the content part.\n */\nexport class ChatCompletionRequestMessageContentPartTextType extends S.Literal(\"text\") {}\n\n/**\n * Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation).\n */\nexport class ChatCompletionRequestMessageContentPartText\n  extends S.Class<ChatCompletionRequestMessageContentPartText>(\"ChatCompletionRequestMessageContentPartText\")({\n    /**\n     * The type of the content part.\n     */\n    \"type\": ChatCompletionRequestMessageContentPartTextType,\n    /**\n     * The text content.\n     */\n    \"text\": S.String\n  })\n{}\n\n/**\n * The role of the messages author, in this case `developer`.\n */\nexport class ChatCompletionRequestDeveloperMessageRole extends S.Literal(\"developer\") {}\n\n/**\n * Developer-provided instructions that the model should follow, regardless of\n * messages sent by the user. With o1 models and newer, `developer` messages\n * replace the previous `system` messages.\n */\nexport class ChatCompletionRequestDeveloperMessage\n  extends S.Class<ChatCompletionRequestDeveloperMessage>(\"ChatCompletionRequestDeveloperMessage\")({\n    /**\n     * The contents of the developer message.\n     */\n    \"content\": S.Union(\n      /**\n       * The contents of the developer message.\n       */\n      S.String,\n      /**\n       * An array of content parts with a defined type. For developer messages, only type `text` is supported.\n       */\n      S.NonEmptyArray(ChatCompletionRequestMessageContentPartText).pipe(S.minItems(1))\n    ),\n    /**\n     * The role of the messages author, in this case `developer`.\n     */\n    \"role\": ChatCompletionRequestDeveloperMessageRole,\n    /**\n     * An optional name for the participant. Provides the model information to differentiate between participants of the same role.\n     */\n    \"name\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\nexport class ChatCompletionRequestSystemMessageContentPart extends ChatCompletionRequestMessageContentPartText {}\n\n/**\n * The role of the messages author, in this case `system`.\n */\nexport class ChatCompletionRequestSystemMessageRole extends S.Literal(\"system\") {}\n\n/**\n * Developer-provided instructions that the model should follow, regardless of\n * messages sent by the user. With o1 models and newer, use `developer` messages\n * for this purpose instead.\n */\nexport class ChatCompletionRequestSystemMessage\n  extends S.Class<ChatCompletionRequestSystemMessage>(\"ChatCompletionRequestSystemMessage\")({\n    /**\n     * The contents of the system message.\n     */\n    \"content\": S.Union(\n      /**\n       * The contents of the system message.\n       */\n      S.String,\n      /**\n       * An array of content parts with a defined type. For system messages, only type `text` is supported.\n       */\n      S.NonEmptyArray(ChatCompletionRequestSystemMessageContentPart).pipe(S.minItems(1))\n    ),\n    /**\n     * The role of the messages author, in this case `system`.\n     */\n    \"role\": ChatCompletionRequestSystemMessageRole,\n    /**\n     * An optional name for the participant. Provides the model information to differentiate between participants of the same role.\n     */\n    \"name\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * The type of the content part.\n */\nexport class ChatCompletionRequestMessageContentPartImageType extends S.Literal(\"image_url\") {}\n\n/**\n * Specifies the detail level of the image. Learn more in the [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding).\n */\nexport class ChatCompletionRequestMessageContentPartImageImageUrlDetail extends S.Literal(\"auto\", \"low\", \"high\") {}\n\n/**\n * Learn about [image inputs](https://platform.openai.com/docs/guides/vision).\n */\nexport class ChatCompletionRequestMessageContentPartImage\n  extends S.Class<ChatCompletionRequestMessageContentPartImage>(\"ChatCompletionRequestMessageContentPartImage\")({\n    /**\n     * The type of the content part.\n     */\n    \"type\": ChatCompletionRequestMessageContentPartImageType,\n    \"image_url\": S.Struct({\n      /**\n       * Either a URL of the image or the base64 encoded image data.\n       */\n      \"url\": S.String,\n      /**\n       * Specifies the detail level of the image. Learn more in the [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding).\n       */\n      \"detail\": S.optionalWith(ChatCompletionRequestMessageContentPartImageImageUrlDetail, {\n        nullable: true,\n        default: () => \"auto\" as const\n      })\n    })\n  })\n{}\n\n/**\n * The type of the content part. Always `input_audio`.\n */\nexport class ChatCompletionRequestMessageContentPartAudioType extends S.Literal(\"input_audio\") {}\n\n/**\n * The format of the encoded audio data. Currently supports \"wav\" and \"mp3\".\n */\nexport class ChatCompletionRequestMessageContentPartAudioInputAudioFormat extends S.Literal(\"wav\", \"mp3\") {}\n\n/**\n * Learn about [audio inputs](https://platform.openai.com/docs/guides/audio).\n */\nexport class ChatCompletionRequestMessageContentPartAudio\n  extends S.Class<ChatCompletionRequestMessageContentPartAudio>(\"ChatCompletionRequestMessageContentPartAudio\")({\n    /**\n     * The type of the content part. Always `input_audio`.\n     */\n    \"type\": ChatCompletionRequestMessageContentPartAudioType,\n    \"input_audio\": S.Struct({\n      /**\n       * Base64 encoded audio data.\n       */\n      \"data\": S.String,\n      /**\n       * The format of the encoded audio data. Currently supports \"wav\" and \"mp3\".\n       */\n      \"format\": ChatCompletionRequestMessageContentPartAudioInputAudioFormat\n    })\n  })\n{}\n\n/**\n * The type of the content part. Always `file`.\n */\nexport class ChatCompletionRequestMessageContentPartFileType extends S.Literal(\"file\") {}\n\n/**\n * Learn about [file inputs](https://platform.openai.com/docs/guides/text) for text generation.\n */\nexport class ChatCompletionRequestMessageContentPartFile\n  extends S.Class<ChatCompletionRequestMessageContentPartFile>(\"ChatCompletionRequestMessageContentPartFile\")({\n    /**\n     * The type of the content part. Always `file`.\n     */\n    \"type\": ChatCompletionRequestMessageContentPartFileType,\n    \"file\": S.Struct({\n      /**\n       * The name of the file, used when passing the file to the model as a\n       * string.\n       */\n      \"filename\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The base64 encoded file data, used when passing the file to the model\n       * as a string.\n       */\n      \"file_data\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The ID of an uploaded file to use as input.\n       */\n      \"file_id\": S.optionalWith(S.String, { nullable: true })\n    })\n  })\n{}\n\nexport class ChatCompletionRequestUserMessageContentPart extends S.Union(\n  ChatCompletionRequestMessageContentPartText,\n  ChatCompletionRequestMessageContentPartImage,\n  ChatCompletionRequestMessageContentPartAudio,\n  ChatCompletionRequestMessageContentPartFile\n) {}\n\n/**\n * The role of the messages author, in this case `user`.\n */\nexport class ChatCompletionRequestUserMessageRole extends S.Literal(\"user\") {}\n\n/**\n * Messages sent by an end user, containing prompts or additional context\n * information.\n */\nexport class ChatCompletionRequestUserMessage\n  extends S.Class<ChatCompletionRequestUserMessage>(\"ChatCompletionRequestUserMessage\")({\n    /**\n     * The contents of the user message.\n     */\n    \"content\": S.Union(\n      /**\n       * The text contents of the message.\n       */\n      S.String,\n      /**\n       * An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text, image, or audio inputs.\n       */\n      S.NonEmptyArray(ChatCompletionRequestUserMessageContentPart).pipe(S.minItems(1))\n    ),\n    /**\n     * The role of the messages author, in this case `user`.\n     */\n    \"role\": ChatCompletionRequestUserMessageRole,\n    /**\n     * An optional name for the participant. Provides the model information to differentiate between participants of the same role.\n     */\n    \"name\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * The type of the content part.\n */\nexport class ChatCompletionRequestMessageContentPartRefusalType extends S.Literal(\"refusal\") {}\n\nexport class ChatCompletionRequestMessageContentPartRefusal\n  extends S.Class<ChatCompletionRequestMessageContentPartRefusal>(\"ChatCompletionRequestMessageContentPartRefusal\")({\n    /**\n     * The type of the content part.\n     */\n    \"type\": ChatCompletionRequestMessageContentPartRefusalType,\n    /**\n     * The refusal message generated by the model.\n     */\n    \"refusal\": S.String\n  })\n{}\n\nexport class ChatCompletionRequestAssistantMessageContentPart\n  extends S.Union(ChatCompletionRequestMessageContentPartText, ChatCompletionRequestMessageContentPartRefusal)\n{}\n\n/**\n * The role of the messages author, in this case `assistant`.\n */\nexport class ChatCompletionRequestAssistantMessageRole extends S.Literal(\"assistant\") {}\n\n/**\n * Messages sent by the model in response to user messages.\n */\nexport class ChatCompletionRequestAssistantMessage\n  extends S.Class<ChatCompletionRequestAssistantMessage>(\"ChatCompletionRequestAssistantMessage\")({\n    \"content\": S.optionalWith(\n      S.Union(\n        /**\n         * The contents of the assistant message.\n         */\n        S.String,\n        /**\n         * An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`.\n         */\n        S.NonEmptyArray(ChatCompletionRequestAssistantMessageContentPart).pipe(S.minItems(1))\n      ),\n      { nullable: true }\n    ),\n    \"refusal\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The role of the messages author, in this case `assistant`.\n     */\n    \"role\": ChatCompletionRequestAssistantMessageRole,\n    /**\n     * An optional name for the participant. Provides the model information to differentiate between participants of the same role.\n     */\n    \"name\": S.optionalWith(S.String, { nullable: true }),\n    \"audio\": S.optionalWith(\n      S.Struct({\n        /**\n         * Unique identifier for a previous audio response from the model.\n         */\n        \"id\": S.String\n      }),\n      { nullable: true }\n    ),\n    \"tool_calls\": S.optionalWith(ChatCompletionMessageToolCalls, { nullable: true }),\n    \"function_call\": S.optionalWith(\n      S.Struct({\n        /**\n         * The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.\n         */\n        \"arguments\": S.String,\n        /**\n         * The name of the function to call.\n         */\n        \"name\": S.String\n      }),\n      { nullable: true }\n    )\n  })\n{}\n\n/**\n * The role of the messages author, in this case `tool`.\n */\nexport class ChatCompletionRequestToolMessageRole extends S.Literal(\"tool\") {}\n\nexport class ChatCompletionRequestToolMessageContentPart extends ChatCompletionRequestMessageContentPartText {}\n\nexport class ChatCompletionRequestToolMessage\n  extends S.Class<ChatCompletionRequestToolMessage>(\"ChatCompletionRequestToolMessage\")({\n    /**\n     * The role of the messages author, in this case `tool`.\n     */\n    \"role\": ChatCompletionRequestToolMessageRole,\n    /**\n     * The contents of the tool message.\n     */\n    \"content\": S.Union(\n      /**\n       * The contents of the tool message.\n       */\n      S.String,\n      /**\n       * An array of content parts with a defined type. For tool messages, only type `text` is supported.\n       */\n      S.NonEmptyArray(ChatCompletionRequestToolMessageContentPart).pipe(S.minItems(1))\n    ),\n    /**\n     * Tool call that this message is responding to.\n     */\n    \"tool_call_id\": S.String\n  })\n{}\n\n/**\n * The role of the messages author, in this case `function`.\n */\nexport class ChatCompletionRequestFunctionMessageRole extends S.Literal(\"function\") {}\n\nexport class ChatCompletionRequestFunctionMessage\n  extends S.Class<ChatCompletionRequestFunctionMessage>(\"ChatCompletionRequestFunctionMessage\")({\n    /**\n     * The role of the messages author, in this case `function`.\n     */\n    \"role\": ChatCompletionRequestFunctionMessageRole,\n    \"content\": S.NullOr(S.String),\n    /**\n     * The name of the function to call.\n     */\n    \"name\": S.String\n  })\n{}\n\nexport class ChatCompletionRequestMessage extends S.Union(\n  ChatCompletionRequestDeveloperMessage,\n  ChatCompletionRequestSystemMessage,\n  ChatCompletionRequestUserMessage,\n  ChatCompletionRequestAssistantMessage,\n  ChatCompletionRequestToolMessage,\n  ChatCompletionRequestFunctionMessage\n) {}\n\nexport class ChatModel extends S.Literal(\n  \"gpt-5.1\",\n  \"gpt-5.1-2025-11-13\",\n  \"gpt-5.1-codex\",\n  \"gpt-5.1-mini\",\n  \"gpt-5.1-chat-latest\",\n  \"gpt-5\",\n  \"gpt-5-mini\",\n  \"gpt-5-nano\",\n  \"gpt-5-2025-08-07\",\n  \"gpt-5-mini-2025-08-07\",\n  \"gpt-5-nano-2025-08-07\",\n  \"gpt-5-chat-latest\",\n  \"gpt-4.1\",\n  \"gpt-4.1-mini\",\n  \"gpt-4.1-nano\",\n  \"gpt-4.1-2025-04-14\",\n  \"gpt-4.1-mini-2025-04-14\",\n  \"gpt-4.1-nano-2025-04-14\",\n  \"o4-mini\",\n  \"o4-mini-2025-04-16\",\n  \"o3\",\n  \"o3-2025-04-16\",\n  \"o3-mini\",\n  \"o3-mini-2025-01-31\",\n  \"o1\",\n  \"o1-2024-12-17\",\n  \"o1-preview\",\n  \"o1-preview-2024-09-12\",\n  \"o1-mini\",\n  \"o1-mini-2024-09-12\",\n  \"gpt-4o\",\n  \"gpt-4o-2024-11-20\",\n  \"gpt-4o-2024-08-06\",\n  \"gpt-4o-2024-05-13\",\n  \"gpt-4o-audio-preview\",\n  \"gpt-4o-audio-preview-2024-10-01\",\n  \"gpt-4o-audio-preview-2024-12-17\",\n  \"gpt-4o-audio-preview-2025-06-03\",\n  \"gpt-4o-mini-audio-preview\",\n  \"gpt-4o-mini-audio-preview-2024-12-17\",\n  \"gpt-4o-search-preview\",\n  \"gpt-4o-mini-search-preview\",\n  \"gpt-4o-search-preview-2025-03-11\",\n  \"gpt-4o-mini-search-preview-2025-03-11\",\n  \"chatgpt-4o-latest\",\n  \"codex-mini-latest\",\n  \"gpt-4o-mini\",\n  \"gpt-4o-mini-2024-07-18\",\n  \"gpt-4-turbo\",\n  \"gpt-4-turbo-2024-04-09\",\n  \"gpt-4-0125-preview\",\n  \"gpt-4-turbo-preview\",\n  \"gpt-4-1106-preview\",\n  \"gpt-4-vision-preview\",\n  \"gpt-4\",\n  \"gpt-4-0314\",\n  \"gpt-4-0613\",\n  \"gpt-4-32k\",\n  \"gpt-4-32k-0314\",\n  \"gpt-4-32k-0613\",\n  \"gpt-3.5-turbo\",\n  \"gpt-3.5-turbo-16k\",\n  \"gpt-3.5-turbo-0301\",\n  \"gpt-3.5-turbo-0613\",\n  \"gpt-3.5-turbo-1106\",\n  \"gpt-3.5-turbo-0125\",\n  \"gpt-3.5-turbo-16k-0613\"\n) {}\n\nexport class ModelIdsShared extends S.Union(S.String, ChatModel) {}\n\nexport class ResponseModalities extends S.Union(\n  /**\n   * Output types that you would like the model to generate.\n   * Most models are capable of generating text, which is the default:\n   *\n   * `[\"text\"]`\n   *\n   * The `gpt-4o-audio-preview` model can also be used to\n   * [generate audio](https://platform.openai.com/docs/guides/audio). To request that this model generate\n   * both text and audio responses, you can use:\n   *\n   * `[\"text\", \"audio\"]`\n   */\n  S.Array(S.Literal(\"text\", \"audio\")),\n  S.Null\n) {}\n\n/**\n * Constrains the verbosity of the model's response. Lower values will result in\n * more concise responses, while higher values will result in more verbose responses.\n * Currently supported values are `low`, `medium`, and `high`.\n */\nexport class VerbosityEnum extends S.Literal(\"low\", \"medium\", \"high\") {}\n\nexport class Verbosity extends S.Union(\n  /**\n   * Constrains the verbosity of the model's response. Lower values will result in\n   * more concise responses, while higher values will result in more verbose responses.\n   * Currently supported values are `low`, `medium`, and `high`.\n   */\n  VerbosityEnum,\n  S.Null\n) {}\n\n/**\n * The type of location approximation. Always `approximate`.\n */\nexport class CreateChatCompletionRequestWebSearchOptionsUserLocationType extends S.Literal(\"approximate\") {}\n\n/**\n * Approximate location parameters for the search.\n */\nexport class WebSearchLocation extends S.Class<WebSearchLocation>(\"WebSearchLocation\")({\n  /**\n   * The two-letter\n   * [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user,\n   * e.g. `US`.\n   */\n  \"country\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Free text input for the region of the user, e.g. `California`.\n   */\n  \"region\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Free text input for the city of the user, e.g. `San Francisco`.\n   */\n  \"city\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The [IANA timezone](https://timeapi.io/documentation/iana-timezones)\n   * of the user, e.g. `America/Los_Angeles`.\n   */\n  \"timezone\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * High level guidance for the amount of context window space to use for the\n * search. One of `low`, `medium`, or `high`. `medium` is the default.\n */\nexport class WebSearchContextSize extends S.Literal(\"low\", \"medium\", \"high\") {}\n\n/**\n * Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`,\n * `opus`, or `pcm16`.\n */\nexport class CreateChatCompletionRequestAudioFormat extends S.Literal(\"wav\", \"aac\", \"mp3\", \"flac\", \"opus\", \"pcm16\") {}\n\n/**\n * Not supported with latest reasoning models `o3` and `o4-mini`.\n *\n * Up to 4 sequences where the API will stop generating further tokens. The\n * returned text will not contain the stop sequence.\n */\nexport class StopConfiguration\n  extends S.Union(S.String, S.NonEmptyArray(S.String).pipe(S.minItems(1), S.maxItems(4)))\n{}\n\n/**\n * The type of the predicted content you want to provide. This type is\n * currently always `content`.\n */\nexport class PredictionContentType extends S.Literal(\"content\") {}\n\n/**\n * Static predicted output content, such as the content of a text file that is\n * being regenerated.\n */\nexport class PredictionContent extends S.Class<PredictionContent>(\"PredictionContent\")({\n  /**\n   * The type of the predicted content you want to provide. This type is\n   * currently always `content`.\n   */\n  \"type\": PredictionContentType,\n  /**\n   * The content that should be matched when generating a model response.\n   * If generated tokens would match this content, the entire model response\n   * can be returned much more quickly.\n   */\n  \"content\": S.Union(\n    /**\n     * The content used for a Predicted Output. This is often the\n     * text of a file you are regenerating with minor changes.\n     */\n    S.String,\n    /**\n     * An array of content parts with a defined type. Supported options differ based on the [model](https://platform.openai.com/docs/models) being used to generate the response. Can contain text inputs.\n     */\n    S.NonEmptyArray(ChatCompletionRequestMessageContentPartText).pipe(S.minItems(1))\n  )\n}) {}\n\nexport class ChatCompletionStreamOptions extends S.Union(\n  /**\n   * Options for streaming response. Only set this when you set `stream: true`.\n   */\n  S.Struct({\n    /**\n     * If set, an additional chunk will be streamed before the `data: [DONE]`\n     * message. The `usage` field on this chunk shows the token usage statistics\n     * for the entire request, and the `choices` field will always be an empty\n     * array.\n     *\n     * All other chunks will also include a `usage` field, but with a null\n     * value. **NOTE:** If the stream is interrupted, you may not receive the\n     * final usage chunk which contains the total token usage for the request.\n     */\n    \"include_usage\": S.optionalWith(S.Boolean, { nullable: true }),\n    /**\n     * When true, stream obfuscation will be enabled. Stream obfuscation adds\n     * random characters to an `obfuscation` field on streaming delta events to\n     * normalize payload sizes as a mitigation to certain side-channel attacks.\n     * These obfuscation fields are included by default, but add a small amount\n     * of overhead to the data stream. You can set `include_obfuscation` to\n     * false to optimize for bandwidth if you trust the network links between\n     * your application and the OpenAI API.\n     */\n    \"include_obfuscation\": S.optionalWith(S.Boolean, { nullable: true })\n  }),\n  S.Null\n) {}\n\n/**\n * The type of the tool. Currently, only `function` is supported.\n */\nexport class ChatCompletionToolType extends S.Literal(\"function\") {}\n\n/**\n * A function tool that can be used to generate a response.\n */\nexport class ChatCompletionTool extends S.Class<ChatCompletionTool>(\"ChatCompletionTool\")({\n  /**\n   * The type of the tool. Currently, only `function` is supported.\n   */\n  \"type\": ChatCompletionToolType,\n  \"function\": FunctionObject\n}) {}\n\n/**\n * The type of the custom tool. Always `custom`.\n */\nexport class CustomToolChatCompletionsType extends S.Literal(\"custom\") {}\n\n/**\n * Grammar format. Always `grammar`.\n */\nexport class CustomToolChatCompletionsCustomFormatEnumType extends S.Literal(\"grammar\") {}\n\n/**\n * The syntax of the grammar definition. One of `lark` or `regex`.\n */\nexport class CustomToolChatCompletionsCustomFormatEnumGrammarSyntax extends S.Literal(\"lark\", \"regex\") {}\n\n/**\n * A custom tool that processes input using a specified format.\n */\nexport class CustomToolChatCompletions extends S.Class<CustomToolChatCompletions>(\"CustomToolChatCompletions\")({\n  /**\n   * The type of the custom tool. Always `custom`.\n   */\n  \"type\": CustomToolChatCompletionsType,\n  /**\n   * Properties of the custom tool.\n   */\n  \"custom\": S.Struct({\n    /**\n     * The name of the custom tool, used to identify it in tool calls.\n     */\n    \"name\": S.String,\n    /**\n     * Optional description of the custom tool, used to provide more context.\n     */\n    \"description\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The input format for the custom tool. Default is unconstrained text.\n     */\n    \"format\": S.optionalWith(\n      S.Union(\n        /**\n         * Unconstrained free-form text.\n         */\n        S.Struct({\n          /**\n           * Unconstrained text format. Always `text`.\n           */\n          \"type\": CustomToolChatCompletionsCustomFormatEnumType\n        }),\n        /**\n         * A grammar defined by the user.\n         */\n        S.Struct({\n          /**\n           * Grammar format. Always `grammar`.\n           */\n          \"type\": CustomToolChatCompletionsCustomFormatEnumType,\n          /**\n           * Your chosen grammar.\n           */\n          \"grammar\": S.Struct({\n            /**\n             * The grammar definition.\n             */\n            \"definition\": S.String,\n            /**\n             * The syntax of the grammar definition. One of `lark` or `regex`.\n             */\n            \"syntax\": CustomToolChatCompletionsCustomFormatEnumGrammarSyntax\n          })\n        })\n      ),\n      { nullable: true }\n    )\n  })\n}) {}\n\n/**\n * `none` means the model will not call any tool and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools.\n */\nexport class ChatCompletionToolChoiceOptionEnum extends S.Literal(\"none\", \"auto\", \"required\") {}\n\n/**\n * Allowed tool configuration type. Always `allowed_tools`.\n */\nexport class ChatCompletionAllowedToolsChoiceType extends S.Literal(\"allowed_tools\") {}\n\n/**\n * Constrains the tools available to the model to a pre-defined set.\n *\n * `auto` allows the model to pick from among the allowed tools and generate a\n * message.\n *\n * `required` requires the model to call one or more of the allowed tools.\n */\nexport class ChatCompletionAllowedToolsMode extends S.Literal(\"auto\", \"required\") {}\n\n/**\n * Constrains the tools available to the model to a pre-defined set.\n */\nexport class ChatCompletionAllowedTools extends S.Class<ChatCompletionAllowedTools>(\"ChatCompletionAllowedTools\")({\n  /**\n   * Constrains the tools available to the model to a pre-defined set.\n   *\n   * `auto` allows the model to pick from among the allowed tools and generate a\n   * message.\n   *\n   * `required` requires the model to call one or more of the allowed tools.\n   */\n  \"mode\": ChatCompletionAllowedToolsMode,\n  /**\n   * A list of tool definitions that the model should be allowed to call.\n   *\n   * For the Chat Completions API, the list of tool definitions might look like:\n   * ```json\n   * [\n   *   { \"type\": \"function\", \"function\": { \"name\": \"get_weather\" } },\n   *   { \"type\": \"function\", \"function\": { \"name\": \"get_time\" } }\n   * ]\n   * ```\n   */\n  \"tools\": S.Array(S.Record({ key: S.String, value: S.Unknown }))\n}) {}\n\n/**\n * Constrains the tools available to the model to a pre-defined set.\n */\nexport class ChatCompletionAllowedToolsChoice\n  extends S.Class<ChatCompletionAllowedToolsChoice>(\"ChatCompletionAllowedToolsChoice\")({\n    /**\n     * Allowed tool configuration type. Always `allowed_tools`.\n     */\n    \"type\": ChatCompletionAllowedToolsChoiceType,\n    \"allowed_tools\": ChatCompletionAllowedTools\n  })\n{}\n\n/**\n * For function calling, the type is always `function`.\n */\nexport class ChatCompletionNamedToolChoiceType extends S.Literal(\"function\") {}\n\n/**\n * Specifies a tool the model should use. Use to force the model to call a specific function.\n */\nexport class ChatCompletionNamedToolChoice\n  extends S.Class<ChatCompletionNamedToolChoice>(\"ChatCompletionNamedToolChoice\")({\n    /**\n     * For function calling, the type is always `function`.\n     */\n    \"type\": ChatCompletionNamedToolChoiceType,\n    \"function\": S.Struct({\n      /**\n       * The name of the function to call.\n       */\n      \"name\": S.String\n    })\n  })\n{}\n\n/**\n * For custom tool calling, the type is always `custom`.\n */\nexport class ChatCompletionNamedToolChoiceCustomType extends S.Literal(\"custom\") {}\n\n/**\n * Specifies a tool the model should use. Use to force the model to call a specific custom tool.\n */\nexport class ChatCompletionNamedToolChoiceCustom\n  extends S.Class<ChatCompletionNamedToolChoiceCustom>(\"ChatCompletionNamedToolChoiceCustom\")({\n    /**\n     * For custom tool calling, the type is always `custom`.\n     */\n    \"type\": ChatCompletionNamedToolChoiceCustomType,\n    \"custom\": S.Struct({\n      /**\n       * The name of the custom tool to call.\n       */\n      \"name\": S.String\n    })\n  })\n{}\n\n/**\n * Controls which (if any) tool is called by the model.\n * `none` means the model will not call any tool and instead generates a message.\n * `auto` means the model can pick between generating a message or calling one or more tools.\n * `required` means the model must call one or more tools.\n * Specifying a particular tool via `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.\n *\n * `none` is the default when no tools are present. `auto` is the default if tools are present.\n */\nexport class ChatCompletionToolChoiceOption extends S.Union(\n  /**\n   * `none` means the model will not call any tool and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools.\n   */\n  ChatCompletionToolChoiceOptionEnum,\n  ChatCompletionAllowedToolsChoice,\n  ChatCompletionNamedToolChoice,\n  ChatCompletionNamedToolChoiceCustom\n) {}\n\n/**\n * Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use.\n */\nexport class ParallelToolCalls extends S.Boolean {}\n\n/**\n * `none` means the model will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function.\n */\nexport class CreateChatCompletionRequestFunctionCallEnum extends S.Literal(\"none\", \"auto\") {}\n\n/**\n * Specifying a particular function via `{\"name\": \"my_function\"}` forces the model to call that function.\n */\nexport class ChatCompletionFunctionCallOption\n  extends S.Class<ChatCompletionFunctionCallOption>(\"ChatCompletionFunctionCallOption\")({\n    /**\n     * The name of the function to call.\n     */\n    \"name\": S.String\n  })\n{}\n\nexport class ChatCompletionFunctions extends S.Class<ChatCompletionFunctions>(\"ChatCompletionFunctions\")({\n  /**\n   * A description of what the function does, used by the model to choose when and how to call the function.\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.\n   */\n  \"name\": S.String,\n  \"parameters\": S.optionalWith(FunctionParameters, { nullable: true })\n}) {}\n\n/**\n * The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](https://platform.openai.com/docs/guides/prompt-caching#prompt-cache-retention).\n */\nexport class CreateChatCompletionRequestPromptCacheRetentionEnum extends S.Literal(\"in-memory\", \"24h\") {}\n\nexport class CreateChatCompletionRequest extends S.Class<CreateChatCompletionRequest>(\"CreateChatCompletionRequest\")({\n  /**\n   * A list of messages comprising the conversation so far. Depending on the\n   * [model](https://platform.openai.com/docs/models) you use, different message types (modalities) are\n   * supported, like [text](https://platform.openai.com/docs/guides/text-generation),\n   * [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio).\n   */\n  \"messages\": S.NonEmptyArray(ChatCompletionRequestMessage).pipe(S.minItems(1)),\n  /**\n   * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\n   * offers a wide range of models with different capabilities, performance\n   * characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models)\n   * to browse and compare available models.\n   */\n  \"model\": ModelIdsShared,\n  \"modalities\": S.optionalWith(S.Array(S.Literal(\"text\", \"audio\")), { nullable: true }),\n  \"verbosity\": S.optionalWith(S.Literal(\"low\", \"medium\", \"high\"), { nullable: true }),\n  \"reasoning_effort\": S.optionalWith(S.Literal(\"none\", \"minimal\", \"low\", \"medium\", \"high\"), { nullable: true }),\n  /**\n   * An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).\n   */\n  \"max_completion_tokens\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Number between -2.0 and 2.0. Positive values penalize new tokens based on\n   * their existing frequency in the text so far, decreasing the model's\n   * likelihood to repeat the same line verbatim.\n   */\n  \"frequency_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true,\n    default: () => 0 as const\n  }),\n  /**\n   * Number between -2.0 and 2.0. Positive values penalize new tokens based on\n   * whether they appear in the text so far, increasing the model's likelihood\n   * to talk about new topics.\n   */\n  \"presence_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true,\n    default: () => 0 as const\n  }),\n  /**\n   * This tool searches the web for relevant results to use in a response.\n   * Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n   */\n  \"web_search_options\": S.optionalWith(\n    S.Struct({\n      /**\n       * Approximate location parameters for the search.\n       */\n      \"user_location\": S.optionalWith(\n        S.Struct({\n          /**\n           * The type of location approximation. Always `approximate`.\n           */\n          \"type\": CreateChatCompletionRequestWebSearchOptionsUserLocationType,\n          \"approximate\": WebSearchLocation\n        }),\n        { nullable: true }\n      ),\n      \"search_context_size\": S.optionalWith(WebSearchContextSize, { nullable: true, default: () => \"medium\" as const })\n    }),\n    { nullable: true }\n  ),\n  \"top_logprobs\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(20)), { nullable: true }),\n  /**\n   * An object specifying the format that the model must output.\n   *\n   * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables\n   * Structured Outputs which ensures the model will match your supplied JSON\n   * schema. Learn more in the [Structured Outputs\n   * guide](https://platform.openai.com/docs/guides/structured-outputs).\n   *\n   * Setting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\n   * ensures the message the model generates is valid JSON. Using `json_schema`\n   * is preferred for models that support it.\n   */\n  \"response_format\": S.optionalWith(S.Union(ResponseFormatText, ResponseFormatJsonSchema, ResponseFormatJsonObject), {\n    nullable: true\n  }),\n  /**\n   * Parameters for audio output. Required when audio output is requested with\n   * `modalities: [\"audio\"]`. [Learn more](https://platform.openai.com/docs/guides/audio).\n   */\n  \"audio\": S.optionalWith(\n    S.Struct({\n      /**\n       * The voice the model uses to respond. Supported voices are\n       * `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`, `sage`, and `shimmer`.\n       */\n      \"voice\": VoiceIdsShared,\n      /**\n       * Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`,\n       * `opus`, or `pcm16`.\n       */\n      \"format\": CreateChatCompletionRequestAudioFormat\n    }),\n    { nullable: true }\n  ),\n  /**\n   * Whether or not to store the output of this chat completion request for\n   * use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or\n   * [evals](https://platform.openai.com/docs/guides/evals) products.\n   *\n   * Supports text and image inputs. Note: image inputs over 8MB will be dropped.\n   */\n  \"store\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  /**\n   * If set to true, the model response data will be streamed to the client\n   * as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\n   * See the [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming)\n   * for more information, along with the [streaming responses](https://platform.openai.com/docs/guides/streaming-responses)\n   * guide for more information on how to handle the streaming events.\n   */\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  \"stop\": S.optionalWith(StopConfiguration, { nullable: true }),\n  /**\n   * Modify the likelihood of specified tokens appearing in the completion.\n   *\n   * Accepts a JSON object that maps tokens (specified by their token ID in the\n   * tokenizer) to an associated bias value from -100 to 100. Mathematically,\n   * the bias is added to the logits generated by the model prior to sampling.\n   * The exact effect will vary per model, but values between -1 and 1 should\n   * decrease or increase likelihood of selection; values like -100 or 100\n   * should result in a ban or exclusive selection of the relevant token.\n   */\n  \"logit_bias\": S.optionalWith(S.NullOr(S.Record({ key: S.String, value: S.Unknown })), { default: () => null }),\n  /**\n   * Whether to return log probabilities of the output tokens or not. If true,\n   * returns the log probabilities of each output token returned in the\n   * `content` of `message`.\n   */\n  \"logprobs\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  /**\n   * The maximum number of [tokens](/tokenizer) that can be generated in the\n   * chat completion. This value can be used to control\n   * [costs](https://openai.com/api/pricing/) for text generated via API.\n   *\n   * This value is now deprecated in favor of `max_completion_tokens`, and is\n   * not compatible with [o-series models](https://platform.openai.com/docs/guides/reasoning).\n   */\n  \"max_tokens\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs.\n   */\n  \"n\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(128)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * Configuration for a [Predicted Output](https://platform.openai.com/docs/guides/predicted-outputs),\n   * which can greatly improve response times when large parts of the model\n   * response are known ahead of time. This is most common when you are\n   * regenerating a file with only minor changes to most of the content.\n   */\n  \"prediction\": S.optionalWith(PredictionContent, { nullable: true }),\n  /**\n   * This feature is in Beta.\n   * If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\n   * Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n   */\n  \"seed\": S.optionalWith(\n    S.Int.pipe(S.greaterThanOrEqualTo(-9223372036854776000), S.lessThanOrEqualTo(9223372036854776000)),\n    { nullable: true }\n  ),\n  \"stream_options\": S.optionalWith(\n    S.Struct({\n      /**\n       * If set, an additional chunk will be streamed before the `data: [DONE]`\n       * message. The `usage` field on this chunk shows the token usage statistics\n       * for the entire request, and the `choices` field will always be an empty\n       * array.\n       *\n       * All other chunks will also include a `usage` field, but with a null\n       * value. **NOTE:** If the stream is interrupted, you may not receive the\n       * final usage chunk which contains the total token usage for the request.\n       */\n      \"include_usage\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * When true, stream obfuscation will be enabled. Stream obfuscation adds\n       * random characters to an `obfuscation` field on streaming delta events to\n       * normalize payload sizes as a mitigation to certain side-channel attacks.\n       * These obfuscation fields are included by default, but add a small amount\n       * of overhead to the data stream. You can set `include_obfuscation` to\n       * false to optimize for bandwidth if you trust the network links between\n       * your application and the OpenAI API.\n       */\n      \"include_obfuscation\": S.optionalWith(S.Boolean, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * A list of tools the model may call. You can provide either\n   * [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) or\n   * [function tools](https://platform.openai.com/docs/guides/function-calling).\n   */\n  \"tools\": S.optionalWith(S.Array(S.Union(ChatCompletionTool, CustomToolChatCompletions)), { nullable: true }),\n  \"tool_choice\": S.optionalWith(ChatCompletionToolChoiceOption, { nullable: true }),\n  \"parallel_tool_calls\": S.optionalWith(ParallelToolCalls, { nullable: true, default: () => true as const }),\n  /**\n   * Deprecated in favor of `tool_choice`.\n   *\n   * Controls which (if any) function is called by the model.\n   *\n   * `none` means the model will not call a function and instead generates a\n   * message.\n   *\n   * `auto` means the model can pick between generating a message or calling a\n   * function.\n   *\n   * Specifying a particular function via `{\"name\": \"my_function\"}` forces the\n   * model to call that function.\n   *\n   * `none` is the default when no functions are present. `auto` is the default\n   * if functions are present.\n   */\n  \"function_call\": S.optionalWith(\n    S.Union(\n      /**\n       * `none` means the model will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function.\n       */\n      CreateChatCompletionRequestFunctionCallEnum,\n      ChatCompletionFunctionCallOption\n    ),\n    { nullable: true }\n  ),\n  /**\n   * Deprecated in favor of `tools`.\n   *\n   * A list of functions the model may generate JSON inputs for.\n   */\n  \"functions\": S.optionalWith(S.NonEmptyArray(ChatCompletionFunctions).pipe(S.minItems(1), S.maxItems(128)), {\n    nullable: true\n  }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  /**\n   * This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\n   * A stable identifier for your end-users.\n   * Used to boost cache hit rates by better bucketing similar requests and  to help OpenAI detect and prevent abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n   */\n  \"user\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\n   * The IDs should be a string that uniquely identifies each user. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n   */\n  \"safety_identifier\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching).\n   */\n  \"prompt_cache_key\": S.optionalWith(S.String, { nullable: true }),\n  \"service_tier\": S.optionalWith(S.Literal(\"auto\", \"default\", \"flex\", \"scale\", \"priority\"), { nullable: true }),\n  \"prompt_cache_retention\": S.optionalWith(CreateChatCompletionRequestPromptCacheRetentionEnum, { nullable: true })\n}) {}\n\nexport class UpdateChatCompletionRequest extends S.Class<UpdateChatCompletionRequest>(\"UpdateChatCompletionRequest\")({\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown }))\n}) {}\n\n/**\n * The type of object being deleted.\n */\nexport class ChatCompletionDeletedObject extends S.Literal(\"chat.completion.deleted\") {}\n\nexport class ChatCompletionDeleted extends S.Class<ChatCompletionDeleted>(\"ChatCompletionDeleted\")({\n  /**\n   * The type of object being deleted.\n   */\n  \"object\": ChatCompletionDeletedObject,\n  /**\n   * The ID of the chat completion that was deleted.\n   */\n  \"id\": S.String,\n  /**\n   * Whether the chat completion was deleted.\n   */\n  \"deleted\": S.Boolean\n}) {}\n\nexport class GetChatCompletionMessagesParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class GetChatCompletionMessagesParams extends S.Struct({\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(GetChatCompletionMessagesParamsOrder, { nullable: true, default: () => \"asc\" as const })\n}) {}\n\n/**\n * The type of this object. It is always set to \"list\".\n */\nexport class ChatCompletionMessageListObject extends S.Literal(\"list\") {}\n\n/**\n * An object representing a list of chat completion messages.\n */\nexport class ChatCompletionMessageList extends S.Class<ChatCompletionMessageList>(\"ChatCompletionMessageList\")({\n  /**\n   * The type of this object. It is always set to \"list\".\n   */\n  \"object\": ChatCompletionMessageListObject.pipe(S.propertySignature, S.withConstructorDefault(() => \"list\" as const)),\n  /**\n   * An array of chat completion message objects.\n   */\n  \"data\": S.Array(S.Struct({\n    /**\n     * The identifier of the chat message.\n     */\n    \"id\": S.String,\n    \"content_parts\": S.optionalWith(\n      S.Array(S.Union(ChatCompletionRequestMessageContentPartText, ChatCompletionRequestMessageContentPartImage)),\n      { nullable: true }\n    ),\n    \"content\": S.NullOr(S.String),\n    \"refusal\": S.NullOr(S.String),\n    \"tool_calls\": S.optionalWith(ChatCompletionMessageToolCalls, { nullable: true }),\n    /**\n     * Annotations for the message, when applicable, as when using the\n     * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).\n     */\n    \"annotations\": S.optionalWith(\n      S.Array(S.Struct({\n        /**\n         * The type of the URL citation. Always `url_citation`.\n         */\n        \"type\": S.Literal(\"url_citation\"),\n        /**\n         * A URL citation when using web search.\n         */\n        \"url_citation\": S.Struct({\n          /**\n           * The index of the last character of the URL citation in the message.\n           */\n          \"end_index\": S.Int,\n          /**\n           * The index of the first character of the URL citation in the message.\n           */\n          \"start_index\": S.Int,\n          /**\n           * The URL of the web resource.\n           */\n          \"url\": S.String,\n          /**\n           * The title of the web resource.\n           */\n          \"title\": S.String\n        })\n      })),\n      { nullable: true }\n    ),\n    /**\n     * The role of the author of this message.\n     */\n    \"role\": S.Literal(\"assistant\"),\n    /**\n     * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model.\n     */\n    \"function_call\": S.optionalWith(\n      S.Struct({\n        /**\n         * The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.\n         */\n        \"arguments\": S.String,\n        /**\n         * The name of the function to call.\n         */\n        \"name\": S.String\n      }),\n      { nullable: true }\n    ),\n    \"audio\": S.optionalWith(\n      S.Struct({\n        /**\n         * Unique identifier for this audio response.\n         */\n        \"id\": S.String,\n        /**\n         * The Unix timestamp (in seconds) for when this audio response will\n         * no longer be accessible on the server for use in multi-turn\n         * conversations.\n         */\n        \"expires_at\": S.Int,\n        /**\n         * Base64 encoded audio bytes generated by the model, in the format\n         * specified in the request.\n         */\n        \"data\": S.String,\n        /**\n         * Transcript of the audio generated by the model.\n         */\n        \"transcript\": S.String\n      }),\n      { nullable: true }\n    )\n  })),\n  /**\n   * The identifier of the first chat message in the data array.\n   */\n  \"first_id\": S.String,\n  /**\n   * The identifier of the last chat message in the data array.\n   */\n  \"last_id\": S.String,\n  /**\n   * Indicates whether there are more chat messages available.\n   */\n  \"has_more\": S.Boolean\n}) {}\n\nexport class CreateCompletionRequestModelEnum\n  extends S.Literal(\"gpt-3.5-turbo-instruct\", \"davinci-002\", \"babbage-002\")\n{}\n\nexport class CreateCompletionRequest extends S.Class<CreateCompletionRequest>(\"CreateCompletionRequest\")({\n  /**\n   * ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n   */\n  \"model\": S.Union(S.String, CreateCompletionRequestModelEnum),\n  /**\n   * The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n   *\n   * Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n   */\n  \"prompt\": S.NullOr(\n    S.Union(\n      S.String,\n      S.Array(S.String),\n      S.NonEmptyArray(S.Int).pipe(S.minItems(1)),\n      S.NonEmptyArray(S.NonEmptyArray(S.Int).pipe(S.minItems(1))).pipe(S.minItems(1))\n    )\n  ),\n  /**\n   * Generates `best_of` completions server-side and returns the \"best\" (the one with the highest log probability per token). Results cannot be streamed.\n   *\n   * When used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`.\n   *\n   * **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n   */\n  \"best_of\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(20)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * Echo back the prompt in addition to the completion\n   */\n  \"echo\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  /**\n   * Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.\n   *\n   * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)\n   */\n  \"frequency_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true,\n    default: () => 0 as const\n  }),\n  /**\n   * Modify the likelihood of specified tokens appearing in the completion.\n   *\n   * Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.\n   *\n   * As an example, you can pass `{\"50256\": -100}` to prevent the <|endoftext|> token from being generated.\n   */\n  \"logit_bias\": S.optionalWith(S.NullOr(S.Record({ key: S.String, value: S.Unknown })), { default: () => null }),\n  /**\n   * Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response.\n   *\n   * The maximum value for `logprobs` is 5.\n   */\n  \"logprobs\": S.optionalWith(S.NullOr(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(5))), {\n    default: () => null\n  }),\n  /**\n   * The maximum number of [tokens](/tokenizer) that can be generated in the completion.\n   *\n   * The token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n   */\n  \"max_tokens\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0)), { nullable: true, default: () => 16 as const }),\n  /**\n   * How many completions to generate for each prompt.\n   *\n   * **Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n   */\n  \"n\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(128)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.\n   *\n   * [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)\n   */\n  \"presence_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true,\n    default: () => 0 as const\n  }),\n  /**\n   * If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\n   *\n   * Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n   */\n  \"seed\": S.optionalWith(S.Int, { nullable: true }),\n  \"stop\": S.optionalWith(StopConfiguration, { nullable: true }),\n  /**\n   * Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n   */\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  \"stream_options\": S.optionalWith(\n    S.Struct({\n      /**\n       * If set, an additional chunk will be streamed before the `data: [DONE]`\n       * message. The `usage` field on this chunk shows the token usage statistics\n       * for the entire request, and the `choices` field will always be an empty\n       * array.\n       *\n       * All other chunks will also include a `usage` field, but with a null\n       * value. **NOTE:** If the stream is interrupted, you may not receive the\n       * final usage chunk which contains the total token usage for the request.\n       */\n      \"include_usage\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * When true, stream obfuscation will be enabled. Stream obfuscation adds\n       * random characters to an `obfuscation` field on streaming delta events to\n       * normalize payload sizes as a mitigation to certain side-channel attacks.\n       * These obfuscation fields are included by default, but add a small amount\n       * of overhead to the data stream. You can set `include_obfuscation` to\n       * false to optimize for bandwidth if you trust the network links between\n       * your application and the OpenAI API.\n       */\n      \"include_obfuscation\": S.optionalWith(S.Boolean, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The suffix that comes after a completion of inserted text.\n   *\n   * This parameter is only supported for `gpt-3.5-turbo-instruct`.\n   */\n  \"suffix\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n  /**\n   * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n   *\n   * We generally recommend altering this or `top_p` but not both.\n   */\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n   *\n   * We generally recommend altering this or `temperature` but not both.\n   */\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n   */\n  \"user\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always \"text_completion\"\n */\nexport class CreateCompletionResponseObject extends S.Literal(\"text_completion\") {}\n\n/**\n * Represents a completion response from the API. Note: both the streamed and non-streamed response objects share the same shape (unlike the chat endpoint).\n */\nexport class CreateCompletionResponse extends S.Class<CreateCompletionResponse>(\"CreateCompletionResponse\")({\n  /**\n   * A unique identifier for the completion.\n   */\n  \"id\": S.String,\n  /**\n   * The list of completion choices the model generated for the input prompt.\n   */\n  \"choices\": S.Array(S.Struct({\n    /**\n     * The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n     * `length` if the maximum number of tokens specified in the request was reached,\n     * or `content_filter` if content was omitted due to a flag from our content filters.\n     */\n    \"finish_reason\": S.Literal(\"stop\", \"length\", \"content_filter\"),\n    \"index\": S.Int,\n    \"logprobs\": S.NullOr(S.Struct({\n      \"text_offset\": S.optionalWith(S.Array(S.Int), { nullable: true }),\n      \"token_logprobs\": S.optionalWith(S.Array(S.Number), { nullable: true }),\n      \"tokens\": S.optionalWith(S.Array(S.String), { nullable: true }),\n      \"top_logprobs\": S.optionalWith(S.Array(S.Record({ key: S.String, value: S.Unknown })), { nullable: true })\n    })),\n    \"text\": S.String\n  })),\n  /**\n   * The Unix timestamp (in seconds) of when the completion was created.\n   */\n  \"created\": S.Int,\n  /**\n   * The model used for completion.\n   */\n  \"model\": S.String,\n  /**\n   * This fingerprint represents the backend configuration that the model runs with.\n   *\n   * Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n   */\n  \"system_fingerprint\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The object type, which is always \"text_completion\"\n   */\n  \"object\": CreateCompletionResponseObject,\n  \"usage\": S.optionalWith(CompletionUsage, { nullable: true })\n}) {}\n\nexport class ListContainersParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListContainersParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListContainersParamsOrder, { nullable: true, default: () => \"desc\" as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The reference point for the expiration.\n */\nexport class ContainerResourceExpiresAfterAnchor extends S.Literal(\"last_active_at\") {}\n\nexport class ContainerResource extends S.Class<ContainerResource>(\"ContainerResource\")({\n  /**\n   * Unique identifier for the container.\n   */\n  \"id\": S.String,\n  /**\n   * The type of this object.\n   */\n  \"object\": S.String,\n  /**\n   * Name of the container.\n   */\n  \"name\": S.String,\n  /**\n   * Unix timestamp (in seconds) when the container was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Status of the container (e.g., active, deleted).\n   */\n  \"status\": S.String,\n  /**\n   * The container will expire after this time period.\n   * The anchor is the reference point for the expiration.\n   * The minutes is the number of minutes after the anchor before the container expires.\n   */\n  \"expires_after\": S.optionalWith(\n    S.Struct({\n      /**\n       * The reference point for the expiration.\n       */\n      \"anchor\": S.optionalWith(ContainerResourceExpiresAfterAnchor, { nullable: true }),\n      /**\n       * The number of minutes after the anchor before the container expires.\n       */\n      \"minutes\": S.optionalWith(S.Int, { nullable: true })\n    }),\n    { nullable: true }\n  )\n}) {}\n\nexport class ContainerListResource extends S.Class<ContainerListResource>(\"ContainerListResource\")({\n  /**\n   * The type of object returned, must be 'list'.\n   */\n  \"object\": S.Literal(\"list\"),\n  /**\n   * A list of containers.\n   */\n  \"data\": S.Array(ContainerResource),\n  /**\n   * The ID of the first container in the list.\n   */\n  \"first_id\": S.String,\n  /**\n   * The ID of the last container in the list.\n   */\n  \"last_id\": S.String,\n  /**\n   * Whether there are more containers available.\n   */\n  \"has_more\": S.Boolean\n}) {}\n\n/**\n * Time anchor for the expiration time. Currently only 'last_active_at' is supported.\n */\nexport class CreateContainerBodyExpiresAfterAnchor extends S.Literal(\"last_active_at\") {}\n\nexport class CreateContainerBody extends S.Class<CreateContainerBody>(\"CreateContainerBody\")({\n  /**\n   * Name of the container to create.\n   */\n  \"name\": S.String,\n  /**\n   * IDs of files to copy to the container.\n   */\n  \"file_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Container expiration time in seconds relative to the 'anchor' time.\n   */\n  \"expires_after\": S.optionalWith(\n    S.Struct({\n      /**\n       * Time anchor for the expiration time. Currently only 'last_active_at' is supported.\n       */\n      \"anchor\": CreateContainerBodyExpiresAfterAnchor,\n      \"minutes\": S.Int\n    }),\n    { nullable: true }\n  )\n}) {}\n\nexport class ListContainerFilesParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListContainerFilesParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListContainerFilesParamsOrder, { nullable: true, default: () => \"desc\" as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ContainerFileResource extends S.Class<ContainerFileResource>(\"ContainerFileResource\")({\n  /**\n   * Unique identifier for the file.\n   */\n  \"id\": S.String,\n  /**\n   * The type of this object (`container.file`).\n   */\n  \"object\": S.Literal(\"container.file\"),\n  /**\n   * The container this file belongs to.\n   */\n  \"container_id\": S.String,\n  /**\n   * Unix timestamp (in seconds) when the file was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Size of the file in bytes.\n   */\n  \"bytes\": S.Int,\n  /**\n   * Path of the file in the container.\n   */\n  \"path\": S.String,\n  /**\n   * Source of the file (e.g., `user`, `assistant`).\n   */\n  \"source\": S.String\n}) {}\n\nexport class ContainerFileListResource extends S.Class<ContainerFileListResource>(\"ContainerFileListResource\")({\n  /**\n   * The type of object returned, must be 'list'.\n   */\n  \"object\": S.Literal(\"list\"),\n  /**\n   * A list of container files.\n   */\n  \"data\": S.Array(ContainerFileResource),\n  /**\n   * The ID of the first file in the list.\n   */\n  \"first_id\": S.String,\n  /**\n   * The ID of the last file in the list.\n   */\n  \"last_id\": S.String,\n  /**\n   * Whether there are more files available.\n   */\n  \"has_more\": S.Boolean\n}) {}\n\nexport class CreateContainerFileBody extends S.Class<CreateContainerFileBody>(\"CreateContainerFileBody\")({\n  /**\n   * Name of the file to create.\n   */\n  \"file_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The File object (not file name) to be uploaded.\n   */\n  \"file\": S.optionalWith(S.instanceOf(globalThis.Blob), { nullable: true })\n}) {}\n\nexport class ListConversationItemsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\n/**\n * Specify additional output data to include in the model response. Currently supported values are:\n * - `web_search_call.action.sources`: Include the sources of the web search tool call.\n * - `code_interpreter_call.outputs`: Includes the outputs of python code execution in code interpreter tool call items.\n * - `computer_call_output.output.image_url`: Include image urls from the computer call output.\n * - `file_search_call.results`: Include the search results of the file search tool call.\n * - `message.input_image.image_url`: Include image urls from the input message.\n * - `message.output_text.logprobs`: Include logprobs with assistant messages.\n * - `reasoning.encrypted_content`: Includes an encrypted version of reasoning tokens in reasoning item outputs. This enables reasoning items to be used in multi-turn conversations when using the Responses API statelessly (like when the `store` parameter is set to `false`, or when an organization is enrolled in the zero data retention program).\n */\nexport class IncludeEnum extends S.Literal(\n  \"file_search_call.results\",\n  \"web_search_call.results\",\n  \"web_search_call.action.sources\",\n  \"message.input_image.image_url\",\n  \"computer_call_output.output.image_url\",\n  \"code_interpreter_call.outputs\",\n  \"reasoning.encrypted_content\",\n  \"message.output_text.logprobs\"\n) {}\n\nexport class ListConversationItemsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListConversationItemsParamsOrder, { nullable: true }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"include\": S.optionalWith(S.Array(IncludeEnum), { nullable: true })\n}) {}\n\n/**\n * The type of the message. Always set to `message`.\n */\nexport class MessageType extends S.Literal(\"message\") {}\n\nexport class MessageStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\nexport class MessageRole\n  extends S.Literal(\"unknown\", \"user\", \"assistant\", \"system\", \"critic\", \"discriminator\", \"developer\", \"tool\")\n{}\n\n/**\n * The type of the input item. Always `input_text`.\n */\nexport class InputTextContentType extends S.Literal(\"input_text\") {}\n\n/**\n * A text input to the model.\n */\nexport class InputTextContent extends S.Class<InputTextContent>(\"InputTextContent\")({\n  /**\n   * The type of the input item. Always `input_text`.\n   */\n  \"type\": InputTextContentType.pipe(S.propertySignature, S.withConstructorDefault(() => \"input_text\" as const)),\n  /**\n   * The text input to the model.\n   */\n  \"text\": S.String\n}) {}\n\n/**\n * The type of the output text. Always `output_text`.\n */\nexport class OutputTextContentType extends S.Literal(\"output_text\") {}\n\n/**\n * The type of the file citation. Always `file_citation`.\n */\nexport class FileCitationBodyType extends S.Literal(\"file_citation\") {}\n\n/**\n * A citation to a file.\n */\nexport class FileCitationBody extends S.Class<FileCitationBody>(\"FileCitationBody\")({\n  /**\n   * The type of the file citation. Always `file_citation`.\n   */\n  \"type\": FileCitationBodyType.pipe(S.propertySignature, S.withConstructorDefault(() => \"file_citation\" as const)),\n  /**\n   * The ID of the file.\n   */\n  \"file_id\": S.String,\n  /**\n   * The index of the file in the list of files.\n   */\n  \"index\": S.Int,\n  /**\n   * The filename of the file cited.\n   */\n  \"filename\": S.String\n}) {}\n\n/**\n * The type of the URL citation. Always `url_citation`.\n */\nexport class UrlCitationBodyType extends S.Literal(\"url_citation\") {}\n\n/**\n * A citation for a web resource used to generate a model response.\n */\nexport class UrlCitationBody extends S.Class<UrlCitationBody>(\"UrlCitationBody\")({\n  /**\n   * The type of the URL citation. Always `url_citation`.\n   */\n  \"type\": UrlCitationBodyType.pipe(S.propertySignature, S.withConstructorDefault(() => \"url_citation\" as const)),\n  /**\n   * The URL of the web resource.\n   */\n  \"url\": S.String,\n  /**\n   * The index of the first character of the URL citation in the message.\n   */\n  \"start_index\": S.Int,\n  /**\n   * The index of the last character of the URL citation in the message.\n   */\n  \"end_index\": S.Int,\n  /**\n   * The title of the web resource.\n   */\n  \"title\": S.String\n}) {}\n\n/**\n * The type of the container file citation. Always `container_file_citation`.\n */\nexport class ContainerFileCitationBodyType extends S.Literal(\"container_file_citation\") {}\n\n/**\n * A citation for a container file used to generate a model response.\n */\nexport class ContainerFileCitationBody extends S.Class<ContainerFileCitationBody>(\"ContainerFileCitationBody\")({\n  /**\n   * The type of the container file citation. Always `container_file_citation`.\n   */\n  \"type\": ContainerFileCitationBodyType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"container_file_citation\" as const)\n  ),\n  /**\n   * The ID of the container file.\n   */\n  \"container_id\": S.String,\n  /**\n   * The ID of the file.\n   */\n  \"file_id\": S.String,\n  /**\n   * The index of the first character of the container file citation in the message.\n   */\n  \"start_index\": S.Int,\n  /**\n   * The index of the last character of the container file citation in the message.\n   */\n  \"end_index\": S.Int,\n  /**\n   * The filename of the container file cited.\n   */\n  \"filename\": S.String\n}) {}\n\n/**\n * The type of the file path. Always `file_path`.\n */\nexport class FilePathType extends S.Literal(\"file_path\") {}\n\n/**\n * A path to a file.\n */\nexport class FilePath extends S.Class<FilePath>(\"FilePath\")({\n  /**\n   * The type of the file path. Always `file_path`.\n   */\n  \"type\": FilePathType,\n  /**\n   * The ID of the file.\n   */\n  \"file_id\": S.String,\n  /**\n   * The index of the file in the list of files.\n   */\n  \"index\": S.Int\n}) {}\n\nexport class Annotation extends S.Union(FileCitationBody, UrlCitationBody, ContainerFileCitationBody, FilePath) {}\n\n/**\n * The top log probability of a token.\n */\nexport class TopLogProb extends S.Class<TopLogProb>(\"TopLogProb\")({\n  \"token\": S.String,\n  \"logprob\": S.Number,\n  \"bytes\": S.Array(S.Int)\n}) {}\n\n/**\n * The log probability of a token.\n */\nexport class LogProb extends S.Class<LogProb>(\"LogProb\")({\n  \"token\": S.String,\n  \"logprob\": S.Number,\n  \"bytes\": S.Array(S.Int),\n  \"top_logprobs\": S.Array(TopLogProb)\n}) {}\n\n/**\n * A text output from the model.\n */\nexport class OutputTextContent extends S.Class<OutputTextContent>(\"OutputTextContent\")({\n  /**\n   * The type of the output text. Always `output_text`.\n   */\n  \"type\": OutputTextContentType.pipe(S.propertySignature, S.withConstructorDefault(() => \"output_text\" as const)),\n  /**\n   * The text output from the model.\n   */\n  \"text\": S.String,\n  /**\n   * The annotations of the text output.\n   */\n  \"annotations\": S.Array(Annotation),\n  \"logprobs\": S.optionalWith(S.Array(LogProb), { nullable: true })\n}) {}\n\nexport class TextContentType extends S.Literal(\"text\") {}\n\n/**\n * A text content.\n */\nexport class TextContent extends S.Class<TextContent>(\"TextContent\")({\n  \"type\": TextContentType.pipe(S.propertySignature, S.withConstructorDefault(() => \"text\" as const)),\n  \"text\": S.String\n}) {}\n\n/**\n * The type of the object. Always `summary_text`.\n */\nexport class SummaryTextContentType extends S.Literal(\"summary_text\") {}\n\n/**\n * A summary text from the model.\n */\nexport class SummaryTextContent extends S.Class<SummaryTextContent>(\"SummaryTextContent\")({\n  /**\n   * The type of the object. Always `summary_text`.\n   */\n  \"type\": SummaryTextContentType.pipe(S.propertySignature, S.withConstructorDefault(() => \"summary_text\" as const)),\n  /**\n   * A summary of the reasoning output from the model so far.\n   */\n  \"text\": S.String\n}) {}\n\n/**\n * The type of the reasoning text. Always `reasoning_text`.\n */\nexport class ReasoningTextContentType extends S.Literal(\"reasoning_text\") {}\n\n/**\n * Reasoning text from the model.\n */\nexport class ReasoningTextContent extends S.Class<ReasoningTextContent>(\"ReasoningTextContent\")({\n  /**\n   * The type of the reasoning text. Always `reasoning_text`.\n   */\n  \"type\": ReasoningTextContentType.pipe(S.propertySignature, S.withConstructorDefault(() => \"reasoning_text\" as const)),\n  /**\n   * The reasoning text from the model.\n   */\n  \"text\": S.String\n}) {}\n\n/**\n * The type of the refusal. Always `refusal`.\n */\nexport class RefusalContentType extends S.Literal(\"refusal\") {}\n\n/**\n * A refusal from the model.\n */\nexport class RefusalContent extends S.Class<RefusalContent>(\"RefusalContent\")({\n  /**\n   * The type of the refusal. Always `refusal`.\n   */\n  \"type\": RefusalContentType.pipe(S.propertySignature, S.withConstructorDefault(() => \"refusal\" as const)),\n  /**\n   * The refusal explanation from the model.\n   */\n  \"refusal\": S.String\n}) {}\n\n/**\n * The type of the input item. Always `input_image`.\n */\nexport class InputImageContentType extends S.Literal(\"input_image\") {}\n\nexport class ImageDetail extends S.Literal(\"low\", \"high\", \"auto\") {}\n\n/**\n * An image input to the model. Learn about [image inputs](https://platform.openai.com/docs/guides/vision).\n */\nexport class InputImageContent extends S.Class<InputImageContent>(\"InputImageContent\")({\n  /**\n   * The type of the input item. Always `input_image`.\n   */\n  \"type\": InputImageContentType.pipe(S.propertySignature, S.withConstructorDefault(() => \"input_image\" as const)),\n  \"image_url\": S.optionalWith(S.String, { nullable: true }),\n  \"file_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`.\n   */\n  \"detail\": ImageDetail\n}) {}\n\n/**\n * Specifies the event type. For a computer screenshot, this property is always set to `computer_screenshot`.\n */\nexport class ComputerScreenshotContentType extends S.Literal(\"computer_screenshot\") {}\n\n/**\n * A screenshot of a computer.\n */\nexport class ComputerScreenshotContent extends S.Class<ComputerScreenshotContent>(\"ComputerScreenshotContent\")({\n  /**\n   * Specifies the event type. For a computer screenshot, this property is always set to `computer_screenshot`.\n   */\n  \"type\": ComputerScreenshotContentType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"computer_screenshot\" as const)\n  ),\n  \"image_url\": S.NullOr(S.String),\n  \"file_id\": S.NullOr(S.String)\n}) {}\n\n/**\n * The type of the input item. Always `input_file`.\n */\nexport class InputFileContentType extends S.Literal(\"input_file\") {}\n\n/**\n * A file input to the model.\n */\nexport class InputFileContent extends S.Class<InputFileContent>(\"InputFileContent\")({\n  /**\n   * The type of the input item. Always `input_file`.\n   */\n  \"type\": InputFileContentType.pipe(S.propertySignature, S.withConstructorDefault(() => \"input_file\" as const)),\n  \"file_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The name of the file to be sent to the model.\n   */\n  \"filename\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The URL of the file to be sent to the model.\n   */\n  \"file_url\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The content of the file to be sent to the model.\n   */\n  \"file_data\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * A message to or from the model.\n */\nexport class Message extends S.Class<Message>(\"Message\")({\n  /**\n   * The type of the message. Always set to `message`.\n   */\n  \"type\": MessageType.pipe(S.propertySignature, S.withConstructorDefault(() => \"message\" as const)),\n  /**\n   * The unique ID of the message.\n   */\n  \"id\": S.String,\n  /**\n   * The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API.\n   */\n  \"status\": MessageStatus,\n  /**\n   * The role of the message. One of `unknown`, `user`, `assistant`, `system`, `critic`, `discriminator`, `developer`, or `tool`.\n   */\n  \"role\": MessageRole,\n  /**\n   * The content of the message\n   */\n  \"content\": S.Array(\n    S.Union(\n      InputTextContent,\n      OutputTextContent,\n      TextContent,\n      SummaryTextContent,\n      ReasoningTextContent,\n      RefusalContent,\n      InputImageContent,\n      ComputerScreenshotContent,\n      InputFileContent\n    )\n  )\n}) {}\n\n/**\n * The type of the function tool call. Always `function_call`.\n */\nexport class FunctionToolCallResourceType extends S.Literal(\"function_call\") {}\n\n/**\n * The status of the item. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when items are returned via API.\n */\nexport class FunctionToolCallResourceStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * A tool call to run a function. See the\n * [function calling guide](https://platform.openai.com/docs/guides/function-calling) for more information.\n */\nexport class FunctionToolCallResource extends S.Class<FunctionToolCallResource>(\"FunctionToolCallResource\")({\n  /**\n   * The unique ID of the function tool call.\n   */\n  \"id\": S.String,\n  /**\n   * The type of the function tool call. Always `function_call`.\n   */\n  \"type\": FunctionToolCallResourceType,\n  /**\n   * The unique ID of the function tool call generated by the model.\n   */\n  \"call_id\": S.String,\n  /**\n   * The name of the function to run.\n   */\n  \"name\": S.String,\n  /**\n   * A JSON string of the arguments to pass to the function.\n   */\n  \"arguments\": S.String,\n  /**\n   * The status of the item. One of `in_progress`, `completed`, or\n   * `incomplete`. Populated when items are returned via API.\n   */\n  \"status\": S.optionalWith(FunctionToolCallResourceStatus, { nullable: true })\n}) {}\n\n/**\n * The type of the function tool call output. Always `function_call_output`.\n */\nexport class FunctionToolCallOutputResourceType extends S.Literal(\"function_call_output\") {}\n\nexport class FunctionAndCustomToolCallOutput extends S.Union(InputTextContent, InputImageContent, InputFileContent) {}\n\n/**\n * The status of the item. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when items are returned via API.\n */\nexport class FunctionToolCallOutputResourceStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * The output of a function tool call.\n */\nexport class FunctionToolCallOutputResource\n  extends S.Class<FunctionToolCallOutputResource>(\"FunctionToolCallOutputResource\")({\n    /**\n     * The unique ID of the function tool call output. Populated when this item\n     * is returned via API.\n     */\n    \"id\": S.String,\n    /**\n     * The type of the function tool call output. Always `function_call_output`.\n     */\n    \"type\": FunctionToolCallOutputResourceType,\n    /**\n     * The unique ID of the function tool call generated by the model.\n     */\n    \"call_id\": S.String,\n    /**\n     * The output from the function call generated by your code.\n     * Can be a string or an list of output content.\n     */\n    \"output\": S.Union(\n      /**\n       * A string of the output of the function call.\n       */\n      S.String,\n      /**\n       * Text, image, or file output of the function call.\n       */\n      S.Array(FunctionAndCustomToolCallOutput)\n    ),\n    /**\n     * The status of the item. One of `in_progress`, `completed`, or\n     * `incomplete`. Populated when items are returned via API.\n     */\n    \"status\": S.optionalWith(FunctionToolCallOutputResourceStatus, { nullable: true })\n  })\n{}\n\n/**\n * The type of the file search tool call. Always `file_search_call`.\n */\nexport class FileSearchToolCallType extends S.Literal(\"file_search_call\") {}\n\n/**\n * The status of the file search tool call. One of `in_progress`,\n * `searching`, `incomplete` or `failed`,\n */\nexport class FileSearchToolCallStatus\n  extends S.Literal(\"in_progress\", \"searching\", \"completed\", \"incomplete\", \"failed\")\n{}\n\nexport class VectorStoreFileAttributes extends S.Union(\n  /**\n   * Set of 16 key-value pairs that can be attached to an object. This can be\n   * useful for storing additional information about the object in a structured\n   * format, and querying for objects via API or the dashboard. Keys are strings\n   * with a maximum length of 64 characters. Values are strings with a maximum\n   * length of 512 characters, booleans, or numbers.\n   */\n  S.Record({ key: S.String, value: S.Unknown }),\n  S.Null\n) {}\n\n/**\n * The results of a file search tool call. See the\n * [file search guide](https://platform.openai.com/docs/guides/tools-file-search) for more information.\n */\nexport class FileSearchToolCall extends S.Class<FileSearchToolCall>(\"FileSearchToolCall\")({\n  /**\n   * The unique ID of the file search tool call.\n   */\n  \"id\": S.String,\n  /**\n   * The type of the file search tool call. Always `file_search_call`.\n   */\n  \"type\": FileSearchToolCallType,\n  /**\n   * The status of the file search tool call. One of `in_progress`,\n   * `searching`, `incomplete` or `failed`,\n   */\n  \"status\": FileSearchToolCallStatus,\n  /**\n   * The queries used to search for files.\n   */\n  \"queries\": S.Array(S.String),\n  \"results\": S.optionalWith(\n    S.Array(S.Struct({\n      /**\n       * The unique ID of the file.\n       */\n      \"file_id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The text that was retrieved from the file.\n       */\n      \"text\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The name of the file.\n       */\n      \"filename\": S.optionalWith(S.String, { nullable: true }),\n      \"attributes\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n      /**\n       * The relevance score of the file - a value between 0 and 1.\n       */\n      \"score\": S.optionalWith(S.Number, { nullable: true })\n    })),\n    { nullable: true }\n  )\n}) {}\n\n/**\n * The type of the web search tool call. Always `web_search_call`.\n */\nexport class WebSearchToolCallType extends S.Literal(\"web_search_call\") {}\n\n/**\n * The status of the web search tool call.\n */\nexport class WebSearchToolCallStatus extends S.Literal(\"in_progress\", \"searching\", \"completed\", \"failed\") {}\n\n/**\n * The action type.\n */\nexport class WebSearchActionSearchType extends S.Literal(\"search\") {}\n\n/**\n * Action type \"search\" - Performs a web search query.\n */\nexport class WebSearchActionSearch extends S.Class<WebSearchActionSearch>(\"WebSearchActionSearch\")({\n  /**\n   * The action type.\n   */\n  \"type\": WebSearchActionSearchType,\n  /**\n   * The search query.\n   */\n  \"query\": S.String,\n  /**\n   * The sources used in the search.\n   */\n  \"sources\": S.optionalWith(\n    S.Array(S.Struct({\n      /**\n       * The type of source. Always `url`.\n       */\n      \"type\": S.Literal(\"url\"),\n      /**\n       * The URL of the source.\n       */\n      \"url\": S.String\n    })),\n    { nullable: true }\n  )\n}) {}\n\n/**\n * The action type.\n */\nexport class WebSearchActionOpenPageType extends S.Literal(\"open_page\") {}\n\n/**\n * Action type \"open_page\" - Opens a specific URL from search results.\n */\nexport class WebSearchActionOpenPage extends S.Class<WebSearchActionOpenPage>(\"WebSearchActionOpenPage\")({\n  /**\n   * The action type.\n   */\n  \"type\": WebSearchActionOpenPageType,\n  /**\n   * The URL opened by the model.\n   */\n  \"url\": S.String\n}) {}\n\n/**\n * The action type.\n */\nexport class WebSearchActionFindType extends S.Literal(\"find\") {}\n\n/**\n * Action type \"find\": Searches for a pattern within a loaded page.\n */\nexport class WebSearchActionFind extends S.Class<WebSearchActionFind>(\"WebSearchActionFind\")({\n  /**\n   * The action type.\n   */\n  \"type\": WebSearchActionFindType,\n  /**\n   * The URL of the page searched for the pattern.\n   */\n  \"url\": S.String,\n  /**\n   * The pattern or text to search for within the page.\n   */\n  \"pattern\": S.String\n}) {}\n\n/**\n * The results of a web search tool call. See the\n * [web search guide](https://platform.openai.com/docs/guides/tools-web-search) for more information.\n */\nexport class WebSearchToolCall extends S.Class<WebSearchToolCall>(\"WebSearchToolCall\")({\n  /**\n   * The unique ID of the web search tool call.\n   */\n  \"id\": S.String,\n  /**\n   * The type of the web search tool call. Always `web_search_call`.\n   */\n  \"type\": WebSearchToolCallType,\n  /**\n   * The status of the web search tool call.\n   */\n  \"status\": WebSearchToolCallStatus,\n  /**\n   * An object describing the specific action taken in this web search call.\n   * Includes details on how the model used the web (search, open_page, find).\n   */\n  \"action\": S.Record({ key: S.String, value: S.Unknown })\n}) {}\n\n/**\n * The type of the image generation call. Always `image_generation_call`.\n */\nexport class ImageGenToolCallType extends S.Literal(\"image_generation_call\") {}\n\n/**\n * The status of the image generation call.\n */\nexport class ImageGenToolCallStatus extends S.Literal(\"in_progress\", \"completed\", \"generating\", \"failed\") {}\n\n/**\n * An image generation request made by the model.\n */\nexport class ImageGenToolCall extends S.Class<ImageGenToolCall>(\"ImageGenToolCall\")({\n  /**\n   * The type of the image generation call. Always `image_generation_call`.\n   */\n  \"type\": ImageGenToolCallType,\n  /**\n   * The unique ID of the image generation call.\n   */\n  \"id\": S.String,\n  /**\n   * The status of the image generation call.\n   */\n  \"status\": ImageGenToolCallStatus,\n  \"result\": S.NullOr(S.String)\n}) {}\n\n/**\n * The type of the computer call. Always `computer_call`.\n */\nexport class ComputerToolCallType extends S.Literal(\"computer_call\") {}\n\n/**\n * Specifies the event type. For a click action, this property is always `click`.\n */\nexport class ClickParamType extends S.Literal(\"click\") {}\n\nexport class ClickButtonType extends S.Literal(\"left\", \"right\", \"wheel\", \"back\", \"forward\") {}\n\n/**\n * A click action.\n */\nexport class ClickParam extends S.Class<ClickParam>(\"ClickParam\")({\n  /**\n   * Specifies the event type. For a click action, this property is always `click`.\n   */\n  \"type\": ClickParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"click\" as const)),\n  /**\n   * Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`.\n   */\n  \"button\": ClickButtonType,\n  /**\n   * The x-coordinate where the click occurred.\n   */\n  \"x\": S.Int,\n  /**\n   * The y-coordinate where the click occurred.\n   */\n  \"y\": S.Int\n}) {}\n\n/**\n * Specifies the event type. For a double click action, this property is always set to `double_click`.\n */\nexport class DoubleClickActionType extends S.Literal(\"double_click\") {}\n\n/**\n * A double click action.\n */\nexport class DoubleClickAction extends S.Class<DoubleClickAction>(\"DoubleClickAction\")({\n  /**\n   * Specifies the event type. For a double click action, this property is always set to `double_click`.\n   */\n  \"type\": DoubleClickActionType.pipe(S.propertySignature, S.withConstructorDefault(() => \"double_click\" as const)),\n  /**\n   * The x-coordinate where the double click occurred.\n   */\n  \"x\": S.Int,\n  /**\n   * The y-coordinate where the double click occurred.\n   */\n  \"y\": S.Int\n}) {}\n\n/**\n * Specifies the event type. For a drag action, this property is\n * always set to `drag`.\n */\nexport class DragType extends S.Literal(\"drag\") {}\n\n/**\n * An x/y coordinate pair, e.g. `{ x: 100, y: 200 }`.\n */\nexport class DragPoint extends S.Class<DragPoint>(\"DragPoint\")({\n  /**\n   * The x-coordinate.\n   */\n  \"x\": S.Int,\n  /**\n   * The y-coordinate.\n   */\n  \"y\": S.Int\n}) {}\n\n/**\n * A drag action.\n */\nexport class Drag extends S.Class<Drag>(\"Drag\")({\n  /**\n   * Specifies the event type. For a drag action, this property is\n   * always set to `drag`.\n   */\n  \"type\": DragType.pipe(S.propertySignature, S.withConstructorDefault(() => \"drag\" as const)),\n  /**\n   * An array of coordinates representing the path of the drag action. Coordinates will appear as an array\n   * of objects, eg\n   * ```\n   * [\n   *   { x: 100, y: 200 },\n   *   { x: 200, y: 300 }\n   * ]\n   * ```\n   */\n  \"path\": S.Array(DragPoint)\n}) {}\n\n/**\n * Specifies the event type. For a keypress action, this property is always set to `keypress`.\n */\nexport class KeyPressActionType extends S.Literal(\"keypress\") {}\n\n/**\n * A collection of keypresses the model would like to perform.\n */\nexport class KeyPressAction extends S.Class<KeyPressAction>(\"KeyPressAction\")({\n  /**\n   * Specifies the event type. For a keypress action, this property is always set to `keypress`.\n   */\n  \"type\": KeyPressActionType.pipe(S.propertySignature, S.withConstructorDefault(() => \"keypress\" as const)),\n  /**\n   * The combination of keys the model is requesting to be pressed. This is an array of strings, each representing a key.\n   */\n  \"keys\": S.Array(S.String)\n}) {}\n\n/**\n * Specifies the event type. For a move action, this property is\n * always set to `move`.\n */\nexport class MoveType extends S.Literal(\"move\") {}\n\n/**\n * A mouse move action.\n */\nexport class Move extends S.Class<Move>(\"Move\")({\n  /**\n   * Specifies the event type. For a move action, this property is\n   * always set to `move`.\n   */\n  \"type\": MoveType.pipe(S.propertySignature, S.withConstructorDefault(() => \"move\" as const)),\n  /**\n   * The x-coordinate to move to.\n   */\n  \"x\": S.Int,\n  /**\n   * The y-coordinate to move to.\n   */\n  \"y\": S.Int\n}) {}\n\n/**\n * Specifies the event type. For a screenshot action, this property is\n * always set to `screenshot`.\n */\nexport class ScreenshotType extends S.Literal(\"screenshot\") {}\n\n/**\n * A screenshot action.\n */\nexport class Screenshot extends S.Class<Screenshot>(\"Screenshot\")({\n  /**\n   * Specifies the event type. For a screenshot action, this property is\n   * always set to `screenshot`.\n   */\n  \"type\": ScreenshotType.pipe(S.propertySignature, S.withConstructorDefault(() => \"screenshot\" as const))\n}) {}\n\n/**\n * Specifies the event type. For a scroll action, this property is\n * always set to `scroll`.\n */\nexport class ScrollType extends S.Literal(\"scroll\") {}\n\n/**\n * A scroll action.\n */\nexport class Scroll extends S.Class<Scroll>(\"Scroll\")({\n  /**\n   * Specifies the event type. For a scroll action, this property is\n   * always set to `scroll`.\n   */\n  \"type\": ScrollType.pipe(S.propertySignature, S.withConstructorDefault(() => \"scroll\" as const)),\n  /**\n   * The x-coordinate where the scroll occurred.\n   */\n  \"x\": S.Int,\n  /**\n   * The y-coordinate where the scroll occurred.\n   */\n  \"y\": S.Int,\n  /**\n   * The horizontal scroll distance.\n   */\n  \"scroll_x\": S.Int,\n  /**\n   * The vertical scroll distance.\n   */\n  \"scroll_y\": S.Int\n}) {}\n\n/**\n * Specifies the event type. For a type action, this property is\n * always set to `type`.\n */\nexport class TypeType extends S.Literal(\"type\") {}\n\n/**\n * An action to type in text.\n */\nexport class Type extends S.Class<Type>(\"Type\")({\n  /**\n   * Specifies the event type. For a type action, this property is\n   * always set to `type`.\n   */\n  \"type\": TypeType.pipe(S.propertySignature, S.withConstructorDefault(() => \"type\" as const)),\n  /**\n   * The text to type.\n   */\n  \"text\": S.String\n}) {}\n\n/**\n * Specifies the event type. For a wait action, this property is\n * always set to `wait`.\n */\nexport class WaitType extends S.Literal(\"wait\") {}\n\n/**\n * A wait action.\n */\nexport class Wait extends S.Class<Wait>(\"Wait\")({\n  /**\n   * Specifies the event type. For a wait action, this property is\n   * always set to `wait`.\n   */\n  \"type\": WaitType.pipe(S.propertySignature, S.withConstructorDefault(() => \"wait\" as const))\n}) {}\n\nexport class ComputerAction\n  extends S.Union(ClickParam, DoubleClickAction, Drag, KeyPressAction, Move, Screenshot, Scroll, Type, Wait)\n{}\n\n/**\n * A pending safety check for the computer call.\n */\nexport class ComputerCallSafetyCheckParam\n  extends S.Class<ComputerCallSafetyCheckParam>(\"ComputerCallSafetyCheckParam\")({\n    /**\n     * The ID of the pending safety check.\n     */\n    \"id\": S.String,\n    \"code\": S.optionalWith(S.String, { nullable: true }),\n    \"message\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * The status of the item. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when items are returned via API.\n */\nexport class ComputerToolCallStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * A tool call to a computer use tool. See the\n * [computer use guide](https://platform.openai.com/docs/guides/tools-computer-use) for more information.\n */\nexport class ComputerToolCall extends S.Class<ComputerToolCall>(\"ComputerToolCall\")({\n  /**\n   * The type of the computer call. Always `computer_call`.\n   */\n  \"type\": ComputerToolCallType.pipe(S.propertySignature, S.withConstructorDefault(() => \"computer_call\" as const)),\n  /**\n   * The unique ID of the computer call.\n   */\n  \"id\": S.String,\n  /**\n   * An identifier used when responding to the tool call with output.\n   */\n  \"call_id\": S.String,\n  \"action\": ComputerAction,\n  /**\n   * The pending safety checks for the computer call.\n   */\n  \"pending_safety_checks\": S.Array(ComputerCallSafetyCheckParam),\n  /**\n   * The status of the item. One of `in_progress`, `completed`, or\n   * `incomplete`. Populated when items are returned via API.\n   */\n  \"status\": ComputerToolCallStatus\n}) {}\n\n/**\n * The type of the computer tool call output. Always `computer_call_output`.\n */\nexport class ComputerToolCallOutputResourceType extends S.Literal(\"computer_call_output\") {}\n\n/**\n * Specifies the event type. For a computer screenshot, this property is\n * always set to `computer_screenshot`.\n */\nexport class ComputerScreenshotImageType extends S.Literal(\"computer_screenshot\") {}\n\n/**\n * A computer screenshot image used with the computer use tool.\n */\nexport class ComputerScreenshotImage extends S.Class<ComputerScreenshotImage>(\"ComputerScreenshotImage\")({\n  /**\n   * Specifies the event type. For a computer screenshot, this property is\n   * always set to `computer_screenshot`.\n   */\n  \"type\": ComputerScreenshotImageType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"computer_screenshot\" as const)\n  ),\n  /**\n   * The URL of the screenshot image.\n   */\n  \"image_url\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The identifier of an uploaded file that contains the screenshot.\n   */\n  \"file_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The status of the message input. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when input items are returned via API.\n */\nexport class ComputerToolCallOutputResourceStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * The output of a computer tool call.\n */\nexport class ComputerToolCallOutputResource\n  extends S.Class<ComputerToolCallOutputResource>(\"ComputerToolCallOutputResource\")({\n    /**\n     * The ID of the computer tool call output.\n     */\n    \"id\": S.String,\n    /**\n     * The type of the computer tool call output. Always `computer_call_output`.\n     */\n    \"type\": ComputerToolCallOutputResourceType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"computer_call_output\" as const)\n    ),\n    /**\n     * The ID of the computer tool call that produced the output.\n     */\n    \"call_id\": S.String,\n    /**\n     * The safety checks reported by the API that have been acknowledged by the\n     * developer.\n     */\n    \"acknowledged_safety_checks\": S.optionalWith(S.Array(ComputerCallSafetyCheckParam), { nullable: true }),\n    \"output\": ComputerScreenshotImage,\n    /**\n     * The status of the message input. One of `in_progress`, `completed`, or\n     * `incomplete`. Populated when input items are returned via API.\n     */\n    \"status\": S.optionalWith(ComputerToolCallOutputResourceStatus, { nullable: true })\n  })\n{}\n\n/**\n * The type of the object. Always `reasoning`.\n */\nexport class ReasoningItemType extends S.Literal(\"reasoning\") {}\n\n/**\n * The type of the object. Always `summary_text`.\n */\nexport class SummaryType extends S.Literal(\"summary_text\") {}\n\n/**\n * A summary text from the model.\n */\nexport class Summary extends S.Class<Summary>(\"Summary\")({\n  /**\n   * The type of the object. Always `summary_text`.\n   */\n  \"type\": SummaryType.pipe(S.propertySignature, S.withConstructorDefault(() => \"summary_text\" as const)),\n  /**\n   * A summary of the reasoning output from the model so far.\n   */\n  \"text\": S.String\n}) {}\n\n/**\n * The status of the item. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when items are returned via API.\n */\nexport class ReasoningItemStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * A description of the chain of thought used by a reasoning model while generating\n * a response. Be sure to include these items in your `input` to the Responses API\n * for subsequent turns of a conversation if you are manually\n * [managing context](https://platform.openai.com/docs/guides/conversation-state).\n */\nexport class ReasoningItem extends S.Class<ReasoningItem>(\"ReasoningItem\")({\n  /**\n   * The type of the object. Always `reasoning`.\n   */\n  \"type\": ReasoningItemType,\n  /**\n   * The unique identifier of the reasoning content.\n   */\n  \"id\": S.String,\n  \"encrypted_content\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Reasoning summary content.\n   */\n  \"summary\": S.Array(Summary),\n  /**\n   * Reasoning text content.\n   */\n  \"content\": S.optionalWith(S.Array(ReasoningTextContent), { nullable: true }),\n  /**\n   * The status of the item. One of `in_progress`, `completed`, or\n   * `incomplete`. Populated when items are returned via API.\n   */\n  \"status\": S.optionalWith(ReasoningItemStatus, { nullable: true })\n}) {}\n\n/**\n * The type of the code interpreter tool call. Always `code_interpreter_call`.\n */\nexport class CodeInterpreterToolCallType extends S.Literal(\"code_interpreter_call\") {}\n\n/**\n * The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`.\n */\nexport class CodeInterpreterToolCallStatus\n  extends S.Literal(\"in_progress\", \"completed\", \"incomplete\", \"interpreting\", \"failed\")\n{}\n\n/**\n * The type of the output. Always `logs`.\n */\nexport class CodeInterpreterOutputLogsType extends S.Literal(\"logs\") {}\n\n/**\n * The logs output from the code interpreter.\n */\nexport class CodeInterpreterOutputLogs extends S.Class<CodeInterpreterOutputLogs>(\"CodeInterpreterOutputLogs\")({\n  /**\n   * The type of the output. Always `logs`.\n   */\n  \"type\": CodeInterpreterOutputLogsType.pipe(S.propertySignature, S.withConstructorDefault(() => \"logs\" as const)),\n  /**\n   * The logs output from the code interpreter.\n   */\n  \"logs\": S.String\n}) {}\n\n/**\n * The type of the output. Always `image`.\n */\nexport class CodeInterpreterOutputImageType extends S.Literal(\"image\") {}\n\n/**\n * The image output from the code interpreter.\n */\nexport class CodeInterpreterOutputImage extends S.Class<CodeInterpreterOutputImage>(\"CodeInterpreterOutputImage\")({\n  /**\n   * The type of the output. Always `image`.\n   */\n  \"type\": CodeInterpreterOutputImageType.pipe(S.propertySignature, S.withConstructorDefault(() => \"image\" as const)),\n  /**\n   * The URL of the image output from the code interpreter.\n   */\n  \"url\": S.String\n}) {}\n\n/**\n * A tool call to run code.\n */\nexport class CodeInterpreterToolCall extends S.Class<CodeInterpreterToolCall>(\"CodeInterpreterToolCall\")({\n  /**\n   * The type of the code interpreter tool call. Always `code_interpreter_call`.\n   */\n  \"type\": CodeInterpreterToolCallType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"code_interpreter_call\" as const)\n  ),\n  /**\n   * The unique ID of the code interpreter tool call.\n   */\n  \"id\": S.String,\n  /**\n   * The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`.\n   */\n  \"status\": CodeInterpreterToolCallStatus,\n  /**\n   * The ID of the container used to run the code.\n   */\n  \"container_id\": S.String,\n  \"code\": S.NullOr(S.String),\n  \"outputs\": S.NullOr(S.Array(S.Union(CodeInterpreterOutputLogs, CodeInterpreterOutputImage)))\n}) {}\n\n/**\n * The type of the local shell call. Always `local_shell_call`.\n */\nexport class LocalShellToolCallType extends S.Literal(\"local_shell_call\") {}\n\n/**\n * The type of the local shell action. Always `exec`.\n */\nexport class LocalShellExecActionType extends S.Literal(\"exec\") {}\n\n/**\n * Execute a shell command on the server.\n */\nexport class LocalShellExecAction extends S.Class<LocalShellExecAction>(\"LocalShellExecAction\")({\n  /**\n   * The type of the local shell action. Always `exec`.\n   */\n  \"type\": LocalShellExecActionType.pipe(S.propertySignature, S.withConstructorDefault(() => \"exec\" as const)),\n  /**\n   * The command to run.\n   */\n  \"command\": S.Array(S.String),\n  \"timeout_ms\": S.optionalWith(S.Int, { nullable: true }),\n  \"working_directory\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Environment variables to set for the command.\n   */\n  \"env\": S.Record({ key: S.String, value: S.Unknown }),\n  \"user\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The status of the local shell call.\n */\nexport class LocalShellToolCallStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * A tool call to run a command on the local shell.\n */\nexport class LocalShellToolCall extends S.Class<LocalShellToolCall>(\"LocalShellToolCall\")({\n  /**\n   * The type of the local shell call. Always `local_shell_call`.\n   */\n  \"type\": LocalShellToolCallType,\n  /**\n   * The unique ID of the local shell call.\n   */\n  \"id\": S.String,\n  /**\n   * The unique ID of the local shell tool call generated by the model.\n   */\n  \"call_id\": S.String,\n  \"action\": LocalShellExecAction,\n  /**\n   * The status of the local shell call.\n   */\n  \"status\": LocalShellToolCallStatus\n}) {}\n\n/**\n * The type of the local shell tool call output. Always `local_shell_call_output`.\n */\nexport class LocalShellToolCallOutputType extends S.Literal(\"local_shell_call_output\") {}\n\n/**\n * The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n */\nexport class LocalShellToolCallOutputStatusEnum extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * The output of a local shell tool call.\n */\nexport class LocalShellToolCallOutput extends S.Class<LocalShellToolCallOutput>(\"LocalShellToolCallOutput\")({\n  /**\n   * The type of the local shell tool call output. Always `local_shell_call_output`.\n   */\n  \"type\": LocalShellToolCallOutputType,\n  /**\n   * The unique ID of the local shell tool call generated by the model.\n   */\n  \"id\": S.String,\n  /**\n   * A JSON string of the output of the local shell tool call.\n   */\n  \"output\": S.String,\n  \"status\": S.optionalWith(LocalShellToolCallOutputStatusEnum, { nullable: true })\n}) {}\n\n/**\n * The type of the item. Always `shell_call`.\n */\nexport class FunctionShellCallType extends S.Literal(\"shell_call\") {}\n\n/**\n * Execute a shell command.\n */\nexport class FunctionShellAction extends S.Class<FunctionShellAction>(\"FunctionShellAction\")({\n  \"commands\": S.Array(S.String),\n  \"timeout_ms\": S.NullOr(S.Int),\n  \"max_output_length\": S.NullOr(S.Int)\n}) {}\n\nexport class LocalShellCallStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * A tool call that executes one or more shell commands in a managed environment.\n */\nexport class FunctionShellCall extends S.Class<FunctionShellCall>(\"FunctionShellCall\")({\n  /**\n   * The type of the item. Always `shell_call`.\n   */\n  \"type\": FunctionShellCallType.pipe(S.propertySignature, S.withConstructorDefault(() => \"shell_call\" as const)),\n  /**\n   * The unique ID of the function shell tool call. Populated when this item is returned via API.\n   */\n  \"id\": S.String,\n  /**\n   * The unique ID of the function shell tool call generated by the model.\n   */\n  \"call_id\": S.String,\n  /**\n   * The shell commands and limits that describe how to run the tool call.\n   */\n  \"action\": FunctionShellAction,\n  /**\n   * The status of the shell call. One of `in_progress`, `completed`, or `incomplete`.\n   */\n  \"status\": LocalShellCallStatus,\n  /**\n   * The ID of the entity that created this tool call.\n   */\n  \"created_by\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The type of the shell call output. Always `shell_call_output`.\n */\nexport class FunctionShellCallOutputType extends S.Literal(\"shell_call_output\") {}\n\n/**\n * The outcome type. Always `timeout`.\n */\nexport class FunctionShellCallOutputTimeoutOutcomeType extends S.Literal(\"timeout\") {}\n\n/**\n * Indicates that the function shell call exceeded its configured time limit.\n */\nexport class FunctionShellCallOutputTimeoutOutcome\n  extends S.Class<FunctionShellCallOutputTimeoutOutcome>(\"FunctionShellCallOutputTimeoutOutcome\")({\n    /**\n     * The outcome type. Always `timeout`.\n     */\n    \"type\": FunctionShellCallOutputTimeoutOutcomeType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"timeout\" as const)\n    )\n  })\n{}\n\n/**\n * The outcome type. Always `exit`.\n */\nexport class FunctionShellCallOutputExitOutcomeType extends S.Literal(\"exit\") {}\n\n/**\n * Indicates that the shell commands finished and returned an exit code.\n */\nexport class FunctionShellCallOutputExitOutcome\n  extends S.Class<FunctionShellCallOutputExitOutcome>(\"FunctionShellCallOutputExitOutcome\")({\n    /**\n     * The outcome type. Always `exit`.\n     */\n    \"type\": FunctionShellCallOutputExitOutcomeType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"exit\" as const)\n    ),\n    /**\n     * Exit code from the shell process.\n     */\n    \"exit_code\": S.Int\n  })\n{}\n\n/**\n * The content of a shell call output.\n */\nexport class FunctionShellCallOutputContent\n  extends S.Class<FunctionShellCallOutputContent>(\"FunctionShellCallOutputContent\")({\n    \"stdout\": S.String,\n    \"stderr\": S.String,\n    /**\n     * Represents either an exit outcome (with an exit code) or a timeout outcome for a shell call output chunk.\n     */\n    \"outcome\": S.Union(FunctionShellCallOutputTimeoutOutcome, FunctionShellCallOutputExitOutcome),\n    \"created_by\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * The output of a shell tool call.\n */\nexport class FunctionShellCallOutput extends S.Class<FunctionShellCallOutput>(\"FunctionShellCallOutput\")({\n  /**\n   * The type of the shell call output. Always `shell_call_output`.\n   */\n  \"type\": FunctionShellCallOutputType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"shell_call_output\" as const)\n  ),\n  /**\n   * The unique ID of the shell call output. Populated when this item is returned via API.\n   */\n  \"id\": S.String,\n  /**\n   * The unique ID of the shell tool call generated by the model.\n   */\n  \"call_id\": S.String,\n  /**\n   * An array of shell call output contents\n   */\n  \"output\": S.Array(FunctionShellCallOutputContent),\n  \"max_output_length\": S.NullOr(S.Int),\n  \"created_by\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The type of the item. Always `apply_patch_call`.\n */\nexport class ApplyPatchToolCallType extends S.Literal(\"apply_patch_call\") {}\n\nexport class ApplyPatchCallStatus extends S.Literal(\"in_progress\", \"completed\") {}\n\n/**\n * Create a new file with the provided diff.\n */\nexport class ApplyPatchCreateFileOperationType extends S.Literal(\"create_file\") {}\n\n/**\n * Instruction describing how to create a file via the apply_patch tool.\n */\nexport class ApplyPatchCreateFileOperation\n  extends S.Class<ApplyPatchCreateFileOperation>(\"ApplyPatchCreateFileOperation\")({\n    /**\n     * Create a new file with the provided diff.\n     */\n    \"type\": ApplyPatchCreateFileOperationType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"create_file\" as const)\n    ),\n    /**\n     * Path of the file to create.\n     */\n    \"path\": S.String,\n    /**\n     * Diff to apply.\n     */\n    \"diff\": S.String\n  })\n{}\n\n/**\n * Delete the specified file.\n */\nexport class ApplyPatchDeleteFileOperationType extends S.Literal(\"delete_file\") {}\n\n/**\n * Instruction describing how to delete a file via the apply_patch tool.\n */\nexport class ApplyPatchDeleteFileOperation\n  extends S.Class<ApplyPatchDeleteFileOperation>(\"ApplyPatchDeleteFileOperation\")({\n    /**\n     * Delete the specified file.\n     */\n    \"type\": ApplyPatchDeleteFileOperationType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"delete_file\" as const)\n    ),\n    /**\n     * Path of the file to delete.\n     */\n    \"path\": S.String\n  })\n{}\n\n/**\n * Update an existing file with the provided diff.\n */\nexport class ApplyPatchUpdateFileOperationType extends S.Literal(\"update_file\") {}\n\n/**\n * Instruction describing how to update a file via the apply_patch tool.\n */\nexport class ApplyPatchUpdateFileOperation\n  extends S.Class<ApplyPatchUpdateFileOperation>(\"ApplyPatchUpdateFileOperation\")({\n    /**\n     * Update an existing file with the provided diff.\n     */\n    \"type\": ApplyPatchUpdateFileOperationType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"update_file\" as const)\n    ),\n    /**\n     * Path of the file to update.\n     */\n    \"path\": S.String,\n    /**\n     * Diff to apply.\n     */\n    \"diff\": S.String\n  })\n{}\n\n/**\n * A tool call that applies file diffs by creating, deleting, or updating files.\n */\nexport class ApplyPatchToolCall extends S.Class<ApplyPatchToolCall>(\"ApplyPatchToolCall\")({\n  /**\n   * The type of the item. Always `apply_patch_call`.\n   */\n  \"type\": ApplyPatchToolCallType.pipe(S.propertySignature, S.withConstructorDefault(() => \"apply_patch_call\" as const)),\n  /**\n   * The unique ID of the apply patch tool call. Populated when this item is returned via API.\n   */\n  \"id\": S.String,\n  /**\n   * The unique ID of the apply patch tool call generated by the model.\n   */\n  \"call_id\": S.String,\n  /**\n   * The status of the apply patch tool call. One of `in_progress` or `completed`.\n   */\n  \"status\": ApplyPatchCallStatus,\n  /**\n   * One of the create_file, delete_file, or update_file operations applied via apply_patch.\n   */\n  \"operation\": S.Union(ApplyPatchCreateFileOperation, ApplyPatchDeleteFileOperation, ApplyPatchUpdateFileOperation),\n  /**\n   * The ID of the entity that created this tool call.\n   */\n  \"created_by\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The type of the item. Always `apply_patch_call_output`.\n */\nexport class ApplyPatchToolCallOutputType extends S.Literal(\"apply_patch_call_output\") {}\n\nexport class ApplyPatchCallOutputStatus extends S.Literal(\"completed\", \"failed\") {}\n\n/**\n * The output emitted by an apply patch tool call.\n */\nexport class ApplyPatchToolCallOutput extends S.Class<ApplyPatchToolCallOutput>(\"ApplyPatchToolCallOutput\")({\n  /**\n   * The type of the item. Always `apply_patch_call_output`.\n   */\n  \"type\": ApplyPatchToolCallOutputType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"apply_patch_call_output\" as const)\n  ),\n  /**\n   * The unique ID of the apply patch tool call output. Populated when this item is returned via API.\n   */\n  \"id\": S.String,\n  /**\n   * The unique ID of the apply patch tool call generated by the model.\n   */\n  \"call_id\": S.String,\n  /**\n   * The status of the apply patch tool call output. One of `completed` or `failed`.\n   */\n  \"status\": ApplyPatchCallOutputStatus,\n  \"output\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The ID of the entity that created this tool call output.\n   */\n  \"created_by\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The type of the item. Always `mcp_list_tools`.\n */\nexport class MCPListToolsType extends S.Literal(\"mcp_list_tools\") {}\n\n/**\n * A tool available on an MCP server.\n */\nexport class MCPListToolsTool extends S.Class<MCPListToolsTool>(\"MCPListToolsTool\")({\n  /**\n   * The name of the tool.\n   */\n  \"name\": S.String,\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The JSON schema describing the tool's input.\n   */\n  \"input_schema\": S.Record({ key: S.String, value: S.Unknown }),\n  \"annotations\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * A list of tools available on an MCP server.\n */\nexport class MCPListTools extends S.Class<MCPListTools>(\"MCPListTools\")({\n  /**\n   * The type of the item. Always `mcp_list_tools`.\n   */\n  \"type\": MCPListToolsType,\n  /**\n   * The unique ID of the list.\n   */\n  \"id\": S.String,\n  /**\n   * The label of the MCP server.\n   */\n  \"server_label\": S.String,\n  /**\n   * The tools available on the server.\n   */\n  \"tools\": S.Array(MCPListToolsTool),\n  \"error\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The type of the item. Always `mcp_approval_request`.\n */\nexport class MCPApprovalRequestType extends S.Literal(\"mcp_approval_request\") {}\n\n/**\n * A request for human approval of a tool invocation.\n */\nexport class MCPApprovalRequest extends S.Class<MCPApprovalRequest>(\"MCPApprovalRequest\")({\n  /**\n   * The type of the item. Always `mcp_approval_request`.\n   */\n  \"type\": MCPApprovalRequestType,\n  /**\n   * The unique ID of the approval request.\n   */\n  \"id\": S.String,\n  /**\n   * The label of the MCP server making the request.\n   */\n  \"server_label\": S.String,\n  /**\n   * The name of the tool to run.\n   */\n  \"name\": S.String,\n  /**\n   * A JSON string of arguments for the tool.\n   */\n  \"arguments\": S.String\n}) {}\n\n/**\n * The type of the item. Always `mcp_approval_response`.\n */\nexport class MCPApprovalResponseResourceType extends S.Literal(\"mcp_approval_response\") {}\n\n/**\n * A response to an MCP approval request.\n */\nexport class MCPApprovalResponseResource extends S.Class<MCPApprovalResponseResource>(\"MCPApprovalResponseResource\")({\n  /**\n   * The type of the item. Always `mcp_approval_response`.\n   */\n  \"type\": MCPApprovalResponseResourceType,\n  /**\n   * The unique ID of the approval response\n   */\n  \"id\": S.String,\n  /**\n   * The ID of the approval request being answered.\n   */\n  \"approval_request_id\": S.String,\n  /**\n   * Whether the request was approved.\n   */\n  \"approve\": S.Boolean,\n  \"reason\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The type of the item. Always `mcp_call`.\n */\nexport class MCPToolCallType extends S.Literal(\"mcp_call\") {}\n\nexport class MCPToolCallStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\", \"calling\", \"failed\") {}\n\n/**\n * An invocation of a tool on an MCP server.\n */\nexport class MCPToolCall extends S.Class<MCPToolCall>(\"MCPToolCall\")({\n  /**\n   * The type of the item. Always `mcp_call`.\n   */\n  \"type\": MCPToolCallType,\n  /**\n   * The unique ID of the tool call.\n   */\n  \"id\": S.String,\n  /**\n   * The label of the MCP server running the tool.\n   */\n  \"server_label\": S.String,\n  /**\n   * The name of the tool that was run.\n   */\n  \"name\": S.String,\n  /**\n   * A JSON string of the arguments passed to the tool.\n   */\n  \"arguments\": S.String,\n  \"output\": S.optionalWith(S.String, { nullable: true }),\n  \"error\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`, or `failed`.\n   */\n  \"status\": S.optionalWith(MCPToolCallStatus, { nullable: true }),\n  \"approval_request_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The type of the custom tool call. Always `custom_tool_call`.\n */\nexport class CustomToolCallType extends S.Literal(\"custom_tool_call\") {}\n\n/**\n * A call to a custom tool created by the model.\n */\nexport class CustomToolCall extends S.Class<CustomToolCall>(\"CustomToolCall\")({\n  /**\n   * The type of the custom tool call. Always `custom_tool_call`.\n   */\n  \"type\": CustomToolCallType,\n  /**\n   * The unique ID of the custom tool call in the OpenAI platform.\n   */\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * An identifier used to map this custom tool call to a tool call output.\n   */\n  \"call_id\": S.String,\n  /**\n   * The name of the custom tool being called.\n   */\n  \"name\": S.String,\n  /**\n   * The input for the custom tool call generated by the model.\n   */\n  \"input\": S.String\n}) {}\n\n/**\n * The type of the custom tool call output. Always `custom_tool_call_output`.\n */\nexport class CustomToolCallOutputType extends S.Literal(\"custom_tool_call_output\") {}\n\n/**\n * The output of a custom tool call from your code, being sent back to the model.\n */\nexport class CustomToolCallOutput extends S.Class<CustomToolCallOutput>(\"CustomToolCallOutput\")({\n  /**\n   * The type of the custom tool call output. Always `custom_tool_call_output`.\n   */\n  \"type\": CustomToolCallOutputType,\n  /**\n   * The unique ID of the custom tool call output in the OpenAI platform.\n   */\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The call ID, used to map this custom tool call output to a custom tool call.\n   */\n  \"call_id\": S.String,\n  /**\n   * The output from the custom tool call generated by your code.\n   * Can be a string or an list of output content.\n   */\n  \"output\": S.Union(\n    /**\n     * A string of the output of the custom tool call.\n     */\n    S.String,\n    /**\n     * Text, image, or file output of the custom tool call.\n     */\n    S.Array(FunctionAndCustomToolCallOutput)\n  )\n}) {}\n\n/**\n * A single item within a conversation. The set of possible types are the same as the `output` type of a [Response object](https://platform.openai.com/docs/api-reference/responses/object#responses/object-output).\n */\nexport class ConversationItem extends S.Union(\n  Message,\n  FunctionToolCallResource,\n  FunctionToolCallOutputResource,\n  FileSearchToolCall,\n  WebSearchToolCall,\n  ImageGenToolCall,\n  ComputerToolCall,\n  ComputerToolCallOutputResource,\n  ReasoningItem,\n  CodeInterpreterToolCall,\n  LocalShellToolCall,\n  LocalShellToolCallOutput,\n  FunctionShellCall,\n  FunctionShellCallOutput,\n  ApplyPatchToolCall,\n  ApplyPatchToolCallOutput,\n  MCPListTools,\n  MCPApprovalRequest,\n  MCPApprovalResponseResource,\n  MCPToolCall,\n  CustomToolCall,\n  CustomToolCallOutput\n) {}\n\n/**\n * A list of Conversation items.\n */\nexport class ConversationItemList extends S.Class<ConversationItemList>(\"ConversationItemList\")({\n  /**\n   * The type of object returned, must be `list`.\n   */\n  \"object\": S.Literal(\"list\"),\n  /**\n   * A list of conversation items.\n   */\n  \"data\": S.Array(ConversationItem),\n  /**\n   * Whether there are more items available.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * The ID of the first item in the list.\n   */\n  \"first_id\": S.String,\n  /**\n   * The ID of the last item in the list.\n   */\n  \"last_id\": S.String\n}) {}\n\nexport class CreateConversationItemsParams extends S.Struct({\n  \"include\": S.optionalWith(S.Array(IncludeEnum), { nullable: true })\n}) {}\n\n/**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\nexport class EasyInputMessageRole extends S.Literal(\"user\", \"assistant\", \"system\", \"developer\") {}\n\nexport class InputContent extends S.Union(InputTextContent, InputImageContent, InputFileContent) {}\n\n/**\n * A list of one or many input items to the model, containing different content\n * types.\n */\nexport class InputMessageContentList extends S.Array(InputContent) {}\n\n/**\n * The type of the message input. Always `message`.\n */\nexport class EasyInputMessageType extends S.Literal(\"message\") {}\n\n/**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\nexport class EasyInputMessage extends S.Class<EasyInputMessage>(\"EasyInputMessage\")({\n  /**\n   * The role of the message input. One of `user`, `assistant`, `system`, or\n   * `developer`.\n   */\n  \"role\": EasyInputMessageRole,\n  /**\n   * Text, image, or audio input to the model, used to generate a response.\n   * Can also contain previous assistant responses.\n   */\n  \"content\": S.Union(\n    /**\n     * A text input to the model.\n     */\n    S.String,\n    InputMessageContentList\n  ),\n  /**\n   * The type of the message input. Always `message`.\n   */\n  \"type\": S.optionalWith(EasyInputMessageType, { nullable: true })\n}) {}\n\n/**\n * The type of the message input. Always set to `message`.\n */\nexport class InputMessageType extends S.Literal(\"message\") {}\n\n/**\n * The role of the message input. One of `user`, `system`, or `developer`.\n */\nexport class InputMessageRole extends S.Literal(\"user\", \"system\", \"developer\") {}\n\n/**\n * The status of item. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when items are returned via API.\n */\nexport class InputMessageStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role.\n */\nexport class InputMessage extends S.Class<InputMessage>(\"InputMessage\")({\n  /**\n   * The type of the message input. Always set to `message`.\n   */\n  \"type\": S.optionalWith(InputMessageType, { nullable: true }),\n  /**\n   * The role of the message input. One of `user`, `system`, or `developer`.\n   */\n  \"role\": InputMessageRole,\n  /**\n   * The status of item. One of `in_progress`, `completed`, or\n   * `incomplete`. Populated when items are returned via API.\n   */\n  \"status\": S.optionalWith(InputMessageStatus, { nullable: true }),\n  \"content\": InputMessageContentList\n}) {}\n\n/**\n * The type of the output message. Always `message`.\n */\nexport class OutputMessageType extends S.Literal(\"message\") {}\n\n/**\n * The role of the output message. Always `assistant`.\n */\nexport class OutputMessageRole extends S.Literal(\"assistant\") {}\n\nexport class OutputMessageContent extends S.Union(OutputTextContent, RefusalContent) {}\n\n/**\n * The status of the message input. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when input items are returned via API.\n */\nexport class OutputMessageStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * An output message from the model.\n */\nexport class OutputMessage extends S.Class<OutputMessage>(\"OutputMessage\")({\n  /**\n   * The unique ID of the output message.\n   */\n  \"id\": S.String,\n  /**\n   * The type of the output message. Always `message`.\n   */\n  \"type\": OutputMessageType,\n  /**\n   * The role of the output message. Always `assistant`.\n   */\n  \"role\": OutputMessageRole,\n  /**\n   * The content of the output message.\n   */\n  \"content\": S.Array(OutputMessageContent),\n  /**\n   * The status of the message input. One of `in_progress`, `completed`, or\n   * `incomplete`. Populated when input items are returned via API.\n   */\n  \"status\": OutputMessageStatus\n}) {}\n\n/**\n * The type of the computer tool call output. Always `computer_call_output`.\n */\nexport class ComputerCallOutputItemParamType extends S.Literal(\"computer_call_output\") {}\n\nexport class FunctionCallItemStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * The output of a computer tool call.\n */\nexport class ComputerCallOutputItemParam extends S.Class<ComputerCallOutputItemParam>(\"ComputerCallOutputItemParam\")({\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The ID of the computer tool call that produced the output.\n   */\n  \"call_id\": S.String.pipe(S.minLength(1), S.maxLength(64)),\n  /**\n   * The type of the computer tool call output. Always `computer_call_output`.\n   */\n  \"type\": ComputerCallOutputItemParamType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"computer_call_output\" as const)\n  ),\n  \"output\": ComputerScreenshotImage,\n  \"acknowledged_safety_checks\": S.optionalWith(S.Array(ComputerCallSafetyCheckParam), { nullable: true }),\n  \"status\": S.optionalWith(FunctionCallItemStatus, { nullable: true })\n}) {}\n\n/**\n * The type of the function tool call. Always `function_call`.\n */\nexport class FunctionToolCallType extends S.Literal(\"function_call\") {}\n\n/**\n * The status of the item. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when items are returned via API.\n */\nexport class FunctionToolCallStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * A tool call to run a function. See the\n * [function calling guide](https://platform.openai.com/docs/guides/function-calling) for more information.\n */\nexport class FunctionToolCall extends S.Class<FunctionToolCall>(\"FunctionToolCall\")({\n  /**\n   * The unique ID of the function tool call.\n   */\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The type of the function tool call. Always `function_call`.\n   */\n  \"type\": FunctionToolCallType,\n  /**\n   * The unique ID of the function tool call generated by the model.\n   */\n  \"call_id\": S.String,\n  /**\n   * The name of the function to run.\n   */\n  \"name\": S.String,\n  /**\n   * A JSON string of the arguments to pass to the function.\n   */\n  \"arguments\": S.String,\n  /**\n   * The status of the item. One of `in_progress`, `completed`, or\n   * `incomplete`. Populated when items are returned via API.\n   */\n  \"status\": S.optionalWith(FunctionToolCallStatus, { nullable: true })\n}) {}\n\n/**\n * The type of the function tool call output. Always `function_call_output`.\n */\nexport class FunctionCallOutputItemParamType extends S.Literal(\"function_call_output\") {}\n\n/**\n * The type of the input item. Always `input_text`.\n */\nexport class InputTextContentParamType extends S.Literal(\"input_text\") {}\n\n/**\n * A text input to the model.\n */\nexport class InputTextContentParam extends S.Class<InputTextContentParam>(\"InputTextContentParam\")({\n  /**\n   * The type of the input item. Always `input_text`.\n   */\n  \"type\": InputTextContentParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"input_text\" as const)),\n  /**\n   * The text input to the model.\n   */\n  \"text\": S.String.pipe(S.maxLength(10485760))\n}) {}\n\n/**\n * The type of the input item. Always `input_image`.\n */\nexport class InputImageContentParamAutoParamType extends S.Literal(\"input_image\") {}\n\nexport class DetailEnum extends S.Literal(\"low\", \"high\", \"auto\") {}\n\n/**\n * An image input to the model. Learn about [image inputs](https://platform.openai.com/docs/guides/vision)\n */\nexport class InputImageContentParamAutoParam\n  extends S.Class<InputImageContentParamAutoParam>(\"InputImageContentParamAutoParam\")({\n    /**\n     * The type of the input item. Always `input_image`.\n     */\n    \"type\": InputImageContentParamAutoParamType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"input_image\" as const)\n    ),\n    \"image_url\": S.optionalWith(S.String.pipe(S.maxLength(20971520)), { nullable: true }),\n    \"file_id\": S.optionalWith(S.String, { nullable: true }),\n    \"detail\": S.optionalWith(DetailEnum, { nullable: true })\n  })\n{}\n\n/**\n * The type of the input item. Always `input_file`.\n */\nexport class InputFileContentParamType extends S.Literal(\"input_file\") {}\n\n/**\n * A file input to the model.\n */\nexport class InputFileContentParam extends S.Class<InputFileContentParam>(\"InputFileContentParam\")({\n  /**\n   * The type of the input item. Always `input_file`.\n   */\n  \"type\": InputFileContentParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"input_file\" as const)),\n  \"file_id\": S.optionalWith(S.String, { nullable: true }),\n  \"filename\": S.optionalWith(S.String, { nullable: true }),\n  \"file_data\": S.optionalWith(S.String.pipe(S.maxLength(33554432)), { nullable: true }),\n  \"file_url\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The output of a function tool call.\n */\nexport class FunctionCallOutputItemParam extends S.Class<FunctionCallOutputItemParam>(\"FunctionCallOutputItemParam\")({\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The unique ID of the function tool call generated by the model.\n   */\n  \"call_id\": S.String.pipe(S.minLength(1), S.maxLength(64)),\n  /**\n   * The type of the function tool call output. Always `function_call_output`.\n   */\n  \"type\": FunctionCallOutputItemParamType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"function_call_output\" as const)\n  ),\n  /**\n   * Text, image, or file output of the function tool call.\n   */\n  \"output\": S.Union(\n    /**\n     * A JSON string of the output of the function tool call.\n     */\n    S.String.pipe(S.maxLength(10485760)),\n    S.Array(S.Union(InputTextContentParam, InputImageContentParamAutoParam, InputFileContentParam))\n  ),\n  \"status\": S.optionalWith(FunctionCallItemStatus, { nullable: true })\n}) {}\n\n/**\n * The type of the item. Always `function_shell_call`.\n */\nexport class FunctionShellCallItemParamType extends S.Literal(\"shell_call\") {}\n\n/**\n * Commands and limits describing how to run the function shell tool call.\n */\nexport class FunctionShellActionParam extends S.Class<FunctionShellActionParam>(\"FunctionShellActionParam\")({\n  /**\n   * Ordered shell commands for the execution environment to run.\n   */\n  \"commands\": S.Array(S.String),\n  \"timeout_ms\": S.optionalWith(S.Int, { nullable: true }),\n  \"max_output_length\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * Status values reported for function shell tool calls.\n */\nexport class FunctionShellCallItemStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * A tool representing a request to execute one or more shell commands.\n */\nexport class FunctionShellCallItemParam extends S.Class<FunctionShellCallItemParam>(\"FunctionShellCallItemParam\")({\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The unique ID of the function shell tool call generated by the model.\n   */\n  \"call_id\": S.String.pipe(S.minLength(1), S.maxLength(64)),\n  /**\n   * The type of the item. Always `function_shell_call`.\n   */\n  \"type\": FunctionShellCallItemParamType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"shell_call\" as const)\n  ),\n  /**\n   * The shell commands and limits that describe how to run the tool call.\n   */\n  \"action\": FunctionShellActionParam,\n  \"status\": S.optionalWith(FunctionShellCallItemStatus, { nullable: true })\n}) {}\n\n/**\n * The type of the item. Always `function_shell_call_output`.\n */\nexport class FunctionShellCallOutputItemParamType extends S.Literal(\"shell_call_output\") {}\n\n/**\n * The outcome type. Always `timeout`.\n */\nexport class FunctionShellCallOutputTimeoutOutcomeParamType extends S.Literal(\"timeout\") {}\n\n/**\n * Indicates that the function shell call exceeded its configured time limit.\n */\nexport class FunctionShellCallOutputTimeoutOutcomeParam\n  extends S.Class<FunctionShellCallOutputTimeoutOutcomeParam>(\"FunctionShellCallOutputTimeoutOutcomeParam\")({\n    /**\n     * The outcome type. Always `timeout`.\n     */\n    \"type\": FunctionShellCallOutputTimeoutOutcomeParamType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"timeout\" as const)\n    )\n  })\n{}\n\n/**\n * The outcome type. Always `exit`.\n */\nexport class FunctionShellCallOutputExitOutcomeParamType extends S.Literal(\"exit\") {}\n\n/**\n * Indicates that the shell commands finished and returned an exit code.\n */\nexport class FunctionShellCallOutputExitOutcomeParam\n  extends S.Class<FunctionShellCallOutputExitOutcomeParam>(\"FunctionShellCallOutputExitOutcomeParam\")({\n    /**\n     * The outcome type. Always `exit`.\n     */\n    \"type\": FunctionShellCallOutputExitOutcomeParamType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"exit\" as const)\n    ),\n    /**\n     * The exit code returned by the shell process.\n     */\n    \"exit_code\": S.Int\n  })\n{}\n\n/**\n * The exit or timeout outcome associated with this chunk.\n */\nexport class FunctionShellCallOutputOutcomeParam\n  extends S.Union(FunctionShellCallOutputTimeoutOutcomeParam, FunctionShellCallOutputExitOutcomeParam)\n{}\n\n/**\n * Captured stdout and stderr for a portion of a function shell tool call output.\n */\nexport class FunctionShellCallOutputContentParam\n  extends S.Class<FunctionShellCallOutputContentParam>(\"FunctionShellCallOutputContentParam\")({\n    /**\n     * Captured stdout output for this chunk of the shell call.\n     */\n    \"stdout\": S.String.pipe(S.maxLength(10485760)),\n    /**\n     * Captured stderr output for this chunk of the shell call.\n     */\n    \"stderr\": S.String.pipe(S.maxLength(10485760)),\n    /**\n     * The exit or timeout outcome associated with this chunk.\n     */\n    \"outcome\": FunctionShellCallOutputOutcomeParam\n  })\n{}\n\n/**\n * The streamed output items emitted by a function shell tool call.\n */\nexport class FunctionShellCallOutputItemParam\n  extends S.Class<FunctionShellCallOutputItemParam>(\"FunctionShellCallOutputItemParam\")({\n    \"id\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The unique ID of the function shell tool call generated by the model.\n     */\n    \"call_id\": S.String.pipe(S.minLength(1), S.maxLength(64)),\n    /**\n     * The type of the item. Always `function_shell_call_output`.\n     */\n    \"type\": FunctionShellCallOutputItemParamType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"shell_call_output\" as const)\n    ),\n    /**\n     * Captured chunks of stdout and stderr output, along with their associated outcomes.\n     */\n    \"output\": S.Array(FunctionShellCallOutputContentParam),\n    \"max_output_length\": S.optionalWith(S.Int, { nullable: true })\n  })\n{}\n\n/**\n * The type of the item. Always `apply_patch_call`.\n */\nexport class ApplyPatchToolCallItemParamType extends S.Literal(\"apply_patch_call\") {}\n\n/**\n * Status values reported for apply_patch tool calls.\n */\nexport class ApplyPatchCallStatusParam extends S.Literal(\"in_progress\", \"completed\") {}\n\n/**\n * The operation type. Always `create_file`.\n */\nexport class ApplyPatchCreateFileOperationParamType extends S.Literal(\"create_file\") {}\n\n/**\n * Instruction for creating a new file via the apply_patch tool.\n */\nexport class ApplyPatchCreateFileOperationParam\n  extends S.Class<ApplyPatchCreateFileOperationParam>(\"ApplyPatchCreateFileOperationParam\")({\n    /**\n     * The operation type. Always `create_file`.\n     */\n    \"type\": ApplyPatchCreateFileOperationParamType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"create_file\" as const)\n    ),\n    /**\n     * Path of the file to create relative to the workspace root.\n     */\n    \"path\": S.String.pipe(S.minLength(1)),\n    /**\n     * Unified diff content to apply when creating the file.\n     */\n    \"diff\": S.String.pipe(S.maxLength(10485760))\n  })\n{}\n\n/**\n * The operation type. Always `delete_file`.\n */\nexport class ApplyPatchDeleteFileOperationParamType extends S.Literal(\"delete_file\") {}\n\n/**\n * Instruction for deleting an existing file via the apply_patch tool.\n */\nexport class ApplyPatchDeleteFileOperationParam\n  extends S.Class<ApplyPatchDeleteFileOperationParam>(\"ApplyPatchDeleteFileOperationParam\")({\n    /**\n     * The operation type. Always `delete_file`.\n     */\n    \"type\": ApplyPatchDeleteFileOperationParamType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"delete_file\" as const)\n    ),\n    /**\n     * Path of the file to delete relative to the workspace root.\n     */\n    \"path\": S.String.pipe(S.minLength(1))\n  })\n{}\n\n/**\n * The operation type. Always `update_file`.\n */\nexport class ApplyPatchUpdateFileOperationParamType extends S.Literal(\"update_file\") {}\n\n/**\n * Instruction for updating an existing file via the apply_patch tool.\n */\nexport class ApplyPatchUpdateFileOperationParam\n  extends S.Class<ApplyPatchUpdateFileOperationParam>(\"ApplyPatchUpdateFileOperationParam\")({\n    /**\n     * The operation type. Always `update_file`.\n     */\n    \"type\": ApplyPatchUpdateFileOperationParamType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"update_file\" as const)\n    ),\n    /**\n     * Path of the file to update relative to the workspace root.\n     */\n    \"path\": S.String.pipe(S.minLength(1)),\n    /**\n     * Unified diff content to apply to the existing file.\n     */\n    \"diff\": S.String.pipe(S.maxLength(10485760))\n  })\n{}\n\n/**\n * One of the create_file, delete_file, or update_file operations supplied to the apply_patch tool.\n */\nexport class ApplyPatchOperationParam extends S.Union(\n  ApplyPatchCreateFileOperationParam,\n  ApplyPatchDeleteFileOperationParam,\n  ApplyPatchUpdateFileOperationParam\n) {}\n\n/**\n * A tool call representing a request to create, delete, or update files using diff patches.\n */\nexport class ApplyPatchToolCallItemParam extends S.Class<ApplyPatchToolCallItemParam>(\"ApplyPatchToolCallItemParam\")({\n  /**\n   * The type of the item. Always `apply_patch_call`.\n   */\n  \"type\": ApplyPatchToolCallItemParamType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"apply_patch_call\" as const)\n  ),\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The unique ID of the apply patch tool call generated by the model.\n   */\n  \"call_id\": S.String.pipe(S.minLength(1), S.maxLength(64)),\n  /**\n   * The status of the apply patch tool call. One of `in_progress` or `completed`.\n   */\n  \"status\": ApplyPatchCallStatusParam,\n  /**\n   * The specific create, delete, or update instruction for the apply_patch tool call.\n   */\n  \"operation\": ApplyPatchOperationParam\n}) {}\n\n/**\n * The type of the item. Always `apply_patch_call_output`.\n */\nexport class ApplyPatchToolCallOutputItemParamType extends S.Literal(\"apply_patch_call_output\") {}\n\n/**\n * Outcome values reported for apply_patch tool call outputs.\n */\nexport class ApplyPatchCallOutputStatusParam extends S.Literal(\"completed\", \"failed\") {}\n\n/**\n * The streamed output emitted by an apply patch tool call.\n */\nexport class ApplyPatchToolCallOutputItemParam\n  extends S.Class<ApplyPatchToolCallOutputItemParam>(\"ApplyPatchToolCallOutputItemParam\")({\n    /**\n     * The type of the item. Always `apply_patch_call_output`.\n     */\n    \"type\": ApplyPatchToolCallOutputItemParamType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"apply_patch_call_output\" as const)\n    ),\n    \"id\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The unique ID of the apply patch tool call generated by the model.\n     */\n    \"call_id\": S.String.pipe(S.minLength(1), S.maxLength(64)),\n    /**\n     * The status of the apply patch tool call output. One of `completed` or `failed`.\n     */\n    \"status\": ApplyPatchCallOutputStatusParam,\n    \"output\": S.optionalWith(S.String.pipe(S.maxLength(10485760)), { nullable: true })\n  })\n{}\n\n/**\n * The type of the item. Always `mcp_approval_response`.\n */\nexport class MCPApprovalResponseType extends S.Literal(\"mcp_approval_response\") {}\n\n/**\n * A response to an MCP approval request.\n */\nexport class MCPApprovalResponse extends S.Class<MCPApprovalResponse>(\"MCPApprovalResponse\")({\n  /**\n   * The type of the item. Always `mcp_approval_response`.\n   */\n  \"type\": MCPApprovalResponseType,\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The ID of the approval request being answered.\n   */\n  \"approval_request_id\": S.String,\n  /**\n   * Whether the request was approved.\n   */\n  \"approve\": S.Boolean,\n  \"reason\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Content item used to generate a response.\n */\nexport class Item extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * The type of item to reference. Always `item_reference`.\n */\nexport class ItemReferenceParamTypeEnum extends S.Literal(\"item_reference\") {}\n\n/**\n * An internal identifier for an item to reference.\n */\nexport class ItemReferenceParam extends S.Class<ItemReferenceParam>(\"ItemReferenceParam\")({\n  \"type\": S.optionalWith(ItemReferenceParamTypeEnum, { nullable: true }),\n  /**\n   * The ID of the item to reference.\n   */\n  \"id\": S.String\n}) {}\n\nexport class InputItem extends S.Union(\n  EasyInputMessage,\n  /**\n   * An item representing part of the context for the response to be\n   * generated by the model. Can contain text, images, and audio inputs,\n   * as well as previous assistant responses and tool call outputs.\n   */\n  S.Record({ key: S.String, value: S.Unknown }),\n  ItemReferenceParam\n) {}\n\nexport class CreateConversationItemsRequest\n  extends S.Class<CreateConversationItemsRequest>(\"CreateConversationItemsRequest\")({\n    /**\n     * The items to add to the conversation. You may add up to 20 items at a time.\n     */\n    \"items\": S.Array(InputItem).pipe(S.maxItems(20))\n  })\n{}\n\nexport class GetConversationItemParams extends S.Struct({\n  \"include\": S.optionalWith(S.Array(IncludeEnum), { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `conversation`.\n */\nexport class ConversationResourceObject extends S.Literal(\"conversation\") {}\n\nexport class ConversationResource extends S.Class<ConversationResource>(\"ConversationResource\")({\n  /**\n   * The unique ID of the conversation.\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `conversation`.\n   */\n  \"object\": ConversationResourceObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"conversation\" as const)\n  ),\n  /**\n   * The time at which the conversation was created, measured in seconds since the Unix epoch.\n   */\n  \"created_at\": S.Int\n}) {}\n\nexport class CreateEmbeddingRequestModelEnum\n  extends S.Literal(\"text-embedding-ada-002\", \"text-embedding-3-small\", \"text-embedding-3-large\")\n{}\n\n/**\n * The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/).\n */\nexport class CreateEmbeddingRequestEncodingFormat extends S.Literal(\"float\", \"base64\") {}\n\nexport class CreateEmbeddingRequest extends S.Class<CreateEmbeddingRequest>(\"CreateEmbeddingRequest\")({\n  /**\n   * Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for all embedding models), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. In addition to the per-input token limit, all embedding  models enforce a maximum of 300,000 tokens summed across all inputs in a  single request.\n   */\n  \"input\": S.Union(\n    /**\n     * The string that will be turned into an embedding.\n     */\n    S.String,\n    /**\n     * The array of strings that will be turned into an embedding.\n     */\n    S.NonEmptyArray(S.String).pipe(S.minItems(1), S.maxItems(2048)),\n    /**\n     * The array of integers that will be turned into an embedding.\n     */\n    S.NonEmptyArray(S.Int).pipe(S.minItems(1), S.maxItems(2048)),\n    /**\n     * The array of arrays containing integers that will be turned into an embedding.\n     */\n    S.NonEmptyArray(S.NonEmptyArray(S.Int).pipe(S.minItems(1))).pipe(S.minItems(1), S.maxItems(2048))\n  ),\n  /**\n   * ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](https://platform.openai.com/docs/models) for descriptions of them.\n   */\n  \"model\": S.Union(S.String, CreateEmbeddingRequestModelEnum),\n  /**\n   * The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/).\n   */\n  \"encoding_format\": S.optionalWith(CreateEmbeddingRequestEncodingFormat, {\n    nullable: true,\n    default: () => \"float\" as const\n  }),\n  /**\n   * The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models.\n   */\n  \"dimensions\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true }),\n  /**\n   * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n   */\n  \"user\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always \"embedding\".\n */\nexport class EmbeddingObject extends S.Literal(\"embedding\") {}\n\n/**\n * Represents an embedding vector returned by embedding endpoint.\n */\nexport class Embedding extends S.Class<Embedding>(\"Embedding\")({\n  /**\n   * The index of the embedding in the list of embeddings.\n   */\n  \"index\": S.Int,\n  /**\n   * The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](https://platform.openai.com/docs/guides/embeddings).\n   */\n  \"embedding\": S.Array(S.Number),\n  /**\n   * The object type, which is always \"embedding\".\n   */\n  \"object\": EmbeddingObject\n}) {}\n\n/**\n * The object type, which is always \"list\".\n */\nexport class CreateEmbeddingResponseObject extends S.Literal(\"list\") {}\n\nexport class CreateEmbeddingResponse extends S.Class<CreateEmbeddingResponse>(\"CreateEmbeddingResponse\")({\n  /**\n   * The list of embeddings generated by the model.\n   */\n  \"data\": S.Array(Embedding),\n  /**\n   * The name of the model used to generate the embedding.\n   */\n  \"model\": S.String,\n  /**\n   * The object type, which is always \"list\".\n   */\n  \"object\": CreateEmbeddingResponseObject,\n  /**\n   * The usage information for the request.\n   */\n  \"usage\": S.Struct({\n    /**\n     * The number of tokens used by the prompt.\n     */\n    \"prompt_tokens\": S.Int,\n    /**\n     * The total number of tokens used by the request.\n     */\n    \"total_tokens\": S.Int\n  })\n}) {}\n\nexport class ListEvalsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListEvalsParamsOrderBy extends S.Literal(\"created_at\", \"updated_at\") {}\n\nexport class ListEvalsParams extends S.Struct({\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListEvalsParamsOrder, { nullable: true, default: () => \"asc\" as const }),\n  \"order_by\": S.optionalWith(ListEvalsParamsOrderBy, { nullable: true, default: () => \"created_at\" as const })\n}) {}\n\n/**\n * The type of this object. It is always set to \"list\".\n */\nexport class EvalListObject extends S.Literal(\"list\") {}\n\n/**\n * The object type.\n */\nexport class EvalObject extends S.Literal(\"eval\") {}\n\n/**\n * The type of data source. Always `custom`.\n */\nexport class EvalCustomDataSourceConfigType extends S.Literal(\"custom\") {}\n\n/**\n * A CustomDataSourceConfig which specifies the schema of your `item` and optionally `sample` namespaces.\n * The response schema defines the shape of the data that will be:\n * - Used to define your testing criteria and\n * - What data is required when creating a run\n */\nexport class EvalCustomDataSourceConfig extends S.Class<EvalCustomDataSourceConfig>(\"EvalCustomDataSourceConfig\")({\n  /**\n   * The type of data source. Always `custom`.\n   */\n  \"type\": EvalCustomDataSourceConfigType.pipe(S.propertySignature, S.withConstructorDefault(() => \"custom\" as const)),\n  /**\n   * The json schema for the run data source items.\n   * Learn how to build JSON schemas [here](https://json-schema.org/).\n   */\n  \"schema\": S.Record({ key: S.String, value: S.Unknown })\n}) {}\n\n/**\n * The type of data source. Always `logs`.\n */\nexport class EvalLogsDataSourceConfigType extends S.Literal(\"logs\") {}\n\n/**\n * A LogsDataSourceConfig which specifies the metadata property of your logs query.\n * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc.\n * The schema returned by this data source config is used to defined what variables are available in your evals.\n * `item` and `sample` are both defined when using this data source config.\n */\nexport class EvalLogsDataSourceConfig extends S.Class<EvalLogsDataSourceConfig>(\"EvalLogsDataSourceConfig\")({\n  /**\n   * The type of data source. Always `logs`.\n   */\n  \"type\": EvalLogsDataSourceConfigType.pipe(S.propertySignature, S.withConstructorDefault(() => \"logs\" as const)),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * The json schema for the run data source items.\n   * Learn how to build JSON schemas [here](https://json-schema.org/).\n   */\n  \"schema\": S.Record({ key: S.String, value: S.Unknown })\n}) {}\n\n/**\n * The type of data source. Always `stored_completions`.\n */\nexport class EvalStoredCompletionsDataSourceConfigType extends S.Literal(\"stored_completions\") {}\n\n/**\n * Deprecated in favor of LogsDataSourceConfig.\n */\nexport class EvalStoredCompletionsDataSourceConfig\n  extends S.Class<EvalStoredCompletionsDataSourceConfig>(\"EvalStoredCompletionsDataSourceConfig\")({\n    /**\n     * The type of data source. Always `stored_completions`.\n     */\n    \"type\": EvalStoredCompletionsDataSourceConfigType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"stored_completions\" as const)\n    ),\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n    /**\n     * The json schema for the run data source items.\n     * Learn how to build JSON schemas [here](https://json-schema.org/).\n     */\n    \"schema\": S.Record({ key: S.String, value: S.Unknown })\n  })\n{}\n\n/**\n * The object type, which is always `label_model`.\n */\nexport class EvalGraderLabelModelType extends S.Literal(\"label_model\") {}\n\n/**\n * The role of the message input. One of `user`, `assistant`, `system`, or\n * `developer`.\n */\nexport class EvalItemRole extends S.Literal(\"user\", \"assistant\", \"system\", \"developer\") {}\n\n/**\n * The type of the image input. Always `input_image`.\n */\nexport class EvalItemContentEnumType extends S.Literal(\"input_image\") {}\n\n/**\n * The type of the input item. Always `input_audio`.\n */\nexport class InputAudioType extends S.Literal(\"input_audio\") {}\n\n/**\n * The format of the audio data. Currently supported formats are `mp3` and\n * `wav`.\n */\nexport class InputAudioInputAudioFormat extends S.Literal(\"mp3\", \"wav\") {}\n\n/**\n * An audio input to the model.\n */\nexport class InputAudio extends S.Class<InputAudio>(\"InputAudio\")({\n  /**\n   * The type of the input item. Always `input_audio`.\n   */\n  \"type\": InputAudioType,\n  \"input_audio\": S.Struct({\n    /**\n     * Base64-encoded audio data.\n     */\n    \"data\": S.String,\n    /**\n     * The format of the audio data. Currently supported formats are `mp3` and\n     * `wav`.\n     */\n    \"format\": InputAudioInputAudioFormat\n  })\n}) {}\n\n/**\n * The type of the message input. Always `message`.\n */\nexport class EvalItemType extends S.Literal(\"message\") {}\n\n/**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role. Messages with the\n * `assistant` role are presumed to have been generated by the model in previous\n * interactions.\n */\nexport class EvalItem extends S.Class<EvalItem>(\"EvalItem\")({\n  /**\n   * The role of the message input. One of `user`, `assistant`, `system`, or\n   * `developer`.\n   */\n  \"role\": EvalItemRole,\n  /**\n   * Inputs to the model - can contain template strings.\n   */\n  \"content\": S.Union(\n    /**\n     * A text input to the model.\n     */\n    S.String,\n    InputTextContent,\n    /**\n     * A text output from the model.\n     */\n    S.Struct({\n      /**\n       * The type of the output text. Always `output_text`.\n       */\n      \"type\": EvalItemContentEnumType,\n      /**\n       * The text output from the model.\n       */\n      \"text\": S.String\n    }),\n    /**\n     * An image input to the model.\n     */\n    S.Struct({\n      /**\n       * The type of the image input. Always `input_image`.\n       */\n      \"type\": EvalItemContentEnumType,\n      /**\n       * The URL of the image input.\n       */\n      \"image_url\": S.String,\n      /**\n       * The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`.\n       */\n      \"detail\": S.optionalWith(S.String, { nullable: true })\n    }),\n    InputAudio\n  ),\n  /**\n   * The type of the message input. Always `message`.\n   */\n  \"type\": S.optionalWith(EvalItemType, { nullable: true })\n}) {}\n\n/**\n * A LabelModelGrader object which uses a model to assign labels to each item\n * in the evaluation.\n */\nexport class EvalGraderLabelModel extends S.Class<EvalGraderLabelModel>(\"EvalGraderLabelModel\")({\n  /**\n   * The object type, which is always `label_model`.\n   */\n  \"type\": EvalGraderLabelModelType,\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The model to use for the evaluation. Must support structured outputs.\n   */\n  \"model\": S.String,\n  \"input\": S.Array(EvalItem),\n  /**\n   * The labels to assign to each item in the evaluation.\n   */\n  \"labels\": S.Array(S.String),\n  /**\n   * The labels that indicate a passing result. Must be a subset of labels.\n   */\n  \"passing_labels\": S.Array(S.String)\n}) {}\n\n/**\n * The object type, which is always `string_check`.\n */\nexport class EvalGraderStringCheckType extends S.Literal(\"string_check\") {}\n\n/**\n * The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`.\n */\nexport class EvalGraderStringCheckOperation extends S.Literal(\"eq\", \"ne\", \"like\", \"ilike\") {}\n\n/**\n * A StringCheckGrader object that performs a string comparison between input and reference using a specified operation.\n */\nexport class EvalGraderStringCheck extends S.Class<EvalGraderStringCheck>(\"EvalGraderStringCheck\")({\n  /**\n   * The object type, which is always `string_check`.\n   */\n  \"type\": EvalGraderStringCheckType,\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The input text. This may include template strings.\n   */\n  \"input\": S.String,\n  /**\n   * The reference text. This may include template strings.\n   */\n  \"reference\": S.String,\n  /**\n   * The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`.\n   */\n  \"operation\": EvalGraderStringCheckOperation\n}) {}\n\n/**\n * The type of grader.\n */\nexport class EvalGraderTextSimilarityType extends S.Literal(\"text_similarity\") {}\n\n/**\n * The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`,\n * `gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`,\n * or `rouge_l`.\n */\nexport class EvalGraderTextSimilarityEvaluationMetric extends S.Literal(\n  \"cosine\",\n  \"fuzzy_match\",\n  \"bleu\",\n  \"gleu\",\n  \"meteor\",\n  \"rouge_1\",\n  \"rouge_2\",\n  \"rouge_3\",\n  \"rouge_4\",\n  \"rouge_5\",\n  \"rouge_l\"\n) {}\n\n/**\n * A TextSimilarityGrader object which grades text based on similarity metrics.\n */\nexport class EvalGraderTextSimilarity extends S.Class<EvalGraderTextSimilarity>(\"EvalGraderTextSimilarity\")({\n  /**\n   * The threshold for the score.\n   */\n  \"pass_threshold\": S.Number,\n  /**\n   * The type of grader.\n   */\n  \"type\": EvalGraderTextSimilarityType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"text_similarity\" as const)\n  ),\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The text being graded.\n   */\n  \"input\": S.String,\n  /**\n   * The text being graded against.\n   */\n  \"reference\": S.String,\n  /**\n   * The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`,\n   * `gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`,\n   * or `rouge_l`.\n   */\n  \"evaluation_metric\": EvalGraderTextSimilarityEvaluationMetric\n}) {}\n\n/**\n * The object type, which is always `python`.\n */\nexport class EvalGraderPythonType extends S.Literal(\"python\") {}\n\n/**\n * A PythonGrader object that runs a python script on the input.\n */\nexport class EvalGraderPython extends S.Class<EvalGraderPython>(\"EvalGraderPython\")({\n  /**\n   * The threshold for the score.\n   */\n  \"pass_threshold\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * The object type, which is always `python`.\n   */\n  \"type\": EvalGraderPythonType,\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The source code of the python script.\n   */\n  \"source\": S.String,\n  /**\n   * The image tag to use for the python script.\n   */\n  \"image_tag\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `score_model`.\n */\nexport class EvalGraderScoreModelType extends S.Literal(\"score_model\") {}\n\n/**\n * A ScoreModelGrader object that uses a model to assign a score to the input.\n */\nexport class EvalGraderScoreModel extends S.Class<EvalGraderScoreModel>(\"EvalGraderScoreModel\")({\n  /**\n   * The threshold for the score.\n   */\n  \"pass_threshold\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * The object type, which is always `score_model`.\n   */\n  \"type\": EvalGraderScoreModelType,\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The model to use for the evaluation.\n   */\n  \"model\": S.String,\n  /**\n   * The sampling parameters for the model.\n   */\n  \"sampling_params\": S.optionalWith(\n    S.Struct({\n      \"seed\": S.optionalWith(S.Int, { nullable: true }),\n      \"top_p\": S.optionalWith(S.Number, { nullable: true }),\n      \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n      \"max_completions_tokens\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true }),\n      \"reasoning_effort\": S.optionalWith(S.Literal(\"none\", \"minimal\", \"low\", \"medium\", \"high\"), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The input text. This may include template strings.\n   */\n  \"input\": S.Array(EvalItem),\n  /**\n   * The range of the score. Defaults to `[0, 1]`.\n   */\n  \"range\": S.optionalWith(S.Array(S.Number), { nullable: true })\n}) {}\n\n/**\n * An Eval object with a data source config and testing criteria.\n * An Eval represents a task to be done for your LLM integration.\n * Like:\n *  - Improve the quality of my chatbot\n *  - See how well my chatbot handles customer support\n *  - Check if o4-mini is better at my usecase than gpt-4o\n */\nexport class Eval extends S.Class<Eval>(\"Eval\")({\n  /**\n   * The object type.\n   */\n  \"object\": EvalObject.pipe(S.propertySignature, S.withConstructorDefault(() => \"eval\" as const)),\n  /**\n   * Unique identifier for the evaluation.\n   */\n  \"id\": S.String,\n  /**\n   * The name of the evaluation.\n   */\n  \"name\": S.String,\n  /**\n   * Configuration of data sources used in runs of the evaluation.\n   */\n  \"data_source_config\": S.Record({ key: S.String, value: S.Unknown }),\n  /**\n   * A list of testing criteria.\n   */\n  \"testing_criteria\": S.Array(\n    S.Union(\n      EvalGraderLabelModel,\n      EvalGraderStringCheck,\n      EvalGraderTextSimilarity,\n      EvalGraderPython,\n      EvalGraderScoreModel\n    )\n  ),\n  /**\n   * The Unix timestamp (in seconds) for when the eval was created.\n   */\n  \"created_at\": S.Int,\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown }))\n}) {}\n\n/**\n * An object representing a list of evals.\n */\nexport class EvalList extends S.Class<EvalList>(\"EvalList\")({\n  /**\n   * The type of this object. It is always set to \"list\".\n   */\n  \"object\": EvalListObject.pipe(S.propertySignature, S.withConstructorDefault(() => \"list\" as const)),\n  /**\n   * An array of eval objects.\n   */\n  \"data\": S.Array(Eval),\n  /**\n   * The identifier of the first eval in the data array.\n   */\n  \"first_id\": S.String,\n  /**\n   * The identifier of the last eval in the data array.\n   */\n  \"last_id\": S.String,\n  /**\n   * Indicates whether there are more evals available.\n   */\n  \"has_more\": S.Boolean\n}) {}\n\n/**\n * The type of data source. Always `custom`.\n */\nexport class CreateEvalCustomDataSourceConfigType extends S.Literal(\"custom\") {}\n\n/**\n * A CustomDataSourceConfig object that defines the schema for the data source used for the evaluation runs.\n * This schema is used to define the shape of the data that will be:\n * - Used to define your testing criteria and\n * - What data is required when creating a run\n */\nexport class CreateEvalCustomDataSourceConfig\n  extends S.Class<CreateEvalCustomDataSourceConfig>(\"CreateEvalCustomDataSourceConfig\")({\n    /**\n     * The type of data source. Always `custom`.\n     */\n    \"type\": CreateEvalCustomDataSourceConfigType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"custom\" as const)\n    ),\n    /**\n     * The json schema for each row in the data source.\n     */\n    \"item_schema\": S.Record({ key: S.String, value: S.Unknown }),\n    /**\n     * Whether the eval should expect you to populate the sample namespace (ie, by generating responses off of your data source)\n     */\n    \"include_sample_schema\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const })\n  })\n{}\n\n/**\n * The type of data source. Always `logs`.\n */\nexport class CreateEvalLogsDataSourceConfigType extends S.Literal(\"logs\") {}\n\n/**\n * A data source config which specifies the metadata property of your logs query.\n * This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, etc.\n */\nexport class CreateEvalLogsDataSourceConfig\n  extends S.Class<CreateEvalLogsDataSourceConfig>(\"CreateEvalLogsDataSourceConfig\")({\n    /**\n     * The type of data source. Always `logs`.\n     */\n    \"type\": CreateEvalLogsDataSourceConfigType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"logs\" as const)\n    ),\n    /**\n     * Metadata filters for the logs data source.\n     */\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * The type of data source. Always `stored_completions`.\n */\nexport class CreateEvalStoredCompletionsDataSourceConfigType extends S.Literal(\"stored_completions\") {}\n\n/**\n * Deprecated in favor of LogsDataSourceConfig.\n */\nexport class CreateEvalStoredCompletionsDataSourceConfig\n  extends S.Class<CreateEvalStoredCompletionsDataSourceConfig>(\"CreateEvalStoredCompletionsDataSourceConfig\")({\n    /**\n     * The type of data source. Always `stored_completions`.\n     */\n    \"type\": CreateEvalStoredCompletionsDataSourceConfigType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"stored_completions\" as const)\n    ),\n    /**\n     * Metadata filters for the stored completions data source.\n     */\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * The object type, which is always `label_model`.\n */\nexport class CreateEvalLabelModelGraderType extends S.Literal(\"label_model\") {}\n\n/**\n * A chat message that makes up the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.\n */\nexport class CreateEvalItem extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * A LabelModelGrader object which uses a model to assign labels to each item\n * in the evaluation.\n */\nexport class CreateEvalLabelModelGrader extends S.Class<CreateEvalLabelModelGrader>(\"CreateEvalLabelModelGrader\")({\n  /**\n   * The object type, which is always `label_model`.\n   */\n  \"type\": CreateEvalLabelModelGraderType,\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The model to use for the evaluation. Must support structured outputs.\n   */\n  \"model\": S.String,\n  /**\n   * A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.\n   */\n  \"input\": S.Array(CreateEvalItem),\n  /**\n   * The labels to classify to each item in the evaluation.\n   */\n  \"labels\": S.Array(S.String),\n  /**\n   * The labels that indicate a passing result. Must be a subset of labels.\n   */\n  \"passing_labels\": S.Array(S.String)\n}) {}\n\nexport class CreateEvalRequest extends S.Class<CreateEvalRequest>(\"CreateEvalRequest\")({\n  /**\n   * The name of the evaluation.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * The configuration for the data source used for the evaluation runs. Dictates the schema of the data used in the evaluation.\n   */\n  \"data_source_config\": S.Record({ key: S.String, value: S.Unknown }),\n  /**\n   * A list of graders for all eval runs in this group. Graders can reference variables in the data source using double curly braces notation, like `{{item.variable_name}}`. To reference the model's output, use the `sample` namespace (ie, `{{sample.output_text}}`).\n   */\n  \"testing_criteria\": S.Array(\n    S.Union(\n      CreateEvalLabelModelGrader,\n      EvalGraderStringCheck,\n      EvalGraderTextSimilarity,\n      EvalGraderPython,\n      EvalGraderScoreModel\n    )\n  )\n}) {}\n\nexport class UpdateEvalRequest extends S.Class<UpdateEvalRequest>(\"UpdateEvalRequest\")({\n  /**\n   * Rename the evaluation.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class DeleteEval200 extends S.Struct({\n  \"object\": S.String,\n  \"deleted\": S.Boolean,\n  \"eval_id\": S.String\n}) {}\n\nexport class Error extends S.Class<Error>(\"Error\")({\n  \"code\": S.NullOr(S.String),\n  \"message\": S.String,\n  \"param\": S.NullOr(S.String),\n  \"type\": S.String\n}) {}\n\nexport class GetEvalRunsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class GetEvalRunsParamsStatus extends S.Literal(\"queued\", \"in_progress\", \"completed\", \"canceled\", \"failed\") {}\n\nexport class GetEvalRunsParams extends S.Struct({\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(GetEvalRunsParamsOrder, { nullable: true, default: () => \"asc\" as const }),\n  \"status\": S.optionalWith(GetEvalRunsParamsStatus, { nullable: true })\n}) {}\n\n/**\n * The type of this object. It is always set to \"list\".\n */\nexport class EvalRunListObject extends S.Literal(\"list\") {}\n\n/**\n * The type of the object. Always \"eval.run\".\n */\nexport class EvalRunObject extends S.Literal(\"eval.run\") {}\n\n/**\n * The type of data source. Always `jsonl`.\n */\nexport class CreateEvalJsonlRunDataSourceType extends S.Literal(\"jsonl\") {}\n\n/**\n * The type of jsonl source. Always `file_content`.\n */\nexport class EvalJsonlFileContentSourceType extends S.Literal(\"file_content\") {}\n\nexport class EvalJsonlFileContentSource extends S.Class<EvalJsonlFileContentSource>(\"EvalJsonlFileContentSource\")({\n  /**\n   * The type of jsonl source. Always `file_content`.\n   */\n  \"type\": EvalJsonlFileContentSourceType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"file_content\" as const)\n  ),\n  /**\n   * The content of the jsonl file.\n   */\n  \"content\": S.Array(S.Struct({\n    \"item\": S.Record({ key: S.String, value: S.Unknown }),\n    \"sample\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  }))\n}) {}\n\n/**\n * The type of jsonl source. Always `file_id`.\n */\nexport class EvalJsonlFileIdSourceType extends S.Literal(\"file_id\") {}\n\nexport class EvalJsonlFileIdSource extends S.Class<EvalJsonlFileIdSource>(\"EvalJsonlFileIdSource\")({\n  /**\n   * The type of jsonl source. Always `file_id`.\n   */\n  \"type\": EvalJsonlFileIdSourceType.pipe(S.propertySignature, S.withConstructorDefault(() => \"file_id\" as const)),\n  /**\n   * The identifier of the file.\n   */\n  \"id\": S.String\n}) {}\n\n/**\n * A JsonlRunDataSource object with that specifies a JSONL file that matches the eval\n */\nexport class CreateEvalJsonlRunDataSource\n  extends S.Class<CreateEvalJsonlRunDataSource>(\"CreateEvalJsonlRunDataSource\")({\n    /**\n     * The type of data source. Always `jsonl`.\n     */\n    \"type\": CreateEvalJsonlRunDataSourceType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"jsonl\" as const)\n    ),\n    /**\n     * Determines what populates the `item` namespace in the data source.\n     */\n    \"source\": S.Union(EvalJsonlFileContentSource, EvalJsonlFileIdSource)\n  })\n{}\n\n/**\n * The type of run data source. Always `completions`.\n */\nexport class CreateEvalCompletionsRunDataSourceType extends S.Literal(\"completions\") {}\n\n/**\n * The type of input messages. Always `item_reference`.\n */\nexport class CreateEvalCompletionsRunDataSourceInputMessagesEnumType extends S.Literal(\"item_reference\") {}\n\n/**\n * The type of source. Always `stored_completions`.\n */\nexport class EvalStoredCompletionsSourceType extends S.Literal(\"stored_completions\") {}\n\n/**\n * A StoredCompletionsRunDataSource configuration describing a set of filters\n */\nexport class EvalStoredCompletionsSource extends S.Class<EvalStoredCompletionsSource>(\"EvalStoredCompletionsSource\")({\n  /**\n   * The type of source. Always `stored_completions`.\n   */\n  \"type\": EvalStoredCompletionsSourceType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"stored_completions\" as const)\n  ),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"model\": S.optionalWith(S.String, { nullable: true }),\n  \"created_after\": S.optionalWith(S.Int, { nullable: true }),\n  \"created_before\": S.optionalWith(S.Int, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * A CompletionsRunDataSource object describing a model sampling configuration.\n */\nexport class CreateEvalCompletionsRunDataSource\n  extends S.Class<CreateEvalCompletionsRunDataSource>(\"CreateEvalCompletionsRunDataSource\")({\n    /**\n     * The type of run data source. Always `completions`.\n     */\n    \"type\": CreateEvalCompletionsRunDataSourceType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"completions\" as const)\n    ),\n    /**\n     * Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace.\n     */\n    \"input_messages\": S.optionalWith(\n      S.Union(\n        S.Struct({\n          /**\n           * The type of input messages. Always `template`.\n           */\n          \"type\": CreateEvalCompletionsRunDataSourceInputMessagesEnumType,\n          /**\n           * A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.\n           */\n          \"template\": S.Array(S.Union(EasyInputMessage, EvalItem))\n        }),\n        S.Struct({\n          /**\n           * The type of input messages. Always `item_reference`.\n           */\n          \"type\": CreateEvalCompletionsRunDataSourceInputMessagesEnumType,\n          /**\n           * A reference to a variable in the `item` namespace. Ie, \"item.input_trajectory\"\n           */\n          \"item_reference\": S.String\n        })\n      ),\n      { nullable: true }\n    ),\n    \"sampling_params\": S.optionalWith(\n      S.Struct({\n        \"reasoning_effort\": S.optionalWith(S.Literal(\"none\", \"minimal\", \"low\", \"medium\", \"high\"), { nullable: true }),\n        /**\n         * A higher temperature increases randomness in the outputs.\n         */\n        \"temperature\": S.optionalWith(S.Number, { nullable: true, default: () => 1 as const }),\n        /**\n         * The maximum number of tokens in the generated output.\n         */\n        \"max_completion_tokens\": S.optionalWith(S.Int, { nullable: true }),\n        /**\n         * An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n         */\n        \"top_p\": S.optionalWith(S.Number, { nullable: true, default: () => 1 as const }),\n        /**\n         * A seed value to initialize the randomness, during sampling.\n         */\n        \"seed\": S.optionalWith(S.Int, { nullable: true, default: () => 42 as const }),\n        /**\n         * An object specifying the format that the model must output.\n         *\n         * Setting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables\n         * Structured Outputs which ensures the model will match your supplied JSON\n         * schema. Learn more in the [Structured Outputs\n         * guide](https://platform.openai.com/docs/guides/structured-outputs).\n         *\n         * Setting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\n         * ensures the message the model generates is valid JSON. Using `json_schema`\n         * is preferred for models that support it.\n         */\n        \"response_format\": S.optionalWith(\n          S.Union(ResponseFormatText, ResponseFormatJsonSchema, ResponseFormatJsonObject),\n          { nullable: true }\n        ),\n        /**\n         * A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.\n         */\n        \"tools\": S.optionalWith(S.Array(ChatCompletionTool), { nullable: true })\n      }),\n      { nullable: true }\n    ),\n    /**\n     * The name of the model to use for generating completions (e.g. \"o3-mini\").\n     */\n    \"model\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Determines what populates the `item` namespace in this run's data source.\n     */\n    \"source\": S.Union(EvalJsonlFileContentSource, EvalJsonlFileIdSource, EvalStoredCompletionsSource)\n  })\n{}\n\n/**\n * The type of run data source. Always `responses`.\n */\nexport class CreateEvalResponsesRunDataSourceType extends S.Literal(\"responses\") {}\n\n/**\n * The type of input messages. Always `item_reference`.\n */\nexport class CreateEvalResponsesRunDataSourceInputMessagesEnumType extends S.Literal(\"item_reference\") {}\n\n/**\n * The type of the function tool. Always `function`.\n */\nexport class FunctionToolType extends S.Literal(\"function\") {}\n\n/**\n * Defines a function in your own code the model can choose to call. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling).\n */\nexport class FunctionTool extends S.Class<FunctionTool>(\"FunctionTool\")({\n  /**\n   * The type of the function tool. Always `function`.\n   */\n  \"type\": FunctionToolType.pipe(S.propertySignature, S.withConstructorDefault(() => \"function\" as const)),\n  /**\n   * The name of the function to call.\n   */\n  \"name\": S.String,\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  \"parameters\": S.NullOr(S.Record({ key: S.String, value: S.Unknown })),\n  \"strict\": S.NullOr(S.Boolean)\n}) {}\n\n/**\n * The type of the file search tool. Always `file_search`.\n */\nexport class FileSearchToolType extends S.Literal(\"file_search\") {}\n\nexport class RankerVersionType extends S.Literal(\"auto\", \"default-2024-11-15\") {}\n\nexport class HybridSearchOptions extends S.Class<HybridSearchOptions>(\"HybridSearchOptions\")({\n  /**\n   * The weight of the embedding in the reciprocal ranking fusion.\n   */\n  \"embedding_weight\": S.Number,\n  /**\n   * The weight of the text in the reciprocal ranking fusion.\n   */\n  \"text_weight\": S.Number\n}) {}\n\nexport class RankingOptions extends S.Class<RankingOptions>(\"RankingOptions\")({\n  /**\n   * The ranker to use for the file search.\n   */\n  \"ranker\": S.optionalWith(RankerVersionType, { nullable: true }),\n  /**\n   * The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results.\n   */\n  \"score_threshold\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Weights that control how reciprocal rank fusion balances semantic embedding matches versus sparse keyword matches when hybrid search is enabled.\n   */\n  \"hybrid_search\": S.optionalWith(HybridSearchOptions, { nullable: true })\n}) {}\n\n/**\n * Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`.\n * - `eq`: equals\n * - `ne`: not equal\n * - `gt`: greater than\n * - `gte`: greater than or equal\n * - `lt`: less than\n * - `lte`: less than or equal\n * - `in`: in\n * - `nin`: not in\n */\nexport class ComparisonFilterType extends S.Literal(\"eq\", \"ne\", \"gt\", \"gte\", \"lt\", \"lte\") {}\n\nexport class ComparisonFilterValueItems extends S.Union(S.String, S.Number) {}\n\n/**\n * A filter used to compare a specified attribute key to a given value using a defined comparison operation.\n */\nexport class ComparisonFilter extends S.Class<ComparisonFilter>(\"ComparisonFilter\")({\n  /**\n   * Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`.\n   * - `eq`: equals\n   * - `ne`: not equal\n   * - `gt`: greater than\n   * - `gte`: greater than or equal\n   * - `lt`: less than\n   * - `lte`: less than or equal\n   * - `in`: in\n   * - `nin`: not in\n   */\n  \"type\": ComparisonFilterType.pipe(S.propertySignature, S.withConstructorDefault(() => \"eq\" as const)),\n  /**\n   * The key to compare against the value.\n   */\n  \"key\": S.String,\n  /**\n   * The value to compare against the attribute key; supports string, number, or boolean types.\n   */\n  \"value\": S.Union(S.String, S.Number, S.Boolean, S.Array(ComparisonFilterValueItems))\n}) {}\n\n/**\n * Type of operation: `and` or `or`.\n */\nexport class CompoundFilterType extends S.Literal(\"and\", \"or\") {}\n\n/**\n * Combine multiple filters using `and` or `or`.\n */\nexport class CompoundFilter extends S.Class<CompoundFilter>(\"CompoundFilter\")({\n  /**\n   * Type of operation: `and` or `or`.\n   */\n  \"type\": CompoundFilterType,\n  /**\n   * Array of filters to combine. Items can be `ComparisonFilter` or `CompoundFilter`.\n   */\n  \"filters\": S.Array(ComparisonFilter)\n}) {}\n\nexport class Filters extends S.Union(ComparisonFilter, CompoundFilter) {}\n\n/**\n * A tool that searches for relevant content from uploaded files. Learn more about the [file search tool](https://platform.openai.com/docs/guides/tools-file-search).\n */\nexport class FileSearchTool extends S.Class<FileSearchTool>(\"FileSearchTool\")({\n  /**\n   * The type of the file search tool. Always `file_search`.\n   */\n  \"type\": FileSearchToolType.pipe(S.propertySignature, S.withConstructorDefault(() => \"file_search\" as const)),\n  /**\n   * The IDs of the vector stores to search.\n   */\n  \"vector_store_ids\": S.Array(S.String),\n  /**\n   * The maximum number of results to return. This number should be between 1 and 50 inclusive.\n   */\n  \"max_num_results\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Ranking options for search.\n   */\n  \"ranking_options\": S.optionalWith(RankingOptions, { nullable: true }),\n  \"filters\": S.optionalWith(Filters, { nullable: true })\n}) {}\n\n/**\n * The type of the computer use tool. Always `computer_use_preview`.\n */\nexport class ComputerUsePreviewToolType extends S.Literal(\"computer_use_preview\") {}\n\nexport class ComputerEnvironment extends S.Literal(\"windows\", \"mac\", \"linux\", \"ubuntu\", \"browser\") {}\n\n/**\n * A tool that controls a virtual computer. Learn more about the [computer tool](https://platform.openai.com/docs/guides/tools-computer-use).\n */\nexport class ComputerUsePreviewTool extends S.Class<ComputerUsePreviewTool>(\"ComputerUsePreviewTool\")({\n  /**\n   * The type of the computer use tool. Always `computer_use_preview`.\n   */\n  \"type\": ComputerUsePreviewToolType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"computer_use_preview\" as const)\n  ),\n  /**\n   * The type of computer environment to control.\n   */\n  \"environment\": ComputerEnvironment,\n  /**\n   * The width of the computer display.\n   */\n  \"display_width\": S.Int,\n  /**\n   * The height of the computer display.\n   */\n  \"display_height\": S.Int\n}) {}\n\n/**\n * The type of the web search tool. One of `web_search` or `web_search_2025_08_26`.\n */\nexport class WebSearchToolType extends S.Literal(\"web_search\", \"web_search_2025_08_26\") {}\n\n/**\n * The type of location approximation. Always `approximate`.\n */\nexport class WebSearchApproximateLocationEnumType extends S.Literal(\"approximate\") {}\n\nexport class WebSearchApproximateLocation extends S.Union(\n  /**\n   * The approximate location of the user.\n   */\n  S.Struct({\n    /**\n     * The type of location approximation. Always `approximate`.\n     */\n    \"type\": S.optionalWith(WebSearchApproximateLocationEnumType, {\n      nullable: true,\n      default: () => \"approximate\" as const\n    }),\n    \"country\": S.optionalWith(S.String, { nullable: true }),\n    \"region\": S.optionalWith(S.String, { nullable: true }),\n    \"city\": S.optionalWith(S.String, { nullable: true }),\n    \"timezone\": S.optionalWith(S.String, { nullable: true })\n  }),\n  S.Null\n) {}\n\n/**\n * High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default.\n */\nexport class WebSearchToolSearchContextSize extends S.Literal(\"low\", \"medium\", \"high\") {}\n\n/**\n * Search the Internet for sources related to the prompt. Learn more about the\n * [web search tool](https://platform.openai.com/docs/guides/tools-web-search).\n */\nexport class WebSearchTool extends S.Class<WebSearchTool>(\"WebSearchTool\")({\n  /**\n   * The type of the web search tool. One of `web_search` or `web_search_2025_08_26`.\n   */\n  \"type\": WebSearchToolType.pipe(S.propertySignature, S.withConstructorDefault(() => \"web_search\" as const)),\n  \"filters\": S.optionalWith(\n    S.Struct({\n      \"allowed_domains\": S.optionalWith(S.Array(S.String), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"user_location\": S.optionalWith(\n    S.Struct({\n      /**\n       * The type of location approximation. Always `approximate`.\n       */\n      \"type\": S.optionalWith(S.Literal(\"approximate\"), { nullable: true, default: () => \"approximate\" as const }),\n      \"country\": S.optionalWith(S.String, { nullable: true }),\n      \"region\": S.optionalWith(S.String, { nullable: true }),\n      \"city\": S.optionalWith(S.String, { nullable: true }),\n      \"timezone\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default.\n   */\n  \"search_context_size\": S.optionalWith(WebSearchToolSearchContextSize, {\n    nullable: true,\n    default: () => \"medium\" as const\n  })\n}) {}\n\n/**\n * The type of the MCP tool. Always `mcp`.\n */\nexport class MCPToolType extends S.Literal(\"mcp\") {}\n\n/**\n * Identifier for service connectors, like those available in ChatGPT. One of\n * `server_url` or `connector_id` must be provided. Learn more about service\n * connectors [here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors).\n *\n * Currently supported `connector_id` values are:\n *\n * - Dropbox: `connector_dropbox`\n * - Gmail: `connector_gmail`\n * - Google Calendar: `connector_googlecalendar`\n * - Google Drive: `connector_googledrive`\n * - Microsoft Teams: `connector_microsoftteams`\n * - Outlook Calendar: `connector_outlookcalendar`\n * - Outlook Email: `connector_outlookemail`\n * - SharePoint: `connector_sharepoint`\n */\nexport class MCPToolConnectorId extends S.Literal(\n  \"connector_dropbox\",\n  \"connector_gmail\",\n  \"connector_googlecalendar\",\n  \"connector_googledrive\",\n  \"connector_microsoftteams\",\n  \"connector_outlookcalendar\",\n  \"connector_outlookemail\",\n  \"connector_sharepoint\"\n) {}\n\n/**\n * A filter object to specify which tools are allowed.\n */\nexport class MCPToolFilter extends S.Class<MCPToolFilter>(\"MCPToolFilter\")({\n  /**\n   * List of allowed tool names.\n   */\n  \"tool_names\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  /**\n   * Indicates whether or not a tool modifies data or is read-only. If an\n   * MCP server is [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint),\n   * it will match this filter.\n   */\n  \"read_only\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * Specify a single approval policy for all tools. One of `always` or\n * `never`. When set to `always`, all tools will require approval. When\n * set to `never`, all tools will not require approval.\n */\nexport class MCPToolRequireApprovalEnum extends S.Literal(\"always\", \"never\") {}\n\n/**\n * Give the model access to additional tools via remote Model Context Protocol\n * (MCP) servers. [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp).\n */\nexport class MCPTool extends S.Class<MCPTool>(\"MCPTool\")({\n  /**\n   * The type of the MCP tool. Always `mcp`.\n   */\n  \"type\": MCPToolType,\n  /**\n   * A label for this MCP server, used to identify it in tool calls.\n   */\n  \"server_label\": S.String,\n  /**\n   * The URL for the MCP server. One of `server_url` or `connector_id` must be\n   * provided.\n   */\n  \"server_url\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Identifier for service connectors, like those available in ChatGPT. One of\n   * `server_url` or `connector_id` must be provided. Learn more about service\n   * connectors [here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors).\n   *\n   * Currently supported `connector_id` values are:\n   *\n   * - Dropbox: `connector_dropbox`\n   * - Gmail: `connector_gmail`\n   * - Google Calendar: `connector_googlecalendar`\n   * - Google Drive: `connector_googledrive`\n   * - Microsoft Teams: `connector_microsoftteams`\n   * - Outlook Calendar: `connector_outlookcalendar`\n   * - Outlook Email: `connector_outlookemail`\n   * - SharePoint: `connector_sharepoint`\n   */\n  \"connector_id\": S.optionalWith(MCPToolConnectorId, { nullable: true }),\n  /**\n   * An OAuth access token that can be used with a remote MCP server, either\n   * with a custom MCP server URL or a service connector. Your application\n   * must handle the OAuth authorization flow and provide the token here.\n   */\n  \"authorization\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Optional description of the MCP server, used to provide more context.\n   */\n  \"server_description\": S.optionalWith(S.String, { nullable: true }),\n  \"headers\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"allowed_tools\": S.optionalWith(\n    S.Union(\n      /**\n       * A string array of allowed tool names\n       */\n      S.Array(S.String),\n      MCPToolFilter\n    ),\n    { nullable: true }\n  ),\n  \"require_approval\": S.optionalWith(\n    S.Union(\n      /**\n       * Specify which of the MCP server's tools require approval. Can be\n       * `always`, `never`, or a filter object associated with tools\n       * that require approval.\n       */\n      S.Struct({\n        \"always\": S.optionalWith(MCPToolFilter, { nullable: true }),\n        \"never\": S.optionalWith(MCPToolFilter, { nullable: true })\n      }),\n      /**\n       * Specify a single approval policy for all tools. One of `always` or\n       * `never`. When set to `always`, all tools will require approval. When\n       * set to `never`, all tools will not require approval.\n       */\n      MCPToolRequireApprovalEnum\n    ),\n    { nullable: true }\n  )\n}) {}\n\n/**\n * The type of the code interpreter tool. Always `code_interpreter`.\n */\nexport class CodeInterpreterToolType extends S.Literal(\"code_interpreter\") {}\n\n/**\n * Always `auto`.\n */\nexport class CodeInterpreterContainerAutoType extends S.Literal(\"auto\") {}\n\nexport class ContainerMemoryLimit extends S.Literal(\"1g\", \"4g\", \"16g\", \"64g\") {}\n\n/**\n * Configuration for a code interpreter container. Optionally specify the IDs of the files to run the code on.\n */\nexport class CodeInterpreterContainerAuto\n  extends S.Class<CodeInterpreterContainerAuto>(\"CodeInterpreterContainerAuto\")({\n    /**\n     * Always `auto`.\n     */\n    \"type\": CodeInterpreterContainerAutoType.pipe(S.propertySignature, S.withConstructorDefault(() => \"auto\" as const)),\n    /**\n     * An optional list of uploaded files to make available to your code.\n     */\n    \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(50)), { nullable: true }),\n    \"memory_limit\": S.optionalWith(ContainerMemoryLimit, { nullable: true })\n  })\n{}\n\n/**\n * A tool that runs Python code to help generate a response to a prompt.\n */\nexport class CodeInterpreterTool extends S.Class<CodeInterpreterTool>(\"CodeInterpreterTool\")({\n  /**\n   * The type of the code interpreter tool. Always `code_interpreter`.\n   */\n  \"type\": CodeInterpreterToolType,\n  /**\n   * The code interpreter container. Can be a container ID or an object that\n   * specifies uploaded file IDs to make available to your code.\n   */\n  \"container\": S.Union(\n    /**\n     * The container ID.\n     */\n    S.String,\n    CodeInterpreterContainerAuto\n  )\n}) {}\n\n/**\n * The type of the image generation tool. Always `image_generation`.\n */\nexport class ImageGenToolType extends S.Literal(\"image_generation\") {}\n\n/**\n * The image generation model to use. Default: `gpt-image-1`.\n */\nexport class ImageGenToolModel extends S.Literal(\"gpt-image-1\", \"gpt-image-1-mini\") {}\n\n/**\n * The quality of the generated image. One of `low`, `medium`, `high`,\n * or `auto`. Default: `auto`.\n */\nexport class ImageGenToolQuality extends S.Literal(\"low\", \"medium\", \"high\", \"auto\") {}\n\n/**\n * The size of the generated image. One of `1024x1024`, `1024x1536`,\n * `1536x1024`, or `auto`. Default: `auto`.\n */\nexport class ImageGenToolSize extends S.Literal(\"1024x1024\", \"1024x1536\", \"1536x1024\", \"auto\") {}\n\n/**\n * The output format of the generated image. One of `png`, `webp`, or\n * `jpeg`. Default: `png`.\n */\nexport class ImageGenToolOutputFormat extends S.Literal(\"png\", \"webp\", \"jpeg\") {}\n\n/**\n * Moderation level for the generated image. Default: `auto`.\n */\nexport class ImageGenToolModeration extends S.Literal(\"auto\", \"low\") {}\n\n/**\n * Background type for the generated image. One of `transparent`,\n * `opaque`, or `auto`. Default: `auto`.\n */\nexport class ImageGenToolBackground extends S.Literal(\"transparent\", \"opaque\", \"auto\") {}\n\n/**\n * Control how much effort the model will exert to match the style and features, especially facial features, of input images. This parameter is only supported for `gpt-image-1`. Unsupported for `gpt-image-1-mini`. Supports `high` and `low`. Defaults to `low`.\n */\nexport class InputFidelity extends S.Literal(\"high\", \"low\") {}\n\n/**\n * A tool that generates images using a model like `gpt-image-1`.\n */\nexport class ImageGenTool extends S.Class<ImageGenTool>(\"ImageGenTool\")({\n  /**\n   * The type of the image generation tool. Always `image_generation`.\n   */\n  \"type\": ImageGenToolType,\n  /**\n   * The image generation model to use. Default: `gpt-image-1`.\n   */\n  \"model\": S.optionalWith(ImageGenToolModel, { nullable: true, default: () => \"gpt-image-1\" as const }),\n  /**\n   * The quality of the generated image. One of `low`, `medium`, `high`,\n   * or `auto`. Default: `auto`.\n   */\n  \"quality\": S.optionalWith(ImageGenToolQuality, { nullable: true, default: () => \"auto\" as const }),\n  /**\n   * The size of the generated image. One of `1024x1024`, `1024x1536`,\n   * `1536x1024`, or `auto`. Default: `auto`.\n   */\n  \"size\": S.optionalWith(ImageGenToolSize, { nullable: true, default: () => \"auto\" as const }),\n  /**\n   * The output format of the generated image. One of `png`, `webp`, or\n   * `jpeg`. Default: `png`.\n   */\n  \"output_format\": S.optionalWith(ImageGenToolOutputFormat, { nullable: true, default: () => \"png\" as const }),\n  /**\n   * Compression level for the output image. Default: 100.\n   */\n  \"output_compression\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(100)), {\n    nullable: true,\n    default: () => 100 as const\n  }),\n  /**\n   * Moderation level for the generated image. Default: `auto`.\n   */\n  \"moderation\": S.optionalWith(ImageGenToolModeration, { nullable: true, default: () => \"auto\" as const }),\n  /**\n   * Background type for the generated image. One of `transparent`,\n   * `opaque`, or `auto`. Default: `auto`.\n   */\n  \"background\": S.optionalWith(ImageGenToolBackground, { nullable: true, default: () => \"auto\" as const }),\n  \"input_fidelity\": S.optionalWith(InputFidelity, { nullable: true }),\n  /**\n   * Optional mask for inpainting. Contains `image_url`\n   * (string, optional) and `file_id` (string, optional).\n   */\n  \"input_image_mask\": S.optionalWith(\n    S.Struct({\n      /**\n       * Base64-encoded mask image.\n       */\n      \"image_url\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * File ID for the mask image.\n       */\n      \"file_id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * Number of partial images to generate in streaming mode, from 0 (default value) to 3.\n   */\n  \"partial_images\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(3)), {\n    nullable: true,\n    default: () => 0 as const\n  })\n}) {}\n\n/**\n * The type of the local shell tool. Always `local_shell`.\n */\nexport class LocalShellToolParamType extends S.Literal(\"local_shell\") {}\n\n/**\n * A tool that allows the model to execute shell commands in a local environment.\n */\nexport class LocalShellToolParam extends S.Class<LocalShellToolParam>(\"LocalShellToolParam\")({\n  /**\n   * The type of the local shell tool. Always `local_shell`.\n   */\n  \"type\": LocalShellToolParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"local_shell\" as const))\n}) {}\n\n/**\n * The type of the shell tool. Always `shell`.\n */\nexport class FunctionShellToolParamType extends S.Literal(\"shell\") {}\n\n/**\n * A tool that allows the model to execute shell commands.\n */\nexport class FunctionShellToolParam extends S.Class<FunctionShellToolParam>(\"FunctionShellToolParam\")({\n  /**\n   * The type of the shell tool. Always `shell`.\n   */\n  \"type\": FunctionShellToolParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"shell\" as const))\n}) {}\n\n/**\n * The type of the custom tool. Always `custom`.\n */\nexport class CustomToolParamType extends S.Literal(\"custom\") {}\n\n/**\n * Unconstrained text format. Always `text`.\n */\nexport class CustomTextFormatParamType extends S.Literal(\"text\") {}\n\n/**\n * Unconstrained free-form text.\n */\nexport class CustomTextFormatParam extends S.Class<CustomTextFormatParam>(\"CustomTextFormatParam\")({\n  /**\n   * Unconstrained text format. Always `text`.\n   */\n  \"type\": CustomTextFormatParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"text\" as const))\n}) {}\n\n/**\n * Grammar format. Always `grammar`.\n */\nexport class CustomGrammarFormatParamType extends S.Literal(\"grammar\") {}\n\nexport class GrammarSyntax1 extends S.Literal(\"lark\", \"regex\") {}\n\n/**\n * A grammar defined by the user.\n */\nexport class CustomGrammarFormatParam extends S.Class<CustomGrammarFormatParam>(\"CustomGrammarFormatParam\")({\n  /**\n   * Grammar format. Always `grammar`.\n   */\n  \"type\": CustomGrammarFormatParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"grammar\" as const)),\n  /**\n   * The syntax of the grammar definition. One of `lark` or `regex`.\n   */\n  \"syntax\": GrammarSyntax1,\n  /**\n   * The grammar definition.\n   */\n  \"definition\": S.String\n}) {}\n\n/**\n * A custom tool that processes input using a specified format. Learn more about   [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools)\n */\nexport class CustomToolParam extends S.Class<CustomToolParam>(\"CustomToolParam\")({\n  /**\n   * The type of the custom tool. Always `custom`.\n   */\n  \"type\": CustomToolParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"custom\" as const)),\n  /**\n   * The name of the custom tool, used to identify it in tool calls.\n   */\n  \"name\": S.String,\n  /**\n   * Optional description of the custom tool, used to provide more context.\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The input format for the custom tool. Default is unconstrained text.\n   */\n  \"format\": S.optionalWith(S.Union(CustomTextFormatParam, CustomGrammarFormatParam), { nullable: true })\n}) {}\n\n/**\n * The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`.\n */\nexport class WebSearchPreviewToolType extends S.Literal(\"web_search_preview\", \"web_search_preview_2025_03_11\") {}\n\n/**\n * The type of location approximation. Always `approximate`.\n */\nexport class ApproximateLocationType extends S.Literal(\"approximate\") {}\n\nexport class ApproximateLocation extends S.Class<ApproximateLocation>(\"ApproximateLocation\")({\n  /**\n   * The type of location approximation. Always `approximate`.\n   */\n  \"type\": ApproximateLocationType.pipe(S.propertySignature, S.withConstructorDefault(() => \"approximate\" as const)),\n  \"country\": S.optionalWith(S.String, { nullable: true }),\n  \"region\": S.optionalWith(S.String, { nullable: true }),\n  \"city\": S.optionalWith(S.String, { nullable: true }),\n  \"timezone\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class SearchContextSize extends S.Literal(\"low\", \"medium\", \"high\") {}\n\n/**\n * This tool searches the web for relevant results to use in a response. Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search).\n */\nexport class WebSearchPreviewTool extends S.Class<WebSearchPreviewTool>(\"WebSearchPreviewTool\")({\n  /**\n   * The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`.\n   */\n  \"type\": WebSearchPreviewToolType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"web_search_preview\" as const)\n  ),\n  \"user_location\": S.optionalWith(ApproximateLocation, { nullable: true }),\n  /**\n   * High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default.\n   */\n  \"search_context_size\": S.optionalWith(SearchContextSize, { nullable: true })\n}) {}\n\n/**\n * The type of the tool. Always `apply_patch`.\n */\nexport class ApplyPatchToolParamType extends S.Literal(\"apply_patch\") {}\n\n/**\n * Allows the assistant to create, delete, or update files using unified diffs.\n */\nexport class ApplyPatchToolParam extends S.Class<ApplyPatchToolParam>(\"ApplyPatchToolParam\")({\n  /**\n   * The type of the tool. Always `apply_patch`.\n   */\n  \"type\": ApplyPatchToolParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"apply_patch\" as const))\n}) {}\n\n/**\n * A tool that can be used to generate a response.\n */\nexport class Tool extends S.Union(\n  FunctionTool,\n  FileSearchTool,\n  ComputerUsePreviewTool,\n  WebSearchTool,\n  MCPTool,\n  CodeInterpreterTool,\n  ImageGenTool,\n  LocalShellToolParam,\n  FunctionShellToolParam,\n  CustomToolParam,\n  WebSearchPreviewTool,\n  ApplyPatchToolParam\n) {}\n\n/**\n * The type of response format being defined. Always `json_schema`.\n */\nexport class TextResponseFormatJsonSchemaType extends S.Literal(\"json_schema\") {}\n\n/**\n * JSON Schema response format. Used to generate structured JSON responses.\n * Learn more about [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs).\n */\nexport class TextResponseFormatJsonSchema\n  extends S.Class<TextResponseFormatJsonSchema>(\"TextResponseFormatJsonSchema\")({\n    /**\n     * The type of response format being defined. Always `json_schema`.\n     */\n    \"type\": TextResponseFormatJsonSchemaType,\n    /**\n     * A description of what the response format is for, used by the model to\n     * determine how to respond in the format.\n     */\n    \"description\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The name of the response format. Must be a-z, A-Z, 0-9, or contain\n     * underscores and dashes, with a maximum length of 64.\n     */\n    \"name\": S.String,\n    \"schema\": ResponseFormatJsonSchemaSchema,\n    \"strict\": S.optionalWith(S.Boolean, { nullable: true })\n  })\n{}\n\n/**\n * An object specifying the format that the model must output.\n *\n * Configuring `{ \"type\": \"json_schema\" }` enables Structured Outputs,\n * which ensures the model will match your supplied JSON schema. Learn more in the\n * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).\n *\n * The default format is `{ \"type\": \"text\" }` with no additional options.\n *\n * **Not recommended for gpt-4o and newer models:**\n *\n * Setting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\n * ensures the message the model generates is valid JSON. Using `json_schema`\n * is preferred for models that support it.\n */\nexport class TextResponseFormatConfiguration\n  extends S.Union(ResponseFormatText, TextResponseFormatJsonSchema, ResponseFormatJsonObject)\n{}\n\n/**\n * The type of run data source. Always `responses`.\n */\nexport class EvalResponsesSourceType extends S.Literal(\"responses\") {}\n\n/**\n * A EvalResponsesSource object describing a run data source configuration.\n */\nexport class EvalResponsesSource extends S.Class<EvalResponsesSource>(\"EvalResponsesSource\")({\n  /**\n   * The type of run data source. Always `responses`.\n   */\n  \"type\": EvalResponsesSourceType,\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"model\": S.optionalWith(S.String, { nullable: true }),\n  \"instructions_search\": S.optionalWith(S.String, { nullable: true }),\n  \"created_after\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0)), { nullable: true }),\n  \"created_before\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0)), { nullable: true }),\n  \"reasoning_effort\": S.optionalWith(ReasoningEffort, { nullable: true }),\n  \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number, { nullable: true }),\n  \"users\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"tools\": S.optionalWith(S.Array(S.String), { nullable: true })\n}) {}\n\n/**\n * A ResponsesRunDataSource object describing a model sampling configuration.\n */\nexport class CreateEvalResponsesRunDataSource\n  extends S.Class<CreateEvalResponsesRunDataSource>(\"CreateEvalResponsesRunDataSource\")({\n    /**\n     * The type of run data source. Always `responses`.\n     */\n    \"type\": CreateEvalResponsesRunDataSourceType.pipe(\n      S.propertySignature,\n      S.withConstructorDefault(() => \"responses\" as const)\n    ),\n    /**\n     * Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace.\n     */\n    \"input_messages\": S.optionalWith(\n      S.Union(\n        S.Struct({\n          /**\n           * The type of input messages. Always `template`.\n           */\n          \"type\": CreateEvalResponsesRunDataSourceInputMessagesEnumType,\n          /**\n           * A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}.\n           */\n          \"template\": S.Array(S.Union(\n            S.Struct({\n              /**\n               * The role of the message (e.g. \"system\", \"assistant\", \"user\").\n               */\n              \"role\": S.String,\n              /**\n               * The content of the message.\n               */\n              \"content\": S.String\n            }),\n            EvalItem\n          ))\n        }),\n        S.Struct({\n          /**\n           * The type of input messages. Always `item_reference`.\n           */\n          \"type\": CreateEvalResponsesRunDataSourceInputMessagesEnumType,\n          /**\n           * A reference to a variable in the `item` namespace. Ie, \"item.name\"\n           */\n          \"item_reference\": S.String\n        })\n      ),\n      { nullable: true }\n    ),\n    \"sampling_params\": S.optionalWith(\n      S.Struct({\n        \"reasoning_effort\": S.optionalWith(S.Literal(\"none\", \"minimal\", \"low\", \"medium\", \"high\"), { nullable: true }),\n        /**\n         * A higher temperature increases randomness in the outputs.\n         */\n        \"temperature\": S.optionalWith(S.Number, { nullable: true, default: () => 1 as const }),\n        /**\n         * The maximum number of tokens in the generated output.\n         */\n        \"max_completion_tokens\": S.optionalWith(S.Int, { nullable: true }),\n        /**\n         * An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n         */\n        \"top_p\": S.optionalWith(S.Number, { nullable: true, default: () => 1 as const }),\n        /**\n         * A seed value to initialize the randomness, during sampling.\n         */\n        \"seed\": S.optionalWith(S.Int, { nullable: true, default: () => 42 as const }),\n        /**\n         * An array of tools the model may call while generating a response. You\n         * can specify which tool to use by setting the `tool_choice` parameter.\n         *\n         * The two categories of tools you can provide the model are:\n         *\n         * - **Built-in tools**: Tools that are provided by OpenAI that extend the\n         *   model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search)\n         *   or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about\n         *   [built-in tools](https://platform.openai.com/docs/guides/tools).\n         * - **Function calls (custom tools)**: Functions that are defined by you,\n         *   enabling the model to call your own code. Learn more about\n         *   [function calling](https://platform.openai.com/docs/guides/function-calling).\n         */\n        \"tools\": S.optionalWith(S.Array(Tool), { nullable: true }),\n        /**\n         * Configuration options for a text response from the model. Can be plain\n         * text or structured JSON data. Learn more:\n         * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n         * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)\n         */\n        \"text\": S.optionalWith(\n          S.Struct({\n            \"format\": S.optionalWith(TextResponseFormatConfiguration, { nullable: true })\n          }),\n          { nullable: true }\n        )\n      }),\n      { nullable: true }\n    ),\n    /**\n     * The name of the model to use for generating completions (e.g. \"o3-mini\").\n     */\n    \"model\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Determines what populates the `item` namespace in this run's data source.\n     */\n    \"source\": S.Union(EvalJsonlFileContentSource, EvalJsonlFileIdSource, EvalResponsesSource)\n  })\n{}\n\n/**\n * An object representing an error response from the Eval API.\n */\nexport class EvalApiError extends S.Class<EvalApiError>(\"EvalApiError\")({\n  /**\n   * The error code.\n   */\n  \"code\": S.String,\n  /**\n   * The error message.\n   */\n  \"message\": S.String\n}) {}\n\n/**\n * A schema representing an evaluation run.\n */\nexport class EvalRun extends S.Class<EvalRun>(\"EvalRun\")({\n  /**\n   * The type of the object. Always \"eval.run\".\n   */\n  \"object\": EvalRunObject.pipe(S.propertySignature, S.withConstructorDefault(() => \"eval.run\" as const)),\n  /**\n   * Unique identifier for the evaluation run.\n   */\n  \"id\": S.String,\n  /**\n   * The identifier of the associated evaluation.\n   */\n  \"eval_id\": S.String,\n  /**\n   * The status of the evaluation run.\n   */\n  \"status\": S.String,\n  /**\n   * The model that is evaluated, if applicable.\n   */\n  \"model\": S.String,\n  /**\n   * The name of the evaluation run.\n   */\n  \"name\": S.String,\n  /**\n   * Unix timestamp (in seconds) when the evaluation run was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The URL to the rendered evaluation run report on the UI dashboard.\n   */\n  \"report_url\": S.String,\n  /**\n   * Counters summarizing the outcomes of the evaluation run.\n   */\n  \"result_counts\": S.Struct({\n    /**\n     * Total number of executed output items.\n     */\n    \"total\": S.Int,\n    /**\n     * Number of output items that resulted in an error.\n     */\n    \"errored\": S.Int,\n    /**\n     * Number of output items that failed to pass the evaluation.\n     */\n    \"failed\": S.Int,\n    /**\n     * Number of output items that passed the evaluation.\n     */\n    \"passed\": S.Int\n  }),\n  /**\n   * Usage statistics for each model during the evaluation run.\n   */\n  \"per_model_usage\": S.Array(S.Struct({\n    /**\n     * The name of the model.\n     */\n    \"model_name\": S.String,\n    /**\n     * The number of invocations.\n     */\n    \"invocation_count\": S.Int,\n    /**\n     * The number of prompt tokens used.\n     */\n    \"prompt_tokens\": S.Int,\n    /**\n     * The number of completion tokens generated.\n     */\n    \"completion_tokens\": S.Int,\n    /**\n     * The total number of tokens used.\n     */\n    \"total_tokens\": S.Int,\n    /**\n     * The number of tokens retrieved from cache.\n     */\n    \"cached_tokens\": S.Int\n  })),\n  /**\n   * Results per testing criteria applied during the evaluation run.\n   */\n  \"per_testing_criteria_results\": S.Array(S.Struct({\n    /**\n     * A description of the testing criteria.\n     */\n    \"testing_criteria\": S.String,\n    /**\n     * Number of tests passed for this criteria.\n     */\n    \"passed\": S.Int,\n    /**\n     * Number of tests failed for this criteria.\n     */\n    \"failed\": S.Int\n  })),\n  /**\n   * Information about the run's data source.\n   */\n  \"data_source\": S.Record({ key: S.String, value: S.Unknown }),\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown })),\n  \"error\": EvalApiError\n}) {}\n\n/**\n * An object representing a list of runs for an evaluation.\n */\nexport class EvalRunList extends S.Class<EvalRunList>(\"EvalRunList\")({\n  /**\n   * The type of this object. It is always set to \"list\".\n   */\n  \"object\": EvalRunListObject.pipe(S.propertySignature, S.withConstructorDefault(() => \"list\" as const)),\n  /**\n   * An array of eval run objects.\n   */\n  \"data\": S.Array(EvalRun),\n  /**\n   * The identifier of the first eval run in the data array.\n   */\n  \"first_id\": S.String,\n  /**\n   * The identifier of the last eval run in the data array.\n   */\n  \"last_id\": S.String,\n  /**\n   * Indicates whether there are more evals available.\n   */\n  \"has_more\": S.Boolean\n}) {}\n\nexport class CreateEvalRunRequest extends S.Class<CreateEvalRunRequest>(\"CreateEvalRunRequest\")({\n  /**\n   * The name of the run.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * Details about the run's data source.\n   */\n  \"data_source\": S.Record({ key: S.String, value: S.Unknown })\n}) {}\n\nexport class DeleteEvalRun200 extends S.Struct({\n  \"object\": S.optionalWith(S.String, { nullable: true }),\n  \"deleted\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"run_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class GetEvalRunOutputItemsParamsStatus extends S.Literal(\"fail\", \"pass\") {}\n\nexport class GetEvalRunOutputItemsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class GetEvalRunOutputItemsParams extends S.Struct({\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"status\": S.optionalWith(GetEvalRunOutputItemsParamsStatus, { nullable: true }),\n  \"order\": S.optionalWith(GetEvalRunOutputItemsParamsOrder, { nullable: true, default: () => \"asc\" as const })\n}) {}\n\n/**\n * The type of this object. It is always set to \"list\".\n */\nexport class EvalRunOutputItemListObject extends S.Literal(\"list\") {}\n\n/**\n * The type of the object. Always \"eval.run.output_item\".\n */\nexport class EvalRunOutputItemObject extends S.Literal(\"eval.run.output_item\") {}\n\n/**\n * A single grader result for an evaluation run output item.\n */\nexport class EvalRunOutputItemResult extends S.Class<EvalRunOutputItemResult>(\"EvalRunOutputItemResult\")({\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The grader type (for example, \"string-check-grader\").\n   */\n  \"type\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The numeric score produced by the grader.\n   */\n  \"score\": S.Number,\n  /**\n   * Whether the grader considered the output a pass.\n   */\n  \"passed\": S.Boolean,\n  /**\n   * Optional sample or intermediate data produced by the grader.\n   */\n  \"sample\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * A schema representing an evaluation run output item.\n */\nexport class EvalRunOutputItem extends S.Class<EvalRunOutputItem>(\"EvalRunOutputItem\")({\n  /**\n   * The type of the object. Always \"eval.run.output_item\".\n   */\n  \"object\": EvalRunOutputItemObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"eval.run.output_item\" as const)\n  ),\n  /**\n   * Unique identifier for the evaluation run output item.\n   */\n  \"id\": S.String,\n  /**\n   * The identifier of the evaluation run associated with this output item.\n   */\n  \"run_id\": S.String,\n  /**\n   * The identifier of the evaluation group.\n   */\n  \"eval_id\": S.String,\n  /**\n   * Unix timestamp (in seconds) when the evaluation run was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The status of the evaluation run.\n   */\n  \"status\": S.String,\n  /**\n   * The identifier for the data source item.\n   */\n  \"datasource_item_id\": S.Int,\n  /**\n   * Details of the input data source item.\n   */\n  \"datasource_item\": S.Record({ key: S.String, value: S.Unknown }),\n  /**\n   * A list of grader results for this output item.\n   */\n  \"results\": S.Array(EvalRunOutputItemResult),\n  /**\n   * A sample containing the input and output of the evaluation run.\n   */\n  \"sample\": S.Struct({\n    /**\n     * An array of input messages.\n     */\n    \"input\": S.Array(S.Struct({\n      /**\n       * The role of the message sender (e.g., system, user, developer).\n       */\n      \"role\": S.String,\n      /**\n       * The content of the message.\n       */\n      \"content\": S.String\n    })),\n    /**\n     * An array of output messages.\n     */\n    \"output\": S.Array(S.Struct({\n      /**\n       * The role of the message (e.g. \"system\", \"assistant\", \"user\").\n       */\n      \"role\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The content of the message.\n       */\n      \"content\": S.optionalWith(S.String, { nullable: true })\n    })),\n    /**\n     * The reason why the sample generation was finished.\n     */\n    \"finish_reason\": S.String,\n    /**\n     * The model used for generating the sample.\n     */\n    \"model\": S.String,\n    /**\n     * Token usage details for the sample.\n     */\n    \"usage\": S.Struct({\n      /**\n       * The total number of tokens used.\n       */\n      \"total_tokens\": S.Int,\n      /**\n       * The number of completion tokens generated.\n       */\n      \"completion_tokens\": S.Int,\n      /**\n       * The number of prompt tokens used.\n       */\n      \"prompt_tokens\": S.Int,\n      /**\n       * The number of tokens retrieved from cache.\n       */\n      \"cached_tokens\": S.Int\n    }),\n    \"error\": EvalApiError,\n    /**\n     * The sampling temperature used.\n     */\n    \"temperature\": S.Number,\n    /**\n     * The maximum number of tokens allowed for completion.\n     */\n    \"max_completion_tokens\": S.Int,\n    /**\n     * The top_p value used for sampling.\n     */\n    \"top_p\": S.Number,\n    /**\n     * The seed used for generating the sample.\n     */\n    \"seed\": S.Int\n  })\n}) {}\n\n/**\n * An object representing a list of output items for an evaluation run.\n */\nexport class EvalRunOutputItemList extends S.Class<EvalRunOutputItemList>(\"EvalRunOutputItemList\")({\n  /**\n   * The type of this object. It is always set to \"list\".\n   */\n  \"object\": EvalRunOutputItemListObject.pipe(S.propertySignature, S.withConstructorDefault(() => \"list\" as const)),\n  /**\n   * An array of eval run output item objects.\n   */\n  \"data\": S.Array(EvalRunOutputItem),\n  /**\n   * The identifier of the first eval run output item in the data array.\n   */\n  \"first_id\": S.String,\n  /**\n   * The identifier of the last eval run output item in the data array.\n   */\n  \"last_id\": S.String,\n  /**\n   * Indicates whether there are more eval run output items available.\n   */\n  \"has_more\": S.Boolean\n}) {}\n\nexport class ListFilesParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListFilesParams extends S.Struct({\n  \"purpose\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 10000 as const }),\n  \"order\": S.optionalWith(ListFilesParamsOrder, { nullable: true, default: () => \"desc\" as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `file`.\n */\nexport class OpenAIFileObject extends S.Literal(\"file\") {}\n\n/**\n * The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`.\n */\nexport class OpenAIFilePurpose extends S.Literal(\n  \"assistants\",\n  \"assistants_output\",\n  \"batch\",\n  \"batch_output\",\n  \"fine-tune\",\n  \"fine-tune-results\",\n  \"vision\",\n  \"user_data\"\n) {}\n\n/**\n * Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`.\n */\nexport class OpenAIFileStatus extends S.Literal(\"uploaded\", \"processed\", \"error\") {}\n\n/**\n * The `File` object represents a document that has been uploaded to OpenAI.\n */\nexport class OpenAIFile extends S.Class<OpenAIFile>(\"OpenAIFile\")({\n  /**\n   * The file identifier, which can be referenced in the API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The size of the file, in bytes.\n   */\n  \"bytes\": S.Int,\n  /**\n   * The Unix timestamp (in seconds) for when the file was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The Unix timestamp (in seconds) for when the file will expire.\n   */\n  \"expires_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The name of the file.\n   */\n  \"filename\": S.String,\n  /**\n   * The object type, which is always `file`.\n   */\n  \"object\": OpenAIFileObject,\n  /**\n   * The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`.\n   */\n  \"purpose\": OpenAIFilePurpose,\n  /**\n   * Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`.\n   */\n  \"status\": OpenAIFileStatus,\n  /**\n   * Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`.\n   */\n  \"status_details\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListFilesResponse extends S.Class<ListFilesResponse>(\"ListFilesResponse\")({\n  \"object\": S.String,\n  \"data\": S.Array(OpenAIFile),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\n/**\n * The intended purpose of the uploaded file. One of: - `assistants`: Used in the Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: Flexible file type for any purpose - `evals`: Used for eval data sets\n */\nexport class FilePurpose extends S.Literal(\"assistants\", \"batch\", \"fine-tune\", \"vision\", \"user_data\", \"evals\") {}\n\n/**\n * Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`.\n */\nexport class FileExpirationAfterAnchor extends S.Literal(\"created_at\") {}\n\n/**\n * The expiration policy for a file. By default, files with `purpose=batch` expire after 30 days and all other files are persisted until they are manually deleted.\n */\nexport class FileExpirationAfter extends S.Class<FileExpirationAfter>(\"FileExpirationAfter\")({\n  /**\n   * Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`.\n   */\n  \"anchor\": FileExpirationAfterAnchor,\n  /**\n   * The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days).\n   */\n  \"seconds\": S.Int.pipe(S.greaterThanOrEqualTo(3600), S.lessThanOrEqualTo(2592000))\n}) {}\n\nexport class CreateFileRequest extends S.Class<CreateFileRequest>(\"CreateFileRequest\")({\n  /**\n   * The File object (not file name) to be uploaded.\n   */\n  \"file\": S.instanceOf(globalThis.Blob),\n  \"purpose\": FilePurpose,\n  \"expires_after\": S.optionalWith(FileExpirationAfter, { nullable: true })\n}) {}\n\nexport class DeleteFileResponseObject extends S.Literal(\"file\") {}\n\nexport class DeleteFileResponse extends S.Class<DeleteFileResponse>(\"DeleteFileResponse\")({\n  \"id\": S.String,\n  \"object\": DeleteFileResponseObject,\n  \"deleted\": S.Boolean\n}) {}\n\nexport class DownloadFile200 extends S.String {}\n\n/**\n * The object type, which is always `string_check`.\n */\nexport class GraderStringCheckType extends S.Literal(\"string_check\") {}\n\n/**\n * The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`.\n */\nexport class GraderStringCheckOperation extends S.Literal(\"eq\", \"ne\", \"like\", \"ilike\") {}\n\n/**\n * A StringCheckGrader object that performs a string comparison between input and reference using a specified operation.\n */\nexport class GraderStringCheck extends S.Class<GraderStringCheck>(\"GraderStringCheck\")({\n  /**\n   * The object type, which is always `string_check`.\n   */\n  \"type\": GraderStringCheckType,\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The input text. This may include template strings.\n   */\n  \"input\": S.String,\n  /**\n   * The reference text. This may include template strings.\n   */\n  \"reference\": S.String,\n  /**\n   * The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`.\n   */\n  \"operation\": GraderStringCheckOperation\n}) {}\n\n/**\n * The type of grader.\n */\nexport class GraderTextSimilarityType extends S.Literal(\"text_similarity\") {}\n\n/**\n * The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`,\n * `gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`,\n * or `rouge_l`.\n */\nexport class GraderTextSimilarityEvaluationMetric extends S.Literal(\n  \"cosine\",\n  \"fuzzy_match\",\n  \"bleu\",\n  \"gleu\",\n  \"meteor\",\n  \"rouge_1\",\n  \"rouge_2\",\n  \"rouge_3\",\n  \"rouge_4\",\n  \"rouge_5\",\n  \"rouge_l\"\n) {}\n\n/**\n * A TextSimilarityGrader object which grades text based on similarity metrics.\n */\nexport class GraderTextSimilarity extends S.Class<GraderTextSimilarity>(\"GraderTextSimilarity\")({\n  /**\n   * The type of grader.\n   */\n  \"type\": GraderTextSimilarityType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"text_similarity\" as const)\n  ),\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The text being graded.\n   */\n  \"input\": S.String,\n  /**\n   * The text being graded against.\n   */\n  \"reference\": S.String,\n  /**\n   * The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`,\n   * `gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`,\n   * or `rouge_l`.\n   */\n  \"evaluation_metric\": GraderTextSimilarityEvaluationMetric\n}) {}\n\n/**\n * The object type, which is always `python`.\n */\nexport class GraderPythonType extends S.Literal(\"python\") {}\n\n/**\n * A PythonGrader object that runs a python script on the input.\n */\nexport class GraderPython extends S.Class<GraderPython>(\"GraderPython\")({\n  /**\n   * The object type, which is always `python`.\n   */\n  \"type\": GraderPythonType,\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The source code of the python script.\n   */\n  \"source\": S.String,\n  /**\n   * The image tag to use for the python script.\n   */\n  \"image_tag\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `score_model`.\n */\nexport class GraderScoreModelType extends S.Literal(\"score_model\") {}\n\n/**\n * A ScoreModelGrader object that uses a model to assign a score to the input.\n */\nexport class GraderScoreModel extends S.Class<GraderScoreModel>(\"GraderScoreModel\")({\n  /**\n   * The object type, which is always `score_model`.\n   */\n  \"type\": GraderScoreModelType,\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The model to use for the evaluation.\n   */\n  \"model\": S.String,\n  /**\n   * The sampling parameters for the model.\n   */\n  \"sampling_params\": S.optionalWith(\n    S.Struct({\n      \"seed\": S.optionalWith(S.Int, { nullable: true }),\n      \"top_p\": S.optionalWith(S.Number, { nullable: true }),\n      \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n      \"max_completions_tokens\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true }),\n      \"reasoning_effort\": S.optionalWith(S.Literal(\"none\", \"minimal\", \"low\", \"medium\", \"high\"), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The input text. This may include template strings.\n   */\n  \"input\": S.Array(EvalItem),\n  /**\n   * The range of the score. Defaults to `[0, 1]`.\n   */\n  \"range\": S.optionalWith(S.Array(S.Number), { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `multi`.\n */\nexport class GraderMultiType extends S.Literal(\"multi\") {}\n\n/**\n * The object type, which is always `label_model`.\n */\nexport class GraderLabelModelType extends S.Literal(\"label_model\") {}\n\n/**\n * A LabelModelGrader object which uses a model to assign labels to each item\n * in the evaluation.\n */\nexport class GraderLabelModel extends S.Class<GraderLabelModel>(\"GraderLabelModel\")({\n  /**\n   * The object type, which is always `label_model`.\n   */\n  \"type\": GraderLabelModelType,\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  /**\n   * The model to use for the evaluation. Must support structured outputs.\n   */\n  \"model\": S.String,\n  \"input\": S.Array(EvalItem),\n  /**\n   * The labels to assign to each item in the evaluation.\n   */\n  \"labels\": S.Array(S.String),\n  /**\n   * The labels that indicate a passing result. Must be a subset of labels.\n   */\n  \"passing_labels\": S.Array(S.String)\n}) {}\n\n/**\n * A MultiGrader object combines the output of multiple graders to produce a single score.\n */\nexport class GraderMulti extends S.Class<GraderMulti>(\"GraderMulti\")({\n  /**\n   * The object type, which is always `multi`.\n   */\n  \"type\": GraderMultiType.pipe(S.propertySignature, S.withConstructorDefault(() => \"multi\" as const)),\n  /**\n   * The name of the grader.\n   */\n  \"name\": S.String,\n  \"graders\": S.Union(GraderStringCheck, GraderTextSimilarity, GraderPython, GraderScoreModel, GraderLabelModel),\n  /**\n   * A formula to calculate the output based on grader results.\n   */\n  \"calculate_output\": S.String\n}) {}\n\nexport class RunGraderRequest extends S.Class<RunGraderRequest>(\"RunGraderRequest\")({\n  /**\n   * The grader used for the fine-tuning job.\n   */\n  \"grader\": S.Record({ key: S.String, value: S.Unknown }),\n  /**\n   * The dataset item provided to the grader. This will be used to populate\n   * the `item` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details.\n   */\n  \"item\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * The model sample to be evaluated. This value will be used to populate\n   * the `sample` namespace. See [the guide](https://platform.openai.com/docs/guides/graders) for more details.\n   * The `output_json` variable will be populated if the model sample is a\n   * valid JSON string.\n   */\n  \"model_sample\": S.String\n}) {}\n\nexport class RunGraderResponse extends S.Class<RunGraderResponse>(\"RunGraderResponse\")({\n  \"reward\": S.Number,\n  \"metadata\": S.Struct({\n    \"name\": S.String,\n    \"type\": S.String,\n    \"errors\": S.Struct({\n      \"formula_parse_error\": S.Boolean,\n      \"sample_parse_error\": S.Boolean,\n      \"truncated_observation_error\": S.Boolean,\n      \"unresponsive_reward_error\": S.Boolean,\n      \"invalid_variable_error\": S.Boolean,\n      \"other_error\": S.Boolean,\n      \"python_grader_server_error\": S.Boolean,\n      \"python_grader_server_error_type\": S.NullOr(S.String),\n      \"python_grader_runtime_error\": S.Boolean,\n      \"python_grader_runtime_error_details\": S.NullOr(S.String),\n      \"model_grader_server_error\": S.Boolean,\n      \"model_grader_refusal_error\": S.Boolean,\n      \"model_grader_parse_error\": S.Boolean,\n      \"model_grader_server_error_details\": S.NullOr(S.String)\n    }),\n    \"execution_time\": S.Number,\n    \"scores\": S.Record({ key: S.String, value: S.Unknown }),\n    \"token_usage\": S.NullOr(S.Int),\n    \"sampled_model_name\": S.NullOr(S.String)\n  }),\n  \"sub_rewards\": S.Record({ key: S.String, value: S.Unknown }),\n  \"model_grader_token_usage_per_model\": S.Record({ key: S.String, value: S.Unknown })\n}) {}\n\nexport class ValidateGraderRequest extends S.Class<ValidateGraderRequest>(\"ValidateGraderRequest\")({\n  /**\n   * The grader used for the fine-tuning job.\n   */\n  \"grader\": S.Record({ key: S.String, value: S.Unknown })\n}) {}\n\nexport class ValidateGraderResponse extends S.Class<ValidateGraderResponse>(\"ValidateGraderResponse\")({\n  /**\n   * The grader used for the fine-tuning job.\n   */\n  \"grader\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class ListFineTuningCheckpointPermissionsParamsOrder extends S.Literal(\"ascending\", \"descending\") {}\n\nexport class ListFineTuningCheckpointPermissionsParams extends S.Struct({\n  \"project_id\": S.optionalWith(S.String, { nullable: true }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 10 as const }),\n  \"order\": S.optionalWith(ListFineTuningCheckpointPermissionsParamsOrder, {\n    nullable: true,\n    default: () => \"descending\" as const\n  })\n}) {}\n\n/**\n * The object type, which is always \"checkpoint.permission\".\n */\nexport class FineTuningCheckpointPermissionObject extends S.Literal(\"checkpoint.permission\") {}\n\n/**\n * The `checkpoint.permission` object represents a permission for a fine-tuned model checkpoint.\n */\nexport class FineTuningCheckpointPermission\n  extends S.Class<FineTuningCheckpointPermission>(\"FineTuningCheckpointPermission\")({\n    /**\n     * The permission identifier, which can be referenced in the API endpoints.\n     */\n    \"id\": S.String,\n    /**\n     * The Unix timestamp (in seconds) for when the permission was created.\n     */\n    \"created_at\": S.Int,\n    /**\n     * The project identifier that the permission is for.\n     */\n    \"project_id\": S.String,\n    /**\n     * The object type, which is always \"checkpoint.permission\".\n     */\n    \"object\": FineTuningCheckpointPermissionObject\n  })\n{}\n\nexport class ListFineTuningCheckpointPermissionResponseObject extends S.Literal(\"list\") {}\n\nexport class ListFineTuningCheckpointPermissionResponse\n  extends S.Class<ListFineTuningCheckpointPermissionResponse>(\"ListFineTuningCheckpointPermissionResponse\")({\n    \"data\": S.Array(FineTuningCheckpointPermission),\n    \"object\": ListFineTuningCheckpointPermissionResponseObject,\n    \"first_id\": S.optionalWith(S.String, { nullable: true }),\n    \"last_id\": S.optionalWith(S.String, { nullable: true }),\n    \"has_more\": S.Boolean\n  })\n{}\n\nexport class CreateFineTuningCheckpointPermissionRequest\n  extends S.Class<CreateFineTuningCheckpointPermissionRequest>(\"CreateFineTuningCheckpointPermissionRequest\")({\n    /**\n     * The project identifiers to grant access to.\n     */\n    \"project_ids\": S.Array(S.String)\n  })\n{}\n\n/**\n * The object type, which is always \"checkpoint.permission\".\n */\nexport class DeleteFineTuningCheckpointPermissionResponseObject extends S.Literal(\"checkpoint.permission\") {}\n\nexport class DeleteFineTuningCheckpointPermissionResponse\n  extends S.Class<DeleteFineTuningCheckpointPermissionResponse>(\"DeleteFineTuningCheckpointPermissionResponse\")({\n    /**\n     * The ID of the fine-tuned model checkpoint permission that was deleted.\n     */\n    \"id\": S.String,\n    /**\n     * The object type, which is always \"checkpoint.permission\".\n     */\n    \"object\": DeleteFineTuningCheckpointPermissionResponseObject,\n    /**\n     * Whether the fine-tuned model checkpoint permission was successfully deleted.\n     */\n    \"deleted\": S.Boolean\n  })\n{}\n\nexport class ListPaginatedFineTuningJobsParams extends S.Struct({\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class FineTuningJobHyperparametersBatchSizeEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuningJobHyperparametersLearningRateMultiplierEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuningJobHyperparametersNEpochsEnum extends S.Literal(\"auto\") {}\n\n/**\n * The object type, which is always \"fine_tuning.job\".\n */\nexport class FineTuningJobObject extends S.Literal(\"fine_tuning.job\") {}\n\n/**\n * The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`.\n */\nexport class FineTuningJobStatus\n  extends S.Literal(\"validating_files\", \"queued\", \"running\", \"succeeded\", \"failed\", \"cancelled\")\n{}\n\n/**\n * The type of the integration being enabled for the fine-tuning job\n */\nexport class FineTuningIntegrationType extends S.Literal(\"wandb\") {}\n\nexport class FineTuningIntegration extends S.Class<FineTuningIntegration>(\"FineTuningIntegration\")({\n  /**\n   * The type of the integration being enabled for the fine-tuning job\n   */\n  \"type\": FineTuningIntegrationType,\n  /**\n   * The settings for your integration with Weights and Biases. This payload specifies the project that\n   * metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\n   * to your run, and set a default entity (team, username, etc) to be associated with your run.\n   */\n  \"wandb\": S.Struct({\n    /**\n     * The name of the project that the new run will be created under.\n     */\n    \"project\": S.String,\n    \"name\": S.optionalWith(S.String, { nullable: true }),\n    \"entity\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\n     * default tags are generated by OpenAI: \"openai/finetune\", \"openai/{base-model}\", \"openai/{ftjob-abcdef}\".\n     */\n    \"tags\": S.optionalWith(S.Array(S.String), { nullable: true })\n  })\n}) {}\n\n/**\n * The type of method. Is either `supervised`, `dpo`, or `reinforcement`.\n */\nexport class FineTuneMethodType extends S.Literal(\"supervised\", \"dpo\", \"reinforcement\") {}\n\nexport class FineTuneSupervisedHyperparametersBatchSizeEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuneSupervisedHyperparametersLearningRateMultiplierEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuneSupervisedHyperparametersNEpochsEnum extends S.Literal(\"auto\") {}\n\n/**\n * The hyperparameters used for the fine-tuning job.\n */\nexport class FineTuneSupervisedHyperparameters\n  extends S.Class<FineTuneSupervisedHyperparameters>(\"FineTuneSupervisedHyperparameters\")({\n    /**\n     * Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n     */\n    \"batch_size\": S.optionalWith(\n      S.Union(\n        FineTuneSupervisedHyperparametersBatchSizeEnum,\n        S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(256))\n      ),\n      { nullable: true, default: () => \"auto\" as const }\n    ),\n    /**\n     * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n     */\n    \"learning_rate_multiplier\": S.optionalWith(\n      S.Union(FineTuneSupervisedHyperparametersLearningRateMultiplierEnum, S.Number.pipe(S.greaterThan(0))),\n      { nullable: true }\n    ),\n    /**\n     * The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n     */\n    \"n_epochs\": S.optionalWith(\n      S.Union(\n        FineTuneSupervisedHyperparametersNEpochsEnum,\n        S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(50))\n      ),\n      { nullable: true, default: () => \"auto\" as const }\n    )\n  })\n{}\n\n/**\n * Configuration for the supervised fine-tuning method.\n */\nexport class FineTuneSupervisedMethod extends S.Class<FineTuneSupervisedMethod>(\"FineTuneSupervisedMethod\")({\n  \"hyperparameters\": S.optionalWith(FineTuneSupervisedHyperparameters, { nullable: true })\n}) {}\n\nexport class FineTuneDPOHyperparametersBetaEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuneDPOHyperparametersBatchSizeEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuneDPOHyperparametersLearningRateMultiplierEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuneDPOHyperparametersNEpochsEnum extends S.Literal(\"auto\") {}\n\n/**\n * The hyperparameters used for the DPO fine-tuning job.\n */\nexport class FineTuneDPOHyperparameters extends S.Class<FineTuneDPOHyperparameters>(\"FineTuneDPOHyperparameters\")({\n  /**\n   * The beta value for the DPO method. A higher beta value will increase the weight of the penalty between the policy and reference model.\n   */\n  \"beta\": S.optionalWith(\n    S.Union(FineTuneDPOHyperparametersBetaEnum, S.Number.pipe(S.greaterThan(0), S.lessThanOrEqualTo(2))),\n    { nullable: true }\n  ),\n  /**\n   * Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n   */\n  \"batch_size\": S.optionalWith(\n    S.Union(FineTuneDPOHyperparametersBatchSizeEnum, S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(256))),\n    {\n      nullable: true,\n      default: () => \"auto\" as const\n    }\n  ),\n  /**\n   * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n   */\n  \"learning_rate_multiplier\": S.optionalWith(\n    S.Union(FineTuneDPOHyperparametersLearningRateMultiplierEnum, S.Number.pipe(S.greaterThan(0))),\n    { nullable: true }\n  ),\n  /**\n   * The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n   */\n  \"n_epochs\": S.optionalWith(\n    S.Union(FineTuneDPOHyperparametersNEpochsEnum, S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(50))),\n    {\n      nullable: true,\n      default: () => \"auto\" as const\n    }\n  )\n}) {}\n\n/**\n * Configuration for the DPO fine-tuning method.\n */\nexport class FineTuneDPOMethod extends S.Class<FineTuneDPOMethod>(\"FineTuneDPOMethod\")({\n  \"hyperparameters\": S.optionalWith(FineTuneDPOHyperparameters, { nullable: true })\n}) {}\n\nexport class FineTuneReinforcementHyperparametersBatchSizeEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuneReinforcementHyperparametersLearningRateMultiplierEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuneReinforcementHyperparametersNEpochsEnum extends S.Literal(\"auto\") {}\n\n/**\n * Level of reasoning effort.\n */\nexport class FineTuneReinforcementHyperparametersReasoningEffort\n  extends S.Literal(\"default\", \"low\", \"medium\", \"high\")\n{}\n\nexport class FineTuneReinforcementHyperparametersComputeMultiplierEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuneReinforcementHyperparametersEvalIntervalEnum extends S.Literal(\"auto\") {}\n\nexport class FineTuneReinforcementHyperparametersEvalSamplesEnum extends S.Literal(\"auto\") {}\n\n/**\n * The hyperparameters used for the reinforcement fine-tuning job.\n */\nexport class FineTuneReinforcementHyperparameters\n  extends S.Class<FineTuneReinforcementHyperparameters>(\"FineTuneReinforcementHyperparameters\")({\n    /**\n     * Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n     */\n    \"batch_size\": S.optionalWith(\n      S.Union(\n        FineTuneReinforcementHyperparametersBatchSizeEnum,\n        S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(256))\n      ),\n      { nullable: true, default: () => \"auto\" as const }\n    ),\n    /**\n     * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n     */\n    \"learning_rate_multiplier\": S.optionalWith(\n      S.Union(FineTuneReinforcementHyperparametersLearningRateMultiplierEnum, S.Number.pipe(S.greaterThan(0))),\n      { nullable: true }\n    ),\n    /**\n     * The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n     */\n    \"n_epochs\": S.optionalWith(\n      S.Union(\n        FineTuneReinforcementHyperparametersNEpochsEnum,\n        S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(50))\n      ),\n      { nullable: true, default: () => \"auto\" as const }\n    ),\n    /**\n     * Level of reasoning effort.\n     */\n    \"reasoning_effort\": S.optionalWith(FineTuneReinforcementHyperparametersReasoningEffort, {\n      nullable: true,\n      default: () => \"default\" as const\n    }),\n    /**\n     * Multiplier on amount of compute used for exploring search space during training.\n     */\n    \"compute_multiplier\": S.optionalWith(\n      S.Union(\n        FineTuneReinforcementHyperparametersComputeMultiplierEnum,\n        S.Number.pipe(S.greaterThan(0.00001), S.lessThanOrEqualTo(10))\n      ),\n      { nullable: true }\n    ),\n    /**\n     * The number of training steps between evaluation runs.\n     */\n    \"eval_interval\": S.optionalWith(\n      S.Union(FineTuneReinforcementHyperparametersEvalIntervalEnum, S.Int.pipe(S.greaterThanOrEqualTo(1))),\n      {\n        nullable: true,\n        default: () => \"auto\" as const\n      }\n    ),\n    /**\n     * Number of evaluation samples to generate per training step.\n     */\n    \"eval_samples\": S.optionalWith(\n      S.Union(FineTuneReinforcementHyperparametersEvalSamplesEnum, S.Int.pipe(S.greaterThanOrEqualTo(1))),\n      {\n        nullable: true,\n        default: () => \"auto\" as const\n      }\n    )\n  })\n{}\n\n/**\n * Configuration for the reinforcement fine-tuning method.\n */\nexport class FineTuneReinforcementMethod extends S.Class<FineTuneReinforcementMethod>(\"FineTuneReinforcementMethod\")({\n  /**\n   * The grader used for the fine-tuning job.\n   */\n  \"grader\": S.Record({ key: S.String, value: S.Unknown }),\n  \"hyperparameters\": S.optionalWith(FineTuneReinforcementHyperparameters, { nullable: true })\n}) {}\n\n/**\n * The method used for fine-tuning.\n */\nexport class FineTuneMethod extends S.Class<FineTuneMethod>(\"FineTuneMethod\")({\n  /**\n   * The type of method. Is either `supervised`, `dpo`, or `reinforcement`.\n   */\n  \"type\": FineTuneMethodType,\n  \"supervised\": S.optionalWith(FineTuneSupervisedMethod, { nullable: true }),\n  \"dpo\": S.optionalWith(FineTuneDPOMethod, { nullable: true }),\n  \"reinforcement\": S.optionalWith(FineTuneReinforcementMethod, { nullable: true })\n}) {}\n\n/**\n * The `fine_tuning.job` object represents a fine-tuning job that has been created through the API.\n */\nexport class FineTuningJob extends S.Class<FineTuningJob>(\"FineTuningJob\")({\n  /**\n   * The object identifier, which can be referenced in the API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The Unix timestamp (in seconds) for when the fine-tuning job was created.\n   */\n  \"created_at\": S.Int,\n  \"error\": S.NullOr(S.Struct({\n    /**\n     * A machine-readable error code.\n     */\n    \"code\": S.String,\n    /**\n     * A human-readable error message.\n     */\n    \"message\": S.String,\n    \"param\": S.NullOr(S.String)\n  })),\n  \"fine_tuned_model\": S.NullOr(S.String),\n  \"finished_at\": S.NullOr(S.Int),\n  /**\n   * The hyperparameters used for the fine-tuning job. This value will only be returned when running `supervised` jobs.\n   */\n  \"hyperparameters\": S.Struct({\n    \"batch_size\": S.optionalWith(\n      S.Union(\n        FineTuningJobHyperparametersBatchSizeEnum,\n        S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(256))\n      ),\n      { nullable: true }\n    ),\n    /**\n     * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\n     * overfitting.\n     */\n    \"learning_rate_multiplier\": S.optionalWith(\n      S.Union(FineTuningJobHyperparametersLearningRateMultiplierEnum, S.Number.pipe(S.greaterThan(0))),\n      { nullable: true }\n    ),\n    /**\n     * The number of epochs to train the model for. An epoch refers to one full cycle\n     * through the training dataset.\n     */\n    \"n_epochs\": S.optionalWith(\n      S.Union(FineTuningJobHyperparametersNEpochsEnum, S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(50))),\n      {\n        nullable: true,\n        default: () => \"auto\" as const\n      }\n    )\n  }),\n  /**\n   * The base model that is being fine-tuned.\n   */\n  \"model\": S.String,\n  /**\n   * The object type, which is always \"fine_tuning.job\".\n   */\n  \"object\": FineTuningJobObject,\n  /**\n   * The organization that owns the fine-tuning job.\n   */\n  \"organization_id\": S.String,\n  /**\n   * The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents).\n   */\n  \"result_files\": S.Array(S.String),\n  /**\n   * The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`.\n   */\n  \"status\": FineTuningJobStatus,\n  \"trained_tokens\": S.NullOr(S.Int),\n  /**\n   * The file ID used for training. You can retrieve the training data with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents).\n   */\n  \"training_file\": S.String,\n  \"validation_file\": S.NullOr(S.String),\n  \"integrations\": S.optionalWith(S.Array(FineTuningIntegration).pipe(S.maxItems(5)), { nullable: true }),\n  /**\n   * The seed used for the fine-tuning job.\n   */\n  \"seed\": S.Int,\n  \"estimated_finish\": S.optionalWith(S.Int, { nullable: true }),\n  \"method\": S.optionalWith(FineTuneMethod, { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class ListPaginatedFineTuningJobsResponseObject extends S.Literal(\"list\") {}\n\nexport class ListPaginatedFineTuningJobsResponse\n  extends S.Class<ListPaginatedFineTuningJobsResponse>(\"ListPaginatedFineTuningJobsResponse\")({\n    \"data\": S.Array(FineTuningJob),\n    \"has_more\": S.Boolean,\n    \"object\": ListPaginatedFineTuningJobsResponseObject\n  })\n{}\n\nexport class CreateFineTuningJobRequestModelEnum\n  extends S.Literal(\"babbage-002\", \"davinci-002\", \"gpt-3.5-turbo\", \"gpt-4o-mini\")\n{}\n\nexport class CreateFineTuningJobRequestHyperparametersBatchSizeEnum extends S.Literal(\"auto\") {}\n\nexport class CreateFineTuningJobRequestHyperparametersLearningRateMultiplierEnum extends S.Literal(\"auto\") {}\n\nexport class CreateFineTuningJobRequestHyperparametersNEpochsEnum extends S.Literal(\"auto\") {}\n\nexport class CreateFineTuningJobRequest extends S.Class<CreateFineTuningJobRequest>(\"CreateFineTuningJobRequest\")({\n  /**\n   * The name of the model to fine-tune. You can select one of the\n   * [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned).\n   */\n  \"model\": S.Union(S.String, CreateFineTuningJobRequestModelEnum),\n  /**\n   * The ID of an uploaded file that contains training data.\n   *\n   * See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file.\n   *\n   * Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`.\n   *\n   * The contents of the file should differ depending on if the model uses the [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) format, or if the fine-tuning method uses the [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) format.\n   *\n   * See the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details.\n   */\n  \"training_file\": S.String,\n  /**\n   * The hyperparameters used for the fine-tuning job.\n   * This value is now deprecated in favor of `method`, and should be passed in under the `method` parameter.\n   */\n  \"hyperparameters\": S.optionalWith(\n    S.Struct({\n      /**\n       * Number of examples in each batch. A larger batch size means that model parameters\n       * are updated less frequently, but with lower variance.\n       */\n      \"batch_size\": S.optionalWith(\n        S.Union(\n          CreateFineTuningJobRequestHyperparametersBatchSizeEnum,\n          S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(256))\n        ),\n        { nullable: true, default: () => \"auto\" as const }\n      ),\n      /**\n       * Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\n       * overfitting.\n       */\n      \"learning_rate_multiplier\": S.optionalWith(\n        S.Union(CreateFineTuningJobRequestHyperparametersLearningRateMultiplierEnum, S.Number.pipe(S.greaterThan(0))),\n        { nullable: true }\n      ),\n      /**\n       * The number of epochs to train the model for. An epoch refers to one full cycle\n       * through the training dataset.\n       */\n      \"n_epochs\": S.optionalWith(\n        S.Union(\n          CreateFineTuningJobRequestHyperparametersNEpochsEnum,\n          S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(50))\n        ),\n        { nullable: true, default: () => \"auto\" as const }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * A string of up to 64 characters that will be added to your fine-tuned model name.\n   *\n   * For example, a `suffix` of \"custom-model-name\" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`.\n   */\n  \"suffix\": S.optionalWith(S.NullOr(S.String.pipe(S.minLength(1), S.maxLength(64))), { default: () => null }),\n  /**\n   * The ID of an uploaded file that contains validation data.\n   *\n   * If you provide this file, the data is used to generate validation\n   * metrics periodically during fine-tuning. These metrics can be viewed in\n   * the fine-tuning results file.\n   * The same data should not be present in both train and validation files.\n   *\n   * Your dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`.\n   *\n   * See the [fine-tuning guide](https://platform.openai.com/docs/guides/model-optimization) for more details.\n   */\n  \"validation_file\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * A list of integrations to enable for your fine-tuning job.\n   */\n  \"integrations\": S.optionalWith(\n    S.Array(S.Struct({\n      /**\n       * The type of integration to enable. Currently, only \"wandb\" (Weights and Biases) is supported.\n       */\n      \"type\": S.Literal(\"wandb\"),\n      /**\n       * The settings for your integration with Weights and Biases. This payload specifies the project that\n       * metrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\n       * to your run, and set a default entity (team, username, etc) to be associated with your run.\n       */\n      \"wandb\": S.Struct({\n        /**\n         * The name of the project that the new run will be created under.\n         */\n        \"project\": S.String,\n        /**\n         * A display name to set for the run. If not set, we will use the Job ID as the name.\n         */\n        \"name\": S.optionalWith(S.String, { nullable: true }),\n        /**\n         * The entity to use for the run. This allows you to set the team or username of the WandB user that you would\n         * like associated with the run. If not set, the default entity for the registered WandB API key is used.\n         */\n        \"entity\": S.optionalWith(S.String, { nullable: true }),\n        /**\n         * A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\n         * default tags are generated by OpenAI: \"openai/finetune\", \"openai/{base-model}\", \"openai/{ftjob-abcdef}\".\n         */\n        \"tags\": S.optionalWith(S.Array(S.String), { nullable: true })\n      })\n    })),\n    { nullable: true }\n  ),\n  /**\n   * The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases.\n   * If a seed is not specified, one will be generated for you.\n   */\n  \"seed\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2147483647)), { nullable: true }),\n  \"method\": S.optionalWith(FineTuneMethod, { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class ListFineTuningJobCheckpointsParams extends S.Struct({\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 10 as const })\n}) {}\n\n/**\n * The object type, which is always \"fine_tuning.job.checkpoint\".\n */\nexport class FineTuningJobCheckpointObject extends S.Literal(\"fine_tuning.job.checkpoint\") {}\n\n/**\n * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that is ready to use.\n */\nexport class FineTuningJobCheckpoint extends S.Class<FineTuningJobCheckpoint>(\"FineTuningJobCheckpoint\")({\n  /**\n   * The checkpoint identifier, which can be referenced in the API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The Unix timestamp (in seconds) for when the checkpoint was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The name of the fine-tuned checkpoint model that is created.\n   */\n  \"fine_tuned_model_checkpoint\": S.String,\n  /**\n   * The step number that the checkpoint was created at.\n   */\n  \"step_number\": S.Int,\n  /**\n   * Metrics at the step number during the fine-tuning job.\n   */\n  \"metrics\": S.Struct({\n    \"step\": S.optionalWith(S.Number, { nullable: true }),\n    \"train_loss\": S.optionalWith(S.Number, { nullable: true }),\n    \"train_mean_token_accuracy\": S.optionalWith(S.Number, { nullable: true }),\n    \"valid_loss\": S.optionalWith(S.Number, { nullable: true }),\n    \"valid_mean_token_accuracy\": S.optionalWith(S.Number, { nullable: true }),\n    \"full_valid_loss\": S.optionalWith(S.Number, { nullable: true }),\n    \"full_valid_mean_token_accuracy\": S.optionalWith(S.Number, { nullable: true })\n  }),\n  /**\n   * The name of the fine-tuning job that this checkpoint was created from.\n   */\n  \"fine_tuning_job_id\": S.String,\n  /**\n   * The object type, which is always \"fine_tuning.job.checkpoint\".\n   */\n  \"object\": FineTuningJobCheckpointObject\n}) {}\n\nexport class ListFineTuningJobCheckpointsResponseObject extends S.Literal(\"list\") {}\n\nexport class ListFineTuningJobCheckpointsResponse\n  extends S.Class<ListFineTuningJobCheckpointsResponse>(\"ListFineTuningJobCheckpointsResponse\")({\n    \"data\": S.Array(FineTuningJobCheckpoint),\n    \"object\": ListFineTuningJobCheckpointsResponseObject,\n    \"first_id\": S.optionalWith(S.String, { nullable: true }),\n    \"last_id\": S.optionalWith(S.String, { nullable: true }),\n    \"has_more\": S.Boolean\n  })\n{}\n\nexport class ListFineTuningEventsParams extends S.Struct({\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const })\n}) {}\n\n/**\n * The object type, which is always \"fine_tuning.job.event\".\n */\nexport class FineTuningJobEventObject extends S.Literal(\"fine_tuning.job.event\") {}\n\n/**\n * The log level of the event.\n */\nexport class FineTuningJobEventLevel extends S.Literal(\"info\", \"warn\", \"error\") {}\n\n/**\n * The type of event.\n */\nexport class FineTuningJobEventType extends S.Literal(\"message\", \"metrics\") {}\n\n/**\n * Fine-tuning job event object\n */\nexport class FineTuningJobEvent extends S.Class<FineTuningJobEvent>(\"FineTuningJobEvent\")({\n  /**\n   * The object type, which is always \"fine_tuning.job.event\".\n   */\n  \"object\": FineTuningJobEventObject,\n  /**\n   * The object identifier.\n   */\n  \"id\": S.String,\n  /**\n   * The Unix timestamp (in seconds) for when the fine-tuning job was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The log level of the event.\n   */\n  \"level\": FineTuningJobEventLevel,\n  /**\n   * The message of the event.\n   */\n  \"message\": S.String,\n  /**\n   * The type of event.\n   */\n  \"type\": S.optionalWith(FineTuningJobEventType, { nullable: true }),\n  /**\n   * The data associated with the event.\n   */\n  \"data\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class ListFineTuningJobEventsResponseObject extends S.Literal(\"list\") {}\n\nexport class ListFineTuningJobEventsResponse\n  extends S.Class<ListFineTuningJobEventsResponse>(\"ListFineTuningJobEventsResponse\")({\n    \"data\": S.Array(FineTuningJobEvent),\n    \"object\": ListFineTuningJobEventsResponseObject,\n    \"has_more\": S.Boolean\n  })\n{}\n\n/**\n * Allows to set transparency for the background of the generated image(s).\n * This parameter is only supported for `gpt-image-1`. Must be one of\n * `transparent`, `opaque` or `auto` (default value). When `auto` is used, the\n * model will automatically determine the best background for the image.\n *\n * If `transparent`, the output format needs to support transparency, so it\n * should be set to either `png` (default value) or `webp`.\n */\nexport class CreateImageEditRequestBackground extends S.Literal(\"transparent\", \"opaque\", \"auto\") {}\n\nexport class CreateImageEditRequestModelEnum extends S.Literal(\"dall-e-2\", \"gpt-image-1\", \"gpt-image-1-mini\") {}\n\n/**\n * The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`.\n */\nexport class CreateImageEditRequestSize\n  extends S.Literal(\"256x256\", \"512x512\", \"1024x1024\", \"1536x1024\", \"1024x1536\", \"auto\")\n{}\n\n/**\n * The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` will always return base64-encoded images.\n */\nexport class CreateImageEditRequestResponseFormat extends S.Literal(\"url\", \"b64_json\") {}\n\n/**\n * The format in which the generated images are returned. This parameter is\n * only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.\n * The default value is `png`.\n */\nexport class CreateImageEditRequestOutputFormat extends S.Literal(\"png\", \"jpeg\", \"webp\") {}\n\nexport class PartialImages extends S.Union(\n  /**\n   * The number of partial images to generate. This parameter is used for\n   * streaming responses that return partial images. Value must be between 0 and 3.\n   * When set to 0, the response will be a single image sent in one streaming event.\n   *\n   * Note that the final image may be sent before the full number of partial images\n   * are generated if the full image is generated more quickly.\n   */\n  S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(3)),\n  S.Null\n) {}\n\n/**\n * The quality of the image that will be generated. `high`, `medium` and `low` are only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. Defaults to `auto`.\n */\nexport class CreateImageEditRequestQuality extends S.Literal(\"standard\", \"low\", \"medium\", \"high\", \"auto\") {}\n\nexport class CreateImageEditRequest extends S.Class<CreateImageEditRequest>(\"CreateImageEditRequest\")({\n  /**\n   * The image(s) to edit. Must be a supported image file or an array of images.\n   *\n   * For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less\n   * than 50MB. You can provide up to 16 images.\n   *\n   * For `dall-e-2`, you can only provide one image, and it should be a square\n   * `png` file less than 4MB.\n   */\n  \"image\": S.Union(S.instanceOf(globalThis.Blob), S.Array(S.instanceOf(globalThis.Blob)).pipe(S.maxItems(16))),\n  /**\n   * A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for `gpt-image-1`.\n   */\n  \"prompt\": S.String,\n  /**\n   * An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. If there are multiple images provided, the mask will be applied on the first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`.\n   */\n  \"mask\": S.optionalWith(S.instanceOf(globalThis.Blob), { nullable: true }),\n  /**\n   * Allows to set transparency for the background of the generated image(s).\n   * This parameter is only supported for `gpt-image-1`. Must be one of\n   * `transparent`, `opaque` or `auto` (default value). When `auto` is used, the\n   * model will automatically determine the best background for the image.\n   *\n   * If `transparent`, the output format needs to support transparency, so it\n   * should be set to either `png` (default value) or `webp`.\n   */\n  \"background\": S.optionalWith(CreateImageEditRequestBackground, { nullable: true, default: () => \"auto\" as const }),\n  /**\n   * The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used.\n   */\n  \"model\": S.optionalWith(S.Union(S.String, CreateImageEditRequestModelEnum), { nullable: true }),\n  /**\n   * The number of images to generate. Must be between 1 and 10.\n   */\n  \"n\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(10)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`.\n   */\n  \"size\": S.optionalWith(CreateImageEditRequestSize, { nullable: true, default: () => \"1024x1024\" as const }),\n  /**\n   * The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` will always return base64-encoded images.\n   */\n  \"response_format\": S.optionalWith(CreateImageEditRequestResponseFormat, {\n    nullable: true,\n    default: () => \"url\" as const\n  }),\n  /**\n   * The format in which the generated images are returned. This parameter is\n   * only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.\n   * The default value is `png`.\n   */\n  \"output_format\": S.optionalWith(CreateImageEditRequestOutputFormat, {\n    nullable: true,\n    default: () => \"png\" as const\n  }),\n  /**\n   * The compression level (0-100%) for the generated images. This parameter\n   * is only supported for `gpt-image-1` with the `webp` or `jpeg` output\n   * formats, and defaults to 100.\n   */\n  \"output_compression\": S.optionalWith(S.Int, { nullable: true, default: () => 100 as const }),\n  /**\n   * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n   */\n  \"user\": S.optionalWith(S.String, { nullable: true }),\n  \"input_fidelity\": S.optionalWith(InputFidelity, { nullable: true }),\n  /**\n   * Edit the image in streaming mode. Defaults to `false`. See the\n   * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information.\n   */\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  \"partial_images\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(3)), { nullable: true }),\n  /**\n   * The quality of the image that will be generated. `high`, `medium` and `low` are only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. Defaults to `auto`.\n   */\n  \"quality\": S.optionalWith(CreateImageEditRequestQuality, { nullable: true, default: () => \"auto\" as const })\n}) {}\n\n/**\n * Represents the content or the URL of an image generated by the OpenAI API.\n */\nexport class Image extends S.Class<Image>(\"Image\")({\n  /**\n   * The base64-encoded JSON of the generated image. Default value for `gpt-image-1`, and only present if `response_format` is set to `b64_json` for `dall-e-2` and `dall-e-3`.\n   */\n  \"b64_json\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * When using `dall-e-2` or `dall-e-3`, the URL of the generated image if `response_format` is set to `url` (default value). Unsupported for `gpt-image-1`.\n   */\n  \"url\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * For `dall-e-3` only, the revised prompt that was used to generate the image.\n   */\n  \"revised_prompt\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The background parameter used for the image generation. Either `transparent` or `opaque`.\n */\nexport class ImagesResponseBackground extends S.Literal(\"transparent\", \"opaque\") {}\n\n/**\n * The output format of the image generation. Either `png`, `webp`, or `jpeg`.\n */\nexport class ImagesResponseOutputFormat extends S.Literal(\"png\", \"webp\", \"jpeg\") {}\n\n/**\n * The size of the image generated. Either `1024x1024`, `1024x1536`, or `1536x1024`.\n */\nexport class ImagesResponseSize extends S.Literal(\"1024x1024\", \"1024x1536\", \"1536x1024\") {}\n\n/**\n * The quality of the image generated. Either `low`, `medium`, or `high`.\n */\nexport class ImagesResponseQuality extends S.Literal(\"low\", \"medium\", \"high\") {}\n\n/**\n * The input tokens detailed information for the image generation.\n */\nexport class ImageGenInputUsageDetails extends S.Class<ImageGenInputUsageDetails>(\"ImageGenInputUsageDetails\")({\n  /**\n   * The number of text tokens in the input prompt.\n   */\n  \"text_tokens\": S.Int,\n  /**\n   * The number of image tokens in the input prompt.\n   */\n  \"image_tokens\": S.Int\n}) {}\n\n/**\n * For `gpt-image-1` only, the token usage information for the image generation.\n */\nexport class ImageGenUsage extends S.Class<ImageGenUsage>(\"ImageGenUsage\")({\n  /**\n   * The number of tokens (images and text) in the input prompt.\n   */\n  \"input_tokens\": S.Int,\n  /**\n   * The total number of tokens (images and text) used for the image generation.\n   */\n  \"total_tokens\": S.Int,\n  /**\n   * The number of output tokens generated by the model.\n   */\n  \"output_tokens\": S.Int,\n  \"input_tokens_details\": ImageGenInputUsageDetails\n}) {}\n\n/**\n * The response from the image generation endpoint.\n */\nexport class ImagesResponse extends S.Class<ImagesResponse>(\"ImagesResponse\")({\n  /**\n   * The Unix timestamp (in seconds) of when the image was created.\n   */\n  \"created\": S.Int,\n  /**\n   * The list of generated images.\n   */\n  \"data\": S.optionalWith(S.Array(Image), { nullable: true }),\n  /**\n   * The background parameter used for the image generation. Either `transparent` or `opaque`.\n   */\n  \"background\": S.optionalWith(ImagesResponseBackground, { nullable: true }),\n  /**\n   * The output format of the image generation. Either `png`, `webp`, or `jpeg`.\n   */\n  \"output_format\": S.optionalWith(ImagesResponseOutputFormat, { nullable: true }),\n  /**\n   * The size of the image generated. Either `1024x1024`, `1024x1536`, or `1536x1024`.\n   */\n  \"size\": S.optionalWith(ImagesResponseSize, { nullable: true }),\n  /**\n   * The quality of the image generated. Either `low`, `medium`, or `high`.\n   */\n  \"quality\": S.optionalWith(ImagesResponseQuality, { nullable: true }),\n  \"usage\": S.optionalWith(ImageGenUsage, { nullable: true })\n}) {}\n\nexport class CreateImageRequestModelEnum extends S.Literal(\"dall-e-2\", \"dall-e-3\", \"gpt-image-1\", \"gpt-image-1-mini\") {}\n\n/**\n * The quality of the image that will be generated.\n *\n * - `auto` (default value) will automatically select the best quality for the given model.\n * - `high`, `medium` and `low` are supported for `gpt-image-1`.\n * - `hd` and `standard` are supported for `dall-e-3`.\n * - `standard` is the only option for `dall-e-2`.\n */\nexport class CreateImageRequestQuality extends S.Literal(\"standard\", \"hd\", \"low\", \"medium\", \"high\", \"auto\") {}\n\n/**\n * The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for `gpt-image-1` which will always return base64-encoded images.\n */\nexport class CreateImageRequestResponseFormat extends S.Literal(\"url\", \"b64_json\") {}\n\n/**\n * The format in which the generated images are returned. This parameter is only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.\n */\nexport class CreateImageRequestOutputFormat extends S.Literal(\"png\", \"jpeg\", \"webp\") {}\n\n/**\n * The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`.\n */\nexport class CreateImageRequestSize\n  extends S.Literal(\"auto\", \"1024x1024\", \"1536x1024\", \"1024x1536\", \"256x256\", \"512x512\", \"1792x1024\", \"1024x1792\")\n{}\n\n/**\n * Control the content-moderation level for images generated by `gpt-image-1`. Must be either `low` for less restrictive filtering or `auto` (default value).\n */\nexport class CreateImageRequestModeration extends S.Literal(\"low\", \"auto\") {}\n\n/**\n * Allows to set transparency for the background of the generated image(s).\n * This parameter is only supported for `gpt-image-1`. Must be one of\n * `transparent`, `opaque` or `auto` (default value). When `auto` is used, the\n * model will automatically determine the best background for the image.\n *\n * If `transparent`, the output format needs to support transparency, so it\n * should be set to either `png` (default value) or `webp`.\n */\nexport class CreateImageRequestBackground extends S.Literal(\"transparent\", \"opaque\", \"auto\") {}\n\n/**\n * The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images.\n */\nexport class CreateImageRequestStyle extends S.Literal(\"vivid\", \"natural\") {}\n\nexport class CreateImageRequest extends S.Class<CreateImageRequest>(\"CreateImageRequest\")({\n  /**\n   * A text description of the desired image(s). The maximum length is 32000 characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`.\n   */\n  \"prompt\": S.String,\n  /**\n   * The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` is used.\n   */\n  \"model\": S.optionalWith(S.Union(S.String, CreateImageRequestModelEnum), { nullable: true }),\n  /**\n   * The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported.\n   */\n  \"n\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(10)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * The quality of the image that will be generated.\n   *\n   * - `auto` (default value) will automatically select the best quality for the given model.\n   * - `high`, `medium` and `low` are supported for `gpt-image-1`.\n   * - `hd` and `standard` are supported for `dall-e-3`.\n   * - `standard` is the only option for `dall-e-2`.\n   */\n  \"quality\": S.optionalWith(CreateImageRequestQuality, { nullable: true, default: () => \"auto\" as const }),\n  /**\n   * The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for `gpt-image-1` which will always return base64-encoded images.\n   */\n  \"response_format\": S.optionalWith(CreateImageRequestResponseFormat, {\n    nullable: true,\n    default: () => \"url\" as const\n  }),\n  /**\n   * The format in which the generated images are returned. This parameter is only supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.\n   */\n  \"output_format\": S.optionalWith(CreateImageRequestOutputFormat, { nullable: true, default: () => \"png\" as const }),\n  /**\n   * The compression level (0-100%) for the generated images. This parameter is only supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and defaults to 100.\n   */\n  \"output_compression\": S.optionalWith(S.Int, { nullable: true, default: () => 100 as const }),\n  /**\n   * Generate the image in streaming mode. Defaults to `false`. See the\n   * [Image generation guide](https://platform.openai.com/docs/guides/image-generation) for more information.\n   * This parameter is only supported for `gpt-image-1`.\n   */\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  \"partial_images\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(3)), { nullable: true }),\n  /**\n   * The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default value) for `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`.\n   */\n  \"size\": S.optionalWith(CreateImageRequestSize, { nullable: true, default: () => \"auto\" as const }),\n  /**\n   * Control the content-moderation level for images generated by `gpt-image-1`. Must be either `low` for less restrictive filtering or `auto` (default value).\n   */\n  \"moderation\": S.optionalWith(CreateImageRequestModeration, { nullable: true, default: () => \"auto\" as const }),\n  /**\n   * Allows to set transparency for the background of the generated image(s).\n   * This parameter is only supported for `gpt-image-1`. Must be one of\n   * `transparent`, `opaque` or `auto` (default value). When `auto` is used, the\n   * model will automatically determine the best background for the image.\n   *\n   * If `transparent`, the output format needs to support transparency, so it\n   * should be set to either `png` (default value) or `webp`.\n   */\n  \"background\": S.optionalWith(CreateImageRequestBackground, { nullable: true, default: () => \"auto\" as const }),\n  /**\n   * The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images.\n   */\n  \"style\": S.optionalWith(CreateImageRequestStyle, { nullable: true, default: () => \"vivid\" as const }),\n  /**\n   * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n   */\n  \"user\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class CreateImageVariationRequestModelEnum extends S.Literal(\"dall-e-2\") {}\n\n/**\n * The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated.\n */\nexport class CreateImageVariationRequestResponseFormat extends S.Literal(\"url\", \"b64_json\") {}\n\n/**\n * The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`.\n */\nexport class CreateImageVariationRequestSize extends S.Literal(\"256x256\", \"512x512\", \"1024x1024\") {}\n\nexport class CreateImageVariationRequest extends S.Class<CreateImageVariationRequest>(\"CreateImageVariationRequest\")({\n  /**\n   * The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.\n   */\n  \"image\": S.instanceOf(globalThis.Blob),\n  /**\n   * The model to use for image generation. Only `dall-e-2` is supported at this time.\n   */\n  \"model\": S.optionalWith(S.Union(S.String, CreateImageVariationRequestModelEnum), { nullable: true }),\n  /**\n   * The number of images to generate. Must be between 1 and 10.\n   */\n  \"n\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(10)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated.\n   */\n  \"response_format\": S.optionalWith(CreateImageVariationRequestResponseFormat, {\n    nullable: true,\n    default: () => \"url\" as const\n  }),\n  /**\n   * The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`.\n   */\n  \"size\": S.optionalWith(CreateImageVariationRequestSize, { nullable: true, default: () => \"1024x1024\" as const }),\n  /**\n   * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).\n   */\n  \"user\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListModelsResponseObject extends S.Literal(\"list\") {}\n\n/**\n * The object type, which is always \"model\".\n */\nexport class ModelObject extends S.Literal(\"model\") {}\n\n/**\n * Describes an OpenAI model offering that can be used with the API.\n */\nexport class Model extends S.Class<Model>(\"Model\")({\n  /**\n   * The model identifier, which can be referenced in the API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The Unix timestamp (in seconds) when the model was created.\n   */\n  \"created\": S.Int,\n  /**\n   * The object type, which is always \"model\".\n   */\n  \"object\": ModelObject,\n  /**\n   * The organization that owns the model.\n   */\n  \"owned_by\": S.String\n}) {}\n\nexport class ListModelsResponse extends S.Class<ListModelsResponse>(\"ListModelsResponse\")({\n  \"object\": ListModelsResponseObject,\n  \"data\": S.Array(Model)\n}) {}\n\nexport class DeleteModelResponse extends S.Class<DeleteModelResponse>(\"DeleteModelResponse\")({\n  \"id\": S.String,\n  \"deleted\": S.Boolean,\n  \"object\": S.String\n}) {}\n\n/**\n * Always `image_url`.\n */\nexport class ModerationImageURLInputType extends S.Literal(\"image_url\") {}\n\n/**\n * An object describing an image to classify.\n */\nexport class ModerationImageURLInput extends S.Class<ModerationImageURLInput>(\"ModerationImageURLInput\")({\n  /**\n   * Always `image_url`.\n   */\n  \"type\": ModerationImageURLInputType,\n  /**\n   * Contains either an image URL or a data URL for a base64 encoded image.\n   */\n  \"image_url\": S.Struct({\n    /**\n     * Either a URL of the image or the base64 encoded image data.\n     */\n    \"url\": S.String\n  })\n}) {}\n\n/**\n * Always `text`.\n */\nexport class ModerationTextInputType extends S.Literal(\"text\") {}\n\n/**\n * An object describing text to classify.\n */\nexport class ModerationTextInput extends S.Class<ModerationTextInput>(\"ModerationTextInput\")({\n  /**\n   * Always `text`.\n   */\n  \"type\": ModerationTextInputType,\n  /**\n   * A string of text to classify.\n   */\n  \"text\": S.String\n}) {}\n\nexport class CreateModerationRequestModelEnum extends S.Literal(\n  \"omni-moderation-latest\",\n  \"omni-moderation-2024-09-26\",\n  \"text-moderation-latest\",\n  \"text-moderation-stable\"\n) {}\n\nexport class CreateModerationRequest extends S.Class<CreateModerationRequest>(\"CreateModerationRequest\")({\n  /**\n   * Input (or inputs) to classify. Can be a single string, an array of strings, or\n   * an array of multi-modal input objects similar to other models.\n   */\n  \"input\": S.Union(\n    /**\n     * A string of text to classify for moderation.\n     */\n    S.String,\n    /**\n     * An array of strings to classify for moderation.\n     */\n    S.Array(S.String),\n    /**\n     * An array of multi-modal inputs to the moderation model.\n     */\n    S.Array(S.Union(ModerationImageURLInput, ModerationTextInput))\n  ),\n  /**\n   * The content moderation model you would like to use. Learn more in\n   * [the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about\n   * available models [here](https://platform.openai.com/docs/models#moderation).\n   */\n  \"model\": S.optionalWith(S.Union(S.String, CreateModerationRequestModelEnum), { nullable: true })\n}) {}\n\n/**\n * Represents if a given text input is potentially harmful.\n */\nexport class CreateModerationResponse extends S.Class<CreateModerationResponse>(\"CreateModerationResponse\")({\n  /**\n   * The unique identifier for the moderation request.\n   */\n  \"id\": S.String,\n  /**\n   * The model used to generate the moderation results.\n   */\n  \"model\": S.String,\n  /**\n   * A list of moderation objects.\n   */\n  \"results\": S.Array(S.Struct({\n    /**\n     * Whether any of the below categories are flagged.\n     */\n    \"flagged\": S.Boolean,\n    /**\n     * A list of the categories, and whether they are flagged or not.\n     */\n    \"categories\": S.Struct({\n      /**\n       * Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment.\n       */\n      \"hate\": S.Boolean,\n      /**\n       * Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste.\n       */\n      \"hate/threatening\": S.Boolean,\n      /**\n       * Content that expresses, incites, or promotes harassing language towards any target.\n       */\n      \"harassment\": S.Boolean,\n      /**\n       * Harassment content that also includes violence or serious harm towards any target.\n       */\n      \"harassment/threatening\": S.Boolean,\n      \"illicit\": S.NullOr(S.Boolean),\n      \"illicit/violent\": S.NullOr(S.Boolean),\n      /**\n       * Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders.\n       */\n      \"self-harm\": S.Boolean,\n      /**\n       * Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders.\n       */\n      \"self-harm/intent\": S.Boolean,\n      /**\n       * Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts.\n       */\n      \"self-harm/instructions\": S.Boolean,\n      /**\n       * Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness).\n       */\n      \"sexual\": S.Boolean,\n      /**\n       * Sexual content that includes an individual who is under 18 years old.\n       */\n      \"sexual/minors\": S.Boolean,\n      /**\n       * Content that depicts death, violence, or physical injury.\n       */\n      \"violence\": S.Boolean,\n      /**\n       * Content that depicts death, violence, or physical injury in graphic detail.\n       */\n      \"violence/graphic\": S.Boolean\n    }),\n    /**\n     * A list of the categories along with their scores as predicted by model.\n     */\n    \"category_scores\": S.Struct({\n      /**\n       * The score for the category 'hate'.\n       */\n      \"hate\": S.Number,\n      /**\n       * The score for the category 'hate/threatening'.\n       */\n      \"hate/threatening\": S.Number,\n      /**\n       * The score for the category 'harassment'.\n       */\n      \"harassment\": S.Number,\n      /**\n       * The score for the category 'harassment/threatening'.\n       */\n      \"harassment/threatening\": S.Number,\n      /**\n       * The score for the category 'illicit'.\n       */\n      \"illicit\": S.Number,\n      /**\n       * The score for the category 'illicit/violent'.\n       */\n      \"illicit/violent\": S.Number,\n      /**\n       * The score for the category 'self-harm'.\n       */\n      \"self-harm\": S.Number,\n      /**\n       * The score for the category 'self-harm/intent'.\n       */\n      \"self-harm/intent\": S.Number,\n      /**\n       * The score for the category 'self-harm/instructions'.\n       */\n      \"self-harm/instructions\": S.Number,\n      /**\n       * The score for the category 'sexual'.\n       */\n      \"sexual\": S.Number,\n      /**\n       * The score for the category 'sexual/minors'.\n       */\n      \"sexual/minors\": S.Number,\n      /**\n       * The score for the category 'violence'.\n       */\n      \"violence\": S.Number,\n      /**\n       * The score for the category 'violence/graphic'.\n       */\n      \"violence/graphic\": S.Number\n    }),\n    /**\n     * A list of the categories along with the input type(s) that the score applies to.\n     */\n    \"category_applied_input_types\": S.Struct({\n      /**\n       * The applied input type(s) for the category 'hate'.\n       */\n      \"hate\": S.Array(S.Literal(\"text\")),\n      /**\n       * The applied input type(s) for the category 'hate/threatening'.\n       */\n      \"hate/threatening\": S.Array(S.Literal(\"text\")),\n      /**\n       * The applied input type(s) for the category 'harassment'.\n       */\n      \"harassment\": S.Array(S.Literal(\"text\")),\n      /**\n       * The applied input type(s) for the category 'harassment/threatening'.\n       */\n      \"harassment/threatening\": S.Array(S.Literal(\"text\")),\n      /**\n       * The applied input type(s) for the category 'illicit'.\n       */\n      \"illicit\": S.Array(S.Literal(\"text\")),\n      /**\n       * The applied input type(s) for the category 'illicit/violent'.\n       */\n      \"illicit/violent\": S.Array(S.Literal(\"text\")),\n      /**\n       * The applied input type(s) for the category 'self-harm'.\n       */\n      \"self-harm\": S.Array(S.Literal(\"text\", \"image\")),\n      /**\n       * The applied input type(s) for the category 'self-harm/intent'.\n       */\n      \"self-harm/intent\": S.Array(S.Literal(\"text\", \"image\")),\n      /**\n       * The applied input type(s) for the category 'self-harm/instructions'.\n       */\n      \"self-harm/instructions\": S.Array(S.Literal(\"text\", \"image\")),\n      /**\n       * The applied input type(s) for the category 'sexual'.\n       */\n      \"sexual\": S.Array(S.Literal(\"text\", \"image\")),\n      /**\n       * The applied input type(s) for the category 'sexual/minors'.\n       */\n      \"sexual/minors\": S.Array(S.Literal(\"text\")),\n      /**\n       * The applied input type(s) for the category 'violence'.\n       */\n      \"violence\": S.Array(S.Literal(\"text\", \"image\")),\n      /**\n       * The applied input type(s) for the category 'violence/graphic'.\n       */\n      \"violence/graphic\": S.Array(S.Literal(\"text\", \"image\"))\n    })\n  }))\n}) {}\n\n/**\n * Order results by creation time, ascending or descending.\n */\nexport class AdminApiKeysListParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class AdminApiKeysListParams extends S.Struct({\n  /**\n   * Return keys with IDs that come after this ID in the pagination order.\n   */\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Order results by creation time, ascending or descending.\n   */\n  \"order\": S.optionalWith(AdminApiKeysListParamsOrder, { nullable: true, default: () => \"asc\" as const }),\n  /**\n   * Maximum number of keys to return.\n   */\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const })\n}) {}\n\n/**\n * Represents an individual Admin API key in an org.\n */\nexport class AdminApiKey extends S.Class<AdminApiKey>(\"AdminApiKey\")({\n  /**\n   * The object type, which is always `organization.admin_api_key`\n   */\n  \"object\": S.String,\n  /**\n   * The identifier, which can be referenced in API endpoints\n   */\n  \"id\": S.String,\n  /**\n   * The name of the API key\n   */\n  \"name\": S.String,\n  /**\n   * The redacted value of the API key\n   */\n  \"redacted_value\": S.String,\n  /**\n   * The value of the API key. Only shown on create.\n   */\n  \"value\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The Unix timestamp (in seconds) of when the API key was created\n   */\n  \"created_at\": S.Int,\n  \"last_used_at\": S.NullOr(S.Int),\n  \"owner\": S.Struct({\n    /**\n     * Always `user`\n     */\n    \"type\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The object type, which is always organization.user\n     */\n    \"object\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The identifier, which can be referenced in API endpoints\n     */\n    \"id\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The name of the user\n     */\n    \"name\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The Unix timestamp (in seconds) of when the user was created\n     */\n    \"created_at\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * Always `owner`\n     */\n    \"role\": S.optionalWith(S.String, { nullable: true })\n  })\n}) {}\n\nexport class ApiKeyList extends S.Class<ApiKeyList>(\"ApiKeyList\")({\n  \"object\": S.optionalWith(S.String, { nullable: true }),\n  \"data\": S.optionalWith(S.Array(AdminApiKey), { nullable: true }),\n  \"has_more\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"first_id\": S.optionalWith(S.String, { nullable: true }),\n  \"last_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class AdminApiKeysCreateRequest extends S.Class<AdminApiKeysCreateRequest>(\"AdminApiKeysCreateRequest\")({\n  \"name\": S.String\n}) {}\n\nexport class AdminApiKeysDelete200 extends S.Struct({\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  \"object\": S.optionalWith(S.String, { nullable: true }),\n  \"deleted\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * The event type.\n */\nexport class AuditLogEventType extends S.Literal(\n  \"api_key.created\",\n  \"api_key.updated\",\n  \"api_key.deleted\",\n  \"certificate.created\",\n  \"certificate.updated\",\n  \"certificate.deleted\",\n  \"certificates.activated\",\n  \"certificates.deactivated\",\n  \"checkpoint.permission.created\",\n  \"checkpoint.permission.deleted\",\n  \"external_key.registered\",\n  \"external_key.removed\",\n  \"group.created\",\n  \"group.updated\",\n  \"group.deleted\",\n  \"invite.sent\",\n  \"invite.accepted\",\n  \"invite.deleted\",\n  \"ip_allowlist.created\",\n  \"ip_allowlist.updated\",\n  \"ip_allowlist.deleted\",\n  \"ip_allowlist.config.activated\",\n  \"ip_allowlist.config.deactivated\",\n  \"login.succeeded\",\n  \"login.failed\",\n  \"logout.succeeded\",\n  \"logout.failed\",\n  \"organization.updated\",\n  \"project.created\",\n  \"project.updated\",\n  \"project.archived\",\n  \"project.deleted\",\n  \"rate_limit.updated\",\n  \"rate_limit.deleted\",\n  \"resource.deleted\",\n  \"role.created\",\n  \"role.updated\",\n  \"role.deleted\",\n  \"role.assignment.created\",\n  \"role.assignment.deleted\",\n  \"scim.enabled\",\n  \"scim.disabled\",\n  \"service_account.created\",\n  \"service_account.updated\",\n  \"service_account.deleted\",\n  \"user.added\",\n  \"user.updated\",\n  \"user.deleted\"\n) {}\n\nexport class ListAuditLogsParams extends S.Struct({\n  /**\n   * Return only events whose `effective_at` (Unix seconds) is greater than this value.\n   */\n  \"effective_at[gt]\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Return only events whose `effective_at` (Unix seconds) is greater than or equal to this value.\n   */\n  \"effective_at[gte]\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Return only events whose `effective_at` (Unix seconds) is less than this value.\n   */\n  \"effective_at[lt]\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * Return only events whose `effective_at` (Unix seconds) is less than or equal to this value.\n   */\n  \"effective_at[lte]\": S.optionalWith(S.Int, { nullable: true }),\n  \"project_ids[]\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"event_types[]\": S.optionalWith(S.Array(AuditLogEventType), { nullable: true }),\n  \"actor_ids[]\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"actor_emails[]\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"resource_ids[]\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"before\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListAuditLogsResponseObject extends S.Literal(\"list\") {}\n\n/**\n * The type of actor. Is either `session` or `api_key`.\n */\nexport class AuditLogActorType extends S.Literal(\"session\", \"api_key\") {}\n\n/**\n * The user who performed the audit logged action.\n */\nexport class AuditLogActorUser extends S.Class<AuditLogActorUser>(\"AuditLogActorUser\")({\n  /**\n   * The user id.\n   */\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The user email.\n   */\n  \"email\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The session in which the audit logged action was performed.\n */\nexport class AuditLogActorSession extends S.Class<AuditLogActorSession>(\"AuditLogActorSession\")({\n  \"user\": S.optionalWith(AuditLogActorUser, { nullable: true }),\n  /**\n   * The IP address from which the action was performed.\n   */\n  \"ip_address\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The type of API key. Can be either `user` or `service_account`.\n */\nexport class AuditLogActorApiKeyType extends S.Literal(\"user\", \"service_account\") {}\n\n/**\n * The service account that performed the audit logged action.\n */\nexport class AuditLogActorServiceAccount extends S.Class<AuditLogActorServiceAccount>(\"AuditLogActorServiceAccount\")({\n  /**\n   * The service account id.\n   */\n  \"id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The API Key used to perform the audit logged action.\n */\nexport class AuditLogActorApiKey extends S.Class<AuditLogActorApiKey>(\"AuditLogActorApiKey\")({\n  /**\n   * The tracking id of the API key.\n   */\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The type of API key. Can be either `user` or `service_account`.\n   */\n  \"type\": S.optionalWith(AuditLogActorApiKeyType, { nullable: true }),\n  \"user\": S.optionalWith(AuditLogActorUser, { nullable: true }),\n  \"service_account\": S.optionalWith(AuditLogActorServiceAccount, { nullable: true })\n}) {}\n\n/**\n * The actor who performed the audit logged action.\n */\nexport class AuditLogActor extends S.Class<AuditLogActor>(\"AuditLogActor\")({\n  /**\n   * The type of actor. Is either `session` or `api_key`.\n   */\n  \"type\": S.optionalWith(AuditLogActorType, { nullable: true }),\n  \"session\": S.optionalWith(AuditLogActorSession, { nullable: true }),\n  \"api_key\": S.optionalWith(AuditLogActorApiKey, { nullable: true })\n}) {}\n\n/**\n * A log of a user action or configuration change within this organization.\n */\nexport class AuditLog extends S.Class<AuditLog>(\"AuditLog\")({\n  /**\n   * The ID of this log.\n   */\n  \"id\": S.String,\n  \"type\": AuditLogEventType,\n  /**\n   * The Unix timestamp (in seconds) of the event.\n   */\n  \"effective_at\": S.Int,\n  /**\n   * The project that the action was scoped to. Absent for actions not scoped to projects. Note that any admin actions taken via Admin API keys are associated with the default project.\n   */\n  \"project\": S.optionalWith(\n    S.Struct({\n      /**\n       * The project ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The project title.\n       */\n      \"name\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"actor\": AuditLogActor,\n  /**\n   * The details for events with this `type`.\n   */\n  \"api_key.created\": S.optionalWith(\n    S.Struct({\n      /**\n       * The tracking ID of the API key.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to create the API key.\n       */\n      \"data\": S.optionalWith(\n        S.Struct({\n          /**\n           * A list of scopes allowed for the API key, e.g. `[\"api.model.request\"]`\n           */\n          \"scopes\": S.optionalWith(S.Array(S.String), { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"api_key.updated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The tracking ID of the API key.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to update the API key.\n       */\n      \"changes_requested\": S.optionalWith(\n        S.Struct({\n          /**\n           * A list of scopes allowed for the API key, e.g. `[\"api.model.request\"]`\n           */\n          \"scopes\": S.optionalWith(S.Array(S.String), { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"api_key.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The tracking ID of the API key.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The project and fine-tuned model checkpoint that the checkpoint permission was created for.\n   */\n  \"checkpoint.permission.created\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the checkpoint permission.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to create the checkpoint permission.\n       */\n      \"data\": S.optionalWith(\n        S.Struct({\n          /**\n           * The ID of the project that the checkpoint permission was created for.\n           */\n          \"project_id\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The ID of the fine-tuned model checkpoint.\n           */\n          \"fine_tuned_model_checkpoint\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"checkpoint.permission.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the checkpoint permission.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"external_key.registered\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the external key configuration.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The configuration for the external key.\n       */\n      \"data\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"external_key.removed\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the external key configuration.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"group.created\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the group.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * Information about the created group.\n       */\n      \"data\": S.optionalWith(\n        S.Struct({\n          /**\n           * The group name.\n           */\n          \"group_name\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"group.updated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the group.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to update the group.\n       */\n      \"changes_requested\": S.optionalWith(\n        S.Struct({\n          /**\n           * The updated group name.\n           */\n          \"group_name\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"group.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the group.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"scim.enabled\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the SCIM was enabled for.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"scim.disabled\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the SCIM was disabled for.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"invite.sent\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the invite.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to create the invite.\n       */\n      \"data\": S.optionalWith(\n        S.Struct({\n          /**\n           * The email invited to the organization.\n           */\n          \"email\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The role the email was invited to be. Is either `owner` or `member`.\n           */\n          \"role\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"invite.accepted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the invite.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"invite.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the invite.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"ip_allowlist.created\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the IP allowlist configuration.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The name of the IP allowlist configuration.\n       */\n      \"name\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The IP addresses or CIDR ranges included in the configuration.\n       */\n      \"allowed_ips\": S.optionalWith(S.Array(S.String), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"ip_allowlist.updated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the IP allowlist configuration.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The updated set of IP addresses or CIDR ranges in the configuration.\n       */\n      \"allowed_ips\": S.optionalWith(S.Array(S.String), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"ip_allowlist.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The ID of the IP allowlist configuration.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The name of the IP allowlist configuration.\n       */\n      \"name\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The IP addresses or CIDR ranges that were in the configuration.\n       */\n      \"allowed_ips\": S.optionalWith(S.Array(S.String), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"ip_allowlist.config.activated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The configurations that were activated.\n       */\n      \"configs\": S.optionalWith(\n        S.Array(S.Struct({\n          /**\n           * The ID of the IP allowlist configuration.\n           */\n          \"id\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The name of the IP allowlist configuration.\n           */\n          \"name\": S.optionalWith(S.String, { nullable: true })\n        })),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"ip_allowlist.config.deactivated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The configurations that were deactivated.\n       */\n      \"configs\": S.optionalWith(\n        S.Array(S.Struct({\n          /**\n           * The ID of the IP allowlist configuration.\n           */\n          \"id\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The name of the IP allowlist configuration.\n           */\n          \"name\": S.optionalWith(S.String, { nullable: true })\n        })),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * This event has no additional fields beyond the standard audit log attributes.\n   */\n  \"login.succeeded\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * The details for events with this `type`.\n   */\n  \"login.failed\": S.optionalWith(\n    S.Struct({\n      /**\n       * The error code of the failure.\n       */\n      \"error_code\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The error message of the failure.\n       */\n      \"error_message\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * This event has no additional fields beyond the standard audit log attributes.\n   */\n  \"logout.succeeded\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * The details for events with this `type`.\n   */\n  \"logout.failed\": S.optionalWith(\n    S.Struct({\n      /**\n       * The error code of the failure.\n       */\n      \"error_code\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The error message of the failure.\n       */\n      \"error_message\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"organization.updated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The organization ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to update the organization settings.\n       */\n      \"changes_requested\": S.optionalWith(\n        S.Struct({\n          /**\n           * The organization title.\n           */\n          \"title\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The organization description.\n           */\n          \"description\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The organization name.\n           */\n          \"name\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`.\n           */\n          \"threads_ui_visibility\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`.\n           */\n          \"usage_dashboard_visibility\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * How your organization logs data from supported API calls. One of `disabled`, `enabled_per_call`, `enabled_for_all_projects`, or `enabled_for_selected_projects`\n           */\n          \"api_call_logging\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The list of project ids if api_call_logging is set to `enabled_for_selected_projects`\n           */\n          \"api_call_logging_project_ids\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"project.created\": S.optionalWith(\n    S.Struct({\n      /**\n       * The project ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to create the project.\n       */\n      \"data\": S.optionalWith(\n        S.Struct({\n          /**\n           * The project name.\n           */\n          \"name\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The title of the project as seen on the dashboard.\n           */\n          \"title\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"project.updated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The project ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to update the project.\n       */\n      \"changes_requested\": S.optionalWith(\n        S.Struct({\n          /**\n           * The title of the project as seen on the dashboard.\n           */\n          \"title\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"project.archived\": S.optionalWith(\n    S.Struct({\n      /**\n       * The project ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"project.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The project ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"rate_limit.updated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The rate limit ID\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to update the rate limits.\n       */\n      \"changes_requested\": S.optionalWith(\n        S.Struct({\n          /**\n           * The maximum requests per minute.\n           */\n          \"max_requests_per_1_minute\": S.optionalWith(S.Int, { nullable: true }),\n          /**\n           * The maximum tokens per minute.\n           */\n          \"max_tokens_per_1_minute\": S.optionalWith(S.Int, { nullable: true }),\n          /**\n           * The maximum images per minute. Only relevant for certain models.\n           */\n          \"max_images_per_1_minute\": S.optionalWith(S.Int, { nullable: true }),\n          /**\n           * The maximum audio megabytes per minute. Only relevant for certain models.\n           */\n          \"max_audio_megabytes_per_1_minute\": S.optionalWith(S.Int, { nullable: true }),\n          /**\n           * The maximum requests per day. Only relevant for certain models.\n           */\n          \"max_requests_per_1_day\": S.optionalWith(S.Int, { nullable: true }),\n          /**\n           * The maximum batch input tokens per day. Only relevant for certain models.\n           */\n          \"batch_1_day_max_input_tokens\": S.optionalWith(S.Int, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"rate_limit.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The rate limit ID\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"role.created\": S.optionalWith(\n    S.Struct({\n      /**\n       * The role ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The name of the role.\n       */\n      \"role_name\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The permissions granted by the role.\n       */\n      \"permissions\": S.optionalWith(S.Array(S.String), { nullable: true }),\n      /**\n       * The type of resource the role belongs to.\n       */\n      \"resource_type\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The resource the role is scoped to.\n       */\n      \"resource_id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"role.updated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The role ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to update the role.\n       */\n      \"changes_requested\": S.optionalWith(\n        S.Struct({\n          /**\n           * The updated role name, when provided.\n           */\n          \"role_name\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The resource the role is scoped to.\n           */\n          \"resource_id\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The type of resource the role belongs to.\n           */\n          \"resource_type\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The permissions added to the role.\n           */\n          \"permissions_added\": S.optionalWith(S.Array(S.String), { nullable: true }),\n          /**\n           * The permissions removed from the role.\n           */\n          \"permissions_removed\": S.optionalWith(S.Array(S.String), { nullable: true }),\n          /**\n           * The updated role description, when provided.\n           */\n          \"description\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * Additional metadata stored on the role.\n           */\n          \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"role.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The role ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"role.assignment.created\": S.optionalWith(\n    S.Struct({\n      /**\n       * The identifier of the role assignment.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The principal (user or group) that received the role.\n       */\n      \"principal_id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The type of principal (user or group) that received the role.\n       */\n      \"principal_type\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The resource the role assignment is scoped to.\n       */\n      \"resource_id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The type of resource the role assignment is scoped to.\n       */\n      \"resource_type\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"role.assignment.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The identifier of the role assignment.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The principal (user or group) that had the role removed.\n       */\n      \"principal_id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The type of principal (user or group) that had the role removed.\n       */\n      \"principal_type\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The resource the role assignment was scoped to.\n       */\n      \"resource_id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The type of resource the role assignment was scoped to.\n       */\n      \"resource_type\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"service_account.created\": S.optionalWith(\n    S.Struct({\n      /**\n       * The service account ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to create the service account.\n       */\n      \"data\": S.optionalWith(\n        S.Struct({\n          /**\n           * The role of the service account. Is either `owner` or `member`.\n           */\n          \"role\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"service_account.updated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The service account ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to updated the service account.\n       */\n      \"changes_requested\": S.optionalWith(\n        S.Struct({\n          /**\n           * The role of the service account. Is either `owner` or `member`.\n           */\n          \"role\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"service_account.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The service account ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"user.added\": S.optionalWith(\n    S.Struct({\n      /**\n       * The user ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to add the user to the project.\n       */\n      \"data\": S.optionalWith(\n        S.Struct({\n          /**\n           * The role of the user. Is either `owner` or `member`.\n           */\n          \"role\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"user.updated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The project ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The payload used to update the user.\n       */\n      \"changes_requested\": S.optionalWith(\n        S.Struct({\n          /**\n           * The role of the user. Is either `owner` or `member`.\n           */\n          \"role\": S.optionalWith(S.String, { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"user.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The user ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"certificate.created\": S.optionalWith(\n    S.Struct({\n      /**\n       * The certificate ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The name of the certificate.\n       */\n      \"name\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"certificate.updated\": S.optionalWith(\n    S.Struct({\n      /**\n       * The certificate ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The name of the certificate.\n       */\n      \"name\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"certificate.deleted\": S.optionalWith(\n    S.Struct({\n      /**\n       * The certificate ID.\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The name of the certificate.\n       */\n      \"name\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The certificate content in PEM format.\n       */\n      \"certificate\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"certificates.activated\": S.optionalWith(\n    S.Struct({\n      \"certificates\": S.optionalWith(\n        S.Array(S.Struct({\n          /**\n           * The certificate ID.\n           */\n          \"id\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The name of the certificate.\n           */\n          \"name\": S.optionalWith(S.String, { nullable: true })\n        })),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * The details for events with this `type`.\n   */\n  \"certificates.deactivated\": S.optionalWith(\n    S.Struct({\n      \"certificates\": S.optionalWith(\n        S.Array(S.Struct({\n          /**\n           * The certificate ID.\n           */\n          \"id\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The name of the certificate.\n           */\n          \"name\": S.optionalWith(S.String, { nullable: true })\n        })),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  )\n}) {}\n\nexport class ListAuditLogsResponse extends S.Class<ListAuditLogsResponse>(\"ListAuditLogsResponse\")({\n  \"object\": ListAuditLogsResponseObject,\n  \"data\": S.Array(AuditLog),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\nexport class ListOrganizationCertificatesParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListOrganizationCertificatesParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListOrganizationCertificatesParamsOrder, { nullable: true, default: () => \"desc\" as const })\n}) {}\n\n/**\n * The object type.\n *\n * - If creating, updating, or getting a specific certificate, the object type is `certificate`.\n * - If listing, activating, or deactivating certificates for the organization, the object type is `organization.certificate`.\n * - If listing, activating, or deactivating certificates for a project, the object type is `organization.project.certificate`.\n */\nexport class CertificateObject\n  extends S.Literal(\"certificate\", \"organization.certificate\", \"organization.project.certificate\")\n{}\n\n/**\n * Represents an individual `certificate` uploaded to the organization.\n */\nexport class Certificate extends S.Class<Certificate>(\"Certificate\")({\n  /**\n   * The object type.\n   *\n   * - If creating, updating, or getting a specific certificate, the object type is `certificate`.\n   * - If listing, activating, or deactivating certificates for the organization, the object type is `organization.certificate`.\n   * - If listing, activating, or deactivating certificates for a project, the object type is `organization.project.certificate`.\n   */\n  \"object\": CertificateObject,\n  /**\n   * The identifier, which can be referenced in API endpoints\n   */\n  \"id\": S.String,\n  /**\n   * The name of the certificate.\n   */\n  \"name\": S.String,\n  /**\n   * The Unix timestamp (in seconds) of when the certificate was uploaded.\n   */\n  \"created_at\": S.Int,\n  \"certificate_details\": S.Struct({\n    /**\n     * The Unix timestamp (in seconds) of when the certificate becomes valid.\n     */\n    \"valid_at\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * The Unix timestamp (in seconds) of when the certificate expires.\n     */\n    \"expires_at\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * The content of the certificate in PEM format.\n     */\n    \"content\": S.optionalWith(S.String, { nullable: true })\n  }),\n  /**\n   * Whether the certificate is currently active at the specified scope. Not returned when getting details for a specific certificate.\n   */\n  \"active\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class ListCertificatesResponseObject extends S.Literal(\"list\") {}\n\nexport class ListCertificatesResponse extends S.Class<ListCertificatesResponse>(\"ListCertificatesResponse\")({\n  \"data\": S.Array(Certificate),\n  \"first_id\": S.optionalWith(S.String, { nullable: true }),\n  \"last_id\": S.optionalWith(S.String, { nullable: true }),\n  \"has_more\": S.Boolean,\n  \"object\": ListCertificatesResponseObject\n}) {}\n\nexport class UploadCertificateRequest extends S.Class<UploadCertificateRequest>(\"UploadCertificateRequest\")({\n  /**\n   * An optional name for the certificate\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The certificate content in PEM format\n   */\n  \"content\": S.String\n}) {}\n\nexport class ToggleCertificatesRequest extends S.Class<ToggleCertificatesRequest>(\"ToggleCertificatesRequest\")({\n  \"certificate_ids\": S.NonEmptyArray(S.String).pipe(S.minItems(1), S.maxItems(10))\n}) {}\n\nexport class GetCertificateParams extends S.Struct({\n  \"include\": S.optionalWith(S.Array(S.Literal(\"content\")), { nullable: true })\n}) {}\n\nexport class ModifyCertificateRequest extends S.Class<ModifyCertificateRequest>(\"ModifyCertificateRequest\")({\n  /**\n   * The updated name for the certificate\n   */\n  \"name\": S.String\n}) {}\n\nexport class DeleteCertificateResponse extends S.Class<DeleteCertificateResponse>(\"DeleteCertificateResponse\")({\n  /**\n   * The object type, must be `certificate.deleted`.\n   */\n  \"object\": S.Literal(\"certificate.deleted\"),\n  /**\n   * The ID of the certificate that was deleted.\n   */\n  \"id\": S.String\n}) {}\n\nexport class UsageCostsParamsBucketWidth extends S.Literal(\"1d\") {}\n\nexport class UsageCostsParams extends S.Struct({\n  \"start_time\": S.Int,\n  \"end_time\": S.optionalWith(S.Int, { nullable: true }),\n  \"bucket_width\": S.optionalWith(UsageCostsParamsBucketWidth, { nullable: true, default: () => \"1d\" as const }),\n  \"project_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"group_by\": S.optionalWith(S.Array(S.Literal(\"project_id\", \"line_item\")), { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 7 as const }),\n  \"page\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageResponseObject extends S.Literal(\"page\") {}\n\nexport class UsageTimeBucketObject extends S.Literal(\"bucket\") {}\n\nexport class UsageCompletionsResultObject extends S.Literal(\"organization.usage.completions.result\") {}\n\n/**\n * The aggregated completions usage details of the specific time bucket.\n */\nexport class UsageCompletionsResult extends S.Class<UsageCompletionsResult>(\"UsageCompletionsResult\")({\n  \"object\": UsageCompletionsResultObject,\n  /**\n   * The aggregated number of text input tokens used, including cached tokens. For customers subscribe to scale tier, this includes scale tier tokens.\n   */\n  \"input_tokens\": S.Int,\n  /**\n   * The aggregated number of text input tokens that has been cached from previous requests. For customers subscribe to scale tier, this includes scale tier tokens.\n   */\n  \"input_cached_tokens\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The aggregated number of text output tokens used. For customers subscribe to scale tier, this includes scale tier tokens.\n   */\n  \"output_tokens\": S.Int,\n  /**\n   * The aggregated number of audio input tokens used, including cached tokens.\n   */\n  \"input_audio_tokens\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The aggregated number of audio output tokens used.\n   */\n  \"output_audio_tokens\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The count of requests made to the model.\n   */\n  \"num_model_requests\": S.Int,\n  \"project_id\": S.optionalWith(S.String, { nullable: true }),\n  \"user_id\": S.optionalWith(S.String, { nullable: true }),\n  \"api_key_id\": S.optionalWith(S.String, { nullable: true }),\n  \"model\": S.optionalWith(S.String, { nullable: true }),\n  \"batch\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"service_tier\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageEmbeddingsResultObject extends S.Literal(\"organization.usage.embeddings.result\") {}\n\n/**\n * The aggregated embeddings usage details of the specific time bucket.\n */\nexport class UsageEmbeddingsResult extends S.Class<UsageEmbeddingsResult>(\"UsageEmbeddingsResult\")({\n  \"object\": UsageEmbeddingsResultObject,\n  /**\n   * The aggregated number of input tokens used.\n   */\n  \"input_tokens\": S.Int,\n  /**\n   * The count of requests made to the model.\n   */\n  \"num_model_requests\": S.Int,\n  \"project_id\": S.optionalWith(S.String, { nullable: true }),\n  \"user_id\": S.optionalWith(S.String, { nullable: true }),\n  \"api_key_id\": S.optionalWith(S.String, { nullable: true }),\n  \"model\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageModerationsResultObject extends S.Literal(\"organization.usage.moderations.result\") {}\n\n/**\n * The aggregated moderations usage details of the specific time bucket.\n */\nexport class UsageModerationsResult extends S.Class<UsageModerationsResult>(\"UsageModerationsResult\")({\n  \"object\": UsageModerationsResultObject,\n  /**\n   * The aggregated number of input tokens used.\n   */\n  \"input_tokens\": S.Int,\n  /**\n   * The count of requests made to the model.\n   */\n  \"num_model_requests\": S.Int,\n  \"project_id\": S.optionalWith(S.String, { nullable: true }),\n  \"user_id\": S.optionalWith(S.String, { nullable: true }),\n  \"api_key_id\": S.optionalWith(S.String, { nullable: true }),\n  \"model\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageImagesResultObject extends S.Literal(\"organization.usage.images.result\") {}\n\n/**\n * The aggregated images usage details of the specific time bucket.\n */\nexport class UsageImagesResult extends S.Class<UsageImagesResult>(\"UsageImagesResult\")({\n  \"object\": UsageImagesResultObject,\n  /**\n   * The number of images processed.\n   */\n  \"images\": S.Int,\n  /**\n   * The count of requests made to the model.\n   */\n  \"num_model_requests\": S.Int,\n  \"source\": S.optionalWith(S.String, { nullable: true }),\n  \"size\": S.optionalWith(S.String, { nullable: true }),\n  \"project_id\": S.optionalWith(S.String, { nullable: true }),\n  \"user_id\": S.optionalWith(S.String, { nullable: true }),\n  \"api_key_id\": S.optionalWith(S.String, { nullable: true }),\n  \"model\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageAudioSpeechesResultObject extends S.Literal(\"organization.usage.audio_speeches.result\") {}\n\n/**\n * The aggregated audio speeches usage details of the specific time bucket.\n */\nexport class UsageAudioSpeechesResult extends S.Class<UsageAudioSpeechesResult>(\"UsageAudioSpeechesResult\")({\n  \"object\": UsageAudioSpeechesResultObject,\n  /**\n   * The number of characters processed.\n   */\n  \"characters\": S.Int,\n  /**\n   * The count of requests made to the model.\n   */\n  \"num_model_requests\": S.Int,\n  \"project_id\": S.optionalWith(S.String, { nullable: true }),\n  \"user_id\": S.optionalWith(S.String, { nullable: true }),\n  \"api_key_id\": S.optionalWith(S.String, { nullable: true }),\n  \"model\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageAudioTranscriptionsResultObject extends S.Literal(\"organization.usage.audio_transcriptions.result\") {}\n\n/**\n * The aggregated audio transcriptions usage details of the specific time bucket.\n */\nexport class UsageAudioTranscriptionsResult\n  extends S.Class<UsageAudioTranscriptionsResult>(\"UsageAudioTranscriptionsResult\")({\n    \"object\": UsageAudioTranscriptionsResultObject,\n    /**\n     * The number of seconds processed.\n     */\n    \"seconds\": S.Int,\n    /**\n     * The count of requests made to the model.\n     */\n    \"num_model_requests\": S.Int,\n    \"project_id\": S.optionalWith(S.String, { nullable: true }),\n    \"user_id\": S.optionalWith(S.String, { nullable: true }),\n    \"api_key_id\": S.optionalWith(S.String, { nullable: true }),\n    \"model\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\nexport class UsageVectorStoresResultObject extends S.Literal(\"organization.usage.vector_stores.result\") {}\n\n/**\n * The aggregated vector stores usage details of the specific time bucket.\n */\nexport class UsageVectorStoresResult extends S.Class<UsageVectorStoresResult>(\"UsageVectorStoresResult\")({\n  \"object\": UsageVectorStoresResultObject,\n  /**\n   * The vector stores usage in bytes.\n   */\n  \"usage_bytes\": S.Int,\n  \"project_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageCodeInterpreterSessionsResultObject\n  extends S.Literal(\"organization.usage.code_interpreter_sessions.result\")\n{}\n\n/**\n * The aggregated code interpreter sessions usage details of the specific time bucket.\n */\nexport class UsageCodeInterpreterSessionsResult\n  extends S.Class<UsageCodeInterpreterSessionsResult>(\"UsageCodeInterpreterSessionsResult\")({\n    \"object\": UsageCodeInterpreterSessionsResultObject,\n    /**\n     * The number of code interpreter sessions.\n     */\n    \"num_sessions\": S.optionalWith(S.Int, { nullable: true }),\n    \"project_id\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\nexport class CostsResultObject extends S.Literal(\"organization.costs.result\") {}\n\n/**\n * The aggregated costs details of the specific time bucket.\n */\nexport class CostsResult extends S.Class<CostsResult>(\"CostsResult\")({\n  \"object\": CostsResultObject,\n  /**\n   * The monetary value in its associated currency.\n   */\n  \"amount\": S.optionalWith(\n    S.Struct({\n      /**\n       * The numeric value of the cost.\n       */\n      \"value\": S.optionalWith(S.Number, { nullable: true }),\n      /**\n       * Lowercase ISO-4217 currency e.g. \"usd\"\n       */\n      \"currency\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"line_item\": S.optionalWith(S.String, { nullable: true }),\n  \"project_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageTimeBucket extends S.Class<UsageTimeBucket>(\"UsageTimeBucket\")({\n  \"object\": UsageTimeBucketObject,\n  \"start_time\": S.Int,\n  \"end_time\": S.Int,\n  \"result\": S.Array(\n    S.Union(\n      UsageCompletionsResult,\n      UsageEmbeddingsResult,\n      UsageModerationsResult,\n      UsageImagesResult,\n      UsageAudioSpeechesResult,\n      UsageAudioTranscriptionsResult,\n      UsageVectorStoresResult,\n      UsageCodeInterpreterSessionsResult,\n      CostsResult\n    )\n  )\n}) {}\n\nexport class UsageResponse extends S.Class<UsageResponse>(\"UsageResponse\")({\n  \"object\": UsageResponseObject,\n  \"data\": S.Array(UsageTimeBucket),\n  \"has_more\": S.Boolean,\n  \"next_page\": S.String\n}) {}\n\nexport class ListGroupsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListGroupsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1000)), {\n    nullable: true,\n    default: () => 100 as const\n  }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListGroupsParamsOrder, { nullable: true, default: () => \"asc\" as const })\n}) {}\n\n/**\n * Always `list`.\n */\nexport class GroupListResourceObject extends S.Literal(\"list\") {}\n\n/**\n * Details about an organization group.\n */\nexport class GroupResponse extends S.Class<GroupResponse>(\"GroupResponse\")({\n  /**\n   * Identifier for the group.\n   */\n  \"id\": S.String,\n  /**\n   * Display name of the group.\n   */\n  \"name\": S.String,\n  /**\n   * Unix timestamp (in seconds) when the group was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Whether the group is managed through SCIM and controlled by your identity provider.\n   */\n  \"is_scim_managed\": S.Boolean\n}) {}\n\n/**\n * Paginated list of organization groups.\n */\nexport class GroupListResource extends S.Class<GroupListResource>(\"GroupListResource\")({\n  /**\n   * Always `list`.\n   */\n  \"object\": GroupListResourceObject,\n  /**\n   * Groups returned in the current page.\n   */\n  \"data\": S.Array(GroupResponse),\n  /**\n   * Whether additional groups are available when paginating.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Cursor to fetch the next page of results, or `null` if there are no more results.\n   */\n  \"next\": S.NullOr(S.String)\n}) {}\n\n/**\n * Request payload for creating a new group in the organization.\n */\nexport class CreateGroupBody extends S.Class<CreateGroupBody>(\"CreateGroupBody\")({\n  /**\n   * Human readable name for the group.\n   */\n  \"name\": S.String.pipe(S.minLength(1), S.maxLength(255))\n}) {}\n\n/**\n * Request payload for updating the details of an existing group.\n */\nexport class UpdateGroupBody extends S.Class<UpdateGroupBody>(\"UpdateGroupBody\")({\n  /**\n   * New display name for the group.\n   */\n  \"name\": S.String.pipe(S.minLength(1), S.maxLength(255))\n}) {}\n\n/**\n * Response returned after updating a group.\n */\nexport class GroupResourceWithSuccess extends S.Class<GroupResourceWithSuccess>(\"GroupResourceWithSuccess\")({\n  /**\n   * Identifier for the group.\n   */\n  \"id\": S.String,\n  /**\n   * Updated display name for the group.\n   */\n  \"name\": S.String,\n  /**\n   * Unix timestamp (in seconds) when the group was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Whether the group is managed through SCIM and controlled by your identity provider.\n   */\n  \"is_scim_managed\": S.Boolean\n}) {}\n\n/**\n * Always `group.deleted`.\n */\nexport class GroupDeletedResourceObject extends S.Literal(\"group.deleted\") {}\n\n/**\n * Confirmation payload returned after deleting a group.\n */\nexport class GroupDeletedResource extends S.Class<GroupDeletedResource>(\"GroupDeletedResource\")({\n  /**\n   * Always `group.deleted`.\n   */\n  \"object\": GroupDeletedResourceObject,\n  /**\n   * Identifier of the deleted group.\n   */\n  \"id\": S.String,\n  /**\n   * Whether the group was deleted.\n   */\n  \"deleted\": S.Boolean\n}) {}\n\nexport class ListGroupRoleAssignmentsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListGroupRoleAssignmentsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1000)), { nullable: true }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListGroupRoleAssignmentsParamsOrder, { nullable: true })\n}) {}\n\n/**\n * Always `list`.\n */\nexport class RoleListResourceObject extends S.Literal(\"list\") {}\n\n/**\n * Detailed information about a role assignment entry returned when listing assignments.\n */\nexport class AssignedRoleDetails extends S.Class<AssignedRoleDetails>(\"AssignedRoleDetails\")({\n  /**\n   * Identifier for the role.\n   */\n  \"id\": S.String,\n  /**\n   * Name of the role.\n   */\n  \"name\": S.String,\n  /**\n   * Permissions associated with the role.\n   */\n  \"permissions\": S.Array(S.String),\n  /**\n   * Resource type the role applies to.\n   */\n  \"resource_type\": S.String,\n  /**\n   * Whether the role is predefined by OpenAI.\n   */\n  \"predefined_role\": S.Boolean,\n  /**\n   * Description of the role.\n   */\n  \"description\": S.NullOr(S.String),\n  /**\n   * When the role was created.\n   */\n  \"created_at\": S.NullOr(S.Int),\n  /**\n   * When the role was last updated.\n   */\n  \"updated_at\": S.NullOr(S.Int),\n  /**\n   * Identifier of the actor who created the role.\n   */\n  \"created_by\": S.NullOr(S.String),\n  /**\n   * User details for the actor that created the role, when available.\n   */\n  \"created_by_user_obj\": S.NullOr(S.Record({ key: S.String, value: S.Unknown })),\n  /**\n   * Arbitrary metadata stored on the role.\n   */\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown }))\n}) {}\n\n/**\n * Paginated list of roles assigned to a principal.\n */\nexport class RoleListResource extends S.Class<RoleListResource>(\"RoleListResource\")({\n  /**\n   * Always `list`.\n   */\n  \"object\": RoleListResourceObject,\n  /**\n   * Role assignments returned in the current page.\n   */\n  \"data\": S.Array(AssignedRoleDetails),\n  /**\n   * Whether additional assignments are available when paginating.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Cursor to fetch the next page of results, or `null` when there are no more assignments.\n   */\n  \"next\": S.NullOr(S.String)\n}) {}\n\n/**\n * Request payload for assigning a role to a group or user.\n */\nexport class PublicAssignOrganizationGroupRoleBody\n  extends S.Class<PublicAssignOrganizationGroupRoleBody>(\"PublicAssignOrganizationGroupRoleBody\")({\n    /**\n     * Identifier of the role to assign.\n     */\n    \"role_id\": S.String\n  })\n{}\n\n/**\n * Always `group.role`.\n */\nexport class GroupRoleAssignmentObject extends S.Literal(\"group.role\") {}\n\n/**\n * Always `group`.\n */\nexport class GroupObject extends S.Literal(\"group\") {}\n\n/**\n * Summary information about a group returned in role assignment responses.\n */\nexport class Group extends S.Class<Group>(\"Group\")({\n  /**\n   * Always `group`.\n   */\n  \"object\": GroupObject,\n  /**\n   * Identifier for the group.\n   */\n  \"id\": S.String,\n  /**\n   * Display name of the group.\n   */\n  \"name\": S.String,\n  /**\n   * Unix timestamp (in seconds) when the group was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Whether the group is managed through SCIM.\n   */\n  \"scim_managed\": S.Boolean\n}) {}\n\n/**\n * Always `role`.\n */\nexport class RoleObject extends S.Literal(\"role\") {}\n\n/**\n * Details about a role that can be assigned through the public Roles API.\n */\nexport class Role extends S.Class<Role>(\"Role\")({\n  /**\n   * Always `role`.\n   */\n  \"object\": RoleObject,\n  /**\n   * Identifier for the role.\n   */\n  \"id\": S.String,\n  /**\n   * Unique name for the role.\n   */\n  \"name\": S.String,\n  /**\n   * Optional description of the role.\n   */\n  \"description\": S.NullOr(S.String),\n  /**\n   * Permissions granted by the role.\n   */\n  \"permissions\": S.Array(S.String),\n  /**\n   * Resource type the role is bound to (for example `api.organization` or `api.project`).\n   */\n  \"resource_type\": S.String,\n  /**\n   * Whether the role is predefined and managed by OpenAI.\n   */\n  \"predefined_role\": S.Boolean\n}) {}\n\n/**\n * Role assignment linking a group to a role.\n */\nexport class GroupRoleAssignment extends S.Class<GroupRoleAssignment>(\"GroupRoleAssignment\")({\n  /**\n   * Always `group.role`.\n   */\n  \"object\": GroupRoleAssignmentObject,\n  \"group\": Group,\n  \"role\": Role\n}) {}\n\n/**\n * Confirmation payload returned after unassigning a role.\n */\nexport class DeletedRoleAssignmentResource\n  extends S.Class<DeletedRoleAssignmentResource>(\"DeletedRoleAssignmentResource\")({\n    /**\n     * Identifier for the deleted assignment, such as `group.role.deleted` or `user.role.deleted`.\n     */\n    \"object\": S.String,\n    /**\n     * Whether the assignment was removed.\n     */\n    \"deleted\": S.Boolean\n  })\n{}\n\nexport class ListGroupUsersParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListGroupUsersParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1000)), {\n    nullable: true,\n    default: () => 100 as const\n  }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListGroupUsersParamsOrder, { nullable: true, default: () => \"desc\" as const })\n}) {}\n\n/**\n * Always `list`.\n */\nexport class UserListResourceObject extends S.Literal(\"list\") {}\n\n/**\n * The object type, which is always `organization.user`\n */\nexport class UserObject extends S.Literal(\"organization.user\") {}\n\n/**\n * `owner` or `reader`\n */\nexport class UserRole extends S.Literal(\"owner\", \"reader\") {}\n\n/**\n * Represents an individual `user` within an organization.\n */\nexport class User extends S.Class<User>(\"User\")({\n  /**\n   * The object type, which is always `organization.user`\n   */\n  \"object\": UserObject,\n  /**\n   * The identifier, which can be referenced in API endpoints\n   */\n  \"id\": S.String,\n  /**\n   * The name of the user\n   */\n  \"name\": S.String,\n  /**\n   * The email address of the user\n   */\n  \"email\": S.String,\n  /**\n   * `owner` or `reader`\n   */\n  \"role\": UserRole,\n  /**\n   * The Unix timestamp (in seconds) of when the user was added.\n   */\n  \"added_at\": S.Int\n}) {}\n\n/**\n * Paginated list of user objects returned when inspecting group membership.\n */\nexport class UserListResource extends S.Class<UserListResource>(\"UserListResource\")({\n  /**\n   * Always `list`.\n   */\n  \"object\": UserListResourceObject,\n  /**\n   * Users in the current page.\n   */\n  \"data\": S.Array(User),\n  /**\n   * Whether more users are available when paginating.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Cursor to fetch the next page of results, or `null` when no further users are available.\n   */\n  \"next\": S.NullOr(S.String)\n}) {}\n\n/**\n * Request payload for adding a user to a group.\n */\nexport class CreateGroupUserBody extends S.Class<CreateGroupUserBody>(\"CreateGroupUserBody\")({\n  /**\n   * Identifier of the user to add to the group.\n   */\n  \"user_id\": S.String\n}) {}\n\n/**\n * Always `group.user`.\n */\nexport class GroupUserAssignmentObject extends S.Literal(\"group.user\") {}\n\n/**\n * Confirmation payload returned after adding a user to a group.\n */\nexport class GroupUserAssignment extends S.Class<GroupUserAssignment>(\"GroupUserAssignment\")({\n  /**\n   * Always `group.user`.\n   */\n  \"object\": GroupUserAssignmentObject,\n  /**\n   * Identifier of the user that was added.\n   */\n  \"user_id\": S.String,\n  /**\n   * Identifier of the group the user was added to.\n   */\n  \"group_id\": S.String\n}) {}\n\n/**\n * Always `group.user.deleted`.\n */\nexport class GroupUserDeletedResourceObject extends S.Literal(\"group.user.deleted\") {}\n\n/**\n * Confirmation payload returned after removing a user from a group.\n */\nexport class GroupUserDeletedResource extends S.Class<GroupUserDeletedResource>(\"GroupUserDeletedResource\")({\n  /**\n   * Always `group.user.deleted`.\n   */\n  \"object\": GroupUserDeletedResourceObject,\n  /**\n   * Whether the group membership was removed.\n   */\n  \"deleted\": S.Boolean\n}) {}\n\nexport class ListInvitesParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `list`\n */\nexport class InviteListResponseObject extends S.Literal(\"list\") {}\n\n/**\n * The object type, which is always `organization.invite`\n */\nexport class InviteObject extends S.Literal(\"organization.invite\") {}\n\n/**\n * `owner` or `reader`\n */\nexport class InviteRole extends S.Literal(\"owner\", \"reader\") {}\n\n/**\n * `accepted`,`expired`, or `pending`\n */\nexport class InviteStatus extends S.Literal(\"accepted\", \"expired\", \"pending\") {}\n\n/**\n * Represents an individual `invite` to the organization.\n */\nexport class Invite extends S.Class<Invite>(\"Invite\")({\n  /**\n   * The object type, which is always `organization.invite`\n   */\n  \"object\": InviteObject,\n  /**\n   * The identifier, which can be referenced in API endpoints\n   */\n  \"id\": S.String,\n  /**\n   * The email address of the individual to whom the invite was sent\n   */\n  \"email\": S.String,\n  /**\n   * `owner` or `reader`\n   */\n  \"role\": InviteRole,\n  /**\n   * `accepted`,`expired`, or `pending`\n   */\n  \"status\": InviteStatus,\n  /**\n   * The Unix timestamp (in seconds) of when the invite was sent.\n   */\n  \"invited_at\": S.Int,\n  /**\n   * The Unix timestamp (in seconds) of when the invite expires.\n   */\n  \"expires_at\": S.Int,\n  /**\n   * The Unix timestamp (in seconds) of when the invite was accepted.\n   */\n  \"accepted_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The projects that were granted membership upon acceptance of the invite.\n   */\n  \"projects\": S.optionalWith(\n    S.Array(S.Struct({\n      /**\n       * Project's public ID\n       */\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * Project membership role\n       */\n      \"role\": S.optionalWith(S.Literal(\"member\", \"owner\"), { nullable: true })\n    })),\n    { nullable: true }\n  )\n}) {}\n\nexport class InviteListResponse extends S.Class<InviteListResponse>(\"InviteListResponse\")({\n  /**\n   * The object type, which is always `list`\n   */\n  \"object\": InviteListResponseObject,\n  \"data\": S.Array(Invite),\n  /**\n   * The first `invite_id` in the retrieved `list`\n   */\n  \"first_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The last `invite_id` in the retrieved `list`\n   */\n  \"last_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The `has_more` property is used for pagination to indicate there are additional results.\n   */\n  \"has_more\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * `owner` or `reader`\n */\nexport class InviteRequestRole extends S.Literal(\"reader\", \"owner\") {}\n\nexport class InviteRequest extends S.Class<InviteRequest>(\"InviteRequest\")({\n  /**\n   * Send an email to this address\n   */\n  \"email\": S.String,\n  /**\n   * `owner` or `reader`\n   */\n  \"role\": InviteRequestRole,\n  /**\n   * An array of projects to which membership is granted at the same time the org invite is accepted. If omitted, the user will be invited to the default project for compatibility with legacy behavior.\n   */\n  \"projects\": S.optionalWith(\n    S.Array(S.Struct({\n      /**\n       * Project's public ID\n       */\n      \"id\": S.String,\n      /**\n       * Project membership role\n       */\n      \"role\": S.Literal(\"member\", \"owner\")\n    })),\n    { nullable: true }\n  )\n}) {}\n\n/**\n * The object type, which is always `organization.invite.deleted`\n */\nexport class InviteDeleteResponseObject extends S.Literal(\"organization.invite.deleted\") {}\n\nexport class InviteDeleteResponse extends S.Class<InviteDeleteResponse>(\"InviteDeleteResponse\")({\n  /**\n   * The object type, which is always `organization.invite.deleted`\n   */\n  \"object\": InviteDeleteResponseObject,\n  \"id\": S.String,\n  \"deleted\": S.Boolean\n}) {}\n\nexport class ListProjectsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"include_archived\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const })\n}) {}\n\nexport class ProjectListResponseObject extends S.Literal(\"list\") {}\n\n/**\n * The object type, which is always `organization.project`\n */\nexport class ProjectObject extends S.Literal(\"organization.project\") {}\n\n/**\n * `active` or `archived`\n */\nexport class ProjectStatus extends S.Literal(\"active\", \"archived\") {}\n\n/**\n * Represents an individual project.\n */\nexport class Project extends S.Class<Project>(\"Project\")({\n  /**\n   * The identifier, which can be referenced in API endpoints\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `organization.project`\n   */\n  \"object\": ProjectObject,\n  /**\n   * The name of the project. This appears in reporting.\n   */\n  \"name\": S.String,\n  /**\n   * The Unix timestamp (in seconds) of when the project was created.\n   */\n  \"created_at\": S.Int,\n  \"archived_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * `active` or `archived`\n   */\n  \"status\": ProjectStatus\n}) {}\n\nexport class ProjectListResponse extends S.Class<ProjectListResponse>(\"ProjectListResponse\")({\n  \"object\": ProjectListResponseObject,\n  \"data\": S.Array(Project),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\n/**\n * Create the project with the specified data residency region. Your organization must have access to Data residency functionality in order to use. See [data residency controls](https://platform.openai.com/docs/guides/your-data#data-residency-controls) to review the functionality and limitations of setting this field.\n */\nexport class ProjectCreateRequestGeography extends S.Literal(\"US\", \"EU\", \"JP\", \"IN\", \"KR\", \"CA\", \"AU\", \"SG\") {}\n\nexport class ProjectCreateRequest extends S.Class<ProjectCreateRequest>(\"ProjectCreateRequest\")({\n  /**\n   * The friendly name of the project, this name appears in reports.\n   */\n  \"name\": S.String,\n  /**\n   * Create the project with the specified data residency region. Your organization must have access to Data residency functionality in order to use. See [data residency controls](https://platform.openai.com/docs/guides/your-data#data-residency-controls) to review the functionality and limitations of setting this field.\n   */\n  \"geography\": S.optionalWith(ProjectCreateRequestGeography, { nullable: true })\n}) {}\n\nexport class ProjectUpdateRequest extends S.Class<ProjectUpdateRequest>(\"ProjectUpdateRequest\")({\n  /**\n   * The updated name of the project, this name appears in reports.\n   */\n  \"name\": S.String\n}) {}\n\nexport class ErrorResponse extends S.Class<ErrorResponse>(\"ErrorResponse\")({\n  \"error\": Error\n}) {}\n\nexport class ListProjectApiKeysParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ProjectApiKeyListResponseObject extends S.Literal(\"list\") {}\n\n/**\n * The object type, which is always `organization.project.api_key`\n */\nexport class ProjectApiKeyObject extends S.Literal(\"organization.project.api_key\") {}\n\n/**\n * `user` or `service_account`\n */\nexport class ProjectApiKeyOwnerType extends S.Literal(\"user\", \"service_account\") {}\n\n/**\n * The object type, which is always `organization.project.user`\n */\nexport class ProjectUserObject extends S.Literal(\"organization.project.user\") {}\n\n/**\n * `owner` or `member`\n */\nexport class ProjectUserRole extends S.Literal(\"owner\", \"member\") {}\n\n/**\n * Represents an individual user in a project.\n */\nexport class ProjectUser extends S.Class<ProjectUser>(\"ProjectUser\")({\n  /**\n   * The object type, which is always `organization.project.user`\n   */\n  \"object\": ProjectUserObject,\n  /**\n   * The identifier, which can be referenced in API endpoints\n   */\n  \"id\": S.String,\n  /**\n   * The name of the user\n   */\n  \"name\": S.String,\n  /**\n   * The email address of the user\n   */\n  \"email\": S.String,\n  /**\n   * `owner` or `member`\n   */\n  \"role\": ProjectUserRole,\n  /**\n   * The Unix timestamp (in seconds) of when the project was added.\n   */\n  \"added_at\": S.Int\n}) {}\n\n/**\n * The object type, which is always `organization.project.service_account`\n */\nexport class ProjectServiceAccountObject extends S.Literal(\"organization.project.service_account\") {}\n\n/**\n * `owner` or `member`\n */\nexport class ProjectServiceAccountRole extends S.Literal(\"owner\", \"member\") {}\n\n/**\n * Represents an individual service account in a project.\n */\nexport class ProjectServiceAccount extends S.Class<ProjectServiceAccount>(\"ProjectServiceAccount\")({\n  /**\n   * The object type, which is always `organization.project.service_account`\n   */\n  \"object\": ProjectServiceAccountObject,\n  /**\n   * The identifier, which can be referenced in API endpoints\n   */\n  \"id\": S.String,\n  /**\n   * The name of the service account\n   */\n  \"name\": S.String,\n  /**\n   * `owner` or `member`\n   */\n  \"role\": ProjectServiceAccountRole,\n  /**\n   * The Unix timestamp (in seconds) of when the service account was created\n   */\n  \"created_at\": S.Int\n}) {}\n\n/**\n * Represents an individual API key in a project.\n */\nexport class ProjectApiKey extends S.Class<ProjectApiKey>(\"ProjectApiKey\")({\n  /**\n   * The object type, which is always `organization.project.api_key`\n   */\n  \"object\": ProjectApiKeyObject,\n  /**\n   * The redacted value of the API key\n   */\n  \"redacted_value\": S.String,\n  /**\n   * The name of the API key\n   */\n  \"name\": S.String,\n  /**\n   * The Unix timestamp (in seconds) of when the API key was created\n   */\n  \"created_at\": S.Int,\n  /**\n   * The Unix timestamp (in seconds) of when the API key was last used.\n   */\n  \"last_used_at\": S.Int,\n  /**\n   * The identifier, which can be referenced in API endpoints\n   */\n  \"id\": S.String,\n  \"owner\": S.Struct({\n    /**\n     * `user` or `service_account`\n     */\n    \"type\": S.optionalWith(ProjectApiKeyOwnerType, { nullable: true }),\n    \"user\": S.optionalWith(ProjectUser, { nullable: true }),\n    \"service_account\": S.optionalWith(ProjectServiceAccount, { nullable: true })\n  })\n}) {}\n\nexport class ProjectApiKeyListResponse extends S.Class<ProjectApiKeyListResponse>(\"ProjectApiKeyListResponse\")({\n  \"object\": ProjectApiKeyListResponseObject,\n  \"data\": S.Array(ProjectApiKey),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\nexport class ProjectApiKeyDeleteResponseObject extends S.Literal(\"organization.project.api_key.deleted\") {}\n\nexport class ProjectApiKeyDeleteResponse extends S.Class<ProjectApiKeyDeleteResponse>(\"ProjectApiKeyDeleteResponse\")({\n  \"object\": ProjectApiKeyDeleteResponseObject,\n  \"id\": S.String,\n  \"deleted\": S.Boolean\n}) {}\n\nexport class ListProjectCertificatesParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListProjectCertificatesParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListProjectCertificatesParamsOrder, { nullable: true, default: () => \"desc\" as const })\n}) {}\n\nexport class ListProjectGroupsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListProjectGroupsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(100)), {\n    nullable: true,\n    default: () => 20 as const\n  }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListProjectGroupsParamsOrder, { nullable: true, default: () => \"asc\" as const })\n}) {}\n\n/**\n * Always `list`.\n */\nexport class ProjectGroupListResourceObject extends S.Literal(\"list\") {}\n\n/**\n * Always `project.group`.\n */\nexport class ProjectGroupObject extends S.Literal(\"project.group\") {}\n\n/**\n * Details about a group's membership in a project.\n */\nexport class ProjectGroup extends S.Class<ProjectGroup>(\"ProjectGroup\")({\n  /**\n   * Always `project.group`.\n   */\n  \"object\": ProjectGroupObject,\n  /**\n   * Identifier of the project.\n   */\n  \"project_id\": S.String,\n  /**\n   * Identifier of the group that has access to the project.\n   */\n  \"group_id\": S.String,\n  /**\n   * Display name of the group.\n   */\n  \"group_name\": S.String,\n  /**\n   * Unix timestamp (in seconds) when the group was granted project access.\n   */\n  \"created_at\": S.Int\n}) {}\n\n/**\n * Paginated list of groups that have access to a project.\n */\nexport class ProjectGroupListResource extends S.Class<ProjectGroupListResource>(\"ProjectGroupListResource\")({\n  /**\n   * Always `list`.\n   */\n  \"object\": ProjectGroupListResourceObject,\n  /**\n   * Project group memberships returned in the current page.\n   */\n  \"data\": S.Array(ProjectGroup),\n  /**\n   * Whether additional project group memberships are available.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Cursor to fetch the next page of results, or `null` when there are no more results.\n   */\n  \"next\": S.NullOr(S.String)\n}) {}\n\n/**\n * Request payload for granting a group access to a project.\n */\nexport class InviteProjectGroupBody extends S.Class<InviteProjectGroupBody>(\"InviteProjectGroupBody\")({\n  /**\n   * Identifier of the group to add to the project.\n   */\n  \"group_id\": S.String,\n  /**\n   * Identifier of the project role to grant to the group.\n   */\n  \"role\": S.String\n}) {}\n\n/**\n * Always `project.group.deleted`.\n */\nexport class ProjectGroupDeletedResourceObject extends S.Literal(\"project.group.deleted\") {}\n\n/**\n * Confirmation payload returned after removing a group from a project.\n */\nexport class ProjectGroupDeletedResource extends S.Class<ProjectGroupDeletedResource>(\"ProjectGroupDeletedResource\")({\n  /**\n   * Always `project.group.deleted`.\n   */\n  \"object\": ProjectGroupDeletedResourceObject,\n  /**\n   * Whether the group membership in the project was removed.\n   */\n  \"deleted\": S.Boolean\n}) {}\n\nexport class ListProjectRateLimitsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 100 as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"before\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ProjectRateLimitListResponseObject extends S.Literal(\"list\") {}\n\n/**\n * The object type, which is always `project.rate_limit`\n */\nexport class ProjectRateLimitObject extends S.Literal(\"project.rate_limit\") {}\n\n/**\n * Represents a project rate limit config.\n */\nexport class ProjectRateLimit extends S.Class<ProjectRateLimit>(\"ProjectRateLimit\")({\n  /**\n   * The object type, which is always `project.rate_limit`\n   */\n  \"object\": ProjectRateLimitObject,\n  /**\n   * The identifier, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The model this rate limit applies to.\n   */\n  \"model\": S.String,\n  /**\n   * The maximum requests per minute.\n   */\n  \"max_requests_per_1_minute\": S.Int,\n  /**\n   * The maximum tokens per minute.\n   */\n  \"max_tokens_per_1_minute\": S.Int,\n  /**\n   * The maximum images per minute. Only present for relevant models.\n   */\n  \"max_images_per_1_minute\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The maximum audio megabytes per minute. Only present for relevant models.\n   */\n  \"max_audio_megabytes_per_1_minute\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The maximum requests per day. Only present for relevant models.\n   */\n  \"max_requests_per_1_day\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The maximum batch input tokens per day. Only present for relevant models.\n   */\n  \"batch_1_day_max_input_tokens\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\nexport class ProjectRateLimitListResponse\n  extends S.Class<ProjectRateLimitListResponse>(\"ProjectRateLimitListResponse\")({\n    \"object\": ProjectRateLimitListResponseObject,\n    \"data\": S.Array(ProjectRateLimit),\n    \"first_id\": S.String,\n    \"last_id\": S.String,\n    \"has_more\": S.Boolean\n  })\n{}\n\nexport class ProjectRateLimitUpdateRequest\n  extends S.Class<ProjectRateLimitUpdateRequest>(\"ProjectRateLimitUpdateRequest\")({\n    /**\n     * The maximum requests per minute.\n     */\n    \"max_requests_per_1_minute\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * The maximum tokens per minute.\n     */\n    \"max_tokens_per_1_minute\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * The maximum images per minute. Only relevant for certain models.\n     */\n    \"max_images_per_1_minute\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * The maximum audio megabytes per minute. Only relevant for certain models.\n     */\n    \"max_audio_megabytes_per_1_minute\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * The maximum requests per day. Only relevant for certain models.\n     */\n    \"max_requests_per_1_day\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * The maximum batch input tokens per day. Only relevant for certain models.\n     */\n    \"batch_1_day_max_input_tokens\": S.optionalWith(S.Int, { nullable: true })\n  })\n{}\n\nexport class ListProjectServiceAccountsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ProjectServiceAccountListResponseObject extends S.Literal(\"list\") {}\n\nexport class ProjectServiceAccountListResponse\n  extends S.Class<ProjectServiceAccountListResponse>(\"ProjectServiceAccountListResponse\")({\n    \"object\": ProjectServiceAccountListResponseObject,\n    \"data\": S.Array(ProjectServiceAccount),\n    \"first_id\": S.String,\n    \"last_id\": S.String,\n    \"has_more\": S.Boolean\n  })\n{}\n\nexport class ProjectServiceAccountCreateRequest\n  extends S.Class<ProjectServiceAccountCreateRequest>(\"ProjectServiceAccountCreateRequest\")({\n    /**\n     * The name of the service account being created.\n     */\n    \"name\": S.String\n  })\n{}\n\nexport class ProjectServiceAccountCreateResponseObject extends S.Literal(\"organization.project.service_account\") {}\n\n/**\n * Service accounts can only have one role of type `member`\n */\nexport class ProjectServiceAccountCreateResponseRole extends S.Literal(\"member\") {}\n\n/**\n * The object type, which is always `organization.project.service_account.api_key`\n */\nexport class ProjectServiceAccountApiKeyObject extends S.Literal(\"organization.project.service_account.api_key\") {}\n\nexport class ProjectServiceAccountApiKey extends S.Class<ProjectServiceAccountApiKey>(\"ProjectServiceAccountApiKey\")({\n  /**\n   * The object type, which is always `organization.project.service_account.api_key`\n   */\n  \"object\": ProjectServiceAccountApiKeyObject,\n  \"value\": S.String,\n  \"name\": S.String,\n  \"created_at\": S.Int,\n  \"id\": S.String\n}) {}\n\nexport class ProjectServiceAccountCreateResponse\n  extends S.Class<ProjectServiceAccountCreateResponse>(\"ProjectServiceAccountCreateResponse\")({\n    \"object\": ProjectServiceAccountCreateResponseObject,\n    \"id\": S.String,\n    \"name\": S.String,\n    /**\n     * Service accounts can only have one role of type `member`\n     */\n    \"role\": ProjectServiceAccountCreateResponseRole,\n    \"created_at\": S.Int,\n    \"api_key\": ProjectServiceAccountApiKey\n  })\n{}\n\nexport class ProjectServiceAccountDeleteResponseObject\n  extends S.Literal(\"organization.project.service_account.deleted\")\n{}\n\nexport class ProjectServiceAccountDeleteResponse\n  extends S.Class<ProjectServiceAccountDeleteResponse>(\"ProjectServiceAccountDeleteResponse\")({\n    \"object\": ProjectServiceAccountDeleteResponseObject,\n    \"id\": S.String,\n    \"deleted\": S.Boolean\n  })\n{}\n\nexport class ListProjectUsersParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ProjectUserListResponse extends S.Class<ProjectUserListResponse>(\"ProjectUserListResponse\")({\n  \"object\": S.String,\n  \"data\": S.Array(ProjectUser),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\n/**\n * `owner` or `member`\n */\nexport class ProjectUserCreateRequestRole extends S.Literal(\"owner\", \"member\") {}\n\nexport class ProjectUserCreateRequest extends S.Class<ProjectUserCreateRequest>(\"ProjectUserCreateRequest\")({\n  /**\n   * The ID of the user.\n   */\n  \"user_id\": S.String,\n  /**\n   * `owner` or `member`\n   */\n  \"role\": ProjectUserCreateRequestRole\n}) {}\n\n/**\n * `owner` or `member`\n */\nexport class ProjectUserUpdateRequestRole extends S.Literal(\"owner\", \"member\") {}\n\nexport class ProjectUserUpdateRequest extends S.Class<ProjectUserUpdateRequest>(\"ProjectUserUpdateRequest\")({\n  /**\n   * `owner` or `member`\n   */\n  \"role\": ProjectUserUpdateRequestRole\n}) {}\n\nexport class ProjectUserDeleteResponseObject extends S.Literal(\"organization.project.user.deleted\") {}\n\nexport class ProjectUserDeleteResponse extends S.Class<ProjectUserDeleteResponse>(\"ProjectUserDeleteResponse\")({\n  \"object\": ProjectUserDeleteResponseObject,\n  \"id\": S.String,\n  \"deleted\": S.Boolean\n}) {}\n\nexport class ListRolesParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListRolesParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1000)), {\n    nullable: true,\n    default: () => 1000 as const\n  }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListRolesParamsOrder, { nullable: true, default: () => \"asc\" as const })\n}) {}\n\n/**\n * Always `list`.\n */\nexport class PublicRoleListResourceObject extends S.Literal(\"list\") {}\n\n/**\n * Paginated list of roles available on an organization or project.\n */\nexport class PublicRoleListResource extends S.Class<PublicRoleListResource>(\"PublicRoleListResource\")({\n  /**\n   * Always `list`.\n   */\n  \"object\": PublicRoleListResourceObject,\n  /**\n   * Roles returned in the current page.\n   */\n  \"data\": S.Array(Role),\n  /**\n   * Whether more roles are available when paginating.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * Cursor to fetch the next page of results, or `null` when there are no additional roles.\n   */\n  \"next\": S.NullOr(S.String)\n}) {}\n\n/**\n * Request payload for creating a custom role.\n */\nexport class PublicCreateOrganizationRoleBody\n  extends S.Class<PublicCreateOrganizationRoleBody>(\"PublicCreateOrganizationRoleBody\")({\n    /**\n     * Unique name for the role.\n     */\n    \"role_name\": S.String,\n    /**\n     * Permissions to grant to the role.\n     */\n    \"permissions\": S.Array(S.String),\n    /**\n     * Optional description of the role.\n     */\n    \"description\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * Request payload for updating an existing role.\n */\nexport class PublicUpdateOrganizationRoleBody\n  extends S.Class<PublicUpdateOrganizationRoleBody>(\"PublicUpdateOrganizationRoleBody\")({\n    /**\n     * Updated set of permissions for the role.\n     */\n    \"permissions\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    /**\n     * New description for the role.\n     */\n    \"description\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * New name for the role.\n     */\n    \"role_name\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * Always `role.deleted`.\n */\nexport class RoleDeletedResourceObject extends S.Literal(\"role.deleted\") {}\n\n/**\n * Confirmation payload returned after deleting a role.\n */\nexport class RoleDeletedResource extends S.Class<RoleDeletedResource>(\"RoleDeletedResource\")({\n  /**\n   * Always `role.deleted`.\n   */\n  \"object\": RoleDeletedResourceObject,\n  /**\n   * Identifier of the deleted role.\n   */\n  \"id\": S.String,\n  /**\n   * Whether the role was deleted.\n   */\n  \"deleted\": S.Boolean\n}) {}\n\nexport class UsageAudioSpeechesParamsBucketWidth extends S.Literal(\"1m\", \"1h\", \"1d\") {}\n\nexport class UsageAudioSpeechesParams extends S.Struct({\n  \"start_time\": S.Int,\n  \"end_time\": S.optionalWith(S.Int, { nullable: true }),\n  \"bucket_width\": S.optionalWith(UsageAudioSpeechesParamsBucketWidth, { nullable: true, default: () => \"1d\" as const }),\n  \"project_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"user_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"api_key_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"group_by\": S.optionalWith(S.Array(S.Literal(\"project_id\", \"user_id\", \"api_key_id\", \"model\")), { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true }),\n  \"page\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageAudioTranscriptionsParamsBucketWidth extends S.Literal(\"1m\", \"1h\", \"1d\") {}\n\nexport class UsageAudioTranscriptionsParams extends S.Struct({\n  \"start_time\": S.Int,\n  \"end_time\": S.optionalWith(S.Int, { nullable: true }),\n  \"bucket_width\": S.optionalWith(UsageAudioTranscriptionsParamsBucketWidth, {\n    nullable: true,\n    default: () => \"1d\" as const\n  }),\n  \"project_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"user_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"api_key_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"group_by\": S.optionalWith(S.Array(S.Literal(\"project_id\", \"user_id\", \"api_key_id\", \"model\")), { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true }),\n  \"page\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageCodeInterpreterSessionsParamsBucketWidth extends S.Literal(\"1m\", \"1h\", \"1d\") {}\n\nexport class UsageCodeInterpreterSessionsParams extends S.Struct({\n  \"start_time\": S.Int,\n  \"end_time\": S.optionalWith(S.Int, { nullable: true }),\n  \"bucket_width\": S.optionalWith(UsageCodeInterpreterSessionsParamsBucketWidth, {\n    nullable: true,\n    default: () => \"1d\" as const\n  }),\n  \"project_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"group_by\": S.optionalWith(S.Array(S.Literal(\"project_id\")), { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true }),\n  \"page\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageCompletionsParamsBucketWidth extends S.Literal(\"1m\", \"1h\", \"1d\") {}\n\nexport class UsageCompletionsParams extends S.Struct({\n  \"start_time\": S.Int,\n  \"end_time\": S.optionalWith(S.Int, { nullable: true }),\n  \"bucket_width\": S.optionalWith(UsageCompletionsParamsBucketWidth, { nullable: true, default: () => \"1d\" as const }),\n  \"project_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"user_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"api_key_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"batch\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"group_by\": S.optionalWith(\n    S.Array(S.Literal(\"project_id\", \"user_id\", \"api_key_id\", \"model\", \"batch\", \"service_tier\")),\n    { nullable: true }\n  ),\n  \"limit\": S.optionalWith(S.Int, { nullable: true }),\n  \"page\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageEmbeddingsParamsBucketWidth extends S.Literal(\"1m\", \"1h\", \"1d\") {}\n\nexport class UsageEmbeddingsParams extends S.Struct({\n  \"start_time\": S.Int,\n  \"end_time\": S.optionalWith(S.Int, { nullable: true }),\n  \"bucket_width\": S.optionalWith(UsageEmbeddingsParamsBucketWidth, { nullable: true, default: () => \"1d\" as const }),\n  \"project_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"user_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"api_key_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"group_by\": S.optionalWith(S.Array(S.Literal(\"project_id\", \"user_id\", \"api_key_id\", \"model\")), { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true }),\n  \"page\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageImagesParamsBucketWidth extends S.Literal(\"1m\", \"1h\", \"1d\") {}\n\nexport class UsageImagesParams extends S.Struct({\n  \"start_time\": S.Int,\n  \"end_time\": S.optionalWith(S.Int, { nullable: true }),\n  \"bucket_width\": S.optionalWith(UsageImagesParamsBucketWidth, { nullable: true, default: () => \"1d\" as const }),\n  \"sources\": S.optionalWith(S.Array(S.Literal(\"image.generation\", \"image.edit\", \"image.variation\")), {\n    nullable: true\n  }),\n  \"sizes\": S.optionalWith(S.Array(S.Literal(\"256x256\", \"512x512\", \"1024x1024\", \"1792x1792\", \"1024x1792\")), {\n    nullable: true\n  }),\n  \"project_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"user_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"api_key_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"group_by\": S.optionalWith(S.Array(S.Literal(\"project_id\", \"user_id\", \"api_key_id\", \"model\", \"size\", \"source\")), {\n    nullable: true\n  }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true }),\n  \"page\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageModerationsParamsBucketWidth extends S.Literal(\"1m\", \"1h\", \"1d\") {}\n\nexport class UsageModerationsParams extends S.Struct({\n  \"start_time\": S.Int,\n  \"end_time\": S.optionalWith(S.Int, { nullable: true }),\n  \"bucket_width\": S.optionalWith(UsageModerationsParamsBucketWidth, { nullable: true, default: () => \"1d\" as const }),\n  \"project_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"user_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"api_key_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"group_by\": S.optionalWith(S.Array(S.Literal(\"project_id\", \"user_id\", \"api_key_id\", \"model\")), { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true }),\n  \"page\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class UsageVectorStoresParamsBucketWidth extends S.Literal(\"1m\", \"1h\", \"1d\") {}\n\nexport class UsageVectorStoresParams extends S.Struct({\n  \"start_time\": S.Int,\n  \"end_time\": S.optionalWith(S.Int, { nullable: true }),\n  \"bucket_width\": S.optionalWith(UsageVectorStoresParamsBucketWidth, { nullable: true, default: () => \"1d\" as const }),\n  \"project_ids\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"group_by\": S.optionalWith(S.Array(S.Literal(\"project_id\")), { nullable: true }),\n  \"limit\": S.optionalWith(S.Int, { nullable: true }),\n  \"page\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListUsersParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"emails\": S.optionalWith(S.Array(S.String), { nullable: true })\n}) {}\n\nexport class UserListResponseObject extends S.Literal(\"list\") {}\n\nexport class UserListResponse extends S.Class<UserListResponse>(\"UserListResponse\")({\n  \"object\": UserListResponseObject,\n  \"data\": S.Array(User),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\n/**\n * `owner` or `reader`\n */\nexport class UserRoleUpdateRequestRole extends S.Literal(\"owner\", \"reader\") {}\n\nexport class UserRoleUpdateRequest extends S.Class<UserRoleUpdateRequest>(\"UserRoleUpdateRequest\")({\n  /**\n   * `owner` or `reader`\n   */\n  \"role\": UserRoleUpdateRequestRole\n}) {}\n\nexport class UserDeleteResponseObject extends S.Literal(\"organization.user.deleted\") {}\n\nexport class UserDeleteResponse extends S.Class<UserDeleteResponse>(\"UserDeleteResponse\")({\n  \"object\": UserDeleteResponseObject,\n  \"id\": S.String,\n  \"deleted\": S.Boolean\n}) {}\n\nexport class ListUserRoleAssignmentsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListUserRoleAssignmentsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1000)), { nullable: true }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListUserRoleAssignmentsParamsOrder, { nullable: true })\n}) {}\n\n/**\n * Always `user.role`.\n */\nexport class UserRoleAssignmentObject extends S.Literal(\"user.role\") {}\n\n/**\n * Role assignment linking a user to a role.\n */\nexport class UserRoleAssignment extends S.Class<UserRoleAssignment>(\"UserRoleAssignment\")({\n  /**\n   * Always `user.role`.\n   */\n  \"object\": UserRoleAssignmentObject,\n  \"user\": User,\n  \"role\": Role\n}) {}\n\nexport class ListProjectGroupRoleAssignmentsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListProjectGroupRoleAssignmentsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1000)), { nullable: true }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListProjectGroupRoleAssignmentsParamsOrder, { nullable: true })\n}) {}\n\nexport class ListProjectRolesParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListProjectRolesParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1000)), {\n    nullable: true,\n    default: () => 1000 as const\n  }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListProjectRolesParamsOrder, { nullable: true, default: () => \"asc\" as const })\n}) {}\n\nexport class ListProjectUserRoleAssignmentsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListProjectUserRoleAssignmentsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1000)), { nullable: true }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"order\": S.optionalWith(ListProjectUserRoleAssignmentsParamsOrder, { nullable: true })\n}) {}\n\n/**\n * The type of session to create. Always `realtime` for the Realtime API.\n */\nexport class RealtimeSessionCreateRequestGAType extends S.Literal(\"realtime\") {}\n\nexport class RealtimeSessionCreateRequestGAModelEnum extends S.Literal(\n  \"gpt-realtime\",\n  \"gpt-realtime-2025-08-28\",\n  \"gpt-4o-realtime-preview\",\n  \"gpt-4o-realtime-preview-2024-10-01\",\n  \"gpt-4o-realtime-preview-2024-12-17\",\n  \"gpt-4o-realtime-preview-2025-06-03\",\n  \"gpt-4o-mini-realtime-preview\",\n  \"gpt-4o-mini-realtime-preview-2024-12-17\",\n  \"gpt-realtime-mini\",\n  \"gpt-realtime-mini-2025-10-06\",\n  \"gpt-audio-mini\",\n  \"gpt-audio-mini-2025-10-06\"\n) {}\n\n/**\n * The audio format. Always `audio/pcma`.\n */\nexport class RealtimeAudioFormatsEnumType extends S.Literal(\"audio/pcma\") {}\n\n/**\n * The sample rate of the audio. Always `24000`.\n */\nexport class RealtimeAudioFormatsEnumRate extends S.Literal(24000) {}\n\nexport class RealtimeAudioFormats extends S.Union(\n  /**\n   * The PCM audio format. Only a 24kHz sample rate is supported.\n   */\n  S.Struct({\n    /**\n     * The audio format. Always `audio/pcm`.\n     */\n    \"type\": S.optionalWith(RealtimeAudioFormatsEnumType, { nullable: true }),\n    /**\n     * The sample rate of the audio. Always `24000`.\n     */\n    \"rate\": S.optionalWith(RealtimeAudioFormatsEnumRate, { nullable: true })\n  }),\n  /**\n   * The G.711 μ-law format.\n   */\n  S.Struct({\n    /**\n     * The audio format. Always `audio/pcmu`.\n     */\n    \"type\": S.optionalWith(RealtimeAudioFormatsEnumType, { nullable: true })\n  }),\n  /**\n   * The G.711 A-law format.\n   */\n  S.Struct({\n    /**\n     * The audio format. Always `audio/pcma`.\n     */\n    \"type\": S.optionalWith(RealtimeAudioFormatsEnumType, { nullable: true })\n  })\n) {}\n\n/**\n * The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`, and `gpt-4o-transcribe-diarize`. Use `gpt-4o-transcribe-diarize` when you need diarization with speaker labels.\n */\nexport class AudioTranscriptionModel\n  extends S.Literal(\"whisper-1\", \"gpt-4o-mini-transcribe\", \"gpt-4o-transcribe\", \"gpt-4o-transcribe-diarize\")\n{}\n\nexport class AudioTranscription extends S.Class<AudioTranscription>(\"AudioTranscription\")({\n  /**\n   * The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`, and `gpt-4o-transcribe-diarize`. Use `gpt-4o-transcribe-diarize` when you need diarization with speaker labels.\n   */\n  \"model\": S.optionalWith(AudioTranscriptionModel, { nullable: true }),\n  /**\n   * The language of the input audio. Supplying the input language in\n   * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\n   * will improve accuracy and latency.\n   */\n  \"language\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * An optional text to guide the model's style or continue a previous audio\n   * segment.\n   * For `whisper-1`, the [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting).\n   * For `gpt-4o-transcribe` models (excluding `gpt-4o-transcribe-diarize`), the prompt is a free text string, for example \"expect words related to technology\".\n   */\n  \"prompt\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones.\n */\nexport class NoiseReductionType extends S.Literal(\"near_field\", \"far_field\") {}\n\n/**\n * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. `low`, `medium`, and `high` have max timeouts of 8s, 4s, and 2s respectively.\n */\nexport class RealtimeTurnDetectionEnumEagerness extends S.Literal(\"low\", \"medium\", \"high\", \"auto\") {}\n\nexport class RealtimeTurnDetection extends S.Union(\n  /**\n   * Configuration for turn detection, ether Server VAD or Semantic VAD. This can be set to `null` to turn off, in which case the client must manually trigger model response.\n   *\n   * Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech.\n   *\n   * Semantic VAD is more advanced and uses a turn detection model (in conjunction with VAD) to semantically estimate whether the user has finished speaking, then dynamically sets a timeout based on this probability. For example, if user audio trails off with \"uhhm\", the model will score a low probability of turn end and wait longer for the user to continue speaking. This can be useful for more natural conversations, but may have a higher latency.\n   */\n  S.Union(\n    /**\n     * Server-side voice activity detection (VAD) which flips on when user speech is detected and off after a period of silence.\n     */\n    S.Struct({\n      /**\n       * Type of turn detection, `server_vad` to turn on simple Server VAD.\n       */\n      \"type\": S.Literal(\"server_vad\").pipe(S.propertySignature, S.withConstructorDefault(() => \"server_vad\" as const)),\n      /**\n       * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\n       * higher threshold will require louder audio to activate the model, and\n       * thus might perform better in noisy environments.\n       */\n      \"threshold\": S.optionalWith(S.Number, { nullable: true }),\n      /**\n       * Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in\n       * milliseconds). Defaults to 300ms.\n       */\n      \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true }),\n      /**\n       * Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults\n       * to 500ms. With shorter values the model will respond more quickly,\n       * but may jump in on short pauses from the user.\n       */\n      \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true }),\n      /**\n       * Whether or not to automatically generate a response when a VAD stop event occurs.\n       */\n      \"create_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n      /**\n       * Whether or not to automatically interrupt any ongoing response with output to the default\n       * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n       */\n      \"interrupt_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n      \"idle_timeout_ms\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(5000), S.lessThanOrEqualTo(30000)), {\n        nullable: true\n      })\n    }),\n    /**\n     * Server-side semantic turn detection which uses a model to determine when the user has finished speaking.\n     */\n    S.Struct({\n      /**\n       * Type of turn detection, `semantic_vad` to turn on Semantic VAD.\n       */\n      \"type\": S.Literal(\"semantic_vad\"),\n      /**\n       * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. `low`, `medium`, and `high` have max timeouts of 8s, 4s, and 2s respectively.\n       */\n      \"eagerness\": S.optionalWith(S.Literal(\"low\", \"medium\", \"high\", \"auto\"), {\n        nullable: true,\n        default: () => \"auto\" as const\n      }),\n      /**\n       * Whether or not to automatically generate a response when a VAD stop event occurs.\n       */\n      \"create_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n      /**\n       * Whether or not to automatically interrupt any ongoing response with output to the default\n       * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n       */\n      \"interrupt_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const })\n    })\n  ),\n  S.Null\n) {}\n\n/**\n * Enables tracing and sets default values for tracing configuration options. Always `auto`.\n */\nexport class RealtimeSessionCreateRequestGATracingEnum extends S.Literal(\"auto\") {}\n\n/**\n * The type of the tool, i.e. `function`.\n */\nexport class RealtimeFunctionToolType extends S.Literal(\"function\") {}\n\nexport class RealtimeFunctionTool extends S.Class<RealtimeFunctionTool>(\"RealtimeFunctionTool\")({\n  /**\n   * The type of the tool, i.e. `function`.\n   */\n  \"type\": S.optionalWith(RealtimeFunctionToolType, { nullable: true }),\n  /**\n   * The name of the function.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The description of the function, including guidance on when and how\n   * to call it, and guidance about what to tell the user when calling\n   * (if anything).\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Parameters of the function in JSON Schema.\n   */\n  \"parameters\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * Controls which (if any) tool is called by the model.\n *\n * `none` means the model will not call any tool and instead generates a message.\n *\n * `auto` means the model can pick between generating a message or calling one or\n * more tools.\n *\n * `required` means the model must call one or more tools.\n */\nexport class ToolChoiceOptions extends S.Literal(\"none\", \"auto\", \"required\") {}\n\n/**\n * For function calling, the type is always `function`.\n */\nexport class ToolChoiceFunctionType extends S.Literal(\"function\") {}\n\n/**\n * Use this option to force the model to call a specific function.\n */\nexport class ToolChoiceFunction extends S.Class<ToolChoiceFunction>(\"ToolChoiceFunction\")({\n  /**\n   * For function calling, the type is always `function`.\n   */\n  \"type\": ToolChoiceFunctionType,\n  /**\n   * The name of the function to call.\n   */\n  \"name\": S.String\n}) {}\n\n/**\n * For MCP tools, the type is always `mcp`.\n */\nexport class ToolChoiceMCPType extends S.Literal(\"mcp\") {}\n\n/**\n * Use this option to force the model to call a specific tool on a remote MCP server.\n */\nexport class ToolChoiceMCP extends S.Class<ToolChoiceMCP>(\"ToolChoiceMCP\")({\n  /**\n   * For MCP tools, the type is always `mcp`.\n   */\n  \"type\": ToolChoiceMCPType,\n  /**\n   * The label of the MCP server to use.\n   */\n  \"server_label\": S.String,\n  \"name\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class RealtimeSessionCreateRequestGAMaxOutputTokensEnum extends S.Literal(\"inf\") {}\n\n/**\n * The truncation strategy to use for the session. `auto` is the default truncation strategy. `disabled` will disable truncation and emit errors when the conversation exceeds the input token limit.\n */\nexport class RealtimeTruncationEnum extends S.Literal(\"auto\", \"disabled\") {}\n\n/**\n * Use retention ratio truncation.\n */\nexport class RealtimeTruncationEnumType extends S.Literal(\"retention_ratio\") {}\n\n/**\n * When the number of tokens in a conversation exceeds the model's input token limit, the conversation be truncated, meaning messages (starting from the oldest) will not be included in the model's context. A 32k context model with 4,096 max output tokens can only include 28,224 tokens in the context before truncation occurs.\n * Clients can configure truncation behavior to truncate with a lower max token limit, which is an effective way to control token usage and cost.\n * Truncation will reduce the number of cached tokens on the next turn (busting the cache), since messages are dropped from the beginning of the context. However, clients can also configure truncation to retain messages up to a fraction of the maximum context size, which will reduce the need for future truncations and thus improve the cache rate.\n * Truncation can be disabled entirely, which means the server will never truncate but would instead return an error if the conversation exceeds the model's input token limit.\n */\nexport class RealtimeTruncation extends S.Union(\n  /**\n   * The truncation strategy to use for the session. `auto` is the default truncation strategy. `disabled` will disable truncation and emit errors when the conversation exceeds the input token limit.\n   */\n  RealtimeTruncationEnum,\n  /**\n   * Retain a fraction of the conversation tokens when the conversation exceeds the input token limit. This allows you to amortize truncations across multiple turns, which can help improve cached token usage.\n   */\n  S.Struct({\n    /**\n     * Use retention ratio truncation.\n     */\n    \"type\": RealtimeTruncationEnumType,\n    /**\n     * Fraction of post-instruction conversation tokens to retain (`0.0` - `1.0`) when the conversation exceeds the input token limit. Setting this to `0.8` means that messages will be dropped until 80% of the maximum allowed tokens are used. This helps reduce the frequency of truncations and improve cache rates.\n     */\n    \"retention_ratio\": S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)),\n    /**\n     * Optional custom token limits for this truncation strategy. If not provided, the model's default token limits will be used.\n     */\n    \"token_limits\": S.optionalWith(\n      S.Struct({\n        /**\n         * Maximum tokens allowed in the conversation after instructions (which including tool definitions). For example, setting this to 5,000 would mean that truncation would occur when the conversation exceeds 5,000 tokens after instructions. This cannot be higher than the model's context window size minus the maximum output tokens.\n         */\n        \"post_instructions\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0)), { nullable: true })\n      }),\n      { nullable: true }\n    )\n  })\n) {}\n\nexport class ResponsePromptVariables extends S.Union(\n  /**\n   * Optional map of values to substitute in for variables in your\n   * prompt. The substitution values can either be strings, or other\n   * Response input types like images or files.\n   */\n  S.Record({ key: S.String, value: S.Unknown }),\n  S.Null\n) {}\n\nexport class Prompt extends S.Union(\n  /**\n   * Reference to a prompt template and its variables.\n   * [Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts).\n   */\n  S.Struct({\n    /**\n     * The unique identifier of the prompt template to use.\n     */\n    \"id\": S.String,\n    \"version\": S.optionalWith(S.String, { nullable: true }),\n    \"variables\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  }),\n  S.Null\n) {}\n\n/**\n * Realtime session object configuration.\n */\nexport class RealtimeSessionCreateRequestGA\n  extends S.Class<RealtimeSessionCreateRequestGA>(\"RealtimeSessionCreateRequestGA\")({\n    /**\n     * The type of session to create. Always `realtime` for the Realtime API.\n     */\n    \"type\": RealtimeSessionCreateRequestGAType,\n    /**\n     * The set of modalities the model can respond with. It defaults to `[\"audio\"]`, indicating\n     * that the model will respond with audio plus a transcript. `[\"text\"]` can be used to make\n     * the model respond with text only. It is not possible to request both `text` and `audio` at the same time.\n     */\n    \"output_modalities\": S.optionalWith(S.Array(S.Literal(\"text\", \"audio\")), {\n      nullable: true,\n      default: () => [\"audio\"] as const\n    }),\n    /**\n     * The Realtime model used for this session.\n     */\n    \"model\": S.optionalWith(S.Union(S.String, RealtimeSessionCreateRequestGAModelEnum), { nullable: true }),\n    /**\n     * The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior.\n     *\n     * Note that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session.\n     */\n    \"instructions\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Configuration for input and output audio.\n     */\n    \"audio\": S.optionalWith(\n      S.Struct({\n        \"input\": S.optionalWith(\n          S.Struct({\n            /**\n             * The format of the input audio.\n             */\n            \"format\": S.optionalWith(RealtimeAudioFormats, { nullable: true }),\n            /**\n             * Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n             */\n            \"transcription\": S.optionalWith(AudioTranscription, { nullable: true }),\n            /**\n             * Configuration for input audio noise reduction. This can be set to `null` to turn off.\n             * Noise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\n             * Filtering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n             */\n            \"noise_reduction\": S.optionalWith(\n              S.Struct({\n                \"type\": S.optionalWith(NoiseReductionType, { nullable: true })\n              }),\n              { nullable: true }\n            ),\n            \"turn_detection\": S.optionalWith(\n              S.Union(\n                /**\n                 * Server-side voice activity detection (VAD) which flips on when user speech is detected and off after a period of silence.\n                 */\n                S.Struct({\n                  /**\n                   * Type of turn detection, `server_vad` to turn on simple Server VAD.\n                   */\n                  \"type\": S.Literal(\"server_vad\").pipe(\n                    S.propertySignature,\n                    S.withConstructorDefault(() => \"server_vad\" as const)\n                  ),\n                  /**\n                   * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\n                   * higher threshold will require louder audio to activate the model, and\n                   * thus might perform better in noisy environments.\n                   */\n                  \"threshold\": S.optionalWith(S.Number, { nullable: true }),\n                  /**\n                   * Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in\n                   * milliseconds). Defaults to 300ms.\n                   */\n                  \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true }),\n                  /**\n                   * Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults\n                   * to 500ms. With shorter values the model will respond more quickly,\n                   * but may jump in on short pauses from the user.\n                   */\n                  \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true }),\n                  /**\n                   * Whether or not to automatically generate a response when a VAD stop event occurs.\n                   */\n                  \"create_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n                  /**\n                   * Whether or not to automatically interrupt any ongoing response with output to the default\n                   * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n                   */\n                  \"interrupt_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n                  \"idle_timeout_ms\": S.optionalWith(\n                    S.Int.pipe(S.greaterThanOrEqualTo(5000), S.lessThanOrEqualTo(30000)),\n                    { nullable: true }\n                  )\n                }),\n                /**\n                 * Server-side semantic turn detection which uses a model to determine when the user has finished speaking.\n                 */\n                S.Struct({\n                  /**\n                   * Type of turn detection, `semantic_vad` to turn on Semantic VAD.\n                   */\n                  \"type\": S.Literal(\"semantic_vad\"),\n                  /**\n                   * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. `low`, `medium`, and `high` have max timeouts of 8s, 4s, and 2s respectively.\n                   */\n                  \"eagerness\": S.optionalWith(S.Literal(\"low\", \"medium\", \"high\", \"auto\"), {\n                    nullable: true,\n                    default: () => \"auto\" as const\n                  }),\n                  /**\n                   * Whether or not to automatically generate a response when a VAD stop event occurs.\n                   */\n                  \"create_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n                  /**\n                   * Whether or not to automatically interrupt any ongoing response with output to the default\n                   * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n                   */\n                  \"interrupt_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const })\n                })\n              ),\n              { nullable: true }\n            )\n          }),\n          { nullable: true }\n        ),\n        \"output\": S.optionalWith(\n          S.Struct({\n            /**\n             * The format of the output audio.\n             */\n            \"format\": S.optionalWith(RealtimeAudioFormats, { nullable: true }),\n            /**\n             * The voice the model uses to respond. Voice cannot be changed during the\n             * session once the model has responded with audio at least once. Current\n             * voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n             * `shimmer`, `verse`, `marin`, and `cedar`. We recommend `marin` and `cedar` for\n             * best quality.\n             */\n            \"voice\": S.optionalWith(VoiceIdsShared, { nullable: true }),\n            /**\n             * The speed of the model's spoken response as a multiple of the original speed.\n             * 1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum speed. This value can only be changed in between model turns, not while a response is in progress.\n             *\n             * This parameter is a post-processing adjustment to the audio after it is generated, it's\n             * also possible to prompt the model to speak faster or slower.\n             */\n            \"speed\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0.25), S.lessThanOrEqualTo(1.5)), {\n              nullable: true,\n              default: () => 1 as const\n            })\n          }),\n          { nullable: true }\n        )\n      }),\n      { nullable: true }\n    ),\n    /**\n     * Additional fields to include in server outputs.\n     *\n     * `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n     */\n    \"include\": S.optionalWith(S.Array(S.Literal(\"item.input_audio_transcription.logprobs\")), { nullable: true }),\n    /**\n     * Realtime API can write session traces to the [Traces Dashboard](/logs?api=traces). Set to null to disable tracing. Once\n     * tracing is enabled for a session, the configuration cannot be modified.\n     *\n     * `auto` will create a trace for the session with default values for the\n     * workflow name, group id, and metadata.\n     */\n    \"tracing\": S.optionalWith(\n      S.Union(\n        /**\n         * Enables tracing and sets default values for tracing configuration options. Always `auto`.\n         */\n        RealtimeSessionCreateRequestGATracingEnum,\n        /**\n         * Granular configuration for tracing.\n         */\n        S.Struct({\n          /**\n           * The name of the workflow to attach to this trace. This is used to\n           * name the trace in the Traces Dashboard.\n           */\n          \"workflow_name\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The group id to attach to this trace to enable filtering and\n           * grouping in the Traces Dashboard.\n           */\n          \"group_id\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The arbitrary metadata to attach to this trace to enable\n           * filtering in the Traces Dashboard.\n           */\n          \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n        })\n      ),\n      { nullable: true }\n    ),\n    /**\n     * Tools available to the model.\n     */\n    \"tools\": S.optionalWith(S.Array(S.Union(RealtimeFunctionTool, MCPTool)), { nullable: true }),\n    /**\n     * How the model chooses tools. Provide one of the string modes or force a specific\n     * function/MCP tool.\n     */\n    \"tool_choice\": S.optionalWith(S.Union(ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP), {\n      nullable: true,\n      default: () => \"auto\" as const\n    }),\n    /**\n     * Maximum number of output tokens for a single assistant response,\n     * inclusive of tool calls. Provide an integer between 1 and 4096 to\n     * limit output tokens, or `inf` for the maximum available tokens for a\n     * given model. Defaults to `inf`.\n     */\n    \"max_output_tokens\": S.optionalWith(S.Union(S.Int, RealtimeSessionCreateRequestGAMaxOutputTokensEnum), {\n      nullable: true\n    }),\n    \"truncation\": S.optionalWith(RealtimeTruncation, { nullable: true }),\n    \"prompt\": S.optionalWith(\n      S.Struct({\n        /**\n         * The unique identifier of the prompt template to use.\n         */\n        \"id\": S.String,\n        \"version\": S.optionalWith(S.String, { nullable: true }),\n        \"variables\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n      }),\n      { nullable: true }\n    )\n  })\n{}\n\n/**\n * Parameters required to initiate a realtime call and receive the SDP answer\n * needed to complete a WebRTC peer connection. Provide an SDP offer generated\n * by your client and optionally configure the session that will answer the call.\n */\nexport class RealtimeCallCreateRequest extends S.Class<RealtimeCallCreateRequest>(\"RealtimeCallCreateRequest\")({\n  /**\n   * WebRTC Session Description Protocol (SDP) offer generated by the caller.\n   */\n  \"sdp\": S.String,\n  /**\n   * Optional session configuration to apply before the realtime session is\n   * created. Use the same parameters you would send in a [`create client secret`](https://platform.openai.com/docs/api-reference/realtime-sessions/create-realtime-client-secret)\n   * request.\n   */\n  \"session\": S.optionalWith(RealtimeSessionCreateRequestGA, { nullable: true })\n}) {}\n\n/**\n * Parameters required to transfer a SIP call to a new destination using the\n * Realtime API.\n */\nexport class RealtimeCallReferRequest extends S.Class<RealtimeCallReferRequest>(\"RealtimeCallReferRequest\")({\n  /**\n   * URI that should appear in the SIP Refer-To header. Supports values like\n   * `tel:+14155550123` or `sip:agent@example.com`.\n   */\n  \"target_uri\": S.String\n}) {}\n\n/**\n * Parameters used to decline an incoming SIP call handled by the Realtime API.\n */\nexport class RealtimeCallRejectRequest extends S.Class<RealtimeCallRejectRequest>(\"RealtimeCallRejectRequest\")({\n  /**\n   * SIP response code to send back to the caller. Defaults to `603` (Decline)\n   * when omitted.\n   */\n  \"status_code\": S.optionalWith(S.Int, { nullable: true })\n}) {}\n\n/**\n * The anchor point for the client secret expiration, meaning that `seconds` will be added to the `created_at` time of the client secret to produce an expiration timestamp. Only `created_at` is currently supported.\n */\nexport class RealtimeCreateClientSecretRequestExpiresAfterAnchor extends S.Literal(\"created_at\") {}\n\n/**\n * The type of session to create. Always `transcription` for transcription sessions.\n */\nexport class RealtimeTranscriptionSessionCreateRequestGAType extends S.Literal(\"transcription\") {}\n\n/**\n * Realtime transcription session object configuration.\n */\nexport class RealtimeTranscriptionSessionCreateRequestGA\n  extends S.Class<RealtimeTranscriptionSessionCreateRequestGA>(\"RealtimeTranscriptionSessionCreateRequestGA\")({\n    /**\n     * The type of session to create. Always `transcription` for transcription sessions.\n     */\n    \"type\": RealtimeTranscriptionSessionCreateRequestGAType,\n    /**\n     * Configuration for input and output audio.\n     */\n    \"audio\": S.optionalWith(\n      S.Struct({\n        \"input\": S.optionalWith(\n          S.Struct({\n            \"format\": S.optionalWith(RealtimeAudioFormats, { nullable: true }),\n            /**\n             * Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n             */\n            \"transcription\": S.optionalWith(AudioTranscription, { nullable: true }),\n            /**\n             * Configuration for input audio noise reduction. This can be set to `null` to turn off.\n             * Noise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\n             * Filtering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n             */\n            \"noise_reduction\": S.optionalWith(\n              S.Struct({\n                \"type\": S.optionalWith(NoiseReductionType, { nullable: true })\n              }),\n              { nullable: true }\n            ),\n            \"turn_detection\": S.optionalWith(\n              S.Union(\n                /**\n                 * Server-side voice activity detection (VAD) which flips on when user speech is detected and off after a period of silence.\n                 */\n                S.Struct({\n                  /**\n                   * Type of turn detection, `server_vad` to turn on simple Server VAD.\n                   */\n                  \"type\": S.Literal(\"server_vad\").pipe(\n                    S.propertySignature,\n                    S.withConstructorDefault(() => \"server_vad\" as const)\n                  ),\n                  /**\n                   * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\n                   * higher threshold will require louder audio to activate the model, and\n                   * thus might perform better in noisy environments.\n                   */\n                  \"threshold\": S.optionalWith(S.Number, { nullable: true }),\n                  /**\n                   * Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in\n                   * milliseconds). Defaults to 300ms.\n                   */\n                  \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true }),\n                  /**\n                   * Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults\n                   * to 500ms. With shorter values the model will respond more quickly,\n                   * but may jump in on short pauses from the user.\n                   */\n                  \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true }),\n                  /**\n                   * Whether or not to automatically generate a response when a VAD stop event occurs.\n                   */\n                  \"create_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n                  /**\n                   * Whether or not to automatically interrupt any ongoing response with output to the default\n                   * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n                   */\n                  \"interrupt_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n                  \"idle_timeout_ms\": S.optionalWith(\n                    S.Int.pipe(S.greaterThanOrEqualTo(5000), S.lessThanOrEqualTo(30000)),\n                    { nullable: true }\n                  )\n                }),\n                /**\n                 * Server-side semantic turn detection which uses a model to determine when the user has finished speaking.\n                 */\n                S.Struct({\n                  /**\n                   * Type of turn detection, `semantic_vad` to turn on Semantic VAD.\n                   */\n                  \"type\": S.Literal(\"semantic_vad\"),\n                  /**\n                   * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. `low`, `medium`, and `high` have max timeouts of 8s, 4s, and 2s respectively.\n                   */\n                  \"eagerness\": S.optionalWith(S.Literal(\"low\", \"medium\", \"high\", \"auto\"), {\n                    nullable: true,\n                    default: () => \"auto\" as const\n                  }),\n                  /**\n                   * Whether or not to automatically generate a response when a VAD stop event occurs.\n                   */\n                  \"create_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n                  /**\n                   * Whether or not to automatically interrupt any ongoing response with output to the default\n                   * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n                   */\n                  \"interrupt_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const })\n                })\n              ),\n              { nullable: true }\n            )\n          }),\n          { nullable: true }\n        )\n      }),\n      { nullable: true }\n    ),\n    /**\n     * Additional fields to include in server outputs.\n     *\n     * `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n     */\n    \"include\": S.optionalWith(S.Array(S.Literal(\"item.input_audio_transcription.logprobs\")), { nullable: true })\n  })\n{}\n\n/**\n * Create a session and client secret for the Realtime API. The request can specify\n * either a realtime or a transcription session configuration.\n * [Learn more about the Realtime API](https://platform.openai.com/docs/guides/realtime).\n */\nexport class RealtimeCreateClientSecretRequest\n  extends S.Class<RealtimeCreateClientSecretRequest>(\"RealtimeCreateClientSecretRequest\")({\n    /**\n     * Configuration for the client secret expiration. Expiration refers to the time after which\n     * a client secret will no longer be valid for creating sessions. The session itself may\n     * continue after that time once started. A secret can be used to create multiple sessions\n     * until it expires.\n     */\n    \"expires_after\": S.optionalWith(\n      S.Struct({\n        /**\n         * The anchor point for the client secret expiration, meaning that `seconds` will be added to the `created_at` time of the client secret to produce an expiration timestamp. Only `created_at` is currently supported.\n         */\n        \"anchor\": S.optionalWith(RealtimeCreateClientSecretRequestExpiresAfterAnchor, {\n          nullable: true,\n          default: () => \"created_at\" as const\n        }),\n        /**\n         * The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200` (2 hours). This default to 600 seconds (10 minutes) if not specified.\n         */\n        \"seconds\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(10), S.lessThanOrEqualTo(7200)), {\n          nullable: true,\n          default: () => 600 as const\n        })\n      }),\n      { nullable: true }\n    ),\n    /**\n     * Session configuration to use for the client secret. Choose either a realtime\n     * session or a transcription session.\n     */\n    \"session\": S.optionalWith(S.Union(RealtimeSessionCreateRequestGA, RealtimeTranscriptionSessionCreateRequestGA), {\n      nullable: true\n    })\n  })\n{}\n\n/**\n * The type of session to create. Always `realtime` for the Realtime API.\n */\nexport class RealtimeSessionCreateResponseGAType extends S.Literal(\"realtime\") {}\n\nexport class RealtimeSessionCreateResponseGAModelEnum extends S.Literal(\n  \"gpt-realtime\",\n  \"gpt-realtime-2025-08-28\",\n  \"gpt-4o-realtime-preview\",\n  \"gpt-4o-realtime-preview-2024-10-01\",\n  \"gpt-4o-realtime-preview-2024-12-17\",\n  \"gpt-4o-realtime-preview-2025-06-03\",\n  \"gpt-4o-mini-realtime-preview\",\n  \"gpt-4o-mini-realtime-preview-2024-12-17\",\n  \"gpt-realtime-mini\",\n  \"gpt-realtime-mini-2025-10-06\",\n  \"gpt-audio-mini\",\n  \"gpt-audio-mini-2025-10-06\"\n) {}\n\n/**\n * Enables tracing and sets default values for tracing configuration options. Always `auto`.\n */\nexport class RealtimeSessionCreateResponseGATracingEnum extends S.Literal(\"auto\") {}\n\nexport class RealtimeSessionCreateResponseGAMaxOutputTokensEnum extends S.Literal(\"inf\") {}\n\n/**\n * A new Realtime session configuration, with an ephemeral key. Default TTL\n * for keys is one minute.\n */\nexport class RealtimeSessionCreateResponseGA\n  extends S.Class<RealtimeSessionCreateResponseGA>(\"RealtimeSessionCreateResponseGA\")({\n    /**\n     * Ephemeral key returned by the API.\n     */\n    \"client_secret\": S.Struct({\n      /**\n       * Ephemeral key usable in client environments to authenticate connections to the Realtime API. Use this in client-side environments rather than a standard API token, which should only be used server-side.\n       */\n      \"value\": S.String,\n      /**\n       * Timestamp for when the token expires. Currently, all tokens expire\n       * after one minute.\n       */\n      \"expires_at\": S.Int\n    }),\n    /**\n     * The type of session to create. Always `realtime` for the Realtime API.\n     */\n    \"type\": RealtimeSessionCreateResponseGAType,\n    /**\n     * The set of modalities the model can respond with. It defaults to `[\"audio\"]`, indicating\n     * that the model will respond with audio plus a transcript. `[\"text\"]` can be used to make\n     * the model respond with text only. It is not possible to request both `text` and `audio` at the same time.\n     */\n    \"output_modalities\": S.optionalWith(S.Array(S.Literal(\"text\", \"audio\")), {\n      nullable: true,\n      default: () => [\"audio\"] as const\n    }),\n    /**\n     * The Realtime model used for this session.\n     */\n    \"model\": S.optionalWith(S.Union(S.String, RealtimeSessionCreateResponseGAModelEnum), { nullable: true }),\n    /**\n     * The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior.\n     *\n     * Note that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session.\n     */\n    \"instructions\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Configuration for input and output audio.\n     */\n    \"audio\": S.optionalWith(\n      S.Struct({\n        \"input\": S.optionalWith(\n          S.Struct({\n            /**\n             * The format of the input audio.\n             */\n            \"format\": S.optionalWith(RealtimeAudioFormats, { nullable: true }),\n            /**\n             * Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n             */\n            \"transcription\": S.optionalWith(AudioTranscription, { nullable: true }),\n            /**\n             * Configuration for input audio noise reduction. This can be set to `null` to turn off.\n             * Noise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\n             * Filtering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n             */\n            \"noise_reduction\": S.optionalWith(\n              S.Struct({\n                \"type\": S.optionalWith(NoiseReductionType, { nullable: true })\n              }),\n              { nullable: true }\n            ),\n            \"turn_detection\": S.optionalWith(\n              S.Union(\n                /**\n                 * Server-side voice activity detection (VAD) which flips on when user speech is detected and off after a period of silence.\n                 */\n                S.Struct({\n                  /**\n                   * Type of turn detection, `server_vad` to turn on simple Server VAD.\n                   */\n                  \"type\": S.Literal(\"server_vad\").pipe(\n                    S.propertySignature,\n                    S.withConstructorDefault(() => \"server_vad\" as const)\n                  ),\n                  /**\n                   * Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\n                   * higher threshold will require louder audio to activate the model, and\n                   * thus might perform better in noisy environments.\n                   */\n                  \"threshold\": S.optionalWith(S.Number, { nullable: true }),\n                  /**\n                   * Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in\n                   * milliseconds). Defaults to 300ms.\n                   */\n                  \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true }),\n                  /**\n                   * Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults\n                   * to 500ms. With shorter values the model will respond more quickly,\n                   * but may jump in on short pauses from the user.\n                   */\n                  \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true }),\n                  /**\n                   * Whether or not to automatically generate a response when a VAD stop event occurs.\n                   */\n                  \"create_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n                  /**\n                   * Whether or not to automatically interrupt any ongoing response with output to the default\n                   * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n                   */\n                  \"interrupt_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n                  \"idle_timeout_ms\": S.optionalWith(\n                    S.Int.pipe(S.greaterThanOrEqualTo(5000), S.lessThanOrEqualTo(30000)),\n                    { nullable: true }\n                  )\n                }),\n                /**\n                 * Server-side semantic turn detection which uses a model to determine when the user has finished speaking.\n                 */\n                S.Struct({\n                  /**\n                   * Type of turn detection, `semantic_vad` to turn on Semantic VAD.\n                   */\n                  \"type\": S.Literal(\"semantic_vad\"),\n                  /**\n                   * Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. `low`, `medium`, and `high` have max timeouts of 8s, 4s, and 2s respectively.\n                   */\n                  \"eagerness\": S.optionalWith(S.Literal(\"low\", \"medium\", \"high\", \"auto\"), {\n                    nullable: true,\n                    default: () => \"auto\" as const\n                  }),\n                  /**\n                   * Whether or not to automatically generate a response when a VAD stop event occurs.\n                   */\n                  \"create_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const }),\n                  /**\n                   * Whether or not to automatically interrupt any ongoing response with output to the default\n                   * conversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n                   */\n                  \"interrupt_response\": S.optionalWith(S.Boolean, { nullable: true, default: () => true as const })\n                })\n              ),\n              { nullable: true }\n            )\n          }),\n          { nullable: true }\n        ),\n        \"output\": S.optionalWith(\n          S.Struct({\n            /**\n             * The format of the output audio.\n             */\n            \"format\": S.optionalWith(RealtimeAudioFormats, { nullable: true }),\n            /**\n             * The voice the model uses to respond. Voice cannot be changed during the\n             * session once the model has responded with audio at least once. Current\n             * voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n             * `shimmer`, `verse`, `marin`, and `cedar`. We recommend `marin` and `cedar` for\n             * best quality.\n             */\n            \"voice\": S.optionalWith(VoiceIdsShared, { nullable: true }),\n            /**\n             * The speed of the model's spoken response as a multiple of the original speed.\n             * 1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum speed. This value can only be changed in between model turns, not while a response is in progress.\n             *\n             * This parameter is a post-processing adjustment to the audio after it is generated, it's\n             * also possible to prompt the model to speak faster or slower.\n             */\n            \"speed\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0.25), S.lessThanOrEqualTo(1.5)), {\n              nullable: true,\n              default: () => 1 as const\n            })\n          }),\n          { nullable: true }\n        )\n      }),\n      { nullable: true }\n    ),\n    /**\n     * Additional fields to include in server outputs.\n     *\n     * `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n     */\n    \"include\": S.optionalWith(S.Array(S.Literal(\"item.input_audio_transcription.logprobs\")), { nullable: true }),\n    \"tracing\": S.optionalWith(\n      S.Union(\n        /**\n         * Enables tracing and sets default values for tracing configuration options. Always `auto`.\n         */\n        RealtimeSessionCreateResponseGATracingEnum,\n        /**\n         * Granular configuration for tracing.\n         */\n        S.Struct({\n          /**\n           * The name of the workflow to attach to this trace. This is used to\n           * name the trace in the Traces Dashboard.\n           */\n          \"workflow_name\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The group id to attach to this trace to enable filtering and\n           * grouping in the Traces Dashboard.\n           */\n          \"group_id\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The arbitrary metadata to attach to this trace to enable\n           * filtering in the Traces Dashboard.\n           */\n          \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n        })\n      ),\n      { nullable: true }\n    ),\n    /**\n     * Tools available to the model.\n     */\n    \"tools\": S.optionalWith(S.Array(S.Union(RealtimeFunctionTool, MCPTool)), { nullable: true }),\n    /**\n     * How the model chooses tools. Provide one of the string modes or force a specific\n     * function/MCP tool.\n     */\n    \"tool_choice\": S.optionalWith(S.Union(ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP), {\n      nullable: true,\n      default: () => \"auto\" as const\n    }),\n    /**\n     * Maximum number of output tokens for a single assistant response,\n     * inclusive of tool calls. Provide an integer between 1 and 4096 to\n     * limit output tokens, or `inf` for the maximum available tokens for a\n     * given model. Defaults to `inf`.\n     */\n    \"max_output_tokens\": S.optionalWith(S.Union(S.Int, RealtimeSessionCreateResponseGAMaxOutputTokensEnum), {\n      nullable: true\n    }),\n    \"truncation\": S.optionalWith(RealtimeTruncation, { nullable: true }),\n    \"prompt\": S.optionalWith(\n      S.Struct({\n        /**\n         * The unique identifier of the prompt template to use.\n         */\n        \"id\": S.String,\n        \"version\": S.optionalWith(S.String, { nullable: true }),\n        \"variables\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n      }),\n      { nullable: true }\n    )\n  })\n{}\n\n/**\n * The type of session. Always `transcription` for transcription sessions.\n */\nexport class RealtimeTranscriptionSessionCreateResponseGAType extends S.Literal(\"transcription\") {}\n\n/**\n * A Realtime transcription session configuration object.\n */\nexport class RealtimeTranscriptionSessionCreateResponseGA\n  extends S.Class<RealtimeTranscriptionSessionCreateResponseGA>(\"RealtimeTranscriptionSessionCreateResponseGA\")({\n    /**\n     * The type of session. Always `transcription` for transcription sessions.\n     */\n    \"type\": RealtimeTranscriptionSessionCreateResponseGAType,\n    /**\n     * Unique identifier for the session that looks like `sess_1234567890abcdef`.\n     */\n    \"id\": S.String,\n    /**\n     * The object type. Always `realtime.transcription_session`.\n     */\n    \"object\": S.String,\n    /**\n     * Expiration timestamp for the session, in seconds since epoch.\n     */\n    \"expires_at\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * Additional fields to include in server outputs.\n     * - `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n     */\n    \"include\": S.optionalWith(S.Array(S.Literal(\"item.input_audio_transcription.logprobs\")), { nullable: true }),\n    /**\n     * Configuration for input audio for the session.\n     */\n    \"audio\": S.optionalWith(\n      S.Struct({\n        \"input\": S.optionalWith(\n          S.Struct({\n            \"format\": S.optionalWith(RealtimeAudioFormats, { nullable: true }),\n            /**\n             * Configuration of the transcription model.\n             */\n            \"transcription\": S.optionalWith(AudioTranscription, { nullable: true }),\n            /**\n             * Configuration for input audio noise reduction.\n             */\n            \"noise_reduction\": S.optionalWith(\n              S.Struct({\n                \"type\": S.optionalWith(NoiseReductionType, { nullable: true })\n              }),\n              { nullable: true }\n            ),\n            /**\n             * Configuration for turn detection. Can be set to `null` to turn off. Server\n             * VAD means that the model will detect the start and end of speech based on\n             * audio volume and respond at the end of user speech.\n             */\n            \"turn_detection\": S.optionalWith(\n              S.Struct({\n                /**\n                 * Type of turn detection, only `server_vad` is currently supported.\n                 */\n                \"type\": S.optionalWith(S.String, { nullable: true }),\n                /**\n                 * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\n                 * higher threshold will require louder audio to activate the model, and\n                 * thus might perform better in noisy environments.\n                 */\n                \"threshold\": S.optionalWith(S.Number, { nullable: true }),\n                /**\n                 * Amount of audio to include before the VAD detected speech (in\n                 * milliseconds). Defaults to 300ms.\n                 */\n                \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true }),\n                /**\n                 * Duration of silence to detect speech stop (in milliseconds). Defaults\n                 * to 500ms. With shorter values the model will respond more quickly,\n                 * but may jump in on short pauses from the user.\n                 */\n                \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true })\n              }),\n              { nullable: true }\n            )\n          }),\n          { nullable: true }\n        )\n      }),\n      { nullable: true }\n    )\n  })\n{}\n\n/**\n * Response from creating a session and client secret for the Realtime API.\n */\nexport class RealtimeCreateClientSecretResponse\n  extends S.Class<RealtimeCreateClientSecretResponse>(\"RealtimeCreateClientSecretResponse\")({\n    /**\n     * The generated client secret value.\n     */\n    \"value\": S.String,\n    /**\n     * Expiration timestamp for the client secret, in seconds since epoch.\n     */\n    \"expires_at\": S.Int,\n    /**\n     * The session configuration for either a realtime or transcription session.\n     */\n    \"session\": S.Union(RealtimeSessionCreateResponseGA, RealtimeTranscriptionSessionCreateResponseGA)\n  })\n{}\n\n/**\n * Default tracing mode for the session.\n */\nexport class RealtimeSessionCreateRequestTracingEnum extends S.Literal(\"auto\") {}\n\nexport class RealtimeSessionCreateRequestMaxResponseOutputTokensEnum extends S.Literal(\"inf\") {}\n\n/**\n * A new Realtime session configuration, with an ephemeral key. Default TTL\n * for keys is one minute.\n */\nexport class RealtimeSessionCreateRequest\n  extends S.Class<RealtimeSessionCreateRequest>(\"RealtimeSessionCreateRequest\")({\n    /**\n     * Ephemeral key returned by the API.\n     */\n    \"client_secret\": S.Struct({\n      /**\n       * Ephemeral key usable in client environments to authenticate connections\n       * to the Realtime API. Use this in client-side environments rather than\n       * a standard API token, which should only be used server-side.\n       */\n      \"value\": S.String,\n      /**\n       * Timestamp for when the token expires. Currently, all tokens expire\n       * after one minute.\n       */\n      \"expires_at\": S.Int\n    }),\n    /**\n     * The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior.\n     * Note that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session.\n     */\n    \"instructions\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The voice the model uses to respond. Voice cannot be changed during the\n     * session once the model has responded with audio at least once. Current\n     * voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n     * `shimmer`, and `verse`.\n     */\n    \"voice\": S.optionalWith(VoiceIdsShared, { nullable: true }),\n    /**\n     * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n     */\n    \"input_audio_format\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n     */\n    \"output_audio_format\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Configuration for input audio transcription, defaults to off and can be\n     * set to `null` to turn off once on. Input audio transcription is not native\n     * to the model, since the model consumes audio directly. Transcription runs\n     * asynchronously and should be treated as rough guidance\n     * rather than the representation understood by the model.\n     */\n    \"input_audio_transcription\": S.optionalWith(\n      S.Struct({\n        /**\n         * The model to use for transcription.\n         */\n        \"model\": S.optionalWith(S.String, { nullable: true })\n      }),\n      { nullable: true }\n    ),\n    /**\n     * The speed of the model's spoken response. 1.0 is the default speed. 0.25 is\n     * the minimum speed. 1.5 is the maximum speed. This value can only be changed\n     * in between model turns, not while a response is in progress.\n     */\n    \"speed\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0.25), S.lessThanOrEqualTo(1.5)), {\n      nullable: true,\n      default: () => 1 as const\n    }),\n    /**\n     * Configuration options for tracing. Set to null to disable tracing. Once\n     * tracing is enabled for a session, the configuration cannot be modified.\n     *\n     * `auto` will create a trace for the session with default values for the\n     * workflow name, group id, and metadata.\n     */\n    \"tracing\": S.optionalWith(\n      S.Union(\n        /**\n         * Default tracing mode for the session.\n         */\n        RealtimeSessionCreateRequestTracingEnum,\n        /**\n         * Granular configuration for tracing.\n         */\n        S.Struct({\n          /**\n           * The name of the workflow to attach to this trace. This is used to\n           * name the trace in the traces dashboard.\n           */\n          \"workflow_name\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The group id to attach to this trace to enable filtering and\n           * grouping in the traces dashboard.\n           */\n          \"group_id\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The arbitrary metadata to attach to this trace to enable\n           * filtering in the traces dashboard.\n           */\n          \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n        })\n      ),\n      { nullable: true }\n    ),\n    /**\n     * Configuration for turn detection. Can be set to `null` to turn off. Server\n     * VAD means that the model will detect the start and end of speech based on\n     * audio volume and respond at the end of user speech.\n     */\n    \"turn_detection\": S.optionalWith(\n      S.Struct({\n        /**\n         * Type of turn detection, only `server_vad` is currently supported.\n         */\n        \"type\": S.optionalWith(S.String, { nullable: true }),\n        /**\n         * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\n         * higher threshold will require louder audio to activate the model, and\n         * thus might perform better in noisy environments.\n         */\n        \"threshold\": S.optionalWith(S.Number, { nullable: true }),\n        /**\n         * Amount of audio to include before the VAD detected speech (in\n         * milliseconds). Defaults to 300ms.\n         */\n        \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true }),\n        /**\n         * Duration of silence to detect speech stop (in milliseconds). Defaults\n         * to 500ms. With shorter values the model will respond more quickly,\n         * but may jump in on short pauses from the user.\n         */\n        \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true })\n      }),\n      { nullable: true }\n    ),\n    /**\n     * Tools (functions) available to the model.\n     */\n    \"tools\": S.optionalWith(\n      S.Array(S.Struct({\n        /**\n         * The type of the tool, i.e. `function`.\n         */\n        \"type\": S.optionalWith(S.Literal(\"function\"), { nullable: true }),\n        /**\n         * The name of the function.\n         */\n        \"name\": S.optionalWith(S.String, { nullable: true }),\n        /**\n         * The description of the function, including guidance on when and how\n         * to call it, and guidance about what to tell the user when calling\n         * (if anything).\n         */\n        \"description\": S.optionalWith(S.String, { nullable: true }),\n        /**\n         * Parameters of the function in JSON Schema.\n         */\n        \"parameters\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n      })),\n      { nullable: true }\n    ),\n    /**\n     * How the model chooses tools. Options are `auto`, `none`, `required`, or\n     * specify a function.\n     */\n    \"tool_choice\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n     */\n    \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n    /**\n     * Maximum number of output tokens for a single assistant response,\n     * inclusive of tool calls. Provide an integer between 1 and 4096 to\n     * limit output tokens, or `inf` for the maximum available tokens for a\n     * given model. Defaults to `inf`.\n     */\n    \"max_response_output_tokens\": S.optionalWith(\n      S.Union(S.Int, RealtimeSessionCreateRequestMaxResponseOutputTokensEnum),\n      { nullable: true }\n    ),\n    \"truncation\": S.optionalWith(RealtimeTruncation, { nullable: true }),\n    \"prompt\": S.optionalWith(\n      S.Struct({\n        /**\n         * The unique identifier of the prompt template to use.\n         */\n        \"id\": S.String,\n        \"version\": S.optionalWith(S.String, { nullable: true }),\n        \"variables\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n      }),\n      { nullable: true }\n    )\n  })\n{}\n\n/**\n * Default tracing mode for the session.\n */\nexport class RealtimeSessionCreateResponseTracingEnum extends S.Literal(\"auto\") {}\n\nexport class RealtimeSessionCreateResponseMaxOutputTokensEnum extends S.Literal(\"inf\") {}\n\n/**\n * A Realtime session configuration object.\n */\nexport class RealtimeSessionCreateResponse\n  extends S.Class<RealtimeSessionCreateResponse>(\"RealtimeSessionCreateResponse\")({\n    /**\n     * Unique identifier for the session that looks like `sess_1234567890abcdef`.\n     */\n    \"id\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The object type. Always `realtime.session`.\n     */\n    \"object\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Expiration timestamp for the session, in seconds since epoch.\n     */\n    \"expires_at\": S.optionalWith(S.Int, { nullable: true }),\n    /**\n     * Additional fields to include in server outputs.\n     * - `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n     */\n    \"include\": S.optionalWith(S.Array(S.Literal(\"item.input_audio_transcription.logprobs\")), { nullable: true }),\n    /**\n     * The Realtime model used for this session.\n     */\n    \"model\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The default system instructions (i.e. system message) prepended to model\n     * calls. This field allows the client to guide the model on desired\n     * responses. The model can be instructed on response content and format,\n     * (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good\n     * responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion\n     * into your voice\", \"laugh frequently\"). The instructions are not guaranteed\n     * to be followed by the model, but they provide guidance to the model on the\n     * desired behavior.\n     *\n     * Note that the server sets default instructions which will be used if this\n     * field is not set and are visible in the `session.created` event at the\n     * start of the session.\n     */\n    \"instructions\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Configuration for input and output audio for the session.\n     */\n    \"audio\": S.optionalWith(\n      S.Struct({\n        \"input\": S.optionalWith(\n          S.Struct({\n            \"format\": S.optionalWith(RealtimeAudioFormats, { nullable: true }),\n            /**\n             * Configuration for input audio transcription.\n             */\n            \"transcription\": S.optionalWith(AudioTranscription, { nullable: true }),\n            /**\n             * Configuration for input audio noise reduction.\n             */\n            \"noise_reduction\": S.optionalWith(\n              S.Struct({\n                \"type\": S.optionalWith(NoiseReductionType, { nullable: true })\n              }),\n              { nullable: true }\n            ),\n            /**\n             * Configuration for turn detection.\n             */\n            \"turn_detection\": S.optionalWith(\n              S.Struct({\n                /**\n                 * Type of turn detection, only `server_vad` is currently supported.\n                 */\n                \"type\": S.optionalWith(S.String, { nullable: true }),\n                \"threshold\": S.optionalWith(S.Number, { nullable: true }),\n                \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true }),\n                \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true })\n              }),\n              { nullable: true }\n            )\n          }),\n          { nullable: true }\n        ),\n        \"output\": S.optionalWith(\n          S.Struct({\n            \"format\": S.optionalWith(RealtimeAudioFormats, { nullable: true }),\n            \"voice\": S.optionalWith(VoiceIdsShared, { nullable: true }),\n            \"speed\": S.optionalWith(S.Number, { nullable: true })\n          }),\n          { nullable: true }\n        )\n      }),\n      { nullable: true }\n    ),\n    /**\n     * Configuration options for tracing. Set to null to disable tracing. Once\n     * tracing is enabled for a session, the configuration cannot be modified.\n     *\n     * `auto` will create a trace for the session with default values for the\n     * workflow name, group id, and metadata.\n     */\n    \"tracing\": S.optionalWith(\n      S.Union(\n        /**\n         * Default tracing mode for the session.\n         */\n        RealtimeSessionCreateResponseTracingEnum,\n        /**\n         * Granular configuration for tracing.\n         */\n        S.Struct({\n          /**\n           * The name of the workflow to attach to this trace. This is used to\n           * name the trace in the traces dashboard.\n           */\n          \"workflow_name\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The group id to attach to this trace to enable filtering and\n           * grouping in the traces dashboard.\n           */\n          \"group_id\": S.optionalWith(S.String, { nullable: true }),\n          /**\n           * The arbitrary metadata to attach to this trace to enable\n           * filtering in the traces dashboard.\n           */\n          \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n        })\n      ),\n      { nullable: true }\n    ),\n    /**\n     * Configuration for turn detection. Can be set to `null` to turn off. Server\n     * VAD means that the model will detect the start and end of speech based on\n     * audio volume and respond at the end of user speech.\n     */\n    \"turn_detection\": S.optionalWith(\n      S.Struct({\n        /**\n         * Type of turn detection, only `server_vad` is currently supported.\n         */\n        \"type\": S.optionalWith(S.String, { nullable: true }),\n        /**\n         * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\n         * higher threshold will require louder audio to activate the model, and\n         * thus might perform better in noisy environments.\n         */\n        \"threshold\": S.optionalWith(S.Number, { nullable: true }),\n        /**\n         * Amount of audio to include before the VAD detected speech (in\n         * milliseconds). Defaults to 300ms.\n         */\n        \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true }),\n        /**\n         * Duration of silence to detect speech stop (in milliseconds). Defaults\n         * to 500ms. With shorter values the model will respond more quickly,\n         * but may jump in on short pauses from the user.\n         */\n        \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true })\n      }),\n      { nullable: true }\n    ),\n    /**\n     * Tools (functions) available to the model.\n     */\n    \"tools\": S.optionalWith(S.Array(RealtimeFunctionTool), { nullable: true }),\n    /**\n     * How the model chooses tools. Options are `auto`, `none`, `required`, or\n     * specify a function.\n     */\n    \"tool_choice\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Maximum number of output tokens for a single assistant response,\n     * inclusive of tool calls. Provide an integer between 1 and 4096 to\n     * limit output tokens, or `inf` for the maximum available tokens for a\n     * given model. Defaults to `inf`.\n     */\n    \"max_output_tokens\": S.optionalWith(S.Union(S.Int, RealtimeSessionCreateResponseMaxOutputTokensEnum), {\n      nullable: true\n    })\n  })\n{}\n\n/**\n * Type of turn detection. Only `server_vad` is currently supported for transcription sessions.\n */\nexport class RealtimeTranscriptionSessionCreateRequestTurnDetectionType extends S.Literal(\"server_vad\") {}\n\n/**\n * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n * For `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\n * single channel (mono), and little-endian byte order.\n */\nexport class RealtimeTranscriptionSessionCreateRequestInputAudioFormat\n  extends S.Literal(\"pcm16\", \"g711_ulaw\", \"g711_alaw\")\n{}\n\n/**\n * Realtime transcription session object configuration.\n */\nexport class RealtimeTranscriptionSessionCreateRequest\n  extends S.Class<RealtimeTranscriptionSessionCreateRequest>(\"RealtimeTranscriptionSessionCreateRequest\")({\n    /**\n     * Configuration for turn detection. Can be set to `null` to turn off. Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech.\n     */\n    \"turn_detection\": S.optionalWith(\n      S.Struct({\n        /**\n         * Type of turn detection. Only `server_vad` is currently supported for transcription sessions.\n         */\n        \"type\": S.optionalWith(RealtimeTranscriptionSessionCreateRequestTurnDetectionType, { nullable: true }),\n        /**\n         * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\n         * higher threshold will require louder audio to activate the model, and\n         * thus might perform better in noisy environments.\n         */\n        \"threshold\": S.optionalWith(S.Number, { nullable: true }),\n        /**\n         * Amount of audio to include before the VAD detected speech (in\n         * milliseconds). Defaults to 300ms.\n         */\n        \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true }),\n        /**\n         * Duration of silence to detect speech stop (in milliseconds). Defaults\n         * to 500ms. With shorter values the model will respond more quickly,\n         * but may jump in on short pauses from the user.\n         */\n        \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true })\n      }),\n      { nullable: true }\n    ),\n    /**\n     * Configuration for input audio noise reduction. This can be set to `null` to turn off.\n     * Noise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\n     * Filtering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n     */\n    \"input_audio_noise_reduction\": S.optionalWith(\n      S.Struct({\n        \"type\": S.optionalWith(NoiseReductionType, { nullable: true })\n      }),\n      { nullable: true }\n    ),\n    /**\n     * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n     * For `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\n     * single channel (mono), and little-endian byte order.\n     */\n    \"input_audio_format\": S.optionalWith(RealtimeTranscriptionSessionCreateRequestInputAudioFormat, {\n      nullable: true,\n      default: () => \"pcm16\" as const\n    }),\n    /**\n     * Configuration for input audio transcription. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n     */\n    \"input_audio_transcription\": S.optionalWith(AudioTranscription, { nullable: true }),\n    /**\n     * The set of items to include in the transcription. Current available items are:\n     * `item.input_audio_transcription.logprobs`\n     */\n    \"include\": S.optionalWith(S.Array(S.Literal(\"item.input_audio_transcription.logprobs\")), { nullable: true })\n  })\n{}\n\n/**\n * A new Realtime transcription session configuration.\n *\n * When a session is created on the server via REST API, the session object\n * also contains an ephemeral key. Default TTL for keys is 10 minutes. This\n * property is not present when a session is updated via the WebSocket API.\n */\nexport class RealtimeTranscriptionSessionCreateResponse\n  extends S.Class<RealtimeTranscriptionSessionCreateResponse>(\"RealtimeTranscriptionSessionCreateResponse\")({\n    /**\n     * Ephemeral key returned by the API. Only present when the session is\n     * created on the server via REST API.\n     */\n    \"client_secret\": S.Struct({\n      /**\n       * Ephemeral key usable in client environments to authenticate connections\n       * to the Realtime API. Use this in client-side environments rather than\n       * a standard API token, which should only be used server-side.\n       */\n      \"value\": S.String,\n      /**\n       * Timestamp for when the token expires. Currently, all tokens expire\n       * after one minute.\n       */\n      \"expires_at\": S.Int\n    }),\n    /**\n     * The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n     */\n    \"input_audio_format\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Configuration of the transcription model.\n     */\n    \"input_audio_transcription\": S.optionalWith(AudioTranscription, { nullable: true }),\n    /**\n     * Configuration for turn detection. Can be set to `null` to turn off. Server\n     * VAD means that the model will detect the start and end of speech based on\n     * audio volume and respond at the end of user speech.\n     */\n    \"turn_detection\": S.optionalWith(\n      S.Struct({\n        /**\n         * Type of turn detection, only `server_vad` is currently supported.\n         */\n        \"type\": S.optionalWith(S.String, { nullable: true }),\n        /**\n         * Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\n         * higher threshold will require louder audio to activate the model, and\n         * thus might perform better in noisy environments.\n         */\n        \"threshold\": S.optionalWith(S.Number, { nullable: true }),\n        /**\n         * Amount of audio to include before the VAD detected speech (in\n         * milliseconds). Defaults to 300ms.\n         */\n        \"prefix_padding_ms\": S.optionalWith(S.Int, { nullable: true }),\n        /**\n         * Duration of silence to detect speech stop (in milliseconds). Defaults\n         * to 500ms. With shorter values the model will respond more quickly,\n         * but may jump in on short pauses from the user.\n         */\n        \"silence_duration_ms\": S.optionalWith(S.Int, { nullable: true })\n      }),\n      { nullable: true }\n    )\n  })\n{}\n\n/**\n * Text, image, or file inputs to the model, used to generate a response.\n *\n * Learn more:\n * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n * - [Image inputs](https://platform.openai.com/docs/guides/images)\n * - [File inputs](https://platform.openai.com/docs/guides/pdf-files)\n * - [Conversation state](https://platform.openai.com/docs/guides/conversation-state)\n * - [Function calling](https://platform.openai.com/docs/guides/function-calling)\n */\nexport class InputParam extends S.Union(\n  /**\n   * A text input to the model, equivalent to a text input with the\n   * `user` role.\n   */\n  S.String,\n  /**\n   * A list of one or many input items to the model, containing\n   * different content types.\n   */\n  S.Array(InputItem)\n) {}\n\nexport class ResponseStreamOptions extends S.Union(\n  /**\n   * Options for streaming responses. Only set this when you set `stream: true`.\n   */\n  S.Struct({\n    /**\n     * When true, stream obfuscation will be enabled. Stream obfuscation adds\n     * random characters to an `obfuscation` field on streaming delta events to\n     * normalize payload sizes as a mitigation to certain side-channel attacks.\n     * These obfuscation fields are included by default, but add a small amount\n     * of overhead to the data stream. You can set `include_obfuscation` to\n     * false to optimize for bandwidth if you trust the network links between\n     * your application and the OpenAI API.\n     */\n    \"include_obfuscation\": S.optionalWith(S.Boolean, { nullable: true })\n  }),\n  S.Null\n) {}\n\n/**\n * The conversation that this response belongs to.\n */\nexport class ConversationParam2 extends S.Class<ConversationParam2>(\"ConversationParam2\")({\n  /**\n   * The unique ID of the conversation.\n   */\n  \"id\": S.String\n}) {}\n\n/**\n * The conversation that this response belongs to. Items from this conversation are prepended to `input_items` for this response request.\n * Input items and output items from this response are automatically added to this conversation after this response completes.\n */\nexport class ConversationParam extends S.Union(\n  /**\n   * The unique ID of the conversation.\n   */\n  S.String,\n  ConversationParam2\n) {}\n\nexport class ModelIdsResponsesEnum extends S.Literal(\n  \"o1-pro\",\n  \"o1-pro-2025-03-19\",\n  \"o3-pro\",\n  \"o3-pro-2025-06-10\",\n  \"o3-deep-research\",\n  \"o3-deep-research-2025-06-26\",\n  \"o4-mini-deep-research\",\n  \"o4-mini-deep-research-2025-06-26\",\n  \"computer-use-preview\",\n  \"computer-use-preview-2025-03-11\",\n  \"gpt-5-codex\",\n  \"gpt-5-pro\",\n  \"gpt-5-pro-2025-10-06\"\n) {}\n\nexport class ModelIdsResponses extends S.Union(ModelIdsShared, ModelIdsResponsesEnum) {}\n\n/**\n * A summary of the reasoning performed by the model. This can be\n * useful for debugging and understanding the model's reasoning process.\n * One of `auto`, `concise`, or `detailed`.\n *\n * `concise` is only supported for `computer-use-preview` models.\n */\nexport class ReasoningSummaryEnum extends S.Literal(\"auto\", \"concise\", \"detailed\") {}\n\n/**\n * **Deprecated:** use `summary` instead.\n *\n * A summary of the reasoning performed by the model. This can be\n * useful for debugging and understanding the model's reasoning process.\n * One of `auto`, `concise`, or `detailed`.\n */\nexport class ReasoningGenerateSummaryEnum extends S.Literal(\"auto\", \"concise\", \"detailed\") {}\n\n/**\n * **gpt-5 and o-series models only**\n *\n * Configuration options for\n * [reasoning models](https://platform.openai.com/docs/guides/reasoning).\n */\nexport class Reasoning extends S.Class<Reasoning>(\"Reasoning\")({\n  \"effort\": S.optionalWith(ReasoningEffortEnum, { nullable: true }),\n  \"summary\": S.optionalWith(ReasoningSummaryEnum, { nullable: true }),\n  \"generate_summary\": S.optionalWith(ReasoningGenerateSummaryEnum, { nullable: true })\n}) {}\n\n/**\n * Configuration options for a text response from the model. Can be plain\n * text or structured JSON data. Learn more:\n * - [Text inputs and outputs](https://platform.openai.com/docs/guides/text)\n * - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)\n */\nexport class ResponseTextParam extends S.Class<ResponseTextParam>(\"ResponseTextParam\")({\n  \"format\": S.optionalWith(TextResponseFormatConfiguration, { nullable: true }),\n  \"verbosity\": S.optionalWith(S.Literal(\"low\", \"medium\", \"high\"), { nullable: true })\n}) {}\n\n/**\n * An array of tools the model may call while generating a response. You\n * can specify which tool to use by setting the `tool_choice` parameter.\n *\n * We support the following categories of tools:\n * - **Built-in tools**: Tools that are provided by OpenAI that extend the\n *   model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search)\n *   or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about\n *   [built-in tools](https://platform.openai.com/docs/guides/tools).\n * - **MCP Tools**: Integrations with third-party systems via custom MCP servers\n *   or predefined connectors such as Google Drive and SharePoint. Learn more about\n *   [MCP Tools](https://platform.openai.com/docs/guides/tools-connectors-mcp).\n * - **Function calls (custom tools)**: Functions that are defined by you,\n *   enabling the model to call your own code with strongly typed arguments\n *   and outputs. Learn more about\n *   [function calling](https://platform.openai.com/docs/guides/function-calling). You can also use\n *   custom tools to call your own code.\n */\nexport class ToolsArray extends S.Array(Tool) {}\n\n/**\n * Allowed tool configuration type. Always `allowed_tools`.\n */\nexport class ToolChoiceAllowedType extends S.Literal(\"allowed_tools\") {}\n\n/**\n * Constrains the tools available to the model to a pre-defined set.\n *\n * `auto` allows the model to pick from among the allowed tools and generate a\n * message.\n *\n * `required` requires the model to call one or more of the allowed tools.\n */\nexport class ToolChoiceAllowedMode extends S.Literal(\"auto\", \"required\") {}\n\n/**\n * Constrains the tools available to the model to a pre-defined set.\n */\nexport class ToolChoiceAllowed extends S.Class<ToolChoiceAllowed>(\"ToolChoiceAllowed\")({\n  /**\n   * Allowed tool configuration type. Always `allowed_tools`.\n   */\n  \"type\": ToolChoiceAllowedType,\n  /**\n   * Constrains the tools available to the model to a pre-defined set.\n   *\n   * `auto` allows the model to pick from among the allowed tools and generate a\n   * message.\n   *\n   * `required` requires the model to call one or more of the allowed tools.\n   */\n  \"mode\": ToolChoiceAllowedMode,\n  /**\n   * A list of tool definitions that the model should be allowed to call.\n   *\n   * For the Responses API, the list of tool definitions might look like:\n   * ```json\n   * [\n   *   { \"type\": \"function\", \"name\": \"get_weather\" },\n   *   { \"type\": \"mcp\", \"server_label\": \"deepwiki\" },\n   *   { \"type\": \"image_generation\" }\n   * ]\n   * ```\n   */\n  \"tools\": S.Array(S.Record({ key: S.String, value: S.Unknown }))\n}) {}\n\n/**\n * The type of hosted tool the model should to use. Learn more about\n * [built-in tools](https://platform.openai.com/docs/guides/tools).\n *\n * Allowed values are:\n * - `file_search`\n * - `web_search_preview`\n * - `computer_use_preview`\n * - `code_interpreter`\n * - `image_generation`\n */\nexport class ToolChoiceTypesType extends S.Literal(\n  \"file_search\",\n  \"web_search_preview\",\n  \"computer_use_preview\",\n  \"web_search_preview_2025_03_11\",\n  \"image_generation\",\n  \"code_interpreter\"\n) {}\n\n/**\n * Indicates that the model should use a built-in tool to generate a response.\n * [Learn more about built-in tools](https://platform.openai.com/docs/guides/tools).\n */\nexport class ToolChoiceTypes extends S.Class<ToolChoiceTypes>(\"ToolChoiceTypes\")({\n  /**\n   * The type of hosted tool the model should to use. Learn more about\n   * [built-in tools](https://platform.openai.com/docs/guides/tools).\n   *\n   * Allowed values are:\n   * - `file_search`\n   * - `web_search_preview`\n   * - `computer_use_preview`\n   * - `code_interpreter`\n   * - `image_generation`\n   */\n  \"type\": ToolChoiceTypesType\n}) {}\n\n/**\n * For custom tool calling, the type is always `custom`.\n */\nexport class ToolChoiceCustomType extends S.Literal(\"custom\") {}\n\n/**\n * Use this option to force the model to call a specific custom tool.\n */\nexport class ToolChoiceCustom extends S.Class<ToolChoiceCustom>(\"ToolChoiceCustom\")({\n  /**\n   * For custom tool calling, the type is always `custom`.\n   */\n  \"type\": ToolChoiceCustomType,\n  /**\n   * The name of the custom tool to call.\n   */\n  \"name\": S.String\n}) {}\n\n/**\n * The tool to call. Always `apply_patch`.\n */\nexport class SpecificApplyPatchParamType extends S.Literal(\"apply_patch\") {}\n\n/**\n * Forces the model to call the apply_patch tool when executing a tool call.\n */\nexport class SpecificApplyPatchParam extends S.Class<SpecificApplyPatchParam>(\"SpecificApplyPatchParam\")({\n  /**\n   * The tool to call. Always `apply_patch`.\n   */\n  \"type\": SpecificApplyPatchParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"apply_patch\" as const))\n}) {}\n\n/**\n * The tool to call. Always `shell`.\n */\nexport class SpecificFunctionShellParamType extends S.Literal(\"shell\") {}\n\n/**\n * Forces the model to call the function shell tool when a tool call is required.\n */\nexport class SpecificFunctionShellParam extends S.Class<SpecificFunctionShellParam>(\"SpecificFunctionShellParam\")({\n  /**\n   * The tool to call. Always `shell`.\n   */\n  \"type\": SpecificFunctionShellParamType.pipe(S.propertySignature, S.withConstructorDefault(() => \"shell\" as const))\n}) {}\n\n/**\n * How the model should select which tool (or tools) to use when generating\n * a response. See the `tools` parameter to see how to specify which tools\n * the model can call.\n */\nexport class ToolChoiceParam extends S.Union(\n  ToolChoiceOptions,\n  ToolChoiceAllowed,\n  ToolChoiceTypes,\n  ToolChoiceFunction,\n  ToolChoiceMCP,\n  ToolChoiceCustom,\n  SpecificApplyPatchParam,\n  SpecificFunctionShellParam\n) {}\n\n/**\n * The truncation strategy to use for the model response.\n * - `auto`: If the input to this Response exceeds\n *   the model's context window size, the model will truncate the\n *   response to fit the context window by dropping items from the beginning of the conversation.\n * - `disabled` (default): If the input size will exceed the context window\n *   size for a model, the request will fail with a 400 error.\n */\nexport class CreateResponseTruncationEnum extends S.Literal(\"auto\", \"disabled\") {}\n\n/**\n * The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](https://platform.openai.com/docs/guides/prompt-caching#prompt-cache-retention).\n */\nexport class CreateResponsePromptCacheRetentionEnum extends S.Literal(\"in-memory\", \"24h\") {}\n\nexport class CreateResponse extends S.Class<CreateResponse>(\"CreateResponse\")({\n  \"input\": S.optionalWith(InputParam, { nullable: true }),\n  \"include\": S.optionalWith(S.Array(IncludeEnum), { nullable: true }),\n  \"parallel_tool_calls\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"store\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"instructions\": S.optionalWith(S.String, { nullable: true }),\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"stream_options\": S.optionalWith(\n    S.Struct({\n      /**\n       * When true, stream obfuscation will be enabled. Stream obfuscation adds\n       * random characters to an `obfuscation` field on streaming delta events to\n       * normalize payload sizes as a mitigation to certain side-channel attacks.\n       * These obfuscation fields are included by default, but add a small amount\n       * of overhead to the data stream. You can set `include_obfuscation` to\n       * false to optimize for bandwidth if you trust the network links between\n       * your application and the OpenAI API.\n       */\n      \"include_obfuscation\": S.optionalWith(S.Boolean, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"conversation\": S.optionalWith(ConversationParam, { nullable: true }),\n  \"previous_response_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\n   * offers a wide range of models with different capabilities, performance\n   * characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models)\n   * to browse and compare available models.\n   */\n  \"model\": S.optionalWith(ModelIdsResponses, { nullable: true }),\n  \"reasoning\": S.optionalWith(Reasoning, { nullable: true }),\n  \"background\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"max_output_tokens\": S.optionalWith(S.Int, { nullable: true }),\n  \"max_tool_calls\": S.optionalWith(S.Int, { nullable: true }),\n  \"text\": S.optionalWith(ResponseTextParam, { nullable: true }),\n  \"tools\": S.optionalWith(ToolsArray, { nullable: true }),\n  \"tool_choice\": S.optionalWith(ToolChoiceParam, { nullable: true }),\n  \"prompt\": S.optionalWith(\n    S.Struct({\n      /**\n       * The unique identifier of the prompt template to use.\n       */\n      \"id\": S.String,\n      \"version\": S.optionalWith(S.String, { nullable: true }),\n      \"variables\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"truncation\": S.optionalWith(CreateResponseTruncationEnum, { nullable: true }),\n  \"top_logprobs\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(20)), { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  /**\n   * This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\n   * A stable identifier for your end-users.\n   * Used to boost cache hit rates by better bucketing similar requests and  to help OpenAI detect and prevent abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n   */\n  \"user\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\n   * The IDs should be a string that uniquely identifies each user. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n   */\n  \"safety_identifier\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching).\n   */\n  \"prompt_cache_key\": S.optionalWith(S.String, { nullable: true }),\n  \"service_tier\": S.optionalWith(S.Literal(\"auto\", \"default\", \"flex\", \"scale\", \"priority\"), { nullable: true }),\n  \"prompt_cache_retention\": S.optionalWith(CreateResponsePromptCacheRetentionEnum, { nullable: true })\n}) {}\n\n/**\n * The object type of this resource - always set to `response`.\n */\nexport class ResponseObject extends S.Literal(\"response\") {}\n\n/**\n * The status of the response generation. One of `completed`, `failed`,\n * `in_progress`, `cancelled`, `queued`, or `incomplete`.\n */\nexport class ResponseStatus\n  extends S.Literal(\"completed\", \"failed\", \"in_progress\", \"cancelled\", \"queued\", \"incomplete\")\n{}\n\n/**\n * The error code for the response.\n */\nexport class ResponseErrorCode extends S.Literal(\n  \"server_error\",\n  \"rate_limit_exceeded\",\n  \"invalid_prompt\",\n  \"vector_store_timeout\",\n  \"invalid_image\",\n  \"invalid_image_format\",\n  \"invalid_base64_image\",\n  \"invalid_image_url\",\n  \"image_too_large\",\n  \"image_too_small\",\n  \"image_parse_error\",\n  \"image_content_policy_violation\",\n  \"invalid_image_mode\",\n  \"image_file_too_large\",\n  \"unsupported_image_media_type\",\n  \"empty_image_file\",\n  \"failed_to_download_image\",\n  \"image_file_not_found\"\n) {}\n\nexport class ResponseError extends S.Union(\n  /**\n   * An error object returned when the model fails to generate a Response.\n   */\n  S.Struct({\n    \"code\": ResponseErrorCode,\n    /**\n     * A human-readable description of the error.\n     */\n    \"message\": S.String\n  }),\n  S.Null\n) {}\n\n/**\n * The reason why the response is incomplete.\n */\nexport class ResponseIncompleteDetailsEnumReason extends S.Literal(\"max_output_tokens\", \"content_filter\") {}\n\nexport class OutputItem extends S.Union(\n  OutputMessage,\n  FileSearchToolCall,\n  FunctionToolCall,\n  WebSearchToolCall,\n  ComputerToolCall,\n  ReasoningItem,\n  ImageGenToolCall,\n  CodeInterpreterToolCall,\n  LocalShellToolCall,\n  FunctionShellCall,\n  FunctionShellCallOutput,\n  ApplyPatchToolCall,\n  ApplyPatchToolCallOutput,\n  MCPToolCall,\n  MCPListTools,\n  MCPApprovalRequest,\n  CustomToolCall\n) {}\n\n/**\n * Represents token usage details including input tokens, output tokens,\n * a breakdown of output tokens, and the total tokens used.\n */\nexport class ResponseUsage extends S.Class<ResponseUsage>(\"ResponseUsage\")({\n  /**\n   * The number of input tokens.\n   */\n  \"input_tokens\": S.Int,\n  /**\n   * A detailed breakdown of the input tokens.\n   */\n  \"input_tokens_details\": S.Struct({\n    /**\n     * The number of tokens that were retrieved from the cache.\n     * [More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching).\n     */\n    \"cached_tokens\": S.Int\n  }),\n  /**\n   * The number of output tokens.\n   */\n  \"output_tokens\": S.Int,\n  /**\n   * A detailed breakdown of the output tokens.\n   */\n  \"output_tokens_details\": S.Struct({\n    /**\n     * The number of reasoning tokens.\n     */\n    \"reasoning_tokens\": S.Int\n  }),\n  /**\n   * The total number of tokens used.\n   */\n  \"total_tokens\": S.Int\n}) {}\n\n/**\n * The conversation that this response belongs to. Input items and output items from this response are automatically added to this conversation.\n */\nexport class Conversation2 extends S.Class<Conversation2>(\"Conversation2\")({\n  /**\n   * The unique ID of the conversation.\n   */\n  \"id\": S.String\n}) {}\n\n/**\n * The truncation strategy to use for the model response.\n * - `auto`: If the input to this Response exceeds\n *   the model's context window size, the model will truncate the\n *   response to fit the context window by dropping items from the beginning of the conversation.\n * - `disabled` (default): If the input size will exceed the context window\n *   size for a model, the request will fail with a 400 error.\n */\nexport class ResponseTruncationEnum extends S.Literal(\"auto\", \"disabled\") {}\n\n/**\n * The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](https://platform.openai.com/docs/guides/prompt-caching#prompt-cache-retention).\n */\nexport class ResponsePromptCacheRetentionEnum extends S.Literal(\"in-memory\", \"24h\") {}\n\nexport class Response extends S.Class<Response>(\"Response\")({\n  /**\n   * Unique identifier for this Response.\n   */\n  \"id\": S.String,\n  /**\n   * The object type of this resource - always set to `response`.\n   */\n  \"object\": ResponseObject,\n  /**\n   * The status of the response generation. One of `completed`, `failed`,\n   * `in_progress`, `cancelled`, `queued`, or `incomplete`.\n   */\n  \"status\": S.optionalWith(ResponseStatus, { nullable: true }),\n  /**\n   * Unix timestamp (in seconds) of when this Response was created.\n   */\n  \"created_at\": S.Number,\n  \"error\": S.NullOr(S.Struct({\n    \"code\": ResponseErrorCode,\n    /**\n     * A human-readable description of the error.\n     */\n    \"message\": S.String\n  })),\n  \"incomplete_details\": S.NullOr(S.Struct({\n    /**\n     * The reason why the response is incomplete.\n     */\n    \"reason\": S.optionalWith(S.Literal(\"max_output_tokens\", \"content_filter\"), { nullable: true })\n  })),\n  /**\n   * An array of content items generated by the model.\n   *\n   * - The length and order of items in the `output` array is dependent\n   *   on the model's response.\n   * - Rather than accessing the first item in the `output` array and\n   *   assuming it's an `assistant` message with the content generated by\n   *   the model, you might consider using the `output_text` property where\n   *   supported in SDKs.\n   */\n  \"output\": S.Array(OutputItem),\n  \"instructions\": S.NullOr(S.Union(\n    /**\n     * A text input to the model, equivalent to a text input with the\n     * `developer` role.\n     */\n    S.String,\n    /**\n     * A list of one or many input items to the model, containing\n     * different content types.\n     */\n    S.Array(InputItem)\n  )),\n  \"output_text\": S.optionalWith(S.String, { nullable: true }),\n  \"usage\": S.optionalWith(ResponseUsage, { nullable: true }),\n  /**\n   * Whether to allow the model to run tool calls in parallel.\n   */\n  \"parallel_tool_calls\": S.Boolean.pipe(S.propertySignature, S.withConstructorDefault(() => true as const)),\n  \"conversation\": S.optionalWith(Conversation2, { nullable: true }),\n  \"previous_response_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\n   * offers a wide range of models with different capabilities, performance\n   * characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models)\n   * to browse and compare available models.\n   */\n  \"model\": ModelIdsResponses,\n  \"reasoning\": S.optionalWith(Reasoning, { nullable: true }),\n  \"background\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"max_output_tokens\": S.optionalWith(S.Int, { nullable: true }),\n  \"max_tool_calls\": S.optionalWith(S.Int, { nullable: true }),\n  \"text\": S.optionalWith(ResponseTextParam, { nullable: true }),\n  \"tools\": ToolsArray,\n  \"tool_choice\": ToolChoiceParam,\n  \"prompt\": S.optionalWith(\n    S.Struct({\n      /**\n       * The unique identifier of the prompt template to use.\n       */\n      \"id\": S.String,\n      \"version\": S.optionalWith(S.String, { nullable: true }),\n      \"variables\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"truncation\": S.optionalWith(ResponseTruncationEnum, { nullable: true }),\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown })),\n  \"top_logprobs\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(20)), { nullable: true }),\n  \"temperature\": S.NullOr(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2))),\n  \"top_p\": S.NullOr(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1))),\n  /**\n   * This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\n   * A stable identifier for your end-users.\n   * Used to boost cache hit rates by better bucketing similar requests and  to help OpenAI detect and prevent abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n   */\n  \"user\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\n   * The IDs should be a string that uniquely identifies each user. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).\n   */\n  \"safety_identifier\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching).\n   */\n  \"prompt_cache_key\": S.optionalWith(S.String, { nullable: true }),\n  \"service_tier\": S.optionalWith(S.Literal(\"auto\", \"default\", \"flex\", \"scale\", \"priority\"), { nullable: true }),\n  \"prompt_cache_retention\": S.optionalWith(ResponsePromptCacheRetentionEnum, { nullable: true })\n}) {}\n\nexport class GetResponseParams extends S.Struct({\n  \"include\": S.optionalWith(S.Array(IncludeEnum), { nullable: true }),\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"starting_after\": S.optionalWith(S.Int, { nullable: true }),\n  \"include_obfuscation\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class ListInputItemsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListInputItemsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListInputItemsParamsOrder, { nullable: true }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"include\": S.optionalWith(S.Array(IncludeEnum), { nullable: true })\n}) {}\n\n/**\n * The type of the message input. Always set to `message`.\n */\nexport class InputMessageResourceType extends S.Literal(\"message\") {}\n\n/**\n * The role of the message input. One of `user`, `system`, or `developer`.\n */\nexport class InputMessageResourceRole extends S.Literal(\"user\", \"system\", \"developer\") {}\n\n/**\n * The status of item. One of `in_progress`, `completed`, or\n * `incomplete`. Populated when items are returned via API.\n */\nexport class InputMessageResourceStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * A message input to the model with a role indicating instruction following\n * hierarchy. Instructions given with the `developer` or `system` role take\n * precedence over instructions given with the `user` role.\n */\nexport class InputMessageResource extends S.Class<InputMessageResource>(\"InputMessageResource\")({\n  /**\n   * The unique ID of the message input.\n   */\n  \"id\": S.String,\n  /**\n   * The type of the message input. Always set to `message`.\n   */\n  \"type\": S.optionalWith(InputMessageResourceType, { nullable: true }),\n  /**\n   * The role of the message input. One of `user`, `system`, or `developer`.\n   */\n  \"role\": InputMessageResourceRole,\n  /**\n   * The status of item. One of `in_progress`, `completed`, or\n   * `incomplete`. Populated when items are returned via API.\n   */\n  \"status\": S.optionalWith(InputMessageResourceStatus, { nullable: true }),\n  \"content\": InputMessageContentList\n}) {}\n\n/**\n * Content item used to generate a response.\n */\nexport class ItemResource extends S.Union(\n  InputMessageResource,\n  OutputMessage,\n  FileSearchToolCall,\n  ComputerToolCall,\n  ComputerToolCallOutputResource,\n  WebSearchToolCall,\n  FunctionToolCallResource,\n  FunctionToolCallOutputResource,\n  ImageGenToolCall,\n  CodeInterpreterToolCall,\n  LocalShellToolCall,\n  LocalShellToolCallOutput,\n  FunctionShellCall,\n  FunctionShellCallOutput,\n  ApplyPatchToolCall,\n  ApplyPatchToolCallOutput,\n  MCPListTools,\n  MCPApprovalRequest,\n  MCPApprovalResponseResource,\n  MCPToolCall\n) {}\n\n/**\n * A list of Response items.\n */\nexport class ResponseItemList extends S.Class<ResponseItemList>(\"ResponseItemList\")({\n  /**\n   * The type of object returned, must be `list`.\n   */\n  \"object\": S.Literal(\"list\"),\n  /**\n   * A list of items used to generate this response.\n   */\n  \"data\": S.Array(ItemResource),\n  /**\n   * Whether there are more items available.\n   */\n  \"has_more\": S.Boolean,\n  /**\n   * The ID of the first item in the list.\n   */\n  \"first_id\": S.String,\n  /**\n   * The ID of the last item in the list.\n   */\n  \"last_id\": S.String\n}) {}\n\n/**\n * The role of the entity that is creating the message. Allowed values include:\n * - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages.\n * - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation.\n */\nexport class CreateMessageRequestRole extends S.Literal(\"user\", \"assistant\") {}\n\n/**\n * Always `image_file`.\n */\nexport class MessageContentImageFileObjectType extends S.Literal(\"image_file\") {}\n\n/**\n * Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`.\n */\nexport class MessageContentImageFileObjectImageFileDetail extends S.Literal(\"auto\", \"low\", \"high\") {}\n\n/**\n * References an image [File](https://platform.openai.com/docs/api-reference/files) in the content of a message.\n */\nexport class MessageContentImageFileObject\n  extends S.Class<MessageContentImageFileObject>(\"MessageContentImageFileObject\")({\n    /**\n     * Always `image_file`.\n     */\n    \"type\": MessageContentImageFileObjectType,\n    \"image_file\": S.Struct({\n      /**\n       * The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. Set `purpose=\"vision\"` when uploading the File if you need to later display the file content.\n       */\n      \"file_id\": S.String,\n      /**\n       * Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`.\n       */\n      \"detail\": S.optionalWith(MessageContentImageFileObjectImageFileDetail, {\n        nullable: true,\n        default: () => \"auto\" as const\n      })\n    })\n  })\n{}\n\n/**\n * The type of the content part.\n */\nexport class MessageContentImageUrlObjectType extends S.Literal(\"image_url\") {}\n\n/**\n * Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto`\n */\nexport class MessageContentImageUrlObjectImageUrlDetail extends S.Literal(\"auto\", \"low\", \"high\") {}\n\n/**\n * References an image URL in the content of a message.\n */\nexport class MessageContentImageUrlObject\n  extends S.Class<MessageContentImageUrlObject>(\"MessageContentImageUrlObject\")({\n    /**\n     * The type of the content part.\n     */\n    \"type\": MessageContentImageUrlObjectType,\n    \"image_url\": S.Struct({\n      /**\n       * The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.\n       */\n      \"url\": S.String,\n      /**\n       * Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto`\n       */\n      \"detail\": S.optionalWith(MessageContentImageUrlObjectImageUrlDetail, {\n        nullable: true,\n        default: () => \"auto\" as const\n      })\n    })\n  })\n{}\n\n/**\n * Always `text`.\n */\nexport class MessageRequestContentTextObjectType extends S.Literal(\"text\") {}\n\n/**\n * The text content that is part of a message.\n */\nexport class MessageRequestContentTextObject\n  extends S.Class<MessageRequestContentTextObject>(\"MessageRequestContentTextObject\")({\n    /**\n     * Always `text`.\n     */\n    \"type\": MessageRequestContentTextObjectType,\n    /**\n     * Text content to be sent to the model\n     */\n    \"text\": S.String\n  })\n{}\n\n/**\n * The type of tool being defined: `file_search`\n */\nexport class AssistantToolsFileSearchTypeOnlyType extends S.Literal(\"file_search\") {}\n\nexport class AssistantToolsFileSearchTypeOnly\n  extends S.Class<AssistantToolsFileSearchTypeOnly>(\"AssistantToolsFileSearchTypeOnly\")({\n    /**\n     * The type of tool being defined: `file_search`\n     */\n    \"type\": AssistantToolsFileSearchTypeOnlyType\n  })\n{}\n\nexport class CreateMessageRequest extends S.Class<CreateMessageRequest>(\"CreateMessageRequest\")({\n  /**\n   * The role of the entity that is creating the message. Allowed values include:\n   * - `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages.\n   * - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation.\n   */\n  \"role\": CreateMessageRequestRole,\n  \"content\": S.Union(\n    /**\n     * The text contents of the message.\n     */\n    S.String,\n    /**\n     * An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](https://platform.openai.com/docs/models).\n     */\n    S.NonEmptyArray(\n      S.Union(MessageContentImageFileObject, MessageContentImageUrlObject, MessageRequestContentTextObject)\n    ).pipe(S.minItems(1))\n  ),\n  \"attachments\": S.optionalWith(\n    S.Array(S.Struct({\n      /**\n       * The ID of the file to attach to the message.\n       */\n      \"file_id\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The tools to add this file to.\n       */\n      \"tools\": S.optionalWith(S.Array(S.Union(AssistantToolsCode, AssistantToolsFileSearchTypeOnly)), {\n        nullable: true\n      })\n    })),\n    { nullable: true }\n  ),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * Options to create a new thread. If no thread is provided when running a\n * request, an empty thread will be created.\n */\nexport class CreateThreadRequest extends S.Class<CreateThreadRequest>(\"CreateThreadRequest\")({\n  /**\n   * A list of [messages](https://platform.openai.com/docs/api-reference/messages) to start the thread with.\n   */\n  \"messages\": S.optionalWith(S.Array(CreateMessageRequest), { nullable: true }),\n  \"tool_resources\": S.optionalWith(\n    S.Struct({\n      \"code_interpreter\": S.optionalWith(\n        S.Struct({\n          /**\n           * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n           */\n          \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(20)), {\n            nullable: true,\n            default: () => [] as const\n          })\n        }),\n        { nullable: true }\n      ),\n      \"file_search\": S.optionalWith(\n        S.Struct({\n          /**\n           * The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n           */\n          \"vector_store_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(1)), { nullable: true }),\n          /**\n           * A helper to create a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n           */\n          \"vector_stores\": S.optionalWith(\n            S.Array(S.Struct({\n              /**\n               * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to add to the vector store. There can be a maximum of 10000 files in a vector store.\n               */\n              \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(10000)), { nullable: true }),\n              /**\n               * The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy.\n               */\n              \"chunking_strategy\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n              \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n            })).pipe(S.maxItems(1)),\n            { nullable: true }\n          )\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `thread`.\n */\nexport class ThreadObjectObject extends S.Literal(\"thread\") {}\n\n/**\n * Represents a thread that contains [messages](https://platform.openai.com/docs/api-reference/messages).\n */\nexport class ThreadObject extends S.Class<ThreadObject>(\"ThreadObject\")({\n  /**\n   * The identifier, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `thread`.\n   */\n  \"object\": ThreadObjectObject,\n  /**\n   * The Unix timestamp (in seconds) for when the thread was created.\n   */\n  \"created_at\": S.Int,\n  \"tool_resources\": S.NullOr(S.Struct({\n    \"code_interpreter\": S.optionalWith(\n      S.Struct({\n        /**\n         * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n         */\n        \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(20)), {\n          nullable: true,\n          default: () => [] as const\n        })\n      }),\n      { nullable: true }\n    ),\n    \"file_search\": S.optionalWith(\n      S.Struct({\n        /**\n         * The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n         */\n        \"vector_store_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(1)), { nullable: true })\n      }),\n      { nullable: true }\n    )\n  })),\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown }))\n}) {}\n\nexport class CreateThreadAndRunRequestModelEnum extends S.Literal(\n  \"gpt-5\",\n  \"gpt-5-mini\",\n  \"gpt-5-nano\",\n  \"gpt-5-2025-08-07\",\n  \"gpt-5-mini-2025-08-07\",\n  \"gpt-5-nano-2025-08-07\",\n  \"gpt-4.1\",\n  \"gpt-4.1-mini\",\n  \"gpt-4.1-nano\",\n  \"gpt-4.1-2025-04-14\",\n  \"gpt-4.1-mini-2025-04-14\",\n  \"gpt-4.1-nano-2025-04-14\",\n  \"gpt-4o\",\n  \"gpt-4o-2024-11-20\",\n  \"gpt-4o-2024-08-06\",\n  \"gpt-4o-2024-05-13\",\n  \"gpt-4o-mini\",\n  \"gpt-4o-mini-2024-07-18\",\n  \"gpt-4.5-preview\",\n  \"gpt-4.5-preview-2025-02-27\",\n  \"gpt-4-turbo\",\n  \"gpt-4-turbo-2024-04-09\",\n  \"gpt-4-0125-preview\",\n  \"gpt-4-turbo-preview\",\n  \"gpt-4-1106-preview\",\n  \"gpt-4-vision-preview\",\n  \"gpt-4\",\n  \"gpt-4-0314\",\n  \"gpt-4-0613\",\n  \"gpt-4-32k\",\n  \"gpt-4-32k-0314\",\n  \"gpt-4-32k-0613\",\n  \"gpt-3.5-turbo\",\n  \"gpt-3.5-turbo-16k\",\n  \"gpt-3.5-turbo-0613\",\n  \"gpt-3.5-turbo-1106\",\n  \"gpt-3.5-turbo-0125\",\n  \"gpt-3.5-turbo-16k-0613\"\n) {}\n\n/**\n * The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`.\n */\nexport class CreateThreadAndRunRequestTruncationStrategyEnumType extends S.Literal(\"auto\", \"last_messages\") {}\n\n/**\n * Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run.\n */\nexport class CreateThreadAndRunRequestTruncationStrategy extends S.Struct({\n  /**\n   * The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`.\n   */\n  \"type\": S.Literal(\"auto\", \"last_messages\"),\n  \"last_messages\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true })\n}) {}\n\n/**\n * `none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user.\n */\nexport class CreateThreadAndRunRequestToolChoiceEnum extends S.Literal(\"none\", \"auto\", \"required\") {}\n\n/**\n * The type of the tool. If type is `function`, the function name must be set\n */\nexport class AssistantsNamedToolChoiceType extends S.Literal(\"function\", \"code_interpreter\", \"file_search\") {}\n\n/**\n * Specifies a tool the model should use. Use to force the model to call a specific tool.\n */\nexport class AssistantsNamedToolChoice extends S.Class<AssistantsNamedToolChoice>(\"AssistantsNamedToolChoice\")({\n  /**\n   * The type of the tool. If type is `function`, the function name must be set\n   */\n  \"type\": AssistantsNamedToolChoiceType,\n  \"function\": S.optionalWith(\n    S.Struct({\n      /**\n       * The name of the function to call.\n       */\n      \"name\": S.String\n    }),\n    { nullable: true }\n  )\n}) {}\n\n/**\n * Controls which (if any) tool is called by the model.\n * `none` means the model will not call any tools and instead generates a message.\n * `auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n * `required` means the model must call one or more tools before responding to the user.\n * Specifying a particular tool like `{\"type\": \"file_search\"}` or `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.\n */\nexport class CreateThreadAndRunRequestToolChoice extends S.Union(\n  /**\n   * `none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user.\n   */\n  CreateThreadAndRunRequestToolChoiceEnum,\n  AssistantsNamedToolChoice\n) {}\n\nexport class CreateThreadAndRunRequest extends S.Class<CreateThreadAndRunRequest>(\"CreateThreadAndRunRequest\")({\n  /**\n   * The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.\n   */\n  \"assistant_id\": S.String,\n  \"thread\": S.optionalWith(CreateThreadRequest, { nullable: true }),\n  /**\n   * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.\n   */\n  \"model\": S.optionalWith(S.Union(S.String, CreateThreadAndRunRequestModelEnum), { nullable: true }),\n  /**\n   * Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis.\n   */\n  \"instructions\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.\n   */\n  \"tools\": S.optionalWith(S.Array(AssistantTool).pipe(S.maxItems(20)), { nullable: true }),\n  /**\n   * A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n   */\n  \"tool_resources\": S.optionalWith(\n    S.Struct({\n      \"code_interpreter\": S.optionalWith(\n        S.Struct({\n          /**\n           * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n           */\n          \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(20)), {\n            nullable: true,\n            default: () => [] as const\n          })\n        }),\n        { nullable: true }\n      ),\n      \"file_search\": S.optionalWith(\n        S.Struct({\n          /**\n           * The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n           */\n          \"vector_store_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(1)), { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n   */\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n   *\n   * We generally recommend altering this or temperature but not both.\n   */\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n   */\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n   */\n  \"max_prompt_tokens\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(256)), { nullable: true }),\n  /**\n   * The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n   */\n  \"max_completion_tokens\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(256)), { nullable: true }),\n  \"truncation_strategy\": S.optionalWith(CreateThreadAndRunRequestTruncationStrategy, { nullable: true }),\n  \"tool_choice\": S.optionalWith(CreateThreadAndRunRequestToolChoice, { nullable: true }),\n  \"parallel_tool_calls\": S.optionalWith(ParallelToolCalls, { nullable: true, default: () => true as const }),\n  \"response_format\": S.optionalWith(AssistantsApiResponseFormatOption, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `thread.run`.\n */\nexport class RunObjectObject extends S.Literal(\"thread.run\") {}\n\n/**\n * The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`.\n */\nexport class RunStatus extends S.Literal(\n  \"queued\",\n  \"in_progress\",\n  \"requires_action\",\n  \"cancelling\",\n  \"cancelled\",\n  \"failed\",\n  \"completed\",\n  \"incomplete\",\n  \"expired\"\n) {}\n\n/**\n * For now, this is always `submit_tool_outputs`.\n */\nexport class RunObjectRequiredActionType extends S.Literal(\"submit_tool_outputs\") {}\n\n/**\n * The type of tool call the output is required for. For now, this is always `function`.\n */\nexport class RunToolCallObjectType extends S.Literal(\"function\") {}\n\n/**\n * Tool call objects\n */\nexport class RunToolCallObject extends S.Class<RunToolCallObject>(\"RunToolCallObject\")({\n  /**\n   * The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) endpoint.\n   */\n  \"id\": S.String,\n  /**\n   * The type of tool call the output is required for. For now, this is always `function`.\n   */\n  \"type\": RunToolCallObjectType,\n  /**\n   * The function definition.\n   */\n  \"function\": S.Struct({\n    /**\n     * The name of the function.\n     */\n    \"name\": S.String,\n    /**\n     * The arguments that the model expects you to pass to the function.\n     */\n    \"arguments\": S.String\n  })\n}) {}\n\n/**\n * One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`.\n */\nexport class RunObjectLastErrorCode extends S.Literal(\"server_error\", \"rate_limit_exceeded\", \"invalid_prompt\") {}\n\n/**\n * The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run.\n */\nexport class RunObjectIncompleteDetailsReason extends S.Literal(\"max_completion_tokens\", \"max_prompt_tokens\") {}\n\nexport class RunCompletionUsage extends S.Union(\n  /**\n   * Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.).\n   */\n  S.Struct({\n    /**\n     * Number of completion tokens used over the course of the run.\n     */\n    \"completion_tokens\": S.Int,\n    /**\n     * Number of prompt tokens used over the course of the run.\n     */\n    \"prompt_tokens\": S.Int,\n    /**\n     * Total number of tokens used (prompt + completion).\n     */\n    \"total_tokens\": S.Int\n  }),\n  S.Null\n) {}\n\n/**\n * The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`.\n */\nexport class RunObjectTruncationStrategyEnumType extends S.Literal(\"auto\", \"last_messages\") {}\n\n/**\n * Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run.\n */\nexport class RunObjectTruncationStrategy extends S.Struct({\n  /**\n   * The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`.\n   */\n  \"type\": S.Literal(\"auto\", \"last_messages\"),\n  \"last_messages\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true })\n}) {}\n\n/**\n * `none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user.\n */\nexport class RunObjectToolChoiceEnum extends S.Literal(\"none\", \"auto\", \"required\") {}\n\n/**\n * Controls which (if any) tool is called by the model.\n * `none` means the model will not call any tools and instead generates a message.\n * `auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n * `required` means the model must call one or more tools before responding to the user.\n * Specifying a particular tool like `{\"type\": \"file_search\"}` or `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.\n */\nexport class RunObjectToolChoice extends S.Union(\n  /**\n   * `none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user.\n   */\n  RunObjectToolChoiceEnum,\n  AssistantsNamedToolChoice\n) {}\n\n/**\n * Represents an execution run on a [thread](https://platform.openai.com/docs/api-reference/threads).\n */\nexport class RunObject extends S.Class<RunObject>(\"RunObject\")({\n  /**\n   * The identifier, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `thread.run`.\n   */\n  \"object\": RunObjectObject,\n  /**\n   * The Unix timestamp (in seconds) for when the run was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was executed on as a part of this run.\n   */\n  \"thread_id\": S.String,\n  /**\n   * The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for execution of this run.\n   */\n  \"assistant_id\": S.String,\n  \"status\": RunStatus,\n  /**\n   * Details on the action required to continue the run. Will be `null` if no action is required.\n   */\n  \"required_action\": S.NullOr(S.Struct({\n    /**\n     * For now, this is always `submit_tool_outputs`.\n     */\n    \"type\": RunObjectRequiredActionType,\n    /**\n     * Details on the tool outputs needed for this run to continue.\n     */\n    \"submit_tool_outputs\": S.Struct({\n      /**\n       * A list of the relevant tool calls.\n       */\n      \"tool_calls\": S.Array(RunToolCallObject)\n    })\n  })),\n  /**\n   * The last error associated with this run. Will be `null` if there are no errors.\n   */\n  \"last_error\": S.NullOr(S.Struct({\n    /**\n     * One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`.\n     */\n    \"code\": RunObjectLastErrorCode,\n    /**\n     * A human-readable description of the error.\n     */\n    \"message\": S.String\n  })),\n  /**\n   * The Unix timestamp (in seconds) for when the run will expire.\n   */\n  \"expires_at\": S.NullOr(S.Int),\n  /**\n   * The Unix timestamp (in seconds) for when the run was started.\n   */\n  \"started_at\": S.NullOr(S.Int),\n  /**\n   * The Unix timestamp (in seconds) for when the run was cancelled.\n   */\n  \"cancelled_at\": S.NullOr(S.Int),\n  /**\n   * The Unix timestamp (in seconds) for when the run failed.\n   */\n  \"failed_at\": S.NullOr(S.Int),\n  /**\n   * The Unix timestamp (in seconds) for when the run was completed.\n   */\n  \"completed_at\": S.NullOr(S.Int),\n  /**\n   * Details on why the run is incomplete. Will be `null` if the run is not incomplete.\n   */\n  \"incomplete_details\": S.NullOr(S.Struct({\n    /**\n     * The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run.\n     */\n    \"reason\": S.optionalWith(RunObjectIncompleteDetailsReason, { nullable: true })\n  })),\n  /**\n   * The model that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.\n   */\n  \"model\": S.String,\n  /**\n   * The instructions that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.\n   */\n  \"instructions\": S.String,\n  /**\n   * The list of tools that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run.\n   */\n  \"tools\": S.Array(AssistantTool).pipe(S.maxItems(20)).pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => [] as const)\n  ),\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown })),\n  \"usage\": S.NullOr(S.Struct({\n    /**\n     * Number of completion tokens used over the course of the run.\n     */\n    \"completion_tokens\": S.Int,\n    /**\n     * Number of prompt tokens used over the course of the run.\n     */\n    \"prompt_tokens\": S.Int,\n    /**\n     * Total number of tokens used (prompt + completion).\n     */\n    \"total_tokens\": S.Int\n  })),\n  /**\n   * The sampling temperature used for this run. If not set, defaults to 1.\n   */\n  \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * The nucleus sampling value used for this run. If not set, defaults to 1.\n   */\n  \"top_p\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * The maximum number of prompt tokens specified to have been used over the course of the run.\n   */\n  \"max_prompt_tokens\": S.NullOr(S.Int.pipe(S.greaterThanOrEqualTo(256))),\n  /**\n   * The maximum number of completion tokens specified to have been used over the course of the run.\n   */\n  \"max_completion_tokens\": S.NullOr(S.Int.pipe(S.greaterThanOrEqualTo(256))),\n  \"truncation_strategy\": RunObjectTruncationStrategy,\n  \"tool_choice\": RunObjectToolChoice,\n  \"parallel_tool_calls\": ParallelToolCalls.pipe(S.propertySignature, S.withConstructorDefault(() => true as const)),\n  \"response_format\": AssistantsApiResponseFormatOption\n}) {}\n\nexport class ModifyThreadRequest extends S.Class<ModifyThreadRequest>(\"ModifyThreadRequest\")({\n  \"tool_resources\": S.optionalWith(\n    S.Struct({\n      \"code_interpreter\": S.optionalWith(\n        S.Struct({\n          /**\n           * A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n           */\n          \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(20)), {\n            nullable: true,\n            default: () => [] as const\n          })\n        }),\n        { nullable: true }\n      ),\n      \"file_search\": S.optionalWith(\n        S.Struct({\n          /**\n           * The [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n           */\n          \"vector_store_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(1)), { nullable: true })\n        }),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class DeleteThreadResponseObject extends S.Literal(\"thread.deleted\") {}\n\nexport class DeleteThreadResponse extends S.Class<DeleteThreadResponse>(\"DeleteThreadResponse\")({\n  \"id\": S.String,\n  \"deleted\": S.Boolean,\n  \"object\": DeleteThreadResponseObject\n}) {}\n\nexport class ListMessagesParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListMessagesParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListMessagesParamsOrder, { nullable: true, default: () => \"desc\" as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"before\": S.optionalWith(S.String, { nullable: true }),\n  \"run_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `thread.message`.\n */\nexport class MessageObjectObject extends S.Literal(\"thread.message\") {}\n\n/**\n * The status of the message, which can be either `in_progress`, `incomplete`, or `completed`.\n */\nexport class MessageObjectStatus extends S.Literal(\"in_progress\", \"incomplete\", \"completed\") {}\n\n/**\n * The reason the message is incomplete.\n */\nexport class MessageObjectIncompleteDetailsEnumReason\n  extends S.Literal(\"content_filter\", \"max_tokens\", \"run_cancelled\", \"run_expired\", \"run_failed\")\n{}\n\n/**\n * The entity that produced the message. One of `user` or `assistant`.\n */\nexport class MessageObjectRole extends S.Literal(\"user\", \"assistant\") {}\n\n/**\n * Always `text`.\n */\nexport class MessageContentTextObjectType extends S.Literal(\"text\") {}\n\n/**\n * Always `file_citation`.\n */\nexport class MessageContentTextAnnotationsFileCitationObjectType extends S.Literal(\"file_citation\") {}\n\n/**\n * A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the \"file_search\" tool to search files.\n */\nexport class MessageContentTextAnnotationsFileCitationObject\n  extends S.Class<MessageContentTextAnnotationsFileCitationObject>(\"MessageContentTextAnnotationsFileCitationObject\")({\n    /**\n     * Always `file_citation`.\n     */\n    \"type\": MessageContentTextAnnotationsFileCitationObjectType,\n    /**\n     * The text in the message content that needs to be replaced.\n     */\n    \"text\": S.String,\n    \"file_citation\": S.Struct({\n      /**\n       * The ID of the specific File the citation is from.\n       */\n      \"file_id\": S.String\n    }),\n    \"start_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"end_index\": S.Int.pipe(S.greaterThanOrEqualTo(0))\n  })\n{}\n\n/**\n * Always `file_path`.\n */\nexport class MessageContentTextAnnotationsFilePathObjectType extends S.Literal(\"file_path\") {}\n\n/**\n * A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file.\n */\nexport class MessageContentTextAnnotationsFilePathObject\n  extends S.Class<MessageContentTextAnnotationsFilePathObject>(\"MessageContentTextAnnotationsFilePathObject\")({\n    /**\n     * Always `file_path`.\n     */\n    \"type\": MessageContentTextAnnotationsFilePathObjectType,\n    /**\n     * The text in the message content that needs to be replaced.\n     */\n    \"text\": S.String,\n    \"file_path\": S.Struct({\n      /**\n       * The ID of the file that was generated.\n       */\n      \"file_id\": S.String\n    }),\n    \"start_index\": S.Int.pipe(S.greaterThanOrEqualTo(0)),\n    \"end_index\": S.Int.pipe(S.greaterThanOrEqualTo(0))\n  })\n{}\n\nexport class TextAnnotation\n  extends S.Union(MessageContentTextAnnotationsFileCitationObject, MessageContentTextAnnotationsFilePathObject)\n{}\n\n/**\n * The text content that is part of a message.\n */\nexport class MessageContentTextObject extends S.Class<MessageContentTextObject>(\"MessageContentTextObject\")({\n  /**\n   * Always `text`.\n   */\n  \"type\": MessageContentTextObjectType,\n  \"text\": S.Struct({\n    /**\n     * The data that makes up the text.\n     */\n    \"value\": S.String,\n    \"annotations\": S.Array(TextAnnotation)\n  })\n}) {}\n\n/**\n * Always `refusal`.\n */\nexport class MessageContentRefusalObjectType extends S.Literal(\"refusal\") {}\n\n/**\n * The refusal content generated by the assistant.\n */\nexport class MessageContentRefusalObject extends S.Class<MessageContentRefusalObject>(\"MessageContentRefusalObject\")({\n  /**\n   * Always `refusal`.\n   */\n  \"type\": MessageContentRefusalObjectType,\n  \"refusal\": S.String\n}) {}\n\nexport class MessageContent extends S.Union(\n  MessageContentImageFileObject,\n  MessageContentImageUrlObject,\n  MessageContentTextObject,\n  MessageContentRefusalObject\n) {}\n\n/**\n * Represents a message within a [thread](https://platform.openai.com/docs/api-reference/threads).\n */\nexport class MessageObject extends S.Class<MessageObject>(\"MessageObject\")({\n  /**\n   * The identifier, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `thread.message`.\n   */\n  \"object\": MessageObjectObject,\n  /**\n   * The Unix timestamp (in seconds) for when the message was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The [thread](https://platform.openai.com/docs/api-reference/threads) ID that this message belongs to.\n   */\n  \"thread_id\": S.String,\n  /**\n   * The status of the message, which can be either `in_progress`, `incomplete`, or `completed`.\n   */\n  \"status\": MessageObjectStatus,\n  \"incomplete_details\": S.NullOr(S.Struct({\n    /**\n     * The reason the message is incomplete.\n     */\n    \"reason\": S.Literal(\"content_filter\", \"max_tokens\", \"run_cancelled\", \"run_expired\", \"run_failed\")\n  })),\n  \"completed_at\": S.NullOr(S.Int),\n  \"incomplete_at\": S.NullOr(S.Int),\n  /**\n   * The entity that produced the message. One of `user` or `assistant`.\n   */\n  \"role\": MessageObjectRole,\n  /**\n   * The content of the message in array of text and/or images.\n   */\n  \"content\": S.Array(MessageContent),\n  \"assistant_id\": S.NullOr(S.String),\n  \"run_id\": S.NullOr(S.String),\n  \"attachments\": S.NullOr(S.Array(S.Struct({\n    /**\n     * The ID of the file to attach to the message.\n     */\n    \"file_id\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The tools to add this file to.\n     */\n    \"tools\": S.optionalWith(S.Array(S.Union(AssistantToolsCode, AssistantToolsFileSearchTypeOnly)), { nullable: true })\n  }))),\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown }))\n}) {}\n\nexport class ListMessagesResponse extends S.Class<ListMessagesResponse>(\"ListMessagesResponse\")({\n  \"object\": S.String,\n  \"data\": S.Array(MessageObject),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\nexport class ModifyMessageRequest extends S.Class<ModifyMessageRequest>(\"ModifyMessageRequest\")({\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class DeleteMessageResponseObject extends S.Literal(\"thread.message.deleted\") {}\n\nexport class DeleteMessageResponse extends S.Class<DeleteMessageResponse>(\"DeleteMessageResponse\")({\n  \"id\": S.String,\n  \"deleted\": S.Boolean,\n  \"object\": DeleteMessageResponseObject\n}) {}\n\nexport class ListRunsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListRunsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListRunsParamsOrder, { nullable: true, default: () => \"desc\" as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"before\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListRunsResponse extends S.Class<ListRunsResponse>(\"ListRunsResponse\")({\n  \"object\": S.String,\n  \"data\": S.Array(RunObject),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\nexport class CreateRunParams extends S.Struct({\n  \"include[]\": S.optionalWith(S.Array(S.Literal(\"step_details.tool_calls[*].file_search.results[*].content\")), {\n    nullable: true\n  })\n}) {}\n\n/**\n * The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`.\n */\nexport class CreateRunRequestTruncationStrategyEnumType extends S.Literal(\"auto\", \"last_messages\") {}\n\n/**\n * Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run.\n */\nexport class CreateRunRequestTruncationStrategy extends S.Struct({\n  /**\n   * The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`.\n   */\n  \"type\": S.Literal(\"auto\", \"last_messages\"),\n  \"last_messages\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true })\n}) {}\n\n/**\n * `none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user.\n */\nexport class CreateRunRequestToolChoiceEnum extends S.Literal(\"none\", \"auto\", \"required\") {}\n\n/**\n * Controls which (if any) tool is called by the model.\n * `none` means the model will not call any tools and instead generates a message.\n * `auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n * `required` means the model must call one or more tools before responding to the user.\n * Specifying a particular tool like `{\"type\": \"file_search\"}` or `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.\n */\nexport class CreateRunRequestToolChoice extends S.Union(\n  /**\n   * `none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user.\n   */\n  CreateRunRequestToolChoiceEnum,\n  AssistantsNamedToolChoice\n) {}\n\nexport class CreateRunRequest extends S.Class<CreateRunRequest>(\"CreateRunRequest\")({\n  /**\n   * The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run.\n   */\n  \"assistant_id\": S.String,\n  /**\n   * The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used.\n   */\n  \"model\": S.optionalWith(S.Union(S.String, AssistantSupportedModels), { nullable: true }),\n  \"reasoning_effort\": S.optionalWith(S.Literal(\"none\", \"minimal\", \"low\", \"medium\", \"high\"), { nullable: true }),\n  /**\n   * Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis.\n   */\n  \"instructions\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.\n   */\n  \"additional_instructions\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Adds additional messages to the thread before creating the run.\n   */\n  \"additional_messages\": S.optionalWith(S.Array(CreateMessageRequest), { nullable: true }),\n  /**\n   * Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.\n   */\n  \"tools\": S.optionalWith(S.Array(AssistantTool).pipe(S.maxItems(20)), { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n   */\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n   *\n   * We generally recommend altering this or temperature but not both.\n   */\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  /**\n   * If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n   */\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n   */\n  \"max_prompt_tokens\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(256)), { nullable: true }),\n  /**\n   * The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n   */\n  \"max_completion_tokens\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(256)), { nullable: true }),\n  \"truncation_strategy\": S.optionalWith(CreateRunRequestTruncationStrategy, { nullable: true }),\n  \"tool_choice\": S.optionalWith(CreateRunRequestToolChoice, { nullable: true }),\n  \"parallel_tool_calls\": S.optionalWith(ParallelToolCalls, { nullable: true, default: () => true as const }),\n  \"response_format\": S.optionalWith(AssistantsApiResponseFormatOption, { nullable: true })\n}) {}\n\nexport class ModifyRunRequest extends S.Class<ModifyRunRequest>(\"ModifyRunRequest\")({\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class ListRunStepsParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListRunStepsParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListRunStepsParamsOrder, { nullable: true, default: () => \"desc\" as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"before\": S.optionalWith(S.String, { nullable: true }),\n  \"include[]\": S.optionalWith(S.Array(S.Literal(\"step_details.tool_calls[*].file_search.results[*].content\")), {\n    nullable: true\n  })\n}) {}\n\n/**\n * The object type, which is always `thread.run.step`.\n */\nexport class RunStepObjectObject extends S.Literal(\"thread.run.step\") {}\n\n/**\n * The type of run step, which can be either `message_creation` or `tool_calls`.\n */\nexport class RunStepObjectType extends S.Literal(\"message_creation\", \"tool_calls\") {}\n\n/**\n * The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`.\n */\nexport class RunStepObjectStatus extends S.Literal(\"in_progress\", \"cancelled\", \"failed\", \"completed\", \"expired\") {}\n\n/**\n * Always `message_creation`.\n */\nexport class RunStepDetailsMessageCreationObjectType extends S.Literal(\"message_creation\") {}\n\n/**\n * Details of the message creation by the run step.\n */\nexport class RunStepDetailsMessageCreationObject\n  extends S.Class<RunStepDetailsMessageCreationObject>(\"RunStepDetailsMessageCreationObject\")({\n    /**\n     * Always `message_creation`.\n     */\n    \"type\": RunStepDetailsMessageCreationObjectType,\n    \"message_creation\": S.Struct({\n      /**\n       * The ID of the message that was created by this run step.\n       */\n      \"message_id\": S.String\n    })\n  })\n{}\n\n/**\n * Always `tool_calls`.\n */\nexport class RunStepDetailsToolCallsObjectType extends S.Literal(\"tool_calls\") {}\n\n/**\n * The type of tool call. This is always going to be `code_interpreter` for this type of tool call.\n */\nexport class RunStepDetailsToolCallsCodeObjectType extends S.Literal(\"code_interpreter\") {}\n\n/**\n * Always `logs`.\n */\nexport class RunStepDetailsToolCallsCodeOutputLogsObjectType extends S.Literal(\"logs\") {}\n\n/**\n * Text output from the Code Interpreter tool call as part of a run step.\n */\nexport class RunStepDetailsToolCallsCodeOutputLogsObject\n  extends S.Class<RunStepDetailsToolCallsCodeOutputLogsObject>(\"RunStepDetailsToolCallsCodeOutputLogsObject\")({\n    /**\n     * Always `logs`.\n     */\n    \"type\": RunStepDetailsToolCallsCodeOutputLogsObjectType,\n    /**\n     * The text output from the Code Interpreter tool call.\n     */\n    \"logs\": S.String\n  })\n{}\n\n/**\n * Always `image`.\n */\nexport class RunStepDetailsToolCallsCodeOutputImageObjectType extends S.Literal(\"image\") {}\n\nexport class RunStepDetailsToolCallsCodeOutputImageObject\n  extends S.Class<RunStepDetailsToolCallsCodeOutputImageObject>(\"RunStepDetailsToolCallsCodeOutputImageObject\")({\n    /**\n     * Always `image`.\n     */\n    \"type\": RunStepDetailsToolCallsCodeOutputImageObjectType,\n    \"image\": S.Struct({\n      /**\n       * The [file](https://platform.openai.com/docs/api-reference/files) ID of the image.\n       */\n      \"file_id\": S.String\n    })\n  })\n{}\n\n/**\n * Details of the Code Interpreter tool call the run step was involved in.\n */\nexport class RunStepDetailsToolCallsCodeObject\n  extends S.Class<RunStepDetailsToolCallsCodeObject>(\"RunStepDetailsToolCallsCodeObject\")({\n    /**\n     * The ID of the tool call.\n     */\n    \"id\": S.String,\n    /**\n     * The type of tool call. This is always going to be `code_interpreter` for this type of tool call.\n     */\n    \"type\": RunStepDetailsToolCallsCodeObjectType,\n    /**\n     * The Code Interpreter tool call definition.\n     */\n    \"code_interpreter\": S.Struct({\n      /**\n       * The input to the Code Interpreter tool call.\n       */\n      \"input\": S.String,\n      /**\n       * The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type.\n       */\n      \"outputs\": S.Array(S.Record({ key: S.String, value: S.Unknown }))\n    })\n  })\n{}\n\n/**\n * The type of tool call. This is always going to be `file_search` for this type of tool call.\n */\nexport class RunStepDetailsToolCallsFileSearchObjectType extends S.Literal(\"file_search\") {}\n\n/**\n * The ranking options for the file search.\n */\nexport class RunStepDetailsToolCallsFileSearchRankingOptionsObject\n  extends S.Class<RunStepDetailsToolCallsFileSearchRankingOptionsObject>(\n    \"RunStepDetailsToolCallsFileSearchRankingOptionsObject\"\n  )({\n    \"ranker\": FileSearchRanker,\n    /**\n     * The score threshold for the file search. All values must be a floating point number between 0 and 1.\n     */\n    \"score_threshold\": S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1))\n  })\n{}\n\n/**\n * A result instance of the file search.\n */\nexport class RunStepDetailsToolCallsFileSearchResultObject\n  extends S.Class<RunStepDetailsToolCallsFileSearchResultObject>(\"RunStepDetailsToolCallsFileSearchResultObject\")({\n    /**\n     * The ID of the file that result was found in.\n     */\n    \"file_id\": S.String,\n    /**\n     * The name of the file that result was found in.\n     */\n    \"file_name\": S.String,\n    /**\n     * The score of the result. All values must be a floating point number between 0 and 1.\n     */\n    \"score\": S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)),\n    /**\n     * The content of the result that was found. The content is only included if requested via the include query parameter.\n     */\n    \"content\": S.optionalWith(\n      S.Array(S.Struct({\n        /**\n         * The type of the content.\n         */\n        \"type\": S.optionalWith(S.Literal(\"text\"), { nullable: true }),\n        /**\n         * The text content of the file.\n         */\n        \"text\": S.optionalWith(S.String, { nullable: true })\n      })),\n      { nullable: true }\n    )\n  })\n{}\n\nexport class RunStepDetailsToolCallsFileSearchObject\n  extends S.Class<RunStepDetailsToolCallsFileSearchObject>(\"RunStepDetailsToolCallsFileSearchObject\")({\n    /**\n     * The ID of the tool call object.\n     */\n    \"id\": S.String,\n    /**\n     * The type of tool call. This is always going to be `file_search` for this type of tool call.\n     */\n    \"type\": RunStepDetailsToolCallsFileSearchObjectType,\n    /**\n     * For now, this is always going to be an empty object.\n     */\n    \"file_search\": S.Struct({\n      \"ranking_options\": S.optionalWith(RunStepDetailsToolCallsFileSearchRankingOptionsObject, { nullable: true }),\n      /**\n       * The results of the file search.\n       */\n      \"results\": S.optionalWith(S.Array(RunStepDetailsToolCallsFileSearchResultObject), { nullable: true })\n    })\n  })\n{}\n\n/**\n * The type of tool call. This is always going to be `function` for this type of tool call.\n */\nexport class RunStepDetailsToolCallsFunctionObjectType extends S.Literal(\"function\") {}\n\nexport class RunStepDetailsToolCallsFunctionObject\n  extends S.Class<RunStepDetailsToolCallsFunctionObject>(\"RunStepDetailsToolCallsFunctionObject\")({\n    /**\n     * The ID of the tool call object.\n     */\n    \"id\": S.String,\n    /**\n     * The type of tool call. This is always going to be `function` for this type of tool call.\n     */\n    \"type\": RunStepDetailsToolCallsFunctionObjectType,\n    /**\n     * The definition of the function that was called.\n     */\n    \"function\": S.Struct({\n      /**\n       * The name of the function.\n       */\n      \"name\": S.String,\n      /**\n       * The arguments passed to the function.\n       */\n      \"arguments\": S.String,\n      \"output\": S.NullOr(S.String)\n    })\n  })\n{}\n\nexport class RunStepDetailsToolCall extends S.Union(\n  RunStepDetailsToolCallsCodeObject,\n  RunStepDetailsToolCallsFileSearchObject,\n  RunStepDetailsToolCallsFunctionObject\n) {}\n\n/**\n * Details of the tool call.\n */\nexport class RunStepDetailsToolCallsObject\n  extends S.Class<RunStepDetailsToolCallsObject>(\"RunStepDetailsToolCallsObject\")({\n    /**\n     * Always `tool_calls`.\n     */\n    \"type\": RunStepDetailsToolCallsObjectType,\n    /**\n     * An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n     */\n    \"tool_calls\": S.Array(RunStepDetailsToolCall)\n  })\n{}\n\n/**\n * One of `server_error` or `rate_limit_exceeded`.\n */\nexport class RunStepObjectLastErrorEnumCode extends S.Literal(\"server_error\", \"rate_limit_exceeded\") {}\n\nexport class RunStepCompletionUsage extends S.Union(\n  /**\n   * Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`.\n   */\n  S.Struct({\n    /**\n     * Number of completion tokens used over the course of the run step.\n     */\n    \"completion_tokens\": S.Int,\n    /**\n     * Number of prompt tokens used over the course of the run step.\n     */\n    \"prompt_tokens\": S.Int,\n    /**\n     * Total number of tokens used (prompt + completion).\n     */\n    \"total_tokens\": S.Int\n  }),\n  S.Null\n) {}\n\n/**\n * Represents a step in execution of a run.\n */\nexport class RunStepObject extends S.Class<RunStepObject>(\"RunStepObject\")({\n  /**\n   * The identifier of the run step, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `thread.run.step`.\n   */\n  \"object\": RunStepObjectObject,\n  /**\n   * The Unix timestamp (in seconds) for when the run step was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) associated with the run step.\n   */\n  \"assistant_id\": S.String,\n  /**\n   * The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) that was run.\n   */\n  \"thread_id\": S.String,\n  /**\n   * The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that this run step is a part of.\n   */\n  \"run_id\": S.String,\n  /**\n   * The type of run step, which can be either `message_creation` or `tool_calls`.\n   */\n  \"type\": RunStepObjectType,\n  /**\n   * The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`.\n   */\n  \"status\": RunStepObjectStatus,\n  /**\n   * The details of the run step.\n   */\n  \"step_details\": S.Record({ key: S.String, value: S.Unknown }),\n  \"last_error\": S.NullOr(S.Struct({\n    /**\n     * One of `server_error` or `rate_limit_exceeded`.\n     */\n    \"code\": S.Literal(\"server_error\", \"rate_limit_exceeded\"),\n    /**\n     * A human-readable description of the error.\n     */\n    \"message\": S.String\n  })),\n  \"expired_at\": S.NullOr(S.Int),\n  \"cancelled_at\": S.NullOr(S.Int),\n  \"failed_at\": S.NullOr(S.Int),\n  \"completed_at\": S.NullOr(S.Int),\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown })),\n  \"usage\": S.NullOr(S.Struct({\n    /**\n     * Number of completion tokens used over the course of the run step.\n     */\n    \"completion_tokens\": S.Int,\n    /**\n     * Number of prompt tokens used over the course of the run step.\n     */\n    \"prompt_tokens\": S.Int,\n    /**\n     * Total number of tokens used (prompt + completion).\n     */\n    \"total_tokens\": S.Int\n  }))\n}) {}\n\nexport class ListRunStepsResponse extends S.Class<ListRunStepsResponse>(\"ListRunStepsResponse\")({\n  \"object\": S.String,\n  \"data\": S.Array(RunStepObject),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\nexport class GetRunStepParams extends S.Struct({\n  \"include[]\": S.optionalWith(S.Array(S.Literal(\"step_details.tool_calls[*].file_search.results[*].content\")), {\n    nullable: true\n  })\n}) {}\n\nexport class SubmitToolOutputsRunRequest extends S.Class<SubmitToolOutputsRunRequest>(\"SubmitToolOutputsRunRequest\")({\n  /**\n   * A list of tools for which the outputs are being submitted.\n   */\n  \"tool_outputs\": S.Array(S.Struct({\n    /**\n     * The ID of the tool call in the `required_action` object within the run object the output is being submitted for.\n     */\n    \"tool_call_id\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The output of the tool call to be submitted to continue the run.\n     */\n    \"output\": S.optionalWith(S.String, { nullable: true })\n  })),\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * The intended purpose of the uploaded file.\n *\n * See the [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose).\n */\nexport class CreateUploadRequestPurpose extends S.Literal(\"assistants\", \"batch\", \"fine-tune\", \"vision\") {}\n\nexport class CreateUploadRequest extends S.Class<CreateUploadRequest>(\"CreateUploadRequest\")({\n  /**\n   * The name of the file to upload.\n   */\n  \"filename\": S.String,\n  /**\n   * The intended purpose of the uploaded file.\n   *\n   * See the [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose).\n   */\n  \"purpose\": CreateUploadRequestPurpose,\n  /**\n   * The number of bytes in the file you are uploading.\n   */\n  \"bytes\": S.Int,\n  /**\n   * The MIME type of the file.\n   *\n   * This must fall within the supported MIME types for your file purpose. See the supported MIME types for assistants and vision.\n   */\n  \"mime_type\": S.String,\n  \"expires_after\": S.optionalWith(FileExpirationAfter, { nullable: true })\n}) {}\n\n/**\n * The status of the Upload.\n */\nexport class UploadStatus extends S.Literal(\"pending\", \"completed\", \"cancelled\", \"expired\") {}\n\n/**\n * The object type, which is always \"upload\".\n */\nexport class UploadObject extends S.Literal(\"upload\") {}\n\n/**\n * The object type, which is always `file`.\n */\nexport class UploadFileEnumObject extends S.Literal(\"file\") {}\n\n/**\n * The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`.\n */\nexport class UploadFileEnumPurpose extends S.Literal(\n  \"assistants\",\n  \"assistants_output\",\n  \"batch\",\n  \"batch_output\",\n  \"fine-tune\",\n  \"fine-tune-results\",\n  \"vision\",\n  \"user_data\"\n) {}\n\n/**\n * Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`.\n */\nexport class UploadFileEnumStatus extends S.Literal(\"uploaded\", \"processed\", \"error\") {}\n\n/**\n * The ready File object after the Upload is completed.\n */\nexport class UploadFile extends S.Struct({\n  /**\n   * The file identifier, which can be referenced in the API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The size of the file, in bytes.\n   */\n  \"bytes\": S.Int,\n  /**\n   * The Unix timestamp (in seconds) for when the file was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The Unix timestamp (in seconds) for when the file will expire.\n   */\n  \"expires_at\": S.optionalWith(S.Int, { nullable: true }),\n  /**\n   * The name of the file.\n   */\n  \"filename\": S.String,\n  /**\n   * The object type, which is always `file`.\n   */\n  \"object\": S.Literal(\"file\"),\n  /**\n   * The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`.\n   */\n  \"purpose\": S.Literal(\n    \"assistants\",\n    \"assistants_output\",\n    \"batch\",\n    \"batch_output\",\n    \"fine-tune\",\n    \"fine-tune-results\",\n    \"vision\",\n    \"user_data\"\n  ),\n  /**\n   * Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`.\n   */\n  \"status\": S.Literal(\"uploaded\", \"processed\", \"error\"),\n  /**\n   * Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`.\n   */\n  \"status_details\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The Upload object can accept byte chunks in the form of Parts.\n */\nexport class Upload extends S.Class<Upload>(\"Upload\")({\n  /**\n   * The Upload unique identifier, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The Unix timestamp (in seconds) for when the Upload was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The name of the file to be uploaded.\n   */\n  \"filename\": S.String,\n  /**\n   * The intended number of bytes to be uploaded.\n   */\n  \"bytes\": S.Int,\n  /**\n   * The intended purpose of the file. [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) for acceptable values.\n   */\n  \"purpose\": S.String,\n  /**\n   * The status of the Upload.\n   */\n  \"status\": UploadStatus,\n  /**\n   * The Unix timestamp (in seconds) for when the Upload will expire.\n   */\n  \"expires_at\": S.Int,\n  /**\n   * The object type, which is always \"upload\".\n   */\n  \"object\": UploadObject,\n  \"file\": S.optionalWith(UploadFile, { nullable: true })\n}) {}\n\nexport class CompleteUploadRequest extends S.Class<CompleteUploadRequest>(\"CompleteUploadRequest\")({\n  /**\n   * The ordered list of Part IDs.\n   */\n  \"part_ids\": S.Array(S.String),\n  /**\n   * The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect.\n   */\n  \"md5\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class AddUploadPartRequest extends S.Class<AddUploadPartRequest>(\"AddUploadPartRequest\")({\n  /**\n   * The chunk of bytes for this Part.\n   */\n  \"data\": S.instanceOf(globalThis.Blob)\n}) {}\n\n/**\n * The object type, which is always `upload.part`.\n */\nexport class UploadPartObject extends S.Literal(\"upload.part\") {}\n\n/**\n * The upload Part represents a chunk of bytes we can add to an Upload object.\n */\nexport class UploadPart extends S.Class<UploadPart>(\"UploadPart\")({\n  /**\n   * The upload Part unique identifier, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The Unix timestamp (in seconds) for when the Part was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The ID of the Upload object that this Part was added to.\n   */\n  \"upload_id\": S.String,\n  /**\n   * The object type, which is always `upload.part`.\n   */\n  \"object\": UploadPartObject\n}) {}\n\nexport class ListVectorStoresParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListVectorStoresParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListVectorStoresParamsOrder, { nullable: true, default: () => \"desc\" as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"before\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `vector_store`.\n */\nexport class VectorStoreObjectObject extends S.Literal(\"vector_store\") {}\n\n/**\n * The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use.\n */\nexport class VectorStoreObjectStatus extends S.Literal(\"expired\", \"in_progress\", \"completed\") {}\n\n/**\n * Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`.\n */\nexport class VectorStoreExpirationAfterAnchor extends S.Literal(\"last_active_at\") {}\n\n/**\n * The expiration policy for a vector store.\n */\nexport class VectorStoreExpirationAfter extends S.Class<VectorStoreExpirationAfter>(\"VectorStoreExpirationAfter\")({\n  /**\n   * Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`.\n   */\n  \"anchor\": VectorStoreExpirationAfterAnchor,\n  /**\n   * The number of days after the anchor time that the vector store will expire.\n   */\n  \"days\": S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(365))\n}) {}\n\n/**\n * A vector store is a collection of processed files can be used by the `file_search` tool.\n */\nexport class VectorStoreObject extends S.Class<VectorStoreObject>(\"VectorStoreObject\")({\n  /**\n   * The identifier, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `vector_store`.\n   */\n  \"object\": VectorStoreObjectObject,\n  /**\n   * The Unix timestamp (in seconds) for when the vector store was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The name of the vector store.\n   */\n  \"name\": S.String,\n  /**\n   * The total number of bytes used by the files in the vector store.\n   */\n  \"usage_bytes\": S.Int,\n  \"file_counts\": S.Struct({\n    /**\n     * The number of files that are currently being processed.\n     */\n    \"in_progress\": S.Int,\n    /**\n     * The number of files that have been successfully processed.\n     */\n    \"completed\": S.Int,\n    /**\n     * The number of files that have failed to process.\n     */\n    \"failed\": S.Int,\n    /**\n     * The number of files that were cancelled.\n     */\n    \"cancelled\": S.Int,\n    /**\n     * The total number of files.\n     */\n    \"total\": S.Int\n  }),\n  /**\n   * The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use.\n   */\n  \"status\": VectorStoreObjectStatus,\n  \"expires_after\": S.optionalWith(VectorStoreExpirationAfter, { nullable: true }),\n  \"expires_at\": S.optionalWith(S.Int, { nullable: true }),\n  \"last_active_at\": S.NullOr(S.Int),\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown }))\n}) {}\n\nexport class ListVectorStoresResponse extends S.Class<ListVectorStoresResponse>(\"ListVectorStoresResponse\")({\n  \"object\": S.String,\n  \"data\": S.Array(VectorStoreObject),\n  \"first_id\": S.String,\n  \"last_id\": S.String,\n  \"has_more\": S.Boolean\n}) {}\n\n/**\n * Always `auto`.\n */\nexport class AutoChunkingStrategyRequestParamType extends S.Literal(\"auto\") {}\n\n/**\n * The default strategy. This strategy currently uses a `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`.\n */\nexport class AutoChunkingStrategyRequestParam\n  extends S.Class<AutoChunkingStrategyRequestParam>(\"AutoChunkingStrategyRequestParam\")({\n    /**\n     * Always `auto`.\n     */\n    \"type\": AutoChunkingStrategyRequestParamType\n  })\n{}\n\n/**\n * Always `static`.\n */\nexport class StaticChunkingStrategyRequestParamType extends S.Literal(\"static\") {}\n\nexport class StaticChunkingStrategy extends S.Class<StaticChunkingStrategy>(\"StaticChunkingStrategy\")({\n  /**\n   * The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`.\n   */\n  \"max_chunk_size_tokens\": S.Int.pipe(S.greaterThanOrEqualTo(100), S.lessThanOrEqualTo(4096)),\n  /**\n   * The number of tokens that overlap between chunks. The default value is `400`.\n   *\n   * Note that the overlap must not exceed half of `max_chunk_size_tokens`.\n   */\n  \"chunk_overlap_tokens\": S.Int\n}) {}\n\n/**\n * Customize your own chunking strategy by setting chunk size and chunk overlap.\n */\nexport class StaticChunkingStrategyRequestParam\n  extends S.Class<StaticChunkingStrategyRequestParam>(\"StaticChunkingStrategyRequestParam\")({\n    /**\n     * Always `static`.\n     */\n    \"type\": StaticChunkingStrategyRequestParamType,\n    \"static\": StaticChunkingStrategy\n  })\n{}\n\n/**\n * The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty.\n */\nexport class ChunkingStrategyRequestParam extends S.Record({ key: S.String, value: S.Unknown }) {}\n\nexport class CreateVectorStoreRequest extends S.Class<CreateVectorStoreRequest>(\"CreateVectorStoreRequest\")({\n  /**\n   * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files.\n   */\n  \"file_ids\": S.optionalWith(S.Array(S.String).pipe(S.maxItems(500)), { nullable: true }),\n  /**\n   * The name of the vector store.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * A description for the vector store. Can be used to describe the vector store's purpose.\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  \"expires_after\": S.optionalWith(VectorStoreExpirationAfter, { nullable: true }),\n  \"chunking_strategy\": S.optionalWith(ChunkingStrategyRequestParam, { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`.\n */\nexport class UpdateVectorStoreRequestExpiresAfterEnumAnchor extends S.Literal(\"last_active_at\") {}\n\n/**\n * The expiration policy for a vector store.\n */\nexport class UpdateVectorStoreRequestExpiresAfter extends S.Struct({\n  /**\n   * Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`.\n   */\n  \"anchor\": S.Literal(\"last_active_at\"),\n  /**\n   * The number of days after the anchor time that the vector store will expire.\n   */\n  \"days\": S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(365))\n}) {}\n\nexport class UpdateVectorStoreRequest extends S.Class<UpdateVectorStoreRequest>(\"UpdateVectorStoreRequest\")({\n  /**\n   * The name of the vector store.\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  \"expires_after\": S.optionalWith(UpdateVectorStoreRequestExpiresAfter, { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class DeleteVectorStoreResponseObject extends S.Literal(\"vector_store.deleted\") {}\n\nexport class DeleteVectorStoreResponse extends S.Class<DeleteVectorStoreResponse>(\"DeleteVectorStoreResponse\")({\n  \"id\": S.String,\n  \"deleted\": S.Boolean,\n  \"object\": DeleteVectorStoreResponseObject\n}) {}\n\nexport class CreateVectorStoreFileRequest\n  extends S.Class<CreateVectorStoreFileRequest>(\"CreateVectorStoreFileRequest\")({\n    /**\n     * A [File](https://platform.openai.com/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files.\n     */\n    \"file_id\": S.String,\n    \"chunking_strategy\": S.optionalWith(ChunkingStrategyRequestParam, { nullable: true }),\n    \"attributes\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\nexport class CreateVectorStoreFileBatchRequest\n  extends S.Class<CreateVectorStoreFileBatchRequest>(\"CreateVectorStoreFileBatchRequest\")({\n    /**\n     * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files.  If `attributes` or `chunking_strategy` are provided, they will be  applied to all files in the batch. Mutually exclusive with `files`.\n     */\n    \"file_ids\": S.optionalWith(S.NonEmptyArray(S.String).pipe(S.minItems(1), S.maxItems(500)), { nullable: true }),\n    /**\n     * A list of objects that each include a `file_id` plus optional `attributes` or `chunking_strategy`. Use this when you need to override metadata for specific files. The global `attributes` or `chunking_strategy` will be ignored and must be specified for each file. Mutually exclusive with `file_ids`.\n     */\n    \"files\": S.optionalWith(S.NonEmptyArray(CreateVectorStoreFileRequest).pipe(S.minItems(1), S.maxItems(500)), {\n      nullable: true\n    }),\n    \"chunking_strategy\": S.optionalWith(ChunkingStrategyRequestParam, { nullable: true }),\n    \"attributes\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * The object type, which is always `vector_store.file_batch`.\n */\nexport class VectorStoreFileBatchObjectObject extends S.Literal(\"vector_store.files_batch\") {}\n\n/**\n * The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`.\n */\nexport class VectorStoreFileBatchObjectStatus extends S.Literal(\"in_progress\", \"completed\", \"cancelled\", \"failed\") {}\n\n/**\n * A batch of files attached to a vector store.\n */\nexport class VectorStoreFileBatchObject extends S.Class<VectorStoreFileBatchObject>(\"VectorStoreFileBatchObject\")({\n  /**\n   * The identifier, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `vector_store.file_batch`.\n   */\n  \"object\": VectorStoreFileBatchObjectObject,\n  /**\n   * The Unix timestamp (in seconds) for when the vector store files batch was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to.\n   */\n  \"vector_store_id\": S.String,\n  /**\n   * The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`.\n   */\n  \"status\": VectorStoreFileBatchObjectStatus,\n  \"file_counts\": S.Struct({\n    /**\n     * The number of files that are currently being processed.\n     */\n    \"in_progress\": S.Int,\n    /**\n     * The number of files that have been processed.\n     */\n    \"completed\": S.Int,\n    /**\n     * The number of files that have failed to process.\n     */\n    \"failed\": S.Int,\n    /**\n     * The number of files that where cancelled.\n     */\n    \"cancelled\": S.Int,\n    /**\n     * The total number of files.\n     */\n    \"total\": S.Int\n  })\n}) {}\n\nexport class ListFilesInVectorStoreBatchParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListFilesInVectorStoreBatchParamsFilter\n  extends S.Literal(\"in_progress\", \"completed\", \"failed\", \"cancelled\")\n{}\n\nexport class ListFilesInVectorStoreBatchParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListFilesInVectorStoreBatchParamsOrder, { nullable: true, default: () => \"desc\" as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"before\": S.optionalWith(S.String, { nullable: true }),\n  \"filter\": S.optionalWith(ListFilesInVectorStoreBatchParamsFilter, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `vector_store.file`.\n */\nexport class VectorStoreFileObjectObject extends S.Literal(\"vector_store.file\") {}\n\n/**\n * The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use.\n */\nexport class VectorStoreFileObjectStatus extends S.Literal(\"in_progress\", \"completed\", \"cancelled\", \"failed\") {}\n\n/**\n * One of `server_error`, `unsupported_file`, or `invalid_file`.\n */\nexport class VectorStoreFileObjectLastErrorEnumCode\n  extends S.Literal(\"server_error\", \"unsupported_file\", \"invalid_file\")\n{}\n\n/**\n * Always `static`.\n */\nexport class StaticChunkingStrategyResponseParamType extends S.Literal(\"static\") {}\n\nexport class StaticChunkingStrategyResponseParam\n  extends S.Class<StaticChunkingStrategyResponseParam>(\"StaticChunkingStrategyResponseParam\")({\n    /**\n     * Always `static`.\n     */\n    \"type\": StaticChunkingStrategyResponseParamType,\n    \"static\": StaticChunkingStrategy\n  })\n{}\n\n/**\n * Always `other`.\n */\nexport class OtherChunkingStrategyResponseParamType extends S.Literal(\"other\") {}\n\n/**\n * This is returned when the chunking strategy is unknown. Typically, this is because the file was indexed before the `chunking_strategy` concept was introduced in the API.\n */\nexport class OtherChunkingStrategyResponseParam\n  extends S.Class<OtherChunkingStrategyResponseParam>(\"OtherChunkingStrategyResponseParam\")({\n    /**\n     * Always `other`.\n     */\n    \"type\": OtherChunkingStrategyResponseParamType\n  })\n{}\n\n/**\n * The strategy used to chunk the file.\n */\nexport class ChunkingStrategyResponse extends S.Record({ key: S.String, value: S.Unknown }) {}\n\n/**\n * A list of files attached to a vector store.\n */\nexport class VectorStoreFileObject extends S.Class<VectorStoreFileObject>(\"VectorStoreFileObject\")({\n  /**\n   * The identifier, which can be referenced in API endpoints.\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `vector_store.file`.\n   */\n  \"object\": VectorStoreFileObjectObject,\n  /**\n   * The total vector store usage in bytes. Note that this may be different from the original file size.\n   */\n  \"usage_bytes\": S.Int,\n  /**\n   * The Unix timestamp (in seconds) for when the vector store file was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * The ID of the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) that the [File](https://platform.openai.com/docs/api-reference/files) is attached to.\n   */\n  \"vector_store_id\": S.String,\n  /**\n   * The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use.\n   */\n  \"status\": VectorStoreFileObjectStatus,\n  \"last_error\": S.NullOr(S.Struct({\n    /**\n     * One of `server_error`, `unsupported_file`, or `invalid_file`.\n     */\n    \"code\": S.Literal(\"server_error\", \"unsupported_file\", \"invalid_file\"),\n    /**\n     * A human-readable description of the error.\n     */\n    \"message\": S.String\n  })),\n  \"chunking_strategy\": S.optionalWith(ChunkingStrategyResponse, { nullable: true }),\n  \"attributes\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class ListVectorStoreFilesResponse\n  extends S.Class<ListVectorStoreFilesResponse>(\"ListVectorStoreFilesResponse\")({\n    \"object\": S.String,\n    \"data\": S.Array(VectorStoreFileObject),\n    \"first_id\": S.String,\n    \"last_id\": S.String,\n    \"has_more\": S.Boolean\n  })\n{}\n\nexport class ListVectorStoreFilesParamsOrder extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListVectorStoreFilesParamsFilter extends S.Literal(\"in_progress\", \"completed\", \"failed\", \"cancelled\") {}\n\nexport class ListVectorStoreFilesParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int, { nullable: true, default: () => 20 as const }),\n  \"order\": S.optionalWith(ListVectorStoreFilesParamsOrder, { nullable: true, default: () => \"desc\" as const }),\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  \"before\": S.optionalWith(S.String, { nullable: true }),\n  \"filter\": S.optionalWith(ListVectorStoreFilesParamsFilter, { nullable: true })\n}) {}\n\nexport class UpdateVectorStoreFileAttributesRequest\n  extends S.Class<UpdateVectorStoreFileAttributesRequest>(\"UpdateVectorStoreFileAttributesRequest\")({\n    \"attributes\": S.NullOr(S.Record({ key: S.String, value: S.Unknown }))\n  })\n{}\n\nexport class DeleteVectorStoreFileResponseObject extends S.Literal(\"vector_store.file.deleted\") {}\n\nexport class DeleteVectorStoreFileResponse\n  extends S.Class<DeleteVectorStoreFileResponse>(\"DeleteVectorStoreFileResponse\")({\n    \"id\": S.String,\n    \"deleted\": S.Boolean,\n    \"object\": DeleteVectorStoreFileResponseObject\n  })\n{}\n\n/**\n * The object type, which is always `vector_store.file_content.page`\n */\nexport class VectorStoreFileContentResponseObject extends S.Literal(\"vector_store.file_content.page\") {}\n\n/**\n * Represents the parsed content of a vector store file.\n */\nexport class VectorStoreFileContentResponse\n  extends S.Class<VectorStoreFileContentResponse>(\"VectorStoreFileContentResponse\")({\n    /**\n     * The object type, which is always `vector_store.file_content.page`\n     */\n    \"object\": VectorStoreFileContentResponseObject,\n    /**\n     * Parsed content of the file.\n     */\n    \"data\": S.Array(S.Struct({\n      /**\n       * The content type (currently only `\"text\"`)\n       */\n      \"type\": S.optionalWith(S.String, { nullable: true }),\n      /**\n       * The text content\n       */\n      \"text\": S.optionalWith(S.String, { nullable: true })\n    })),\n    /**\n     * Indicates if there are more content pages to fetch.\n     */\n    \"has_more\": S.Boolean,\n    \"next_page\": S.NullOr(S.String)\n  })\n{}\n\n/**\n * Enable re-ranking; set to `none` to disable, which can help reduce latency.\n */\nexport class VectorStoreSearchRequestRankingOptionsRanker extends S.Literal(\"none\", \"auto\", \"default-2024-11-15\") {}\n\nexport class VectorStoreSearchRequest extends S.Class<VectorStoreSearchRequest>(\"VectorStoreSearchRequest\")({\n  /**\n   * A query string for a search\n   */\n  \"query\": S.Union(S.String, S.Array(S.String)),\n  /**\n   * Whether to rewrite the natural language query for vector search.\n   */\n  \"rewrite_query\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  /**\n   * The maximum number of results to return. This number should be between 1 and 50 inclusive.\n   */\n  \"max_num_results\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(50)), {\n    nullable: true,\n    default: () => 10 as const\n  }),\n  /**\n   * A filter to apply based on file attributes.\n   */\n  \"filters\": S.optionalWith(S.Union(ComparisonFilter, CompoundFilter), { nullable: true }),\n  /**\n   * Ranking options for search.\n   */\n  \"ranking_options\": S.optionalWith(\n    S.Struct({\n      /**\n       * Enable re-ranking; set to `none` to disable, which can help reduce latency.\n       */\n      \"ranker\": S.optionalWith(VectorStoreSearchRequestRankingOptionsRanker, {\n        nullable: true,\n        default: () => \"auto\" as const\n      }),\n      \"score_threshold\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), {\n        nullable: true,\n        default: () => 0 as const\n      })\n    }),\n    { nullable: true }\n  )\n}) {}\n\n/**\n * The object type, which is always `vector_store.search_results.page`\n */\nexport class VectorStoreSearchResultsPageObject extends S.Literal(\"vector_store.search_results.page\") {}\n\n/**\n * The type of content.\n */\nexport class VectorStoreSearchResultContentObjectType extends S.Literal(\"text\") {}\n\nexport class VectorStoreSearchResultContentObject\n  extends S.Class<VectorStoreSearchResultContentObject>(\"VectorStoreSearchResultContentObject\")({\n    /**\n     * The type of content.\n     */\n    \"type\": VectorStoreSearchResultContentObjectType,\n    /**\n     * The text content returned from search.\n     */\n    \"text\": S.String\n  })\n{}\n\nexport class VectorStoreSearchResultItem extends S.Class<VectorStoreSearchResultItem>(\"VectorStoreSearchResultItem\")({\n  /**\n   * The ID of the vector store file.\n   */\n  \"file_id\": S.String,\n  /**\n   * The name of the vector store file.\n   */\n  \"filename\": S.String,\n  /**\n   * The similarity score for the result.\n   */\n  \"score\": S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)),\n  \"attributes\": S.NullOr(S.Record({ key: S.String, value: S.Unknown })),\n  /**\n   * Content chunks from the file.\n   */\n  \"content\": S.Array(VectorStoreSearchResultContentObject)\n}) {}\n\nexport class VectorStoreSearchResultsPage\n  extends S.Class<VectorStoreSearchResultsPage>(\"VectorStoreSearchResultsPage\")({\n    /**\n     * The object type, which is always `vector_store.search_results.page`\n     */\n    \"object\": VectorStoreSearchResultsPageObject,\n    \"search_query\": S.Array(S.String),\n    /**\n     * The list of search result items.\n     */\n    \"data\": S.Array(VectorStoreSearchResultItem),\n    /**\n     * Indicates if there are more results to fetch.\n     */\n    \"has_more\": S.Boolean,\n    \"next_page\": S.NullOr(S.String)\n  })\n{}\n\nexport class CreateConversationBody extends S.Class<CreateConversationBody>(\"CreateConversationBody\")({\n  \"metadata\": S.optionalWith(Metadata, { nullable: true }),\n  \"items\": S.optionalWith(S.Array(InputItem).pipe(S.maxItems(20)), { nullable: true })\n}) {}\n\nexport class UpdateConversationBody extends S.Class<UpdateConversationBody>(\"UpdateConversationBody\")({\n  /**\n   * Set of 16 key-value pairs that can be attached to an object. This can be         useful for storing additional information about the object in a structured         format, and querying for objects via API or the dashboard.\n   *         Keys are strings with a maximum length of 64 characters. Values are strings         with a maximum length of 512 characters.\n   */\n  \"metadata\": S.NullOr(S.Record({ key: S.String, value: S.Unknown }))\n}) {}\n\nexport class DeletedConversationResourceObject extends S.Literal(\"conversation.deleted\") {}\n\nexport class DeletedConversationResource extends S.Class<DeletedConversationResource>(\"DeletedConversationResource\")({\n  \"object\": DeletedConversationResourceObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"conversation.deleted\" as const)\n  ),\n  \"deleted\": S.Boolean,\n  \"id\": S.String\n}) {}\n\nexport class OrderEnum extends S.Literal(\"asc\", \"desc\") {}\n\nexport class ListVideosParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(100)), { nullable: true }),\n  \"order\": S.optionalWith(OrderEnum, { nullable: true }),\n  /**\n   * Identifier for the last item from the previous pagination request\n   */\n  \"after\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * The object type, which is always `video`.\n */\nexport class VideoResourceObject extends S.Literal(\"video\") {}\n\nexport class VideoModel extends S.Literal(\"sora-2\", \"sora-2-pro\") {}\n\nexport class VideoStatus extends S.Literal(\"queued\", \"in_progress\", \"completed\", \"failed\") {}\n\nexport class VideoSize extends S.Literal(\"720x1280\", \"1280x720\", \"1024x1792\", \"1792x1024\") {}\n\nexport class VideoSeconds extends S.Literal(\"4\", \"8\", \"12\") {}\n\nexport class Error2 extends S.Class<Error2>(\"Error2\")({\n  \"code\": S.String,\n  \"message\": S.String\n}) {}\n\n/**\n * Structured information describing a generated video job.\n */\nexport class VideoResource extends S.Class<VideoResource>(\"VideoResource\")({\n  /**\n   * Unique identifier for the video job.\n   */\n  \"id\": S.String,\n  /**\n   * The object type, which is always `video`.\n   */\n  \"object\": VideoResourceObject.pipe(S.propertySignature, S.withConstructorDefault(() => \"video\" as const)),\n  /**\n   * The video generation model that produced the job.\n   */\n  \"model\": VideoModel,\n  /**\n   * Current lifecycle status of the video job.\n   */\n  \"status\": VideoStatus,\n  /**\n   * Approximate completion percentage for the generation task.\n   */\n  \"progress\": S.Int,\n  /**\n   * Unix timestamp (seconds) for when the job was created.\n   */\n  \"created_at\": S.Int,\n  \"completed_at\": S.NullOr(S.Int),\n  \"expires_at\": S.NullOr(S.Int),\n  \"prompt\": S.NullOr(S.String),\n  /**\n   * The resolution of the generated video.\n   */\n  \"size\": VideoSize,\n  /**\n   * Duration of the generated clip in seconds.\n   */\n  \"seconds\": VideoSeconds,\n  \"remixed_from_video_id\": S.NullOr(S.String),\n  \"error\": S.NullOr(Error2)\n}) {}\n\nexport class VideoListResource extends S.Class<VideoListResource>(\"VideoListResource\")({\n  /**\n   * The type of object returned, must be `list`.\n   */\n  \"object\": S.Literal(\"list\").pipe(S.propertySignature, S.withConstructorDefault(() => \"list\" as const)),\n  /**\n   * A list of items\n   */\n  \"data\": S.Array(VideoResource),\n  \"first_id\": S.NullOr(S.String),\n  \"last_id\": S.NullOr(S.String),\n  /**\n   * Whether there are more items available.\n   */\n  \"has_more\": S.Boolean\n}) {}\n\n/**\n * Parameters for creating a new video generation job.\n */\nexport class CreateVideoBody extends S.Class<CreateVideoBody>(\"CreateVideoBody\")({\n  /**\n   * The video generation model to use. Defaults to `sora-2`.\n   */\n  \"model\": S.optionalWith(VideoModel, { nullable: true }),\n  /**\n   * Text prompt that describes the video to generate.\n   */\n  \"prompt\": S.String.pipe(S.minLength(1), S.maxLength(32000)),\n  /**\n   * Optional image reference that guides generation.\n   */\n  \"input_reference\": S.optionalWith(S.instanceOf(globalThis.Blob), { nullable: true }),\n  /**\n   * Clip duration in seconds. Defaults to 4 seconds.\n   */\n  \"seconds\": S.optionalWith(VideoSeconds, { nullable: true }),\n  /**\n   * Output resolution formatted as width x height. Defaults to 720x1280.\n   */\n  \"size\": S.optionalWith(VideoSize, { nullable: true })\n}) {}\n\n/**\n * The object type that signals the deletion response.\n */\nexport class DeletedVideoResourceObject extends S.Literal(\"video.deleted\") {}\n\n/**\n * Confirmation payload returned after deleting a video.\n */\nexport class DeletedVideoResource extends S.Class<DeletedVideoResource>(\"DeletedVideoResource\")({\n  /**\n   * The object type that signals the deletion response.\n   */\n  \"object\": DeletedVideoResourceObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"video.deleted\" as const)\n  ),\n  /**\n   * Indicates that the video resource was deleted.\n   */\n  \"deleted\": S.Boolean,\n  /**\n   * Identifier of the deleted video.\n   */\n  \"id\": S.String\n}) {}\n\nexport class VideoContentVariant extends S.Literal(\"video\", \"thumbnail\", \"spritesheet\") {}\n\nexport class RetrieveVideoContentParams extends S.Struct({\n  \"variant\": S.optionalWith(VideoContentVariant, { nullable: true })\n}) {}\n\nexport class RetrieveVideoContent200 extends S.String {}\n\n/**\n * Parameters for remixing an existing generated video.\n */\nexport class CreateVideoRemixBody extends S.Class<CreateVideoRemixBody>(\"CreateVideoRemixBody\")({\n  /**\n   * Updated text prompt that directs the remix generation.\n   */\n  \"prompt\": S.String.pipe(S.minLength(1), S.maxLength(32000))\n}) {}\n\nexport class TruncationEnum extends S.Literal(\"auto\", \"disabled\") {}\n\nexport class TokenCountsBody extends S.Class<TokenCountsBody>(\"TokenCountsBody\")({\n  \"model\": S.optionalWith(S.String, { nullable: true }),\n  \"input\": S.optionalWith(\n    S.Union(\n      /**\n       * A text input to the model, equivalent to a text input with the `user` role.\n       */\n      S.String.pipe(S.maxLength(10485760)),\n      S.Array(InputItem)\n    ),\n    { nullable: true }\n  ),\n  \"previous_response_id\": S.optionalWith(S.String, { nullable: true }),\n  \"tools\": S.optionalWith(S.Array(Tool), { nullable: true }),\n  \"text\": S.optionalWith(ResponseTextParam, { nullable: true }),\n  \"reasoning\": S.optionalWith(Reasoning, { nullable: true }),\n  /**\n   * The truncation strategy to use for the model response. - `auto`: If the input to this Response exceeds the model's context window size, the model will truncate the response to fit the context window by dropping items from the beginning of the conversation. - `disabled` (default): If the input size will exceed the context window size for a model, the request will fail with a 400 error.\n   */\n  \"truncation\": S.optionalWith(TruncationEnum, { nullable: true }),\n  \"instructions\": S.optionalWith(S.String, { nullable: true }),\n  \"conversation\": S.optionalWith(ConversationParam, { nullable: true }),\n  \"tool_choice\": S.optionalWith(ToolChoiceParam, { nullable: true }),\n  \"parallel_tool_calls\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class TokenCountsResourceObject extends S.Literal(\"response.input_tokens\") {}\n\nexport class TokenCountsResource extends S.Class<TokenCountsResource>(\"TokenCountsResource\")({\n  \"object\": TokenCountsResourceObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"response.input_tokens\" as const)\n  ),\n  \"input_tokens\": S.Int\n}) {}\n\n/**\n * Type discriminator that is always `chatkit.session`.\n */\nexport class ChatSessionResourceObject extends S.Literal(\"chatkit.session\") {}\n\n/**\n * Controls diagnostic tracing during the session.\n */\nexport class ChatkitWorkflowTracing extends S.Class<ChatkitWorkflowTracing>(\"ChatkitWorkflowTracing\")({\n  /**\n   * Indicates whether tracing is enabled.\n   */\n  \"enabled\": S.Boolean\n}) {}\n\n/**\n * Workflow metadata and state returned for the session.\n */\nexport class ChatkitWorkflow extends S.Class<ChatkitWorkflow>(\"ChatkitWorkflow\")({\n  /**\n   * Identifier of the workflow backing the session.\n   */\n  \"id\": S.String,\n  \"version\": S.NullOr(S.String),\n  \"state_variables\": S.NullOr(S.Record({ key: S.String, value: S.Unknown })),\n  /**\n   * Tracing settings applied to the workflow.\n   */\n  \"tracing\": ChatkitWorkflowTracing\n}) {}\n\n/**\n * Active per-minute request limit for the session.\n */\nexport class ChatSessionRateLimits extends S.Class<ChatSessionRateLimits>(\"ChatSessionRateLimits\")({\n  /**\n   * Maximum allowed requests per one-minute window.\n   */\n  \"max_requests_per_1_minute\": S.Int\n}) {}\n\nexport class ChatSessionStatus extends S.Literal(\"active\", \"expired\", \"cancelled\") {}\n\n/**\n * Automatic thread title preferences for the session.\n */\nexport class ChatSessionAutomaticThreadTitling\n  extends S.Class<ChatSessionAutomaticThreadTitling>(\"ChatSessionAutomaticThreadTitling\")({\n    /**\n     * Whether automatic thread titling is enabled.\n     */\n    \"enabled\": S.Boolean\n  })\n{}\n\n/**\n * Upload permissions and limits applied to the session.\n */\nexport class ChatSessionFileUpload extends S.Class<ChatSessionFileUpload>(\"ChatSessionFileUpload\")({\n  /**\n   * Indicates if uploads are enabled for the session.\n   */\n  \"enabled\": S.Boolean,\n  \"max_file_size\": S.NullOr(S.Int),\n  \"max_files\": S.NullOr(S.Int)\n}) {}\n\n/**\n * History retention preferences returned for the session.\n */\nexport class ChatSessionHistory extends S.Class<ChatSessionHistory>(\"ChatSessionHistory\")({\n  /**\n   * Indicates if chat history is persisted for the session.\n   */\n  \"enabled\": S.Boolean,\n  \"recent_threads\": S.NullOr(S.Int)\n}) {}\n\n/**\n * ChatKit configuration for the session.\n */\nexport class ChatSessionChatkitConfiguration\n  extends S.Class<ChatSessionChatkitConfiguration>(\"ChatSessionChatkitConfiguration\")({\n    /**\n     * Automatic thread titling preferences.\n     */\n    \"automatic_thread_titling\": ChatSessionAutomaticThreadTitling,\n    /**\n     * Upload settings for the session.\n     */\n    \"file_upload\": ChatSessionFileUpload,\n    /**\n     * History retention configuration.\n     */\n    \"history\": ChatSessionHistory\n  })\n{}\n\n/**\n * Represents a ChatKit session and its resolved configuration.\n */\nexport class ChatSessionResource extends S.Class<ChatSessionResource>(\"ChatSessionResource\")({\n  /**\n   * Identifier for the ChatKit session.\n   */\n  \"id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.session`.\n   */\n  \"object\": ChatSessionResourceObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"chatkit.session\" as const)\n  ),\n  /**\n   * Unix timestamp (in seconds) for when the session expires.\n   */\n  \"expires_at\": S.Int,\n  /**\n   * Ephemeral client secret that authenticates session requests.\n   */\n  \"client_secret\": S.String,\n  /**\n   * Workflow metadata for the session.\n   */\n  \"workflow\": ChatkitWorkflow,\n  /**\n   * User identifier associated with the session.\n   */\n  \"user\": S.String,\n  /**\n   * Resolved rate limit values.\n   */\n  \"rate_limits\": ChatSessionRateLimits,\n  /**\n   * Convenience copy of the per-minute request limit.\n   */\n  \"max_requests_per_1_minute\": S.Int,\n  /**\n   * Current lifecycle state of the session.\n   */\n  \"status\": ChatSessionStatus,\n  /**\n   * Resolved ChatKit feature configuration for the session.\n   */\n  \"chatkit_configuration\": ChatSessionChatkitConfiguration\n}) {}\n\n/**\n * Controls diagnostic tracing during the session.\n */\nexport class WorkflowTracingParam extends S.Class<WorkflowTracingParam>(\"WorkflowTracingParam\")({\n  /**\n   * Whether tracing is enabled during the session. Defaults to true.\n   */\n  \"enabled\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * Workflow reference and overrides applied to the chat session.\n */\nexport class WorkflowParam extends S.Class<WorkflowParam>(\"WorkflowParam\")({\n  /**\n   * Identifier for the workflow invoked by the session.\n   */\n  \"id\": S.String,\n  /**\n   * Specific workflow version to run. Defaults to the latest deployed version.\n   */\n  \"version\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * State variables forwarded to the workflow. Keys may be up to 64 characters, values must be primitive types, and the map defaults to an empty object.\n   */\n  \"state_variables\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * Optional tracing overrides for the workflow invocation. When omitted, tracing is enabled by default.\n   */\n  \"tracing\": S.optionalWith(WorkflowTracingParam, { nullable: true })\n}) {}\n\n/**\n * Base timestamp used to calculate expiration. Currently fixed to `created_at`.\n */\nexport class ExpiresAfterParamAnchor extends S.Literal(\"created_at\") {}\n\n/**\n * Controls when the session expires relative to an anchor timestamp.\n */\nexport class ExpiresAfterParam extends S.Class<ExpiresAfterParam>(\"ExpiresAfterParam\")({\n  /**\n   * Base timestamp used to calculate expiration. Currently fixed to `created_at`.\n   */\n  \"anchor\": ExpiresAfterParamAnchor.pipe(S.propertySignature, S.withConstructorDefault(() => \"created_at\" as const)),\n  /**\n   * Number of seconds after the anchor when the session expires.\n   */\n  \"seconds\": S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(600))\n}) {}\n\n/**\n * Controls request rate limits for the session.\n */\nexport class RateLimitsParam extends S.Class<RateLimitsParam>(\"RateLimitsParam\")({\n  /**\n   * Maximum number of requests allowed per minute for the session. Defaults to 10.\n   */\n  \"max_requests_per_1_minute\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true })\n}) {}\n\n/**\n * Controls whether ChatKit automatically generates thread titles.\n */\nexport class AutomaticThreadTitlingParam extends S.Class<AutomaticThreadTitlingParam>(\"AutomaticThreadTitlingParam\")({\n  /**\n   * Enable automatic thread title generation. Defaults to true.\n   */\n  \"enabled\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * Controls whether users can upload files.\n */\nexport class FileUploadParam extends S.Class<FileUploadParam>(\"FileUploadParam\")({\n  /**\n   * Enable uploads for this session. Defaults to false.\n   */\n  \"enabled\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * Maximum size in megabytes for each uploaded file. Defaults to 512 MB, which is the maximum allowable size.\n   */\n  \"max_file_size\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(512)), { nullable: true }),\n  /**\n   * Maximum number of files that can be uploaded to the session. Defaults to 10.\n   */\n  \"max_files\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true })\n}) {}\n\n/**\n * Controls how much historical context is retained for the session.\n */\nexport class HistoryParam extends S.Class<HistoryParam>(\"HistoryParam\")({\n  /**\n   * Enables chat users to access previous ChatKit threads. Defaults to true.\n   */\n  \"enabled\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * Number of recent ChatKit threads users have access to. Defaults to unlimited when unset.\n   */\n  \"recent_threads\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1)), { nullable: true })\n}) {}\n\n/**\n * Optional per-session configuration settings for ChatKit behavior.\n */\nexport class ChatkitConfigurationParam extends S.Class<ChatkitConfigurationParam>(\"ChatkitConfigurationParam\")({\n  /**\n   * Configuration for automatic thread titling. When omitted, automatic thread titling is enabled by default.\n   */\n  \"automatic_thread_titling\": S.optionalWith(AutomaticThreadTitlingParam, { nullable: true }),\n  /**\n   * Configuration for upload enablement and limits. When omitted, uploads are disabled by default (max_files 10, max_file_size 512 MB).\n   */\n  \"file_upload\": S.optionalWith(FileUploadParam, { nullable: true }),\n  /**\n   * Configuration for chat history retention. When omitted, history is enabled by default with no limit on recent_threads (null).\n   */\n  \"history\": S.optionalWith(HistoryParam, { nullable: true })\n}) {}\n\n/**\n * Parameters for provisioning a new ChatKit session.\n */\nexport class CreateChatSessionBody extends S.Class<CreateChatSessionBody>(\"CreateChatSessionBody\")({\n  /**\n   * Workflow that powers the session.\n   */\n  \"workflow\": WorkflowParam,\n  /**\n   * A free-form string that identifies your end user; ensures this Session can access other objects that have the same `user` scope.\n   */\n  \"user\": S.String.pipe(S.minLength(1)),\n  /**\n   * Optional override for session expiration timing in seconds from creation. Defaults to 10 minutes.\n   */\n  \"expires_after\": S.optionalWith(ExpiresAfterParam, { nullable: true }),\n  /**\n   * Optional override for per-minute request limits. When omitted, defaults to 10.\n   */\n  \"rate_limits\": S.optionalWith(RateLimitsParam, { nullable: true }),\n  /**\n   * Optional overrides for ChatKit runtime configuration features\n   */\n  \"chatkit_configuration\": S.optionalWith(ChatkitConfigurationParam, { nullable: true })\n}) {}\n\nexport class ListThreadItemsMethodParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(100)), { nullable: true }),\n  \"order\": S.optionalWith(OrderEnum, { nullable: true }),\n  /**\n   * List items created after this thread item ID. Defaults to null for the first page.\n   */\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * List items created before this thread item ID. Defaults to null for the newest results.\n   */\n  \"before\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Type discriminator that is always `chatkit.thread_item`.\n */\nexport class UserMessageItemObject extends S.Literal(\"chatkit.thread_item\") {}\n\nexport class UserMessageItemType extends S.Literal(\"chatkit.user_message\") {}\n\n/**\n * Type discriminator that is always `input_text`.\n */\nexport class UserMessageInputTextType extends S.Literal(\"input_text\") {}\n\n/**\n * Text block that a user contributed to the thread.\n */\nexport class UserMessageInputText extends S.Class<UserMessageInputText>(\"UserMessageInputText\")({\n  /**\n   * Type discriminator that is always `input_text`.\n   */\n  \"type\": UserMessageInputTextType.pipe(S.propertySignature, S.withConstructorDefault(() => \"input_text\" as const)),\n  /**\n   * Plain-text content supplied by the user.\n   */\n  \"text\": S.String\n}) {}\n\n/**\n * Type discriminator that is always `quoted_text`.\n */\nexport class UserMessageQuotedTextType extends S.Literal(\"quoted_text\") {}\n\n/**\n * Quoted snippet that the user referenced in their message.\n */\nexport class UserMessageQuotedText extends S.Class<UserMessageQuotedText>(\"UserMessageQuotedText\")({\n  /**\n   * Type discriminator that is always `quoted_text`.\n   */\n  \"type\": UserMessageQuotedTextType.pipe(S.propertySignature, S.withConstructorDefault(() => \"quoted_text\" as const)),\n  /**\n   * Quoted text content.\n   */\n  \"text\": S.String\n}) {}\n\nexport class AttachmentType extends S.Literal(\"image\", \"file\") {}\n\n/**\n * Attachment metadata included on thread items.\n */\nexport class Attachment extends S.Class<Attachment>(\"Attachment\")({\n  /**\n   * Attachment discriminator.\n   */\n  \"type\": AttachmentType,\n  /**\n   * Identifier for the attachment.\n   */\n  \"id\": S.String,\n  /**\n   * Original display name for the attachment.\n   */\n  \"name\": S.String,\n  /**\n   * MIME type of the attachment.\n   */\n  \"mime_type\": S.String,\n  \"preview_url\": S.NullOr(S.String)\n}) {}\n\n/**\n * Tool selection that the assistant should honor when executing the item.\n */\nexport class ToolChoice extends S.Class<ToolChoice>(\"ToolChoice\")({\n  /**\n   * Identifier of the requested tool.\n   */\n  \"id\": S.String\n}) {}\n\n/**\n * Model and tool overrides applied when generating the assistant response.\n */\nexport class InferenceOptions extends S.Class<InferenceOptions>(\"InferenceOptions\")({\n  \"tool_choice\": S.NullOr(ToolChoice),\n  \"model\": S.NullOr(S.String)\n}) {}\n\n/**\n * User-authored messages within a thread.\n */\nexport class UserMessageItem extends S.Class<UserMessageItem>(\"UserMessageItem\")({\n  /**\n   * Identifier of the thread item.\n   */\n  \"id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.thread_item`.\n   */\n  \"object\": UserMessageItemObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"chatkit.thread_item\" as const)\n  ),\n  /**\n   * Unix timestamp (in seconds) for when the item was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Identifier of the parent thread.\n   */\n  \"thread_id\": S.String,\n  \"type\": UserMessageItemType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"chatkit.user_message\" as const)\n  ),\n  /**\n   * Ordered content elements supplied by the user.\n   */\n  \"content\": S.Array(S.Union(UserMessageInputText, UserMessageQuotedText)),\n  /**\n   * Attachments associated with the user message. Defaults to an empty list.\n   */\n  \"attachments\": S.Array(Attachment),\n  \"inference_options\": S.NullOr(InferenceOptions)\n}) {}\n\n/**\n * Type discriminator that is always `chatkit.thread_item`.\n */\nexport class AssistantMessageItemObject extends S.Literal(\"chatkit.thread_item\") {}\n\n/**\n * Type discriminator that is always `chatkit.assistant_message`.\n */\nexport class AssistantMessageItemType extends S.Literal(\"chatkit.assistant_message\") {}\n\n/**\n * Type discriminator that is always `output_text`.\n */\nexport class ResponseOutputTextType extends S.Literal(\"output_text\") {}\n\n/**\n * Type discriminator that is always `file` for this annotation.\n */\nexport class FileAnnotationType extends S.Literal(\"file\") {}\n\n/**\n * Type discriminator that is always `file`.\n */\nexport class FileAnnotationSourceType extends S.Literal(\"file\") {}\n\n/**\n * Attachment source referenced by an annotation.\n */\nexport class FileAnnotationSource extends S.Class<FileAnnotationSource>(\"FileAnnotationSource\")({\n  /**\n   * Type discriminator that is always `file`.\n   */\n  \"type\": FileAnnotationSourceType.pipe(S.propertySignature, S.withConstructorDefault(() => \"file\" as const)),\n  /**\n   * Filename referenced by the annotation.\n   */\n  \"filename\": S.String\n}) {}\n\n/**\n * Annotation that references an uploaded file.\n */\nexport class FileAnnotation extends S.Class<FileAnnotation>(\"FileAnnotation\")({\n  /**\n   * Type discriminator that is always `file` for this annotation.\n   */\n  \"type\": FileAnnotationType.pipe(S.propertySignature, S.withConstructorDefault(() => \"file\" as const)),\n  /**\n   * File attachment referenced by the annotation.\n   */\n  \"source\": FileAnnotationSource\n}) {}\n\n/**\n * Type discriminator that is always `url` for this annotation.\n */\nexport class UrlAnnotationType extends S.Literal(\"url\") {}\n\n/**\n * Type discriminator that is always `url`.\n */\nexport class UrlAnnotationSourceType extends S.Literal(\"url\") {}\n\n/**\n * URL backing an annotation entry.\n */\nexport class UrlAnnotationSource extends S.Class<UrlAnnotationSource>(\"UrlAnnotationSource\")({\n  /**\n   * Type discriminator that is always `url`.\n   */\n  \"type\": UrlAnnotationSourceType.pipe(S.propertySignature, S.withConstructorDefault(() => \"url\" as const)),\n  /**\n   * URL referenced by the annotation.\n   */\n  \"url\": S.String\n}) {}\n\n/**\n * Annotation that references a URL.\n */\nexport class UrlAnnotation extends S.Class<UrlAnnotation>(\"UrlAnnotation\")({\n  /**\n   * Type discriminator that is always `url` for this annotation.\n   */\n  \"type\": UrlAnnotationType.pipe(S.propertySignature, S.withConstructorDefault(() => \"url\" as const)),\n  /**\n   * URL referenced by the annotation.\n   */\n  \"source\": UrlAnnotationSource\n}) {}\n\n/**\n * Assistant response text accompanied by optional annotations.\n */\nexport class ResponseOutputText extends S.Class<ResponseOutputText>(\"ResponseOutputText\")({\n  /**\n   * Type discriminator that is always `output_text`.\n   */\n  \"type\": ResponseOutputTextType.pipe(S.propertySignature, S.withConstructorDefault(() => \"output_text\" as const)),\n  /**\n   * Assistant generated text.\n   */\n  \"text\": S.String,\n  /**\n   * Ordered list of annotations attached to the response text.\n   */\n  \"annotations\": S.Array(S.Union(FileAnnotation, UrlAnnotation))\n}) {}\n\n/**\n * Assistant-authored message within a thread.\n */\nexport class AssistantMessageItem extends S.Class<AssistantMessageItem>(\"AssistantMessageItem\")({\n  /**\n   * Identifier of the thread item.\n   */\n  \"id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.thread_item`.\n   */\n  \"object\": AssistantMessageItemObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"chatkit.thread_item\" as const)\n  ),\n  /**\n   * Unix timestamp (in seconds) for when the item was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Identifier of the parent thread.\n   */\n  \"thread_id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.assistant_message`.\n   */\n  \"type\": AssistantMessageItemType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"chatkit.assistant_message\" as const)\n  ),\n  /**\n   * Ordered assistant response segments.\n   */\n  \"content\": S.Array(ResponseOutputText)\n}) {}\n\n/**\n * Type discriminator that is always `chatkit.thread_item`.\n */\nexport class WidgetMessageItemObject extends S.Literal(\"chatkit.thread_item\") {}\n\n/**\n * Type discriminator that is always `chatkit.widget`.\n */\nexport class WidgetMessageItemType extends S.Literal(\"chatkit.widget\") {}\n\n/**\n * Thread item that renders a widget payload.\n */\nexport class WidgetMessageItem extends S.Class<WidgetMessageItem>(\"WidgetMessageItem\")({\n  /**\n   * Identifier of the thread item.\n   */\n  \"id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.thread_item`.\n   */\n  \"object\": WidgetMessageItemObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"chatkit.thread_item\" as const)\n  ),\n  /**\n   * Unix timestamp (in seconds) for when the item was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Identifier of the parent thread.\n   */\n  \"thread_id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.widget`.\n   */\n  \"type\": WidgetMessageItemType.pipe(S.propertySignature, S.withConstructorDefault(() => \"chatkit.widget\" as const)),\n  /**\n   * Serialized widget payload rendered in the UI.\n   */\n  \"widget\": S.String\n}) {}\n\n/**\n * Type discriminator that is always `chatkit.thread_item`.\n */\nexport class ClientToolCallItemObject extends S.Literal(\"chatkit.thread_item\") {}\n\n/**\n * Type discriminator that is always `chatkit.client_tool_call`.\n */\nexport class ClientToolCallItemType extends S.Literal(\"chatkit.client_tool_call\") {}\n\nexport class ClientToolCallStatus extends S.Literal(\"in_progress\", \"completed\") {}\n\n/**\n * Record of a client side tool invocation initiated by the assistant.\n */\nexport class ClientToolCallItem extends S.Class<ClientToolCallItem>(\"ClientToolCallItem\")({\n  /**\n   * Identifier of the thread item.\n   */\n  \"id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.thread_item`.\n   */\n  \"object\": ClientToolCallItemObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"chatkit.thread_item\" as const)\n  ),\n  /**\n   * Unix timestamp (in seconds) for when the item was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Identifier of the parent thread.\n   */\n  \"thread_id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.client_tool_call`.\n   */\n  \"type\": ClientToolCallItemType.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"chatkit.client_tool_call\" as const)\n  ),\n  /**\n   * Execution status for the tool call.\n   */\n  \"status\": ClientToolCallStatus,\n  /**\n   * Identifier for the client tool call.\n   */\n  \"call_id\": S.String,\n  /**\n   * Tool name that was invoked.\n   */\n  \"name\": S.String,\n  /**\n   * JSON-encoded arguments that were sent to the tool.\n   */\n  \"arguments\": S.String,\n  \"output\": S.NullOr(S.String)\n}) {}\n\n/**\n * Type discriminator that is always `chatkit.thread_item`.\n */\nexport class TaskItemObject extends S.Literal(\"chatkit.thread_item\") {}\n\n/**\n * Type discriminator that is always `chatkit.task`.\n */\nexport class TaskItemType extends S.Literal(\"chatkit.task\") {}\n\nexport class TaskType extends S.Literal(\"custom\", \"thought\") {}\n\n/**\n * Task emitted by the workflow to show progress and status updates.\n */\nexport class TaskItem extends S.Class<TaskItem>(\"TaskItem\")({\n  /**\n   * Identifier of the thread item.\n   */\n  \"id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.thread_item`.\n   */\n  \"object\": TaskItemObject.pipe(S.propertySignature, S.withConstructorDefault(() => \"chatkit.thread_item\" as const)),\n  /**\n   * Unix timestamp (in seconds) for when the item was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Identifier of the parent thread.\n   */\n  \"thread_id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.task`.\n   */\n  \"type\": TaskItemType.pipe(S.propertySignature, S.withConstructorDefault(() => \"chatkit.task\" as const)),\n  /**\n   * Subtype for the task.\n   */\n  \"task_type\": TaskType,\n  \"heading\": S.NullOr(S.String),\n  \"summary\": S.NullOr(S.String)\n}) {}\n\n/**\n * Type discriminator that is always `chatkit.thread_item`.\n */\nexport class TaskGroupItemObject extends S.Literal(\"chatkit.thread_item\") {}\n\n/**\n * Type discriminator that is always `chatkit.task_group`.\n */\nexport class TaskGroupItemType extends S.Literal(\"chatkit.task_group\") {}\n\n/**\n * Task entry that appears within a TaskGroup.\n */\nexport class TaskGroupTask extends S.Class<TaskGroupTask>(\"TaskGroupTask\")({\n  /**\n   * Subtype for the grouped task.\n   */\n  \"type\": TaskType,\n  \"heading\": S.NullOr(S.String),\n  \"summary\": S.NullOr(S.String)\n}) {}\n\n/**\n * Collection of workflow tasks grouped together in the thread.\n */\nexport class TaskGroupItem extends S.Class<TaskGroupItem>(\"TaskGroupItem\")({\n  /**\n   * Identifier of the thread item.\n   */\n  \"id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.thread_item`.\n   */\n  \"object\": TaskGroupItemObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"chatkit.thread_item\" as const)\n  ),\n  /**\n   * Unix timestamp (in seconds) for when the item was created.\n   */\n  \"created_at\": S.Int,\n  /**\n   * Identifier of the parent thread.\n   */\n  \"thread_id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.task_group`.\n   */\n  \"type\": TaskGroupItemType.pipe(S.propertySignature, S.withConstructorDefault(() => \"chatkit.task_group\" as const)),\n  /**\n   * Tasks included in the group.\n   */\n  \"tasks\": S.Array(TaskGroupTask)\n}) {}\n\nexport class ThreadItem\n  extends S.Union(UserMessageItem, AssistantMessageItem, WidgetMessageItem, ClientToolCallItem, TaskItem, TaskGroupItem)\n{}\n\n/**\n * A paginated list of thread items rendered for the ChatKit API.\n */\nexport class ThreadItemListResource extends S.Class<ThreadItemListResource>(\"ThreadItemListResource\")({\n  /**\n   * The type of object returned, must be `list`.\n   */\n  \"object\": S.Literal(\"list\").pipe(S.propertySignature, S.withConstructorDefault(() => \"list\" as const)),\n  /**\n   * A list of items\n   */\n  \"data\": S.Array(ThreadItem),\n  \"first_id\": S.NullOr(S.String),\n  \"last_id\": S.NullOr(S.String),\n  /**\n   * Whether there are more items available.\n   */\n  \"has_more\": S.Boolean\n}) {}\n\n/**\n * Type discriminator that is always `chatkit.thread`.\n */\nexport class ThreadResourceObject extends S.Literal(\"chatkit.thread\") {}\n\n/**\n * Status discriminator that is always `active`.\n */\nexport class ActiveStatusType extends S.Literal(\"active\") {}\n\n/**\n * Indicates that a thread is active.\n */\nexport class ActiveStatus extends S.Class<ActiveStatus>(\"ActiveStatus\")({\n  /**\n   * Status discriminator that is always `active`.\n   */\n  \"type\": ActiveStatusType.pipe(S.propertySignature, S.withConstructorDefault(() => \"active\" as const))\n}) {}\n\n/**\n * Status discriminator that is always `locked`.\n */\nexport class LockedStatusType extends S.Literal(\"locked\") {}\n\n/**\n * Indicates that a thread is locked and cannot accept new input.\n */\nexport class LockedStatus extends S.Class<LockedStatus>(\"LockedStatus\")({\n  /**\n   * Status discriminator that is always `locked`.\n   */\n  \"type\": LockedStatusType.pipe(S.propertySignature, S.withConstructorDefault(() => \"locked\" as const)),\n  \"reason\": S.NullOr(S.String)\n}) {}\n\n/**\n * Status discriminator that is always `closed`.\n */\nexport class ClosedStatusType extends S.Literal(\"closed\") {}\n\n/**\n * Indicates that a thread has been closed.\n */\nexport class ClosedStatus extends S.Class<ClosedStatus>(\"ClosedStatus\")({\n  /**\n   * Status discriminator that is always `closed`.\n   */\n  \"type\": ClosedStatusType.pipe(S.propertySignature, S.withConstructorDefault(() => \"closed\" as const)),\n  \"reason\": S.NullOr(S.String)\n}) {}\n\n/**\n * Represents a ChatKit thread and its current status.\n */\nexport class ThreadResource extends S.Class<ThreadResource>(\"ThreadResource\")({\n  /**\n   * Identifier of the thread.\n   */\n  \"id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.thread`.\n   */\n  \"object\": ThreadResourceObject.pipe(S.propertySignature, S.withConstructorDefault(() => \"chatkit.thread\" as const)),\n  /**\n   * Unix timestamp (in seconds) for when the thread was created.\n   */\n  \"created_at\": S.Int,\n  \"title\": S.NullOr(S.String),\n  /**\n   * Current status for the thread. Defaults to `active` for newly created threads.\n   */\n  \"status\": S.Union(ActiveStatus, LockedStatus, ClosedStatus),\n  /**\n   * Free-form string that identifies your end user who owns the thread.\n   */\n  \"user\": S.String\n}) {}\n\n/**\n * Type discriminator that is always `chatkit.thread.deleted`.\n */\nexport class DeletedThreadResourceObject extends S.Literal(\"chatkit.thread.deleted\") {}\n\n/**\n * Confirmation payload returned after deleting a thread.\n */\nexport class DeletedThreadResource extends S.Class<DeletedThreadResource>(\"DeletedThreadResource\")({\n  /**\n   * Identifier of the deleted thread.\n   */\n  \"id\": S.String,\n  /**\n   * Type discriminator that is always `chatkit.thread.deleted`.\n   */\n  \"object\": DeletedThreadResourceObject.pipe(\n    S.propertySignature,\n    S.withConstructorDefault(() => \"chatkit.thread.deleted\" as const)\n  ),\n  /**\n   * Indicates that the thread has been deleted.\n   */\n  \"deleted\": S.Boolean\n}) {}\n\nexport class ListThreadsMethodParams extends S.Struct({\n  \"limit\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(100)), { nullable: true }),\n  \"order\": S.optionalWith(OrderEnum, { nullable: true }),\n  /**\n   * List items created after this thread item ID. Defaults to null for the first page.\n   */\n  \"after\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * List items created before this thread item ID. Defaults to null for the newest results.\n   */\n  \"before\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Filter threads that belong to this user identifier. Defaults to null to return all users.\n   */\n  \"user\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(512)), { nullable: true })\n}) {}\n\n/**\n * A paginated list of ChatKit threads.\n */\nexport class ThreadListResource extends S.Class<ThreadListResource>(\"ThreadListResource\")({\n  /**\n   * The type of object returned, must be `list`.\n   */\n  \"object\": S.Literal(\"list\").pipe(S.propertySignature, S.withConstructorDefault(() => \"list\" as const)),\n  /**\n   * A list of items\n   */\n  \"data\": S.Array(ThreadResource),\n  \"first_id\": S.NullOr(S.String),\n  \"last_id\": S.NullOr(S.String),\n  /**\n   * Whether there are more items available.\n   */\n  \"has_more\": S.Boolean\n}) {}\n\nexport const make = (\n  httpClient: HttpClient.HttpClient,\n  options: {\n    readonly transformClient?: ((client: HttpClient.HttpClient) => Effect.Effect<HttpClient.HttpClient>) | undefined\n  } = {}\n): Client => {\n  const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) =>\n    Effect.flatMap(\n      Effect.orElseSucceed(response.json, () => \"Unexpected status code\"),\n      (description) =>\n        Effect.fail(\n          new HttpClientError.ResponseError({\n            request: response.request,\n            response,\n            reason: \"StatusCode\",\n            description: typeof description === \"string\" ? description : JSON.stringify(description)\n          })\n        )\n    )\n  const withResponse: <A, E>(\n    f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E>\n  ) => (\n    request: HttpClientRequest.HttpClientRequest\n  ) => Effect.Effect<any, any> = options.transformClient\n    ? (f) => (request) =>\n      Effect.flatMap(\n        Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)),\n        f\n      )\n    : (f) => (request) => Effect.flatMap(httpClient.execute(request), f)\n  const decodeSuccess = <A, I, R>(schema: S.Schema<A, I, R>) => (response: HttpClientResponse.HttpClientResponse) =>\n    HttpClientResponse.schemaBodyJson(schema)(response)\n  const decodeError =\n    <const Tag extends string, A, I, R>(tag: Tag, schema: S.Schema<A, I, R>) =>\n    (response: HttpClientResponse.HttpClientResponse) =>\n      Effect.flatMap(\n        HttpClientResponse.schemaBodyJson(schema)(response),\n        (cause) => Effect.fail(ClientError(tag, cause, response))\n      )\n  return {\n    httpClient,\n    \"listAssistants\": (options) =>\n      HttpClientRequest.get(`/assistants`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListAssistantsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createAssistant\": (options) =>\n      HttpClientRequest.post(`/assistants`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(AssistantObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getAssistant\": (assistantId) =>\n      HttpClientRequest.get(`/assistants/${assistantId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(AssistantObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modifyAssistant\": (assistantId, options) =>\n      HttpClientRequest.post(`/assistants/${assistantId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(AssistantObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteAssistant\": (assistantId) =>\n      HttpClientRequest.del(`/assistants/${assistantId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteAssistantResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createSpeech\": (options) =>\n      HttpClientRequest.post(`/audio/speech`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createTranscription\": (options) =>\n      HttpClientRequest.post(`/audio/transcriptions`).pipe(\n        HttpClientRequest.bodyFormDataRecord(options as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateTranscription200),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createTranslation\": (options) =>\n      HttpClientRequest.post(`/audio/translations`).pipe(\n        HttpClientRequest.bodyFormDataRecord(options as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateTranslation200),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listBatches\": (options) =>\n      HttpClientRequest.get(`/batches`).pipe(\n        HttpClientRequest.setUrlParams({ \"after\": options?.[\"after\"] as any, \"limit\": options?.[\"limit\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListBatchesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createBatch\": (options) =>\n      HttpClientRequest.post(`/batches`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Batch),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveBatch\": (batchId) =>\n      HttpClientRequest.get(`/batches/${batchId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Batch),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"cancelBatch\": (batchId) =>\n      HttpClientRequest.post(`/batches/${batchId}/cancel`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Batch),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listChatCompletions\": (options) =>\n      HttpClientRequest.get(`/chat/completions`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"model\": options?.[\"model\"] as any,\n          \"metadata\": options?.[\"metadata\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ChatCompletionList),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createChatCompletion\": (options) =>\n      HttpClientRequest.post(`/chat/completions`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateChatCompletionResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getChatCompletion\": (completionId) =>\n      HttpClientRequest.get(`/chat/completions/${completionId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateChatCompletionResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"updateChatCompletion\": (completionId, options) =>\n      HttpClientRequest.post(`/chat/completions/${completionId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateChatCompletionResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteChatCompletion\": (completionId) =>\n      HttpClientRequest.del(`/chat/completions/${completionId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ChatCompletionDeleted),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getChatCompletionMessages\": (completionId, options) =>\n      HttpClientRequest.get(`/chat/completions/${completionId}/messages`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"after\": options?.[\"after\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ChatCompletionMessageList),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createCompletion\": (options) =>\n      HttpClientRequest.post(`/completions`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateCompletionResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListContainers\": (options) =>\n      HttpClientRequest.get(`/containers`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ContainerListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreateContainer\": (options) =>\n      HttpClientRequest.post(`/containers`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ContainerResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"RetrieveContainer\": (containerId) =>\n      HttpClientRequest.get(`/containers/${containerId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ContainerResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteContainer\": (containerId) =>\n      HttpClientRequest.del(`/containers/${containerId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"200\": () => Effect.void,\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListContainerFiles\": (containerId, options) =>\n      HttpClientRequest.get(`/containers/${containerId}/files`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ContainerFileListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreateContainerFile\": (containerId, options) =>\n      HttpClientRequest.post(`/containers/${containerId}/files`).pipe(\n        HttpClientRequest.bodyFormDataRecord(options as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ContainerFileResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"RetrieveContainerFile\": (containerId, fileId) =>\n      HttpClientRequest.get(`/containers/${containerId}/files/${fileId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ContainerFileResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteContainerFile\": (containerId, fileId) =>\n      HttpClientRequest.del(`/containers/${containerId}/files/${fileId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"200\": () => Effect.void,\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"RetrieveContainerFileContent\": (containerId, fileId) =>\n      HttpClientRequest.get(`/containers/${containerId}/files/${fileId}/content`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"200\": () => Effect.void,\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listConversationItems\": (conversationId, options) =>\n      HttpClientRequest.get(`/conversations/${conversationId}/items`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"include\": options?.[\"include\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ConversationItemList),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createConversationItems\": (conversationId, options) =>\n      HttpClientRequest.post(`/conversations/${conversationId}/items`).pipe(\n        HttpClientRequest.setUrlParams({ \"include\": options.params?.[\"include\"] as any }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ConversationItemList),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getConversationItem\": (conversationId, itemId, options) =>\n      HttpClientRequest.get(`/conversations/${conversationId}/items/${itemId}`).pipe(\n        HttpClientRequest.setUrlParams({ \"include\": options?.[\"include\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ConversationItem),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteConversationItem\": (conversationId, itemId) =>\n      HttpClientRequest.del(`/conversations/${conversationId}/items/${itemId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ConversationResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createEmbedding\": (options) =>\n      HttpClientRequest.post(`/embeddings`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateEmbeddingResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listEvals\": (options) =>\n      HttpClientRequest.get(`/evals`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"after\": options?.[\"after\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"order_by\": options?.[\"order_by\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(EvalList),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createEval\": (options) =>\n      HttpClientRequest.post(`/evals`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Eval),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getEval\": (evalId) =>\n      HttpClientRequest.get(`/evals/${evalId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Eval),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"updateEval\": (evalId, options) =>\n      HttpClientRequest.post(`/evals/${evalId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Eval),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteEval\": (evalId) =>\n      HttpClientRequest.del(`/evals/${evalId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteEval200),\n          \"404\": decodeError(\"Error\", Error),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getEvalRuns\": (evalId, options) =>\n      HttpClientRequest.get(`/evals/${evalId}/runs`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"after\": options?.[\"after\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"status\": options?.[\"status\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(EvalRunList),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createEvalRun\": (evalId, options) =>\n      HttpClientRequest.post(`/evals/${evalId}/runs`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(EvalRun),\n          \"400\": decodeError(\"Error\", Error),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getEvalRun\": (evalId, runId) =>\n      HttpClientRequest.get(`/evals/${evalId}/runs/${runId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(EvalRun),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"cancelEvalRun\": (evalId, runId) =>\n      HttpClientRequest.post(`/evals/${evalId}/runs/${runId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(EvalRun),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteEvalRun\": (evalId, runId) =>\n      HttpClientRequest.del(`/evals/${evalId}/runs/${runId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteEvalRun200),\n          \"404\": decodeError(\"Error\", Error),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getEvalRunOutputItems\": (evalId, runId, options) =>\n      HttpClientRequest.get(`/evals/${evalId}/runs/${runId}/output_items`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"after\": options?.[\"after\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"status\": options?.[\"status\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(EvalRunOutputItemList),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getEvalRunOutputItem\": (evalId, runId, outputItemId) =>\n      HttpClientRequest.get(`/evals/${evalId}/runs/${runId}/output_items/${outputItemId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(EvalRunOutputItem),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listFiles\": (options) =>\n      HttpClientRequest.get(`/files`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"purpose\": options?.[\"purpose\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListFilesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createFile\": (options) =>\n      HttpClientRequest.post(`/files`).pipe(\n        HttpClientRequest.bodyFormDataRecord(options as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(OpenAIFile),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveFile\": (fileId) =>\n      HttpClientRequest.get(`/files/${fileId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(OpenAIFile),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteFile\": (fileId) =>\n      HttpClientRequest.del(`/files/${fileId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteFileResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"downloadFile\": (fileId) =>\n      HttpClientRequest.get(`/files/${fileId}/content`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DownloadFile200),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"runGrader\": (options) =>\n      HttpClientRequest.post(`/fine_tuning/alpha/graders/run`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RunGraderResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"validateGrader\": (options) =>\n      HttpClientRequest.post(`/fine_tuning/alpha/graders/validate`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ValidateGraderResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listFineTuningCheckpointPermissions\": (fineTunedModelCheckpoint, options) =>\n      HttpClientRequest.get(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"project_id\": options?.[\"project_id\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListFineTuningCheckpointPermissionResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createFineTuningCheckpointPermission\": (fineTunedModelCheckpoint, options) =>\n      HttpClientRequest.post(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListFineTuningCheckpointPermissionResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteFineTuningCheckpointPermission\": (fineTunedModelCheckpoint, permissionId) =>\n      HttpClientRequest.del(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions/${permissionId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteFineTuningCheckpointPermissionResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listPaginatedFineTuningJobs\": (options) =>\n      HttpClientRequest.get(`/fine_tuning/jobs`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"after\": options?.[\"after\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"metadata\": options?.[\"metadata\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListPaginatedFineTuningJobsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createFineTuningJob\": (options) =>\n      HttpClientRequest.post(`/fine_tuning/jobs`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FineTuningJob),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveFineTuningJob\": (fineTuningJobId) =>\n      HttpClientRequest.get(`/fine_tuning/jobs/${fineTuningJobId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FineTuningJob),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"cancelFineTuningJob\": (fineTuningJobId) =>\n      HttpClientRequest.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FineTuningJob),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listFineTuningJobCheckpoints\": (fineTuningJobId, options) =>\n      HttpClientRequest.get(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`).pipe(\n        HttpClientRequest.setUrlParams({ \"after\": options?.[\"after\"] as any, \"limit\": options?.[\"limit\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListFineTuningJobCheckpointsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listFineTuningEvents\": (fineTuningJobId, options) =>\n      HttpClientRequest.get(`/fine_tuning/jobs/${fineTuningJobId}/events`).pipe(\n        HttpClientRequest.setUrlParams({ \"after\": options?.[\"after\"] as any, \"limit\": options?.[\"limit\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListFineTuningJobEventsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"pauseFineTuningJob\": (fineTuningJobId) =>\n      HttpClientRequest.post(`/fine_tuning/jobs/${fineTuningJobId}/pause`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FineTuningJob),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"resumeFineTuningJob\": (fineTuningJobId) =>\n      HttpClientRequest.post(`/fine_tuning/jobs/${fineTuningJobId}/resume`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(FineTuningJob),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createImageEdit\": (options) =>\n      HttpClientRequest.post(`/images/edits`).pipe(\n        HttpClientRequest.bodyFormDataRecord(options as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ImagesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createImage\": (options) =>\n      HttpClientRequest.post(`/images/generations`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ImagesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createImageVariation\": (options) =>\n      HttpClientRequest.post(`/images/variations`).pipe(\n        HttpClientRequest.bodyFormDataRecord(options as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ImagesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listModels\": () =>\n      HttpClientRequest.get(`/models`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListModelsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveModel\": (model) =>\n      HttpClientRequest.get(`/models/${model}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Model),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteModel\": (model) =>\n      HttpClientRequest.del(`/models/${model}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteModelResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createModeration\": (options) =>\n      HttpClientRequest.post(`/moderations`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateModerationResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"adminApiKeysList\": (options) =>\n      HttpClientRequest.get(`/organization/admin_api_keys`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"limit\": options?.[\"limit\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ApiKeyList),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"adminApiKeysCreate\": (options) =>\n      HttpClientRequest.post(`/organization/admin_api_keys`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(AdminApiKey),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"adminApiKeysGet\": (keyId) =>\n      HttpClientRequest.get(`/organization/admin_api_keys/${keyId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(AdminApiKey),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"adminApiKeysDelete\": (keyId) =>\n      HttpClientRequest.del(`/organization/admin_api_keys/${keyId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(AdminApiKeysDelete200),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listAuditLogs\": (options) =>\n      HttpClientRequest.get(`/organization/audit_logs`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"effective_at[gt]\": options?.[\"effective_at[gt]\"] as any,\n          \"effective_at[gte]\": options?.[\"effective_at[gte]\"] as any,\n          \"effective_at[lt]\": options?.[\"effective_at[lt]\"] as any,\n          \"effective_at[lte]\": options?.[\"effective_at[lte]\"] as any,\n          \"project_ids[]\": options?.[\"project_ids[]\"] as any,\n          \"event_types[]\": options?.[\"event_types[]\"] as any,\n          \"actor_ids[]\": options?.[\"actor_ids[]\"] as any,\n          \"actor_emails[]\": options?.[\"actor_emails[]\"] as any,\n          \"resource_ids[]\": options?.[\"resource_ids[]\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListAuditLogsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listOrganizationCertificates\": (options) =>\n      HttpClientRequest.get(`/organization/certificates`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListCertificatesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"uploadCertificate\": (options) =>\n      HttpClientRequest.post(`/organization/certificates`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Certificate),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"activateOrganizationCertificates\": (options) =>\n      HttpClientRequest.post(`/organization/certificates/activate`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListCertificatesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deactivateOrganizationCertificates\": (options) =>\n      HttpClientRequest.post(`/organization/certificates/deactivate`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListCertificatesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getCertificate\": (certificateId, options) =>\n      HttpClientRequest.get(`/organization/certificates/${certificateId}`).pipe(\n        HttpClientRequest.setUrlParams({ \"include\": options?.[\"include\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Certificate),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modifyCertificate\": (certificateId, options) =>\n      HttpClientRequest.post(`/organization/certificates/${certificateId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Certificate),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteCertificate\": (certificateId) =>\n      HttpClientRequest.del(`/organization/certificates/${certificateId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteCertificateResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"usageCosts\": (options) =>\n      HttpClientRequest.get(`/organization/costs`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"start_time\": options?.[\"start_time\"] as any,\n          \"end_time\": options?.[\"end_time\"] as any,\n          \"bucket_width\": options?.[\"bucket_width\"] as any,\n          \"project_ids\": options?.[\"project_ids\"] as any,\n          \"group_by\": options?.[\"group_by\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"page\": options?.[\"page\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UsageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listGroups\": (options) =>\n      HttpClientRequest.get(`/organization/groups`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GroupListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createGroup\": (options) =>\n      HttpClientRequest.post(`/organization/groups`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GroupResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"updateGroup\": (groupId, options) =>\n      HttpClientRequest.post(`/organization/groups/${groupId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GroupResourceWithSuccess),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteGroup\": (groupId) =>\n      HttpClientRequest.del(`/organization/groups/${groupId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GroupDeletedResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listGroupRoleAssignments\": (groupId, options) =>\n      HttpClientRequest.get(`/organization/groups/${groupId}/roles`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RoleListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"assignGroupRole\": (groupId, options) =>\n      HttpClientRequest.post(`/organization/groups/${groupId}/roles`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GroupRoleAssignment),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"unassignGroupRole\": (groupId, roleId) =>\n      HttpClientRequest.del(`/organization/groups/${groupId}/roles/${roleId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeletedRoleAssignmentResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listGroupUsers\": (groupId, options) =>\n      HttpClientRequest.get(`/organization/groups/${groupId}/users`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UserListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"addGroupUser\": (groupId, options) =>\n      HttpClientRequest.post(`/organization/groups/${groupId}/users`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GroupUserAssignment),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"removeGroupUser\": (groupId, userId) =>\n      HttpClientRequest.del(`/organization/groups/${groupId}/users/${userId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GroupUserDeletedResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listInvites\": (options) =>\n      HttpClientRequest.get(`/organization/invites`).pipe(\n        HttpClientRequest.setUrlParams({ \"limit\": options?.[\"limit\"] as any, \"after\": options?.[\"after\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(InviteListResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"inviteUser\": (options) =>\n      HttpClientRequest.post(`/organization/invites`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Invite),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveInvite\": (inviteId) =>\n      HttpClientRequest.get(`/organization/invites/${inviteId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Invite),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteInvite\": (inviteId) =>\n      HttpClientRequest.del(`/organization/invites/${inviteId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(InviteDeleteResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProjects\": (options) =>\n      HttpClientRequest.get(`/organization/projects`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"include_archived\": options?.[\"include_archived\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectListResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createProject\": (options) =>\n      HttpClientRequest.post(`/organization/projects`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Project),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveProject\": (projectId) =>\n      HttpClientRequest.get(`/organization/projects/${projectId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Project),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modifyProject\": (projectId, options) =>\n      HttpClientRequest.post(`/organization/projects/${projectId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Project),\n          \"400\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProjectApiKeys\": (projectId, options) =>\n      HttpClientRequest.get(`/organization/projects/${projectId}/api_keys`).pipe(\n        HttpClientRequest.setUrlParams({ \"limit\": options?.[\"limit\"] as any, \"after\": options?.[\"after\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectApiKeyListResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveProjectApiKey\": (projectId, keyId) =>\n      HttpClientRequest.get(`/organization/projects/${projectId}/api_keys/${keyId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectApiKey),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteProjectApiKey\": (projectId, keyId) =>\n      HttpClientRequest.del(`/organization/projects/${projectId}/api_keys/${keyId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectApiKeyDeleteResponse),\n          \"400\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"archiveProject\": (projectId) =>\n      HttpClientRequest.post(`/organization/projects/${projectId}/archive`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Project),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProjectCertificates\": (projectId, options) =>\n      HttpClientRequest.get(`/organization/projects/${projectId}/certificates`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListCertificatesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"activateProjectCertificates\": (projectId, options) =>\n      HttpClientRequest.post(`/organization/projects/${projectId}/certificates/activate`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListCertificatesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deactivateProjectCertificates\": (projectId, options) =>\n      HttpClientRequest.post(`/organization/projects/${projectId}/certificates/deactivate`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListCertificatesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProjectGroups\": (projectId, options) =>\n      HttpClientRequest.get(`/organization/projects/${projectId}/groups`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectGroupListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"addProjectGroup\": (projectId, options) =>\n      HttpClientRequest.post(`/organization/projects/${projectId}/groups`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectGroup),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"removeProjectGroup\": (projectId, groupId) =>\n      HttpClientRequest.del(`/organization/projects/${projectId}/groups/${groupId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectGroupDeletedResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProjectRateLimits\": (projectId, options) =>\n      HttpClientRequest.get(`/organization/projects/${projectId}/rate_limits`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectRateLimitListResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"updateProjectRateLimits\": (projectId, rateLimitId, options) =>\n      HttpClientRequest.post(`/organization/projects/${projectId}/rate_limits/${rateLimitId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectRateLimit),\n          \"400\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProjectServiceAccounts\": (projectId, options) =>\n      HttpClientRequest.get(`/organization/projects/${projectId}/service_accounts`).pipe(\n        HttpClientRequest.setUrlParams({ \"limit\": options?.[\"limit\"] as any, \"after\": options?.[\"after\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectServiceAccountListResponse),\n          \"400\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createProjectServiceAccount\": (projectId, options) =>\n      HttpClientRequest.post(`/organization/projects/${projectId}/service_accounts`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectServiceAccountCreateResponse),\n          \"400\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveProjectServiceAccount\": (projectId, serviceAccountId) =>\n      HttpClientRequest.get(`/organization/projects/${projectId}/service_accounts/${serviceAccountId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectServiceAccount),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteProjectServiceAccount\": (projectId, serviceAccountId) =>\n      HttpClientRequest.del(`/organization/projects/${projectId}/service_accounts/${serviceAccountId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectServiceAccountDeleteResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProjectUsers\": (projectId, options) =>\n      HttpClientRequest.get(`/organization/projects/${projectId}/users`).pipe(\n        HttpClientRequest.setUrlParams({ \"limit\": options?.[\"limit\"] as any, \"after\": options?.[\"after\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectUserListResponse),\n          \"400\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createProjectUser\": (projectId, options) =>\n      HttpClientRequest.post(`/organization/projects/${projectId}/users`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectUser),\n          \"400\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveProjectUser\": (projectId, userId) =>\n      HttpClientRequest.get(`/organization/projects/${projectId}/users/${userId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectUser),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modifyProjectUser\": (projectId, userId, options) =>\n      HttpClientRequest.post(`/organization/projects/${projectId}/users/${userId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectUser),\n          \"400\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteProjectUser\": (projectId, userId) =>\n      HttpClientRequest.del(`/organization/projects/${projectId}/users/${userId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ProjectUserDeleteResponse),\n          \"400\": decodeError(\"ErrorResponse\", ErrorResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listRoles\": (options) =>\n      HttpClientRequest.get(`/organization/roles`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(PublicRoleListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createRole\": (options) =>\n      HttpClientRequest.post(`/organization/roles`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Role),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"updateRole\": (roleId, options) =>\n      HttpClientRequest.post(`/organization/roles/${roleId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Role),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteRole\": (roleId) =>\n      HttpClientRequest.del(`/organization/roles/${roleId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RoleDeletedResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"usageAudioSpeeches\": (options) =>\n      HttpClientRequest.get(`/organization/usage/audio_speeches`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"start_time\": options?.[\"start_time\"] as any,\n          \"end_time\": options?.[\"end_time\"] as any,\n          \"bucket_width\": options?.[\"bucket_width\"] as any,\n          \"project_ids\": options?.[\"project_ids\"] as any,\n          \"user_ids\": options?.[\"user_ids\"] as any,\n          \"api_key_ids\": options?.[\"api_key_ids\"] as any,\n          \"models\": options?.[\"models\"] as any,\n          \"group_by\": options?.[\"group_by\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"page\": options?.[\"page\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UsageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"usageAudioTranscriptions\": (options) =>\n      HttpClientRequest.get(`/organization/usage/audio_transcriptions`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"start_time\": options?.[\"start_time\"] as any,\n          \"end_time\": options?.[\"end_time\"] as any,\n          \"bucket_width\": options?.[\"bucket_width\"] as any,\n          \"project_ids\": options?.[\"project_ids\"] as any,\n          \"user_ids\": options?.[\"user_ids\"] as any,\n          \"api_key_ids\": options?.[\"api_key_ids\"] as any,\n          \"models\": options?.[\"models\"] as any,\n          \"group_by\": options?.[\"group_by\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"page\": options?.[\"page\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UsageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"usageCodeInterpreterSessions\": (options) =>\n      HttpClientRequest.get(`/organization/usage/code_interpreter_sessions`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"start_time\": options?.[\"start_time\"] as any,\n          \"end_time\": options?.[\"end_time\"] as any,\n          \"bucket_width\": options?.[\"bucket_width\"] as any,\n          \"project_ids\": options?.[\"project_ids\"] as any,\n          \"group_by\": options?.[\"group_by\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"page\": options?.[\"page\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UsageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"usageCompletions\": (options) =>\n      HttpClientRequest.get(`/organization/usage/completions`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"start_time\": options?.[\"start_time\"] as any,\n          \"end_time\": options?.[\"end_time\"] as any,\n          \"bucket_width\": options?.[\"bucket_width\"] as any,\n          \"project_ids\": options?.[\"project_ids\"] as any,\n          \"user_ids\": options?.[\"user_ids\"] as any,\n          \"api_key_ids\": options?.[\"api_key_ids\"] as any,\n          \"models\": options?.[\"models\"] as any,\n          \"batch\": options?.[\"batch\"] as any,\n          \"group_by\": options?.[\"group_by\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"page\": options?.[\"page\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UsageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"usageEmbeddings\": (options) =>\n      HttpClientRequest.get(`/organization/usage/embeddings`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"start_time\": options?.[\"start_time\"] as any,\n          \"end_time\": options?.[\"end_time\"] as any,\n          \"bucket_width\": options?.[\"bucket_width\"] as any,\n          \"project_ids\": options?.[\"project_ids\"] as any,\n          \"user_ids\": options?.[\"user_ids\"] as any,\n          \"api_key_ids\": options?.[\"api_key_ids\"] as any,\n          \"models\": options?.[\"models\"] as any,\n          \"group_by\": options?.[\"group_by\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"page\": options?.[\"page\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UsageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"usageImages\": (options) =>\n      HttpClientRequest.get(`/organization/usage/images`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"start_time\": options?.[\"start_time\"] as any,\n          \"end_time\": options?.[\"end_time\"] as any,\n          \"bucket_width\": options?.[\"bucket_width\"] as any,\n          \"sources\": options?.[\"sources\"] as any,\n          \"sizes\": options?.[\"sizes\"] as any,\n          \"project_ids\": options?.[\"project_ids\"] as any,\n          \"user_ids\": options?.[\"user_ids\"] as any,\n          \"api_key_ids\": options?.[\"api_key_ids\"] as any,\n          \"models\": options?.[\"models\"] as any,\n          \"group_by\": options?.[\"group_by\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"page\": options?.[\"page\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UsageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"usageModerations\": (options) =>\n      HttpClientRequest.get(`/organization/usage/moderations`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"start_time\": options?.[\"start_time\"] as any,\n          \"end_time\": options?.[\"end_time\"] as any,\n          \"bucket_width\": options?.[\"bucket_width\"] as any,\n          \"project_ids\": options?.[\"project_ids\"] as any,\n          \"user_ids\": options?.[\"user_ids\"] as any,\n          \"api_key_ids\": options?.[\"api_key_ids\"] as any,\n          \"models\": options?.[\"models\"] as any,\n          \"group_by\": options?.[\"group_by\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"page\": options?.[\"page\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UsageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"usageVectorStores\": (options) =>\n      HttpClientRequest.get(`/organization/usage/vector_stores`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"start_time\": options?.[\"start_time\"] as any,\n          \"end_time\": options?.[\"end_time\"] as any,\n          \"bucket_width\": options?.[\"bucket_width\"] as any,\n          \"project_ids\": options?.[\"project_ids\"] as any,\n          \"group_by\": options?.[\"group_by\"] as any,\n          \"limit\": options?.[\"limit\"] as any,\n          \"page\": options?.[\"page\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UsageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listUsers\": (options) =>\n      HttpClientRequest.get(`/organization/users`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"emails\": options?.[\"emails\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UserListResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveUser\": (userId) =>\n      HttpClientRequest.get(`/organization/users/${userId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(User),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modifyUser\": (userId, options) =>\n      HttpClientRequest.post(`/organization/users/${userId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(User),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteUser\": (userId) =>\n      HttpClientRequest.del(`/organization/users/${userId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UserDeleteResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listUserRoleAssignments\": (userId, options) =>\n      HttpClientRequest.get(`/organization/users/${userId}/roles`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RoleListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"assignUserRole\": (userId, options) =>\n      HttpClientRequest.post(`/organization/users/${userId}/roles`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UserRoleAssignment),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"unassignUserRole\": (userId, roleId) =>\n      HttpClientRequest.del(`/organization/users/${userId}/roles/${roleId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeletedRoleAssignmentResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProjectGroupRoleAssignments\": (projectId, groupId, options) =>\n      HttpClientRequest.get(`/projects/${projectId}/groups/${groupId}/roles`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RoleListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"assignProjectGroupRole\": (projectId, groupId, options) =>\n      HttpClientRequest.post(`/projects/${projectId}/groups/${groupId}/roles`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GroupRoleAssignment),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"unassignProjectGroupRole\": (projectId, groupId, roleId) =>\n      HttpClientRequest.del(`/projects/${projectId}/groups/${groupId}/roles/${roleId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeletedRoleAssignmentResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProjectRoles\": (projectId, options) =>\n      HttpClientRequest.get(`/projects/${projectId}/roles`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(PublicRoleListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createProjectRole\": (projectId, options) =>\n      HttpClientRequest.post(`/projects/${projectId}/roles`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Role),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"updateProjectRole\": (projectId, roleId, options) =>\n      HttpClientRequest.post(`/projects/${projectId}/roles/${roleId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Role),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteProjectRole\": (projectId, roleId) =>\n      HttpClientRequest.del(`/projects/${projectId}/roles/${roleId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RoleDeletedResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProjectUserRoleAssignments\": (projectId, userId, options) =>\n      HttpClientRequest.get(`/projects/${projectId}/users/${userId}/roles`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"order\": options?.[\"order\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RoleListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"assignProjectUserRole\": (projectId, userId, options) =>\n      HttpClientRequest.post(`/projects/${projectId}/users/${userId}/roles`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UserRoleAssignment),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"unassignProjectUserRole\": (projectId, userId, roleId) =>\n      HttpClientRequest.del(`/projects/${projectId}/users/${userId}/roles/${roleId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeletedRoleAssignmentResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createRealtimeCall\": (options) =>\n      HttpClientRequest.post(`/realtime/calls`).pipe(\n        HttpClientRequest.bodyFormDataRecord(options as any),\n        withResponse(HttpClientResponse.matchStatus({\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"acceptRealtimeCall\": (callId, options) =>\n      HttpClientRequest.post(`/realtime/calls/${callId}/accept`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"200\": () => Effect.void,\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"hangupRealtimeCall\": (callId) =>\n      HttpClientRequest.post(`/realtime/calls/${callId}/hangup`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"200\": () => Effect.void,\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"referRealtimeCall\": (callId, options) =>\n      HttpClientRequest.post(`/realtime/calls/${callId}/refer`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"200\": () => Effect.void,\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"rejectRealtimeCall\": (callId, options) =>\n      HttpClientRequest.post(`/realtime/calls/${callId}/reject`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"200\": () => Effect.void,\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createRealtimeClientSecret\": (options) =>\n      HttpClientRequest.post(`/realtime/client_secrets`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RealtimeCreateClientSecretResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createRealtimeSession\": (options) =>\n      HttpClientRequest.post(`/realtime/sessions`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RealtimeSessionCreateResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createRealtimeTranscriptionSession\": (options) =>\n      HttpClientRequest.post(`/realtime/transcription_sessions`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RealtimeTranscriptionSessionCreateResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createResponse\": (options) =>\n      HttpClientRequest.post(`/responses`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Response),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getResponse\": (responseId, options) =>\n      HttpClientRequest.get(`/responses/${responseId}`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"include\": options?.[\"include\"] as any,\n          \"stream\": options?.[\"stream\"] as any,\n          \"starting_after\": options?.[\"starting_after\"] as any,\n          \"include_obfuscation\": options?.[\"include_obfuscation\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Response),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteResponse\": (responseId) =>\n      HttpClientRequest.del(`/responses/${responseId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"404\": decodeError(\"Error\", Error),\n          \"200\": () => Effect.void,\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"cancelResponse\": (responseId) =>\n      HttpClientRequest.post(`/responses/${responseId}/cancel`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Response),\n          \"404\": decodeError(\"Error\", Error),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listInputItems\": (responseId, options) =>\n      HttpClientRequest.get(`/responses/${responseId}/input_items`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"include\": options?.[\"include\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ResponseItemList),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createThread\": (options) =>\n      HttpClientRequest.post(`/threads`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ThreadObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createThreadAndRun\": (options) =>\n      HttpClientRequest.post(`/threads/runs`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RunObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getThread\": (threadId) =>\n      HttpClientRequest.get(`/threads/${threadId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ThreadObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modifyThread\": (threadId, options) =>\n      HttpClientRequest.post(`/threads/${threadId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ThreadObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteThread\": (threadId) =>\n      HttpClientRequest.del(`/threads/${threadId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteThreadResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listMessages\": (threadId, options) =>\n      HttpClientRequest.get(`/threads/${threadId}/messages`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any,\n          \"run_id\": options?.[\"run_id\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListMessagesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createMessage\": (threadId, options) =>\n      HttpClientRequest.post(`/threads/${threadId}/messages`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(MessageObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getMessage\": (threadId, messageId) =>\n      HttpClientRequest.get(`/threads/${threadId}/messages/${messageId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(MessageObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modifyMessage\": (threadId, messageId, options) =>\n      HttpClientRequest.post(`/threads/${threadId}/messages/${messageId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(MessageObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteMessage\": (threadId, messageId) =>\n      HttpClientRequest.del(`/threads/${threadId}/messages/${messageId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteMessageResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listRuns\": (threadId, options) =>\n      HttpClientRequest.get(`/threads/${threadId}/runs`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListRunsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createRun\": (threadId, options) =>\n      HttpClientRequest.post(`/threads/${threadId}/runs`).pipe(\n        HttpClientRequest.setUrlParams({ \"include[]\": options.params?.[\"include[]\"] as any }),\n        HttpClientRequest.bodyUnsafeJson(options.payload),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RunObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getRun\": (threadId, runId) =>\n      HttpClientRequest.get(`/threads/${threadId}/runs/${runId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RunObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modifyRun\": (threadId, runId, options) =>\n      HttpClientRequest.post(`/threads/${threadId}/runs/${runId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RunObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"cancelRun\": (threadId, runId) =>\n      HttpClientRequest.post(`/threads/${threadId}/runs/${runId}/cancel`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RunObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listRunSteps\": (threadId, runId, options) =>\n      HttpClientRequest.get(`/threads/${threadId}/runs/${runId}/steps`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any,\n          \"include[]\": options?.[\"include[]\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListRunStepsResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getRunStep\": (threadId, runId, stepId, options) =>\n      HttpClientRequest.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`).pipe(\n        HttpClientRequest.setUrlParams({ \"include[]\": options?.[\"include[]\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RunStepObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"submitToolOuputsToRun\": (threadId, runId, options) =>\n      HttpClientRequest.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RunObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createUpload\": (options) =>\n      HttpClientRequest.post(`/uploads`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Upload),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"cancelUpload\": (uploadId) =>\n      HttpClientRequest.post(`/uploads/${uploadId}/cancel`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Upload),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"completeUpload\": (uploadId, options) =>\n      HttpClientRequest.post(`/uploads/${uploadId}/complete`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(Upload),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"addUploadPart\": (uploadId, options) =>\n      HttpClientRequest.post(`/uploads/${uploadId}/parts`).pipe(\n        HttpClientRequest.bodyFormDataRecord(options as any),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UploadPart),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listVectorStores\": (options) =>\n      HttpClientRequest.get(`/vector_stores`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListVectorStoresResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createVectorStore\": (options) =>\n      HttpClientRequest.post(`/vector_stores`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getVectorStore\": (vectorStoreId) =>\n      HttpClientRequest.get(`/vector_stores/${vectorStoreId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"modifyVectorStore\": (vectorStoreId, options) =>\n      HttpClientRequest.post(`/vector_stores/${vectorStoreId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteVectorStore\": (vectorStoreId) =>\n      HttpClientRequest.del(`/vector_stores/${vectorStoreId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteVectorStoreResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createVectorStoreFileBatch\": (vectorStoreId, options) =>\n      HttpClientRequest.post(`/vector_stores/${vectorStoreId}/file_batches`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreFileBatchObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getVectorStoreFileBatch\": (vectorStoreId, batchId) =>\n      HttpClientRequest.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreFileBatchObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"cancelVectorStoreFileBatch\": (vectorStoreId, batchId) =>\n      HttpClientRequest.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreFileBatchObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listFilesInVectorStoreBatch\": (vectorStoreId, batchId, options) =>\n      HttpClientRequest.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any,\n          \"filter\": options?.[\"filter\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListVectorStoreFilesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listVectorStoreFiles\": (vectorStoreId, options) =>\n      HttpClientRequest.get(`/vector_stores/${vectorStoreId}/files`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any,\n          \"filter\": options?.[\"filter\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListVectorStoreFilesResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createVectorStoreFile\": (vectorStoreId, options) =>\n      HttpClientRequest.post(`/vector_stores/${vectorStoreId}/files`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreFileObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getVectorStoreFile\": (vectorStoreId, fileId) =>\n      HttpClientRequest.get(`/vector_stores/${vectorStoreId}/files/${fileId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreFileObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"updateVectorStoreFileAttributes\": (vectorStoreId, fileId, options) =>\n      HttpClientRequest.post(`/vector_stores/${vectorStoreId}/files/${fileId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreFileObject),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteVectorStoreFile\": (vectorStoreId, fileId) =>\n      HttpClientRequest.del(`/vector_stores/${vectorStoreId}/files/${fileId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteVectorStoreFileResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"retrieveVectorStoreFileContent\": (vectorStoreId, fileId) =>\n      HttpClientRequest.get(`/vector_stores/${vectorStoreId}/files/${fileId}/content`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreFileContentResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"searchVectorStore\": (vectorStoreId, options) =>\n      HttpClientRequest.post(`/vector_stores/${vectorStoreId}/search`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VectorStoreSearchResultsPage),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createConversation\": (options) =>\n      HttpClientRequest.post(`/conversations`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ConversationResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getConversation\": (conversationId) =>\n      HttpClientRequest.get(`/conversations/${conversationId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ConversationResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"updateConversation\": (conversationId, options) =>\n      HttpClientRequest.post(`/conversations/${conversationId}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ConversationResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteConversation\": (conversationId) =>\n      HttpClientRequest.del(`/conversations/${conversationId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeletedConversationResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListVideos\": (options) =>\n      HttpClientRequest.get(`/videos`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VideoListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createVideo\": (options) =>\n      HttpClientRequest.post(`/videos`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VideoResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetVideo\": (videoId) =>\n      HttpClientRequest.get(`/videos/${videoId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VideoResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteVideo\": (videoId) =>\n      HttpClientRequest.del(`/videos/${videoId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeletedVideoResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"RetrieveVideoContent\": (videoId, options) =>\n      HttpClientRequest.get(`/videos/${videoId}/content`).pipe(\n        HttpClientRequest.setUrlParams({ \"variant\": options?.[\"variant\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(RetrieveVideoContent200),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreateVideoRemix\": (videoId, options) =>\n      HttpClientRequest.post(`/videos/${videoId}/remix`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(VideoResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"Getinputtokencounts\": (options) =>\n      HttpClientRequest.post(`/responses/input_tokens`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(TokenCountsResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CancelChatSessionMethod\": (sessionId) =>\n      HttpClientRequest.post(`/chatkit/sessions/${sessionId}/cancel`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ChatSessionResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"CreateChatSessionMethod\": (options) =>\n      HttpClientRequest.post(`/chatkit/sessions`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ChatSessionResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListThreadItemsMethod\": (threadId, options) =>\n      HttpClientRequest.get(`/chatkit/threads/${threadId}/items`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ThreadItemListResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"GetThreadMethod\": (threadId) =>\n      HttpClientRequest.get(`/chatkit/threads/${threadId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ThreadResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"DeleteThreadMethod\": (threadId) =>\n      HttpClientRequest.del(`/chatkit/threads/${threadId}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeletedThreadResource),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"ListThreadsMethod\": (options) =>\n      HttpClientRequest.get(`/chatkit/threads`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"limit\": options?.[\"limit\"] as any,\n          \"order\": options?.[\"order\"] as any,\n          \"after\": options?.[\"after\"] as any,\n          \"before\": options?.[\"before\"] as any,\n          \"user\": options?.[\"user\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ThreadListResource),\n          orElse: unexpectedStatus\n        }))\n      )\n  }\n}\n\nexport interface Client {\n  readonly httpClient: HttpClient.HttpClient\n  /**\n   * Returns a list of assistants.\n   */\n  readonly \"listAssistants\": (\n    options?: typeof ListAssistantsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListAssistantsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create an assistant with a model and instructions.\n   */\n  readonly \"createAssistant\": (\n    options: typeof CreateAssistantRequest.Encoded\n  ) => Effect.Effect<typeof AssistantObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves an assistant.\n   */\n  readonly \"getAssistant\": (\n    assistantId: string\n  ) => Effect.Effect<typeof AssistantObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Modifies an assistant.\n   */\n  readonly \"modifyAssistant\": (\n    assistantId: string,\n    options: typeof ModifyAssistantRequest.Encoded\n  ) => Effect.Effect<typeof AssistantObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete an assistant.\n   */\n  readonly \"deleteAssistant\": (\n    assistantId: string\n  ) => Effect.Effect<typeof DeleteAssistantResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Generates audio from the input text.\n   */\n  readonly \"createSpeech\": (\n    options: typeof CreateSpeechRequest.Encoded\n  ) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Transcribes audio into the input language.\n   */\n  readonly \"createTranscription\": (\n    options: typeof CreateTranscriptionRequest.Encoded\n  ) => Effect.Effect<typeof CreateTranscription200.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Translates audio into English.\n   */\n  readonly \"createTranslation\": (\n    options: typeof CreateTranslationRequest.Encoded\n  ) => Effect.Effect<typeof CreateTranslation200.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List your organization's batches.\n   */\n  readonly \"listBatches\": (\n    options?: typeof ListBatchesParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListBatchesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates and executes a batch from an uploaded file of requests\n   */\n  readonly \"createBatch\": (\n    options: typeof CreateBatchRequest.Encoded\n  ) => Effect.Effect<typeof Batch.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves a batch.\n   */\n  readonly \"retrieveBatch\": (\n    batchId: string\n  ) => Effect.Effect<typeof Batch.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, before changing to `cancelled`, where it will have partial results (if any) available in the output file.\n   */\n  readonly \"cancelBatch\": (\n    batchId: string\n  ) => Effect.Effect<typeof Batch.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List stored Chat Completions. Only Chat Completions that have been stored\n   * with the `store` parameter set to `true` will be returned.\n   */\n  readonly \"listChatCompletions\": (\n    options?: typeof ListChatCompletionsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ChatCompletionList.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * **Starting a new project?** We recommend trying [Responses](https://platform.openai.com/docs/api-reference/responses)\n   * to take advantage of the latest OpenAI platform features. Compare\n   * [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses).\n   *\n   * ---\n   *\n   * Creates a model response for the given chat conversation. Learn more in the\n   * [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision),\n   * and [audio](https://platform.openai.com/docs/guides/audio) guides.\n   *\n   * Parameter support can differ depending on the model used to generate the\n   * response, particularly for newer reasoning models. Parameters that are only\n   * supported for reasoning models are noted below. For the current state of\n   * unsupported parameters in reasoning models,\n   * [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning).\n   */\n  readonly \"createChatCompletion\": (\n    options: typeof CreateChatCompletionRequest.Encoded\n  ) => Effect.Effect<typeof CreateChatCompletionResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get a stored chat completion. Only Chat Completions that have been created\n   * with the `store` parameter set to `true` will be returned.\n   */\n  readonly \"getChatCompletion\": (\n    completionId: string\n  ) => Effect.Effect<typeof CreateChatCompletionResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Modify a stored chat completion. Only Chat Completions that have been\n   * created with the `store` parameter set to `true` can be modified. Currently,\n   * the only supported modification is to update the `metadata` field.\n   */\n  readonly \"updateChatCompletion\": (\n    completionId: string,\n    options: typeof UpdateChatCompletionRequest.Encoded\n  ) => Effect.Effect<typeof CreateChatCompletionResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete a stored chat completion. Only Chat Completions that have been\n   * created with the `store` parameter set to `true` can be deleted.\n   */\n  readonly \"deleteChatCompletion\": (\n    completionId: string\n  ) => Effect.Effect<typeof ChatCompletionDeleted.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get the messages in a stored chat completion. Only Chat Completions that\n   * have been created with the `store` parameter set to `true` will be\n   * returned.\n   */\n  readonly \"getChatCompletionMessages\": (\n    completionId: string,\n    options?: typeof GetChatCompletionMessagesParams.Encoded | undefined\n  ) => Effect.Effect<typeof ChatCompletionMessageList.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates a completion for the provided prompt and parameters.\n   */\n  readonly \"createCompletion\": (\n    options: typeof CreateCompletionRequest.Encoded\n  ) => Effect.Effect<typeof CreateCompletionResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List Containers\n   */\n  readonly \"ListContainers\": (\n    options?: typeof ListContainersParams.Encoded | undefined\n  ) => Effect.Effect<typeof ContainerListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create Container\n   */\n  readonly \"CreateContainer\": (\n    options: typeof CreateContainerBody.Encoded\n  ) => Effect.Effect<typeof ContainerResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieve Container\n   */\n  readonly \"RetrieveContainer\": (\n    containerId: string\n  ) => Effect.Effect<typeof ContainerResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete Container\n   */\n  readonly \"DeleteContainer\": (containerId: string) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List Container files\n   */\n  readonly \"ListContainerFiles\": (\n    containerId: string,\n    options?: typeof ListContainerFilesParams.Encoded | undefined\n  ) => Effect.Effect<typeof ContainerFileListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a Container File\n   *\n   * You can send either a multipart/form-data request with the raw file content, or a JSON request with a file ID.\n   */\n  readonly \"CreateContainerFile\": (\n    containerId: string,\n    options: typeof CreateContainerFileBody.Encoded\n  ) => Effect.Effect<typeof ContainerFileResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieve Container File\n   */\n  readonly \"RetrieveContainerFile\": (\n    containerId: string,\n    fileId: string\n  ) => Effect.Effect<typeof ContainerFileResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete Container File\n   */\n  readonly \"DeleteContainerFile\": (\n    containerId: string,\n    fileId: string\n  ) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieve Container File Content\n   */\n  readonly \"RetrieveContainerFileContent\": (\n    containerId: string,\n    fileId: string\n  ) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List all items for a conversation with the given ID.\n   */\n  readonly \"listConversationItems\": (\n    conversationId: string,\n    options?: typeof ListConversationItemsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ConversationItemList.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create items in a conversation with the given ID.\n   */\n  readonly \"createConversationItems\": (\n    conversationId: string,\n    options: {\n      readonly params?: typeof CreateConversationItemsParams.Encoded | undefined\n      readonly payload: typeof CreateConversationItemsRequest.Encoded\n    }\n  ) => Effect.Effect<typeof ConversationItemList.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get a single item from a conversation with the given IDs.\n   */\n  readonly \"getConversationItem\": (\n    conversationId: string,\n    itemId: string,\n    options?: typeof GetConversationItemParams.Encoded | undefined\n  ) => Effect.Effect<typeof ConversationItem.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete an item from a conversation with the given IDs.\n   */\n  readonly \"deleteConversationItem\": (\n    conversationId: string,\n    itemId: string\n  ) => Effect.Effect<typeof ConversationResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates an embedding vector representing the input text.\n   */\n  readonly \"createEmbedding\": (\n    options: typeof CreateEmbeddingRequest.Encoded\n  ) => Effect.Effect<typeof CreateEmbeddingResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List evaluations for a project.\n   */\n  readonly \"listEvals\": (\n    options?: typeof ListEvalsParams.Encoded | undefined\n  ) => Effect.Effect<typeof EvalList.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create the structure of an evaluation that can be used to test a model's performance.\n   * An evaluation is a set of testing criteria and the config for a data source, which dictates the schema of the data used in the evaluation. After creating an evaluation, you can run it on different models and model parameters. We support several types of graders and datasources.\n   * For more information, see the [Evals guide](https://platform.openai.com/docs/guides/evals).\n   */\n  readonly \"createEval\": (\n    options: typeof CreateEvalRequest.Encoded\n  ) => Effect.Effect<typeof Eval.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get an evaluation by ID.\n   */\n  readonly \"getEval\": (evalId: string) => Effect.Effect<typeof Eval.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Update certain properties of an evaluation.\n   */\n  readonly \"updateEval\": (\n    evalId: string,\n    options: typeof UpdateEvalRequest.Encoded\n  ) => Effect.Effect<typeof Eval.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete an evaluation.\n   */\n  readonly \"deleteEval\": (\n    evalId: string\n  ) => Effect.Effect<\n    typeof DeleteEval200.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"Error\", typeof Error.Type>\n  >\n  /**\n   * Get a list of runs for an evaluation.\n   */\n  readonly \"getEvalRuns\": (\n    evalId: string,\n    options?: typeof GetEvalRunsParams.Encoded | undefined\n  ) => Effect.Effect<typeof EvalRunList.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Kicks off a new run for a given evaluation, specifying the data source, and what model configuration to use to test. The datasource will be validated against the schema specified in the config of the evaluation.\n   */\n  readonly \"createEvalRun\": (\n    evalId: string,\n    options: typeof CreateEvalRunRequest.Encoded\n  ) => Effect.Effect<\n    typeof EvalRun.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"Error\", typeof Error.Type>\n  >\n  /**\n   * Get an evaluation run by ID.\n   */\n  readonly \"getEvalRun\": (\n    evalId: string,\n    runId: string\n  ) => Effect.Effect<typeof EvalRun.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Cancel an ongoing evaluation run.\n   */\n  readonly \"cancelEvalRun\": (\n    evalId: string,\n    runId: string\n  ) => Effect.Effect<typeof EvalRun.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete an eval run.\n   */\n  readonly \"deleteEvalRun\": (\n    evalId: string,\n    runId: string\n  ) => Effect.Effect<\n    typeof DeleteEvalRun200.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"Error\", typeof Error.Type>\n  >\n  /**\n   * Get a list of output items for an evaluation run.\n   */\n  readonly \"getEvalRunOutputItems\": (\n    evalId: string,\n    runId: string,\n    options?: typeof GetEvalRunOutputItemsParams.Encoded | undefined\n  ) => Effect.Effect<typeof EvalRunOutputItemList.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get an evaluation run output item by ID.\n   */\n  readonly \"getEvalRunOutputItem\": (\n    evalId: string,\n    runId: string,\n    outputItemId: string\n  ) => Effect.Effect<typeof EvalRunOutputItem.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns a list of files.\n   */\n  readonly \"listFiles\": (\n    options?: typeof ListFilesParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListFilesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Upload a file that can be used across various endpoints. Individual files\n   * can be up to 512 MB, and the size of all files uploaded by one organization\n   * can be up to 1 TB.\n   *\n   * - The Assistants API supports files up to 2 million tokens and of specific\n   *   file types. See the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for\n   *   details.\n   * - The Fine-tuning API only supports `.jsonl` files. The input also has\n   *   certain required formats for fine-tuning\n   *   [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or\n   *   [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) models.\n   * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input\n   *   also has a specific required\n   *   [format](https://platform.openai.com/docs/api-reference/batch/request-input).\n   *\n   * Please [contact us](https://help.openai.com/) if you need to increase these\n   * storage limits.\n   */\n  readonly \"createFile\": (\n    options: typeof CreateFileRequest.Encoded\n  ) => Effect.Effect<typeof OpenAIFile.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns information about a specific file.\n   */\n  readonly \"retrieveFile\": (\n    fileId: string\n  ) => Effect.Effect<typeof OpenAIFile.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete a file and remove it from all vector stores.\n   */\n  readonly \"deleteFile\": (\n    fileId: string\n  ) => Effect.Effect<typeof DeleteFileResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns the contents of the specified file.\n   */\n  readonly \"downloadFile\": (\n    fileId: string\n  ) => Effect.Effect<typeof DownloadFile200.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Run a grader.\n   */\n  readonly \"runGrader\": (\n    options: typeof RunGraderRequest.Encoded\n  ) => Effect.Effect<typeof RunGraderResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Validate a grader.\n   */\n  readonly \"validateGrader\": (\n    options: typeof ValidateGraderRequest.Encoded\n  ) => Effect.Effect<typeof ValidateGraderResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).\n   *\n   * Organization owners can use this endpoint to view all permissions for a fine-tuned model checkpoint.\n   */\n  readonly \"listFineTuningCheckpointPermissions\": (\n    fineTunedModelCheckpoint: string,\n    options?: typeof ListFineTuningCheckpointPermissionsParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ListFineTuningCheckpointPermissionResponse.Type,\n    HttpClientError.HttpClientError | ParseError\n  >\n  /**\n   * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys).\n   *\n   * This enables organization owners to share fine-tuned models with other projects in their organization.\n   */\n  readonly \"createFineTuningCheckpointPermission\": (\n    fineTunedModelCheckpoint: string,\n    options: typeof CreateFineTuningCheckpointPermissionRequest.Encoded\n  ) => Effect.Effect<\n    typeof ListFineTuningCheckpointPermissionResponse.Type,\n    HttpClientError.HttpClientError | ParseError\n  >\n  /**\n   * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys).\n   *\n   * Organization owners can use this endpoint to delete a permission for a fine-tuned model checkpoint.\n   */\n  readonly \"deleteFineTuningCheckpointPermission\": (\n    fineTunedModelCheckpoint: string,\n    permissionId: string\n  ) => Effect.Effect<\n    typeof DeleteFineTuningCheckpointPermissionResponse.Type,\n    HttpClientError.HttpClientError | ParseError\n  >\n  /**\n   * List your organization's fine-tuning jobs\n   */\n  readonly \"listPaginatedFineTuningJobs\": (\n    options?: typeof ListPaginatedFineTuningJobsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListPaginatedFineTuningJobsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates a fine-tuning job which begins the process of creating a new model from a given dataset.\n   *\n   * Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete.\n   *\n   * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)\n   */\n  readonly \"createFineTuningJob\": (\n    options: typeof CreateFineTuningJobRequest.Encoded\n  ) => Effect.Effect<typeof FineTuningJob.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get info about a fine-tuning job.\n   *\n   * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization)\n   */\n  readonly \"retrieveFineTuningJob\": (\n    fineTuningJobId: string\n  ) => Effect.Effect<typeof FineTuningJob.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Immediately cancel a fine-tune job.\n   */\n  readonly \"cancelFineTuningJob\": (\n    fineTuningJobId: string\n  ) => Effect.Effect<typeof FineTuningJob.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List checkpoints for a fine-tuning job.\n   */\n  readonly \"listFineTuningJobCheckpoints\": (\n    fineTuningJobId: string,\n    options?: typeof ListFineTuningJobCheckpointsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListFineTuningJobCheckpointsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get status updates for a fine-tuning job.\n   */\n  readonly \"listFineTuningEvents\": (\n    fineTuningJobId: string,\n    options?: typeof ListFineTuningEventsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListFineTuningJobEventsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Pause a fine-tune job.\n   */\n  readonly \"pauseFineTuningJob\": (\n    fineTuningJobId: string\n  ) => Effect.Effect<typeof FineTuningJob.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Resume a fine-tune job.\n   */\n  readonly \"resumeFineTuningJob\": (\n    fineTuningJobId: string\n  ) => Effect.Effect<typeof FineTuningJob.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates an edited or extended image given one or more source images and a prompt. This endpoint only supports `gpt-image-1` and `dall-e-2`.\n   */\n  readonly \"createImageEdit\": (\n    options: typeof CreateImageEditRequest.Encoded\n  ) => Effect.Effect<typeof ImagesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates an image given a prompt. [Learn more](https://platform.openai.com/docs/guides/images).\n   */\n  readonly \"createImage\": (\n    options: typeof CreateImageRequest.Encoded\n  ) => Effect.Effect<typeof ImagesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates a variation of a given image. This endpoint only supports `dall-e-2`.\n   */\n  readonly \"createImageVariation\": (\n    options: typeof CreateImageVariationRequest.Encoded\n  ) => Effect.Effect<typeof ImagesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the currently available models, and provides basic information about each one such as the owner and availability.\n   */\n  readonly \"listModels\": () => Effect.Effect<\n    typeof ListModelsResponse.Type,\n    HttpClientError.HttpClientError | ParseError\n  >\n  /**\n   * Retrieves a model instance, providing basic information about the model such as the owner and permissioning.\n   */\n  readonly \"retrieveModel\": (\n    model: string\n  ) => Effect.Effect<typeof Model.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete a fine-tuned model. You must have the Owner role in your organization to delete a model.\n   */\n  readonly \"deleteModel\": (\n    model: string\n  ) => Effect.Effect<typeof DeleteModelResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Classifies if text and/or image inputs are potentially harmful. Learn\n   * more in the [moderation guide](https://platform.openai.com/docs/guides/moderation).\n   */\n  readonly \"createModeration\": (\n    options: typeof CreateModerationRequest.Encoded\n  ) => Effect.Effect<typeof CreateModerationResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List organization API keys\n   */\n  readonly \"adminApiKeysList\": (\n    options?: typeof AdminApiKeysListParams.Encoded | undefined\n  ) => Effect.Effect<typeof ApiKeyList.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create an organization admin API key\n   */\n  readonly \"adminApiKeysCreate\": (\n    options: typeof AdminApiKeysCreateRequest.Encoded\n  ) => Effect.Effect<typeof AdminApiKey.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieve a single organization API key\n   */\n  readonly \"adminApiKeysGet\": (\n    keyId: string\n  ) => Effect.Effect<typeof AdminApiKey.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete an organization admin API key\n   */\n  readonly \"adminApiKeysDelete\": (\n    keyId: string\n  ) => Effect.Effect<typeof AdminApiKeysDelete200.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List user actions and configuration changes within this organization.\n   */\n  readonly \"listAuditLogs\": (\n    options?: typeof ListAuditLogsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListAuditLogsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List uploaded certificates for this organization.\n   */\n  readonly \"listOrganizationCertificates\": (\n    options?: typeof ListOrganizationCertificatesParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListCertificatesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Upload a certificate to the organization. This does **not** automatically activate the certificate.\n   *\n   * Organizations can upload up to 50 certificates.\n   */\n  readonly \"uploadCertificate\": (\n    options: typeof UploadCertificateRequest.Encoded\n  ) => Effect.Effect<typeof Certificate.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Activate certificates at the organization level.\n   *\n   * You can atomically and idempotently activate up to 10 certificates at a time.\n   */\n  readonly \"activateOrganizationCertificates\": (\n    options: typeof ToggleCertificatesRequest.Encoded\n  ) => Effect.Effect<typeof ListCertificatesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deactivate certificates at the organization level.\n   *\n   * You can atomically and idempotently deactivate up to 10 certificates at a time.\n   */\n  readonly \"deactivateOrganizationCertificates\": (\n    options: typeof ToggleCertificatesRequest.Encoded\n  ) => Effect.Effect<typeof ListCertificatesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get a certificate that has been uploaded to the organization.\n   *\n   * You can get a certificate regardless of whether it is active or not.\n   */\n  readonly \"getCertificate\": (\n    certificateId: string,\n    options?: typeof GetCertificateParams.Encoded | undefined\n  ) => Effect.Effect<typeof Certificate.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Modify a certificate. Note that only the name can be modified.\n   */\n  readonly \"modifyCertificate\": (\n    certificateId: string,\n    options: typeof ModifyCertificateRequest.Encoded\n  ) => Effect.Effect<typeof Certificate.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete a certificate from the organization.\n   *\n   * The certificate must be inactive for the organization and all projects.\n   */\n  readonly \"deleteCertificate\": (\n    certificateId: string\n  ) => Effect.Effect<typeof DeleteCertificateResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get costs details for the organization.\n   */\n  readonly \"usageCosts\": (\n    options: typeof UsageCostsParams.Encoded\n  ) => Effect.Effect<typeof UsageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists all groups in the organization.\n   */\n  readonly \"listGroups\": (\n    options?: typeof ListGroupsParams.Encoded | undefined\n  ) => Effect.Effect<typeof GroupListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates a new group in the organization.\n   */\n  readonly \"createGroup\": (\n    options: typeof CreateGroupBody.Encoded\n  ) => Effect.Effect<typeof GroupResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Updates a group's information.\n   */\n  readonly \"updateGroup\": (\n    groupId: string,\n    options: typeof UpdateGroupBody.Encoded\n  ) => Effect.Effect<typeof GroupResourceWithSuccess.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a group from the organization.\n   */\n  readonly \"deleteGroup\": (\n    groupId: string\n  ) => Effect.Effect<typeof GroupDeletedResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the organization roles assigned to a group within the organization.\n   */\n  readonly \"listGroupRoleAssignments\": (\n    groupId: string,\n    options?: typeof ListGroupRoleAssignmentsParams.Encoded | undefined\n  ) => Effect.Effect<typeof RoleListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Assigns an organization role to a group within the organization.\n   */\n  readonly \"assignGroupRole\": (\n    groupId: string,\n    options: typeof PublicAssignOrganizationGroupRoleBody.Encoded\n  ) => Effect.Effect<typeof GroupRoleAssignment.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Unassigns an organization role from a group within the organization.\n   */\n  readonly \"unassignGroupRole\": (\n    groupId: string,\n    roleId: string\n  ) => Effect.Effect<typeof DeletedRoleAssignmentResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the users assigned to a group.\n   */\n  readonly \"listGroupUsers\": (\n    groupId: string,\n    options?: typeof ListGroupUsersParams.Encoded | undefined\n  ) => Effect.Effect<typeof UserListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Adds a user to a group.\n   */\n  readonly \"addGroupUser\": (\n    groupId: string,\n    options: typeof CreateGroupUserBody.Encoded\n  ) => Effect.Effect<typeof GroupUserAssignment.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Removes a user from a group.\n   */\n  readonly \"removeGroupUser\": (\n    groupId: string,\n    userId: string\n  ) => Effect.Effect<typeof GroupUserDeletedResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns a list of invites in the organization.\n   */\n  readonly \"listInvites\": (\n    options?: typeof ListInvitesParams.Encoded | undefined\n  ) => Effect.Effect<typeof InviteListResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create an invite for a user to the organization. The invite must be accepted by the user before they have access to the organization.\n   */\n  readonly \"inviteUser\": (\n    options: typeof InviteRequest.Encoded\n  ) => Effect.Effect<typeof Invite.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves an invite.\n   */\n  readonly \"retrieveInvite\": (\n    inviteId: string\n  ) => Effect.Effect<typeof Invite.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete an invite. If the invite has already been accepted, it cannot be deleted.\n   */\n  readonly \"deleteInvite\": (\n    inviteId: string\n  ) => Effect.Effect<typeof InviteDeleteResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns a list of projects.\n   */\n  readonly \"listProjects\": (\n    options?: typeof ListProjectsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ProjectListResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a new project in the organization. Projects can be created and archived, but cannot be deleted.\n   */\n  readonly \"createProject\": (\n    options: typeof ProjectCreateRequest.Encoded\n  ) => Effect.Effect<typeof Project.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves a project.\n   */\n  readonly \"retrieveProject\": (\n    projectId: string\n  ) => Effect.Effect<typeof Project.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Modifies a project in the organization.\n   */\n  readonly \"modifyProject\": (\n    projectId: string,\n    options: typeof ProjectUpdateRequest.Encoded\n  ) => Effect.Effect<\n    typeof Project.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Returns a list of API keys in the project.\n   */\n  readonly \"listProjectApiKeys\": (\n    projectId: string,\n    options?: typeof ListProjectApiKeysParams.Encoded | undefined\n  ) => Effect.Effect<typeof ProjectApiKeyListResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves an API key in the project.\n   */\n  readonly \"retrieveProjectApiKey\": (\n    projectId: string,\n    keyId: string\n  ) => Effect.Effect<typeof ProjectApiKey.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes an API key from the project.\n   */\n  readonly \"deleteProjectApiKey\": (\n    projectId: string,\n    keyId: string\n  ) => Effect.Effect<\n    typeof ProjectApiKeyDeleteResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Archives a project in the organization. Archived projects cannot be used or updated.\n   */\n  readonly \"archiveProject\": (\n    projectId: string\n  ) => Effect.Effect<typeof Project.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List certificates for this project.\n   */\n  readonly \"listProjectCertificates\": (\n    projectId: string,\n    options?: typeof ListProjectCertificatesParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListCertificatesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Activate certificates at the project level.\n   *\n   * You can atomically and idempotently activate up to 10 certificates at a time.\n   */\n  readonly \"activateProjectCertificates\": (\n    projectId: string,\n    options: typeof ToggleCertificatesRequest.Encoded\n  ) => Effect.Effect<typeof ListCertificatesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deactivate certificates at the project level. You can atomically and\n   * idempotently deactivate up to 10 certificates at a time.\n   */\n  readonly \"deactivateProjectCertificates\": (\n    projectId: string,\n    options: typeof ToggleCertificatesRequest.Encoded\n  ) => Effect.Effect<typeof ListCertificatesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the groups that have access to a project.\n   */\n  readonly \"listProjectGroups\": (\n    projectId: string,\n    options?: typeof ListProjectGroupsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ProjectGroupListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Grants a group access to a project.\n   */\n  readonly \"addProjectGroup\": (\n    projectId: string,\n    options: typeof InviteProjectGroupBody.Encoded\n  ) => Effect.Effect<typeof ProjectGroup.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Revokes a group's access to a project.\n   */\n  readonly \"removeProjectGroup\": (\n    projectId: string,\n    groupId: string\n  ) => Effect.Effect<typeof ProjectGroupDeletedResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns the rate limits per model for a project.\n   */\n  readonly \"listProjectRateLimits\": (\n    projectId: string,\n    options?: typeof ListProjectRateLimitsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ProjectRateLimitListResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Updates a project rate limit.\n   */\n  readonly \"updateProjectRateLimits\": (\n    projectId: string,\n    rateLimitId: string,\n    options: typeof ProjectRateLimitUpdateRequest.Encoded\n  ) => Effect.Effect<\n    typeof ProjectRateLimit.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Returns a list of service accounts in the project.\n   */\n  readonly \"listProjectServiceAccounts\": (\n    projectId: string,\n    options?: typeof ListProjectServiceAccountsParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ProjectServiceAccountListResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Creates a new service account in the project. This also returns an unredacted API key for the service account.\n   */\n  readonly \"createProjectServiceAccount\": (\n    projectId: string,\n    options: typeof ProjectServiceAccountCreateRequest.Encoded\n  ) => Effect.Effect<\n    typeof ProjectServiceAccountCreateResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Retrieves a service account in the project.\n   */\n  readonly \"retrieveProjectServiceAccount\": (\n    projectId: string,\n    serviceAccountId: string\n  ) => Effect.Effect<typeof ProjectServiceAccount.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a service account from the project.\n   */\n  readonly \"deleteProjectServiceAccount\": (\n    projectId: string,\n    serviceAccountId: string\n  ) => Effect.Effect<typeof ProjectServiceAccountDeleteResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns a list of users in the project.\n   */\n  readonly \"listProjectUsers\": (\n    projectId: string,\n    options?: typeof ListProjectUsersParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ProjectUserListResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Adds a user to the project. Users must already be members of the organization to be added to a project.\n   */\n  readonly \"createProjectUser\": (\n    projectId: string,\n    options: typeof ProjectUserCreateRequest.Encoded\n  ) => Effect.Effect<\n    typeof ProjectUser.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Retrieves a user in the project.\n   */\n  readonly \"retrieveProjectUser\": (\n    projectId: string,\n    userId: string\n  ) => Effect.Effect<typeof ProjectUser.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Modifies a user's role in the project.\n   */\n  readonly \"modifyProjectUser\": (\n    projectId: string,\n    userId: string,\n    options: typeof ProjectUserUpdateRequest.Encoded\n  ) => Effect.Effect<\n    typeof ProjectUser.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Deletes a user from the project.\n   */\n  readonly \"deleteProjectUser\": (\n    projectId: string,\n    userId: string\n  ) => Effect.Effect<\n    typeof ProjectUserDeleteResponse.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"ErrorResponse\", typeof ErrorResponse.Type>\n  >\n  /**\n   * Lists the roles configured for the organization.\n   */\n  readonly \"listRoles\": (\n    options?: typeof ListRolesParams.Encoded | undefined\n  ) => Effect.Effect<typeof PublicRoleListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates a custom role for the organization.\n   */\n  readonly \"createRole\": (\n    options: typeof PublicCreateOrganizationRoleBody.Encoded\n  ) => Effect.Effect<typeof Role.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Updates an existing organization role.\n   */\n  readonly \"updateRole\": (\n    roleId: string,\n    options: typeof PublicUpdateOrganizationRoleBody.Encoded\n  ) => Effect.Effect<typeof Role.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a custom role from the organization.\n   */\n  readonly \"deleteRole\": (\n    roleId: string\n  ) => Effect.Effect<typeof RoleDeletedResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get audio speeches usage details for the organization.\n   */\n  readonly \"usageAudioSpeeches\": (\n    options: typeof UsageAudioSpeechesParams.Encoded\n  ) => Effect.Effect<typeof UsageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get audio transcriptions usage details for the organization.\n   */\n  readonly \"usageAudioTranscriptions\": (\n    options: typeof UsageAudioTranscriptionsParams.Encoded\n  ) => Effect.Effect<typeof UsageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get code interpreter sessions usage details for the organization.\n   */\n  readonly \"usageCodeInterpreterSessions\": (\n    options: typeof UsageCodeInterpreterSessionsParams.Encoded\n  ) => Effect.Effect<typeof UsageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get completions usage details for the organization.\n   */\n  readonly \"usageCompletions\": (\n    options: typeof UsageCompletionsParams.Encoded\n  ) => Effect.Effect<typeof UsageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get embeddings usage details for the organization.\n   */\n  readonly \"usageEmbeddings\": (\n    options: typeof UsageEmbeddingsParams.Encoded\n  ) => Effect.Effect<typeof UsageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get images usage details for the organization.\n   */\n  readonly \"usageImages\": (\n    options: typeof UsageImagesParams.Encoded\n  ) => Effect.Effect<typeof UsageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get moderations usage details for the organization.\n   */\n  readonly \"usageModerations\": (\n    options: typeof UsageModerationsParams.Encoded\n  ) => Effect.Effect<typeof UsageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get vector stores usage details for the organization.\n   */\n  readonly \"usageVectorStores\": (\n    options: typeof UsageVectorStoresParams.Encoded\n  ) => Effect.Effect<typeof UsageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists all of the users in the organization.\n   */\n  readonly \"listUsers\": (\n    options?: typeof ListUsersParams.Encoded | undefined\n  ) => Effect.Effect<typeof UserListResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves a user by their identifier.\n   */\n  readonly \"retrieveUser\": (\n    userId: string\n  ) => Effect.Effect<typeof User.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Modifies a user's role in the organization.\n   */\n  readonly \"modifyUser\": (\n    userId: string,\n    options: typeof UserRoleUpdateRequest.Encoded\n  ) => Effect.Effect<typeof User.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a user from the organization.\n   */\n  readonly \"deleteUser\": (\n    userId: string\n  ) => Effect.Effect<typeof UserDeleteResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the organization roles assigned to a user within the organization.\n   */\n  readonly \"listUserRoleAssignments\": (\n    userId: string,\n    options?: typeof ListUserRoleAssignmentsParams.Encoded | undefined\n  ) => Effect.Effect<typeof RoleListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Assigns an organization role to a user within the organization.\n   */\n  readonly \"assignUserRole\": (\n    userId: string,\n    options: typeof PublicAssignOrganizationGroupRoleBody.Encoded\n  ) => Effect.Effect<typeof UserRoleAssignment.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Unassigns an organization role from a user within the organization.\n   */\n  readonly \"unassignUserRole\": (\n    userId: string,\n    roleId: string\n  ) => Effect.Effect<typeof DeletedRoleAssignmentResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the project roles assigned to a group within a project.\n   */\n  readonly \"listProjectGroupRoleAssignments\": (\n    projectId: string,\n    groupId: string,\n    options?: typeof ListProjectGroupRoleAssignmentsParams.Encoded | undefined\n  ) => Effect.Effect<typeof RoleListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Assigns a project role to a group within a project.\n   */\n  readonly \"assignProjectGroupRole\": (\n    projectId: string,\n    groupId: string,\n    options: typeof PublicAssignOrganizationGroupRoleBody.Encoded\n  ) => Effect.Effect<typeof GroupRoleAssignment.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Unassigns a project role from a group within a project.\n   */\n  readonly \"unassignProjectGroupRole\": (\n    projectId: string,\n    groupId: string,\n    roleId: string\n  ) => Effect.Effect<typeof DeletedRoleAssignmentResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the roles configured for a project.\n   */\n  readonly \"listProjectRoles\": (\n    projectId: string,\n    options?: typeof ListProjectRolesParams.Encoded | undefined\n  ) => Effect.Effect<typeof PublicRoleListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates a custom role for a project.\n   */\n  readonly \"createProjectRole\": (\n    projectId: string,\n    options: typeof PublicCreateOrganizationRoleBody.Encoded\n  ) => Effect.Effect<typeof Role.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Updates an existing project role.\n   */\n  readonly \"updateProjectRole\": (\n    projectId: string,\n    roleId: string,\n    options: typeof PublicUpdateOrganizationRoleBody.Encoded\n  ) => Effect.Effect<typeof Role.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a custom role from a project.\n   */\n  readonly \"deleteProjectRole\": (\n    projectId: string,\n    roleId: string\n  ) => Effect.Effect<typeof RoleDeletedResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Lists the project roles assigned to a user within a project.\n   */\n  readonly \"listProjectUserRoleAssignments\": (\n    projectId: string,\n    userId: string,\n    options?: typeof ListProjectUserRoleAssignmentsParams.Encoded | undefined\n  ) => Effect.Effect<typeof RoleListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Assigns a project role to a user within a project.\n   */\n  readonly \"assignProjectUserRole\": (\n    projectId: string,\n    userId: string,\n    options: typeof PublicAssignOrganizationGroupRoleBody.Encoded\n  ) => Effect.Effect<typeof UserRoleAssignment.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Unassigns a project role from a user within a project.\n   */\n  readonly \"unassignProjectUserRole\": (\n    projectId: string,\n    userId: string,\n    roleId: string\n  ) => Effect.Effect<typeof DeletedRoleAssignmentResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a new Realtime API call over WebRTC and receive the SDP answer needed\n   * to complete the peer connection.\n   */\n  readonly \"createRealtimeCall\": (\n    options: typeof RealtimeCallCreateRequest.Encoded\n  ) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Accept an incoming SIP call and configure the realtime session that will\n   * handle it.\n   */\n  readonly \"acceptRealtimeCall\": (\n    callId: string,\n    options: typeof RealtimeSessionCreateRequestGA.Encoded\n  ) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * End an active Realtime API call, whether it was initiated over SIP or\n   * WebRTC.\n   */\n  readonly \"hangupRealtimeCall\": (callId: string) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Transfer an active SIP call to a new destination using the SIP REFER verb.\n   */\n  readonly \"referRealtimeCall\": (\n    callId: string,\n    options: typeof RealtimeCallReferRequest.Encoded\n  ) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Decline an incoming SIP call by returning a SIP status code to the caller.\n   */\n  readonly \"rejectRealtimeCall\": (\n    callId: string,\n    options: typeof RealtimeCallRejectRequest.Encoded\n  ) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a Realtime client secret with an associated session configuration.\n   */\n  readonly \"createRealtimeClientSecret\": (\n    options: typeof RealtimeCreateClientSecretRequest.Encoded\n  ) => Effect.Effect<typeof RealtimeCreateClientSecretResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create an ephemeral API token for use in client-side applications with the\n   * Realtime API. Can be configured with the same session parameters as the\n   * `session.update` client event.\n   *\n   * It responds with a session object, plus a `client_secret` key which contains\n   * a usable ephemeral API token that can be used to authenticate browser clients\n   * for the Realtime API.\n   */\n  readonly \"createRealtimeSession\": (\n    options: typeof RealtimeSessionCreateRequest.Encoded\n  ) => Effect.Effect<typeof RealtimeSessionCreateResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create an ephemeral API token for use in client-side applications with the\n   * Realtime API specifically for realtime transcriptions.\n   * Can be configured with the same session parameters as the `transcription_session.update` client event.\n   *\n   * It responds with a session object, plus a `client_secret` key which contains\n   * a usable ephemeral API token that can be used to authenticate browser clients\n   * for the Realtime API.\n   */\n  readonly \"createRealtimeTranscriptionSession\": (\n    options: typeof RealtimeTranscriptionSessionCreateRequest.Encoded\n  ) => Effect.Effect<\n    typeof RealtimeTranscriptionSessionCreateResponse.Type,\n    HttpClientError.HttpClientError | ParseError\n  >\n  /**\n   * Creates a model response. Provide [text](https://platform.openai.com/docs/guides/text) or\n   * [image](https://platform.openai.com/docs/guides/images) inputs to generate [text](https://platform.openai.com/docs/guides/text)\n   * or [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have the model call\n   * your own [custom code](https://platform.openai.com/docs/guides/function-calling) or use built-in\n   * [tools](https://platform.openai.com/docs/guides/tools) like [web search](https://platform.openai.com/docs/guides/tools-web-search)\n   * or [file search](https://platform.openai.com/docs/guides/tools-file-search) to use your own data\n   * as input for the model's response.\n   */\n  readonly \"createResponse\": (\n    options: typeof CreateResponse.Encoded\n  ) => Effect.Effect<typeof Response.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves a model response with the given ID.\n   */\n  readonly \"getResponse\": (\n    responseId: string,\n    options?: typeof GetResponseParams.Encoded | undefined\n  ) => Effect.Effect<typeof Response.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a model response with the given ID.\n   */\n  readonly \"deleteResponse\": (\n    responseId: string\n  ) => Effect.Effect<void, HttpClientError.HttpClientError | ParseError | ClientError<\"Error\", typeof Error.Type>>\n  /**\n   * Cancels a model response with the given ID. Only responses created with\n   * the `background` parameter set to `true` can be cancelled.\n   * [Learn more](https://platform.openai.com/docs/guides/background).\n   */\n  readonly \"cancelResponse\": (\n    responseId: string\n  ) => Effect.Effect<\n    typeof Response.Type,\n    HttpClientError.HttpClientError | ParseError | ClientError<\"Error\", typeof Error.Type>\n  >\n  /**\n   * Returns a list of input items for a given response.\n   */\n  readonly \"listInputItems\": (\n    responseId: string,\n    options?: typeof ListInputItemsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ResponseItemList.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a thread.\n   */\n  readonly \"createThread\": (\n    options: typeof CreateThreadRequest.Encoded\n  ) => Effect.Effect<typeof ThreadObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a thread and run it in one request.\n   */\n  readonly \"createThreadAndRun\": (\n    options: typeof CreateThreadAndRunRequest.Encoded\n  ) => Effect.Effect<typeof RunObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves a thread.\n   */\n  readonly \"getThread\": (\n    threadId: string\n  ) => Effect.Effect<typeof ThreadObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Modifies a thread.\n   */\n  readonly \"modifyThread\": (\n    threadId: string,\n    options: typeof ModifyThreadRequest.Encoded\n  ) => Effect.Effect<typeof ThreadObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete a thread.\n   */\n  readonly \"deleteThread\": (\n    threadId: string\n  ) => Effect.Effect<typeof DeleteThreadResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns a list of messages for a given thread.\n   */\n  readonly \"listMessages\": (\n    threadId: string,\n    options?: typeof ListMessagesParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListMessagesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a message.\n   */\n  readonly \"createMessage\": (\n    threadId: string,\n    options: typeof CreateMessageRequest.Encoded\n  ) => Effect.Effect<typeof MessageObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieve a message.\n   */\n  readonly \"getMessage\": (\n    threadId: string,\n    messageId: string\n  ) => Effect.Effect<typeof MessageObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Modifies a message.\n   */\n  readonly \"modifyMessage\": (\n    threadId: string,\n    messageId: string,\n    options: typeof ModifyMessageRequest.Encoded\n  ) => Effect.Effect<typeof MessageObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Deletes a message.\n   */\n  readonly \"deleteMessage\": (\n    threadId: string,\n    messageId: string\n  ) => Effect.Effect<typeof DeleteMessageResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns a list of runs belonging to a thread.\n   */\n  readonly \"listRuns\": (\n    threadId: string,\n    options?: typeof ListRunsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListRunsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a run.\n   */\n  readonly \"createRun\": (\n    threadId: string,\n    options: {\n      readonly params?: typeof CreateRunParams.Encoded | undefined\n      readonly payload: typeof CreateRunRequest.Encoded\n    }\n  ) => Effect.Effect<typeof RunObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves a run.\n   */\n  readonly \"getRun\": (\n    threadId: string,\n    runId: string\n  ) => Effect.Effect<typeof RunObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Modifies a run.\n   */\n  readonly \"modifyRun\": (\n    threadId: string,\n    runId: string,\n    options: typeof ModifyRunRequest.Encoded\n  ) => Effect.Effect<typeof RunObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Cancels a run that is `in_progress`.\n   */\n  readonly \"cancelRun\": (\n    threadId: string,\n    runId: string\n  ) => Effect.Effect<typeof RunObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns a list of run steps belonging to a run.\n   */\n  readonly \"listRunSteps\": (\n    threadId: string,\n    runId: string,\n    options?: typeof ListRunStepsParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListRunStepsResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves a run step.\n   */\n  readonly \"getRunStep\": (\n    threadId: string,\n    runId: string,\n    stepId: string,\n    options?: typeof GetRunStepParams.Encoded | undefined\n  ) => Effect.Effect<typeof RunStepObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * When a run has the `status: \"requires_action\"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request.\n   */\n  readonly \"submitToolOuputsToRun\": (\n    threadId: string,\n    runId: string,\n    options: typeof SubmitToolOutputsRunRequest.Encoded\n  ) => Effect.Effect<typeof RunObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Creates an intermediate [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object\n   * that you can add [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.\n   * Currently, an Upload can accept at most 8 GB in total and expires after an\n   * hour after you create it.\n   *\n   * Once you complete the Upload, we will create a\n   * [File](https://platform.openai.com/docs/api-reference/files/object) object that contains all the parts\n   * you uploaded. This File is usable in the rest of our platform as a regular\n   * File object.\n   *\n   * For certain `purpose` values, the correct `mime_type` must be specified.\n   * Please refer to documentation for the\n   * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files).\n   *\n   * For guidance on the proper filename extensions for each purpose, please\n   * follow the documentation on [creating a\n   * File](https://platform.openai.com/docs/api-reference/files/create).\n   */\n  readonly \"createUpload\": (\n    options: typeof CreateUploadRequest.Encoded\n  ) => Effect.Effect<typeof Upload.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Cancels the Upload. No Parts may be added after an Upload is cancelled.\n   */\n  readonly \"cancelUpload\": (\n    uploadId: string\n  ) => Effect.Effect<typeof Upload.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Completes the [Upload](https://platform.openai.com/docs/api-reference/uploads/object).\n   *\n   * Within the returned Upload object, there is a nested [File](https://platform.openai.com/docs/api-reference/files/object) object that is ready to use in the rest of the platform.\n   *\n   * You can specify the order of the Parts by passing in an ordered list of the Part IDs.\n   *\n   * The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed.\n   */\n  readonly \"completeUpload\": (\n    uploadId: string,\n    options: typeof CompleteUploadRequest.Encoded\n  ) => Effect.Effect<typeof Upload.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Adds a [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. A Part represents a chunk of bytes from the file you are trying to upload.\n   *\n   * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB.\n   *\n   * It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).\n   */\n  readonly \"addUploadPart\": (\n    uploadId: string,\n    options: typeof AddUploadPartRequest.Encoded\n  ) => Effect.Effect<typeof UploadPart.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns a list of vector stores.\n   */\n  readonly \"listVectorStores\": (\n    options?: typeof ListVectorStoresParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListVectorStoresResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a vector store.\n   */\n  readonly \"createVectorStore\": (\n    options: typeof CreateVectorStoreRequest.Encoded\n  ) => Effect.Effect<typeof VectorStoreObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves a vector store.\n   */\n  readonly \"getVectorStore\": (\n    vectorStoreId: string\n  ) => Effect.Effect<typeof VectorStoreObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Modifies a vector store.\n   */\n  readonly \"modifyVectorStore\": (\n    vectorStoreId: string,\n    options: typeof UpdateVectorStoreRequest.Encoded\n  ) => Effect.Effect<typeof VectorStoreObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete a vector store.\n   */\n  readonly \"deleteVectorStore\": (\n    vectorStoreId: string\n  ) => Effect.Effect<typeof DeleteVectorStoreResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a vector store file batch.\n   */\n  readonly \"createVectorStoreFileBatch\": (\n    vectorStoreId: string,\n    options: typeof CreateVectorStoreFileBatchRequest.Encoded\n  ) => Effect.Effect<typeof VectorStoreFileBatchObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves a vector store file batch.\n   */\n  readonly \"getVectorStoreFileBatch\": (\n    vectorStoreId: string,\n    batchId: string\n  ) => Effect.Effect<typeof VectorStoreFileBatchObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible.\n   */\n  readonly \"cancelVectorStoreFileBatch\": (\n    vectorStoreId: string,\n    batchId: string\n  ) => Effect.Effect<typeof VectorStoreFileBatchObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns a list of vector store files in a batch.\n   */\n  readonly \"listFilesInVectorStoreBatch\": (\n    vectorStoreId: string,\n    batchId: string,\n    options?: typeof ListFilesInVectorStoreBatchParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListVectorStoreFilesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Returns a list of vector store files.\n   */\n  readonly \"listVectorStoreFiles\": (\n    vectorStoreId: string,\n    options?: typeof ListVectorStoreFilesParams.Encoded | undefined\n  ) => Effect.Effect<typeof ListVectorStoreFilesResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a vector store file by attaching a [File](https://platform.openai.com/docs/api-reference/files) to a [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).\n   */\n  readonly \"createVectorStoreFile\": (\n    vectorStoreId: string,\n    options: typeof CreateVectorStoreFileRequest.Encoded\n  ) => Effect.Effect<typeof VectorStoreFileObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieves a vector store file.\n   */\n  readonly \"getVectorStoreFile\": (\n    vectorStoreId: string,\n    fileId: string\n  ) => Effect.Effect<typeof VectorStoreFileObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Update attributes on a vector store file.\n   */\n  readonly \"updateVectorStoreFileAttributes\": (\n    vectorStoreId: string,\n    fileId: string,\n    options: typeof UpdateVectorStoreFileAttributesRequest.Encoded\n  ) => Effect.Effect<typeof VectorStoreFileObject.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. To delete the file, use the [delete file](https://platform.openai.com/docs/api-reference/files/delete) endpoint.\n   */\n  readonly \"deleteVectorStoreFile\": (\n    vectorStoreId: string,\n    fileId: string\n  ) => Effect.Effect<typeof DeleteVectorStoreFileResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieve the parsed contents of a vector store file.\n   */\n  readonly \"retrieveVectorStoreFileContent\": (\n    vectorStoreId: string,\n    fileId: string\n  ) => Effect.Effect<typeof VectorStoreFileContentResponse.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Search a vector store for relevant chunks based on a query and file attributes filter.\n   */\n  readonly \"searchVectorStore\": (\n    vectorStoreId: string,\n    options: typeof VectorStoreSearchRequest.Encoded\n  ) => Effect.Effect<typeof VectorStoreSearchResultsPage.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a conversation.\n   */\n  readonly \"createConversation\": (\n    options: typeof CreateConversationBody.Encoded\n  ) => Effect.Effect<typeof ConversationResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get a conversation\n   */\n  readonly \"getConversation\": (\n    conversationId: string\n  ) => Effect.Effect<typeof ConversationResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Update a conversation\n   */\n  readonly \"updateConversation\": (\n    conversationId: string,\n    options: typeof UpdateConversationBody.Encoded\n  ) => Effect.Effect<typeof ConversationResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete a conversation. Items in the conversation will not be deleted.\n   */\n  readonly \"deleteConversation\": (\n    conversationId: string\n  ) => Effect.Effect<typeof DeletedConversationResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List videos\n   */\n  readonly \"ListVideos\": (\n    options?: typeof ListVideosParams.Encoded | undefined\n  ) => Effect.Effect<typeof VideoListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a video\n   */\n  readonly \"createVideo\": (\n    options: typeof CreateVideoBody.Encoded\n  ) => Effect.Effect<typeof VideoResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieve a video\n   */\n  readonly \"GetVideo\": (\n    videoId: string\n  ) => Effect.Effect<typeof VideoResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete a video\n   */\n  readonly \"DeleteVideo\": (\n    videoId: string\n  ) => Effect.Effect<typeof DeletedVideoResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Download video content\n   */\n  readonly \"RetrieveVideoContent\": (\n    videoId: string,\n    options?: typeof RetrieveVideoContentParams.Encoded | undefined\n  ) => Effect.Effect<typeof RetrieveVideoContent200.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a video remix\n   */\n  readonly \"CreateVideoRemix\": (\n    videoId: string,\n    options: typeof CreateVideoRemixBody.Encoded\n  ) => Effect.Effect<typeof VideoResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Get input token counts\n   */\n  readonly \"Getinputtokencounts\": (\n    options: typeof TokenCountsBody.Encoded\n  ) => Effect.Effect<typeof TokenCountsResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Cancel a ChatKit session\n   */\n  readonly \"CancelChatSessionMethod\": (\n    sessionId: string\n  ) => Effect.Effect<typeof ChatSessionResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Create a ChatKit session\n   */\n  readonly \"CreateChatSessionMethod\": (\n    options: typeof CreateChatSessionBody.Encoded\n  ) => Effect.Effect<typeof ChatSessionResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List ChatKit thread items\n   */\n  readonly \"ListThreadItemsMethod\": (\n    threadId: string,\n    options?: typeof ListThreadItemsMethodParams.Encoded | undefined\n  ) => Effect.Effect<typeof ThreadItemListResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Retrieve a ChatKit thread\n   */\n  readonly \"GetThreadMethod\": (\n    threadId: string\n  ) => Effect.Effect<typeof ThreadResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * Delete a ChatKit thread\n   */\n  readonly \"DeleteThreadMethod\": (\n    threadId: string\n  ) => Effect.Effect<typeof DeletedThreadResource.Type, HttpClientError.HttpClientError | ParseError>\n  /**\n   * List ChatKit threads\n   */\n  readonly \"ListThreadsMethod\": (\n    options?: typeof ListThreadsMethodParams.Encoded | undefined\n  ) => Effect.Effect<typeof ThreadListResource.Type, HttpClientError.HttpClientError | ParseError>\n}\n\nexport interface ClientError<Tag extends string, E> {\n  readonly _tag: Tag\n  readonly request: HttpClientRequest.HttpClientRequest\n  readonly response: HttpClientResponse.HttpClientResponse\n  readonly cause: E\n}\n\nclass ClientErrorImpl extends Data.Error<{\n  _tag: string\n  cause: any\n  request: HttpClientRequest.HttpClientRequest\n  response: HttpClientResponse.HttpClientResponse\n}> {}\n\nexport const ClientError = <Tag extends string, E>(\n  tag: Tag,\n  cause: E,\n  response: HttpClientResponse.HttpClientResponse\n): ClientError<Tag, E> =>\n  new ClientErrorImpl({\n    _tag: tag,\n    cause,\n    response,\n    request: response.request\n  }) as any\n"
  },
  {
    "path": "packages/ai/openai/src/OpenAiClient.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AiError from \"@effect/ai/AiError\"\nimport * as Sse from \"@effect/experimental/Sse\"\nimport * as Headers from \"@effect/platform/Headers\"\nimport * as HttpBody from \"@effect/platform/HttpBody\"\nimport * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as Arr from \"effect/Array\"\nimport * as Config from \"effect/Config\"\nimport type { ConfigError } from \"effect/ConfigError\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport * as Generated from \"./Generated.js\"\nimport { OpenAiConfig } from \"./OpenAiConfig.js\"\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class OpenAiClient extends Context.Tag(\n  \"@effect/ai-openai/OpenAiClient\"\n)<OpenAiClient, Service>() {}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface Service {\n  readonly client: Generated.Client\n\n  readonly streamRequest: <A, I, R>(\n    request: HttpClientRequest.HttpClientRequest,\n    schema: Schema.Schema<A, I, R>\n  ) => Stream.Stream<A, AiError.AiError, R>\n\n  readonly createResponse: (\n    options: typeof Generated.CreateResponse.Encoded\n  ) => Effect.Effect<Generated.Response, AiError.AiError>\n\n  readonly createResponseStream: (\n    options: Omit<typeof Generated.CreateResponse.Encoded, \"stream\">\n  ) => Stream.Stream<ResponseStreamEvent, AiError.AiError>\n\n  readonly createEmbedding: (\n    options: typeof Generated.CreateEmbeddingRequest.Encoded\n  ) => Effect.Effect<Generated.CreateEmbeddingResponse, AiError.AiError>\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type StreamCompletionRequest = Omit<typeof Generated.CreateChatCompletionRequest.Encoded, \"stream\">\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (options: {\n  /**\n   * The API key to use to communicate with the OpenAi API.\n   */\n  readonly apiKey?: Redacted.Redacted | undefined\n  /**\n   * The URL to use to communicate with the OpenAi API.\n   */\n  readonly apiUrl?: string | undefined\n  /**\n   * The OpenAi organization identifier to use when communicating with the\n   * OpenAi API.\n   */\n  readonly organizationId?: Redacted.Redacted | undefined\n  /**\n   * The OpenAi project identifier to use when communicating with the OpenAi\n   * API.\n   */\n  readonly projectId?: Redacted.Redacted | undefined\n  /**\n   * A method which can be used to transform the underlying `HttpClient` which\n   * will be used to communicate with the OpenAi API.\n   */\n  readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n}): Effect.Effect<Service, never, HttpClient.HttpClient | Scope.Scope> =>\n  Effect.gen(function*() {\n    const organizationHeader = \"OpenAI-Organization\"\n    const projectHeader = \"OpenAI-Project\"\n\n    yield* Effect.locallyScopedWith(Headers.currentRedactedNames, Arr.appendAll([organizationHeader, projectHeader]))\n\n    const httpClient = (yield* HttpClient.HttpClient).pipe(\n      HttpClient.mapRequest((request) =>\n        request.pipe(\n          HttpClientRequest.prependUrl(options.apiUrl ?? \"https://api.openai.com/v1\"),\n          options.apiKey ? HttpClientRequest.bearerToken(options.apiKey) : identity,\n          options.organizationId !== undefined\n            ? HttpClientRequest.setHeader(organizationHeader, Redacted.value(options.organizationId))\n            : identity,\n          options.projectId !== undefined\n            ? HttpClientRequest.setHeader(projectHeader, Redacted.value(options.projectId))\n            : identity,\n          HttpClientRequest.acceptJson\n        )\n      ),\n      options.transformClient ? options.transformClient : identity\n    )\n\n    const httpClientOk = HttpClient.filterStatusOk(httpClient)\n\n    const client = Generated.make(httpClient, {\n      transformClient: (client) =>\n        OpenAiConfig.getOrUndefined.pipe(\n          Effect.map((config) => config?.transformClient ? config.transformClient(client) : client)\n        )\n    })\n\n    const streamRequest = <A, I, R>(\n      request: HttpClientRequest.HttpClientRequest,\n      schema: Schema.Schema<A, I, R>\n    ): Stream.Stream<A, AiError.AiError, R> => {\n      const decodeEvent = Schema.decode(Schema.parseJson(schema))\n      return httpClientOk.execute(request).pipe(\n        Effect.map((r) => r.stream),\n        Stream.unwrapScoped,\n        Stream.decodeText(),\n        Stream.pipeThroughChannel(Sse.makeChannel()),\n        Stream.mapEffect((event) => decodeEvent(event.data)),\n        Stream.catchTags({\n          RequestError: (error) =>\n            AiError.HttpRequestError.fromRequestError({\n              module: \"OpenAiClient\",\n              method: \"streamRequest\",\n              error\n            }),\n          ResponseError: (error) =>\n            AiError.HttpResponseError.fromResponseError({\n              module: \"OpenAiClient\",\n              method: \"streamRequest\",\n              error\n            }),\n          ParseError: (error) =>\n            AiError.MalformedOutput.fromParseError({\n              module: \"OpenAiClient\",\n              method: \"streamRequest\",\n              error\n            })\n        })\n      )\n    }\n\n    const createResponse = (\n      options: typeof Generated.CreateResponse.Encoded\n    ): Effect.Effect<Generated.Response, AiError.AiError> =>\n      client.createResponse(options).pipe(\n        Effect.catchTags({\n          RequestError: (error) =>\n            AiError.HttpRequestError.fromRequestError({\n              module: \"OpenAiClient\",\n              method: \"createResponse\",\n              error\n            }),\n          ResponseError: (error) =>\n            AiError.HttpResponseError.fromResponseError({\n              module: \"OpenAiClient\",\n              method: \"createResponse\",\n              error\n            }),\n          ParseError: (error) =>\n            AiError.MalformedOutput.fromParseError({\n              module: \"OpenAiClient\",\n              method: \"createResponse\",\n              error\n            })\n        })\n      )\n\n    const createResponseStream = (\n      options: Omit<typeof Generated.CreateResponse.Encoded, \"stream\">\n    ): Stream.Stream<ResponseStreamEvent, AiError.AiError> => {\n      const request = HttpClientRequest.post(\"/responses\", {\n        body: HttpBody.unsafeJson({ ...options, stream: true })\n      })\n      return streamRequest(request, ResponseStreamEvent).pipe(\n        Stream.takeUntil((event) => event.type === \"response.completed\" || event.type === \"response.incomplete\")\n      )\n    }\n\n    const createEmbedding = (\n      options: typeof Generated.CreateEmbeddingRequest.Encoded\n    ): Effect.Effect<Generated.CreateEmbeddingResponse, AiError.AiError> =>\n      client.createEmbedding(options).pipe(\n        Effect.catchTags({\n          RequestError: (error) =>\n            AiError.HttpRequestError.fromRequestError({\n              module: \"OpenAiClient\",\n              method: \"createResponse\",\n              error\n            }),\n          ResponseError: (error) =>\n            AiError.HttpResponseError.fromResponseError({\n              module: \"OpenAiClient\",\n              method: \"createResponse\",\n              error\n            }),\n          ParseError: (error) =>\n            AiError.MalformedOutput.fromParseError({\n              module: \"OpenAiClient\",\n              method: \"createResponse\",\n              error\n            })\n        })\n      )\n\n    return OpenAiClient.of({\n      client,\n      streamRequest,\n      createResponse,\n      createResponseStream,\n      createEmbedding\n    })\n  })\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly apiKey?: Redacted.Redacted | undefined\n  readonly apiUrl?: string | undefined\n  readonly organizationId?: Redacted.Redacted | undefined\n  readonly projectId?: Redacted.Redacted | undefined\n  readonly transformClient?: (client: HttpClient.HttpClient) => HttpClient.HttpClient\n}): Layer.Layer<OpenAiClient, never, HttpClient.HttpClient> => Layer.scoped(OpenAiClient, make(options))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerConfig = (\n  options: {\n    readonly apiKey?: Config.Config<Redacted.Redacted | undefined> | undefined\n    readonly apiUrl?: Config.Config<string | undefined> | undefined\n    readonly organizationId?: Config.Config<Redacted.Redacted | undefined> | undefined\n    readonly projectId?: Config.Config<Redacted.Redacted | undefined> | undefined\n    readonly transformClient?: (client: HttpClient.HttpClient) => HttpClient.HttpClient\n  }\n): Layer.Layer<OpenAiClient, ConfigError, HttpClient.HttpClient> => {\n  const { transformClient, ...configs } = options\n  return Config.all(configs).pipe(\n    Effect.flatMap((configs) => make({ ...configs, transformClient })),\n    Layer.scoped(OpenAiClient)\n  )\n}\n\n// =============================================================================\n// Response Stream Schema\n// =============================================================================\n\n/**\n * An event that is emitted when a response is created.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseCreatedEvent extends Schema.Class<ResponseCreatedEvent>(\n  \"@effect/ai-openai/ResponseCreatedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.created\"`.\n   */\n  type: Schema.Literal(\"response.created\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The response that was created.\n   */\n  response: Generated.Response\n}) {}\n\n/**\n * Emitted when a response is queued and waiting to be processed.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseQueuedEvent extends Schema.Class<ResponseQueuedEvent>(\n  \"@effect/ai-openai/ResponseQueuedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.queued\"`.\n   */\n  type: Schema.Literal(\"response.queued\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The full response object that is queued.\n   */\n  response: Generated.Response\n}) {}\n\n/**\n * Emitted when the response is in progress.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseInProgressEvent extends Schema.Class<ResponseInProgressEvent>(\n  \"@effect/ai-openai/ResponseInProgressEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.in_progress\"`.\n   */\n  type: Schema.Literal(\"response.in_progress\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The response that is in progress.\n   */\n  response: Generated.Response\n}) {}\n\n/**\n * Emitted when the model response is complete.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseCompletedEvent extends Schema.Class<ResponseCompletedEvent>(\n  \"@effect/ai-openai/ResponseCompletedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.completed\"`.\n   */\n  type: Schema.Literal(\"response.completed\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * Properties of the completed response.\n   */\n  response: Generated.Response\n}) {}\n\n/**\n * An event that is emitted when a response finishes as incomplete.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseIncompleteEvent extends Schema.Class<ResponseIncompleteEvent>(\n  \"@effect/ai-openai/ResponseIncompleteEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.incomplete\"`.\n   */\n  type: Schema.Literal(\"response.incomplete\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The response that was incomplete.\n   */\n  response: Generated.Response\n}) {}\n\n/**\n * An event that is emitted when a response fails.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseFailedEvent extends Schema.Class<ResponseFailedEvent>(\n  \"@effect/ai-openai/ResponseFailedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.failed\"`.\n   */\n  type: Schema.Literal(\"response.failed\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The response that failed.\n   */\n  response: Generated.Response\n}) {}\n\nconst WebSearchToolCallForAddEvent = Schema.asSchema(\n  Generated.WebSearchToolCall.pipe(\n    Schema.omit(\"action\")\n  )\n)\n\nconst AddEventOutputItem = Schema.Union(\n  Generated.OutputItem,\n  WebSearchToolCallForAddEvent\n)\n\n/**\n * Emitted when a new output item is added.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseOutputItemAddedEvent extends Schema.Class<ResponseOutputItemAddedEvent>(\n  \"@effect/ai-openai/ResponseOutputItemAddedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.output_item.added\"`.\n   */\n  type: Schema.Literal(\"response.output_item.added\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that was added.\n   */\n  output_index: Schema.Int,\n  /**\n   * The output item that was added.\n   */\n  item: AddEventOutputItem\n}) {}\n\n/**\n * Emitted when an output item is marked done.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseOutputItemDoneEvent extends Schema.Class<ResponseOutputItemDoneEvent>(\n  \"@effect/ai-openai/ResponseOutputItemDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.output_item.done\"`.\n   */\n  type: Schema.Literal(\"response.output_item.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that was marked done.\n   */\n  output_index: Schema.Int,\n  /**\n   * The output item that was marked done.\n   */\n  item: Generated.OutputItem\n}) {}\n\n/**\n * Emitted when a new content part is added.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseContentPartAddedEvent extends Schema.Class<ResponseContentPartAddedEvent>(\n  \"@effect/ai-openai/ResponseContentPartAddedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.content_part.added\"`.\n   */\n  type: Schema.Literal(\"response.content_part.added\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the content part was added to.\n   */\n  output_index: Schema.Int,\n  /**\n   * The index of the content part that was added.\n   */\n  content_index: Schema.Int,\n  /**\n   * The ID of the output item that the content part was added to.\n   */\n  item_id: Schema.String,\n  /**\n   * The content part that was added.\n   */\n  part: Schema.Union(\n    Generated.OutputTextContent,\n    Generated.RefusalContent,\n    Generated.ReasoningTextContent\n  )\n}) {}\n\n/**\n * Emitted when a content part is done.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseContentPartDoneEvent extends Schema.Class<ResponseContentPartDoneEvent>(\n  \"@effect/ai-openai/ResponseContentPartDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.content_part.done\"`.\n   */\n  type: Schema.Literal(\"response.content_part.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the content part was added to.\n   */\n  output_index: Schema.Int,\n  /**\n   * The index of the content part that is done.\n   */\n  content_index: Schema.Int,\n  /**\n   * The ID of the output item that the content part was added to.\n   */\n  item_id: Schema.String,\n  /**\n   * The content part that was added.\n   */\n  part: Schema.Union(\n    Generated.OutputTextContent,\n    Generated.RefusalContent,\n    Generated.ReasoningTextContent\n  )\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class LogProbs extends Schema.Class<LogProbs>(\n  \"@effect/ai-openai/LogProbs\"\n)({\n  /**\n   * The log probability of this token.\n   */\n  logprob: Schema.Number,\n  /**\n   * A possible text token.\n   */\n  token: Schema.String,\n  /**\n   * The log probability of the top 20 most likely tokens.\n   */\n  top_logprobs: Schema.Array(Schema.Struct({\n    /**\n     * The log probability of this token.\n     */\n    logprob: Schema.Number,\n    /**\n     * A possible text token.\n     */\n    token: Schema.String\n  }))\n}) {}\n\n/**\n * Emitted when there is an additional text delta.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseOutputTextDeltaEvent extends Schema.Class<ResponseOutputTextDeltaEvent>(\n  \"@effect/ai-openai/ResponseOutputTextDeltaEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.output_text.delta\"`.\n   */\n  type: Schema.Literal(\"response.output_text.delta\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the text delta was added to.\n   */\n  output_index: Schema.Int,\n  /**\n   * The index of the content part that the text delta was added to.\n   */\n  content_index: Schema.Int,\n  /**\n   * The ID of the output item that the text delta was added to.\n   */\n  item_id: Schema.String,\n  /**\n   * The text delta that was added.\n   */\n  delta: Schema.String,\n  /**\n   * The log probabilities of the tokens in the delta.\n   */\n  logprobs: Schema.optional(Schema.NullOr(Schema.Array(LogProbs)))\n}) {}\n\n/**\n * Emitted when text content is finalized.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseOutputTextDoneEvent extends Schema.Class<ResponseOutputTextDoneEvent>(\n  \"@effect/ai-openai/ResponseOutputTextDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.output_text.done\"`.\n   */\n  type: Schema.Literal(\"response.output_text.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the text content is finalized.\n   */\n  output_index: Schema.Int,\n  /**\n   * The index of the content part that the text content is finalized.\n   */\n  content_index: Schema.Int,\n  /**\n   * The ID of the output item that the text content is finalized.\n   */\n  item_id: Schema.String,\n  /**\n   * The text content that is finalized.\n   */\n  text: Schema.String,\n  /**\n   * The log probabilities of the tokens in the delta.\n   */\n  logprobs: Schema.optional(Schema.NullOr(Schema.Array(LogProbs)))\n}) {}\n\n/**\n * Emitted when an annotation is added to output text content.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseOutputTextAnnotationAddedEvent extends Schema.Class<ResponseOutputTextAnnotationAddedEvent>(\n  \"@effect/ai-openai/ResponseOutputTextAnnotationAddedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.output_text.annotation.added\"`.\n   */\n  type: Schema.Literal(\"response.output_text.annotation.added\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item in the response's output array.\n   */\n  output_index: Schema.Int,\n  /**\n   * The index of the content part within the output item.\n   */\n  content_index: Schema.Int,\n  /**\n   * The index of the annotation within the content part.\n   */\n  annotation_index: Schema.Int,\n  /**\n   * The unique identifier of the item to which the annotation is being added.\n   */\n  item_id: Schema.String,\n  /**\n   * The annotation object being added. (See annotation schema for details.)\n   */\n  annotation: Generated.Annotation\n}) {}\n\n/**\n * Emitted when there is a partial refusal text.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseRefusalDeltaEvent extends Schema.Class<ResponseRefusalDeltaEvent>(\n  \"@effect/ai-openai/ResponseRefusalDeltaEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.refusal.delta\"`.\n   */\n  type: Schema.Literal(\"response.refusal.delta\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the refusal text is added to.\n   */\n  output_index: Schema.Int,\n  /**\n   * The index of the content part that the refusal text is added to.\n   */\n  content_index: Schema.Int,\n  /**\n   * The ID of the output item that the refusal text is added to.\n   */\n  item_id: Schema.String,\n  /**\n   * The refusal text that is added.\n   */\n  delta: Schema.String\n}) {}\n\n/**\n * Emitted when refusal text is finalized.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseRefusalDoneEvent extends Schema.Class<ResponseRefusalDoneEvent>(\n  \"@effect/ai-openai/ResponseRefusalDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.refusal.done\"`.\n   */\n  type: Schema.Literal(\"response.refusal.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the refusal text is finalized.\n   */\n  output_index: Schema.Int,\n  /**\n   * The index of the content part that the refusal text is finalized.\n   */\n  content_index: Schema.Int,\n  /**\n   * The index of the output item that the refusal text is added to.\n   */\n  item_id: Schema.String,\n  /**\n   * The refusal text that is finalized.\n   */\n  refusal: Schema.String\n}) {}\n\n/**\n * Emitted when there is a partial function-call arguments delta.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseFunctionCallArgumentsDeltaEvent extends Schema.Class<ResponseFunctionCallArgumentsDeltaEvent>(\n  \"@effect/ai-openai/ResponseFunctionCallArgumentsDeltaEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.function_call_arguments.delta\"`.\n   */\n  type: Schema.Literal(\"response.function_call_arguments.delta\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the function-call arguments delta is added to.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the output item that the function-call arguments delta is added to.\n   */\n  item_id: Schema.String,\n  /**\n   * The function-call arguments delta that is added.\n   */\n  delta: Schema.String\n}) {}\n\n/**\n * Emitted when function-call arguments are finalized.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseFunctionCallArgumentsDoneEvent extends Schema.Class<ResponseFunctionCallArgumentsDoneEvent>(\n  \"@effect/ai-openai/ResponseFunctionCallArgumentsDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.function_call_arguments.done\"`.\n   */\n  type: Schema.Literal(\"response.function_call_arguments.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the item.\n   */\n  item_id: Schema.String,\n  /**\n   * The function-call arguments.\n   */\n  arguments: Schema.String\n}) {}\n\n/**\n * Emitted when a file search call is initiated.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseFileSearchCallInProgressEvent extends Schema.Class<ResponseFileSearchCallInProgressEvent>(\n  \"@effect/ai-openai/ResponseFileSearchCallInProgressEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.file_search_call.in_progress\"`.\n   */\n  type: Schema.Literal(\"response.file_search_call.in_progress\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the file search call is initiated.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the output item that the file search call is initiated.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when a file search is currently searching.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseFileSearchCallSearchingEvent extends Schema.Class<ResponseFileSearchCallSearchingEvent>(\n  \"@effect/ai-openai/ResponseFileSearchCallSearchingEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.file_search_call.searching\"`.\n   */\n  type: Schema.Literal(\"response.file_search_call.searching\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the file search call is searching.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the output item that the file search call is initiated.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when a file search call is completed (results found).\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseFileSearchCallCompletedEvent extends Schema.Class<ResponseFileSearchCallCompletedEvent>(\n  \"@effect/ai-openai/ResponseFileSearchCallCompletedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.file_search_call.completed\"`.\n   */\n  type: Schema.Literal(\"response.file_search_call.completed\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the file search call is initiated.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the output item that the file search call is initiated.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when a web search call is initiated.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseWebSearchCallInProgressEvent extends Schema.Class<ResponseWebSearchCallInProgressEvent>(\n  \"@effect/ai-openai/ResponseWebSearchCallInProgressEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.web_search_call.in_progress\"`.\n   */\n  type: Schema.Literal(\"response.web_search_call.in_progress\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the web search call is associated with.\n   */\n  output_index: Schema.Int,\n  /**\n   * Unique ID for the output item associated with the web search call.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when a web search call is executing.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseWebSearchCallSearchingEvent extends Schema.Class<ResponseWebSearchCallSearchingEvent>(\n  \"@effect/ai-openai/ResponseWebSearchCallSearchingEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.web_search_call.searching\"`.\n   */\n  type: Schema.Literal(\"response.web_search_call.searching\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the web search call is associated with.\n   */\n  output_index: Schema.Int,\n  /**\n   * Unique ID for the output item associated with the web search call.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when a web search call is completed.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseWebSearchCallCompletedEvent extends Schema.Class<ResponseWebSearchCallCompletedEvent>(\n  \"@effect/ai-openai/ResponseWebSearchCallCompletedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.web_search_call.completed\"`.\n   */\n  type: Schema.Literal(\"response.web_search_call.completed\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that the web search call is associated with.\n   */\n  output_index: Schema.Int,\n  /**\n   * Unique ID for the output item associated with the web search call.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class SummaryPart extends Schema.Class<SummaryPart>(\n  \"@effect/ai-openai/SummaryPart\"\n)({\n  /**\n   * The type of the summary part. Always `\"summary_text\"`.\n   */\n  type: Schema.Literal(\"summary_text\"),\n  /**\n   * The text of the summary part.\n   */\n  text: Schema.String\n}) {}\n\n/**\n * Emitted when a reasoning summary part is completed.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseReasoningSummaryPartAddedEvent extends Schema.Class<ResponseReasoningSummaryPartAddedEvent>(\n  \"@effect/ai-openai/ResponseReasoningSummaryPartAddedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.reasoning_summary_part.added\"`.\n   */\n  type: Schema.Literal(\"response.reasoning_summary_part.added\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the summary part within the reasoning summary.\n   */\n  summary_index: Schema.Int,\n  /**\n   * The index of the output item this summary part is associated with.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the item this summary part is associated with.\n   */\n  item_id: Schema.String,\n  /**\n   * The summary part that was added.\n   */\n  part: SummaryPart\n}) {}\n\n/**\n * Emitted when a new reasoning summary part is added.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseReasoningSummaryPartDoneEvent extends Schema.Class<ResponseReasoningSummaryPartDoneEvent>(\n  \"@effect/ai-openai/ResponseReasoningSummaryPartDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.reasoning_summary_part.done\"`.\n   */\n  type: Schema.Literal(\"response.reasoning_summary_part.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the summary part within the reasoning summary.\n   */\n  summary_index: Schema.Int,\n  /**\n   * The index of the output item this summary part is associated with.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the item this summary part is associated with.\n   */\n  item_id: Schema.String,\n  /**\n   * The completed summary part.\n   */\n  part: SummaryPart\n}) {}\n\n/**\n * Emitted when a delta is added to a reasoning summary text.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseReasoningSummaryTextDeltaEvent extends Schema.Class<ResponseReasoningSummaryTextDeltaEvent>(\n  \"@effect/ai-openai/ResponseReasoningSummaryTextDeltaEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.reasoning_summary_text.delta\"`.\n   */\n  type: Schema.Literal(\"response.reasoning_summary_text.delta\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the summary part within the reasoning summary.\n   */\n  summary_index: Schema.Int,\n  /**\n   * The index of the output item this summary text delta is associated with.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the item this summary text delta is associated with.\n   */\n  item_id: Schema.String,\n  /**\n   * The text delta that was added to the summary.\n   */\n  delta: Schema.String\n}) {}\n\n/**\n * Emitted when a reasoning summary text is completed.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseReasoningSummaryTextDoneEvent extends Schema.Class<ResponseReasoningSummaryTextDoneEvent>(\n  \"@effect/ai-openai/ResponseReasoningSummaryTextDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.reasoning_summary_text.done\"`.\n   */\n  type: Schema.Literal(\"response.reasoning_summary_text.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the summary part within the reasoning summary.\n   */\n  summary_index: Schema.Int,\n  /**\n   * The index of the output item this summary text is associated with.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the item this summary text is associated with.\n   */\n  item_id: Schema.String,\n  /**\n   * The full text of the completed reasoning summary.\n   */\n  text: Schema.String\n}) {}\n\n/**\n * Emitted when a delta is added to a reasoning text.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseReasoningTextDeltaEvent extends Schema.Class<ResponseReasoningTextDeltaEvent>(\n  \"@effect/ai-openai/ResponseReasoningTextDeltaEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.reasoning_text.delta\"`.\n   */\n  type: Schema.Literal(\"response.reasoning_text.delta\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the reasoning content part this delta is associated with.\n   */\n  content_index: Schema.Int,\n  /**\n   * The index of the output item this reasoning text delta is associated with.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the item this reasoning text delta is associated with.\n   */\n  item_id: Schema.String,\n  /**\n   * The text delta that was added to the reasoning content.\n   */\n  delta: Schema.String\n}) {}\n\n/**\n * Emitted when a reasoning text is completed.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseReasoningTextDoneEvent extends Schema.Class<ResponseReasoningTextDoneEvent>(\n  \"@effect/ai-openai/ResponseReasoningPartDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.reasoning_text.done\"`.\n   */\n  type: Schema.Literal(\"response.reasoning_text.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the reasoning content part.\n   */\n  content_index: Schema.Int,\n  /**\n   * The index of the output item this reasoning text is associated with.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the item this reasoning text is associated with.\n   */\n  item_id: Schema.String,\n  /**\n   * The full text of the completed reasoning content.\n   */\n  text: Schema.String\n}) {}\n\n/**\n * Emitted when an image generation tool call is in progress.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseImageGenerationCallInProgressEvent\n  extends Schema.Class<ResponseImageGenerationCallInProgressEvent>(\n    \"@effect/ai-openai/ResponseImageGenerationCallInProgressEvent\"\n  )({\n    /**\n     * The type of the event. Always `\"response.image_generation_call.in_progress\"`.\n     */\n    type: Schema.Literal(\"response.image_generation_call.in_progress\"),\n    /**\n     * The sequence number for this event.\n     */\n    sequence_number: Schema.Int,\n    /**\n     * The index of the output item in the response's output array.\n     */\n    output_index: Schema.Int,\n    /**\n     * The unique identifier of the image generation item being processed.\n     */\n    item_id: Schema.String\n  })\n{}\n\n/**\n * Emitted when an image generation tool call is actively generating an image\n * (intermediate state).\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseImageGenerationCallGeneratingEvent\n  extends Schema.Class<ResponseImageGenerationCallGeneratingEvent>(\n    \"@effect/ai-openai/ResponseImageGenerationCallGeneratingEvent\"\n  )({\n    /**\n     * The type of the event. Always `\"response.image_generation_call.generating\"`.\n     */\n    type: Schema.Literal(\"response.image_generation_call.generating\"),\n    /**\n     * The sequence number for this event.\n     */\n    sequence_number: Schema.Int,\n    /**\n     * The index of the output item in the response's output array.\n     */\n    output_index: Schema.Int,\n    /**\n     * The unique identifier of the image generation item being processed.\n     */\n    item_id: Schema.String\n  })\n{}\n\n/**\n * Emitted when a partial image is available during image generation streaming.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseImageGenerationCallPartialImageEvent\n  extends Schema.Class<ResponseImageGenerationCallPartialImageEvent>(\n    \"@effect/ai-openai/ResponseImageGenerationCallPartialImageEvent\"\n  )({\n    /**\n     * The type of the event. Always `\"response.image_generation_call.partial_image\"`.\n     */\n    type: Schema.Literal(\"response.image_generation_call.partial_image\"),\n    /**\n     * The sequence number for this event.\n     */\n    sequence_number: Schema.Int,\n    /**\n     * The index of the output item in the response's output array.\n     */\n    output_index: Schema.Int,\n    /**\n     * The unique identifier of the image generation item being processed.\n     */\n    item_id: Schema.String,\n    /**\n     * `0`-based index for the partial image (backend is `1`-based, but this is\n     * `0`-based for the user).\n     */\n    partial_image_index: Schema.Int,\n    /**\n     * Base64-encoded partial image data, suitable for rendering as an image.\n     */\n    partial_image_b64: Schema.String\n  })\n{}\n\n/**\n * Emitted when an image generation tool call has completed and the final image\n * is available.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseImageGenerationCallCompletedEvent extends Schema.Class<ResponseImageGenerationCallCompletedEvent>(\n  \"@effect/ai-openai/ResponseImageGenerationCallCompletedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.image_generation_call.completed\"`.\n   */\n  type: Schema.Literal(\"response.image_generation_call.completed\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item in the response's output array.\n   */\n  output_index: Schema.Int,\n  /**\n   * The unique identifier of the image generation item being processed.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when there is a delta (partial update) to the arguments of an MCP\n * tool call.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseMcpCallArgumentsDeltaEvent extends Schema.Class<ResponseMcpCallArgumentsDeltaEvent>(\n  \"@effect/ai-openai/ResponseMcpCallArgumentsDeltaEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.mcp_call_arguments.delta\"`.\n   */\n  type: Schema.Literal(\"response.mcp_call_arguments.delta\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item in the response's output array.\n   */\n  output_index: Schema.Int,\n  /**\n   * The unique identifier of the MCP tool call item being processed.\n   */\n  item_id: Schema.String,\n  /**\n   * A JSON string containing the partial update to the arguments for the MCP\n   * tool call.\n   */\n  delta: Schema.String\n}) {}\n\n/**\n * Emitted when the arguments for an MCP tool call are finalized.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseMcpCallArgumentsDoneEvent extends Schema.Class<ResponseMcpCallArgumentsDoneEvent>(\n  \"@effect/ai-openai/ResponseMcpCallArgumentsDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.mcp_call_arguments.done\"`.\n   */\n  type: Schema.Literal(\"response.mcp_call_arguments.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item in the response's output array.\n   */\n  output_index: Schema.Int,\n  /**\n   * The unique identifier of the MCP tool call item being processed.\n   */\n  item_id: Schema.String,\n  /**\n   * A JSON string containing the finalized arguments for the MCP tool call.\n   */\n  arguments: Schema.String\n}) {}\n\n/**\n * Emitted when an MCP tool call is in progress.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseMcpCallInProgressEvent extends Schema.Class<ResponseMcpCallInProgressEvent>(\n  \"@effect/ai-openai/ResponseMcpCallInProgressEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.mcp_call.in_progress\"`.\n   */\n  type: Schema.Literal(\"response.mcp_call.in_progress\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item in the response's output array.\n   */\n  output_index: Schema.Int,\n  /**\n   * The unique identifier of the MCP tool call item being processed.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when an MCP tool call has completed successfully.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseMcpCallCompletedEvent extends Schema.Class<ResponseMcpCallCompletedEvent>(\n  \"@effect/ai-openai/ResponseMcpCallCompletedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.mcp_call.completed\"`.\n   */\n  type: Schema.Literal(\"response.mcp_call.completed\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that completed.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the MCP tool call item that completed.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when an MCP tool call has failed.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseMcpCallFailedEvent extends Schema.Class<ResponseMcpCallFailedEvent>(\n  \"@effect/ai-openai/ResponseMcpCallFailedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.mcp_call.failed\"`.\n   */\n  type: Schema.Literal(\"response.mcp_call.failed\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that failed.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the MCP tool call item that failed.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when the system is in the process of retrieving the list of available\n * MCP tools.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseMcpListToolsInProgressEvent extends Schema.Class<ResponseMcpListToolsInProgressEvent>(\n  \"@effect/ai-openai/ResponseMcpListToolsInProgressEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.mcp_list_tools.in_progress\"`.\n   */\n  type: Schema.Literal(\"response.mcp_list_tools.in_progress\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that is being processed.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the MCP tool call item that is being processed.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when the list of available MCP tools has been successfully retrieved.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseMcpListToolsCompletedEvent extends Schema.Class<ResponseMcpListToolsCompletedEvent>(\n  \"@effect/ai-openai/ResponseMcpListToolsCompletedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.mcp_list_tools.completed\"`.\n   */\n  type: Schema.Literal(\"response.mcp_list_tools.completed\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that was processed.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the MCP tool call item that produced this output.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when the attempt to list available MCP tools has failed.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseMcpListToolsFailedEvent extends Schema.Class<ResponseMcpListToolsFailedEvent>(\n  \"@effect/ai-openai/ResponseMcpListToolsFailedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.mcp_list_tools.failed\"`.\n   */\n  type: Schema.Literal(\"response.mcp_list_tools.failed\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item that failed.\n   */\n  output_index: Schema.Int,\n  /**\n   * The ID of the MCP tool call item that failed.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when a code interpreter call is in progress.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseCodeInterpreterCallInProgressEvent\n  extends Schema.Class<ResponseCodeInterpreterCallInProgressEvent>(\n    \"@effect/ai-openai/ResponseCodeInterpreterCallInProgressEvent\"\n  )({\n    /**\n     * The type of the event. Always `\"response.code_interpreter_call.in_progress\"`.\n     */\n    type: Schema.Literal(\"response.code_interpreter_call.in_progress\"),\n    /**\n     * The sequence number for this event.\n     */\n    sequence_number: Schema.Int,\n    /**\n     * The index of the output item in the response for which the code interpreter\n     * call is in progress.\n     */\n    output_index: Schema.Int,\n    /**\n     * The unique identifier of the code interpreter tool call item.\n     */\n    item_id: Schema.String\n  })\n{}\n\n/**\n * Emitted when the code interpreter is actively interpreting the code snippet.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseCodeInterpreterCallInterpretingEvent\n  extends Schema.Class<ResponseCodeInterpreterCallInterpretingEvent>(\n    \"@effect/ai-openai/ResponseCodeInterpreterCallInterpretingEvent\"\n  )({\n    /**\n     * The type of the event. Always `\"response.code_interpreter_call.interpreting\"`.\n     */\n    type: Schema.Literal(\"response.code_interpreter_call.interpreting\"),\n    /**\n     * The sequence number for this event.\n     */\n    sequence_number: Schema.Int,\n    /**\n     * The index of the output item in the response for which the code\n     * interpreter is interpreting code.\n     */\n    output_index: Schema.Int,\n    /**\n     * The unique identifier of the code interpreter tool call item.\n     */\n    item_id: Schema.String\n  })\n{}\n\n/**\n * Emitted when the code interpreter call is completed.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseCodeInterpreterCallCompletedEvent extends Schema.Class<ResponseCodeInterpreterCallCompletedEvent>(\n  \"@effect/ai-openai/ResponseCodeInterpreterCallCompletedEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.code_interpreter_call.completed\"`.\n   */\n  type: Schema.Literal(\"response.code_interpreter_call.completed\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item in the response for which the code interpreter\n   * call is completed.\n   */\n  output_index: Schema.Int,\n  /**\n   * The unique identifier of the code interpreter tool call item.\n   */\n  item_id: Schema.String\n}) {}\n\n/**\n * Emitted when a partial code snippet is streamed by the code interpreter.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseCodeInterpreterCallCodeDeltaEvent extends Schema.Class<ResponseCodeInterpreterCallCodeDeltaEvent>(\n  \"@effect/ai-openai/ResponseCodeInterpreterCallCodeDeltaEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.code_interpreter_call_code.delta\"`.\n   */\n  type: Schema.Literal(\"response.code_interpreter_call_code.delta\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item in the response for which the code is being\n   * streamed.\n   */\n  output_index: Schema.Int,\n  /**\n   * The unique identifier of the code interpreter tool call item.\n   */\n  item_id: Schema.String,\n  /**\n   * The partial code snippet being streamed by the code interpreter.\n   */\n  delta: Schema.String\n}) {}\n\n/**\n * Emitted when the code snippet is finalized by the code interpreter.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseCodeInterpreterCallCodeDoneEvent extends Schema.Class<ResponseCodeInterpreterCallCodeDoneEvent>(\n  \"@effect/ai-openai/ResponseCodeInterpreterCallCodeDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.code_interpreter_call_code.done\"`.\n   */\n  type: Schema.Literal(\"response.code_interpreter_call_code.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output item in the response for which the code is finalized.\n   */\n  output_index: Schema.Int,\n  /**\n   * The unique identifier of the code interpreter tool call item.\n   */\n  item_id: Schema.String,\n  /**\n   * The final code snippet output by the code interpreter.\n   */\n  code: Schema.String\n}) {}\n\n/**\n * Event representing a delta (partial update) to the input of a custom tool call.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseCustomToolCallInputDeltaEvent extends Schema.Class<ResponseCustomToolCallInputDeltaEvent>(\n  \"@effect/ai-openai/ResponseCustomToolCallInputDeltaEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.custom_tool_call_input.delta\"`.\n   */\n  type: Schema.Literal(\"response.custom_tool_call_input.delta\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output this delta applies to.\n   */\n  output_index: Schema.Int,\n  /**\n   * Unique identifier for the API item associated with this event.\n   */\n  item_id: Schema.String,\n  /**\n   * The incremental input data (delta) for the custom tool call.\n   */\n  delta: Schema.String\n}) {}\n\n/**\n * Event indicating that input for a custom tool call is complete.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseCustomToolCallInputDoneEvent extends Schema.Class<ResponseCustomToolCallInputDoneEvent>(\n  \"@effect/ai-openai/ResponseCustomToolCallInputDoneEvent\"\n)({\n  /**\n   * The type of the event. Always `\"response.custom_tool_call_input.done\"`.\n   */\n  type: Schema.Literal(\"response.custom_tool_call_input.done\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The index of the output this event applies to.\n   */\n  output_index: Schema.Int,\n  /**\n   * Unique identifier for the API item associated with this event.\n   */\n  item_id: Schema.String,\n  /**\n   * The complete input data for the custom tool call.\n   */\n  input: Schema.String\n}) {}\n\n/**\n * Emitted when an error occurs.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport class ResponseErrorEvent extends Schema.Class<ResponseErrorEvent>(\n  \"@effect/ai-openai/ResponseErrorEvent\"\n)({\n  /**\n   * The type of the event. Always `\"error\"`.\n   */\n  type: Schema.Literal(\"error\"),\n  /**\n   * The sequence number for this event.\n   */\n  sequence_number: Schema.Int,\n  /**\n   * The error code.\n   */\n  code: Schema.optional(Schema.NullOr(Schema.String)),\n  /**\n   * The error message.\n   */\n  message: Schema.String,\n  /**\n   * The error parameter.\n   */\n  param: Schema.optional(Schema.NullOr(Schema.String))\n}) {}\n\n/**\n * Represents the events that can be emitted during a streaming response.\n *\n * @since 1.0.0\n * @category Schemas\n */\nexport const ResponseStreamEvent: Schema.Union<[\n  typeof ResponseCreatedEvent,\n  typeof ResponseQueuedEvent,\n  typeof ResponseInProgressEvent,\n  typeof ResponseCompletedEvent,\n  typeof ResponseIncompleteEvent,\n  typeof ResponseFailedEvent,\n  typeof ResponseOutputItemAddedEvent,\n  typeof ResponseOutputItemDoneEvent,\n  typeof ResponseContentPartAddedEvent,\n  typeof ResponseContentPartDoneEvent,\n  typeof ResponseOutputTextDeltaEvent,\n  typeof ResponseOutputTextDoneEvent,\n  typeof ResponseOutputTextAnnotationAddedEvent,\n  typeof ResponseRefusalDeltaEvent,\n  typeof ResponseRefusalDoneEvent,\n  typeof ResponseFunctionCallArgumentsDeltaEvent,\n  typeof ResponseFunctionCallArgumentsDoneEvent,\n  typeof ResponseFileSearchCallInProgressEvent,\n  typeof ResponseFileSearchCallSearchingEvent,\n  typeof ResponseFileSearchCallCompletedEvent,\n  typeof ResponseWebSearchCallInProgressEvent,\n  typeof ResponseWebSearchCallSearchingEvent,\n  typeof ResponseWebSearchCallCompletedEvent,\n  typeof ResponseReasoningSummaryPartAddedEvent,\n  typeof ResponseReasoningSummaryPartDoneEvent,\n  typeof ResponseReasoningSummaryTextDeltaEvent,\n  typeof ResponseReasoningSummaryTextDoneEvent,\n  typeof ResponseReasoningTextDeltaEvent,\n  typeof ResponseReasoningTextDoneEvent,\n  typeof ResponseImageGenerationCallInProgressEvent,\n  typeof ResponseImageGenerationCallGeneratingEvent,\n  typeof ResponseImageGenerationCallPartialImageEvent,\n  typeof ResponseImageGenerationCallCompletedEvent,\n  typeof ResponseMcpCallArgumentsDeltaEvent,\n  typeof ResponseMcpCallArgumentsDoneEvent,\n  typeof ResponseMcpCallInProgressEvent,\n  typeof ResponseMcpCallCompletedEvent,\n  typeof ResponseMcpCallFailedEvent,\n  typeof ResponseMcpListToolsInProgressEvent,\n  typeof ResponseMcpListToolsCompletedEvent,\n  typeof ResponseMcpListToolsFailedEvent,\n  typeof ResponseCodeInterpreterCallInProgressEvent,\n  typeof ResponseCodeInterpreterCallInterpretingEvent,\n  typeof ResponseCodeInterpreterCallCompletedEvent,\n  typeof ResponseCodeInterpreterCallCodeDeltaEvent,\n  typeof ResponseCodeInterpreterCallCodeDoneEvent,\n  typeof ResponseCustomToolCallInputDeltaEvent,\n  typeof ResponseCustomToolCallInputDoneEvent,\n  typeof ResponseErrorEvent\n]> = Schema.Union(\n  ResponseCreatedEvent,\n  ResponseQueuedEvent,\n  ResponseInProgressEvent,\n  ResponseCompletedEvent,\n  ResponseIncompleteEvent,\n  ResponseFailedEvent,\n  ResponseOutputItemAddedEvent,\n  ResponseOutputItemDoneEvent,\n  ResponseContentPartAddedEvent,\n  ResponseContentPartDoneEvent,\n  ResponseOutputTextDeltaEvent,\n  ResponseOutputTextDoneEvent,\n  ResponseOutputTextAnnotationAddedEvent,\n  ResponseRefusalDeltaEvent,\n  ResponseRefusalDoneEvent,\n  ResponseFunctionCallArgumentsDeltaEvent,\n  ResponseFunctionCallArgumentsDoneEvent,\n  ResponseFileSearchCallInProgressEvent,\n  ResponseFileSearchCallSearchingEvent,\n  ResponseFileSearchCallCompletedEvent,\n  ResponseWebSearchCallInProgressEvent,\n  ResponseWebSearchCallSearchingEvent,\n  ResponseWebSearchCallCompletedEvent,\n  ResponseReasoningSummaryPartAddedEvent,\n  ResponseReasoningSummaryPartDoneEvent,\n  ResponseReasoningSummaryTextDeltaEvent,\n  ResponseReasoningSummaryTextDoneEvent,\n  ResponseReasoningTextDeltaEvent,\n  ResponseReasoningTextDoneEvent,\n  ResponseImageGenerationCallInProgressEvent,\n  ResponseImageGenerationCallGeneratingEvent,\n  ResponseImageGenerationCallPartialImageEvent,\n  ResponseImageGenerationCallCompletedEvent,\n  ResponseMcpCallArgumentsDeltaEvent,\n  ResponseMcpCallArgumentsDoneEvent,\n  ResponseMcpCallInProgressEvent,\n  ResponseMcpCallCompletedEvent,\n  ResponseMcpCallFailedEvent,\n  ResponseMcpListToolsInProgressEvent,\n  ResponseMcpListToolsCompletedEvent,\n  ResponseMcpListToolsFailedEvent,\n  ResponseCodeInterpreterCallInProgressEvent,\n  ResponseCodeInterpreterCallInterpretingEvent,\n  ResponseCodeInterpreterCallCompletedEvent,\n  ResponseCodeInterpreterCallCodeDeltaEvent,\n  ResponseCodeInterpreterCallCodeDoneEvent,\n  ResponseCustomToolCallInputDeltaEvent,\n  ResponseCustomToolCallInputDoneEvent,\n  ResponseErrorEvent\n)\n\n/**\n * Represents the events that can be emitted during a streaming response.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type ResponseStreamEvent = typeof ResponseStreamEvent.Type\n"
  },
  {
    "path": "packages/ai/openai/src/OpenAiConfig.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { HttpClient } from \"@effect/platform/HttpClient\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class OpenAiConfig extends Context.Tag(\"@effect/ai-openai/OpenAiConfig\")<\n  OpenAiConfig,\n  OpenAiConfig.Service\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<typeof OpenAiConfig.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(OpenAiConfig.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace OpenAiConfig {\n  /**\n   * @since 1.0.\n   * @category Models\n   */\n  export interface Service {\n    readonly transformClient?: (client: HttpClient) => HttpClient\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport const withClientTransform: {\n  (transform: (client: HttpClient) => HttpClient): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient): Effect.Effect<A, E, R>\n} = dual<\n  (transform: (client: HttpClient) => HttpClient) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient) => Effect.Effect<A, E, R>\n>(\n  2,\n  (self, transformClient) =>\n    Effect.flatMap(\n      OpenAiConfig.getOrUndefined,\n      (config) => Effect.provideService(self, OpenAiConfig, { ...config, transformClient })\n    )\n)\n"
  },
  {
    "path": "packages/ai/openai/src/OpenAiEmbeddingModel.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as EmbeddingModel from \"@effect/ai/EmbeddingModel\"\nimport * as AiModel from \"@effect/ai/Model\"\nimport * as Context from \"effect/Context\"\nimport type * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport type { Simplify } from \"effect/Types\"\nimport type * as Generated from \"./Generated.js\"\nimport * as OpenAiClient from \"./OpenAiClient.js\"\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type Model = typeof Generated.CreateEmbeddingRequestModelEnum.Encoded\n\n// =============================================================================\n// Configuration\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class Config extends Context.Tag(\"@effect/ai-openai/OpenAiEmbeddingModel/Config\")<\n  Config,\n  Config.Service\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<Config.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(Config.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Config {\n  /**\n   * @since 1.0.\n   * @category Configuration\n   */\n  export interface Service extends\n    Simplify<\n      Partial<\n        Omit<\n          typeof Generated.CreateEmbeddingRequest.Encoded,\n          \"input\"\n        >\n      >\n    >\n  {}\n\n  /**\n   * @since 1.0.\n   * @category Configuration\n   */\n  export interface Batched extends Omit<Config.Service, \"model\"> {\n    readonly maxBatchSize?: number\n    readonly cache?: {\n      readonly capacity: number\n      readonly timeToLive: Duration.DurationInput\n    }\n  }\n\n  /**\n   * @since 1.0.\n   * @category Configuration\n   */\n  export interface DataLoader extends Omit<Config.Service, \"model\"> {\n    readonly window: Duration.DurationInput\n    readonly maxBatchSize?: number\n  }\n}\n\n// =============================================================================\n// OpenAi Embedding Model\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport const model = (\n  model: (string & {}) | Model,\n  { mode, ...config }: Simplify<\n    (\n      | ({ readonly mode: \"batched\" } & Config.Batched)\n      | ({ readonly mode: \"data-loader\" } & Config.DataLoader)\n    )\n  >\n): AiModel.Model<\"openai\", EmbeddingModel.EmbeddingModel, OpenAiClient.OpenAiClient> => {\n  return AiModel.make(\n    \"openai\",\n    mode === \"batched\"\n      ? layerBatched({ model, config: config as Config.Batched })\n      : layerDataLoader({ model, config: config as Config.DataLoader })\n  )\n}\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nconst makeBatched = Effect.fnUntraced(function*(options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Config.Batched\n}) {\n  const client = yield* OpenAiClient.OpenAiClient\n\n  const { config = {}, model } = options\n  const { cache, maxBatchSize = 2048, ...globalConfig } = config\n\n  const makeRequest = Effect.fnUntraced(\n    function*(input: ReadonlyArray<string>) {\n      const context = yield* Effect.context<never>()\n      const requestConfig = context.unsafeMap.get(Config.key)\n      const request: typeof Generated.CreateEmbeddingRequest.Encoded = {\n        model,\n        ...globalConfig,\n        ...requestConfig,\n        input\n      }\n      return request\n    }\n  )\n\n  return yield* EmbeddingModel.make({\n    cache,\n    maxBatchSize,\n    embedMany: Effect.fnUntraced(function*(input) {\n      const request = yield* makeRequest(input)\n      const response = yield* client.createEmbedding(request)\n      return makeResults(response)\n    })\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const makeDataLoader = Effect.fnUntraced(function*(options: {\n  readonly model: (string & {}) | Model\n  readonly config: Config.DataLoader\n}) {\n  const client = yield* OpenAiClient.OpenAiClient\n  const { config, model } = options\n  const { maxBatchSize = 2048, window, ...globalConfig } = config\n\n  const makeRequest = Effect.fnUntraced(\n    function*(input: ReadonlyArray<string>) {\n      const context = yield* Effect.context<never>()\n      const requestConfig = context.unsafeMap.get(Config.key)\n      const request: typeof Generated.CreateEmbeddingRequest.Encoded = {\n        model,\n        ...globalConfig,\n        ...requestConfig,\n        input\n      }\n      return request\n    }\n  )\n\n  return yield* EmbeddingModel.makeDataLoader({\n    window,\n    maxBatchSize,\n    embedMany: Effect.fnUntraced(function*(input) {\n      const request = yield* makeRequest(input)\n      const response = yield* client.createEmbedding(request)\n      return makeResults(response)\n    })\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerBatched = (options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Config.Batched\n}): Layer.Layer<EmbeddingModel.EmbeddingModel, never, OpenAiClient.OpenAiClient> =>\n  Layer.effect(EmbeddingModel.EmbeddingModel, makeBatched(options))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerDataLoader = (options: {\n  readonly model: (string & {}) | Model\n  readonly config: Config.DataLoader\n}): Layer.Layer<EmbeddingModel.EmbeddingModel, never, OpenAiClient.OpenAiClient> =>\n  Layer.scoped(EmbeddingModel.EmbeddingModel, makeDataLoader(options))\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport const withConfigOverride: {\n  (config: Config.Service): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, config: Config.Service): Effect.Effect<A, E, R>\n} = dual<\n  (config: Config.Service) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, config: Config.Service) => Effect.Effect<A, E, R>\n>(2, (self, overrides) =>\n  Effect.flatMap(\n    Config.getOrUndefined,\n    (config) => Effect.provideService(self, Config, { ...config, ...overrides })\n  ))\n\n// =============================================================================\n// Response Conversion\n// =============================================================================\n\nconst makeResults = (response: Generated.CreateEmbeddingResponse): Array<EmbeddingModel.Result> =>\n  response.data.map(({ embedding, index }) => ({\n    embeddings: embedding as Array<number>,\n    index\n  }))\n"
  },
  {
    "path": "packages/ai/openai/src/OpenAiLanguageModel.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AiError from \"@effect/ai/AiError\"\nimport * as IdGenerator from \"@effect/ai/IdGenerator\"\nimport * as LanguageModel from \"@effect/ai/LanguageModel\"\nimport * as AiModel from \"@effect/ai/Model\"\nimport type * as Prompt from \"@effect/ai/Prompt\"\nimport type * as Response from \"@effect/ai/Response\"\nimport type * as Tokenizer from \"@effect/ai/Tokenizer\"\nimport * as Tool from \"@effect/ai/Tool\"\nimport * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport { dual } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Stream from \"effect/Stream\"\nimport type { Span } from \"effect/Tracer\"\nimport type { DeepMutable, Mutable, Simplify } from \"effect/Types\"\nimport type * as Generated from \"./Generated.js\"\nimport * as InternalUtilities from \"./internal/utilities.js\"\nimport type { ResponseStreamEvent } from \"./OpenAiClient.js\"\nimport { OpenAiClient } from \"./OpenAiClient.js\"\nimport { addGenAIAnnotations } from \"./OpenAiTelemetry.js\"\nimport * as OpenAiTokenizer from \"./OpenAiTokenizer.js\"\nimport * as OpenAiTool from \"./OpenAiTool.js\"\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type Model = typeof Generated.ChatModel.Encoded | typeof Generated.ModelIdsResponsesEnum.Encoded\n\n// =============================================================================\n// Configuration\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class Config extends Context.Tag(\"@effect/ai-openai/OpenAiLanguageModel/Config\")<\n  Config,\n  Config.Service\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<Config.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(Config.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Config {\n  /**\n   * @since 1.0.0\n   * @category Models\n   */\n  export interface Service extends\n    Simplify<\n      Partial<\n        Omit<\n          typeof Generated.CreateResponse.Encoded,\n          \"input\" | \"tools\" | \"tool_choice\" | \"stream\" | \"text\"\n        >\n      >\n    >\n  {\n    /**\n     * File ID prefixes used to identify file IDs in Responses API.\n     * When undefined, all file data is treated as base64 content.\n     *\n     * Examples:\n     * - OpenAI: ['file-'] for IDs like 'file-abc123'\n     * - Azure OpenAI: ['assistant-'] for IDs like 'assistant-abc123'\n     */\n    readonly fileIdPrefixes?: ReadonlyArray<string>\n    /**\n     * Configuration options for a text response from the model.\n     */\n    readonly text?: {\n      /**\n       * Constrains the verbosity of the model's response. Lower values will\n       * result in more concise responses, while higher values will result in\n       * more verbose responses.\n       *\n       * Defaults to `\"medium\"`.\n       */\n      readonly verbosity?: \"low\" | \"medium\" | \"high\"\n    }\n  }\n}\n\n// =============================================================================\n// OpenAI Provider Options / Metadata\n// =============================================================================\n\ndeclare module \"@effect/ai/Prompt\" {\n  export interface FilePartOptions extends ProviderOptions {\n    readonly openai?: {\n      /**\n       * The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`.\n       */\n      readonly imageDetail?: typeof Generated.ImageDetail.Encoded | undefined\n    } | undefined\n  }\n\n  export interface ReasoningPartOptions extends ProviderOptions {\n    readonly openai?: {\n      /**\n       * The ID of the item to reference.\n       */\n      readonly itemId?: string | undefined\n      /**\n       * The encrypted content of the reasoning item - populated when a response\n       * is generated with `reasoning.encrypted_content` in the `include`\n       * parameter.\n       */\n      readonly encryptedContent?: string | undefined\n    } | undefined\n  }\n\n  export interface ToolCallPartOptions extends ProviderOptions {\n    readonly openai?: {\n      /**\n       * The ID of the item to reference.\n       */\n      readonly itemId?: string | undefined\n    } | undefined\n  }\n\n  export interface TextPartOptions extends ProviderOptions {\n    readonly openai?: {\n      /**\n       * The ID of the item to reference.\n       */\n      readonly itemId?: string | undefined\n    } | undefined\n  }\n}\n\ndeclare module \"@effect/ai/Response\" {\n  export interface TextPartMetadata extends ProviderMetadata {\n    readonly openai?: {\n      readonly itemId?: string | undefined\n      /**\n       * If the model emits a refusal content part, the refusal explanation\n       * from the model will be contained in the metadata of an empty text\n       * part.\n       */\n      readonly refusal?: string | undefined\n    } | undefined\n  }\n\n  export interface TextStartPartMetadata extends ProviderMetadata {\n    readonly openai?: {\n      readonly itemId?: string | undefined\n    } | undefined\n  }\n\n  export interface ReasoningPartMetadata extends ProviderMetadata {\n    readonly openai?: {\n      readonly itemId?: string | undefined\n      readonly encryptedContent?: string | undefined\n    } | undefined\n  }\n\n  export interface ReasoningStartPartMetadata extends ProviderMetadata {\n    readonly openai?: {\n      readonly itemId?: string | undefined\n      readonly encryptedContent?: string | undefined\n    } | undefined\n  }\n\n  export interface ReasoningDeltaPartMetadata extends ProviderMetadata {\n    readonly openai?: {\n      readonly itemId?: string | undefined\n    } | undefined\n  }\n\n  export interface ReasoningEndPartMetadata extends ProviderMetadata {\n    readonly openai?: {\n      readonly itemId?: string | undefined\n      readonly encryptedContent?: string | undefined\n    } | undefined\n  }\n\n  export interface ToolCallPartMetadata extends ProviderMetadata {\n    readonly openai?: {\n      readonly itemId?: string | undefined\n    } | undefined\n  }\n\n  export interface DocumentSourcePartMetadata extends ProviderMetadata {\n    readonly openai?: {\n      readonly type: \"file_citation\"\n      /**\n       * The index of the file in the list of files.\n       */\n      readonly index: number\n    } | undefined\n  }\n\n  export interface UrlSourcePartMetadata extends ProviderMetadata {\n    readonly openai?: {\n      readonly type: \"url_citation\"\n      /**\n       * The index of the first character of the URL citation in the message.\n       */\n      readonly startIndex: number\n      /**\n       * The index of the last character of the URL citation in the message.\n       */\n      readonly endIndex: number\n    } | undefined\n  }\n\n  export interface FinishPartMetadata extends ProviderMetadata {\n    readonly openai?: {\n      readonly serviceTier?: \"default\" | \"auto\" | \"flex\" | \"scale\" | \"priority\" | undefined\n    } | undefined\n  }\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace ProviderMetadata {\n  /**\n   * @since 1.0.0\n   * @category Provider Metadata\n   */\n  export interface Service {\n    \"source\": {} | {}\n  }\n}\n\n// =============================================================================\n// OpenAI Language Model\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Ai Models\n */\nexport const model = (\n  model: (string & {}) | Model,\n  config?: Omit<Config.Service, \"model\">\n): AiModel.Model<\"openai\", LanguageModel.LanguageModel, OpenAiClient> =>\n  AiModel.make(\"openai\", layer({ model, config }))\n\n/**\n * @since 1.0.0\n * @category Ai Models\n */\nexport const modelWithTokenizer = (\n  model: (string & {}) | Model,\n  config?: Omit<Config.Service, \"model\">\n): AiModel.Model<\"openai\", LanguageModel.LanguageModel | Tokenizer.Tokenizer, OpenAiClient> =>\n  AiModel.make(\"openai\", layerWithTokenizer({ model, config }))\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.fnUntraced(function*(options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Omit<Config.Service, \"model\">\n}) {\n  const client = yield* OpenAiClient\n\n  const makeRequest: (providerOptions: LanguageModel.ProviderOptions) => Effect.Effect<\n    typeof Generated.CreateResponse.Encoded,\n    AiError.AiError\n  > = Effect.fnUntraced(\n    function*(providerOptions) {\n      const context = yield* Effect.context<never>()\n      const config = { model: options.model, ...options.config, ...context.unsafeMap.get(Config.key) }\n      const messages = yield* prepareMessages(providerOptions, config)\n      const { toolChoice, tools } = yield* prepareTools(providerOptions)\n      const include = prepareInclude(providerOptions, config)\n      const responseFormat = prepareResponseFormat(providerOptions)\n      const verbosity = config.text?.verbosity\n      const request: typeof Generated.CreateResponse.Encoded = {\n        ...config,\n        input: messages,\n        include,\n        text: { format: responseFormat, verbosity },\n        tools,\n        tool_choice: toolChoice\n      }\n      return request\n    }\n  )\n\n  return yield* LanguageModel.make({\n    generateText: Effect.fnUntraced(\n      function*(options) {\n        const request = yield* makeRequest(options)\n        annotateRequest(options.span, request)\n        const rawResponse = yield* client.createResponse(request)\n        annotateResponse(options.span, rawResponse)\n        return yield* makeResponse(rawResponse, options)\n      }\n    ),\n    streamText: Effect.fnUntraced(\n      function*(options) {\n        const request = yield* makeRequest(options)\n        annotateRequest(options.span, request)\n        return client.createResponseStream(request)\n      },\n      (effect, options) =>\n        effect.pipe(\n          Effect.flatMap((stream) => makeStreamResponse(stream, options)),\n          Stream.unwrap,\n          Stream.map((response) => {\n            annotateStreamResponse(options.span, response)\n            return response\n          })\n        )\n    )\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Omit<Config.Service, \"model\">\n}): Layer.Layer<LanguageModel.LanguageModel, never, OpenAiClient> =>\n  Layer.effect(LanguageModel.LanguageModel, make({ model: options.model, config: options.config }))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerWithTokenizer = (options: {\n  readonly model: (string & {}) | Model\n  readonly config?: Omit<Config.Service, \"model\">\n}): Layer.Layer<LanguageModel.LanguageModel | Tokenizer.Tokenizer, never, OpenAiClient> =>\n  Layer.merge(layer(options), OpenAiTokenizer.layer(options))\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport const withConfigOverride: {\n  (overrides: Config.Service): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, overrides: Config.Service): Effect.Effect<A, E, R>\n} = dual<\n  (overrides: Config.Service) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, overrides: Config.Service) => Effect.Effect<A, E, R>\n>(2, (self, overrides) =>\n  Effect.flatMap(\n    Config.getOrUndefined,\n    (config) => Effect.provideService(self, Config, { ...config, ...overrides })\n  ))\n\n// =============================================================================\n// Prompt Conversion\n// =============================================================================\n\nconst getSystemMessageMode = (model: string): \"system\" | \"developer\" =>\n  model.startsWith(\"o\") ||\n    model.startsWith(\"gpt-5\") ||\n    model.startsWith(\"codex-\") ||\n    model.startsWith(\"computer-use\")\n    ? \"developer\"\n    : \"system\"\n\nconst prepareMessages: (\n  options: LanguageModel.ProviderOptions,\n  config: Config.Service\n) => Effect.Effect<\n  ReadonlyArray<typeof Generated.InputItem.Encoded>,\n  AiError.AiError\n> = Effect.fnUntraced(function*(options, config) {\n  const messages: Array<typeof Generated.InputItem.Encoded> = []\n\n  for (const message of options.prompt.content) {\n    switch (message.role) {\n      case \"system\": {\n        messages.push({\n          role: getSystemMessageMode(config.model!),\n          content: message.content\n        })\n        break\n      }\n\n      case \"user\": {\n        const content: Array<typeof Generated.InputContent.Encoded> = []\n\n        for (let index = 0; index < message.content.length; index++) {\n          const part = message.content[index]\n\n          switch (part.type) {\n            case \"text\": {\n              content.push({ type: \"input_text\", text: part.text })\n              break\n            }\n\n            case \"file\": {\n              if (part.mediaType.startsWith(\"image/\")) {\n                const detail = getImageDetail(part)\n                const mediaType = part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType\n\n                if (typeof part.data === \"string\" && isFileId(part.data, config)) {\n                  content.push({ type: \"input_image\", file_id: part.data, detail })\n                }\n\n                if (part.data instanceof URL) {\n                  content.push({ type: \"input_image\", image_url: part.data.toString(), detail })\n                }\n\n                if (part.data instanceof Uint8Array) {\n                  const base64 = Encoding.encodeBase64(part.data)\n                  const imageUrl = `data:${mediaType};base64,${base64}`\n                  content.push({ type: \"input_image\", image_url: imageUrl, detail })\n                }\n              } else if (part.mediaType === \"application/pdf\") {\n                if (typeof part.data === \"string\" && isFileId(part.data, config)) {\n                  content.push({ type: \"input_file\", file_id: part.data })\n                }\n\n                if (part.data instanceof URL) {\n                  content.push({ type: \"input_file\", file_url: part.data.toString() })\n                }\n\n                if (part.data instanceof Uint8Array) {\n                  const base64 = Encoding.encodeBase64(part.data)\n                  const fileName = part.fileName ?? `part-${index}.pdf`\n                  const fileData = `data:application/pdf;base64,${base64}`\n                  content.push({ type: \"input_file\", filename: fileName, file_data: fileData })\n                }\n              } else {\n                return yield* new AiError.MalformedInput({\n                  module: \"OpenAiLanguageModel\",\n                  method: \"prepareMessages\",\n                  description: `Detected unsupported media type for file: '${part.mediaType}'`\n                })\n              }\n            }\n          }\n        }\n\n        messages.push({ role: \"user\", content })\n\n        break\n      }\n\n      case \"assistant\": {\n        const reasoningMessages: Record<string, DeepMutable<typeof Generated.ReasoningItem.Encoded>> = {}\n\n        for (const part of message.content) {\n          switch (part.type) {\n            case \"text\": {\n              messages.push({\n                role: \"assistant\",\n                content: [{ type: \"output_text\", text: part.text }],\n                id: getItemId(part)\n              })\n              break\n            }\n\n            case \"reasoning\": {\n              const options = part.options.openai\n\n              if (Predicate.isNotUndefined(options?.itemId)) {\n                const reasoningMessage = reasoningMessages[options.itemId]\n                const summaryParts: Mutable<typeof Generated.ReasoningItem.fields.summary.Encoded> = []\n\n                if (part.text.length > 0) {\n                  summaryParts.push({ type: \"summary_text\", text: part.text })\n                }\n\n                if (Predicate.isUndefined(reasoningMessage)) {\n                  reasoningMessages[options.itemId] = {\n                    id: options.itemId,\n                    type: \"reasoning\",\n                    summary: summaryParts,\n                    encrypted_content: options.encryptedContent\n                  }\n                  messages.push(reasoningMessages[options.itemId])\n                } else {\n                  for (const summaryPart of summaryParts) {\n                    reasoningMessage.summary.push(summaryPart)\n                  }\n                }\n              }\n\n              break\n            }\n\n            case \"tool-call\": {\n              if (!part.providerExecuted) {\n                messages.push({\n                  id: getItemId(part),\n                  type: \"function_call\",\n                  call_id: part.id,\n                  name: part.name,\n                  arguments: JSON.stringify(part.params)\n                })\n              }\n\n              break\n            }\n          }\n        }\n\n        break\n      }\n\n      case \"tool\": {\n        for (const part of message.content) {\n          messages.push({\n            type: \"function_call_output\",\n            call_id: part.id,\n            output: JSON.stringify(part.result)\n          })\n        }\n\n        break\n      }\n    }\n  }\n\n  return messages\n})\n\n// =============================================================================\n// Response Conversion\n// =============================================================================\n\nconst makeResponse: (\n  response: Generated.Response,\n  options: LanguageModel.ProviderOptions\n) => Effect.Effect<\n  Array<Response.PartEncoded>,\n  AiError.AiError,\n  IdGenerator.IdGenerator\n> = Effect.fnUntraced(\n  function*(response, options) {\n    const idGenerator = yield* IdGenerator.IdGenerator\n\n    const webSearchTool = options.tools.find((tool) =>\n      Tool.isProviderDefined(tool) &&\n      (tool.id === \"openai.web_search\" ||\n        tool.id === \"openai.web_search_preview\")\n    ) as Tool.AnyProviderDefined | undefined\n\n    let hasToolCalls = false\n    const parts: Array<Response.PartEncoded> = []\n\n    const createdAt = new Date(response.created_at * 1000)\n    parts.push({\n      type: \"response-metadata\",\n      id: response.id,\n      modelId: response.model,\n      timestamp: DateTime.formatIso(DateTime.unsafeFromDate(createdAt))\n    })\n\n    for (const part of response.output) {\n      switch (part.type) {\n        case \"message\": {\n          for (const contentPart of part.content) {\n            switch (contentPart.type) {\n              case \"output_text\": {\n                parts.push({\n                  type: \"text\",\n                  text: contentPart.text,\n                  metadata: { openai: { itemId: part.id } }\n                })\n\n                for (const annotation of contentPart.annotations) {\n                  if (annotation.type === \"file_citation\") {\n                    const metadata = {\n                      type: annotation.type,\n                      index: annotation.index\n                    }\n\n                    parts.push({\n                      type: \"source\",\n                      sourceType: \"document\",\n                      id: yield* idGenerator.generateId(),\n                      mediaType: \"text/plain\",\n                      title: annotation.filename ?? \"Untitled Document\",\n                      metadata: { openai: metadata }\n                    })\n                  }\n\n                  if (annotation.type === \"url_citation\") {\n                    const metadata = {\n                      type: annotation.type,\n                      startIndex: annotation.start_index,\n                      endIndex: annotation.end_index\n                    }\n\n                    parts.push({\n                      type: \"source\",\n                      sourceType: \"url\",\n                      id: yield* idGenerator.generateId(),\n                      url: annotation.url,\n                      title: annotation.title,\n                      metadata: { openai: metadata }\n                    })\n                  }\n                }\n\n                break\n              }\n              case \"refusal\": {\n                parts.push({\n                  type: \"text\",\n                  text: \"\",\n                  metadata: { openai: { refusal: contentPart.refusal } }\n                })\n\n                break\n              }\n            }\n          }\n\n          break\n        }\n\n        case \"function_call\": {\n          hasToolCalls = true\n\n          const toolName = part.name\n          const toolParams = part.arguments\n\n          const params = yield* Effect.try({\n            try: () => Tool.unsafeSecureJsonParse(toolParams),\n            catch: (cause) =>\n              new AiError.MalformedOutput({\n                module: \"OpenAiLanguageModel\",\n                method: \"makeResponse\",\n                description: \"Failed to securely parse tool call parameters \" +\n                  `for tool '${toolName}':\\nParameters: ${toolParams}`,\n                cause\n              })\n          })\n\n          parts.push({\n            type: \"tool-call\",\n            id: part.call_id,\n            name: toolName,\n            params,\n            metadata: { openai: { itemId: part.id } }\n          })\n\n          break\n        }\n\n        case \"code_interpreter_call\": {\n          parts.push({\n            type: \"tool-call\",\n            id: part.id,\n            name: \"OpenAiCodeInterpreter\",\n            params: { code: part.code, container_id: part.container_id },\n            providerName: \"code_interpreter\",\n            providerExecuted: true\n          })\n\n          parts.push({\n            type: \"tool-result\",\n            id: part.id,\n            name: \"OpenAiCodeInterpreter\",\n            isFailure: false,\n            result: part.outputs,\n            providerName: \"code_interpreter\",\n            providerExecuted: true\n          })\n\n          break\n        }\n\n        case \"file_search_call\": {\n          parts.push({\n            type: \"tool-call\",\n            id: part.id,\n            name: \"OpenAiFileSearch\",\n            params: {},\n            providerName: \"file_search\",\n            providerExecuted: true\n          })\n\n          parts.push({\n            type: \"tool-result\",\n            id: part.id,\n            name: \"OpenAiFileSearch\",\n            isFailure: false,\n            result: {\n              status: part.status,\n              queries: part.queries,\n              ...(part.results && { results: part.results })\n            },\n            providerName: \"file_search\",\n            providerExecuted: true\n          })\n\n          break\n        }\n\n        case \"web_search_call\": {\n          parts.push({\n            type: \"tool-call\",\n            id: part.id,\n            name: webSearchTool?.name ?? \"OpenAiWebSearch\",\n            params: { action: part.action },\n            providerName: webSearchTool?.providerName ?? \"web_search\",\n            providerExecuted: true\n          })\n\n          parts.push({\n            type: \"tool-result\",\n            id: part.id,\n            name: webSearchTool?.name ?? \"OpenAiWebSearch\",\n            isFailure: false,\n            result: { status: part.status },\n            providerName: webSearchTool?.providerName ?? \"web_search\",\n            providerExecuted: true\n          })\n\n          break\n        }\n\n        // TODO(Max): support computer use\n        // case \"computer_call\": {\n        //   parts.push({\n        //     type: \"tool-call\",\n        //     id: part.id,\n        //     name: \"OpenAiComputerUse\",\n        //     params: { action: part.action },\n        //     providerName: webSearchTool?.providerName ?? \"web_search\",\n        //     providerExecuted: true\n        //   })\n        //\n        //   parts.push({\n        //     type: \"tool-result\",\n        //     id: part.id,\n        //     name: webSearchTool?.name ?? \"OpenAiWebSearch\",\n        //     result: { status: part.status },\n        //     providerName: webSearchTool?.providerName ?? \"web_search\",\n        //     providerExecuted: true\n        //   })\n        //   break\n        // }\n\n        case \"reasoning\": {\n          // If there are no summary parts, we have to add an empty one to\n          // propagate the part identifier\n          if (part.summary.length === 0) {\n            parts.push({\n              type: \"reasoning\",\n              text: \"\",\n              metadata: { openai: { itemId: part.id } }\n            })\n          } else {\n            for (const summary of part.summary) {\n              const metadata = {\n                itemId: part.id,\n                encryptedContent: part.encrypted_content ?? undefined\n              }\n              parts.push({\n                type: \"reasoning\",\n                text: summary.text,\n                metadata: { openai: metadata }\n              })\n            }\n          }\n\n          break\n        }\n      }\n    }\n\n    const finishReason = InternalUtilities.resolveFinishReason(\n      response.incomplete_details?.reason,\n      hasToolCalls\n    )\n\n    const metadata = {\n      serviceTier: response.service_tier\n    }\n\n    parts.push({\n      type: \"finish\",\n      reason: finishReason,\n      usage: {\n        inputTokens: response.usage?.input_tokens,\n        outputTokens: response.usage?.output_tokens,\n        totalTokens: (response.usage?.input_tokens ?? 0) + (response.usage?.output_tokens ?? 0),\n        reasoningTokens: response.usage?.output_tokens_details?.reasoning_tokens,\n        cachedInputTokens: response.usage?.input_tokens_details?.cached_tokens\n      },\n      metadata: { openai: metadata }\n    })\n\n    return parts\n  }\n)\n\nconst makeStreamResponse: (\n  stream: Stream.Stream<ResponseStreamEvent, AiError.AiError>,\n  options: LanguageModel.ProviderOptions\n) => Effect.Effect<\n  Stream.Stream<Response.StreamPartEncoded, AiError.AiError>,\n  never,\n  IdGenerator.IdGenerator\n> = Effect.fnUntraced(\n  function*(stream, options) {\n    const idGenerator = yield* IdGenerator.IdGenerator\n\n    let hasToolCalls = false\n\n    const activeReasoning: Record<string, {\n      readonly summaryParts: Array<number>\n      readonly encryptedContent: string | undefined\n    }> = {}\n\n    const activeToolCalls: Record<number, {\n      readonly id: string\n      readonly name: string\n    }> = {}\n\n    const webSearchTool = options.tools.find((tool) =>\n      Tool.isProviderDefined(tool) &&\n      (tool.id === \"openai.web_search\" ||\n        tool.id === \"openai.web_search_preview\")\n    ) as Tool.AnyProviderDefined | undefined\n\n    return stream.pipe(\n      Stream.mapEffect(Effect.fnUntraced(function*(event) {\n        const parts: Array<Response.StreamPartEncoded> = []\n\n        switch (event.type) {\n          case \"response.created\": {\n            const createdAt = new Date(event.response.created_at * 1000)\n            parts.push({\n              type: \"response-metadata\",\n              id: event.response.id,\n              modelId: event.response.model,\n              timestamp: DateTime.formatIso(DateTime.unsafeFromDate(createdAt))\n            })\n            break\n          }\n\n          case \"error\": {\n            parts.push({ type: \"error\", error: event })\n            break\n          }\n\n          case \"response.completed\":\n          case \"response.incomplete\":\n          case \"response.failed\": {\n            parts.push({\n              type: \"finish\",\n              reason: InternalUtilities.resolveFinishReason(\n                event.response.incomplete_details?.reason,\n                hasToolCalls\n              ),\n              usage: {\n                inputTokens: event.response.usage?.input_tokens,\n                outputTokens: event.response.usage?.output_tokens,\n                totalTokens: (event.response.usage?.input_tokens ?? 0) + (event.response.usage?.output_tokens ?? 0),\n                reasoningTokens: event.response.usage?.output_tokens_details?.reasoning_tokens,\n                cachedInputTokens: event.response.usage?.input_tokens_details?.cached_tokens\n              },\n              metadata: { openai: { serviceTier: event.response.service_tier } }\n            })\n            break\n          }\n\n          case \"response.output_item.added\": {\n            switch (event.item.type) {\n              case \"computer_call\": {\n                // TODO(Max): support computer use\n                break\n              }\n\n              case \"file_search_call\": {\n                activeToolCalls[event.output_index] = {\n                  id: event.item.id,\n                  name: \"OpenAiFileSearch\"\n                }\n                parts.push({\n                  type: \"tool-params-start\",\n                  id: event.item.id,\n                  name: \"OpenAiFileSearch\",\n                  providerName: \"file_search\",\n                  providerExecuted: true\n                })\n                break\n              }\n\n              case \"function_call\": {\n                activeToolCalls[event.output_index] = {\n                  id: event.item.call_id,\n                  name: event.item.name\n                }\n                parts.push({\n                  type: \"tool-params-start\",\n                  id: event.item.call_id,\n                  name: event.item.name\n                })\n                break\n              }\n\n              case \"message\": {\n                parts.push({\n                  type: \"text-start\",\n                  id: event.item.id,\n                  metadata: { openai: { itemId: event.item.id } }\n                })\n                break\n              }\n\n              case \"reasoning\": {\n                activeReasoning[event.item.id] = {\n                  summaryParts: [0],\n                  encryptedContent: event.item.encrypted_content\n                }\n                parts.push({\n                  type: \"reasoning-start\",\n                  id: `${event.item.id}:0`,\n                  metadata: {\n                    openai: {\n                      itemId: event.item.id,\n                      encryptedContent: event.item.encrypted_content\n                    }\n                  }\n                })\n                break\n              }\n\n              case \"web_search_call\": {\n                activeToolCalls[event.output_index] = {\n                  id: event.item.id,\n                  name: webSearchTool?.name ?? \"OpenAiWebSearch\"\n                }\n                parts.push({\n                  type: \"tool-params-start\",\n                  id: event.item.id,\n                  name: webSearchTool?.name ?? \"OpenAiWebSearch\",\n                  providerName: webSearchTool?.providerName ?? \"web_search\",\n                  providerExecuted: true\n                })\n                break\n              }\n            }\n\n            break\n          }\n\n          case \"response.output_item.done\": {\n            switch (event.item.type) {\n              case \"code_interpreter_call\": {\n                parts.push({\n                  type: \"tool-call\",\n                  id: event.item.id,\n                  name: \"OpenAiCodeInterpreter\",\n                  params: { code: event.item.code, container_id: event.item.container_id },\n                  providerName: \"code_interpreter\",\n                  providerExecuted: true\n                })\n                parts.push({\n                  type: \"tool-result\",\n                  id: event.item.id,\n                  name: \"OpenAiCodeInterpreter\",\n                  isFailure: false,\n                  result: { outputs: event.item.outputs },\n                  providerName: \"code_interpreter\",\n                  providerExecuted: true\n                })\n                break\n              }\n\n              // TODO(Max): support computer use\n              case \"computer_call\": {\n                break\n              }\n\n              case \"file_search_call\": {\n                delete activeToolCalls[event.output_index]\n                parts.push({\n                  type: \"tool-params-end\",\n                  id: event.item.id\n                })\n                parts.push({\n                  type: \"tool-call\",\n                  id: event.item.id,\n                  name: \"OpenAiFileSearch\",\n                  params: {},\n                  providerName: \"file_search\",\n                  providerExecuted: true\n                })\n                parts.push({\n                  type: \"tool-result\",\n                  id: event.item.id,\n                  name: \"OpenAiFileSearch\",\n                  isFailure: false,\n                  result: {\n                    status: event.item.status,\n                    queries: event.item.queries,\n                    ...(event.item.results && { results: event.item.results })\n                  },\n                  providerName: \"file_search\",\n                  providerExecuted: true\n                })\n                break\n              }\n\n              case \"function_call\": {\n                hasToolCalls = true\n\n                const toolName = event.item.name\n                const toolParams = event.item.arguments\n\n                const params = yield* Effect.try({\n                  try: () => Tool.unsafeSecureJsonParse(toolParams),\n                  catch: (cause) =>\n                    new AiError.MalformedOutput({\n                      module: \"OpenAiLanguageModel\",\n                      method: \"makeStreamResponse\",\n                      description: \"Failed to securely parse tool call parameters \" +\n                        `for tool '${toolName}':\\nParameters: ${toolParams}`,\n                      cause\n                    })\n                })\n\n                parts.push({\n                  type: \"tool-params-end\",\n                  id: event.item.call_id\n                })\n\n                parts.push({\n                  type: \"tool-call\",\n                  id: event.item.call_id,\n                  name: toolName,\n                  params,\n                  metadata: { openai: { itemId: event.item.id } }\n                })\n\n                delete activeToolCalls[event.output_index]\n\n                break\n              }\n\n              case \"message\": {\n                parts.push({\n                  type: \"text-end\",\n                  id: event.item.id\n                })\n                break\n              }\n\n              case \"reasoning\": {\n                const reasoningPart = activeReasoning[event.item.id]\n                for (const summaryIndex of reasoningPart.summaryParts) {\n                  parts.push({\n                    type: \"reasoning-end\",\n                    id: `${event.item.id}:${summaryIndex}`,\n                    metadata: {\n                      openai: {\n                        itemId: event.item.id,\n                        encryptedContent: event.item.encrypted_content\n                      }\n                    }\n                  })\n                }\n                delete activeReasoning[event.item.id]\n                break\n              }\n\n              case \"web_search_call\": {\n                delete activeToolCalls[event.output_index]\n                parts.push({\n                  type: \"tool-params-end\",\n                  id: event.item.id\n                })\n                parts.push({\n                  type: \"tool-call\",\n                  id: event.item.id,\n                  name: \"OpenAiWebSearch\",\n                  params: { action: event.item.action },\n                  providerName: \"web_search\",\n                  providerExecuted: true\n                })\n                parts.push({\n                  type: \"tool-result\",\n                  id: event.item.id,\n                  name: \"OpenAiWebSearch\",\n                  isFailure: false,\n                  result: { status: event.item.status },\n                  providerName: \"web_search\",\n                  providerExecuted: true\n                })\n                break\n              }\n            }\n\n            break\n          }\n\n          case \"response.output_text.delta\": {\n            parts.push({\n              type: \"text-delta\",\n              id: event.item_id,\n              delta: event.delta\n            })\n            break\n          }\n\n          case \"response.output_text.annotation.added\": {\n            if (event.annotation.type === \"file_citation\") {\n              parts.push({\n                type: \"source\",\n                sourceType: \"document\",\n                id: yield* idGenerator.generateId(),\n                mediaType: \"text/plain\",\n                title: event.annotation.filename ?? \"Untitled Document\",\n                fileName: event.annotation.filename ?? event.annotation.file_id\n              })\n            }\n            if (event.annotation.type === \"url_citation\") {\n              parts.push({\n                type: \"source\",\n                sourceType: \"url\",\n                id: yield* idGenerator.generateId(),\n                url: event.annotation.url,\n                title: event.annotation.title\n              })\n            }\n            break\n          }\n\n          case \"response.function_call_arguments.delta\": {\n            const toolCallPart = activeToolCalls[event.output_index]\n            if (Predicate.isNotUndefined(toolCallPart)) {\n              parts.push({\n                type: \"tool-params-delta\",\n                id: toolCallPart.id,\n                delta: event.delta\n              })\n            }\n            break\n          }\n\n          case \"response.reasoning_summary_part.added\": {\n            // The first reasoning start is pushed in the `response.output_item.added` block\n            if (event.summary_index > 0) {\n              const reasoningPart = activeReasoning[event.item_id]\n              if (Predicate.isNotUndefined(reasoningPart)) {\n                reasoningPart.summaryParts.push(event.summary_index)\n              }\n              parts.push({\n                type: \"reasoning-start\",\n                id: `${event.item_id}:${event.summary_index}`,\n                metadata: {\n                  openai: {\n                    itemId: event.item_id,\n                    encryptedContent: reasoningPart?.encryptedContent\n                  }\n                }\n              })\n            }\n            break\n          }\n\n          case \"response.reasoning_summary_text.delta\": {\n            parts.push({\n              type: \"reasoning-delta\",\n              id: `${event.item_id}:${event.summary_index}`,\n              delta: event.delta,\n              metadata: { openai: { itemId: event.item_id } }\n            })\n            break\n          }\n        }\n\n        return parts\n      })),\n      Stream.flattenIterables\n    )\n  }\n)\n\n// =============================================================================\n// Telemetry\n// =============================================================================\n\nconst annotateRequest = (\n  span: Span,\n  request: typeof Generated.CreateResponse.Encoded\n): void => {\n  addGenAIAnnotations(span, {\n    system: \"openai\",\n    operation: { name: \"chat\" },\n    request: {\n      model: request.model,\n      temperature: request.temperature,\n      topP: request.top_p,\n      maxTokens: request.max_output_tokens\n    },\n    openai: {\n      request: {\n        responseFormat: request.text?.format?.type,\n        serviceTier: request.service_tier\n      }\n    }\n  })\n}\n\nconst annotateResponse = (span: Span, response: Generated.Response): void => {\n  const finishReason = response.incomplete_details?.reason\n  addGenAIAnnotations(span, {\n    response: {\n      id: response.id,\n      model: response.model,\n      finishReasons: Predicate.isNotUndefined(finishReason) ? [finishReason] : undefined\n    },\n    usage: {\n      inputTokens: response.usage?.input_tokens,\n      outputTokens: response.usage?.output_tokens\n    },\n    openai: {\n      response: {\n        serviceTier: response.service_tier\n      }\n    }\n  })\n}\n\nconst annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded) => {\n  if (part.type === \"response-metadata\") {\n    addGenAIAnnotations(span, {\n      response: {\n        id: part.id,\n        model: part.modelId\n      }\n    })\n  }\n  if (part.type === \"finish\") {\n    const serviceTier = part.metadata?.openai?.serviceTier as string | undefined\n    addGenAIAnnotations(span, {\n      response: {\n        finishReasons: [part.reason]\n      },\n      usage: {\n        inputTokens: part.usage.inputTokens,\n        outputTokens: part.usage.outputTokens\n      },\n      openai: {\n        response: { serviceTier }\n      }\n    })\n  }\n}\n\n// =============================================================================\n// Tool Calling\n// =============================================================================\n\ntype OpenAiToolChoice = typeof Generated.CreateResponse.fields.tool_choice.from.Encoded\n\nconst prepareTools: (options: LanguageModel.ProviderOptions) => Effect.Effect<{\n  readonly tools: ReadonlyArray<typeof Generated.Tool.Encoded> | undefined\n  readonly toolChoice: OpenAiToolChoice | undefined\n}, AiError.AiError> = Effect.fnUntraced(function*(options) {\n  // Return immediately if no tools are in the toolkit\n  if (options.tools.length === 0) {\n    return { tools: undefined, toolChoice: undefined }\n  }\n\n  const tools: Array<typeof Generated.Tool.Encoded> = []\n  let toolChoice: OpenAiToolChoice | undefined = undefined\n\n  // Filter the incoming tools down to the set of allowed tools as indicated by\n  // the tool choice. This must be done here given that there is no tool name\n  // in OpenAI's provider-defined tools, so there would be no way to perform\n  // this filter otherwise\n  let allowedTools = options.tools\n  if (typeof options.toolChoice === \"object\" && \"oneOf\" in options.toolChoice) {\n    const allowedToolNames = new Set(options.toolChoice.oneOf)\n    allowedTools = options.tools.filter((tool) => allowedToolNames.has(tool.name))\n    toolChoice = options.toolChoice.mode === \"required\" ? \"required\" : \"auto\"\n  }\n\n  // Convert the tools in the toolkit to the provider-defined format\n  for (const tool of allowedTools) {\n    if (Tool.isUserDefined(tool)) {\n      tools.push({\n        type: \"function\",\n        name: tool.name,\n        description: Tool.getDescription(tool as any),\n        parameters: Tool.getJsonSchema(tool as any) as any,\n        strict: true\n      })\n    }\n\n    if (Tool.isProviderDefined(tool)) {\n      switch (tool.id) {\n        case \"openai.code_interpreter\": {\n          tools.push({\n            ...tool.args,\n            type: \"code_interpreter\"\n          })\n          break\n        }\n        case \"openai.file_search\": {\n          tools.push({\n            ...tool.args,\n            type: \"file_search\"\n          })\n          break\n        }\n        case \"openai.web_search\": {\n          tools.push({\n            ...tool.args,\n            type: \"web_search\"\n          })\n          break\n        }\n        case \"openai.web_search_preview\": {\n          tools.push({\n            ...tool.args,\n            type: \"web_search_preview\"\n          })\n          break\n        }\n        default: {\n          return yield* new AiError.MalformedInput({\n            module: \"AnthropicLanguageModel\",\n            method: \"prepareTools\",\n            description: `Received request to call unknown provider-defined tool '${tool.name}'`\n          })\n        }\n      }\n    }\n  }\n\n  if (options.toolChoice === \"auto\" || options.toolChoice === \"none\" || options.toolChoice === \"required\") {\n    toolChoice = options.toolChoice\n  }\n\n  if (typeof options.toolChoice === \"object\" && \"tool\" in options.toolChoice) {\n    toolChoice = Predicate.isUndefined(OpenAiTool.getProviderDefinedToolName(options.toolChoice.tool))\n      ? { type: \"function\", name: options.toolChoice.tool }\n      : { type: options.toolChoice.tool }\n  }\n\n  return { tools, toolChoice }\n})\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nconst isFileId = (data: string, config: Config.Service): boolean =>\n  Predicate.isNotUndefined(config.fileIdPrefixes) && config.fileIdPrefixes.some((prefix) => data.startsWith(prefix))\n\nconst getItemId = (\n  part:\n    | Prompt.TextPart\n    | Prompt.ToolCallPart\n): string | undefined => part.options.openai?.itemId\n\nconst getImageDetail = (part: Prompt.FilePart): typeof Generated.ImageDetail.Encoded =>\n  part.options.openai?.imageDetail ?? \"auto\"\n\nconst prepareInclude = (\n  options: LanguageModel.ProviderOptions,\n  config: Config.Service\n): ReadonlyArray<typeof Generated.IncludeEnum.Encoded> => {\n  const include: Set<typeof Generated.IncludeEnum.Encoded> = new Set(config.include ?? [])\n\n  const codeInterpreterTool = options.tools.find((tool) =>\n    Tool.isProviderDefined(tool) &&\n    tool.id === \"openai.code_interpreter\"\n  ) as Tool.AnyProviderDefined | undefined\n\n  if (Predicate.isNotUndefined(codeInterpreterTool)) {\n    include.add(\"code_interpreter_call.outputs\")\n  }\n\n  const webSearchTool = options.tools.find((tool) =>\n    Tool.isProviderDefined(tool) &&\n    (tool.id === \"openai.web_search\" ||\n      tool.id === \"openai.web_search_preview\")\n  ) as Tool.AnyProviderDefined | undefined\n\n  if (Predicate.isNotUndefined(webSearchTool)) {\n    include.add(\"web_search_call.action.sources\")\n  }\n\n  return Array.from(include)\n}\n\nconst prepareResponseFormat = (\n  options: LanguageModel.ProviderOptions\n): typeof Generated.TextResponseFormatConfiguration.Encoded => {\n  if (options.responseFormat.type === \"json\") {\n    const name = options.responseFormat.objectName\n    const schema = options.responseFormat.schema\n    return {\n      type: \"json_schema\",\n      name,\n      description: Tool.getDescriptionFromSchemaAst(schema.ast) ?? \"Response with a JSON object\",\n      schema: Tool.getJsonSchemaFromSchemaAst(schema.ast) as any,\n      strict: true\n    }\n  }\n  return { type: \"text\" }\n}\n"
  },
  {
    "path": "packages/ai/openai/src/OpenAiTelemetry.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Telemetry from \"@effect/ai/Telemetry\"\nimport { dual } from \"effect/Function\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as String from \"effect/String\"\nimport type { Span } from \"effect/Tracer\"\nimport type { Simplify } from \"effect/Types\"\n\n/**\n * The attributes used to describe telemetry in the context of Generative\n * Artificial Intelligence (GenAI) Models requests and responses.\n *\n * {@see https://opentelemetry.io/docs/specs/semconv/attributes-registry/gen-ai/}\n *\n * @since 1.0.0\n * @category Models\n */\nexport type OpenAiTelemetryAttributes = Simplify<\n  & Telemetry.GenAITelemetryAttributes\n  & Telemetry.AttributesWithPrefix<RequestAttributes, \"gen_ai.openai.request\">\n  & Telemetry.AttributesWithPrefix<ResponseAttributes, \"gen_ai.openai.request\">\n>\n\n/**\n * All telemetry attributes which are part of the GenAI specification,\n * including the OpenAi-specific attributes.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type AllAttributes = Telemetry.AllAttributes & RequestAttributes & ResponseAttributes\n\n/**\n * Telemetry attributes which are part of the GenAI specification and are\n * namespaced by `gen_ai.openai.request`.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface RequestAttributes {\n  /**\n   * The response format that is requested.\n   */\n  readonly responseFormat?: (string & {}) | WellKnownResponseFormat | null | undefined\n  /**\n   * The service tier requested. May be a specific tier, `default`, or `auto`.\n   */\n  readonly serviceTier?: (string & {}) | WellKnownServiceTier | null | undefined\n}\n\n/**\n * Telemetry attributes which are part of the GenAI specification and are\n * namespaced by `gen_ai.openai.response`.\n *\n * @since 1.0.0\n * @category Models\n */\nexport interface ResponseAttributes {\n  /**\n   * The service tier used for the response.\n   */\n  readonly serviceTier?: string | null | undefined\n  /**\n   * A fingerprint to track any eventual change in the Generative AI\n   * environment.\n   */\n  readonly systemFingerprint?: string | null | undefined\n}\n\n/**\n * The `gen_ai.openai.request.response_format` attribute has the following\n * list of well-known values.\n *\n * If one of them applies, then the respective value **MUST** be used;\n * otherwise, a custom value **MAY** be used.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type WellKnownResponseFormat = \"json_object\" | \"json_schema\" | \"text\"\n\n/**\n * The `gen_ai.openai.request.service_tier` attribute has the following\n * list of well-known values.\n *\n * If one of them applies, then the respective value **MUST** be used;\n * otherwise, a custom value **MAY** be used.\n *\n * @since 1.0.0\n * @category Models\n */\nexport type WellKnownServiceTier = \"auto\" | \"default\"\n\n/**\n * @since 1.0.0\n * @since Models\n */\nexport type OpenAiTelemetryAttributeOptions = Telemetry.GenAITelemetryAttributeOptions & {\n  openai?: {\n    request?: RequestAttributes | undefined\n    response?: ResponseAttributes | undefined\n  } | undefined\n}\n\nconst addOpenAiRequestAttributes = Telemetry.addSpanAttributes(\"gen_ai.openai.request\", String.camelToSnake)<\n  RequestAttributes\n>\nconst addOpenAiResponseAttributes = Telemetry.addSpanAttributes(\"gen_ai.openai.response\", String.camelToSnake)<\n  ResponseAttributes\n>\n\n/**\n * Applies the specified OpenAi GenAI telemetry attributes to the provided\n * `Span`.\n *\n * **NOTE**: This method will mutate the `Span` **in-place**.\n *\n * @since 1.0.0\n * @since Utilities\n */\nexport const addGenAIAnnotations = dual<\n  (options: OpenAiTelemetryAttributeOptions) => (span: Span) => void,\n  (span: Span, options: OpenAiTelemetryAttributeOptions) => void\n>(2, (span, options) => {\n  Telemetry.addGenAIAnnotations(span, options)\n  if (Predicate.isNotNullable(options.openai)) {\n    if (Predicate.isNotNullable(options.openai.request)) {\n      addOpenAiRequestAttributes(span, options.openai.request)\n    }\n    if (Predicate.isNotNullable(options.openai.response)) {\n      addOpenAiResponseAttributes(span, options.openai.response)\n    }\n  }\n})\n"
  },
  {
    "path": "packages/ai/openai/src/OpenAiTokenizer.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AiError from \"@effect/ai/AiError\"\nimport type * as Prompt from \"@effect/ai/Prompt\"\nimport * as Tokenizer from \"@effect/ai/Tokenizer\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as GptTokenizer from \"gpt-tokenizer\"\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (options: { readonly model: string }) =>\n  Tokenizer.make({\n    tokenize(prompt) {\n      return Effect.try({\n        try: () => {\n          const content: Array<{\n            readonly role: \"assistant\" | \"system\" | \"user\"\n            readonly content: string\n          }> = []\n\n          for (const message of prompt.content) {\n            if (message.role === \"system\") {\n              content.push({ role: getRole(message), content: message.content })\n              continue\n            }\n\n            for (const part of message.content) {\n              switch (part.type) {\n                case \"reasoning\":\n                case \"text\": {\n                  content.push({ role: getRole(message), content: part.text })\n                  break\n                }\n                case \"tool-call\": {\n                  content.push({ role: getRole(message), content: JSON.stringify(part.params) })\n                  break\n                }\n                case \"tool-result\": {\n                  content.push({ role: getRole(message), content: JSON.stringify(part.result) })\n                  break\n                }\n              }\n            }\n          }\n          return GptTokenizer.encodeChat(content, options.model as any)\n        },\n        catch: (cause) =>\n          new AiError.UnknownError({\n            module: \"OpenAiTokenizer\",\n            method: \"tokenize\",\n            description: \"Could not tokenize\",\n            cause\n          })\n      })\n    }\n  })\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: { readonly model: string }): Layer.Layer<Tokenizer.Tokenizer> =>\n  Layer.succeed(Tokenizer.Tokenizer, make(options))\n\nconst getRole = (message: Prompt.Message): \"assistant\" | \"system\" | \"user\" =>\n  message.role === \"tool\" ? \"assistant\" : message.role\n"
  },
  {
    "path": "packages/ai/openai/src/OpenAiTool.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Tool from \"@effect/ai/Tool\"\nimport * as Schema from \"effect/Schema\"\nimport * as Struct from \"effect/Struct\"\nimport * as Generated from \"./Generated.js\"\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const CodeInterpreter = Tool.providerDefined({\n  id: \"openai.code_interpreter\",\n  toolkitName: \"OpenAiCodeInterpreter\",\n  providerName: \"code_interpreter\",\n  args: {\n    /**\n     * The configuration for the code interpreter container.\n     *\n     * Can be either a string which specifies the ID of a container created via\n     * the `/v1/containers` endpoint, or an object which specifies an optional\n     * list of files to make available to the container.\n     */\n    container: Schema.Union(\n      Schema.String,\n      Schema.Struct({\n        type: Schema.Literal(\"auto\"),\n        /**\n         * An optional list of uploaded files to make available to your code.\n         */\n        file_ids: Schema.optional(Schema.Array(Schema.String))\n      })\n    )\n  },\n  parameters: {\n    code: Schema.NullOr(Schema.String),\n    container_id: Schema.String\n  },\n  success: Schema.NullOr(Schema.Array(Schema.Union(\n    Generated.CodeInterpreterOutputLogs,\n    Generated.CodeInterpreterOutputImage\n  )))\n})\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const FileSearch = Tool.providerDefined({\n  id: \"openai.file_search\",\n  toolkitName: \"OpenAiFileSearch\",\n  providerName: \"file_search\",\n  args: Struct.omit(Generated.FileSearchTool.fields, \"type\"),\n  success: Generated.FileSearchToolCall.pipe(Schema.omit(\"id\", \"type\"))\n})\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const WebSearch = Tool.providerDefined({\n  id: \"openai.web_search\",\n  toolkitName: \"OpenAiWebSearch\",\n  providerName: \"web_search\",\n  args: Struct.omit(Generated.WebSearchTool.fields, \"type\"),\n  parameters: {\n    action: Schema.Union(\n      Generated.WebSearchActionSearch,\n      Generated.WebSearchActionOpenPage,\n      Generated.WebSearchActionFind\n    )\n  },\n  success: Schema.Struct({\n    status: Generated.WebSearchToolCallStatus\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Tools\n */\nexport const WebSearchPreview = Tool.providerDefined({\n  id: \"openai.web_search_preview\",\n  toolkitName: \"OpenAiWebSearchPreview\",\n  providerName: \"web_search_preview\",\n  args: Struct.omit(Generated.WebSearchPreviewTool.fields, \"type\"),\n  parameters: {\n    action: Schema.Union(\n      Generated.WebSearchActionSearch,\n      Generated.WebSearchActionOpenPage,\n      Generated.WebSearchActionFind\n    )\n  },\n  success: Schema.Struct({\n    status: Generated.WebSearchToolCallStatus\n  })\n})\n\ntype ProviderToolNames = \"code_interpreter\" | \"file_search\" | \"web_search\" | \"web_search_preview\"\n\nconst ProviderToolNamesMap: Map<ProviderToolNames | (string & {}), string> = new Map([\n  [\"code_interpreter\", \"OpenAiCodeInterpreter\"],\n  [\"file_search\", \"OpenAiFileSearch\"],\n  [\"web_search\", \"OpenAiWebSearch\"],\n  [\"web_search_preview\", \"OpenAiWebSearchPreview\"]\n])\n\n/** @internal */\nexport const getProviderDefinedToolName = (name: string): string | undefined => ProviderToolNamesMap.get(name)\n"
  },
  {
    "path": "packages/ai/openai/src/index.ts",
    "content": "/**\n * @since 1.0.0\n */\nexport * as Generated from \"./Generated.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OpenAiClient from \"./OpenAiClient.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OpenAiConfig from \"./OpenAiConfig.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OpenAiEmbeddingModel from \"./OpenAiEmbeddingModel.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OpenAiLanguageModel from \"./OpenAiLanguageModel.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OpenAiTelemetry from \"./OpenAiTelemetry.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OpenAiTokenizer from \"./OpenAiTokenizer.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OpenAiTool from \"./OpenAiTool.js\"\n"
  },
  {
    "path": "packages/ai/openai/src/internal/utilities.ts",
    "content": "import type * as Response from \"@effect/ai/Response\"\nimport * as Predicate from \"effect/Predicate\"\n\n/** @internal */\nexport const ProviderOptionsKey = \"@effect/ai-openai/OpenAiLanguageModel/ProviderOptions\"\n\n/** @internal */\nexport const ProviderMetadataKey = \"@effect/ai-openai/OpenAiLanguageModel/ProviderMetadata\"\n\nconst finishReasonMap: Record<string, Response.FinishReason> = {\n  content_filter: \"content-filter\",\n  function_call: \"tool-calls\",\n  length: \"length\",\n  stop: \"stop\",\n  tool_calls: \"tool-calls\"\n}\n\n/** @internal */\nexport const resolveFinishReason = (\n  finishReason: string | undefined,\n  hasToolCalls: boolean\n): Response.FinishReason => {\n  if (Predicate.isNullable(finishReason)) {\n    return hasToolCalls ? \"tool-calls\" : \"stop\"\n  }\n  const reason = finishReasonMap[finishReason]\n  if (Predicate.isNullable(reason)) {\n    return hasToolCalls ? \"tool-calls\" : \"unknown\"\n  }\n  return reason\n}\n"
  },
  {
    "path": "packages/ai/openai/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"references\": [\n    { \"path\": \"../ai/tsconfig.build.json\" },\n    { \"path\": \"../../effect/tsconfig.build.json\" },\n    { \"path\": \"../../experimental/tsconfig.build.json\" },\n    { \"path\": \"../../platform/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/openai/tsconfig.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/ai/openai/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"references\": [\n    { \"path\": \"../ai/tsconfig.src.json\" },\n    { \"path\": \"../../effect/tsconfig.src.json\" },\n    { \"path\": \"../../experimental/tsconfig.src.json\" },\n    { \"path\": \"../../platform/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\",\n    \"outDir\": \"build/src\",\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/openai/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../../vitest/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"noEmit\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/openai/vitest.config.ts",
    "content": "import { mergeConfig, type ViteUserConfig } from \"vitest/config\"\nimport shared from \"../../../vitest.shared.js\"\n\nconst config: ViteUserConfig = {}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/ai/openrouter/CHANGELOG.md",
    "content": "# @effect/ai-openrouter\n\n## 0.10.0\n\n### Patch Changes\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n  - @effect/ai@0.35.0\n  - @effect/experimental@0.60.0\n  - @effect/platform@0.96.0\n\n## 0.9.1\n\n### Patch Changes\n\n- [#6131](https://github.com/Effect-TS/effect/pull/6131) [`5c80e57`](https://github.com/Effect-TS/effect/commit/5c80e578bd95e0cf6fceffc72fa0b130ca11ec8e) Thanks @fabstorres! - Allow partial tool_call deltas in OpenRouter streaming\n\n- Updated dependencies [[`add06f4`](https://github.com/Effect-TS/effect/commit/add06f4521403cbf4b9a692f9b59fb9d3d48293c), [`a03b6a2`](https://github.com/Effect-TS/effect/commit/a03b6a29ed0b983b0440b8ef4be47f47c57d73d7)]:\n  - effect@3.20.1\n\n## 0.9.0\n\n### Patch Changes\n\n- [#6117](https://github.com/Effect-TS/effect/pull/6117) [`7103e24`](https://github.com/Effect-TS/effect/commit/7103e2473db805cc9f0024d4744c77c16d81e2f1) Thanks @nickbreaton! - Fix OpenRouter streaming finalization for usage-only terminal chunks.\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n  - @effect/ai@0.34.0\n  - @effect/experimental@0.59.0\n  - @effect/platform@0.95.0\n\n## 0.8.4\n\n### Patch Changes\n\n- [#6071](https://github.com/Effect-TS/effect/pull/6071) [`a91364d`](https://github.com/Effect-TS/effect/commit/a91364d0ef48de0f66afe801c4da13bfe8a5aeed) Thanks @marbemac! - Fix `ChatStreamingMessageToolCall` schema rejecting valid streaming tool call chunks.\n\n  The OpenAI streaming spec splits tool calls across multiple SSE chunks — `function.name` is only present on the first chunk, but the schema required it on every chunk, causing a `MalformedOutput` error whenever the model returned a tool call.\n\n  Made `function.name` optional to match `id` which was already optional.\n\n## 0.8.3\n\n### Patch Changes\n\n- [#6060](https://github.com/Effect-TS/effect/pull/6060) [`c3e706f`](https://github.com/Effect-TS/effect/commit/c3e706ff4d01c70ae1754b13c9cbc1f001c09068) Thanks @nvonbulow! - fix(ai-openrouter): deduplicate reasoning parts when both `reasoning` and `reasoning_details` are present in a stream delta\n\n- Updated dependencies [[`d67c708`](https://github.com/Effect-TS/effect/commit/d67c7089ba8616b2d48ef7324312267a2a6f310a), [`a8c436f`](https://github.com/Effect-TS/effect/commit/a8c436f7004cc2a8ce2daec589ea7256b91c324f)]:\n  - @effect/platform@0.94.5\n  - effect@3.19.17\n\n## 0.8.2\n\n### Patch Changes\n\n- [#6026](https://github.com/Effect-TS/effect/pull/6026) [`38241de`](https://github.com/Effect-TS/effect/commit/38241dee2319d051f3ab15781f73f838d626ac24) Thanks @IMax153! - Fix the OpenRouter AI provider schemas\n\n- Updated dependencies [[`0023c19`](https://github.com/Effect-TS/effect/commit/0023c19c63c402c050d496817ba92aceea7f25b7), [`e71889f`](https://github.com/Effect-TS/effect/commit/e71889f35b081d13b7da2c04d2f81d6933056b49), [`9a96b87`](https://github.com/Effect-TS/effect/commit/9a96b87a33a75ebc277c585e60758ab4409c0d9e)]:\n  - @effect/platform@0.94.3\n  - effect@3.19.16\n\n## 0.8.1\n\n### Patch Changes\n\n- [#5928](https://github.com/Effect-TS/effect/pull/5928) [`34fbbb1`](https://github.com/Effect-TS/effect/commit/34fbbb18e34cbad6ee5f0f396b3e27ba590925b8) Thanks @harrysolovay! - Regenerate OpenRouter schemas to fix schema validation.\n\n- Updated dependencies [[`65e9e35`](https://github.com/Effect-TS/effect/commit/65e9e35157cbdfb40826ddad34555c4ebcf7c0b0), [`ee69cd7`](https://github.com/Effect-TS/effect/commit/ee69cd796feb3d8d1046f52edd8950404cd4ed0e), [`488d6e8`](https://github.com/Effect-TS/effect/commit/488d6e870eda3dfc137f4940bb69416f61ed8fe3), [`ba9e790`](https://github.com/Effect-TS/effect/commit/ba9e7908a80a55f24217c88af4f7d89a4f7bc0e4)]:\n  - @effect/platform@0.94.1\n  - effect@3.19.14\n  - @effect/ai@0.33.1\n\n## 0.8.0\n\n### Patch Changes\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n  - @effect/platform@0.94.0\n  - @effect/ai@0.33.0\n  - @effect/experimental@0.58.0\n\n## 0.7.1\n\n### Patch Changes\n\n- [#5799](https://github.com/Effect-TS/effect/pull/5799) [`5d7c9d8`](https://github.com/Effect-TS/effect/commit/5d7c9d8bb89b955b79303e7445c713ce56b06977) Thanks @subtleGradient! - Add support for google-gemini-v1 reasoning format\n\n- Updated dependencies [[`65bff45`](https://github.com/Effect-TS/effect/commit/65bff451fc54d47b32995b3bc898ccc5f8b1beb6)]:\n  - @effect/platform@0.93.7\n\n## 0.7.0\n\n### Minor Changes\n\n- [#5849](https://github.com/Effect-TS/effect/pull/5849) [`2dcbf98`](https://github.com/Effect-TS/effect/commit/2dcbf98b0b426536f71dfb33cbe6f310d7ad4e77) Thanks @IMax153! - Update generated schema definitions and apply patch fixes\n\n### Patch Changes\n\n- Updated dependencies [[`96c9537`](https://github.com/Effect-TS/effect/commit/96c9537f73a87a651c348488bdce7efbfd8360d1)]:\n  - @effect/experimental@0.57.10\n\n## 0.6.0\n\n### Patch Changes\n\n- Updated dependencies [[`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - effect@3.19.0\n  - @effect/platform@0.93.0\n  - @effect/ai@0.32.0\n  - @effect/experimental@0.57.0\n\n## 0.5.0\n\n### Minor Changes\n\n- [#5621](https://github.com/Effect-TS/effect/pull/5621) [`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825) Thanks @IMax153! - Remove `Either` / `EitherEncoded` from tool call results.\n\n  Specifically, the encoding of tool call results as an `Either` / `EitherEncoded` has been removed and is replaced by encoding the tool call success / failure directly into the `result` property.\n\n  To allow type-safe discrimination between a tool call result which was a success vs. one that was a failure, an `isFailure` property has also been added to the `\"tool-result\"` part. If `isFailure` is `true`, then the tool call handler result was an error.\n\n  ```ts\n  import * as AnthropicClient from \"@effect/ai-anthropic/AnthropicClient\"\n  import * as AnthropicLanguageModel from \"@effect/ai-anthropic/AnthropicLanguageModel\"\n  import * as LanguageModel from \"@effect/ai/LanguageModel\"\n  import * as Tool from \"@effect/ai/Tool\"\n  import * as Toolkit from \"@effect/ai/Toolkit\"\n  import * as NodeHttpClient from \"@effect/platform-node/NodeHttpClient\"\n  import { Config, Effect, Layer, Schema, Stream } from \"effect\"\n\n  const Claude = AnthropicLanguageModel.model(\"claude-4-sonnet-20250514\")\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"An example of a tool with success and failure types\",\n    failureMode: \"return\", // Return errors in the response\n    parameters: { bar: Schema.Number },\n    success: Schema.Number,\n    failure: Schema.Struct({ reason: Schema.Literal(\"reason-1\", \"reason-2\") })\n  })\n\n  const MyToolkit = Toolkit.make(MyTool)\n\n  const MyToolkitLayer = MyToolkit.toLayer({\n    MyTool: () => Effect.succeed(42)\n  })\n\n  const program = LanguageModel.streamText({\n    prompt: \"Tell me about the meaning of life\",\n    toolkit: MyToolkit\n  }).pipe(\n    Stream.runForEach((part) => {\n      if (part.type === \"tool-result\" && part.name === \"MyTool\") {\n        // The `isFailure` property can be used to discriminate whether the result\n        // of a tool call is a success or a failure\n        if (part.isFailure) {\n          part.result\n          //   ^? { readonly reason: \"reason-1\" | \"reason-2\"; }\n        } else {\n          part.result\n          //   ^? number\n        }\n      }\n      return Effect.void\n    }),\n    Effect.provide(Claude)\n  )\n\n  const Anthropic = AnthropicClient.layerConfig({\n    apiKey: Config.redacted(\"ANTHROPIC_API_KEY\")\n  }).pipe(Layer.provide(NodeHttpClient.layerUndici))\n\n  program.pipe(Effect.provide([Anthropic, MyToolkitLayer]), Effect.runPromise)\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`4c3bdfb`](https://github.com/Effect-TS/effect/commit/4c3bdfbcbc2dcd7ecd6321df3e4a504af19de825)]:\n  - @effect/ai@0.31.0\n\n## 0.4.0\n\n### Minor Changes\n\n- [#5614](https://github.com/Effect-TS/effect/pull/5614) [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652) Thanks @IMax153! - Previously, tool call handler errors were _always_ raised as an expected error in the Effect `E` channel at the point of execution of the tool call handler (i.e. when a `generate*` method is invoked on a `LanguageModel`).\n\n  With this PR, the end user now has control over whether tool call handler errors should be raised as an Effect error, or returned by the SDK to allow, for example, sending that error information to another application.\n\n  ### Tool Call Specification\n\n  The `Tool.make` and `Tool.providerDefined` constructors now take an extra optional parameter called `failureMode`, which can be set to either `\"error\"` or `\"return\"`.\n\n  ```ts\n  import { Tool } from \"@effect/ai\"\n  import { Schema } from \"effect\"\n\n  const MyTool = Tool.make(\"MyTool\", {\n    description: \"My special tool\",\n    failureMode: \"return\" // \"error\" (default) or \"return\"\n    parameters: {\n      myParam: Schema.String\n    },\n    success: Schema.Struct({\n      mySuccess: Schema.String\n    }),\n    failure: Schema.Struct({\n      myFailure: Schema.String\n    })\n  })\n\n  ```\n\n  The semantics of `failureMode` are as follows:\n  - If set to `\"error\"` (the default), errors that occur during tool call handler execution will be returned in the error channel of the calling effect\n  - If set to `\"return\"`, errors that occur during tool call handler execution will be captured and returned as part of the tool call result\n\n  ### Response - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a large language model provider response is now represented as an `Either`.\n  - If the `result` is a `Left`, the `result` will be the `failure` specified in the tool call specification\n  - If the `result` is a `Right`, the `result` will be the `success` specified in the tool call specification\n\n  This is only relevant if the end user sets `failureMode` to `\"return\"`. If set to `\"error\"` (the default), then the `result` property will always be a `Right` with the successful result of the tool call handler.\n\n  Similarly the `encodedResult` field of a `\"tool-result\"` part will be represented as an `EitherEncoded`, where:\n  - `{ _tag: \"Left\", left: <failure> }` represents a tool call handler failure\n  - `{ _tag: \"Right\", right: <success> }` represents a tool call handler success\n\n  ### Prompt - Tool Result Parts\n\n  The `result` field of a `\"tool-result\"` part of a prompt will now only accept an `EitherEncoded` as specified above.\n\n### Patch Changes\n\n- Updated dependencies [[`6ae2f5d`](https://github.com/Effect-TS/effect/commit/6ae2f5da45a9ed9832605eca12b3e2bf2e2a1a67), [`c63e658`](https://github.com/Effect-TS/effect/commit/c63e6582244fbb50d31650c4b4ea0660fe194652)]:\n  - effect@3.18.4\n  - @effect/ai@0.30.0\n\n## 0.3.0\n\n### Patch Changes\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2), [`f8b93ac`](https://github.com/Effect-TS/effect/commit/f8b93ac6446efd3dd790778b0fc71d299a38f272)]:\n  - effect@3.18.0\n  - @effect/ai@0.29.0\n  - @effect/platform@0.92.0\n  - @effect/experimental@0.56.0\n\n## 0.2.1\n\n### Patch Changes\n\n- [#5571](https://github.com/Effect-TS/effect/pull/5571) [`122aa53`](https://github.com/Effect-TS/effect/commit/122aa53058ff008cf605cc2f0f0675a946c3cae9) Thanks @IMax153! - Ensure that AI provider clients filter response status for stream requests\n\n## 0.2.0\n\n### Patch Changes\n\n- Updated dependencies [[`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a)]:\n  - @effect/platform@0.91.0\n  - @effect/ai@0.28.0\n  - @effect/experimental@0.55.0\n\n## 0.1.0\n\n### Minor Changes\n\n- [#5521](https://github.com/Effect-TS/effect/pull/5521) [`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80) Thanks @IMax153! - Add Effect AI SDK provider integration package for OpenRouter\n\n### Patch Changes\n\n- [#5521](https://github.com/Effect-TS/effect/pull/5521) [`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80) Thanks @IMax153! - Fix provider metadata and parse tool call parameters safely\n\n- Updated dependencies [[`fa49bc8`](https://github.com/Effect-TS/effect/commit/fa49bc86b14599300d106f306ceaf82a79121b80)]:\n  - @effect/ai@0.27.1\n"
  },
  {
    "path": "packages/ai/openrouter/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Effectful Technologies Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/ai/openrouter/README.md",
    "content": "# `@effect/ai-openrouter`\n\n## Documentation\n\n- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/ai/openrouter).\n"
  },
  {
    "path": "packages/ai/openrouter/docgen.json",
    "content": "{\n  \"$schema\": \"../../../node_modules/@effect/docgen/schema.json\",\n  \"exclude\": [\"src/Generated.ts\", \"src/internal/**/*.ts\"],\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/ai/openrouter/src/\",\n  \"examplesCompilerOptions\": {\n    \"noEmit\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"module\": \"ES2022\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n    \"paths\": {\n      \"effect\": [\"../../../../effect/src/index.js\"],\n      \"effect/*\": [\"../../../../effect/src/*.js\"],\n      \"@effect/experimental\": [\"../../../../experimental/src/index.js\"],\n      \"@effect/experimental/*\": [\"../../../../experimental/src/*.js\"],\n      \"@effect/platform\": [\"../../../../platform/src/index.js\"],\n      \"@effect/platform/*\": [\"../../../../platform/src/*.js\"],\n      \"@effect/ai\": [\"../../../ai/src/index.js\"],\n      \"@effect/ai/*\": [\"../../../ai/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/ai/openrouter/package.json",
    "content": "{\n  \"name\": \"@effect/ai-openrouter\",\n  \"type\": \"module\",\n  \"version\": \"0.10.0\",\n  \"license\": \"MIT\",\n  \"description\": \"Effect modules for working with AI apis\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/ai/openrouter\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"keywords\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"peerDependencies\": {\n    \"@effect/ai\": \"workspace:^\",\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"effect\": \"workspace:^\"\n  },\n  \"devDependencies\": {\n    \"@effect/ai\": \"workspace:^\",\n    \"@effect/experimental\": \"workspace:^\",\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/platform-node\": \"workspace:^\",\n    \"@tim-smart/openapi-gen\": \"^0.4.10\",\n    \"effect\": \"workspace:^\"\n  }\n}\n"
  },
  {
    "path": "packages/ai/openrouter/scripts/generate.sh",
    "content": "#!/usr/bin/env bash\n\nset -euo pipefail\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &> /dev/null && pwd)\n\ntemp_dir=$(mktemp -d)\n\ncleanup() {\n  rm -rf \"${temp_dir}\"\n}\n\ntrap cleanup EXIT\n\nopenapi_spec_url=\"https://openrouter.ai/openapi.yaml\"\n# openapi_spec_url=\"https://spec.speakeasy.com/openrouter/sdk/open-router-chat-completions-api-with-code-samples\"\ntemp_file=\"${temp_dir}/openrouter.yaml\"\n\ntouch \"${temp_file}\"\ncurl \"${openapi_spec_url}\" > \"${temp_file}\"\n\necho \"/**\n * @since 1.0.0\n */\" > src/Generated.ts\n\npnpm openapi-gen -s \"${temp_file}\" >> src/Generated.ts\n\npnpm eslint --fix src/Generated.ts\n\ngit apply --reject --whitespace=fix \"${SCRIPT_DIR}/generated.patch\"\n"
  },
  {
    "path": "packages/ai/openrouter/scripts/generated.patch",
    "content": "diff --git a/packages/ai/openrouter/src/Generated.ts b/packages/ai/openrouter/src/Generated.ts\nindex 92a756c..837d7dd 100644\n--- a/packages/ai/openrouter/src/Generated.ts\n+++ b/packages/ai/openrouter/src/Generated.ts\n@@ -10,6 +10,10 @@ import * as Effect from \"effect/Effect\"\n import type { ParseError } from \"effect/ParseResult\"\n import * as S from \"effect/Schema\"\n \n+export class CacheControlEphemeral extends S.Class<CacheControlEphemeral>(\"CacheControlEphemeral\")({\n+  \"type\": S.Literal(\"ephemeral\")\n+}) {}\n+\n export class OpenResponsesReasoningFormat extends S.Literal(\n   \"unknown\",\n   \"openai-responses-v1\",\n@@ -51,6 +55,70 @@ export class OpenResponsesReasoning extends S.Class<OpenResponsesReasoning>(\"Ope\n   )\n }) {}\n \n+export class ReasoningDetailSummary extends S.Class<ReasoningDetailSummary>(\"ReasoningDetailSummary\")({\n+  id: S.optionalWith(S.String, { nullable: true }),\n+  type: S.Literal(\"reasoning.summary\"),\n+  index: S.optional(S.Number),\n+  format: S.optionalWith(OpenResponsesReasoningFormat, { nullable: true }),\n+  summary: S.String\n+}) {}\n+\n+export class ReasoningDetailEncrypted extends S.Class<ReasoningDetailEncrypted>(\"ReasoningDetailEncrypted\")({\n+  id: S.optionalWith(S.String, { nullable: true }),\n+  type: S.Literal(\"reasoning.encrypted\"),\n+  index: S.optional(S.Number),\n+  format: S.optionalWith(OpenResponsesReasoningFormat, { nullable: true }),\n+  data: S.String\n+}) {}\n+\n+export class ReasoningDetailText extends S.Class<ReasoningDetailText>(\"ReasoningDetailText\")({\n+  id: S.optionalWith(S.String, { nullable: true }),\n+  type: S.Literal(\"reasoning.text\"),\n+  index: S.optional(S.Number),\n+  format: S.optionalWith(OpenResponsesReasoningFormat, { nullable: true }),\n+  text: S.optionalWith(S.String, { nullable: true }),\n+  signature: S.optionalWith(S.String, { nullable: true })\n+}) {}\n+\n+export class ReasoningDetail extends S.Union(\n+  ReasoningDetailSummary,\n+  ReasoningDetailEncrypted,\n+  ReasoningDetailText\n+) {}\n+\n+export class FileAnnotationDetail extends S.Class<FileAnnotationDetail>(\"FileAnnotationDetail\")({\n+  \"type\": S.Literal(\"file\"),\n+  \"file\": S.Struct({\n+    \"hash\": S.String,\n+    \"name\": S.optionalWith(S.String, { nullable: true }),\n+    \"content\": S.Array(S.Union(\n+      S.Struct({\n+        \"type\": S.Literal(\"text\"),\n+        \"text\": S.String\n+      }),\n+      S.Struct({\n+        \"type\": S.Literal(\"image_url\"),\n+        \"image_url\": S.Struct({\n+          \"url\": S.String\n+        })\n+      })\n+    ))\n+  })\n+}) {}\n+\n+export class URLCitationAnnotationDetail extends S.Class<URLCitationAnnotationDetail>(\"URLCitationAnnotationDetail\")({\n+  \"type\": S.Literal(\"url_citation\"),\n+  \"url_citation\": S.Struct({\n+    \"end_index\": S.Number,\n+    \"start_index\": S.Number,\n+    \"title\": S.String,\n+    \"url\": S.String,\n+    \"content\": S.optionalWith(S.String, { nullable: true })\n+  })\n+}) {}\n+\n+export class AnnotationDetail extends S.Union(FileAnnotationDetail, URLCitationAnnotationDetail) {}\n+\n export class OpenResponsesEasyInputMessageType extends S.Literal(\"message\") {}\n \n export class OpenResponsesEasyInputMessageRoleEnum extends S.Literal(\"developer\") {}\n@@ -4637,7 +4705,7 @@ export class AssistantMessage extends S.Class<AssistantMessage>(\"AssistantMessag\n   \"tool_calls\": S.optionalWith(S.Array(ChatMessageToolCall), { nullable: true }),\n   \"refusal\": S.optionalWith(S.String, { nullable: true }),\n   \"reasoning\": S.optionalWith(S.String, { nullable: true }),\n-  \"reasoning_details\": S.optionalWith(S.Array(Schema2), { nullable: true }),\n+  \"reasoning_details\": S.optionalWith(S.Array(ReasoningDetail), { nullable: true }),\n   \"images\": S.optionalWith(\n     S.Array(S.Struct({\n       \"image_url\": S.Struct({\n@@ -4645,7 +4713,8 @@ export class AssistantMessage extends S.Class<AssistantMessage>(\"AssistantMessag\n       })\n     })),\n     { nullable: true }\n-  )\n+  ),\n+  \"annotations\": S.optionalWith(S.Array(AnnotationDetail), { nullable: true })\n }) {}\n \n export class ToolResponseMessage extends S.Class<ToolResponseMessage>(\"ToolResponseMessage\")({\n@@ -4873,15 +4942,15 @@ export class ChatMessageTokenLogprob extends S.Class<ChatMessageTokenLogprob>(\"C\n }) {}\n \n export class ChatMessageTokenLogprobs extends S.Class<ChatMessageTokenLogprobs>(\"ChatMessageTokenLogprobs\")({\n-  \"content\": S.NullOr(S.Array(ChatMessageTokenLogprob)),\n-  \"refusal\": S.NullOr(S.Array(ChatMessageTokenLogprob))\n+  \"content\": S.optionalWith(S.Array(ChatMessageTokenLogprob), { nullable: true }),\n+  \"refusal\": S.optionalWith(S.Array(ChatMessageTokenLogprob), { nullable: true })\n }) {}\n \n export class ChatResponseChoice extends S.Class<ChatResponseChoice>(\"ChatResponseChoice\")({\n   \"finish_reason\": S.NullOr(ChatCompletionFinishReason),\n   \"index\": S.Number,\n   \"message\": AssistantMessage,\n-  \"logprobs\": S.optionalWith(ChatMessageTokenLogprobs, { nullable: true })\n+  \"logprobs\": S.optionalWith(ChatMessageTokenLogprobs, { nullable: true }),\n }) {}\n \n export class ChatGenerationTokenUsage extends S.Class<ChatGenerationTokenUsage>(\"ChatGenerationTokenUsage\")({\n@@ -4905,11 +4974,16 @@ export class ChatGenerationTokenUsage extends S.Class<ChatGenerationTokenUsage>(\n       \"video_tokens\": S.optionalWith(S.Number, { nullable: true })\n     }),\n     { nullable: true }\n-  )\n+  ),\n+  \"cost\": S.optionalWith(S.Number, { nullable: true }),\n+  \"cost_details\": S.optionalWith(S.Struct({ upstream_inference_cost: S.optionalWith(S.Number, { nullable: true }) }), {\n+    nullable: true\n+  })\n }) {}\n \n export class ChatResponse extends S.Class<ChatResponse>(\"ChatResponse\")({\n   \"id\": S.String,\n+  \"provider\": S.optionalWith(S.String, { nullable: true }),\n   \"choices\": S.Array(ChatResponseChoice),\n   \"created\": S.Number,\n   \"model\": S.String,\n"
  },
  {
    "path": "packages/ai/openrouter/src/Generated.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientError from \"@effect/platform/HttpClientError\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as HttpClientResponse from \"@effect/platform/HttpClientResponse\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\n\nexport class CacheControlEphemeral extends S.Class<CacheControlEphemeral>(\"CacheControlEphemeral\")({\n  \"type\": S.Literal(\"ephemeral\")\n}) {}\n\nexport class OpenResponsesReasoningFormat extends S.Literal(\n  \"unknown\",\n  \"openai-responses-v1\",\n  \"azure-openai-responses-v1\",\n  \"xai-responses-v1\",\n  \"anthropic-claude-v1\",\n  \"google-gemini-v1\"\n) {}\n\nexport class OpenResponsesReasoningType extends S.Literal(\"reasoning\") {}\n\nexport class ReasoningTextContentType extends S.Literal(\"reasoning_text\") {}\n\nexport class ReasoningTextContent extends S.Class<ReasoningTextContent>(\"ReasoningTextContent\")({\n  \"type\": ReasoningTextContentType,\n  \"text\": S.String\n}) {}\n\nexport class ReasoningSummaryTextType extends S.Literal(\"summary_text\") {}\n\nexport class ReasoningSummaryText extends S.Class<ReasoningSummaryText>(\"ReasoningSummaryText\")({\n  \"type\": ReasoningSummaryTextType,\n  \"text\": S.String\n}) {}\n\nexport class OpenResponsesReasoningStatusEnum extends S.Literal(\"in_progress\") {}\n\nexport class OpenResponsesReasoning extends S.Class<OpenResponsesReasoning>(\"OpenResponsesReasoning\")({\n  \"signature\": S.optionalWith(S.String, { nullable: true }),\n  \"format\": S.optionalWith(OpenResponsesReasoningFormat, { nullable: true }),\n  \"type\": OpenResponsesReasoningType,\n  \"id\": S.String,\n  \"content\": S.optionalWith(S.Array(ReasoningTextContent), { nullable: true }),\n  \"summary\": S.Array(ReasoningSummaryText),\n  \"encrypted_content\": S.optionalWith(S.String, { nullable: true }),\n  \"status\": S.optionalWith(\n    S.Union(OpenResponsesReasoningStatusEnum, OpenResponsesReasoningStatusEnum, OpenResponsesReasoningStatusEnum),\n    { nullable: true }\n  )\n}) {}\n\nexport class ReasoningDetailSummary extends S.Class<ReasoningDetailSummary>(\"ReasoningDetailSummary\")({\n  id: S.optionalWith(S.String, { nullable: true }),\n  type: S.Literal(\"reasoning.summary\"),\n  index: S.optional(S.Number),\n  format: S.optionalWith(OpenResponsesReasoningFormat, { nullable: true }),\n  summary: S.String\n}) {}\n\nexport class ReasoningDetailEncrypted extends S.Class<ReasoningDetailEncrypted>(\"ReasoningDetailEncrypted\")({\n  id: S.optionalWith(S.String, { nullable: true }),\n  type: S.Literal(\"reasoning.encrypted\"),\n  index: S.optional(S.Number),\n  format: S.optionalWith(OpenResponsesReasoningFormat, { nullable: true }),\n  data: S.String\n}) {}\n\nexport class ReasoningDetailText extends S.Class<ReasoningDetailText>(\"ReasoningDetailText\")({\n  id: S.optionalWith(S.String, { nullable: true }),\n  type: S.Literal(\"reasoning.text\"),\n  index: S.optional(S.Number),\n  format: S.optionalWith(OpenResponsesReasoningFormat, { nullable: true }),\n  text: S.optionalWith(S.String, { nullable: true }),\n  signature: S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ReasoningDetail extends S.Union(\n  ReasoningDetailSummary,\n  ReasoningDetailEncrypted,\n  ReasoningDetailText\n) {}\n\nexport class FileAnnotationDetail extends S.Class<FileAnnotationDetail>(\"FileAnnotationDetail\")({\n  \"type\": S.Literal(\"file\"),\n  \"file\": S.Struct({\n    \"hash\": S.String,\n    \"name\": S.optionalWith(S.String, { nullable: true }),\n    \"content\": S.Array(S.Union(\n      S.Struct({\n        \"type\": S.Literal(\"text\"),\n        \"text\": S.String\n      }),\n      S.Struct({\n        \"type\": S.Literal(\"image_url\"),\n        \"image_url\": S.Struct({\n          \"url\": S.String\n        })\n      })\n    ))\n  })\n}) {}\n\nexport class URLCitationAnnotationDetail extends S.Class<URLCitationAnnotationDetail>(\"URLCitationAnnotationDetail\")({\n  \"type\": S.Literal(\"url_citation\"),\n  \"url_citation\": S.Struct({\n    \"end_index\": S.Number,\n    \"start_index\": S.Number,\n    \"title\": S.String,\n    \"url\": S.String,\n    \"content\": S.optionalWith(S.String, { nullable: true })\n  })\n}) {}\n\nexport class AnnotationDetail extends S.Union(FileAnnotationDetail, URLCitationAnnotationDetail) {}\n\nexport class OpenResponsesEasyInputMessageType extends S.Literal(\"message\") {}\n\nexport class OpenResponsesEasyInputMessageRoleEnum extends S.Literal(\"developer\") {}\n\nexport class ResponseInputTextType extends S.Literal(\"input_text\") {}\n\n/**\n * Text input content item\n */\nexport class ResponseInputText extends S.Class<ResponseInputText>(\"ResponseInputText\")({\n  \"type\": ResponseInputTextType,\n  \"text\": S.String\n}) {}\n\nexport class ResponseInputFileType extends S.Literal(\"input_file\") {}\n\n/**\n * File input content item\n */\nexport class ResponseInputFile extends S.Class<ResponseInputFile>(\"ResponseInputFile\")({\n  \"type\": ResponseInputFileType,\n  \"file_id\": S.optionalWith(S.String, { nullable: true }),\n  \"file_data\": S.optionalWith(S.String, { nullable: true }),\n  \"filename\": S.optionalWith(S.String, { nullable: true }),\n  \"file_url\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ResponseInputAudioType extends S.Literal(\"input_audio\") {}\n\nexport class ResponseInputAudioInputAudioFormat extends S.Literal(\"mp3\", \"wav\") {}\n\n/**\n * Audio input content item\n */\nexport class ResponseInputAudio extends S.Class<ResponseInputAudio>(\"ResponseInputAudio\")({\n  \"type\": ResponseInputAudioType,\n  \"input_audio\": S.Struct({\n    \"data\": S.String,\n    \"format\": ResponseInputAudioInputAudioFormat\n  })\n}) {}\n\nexport class ResponseInputVideoType extends S.Literal(\"input_video\") {}\n\n/**\n * Video input content item\n */\nexport class ResponseInputVideo extends S.Class<ResponseInputVideo>(\"ResponseInputVideo\")({\n  \"type\": ResponseInputVideoType,\n  /**\n   * A base64 data URL or remote URL that resolves to a video file\n   */\n  \"video_url\": S.String\n}) {}\n\nexport class OpenResponsesEasyInputMessage\n  extends S.Class<OpenResponsesEasyInputMessage>(\"OpenResponsesEasyInputMessage\")({\n    \"type\": S.optionalWith(OpenResponsesEasyInputMessageType, { nullable: true }),\n    \"role\": S.Union(\n      OpenResponsesEasyInputMessageRoleEnum,\n      OpenResponsesEasyInputMessageRoleEnum,\n      OpenResponsesEasyInputMessageRoleEnum,\n      OpenResponsesEasyInputMessageRoleEnum\n    ),\n    \"content\": S.Union(\n      S.Array(S.Union(\n        ResponseInputText,\n        /**\n         * Image input content item\n         */\n        S.Struct({\n          \"type\": S.Literal(\"input_image\"),\n          \"detail\": S.Literal(\"auto\", \"high\", \"low\"),\n          \"image_url\": S.optionalWith(S.String, { nullable: true })\n        }),\n        ResponseInputFile,\n        ResponseInputAudio,\n        ResponseInputVideo\n      )),\n      S.String\n    )\n  })\n{}\n\nexport class OpenResponsesInputMessageItemType extends S.Literal(\"message\") {}\n\nexport class OpenResponsesInputMessageItemRoleEnum extends S.Literal(\"developer\") {}\n\nexport class OpenResponsesInputMessageItem\n  extends S.Class<OpenResponsesInputMessageItem>(\"OpenResponsesInputMessageItem\")({\n    \"id\": S.optionalWith(S.String, { nullable: true }),\n    \"type\": S.optionalWith(OpenResponsesInputMessageItemType, { nullable: true }),\n    \"role\": S.Union(\n      OpenResponsesInputMessageItemRoleEnum,\n      OpenResponsesInputMessageItemRoleEnum,\n      OpenResponsesInputMessageItemRoleEnum\n    ),\n    \"content\": S.Array(S.Union(\n      ResponseInputText,\n      /**\n       * Image input content item\n       */\n      S.Struct({\n        \"type\": S.Literal(\"input_image\"),\n        \"detail\": S.Literal(\"auto\", \"high\", \"low\"),\n        \"image_url\": S.optionalWith(S.String, { nullable: true })\n      }),\n      ResponseInputFile,\n      ResponseInputAudio,\n      ResponseInputVideo\n    ))\n  })\n{}\n\nexport class OpenResponsesFunctionToolCallType extends S.Literal(\"function_call\") {}\n\nexport class ToolCallStatus extends S.Literal(\"in_progress\", \"completed\", \"incomplete\") {}\n\n/**\n * A function call initiated by the model\n */\nexport class OpenResponsesFunctionToolCall\n  extends S.Class<OpenResponsesFunctionToolCall>(\"OpenResponsesFunctionToolCall\")({\n    \"type\": OpenResponsesFunctionToolCallType,\n    \"call_id\": S.String,\n    \"name\": S.String,\n    \"arguments\": S.String,\n    \"id\": S.String,\n    \"status\": S.optionalWith(ToolCallStatus, { nullable: true })\n  })\n{}\n\nexport class OpenResponsesFunctionCallOutputType extends S.Literal(\"function_call_output\") {}\n\n/**\n * The output from a function call execution\n */\nexport class OpenResponsesFunctionCallOutput\n  extends S.Class<OpenResponsesFunctionCallOutput>(\"OpenResponsesFunctionCallOutput\")({\n    \"type\": OpenResponsesFunctionCallOutputType,\n    \"id\": S.optionalWith(S.String, { nullable: true }),\n    \"call_id\": S.String,\n    \"output\": S.String,\n    \"status\": S.optionalWith(ToolCallStatus, { nullable: true })\n  })\n{}\n\nexport class ResponsesOutputMessageRole extends S.Literal(\"assistant\") {}\n\nexport class ResponsesOutputMessageType extends S.Literal(\"message\") {}\n\nexport class ResponsesOutputMessageStatusEnum extends S.Literal(\"in_progress\") {}\n\nexport class ResponseOutputTextType extends S.Literal(\"output_text\") {}\n\nexport class FileCitationType extends S.Literal(\"file_citation\") {}\n\nexport class FileCitation extends S.Class<FileCitation>(\"FileCitation\")({\n  \"type\": FileCitationType,\n  \"file_id\": S.String,\n  \"filename\": S.String,\n  \"index\": S.Number\n}) {}\n\nexport class URLCitationType extends S.Literal(\"url_citation\") {}\n\nexport class URLCitation extends S.Class<URLCitation>(\"URLCitation\")({\n  \"type\": URLCitationType,\n  \"url\": S.String,\n  \"title\": S.String,\n  \"start_index\": S.Number,\n  \"end_index\": S.Number\n}) {}\n\nexport class FilePathType extends S.Literal(\"file_path\") {}\n\nexport class FilePath extends S.Class<FilePath>(\"FilePath\")({\n  \"type\": FilePathType,\n  \"file_id\": S.String,\n  \"index\": S.Number\n}) {}\n\nexport class OpenAIResponsesAnnotation extends S.Union(FileCitation, URLCitation, FilePath) {}\n\nexport class ResponseOutputText extends S.Class<ResponseOutputText>(\"ResponseOutputText\")({\n  \"type\": ResponseOutputTextType,\n  \"text\": S.String,\n  \"annotations\": S.optionalWith(S.Array(OpenAIResponsesAnnotation), { nullable: true }),\n  \"logprobs\": S.optionalWith(\n    S.Array(S.Struct({\n      \"token\": S.String,\n      \"bytes\": S.Array(S.Number),\n      \"logprob\": S.Number,\n      \"top_logprobs\": S.Array(S.Struct({\n        \"token\": S.String,\n        \"bytes\": S.Array(S.Number),\n        \"logprob\": S.Number\n      }))\n    })),\n    { nullable: true }\n  )\n}) {}\n\nexport class OpenAIResponsesRefusalContentType extends S.Literal(\"refusal\") {}\n\nexport class OpenAIResponsesRefusalContent\n  extends S.Class<OpenAIResponsesRefusalContent>(\"OpenAIResponsesRefusalContent\")({\n    \"type\": OpenAIResponsesRefusalContentType,\n    \"refusal\": S.String\n  })\n{}\n\nexport class ResponsesOutputMessage extends S.Class<ResponsesOutputMessage>(\"ResponsesOutputMessage\")({\n  \"id\": S.String,\n  \"role\": ResponsesOutputMessageRole,\n  \"type\": ResponsesOutputMessageType,\n  \"status\": S.optionalWith(\n    S.Union(ResponsesOutputMessageStatusEnum, ResponsesOutputMessageStatusEnum, ResponsesOutputMessageStatusEnum),\n    { nullable: true }\n  ),\n  \"content\": S.Array(S.Union(ResponseOutputText, OpenAIResponsesRefusalContent))\n}) {}\n\n/**\n * The format of the reasoning content\n */\nexport class ResponsesOutputItemReasoningFormat extends S.Literal(\n  \"unknown\",\n  \"openai-responses-v1\",\n  \"azure-openai-responses-v1\",\n  \"xai-responses-v1\",\n  \"anthropic-claude-v1\",\n  \"google-gemini-v1\"\n) {}\n\nexport class ResponsesOutputItemReasoningType extends S.Literal(\"reasoning\") {}\n\nexport class ResponsesOutputItemReasoningStatusEnum extends S.Literal(\"in_progress\") {}\n\nexport class ResponsesOutputItemReasoning\n  extends S.Class<ResponsesOutputItemReasoning>(\"ResponsesOutputItemReasoning\")({\n    /**\n     * A signature for the reasoning content, used for verification\n     */\n    \"signature\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The format of the reasoning content\n     */\n    \"format\": S.optionalWith(ResponsesOutputItemReasoningFormat, { nullable: true }),\n    \"type\": ResponsesOutputItemReasoningType,\n    \"id\": S.String,\n    \"content\": S.optionalWith(S.Array(ReasoningTextContent), { nullable: true }),\n    \"summary\": S.Array(ReasoningSummaryText),\n    \"encrypted_content\": S.optionalWith(S.String, { nullable: true }),\n    \"status\": S.optionalWith(\n      S.Union(\n        ResponsesOutputItemReasoningStatusEnum,\n        ResponsesOutputItemReasoningStatusEnum,\n        ResponsesOutputItemReasoningStatusEnum\n      ),\n      { nullable: true }\n    )\n  })\n{}\n\nexport class ResponsesOutputItemFunctionCallType extends S.Literal(\"function_call\") {}\n\nexport class ResponsesOutputItemFunctionCallStatusEnum extends S.Literal(\"in_progress\") {}\n\nexport class ResponsesOutputItemFunctionCall\n  extends S.Class<ResponsesOutputItemFunctionCall>(\"ResponsesOutputItemFunctionCall\")({\n    \"type\": ResponsesOutputItemFunctionCallType,\n    \"id\": S.optionalWith(S.String, { nullable: true }),\n    \"name\": S.String,\n    \"arguments\": S.String,\n    \"call_id\": S.String,\n    \"status\": S.optionalWith(\n      S.Union(\n        ResponsesOutputItemFunctionCallStatusEnum,\n        ResponsesOutputItemFunctionCallStatusEnum,\n        ResponsesOutputItemFunctionCallStatusEnum\n      ),\n      { nullable: true }\n    )\n  })\n{}\n\nexport class ResponsesWebSearchCallOutputType extends S.Literal(\"web_search_call\") {}\n\nexport class WebSearchStatus extends S.Literal(\"completed\", \"searching\", \"in_progress\", \"failed\") {}\n\nexport class ResponsesWebSearchCallOutput\n  extends S.Class<ResponsesWebSearchCallOutput>(\"ResponsesWebSearchCallOutput\")({\n    \"type\": ResponsesWebSearchCallOutputType,\n    \"id\": S.String,\n    \"status\": WebSearchStatus\n  })\n{}\n\nexport class ResponsesOutputItemFileSearchCallType extends S.Literal(\"file_search_call\") {}\n\nexport class ResponsesOutputItemFileSearchCall\n  extends S.Class<ResponsesOutputItemFileSearchCall>(\"ResponsesOutputItemFileSearchCall\")({\n    \"type\": ResponsesOutputItemFileSearchCallType,\n    \"id\": S.String,\n    \"queries\": S.Array(S.String),\n    \"status\": WebSearchStatus\n  })\n{}\n\nexport class ResponsesImageGenerationCallType extends S.Literal(\"image_generation_call\") {}\n\nexport class ImageGenerationStatus extends S.Literal(\"in_progress\", \"completed\", \"generating\", \"failed\") {}\n\nexport class ResponsesImageGenerationCall\n  extends S.Class<ResponsesImageGenerationCall>(\"ResponsesImageGenerationCall\")({\n    \"type\": ResponsesImageGenerationCallType,\n    \"id\": S.String,\n    \"result\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"status\": ImageGenerationStatus\n  })\n{}\n\n/**\n * Input for a response request - can be a string or array of items\n */\nexport class OpenResponsesInput extends S.Union(\n  S.String,\n  S.Array(\n    S.Union(\n      OpenResponsesReasoning,\n      OpenResponsesEasyInputMessage,\n      OpenResponsesInputMessageItem,\n      OpenResponsesFunctionToolCall,\n      OpenResponsesFunctionCallOutput,\n      ResponsesOutputMessage,\n      ResponsesOutputItemReasoning,\n      ResponsesOutputItemFunctionCall,\n      ResponsesWebSearchCallOutput,\n      ResponsesOutputItemFileSearchCall,\n      ResponsesImageGenerationCall\n    )\n  )\n) {}\n\n/**\n * Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed.\n */\nexport class OpenResponsesRequestMetadata extends S.Record({ key: S.String, value: S.Unknown }) {}\n\nexport class OpenResponsesWebSearchPreviewToolType extends S.Literal(\"web_search_preview\") {}\n\n/**\n * Size of the search context for web search tools\n */\nexport class ResponsesSearchContextSize extends S.Literal(\"low\", \"medium\", \"high\") {}\n\nexport class WebSearchPreviewToolUserLocationType extends S.Literal(\"approximate\") {}\n\nexport class WebSearchPreviewToolUserLocation\n  extends S.Class<WebSearchPreviewToolUserLocation>(\"WebSearchPreviewToolUserLocation\")({\n    \"type\": WebSearchPreviewToolUserLocationType,\n    \"city\": S.optionalWith(S.String, { nullable: true }),\n    \"country\": S.optionalWith(S.String, { nullable: true }),\n    \"region\": S.optionalWith(S.String, { nullable: true }),\n    \"timezone\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * Web search preview tool configuration\n */\nexport class OpenResponsesWebSearchPreviewTool\n  extends S.Class<OpenResponsesWebSearchPreviewTool>(\"OpenResponsesWebSearchPreviewTool\")({\n    \"type\": OpenResponsesWebSearchPreviewToolType,\n    \"search_context_size\": S.optionalWith(ResponsesSearchContextSize, { nullable: true }),\n    \"user_location\": S.optionalWith(WebSearchPreviewToolUserLocation, { nullable: true })\n  })\n{}\n\nexport class OpenResponsesWebSearchPreview20250311ToolType extends S.Literal(\"web_search_preview_2025_03_11\") {}\n\n/**\n * Web search preview tool configuration (2025-03-11 version)\n */\nexport class OpenResponsesWebSearchPreview20250311Tool\n  extends S.Class<OpenResponsesWebSearchPreview20250311Tool>(\"OpenResponsesWebSearchPreview20250311Tool\")({\n    \"type\": OpenResponsesWebSearchPreview20250311ToolType,\n    \"search_context_size\": S.optionalWith(ResponsesSearchContextSize, { nullable: true }),\n    \"user_location\": S.optionalWith(WebSearchPreviewToolUserLocation, { nullable: true })\n  })\n{}\n\nexport class OpenResponsesWebSearchToolType extends S.Literal(\"web_search\") {}\n\nexport class ResponsesWebSearchUserLocationType extends S.Literal(\"approximate\") {}\n\n/**\n * User location information for web search\n */\nexport class ResponsesWebSearchUserLocation\n  extends S.Class<ResponsesWebSearchUserLocation>(\"ResponsesWebSearchUserLocation\")({\n    \"type\": S.optionalWith(ResponsesWebSearchUserLocationType, { nullable: true }),\n    \"city\": S.optionalWith(S.String, { nullable: true }),\n    \"country\": S.optionalWith(S.String, { nullable: true }),\n    \"region\": S.optionalWith(S.String, { nullable: true }),\n    \"timezone\": S.optionalWith(S.String, { nullable: true })\n  })\n{}\n\n/**\n * Web search tool configuration\n */\nexport class OpenResponsesWebSearchTool extends S.Class<OpenResponsesWebSearchTool>(\"OpenResponsesWebSearchTool\")({\n  \"type\": OpenResponsesWebSearchToolType,\n  \"filters\": S.optionalWith(\n    S.Struct({\n      \"allowed_domains\": S.optionalWith(S.Array(S.String), { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"search_context_size\": S.optionalWith(ResponsesSearchContextSize, { nullable: true }),\n  \"user_location\": S.optionalWith(ResponsesWebSearchUserLocation, { nullable: true })\n}) {}\n\nexport class OpenResponsesWebSearch20250826ToolType extends S.Literal(\"web_search_2025_08_26\") {}\n\n/**\n * Web search tool configuration (2025-08-26 version)\n */\nexport class OpenResponsesWebSearch20250826Tool\n  extends S.Class<OpenResponsesWebSearch20250826Tool>(\"OpenResponsesWebSearch20250826Tool\")({\n    \"type\": OpenResponsesWebSearch20250826ToolType,\n    \"filters\": S.optionalWith(\n      S.Struct({\n        \"allowed_domains\": S.optionalWith(S.Array(S.String), { nullable: true })\n      }),\n      { nullable: true }\n    ),\n    \"search_context_size\": S.optionalWith(ResponsesSearchContextSize, { nullable: true }),\n    \"user_location\": S.optionalWith(ResponsesWebSearchUserLocation, { nullable: true })\n  })\n{}\n\nexport class OpenAIResponsesToolChoiceEnum extends S.Literal(\"required\") {}\n\nexport class OpenAIResponsesToolChoiceEnumType extends S.Literal(\"function\") {}\n\nexport class OpenAIResponsesToolChoiceEnumTypeEnum extends S.Literal(\"web_search_preview\") {}\n\nexport class OpenAIResponsesToolChoice extends S.Union(\n  OpenAIResponsesToolChoiceEnum,\n  OpenAIResponsesToolChoiceEnum,\n  OpenAIResponsesToolChoiceEnum,\n  S.Struct({\n    \"type\": OpenAIResponsesToolChoiceEnumType,\n    \"name\": S.String\n  }),\n  S.Struct({\n    \"type\": S.Union(OpenAIResponsesToolChoiceEnumTypeEnum, OpenAIResponsesToolChoiceEnumTypeEnum)\n  })\n) {}\n\nexport class ResponsesFormatTextType extends S.Literal(\"text\") {}\n\n/**\n * Plain text response format\n */\nexport class ResponsesFormatText extends S.Class<ResponsesFormatText>(\"ResponsesFormatText\")({\n  \"type\": ResponsesFormatTextType\n}) {}\n\nexport class ResponsesFormatJSONObjectType extends S.Literal(\"json_object\") {}\n\n/**\n * JSON object response format\n */\nexport class ResponsesFormatJSONObject extends S.Class<ResponsesFormatJSONObject>(\"ResponsesFormatJSONObject\")({\n  \"type\": ResponsesFormatJSONObjectType\n}) {}\n\nexport class ResponsesFormatTextJSONSchemaConfigType extends S.Literal(\"json_schema\") {}\n\n/**\n * JSON schema constrained response format\n */\nexport class ResponsesFormatTextJSONSchemaConfig\n  extends S.Class<ResponsesFormatTextJSONSchemaConfig>(\"ResponsesFormatTextJSONSchemaConfig\")({\n    \"type\": ResponsesFormatTextJSONSchemaConfigType,\n    \"name\": S.String,\n    \"description\": S.optionalWith(S.String, { nullable: true }),\n    \"strict\": S.optionalWith(S.Boolean, { nullable: true }),\n    \"schema\": S.Record({ key: S.String, value: S.Unknown })\n  })\n{}\n\n/**\n * Text response format configuration\n */\nexport class ResponseFormatTextConfig\n  extends S.Union(ResponsesFormatText, ResponsesFormatJSONObject, ResponsesFormatTextJSONSchemaConfig)\n{}\n\nexport class OpenResponsesResponseTextVerbosity extends S.Literal(\"high\", \"low\", \"medium\") {}\n\n/**\n * Text output configuration including format and verbosity\n */\nexport class OpenResponsesResponseText extends S.Class<OpenResponsesResponseText>(\"OpenResponsesResponseText\")({\n  \"format\": S.optionalWith(ResponseFormatTextConfig, { nullable: true }),\n  \"verbosity\": S.optionalWith(OpenResponsesResponseTextVerbosity, { nullable: true })\n}) {}\n\nexport class OpenAIResponsesReasoningEffort extends S.Literal(\"xhigh\", \"high\", \"medium\", \"low\", \"minimal\", \"none\") {}\n\nexport class ReasoningSummaryVerbosity extends S.Literal(\"auto\", \"concise\", \"detailed\") {}\n\nexport class OpenResponsesReasoningConfig\n  extends S.Class<OpenResponsesReasoningConfig>(\"OpenResponsesReasoningConfig\")({\n    \"max_tokens\": S.optionalWith(S.Number, { nullable: true }),\n    \"enabled\": S.optionalWith(S.Boolean, { nullable: true }),\n    \"effort\": S.optionalWith(OpenAIResponsesReasoningEffort, { nullable: true }),\n    \"summary\": S.optionalWith(ReasoningSummaryVerbosity, { nullable: true })\n  })\n{}\n\nexport class ResponsesOutputModality extends S.Literal(\"text\", \"image\") {}\n\nexport class OpenAIResponsesPrompt extends S.Class<OpenAIResponsesPrompt>(\"OpenAIResponsesPrompt\")({\n  \"id\": S.String,\n  \"variables\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class OpenAIResponsesIncludable extends S.Literal(\n  \"file_search_call.results\",\n  \"message.input_image.image_url\",\n  \"computer_call_output.output.image_url\",\n  \"reasoning.encrypted_content\",\n  \"code_interpreter_call.outputs\"\n) {}\n\nexport class OpenResponsesRequestServiceTier extends S.Literal(\"auto\") {}\n\nexport class OpenResponsesRequestTruncationEnum extends S.Literal(\"auto\", \"disabled\") {}\n\nexport class OpenResponsesRequestTruncation extends OpenResponsesRequestTruncationEnum {}\n\n/**\n * Data collection setting. If no available model provider meets the requirement, your request will return an error.\n * - allow: (default) allow providers which store user data non-transiently and may train on it\n *\n * - deny: use only providers which do not collect user data.\n */\nexport class DataCollection extends S.Literal(\"deny\", \"allow\") {}\n\nexport class ProviderName extends S.Literal(\n  \"AI21\",\n  \"AionLabs\",\n  \"Alibaba\",\n  \"Amazon Bedrock\",\n  \"Amazon Nova\",\n  \"Anthropic\",\n  \"Arcee AI\",\n  \"AtlasCloud\",\n  \"Avian\",\n  \"Azure\",\n  \"BaseTen\",\n  \"BytePlus\",\n  \"Black Forest Labs\",\n  \"Cerebras\",\n  \"Chutes\",\n  \"Cirrascale\",\n  \"Clarifai\",\n  \"Cloudflare\",\n  \"Cohere\",\n  \"Crusoe\",\n  \"DeepInfra\",\n  \"DeepSeek\",\n  \"Featherless\",\n  \"Fireworks\",\n  \"Friendli\",\n  \"GMICloud\",\n  \"Google\",\n  \"Google AI Studio\",\n  \"Groq\",\n  \"Hyperbolic\",\n  \"Inception\",\n  \"Inceptron\",\n  \"InferenceNet\",\n  \"Infermatic\",\n  \"Inflection\",\n  \"Liquid\",\n  \"Mara\",\n  \"Mancer 2\",\n  \"Minimax\",\n  \"ModelRun\",\n  \"Mistral\",\n  \"Modular\",\n  \"Moonshot AI\",\n  \"Morph\",\n  \"NCompass\",\n  \"Nebius\",\n  \"NextBit\",\n  \"Novita\",\n  \"Nvidia\",\n  \"OpenAI\",\n  \"OpenInference\",\n  \"Parasail\",\n  \"Perplexity\",\n  \"Phala\",\n  \"Relace\",\n  \"SambaNova\",\n  \"Seed\",\n  \"SiliconFlow\",\n  \"Sourceful\",\n  \"Stealth\",\n  \"StreamLake\",\n  \"Switchpoint\",\n  \"Together\",\n  \"Upstage\",\n  \"Venice\",\n  \"WandB\",\n  \"Xiaomi\",\n  \"xAI\",\n  \"Z.AI\",\n  \"FakeProvider\"\n) {}\n\nexport class Quantization extends S.Literal(\"int4\", \"int8\", \"fp4\", \"fp6\", \"fp8\", \"fp16\", \"bf16\", \"fp32\", \"unknown\") {}\n\nexport class ProviderSort extends S.Literal(\"price\", \"throughput\", \"latency\") {}\n\nexport class ProviderSortConfigPartitionEnum extends S.Literal(\"model\", \"none\") {}\n\nexport class ProviderSortConfig extends S.Class<ProviderSortConfig>(\"ProviderSortConfig\")({\n  \"by\": S.optionalWith(ProviderSort, { nullable: true }),\n  \"partition\": S.optionalWith(ProviderSortConfigPartitionEnum, { nullable: true })\n}) {}\n\n/**\n * A value in string format that is a large number\n */\nexport class BigNumberUnion extends S.String {}\n\n/**\n * Percentile-based throughput cutoffs. All specified cutoffs must be met for an endpoint to be preferred.\n */\nexport class PercentileThroughputCutoffs extends S.Class<PercentileThroughputCutoffs>(\"PercentileThroughputCutoffs\")({\n  /**\n   * Minimum p50 throughput (tokens/sec)\n   */\n  \"p50\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Minimum p75 throughput (tokens/sec)\n   */\n  \"p75\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Minimum p90 throughput (tokens/sec)\n   */\n  \"p90\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Minimum p99 throughput (tokens/sec)\n   */\n  \"p99\": S.optionalWith(S.Number, { nullable: true })\n}) {}\n\n/**\n * Preferred minimum throughput (in tokens per second). Can be a number (applies to p50) or an object with percentile-specific cutoffs. Endpoints below the threshold(s) may still be used, but are deprioritized in routing. When using fallback models, this may cause a fallback model to be used instead of the primary model if it meets the threshold.\n */\nexport class PreferredMinThroughput extends S.Union(S.Number, PercentileThroughputCutoffs) {}\n\n/**\n * Percentile-based latency cutoffs. All specified cutoffs must be met for an endpoint to be preferred.\n */\nexport class PercentileLatencyCutoffs extends S.Class<PercentileLatencyCutoffs>(\"PercentileLatencyCutoffs\")({\n  /**\n   * Maximum p50 latency (seconds)\n   */\n  \"p50\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Maximum p75 latency (seconds)\n   */\n  \"p75\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Maximum p90 latency (seconds)\n   */\n  \"p90\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Maximum p99 latency (seconds)\n   */\n  \"p99\": S.optionalWith(S.Number, { nullable: true })\n}) {}\n\n/**\n * Preferred maximum latency (in seconds). Can be a number (applies to p50) or an object with percentile-specific cutoffs. Endpoints above the threshold(s) may still be used, but are deprioritized in routing. When using fallback models, this may cause a fallback model to be used instead of the primary model if it meets the threshold.\n */\nexport class PreferredMaxLatency extends S.Union(S.Number, PercentileLatencyCutoffs) {}\n\n/**\n * The search engine to use for web search.\n */\nexport class WebSearchEngine extends S.Literal(\"native\", \"exa\") {}\n\n/**\n * The engine to use for parsing PDF files.\n */\nexport class PDFParserEngine extends S.Literal(\"mistral-ocr\", \"pdf-text\", \"native\") {}\n\n/**\n * Options for PDF parsing.\n */\nexport class PDFParserOptions extends S.Class<PDFParserOptions>(\"PDFParserOptions\")({\n  \"engine\": S.optionalWith(PDFParserEngine, { nullable: true })\n}) {}\n\n/**\n * **DEPRECATED** Use providers.sort.partition instead. Backwards-compatible alias for providers.sort.partition. Accepts legacy values: \"fallback\" (maps to \"model\"), \"sort\" (maps to \"none\").\n */\nexport class OpenResponsesRequestRoute extends S.Literal(\"fallback\", \"sort\") {}\n\n/**\n * Request schema for Responses endpoint\n */\nexport class OpenResponsesRequest extends S.Class<OpenResponsesRequest>(\"OpenResponsesRequest\")({\n  \"input\": S.optionalWith(OpenResponsesInput, { nullable: true }),\n  \"instructions\": S.optionalWith(S.String, { nullable: true }),\n  \"metadata\": S.optionalWith(OpenResponsesRequestMetadata, { nullable: true }),\n  \"tools\": S.optionalWith(\n    S.Array(S.Union(\n      /**\n       * Function tool definition\n       */\n      S.Struct({}),\n      OpenResponsesWebSearchPreviewTool,\n      OpenResponsesWebSearchPreview20250311Tool,\n      OpenResponsesWebSearchTool,\n      OpenResponsesWebSearch20250826Tool\n    )),\n    { nullable: true }\n  ),\n  \"tool_choice\": S.optionalWith(OpenAIResponsesToolChoice, { nullable: true }),\n  \"parallel_tool_calls\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"model\": S.optionalWith(S.String, { nullable: true }),\n  \"models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"text\": S.optionalWith(OpenResponsesResponseText, { nullable: true }),\n  \"reasoning\": S.optionalWith(OpenResponsesReasoningConfig, { nullable: true }),\n  \"max_output_tokens\": S.optionalWith(S.Number, { nullable: true }),\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0)), { nullable: true }),\n  \"top_logprobs\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(20)), { nullable: true }),\n  \"max_tool_calls\": S.optionalWith(S.Int, { nullable: true }),\n  \"presence_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true\n  }),\n  \"frequency_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true\n  }),\n  \"top_k\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/features/multimodal/image-generation for more details.\n   */\n  \"image_config\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  /**\n   * Output modalities for the response. Supported values are \"text\" and \"image\".\n   */\n  \"modalities\": S.optionalWith(S.Array(ResponsesOutputModality), { nullable: true }),\n  \"prompt_cache_key\": S.optionalWith(S.String, { nullable: true }),\n  \"previous_response_id\": S.optionalWith(S.String, { nullable: true }),\n  \"prompt\": S.optionalWith(OpenAIResponsesPrompt, { nullable: true }),\n  \"include\": S.optionalWith(S.Array(OpenAIResponsesIncludable), { nullable: true }),\n  \"background\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"safety_identifier\": S.optionalWith(S.String, { nullable: true }),\n  \"store\": S.optionalWith(S.Literal(false), { nullable: true, default: () => false as const }),\n  \"service_tier\": S.optionalWith(OpenResponsesRequestServiceTier, { nullable: true, default: () => \"auto\" as const }),\n  \"truncation\": S.optionalWith(OpenResponsesRequestTruncation, { nullable: true }),\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  /**\n   * When multiple model providers are available, optionally indicate your routing preference.\n   */\n  \"provider\": S.optionalWith(\n    S.Struct({\n      /**\n       * Whether to allow backup providers to serve requests\n       * - true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider.\n       * - false: use only the primary/custom provider, and return the upstream error if it's unavailable.\n       */\n      \"allow_fallbacks\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest.\n       */\n      \"require_parameters\": S.optionalWith(S.Boolean, { nullable: true }),\n      \"data_collection\": S.optionalWith(DataCollection, { nullable: true }),\n      /**\n       * Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used.\n       */\n      \"zdr\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used.\n       */\n      \"enforce_distillable_text\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message.\n       */\n      \"order\": S.optionalWith(S.Array(S.Union(ProviderName, S.String)), { nullable: true }),\n      /**\n       * List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request.\n       */\n      \"only\": S.optionalWith(S.Array(S.Union(ProviderName, S.String)), { nullable: true }),\n      /**\n       * List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request.\n       */\n      \"ignore\": S.optionalWith(S.Array(S.Union(ProviderName, S.String)), { nullable: true }),\n      /**\n       * A list of quantization levels to filter the provider by.\n       */\n      \"quantizations\": S.optionalWith(S.Array(Quantization), { nullable: true }),\n      /**\n       * The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed.\n       */\n      \"sort\": S.optionalWith(S.Union(ProviderSort, ProviderSortConfig), { nullable: true }),\n      /**\n       * The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.\n       */\n      \"max_price\": S.optionalWith(\n        S.Struct({\n          \"prompt\": S.optionalWith(BigNumberUnion, { nullable: true }),\n          \"completion\": S.optionalWith(BigNumberUnion, { nullable: true }),\n          \"image\": S.optionalWith(BigNumberUnion, { nullable: true }),\n          \"audio\": S.optionalWith(BigNumberUnion, { nullable: true }),\n          \"request\": S.optionalWith(BigNumberUnion, { nullable: true })\n        }),\n        { nullable: true }\n      ),\n      \"preferred_min_throughput\": S.optionalWith(PreferredMinThroughput, { nullable: true }),\n      \"preferred_max_latency\": S.optionalWith(PreferredMaxLatency, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * Plugins you want to enable for this request, including their settings.\n   */\n  \"plugins\": S.optionalWith(\n    S.Array(S.Union(\n      S.Struct({\n        \"id\": S.Literal(\"auto-router\"),\n        /**\n         * Set to false to disable the auto-router plugin for this request. Defaults to true.\n         */\n        \"enabled\": S.optionalWith(S.Boolean, { nullable: true }),\n        /**\n         * List of model patterns to filter which models the auto-router can route between. Supports wildcards (e.g., \"anthropic/*\" matches all Anthropic models). When not specified, uses the default supported models list.\n         */\n        \"allowed_models\": S.optionalWith(S.Array(S.String), { nullable: true })\n      }),\n      S.Struct({\n        \"id\": S.Literal(\"moderation\")\n      }),\n      S.Struct({\n        \"id\": S.Literal(\"web\"),\n        /**\n         * Set to false to disable the web-search plugin for this request. Defaults to true.\n         */\n        \"enabled\": S.optionalWith(S.Boolean, { nullable: true }),\n        \"max_results\": S.optionalWith(S.Number, { nullable: true }),\n        \"search_prompt\": S.optionalWith(S.String, { nullable: true }),\n        \"engine\": S.optionalWith(WebSearchEngine, { nullable: true })\n      }),\n      S.Struct({\n        \"id\": S.Literal(\"file-parser\"),\n        /**\n         * Set to false to disable the file-parser plugin for this request. Defaults to true.\n         */\n        \"enabled\": S.optionalWith(S.Boolean, { nullable: true }),\n        \"pdf\": S.optionalWith(PDFParserOptions, { nullable: true })\n      }),\n      S.Struct({\n        \"id\": S.Literal(\"response-healing\"),\n        /**\n         * Set to false to disable the response-healing plugin for this request. Defaults to true.\n         */\n        \"enabled\": S.optionalWith(S.Boolean, { nullable: true })\n      })\n    )),\n    { nullable: true }\n  ),\n  /**\n   * **DEPRECATED** Use providers.sort.partition instead. Backwards-compatible alias for providers.sort.partition. Accepts legacy values: \"fallback\" (maps to \"model\"), \"sort\" (maps to \"none\").\n   */\n  \"route\": S.optionalWith(OpenResponsesRequestRoute, { nullable: true }),\n  /**\n   * A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters.\n   */\n  \"user\": S.optionalWith(S.String.pipe(S.maxLength(128)), { nullable: true }),\n  /**\n   * A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 128 characters.\n   */\n  \"session_id\": S.optionalWith(S.String.pipe(S.maxLength(128)), { nullable: true })\n}) {}\n\nexport class OutputMessageRole extends S.Literal(\"assistant\") {}\n\nexport class OutputMessageType extends S.Literal(\"message\") {}\n\nexport class OutputMessageStatusEnum extends S.Literal(\"in_progress\") {}\n\nexport class OutputMessage extends S.Class<OutputMessage>(\"OutputMessage\")({\n  \"id\": S.String,\n  \"role\": OutputMessageRole,\n  \"type\": OutputMessageType,\n  \"status\": S.optionalWith(S.Union(OutputMessageStatusEnum, OutputMessageStatusEnum, OutputMessageStatusEnum), {\n    nullable: true\n  }),\n  \"content\": S.Array(S.Union(ResponseOutputText, OpenAIResponsesRefusalContent))\n}) {}\n\nexport class OutputItemReasoningType extends S.Literal(\"reasoning\") {}\n\nexport class OutputItemReasoningStatusEnum extends S.Literal(\"in_progress\") {}\n\nexport class OutputItemReasoning extends S.Class<OutputItemReasoning>(\"OutputItemReasoning\")({\n  \"type\": OutputItemReasoningType,\n  \"id\": S.String,\n  \"content\": S.optionalWith(S.Array(ReasoningTextContent), { nullable: true }),\n  \"summary\": S.Array(ReasoningSummaryText),\n  \"encrypted_content\": S.optionalWith(S.String, { nullable: true }),\n  \"status\": S.optionalWith(\n    S.Union(OutputItemReasoningStatusEnum, OutputItemReasoningStatusEnum, OutputItemReasoningStatusEnum),\n    { nullable: true }\n  )\n}) {}\n\nexport class OutputItemFunctionCallType extends S.Literal(\"function_call\") {}\n\nexport class OutputItemFunctionCallStatusEnum extends S.Literal(\"in_progress\") {}\n\nexport class OutputItemFunctionCall extends S.Class<OutputItemFunctionCall>(\"OutputItemFunctionCall\")({\n  \"type\": OutputItemFunctionCallType,\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  \"name\": S.String,\n  \"arguments\": S.String,\n  \"call_id\": S.String,\n  \"status\": S.optionalWith(\n    S.Union(OutputItemFunctionCallStatusEnum, OutputItemFunctionCallStatusEnum, OutputItemFunctionCallStatusEnum),\n    { nullable: true }\n  )\n}) {}\n\nexport class OutputItemWebSearchCallType extends S.Literal(\"web_search_call\") {}\n\nexport class OutputItemWebSearchCall extends S.Class<OutputItemWebSearchCall>(\"OutputItemWebSearchCall\")({\n  \"type\": OutputItemWebSearchCallType,\n  \"id\": S.String,\n  \"status\": WebSearchStatus\n}) {}\n\nexport class OutputItemFileSearchCallType extends S.Literal(\"file_search_call\") {}\n\nexport class OutputItemFileSearchCall extends S.Class<OutputItemFileSearchCall>(\"OutputItemFileSearchCall\")({\n  \"type\": OutputItemFileSearchCallType,\n  \"id\": S.String,\n  \"queries\": S.Array(S.String),\n  \"status\": WebSearchStatus\n}) {}\n\nexport class OutputItemImageGenerationCallType extends S.Literal(\"image_generation_call\") {}\n\nexport class OutputItemImageGenerationCall\n  extends S.Class<OutputItemImageGenerationCall>(\"OutputItemImageGenerationCall\")({\n    \"type\": OutputItemImageGenerationCallType,\n    \"id\": S.String,\n    \"result\": S.optionalWith(S.NullOr(S.String), { default: () => null }),\n    \"status\": ImageGenerationStatus\n  })\n{}\n\nexport class OpenAIResponsesUsage extends S.Class<OpenAIResponsesUsage>(\"OpenAIResponsesUsage\")({\n  \"input_tokens\": S.Number,\n  \"input_tokens_details\": S.Struct({\n    \"cached_tokens\": S.Number\n  }),\n  \"output_tokens\": S.Number,\n  \"output_tokens_details\": S.Struct({\n    \"reasoning_tokens\": S.Number\n  }),\n  \"total_tokens\": S.Number\n}) {}\n\nexport class OpenResponsesNonStreamingResponseObject extends S.Literal(\"response\") {}\n\nexport class OpenAIResponsesResponseStatus\n  extends S.Literal(\"completed\", \"incomplete\", \"in_progress\", \"failed\", \"cancelled\", \"queued\")\n{}\n\nexport class ResponsesErrorFieldCode extends S.Literal(\n  \"server_error\",\n  \"rate_limit_exceeded\",\n  \"invalid_prompt\",\n  \"vector_store_timeout\",\n  \"invalid_image\",\n  \"invalid_image_format\",\n  \"invalid_base64_image\",\n  \"invalid_image_url\",\n  \"image_too_large\",\n  \"image_too_small\",\n  \"image_parse_error\",\n  \"image_content_policy_violation\",\n  \"invalid_image_mode\",\n  \"image_file_too_large\",\n  \"unsupported_image_media_type\",\n  \"empty_image_file\",\n  \"failed_to_download_image\",\n  \"image_file_not_found\"\n) {}\n\n/**\n * Error information returned from the API\n */\nexport class ResponsesErrorField extends S.Class<ResponsesErrorField>(\"ResponsesErrorField\")({\n  \"code\": ResponsesErrorFieldCode,\n  \"message\": S.String\n}) {}\n\nexport class OpenAIResponsesIncompleteDetailsReason extends S.Literal(\"max_output_tokens\", \"content_filter\") {}\n\nexport class OpenAIResponsesIncompleteDetails\n  extends S.Class<OpenAIResponsesIncompleteDetails>(\"OpenAIResponsesIncompleteDetails\")({\n    \"reason\": S.optionalWith(OpenAIResponsesIncompleteDetailsReason, { nullable: true })\n  })\n{}\n\nexport class ResponseInputImageType extends S.Literal(\"input_image\") {}\n\nexport class ResponseInputImageDetail extends S.Literal(\"auto\", \"high\", \"low\") {}\n\n/**\n * Image input content item\n */\nexport class ResponseInputImage extends S.Class<ResponseInputImage>(\"ResponseInputImage\")({\n  \"type\": ResponseInputImageType,\n  \"detail\": ResponseInputImageDetail,\n  \"image_url\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class OpenAIResponsesInput extends S.Union(\n  S.String,\n  S.Array(S.Union(\n    S.Struct({\n      \"type\": S.optionalWith(S.Literal(\"message\"), { nullable: true }),\n      \"role\": S.Union(S.Literal(\"user\"), S.Literal(\"system\"), S.Literal(\"assistant\"), S.Literal(\"developer\")),\n      \"content\": S.Union(\n        S.Array(S.Union(ResponseInputText, ResponseInputImage, ResponseInputFile, ResponseInputAudio)),\n        S.String\n      )\n    }),\n    S.Struct({\n      \"id\": S.String,\n      \"type\": S.optionalWith(S.Literal(\"message\"), { nullable: true }),\n      \"role\": S.Union(S.Literal(\"user\"), S.Literal(\"system\"), S.Literal(\"developer\")),\n      \"content\": S.Array(S.Union(ResponseInputText, ResponseInputImage, ResponseInputFile, ResponseInputAudio))\n    }),\n    S.Struct({\n      \"type\": S.Literal(\"function_call_output\"),\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      \"call_id\": S.String,\n      \"output\": S.String,\n      \"status\": S.optionalWith(ToolCallStatus, { nullable: true })\n    }),\n    S.Struct({\n      \"type\": S.Literal(\"function_call\"),\n      \"call_id\": S.String,\n      \"name\": S.String,\n      \"arguments\": S.String,\n      \"id\": S.optionalWith(S.String, { nullable: true }),\n      \"status\": S.optionalWith(ToolCallStatus, { nullable: true })\n    }),\n    OutputItemImageGenerationCall,\n    OutputMessage\n  ))\n) {}\n\nexport class OpenAIResponsesReasoningConfig\n  extends S.Class<OpenAIResponsesReasoningConfig>(\"OpenAIResponsesReasoningConfig\")({\n    \"effort\": S.optionalWith(OpenAIResponsesReasoningEffort, { nullable: true }),\n    \"summary\": S.optionalWith(ReasoningSummaryVerbosity, { nullable: true })\n  })\n{}\n\nexport class OpenAIResponsesServiceTier extends S.Literal(\"auto\", \"default\", \"flex\", \"priority\", \"scale\") {}\n\nexport class OpenAIResponsesTruncation extends S.Literal(\"auto\", \"disabled\") {}\n\nexport class ResponseTextConfigVerbosity extends S.Literal(\"high\", \"low\", \"medium\") {}\n\n/**\n * Text output configuration including format and verbosity\n */\nexport class ResponseTextConfig extends S.Class<ResponseTextConfig>(\"ResponseTextConfig\")({\n  \"format\": S.optionalWith(ResponseFormatTextConfig, { nullable: true }),\n  \"verbosity\": S.optionalWith(ResponseTextConfigVerbosity, { nullable: true })\n}) {}\n\nexport class OpenResponsesNonStreamingResponse\n  extends S.Class<OpenResponsesNonStreamingResponse>(\"OpenResponsesNonStreamingResponse\")({\n    \"output\": S.Array(\n      S.Union(\n        OutputMessage,\n        OutputItemReasoning,\n        OutputItemFunctionCall,\n        OutputItemWebSearchCall,\n        OutputItemFileSearchCall,\n        OutputItemImageGenerationCall\n      )\n    ),\n    \"usage\": S.optionalWith(OpenAIResponsesUsage, { nullable: true }),\n    \"id\": S.String,\n    \"object\": OpenResponsesNonStreamingResponseObject,\n    \"created_at\": S.Number,\n    \"model\": S.String,\n    \"status\": OpenAIResponsesResponseStatus,\n    \"completed_at\": S.NullOr(S.Number),\n    \"user\": S.optionalWith(S.String, { nullable: true }),\n    \"output_text\": S.optionalWith(S.String, { nullable: true }),\n    \"prompt_cache_key\": S.optionalWith(S.String, { nullable: true }),\n    \"safety_identifier\": S.optionalWith(S.String, { nullable: true }),\n    \"error\": S.NullOr(ResponsesErrorField),\n    \"incomplete_details\": S.NullOr(OpenAIResponsesIncompleteDetails),\n    \"max_tool_calls\": S.optionalWith(S.Number, { nullable: true }),\n    \"top_logprobs\": S.optionalWith(S.Number, { nullable: true }),\n    \"max_output_tokens\": S.optionalWith(S.Number, { nullable: true }),\n    \"temperature\": S.NullOr(S.Number),\n    \"top_p\": S.NullOr(S.Number),\n    \"presence_penalty\": S.NullOr(S.Number),\n    \"frequency_penalty\": S.NullOr(S.Number),\n    \"instructions\": OpenAIResponsesInput,\n    \"metadata\": S.NullOr(OpenResponsesRequestMetadata),\n    \"tools\": S.Array(S.Union(\n      /**\n       * Function tool definition\n       */\n      S.Struct({}),\n      OpenResponsesWebSearchPreviewTool,\n      OpenResponsesWebSearchPreview20250311Tool,\n      OpenResponsesWebSearchTool,\n      OpenResponsesWebSearch20250826Tool\n    )),\n    \"tool_choice\": OpenAIResponsesToolChoice,\n    \"parallel_tool_calls\": S.Boolean,\n    \"prompt\": S.optionalWith(OpenAIResponsesPrompt, { nullable: true }),\n    \"background\": S.optionalWith(S.Boolean, { nullable: true }),\n    \"previous_response_id\": S.optionalWith(S.String, { nullable: true }),\n    \"reasoning\": S.optionalWith(OpenAIResponsesReasoningConfig, { nullable: true }),\n    \"service_tier\": S.optionalWith(OpenAIResponsesServiceTier, { nullable: true }),\n    \"store\": S.optionalWith(S.Boolean, { nullable: true }),\n    \"truncation\": S.optionalWith(OpenAIResponsesTruncation, { nullable: true }),\n    \"text\": S.optionalWith(ResponseTextConfig, { nullable: true })\n  })\n{}\n\n/**\n * Error data for BadRequestResponse\n */\nexport class BadRequestResponseErrorData extends S.Class<BadRequestResponseErrorData>(\"BadRequestResponseErrorData\")({\n  \"code\": S.Int,\n  \"message\": S.String,\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * Bad Request - Invalid request parameters or malformed input\n */\nexport class BadRequestResponse extends S.Class<BadRequestResponse>(\"BadRequestResponse\")({\n  \"error\": BadRequestResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for UnauthorizedResponse\n */\nexport class UnauthorizedResponseErrorData\n  extends S.Class<UnauthorizedResponseErrorData>(\"UnauthorizedResponseErrorData\")({\n    \"code\": S.Int,\n    \"message\": S.String,\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * Unauthorized - Authentication required or invalid credentials\n */\nexport class UnauthorizedResponse extends S.Class<UnauthorizedResponse>(\"UnauthorizedResponse\")({\n  \"error\": UnauthorizedResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for PaymentRequiredResponse\n */\nexport class PaymentRequiredResponseErrorData\n  extends S.Class<PaymentRequiredResponseErrorData>(\"PaymentRequiredResponseErrorData\")({\n    \"code\": S.Int,\n    \"message\": S.String,\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * Payment Required - Insufficient credits or quota to complete request\n */\nexport class PaymentRequiredResponse extends S.Class<PaymentRequiredResponse>(\"PaymentRequiredResponse\")({\n  \"error\": PaymentRequiredResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for NotFoundResponse\n */\nexport class NotFoundResponseErrorData extends S.Class<NotFoundResponseErrorData>(\"NotFoundResponseErrorData\")({\n  \"code\": S.Int,\n  \"message\": S.String,\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * Not Found - Resource does not exist\n */\nexport class NotFoundResponse extends S.Class<NotFoundResponse>(\"NotFoundResponse\")({\n  \"error\": NotFoundResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for RequestTimeoutResponse\n */\nexport class RequestTimeoutResponseErrorData\n  extends S.Class<RequestTimeoutResponseErrorData>(\"RequestTimeoutResponseErrorData\")({\n    \"code\": S.Int,\n    \"message\": S.String,\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * Request Timeout - Operation exceeded time limit\n */\nexport class RequestTimeoutResponse extends S.Class<RequestTimeoutResponse>(\"RequestTimeoutResponse\")({\n  \"error\": RequestTimeoutResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for PayloadTooLargeResponse\n */\nexport class PayloadTooLargeResponseErrorData\n  extends S.Class<PayloadTooLargeResponseErrorData>(\"PayloadTooLargeResponseErrorData\")({\n    \"code\": S.Int,\n    \"message\": S.String,\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * Payload Too Large - Request payload exceeds size limits\n */\nexport class PayloadTooLargeResponse extends S.Class<PayloadTooLargeResponse>(\"PayloadTooLargeResponse\")({\n  \"error\": PayloadTooLargeResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for UnprocessableEntityResponse\n */\nexport class UnprocessableEntityResponseErrorData\n  extends S.Class<UnprocessableEntityResponseErrorData>(\"UnprocessableEntityResponseErrorData\")({\n    \"code\": S.Int,\n    \"message\": S.String,\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * Unprocessable Entity - Semantic validation failure\n */\nexport class UnprocessableEntityResponse extends S.Class<UnprocessableEntityResponse>(\"UnprocessableEntityResponse\")({\n  \"error\": UnprocessableEntityResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for TooManyRequestsResponse\n */\nexport class TooManyRequestsResponseErrorData\n  extends S.Class<TooManyRequestsResponseErrorData>(\"TooManyRequestsResponseErrorData\")({\n    \"code\": S.Int,\n    \"message\": S.String,\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * Too Many Requests - Rate limit exceeded\n */\nexport class TooManyRequestsResponse extends S.Class<TooManyRequestsResponse>(\"TooManyRequestsResponse\")({\n  \"error\": TooManyRequestsResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for InternalServerResponse\n */\nexport class InternalServerResponseErrorData\n  extends S.Class<InternalServerResponseErrorData>(\"InternalServerResponseErrorData\")({\n    \"code\": S.Int,\n    \"message\": S.String,\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * Internal Server Error - Unexpected server error\n */\nexport class InternalServerResponse extends S.Class<InternalServerResponse>(\"InternalServerResponse\")({\n  \"error\": InternalServerResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for BadGatewayResponse\n */\nexport class BadGatewayResponseErrorData extends S.Class<BadGatewayResponseErrorData>(\"BadGatewayResponseErrorData\")({\n  \"code\": S.Int,\n  \"message\": S.String,\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * Bad Gateway - Provider/upstream API failure\n */\nexport class BadGatewayResponse extends S.Class<BadGatewayResponse>(\"BadGatewayResponse\")({\n  \"error\": BadGatewayResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for ServiceUnavailableResponse\n */\nexport class ServiceUnavailableResponseErrorData\n  extends S.Class<ServiceUnavailableResponseErrorData>(\"ServiceUnavailableResponseErrorData\")({\n    \"code\": S.Int,\n    \"message\": S.String,\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * Service Unavailable - Service temporarily unavailable\n */\nexport class ServiceUnavailableResponse extends S.Class<ServiceUnavailableResponse>(\"ServiceUnavailableResponse\")({\n  \"error\": ServiceUnavailableResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for EdgeNetworkTimeoutResponse\n */\nexport class EdgeNetworkTimeoutResponseErrorData\n  extends S.Class<EdgeNetworkTimeoutResponseErrorData>(\"EdgeNetworkTimeoutResponseErrorData\")({\n    \"code\": S.Int,\n    \"message\": S.String,\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * Infrastructure Timeout - Provider request timed out at edge network\n */\nexport class EdgeNetworkTimeoutResponse extends S.Class<EdgeNetworkTimeoutResponse>(\"EdgeNetworkTimeoutResponse\")({\n  \"error\": EdgeNetworkTimeoutResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Error data for ProviderOverloadedResponse\n */\nexport class ProviderOverloadedResponseErrorData\n  extends S.Class<ProviderOverloadedResponseErrorData>(\"ProviderOverloadedResponseErrorData\")({\n    \"code\": S.Int,\n    \"message\": S.String,\n    \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n  })\n{}\n\n/**\n * Provider Overloaded - Provider is temporarily overloaded\n */\nexport class ProviderOverloadedResponse extends S.Class<ProviderOverloadedResponse>(\"ProviderOverloadedResponse\")({\n  \"error\": ProviderOverloadedResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class OpenRouterAnthropicMessageParamRole extends S.Literal(\"user\", \"assistant\") {}\n\n/**\n * Anthropic message with OpenRouter extensions\n */\nexport class OpenRouterAnthropicMessageParam\n  extends S.Class<OpenRouterAnthropicMessageParam>(\"OpenRouterAnthropicMessageParam\")({\n    \"role\": OpenRouterAnthropicMessageParamRole,\n    \"content\": S.Union(\n      S.String,\n      S.Array(S.Union(\n        S.Struct({\n          \"type\": S.Literal(\"text\"),\n          \"text\": S.String,\n          \"citations\": S.optionalWith(\n            S.Array(S.Union(\n              S.Struct({\n                \"type\": S.Literal(\"char_location\"),\n                \"cited_text\": S.String,\n                \"document_index\": S.Number,\n                \"document_title\": S.NullOr(S.String),\n                \"start_char_index\": S.Number,\n                \"end_char_index\": S.Number\n              }),\n              S.Struct({\n                \"type\": S.Literal(\"page_location\"),\n                \"cited_text\": S.String,\n                \"document_index\": S.Number,\n                \"document_title\": S.NullOr(S.String),\n                \"start_page_number\": S.Number,\n                \"end_page_number\": S.Number\n              }),\n              S.Struct({\n                \"type\": S.Literal(\"content_block_location\"),\n                \"cited_text\": S.String,\n                \"document_index\": S.Number,\n                \"document_title\": S.NullOr(S.String),\n                \"start_block_index\": S.Number,\n                \"end_block_index\": S.Number\n              }),\n              S.Struct({\n                \"type\": S.Literal(\"web_search_result_location\"),\n                \"cited_text\": S.String,\n                \"encrypted_index\": S.String,\n                \"title\": S.NullOr(S.String),\n                \"url\": S.String\n              }),\n              S.Struct({\n                \"type\": S.Literal(\"search_result_location\"),\n                \"cited_text\": S.String,\n                \"search_result_index\": S.Number,\n                \"source\": S.String,\n                \"title\": S.NullOr(S.String),\n                \"start_block_index\": S.Number,\n                \"end_block_index\": S.Number\n              })\n            )),\n            { nullable: true }\n          ),\n          \"cache_control\": S.optionalWith(\n            S.Struct({\n              \"type\": S.Literal(\"ephemeral\"),\n              \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n            }),\n            { nullable: true }\n          )\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"image\"),\n          \"source\": S.Union(\n            S.Struct({\n              \"type\": S.Literal(\"base64\"),\n              \"media_type\": S.Literal(\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"),\n              \"data\": S.String\n            }),\n            S.Struct({\n              \"type\": S.Literal(\"url\"),\n              \"url\": S.String\n            })\n          ),\n          \"cache_control\": S.optionalWith(\n            S.Struct({\n              \"type\": S.Literal(\"ephemeral\"),\n              \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n            }),\n            { nullable: true }\n          )\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"document\"),\n          \"source\": S.Union(\n            S.Struct({\n              \"type\": S.Literal(\"base64\"),\n              \"media_type\": S.Literal(\"application/pdf\"),\n              \"data\": S.String\n            }),\n            S.Struct({\n              \"type\": S.Literal(\"text\"),\n              \"media_type\": S.Literal(\"text/plain\"),\n              \"data\": S.String\n            }),\n            S.Struct({\n              \"type\": S.Literal(\"content\"),\n              \"content\": S.Union(\n                S.String,\n                S.Array(S.Union(\n                  S.Struct({\n                    \"type\": S.Literal(\"text\"),\n                    \"text\": S.String,\n                    \"citations\": S.optionalWith(\n                      S.Array(S.Union(\n                        S.Struct({\n                          \"type\": S.Literal(\"char_location\"),\n                          \"cited_text\": S.String,\n                          \"document_index\": S.Number,\n                          \"document_title\": S.NullOr(S.String),\n                          \"start_char_index\": S.Number,\n                          \"end_char_index\": S.Number\n                        }),\n                        S.Struct({\n                          \"type\": S.Literal(\"page_location\"),\n                          \"cited_text\": S.String,\n                          \"document_index\": S.Number,\n                          \"document_title\": S.NullOr(S.String),\n                          \"start_page_number\": S.Number,\n                          \"end_page_number\": S.Number\n                        }),\n                        S.Struct({\n                          \"type\": S.Literal(\"content_block_location\"),\n                          \"cited_text\": S.String,\n                          \"document_index\": S.Number,\n                          \"document_title\": S.NullOr(S.String),\n                          \"start_block_index\": S.Number,\n                          \"end_block_index\": S.Number\n                        }),\n                        S.Struct({\n                          \"type\": S.Literal(\"web_search_result_location\"),\n                          \"cited_text\": S.String,\n                          \"encrypted_index\": S.String,\n                          \"title\": S.NullOr(S.String),\n                          \"url\": S.String\n                        }),\n                        S.Struct({\n                          \"type\": S.Literal(\"search_result_location\"),\n                          \"cited_text\": S.String,\n                          \"search_result_index\": S.Number,\n                          \"source\": S.String,\n                          \"title\": S.NullOr(S.String),\n                          \"start_block_index\": S.Number,\n                          \"end_block_index\": S.Number\n                        })\n                      )),\n                      { nullable: true }\n                    ),\n                    \"cache_control\": S.optionalWith(\n                      S.Struct({\n                        \"type\": S.Literal(\"ephemeral\"),\n                        \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n                      }),\n                      { nullable: true }\n                    )\n                  }),\n                  S.Struct({\n                    \"type\": S.Literal(\"image\"),\n                    \"source\": S.Union(\n                      S.Struct({\n                        \"type\": S.Literal(\"base64\"),\n                        \"media_type\": S.Literal(\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"),\n                        \"data\": S.String\n                      }),\n                      S.Struct({\n                        \"type\": S.Literal(\"url\"),\n                        \"url\": S.String\n                      })\n                    ),\n                    \"cache_control\": S.optionalWith(\n                      S.Struct({\n                        \"type\": S.Literal(\"ephemeral\"),\n                        \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n                      }),\n                      { nullable: true }\n                    )\n                  })\n                ))\n              )\n            }),\n            S.Struct({\n              \"type\": S.Literal(\"url\"),\n              \"url\": S.String\n            })\n          ),\n          \"citations\": S.optionalWith(\n            S.Struct({\n              \"enabled\": S.optionalWith(S.Boolean, { nullable: true })\n            }),\n            { nullable: true }\n          ),\n          \"context\": S.optionalWith(S.String, { nullable: true }),\n          \"title\": S.optionalWith(S.String, { nullable: true }),\n          \"cache_control\": S.optionalWith(\n            S.Struct({\n              \"type\": S.Literal(\"ephemeral\"),\n              \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n            }),\n            { nullable: true }\n          )\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"tool_use\"),\n          \"id\": S.String,\n          \"name\": S.String,\n          \"cache_control\": S.optionalWith(\n            S.Struct({\n              \"type\": S.Literal(\"ephemeral\"),\n              \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n            }),\n            { nullable: true }\n          )\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"tool_result\"),\n          \"tool_use_id\": S.String,\n          \"content\": S.optionalWith(\n            S.Union(\n              S.String,\n              S.Array(S.Union(\n                S.Struct({\n                  \"type\": S.Literal(\"text\"),\n                  \"text\": S.String,\n                  \"citations\": S.optionalWith(\n                    S.Array(S.Union(\n                      S.Struct({\n                        \"type\": S.Literal(\"char_location\"),\n                        \"cited_text\": S.String,\n                        \"document_index\": S.Number,\n                        \"document_title\": S.NullOr(S.String),\n                        \"start_char_index\": S.Number,\n                        \"end_char_index\": S.Number\n                      }),\n                      S.Struct({\n                        \"type\": S.Literal(\"page_location\"),\n                        \"cited_text\": S.String,\n                        \"document_index\": S.Number,\n                        \"document_title\": S.NullOr(S.String),\n                        \"start_page_number\": S.Number,\n                        \"end_page_number\": S.Number\n                      }),\n                      S.Struct({\n                        \"type\": S.Literal(\"content_block_location\"),\n                        \"cited_text\": S.String,\n                        \"document_index\": S.Number,\n                        \"document_title\": S.NullOr(S.String),\n                        \"start_block_index\": S.Number,\n                        \"end_block_index\": S.Number\n                      }),\n                      S.Struct({\n                        \"type\": S.Literal(\"web_search_result_location\"),\n                        \"cited_text\": S.String,\n                        \"encrypted_index\": S.String,\n                        \"title\": S.NullOr(S.String),\n                        \"url\": S.String\n                      }),\n                      S.Struct({\n                        \"type\": S.Literal(\"search_result_location\"),\n                        \"cited_text\": S.String,\n                        \"search_result_index\": S.Number,\n                        \"source\": S.String,\n                        \"title\": S.NullOr(S.String),\n                        \"start_block_index\": S.Number,\n                        \"end_block_index\": S.Number\n                      })\n                    )),\n                    { nullable: true }\n                  ),\n                  \"cache_control\": S.optionalWith(\n                    S.Struct({\n                      \"type\": S.Literal(\"ephemeral\"),\n                      \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n                    }),\n                    { nullable: true }\n                  )\n                }),\n                S.Struct({\n                  \"type\": S.Literal(\"image\"),\n                  \"source\": S.Union(\n                    S.Struct({\n                      \"type\": S.Literal(\"base64\"),\n                      \"media_type\": S.Literal(\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"),\n                      \"data\": S.String\n                    }),\n                    S.Struct({\n                      \"type\": S.Literal(\"url\"),\n                      \"url\": S.String\n                    })\n                  ),\n                  \"cache_control\": S.optionalWith(\n                    S.Struct({\n                      \"type\": S.Literal(\"ephemeral\"),\n                      \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n                    }),\n                    { nullable: true }\n                  )\n                })\n              ))\n            ),\n            { nullable: true }\n          ),\n          \"is_error\": S.optionalWith(S.Boolean, { nullable: true }),\n          \"cache_control\": S.optionalWith(\n            S.Struct({\n              \"type\": S.Literal(\"ephemeral\"),\n              \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n            }),\n            { nullable: true }\n          )\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"thinking\"),\n          \"thinking\": S.String,\n          \"signature\": S.String\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"redacted_thinking\"),\n          \"data\": S.String\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"server_tool_use\"),\n          \"id\": S.String,\n          \"name\": S.Literal(\"web_search\"),\n          \"cache_control\": S.optionalWith(\n            S.Struct({\n              \"type\": S.Literal(\"ephemeral\"),\n              \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n            }),\n            { nullable: true }\n          )\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"web_search_tool_result\"),\n          \"tool_use_id\": S.String,\n          \"content\": S.Union(\n            S.Array(S.Struct({\n              \"type\": S.Literal(\"web_search_result\"),\n              \"encrypted_content\": S.String,\n              \"title\": S.String,\n              \"url\": S.String,\n              \"page_age\": S.optionalWith(S.String, { nullable: true })\n            })),\n            S.Struct({\n              \"type\": S.Literal(\"web_search_tool_result_error\"),\n              \"error_code\": S.Literal(\n                \"invalid_tool_input\",\n                \"unavailable\",\n                \"max_uses_exceeded\",\n                \"too_many_requests\",\n                \"query_too_long\"\n              )\n            })\n          ),\n          \"cache_control\": S.optionalWith(\n            S.Struct({\n              \"type\": S.Literal(\"ephemeral\"),\n              \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n            }),\n            { nullable: true }\n          )\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"search_result\"),\n          \"source\": S.String,\n          \"title\": S.String,\n          \"content\": S.Array(S.Struct({\n            \"type\": S.Literal(\"text\"),\n            \"text\": S.String,\n            \"citations\": S.optionalWith(\n              S.Array(S.Union(\n                S.Struct({\n                  \"type\": S.Literal(\"char_location\"),\n                  \"cited_text\": S.String,\n                  \"document_index\": S.Number,\n                  \"document_title\": S.NullOr(S.String),\n                  \"start_char_index\": S.Number,\n                  \"end_char_index\": S.Number\n                }),\n                S.Struct({\n                  \"type\": S.Literal(\"page_location\"),\n                  \"cited_text\": S.String,\n                  \"document_index\": S.Number,\n                  \"document_title\": S.NullOr(S.String),\n                  \"start_page_number\": S.Number,\n                  \"end_page_number\": S.Number\n                }),\n                S.Struct({\n                  \"type\": S.Literal(\"content_block_location\"),\n                  \"cited_text\": S.String,\n                  \"document_index\": S.Number,\n                  \"document_title\": S.NullOr(S.String),\n                  \"start_block_index\": S.Number,\n                  \"end_block_index\": S.Number\n                }),\n                S.Struct({\n                  \"type\": S.Literal(\"web_search_result_location\"),\n                  \"cited_text\": S.String,\n                  \"encrypted_index\": S.String,\n                  \"title\": S.NullOr(S.String),\n                  \"url\": S.String\n                }),\n                S.Struct({\n                  \"type\": S.Literal(\"search_result_location\"),\n                  \"cited_text\": S.String,\n                  \"search_result_index\": S.Number,\n                  \"source\": S.String,\n                  \"title\": S.NullOr(S.String),\n                  \"start_block_index\": S.Number,\n                  \"end_block_index\": S.Number\n                })\n              )),\n              { nullable: true }\n            ),\n            \"cache_control\": S.optionalWith(\n              S.Struct({\n                \"type\": S.Literal(\"ephemeral\"),\n                \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n              }),\n              { nullable: true }\n            )\n          })),\n          \"citations\": S.optionalWith(\n            S.Struct({\n              \"enabled\": S.optionalWith(S.Boolean, { nullable: true })\n            }),\n            { nullable: true }\n          ),\n          \"cache_control\": S.optionalWith(\n            S.Struct({\n              \"type\": S.Literal(\"ephemeral\"),\n              \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n            }),\n            { nullable: true }\n          )\n        })\n      ))\n    )\n  })\n{}\n\nexport class AnthropicMessagesRequestToolChoiceEnumType extends S.Literal(\"tool\") {}\n\nexport class AnthropicMessagesRequestThinkingEnumType extends S.Literal(\"disabled\") {}\n\nexport class AnthropicMessagesRequestServiceTier extends S.Literal(\"auto\", \"standard_only\") {}\n\n/**\n * The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed.\n */\nexport class AnthropicMessagesRequestProviderSort extends S.Literal(\"price\", \"throughput\", \"latency\") {}\n\n/**\n * **DEPRECATED** Use providers.sort.partition instead. Backwards-compatible alias for providers.sort.partition. Accepts legacy values: \"fallback\" (maps to \"model\"), \"sort\" (maps to \"none\").\n */\nexport class AnthropicMessagesRequestRoute extends S.Literal(\"fallback\", \"sort\") {}\n\n/**\n * Request schema for Anthropic Messages API endpoint\n */\nexport class AnthropicMessagesRequest extends S.Class<AnthropicMessagesRequest>(\"AnthropicMessagesRequest\")({\n  \"model\": S.String,\n  \"max_tokens\": S.Number,\n  \"messages\": S.Array(OpenRouterAnthropicMessageParam),\n  \"system\": S.optionalWith(\n    S.Union(\n      S.String,\n      S.Array(S.Struct({\n        \"type\": S.Literal(\"text\"),\n        \"text\": S.String,\n        \"citations\": S.optionalWith(\n          S.Array(S.Union(\n            S.Struct({\n              \"type\": S.Literal(\"char_location\"),\n              \"cited_text\": S.String,\n              \"document_index\": S.Number,\n              \"document_title\": S.NullOr(S.String),\n              \"start_char_index\": S.Number,\n              \"end_char_index\": S.Number\n            }),\n            S.Struct({\n              \"type\": S.Literal(\"page_location\"),\n              \"cited_text\": S.String,\n              \"document_index\": S.Number,\n              \"document_title\": S.NullOr(S.String),\n              \"start_page_number\": S.Number,\n              \"end_page_number\": S.Number\n            }),\n            S.Struct({\n              \"type\": S.Literal(\"content_block_location\"),\n              \"cited_text\": S.String,\n              \"document_index\": S.Number,\n              \"document_title\": S.NullOr(S.String),\n              \"start_block_index\": S.Number,\n              \"end_block_index\": S.Number\n            }),\n            S.Struct({\n              \"type\": S.Literal(\"web_search_result_location\"),\n              \"cited_text\": S.String,\n              \"encrypted_index\": S.String,\n              \"title\": S.NullOr(S.String),\n              \"url\": S.String\n            }),\n            S.Struct({\n              \"type\": S.Literal(\"search_result_location\"),\n              \"cited_text\": S.String,\n              \"search_result_index\": S.Number,\n              \"source\": S.String,\n              \"title\": S.NullOr(S.String),\n              \"start_block_index\": S.Number,\n              \"end_block_index\": S.Number\n            })\n          )),\n          { nullable: true }\n        ),\n        \"cache_control\": S.optionalWith(\n          S.Struct({\n            \"type\": S.Literal(\"ephemeral\"),\n            \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n          }),\n          { nullable: true }\n        )\n      }))\n    ),\n    { nullable: true }\n  ),\n  \"metadata\": S.optionalWith(\n    S.Struct({\n      \"user_id\": S.optionalWith(S.String, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"stop_sequences\": S.optionalWith(S.Array(S.String), { nullable: true }),\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"temperature\": S.optionalWith(S.Number, { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number, { nullable: true }),\n  \"top_k\": S.optionalWith(S.Number, { nullable: true }),\n  \"tools\": S.optionalWith(\n    S.Array(S.Union(\n      S.Struct({\n        \"name\": S.String,\n        \"description\": S.optionalWith(S.String, { nullable: true }),\n        \"input_schema\": S.Struct({\n          \"type\": S.Literal(\"object\"),\n          \"required\": S.optionalWith(S.Array(S.String), { nullable: true })\n        }),\n        \"type\": S.optionalWith(S.Literal(\"custom\"), { nullable: true }),\n        \"cache_control\": S.optionalWith(\n          S.Struct({\n            \"type\": S.Literal(\"ephemeral\"),\n            \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n          }),\n          { nullable: true }\n        )\n      }),\n      S.Struct({\n        \"type\": S.Literal(\"bash_20250124\"),\n        \"name\": S.Literal(\"bash\"),\n        \"cache_control\": S.optionalWith(\n          S.Struct({\n            \"type\": S.Literal(\"ephemeral\"),\n            \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n          }),\n          { nullable: true }\n        )\n      }),\n      S.Struct({\n        \"type\": S.Literal(\"text_editor_20250124\"),\n        \"name\": S.Literal(\"str_replace_editor\"),\n        \"cache_control\": S.optionalWith(\n          S.Struct({\n            \"type\": S.Literal(\"ephemeral\"),\n            \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n          }),\n          { nullable: true }\n        )\n      }),\n      S.Struct({\n        \"type\": S.Literal(\"web_search_20250305\"),\n        \"name\": S.Literal(\"web_search\"),\n        \"allowed_domains\": S.optionalWith(S.Array(S.String), { nullable: true }),\n        \"blocked_domains\": S.optionalWith(S.Array(S.String), { nullable: true }),\n        \"max_uses\": S.optionalWith(S.Number, { nullable: true }),\n        \"user_location\": S.optionalWith(\n          S.Struct({\n            \"type\": S.Literal(\"approximate\"),\n            \"city\": S.optionalWith(S.String, { nullable: true }),\n            \"country\": S.optionalWith(S.String, { nullable: true }),\n            \"region\": S.optionalWith(S.String, { nullable: true }),\n            \"timezone\": S.optionalWith(S.String, { nullable: true })\n          }),\n          { nullable: true }\n        ),\n        \"cache_control\": S.optionalWith(\n          S.Struct({\n            \"type\": S.Literal(\"ephemeral\"),\n            \"ttl\": S.optionalWith(S.Literal(\"5m\", \"1h\"), { nullable: true })\n          }),\n          { nullable: true }\n        )\n      })\n    )),\n    { nullable: true }\n  ),\n  \"tool_choice\": S.optionalWith(\n    S.Union(\n      S.Struct({\n        \"type\": AnthropicMessagesRequestToolChoiceEnumType,\n        \"disable_parallel_tool_use\": S.optionalWith(S.Boolean, { nullable: true })\n      }),\n      S.Struct({\n        \"type\": AnthropicMessagesRequestToolChoiceEnumType,\n        \"disable_parallel_tool_use\": S.optionalWith(S.Boolean, { nullable: true })\n      }),\n      S.Struct({\n        \"type\": AnthropicMessagesRequestToolChoiceEnumType\n      }),\n      S.Struct({\n        \"type\": AnthropicMessagesRequestToolChoiceEnumType,\n        \"name\": S.String,\n        \"disable_parallel_tool_use\": S.optionalWith(S.Boolean, { nullable: true })\n      })\n    ),\n    { nullable: true }\n  ),\n  \"thinking\": S.optionalWith(\n    S.Union(\n      S.Struct({\n        \"type\": AnthropicMessagesRequestThinkingEnumType,\n        \"budget_tokens\": S.Number\n      }),\n      S.Struct({\n        \"type\": AnthropicMessagesRequestThinkingEnumType\n      })\n    ),\n    { nullable: true }\n  ),\n  \"service_tier\": S.optionalWith(AnthropicMessagesRequestServiceTier, { nullable: true }),\n  /**\n   * When multiple model providers are available, optionally indicate your routing preference.\n   */\n  \"provider\": S.optionalWith(\n    S.Struct({\n      /**\n       * Whether to allow backup providers to serve requests\n       * - true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider.\n       * - false: use only the primary/custom provider, and return the upstream error if it's unavailable.\n       */\n      \"allow_fallbacks\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest.\n       */\n      \"require_parameters\": S.optionalWith(S.Boolean, { nullable: true }),\n      \"data_collection\": S.optionalWith(DataCollection, { nullable: true }),\n      /**\n       * Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used.\n       */\n      \"zdr\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used.\n       */\n      \"enforce_distillable_text\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message.\n       */\n      \"order\": S.optionalWith(S.Array(S.Union(ProviderName, S.String)), { nullable: true }),\n      /**\n       * List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request.\n       */\n      \"only\": S.optionalWith(S.Array(S.Union(ProviderName, S.String)), { nullable: true }),\n      /**\n       * List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request.\n       */\n      \"ignore\": S.optionalWith(S.Array(S.Union(ProviderName, S.String)), { nullable: true }),\n      /**\n       * A list of quantization levels to filter the provider by.\n       */\n      \"quantizations\": S.optionalWith(S.Array(Quantization), { nullable: true }),\n      \"sort\": S.optionalWith(AnthropicMessagesRequestProviderSort, { nullable: true }),\n      /**\n       * The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.\n       */\n      \"max_price\": S.optionalWith(\n        S.Struct({\n          \"prompt\": S.optionalWith(BigNumberUnion, { nullable: true }),\n          \"completion\": S.optionalWith(BigNumberUnion, { nullable: true }),\n          \"image\": S.optionalWith(BigNumberUnion, { nullable: true }),\n          \"audio\": S.optionalWith(BigNumberUnion, { nullable: true }),\n          \"request\": S.optionalWith(BigNumberUnion, { nullable: true })\n        }),\n        { nullable: true }\n      ),\n      \"preferred_min_throughput\": S.optionalWith(PreferredMinThroughput, { nullable: true }),\n      \"preferred_max_latency\": S.optionalWith(PreferredMaxLatency, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  /**\n   * Plugins you want to enable for this request, including their settings.\n   */\n  \"plugins\": S.optionalWith(\n    S.Array(S.Union(\n      S.Struct({\n        \"id\": S.Literal(\"auto-router\"),\n        /**\n         * Set to false to disable the auto-router plugin for this request. Defaults to true.\n         */\n        \"enabled\": S.optionalWith(S.Boolean, { nullable: true }),\n        /**\n         * List of model patterns to filter which models the auto-router can route between. Supports wildcards (e.g., \"anthropic/*\" matches all Anthropic models). When not specified, uses the default supported models list.\n         */\n        \"allowed_models\": S.optionalWith(S.Array(S.String), { nullable: true })\n      }),\n      S.Struct({\n        \"id\": S.Literal(\"moderation\")\n      }),\n      S.Struct({\n        \"id\": S.Literal(\"web\"),\n        /**\n         * Set to false to disable the web-search plugin for this request. Defaults to true.\n         */\n        \"enabled\": S.optionalWith(S.Boolean, { nullable: true }),\n        \"max_results\": S.optionalWith(S.Number, { nullable: true }),\n        \"search_prompt\": S.optionalWith(S.String, { nullable: true }),\n        \"engine\": S.optionalWith(WebSearchEngine, { nullable: true })\n      }),\n      S.Struct({\n        \"id\": S.Literal(\"file-parser\"),\n        /**\n         * Set to false to disable the file-parser plugin for this request. Defaults to true.\n         */\n        \"enabled\": S.optionalWith(S.Boolean, { nullable: true }),\n        \"pdf\": S.optionalWith(PDFParserOptions, { nullable: true })\n      }),\n      S.Struct({\n        \"id\": S.Literal(\"response-healing\"),\n        /**\n         * Set to false to disable the response-healing plugin for this request. Defaults to true.\n         */\n        \"enabled\": S.optionalWith(S.Boolean, { nullable: true })\n      })\n    )),\n    { nullable: true }\n  ),\n  /**\n   * **DEPRECATED** Use providers.sort.partition instead. Backwards-compatible alias for providers.sort.partition. Accepts legacy values: \"fallback\" (maps to \"model\"), \"sort\" (maps to \"none\").\n   */\n  \"route\": S.optionalWith(AnthropicMessagesRequestRoute, { nullable: true }),\n  /**\n   * A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 128 characters.\n   */\n  \"user\": S.optionalWith(S.String.pipe(S.maxLength(128)), { nullable: true }),\n  /**\n   * A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 128 characters.\n   */\n  \"session_id\": S.optionalWith(S.String.pipe(S.maxLength(128)), { nullable: true }),\n  \"models\": S.optionalWith(S.Array(S.String), { nullable: true })\n}) {}\n\nexport class AnthropicMessagesResponseType extends S.Literal(\"message\") {}\n\nexport class AnthropicMessagesResponseRole extends S.Literal(\"assistant\") {}\n\nexport class AnthropicMessagesResponseStopReason extends S.Literal(\n  \"end_turn\",\n  \"max_tokens\",\n  \"stop_sequence\",\n  \"tool_use\",\n  \"pause_turn\",\n  \"refusal\",\n  \"model_context_window_exceeded\"\n) {}\n\nexport class AnthropicMessagesResponseUsageServiceTier extends S.Literal(\"standard\", \"priority\", \"batch\") {}\n\nexport class AnthropicMessagesResponse extends S.Class<AnthropicMessagesResponse>(\"AnthropicMessagesResponse\")({\n  \"id\": S.String,\n  \"type\": AnthropicMessagesResponseType,\n  \"role\": AnthropicMessagesResponseRole,\n  \"content\": S.Array(S.Union(\n    S.Struct({\n      \"type\": S.Literal(\"text\"),\n      \"text\": S.String,\n      \"citations\": S.NullOr(S.Array(S.Union(\n        S.Struct({\n          \"type\": S.Literal(\"char_location\"),\n          \"cited_text\": S.String,\n          \"document_index\": S.Number,\n          \"document_title\": S.NullOr(S.String),\n          \"start_char_index\": S.Number,\n          \"end_char_index\": S.Number,\n          \"file_id\": S.NullOr(S.String)\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"page_location\"),\n          \"cited_text\": S.String,\n          \"document_index\": S.Number,\n          \"document_title\": S.NullOr(S.String),\n          \"start_page_number\": S.Number,\n          \"end_page_number\": S.Number,\n          \"file_id\": S.NullOr(S.String)\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"content_block_location\"),\n          \"cited_text\": S.String,\n          \"document_index\": S.Number,\n          \"document_title\": S.NullOr(S.String),\n          \"start_block_index\": S.Number,\n          \"end_block_index\": S.Number,\n          \"file_id\": S.NullOr(S.String)\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"web_search_result_location\"),\n          \"cited_text\": S.String,\n          \"encrypted_index\": S.String,\n          \"title\": S.NullOr(S.String),\n          \"url\": S.String\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"search_result_location\"),\n          \"cited_text\": S.String,\n          \"search_result_index\": S.Number,\n          \"source\": S.String,\n          \"title\": S.NullOr(S.String),\n          \"start_block_index\": S.Number,\n          \"end_block_index\": S.Number\n        })\n      )))\n    }),\n    S.Struct({\n      \"type\": S.Literal(\"tool_use\"),\n      \"id\": S.String,\n      \"name\": S.String\n    }),\n    S.Struct({\n      \"type\": S.Literal(\"thinking\"),\n      \"thinking\": S.String,\n      \"signature\": S.String\n    }),\n    S.Struct({\n      \"type\": S.Literal(\"redacted_thinking\"),\n      \"data\": S.String\n    }),\n    S.Struct({\n      \"type\": S.Literal(\"server_tool_use\"),\n      \"id\": S.String,\n      \"name\": S.Literal(\"web_search\")\n    }),\n    S.Struct({\n      \"type\": S.Literal(\"web_search_tool_result\"),\n      \"tool_use_id\": S.String,\n      \"content\": S.Union(\n        S.Array(S.Struct({\n          \"type\": S.Literal(\"web_search_result\"),\n          \"encrypted_content\": S.String,\n          \"page_age\": S.NullOr(S.String),\n          \"title\": S.String,\n          \"url\": S.String\n        })),\n        S.Struct({\n          \"type\": S.Literal(\"web_search_tool_result_error\"),\n          \"error_code\": S.Literal(\n            \"invalid_tool_input\",\n            \"unavailable\",\n            \"max_uses_exceeded\",\n            \"too_many_requests\",\n            \"query_too_long\"\n          )\n        })\n      )\n    })\n  )),\n  \"model\": S.String,\n  \"stop_reason\": S.NullOr(AnthropicMessagesResponseStopReason),\n  \"stop_sequence\": S.NullOr(S.String),\n  \"usage\": S.Struct({\n    \"input_tokens\": S.Number,\n    \"output_tokens\": S.Number,\n    \"cache_creation_input_tokens\": S.NullOr(S.Number),\n    \"cache_read_input_tokens\": S.NullOr(S.Number),\n    \"cache_creation\": S.NullOr(S.Struct({\n      \"ephemeral_5m_input_tokens\": S.Number,\n      \"ephemeral_1h_input_tokens\": S.Number\n    })),\n    \"server_tool_use\": S.NullOr(S.Struct({\n      \"web_search_requests\": S.Number\n    })),\n    \"service_tier\": S.NullOr(AnthropicMessagesResponseUsageServiceTier)\n  })\n}) {}\n\nexport class CreateMessages400Type extends S.Literal(\"error\") {}\n\nexport class CreateMessages400 extends S.Struct({\n  \"type\": CreateMessages400Type,\n  \"error\": S.Struct({\n    \"type\": S.String,\n    \"message\": S.String\n  })\n}) {}\n\nexport class CreateMessages401Type extends S.Literal(\"error\") {}\n\nexport class CreateMessages401 extends S.Struct({\n  \"type\": CreateMessages401Type,\n  \"error\": S.Struct({\n    \"type\": S.String,\n    \"message\": S.String\n  })\n}) {}\n\nexport class CreateMessages403Type extends S.Literal(\"error\") {}\n\nexport class CreateMessages403 extends S.Struct({\n  \"type\": CreateMessages403Type,\n  \"error\": S.Struct({\n    \"type\": S.String,\n    \"message\": S.String\n  })\n}) {}\n\nexport class CreateMessages404Type extends S.Literal(\"error\") {}\n\nexport class CreateMessages404 extends S.Struct({\n  \"type\": CreateMessages404Type,\n  \"error\": S.Struct({\n    \"type\": S.String,\n    \"message\": S.String\n  })\n}) {}\n\nexport class CreateMessages429Type extends S.Literal(\"error\") {}\n\nexport class CreateMessages429 extends S.Struct({\n  \"type\": CreateMessages429Type,\n  \"error\": S.Struct({\n    \"type\": S.String,\n    \"message\": S.String\n  })\n}) {}\n\nexport class CreateMessages500Type extends S.Literal(\"error\") {}\n\nexport class CreateMessages500 extends S.Struct({\n  \"type\": CreateMessages500Type,\n  \"error\": S.Struct({\n    \"type\": S.String,\n    \"message\": S.String\n  })\n}) {}\n\nexport class CreateMessages503Type extends S.Literal(\"error\") {}\n\nexport class CreateMessages503 extends S.Struct({\n  \"type\": CreateMessages503Type,\n  \"error\": S.Struct({\n    \"type\": S.String,\n    \"message\": S.String\n  })\n}) {}\n\nexport class CreateMessages529Type extends S.Literal(\"error\") {}\n\nexport class CreateMessages529 extends S.Struct({\n  \"type\": CreateMessages529Type,\n  \"error\": S.Struct({\n    \"type\": S.String,\n    \"message\": S.String\n  })\n}) {}\n\nexport class GetUserActivityParams extends S.Struct({\n  /**\n   * Filter by a single UTC date in the last 30 days (YYYY-MM-DD format).\n   */\n  \"date\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ActivityItem extends S.Class<ActivityItem>(\"ActivityItem\")({\n  /**\n   * Date of the activity (YYYY-MM-DD format)\n   */\n  \"date\": S.String,\n  /**\n   * Model slug (e.g., \"openai/gpt-4.1\")\n   */\n  \"model\": S.String,\n  /**\n   * Model permaslug (e.g., \"openai/gpt-4.1-2025-04-14\")\n   */\n  \"model_permaslug\": S.String,\n  /**\n   * Unique identifier for the endpoint\n   */\n  \"endpoint_id\": S.String,\n  /**\n   * Name of the provider serving this endpoint\n   */\n  \"provider_name\": S.String,\n  /**\n   * Total cost in USD (OpenRouter credits spent)\n   */\n  \"usage\": S.Number,\n  /**\n   * BYOK inference cost in USD (external credits spent)\n   */\n  \"byok_usage_inference\": S.Number,\n  /**\n   * Number of requests made\n   */\n  \"requests\": S.Number,\n  /**\n   * Total prompt tokens used\n   */\n  \"prompt_tokens\": S.Number,\n  /**\n   * Total completion tokens generated\n   */\n  \"completion_tokens\": S.Number,\n  /**\n   * Total reasoning tokens used\n   */\n  \"reasoning_tokens\": S.Number\n}) {}\n\nexport class GetUserActivity200 extends S.Struct({\n  /**\n   * List of activity items\n   */\n  \"data\": S.Array(ActivityItem)\n}) {}\n\n/**\n * Error data for ForbiddenResponse\n */\nexport class ForbiddenResponseErrorData extends S.Class<ForbiddenResponseErrorData>(\"ForbiddenResponseErrorData\")({\n  \"code\": S.Int,\n  \"message\": S.String,\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\n/**\n * Forbidden - Authentication successful but insufficient permissions\n */\nexport class ForbiddenResponse extends S.Class<ForbiddenResponse>(\"ForbiddenResponse\")({\n  \"error\": ForbiddenResponseErrorData,\n  \"user_id\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Total credits purchased and used\n */\nexport class GetCredits200 extends S.Struct({\n  \"data\": S.Struct({\n    /**\n     * Total credits purchased\n     */\n    \"total_credits\": S.Number,\n    /**\n     * Total credits used\n     */\n    \"total_usage\": S.Number\n  })\n}) {}\n\nexport class CreateChargeRequestChainId extends S.Literal(1, 137, 8453) {}\n\n/**\n * Create a Coinbase charge for crypto payment\n */\nexport class CreateChargeRequest extends S.Class<CreateChargeRequest>(\"CreateChargeRequest\")({\n  \"amount\": S.Number,\n  \"sender\": S.String,\n  \"chain_id\": CreateChargeRequestChainId\n}) {}\n\nexport class CreateCoinbaseCharge200 extends S.Struct({\n  \"data\": S.Struct({\n    \"id\": S.String,\n    \"created_at\": S.String,\n    \"expires_at\": S.String,\n    \"web3_data\": S.Struct({\n      \"transfer_intent\": S.Struct({\n        \"call_data\": S.Struct({\n          \"deadline\": S.String,\n          \"fee_amount\": S.String,\n          \"id\": S.String,\n          \"operator\": S.String,\n          \"prefix\": S.String,\n          \"recipient\": S.String,\n          \"recipient_amount\": S.String,\n          \"recipient_currency\": S.String,\n          \"refund_destination\": S.String,\n          \"signature\": S.String\n        }),\n        \"metadata\": S.Struct({\n          \"chain_id\": S.Number,\n          \"contract_address\": S.String,\n          \"sender\": S.String\n        })\n      })\n    })\n  })\n}) {}\n\nexport class CreateEmbeddingsRequestEncodingFormat extends S.Literal(\"float\", \"base64\") {}\n\n/**\n * The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed.\n */\nexport class ProviderPreferencesSort extends S.Literal(\"price\", \"throughput\", \"latency\") {}\n\n/**\n * Provider routing preferences for the request.\n */\nexport class ProviderPreferences extends S.Class<ProviderPreferences>(\"ProviderPreferences\")({\n  /**\n   * Whether to allow backup providers to serve requests\n   * - true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider.\n   * - false: use only the primary/custom provider, and return the upstream error if it's unavailable.\n   */\n  \"allow_fallbacks\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest.\n   */\n  \"require_parameters\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"data_collection\": S.optionalWith(DataCollection, { nullable: true }),\n  /**\n   * Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used.\n   */\n  \"zdr\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used.\n   */\n  \"enforce_distillable_text\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message.\n   */\n  \"order\": S.optionalWith(S.Array(S.Union(ProviderName, S.String)), { nullable: true }),\n  /**\n   * List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request.\n   */\n  \"only\": S.optionalWith(S.Array(S.Union(ProviderName, S.String)), { nullable: true }),\n  /**\n   * List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request.\n   */\n  \"ignore\": S.optionalWith(S.Array(S.Union(ProviderName, S.String)), { nullable: true }),\n  /**\n   * A list of quantization levels to filter the provider by.\n   */\n  \"quantizations\": S.optionalWith(S.Array(Quantization), { nullable: true }),\n  \"sort\": S.optionalWith(ProviderPreferencesSort, { nullable: true }),\n  /**\n   * The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.\n   */\n  \"max_price\": S.optionalWith(\n    S.Struct({\n      \"prompt\": S.optionalWith(BigNumberUnion, { nullable: true }),\n      \"completion\": S.optionalWith(BigNumberUnion, { nullable: true }),\n      \"image\": S.optionalWith(BigNumberUnion, { nullable: true }),\n      \"audio\": S.optionalWith(BigNumberUnion, { nullable: true }),\n      \"request\": S.optionalWith(BigNumberUnion, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"preferred_min_throughput\": S.optionalWith(PreferredMinThroughput, { nullable: true }),\n  \"preferred_max_latency\": S.optionalWith(PreferredMaxLatency, { nullable: true })\n}) {}\n\nexport class CreateEmbeddingsRequest extends S.Class<CreateEmbeddingsRequest>(\"CreateEmbeddingsRequest\")({\n  \"input\": S.Union(\n    S.String,\n    S.Array(S.String),\n    S.Array(S.Number),\n    S.Array(S.Array(S.Number)),\n    S.Array(S.Struct({\n      \"content\": S.Array(S.Union(\n        S.Struct({\n          \"type\": S.Literal(\"text\"),\n          \"text\": S.String\n        }),\n        S.Struct({\n          \"type\": S.Literal(\"image_url\"),\n          \"image_url\": S.Struct({\n            \"url\": S.String\n          })\n        })\n      ))\n    }))\n  ),\n  \"model\": S.String,\n  \"encoding_format\": S.optionalWith(CreateEmbeddingsRequestEncodingFormat, { nullable: true }),\n  \"dimensions\": S.optionalWith(S.Int.pipe(S.greaterThan(0)), { nullable: true }),\n  \"user\": S.optionalWith(S.String, { nullable: true }),\n  \"provider\": S.optionalWith(ProviderPreferences, { nullable: true }),\n  \"input_type\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class CreateEmbeddings200Object extends S.Literal(\"list\") {}\n\nexport class CreateEmbeddings200 extends S.Struct({\n  \"id\": S.optionalWith(S.String, { nullable: true }),\n  \"object\": CreateEmbeddings200Object,\n  \"data\": S.Array(S.Struct({\n    \"object\": S.Literal(\"embedding\"),\n    \"embedding\": S.Union(S.Array(S.Number), S.String),\n    \"index\": S.optionalWith(S.Number, { nullable: true })\n  })),\n  \"model\": S.String,\n  \"usage\": S.optionalWith(\n    S.Struct({\n      \"prompt_tokens\": S.Number,\n      \"total_tokens\": S.Number,\n      \"cost\": S.optionalWith(S.Number, { nullable: true })\n    }),\n    { nullable: true }\n  )\n}) {}\n\n/**\n * Pricing information for the model\n */\nexport class PublicPricing extends S.Class<PublicPricing>(\"PublicPricing\")({\n  \"prompt\": BigNumberUnion,\n  \"completion\": BigNumberUnion,\n  \"request\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"image\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"image_token\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"image_output\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"audio\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"audio_output\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"input_audio_cache\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"web_search\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"internal_reasoning\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"input_cache_read\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"input_cache_write\": S.optionalWith(BigNumberUnion, { nullable: true }),\n  \"discount\": S.optionalWith(S.Number, { nullable: true })\n}) {}\n\n/**\n * Tokenizer type used by the model\n */\nexport class ModelGroup extends S.Literal(\n  \"Router\",\n  \"Media\",\n  \"Other\",\n  \"GPT\",\n  \"Claude\",\n  \"Gemini\",\n  \"Grok\",\n  \"Cohere\",\n  \"Nova\",\n  \"Qwen\",\n  \"Yi\",\n  \"DeepSeek\",\n  \"Mistral\",\n  \"Llama2\",\n  \"Llama3\",\n  \"Llama4\",\n  \"PaLM\",\n  \"RWKV\",\n  \"Qwen3\"\n) {}\n\n/**\n * Instruction format type\n */\nexport class ModelArchitectureInstructType extends S.Literal(\n  \"none\",\n  \"airoboros\",\n  \"alpaca\",\n  \"alpaca-modif\",\n  \"chatml\",\n  \"claude\",\n  \"code-llama\",\n  \"gemma\",\n  \"llama2\",\n  \"llama3\",\n  \"mistral\",\n  \"nemotron\",\n  \"neural\",\n  \"openchat\",\n  \"phi3\",\n  \"rwkv\",\n  \"vicuna\",\n  \"zephyr\",\n  \"deepseek-r1\",\n  \"deepseek-v3.1\",\n  \"qwq\",\n  \"qwen3\"\n) {}\n\nexport class InputModality extends S.Literal(\"text\", \"image\", \"file\", \"audio\", \"video\") {}\n\nexport class OutputModality extends S.Literal(\"text\", \"image\", \"embeddings\", \"audio\") {}\n\n/**\n * Model architecture information\n */\nexport class ModelArchitecture extends S.Class<ModelArchitecture>(\"ModelArchitecture\")({\n  \"tokenizer\": S.optionalWith(ModelGroup, { nullable: true }),\n  /**\n   * Instruction format type\n   */\n  \"instruct_type\": S.optionalWith(ModelArchitectureInstructType, { nullable: true }),\n  /**\n   * Primary modality of the model\n   */\n  \"modality\": S.NullOr(S.String),\n  /**\n   * Supported input modalities\n   */\n  \"input_modalities\": S.Array(InputModality),\n  /**\n   * Supported output modalities\n   */\n  \"output_modalities\": S.Array(OutputModality)\n}) {}\n\n/**\n * Information about the top provider for this model\n */\nexport class TopProviderInfo extends S.Class<TopProviderInfo>(\"TopProviderInfo\")({\n  /**\n   * Context length from the top provider\n   */\n  \"context_length\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Maximum completion tokens from the top provider\n   */\n  \"max_completion_tokens\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Whether the top provider moderates content\n   */\n  \"is_moderated\": S.Boolean\n}) {}\n\n/**\n * Per-request token limits\n */\nexport class PerRequestLimits extends S.Class<PerRequestLimits>(\"PerRequestLimits\")({\n  /**\n   * Maximum prompt tokens per request\n   */\n  \"prompt_tokens\": S.Number,\n  /**\n   * Maximum completion tokens per request\n   */\n  \"completion_tokens\": S.Number\n}) {}\n\nexport class Parameter extends S.Literal(\n  \"temperature\",\n  \"top_p\",\n  \"top_k\",\n  \"min_p\",\n  \"top_a\",\n  \"frequency_penalty\",\n  \"presence_penalty\",\n  \"repetition_penalty\",\n  \"max_tokens\",\n  \"logit_bias\",\n  \"logprobs\",\n  \"top_logprobs\",\n  \"seed\",\n  \"response_format\",\n  \"structured_outputs\",\n  \"stop\",\n  \"tools\",\n  \"tool_choice\",\n  \"parallel_tool_calls\",\n  \"include_reasoning\",\n  \"reasoning\",\n  \"reasoning_effort\",\n  \"web_search_options\",\n  \"verbosity\"\n) {}\n\n/**\n * Default parameters for this model\n */\nexport class DefaultParameters extends S.Class<DefaultParameters>(\"DefaultParameters\")({\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  \"frequency_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true\n  })\n}) {}\n\n/**\n * Information about an AI model available on OpenRouter\n */\nexport class Model extends S.Class<Model>(\"Model\")({\n  /**\n   * Unique identifier for the model\n   */\n  \"id\": S.String,\n  /**\n   * Canonical slug for the model\n   */\n  \"canonical_slug\": S.String,\n  /**\n   * Hugging Face model identifier, if applicable\n   */\n  \"hugging_face_id\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Display name of the model\n   */\n  \"name\": S.String,\n  /**\n   * Unix timestamp of when the model was created\n   */\n  \"created\": S.Number,\n  /**\n   * Description of the model\n   */\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  \"pricing\": PublicPricing,\n  /**\n   * Maximum context length in tokens\n   */\n  \"context_length\": S.NullOr(S.Number),\n  \"architecture\": ModelArchitecture,\n  \"top_provider\": TopProviderInfo,\n  \"per_request_limits\": S.NullOr(PerRequestLimits),\n  /**\n   * List of supported parameters for this model\n   */\n  \"supported_parameters\": S.Array(Parameter),\n  \"default_parameters\": S.NullOr(DefaultParameters),\n  /**\n   * The date after which the model may be removed. ISO 8601 date string (YYYY-MM-DD) or null if no expiration.\n   */\n  \"expiration_date\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * List of available models\n */\nexport class ModelsListResponseData extends S.Array(Model) {}\n\n/**\n * List of available models\n */\nexport class ModelsListResponse extends S.Class<ModelsListResponse>(\"ModelsListResponse\")({\n  \"data\": ModelsListResponseData\n}) {}\n\nexport class GetGenerationParams extends S.Struct({\n  \"id\": S.String.pipe(S.minLength(1))\n}) {}\n\n/**\n * Type of API used for the generation\n */\nexport class GetGeneration200DataApiType extends S.Literal(\"completions\", \"embeddings\") {}\n\n/**\n * Generation response\n */\nexport class GetGeneration200 extends S.Struct({\n  /**\n   * Generation data\n   */\n  \"data\": S.Struct({\n    /**\n     * Unique identifier for the generation\n     */\n    \"id\": S.String,\n    /**\n     * Upstream provider's identifier for this generation\n     */\n    \"upstream_id\": S.NullOr(S.String),\n    /**\n     * Total cost of the generation in USD\n     */\n    \"total_cost\": S.Number,\n    /**\n     * Discount applied due to caching\n     */\n    \"cache_discount\": S.NullOr(S.Number),\n    /**\n     * Cost charged by the upstream provider\n     */\n    \"upstream_inference_cost\": S.NullOr(S.Number),\n    /**\n     * ISO 8601 timestamp of when the generation was created\n     */\n    \"created_at\": S.String,\n    /**\n     * Model used for the generation\n     */\n    \"model\": S.String,\n    /**\n     * ID of the app that made the request\n     */\n    \"app_id\": S.NullOr(S.Number),\n    /**\n     * Whether the response was streamed\n     */\n    \"streamed\": S.NullOr(S.Boolean),\n    /**\n     * Whether the generation was cancelled\n     */\n    \"cancelled\": S.NullOr(S.Boolean),\n    /**\n     * Name of the provider that served the request\n     */\n    \"provider_name\": S.NullOr(S.String),\n    /**\n     * Total latency in milliseconds\n     */\n    \"latency\": S.NullOr(S.Number),\n    /**\n     * Moderation latency in milliseconds\n     */\n    \"moderation_latency\": S.NullOr(S.Number),\n    /**\n     * Time taken for generation in milliseconds\n     */\n    \"generation_time\": S.NullOr(S.Number),\n    /**\n     * Reason the generation finished\n     */\n    \"finish_reason\": S.NullOr(S.String),\n    /**\n     * Number of tokens in the prompt\n     */\n    \"tokens_prompt\": S.NullOr(S.Number),\n    /**\n     * Number of tokens in the completion\n     */\n    \"tokens_completion\": S.NullOr(S.Number),\n    /**\n     * Native prompt tokens as reported by provider\n     */\n    \"native_tokens_prompt\": S.NullOr(S.Number),\n    /**\n     * Native completion tokens as reported by provider\n     */\n    \"native_tokens_completion\": S.NullOr(S.Number),\n    /**\n     * Native completion image tokens as reported by provider\n     */\n    \"native_tokens_completion_images\": S.NullOr(S.Number),\n    /**\n     * Native reasoning tokens as reported by provider\n     */\n    \"native_tokens_reasoning\": S.NullOr(S.Number),\n    /**\n     * Native cached tokens as reported by provider\n     */\n    \"native_tokens_cached\": S.NullOr(S.Number),\n    /**\n     * Number of media items in the prompt\n     */\n    \"num_media_prompt\": S.NullOr(S.Number),\n    /**\n     * Number of audio inputs in the prompt\n     */\n    \"num_input_audio_prompt\": S.NullOr(S.Number),\n    /**\n     * Number of media items in the completion\n     */\n    \"num_media_completion\": S.NullOr(S.Number),\n    /**\n     * Number of search results included\n     */\n    \"num_search_results\": S.NullOr(S.Number),\n    /**\n     * Origin URL of the request\n     */\n    \"origin\": S.String,\n    /**\n     * Usage amount in USD\n     */\n    \"usage\": S.Number,\n    /**\n     * Whether this used bring-your-own-key\n     */\n    \"is_byok\": S.Boolean,\n    /**\n     * Native finish reason as reported by provider\n     */\n    \"native_finish_reason\": S.NullOr(S.String),\n    /**\n     * External user identifier\n     */\n    \"external_user\": S.NullOr(S.String),\n    /**\n     * Type of API used for the generation\n     */\n    \"api_type\": S.NullOr(GetGeneration200DataApiType),\n    /**\n     * Router used for the request (e.g., openrouter/auto)\n     */\n    \"router\": S.NullOr(S.String)\n  })\n}) {}\n\n/**\n * Model count data\n */\nexport class ModelsCountResponse extends S.Class<ModelsCountResponse>(\"ModelsCountResponse\")({\n  /**\n   * Model count data\n   */\n  \"data\": S.Struct({\n    /**\n     * Total number of available models\n     */\n    \"count\": S.Number\n  })\n}) {}\n\n/**\n * Filter models by use case category\n */\nexport class GetModelsParamsCategory extends S.Literal(\n  \"programming\",\n  \"roleplay\",\n  \"marketing\",\n  \"marketing/seo\",\n  \"technology\",\n  \"science\",\n  \"translation\",\n  \"legal\",\n  \"finance\",\n  \"health\",\n  \"trivia\",\n  \"academia\"\n) {}\n\nexport class GetModelsParams extends S.Struct({\n  /**\n   * Filter models by use case category\n   */\n  \"category\": S.optionalWith(GetModelsParamsCategory, { nullable: true }),\n  \"supported_parameters\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\n/**\n * Instruction format type\n */\nexport class ListEndpointsResponseArchitectureEnumInstructType extends S.Literal(\n  \"none\",\n  \"airoboros\",\n  \"alpaca\",\n  \"alpaca-modif\",\n  \"chatml\",\n  \"claude\",\n  \"code-llama\",\n  \"gemma\",\n  \"llama2\",\n  \"llama3\",\n  \"mistral\",\n  \"nemotron\",\n  \"neural\",\n  \"openchat\",\n  \"phi3\",\n  \"rwkv\",\n  \"vicuna\",\n  \"zephyr\",\n  \"deepseek-r1\",\n  \"deepseek-v3.1\",\n  \"qwq\",\n  \"qwen3\"\n) {}\n\n/**\n * Model architecture information\n */\nexport class ListEndpointsResponseArchitecture extends S.Struct({\n  \"tokenizer\": ModelGroup,\n  /**\n   * Instruction format type\n   */\n  \"instruct_type\": S.NullOr(\n    S.Literal(\n      \"none\",\n      \"airoboros\",\n      \"alpaca\",\n      \"alpaca-modif\",\n      \"chatml\",\n      \"claude\",\n      \"code-llama\",\n      \"gemma\",\n      \"llama2\",\n      \"llama3\",\n      \"mistral\",\n      \"nemotron\",\n      \"neural\",\n      \"openchat\",\n      \"phi3\",\n      \"rwkv\",\n      \"vicuna\",\n      \"zephyr\",\n      \"deepseek-r1\",\n      \"deepseek-v3.1\",\n      \"qwq\",\n      \"qwen3\"\n    )\n  ),\n  /**\n   * Primary modality of the model\n   */\n  \"modality\": S.NullOr(S.String),\n  /**\n   * Supported input modalities\n   */\n  \"input_modalities\": S.Array(InputModality),\n  /**\n   * Supported output modalities\n   */\n  \"output_modalities\": S.Array(OutputModality)\n}) {}\n\nexport class PublicEndpointQuantizationEnum\n  extends S.Literal(\"int4\", \"int8\", \"fp4\", \"fp6\", \"fp8\", \"fp16\", \"bf16\", \"fp32\", \"unknown\")\n{}\n\nexport class PublicEndpointQuantization extends PublicEndpointQuantizationEnum {}\n\nexport class EndpointStatus extends S.Literal(0, -1, -2, -3, -5, -10) {}\n\n/**\n * Latency percentiles in milliseconds over the last 30 minutes. Latency measures time to first token. Only visible when authenticated with an API key or cookie; returns null for unauthenticated requests.\n */\nexport class PercentileStats extends S.Class<PercentileStats>(\"PercentileStats\")({\n  /**\n   * Median (50th percentile)\n   */\n  \"p50\": S.Number,\n  /**\n   * 75th percentile\n   */\n  \"p75\": S.Number,\n  /**\n   * 90th percentile\n   */\n  \"p90\": S.Number,\n  /**\n   * 99th percentile\n   */\n  \"p99\": S.Number\n}) {}\n\n/**\n * Throughput percentiles in tokens per second over the last 30 minutes. Throughput measures output token generation speed. Only visible when authenticated with an API key or cookie; returns null for unauthenticated requests.\n */\nexport class PublicEndpointThroughputLast30M extends S.Struct({\n  /**\n   * Median (50th percentile)\n   */\n  \"p50\": S.Number,\n  /**\n   * 75th percentile\n   */\n  \"p75\": S.Number,\n  /**\n   * 90th percentile\n   */\n  \"p90\": S.Number,\n  /**\n   * 99th percentile\n   */\n  \"p99\": S.Number\n}) {}\n\n/**\n * Information about a specific model endpoint\n */\nexport class PublicEndpoint extends S.Class<PublicEndpoint>(\"PublicEndpoint\")({\n  \"name\": S.String,\n  /**\n   * The unique identifier for the model (permaslug)\n   */\n  \"model_id\": S.String,\n  \"model_name\": S.String,\n  \"context_length\": S.Number,\n  \"pricing\": S.Struct({\n    \"prompt\": BigNumberUnion,\n    \"completion\": BigNumberUnion,\n    \"request\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"image\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"image_token\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"image_output\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"audio\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"audio_output\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"input_audio_cache\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"web_search\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"internal_reasoning\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"input_cache_read\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"input_cache_write\": S.optionalWith(BigNumberUnion, { nullable: true }),\n    \"discount\": S.optionalWith(S.Number, { nullable: true })\n  }),\n  \"provider_name\": ProviderName,\n  \"tag\": S.String,\n  \"quantization\": PublicEndpointQuantization,\n  \"max_completion_tokens\": S.NullOr(S.Number),\n  \"max_prompt_tokens\": S.NullOr(S.Number),\n  \"supported_parameters\": S.Array(Parameter),\n  \"status\": S.optionalWith(EndpointStatus, { nullable: true }),\n  \"uptime_last_30m\": S.NullOr(S.Number),\n  \"supports_implicit_caching\": S.Boolean,\n  \"latency_last_30m\": S.NullOr(PercentileStats),\n  \"throughput_last_30m\": PublicEndpointThroughputLast30M\n}) {}\n\n/**\n * List of available endpoints for a model\n */\nexport class ListEndpointsResponse extends S.Class<ListEndpointsResponse>(\"ListEndpointsResponse\")({\n  /**\n   * Unique identifier for the model\n   */\n  \"id\": S.String,\n  /**\n   * Display name of the model\n   */\n  \"name\": S.String,\n  /**\n   * Unix timestamp of when the model was created\n   */\n  \"created\": S.Number,\n  /**\n   * Description of the model\n   */\n  \"description\": S.String,\n  \"architecture\": ListEndpointsResponseArchitecture,\n  /**\n   * List of available endpoints for this model\n   */\n  \"endpoints\": S.Array(PublicEndpoint)\n}) {}\n\nexport class ListEndpoints200 extends S.Struct({\n  \"data\": ListEndpointsResponse\n}) {}\n\nexport class ListEndpointsZdr200 extends S.Struct({\n  \"data\": S.Array(PublicEndpoint)\n}) {}\n\nexport class ListProviders200 extends S.Struct({\n  \"data\": S.Array(S.Struct({\n    /**\n     * Display name of the provider\n     */\n    \"name\": S.String,\n    /**\n     * URL-friendly identifier for the provider\n     */\n    \"slug\": S.String,\n    /**\n     * URL to the provider's privacy policy\n     */\n    \"privacy_policy_url\": S.NullOr(S.String),\n    /**\n     * URL to the provider's terms of service\n     */\n    \"terms_of_service_url\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * URL to the provider's status page\n     */\n    \"status_page_url\": S.optionalWith(S.String, { nullable: true })\n  }))\n}) {}\n\nexport class ListParams extends S.Struct({\n  /**\n   * Whether to include disabled API keys in the response\n   */\n  \"include_disabled\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Number of API keys to skip for pagination\n   */\n  \"offset\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class List200 extends S.Struct({\n  /**\n   * List of API keys\n   */\n  \"data\": S.Array(S.Struct({\n    /**\n     * Unique hash identifier for the API key\n     */\n    \"hash\": S.String,\n    /**\n     * Name of the API key\n     */\n    \"name\": S.String,\n    /**\n     * Human-readable label for the API key\n     */\n    \"label\": S.String,\n    /**\n     * Whether the API key is disabled\n     */\n    \"disabled\": S.Boolean,\n    /**\n     * Spending limit for the API key in USD\n     */\n    \"limit\": S.NullOr(S.Number),\n    /**\n     * Remaining spending limit in USD\n     */\n    \"limit_remaining\": S.NullOr(S.Number),\n    /**\n     * Type of limit reset for the API key\n     */\n    \"limit_reset\": S.NullOr(S.String),\n    /**\n     * Whether to include external BYOK usage in the credit limit\n     */\n    \"include_byok_in_limit\": S.Boolean,\n    /**\n     * Total OpenRouter credit usage (in USD) for the API key\n     */\n    \"usage\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC day\n     */\n    \"usage_daily\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)\n     */\n    \"usage_weekly\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC month\n     */\n    \"usage_monthly\": S.Number,\n    /**\n     * Total external BYOK usage (in USD) for the API key\n     */\n    \"byok_usage\": S.Number,\n    /**\n     * External BYOK usage (in USD) for the current UTC day\n     */\n    \"byok_usage_daily\": S.Number,\n    /**\n     * External BYOK usage (in USD) for the current UTC week (Monday-Sunday)\n     */\n    \"byok_usage_weekly\": S.Number,\n    /**\n     * External BYOK usage (in USD) for current UTC month\n     */\n    \"byok_usage_monthly\": S.Number,\n    /**\n     * ISO 8601 timestamp of when the API key was created\n     */\n    \"created_at\": S.String,\n    /**\n     * ISO 8601 timestamp of when the API key was last updated\n     */\n    \"updated_at\": S.NullOr(S.String),\n    /**\n     * ISO 8601 UTC timestamp when the API key expires, or null if no expiration\n     */\n    \"expires_at\": S.optionalWith(S.String, { nullable: true })\n  }))\n}) {}\n\n/**\n * Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.\n */\nexport class CreateKeysRequestLimitReset extends S.Literal(\"daily\", \"weekly\", \"monthly\") {}\n\nexport class CreateKeysRequest extends S.Class<CreateKeysRequest>(\"CreateKeysRequest\")({\n  /**\n   * Name for the new API key\n   */\n  \"name\": S.String.pipe(S.minLength(1)),\n  /**\n   * Optional spending limit for the API key in USD\n   */\n  \"limit\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.\n   */\n  \"limit_reset\": S.optionalWith(CreateKeysRequestLimitReset, { nullable: true }),\n  /**\n   * Whether to include BYOK usage in the limit\n   */\n  \"include_byok_in_limit\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected\n   */\n  \"expires_at\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class CreateKeys201 extends S.Struct({\n  /**\n   * The created API key information\n   */\n  \"data\": S.Struct({\n    /**\n     * Unique hash identifier for the API key\n     */\n    \"hash\": S.String,\n    /**\n     * Name of the API key\n     */\n    \"name\": S.String,\n    /**\n     * Human-readable label for the API key\n     */\n    \"label\": S.String,\n    /**\n     * Whether the API key is disabled\n     */\n    \"disabled\": S.Boolean,\n    /**\n     * Spending limit for the API key in USD\n     */\n    \"limit\": S.NullOr(S.Number),\n    /**\n     * Remaining spending limit in USD\n     */\n    \"limit_remaining\": S.NullOr(S.Number),\n    /**\n     * Type of limit reset for the API key\n     */\n    \"limit_reset\": S.NullOr(S.String),\n    /**\n     * Whether to include external BYOK usage in the credit limit\n     */\n    \"include_byok_in_limit\": S.Boolean,\n    /**\n     * Total OpenRouter credit usage (in USD) for the API key\n     */\n    \"usage\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC day\n     */\n    \"usage_daily\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)\n     */\n    \"usage_weekly\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC month\n     */\n    \"usage_monthly\": S.Number,\n    /**\n     * Total external BYOK usage (in USD) for the API key\n     */\n    \"byok_usage\": S.Number,\n    /**\n     * External BYOK usage (in USD) for the current UTC day\n     */\n    \"byok_usage_daily\": S.Number,\n    /**\n     * External BYOK usage (in USD) for the current UTC week (Monday-Sunday)\n     */\n    \"byok_usage_weekly\": S.Number,\n    /**\n     * External BYOK usage (in USD) for current UTC month\n     */\n    \"byok_usage_monthly\": S.Number,\n    /**\n     * ISO 8601 timestamp of when the API key was created\n     */\n    \"created_at\": S.String,\n    /**\n     * ISO 8601 timestamp of when the API key was last updated\n     */\n    \"updated_at\": S.NullOr(S.String),\n    /**\n     * ISO 8601 UTC timestamp when the API key expires, or null if no expiration\n     */\n    \"expires_at\": S.optionalWith(S.String, { nullable: true })\n  }),\n  /**\n   * The actual API key string (only shown once)\n   */\n  \"key\": S.String\n}) {}\n\nexport class GetKey200 extends S.Struct({\n  /**\n   * The API key information\n   */\n  \"data\": S.Struct({\n    /**\n     * Unique hash identifier for the API key\n     */\n    \"hash\": S.String,\n    /**\n     * Name of the API key\n     */\n    \"name\": S.String,\n    /**\n     * Human-readable label for the API key\n     */\n    \"label\": S.String,\n    /**\n     * Whether the API key is disabled\n     */\n    \"disabled\": S.Boolean,\n    /**\n     * Spending limit for the API key in USD\n     */\n    \"limit\": S.NullOr(S.Number),\n    /**\n     * Remaining spending limit in USD\n     */\n    \"limit_remaining\": S.NullOr(S.Number),\n    /**\n     * Type of limit reset for the API key\n     */\n    \"limit_reset\": S.NullOr(S.String),\n    /**\n     * Whether to include external BYOK usage in the credit limit\n     */\n    \"include_byok_in_limit\": S.Boolean,\n    /**\n     * Total OpenRouter credit usage (in USD) for the API key\n     */\n    \"usage\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC day\n     */\n    \"usage_daily\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)\n     */\n    \"usage_weekly\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC month\n     */\n    \"usage_monthly\": S.Number,\n    /**\n     * Total external BYOK usage (in USD) for the API key\n     */\n    \"byok_usage\": S.Number,\n    /**\n     * External BYOK usage (in USD) for the current UTC day\n     */\n    \"byok_usage_daily\": S.Number,\n    /**\n     * External BYOK usage (in USD) for the current UTC week (Monday-Sunday)\n     */\n    \"byok_usage_weekly\": S.Number,\n    /**\n     * External BYOK usage (in USD) for current UTC month\n     */\n    \"byok_usage_monthly\": S.Number,\n    /**\n     * ISO 8601 timestamp of when the API key was created\n     */\n    \"created_at\": S.String,\n    /**\n     * ISO 8601 timestamp of when the API key was last updated\n     */\n    \"updated_at\": S.NullOr(S.String),\n    /**\n     * ISO 8601 UTC timestamp when the API key expires, or null if no expiration\n     */\n    \"expires_at\": S.optionalWith(S.String, { nullable: true })\n  })\n}) {}\n\nexport class DeleteKeys200 extends S.Struct({\n  /**\n   * Confirmation that the API key was deleted\n   */\n  \"deleted\": S.Literal(true)\n}) {}\n\n/**\n * New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.\n */\nexport class UpdateKeysRequestLimitReset extends S.Literal(\"daily\", \"weekly\", \"monthly\") {}\n\nexport class UpdateKeysRequest extends S.Class<UpdateKeysRequest>(\"UpdateKeysRequest\")({\n  /**\n   * New name for the API key\n   */\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Whether to disable the API key\n   */\n  \"disabled\": S.optionalWith(S.Boolean, { nullable: true }),\n  /**\n   * New spending limit for the API key in USD\n   */\n  \"limit\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.\n   */\n  \"limit_reset\": S.optionalWith(UpdateKeysRequestLimitReset, { nullable: true }),\n  /**\n   * Whether to include BYOK usage in the limit\n   */\n  \"include_byok_in_limit\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class UpdateKeys200 extends S.Struct({\n  /**\n   * The updated API key information\n   */\n  \"data\": S.Struct({\n    /**\n     * Unique hash identifier for the API key\n     */\n    \"hash\": S.String,\n    /**\n     * Name of the API key\n     */\n    \"name\": S.String,\n    /**\n     * Human-readable label for the API key\n     */\n    \"label\": S.String,\n    /**\n     * Whether the API key is disabled\n     */\n    \"disabled\": S.Boolean,\n    /**\n     * Spending limit for the API key in USD\n     */\n    \"limit\": S.NullOr(S.Number),\n    /**\n     * Remaining spending limit in USD\n     */\n    \"limit_remaining\": S.NullOr(S.Number),\n    /**\n     * Type of limit reset for the API key\n     */\n    \"limit_reset\": S.NullOr(S.String),\n    /**\n     * Whether to include external BYOK usage in the credit limit\n     */\n    \"include_byok_in_limit\": S.Boolean,\n    /**\n     * Total OpenRouter credit usage (in USD) for the API key\n     */\n    \"usage\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC day\n     */\n    \"usage_daily\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)\n     */\n    \"usage_weekly\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC month\n     */\n    \"usage_monthly\": S.Number,\n    /**\n     * Total external BYOK usage (in USD) for the API key\n     */\n    \"byok_usage\": S.Number,\n    /**\n     * External BYOK usage (in USD) for the current UTC day\n     */\n    \"byok_usage_daily\": S.Number,\n    /**\n     * External BYOK usage (in USD) for the current UTC week (Monday-Sunday)\n     */\n    \"byok_usage_weekly\": S.Number,\n    /**\n     * External BYOK usage (in USD) for current UTC month\n     */\n    \"byok_usage_monthly\": S.Number,\n    /**\n     * ISO 8601 timestamp of when the API key was created\n     */\n    \"created_at\": S.String,\n    /**\n     * ISO 8601 timestamp of when the API key was last updated\n     */\n    \"updated_at\": S.NullOr(S.String),\n    /**\n     * ISO 8601 UTC timestamp when the API key expires, or null if no expiration\n     */\n    \"expires_at\": S.optionalWith(S.String, { nullable: true })\n  })\n}) {}\n\nexport class ListGuardrailsParams extends S.Struct({\n  /**\n   * Number of records to skip for pagination\n   */\n  \"offset\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Maximum number of records to return (max 100)\n   */\n  \"limit\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListGuardrails200 extends S.Struct({\n  /**\n   * List of guardrails\n   */\n  \"data\": S.Array(S.Struct({\n    /**\n     * Unique identifier for the guardrail\n     */\n    \"id\": S.String,\n    /**\n     * Name of the guardrail\n     */\n    \"name\": S.String,\n    /**\n     * Description of the guardrail\n     */\n    \"description\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Spending limit in USD\n     */\n    \"limit_usd\": S.optionalWith(S.Number.pipe(S.greaterThan(0)), { nullable: true }),\n    /**\n     * Interval at which the limit resets (daily, weekly, monthly)\n     */\n    \"reset_interval\": S.optionalWith(S.Literal(\"daily\", \"weekly\", \"monthly\"), { nullable: true }),\n    /**\n     * List of allowed provider IDs\n     */\n    \"allowed_providers\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    /**\n     * Array of model canonical_slugs (immutable identifiers)\n     */\n    \"allowed_models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    /**\n     * Whether to enforce zero data retention\n     */\n    \"enforce_zdr\": S.optionalWith(S.Boolean, { nullable: true }),\n    /**\n     * ISO 8601 timestamp of when the guardrail was created\n     */\n    \"created_at\": S.String,\n    /**\n     * ISO 8601 timestamp of when the guardrail was last updated\n     */\n    \"updated_at\": S.optionalWith(S.String, { nullable: true })\n  })),\n  /**\n   * Total number of guardrails\n   */\n  \"total_count\": S.Number\n}) {}\n\n/**\n * Interval at which the limit resets (daily, weekly, monthly)\n */\nexport class CreateGuardrailRequestResetInterval extends S.Literal(\"daily\", \"weekly\", \"monthly\") {}\n\nexport class CreateGuardrailRequest extends S.Class<CreateGuardrailRequest>(\"CreateGuardrailRequest\")({\n  /**\n   * Name for the new guardrail\n   */\n  \"name\": S.String.pipe(S.minLength(1), S.maxLength(200)),\n  /**\n   * Description of the guardrail\n   */\n  \"description\": S.optionalWith(S.String.pipe(S.maxLength(1000)), { nullable: true }),\n  /**\n   * Spending limit in USD\n   */\n  \"limit_usd\": S.optionalWith(S.Number.pipe(S.greaterThan(0)), { nullable: true }),\n  /**\n   * Interval at which the limit resets (daily, weekly, monthly)\n   */\n  \"reset_interval\": S.optionalWith(CreateGuardrailRequestResetInterval, { nullable: true }),\n  /**\n   * List of allowed provider IDs\n   */\n  \"allowed_providers\": S.optionalWith(S.NonEmptyArray(S.String).pipe(S.minItems(1)), { nullable: true }),\n  /**\n   * Array of model identifiers (slug or canonical_slug accepted)\n   */\n  \"allowed_models\": S.optionalWith(S.NonEmptyArray(S.String).pipe(S.minItems(1)), { nullable: true }),\n  /**\n   * Whether to enforce zero data retention\n   */\n  \"enforce_zdr\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * Interval at which the limit resets (daily, weekly, monthly)\n */\nexport class CreateGuardrail201DataResetInterval extends S.Literal(\"daily\", \"weekly\", \"monthly\") {}\n\nexport class CreateGuardrail201 extends S.Struct({\n  /**\n   * The created guardrail\n   */\n  \"data\": S.Struct({\n    /**\n     * Unique identifier for the guardrail\n     */\n    \"id\": S.String,\n    /**\n     * Name of the guardrail\n     */\n    \"name\": S.String,\n    /**\n     * Description of the guardrail\n     */\n    \"description\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Spending limit in USD\n     */\n    \"limit_usd\": S.optionalWith(S.Number.pipe(S.greaterThan(0)), { nullable: true }),\n    /**\n     * Interval at which the limit resets (daily, weekly, monthly)\n     */\n    \"reset_interval\": S.optionalWith(CreateGuardrail201DataResetInterval, { nullable: true }),\n    /**\n     * List of allowed provider IDs\n     */\n    \"allowed_providers\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    /**\n     * Array of model canonical_slugs (immutable identifiers)\n     */\n    \"allowed_models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    /**\n     * Whether to enforce zero data retention\n     */\n    \"enforce_zdr\": S.optionalWith(S.Boolean, { nullable: true }),\n    /**\n     * ISO 8601 timestamp of when the guardrail was created\n     */\n    \"created_at\": S.String,\n    /**\n     * ISO 8601 timestamp of when the guardrail was last updated\n     */\n    \"updated_at\": S.optionalWith(S.String, { nullable: true })\n  })\n}) {}\n\n/**\n * Interval at which the limit resets (daily, weekly, monthly)\n */\nexport class GetGuardrail200DataResetInterval extends S.Literal(\"daily\", \"weekly\", \"monthly\") {}\n\nexport class GetGuardrail200 extends S.Struct({\n  /**\n   * The guardrail\n   */\n  \"data\": S.Struct({\n    /**\n     * Unique identifier for the guardrail\n     */\n    \"id\": S.String,\n    /**\n     * Name of the guardrail\n     */\n    \"name\": S.String,\n    /**\n     * Description of the guardrail\n     */\n    \"description\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Spending limit in USD\n     */\n    \"limit_usd\": S.optionalWith(S.Number.pipe(S.greaterThan(0)), { nullable: true }),\n    /**\n     * Interval at which the limit resets (daily, weekly, monthly)\n     */\n    \"reset_interval\": S.optionalWith(GetGuardrail200DataResetInterval, { nullable: true }),\n    /**\n     * List of allowed provider IDs\n     */\n    \"allowed_providers\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    /**\n     * Array of model canonical_slugs (immutable identifiers)\n     */\n    \"allowed_models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    /**\n     * Whether to enforce zero data retention\n     */\n    \"enforce_zdr\": S.optionalWith(S.Boolean, { nullable: true }),\n    /**\n     * ISO 8601 timestamp of when the guardrail was created\n     */\n    \"created_at\": S.String,\n    /**\n     * ISO 8601 timestamp of when the guardrail was last updated\n     */\n    \"updated_at\": S.optionalWith(S.String, { nullable: true })\n  })\n}) {}\n\nexport class DeleteGuardrail200 extends S.Struct({\n  /**\n   * Confirmation that the guardrail was deleted\n   */\n  \"deleted\": S.Literal(true)\n}) {}\n\n/**\n * Interval at which the limit resets (daily, weekly, monthly)\n */\nexport class UpdateGuardrailRequestResetInterval extends S.Literal(\"daily\", \"weekly\", \"monthly\") {}\n\nexport class UpdateGuardrailRequest extends S.Class<UpdateGuardrailRequest>(\"UpdateGuardrailRequest\")({\n  /**\n   * New name for the guardrail\n   */\n  \"name\": S.optionalWith(S.String.pipe(S.minLength(1), S.maxLength(200)), { nullable: true }),\n  /**\n   * New description for the guardrail\n   */\n  \"description\": S.optionalWith(S.String.pipe(S.maxLength(1000)), { nullable: true }),\n  /**\n   * New spending limit in USD\n   */\n  \"limit_usd\": S.optionalWith(S.Number.pipe(S.greaterThan(0)), { nullable: true }),\n  /**\n   * Interval at which the limit resets (daily, weekly, monthly)\n   */\n  \"reset_interval\": S.optionalWith(UpdateGuardrailRequestResetInterval, { nullable: true }),\n  /**\n   * New list of allowed provider IDs\n   */\n  \"allowed_providers\": S.optionalWith(S.NonEmptyArray(S.String).pipe(S.minItems(1)), { nullable: true }),\n  /**\n   * Array of model identifiers (slug or canonical_slug accepted)\n   */\n  \"allowed_models\": S.optionalWith(S.NonEmptyArray(S.String).pipe(S.minItems(1)), { nullable: true }),\n  /**\n   * Whether to enforce zero data retention\n   */\n  \"enforce_zdr\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\n/**\n * Interval at which the limit resets (daily, weekly, monthly)\n */\nexport class UpdateGuardrail200DataResetInterval extends S.Literal(\"daily\", \"weekly\", \"monthly\") {}\n\nexport class UpdateGuardrail200 extends S.Struct({\n  /**\n   * The updated guardrail\n   */\n  \"data\": S.Struct({\n    /**\n     * Unique identifier for the guardrail\n     */\n    \"id\": S.String,\n    /**\n     * Name of the guardrail\n     */\n    \"name\": S.String,\n    /**\n     * Description of the guardrail\n     */\n    \"description\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Spending limit in USD\n     */\n    \"limit_usd\": S.optionalWith(S.Number.pipe(S.greaterThan(0)), { nullable: true }),\n    /**\n     * Interval at which the limit resets (daily, weekly, monthly)\n     */\n    \"reset_interval\": S.optionalWith(UpdateGuardrail200DataResetInterval, { nullable: true }),\n    /**\n     * List of allowed provider IDs\n     */\n    \"allowed_providers\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    /**\n     * Array of model canonical_slugs (immutable identifiers)\n     */\n    \"allowed_models\": S.optionalWith(S.Array(S.String), { nullable: true }),\n    /**\n     * Whether to enforce zero data retention\n     */\n    \"enforce_zdr\": S.optionalWith(S.Boolean, { nullable: true }),\n    /**\n     * ISO 8601 timestamp of when the guardrail was created\n     */\n    \"created_at\": S.String,\n    /**\n     * ISO 8601 timestamp of when the guardrail was last updated\n     */\n    \"updated_at\": S.optionalWith(S.String, { nullable: true })\n  })\n}) {}\n\nexport class ListKeyAssignmentsParams extends S.Struct({\n  /**\n   * Number of records to skip for pagination\n   */\n  \"offset\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Maximum number of records to return (max 100)\n   */\n  \"limit\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListKeyAssignments200 extends S.Struct({\n  /**\n   * List of key assignments\n   */\n  \"data\": S.Array(S.Struct({\n    /**\n     * Unique identifier for the assignment\n     */\n    \"id\": S.String,\n    /**\n     * Hash of the assigned API key\n     */\n    \"key_hash\": S.String,\n    /**\n     * ID of the guardrail\n     */\n    \"guardrail_id\": S.String,\n    /**\n     * Name of the API key\n     */\n    \"key_name\": S.String,\n    /**\n     * Label of the API key\n     */\n    \"key_label\": S.String,\n    /**\n     * User ID of who made the assignment\n     */\n    \"assigned_by\": S.NullOr(S.String),\n    /**\n     * ISO 8601 timestamp of when the assignment was created\n     */\n    \"created_at\": S.String\n  })),\n  /**\n   * Total number of key assignments for this guardrail\n   */\n  \"total_count\": S.Number\n}) {}\n\nexport class ListMemberAssignmentsParams extends S.Struct({\n  /**\n   * Number of records to skip for pagination\n   */\n  \"offset\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Maximum number of records to return (max 100)\n   */\n  \"limit\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListMemberAssignments200 extends S.Struct({\n  /**\n   * List of member assignments\n   */\n  \"data\": S.Array(S.Struct({\n    /**\n     * Unique identifier for the assignment\n     */\n    \"id\": S.String,\n    /**\n     * Clerk user ID of the assigned member\n     */\n    \"user_id\": S.String,\n    /**\n     * Organization ID\n     */\n    \"organization_id\": S.String,\n    /**\n     * ID of the guardrail\n     */\n    \"guardrail_id\": S.String,\n    /**\n     * User ID of who made the assignment\n     */\n    \"assigned_by\": S.NullOr(S.String),\n    /**\n     * ISO 8601 timestamp of when the assignment was created\n     */\n    \"created_at\": S.String\n  })),\n  /**\n   * Total number of member assignments\n   */\n  \"total_count\": S.Number\n}) {}\n\nexport class ListGuardrailKeyAssignmentsParams extends S.Struct({\n  /**\n   * Number of records to skip for pagination\n   */\n  \"offset\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Maximum number of records to return (max 100)\n   */\n  \"limit\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListGuardrailKeyAssignments200 extends S.Struct({\n  /**\n   * List of key assignments\n   */\n  \"data\": S.Array(S.Struct({\n    /**\n     * Unique identifier for the assignment\n     */\n    \"id\": S.String,\n    /**\n     * Hash of the assigned API key\n     */\n    \"key_hash\": S.String,\n    /**\n     * ID of the guardrail\n     */\n    \"guardrail_id\": S.String,\n    /**\n     * Name of the API key\n     */\n    \"key_name\": S.String,\n    /**\n     * Label of the API key\n     */\n    \"key_label\": S.String,\n    /**\n     * User ID of who made the assignment\n     */\n    \"assigned_by\": S.NullOr(S.String),\n    /**\n     * ISO 8601 timestamp of when the assignment was created\n     */\n    \"created_at\": S.String\n  })),\n  /**\n   * Total number of key assignments for this guardrail\n   */\n  \"total_count\": S.Number\n}) {}\n\nexport class BulkAssignKeysToGuardrailRequest\n  extends S.Class<BulkAssignKeysToGuardrailRequest>(\"BulkAssignKeysToGuardrailRequest\")({\n    /**\n     * Array of API key hashes to assign to the guardrail\n     */\n    \"key_hashes\": S.NonEmptyArray(S.String.pipe(S.minLength(1))).pipe(S.minItems(1))\n  })\n{}\n\nexport class BulkAssignKeysToGuardrail200 extends S.Struct({\n  /**\n   * Number of keys successfully assigned\n   */\n  \"assigned_count\": S.Number\n}) {}\n\nexport class ListGuardrailMemberAssignmentsParams extends S.Struct({\n  /**\n   * Number of records to skip for pagination\n   */\n  \"offset\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * Maximum number of records to return (max 100)\n   */\n  \"limit\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ListGuardrailMemberAssignments200 extends S.Struct({\n  /**\n   * List of member assignments\n   */\n  \"data\": S.Array(S.Struct({\n    /**\n     * Unique identifier for the assignment\n     */\n    \"id\": S.String,\n    /**\n     * Clerk user ID of the assigned member\n     */\n    \"user_id\": S.String,\n    /**\n     * Organization ID\n     */\n    \"organization_id\": S.String,\n    /**\n     * ID of the guardrail\n     */\n    \"guardrail_id\": S.String,\n    /**\n     * User ID of who made the assignment\n     */\n    \"assigned_by\": S.NullOr(S.String),\n    /**\n     * ISO 8601 timestamp of when the assignment was created\n     */\n    \"created_at\": S.String\n  })),\n  /**\n   * Total number of member assignments\n   */\n  \"total_count\": S.Number\n}) {}\n\nexport class BulkAssignMembersToGuardrailRequest\n  extends S.Class<BulkAssignMembersToGuardrailRequest>(\"BulkAssignMembersToGuardrailRequest\")({\n    /**\n     * Array of member user IDs to assign to the guardrail\n     */\n    \"member_user_ids\": S.NonEmptyArray(S.String.pipe(S.minLength(1))).pipe(S.minItems(1))\n  })\n{}\n\nexport class BulkAssignMembersToGuardrail200 extends S.Struct({\n  /**\n   * Number of members successfully assigned\n   */\n  \"assigned_count\": S.Number\n}) {}\n\nexport class BulkUnassignKeysFromGuardrailRequest\n  extends S.Class<BulkUnassignKeysFromGuardrailRequest>(\"BulkUnassignKeysFromGuardrailRequest\")({\n    /**\n     * Array of API key hashes to unassign from the guardrail\n     */\n    \"key_hashes\": S.NonEmptyArray(S.String.pipe(S.minLength(1))).pipe(S.minItems(1))\n  })\n{}\n\nexport class BulkUnassignKeysFromGuardrail200 extends S.Struct({\n  /**\n   * Number of keys successfully unassigned\n   */\n  \"unassigned_count\": S.Number\n}) {}\n\nexport class BulkUnassignMembersFromGuardrailRequest\n  extends S.Class<BulkUnassignMembersFromGuardrailRequest>(\"BulkUnassignMembersFromGuardrailRequest\")({\n    /**\n     * Array of member user IDs to unassign from the guardrail\n     */\n    \"member_user_ids\": S.NonEmptyArray(S.String.pipe(S.minLength(1))).pipe(S.minItems(1))\n  })\n{}\n\nexport class BulkUnassignMembersFromGuardrail200 extends S.Struct({\n  /**\n   * Number of members successfully unassigned\n   */\n  \"unassigned_count\": S.Number\n}) {}\n\nexport class GetCurrentKey200 extends S.Struct({\n  /**\n   * Current API key information\n   */\n  \"data\": S.Struct({\n    /**\n     * Human-readable label for the API key\n     */\n    \"label\": S.String,\n    /**\n     * Spending limit for the API key in USD\n     */\n    \"limit\": S.NullOr(S.Number),\n    /**\n     * Total OpenRouter credit usage (in USD) for the API key\n     */\n    \"usage\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC day\n     */\n    \"usage_daily\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)\n     */\n    \"usage_weekly\": S.Number,\n    /**\n     * OpenRouter credit usage (in USD) for the current UTC month\n     */\n    \"usage_monthly\": S.Number,\n    /**\n     * Total external BYOK usage (in USD) for the API key\n     */\n    \"byok_usage\": S.Number,\n    /**\n     * External BYOK usage (in USD) for the current UTC day\n     */\n    \"byok_usage_daily\": S.Number,\n    /**\n     * External BYOK usage (in USD) for the current UTC week (Monday-Sunday)\n     */\n    \"byok_usage_weekly\": S.Number,\n    /**\n     * External BYOK usage (in USD) for current UTC month\n     */\n    \"byok_usage_monthly\": S.Number,\n    /**\n     * Whether this is a free tier API key\n     */\n    \"is_free_tier\": S.Boolean,\n    /**\n     * Whether this is a provisioning key\n     */\n    \"is_provisioning_key\": S.Boolean,\n    /**\n     * Remaining spending limit in USD\n     */\n    \"limit_remaining\": S.NullOr(S.Number),\n    /**\n     * Type of limit reset for the API key\n     */\n    \"limit_reset\": S.NullOr(S.String),\n    /**\n     * Whether to include external BYOK usage in the credit limit\n     */\n    \"include_byok_in_limit\": S.Boolean,\n    /**\n     * ISO 8601 UTC timestamp when the API key expires, or null if no expiration\n     */\n    \"expires_at\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * Legacy rate limit information about a key. Will always return -1.\n     */\n    \"rate_limit\": S.Struct({\n      /**\n       * Number of requests allowed per interval\n       */\n      \"requests\": S.Number,\n      /**\n       * Rate limit interval\n       */\n      \"interval\": S.String,\n      /**\n       * Note about the rate limit\n       */\n      \"note\": S.String\n    })\n  })\n}) {}\n\n/**\n * The method used to generate the code challenge\n */\nexport class ExchangeAuthCodeForAPIKeyRequestCodeChallengeMethod extends S.Literal(\"S256\", \"plain\") {}\n\nexport class ExchangeAuthCodeForAPIKeyRequest\n  extends S.Class<ExchangeAuthCodeForAPIKeyRequest>(\"ExchangeAuthCodeForAPIKeyRequest\")({\n    /**\n     * The authorization code received from the OAuth redirect\n     */\n    \"code\": S.String,\n    /**\n     * The code verifier if code_challenge was used in the authorization request\n     */\n    \"code_verifier\": S.optionalWith(S.String, { nullable: true }),\n    /**\n     * The method used to generate the code challenge\n     */\n    \"code_challenge_method\": S.optionalWith(ExchangeAuthCodeForAPIKeyRequestCodeChallengeMethod, { nullable: true })\n  })\n{}\n\nexport class ExchangeAuthCodeForAPIKey200 extends S.Struct({\n  /**\n   * The API key to use for OpenRouter requests\n   */\n  \"key\": S.String,\n  /**\n   * User ID associated with the API key\n   */\n  \"user_id\": S.NullOr(S.String)\n}) {}\n\n/**\n * The method used to generate the code challenge\n */\nexport class CreateAuthKeysCodeRequestCodeChallengeMethod extends S.Literal(\"S256\", \"plain\") {}\n\nexport class CreateAuthKeysCodeRequest extends S.Class<CreateAuthKeysCodeRequest>(\"CreateAuthKeysCodeRequest\")({\n  /**\n   * The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed.\n   */\n  \"callback_url\": S.String,\n  /**\n   * PKCE code challenge for enhanced security\n   */\n  \"code_challenge\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * The method used to generate the code challenge\n   */\n  \"code_challenge_method\": S.optionalWith(CreateAuthKeysCodeRequestCodeChallengeMethod, { nullable: true }),\n  /**\n   * Credit limit for the API key to be created\n   */\n  \"limit\": S.optionalWith(S.Number, { nullable: true }),\n  /**\n   * Optional expiration time for the API key to be created\n   */\n  \"expires_at\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class CreateAuthKeysCode200 extends S.Struct({\n  /**\n   * Auth code data\n   */\n  \"data\": S.Struct({\n    /**\n     * The authorization code ID to use in the exchange request\n     */\n    \"id\": S.String,\n    /**\n     * The application ID associated with this auth code\n     */\n    \"app_id\": S.Number,\n    /**\n     * ISO 8601 timestamp of when the auth code was created\n     */\n    \"created_at\": S.String\n  })\n}) {}\n\nexport class ChatGenerationParamsProviderEnumDataCollectionEnum extends S.Literal(\"deny\", \"allow\") {}\n\nexport class Schema0 extends S.Array(\n  S.Union(\n    S.Literal(\n      \"AI21\",\n      \"AionLabs\",\n      \"Alibaba\",\n      \"Amazon Bedrock\",\n      \"Amazon Nova\",\n      \"Anthropic\",\n      \"Arcee AI\",\n      \"AtlasCloud\",\n      \"Avian\",\n      \"Azure\",\n      \"BaseTen\",\n      \"BytePlus\",\n      \"Black Forest Labs\",\n      \"Cerebras\",\n      \"Chutes\",\n      \"Cirrascale\",\n      \"Clarifai\",\n      \"Cloudflare\",\n      \"Cohere\",\n      \"Crusoe\",\n      \"DeepInfra\",\n      \"DeepSeek\",\n      \"Featherless\",\n      \"Fireworks\",\n      \"Friendli\",\n      \"GMICloud\",\n      \"Google\",\n      \"Google AI Studio\",\n      \"Groq\",\n      \"Hyperbolic\",\n      \"Inception\",\n      \"Inceptron\",\n      \"InferenceNet\",\n      \"Infermatic\",\n      \"Inflection\",\n      \"Liquid\",\n      \"Mara\",\n      \"Mancer 2\",\n      \"Minimax\",\n      \"ModelRun\",\n      \"Mistral\",\n      \"Modular\",\n      \"Moonshot AI\",\n      \"Morph\",\n      \"NCompass\",\n      \"Nebius\",\n      \"NextBit\",\n      \"Novita\",\n      \"Nvidia\",\n      \"OpenAI\",\n      \"OpenInference\",\n      \"Parasail\",\n      \"Perplexity\",\n      \"Phala\",\n      \"Relace\",\n      \"SambaNova\",\n      \"Seed\",\n      \"SiliconFlow\",\n      \"Sourceful\",\n      \"Stealth\",\n      \"StreamLake\",\n      \"Switchpoint\",\n      \"Together\",\n      \"Upstage\",\n      \"Venice\",\n      \"WandB\",\n      \"Xiaomi\",\n      \"xAI\",\n      \"Z.AI\",\n      \"FakeProvider\"\n    ),\n    S.String\n  )\n) {}\n\nexport class ProviderSortUnion extends S.Union(ProviderSort, ProviderSortConfig) {}\n\nexport class Schema1 extends S.Union(S.Number, S.String, S.Number) {}\n\nexport class ChatGenerationParamsRouteEnum extends S.Literal(\"fallback\", \"sort\") {}\n\nexport class ChatMessageContentItemCacheControlTtl extends S.Literal(\"5m\", \"1h\") {}\n\nexport class ChatMessageContentItemCacheControl\n  extends S.Class<ChatMessageContentItemCacheControl>(\"ChatMessageContentItemCacheControl\")({\n    \"type\": S.Literal(\"ephemeral\"),\n    \"ttl\": S.optionalWith(ChatMessageContentItemCacheControlTtl, { nullable: true })\n  })\n{}\n\nexport class ChatMessageContentItemText extends S.Class<ChatMessageContentItemText>(\"ChatMessageContentItemText\")({\n  \"type\": S.Literal(\"text\"),\n  \"text\": S.String,\n  \"cache_control\": S.optionalWith(ChatMessageContentItemCacheControl, { nullable: true })\n}) {}\n\nexport class SystemMessage extends S.Class<SystemMessage>(\"SystemMessage\")({\n  \"role\": S.Literal(\"system\"),\n  \"content\": S.Union(S.String, S.Array(ChatMessageContentItemText)),\n  \"name\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ChatMessageContentItemImageImageUrlDetail extends S.Literal(\"auto\", \"low\", \"high\") {}\n\nexport class ChatMessageContentItemImage extends S.Class<ChatMessageContentItemImage>(\"ChatMessageContentItemImage\")({\n  \"type\": S.Literal(\"image_url\"),\n  \"image_url\": S.Struct({\n    \"url\": S.String,\n    \"detail\": S.optionalWith(ChatMessageContentItemImageImageUrlDetail, { nullable: true })\n  })\n}) {}\n\nexport class ChatMessageContentItemAudio extends S.Class<ChatMessageContentItemAudio>(\"ChatMessageContentItemAudio\")({\n  \"type\": S.Literal(\"input_audio\"),\n  \"input_audio\": S.Struct({\n    \"data\": S.String,\n    \"format\": S.String\n  })\n}) {}\n\nexport class ChatMessageContentItemVideo extends S.Record({ key: S.String, value: S.Unknown }) {}\n\nexport class ChatMessageContentItem extends S.Record({ key: S.String, value: S.Unknown }) {}\n\nexport class UserMessage extends S.Class<UserMessage>(\"UserMessage\")({\n  \"role\": S.Literal(\"user\"),\n  \"content\": S.Union(S.String, S.Array(ChatMessageContentItem)),\n  \"name\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class ChatMessageToolCall extends S.Class<ChatMessageToolCall>(\"ChatMessageToolCall\")({\n  \"id\": S.String,\n  \"type\": S.Literal(\"function\"),\n  \"function\": S.Struct({\n    \"name\": S.String,\n    \"arguments\": S.String\n  })\n}) {}\n\nexport class Schema3 extends S.Union(S.String, S.Null) {}\n\nexport class Schema4Enum extends S.Literal(\n  \"unknown\",\n  \"openai-responses-v1\",\n  \"azure-openai-responses-v1\",\n  \"xai-responses-v1\",\n  \"anthropic-claude-v1\",\n  \"google-gemini-v1\"\n) {}\n\nexport class Schema4 extends S.Union(Schema4Enum, S.Null) {}\n\nexport class Schema5 extends S.Number {}\n\nexport class Schema2 extends S.Record({ key: S.String, value: S.Unknown }) {}\n\nexport class AssistantMessage extends S.Class<AssistantMessage>(\"AssistantMessage\")({\n  \"role\": S.Literal(\"assistant\"),\n  \"content\": S.optionalWith(S.Union(S.String, S.Array(ChatMessageContentItem)), { nullable: true }),\n  \"name\": S.optionalWith(S.String, { nullable: true }),\n  \"tool_calls\": S.optionalWith(S.Array(ChatMessageToolCall), { nullable: true }),\n  \"refusal\": S.optionalWith(S.String, { nullable: true }),\n  \"reasoning\": S.optionalWith(S.String, { nullable: true }),\n  \"reasoning_details\": S.optionalWith(S.Array(ReasoningDetail), { nullable: true }),\n  \"images\": S.optionalWith(\n    S.Array(S.Struct({\n      \"image_url\": S.Struct({\n        \"url\": S.String\n      })\n    })),\n    { nullable: true }\n  ),\n  \"annotations\": S.optionalWith(S.Array(AnnotationDetail), { nullable: true })\n}) {}\n\nexport class ToolResponseMessage extends S.Class<ToolResponseMessage>(\"ToolResponseMessage\")({\n  \"role\": S.Literal(\"tool\"),\n  \"content\": S.Union(S.String, S.Array(ChatMessageContentItem)),\n  \"tool_call_id\": S.String\n}) {}\n\nexport class Message extends S.Record({ key: S.String, value: S.Unknown }) {}\n\nexport class ModelName extends S.String {}\n\nexport class ChatGenerationParamsReasoningEffortEnum\n  extends S.Literal(\"xhigh\", \"high\", \"medium\", \"low\", \"minimal\", \"none\")\n{}\n\nexport class JSONSchemaConfig extends S.Class<JSONSchemaConfig>(\"JSONSchemaConfig\")({\n  \"name\": S.String.pipe(S.maxLength(64)),\n  \"description\": S.optionalWith(S.String, { nullable: true }),\n  \"schema\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"strict\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class ResponseFormatJSONSchema extends S.Class<ResponseFormatJSONSchema>(\"ResponseFormatJSONSchema\")({\n  \"type\": S.Literal(\"json_schema\"),\n  \"json_schema\": JSONSchemaConfig\n}) {}\n\nexport class ResponseFormatTextGrammar extends S.Class<ResponseFormatTextGrammar>(\"ResponseFormatTextGrammar\")({\n  \"type\": S.Literal(\"grammar\"),\n  \"grammar\": S.String\n}) {}\n\nexport class ChatStreamOptions extends S.Class<ChatStreamOptions>(\"ChatStreamOptions\")({\n  \"include_usage\": S.optionalWith(S.Boolean, { nullable: true })\n}) {}\n\nexport class NamedToolChoice extends S.Class<NamedToolChoice>(\"NamedToolChoice\")({\n  \"type\": S.Literal(\"function\"),\n  \"function\": S.Struct({\n    \"name\": S.String\n  })\n}) {}\n\nexport class ToolChoiceOption\n  extends S.Union(S.Literal(\"none\"), S.Literal(\"auto\"), S.Literal(\"required\"), NamedToolChoice)\n{}\n\nexport class ToolDefinitionJson extends S.Class<ToolDefinitionJson>(\"ToolDefinitionJson\")({\n  \"type\": S.Literal(\"function\"),\n  \"function\": S.Struct({\n    \"name\": S.String.pipe(S.maxLength(64)),\n    \"description\": S.optionalWith(S.String, { nullable: true }),\n    \"parameters\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n    \"strict\": S.optionalWith(S.Boolean, { nullable: true })\n  })\n}) {}\n\nexport class ChatGenerationParams extends S.Class<ChatGenerationParams>(\"ChatGenerationParams\")({\n  /**\n   * When multiple model providers are available, optionally indicate your routing preference.\n   */\n  \"provider\": S.optionalWith(\n    S.Struct({\n      /**\n       * Whether to allow backup providers to serve requests\n       * - true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider.\n       * - false: use only the primary/custom provider, and return the upstream error if it's unavailable.\n       */\n      \"allow_fallbacks\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest.\n       */\n      \"require_parameters\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * Data collection setting. If no available model provider meets the requirement, your request will return an error.\n       * - allow: (default) allow providers which store user data non-transiently and may train on it\n       *\n       * - deny: use only providers which do not collect user data.\n       */\n      \"data_collection\": S.optionalWith(S.Literal(\"deny\", \"allow\"), { nullable: true }),\n      \"zdr\": S.optionalWith(S.Boolean, { nullable: true }),\n      \"enforce_distillable_text\": S.optionalWith(S.Boolean, { nullable: true }),\n      /**\n       * An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message.\n       */\n      \"order\": S.optionalWith(Schema0, { nullable: true }),\n      /**\n       * List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request.\n       */\n      \"only\": S.optionalWith(Schema0, { nullable: true }),\n      /**\n       * List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request.\n       */\n      \"ignore\": S.optionalWith(Schema0, { nullable: true }),\n      /**\n       * A list of quantization levels to filter the provider by.\n       */\n      \"quantizations\": S.optionalWith(\n        S.Array(S.Literal(\"int4\", \"int8\", \"fp4\", \"fp6\", \"fp8\", \"fp16\", \"bf16\", \"fp32\", \"unknown\")),\n        { nullable: true }\n      ),\n      /**\n       * The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed.\n       */\n      \"sort\": S.optionalWith(ProviderSortUnion, { nullable: true }),\n      /**\n       * The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.\n       */\n      \"max_price\": S.optionalWith(\n        S.Struct({\n          \"prompt\": S.optionalWith(Schema1, { nullable: true }),\n          \"completion\": S.optionalWith(Schema1, { nullable: true }),\n          \"image\": S.optionalWith(Schema1, { nullable: true }),\n          \"audio\": S.optionalWith(Schema1, { nullable: true }),\n          \"request\": S.optionalWith(Schema1, { nullable: true })\n        }),\n        { nullable: true }\n      ),\n      /**\n       * Preferred minimum throughput (in tokens per second). Can be a number (applies to p50) or an object with percentile-specific cutoffs. Endpoints below the threshold(s) may still be used, but are deprioritized in routing. When using fallback models, this may cause a fallback model to be used instead of the primary model if it meets the threshold.\n       */\n      \"preferred_min_throughput\": S.optionalWith(\n        S.Union(\n          S.Number,\n          S.Struct({\n            \"p50\": S.optionalWith(S.Number, { nullable: true }),\n            \"p75\": S.optionalWith(S.Number, { nullable: true }),\n            \"p90\": S.optionalWith(S.Number, { nullable: true }),\n            \"p99\": S.optionalWith(S.Number, { nullable: true })\n          })\n        ),\n        { nullable: true }\n      ),\n      /**\n       * Preferred maximum latency (in seconds). Can be a number (applies to p50) or an object with percentile-specific cutoffs. Endpoints above the threshold(s) may still be used, but are deprioritized in routing. When using fallback models, this may cause a fallback model to be used instead of the primary model if it meets the threshold.\n       */\n      \"preferred_max_latency\": S.optionalWith(\n        S.Union(\n          S.Number,\n          S.Struct({\n            \"p50\": S.optionalWith(S.Number, { nullable: true }),\n            \"p75\": S.optionalWith(S.Number, { nullable: true }),\n            \"p90\": S.optionalWith(S.Number, { nullable: true }),\n            \"p99\": S.optionalWith(S.Number, { nullable: true })\n          })\n        ),\n        { nullable: true }\n      )\n    }),\n    { nullable: true }\n  ),\n  /**\n   * Plugins you want to enable for this request, including their settings.\n   */\n  \"plugins\": S.optionalWith(S.Array(S.Record({ key: S.String, value: S.Unknown })), { nullable: true }),\n  \"route\": S.optionalWith(ChatGenerationParamsRouteEnum, { nullable: true }),\n  \"user\": S.optionalWith(S.String, { nullable: true }),\n  /**\n   * A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 128 characters.\n   */\n  \"session_id\": S.optionalWith(S.String.pipe(S.maxLength(128)), { nullable: true }),\n  \"messages\": S.NonEmptyArray(Message).pipe(S.minItems(1)),\n  \"model\": S.optionalWith(ModelName, { nullable: true }),\n  \"models\": S.optionalWith(S.Array(ModelName), { nullable: true }),\n  \"frequency_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true\n  }),\n  \"logit_bias\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"logprobs\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"top_logprobs\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(20)), { nullable: true }),\n  \"max_completion_tokens\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(1)), { nullable: true }),\n  \"max_tokens\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(1)), { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"presence_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true\n  }),\n  \"reasoning\": S.optionalWith(\n    S.Struct({\n      \"effort\": S.optionalWith(ChatGenerationParamsReasoningEffortEnum, { nullable: true }),\n      \"summary\": S.optionalWith(ReasoningSummaryVerbosity, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"response_format\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"seed\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(-9007199254740991), S.lessThanOrEqualTo(9007199254740991)), {\n    nullable: true\n  }),\n  \"stop\": S.optionalWith(S.Union(S.String, S.Array(S.String).pipe(S.maxItems(4))), { nullable: true }),\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  \"stream_options\": S.optionalWith(ChatStreamOptions, { nullable: true }),\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  \"tool_choice\": S.optionalWith(ToolChoiceOption, { nullable: true }),\n  \"tools\": S.optionalWith(S.Array(ToolDefinitionJson), { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), {\n    nullable: true,\n    default: () => 1 as const\n  }),\n  \"debug\": S.optionalWith(\n    S.Struct({\n      \"echo_upstream_body\": S.optionalWith(S.Boolean, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"image_config\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"modalities\": S.optionalWith(S.Array(S.Literal(\"text\", \"image\")), { nullable: true })\n}) {}\n\nexport class ChatCompletionFinishReason extends S.Literal(\"tool_calls\", \"stop\", \"length\", \"content_filter\", \"error\") {}\n\nexport class Schema6 extends S.Union(ChatCompletionFinishReason, S.Null) {}\n\nexport class ChatMessageTokenLogprob extends S.Class<ChatMessageTokenLogprob>(\"ChatMessageTokenLogprob\")({\n  \"token\": S.String,\n  \"logprob\": S.Number,\n  \"bytes\": S.NullOr(S.Array(S.Number)),\n  \"top_logprobs\": S.Array(S.Struct({\n    \"token\": S.String,\n    \"logprob\": S.Number,\n    \"bytes\": S.NullOr(S.Array(S.Number))\n  }))\n}) {}\n\nexport class ChatMessageTokenLogprobs extends S.Class<ChatMessageTokenLogprobs>(\"ChatMessageTokenLogprobs\")({\n  \"content\": S.optionalWith(S.Array(ChatMessageTokenLogprob), { nullable: true }),\n  \"refusal\": S.optionalWith(S.Array(ChatMessageTokenLogprob), { nullable: true })\n}) {}\n\nexport class ChatResponseChoice extends S.Class<ChatResponseChoice>(\"ChatResponseChoice\")({\n  \"finish_reason\": S.NullOr(ChatCompletionFinishReason),\n  \"index\": S.Number,\n  \"message\": AssistantMessage,\n  \"logprobs\": S.optionalWith(ChatMessageTokenLogprobs, { nullable: true })\n}) {}\n\nexport class ChatGenerationTokenUsage extends S.Class<ChatGenerationTokenUsage>(\"ChatGenerationTokenUsage\")({\n  \"completion_tokens\": S.Number,\n  \"prompt_tokens\": S.Number,\n  \"total_tokens\": S.Number,\n  \"completion_tokens_details\": S.optionalWith(\n    S.Struct({\n      \"reasoning_tokens\": S.optionalWith(S.Number, { nullable: true }),\n      \"audio_tokens\": S.optionalWith(S.Number, { nullable: true }),\n      \"accepted_prediction_tokens\": S.optionalWith(S.Number, { nullable: true }),\n      \"rejected_prediction_tokens\": S.optionalWith(S.Number, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"prompt_tokens_details\": S.optionalWith(\n    S.Struct({\n      \"cached_tokens\": S.optionalWith(S.Number, { nullable: true }),\n      \"cache_write_tokens\": S.optionalWith(S.Number, { nullable: true }),\n      \"audio_tokens\": S.optionalWith(S.Number, { nullable: true }),\n      \"video_tokens\": S.optionalWith(S.Number, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"cost\": S.optionalWith(S.Number, { nullable: true }),\n  \"cost_details\": S.optionalWith(S.Struct({ upstream_inference_cost: S.optionalWith(S.Number, { nullable: true }) }), {\n    nullable: true\n  })\n}) {}\n\nexport class ChatResponse extends S.Class<ChatResponse>(\"ChatResponse\")({\n  \"id\": S.String,\n  \"provider\": S.optionalWith(S.String, { nullable: true }),\n  \"choices\": S.Array(ChatResponseChoice),\n  \"created\": S.Number,\n  \"model\": S.String,\n  \"object\": S.Literal(\"chat.completion\"),\n  \"system_fingerprint\": S.optionalWith(S.String, { nullable: true }),\n  \"usage\": S.optionalWith(ChatGenerationTokenUsage, { nullable: true })\n}) {}\n\nexport class ChatError extends S.Class<ChatError>(\"ChatError\")({\n  \"error\": S.Struct({\n    \"code\": S.NullOr(S.Union(S.String, S.Number)),\n    \"message\": S.String,\n    \"param\": S.optionalWith(S.String, { nullable: true }),\n    \"type\": S.optionalWith(S.String, { nullable: true })\n  })\n}) {}\n\nexport class CompletionCreateParams extends S.Class<CompletionCreateParams>(\"CompletionCreateParams\")({\n  \"model\": S.optionalWith(ModelName, { nullable: true }),\n  \"models\": S.optionalWith(S.Array(ModelName), { nullable: true }),\n  \"prompt\": S.Union(S.String, S.Array(S.String), S.Array(S.Number), S.Array(S.Array(S.Number))),\n  \"best_of\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(20)), { nullable: true }),\n  \"echo\": S.optionalWith(S.Boolean, { nullable: true }),\n  \"frequency_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true\n  }),\n  \"logit_bias\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"logprobs\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(5)), { nullable: true }),\n  \"max_tokens\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(9007199254740991)), {\n    nullable: true\n  }),\n  \"n\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(1), S.lessThanOrEqualTo(128)), { nullable: true }),\n  \"presence_penalty\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(-2), S.lessThanOrEqualTo(2)), {\n    nullable: true\n  }),\n  \"seed\": S.optionalWith(S.Int.pipe(S.greaterThanOrEqualTo(-9007199254740991), S.lessThanOrEqualTo(9007199254740991)), {\n    nullable: true\n  }),\n  \"stop\": S.optionalWith(S.Union(S.String, S.Array(S.String)), { nullable: true }),\n  \"stream\": S.optionalWith(S.Boolean, { nullable: true, default: () => false as const }),\n  \"stream_options\": S.optionalWith(\n    S.Struct({\n      \"include_usage\": S.optionalWith(S.Boolean, { nullable: true })\n    }),\n    { nullable: true }\n  ),\n  \"suffix\": S.optionalWith(S.String, { nullable: true }),\n  \"temperature\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(2)), { nullable: true }),\n  \"top_p\": S.optionalWith(S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(1)), { nullable: true }),\n  \"user\": S.optionalWith(S.String, { nullable: true }),\n  \"metadata\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true }),\n  \"response_format\": S.optionalWith(S.Record({ key: S.String, value: S.Unknown }), { nullable: true })\n}) {}\n\nexport class CompletionLogprobs extends S.Class<CompletionLogprobs>(\"CompletionLogprobs\")({\n  \"tokens\": S.Array(S.String),\n  \"token_logprobs\": S.Array(S.Number),\n  \"top_logprobs\": S.NullOr(S.Array(S.Record({ key: S.String, value: S.Unknown }))),\n  \"text_offset\": S.Array(S.Number)\n}) {}\n\nexport class CompletionFinishReasonEnum extends S.Literal(\"stop\", \"length\", \"content_filter\") {}\n\nexport class CompletionFinishReason extends S.Union(CompletionFinishReasonEnum, S.Null) {}\n\nexport class CompletionChoice extends S.Class<CompletionChoice>(\"CompletionChoice\")({\n  \"text\": S.String,\n  \"index\": S.Number,\n  \"logprobs\": S.NullOr(CompletionLogprobs),\n  \"finish_reason\": S.NullOr(S.Literal(\"stop\", \"length\", \"content_filter\")),\n  \"native_finish_reason\": S.optionalWith(S.String, { nullable: true }),\n  \"reasoning\": S.optionalWith(S.String, { nullable: true })\n}) {}\n\nexport class CompletionUsage extends S.Class<CompletionUsage>(\"CompletionUsage\")({\n  \"prompt_tokens\": S.Number,\n  \"completion_tokens\": S.Number,\n  \"total_tokens\": S.Number\n}) {}\n\nexport class CompletionResponse extends S.Class<CompletionResponse>(\"CompletionResponse\")({\n  \"id\": S.String,\n  \"object\": S.Literal(\"text_completion\"),\n  \"created\": S.Number,\n  \"model\": S.String,\n  \"provider\": S.optionalWith(S.String, { nullable: true }),\n  \"system_fingerprint\": S.optionalWith(S.String, { nullable: true }),\n  \"choices\": S.Array(CompletionChoice),\n  \"usage\": S.optionalWith(CompletionUsage, { nullable: true })\n}) {}\n\nexport const make = (\n  httpClient: HttpClient.HttpClient,\n  options: {\n    readonly transformClient?: ((client: HttpClient.HttpClient) => Effect.Effect<HttpClient.HttpClient>) | undefined\n  } = {}\n): Client => {\n  const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) =>\n    Effect.flatMap(\n      Effect.orElseSucceed(response.json, () => \"Unexpected status code\"),\n      (description) =>\n        Effect.fail(\n          new HttpClientError.ResponseError({\n            request: response.request,\n            response,\n            reason: \"StatusCode\",\n            description: typeof description === \"string\" ? description : JSON.stringify(description)\n          })\n        )\n    )\n  const withResponse: <A, E>(\n    f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E>\n  ) => (\n    request: HttpClientRequest.HttpClientRequest\n  ) => Effect.Effect<any, any> = options.transformClient\n    ? (f) => (request) =>\n      Effect.flatMap(\n        Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)),\n        f\n      )\n    : (f) => (request) => Effect.flatMap(httpClient.execute(request), f)\n  const decodeSuccess = <A, I, R>(schema: S.Schema<A, I, R>) => (response: HttpClientResponse.HttpClientResponse) =>\n    HttpClientResponse.schemaBodyJson(schema)(response)\n  const decodeError =\n    <const Tag extends string, A, I, R>(tag: Tag, schema: S.Schema<A, I, R>) =>\n    (response: HttpClientResponse.HttpClientResponse) =>\n      Effect.flatMap(\n        HttpClientResponse.schemaBodyJson(schema)(response),\n        (cause) => Effect.fail(ClientError(tag, cause, response))\n      )\n  return {\n    httpClient,\n    \"createResponses\": (options) =>\n      HttpClientRequest.post(`/responses`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(OpenResponsesNonStreamingResponse),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"402\": decodeError(\"PaymentRequiredResponse\", PaymentRequiredResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"408\": decodeError(\"RequestTimeoutResponse\", RequestTimeoutResponse),\n          \"413\": decodeError(\"PayloadTooLargeResponse\", PayloadTooLargeResponse),\n          \"422\": decodeError(\"UnprocessableEntityResponse\", UnprocessableEntityResponse),\n          \"429\": decodeError(\"TooManyRequestsResponse\", TooManyRequestsResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          \"502\": decodeError(\"BadGatewayResponse\", BadGatewayResponse),\n          \"503\": decodeError(\"ServiceUnavailableResponse\", ServiceUnavailableResponse),\n          \"524\": decodeError(\"EdgeNetworkTimeoutResponse\", EdgeNetworkTimeoutResponse),\n          \"529\": decodeError(\"ProviderOverloadedResponse\", ProviderOverloadedResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createMessages\": (options) =>\n      HttpClientRequest.post(`/messages`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(AnthropicMessagesResponse),\n          \"400\": decodeError(\"CreateMessages400\", CreateMessages400),\n          \"401\": decodeError(\"CreateMessages401\", CreateMessages401),\n          \"403\": decodeError(\"CreateMessages403\", CreateMessages403),\n          \"404\": decodeError(\"CreateMessages404\", CreateMessages404),\n          \"429\": decodeError(\"CreateMessages429\", CreateMessages429),\n          \"500\": decodeError(\"CreateMessages500\", CreateMessages500),\n          \"503\": decodeError(\"CreateMessages503\", CreateMessages503),\n          \"529\": decodeError(\"CreateMessages529\", CreateMessages529),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getUserActivity\": (options) =>\n      HttpClientRequest.get(`/activity`).pipe(\n        HttpClientRequest.setUrlParams({ \"date\": options?.[\"date\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GetUserActivity200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"403\": decodeError(\"ForbiddenResponse\", ForbiddenResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getCredits\": () =>\n      HttpClientRequest.get(`/credits`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GetCredits200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"403\": decodeError(\"ForbiddenResponse\", ForbiddenResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createCoinbaseCharge\": (options) =>\n      HttpClientRequest.post(`/credits/coinbase`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateCoinbaseCharge200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"429\": decodeError(\"TooManyRequestsResponse\", TooManyRequestsResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createEmbeddings\": (options) =>\n      HttpClientRequest.post(`/embeddings`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateEmbeddings200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"402\": decodeError(\"PaymentRequiredResponse\", PaymentRequiredResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"429\": decodeError(\"TooManyRequestsResponse\", TooManyRequestsResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          \"502\": decodeError(\"BadGatewayResponse\", BadGatewayResponse),\n          \"503\": decodeError(\"ServiceUnavailableResponse\", ServiceUnavailableResponse),\n          \"524\": decodeError(\"EdgeNetworkTimeoutResponse\", EdgeNetworkTimeoutResponse),\n          \"529\": decodeError(\"ProviderOverloadedResponse\", ProviderOverloadedResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listEmbeddingsModels\": () =>\n      HttpClientRequest.get(`/embeddings/models`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ModelsListResponse),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getGeneration\": (options) =>\n      HttpClientRequest.get(`/generation`).pipe(\n        HttpClientRequest.setUrlParams({ \"id\": options?.[\"id\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GetGeneration200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"402\": decodeError(\"PaymentRequiredResponse\", PaymentRequiredResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"429\": decodeError(\"TooManyRequestsResponse\", TooManyRequestsResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          \"502\": decodeError(\"BadGatewayResponse\", BadGatewayResponse),\n          \"524\": decodeError(\"EdgeNetworkTimeoutResponse\", EdgeNetworkTimeoutResponse),\n          \"529\": decodeError(\"ProviderOverloadedResponse\", ProviderOverloadedResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listModelsCount\": () =>\n      HttpClientRequest.get(`/models/count`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ModelsCountResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getModels\": (options) =>\n      HttpClientRequest.get(`/models`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"category\": options?.[\"category\"] as any,\n          \"supported_parameters\": options?.[\"supported_parameters\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ModelsListResponse),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listModelsUser\": () =>\n      HttpClientRequest.get(`/models/user`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ModelsListResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listEndpoints\": (author, slug) =>\n      HttpClientRequest.get(`/models/${author}/${slug}/endpoints`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListEndpoints200),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listEndpointsZdr\": () =>\n      HttpClientRequest.get(`/endpoints/zdr`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListEndpointsZdr200),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listProviders\": () =>\n      HttpClientRequest.get(`/providers`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListProviders200),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"list\": (options) =>\n      HttpClientRequest.get(`/keys`).pipe(\n        HttpClientRequest.setUrlParams({\n          \"include_disabled\": options?.[\"include_disabled\"] as any,\n          \"offset\": options?.[\"offset\"] as any\n        }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(List200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"429\": decodeError(\"TooManyRequestsResponse\", TooManyRequestsResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createKeys\": (options) =>\n      HttpClientRequest.post(`/keys`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateKeys201),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"429\": decodeError(\"TooManyRequestsResponse\", TooManyRequestsResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getKey\": (hash) =>\n      HttpClientRequest.get(`/keys/${hash}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GetKey200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"429\": decodeError(\"TooManyRequestsResponse\", TooManyRequestsResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteKeys\": (hash) =>\n      HttpClientRequest.del(`/keys/${hash}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteKeys200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"429\": decodeError(\"TooManyRequestsResponse\", TooManyRequestsResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"updateKeys\": (hash, options) =>\n      HttpClientRequest.patch(`/keys/${hash}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UpdateKeys200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"429\": decodeError(\"TooManyRequestsResponse\", TooManyRequestsResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listGuardrails\": (options) =>\n      HttpClientRequest.get(`/guardrails`).pipe(\n        HttpClientRequest.setUrlParams({ \"offset\": options?.[\"offset\"] as any, \"limit\": options?.[\"limit\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListGuardrails200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createGuardrail\": (options) =>\n      HttpClientRequest.post(`/guardrails`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateGuardrail201),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getGuardrail\": (id) =>\n      HttpClientRequest.get(`/guardrails/${id}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GetGuardrail200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"deleteGuardrail\": (id) =>\n      HttpClientRequest.del(`/guardrails/${id}`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(DeleteGuardrail200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"updateGuardrail\": (id, options) =>\n      HttpClientRequest.patch(`/guardrails/${id}`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(UpdateGuardrail200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listKeyAssignments\": (options) =>\n      HttpClientRequest.get(`/guardrails/assignments/keys`).pipe(\n        HttpClientRequest.setUrlParams({ \"offset\": options?.[\"offset\"] as any, \"limit\": options?.[\"limit\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListKeyAssignments200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listMemberAssignments\": (options) =>\n      HttpClientRequest.get(`/guardrails/assignments/members`).pipe(\n        HttpClientRequest.setUrlParams({ \"offset\": options?.[\"offset\"] as any, \"limit\": options?.[\"limit\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListMemberAssignments200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listGuardrailKeyAssignments\": (id, options) =>\n      HttpClientRequest.get(`/guardrails/${id}/assignments/keys`).pipe(\n        HttpClientRequest.setUrlParams({ \"offset\": options?.[\"offset\"] as any, \"limit\": options?.[\"limit\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListGuardrailKeyAssignments200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"bulkAssignKeysToGuardrail\": (id, options) =>\n      HttpClientRequest.post(`/guardrails/${id}/assignments/keys`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BulkAssignKeysToGuardrail200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"listGuardrailMemberAssignments\": (id, options) =>\n      HttpClientRequest.get(`/guardrails/${id}/assignments/members`).pipe(\n        HttpClientRequest.setUrlParams({ \"offset\": options?.[\"offset\"] as any, \"limit\": options?.[\"limit\"] as any }),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ListGuardrailMemberAssignments200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"bulkAssignMembersToGuardrail\": (id, options) =>\n      HttpClientRequest.post(`/guardrails/${id}/assignments/members`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BulkAssignMembersToGuardrail200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"bulkUnassignKeysFromGuardrail\": (id, options) =>\n      HttpClientRequest.post(`/guardrails/${id}/assignments/keys/remove`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BulkUnassignKeysFromGuardrail200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"bulkUnassignMembersFromGuardrail\": (id, options) =>\n      HttpClientRequest.post(`/guardrails/${id}/assignments/members/remove`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(BulkUnassignMembersFromGuardrail200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"404\": decodeError(\"NotFoundResponse\", NotFoundResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"getCurrentKey\": () =>\n      HttpClientRequest.get(`/key`).pipe(\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(GetCurrentKey200),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"exchangeAuthCodeForAPIKey\": (options) =>\n      HttpClientRequest.post(`/auth/keys`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ExchangeAuthCodeForAPIKey200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"403\": decodeError(\"ForbiddenResponse\", ForbiddenResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createAuthKeysCode\": (options) =>\n      HttpClientRequest.post(`/auth/keys/code`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CreateAuthKeysCode200),\n          \"400\": decodeError(\"BadRequestResponse\", BadRequestResponse),\n          \"401\": decodeError(\"UnauthorizedResponse\", UnauthorizedResponse),\n          \"500\": decodeError(\"InternalServerResponse\", InternalServerResponse),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"sendChatCompletionRequest\": (options) =>\n      HttpClientRequest.post(`/chat/completions`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(ChatResponse),\n          \"400\": decodeError(\"ChatError\", ChatError),\n          \"401\": decodeError(\"ChatError\", ChatError),\n          \"429\": decodeError(\"ChatError\", ChatError),\n          \"500\": decodeError(\"ChatError\", ChatError),\n          orElse: unexpectedStatus\n        }))\n      ),\n    \"createCompletions\": (options) =>\n      HttpClientRequest.post(`/completions`).pipe(\n        HttpClientRequest.bodyUnsafeJson(options),\n        withResponse(HttpClientResponse.matchStatus({\n          \"2xx\": decodeSuccess(CompletionResponse),\n          \"400\": decodeError(\"ChatError\", ChatError),\n          \"401\": decodeError(\"ChatError\", ChatError),\n          \"429\": decodeError(\"ChatError\", ChatError),\n          \"500\": decodeError(\"ChatError\", ChatError),\n          orElse: unexpectedStatus\n        }))\n      )\n  }\n}\n\nexport interface Client {\n  readonly httpClient: HttpClient.HttpClient\n  /**\n   * Creates a streaming or non-streaming response using OpenResponses API format\n   */\n  readonly \"createResponses\": (\n    options: typeof OpenResponsesRequest.Encoded\n  ) => Effect.Effect<\n    typeof OpenResponsesNonStreamingResponse.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"PaymentRequiredResponse\", typeof PaymentRequiredResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"RequestTimeoutResponse\", typeof RequestTimeoutResponse.Type>\n    | ClientError<\"PayloadTooLargeResponse\", typeof PayloadTooLargeResponse.Type>\n    | ClientError<\"UnprocessableEntityResponse\", typeof UnprocessableEntityResponse.Type>\n    | ClientError<\"TooManyRequestsResponse\", typeof TooManyRequestsResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n    | ClientError<\"BadGatewayResponse\", typeof BadGatewayResponse.Type>\n    | ClientError<\"ServiceUnavailableResponse\", typeof ServiceUnavailableResponse.Type>\n    | ClientError<\"EdgeNetworkTimeoutResponse\", typeof EdgeNetworkTimeoutResponse.Type>\n    | ClientError<\"ProviderOverloadedResponse\", typeof ProviderOverloadedResponse.Type>\n  >\n  /**\n   * Creates a message using the Anthropic Messages API format. Supports text, images, PDFs, tools, and extended thinking.\n   */\n  readonly \"createMessages\": (\n    options: typeof AnthropicMessagesRequest.Encoded\n  ) => Effect.Effect<\n    typeof AnthropicMessagesResponse.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"CreateMessages400\", typeof CreateMessages400.Type>\n    | ClientError<\"CreateMessages401\", typeof CreateMessages401.Type>\n    | ClientError<\"CreateMessages403\", typeof CreateMessages403.Type>\n    | ClientError<\"CreateMessages404\", typeof CreateMessages404.Type>\n    | ClientError<\"CreateMessages429\", typeof CreateMessages429.Type>\n    | ClientError<\"CreateMessages500\", typeof CreateMessages500.Type>\n    | ClientError<\"CreateMessages503\", typeof CreateMessages503.Type>\n    | ClientError<\"CreateMessages529\", typeof CreateMessages529.Type>\n  >\n  /**\n   * Returns user activity data grouped by endpoint for the last 30 (completed) UTC days. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"getUserActivity\": (\n    options?: typeof GetUserActivityParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof GetUserActivity200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"ForbiddenResponse\", typeof ForbiddenResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Get total credits purchased and used for the authenticated user. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"getCredits\": () => Effect.Effect<\n    typeof GetCredits200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"ForbiddenResponse\", typeof ForbiddenResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Create a Coinbase charge for crypto payment\n   */\n  readonly \"createCoinbaseCharge\": (\n    options: typeof CreateChargeRequest.Encoded\n  ) => Effect.Effect<\n    typeof CreateCoinbaseCharge200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"TooManyRequestsResponse\", typeof TooManyRequestsResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Submits an embedding request to the embeddings router\n   */\n  readonly \"createEmbeddings\": (\n    options: typeof CreateEmbeddingsRequest.Encoded\n  ) => Effect.Effect<\n    typeof CreateEmbeddings200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"PaymentRequiredResponse\", typeof PaymentRequiredResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"TooManyRequestsResponse\", typeof TooManyRequestsResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n    | ClientError<\"BadGatewayResponse\", typeof BadGatewayResponse.Type>\n    | ClientError<\"ServiceUnavailableResponse\", typeof ServiceUnavailableResponse.Type>\n    | ClientError<\"EdgeNetworkTimeoutResponse\", typeof EdgeNetworkTimeoutResponse.Type>\n    | ClientError<\"ProviderOverloadedResponse\", typeof ProviderOverloadedResponse.Type>\n  >\n  /**\n   * Returns a list of all available embeddings models and their properties\n   */\n  readonly \"listEmbeddingsModels\": () => Effect.Effect<\n    typeof ModelsListResponse.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Get request & usage metadata for a generation\n   */\n  readonly \"getGeneration\": (\n    options: typeof GetGenerationParams.Encoded\n  ) => Effect.Effect<\n    typeof GetGeneration200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"PaymentRequiredResponse\", typeof PaymentRequiredResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"TooManyRequestsResponse\", typeof TooManyRequestsResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n    | ClientError<\"BadGatewayResponse\", typeof BadGatewayResponse.Type>\n    | ClientError<\"EdgeNetworkTimeoutResponse\", typeof EdgeNetworkTimeoutResponse.Type>\n    | ClientError<\"ProviderOverloadedResponse\", typeof ProviderOverloadedResponse.Type>\n  >\n  /**\n   * Get total count of available models\n   */\n  readonly \"listModelsCount\": () => Effect.Effect<\n    typeof ModelsCountResponse.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * List all models and their properties\n   */\n  readonly \"getModels\": (\n    options?: typeof GetModelsParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ModelsListResponse.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * List models filtered by user provider preferences\n   */\n  readonly \"listModelsUser\": () => Effect.Effect<\n    typeof ModelsListResponse.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * List all endpoints for a model\n   */\n  readonly \"listEndpoints\": (\n    author: string,\n    slug: string\n  ) => Effect.Effect<\n    typeof ListEndpoints200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Preview the impact of ZDR on the available endpoints\n   */\n  readonly \"listEndpointsZdr\": () => Effect.Effect<\n    typeof ListEndpointsZdr200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * List all providers\n   */\n  readonly \"listProviders\": () => Effect.Effect<\n    typeof ListProviders200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * List all API keys for the authenticated user. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"list\": (\n    options?: typeof ListParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof List200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"TooManyRequestsResponse\", typeof TooManyRequestsResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Create a new API key for the authenticated user. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"createKeys\": (\n    options: typeof CreateKeysRequest.Encoded\n  ) => Effect.Effect<\n    typeof CreateKeys201.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"TooManyRequestsResponse\", typeof TooManyRequestsResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Get a single API key by hash. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"getKey\": (\n    hash: string\n  ) => Effect.Effect<\n    typeof GetKey200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"TooManyRequestsResponse\", typeof TooManyRequestsResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Delete an existing API key. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"deleteKeys\": (\n    hash: string\n  ) => Effect.Effect<\n    typeof DeleteKeys200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"TooManyRequestsResponse\", typeof TooManyRequestsResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Update an existing API key. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"updateKeys\": (\n    hash: string,\n    options: typeof UpdateKeysRequest.Encoded\n  ) => Effect.Effect<\n    typeof UpdateKeys200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"TooManyRequestsResponse\", typeof TooManyRequestsResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * List all guardrails for the authenticated user. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"listGuardrails\": (\n    options?: typeof ListGuardrailsParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ListGuardrails200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Create a new guardrail for the authenticated user. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"createGuardrail\": (\n    options: typeof CreateGuardrailRequest.Encoded\n  ) => Effect.Effect<\n    typeof CreateGuardrail201.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Get a single guardrail by ID. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"getGuardrail\": (\n    id: string\n  ) => Effect.Effect<\n    typeof GetGuardrail200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Delete an existing guardrail. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"deleteGuardrail\": (\n    id: string\n  ) => Effect.Effect<\n    typeof DeleteGuardrail200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Update an existing guardrail. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"updateGuardrail\": (\n    id: string,\n    options: typeof UpdateGuardrailRequest.Encoded\n  ) => Effect.Effect<\n    typeof UpdateGuardrail200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * List all API key guardrail assignments for the authenticated user. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"listKeyAssignments\": (\n    options?: typeof ListKeyAssignmentsParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ListKeyAssignments200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * List all organization member guardrail assignments for the authenticated user. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"listMemberAssignments\": (\n    options?: typeof ListMemberAssignmentsParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ListMemberAssignments200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * List all API key assignments for a specific guardrail. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"listGuardrailKeyAssignments\": (\n    id: string,\n    options?: typeof ListGuardrailKeyAssignmentsParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ListGuardrailKeyAssignments200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Assign multiple API keys to a specific guardrail. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"bulkAssignKeysToGuardrail\": (\n    id: string,\n    options: typeof BulkAssignKeysToGuardrailRequest.Encoded\n  ) => Effect.Effect<\n    typeof BulkAssignKeysToGuardrail200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * List all organization member assignments for a specific guardrail. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"listGuardrailMemberAssignments\": (\n    id: string,\n    options?: typeof ListGuardrailMemberAssignmentsParams.Encoded | undefined\n  ) => Effect.Effect<\n    typeof ListGuardrailMemberAssignments200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Assign multiple organization members to a specific guardrail. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"bulkAssignMembersToGuardrail\": (\n    id: string,\n    options: typeof BulkAssignMembersToGuardrailRequest.Encoded\n  ) => Effect.Effect<\n    typeof BulkAssignMembersToGuardrail200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Unassign multiple API keys from a specific guardrail. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"bulkUnassignKeysFromGuardrail\": (\n    id: string,\n    options: typeof BulkUnassignKeysFromGuardrailRequest.Encoded\n  ) => Effect.Effect<\n    typeof BulkUnassignKeysFromGuardrail200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Unassign multiple organization members from a specific guardrail. [Provisioning key](/docs/guides/overview/auth/provisioning-api-keys) required.\n   */\n  readonly \"bulkUnassignMembersFromGuardrail\": (\n    id: string,\n    options: typeof BulkUnassignMembersFromGuardrailRequest.Encoded\n  ) => Effect.Effect<\n    typeof BulkUnassignMembersFromGuardrail200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"NotFoundResponse\", typeof NotFoundResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Get information on the API key associated with the current authentication session\n   */\n  readonly \"getCurrentKey\": () => Effect.Effect<\n    typeof GetCurrentKey200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Exchange an authorization code from the PKCE flow for a user-controlled API key\n   */\n  readonly \"exchangeAuthCodeForAPIKey\": (\n    options: typeof ExchangeAuthCodeForAPIKeyRequest.Encoded\n  ) => Effect.Effect<\n    typeof ExchangeAuthCodeForAPIKey200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"ForbiddenResponse\", typeof ForbiddenResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Create an authorization code for the PKCE flow to generate a user-controlled API key\n   */\n  readonly \"createAuthKeysCode\": (\n    options: typeof CreateAuthKeysCodeRequest.Encoded\n  ) => Effect.Effect<\n    typeof CreateAuthKeysCode200.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"BadRequestResponse\", typeof BadRequestResponse.Type>\n    | ClientError<\"UnauthorizedResponse\", typeof UnauthorizedResponse.Type>\n    | ClientError<\"InternalServerResponse\", typeof InternalServerResponse.Type>\n  >\n  /**\n   * Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes.\n   */\n  readonly \"sendChatCompletionRequest\": (\n    options: typeof ChatGenerationParams.Encoded\n  ) => Effect.Effect<\n    typeof ChatResponse.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"ChatError\", typeof ChatError.Type>\n    | ClientError<\"ChatError\", typeof ChatError.Type>\n    | ClientError<\"ChatError\", typeof ChatError.Type>\n    | ClientError<\"ChatError\", typeof ChatError.Type>\n  >\n  /**\n   * Creates a completion for the provided prompt and parameters. Supports both streaming and non-streaming modes.\n   */\n  readonly \"createCompletions\": (\n    options: typeof CompletionCreateParams.Encoded\n  ) => Effect.Effect<\n    typeof CompletionResponse.Type,\n    | HttpClientError.HttpClientError\n    | ParseError\n    | ClientError<\"ChatError\", typeof ChatError.Type>\n    | ClientError<\"ChatError\", typeof ChatError.Type>\n    | ClientError<\"ChatError\", typeof ChatError.Type>\n    | ClientError<\"ChatError\", typeof ChatError.Type>\n  >\n}\n\nexport interface ClientError<Tag extends string, E> {\n  readonly _tag: Tag\n  readonly request: HttpClientRequest.HttpClientRequest\n  readonly response: HttpClientResponse.HttpClientResponse\n  readonly cause: E\n}\n\nclass ClientErrorImpl extends Data.Error<{\n  _tag: string\n  cause: any\n  request: HttpClientRequest.HttpClientRequest\n  response: HttpClientResponse.HttpClientResponse\n}> {}\n\nexport const ClientError = <Tag extends string, E>(\n  tag: Tag,\n  cause: E,\n  response: HttpClientResponse.HttpClientResponse\n): ClientError<Tag, E> =>\n  new ClientErrorImpl({\n    _tag: tag,\n    cause,\n    response,\n    request: response.request\n  }) as any\n"
  },
  {
    "path": "packages/ai/openrouter/src/OpenRouterClient.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AiError from \"@effect/ai/AiError\"\nimport * as Sse from \"@effect/experimental/Sse\"\nimport * as HttpBody from \"@effect/platform/HttpBody\"\nimport * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as Config from \"effect/Config\"\nimport type { ConfigError } from \"effect/ConfigError\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport type * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport * as Stream from \"effect/Stream\"\nimport * as Generated from \"./Generated.js\"\nimport { OpenRouterConfig } from \"./OpenRouterConfig.js\"\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class OpenRouterClient extends Context.Tag(\n  \"@effect/ai-openrouter/OpenRouterClient\"\n)<OpenRouterClient, Service>() {}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface Service {\n  /**\n   * The underlying HTTP client capable of communicating with the OpenRouter API.\n   *\n   * This client is pre-configured with authentication, base URL, and standard\n   * headers required for OpenRouter API communication. It provides direct access\n   * to the generated OpenRouter API client for operations not covered by the\n   * higher-level methods.\n   *\n   * Use this when you need to:\n   * - Access provider-specific API endpoints not available through the AI SDK\n   * - Implement custom request/response handling\n   * - Use OpenRouter API features not yet supported by the Effect AI abstractions\n   * - Perform batch operations or non-streaming requests\n   *\n   * The client automatically handles authentication and follows OpenRouter's\n   * API conventions for request formatting and error handling.\n   */\n  readonly client: Generated.Client\n\n  readonly createChatCompletion: (\n    options: typeof Generated.ChatGenerationParams.Encoded\n  ) => Effect.Effect<Generated.ChatResponse, AiError.AiError>\n\n  readonly createChatCompletionStream: (\n    options: Omit<typeof Generated.ChatGenerationParams.Encoded, \"stream\">\n  ) => Stream.Stream<ChatStreamingResponseChunk, AiError.AiError>\n}\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make: (options: {\n  readonly apiKey?: Redacted.Redacted | undefined\n  readonly apiUrl?: string | undefined\n  /**\n   * Optional URL of your site for rankings on `openrouter.ai`.\n   */\n  readonly referrer?: string | undefined\n  /**\n   * Optional title of your site for rankings on `openrouter.ai`.\n   */\n  readonly title?: string | undefined\n  /**\n   * A function to transform the underlying HTTP client before it's used to send\n   * API requests.\n   *\n   * This transformation function receives the configured HTTP client and returns\n   * a modified version. It's applied after all standard client configuration\n   * (authentication, base URL, headers) but before any requests are made.\n   *\n   * Use this for:\n   * - Adding custom middleware (logging, metrics, caching)\n   * - Modifying request/response processing behavior\n   * - Adding custom retry logic or error handling\n   * - Integrating with monitoring or debugging tools\n   * - Applying organization-specific HTTP client policies\n   *\n   * The transformation is applied once during client initialization and affects\n   * all subsequent API requests made through this client instance.\n   *\n   * Leave absent or set to `undefined` if no custom HTTP client behavior is\n   * needed.\n   */\n  readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n}) => Effect.Effect<Service, never, HttpClient.HttpClient> = Effect.fnUntraced(function*(options) {\n  const httpClient = (yield* HttpClient.HttpClient).pipe(\n    HttpClient.mapRequest((request) =>\n      request.pipe(\n        HttpClientRequest.prependUrl(options.apiUrl ?? \"https://openrouter.ai/api/v1\"),\n        options.apiKey ? HttpClientRequest.bearerToken(options.apiKey) : identity,\n        options.referrer ? HttpClientRequest.setHeader(\"HTTP-Referrer\", options.referrer) : identity,\n        options.title ? HttpClientRequest.setHeader(\"X-Title\", options.title) : identity,\n        HttpClientRequest.acceptJson\n      )\n    ),\n    options.transformClient ?? identity\n  )\n\n  const httpClientOk = HttpClient.filterStatusOk(httpClient)\n\n  const client = Generated.make(httpClient, {\n    transformClient: (client) =>\n      OpenRouterConfig.getOrUndefined.pipe(\n        Effect.map((config) => config?.transformClient ? config.transformClient(client) : client)\n      )\n  })\n\n  const streamRequest = <A, I, R>(\n    request: HttpClientRequest.HttpClientRequest,\n    schema: Schema.Schema<A, I, R>\n  ): Stream.Stream<A, AiError.AiError, R> => {\n    const decodeEvent = Schema.decode(Schema.parseJson(schema))\n    return httpClientOk.execute(request).pipe(\n      Effect.map((r) => r.stream),\n      Stream.unwrapScoped,\n      Stream.decodeText(),\n      Stream.pipeThroughChannel(Sse.makeChannel()),\n      Stream.takeWhile((event) => event.data !== \"[DONE]\"),\n      Stream.mapEffect((event) => decodeEvent(event.data)),\n      Stream.catchTags({\n        RequestError: (error) =>\n          AiError.HttpRequestError.fromRequestError({\n            module: \"OpenRouterClient\",\n            method: \"streamRequest\",\n            error\n          }),\n        ResponseError: (error) =>\n          AiError.HttpResponseError.fromResponseError({\n            module: \"OpenRouterClient\",\n            method: \"streamRequest\",\n            error\n          }),\n        ParseError: (error) =>\n          AiError.MalformedOutput.fromParseError({\n            module: \"OpenRouterClient\",\n            method: \"streamRequest\",\n            error\n          })\n      })\n    )\n  }\n\n  const createChatCompletion: (\n    options: typeof Generated.ChatGenerationParams.Encoded\n  ) => Effect.Effect<Generated.ChatResponse, AiError.AiError> = Effect.fnUntraced(\n    function*(options) {\n      return yield* client.sendChatCompletionRequest(options).pipe(\n        Effect.catchTag(\"ChatError\", (error) =>\n          new AiError.HttpResponseError({\n            module: \"OpenRouterClient\",\n            method: \"createChatCompletion\",\n            reason: \"StatusCode\",\n            request: {\n              hash: error.request.hash,\n              headers: error.request.headers,\n              method: error.request.method,\n              url: error.request.url,\n              urlParams: error.request.urlParams\n            },\n            response: {\n              headers: error.response.headers,\n              status: error.response.status\n            }\n          })),\n        Effect.catchTags({\n          RequestError: (error) =>\n            AiError.HttpRequestError.fromRequestError({\n              module: \"OpenRouterClient\",\n              method: \"createChatCompletion\",\n              error\n            }),\n          ResponseError: (error) =>\n            AiError.HttpResponseError.fromResponseError({\n              module: \"OpenRouterClient\",\n              method: \"createChatCompletion\",\n              error\n            }),\n          ParseError: (error) =>\n            AiError.MalformedOutput.fromParseError({\n              module: \"OpenRouterClient\",\n              method: \"createChatCompletion\",\n              error\n            })\n        })\n      )\n    }\n  )\n\n  const createChatCompletionStream = (\n    options: Omit<typeof Generated.ChatGenerationParams.Encoded, \"stream\">\n  ): Stream.Stream<ChatStreamingResponseChunk, AiError.AiError> => {\n    const request = HttpClientRequest.post(\"/chat/completions\", {\n      body: HttpBody.unsafeJson({\n        ...options,\n        stream: true,\n        stream_options: { include_usage: true }\n      })\n    })\n    return streamRequest(request, ChatStreamingResponseChunk)\n  }\n\n  return OpenRouterClient.of({\n    client,\n    createChatCompletion,\n    createChatCompletionStream\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly apiKey?: Redacted.Redacted | undefined\n  readonly apiUrl?: string | undefined\n  /**\n   * Optional URL of your site for rankings on `openrouter.ai`.\n   */\n  readonly referrer?: string | undefined\n  /**\n   * Optional title of your site for rankings on `openrouter.ai`.\n   */\n  readonly title?: string | undefined\n  /**\n   * A function to transform the underlying HTTP client before it's used to send\n   * API requests.\n   *\n   * This transformation function receives the configured HTTP client and returns\n   * a modified version. It's applied after all standard client configuration\n   * (authentication, base URL, headers) but before any requests are made.\n   *\n   * Use this for:\n   * - Adding custom middleware (logging, metrics, caching)\n   * - Modifying request/response processing behavior\n   * - Adding custom retry logic or error handling\n   * - Integrating with monitoring or debugging tools\n   * - Applying organization-specific HTTP client policies\n   *\n   * The transformation is applied once during client initialization and affects\n   * all subsequent API requests made through this client instance.\n   *\n   * Leave absent or set to `undefined` if no custom HTTP client behavior is\n   * needed.\n   */\n  readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n}): Layer.Layer<OpenRouterClient, never, HttpClient.HttpClient> => Layer.effect(OpenRouterClient, make(options))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerConfig = (options: {\n  readonly apiKey?: Config.Config<Redacted.Redacted> | undefined\n  readonly apiUrl?: Config.Config<string> | undefined\n  /**\n   * Optional URL of your site for rankings on `openrouter.ai`.\n   */\n  readonly referrer?: Config.Config<string> | undefined\n  /**\n   * Optional title of your site for rankings on `openrouter.ai`.\n   */\n  readonly title?: Config.Config<string> | undefined\n  /**\n   * A function to transform the underlying HTTP client before it's used to send\n   * API requests.\n   *\n   * This transformation function receives the configured HTTP client and returns\n   * a modified version. It's applied after all standard client configuration\n   * (authentication, base URL, headers) but before any requests are made.\n   *\n   * Use this for:\n   * - Adding custom middleware (logging, metrics, caching)\n   * - Modifying request/response processing behavior\n   * - Adding custom retry logic or error handling\n   * - Integrating with monitoring or debugging tools\n   * - Applying organization-specific HTTP client policies\n   *\n   * The transformation is applied once during client initialization and affects\n   * all subsequent API requests made through this client instance.\n   *\n   * Leave absent or set to `undefined` if no custom HTTP client behavior is\n   * needed.\n   */\n  readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n}): Layer.Layer<OpenRouterClient, ConfigError, HttpClient.HttpClient> => {\n  const { transformClient, ...configs } = options\n  return Config.all(configs).pipe(\n    Effect.flatMap((configs) => make({ ...configs, transformClient })),\n    Layer.effect(OpenRouterClient)\n  )\n}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ChatStreamingMessageToolCall extends Schema.Class<ChatStreamingMessageToolCall>(\n  \"@effect/ai-openrouter/ChatStreamingMessageToolCall\"\n)({\n  index: Schema.Number,\n  id: Schema.optionalWith(Schema.String, { nullable: true }),\n  type: Schema.optionalWith(Schema.Literal(\"function\"), { nullable: true }),\n  function: Schema.Struct({\n    name: Schema.optionalWith(Schema.String, { nullable: true }),\n    arguments: Schema.optionalWith(Schema.String, { nullable: true })\n  })\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ChatStreamingMessageChunk extends Schema.Class<ChatStreamingMessageChunk>(\n  \"@effect/ai-openrouter/ChatStreamingMessageChunk\"\n)({\n  role: Schema.optionalWith(Schema.Literal(\"assistant\"), { nullable: true }),\n  content: Schema.optionalWith(Schema.String, { nullable: true }),\n  reasoning: Schema.optionalWith(Schema.String, { nullable: true }),\n  reasoning_details: Schema.optionalWith(Schema.Array(Generated.ReasoningDetail), { nullable: true }),\n  images: Schema.optionalWith(Schema.Array(Generated.ChatMessageContentItemImage), { nullable: true }),\n  refusal: Schema.optionalWith(Schema.String, { nullable: true }),\n  tool_calls: Schema.optionalWith(Schema.Array(ChatStreamingMessageToolCall), { nullable: true }),\n  annotations: Schema.optionalWith(Schema.Array(Generated.AnnotationDetail), { nullable: true })\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ChatStreamingChoice extends Schema.Class<ChatStreamingChoice>(\n  \"@effect/ai-openrouter/ChatStreamingChoice\"\n)({\n  index: Schema.Number,\n  delta: Schema.optionalWith(ChatStreamingMessageChunk, { nullable: true }),\n  finish_reason: Schema.optionalWith(Generated.ChatCompletionFinishReason, { nullable: true }),\n  native_finish_reason: Schema.optionalWith(Schema.String, { nullable: true }),\n  logprobs: Schema.optionalWith(Generated.ChatMessageTokenLogprobs, { nullable: true })\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class ChatStreamingResponseChunk extends Schema.Class<ChatStreamingResponseChunk>(\n  \"@effect/ai-openrouter/ChatStreamingResponseChunk\"\n)({\n  id: Schema.optionalWith(Schema.String, { nullable: true }),\n  model: Schema.optionalWith(\n    Schema.TemplateLiteral(Schema.String, Schema.Literal(\"/\"), Schema.String),\n    { nullable: true }\n  ),\n  provider: Schema.optionalWith(Schema.String, { nullable: true }),\n  created: Schema.DateTimeUtcFromNumber,\n  choices: Schema.Array(ChatStreamingChoice),\n  error: Schema.optionalWith(Generated.ChatError.fields.error, { nullable: true }),\n  system_fingerprint: Schema.optionalWith(Schema.String, { nullable: true }),\n  usage: Schema.optionalWith(Generated.ChatGenerationTokenUsage, { nullable: true })\n}) {}\n"
  },
  {
    "path": "packages/ai/openrouter/src/OpenRouterConfig.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { HttpClient } from \"@effect/platform/HttpClient\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class OpenRouterConfig extends Context.Tag(\"@effect/ai-openrouter/OpenRouterConfig\")<\n  OpenRouterConfig,\n  OpenRouterConfig.Service\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<typeof OpenRouterConfig.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(OpenRouterConfig.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace OpenRouterConfig {\n  /**\n   * @since 1.0.0\n   * @category Models\n   */\n  export interface Service {\n    readonly transformClient?: (client: HttpClient) => HttpClient\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport const withClientTransform: {\n  (transform: (client: HttpClient) => HttpClient): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient): Effect.Effect<A, E, R>\n} = dual<\n  (transform: (client: HttpClient) => HttpClient) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient) => Effect.Effect<A, E, R>\n>(\n  2,\n  (self, transformClient) =>\n    Effect.flatMap(\n      OpenRouterConfig.getOrUndefined,\n      (config) => Effect.provideService(self, OpenRouterConfig, { ...config, transformClient })\n    )\n)\n"
  },
  {
    "path": "packages/ai/openrouter/src/OpenRouterLanguageModel.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as AiError from \"@effect/ai/AiError\"\nimport * as LanguageModel from \"@effect/ai/LanguageModel\"\nimport * as AiModel from \"@effect/ai/Model\"\nimport type * as Prompt from \"@effect/ai/Prompt\"\nimport type * as Response from \"@effect/ai/Response\"\nimport { addGenAIAnnotations } from \"@effect/ai/Telemetry\"\nimport * as Tool from \"@effect/ai/Tool\"\nimport * as Arr from \"effect/Array\"\nimport * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport { dual } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Stream from \"effect/Stream\"\nimport type { Span } from \"effect/Tracer\"\nimport type { Simplify } from \"effect/Types\"\nimport type * as Generated from \"./Generated.js\"\nimport * as InternalUtilities from \"./internal/utilities.js\"\nimport type { ChatStreamingResponseChunk } from \"./OpenRouterClient.js\"\nimport { OpenRouterClient } from \"./OpenRouterClient.js\"\n\n// =============================================================================\n// Configuration\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Context\n */\nexport class Config extends Context.Tag(\n  \"@effect/ai-openrouter/OpenRouterLanguageModel/Config\"\n)<Config, Config.Service>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly getOrUndefined: Effect.Effect<typeof Config.Service | undefined> = Effect.map(\n    Effect.context<never>(),\n    (context) => context.unsafeMap.get(Config.key)\n  )\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Config {\n  /**\n   * @since 1.0.0\n   * @category Configuration\n   */\n  export interface Service extends\n    Simplify<\n      Partial<\n        Omit<\n          typeof Generated.ChatGenerationParams.Encoded,\n          \"messages\" | \"response_format\" | \"tools\" | \"tool_choice\" | \"stream\"\n        >\n      >\n    >\n  {}\n}\n\n// =============================================================================\n// OpenRouter Provider Options / Metadata\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Provider Metadata\n */\nexport type OpenRouterReasoningInfo = {\n  readonly type: \"reasoning\"\n  readonly signature: string | undefined\n} | {\n  readonly type: \"encrypted_reasoning\"\n  readonly format: typeof Generated.ReasoningDetailSummary.Type[\"format\"]\n  readonly redactedData: string\n}\n\n/**\n * @since 1.0.0\n * @category Provider Options\n */\ndeclare module \"@effect/ai/Prompt\" {\n  export interface SystemMessageOptions extends ProviderOptions {\n    readonly openrouter?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface UserMessageOptions extends ProviderOptions {\n    readonly openrouter?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface AssistantMessageOptions extends ProviderOptions {\n    readonly openrouter?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface ToolMessageOptions extends ProviderOptions {\n    readonly openrouter?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface TextPartOptions extends ProviderOptions {\n    readonly openrouter?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface ReasoningPartOptions extends ProviderOptions {\n    readonly openrouter?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface FilePartOptions extends ProviderOptions {\n    readonly openrouter?: {\n      /**\n       * The name to give to the file. Will be prioritized over the file name\n       * associated with the file part, if present.\n       */\n      readonly fileName?: string | undefined\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n\n  export interface ToolResultPartOptions extends ProviderOptions {\n    readonly openrouter?: {\n      /**\n       * A breakpoint which marks the end of reusable content eligible for caching.\n       */\n      readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | undefined\n    } | undefined\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Provider Metadata\n */\ndeclare module \"@effect/ai/Response\" {\n  export interface ReasoningPartMetadata extends ProviderMetadata {\n    readonly openrouter?: OpenRouterReasoningInfo | undefined\n  }\n\n  export interface ReasoningStartPartMetadata extends ProviderMetadata {\n    readonly openrouter?: OpenRouterReasoningInfo | undefined\n  }\n\n  export interface ReasoningDeltaPartMetadata extends ProviderMetadata {\n    readonly openrouter?: OpenRouterReasoningInfo | undefined\n  }\n\n  export interface UrlSourcePartMetadata extends ProviderMetadata {\n    readonly openrouter?: {\n      readonly content?: string | undefined\n    } | undefined\n  }\n\n  export interface FinishPartMetadata extends ProviderMetadata {\n    readonly openrouter?: {\n      /**\n       * The provider used to generate the response.\n       */\n      readonly provider?: string | undefined\n      /**\n       * Additional usage information.\n       */\n      readonly usage?: {\n        /**\n         * The total cost of generating the response.\n         */\n        readonly cost?: number | undefined\n        /**\n         * Additional details about cost.\n         */\n        readonly costDetails?: {\n          readonly upstream_inference_cost?: number | undefined\n        } | undefined\n        /**\n         * Additional details about prompt token usage.\n         */\n        readonly promptTokensDetails?: {\n          readonly audio_tokens?: number | undefined\n          readonly cached_tokens?: number | undefined\n        }\n        /**\n         * Additional details about completion token usage.\n         */\n        readonly completionTokensDetails?: {\n          readonly reasoning_tokens?: number | undefined\n          readonly audio_tokens?: number | undefined\n          readonly accepted_prediction_tokens?: number | undefined\n          readonly rejected_prediction_tokens?: number | undefined\n        } | undefined\n      } | undefined\n    } | undefined\n  }\n}\n\n// =============================================================================\n// OpenRouter Language Model\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category Ai Models\n */\nexport const model = (\n  model: string,\n  config?: Omit<Config.Service, \"model\">\n): AiModel.Model<\"openrouter\", LanguageModel.LanguageModel, OpenRouterClient> =>\n  AiModel.make(\"openrouter\", layer({ model, config }))\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.fnUntraced(function*(options: {\n  readonly model: string\n  readonly config?: Omit<Config.Service, \"model\">\n}) {\n  const client = yield* OpenRouterClient\n\n  const makeRequest = Effect.fnUntraced(\n    function*(providerOptions: LanguageModel.ProviderOptions) {\n      const context = yield* Effect.context<never>()\n      const config = { model: options.model, ...options.config, ...context.unsafeMap.get(Config.key) }\n      const messages = yield* prepareMessages(providerOptions)\n      const { toolChoice, tools } = yield* prepareTools(providerOptions)\n      const responseFormat = providerOptions.responseFormat\n      const request: typeof Generated.ChatGenerationParams.Encoded = {\n        ...config,\n        messages,\n        tools,\n        tool_choice: toolChoice,\n        response_format: responseFormat.type === \"text\" ? undefined : {\n          type: \"json_schema\",\n          json_schema: {\n            name: responseFormat.objectName,\n            description: Tool.getDescriptionFromSchemaAst(responseFormat.schema.ast) ?? \"Respond with a JSON object\",\n            schema: Tool.getJsonSchemaFromSchemaAst(responseFormat.schema.ast),\n            strict: true\n          }\n        }\n      }\n      return request\n    }\n  )\n\n  return yield* LanguageModel.make({\n    generateText: Effect.fnUntraced(\n      function*(options) {\n        const request = yield* makeRequest(options)\n        annotateRequest(options.span, request)\n        const rawResponse = yield* client.createChatCompletion(request)\n        annotateResponse(options.span, rawResponse)\n        return yield* makeResponse(rawResponse)\n      }\n    ),\n    streamText: Effect.fnUntraced(\n      function*(options) {\n        const request = yield* makeRequest(options)\n        annotateRequest(options.span, request)\n        return client.createChatCompletionStream(request)\n      },\n      (effect, options) =>\n        effect.pipe(\n          Effect.flatMap((stream) => makeStreamResponse(stream)),\n          Stream.unwrap,\n          Stream.map((response) => {\n            annotateStreamResponse(options.span, response)\n            return response\n          })\n        )\n    )\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly model: string\n  readonly config?: Omit<Config.Service, \"model\">\n}): Layer.Layer<LanguageModel.LanguageModel, never, OpenRouterClient> =>\n  Layer.effect(LanguageModel.LanguageModel, make({ model: options.model, config: options.config }))\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport const withConfigOverride: {\n  (config: Config.Service): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, config: Config.Service): Effect.Effect<A, E, R>\n} = dual<\n  (config: Config.Service) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, config: Config.Service) => Effect.Effect<A, E, R>\n>(2, (self, overrides) =>\n  Effect.flatMap(\n    Config.getOrUndefined,\n    (config) => Effect.provideService(self, Config, { ...config, ...overrides })\n  ))\n\n// =============================================================================\n// Prompt Conversion\n// =============================================================================\n\nconst prepareMessages: (options: LanguageModel.ProviderOptions) => Effect.Effect<\n  ReadonlyArray<typeof Generated.Message.Encoded>,\n  AiError.AiError\n> = Effect.fnUntraced(function*(options) {\n  const messages: Array<typeof Generated.Message.Encoded> = []\n\n  for (const message of options.prompt.content) {\n    switch (message.role) {\n      case \"system\": {\n        messages.push({\n          role: \"system\",\n          content: message.content,\n          cache_control: getCacheControl(message)\n        })\n        break\n      }\n\n      case \"user\": {\n        if (message.content.length === 1 && message.content[0].type === \"text\") {\n          const part = message.content[0]\n          const cacheControl = getCacheControl(message) ?? getCacheControl(part)\n          messages.push({\n            role: \"user\",\n            content: Predicate.isNotUndefined(cacheControl)\n              ? [{ type: \"text\", text: part.text, cache_control: cacheControl }]\n              : part.text\n          })\n        } else {\n          const content: Array<typeof Generated.ChatMessageContentItem.Encoded> = []\n          const messageCacheControl = getCacheControl(message)\n          for (const part of message.content) {\n            const partCacheControl = getCacheControl(part)\n            const cacheControl = partCacheControl ?? messageCacheControl\n            switch (part.type) {\n              case \"text\": {\n                content.push({\n                  type: \"text\",\n                  text: part.text,\n                  cache_control: cacheControl\n                })\n                break\n              }\n              case \"file\": {\n                if (part.mediaType.startsWith(\"image/\")) {\n                  const mediaType = part.mediaType === \"image/*\" ? \"image/jpeg\" : part.mediaType\n                  content.push({\n                    type: \"image_url\",\n                    image_url: {\n                      url: part.data instanceof URL\n                        ? part.data.toString()\n                        : part.data instanceof Uint8Array\n                        ? `data:${mediaType};base64,${Encoding.encodeBase64(part.data)}`\n                        : part.data\n                    },\n                    cache_control: cacheControl\n                  })\n                } else {\n                  const options = part.options.openrouter\n                  const fileName = options?.fileName ?? part.fileName ?? \"\"\n                  content.push({\n                    type: \"file\",\n                    file: {\n                      filename: fileName,\n                      file_data: part.data instanceof URL\n                        ? part.data.toString()\n                        : part.data instanceof Uint8Array\n                        ? `data:${part.mediaType};base64,${Encoding.encodeBase64(part.data)}`\n                        : part.data\n                    },\n                    cache_control: part.data instanceof URL ? cacheControl : undefined\n                  })\n                }\n                break\n              }\n            }\n          }\n          messages.push({\n            role: \"user\",\n            content\n          })\n        }\n        break\n      }\n\n      case \"assistant\": {\n        let text = \"\"\n        let reasoning = \"\"\n        const reasoningDetails: Array<typeof Generated.ReasoningDetail.Encoded> = []\n        const toolCalls: Array<typeof Generated.ChatMessageToolCall.Encoded> = []\n        const cacheControl = getCacheControl(message)\n        for (const part of message.content) {\n          switch (part.type) {\n            case \"text\": {\n              text += part.text\n              break\n            }\n            case \"reasoning\": {\n              reasoning += part.text\n              reasoningDetails.push({\n                type: \"reasoning.text\",\n                text: part.text\n              })\n              break\n            }\n            case \"tool-call\": {\n              toolCalls.push({\n                id: part.id,\n                type: \"function\",\n                function: {\n                  name: part.name,\n                  arguments: JSON.stringify(part.params)\n                }\n              })\n              break\n            }\n          }\n        }\n        messages.push({\n          role: \"assistant\",\n          content: text,\n          tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\n          reasoning: reasoning.length > 0 ? reasoning : undefined,\n          reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : undefined,\n          cache_control: cacheControl\n        })\n        break\n      }\n\n      case \"tool\": {\n        const cacheControl = getCacheControl(message)\n        for (const part of message.content) {\n          messages.push({\n            role: \"tool\",\n            tool_call_id: part.id,\n            content: JSON.stringify(part.result),\n            cache_control: cacheControl\n          })\n        }\n        break\n      }\n    }\n  }\n\n  return messages\n})\n\n// =============================================================================\n// Tool Conversion\n// =============================================================================\n\nconst prepareTools: (options: LanguageModel.ProviderOptions) => Effect.Effect<{\n  readonly tools: ReadonlyArray<typeof Generated.ToolDefinitionJson.Encoded> | undefined\n  readonly toolChoice: typeof Generated.ToolChoiceOption.Encoded | undefined\n}, AiError.AiError> = Effect.fnUntraced(\n  function*(options: LanguageModel.ProviderOptions) {\n    if (options.tools.length === 0) {\n      return { tools: undefined, toolChoice: undefined }\n    }\n\n    const hasProviderDefinedTools = options.tools.some((tool) => Tool.isProviderDefined(tool))\n    if (hasProviderDefinedTools) {\n      return yield* new AiError.MalformedInput({\n        module: \"OpenRouterLanguageModel\",\n        method: \"prepareTools\",\n        description: \"Provider-defined tools are unsupported by the OpenRouter \" +\n          \"provider integration at this time\"\n      })\n    }\n\n    let tools: Array<typeof Generated.ToolDefinitionJson.Encoded> = []\n    let toolChoice: typeof Generated.ToolChoiceOption.Encoded | undefined = undefined\n\n    for (const tool of options.tools) {\n      tools.push({\n        type: \"function\",\n        function: {\n          name: tool.name,\n          description: Tool.getDescription(tool as any),\n          parameters: Tool.getJsonSchema(tool as any) as any,\n          strict: true\n        }\n      })\n    }\n\n    if (options.toolChoice === \"none\") {\n      toolChoice = \"none\"\n    } else if (options.toolChoice === \"auto\") {\n      toolChoice = \"auto\"\n    } else if (options.toolChoice === \"required\") {\n      toolChoice = \"required\"\n    } else if (\"tool\" in options.toolChoice) {\n      toolChoice = { type: \"function\", function: { name: options.toolChoice.tool } }\n    } else {\n      const allowedTools = new Set(options.toolChoice.oneOf)\n      tools = tools.filter((tool) => allowedTools.has(tool.function.name))\n      toolChoice = options.toolChoice.mode === \"auto\" ? \"auto\" : \"required\"\n    }\n\n    return { tools, toolChoice }\n  }\n)\n\n// =============================================================================\n// Response Conversion\n// =============================================================================\n\nconst makeResponse: (response: Generated.ChatResponse) => Effect.Effect<\n  Array<Response.PartEncoded>,\n  AiError.AiError\n> = Effect.fnUntraced(\n  function*(response) {\n    const choice = response.choices[0]\n\n    if (Predicate.isUndefined(choice)) {\n      return yield* new AiError.MalformedOutput({\n        module: \"OpenRouterLanguageModel\",\n        method: \"makeResponse\",\n        description: \"Received response with no valid choices\"\n      })\n    }\n\n    const parts: Array<Response.PartEncoded> = []\n    const message = choice.message\n\n    const createdAt = new Date(response.created * 1000)\n    parts.push({\n      type: \"response-metadata\",\n      id: response.id,\n      modelId: response.model,\n      timestamp: DateTime.formatIso(DateTime.unsafeFromDate(createdAt))\n    })\n\n    if (Predicate.isNotNullable(message.reasoning) && message.reasoning.length > 0) {\n      parts.push({\n        type: \"reasoning\",\n        text: message.reasoning\n      })\n    }\n\n    if (Predicate.isNotNullable(message.reasoning_details) && message.reasoning_details.length > 0) {\n      for (const detail of message.reasoning_details) {\n        switch (detail.type) {\n          case \"reasoning.summary\": {\n            if (Predicate.isNotUndefined(detail.summary) && detail.summary.length > 0) {\n              parts.push({\n                type: \"reasoning\",\n                text: detail.summary\n              })\n            }\n            break\n          }\n          case \"reasoning.encrypted\": {\n            if (Predicate.isNotUndefined(detail.data) && detail.data.length > 0) {\n              parts.push({\n                type: \"reasoning\",\n                text: \"\",\n                metadata: {\n                  openrouter: {\n                    type: \"encrypted_reasoning\",\n                    format: detail.format,\n                    redactedData: detail.data\n                  }\n                }\n              })\n            }\n            break\n          }\n          case \"reasoning.text\": {\n            if (Predicate.isNotUndefined(detail.text) && detail.text.length > 0) {\n              parts.push({\n                type: \"reasoning\",\n                text: detail.text,\n                metadata: {\n                  openrouter: {\n                    type: \"reasoning\",\n                    signature: detail.signature\n                  }\n                }\n              })\n            }\n            break\n          }\n        }\n      }\n    }\n\n    if (Predicate.isNotNullable(message.content) && message.content.length > 0) {\n      parts.push({\n        type: \"text\",\n        text: message.content as string\n      })\n    }\n\n    if (Predicate.isNotNullable(message.tool_calls)) {\n      for (const toolCall of message.tool_calls) {\n        const toolName = toolCall.function.name\n        const toolParams = toolCall.function.arguments\n        const params = yield* Effect.try({\n          try: () => Tool.unsafeSecureJsonParse(toolParams),\n          catch: (cause) =>\n            new AiError.MalformedOutput({\n              module: \"OpenRouterLanguageModel\",\n              method: \"makeResponse\",\n              description: \"Failed to securely parse tool call parameters \" +\n                `for tool '${toolName}':\\nParameters: ${toolParams}`,\n              cause\n            })\n        })\n        parts.push({\n          type: \"tool-call\",\n          id: toolCall.id,\n          name: toolName,\n          params\n        })\n      }\n    }\n\n    if (Predicate.isNotNullable(message.annotations)) {\n      for (const annotation of message.annotations) {\n        if (annotation.type === \"url_citation\") {\n          parts.push({\n            type: \"source\",\n            sourceType: \"url\",\n            id: annotation.url_citation.url,\n            url: annotation.url_citation.url,\n            title: annotation.url_citation.title,\n            metadata: {\n              openrouter: {\n                content: annotation.url_citation.content\n              }\n            }\n          })\n        }\n      }\n    }\n\n    if (Predicate.isNotNullable(message.images)) {\n      for (const image of message.images) {\n        parts.push({\n          type: \"file\",\n          mediaType: getMediaType(image.image_url.url) ?? \"image/jpeg\",\n          data: getBase64FromDataUrl(image.image_url.url)\n        })\n      }\n    }\n\n    parts.push({\n      type: \"finish\",\n      reason: InternalUtilities.resolveFinishReason(choice.finish_reason),\n      usage: {\n        inputTokens: response.usage?.prompt_tokens,\n        outputTokens: response.usage?.completion_tokens,\n        totalTokens: response.usage?.total_tokens,\n        reasoningTokens: response.usage?.completion_tokens_details?.reasoning_tokens,\n        cachedInputTokens: response.usage?.prompt_tokens_details?.cached_tokens\n      },\n      metadata: {\n        openrouter: {\n          provider: response.provider,\n          usage: {\n            cost: response.usage?.cost,\n            promptTokensDetails: response.usage?.prompt_tokens_details,\n            completionTokensDetails: response.usage?.completion_tokens_details,\n            costDetails: response.usage?.cost_details\n          }\n        }\n      }\n    })\n\n    return parts\n  }\n)\n\nconst makeStreamResponse: (stream: Stream.Stream<ChatStreamingResponseChunk, AiError.AiError>) => Effect.Effect<\n  Stream.Stream<Response.StreamPartEncoded, AiError.AiError>\n> = Effect.fnUntraced(\n  function*(stream) {\n    let idCounter = 0\n    let activeTextId: string | undefined = undefined\n    let activeReasoningId: string | undefined = undefined\n    let finishReason: Response.FinishReason = \"unknown\"\n    let responseMetadataEmitted = false\n\n    const activeToolCalls: Record<number, {\n      readonly index: number\n      readonly id: string\n      readonly name: string\n      params: string\n    }> = {}\n\n    return stream.pipe(\n      Stream.mapEffect(Effect.fnUntraced(function*(event) {\n        const parts: Array<Response.StreamPartEncoded> = []\n\n        if (\"error\" in event) {\n          parts.push({\n            type: \"error\",\n            error: event.error\n          })\n          return parts\n        }\n\n        // Response Metadata\n\n        if (Predicate.isNotUndefined(event.id) && !responseMetadataEmitted) {\n          parts.push({\n            type: \"response-metadata\",\n            id: event.id,\n            modelId: event.model,\n            timestamp: DateTime.formatIso(yield* DateTime.now)\n          })\n          responseMetadataEmitted = true\n        }\n\n        const choice = event.choices[0]\n\n        if (Predicate.isUndefined(choice) && Predicate.isUndefined(event.usage)) {\n          return yield* new AiError.MalformedOutput({\n            module: \"OpenRouterLanguageModel\",\n            method: \"makeResponse\",\n            description: \"Received response with no valid choices\"\n          })\n        }\n\n        const delta = choice?.delta\n\n        // Reasoning Parts\n\n        const emitReasoningPart = (delta: string, metadata: OpenRouterReasoningInfo | undefined = undefined) => {\n          // End in-progress text part if present before starting reasoning\n          if (Predicate.isNotUndefined(activeTextId)) {\n            parts.push({\n              type: \"text-end\",\n              id: activeTextId\n            })\n            activeTextId = undefined\n          }\n          // Start a new reasoning part if necessary\n          if (Predicate.isUndefined(activeReasoningId)) {\n            activeReasoningId = (idCounter++).toString()\n            parts.push({\n              type: \"reasoning-start\",\n              id: activeReasoningId,\n              metadata: { openrouter: metadata }\n            })\n          }\n          // Emit the reasoning delta\n          parts.push({\n            type: \"reasoning-delta\",\n            id: activeReasoningId,\n            delta,\n            metadata: { openrouter: metadata }\n          })\n        }\n\n        if (Predicate.isNotNullable(delta?.reasoning_details) && delta.reasoning_details.length > 0) {\n          for (const detail of delta.reasoning_details) {\n            switch (detail.type) {\n              case \"reasoning.summary\": {\n                if (Predicate.isNotUndefined(detail.summary) && detail.summary.length > 0) {\n                  emitReasoningPart(detail.summary)\n                }\n                break\n              }\n              case \"reasoning.encrypted\": {\n                if (Predicate.isNotUndefined(detail.data) && detail.data.length > 0) {\n                  emitReasoningPart(\"\", {\n                    type: \"encrypted_reasoning\",\n                    format: detail.format,\n                    redactedData: detail.data\n                  })\n                }\n                break\n              }\n              case \"reasoning.text\": {\n                if (Predicate.isNotUndefined(detail.text) && detail.text.length > 0) {\n                  emitReasoningPart(detail.text, {\n                    type: \"reasoning\",\n                    signature: detail.signature\n                  })\n                }\n                break\n              }\n            }\n          }\n        } else if (Predicate.isNotNullable(delta?.reasoning) && delta.reasoning.length > 0) {\n          emitReasoningPart(delta.reasoning)\n        }\n\n        // Text Parts\n\n        if (Predicate.isNotNullable(delta?.content) && delta.content.length > 0) {\n          // End in-progress reasoning part if present before starting text\n          if (Predicate.isNotUndefined(activeReasoningId)) {\n            parts.push({\n              type: \"reasoning-end\",\n              id: activeReasoningId\n            })\n            activeReasoningId = undefined\n          }\n          // Start a new text part if necessary\n          if (Predicate.isUndefined(activeTextId)) {\n            activeTextId = (idCounter++).toString()\n            parts.push({\n              type: \"text-start\",\n              id: activeTextId\n            })\n          }\n          // Emit the text delta\n          parts.push({\n            type: \"text-delta\",\n            id: activeTextId,\n            delta: delta.content\n          })\n        }\n\n        // Source Parts\n\n        if (Predicate.isNotNullable(delta?.annotations)) {\n          for (const annotation of delta.annotations) {\n            if (annotation.type === \"url_citation\") {\n              parts.push({\n                type: \"source\",\n                sourceType: \"url\",\n                id: annotation.url_citation.url,\n                url: annotation.url_citation.url,\n                title: annotation.url_citation.title,\n                metadata: {\n                  openrouter: {\n                    content: annotation.url_citation.content\n                  }\n                }\n              })\n            }\n          }\n        }\n\n        // Tool Call Parts\n\n        if (Predicate.isNotNullable(delta?.tool_calls) && delta.tool_calls.length > 0) {\n          for (const toolCall of delta.tool_calls) {\n            // Get the active tool call, if present\n            let activeToolCall = activeToolCalls[toolCall.index]\n\n            // If no active tool call was found, start a new active tool call\n            if (Predicate.isUndefined(activeToolCall)) {\n              // The tool call id and function name always come back with the\n              // first tool call delta\n              activeToolCall = {\n                index: toolCall.index,\n                id: toolCall.id!,\n                name: toolCall.function.name!,\n                params: toolCall.function.arguments ?? \"\"\n              }\n\n              activeToolCalls[toolCall.index] = activeToolCall\n\n              parts.push({\n                type: \"tool-params-start\",\n                id: activeToolCall.id,\n                name: activeToolCall.name\n              })\n\n              // Emit a tool call delta part if parameters were also sent\n              if (activeToolCall.params.length > 0) {\n                parts.push({\n                  type: \"tool-params-delta\",\n                  id: activeToolCall.id,\n                  delta: activeToolCall.params\n                })\n              }\n            } else {\n              // If an active tool call was found, update and emit the delta for\n              // the tool call's parameters\n              activeToolCall.params += toolCall.function.arguments\n              parts.push({\n                type: \"tool-params-delta\",\n                id: activeToolCall.id,\n                delta: activeToolCall.params\n              })\n            }\n\n            // Check if the tool call is complete\n            try {\n              const params = Tool.unsafeSecureJsonParse(activeToolCall.params)\n              parts.push({\n                type: \"tool-params-end\",\n                id: activeToolCall.id\n              })\n              parts.push({\n                type: \"tool-call\",\n                id: activeToolCall.id,\n                name: activeToolCall.name,\n                params\n              })\n              delete activeToolCalls[toolCall.index]\n            } catch {\n              // Tool call incomplete, continue parsing\n              continue\n            }\n          }\n        }\n\n        // File Parts\n\n        if (Predicate.isNotNullable(delta?.images)) {\n          for (const image of delta.images) {\n            parts.push({\n              type: \"file\",\n              mediaType: getMediaType(image.image_url.url) ?? \"image/jpeg\",\n              data: getBase64FromDataUrl(image.image_url.url)\n            })\n          }\n        }\n\n        // Finish Parts\n\n        if (Predicate.isNotNullable(choice?.finish_reason)) {\n          finishReason = InternalUtilities.resolveFinishReason(choice.finish_reason)\n        }\n\n        // Usage is only emitted by the last part of the stream, so we need to\n        // handle flushing any remaining text / reasoning / tool calls\n        if (Predicate.isNotUndefined(event.usage)) {\n          // Complete any remaining tool calls if the finish reason is tool-calls\n          if (finishReason === \"tool-calls\") {\n            for (const toolCall of Object.values(activeToolCalls)) {\n              // Coerce invalid tool call parameters to an empty object\n              const params = yield* Effect.try(() => Tool.unsafeSecureJsonParse(toolCall.params)).pipe(\n                Effect.catchAll(() => Effect.succeed({}))\n              )\n              parts.push({\n                type: \"tool-params-end\",\n                id: toolCall.id\n              })\n              parts.push({\n                type: \"tool-call\",\n                id: toolCall.id,\n                name: toolCall.name,\n                params\n              })\n              delete activeToolCalls[toolCall.index]\n            }\n          }\n\n          // Flush remaining reasoning parts\n          if (Predicate.isNotUndefined(activeReasoningId)) {\n            parts.push({\n              type: \"reasoning-end\",\n              id: activeReasoningId\n            })\n            activeReasoningId = undefined\n          }\n\n          // Flush remaining text parts\n          if (Predicate.isNotUndefined(activeTextId)) {\n            parts.push({\n              type: \"text-end\",\n              id: activeTextId\n            })\n            activeTextId = undefined\n          }\n\n          parts.push({\n            type: \"finish\",\n            reason: finishReason,\n            usage: {\n              inputTokens: event.usage?.prompt_tokens,\n              outputTokens: event.usage?.completion_tokens,\n              totalTokens: event.usage?.total_tokens,\n              reasoningTokens: event.usage?.completion_tokens_details?.reasoning_tokens,\n              cachedInputTokens: event.usage?.prompt_tokens_details?.cached_tokens\n            },\n            metadata: {\n              openrouter: {\n                provider: event.provider,\n                usage: {\n                  cost: event.usage?.cost,\n                  promptTokensDetails: event.usage?.prompt_tokens_details,\n                  completionTokensDetails: event.usage?.completion_tokens_details,\n                  costDetails: event.usage?.cost_details\n                }\n              }\n            }\n          })\n        }\n\n        return parts\n      })),\n      Stream.flattenIterables\n    )\n  }\n)\n\n// =============================================================================\n// Telemetry\n// =============================================================================\n\nconst annotateRequest = (\n  span: Span,\n  request: typeof Generated.ChatGenerationParams.Encoded\n): void => {\n  addGenAIAnnotations(span, {\n    system: \"openrouter\",\n    operation: { name: \"chat\" },\n    request: {\n      model: request.model,\n      temperature: request.temperature,\n      topP: request.top_p,\n      maxTokens: request.max_tokens,\n      stopSequences: Arr.ensure(request.stop).filter(\n        Predicate.isNotNullable\n      )\n    }\n  })\n}\n\nconst annotateResponse = (span: Span, response: Generated.ChatResponse): void => {\n  addGenAIAnnotations(span, {\n    response: {\n      id: response.id,\n      model: response.model,\n      finishReasons: response.choices.map((choice) => choice.finish_reason).filter(Predicate.isNotNullable)\n    },\n    usage: {\n      inputTokens: response.usage?.prompt_tokens,\n      outputTokens: response.usage?.completion_tokens\n    }\n  })\n}\n\nconst annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded) => {\n  if (part.type === \"response-metadata\") {\n    addGenAIAnnotations(span, {\n      response: {\n        id: part.id,\n        model: part.modelId\n      }\n    })\n  }\n  if (part.type === \"finish\") {\n    addGenAIAnnotations(span, {\n      response: {\n        finishReasons: [part.reason]\n      },\n      usage: {\n        inputTokens: part.usage.inputTokens,\n        outputTokens: part.usage.outputTokens\n      }\n    })\n  }\n}\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nconst getCacheControl = (\n  part:\n    | Prompt.SystemMessage\n    | Prompt.UserMessage\n    | Prompt.AssistantMessage\n    | Prompt.ToolMessage\n    | Prompt.TextPart\n    | Prompt.ReasoningPart\n    | Prompt.FilePart\n    | Prompt.ToolResultPart\n): typeof Generated.CacheControlEphemeral.Encoded | undefined => part.options.openrouter?.cacheControl\n\nconst getMediaType = (dataUrl: string): string | undefined => {\n  const match = dataUrl.match(/^data:([^;]+)/)\n  return match ? match[1] : undefined\n}\n\nconst getBase64FromDataUrl = (dataUrl: string): string => {\n  const match = dataUrl.match(/^data:[^;]*;base64,(.+)$/)\n  return match ? match[1]! : dataUrl\n}\n"
  },
  {
    "path": "packages/ai/openrouter/src/index.ts",
    "content": "/**\n * @since 1.0.0\n */\nexport * as Generated from \"./Generated.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OpenRouterClient from \"./OpenRouterClient.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OpenRouterConfig from \"./OpenRouterConfig.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OpenRouterLanguageModel from \"./OpenRouterLanguageModel.js\"\n"
  },
  {
    "path": "packages/ai/openrouter/src/internal/utilities.ts",
    "content": "import type * as Response from \"@effect/ai/Response\"\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Generated from \"../Generated.js\"\n\nconst finishReasonMap: Record<string, Response.FinishReason> = {\n  content_filter: \"content-filter\",\n  error: \"error\",\n  function_call: \"tool-calls\",\n  tool_calls: \"tool-calls\",\n  length: \"length\",\n  stop: \"stop\"\n}\n\n/** @internal */\nexport const resolveFinishReason = (\n  finishReason: typeof Generated.ChatCompletionFinishReason.Type | null\n): Response.FinishReason => {\n  if (Predicate.isNull(finishReason)) {\n    return \"unknown\"\n  }\n  const reason = finishReasonMap[finishReason]\n  if (Predicate.isUndefined(reason)) {\n    return \"unknown\"\n  }\n  return reason\n}\n"
  },
  {
    "path": "packages/ai/openrouter/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"references\": [\n    { \"path\": \"../ai/tsconfig.build.json\" },\n    { \"path\": \"../../effect/tsconfig.build.json\" },\n    { \"path\": \"../../experimental/tsconfig.build.json\" },\n    { \"path\": \"../../platform/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/openrouter/tsconfig.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/ai/openrouter/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"references\": [\n    { \"path\": \"../ai/tsconfig.src.json\" },\n    { \"path\": \"../../effect/tsconfig.src.json\" },\n    { \"path\": \"../../experimental/tsconfig.src.json\" },\n    { \"path\": \"../../platform/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\",\n    \"outDir\": \"build/src\",\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/openrouter/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../../vitest/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"noEmit\": true,\n    \"exactOptionalPropertyTypes\": false\n  }\n}\n"
  },
  {
    "path": "packages/ai/openrouter/vitest.config.ts",
    "content": "import { mergeConfig, type ViteUserConfig } from \"vitest/config\"\nimport shared from \"../../../vitest.shared.js\"\n\nconst config: ViteUserConfig = {}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/cli/CHANGELOG.md",
    "content": "# @effect/cli\n\n## 0.75.0\n\n### Patch Changes\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n  - @effect/platform@0.96.0\n  - @effect/printer@0.49.0\n  - @effect/printer-ansi@0.49.0\n\n## 0.74.0\n\n### Patch Changes\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n  - @effect/platform@0.95.0\n  - @effect/printer@0.48.0\n  - @effect/printer-ansi@0.48.0\n\n## 0.73.2\n\n### Patch Changes\n\n- [#6022](https://github.com/Effect-TS/effect/pull/6022) [`5df4da1`](https://github.com/Effect-TS/effect/commit/5df4da10de444f379a166f4b28721e75100bb838) Thanks @m9tdev! - Fixed `Prompt.text` rendering duplicate lines when input text wraps to a new terminal line.\n\n- Updated dependencies [[`0023c19`](https://github.com/Effect-TS/effect/commit/0023c19c63c402c050d496817ba92aceea7f25b7), [`e71889f`](https://github.com/Effect-TS/effect/commit/e71889f35b081d13b7da2c04d2f81d6933056b49), [`9a96b87`](https://github.com/Effect-TS/effect/commit/9a96b87a33a75ebc277c585e60758ab4409c0d9e)]:\n  - @effect/platform@0.94.3\n  - effect@3.19.16\n\n## 0.73.1\n\n### Patch Changes\n\n- [#5983](https://github.com/Effect-TS/effect/pull/5983) [`0d1a44f`](https://github.com/Effect-TS/effect/commit/0d1a44fa142c0da25fe36a1ac35675f666944803) Thanks @cevr! - Allow options to appear after positional arguments\n\n  Previously, `@effect/cli` required all options to appear before positional arguments. For example, `cmd --force staging` worked but `cmd staging --force` failed with \"Received unknown argument\".\n\n  This change updates the option parsing logic to scan through all arguments to find options, regardless of their position relative to positional arguments. This aligns with the behavior of most CLI tools (git, npm, docker, etc.) which allow options anywhere in the command.\n\n  **Before:**\n\n  ```bash\n  myapp deploy --force staging  # worked\n  myapp deploy staging --force  # failed: \"Received unknown argument: '--force'\"\n  ```\n\n  **After:**\n\n  ```bash\n  myapp deploy --force staging  # works\n  myapp deploy staging --force  # works\n  ```\n\n- Updated dependencies [[`7e925ea`](https://github.com/Effect-TS/effect/commit/7e925eae4a9db556bcbf7e8b6a762ccf8588aa3b), [`118e7a4`](https://github.com/Effect-TS/effect/commit/118e7a4af5b86f6d707a40d3b03157b6bf5827e7), [`d7e75d6`](https://github.com/Effect-TS/effect/commit/d7e75d6d15294bbcd7ac49a0e9005848379ea86f), [`4860d1e`](https://github.com/Effect-TS/effect/commit/4860d1e09b436061ea4aeca07605a669793560fc)]:\n  - effect@3.19.15\n  - @effect/platform@0.94.2\n\n## 0.73.0\n\n### Patch Changes\n\n- [#5853](https://github.com/Effect-TS/effect/pull/5853) [`1b23741`](https://github.com/Effect-TS/effect/commit/1b23741a3d43acfa99ffa385b9c496d411704d0c) Thanks @Masty88! - handle executable paths with spaces in CLI arguments\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n  - @effect/platform@0.94.0\n\n## 0.72.1\n\n### Patch Changes\n\n- [#5677](https://github.com/Effect-TS/effect/pull/5677) [`f8273c9`](https://github.com/Effect-TS/effect/commit/f8273c9de13ffa6d96c08686f28951177b59f430) Thanks @nemmtor! - fix log level cli arg infinite loop\n\n- Updated dependencies [[`7d28a90`](https://github.com/Effect-TS/effect/commit/7d28a908f965854cff386a19515141aea5b39eb7)]:\n  - effect@3.19.3\n\n## 0.72.0\n\n### Patch Changes\n\n- Updated dependencies [[`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - effect@3.19.0\n  - @effect/platform@0.93.0\n  - @effect/printer@0.47.0\n  - @effect/printer-ansi@0.47.0\n\n## 0.71.0\n\n### Patch Changes\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2)]:\n  - effect@3.18.0\n  - @effect/platform@0.92.0\n  - @effect/printer@0.46.0\n  - @effect/printer-ansi@0.46.0\n\n## 0.70.0\n\n### Patch Changes\n\n- Updated dependencies [[`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a)]:\n  - @effect/platform@0.91.0\n\n## 0.69.2\n\n### Patch Changes\n\n- [#5410](https://github.com/Effect-TS/effect/pull/5410) [`fef9771`](https://github.com/Effect-TS/effect/commit/fef9771eab24af6415be946df0c9f64eba01cef7) Thanks @beeman! - export isQuitExection function from @effect/platform/Terminal\n\n- Updated dependencies [[`84bc300`](https://github.com/Effect-TS/effect/commit/84bc3003b42ad51210e9e1248efd04c5d0e3dd1e), [`fef9771`](https://github.com/Effect-TS/effect/commit/fef9771eab24af6415be946df0c9f64eba01cef7)]:\n  - effect@3.17.8\n  - @effect/platform@0.90.5\n\n## 0.69.1\n\n### Patch Changes\n\n- [#5400](https://github.com/Effect-TS/effect/pull/5400) [`0e296f5`](https://github.com/Effect-TS/effect/commit/0e296f532afa7b69a44d9bff88a56976e248cb43) Thanks @kitlangton! - cli: multiSelect supports per-choice default selection via `selected: true`; single select honors one default\n  - Add `selected?: boolean` to `Prompt.SelectChoice`\n  - Seed initial selection in `Prompt.multiSelect` from choices marked `selected: true`\n  - Allow `Prompt.select` to honor a single `selected: true` choice and throw an error if multiple defaults are provided\n  - Add tests covering both behaviors\n\n## 0.69.0\n\n### Patch Changes\n\n- Updated dependencies [[`7813640`](https://github.com/Effect-TS/effect/commit/7813640279d9e3a3e7fc0a29bfb5c6d5fb3c270f)]:\n  - @effect/platform@0.90.0\n\n## 0.68.0\n\n### Patch Changes\n\n- Updated dependencies [[`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9), [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104), [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63), [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c), [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989), [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636), [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2), [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d)]:\n  - effect@3.17.0\n  - @effect/platform@0.89.0\n  - @effect/printer@0.45.0\n  - @effect/printer-ansi@0.45.0\n\n## 0.67.1\n\n### Patch Changes\n\n- Updated dependencies [[`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec), [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38), [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48)]:\n  - effect@3.16.14\n  - @effect/platform@0.88.1\n  - @effect/printer@0.44.14\n  - @effect/printer-ansi@0.44.14\n\n## 0.67.0\n\n### Patch Changes\n\n- Updated dependencies [[`27206d7`](https://github.com/Effect-TS/effect/commit/27206d7f0558d7fe28de57bf54f1d0cc83acc92e), [`dbabf5e`](https://github.com/Effect-TS/effect/commit/dbabf5e76fa63b050d2b6c466713c7dc59f07d3c)]:\n  - @effect/platform@0.88.0\n\n## 0.66.13\n\n### Patch Changes\n\n- Updated dependencies [[`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7), [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db)]:\n  - effect@3.16.13\n  - @effect/platform@0.87.13\n  - @effect/printer@0.44.13\n  - @effect/printer-ansi@0.44.13\n\n## 0.66.12\n\n### Patch Changes\n\n- Updated dependencies [[`32ba77a`](https://github.com/Effect-TS/effect/commit/32ba77ae304d2161362a73e8b61965332626cf2d), [`d5e25b2`](https://github.com/Effect-TS/effect/commit/d5e25b237f05670ee42b386cb40b2cb448fc11d7)]:\n  - @effect/platform@0.87.12\n\n## 0.66.11\n\n### Patch Changes\n\n- Updated dependencies [[`001392b`](https://github.com/Effect-TS/effect/commit/001392ba8bfcad101bb034348a7415012fb12f72), [`7bfb099`](https://github.com/Effect-TS/effect/commit/7bfb099cb5528511b8d63045c4fbb4dc9cb18528)]:\n  - @effect/platform@0.87.11\n\n## 0.66.10\n\n### Patch Changes\n\n- Updated dependencies [[`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0), [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0)]:\n  - @effect/platform@0.87.10\n\n## 0.66.9\n\n### Patch Changes\n\n- Updated dependencies [[`54514a2`](https://github.com/Effect-TS/effect/commit/54514a2f53166de27ad7e756dbf12194691fd4af)]:\n  - @effect/platform@0.87.9\n\n## 0.66.8\n\n### Patch Changes\n\n- Updated dependencies [[`4ce4f82`](https://github.com/Effect-TS/effect/commit/4ce4f824f6fdef492be1d35c05a490ffce518c89)]:\n  - @effect/platform@0.87.8\n\n## 0.66.7\n\n### Patch Changes\n\n- Updated dependencies [[`a9b617f`](https://github.com/Effect-TS/effect/commit/a9b617f125171ed76cd79ab46d7a924daf3b0e70), [`7e26e86`](https://github.com/Effect-TS/effect/commit/7e26e86524abcc93713d6ad7eee486638c98f7c2)]:\n  - @effect/platform@0.87.7\n\n## 0.66.6\n\n### Patch Changes\n\n- Updated dependencies [[`905da99`](https://github.com/Effect-TS/effect/commit/905da996aad665057b4ca6dba1a4af44fb8835bd)]:\n  - effect@3.16.12\n  - @effect/platform@0.87.6\n  - @effect/printer@0.44.12\n  - @effect/printer-ansi@0.44.12\n\n## 0.66.5\n\n### Patch Changes\n\n- Updated dependencies [[`2fd8676`](https://github.com/Effect-TS/effect/commit/2fd8676c803cd40000dfc3231f5daecaa0e0ebd2)]:\n  - @effect/platform@0.87.5\n\n## 0.66.4\n\n### Patch Changes\n\n- Updated dependencies [[`e82a4fd`](https://github.com/Effect-TS/effect/commit/e82a4fd60f6528d08cef1a4aba0abe0d3ba741ad)]:\n  - @effect/platform@0.87.4\n\n## 0.66.3\n\n### Patch Changes\n\n- Updated dependencies [[`1b6e396`](https://github.com/Effect-TS/effect/commit/1b6e396d699f3cbbc56b68f99055cf746529bb9e)]:\n  - @effect/platform@0.87.3\n\n## 0.66.2\n\n### Patch Changes\n\n- Updated dependencies [[`4fea68c`](https://github.com/Effect-TS/effect/commit/4fea68ca7a25a3c39a1ab68b3885534513ab0c81), [`b927954`](https://github.com/Effect-TS/effect/commit/b9279543cf5688dd8a577af80456959c615217d0), [`99590a6`](https://github.com/Effect-TS/effect/commit/99590a6ca9128eb1ede265b6670b655311995614), [`6c3e24c`](https://github.com/Effect-TS/effect/commit/6c3e24c2308f7d4a29b8f4270ab81bca22ac6bb4)]:\n  - @effect/platform@0.87.2\n  - effect@3.16.11\n  - @effect/printer@0.44.11\n  - @effect/printer-ansi@0.44.11\n\n## 0.66.1\n\n### Patch Changes\n\n- Updated dependencies [[`faad30e`](https://github.com/Effect-TS/effect/commit/faad30ec8742916be59f9db642d0fc98225b636c)]:\n  - effect@3.16.10\n  - @effect/platform@0.87.1\n  - @effect/printer@0.44.10\n  - @effect/printer-ansi@0.44.10\n\n## 0.66.0\n\n### Patch Changes\n\n- Updated dependencies [[`b5bac9a`](https://github.com/Effect-TS/effect/commit/b5bac9ac2913fcd11b02322624f03b544eef53ba)]:\n  - @effect/platform@0.87.0\n\n## 0.65.0\n\n### Patch Changes\n\n- Updated dependencies [[`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`c23d25c`](https://github.com/Effect-TS/effect/commit/c23d25c3e7c541f1f63b28484d8c461d86c67e99), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07)]:\n  - effect@3.16.9\n  - @effect/platform@0.86.0\n  - @effect/printer@0.44.9\n  - @effect/printer-ansi@0.44.9\n\n## 0.64.2\n\n### Patch Changes\n\n- Updated dependencies [[`914a191`](https://github.com/Effect-TS/effect/commit/914a191e7cb6341a3d0e965bccd27c336cf22e44)]:\n  - @effect/platform@0.85.2\n\n## 0.64.1\n\n### Patch Changes\n\n- Updated dependencies [[`8cb98d5`](https://github.com/Effect-TS/effect/commit/8cb98d53e68330228287ce2a2e0d8a4c86bcab3b), [`db2dd3c`](https://github.com/Effect-TS/effect/commit/db2dd3c3a8a77d791eae19e66153527e1cde4e6e)]:\n  - effect@3.16.8\n  - @effect/platform@0.85.1\n  - @effect/printer@0.44.8\n  - @effect/printer-ansi@0.44.8\n\n## 0.64.0\n\n### Patch Changes\n\n- Updated dependencies [[`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e)]:\n  - @effect/platform@0.85.0\n\n## 0.63.11\n\n### Patch Changes\n\n- Updated dependencies [[`1bb0d8a`](https://github.com/Effect-TS/effect/commit/1bb0d8ab96782e99434356266b38251554ea0294)]:\n  - effect@3.16.7\n  - @effect/platform@0.84.11\n  - @effect/printer@0.44.7\n  - @effect/printer-ansi@0.44.7\n\n## 0.63.10\n\n### Patch Changes\n\n- Updated dependencies [[`a5f7595`](https://github.com/Effect-TS/effect/commit/a5f75956ef9a15a83c416517ef493f0ee2f5ee8a), [`a02470c`](https://github.com/Effect-TS/effect/commit/a02470c75579e91525a25adb3f21b3650d042fdd), [`bf369b2`](https://github.com/Effect-TS/effect/commit/bf369b2902a0e0b195d957c18b9efd180942cf8b), [`f891d45`](https://github.com/Effect-TS/effect/commit/f891d45adffdafd3f94a2eca23faa354e3a409a8)]:\n  - effect@3.16.6\n  - @effect/platform@0.84.10\n  - @effect/printer@0.44.6\n  - @effect/printer-ansi@0.44.6\n\n## 0.63.9\n\n### Patch Changes\n\n- Updated dependencies [[`bf418ef`](https://github.com/Effect-TS/effect/commit/bf418ef14a0f2ec965535793d5cea8fa8ba177ac)]:\n  - effect@3.16.5\n  - @effect/platform@0.84.9\n  - @effect/printer@0.44.5\n  - @effect/printer-ansi@0.44.5\n\n## 0.63.8\n\n### Patch Changes\n\n- Updated dependencies [[`8b9db77`](https://github.com/Effect-TS/effect/commit/8b9db7742846af0f58fd8e8b7acb7f4f5ff487ec)]:\n  - @effect/platform@0.84.8\n\n## 0.63.7\n\n### Patch Changes\n\n- Updated dependencies [[`74ab9a0`](https://github.com/Effect-TS/effect/commit/74ab9a0a9e16d6e019369d256e1e24175c8bc3f3), [`770008e`](https://github.com/Effect-TS/effect/commit/770008eca3aad2899a2ed951236e575793294b28)]:\n  - effect@3.16.4\n  - @effect/platform@0.84.7\n  - @effect/printer@0.44.4\n  - @effect/printer-ansi@0.44.4\n\n## 0.63.6\n\n### Patch Changes\n\n- Updated dependencies [[`ceea77a`](https://github.com/Effect-TS/effect/commit/ceea77a13055f145520f763e3fce5b8ff15d728f)]:\n  - @effect/platform@0.84.6\n\n## 0.63.5\n\n### Patch Changes\n\n- Updated dependencies [[`ec52c6a`](https://github.com/Effect-TS/effect/commit/ec52c6a2211e76972462b15b9d5a9d6d56761b7a)]:\n  - @effect/platform@0.84.5\n\n## 0.63.4\n\n### Patch Changes\n\n- Updated dependencies [[`87722fc`](https://github.com/Effect-TS/effect/commit/87722fce693a9b49284bbddbf82d30714c688261), [`36217ee`](https://github.com/Effect-TS/effect/commit/36217eeb1337edd9ac3f9a635b80a6385d22ae8f)]:\n  - effect@3.16.3\n  - @effect/platform@0.84.4\n  - @effect/printer@0.44.3\n  - @effect/printer-ansi@0.44.3\n\n## 0.63.3\n\n### Patch Changes\n\n- Updated dependencies [[`ab7684f`](https://github.com/Effect-TS/effect/commit/ab7684f1c2a0671bf091f255d220e3a4cc7f528e)]:\n  - @effect/platform@0.84.3\n\n## 0.63.2\n\n### Patch Changes\n\n- Updated dependencies [[`0ddf148`](https://github.com/Effect-TS/effect/commit/0ddf148a247aa87af043d276b8453a714a400897)]:\n  - effect@3.16.2\n  - @effect/platform@0.84.2\n  - @effect/printer@0.44.2\n  - @effect/printer-ansi@0.44.2\n\n## 0.63.1\n\n### Patch Changes\n\n- Updated dependencies [[`71174d0`](https://github.com/Effect-TS/effect/commit/71174d09691314a9b6b66189e456fd21e3eb6543), [`d615e6e`](https://github.com/Effect-TS/effect/commit/d615e6e5b944f6fd5e627e31752c7ca7e4e1c17d)]:\n  - @effect/platform@0.84.1\n  - effect@3.16.1\n  - @effect/printer@0.44.1\n  - @effect/printer-ansi@0.44.1\n\n## 0.63.0\n\n### Patch Changes\n\n- Updated dependencies [[`ee0bd5d`](https://github.com/Effect-TS/effect/commit/ee0bd5d24864752c54cb359f67a67dd903971ec4), [`5189800`](https://github.com/Effect-TS/effect/commit/51898004e11766b8cf6d95e960b636f6d5db79ec), [`58bfeaa`](https://github.com/Effect-TS/effect/commit/58bfeaa64ded8c88f772b184311c0c0dbac10960), [`194d748`](https://github.com/Effect-TS/effect/commit/194d7486943f56f3267ef415395ac220a4b3e634), [`918c9ea`](https://github.com/Effect-TS/effect/commit/918c9ea1a57facb154f0fb26792021f337054dee), [`9198e6f`](https://github.com/Effect-TS/effect/commit/9198e6fcc1a3ff4fefb3363004de558d8de01f40), [`2a370bf`](https://github.com/Effect-TS/effect/commit/2a370bf625fdeede5659721468eb0d527e403279), [`58ccb91`](https://github.com/Effect-TS/effect/commit/58ccb91328c8df5d49808b673738bc09df355201), [`fd47834`](https://github.com/Effect-TS/effect/commit/fd478348203fa89462b0a1d067ce4de034353df4)]:\n  - effect@3.16.0\n  - @effect/platform@0.84.0\n  - @effect/printer@0.44.0\n  - @effect/printer-ansi@0.44.0\n\n## 0.62.0\n\n### Patch Changes\n\n- Updated dependencies [[`5522520`](https://github.com/Effect-TS/effect/commit/55225206ab9af0ad60b1c0654690a8a096d625cd), [`cc5bb2b`](https://github.com/Effect-TS/effect/commit/cc5bb2b918a9450a975f702dabcea891bda382cb)]:\n  - @effect/platform@0.83.0\n  - effect@3.15.5\n  - @effect/printer@0.43.5\n  - @effect/printer-ansi@0.43.5\n\n## 0.61.8\n\n### Patch Changes\n\n- Updated dependencies [[`0617b9d`](https://github.com/Effect-TS/effect/commit/0617b9dc365f1963b36949ad7f9023ab6eb94524)]:\n  - @effect/platform@0.82.8\n\n## 0.61.7\n\n### Patch Changes\n\n- Updated dependencies [[`f570554`](https://github.com/Effect-TS/effect/commit/f57055459524587b041340577dad85476bb35f81), [`78047e8`](https://github.com/Effect-TS/effect/commit/78047e8dfc8005b66f87afe50bb95981fea51561), [`c20b95a`](https://github.com/Effect-TS/effect/commit/c20b95a99ffe452b4774c844d397a905f713b6d6), [`94ada43`](https://github.com/Effect-TS/effect/commit/94ada430928d5685bdbef513e87562c20774a3a2)]:\n  - effect@3.15.4\n  - @effect/platform@0.82.7\n  - @effect/printer@0.43.4\n  - @effect/printer-ansi@0.43.4\n\n## 0.61.6\n\n### Patch Changes\n\n- Updated dependencies [[`618903b`](https://github.com/Effect-TS/effect/commit/618903ba9ae96e2bfe6ee31f61c4359b915f2a36)]:\n  - @effect/platform@0.82.6\n\n## 0.61.5\n\n### Patch Changes\n\n- Updated dependencies [[`7764a07`](https://github.com/Effect-TS/effect/commit/7764a07d960c60df81f14e1dc949518f4bbe494a), [`4577f54`](https://github.com/Effect-TS/effect/commit/4577f548d67273e576cdde423bdd34a4b910766a), [`30a0d9c`](https://github.com/Effect-TS/effect/commit/30a0d9cb51c84290d51b1361d72ff5cee33c13c7)]:\n  - @effect/platform@0.82.5\n  - effect@3.15.3\n  - @effect/printer@0.43.3\n  - @effect/printer-ansi@0.43.3\n\n## 0.61.4\n\n### Patch Changes\n\n- Updated dependencies [[`d45e8a8`](https://github.com/Effect-TS/effect/commit/d45e8a8ac8227192f504e39e6d04fdcf4fb1d225), [`d13b68e`](https://github.com/Effect-TS/effect/commit/d13b68e3a9456d0bfee9bca8273a7b44a9c69087)]:\n  - @effect/platform@0.82.4\n\n## 0.61.3\n\n### Patch Changes\n\n- Updated dependencies [[`b8722b8`](https://github.com/Effect-TS/effect/commit/b8722b817e2306fe8c8245f3f9e32d85b824b961), [`a328f4b`](https://github.com/Effect-TS/effect/commit/a328f4b4fe717dd53e5b04a30f387433c32f7328)]:\n  - effect@3.15.2\n  - @effect/platform@0.82.3\n  - @effect/printer@0.43.2\n  - @effect/printer-ansi@0.43.2\n\n## 0.61.2\n\n### Patch Changes\n\n- Updated dependencies [[`739a3d4`](https://github.com/Effect-TS/effect/commit/739a3d4a4565915fe2e690003f4f9085cb4422fc)]:\n  - @effect/platform@0.82.2\n\n## 0.61.1\n\n### Patch Changes\n\n- Updated dependencies [[`787ce70`](https://github.com/Effect-TS/effect/commit/787ce7042e35b657963473c6efe47752868cd811), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348)]:\n  - effect@3.15.1\n  - @effect/platform@0.82.1\n  - @effect/printer@0.43.1\n  - @effect/printer-ansi@0.43.1\n\n## 0.61.0\n\n### Patch Changes\n\n- Updated dependencies [[`c654595`](https://github.com/Effect-TS/effect/commit/c65459587b51da140b78098e81fdbfece65d53e2), [`d9f5dea`](https://github.com/Effect-TS/effect/commit/d9f5deae0f02f5de2b9fcb1cca8b142ba4bc2bba), [`49aa723`](https://github.com/Effect-TS/effect/commit/49aa7236a15e13f818c86edbca08c4af67c8dfaf), [`74c14d0`](https://github.com/Effect-TS/effect/commit/74c14d01d0cb48cf517a1b6e29a373a96ed0ff5b), [`e4f49b6`](https://github.com/Effect-TS/effect/commit/e4f49b66857e01b74ab6a9a0bc7132f44cd04cbb), [`6f02224`](https://github.com/Effect-TS/effect/commit/6f02224b3fc46a682ad2defb1a260841956c6780), [`1dcfd41`](https://github.com/Effect-TS/effect/commit/1dcfd41ff96abd706901293a00c1893cb29dd8fd), [`b21ab16`](https://github.com/Effect-TS/effect/commit/b21ab16b6f773e7ec4369db4e752c35e719f7870), [`fcf1822`](https://github.com/Effect-TS/effect/commit/fcf1822f98fcda60351d64e9d2c2c13563d7e6db), [`0061dd1`](https://github.com/Effect-TS/effect/commit/0061dd140740165e91569a684cce27a77b23229e), [`8421e6e`](https://github.com/Effect-TS/effect/commit/8421e6e49332bca8f96f482dfd48680e238b3a89), [`a9b3fb7`](https://github.com/Effect-TS/effect/commit/a9b3fb78abcfdb525318a956fd02fcadeb56143e), [`fa10f56`](https://github.com/Effect-TS/effect/commit/fa10f56b96bd9af070ba99ebc3279aa93954261e)]:\n  - effect@3.15.0\n  - @effect/platform@0.82.0\n  - @effect/printer@0.43.0\n  - @effect/printer-ansi@0.43.0\n\n## 0.60.1\n\n### Patch Changes\n\n- Updated dependencies [[`24a9ebb`](https://github.com/Effect-TS/effect/commit/24a9ebbb5af598f0bfd6ecc45307e528043fe011)]:\n  - effect@3.14.22\n  - @effect/platform@0.81.1\n  - @effect/printer@0.42.22\n  - @effect/printer-ansi@0.42.22\n\n## 0.60.0\n\n### Patch Changes\n\n- Updated dependencies [[`672920f`](https://github.com/Effect-TS/effect/commit/672920f85da8abd5f9d4ad85e29248a2aca57ed8)]:\n  - @effect/platform@0.81.0\n\n## 0.59.21\n\n### Patch Changes\n\n- Updated dependencies [[`2f3b7d4`](https://github.com/Effect-TS/effect/commit/2f3b7d4e1fa1ef8790b0ca4da22eb88872ee31df)]:\n  - effect@3.14.21\n  - @effect/platform@0.80.21\n  - @effect/printer@0.42.21\n  - @effect/printer-ansi@0.42.21\n\n## 0.59.20\n\n### Patch Changes\n\n- Updated dependencies [[`17e2f30`](https://github.com/Effect-TS/effect/commit/17e2f3091408cf0fca9414d4af3bdf7b2765b378)]:\n  - effect@3.14.20\n  - @effect/platform@0.80.20\n  - @effect/printer@0.42.20\n  - @effect/printer-ansi@0.42.20\n\n## 0.59.19\n\n### Patch Changes\n\n- Updated dependencies [[`056a910`](https://github.com/Effect-TS/effect/commit/056a910d0a0b8b00b0dc9df4a070466b2b5c2f6c), [`e25e7bb`](https://github.com/Effect-TS/effect/commit/e25e7bbc1797733916f48f501425d9f2ef310d9f), [`3273d57`](https://github.com/Effect-TS/effect/commit/3273d572c2b3175a842677f19efeea4cd65ab016)]:\n  - effect@3.14.19\n  - @effect/platform@0.80.19\n  - @effect/printer@0.42.19\n  - @effect/printer-ansi@0.42.19\n\n## 0.59.18\n\n### Patch Changes\n\n- Updated dependencies [[`b1164d4`](https://github.com/Effect-TS/effect/commit/b1164d49a1dfdf299e9971367b6fc6be4df0ddff)]:\n  - effect@3.14.18\n  - @effect/platform@0.80.18\n  - @effect/printer@0.42.18\n  - @effect/printer-ansi@0.42.18\n\n## 0.59.17\n\n### Patch Changes\n\n- Updated dependencies [[`0b54681`](https://github.com/Effect-TS/effect/commit/0b54681cd89245e211d8f49272be0f1bf2f81813), [`41a59d5`](https://github.com/Effect-TS/effect/commit/41a59d5916a296b12b0d5ead9e859e05f40b4cce)]:\n  - effect@3.14.17\n  - @effect/platform@0.80.17\n  - @effect/printer@0.42.17\n  - @effect/printer-ansi@0.42.17\n\n## 0.59.16\n\n### Patch Changes\n\n- Updated dependencies [[`ee14444`](https://github.com/Effect-TS/effect/commit/ee144441021ec77039e43396eaf90714687bb495), [`f1c8583`](https://github.com/Effect-TS/effect/commit/f1c8583f8c3ea9415f813795ca2940a897c9ba9a)]:\n  - effect@3.14.16\n  - @effect/platform@0.80.16\n  - @effect/printer@0.42.16\n  - @effect/printer-ansi@0.42.16\n\n## 0.59.15\n\n### Patch Changes\n\n- Updated dependencies [[`239cc99`](https://github.com/Effect-TS/effect/commit/239cc995ce645946210a3c3d2cb52bd3547c0687), [`8b6c947`](https://github.com/Effect-TS/effect/commit/8b6c947eaa8e45a67ecb3c37d45cd27f3e41d165), [`c50a63b`](https://github.com/Effect-TS/effect/commit/c50a63bbecb9f560b9cae349c447eed877d1b9b6)]:\n  - effect@3.14.15\n  - @effect/platform@0.80.15\n  - @effect/printer@0.42.15\n  - @effect/printer-ansi@0.42.15\n\n## 0.59.14\n\n### Patch Changes\n\n- Updated dependencies [[`6ed8d15`](https://github.com/Effect-TS/effect/commit/6ed8d1589beb181d30abc79afebdaabc1d101538)]:\n  - effect@3.14.14\n  - @effect/platform@0.80.14\n  - @effect/printer@0.42.14\n  - @effect/printer-ansi@0.42.14\n\n## 0.59.13\n\n### Patch Changes\n\n- Updated dependencies [[`ee77788`](https://github.com/Effect-TS/effect/commit/ee77788747e7ebbde6bfa88256cde49dbbad3608), [`5fce6ba`](https://github.com/Effect-TS/effect/commit/5fce6ba19c3cc63cc0104e737e581ad989dedbf0), [`570e45f`](https://github.com/Effect-TS/effect/commit/570e45f8cb936e42ec48f67f21bb2b7252f36c0c)]:\n  - effect@3.14.13\n  - @effect/platform@0.80.13\n  - @effect/printer@0.42.13\n  - @effect/printer-ansi@0.42.13\n\n## 0.59.12\n\n### Patch Changes\n\n- Updated dependencies [[`c2ad9ee`](https://github.com/Effect-TS/effect/commit/c2ad9ee9f3c4c743390edf35ed9e85a20be33811), [`9c68654`](https://github.com/Effect-TS/effect/commit/9c686542b6eb3ea188cb70673ef2e41223633e89)]:\n  - effect@3.14.12\n  - @effect/platform@0.80.12\n  - @effect/printer@0.42.12\n  - @effect/printer-ansi@0.42.12\n\n## 0.59.11\n\n### Patch Changes\n\n- Updated dependencies [[`e536127`](https://github.com/Effect-TS/effect/commit/e536127c1e6f2fb3a542c73ae919435a629a346b)]:\n  - effect@3.14.11\n  - @effect/platform@0.80.11\n  - @effect/printer@0.42.11\n  - @effect/printer-ansi@0.42.11\n\n## 0.59.10\n\n### Patch Changes\n\n- Updated dependencies [[`bc7efa3`](https://github.com/Effect-TS/effect/commit/bc7efa3b031bb25e1ed3c8f2d3fb5e8da166cadc)]:\n  - effect@3.14.10\n  - @effect/platform@0.80.10\n  - @effect/printer@0.42.10\n  - @effect/printer-ansi@0.42.10\n\n## 0.59.9\n\n### Patch Changes\n\n- Updated dependencies [[`d78249f`](https://github.com/Effect-TS/effect/commit/d78249f0b67f63cf4baf806ff090cba33293daf0)]:\n  - effect@3.14.9\n  - @effect/platform@0.80.9\n  - @effect/printer@0.42.9\n  - @effect/printer-ansi@0.42.9\n\n## 0.59.8\n\n### Patch Changes\n\n- Updated dependencies [[`b3a2d32`](https://github.com/Effect-TS/effect/commit/b3a2d32772e6f7f20eacf2e18128e99324c4d378)]:\n  - effect@3.14.8\n  - @effect/platform@0.80.8\n  - @effect/printer@0.42.8\n  - @effect/printer-ansi@0.42.8\n\n## 0.59.7\n\n### Patch Changes\n\n- Updated dependencies [[`b542a4b`](https://github.com/Effect-TS/effect/commit/b542a4bf195be0c9af1523e1ba96c953decc4d25)]:\n  - effect@3.14.7\n  - @effect/platform@0.80.7\n  - @effect/printer@0.42.7\n  - @effect/printer-ansi@0.42.7\n\n## 0.59.6\n\n### Patch Changes\n\n- Updated dependencies [[`47618c1`](https://github.com/Effect-TS/effect/commit/47618c1ad84ebcc5a51133a3fff5aa5012d49d45), [`6077882`](https://github.com/Effect-TS/effect/commit/60778824a4794336c33807801f813f8751d1c7e4)]:\n  - effect@3.14.6\n  - @effect/platform@0.80.6\n  - @effect/printer@0.42.6\n  - @effect/printer-ansi@0.42.6\n\n## 0.59.5\n\n### Patch Changes\n\n- Updated dependencies [[`40dbfef`](https://github.com/Effect-TS/effect/commit/40dbfeff239b6e567706752114f31b2fce7de4e3), [`85fba81`](https://github.com/Effect-TS/effect/commit/85fba815ac07eb13d4227a69ac76a18e4b94df18), [`5a5ebdd`](https://github.com/Effect-TS/effect/commit/5a5ebdddfaddd259538b4599a6676281faca778e)]:\n  - effect@3.14.5\n  - @effect/platform@0.80.5\n  - @effect/printer@0.42.5\n  - @effect/printer-ansi@0.42.5\n\n## 0.59.4\n\n### Patch Changes\n\n- Updated dependencies [[`e4ba2c6`](https://github.com/Effect-TS/effect/commit/e4ba2c66a878e81b5e295d6d49aaf724b80a28ef)]:\n  - effect@3.14.4\n  - @effect/platform@0.80.4\n  - @effect/printer@0.42.4\n  - @effect/printer-ansi@0.42.4\n\n## 0.59.3\n\n### Patch Changes\n\n- Updated dependencies [[`37aa8e1`](https://github.com/Effect-TS/effect/commit/37aa8e137725a902e70cd1e468ea98b873aa5056), [`34f03d6`](https://github.com/Effect-TS/effect/commit/34f03d66875f21f266f102223a03cd14c2ed6ea6)]:\n  - effect@3.14.3\n  - @effect/platform@0.80.3\n  - @effect/printer@0.42.3\n  - @effect/printer-ansi@0.42.3\n\n## 0.59.2\n\n### Patch Changes\n\n- Updated dependencies [[`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`0a3e3e1`](https://github.com/Effect-TS/effect/commit/0a3e3e18eea5e0d1882f1a6c906198e6ef226a41)]:\n  - effect@3.14.2\n  - @effect/platform@0.80.2\n  - @effect/printer@0.42.2\n  - @effect/printer-ansi@0.42.2\n\n## 0.59.1\n\n### Patch Changes\n\n- Updated dependencies [[`4a274fe`](https://github.com/Effect-TS/effect/commit/4a274fe9f623182b6b902827e0e83bd89ca3b05c)]:\n  - effect@3.14.1\n  - @effect/platform@0.80.1\n  - @effect/printer@0.42.1\n  - @effect/printer-ansi@0.42.1\n\n## 0.59.0\n\n### Patch Changes\n\n- Updated dependencies [[`1f47e4e`](https://github.com/Effect-TS/effect/commit/1f47e4e12546ab691b29bfb7b5128bb17b93baa5), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`3131f8f`](https://github.com/Effect-TS/effect/commit/3131f8fd12ba9eb31b90fa2f42bf88b12309133c), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`04dff2d`](https://github.com/Effect-TS/effect/commit/04dff2d01ac68c260f29a6d4743381825c353c86), [`c7fac0c`](https://github.com/Effect-TS/effect/commit/c7fac0cd7eadcd5cc0c3a987051c5b57ad271638), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`ffaa3f3`](https://github.com/Effect-TS/effect/commit/ffaa3f3969df26610fcc02ad537340641d44e803), [`ab957c1`](https://github.com/Effect-TS/effect/commit/ab957c1fee714868f56c7ab4e802b9d449e9b666), [`35db9ce`](https://github.com/Effect-TS/effect/commit/35db9ce228f1416c8abacc6dc9c36fbd0f33ef0f), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`cf77ea9`](https://github.com/Effect-TS/effect/commit/cf77ea9ab4fc89e66a43f682a9926ccdee6c57ed), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`baaab60`](https://github.com/Effect-TS/effect/commit/baaab60b737f35dfab8e4a21bce28a195d19e899)]:\n  - effect@3.14.0\n  - @effect/platform@0.80.0\n  - @effect/printer@0.42.0\n  - @effect/printer-ansi@0.42.0\n\n## 0.58.4\n\n### Patch Changes\n\n- Updated dependencies [[`5662363`](https://github.com/Effect-TS/effect/commit/566236361e270e575ef1cbf308ad1967c82a362c), [`5f1fd15`](https://github.com/Effect-TS/effect/commit/5f1fd15308ab154791580059b89877d19a2055c2), [`8bb1460`](https://github.com/Effect-TS/effect/commit/8bb1460c824f66f0f25ebd899c5e74e388089c37)]:\n  - @effect/platform@0.79.4\n\n## 0.58.3\n\n### Patch Changes\n\n- Updated dependencies [[`0c4803f`](https://github.com/Effect-TS/effect/commit/0c4803fcc69262d11a97ce49d0e9b4288df0651f), [`6f65ac4`](https://github.com/Effect-TS/effect/commit/6f65ac4eac1489cd6ea390e18b0908670722adad)]:\n  - effect@3.13.12\n  - @effect/platform@0.79.3\n  - @effect/printer@0.41.12\n  - @effect/printer-ansi@0.41.12\n\n## 0.58.2\n\n### Patch Changes\n\n- Updated dependencies [[`fad8cca`](https://github.com/Effect-TS/effect/commit/fad8cca9bbfcc2eaeb44b97c15dbe0a1eda75315), [`4296293`](https://github.com/Effect-TS/effect/commit/4296293049414d0cf2d915a26c552b09f946b9a0), [`9c241ab`](https://github.com/Effect-TS/effect/commit/9c241abe47ccf7a5257b98a4a64a63054a12741d), [`082b0c1`](https://github.com/Effect-TS/effect/commit/082b0c1b9f4252bcdd69608f2e4a9226f953ac3f), [`be12983`](https://github.com/Effect-TS/effect/commit/be12983bc7e7537b41cd8910fc4eb7d1da56ab07), [`de88127`](https://github.com/Effect-TS/effect/commit/de88127a5a5906ccece98af74787b5ae0e65e431)]:\n  - effect@3.13.11\n  - @effect/platform@0.79.2\n  - @effect/printer@0.41.11\n  - @effect/printer-ansi@0.41.11\n\n## 0.58.1\n\n### Patch Changes\n\n- Updated dependencies [[`527c964`](https://github.com/Effect-TS/effect/commit/527c9645229f5be9714a7e60a38a9e753c4bbfb1)]:\n  - effect@3.13.10\n  - @effect/platform@0.79.1\n  - @effect/printer@0.41.10\n  - @effect/printer-ansi@0.41.10\n\n## 0.58.0\n\n### Patch Changes\n\n- Updated dependencies [[`88fe129`](https://github.com/Effect-TS/effect/commit/88fe12923740765c0335a6e6203fdcc6a463edca), [`d630249`](https://github.com/Effect-TS/effect/commit/d630249426113088abe8b382db4f14d80f2160c2), [`2976e52`](https://github.com/Effect-TS/effect/commit/2976e52538d9dc9ffdcbc84d4ac748cff9305971)]:\n  - @effect/platform@0.79.0\n  - effect@3.13.9\n  - @effect/printer@0.41.9\n  - @effect/printer-ansi@0.41.9\n\n## 0.57.1\n\n### Patch Changes\n\n- Updated dependencies [[`c65d336`](https://github.com/Effect-TS/effect/commit/c65d3362d07ec815ff3b46278314e8a31706ddc2), [`22d2ebb`](https://github.com/Effect-TS/effect/commit/22d2ebb4b11f5a44351a4736e65da391a3b647d0)]:\n  - effect@3.13.8\n  - @effect/platform@0.78.1\n  - @effect/printer@0.41.8\n  - @effect/printer-ansi@0.41.8\n\n## 0.57.0\n\n### Patch Changes\n\n- Updated dependencies [[`c5bcf53`](https://github.com/Effect-TS/effect/commit/c5bcf53b7cb49dacffdd2a6cd8eb48cc452b417e)]:\n  - @effect/platform@0.78.0\n\n## 0.56.7\n\n### Patch Changes\n\n- Updated dependencies [[`840cc73`](https://github.com/Effect-TS/effect/commit/840cc7329908db7ca693ef47b07d4f845c29cadd), [`9bf8a74`](https://github.com/Effect-TS/effect/commit/9bf8a74b967f18d931743dd5196af326c9118e9c), [`87ba23c`](https://github.com/Effect-TS/effect/commit/87ba23c41c193503ed0c612b0d32d0b253794c64), [`f910880`](https://github.com/Effect-TS/effect/commit/f91088069057f3b4529753f5bc5532b028d726df), [`0d01480`](https://github.com/Effect-TS/effect/commit/0d014803e4f688f74386a80abd65485e1a319244)]:\n  - @effect/platform@0.77.7\n  - effect@3.13.7\n  - @effect/printer@0.41.7\n  - @effect/printer-ansi@0.41.7\n\n## 0.56.6\n\n### Patch Changes\n\n- Updated dependencies [[`3154ce4`](https://github.com/Effect-TS/effect/commit/3154ce4692fa18b804982158d3c4c8a8a5fae386)]:\n  - effect@3.13.6\n  - @effect/platform@0.77.6\n  - @effect/printer@0.41.6\n  - @effect/printer-ansi@0.41.6\n\n## 0.56.5\n\n### Patch Changes\n\n- Updated dependencies [[`367bb35`](https://github.com/Effect-TS/effect/commit/367bb35f4c2a254e1fb211d96db2474a7aed9020), [`6cf11c3`](https://github.com/Effect-TS/effect/commit/6cf11c3a75773ceec2877c85ddc760f381f0866d), [`a0acec8`](https://github.com/Effect-TS/effect/commit/a0acec851f72e19466363d24b9cc218acd00006a)]:\n  - effect@3.13.5\n  - @effect/platform@0.77.5\n  - @effect/printer@0.41.5\n  - @effect/printer-ansi@0.41.5\n\n## 0.56.4\n\n### Patch Changes\n\n- Updated dependencies [[`e0746f9`](https://github.com/Effect-TS/effect/commit/e0746f9aa398b69c6542e375910683bf17f49f46), [`17d9e89`](https://github.com/Effect-TS/effect/commit/17d9e89f9851663bdbb6c1e685601d97806114a4)]:\n  - @effect/platform@0.77.4\n  - effect@3.13.4\n  - @effect/printer@0.41.4\n  - @effect/printer-ansi@0.41.4\n\n## 0.56.3\n\n### Patch Changes\n\n- Updated dependencies [[`cc5588d`](https://github.com/Effect-TS/effect/commit/cc5588df07f9103513547cb429ce041b9436a8bd), [`623c8cd`](https://github.com/Effect-TS/effect/commit/623c8cd053ed6ee3d353aaa8778d484670fca2bb), [`00b4eb1`](https://github.com/Effect-TS/effect/commit/00b4eb1ece12a16e222e6220965bb4024d6752ac), [`f2aee98`](https://github.com/Effect-TS/effect/commit/f2aee989b0a600900ce83e7f460d02908620c80f), [`fb798eb`](https://github.com/Effect-TS/effect/commit/fb798eb9061f1191badc017d1aa649360254da20), [`2251b15`](https://github.com/Effect-TS/effect/commit/2251b1528810bb695b37ce388b653cec0c5bf80c), [`2e15c1e`](https://github.com/Effect-TS/effect/commit/2e15c1e33648add0b29fe274fbcb7294b7515085), [`a4979db`](https://github.com/Effect-TS/effect/commit/a4979db021aef16e731be64df196b72088fc4376), [`b74255a`](https://github.com/Effect-TS/effect/commit/b74255a304ad49d60bedb1a260fd697f370af27a), [`d7f6a5c`](https://github.com/Effect-TS/effect/commit/d7f6a5c7d26c1963dcd864ca62360d20d08c7b49), [`9dd8979`](https://github.com/Effect-TS/effect/commit/9dd8979e940915b1cc1b1f264f3d019c77a65a02), [`477b488`](https://github.com/Effect-TS/effect/commit/477b488284f47c5469d7fba3e4065fb7e3b6556e), [`10932cb`](https://github.com/Effect-TS/effect/commit/10932cbf58fc721ada631cebec42f773ce96d3cc), [`9f6c784`](https://github.com/Effect-TS/effect/commit/9f6c78468b3b5e9ebfc38ffdfb70702901ee977b), [`2c639ec`](https://github.com/Effect-TS/effect/commit/2c639ecee332de4266e36022c989c35ae4e02105), [`886aaa8`](https://github.com/Effect-TS/effect/commit/886aaa81e06dfd3cd9391e8ea987d8cd5ada1124)]:\n  - effect@3.13.3\n  - @effect/platform@0.77.3\n  - @effect/printer@0.41.3\n  - @effect/printer-ansi@0.41.3\n\n## 0.56.2\n\n### Patch Changes\n\n- Updated dependencies [[`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f), [`3e7ce97`](https://github.com/Effect-TS/effect/commit/3e7ce97f8a41756a039cf635d0b3d9a75d781097), [`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f)]:\n  - effect@3.13.2\n  - @effect/platform@0.77.2\n  - @effect/printer@0.41.2\n  - @effect/printer-ansi@0.41.2\n\n## 0.56.1\n\n### Patch Changes\n\n- Updated dependencies [[`b56a211`](https://github.com/Effect-TS/effect/commit/b56a2110569fd0ec0b57ac137743e926d49f51cc)]:\n  - effect@3.13.1\n  - @effect/platform@0.77.1\n  - @effect/printer@0.41.1\n  - @effect/printer-ansi@0.41.1\n\n## 0.56.0\n\n### Patch Changes\n\n- Updated dependencies [[`8baef83`](https://github.com/Effect-TS/effect/commit/8baef83e7ff0b7bc0738b680e1ef013065386cff), [`655bfe2`](https://github.com/Effect-TS/effect/commit/655bfe29e44cc3f0fb9b4e53038f50b891c188df), [`d90cbc2`](https://github.com/Effect-TS/effect/commit/d90cbc274e2742d18671fe65aa4764c057eb6cba), [`75632bd`](https://github.com/Effect-TS/effect/commit/75632bd44b8025101d652ccbaeef898c7086c91c), [`c874a2e`](https://github.com/Effect-TS/effect/commit/c874a2e4b17e9d71904ca8375bb77b020975cb1d), [`bf865e5`](https://github.com/Effect-TS/effect/commit/bf865e5833f77fd8f6c06944ca9d507b54488301), [`f98b2b7`](https://github.com/Effect-TS/effect/commit/f98b2b7592cf20f9d85313e7f1e964cb65878138), [`de8ce92`](https://github.com/Effect-TS/effect/commit/de8ce924923eaa4e1b761a97eb45ec967389f3d5), [`cf8b2dd`](https://github.com/Effect-TS/effect/commit/cf8b2dd112f8e092ed99d78fd728db0f91c29050), [`db426a5`](https://github.com/Effect-TS/effect/commit/db426a5fb41ab84d18e3c8753a7329b4de544245), [`6862444`](https://github.com/Effect-TS/effect/commit/6862444094906ad4f2cb077ff3b9cc0b73880c8c), [`5fc8a90`](https://github.com/Effect-TS/effect/commit/5fc8a90ba46a5fd9f3b643f0b5aeadc69d717339), [`546a492`](https://github.com/Effect-TS/effect/commit/546a492e60eb2b8b048a489a474b934ea0877005), [`65c4796`](https://github.com/Effect-TS/effect/commit/65c47966ce39055f02cf5c808daabb3ea6442b0b), [`9760fdc`](https://github.com/Effect-TS/effect/commit/9760fdc37bdaef9da8b150e46b86ddfbe2ad9221), [`5b471e7`](https://github.com/Effect-TS/effect/commit/5b471e7d4317e8ee5d72bbbd3e0c9775160949ab), [`4f810cc`](https://github.com/Effect-TS/effect/commit/4f810cc2770e9f1f266851d2cb6257112c12af49)]:\n  - effect@3.13.0\n  - @effect/platform@0.77.0\n  - @effect/printer@0.41.0\n  - @effect/printer-ansi@0.41.0\n\n## 0.55.1\n\n### Patch Changes\n\n- Updated dependencies [[`4018eae`](https://github.com/Effect-TS/effect/commit/4018eaed2733241676ddb8c52416f463a8c32e35), [`543d36d`](https://github.com/Effect-TS/effect/commit/543d36d1a11452560b01ab966a82529ad5fee8c9), [`c407726`](https://github.com/Effect-TS/effect/commit/c407726f79df4a567a9631cddd8effaa16b3535d), [`f70a65a`](https://github.com/Effect-TS/effect/commit/f70a65ac80c6635d80b12beaf4d32a9cc59fa143), [`ba409f6`](https://github.com/Effect-TS/effect/commit/ba409f69c41aeaa29e475c0630735726eaf4dbac), [`3d2e356`](https://github.com/Effect-TS/effect/commit/3d2e3565e8a43d1bdb5daee8db3b90f56d71d859)]:\n  - effect@3.12.12\n  - @effect/platform@0.76.1\n  - @effect/printer@0.40.12\n  - @effect/printer-ansi@0.40.12\n\n## 0.55.0\n\n### Patch Changes\n\n- Updated dependencies [[`b6a032f`](https://github.com/Effect-TS/effect/commit/b6a032f07bffa020a848c813881879395134fa20), [`42ddd5f`](https://github.com/Effect-TS/effect/commit/42ddd5f144ce9f9d94a036679ebbd626446d37f5), [`2fe447c`](https://github.com/Effect-TS/effect/commit/2fe447c6354d334f9c591b8a8481818f5f0e797e), [`2473ad5`](https://github.com/Effect-TS/effect/commit/2473ad5cf23582e3a41338091fa526ffe611288d)]:\n  - effect@3.12.11\n  - @effect/platform@0.76.0\n  - @effect/printer@0.40.11\n  - @effect/printer-ansi@0.40.11\n\n## 0.54.4\n\n### Patch Changes\n\n- [#4402](https://github.com/Effect-TS/effect/pull/4402) [`3e56745`](https://github.com/Effect-TS/effect/commit/3e56745421e3ad7186cf3e6772c691c49be5c71a) Thanks @Delusion2056! - Fix CLI help output to correctly display default values\n\n- Updated dependencies [[`e30f132`](https://github.com/Effect-TS/effect/commit/e30f132c336c9d0760bad39f82a55c7ce5159eb7), [`33fa667`](https://github.com/Effect-TS/effect/commit/33fa667c2623be1026e1ccee91bd44f73b09020a), [`87f5f28`](https://github.com/Effect-TS/effect/commit/87f5f2842e4196cb88d13f10f443ff0567e82832), [`7d57ecd`](https://github.com/Effect-TS/effect/commit/7d57ecdaf5da2345ebbf9c22df50317578bde0f5), [`4dbd170`](https://github.com/Effect-TS/effect/commit/4dbd170538e8fb7a36aa7c469c6f93b6c7000091)]:\n  - effect@3.12.10\n  - @effect/platform@0.75.4\n  - @effect/printer@0.40.10\n  - @effect/printer-ansi@0.40.10\n\n## 0.54.3\n\n### Patch Changes\n\n- Updated dependencies [[`1b4a4e9`](https://github.com/Effect-TS/effect/commit/1b4a4e904ef5227ec7d9114d4e417eca19eed940)]:\n  - effect@3.12.9\n  - @effect/platform@0.75.3\n  - @effect/printer@0.40.9\n  - @effect/printer-ansi@0.40.9\n\n## 0.54.2\n\n### Patch Changes\n\n- [#4380](https://github.com/Effect-TS/effect/pull/4380) [`c45b559`](https://github.com/Effect-TS/effect/commit/c45b5592b5fd1189a5c932cfe05bd7d5f6d68508) Thanks @fubhy! - Fixed module imports\n\n- Updated dependencies [[`59b3cfb`](https://github.com/Effect-TS/effect/commit/59b3cfbbd5713dd9475998e95fad5534c0b21466), [`766113c`](https://github.com/Effect-TS/effect/commit/766113c0ea3512cdb887650ead8ba314236e22ee), [`bb05fb8`](https://github.com/Effect-TS/effect/commit/bb05fb83457355b1ca567228a9e041edfb6fd85d), [`712277f`](https://github.com/Effect-TS/effect/commit/712277f949052a24b46e4aa234063a6abf395c90), [`f269122`](https://github.com/Effect-TS/effect/commit/f269122508693b111142994dd48698ddc75f3d69), [`8f6006a`](https://github.com/Effect-TS/effect/commit/8f6006a610fb6d6c7b8d14209a7323338a8964ff), [`c45b559`](https://github.com/Effect-TS/effect/commit/c45b5592b5fd1189a5c932cfe05bd7d5f6d68508), [`430c846`](https://github.com/Effect-TS/effect/commit/430c846cbac05b187e3d24ac8dfee0cf22506f7c), [`7b03057`](https://github.com/Effect-TS/effect/commit/7b03057507d2dab5e6793beb9c578dedaaeb15fe), [`a9c94c8`](https://github.com/Effect-TS/effect/commit/a9c94c807755610831211a686d2fad849ab38eb4), [`107e6f0`](https://github.com/Effect-TS/effect/commit/107e6f0557a1e2d3b0dce25d62fa1e2601521752), [`c9175ae`](https://github.com/Effect-TS/effect/commit/c9175aef41cb1e3b689d0ac0a4f53d8107376b58), [`65c11b9`](https://github.com/Effect-TS/effect/commit/65c11b9266ec9447c31c26fe3ed35c73bd3b81fd), [`e386d2f`](https://github.com/Effect-TS/effect/commit/e386d2f1b3ab3ac2c14ee76de11f5963d32a3df4), [`9172efb`](https://github.com/Effect-TS/effect/commit/9172efba98bc6a82353e6ec2af61ac08f038ba64)]:\n  - @effect/platform@0.75.2\n  - effect@3.12.8\n  - @effect/printer@0.40.8\n  - @effect/printer-ansi@0.40.8\n\n## 0.54.1\n\n### Patch Changes\n\n- Updated dependencies [[`8dff1d1`](https://github.com/Effect-TS/effect/commit/8dff1d1bff76cdba643cad7f0bf864300f08bc61)]:\n  - effect@3.12.7\n  - @effect/platform@0.75.1\n  - @effect/printer@0.40.7\n  - @effect/printer-ansi@0.40.7\n\n## 0.54.0\n\n### Patch Changes\n\n- Updated dependencies [[`5e43ce5`](https://github.com/Effect-TS/effect/commit/5e43ce50bae116865906112e7f88d390739d778b), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`76eb7d0`](https://github.com/Effect-TS/effect/commit/76eb7d0fbce3c009c8f77e84c178cb15bbed9709), [`8b4e75d`](https://github.com/Effect-TS/effect/commit/8b4e75d35daea807c447ca760948a717aa66bb52), [`fc5e0f0`](https://github.com/Effect-TS/effect/commit/fc5e0f0d357a0051cfa01c1ede83ffdd3cb41ab1), [`004fd2b`](https://github.com/Effect-TS/effect/commit/004fd2bbd1459e64fb1b57f02eeb791ca5ea1ea5), [`b2a31be`](https://github.com/Effect-TS/effect/commit/b2a31be85c35d891351ce4f9a2cc93ece0c257f6), [`5514d05`](https://github.com/Effect-TS/effect/commit/5514d05b5cd586ff5868b8bd41c959e95e6c33cd), [`bf5f0ae`](https://github.com/Effect-TS/effect/commit/bf5f0ae9daa0170471678e22585e8ec14ce667bb), [`3b19bcf`](https://github.com/Effect-TS/effect/commit/3b19bcfd3aaadb6c9253428622df524537c8e626), [`b064b3b`](https://github.com/Effect-TS/effect/commit/b064b3b293615fd268cc5a5647d0981eb67750b8), [`eb264ed`](https://github.com/Effect-TS/effect/commit/eb264ed8a6e8c92a9dc7006f766c6ca2e5d29e03), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`f474678`](https://github.com/Effect-TS/effect/commit/f474678bf10b8f1c80e3dc096ddc7ecf20b2b23e), [`ee187d0`](https://github.com/Effect-TS/effect/commit/ee187d098007a402844c94d04f0cd8f07695377a)]:\n  - @effect/platform@0.75.0\n  - effect@3.12.6\n  - @effect/printer@0.40.6\n  - @effect/printer-ansi@0.40.6\n\n## 0.53.0\n\n### Patch Changes\n\n- [#4275](https://github.com/Effect-TS/effect/pull/4275) [`8645754`](https://github.com/Effect-TS/effect/commit/86457544ed6c144c6de938400f8c5a3fe7369c8f) Thanks @IMax153! - Ensure `ConfigError` is surfaced by the CLI when a fallback `Config` fails to parse\n\n- Updated dependencies [[`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8653072`](https://github.com/Effect-TS/effect/commit/86530720d7a03e118d2c5a8bf5a997cee7e7f3d6), [`507d546`](https://github.com/Effect-TS/effect/commit/507d546bd49db31000425fb5da88c434e4291bea), [`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8db239b`](https://github.com/Effect-TS/effect/commit/8db239b9c869a3707f6566b9d9dbdf53c4df03fc), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`3179a9f`](https://github.com/Effect-TS/effect/commit/3179a9f65d23369a6a9a1f80f7750566dd28df22), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e), [`1fcbe55`](https://github.com/Effect-TS/effect/commit/1fcbe55345042d8468f6a98c84081bd00b6bcf5a), [`d9a63d9`](https://github.com/Effect-TS/effect/commit/d9a63d9d385653865954cac895065360d54cc56b), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e)]:\n  - effect@3.12.5\n  - @effect/platform@0.74.0\n  - @effect/printer@0.40.5\n  - @effect/printer-ansi@0.40.5\n\n## 0.52.1\n\n### Patch Changes\n\n- Updated dependencies [[`5b50ea4`](https://github.com/Effect-TS/effect/commit/5b50ea4a10cf9acd51f9624b2474d9d5ded74019), [`c170a68`](https://github.com/Effect-TS/effect/commit/c170a68b6266100774461fcd6c0e0fabb60112f2), [`a66c2eb`](https://github.com/Effect-TS/effect/commit/a66c2eb473245092cd41f04c2eb2b7b02cf53718), [`c9e5e1b`](https://github.com/Effect-TS/effect/commit/c9e5e1be17c0c84d3d4e2abc3c60215cdb56bbbe), [`7b3d58d`](https://github.com/Effect-TS/effect/commit/7b3d58d7aec2152ec282460871d3e9de45ed254d)]:\n  - effect@3.12.4\n  - @effect/platform@0.73.1\n  - @effect/printer@0.40.4\n  - @effect/printer-ansi@0.40.4\n\n## 0.52.0\n\n### Patch Changes\n\n- Updated dependencies [[`d7dac48`](https://github.com/Effect-TS/effect/commit/d7dac48a477cdfeec509dbe9f33fce6a1b02b63d), [`c110032`](https://github.com/Effect-TS/effect/commit/c110032322450a8824ba38ae24335a538cd2ce9a), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`23ac740`](https://github.com/Effect-TS/effect/commit/23ac740c7dd4610b7d265c2071b88b0968419e9a), [`8cd7319`](https://github.com/Effect-TS/effect/commit/8cd7319b6568bfc7a30ca16c104d189e37eac3a0)]:\n  - effect@3.12.3\n  - @effect/platform@0.73.0\n  - @effect/printer@0.40.3\n  - @effect/printer-ansi@0.40.3\n\n## 0.51.2\n\n### Patch Changes\n\n- Updated dependencies [[`734af82`](https://github.com/Effect-TS/effect/commit/734af82138e78b9c57a8355b1c6b80e80d38b222), [`b63c780`](https://github.com/Effect-TS/effect/commit/b63c78010893101520448ddda7019c487cf7eedd), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`f852cb0`](https://github.com/Effect-TS/effect/commit/f852cb02040ea2f165e9b449615b8b1366add5d5), [`7276ae2`](https://github.com/Effect-TS/effect/commit/7276ae21062896adbb7508ac5b2dece95316322f), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`c640d77`](https://github.com/Effect-TS/effect/commit/c640d77b33ad417876f4e8ffe8574ee6cbe5607f), [`0def088`](https://github.com/Effect-TS/effect/commit/0def0887cfdb6755729a64dfd52b3b9f46b0576c)]:\n  - effect@3.12.2\n  - @effect/platform@0.72.2\n  - @effect/printer@0.40.2\n  - @effect/printer-ansi@0.40.2\n\n## 0.51.1\n\n### Patch Changes\n\n- Updated dependencies [[`302b57d`](https://github.com/Effect-TS/effect/commit/302b57d2cbf9b9ccc17450945aeebfb33cfe8d43), [`0988083`](https://github.com/Effect-TS/effect/commit/0988083d4594938590df5a287e5b27d38526dd07), [`8b46be6`](https://github.com/Effect-TS/effect/commit/8b46be6a3b8160362ab5ea9171c5e6932505125c), [`bfe8027`](https://github.com/Effect-TS/effect/commit/bfe802734b450a4b4ee069d1125dd37995db2bff), [`16dd657`](https://github.com/Effect-TS/effect/commit/16dd657033d8afac2ffea567b3c8bb27c9b249b6), [`39db211`](https://github.com/Effect-TS/effect/commit/39db211414e90c8db8fdad7dc8ce5b4661bcfaef)]:\n  - effect@3.12.1\n  - @effect/platform@0.72.1\n  - @effect/printer@0.40.1\n  - @effect/printer-ansi@0.40.1\n\n## 0.51.0\n\n### Patch Changes\n\n- Updated dependencies [[`abb22a4`](https://github.com/Effect-TS/effect/commit/abb22a429b9c52c31e84856294f175d2064a9b4d), [`f369a89`](https://github.com/Effect-TS/effect/commit/f369a89e98bc682969803b9304adaf4557bb36c2), [`642376c`](https://github.com/Effect-TS/effect/commit/642376c63fd7d78754db991631a4d50a5dc79aa3), [`3d2b7a7`](https://github.com/Effect-TS/effect/commit/3d2b7a7e942a7157afae5b1cdbc6f3fef116428e), [`ef64c6f`](https://github.com/Effect-TS/effect/commit/ef64c6fec0d47da573c04230dde9ea729366d871), [`73f9c6f`](https://github.com/Effect-TS/effect/commit/73f9c6f2ff091512cf904cc54ab59965b86e87c8), [`17cb451`](https://github.com/Effect-TS/effect/commit/17cb4514590e8a86263f7aed009f24da8a237342), [`d801820`](https://github.com/Effect-TS/effect/commit/d80182060c2ee945d7e0e4728812abf9465a0d6a), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1), [`c11f3a6`](https://github.com/Effect-TS/effect/commit/c11f3a60a05c3b5fc8e7ce90136728154dc505b0), [`618f7e0`](https://github.com/Effect-TS/effect/commit/618f7e092a1011e5090dca1e69b5e9285689654b), [`c0ba834`](https://github.com/Effect-TS/effect/commit/c0ba834d1995cf5a8b250e4780fd43f3e3881151), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1)]:\n  - effect@3.12.0\n  - @effect/platform@0.72.0\n  - @effect/printer@0.40.0\n  - @effect/printer-ansi@0.40.0\n\n## 0.50.7\n\n### Patch Changes\n\n- Updated dependencies [[`39457d4`](https://github.com/Effect-TS/effect/commit/39457d4897d9bc7df8af5c05d352866bbeae82eb), [`a475cc2`](https://github.com/Effect-TS/effect/commit/a475cc25fd7c9f26b27a8e98f8fbe43cc9e6ee3e), [`199214e`](https://github.com/Effect-TS/effect/commit/199214e21c616d8a0ccd7ed5f92e944e6c580193), [`b3c160d`](https://github.com/Effect-TS/effect/commit/b3c160d7a1fdfc2d3fb2440530f1ab80efc65133)]:\n  - effect@3.11.10\n  - @effect/platform@0.71.7\n  - @effect/printer@0.39.10\n  - @effect/printer-ansi@0.39.10\n\n## 0.50.6\n\n### Patch Changes\n\n- Updated dependencies [[`1c08a0b`](https://github.com/Effect-TS/effect/commit/1c08a0b8505badcffb4d9cade5a746ea90c9557e), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd)]:\n  - effect@3.11.9\n  - @effect/platform@0.71.6\n  - @effect/printer@0.39.9\n  - @effect/printer-ansi@0.39.9\n\n## 0.50.5\n\n### Patch Changes\n\n- Updated dependencies [[`05d71f8`](https://github.com/Effect-TS/effect/commit/05d71f85622305705d8316817694a09762e60865), [`e66b920`](https://github.com/Effect-TS/effect/commit/e66b9205f25ab425d30640886eb3fb2c4715bc26)]:\n  - @effect/platform@0.71.5\n\n## 0.50.4\n\n### Patch Changes\n\n- Updated dependencies [[`909181a`](https://github.com/Effect-TS/effect/commit/909181a9ce9052a80432ccf52187e0723004bf7f), [`909181a`](https://github.com/Effect-TS/effect/commit/909181a9ce9052a80432ccf52187e0723004bf7f), [`1a6b52d`](https://github.com/Effect-TS/effect/commit/1a6b52dcf020d36e38a7bc90b648152cf5a8ccba)]:\n  - @effect/platform@0.71.4\n  - effect@3.11.8\n  - @effect/printer@0.39.8\n  - @effect/printer-ansi@0.39.8\n\n## 0.50.3\n\n### Patch Changes\n\n- Updated dependencies [[`6984508`](https://github.com/Effect-TS/effect/commit/6984508c87f1bd91213b44c19b25ab5e2dcc1ce0), [`883639c`](https://github.com/Effect-TS/effect/commit/883639cc8ce47757f1cd39439391a8028c0812fe)]:\n  - @effect/platform@0.71.3\n\n## 0.50.2\n\n### Patch Changes\n\n- Updated dependencies [[`2408616`](https://github.com/Effect-TS/effect/commit/24086163b60b09cc6d0885bd565ef080dcbe866b), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`8d978c5`](https://github.com/Effect-TS/effect/commit/8d978c53f6fcc98d9d645ecba3e4b55d4297dd36), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e)]:\n  - effect@3.11.7\n  - @effect/platform@0.71.2\n  - @effect/printer@0.39.7\n  - @effect/printer-ansi@0.39.7\n\n## 0.50.1\n\n### Patch Changes\n\n- Updated dependencies [[`1d3df5b`](https://github.com/Effect-TS/effect/commit/1d3df5bc4324e88a392c348db35fd9d029c7b25e)]:\n  - @effect/platform@0.71.1\n\n## 0.50.0\n\n### Patch Changes\n\n- Updated dependencies [[`662d1ce`](https://github.com/Effect-TS/effect/commit/662d1ce6fb7da384a95888d5b2bb5605bdf3208d), [`c99a0f3`](https://github.com/Effect-TS/effect/commit/c99a0f376d049d3793ed33e146d9873b8a5e5b78), [`11fc401`](https://github.com/Effect-TS/effect/commit/11fc401f436f99bf4be95f56d50b0e4bdfe5edea), [`c99a0f3`](https://github.com/Effect-TS/effect/commit/c99a0f376d049d3793ed33e146d9873b8a5e5b78), [`31c62d8`](https://github.com/Effect-TS/effect/commit/31c62d83cbdcf9850a8b5331faa239601c60f78a)]:\n  - effect@3.11.6\n  - @effect/platform@0.71.0\n  - @effect/printer@0.39.6\n  - @effect/printer-ansi@0.39.6\n\n## 0.49.7\n\n### Patch Changes\n\n- Updated dependencies [[`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`22905cf`](https://github.com/Effect-TS/effect/commit/22905cf5addfb1ff3d2a6135c52036be958ae911), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`1e59e4f`](https://github.com/Effect-TS/effect/commit/1e59e4fd778da18296812a2a32f36ca8ae50f60d), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`8d914e5`](https://github.com/Effect-TS/effect/commit/8d914e504e7a22d0ea628e8af265ee450ff9530f), [`03bb00f`](https://github.com/Effect-TS/effect/commit/03bb00faa74f9e168a54a8cc0828a664fbb1ab05), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`14e1149`](https://github.com/Effect-TS/effect/commit/14e1149f1af5a022f06eb8c2e4ba9fec17fe7426), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8)]:\n  - effect@3.11.5\n  - @effect/platform@0.70.7\n  - @effect/printer@0.39.5\n  - @effect/printer-ansi@0.39.5\n\n## 0.49.6\n\n### Patch Changes\n\n- Updated dependencies [[`9a5b8e3`](https://github.com/Effect-TS/effect/commit/9a5b8e36d184bd4967a88752cb6e755e1be263af)]:\n  - @effect/platform@0.70.6\n\n## 0.49.5\n\n### Patch Changes\n\n- Updated dependencies [[`415f4c9`](https://github.com/Effect-TS/effect/commit/415f4c98321868531727a83cbaad70164f5e4c40), [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f), [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f)]:\n  - @effect/platform@0.70.5\n  - effect@3.11.4\n  - @effect/printer@0.39.4\n  - @effect/printer-ansi@0.39.4\n\n## 0.49.4\n\n### Patch Changes\n\n- Updated dependencies [[`90906f7`](https://github.com/Effect-TS/effect/commit/90906f7f154b12c7182e8f39e3c55ef3937db857), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`343b6aa`](https://github.com/Effect-TS/effect/commit/343b6aa6ac4a74276bfc7c63ccbf4a1d72bc1bed), [`afba339`](https://github.com/Effect-TS/effect/commit/afba339adc11dad56b5a3b7ca94487e58f34d613)]:\n  - effect@3.11.3\n  - @effect/platform@0.70.4\n  - @effect/printer@0.39.3\n  - @effect/printer-ansi@0.39.3\n\n## 0.49.3\n\n### Patch Changes\n\n- Updated dependencies [[`7044730`](https://github.com/Effect-TS/effect/commit/70447306be1aeeb7d87c230b2a96ec87b993ede9)]:\n  - @effect/platform@0.70.3\n\n## 0.49.2\n\n### Patch Changes\n\n- Updated dependencies [[`01cee56`](https://github.com/Effect-TS/effect/commit/01cee560b58d94b24cc20e98083251b73e658b41), [`c2249ea`](https://github.com/Effect-TS/effect/commit/c2249ea13fd98ab7d9aa628787931356d8ec2860), [`1358aa5`](https://github.com/Effect-TS/effect/commit/1358aa5326eaa85ef13ee8d1fed0b4a4288ed3eb), [`1de3fe7`](https://github.com/Effect-TS/effect/commit/1de3fe7d1cbafd6391eaa38c2300b99e332cc2aa)]:\n  - effect@3.11.2\n  - @effect/platform@0.70.2\n  - @effect/printer@0.39.2\n  - @effect/printer-ansi@0.39.2\n\n## 0.49.1\n\n### Patch Changes\n\n- Updated dependencies [[`dd8a2d8`](https://github.com/Effect-TS/effect/commit/dd8a2d8e80d33b16719fc69361eaedf0b59d4620), [`a71bfef`](https://github.com/Effect-TS/effect/commit/a71bfef46f5061bb2502a61a333638a987b62273)]:\n  - effect@3.11.1\n  - @effect/platform@0.70.1\n  - @effect/printer@0.39.1\n  - @effect/printer-ansi@0.39.1\n\n## 0.49.0\n\n### Patch Changes\n\n- Updated dependencies [[`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`6e69493`](https://github.com/Effect-TS/effect/commit/6e694930048bbaf98110f35f41566aeb9752d471), [`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`5eff3f6`](https://github.com/Effect-TS/effect/commit/5eff3f6fa3aae7e86948a62cbfd63b8d6c3bdf92), [`d9fe79b`](https://github.com/Effect-TS/effect/commit/d9fe79bb5a3fe105d8e7a3bc2922a8ad936a5d10), [`251d189`](https://github.com/Effect-TS/effect/commit/251d189420bbba71990574e91098c499065f9a9b), [`5a259f3`](https://github.com/Effect-TS/effect/commit/5a259f3711b4369f55d885b568bdb21136155261), [`b4ce4ea`](https://github.com/Effect-TS/effect/commit/b4ce4ea7fd514a7e572f2dcd879c98f334981b0e), [`15fcc5a`](https://github.com/Effect-TS/effect/commit/15fcc5a0ea4bbf40ab48fa6a04fdda74f76f4c07), [`9bc9a47`](https://github.com/Effect-TS/effect/commit/9bc9a476800dc645903c888a68bb1d3baa3383c6), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb), [`1e2747c`](https://github.com/Effect-TS/effect/commit/1e2747c63a4820d1459cbbc88c71212983bd68bd), [`9264162`](https://github.com/Effect-TS/effect/commit/9264162a82783a651776fb7b87604564a63e7070), [`e0b9b09`](https://github.com/Effect-TS/effect/commit/e0b9b09e70c386b2da17d1f0a15b0511861c89e8), [`c36f3b9`](https://github.com/Effect-TS/effect/commit/c36f3b95df5ce9d71b66f22f26ce12eda8d3e848), [`672bde5`](https://github.com/Effect-TS/effect/commit/672bde5bec51c7d6f9862828e6a654cb2cb6f93d), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb)]:\n  - effect@3.11.0\n  - @effect/platform@0.70.0\n  - @effect/printer@0.39.0\n  - @effect/printer-ansi@0.39.0\n\n## 0.48.32\n\n### Patch Changes\n\n- Updated dependencies [[`3069614`](https://github.com/Effect-TS/effect/commit/30696149271129fc618f6f2ccd1d8f2f6c0f9cd7), [`09a5e52`](https://github.com/Effect-TS/effect/commit/09a5e522fd9b221f05d85b1d1c8a740d4973c302)]:\n  - effect@3.10.20\n  - @effect/platform@0.69.32\n  - @effect/printer@0.38.20\n  - @effect/printer-ansi@0.38.20\n\n## 0.48.31\n\n### Patch Changes\n\n- Updated dependencies [[`e6d4a37`](https://github.com/Effect-TS/effect/commit/e6d4a37c1d7e657b5ea44063a1cf586808228fe5)]:\n  - @effect/platform@0.69.31\n\n## 0.48.30\n\n### Patch Changes\n\n- Updated dependencies [[`270f199`](https://github.com/Effect-TS/effect/commit/270f199b31810fd643e4c22818698adcbdb5d396)]:\n  - @effect/platform@0.69.30\n\n## 0.48.29\n\n### Patch Changes\n\n- Updated dependencies [[`24cc35e`](https://github.com/Effect-TS/effect/commit/24cc35e26d6ed4a076470bc687ffd99cc50991b3)]:\n  - @effect/platform@0.69.29\n\n## 0.48.28\n\n### Patch Changes\n\n- [#4007](https://github.com/Effect-TS/effect/pull/4007) [`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1) Thanks @gcanti! - Wrap JSDoc @example tags with a TypeScript fence, closes #4002\n\n- Updated dependencies [[`edd72be`](https://github.com/Effect-TS/effect/commit/edd72be57b904d60c9cbffc2537901821a9da537), [`a3e2771`](https://github.com/Effect-TS/effect/commit/a3e277170a1f7cf61fd629acb60304c7e81d9498), [`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1), [`54addee`](https://github.com/Effect-TS/effect/commit/54addee438a644bf010646c52042c7b89c5fc0a7), [`a9e00e4`](https://github.com/Effect-TS/effect/commit/a9e00e43f0b5dd22c1f9d5b78be6383daea09c20)]:\n  - @effect/platform@0.69.28\n  - @effect/printer@0.38.19\n  - effect@3.10.19\n  - @effect/printer-ansi@0.38.19\n\n## 0.48.27\n\n### Patch Changes\n\n- Updated dependencies [[`af409cf`](https://github.com/Effect-TS/effect/commit/af409cf1d2ff973be11cc079ea373eaeedca25de), [`beaccae`](https://github.com/Effect-TS/effect/commit/beaccae2d15931e9fe475fb50a0b3638243fe3f7)]:\n  - effect@3.10.18\n  - @effect/platform@0.69.27\n  - @effect/printer@0.38.18\n  - @effect/printer-ansi@0.38.18\n\n## 0.48.26\n\n### Patch Changes\n\n- [#3992](https://github.com/Effect-TS/effect/pull/3992) [`a1cf616`](https://github.com/Effect-TS/effect/commit/a1cf6167687dab5070bc944c2fef48269275014e) Thanks @IMax153! - fix multi-select prompt not displaying choice description\n\n- Updated dependencies [[`c963886`](https://github.com/Effect-TS/effect/commit/c963886d5817986fcbd6bfa4ddf50aca8b6c8184), [`42c4ce6`](https://github.com/Effect-TS/effect/commit/42c4ce6f8d8c7d847e97757650a8ad9419a829d7)]:\n  - @effect/platform@0.69.26\n  - effect@3.10.17\n  - @effect/printer@0.38.17\n  - @effect/printer-ansi@0.38.17\n\n## 0.48.25\n\n### Patch Changes\n\n- [#3929](https://github.com/Effect-TS/effect/pull/3929) [`71f7d4e`](https://github.com/Effect-TS/effect/commit/71f7d4ecb944dbc50b9a5d1491b2e34075faec1b) Thanks @joepjoosten! - added prompt multi select\n\n- [#3976](https://github.com/Effect-TS/effect/pull/3976) [`a36a250`](https://github.com/Effect-TS/effect/commit/a36a25069fbf47d30046df1deef8468dfb9db7a8) Thanks @IMax153! - Ensure that command-line arguments are parsed correctly for prompt-based commands\n\n- Updated dependencies [[`320557a`](https://github.com/Effect-TS/effect/commit/320557ab18d13c5e22fc7dc0d2a157eae461012f), [`4dca30c`](https://github.com/Effect-TS/effect/commit/4dca30cfcdafe4542e236489f71d6f171a5b4e38), [`1d99867`](https://github.com/Effect-TS/effect/commit/1d998671be3cd11043f232822e91dd8c98fccfa9), [`6dae414`](https://github.com/Effect-TS/effect/commit/6dae4147991a97ec14a99289bd25fadae7541e8d), [`6b0d737`](https://github.com/Effect-TS/effect/commit/6b0d737078bf63b97891e6bc47affc04b28f9cf7), [`d8356aa`](https://github.com/Effect-TS/effect/commit/d8356aad428a0c2290db52380220f81d9ec94232), [`7b93dd6`](https://github.com/Effect-TS/effect/commit/7b93dd622e2ab79c7072d79d0d9611e446202201)]:\n  - @effect/platform@0.69.25\n  - effect@3.10.16\n  - @effect/printer@0.38.16\n  - @effect/printer-ansi@0.38.16\n\n## 0.48.24\n\n### Patch Changes\n\n- Updated dependencies [[`3cc6514`](https://github.com/Effect-TS/effect/commit/3cc6514d2dd64e010cb760cc29bfce98c349bb10)]:\n  - @effect/platform@0.69.24\n\n## 0.48.23\n\n### Patch Changes\n\n- Updated dependencies [[`3aff4d3`](https://github.com/Effect-TS/effect/commit/3aff4d38837c213bb2987973dc4b98febb9f92d2)]:\n  - @effect/platform@0.69.23\n\n## 0.48.22\n\n### Patch Changes\n\n- Updated dependencies [[`8398b32`](https://github.com/Effect-TS/effect/commit/8398b3208242a88239d4449910b7baf923cfe3b6), [`72e55b7`](https://github.com/Effect-TS/effect/commit/72e55b7c610784fcebdbadc592c876e23e76a986)]:\n  - effect@3.10.15\n  - @effect/platform@0.69.22\n  - @effect/printer@0.38.15\n  - @effect/printer-ansi@0.38.15\n\n## 0.48.21\n\n### Patch Changes\n\n- Updated dependencies [[`f983946`](https://github.com/Effect-TS/effect/commit/f9839467b4cad6e788297764ef9f9f0b9fd203f9), [`2d8a750`](https://github.com/Effect-TS/effect/commit/2d8a75081eb83a0a81f817fdf6f428369c5064ab)]:\n  - effect@3.10.14\n  - @effect/platform@0.69.21\n  - @effect/printer@0.38.14\n  - @effect/printer-ansi@0.38.14\n\n## 0.48.20\n\n### Patch Changes\n\n- Updated dependencies [[`995bbdf`](https://github.com/Effect-TS/effect/commit/995bbdffea2e332f203cd5b474cd6a1c77dfa6ae)]:\n  - effect@3.10.13\n  - @effect/platform@0.69.20\n  - @effect/printer@0.38.13\n  - @effect/printer-ansi@0.38.13\n\n## 0.48.19\n\n### Patch Changes\n\n- Updated dependencies [[`eb8c52d`](https://github.com/Effect-TS/effect/commit/eb8c52d8b4c5e067ebf0a81eb742f5822e6439b5)]:\n  - @effect/platform@0.69.19\n\n## 0.48.18\n\n### Patch Changes\n\n- Updated dependencies [[`a0584ec`](https://github.com/Effect-TS/effect/commit/a0584ece92ed784bfb139e9c5a699f02d1e71c2d), [`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6), [`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6)]:\n  - @effect/platform@0.69.18\n  - effect@3.10.12\n  - @effect/printer@0.38.12\n  - @effect/printer-ansi@0.38.12\n\n## 0.48.17\n\n### Patch Changes\n\n- Updated dependencies [[`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a), [`8240b1c`](https://github.com/Effect-TS/effect/commit/8240b1c10d45312fc863cb679b1a1e8441af0c1a), [`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a)]:\n  - effect@3.10.11\n  - @effect/platform@0.69.17\n  - @effect/printer@0.38.11\n  - @effect/printer-ansi@0.38.11\n\n## 0.48.16\n\n### Patch Changes\n\n- Updated dependencies [[`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`b631f40`](https://github.com/Effect-TS/effect/commit/b631f40abbe649b2a089764585b5c39f6a695ac6), [`7d89650`](https://github.com/Effect-TS/effect/commit/7d8965036cd2ea435c8441ffec3345488baebf85)]:\n  - effect@3.10.10\n  - @effect/platform@0.69.16\n  - @effect/printer@0.38.10\n  - @effect/printer-ansi@0.38.10\n\n## 0.48.15\n\n### Patch Changes\n\n- Updated dependencies [[`8a30e1d`](https://github.com/Effect-TS/effect/commit/8a30e1dfa3a7103bf5414fc6a7fca3088d8c8c00)]:\n  - @effect/platform@0.69.15\n\n## 0.48.14\n\n### Patch Changes\n\n- Updated dependencies [[`a123e80`](https://github.com/Effect-TS/effect/commit/a123e80f111a625428a5b5622b7f55ee1073566b), [`bd5fcd3`](https://github.com/Effect-TS/effect/commit/bd5fcd3e6b603b1e505af90d6a00627c8eca6d41), [`0289d3b`](https://github.com/Effect-TS/effect/commit/0289d3b6391031d00329365bab9791b355031fe3), [`7386b71`](https://github.com/Effect-TS/effect/commit/7386b710e5be570e17f468928a6ed19d549a3e12), [`07c493a`](https://github.com/Effect-TS/effect/commit/07c493a598e096c7810cd06def8cfa43493c46b1), [`257ab1b`](https://github.com/Effect-TS/effect/commit/257ab1b539fa6e930b7ae2583a188376372200d7), [`4211a23`](https://github.com/Effect-TS/effect/commit/4211a2355bb3af3f0e756e2aae9d293379f25662)]:\n  - effect@3.10.9\n  - @effect/platform@0.69.14\n  - @effect/printer@0.38.9\n  - @effect/printer-ansi@0.38.9\n\n## 0.48.13\n\n### Patch Changes\n\n- Updated dependencies [[`68b5c9e`](https://github.com/Effect-TS/effect/commit/68b5c9e44f34192cef26e1cadda5e661a027df41), [`9c9928d`](https://github.com/Effect-TS/effect/commit/9c9928dfeacd9ac33dc37eb0ca3d7d8c39175ada), [`6306e66`](https://github.com/Effect-TS/effect/commit/6306e6656092b350d4ede5746da6f245ec9f7e07), [`361c7f3`](https://github.com/Effect-TS/effect/commit/361c7f39a2c10ede9324847c3d3ba192a6f9b20a)]:\n  - effect@3.10.8\n  - @effect/platform@0.69.13\n  - @effect/printer@0.38.8\n  - @effect/printer-ansi@0.38.8\n\n## 0.48.12\n\n### Patch Changes\n\n- Updated dependencies [[`33f5b9f`](https://github.com/Effect-TS/effect/commit/33f5b9ffaebea4f1bd0e391b44c41fb6230e743a), [`50f0281`](https://github.com/Effect-TS/effect/commit/50f0281b0d2116726b8927a6217622d5f394f3e4)]:\n  - effect@3.10.7\n  - @effect/platform@0.69.12\n  - @effect/printer@0.38.7\n  - @effect/printer-ansi@0.38.7\n\n## 0.48.11\n\n### Patch Changes\n\n- Updated dependencies [[`ce1c21f`](https://github.com/Effect-TS/effect/commit/ce1c21ffc11902ac9ab453a51904207859d38552), [`81ddd45`](https://github.com/Effect-TS/effect/commit/81ddd45fc074b98206fafab416d9a5a28b31e07a)]:\n  - effect@3.10.6\n  - @effect/platform@0.69.11\n  - @effect/printer@0.38.6\n  - @effect/printer-ansi@0.38.6\n\n## 0.48.10\n\n### Patch Changes\n\n- Updated dependencies [[`3a6d757`](https://github.com/Effect-TS/effect/commit/3a6d757badeebe00d8ef4d67530d073c8264dcfa), [`59d813a`](https://github.com/Effect-TS/effect/commit/59d813aa4973d1115cfc70cc3667508335f49693)]:\n  - effect@3.10.5\n  - @effect/platform@0.69.10\n  - @effect/printer@0.38.5\n  - @effect/printer-ansi@0.38.5\n\n## 0.48.9\n\n### Patch Changes\n\n- Updated dependencies [[`2367708`](https://github.com/Effect-TS/effect/commit/2367708be449f9526a2047e321302d7bfb16f18e)]:\n  - @effect/platform@0.69.9\n  - effect@3.10.4\n  - @effect/printer@0.38.4\n  - @effect/printer-ansi@0.38.4\n\n## 0.48.8\n\n### Patch Changes\n\n- Updated dependencies [[`522f7c5`](https://github.com/Effect-TS/effect/commit/522f7c518a5acfb55ef96d6796869f002cc3eaf8)]:\n  - @effect/platform@0.69.8\n\n## 0.48.7\n\n### Patch Changes\n\n- Updated dependencies [[`690d6c5`](https://github.com/Effect-TS/effect/commit/690d6c54d2145adb0af545c447db7d4755bf3c6b), [`b9423d8`](https://github.com/Effect-TS/effect/commit/b9423d8bf8181a2389fdbce1e3c14ac6fe8d54f5), [`279fe3a`](https://github.com/Effect-TS/effect/commit/279fe3a7168fe84e520c2cc88ba189a15f03a2bc)]:\n  - @effect/platform@0.69.7\n  - effect@3.10.3\n  - @effect/printer@0.38.3\n  - @effect/printer-ansi@0.38.3\n\n## 0.48.6\n\n### Patch Changes\n\n- Updated dependencies [[`714e119`](https://github.com/Effect-TS/effect/commit/714e11945e45e5a2554ee058e6c43f82a8e309cf), [`c1afd55`](https://github.com/Effect-TS/effect/commit/c1afd55c54e61f9c432823d21b3d016f79160a37), [`42cd72a`](https://github.com/Effect-TS/effect/commit/42cd72a44ca9593e4d81fbb50e8111625fd0fb81)]:\n  - effect@3.10.2\n  - @effect/platform@0.69.6\n  - @effect/printer@0.38.2\n  - @effect/printer-ansi@0.38.2\n\n## 0.48.5\n\n### Patch Changes\n\n- Updated dependencies [[`9604d6b`](https://github.com/Effect-TS/effect/commit/9604d6b616435103dafea8b53637a9d1450b4750)]:\n  - effect@3.10.1\n  - @effect/platform@0.69.5\n  - @effect/printer@0.38.1\n  - @effect/printer-ansi@0.38.1\n\n## 0.48.4\n\n### Patch Changes\n\n- Updated dependencies [[`c86b1d7`](https://github.com/Effect-TS/effect/commit/c86b1d7cd47b66df190ef9775a475467c1abdbd6)]:\n  - @effect/platform@0.69.4\n\n## 0.48.3\n\n### Patch Changes\n\n- [#3773](https://github.com/Effect-TS/effect/pull/3773) [`a619704`](https://github.com/Effect-TS/effect/commit/a619704fd4bdaf0dc948e32601577983e355c0fe) Thanks @joepjoosten! - Repeated options can now be parsed independend of the order of the arguments\n\n- Updated dependencies [[`d5fba63`](https://github.com/Effect-TS/effect/commit/d5fba6391e1005e374aa0238f13edfbd65848313), [`1eb2c30`](https://github.com/Effect-TS/effect/commit/1eb2c30ba064398db5790e376dedcfad55b7b005), [`02d413e`](https://github.com/Effect-TS/effect/commit/02d413e7b6bc1c64885969c37cc3e4e690c94d7d)]:\n  - @effect/platform@0.69.3\n\n## 0.48.2\n\n### Patch Changes\n\n- Updated dependencies [[`e7afc47`](https://github.com/Effect-TS/effect/commit/e7afc47ce83e381c3f4aed2b2974e3b3d86a2340)]:\n  - @effect/platform@0.69.2\n\n## 0.48.1\n\n### Patch Changes\n\n- Updated dependencies [[`7564f56`](https://github.com/Effect-TS/effect/commit/7564f56bb2844cf39d2b0d2d9e93cf9b2205e9a8), [`7564f56`](https://github.com/Effect-TS/effect/commit/7564f56bb2844cf39d2b0d2d9e93cf9b2205e9a8)]:\n  - @effect/platform@0.69.1\n\n## 0.48.0\n\n### Patch Changes\n\n- Updated dependencies [[`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`6d9de6b`](https://github.com/Effect-TS/effect/commit/6d9de6b871c5c08e6509a4e830c3d74758faa198), [`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`c79c4c1`](https://github.com/Effect-TS/effect/commit/c79c4c178390fe61ff6dda88c9e058862349343a), [`38d30f0`](https://github.com/Effect-TS/effect/commit/38d30f08b8da62f9c3e308b9250738cb8d17bdb5), [`5821ce3`](https://github.com/Effect-TS/effect/commit/5821ce3455b47d25e0a40cae6ce22af9db5fa556)]:\n  - effect@3.10.0\n  - @effect/platform@0.69.0\n  - @effect/printer@0.38.0\n  - @effect/printer-ansi@0.38.0\n\n## 0.47.6\n\n### Patch Changes\n\n- Updated dependencies [[`382556f`](https://github.com/Effect-TS/effect/commit/382556f8930780c0634de681077706113a8c8239), [`97cb014`](https://github.com/Effect-TS/effect/commit/97cb0145114b2cd2f378e98f6c4ff5bf2c1865f5)]:\n  - @effect/schema@0.75.5\n  - @effect/platform@0.68.6\n\n## 0.47.5\n\n### Patch Changes\n\n- Updated dependencies [[`2036402`](https://github.com/Effect-TS/effect/commit/20364020b8b75a684791aa93d90626758023e9e9)]:\n  - @effect/platform@0.68.5\n\n## 0.47.4\n\n### Patch Changes\n\n- Updated dependencies [[`1b1ef29`](https://github.com/Effect-TS/effect/commit/1b1ef29ae302322f69dc938f9337aa97b4c63266)]:\n  - @effect/platform@0.68.4\n\n## 0.47.3\n\n### Patch Changes\n\n- Updated dependencies [[`61a99b2`](https://github.com/Effect-TS/effect/commit/61a99b2bf9d757870ef0c2ec9d4c877cdd364a3d), [`8c33087`](https://github.com/Effect-TS/effect/commit/8c330879425e80bed2f65e407cd59e991f0d7bec)]:\n  - effect@3.9.2\n  - @effect/platform@0.68.3\n  - @effect/printer@0.37.2\n  - @effect/printer-ansi@0.37.2\n  - @effect/schema@0.75.4\n\n## 0.47.2\n\n### Patch Changes\n\n- Updated dependencies [[`360ec14`](https://github.com/Effect-TS/effect/commit/360ec14dd4102c526aef7433a8881ad4d9beab75)]:\n  - @effect/schema@0.75.3\n  - @effect/platform@0.68.2\n\n## 0.47.1\n\n### Patch Changes\n\n- Updated dependencies [[`b75ac5d`](https://github.com/Effect-TS/effect/commit/b75ac5d0909115507bedc90f18f2d34deb217769)]:\n  - @effect/platform@0.68.1\n\n## 0.47.0\n\n### Patch Changes\n\n- Updated dependencies [[`f02b354`](https://github.com/Effect-TS/effect/commit/f02b354ab5b0451143b82bb73dc866be29adec85), [`90ceeab`](https://github.com/Effect-TS/effect/commit/90ceeab3a04051b740af18c8af8bd73ee8ec6363), [`90ceeab`](https://github.com/Effect-TS/effect/commit/90ceeab3a04051b740af18c8af8bd73ee8ec6363), [`90ceeab`](https://github.com/Effect-TS/effect/commit/90ceeab3a04051b740af18c8af8bd73ee8ec6363)]:\n  - @effect/schema@0.75.2\n  - @effect/platform@0.68.0\n\n## 0.46.1\n\n### Patch Changes\n\n- Updated dependencies [[`3b2ad1d`](https://github.com/Effect-TS/effect/commit/3b2ad1d58a2e33dc1a72b7037396bd25ca1702a9)]:\n  - @effect/platform@0.67.1\n  - effect@3.9.1\n  - @effect/schema@0.75.1\n  - @effect/printer@0.37.1\n  - @effect/printer-ansi@0.37.1\n\n## 0.46.0\n\n### Patch Changes\n\n- Updated dependencies [[`ff3d1aa`](https://github.com/Effect-TS/effect/commit/ff3d1aab290b4d1173b2dfc7e4c76abb4babdc16), [`0ba66f2`](https://github.com/Effect-TS/effect/commit/0ba66f2451641fd6990e02ec1ed01c014db9dab0), [`bf77f51`](https://github.com/Effect-TS/effect/commit/bf77f51b323c383224ebf08adf77a7a6e8c9b3cd), [`016f9ad`](https://github.com/Effect-TS/effect/commit/016f9ad931a4b3d09a34e5caf13d87c5b8e9c984), [`0779681`](https://github.com/Effect-TS/effect/commit/07796813f07de035719728733096ba64ce333469), [`534129f`](https://github.com/Effect-TS/effect/commit/534129f8113ce1a8ec50828083e16da9c86326c6), [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda), [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03), [`9237ac6`](https://github.com/Effect-TS/effect/commit/9237ac69bc07de5b3b60076a0ad2921c21de7457), [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03), [`5b36494`](https://github.com/Effect-TS/effect/commit/5b364942e9a9003fdb8217324f8a2d8369c969da), [`c716adb`](https://github.com/Effect-TS/effect/commit/c716adb250ebbea1d1048d818ef7fed4f621d186), [`4986391`](https://github.com/Effect-TS/effect/commit/49863919cd8628c962a712fb1df30d2983820933), [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda), [`d1387ae`](https://github.com/Effect-TS/effect/commit/d1387aebd1ff01bbebde26be46d488956e4daef6)]:\n  - effect@3.9.0\n  - @effect/platform@0.67.0\n  - @effect/schema@0.75.0\n  - @effect/printer@0.37.0\n  - @effect/printer-ansi@0.37.0\n\n## 0.45.3\n\n### Patch Changes\n\n- Updated dependencies [[`88e85db`](https://github.com/Effect-TS/effect/commit/88e85db34bd402526e27a323e950d053fa34d232), [`f40da15`](https://github.com/Effect-TS/effect/commit/f40da15fbeb7c491840b8f409d47de79720891c3), [`8e94585`](https://github.com/Effect-TS/effect/commit/8e94585abe62753bf3af28bfae77926a7c570ac3), [`83887ca`](https://github.com/Effect-TS/effect/commit/83887ca1b1793916913d8550a4db4450cd14a044), [`5266b6c`](https://github.com/Effect-TS/effect/commit/5266b6cd86d76c3886da041c8829bca04b1a3110), [`cdead5c`](https://github.com/Effect-TS/effect/commit/cdead5c9cfd54dc6c4f215d9732f654c4a12e991), [`f40da15`](https://github.com/Effect-TS/effect/commit/f40da15fbeb7c491840b8f409d47de79720891c3), [`766a8af`](https://github.com/Effect-TS/effect/commit/766a8af307b414aca3648d91c4eab7493a5ec862)]:\n  - effect@3.8.5\n  - @effect/platform@0.66.3\n  - @effect/printer@0.36.5\n  - @effect/printer-ansi@0.36.5\n  - @effect/schema@0.74.2\n\n## 0.45.2\n\n### Patch Changes\n\n- Updated dependencies [[`734eae6`](https://github.com/Effect-TS/effect/commit/734eae654f215e4adca457d04d2a1728b1a55c83), [`fd83d0e`](https://github.com/Effect-TS/effect/commit/fd83d0e548feff9ea2d53d370a0b626c4a1d940e), [`4509656`](https://github.com/Effect-TS/effect/commit/45096569d50262275ee984f44c456f5c83b62683), [`ad7e1de`](https://github.com/Effect-TS/effect/commit/ad7e1de948745c0751bfdac96671028ff4b7a727), [`090e41c`](https://github.com/Effect-TS/effect/commit/090e41c636d720b1c7d89684a739855765ed4382), [`090e41c`](https://github.com/Effect-TS/effect/commit/090e41c636d720b1c7d89684a739855765ed4382)]:\n  - @effect/schema@0.74.1\n  - @effect/platform@0.66.2\n  - effect@3.8.4\n  - @effect/printer@0.36.4\n  - @effect/printer-ansi@0.36.4\n\n## 0.45.1\n\n### Patch Changes\n\n- Updated dependencies [[`3812788`](https://github.com/Effect-TS/effect/commit/3812788d79caaab8f559a62fd443018a04ac5647)]:\n  - @effect/platform@0.66.1\n\n## 0.45.0\n\n### Patch Changes\n\n- Updated dependencies [[`de48aa5`](https://github.com/Effect-TS/effect/commit/de48aa54e98d97722a8a4c2c8f9e1fe1d4560ea2)]:\n  - @effect/schema@0.74.0\n  - @effect/platform@0.66.0\n\n## 0.44.5\n\n### Patch Changes\n\n- Updated dependencies [[`321b201`](https://github.com/Effect-TS/effect/commit/321b201adcb6bbbeb806b3467dd0b4cf063ccda8), [`bb5ec6b`](https://github.com/Effect-TS/effect/commit/bb5ec6b4b6a6f537394596c5a596faf52cb2aef4)]:\n  - @effect/platform@0.65.5\n  - effect@3.8.3\n  - @effect/printer@0.36.3\n  - @effect/printer-ansi@0.36.3\n  - @effect/schema@0.73.4\n\n## 0.44.4\n\n### Patch Changes\n\n- Updated dependencies [[`e6440a7`](https://github.com/Effect-TS/effect/commit/e6440a74fb3f12f6422ed794c07cb44af91cbacc)]:\n  - @effect/schema@0.73.3\n  - @effect/platform@0.65.4\n\n## 0.44.3\n\n### Patch Changes\n\n- Updated dependencies [[`f0d8ef1`](https://github.com/Effect-TS/effect/commit/f0d8ef1ce97ec2a87b09b3e24150cfeab85d6e2f)]:\n  - effect@3.8.2\n  - @effect/platform@0.65.3\n  - @effect/printer@0.36.2\n  - @effect/printer-ansi@0.36.2\n  - @effect/schema@0.73.2\n\n## 0.44.2\n\n### Patch Changes\n\n- Updated dependencies [[`10bf621`](https://github.com/Effect-TS/effect/commit/10bf6213f36d8ddb00f058a4609b85220f3d8334), [`f56ab78`](https://github.com/Effect-TS/effect/commit/f56ab785cbee0c1c43bd2c182c35602f486f61f0), [`ae36fa6`](https://github.com/Effect-TS/effect/commit/ae36fa68f754eeab9a54b6dc0f8b44db513aa2b6)]:\n  - effect@3.8.1\n  - @effect/schema@0.73.1\n  - @effect/platform@0.65.2\n  - @effect/printer@0.36.1\n  - @effect/printer-ansi@0.36.1\n\n## 0.44.1\n\n### Patch Changes\n\n- Updated dependencies [[`e44c5f2`](https://github.com/Effect-TS/effect/commit/e44c5f228215738fe4e75023c7461bf9521249cb)]:\n  - @effect/platform@0.65.1\n\n## 0.44.0\n\n### Patch Changes\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`aa1fa53`](https://github.com/Effect-TS/effect/commit/aa1fa5301e886b9657c8eb0d38cb87cef92a8305) Thanks @vinassefranche! - Add Number.round\n\n- Updated dependencies [[`fcfa6ee`](https://github.com/Effect-TS/effect/commit/fcfa6ee30ffd07d998bf22799357bf58580a116f), [`bb9931b`](https://github.com/Effect-TS/effect/commit/bb9931b62e249a3b801f2cb9d097aec0c8511af7), [`5798f76`](https://github.com/Effect-TS/effect/commit/5798f7619529de33e5ba06f551806f68fedc19db), [`5f0bfa1`](https://github.com/Effect-TS/effect/commit/5f0bfa17205398d4e4818bfbcf9e1b505b3b1fc5), [`7fdf9d9`](https://github.com/Effect-TS/effect/commit/7fdf9d9aa1e2c1c125cbf87991e6efbf4abb7b07), [`812a4e8`](https://github.com/Effect-TS/effect/commit/812a4e86e2d1aa23b477ef5829aa0e5c07784936), [`6a128f6`](https://github.com/Effect-TS/effect/commit/6a128f63f9b41fec2db70790b3bbb96cb9afa1ab), [`273565e`](https://github.com/Effect-TS/effect/commit/273565e7901639e8d0541930ab715aea9c80fbaa), [`adf7d7a`](https://github.com/Effect-TS/effect/commit/adf7d7a7dfce3a7021e9f3b0d847dc85be89d754), [`569a801`](https://github.com/Effect-TS/effect/commit/569a8017ef0a0bc203e4312867cbdd37b0effbd7), [`aa1fa53`](https://github.com/Effect-TS/effect/commit/aa1fa5301e886b9657c8eb0d38cb87cef92a8305), [`02f6b06`](https://github.com/Effect-TS/effect/commit/02f6b0660e12bee1069532a9cc18d3ab855257be), [`12b893e`](https://github.com/Effect-TS/effect/commit/12b893e63cc6dfada4aca7773b4783940e2edf25), [`bbad27e`](https://github.com/Effect-TS/effect/commit/bbad27ec0a90860593f759405caa877e7f4a655f), [`7041393`](https://github.com/Effect-TS/effect/commit/7041393cff132e96566d3f36da0483a6ff6195e4), [`e0d21a5`](https://github.com/Effect-TS/effect/commit/e0d21a54c8323728fbb75a32f4820a9996257809), [`adf7d7a`](https://github.com/Effect-TS/effect/commit/adf7d7a7dfce3a7021e9f3b0d847dc85be89d754), [`007289a`](https://github.com/Effect-TS/effect/commit/007289a52d5877f8e90e2dacf38171ff9bf603fd), [`42a8f99`](https://github.com/Effect-TS/effect/commit/42a8f99740eefdaf2c4544d2c345313f97547a36), [`eebfd29`](https://github.com/Effect-TS/effect/commit/eebfd29633fd5d38b505c5c0842036f61f05e913), [`040703d`](https://github.com/Effect-TS/effect/commit/040703d0e100cd5511e52d812c15492414262b5e)]:\n  - effect@3.8.0\n  - @effect/schema@0.73.0\n  - @effect/platform@0.65.0\n  - @effect/printer@0.36.0\n  - @effect/printer-ansi@0.36.0\n\n## 0.43.3\n\n### Patch Changes\n\n- Updated dependencies [[`35a0f81`](https://github.com/Effect-TS/effect/commit/35a0f813141652d696461cd5d19fd146adaf85be), [`8261c5a`](https://github.com/Effect-TS/effect/commit/8261c5ae6fe86872292ec1fc1a58ab9cea2f5f51)]:\n  - effect@3.7.3\n  - @effect/platform@0.64.1\n  - @effect/printer@0.35.3\n  - @effect/printer-ansi@0.35.3\n  - @effect/schema@0.72.4\n\n## 0.43.2\n\n### Patch Changes\n\n- [#3569](https://github.com/Effect-TS/effect/pull/3569) [`06989e9`](https://github.com/Effect-TS/effect/commit/06989e9969ef78132c4c2dde3ac4892ff60fdb4c) Thanks @IMax153! - Ensure `QuitException` terminates command-line processing.\n\n  A `QuitException` raised by a `Prompt` that is executing as a fallback for a CLI option will terminate processing of the command line.\n\n## 0.43.1\n\n### Patch Changes\n\n- [#3561](https://github.com/Effect-TS/effect/pull/3561) [`2df49c4`](https://github.com/Effect-TS/effect/commit/2df49c44ee9c2504eb96507ce5dfb1fa57b33b18) Thanks @IMax153! - Add `Options.withFallbackPrompt` to CLI\n\n  You can now specify that a command-line option should fallback to prompting the\n  user for a value if no value is specified.\n\n  ```ts\n  import * as Options from \"@effect/cli/Options\"\n  import * as Prompt from \"@effect/cli/Prompt\"\n\n  const name = Options.text(\"name\").pipe(\n    Options.withFallbackPrompt(\n      Prompt.text({\n        message: \"Please provide your name\"\n      })\n    )\n  )\n  ```\n\n## 0.43.0\n\n### Patch Changes\n\n- Updated dependencies [[`f6acb71`](https://github.com/Effect-TS/effect/commit/f6acb71b17a0e6b0d449e7f661c9e2c3d335fcac), [`90ac8f6`](https://github.com/Effect-TS/effect/commit/90ac8f6f6053a2e4498f8b0cc56fe12777d02e1a), [`90ac8f6`](https://github.com/Effect-TS/effect/commit/90ac8f6f6053a2e4498f8b0cc56fe12777d02e1a), [`3791e24`](https://github.com/Effect-TS/effect/commit/3791e241636b1dfe924a56f380ebc9a7ff0827a9), [`3791e24`](https://github.com/Effect-TS/effect/commit/3791e241636b1dfe924a56f380ebc9a7ff0827a9)]:\n  - @effect/schema@0.72.3\n  - @effect/platform@0.64.0\n\n## 0.42.3\n\n### Patch Changes\n\n- Updated dependencies [[`4a701c4`](https://github.com/Effect-TS/effect/commit/4a701c406da032563fedae459536c00ae5cfe3c7)]:\n  - @effect/platform@0.63.3\n\n## 0.42.2\n\n### Patch Changes\n\n- Updated dependencies [[`8a601d7`](https://github.com/Effect-TS/effect/commit/8a601d7a1f8ffe52ac9e6d67e9282a1495fe59c9), [`353ba19`](https://github.com/Effect-TS/effect/commit/353ba19f9b2b9e959f0a00d058c6d40a4bc02db7)]:\n  - effect@3.7.2\n  - @effect/platform@0.63.2\n  - @effect/printer@0.35.2\n  - @effect/printer-ansi@0.35.2\n  - @effect/schema@0.72.2\n\n## 0.42.1\n\n### Patch Changes\n\n- Updated dependencies [[`79859e7`](https://github.com/Effect-TS/effect/commit/79859e71040d8edf1868b8530b90c650f4321eff), [`f6a469c`](https://github.com/Effect-TS/effect/commit/f6a469c190b9f00eee5ea0cd4d5912a0ef8b46f5), [`dcb9ec0`](https://github.com/Effect-TS/effect/commit/dcb9ec0db443894dd204d87450f779c44b9ad7f1), [`79aa6b1`](https://github.com/Effect-TS/effect/commit/79aa6b136e1f29b36f34e88cb2ff162bff2bb4ed)]:\n  - effect@3.7.1\n  - @effect/platform@0.63.1\n  - @effect/printer@0.35.1\n  - @effect/printer-ansi@0.35.1\n  - @effect/schema@0.72.1\n\n## 0.42.0\n\n### Patch Changes\n\n- Updated dependencies [[`db89601`](https://github.com/Effect-TS/effect/commit/db89601ee9c1050c4e762b7bd7ec65a6a2799dfe), [`2f456cc`](https://github.com/Effect-TS/effect/commit/2f456cce5012b9fcb6b4e039190d527813b75b92), [`8745e41`](https://github.com/Effect-TS/effect/commit/8745e41ed96e3765dc6048efc2a9afbe05c8a1e9), [`e557838`](https://github.com/Effect-TS/effect/commit/e55783886b046d3c5f33447f455f9ccf2fa75922), [`d6e7e40`](https://github.com/Effect-TS/effect/commit/d6e7e40b1e2ad0c59aa02f07344d28601b14ebdc), [`8356321`](https://github.com/Effect-TS/effect/commit/8356321598da04bd77c1001f45a4e447bec5591d), [`192f2eb`](https://github.com/Effect-TS/effect/commit/192f2ebb2c4ddbf4bfd8baedd32140b2376868f4), [`718cb70`](https://github.com/Effect-TS/effect/commit/718cb70038629a6d58d02e407760e341f7c94474), [`e9d0310`](https://github.com/Effect-TS/effect/commit/e9d03107acbf204d9304f3e8aea0816b7d3c7dfb), [`6bf28f7`](https://github.com/Effect-TS/effect/commit/6bf28f7e3b1e5e0608ff567205fea0581d11666f)]:\n  - effect@3.7.0\n  - @effect/platform@0.63.0\n  - @effect/printer@0.35.0\n  - @effect/printer-ansi@0.35.0\n  - @effect/schema@0.72.0\n\n## 0.41.5\n\n### Patch Changes\n\n- [#3508](https://github.com/Effect-TS/effect/pull/3508) [`8e64b1a`](https://github.com/Effect-TS/effect/commit/8e64b1a6ed4310fbc767910c6141adda9d19463c) Thanks @cdierkens! - Renders the default for all `Prompt` types that accepts `TextOptions`.\n  - The default value will be rendered as ghost text for `Prompt.text` and `Prompt.list`.\n  - The default value will be rendered as redacted ghost text for `Prompt.password`.\n  - The default value will remain hidden for `Prompt.hidden`.\n\n- Updated dependencies [[`e809286`](https://github.com/Effect-TS/effect/commit/e8092865900608c4df7a6b7991b1c13cc1e4ca2d)]:\n  - effect@3.6.8\n  - @effect/platform@0.62.5\n  - @effect/printer@0.34.8\n  - @effect/printer-ansi@0.34.8\n  - @effect/schema@0.71.4\n\n## 0.41.4\n\n### Patch Changes\n\n- Updated dependencies [[`e7a65e3`](https://github.com/Effect-TS/effect/commit/e7a65e3c6a08636bbfce3d3af3098bf28474364d), [`50ec889`](https://github.com/Effect-TS/effect/commit/50ec8897a49b7d1fe84f63107f89d543c52f3dfc)]:\n  - @effect/platform@0.62.4\n  - effect@3.6.7\n  - @effect/printer@0.34.7\n  - @effect/printer-ansi@0.34.7\n  - @effect/schema@0.71.3\n\n## 0.41.3\n\n### Patch Changes\n\n- Updated dependencies [[`f960bf4`](https://github.com/Effect-TS/effect/commit/f960bf45239e9badac6e0ad3a602f4174cd7bbdf), [`46a575f`](https://github.com/Effect-TS/effect/commit/46a575f48a05457b782fb21f7827d338c9b59320)]:\n  - effect@3.6.6\n  - @effect/platform@0.62.3\n  - @effect/printer@0.34.6\n  - @effect/printer-ansi@0.34.6\n  - @effect/schema@0.71.2\n\n## 0.41.2\n\n### Patch Changes\n\n- [#3466](https://github.com/Effect-TS/effect/pull/3466) [`72dd535`](https://github.com/Effect-TS/effect/commit/72dd53566a2050ef2fa21153a07520df1969edf8) Thanks @cdierkens! - Respect the `Prompt.TextOptions.default` for a prompt created with `Prompt.text`\n\n- Updated dependencies [[`413994c`](https://github.com/Effect-TS/effect/commit/413994c9792f16d9d57cca3ae6eb254bf93bd261), [`14a47a8`](https://github.com/Effect-TS/effect/commit/14a47a8c1f3cff2186b8fe7a919a1d773888fb5b), [`0c09841`](https://github.com/Effect-TS/effect/commit/0c0984173be3d58f050b300a1a8aa89d76ba49ae)]:\n  - @effect/platform@0.62.2\n  - effect@3.6.5\n  - @effect/printer@0.34.5\n  - @effect/printer-ansi@0.34.5\n  - @effect/schema@0.71.1\n\n## 0.41.1\n\n### Patch Changes\n\n- Updated dependencies [[`9efe0e5`](https://github.com/Effect-TS/effect/commit/9efe0e5b57ac557399be620822c21cc6e9add285)]:\n  - @effect/platform@0.62.1\n\n## 0.41.0\n\n### Patch Changes\n\n- [#3450](https://github.com/Effect-TS/effect/pull/3450) [`0e42a8f`](https://github.com/Effect-TS/effect/commit/0e42a8f045ecb1fd3d080edf3d49fef16a9b0ca1) Thanks @tim-smart! - update dependencies\n\n- Updated dependencies [[`c1987e2`](https://github.com/Effect-TS/effect/commit/c1987e25c8f5c48bdc9ad223d7a6f2c32f93f5a1), [`8295281`](https://github.com/Effect-TS/effect/commit/8295281ae9bd7441e680402540bf3c8682ec417b), [`c940df6`](https://github.com/Effect-TS/effect/commit/c940df63800bf3c4396d91cf28ec34938642fd2c), [`00b6c6d`](https://github.com/Effect-TS/effect/commit/00b6c6d4001f5de728b7d990a1b14560b4961a63), [`1ceed14`](https://github.com/Effect-TS/effect/commit/1ceed149dc64f4874e64b5cf2f954eba0a5a1f12), [`f8d95a6`](https://github.com/Effect-TS/effect/commit/f8d95a61ad0762147933c5c32bb6d7237e18eef4), [`0e42a8f`](https://github.com/Effect-TS/effect/commit/0e42a8f045ecb1fd3d080edf3d49fef16a9b0ca1)]:\n  - @effect/schema@0.71.0\n  - effect@3.6.4\n  - @effect/platform@0.62.0\n  - @effect/printer@0.34.4\n  - @effect/printer-ansi@0.34.4\n\n## 0.40.8\n\n### Patch Changes\n\n- Updated dependencies [[`04adcac`](https://github.com/Effect-TS/effect/commit/04adcace913e6fc483df266874a68005e9e04ccf)]:\n  - effect@3.6.3\n  - @effect/platform@0.61.8\n  - @effect/printer@0.34.3\n  - @effect/printer-ansi@0.34.3\n  - @effect/schema@0.70.4\n\n## 0.40.7\n\n### Patch Changes\n\n- Updated dependencies [[`17245a4`](https://github.com/Effect-TS/effect/commit/17245a4e783c19dee51529600b3b40f164fa59bc), [`630d40e`](https://github.com/Effect-TS/effect/commit/630d40eaa7eb4d2f8b6705b16d4f426bc28a7d09), [`630d40e`](https://github.com/Effect-TS/effect/commit/630d40eaa7eb4d2f8b6705b16d4f426bc28a7d09)]:\n  - @effect/platform@0.61.7\n\n## 0.40.6\n\n### Patch Changes\n\n- Updated dependencies [[`99ad841`](https://github.com/Effect-TS/effect/commit/99ad8415293a82d08bd7043c563b29e2b468ca74), [`d829b57`](https://github.com/Effect-TS/effect/commit/d829b576357f2e3b203ab7e107a1492de903a106), [`fd4b2f6`](https://github.com/Effect-TS/effect/commit/fd4b2f6516b325740dde615f1cf0229edf13ca0c)]:\n  - @effect/schema@0.70.3\n  - @effect/platform@0.61.6\n  - effect@3.6.2\n  - @effect/printer@0.34.2\n  - @effect/printer-ansi@0.34.2\n\n## 0.40.5\n\n### Patch Changes\n\n- Updated dependencies [[`056b710`](https://github.com/Effect-TS/effect/commit/056b7108978e70612176c23991916f678d947f38)]:\n  - @effect/platform@0.61.5\n\n## 0.40.4\n\n### Patch Changes\n\n- Updated dependencies [[`e7cb109`](https://github.com/Effect-TS/effect/commit/e7cb109d0754207024a64d55b6bd2a674dd8ed7d)]:\n  - @effect/platform@0.61.4\n\n## 0.40.3\n\n### Patch Changes\n\n- Updated dependencies [[`510a34d`](https://github.com/Effect-TS/effect/commit/510a34d4cc5d2f51347a53847f6c7db84d2b17c6), [`fb9f786`](https://github.com/Effect-TS/effect/commit/fb9f7867f0c895e63f9ef23e8d0941248c42179d), [`45dbb9f`](https://github.com/Effect-TS/effect/commit/45dbb9ffeaf93d9e4df99d0cd4920e41ba9a3978)]:\n  - effect@3.6.1\n  - @effect/platform@0.61.3\n  - @effect/printer@0.34.1\n  - @effect/printer-ansi@0.34.1\n  - @effect/schema@0.70.2\n\n## 0.40.2\n\n### Patch Changes\n\n- Updated dependencies [[`3dce357`](https://github.com/Effect-TS/effect/commit/3dce357efe4a4451d7d29859d08ac11713999b1a), [`657fc48`](https://github.com/Effect-TS/effect/commit/657fc48bb32daf2dc09c9335b3cbc3152bcbdd3b)]:\n  - @effect/schema@0.70.1\n  - @effect/platform@0.61.2\n\n## 0.40.1\n\n### Patch Changes\n\n- Updated dependencies [[`11223bf`](https://github.com/Effect-TS/effect/commit/11223bf9cbf5b822e0bf9a9fb2b35b2ad88af692)]:\n  - @effect/platform@0.61.1\n\n## 0.40.0\n\n### Patch Changes\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`7d02174`](https://github.com/Effect-TS/effect/commit/7d02174af3bcbf054e5cdddb821c91d0f47e8285) Thanks @fubhy! - Changed various function signatures to return `Array` instead of `ReadonlyArray`\n\n- Updated dependencies [[`1e0fe80`](https://github.com/Effect-TS/effect/commit/1e0fe802b36c257971296617473ce0abe730e8dc), [`8135294`](https://github.com/Effect-TS/effect/commit/8135294b591ea94fde7e6f94a504608f0e630520), [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987), [`3845646`](https://github.com/Effect-TS/effect/commit/3845646828e98f3c7cda1217f6cfe5f642ac0603), [`2d09078`](https://github.com/Effect-TS/effect/commit/2d09078c5948b37fc2f79ef858fe4ca3e4814085), [`4bce5a0`](https://github.com/Effect-TS/effect/commit/4bce5a0274203550ccf117d830721891b0a3d182), [`4ddbff0`](https://github.com/Effect-TS/effect/commit/4ddbff0bb4e3ffddfeb509c59835b83245fb975e), [`e74cc38`](https://github.com/Effect-TS/effect/commit/e74cc38cb420a320c4d7ef98180f19d452a8b316), [`bb069b4`](https://github.com/Effect-TS/effect/commit/bb069b49ef291c532a02c1e8e74271f6d1bb32ec), [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987), [`7d02174`](https://github.com/Effect-TS/effect/commit/7d02174af3bcbf054e5cdddb821c91d0f47e8285)]:\n  - effect@3.6.0\n  - @effect/schema@0.70.0\n  - @effect/platform@0.61.0\n  - @effect/printer@0.34.0\n  - @effect/printer-ansi@0.34.0\n\n## 0.39.3\n\n### Patch Changes\n\n- Updated dependencies [[`7c0da50`](https://github.com/Effect-TS/effect/commit/7c0da5050d30cb804f4eacb15995d0fb7f3a28d2), [`2fc0ff4`](https://github.com/Effect-TS/effect/commit/2fc0ff4c59c25977018f6ac70ced99b04a8c7b2b), [`6359644`](https://github.com/Effect-TS/effect/commit/635964446323cf55d4060559337e710e4a24496e), [`f262665`](https://github.com/Effect-TS/effect/commit/f262665c2773492c01e5dd0e8d6db235aafaaad8), [`7f41e42`](https://github.com/Effect-TS/effect/commit/7f41e428830bf3043b8be0d28dcd235d5747c942), [`9bbe7a6`](https://github.com/Effect-TS/effect/commit/9bbe7a681430ebf5c10167bb7140ba3742e46bb7), [`f566fd1`](https://github.com/Effect-TS/effect/commit/f566fd1d7eea531a0d981dd24037f14a603a1273)]:\n  - @effect/schema@0.69.3\n  - effect@3.5.9\n  - @effect/platform@0.60.3\n  - @effect/printer@0.33.52\n  - @effect/printer-ansi@0.33.52\n\n## 0.39.2\n\n### Patch Changes\n\n- Updated dependencies [[`eb4d014`](https://github.com/Effect-TS/effect/commit/eb4d014c559e1b4c95b3fb9295fe77593c17ed7a), [`1ba640c`](https://github.com/Effect-TS/effect/commit/1ba640c702f187a866023bf043c26e25cce941ef), [`c8c71bd`](https://github.com/Effect-TS/effect/commit/c8c71bd20eb87d23133dac6156b83bb08941597c), [`a26ce58`](https://github.com/Effect-TS/effect/commit/a26ce581ca7d407e1e81439b58c8045b3fa65231), [`fc20f73`](https://github.com/Effect-TS/effect/commit/fc20f73c69e577981cb64714de2adc97e1004dae)]:\n  - @effect/platform@0.60.2\n  - effect@3.5.8\n  - @effect/printer@0.33.51\n  - @effect/printer-ansi@0.33.51\n  - @effect/schema@0.69.2\n\n## 0.39.1\n\n### Patch Changes\n\n- [#3329](https://github.com/Effect-TS/effect/pull/3329) [`b8e3ab6`](https://github.com/Effect-TS/effect/commit/b8e3ab6739d122c31fb9b91ea5cbfc1afff1180b) Thanks @IMax153! - The `Prompt.all` method now supports taking in a record of `Prompt`s to be more\n  consistent with other `all` APIs throughout the Effect ecosystem.\n\n  You can now do:\n\n  ```ts\n  import * as Prompt from \"@effect/cli/Prompt\"\n  import * as NodeContext from \"@effect/platform-node/NodeContext\"\n  import * as Runtime from \"@effect/platform-node/NodeRuntime\"\n  import * as Effect from \"effect/Effect\"\n\n  const program = Prompt.all({\n    username: Prompt.text({\n      message: \"Enter your username\"\n    }),\n    password: Prompt.password({\n      message: \"Enter your password: \",\n      validate: (value) =>\n        value.length === 0\n          ? Effect.fail(\"Password cannot be empty\")\n          : Effect.succeed(value)\n    })\n  })\n\n  program.pipe(\n    Effect.flatMap(({ username, password }) => /* Your logic here */ ),\n    Effect.provide(NodeContext.layer),\n    NodeRuntime.runMain\n  )\n  ```\n\n- [#3332](https://github.com/Effect-TS/effect/pull/3332) [`c8f8690`](https://github.com/Effect-TS/effect/commit/c8f86905859c39ed2735890eebe8d73ceb2eb12e) Thanks @IMax153! - improve the `Prompt.all` JSDoc and add example\n\n- Updated dependencies [[`f241154`](https://github.com/Effect-TS/effect/commit/f241154added5d91e95866c39481f09cdb13bd4d)]:\n  - @effect/schema@0.69.1\n  - @effect/platform@0.60.1\n\n## 0.39.0\n\n### Patch Changes\n\n- Updated dependencies [[`20807a4`](https://github.com/Effect-TS/effect/commit/20807a45edeb4334e903dca5d708cd62a71702d8)]:\n  - @effect/schema@0.69.0\n  - @effect/platform@0.60.0\n\n## 0.38.3\n\n### Patch Changes\n\n- [#3310](https://github.com/Effect-TS/effect/pull/3310) [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc) Thanks @fubhy! - Added additional pure annotations to improve tree-shakeability\n\n- Updated dependencies [[`3afcc93`](https://github.com/Effect-TS/effect/commit/3afcc93413a3d910beb69e4ce9ae120e4adaffd5), [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc), [`6921c4f`](https://github.com/Effect-TS/effect/commit/6921c4fb8c45badff09b493043b85ca71302b560)]:\n  - effect@3.5.7\n  - @effect/platform@0.59.3\n  - @effect/printer@0.33.50\n  - @effect/printer-ansi@0.33.50\n  - @effect/schema@0.68.27\n\n## 0.38.2\n\n### Patch Changes\n\n- Updated dependencies [[`f0285d3`](https://github.com/Effect-TS/effect/commit/f0285d3af6a18829123bc1818331c67206becbc4), [`8ec4955`](https://github.com/Effect-TS/effect/commit/8ec49555ed3b3c98093fa4d135a4c57a3f16ebd1), [`3ac2d76`](https://github.com/Effect-TS/effect/commit/3ac2d76048da09e876cf6c3aee3397febd843fe9), [`cc327a1`](https://github.com/Effect-TS/effect/commit/cc327a1bccd22a4ee27ec7e58b53205e93b23e2c), [`4bfe4fb`](https://github.com/Effect-TS/effect/commit/4bfe4fb5c82f597c9beea9baa92e772593598b60), [`2b14d18`](https://github.com/Effect-TS/effect/commit/2b14d181462cad8359da4fa6bc6dfda0f742c398)]:\n  - @effect/schema@0.68.26\n  - effect@3.5.6\n  - @effect/platform@0.59.2\n  - @effect/printer@0.33.49\n  - @effect/printer-ansi@0.33.49\n\n## 0.38.1\n\n### Patch Changes\n\n- [#2755](https://github.com/Effect-TS/effect/pull/2755) [`51e9c5c`](https://github.com/Effect-TS/effect/commit/51e9c5c87f849ef1a013de4b4c35d397acb1e147) Thanks @dpnova! - Allow using the equals (`=`) character inside aliased key value params.\n\n- Updated dependencies [[`a9d7800`](https://github.com/Effect-TS/effect/commit/a9d7800f6a253192b653d77778b0674f39b1ca39), [`fcecff7`](https://github.com/Effect-TS/effect/commit/fcecff7f7e12b295a252f124861b801c73072151), [`adbf753`](https://github.com/Effect-TS/effect/commit/adbf75340a9db15dc5cadc66e911a8978a195a65), [`adbf753`](https://github.com/Effect-TS/effect/commit/adbf75340a9db15dc5cadc66e911a8978a195a65)]:\n  - effect@3.5.5\n  - @effect/platform@0.59.1\n  - @effect/printer@0.33.48\n  - @effect/printer-ansi@0.33.48\n  - @effect/schema@0.68.25\n\n## 0.38.0\n\n### Patch Changes\n\n- [#3253](https://github.com/Effect-TS/effect/pull/3253) [`ed0dde4`](https://github.com/Effect-TS/effect/commit/ed0dde4888e6f1a97ad5bba06b755d26a6a1c52e) Thanks @tim-smart! - update dependencies\n\n- Updated dependencies [[`53c0db0`](https://github.com/Effect-TS/effect/commit/53c0db06872d5b5edea2a706e83249908385325c), [`ed0dde4`](https://github.com/Effect-TS/effect/commit/ed0dde4888e6f1a97ad5bba06b755d26a6a1c52e), [`ada68b3`](https://github.com/Effect-TS/effect/commit/ada68b3e61c67907c2a281c024c84d818186ca4c), [`ca775ce`](https://github.com/Effect-TS/effect/commit/ca775cec53baebc1a43d9b8852a3ac6726178498), [`5be9cc0`](https://github.com/Effect-TS/effect/commit/5be9cc044025a9541b9b7acefa2d3fc05fa1301b), [`203658f`](https://github.com/Effect-TS/effect/commit/203658f8001c132b25764ab70344b171683b554c), [`eb1c4d4`](https://github.com/Effect-TS/effect/commit/eb1c4d44e54b9d8d201a366d1ff94face2a6dcd3)]:\n  - @effect/platform@0.59.0\n  - effect@3.5.4\n  - @effect/schema@0.68.24\n  - @effect/printer@0.33.47\n  - @effect/printer-ansi@0.33.47\n\n## 0.37.10\n\n### Patch Changes\n\n- Updated dependencies [[`edb0da3`](https://github.com/Effect-TS/effect/commit/edb0da383746d760f35d8582f5fb0cc0eeca9217), [`edb0da3`](https://github.com/Effect-TS/effect/commit/edb0da383746d760f35d8582f5fb0cc0eeca9217), [`a1db40a`](https://github.com/Effect-TS/effect/commit/a1db40a650ab842e778654f0d88e80f2ef4fd6f3), [`c8d3fb0`](https://github.com/Effect-TS/effect/commit/c8d3fb0fe23585f6efb724af51fbab3ba1ad6e83), [`dabd028`](https://github.com/Effect-TS/effect/commit/dabd028decf9b7983ca16ebe0f48c05c11a84b68), [`786b2ab`](https://github.com/Effect-TS/effect/commit/786b2ab29d525c877bb84035dac9e2d6499339d1), [`fc57354`](https://github.com/Effect-TS/effect/commit/fc573547d41667016fce05eaee75960fcc6dce4d)]:\n  - effect@3.5.3\n  - @effect/schema@0.68.23\n  - @effect/platform@0.58.27\n  - @effect/printer@0.33.46\n  - @effect/printer-ansi@0.33.46\n\n## 0.37.9\n\n### Patch Changes\n\n- Updated dependencies [[`639208e`](https://github.com/Effect-TS/effect/commit/639208eeb8a44622994f832bc2d45d06ab636bc8), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5)]:\n  - effect@3.5.2\n  - @effect/platform@0.58.26\n  - @effect/printer@0.33.45\n  - @effect/printer-ansi@0.33.45\n  - @effect/schema@0.68.22\n\n## 0.37.8\n\n### Patch Changes\n\n- Updated dependencies [[`0623fca`](https://github.com/Effect-TS/effect/commit/0623fca41679b0e3c5a10dd0f8985f91670bd721)]:\n  - @effect/platform@0.58.25\n\n## 0.37.7\n\n### Patch Changes\n\n- Updated dependencies [[`55fdd76`](https://github.com/Effect-TS/effect/commit/55fdd761ee95afd73b6a892c13fee92b36c02837)]:\n  - effect@3.5.1\n  - @effect/platform@0.58.24\n  - @effect/printer@0.33.44\n  - @effect/printer-ansi@0.33.44\n  - @effect/schema@0.68.21\n\n## 0.37.6\n\n### Patch Changes\n\n- Updated dependencies [[`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`5ab348f`](https://github.com/Effect-TS/effect/commit/5ab348f265db3d283aa091ddca6d2d49137c16f2), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`3e04bf8`](https://github.com/Effect-TS/effect/commit/3e04bf8a7127e956cadb7684a8f4c661df57663b), [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`4626de5`](https://github.com/Effect-TS/effect/commit/4626de59c25b384216faa0be87bf0b8cd36357d0), [`f01e7db`](https://github.com/Effect-TS/effect/commit/f01e7db317827255d7901f523f2e28b43298e8df), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6), [`ac71f37`](https://github.com/Effect-TS/effect/commit/ac71f378f2413e5aa91c95f649ffe898d6a26114), [`8432360`](https://github.com/Effect-TS/effect/commit/8432360ce68614a419bb328083a4109d0fc8aa93), [`e4bf1bf`](https://github.com/Effect-TS/effect/commit/e4bf1bf2b4a970eacd77c9b77b5ea8c68bc84498), [`13cb861`](https://github.com/Effect-TS/effect/commit/13cb861a5eded15c55c6cdcf6a8acde8320367a6), [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6), [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3), [`9f66825`](https://github.com/Effect-TS/effect/commit/9f66825f1fce0fe8d10420c285f7dc4c71e8af8d)]:\n  - effect@3.5.0\n  - @effect/platform@0.58.23\n  - @effect/printer@0.33.43\n  - @effect/printer-ansi@0.33.43\n  - @effect/schema@0.68.20\n\n## 0.37.5\n\n### Patch Changes\n\n- Updated dependencies [[`7af137c`](https://github.com/Effect-TS/effect/commit/7af137c9433f6e74959b3887561ec1e6f12e10ee), [`ee4b3dc`](https://github.com/Effect-TS/effect/commit/ee4b3dc5f68d19dc3ae1c2d12901c5b8ffbebabb), [`366f2ee`](https://github.com/Effect-TS/effect/commit/366f2ee3fb6f712a44e8f84fc188612e5ecc016d), [`366f2ee`](https://github.com/Effect-TS/effect/commit/366f2ee3fb6f712a44e8f84fc188612e5ecc016d), [`097d25c`](https://github.com/Effect-TS/effect/commit/097d25cb5d13c049e01789651be56b09620186ef)]:\n  - effect@3.4.9\n  - @effect/platform@0.58.22\n  - @effect/printer@0.33.42\n  - @effect/printer-ansi@0.33.42\n  - @effect/schema@0.68.19\n\n## 0.37.4\n\n### Patch Changes\n\n- Updated dependencies [[`5d5cc6c`](https://github.com/Effect-TS/effect/commit/5d5cc6cfd7d63b07081290fb189b364999201fc5), [`a435e0f`](https://github.com/Effect-TS/effect/commit/a435e0fc5378b33a49bcec92ee235df6f16a2419), [`b5554db`](https://github.com/Effect-TS/effect/commit/b5554db36c4dd6f64fa5e6a62a29b2759c54217a), [`359ff8a`](https://github.com/Effect-TS/effect/commit/359ff8aa2e4e6389bf56d759baa804e2a7674a16), [`a9c4fb3`](https://github.com/Effect-TS/effect/commit/a9c4fb3bf3c6e92cd1c142b0605fddf7eb3c697c), [`f7534b9`](https://github.com/Effect-TS/effect/commit/f7534b94cba06b143a3d4f29275d92874a939559)]:\n  - @effect/schema@0.68.18\n  - effect@3.4.8\n  - @effect/platform@0.58.21\n  - @effect/printer@0.33.41\n  - @effect/printer-ansi@0.33.41\n\n## 0.37.3\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/printer@0.33.40\n  - @effect/printer-ansi@0.33.40\n\n## 0.37.2\n\n### Patch Changes\n\n- [#3167](https://github.com/Effect-TS/effect/pull/3167) [`749b903`](https://github.com/Effect-TS/effect/commit/749b90345f38d8e61a2f1d6861e55d632daa169e) Thanks @IMax153! - ensure that file selector properly traverses up directories\n\n## 0.37.1\n\n### Patch Changes\n\n- Updated dependencies [[`15967cf`](https://github.com/Effect-TS/effect/commit/15967cf18931fb6ede3083eb687a8dfff371cc56), [`2328e17`](https://github.com/Effect-TS/effect/commit/2328e17577112db17c29b7756942a0ff64a70ee0), [`a5737d6`](https://github.com/Effect-TS/effect/commit/a5737d6db2b921605c332eabbc5402ee3d17357b)]:\n  - @effect/schema@0.68.17\n  - effect@3.4.7\n  - @effect/platform@0.58.20\n  - @effect/printer@0.33.39\n  - @effect/printer-ansi@0.33.39\n\n## 0.37.0\n\n### Minor Changes\n\n- [#3153](https://github.com/Effect-TS/effect/pull/3153) [`51bb7d5`](https://github.com/Effect-TS/effect/commit/51bb7d5677069e51f0c9b0f7e57c4ea2f41401b7) Thanks @IMax153! - Refactors the `Prompt.custom` constructor to make it easier to create custom\n  `Prompt`s.\n\n  The `Prompt.custom` constructor allows for creation of a custom `Prompt` from\n  the provided initial state and handlers.\n\n  ```ts\n  export const custom: <State, Output>(\n    initialState: State | Effect<State, never, Prompt.Environment>,\n    handlers: {\n      readonly render: (\n        state: State,\n        action: Action<State, Output>\n      ) => Effect<string, never, Environment>\n      readonly process: (\n        input: UserInput,\n        state: State\n      ) => Effect<Action<State, Output>, never, Environment>\n      readonly clear: (\n        state: State,\n        action: Action<State, Output>\n      ) => Effect<string, never, Environment>\n    }\n  ) => Prompt<Output> = InternalPrompt.custom\n  ```\n\n  The initial state of a `Prompt` can either be a pure value or an `Effect`. This\n  is particularly useful when the initial state of the `Prompt` must be computed\n  by performing some effectful computation, such as reading data from the file\n  system.\n\n  A `Prompt` is essentially a render loop where user input triggers a new frame\n  to be rendered to the `Terminal`. The `handlers` of a custom prompt are used\n  to control what is rendered to the `Terminal` each frame. During each frame,\n  the following occurs:\n  1. The `render` handler is called with this frame's prompt state and prompt\n     action and returns an ANSI escape string to be rendered to the\n     `Terminal`\n  2. The `Terminal` obtains input from the user\n  3. The `process` handler is called with the input obtained from the user\n     and this frame's prompt state and returns the next prompt action that\n     should be performed\n  4. The `clear` handler is called with this frame's prompt state and prompt\n     action and returns an ANSI escape string used to clear the screen of\n     the `Terminal`\n\n- [#3153](https://github.com/Effect-TS/effect/pull/3153) [`51bb7d5`](https://github.com/Effect-TS/effect/commit/51bb7d5677069e51f0c9b0f7e57c4ea2f41401b7) Thanks @IMax153! - Utilize the `Prompt.file` constructor in Effect CLI's wizard mode for file and directory `Options`\n\n- [#3153](https://github.com/Effect-TS/effect/pull/3153) [`51bb7d5`](https://github.com/Effect-TS/effect/commit/51bb7d5677069e51f0c9b0f7e57c4ea2f41401b7) Thanks @IMax153! - Adds a `Prompt.file` constructor to the `Prompt` module which allows the user to select a file\n\n## 0.36.72\n\n### Patch Changes\n\n- Updated dependencies [[`d006cec`](https://github.com/Effect-TS/effect/commit/d006cec022e8524dbfd6dc6df751fe4c86b10042), [`cb22726`](https://github.com/Effect-TS/effect/commit/cb2272656881aa5878a1c3fc0b12d8fbc66eb63c), [`e911cfd`](https://github.com/Effect-TS/effect/commit/e911cfdc79418462d7e9000976fded15ea6b738d)]:\n  - @effect/schema@0.68.16\n  - @effect/platform@0.58.19\n\n## 0.36.71\n\n### Patch Changes\n\n- Updated dependencies [[`7f8900a`](https://github.com/Effect-TS/effect/commit/7f8900a1de9addeb0d371103a2c5c2aa3e4ff95e)]:\n  - @effect/platform@0.58.18\n\n## 0.36.70\n\n### Patch Changes\n\n- Updated dependencies [[`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`34faeb6`](https://github.com/Effect-TS/effect/commit/34faeb6305ba52af4d6f8bdd2e633bb6a5a7a35b), [`33735b1`](https://github.com/Effect-TS/effect/commit/33735b16b41bd26929d8f4754c190925db6323b7), [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`139d4b3`](https://github.com/Effect-TS/effect/commit/139d4b39fb3bff2eeaa7c0c809c581da42425a83)]:\n  - effect@3.4.6\n  - @effect/schema@0.68.15\n  - @effect/platform@0.58.17\n  - @effect/printer@0.33.38\n  - @effect/printer-ansi@0.33.38\n\n## 0.36.69\n\n### Patch Changes\n\n- Updated dependencies [[`61e5964`](https://github.com/Effect-TS/effect/commit/61e59640fd993216cca8ace0ac8abd9104e213ce)]:\n  - @effect/schema@0.68.14\n  - @effect/platform@0.58.16\n\n## 0.36.68\n\n### Patch Changes\n\n- [#3107](https://github.com/Effect-TS/effect/pull/3107) [`fcb7411`](https://github.com/Effect-TS/effect/commit/fcb7411be7ccc8b62da7c5e2b2044365ae879a0e) Thanks @IMax153! - Adds a `--log-level` built-in option to all commands which can be used to control the minimum `LogLevel` of the command's associated handler\n\n- Updated dependencies [[`cb76bcb`](https://github.com/Effect-TS/effect/commit/cb76bcb2f8858a90db4f785efee262cea1b9844e), [`baa90df`](https://github.com/Effect-TS/effect/commit/baa90df9663f5f37d7b6814dad25142d53dbc720)]:\n  - @effect/schema@0.68.13\n  - @effect/platform@0.58.15\n\n## 0.36.67\n\n### Patch Changes\n\n- [#3106](https://github.com/Effect-TS/effect/pull/3106) [`0cb3e9d`](https://github.com/Effect-TS/effect/commit/0cb3e9de39f9e381a122939b32af4a59b84ea8e7) Thanks @IMax153! - ensure that the built-in option for displaying the CLI's help documentation always respects `CliConfig.showBuiltIns`\n\n- Updated dependencies [[`52a87c7`](https://github.com/Effect-TS/effect/commit/52a87c7a0b9536398deaf8ec507e53a82c607219), [`6d2280e`](https://github.com/Effect-TS/effect/commit/6d2280e9497c95cb0e965ca462c825345074eedf)]:\n  - @effect/platform@0.58.14\n\n## 0.36.66\n\n### Patch Changes\n\n- Updated dependencies [[`a047af9`](https://github.com/Effect-TS/effect/commit/a047af99447dfffc729e9c8ef0ca143537927e91), [`dbd53ea`](https://github.com/Effect-TS/effect/commit/dbd53ea363c71a24449cb068251054c3a1acf864), [`d990544`](https://github.com/Effect-TS/effect/commit/d9905444b9e800850cb65899114ca0e502e68fe8)]:\n  - effect@3.4.5\n  - @effect/platform@0.58.13\n  - @effect/schema@0.68.12\n  - @effect/printer@0.33.37\n  - @effect/printer-ansi@0.33.37\n\n## 0.36.65\n\n### Patch Changes\n\n- Updated dependencies [[`74e0ad2`](https://github.com/Effect-TS/effect/commit/74e0ad23b4c36f41b7fd10856b20f8b701bc4044), [`74e0ad2`](https://github.com/Effect-TS/effect/commit/74e0ad23b4c36f41b7fd10856b20f8b701bc4044), [`72638e3`](https://github.com/Effect-TS/effect/commit/72638e3d99f0e93a24febf6c225256ce92d4a20b), [`d7dde2b`](https://github.com/Effect-TS/effect/commit/d7dde2b4af08b37af859d4c327c1f5c6f00cf9d9), [`9b2fc3b`](https://github.com/Effect-TS/effect/commit/9b2fc3b9dfd304a2bd0508ef2313cfc54357be0c), [`d71c192`](https://github.com/Effect-TS/effect/commit/d71c192b89fd1162423acddc5fd3d6270fbf2ef6)]:\n  - @effect/platform@0.58.12\n  - effect@3.4.4\n  - @effect/schema@0.68.11\n  - @effect/printer@0.33.36\n  - @effect/printer-ansi@0.33.36\n\n## 0.36.64\n\n### Patch Changes\n\n- Updated dependencies [[`a5b95b5`](https://github.com/Effect-TS/effect/commit/a5b95b548284e4798654ae7ce6883fa49108f0ea), [`5e29579`](https://github.com/Effect-TS/effect/commit/5e29579187cb8420ea4930b3999fec984f8999f4)]:\n  - @effect/platform@0.58.11\n\n## 0.36.63\n\n### Patch Changes\n\n- [#3079](https://github.com/Effect-TS/effect/pull/3079) [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd) Thanks @tim-smart! - update dependencies\n\n- [#3079](https://github.com/Effect-TS/effect/pull/3079) [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd) Thanks @tim-smart! - update to typescript 5.5\n\n- Updated dependencies [[`a48ee84`](https://github.com/Effect-TS/effect/commit/a48ee845ac21bbde9baf938af9e97a98322211c9), [`c342739`](https://github.com/Effect-TS/effect/commit/c3427396226e1ad7b95b40595a23f9bdff3e3365), [`8898e5e`](https://github.com/Effect-TS/effect/commit/8898e5e238622f6337583d91ee23609c1f5ccdf7), [`a48ee84`](https://github.com/Effect-TS/effect/commit/a48ee845ac21bbde9baf938af9e97a98322211c9), [`a48ee84`](https://github.com/Effect-TS/effect/commit/a48ee845ac21bbde9baf938af9e97a98322211c9), [`ff78636`](https://github.com/Effect-TS/effect/commit/ff786367c522975f40f0f179a0ecdfcfab7ecbdb), [`c86bd4e`](https://github.com/Effect-TS/effect/commit/c86bd4e134c23146c216f9ff97e03781d55991b6), [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd), [`ab3180f`](https://github.com/Effect-TS/effect/commit/ab3180f827041d0ea3b2d72254a1a8683e99e056), [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd)]:\n  - @effect/platform@0.58.10\n  - effect@3.4.3\n  - @effect/schema@0.68.10\n  - @effect/printer@0.33.35\n  - @effect/printer-ansi@0.33.35\n\n## 0.36.62\n\n### Patch Changes\n\n- Updated dependencies [[`0b47fdf`](https://github.com/Effect-TS/effect/commit/0b47fdfe449f42de89e0e88b61ae5140f629e5c4)]:\n  - @effect/schema@0.68.9\n  - @effect/platform@0.58.9\n\n## 0.36.61\n\n### Patch Changes\n\n- Updated dependencies [[`192261b`](https://github.com/Effect-TS/effect/commit/192261b2aec94e9913ceed83683fdcfbc9fca66f), [`3da1497`](https://github.com/Effect-TS/effect/commit/3da1497b5c9cc886d300258bc928fd68a4fefe6f)]:\n  - @effect/schema@0.68.8\n  - effect@3.4.2\n  - @effect/platform@0.58.8\n  - @effect/printer@0.33.34\n  - @effect/printer-ansi@0.33.34\n\n## 0.36.60\n\n### Patch Changes\n\n- Updated dependencies [[`027004a`](https://github.com/Effect-TS/effect/commit/027004a897f654791e75faa28eefb50dd0244b6e)]:\n  - @effect/platform@0.58.7\n\n## 0.36.59\n\n### Patch Changes\n\n- Updated dependencies [[`66a1910`](https://github.com/Effect-TS/effect/commit/66a19109ff90c4252123b8809b8c8a74681dba6a), [`2e8e252`](https://github.com/Effect-TS/effect/commit/2e8e2520cac712f0eb644553bd476429ebd674e4)]:\n  - effect@3.4.1\n  - @effect/platform@0.58.6\n  - @effect/printer@0.33.33\n  - @effect/printer-ansi@0.33.33\n  - @effect/schema@0.68.7\n\n## 0.36.58\n\n### Patch Changes\n\n- Updated dependencies [[`37a07a2`](https://github.com/Effect-TS/effect/commit/37a07a2d8d1ce09ab965c0ada84a3fae9a6aba05)]:\n  - @effect/platform@0.58.5\n\n## 0.36.57\n\n### Patch Changes\n\n- Updated dependencies [[`b77fb0a`](https://github.com/Effect-TS/effect/commit/b77fb0a811ec1ad0e794917077c9a90824515db8)]:\n  - @effect/platform@0.58.4\n\n## 0.36.56\n\n### Patch Changes\n\n- Updated dependencies [[`530fa9e`](https://github.com/Effect-TS/effect/commit/530fa9e36b8532589b948fc4faa37593f36b7f42)]:\n  - @effect/schema@0.68.6\n  - @effect/platform@0.58.3\n\n## 0.36.55\n\n### Patch Changes\n\n- Updated dependencies [[`1d62815`](https://github.com/Effect-TS/effect/commit/1d62815a50f34115606940ffa397442d75a20c81)]:\n  - @effect/schema@0.68.5\n  - @effect/platform@0.58.2\n\n## 0.36.54\n\n### Patch Changes\n\n- Updated dependencies [[`5a248aa`](https://github.com/Effect-TS/effect/commit/5a248aa5ab2db3f7131ebc79bb9871a76de57973)]:\n  - @effect/platform@0.58.1\n\n## 0.36.53\n\n### Patch Changes\n\n- Updated dependencies [[`c0ce180`](https://github.com/Effect-TS/effect/commit/c0ce180861ad0938053c0e6145e813fa6404df3b), [`63dd0c3`](https://github.com/Effect-TS/effect/commit/63dd0c3af45876c1caad7d03356c74daf551c628), [`61707b6`](https://github.com/Effect-TS/effect/commit/61707b6ffc7397c2ba0dce22512b44955724f60f), [`9c1b5b3`](https://github.com/Effect-TS/effect/commit/9c1b5b39e6c19604ce834f072a114ad392c50a06), [`a35faf8`](https://github.com/Effect-TS/effect/commit/a35faf8d116f94899bfc03feab33b004c8ddfdf7), [`ff73c0c`](https://github.com/Effect-TS/effect/commit/ff73c0cacd66132bfad2e5211b3eae347729c667), [`984d516`](https://github.com/Effect-TS/effect/commit/984d516ccd9412dc41188f6a46b748dd20dd5848), [`8c3b8a2`](https://github.com/Effect-TS/effect/commit/8c3b8a2ce208eab753b6206a51605a424f104e98), [`017e2f9`](https://github.com/Effect-TS/effect/commit/017e2f9b371ce24ea4945e5d7390c934ad3c39cf), [`91bf8a2`](https://github.com/Effect-TS/effect/commit/91bf8a2e9d1959393b3cf7366cc1d584d3e666b7), [`c6a4a26`](https://github.com/Effect-TS/effect/commit/c6a4a266606575fd2c7165940c4072ad4c57d01f)]:\n  - effect@3.4.0\n  - @effect/platform@0.58.0\n  - @effect/printer@0.33.32\n  - @effect/printer-ansi@0.33.32\n  - @effect/schema@0.68.4\n\n## 0.36.52\n\n### Patch Changes\n\n- Updated dependencies [[`3ba7ea1`](https://github.com/Effect-TS/effect/commit/3ba7ea1c3c2923e85bf2f17e41176f8f8796d203)]:\n  - @effect/platform@0.57.8\n\n## 0.36.51\n\n### Patch Changes\n\n- Updated dependencies [[`d473800`](https://github.com/Effect-TS/effect/commit/d47380012c3241d7287b66968d33a2414275ce7b)]:\n  - @effect/schema@0.68.3\n  - @effect/platform@0.57.7\n\n## 0.36.50\n\n### Patch Changes\n\n- Updated dependencies [[`eb341b3`](https://github.com/Effect-TS/effect/commit/eb341b3eb34ad64499371bc08b7f59e429979d8a)]:\n  - @effect/schema@0.68.2\n  - @effect/platform@0.57.6\n\n## 0.36.49\n\n### Patch Changes\n\n- Updated dependencies [[`b8ea6aa`](https://github.com/Effect-TS/effect/commit/b8ea6aa479006358042b4256ee0a1c5cfbe57acb)]:\n  - @effect/platform@0.57.5\n\n## 0.36.48\n\n### Patch Changes\n\n- Updated dependencies [[`b51e266`](https://github.com/Effect-TS/effect/commit/b51e26662b879b55d2c5164b7c97742739aa9446), [`6c89408`](https://github.com/Effect-TS/effect/commit/6c89408cd7b9204ec4c5828a46cd5312d8afb5e7)]:\n  - @effect/schema@0.68.1\n  - effect@3.3.5\n  - @effect/platform@0.57.4\n  - @effect/printer@0.33.31\n  - @effect/printer-ansi@0.33.31\n\n## 0.36.47\n\n### Patch Changes\n\n- Updated dependencies [[`f6c7977`](https://github.com/Effect-TS/effect/commit/f6c79772e632c440b7e5221bb75f0ef9d3c3b005), [`a67b8fe`](https://github.com/Effect-TS/effect/commit/a67b8fe2ace08419424811b5f0d9a5378eaea352)]:\n  - @effect/schema@0.68.0\n  - effect@3.3.4\n  - @effect/platform@0.57.3\n  - @effect/printer@0.33.30\n  - @effect/printer-ansi@0.33.30\n\n## 0.36.46\n\n### Patch Changes\n\n- Updated dependencies [[`3b15e1b`](https://github.com/Effect-TS/effect/commit/3b15e1b505c0b0e62a03b4a3605d42a9932cc99c), [`06ede85`](https://github.com/Effect-TS/effect/commit/06ede85d6e84710e6622463be95ff3927fb30dad), [`3a750b2`](https://github.com/Effect-TS/effect/commit/3a750b25b1ed92094a7f7ebc332a6bcfb212871b), [`7204ca5`](https://github.com/Effect-TS/effect/commit/7204ca5761c2b1d27999a624db23aa10b6e0504d)]:\n  - @effect/schema@0.67.24\n  - effect@3.3.3\n  - @effect/platform@0.57.2\n  - @effect/printer@0.33.29\n  - @effect/printer-ansi@0.33.29\n\n## 0.36.45\n\n### Patch Changes\n\n- Updated dependencies [[`2ee4f2b`](https://github.com/Effect-TS/effect/commit/2ee4f2be7fd63074a9cbac6dcdfb533b6683533a), [`07e12ec`](https://github.com/Effect-TS/effect/commit/07e12ecdb0e20b9763bd9e9058e567a7c8862efc), [`3572646`](https://github.com/Effect-TS/effect/commit/3572646d5e0804f85bc7f64633fb95722533f9dd), [`1aed347`](https://github.com/Effect-TS/effect/commit/1aed347a125ed3847ec90863424810d6759cbc85), [`df4bf4b`](https://github.com/Effect-TS/effect/commit/df4bf4b62e7b316c6647da0271fc5544a84e7ba2), [`f085f92`](https://github.com/Effect-TS/effect/commit/f085f92dfa204afb41823ffc27d437225137643d), [`9b3b4ac`](https://github.com/Effect-TS/effect/commit/9b3b4ac639d98aae33883926bece1e31fa280d22)]:\n  - @effect/schema@0.67.23\n  - @effect/platform@0.57.1\n  - effect@3.3.2\n  - @effect/printer@0.33.28\n  - @effect/printer-ansi@0.33.28\n\n## 0.36.44\n\n### Patch Changes\n\n- Updated dependencies [[`eb98c5b`](https://github.com/Effect-TS/effect/commit/eb98c5b79ab50aa0cde239bd4e660dd19dbab612), [`184fed8`](https://github.com/Effect-TS/effect/commit/184fed83ac36cba05a75a5a8013f740f9f696e3b), [`4d3fbe8`](https://github.com/Effect-TS/effect/commit/4d3fbe82e8cec13ccd0cd0b2096deac6818fb59a), [`6068e07`](https://github.com/Effect-TS/effect/commit/6068e073d4cc8b3c8583583fd5eb3efe43f7d5ba), [`3a77e20`](https://github.com/Effect-TS/effect/commit/3a77e209783933bac3aaddba1b05ff6a9ac72b36), [`d79ca17`](https://github.com/Effect-TS/effect/commit/d79ca17d9fa432571c69714776cab5cf8fef9c34)]:\n  - effect@3.3.1\n  - @effect/platform@0.57.0\n  - @effect/schema@0.67.22\n  - @effect/printer@0.33.27\n  - @effect/printer-ansi@0.33.27\n\n## 0.36.43\n\n### Patch Changes\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`67f160a`](https://github.com/Effect-TS/effect/commit/67f160a213de0219a565d4bf653b3cbf24f58e8f) Thanks @KhraksMamtsov! - add .redacted apis to /cli package\n\n- Updated dependencies [[`2b9ddfc`](https://github.com/Effect-TS/effect/commit/2b9ddfcbac505d98551e764a43923854907ca5c1), [`1f4ac00`](https://github.com/Effect-TS/effect/commit/1f4ac00a91c336c9c9c9b8c3ed9ceb9920ebc9bd), [`9305b76`](https://github.com/Effect-TS/effect/commit/9305b764cceeae4f16564435ae7172f79c2bf822), [`0f40d98`](https://github.com/Effect-TS/effect/commit/0f40d989da10f68df3ecd72b36849401ad679bfb), [`188f0a5`](https://github.com/Effect-TS/effect/commit/188f0a5c57ed0d7c9e5852e0c1c998f1b95810a1), [`b761ef0`](https://github.com/Effect-TS/effect/commit/b761ef00eaf6c67b7ffe34798b98aae5347ab376), [`b53f69b`](https://github.com/Effect-TS/effect/commit/b53f69bff1452a487b21198cd83961f844e02d36), [`0f40d98`](https://github.com/Effect-TS/effect/commit/0f40d989da10f68df3ecd72b36849401ad679bfb), [`5bd549e`](https://github.com/Effect-TS/effect/commit/5bd549e4bd7144727db438ecca6b8dc9b3ef7e22), [`67f160a`](https://github.com/Effect-TS/effect/commit/67f160a213de0219a565d4bf653b3cbf24f58e8f), [`67f160a`](https://github.com/Effect-TS/effect/commit/67f160a213de0219a565d4bf653b3cbf24f58e8f)]:\n  - @effect/platform@0.56.0\n  - effect@3.3.0\n  - @effect/schema@0.67.21\n  - @effect/printer@0.33.26\n  - @effect/printer-ansi@0.33.26\n\n## 0.36.42\n\n### Patch Changes\n\n- [#2920](https://github.com/Effect-TS/effect/pull/2920) [`61e8edb`](https://github.com/Effect-TS/effect/commit/61e8edbf95ac9f1b2b0e9f4c2532bac42ac1f10b) Thanks @Iri-Hor! - in case of error let cli print to stderr instead of stdout (#1812)\n\n- Updated dependencies [[`4c6bc7f`](https://github.com/Effect-TS/effect/commit/4c6bc7f190c142dc9db70b365a2bf30715a98e62), [`a67d602`](https://github.com/Effect-TS/effect/commit/a67d60276f96cd20b76145b4cee13efca6c6158a)]:\n  - @effect/schema@0.67.20\n  - @effect/platform@0.55.7\n\n## 0.36.41\n\n### Patch Changes\n\n- Updated dependencies [[`8c5d280`](https://github.com/Effect-TS/effect/commit/8c5d280c0402284a4e58372867a15a431cb99461), [`6ba6d26`](https://github.com/Effect-TS/effect/commit/6ba6d269f5891e6b11aa35c5281dde4bf3273004), [`cd7496b`](https://github.com/Effect-TS/effect/commit/cd7496ba214eabac2e3c297f513fcbd5b11f0e91), [`3f28bf2`](https://github.com/Effect-TS/effect/commit/3f28bf274333611906175446b772243f34f1b6d5), [`5817820`](https://github.com/Effect-TS/effect/commit/58178204a770d1a78c06945ef438f9fffbb50afa), [`349a036`](https://github.com/Effect-TS/effect/commit/349a036ffb08351481c060655660a6ccf26473de), [`799aa20`](https://github.com/Effect-TS/effect/commit/799aa20b4f618736ba33a5297fda90a75d4c26c6)]:\n  - effect@3.2.9\n  - @effect/schema@0.67.19\n  - @effect/platform@0.55.6\n  - @effect/printer@0.33.25\n  - @effect/printer-ansi@0.33.25\n\n## 0.36.40\n\n### Patch Changes\n\n- Updated dependencies [[`a0dd1c1`](https://github.com/Effect-TS/effect/commit/a0dd1c1ede2a1e856ecb0e67826ec992016fef97)]:\n  - @effect/schema@0.67.18\n  - @effect/platform@0.55.5\n\n## 0.36.39\n\n### Patch Changes\n\n- Updated dependencies [[`d9d22e7`](https://github.com/Effect-TS/effect/commit/d9d22e7c4d5e31d5b46644c729b027796e467c16), [`3c080f7`](https://github.com/Effect-TS/effect/commit/3c080f74b2e2290edb6143c3aa01026e57f87a2a), [`3c080f7`](https://github.com/Effect-TS/effect/commit/3c080f74b2e2290edb6143c3aa01026e57f87a2a), [`7d6d875`](https://github.com/Effect-TS/effect/commit/7d6d8750077d9c8379f37240745240d7f3b7a4f8), [`70cda70`](https://github.com/Effect-TS/effect/commit/70cda704e8e31c80737b95121c8199e726ea132f), [`fb91f17`](https://github.com/Effect-TS/effect/commit/fb91f17098b48497feca9ec976feb87e4a82451b)]:\n  - @effect/schema@0.67.17\n  - effect@3.2.8\n  - @effect/platform@0.55.4\n  - @effect/printer@0.33.24\n  - @effect/printer-ansi@0.33.24\n\n## 0.36.38\n\n### Patch Changes\n\n- Updated dependencies [[`5745886`](https://github.com/Effect-TS/effect/commit/57458869859943410221ccc87f8cecfba7c79d92), [`6801fca`](https://github.com/Effect-TS/effect/commit/6801fca44366be3ee1b6b99f54bd4f38a1b5e4f4)]:\n  - @effect/schema@0.67.16\n  - effect@3.2.7\n  - @effect/platform@0.55.3\n  - @effect/printer@0.33.23\n  - @effect/printer-ansi@0.33.23\n\n## 0.36.37\n\n### Patch Changes\n\n- Updated dependencies [[`2c2280b`](https://github.com/Effect-TS/effect/commit/2c2280b98a11fc002663c55792a4fa5781cd5fb6), [`e2740fc`](https://github.com/Effect-TS/effect/commit/e2740fc4e212ba85a90541e8c8d85b0bcd5c2e7c), [`cc8ac50`](https://github.com/Effect-TS/effect/commit/cc8ac5080daba8622ca2ff5dab5c37ddfab732ba), [`60fe3d5`](https://github.com/Effect-TS/effect/commit/60fe3d5fb2be168dd35c6d0cb8ac8f55deb30fc0)]:\n  - @effect/platform@0.55.2\n  - @effect/schema@0.67.15\n  - effect@3.2.6\n  - @effect/printer@0.33.22\n  - @effect/printer-ansi@0.33.22\n\n## 0.36.36\n\n### Patch Changes\n\n- [#2847](https://github.com/Effect-TS/effect/pull/2847) [`7000173`](https://github.com/Effect-TS/effect/commit/70001732f4b04678772249377f06dbe448f15d6c) Thanks @ricardo-valero! - display a nicer message in the cli wizard when using Option\n\n- Updated dependencies [[`c5846e9`](https://github.com/Effect-TS/effect/commit/c5846e99137e9eb02efd31865e26f49f0d2c7c03)]:\n  - @effect/schema@0.67.14\n  - @effect/platform@0.55.1\n\n## 0.36.35\n\n### Patch Changes\n\n- Updated dependencies [[`608b01f`](https://github.com/Effect-TS/effect/commit/608b01fc342dbae2a642b308a67b84ead530ecea), [`031c712`](https://github.com/Effect-TS/effect/commit/031c7122a24ac42e48d6a434646b4f5d279d7442), [`a44e532`](https://github.com/Effect-TS/effect/commit/a44e532cf3a6a498b12a5aacf8124aa267e24ba0), [`5133ca9`](https://github.com/Effect-TS/effect/commit/5133ca9dc4b8da0e28951316da9ab55dfbe0fbb9)]:\n  - effect@3.2.5\n  - @effect/platform@0.55.0\n  - @effect/printer@0.33.21\n  - @effect/printer-ansi@0.33.21\n  - @effect/schema@0.67.13\n\n## 0.36.34\n\n### Patch Changes\n\n- Updated dependencies [[`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3), [`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3), [`f8038ca`](https://github.com/Effect-TS/effect/commit/f8038cadd5f50d397469e5fdbc70dd8f69671f50), [`e376641`](https://github.com/Effect-TS/effect/commit/e3766411b60ebb45d31e9c9d94efa099121d4d58), [`c07e0ce`](https://github.com/Effect-TS/effect/commit/c07e0cea8ce165887e2c9dfa5d669eba9b2fb798), [`e313a01`](https://github.com/Effect-TS/effect/commit/e313a01b7e80f6cb7704055a190e5623c9d22c6d), [`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3)]:\n  - effect@3.2.4\n  - @effect/platform@0.54.0\n  - @effect/schema@0.67.12\n  - @effect/printer@0.33.20\n  - @effect/printer-ansi@0.33.20\n\n## 0.36.33\n\n### Patch Changes\n\n- Updated dependencies [[`5af633e`](https://github.com/Effect-TS/effect/commit/5af633eb5ff6560a64d87263d1692bb9c75f7b3c), [`45578e8`](https://github.com/Effect-TS/effect/commit/45578e8faa80ae33d23e08f6f19467f818b7788f)]:\n  - @effect/schema@0.67.11\n  - effect@3.2.3\n  - @effect/platform@0.53.14\n  - @effect/printer@0.33.19\n  - @effect/printer-ansi@0.33.19\n\n## 0.36.32\n\n### Patch Changes\n\n- Updated dependencies [[`5d9266e`](https://github.com/Effect-TS/effect/commit/5d9266e8c740746ac9e186c3df6090a1b57fbe2a), [`9f8122e`](https://github.com/Effect-TS/effect/commit/9f8122e78884ab47c5e5f364d86eee1d1543cc61), [`6a6f670`](https://github.com/Effect-TS/effect/commit/6a6f6706b8613c8c7c10971b8d81a0f9e440a6f2), [`c1eaef9`](https://github.com/Effect-TS/effect/commit/c1eaef910420dae416923d172ee58d219e921d0f), [`78ffc27`](https://github.com/Effect-TS/effect/commit/78ffc27ee3fa708433c25fa118c53d38d90d08bc)]:\n  - effect@3.2.2\n  - @effect/platform@0.53.13\n  - @effect/schema@0.67.10\n  - @effect/printer@0.33.18\n  - @effect/printer-ansi@0.33.18\n\n## 0.36.31\n\n### Patch Changes\n\n- Updated dependencies [[`5432fff`](https://github.com/Effect-TS/effect/commit/5432fff7c9a69d43910426c1053ebfc3b73ebed6)]:\n  - @effect/schema@0.67.9\n  - @effect/platform@0.53.12\n\n## 0.36.30\n\n### Patch Changes\n\n- Updated dependencies [[`c1e991d`](https://github.com/Effect-TS/effect/commit/c1e991dd5ba87901cd0e05697a8b4a267e7e954a)]:\n  - effect@3.2.1\n  - @effect/platform@0.53.11\n  - @effect/printer@0.33.17\n  - @effect/printer-ansi@0.33.17\n  - @effect/schema@0.67.8\n\n## 0.36.29\n\n### Patch Changes\n\n- Updated dependencies [[`146cadd`](https://github.com/Effect-TS/effect/commit/146cadd9d004634a3ff85c480bf92cf975c853e2), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`963b4e7`](https://github.com/Effect-TS/effect/commit/963b4e7ac87e2468feb6a344f7ab4ee4ad711198), [`64c9414`](https://github.com/Effect-TS/effect/commit/64c9414e960e82058ca09bbb3976d6fbef303a8e), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`2cbb76b`](https://github.com/Effect-TS/effect/commit/2cbb76bb52500a3f4bf27d1c91482518cbea56d7), [`870c5fa`](https://github.com/Effect-TS/effect/commit/870c5fa52cd61e745e8e828d38c3f09f00737553), [`146cadd`](https://github.com/Effect-TS/effect/commit/146cadd9d004634a3ff85c480bf92cf975c853e2), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`64c9414`](https://github.com/Effect-TS/effect/commit/64c9414e960e82058ca09bbb3976d6fbef303a8e)]:\n  - effect@3.2.0\n  - @effect/platform@0.53.10\n  - @effect/printer@0.33.16\n  - @effect/printer-ansi@0.33.16\n  - @effect/schema@0.67.7\n\n## 0.36.28\n\n### Patch Changes\n\n- Updated dependencies [[`17da864`](https://github.com/Effect-TS/effect/commit/17da864e4a6f80becdb82db7dece2ba583bfdda3), [`17fc22e`](https://github.com/Effect-TS/effect/commit/17fc22e132593c5caa563705a4748ba0f04a853c), [`810f222`](https://github.com/Effect-TS/effect/commit/810f222268792b13067c7a7bf317b93a9bb8917b), [`596aaea`](https://github.com/Effect-TS/effect/commit/596aaea022648b2e06fb1ec22f1652043d6fe64e), [`ff0efa0`](https://github.com/Effect-TS/effect/commit/ff0efa0a1415a41d4a4312a16cf7a63def86db3f)]:\n  - @effect/schema@0.67.6\n  - @effect/platform@0.53.9\n  - effect@3.1.6\n  - @effect/printer@0.33.15\n  - @effect/printer-ansi@0.33.15\n\n## 0.36.27\n\n### Patch Changes\n\n- Updated dependencies [[`9c514de`](https://github.com/Effect-TS/effect/commit/9c514de28152696edff008324d2d7e67d55afd56)]:\n  - @effect/schema@0.67.5\n  - @effect/platform@0.53.8\n\n## 0.36.26\n\n### Patch Changes\n\n- Updated dependencies [[`ee08593`](https://github.com/Effect-TS/effect/commit/ee0859398ecc2589cab0d017bef6a17e00c34dfd), [`da6d7d8`](https://github.com/Effect-TS/effect/commit/da6d7d845246e9d04631d64fa7694944b6010d09)]:\n  - @effect/schema@0.67.4\n  - @effect/platform@0.53.7\n\n## 0.36.25\n\n### Patch Changes\n\n- Updated dependencies [[`6ac4847`](https://github.com/Effect-TS/effect/commit/6ac48479447c01a4f35d655552af93e47e562610), [`6ac4847`](https://github.com/Effect-TS/effect/commit/6ac48479447c01a4f35d655552af93e47e562610)]:\n  - @effect/platform@0.53.6\n  - effect@3.1.5\n  - @effect/printer@0.33.14\n  - @effect/printer-ansi@0.33.14\n  - @effect/schema@0.67.3\n\n## 0.36.24\n\n### Patch Changes\n\n- Updated dependencies [[`89a3afb`](https://github.com/Effect-TS/effect/commit/89a3afbe191c83b84b17bfaa95519aff0749afbe), [`992c8e2`](https://github.com/Effect-TS/effect/commit/992c8e21535db9f0c66e81d32fee8af56a96274f)]:\n  - @effect/schema@0.67.2\n  - @effect/platform@0.53.5\n\n## 0.36.23\n\n### Patch Changes\n\n- Updated dependencies [[`e41e911`](https://github.com/Effect-TS/effect/commit/e41e91122fa6dd12fc81e50dcad0db891be67146)]:\n  - effect@3.1.4\n  - @effect/platform@0.53.4\n  - @effect/printer@0.33.13\n  - @effect/printer-ansi@0.33.13\n  - @effect/schema@0.67.1\n\n## 0.36.22\n\n### Patch Changes\n\n- Updated dependencies [[`d7e4997`](https://github.com/Effect-TS/effect/commit/d7e49971fe97b7ee5fb7991f3f5ac4d627a26338)]:\n  - @effect/schema@0.67.0\n  - @effect/platform@0.53.3\n\n## 0.36.21\n\n### Patch Changes\n\n- Updated dependencies [[`1f6dc96`](https://github.com/Effect-TS/effect/commit/1f6dc96f51c7bb9c8d11415358308604ba7c7c8e)]:\n  - effect@3.1.3\n  - @effect/platform@0.53.2\n  - @effect/printer@0.33.12\n  - @effect/printer-ansi@0.33.12\n  - @effect/schema@0.66.16\n\n## 0.36.20\n\n### Patch Changes\n\n- Updated dependencies [[`121d6d9`](https://github.com/Effect-TS/effect/commit/121d6d93755138c7510ba3ab4f0019ec0cb91890)]:\n  - @effect/schema@0.66.15\n  - @effect/platform@0.53.1\n\n## 0.36.19\n\n### Patch Changes\n\n- Updated dependencies [[`d57fbbb`](https://github.com/Effect-TS/effect/commit/d57fbbbd6c466936213a671fc3cd2390064f864e)]:\n  - @effect/platform@0.53.0\n\n## 0.36.18\n\n### Patch Changes\n\n- Updated dependencies [[`5866c62`](https://github.com/Effect-TS/effect/commit/5866c621d7eb4cc84e4ba972bfdfd219734cd45d)]:\n  - @effect/platform@0.52.3\n\n## 0.36.17\n\n### Patch Changes\n\n- Updated dependencies [[`2e1cdf6`](https://github.com/Effect-TS/effect/commit/2e1cdf67d141281288fffe9a5c10d1379a800513)]:\n  - @effect/platform@0.52.2\n  - effect@3.1.2\n  - @effect/schema@0.66.14\n  - @effect/printer@0.33.11\n  - @effect/printer-ansi@0.33.11\n\n## 0.36.16\n\n### Patch Changes\n\n- Updated dependencies [[`e5e56d1`](https://github.com/Effect-TS/effect/commit/e5e56d138dbed3204636f605229c6685f89659fc)]:\n  - effect@3.1.1\n  - @effect/platform@0.52.1\n  - @effect/printer@0.33.10\n  - @effect/printer-ansi@0.33.10\n  - @effect/schema@0.66.13\n\n## 0.36.15\n\n### Patch Changes\n\n- Updated dependencies [[`9deab0a`](https://github.com/Effect-TS/effect/commit/9deab0aec9e99501f9441843e34df9afa10c5be9), [`7719b8a`](https://github.com/Effect-TS/effect/commit/7719b8a7350c14e952ffe685bfd5308773b3e271)]:\n  - @effect/platform@0.52.0\n\n## 0.36.14\n\n### Patch Changes\n\n- Updated dependencies [[`c3c12c6`](https://github.com/Effect-TS/effect/commit/c3c12c6625633fe80e79f9db75a3b8cf8ca8b11d), [`ba64ea6`](https://github.com/Effect-TS/effect/commit/ba64ea6757810c5e74cad3863a7d19d4d38af66b), [`b5de2d2`](https://github.com/Effect-TS/effect/commit/b5de2d2ce5b1afe8be90827bf898a95cec40eb2b), [`a1c7ab8`](https://github.com/Effect-TS/effect/commit/a1c7ab8ffedacd18c1fc784f4ff5844f79498b83), [`a023f28`](https://github.com/Effect-TS/effect/commit/a023f28336f3865687d9a30c1883e36909906d85), [`0ec93cb`](https://github.com/Effect-TS/effect/commit/0ec93cb4f166e7401c171c2f8e8276ce958d9a57), [`1c9454d`](https://github.com/Effect-TS/effect/commit/1c9454d532eae79b9f759aea77f59332cc6d18ed), [`a023f28`](https://github.com/Effect-TS/effect/commit/a023f28336f3865687d9a30c1883e36909906d85), [`92d56db`](https://github.com/Effect-TS/effect/commit/92d56dbb3f33e36636c2a2f1030c56492e39cf4d)]:\n  - effect@3.1.0\n  - @effect/platform@0.51.0\n  - @effect/printer@0.33.9\n  - @effect/printer-ansi@0.33.9\n  - @effect/schema@0.66.12\n\n## 0.36.13\n\n### Patch Changes\n\n- [#2656](https://github.com/Effect-TS/effect/pull/2656) [`557707b`](https://github.com/Effect-TS/effect/commit/557707bc9e5f230c8964d2757012075c34339b5c) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n- Updated dependencies [[`16039a0`](https://github.com/Effect-TS/effect/commit/16039a08f04f11545e2fdf40952788a8f9cef04f), [`557707b`](https://github.com/Effect-TS/effect/commit/557707bc9e5f230c8964d2757012075c34339b5c), [`d1d33e1`](https://github.com/Effect-TS/effect/commit/d1d33e10b25109f44b5ab1c6e4d778a59c0d3eeb), [`f4ed306`](https://github.com/Effect-TS/effect/commit/f4ed3068a70b50302d078a30d18ca3cfd2bc679c), [`661004f`](https://github.com/Effect-TS/effect/commit/661004f4bf5f8b25f5a0678c21a3a822188ce461), [`e79cb83`](https://github.com/Effect-TS/effect/commit/e79cb83d3b19098bc40a3012e2a059b8426306c2)]:\n  - @effect/platform@0.50.8\n  - effect@3.0.8\n  - @effect/schema@0.66.11\n  - @effect/printer@0.33.8\n  - @effect/printer-ansi@0.33.8\n\n## 0.36.12\n\n### Patch Changes\n\n- Updated dependencies [[`18de56b`](https://github.com/Effect-TS/effect/commit/18de56b4a6b6d1f99230dfabf9147d59ea4dd759)]:\n  - effect@3.0.7\n  - @effect/platform@0.50.7\n  - @effect/printer@0.33.7\n  - @effect/printer-ansi@0.33.7\n  - @effect/schema@0.66.10\n\n## 0.36.11\n\n### Patch Changes\n\n- Updated dependencies [[`ffe4f4e`](https://github.com/Effect-TS/effect/commit/ffe4f4e95db35fff6869e360b072e3837befa0a1), [`027418e`](https://github.com/Effect-TS/effect/commit/027418edaa6aa6c0ae4861b95832827b45adace4), [`ac1898e`](https://github.com/Effect-TS/effect/commit/ac1898eb7bc96880f911c276048e2ea3d6fe9c50), [`ffe4f4e`](https://github.com/Effect-TS/effect/commit/ffe4f4e95db35fff6869e360b072e3837befa0a1), [`8206529`](https://github.com/Effect-TS/effect/commit/8206529d6a7bbf3e3c6f670afb0381e83176736e)]:\n  - effect@3.0.6\n  - @effect/schema@0.66.9\n  - @effect/platform@0.50.6\n  - @effect/printer@0.33.6\n  - @effect/printer-ansi@0.33.6\n\n## 0.36.10\n\n### Patch Changes\n\n- Updated dependencies [[`6222404`](https://github.com/Effect-TS/effect/commit/62224044678751829ed2f128e05133a91c6b0569), [`868ed2a`](https://github.com/Effect-TS/effect/commit/868ed2a8fe94ee7f4206a6070f29dcf2a5ba1dc3)]:\n  - effect@3.0.5\n  - @effect/platform@0.50.5\n  - @effect/printer@0.33.5\n  - @effect/printer-ansi@0.33.5\n  - @effect/schema@0.66.8\n\n## 0.36.9\n\n### Patch Changes\n\n- Updated dependencies [[`dd41c6c`](https://github.com/Effect-TS/effect/commit/dd41c6c725b1c1c980683275d8fa69779902187e), [`9a24667`](https://github.com/Effect-TS/effect/commit/9a246672008a2b668d43fbfd2fe5508c54b2b920)]:\n  - @effect/schema@0.66.7\n  - effect@3.0.4\n  - @effect/platform@0.50.4\n  - @effect/printer@0.33.4\n  - @effect/printer-ansi@0.33.4\n\n## 0.36.8\n\n### Patch Changes\n\n- Updated dependencies [[`9dfc156`](https://github.com/Effect-TS/effect/commit/9dfc156dc13fb4da9c777aae3acece4b5ecf0064), [`80271bd`](https://github.com/Effect-TS/effect/commit/80271bdc648e9efa659ce66b2c255754a6a1a8b0), [`b3b51a2`](https://github.com/Effect-TS/effect/commit/b3b51a2ea0c6ab92a363db46ebaa7e1176d089f5), [`e4ba97d`](https://github.com/Effect-TS/effect/commit/e4ba97d060c16bdf4e3b5bd5db6777f121a6768c)]:\n  - @effect/schema@0.66.6\n  - @effect/platform@0.50.3\n\n## 0.36.7\n\n### Patch Changes\n\n- Updated dependencies [[`b3fe829`](https://github.com/Effect-TS/effect/commit/b3fe829e8b12726afe94086b5375968f41a26411), [`a58b7de`](https://github.com/Effect-TS/effect/commit/a58b7deb8bb1d3b0dd636decf5d16f115f37eb72), [`d90e8c3`](https://github.com/Effect-TS/effect/commit/d90e8c3090cbc78e2bc7b51c974df66ffefacdfa)]:\n  - @effect/schema@0.66.5\n  - @effect/platform@0.50.2\n\n## 0.36.6\n\n### Patch Changes\n\n- Updated dependencies [[`773b8e0`](https://github.com/Effect-TS/effect/commit/773b8e01521e8fa7c38ff15d92d21d6fd6dad56f)]:\n  - @effect/schema@0.66.4\n  - @effect/platform@0.50.1\n\n## 0.36.5\n\n### Patch Changes\n\n- Updated dependencies [[`6f38dff`](https://github.com/Effect-TS/effect/commit/6f38dff41ffa34532cc2f25b90446550c5730bb6), [`a7b4b84`](https://github.com/Effect-TS/effect/commit/a7b4b84bd5a25f51aba922f9259c3a58c98c6a4e), [`a3b0e6c`](https://github.com/Effect-TS/effect/commit/a3b0e6c490772e6d44b5d98dcf2729c4d5310ecc), [`6f38dff`](https://github.com/Effect-TS/effect/commit/6f38dff41ffa34532cc2f25b90446550c5730bb6)]:\n  - @effect/platform@0.50.0\n  - effect@3.0.3\n  - @effect/printer@0.33.3\n  - @effect/printer-ansi@0.33.3\n  - @effect/schema@0.66.3\n\n## 0.36.4\n\n### Patch Changes\n\n- [#2562](https://github.com/Effect-TS/effect/pull/2562) [`2cecdbd`](https://github.com/Effect-TS/effect/commit/2cecdbd1cf30befce4e84796ccd953ea55ecfb86) Thanks [@fubhy](https://github.com/fubhy)! - Added provenance publishing\n\n- Updated dependencies [[`2cecdbd`](https://github.com/Effect-TS/effect/commit/2cecdbd1cf30befce4e84796ccd953ea55ecfb86)]:\n  - @effect/printer-ansi@0.33.2\n  - @effect/platform@0.49.4\n  - @effect/printer@0.33.2\n  - effect@3.0.2\n  - @effect/schema@0.66.2\n\n## 0.36.3\n\n### Patch Changes\n\n- Updated dependencies [[`8d39d65`](https://github.com/Effect-TS/effect/commit/8d39d6554af548228ad767112ce2e0b1f68fa8e1)]:\n  - @effect/platform@0.49.3\n\n## 0.36.2\n\n### Patch Changes\n\n- Updated dependencies [[`5ef0a1a`](https://github.com/Effect-TS/effect/commit/5ef0a1ae9b773fa2481550cb0d43ff7a0e03cd44)]:\n  - @effect/platform@0.49.2\n\n## 0.36.1\n\n### Patch Changes\n\n- [#2555](https://github.com/Effect-TS/effect/pull/2555) [`8edacca`](https://github.com/Effect-TS/effect/commit/8edacca37f8e37c01a63fec332b06d9361efaa7b) Thanks [@tim-smart](https://github.com/tim-smart)! - prevent use of `Array` as import name to solve bundler issues\n\n- Updated dependencies [[`3da0cfa`](https://github.com/Effect-TS/effect/commit/3da0cfa12c407fd930dc480be1ecc9217a8058f8), [`570e8d8`](https://github.com/Effect-TS/effect/commit/570e8d87e7c0e9ad4cd2686462fdb9b4812f7716), [`b2b5d66`](https://github.com/Effect-TS/effect/commit/b2b5d6626b18eb5289f364ffab5240e84b04d085), [`87c5687`](https://github.com/Effect-TS/effect/commit/87c5687de0782dab177b7861217fa3b040046282), [`8edacca`](https://github.com/Effect-TS/effect/commit/8edacca37f8e37c01a63fec332b06d9361efaa7b)]:\n  - effect@3.0.1\n  - @effect/schema@0.66.1\n  - @effect/platform@0.49.1\n  - @effect/printer-ansi@0.33.1\n  - @effect/printer@0.33.1\n\n## 0.36.0\n\n### Minor Changes\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`5a2314b`](https://github.com/Effect-TS/effect/commit/5a2314b70ec79c2c02b51cef45a5ddec8327daa1) Thanks [@github-actions](https://github.com/apps/github-actions)! - replace use of `unit` terminology with `void`\n\n  For all the data types.\n\n  ```ts\n  Effect.unit // => Effect.void\n  Stream.unit // => Stream.void\n\n  // etc\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`2fb7d9c`](https://github.com/Effect-TS/effect/commit/2fb7d9ca15037ff62a578bb9fe5732da5f4f317d) Thanks [@github-actions](https://github.com/apps/github-actions)! - Release Effect 3.0 🎉\n\n### Patch Changes\n\n- [#2529](https://github.com/Effect-TS/effect/pull/2529) [`78b767c`](https://github.com/Effect-TS/effect/commit/78b767c2b1625186e17131761a0edbac25d21850) Thanks [@fubhy](https://github.com/fubhy)! - Renamed `ReadonlyArray` and `ReadonlyRecord` modules for better discoverability.\n\n- Updated dependencies [[`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`d50a652`](https://github.com/Effect-TS/effect/commit/d50a652479f4d1d64f48da05c79fa847e6e51548), [`9aeae46`](https://github.com/Effect-TS/effect/commit/9aeae461fdf9265389cf3dfe4e428b037215ba5f), [`9a3bd47`](https://github.com/Effect-TS/effect/commit/9a3bd47ebd0750c7e498162734f6d21895de0cb2), [`6460414`](https://github.com/Effect-TS/effect/commit/6460414351a45fb8e0a457c63f3653422efee766), [`cf69f46`](https://github.com/Effect-TS/effect/commit/cf69f46690058d71eeada03cfb40dc744573e9e4), [`cf69f46`](https://github.com/Effect-TS/effect/commit/cf69f46690058d71eeada03cfb40dc744573e9e4), [`e542371`](https://github.com/Effect-TS/effect/commit/e542371981f8b4b484979feaad8a25b1f45e2df0), [`be9d025`](https://github.com/Effect-TS/effect/commit/be9d025e42355260ace02dd135851a8935a4deba), [`78b767c`](https://github.com/Effect-TS/effect/commit/78b767c2b1625186e17131761a0edbac25d21850), [`aa4a3b5`](https://github.com/Effect-TS/effect/commit/aa4a3b550da1c1020265ac389ed3f309388994a2), [`1499974`](https://github.com/Effect-TS/effect/commit/14999741d2e19c1747f6a7e19d68977f6429cdb8), [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`5c2b561`](https://github.com/Effect-TS/effect/commit/5c2b5614f583b88784ed68126ae939832fb3c092), [`6c6087a`](https://github.com/Effect-TS/effect/commit/6c6087a4a897b64252346426660782d31c13f769), [`a18f594`](https://github.com/Effect-TS/effect/commit/a18f5948f1439a147232448b2c443472fda0eceb), [`1499974`](https://github.com/Effect-TS/effect/commit/14999741d2e19c1747f6a7e19d68977f6429cdb8), [`2f96d93`](https://github.com/Effect-TS/effect/commit/2f96d938b90f8c19377583279e3c7afd9b509c50), [`5a2314b`](https://github.com/Effect-TS/effect/commit/5a2314b70ec79c2c02b51cef45a5ddec8327daa1), [`25d74f8`](https://github.com/Effect-TS/effect/commit/25d74f8c4d2dd4a9e5ec57ce2f20d36dedd25343), [`6c6087a`](https://github.com/Effect-TS/effect/commit/6c6087a4a897b64252346426660782d31c13f769), [`271b79f`](https://github.com/Effect-TS/effect/commit/271b79fc0b66a6c11e07a8779ff8800493a7eac2), [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`2fb7d9c`](https://github.com/Effect-TS/effect/commit/2fb7d9ca15037ff62a578bb9fe5732da5f4f317d), [`53d1c2a`](https://github.com/Effect-TS/effect/commit/53d1c2a77559081fbb89667e343346375c6d6650), [`e7e1bbe`](https://github.com/Effect-TS/effect/commit/e7e1bbe68486fdf31c8f84b0880522d39adcaad3), [`10c169e`](https://github.com/Effect-TS/effect/commit/10c169eadc874e91b4defca3f467b4e6a50fd8f3), [`6424181`](https://github.com/Effect-TS/effect/commit/64241815fe6a939e91e6947253e7dceea1306aa8)]:\n  - effect@3.0.0\n  - @effect/schema@0.66.0\n  - @effect/platform@0.49.0\n  - @effect/printer-ansi@0.33.0\n  - @effect/printer@0.33.0\n\n## 0.35.31\n\n### Patch Changes\n\n- Updated dependencies [[`b79cc59`](https://github.com/Effect-TS/effect/commit/b79cc59dbe64b9a0a7742dc9100a9d36c8e46b72)]:\n  - @effect/platform@0.48.29\n\n## 0.35.30\n\n### Patch Changes\n\n- Updated dependencies [[`0aee906`](https://github.com/Effect-TS/effect/commit/0aee906f034539344db6fbac08919de3e28eccde), [`41c8102`](https://github.com/Effect-TS/effect/commit/41c810228b1a50e4b41f19e735d7c62fe8d36871), [`4c37001`](https://github.com/Effect-TS/effect/commit/4c370013417e18c4f564818de1341a8fccb43b4c), [`776ef2b`](https://github.com/Effect-TS/effect/commit/776ef2bb66db9aa9f68b7beab14f6986f9c1288b), [`217147e`](https://github.com/Effect-TS/effect/commit/217147ea67c5c42c96f024775c41e5b070f81e4c), [`8a69b4e`](https://github.com/Effect-TS/effect/commit/8a69b4ef6a3a06d2e21fe2e11a626038beefb4e1), [`90776ec`](https://github.com/Effect-TS/effect/commit/90776ec8e8671d835b65fc33ead1de6c864b81b9), [`b3acf47`](https://github.com/Effect-TS/effect/commit/b3acf47f9c9dfae1c99377aa906097aaa2d47d44), [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55), [`232c353`](https://github.com/Effect-TS/effect/commit/232c353c2e6f743f38e57639ee30e324ffa9c2a9), [`0d3231a`](https://github.com/Effect-TS/effect/commit/0d3231a195202635ecc0bf6bbf6a08fc017d0d69), [`0ca835c`](https://github.com/Effect-TS/effect/commit/0ca835cbac8e69072a93ace83b534219faba24e8), [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55), [`d590094`](https://github.com/Effect-TS/effect/commit/d5900943489ec1e0891836aeafb5ce99fb9c75c7), [`c22b019`](https://github.com/Effect-TS/effect/commit/c22b019e5eaf9d3a937a3d99cadbb8f8e9116a70), [`e983740`](https://github.com/Effect-TS/effect/commit/e9837401145605aff5bc2ec7e73004f397c5d2d1), [`e3e0924`](https://github.com/Effect-TS/effect/commit/e3e09247d46a35430fc60e4aa4032cc50814f212)]:\n  - @effect/schema@0.65.0\n  - effect@2.4.19\n  - @effect/platform@0.48.28\n  - @effect/printer@0.32.4\n  - @effect/printer-ansi@0.32.28\n\n## 0.35.29\n\n### Patch Changes\n\n- Updated dependencies [[`c6dd3c6`](https://github.com/Effect-TS/effect/commit/c6dd3c6909cafe05adc8450c5a499260e17e60d3), [`672f137`](https://github.com/Effect-TS/effect/commit/672f13747ddf6dac3ba304fd4511b1df44ab566d), [`42b3651`](https://github.com/Effect-TS/effect/commit/42b36519f356bae9258a1ea1d416e2902b973e85), [`672f137`](https://github.com/Effect-TS/effect/commit/672f13747ddf6dac3ba304fd4511b1df44ab566d)]:\n  - @effect/platform@0.48.27\n  - @effect/schema@0.64.20\n\n## 0.35.28\n\n### Patch Changes\n\n- Updated dependencies [[`365a486`](https://github.com/Effect-TS/effect/commit/365a4865de5e47ce09f4cfd51fc0f67438f82a57)]:\n  - @effect/platform@0.48.26\n\n## 0.35.27\n\n### Patch Changes\n\n- Updated dependencies [[`dadc690`](https://github.com/Effect-TS/effect/commit/dadc6906121c512bc32be22b52adbd1ada834594), [`58f66fe`](https://github.com/Effect-TS/effect/commit/58f66fecd4e646c6c8f10995df9faab17022eb8f), [`3cad21d`](https://github.com/Effect-TS/effect/commit/3cad21daa5d2332d33692498c87b7ffff979e304), [`d209171`](https://github.com/Effect-TS/effect/commit/d2091714a786820ebae4bef04a9d67d25dd08e88)]:\n  - effect@2.4.18\n  - @effect/schema@0.64.19\n  - @effect/platform@0.48.25\n  - @effect/printer@0.32.3\n  - @effect/printer-ansi@0.32.27\n\n## 0.35.26\n\n### Patch Changes\n\n- Updated dependencies [[`9c6a500`](https://github.com/Effect-TS/effect/commit/9c6a5001b467b6255c68a922f4b6e8d692b63d01), [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`607b2e7`](https://github.com/Effect-TS/effect/commit/607b2e7a7fd9318c57acf4e50ec61747eea74ad7), [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`35ad0ba`](https://github.com/Effect-TS/effect/commit/35ad0ba9f3ba27c60453620e514b980f819f92af), [`8206caf`](https://github.com/Effect-TS/effect/commit/8206caf7c2d22c68be4313318b61cfdacf6222b6), [`7ddd654`](https://github.com/Effect-TS/effect/commit/7ddd65415b65ccb654ad04f4dbefe39402f15117), [`7ddd654`](https://github.com/Effect-TS/effect/commit/7ddd65415b65ccb654ad04f4dbefe39402f15117), [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`f456ba2`](https://github.com/Effect-TS/effect/commit/f456ba273bae21a6dcf8c966c50c97b5f0897d9f)]:\n  - @effect/platform@0.48.24\n  - effect@2.4.17\n  - @effect/printer@0.32.2\n  - @effect/printer-ansi@0.32.26\n  - @effect/schema@0.64.18\n\n## 0.35.25\n\n### Patch Changes\n\n- Updated dependencies [[`5170ce7`](https://github.com/Effect-TS/effect/commit/5170ce708c606283e8a30d273950f1a21c7eddc2), [`63a1df2`](https://github.com/Effect-TS/effect/commit/63a1df2e4de3766f48f15676fbd0360ab9c27816), [`5170ce7`](https://github.com/Effect-TS/effect/commit/5170ce708c606283e8a30d273950f1a21c7eddc2), [`62a7f23`](https://github.com/Effect-TS/effect/commit/62a7f23937c0dfaca67a7b2f055b85cfde25ed11), [`7cc2b41`](https://github.com/Effect-TS/effect/commit/7cc2b41d6c551fdca2590b06681c5ad9832aba46), [`74a5dae`](https://github.com/Effect-TS/effect/commit/74a5daed0e65b32a36e026bfcf66d02269cb967a), [`8b46fde`](https://github.com/Effect-TS/effect/commit/8b46fdebf2c075a74cd2cd29dfb69531d20fc154)]:\n  - @effect/platform@0.48.23\n  - effect@2.4.16\n  - @effect/schema@0.64.17\n  - @effect/printer@0.32.1\n  - @effect/printer-ansi@0.32.25\n\n## 0.35.24\n\n### Patch Changes\n\n- Updated dependencies [[`a31917a`](https://github.com/Effect-TS/effect/commit/a31917aa4b05b1189b7a8e0bedb60bb3d49262ad), [`4cd2bed`](https://github.com/Effect-TS/effect/commit/4cd2bedf978f864bddd289d1c524c8e868bf587b), [`6cc6267`](https://github.com/Effect-TS/effect/commit/6cc6267026d9bfb1a9882cddf534787327e86ec1)]:\n  - @effect/schema@0.64.16\n  - @effect/platform@0.48.22\n\n## 0.35.23\n\n### Patch Changes\n\n- Updated dependencies [[`d7688c0`](https://github.com/Effect-TS/effect/commit/d7688c0c72717fe7876c871567f6946dabfc0546), [`b3a4fac`](https://github.com/Effect-TS/effect/commit/b3a4face2acaca422f0b0530436e8f13129f3b3a), [`0dd62a7`](https://github.com/Effect-TS/effect/commit/0dd62a701934b44c4c78e2d7878afdccfe414c39), [`5ded019`](https://github.com/Effect-TS/effect/commit/5ded019970169e3c1f2a375d0876b95fb1ff67f5), [`0dd62a7`](https://github.com/Effect-TS/effect/commit/0dd62a701934b44c4c78e2d7878afdccfe414c39), [`0dd62a7`](https://github.com/Effect-TS/effect/commit/0dd62a701934b44c4c78e2d7878afdccfe414c39)]:\n  - effect@2.4.15\n  - @effect/printer@0.32.0\n  - @effect/schema@0.64.15\n  - @effect/printer-ansi@0.32.24\n  - @effect/platform@0.48.21\n\n## 0.35.22\n\n### Patch Changes\n\n- Updated dependencies [[`4789083`](https://github.com/Effect-TS/effect/commit/4789083283bdaec456982d614ebc4a496ea0e7f7), [`4789083`](https://github.com/Effect-TS/effect/commit/4789083283bdaec456982d614ebc4a496ea0e7f7)]:\n  - @effect/platform@0.48.20\n\n## 0.35.21\n\n### Patch Changes\n\n- Updated dependencies [[`fb7285e`](https://github.com/Effect-TS/effect/commit/fb7285e8d6a70527df7137a6a3efdd03ae61cb8b)]:\n  - @effect/platform@0.48.19\n\n## 0.35.20\n\n### Patch Changes\n\n- Updated dependencies [[`26435ec`](https://github.com/Effect-TS/effect/commit/26435ecfa06569dc18d1801ccf38213a43b7c334), [`a76e5e1`](https://github.com/Effect-TS/effect/commit/a76e5e131a35c88a72771fb745df08f60fbc0e18), [`6180c0c`](https://github.com/Effect-TS/effect/commit/6180c0cc51dee785cfce72220a52c9fc3b9bf9aa)]:\n  - @effect/platform@0.48.18\n  - @effect/schema@0.64.14\n  - effect@2.4.14\n  - @effect/printer@0.31.23\n  - @effect/printer-ansi@0.32.23\n\n## 0.35.19\n\n### Patch Changes\n\n- Updated dependencies [[`47a8f1b`](https://github.com/Effect-TS/effect/commit/47a8f1b644d8294692d92cacd3c8c7543edbfabe), [`8c9abe2`](https://github.com/Effect-TS/effect/commit/8c9abe2b35c46d8891d4b2c14ff9eb46302a14f3), [`8c9abe2`](https://github.com/Effect-TS/effect/commit/8c9abe2b35c46d8891d4b2c14ff9eb46302a14f3), [`3336287`](https://github.com/Effect-TS/effect/commit/3336287ff55a25e56d759b83847bfaa21c40f499), [`54b7c00`](https://github.com/Effect-TS/effect/commit/54b7c0077fa784ad2646b812d6a44641f672edcd), [`3336287`](https://github.com/Effect-TS/effect/commit/3336287ff55a25e56d759b83847bfaa21c40f499), [`47a8f1b`](https://github.com/Effect-TS/effect/commit/47a8f1b644d8294692d92cacd3c8c7543edbfabe)]:\n  - @effect/platform@0.48.17\n  - effect@2.4.13\n  - @effect/printer@0.31.22\n  - @effect/printer-ansi@0.32.22\n  - @effect/schema@0.64.13\n\n## 0.35.18\n\n### Patch Changes\n\n- [#2385](https://github.com/Effect-TS/effect/pull/2385) [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87) Thanks [@tim-smart](https://github.com/tim-smart)! - update typescript to 5.4\n\n- Updated dependencies [[`9392de6`](https://github.com/Effect-TS/effect/commit/9392de6baa6861662abc2bd3171897145f5ea073), [`75a8d16`](https://github.com/Effect-TS/effect/commit/75a8d16247cc14860cdd7fd948ef542c50c2d55e), [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87), [`9392de6`](https://github.com/Effect-TS/effect/commit/9392de6baa6861662abc2bd3171897145f5ea073), [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87), [`d17a427`](https://github.com/Effect-TS/effect/commit/d17a427c4427972fb55c45a058780716dc408631)]:\n  - @effect/schema@0.64.12\n  - @effect/platform@0.48.16\n  - effect@2.4.12\n  - @effect/printer@0.31.21\n  - @effect/printer-ansi@0.32.21\n\n## 0.35.17\n\n### Patch Changes\n\n- [#2384](https://github.com/Effect-TS/effect/pull/2384) [`2f488c4`](https://github.com/Effect-TS/effect/commit/2f488c436de52576562803c57ebc132ef40ccdd8) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n- Updated dependencies [[`2f488c4`](https://github.com/Effect-TS/effect/commit/2f488c436de52576562803c57ebc132ef40ccdd8), [`37ca592`](https://github.com/Effect-TS/effect/commit/37ca592a4101ad90adbf8c8b3f727faf3110cae5), [`317b5b8`](https://github.com/Effect-TS/effect/commit/317b5b8e8c8c2207469b3ebfcf72bf3a9f7cbc60)]:\n  - effect@2.4.11\n  - @effect/schema@0.64.11\n  - @effect/platform@0.48.15\n  - @effect/printer@0.31.20\n  - @effect/printer-ansi@0.32.20\n\n## 0.35.16\n\n### Patch Changes\n\n- Updated dependencies [[`9bab1f9`](https://github.com/Effect-TS/effect/commit/9bab1f9fa5b999740755e4e82485cb77c638643a), [`9bbde5b`](https://github.com/Effect-TS/effect/commit/9bbde5be9a0168d1c2a0308bfc27167ed62f3968)]:\n  - effect@2.4.10\n  - @effect/platform@0.48.14\n  - @effect/printer@0.31.19\n  - @effect/printer-ansi@0.32.19\n  - @effect/schema@0.64.10\n\n## 0.35.15\n\n### Patch Changes\n\n- Updated dependencies [[`dc7e497`](https://github.com/Effect-TS/effect/commit/dc7e49720df416870a7483f48adc40aeb23fe32d), [`ffaf7c3`](https://github.com/Effect-TS/effect/commit/ffaf7c36514f88496cdd2fdfdf0bc7ba5a2e5cd4)]:\n  - @effect/schema@0.64.9\n  - @effect/platform@0.48.13\n\n## 0.35.14\n\n### Patch Changes\n\n- Updated dependencies [[`e0af20e`](https://github.com/Effect-TS/effect/commit/e0af20ec5f6d0b19d66c5ebf610969d55bfc6c22)]:\n  - @effect/schema@0.64.8\n  - @effect/platform@0.48.12\n\n## 0.35.13\n\n### Patch Changes\n\n- Updated dependencies [[`0f6c7b4`](https://github.com/Effect-TS/effect/commit/0f6c7b426eb3432f60e3a17f8cd92ceac91597bf)]:\n  - @effect/platform@0.48.11\n\n## 0.35.12\n\n### Patch Changes\n\n- Updated dependencies [[`71fd528`](https://github.com/Effect-TS/effect/commit/71fd5287500f9ce155a7d9f0df6ee3e0ac3aeb99)]:\n  - @effect/platform@0.48.10\n  - effect@2.4.9\n  - @effect/printer@0.31.18\n  - @effect/printer-ansi@0.32.18\n  - @effect/schema@0.64.7\n\n## 0.35.11\n\n### Patch Changes\n\n- [#2352](https://github.com/Effect-TS/effect/pull/2352) [`63f8372`](https://github.com/Effect-TS/effect/commit/63f83722b137e2ab7fdf8ef947c65ed107221353) Thanks [@tim-smart](https://github.com/tim-smart)! - remove use of `__proto__`\n\n- Updated dependencies [[`595140a`](https://github.com/Effect-TS/effect/commit/595140a13bda09bf22c669196440868e8a274599), [`5f5fcd9`](https://github.com/Effect-TS/effect/commit/5f5fcd969ae30ed6fe61d566a571498d9e895e16), [`bb0b69e`](https://github.com/Effect-TS/effect/commit/bb0b69e519698c7c76aa68217de423c78ad16566), [`7a45ad0`](https://github.com/Effect-TS/effect/commit/7a45ad0a5f715d64a69b28a8ee3573e5f86909c3), [`5c3b1cc`](https://github.com/Effect-TS/effect/commit/5c3b1ccba182d0f636a973729f9c6bfb12539dc8), [`6f7dfc9`](https://github.com/Effect-TS/effect/commit/6f7dfc9637bd641beb93b14e027dcfcb5d2c8feb), [`88b8583`](https://github.com/Effect-TS/effect/commit/88b85838e03d4f33036f9d16c9c00a487fa99bd8), [`cb20824`](https://github.com/Effect-TS/effect/commit/cb20824416cbf251188395d0aad3622e3a5d7ff2), [`6b20bad`](https://github.com/Effect-TS/effect/commit/6b20badebb3a7ca4d38857753e8ecaa09d02ccfb), [`4e64e9b`](https://github.com/Effect-TS/effect/commit/4e64e9b9876de6bfcbabe39e18a91a08e5f3fbb0), [`3851a02`](https://github.com/Effect-TS/effect/commit/3851a022c481006aec1db36651e4b4fd727aa742), [`5f5fcd9`](https://github.com/Effect-TS/effect/commit/5f5fcd969ae30ed6fe61d566a571498d9e895e16), [`814e5b8`](https://github.com/Effect-TS/effect/commit/814e5b828f68210b9e8f336fd6ac688646835dd9), [`a45a525`](https://github.com/Effect-TS/effect/commit/a45a525e7ccf07704dff1666f1e390282b5bac91)]:\n  - @effect/schema@0.64.6\n  - effect@2.4.8\n  - @effect/platform@0.48.9\n  - @effect/printer@0.31.17\n  - @effect/printer-ansi@0.32.17\n\n## 0.35.10\n\n### Patch Changes\n\n- Updated dependencies [[`69d27bb`](https://github.com/Effect-TS/effect/commit/69d27bb633884b6b50f9c3d9e95c29f09b4860b5), [`d0f56c6`](https://github.com/Effect-TS/effect/commit/d0f56c68e604b1cf8dd4e761a3f3cf3631b3cec1)]:\n  - @effect/platform@0.48.8\n  - @effect/schema@0.64.5\n\n## 0.35.9\n\n### Patch Changes\n\n- Updated dependencies [[`f908948`](https://github.com/Effect-TS/effect/commit/f908948fd05771a670c0b746e2dd9caa9408ef83)]:\n  - @effect/platform@0.48.7\n\n## 0.35.8\n\n### Patch Changes\n\n- Updated dependencies [[`eb93283`](https://github.com/Effect-TS/effect/commit/eb93283985913d7b04ca750e36ac8513e7b6cef6)]:\n  - effect@2.4.7\n  - @effect/platform@0.48.6\n  - @effect/printer@0.31.16\n  - @effect/printer-ansi@0.32.16\n  - @effect/schema@0.64.4\n\n## 0.35.7\n\n### Patch Changes\n\n- Updated dependencies [[`e006e4a`](https://github.com/Effect-TS/effect/commit/e006e4a538c97bae6ca1efa74802159e8a688fcb)]:\n  - @effect/platform@0.48.5\n\n## 0.35.6\n\n### Patch Changes\n\n- Updated dependencies [[`cfef6ec`](https://github.com/Effect-TS/effect/commit/cfef6ecd1fe801cec1a3cbfb7f064fc394b0ad73)]:\n  - @effect/schema@0.64.3\n  - @effect/platform@0.48.4\n\n## 0.35.5\n\n### Patch Changes\n\n- Updated dependencies [[`c362e06`](https://github.com/Effect-TS/effect/commit/c362e066550252d5a9fcbc31a4b34d0e17c50699), [`83ddd6f`](https://github.com/Effect-TS/effect/commit/83ddd6f41029724b2cbd144cf309463967ed1164)]:\n  - @effect/platform@0.48.3\n\n## 0.35.4\n\n### Patch Changes\n\n- Updated dependencies [[`89748c9`](https://github.com/Effect-TS/effect/commit/89748c90b36cb5eb880a9ab9323b252338dee848), [`4f35a7e`](https://github.com/Effect-TS/effect/commit/4f35a7e7c4eba598924aff24d1158b9056bb24be), [`9971186`](https://github.com/Effect-TS/effect/commit/99711862722188fbb5ed3ee75126ad5edf13f72f)]:\n  - @effect/schema@0.64.2\n  - @effect/platform@0.48.2\n  - effect@2.4.6\n  - @effect/printer@0.31.15\n  - @effect/printer-ansi@0.32.15\n\n## 0.35.3\n\n### Patch Changes\n\n- Updated dependencies [[`d10f876`](https://github.com/Effect-TS/effect/commit/d10f876cd98da275bc5dc5750a91a7fc95e97541), [`743ae6d`](https://github.com/Effect-TS/effect/commit/743ae6d12b249f0b35b31b65b2f7ec91d83ee387), [`a75bc48`](https://github.com/Effect-TS/effect/commit/a75bc48e0e3278d0f70665fedecc5ae7ec447e24), [`bce21c5`](https://github.com/Effect-TS/effect/commit/bce21c5ded2177114666ba229bd5029fa000dee3), [`c7d3036`](https://github.com/Effect-TS/effect/commit/c7d303630b7f0825cb2e584557c5767a67214d9f)]:\n  - @effect/schema@0.64.1\n  - effect@2.4.5\n  - @effect/platform@0.48.1\n  - @effect/printer@0.31.14\n  - @effect/printer-ansi@0.32.14\n\n## 0.35.2\n\n### Patch Changes\n\n- Updated dependencies [[`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949), [`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949), [`1cb7f9c`](https://github.com/Effect-TS/effect/commit/1cb7f9cff7c2272a32fc7a324d87b02e2cd8a2f5), [`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949), [`817a04c`](https://github.com/Effect-TS/effect/commit/817a04cb2df0f4140984dc97eb3e1bb14a6c4a38), [`d90a99d`](https://github.com/Effect-TS/effect/commit/d90a99d03d074adc7cd2533f15419138264da5a2), [`dd05faa`](https://github.com/Effect-TS/effect/commit/dd05faa621555ef3585ecd914ac13ecd89b710f4), [`509be1a`](https://github.com/Effect-TS/effect/commit/509be1a0817118489750cf028523134677e44a8a), [`1cb7f9c`](https://github.com/Effect-TS/effect/commit/1cb7f9cff7c2272a32fc7a324d87b02e2cd8a2f5), [`dd05faa`](https://github.com/Effect-TS/effect/commit/dd05faa621555ef3585ecd914ac13ecd89b710f4), [`e7ca973`](https://github.com/Effect-TS/effect/commit/e7ca973c5430ae60716701e58bedd4632ff971fd), [`a1f44cb`](https://github.com/Effect-TS/effect/commit/a1f44cb5112713ff9a3ac3d91a63a2c99d6b7fc1), [`d910dd2`](https://github.com/Effect-TS/effect/commit/d910dd2ca1e8e5aa2f09d9bf3694ede745758f99), [`e7ca973`](https://github.com/Effect-TS/effect/commit/e7ca973c5430ae60716701e58bedd4632ff971fd), [`802674b`](https://github.com/Effect-TS/effect/commit/802674b379b7559ad3ff09b33388891445a9e48b), [`bdff193`](https://github.com/Effect-TS/effect/commit/bdff193365dd9ec2863573b08eb960aa8dee5c93)]:\n  - @effect/schema@0.64.0\n  - effect@2.4.4\n  - @effect/platform@0.48.0\n  - @effect/printer@0.31.13\n  - @effect/printer-ansi@0.32.13\n\n## 0.35.1\n\n### Patch Changes\n\n- Updated dependencies [[`0680545`](https://github.com/Effect-TS/effect/commit/068054540f19bb23a79c7c021ed8b2fe34f3e19f), [`20e63fb`](https://github.com/Effect-TS/effect/commit/20e63fb9207210f3fe2d136ec40d0a2dbff3225e), [`20e63fb`](https://github.com/Effect-TS/effect/commit/20e63fb9207210f3fe2d136ec40d0a2dbff3225e)]:\n  - @effect/platform@0.47.1\n  - effect@2.4.3\n  - @effect/printer@0.31.12\n  - @effect/printer-ansi@0.32.12\n  - @effect/schema@0.63.4\n\n## 0.35.0\n\n### Minor Changes\n\n- [#2240](https://github.com/Effect-TS/effect/pull/2240) [`0c2da75`](https://github.com/Effect-TS/effect/commit/0c2da75f4964338d1165e7f51e33c2795d16c8de) Thanks [@ccntrq](https://github.com/ccntrq)! - Remove duplicate 'should' in wizard mode prompt for variadic arguments\n\n- [#2252](https://github.com/Effect-TS/effect/pull/2252) [`89b5d1c`](https://github.com/Effect-TS/effect/commit/89b5d1c4bbd05ef9558272eba80c6f5b0707c562) Thanks [@ccntrq](https://github.com/ccntrq)! - Print unknown argument errors\n\n### Patch Changes\n\n- Updated dependencies [[`e03811e`](https://github.com/Effect-TS/effect/commit/e03811e80c93e986e6348b3b67ac2ed6d5fefff0), [`ac41d84`](https://github.com/Effect-TS/effect/commit/ac41d84776484cdce8165b7ca2c9c9b6377eee2d), [`0f3d99c`](https://github.com/Effect-TS/effect/commit/0f3d99c27521ec6b221b644a0fffc79199c3acca), [`6137533`](https://github.com/Effect-TS/effect/commit/613753300c7705518ab1fea2f370b032851c2750), [`f373529`](https://github.com/Effect-TS/effect/commit/f373529999f4b8bc92b634f6ea14f19271388eed), [`1bf9f31`](https://github.com/Effect-TS/effect/commit/1bf9f31f07667de677673f7c29a4e7a26ebad3c8), [`e3ff789`](https://github.com/Effect-TS/effect/commit/e3ff789226f89e71eb28ca38ce79f90af6a03f1a), [`6137533`](https://github.com/Effect-TS/effect/commit/613753300c7705518ab1fea2f370b032851c2750), [`507ba40`](https://github.com/Effect-TS/effect/commit/507ba4060ff043c1a8d541dae723fa6940633b00), [`4064ea0`](https://github.com/Effect-TS/effect/commit/4064ea04e0b3fa23108ee471cd89ab2482b2f6e5), [`e466afe`](https://github.com/Effect-TS/effect/commit/e466afe32f2de598ceafd8982bd0cfbd388e5671), [`465be79`](https://github.com/Effect-TS/effect/commit/465be7926afe98169837d8a4ed5ebc059a732d21), [`f373529`](https://github.com/Effect-TS/effect/commit/f373529999f4b8bc92b634f6ea14f19271388eed), [`de74eb8`](https://github.com/Effect-TS/effect/commit/de74eb80a79eebde5ff645033765e7a617e92f27), [`d8e6940`](https://github.com/Effect-TS/effect/commit/d8e694040f67da6fefc0f5c98fc8e15c0b48822e), [`fa9663c`](https://github.com/Effect-TS/effect/commit/fa9663cb854ca03dba672d7857ecff84f1140c9e), [`fa9663c`](https://github.com/Effect-TS/effect/commit/fa9663cb854ca03dba672d7857ecff84f1140c9e)]:\n  - effect@2.4.2\n  - @effect/platform@0.47.0\n  - @effect/schema@0.63.3\n  - @effect/printer@0.31.11\n  - @effect/printer-ansi@0.32.11\n\n## 0.34.3\n\n### Patch Changes\n\n- Updated dependencies [[`a4a0006`](https://github.com/Effect-TS/effect/commit/a4a0006c7f19fc261df5cda16963d73457e4d6ac), [`7535080`](https://github.com/Effect-TS/effect/commit/7535080f2e2f9859711031161600c01807cc43ea), [`39f583e`](https://github.com/Effect-TS/effect/commit/39f583eaeb29eecd6eaec3b113b24d9d413153df), [`f428198`](https://github.com/Effect-TS/effect/commit/f428198725d4b9e304ecd5ff8bad8f92d871dbe3), [`0a37676`](https://github.com/Effect-TS/effect/commit/0a37676aa0eb2a21e17af2e6df9f81f52bbc8831), [`bd1d7ac`](https://github.com/Effect-TS/effect/commit/bd1d7ac75eea57a94d5e2d8e1edccb3136e84899), [`c035972`](https://github.com/Effect-TS/effect/commit/c035972dfabdd3cb3372b5ab468aa2fd0d808f4d), [`6f503b7`](https://github.com/Effect-TS/effect/commit/6f503b774d893bf2af34f66202e270d8c45d5f31)]:\n  - effect@2.4.1\n  - @effect/platform@0.46.3\n  - @effect/schema@0.63.2\n  - @effect/printer@0.31.10\n  - @effect/printer-ansi@0.32.10\n\n## 0.34.2\n\n### Patch Changes\n\n- Updated dependencies [[`5d30853`](https://github.com/Effect-TS/effect/commit/5d308534cac6f187227185393c0bac9eb27f90ab), [`6e350ed`](https://github.com/Effect-TS/effect/commit/6e350ed611feb0341e00aafd3c3905cd5ba53f07)]:\n  - @effect/schema@0.63.1\n  - @effect/platform@0.46.2\n\n## 0.34.1\n\n### Patch Changes\n\n- Updated dependencies [[`aa6556f`](https://github.com/Effect-TS/effect/commit/aa6556f007117caea84d6965aa30846a11879e9d)]:\n  - @effect/platform@0.46.1\n\n## 0.34.0\n\n### Minor Changes\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`a025b12`](https://github.com/Effect-TS/effect/commit/a025b121235ba01cfce8d62a775491880c575561) Thanks [@github-actions](https://github.com/apps/github-actions)! - Swap type params of Either from `Either<E, A>` to `Either<R, L = never>`.\n\n  Along the same line of the other changes this allows to shorten the most common types such as:\n\n  ```ts\n  import { Either } from \"effect\"\n\n  const right: Either.Either<string> = Either.right(\"ok\")\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2), [`489fcf3`](https://github.com/Effect-TS/effect/commit/489fcf363ff2b2a953166b740cb9a62d7fc2a101), [`7d9c3bf`](https://github.com/Effect-TS/effect/commit/7d9c3bff6c18d451e0e4781042945ec5c7be1b9f), [`d8d278b`](https://github.com/Effect-TS/effect/commit/d8d278b2efb2966947029885e01f7b68348a021f), [`14c5711`](https://github.com/Effect-TS/effect/commit/14c57110078f0862b8da5c7a2c5d980f54447484), [`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2), [`54ddbb7`](https://github.com/Effect-TS/effect/commit/54ddbb720aeeb657537b01ae221cdcd5e919c1a6), [`b9cb3a9`](https://github.com/Effect-TS/effect/commit/b9cb3a9c9bfdd75536bd70b4e8b557c12d4923ff), [`585fcce`](https://github.com/Effect-TS/effect/commit/585fcce162d0f07a48d7cd984a9b722966fbebbe), [`93b412d`](https://github.com/Effect-TS/effect/commit/93b412d4a9ed762dc9fa5807e51fad0fc78a614a), [`55b26a6`](https://github.com/Effect-TS/effect/commit/55b26a6342b4826f1116e7a1eb660118c274458e), [`136ef40`](https://github.com/Effect-TS/effect/commit/136ef40fe4a394abfa5c6a7ec103eea57251423e), [`a025b12`](https://github.com/Effect-TS/effect/commit/a025b121235ba01cfce8d62a775491880c575561), [`2097739`](https://github.com/Effect-TS/effect/commit/20977393d2383bff709304e81ec7d51cafd57108), [`f24ac9f`](https://github.com/Effect-TS/effect/commit/f24ac9f0c2c520add58f09fbdcec5defda03bd52)]:\n  - effect@2.4.0\n  - @effect/platform@0.46.0\n  - @effect/schema@0.63.0\n  - @effect/printer@0.31.9\n  - @effect/printer-ansi@0.32.9\n\n## 0.33.14\n\n### Patch Changes\n\n- [#2187](https://github.com/Effect-TS/effect/pull/2187) [`e6d36c0`](https://github.com/Effect-TS/effect/commit/e6d36c0813d836f17eabb6a9c7849baffca12dbf) Thanks [@tim-smart](https://github.com/tim-smart)! - update development dependencies\n\n- Updated dependencies [[`5ad2eec`](https://github.com/Effect-TS/effect/commit/5ad2eece0280b6db6a749d25cac1dcf6d33659a9), [`e6d36c0`](https://github.com/Effect-TS/effect/commit/e6d36c0813d836f17eabb6a9c7849baffca12dbf)]:\n  - effect@2.3.8\n  - @effect/schema@0.62.9\n  - @effect/platform@0.45.6\n  - @effect/printer@0.31.8\n  - @effect/printer-ansi@0.32.8\n\n## 0.33.13\n\n### Patch Changes\n\n- [#2175](https://github.com/Effect-TS/effect/pull/2175) [`bbb097b`](https://github.com/Effect-TS/effect/commit/bbb097b767013bd5be0d17162e391d614ff4b23e) Thanks [@IMax153](https://github.com/IMax153)! - Ensure wizard mode does not prompt further for 0 input to variadic arg / option\n\n- [#2175](https://github.com/Effect-TS/effect/pull/2175) [`bbb097b`](https://github.com/Effect-TS/effect/commit/bbb097b767013bd5be0d17162e391d614ff4b23e) Thanks [@IMax153](https://github.com/IMax153)! - Fix the display of CLI wizard mode to show the root command name and not the current executable\n\n- Updated dependencies [[`6daf084`](https://github.com/Effect-TS/effect/commit/6daf0845de008772011db8d7c75b7c37a6b4d334)]:\n  - @effect/platform@0.45.5\n\n## 0.33.12\n\n### Patch Changes\n\n- [#2173](https://github.com/Effect-TS/effect/pull/2173) [`cbd1a5a`](https://github.com/Effect-TS/effect/commit/cbd1a5a3c47a37f9ee842446d5d66086693c2a74) Thanks [@IMax153](https://github.com/IMax153)! - Fixes the root command name in generated shell completion scripts\n\n- Updated dependencies [[`bc8404d`](https://github.com/Effect-TS/effect/commit/bc8404d54fd42072d200c0399cb39672837afa9f), [`abcb7d9`](https://github.com/Effect-TS/effect/commit/abcb7d983a4a85b43b7175e952f5b331b9019aea), [`2c5cbcd`](https://github.com/Effect-TS/effect/commit/2c5cbcd1161b4f40dab184999291e817314107de), [`6565916`](https://github.com/Effect-TS/effect/commit/6565916ef254bf910e47d25fd0ef55e7cb420241), [`abcb7d9`](https://github.com/Effect-TS/effect/commit/abcb7d983a4a85b43b7175e952f5b331b9019aea)]:\n  - effect@2.3.7\n  - @effect/platform@0.45.4\n  - @effect/printer@0.31.7\n  - @effect/printer-ansi@0.32.7\n  - @effect/schema@0.62.8\n\n## 0.33.11\n\n### Patch Changes\n\n- Updated dependencies [[`09532a8`](https://github.com/Effect-TS/effect/commit/09532a86b7d0cc23557c89158f0342753dfce4b0)]:\n  - @effect/platform@0.45.3\n\n## 0.33.10\n\n### Patch Changes\n\n- Updated dependencies [[`b1163b2`](https://github.com/Effect-TS/effect/commit/b1163b2bd67b65bafbbb39fc4c67576e5cbaf444), [`b46b869`](https://github.com/Effect-TS/effect/commit/b46b869e59a6da5aa235a9fcc25e1e0d24e9e8f8), [`dbff62c`](https://github.com/Effect-TS/effect/commit/dbff62c3026054350a671f6210058ec5844c285e), [`de1b226`](https://github.com/Effect-TS/effect/commit/de1b226282b5ab6c2809dd93f3bdb066f24a1333), [`a663390`](https://github.com/Effect-TS/effect/commit/a66339090ae7b960f8a8b90a0dcdc505de5aaf3e), [`ff88f80`](https://github.com/Effect-TS/effect/commit/ff88f808c4ed9947a148045849e7410b00acad0a), [`11be07b`](https://github.com/Effect-TS/effect/commit/11be07bf65d82cfdf994cdb9d8ca937f995cb4f0), [`c568645`](https://github.com/Effect-TS/effect/commit/c5686451c87d26382135a1c63b00ef171bb24f62), [`88835e5`](https://github.com/Effect-TS/effect/commit/88835e575a0bfbeff9a3696a332f32192c940e12), [`e572b07`](https://github.com/Effect-TS/effect/commit/e572b076e9b4369d9cc8e55414006eef376c93d9), [`e787a57`](https://github.com/Effect-TS/effect/commit/e787a5772e30d8b840cb98b49d36996e7d659a6c), [`b415577`](https://github.com/Effect-TS/effect/commit/b415577f6c576073733929c858e5aac27b6d5880), [`ff8046f`](https://github.com/Effect-TS/effect/commit/ff8046f57dfd073eba60ce6d3144ab060fbf93ce), [`44c3b43`](https://github.com/Effect-TS/effect/commit/44c3b43653e64d7e425d39815d8ff405acec9b99)]:\n  - effect@2.3.6\n  - @effect/schema@0.62.7\n  - @effect/platform@0.45.2\n  - @effect/printer@0.31.6\n  - @effect/printer-ansi@0.32.6\n\n## 0.33.9\n\n### Patch Changes\n\n- Updated dependencies [[`65895ab`](https://github.com/Effect-TS/effect/commit/65895ab982e0917ac92f0827e387e7cf61be1e69)]:\n  - @effect/platform@0.45.1\n\n## 0.33.8\n\n### Patch Changes\n\n- Updated dependencies [[`2b62548`](https://github.com/Effect-TS/effect/commit/2b6254845882f399636d24223c483e5489e3cff4)]:\n  - @effect/platform@0.45.0\n\n## 0.33.7\n\n### Patch Changes\n\n- Updated dependencies [[`aef2b8b`](https://github.com/Effect-TS/effect/commit/aef2b8bb636ada07224dc9cf491bebe622c1aeda), [`b881365`](https://github.com/Effect-TS/effect/commit/b8813650355322ea2fc1fbaa4f846bd87a7a05f3), [`7eecb1c`](https://github.com/Effect-TS/effect/commit/7eecb1c6cebe36550df3cca85a46867adbcaa2ca)]:\n  - @effect/schema@0.62.6\n  - effect@2.3.5\n  - @effect/platform@0.44.7\n  - @effect/printer@0.31.5\n  - @effect/printer-ansi@0.32.5\n\n## 0.33.6\n\n### Patch Changes\n\n- Updated dependencies [[`17bda66`](https://github.com/Effect-TS/effect/commit/17bda66431c999a546920c10adb205e6c8bea7d1)]:\n  - effect@2.3.4\n  - @effect/platform@0.44.6\n  - @effect/printer@0.31.4\n  - @effect/printer-ansi@0.32.4\n  - @effect/schema@0.62.5\n\n## 0.33.5\n\n### Patch Changes\n\n- Updated dependencies [[`1c6d18b`](https://github.com/Effect-TS/effect/commit/1c6d18b422b0bd800f2ed036dba9cb78db296c03), [`13d3266`](https://github.com/Effect-TS/effect/commit/13d3266f331f7aa49b55dd244d4e749a82255274), [`a344b42`](https://github.com/Effect-TS/effect/commit/a344b420862f71532a28c72f00b7ba54776d744d)]:\n  - @effect/schema@0.62.4\n  - @effect/platform@0.44.5\n\n## 0.33.4\n\n### Patch Changes\n\n- Updated dependencies [[`efd41d8`](https://github.com/Effect-TS/effect/commit/efd41d8131c3d90867608969ef7c4eef490eb5e6), [`0f83515`](https://github.com/Effect-TS/effect/commit/0f83515a9c01d13c7c15a3f026e02d22c3c6bb7f), [`0f83515`](https://github.com/Effect-TS/effect/commit/0f83515a9c01d13c7c15a3f026e02d22c3c6bb7f)]:\n  - effect@2.3.3\n  - @effect/platform@0.44.4\n  - @effect/printer@0.31.3\n  - @effect/printer-ansi@0.32.3\n  - @effect/schema@0.62.3\n\n## 0.33.3\n\n### Patch Changes\n\n- Updated dependencies [[`6654f5f`](https://github.com/Effect-TS/effect/commit/6654f5f0f6b9d97165ede5e04ca16776e2599328), [`2eb11b4`](https://github.com/Effect-TS/effect/commit/2eb11b47752cedf233ef4c4395d9c4efc9b9e180), [`56c09bd`](https://github.com/Effect-TS/effect/commit/56c09bd369279a6a7785209d172739935818cba6), [`71aa5b1`](https://github.com/Effect-TS/effect/commit/71aa5b1c180dcb8b53aefe232d12a97bd06b5447), [`1700af8`](https://github.com/Effect-TS/effect/commit/1700af8af1131602887da721914c8562b6342393)]:\n  - effect@2.3.2\n  - @effect/platform@0.44.3\n  - @effect/printer@0.31.2\n  - @effect/printer-ansi@0.32.2\n  - @effect/schema@0.62.2\n\n## 0.33.2\n\n### Patch Changes\n\n- Updated dependencies [[`29739dd`](https://github.com/Effect-TS/effect/commit/29739dde8e6232824d49c4c7f8856de245249c5c)]:\n  - @effect/platform@0.44.2\n\n## 0.33.1\n\n### Patch Changes\n\n- Updated dependencies [[`b5a8215`](https://github.com/Effect-TS/effect/commit/b5a8215ee2a97a8865d69ee55ce1b9835948c922)]:\n  - effect@2.3.1\n  - @effect/platform@0.44.1\n  - @effect/printer@0.31.1\n  - @effect/printer-ansi@0.32.1\n  - @effect/schema@0.62.1\n\n## 0.33.0\n\n### Minor Changes\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c) Thanks [@github-actions](https://github.com/apps/github-actions)! - With this change we now require a string key to be provided for all tags and renames the dear old `Tag` to `GenericTag`, so when previously you could do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  interface Service {\n    readonly _: unique symbol\n  }\n  const Service = Context.Tag<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >()\n  ```\n\n  you are now mandated to do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  interface Service {\n    readonly _: unique symbol\n  }\n  const Service = Context.GenericTag<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >(\"Service\")\n  ```\n\n  This makes by default all tags globals and ensures better debuggaility when unexpected errors arise.\n\n  Furthermore we introduce a new way of constructing tags that should be considered the new default:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  class Service extends Context.Tag(\"Service\")<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >() {}\n\n  const program = Effect.flatMap(Service, ({ number }) => number).pipe(\n    Effect.flatMap((_) => Effect.log(`number: ${_}`))\n  )\n  ```\n\n  this will use \"Service\" as the key and will create automatically an opaque identifier (the class) to be used at the type level, it does something similar to the above in a single shot.\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`1a77f72`](https://github.com/Effect-TS/effect/commit/1a77f72cdaf43d6cdc91b6060f82832edcdbbcb3) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Effect` type parameters order from `Effect<R, E, A>` to `Effect<A, E = never, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`a34dbdc`](https://github.com/Effect-TS/effect/commit/a34dbdc1552c73c1b612676f262a0c735ce444a7) Thanks [@github-actions](https://github.com/apps/github-actions)! - - Schema: change type parameters order from `Schema<R, I, A>` to `Schema<A, I = A, R = never>`\n  - Serializable: change type parameters order from `Serializable<R, I, A>` to `Serializable<A, I, R>`\n  - Class: change type parameters order from `Class<R, I, A, C, Self, Inherited>` to `Class<A, I, R, C, Self, Inherited>`\n  - PropertySignature: change type parameters order from `PropertySignature<R, From, FromIsOptional, To, ToIsOptional>` to `PropertySignature<From, FromIsOptional, To, ToIsOptional, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`b1e2086`](https://github.com/Effect-TS/effect/commit/b1e2086ea8bf410e4ad75d71c0760825924e8f9f) Thanks [@github-actions](https://github.com/apps/github-actions)! - remove re-exports from platform packages\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`02c3461`](https://github.com/Effect-TS/effect/commit/02c34615d02f91269ea04036d0306fccf4e39e18) Thanks [@github-actions](https://github.com/apps/github-actions)! - With this change we remove the `Data.Data` type and we make `Equal.Equal` & `Hash.Hash` implicit traits.\n\n  The main reason is that `Data.Data<A>` was structurally equivalent to `A & Equal.Equal` but extending `Equal.Equal` doesn't mean that the equality is implemented by-value, so the type was simply adding noise without gaining any level of safety.\n\n  The module `Data` remains unchanged at the value level, all the functions previously available are supposed to work in exactly the same manner.\n\n  At the type level instead the functions return `Readonly` variants, so for example we have:\n\n  ```ts\n  import { Data } from \"effect\"\n\n  const obj = Data.struct({\n    a: 0,\n    b: 1\n  })\n  ```\n\n  will have the `obj` typed as:\n\n  ```ts\n  declare const obj: {\n    readonly a: number\n    readonly b: number\n  }\n  ```\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c) Thanks [@github-actions](https://github.com/apps/github-actions)! - This change enables `Effect.serviceConstants` and `Effect.serviceMembers` to access any constant in the service, not only the effects, namely it is now possible to do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n\n  class NumberRepo extends Context.TagClass(\"NumberRepo\")<\n    NumberRepo,\n    {\n      readonly numbers: Array<number>\n    }\n  >() {\n    static numbers = Effect.serviceConstants(NumberRepo).numbers\n  }\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`b1e2086`](https://github.com/Effect-TS/effect/commit/b1e2086ea8bf410e4ad75d71c0760825924e8f9f), [`4cd6e14`](https://github.com/Effect-TS/effect/commit/4cd6e144945b6c398f5f5abe3471ff7fb3372bfd), [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`c77f635`](https://github.com/Effect-TS/effect/commit/c77f635f8a26ca6d83cb569d911f8eee79033fd9), [`e343a74`](https://github.com/Effect-TS/effect/commit/e343a74843dd9edf879417fa94cb51de7ed5b402), [`acf1894`](https://github.com/Effect-TS/effect/commit/acf1894f45945dbe5c39451e36aabb4b5092f257), [`9dc04c8`](https://github.com/Effect-TS/effect/commit/9dc04c88a2ea9c68122cb2632a76f0f4be40329a), [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c), [`1a77f72`](https://github.com/Effect-TS/effect/commit/1a77f72cdaf43d6cdc91b6060f82832edcdbbcb3), [`af47aa3`](https://github.com/Effect-TS/effect/commit/af47aa37196ad542c9c23a4896d8ef98147e1205), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`c986f0e`](https://github.com/Effect-TS/effect/commit/c986f0e0ce4d22ba08177ed351152718479ab63c), [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`70dde23`](https://github.com/Effect-TS/effect/commit/70dde238f81125e353fd7bde5fc24ecd8969bf97), [`a34dbdc`](https://github.com/Effect-TS/effect/commit/a34dbdc1552c73c1b612676f262a0c735ce444a7), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`81b7425`](https://github.com/Effect-TS/effect/commit/81b7425320cbbe2a6cf547a3e3ab3549cdba14cf), [`b1e2086`](https://github.com/Effect-TS/effect/commit/b1e2086ea8bf410e4ad75d71c0760825924e8f9f), [`02c3461`](https://github.com/Effect-TS/effect/commit/02c34615d02f91269ea04036d0306fccf4e39e18), [`0e56e99`](https://github.com/Effect-TS/effect/commit/0e56e998ab9815c4d096c239a553cb86a0f99af9), [`8b0ded9`](https://github.com/Effect-TS/effect/commit/8b0ded9f10ba0d96fcb9af24eff2dbd9341f85e3), [`8dd83e8`](https://github.com/Effect-TS/effect/commit/8dd83e854bfcaa6dab876994c5f813dcfb486c28), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e), [`d75f6fe`](https://github.com/Effect-TS/effect/commit/d75f6fe6499deb0a5ee9ec94af3b5fd4eb03a2d0), [`7356e5c`](https://github.com/Effect-TS/effect/commit/7356e5cc16e9d70f18c02dee1dcb4ad539fd130a), [`3077cde`](https://github.com/Effect-TS/effect/commit/3077cde08a60246821a940964a84dd7f7c8b9f54), [`be19ce0`](https://github.com/Effect-TS/effect/commit/be19ce0b8bdf1fac80bb8d7e0b06a86986b47409), [`4a5d01a`](https://github.com/Effect-TS/effect/commit/4a5d01a409e9b6dd53893e65f8e5c9247f568021), [`78f47ab`](https://github.com/Effect-TS/effect/commit/78f47abfe3cb0a8bbde818b1c5fc603270538b47), [`6361ee2`](https://github.com/Effect-TS/effect/commit/6361ee2e83bdfead24045c3d058a7298efc18113), [`52e5d20`](https://github.com/Effect-TS/effect/commit/52e5d2077582bf51f25861c7139fc920c2c24166), [`c6137ec`](https://github.com/Effect-TS/effect/commit/c6137ec62c6b5542d5062ae1a3c936cb915dee22), [`86f665d`](https://github.com/Effect-TS/effect/commit/86f665d7bd25ba0a3f046a2384798378310dcf0c), [`f5ae081`](https://github.com/Effect-TS/effect/commit/f5ae08195e68e76faeac258c565d79da4e01e7d6), [`4a5d01a`](https://github.com/Effect-TS/effect/commit/4a5d01a409e9b6dd53893e65f8e5c9247f568021), [`60686f5`](https://github.com/Effect-TS/effect/commit/60686f5c38bef1b93a3a0dda9b6596d46aceab03), [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e), [`56b8691`](https://github.com/Effect-TS/effect/commit/56b86916bf3da18002f3655d859dbc487eb5a6de), [`8ee2931`](https://github.com/Effect-TS/effect/commit/8ee293159b4f7cb7af8558287a0a047f3a69743d), [`6727474`](https://github.com/Effect-TS/effect/commit/672747497490a30d36dd49c06db19aabf09dc7f0), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e)]:\n  - effect@2.3.0\n  - @effect/platform@0.44.0\n  - @effect/schema@0.62.0\n  - @effect/printer-ansi@0.32.0\n  - @effect/printer@0.31.0\n\n## 0.32.2\n\n### Patch Changes\n\n- Updated dependencies [[`3ddfdbf`](https://github.com/Effect-TS/effect/commit/3ddfdbf914edea536aef207cec6695f33496258c), [`3ddfdbf`](https://github.com/Effect-TS/effect/commit/3ddfdbf914edea536aef207cec6695f33496258c)]:\n  - effect@2.2.5\n  - @effect/platform@0.43.11\n  - @effect/printer@0.30.14\n  - @effect/printer-ansi@0.31.14\n  - @effect/schema@0.61.7\n\n## 0.32.1\n\n### Patch Changes\n\n- Updated dependencies [[`d0b911c`](https://github.com/Effect-TS/effect/commit/d0b911c75f284c7aa87f25aa96926e6bde7690d0), [`330e1a4`](https://github.com/Effect-TS/effect/commit/330e1a4e2c1fc0af6c80c80c81dd38c3e50fab78), [`6928a2b`](https://github.com/Effect-TS/effect/commit/6928a2b0bae86a4bdfbece0aa32924207c2d5a70), [`296bc1c`](https://github.com/Effect-TS/effect/commit/296bc1c9d24986d299d2669115d584cb27b73c60)]:\n  - effect@2.2.4\n  - @effect/platform@0.43.10\n  - @effect/schema@0.61.6\n  - @effect/printer@0.30.13\n  - @effect/printer-ansi@0.31.13\n\n## 0.32.0\n\n### Minor Changes\n\n- [#2047](https://github.com/Effect-TS/effect/pull/2047) [`eb1f787`](https://github.com/Effect-TS/effect/commit/eb1f7878c9e5f52f17fa4ed8a13151ab70df6b12) Thanks [@tim-smart](https://github.com/tim-smart)! - make array types in cli more permissive\n\n  This change removes NonEmpty\\* arrays as input parameters, and removes use of ReadonlyArray as a return type (prefering Array instead).\n\n  This allows more interop with the existing js ecosystem.\n\n## 0.31.9\n\n### Patch Changes\n\n- Updated dependencies [[`1b841a9`](https://github.com/Effect-TS/effect/commit/1b841a91fed86825cd2867cf1e68e41d8ff26b4e)]:\n  - @effect/platform@0.43.9\n\n## 0.31.8\n\n### Patch Changes\n\n- Updated dependencies [[`32bf796`](https://github.com/Effect-TS/effect/commit/32bf796c3e5db1b2b68e8b1b20db664295991643)]:\n  - @effect/platform@0.43.8\n\n## 0.31.7\n\n### Patch Changes\n\n- Updated dependencies [[`cde08f3`](https://github.com/Effect-TS/effect/commit/cde08f354ed2ff2921d1d98bd539c7d65a2ddd73)]:\n  - @effect/platform@0.43.7\n\n## 0.31.6\n\n### Patch Changes\n\n- Updated dependencies [[`c96bb17`](https://github.com/Effect-TS/effect/commit/c96bb17043e2cec1eaeb319614a4c2904d876beb)]:\n  - @effect/platform@0.43.6\n\n## 0.31.5\n\n### Patch Changes\n\n- Updated dependencies [[`f1ff44b`](https://github.com/Effect-TS/effect/commit/f1ff44b58cdb1886b38681e8fedc309eb9ac6853), [`13785cf`](https://github.com/Effect-TS/effect/commit/13785cf4a5082d8d9cf8d7c991141dee0d2b4d31)]:\n  - @effect/schema@0.61.5\n  - @effect/platform@0.43.5\n\n## 0.31.4\n\n### Patch Changes\n\n- [#2001](https://github.com/Effect-TS/effect/pull/2001) [`aab2e4e`](https://github.com/Effect-TS/effect/commit/aab2e4e156207e0977c0529a7afdcae2992a08ff) Thanks [@IMax153](https://github.com/IMax153)! - ensure single invalid variadic option is reported as an error\n\n- Updated dependencies [[`22794e0`](https://github.com/Effect-TS/effect/commit/22794e0ba00e40281f30a22fa84412003c24877d), [`f73e6c0`](https://github.com/Effect-TS/effect/commit/f73e6c033fb0729a9cfa5eb4bc39f79d3126e247), [`6bf02c7`](https://github.com/Effect-TS/effect/commit/6bf02c70fe10a04d1b34d6666f95416e42a6225a), [`78f5921`](https://github.com/Effect-TS/effect/commit/78f59211502ded6fcbe15a49d6fde941cccc9d52)]:\n  - effect@2.2.3\n  - @effect/schema@0.61.4\n  - @effect/platform@0.43.4\n  - @effect/printer@0.30.12\n  - @effect/printer-ansi@0.31.12\n\n## 0.31.3\n\n### Patch Changes\n\n- [#1990](https://github.com/Effect-TS/effect/pull/1990) [`003bb69`](https://github.com/Effect-TS/effect/commit/003bb691f2059ef596121c78b556196f22ab2a1e) Thanks [@IMax153](https://github.com/IMax153)! - fix stack overflow exception when nesting cli options / args in a command config\n\n## 0.31.2\n\n### Patch Changes\n\n- Updated dependencies [[`9863e2f`](https://github.com/Effect-TS/effect/commit/9863e2fb3561dc019965aeccd6584a418fc8b401)]:\n  - @effect/schema@0.61.3\n  - @effect/platform@0.43.3\n\n## 0.31.1\n\n### Patch Changes\n\n- Updated dependencies [[`64f710a`](https://github.com/Effect-TS/effect/commit/64f710aa49dec6ffcd33ee23438d0774f5489733)]:\n  - @effect/schema@0.61.2\n  - @effect/platform@0.43.2\n\n## 0.31.0\n\n### Minor Changes\n\n- [#1984](https://github.com/Effect-TS/effect/pull/1984) [`eaab2e8`](https://github.com/Effect-TS/effect/commit/eaab2e81be72df9ded2e01e4c6d40b2bb159a349) Thanks [@IMax153](https://github.com/IMax153)! - default Options.repeated to return an empty array if option is not provided\n\n### Patch Changes\n\n- [#1980](https://github.com/Effect-TS/effect/pull/1980) [`9cf3782`](https://github.com/Effect-TS/effect/commit/9cf3782a17f38097f7b1a0024bd7ec7db8aeb2d0) Thanks [@IMax153](https://github.com/IMax153)! - fix CLI argument parsing to properly handle the case when a repeated option is not provided\n\n## 0.30.6\n\n### Patch Changes\n\n- Updated dependencies [[`c7550f9`](https://github.com/Effect-TS/effect/commit/c7550f96e1006eee832ce5025bf0c197a65935ea), [`8d1f6e4`](https://github.com/Effect-TS/effect/commit/8d1f6e4bb13e221804fb1762ef19e02bcefc8f61), [`d404561`](https://github.com/Effect-TS/effect/commit/d404561e47ec2fa5f68709a308ee5d2ee959141d), [`7b84a3c`](https://github.com/Effect-TS/effect/commit/7b84a3c7e4b9c8dc02294b0e3cc3ae3becea977b), [`1a84dee`](https://github.com/Effect-TS/effect/commit/1a84dee0e9ddbfaf2610e4d7c00c7020c427171a), [`ac30bf4`](https://github.com/Effect-TS/effect/commit/ac30bf4cd53de0663784f65ae6bee8279333df97)]:\n  - @effect/schema@0.61.1\n  - effect@2.2.2\n  - @effect/platform@0.43.1\n  - @effect/printer@0.30.11\n  - @effect/printer-ansi@0.31.11\n\n## 0.30.5\n\n### Patch Changes\n\n- [#1963](https://github.com/Effect-TS/effect/pull/1963) [`de4cb04`](https://github.com/Effect-TS/effect/commit/de4cb049a39923d673fa4acd3db62dd60d341887) Thanks [@IMax153](https://github.com/IMax153)! - fix the parsed letter case for variadic and key/value flags\n\n- [#1922](https://github.com/Effect-TS/effect/pull/1922) [`62b40e8`](https://github.com/Effect-TS/effect/commit/62b40e8479371d6663c0255aaca56a1ae0d59764) Thanks [@gcanti](https://github.com/gcanti)! - add context tracking to Schema, closes #1873\n\n- Updated dependencies [[`84da31f`](https://github.com/Effect-TS/effect/commit/84da31f0643e8651b9d311b30526b1e4edfbdfb8), [`62b40e8`](https://github.com/Effect-TS/effect/commit/62b40e8479371d6663c0255aaca56a1ae0d59764), [`645bea2`](https://github.com/Effect-TS/effect/commit/645bea2551129f94a5b0e38347e28067dee531bb), [`62b40e8`](https://github.com/Effect-TS/effect/commit/62b40e8479371d6663c0255aaca56a1ae0d59764)]:\n  - effect@2.2.1\n  - @effect/schema@0.61.0\n  - @effect/platform@0.43.0\n  - @effect/printer@0.30.10\n  - @effect/printer-ansi@0.31.10\n\n## 0.30.4\n\n### Patch Changes\n\n- Updated dependencies [[`202befc`](https://github.com/Effect-TS/effect/commit/202befc2ecbeb117c4fa85ef9b12a3d3a48273d2), [`fe05ad7`](https://github.com/Effect-TS/effect/commit/fe05ad7bcb3b88d47800ab69ebf53641023676f1), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`10df798`](https://github.com/Effect-TS/effect/commit/10df798639e556f9d88265ef7fc3cf8a3bbe3874)]:\n  - effect@2.2.0\n  - @effect/platform@0.42.7\n  - @effect/printer@0.30.9\n  - @effect/printer-ansi@0.31.9\n  - @effect/schema@0.60.7\n\n## 0.30.3\n\n### Patch Changes\n\n- Updated dependencies [[`21b9edd`](https://github.com/Effect-TS/effect/commit/21b9edde464f7c5624ef54ad1b5e264204a37625)]:\n  - effect@2.1.2\n  - @effect/platform@0.42.6\n  - @effect/printer@0.30.8\n  - @effect/printer-ansi@0.31.8\n  - @effect/schema@0.60.6\n\n## 0.30.2\n\n### Patch Changes\n\n- Updated dependencies [[`3bf67cf`](https://github.com/Effect-TS/effect/commit/3bf67cf64ff27ffaa811b07751875cb161ac3385)]:\n  - @effect/schema@0.60.5\n  - @effect/platform@0.42.5\n\n## 0.30.1\n\n### Patch Changes\n\n- [#1942](https://github.com/Effect-TS/effect/pull/1942) [`d21e028`](https://github.com/Effect-TS/effect/commit/d21e028fe2628b42e681eee641547b0bc01a70d1) Thanks [@tim-smart](https://github.com/tim-smart)! - fix Options.mapEffect export\n\n## 0.30.0\n\n### Minor Changes\n\n- [#1938](https://github.com/Effect-TS/effect/pull/1938) [`9a0d61f`](https://github.com/Effect-TS/effect/commit/9a0d61f674b70ff17c8bcffbd27fea9d5ec57857) Thanks [@IMax153](https://github.com/IMax153)! - rename mapOrFail to mapEffect for Command, Options, and Args modules\n\n## 0.29.0\n\n### Minor Changes\n\n- [#1925](https://github.com/Effect-TS/effect/pull/1925) [`86180cc`](https://github.com/Effect-TS/effect/commit/86180cc96102627a42397d2e4f84fb3a55c3038e) Thanks [@IMax153](https://github.com/IMax153)! - adds optional `executable` parameter to `CliApp.make`\n\n  **NOTE**: This means that users are no longer required to manually remove the executable from the CLI arguments (i.e. `process.argv.slice(2)`). The executable is stripped from the CLI arguments internally within `CliApp.make`, so all command-line arguments can be provided directly to the CLI application.\n\n### Patch Changes\n\n- Updated dependencies [[`0d1af1e`](https://github.com/Effect-TS/effect/commit/0d1af1e38c11b94e152beaccd0ff7569a1b3f5b7), [`0d1af1e`](https://github.com/Effect-TS/effect/commit/0d1af1e38c11b94e152beaccd0ff7569a1b3f5b7), [`a222524`](https://github.com/Effect-TS/effect/commit/a2225247e9de2e013d287320790fde88c081dbbd)]:\n  - @effect/schema@0.60.4\n  - effect@2.1.1\n  - @effect/platform@0.42.4\n  - @effect/printer@0.30.7\n  - @effect/printer-ansi@0.31.7\n\n## 0.28.9\n\n### Patch Changes\n\n- Updated dependencies [[`d543221`](https://github.com/Effect-TS/effect/commit/d5432213e91ab620aa66e0fd92a6593134d18940), [`2530d47`](https://github.com/Effect-TS/effect/commit/2530d470b0ad5df7e636921eedfb1cbe42821f94), [`f493929`](https://github.com/Effect-TS/effect/commit/f493929ab88d2ea137ca5fbff70bdc6c9d804d80), [`5911fa9`](https://github.com/Effect-TS/effect/commit/5911fa9c9440dd3bc1ee38542bcd15f8c75a4637)]:\n  - @effect/schema@0.60.3\n  - @effect/platform@0.42.3\n\n## 0.28.8\n\n### Patch Changes\n\n- Updated dependencies [[`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02)]:\n  - effect@2.1.0\n  - @effect/platform@0.42.2\n  - @effect/printer@0.30.6\n  - @effect/printer-ansi@0.31.6\n  - @effect/schema@0.60.2\n\n## 0.28.7\n\n### Patch Changes\n\n- Updated dependencies [[`f7f19f6`](https://github.com/Effect-TS/effect/commit/f7f19f66a5fa349baa2412c1f9f15111c437df09)]:\n  - effect@2.0.5\n  - @effect/platform@0.42.1\n  - @effect/printer@0.30.5\n  - @effect/printer-ansi@0.31.5\n  - @effect/schema@0.60.1\n\n## 0.28.6\n\n### Patch Changes\n\n- [#1907](https://github.com/Effect-TS/effect/pull/1907) [`d1c7cf5`](https://github.com/Effect-TS/effect/commit/d1c7cf54fd9c269cca57652391158b6f5ab19628) Thanks [@tim-smart](https://github.com/tim-smart)! - add ConfigFile module to cli\n\n- [#1899](https://github.com/Effect-TS/effect/pull/1899) [`4863253`](https://github.com/Effect-TS/effect/commit/4863253bfc07d43aec357d214d18879743549ac5) Thanks [@tim-smart](https://github.com/tim-smart)! - add file parsing apis to cli\n\n- [#1898](https://github.com/Effect-TS/effect/pull/1898) [`4ef1e6f`](https://github.com/Effect-TS/effect/commit/4ef1e6f4e0376532957208d3f4c82a8ed277ffd6) Thanks [@tim-smart](https://github.com/tim-smart)! - add Schema apis to cli Options & Args\n\n- Updated dependencies [[`ec2bdfa`](https://github.com/Effect-TS/effect/commit/ec2bdfae2da717f28147b9d6820d3494cb240945), [`687e02e`](https://github.com/Effect-TS/effect/commit/687e02e7d84dc06957844160761fda90929470ab), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`540b294`](https://github.com/Effect-TS/effect/commit/540b2941dd0a81e9688311583ce7e2e140d6e7a5), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`a3f96d6`](https://github.com/Effect-TS/effect/commit/a3f96d615b8b3e238dbfa01ef713c87e6f4532be), [`0c397e7`](https://github.com/Effect-TS/effect/commit/0c397e762008a0de40c7526c9d99ff2cfe4f7a6a), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`b557a10`](https://github.com/Effect-TS/effect/commit/b557a10b773e321bea77fc4951f0ef171dd193c9), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`74b9094`](https://github.com/Effect-TS/effect/commit/74b90940e571c73a6b76cafa88ffb8a1c949cb4c), [`337e80f`](https://github.com/Effect-TS/effect/commit/337e80f69bc36966f889c439b819db2f84cae496), [`25adce7`](https://github.com/Effect-TS/effect/commit/25adce7ae76ce834096dca1ed70a60ad1a349217), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`48a3d40`](https://github.com/Effect-TS/effect/commit/48a3d40aed0f923f567b8911dade732ff472d981)]:\n  - @effect/schema@0.60.0\n  - effect@2.0.4\n  - @effect/platform@0.42.0\n  - @effect/printer@0.30.4\n  - @effect/printer-ansi@0.31.4\n\n## 0.28.5\n\n### Patch Changes\n\n- Updated dependencies [[`5b46e99`](https://github.com/Effect-TS/effect/commit/5b46e996d30e2497eb23095e2c21eee04438edf5), [`87f7ef2`](https://github.com/Effect-TS/effect/commit/87f7ef28a3c27e2e4f2fcfa465f85bb2a45a3d6b), [`1d3a06b`](https://github.com/Effect-TS/effect/commit/1d3a06bb58ad1ac123ae8f9d42b4345f9c9c53c0), [`210d27e`](https://github.com/Effect-TS/effect/commit/210d27e999e066ea9b907301150c65f9ff080b39), [`1d3a06b`](https://github.com/Effect-TS/effect/commit/1d3a06bb58ad1ac123ae8f9d42b4345f9c9c53c0)]:\n  - @effect/schema@0.59.1\n  - effect@2.0.3\n  - @effect/platform@0.41.0\n  - @effect/printer@0.30.3\n  - @effect/printer-ansi@0.31.3\n\n## 0.28.4\n\n### Patch Changes\n\n- Updated dependencies [[`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f), [`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f), [`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f), [`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f)]:\n  - @effect/schema@0.59.0\n  - @effect/platform@0.40.4\n\n## 0.28.3\n\n### Patch Changes\n\n- Updated dependencies [[`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`a904a73`](https://github.com/Effect-TS/effect/commit/a904a739459bfd0fa7844b00b902d2fa984fb014), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`92c0322`](https://github.com/Effect-TS/effect/commit/92c0322a58bf7e5b8dbb602186030839e89df5af), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c)]:\n  - @effect/schema@0.58.0\n  - @effect/platform@0.40.3\n\n## 0.28.2\n\n### Patch Changes\n\n- Updated dependencies [[`4c90c54`](https://github.com/Effect-TS/effect/commit/4c90c54d87c91f75f3ad114926cdf3b0c25df091), [`d5a1949`](https://github.com/Effect-TS/effect/commit/d5a19499aac7c1d147674a35ac69992177c7536c), [`d3d3bda`](https://github.com/Effect-TS/effect/commit/d3d3bda74c794153def9027e0c40896e72cd5d14)]:\n  - @effect/platform@0.40.2\n  - effect@2.0.2\n  - @effect/printer@0.30.2\n  - @effect/printer-ansi@0.31.2\n  - @effect/schema@0.57.2\n\n## 0.28.1\n\n### Patch Changes\n\n- Updated dependencies [[`16bd87d`](https://github.com/Effect-TS/effect/commit/16bd87d32611b966dc42ea4fc979764f97a49071)]:\n  - effect@2.0.1\n  - @effect/platform@0.40.1\n  - @effect/printer@0.30.1\n  - @effect/printer-ansi@0.31.1\n  - @effect/schema@0.57.1\n\n## 0.28.0\n\n### Minor Changes\n\n- [`d0471ca`](https://github.com/Effect-TS/effect/commit/d0471ca7b544746674b9e1750202da72b0a21233) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Switch to monorepo structure\n\n- [#1846](https://github.com/Effect-TS/effect/pull/1846) [`693b8f3`](https://github.com/Effect-TS/effect/commit/693b8f3a3dfd43ae61f0d9292cdf356be7329f2f) Thanks [@fubhy](https://github.com/fubhy)! - Enabled `exactOptionalPropertyTypes` throughout\n\n### Patch Changes\n\n- [`d987daa`](https://github.com/Effect-TS/effect/commit/d987daafaddd43b6ade74916a08236c19ea0a9fa) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Switch effect dependency to caret\n\n- [#1848](https://github.com/Effect-TS/effect/pull/1848) [`04fb8b4`](https://github.com/Effect-TS/effect/commit/04fb8b428b19bba85a2c79910c5e363340d074e7) Thanks [@fubhy](https://github.com/fubhy)! - Avoid default parameter initilization\n\n- [#1853](https://github.com/Effect-TS/effect/pull/1853) [`78fec17`](https://github.com/Effect-TS/effect/commit/78fec17bf1210e3ce35b4e96f3a23cbef2f65c79) Thanks [@tim-smart](https://github.com/tim-smart)! - fix Args.optional returning Option\n\n- Updated dependencies [[`d987daa`](https://github.com/Effect-TS/effect/commit/d987daafaddd43b6ade74916a08236c19ea0a9fa), [`7b5eaa3`](https://github.com/Effect-TS/effect/commit/7b5eaa3838c79bf4bdccf91b94d61bbc38a2ec95), [`0724211`](https://github.com/Effect-TS/effect/commit/072421149c36010748ff6b6ee19c15c6cffefe09), [`9f2bc5a`](https://github.com/Effect-TS/effect/commit/9f2bc5a19e0b678a0a85e84daac290922b0fd57d), [`04fb8b4`](https://github.com/Effect-TS/effect/commit/04fb8b428b19bba85a2c79910c5e363340d074e7), [`d0471ca`](https://github.com/Effect-TS/effect/commit/d0471ca7b544746674b9e1750202da72b0a21233), [`bcf0900`](https://github.com/Effect-TS/effect/commit/bcf0900b58f449262556f80bff21e771a37272aa), [`6299b84`](https://github.com/Effect-TS/effect/commit/6299b84c11e5d1fe79fa538df8935018c7613747), [`c0aeb5e`](https://github.com/Effect-TS/effect/commit/c0aeb5e302869bcd7d7627f8cc5b630d07c12d10), [`693b8f3`](https://github.com/Effect-TS/effect/commit/693b8f3a3dfd43ae61f0d9292cdf356be7329f2f)]:\n  - @effect/printer-ansi@0.31.0\n  - @effect/platform@0.40.0\n  - @effect/printer@0.30.0\n  - @effect/schema@0.57.0\n  - effect@2.0.0\n\n## 0.27.0\n\n### Minor Changes\n\n- [#432](https://github.com/Effect-TS/cli/pull/432) [`66fe7a0`](https://github.com/Effect-TS/cli/commit/66fe7a078ce3fa9d9fa412599fb6a9d416d7fd03) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.26.0\n\n### Minor Changes\n\n- [#430](https://github.com/Effect-TS/cli/pull/430) [`859b1e7`](https://github.com/Effect-TS/cli/commit/859b1e7cdb8b454ef3d6514889a0e1dc9b24966f) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.25.4\n\n### Patch Changes\n\n- [#428](https://github.com/Effect-TS/cli/pull/428) [`ff2d006`](https://github.com/Effect-TS/cli/commit/ff2d006495fa317a53763302846ebce0cd9a620b) Thanks [@tim-smart](https://github.com/tim-smart)! - fix for multiple handler transforms\n\n## 0.25.3\n\n### Patch Changes\n\n- [#426](https://github.com/Effect-TS/cli/pull/426) [`5ac4637`](https://github.com/Effect-TS/cli/commit/5ac4637c37b779363115afb94b477e5f7558cf6b) Thanks [@tim-smart](https://github.com/tim-smart)! - add Command.provideSync\n\n- [#426](https://github.com/Effect-TS/cli/pull/426) [`5ac4637`](https://github.com/Effect-TS/cli/commit/5ac4637c37b779363115afb94b477e5f7558cf6b) Thanks [@tim-smart](https://github.com/tim-smart)! - add Command.provideEffect\n\n## 0.25.2\n\n### Patch Changes\n\n- [#424](https://github.com/Effect-TS/cli/pull/424) [`960cc02`](https://github.com/Effect-TS/cli/commit/960cc02998c177462b22c566d714b8114a5a1cff) Thanks [@tim-smart](https://github.com/tim-smart)! - update /platform\n\n## 0.25.1\n\n### Patch Changes\n\n- [#422](https://github.com/Effect-TS/cli/pull/422) [`ca7dcd5`](https://github.com/Effect-TS/cli/commit/ca7dcd5fe5cc23527639e971d19d13e555912a37) Thanks [@tim-smart](https://github.com/tim-smart)! - add Command.withHandler,transformHandler,provide,provideEffectDiscard\n\n## 0.25.0\n\n### Minor Changes\n\n- [#417](https://github.com/Effect-TS/cli/pull/417) [`486dcdd`](https://github.com/Effect-TS/cli/commit/486dcddf60ee603fb02ca30d09e984826c1f66e5) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n### Patch Changes\n\n- [#411](https://github.com/Effect-TS/cli/pull/411) [`07b3529`](https://github.com/Effect-TS/cli/commit/07b35297b18401a3b3600bd6ccdbfd8dc496c353) Thanks [@IMax153](https://github.com/IMax153)! - default `CliConfig.finalCheckBuiltIn` to `false`\n\n- [#404](https://github.com/Effect-TS/cli/pull/404) [`70fc225`](https://github.com/Effect-TS/cli/commit/70fc225a2e463ec5b2cea6692491e036ec41fd5b) Thanks [@IMax153](https://github.com/IMax153)! - remove `\"type\"` option from `Prompt.text` and add `Prompt.password` and `Prompt.hidden` which return `Secret`\n\n- [#416](https://github.com/Effect-TS/cli/pull/416) [`234c3f7`](https://github.com/Effect-TS/cli/commit/234c3f780cd9409386b5b4fbcccaadbe7035c2b9) Thanks [@IMax153](https://github.com/IMax153)! - Make help documentation print built-in options by default\n\n  The printing of built-in options in the help documentation can be disabled by providing a custom\n  `CliConfig` to your CLI application with `showBuiltIns` set to `false`.\n\n## 0.24.0\n\n### Minor Changes\n\n- [#410](https://github.com/Effect-TS/cli/pull/410) [`686ce6c`](https://github.com/Effect-TS/cli/commit/686ce6c7caf6be6f0c6b37e8b83e746cac95a1cd) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n### Patch Changes\n\n- [#407](https://github.com/Effect-TS/cli/pull/407) [`77b31e8`](https://github.com/Effect-TS/cli/commit/77b31e891d0a246db709cf7dba81dd7cd19a5d44) Thanks [@tim-smart](https://github.com/tim-smart)! - fix Subcommand type extraction\n\n## 0.23.1\n\n### Patch Changes\n\n- [#403](https://github.com/Effect-TS/cli/pull/403) [`26ab5b5`](https://github.com/Effect-TS/cli/commit/26ab5b5304c84faf73e4d9e7a2443332e7a6b640) Thanks [@tim-smart](https://github.com/tim-smart)! - add Args/Options.withFallbackConfig\n\n## 0.23.0\n\n### Minor Changes\n\n- [#373](https://github.com/Effect-TS/cli/pull/373) [`e6b790d`](https://github.com/Effect-TS/cli/commit/e6b790d0c05be67a6eccb4673d803ebf4faec832) Thanks [@IMax153](https://github.com/IMax153)! - implement `--wizard` mode for cli applications\n\n- [#373](https://github.com/Effect-TS/cli/pull/373) [`e6b790d`](https://github.com/Effect-TS/cli/commit/e6b790d0c05be67a6eccb4673d803ebf4faec832) Thanks [@IMax153](https://github.com/IMax153)! - implement completion script generation for cli applications\n\n- [#390](https://github.com/Effect-TS/cli/pull/390) [`1512ce7`](https://github.com/Effect-TS/cli/commit/1512ce7c9da71c1bf122b4e11205f2b158c8f04e) Thanks [@tim-smart](https://github.com/tim-smart)! - add localized handlers for Command's\n\n- [#398](https://github.com/Effect-TS/cli/pull/398) [`3e21194`](https://github.com/Effect-TS/cli/commit/3e21194f61de4144161eeaa1bfcb54946b588b0f) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n- [#388](https://github.com/Effect-TS/cli/pull/388) [`0502e7e`](https://github.com/Effect-TS/cli/commit/0502e7e176606069a46ad0c09d2ce8db0468a835) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n### Patch Changes\n\n- [#382](https://github.com/Effect-TS/cli/pull/382) [`d24623b`](https://github.com/Effect-TS/cli/commit/d24623bfce76bb407d03ff1f61a3936bd0902d64) Thanks [@IMax153](https://github.com/IMax153)! - fix the type signature of `Options.keyValueMap`\n\n- [#397](https://github.com/Effect-TS/cli/pull/397) [`48db351`](https://github.com/Effect-TS/cli/commit/48db351b51a74f634779b453f299376a526da911) Thanks [@tim-smart](https://github.com/tim-smart)! - fix withDescription for mapped commands\n\n- [#375](https://github.com/Effect-TS/cli/pull/375) [`ab92954`](https://github.com/Effect-TS/cli/commit/ab92954a8d3dc22970712af5ce487c004d004737) Thanks [@IMax153](https://github.com/IMax153)! - cleanup readonly tuple types\n\n- [#385](https://github.com/Effect-TS/cli/pull/385) [`fec4166`](https://github.com/Effect-TS/cli/commit/fec416627e389f111cd82f0dbe0e512ac48b9d8b) Thanks [@IMax153](https://github.com/IMax153)! - support multi-valued arguments appearing anywhere in command-line arguments\n\n- [#383](https://github.com/Effect-TS/cli/pull/383) [`714fe74`](https://github.com/Effect-TS/cli/commit/714fe74dfe919b79384480cd62d1a2f62f537932) Thanks [@IMax153](https://github.com/IMax153)! - add support for variadic options\n\n- [#384](https://github.com/Effect-TS/cli/pull/384) [`3fd5804`](https://github.com/Effect-TS/cli/commit/3fd58041e5b45c20205bee48eca28eedf20e154b) Thanks [@IMax153](https://github.com/IMax153)! - implement withDefault for Args\n\n- [#381](https://github.com/Effect-TS/cli/pull/381) [`fb0bb00`](https://github.com/Effect-TS/cli/commit/fb0bb00cf7b4c3fcda8dccb3783df67e3e8f474b) Thanks [@IMax153](https://github.com/IMax153)! - introduce Args.optional\n\n- [#375](https://github.com/Effect-TS/cli/pull/375) [`ab92954`](https://github.com/Effect-TS/cli/commit/ab92954a8d3dc22970712af5ce487c004d004737) Thanks [@IMax153](https://github.com/IMax153)! - convert all modules to better support tree-shaking\n\n- [#378](https://github.com/Effect-TS/cli/pull/378) [`2cc9d15`](https://github.com/Effect-TS/cli/commit/2cc9d15541011e20b8d4bc1a7971c84f179589f8) Thanks [@IMax153](https://github.com/IMax153)! - fix completion script generation\n\n## 0.22.0\n\n### Minor Changes\n\n- [#370](https://github.com/Effect-TS/cli/pull/370) [`10eceaa`](https://github.com/Effect-TS/cli/commit/10eceaa9c558166eaa8c4090cc4950fbb8c2de9f) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.21.0\n\n### Minor Changes\n\n- [#365](https://github.com/Effect-TS/cli/pull/365) [`cb01813`](https://github.com/Effect-TS/cli/commit/cb01813803a1458248cfda1c3f23844bedf9ff40) Thanks [@fubhy](https://github.com/fubhy)! - Fixed exports of public module at subpaths\n\n- [#353](https://github.com/Effect-TS/cli/pull/353) [`a09fa9f`](https://github.com/Effect-TS/cli/commit/a09fa9feaf9dfdd19b4a3b3a15ad2854e190391e) Thanks [@IMax153](https://github.com/IMax153)! - refactor library internals to fix a number of different bugs\n\n### Patch Changes\n\n- [#358](https://github.com/Effect-TS/cli/pull/358) [`07eaa9d`](https://github.com/Effect-TS/cli/commit/07eaa9db5b828f1515fba9aa01265d05f507b748) Thanks [@IMax153](https://github.com/IMax153)! - add support for auto-generating completions for a cli program\n\n## 0.20.1\n\n### Patch Changes\n\n- [#351](https://github.com/Effect-TS/cli/pull/351) [`95d2057`](https://github.com/Effect-TS/cli/commit/95d2057f831c625c39b3f6a791c6979c8c887c75) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.20.0\n\n### Minor Changes\n\n- [#349](https://github.com/Effect-TS/cli/pull/349) [`af7a22f`](https://github.com/Effect-TS/cli/commit/af7a22f751f368368f07e8cd99a9f7522fae194e) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.19.0\n\n### Minor Changes\n\n- [#345](https://github.com/Effect-TS/cli/pull/345) [`0be387a`](https://github.com/Effect-TS/cli/commit/0be387af00d114bb70c4c2089eabedca30e0d9c2) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.18.0\n\n### Minor Changes\n\n- [#343](https://github.com/Effect-TS/cli/pull/343) [`f3facf4`](https://github.com/Effect-TS/cli/commit/f3facf4a99772098b90a51f173de514fbcf8a717) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.17.0\n\n### Minor Changes\n\n- [#341](https://github.com/Effect-TS/cli/pull/341) [`263180c`](https://github.com/Effect-TS/cli/commit/263180cbdc7016f377e793de6c68c6c3a9c75cff) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.16.0\n\n### Minor Changes\n\n- [#338](https://github.com/Effect-TS/cli/pull/338) [`94b219e`](https://github.com/Effect-TS/cli/commit/94b219ed3985891dfed82e42ebc4a26a429e8169) Thanks [@tim-smart](https://github.com/tim-smart)! - use preconstruct\n\n### Patch Changes\n\n- [#336](https://github.com/Effect-TS/cli/pull/336) [`06934e8`](https://github.com/Effect-TS/cli/commit/06934e8254c93a0488ec1f3a70a61f106630215b) Thanks [@IMax153](https://github.com/IMax153)! - add Prompt module\n\n## 0.15.1\n\n### Patch Changes\n\n- [#333](https://github.com/Effect-TS/cli/pull/333) [`333baa6`](https://github.com/Effect-TS/cli/commit/333baa60cbd847f39d7ab3303a7d866b467cb896) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.15.0\n\n### Minor Changes\n\n- [#330](https://github.com/Effect-TS/cli/pull/330) [`7e8267a`](https://github.com/Effect-TS/cli/commit/7e8267aed27cf352831e12f6fbcdf844376e6262) Thanks [@tim-smart](https://github.com/tim-smart)! - update to effect package\n\n## 0.14.0\n\n### Minor Changes\n\n- [#328](https://github.com/Effect-TS/cli/pull/328) [`469a824`](https://github.com/Effect-TS/cli/commit/469a8242e1ab774ff55b12c8bab65a6f2fbd2881) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.13.0\n\n### Minor Changes\n\n- [#326](https://github.com/Effect-TS/cli/pull/326) [`22dd35f`](https://github.com/Effect-TS/cli/commit/22dd35fe0eb7f24e7d19015ebd83d4c300cc5422) Thanks [@IMax153](https://github.com/IMax153)! - use builtin Console service\n\n## 0.12.0\n\n### Minor Changes\n\n- [#324](https://github.com/Effect-TS/cli/pull/324) [`70edc03`](https://github.com/Effect-TS/cli/commit/70edc03b932b3f4cf068ff14afd5b585ec8beeed) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.11.0\n\n### Minor Changes\n\n- [#322](https://github.com/Effect-TS/cli/pull/322) [`79befce`](https://github.com/Effect-TS/cli/commit/79befceef82614438589746ae5bddc6571705518) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.10.1\n\n### Patch Changes\n\n- [#320](https://github.com/Effect-TS/cli/pull/320) [`2ebdf8c`](https://github.com/Effect-TS/cli/commit/2ebdf8c870f23fd20e0aa1b1c1cb5581056e73cc) Thanks [@tim-smart](https://github.com/tim-smart)! - move /printer to peer deps and fix version\n\n## 0.10.0\n\n### Minor Changes\n\n- [#319](https://github.com/Effect-TS/cli/pull/319) [`6dd210a`](https://github.com/Effect-TS/cli/commit/6dd210a46e1f2f16b8c8ac85e746c64ea5f00b57) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n### Patch Changes\n\n- [#316](https://github.com/Effect-TS/cli/pull/316) [`3f4e8c3`](https://github.com/Effect-TS/cli/commit/3f4e8c3337d0ca1c1960a060654a4f86e9b23685) Thanks [@fubhy](https://github.com/fubhy)! - Made `Command`, `Option`, `Args` and `Primitive` pipeable\n\n- [#318](https://github.com/Effect-TS/cli/pull/318) [`4a0fbae`](https://github.com/Effect-TS/cli/commit/4a0fbae24f85dd396ee36c3f185ccc84026839b7) Thanks [@tim-smart](https://github.com/tim-smart)! - use peer deps for /data and /io\n\n- [#314](https://github.com/Effect-TS/cli/pull/314) [`886f1fe`](https://github.com/Effect-TS/cli/commit/886f1fe3666aacd1fb54e5b0cde85f8b6fdb88d8) Thanks [@fubhy](https://github.com/fubhy)! - Fixed `withDefault` types\n\n- [#317](https://github.com/Effect-TS/cli/pull/317) [`eca403d`](https://github.com/Effect-TS/cli/commit/eca403d834ec0dc2918828f0140ef8c7052c80ff) Thanks [@tim-smart](https://github.com/tim-smart)! - update build tools\n\n## 0.9.0\n\n### Minor Changes\n\n- [#312](https://github.com/Effect-TS/cli/pull/312) [`5385275`](https://github.com/Effect-TS/cli/commit/5385275f9f151b99a0a5fa4f2364b3a7417e0509) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.8.0\n\n### Minor Changes\n\n- [#309](https://github.com/Effect-TS/cli/pull/309) [`dca0f8f`](https://github.com/Effect-TS/cli/commit/dca0f8fc721b5f85ddf9bf1cf7c3d5978ac63bef) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.7.0\n\n### Minor Changes\n\n- [#307](https://github.com/Effect-TS/cli/pull/307) [`81da44d`](https://github.com/Effect-TS/cli/commit/81da44deb77c52ce203ba1716f3be972ac9a3594) Thanks [@IMax153](https://github.com/IMax153)! - upgrade to latest effect packages\n\n## 0.6.0\n\n### Minor Changes\n\n- [#305](https://github.com/Effect-TS/cli/pull/305) [`51a1bda`](https://github.com/Effect-TS/cli/commit/51a1bda139217fcaefccdf0145e0cb7665906931) Thanks [@IMax153](https://github.com/IMax153)! - upgrade to @effect/data@0.13.5, @effect/io@0.31.3, and @effect/printer{-ansi}@0.9.0\n\n## 0.5.0\n\n### Minor Changes\n\n- [#303](https://github.com/Effect-TS/cli/pull/303) [`9c3cf14`](https://github.com/Effect-TS/cli/commit/9c3cf1437709a13f35a127629cdd3b112edebc29) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n### Patch Changes\n\n- [#301](https://github.com/Effect-TS/cli/pull/301) [`bb8f3b5`](https://github.com/Effect-TS/cli/commit/bb8f3b5457586c4060b2af500bbb365b74f3c3d1) Thanks [@IMax153](https://github.com/IMax153)! - separate Options.choice and Options.choiceWithValue\n\n## 0.4.1\n\n### Patch Changes\n\n- [#299](https://github.com/Effect-TS/cli/pull/299) [`06267a8`](https://github.com/Effect-TS/cli/commit/06267a864e4636bf5ff79f2abecc47940954db5f) Thanks [@IMax153](https://github.com/IMax153)! - update dependencies\n\n## 0.4.0\n\n### Minor Changes\n\n- [#296](https://github.com/Effect-TS/cli/pull/296) [`13cbed7`](https://github.com/Effect-TS/cli/commit/13cbed7013035b74f37a34de50794d6a41c29f8e) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io and /data\n\n## 0.3.0\n\n### Minor Changes\n\n- [#295](https://github.com/Effect-TS/cli/pull/295) [`dfb0b05`](https://github.com/Effect-TS/cli/commit/dfb0b05fde9bbf3b4de43fab45112cd343033ea3) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n### Patch Changes\n\n- [#293](https://github.com/Effect-TS/cli/pull/293) [`f702bb9`](https://github.com/Effect-TS/cli/commit/f702bb9d1a38b1b632fb3461e0d8b335d2c63c79) Thanks [@tim-smart](https://github.com/tim-smart)! - non empty chunks for more than one element\n\n## 0.2.0\n\n### Minor Changes\n\n- [#289](https://github.com/Effect-TS/cli/pull/289) [`39c90e9`](https://github.com/Effect-TS/cli/commit/39c90e9b70bfb8a34a82e34811ca48279c3f0326) Thanks [@tim-smart](https://github.com/tim-smart)! - add variadic Options\n\n### Patch Changes\n\n- [#288](https://github.com/Effect-TS/cli/pull/288) [`9b14798`](https://github.com/Effect-TS/cli/commit/9b14798ee6ad1bf0e12d3b907195ffd6d79397e7) Thanks [@tim-smart](https://github.com/tim-smart)! - improve optional message if default is Option\n\n- [#292](https://github.com/Effect-TS/cli/pull/292) [`e15ef09`](https://github.com/Effect-TS/cli/commit/e15ef0943a002165c4109a0b8178e55c48cef3a6) Thanks [@tim-smart](https://github.com/tim-smart)! - update /printer\n\n## 0.1.0\n\n### Minor Changes\n\n- [#286](https://github.com/Effect-TS/cli/pull/286) [`9000a03`](https://github.com/Effect-TS/cli/commit/9000a03306d1aecca5e06efea475cccf68d37707) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.0.1\n\n### Patch Changes\n\n- [#284](https://github.com/Effect-TS/cli/pull/284) [`5fc66c6`](https://github.com/Effect-TS/cli/commit/5fc66c66c2a6f6c8910cb38000f2f71b7ac2a715) Thanks [@IMax153](https://github.com/IMax153)! - initial release\n"
  },
  {
    "path": "packages/cli/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Effectful Technologies Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/cli/README.md",
    "content": "# Installation\n\nInstalling `@effect/cli` is straightforward and can be done using any of the popular package managers. Follow the steps below to get started with setting up `@effect/cli` on your system.\n\n### Step 1: Install `@effect/cli`\n\nChoose your preferred package manager and run one of the following commands in your terminal:\n\n- **Using npm:**\n\n  ```sh\n  npm install @effect/cli\n  ```\n\n- **Using pnpm:**\n\n  ```sh\n  pnpm add @effect/cli\n  ```\n\n- **Using yarn:**\n  ```sh\n  yarn add @effect/cli\n  ```\n\n### Step 2: Install Platform-Specific Packages\n\n`@effect/cli` interacts directly with various platform-specific services like the file system and the terminal. Depending on the environment where you'll run your command-line application, you need to install the appropriate `@effect/platform` package.\n\n#### For Node.js Environments\n\nIf your application will run in a Node.js environment, you'll need to install `@effect/platform-node`. This package ensures that `@effect/cli` can effectively interact with Node.js-specific functionalities.\n\nRun one of the following commands based on your package manager:\n\n- **Using npm:**\n\n  ```sh\n  npm install @effect/platform-node\n  ```\n\n- **Using pnpm:**\n\n  ```sh\n  pnpm add @effect/platform-node\n  ```\n\n- **Using yarn:**\n  ```sh\n  yarn add @effect/platform-node\n  ```\n\n### Step 3: Configure Your Application\n\nAfter installing the necessary packages, you must configure your application to use the `NodeContext.layer` from `@effect/platform-node`. This step is crucial as it grants `@effect/cli` access to all necessary Node.js services and APIs, ensuring your CLI tool functions correctly within the Node.js environment.\n\nHere's how you can incorporate `NodeContext.layer` into your application:\n\n```ts\nimport { NodeContext, NodeRuntime } from \"@effect/platform-node\"\n// Your application's setup code here\n```\n\nThis configuration will make sure that your CLI application is fully integrated with the Node.js runtime, allowing it to perform optimally with access to system resources and services.\n\nFor a more detailed walkthrough, take a read through the [Tutorial](#tutorial) below.\n\n# Built-In Options\n\n`@effect/cli` comes equipped with several powerful built-in options that enhance the functionality of your CLI applications without the need for additional coding. These options are ready to use immediately after installation and are designed to simplify common tasks and improve the user experience.\n\n### Overview of Built-In Options\n\nHere's a breakdown of the key built-in options available in `@effect/cli`:\n\n- **Log Level (`[--log-level]`)**:\n\n  - **Description**: Sets the **minimum** log level for a `Command`'s handler method\n  - **Usage**: `--log-level (all | trace | debug | info | warning | error | fatal | none)`\n  - **Functionality**: Allows you to specify the **minimum** log level for a `Command`'s handler method. By setting this option, you can control the verbosity of the log output, ensuring that only logs of a certain priority or higher are output by your program.\n\n- **Shell Completions (`[--completions]`)**:\n\n  - **Description**: Automatically generates shell completion scripts to enhance user experience. Shell completions suggest possible command options when you type a command and hit the tab key.\n  - **Usage**: `--completions (bash | sh | fish | zsh)`\n  - **Functionality**: Depending on your shell environment (bash, sh, fish, or zsh), this option generates a script that, when sourced, provides tab completions for your CLI commands.\n\n- **Help (`[-h | --help]`)**:\n\n  - **Description**: Instantly generates and displays helpful documentation about your CLI application's commands and options.\n  - **Usage**: `-h` or `--help`\n  - **Functionality**: When this option is used, it displays all available commands and options along with descriptions, usage patterns, and examples if available. This is crucial for new users or when you need a quick reminder about the tool's capabilities.\n\n- **Version (`[--version]`)**:\n\n  - **Description**: Displays the current version number of your CLI application.\n  - **Usage**: `--version`\n  - **Functionality**: This is particularly useful for debugging and ensuring compatibility, as it lets you confirm the version of the CLI tool you are currently using.\n\n- **Wizard Mode (`[--wizard]`)**:\n  - **Description**: Activates a guided interface to help users construct commands.\n  - **Usage**: `--wizard`\n  - **Functionality**: This interactive mode takes users step-by-step through the process of building a command, making it ideal for newcomers or complex commands. It asks questions and uses the responses to form the correct command syntax, which can then be executed or edited further.\n\n### Practical Applications\n\nThese built-in options are designed to make the CLI user-friendly and more accessible, especially for those who are new to command-line interfaces. They reduce the learning curve and provide immediate assistance, enhancing productivity and user engagement.\n\nFor instance, a new user can type the following to get a list of all commands and options:\n\n```sh\nyour-cli-app --help\n```\n\nOr, to quickly add command completion to their shell, they might use:\n\n```sh\nsource <(your-cli-app --completions bash)\n```\n\n# Overview\n\n`@effect/cli` is a powerful framework designed to simplify the development of command-line applications in TypeScript. It employs a modular architecture that allows developers to create scalable and maintainable CLI tools. Below is a table highlighting its key features:\n\n| Feature                       | Description                                                                                                                                        |\n| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Command Structure             | Supports a hierarchical command structure with a top-level command and potentially multiple nested subcommands.                                    |\n| Parsing Arguments             | Built-in support for parsing command-line arguments efficiently.                                                                                   |\n| Generating Help Text          | Automatically generates and displays help documentation for each command.                                                                          |\n| Handling Subcommands          | Facilitates the management and execution of nested subcommands.                                                                                    |\n| Built-in Options              | Includes built-in options such as `--help`, `--version`, and shell completions for enhanced usability.                                             |\n| Wizard Mode                   | Offers a Wizard Mode that guides users through constructing commands interactively.                                                                |\n| Platform-Specific Integration | Integrates with platform-specific services via `@effect/platform` packages, ensuring compatibility with diverse environments like Node.js. and Bun |\n\n## Command Structure\n\nEvery command-line application built with `@effect/cli` consists of one or more commands (`Command`). There is always a top-level command representing the application itself, and potentially multiple nested subcommands:\n\n- **Top-Level Command**: This is the main command that represents your application. It's always of type `Command`.\n- **Subcommands**: These are nested commands under the top-level command. Each subcommand is also of type `Command`, allowing you to organize functionality into distinct actions.\n- **Options**: Commands can have zero or more options (such as `--help` or `--version`). These are specified using `Options` and can be either required or optional. Options can be boolean flags or can accept values from user input.\n- **Arguments**: Commands can also have zero or more arguments (such as `<directory>`). These are specified using `Args` and represent the data that users need to provide to commands.\n- **Command Handler**: Each command has a command handler, which is a function responsible for the actual execution of the command. This is where you define what the command does when it runs.\n\nThis structure allows you to build complex CLI tools that are easy to extend and maintain. Whether you are adding new options to existing commands, creating new subcommands, or handling user inputs, `@effect/cli` provides a structured and intuitive way to scale your application.\n\n# Getting Started with Your First CLI Application\n\n## Creating a Simple \"Hello World\" CLI\n\nStarting with a basic \"Hello World\" application is a great way to get familiar with the `@effect/cli`. Below is a step-by-step guide to creating your first command-line interface (CLI) application.\n\n### 1. Set Up Your Project\n\nBegin by creating a new file for your project:\n\n- **File Name**: `hello-world.ts`\n- **Purpose**: This file will hold all the necessary code for your CLI application.\n\n### 2. Write the CLI Code\n\nNow, let's write the code for your CLI. Open your `hello-world.ts` file in your favorite code editor and insert the following TypeScript code:\n\n```ts\n// Import necessary modules from the libraries\nimport { Command } from \"@effect/cli\"\nimport { NodeContext, NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect } from \"effect\"\n\n// Define the top-level command\nconst command = Command.make(\"hello-world\", {}, () =>\n  Console.log(\"Hello World\")\n)\n\n// Set up the CLI application\nconst cli = Command.run(command, {\n  name: \"Hello World CLI\",\n  version: \"v1.0.0\"\n})\n\n// Prepare and run the CLI application\ncli(process.argv).pipe(Effect.provide(NodeContext.layer), NodeRuntime.runMain)\n```\n\n**Explanation of Code:**\n\n- **Import Statements**:\n\n  - `Command` from `@effect/cli` allows you to define commands and subcommands.\n  - `NodeContext` and `NodeRuntime` from `@effect/platform-node` enable your CLI to interact and integrate seamlessly with the Node.js runtime environment. This setup is crucial for running your CLI on Node.js, as it ensures that all Node-specific APIs and functionalities are accessible.\n  - `Console` and `Effect` from `effect` provide utilities for logging and managing effects, which are essential for handling asynchronous operations and side effects in your CLI.\n\n- **Command Definition**:\n\n  - The `Command.make` function creates a new command named \"hello-world\". This command is configured to print \"Hello World\" when executed, serving as the basic functionality of your CLI.\n\n- **CLI Configuration**:\n\n  - The `Command.run` function initializes your CLI application with a specific name and version, preparing it for execution.\n\n- **Execution Setup**:\n  - The `cli(process.argv)` call processes the command-line arguments.\n  - It uses `Effect.provide` to inject the `NodeContext.layer`, which integrates the CLI with the Node.js environment, allowing your application to utilize Node-specific features and settings.\n  - `NodeRuntime.runMain` ensures that your application is executed within the Node.js main runtime, handling any asynchronous tasks and managing the lifecycle of your CLI.\n\n### 3. Run Your CLI\n\nAfter saving your `hello-world.ts` file, you can run your CLI application directly from your terminal to see it in action. Here's how:\n\n```sh\nnpx tsx hello-world.ts\n# Expected Output: Hello World\n```\n\n**Explanation of the Command:**\n\n- **`tsx`**: This is a command-line tool that enables direct execution of TypeScript files. It simplifies the development process by eliminating the need to manually compile TypeScript (`*.ts`) files into JavaScript (`*.js`) before running them. `tsx` automatically compiles the TypeScript code on-the-fly and executes it, leveraging the Node.js environment.\n\n- **`npx`**: Part of the npm (Node Package Manager) suite, `npx` is used to execute packages. When you run `npx tsx`, it temporarily installs `tsx` if it isn't already present in your project's local `node_modules` folder or globally on your machine. Then, `npx` executes `tsx` with the specified TypeScript file as its argument.\n\n- **Usage in Your CLI**: By using `npx tsx hello-world.ts`, you're instructing `npx` to execute your TypeScript file using `tsx`. This command is especially useful for quick testing and development purposes, as it allows you to run your code directly without setting up a full TypeScript compilation workflow beforehand.\n\n## Exploring CLI Features\n\nYour new CLI comes with a variety of built-in features designed to enhance usability and help you manage your application effectively:\n\n### Check the Version\n\nYou can display the version of your CLI by using the `--version` option:\n\n```sh\nnpx tsx hello-world.ts --version\n# Output: v1.0.0\n```\n\n### Access Help Information\n\nYour CLI automatically generates help documentation that describes available commands and options. This feature is useful when you need guidance on how the CLI operates or when you want to learn more about its capabilities.\n\n```sh\nnpx tsx hello-world.ts --help # or -h\n```\n\nWhen you request help, the CLI will display information like this:\n\n```\nHello World CLI\n\nHello World CLI v1.0.0\n\nUSAGE\n\n$ hello-world\n\nOPTIONS\n\n--completions sh | bash | fish | zsh\n\n  One of the following: sh, bash, fish, zsh\n\n  Generate a completion script for a specific shell\n\n  This setting is optional.\n\n(-h, --help)\n\n  A true or false value.\n\n  Show the help documentation for a command\n\n  This setting is optional.\n\n--wizard\n\n  A true or false value.\n\n  Start wizard mode for a command\n\n  This setting is optional.\n\n--version\n\n  A true or false value.\n\n  Show the version of the application\n\n  This setting is optional.\n```\n\n### Using the Wizard Mode\n\nThe `--wizard` option activates the Wizard Mode in your CLI application, which provides a guided process for constructing commands. This is especially helpful for users who are new to your CLI or need assistance in building the correct command syntax.\n\nTo initiate the Wizard Mode, run your CLI application with the `--wizard` option like this:\n\n```sh\nnpx tsx hello-world.ts --wizard\n```\n\nWhen you start the Wizard Mode, the CLI will interactively guide you through the process of setting up a command. Here's what the interaction might look like:\n\n```\nWizard Mode for CLI Application: Hello World CLI (v1.0.0)\n\nInstructions\n\n  The wizard mode will assist you with constructing commands for Hello World CLI (v1.0.0).\n\n  Please answer all prompts provided by the wizard.\n\nCOMMAND: hello-world\n\nWizard Mode Complete!\n\nYou may now execute your command directly with the following options and arguments:\n\n    hello-world\n\n✔ Would you like to run the command? … yes / no\n```\n\n# Basic Usage\n\n## Adding Arguments to Commands\n\nAdding arguments to your commands allows your CLI applications to accept and process user input dynamically. Let's create a simple `echo` CLI that echoes back whatever text you pass to it.\n\n### Setting Up Your CLI\n\nBegin by creating a new TypeScript file named `echo.ts`. This file will contain all the code necessary to define a command that accepts user input as an argument.\n\n```ts\n// Import the necessary modules from the Effect libraries\nimport { Args, Command } from \"@effect/cli\"\nimport { NodeContext, NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect } from \"effect\"\n\n// Define a text argument\nconst text = Args.text({ name: \"text\" })\n\n// Create a command that logs the provided text argument to the console\nconst command = Command.make(\"echo\", { text }, ({ text }) => Console.log(text))\n\n// Configure and initialize the CLI application\nconst cli = Command.run(command, {\n  name: \"Echo CLI\",\n  version: \"v0.0.1\"\n})\n\n// Prepare and run the CLI application, providing necessary context and runtime\ncli(process.argv).pipe(Effect.provide(NodeContext.layer), NodeRuntime.runMain)\n```\n\n**Understanding the Code:**\n\n- **Arguments**: The `text` declaration creates an input parameter that users need to provide when they run your CLI.\n- **Command Definition**: The `Command.make` function sets up your CLI command. It's designed to take the `text` argument and display it using `Console.log`.\n- **Command Execution:** By using `Command.run`, the CLI application is formally structured with a specified name and version, and is ready to execute based on the defined command structure.\n- **Execution Setup**: The `cli(process.argv)` call processes the command-line arguments and runs the CLI application. The `Effect.provide(NodeContext.layer)` injects the necessary Node.js context, and `NodeRuntime.runMain` ensures proper execution within the Node.js environment.\n\n### Running the CLI\n\nWith your `echo.ts` script ready, you can run it to interact with the argument you've set up.\n\n**Run Without Arguments**\n\nIf you try running the CLI without specifying any arguments, it will remind you to provide the required text:\n\n```sh\nnpx tsx echo.ts\n# Output: Missing argument <text>\n```\n\n**Run With Arguments**\n\nTo pass the text argument correctly, wrap your input in quotes to treat it as a single string:\n\n```sh\nnpx tsx echo.ts \"This is a test\"\n# Output: This is a test\n```\n\n**Common Mistake**\n\nForgetting to use quotes can cause issues since each word might be interpreted as a separate argument:\n\n```sh\nnpx tsx echo.ts This is a test\n# Output: Received unknown argument: 'is'\n```\n\n## Adding Options to Commands\n\nLet's enhance the `echo` CLI we built earlier by introducing an option that allows text to be displayed in bold. This tutorial will guide you on adding a `--bold` option, abbreviated as `-b`, to your command.\n\n### Modify Your TypeScript File\n\nFirst, open the TypeScript file (`echo.ts`) where your `echo` command is defined. We will add a new option that enables users to choose whether their text output should be bold.\n\n### Update the Code\n\nBelow is the updated version of your code with the bold option included:\n\n```ts\nimport { Args, Command, Options } from \"@effect/cli\"\nimport { NodeContext, NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect } from \"effect\"\n\nconst text = Args.text({ name: \"text\" })\n\n// Define the 'bold' option with an alias '-b'\nconst bold = Options.boolean(\"bold\").pipe(Options.withAlias(\"b\"))\n\n// Create the command that outputs the text with bold formatting if the bold option is used\nconst command = Command.make(\"echo\", { text, bold }, ({ bold, text }) =>\n  Console.log(bold ? `\\x1b[1m${text}\\x1b[0m` : text)\n)\n\nconst cli = Command.run(command, {\n  name: \"Echo CLI\",\n  version: \"v0.0.2\"\n})\n\ncli(process.argv).pipe(Effect.provide(NodeContext.layer), NodeRuntime.runMain)\n```\n\n### Explanation of the Changes\n\n- **Bold Option**: The `bold` declaration creates a boolean option that users can toggle. Using `Options.withAlias(\"b\")` allows the option to be invoked with a shorter `-b` flag. This makes the command easier to type and remember.\n\n- **Command Functionality**: Within the function of the command, there's a check to see if the `bold` option is true. If it is, the text is formatted with ANSI escape codes (`\\x1b[1m` and `\\x1b[0m`) to appear bold in the terminal. This formatting adds visual emphasis and can help distinguish output in complex console applications.\n\n### Running the Updated CLI\n\nWith the command updated, you can now see the effect of the `--bold` or `-b` option by running:\n\n```sh\nnpx tsx echo.ts --bold \"This is a test\"\n```\n\nor\n\n```sh\nnpx tsx echo.ts -b \"This is a test\"\n```\n\n**Expected Output:**\n\nBoth commands will display \"This is a test\" in bold text, assuming your terminal supports ANSI escape codes.\n\n## Important Note on Argument Order\n\nWhen using your CLI, it's crucial to understand the order in which you specify options and arguments. By default, the `@effect/cli` parses `Options` and `Args` **before** any subcommands. This means that options need to be placed directly after the main command, and before any subcommands or additional arguments.\n\nFor example, the command:\n\n```sh\nnpx tsx echo.ts \"This is a test\" -b\n```\n\n**would not work** because the `-b` option appears after the text argument `\"This is a test\"`. The parser expects options to be specified before any standalone arguments or subcommands. This ensures that the options are correctly associated with the main command and not misinterpreted as arguments for a subcommand or additional text.\n\n## Adding Valued Options to Commands\n\nIn this section, we will continue to improve our `echo` CLI by introducing options to customize the color of the output text. This enhancement not only adds visual customization but also demonstrates how to use valued options to modify the behavior of commands.\n\n### Update Your TypeScript File\n\nStart by opening the TypeScript file where your `echo` command is defined. We will add new functionalities that allow for text coloring and optional bold formatting.\n\n### Code Implementation\n\nBelow is the modified version of your code, now including options for text color:\n\n```ts\nimport { Args, Command, Options } from \"@effect/cli\"\nimport { NodeContext, NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect, Option } from \"effect\"\n\n// Define a text argument\nconst text = Args.text({ name: \"text\" })\n\n// Define the 'bold' option with an alias '-b'\nconst bold = Options.boolean(\"bold\").pipe(Options.withAlias(\"b\"))\n\n// Color codes for ANSI escape sequences\nconst colorToAnsiSequence = {\n  red: \"\\x1b[31m\",\n  green: \"\\x1b[32m\",\n  blue: \"\\x1b[34m\"\n} as const\nconst resetCode = \"\\x1b[0m\"\n\ntype SupportedColor = keyof typeof colorToAnsiSequence\nconst supportedColors = Object.keys(colorToAnsiSequence) as SupportedColor[]\n\n// Define the 'color' option with choices and an alias '-c'\nconst color = Options.choice(\"color\", supportedColors).pipe(\n  Options.withAlias(\"c\"),\n  Options.optional\n)\n\n// Function to apply ANSI color codes based on user input\nconst applyColor = (\n  text: string,\n  color: Option.Option<SupportedColor>\n): string =>\n  Option.match(color, {\n    onNone: () => text,\n    onSome: (color) => `${colorToAnsiSequence[color]}${text}${resetCode}`\n  })\n\n// Create the command that outputs formatted text\nconst command = Command.make(\n  \"echo\",\n  { text, bold, color },\n  ({ bold, color, text }) => {\n    let formattedText = applyColor(text, color)\n    if (bold) {\n      formattedText = `\\x1b[1m${formattedText}\\x1b[0m`\n    }\n    return Console.log(formattedText)\n  }\n)\n\nconst cli = Command.run(command, {\n  name: \"Echo CLI\",\n  version: \"v0.0.3\"\n})\n\ncli(process.argv).pipe(Effect.provide(NodeContext.layer), NodeRuntime.runMain)\n```\n\n### Explanation of the Changes\n\n- **Color Options**: The `color` option enables users to specify the text color as \"red\", \"green\", or \"blue\", enhancing the visual aspect of the output. This option uses `Options.choice` to provide a list of possible values.\n\n- **applyColor Function**: This function applies the chosen ANSI color code to the text. If no color is selected, the text remains unchanged. This allows for dynamic customization of the output based on user preference.\n\n### Running the Enhanced CLI\n\nWith the new color and bold options, you can now run the CLI and see colored text output. Here's how to use these options:\n\n```sh\nnpx tsx echo.ts --bold --color red \"This is a test\"\nnpx tsx echo.ts -b -c green \"Another test\"\n```\n\n**Expected Output:**\n\nThese commands will print \"This is a test\" in bold red and \"Another test\" in bold green, provided your terminal supports ANSI colors.\n\n## Adding Subcommands\n\nLet's enhance the functionality of your `echo` CLI by adding a new subcommand called `repeat`. This subcommand will allow users to repeat a specified message multiple times, providing a practical example of how to extend a CLI application.\n\n### Update Your TypeScript File\n\nOpen the TypeScript file where your `echo` command is defined. We'll incorporate the `repeat` subcommand into this setup.\n\n### Implementing the `Repeat` Subcommand\n\nHere is how you can update your code to include the `repeat` subcommand:\n\n```ts\nimport { Args, Command, Options } from \"@effect/cli\"\nimport { NodeContext, NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect, Option } from \"effect\"\n\nconst text = Args.text({ name: \"text\" })\n\nconst bold = Options.boolean(\"bold\").pipe(Options.withAlias(\"b\"))\n\nconst colorToAnsiSequence = {\n  red: \"\\x1b[31m\",\n  green: \"\\x1b[32m\",\n  blue: \"\\x1b[34m\"\n} as const\nconst resetCode = \"\\x1b[0m\"\n\ntype SupportedColor = keyof typeof colorToAnsiSequence\nconst supportedColors = Object.keys(colorToAnsiSequence) as SupportedColor[]\n\nconst color = Options.choice(\"color\", supportedColors).pipe(\n  Options.withAlias(\"c\"),\n  Options.optional\n)\n\nconst applyColor = (\n  text: string,\n  color: Option.Option<SupportedColor>\n): string =>\n  Option.match(color, {\n    onNone: () => text,\n    onSome: (color) => `${colorToAnsiSequence[color]}${text}${resetCode}`\n  })\n\n// Argument for the number of repetitions\nconst count = Args.integer().pipe(Args.withDefault(1))\n\n// Creating the repeat subcommand\nconst repeat = Command.make(\"repeat\", { count }, ({ count }) =>\n  echo.pipe(\n    Effect.andThen((config) => Effect.repeatN(echo.handler(config), count - 1))\n  )\n)\n\n// Main echo command\nconst echo = Command.make(\n  \"echo\",\n  { text, bold, color },\n  ({ bold, color, text }) => {\n    let formattedText = applyColor(text, color)\n    if (bold) {\n      formattedText = `\\x1b[1m${formattedText}\\x1b[0m`\n    }\n    return Console.log(formattedText)\n  }\n)\n\n// Combining commands\nconst command = echo.pipe(Command.withSubcommands([repeat]))\n\nconst cli = Command.run(command, {\n  name: \"Echo CLI\",\n  version: \"v0.0.4\"\n})\n\ncli(process.argv).pipe(Effect.provide(NodeContext.layer), NodeRuntime.runMain)\n```\n\n### Explanation of the Changes\n\n- **Count Argument**: We introduced a new argument named `count`. This argument specifies the number of times the echo message will be repeated.\n- **Repeat Command**: This new subcommand leverages the `count` argument to repeat the message the specified number of times.\n- **Integration with Main Command**: We integrated the `repeat` subcommand into the existing `echo` command structure. This means users can activate this feature by simply appending the `repeat` keyword followed by the desired count after their message in the command line. For example, `echo \"Hello\" repeat 5` would output \"Hello\" five times.\n\n> [!NOTE]\n> Since `Command` is a subtype of `Effect`, you can use `Effect.andThen` within a subcommand's handler to directly access and utilize the `Config` from a parent command, and subsequently apply its handler.\n\n### Running the `Repeat` Subcommand\n\nWith the `repeat` subcommand added, you can now use it to repeat messages:\n\n```sh\nnpx tsx echo.ts -b -c red \"This is a test\" repeat 3\n```\n\n**Expected Output:**\n\nThis command will output \"This is a test\" in bold red text three times, demonstrating both the color and repeat functionalities.\n\n# Tutorial: Building Your Own Git-Style CLI\n\nIn this tutorial, we will create a basic version of a Git-like command-line interface (CLI) called `minigit` using the powerful `@effect/cli` library. Our goal is to replicate a small set of Git commands to demonstrate how you can build structured CLI tools:\n\n```\nminigit       [-v | --version] [-h | --help] [-c <name>=<value>]\nminigit add   [-v | --verbose] [--] [<pathspec>...]\nminigit clone [--depth <depth>] [--] <repository> [<directory>]\n```\n\n> [!NOTE]\n> This guide focuses on the setup and parsing of commands. Implementing the actual functionality of these commands is beyond the scope of this tutorial but can be developed further based on the patterns shown here.\n\nThe full code for this CLI application can be found in our [examples directory](./examples/minigit.ts).\n\n## Creating the Command-Line Application\n\nBegin by creating a TypeScript file named `minigit.ts`. This file will host all your CLI application code. We will structure our CLI with three main commands, demonstrating the powerful features of the `@effect/cli` library.\n\n### Setting Up the Main Command\n\nLet's start by setting up the primary command for our CLI, named `minigit`. To do this, we use the `Command.make` constructor which is pivotal for structuring commands in the `@effect/cli` framework.\n\n```ts\nimport { Command } from \"@effect/cli\"\nimport { Effect } from \"effect\"\n\n// Define the main 'minigit' command\nconst minigit = Command.make(\n  \"minigit\",\n  // Configuration object for the command\n  {},\n  // Handler function that executes the command\n  (config) => Effect.succeed(\"Welcome to Minigit!\")\n)\n```\n\n#### Breakdown of Key Components\n\n- **`Command.make` Function:** This function constructs a new `Command`. It requires three parameters:\n  - **Name:** This is the command name, like 'minigit', which you use to call the command from the command line.\n  - **Configuration:** This object specifies the options (`Options`) and arguments (`Args`) that the command can accept.\n  - **Handler:** This function is executed when the command is called. It receives the parsed configuration and carries out the command's core functionalities.\n\n#### Understanding the Command Type Signature\n\nThe `Command` interface in `@effect/cli` is structured as follows:\n\n```ts\nexport interface Command<Name extends string, R, E, A> {\n  readonly handler: (_: A) => Effect<void, E, R>\n  // Additional properties and methods...\n}\n```\n\n- **`Name` (`Name extends string`):** A unique string that identifies the command.\n- **`R` (Environment):** Defines the dependencies or the environment needed by the command's handler.\n- **`E` (Expected Errors):** Specifies the types of errors the command might expect during its execution.\n- **`A` (Arguments/Configuration):** Represents the configuration object the handler receives.\n\n### Detailed Explanation of Parameters\n\n**Command Name:**\n\nThe `name` parameter in `Command.make` designates the command's identifier. This name is crucial as it is used to invoke the command from the command line. For example, if we have a CLI application called `my-cli-app` with a single subcommand named `foo`, then executing the following command will run the `foo` command in your CLI application:\n\n```sh\nmy-cli-app foo\n```\n\n**Command Configuration:**\n\nThe configuration parameter allows you to define what options and arguments the command can accept. This setup includes both simple flags and more complex objects. The `Config` is an object of key/value pairs where the keys are just identifiers and the values are the `Options` and `Args` that the `Command` may receive. The `Config` object can have nested `Config` objects or arrays of `Config` objects. When the CLI application is actually executed, the command `Config` is parsed from the command-line options and arguments following the command name.\n\n**Command Handler:**\n\nThis function is where the action happens. It takes the parsed configuration and executes the core functionality of the command, utilizing the full capabilities of the `Effect` framework for managing effects and asynchronous operations.\n\n### Our First Command\n\nLet's apply what we've learned from using the `Command.make` method by defining the primary command for our `minigit` CLI application. This command will include configurations that handle various options like version, help, and custom key-value pairs.\n\n```ts\nimport { Command, Options } from \"@effect/cli\"\nimport { Console, Option } from \"effect\"\n\n// minigit [--version] [-h | --help] [-c <name>=<value>]\nconst configs = Options.keyValueMap(\"c\").pipe(Options.optional)\n\n// Define the main 'minigit' command\nconst minigit = Command.make(\n  \"minigit\",\n  // Configuration object for the command\n  { configs },\n  // Handler function that executes the command\n  ({ configs }) =>\n    Option.match(configs, {\n      onNone: () => Console.log(\"Running 'minigit'\"),\n      onSome: (configs) => {\n        const keyValuePairs = Array.from(\n          configs,\n          ([key, value]) => `${key}=${value}`\n        ).join(\", \")\n        return Console.log(\n          `Running 'minigit' with the following configs: ${keyValuePairs}`\n        )\n      }\n    })\n)\n```\n\n#### Key Aspects of the Code:\n\n- **Options Configuration:**\n\n  - **`Options.keyValueMap(\"c\")`:** This line sets up an option that accepts key-value pairs, allowing the user to input configurations in the format `-c key=value`.\n  - **`Options.optional`:** By chaining this combinator, the `-c` option becomes optional, meaning the CLI will operate correctly whether or not this option is provided.\n\n- **Command Execution:**\n  - The command handler utilizes the `Option.match` function to determine how to respond based on whether the user has provided any key-value configurations.\n  - If no configurations are provided (`onNone`), it simply logs \"Running 'minigit'.\"\n  - If configurations are provided (`onSome`), it logs these configurations in a readable string format, enhancing user feedback and interaction.\n\n#### Built-In Options:\n\nYou may have noticed the lack of explicit version and help options in our command setup. This is due to `@effect/cli`'s design, which includes several built-in options such as `--version` and `--help` (see [Built-In Options](#built-in-options). These are automatically available and do not need to be manually configured, simplifying the setup of common CLI functionalities.\n\n### Expanding the `minigit` CLI with Subcommands\n\nBuilding on our basic `minigit` CLI, we'll now introduce two key subcommands: `add` and `clone`. These subcommands will demonstrate how to handle more complex command structures and multiple parameters using the `@effect/cli` library.\n\n#### Adding Subcommands\n\nWe'll continue our `minigit` CLI development by incorporating `add` and `clone` subcommands to handle specific actions, much like the original Git commands.\n\n```ts\nimport { Args, Command, Options } from \"@effect/cli\"\nimport { Console, Option, Array } from \"effect\"\n\n// minigit [--version] [-h | --help] [-c <name>=<value>]\nconst configs = Options.keyValueMap(\"c\").pipe(Options.optional)\n\nconst minigit = Command.make(\"minigit\", { configs }, ({ configs }) =>\n  Option.match(configs, {\n    onNone: () => Console.log(\"Running 'minigit'\"),\n    onSome: (configs) => {\n      const keyValuePairs = Array.fromIterable(configs)\n        .map(([key, value]) => `${key}=${value}`)\n        .join(\", \")\n      return Console.log(\n        `Running 'minigit' with the following configs: ${keyValuePairs}`\n      )\n    }\n  })\n)\n\n// minigit add [-v | --verbose] [--] [<pathspec>...]\nconst pathspec = Args.text({ name: \"pathspec\" }).pipe(Args.repeated)\nconst verbose = Options.boolean(\"verbose\").pipe(Options.withAlias(\"v\"))\nconst minigitAdd = Command.make(\n  \"add\",\n  { pathspec, verbose },\n  ({ pathspec, verbose }) => {\n    const paths = Array.match(pathspec, {\n      onEmpty: () => \"\",\n      onNonEmpty: (paths) => ` ${Array.join(paths, \" \")}`\n    })\n    return Console.log(\n      `Running 'minigit add${paths}' with '--verbose ${verbose}'`\n    )\n  }\n)\n\n// minigit clone [--depth <depth>] [--] <repository> [<directory>]\nconst repository = Args.text({ name: \"repository\" })\nconst directory = Args.text({ name: \"directory\" }).pipe(Args.optional)\nconst depth = Options.integer(\"depth\").pipe(Options.optional)\nconst minigitClone = Command.make(\n  \"clone\",\n  { repository, directory, depth },\n  (config) => {\n    const depth = Option.map(config.depth, (depth) => `--depth ${depth}`)\n    const repository = Option.some(config.repository)\n    const optionsAndArgs = Array.getSomes([depth, repository, config.directory])\n    return Console.log(\n      \"Running 'minigit clone' with the following options and arguments: \" +\n        `'${Array.join(optionsAndArgs, \", \")}'`\n    )\n  }\n)\n```\n\n#### Key Points to Note:\n\n1. **Importing Modules:**\n\n   - The `Args` module from `@effect/cli` is utilized to define positional arguments for both `add` and `clone` subcommands.\n   - The `Array` module from `effect` is used to handle arrays and provide utility functions like `Array.match` and `Array.join`.\n\n2. **Configuring Commands:**\n\n   - Both subcommands utilize options and arguments that allow for detailed configuration, reflecting common use cases in command-line interfaces.\n   - The `Options.withAlias` method simplifies command usage by providing shorthand aliases like `-v` for `--verbose`.\n\n3. **Command Handlers:**\n   - Each subcommand has a handler that logs execution details, which helps in understanding the flow and actions of the CLI commands.\n\n### Assembling Your CLI Application\n\nNow that you've defined all the necessary commands for your CLI application, it's time to assemble them into a fully functional command-line interface. This section will guide you through setting up the CLI to run within a NodeJS environment, assuming that you've already installed `@effect/platform-node` as described in the [Installation](#installation) guide.\n\nLet's put together the `minigit` CLI:\n\n```ts\nimport { Args, Command, Options } from \"@effect/cli\"\nimport { NodeContext, NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect, Option, Array } from \"effect\"\n\n// minigit [--version] [-h | --help] [-c <name>=<value>]\nconst configs = Options.keyValueMap(\"c\").pipe(Options.optional)\nconst minigit = Command.make(\"minigit\", { configs }, ({ configs }) =>\n  Option.match(configs, {\n    onNone: () => Console.log(\"Running 'minigit'\"),\n    onSome: (configs) => {\n      const keyValuePairs = Array.fromIterable(configs)\n        .map(([key, value]) => `${key}=${value}`)\n        .join(\", \")\n      return Console.log(\n        `Running 'minigit' with the following configs: ${keyValuePairs}`\n      )\n    }\n  })\n)\n\n// minigit add [-v | --verbose] [--] [<pathspec>...]\nconst pathspec = Args.text({ name: \"pathspec\" }).pipe(Args.repeated)\nconst verbose = Options.boolean(\"verbose\").pipe(Options.withAlias(\"v\"))\nconst minigitAdd = Command.make(\n  \"add\",\n  { pathspec, verbose },\n  ({ pathspec, verbose }) => {\n    const paths = Array.match(pathspec, {\n      onEmpty: () => \"\",\n      onNonEmpty: (paths) => ` ${Array.join(paths, \" \")}`\n    })\n    return Console.log(\n      `Running 'minigit add${paths}' with '--verbose ${verbose}'`\n    )\n  }\n)\n\n// minigit clone [--depth <depth>] [--] <repository> [<directory>]\nconst repository = Args.text({ name: \"repository\" })\nconst directory = Args.text({ name: \"directory\" }).pipe(Args.optional)\nconst depth = Options.integer(\"depth\").pipe(Options.optional)\nconst minigitClone = Command.make(\n  \"clone\",\n  { repository, directory, depth },\n  (config) => {\n    const depth = Option.map(config.depth, (depth) => `--depth ${depth}`)\n    const repository = Option.some(config.repository)\n    const optionsAndArgs = Array.getSomes([depth, repository, config.directory])\n    return Console.log(\n      \"Running 'minigit clone' with the following options and arguments: \" +\n        `'${Array.join(optionsAndArgs, \", \")}'`\n    )\n  }\n)\n\n// Combine all commands into the main 'minigit' command\nconst command = minigit.pipe(\n  Command.withSubcommands([minigitAdd, minigitClone])\n)\n\n// Initialize and run the CLI application\nconst cli = Command.run(command, {\n  name: \"Minigit Distributed Version Control\",\n  version: \"v1.0.0\"\n})\n\ncli(process.argv).pipe(Effect.provide(NodeContext.layer), NodeRuntime.runMain)\n```\n\n#### Key Features and Configuration:\n\n- **Command Integration:** The `minigit` command integrates both `add` and `clone` as subcommands, enabling a structured approach to handle different functionalities within the same CLI application.\n- **Environment Setup:** We've imported `NodeContext` and `NodeRuntime` to ensure that our CLI application correctly interacts with NodeJS's runtime environment, making full use of Node-specific features.\n- **Command Execution:** By using `Command.run`, the CLI application is formally structured with a specified name and version, and is ready to execute based on the defined command structure.\n- **Execution Setup**: The `cli(process.argv)` call processes the command-line arguments and runs the CLI application. The `Effect.provide(NodeContext.layer)` injects the necessary Node.js context, and `NodeRuntime.runMain` ensures proper execution within the Node.js environment.\n\n### Running the CLI Application\n\nNow that your CLI application, `minigit`, is fully assembled and prepared, it's time to see it in action! This section will guide you through running `minigit` directly from the command line, using the example file `minigit.ts`. If you are experimenting using the `minigit` example from the provided [repository](./examples/minigit.ts), the same instructions apply, just replace the command file name with `npx tsx ./examples/minigit.ts`.\n\n#### Executing Built-In Options\n\nFirst, let’s test out the built-in options to understand the core functionalities of our CLI application.\n\nRun the following command to display the current version of your CLI application:\n\n```sh\nnpx tsx minigit.ts --version\n# Output: v1.0.0\n```\n\nTo view the help documentation and understand the usage of each command within `minigit`, use the `-h` or `--help` option:\n\n```sh\nnpx tsx minigit.ts --help\n```\n\nOutput:\n\n```\nMinigit Distributed Version Control\n\nMinigit Distributed Version Control v1.0.0\n\nUSAGE\n\n$ minigit [-c text]\n\nOPTIONS\n\n-c text\n\n  A user-defined piece of text.\n\n  This setting is a property argument which:\n\n    - May be specified a single time:  '-c key1=value key2=value2'\n\n    - May be specified multiple times: '-c key1=value -c key2=value2'\n\n  This setting is optional.\n\n--completions sh | bash | fish | zsh\n\n  One of the following: sh, bash, fish, zsh\n\n  Generate a completion script for a specific shell\n\n  This setting is optional.\n\n(-h, --help)\n\n  A true or false value.\n\n  Show the help documentation for a command\n\n  This setting is optional.\n\n--wizard\n\n  A true or false value.\n\n  Start wizard mode for a command\n\n  This setting is optional.\n\n--version\n\n  A true or false value.\n\n  Show the version of the application\n\n  This setting is optional.\n\nCOMMANDS\n\n  - add [(-v, --verbose)] <pathspec>...\n\n  - clone [--depth integer] <repository> [<directory>]\n```\n\nThis output provides a breakdown of all available commands and options, helping users navigate through the functionalities offered by `minigit`.\n\nTo get more detailed help on subcommands like `add`, simply append `--help` after the subcommand:\n\n```sh\nnpx tsx minigit.ts add --help\n```\n\nOutput:\n\n```\nMinigit Distributed Version Control\n\nMinigit Distributed Version Control v1.0.0\n\nUSAGE\n\n$ add [(-v, --verbose)] <pathspec>...\n\nARGUMENTS\n\n<pathspec>...\n\n  A user-defined piece of text.\n\n  This argument may be repeated zero or more times.\n\nOPTIONS\n\n(-v, --verbose)\n\n  A true or false value.\n\n  This setting is optional.\n\n--completions sh | bash | fish | zsh\n\n  One of the following: sh, bash, fish, zsh\n\n  Generate a completion script for a specific shell\n\n  This setting is optional.\n\n(-h, --help)\n\n  A true or false value.\n\n  Show the help documentation for a command\n\n  This setting is optional.\n\n--wizard\n\n  A true or false value.\n\n  Start wizard mode for a command\n\n  This setting is optional.\n\n--version\n\n  A true or false value.\n\n  Show the version of the application\n\n  This setting is optional.\n```\n\n#### Executing User-Defined Commands\n\nBeyond viewing documentation, `minigit` allows you to execute commands with specific options to tailor its behavior.\n\nHere's how you can add files with the verbose option enabled or disabled:\n\n```sh\nnpx tsx minigit.ts add .\n# Output: Running 'minigit add .' with '--verbose false'\n```\n\n```sh\nnpx tsx minigit.ts add --verbose .\n# Output: Running 'minigit add .' with '--verbose true'\n```\n\n```sh\nnpx tsx minigit.ts clone --depth 1 https://github.com/Effect-TS/cli.git\n# Output: Running 'minigit clone' with the following options and arguments: '--depth 1, https://github.com/Effect-TS/cli.git'\n```\n\n## Accessing Parent Arguments in Subcommands\n\nIn certain scenarios, you may want your subcommands to have access to the `Options` and `Args` passed to their parent commands.\n\nSince `Command` is a subtype of `Effect`, you can use `Effect.flatMap` within a subcommand's handler to extract the `Config` from a parent command. This technique allows subcommands to utilize the configuration parameters specified at higher levels in the command hierarchy.\n\nFor example, let's say our `minigit clone` subcommand needs access to the configuration parameters passed to the parent `minigit` command via `minigit -c key=value`. We can accomplish this by modifying the `clone` command's handler to use `Effect.flatMap` with the parent `minigit` command:\n\n```ts\nconst repository = Args.text({ name: \"repository\" })\nconst directory = Args.directory().pipe(Args.optional)\nconst depth = Options.integer(\"depth\").pipe(Options.optional)\nconst minigitClone = Command.make(\n  \"clone\",\n  { repository, directory, depth },\n  (subcommandConfig) =>\n    // By using `Effect.flatMap` on the parent command, we get access to its parsed config\n    Effect.flatMap(minigit, (parentConfig) => {\n      const depth = Option.map(\n        subcommandConfig.depth,\n        (depth) => `--depth ${depth}`\n      )\n      const repository = Option.some(subcommandConfig.repository)\n      const optionsAndArgs = Array.getSomes([\n        depth,\n        repository,\n        subcommandConfig.directory\n      ])\n      const configs = Option.match(parentConfig.configs, {\n        onNone: () => \"\",\n        onSome: (map) =>\n          Array.fromIterable(map)\n            .map(([key, value]) => `${key}=${value}`)\n            .join(\", \")\n      })\n      return Console.log(\n        \"Running 'minigit clone' with the following options and arguments: \" +\n          `'${Array.join(optionsAndArgs, \", \")}'\\n` +\n          `and the following configuration parameters: ${configs}`\n      )\n    })\n)\n```\n\nBy examining the type of `minigitClone` after incorporating the parent command, you can see the added context:\n\n```ts\nconst minigitClone: Command.Command<\n  \"clone\",\n  // The parent `minigit` command has been added to the environment required by\n  // the subcommand's handler\n  Command.Command.Context<\"minigit\">,\n  never,\n  {\n    readonly repository: string\n    readonly directory: Option.Option<string>\n    readonly depth: Option.Option<number>\n  }\n>\n```\n\nThe parent command's context will be \"erased\" from the subcommand's environment when using `Command.withSubcommands`:\n\n```ts\nconst command = minigit.pipe(Command.withSubcommands([minigitClone]))\n//    ^? Command<\"minigit\", never, ..., ...>\n```\n\nFinally, run the command with some configuration parameters to see the result:\n\n```sh\nnpx tsx minigit.ts -c key1=value1 clone --depth 1 https://github.com/Effect-TS/cli.git\n# Running 'minigit clone' with the following options and arguments: '--depth 1, https://github.com/Effect-TS/cli.git'\n# and the following configuration parameters: key1=value1\n```\n\n# Frequently Asked Questions (FAQ)\n\n## Command-Line Argument Parsing Specification\n\nUnderstanding how command-line arguments are parsed in your applications is crucial for designing effective and user-friendly command interfaces. Here are the key rules that the internal command-line argument parser follows:\n\n### 1. Order of Options and Subcommands\n\nOptions and arguments (collectively referred to as `Options` / `Args`) associated with a command must be specified **before** any subcommands. This rule helps the parser determine which command the options apply to.\n\n**Examples:**\n\n- **Correct Usage**:\n\n  ```sh\n  program -v subcommand\n  ```\n\n  In this example, the `-v` option applies to the main program before the subcommand is processed.\n\n- **Incorrect Usage**:\n  ```sh\n  program subcommand -v\n  ```\n  Here, placing `-v` after the subcommand causes confusion as to whether `-v` applies to the main program or the subcommand.\n\n### 2. Parsing Options Before Positional Arguments\n\nThe parser is designed to recognize options before any positional arguments. This ordering ensures clarity and prevents confusion between options and regular arguments.\n\n**Examples:**\n\n- **Valid Command**:\n\n  ```sh\n  program --option arg\n  ```\n\n  This command correctly places the `--option` before the positional argument `arg`.\n\n- **Invalid Command**:\n  ```sh\n  program arg --option\n  ```\n  Placing an argument before an option is not allowed and can lead to errors in command processing.\n\n### 3. Handling Excess Arguments\n\nIf there are excess arguments that do not fit the expected structure of the command, the parser will return a `ValidationError`. This safeguard prevents the execution of malformed or potentially harmful commands.\n\n# API Reference\n\n- https://effect-ts.github.io/effect/docs/cli\n"
  },
  {
    "path": "packages/cli/docgen.json",
    "content": "{\n  \"$schema\": \"../../node_modules/@effect/docgen/schema.json\",\n  \"exclude\": [\"src/internal/**/*.ts\"],\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/cli/src/\",\n  \"examplesCompilerOptions\": {\n    \"noEmit\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"module\": \"ES2022\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n    \"paths\": {\n      \"effect\": [\"../../../effect/src/index.js\"],\n      \"effect/*\": [\"../../../effect/src/*.js\"],\n      \"@effect/platform\": [\"../../../platform/src/index.js\"],\n      \"@effect/platform/*\": [\"../../../platform/src/*.js\"],\n      \"@effect/platform-node\": [\"../../../platform-node/src/index.js\"],\n      \"@effect/platform-node/*\": [\"../../../platform-node/src/*.js\"],\n      \"@effect/platform-node-shared\": [\n        \"../../../platform-node-shared/src/index.js\"\n      ],\n      \"@effect/platform-node-shared/*\": [\n        \"../../../platform-node-shared/src/*.js\"\n      ],\n      \"@effect/printer\": [\"../../../printer/src/index.js\"],\n      \"@effect/printer/*\": [\"../../../printer/src/*.js\"],\n      \"@effect/printer-ansi\": [\"../../../printer-ansi/src/index.js\"],\n      \"@effect/printer-ansi/*\": [\"../../../printer-ansi/src/*.js\"],\n      \"@effect/typeclass\": [\"../../../typeclass/src/index.js\"],\n      \"@effect/typeclass/*\": [\"../../../typeclass/src/*.js\"],\n      \"@effect/cli\": [\"../../../cli/src/index.js\"],\n      \"@effect/cli/*\": [\"../../../cli/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/cli/examples/minigit.ts",
    "content": "import { Args, Command, Options } from \"@effect/cli\"\nimport { NodeContext, NodeRuntime } from \"@effect/platform-node\"\nimport { Array, Config, ConfigProvider, Console, Effect, Option } from \"effect\"\n\n// minigit [--version] [-h | --help] [-c <name>=<value>]\nconst configs = Options.keyValueMap(\"c\").pipe(Options.optional)\nconst minigit = Command.make(\"minigit\", { configs }, ({ configs }) =>\n  Option.match(configs, {\n    onNone: () => Console.log(\"Running 'minigit'\"),\n    onSome: (configs) => {\n      const keyValuePairs = Array.fromIterable(configs)\n        .map(([key, value]) => `${key}=${value}`)\n        .join(\", \")\n      return Console.log(`Running 'minigit' with the following configs: ${keyValuePairs}`)\n    }\n  }))\n\n// minigit add   [-v | --verbose] [--] [<pathspec>...]\nconst pathspec = Args.text({ name: \"pathspec\" }).pipe(Args.repeated)\nconst verbose = Options.boolean(\"verbose\").pipe(\n  Options.withAlias(\"v\"),\n  Options.withFallbackConfig(Config.boolean(\"VERBOSE\"))\n)\nconst minigitAdd = Command.make(\"add\", { pathspec, verbose }, ({ pathspec, verbose }) => {\n  const paths = Array.match(pathspec, {\n    onEmpty: () => \"\",\n    onNonEmpty: (paths) => ` ${Array.join(paths, \" \")}`\n  })\n  return Console.log(`Running 'minigit add${paths}' with '--verbose ${verbose}'`)\n})\n\n// minigit clone [--depth <depth>] [--] <repository> [<directory>]\nconst repository = Args.text({ name: \"repository\" })\nconst directory = Args.directory().pipe(Args.optional)\nconst depth = Options.integer(\"depth\").pipe(\n  Options.withFallbackConfig(Config.integer(\"DEPTH\")),\n  Options.optional\n)\nconst minigitClone = Command.make(\n  \"clone\",\n  { repository, directory, depth },\n  (subcommandConfig) =>\n    Effect.flatMap(minigit, (parentConfig) => {\n      const depth = Option.map(subcommandConfig.depth, (depth) => `--depth ${depth}`)\n      const repository = Option.some(subcommandConfig.repository)\n      const optionsAndArgs = Array.getSomes([depth, repository, subcommandConfig.directory])\n      const configs = Option.match(parentConfig.configs, {\n        onNone: () => \"\",\n        onSome: (map) => Array.fromIterable(map).map(([key, value]) => `${key}=${value}`).join(\", \")\n      })\n      return Console.log(\n        \"Running 'minigit clone' with the following options and arguments: \" +\n          `'${Array.join(optionsAndArgs, \", \")}'\\n` +\n          `and the following configuration parameters: ${configs}`\n      )\n    })\n)\n\nconst command = minigit.pipe(Command.withSubcommands([minigitAdd, minigitClone]))\n\nconst cli = Command.run(command, {\n  name: \"Minigit Distributed Version Control\",\n  version: \"v1.0.0\"\n})\n\nEffect.suspend(() => cli(process.argv)).pipe(\n  Effect.withConfigProvider(ConfigProvider.nested(ConfigProvider.fromEnv(), \"GIT\")),\n  Effect.provide(NodeContext.layer),\n  NodeRuntime.runMain\n)\n"
  },
  {
    "path": "packages/cli/examples/naval-fate/domain.ts",
    "content": "import * as Data from \"effect/Data\"\nimport * as Schema from \"effect/Schema\"\n\n/**\n * An error that occurs when attempting to create a Naval Fate ship that already\n * exists.\n */\nexport class ShipExistsError extends Data.TaggedError(\"ShipExistsError\")<{\n  readonly name: string\n}> {\n  toString(): string {\n    return `ShipExistsError: ship with name '${this.name}' already exists`\n  }\n}\n\n/**\n * An error that occurs when attempting to move a Naval Fate ship that does not\n * exist.\n */\nexport class ShipNotFoundError extends Data.TaggedError(\"ShipNotFoundError\")<{\n  readonly name: string\n  readonly x: number\n  readonly y: number\n}> {\n  toString(): string {\n    return `ShipNotFoundError: ship with name '${this.name}' does not exist`\n  }\n}\n\n/**\n * An error that occurs when attempting to move a Naval Fate ship to coordinates\n * already occupied by another ship.\n */\nexport class CoordinatesOccupiedError extends Data.TaggedError(\"CoordinatesOccupiedError\")<{\n  readonly name: string\n  readonly x: number\n  readonly y: number\n}> {\n  toString(): string {\n    return `CoordinatesOccupiedError: ship with name '${this.name}' already occupies coordinates (${this.x}, ${this.y})`\n  }\n}\n\n/**\n * Represents a Naval Fate ship.\n */\nexport class Ship extends Schema.Class<Ship>(\"Ship\")({\n  name: Schema.String,\n  x: Schema.Number,\n  y: Schema.Number,\n  status: Schema.Literal(\"sailing\", \"destroyed\")\n}) {\n  static readonly create = (name: string) => new Ship({ name, x: 0, y: 0, status: \"sailing\" })\n\n  hasCoordinates(x: number, y: number): boolean {\n    return this.x === x && this.y === y\n  }\n\n  move(x: number, y: number): Ship {\n    return new Ship({ name: this.name, x, y, status: this.status })\n  }\n\n  destroy(): Ship {\n    return new Ship({ name: this.name, x: this.x, y: this.y, status: \"destroyed\" })\n  }\n}\n\n/**\n * Represents a Naval Fate mine.\n */\nexport class Mine extends Schema.Class<Mine>(\"Mine\")({\n  x: Schema.Number,\n  y: Schema.Number\n}) {\n  static readonly create = (x: number, y: number) => new Mine({ x, y })\n\n  hasCoordinates(x: number, y: number): boolean {\n    return this.x === x && this.y === y\n  }\n}\n"
  },
  {
    "path": "packages/cli/examples/naval-fate/store.ts",
    "content": "import * as KeyValueStore from \"@effect/platform/KeyValueStore\"\nimport * as Arr from \"effect/Array\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\nimport { CoordinatesOccupiedError, Mine, Ship, ShipExistsError, ShipNotFoundError } from \"./domain.js\"\n\n/**\n * Represents the storage layer for the Naval Fate command-line application.\n */\nexport interface NavalFateStore {\n  createShip(name: string): Effect.Effect<Ship, ShipExistsError>\n  moveShip(\n    name: string,\n    x: number,\n    y: number\n  ): Effect.Effect<Ship, CoordinatesOccupiedError | ShipNotFoundError>\n  shoot(x: number, y: number): Effect.Effect<void>\n  setMine(x: number, y: number): Effect.Effect<void>\n  removeMine(x: number, y: number): Effect.Effect<void>\n}\n\nexport const NavalFateStore = Context.GenericTag<NavalFateStore>(\"NavalFateStore\")\n\nexport const make = Effect.gen(function*() {\n  const shipsStore = yield* Effect.map(\n    KeyValueStore.KeyValueStore,\n    (store) => store.forSchema(Schema.ReadonlyMap({ key: Schema.String, value: Ship }))\n  )\n  const minesStore = yield* Effect.map(\n    KeyValueStore.KeyValueStore,\n    (store) => store.forSchema(Schema.Array(Mine))\n  )\n\n  const getShips = shipsStore.get(\"ships\").pipe(\n    Effect.map(Option.getOrElse<ReadonlyMap<string, Ship>>(() => new Map())),\n    Effect.orDie\n  )\n  const getMines = minesStore.get(\"mines\").pipe(\n    Effect.map(Option.getOrElse<ReadonlyArray<Mine>>(() => [])),\n    Effect.orDie\n  )\n  const setShips = (ships: ReadonlyMap<string, Ship>) => shipsStore.set(\"ships\", ships).pipe(Effect.orDie)\n  const setMines = (mines: ReadonlyArray<Mine>) => minesStore.set(\"mines\", mines).pipe(Effect.orDie)\n\n  const createShip: NavalFateStore[\"createShip\"] = (name) =>\n    Effect.gen(function*() {\n      const oldShips = yield* getShips\n      const foundShip = Option.fromNullable(oldShips.get(name))\n      if (Option.isSome(foundShip)) {\n        return yield* Effect.fail(new ShipExistsError({ name }))\n      }\n      const ship = Ship.create(name)\n      const newShips = new Map(oldShips).set(name, ship)\n      yield* setShips(newShips)\n      return ship\n    })\n\n  const moveShip: NavalFateStore[\"moveShip\"] = (name, x, y) =>\n    Effect.gen(function*() {\n      const oldShips = yield* getShips\n      const foundShip = Option.fromNullable(oldShips.get(name))\n      if (Option.isNone(foundShip)) {\n        return yield* Effect.fail(new ShipNotFoundError({ name, x, y }))\n      }\n      const shipAtCoords = pipe(\n        Arr.fromIterable(oldShips.values()),\n        Arr.findFirst((ship) => ship.hasCoordinates(x, y))\n      )\n      if (Option.isSome(shipAtCoords)) {\n        return yield* Effect.fail(\n          new CoordinatesOccupiedError({ name: shipAtCoords.value.name, x, y })\n        )\n      }\n      const mines = yield* getMines\n      const mineAtCoords = Arr.findFirst(mines, (mine) => mine.hasCoordinates(x, y))\n      const ship = Option.isSome(mineAtCoords)\n        ? foundShip.value.move(x, y).destroy()\n        : foundShip.value.move(x, y)\n      const newShips = new Map(oldShips).set(name, ship)\n      yield* setShips(newShips)\n      return ship\n    })\n\n  const shoot: NavalFateStore[\"shoot\"] = (x, y) =>\n    Effect.gen(function*() {\n      const oldShips = yield* getShips\n      const shipAtCoords = pipe(\n        Arr.fromIterable(oldShips.values()),\n        Arr.findFirst((ship) => ship.hasCoordinates(x, y))\n      )\n      if (Option.isSome(shipAtCoords)) {\n        const ship = shipAtCoords.value.destroy()\n        const newShips = new Map(oldShips).set(ship.name, ship)\n        yield* setShips(newShips)\n      }\n    })\n\n  const setMine: NavalFateStore[\"setMine\"] = (x, y) =>\n    Effect.gen(function*() {\n      const mines = yield* getMines\n      const mineAtCoords = Arr.findFirst(mines, (mine) => mine.hasCoordinates(x, y))\n      if (Option.isNone(mineAtCoords)) {\n        const mine = Mine.create(x, y)\n        const newMines = Arr.append(mines, mine)\n        yield* setMines(newMines)\n      }\n    })\n\n  const removeMine: NavalFateStore[\"removeMine\"] = (x, y) =>\n    Effect.gen(function*() {\n      const mines = yield* getMines\n      const mineAtCoords = Arr.findFirstIndex(mines, (mine) => mine.hasCoordinates(x, y))\n      if (Option.isSome(mineAtCoords)) {\n        const newMines = Arr.remove(mines, mineAtCoords.value)\n        yield* setMines(newMines)\n      }\n    })\n\n  return NavalFateStore.of({\n    createShip,\n    moveShip,\n    shoot,\n    setMine,\n    removeMine\n  })\n})\n\nexport const layer = Layer.effect(NavalFateStore, make)\n"
  },
  {
    "path": "packages/cli/examples/naval-fate.ts",
    "content": "import { Args, CliConfig, Command, Options } from \"@effect/cli\"\nimport { NodeContext, NodeKeyValueStore, NodeRuntime } from \"@effect/platform-node\"\nimport * as Console from \"effect/Console\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as NavalFateStore from \"./naval-fate/store.js\"\n\nconst { createShip, moveShip, removeMine, setMine, shoot } = Effect.serviceFunctions(\n  NavalFateStore.NavalFateStore\n)\n\n// naval_fate [-h | --help] [--version]\n// naval_fate ship new <name>...\n// naval_fate ship move [--speed=<kn>] <name> <x> <y>\n// naval_fate ship shoot <x> <y>\n// naval_fate mine set <x> <y> [--moored]\n// naval_fate mine remove <x> <y> [--moored]\n\nconst nameArg = Args.text({ name: \"name\" }).pipe(Args.withDescription(\"The name of the ship\"))\nconst xArg = Args.integer({ name: \"x\" }).pipe(Args.withDescription(\"The x coordinate\"))\nconst yArg = Args.integer({ name: \"y\" }).pipe(Args.withDescription(\"The y coordinate\"))\nconst coordinatesArg = { x: xArg, y: yArg }\nconst nameAndCoordinatesArg = { name: nameArg, ...coordinatesArg }\n\nconst mooredOption = Options.boolean(\"moored\").pipe(\n  Options.withDescription(\"Whether the mine is moored (anchored) or drifting\")\n)\nconst speedOption = Options.integer(\"speed\").pipe(\n  Options.withDescription(\"Speed in knots\"),\n  Options.withDefault(10)\n)\n\nconst shipCommand = Command.make(\"ship\", {\n  verbose: Options.boolean(\"verbose\")\n}).pipe(Command.withDescription(\"Controls a ship in Naval Fate\"))\n\nconst newShipCommand = Command.make(\"new\", {\n  name: nameArg\n}, ({ name }) =>\n  Effect.gen(function*() {\n    const { verbose } = yield* shipCommand\n    yield* createShip(name)\n    yield* Console.log(`Created ship: '${name}'`)\n    if (verbose) {\n      yield* Console.log(`Verbose mode enabled`)\n    }\n  })).pipe(Command.withDescription(\"Create a new ship\"))\n\nconst moveShipCommand = Command.make(\"move\", {\n  ...nameAndCoordinatesArg,\n  speed: speedOption\n}, ({ name, speed, x, y }) =>\n  Effect.gen(function*() {\n    yield* moveShip(name, x, y)\n    yield* Console.log(`Moving ship '${name}' to coordinates (${x}, ${y}) at ${speed} knots`)\n  })).pipe(Command.withDescription(\"Move a ship\"))\n\nconst shootShipCommand = Command.make(\n  \"shoot\",\n  { ...coordinatesArg },\n  ({ x, y }) =>\n    Effect.gen(function*() {\n      yield* shoot(x, y)\n      yield* Console.log(`Shot cannons at coordinates (${x}, ${y})`)\n    })\n).pipe(Command.withDescription(\"Shoot from a ship\"))\n\nconst mineCommand = Command.make(\"mine\").pipe(\n  Command.withDescription(\"Controls mines in Naval Fate\")\n)\n\nconst setMineCommand = Command.make(\"set\", {\n  ...coordinatesArg,\n  moored: mooredOption\n}, ({ moored, x, y }) =>\n  Effect.gen(function*() {\n    yield* setMine(x, y)\n    yield* Console.log(`Set ${moored ? \"moored\" : \"drifting\"} mine at coordinates (${x}, ${y})`)\n  })).pipe(Command.withDescription(\"Set a mine at specific coordinates\"))\n\nconst removeMineCommand = Command.make(\"remove\", {\n  ...coordinatesArg\n}, ({ x, y }) =>\n  Effect.gen(function*() {\n    yield* removeMine(x, y)\n    yield* Console.log(`Removing mine at coordinates (${x}, ${y}), if present`)\n  })).pipe(Command.withDescription(\"Remove a mine at specific coordinates\"))\n\nconst command = Command.make(\"naval_fate\").pipe(\n  Command.withDescription(\"An implementation of the Naval Fate CLI application.\"),\n  Command.withSubcommands([\n    shipCommand.pipe(Command.withSubcommands([\n      newShipCommand,\n      moveShipCommand,\n      shootShipCommand\n    ])),\n    mineCommand.pipe(Command.withSubcommands([\n      setMineCommand,\n      removeMineCommand\n    ]))\n  ])\n)\n\nconst ConfigLive = CliConfig.layer({\n  showBuiltIns: false\n})\n\nconst NavalFateLive = NavalFateStore.layer.pipe(\n  Layer.provide(NodeKeyValueStore.layerFileSystem(\"naval-fate-store\"))\n)\n\nconst MainLayer = Layer.mergeAll(\n  ConfigLive,\n  NavalFateLive,\n  NodeContext.layer\n)\n\nconst cli = Command.run(command, {\n  name: \"Naval Fate\",\n  version: \"1.0.0\"\n})\n\nEffect.suspend(() => cli(process.argv)).pipe(\n  Effect.provide(MainLayer),\n  Effect.tapErrorCause(Effect.logError),\n  NodeRuntime.runMain\n)\n"
  },
  {
    "path": "packages/cli/examples/prompt.ts",
    "content": "import * as Command from \"@effect/cli/Command\"\nimport * as Prompt from \"@effect/cli/Prompt\"\nimport * as NodeContext from \"@effect/platform-node/NodeContext\"\nimport * as Runtime from \"@effect/platform-node/NodeRuntime\"\nimport * as Effect from \"effect/Effect\"\n\nconst colorPrompt = Prompt.select({\n  message: \"Pick your favorite color\",\n  choices: [\n    {\n      title: \"Red\",\n      value: \"#ff0000\",\n      description: \"This option has a description\"\n    },\n    { title: \"Green\", value: \"#00ff00\", description: \"So does this one\" },\n    { title: \"Blue\", value: \"#0000ff\", disabled: true }\n  ]\n})\n\nconst confirmPrompt = Prompt.confirm({\n  message: \"Can you please confirm?\"\n})\n\nconst datePrompt = Prompt.date({\n  message: \"What's your birth day?\",\n  dateMask: \"\\\"Year:\\\" YYYY, \\\"Month:\\\" MM, \\\"Day:\\\" DD \\\\\\\\\\\\\\\\||// \\\\Hour: HH, \\\\Minute: mm, \\\"Seconds:\\\" ss\",\n  validate: (date) =>\n    date.getTime() > Date.now()\n      ? Effect.fail(\"Your birth day can't be in the future\")\n      : Effect.succeed(date)\n})\n\nconst numberPrompt = Prompt.float({\n  message: `What is your favorite number?`,\n  validate: (n) => n > 0 ? Effect.succeed(n) : Effect.fail(\"must be greater than 0\")\n})\n\nconst passwordPrompt = Prompt.password({\n  message: \"Enter your password: \",\n  validate: (value) =>\n    value.length === 0\n      ? Effect.fail(\"Password cannot be empty\")\n      : Effect.succeed(value)\n})\n\nconst togglePrompt = Prompt.toggle({\n  message: \"Yes or no?\",\n  active: \"yes\",\n  inactive: \"no\"\n})\n\nconst prompt = Prompt.all([\n  colorPrompt,\n  confirmPrompt,\n  datePrompt,\n  numberPrompt,\n  passwordPrompt,\n  togglePrompt\n])\n\nconst command = Command.prompt(\"favorites\", prompt, Effect.log)\n\nconst cli = Command.run(command, {\n  name: \"Prompt Examples\",\n  version: \"0.0.1\"\n})\n\nEffect.suspend(() => cli(process.argv)).pipe(\n  Effect.provide(NodeContext.layer),\n  Runtime.runMain\n)\n"
  },
  {
    "path": "packages/cli/package.json",
    "content": "{\n  \"name\": \"@effect/cli\",\n  \"version\": \"0.75.0\",\n  \"type\": \"module\",\n  \"license\": \"MIT\",\n  \"description\": \"A library for building command-line interfaces with Effect\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/cli\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"cli\",\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"keywords\": [\n    \"cli\",\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"peerDependencies\": {\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/printer\": \"workspace:^\",\n    \"@effect/printer-ansi\": \"workspace:^\",\n    \"effect\": \"workspace:^\"\n  },\n  \"devDependencies\": {\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/platform-node\": \"workspace:^\",\n    \"@effect/printer\": \"workspace:^\",\n    \"@effect/printer-ansi\": \"workspace:^\",\n    \"@types/ini\": \"^4.1.1\",\n    \"effect\": \"workspace:^\"\n  },\n  \"dependencies\": {\n    \"ini\": \"^4.1.3\",\n    \"toml\": \"^3.0.0\",\n    \"yaml\": \"^2.5.0\"\n  },\n  \"effect\": {\n    \"generateIndex\": {\n      \"include\": [\n        \"**/*\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/cli/src/Args.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { FileSystem } from \"@effect/platform/FileSystem\"\nimport type { Path } from \"@effect/platform/Path\"\nimport type { QuitException, Terminal } from \"@effect/platform/Terminal\"\nimport type { NonEmptyArray } from \"effect/Array\"\nimport type { Config } from \"effect/Config\"\nimport type { Effect } from \"effect/Effect\"\nimport type { Option } from \"effect/Option\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport type { Redacted } from \"effect/Redacted\"\nimport type { Schema } from \"effect/Schema\"\nimport type { Secret } from \"effect/Secret\"\nimport type { CliConfig } from \"./CliConfig.js\"\nimport type { HelpDoc } from \"./HelpDoc.js\"\nimport * as InternalArgs from \"./internal/args.js\"\nimport type { Primitive } from \"./Primitive.js\"\nimport type { Usage } from \"./Usage.js\"\nimport type { ValidationError } from \"./ValidationError.js\"\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport const ArgsTypeId: unique symbol = InternalArgs.ArgsTypeId\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport type ArgsTypeId = typeof ArgsTypeId\n\n/**\n * Represents arguments that can be passed to a command-line application.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface Args<A> extends Args.Variance<A>, Pipeable {}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Args {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Variance<A> {\n    readonly [ArgsTypeId]: {\n      readonly _A: (_: never) => A\n    }\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface BaseArgsConfig {\n    readonly name?: string\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface PathArgsConfig extends BaseArgsConfig {\n    readonly exists?: Primitive.PathExists\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface FormatArgsConfig extends BaseArgsConfig {\n    readonly format?: \"json\" | \"yaml\" | \"ini\" | \"toml\"\n  }\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace All {\n  /**\n   * @since 1.0.0\n   */\n  export type ArgsAny = Args<any>\n\n  /**\n   * @since 1.0.0\n   */\n  export type ReturnIterable<T extends Iterable<ArgsAny>> = [T] extends [Iterable<Args.Variance<infer A>>] ?\n    Args<Array<A>>\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type ReturnTuple<T extends ReadonlyArray<unknown>> = Args<\n    T[number] extends never ? []\n      : {\n        -readonly [K in keyof T]: [T[K]] extends [Args.Variance<infer _A>] ? _A : never\n      }\n  > extends infer X ? X : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type ReturnObject<T> = [T] extends [{ [K: string]: ArgsAny }] ? Args<\n      {\n        -readonly [K in keyof T]: [T[K]] extends [Args.Variance<infer _A>] ? _A : never\n      }\n    >\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type Return<\n    Arg extends Iterable<ArgsAny> | Record<string, ArgsAny>\n  > = [Arg] extends [ReadonlyArray<ArgsAny>] ? ReturnTuple<Arg>\n    : [Arg] extends [Iterable<ArgsAny>] ? ReturnIterable<Arg>\n    : [Arg] extends [Record<string, ArgsAny>] ? ReturnObject<Arg>\n    : never\n}\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isArgs: (u: unknown) => u is Args<unknown> = InternalArgs.isArgs\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const all: <const Arg extends Iterable<Args<any>> | Record<string, Args<any>>>(\n  arg: Arg\n) => All.Return<Arg> = InternalArgs.all\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const atLeast: {\n  (times: 0): <A>(self: Args<A>) => Args<Array<A>>\n  (times: number): <A>(self: Args<A>) => Args<NonEmptyArray<A>>\n  <A>(self: Args<A>, times: 0): Args<Array<A>>\n  <A>(self: Args<A>, times: number): Args<NonEmptyArray<A>>\n} = InternalArgs.atLeast\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const atMost: {\n  (times: number): <A>(self: Args<A>) => Args<Array<A>>\n  <A>(self: Args<A>, times: number): Args<Array<A>>\n} = InternalArgs.atMost\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const between: {\n  (min: 0, max: number): <A>(self: Args<A>) => Args<Array<A>>\n  (min: number, max: number): <A>(self: Args<A>) => Args<NonEmptyArray<A>>\n  <A>(self: Args<A>, min: 0, max: number): Args<Array<A>>\n  <A>(self: Args<A>, min: number, max: number): Args<NonEmptyArray<A>>\n} = InternalArgs.between\n\n/**\n * Creates a boolean argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"boolean\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const boolean: (options?: Args.BaseArgsConfig) => Args<boolean> = InternalArgs.boolean\n\n/**\n * Creates a choice argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"choice\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const choice: <A>(\n  choices: ReadonlyArray<[string, A]>,\n  config?: Args.BaseArgsConfig\n) => Args<A> = InternalArgs.choice\n\n/**\n * Creates a date argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"date\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const date: (config?: Args.BaseArgsConfig) => Args<globalThis.Date> = InternalArgs.date\n\n/**\n * Creates a directory argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"directory\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const directory: (config?: Args.PathArgsConfig) => Args<string> = InternalArgs.directory\n\n/**\n * Creates a file argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"file\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const file: (config?: Args.PathArgsConfig) => Args<string> = InternalArgs.file\n\n/**\n * Creates a file argument that reads its contents.\n *\n * Can optionally provide a custom argument name (defaults to `\"file\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fileContent: (\n  config?: Args.BaseArgsConfig | undefined\n) => Args<readonly [path: string, content: Uint8Array]> = InternalArgs.fileContent\n\n/**\n * Creates a file argument that reads and parses its contents.\n *\n * Can optionally provide a custom argument name (defaults to `\"file\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fileParse: (config?: Args.FormatArgsConfig | undefined) => Args<unknown> = InternalArgs.fileParse\n\n/**\n * Creates a file argument that reads, parses and validates its contents.\n *\n * Can optionally provide a custom argument name (defaults to `\"file\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fileSchema: <I, A>(\n  schema: Schema<A, I, FileSystem | Path | Terminal>,\n  config?: Args.FormatArgsConfig | undefined\n) => Args<A> = InternalArgs.fileSchema\n\n/**\n * Creates a file argument that reads it's contents.\n *\n * Can optionally provide a custom argument name (defaults to `\"file\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fileText: (\n  config?: Args.BaseArgsConfig | undefined\n) => Args<readonly [path: string, content: string]> = InternalArgs.fileText\n\n/**\n * Creates a floating point number argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"float\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const float: (config?: Args.BaseArgsConfig) => Args<number> = InternalArgs.float\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getHelp: <A>(self: Args<A>) => HelpDoc = InternalArgs.getHelp\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getIdentifier: <A>(self: Args<A>) => Option<string> = InternalArgs.getIdentifier\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getMinSize: <A>(self: Args<A>) => number = InternalArgs.getMinSize\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getMaxSize: <A>(self: Args<A>) => number = InternalArgs.getMaxSize\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getUsage: <A>(self: Args<A>) => Usage = InternalArgs.getUsage\n\n/**\n * Creates an integer argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"integer\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const integer: (config?: Args.BaseArgsConfig) => Args<number> = InternalArgs.integer\n\n/**\n * @since 1.0.0\n * @category mapping\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): (self: Args<A>) => Args<B>\n  <A, B>(self: Args<A>, f: (a: A) => B): Args<B>\n} = InternalArgs.map\n\n/**\n * @since 1.0.0\n * @category mapping\n */\nexport const mapEffect: {\n  <A, B>(f: (a: A) => Effect<B, HelpDoc, FileSystem | Path | Terminal>): (self: Args<A>) => Args<B>\n  <A, B>(self: Args<A>, f: (a: A) => Effect<B, HelpDoc, FileSystem | Path | Terminal>): Args<B>\n} = InternalArgs.mapEffect\n\n/**\n * @since 1.0.0\n * @category mapping\n */\nexport const mapTryCatch: {\n  <A, B>(f: (a: A) => B, onError: (e: unknown) => HelpDoc): (self: Args<A>) => Args<B>\n  <A, B>(self: Args<A>, f: (a: A) => B, onError: (e: unknown) => HelpDoc): Args<B>\n} = InternalArgs.mapTryCatch\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const optional: <A>(self: Args<A>) => Args<Option<A>> = InternalArgs.optional\n\n/**\n *  Creates an empty argument.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const none: Args<void> = InternalArgs.none\n\n/**\n * Creates a path argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"path\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const path: (config?: Args.PathArgsConfig) => Args<string> = InternalArgs.path\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const repeated: <A>(self: Args<A>) => Args<Array<A>> = InternalArgs.repeated\n\n/**\n * Creates a text argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"redacted\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const redacted: (config?: Args.BaseArgsConfig) => Args<Redacted> = InternalArgs.redacted\n\n/**\n * Creates a text argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"secret\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const secret: (config?: Args.BaseArgsConfig) => Args<Secret> = InternalArgs.secret\n\n/**\n * Creates a text argument.\n *\n * Can optionally provide a custom argument name (defaults to `\"text\"`).\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const text: (config?: Args.BaseArgsConfig) => Args<string> = InternalArgs.text\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const validate: {\n  (\n    args: ReadonlyArray<string>,\n    config: CliConfig\n  ): <A>(self: Args<A>) => Effect<\n    [Array<string>, A],\n    ValidationError,\n    FileSystem | Path | Terminal\n  >\n  <A>(\n    self: Args<A>,\n    args: ReadonlyArray<string>,\n    config: CliConfig\n  ): Effect<\n    [Array<string>, A],\n    ValidationError,\n    FileSystem | Path | Terminal\n  >\n} = InternalArgs.validate\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withDefault: {\n  <const B>(fallback: B): <A>(self: Args<A>) => Args<B | A>\n  <A, const B>(self: Args<A>, fallback: B): Args<A | B>\n} = InternalArgs.withDefault\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withFallbackConfig: {\n  <B>(config: Config<B>): <A>(self: Args<A>) => Args<B | A>\n  <A, B>(self: Args<A>, config: Config<B>): Args<A | B>\n} = InternalArgs.withFallbackConfig\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withDescription: {\n  (description: string): <A>(self: Args<A>) => Args<A>\n  <A>(self: Args<A>, description: string): Args<A>\n} = InternalArgs.withDescription\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withSchema: {\n  <A, I extends A, B>(schema: Schema<B, I, FileSystem | Path | Terminal>): (self: Args<A>) => Args<B>\n  <A, I extends A, B>(self: Args<A>, schema: Schema<B, I, FileSystem | Path | Terminal>): Args<B>\n} = InternalArgs.withSchema\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const wizard: {\n  (\n    config: CliConfig\n  ): <A>(\n    self: Args<A>\n  ) => Effect<\n    Array<string>,\n    ValidationError | QuitException,\n    FileSystem | Path | Terminal\n  >\n  <A>(\n    self: Args<A>,\n    config: CliConfig\n  ): Effect<\n    Array<string>,\n    ValidationError | QuitException,\n    FileSystem | Path | Terminal\n  >\n} = InternalArgs.wizard\n"
  },
  {
    "path": "packages/cli/src/AutoCorrect.ts",
    "content": "/**\n * @since 1.0.0\n */\n\nimport type { CliConfig } from \"./CliConfig.js\"\nimport * as InternalAutoCorrect from \"./internal/autoCorrect.js\"\n\n/**\n * @since 1.0.0\n * @category utilities\n */\nexport const levensteinDistance: (first: string, second: string, config: CliConfig) => number =\n  InternalAutoCorrect.levensteinDistance\n"
  },
  {
    "path": "packages/cli/src/BuiltInOptions.ts",
    "content": "/**\n * @since 1.0.0\n */\n\nimport type { LogLevel } from \"effect/LogLevel\"\nimport type { Option } from \"effect/Option\"\nimport type { Command } from \"./CommandDescriptor.js\"\nimport type { HelpDoc } from \"./HelpDoc.js\"\nimport * as InternalBuiltInOptions from \"./internal/builtInOptions.js\"\nimport type { Options } from \"./Options.js\"\nimport type { Usage } from \"./Usage.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type BuiltInOptions =\n  | SetLogLevel\n  | ShowHelp\n  | ShowCompletions\n  | ShowWizard\n  | ShowVersion\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface SetLogLevel {\n  readonly _tag: \"SetLogLevel\"\n  readonly level: LogLevel\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface ShowHelp {\n  readonly _tag: \"ShowHelp\"\n  readonly usage: Usage\n  readonly helpDoc: HelpDoc\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface ShowCompletions {\n  readonly _tag: \"ShowCompletions\"\n  readonly shellType: BuiltInOptions.ShellType\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface ShowWizard {\n  readonly _tag: \"ShowWizard\"\n  readonly command: Command<unknown>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface ShowVersion {\n  readonly _tag: \"ShowVersion\"\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace BuiltInOptions {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ShellType = \"bash\" | \"fish\" | \"zsh\"\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport const builtInOptions: <A>(\n  command: Command<A>,\n  usage: Usage,\n  helpDoc: HelpDoc\n) => Options<Option<BuiltInOptions>> = InternalBuiltInOptions.builtInOptions\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isShowCompletions: (self: BuiltInOptions) => self is ShowCompletions =\n  InternalBuiltInOptions.isShowCompletions\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isShowHelp: (self: BuiltInOptions) => self is ShowHelp = InternalBuiltInOptions.isShowHelp\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isShowWizard: (self: BuiltInOptions) => self is ShowWizard = InternalBuiltInOptions.isShowWizard\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isShowVersion: (self: BuiltInOptions) => self is ShowVersion = InternalBuiltInOptions.isShowVersion\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const showCompletions: (shellType: BuiltInOptions.ShellType) => BuiltInOptions =\n  InternalBuiltInOptions.showCompletions\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const showHelp: (usage: Usage, helpDoc: HelpDoc) => BuiltInOptions = InternalBuiltInOptions.showHelp\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const showWizard: (command: Command<unknown>) => BuiltInOptions = InternalBuiltInOptions.showWizard\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const showVersion: BuiltInOptions = InternalBuiltInOptions.showVersion\n"
  },
  {
    "path": "packages/cli/src/CliApp.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { FileSystem } from \"@effect/platform/FileSystem\"\nimport type { Path } from \"@effect/platform/Path\"\nimport type { Terminal } from \"@effect/platform/Terminal\"\nimport type { Effect } from \"effect/Effect\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport type { Command } from \"./CommandDescriptor.js\"\nimport type { HelpDoc } from \"./HelpDoc.js\"\nimport type { Span } from \"./HelpDoc/Span.js\"\nimport * as InternalCliApp from \"./internal/cliApp.js\"\nimport type { ValidationError } from \"./ValidationError.js\"\n\n/**\n * A `CliApp<A>` is a complete description of a command-line application.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface CliApp<A> extends Pipeable {\n  readonly name: string\n  readonly version: string\n  readonly executable: string\n  readonly command: Command<A>\n  readonly summary: Span\n  readonly footer: HelpDoc\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace CliApp {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Environment = FileSystem | Path | Terminal\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface ConstructorArgs<A> {\n    readonly name: string\n    readonly version: string\n    readonly command: Command<A>\n    readonly executable?: string | undefined\n    readonly summary?: Span | undefined\n    readonly footer?: HelpDoc | undefined\n  }\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: <A>(config: CliApp.ConstructorArgs<A>) => CliApp<A> = InternalCliApp.make\n\n/**\n * @since 1.0.0\n * @category execution\n */\nexport const run: {\n  <R, E, A>(\n    args: ReadonlyArray<string>,\n    execute: (a: A) => Effect<void, E, R>\n  ): (self: CliApp<A>) => Effect<void | E, CliApp.Environment | R, ValidationError>\n  <R, E, A>(\n    self: CliApp<A>,\n    args: ReadonlyArray<string>,\n    execute: (a: A) => Effect<void, E, R>\n  ): Effect<void | E, CliApp.Environment | R, ValidationError>\n} = InternalCliApp.run\n"
  },
  {
    "path": "packages/cli/src/CliConfig.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Context from \"effect/Context\"\nimport type * as Layer from \"effect/Layer\"\nimport * as InternalCliConfig from \"./internal/cliConfig.js\"\n\n/**\n * Represents how arguments from the command-line are to be parsed.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface CliConfig {\n  /**\n   * Whether or not the argument parser should be case sensitive.\n   *\n   * Defaults to `false`.\n   */\n  readonly isCaseSensitive: boolean\n  /**\n   * Levenstein distance threshold for when to show auto correct suggestions.\n   *\n   * Defaults to `2`.\n   */\n  readonly autoCorrectLimit: number\n  /**\n   * Whether or not to perform a final check of the command-line arguments for\n   * a built-in option, even if the provided command is not valid.\n   *\n   * Defaults to `false`.\n   */\n  readonly finalCheckBuiltIn: boolean\n  /**\n   * Whether or not to display all the names of an option in the usage of a\n   * particular command.\n   *\n   * Defaults to `true`.\n   */\n  readonly showAllNames: boolean\n  /**\n   * Whether or not to display built-in options in the help documentation\n   * generated for a `Command`.\n   *\n   * Defaults to `true`.\n   */\n  readonly showBuiltIns: boolean\n  /**\n   * Whether or not to display the type of an option in the usage of a\n   * particular command.\n   *\n   * Defaults to `true`.\n   */\n  readonly showTypes: boolean\n}\n\n/**\n * @since 1.0.0\n * @category context\n */\nexport const CliConfig: Context.Tag<CliConfig, CliConfig> = InternalCliConfig.Tag\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const defaultConfig: CliConfig = InternalCliConfig.defaultConfig\n\n/**\n * @since 1.0.0\n * @category context\n */\nexport const defaultLayer: Layer.Layer<CliConfig> = InternalCliConfig.defaultLayer\n\n/**\n * @since 1.0.0\n * @category context\n */\nexport const layer: (config?: Partial<CliConfig>) => Layer.Layer<CliConfig> = InternalCliConfig.layer\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: (params: Partial<CliConfig>) => CliConfig = InternalCliConfig.make\n\n/**\n * @since 1.0.0\n * @category utilities\n */\nexport const normalizeCase: {\n  (text: string): (self: CliConfig) => string\n  (self: CliConfig, text: string): string\n} = InternalCliConfig.normalizeCase\n"
  },
  {
    "path": "packages/cli/src/Command.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { FileSystem } from \"@effect/platform/FileSystem\"\nimport type { Path } from \"@effect/platform/Path\"\nimport type { QuitException, Terminal } from \"@effect/platform/Terminal\"\nimport type { Tag } from \"effect/Context\"\nimport type { Effect } from \"effect/Effect\"\nimport type { HashMap } from \"effect/HashMap\"\nimport type { HashSet } from \"effect/HashSet\"\nimport type { Layer } from \"effect/Layer\"\nimport type { Option } from \"effect/Option\"\nimport { type Pipeable } from \"effect/Pipeable\"\nimport type * as Types from \"effect/Types\"\nimport type { Args } from \"./Args.js\"\nimport type { CliApp } from \"./CliApp.js\"\nimport type { CliConfig } from \"./CliConfig.js\"\nimport type * as Descriptor from \"./CommandDescriptor.js\"\nimport type { HelpDoc } from \"./HelpDoc.js\"\nimport * as Internal from \"./internal/command.js\"\nimport type { Options } from \"./Options.js\"\nimport type { Prompt } from \"./Prompt.js\"\nimport type { Usage } from \"./Usage.js\"\nimport type { ValidationError } from \"./ValidationError.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Command<Name extends string, R, E, A> extends Pipeable, Effect<A, never, Command.Context<Name>> {\n  readonly [TypeId]: TypeId\n  readonly descriptor: Descriptor.Command<A>\n  readonly handler: (_: A) => Effect<void, E, R>\n  readonly tag: Tag<Command.Context<Name>, A>\n  readonly transform: Command.Transform<R, E, A>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace Command {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Context<Name extends string> {\n    readonly _: unique symbol\n    readonly name: Name\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Config {\n    readonly [key: string]:\n      | Args<any>\n      | Options<any>\n      | ReadonlyArray<Args<any> | Options<any> | Config>\n      | Config\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ParseConfig<A extends Config> = Types.Simplify<\n    { readonly [Key in keyof A]: ParseConfigValue<A[Key]> }\n  >\n\n  type ParseConfigValue<A> = A extends ReadonlyArray<infer _> ?\n    { readonly [Key in keyof A]: ParseConfigValue<A[Key]> } :\n    A extends Args<infer Value> ? Value\n    : A extends Options<infer Value> ? Value\n    : A extends Config ? ParseConfig<A>\n    : never\n\n  interface ParsedConfigTree {\n    [key: string]: ParsedConfigNode\n  }\n\n  type ParsedConfigNode = {\n    readonly _tag: \"Args\"\n    readonly index: number\n  } | {\n    readonly _tag: \"Options\"\n    readonly index: number\n  } | {\n    readonly _tag: \"Array\"\n    readonly children: ReadonlyArray<ParsedConfigNode>\n  } | {\n    readonly _tag: \"ParsedConfig\"\n    readonly tree: ParsedConfigTree\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface ParsedConfig {\n    readonly args: ReadonlyArray<Args<any>>\n    readonly options: ReadonlyArray<Options<any>>\n    readonly tree: ParsedConfigTree\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Transform<R, E, A> = (effect: Effect<void, any, any>, config: A) => Effect<void, E, R>\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fromDescriptor: {\n  (): <A extends { readonly name: string }>(\n    command: Descriptor.Command<A>\n  ) => Command<A[\"name\"], never, never, A>\n\n  <A extends { readonly name: string }, R, E>(\n    handler: (_: A) => Effect<void, E, R>\n  ): (command: Descriptor.Command<A>) => Command<A[\"name\"], R, E, A>\n\n  <A extends { readonly name: string }>(\n    descriptor: Descriptor.Command<A>\n  ): Command<A[\"name\"], never, never, A>\n\n  <A extends { readonly name: string }, R, E>(\n    descriptor: Descriptor.Command<A>,\n    handler: (_: A) => Effect<void, E, R>\n  ): Command<A[\"name\"], R, E, A>\n} = Internal.fromDescriptor\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const getHelp: <Name extends string, R, E, A>(\n  self: Command<Name, R, E, A>,\n  config: CliConfig\n) => HelpDoc = Internal.getHelp\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const getNames: <Name extends string, R, E, A>(\n  self: Command<Name, R, E, A>\n) => HashSet<string> = Internal.getNames\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const getBashCompletions: <Name extends string, R, E, A>(\n  self: Command<Name, R, E, A>,\n  programName: string\n) => Effect<Array<string>> = Internal.getBashCompletions\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const getFishCompletions: <Name extends string, R, E, A>(\n  self: Command<Name, R, E, A>,\n  programName: string\n) => Effect<Array<string>> = Internal.getFishCompletions\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const getZshCompletions: <Name extends string, R, E, A>(\n  self: Command<Name, R, E, A>,\n  programName: string\n) => Effect<Array<string>> = Internal.getZshCompletions\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const getSubcommands: <Name extends string, R, E, A>(\n  self: Command<Name, R, E, A>\n) => HashMap<string, Descriptor.Command<unknown>> = Internal.getSubcommands\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const getUsage: <Name extends string, R, E, A>(self: Command<Name, R, E, A>) => Usage = Internal.getUsage\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: {\n  <Name extends string>(name: Name): Command<\n    Name,\n    never,\n    never,\n    {}\n  >\n\n  <Name extends string, const Config extends Command.Config>(\n    name: Name,\n    config: Config\n  ): Command<\n    Name,\n    never,\n    never,\n    Types.Simplify<Command.ParseConfig<Config>>\n  >\n\n  <Name extends string, const Config extends Command.Config, R, E>(\n    name: Name,\n    config: Config,\n    handler: (_: Types.Simplify<Command.ParseConfig<Config>>) => Effect<void, E, R>\n  ): Command<\n    Name,\n    R,\n    E,\n    Types.Simplify<Command.ParseConfig<Config>>\n  >\n} = Internal.make\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const prompt: <Name extends string, A, R, E>(\n  name: Name,\n  prompt: Prompt<A>,\n  handler: (_: A) => Effect<void, E, R>\n) => Command<string, R, E, A> = Internal.prompt\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const provide: {\n  <A, LR, LE, LA>(\n    layer: Layer<LA, LE, LR> | ((_: A) => Layer<LA, LE, LR>)\n  ): <Name extends string, R, E>(\n    self: Command<Name, R, E, A>\n  ) => Command<Name, LR | Exclude<R, LA>, LE | E, A>\n  <Name extends string, R, E, A, LR, LE, LA>(\n    self: Command<Name, R, E, A>,\n    layer: Layer<LA, LE, LR> | ((_: A) => Layer<LA, LE, LR>)\n  ): Command<Name, LR | Exclude<R, LA>, E | LE, A>\n} = Internal.provide\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const provideEffect: {\n  <I, S, A, R2, E2>(\n    tag: Tag<I, S>,\n    effect: Effect<S, E2, R2> | ((_: A) => Effect<S, E2, R2>)\n  ): <Name extends string, R, E>(\n    self: Command<Name, R, E, A>\n  ) => Command<Name, R2 | Exclude<R, I>, E2 | E, A>\n  <Name extends string, R, E, A, I, S, R2, E2>(\n    self: Command<Name, R, E, A>,\n    tag: Tag<I, S>,\n    effect: Effect<S, E2, R2> | ((_: A) => Effect<S, E2, R2>)\n  ): Command<Name, R2 | Exclude<R, I>, E | E2, A>\n} = Internal.provideEffect\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const provideEffectDiscard: {\n  <A, R2, E2, _>(\n    effect: Effect<_, E2, R2> | ((_: A) => Effect<_, E2, R2>)\n  ): <Name extends string, R, E>(self: Command<Name, R, E, A>) => Command<Name, R2 | R, E2 | E, A>\n  <Name extends string, R, E, A, R2, E2, _>(\n    self: Command<Name, R, E, A>,\n    effect: Effect<_, E2, R2> | ((_: A) => Effect<_, E2, R2>)\n  ): Command<Name, R | R2, E | E2, A>\n} = Internal.provideEffectDiscard\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const provideSync: {\n  <I, S, A>(\n    tag: Tag<I, S>,\n    service: S | ((_: A) => S)\n  ): <Name extends string, R, E>(self: Command<Name, R, E, A>) => Command<Name, Exclude<R, I>, E, A>\n  <Name extends string, R, E, A, I, S>(\n    self: Command<Name, R, E, A>,\n    tag: Tag<I, S>,\n    service: S | ((_: A) => S)\n  ): Command<Name, Exclude<R, I>, E, A>\n} = Internal.provideSync\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const transformHandler: {\n  <R, E, A, R2, E2>(\n    f: (effect: Effect<void, E, R>, config: A) => Effect<void, E2, R2>\n  ): <Name extends string>(self: Command<Name, R, E, A>) => Command<Name, R | R2, E | E2, A>\n  <Name extends string, R, E, A, R2, E2>(\n    self: Command<Name, R, E, A>,\n    f: (effect: Effect<void, E, R>, config: A) => Effect<void, E2, R2>\n  ): Command<Name, R | R2, E | E2, A>\n} = Internal.transformHandler\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withDescription: {\n  (\n    help: string | HelpDoc\n  ): <Name extends string, R, E, A>(self: Command<Name, R, E, A>) => Command<Name, R, E, A>\n  <Name extends string, R, E, A>(\n    self: Command<Name, R, E, A>,\n    help: string | HelpDoc\n  ): Command<Name, R, E, A>\n} = Internal.withDescription\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withHandler: {\n  <A, R, E>(\n    handler: (_: A) => Effect<void, E, R>\n  ): <Name extends string, XR, XE>(self: Command<Name, XR, XE, A>) => Command<Name, R, E, A>\n  <Name extends string, XR, XE, A, R, E>(\n    self: Command<Name, XR, XE, A>,\n    handler: (_: A) => Effect<void, E, R>\n  ): Command<Name, R, E, A>\n} = Internal.withHandler\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withSubcommands: {\n  <\n    Subcommand extends readonly [Command<any, any, any, any>, ...Array<Command<any, any, any, any>>]\n  >(\n    subcommands: Subcommand\n  ): <Name extends string, R, E, A>(\n    self: Command<Name, R, E, A>\n  ) => Command<\n    Name,\n    | R\n    | Exclude<Effect.Context<ReturnType<Subcommand[number][\"handler\"]>>, Command.Context<Name>>,\n    E | Effect.Error<ReturnType<Subcommand[number][\"handler\"]>>,\n    Descriptor.Command.ComputeParsedType<\n      & A\n      & Readonly<\n        { subcommand: Option<Descriptor.Command.GetParsedType<Subcommand[number][\"descriptor\"]>> }\n      >\n    >\n  >\n  <\n    Name extends string,\n    R,\n    E,\n    A,\n    Subcommand extends readonly [Command<any, any, any, any>, ...Array<Command<any, any, any, any>>]\n  >(\n    self: Command<Name, R, E, A>,\n    subcommands: Subcommand\n  ): Command<\n    Name,\n    | R\n    | Exclude<Effect.Context<ReturnType<Subcommand[number][\"handler\"]>>, Command.Context<Name>>,\n    E | Effect.Error<ReturnType<Subcommand[number][\"handler\"]>>,\n    Descriptor.Command.ComputeParsedType<\n      & A\n      & Readonly<\n        { subcommand: Option<Descriptor.Command.GetParsedType<Subcommand[number][\"descriptor\"]>> }\n      >\n    >\n  >\n} = Internal.withSubcommands\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const wizard: {\n  (\n    prefix: ReadonlyArray<string>,\n    config: CliConfig\n  ): <Name extends string, R, E, A>(\n    self: Command<Name, R, E, A>\n  ) => Effect<\n    Array<string>,\n    QuitException | ValidationError,\n    FileSystem | Path | Terminal\n  >\n  <Name extends string, R, E, A>(\n    self: Command<Name, R, E, A>,\n    prefix: ReadonlyArray<string>,\n    config: CliConfig\n  ): Effect<\n    Array<string>,\n    QuitException | ValidationError,\n    FileSystem | Path | Terminal\n  >\n} = Internal.wizard\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const run: {\n  (\n    config: Omit<CliApp.ConstructorArgs<never>, \"command\">\n  ): <Name extends string, R, E, A>(\n    self: Command<Name, R, E, A>\n  ) => (args: ReadonlyArray<string>) => Effect<void, E | ValidationError, R | CliApp.Environment>\n  <Name extends string, R, E, A>(\n    self: Command<Name, R, E, A>,\n    config: Omit<CliApp.ConstructorArgs<never>, \"command\">\n  ): (args: ReadonlyArray<string>) => Effect<void, E | ValidationError, R | CliApp.Environment>\n} = Internal.run\n"
  },
  {
    "path": "packages/cli/src/CommandDescriptor.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { FileSystem } from \"@effect/platform/FileSystem\"\nimport type { Path } from \"@effect/platform/Path\"\nimport type { QuitException, Terminal } from \"@effect/platform/Terminal\"\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport type { Effect } from \"effect/Effect\"\nimport type { HashMap } from \"effect/HashMap\"\nimport type { HashSet } from \"effect/HashSet\"\nimport type { Option } from \"effect/Option\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport type { Args } from \"./Args.js\"\nimport type { CliConfig } from \"./CliConfig.js\"\nimport type { CommandDirective } from \"./CommandDirective.js\"\nimport type { HelpDoc } from \"./HelpDoc.js\"\nimport * as Internal from \"./internal/commandDescriptor.js\"\nimport type { Options } from \"./Options.js\"\nimport type { Prompt } from \"./Prompt.js\"\nimport type { Usage } from \"./Usage.js\"\nimport type { ValidationError } from \"./ValidationError.js\"\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport const TypeId: unique symbol = Internal.TypeId\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport type TypeId = typeof TypeId\n\n/**\n * A `Command` represents a command in a command-line application.\n *\n * Every command-line application will have at least one command: the\n * application itself. Other command-line applications may support multiple\n * commands.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface Command<A> extends Command.Variance<A>, Pipeable {}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Command {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Variance<A> {\n    readonly [TypeId]: {\n      readonly _A: (_: never) => A\n    }\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ParsedStandardCommand<Name extends string, OptionsType, ArgsType> = Command.ComputeParsedType<{\n    readonly name: Name\n    readonly options: OptionsType\n    readonly args: ArgsType\n  }>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ParsedUserInputCommand<Name extends string, ValueType> = Command.ComputeParsedType<{\n    readonly name: Name\n    readonly value: ValueType\n  }>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type GetParsedType<C> = C extends Command<infer P> ? P : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ComputeParsedType<A> = { [K in keyof A]: A[K] } extends infer X ? X : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Subcommands<\n    A extends NonEmptyReadonlyArray<readonly [id: unknown, command: Command<any>]>\n  > = {\n    [I in keyof A]: A[I] extends readonly [infer Id, Command<infer Value>] ? readonly [id: Id, value: Value]\n      : never\n  }[number]\n}\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getHelp: <A>(self: Command<A>, config: CliConfig) => HelpDoc = Internal.getHelp\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getBashCompletions: <A>(\n  self: Command<A>,\n  programName: string\n) => Effect<Array<string>> = Internal.getBashCompletions\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getFishCompletions: <A>(\n  self: Command<A>,\n  programName: string\n) => Effect<Array<string>> = Internal.getFishCompletions\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getZshCompletions: <A>(\n  self: Command<A>,\n  programName: string\n) => Effect<Array<string>> = Internal.getZshCompletions\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getNames: <A>(self: Command<A>) => HashSet<string> = Internal.getNames\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getSubcommands: <A>(self: Command<A>) => HashMap<string, Command<unknown>> = Internal.getSubcommands\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getUsage: <A>(self: Command<A>) => Usage = Internal.getUsage\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): (self: Command<A>) => Command<B>\n  <A, B>(self: Command<A>, f: (a: A) => B): Command<B>\n} = Internal.map\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const mapEffect: {\n  <A, B>(f: (a: A) => Effect<B, ValidationError, FileSystem | Path | Terminal>): (self: Command<A>) => Command<B>\n  <A, B>(self: Command<A>, f: (a: A) => Effect<B, ValidationError, FileSystem | Path | Terminal>): Command<B>\n} = Internal.mapEffect\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const parse: {\n  (\n    args: ReadonlyArray<string>,\n    config: CliConfig\n  ): <A>(\n    self: Command<A>\n  ) => Effect<CommandDirective<A>, ValidationError, FileSystem | Path | Terminal>\n  <A>(\n    self: Command<A>,\n    args: ReadonlyArray<string>,\n    config: CliConfig\n  ): Effect<CommandDirective<A>, ValidationError, FileSystem | Path | Terminal>\n} = Internal.parse\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const prompt: <Name extends string, A>(\n  name: Name,\n  prompt: Prompt<A>\n) => Command<{ readonly name: Name; readonly value: A }> = Internal.prompt\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: <Name extends string, OptionsType = void, ArgsType = void>(\n  name: Name,\n  options?: Options<OptionsType>,\n  args?: Args<ArgsType>\n) => Command<{ readonly name: Name; readonly options: OptionsType; readonly args: ArgsType }> = Internal.make\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withDescription: {\n  (description: string | HelpDoc): <A>(self: Command<A>) => Command<A>\n  <A>(self: Command<A>, description: string | HelpDoc): Command<A>\n} = Internal.withDescription\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withSubcommands: {\n  <\n    const Subcommands extends readonly [\n      readonly [id: unknown, command: Command<any>],\n      ...Array<readonly [id: unknown, command: Command<any>]>\n    ]\n  >(\n    subcommands: [...Subcommands]\n  ): <A>(\n    self: Command<A>\n  ) => Command<\n    Command.ComputeParsedType<\n      A & Readonly<{ subcommand: Option<Command.Subcommands<Subcommands>> }>\n    >\n  >\n  <\n    A,\n    const Subcommands extends readonly [\n      readonly [id: unknown, command: Command<any>],\n      ...Array<readonly [id: unknown, command: Command<any>]>\n    ]\n  >(\n    self: Command<A>,\n    subcommands: [...Subcommands]\n  ): Command<\n    Command.ComputeParsedType<\n      A & Readonly<{ subcommand: Option<Command.Subcommands<Subcommands>> }>\n    >\n  >\n} = Internal.withSubcommands\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const wizard: {\n  (\n    prefix: ReadonlyArray<string>,\n    config: CliConfig\n  ): <A>(\n    self: Command<A>\n  ) => Effect<\n    Array<string>,\n    ValidationError | QuitException,\n    FileSystem | Path | Terminal\n  >\n  <A>(\n    self: Command<A>,\n    prefix: ReadonlyArray<string>,\n    config: CliConfig\n  ): Effect<\n    Array<string>,\n    ValidationError | QuitException,\n    FileSystem | Path | Terminal\n  >\n} = Internal.wizard\n"
  },
  {
    "path": "packages/cli/src/CommandDirective.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { BuiltInOptions } from \"./BuiltInOptions.js\"\nimport * as InternalCommandDirective from \"./internal/commandDirective.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type CommandDirective<A> = BuiltIn | UserDefined<A>\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface BuiltIn {\n  readonly _tag: \"BuiltIn\"\n  readonly option: BuiltInOptions\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface UserDefined<A> {\n  readonly _tag: \"UserDefined\"\n  readonly leftover: ReadonlyArray<string>\n  readonly value: A\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const builtIn: (option: BuiltInOptions) => CommandDirective<never> = InternalCommandDirective.builtIn\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isBuiltIn: <A>(self: CommandDirective<A>) => self is BuiltIn = InternalCommandDirective.isBuiltIn\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isUserDefined: <A>(self: CommandDirective<A>) => self is UserDefined<A> =\n  InternalCommandDirective.isUserDefined\n\n/**\n * @since 1.0.0\n * @category mapping\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): (self: CommandDirective<A>) => CommandDirective<B>\n  <A, B>(self: CommandDirective<A>, f: (a: A) => B): CommandDirective<B>\n} = InternalCommandDirective.map\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const userDefined: <A>(leftover: ReadonlyArray<string>, value: A) => CommandDirective<A> =\n  InternalCommandDirective.userDefined\n"
  },
  {
    "path": "packages/cli/src/ConfigFile.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { FileSystem } from \"@effect/platform/FileSystem\"\nimport type { Path } from \"@effect/platform/Path\"\nimport type { YieldableError } from \"effect/Cause\"\nimport type { ConfigProvider } from \"effect/ConfigProvider\"\nimport type { Effect } from \"effect/Effect\"\nimport type { Layer } from \"effect/Layer\"\nimport * as Internal from \"./internal/configFile.js\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type Kind = \"json\" | \"yaml\" | \"ini\" | \"toml\"\n\n/**\n * @since 2.0.0\n * @category errors\n */\nexport const ConfigErrorTypeId: unique symbol = Internal.ConfigErrorTypeId\n\n/**\n * @since 2.0.0\n * @category errors\n */\nexport type ConfigErrorTypeId = typeof ConfigErrorTypeId\n\n/**\n * @since 2.0.0\n * @category errors\n */\nexport interface ConfigFileError extends YieldableError {\n  readonly [ConfigErrorTypeId]: ConfigErrorTypeId\n  readonly _tag: \"ConfigFileError\"\n  readonly message: string\n}\n\n/**\n * @since 2.0.0\n * @category errors\n */\nexport const ConfigFileError: (message: string) => ConfigFileError = Internal.ConfigFileError\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const makeProvider: (\n  fileName: string,\n  options?:\n    | {\n      readonly formats?: ReadonlyArray<Kind>\n      readonly searchPaths?: ReadonlyArray<string>\n    }\n    | undefined\n) => Effect<ConfigProvider, ConfigFileError, Path | FileSystem> = Internal.makeProvider\n\n/**\n * @since 2.0.0\n * @category layers\n */\nexport const layer: (\n  fileName: string,\n  options?:\n    | {\n      readonly formats?: ReadonlyArray<Kind>\n      readonly searchPaths?: ReadonlyArray<string>\n    }\n    | undefined\n) => Layer<never, ConfigFileError, Path | FileSystem> = Internal.layer\n"
  },
  {
    "path": "packages/cli/src/HelpDoc/Span.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { Color } from \"@effect/printer-ansi/Color\"\nimport * as InternalSpan from \"../internal/helpDoc/span.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Span = Highlight | Sequence | Strong | Text | URI | Weak\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Highlight {\n  readonly _tag: \"Highlight\"\n  readonly value: Span\n  readonly color: Color\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Sequence {\n  readonly _tag: \"Sequence\"\n  readonly left: Span\n  readonly right: Span\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Strong {\n  readonly _tag: \"Strong\"\n  readonly value: Span\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Text {\n  readonly _tag: \"Text\"\n  readonly value: string\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface URI {\n  readonly _tag: \"URI\"\n  readonly value: string\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Weak {\n  readonly _tag: \"Weak\"\n  readonly value: Span\n}\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isSequence: (self: Span) => self is Sequence = InternalSpan.isSequence\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isStrong: (self: Span) => self is Strong = InternalSpan.isStrong\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isText: (self: Span) => self is Text = InternalSpan.isText\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isUri: (self: Span) => self is URI = InternalSpan.isUri\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isWeak: (self: Span) => self is Weak = InternalSpan.isWeak\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: Span = InternalSpan.empty\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const space: Span = InternalSpan.space\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const text: (value: string) => Span = InternalSpan.text\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const code: (value: string | Span) => Span = InternalSpan.code\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const error: (value: string | Span) => Span = InternalSpan.error\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const weak: (value: string | Span) => Span = InternalSpan.weak\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const strong: (value: string | Span) => Span = InternalSpan.strong\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const uri: (value: string) => Span = InternalSpan.uri\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const concat: {\n  (that: Span): (self: Span) => Span\n  (self: Span, that: Span): Span\n} = InternalSpan.concat\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const spans: (spans: Iterable<Span>) => Span = InternalSpan.spans\n"
  },
  {
    "path": "packages/cli/src/HelpDoc.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { AnsiDoc } from \"@effect/printer-ansi/AnsiDoc\"\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport type { Span } from \"./HelpDoc/Span.js\"\nimport * as InternalHelpDoc from \"./internal/helpDoc.js\"\n\n/**\n * A `HelpDoc` models the full documentation for a command-line application.\n *\n * `HelpDoc` is composed of optional header and footers, and in-between, a\n * list of HelpDoc-level content items.\n *\n * HelpDoc-level content items, in turn, can be headers, paragraphs, description\n * lists, and enumerations.\n *\n * A `HelpDoc` can be converted into plaintext, JSON, and HTML.\n *\n * @since 1.0.0\n * @category models\n */\nexport type HelpDoc = Empty | Header | Paragraph | DescriptionList | Enumeration | Sequence\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Empty {\n  readonly _tag: \"Empty\"\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Header {\n  readonly _tag: \"Header\"\n  readonly value: Span\n  readonly level: number\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Paragraph {\n  readonly _tag: \"Paragraph\"\n  readonly value: Span\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface DescriptionList {\n  readonly _tag: \"DescriptionList\"\n  readonly definitions: NonEmptyReadonlyArray<readonly [Span, HelpDoc]>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Enumeration {\n  readonly _tag: \"Enumeration\"\n  readonly elements: NonEmptyReadonlyArray<HelpDoc>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Sequence {\n  readonly _tag: \"Sequence\"\n  readonly left: HelpDoc\n  readonly right: HelpDoc\n}\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isEmpty: (helpDoc: HelpDoc) => helpDoc is Empty = InternalHelpDoc.isEmpty\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isHeader: (helpDoc: HelpDoc) => helpDoc is Header = InternalHelpDoc.isHeader\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isParagraph: (helpDoc: HelpDoc) => helpDoc is Paragraph = InternalHelpDoc.isParagraph\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isDescriptionList: (helpDoc: HelpDoc) => helpDoc is DescriptionList = InternalHelpDoc.isDescriptionList\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isEnumeration: (helpDoc: HelpDoc) => helpDoc is Enumeration = InternalHelpDoc.isEnumeration\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isSequence: (helpDoc: HelpDoc) => helpDoc is Sequence = InternalHelpDoc.isSequence\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: HelpDoc = InternalHelpDoc.empty\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const blocks: (helpDocs: Iterable<HelpDoc>) => HelpDoc = InternalHelpDoc.blocks\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const h1: (value: string | Span) => HelpDoc = InternalHelpDoc.h1\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const h2: (value: string | Span) => HelpDoc = InternalHelpDoc.h2\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const h3: (value: string | Span) => HelpDoc = InternalHelpDoc.h3\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const p: (value: string | Span) => HelpDoc = InternalHelpDoc.p\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const descriptionList: (\n  definitions: NonEmptyReadonlyArray<[Span, HelpDoc]>\n) => HelpDoc = InternalHelpDoc.descriptionList\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const enumeration: (elements: NonEmptyReadonlyArray<HelpDoc>) => HelpDoc = InternalHelpDoc.enumeration\n\n/**\n * @since 1.0.0\n * @category getters\n */\nexport const getSpan: (self: HelpDoc) => Span = InternalHelpDoc.getSpan\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const sequence: {\n  (that: HelpDoc): (self: HelpDoc) => HelpDoc\n  (self: HelpDoc, that: HelpDoc): HelpDoc\n} = InternalHelpDoc.sequence\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const orElse: {\n  (that: HelpDoc): (self: HelpDoc) => HelpDoc\n  (self: HelpDoc, that: HelpDoc): HelpDoc\n} = InternalHelpDoc.orElse\n\n/**\n * @since 1.0.0\n * @category mapping\n */\nexport const mapDescriptionList: {\n  (f: (span: Span, helpDoc: HelpDoc) => [Span, HelpDoc]): (self: HelpDoc) => HelpDoc\n  (self: HelpDoc, f: (span: Span, helpDoc: HelpDoc) => [Span, HelpDoc]): HelpDoc\n} = InternalHelpDoc.mapDescriptionList\n\n/**\n * @since 1.0.0\n * @category rendering\n */\nexport const toAnsiDoc: (self: HelpDoc) => AnsiDoc = InternalHelpDoc.toAnsiDoc\n\n/**\n * @since 1.0.0\n * @category rendering\n */\nexport const toAnsiText: (self: HelpDoc) => string = InternalHelpDoc.toAnsiText\n"
  },
  {
    "path": "packages/cli/src/Options.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { FileSystem } from \"@effect/platform/FileSystem\"\nimport type { Path } from \"@effect/platform/Path\"\nimport type { QuitException, Terminal } from \"@effect/platform/Terminal\"\nimport type { NonEmptyArray } from \"effect/Array\"\nimport type { Config } from \"effect/Config\"\nimport type { Effect } from \"effect/Effect\"\nimport type { Either } from \"effect/Either\"\nimport type { HashMap } from \"effect/HashMap\"\nimport type { Option } from \"effect/Option\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport type { Redacted } from \"effect/Redacted\"\nimport type { Schema } from \"effect/Schema\"\nimport type { Secret } from \"effect/Secret\"\nimport type { CliConfig } from \"./CliConfig.js\"\nimport type { HelpDoc } from \"./HelpDoc.js\"\nimport * as InternalOptions from \"./internal/options.js\"\nimport type { Primitive } from \"./Primitive.js\"\nimport type { Prompt } from \"./Prompt.js\"\nimport type { Usage } from \"./Usage.js\"\nimport type { ValidationError } from \"./ValidationError.js\"\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport const OptionsTypeId: unique symbol = InternalOptions.OptionsTypeId\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport type OptionsTypeId = typeof OptionsTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Options<A> extends Options.Variance<A>, Pipeable {}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Options {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Variance<A> {\n    readonly [OptionsTypeId]: {\n      _A: (_: never) => A\n    }\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface BooleanOptionsConfig {\n    readonly ifPresent?: boolean\n    readonly negationNames?: ReadonlyArray<string>\n    readonly aliases?: ReadonlyArray<string>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface PathOptionsConfig {\n    readonly exists?: Primitive.PathExists\n  }\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace All {\n  /**\n   * @since 1.0.0\n   */\n  export type OptionsAny = Options<any>\n\n  /**\n   * @since 1.0.0\n   */\n  export type ReturnIterable<T extends Iterable<OptionsAny>> = [T] extends [Iterable<Options.Variance<infer A>>] ?\n    Options<Array<A>>\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type ReturnTuple<T extends ReadonlyArray<unknown>> = Options<\n    T[number] extends never ? []\n      : {\n        -readonly [K in keyof T]: [T[K]] extends [Options.Variance<infer _A>] ? _A : never\n      }\n  > extends infer X ? X : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type ReturnObject<T> = [T] extends [{ [K: string]: OptionsAny }] ? Options<\n      {\n        -readonly [K in keyof T]: [T[K]] extends [Options.Variance<infer _A>] ? _A : never\n      }\n    >\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type Return<\n    Arg extends Iterable<OptionsAny> | Record<string, OptionsAny>\n  > = [Arg] extends [ReadonlyArray<OptionsAny>] ? ReturnTuple<Arg>\n    : [Arg] extends [Iterable<OptionsAny>] ? ReturnIterable<Arg>\n    : [Arg] extends [Record<string, OptionsAny>] ? ReturnObject<Arg>\n    : never\n}\n\n// =============================================================================\n// Refinements\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isOptions: (u: unknown) => u is Options<unknown> = InternalOptions.isOptions\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const all: <\n  const Arg extends Iterable<Options<any>> | Record<string, Options<any>>\n>(arg: Arg) => All.Return<Arg> = InternalOptions.all\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const boolean: (name: string, options?: Options.BooleanOptionsConfig) => Options<boolean> =\n  InternalOptions.boolean\n\n/**\n * Constructs command-line `Options` that represent a choice between several\n * inputs. The input will be mapped to it's associated value during parsing.\n *\n * **Example**\n *\n * ```ts\n * import * as Options from \"@effect/cli/Options\"\n *\n * export const animal: Options.Options<\"dog\" | \"cat\"> = Options.choice(\n *   \"animal\",\n *   [\"dog\", \"cat\"]\n * )\n * ```\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const choice: <A extends string, C extends ReadonlyArray<A>>(\n  name: string,\n  choices: C\n) => Options<C[number]> = InternalOptions.choice\n\n/**\n * Constructs command-line `Options` that represent a choice between several\n * inputs. The input will be mapped to it's associated value during parsing.\n *\n * **Example**\n *\n * ```ts\n * import * as Options from \"@effect/cli/Options\"\n * import * as Data from \"effect/Data\"\n *\n * export type Animal = Dog | Cat\n *\n * export interface Dog {\n *   readonly _tag: \"Dog\"\n * }\n *\n * export const Dog = Data.tagged<Dog>(\"Dog\")\n *\n * export interface Cat {\n *   readonly _tag: \"Cat\"\n * }\n *\n * export const Cat = Data.tagged<Cat>(\"Cat\")\n *\n * export const animal: Options.Options<Animal> = Options.choiceWithValue(\"animal\", [\n *   [\"dog\", Dog()],\n *   [\"cat\", Cat()],\n * ])\n * ```\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const choiceWithValue: <C extends ReadonlyArray<[string, any]>>(\n  name: string,\n  choices: C\n) => Options<C[number][1]> = InternalOptions.choiceWithValue\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const date: (name: string) => Options<globalThis.Date> = InternalOptions.date\n\n/**\n * Creates a parameter expecting path to a directory.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const directory: (name: string, config?: Options.PathOptionsConfig) => Options<string> =\n  InternalOptions.directory\n\n/**\n * Creates a parameter expecting path to a file.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const file: (name: string, config?: Options.PathOptionsConfig) => Options<string> = InternalOptions.file\n\n/**\n * Creates a parameter expecting path to a file and reads its contents.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fileContent: (name: string) => Options<readonly [path: string, content: Uint8Array]> =\n  InternalOptions.fileContent\n\n/**\n * Creates a parameter expecting path to a file and parse its contents.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fileParse: (name: string, format?: \"json\" | \"yaml\" | \"ini\" | \"toml\" | undefined) => Options<unknown> =\n  InternalOptions.fileParse\n\n/**\n * Creates a parameter expecting path to a file, parse its contents and validate\n * it with a Schema.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fileSchema: <I, A>(\n  name: string,\n  schema: Schema<A, I, FileSystem | Path | Terminal>,\n  format?: \"json\" | \"yaml\" | \"ini\" | \"toml\" | undefined\n) => Options<A> = InternalOptions.fileSchema\n\n/**\n * Creates a parameter expecting path to a file and reads its contents.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fileText: (name: string) => Options<readonly [path: string, content: string]> = InternalOptions.fileText\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const float: (name: string) => Options<number> = InternalOptions.float\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getHelp: <A>(self: Options<A>) => HelpDoc = InternalOptions.getHelp\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getIdentifier: <A>(self: Options<A>) => Option<string> = InternalOptions.getIdentifier\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getUsage: <A>(self: Options<A>) => Usage = InternalOptions.getUsage\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const integer: (name: string) => Options<number> = InternalOptions.integer\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const keyValueMap: (option: string | Options<string>) => Options<HashMap<string, string>> =\n  InternalOptions.keyValueMap\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const none: Options<void> = InternalOptions.none\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const redacted: (name: string) => Options<Redacted> = InternalOptions.redacted\n\n/**\n * @since 1.0.0\n * @category constructors\n * @deprecated\n */\nexport const secret: (name: string) => Options<Secret> = InternalOptions.secret\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const text: (name: string) => Options<string> = InternalOptions.text\n\n// =============================================================================\n// Combinators\n// =============================================================================\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const atMost: {\n  (times: number): <A>(self: Options<A>) => Options<Array<A>>\n  <A>(self: Options<A>, times: number): Options<Array<A>>\n} = InternalOptions.atMost\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const atLeast: {\n  (times: 0): <A>(self: Options<A>) => Options<Array<A>>\n  (times: number): <A>(self: Options<A>) => Options<NonEmptyArray<A>>\n  <A>(self: Options<A>, times: 0): Options<Array<A>>\n  <A>(self: Options<A>, times: number): Options<NonEmptyArray<A>>\n} = InternalOptions.atLeast\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const between: {\n  (min: 0, max: number): <A>(self: Options<A>) => Options<Array<A>>\n  (min: number, max: number): <A>(self: Options<A>) => Options<NonEmptyArray<A>>\n  <A>(self: Options<A>, min: 0, max: number): Options<Array<A>>\n  <A>(self: Options<A>, min: number, max: number): Options<NonEmptyArray<A>>\n} = InternalOptions.between\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const filterMap: {\n  <A, B>(f: (a: A) => Option<B>, message: string): (self: Options<A>) => Options<B>\n  <A, B>(self: Options<A>, f: (a: A) => Option<B>, message: string): Options<B>\n} = InternalOptions.filterMap\n\n/**\n * Returns `true` if the specified `Options` is a boolean flag, `false`\n * otherwise.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const isBool: <A>(self: Options<A>) => boolean = InternalOptions.isBool\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): (self: Options<A>) => Options<B>\n  <A, B>(self: Options<A>, f: (a: A) => B): Options<B>\n} = InternalOptions.map\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const mapEffect: {\n  <A, B>(f: (a: A) => Effect<B, ValidationError, FileSystem | Path | Terminal>): (self: Options<A>) => Options<B>\n  <A, B>(self: Options<A>, f: (a: A) => Effect<B, ValidationError, FileSystem | Path | Terminal>): Options<B>\n} = InternalOptions.mapEffect\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const mapTryCatch: {\n  <A, B>(f: (a: A) => B, onError: (e: unknown) => HelpDoc): (self: Options<A>) => Options<B>\n  <A, B>(self: Options<A>, f: (a: A) => B, onError: (e: unknown) => HelpDoc): Options<B>\n} = InternalOptions.mapTryCatch\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const optional: <A>(self: Options<A>) => Options<Option<A>> = InternalOptions.optional\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const orElse: {\n  <A>(that: Options<A>): <B>(self: Options<B>) => Options<A | B>\n  <A, B>(self: Options<A>, that: Options<B>): Options<A | B>\n} = InternalOptions.orElse\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const orElseEither: {\n  <A>(that: Options<A>): <B>(self: Options<B>) => Options<Either<A, B>>\n  <A, B>(self: Options<A>, that: Options<B>): Options<Either<A, B>>\n} = InternalOptions.orElseEither\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const parse: {\n  (\n    args: HashMap<string, ReadonlyArray<string>>,\n    config: CliConfig\n  ): <A>(self: Options<A>) => Effect<A, ValidationError, FileSystem>\n  <A>(\n    self: Options<A>,\n    args: HashMap<string, ReadonlyArray<string>>,\n    config: CliConfig\n  ): Effect<A, ValidationError, FileSystem>\n} = InternalOptions.parse\n\n/**\n * Indicates that the specified command-line option can be repeated `0` or more\n * times.\n *\n * **NOTE**: if the command-line option is not provided, and empty array will be\n * returned as the value for said option.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const repeated: <A>(self: Options<A>) => Options<Array<A>> = InternalOptions.repeated\n\n/**\n * Processes the provided command-line arguments, searching for the specified\n * `Options`.\n *\n * Returns an `Option<ValidationError>`, any leftover arguments, and the\n * constructed value of type `A`. The possible error inside\n * `Option<ValidationError>` would only be triggered if there is an error when\n * parsing the command-line arguments. This is because `ValidationError`s are\n * also used internally to control the end of the command-line arguments (i.e.\n * the command-line symbol `--`) corresponding to options.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const processCommandLine: {\n  (\n    args: ReadonlyArray<string>,\n    config: CliConfig\n  ): <A>(\n    self: Options<A>\n  ) => Effect<\n    [Option<ValidationError>, Array<string>, A],\n    ValidationError,\n    FileSystem | Path | Terminal\n  >\n  <A>(\n    self: Options<A>,\n    args: ReadonlyArray<string>,\n    config: CliConfig\n  ): Effect<\n    [Option<ValidationError>, Array<string>, A],\n    ValidationError,\n    FileSystem | Path | Terminal\n  >\n} = InternalOptions.processCommandLine\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withAlias: {\n  (alias: string): <A>(self: Options<A>) => Options<A>\n  <A>(self: Options<A>, alias: string): Options<A>\n} = InternalOptions.withAlias\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withDefault: {\n  <const B>(fallback: B): <A>(self: Options<A>) => Options<B | A>\n  <A, const B>(self: Options<A>, fallback: B): Options<A | B>\n} = InternalOptions.withDefault\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withFallbackConfig: {\n  <B>(config: Config<B>): <A>(self: Options<A>) => Options<B | A>\n  <A, B>(self: Options<A>, config: Config<B>): Options<A | B>\n} = InternalOptions.withFallbackConfig\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withFallbackPrompt: {\n  <B>(prompt: Prompt<B>): <A>(self: Options<A>) => Options<B | A>\n  <A, B>(self: Options<A>, prompt: Prompt<B>): Options<A | B>\n} = InternalOptions.withFallbackPrompt\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withDescription: {\n  (description: string): <A>(self: Options<A>) => Options<A>\n  <A>(self: Options<A>, description: string): Options<A>\n} = InternalOptions.withDescription\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withPseudoName: {\n  (pseudoName: string): <A>(self: Options<A>) => Options<A>\n  <A>(self: Options<A>, pseudoName: string): Options<A>\n} = InternalOptions.withPseudoName\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withSchema: {\n  <A, I extends A, B>(schema: Schema<B, I, FileSystem | Path | Terminal>): (self: Options<A>) => Options<B>\n  <A, I extends A, B>(self: Options<A>, schema: Schema<B, I, FileSystem | Path | Terminal>): Options<B>\n} = InternalOptions.withSchema\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const wizard: {\n  (\n    config: CliConfig\n  ): <A>(\n    self: Options<A>\n  ) => Effect<\n    Array<string>,\n    QuitException | ValidationError,\n    FileSystem | Path | Terminal\n  >\n  <A>(\n    self: Options<A>,\n    config: CliConfig\n  ): Effect<\n    Array<string>,\n    QuitException | ValidationError,\n    FileSystem | Path | Terminal\n  >\n} = InternalOptions.wizard\n"
  },
  {
    "path": "packages/cli/src/Primitive.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { FileSystem } from \"@effect/platform/FileSystem\"\nimport type { Effect } from \"effect/Effect\"\nimport type { Option } from \"effect/Option\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport type { CliConfig } from \"./CliConfig.js\"\nimport type { HelpDoc } from \"./HelpDoc.js\"\nimport type { Span } from \"./HelpDoc/Span.js\"\nimport * as InternalPrimitive from \"./internal/primitive.js\"\nimport type { Prompt } from \"./Prompt.js\"\n\n/**\n * @since 1.0.0\n * @category symbol\n */\nexport const PrimitiveTypeId: unique symbol = InternalPrimitive.PrimitiveTypeId as PrimitiveTypeId\n\n/**\n * @since 1.0.0\n * @category symbol\n */\nexport type PrimitiveTypeId = typeof PrimitiveTypeId\n\n/**\n * A `Primitive` represents the primitive types supported by Effect CLI.\n *\n * Each primitive type has a way to parse and validate from a string.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface Primitive<A> extends Primitive.Variance<A> {}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Primitive {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Variance<A> extends Pipeable {\n    readonly [PrimitiveTypeId]: {\n      readonly _A: (_: never) => A\n    }\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type PathExists = \"yes\" | \"no\" | \"either\"\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type PathType = \"file\" | \"directory\" | \"either\"\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ValueType<P> = [P] extends [{\n    readonly [PrimitiveTypeId]: {\n      readonly _A: (_: never) => infer A\n    }\n  }] ? A\n    : never\n}\n\n/**\n * @since 1.0.0\n * @category Predicates\n */\nexport const isBool: <A>(self: Primitive<A>) => boolean = InternalPrimitive.isBool\n\n/**\n * Represents a boolean value.\n *\n * True values can be passed as one of: `[\"true\", \"1\", \"y\", \"yes\" or \"on\"]`.\n * False value can be passed as one of: `[\"false\", \"o\", \"n\", \"no\" or \"off\"]`.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const boolean: (defaultValue: Option<boolean>) => Primitive<boolean> = InternalPrimitive.boolean\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const choice: <A>(alternatives: ReadonlyArray<[string, A]>) => Primitive<A> = InternalPrimitive.choice\n\n/**\n * Represents a date in ISO-8601 format, such as `2007-12-03T10:15:30`.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const date: Primitive<globalThis.Date> = InternalPrimitive.date\n\n/**\n * Represents a floating point number.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const float: Primitive<number> = InternalPrimitive.float\n\n/**\n * Returns a text representation of the valid choices for a primitive type, if\n * any.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const getChoices: <A>(self: Primitive<A>) => Option<string> = InternalPrimitive.getChoices\n\n/**\n * Returns help documentation for a primitive type.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const getHelp: <A>(self: Primitive<A>) => Span = InternalPrimitive.getHelp\n\n/**\n * Returns a string representation of the primitive type.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const getTypeName: <A>(self: Primitive<A>) => string = InternalPrimitive.getTypeName\n\n/**\n * Represents an integer.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const integer: Primitive<number> = InternalPrimitive.integer\n\n/**\n * Represents a user-defined piece of text.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const text: Primitive<string> = InternalPrimitive.text\n\n/**\n * Validates that the specified value, if any, matches the specified primitive\n * type.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const validate: {\n  (\n    value: Option<string>,\n    config: CliConfig\n  ): <A>(self: Primitive<A>) => Effect<A, string, FileSystem>\n  <A>(\n    self: Primitive<A>,\n    value: Option<string>,\n    config: CliConfig\n  ): Effect<A, string, FileSystem>\n} = InternalPrimitive.validate\n\n/**\n * Runs a wizard that will prompt the user for input matching the specified\n * primitive type.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const wizard: {\n  (help: HelpDoc): <A>(self: Primitive<A>) => Prompt<A>\n  <A>(self: Primitive<A>, help: HelpDoc): Prompt<A>\n} = InternalPrimitive.wizard\n"
  },
  {
    "path": "packages/cli/src/Prompt.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { FileSystem } from \"@effect/platform/FileSystem\"\nimport type { Path } from \"@effect/platform/Path\"\nimport type { QuitException, Terminal, UserInput } from \"@effect/platform/Terminal\"\nimport type { TaggedEnum } from \"effect/Data\"\nimport type { Effect } from \"effect/Effect\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport type { Redacted } from \"effect/Redacted\"\nimport * as InternalPrompt from \"./internal/prompt.js\"\nimport * as InternalConfirmPrompt from \"./internal/prompt/confirm.js\"\nimport * as InternalDatePrompt from \"./internal/prompt/date.js\"\nimport * as InternalFilePrompt from \"./internal/prompt/file.js\"\nimport * as InternalListPrompt from \"./internal/prompt/list.js\"\nimport * as InternalMultiSelectPrompt from \"./internal/prompt/multi-select.js\"\nimport * as InternalNumberPrompt from \"./internal/prompt/number.js\"\nimport * as InternalSelectPrompt from \"./internal/prompt/select.js\"\nimport * as InternalTextPrompt from \"./internal/prompt/text.js\"\nimport * as InternalTogglePrompt from \"./internal/prompt/toggle.js\"\nimport type { Primitive } from \"./Primitive.js\"\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport const PromptTypeId: unique symbol = InternalPrompt.PromptTypeId\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport type PromptTypeId = typeof PromptTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Prompt<Output> extends Prompt.Variance<Output>, Pipeable, Effect<Output, QuitException, Terminal> {}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Prompt {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Variance<Output> {\n    readonly [PromptTypeId]: Prompt.VarianceStruct<Output>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface VarianceStruct<Output> {\n    readonly _Output: (_: never) => Output\n  }\n\n  /**\n   * Represents the services available to a custom `Prompt`.\n   *\n   * @since 1.0.0\n   * @category models\n   */\n  export type Environment = FileSystem | Path | Terminal\n\n  /**\n   * Represents the action that should be taken by a `Prompt` based upon the\n   * user input received during the current frame.\n   *\n   * @since 1.0.0\n   * @category models\n   */\n  export type Action<State, Output> = TaggedEnum<{\n    readonly Beep: {}\n    readonly NextFrame: { readonly state: State }\n    readonly Submit: { readonly value: Output }\n  }>\n\n  /**\n   * Represents the definition of an `Action`.\n   *\n   * Required to create a `Data.TaggedEnum` with generic type arguments.\n   *\n   * @since 1.0.0\n   * @category models\n   */\n  export interface ActionDefinition extends TaggedEnum.WithGenerics<2> {\n    readonly taggedEnum: Action<this[\"A\"], this[\"B\"]>\n  }\n\n  /**\n   * Represents the set of handlers used by a `Prompt` to:\n   *\n   *   - Render the current frame of the prompt\n   *   - Process user input and determine the next `Prompt.Action` to take\n   *   - Clear the terminal screen before the next frame\n   *\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Handlers<State, Output> {\n    /**\n     * A function that is called to render the current frame of the `Prompt`.\n     *\n     * @param state The current state of the prompt.\n     * @param action The `Prompt.Action` for the current frame.\n     * @returns An ANSI escape code sequence to display in the terminal screen.\n     */\n    readonly render: (\n      state: State,\n      action: Action<State, Output>\n    ) => Effect<string, never, Environment>\n    /**\n     * A function that is called to process user input and determine the next\n     * `Prompt.Action` that should be taken.\n     *\n     * @param input The input the user provided for the current frame.\n     * @param state The current state of the prompt.\n     * @returns The next `Prompt.Action` that should be taken.\n     */\n    readonly process: (\n      input: UserInput,\n      state: State\n    ) => Effect<Action<State, Output>, never, Environment>\n    /**\n     * A function that is called to clear the terminal screen before rendering\n     * the next frame of the `Prompt`.\n     *\n     * @param action The `Prompt.Action` for the current frame.\n     * @param columns The current number of columns available in the `Terminal`.\n     * @returns An ANSI escape code sequence used to clear the terminal screen.\n     */\n    readonly clear: (\n      state: State,\n      action: Action<State, Output>\n    ) => Effect<string, never, Environment>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface ConfirmOptions {\n    /**\n     * The message to display in the prompt.\n     */\n    readonly message: string\n    /**\n     * The intitial value of the confirm prompt (defaults to `false`).\n     */\n    readonly initial?: boolean\n    /**\n     * The label to display after a user has responded to the prompt.\n     */\n    readonly label?: {\n      /**\n       * The label used if the prompt is confirmed (defaults to `\"yes\"`).\n       */\n      readonly confirm: string\n      /**\n       * The label used if the prompt is not confirmed (defaults to `\"no\"`).\n       */\n      readonly deny: string\n    }\n    /**\n     * The placeholder to display when a user is responding to the prompt.\n     */\n    readonly placeholder?: {\n      /**\n       * The placeholder to use if the `initial` value of the prompt is `true`\n       * (defaults to `\"(Y/n)\"`).\n       */\n      readonly defaultConfirm?: string\n      /**\n       * The placeholder to use if the `initial` value of the prompt is `false`\n       * (defaults to `\"(y/N)\"`).\n       */\n      readonly defaultDeny?: string\n    }\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface DateOptions {\n    /**\n     * The message to display in the prompt.\n     */\n    readonly message: string\n    /**\n     * The initial date value to display in the prompt (defaults to the current\n     * date).\n     */\n    readonly initial?: globalThis.Date\n    /**\n     * The format mask of the date (defaults to `YYYY-MM-DD HH:mm:ss`).\n     */\n    readonly dateMask?: string\n    /**\n     * An effectful function that can be used to validate the value entered into\n     * the prompt before final submission.\n     */\n    readonly validate?: (value: globalThis.Date) => Effect<globalThis.Date, string>\n    /**\n     * Custom locales that can be used in place of the defaults.\n     */\n    readonly locales?: {\n      /**\n       * The full names of each month of the year.\n       */\n      readonly months: [\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string\n      ]\n      /**\n       * The short names of each month of the year.\n       */\n      readonly monthsShort: [\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string,\n        string\n      ]\n      /**\n       * The full names of each day of the week.\n       */\n      readonly weekdays: [string, string, string, string, string, string, string]\n      /**\n       * The short names of each day of the week.\n       */\n      readonly weekdaysShort: [string, string, string, string, string, string, string]\n    }\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface IntegerOptions {\n    /**\n     * The message to display in the prompt.\n     */\n    readonly message: string\n    /**\n     * The minimum value that can be entered by the user (defaults to `-Infinity`).\n     */\n    readonly min?: number\n    /**\n     * The maximum value that can be entered by the user (defaults to `Infinity`).\n     */\n    readonly max?: number\n    /**\n     * The value that will be used to increment the prompt value when using the\n     * up arrow key (defaults to `1`).\n     */\n    readonly incrementBy?: number\n    /**\n     * The value that will be used to decrement the prompt value when using the\n     * down arrow key (defaults to `1`).\n     */\n    readonly decrementBy?: number\n    /**\n     * An effectful function that can be used to validate the value entered into\n     * the prompt before final submission.\n     */\n    readonly validate?: (value: number) => Effect<number, string>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface FloatOptions extends IntegerOptions {\n    /**\n     * The precision to use for the floating point value (defaults to `2`).\n     */\n    readonly precision?: number\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface ListOptions extends TextOptions {\n    /**\n     * The delimiter that separates list entries.\n     */\n    readonly delimiter?: string\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface FileOptions {\n    /**\n     * The path type that will be selected.\n     *\n     * Defaults to `\"file\"`.\n     */\n    readonly type?: Primitive.PathType\n    /**\n     * The message to display in the prompt.\n     *\n     * Defaults to `\"Choose a file\"`.\n     */\n    readonly message?: string\n    /**\n     * Where the user will initially be prompted to select files from.\n     *\n     * Defaults to the current working directory.\n     */\n    readonly startingPath?: string\n    /**\n     * The number of choices to display at one time\n     *\n     * Defaults to `10`.\n     */\n    readonly maxPerPage?: number\n    /**\n     * A function which removes any file from the prompt display where the\n     * specified predicate returns `true`.\n     *\n     * Defaults to returning all files.\n     */\n    readonly filter?: (file: string) => boolean | Effect<boolean, never, Environment>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface SelectOptions<A> {\n    /**\n     * The message to display in the prompt.\n     */\n    readonly message: string\n    /**\n     * The choices to display to the user.\n     */\n    readonly choices: ReadonlyArray<SelectChoice<A>>\n    /**\n     * The number of choices to display at one time (defaults to `10`).\n     */\n    readonly maxPerPage?: number\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface MultiSelectOptions {\n    /**\n     * Text for the \"Select All\" option (defaults to \"Select All\").\n     */\n    readonly selectAll?: string\n    /**\n     * Text for the \"Select None\" option (defaults to \"Select None\").\n     */\n    readonly selectNone?: string\n    /**\n     * Text for the \"Inverse Selection\" option (defaults to \"Inverse Selection\").\n     */\n    readonly inverseSelection?: string\n    /**\n     * The minimum number of choices that must be selected.\n     */\n    readonly min?: number\n    /**\n     * The maximum number of choices that can be selected.\n     */\n    readonly max?: number\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface SelectChoice<A> {\n    /**\n     * The name of the select option that is displayed to the user.\n     */\n    readonly title: string\n    /**\n     * The underlying value of the select option.\n     */\n    readonly value: A\n    /**\n     * An optional description for the select option which will be displayed\n     * to the user.\n     */\n    readonly description?: string\n    /**\n     * Whether or not this select option is disabled.\n     */\n    readonly disabled?: boolean\n    /**\n     * Whether this option should be selected by default (only used by MultiSelect).\n     */\n    readonly selected?: boolean\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface TextOptions {\n    /**\n     * The message to display in the prompt.\n     */\n    readonly message: string\n    /**\n     * The default value of the text option.\n     */\n    readonly default?: string\n    /**\n     * An effectful function that can be used to validate the value entered into\n     * the prompt before final submission.\n     */\n    readonly validate?: (value: string) => Effect<string, string>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface ToggleOptions {\n    /**\n     * The message to display in the prompt.\n     */\n    readonly message: string\n    /**\n     * The intitial value of the toggle prompt (defaults to `false`).\n     */\n    readonly initial?: boolean\n    /**\n     * The text to display when the toggle is in the active state (defaults to\n     * `on`).\n     */\n    readonly active?: string\n    /**\n     * The text to display when the toggle is in the inactive state (defaults to\n     * `off`).\n     */\n    readonly inactive?: string\n  }\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace All {\n  /**\n   * @since 1.0.0\n   */\n  export type PromptAny = Prompt<any>\n\n  /**\n   * @since 1.0.0\n   */\n  export type ReturnIterable<T extends Iterable<PromptAny>> = [T] extends [Iterable<Prompt.Variance<infer A>>] ?\n    Prompt<Array<A>>\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type ReturnTuple<T extends ReadonlyArray<unknown>> = Prompt<\n    T[number] extends never ? []\n      : { -readonly [K in keyof T]: [T[K]] extends [Prompt.Variance<infer _A>] ? _A : never }\n  > extends infer X ? X : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type ReturnObject<T> = [T] extends [{ [K: string]: PromptAny }] ? Prompt<\n      {\n        -readonly [K in keyof T]: [T[K]] extends [Prompt.Variance<infer _A>] ? _A : never\n      }\n    >\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type Return<\n    Arg extends Iterable<PromptAny> | Record<string, PromptAny>\n  > = [Arg] extends [ReadonlyArray<PromptAny>] ? ReturnTuple<Arg>\n    : [Arg] extends [Iterable<PromptAny>] ? ReturnIterable<Arg>\n    : [Arg] extends [Record<string, PromptAny>] ? ReturnObject<Arg>\n    : never\n}\n\n/**\n * Runs all the provided prompts in sequence respecting the structure provided\n * in input.\n *\n * Supports either a tuple / iterable of prompts or a record / struct of prompts\n * as an argument.\n *\n * **Example**\n *\n * ```ts\n * import * as Prompt from \"@effect/cli/Prompt\"\n * import * as Effect from \"effect/Effect\"\n *\n * const username = Prompt.text({\n *   message: \"Enter your username: \"\n * })\n *\n * const password = Prompt.password({\n *   message: \"Enter your password: \",\n *   validate: (value) =>\n *     value.length === 0\n *       ? Effect.fail(\"Password cannot be empty\")\n *       : Effect.succeed(value)\n * })\n *\n * const allWithTuple = Prompt.all([username, password])\n *\n * const allWithRecord = Prompt.all({ username, password })\n * ```\n *\n * @since 1.0.0\n * @category collecting & elements\n */\nexport const all: <const Arg extends Iterable<Prompt<any>> | Record<string, Prompt<any>>>(arg: Arg) => All.Return<Arg> =\n  InternalPrompt.all\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const confirm: (options: Prompt.ConfirmOptions) => Prompt<boolean> = InternalConfirmPrompt.confirm\n\n/**\n * Creates a custom `Prompt` from the specified initial state and handlers.\n *\n * The initial state can either be a pure value or an `Effect`. This is\n * particularly useful when the initial state of the `Prompt` must be computed\n * by performing some effectful computation, such as reading data from the file\n * system.\n *\n * A `Prompt` is essentially a render loop where user input triggers a new frame\n * to be rendered to the `Terminal`. The `handlers` of a custom prompt are used\n * to control what is rendered to the `Terminal` each frame. During each frame,\n * the following occurs:\n *\n *   1. The `render` handler is called with this frame's prompt state and prompt\n *      action and returns an ANSI escape string to be rendered to the\n *      `Terminal`\n *   2. The `Terminal` obtains input from the user\n *   3. The `process` handler is called with the input obtained from the user\n *      and this frame's prompt state and returns the next prompt action that\n *      should be performed\n *   4. The `clear` handler is called with this frame's prompt state and prompt\n *      action and returns an ANSI escape string used to clear the screen of\n *      the `Terminal`\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const custom: <State, Output>(\n  initialState: State | Effect<State, never, Prompt.Environment>,\n  handlers: Prompt.Handlers<State, Output>\n) => Prompt<Output> = InternalPrompt.custom\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const date: (options: Prompt.DateOptions) => Prompt<Date> = InternalDatePrompt.date\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const file: (options?: Prompt.FileOptions) => Prompt<string> = InternalFilePrompt.file\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const flatMap: {\n  <Output, Output2>(\n    f: (output: Output) => Prompt<Output2>\n  ): (self: Prompt<Output>) => Prompt<Output2>\n  <Output, Output2>(self: Prompt<Output>, f: (output: Output) => Prompt<Output2>): Prompt<Output2>\n} = InternalPrompt.flatMap\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const float: (options: Prompt.FloatOptions) => Prompt<number> = InternalNumberPrompt.float\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const hidden: (options: Prompt.TextOptions) => Prompt<Redacted> = InternalTextPrompt.hidden\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const integer: (options: Prompt.IntegerOptions) => Prompt<number> = InternalNumberPrompt.integer\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const list: (options: Prompt.ListOptions) => Prompt<Array<string>> = InternalListPrompt.list\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const map: {\n  <Output, Output2>(f: (output: Output) => Output2): (self: Prompt<Output>) => Prompt<Output2>\n  <Output, Output2>(self: Prompt<Output>, f: (output: Output) => Output2): Prompt<Output2>\n} = InternalPrompt.map\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const password: (options: Prompt.TextOptions) => Prompt<Redacted> = InternalTextPrompt.password\n\n/**\n * Executes the specified `Prompt`.\n *\n * @since 1.0.0\n * @category execution\n */\nexport const run: <Output>(self: Prompt<Output>) => Effect<Output, QuitException, Prompt.Environment> =\n  InternalPrompt.run\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const select: <const A>(options: Prompt.SelectOptions<A>) => Prompt<A> = InternalSelectPrompt.select\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const multiSelect: <const A>(options: Prompt.SelectOptions<A> & Prompt.MultiSelectOptions) => Prompt<Array<A>> =\n  InternalMultiSelectPrompt.multiSelect\n\n/**\n * Creates a `Prompt` which immediately succeeds with the specified value.\n *\n * **NOTE**: This method will not attempt to obtain user input or render\n * anything to the screen.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const succeed: <A>(value: A) => Prompt<A> = InternalPrompt.succeed\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const text: (options: Prompt.TextOptions) => Prompt<string> = InternalTextPrompt.text\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const toggle: (options: Prompt.ToggleOptions) => Prompt<boolean> = InternalTogglePrompt.toggle\n"
  },
  {
    "path": "packages/cli/src/Usage.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { Option } from \"effect/Option\"\nimport type { CliConfig } from \"./CliConfig.js\"\nimport type { HelpDoc } from \"./HelpDoc.js\"\nimport type { Span } from \"./HelpDoc/Span.js\"\nimport * as InternalUsage from \"./internal/usage.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Usage = Empty | Mixed | Named | Optional | Repeated | Alternation | Concat\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Empty {\n  readonly _tag: \"Empty\"\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Mixed {\n  readonly _tag: \"Mixed\"\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Named {\n  readonly _tag: \"Named\"\n  readonly names: ReadonlyArray<string>\n  readonly acceptedValues: Option<string>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Optional {\n  readonly _tag: \"Optional\"\n  readonly usage: Usage\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Repeated {\n  readonly _tag: \"Repeated\"\n  readonly usage: Usage\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Alternation {\n  readonly _tag: \"Alternation\"\n  readonly left: Usage\n  readonly right: Usage\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Concat {\n  readonly _tag: \"Concat\"\n  readonly left: Usage\n  readonly right: Usage\n}\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const alternation: {\n  (that: Usage): (self: Usage) => Usage\n  (self: Usage, that: Usage): Usage\n} = InternalUsage.alternation\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const concat: {\n  (that: Usage): (self: Usage) => Usage\n  (self: Usage, that: Usage): Usage\n} = InternalUsage.concat\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: Usage = InternalUsage.empty\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const enumerate: {\n  (config: CliConfig): (self: Usage) => Array<Span>\n  (self: Usage, config: CliConfig): Array<Span>\n} = InternalUsage.enumerate\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const getHelp: (self: Usage) => HelpDoc = InternalUsage.getHelp\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const mixed: Usage = InternalUsage.mixed\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const named: (names: ReadonlyArray<string>, acceptedValues: Option<string>) => Usage = InternalUsage.named\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const optional: (self: Usage) => Usage = InternalUsage.optional\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const repeated: (self: Usage) => Usage = InternalUsage.repeated\n"
  },
  {
    "path": "packages/cli/src/ValidationError.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { Command } from \"./CommandDescriptor.js\"\nimport type { HelpDoc } from \"./HelpDoc.js\"\nimport * as InternalCommand from \"./internal/commandDescriptor.js\"\nimport * as InternalValidationError from \"./internal/validationError.js\"\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport const ValidationErrorTypeId: unique symbol = InternalValidationError.ValidationErrorTypeId\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport type ValidationErrorTypeId = typeof ValidationErrorTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type ValidationError =\n  | CommandMismatch\n  | CorrectedFlag\n  | HelpRequested\n  | InvalidArgument\n  | InvalidValue\n  | MissingValue\n  | MissingFlag\n  | MultipleValuesDetected\n  | MissingSubcommand\n  | NoBuiltInMatch\n  | UnclusteredFlag\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface CommandMismatch extends ValidationError.Proto {\n  readonly _tag: \"CommandMismatch\"\n  readonly error: HelpDoc\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface CorrectedFlag extends ValidationError.Proto {\n  readonly _tag: \"CorrectedFlag\"\n  readonly error: HelpDoc\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HelpRequested extends ValidationError.Proto {\n  readonly _tag: \"HelpRequested\"\n  readonly error: HelpDoc\n  readonly command: Command<unknown>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface InvalidArgument extends ValidationError.Proto {\n  readonly _tag: \"InvalidArgument\"\n  readonly error: HelpDoc\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface InvalidValue extends ValidationError.Proto {\n  readonly _tag: \"InvalidValue\"\n  readonly error: HelpDoc\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface MissingFlag extends ValidationError.Proto {\n  readonly _tag: \"MissingFlag\"\n  readonly error: HelpDoc\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface MissingValue extends ValidationError.Proto {\n  readonly _tag: \"MissingValue\"\n  readonly error: HelpDoc\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface MissingSubcommand extends ValidationError.Proto {\n  readonly _tag: \"MissingSubcommand\"\n  readonly error: HelpDoc\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface MultipleValuesDetected extends ValidationError.Proto {\n  readonly _tag: \"MultipleValuesDetected\"\n  readonly error: HelpDoc\n  readonly values: ReadonlyArray<string>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface NoBuiltInMatch extends ValidationError.Proto {\n  readonly _tag: \"NoBuiltInMatch\"\n  readonly error: HelpDoc\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface UnclusteredFlag extends ValidationError.Proto {\n  readonly _tag: \"UnclusteredFlag\"\n  readonly error: HelpDoc\n  readonly unclustered: ReadonlyArray<string>\n  readonly rest: ReadonlyArray<string>\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace ValidationError {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Proto {\n    readonly [ValidationErrorTypeId]: ValidationErrorTypeId\n  }\n}\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isValidationError: (u: unknown) => u is ValidationError = InternalValidationError.isValidationError\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isCommandMismatch: (self: ValidationError) => self is CommandMismatch =\n  InternalValidationError.isCommandMismatch\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isCorrectedFlag: (self: ValidationError) => self is CorrectedFlag = InternalValidationError.isCorrectedFlag\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isHelpRequested: (self: ValidationError) => self is HelpRequested = InternalValidationError.isHelpRequested\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isInvalidArgument: (self: ValidationError) => self is InvalidArgument =\n  InternalValidationError.isInvalidArgument\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isInvalidValue: (self: ValidationError) => self is InvalidValue = InternalValidationError.isInvalidValue\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isMultipleValuesDetected: (self: ValidationError) => self is MultipleValuesDetected =\n  InternalValidationError.isMultipleValuesDetected\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isMissingFlag: (self: ValidationError) => self is MissingFlag = InternalValidationError.isMissingFlag\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isMissingValue: (self: ValidationError) => self is MissingValue = InternalValidationError.isMissingValue\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isMissingSubcommand: (self: ValidationError) => self is MissingSubcommand =\n  InternalValidationError.isMissingSubcommand\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isNoBuiltInMatch: (self: ValidationError) => self is NoBuiltInMatch =\n  InternalValidationError.isNoBuiltInMatch\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isUnclusteredFlag: (self: ValidationError) => self is UnclusteredFlag =\n  InternalValidationError.isUnclusteredFlag\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const commandMismatch: (error: HelpDoc) => ValidationError = InternalValidationError.commandMismatch\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const correctedFlag: (error: HelpDoc) => ValidationError = InternalValidationError.correctedFlag\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const helpRequested: <A>(command: Command<A>) => ValidationError = InternalCommand.helpRequestedError\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const invalidArgument: (error: HelpDoc) => ValidationError = InternalValidationError.invalidArgument\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const invalidValue: (error: HelpDoc) => ValidationError = InternalValidationError.invalidValue\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const keyValuesDetected: (\n  error: HelpDoc,\n  keyValues: ReadonlyArray<string>\n) => ValidationError = InternalValidationError.multipleValuesDetected\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const missingFlag: (error: HelpDoc) => ValidationError = InternalValidationError.missingFlag\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const missingValue: (error: HelpDoc) => ValidationError = InternalValidationError.missingValue\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const missingSubcommand: (error: HelpDoc) => ValidationError = InternalValidationError.missingSubcommand\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const noBuiltInMatch: (error: HelpDoc) => ValidationError = InternalValidationError.noBuiltInMatch\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const unclusteredFlag: (\n  error: HelpDoc,\n  unclustered: ReadonlyArray<string>,\n  rest: ReadonlyArray<string>\n) => ValidationError = InternalValidationError.unclusteredFlag\n"
  },
  {
    "path": "packages/cli/src/index.ts",
    "content": "/**\n * @since 1.0.0\n */\nexport * as Args from \"./Args.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as AutoCorrect from \"./AutoCorrect.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as BuiltInOptions from \"./BuiltInOptions.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as CliApp from \"./CliApp.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as CliConfig from \"./CliConfig.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Command from \"./Command.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as CommandDescriptor from \"./CommandDescriptor.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as CommandDirective from \"./CommandDirective.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ConfigFile from \"./ConfigFile.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as HelpDoc from \"./HelpDoc.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Options from \"./Options.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Primitive from \"./Primitive.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Prompt from \"./Prompt.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Usage from \"./Usage.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as ValidationError from \"./ValidationError.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Span from \"./HelpDoc/Span.js\"\n"
  },
  {
    "path": "packages/cli/src/internal/args.ts",
    "content": "import type * as FileSystem from \"@effect/platform/FileSystem\"\nimport type * as Path from \"@effect/platform/Path\"\nimport type * as Terminal from \"@effect/platform/Terminal\"\nimport * as Arr from \"effect/Array\"\nimport type * as Config from \"effect/Config\"\nimport * as ConfigError from \"effect/ConfigError\"\nimport * as Console from \"effect/Console\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { dual, pipe } from \"effect/Function\"\nimport * as Inspectable from \"effect/Inspectable\"\nimport * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport { pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Redacted from \"effect/Redacted\"\nimport * as Ref from \"effect/Ref\"\nimport type * as Schema from \"effect/Schema\"\nimport type * as Secret from \"effect/Secret\"\nimport type * as Args from \"../Args.js\"\nimport type * as CliConfig from \"../CliConfig.js\"\nimport type * as HelpDoc from \"../HelpDoc.js\"\nimport type * as Primitive from \"../Primitive.js\"\nimport type * as Usage from \"../Usage.js\"\nimport type * as ValidationError from \"../ValidationError.js\"\nimport * as InternalFiles from \"./files.js\"\nimport * as InternalHelpDoc from \"./helpDoc.js\"\nimport * as InternalSpan from \"./helpDoc/span.js\"\nimport * as InternalPrimitive from \"./primitive.js\"\nimport * as InternalNumberPrompt from \"./prompt/number.js\"\nimport * as InternalSelectPrompt from \"./prompt/select.js\"\nimport * as InternalUsage from \"./usage.js\"\nimport * as InternalValidationError from \"./validationError.js\"\n\nconst ArgsSymbolKey = \"@effect/cli/Args\"\n\n/** @internal */\nexport const ArgsTypeId: Args.ArgsTypeId = Symbol.for(\n  ArgsSymbolKey\n) as Args.ArgsTypeId\n\n/** @internal */\nexport type Op<Tag extends string, Body = {}> = Args.Args<never> & Body & {\n  readonly _tag: Tag\n}\n\nconst proto = {\n  [ArgsTypeId]: {\n    _A: (_: never) => _\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport type Instruction =\n  | Empty\n  | Single\n  | Map\n  | Both\n  | Variadic\n  | WithDefault\n  | WithFallbackConfig\n\n/** @internal */\nexport interface Empty extends Op<\"Empty\", {}> {}\n\n/** @internal */\nexport interface Single extends\n  Op<\"Single\", {\n    readonly name: string\n    readonly pseudoName: Option.Option<string>\n    readonly primitiveType: Primitive.Primitive<unknown>\n    readonly description: HelpDoc.HelpDoc\n  }>\n{}\n\n/** @internal */\nexport interface Map extends\n  Op<\"Map\", {\n    readonly args: Args.Args<unknown>\n    readonly f: (value: unknown) => Effect.Effect<\n      unknown,\n      HelpDoc.HelpDoc,\n      FileSystem.FileSystem | Path.Path | Terminal.Terminal\n    >\n  }>\n{}\n\n/** @internal */\nexport interface Both extends\n  Op<\"Both\", {\n    readonly left: Args.Args<unknown>\n    readonly right: Args.Args<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Variadic extends\n  Op<\"Variadic\", {\n    readonly args: Args.Args<unknown>\n    readonly min: Option.Option<number>\n    readonly max: Option.Option<number>\n  }>\n{}\n\n/** @internal */\nexport interface WithDefault extends\n  Op<\"WithDefault\", {\n    readonly args: Args.Args<unknown>\n    readonly fallback: unknown\n  }>\n{}\n\n/** @internal */\nexport interface WithFallbackConfig extends\n  Op<\"WithFallbackConfig\", {\n    readonly args: Args.Args<unknown>\n    readonly config: Config.Config<unknown>\n  }>\n{}\n\n// =============================================================================\n// Refinements\n// =============================================================================\n\n/** @internal */\nexport const isArgs = (u: unknown): u is Args.Args<unknown> => typeof u === \"object\" && u != null && ArgsTypeId in u\n\n/** @internal */\nexport const isInstruction = <_>(self: Args.Args<_>): self is Instruction => self as any\n\n/** @internal */\nexport const isEmpty = (self: Instruction): self is Empty => self._tag === \"Empty\"\n\n/** @internal */\nexport const isSingle = (self: Instruction): self is Single => self._tag === \"Single\"\n\n/** @internal */\nexport const isBoth = (self: Instruction): self is Both => self._tag === \"Both\"\n\n/** @internal */\nexport const isMap = (self: Instruction): self is Map => self._tag === \"Map\"\n\n/** @internal */\nexport const isVariadic = (self: Instruction): self is Variadic => self._tag === \"Variadic\"\n\n/** @internal */\nexport const isWithDefault = (self: Instruction): self is WithDefault => self._tag === \"WithDefault\"\n\n/** @internal */\nexport const isWithFallbackConfig = (self: Instruction): self is WithFallbackConfig =>\n  self._tag === \"WithFallbackConfig\"\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\n/** @internal */\nexport const all: <\n  const Arg extends Iterable<Args.Args<any>> | Record<string, Args.Args<any>>\n>(arg: Arg) => Args.All.Return<Arg> = function() {\n  if (arguments.length === 1) {\n    if (isArgs(arguments[0])) {\n      return map(arguments[0], (x) => [x]) as any\n    } else if (Arr.isArray(arguments[0])) {\n      return allTupled(arguments[0] as Array<any>) as any\n    } else {\n      const entries = Object.entries(arguments[0] as Readonly<{ [K: string]: Args.Args<any> }>)\n      let result = map(entries[0][1], (value) => ({ [entries[0][0]]: value }))\n      if (entries.length === 1) {\n        return result as any\n      }\n      const rest = entries.slice(1)\n      for (const [key, options] of rest) {\n        result = map(makeBoth(result, options), ([record, value]) => ({\n          ...record,\n          [key]: value\n        }))\n      }\n      return result as any\n    }\n  }\n  return allTupled(arguments[0]) as any\n}\n\n/** @internal */\nexport const boolean = (config?: Args.Args.BaseArgsConfig): Args.Args<boolean> =>\n  makeSingle(Option.fromNullable(config?.name), InternalPrimitive.boolean(Option.none()))\n\n/** @internal */\nexport const choice = <A>(\n  choices: ReadonlyArray<[string, A]>,\n  config?: Args.Args.BaseArgsConfig\n): Args.Args<A> => makeSingle(Option.fromNullable(config?.name), InternalPrimitive.choice(choices))\n\n/** @internal */\nexport const date = (config?: Args.Args.BaseArgsConfig): Args.Args<globalThis.Date> =>\n  makeSingle(Option.fromNullable(config?.name), InternalPrimitive.date)\n\n/** @internal */\nexport const directory = (config?: Args.Args.PathArgsConfig): Args.Args<string> =>\n  makeSingle(\n    Option.fromNullable(config?.name),\n    InternalPrimitive.path(\"directory\", config?.exists || \"either\")\n  )\n\n/** @internal */\nexport const file = (config?: Args.Args.PathArgsConfig): Args.Args<string> =>\n  makeSingle(\n    Option.fromNullable(config?.name),\n    InternalPrimitive.path(\"file\", config?.exists || \"either\")\n  )\n\n/** @internal */\nexport const fileContent = (\n  config?: Args.Args.BaseArgsConfig\n): Args.Args<readonly [path: string, content: Uint8Array]> =>\n  mapEffect(\n    file({ ...config, exists: \"yes\" }),\n    (path) => Effect.mapError(InternalFiles.read(path), (e) => InternalHelpDoc.p(e))\n  )\n\n/** @internal */\nexport const fileParse = (\n  config?: Args.Args.FormatArgsConfig\n): Args.Args<unknown> =>\n  mapEffect(fileText(config), ([path, content]) =>\n    Effect.mapError(\n      InternalFiles.parse(path, content, config?.format),\n      (e) => InternalHelpDoc.p(e)\n    ))\n\n/** @internal */\nexport const fileSchema = <I, A>(\n  schema: Schema.Schema<A, I, FileSystem.FileSystem | Path.Path | Terminal.Terminal>,\n  config?: Args.Args.FormatArgsConfig\n): Args.Args<A> => withSchema(fileParse(config), schema)\n\n/** @internal */\nexport const fileText = (\n  config?: Args.Args.BaseArgsConfig\n): Args.Args<readonly [path: string, content: string]> =>\n  mapEffect(file({ ...config, exists: \"yes\" }), (path) =>\n    Effect.mapError(\n      InternalFiles.readString(path),\n      (e) => InternalHelpDoc.p(e)\n    ))\n\n/** @internal */\nexport const float = (config?: Args.Args.BaseArgsConfig): Args.Args<number> =>\n  makeSingle(Option.fromNullable(config?.name), InternalPrimitive.float)\n\n/** @internal */\nexport const integer = (config?: Args.Args.BaseArgsConfig): Args.Args<number> =>\n  makeSingle(Option.fromNullable(config?.name), InternalPrimitive.integer)\n\n/** @internal */\nexport const none: Args.Args<void> = (() => {\n  const op = Object.create(proto)\n  op._tag = \"Empty\"\n  return op\n})()\n\n/** @internal */\nexport const path = (config?: Args.Args.PathArgsConfig): Args.Args<string> =>\n  makeSingle(\n    Option.fromNullable(config?.name),\n    InternalPrimitive.path(\"either\", config?.exists || \"either\")\n  )\n\n/** @internal */\nexport const redacted = (\n  config?: Args.Args.BaseArgsConfig\n): Args.Args<Redacted.Redacted> => makeSingle(Option.fromNullable(config?.name), InternalPrimitive.redacted)\n\n/** @internal */\nexport const secret = (\n  config?: Args.Args.BaseArgsConfig\n): Args.Args<Secret.Secret> => makeSingle(Option.fromNullable(config?.name), InternalPrimitive.secret)\n\n/** @internal */\nexport const text = (config?: Args.Args.BaseArgsConfig): Args.Args<string> =>\n  makeSingle(Option.fromNullable(config?.name), InternalPrimitive.text)\n\n// =============================================================================\n// Combinators\n// =============================================================================\n\n/** @internal */\nexport const atLeast = dual<\n  {\n    (times: 0): <A>(self: Args.Args<A>) => Args.Args<Array<A>>\n    (times: number): <A>(self: Args.Args<A>) => Args.Args<Arr.NonEmptyArray<A>>\n  },\n  {\n    <A>(self: Args.Args<A>, times: 0): Args.Args<Array<A>>\n    <A>(self: Args.Args<A>, times: number): Args.Args<Arr.NonEmptyArray<A>>\n  }\n>(2, (self, times) => makeVariadic(self, Option.some(times), Option.none()) as any)\n\n/** @internal */\nexport const atMost = dual<\n  (times: number) => <A>(self: Args.Args<A>) => Args.Args<Array<A>>,\n  <A>(self: Args.Args<A>, times: number) => Args.Args<Array<A>>\n>(2, (self, times) => makeVariadic(self, Option.none(), Option.some(times)))\n\n/** @internal */\nexport const between = dual<\n  {\n    (min: 0, max: number): <A>(self: Args.Args<A>) => Args.Args<Array<A>>\n    (\n      min: number,\n      max: number\n    ): <A>(self: Args.Args<A>) => Args.Args<Arr.NonEmptyArray<A>>\n  },\n  {\n    <A>(self: Args.Args<A>, min: 0, max: number): Args.Args<Array<A>>\n    <A>(\n      self: Args.Args<A>,\n      min: number,\n      max: number\n    ): Args.Args<Arr.NonEmptyArray<A>>\n  }\n>(3, (self, min, max) => makeVariadic(self, Option.some(min), Option.some(max)) as any)\n\n/** @internal */\nexport const getHelp = <A>(self: Args.Args<A>): HelpDoc.HelpDoc => getHelpInternal(self as Instruction)\n\n/** @internal */\nexport const getIdentifier = <A>(self: Args.Args<A>): Option.Option<string> =>\n  getIdentifierInternal(self as Instruction)\n\n/** @internal */\nexport const getMinSize = <A>(self: Args.Args<A>): number => getMinSizeInternal(self as Instruction)\n\n/** @internal */\nexport const getMaxSize = <A>(self: Args.Args<A>): number => getMaxSizeInternal(self as Instruction)\n\n/** @internal */\nexport const getUsage = <A>(self: Args.Args<A>): Usage.Usage => getUsageInternal(self as Instruction)\n\n/** @internal */\nexport const map = dual<\n  <A, B>(f: (a: A) => B) => (self: Args.Args<A>) => Args.Args<B>,\n  <A, B>(self: Args.Args<A>, f: (a: A) => B) => Args.Args<B>\n>(2, (self, f) => mapEffect(self, (a) => Effect.succeed(f(a))))\n\n/** @internal */\nexport const mapEffect = dual<\n  <A, B>(\n    f: (a: A) => Effect.Effect<B, HelpDoc.HelpDoc, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n  ) => (self: Args.Args<A>) => Args.Args<B>,\n  <A, B>(\n    self: Args.Args<A>,\n    f: (a: A) => Effect.Effect<B, HelpDoc.HelpDoc, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n  ) => Args.Args<B>\n>(2, (self, f) => makeMap(self, f))\n\n/** @internal */\nexport const mapTryCatch = dual<\n  <A, B>(\n    f: (a: A) => B,\n    onError: (e: unknown) => HelpDoc.HelpDoc\n  ) => (self: Args.Args<A>) => Args.Args<B>,\n  <A, B>(\n    self: Args.Args<A>,\n    f: (a: A) => B,\n    onError: (e: unknown) => HelpDoc.HelpDoc\n  ) => Args.Args<B>\n>(3, (self, f, onError) =>\n  mapEffect(self, (a) => {\n    try {\n      return Either.right(f(a))\n    } catch (e) {\n      return Either.left(onError(e))\n    }\n  }))\n\n/** @internal */\nexport const optional = <A>(self: Args.Args<A>): Args.Args<Option.Option<A>> =>\n  makeWithDefault(map(self, Option.some), Option.none())\n\n/** @internal */\nexport const repeated = <A>(self: Args.Args<A>): Args.Args<Array<A>> => makeVariadic(self, Option.none(), Option.none())\n\n/** @internal */\nexport const validate = dual<\n  (\n    args: ReadonlyArray<string>,\n    config: CliConfig.CliConfig\n  ) => <A>(self: Args.Args<A>) => Effect.Effect<\n    [Array<string>, A],\n    ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >,\n  <A>(\n    self: Args.Args<A>,\n    args: ReadonlyArray<string>,\n    config: CliConfig.CliConfig\n  ) => Effect.Effect<\n    [Array<string>, A],\n    ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >\n>(3, (self, args, config) => validateInternal(self as Instruction, args, config))\n\n/** @internal */\nexport const withDefault = dual<\n  <const B>(fallback: B) => <A>(self: Args.Args<A>) => Args.Args<A | B>,\n  <A, const B>(self: Args.Args<A>, fallback: B) => Args.Args<A | B>\n>(2, (self, fallback) => makeWithDefault(self, fallback))\n\n/** @internal */\nexport const withFallbackConfig: {\n  <B>(config: Config.Config<B>): <A>(self: Args.Args<A>) => Args.Args<B | A>\n  <A, B>(self: Args.Args<A>, config: Config.Config<B>): Args.Args<A | B>\n} = dual<\n  <B>(config: Config.Config<B>) => <A>(self: Args.Args<A>) => Args.Args<A | B>,\n  <A, B>(self: Args.Args<A>, config: Config.Config<B>) => Args.Args<A | B>\n>(2, (self, config) => {\n  if (isInstruction(self) && isWithDefault(self)) {\n    return makeWithDefault(\n      withFallbackConfig(self.args, config),\n      self.fallback as any\n    )\n  }\n  return makeWithFallbackConfig(self, config)\n})\n\n/** @internal */\nexport const withSchema = dual<\n  <A, I extends A, B>(\n    schema: Schema.Schema<B, I, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n  ) => (self: Args.Args<A>) => Args.Args<B>,\n  <A, I extends A, B>(\n    self: Args.Args<A>,\n    schema: Schema.Schema<B, I, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n  ) => Args.Args<B>\n>(2, (self, schema) => {\n  const decode = ParseResult.decode(schema)\n  return mapEffect(self, (_) =>\n    Effect.mapError(\n      decode(_ as any),\n      (issue) => InternalHelpDoc.p(ParseResult.TreeFormatter.formatIssueSync(issue))\n    ))\n})\n\n/** @internal */\nexport const withDescription = dual<\n  (description: string) => <A>(self: Args.Args<A>) => Args.Args<A>,\n  <A>(self: Args.Args<A>, description: string) => Args.Args<A>\n>(2, (self, description) => withDescriptionInternal(self as Instruction, description))\n\n/** @internal */\nexport const wizard = dual<\n  (config: CliConfig.CliConfig) => <A>(self: Args.Args<A>) => Effect.Effect<\n    Array<string>,\n    Terminal.QuitException | ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >,\n  <A>(self: Args.Args<A>, config: CliConfig.CliConfig) => Effect.Effect<\n    Array<string>,\n    Terminal.QuitException | ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >\n>(2, (self, config) => wizardInternal(self as Instruction, config))\n\n// =============================================================================\n// Internals\n// =============================================================================\n\nconst allTupled = <const T extends ArrayLike<Args.Args<any>>>(arg: T): Args.Args<\n  {\n    [K in keyof T]: [T[K]] extends [Args.Args<infer A>] ? A : never\n  }\n> => {\n  if (arg.length === 0) {\n    return none as any\n  }\n  if (arg.length === 1) {\n    return map(arg[0], (x) => [x]) as any\n  }\n  let result = map(arg[0], (x) => [x])\n  for (let i = 1; i < arg.length; i++) {\n    const curr = arg[i]\n    result = map(makeBoth(result, curr), ([a, b]) => [...a, b])\n  }\n  return result as any\n}\n\nconst getHelpInternal = (self: Instruction): HelpDoc.HelpDoc => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return InternalHelpDoc.empty\n    }\n    case \"Single\": {\n      return InternalHelpDoc.descriptionList([[\n        InternalSpan.weak(self.name),\n        InternalHelpDoc.sequence(\n          InternalHelpDoc.p(InternalPrimitive.getHelp(self.primitiveType)),\n          self.description\n        )\n      ]])\n    }\n    case \"Map\": {\n      return getHelpInternal(self.args as Instruction)\n    }\n    case \"Both\": {\n      return InternalHelpDoc.sequence(\n        getHelpInternal(self.left as Instruction),\n        getHelpInternal(self.right as Instruction)\n      )\n    }\n    case \"Variadic\": {\n      const help = getHelpInternal(self.args as Instruction)\n      return InternalHelpDoc.mapDescriptionList(help, (oldSpan, oldBlock) => {\n        const min = getMinSizeInternal(self as Instruction)\n        const max = getMaxSizeInternal(self as Instruction)\n        const newSpan = InternalSpan.text(\n          Option.isSome(self.max) ? ` ${min} - ${max}` : min === 0 ? \"...\" : ` ${min}+`\n        )\n        const newBlock = InternalHelpDoc.p(\n          Option.isSome(self.max)\n            ? `This argument must be repeated at least ${min} times and may be repeated up to ${max} times.`\n            : min === 0\n            ? \"This argument may be repeated zero or more times.\"\n            : `This argument must be repeated at least ${min} times.`\n        )\n        return [InternalSpan.concat(oldSpan, newSpan), InternalHelpDoc.sequence(oldBlock, newBlock)]\n      })\n    }\n    case \"WithDefault\": {\n      return InternalHelpDoc.mapDescriptionList(\n        getHelpInternal(self.args as Instruction),\n        (span, block) => {\n          const optionalDescription = Option.isOption(self.fallback)\n            ? Option.match(self.fallback, {\n              onNone: () => InternalHelpDoc.p(\"This setting is optional.\"),\n              onSome: (fallbackValue) => {\n                const inspectableValue = Predicate.isObject(fallbackValue) ? fallbackValue : String(fallbackValue)\n                const displayValue = Inspectable.toStringUnknown(inspectableValue, 0)\n                return InternalHelpDoc.p(`This setting is optional. Defaults to: ${displayValue}`)\n              }\n            })\n            : InternalHelpDoc.p(\"This setting is optional.\")\n          return [span, InternalHelpDoc.sequence(block, optionalDescription)]\n        }\n      )\n    }\n    case \"WithFallbackConfig\": {\n      return InternalHelpDoc.mapDescriptionList(\n        getHelpInternal(self.args as Instruction),\n        (span, block) => [\n          span,\n          InternalHelpDoc.sequence(\n            block,\n            InternalHelpDoc.p(\n              \"This argument can be set from environment variables.\"\n            )\n          )\n        ]\n      )\n    }\n  }\n}\n\nconst getIdentifierInternal = (self: Instruction): Option.Option<string> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Option.none()\n    }\n    case \"Single\": {\n      return Option.some(self.name)\n    }\n    case \"Map\":\n    case \"Variadic\":\n    case \"WithDefault\":\n    case \"WithFallbackConfig\": {\n      return getIdentifierInternal(self.args as Instruction)\n    }\n    case \"Both\": {\n      const ids = Arr.getSomes([\n        getIdentifierInternal(self.left as Instruction),\n        getIdentifierInternal(self.right as Instruction)\n      ])\n      return Arr.match(ids, {\n        onEmpty: () => Option.none(),\n        onNonEmpty: (ids) => Option.some(Arr.join(ids, \", \"))\n      })\n    }\n  }\n}\n\nconst getMinSizeInternal = (self: Instruction): number => {\n  switch (self._tag) {\n    case \"Empty\":\n    case \"WithDefault\":\n    case \"WithFallbackConfig\": {\n      return 0\n    }\n    case \"Single\": {\n      return 1\n    }\n    case \"Map\": {\n      return getMinSizeInternal(self.args as Instruction)\n    }\n    case \"Both\": {\n      const leftMinSize = getMinSizeInternal(self.left as Instruction)\n      const rightMinSize = getMinSizeInternal(self.right as Instruction)\n      return leftMinSize + rightMinSize\n    }\n    case \"Variadic\": {\n      const argsMinSize = getMinSizeInternal(self.args as Instruction)\n      return Math.floor(Option.getOrElse(self.min, () => 0) * argsMinSize)\n    }\n  }\n}\n\nconst getMaxSizeInternal = (self: Instruction): number => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return 0\n    }\n    case \"Single\": {\n      return 1\n    }\n    case \"Map\":\n    case \"WithDefault\":\n    case \"WithFallbackConfig\": {\n      return getMaxSizeInternal(self.args as Instruction)\n    }\n    case \"Both\": {\n      const leftMaxSize = getMaxSizeInternal(self.left as Instruction)\n      const rightMaxSize = getMaxSizeInternal(self.right as Instruction)\n      return leftMaxSize + rightMaxSize\n    }\n    case \"Variadic\": {\n      const argsMaxSize = getMaxSizeInternal(self.args as Instruction)\n      return Math.floor(Option.getOrElse(self.max, () => Number.MAX_SAFE_INTEGER / 2) * argsMaxSize)\n    }\n  }\n}\n\nconst getUsageInternal = (self: Instruction): Usage.Usage => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return InternalUsage.empty\n    }\n    case \"Single\": {\n      return InternalUsage.named(\n        Arr.of(self.name),\n        InternalPrimitive.getChoices(self.primitiveType)\n      )\n    }\n    case \"Map\": {\n      return getUsageInternal(self.args as Instruction)\n    }\n    case \"Both\": {\n      return InternalUsage.concat(\n        getUsageInternal(self.left as Instruction),\n        getUsageInternal(self.right as Instruction)\n      )\n    }\n    case \"Variadic\": {\n      return InternalUsage.repeated(getUsageInternal(self.args as Instruction))\n    }\n    case \"WithDefault\":\n    case \"WithFallbackConfig\": {\n      return InternalUsage.optional(getUsageInternal(self.args as Instruction))\n    }\n  }\n}\n\nconst makeSingle = <A>(\n  pseudoName: Option.Option<string>,\n  primitiveType: Primitive.Primitive<A>,\n  description: HelpDoc.HelpDoc = InternalHelpDoc.empty\n): Args.Args<A> => {\n  const op = Object.create(proto)\n  op._tag = \"Single\"\n  op.name = `<${Option.getOrElse(pseudoName, () => InternalPrimitive.getTypeName(primitiveType))}>`\n  op.pseudoName = pseudoName\n  op.primitiveType = primitiveType\n  op.description = description\n  return op\n}\n\nconst makeMap = <A, B>(\n  self: Args.Args<A>,\n  f: (value: A) => Effect.Effect<B, HelpDoc.HelpDoc, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n): Args.Args<B> => {\n  const op = Object.create(proto)\n  op._tag = \"Map\"\n  op.args = self\n  op.f = f\n  return op\n}\n\nconst makeBoth = <A, B>(left: Args.Args<A>, right: Args.Args<B>): Args.Args<[A, B]> => {\n  const op = Object.create(proto)\n  op._tag = \"Both\"\n  op.left = left\n  op.right = right\n  return op\n}\n\nconst makeWithDefault = <A, const B>(\n  self: Args.Args<A>,\n  fallback: B\n): Args.Args<A | B> => {\n  const op = Object.create(proto)\n  op._tag = \"WithDefault\"\n  op.args = self\n  op.fallback = fallback\n  return op\n}\n\nconst makeWithFallbackConfig = <A, B>(\n  args: Args.Args<A>,\n  config: Config.Config<B>\n): Args.Args<A | B> => {\n  const op = Object.create(proto)\n  op._tag = \"WithFallbackConfig\"\n  op.args = args\n  op.config = config\n  return op\n}\n\nconst makeVariadic = <A>(\n  args: Args.Args<A>,\n  min: Option.Option<number>,\n  max: Option.Option<number>\n): Args.Args<Array<A>> => {\n  const op = Object.create(proto)\n  op._tag = \"Variadic\"\n  op.args = args\n  op.min = min\n  op.max = max\n  return op\n}\n\nconst validateInternal = (\n  self: Instruction,\n  args: ReadonlyArray<string>,\n  config: CliConfig.CliConfig\n): Effect.Effect<\n  [Array<string>, any],\n  ValidationError.ValidationError,\n  FileSystem.FileSystem | Path.Path | Terminal.Terminal\n> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Effect.succeed([args as Array<string>, undefined])\n    }\n    case \"Single\": {\n      return Effect.suspend(() => {\n        return Arr.matchLeft(args, {\n          onEmpty: () => {\n            const choices = InternalPrimitive.getChoices(self.primitiveType)\n            if (Option.isSome(self.pseudoName) && Option.isSome(choices)) {\n              return Effect.fail(InternalValidationError.missingValue(InternalHelpDoc.p(\n                `Missing argument <${self.pseudoName.value}> with choices ${choices.value}`\n              )))\n            }\n            if (Option.isSome(self.pseudoName)) {\n              return Effect.fail(InternalValidationError.missingValue(InternalHelpDoc.p(\n                `Missing argument <${self.pseudoName.value}>`\n              )))\n            }\n            if (Option.isSome(choices)) {\n              return Effect.fail(InternalValidationError.missingValue(InternalHelpDoc.p(\n                `Missing argument ${InternalPrimitive.getTypeName(self.primitiveType)} with choices ${choices.value}`\n              )))\n            }\n            return Effect.fail(InternalValidationError.missingValue(InternalHelpDoc.p(\n              `Missing argument ${InternalPrimitive.getTypeName(self.primitiveType)}`\n            )))\n          },\n          onNonEmpty: (head, tail) =>\n            InternalPrimitive.validate(self.primitiveType, Option.some(head), config).pipe(\n              Effect.mapBoth({\n                onFailure: (text) => InternalValidationError.invalidArgument(InternalHelpDoc.p(text)),\n                onSuccess: (a) => [tail, a]\n              })\n            )\n        })\n      })\n    }\n    case \"Map\": {\n      return validateInternal(self.args as Instruction, args, config).pipe(\n        Effect.flatMap(([leftover, a]) =>\n          Effect.matchEffect(self.f(a), {\n            onFailure: (doc) => Effect.fail(InternalValidationError.invalidArgument(doc)),\n            onSuccess: (b) => Effect.succeed([leftover, b])\n          })\n        )\n      )\n    }\n    case \"Both\": {\n      return validateInternal(self.left as Instruction, args, config).pipe(\n        Effect.flatMap(([args, a]) =>\n          validateInternal(self.right as Instruction, args, config).pipe(\n            Effect.map(([args, b]) => [args, [a, b]])\n          )\n        )\n      )\n    }\n    case \"Variadic\": {\n      const min1 = Option.getOrElse(self.min, () => 0)\n      const max1 = Option.getOrElse(self.max, () => Number.MAX_SAFE_INTEGER)\n      const loop = (\n        args: ReadonlyArray<string>,\n        acc: ReadonlyArray<any>\n      ): Effect.Effect<\n        [ReadonlyArray<string>, ReadonlyArray<any>],\n        ValidationError.ValidationError,\n        FileSystem.FileSystem | Path.Path | Terminal.Terminal\n      > => {\n        if (acc.length >= max1) {\n          return Effect.succeed([args, acc])\n        }\n        return validateInternal(self.args as Instruction, args, config).pipe(Effect.matchEffect({\n          onFailure: (failure) =>\n            acc.length >= min1 && Arr.isEmptyReadonlyArray(args)\n              ? Effect.succeed([args, acc])\n              : Effect.fail(failure),\n          onSuccess: ([args, a]) => loop(args, Arr.append(acc, a))\n        }))\n      }\n      return loop(args, Arr.empty()).pipe(\n        Effect.map(([args, acc]) => [args as Array<string>, acc])\n      )\n    }\n    case \"WithDefault\": {\n      return validateInternal(self.args as Instruction, args, config).pipe(\n        Effect.catchTag(\"MissingValue\", () =>\n          Effect.succeed<[Array<string>, any]>([\n            args as Array<string>,\n            self.fallback\n          ]))\n      )\n    }\n    case \"WithFallbackConfig\": {\n      return validateInternal(self.args as Instruction, args, config).pipe(\n        Effect.catchTag(\"MissingValue\", (e) =>\n          Effect.map(\n            Effect.catchAll(self.config, (e2) => {\n              if (ConfigError.isMissingDataOnly(e2)) {\n                const help = InternalHelpDoc.p(String(e2))\n                const error = InternalValidationError.invalidValue(help)\n                return Effect.fail(error)\n              }\n              return Effect.fail(e)\n            }),\n            (value) => [args, value] as [Array<string>, any]\n          ))\n      )\n    }\n  }\n}\n\nconst withDescriptionInternal = (self: Instruction, description: string): Args.Args<any> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return none\n    }\n    case \"Single\": {\n      const desc = InternalHelpDoc.sequence(self.description, InternalHelpDoc.p(description))\n      return makeSingle(self.pseudoName, self.primitiveType, desc)\n    }\n    case \"Map\": {\n      return makeMap(withDescriptionInternal(self.args as Instruction, description), self.f)\n    }\n    case \"Both\": {\n      return makeBoth(\n        withDescriptionInternal(self.left as Instruction, description),\n        withDescriptionInternal(self.right as Instruction, description)\n      )\n    }\n    case \"Variadic\": {\n      return makeVariadic(\n        withDescriptionInternal(self.args as Instruction, description),\n        self.min,\n        self.max\n      )\n    }\n    case \"WithDefault\": {\n      return makeWithDefault(\n        withDescriptionInternal(self.args as Instruction, description),\n        self.fallback\n      )\n    }\n    case \"WithFallbackConfig\": {\n      return makeWithFallbackConfig(\n        withDescriptionInternal(self.args as Instruction, description),\n        self.config\n      )\n    }\n  }\n}\n\nconst wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect.Effect<\n  Array<string>,\n  Terminal.QuitException | ValidationError.ValidationError,\n  FileSystem.FileSystem | Path.Path | Terminal.Terminal\n> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Effect.succeed(Arr.empty())\n    }\n    case \"Single\": {\n      const help = getHelpInternal(self)\n      return InternalPrimitive.wizard(self.primitiveType, help).pipe(\n        Effect.zipLeft(Console.log()),\n        Effect.flatMap((input) => {\n          const args = Arr.of(input as string)\n          return validateInternal(self, args, config).pipe(Effect.as(args))\n        })\n      )\n    }\n    case \"Map\": {\n      return wizardInternal(self.args as Instruction, config).pipe(\n        Effect.tap((args) => validateInternal(self.args as Instruction, args, config))\n      )\n    }\n    case \"Both\": {\n      return Effect.zipWith(\n        wizardInternal(self.left as Instruction, config),\n        wizardInternal(self.right as Instruction, config),\n        (left, right) => Arr.appendAll(left, right)\n      ).pipe(Effect.tap((args) => validateInternal(self, args, config)))\n    }\n    case \"Variadic\": {\n      const repeatHelp = InternalHelpDoc.p(\n        \"How many times should this argument should be repeated?\"\n      )\n      const message = pipe(\n        getHelpInternal(self),\n        InternalHelpDoc.sequence(repeatHelp)\n      )\n      return InternalNumberPrompt.integer({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd(),\n        min: getMinSizeInternal(self),\n        max: getMaxSizeInternal(self)\n      }).pipe(\n        Effect.zipLeft(Console.log()),\n        Effect.flatMap((n) =>\n          n <= 0\n            ? Effect.succeed(Arr.empty<string>())\n            : Ref.make(Arr.empty<string>()).pipe(\n              Effect.flatMap((ref) =>\n                wizardInternal(self.args as Instruction, config).pipe(\n                  Effect.flatMap((args) => Ref.update(ref, Arr.appendAll(args))),\n                  Effect.repeatN(n - 1),\n                  Effect.zipRight(Ref.get(ref)),\n                  Effect.tap((args) => validateInternal(self, args, config))\n                )\n              )\n            )\n        )\n      )\n    }\n    case \"WithDefault\": {\n      const defaultHelp = InternalHelpDoc.p(`This argument is optional - use the default?`)\n      const message = pipe(\n        getHelpInternal(self.args as Instruction),\n        InternalHelpDoc.sequence(defaultHelp)\n      )\n      return InternalSelectPrompt.select({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd(),\n        choices: [\n          { title: `Default ['${JSON.stringify(self.fallback)}']`, value: true },\n          { title: \"Custom\", value: false }\n        ]\n      }).pipe(\n        Effect.zipLeft(Console.log()),\n        Effect.flatMap((useFallback) =>\n          useFallback\n            ? Effect.succeed(Arr.empty())\n            : wizardInternal(self.args as Instruction, config)\n        )\n      )\n    }\n    case \"WithFallbackConfig\": {\n      const defaultHelp = InternalHelpDoc.p(`Try load this option from the environment?`)\n      const message = pipe(\n        getHelpInternal(self.args as Instruction),\n        InternalHelpDoc.sequence(defaultHelp)\n      )\n      return InternalSelectPrompt.select({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd(),\n        choices: [\n          { title: `Use environment variables`, value: true },\n          { title: \"Custom\", value: false }\n        ]\n      }).pipe(\n        Effect.zipLeft(Console.log()),\n        Effect.flatMap((useFallback) =>\n          useFallback\n            ? Effect.succeed(Arr.empty())\n            : wizardInternal(self.args as Instruction, config)\n        )\n      )\n    }\n  }\n}\n\n// =============================================================================\n// Completion Internals\n// =============================================================================\n\nconst getShortDescription = (self: Instruction): string => {\n  switch (self._tag) {\n    case \"Empty\":\n    case \"Both\": {\n      return \"\"\n    }\n    case \"Single\": {\n      return InternalSpan.getText(InternalHelpDoc.getSpan(self.description))\n    }\n    case \"Map\":\n    case \"Variadic\":\n    case \"WithDefault\":\n    case \"WithFallbackConfig\": {\n      return getShortDescription(self.args as Instruction)\n    }\n  }\n}\n\n/** @internal */\nexport const getFishCompletions = (self: Instruction): Array<string> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Arr.empty()\n    }\n    case \"Single\": {\n      const description = getShortDescription(self)\n      return pipe(\n        InternalPrimitive.getFishCompletions(\n          self.primitiveType as InternalPrimitive.Instruction\n        ),\n        Arr.appendAll(\n          description.length === 0\n            ? Arr.empty()\n            : Arr.of(`-d '${description}'`)\n        ),\n        Arr.join(\" \"),\n        Arr.of\n      )\n    }\n    case \"Both\": {\n      return pipe(\n        getFishCompletions(self.left as Instruction),\n        Arr.appendAll(getFishCompletions(self.right as Instruction))\n      )\n    }\n    case \"Map\":\n    case \"Variadic\":\n    case \"WithDefault\":\n    case \"WithFallbackConfig\": {\n      return getFishCompletions(self.args as Instruction)\n    }\n  }\n}\n\ninterface ZshCompletionState {\n  readonly multiple: boolean\n  readonly optional: boolean\n}\n\nexport const getZshCompletions = (\n  self: Instruction,\n  state: ZshCompletionState = { multiple: false, optional: false }\n): Array<string> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Arr.empty()\n    }\n    case \"Single\": {\n      const multiple = state.multiple ? \"*\" : \"\"\n      const optional = state.optional ? \"::\" : \":\"\n      const shortDescription = getShortDescription(self)\n      const description = shortDescription.length > 0 ? ` -- ${shortDescription}` : \"\"\n      const possibleValues = InternalPrimitive.getZshCompletions(\n        self.primitiveType as InternalPrimitive.Instruction\n      )\n      return possibleValues.length === 0\n        ? Arr.empty()\n        : Arr.of(`${multiple}${optional}${self.name}${description}${possibleValues}`)\n    }\n    case \"Map\": {\n      return getZshCompletions(self.args as Instruction, state)\n    }\n    case \"Both\": {\n      const left = getZshCompletions(self.left as Instruction, state)\n      const right = getZshCompletions(self.right as Instruction, state)\n      return Arr.appendAll(left, right)\n    }\n    case \"Variadic\": {\n      return Option.isSome(self.max) && self.max.value > 1\n        ? getZshCompletions(self.args as Instruction, { ...state, multiple: true })\n        : getZshCompletions(self.args as Instruction, state)\n    }\n    case \"WithDefault\":\n    case \"WithFallbackConfig\": {\n      return getZshCompletions(self.args as Instruction, { ...state, optional: true })\n    }\n  }\n}\n"
  },
  {
    "path": "packages/cli/src/internal/autoCorrect.ts",
    "content": "import type * as CliConfig from \"../CliConfig.js\"\nimport * as cliConfig from \"./cliConfig.js\"\n\n/** @internal */\nexport const levensteinDistance = (\n  first: string,\n  second: string,\n  config: CliConfig.CliConfig\n): number => {\n  if (first.length === 0 && second.length === 0) {\n    return 0\n  }\n  if (first.length === 0) {\n    return second.length\n  }\n  if (second.length === 0) {\n    return first.length\n  }\n  const rowCount = first.length\n  const columnCount = second.length\n  const matrix = new Array<Array<number>>(rowCount)\n  const normalFirst = cliConfig.normalizeCase(config, first)\n  const normalSecond = cliConfig.normalizeCase(config, second)\n  // Increment each row in the first column\n  for (let x = 0; x <= rowCount; x++) {\n    matrix[x] = new Array<number>(columnCount)\n    matrix[x][0] = x\n  }\n  // Increment each column in the first row\n  for (let y = 0; y <= columnCount; y++) {\n    matrix[0][y] = y\n  }\n  // Fill in the rest of the matrix\n  for (let row = 1; row <= rowCount; row++) {\n    for (let col = 1; col <= columnCount; col++) {\n      const cost = normalFirst.charAt(row - 1) === normalSecond.charAt(col - 1) ? 0 : 1\n      matrix[row][col] = Math.min(\n        matrix[row][col - 1] + 1,\n        Math.min(matrix[row - 1][col] + 1, matrix[row - 1][col - 1] + cost)\n      )\n    }\n  }\n  return matrix[rowCount][columnCount]\n}\n"
  },
  {
    "path": "packages/cli/src/internal/builtInOptions.ts",
    "content": "import * as LogLevel from \"effect/LogLevel\"\nimport * as Option from \"effect/Option\"\nimport type * as BuiltInOptions from \"../BuiltInOptions.js\"\nimport type * as Command from \"../CommandDescriptor.js\"\nimport type * as HelpDoc from \"../HelpDoc.js\"\nimport type * as Options from \"../Options.js\"\nimport type * as Usage from \"../Usage.js\"\nimport * as InternalOptions from \"./options.js\"\n\n/** @internal */\nexport const setLogLevel = (\n  level: LogLevel.LogLevel\n): BuiltInOptions.BuiltInOptions => ({\n  _tag: \"SetLogLevel\",\n  level\n})\n\n/** @internal */\nexport const showCompletions = (\n  shellType: BuiltInOptions.BuiltInOptions.ShellType\n): BuiltInOptions.BuiltInOptions => ({\n  _tag: \"ShowCompletions\",\n  shellType\n})\n\n/** @internal */\nexport const showHelp = (\n  usage: Usage.Usage,\n  helpDoc: HelpDoc.HelpDoc\n): BuiltInOptions.BuiltInOptions => ({\n  _tag: \"ShowHelp\",\n  usage,\n  helpDoc\n})\n\n/** @internal */\nexport const showWizard = (command: Command.Command<unknown>): BuiltInOptions.BuiltInOptions => ({\n  _tag: \"ShowWizard\",\n  command\n})\n\n/** @internal */\nexport const showVersion: BuiltInOptions.BuiltInOptions = {\n  _tag: \"ShowVersion\"\n}\n\n/** @internal */\nexport const isShowCompletions = (\n  self: BuiltInOptions.BuiltInOptions\n): self is BuiltInOptions.ShowCompletions => self._tag === \"ShowCompletions\"\n\n/** @internal */\nexport const isShowHelp = (self: BuiltInOptions.BuiltInOptions): self is BuiltInOptions.ShowHelp =>\n  self._tag === \"ShowHelp\"\n\n/** @internal */\nexport const isShowWizard = (\n  self: BuiltInOptions.BuiltInOptions\n): self is BuiltInOptions.ShowWizard => self._tag === \"ShowWizard\"\n\n/** @internal */\nexport const isShowVersion = (\n  self: BuiltInOptions.BuiltInOptions\n): self is BuiltInOptions.ShowVersion => self._tag === \"ShowVersion\"\n\n/** @internal */\nexport const completionsOptions: Options.Options<\n  Option.Option<BuiltInOptions.BuiltInOptions.ShellType>\n> = InternalOptions.choiceWithValue(\"completions\", [\n  [\"sh\", \"bash\" as const],\n  [\"bash\", \"bash\" as const],\n  [\"fish\", \"fish\" as const],\n  [\"zsh\", \"zsh\" as const]\n]).pipe(\n  InternalOptions.optional,\n  InternalOptions.withDescription(\"Generate a completion script for a specific shell.\")\n)\n\n/** @internal */\nexport const logLevelOptions: Options.Options<\n  Option.Option<LogLevel.LogLevel>\n> = InternalOptions.choiceWithValue(\n  \"log-level\",\n  LogLevel.allLevels.map((level) => [level._tag.toLowerCase(), level] as const)\n).pipe(\n  InternalOptions.optional,\n  InternalOptions.withDescription(\"Sets the minimum log level for a command.\")\n)\n\n/** @internal */\nexport const helpOptions: Options.Options<boolean> = InternalOptions.boolean(\"help\").pipe(\n  InternalOptions.withAlias(\"h\"),\n  InternalOptions.withDescription(\"Show the help documentation for a command.\")\n)\n\n/** @internal */\nexport const versionOptions: Options.Options<boolean> = InternalOptions.boolean(\"version\").pipe(\n  InternalOptions.withDescription(\"Show the version of the application.\")\n)\n\n/** @internal */\nexport const wizardOptions: Options.Options<boolean> = InternalOptions.boolean(\"wizard\").pipe(\n  InternalOptions.withDescription(\"Start wizard mode for a command.\")\n)\n\n/** @internal */\nexport const builtIns = InternalOptions.all({\n  completions: completionsOptions,\n  logLevel: logLevelOptions,\n  help: helpOptions,\n  wizard: wizardOptions,\n  version: versionOptions\n})\n\n/** @internal */\nexport const builtInOptions = <A>(\n  command: Command.Command<A>,\n  usage: Usage.Usage,\n  helpDoc: HelpDoc.HelpDoc\n): Options.Options<Option.Option<BuiltInOptions.BuiltInOptions>> =>\n  InternalOptions.map(builtIns, (builtIn) => {\n    if (Option.isSome(builtIn.completions)) {\n      return Option.some(showCompletions(builtIn.completions.value))\n    }\n    if (Option.isSome(builtIn.logLevel)) {\n      return Option.some(setLogLevel(builtIn.logLevel.value))\n    }\n    if (builtIn.help) {\n      return Option.some(showHelp(usage, helpDoc))\n    }\n    if (builtIn.wizard) {\n      return Option.some(showWizard(command))\n    }\n    if (builtIn.version) {\n      return Option.some(showVersion)\n    }\n    return Option.none()\n  })\n"
  },
  {
    "path": "packages/cli/src/internal/cliApp.ts",
    "content": "import * as Terminal from \"@effect/platform/Terminal\"\nimport * as Color from \"@effect/printer-ansi/Color\"\nimport * as Arr from \"effect/Array\"\nimport * as Console from \"effect/Console\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { dual, pipe } from \"effect/Function\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as Logger from \"effect/Logger\"\nimport * as Option from \"effect/Option\"\nimport { pipeArguments } from \"effect/Pipeable\"\nimport * as Unify from \"effect/Unify\"\nimport type * as BuiltInOptions from \"../BuiltInOptions.js\"\nimport type * as CliApp from \"../CliApp.js\"\nimport type * as CliConfig from \"../CliConfig.js\"\nimport type * as Command from \"../CommandDescriptor.js\"\nimport type * as HelpDoc from \"../HelpDoc.js\"\nimport type * as ValidationError from \"../ValidationError.js\"\nimport * as InternalBuiltInOptions from \"./builtInOptions.js\"\nimport * as InternalCliConfig from \"./cliConfig.js\"\nimport * as InternalCommand from \"./commandDescriptor.js\"\nimport * as InternalHelpDoc from \"./helpDoc.js\"\nimport * as InternalSpan from \"./helpDoc/span.js\"\nimport * as InternalTogglePrompt from \"./prompt/toggle.js\"\nimport * as InternalUsage from \"./usage.js\"\nimport * as InternalValidationError from \"./validationError.js\"\n\nconst proto = {\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\n/** @internal */\nexport const make = <A>(config: CliApp.CliApp.ConstructorArgs<A>): CliApp.CliApp<A> => {\n  const op = Object.create(proto)\n  op.name = config.name\n  op.version = config.version\n  op.executable = config.executable\n  op.command = config.command\n  op.summary = config.summary || InternalSpan.empty\n  op.footer = config.footer || InternalHelpDoc.empty\n  return op\n}\n\n// =============================================================================\n// Combinators\n// =============================================================================\n\n/** @internal */\nexport const run = dual<\n  <R, E, A>(\n    args: ReadonlyArray<string>,\n    execute: (a: A) => Effect.Effect<void, E, R>\n  ) => (\n    self: CliApp.CliApp<A>\n  ) => Effect.Effect<void, E | ValidationError.ValidationError, R | CliApp.CliApp.Environment>,\n  <R, E, A>(\n    self: CliApp.CliApp<A>,\n    args: ReadonlyArray<string>,\n    execute: (a: A) => Effect.Effect<void, E, R>\n  ) => Effect.Effect<void, E | ValidationError.ValidationError, R | CliApp.CliApp.Environment>\n>(3, <R, E, A>(\n  self: CliApp.CliApp<A>,\n  args: ReadonlyArray<string>,\n  execute: (a: A) => Effect.Effect<void, E, R>\n): Effect.Effect<void, E | ValidationError.ValidationError, R | CliApp.CliApp.Environment> =>\n  Effect.contextWithEffect((context: Context.Context<CliApp.CliApp.Environment>) => {\n    // Attempt to parse the CliConfig from the environment, falling back to the\n    // default CliConfig if none was provided\n    const config = Option.getOrElse(\n      Context.getOption(context, InternalCliConfig.Tag),\n      () => InternalCliConfig.defaultConfig\n    )\n    // Remove the executable from the command line arguments\n    const [executable, filteredArgs] = splitExecutable(self, args)\n    // Prefix the command name to the command line arguments\n    const prefixedArgs = Arr.appendAll(prefixCommand(self.command), filteredArgs)\n    // Handle the command\n    return Effect.matchEffect(InternalCommand.parse(self.command, prefixedArgs, config), {\n      onFailure: (e) => Effect.zipRight(printDocs(e.error), Effect.fail(e)),\n      onSuccess: Unify.unify((directive) => {\n        switch (directive._tag) {\n          case \"UserDefined\": {\n            return Arr.matchLeft(directive.leftover, {\n              onEmpty: () =>\n                execute(directive.value).pipe(\n                  Effect.catchSome((e) =>\n                    InternalValidationError.isValidationError(e) &&\n                      InternalValidationError.isHelpRequested(e)\n                      ? Option.some(\n                        handleBuiltInOption(\n                          self,\n                          executable,\n                          filteredArgs,\n                          InternalBuiltInOptions.showHelp(\n                            InternalCommand.getUsage(e.command),\n                            InternalCommand.getHelp(e.command, config)\n                          ),\n                          execute,\n                          config,\n                          args\n                        )\n                      )\n                      : Option.none()\n                  )\n                ),\n              onNonEmpty: (head) => {\n                const error = InternalHelpDoc.p(`Received unknown argument: '${head}'`)\n                return Effect.zipRight(printDocs(error), Effect.fail(InternalValidationError.invalidValue(error)))\n              }\n            })\n          }\n          case \"BuiltIn\": {\n            return handleBuiltInOption(self, executable, filteredArgs, directive.option, execute, config, args).pipe(\n              Effect.catchSome((e) =>\n                InternalValidationError.isValidationError(e)\n                  ? Option.some(Effect.zipRight(printDocs(e.error), Effect.fail(e)))\n                  : Option.none()\n              )\n            )\n          }\n        }\n      })\n    })\n  }))\n\n// =============================================================================\n// Internals\n// =============================================================================\n\nconst splitExecutable = <A>(self: CliApp.CliApp<A>, args: ReadonlyArray<string>): [\n  executable: string,\n  args: ReadonlyArray<string>\n] => {\n  if (self.executable !== undefined) {\n    return [self.executable, Arr.drop(args, 2)]\n  }\n  const [[runtime, script], optionsAndArgs] = Arr.splitAt(args, 2)\n  return [`${runtime} ${script}`, optionsAndArgs]\n}\n\nconst printDocs = (error: HelpDoc.HelpDoc): Effect.Effect<void> => Console.error(InternalHelpDoc.toAnsiText(error))\n\nconst handleBuiltInOption = <R, E, A>(\n  self: CliApp.CliApp<A>,\n  executable: string,\n  args: ReadonlyArray<string>,\n  builtIn: BuiltInOptions.BuiltInOptions,\n  execute: (a: A) => Effect.Effect<void, E, R>,\n  config: CliConfig.CliConfig,\n  originalArgs: ReadonlyArray<string>\n): Effect.Effect<\n  void,\n  E | ValidationError.ValidationError,\n  R | CliApp.CliApp.Environment | Terminal.Terminal\n> => {\n  switch (builtIn._tag) {\n    case \"SetLogLevel\": {\n      // Use first 2 elements from originalArgs (runtime + script) to preserve paths with spaces\n      // Filter out --log-level from args before re-executing\n      const baseArgs = Arr.take(originalArgs, 2)\n      const filteredArgs: Array<string> = []\n      for (let i = 0; i < args.length; i++) {\n        if (isLogLevelArg(args[i]) || isLogLevelArg(args[i - 1])) {\n          continue\n        }\n        filteredArgs.push(args[i])\n      }\n      const nextArgs = Arr.appendAll(baseArgs, filteredArgs)\n      return run(self, nextArgs, execute).pipe(\n        Logger.withMinimumLogLevel(builtIn.level)\n      )\n    }\n    case \"ShowHelp\": {\n      const banner = InternalHelpDoc.h1(InternalSpan.code(self.name))\n      const header = InternalHelpDoc.p(InternalSpan.spans([\n        InternalSpan.text(`${self.name} ${self.version}`),\n        InternalSpan.isEmpty(self.summary)\n          ? InternalSpan.empty\n          : InternalSpan.spans([\n            InternalSpan.space,\n            InternalSpan.text(\"--\"),\n            InternalSpan.space,\n            self.summary\n          ])\n      ]))\n      const usage = InternalHelpDoc.sequence(\n        InternalHelpDoc.h1(\"USAGE\"),\n        pipe(\n          InternalUsage.enumerate(builtIn.usage, config),\n          Arr.map((span) => InternalHelpDoc.p(InternalSpan.concat(InternalSpan.text(\"$ \"), span))),\n          Arr.reduceRight(\n            InternalHelpDoc.empty,\n            (left, right) => InternalHelpDoc.sequence(left, right)\n          )\n        )\n      )\n      const helpDoc = pipe(\n        banner,\n        InternalHelpDoc.sequence(header),\n        InternalHelpDoc.sequence(usage),\n        InternalHelpDoc.sequence(builtIn.helpDoc),\n        InternalHelpDoc.sequence(self.footer)\n      )\n      return Console.log(InternalHelpDoc.toAnsiText(helpDoc))\n    }\n    case \"ShowCompletions\": {\n      const command = Arr.fromIterable(InternalCommand.getNames(self.command))[0]!\n      switch (builtIn.shellType) {\n        case \"bash\": {\n          return InternalCommand.getBashCompletions(self.command, command).pipe(\n            Effect.flatMap((completions) => Console.log(Arr.join(completions, \"\\n\")))\n          )\n        }\n        case \"fish\": {\n          return InternalCommand.getFishCompletions(self.command, command).pipe(\n            Effect.flatMap((completions) => Console.log(Arr.join(completions, \"\\n\")))\n          )\n        }\n        case \"zsh\":\n          return InternalCommand.getZshCompletions(self.command, command).pipe(\n            Effect.flatMap((completions) => Console.log(Arr.join(completions, \"\\n\")))\n          )\n      }\n    }\n    case \"ShowWizard\": {\n      const summary = InternalSpan.isEmpty(self.summary)\n        ? InternalSpan.empty\n        : InternalSpan.spans([\n          InternalSpan.space,\n          InternalSpan.text(\"--\"),\n          InternalSpan.space,\n          self.summary\n        ])\n      const instructions = InternalHelpDoc.sequence(\n        InternalHelpDoc.p(InternalSpan.spans([\n          InternalSpan.text(\"The wizard mode will assist you with constructing commands for\"),\n          InternalSpan.space,\n          InternalSpan.code(`${self.name} (${self.version})`),\n          InternalSpan.text(\".\")\n        ])),\n        InternalHelpDoc.p(\"Please answer all prompts provided by the wizard.\")\n      )\n      const description = InternalHelpDoc.descriptionList([[\n        InternalSpan.text(\"Instructions\"),\n        instructions\n      ]])\n      const header = InternalHelpDoc.h1(\n        InternalSpan.spans([\n          InternalSpan.code(\"Wizard Mode for CLI Application:\"),\n          InternalSpan.space,\n          InternalSpan.code(self.name),\n          InternalSpan.space,\n          InternalSpan.code(`(${self.version})`),\n          summary\n        ])\n      )\n      const help = InternalHelpDoc.sequence(header, description)\n      const text = InternalHelpDoc.toAnsiText(help)\n      const command = Arr.fromIterable(InternalCommand.getNames(self.command))[0]!\n      const wizardPrefix = getWizardPrefix(builtIn, command, args)\n      return Console.log(text).pipe(\n        Effect.zipRight(InternalCommand.wizard(builtIn.command, wizardPrefix, config)),\n        Effect.tap((args) => Console.log(InternalHelpDoc.toAnsiText(renderWizardArgs(args)))),\n        Effect.flatMap((args) =>\n          InternalTogglePrompt.toggle({\n            message: \"Would you like to run the command?\",\n            initial: true,\n            active: \"yes\",\n            inactive: \"no\"\n          }).pipe(Effect.flatMap((shouldRunCommand) => {\n            // Use first 2 elements from originalArgs (runtime + script) to preserve paths with spaces\n            // This mimics executable.split() behavior but without breaking Windows paths\n            const baseArgs = Arr.take(originalArgs, 2)\n            const wizardArgs = Arr.drop(args, 1)\n            const finalArgs = Arr.appendAll(baseArgs, wizardArgs)\n            return shouldRunCommand\n              ? Console.log().pipe(Effect.zipRight(run(self, finalArgs, execute)))\n              : Effect.void\n          }))\n        ),\n        Effect.catchAll((e) => {\n          if (Terminal.isQuitException(e)) {\n            const message = InternalHelpDoc.p(InternalSpan.error(\"\\n\\nQuitting wizard mode...\"))\n            return Console.log(InternalHelpDoc.toAnsiText(message))\n          }\n          return Effect.fail(e)\n        })\n      )\n    }\n    case \"ShowVersion\": {\n      const help = InternalHelpDoc.p(self.version)\n      return Console.log(InternalHelpDoc.toAnsiText(help))\n    }\n  }\n}\n\nconst prefixCommand = <A>(self: Command.Command<A>): ReadonlyArray<string> => {\n  let command: InternalCommand.Instruction | undefined = self as InternalCommand.Instruction\n  let prefix: ReadonlyArray<string> = Arr.empty()\n  while (command !== undefined) {\n    switch (command._tag) {\n      case \"Standard\": {\n        prefix = Arr.of(command.name)\n        command = undefined\n        break\n      }\n      case \"GetUserInput\": {\n        prefix = Arr.of(command.name)\n        command = undefined\n        break\n      }\n      case \"Map\": {\n        command = command.command\n        break\n      }\n      case \"Subcommands\": {\n        command = command.parent\n        break\n      }\n    }\n  }\n  return prefix\n}\n\nconst getWizardPrefix = (\n  builtIn: BuiltInOptions.ShowWizard,\n  rootCommand: string,\n  commandLineArgs: ReadonlyArray<string>\n): ReadonlyArray<string> => {\n  const subcommands = InternalCommand.getSubcommands(builtIn.command)\n  const [parentArgs, childArgs] = Arr.span(\n    commandLineArgs,\n    (name) => !HashMap.has(subcommands, name)\n  )\n  const args = Arr.matchLeft(childArgs, {\n    onEmpty: () => Arr.filter(parentArgs, (arg) => arg !== \"--wizard\"),\n    onNonEmpty: (head) => Arr.append(parentArgs, head)\n  })\n  return Arr.appendAll(rootCommand.split(/\\s+/), args)\n}\n\nconst renderWizardArgs = (args: ReadonlyArray<string>) => {\n  const params = pipe(\n    Arr.filter(args, (param) => param.length > 0),\n    Arr.join(\" \")\n  )\n  const executeMsg = InternalSpan.text(\n    \"You may now execute your command directly with the following options and arguments:\"\n  )\n  return InternalHelpDoc.blocks([\n    InternalHelpDoc.p(InternalSpan.strong(InternalSpan.code(\"Wizard Mode Complete!\"))),\n    InternalHelpDoc.p(executeMsg),\n    InternalHelpDoc.p(InternalSpan.concat(\n      InternalSpan.text(\"    \"),\n      InternalSpan.highlight(params, Color.cyan)\n    ))\n  ])\n}\n\nconst isLogLevelArg = (arg?: string) => {\n  return arg && (arg === \"--log-level\" || arg.startsWith(\"--log-level=\"))\n}\n"
  },
  {
    "path": "packages/cli/src/internal/cliConfig.ts",
    "content": "import * as Context from \"effect/Context\"\nimport { dual } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport type * as CliConfig from \"../CliConfig.js\"\n\n/** @internal */\nexport const make = (params?: Partial<CliConfig.CliConfig>): CliConfig.CliConfig => ({\n  ...defaultConfig,\n  ...params\n})\n\n/** @internal */\nexport const Tag = Context.GenericTag<CliConfig.CliConfig>(\"@effect/cli/CliConfig\")\n\n/** @internal */\nexport const defaultConfig: CliConfig.CliConfig = {\n  isCaseSensitive: false,\n  autoCorrectLimit: 2,\n  finalCheckBuiltIn: false,\n  showAllNames: true,\n  showBuiltIns: true,\n  showTypes: true\n}\n\n/** @internal */\nexport const defaultLayer: Layer.Layer<CliConfig.CliConfig> = Layer.succeed(\n  Tag,\n  defaultConfig\n)\n\n/** @internal */\nexport const layer = (\n  config?: Partial<CliConfig.CliConfig>\n): Layer.Layer<CliConfig.CliConfig> => Layer.succeed(Tag, make(config))\n\n/** @internal */\nexport const normalizeCase = dual<\n  (text: string) => (self: CliConfig.CliConfig) => string,\n  (self: CliConfig.CliConfig, text: string) => string\n>(2, (self, text) => self.isCaseSensitive ? text : text.toLowerCase())\n"
  },
  {
    "path": "packages/cli/src/internal/command.ts",
    "content": "import type * as FileSystem from \"@effect/platform/FileSystem\"\nimport type * as Path from \"@effect/platform/Path\"\nimport type * as Terminal from \"@effect/platform/Terminal\"\nimport * as Arr from \"effect/Array\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Effectable from \"effect/Effectable\"\nimport { dual, identity } from \"effect/Function\"\nimport { globalValue } from \"effect/GlobalValue\"\nimport type * as HashMap from \"effect/HashMap\"\nimport type * as HashSet from \"effect/HashSet\"\nimport type * as Layer from \"effect/Layer\"\nimport type * as Option from \"effect/Option\"\nimport { pipeArguments } from \"effect/Pipeable\"\nimport type * as Types from \"effect/Types\"\nimport type * as Args from \"../Args.js\"\nimport type * as CliApp from \"../CliApp.js\"\nimport type * as CliConfig from \"../CliConfig.js\"\nimport type * as Command from \"../Command.js\"\nimport type * as Descriptor from \"../CommandDescriptor.js\"\nimport type * as HelpDoc from \"../HelpDoc.js\"\nimport type * as Options from \"../Options.js\"\nimport type * as Prompt from \"../Prompt.js\"\nimport type * as Usage from \"../Usage.js\"\nimport * as ValidationError from \"../ValidationError.js\"\nimport * as InternalArgs from \"./args.js\"\nimport * as InternalCliApp from \"./cliApp.js\"\nimport * as InternalDescriptor from \"./commandDescriptor.js\"\nimport * as InternalOptions from \"./options.js\"\n\nconst CommandSymbolKey = \"@effect/cli/Command\"\n\n/** @internal */\nexport const TypeId: Command.TypeId = Symbol.for(\n  CommandSymbolKey\n) as Command.TypeId\n\nconst parseConfig = (config: Command.Command.Config): Command.Command.ParsedConfig => {\n  const args: Array<Args.Args<any>> = []\n  let argsIndex = 0\n  const options: Array<Options.Options<any>> = []\n  let optionsIndex = 0\n\n  function parse(config: Command.Command.Config) {\n    const tree: Command.Command.ParsedConfigTree = {}\n    for (const key in config) {\n      tree[key] = parseValue(config[key])\n    }\n    return tree\n  }\n\n  function parseValue(\n    value:\n      | Args.Args<any>\n      | Options.Options<any>\n      | ReadonlyArray<Args.Args<any> | Options.Options<any> | Command.Command.Config>\n      | Command.Command.Config\n  ): Command.Command.ParsedConfigNode {\n    if (Arr.isArray(value)) {\n      return {\n        _tag: \"Array\",\n        children: Arr.map(value as Array<any>, parseValue)\n      }\n    } else if (InternalArgs.isArgs(value)) {\n      args.push(value)\n      return {\n        _tag: \"Args\",\n        index: argsIndex++\n      }\n    } else if (InternalOptions.isOptions(value)) {\n      options.push(value)\n      return {\n        _tag: \"Options\",\n        index: optionsIndex++\n      }\n    } else {\n      return {\n        _tag: \"ParsedConfig\",\n        tree: parse(value as any)\n      }\n    }\n  }\n\n  return {\n    args,\n    options,\n    tree: parse(config)\n  }\n}\n\nconst reconstructConfigTree = (\n  tree: Command.Command.ParsedConfigTree,\n  args: ReadonlyArray<any>,\n  options: ReadonlyArray<any>\n): Record<string, any> => {\n  const output: Record<string, any> = {}\n\n  for (const key in tree) {\n    output[key] = nodeValue(tree[key])\n  }\n\n  return output\n\n  function nodeValue(node: Command.Command.ParsedConfigNode): any {\n    if (node._tag === \"Args\") {\n      return args[node.index]\n    } else if (node._tag === \"Options\") {\n      return options[node.index]\n    } else if (node._tag === \"Array\") {\n      return Arr.map(node.children, nodeValue)\n    } else {\n      return reconstructConfigTree(node.tree, args, options)\n    }\n  }\n}\n\nconst Prototype = {\n  ...Effectable.CommitPrototype,\n  [TypeId]: TypeId,\n  commit(this: Command.Command<string, any, any, any>) {\n    return this.tag\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst registeredDescriptors = globalValue(\n  \"@effect/cli/Command/registeredDescriptors\",\n  () => new WeakMap<Context.Tag<any, any>, Descriptor.Command<any>>()\n)\n\nconst getDescriptor = <Name extends string, R, E, A>(self: Command.Command<Name, R, E, A>) =>\n  registeredDescriptors.get(self.tag) ?? self.descriptor\n\nconst makeProto = <Name extends string, R, E, A>(\n  descriptor: Descriptor.Command<A>,\n  handler: (_: A) => Effect.Effect<void, E, R>,\n  tag: Context.Tag<any, any>,\n  transform: Command.Command.Transform<R, E, A> = identity\n): Command.Command<Name, R, E, A> => {\n  const self = Object.create(Prototype)\n  self.descriptor = descriptor\n  self.handler = handler\n  self.transform = transform\n  self.tag = tag\n  return self\n}\n\nconst makeDerive = <Name extends string, R, E, A>(\n  self: Command.Command<Name, any, any, A>,\n  options: {\n    readonly descriptor?: Descriptor.Command<A>\n    readonly handler?: (_: A) => Effect.Effect<void, E, R>\n    readonly transform?: Command.Command.Transform<R, E, A>\n  }\n): Command.Command<Name, R, E, A> => {\n  const command = Object.create(Prototype)\n  command.descriptor = options.descriptor ?? self.descriptor\n  command.handler = options.handler ?? self.handler\n  command.transform = options.transform\n    ? ((effect: Effect.Effect<void, E, R>, opts: A) => options.transform!(self.transform(effect, opts), opts))\n    : self.transform\n  command.tag = self.tag\n  return command\n}\n\n/** @internal */\nexport const fromDescriptor = dual<\n  {\n    (): <A extends { readonly name: string }>(\n      command: Descriptor.Command<A>\n    ) => Command.Command<A[\"name\"], never, never, A>\n    <A extends { readonly name: string }, R, E>(\n      handler: (_: A) => Effect.Effect<void, E, R>\n    ): (command: Descriptor.Command<A>) => Command.Command<A[\"name\"], R, E, A>\n  },\n  {\n    <A extends { readonly name: string }>(\n      descriptor: Descriptor.Command<A>\n    ): Command.Command<A[\"name\"], never, never, A>\n    <A extends { readonly name: string }, R, E>(\n      descriptor: Descriptor.Command<A>,\n      handler: (_: A) => Effect.Effect<void, E, R>\n    ): Command.Command<A[\"name\"], R, E, A>\n  }\n>(\n  (args) => InternalDescriptor.isCommand(args[0]),\n  (descriptor: Descriptor.Command<any>, handler?: (_: any) => Effect.Effect<any, any, any>) => {\n    const self: Command.Command<any, any, any, any> = makeProto(\n      descriptor,\n      handler ??\n        ((_) => Effect.failSync(() => ValidationError.helpRequested(getDescriptor(self)))),\n      Context.GenericTag(\n        `@effect/cli/Command/(${Arr.fromIterable(InternalDescriptor.getNames(descriptor)).join(\"|\")})`\n      )\n    )\n    return self as any\n  }\n)\n\nconst makeDescriptor = <const Config extends Command.Command.Config>(\n  name: string,\n  config: Config\n): Descriptor.Command<Types.Simplify<Command.Command.ParseConfig<Config>>> => {\n  const { args, options, tree } = parseConfig(config)\n  return InternalDescriptor.map(\n    InternalDescriptor.make(name, InternalOptions.all(options), InternalArgs.all(args)),\n    ({ args, options }) => reconstructConfigTree(tree, args, options)\n  ) as any\n}\n\n/** @internal */\nexport const make: {\n  <Name extends string>(name: Name): Command.Command<\n    Name,\n    never,\n    never,\n    {}\n  >\n\n  <Name extends string, const Config extends Command.Command.Config>(\n    name: Name,\n    config: Config\n  ): Command.Command<\n    Name,\n    never,\n    never,\n    Types.Simplify<Command.Command.ParseConfig<Config>>\n  >\n\n  <Name extends string, const Config extends Command.Command.Config, R, E>(\n    name: Name,\n    config: Config,\n    handler: (_: Types.Simplify<Command.Command.ParseConfig<Config>>) => Effect.Effect<void, E, R>\n  ): Command.Command<\n    Name,\n    R,\n    E,\n    Types.Simplify<Command.Command.ParseConfig<Config>>\n  >\n} = (\n  name: string,\n  config: Command.Command.Config = {},\n  handler?: (_: any) => Effect.Effect<any, any, any>\n) => fromDescriptor(makeDescriptor(name, config) as any, handler as any) as any\n\n/** @internal */\nexport const getHelp = <Name extends string, R, E, A>(\n  self: Command.Command<Name, R, E, A>,\n  config: CliConfig.CliConfig\n): HelpDoc.HelpDoc => InternalDescriptor.getHelp(self.descriptor, config)\n\n/** @internal */\nexport const getNames = <Name extends string, R, E, A>(\n  self: Command.Command<Name, R, E, A>\n): HashSet.HashSet<string> => InternalDescriptor.getNames(self.descriptor)\n\n/** @internal */\nexport const getBashCompletions = <Name extends string, R, E, A>(\n  self: Command.Command<Name, R, E, A>,\n  programName: string\n): Effect.Effect<Array<string>> => InternalDescriptor.getBashCompletions(self.descriptor, programName)\n\n/** @internal */\nexport const getFishCompletions = <Name extends string, R, E, A>(\n  self: Command.Command<Name, R, E, A>,\n  programName: string\n): Effect.Effect<Array<string>> => InternalDescriptor.getFishCompletions(self.descriptor, programName)\n\n/** @internal */\nexport const getZshCompletions = <Name extends string, R, E, A>(\n  self: Command.Command<Name, R, E, A>,\n  programName: string\n): Effect.Effect<Array<string>> => InternalDescriptor.getZshCompletions(self.descriptor, programName)\n\n/** @internal */\nexport const getSubcommands = <Name extends string, R, E, A>(\n  self: Command.Command<Name, R, E, A>\n): HashMap.HashMap<string, Descriptor.Command<unknown>> => InternalDescriptor.getSubcommands(self.descriptor)\n\n/** @internal */\nexport const getUsage = <Name extends string, R, E, A>(\n  self: Command.Command<Name, R, E, A>\n): Usage.Usage => InternalDescriptor.getUsage(self.descriptor)\n\nconst mapDescriptor = dual<\n  <A>(f: (_: Descriptor.Command<A>) => Descriptor.Command<A>) => <Name extends string, R, E>(\n    self: Command.Command<Name, R, E, A>\n  ) => Command.Command<Name, R, E, A>,\n  <Name extends string, R, E, A>(\n    self: Command.Command<Name, R, E, A>,\n    f: (_: Descriptor.Command<A>) => Descriptor.Command<A>\n  ) => Command.Command<Name, R, E, A>\n>(2, (self, f) => makeDerive(self, { descriptor: f(self.descriptor) }))\n\n/** @internal */\nexport const prompt = <Name extends string, A, R, E>(\n  name: Name,\n  prompt: Prompt.Prompt<A>,\n  handler: (_: A) => Effect.Effect<void, E, R>\n) =>\n  makeProto(\n    InternalDescriptor.map(\n      InternalDescriptor.prompt(name, prompt),\n      (_) => _.value\n    ),\n    handler,\n    Context.GenericTag(`@effect/cli/Prompt/${name}`)\n  )\n\n/** @internal */\nexport const withHandler = dual<\n  <A, R, E>(\n    handler: (_: A) => Effect.Effect<void, E, R>\n  ) => <Name extends string, XR, XE>(\n    self: Command.Command<Name, XR, XE, A>\n  ) => Command.Command<Name, R, E, A>,\n  <Name extends string, XR, XE, A, R, E>(\n    self: Command.Command<Name, XR, XE, A>,\n    handler: (_: A) => Effect.Effect<void, E, R>\n  ) => Command.Command<Name, R, E, A>\n>(2, (self, handler) => makeDerive(self, { handler, transform: identity }))\n\n/** @internal */\nexport const transformHandler = dual<\n  <R, E, A, R2, E2>(\n    f: (effect: Effect.Effect<void, E, R>, config: A) => Effect.Effect<void, E2, R2>\n  ) => <Name extends string>(\n    self: Command.Command<Name, R, E, A>\n  ) => Command.Command<Name, R | R2, E | E2, A>,\n  <Name extends string, R, E, A, R2, E2>(\n    self: Command.Command<Name, R, E, A>,\n    f: (effect: Effect.Effect<void, E, R>, config: A) => Effect.Effect<void, E2, R2>\n  ) => Command.Command<Name, R | R2, E | E2, A>\n>(2, (self, f) => makeDerive(self, { transform: f }))\n\n/** @internal */\nexport const provide = dual<\n  <A, LR, LE, LA>(\n    layer: Layer.Layer<LA, LE, LR> | ((_: A) => Layer.Layer<LA, LE, LR>)\n  ) => <Name extends string, R, E>(\n    self: Command.Command<Name, R, E, A>\n  ) => Command.Command<Name, Exclude<R, LA> | LR, E | LE, A>,\n  <Name extends string, R, E, A, LR, LE, LA>(\n    self: Command.Command<Name, R, E, A>,\n    layer: Layer.Layer<LA, LE, LR> | ((_: A) => Layer.Layer<LA, LE, LR>)\n  ) => Command.Command<Name, Exclude<R, LA> | LR, E | LE, A>\n>(2, (self, layer) =>\n  makeDerive(self, {\n    transform: (effect, config) => Effect.provide(effect, typeof layer === \"function\" ? layer(config) : layer)\n  }))\n\n/** @internal */\nexport const provideEffect = dual<\n  <I, S, A, R2, E2>(\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<S, E2, R2> | ((_: A) => Effect.Effect<S, E2, R2>)\n  ) => <Name extends string, R, E>(\n    self: Command.Command<Name, R, E, A>\n  ) => Command.Command<Name, Exclude<R, I> | R2, E | E2, A>,\n  <Name extends string, R, E, A, I, S, R2, E2>(\n    self: Command.Command<Name, R, E, A>,\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<S, E2, R2> | ((_: A) => Effect.Effect<S, E2, R2>)\n  ) => Command.Command<Name, Exclude<R, I> | R2, E | E2, A>\n>(3, (self, tag, effect_) =>\n  makeDerive(self, {\n    transform: (self, config) => {\n      const effect = typeof effect_ === \"function\" ? effect_(config) : effect_\n      return Effect.provideServiceEffect(self, tag, effect)\n    }\n  }))\n\n/** @internal */\nexport const provideEffectDiscard = dual<\n  <A, R2, E2, _>(\n    effect: Effect.Effect<_, E2, R2> | ((_: A) => Effect.Effect<_, E2, R2>)\n  ) => <Name extends string, R, E>(\n    self: Command.Command<Name, R, E, A>\n  ) => Command.Command<Name, R | R2, E | E2, A>,\n  <Name extends string, R, E, A, R2, E2, _>(\n    self: Command.Command<Name, R, E, A>,\n    effect: Effect.Effect<_, E2, R2> | ((_: A) => Effect.Effect<_, E2, R2>)\n  ) => Command.Command<Name, R | R2, E | E2, A>\n>(2, (self, effect_) =>\n  makeDerive(self, {\n    transform: (self, config) => {\n      const effect = typeof effect_ === \"function\" ? effect_(config) : effect_\n      return Effect.zipRight(effect, self)\n    }\n  }))\n\n/** @internal */\nexport const provideSync = dual<\n  <I, S, A>(\n    tag: Context.Tag<I, S>,\n    service: S | ((_: A) => S)\n  ) => <Name extends string, R, E>(\n    self: Command.Command<Name, R, E, A>\n  ) => Command.Command<Name, Exclude<R, I>, E, A>,\n  <Name extends string, R, E, A, I, S>(\n    self: Command.Command<Name, R, E, A>,\n    tag: Context.Tag<I, S>,\n    service: S | ((_: A) => S)\n  ) => Command.Command<Name, Exclude<R, I>, E, A>\n>(3, (self, tag, f) =>\n  makeDerive(self, {\n    transform: (self, config) => {\n      const service = typeof f === \"function\" ? (f as any)(config) : f\n      return Effect.provideService(self, tag, service)\n    }\n  }))\n\n/** @internal */\nexport const withDescription = dual<\n  (\n    help: string | HelpDoc.HelpDoc\n  ) => <Name extends string, R, E, A>(\n    self: Command.Command<Name, R, E, A>\n  ) => Command.Command<Name, R, E, A>,\n  <Name extends string, R, E, A>(\n    self: Command.Command<Name, R, E, A>,\n    help: string | HelpDoc.HelpDoc\n  ) => Command.Command<Name, R, E, A>\n>(2, (self, help) => mapDescriptor(self, InternalDescriptor.withDescription(help)))\n\n/** @internal */\nexport const withSubcommands = dual<\n  <Subcommand extends Arr.NonEmptyReadonlyArray<Command.Command<any, any, any, any>>>(\n    subcommands: Subcommand\n  ) => <Name extends string, R, E, A>(self: Command.Command<Name, R, E, A>) => Command.Command<\n    Name,\n    | R\n    | Exclude<\n      Effect.Effect.Context<ReturnType<Subcommand[number][\"handler\"]>>,\n      Descriptor.Command<Name>\n    >,\n    E | Effect.Effect.Error<ReturnType<Subcommand[number][\"handler\"]>>,\n    Descriptor.Command.ComputeParsedType<\n      & A\n      & Readonly<\n        {\n          subcommand: Option.Option<\n            Descriptor.Command.GetParsedType<Subcommand[number][\"descriptor\"]>\n          >\n        }\n      >\n    >\n  >,\n  <\n    Name extends string,\n    R,\n    E,\n    A,\n    Subcommand extends Arr.NonEmptyReadonlyArray<Command.Command<any, any, any, any>>\n  >(\n    self: Command.Command<Name, R, E, A>,\n    subcommands: Subcommand\n  ) => Command.Command<\n    Name,\n    | R\n    | Exclude<\n      Effect.Effect.Context<ReturnType<Subcommand[number][\"handler\"]>>,\n      Descriptor.Command<Name>\n    >,\n    E | Effect.Effect.Error<ReturnType<Subcommand[number][\"handler\"]>>,\n    Descriptor.Command.ComputeParsedType<\n      & A\n      & Readonly<\n        {\n          subcommand: Option.Option<\n            Descriptor.Command.GetParsedType<Subcommand[number][\"descriptor\"]>\n          >\n        }\n      >\n    >\n  >\n>(2, (self, subcommands) => {\n  const command = InternalDescriptor.withSubcommands(\n    self.descriptor,\n    Arr.map(subcommands, (_) => [_.tag, _.descriptor])\n  )\n  const subcommandMap = Arr.reduce(\n    subcommands,\n    new Map<Context.Tag<any, any>, Command.Command<any, any, any, any>>(),\n    (handlers, subcommand) => {\n      handlers.set(subcommand.tag, subcommand)\n      registeredDescriptors.set(subcommand.tag, subcommand.descriptor)\n      return handlers\n    }\n  )\n  function handler(\n    args: {\n      readonly name: string\n      readonly subcommand: Option.Option<readonly [id: Context.Tag<any, any>, value: unknown]>\n    }\n  ) {\n    if (args.subcommand._tag === \"Some\") {\n      const [tag, value] = args.subcommand.value\n      const subcommand = subcommandMap.get(tag)!\n      const subcommandEffect = subcommand.transform(subcommand.handler(value), value)\n      return Effect.provideService(\n        subcommandEffect,\n        self.tag,\n        args as any\n      )\n    }\n    return self.handler(args as any)\n  }\n  return makeDerive(self as any, { descriptor: command as any, handler }) as any\n})\n\n/** @internal */\nexport const wizard = dual<\n  (\n    prefix: ReadonlyArray<string>,\n    config: CliConfig.CliConfig\n  ) => <Name extends string, R, E, A>(\n    self: Command.Command<Name, R, E, A>\n  ) => Effect.Effect<\n    Array<string>,\n    Terminal.QuitException | ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >,\n  <Name extends string, R, E, A>(\n    self: Command.Command<Name, R, E, A>,\n    prefix: ReadonlyArray<string>,\n    config: CliConfig.CliConfig\n  ) => Effect.Effect<\n    Array<string>,\n    Terminal.QuitException | ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >\n>(3, (self, prefix, config) => InternalDescriptor.wizard(self.descriptor, prefix, config))\n\n/** @internal */\nexport const run = dual<\n  (\n    config: Omit<CliApp.CliApp.ConstructorArgs<never>, \"command\">\n  ) => <Name extends string, R, E, A>(\n    self: Command.Command<Name, R, E, A>\n  ) => (\n    args: ReadonlyArray<string>\n  ) => Effect.Effect<void, E | ValidationError.ValidationError, R | CliApp.CliApp.Environment>,\n  <Name extends string, R, E, A>(\n    self: Command.Command<Name, R, E, A>,\n    config: Omit<CliApp.CliApp.ConstructorArgs<never>, \"command\">\n  ) => (\n    args: ReadonlyArray<string>\n  ) => Effect.Effect<void, E | ValidationError.ValidationError, R | CliApp.CliApp.Environment>\n>(2, (self, config) => {\n  const app = InternalCliApp.make({\n    ...config,\n    command: self.descriptor\n  })\n  registeredDescriptors.set(self.tag, self.descriptor)\n  const handler = (args: any) => self.transform(self.handler(args), args)\n  return (args) => InternalCliApp.run(app, args, handler)\n})\n"
  },
  {
    "path": "packages/cli/src/internal/commandDescriptor.ts",
    "content": "import type * as FileSystem from \"@effect/platform/FileSystem\"\nimport type * as Path from \"@effect/platform/Path\"\nimport type * as Terminal from \"@effect/platform/Terminal\"\nimport * as Color from \"@effect/printer-ansi/Color\"\nimport * as Arr from \"effect/Array\"\nimport * as Console from \"effect/Console\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { dual, pipe } from \"effect/Function\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as HashSet from \"effect/HashSet\"\nimport * as Option from \"effect/Option\"\nimport * as Order from \"effect/Order\"\nimport { pipeArguments } from \"effect/Pipeable\"\nimport * as Ref from \"effect/Ref\"\nimport * as SynchronizedRef from \"effect/SynchronizedRef\"\nimport type * as Args from \"../Args.js\"\nimport type * as CliConfig from \"../CliConfig.js\"\nimport type * as Descriptor from \"../CommandDescriptor.js\"\nimport type * as Directive from \"../CommandDirective.js\"\nimport * as HelpDoc from \"../HelpDoc.js\"\nimport type * as Span from \"../HelpDoc/Span.js\"\nimport * as Options from \"../Options.js\"\nimport type * as Prompt from \"../Prompt.js\"\nimport type * as Usage from \"../Usage.js\"\nimport type * as ValidationError from \"../ValidationError.js\"\nimport * as InternalArgs from \"./args.js\"\nimport * as InternalBuiltInOptions from \"./builtInOptions.js\"\nimport * as InternalCliConfig from \"./cliConfig.js\"\nimport * as InternalCommandDirective from \"./commandDirective.js\"\nimport * as InternalHelpDoc from \"./helpDoc.js\"\nimport * as InternalSpan from \"./helpDoc/span.js\"\nimport * as InternalOptions from \"./options.js\"\nimport * as InternalPrompt from \"./prompt.js\"\nimport * as InternalSelectPrompt from \"./prompt/select.js\"\nimport * as InternalUsage from \"./usage.js\"\nimport * as InternalValidationError from \"./validationError.js\"\n\nconst CommandDescriptorSymbolKey = \"@effect/cli/CommandDescriptor\"\n\n/** @internal */\nexport const TypeId: Descriptor.TypeId = Symbol.for(\n  CommandDescriptorSymbolKey\n) as Descriptor.TypeId\n\n/** @internal */\nexport type Op<Tag extends string, Body = {}> = Descriptor.Command<never> & Body & {\n  readonly _tag: Tag\n}\n\nconst proto = {\n  [TypeId]: {\n    _A: (_: never) => _\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport type Instruction =\n  | Standard\n  | GetUserInput\n  | Map\n  | Subcommands\n\n/** @internal */\nexport interface Standard extends\n  Op<\"Standard\", {\n    readonly name: string\n    readonly description: HelpDoc.HelpDoc\n    readonly options: Options.Options<unknown>\n    readonly args: Args.Args<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface GetUserInput extends\n  Op<\"GetUserInput\", {\n    readonly name: string\n    readonly description: HelpDoc.HelpDoc\n    readonly prompt: Prompt.Prompt<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Map extends\n  Op<\"Map\", {\n    readonly command: Instruction\n    readonly f: (value: unknown) => Effect.Effect<\n      unknown,\n      ValidationError.ValidationError,\n      FileSystem.FileSystem | Path.Path | Terminal.Terminal\n    >\n  }>\n{}\n\n/** @internal */\nexport interface Subcommands extends\n  Op<\"Subcommands\", {\n    readonly parent: Instruction\n    readonly children: Arr.NonEmptyReadonlyArray<Instruction>\n  }>\n{}\n\n// =============================================================================\n// Refinements\n// =============================================================================\n\n/** @internal */\nexport const isCommand = (u: unknown): u is Descriptor.Command<unknown> =>\n  typeof u === \"object\" && u != null && TypeId in u\n\n/** @internal */\nexport const isStandard = (self: Instruction): self is Standard => self._tag === \"Standard\"\n\n/** @internal */\nexport const isGetUserInput = (self: Instruction): self is GetUserInput => self._tag === \"GetUserInput\"\n\n/** @internal */\nexport const isMap = (self: Instruction): self is Map => self._tag === \"Map\"\n\n/** @internal */\nexport const isSubcommands = (self: Instruction): self is Subcommands => self._tag === \"Subcommands\"\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\n/** @internal */\nexport const make = <Name extends string, OptionsType = void, ArgsType = void>(\n  name: Name,\n  options: Options.Options<OptionsType> = InternalOptions.none as any,\n  args: Args.Args<ArgsType> = InternalArgs.none as any\n): Descriptor.Command<\n  Descriptor.Command.ParsedStandardCommand<Name, OptionsType, ArgsType>\n> => {\n  const op = Object.create(proto)\n  op._tag = \"Standard\"\n  op.name = name\n  op.description = InternalHelpDoc.empty\n  op.options = options\n  op.args = args\n  return op\n}\n\n/** @internal */\nexport const prompt = <Name extends string, A>(\n  name: Name,\n  prompt: Prompt.Prompt<A>\n): Descriptor.Command<Descriptor.Command.ParsedUserInputCommand<Name, A>> => {\n  const op = Object.create(proto)\n  op._tag = \"GetUserInput\"\n  op.name = name\n  op.description = InternalHelpDoc.empty\n  op.prompt = prompt\n  return op\n}\n\n// =============================================================================\n// Combinators\n// =============================================================================\n\n/** @internal */\nexport const getHelp = <A>(\n  self: Descriptor.Command<A>,\n  config: CliConfig.CliConfig\n): HelpDoc.HelpDoc => getHelpInternal(self as Instruction, config)\n\n/** @internal */\nexport const getNames = <A>(self: Descriptor.Command<A>): HashSet.HashSet<string> =>\n  HashSet.fromIterable(getNamesInternal(self as Instruction))\n\n/** @internal */\nexport const getBashCompletions = <A>(\n  self: Descriptor.Command<A>,\n  executable: string\n): Effect.Effect<Array<string>> => getBashCompletionsInternal(self as Instruction, executable)\n\n/** @internal */\nexport const getFishCompletions = <A>(\n  self: Descriptor.Command<A>,\n  executable: string\n): Effect.Effect<Array<string>> => getFishCompletionsInternal(self as Instruction, executable)\n\n/** @internal */\nexport const getZshCompletions = <A>(\n  self: Descriptor.Command<A>,\n  executable: string\n): Effect.Effect<Array<string>> => getZshCompletionsInternal(self as Instruction, executable)\n\n/** @internal */\nexport const getSubcommands = <A>(\n  self: Descriptor.Command<A>\n): HashMap.HashMap<string, Descriptor.Command<unknown>> =>\n  HashMap.fromIterable(getSubcommandsInternal(self as Instruction))\n\n/** @internal */\nexport const getUsage = <A>(self: Descriptor.Command<A>): Usage.Usage => getUsageInternal(self as Instruction)\n\n/** @internal */\nexport const map = dual<\n  <A, B>(f: (a: A) => B) => (self: Descriptor.Command<A>) => Descriptor.Command<B>,\n  <A, B>(self: Descriptor.Command<A>, f: (a: A) => B) => Descriptor.Command<B>\n>(2, (self, f) => mapEffect(self, (a) => Either.right(f(a))))\n\n/** @internal */\nexport const mapEffect = dual<\n  <A, B>(\n    f: (a: A) => Effect.Effect<\n      B,\n      ValidationError.ValidationError,\n      FileSystem.FileSystem | Path.Path | Terminal.Terminal\n    >\n  ) => (self: Descriptor.Command<A>) => Descriptor.Command<B>,\n  <A, B>(\n    self: Descriptor.Command<A>,\n    f: (a: A) => Effect.Effect<\n      B,\n      ValidationError.ValidationError,\n      FileSystem.FileSystem | Path.Path | Terminal.Terminal\n    >\n  ) => Descriptor.Command<B>\n>(2, (self, f) => {\n  const op = Object.create(proto)\n  op._tag = \"Map\"\n  op.command = self\n  op.f = f\n  return op\n})\n\n/** @internal */\nexport const parse = dual<\n  (\n    args: ReadonlyArray<string>,\n    config: CliConfig.CliConfig\n  ) => <A>(self: Descriptor.Command<A>) => Effect.Effect<\n    Directive.CommandDirective<A>,\n    ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >,\n  <A>(\n    self: Descriptor.Command<A>,\n    args: ReadonlyArray<string>,\n    config: CliConfig.CliConfig\n  ) => Effect.Effect<\n    Directive.CommandDirective<A>,\n    ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >\n>(3, (self, args, config) => parseInternal(self as Instruction, args, config))\n\n/** @internal */\nexport const withDescription = dual<\n  (\n    help: string | HelpDoc.HelpDoc\n  ) => <A>(self: Descriptor.Command<A>) => Descriptor.Command<A>,\n  <A>(\n    self: Descriptor.Command<A>,\n    help: string | HelpDoc.HelpDoc\n  ) => Descriptor.Command<A>\n>(2, (self, help) => withDescriptionInternal(self as Instruction, help))\n\n/** @internal */\nexport const withSubcommands = dual<\n  <\n    const Subcommands extends Arr.NonEmptyReadonlyArray<\n      readonly [id: unknown, command: Descriptor.Command<any>]\n    >\n  >(\n    subcommands: [...Subcommands]\n  ) => <A>(\n    self: Descriptor.Command<A>\n  ) => Descriptor.Command<\n    Descriptor.Command.ComputeParsedType<\n      & A\n      & Readonly<{ subcommand: Option.Option<Descriptor.Command.Subcommands<Subcommands>> }>\n    >\n  >,\n  <\n    A,\n    const Subcommands extends Arr.NonEmptyReadonlyArray<\n      readonly [id: unknown, command: Descriptor.Command<any>]\n    >\n  >(\n    self: Descriptor.Command<A>,\n    subcommands: [...Subcommands]\n  ) => Descriptor.Command<\n    Descriptor.Command.ComputeParsedType<\n      & A\n      & Readonly<{ subcommand: Option.Option<Descriptor.Command.Subcommands<Subcommands>> }>\n    >\n  >\n>(2, (self, subcommands) => {\n  const op = Object.create(proto)\n  op._tag = \"Subcommands\"\n  op.parent = self\n  op.children = Arr.map(subcommands, ([id, command]) => map(command, (a) => [id, a]))\n  return op\n})\n\n/** @internal */\nexport const wizard = dual<\n  (\n    prefix: ReadonlyArray<string>,\n    config: CliConfig.CliConfig\n  ) => <A>(self: Descriptor.Command<A>) => Effect.Effect<\n    Array<string>,\n    Terminal.QuitException | ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >,\n  <A>(\n    self: Descriptor.Command<A>,\n    prefix: ReadonlyArray<string>,\n    config: CliConfig.CliConfig\n  ) => Effect.Effect<\n    Array<string>,\n    Terminal.QuitException | ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >\n>(3, (self, prefix, config) => wizardInternal(self as Instruction, prefix, config))\n\n// =============================================================================\n// Internals\n// =============================================================================\n\nconst getHelpInternal = (self: Instruction, config: CliConfig.CliConfig): HelpDoc.HelpDoc => {\n  switch (self._tag) {\n    case \"Standard\": {\n      const header = InternalHelpDoc.isEmpty(self.description)\n        ? InternalHelpDoc.empty\n        : InternalHelpDoc.sequence(InternalHelpDoc.h1(\"DESCRIPTION\"), self.description)\n      const argsHelp = InternalArgs.getHelp(self.args)\n      const argsSection = InternalHelpDoc.isEmpty(argsHelp)\n        ? InternalHelpDoc.empty\n        : InternalHelpDoc.sequence(InternalHelpDoc.h1(\"ARGUMENTS\"), argsHelp)\n      const options = config.showBuiltIns\n        ? Options.all([self.options, InternalBuiltInOptions.builtIns])\n        : self.options\n      const optionsHelp = InternalOptions.getHelp(options)\n      const optionsSection = InternalHelpDoc.isEmpty(optionsHelp)\n        ? InternalHelpDoc.empty\n        : InternalHelpDoc.sequence(InternalHelpDoc.h1(\"OPTIONS\"), optionsHelp)\n      return InternalHelpDoc.sequence(header, InternalHelpDoc.sequence(argsSection, optionsSection))\n    }\n    case \"GetUserInput\": {\n      return InternalHelpDoc.isEmpty(self.description)\n        ? InternalHelpDoc.empty\n        : InternalHelpDoc.sequence(InternalHelpDoc.h1(\"DESCRIPTION\"), self.description)\n    }\n    case \"Map\": {\n      return getHelpInternal(self.command, config)\n    }\n    case \"Subcommands\": {\n      const getUsage = (\n        command: Instruction,\n        preceding: ReadonlyArray<Span.Span>\n      ): ReadonlyArray<[Span.Span, Span.Span]> => {\n        switch (command._tag) {\n          case \"Standard\":\n          case \"GetUserInput\": {\n            const usage = InternalHelpDoc.getSpan(InternalUsage.getHelp(getUsageInternal(command)))\n            const usages = Arr.append(preceding, usage)\n            const finalUsage = Arr.reduce(\n              usages,\n              InternalSpan.empty,\n              (acc, next) =>\n                InternalSpan.isText(acc) && acc.value === \"\"\n                  ? next\n                  : InternalSpan.isText(next) && next.value === \"\"\n                  ? acc\n                  : InternalSpan.spans([acc, InternalSpan.space, next])\n            )\n            const description = InternalHelpDoc.getSpan(command.description)\n            return Arr.of([finalUsage, description])\n          }\n          case \"Map\": {\n            return getUsage(command.command, preceding)\n          }\n          case \"Subcommands\": {\n            const parentUsage = getUsage(command.parent, preceding)\n            return Option.match(Arr.head(parentUsage), {\n              onNone: () =>\n                Arr.flatMap(\n                  command.children,\n                  (child) => getUsage(child, preceding)\n                ),\n              onSome: ([usage]) => {\n                const childrenUsage = Arr.flatMap(\n                  command.children,\n                  (child) => getUsage(child, Arr.append(preceding, usage))\n                )\n                return Arr.appendAll(parentUsage, childrenUsage)\n              }\n            })\n          }\n        }\n      }\n      const printSubcommands = (\n        subcommands: ReadonlyArray<[Span.Span, Span.Span]>\n      ): HelpDoc.HelpDoc => {\n        const maxUsageLength = Arr.reduceRight(\n          subcommands,\n          0,\n          (max, [usage]) => Math.max(InternalSpan.size(usage), max)\n        )\n        const documents = Arr.map(subcommands, ([usage, desc]) =>\n          InternalHelpDoc.p(\n            InternalSpan.spans([\n              usage,\n              InternalSpan.text(\" \".repeat(maxUsageLength - InternalSpan.size(usage) + 2)),\n              desc\n            ])\n          ))\n        if (Arr.isNonEmptyReadonlyArray(documents)) {\n          return InternalHelpDoc.enumeration(documents)\n        }\n        throw new Error(\"[BUG]: Subcommands.usage - received empty list of subcommands to print\")\n      }\n      return InternalHelpDoc.sequence(\n        getHelpInternal(self.parent, config),\n        InternalHelpDoc.sequence(\n          InternalHelpDoc.h1(\"COMMANDS\"),\n          printSubcommands(Arr.flatMap(\n            self.children,\n            (child) => getUsage(child, Arr.empty())\n          ))\n        )\n      )\n    }\n  }\n}\n\nconst getNamesInternal = (self: Instruction): Array<string> => {\n  switch (self._tag) {\n    case \"Standard\":\n    case \"GetUserInput\": {\n      return Arr.of(self.name)\n    }\n    case \"Map\": {\n      return getNamesInternal(self.command)\n    }\n    case \"Subcommands\": {\n      return getNamesInternal(self.parent)\n    }\n  }\n}\n\nconst getSubcommandsInternal = (\n  self: Instruction\n): Array<[string, GetUserInput | Standard]> => {\n  const loop = (\n    self: Instruction,\n    isSubcommand: boolean\n  ): Array<[string, GetUserInput | Standard]> => {\n    switch (self._tag) {\n      case \"Standard\":\n      case \"GetUserInput\": {\n        return Arr.of([self.name, self])\n      }\n      case \"Map\": {\n        return loop(self.command, isSubcommand)\n      }\n      case \"Subcommands\": {\n        // Ensure that we only traverse the subcommands one level deep from the\n        // parent command\n        return isSubcommand\n          ? loop(self.parent, false)\n          : Arr.flatMap(self.children, (child) => loop(child, true))\n      }\n    }\n  }\n  return loop(self, false)\n}\n\nconst getUsageInternal = (self: Instruction): Usage.Usage => {\n  switch (self._tag) {\n    case \"Standard\": {\n      return InternalUsage.concat(\n        InternalUsage.named(Arr.of(self.name), Option.none()),\n        InternalUsage.concat(\n          InternalOptions.getUsage(self.options),\n          InternalArgs.getUsage(self.args)\n        )\n      )\n    }\n    case \"GetUserInput\": {\n      return InternalUsage.named(Arr.of(self.name), Option.none())\n    }\n    case \"Map\": {\n      return getUsageInternal(self.command)\n    }\n    case \"Subcommands\": {\n      return InternalUsage.concat(\n        getUsageInternal(self.parent),\n        InternalUsage.mixed\n      )\n    }\n  }\n}\n\nconst parseInternal = (\n  self: Instruction,\n  args: ReadonlyArray<string>,\n  config: CliConfig.CliConfig\n): Effect.Effect<\n  Directive.CommandDirective<any>,\n  ValidationError.ValidationError,\n  FileSystem.FileSystem | Path.Path | Terminal.Terminal\n> => {\n  const parseCommandLine = (\n    self: Standard | GetUserInput,\n    args: ReadonlyArray<string>\n  ): Effect.Effect<Array<string>, ValidationError.ValidationError> =>\n    Arr.matchLeft(args, {\n      onEmpty: () => {\n        const error = InternalHelpDoc.p(`Missing command name: '${self.name}'`)\n        return Effect.fail(InternalValidationError.commandMismatch(error))\n      },\n      onNonEmpty: (head, tail) => {\n        const normalizedArgv0 = InternalCliConfig.normalizeCase(config, head)\n        const normalizedCommandName = InternalCliConfig.normalizeCase(config, self.name)\n        return Effect.succeed(tail).pipe(\n          Effect.when(() => normalizedArgv0 === normalizedCommandName),\n          Effect.flatten,\n          Effect.catchTag(\"NoSuchElementException\", () => {\n            const error = InternalHelpDoc.p(`Missing command name: '${self.name}'`)\n            return Effect.fail(InternalValidationError.commandMismatch(error))\n          })\n        )\n      }\n    })\n  switch (self._tag) {\n    case \"Standard\": {\n      const parseBuiltInArgs = (\n        args: ReadonlyArray<string>\n      ): Effect.Effect<\n        Directive.CommandDirective<never>,\n        ValidationError.ValidationError,\n        FileSystem.FileSystem | Path.Path | Terminal.Terminal\n      > =>\n        Arr.matchLeft(args, {\n          onEmpty: () => {\n            const error = InternalHelpDoc.p(`Missing command name: '${self.name}'`)\n            return Effect.fail(InternalValidationError.commandMismatch(error))\n          },\n          onNonEmpty: (argv0) => {\n            const normalizedArgv0 = InternalCliConfig.normalizeCase(config, argv0)\n            const normalizedCommandName = InternalCliConfig.normalizeCase(config, self.name)\n            if (normalizedArgv0 === normalizedCommandName) {\n              const help = getHelpInternal(self, config)\n              const usage = getUsageInternal(self)\n              const options = InternalBuiltInOptions.builtInOptions(self, usage, help)\n              const argsWithoutCommand = Arr.drop(args, 1)\n              return InternalOptions.processCommandLine(options, argsWithoutCommand, config)\n                .pipe(\n                  Effect.flatMap((tuple) => tuple[2]),\n                  Effect.catchTag(\"NoSuchElementException\", () => {\n                    const error = InternalHelpDoc.p(\"No built-in option was matched\")\n                    return Effect.fail(InternalValidationError.noBuiltInMatch(error))\n                  }),\n                  Effect.map(InternalCommandDirective.builtIn)\n                )\n            }\n            const error = InternalHelpDoc.p(`Missing command name: '${self.name}'`)\n            return Effect.fail(InternalValidationError.commandMismatch(error))\n          }\n        })\n      const parseUserDefinedArgs = (\n        args: ReadonlyArray<string>\n      ): Effect.Effect<\n        Directive.CommandDirective<unknown>,\n        ValidationError.ValidationError,\n        FileSystem.FileSystem | Path.Path | Terminal.Terminal\n      > =>\n        parseCommandLine(self, args).pipe(Effect.flatMap((commandOptionsAndArgs) => {\n          const [optionsAndArgs, forcedCommandArgs] = splitForcedArgs(commandOptionsAndArgs)\n          return InternalOptions.processCommandLine(self.options, optionsAndArgs, config).pipe(\n            Effect.flatMap(([error, commandArgs, optionsType]) =>\n              InternalArgs.validate(\n                self.args,\n                Arr.appendAll(commandArgs, forcedCommandArgs),\n                config\n              ).pipe(\n                Effect.catchAll((e) =>\n                  Option.match(error, {\n                    onNone: () => Effect.fail(e),\n                    onSome: (err) => Effect.fail(err)\n                  })\n                ),\n                Effect.map(([argsLeftover, argsType]) =>\n                  InternalCommandDirective.userDefined(argsLeftover, {\n                    name: self.name,\n                    options: optionsType,\n                    args: argsType\n                  })\n                )\n              )\n            )\n          )\n        }))\n      const exhaustiveSearch = (\n        args: ReadonlyArray<string>\n      ): Effect.Effect<\n        Directive.CommandDirective<never>,\n        ValidationError.ValidationError,\n        FileSystem.FileSystem | Path.Path | Terminal.Terminal\n      > => {\n        if (Arr.contains(args, \"--help\") || Arr.contains(args, \"-h\")) {\n          return parseBuiltInArgs(Arr.make(self.name, \"--help\"))\n        }\n        if (Arr.contains(args, \"--wizard\")) {\n          return parseBuiltInArgs(Arr.make(self.name, \"--wizard\"))\n        }\n        if (Arr.contains(args, \"--version\")) {\n          return parseBuiltInArgs(Arr.make(self.name, \"--version\"))\n        }\n        const error = InternalHelpDoc.p(`Missing command name: '${self.name}'`)\n        return Effect.fail(InternalValidationError.commandMismatch(error))\n      }\n      return parseBuiltInArgs(args).pipe(\n        Effect.orElse(() => parseUserDefinedArgs(args)),\n        Effect.catchSome((e) => {\n          if (InternalValidationError.isValidationError(e)) {\n            if (config.finalCheckBuiltIn) {\n              return Option.some(\n                exhaustiveSearch(args).pipe(\n                  Effect.catchSome((_) =>\n                    InternalValidationError.isValidationError(_)\n                      ? Option.some(Effect.fail(e))\n                      : Option.none()\n                  )\n                )\n              )\n            }\n            return Option.some(Effect.fail(e))\n          }\n          return Option.none()\n        })\n      )\n    }\n    case \"GetUserInput\": {\n      return parseCommandLine(self, args).pipe(\n        Effect.zipRight(InternalPrompt.run(self.prompt)),\n        Effect.catchTag(\"QuitException\", (e) => Effect.die(e)),\n        Effect.map((value) =>\n          InternalCommandDirective.userDefined(Arr.drop(args, 1), {\n            name: self.name,\n            value\n          })\n        )\n      )\n    }\n    case \"Map\": {\n      return parseInternal(self.command, args, config).pipe(\n        Effect.flatMap((directive) => {\n          if (InternalCommandDirective.isUserDefined(directive)) {\n            return self.f(directive.value).pipe(Effect.map((value) =>\n              InternalCommandDirective.userDefined(\n                directive.leftover,\n                value\n              )\n            ))\n          }\n          return Effect.succeed(directive)\n        })\n      )\n    }\n    case \"Subcommands\": {\n      const names = getNamesInternal(self)\n      const subcommands = getSubcommandsInternal(self)\n      const [parentArgs, childArgs] = Arr.span(\n        args,\n        (arg) => !Arr.some(subcommands, ([name]) => name === arg)\n      )\n      const parseChildrenWith = (argsForChildren: ReadonlyArray<string>) =>\n        Effect.suspend(() => {\n          const iterator = self.children[Symbol.iterator]()\n          const loop = (\n            next: Instruction\n          ): Effect.Effect<\n            Directive.CommandDirective<any>,\n            ValidationError.ValidationError,\n            FileSystem.FileSystem | Path.Path | Terminal.Terminal\n          > => {\n            return parseInternal(next, argsForChildren, config).pipe(\n              Effect.catchIf(InternalValidationError.isCommandMismatch, (e) => {\n                const next = iterator.next()\n                return next.done ? Effect.fail(e) : loop(next.value)\n              })\n            )\n          }\n          return loop(iterator.next().value!)\n        })\n      const parseChildren = parseChildrenWith(childArgs)\n      const helpDirectiveForParent = Effect.sync(() => {\n        return InternalCommandDirective.builtIn(InternalBuiltInOptions.showHelp(\n          getUsageInternal(self),\n          getHelpInternal(self, config)\n        ))\n      })\n      const helpDirectiveForChild = parseChildren.pipe(\n        Effect.flatMap((directive) => {\n          if (\n            InternalCommandDirective.isBuiltIn(directive) &&\n            InternalBuiltInOptions.isShowHelp(directive.option)\n          ) {\n            const parentName = Option.getOrElse(Arr.head(names), () => \"\")\n            const newDirective = InternalCommandDirective.builtIn(InternalBuiltInOptions.showHelp(\n              InternalUsage.concat(\n                InternalUsage.named(Arr.of(parentName), Option.none()),\n                directive.option.usage\n              ),\n              directive.option.helpDoc\n            ))\n            return Effect.succeed(newDirective)\n          }\n          return Effect.fail(InternalValidationError.invalidArgument(InternalHelpDoc.empty))\n        })\n      )\n      const wizardDirectiveForParent = Effect.sync(() =>\n        InternalCommandDirective.builtIn(InternalBuiltInOptions.showWizard(self))\n      )\n      const wizardDirectiveForChild = parseChildren.pipe(\n        Effect.flatMap((directive) => {\n          if (\n            InternalCommandDirective.isBuiltIn(directive) &&\n            InternalBuiltInOptions.isShowWizard(directive.option)\n          ) {\n            return Effect.succeed(directive)\n          }\n          return Effect.fail(InternalValidationError.invalidArgument(InternalHelpDoc.empty))\n        })\n      )\n      return Effect.suspend(() =>\n        parseInternal(self.parent, parentArgs, config).pipe(\n          Effect.flatMap((directive) => {\n            switch (directive._tag) {\n              case \"BuiltIn\": {\n                if (InternalBuiltInOptions.isShowHelp(directive.option)) {\n                  // We do not want to display the child help docs if there are\n                  // no arguments indicating the CLI command was for the child\n                  return Arr.isNonEmptyReadonlyArray(childArgs)\n                    ? Effect.orElse(helpDirectiveForChild, () => helpDirectiveForParent)\n                    : helpDirectiveForParent\n                }\n                if (InternalBuiltInOptions.isShowWizard(directive.option)) {\n                  return Effect.orElse(wizardDirectiveForChild, () => wizardDirectiveForParent)\n                }\n                return Effect.succeed(directive)\n              }\n              case \"UserDefined\": {\n                const args = Arr.appendAll(directive.leftover, childArgs)\n                if (Arr.isNonEmptyReadonlyArray(args)) {\n                  return parseChildrenWith(args).pipe(\n                    Effect.flatMap((childDirective) => {\n                      if (!InternalCommandDirective.isUserDefined(childDirective)) {\n                        return Effect.succeed(childDirective)\n                      }\n                      const childLeftover = childDirective.leftover\n                      if (Arr.isEmptyReadonlyArray(childLeftover)) {\n                        return Effect.succeed(InternalCommandDirective.userDefined(childLeftover, {\n                          ...directive.value as any,\n                          subcommand: Option.some(childDirective.value)\n                        }))\n                      }\n                      const parentArgsWithLeftover = Arr.appendAll(parentArgs, childLeftover)\n                      return parseInternal(self.parent, parentArgsWithLeftover, config).pipe(\n                        Effect.flatMap((reParsedParentDirective) => {\n                          if (!InternalCommandDirective.isUserDefined(reParsedParentDirective)) {\n                            return Effect.succeed(InternalCommandDirective.userDefined(childLeftover, {\n                              ...directive.value as any,\n                              subcommand: Option.some(childDirective.value)\n                            }))\n                          }\n                          return Effect.succeed(InternalCommandDirective.userDefined(\n                            reParsedParentDirective.leftover as Array<string>,\n                            {\n                              ...reParsedParentDirective.value as any,\n                              subcommand: Option.some(childDirective.value)\n                            }\n                          ))\n                        }),\n                        Effect.catchAll(() =>\n                          Effect.succeed(InternalCommandDirective.userDefined(childLeftover, {\n                            ...directive.value as any,\n                            subcommand: Option.some(childDirective.value)\n                          }))\n                        )\n                      )\n                    }),\n                    Effect.catchAll((err) => {\n                      if (InternalValidationError.isCommandMismatch(err)) {\n                        const parentName = Option.getOrElse(Arr.head(names), () => \"\")\n                        const childNames = Arr.map(subcommands, ([name]) => `'${name}'`)\n                        const oneOf = childNames.length === 1 ? \"\" : \" one of\"\n                        const error = InternalHelpDoc.p(\n                          `Invalid subcommand for ${parentName} - use${oneOf} ${Arr.join(childNames, \", \")}`\n                        )\n                        return Effect.fail(InternalValidationError.commandMismatch(error))\n                      }\n                      return Effect.fail(err)\n                    })\n                  )\n                }\n                return Effect.succeed(InternalCommandDirective.userDefined(directive.leftover, {\n                  ...directive.value as any,\n                  subcommand: Option.none()\n                }))\n              }\n            }\n          }),\n          Effect.catchSome(() =>\n            Arr.isEmptyReadonlyArray(args)\n              ? Option.some(helpDirectiveForParent) :\n              Option.none()\n          )\n        )\n      )\n    }\n  }\n}\n\nconst splitForcedArgs = (\n  args: ReadonlyArray<string>\n): [Array<string>, Array<string>] => {\n  const [remainingArgs, forcedArgs] = Arr.span(args, (str) => str !== \"--\")\n  return [remainingArgs, Arr.drop(forcedArgs, 1)]\n}\n\nconst withDescriptionInternal = (\n  self: Instruction,\n  description: string | HelpDoc.HelpDoc\n): Descriptor.Command<any> => {\n  switch (self._tag) {\n    case \"Standard\": {\n      const helpDoc = typeof description === \"string\" ? HelpDoc.p(description) : description\n      const op = Object.create(proto)\n      op._tag = \"Standard\"\n      op.name = self.name\n      op.description = helpDoc\n      op.options = self.options\n      op.args = self.args\n      return op\n    }\n    case \"GetUserInput\": {\n      const helpDoc = typeof description === \"string\" ? HelpDoc.p(description) : description\n      const op = Object.create(proto)\n      op._tag = \"GetUserInput\"\n      op.name = self.name\n      op.description = helpDoc\n      op.prompt = self.prompt\n      return op\n    }\n    case \"Map\": {\n      return mapEffect(withDescriptionInternal(self.command, description), self.f)\n    }\n    case \"Subcommands\": {\n      const op = Object.create(proto)\n      op._tag = \"Subcommands\"\n      op.parent = withDescriptionInternal(self.parent, description)\n      op.children = self.children.slice()\n      return op\n    }\n  }\n}\n\nconst argsWizardHeader = InternalSpan.code(\"Args Wizard - \")\nconst optionsWizardHeader = InternalSpan.code(\"Options Wizard - \")\n\nconst wizardInternal = (\n  self: Instruction,\n  prefix: ReadonlyArray<string>,\n  config: CliConfig.CliConfig\n): Effect.Effect<\n  Array<string>,\n  Terminal.QuitException | ValidationError.ValidationError,\n  FileSystem.FileSystem | Path.Path | Terminal.Terminal\n> => {\n  const loop = (\n    self: Instruction,\n    commandLineRef: Ref.Ref<ReadonlyArray<string>>\n  ): Effect.Effect<\n    ReadonlyArray<string>,\n    Terminal.QuitException | ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  > => {\n    switch (self._tag) {\n      case \"GetUserInput\":\n      case \"Standard\": {\n        return Effect.gen(function*() {\n          const logCurrentCommand = Ref.get(commandLineRef).pipe(Effect.flatMap((commandLine) => {\n            const currentCommand = InternalHelpDoc.p(pipe(\n              InternalSpan.strong(InternalSpan.highlight(\"COMMAND:\", Color.cyan)),\n              InternalSpan.concat(InternalSpan.space),\n              InternalSpan.concat(InternalSpan.highlight(\n                Arr.join(commandLine, \" \"),\n                Color.magenta\n              ))\n            ))\n            return Console.log(InternalHelpDoc.toAnsiText(currentCommand))\n          }))\n          if (isStandard(self)) {\n            // Log the current command line arguments\n            yield* logCurrentCommand\n            const commandName = InternalSpan.highlight(self.name, Color.magenta)\n            // If the command has options, run the wizard for them\n            if (!InternalOptions.isEmpty(self.options as InternalOptions.Instruction)) {\n              const message = InternalHelpDoc.p(\n                InternalSpan.concat(optionsWizardHeader, commandName)\n              )\n              yield* Console.log(InternalHelpDoc.toAnsiText(message))\n              const options = yield* InternalOptions.wizard(self.options, config)\n              yield* Ref.updateAndGet(commandLineRef, Arr.appendAll(options))\n              yield* logCurrentCommand\n            }\n            // If the command has args, run the wizard for them\n            if (!InternalArgs.isEmpty(self.args as InternalArgs.Instruction)) {\n              const message = InternalHelpDoc.p(\n                InternalSpan.concat(argsWizardHeader, commandName)\n              )\n              yield* Console.log(InternalHelpDoc.toAnsiText(message))\n              const options = yield* InternalArgs.wizard(self.args, config)\n              yield* Ref.updateAndGet(commandLineRef, Arr.appendAll(options))\n              yield* logCurrentCommand\n            }\n          }\n          return yield* Ref.get(commandLineRef)\n        })\n      }\n      case \"Map\": {\n        return loop(self.command, commandLineRef)\n      }\n      case \"Subcommands\": {\n        const description = InternalHelpDoc.p(\"Select which command you would like to execute\")\n        const message = InternalHelpDoc.toAnsiText(description).trimEnd()\n        const makeChoice = (title: string, index: number) => ({\n          title,\n          value: [title, index] as const\n        })\n        const choices = pipe(\n          getSubcommandsInternal(self),\n          Arr.map(([name], index) => makeChoice(name, index))\n        )\n        return loop(self.parent, commandLineRef).pipe(\n          Effect.zipRight(\n            InternalSelectPrompt.select({ message, choices }).pipe(\n              Effect.tap(([name]) => Ref.update(commandLineRef, Arr.append(name))),\n              Effect.zipLeft(Console.log()),\n              Effect.flatMap(([, nextIndex]) => loop(self.children[nextIndex], commandLineRef))\n            )\n          )\n        )\n      }\n    }\n  }\n  return Ref.make(prefix).pipe(\n    Effect.flatMap((commandLineRef) =>\n      loop(self, commandLineRef).pipe(\n        Effect.zipRight(Ref.get(commandLineRef) as Effect.Effect<Array<string>>)\n      )\n    )\n  )\n}\n\n// =============================================================================\n// Completion Internals\n// =============================================================================\n\nconst getShortDescription = (self: Instruction): string => {\n  switch (self._tag) {\n    case \"Standard\": {\n      return InternalSpan.getText(InternalHelpDoc.getSpan(self.description))\n    }\n    case \"GetUserInput\": {\n      return InternalSpan.getText(InternalHelpDoc.getSpan(self.description))\n    }\n    case \"Map\": {\n      return getShortDescription(self.command)\n    }\n    case \"Subcommands\": {\n      return \"\"\n    }\n  }\n}\n\ninterface CommandInfo {\n  readonly command: Standard | GetUserInput\n  readonly parentCommands: ReadonlyArray<string>\n  readonly subcommands: ReadonlyArray<[string, Standard | GetUserInput]>\n  readonly level: number\n}\n\n/**\n * Allows for linear traversal of a `Command` data structure, accumulating state\n * based on information acquired from the command.\n */\nconst traverseCommand = <S>(\n  self: Instruction,\n  initialState: S,\n  f: (state: S, info: CommandInfo) => Effect.Effect<S>\n): Effect.Effect<S> =>\n  SynchronizedRef.make(initialState).pipe(Effect.flatMap((ref) => {\n    const loop = (\n      self: Instruction,\n      parentCommands: ReadonlyArray<string>,\n      subcommands: ReadonlyArray<[string, Standard | GetUserInput]>,\n      level: number\n    ): Effect.Effect<void, never, never> => {\n      switch (self._tag) {\n        case \"Standard\": {\n          const info: CommandInfo = {\n            command: self,\n            parentCommands,\n            subcommands,\n            level\n          }\n          return SynchronizedRef.updateEffect(ref, (state) => f(state, info))\n        }\n        case \"GetUserInput\": {\n          const info: CommandInfo = {\n            command: self,\n            parentCommands,\n            subcommands,\n            level\n          }\n          return SynchronizedRef.updateEffect(ref, (state) => f(state, info))\n        }\n        case \"Map\": {\n          return loop(self.command, parentCommands, subcommands, level)\n        }\n        case \"Subcommands\": {\n          const parentNames = getNamesInternal(self.parent)\n          const nextSubcommands = getSubcommandsInternal(self)\n          const nextParentCommands = Arr.appendAll(parentCommands, parentNames)\n          // Traverse the parent command using old parent names and next subcommands\n          return loop(self.parent, parentCommands, nextSubcommands, level).pipe(\n            Effect.zipRight(Effect.forEach(self.children, (child) =>\n              // Traverse the child command using next parent names and old subcommands\n              loop(child, nextParentCommands, subcommands, level + 1)))\n          )\n        }\n      }\n    }\n    return Effect.suspend(() => loop(self, Arr.empty(), Arr.empty(), 0)).pipe(\n      Effect.zipRight(SynchronizedRef.get(ref))\n    )\n  }))\n\nconst indentAll = dual<\n  (indent: number) => (self: ReadonlyArray<string>) => Array<string>,\n  (self: ReadonlyArray<string>, indent: number) => Array<string>\n>(2, (self: ReadonlyArray<string>, indent: number): Array<string> => {\n  const indentation = Arr.allocate(indent + 1).join(\" \")\n  return Arr.map(self, (line) => `${indentation}${line}`)\n})\n\nconst getBashCompletionsInternal = (\n  self: Instruction,\n  executable: string\n): Effect.Effect<Array<string>> =>\n  traverseCommand(\n    self,\n    Arr.empty<[ReadonlyArray<string>, ReadonlyArray<string>]>(),\n    (state, info) => {\n      const options = isStandard(info.command)\n        ? Options.all([info.command.options, InternalBuiltInOptions.builtIns])\n        : InternalBuiltInOptions.builtIns\n      const optionNames = InternalOptions.getNames(options as InternalOptions.Instruction)\n      const optionCases = isStandard(info.command)\n        ? InternalOptions.getBashCompletions(info.command.options as InternalOptions.Instruction)\n        : Arr.empty()\n      const subcommandNames = pipe(\n        info.subcommands,\n        Arr.map(([name]) => name),\n        Arr.sort(Order.string)\n      )\n      const wordList = Arr.appendAll(optionNames, subcommandNames)\n      const preformatted = Arr.isEmptyReadonlyArray(info.parentCommands)\n        ? Arr.of(info.command.name)\n        : pipe(\n          info.parentCommands,\n          Arr.append(info.command.name),\n          Arr.map((command) => command.replace(\"-\", \"__\"))\n        )\n      const caseName = Arr.join(preformatted, \",\")\n      const funcName = Arr.join(preformatted, \"__\")\n      const funcLines = Arr.isEmptyReadonlyArray(info.parentCommands)\n        ? Arr.empty()\n        : [\n          `${caseName})`,\n          `    cmd=\"${funcName}\"`,\n          \"    ;;\"\n        ]\n      const cmdLines = [\n        `${funcName})`,\n        `    opts=\"${Arr.join(wordList, \" \")}\"`,\n        `    if [[ \\${cur} == -* || \\${COMP_CWORD} -eq ${info.level + 1} ]] ; then`,\n        \"        COMPREPLY=( $(compgen -W \\\"${opts}\\\" -- \\\"${cur}\\\") )\",\n        \"        return 0\",\n        \"    fi\",\n        \"    case \\\"${prev}\\\" in\",\n        ...indentAll(optionCases, 8),\n        \"    *)\",\n        \"        COMPREPLY=()\",\n        \"        ;;\",\n        \"    esac\",\n        \"    COMPREPLY=( $(compgen -W \\\"${opts}\\\" -- \\\"${cur}\\\") )\",\n        \"    return 0\",\n        \"    ;;\"\n      ]\n      const lines = Arr.append(\n        state,\n        [funcLines, cmdLines] as [ReadonlyArray<string>, ReadonlyArray<string>]\n      )\n      return Effect.succeed(lines)\n    }\n  ).pipe(Effect.map((lines) => {\n    const rootCommand = Arr.unsafeGet(getNamesInternal(self), 0)\n    const scriptName = `_${rootCommand}_bash_completions`\n    const funcCases = Arr.flatMap(lines, ([funcLines]) => funcLines)\n    const cmdCases = Arr.flatMap(lines, ([, cmdLines]) => cmdLines)\n    return [\n      `function ${scriptName}() {`,\n      \"    local i cur prev opts cmd\",\n      \"    COMPREPLY=()\",\n      \"    cur=\\\"${COMP_WORDS[COMP_CWORD]}\\\"\",\n      \"    prev=\\\"${COMP_WORDS[COMP_CWORD-1]}\\\"\",\n      \"    cmd=\\\"\\\"\",\n      \"    opts=\\\"\\\"\",\n      \"    for i in \\\"${COMP_WORDS[@]}\\\"; do\",\n      \"        case \\\"${cmd},${i}\\\" in\",\n      \"            \\\",$1\\\")\",\n      `                cmd=\"${executable}\"`,\n      \"                ;;\",\n      ...indentAll(funcCases, 12),\n      \"            *)\",\n      \"                ;;\",\n      \"        esac\",\n      \"    done\",\n      \"    case \\\"${cmd}\\\" in\",\n      ...indentAll(cmdCases, 8),\n      \"    esac\",\n      \"}\",\n      `complete -F ${scriptName} -o nosort -o bashdefault -o default ${rootCommand}`\n    ]\n  }))\n\nconst getFishCompletionsInternal = (\n  self: Instruction,\n  executable: string\n): Effect.Effect<Array<string>> =>\n  traverseCommand(self, Arr.empty(), (state, info) => {\n    const baseTemplate = Arr.make(\"complete\", \"-c\", executable)\n    const options = isStandard(info.command)\n      ? InternalOptions.all([InternalBuiltInOptions.builtIns, info.command.options])\n      : InternalBuiltInOptions.builtIns\n    const optionsCompletions = InternalOptions.getFishCompletions(\n      options as InternalOptions.Instruction\n    )\n    const argsCompletions = isStandard(info.command)\n      ? InternalArgs.getFishCompletions(info.command.args as InternalArgs.Instruction)\n      : Arr.empty()\n    const rootCompletions = (conditionals: ReadonlyArray<string>) =>\n      pipe(\n        Arr.map(optionsCompletions, (option) =>\n          pipe(\n            baseTemplate,\n            Arr.appendAll(conditionals),\n            Arr.append(option),\n            Arr.join(\" \")\n          )),\n        Arr.appendAll(\n          Arr.map(argsCompletions, (option) =>\n            pipe(\n              baseTemplate,\n              Arr.appendAll(conditionals),\n              Arr.append(option),\n              Arr.join(\" \")\n            ))\n        )\n      )\n    const subcommandCompletions = (conditionals: ReadonlyArray<string>) =>\n      Arr.map(info.subcommands, ([name, subcommand]) => {\n        const description = getShortDescription(subcommand)\n        return pipe(\n          baseTemplate,\n          Arr.appendAll(conditionals),\n          Arr.appendAll(Arr.make(\"-f\", \"-a\", `\"${name}\"`)),\n          Arr.appendAll(\n            description.length === 0\n              ? Arr.empty()\n              : Arr.make(\"-d\", `'${description}'`)\n          ),\n          Arr.join(\" \")\n        )\n      })\n    // If parent commands are empty, then the info is for the root command\n    if (Arr.isEmptyReadonlyArray(info.parentCommands)) {\n      const conditionals = Arr.make(\"-n\", \"\\\"__fish_use_subcommand\\\"\")\n      return Effect.succeed(pipe(\n        state,\n        Arr.appendAll(rootCompletions(conditionals)),\n        Arr.appendAll(subcommandCompletions(conditionals))\n      ))\n    }\n    // Otherwise the info is for a subcommand\n    const parentConditionals = pipe(\n      info.parentCommands,\n      // Drop the root command name from the subcommand conditionals\n      Arr.drop(1),\n      Arr.append(info.command.name),\n      Arr.map((command) => `__fish_seen_subcommand_from ${command}`)\n    )\n    const subcommandConditionals = Arr.map(\n      info.subcommands,\n      ([name]) => `not __fish_seen_subcommand_from ${name}`\n    )\n    const baseConditionals = pipe(\n      Arr.appendAll(parentConditionals, subcommandConditionals),\n      Arr.join(\"; and \")\n    )\n    const conditionals = Arr.make(\"-n\", `\"${baseConditionals}\"`)\n    return Effect.succeed(pipe(\n      state,\n      Arr.appendAll(rootCompletions(conditionals)),\n      Arr.appendAll(subcommandCompletions(conditionals))\n    ))\n  })\n\nconst getZshCompletionsInternal = (\n  self: Instruction,\n  executable: string\n): Effect.Effect<Array<string>> =>\n  traverseCommand(self, Arr.empty<string>(), (state, info) => {\n    const preformatted = Arr.isEmptyReadonlyArray(info.parentCommands)\n      ? Arr.of(info.command.name)\n      : pipe(\n        info.parentCommands,\n        Arr.append(info.command.name),\n        Arr.map((command) => command.replace(\"-\", \"__\"))\n      )\n    const underscoreName = Arr.join(preformatted, \"__\")\n    const spaceName = Arr.join(preformatted, \" \")\n    const subcommands = pipe(\n      info.subcommands,\n      Arr.map(([name, subcommand]) => {\n        const desc = getShortDescription(subcommand)\n        return `'${name}:${desc}' \\\\`\n      })\n    )\n    const commands = Arr.isEmptyReadonlyArray(subcommands)\n      ? `commands=()`\n      : `commands=(\\n${Arr.join(indentAll(subcommands, 8), \"\\n\")}\\n    )`\n    const handlerLines = [\n      `(( $+functions[_${underscoreName}_commands] )) ||`,\n      `_${underscoreName}_commands() {`,\n      `    local commands; ${commands}`,\n      `    _describe -t commands '${spaceName} commands' commands \"$@\"`,\n      \"}\"\n    ]\n    return Effect.succeed(Arr.appendAll(state, handlerLines))\n  }).pipe(Effect.map((handlers) => {\n    const rootCommand = Arr.unsafeGet(getNamesInternal(self), 0)\n    const cases = getZshSubcommandCases(self, Arr.empty(), Arr.empty())\n    const scriptName = `_${rootCommand}_zsh_completions`\n    return [\n      `#compdef ${executable}`,\n      \"\",\n      \"autoload -U is-at-least\",\n      \"\",\n      `function ${scriptName}() {`,\n      \"    typeset -A opt_args\",\n      \"    typeset -a _arguments_options\",\n      \"    local ret=1\",\n      \"\",\n      \"    if is-at-least 5.2; then\",\n      \"        _arguments_options=(-s -S -C)\",\n      \"    else\",\n      \"        _arguments_options=(-s -C)\",\n      \"    fi\",\n      \"\",\n      \"    local context curcontext=\\\"$curcontext\\\" state line\",\n      ...indentAll(cases, 4),\n      \"}\",\n      \"\",\n      ...handlers,\n      \"\",\n      `if [ \"$funcstack[1]\" = \"${scriptName}\" ]; then`,\n      `    ${scriptName} \"$@\"`,\n      \"else\",\n      `    compdef ${scriptName} ${rootCommand}`,\n      \"fi\"\n    ]\n  }))\n\nconst getZshSubcommandCases = (\n  self: Instruction,\n  parentCommands: ReadonlyArray<string>,\n  subcommands: ReadonlyArray<[string, Standard | GetUserInput]>\n): Array<string> => {\n  switch (self._tag) {\n    case \"Standard\":\n    case \"GetUserInput\": {\n      const options = isStandard(self)\n        ? InternalOptions.all([InternalBuiltInOptions.builtIns, self.options])\n        : InternalBuiltInOptions.builtIns\n      const args = isStandard(self) ? self.args : InternalArgs.none\n      const optionCompletions = pipe(\n        InternalOptions.getZshCompletions(options as InternalOptions.Instruction),\n        Arr.map((completion) => `'${completion}' \\\\`)\n      )\n      const argCompletions = pipe(\n        InternalArgs.getZshCompletions(args as InternalArgs.Instruction),\n        Arr.map((completion) => `'${completion}' \\\\`)\n      )\n      if (Arr.isEmptyReadonlyArray(parentCommands)) {\n        return [\n          \"_arguments \\\"${_arguments_options[@]}\\\" \\\\\",\n          ...indentAll(optionCompletions, 4),\n          ...indentAll(argCompletions, 4),\n          `    \":: :_${self.name}_commands\" \\\\`,\n          `    \"*::: :->${self.name}\" \\\\`,\n          \"    && ret=0\"\n        ]\n      }\n      if (Arr.isEmptyReadonlyArray(subcommands)) {\n        return [\n          `(${self.name})`,\n          \"_arguments \\\"${_arguments_options[@]}\\\" \\\\\",\n          ...indentAll(optionCompletions, 4),\n          ...indentAll(argCompletions, 4),\n          \"    && ret=0\",\n          \";;\"\n        ]\n      }\n      return [\n        `(${self.name})`,\n        \"_arguments \\\"${_arguments_options[@]}\\\" \\\\\",\n        ...indentAll(optionCompletions, 4),\n        ...indentAll(argCompletions, 4),\n        `    \":: :_${Arr.append(parentCommands, self.name).join(\"__\")}_commands\" \\\\`,\n        `    \"*::: :->${self.name}\" \\\\`,\n        \"    && ret=0\"\n      ]\n    }\n    case \"Map\": {\n      return getZshSubcommandCases(self.command, parentCommands, subcommands)\n    }\n    case \"Subcommands\": {\n      const nextSubcommands = getSubcommandsInternal(self)\n      const parentNames = getNamesInternal(self.parent)\n      const parentLines = getZshSubcommandCases(\n        self.parent,\n        parentCommands,\n        Arr.appendAll(subcommands, nextSubcommands)\n      )\n      const childCases = pipe(\n        self.children,\n        Arr.flatMap((child) =>\n          getZshSubcommandCases(\n            child,\n            Arr.appendAll(parentCommands, parentNames),\n            subcommands\n          )\n        )\n      )\n      const hyphenName = pipe(\n        Arr.appendAll(parentCommands, parentNames),\n        Arr.join(\"-\")\n      )\n      const childLines = pipe(\n        parentNames,\n        Arr.flatMap((parentName) => [\n          \"case $state in\",\n          `    (${parentName})`,\n          `    words=($line[1] \"\\${words[@]}\")`,\n          \"    (( CURRENT += 1 ))\",\n          `    curcontext=\"\\${curcontext%:*:*}:${hyphenName}-command-$line[1]:\"`,\n          `    case $line[1] in`,\n          ...indentAll(childCases, 8),\n          \"    esac\",\n          \"    ;;\",\n          \"esac\"\n        ]),\n        Arr.appendAll(\n          Arr.isEmptyReadonlyArray(parentCommands)\n            ? Arr.empty()\n            : Arr.of(\";;\")\n        )\n      )\n      return Arr.appendAll(parentLines, childLines)\n    }\n  }\n}\n\n// Circular with ValidationError\n\n/** @internal */\nexport const helpRequestedError = <A>(\n  command: Descriptor.Command<A>\n): ValidationError.ValidationError => {\n  const op = Object.create(InternalValidationError.proto)\n  op._tag = \"HelpRequested\"\n  op.error = InternalHelpDoc.empty\n  op.command = command\n  return op\n}\n"
  },
  {
    "path": "packages/cli/src/internal/commandDirective.ts",
    "content": "import { dual } from \"effect/Function\"\nimport type * as BuiltInOption from \"../BuiltInOptions.js\"\nimport type * as CommandDirective from \"../CommandDirective.js\"\n\n/** @internal */\nexport const builtIn = (\n  option: BuiltInOption.BuiltInOptions\n): CommandDirective.CommandDirective<never> => ({\n  _tag: \"BuiltIn\",\n  option\n})\n\n/** @internal */\nexport const userDefined = <A>(\n  leftover: ReadonlyArray<string>,\n  value: A\n): CommandDirective.CommandDirective<A> => ({\n  _tag: \"UserDefined\",\n  leftover,\n  value\n})\n\n/** @internal */\nexport const isBuiltIn = <A>(\n  self: CommandDirective.CommandDirective<A>\n): self is CommandDirective.BuiltIn => self._tag === \"BuiltIn\"\n\n/** @internal */\nexport const isUserDefined = <A>(\n  self: CommandDirective.CommandDirective<A>\n): self is CommandDirective.UserDefined<A> => self._tag === \"UserDefined\"\n\n/** @internal */\nexport const map = dual<\n  <A, B>(\n    f: (a: A) => B\n  ) => (self: CommandDirective.CommandDirective<A>) => CommandDirective.CommandDirective<B>,\n  <A, B>(\n    self: CommandDirective.CommandDirective<A>,\n    f: (a: A) => B\n  ) => CommandDirective.CommandDirective<B>\n>(2, (self, f) => isUserDefined(self) ? userDefined(self.leftover, f(self.value)) : self)\n"
  },
  {
    "path": "packages/cli/src/internal/configFile.ts",
    "content": "import * as FileSystem from \"@effect/platform/FileSystem\"\nimport * as Path from \"@effect/platform/Path\"\nimport * as Cause from \"effect/Cause\"\nimport * as ConfigProvider from \"effect/ConfigProvider\"\nimport * as Context from \"effect/Context\"\nimport * as DefaultServices from \"effect/DefaultServices\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport type * as ConfigFile from \"../ConfigFile.js\"\nimport * as InternalFiles from \"./files.js\"\n\nconst fileExtensions: Record<ConfigFile.Kind, ReadonlyArray<string>> = {\n  json: [\"json\"],\n  yaml: [\"yaml\", \"yml\"],\n  ini: [\"ini\"],\n  toml: [\"toml\", \"tml\"]\n}\n\nconst allFileExtensions = Object.values(fileExtensions).flat()\n\n/** @internal */\nexport const makeProvider = (fileName: string, options?: {\n  readonly formats?: ReadonlyArray<ConfigFile.Kind>\n  readonly searchPaths?: ReadonlyArray<string>\n}): Effect.Effect<ConfigProvider.ConfigProvider, ConfigFile.ConfigFileError, Path.Path | FileSystem.FileSystem> =>\n  Effect.gen(function*() {\n    const path = yield* Path.Path\n    const fs = yield* FileSystem.FileSystem\n    const searchPaths = options?.searchPaths && options.searchPaths.length ? options.searchPaths : [\".\"]\n    const extensions = options?.formats && options.formats.length\n      ? options.formats.flatMap((_) => fileExtensions[_])\n      : allFileExtensions\n    const filePaths = yield* Effect.filter(\n      searchPaths.flatMap(\n        (searchPath) => extensions.map((ext) => path.join(searchPath, `${fileName}.${ext}`))\n      ),\n      (path) => Effect.orElseSucceed(fs.exists(path), () => false)\n    )\n    const providers = yield* Effect.forEach(filePaths, (path) =>\n      pipe(\n        fs.readFileString(path),\n        Effect.mapError((_) => ConfigFileError(`Could not read file (${path})`)),\n        Effect.flatMap((content) =>\n          Effect.mapError(\n            InternalFiles.parse(path, content),\n            (message) => ConfigFileError(message)\n          )\n        ),\n        Effect.map((data) => ConfigProvider.fromJson(data))\n      ))\n\n    if (providers.length === 0) {\n      return ConfigProvider.fromMap(new Map())\n    }\n\n    return providers.reduce((acc, provider) => ConfigProvider.orElse(acc, () => provider))\n  })\n\n/** @internal */\nexport const layer = (fileName: string, options?: {\n  readonly formats?: ReadonlyArray<ConfigFile.Kind>\n  readonly searchPaths?: ReadonlyArray<string>\n}): Layer.Layer<never, ConfigFile.ConfigFileError, Path.Path | FileSystem.FileSystem> =>\n  pipe(\n    makeProvider(fileName, options),\n    Effect.map((provider) =>\n      Layer.fiberRefLocallyScopedWith(DefaultServices.currentServices, (services) => {\n        const current = Context.get(services, ConfigProvider.ConfigProvider)\n        return Context.add(services, ConfigProvider.ConfigProvider, ConfigProvider.orElse(current, () => provider))\n      })\n    ),\n    Layer.unwrapEffect\n  )\n\n/** @internal */\nexport const ConfigErrorTypeId: ConfigFile.ConfigErrorTypeId = Symbol.for(\n  \"@effect/cli/ConfigFile/ConfigFileError\"\n) as ConfigFile.ConfigErrorTypeId\n\nconst ConfigFileErrorProto = Object.assign(Object.create(Cause.YieldableError.prototype), {\n  [ConfigErrorTypeId]: ConfigErrorTypeId\n})\n\n/** @internal */\nexport const ConfigFileError = (message: string): ConfigFile.ConfigFileError => {\n  const self = Object.create(ConfigFileErrorProto)\n  self._tag = \"ConfigFileError\"\n  self.message = message\n  return self\n}\n"
  },
  {
    "path": "packages/cli/src/internal/files.ts",
    "content": "import * as FileSystem from \"@effect/platform/FileSystem\"\nimport * as Effect from \"effect/Effect\"\nimport * as Ini from \"ini\"\nimport * as Toml from \"toml\"\nimport * as Yaml from \"yaml\"\n\n/** @internal */\nexport const fileParsers: Record<string, (content: string) => unknown> = {\n  json: (content: string) => JSON.parse(content),\n  yaml: (content: string) => Yaml.parse(content),\n  yml: (content: string) => Yaml.parse(content),\n  ini: (content: string) => Ini.parse(content),\n  toml: (content: string) => Toml.parse(content),\n  tml: (content: string) => Toml.parse(content)\n}\n\n/** @internal */\nexport const read = (\n  path: string\n): Effect.Effect<readonly [path: string, content: Uint8Array], string, FileSystem.FileSystem> =>\n  Effect.flatMap(\n    FileSystem.FileSystem,\n    (fs) =>\n      Effect.matchEffect(fs.readFile(path), {\n        onFailure: (error) => Effect.fail(`Could not read file (${path}): ${error}`),\n        onSuccess: (content) => Effect.succeed([path, content] as const)\n      })\n  )\n\n/** @internal */\nexport const readString = (\n  path: string\n): Effect.Effect<readonly [path: string, content: string], string, FileSystem.FileSystem> =>\n  Effect.flatMap(\n    FileSystem.FileSystem,\n    (fs) =>\n      Effect.matchEffect(fs.readFileString(path), {\n        onFailure: (error) => Effect.fail(`Could not read file (${path}): ${error}`),\n        onSuccess: (content) => Effect.succeed([path, content] as const)\n      })\n  )\n\n/** @internal */\nexport const parse = (\n  path: string,\n  content: string,\n  format?: \"json\" | \"yaml\" | \"ini\" | \"toml\"\n): Effect.Effect<unknown, string> => {\n  const parser = fileParsers[format ?? path.split(\".\").pop() as string]\n  if (parser === undefined) {\n    return Effect.fail(`Unsupported file format: ${format}`)\n  }\n\n  return Effect.try({\n    try: () => parser(content),\n    catch: (e) => `Could not parse ${format} file (${path}): ${e}`\n  })\n}\n"
  },
  {
    "path": "packages/cli/src/internal/helpDoc/span.ts",
    "content": "import * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Color from \"@effect/printer-ansi/Color\"\nimport * as Arr from \"effect/Array\"\nimport { dual } from \"effect/Function\"\nimport type * as Span from \"../../HelpDoc/Span.js\"\n\n/** @internal */\nexport const text = (value: string): Span.Span => ({\n  _tag: \"Text\",\n  value\n})\n\n/** @internal */\nexport const empty: Span.Span = text(\"\")\n\n/** @internal */\nexport const space: Span.Span = text(\" \")\n\n/** @internal */\nexport const code = (value: Span.Span | string): Span.Span => highlight(value, Color.white)\n\n/** @internal */\nexport const error = (value: Span.Span | string): Span.Span => highlight(value, Color.red)\n\n/** @internal */\nexport const highlight = (value: Span.Span | string, color: Color.Color): Span.Span => ({\n  _tag: \"Highlight\",\n  value: typeof value === \"string\" ? text(value) : value,\n  color\n})\n\n/** @internal */\nexport const strong = (value: Span.Span | string): Span.Span => ({\n  _tag: \"Strong\",\n  value: typeof value === \"string\" ? text(value) : value\n})\n\n/** @internal */\nexport const uri = (value: string): Span.Span => ({\n  _tag: \"URI\",\n  value\n})\n\n/** @internal */\nexport const weak = (value: Span.Span | string): Span.Span => ({\n  _tag: \"Weak\",\n  value: typeof value === \"string\" ? text(value) : value\n})\n\n/** @internal */\nexport const isSequence = (self: Span.Span): self is Span.Sequence => self._tag === \"Sequence\"\n\n/** @internal */\nexport const isStrong = (self: Span.Span): self is Span.Strong => self._tag === \"Strong\"\n\n/** @internal */\nexport const isText = (self: Span.Span): self is Span.Text => self._tag === \"Text\"\n\n/** @internal */\nexport const isUri = (self: Span.Span): self is Span.URI => self._tag === \"URI\"\n\n/** @internal */\nexport const isWeak = (self: Span.Span): self is Span.Weak => self._tag === \"Weak\"\n\n/** @internal */\nexport const concat = dual<\n  (that: Span.Span) => (self: Span.Span) => Span.Span,\n  (self: Span.Span, that: Span.Span) => Span.Span\n>(2, (self, that): Span.Span => ({\n  _tag: \"Sequence\",\n  left: self,\n  right: that\n}))\n\nexport const getText = (self: Span.Span): string => {\n  switch (self._tag) {\n    case \"Text\":\n    case \"URI\": {\n      return self.value\n    }\n    case \"Highlight\":\n    case \"Weak\":\n    case \"Strong\": {\n      return getText(self.value)\n    }\n    case \"Sequence\": {\n      return getText(self.left) + getText(self.right)\n    }\n  }\n}\n\n/** @internal */\nexport const spans = (spans: Iterable<Span.Span>): Span.Span => {\n  const elements = Arr.fromIterable(spans)\n  if (Arr.isNonEmptyReadonlyArray(elements)) {\n    return elements.slice(1).reduce(concat, elements[0])\n  }\n  return empty\n}\n\n/** @internal */\nexport const isEmpty = (self: Span.Span): boolean => size(self) === 0\n\n/** @internal */\nexport const size = (self: Span.Span): number => {\n  switch (self._tag) {\n    case \"Text\":\n    case \"URI\": {\n      return self.value.length\n    }\n    case \"Highlight\":\n    case \"Strong\":\n    case \"Weak\": {\n      return size(self.value)\n    }\n    case \"Sequence\": {\n      return size(self.left) + size(self.right)\n    }\n  }\n}\n\n/** @internal */\nexport const toAnsiDoc = (self: Span.Span): Doc.AnsiDoc => {\n  switch (self._tag) {\n    case \"Highlight\": {\n      return Doc.annotate(toAnsiDoc(self.value), Ansi.color(self.color))\n    }\n    case \"Sequence\": {\n      return Doc.cat(toAnsiDoc(self.left), toAnsiDoc(self.right))\n    }\n    case \"Strong\": {\n      return Doc.annotate(toAnsiDoc(self.value), Ansi.bold)\n    }\n    case \"Text\": {\n      return Doc.text(self.value)\n    }\n    case \"URI\": {\n      return Doc.annotate(Doc.text(self.value), Ansi.underlined)\n    }\n    case \"Weak\": {\n      return Doc.annotate(toAnsiDoc(self.value), Ansi.black)\n    }\n  }\n}\n"
  },
  {
    "path": "packages/cli/src/internal/helpDoc.ts",
    "content": "import * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Optimize from \"@effect/printer/Optimize\"\nimport * as Arr from \"effect/Array\"\nimport { dual, pipe } from \"effect/Function\"\nimport type * as HelpDoc from \"../HelpDoc.js\"\nimport type * as Span from \"../HelpDoc/Span.js\"\nimport * as InternalSpan from \"./helpDoc/span.js\"\n\n/** @internal */\nexport const isEmpty = (helpDoc: HelpDoc.HelpDoc): helpDoc is HelpDoc.Empty => helpDoc._tag === \"Empty\"\n\n/** @internal */\nexport const isHeader = (helpDoc: HelpDoc.HelpDoc): helpDoc is HelpDoc.Header => helpDoc._tag === \"Header\"\n\n/** @internal */\nexport const isParagraph = (helpDoc: HelpDoc.HelpDoc): helpDoc is HelpDoc.Paragraph => helpDoc._tag === \"Paragraph\"\n\n/** @internal */\nexport const isDescriptionList = (helpDoc: HelpDoc.HelpDoc): helpDoc is HelpDoc.DescriptionList =>\n  helpDoc._tag === \"DescriptionList\"\n\n/** @internal */\nexport const isEnumeration = (helpDoc: HelpDoc.HelpDoc): helpDoc is HelpDoc.Enumeration =>\n  helpDoc._tag === \"Enumeration\"\n\n/** @internal */\nexport const isSequence = (helpDoc: HelpDoc.HelpDoc): helpDoc is HelpDoc.Sequence => helpDoc._tag === \"Sequence\"\n\n/** @internal */\nexport const empty: HelpDoc.HelpDoc = {\n  _tag: \"Empty\"\n}\n\n/** @internal */\nexport const sequence = dual<\n  (that: HelpDoc.HelpDoc) => (self: HelpDoc.HelpDoc) => HelpDoc.HelpDoc,\n  (self: HelpDoc.HelpDoc, that: HelpDoc.HelpDoc) => HelpDoc.HelpDoc\n>(2, (self, that) => {\n  if (isEmpty(self)) {\n    return that\n  }\n  if (isEmpty(that)) {\n    return self\n  }\n  return {\n    _tag: \"Sequence\",\n    left: self,\n    right: that\n  }\n})\n\n/** @internal */\nexport const orElse = dual<\n  (that: HelpDoc.HelpDoc) => (self: HelpDoc.HelpDoc) => HelpDoc.HelpDoc,\n  (self: HelpDoc.HelpDoc, that: HelpDoc.HelpDoc) => HelpDoc.HelpDoc\n>(2, (self, that) => isEmpty(self) ? that : self)\n\n/** @internal */\nexport const blocks = (helpDocs: Iterable<HelpDoc.HelpDoc>): HelpDoc.HelpDoc => {\n  const elements = Arr.fromIterable(helpDocs)\n  if (Arr.isNonEmptyReadonlyArray(elements)) {\n    return elements.slice(1).reduce(sequence, elements[0])\n  }\n  return empty\n}\n\n/** @internal */\nexport const getSpan = (self: HelpDoc.HelpDoc): Span.Span =>\n  isHeader(self) || isParagraph(self) ? self.value : InternalSpan.empty\n\n/** @internal */\nexport const descriptionList = (\n  definitions: Arr.NonEmptyReadonlyArray<[Span.Span, HelpDoc.HelpDoc]>\n): HelpDoc.HelpDoc => ({\n  _tag: \"DescriptionList\",\n  definitions\n})\n\n/** @internal */\nexport const enumeration = (\n  elements: Arr.NonEmptyReadonlyArray<HelpDoc.HelpDoc>\n): HelpDoc.HelpDoc => ({\n  _tag: \"Enumeration\",\n  elements\n})\n\n/** @internal */\nexport const h1 = (value: string | Span.Span): HelpDoc.HelpDoc => ({\n  _tag: \"Header\",\n  value: typeof value === \"string\" ? InternalSpan.text(value) : value,\n  level: 1\n})\n\n/** @internal */\nexport const h2 = (value: string | Span.Span): HelpDoc.HelpDoc => ({\n  _tag: \"Header\",\n  value: typeof value === \"string\" ? InternalSpan.text(value) : value,\n  level: 2\n})\n\n/** @internal */\nexport const h3 = (value: string | Span.Span): HelpDoc.HelpDoc => ({\n  _tag: \"Header\",\n  value: typeof value === \"string\" ? InternalSpan.text(value) : value,\n  level: 3\n})\n\n/** @internal */\nexport const p = (value: string | Span.Span): HelpDoc.HelpDoc => ({\n  _tag: \"Paragraph\",\n  value: typeof value === \"string\" ? InternalSpan.text(value) : value\n})\n\n/** @internal */\nexport const mapDescriptionList = dual<\n  (\n    f: (span: Span.Span, helpDoc: HelpDoc.HelpDoc) => [Span.Span, HelpDoc.HelpDoc]\n  ) => (self: HelpDoc.HelpDoc) => HelpDoc.HelpDoc,\n  (\n    self: HelpDoc.HelpDoc,\n    f: (span: Span.Span, helpDoc: HelpDoc.HelpDoc) => [Span.Span, HelpDoc.HelpDoc]\n  ) => HelpDoc.HelpDoc\n>(2, (self, f) =>\n  isDescriptionList(self)\n    ? descriptionList(Arr.map(self.definitions, ([span, helpDoc]) => f(span, helpDoc)))\n    : self)\n\n/** @internal */\nexport const toAnsiDoc = (self: HelpDoc.HelpDoc): Doc.AnsiDoc =>\n  Optimize.optimize(toAnsiDocInternal(self), Optimize.Deep)\n\n/** @internal */\nexport const toAnsiText = (self: HelpDoc.HelpDoc): string => Doc.render(toAnsiDoc(self), { style: \"pretty\" })\n\n// =============================================================================\n// Internals\n// =============================================================================\n\nconst toAnsiDocInternal = (self: HelpDoc.HelpDoc): Doc.AnsiDoc => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Doc.empty\n    }\n    case \"Header\": {\n      return pipe(\n        Doc.annotate(InternalSpan.toAnsiDoc(self.value), Ansi.bold),\n        Doc.cat(Doc.hardLine)\n      )\n    }\n    case \"Paragraph\": {\n      return pipe(\n        InternalSpan.toAnsiDoc(self.value),\n        Doc.cat(Doc.hardLine)\n      )\n    }\n    case \"DescriptionList\": {\n      const definitions = self.definitions.map(([span, doc]) =>\n        Doc.cats([\n          Doc.annotate(InternalSpan.toAnsiDoc(span), Ansi.bold),\n          Doc.empty,\n          Doc.indent(toAnsiDocInternal(doc), 2)\n        ])\n      )\n      return Doc.vsep(definitions)\n    }\n    case \"Enumeration\": {\n      const elements = self.elements.map((doc) => Doc.cat(Doc.text(\"- \"), toAnsiDocInternal(doc)))\n      return Doc.indent(Doc.vsep(elements), 2)\n    }\n    case \"Sequence\": {\n      return Doc.vsep([\n        toAnsiDocInternal(self.left),\n        toAnsiDocInternal(self.right)\n      ])\n    }\n  }\n}\n"
  },
  {
    "path": "packages/cli/src/internal/options.ts",
    "content": "import type * as FileSystem from \"@effect/platform/FileSystem\"\nimport type * as Path from \"@effect/platform/Path\"\nimport type * as Terminal from \"@effect/platform/Terminal\"\nimport * as Arr from \"effect/Array\"\nimport * as Config from \"effect/Config\"\nimport * as ConfigError from \"effect/ConfigError\"\nimport * as Console from \"effect/Console\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { dual, pipe } from \"effect/Function\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as Inspectable from \"effect/Inspectable\"\nimport * as Option from \"effect/Option\"\nimport * as Order from \"effect/Order\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport { pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Redacted from \"effect/Redacted\"\nimport * as Ref from \"effect/Ref\"\nimport type * as Schema from \"effect/Schema\"\nimport type * as Secret from \"effect/Secret\"\nimport type * as CliConfig from \"../CliConfig.js\"\nimport type * as HelpDoc from \"../HelpDoc.js\"\nimport type * as Options from \"../Options.js\"\nimport type * as Primitive from \"../Primitive.js\"\nimport type * as Prompt from \"../Prompt.js\"\nimport type * as Usage from \"../Usage.js\"\nimport type * as ValidationError from \"../ValidationError.js\"\nimport * as InternalAutoCorrect from \"./autoCorrect.js\"\nimport * as InternalCliConfig from \"./cliConfig.js\"\nimport * as InternalFiles from \"./files.js\"\nimport * as InternalHelpDoc from \"./helpDoc.js\"\nimport * as InternalSpan from \"./helpDoc/span.js\"\nimport * as InternalPrimitive from \"./primitive.js\"\nimport * as InternalPrompt from \"./prompt.js\"\nimport * as InternalListPrompt from \"./prompt/list.js\"\nimport * as InternalNumberPrompt from \"./prompt/number.js\"\nimport * as InternalSelectPrompt from \"./prompt/select.js\"\nimport * as InternalUsage from \"./usage.js\"\nimport * as InternalValidationError from \"./validationError.js\"\n\nconst OptionsSymbolKey = \"@effect/cli/Options\"\n\n/** @internal */\nexport const OptionsTypeId: Options.OptionsTypeId = Symbol.for(\n  OptionsSymbolKey\n) as Options.OptionsTypeId\n\n/** @internal */\nexport type Op<Tag extends string, Body = {}> = Options.Options<never> & Body & {\n  readonly _tag: Tag\n}\n\nconst proto = {\n  [OptionsTypeId]: {\n    _A: (_: never) => _\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport type Instruction =\n  | Empty\n  | Single\n  | KeyValueMap\n  | Map\n  | Both\n  | OrElse\n  | WithFallback\n  | Variadic\n  | WithDefault\n\n/** @internal */\nexport type ParseableInstruction = Single | KeyValueMap | Variadic\n\n/** @internal */\nexport interface Empty extends Op<\"Empty\", {}> {}\n\n/** @internal */\nexport interface Single extends\n  Op<\"Single\", {\n    readonly name: string\n    readonly fullName: string\n    readonly placeholder: string\n    readonly aliases: ReadonlyArray<string>\n    readonly primitiveType: Primitive.Primitive<unknown>\n    readonly description: HelpDoc.HelpDoc\n    readonly pseudoName: Option.Option<string>\n  }>\n{}\n\n/** @internal */\nexport interface KeyValueMap extends\n  Op<\"KeyValueMap\", {\n    readonly argumentOption: Single\n  }>\n{}\n\n/** @internal */\nexport interface Map extends\n  Op<\"Map\", {\n    readonly options: Options.Options<unknown>\n    readonly f: (a: unknown) => Effect.Effect<\n      unknown,\n      ValidationError.ValidationError,\n      FileSystem.FileSystem | Path.Path | Terminal.Terminal\n    >\n  }>\n{}\n\n/** @internal */\nexport interface Both extends\n  Op<\"Both\", {\n    readonly left: Options.Options<unknown>\n    readonly right: Options.Options<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface OrElse extends\n  Op<\"OrElse\", {\n    readonly left: Options.Options<unknown>\n    readonly right: Options.Options<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface WithFallback extends\n  Op<\"WithFallback\", {\n    readonly options: Options.Options<unknown>\n    readonly effect: Effect.Effect<\n      unknown,\n      unknown,\n      FileSystem.FileSystem | Path.Path | Terminal.Terminal\n    >\n  }>\n{}\n\n/** @internal */\nexport interface Variadic extends\n  Op<\"Variadic\", {\n    readonly argumentOption: Single\n    readonly min: Option.Option<number>\n    readonly max: Option.Option<number>\n  }>\n{}\n\n/** @internal */\nexport interface WithDefault extends\n  Op<\"WithDefault\", {\n    readonly options: Options.Options<unknown>\n    readonly fallback: unknown\n  }>\n{}\n\n// =============================================================================\n// Refinements\n// =============================================================================\n\n/** @internal */\nexport const isOptions = (u: unknown): u is Options.Options<unknown> =>\n  typeof u === \"object\" && u != null && OptionsTypeId in u\n\n/** @internal */\nexport const isInstruction = <_>(self: Options.Options<_>): self is Instruction => self as any\n\n/** @internal */\nexport const isEmpty = (self: Instruction): self is Empty => self._tag === \"Empty\"\n\n/** @internal */\nexport const isSingle = (self: Instruction): self is Single => self._tag === \"Single\"\n\n/** @internal */\nexport const isKeyValueMap = (self: Instruction): self is KeyValueMap => self._tag === \"KeyValueMap\"\n\n/** @internal */\nexport const isMap = (self: Instruction): self is Map => self._tag === \"Map\"\n\n/** @internal */\nexport const isBoth = (self: Instruction): self is Both => self._tag === \"Both\"\n\n/** @internal */\nexport const isOrElse = (self: Instruction): self is OrElse => self._tag === \"OrElse\"\n\n/** @internal */\nexport const isWithDefault = (self: Instruction): self is WithDefault => self._tag === \"WithDefault\"\n\n/** @internal */\nexport const isWithFallback = (self: Instruction): self is WithFallback => self._tag === \"WithFallback\"\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\n/** @internal */\nexport const all: <\n  const Arg extends Iterable<Options.Options<any>> | Record<string, Options.Options<any>>\n>(arg: Arg) => Options.All.Return<Arg> = function() {\n  if (arguments.length === 1) {\n    if (isOptions(arguments[0])) {\n      return map(arguments[0], (x) => [x]) as any\n    } else if (Arr.isArray(arguments[0])) {\n      return allTupled(arguments[0] as Array<any>) as any\n    } else {\n      const entries = Object.entries(\n        arguments[0] as Readonly<{ [K: string]: Options.Options<any> }>\n      )\n      let result = map(entries[0][1], (value) => ({ [entries[0][0]]: value }))\n      if (entries.length === 1) {\n        return result as any\n      }\n      const rest = entries.slice(1)\n      for (const [key, options] of rest) {\n        result = map(makeBoth(result, options), ([record, value]) => ({\n          ...record,\n          [key]: value\n        }))\n      }\n      return result as any\n    }\n  }\n  return allTupled(arguments[0]) as any\n}\n\nconst defaultBooleanOptions = {\n  ifPresent: true,\n  negationNames: [],\n  aliases: []\n}\n\n/** @internal */\nexport const boolean = (\n  name: string,\n  options?: Options.Options.BooleanOptionsConfig\n): Options.Options<boolean> => {\n  const { aliases, ifPresent, negationNames } = { ...defaultBooleanOptions, ...options }\n  const option = makeSingle(\n    name,\n    aliases,\n    InternalPrimitive.boolean(Option.some(ifPresent))\n  )\n  if (Arr.isNonEmptyReadonlyArray(negationNames)) {\n    const head = Arr.headNonEmpty(negationNames)\n    const tail = Arr.tailNonEmpty(negationNames)\n    const negationOption = makeSingle(\n      head,\n      tail,\n      InternalPrimitive.boolean(Option.some(!ifPresent))\n    )\n    return withDefault(\n      orElse(option, negationOption),\n      !ifPresent\n    )\n  }\n  return withDefault(option, !ifPresent)\n}\n\n/** @internal */\nexport const choice = <A extends string, C extends ReadonlyArray<A>>(\n  name: string,\n  choices: C\n): Options.Options<C[number]> => {\n  const primitive = InternalPrimitive.choice(\n    Arr.map(choices, (choice) => [choice, choice])\n  )\n  return makeSingle(name, Arr.empty(), primitive)\n}\n\n/** @internal */\nexport const choiceWithValue = <const C extends ReadonlyArray<[string, any]>>(\n  name: string,\n  choices: C\n): Options.Options<C[number][1]> => makeSingle(name, Arr.empty(), InternalPrimitive.choice(choices))\n\n/** @internal */\nexport const date = (name: string): Options.Options<Date> => makeSingle(name, Arr.empty(), InternalPrimitive.date)\n\n/** @internal */\nexport const directory = (\n  name: string,\n  config?: Options.Options.PathOptionsConfig\n): Options.Options<string> =>\n  makeSingle(\n    name,\n    Arr.empty(),\n    InternalPrimitive.path(\"directory\", config?.exists ?? \"either\")\n  )\n\n/** @internal */\nexport const file = (\n  name: string,\n  config?: Options.Options.PathOptionsConfig\n): Options.Options<string> =>\n  makeSingle(\n    name,\n    Arr.empty(),\n    InternalPrimitive.path(\"file\", config?.exists ?? \"either\")\n  )\n\n/** @internal */\nexport const fileContent = (\n  name: string\n): Options.Options<readonly [path: string, content: Uint8Array]> =>\n  mapEffect(file(name, { exists: \"yes\" }), (path) =>\n    Effect.mapError(\n      InternalFiles.read(path),\n      (msg) => InternalValidationError.invalidValue(InternalHelpDoc.p(msg))\n    ))\n\n/** @internal */\nexport const fileParse = (\n  name: string,\n  format?: \"json\" | \"yaml\" | \"ini\" | \"toml\"\n): Options.Options<unknown> =>\n  mapEffect(fileText(name), ([path, content]) =>\n    Effect.mapError(\n      InternalFiles.parse(path, content, format),\n      (error) => InternalValidationError.invalidValue(InternalHelpDoc.p(error))\n    ))\n\n/** @internal */\nexport const fileSchema = <I, A>(\n  name: string,\n  schema: Schema.Schema<A, I, FileSystem.FileSystem | Path.Path | Terminal.Terminal>,\n  format?: \"json\" | \"yaml\" | \"ini\" | \"toml\"\n): Options.Options<A> => withSchema(fileParse(name, format), schema)\n\n/** @internal */\nexport const fileText = (\n  name: string\n): Options.Options<readonly [path: string, content: string]> =>\n  mapEffect(file(name, { exists: \"yes\" }), (path) =>\n    Effect.mapError(\n      InternalFiles.readString(path),\n      (error) => InternalValidationError.invalidValue(InternalHelpDoc.p(error))\n    ))\n\n/** @internal */\nexport const filterMap = dual<\n  <A, B>(\n    f: (a: A) => Option.Option<B>,\n    message: string\n  ) => (self: Options.Options<A>) => Options.Options<B>,\n  <A, B>(\n    self: Options.Options<A>,\n    f: (a: A) => Option.Option<B>,\n    message: string\n  ) => Options.Options<B>\n>(3, (self, f, message) =>\n  mapEffect(self, (a) =>\n    Option.match(f(a), {\n      onNone: () => Either.left(InternalValidationError.invalidValue(InternalHelpDoc.p(message))),\n      onSome: Either.right\n    })))\n\n/** @internal */\nexport const float = (name: string): Options.Options<number> => makeSingle(name, Arr.empty(), InternalPrimitive.float)\n\n/** @internal */\nexport const integer = (name: string): Options.Options<number> =>\n  makeSingle(name, Arr.empty(), InternalPrimitive.integer)\n\n/** @internal */\nexport const keyValueMap = (\n  option: string | Options.Options<string>\n): Options.Options<HashMap.HashMap<string, string>> => {\n  if (typeof option === \"string\") {\n    const single = makeSingle(option, Arr.empty(), InternalPrimitive.text)\n    return makeKeyValueMap(single as Single)\n  }\n  if (!isSingle(option as Instruction)) {\n    throw new Error(\"InvalidArgumentException: only single options can be key/value maps\")\n  } else {\n    return makeKeyValueMap(option as Single)\n  }\n}\n\n/** @internal */\nexport const none: Options.Options<void> = (() => {\n  const op = Object.create(proto)\n  op._tag = \"Empty\"\n  return op\n})()\n\n/** @internal */\nexport const redacted = (name: string): Options.Options<Redacted.Redacted> =>\n  makeSingle(name, Arr.empty(), InternalPrimitive.redacted)\n\n/** @internal */\nexport const secret = (name: string): Options.Options<Secret.Secret> =>\n  makeSingle(name, Arr.empty(), InternalPrimitive.secret)\n\n/** @internal */\nexport const text = (name: string): Options.Options<string> => makeSingle(name, Arr.empty(), InternalPrimitive.text)\n\n// =============================================================================\n// Combinators\n// =============================================================================\n\n/** @internal */\nexport const atLeast = dual<\n  {\n    (times: 0): <A>(self: Options.Options<A>) => Options.Options<Array<A>>\n    (\n      times: number\n    ): <A>(self: Options.Options<A>) => Options.Options<Arr.NonEmptyArray<A>>\n  },\n  {\n    <A>(self: Options.Options<A>, times: 0): Options.Options<Array<A>>\n    <A>(\n      self: Options.Options<A>,\n      times: number\n    ): Options.Options<Arr.NonEmptyArray<A>>\n  }\n>(2, (self, times) => makeVariadic(self, Option.some(times), Option.none()) as any)\n\n/** @internal */\nexport const atMost = dual<\n  (times: number) => <A>(self: Options.Options<A>) => Options.Options<Array<A>>,\n  <A>(self: Options.Options<A>, times: number) => Options.Options<Array<A>>\n>(2, (self, times) => makeVariadic(self, Option.none(), Option.some(times)) as any)\n\n/** @internal */\nexport const between = dual<\n  {\n    (min: 0, max: number): <A>(self: Options.Options<A>) => Options.Options<Array<A>>\n    (\n      min: number,\n      max: number\n    ): <A>(self: Options.Options<A>) => Options.Options<Arr.NonEmptyArray<A>>\n  },\n  {\n    <A>(self: Options.Options<A>, min: 0, max: number): Options.Options<Array<A>>\n    <A>(\n      self: Options.Options<A>,\n      min: number,\n      max: number\n    ): Options.Options<Arr.NonEmptyArray<A>>\n  }\n>(3, (self, min, max) => makeVariadic(self, Option.some(min), Option.some(max)) as any)\n\n/** @internal */\nexport const isBool = <A>(self: Options.Options<A>): boolean => isBoolInternal(self as Instruction)\n\n/** @internal */\nexport const getHelp = <A>(self: Options.Options<A>): HelpDoc.HelpDoc => getHelpInternal(self as Instruction)\n\n/** @internal */\nexport const getIdentifier = <A>(self: Options.Options<A>): Option.Option<string> =>\n  getIdentifierInternal(self as Instruction)\n\n/** @internal */\nexport const getMinSize = <A>(self: Options.Options<A>): number => getMinSizeInternal(self as Instruction)\n\n/** @internal */\nexport const getMaxSize = <A>(self: Options.Options<A>): number => getMaxSizeInternal(self as Instruction)\n\n/** @internal */\nexport const getUsage = <A>(self: Options.Options<A>): Usage.Usage => getUsageInternal(self as Instruction)\n\n/** @internal */\nexport const map = dual<\n  <A, B>(f: (a: A) => B) => (self: Options.Options<A>) => Options.Options<B>,\n  <A, B>(self: Options.Options<A>, f: (a: A) => B) => Options.Options<B>\n>(2, (self, f) => makeMap(self, (a) => Either.right(f(a))))\n\n/** @internal */\nexport const mapEffect = dual<\n  <A, B>(\n    f: (\n      a: A\n    ) => Effect.Effect<B, ValidationError.ValidationError, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n  ) => (self: Options.Options<A>) => Options.Options<B>,\n  <A, B>(\n    self: Options.Options<A>,\n    f: (\n      a: A\n    ) => Effect.Effect<B, ValidationError.ValidationError, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n  ) => Options.Options<B>\n>(2, (self, f) => makeMap(self, f))\n\n/** @internal */\nexport const mapTryCatch = dual<\n  <A, B>(\n    f: (a: A) => B,\n    onError: (e: unknown) => HelpDoc.HelpDoc\n  ) => (self: Options.Options<A>) => Options.Options<B>,\n  <A, B>(\n    self: Options.Options<A>,\n    f: (a: A) => B,\n    onError: (e: unknown) => HelpDoc.HelpDoc\n  ) => Options.Options<B>\n>(3, (self, f, onError) =>\n  mapEffect(self, (a) => {\n    try {\n      return Either.right(f(a))\n    } catch (e) {\n      return Either.left(InternalValidationError.invalidValue(onError(e)))\n    }\n  }))\n\n/** @internal */\nexport const optional = <A>(self: Options.Options<A>): Options.Options<Option.Option<A>> =>\n  withDefault(map(self, Option.some), Option.none())\n\n/** @internal */\nexport const orElse = dual<\n  <B>(that: Options.Options<B>) => <A>(self: Options.Options<A>) => Options.Options<A | B>,\n  <A, B>(self: Options.Options<A>, that: Options.Options<B>) => Options.Options<A | B>\n>(2, (self, that) => orElseEither(self, that).pipe(map(Either.merge)))\n\n/** @internal */\nexport const orElseEither = dual<\n  <B>(\n    that: Options.Options<B>\n  ) => <A>(self: Options.Options<A>) => Options.Options<Either.Either<B, A>>,\n  <A, B>(self: Options.Options<A>, that: Options.Options<B>) => Options.Options<Either.Either<B, A>>\n>(2, (self, that) => makeOrElse(self, that))\n\n/** @internal */\nexport const parse = dual<\n  (\n    args: HashMap.HashMap<string, ReadonlyArray<string>>,\n    config: CliConfig.CliConfig\n  ) => <A>(\n    self: Options.Options<A>\n  ) => Effect.Effect<A, ValidationError.ValidationError, FileSystem.FileSystem>,\n  <A>(\n    self: Options.Options<A>,\n    args: HashMap.HashMap<string, ReadonlyArray<string>>,\n    config: CliConfig.CliConfig\n  ) => Effect.Effect<A, ValidationError.ValidationError, FileSystem.FileSystem>\n>(3, (self, args, config) => parseInternal(self as Instruction, args, config) as any)\n\n/** @internal */\nexport const processCommandLine = dual<\n  (\n    args: ReadonlyArray<string>,\n    config: CliConfig.CliConfig\n  ) => <A>(\n    self: Options.Options<A>\n  ) => Effect.Effect<\n    [Option.Option<ValidationError.ValidationError>, Array<string>, A],\n    ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >,\n  <A>(\n    self: Options.Options<A>,\n    args: ReadonlyArray<string>,\n    config: CliConfig.CliConfig\n  ) => Effect.Effect<\n    [Option.Option<ValidationError.ValidationError>, Array<string>, A],\n    ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >\n>(\n  3,\n  (self, args, config) =>\n    matchOptions(args, toParseableInstruction(self as Instruction), config).pipe(\n      Effect.flatMap(([error, commandArgs, matchedOptions]) =>\n        parseInternal(self as Instruction, matchedOptions, config).pipe(\n          Effect.catchAll((e) =>\n            Option.match(error, {\n              onNone: () => Effect.fail(e),\n              onSome: (err) => Effect.fail(err)\n            })\n          ),\n          Effect.map((a) => [error, commandArgs as Array<string>, a as any])\n        )\n      )\n    )\n)\n\n/** @internal */\nexport const repeated = <A>(self: Options.Options<A>): Options.Options<Array<A>> =>\n  makeVariadic(self, Option.none(), Option.none())\n\n/** @internal */\nexport const withAlias = dual<\n  (alias: string) => <A>(self: Options.Options<A>) => Options.Options<A>,\n  <A>(self: Options.Options<A>, alias: string) => Options.Options<A>\n>(2, (self, alias) =>\n  modifySingle(self as Instruction, (single) => {\n    const aliases = Arr.append(single.aliases, alias)\n    return makeSingle(\n      single.name,\n      aliases,\n      single.primitiveType,\n      single.description,\n      single.pseudoName\n    ) as Single\n  }))\n\n/** @internal */\nexport const withDefault = dual<\n  <const B>(fallback: B) => <A>(self: Options.Options<A>) => Options.Options<A | B>,\n  <A, const B>(self: Options.Options<A>, fallback: B) => Options.Options<A | B>\n>(2, (self, fallback) => makeWithDefault(self, fallback))\n\n/** @internal */\nexport const withFallbackConfig: {\n  <B>(config: Config.Config<B>): <A>(self: Options.Options<A>) => Options.Options<B | A>\n  <A, B>(self: Options.Options<A>, config: Config.Config<B>): Options.Options<A | B>\n} = dual<\n  <B>(config: Config.Config<B>) => <A>(self: Options.Options<A>) => Options.Options<A | B>,\n  <A, B>(self: Options.Options<A>, config: Config.Config<B>) => Options.Options<A | B>\n>(2, (self, config) => {\n  if (isInstruction(self) && isWithDefault(self)) {\n    return makeWithDefault(\n      withFallbackConfig(self.options, config),\n      self.fallback as any\n    )\n  }\n  return makeWithFallback(self, config)\n})\n\n/** @internal */\nexport const withFallbackPrompt: {\n  <B>(prompt: Prompt.Prompt<B>): <A>(self: Options.Options<A>) => Options.Options<B | A>\n  <A, B>(self: Options.Options<A>, prompt: Prompt.Prompt<B>): Options.Options<A | B>\n} = dual<\n  <B>(prompt: Prompt.Prompt<B>) => <A>(self: Options.Options<A>) => Options.Options<A | B>,\n  <A, B>(self: Options.Options<A>, prompt: Prompt.Prompt<B>) => Options.Options<A | B>\n>(2, (self, prompt) => {\n  if (isInstruction(self) && isWithDefault(self)) {\n    return makeWithDefault(\n      withFallbackPrompt(self.options, prompt),\n      self.fallback as any\n    )\n  }\n  return makeWithFallback(self, prompt)\n})\n\n/** @internal */\nexport const withDescription = dual<\n  (description: string) => <A>(self: Options.Options<A>) => Options.Options<A>,\n  <A>(self: Options.Options<A>, description: string) => Options.Options<A>\n>(2, (self, desc) =>\n  modifySingle(self as Instruction, (single) => {\n    const description = InternalHelpDoc.sequence(single.description, InternalHelpDoc.p(desc))\n    return makeSingle(\n      single.name,\n      single.aliases,\n      single.primitiveType,\n      description,\n      single.pseudoName\n    ) as Single\n  }))\n\n/** @internal */\nexport const withPseudoName = dual<\n  (pseudoName: string) => <A>(self: Options.Options<A>) => Options.Options<A>,\n  <A>(self: Options.Options<A>, pseudoName: string) => Options.Options<A>\n>(2, (self, pseudoName) =>\n  modifySingle(self as Instruction, (single) =>\n    makeSingle(\n      single.name,\n      single.aliases,\n      single.primitiveType,\n      single.description,\n      Option.some(pseudoName)\n    ) as Single))\n\n/** @internal */\nexport const withSchema = dual<\n  <A, I extends A, B>(\n    schema: Schema.Schema<B, I, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n  ) => (self: Options.Options<A>) => Options.Options<B>,\n  <A, I extends A, B>(\n    self: Options.Options<A>,\n    schema: Schema.Schema<B, I, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n  ) => Options.Options<B>\n>(2, (self, schema) => {\n  const decode = ParseResult.decode(schema)\n  return mapEffect(self, (_) =>\n    Effect.mapError(\n      decode(_ as any),\n      (issue) =>\n        InternalValidationError.invalidValue(InternalHelpDoc.p(ParseResult.TreeFormatter.formatIssueSync(issue)))\n    ))\n})\n\n/** @internal */\nexport const wizard = dual<\n  (config: CliConfig.CliConfig) => <A>(self: Options.Options<A>) => Effect.Effect<\n    Array<string>,\n    Terminal.QuitException | ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >,\n  <A>(self: Options.Options<A>, config: CliConfig.CliConfig) => Effect.Effect<\n    Array<string>,\n    Terminal.QuitException | ValidationError.ValidationError,\n    FileSystem.FileSystem | Path.Path | Terminal.Terminal\n  >\n>(2, (self, config) => wizardInternal(self as Instruction, config))\n\n// =============================================================================\n// Internals\n// =============================================================================\n\nconst allTupled = <const T extends ArrayLike<Options.Options<any>>>(arg: T): Options.Options<\n  {\n    [K in keyof T]: [T[K]] extends [Options.Options<infer A>] ? A : never\n  }\n> => {\n  if (arg.length === 0) {\n    return none as any\n  }\n  if (arg.length === 1) {\n    return map(arg[0], (x) => [x]) as any\n  }\n  let result = map(arg[0], (x) => [x])\n  for (let i = 1; i < arg.length; i++) {\n    const curr = arg[i]\n    result = map(makeBoth(result, curr), ([a, b]) => [...a, b])\n  }\n  return result as any\n}\n\nconst getHelpInternal = (self: Instruction): HelpDoc.HelpDoc => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return InternalHelpDoc.empty\n    }\n    case \"Single\": {\n      return InternalHelpDoc.descriptionList(Arr.of([\n        InternalHelpDoc.getSpan(InternalUsage.getHelp(getUsageInternal(self))),\n        InternalHelpDoc.sequence(\n          InternalHelpDoc.p(InternalPrimitive.getHelp(self.primitiveType)),\n          self.description\n        )\n      ]))\n    }\n    case \"KeyValueMap\": {\n      // Single options always have an identifier, so we can safely `getOrThrow`\n      const identifier = Option.getOrThrow(\n        getIdentifierInternal(self.argumentOption as Instruction)\n      )\n      return InternalHelpDoc.mapDescriptionList(\n        getHelpInternal(self.argumentOption as Instruction),\n        (span, oldBlock) => {\n          const header = InternalHelpDoc.p(\"This setting is a property argument which:\")\n          const single = `${identifier} key1=value key2=value2`\n          const multiple = `${identifier} key1=value ${identifier} key2=value2`\n          const description = InternalHelpDoc.enumeration([\n            InternalHelpDoc.p(`May be specified a single time:  '${single}'`),\n            InternalHelpDoc.p(`May be specified multiple times: '${multiple}'`)\n          ])\n          const newBlock = pipe(\n            oldBlock,\n            InternalHelpDoc.sequence(header),\n            InternalHelpDoc.sequence(description)\n          )\n          return [span, newBlock]\n        }\n      )\n    }\n    case \"Map\": {\n      return getHelpInternal(self.options as Instruction)\n    }\n    case \"Both\":\n    case \"OrElse\": {\n      return InternalHelpDoc.sequence(\n        getHelpInternal(self.left as Instruction),\n        getHelpInternal(self.right as Instruction)\n      )\n    }\n    case \"Variadic\": {\n      const help = getHelpInternal(self.argumentOption as Instruction)\n      return InternalHelpDoc.mapDescriptionList(help, (oldSpan, oldBlock) => {\n        const min = getMinSizeInternal(self as Instruction)\n        const max = getMaxSizeInternal(self as Instruction)\n        const newSpan = InternalSpan.text(\n          Option.isSome(self.max) ? ` ${min} - ${max}` : min === 0 ? \"...\" : ` ${min}+`\n        )\n        const newBlock = InternalHelpDoc.p(\n          Option.isSome(self.max)\n            ? `This option must be repeated at least ${min} times and may be repeated up to ${max} times.`\n            : min === 0\n            ? \"This option may be repeated zero or more times.\"\n            : `This option must be repeated at least ${min} times.`\n        )\n        return [InternalSpan.concat(oldSpan, newSpan), InternalHelpDoc.sequence(oldBlock, newBlock)]\n      })\n    }\n    case \"WithDefault\": {\n      return InternalHelpDoc.mapDescriptionList(\n        getHelpInternal(self.options as Instruction),\n        (span, block) => {\n          const optionalDescription = Option.isOption(self.fallback)\n            ? Option.match(self.fallback, {\n              onNone: () => InternalHelpDoc.p(\"This setting is optional.\"),\n              onSome: (fallbackValue) => {\n                const inspectableValue = Predicate.isObject(fallbackValue) ? fallbackValue : String(fallbackValue)\n                const displayValue = Inspectable.toStringUnknown(inspectableValue, 0)\n                return InternalHelpDoc.p(`This setting is optional. Defaults to: ${displayValue}`)\n              }\n            })\n            : InternalHelpDoc.p(\"This setting is optional.\")\n          return [span, InternalHelpDoc.sequence(block, optionalDescription)]\n        }\n      )\n    }\n    case \"WithFallback\": {\n      const helpDoc: HelpDoc.HelpDoc = Config.isConfig(self.effect)\n        ? InternalHelpDoc.p(\"This option can be set from environment variables.\")\n        : InternalPrompt.isPrompt(self.effect)\n        ? InternalHelpDoc.p(\"Will prompt the user for input if this option is not provided.\")\n        : InternalHelpDoc.empty\n      return InternalHelpDoc.mapDescriptionList(\n        getHelpInternal(self.options as Instruction),\n        (span, block) => [span, InternalHelpDoc.sequence(block, helpDoc)]\n      )\n    }\n  }\n}\n\nconst getIdentifierInternal = (self: Instruction): Option.Option<string> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Option.none()\n    }\n    case \"Single\": {\n      return Option.some(self.fullName)\n    }\n    case \"Both\":\n    case \"OrElse\": {\n      const ids = Arr.getSomes([\n        getIdentifierInternal(self.left as Instruction),\n        getIdentifierInternal(self.right as Instruction)\n      ])\n      return Arr.match(ids, {\n        onEmpty: () => Option.none(),\n        onNonEmpty: (ids) => Option.some(Arr.join(ids, \", \"))\n      })\n    }\n    case \"KeyValueMap\":\n    case \"Variadic\": {\n      return getIdentifierInternal(self.argumentOption as Instruction)\n    }\n    case \"Map\":\n    case \"WithFallback\":\n    case \"WithDefault\": {\n      return getIdentifierInternal(self.options as Instruction)\n    }\n  }\n}\n\nconst getMinSizeInternal = (self: Instruction): number => {\n  switch (self._tag) {\n    case \"Empty\":\n    case \"WithDefault\":\n    case \"WithFallback\": {\n      return 0\n    }\n    case \"Single\":\n    case \"KeyValueMap\": {\n      return 1\n    }\n    case \"Map\": {\n      return getMinSizeInternal(self.options as Instruction)\n    }\n    case \"Both\": {\n      const leftMinSize = getMinSizeInternal(self.left as Instruction)\n      const rightMinSize = getMinSizeInternal(self.right as Instruction)\n      return leftMinSize + rightMinSize\n    }\n    case \"OrElse\": {\n      const leftMinSize = getMinSizeInternal(self.left as Instruction)\n      const rightMinSize = getMinSizeInternal(self.right as Instruction)\n      return Math.min(leftMinSize, rightMinSize)\n    }\n    case \"Variadic\": {\n      const selfMinSize = Option.getOrElse(self.min, () => 0)\n      const argumentOptionMinSize = getMinSizeInternal(self.argumentOption as Instruction)\n      return selfMinSize * argumentOptionMinSize\n    }\n  }\n}\n\nconst getMaxSizeInternal = (self: Instruction): number => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return 0\n    }\n    case \"Single\": {\n      return 1\n    }\n    case \"KeyValueMap\": {\n      return Number.MAX_SAFE_INTEGER\n    }\n    case \"Map\":\n    case \"WithDefault\":\n    case \"WithFallback\": {\n      return getMaxSizeInternal(self.options as Instruction)\n    }\n    case \"Both\": {\n      const leftMaxSize = getMaxSizeInternal(self.left as Instruction)\n      const rightMaxSize = getMaxSizeInternal(self.right as Instruction)\n      return leftMaxSize + rightMaxSize\n    }\n    case \"OrElse\": {\n      const leftMin = getMaxSizeInternal(self.left as Instruction)\n      const rightMin = getMaxSizeInternal(self.right as Instruction)\n      return Math.min(leftMin, rightMin)\n    }\n    case \"Variadic\": {\n      const selfMaxSize = Option.getOrElse(self.max, () => Number.MAX_SAFE_INTEGER / 2)\n      const optionsMaxSize = getMaxSizeInternal(self.argumentOption as Instruction)\n      return Math.floor(selfMaxSize * optionsMaxSize)\n    }\n  }\n}\n\nconst getUsageInternal = (self: Instruction): Usage.Usage => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return InternalUsage.empty\n    }\n    case \"Single\": {\n      const acceptedValues = InternalPrimitive.isBool(self.primitiveType)\n        ? Option.none()\n        : Option.orElse(\n          InternalPrimitive.getChoices(self.primitiveType),\n          () => Option.some(self.placeholder)\n        )\n      return InternalUsage.named(getNames(self), acceptedValues)\n    }\n    case \"KeyValueMap\": {\n      return getUsageInternal(self.argumentOption as Instruction)\n    }\n    case \"Map\": {\n      return getUsageInternal(self.options as Instruction)\n    }\n    case \"Both\": {\n      return InternalUsage.concat(\n        getUsageInternal(self.left as Instruction),\n        getUsageInternal(self.right as Instruction)\n      )\n    }\n    case \"OrElse\": {\n      return InternalUsage.alternation(\n        getUsageInternal(self.left as Instruction),\n        getUsageInternal(self.right as Instruction)\n      )\n    }\n    case \"Variadic\": {\n      return InternalUsage.repeated(getUsageInternal(self.argumentOption as Instruction))\n    }\n    case \"WithDefault\":\n    case \"WithFallback\": {\n      return InternalUsage.optional(getUsageInternal(self.options as Instruction))\n    }\n  }\n}\n\nconst isBoolInternal = (self: Instruction): boolean => {\n  switch (self._tag) {\n    case \"Single\": {\n      return InternalPrimitive.isBool(self.primitiveType)\n    }\n    case \"Map\": {\n      return isBoolInternal(self.options as Instruction)\n    }\n    case \"WithDefault\": {\n      return isBoolInternal(self.options as Instruction)\n    }\n    default: {\n      return false\n    }\n  }\n}\n\nconst makeBoth = <A, B>(\n  left: Options.Options<A>,\n  right: Options.Options<B>\n): Options.Options<[A, B]> => {\n  const op = Object.create(proto)\n  op._tag = \"Both\"\n  op.left = left\n  op.right = right\n  return op\n}\n\nconst makeFullName = (str: string): [boolean, string] => str.length === 1 ? [true, `-${str}`] : [false, `--${str}`]\n\nconst makeKeyValueMap = (\n  argumentOption: Single\n): Options.Options<HashMap.HashMap<string, string>> => {\n  const op = Object.create(proto)\n  op._tag = \"KeyValueMap\"\n  op.argumentOption = argumentOption\n  return op\n}\n\nconst makeMap = <A, B>(\n  options: Options.Options<A>,\n  f: (a: A) => Effect.Effect<B, ValidationError.ValidationError, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n): Options.Options<B> => {\n  const op = Object.create(proto)\n  op._tag = \"Map\"\n  op.options = options\n  op.f = f\n  return op\n}\n\nconst makeOrElse = <A, B>(\n  left: Options.Options<A>,\n  right: Options.Options<B>\n): Options.Options<Either.Either<B, A>> => {\n  const op = Object.create(proto)\n  op._tag = \"OrElse\"\n  op.left = left\n  op.right = right\n  return op\n}\n\nconst makeSingle = <A>(\n  name: string,\n  aliases: ReadonlyArray<string>,\n  primitiveType: Primitive.Primitive<A>,\n  description: HelpDoc.HelpDoc = InternalHelpDoc.empty,\n  pseudoName: Option.Option<string> = Option.none()\n): Options.Options<A> => {\n  const op = Object.create(proto)\n  op._tag = \"Single\"\n  op.name = name\n  op.fullName = makeFullName(name)[1]\n  op.placeholder = `${Option.getOrElse(pseudoName, () => InternalPrimitive.getTypeName(primitiveType))}`\n  op.aliases = aliases\n  op.primitiveType = primitiveType\n  op.description = description\n  op.pseudoName = pseudoName\n  return op\n}\n\nconst makeVariadic = <A>(\n  argumentOption: Options.Options<A>,\n  min: Option.Option<number>,\n  max: Option.Option<number>\n): Options.Options<Array<A>> => {\n  if (!isSingle(argumentOption as Instruction)) {\n    throw new Error(\"InvalidArgumentException: only single options can be variadic\")\n  }\n  const op = Object.create(proto)\n  op._tag = \"Variadic\"\n  op.argumentOption = argumentOption\n  op.min = min\n  op.max = max\n  return op\n}\n\nconst makeWithDefault = <A, const B>(\n  options: Options.Options<A>,\n  fallback: B\n): Options.Options<A | B> => {\n  const op = Object.create(proto)\n  op._tag = \"WithDefault\"\n  op.options = options\n  op.fallback = fallback\n  return op\n}\n\nconst makeWithFallback = <A, B>(\n  options: Options.Options<A>,\n  effect: Effect.Effect<B, unknown, FileSystem.FileSystem | Path.Path | Terminal.Terminal>\n): Options.Options<A | B> => {\n  const op = Object.create(proto)\n  op._tag = \"WithFallback\"\n  op.options = options\n  op.effect = effect\n  return op\n}\n\nconst modifySingle = (self: Instruction, f: (single: Single) => Single): Options.Options<any> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return none\n    }\n    case \"Single\": {\n      return f(self)\n    }\n    case \"KeyValueMap\": {\n      return makeKeyValueMap(f(self.argumentOption))\n    }\n    case \"Map\": {\n      return makeMap(modifySingle(self.options as Instruction, f), self.f)\n    }\n    case \"Both\": {\n      return makeBoth(\n        modifySingle(self.left as Instruction, f),\n        modifySingle(self.right as Instruction, f)\n      )\n    }\n    case \"OrElse\": {\n      return makeOrElse(\n        modifySingle(self.left as Instruction, f),\n        modifySingle(self.right as Instruction, f)\n      )\n    }\n    case \"Variadic\": {\n      return makeVariadic(f(self.argumentOption), self.min, self.max)\n    }\n    case \"WithDefault\": {\n      return makeWithDefault(modifySingle(self.options as Instruction, f), self.fallback)\n    }\n    case \"WithFallback\": {\n      return makeWithFallback(\n        modifySingle(self.options as Instruction, f),\n        self.effect\n      )\n    }\n  }\n}\n\n/** @internal */\nexport const getNames = (self: Instruction): Array<string> => {\n  const loop = (self: Instruction): ReadonlyArray<string> => {\n    switch (self._tag) {\n      case \"Empty\": {\n        return Arr.empty()\n      }\n      case \"Single\": {\n        return Arr.prepend(self.aliases, self.name)\n      }\n      case \"KeyValueMap\":\n      case \"Variadic\": {\n        return loop(self.argumentOption as Instruction)\n      }\n      case \"Map\":\n      case \"WithDefault\":\n      case \"WithFallback\": {\n        return loop(self.options as Instruction)\n      }\n      case \"Both\":\n      case \"OrElse\": {\n        const left = loop(self.left as Instruction)\n        const right = loop(self.right as Instruction)\n        return Arr.appendAll(left, right)\n      }\n    }\n  }\n  const order = Order.mapInput(\n    Order.boolean,\n    (tuple: [boolean, string]) => !tuple[0]\n  )\n  return pipe(\n    loop(self),\n    Arr.map((str) => makeFullName(str)),\n    Arr.sort(order),\n    Arr.map((tuple) => tuple[1])\n  )\n}\n\nconst toParseableInstruction = (self: Instruction): Array<ParseableInstruction> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Arr.empty()\n    }\n    case \"Single\":\n    case \"KeyValueMap\":\n    case \"Variadic\": {\n      return Arr.of(self)\n    }\n    case \"Map\":\n    case \"WithDefault\":\n    case \"WithFallback\": {\n      return toParseableInstruction(self.options as Instruction)\n    }\n    case \"Both\":\n    case \"OrElse\": {\n      return Arr.appendAll(\n        toParseableInstruction(self.left as Instruction),\n        toParseableInstruction(self.right as Instruction)\n      )\n    }\n  }\n}\n\n/** @internal */\nconst keyValueSplitter = /=(.*)/\n\nconst parseInternal = (\n  self: Instruction,\n  args: HashMap.HashMap<string, ReadonlyArray<string>>,\n  config: CliConfig.CliConfig\n): Effect.Effect<\n  unknown,\n  ValidationError.ValidationError,\n  FileSystem.FileSystem | Path.Path | Terminal.Terminal\n> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Effect.void\n    }\n    case \"Single\": {\n      const singleNames = Arr.filterMap(getNames(self), (name) => HashMap.get(args, name))\n      if (Arr.isNonEmptyReadonlyArray(singleNames)) {\n        const head = Arr.headNonEmpty(singleNames)\n        const tail = Arr.tailNonEmpty(singleNames)\n        if (Arr.isEmptyReadonlyArray(tail)) {\n          if (Arr.isEmptyReadonlyArray(head)) {\n            return InternalPrimitive.validate(self.primitiveType, Option.none(), config).pipe(\n              Effect.mapError((e) => InternalValidationError.invalidValue(InternalHelpDoc.p(e)))\n            )\n          }\n          if (\n            Arr.isNonEmptyReadonlyArray(head) &&\n            Arr.isEmptyReadonlyArray(Arr.tailNonEmpty(head))\n          ) {\n            const value = Arr.headNonEmpty(head)\n            return InternalPrimitive.validate(self.primitiveType, Option.some(value), config).pipe(\n              Effect.mapError((e) => InternalValidationError.invalidValue(InternalHelpDoc.p(e)))\n            )\n          }\n          return Effect.fail(\n            InternalValidationError.multipleValuesDetected(InternalHelpDoc.empty, head)\n          )\n        }\n        const error = InternalHelpDoc.p(\n          `More than one reference to option '${self.fullName}' detected`\n        )\n        return Effect.fail(InternalValidationError.invalidValue(error))\n      }\n      const error = InternalHelpDoc.p(`Expected to find option: '${self.fullName}'`)\n      return Effect.fail(InternalValidationError.missingValue(error))\n    }\n    case \"KeyValueMap\": {\n      const extractKeyValue = (\n        value: string\n      ): Effect.Effect<[string, string], ValidationError.ValidationError> => {\n        const split = value.trim().split(keyValueSplitter, 2)\n        if (Arr.isNonEmptyReadonlyArray(split) && split.length === 2 && split[1] !== \"\") {\n          return Effect.succeed(split as unknown as [string, string])\n        }\n        const error = InternalHelpDoc.p(`Expected a key/value pair but received '${value}'`)\n        return Effect.fail(InternalValidationError.invalidArgument(error))\n      }\n      return parseInternal(self.argumentOption, args, config).pipe(Effect.matchEffect({\n        onFailure: (e) =>\n          InternalValidationError.isMultipleValuesDetected(e)\n            ? Effect.forEach(e.values, (kv) => extractKeyValue(kv)).pipe(\n              Effect.map(HashMap.fromIterable)\n            )\n            : Effect.fail(e),\n        onSuccess: (kv) => extractKeyValue(kv as string).pipe(Effect.map(HashMap.make))\n      }))\n    }\n    case \"Map\": {\n      return parseInternal(self.options as Instruction, args, config).pipe(\n        Effect.flatMap((a) => self.f(a))\n      )\n    }\n    case \"Both\": {\n      return parseInternal(self.left as Instruction, args, config).pipe(\n        Effect.catchAll((err1) =>\n          parseInternal(self.right as Instruction, args, config).pipe(Effect.matchEffect({\n            onFailure: (err2) => {\n              const error = InternalHelpDoc.sequence(err1.error, err2.error)\n              return Effect.fail(InternalValidationError.missingValue(error))\n            },\n            onSuccess: () => Effect.fail(err1)\n          }))\n        ),\n        Effect.zip(parseInternal(self.right as Instruction, args, config))\n      )\n    }\n    case \"OrElse\": {\n      return parseInternal(self.left as Instruction, args, config).pipe(\n        Effect.matchEffect({\n          onFailure: (err1) =>\n            parseInternal(self.right as Instruction, args, config).pipe(\n              Effect.mapBoth({\n                onFailure: (err2) =>\n                  // orElse option is only missing in case neither option was given\n                  InternalValidationError.isMissingValue(err1) &&\n                    InternalValidationError.isMissingValue(err2)\n                    ? InternalValidationError.missingValue(\n                      InternalHelpDoc.sequence(err1.error, err2.error)\n                    )\n                    : InternalValidationError.invalidValue(\n                      InternalHelpDoc.sequence(err1.error, err2.error)\n                    ),\n                onSuccess: (b) => Either.right(b)\n              })\n            ),\n          onSuccess: (a) =>\n            parseInternal(self.right as Instruction, args, config).pipe(Effect.matchEffect({\n              onFailure: () => Effect.succeed(Either.left(a)),\n              onSuccess: () => {\n                // The `identifier` will only be `None` for `Options.Empty`, which\n                // means the user would have had to purposefully compose\n                // `Options.Empty | otherArgument`\n                const leftUid = Option.getOrElse(\n                  getIdentifierInternal(self.left as Instruction),\n                  () => \"???\"\n                )\n                const rightUid = Option.getOrElse(\n                  getIdentifierInternal(self.right as Instruction),\n                  () => \"???\"\n                )\n                const error = InternalHelpDoc.p(\n                  \"Collision between two options detected - you can only specify \" +\n                    `one of either: ['${leftUid}', '${rightUid}']`\n                )\n                return Effect.fail(InternalValidationError.invalidValue(error))\n              }\n            }))\n        })\n      )\n    }\n    case \"Variadic\": {\n      const min = Option.getOrElse(self.min, () => 0)\n      const max = Option.getOrElse(self.max, () => Number.MAX_SAFE_INTEGER)\n      const matchedArgument = Arr.filterMap(getNames(self), (name) => HashMap.get(args, name))\n      const validateMinMax = (values: ReadonlyArray<string>) => {\n        if (values.length < min) {\n          const name = self.argumentOption.fullName\n          const error = `Expected at least ${min} value(s) for option: '${name}'`\n          return Effect.fail(InternalValidationError.invalidValue(InternalHelpDoc.p(error)))\n        }\n        if (values.length > max) {\n          const name = self.argumentOption.fullName\n          const error = `Expected at most ${max} value(s) for option: '${name}'`\n          return Effect.fail(InternalValidationError.invalidValue(InternalHelpDoc.p(error)))\n        }\n        const primitive = self.argumentOption.primitiveType\n        const validatePrimitive = (value: string) =>\n          InternalPrimitive.validate(primitive, Option.some(value), config).pipe(\n            Effect.mapError((e) => InternalValidationError.invalidValue(InternalHelpDoc.p(e)))\n          )\n        return Effect.forEach(values, (value) => validatePrimitive(value))\n      }\n      // If we did not receive any variadic arguments then perform the bounds\n      // checks with an empty array\n      if (Arr.every(matchedArgument, Arr.isEmptyReadonlyArray)) {\n        return validateMinMax(Arr.empty())\n      }\n      return parseInternal(self.argumentOption, args, config).pipe(Effect.matchEffect({\n        onFailure: (error) =>\n          InternalValidationError.isMultipleValuesDetected(error)\n            ? validateMinMax(error.values)\n            : Effect.fail(error),\n        onSuccess: (value) => validateMinMax(Arr.of(value as string))\n      }))\n    }\n    case \"WithDefault\": {\n      return parseInternal(self.options as Instruction, args, config).pipe(\n        Effect.catchTag(\"MissingValue\", () => Effect.succeed(self.fallback))\n      )\n    }\n    case \"WithFallback\": {\n      return parseInternal(self.options as Instruction, args, config).pipe(\n        Effect.catchTag(\"MissingValue\", (e) =>\n          self.effect.pipe(Effect.catchAll((e2) => {\n            if (Predicate.isTagged(e2, \"QuitException\")) {\n              return Effect.die(e2)\n            }\n            if (ConfigError.isConfigError(e2) && !ConfigError.isMissingDataOnly(e2)) {\n              const help = InternalHelpDoc.p(String(e2))\n              const error = InternalValidationError.invalidValue(help)\n              return Effect.fail(error)\n            }\n            return Effect.fail(e)\n          })))\n      )\n    }\n  }\n}\n\nconst wizardInternal = (self: Instruction, config: CliConfig.CliConfig): Effect.Effect<\n  Array<string>,\n  Terminal.QuitException | ValidationError.ValidationError,\n  FileSystem.FileSystem | Path.Path | Terminal.Terminal\n> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Effect.succeed(Arr.empty())\n    }\n    case \"Single\": {\n      const help = getHelpInternal(self)\n      return InternalPrimitive.wizard(self.primitiveType, help).pipe(\n        Effect.flatMap((input) => {\n          // There will always be at least one name in names\n          const args = Arr.make(getNames(self)[0]!, input as string)\n          return parseCommandLine(self, args, config).pipe(Effect.as(args))\n        }),\n        Effect.zipLeft(Console.log())\n      )\n    }\n    case \"KeyValueMap\": {\n      const message = InternalHelpDoc.p(\"Enter `key=value` pairs separated by spaces\")\n      return InternalListPrompt.list({\n        message: InternalHelpDoc.toAnsiText(message).trim(),\n        delimiter: \" \"\n      }).pipe(\n        Effect.flatMap((args) => {\n          const identifier = Option.getOrElse(getIdentifierInternal(self), () => \"\")\n          return parseInternal(self, HashMap.make([identifier, args]), config).pipe(\n            Effect.as(Arr.prepend(args, identifier))\n          )\n        }),\n        Effect.zipLeft(Console.log())\n      )\n    }\n    case \"Map\": {\n      return wizardInternal(self.options as Instruction, config)\n    }\n    case \"Both\": {\n      return Effect.zipWith(\n        wizardInternal(self.left as Instruction, config),\n        wizardInternal(self.right as Instruction, config),\n        (left, right) => Arr.appendAll(left, right)\n      )\n    }\n    case \"OrElse\": {\n      const alternativeHelp = InternalHelpDoc.p(\"Select which option you would like to use\")\n      const message = pipe(\n        getHelpInternal(self),\n        InternalHelpDoc.sequence(alternativeHelp)\n      )\n      const makeChoice = (title: string, value: Instruction) => ({ title, value })\n      const choices = Arr.getSomes([\n        Option.map(\n          getIdentifierInternal(self.left as Instruction),\n          (title) => makeChoice(title, self.left as Instruction)\n        ),\n        Option.map(\n          getIdentifierInternal(self.right as Instruction),\n          (title) => makeChoice(title, self.right as Instruction)\n        )\n      ])\n      return InternalSelectPrompt.select({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd(),\n        choices\n      }).pipe(Effect.flatMap((option) => wizardInternal(option, config)))\n    }\n    case \"Variadic\": {\n      const repeatHelp = InternalHelpDoc.p(\n        \"How many times should this argument be repeated?\"\n      )\n      const message = pipe(\n        getHelpInternal(self),\n        InternalHelpDoc.sequence(repeatHelp)\n      )\n      return InternalNumberPrompt.integer({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd(),\n        min: getMinSizeInternal(self),\n        max: getMaxSizeInternal(self)\n      }).pipe(\n        Effect.flatMap((n) =>\n          n <= 0\n            ? Effect.succeed(Arr.empty<string>())\n            : Ref.make(Arr.empty<string>()).pipe(\n              Effect.flatMap((ref) =>\n                wizardInternal(self.argumentOption as Instruction, config).pipe(\n                  Effect.flatMap((args) => Ref.update(ref, Arr.appendAll(args))),\n                  Effect.repeatN(n - 1),\n                  Effect.zipRight(Ref.get(ref))\n                )\n              )\n            )\n        )\n      )\n    }\n    case \"WithDefault\": {\n      if (isBoolInternal(self.options as Instruction)) {\n        return wizardInternal(self.options as Instruction, config)\n      }\n      const defaultHelp = InternalHelpDoc.p(`This option is optional - use the default?`)\n      const message = pipe(\n        getHelpInternal(self.options as Instruction),\n        InternalHelpDoc.sequence(defaultHelp)\n      )\n      return InternalSelectPrompt.select({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd(),\n        choices: [\n          {\n            title: \"Yes\",\n            value: true,\n            description: `use the default ${\n              Option.isOption(self.fallback)\n                ? Option.match(self.fallback, {\n                  onNone: () => \"\",\n                  onSome: (a) => `(${JSON.stringify(a)})`\n                })\n                : `(${JSON.stringify(self.fallback)})`\n            }`\n          },\n          { title: \"No\", value: false, description: \"use a custom value\" }\n        ]\n      }).pipe(\n        Effect.zipLeft(Console.log()),\n        Effect.flatMap((useFallback) =>\n          useFallback\n            ? Effect.succeed(Arr.empty())\n            : wizardInternal(self.options as Instruction, config)\n        )\n      )\n    }\n    case \"WithFallback\": {\n      if (isBoolInternal(self.options as Instruction)) {\n        return wizardInternal(self.options as Instruction, config)\n      }\n      // TODO: should we use the prompt directly here?\n      if (InternalPrompt.isPrompt(self.effect)) {\n        return wizardInternal(self.options as Instruction, config)\n      }\n      const defaultHelp = InternalHelpDoc.p(`Try load this option from the environment?`)\n      const message = pipe(\n        getHelpInternal(self.options as Instruction),\n        InternalHelpDoc.sequence(defaultHelp)\n      )\n      return InternalSelectPrompt.select({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd(),\n        choices: [\n          { title: `Use environment variables`, value: true },\n          { title: \"Custom\", value: false }\n        ]\n      }).pipe(\n        Effect.zipLeft(Console.log()),\n        Effect.flatMap((useFallback) =>\n          useFallback\n            ? Effect.succeed(Arr.empty())\n            : wizardInternal(self.options as Instruction, config)\n        )\n      )\n    }\n  }\n}\n\n// =============================================================================\n// Parsing Internals\n// =============================================================================\n\n/**\n * Returns a possible `ValidationError` when parsing the commands, leftover\n * arguments from `input` and a mapping between each flag and its values.\n */\nconst matchOptions = (\n  input: ReadonlyArray<string>,\n  options: ReadonlyArray<ParseableInstruction>,\n  config: CliConfig.CliConfig\n): Effect.Effect<\n  [\n    Option.Option<ValidationError.ValidationError>,\n    ReadonlyArray<string>,\n    HashMap.HashMap<string, ReadonlyArray<string>>\n  ]\n> => {\n  if (Arr.isNonEmptyReadonlyArray(options)) {\n    return findOptions(input, options, config).pipe(\n      Effect.flatMap(([otherArgs, otherOptions, map1]) => {\n        if (HashMap.isEmpty(map1)) {\n          return Effect.succeed([Option.none(), input, map1] as [\n            Option.Option<ValidationError.ValidationError>,\n            ReadonlyArray<string>,\n            HashMap.HashMap<string, ReadonlyArray<string>>\n          ])\n        }\n        return matchOptions(otherArgs, otherOptions, config).pipe(\n          Effect.map(([error, otherArgs, map2]) =>\n            [error, otherArgs, merge(map1, Arr.fromIterable(map2))] as [\n              Option.Option<ValidationError.ValidationError>,\n              ReadonlyArray<string>,\n              HashMap.HashMap<string, ReadonlyArray<string>>\n            ]\n          )\n        )\n      }),\n      Effect.catchAll((e) =>\n        Effect.succeed([Option.some(e), input, HashMap.empty()] as [\n          Option.Option<ValidationError.ValidationError>,\n          ReadonlyArray<string>,\n          HashMap.HashMap<string, ReadonlyArray<string>>\n        ])\n      )\n    )\n  }\n  return Arr.isEmptyReadonlyArray(input)\n    ? Effect.succeed([Option.none(), Arr.empty(), HashMap.empty()] as [\n      Option.Option<ValidationError.ValidationError>,\n      ReadonlyArray<string>,\n      HashMap.HashMap<string, ReadonlyArray<string>>\n    ])\n    : Effect.succeed([Option.none(), input, HashMap.empty()] as [\n      Option.Option<ValidationError.ValidationError>,\n      ReadonlyArray<string>,\n      HashMap.HashMap<string, ReadonlyArray<string>>\n    ])\n}\n\n/**\n * Returns the leftover arguments, leftover options, and a mapping between the\n * first argument with its values if it corresponds to an option flag.\n */\nconst findOptions = (\n  input: ReadonlyArray<string>,\n  options: ReadonlyArray<ParseableInstruction>,\n  config: CliConfig.CliConfig\n): Effect.Effect<\n  [\n    ReadonlyArray<string>,\n    ReadonlyArray<ParseableInstruction>,\n    HashMap.HashMap<string, ReadonlyArray<string>>\n  ],\n  ValidationError.ValidationError\n> =>\n  Arr.matchLeft(options, {\n    onEmpty: () => Effect.succeed([input, Arr.empty(), HashMap.empty()]),\n    onNonEmpty: (head, tail) =>\n      parseCommandLine(head, input, config).pipe(\n        Effect.flatMap(({ leftover, parsed }) =>\n          Option.match(parsed, {\n            onNone: () =>\n              findOptions(leftover, tail, config).pipe(Effect.map(([nextArgs, nextOptions, map]) =>\n                [nextArgs, Arr.prepend(nextOptions, head), map] as [\n                  ReadonlyArray<string>,\n                  ReadonlyArray<ParseableInstruction>,\n                  HashMap.HashMap<string, ReadonlyArray<string>>\n                ]\n              )),\n            onSome: ({ name, values }) =>\n              Effect.succeed([leftover, tail, HashMap.make([name, values])] as [\n                ReadonlyArray<string>,\n                ReadonlyArray<ParseableInstruction>,\n                HashMap.HashMap<string, ReadonlyArray<string>>\n              ])\n          })\n        ),\n        Effect.catchTags({\n          CorrectedFlag: (e) =>\n            findOptions(input, tail, config).pipe(\n              Effect.catchSome(() => Option.some(Effect.fail(e))),\n              Effect.flatMap(([otherArgs, otherOptions, map]) =>\n                Effect.fail(e).pipe(\n                  Effect.when(() => HashMap.isEmpty(map)),\n                  Effect.as([otherArgs, Arr.prepend(otherOptions, head), map] as [\n                    ReadonlyArray<string>,\n                    ReadonlyArray<ParseableInstruction>,\n                    HashMap.HashMap<string, ReadonlyArray<string>>\n                  ])\n                )\n              )\n            ),\n          MissingFlag: () =>\n            findOptions(input, tail, config).pipe(\n              Effect.map(([otherArgs, otherOptions, map]) =>\n                [otherArgs, Arr.prepend(otherOptions, head), map] as [\n                  ReadonlyArray<string>,\n                  ReadonlyArray<ParseableInstruction>,\n                  HashMap.HashMap<string, ReadonlyArray<string>>\n                ]\n              )\n            ),\n          UnclusteredFlag: (e) =>\n            matchUnclustered(e.unclustered, e.rest, options, config).pipe(\n              Effect.catchAll(() => Effect.fail(e))\n            )\n        })\n      )\n  })\n\ninterface ParsedCommandLine {\n  readonly parsed: Option.Option<{\n    readonly name: string\n    readonly values: ReadonlyArray<string>\n  }>\n  readonly leftover: ReadonlyArray<string>\n}\n\nconst CLUSTERED_REGEX = /^-{1}([^-]{2,}$)/\nconst FLAG_REGEX = /^(--[^=]+)(?:=(.+))?$/\n\n/**\n * Normalizes the leading command-line argument by performing the following:\n *   1. If a clustered series of short command-line options is encountered,\n *      uncluster the options and return a `ValidationError.UnclusteredFlag`\n *      to be handled later on in the parsing algorithm\n *   2. If a long command-line option with a value is encountered, ensure that\n *      the option and it's value are separated (i.e. `--option=value` becomes\n *      [\"--option\", \"value\"])\n */\nconst processArgs = (\n  args: ReadonlyArray<string>\n): Effect.Effect<ReadonlyArray<string>, ValidationError.ValidationError> =>\n  Arr.matchLeft(args, {\n    onEmpty: () => Effect.succeed(Arr.empty()),\n    onNonEmpty: (head, tail) => {\n      const value = head.trim()\n      // Attempt to match clustered short command-line arguments (i.e. `-abc`)\n      if (CLUSTERED_REGEX.test(value)) {\n        const unclustered = value.substring(1).split(\"\").map((c) => `-${c}`)\n        return Effect.fail(InternalValidationError.unclusteredFlag(\n          InternalHelpDoc.empty,\n          unclustered,\n          tail\n        ))\n      }\n      // Attempt to match a long command-line argument and ensure the option and\n      // it's value have been separated and added back to the arguments\n      if (FLAG_REGEX.test(value)) {\n        const result = FLAG_REGEX.exec(value)\n        if (result !== null && result[2] !== undefined) {\n          return Effect.succeed<ReadonlyArray<string>>(\n            Arr.appendAll([result[1], result[2]], tail)\n          )\n        }\n      }\n      // Otherwise return the original command-line arguments\n      return Effect.succeed(args)\n    }\n  })\n\n/**\n * Processes the command-line arguments for a parseable option, returning the\n * parsed command line results, which inclue:\n *   - The name of the option and its associated value(s), if any\n *   - Any leftover command-line arguments\n */\nconst parseCommandLine = (\n  self: ParseableInstruction,\n  args: ReadonlyArray<string>,\n  config: CliConfig.CliConfig\n): Effect.Effect<ParsedCommandLine, ValidationError.ValidationError> => {\n  switch (self._tag) {\n    case \"Single\": {\n      return processArgs(args).pipe(Effect.flatMap((args) =>\n        Arr.matchLeft(args, {\n          onEmpty: () => {\n            const error = InternalHelpDoc.p(`Expected to find option: '${self.fullName}'`)\n            return Effect.fail(InternalValidationError.missingFlag(error))\n          },\n          onNonEmpty: (head, tail) => {\n            const normalize = (value: string) => InternalCliConfig.normalizeCase(config, value)\n            const normalizedHead = normalize(head)\n            const normalizedNames = Arr.map(getNames(self), (name) => normalize(name))\n\n            if (Arr.contains(normalizedNames, normalizedHead)) {\n              if (InternalPrimitive.isBool(self.primitiveType)) {\n                return Arr.matchLeft(tail, {\n                  onEmpty: () => {\n                    const parsed = Option.some({ name: head, values: Arr.empty() })\n                    return Effect.succeed({ parsed, leftover: tail })\n                  },\n                  onNonEmpty: (value, leftover) => {\n                    if (InternalPrimitive.isTrueValue(value)) {\n                      const parsed = Option.some({ name: head, values: Arr.of(\"true\") })\n                      return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n                    }\n                    if (InternalPrimitive.isFalseValue(value)) {\n                      const parsed = Option.some({ name: head, values: Arr.of(\"false\") })\n                      return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n                    }\n                    const parsed = Option.some({ name: head, values: Arr.empty() })\n                    return Effect.succeed<ParsedCommandLine>({ parsed, leftover: tail })\n                  }\n                })\n              }\n              return Arr.matchLeft(tail, {\n                onEmpty: () => {\n                  const error = InternalHelpDoc.p(\n                    `Expected a value following option: '${self.fullName}'`\n                  )\n                  return Effect.fail(InternalValidationError.missingValue(error))\n                },\n                onNonEmpty: (value, leftover) => {\n                  const parsed = Option.some({ name: head, values: Arr.of(value) })\n                  return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n                }\n              })\n            }\n\n            if (head.startsWith(\"-\")) {\n              if (\n                self.name.length > config.autoCorrectLimit + 1 &&\n                InternalAutoCorrect.levensteinDistance(head, self.fullName, config) <=\n                  config.autoCorrectLimit\n              ) {\n                const error = InternalHelpDoc.p(\n                  `The flag '${head}' is not recognized. Did you mean '${self.fullName}'?`\n                )\n                return Effect.fail(InternalValidationError.correctedFlag(error))\n              }\n              const error = InternalHelpDoc.p(`Expected to find option: '${self.fullName}'`)\n              return Effect.fail(InternalValidationError.missingFlag(error))\n            }\n\n            let optionIndex = -1\n            let equalsValue: string | undefined = undefined\n            for (let i = 0; i < tail.length; i++) {\n              const arg = tail[i]\n              const normalizedArg = normalize(arg)\n              if (Arr.contains(normalizedNames, normalizedArg)) {\n                optionIndex = i\n                break\n              }\n              const flagMatch = FLAG_REGEX.exec(arg)\n              if (flagMatch !== null) {\n                const normalizedFlag = normalize(flagMatch[1])\n                if (Arr.contains(normalizedNames, normalizedFlag)) {\n                  optionIndex = i\n                  equalsValue = flagMatch[2]\n                  break\n                }\n              }\n            }\n\n            if (optionIndex === -1) {\n              const error = InternalHelpDoc.p(`Expected to find option: '${self.fullName}'`)\n              return Effect.fail(InternalValidationError.missingFlag(error))\n            }\n\n            const rawArg = tail[optionIndex]\n            const optionName = equalsValue !== undefined ? FLAG_REGEX.exec(rawArg)![1] : rawArg\n            const beforeOption = Arr.prepend(tail.slice(0, optionIndex), head)\n            const afterOption = tail.slice(optionIndex + 1)\n\n            if (InternalPrimitive.isBool(self.primitiveType)) {\n              if (equalsValue !== undefined) {\n                if (InternalPrimitive.isTrueValue(equalsValue)) {\n                  const parsed = Option.some({ name: optionName, values: Arr.of(\"true\") })\n                  const leftover = Arr.appendAll(beforeOption, afterOption)\n                  return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n                }\n                if (InternalPrimitive.isFalseValue(equalsValue)) {\n                  const parsed = Option.some({ name: optionName, values: Arr.of(\"false\") })\n                  const leftover = Arr.appendAll(beforeOption, afterOption)\n                  return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n                }\n              }\n              if (afterOption.length > 0) {\n                const nextValue = afterOption[0]\n                if (InternalPrimitive.isTrueValue(nextValue)) {\n                  const parsed = Option.some({ name: optionName, values: Arr.of(\"true\") })\n                  const leftover = Arr.appendAll(beforeOption, afterOption.slice(1))\n                  return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n                }\n                if (InternalPrimitive.isFalseValue(nextValue)) {\n                  const parsed = Option.some({ name: optionName, values: Arr.of(\"false\") })\n                  const leftover = Arr.appendAll(beforeOption, afterOption.slice(1))\n                  return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n                }\n              }\n              const parsed = Option.some({ name: optionName, values: Arr.empty() })\n              const leftover = Arr.appendAll(beforeOption, afterOption)\n              return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n            }\n\n            if (equalsValue !== undefined) {\n              const parsed = Option.some({ name: optionName, values: Arr.of(equalsValue) })\n              const leftover = Arr.appendAll(beforeOption, afterOption)\n              return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n            }\n\n            if (afterOption.length === 0) {\n              const error = InternalHelpDoc.p(\n                `Expected a value following option: '${self.fullName}'`\n              )\n              return Effect.fail(InternalValidationError.missingValue(error))\n            }\n\n            const optionValue = afterOption[0]\n            const parsed = Option.some({ name: optionName, values: Arr.of(optionValue) })\n            const leftover = Arr.appendAll(beforeOption, afterOption.slice(1))\n            return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n          }\n        })\n      ))\n    }\n    case \"KeyValueMap\": {\n      const normalizedNames = Arr.map(\n        getNames(self.argumentOption),\n        (name) => InternalCliConfig.normalizeCase(config, name)\n      )\n      return Arr.matchLeft(args, {\n        onEmpty: () => Effect.succeed<ParsedCommandLine>({ parsed: Option.none(), leftover: args }),\n        onNonEmpty: (head, tail) => {\n          const loop = (\n            args: ReadonlyArray<string>\n          ): [ReadonlyArray<string>, ReadonlyArray<string>] => {\n            let keyValues = Arr.empty<string>()\n            let leftover = args as ReadonlyArray<string>\n            while (Arr.isNonEmptyReadonlyArray(leftover)) {\n              const name = Arr.headNonEmpty(leftover).trim()\n              const normalizedName = InternalCliConfig.normalizeCase(config, name)\n              // Can be in the form of \"--flag key1=value1 --flag key2=value2\"\n              if (leftover.length >= 2 && Arr.contains(normalizedNames, normalizedName)) {\n                const keyValue = leftover[1].trim()\n                const [key, value] = keyValue.split(\"=\")\n                if (key !== undefined && value !== undefined && value.length > 0) {\n                  keyValues = Arr.append(keyValues, keyValue)\n                  leftover = leftover.slice(2)\n                  continue\n                }\n              }\n              // Can be in the form of \"--flag key1=value1 key2=value2\")\n              if (name.includes(\"=\")) {\n                const [key, value] = name.split(\"=\")\n                if (key !== undefined && value !== undefined && value.length > 0) {\n                  keyValues = Arr.append(keyValues, name)\n                  leftover = leftover.slice(1)\n                  continue\n                }\n              }\n              break\n            }\n            return [keyValues, leftover]\n          }\n          const normalizedName = InternalCliConfig.normalizeCase(config, head)\n          if (Arr.contains(normalizedNames, normalizedName)) {\n            const [values, leftover] = loop(tail)\n            return Effect.succeed({ parsed: Option.some({ name: head, values }), leftover })\n          }\n\n          if (head.startsWith(\"-\")) {\n            return Effect.succeed<ParsedCommandLine>({ parsed: Option.none(), leftover: args })\n          }\n\n          let optionIndex = -1\n          for (let i = 0; i < tail.length; i++) {\n            const arg = tail[i]\n            const normalizedArg = InternalCliConfig.normalizeCase(config, arg)\n            if (Arr.contains(normalizedNames, normalizedArg)) {\n              optionIndex = i\n              break\n            }\n          }\n\n          if (optionIndex === -1) {\n            return Effect.succeed<ParsedCommandLine>({ parsed: Option.none(), leftover: args })\n          }\n\n          const optionName = tail[optionIndex]\n          const beforeOption = Arr.prepend(tail.slice(0, optionIndex), head)\n          const afterOption = tail.slice(optionIndex + 1)\n          const [values, remaining] = loop(afterOption)\n          const leftover = Arr.appendAll(beforeOption, remaining)\n          return Effect.succeed({ parsed: Option.some({ name: optionName, values }), leftover })\n        }\n      })\n    }\n    case \"Variadic\": {\n      const normalizedNames = Arr.map(\n        getNames(self.argumentOption),\n        (name) => InternalCliConfig.normalizeCase(config, name)\n      )\n      let optionName: string | undefined = undefined\n      let values = Arr.empty<string>()\n      let unparsed = args as ReadonlyArray<string>\n      let leftover = Arr.empty<string>()\n      while (Arr.isNonEmptyReadonlyArray(unparsed)) {\n        const name = Arr.headNonEmpty(unparsed)\n        const normalizedName = InternalCliConfig.normalizeCase(config, name)\n\n        if (Arr.contains(normalizedNames, normalizedName)) {\n          if (optionName === undefined) {\n            optionName = name\n          }\n          const value = unparsed[1]\n          if (value !== undefined && value.length > 0) {\n            values = Arr.append(values, value.trim())\n          }\n          unparsed = unparsed.slice(2)\n        } else {\n          leftover = Arr.append(leftover, Arr.headNonEmpty(unparsed))\n          unparsed = unparsed.slice(1)\n        }\n      }\n      const parsed = Option.fromNullable(optionName).pipe(\n        Option.orElse(() => Option.some(self.argumentOption.fullName)),\n        Option.map((name) => ({ name, values }))\n      )\n      return Effect.succeed<ParsedCommandLine>({ parsed, leftover })\n    }\n  }\n}\n\nconst matchUnclustered = (\n  input: ReadonlyArray<string>,\n  tail: ReadonlyArray<string>,\n  options: ReadonlyArray<ParseableInstruction>,\n  config: CliConfig.CliConfig\n): Effect.Effect<\n  [\n    ReadonlyArray<string>,\n    ReadonlyArray<ParseableInstruction>,\n    HashMap.HashMap<string, ReadonlyArray<string>>\n  ],\n  ValidationError.ValidationError\n> => {\n  if (Arr.isNonEmptyReadonlyArray(input)) {\n    const flag = Arr.headNonEmpty(input)\n    const otherFlags = Arr.tailNonEmpty(input)\n    return findOptions(Arr.of(flag), options, config).pipe(\n      Effect.flatMap(([_, opts1, map1]) => {\n        if (HashMap.isEmpty(map1)) {\n          return Effect.fail(\n            InternalValidationError.unclusteredFlag(\n              InternalHelpDoc.empty,\n              Arr.empty(),\n              tail\n            )\n          )\n        }\n        return matchUnclustered(otherFlags, tail, opts1, config).pipe(\n          Effect.map((\n            [_, opts2, map2]\n          ) => [tail, opts2, merge(map1, Arr.fromIterable(map2))])\n        )\n      })\n    )\n  }\n  return Effect.succeed([tail, options, HashMap.empty()])\n}\n\n/**\n * Sums the list associated with the same key.\n */\nconst merge = (\n  map1: HashMap.HashMap<string, ReadonlyArray<string>>,\n  map2: ReadonlyArray<[string, ReadonlyArray<string>]>\n): HashMap.HashMap<string, ReadonlyArray<string>> => {\n  if (Arr.isNonEmptyReadonlyArray(map2)) {\n    const head = Arr.headNonEmpty(map2)\n    const tail = Arr.tailNonEmpty(map2)\n    const newMap = Option.match(HashMap.get(map1, head[0]), {\n      onNone: () => HashMap.set(map1, head[0], head[1]),\n      onSome: (elems) => HashMap.set(map1, head[0], Arr.appendAll(elems, head[1]))\n    })\n    return merge(newMap, tail)\n  }\n  return map1\n}\n\n// =============================================================================\n// Completion Internals\n// =============================================================================\n\nconst escape = (string: string): string =>\n  string\n    .replaceAll(\"\\\\\", \"\\\\\\\\\")\n    .replaceAll(\"'\", \"'\\\\''\")\n    .replaceAll(\"[\", \"\\\\[\")\n    .replaceAll(\"]\", \"\\\\]\")\n    .replaceAll(\":\", \"\\\\:\")\n    .replaceAll(\"$\", \"\\\\$\")\n    .replaceAll(\"`\", \"\\\\`\")\n    .replaceAll(\"(\", \"\\\\(\")\n    .replaceAll(\")\", \"\\\\)\")\n\nconst getShortDescription = (self: Instruction): string => {\n  switch (self._tag) {\n    case \"Empty\":\n    case \"Both\":\n    case \"OrElse\": {\n      return \"\"\n    }\n    case \"Single\": {\n      return InternalSpan.getText(InternalHelpDoc.getSpan(self.description))\n    }\n    case \"KeyValueMap\":\n    case \"Variadic\": {\n      return getShortDescription(self.argumentOption as Instruction)\n    }\n    case \"Map\":\n    case \"WithDefault\":\n    case \"WithFallback\": {\n      return getShortDescription(self.options as Instruction)\n    }\n  }\n}\n\n/** @internal */\nexport const getBashCompletions = (self: Instruction): ReadonlyArray<string> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Arr.empty()\n    }\n    case \"Single\": {\n      const names = getNames(self)\n      const cases = Arr.join(names, \"|\")\n      const compgen = InternalPrimitive.getBashCompletions(\n        self.primitiveType as InternalPrimitive.Instruction\n      )\n      return Arr.make(\n        `${cases})`,\n        `    COMPREPLY=( ${compgen} )`,\n        `    return 0`,\n        `    ;;`\n      )\n    }\n    case \"KeyValueMap\":\n    case \"Variadic\": {\n      return getBashCompletions(self.argumentOption as Instruction)\n    }\n    case \"Map\":\n    case \"WithDefault\":\n    case \"WithFallback\": {\n      return getBashCompletions(self.options as Instruction)\n    }\n    case \"Both\":\n    case \"OrElse\": {\n      const left = getBashCompletions(self.left as Instruction)\n      const right = getBashCompletions(self.right as Instruction)\n      return Arr.appendAll(left, right)\n    }\n  }\n}\n\n/** @internal */\nexport const getFishCompletions = (self: Instruction): Array<string> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Arr.empty()\n    }\n    case \"Single\": {\n      const description = getShortDescription(self)\n      const order = Order.mapInput(Order.boolean, (tuple: readonly [boolean, string]) => !tuple[0])\n      return pipe(\n        Arr.prepend(self.aliases, self.name),\n        Arr.map((name) => [name.length === 1, name] as const),\n        Arr.sort(order),\n        Arr.flatMap(([isShort, name]) => Arr.make(isShort ? \"-s\" : \"-l\", name)),\n        Arr.appendAll(InternalPrimitive.getFishCompletions(\n          self.primitiveType as InternalPrimitive.Instruction\n        )),\n        Arr.appendAll(\n          description.length === 0\n            ? Arr.empty()\n            : Arr.of(`-d '${description}'`)\n        ),\n        Arr.join(\" \"),\n        Arr.of\n      )\n    }\n    case \"KeyValueMap\":\n    case \"Variadic\": {\n      return getFishCompletions(self.argumentOption as Instruction)\n    }\n    case \"Map\":\n    case \"WithDefault\":\n    case \"WithFallback\": {\n      return getFishCompletions(self.options as Instruction)\n    }\n    case \"Both\":\n    case \"OrElse\": {\n      return pipe(\n        getFishCompletions(self.left as Instruction),\n        Arr.appendAll(getFishCompletions(self.right as Instruction))\n      )\n    }\n  }\n}\n\ninterface ZshCompletionState {\n  readonly conflicts: ReadonlyArray<string>\n  readonly multiple: boolean\n}\n\n/** @internal */\nexport const getZshCompletions = (\n  self: Instruction,\n  state: ZshCompletionState = { conflicts: Arr.empty(), multiple: false }\n): Array<string> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Arr.empty()\n    }\n    case \"Single\": {\n      const names = getNames(self)\n      const description = getShortDescription(self)\n      const possibleValues = InternalPrimitive.getZshCompletions(\n        self.primitiveType as InternalPrimitive.Instruction\n      )\n      const multiple = state.multiple ? \"*\" : \"\"\n      const conflicts = Arr.isNonEmptyReadonlyArray(state.conflicts)\n        ? `(${Arr.join(state.conflicts, \" \")})`\n        : \"\"\n      return Arr.map(\n        names,\n        (name) => `${conflicts}${multiple}${name}[${escape(description)}]${possibleValues}`\n      )\n    }\n    case \"KeyValueMap\": {\n      return getZshCompletions(self.argumentOption as Instruction, { ...state, multiple: true })\n    }\n    case \"Map\":\n    case \"WithDefault\":\n    case \"WithFallback\": {\n      return getZshCompletions(self.options as Instruction, state)\n    }\n    case \"Both\": {\n      const left = getZshCompletions(self.left as Instruction, state)\n      const right = getZshCompletions(self.right as Instruction, state)\n      return Arr.appendAll(left, right)\n    }\n    case \"OrElse\": {\n      const leftNames = getNames(self.left as Instruction)\n      const rightNames = getNames(self.right as Instruction)\n      const left = getZshCompletions(\n        self.left as Instruction,\n        { ...state, conflicts: Arr.appendAll(state.conflicts, rightNames) }\n      )\n      const right = getZshCompletions(\n        self.right as Instruction,\n        { ...state, conflicts: Arr.appendAll(state.conflicts, leftNames) }\n      )\n      return Arr.appendAll(left, right)\n    }\n    case \"Variadic\": {\n      return Option.isSome(self.max) && self.max.value > 1\n        ? getZshCompletions(self.argumentOption as Instruction, { ...state, multiple: true })\n        : getZshCompletions(self.argumentOption as Instruction, state)\n    }\n  }\n}\n"
  },
  {
    "path": "packages/cli/src/internal/primitive.ts",
    "content": "import * as FileSystem from \"@effect/platform/FileSystem\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport { dual, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport { pipeArguments } from \"effect/Pipeable\"\nimport * as EffectRedacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport * as EffectSecret from \"effect/Secret\"\nimport type * as CliConfig from \"../CliConfig.js\"\nimport type * as HelpDoc from \"../HelpDoc.js\"\nimport type * as Span from \"../HelpDoc/Span.js\"\nimport type * as Primitive from \"../Primitive.js\"\nimport type * as Prompt from \"../Prompt.js\"\nimport * as InternalCliConfig from \"./cliConfig.js\"\nimport * as InternalHelpDoc from \"./helpDoc.js\"\nimport * as InternalSpan from \"./helpDoc/span.js\"\nimport * as InternalPrompt from \"./prompt.js\"\nimport * as InternalDatePrompt from \"./prompt/date.js\"\nimport * as InternalFilePrompt from \"./prompt/file.js\"\nimport * as InternalNumberPrompt from \"./prompt/number.js\"\nimport * as InternalSelectPrompt from \"./prompt/select.js\"\nimport * as InternalTextPrompt from \"./prompt/text.js\"\nimport * as InternalTogglePrompt from \"./prompt/toggle.js\"\n\nconst PrimitiveSymbolKey = \"@effect/cli/Primitive\"\n\n/** @internal */\nexport const PrimitiveTypeId: Primitive.PrimitiveTypeId = Symbol.for(\n  PrimitiveSymbolKey\n) as Primitive.PrimitiveTypeId\n\n/** @internal */\nexport type Op<Tag extends string, Body = {}> = Primitive.Primitive<never> & Body & {\n  readonly _tag: Tag\n}\n\nconst proto = {\n  [PrimitiveTypeId]: {\n    _A: (_: never) => _\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport type Instruction =\n  | Bool\n  | Choice\n  | DateTime\n  | Float\n  | Integer\n  | Path\n  | Secret\n  | Redacted\n  | Text\n\n/** @internal */\nexport interface Bool extends\n  Op<\"Bool\", {\n    readonly defaultValue: Option.Option<boolean>\n  }>\n{}\n\n/** @internal */\nexport interface Choice extends\n  Op<\"Choice\", {\n    readonly alternatives: ReadonlyArray<[string, unknown]>\n  }>\n{}\n\n/** @internal */\nexport interface DateTime extends Op<\"DateTime\", {}> {}\n\n/** @internal */\nexport interface Float extends Op<\"Float\", {}> {}\n\n/** @internal */\nexport interface Integer extends Op<\"Integer\", {}> {}\n\n/** @internal */\nexport interface Path extends\n  Op<\"Path\", {\n    readonly pathType: Primitive.Primitive.PathType\n    readonly pathExists: Primitive.Primitive.PathExists\n  }>\n{}\n\n/** @internal */\nexport interface Redacted extends Op<\"Redacted\", {}> {}\n\n/** @internal */\nexport interface Secret extends Op<\"Secret\", {}> {}\n\n/** @internal */\nexport interface Text extends Op<\"Text\", {}> {}\n\n// =============================================================================\n// Refinements\n// =============================================================================\n\n/** @internal */\nexport const isPrimitive = (u: unknown): u is Primitive.Primitive<unknown> =>\n  typeof u === \"object\" && u != null && PrimitiveTypeId in u\n\n/** @internal */\nexport const isBool = <A>(self: Primitive.Primitive<A>): boolean => isPrimitive(self) && isBoolType(self as Instruction)\n\n/** @internal */\nexport const isBoolType = (self: Instruction): self is Bool => self._tag === \"Bool\"\n\n/** @internal */\nexport const isChoiceType = (self: Instruction): self is Choice => self._tag === \"Choice\"\n\n/** @internal */\nexport const isDateTimeType = (self: Instruction): self is DateTime => self._tag === \"DateTime\"\n\n/** @internal */\nexport const isFloatType = (self: Instruction): self is Float => self._tag === \"Float\"\n\n/** @internal */\nexport const isIntegerType = (self: Instruction): self is Integer => self._tag === \"Integer\"\n\n/** @internal */\nexport const isPathType = (self: Instruction): self is Path => self._tag === \"Path\"\n\n/** @internal */\nexport const isSecretType = (self: Instruction): self is Path => self._tag === \"Path\"\n\n/** @internal */\nexport const isTextType = (self: Instruction): self is Text => self._tag === \"Text\"\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\n/** @internal */\nexport const trueValues = Schema.Literal(\"true\", \"1\", \"y\", \"yes\", \"on\")\n\n/** @internal */\nexport const isTrueValue = Schema.is(trueValues)\n\n/** @internal */\nexport const falseValues = Schema.Literal(\"false\", \"0\", \"n\", \"no\", \"off\")\n\n/** @internal */\nexport const isFalseValue = Schema.is(falseValues)\n\n/** @internal */\nexport const boolean = (defaultValue: Option.Option<boolean>): Primitive.Primitive<boolean> => {\n  const op = Object.create(proto)\n  op._tag = \"Bool\"\n  op.defaultValue = defaultValue\n  return op\n}\n\n/** @internal */\nexport const choice = <A>(\n  alternatives: ReadonlyArray<[string, A]>\n): Primitive.Primitive<A> => {\n  const op = Object.create(proto)\n  op._tag = \"Choice\"\n  op.alternatives = alternatives\n  return op\n}\n\n/** @internal */\nexport const date: Primitive.Primitive<globalThis.Date> = (() => {\n  const op = Object.create(proto)\n  op._tag = \"DateTime\"\n  return op\n})()\n\n/** @internal */\nexport const float: Primitive.Primitive<number> = (() => {\n  const op = Object.create(proto)\n  op._tag = \"Float\"\n  return op\n})()\n\n/** @internal */\nexport const integer: Primitive.Primitive<number> = (() => {\n  const op = Object.create(proto)\n  op._tag = \"Integer\"\n  return op\n})()\n\n/** @internal */\nexport const path = (\n  pathType: Primitive.Primitive.PathType,\n  pathExists: Primitive.Primitive.PathExists\n): Primitive.Primitive<string> => {\n  const op = Object.create(proto)\n  op._tag = \"Path\"\n  op.pathType = pathType\n  op.pathExists = pathExists\n  return op\n}\n\n/** @internal */\nexport const redacted: Primitive.Primitive<EffectRedacted.Redacted> = (() => {\n  const op = Object.create(proto)\n  op._tag = \"Redacted\"\n  return op\n})()\n\n/** @internal */\nexport const secret: Primitive.Primitive<EffectSecret.Secret> = (() => {\n  const op = Object.create(proto)\n  op._tag = \"Secret\"\n  return op\n})()\n\n/** @internal */\nexport const text: Primitive.Primitive<string> = (() => {\n  const op = Object.create(proto)\n  op._tag = \"Text\"\n  return op\n})()\n\n// =============================================================================\n// Combinators\n// =============================================================================\n\n/** @internal */\nexport const getChoices = <A>(self: Primitive.Primitive<A>): Option.Option<string> =>\n  getChoicesInternal(self as Instruction)\n\n/** @internal */\nexport const getHelp = <A>(self: Primitive.Primitive<A>): Span.Span => getHelpInternal(self as Instruction)\n\n/** @internal */\nexport const getTypeName = <A>(self: Primitive.Primitive<A>): string => getTypeNameInternal(self as Instruction)\n\n/** @internal */\nexport const validate = dual<\n  (\n    value: Option.Option<string>,\n    config: CliConfig.CliConfig\n  ) => <A>(self: Primitive.Primitive<A>) => Effect.Effect<\n    A,\n    string,\n    FileSystem.FileSystem\n  >,\n  <A>(\n    self: Primitive.Primitive<A>,\n    value: Option.Option<string>,\n    config: CliConfig.CliConfig\n  ) => Effect.Effect<\n    A,\n    string,\n    FileSystem.FileSystem\n  >\n>(3, (self, value, config) => validateInternal(self as Instruction, value, config))\n\n/** @internal */\nexport const wizard = dual<\n  (help: HelpDoc.HelpDoc) => <A>(self: Primitive.Primitive<A>) => Prompt.Prompt<A>,\n  <A>(self: Primitive.Primitive<A>, help: HelpDoc.HelpDoc) => Prompt.Prompt<A>\n>(2, (self, help) => wizardInternal(self as Instruction, help))\n\n// =============================================================================\n// Internals\n// =============================================================================\n\nconst getChoicesInternal = (self: Instruction): Option.Option<string> => {\n  switch (self._tag) {\n    case \"Bool\": {\n      return Option.some(\"true | false\")\n    }\n    case \"Choice\": {\n      const choices = pipe(\n        Arr.map(self.alternatives, ([choice]) => choice),\n        Arr.join(\" | \")\n      )\n      return Option.some(choices)\n    }\n    case \"DateTime\": {\n      return Option.some(\"date\")\n    }\n    case \"Float\":\n    case \"Integer\":\n    case \"Path\":\n    case \"Redacted\":\n    case \"Secret\":\n    case \"Text\": {\n      return Option.none()\n    }\n  }\n}\n\nconst getHelpInternal = (self: Instruction): Span.Span => {\n  switch (self._tag) {\n    case \"Bool\": {\n      return InternalSpan.text(\"A true or false value.\")\n    }\n    case \"Choice\": {\n      const choices = pipe(\n        Arr.map(self.alternatives, ([choice]) => choice),\n        Arr.join(\", \")\n      )\n      return InternalSpan.text(`One of the following: ${choices}`)\n    }\n    case \"DateTime\": {\n      return InternalSpan.text(\n        \"A date without a time-zone in the ISO-8601 format, such as 2007-12-03T10:15:30.\"\n      )\n    }\n    case \"Float\": {\n      return InternalSpan.text(\"A floating point number.\")\n    }\n    case \"Integer\": {\n      return InternalSpan.text(\"An integer.\")\n    }\n    case \"Path\": {\n      if (self.pathType === \"either\" && self.pathExists === \"yes\") {\n        return InternalSpan.text(\"An existing file or directory.\")\n      }\n      if (self.pathType === \"file\" && self.pathExists === \"yes\") {\n        return InternalSpan.text(\"An existing file.\")\n      }\n      if (self.pathType === \"directory\" && self.pathExists === \"yes\") {\n        return InternalSpan.text(\"An existing directory.\")\n      }\n      if (self.pathType === \"either\" && self.pathExists === \"no\") {\n        return InternalSpan.text(\"A file or directory that must not exist.\")\n      }\n      if (self.pathType === \"file\" && self.pathExists === \"no\") {\n        return InternalSpan.text(\"A file that must not exist.\")\n      }\n      if (self.pathType === \"directory\" && self.pathExists === \"no\") {\n        return InternalSpan.text(\"A directory that must not exist.\")\n      }\n      if (self.pathType === \"either\" && self.pathExists === \"either\") {\n        return InternalSpan.text(\"A file or directory.\")\n      }\n      if (self.pathType === \"file\" && self.pathExists === \"either\") {\n        return InternalSpan.text(\"A file.\")\n      }\n      if (self.pathType === \"directory\" && self.pathExists === \"either\") {\n        return InternalSpan.text(\"A directory.\")\n      }\n      throw new Error(\n        \"[BUG]: Path.help - encountered invalid combination of path type \" +\n          `('${self.pathType}') and path existence ('${self.pathExists}')`\n      )\n    }\n    case \"Secret\":\n    case \"Redacted\": {\n      return InternalSpan.text(\"A user-defined piece of text that is confidential.\")\n    }\n    case \"Text\": {\n      return InternalSpan.text(\"A user-defined piece of text.\")\n    }\n  }\n}\n\nconst getTypeNameInternal = (self: Instruction): string => {\n  switch (self._tag) {\n    case \"Bool\": {\n      return \"boolean\"\n    }\n    case \"Choice\": {\n      return \"choice\"\n    }\n    case \"DateTime\": {\n      return \"date\"\n    }\n    case \"Float\": {\n      return \"float\"\n    }\n    case \"Integer\": {\n      return \"integer\"\n    }\n    case \"Path\": {\n      if (self.pathType === \"either\") {\n        return \"path\"\n      }\n      return self.pathType\n    }\n    case \"Redacted\": {\n      return \"redacted\"\n    }\n    case \"Secret\": {\n      return \"secret\"\n    }\n    case \"Text\": {\n      return \"text\"\n    }\n  }\n}\n\nconst validateInternal = (\n  self: Instruction,\n  value: Option.Option<string>,\n  config: CliConfig.CliConfig\n): Effect.Effect<any, string, FileSystem.FileSystem> => {\n  switch (self._tag) {\n    case \"Bool\": {\n      return Option.map(value, (str) => InternalCliConfig.normalizeCase(config, str)).pipe(\n        Option.match({\n          onNone: () =>\n            Effect.orElseFail(\n              self.defaultValue,\n              () => `Missing default value for boolean parameter`\n            ),\n          onSome: (value) =>\n            isTrueValue(value)\n              ? Effect.succeed(true)\n              : isFalseValue(value)\n              ? Effect.succeed(false)\n              : Effect.fail(`Unable to recognize '${value}' as a valid boolean`)\n        })\n      )\n    }\n    case \"Choice\": {\n      return Effect.orElseFail(\n        value,\n        () => `Choice options to not have a default value`\n      ).pipe(\n        Effect.flatMap((value) => Arr.findFirst(self.alternatives, ([choice]) => choice === value)),\n        Effect.mapBoth({\n          onFailure: () => {\n            const choices = pipe(\n              Arr.map(self.alternatives, ([choice]) => choice),\n              Arr.join(\", \")\n            )\n            return `Expected one of the following cases: ${choices}`\n          },\n          onSuccess: ([, value]) => value\n        })\n      )\n    }\n    case \"DateTime\": {\n      return attempt(value, getTypeNameInternal(self), Schema.decodeUnknown(Schema.Date))\n    }\n    case \"Float\": {\n      return attempt(value, getTypeNameInternal(self), Schema.decodeUnknown(Schema.NumberFromString))\n    }\n    case \"Integer\": {\n      const intFromString = Schema.compose(Schema.NumberFromString, Schema.Int)\n      return attempt(value, getTypeNameInternal(self), Schema.decodeUnknown(intFromString))\n    }\n    case \"Path\": {\n      return Effect.flatMap(FileSystem.FileSystem, (fileSystem) => {\n        const errorMsg = \"Path options do not have a default value\"\n        return Effect.orElseFail(value, () => errorMsg).pipe(\n          Effect.tap((path) =>\n            Effect.orDie(fileSystem.exists(path)).pipe(\n              Effect.tap((pathExists) =>\n                validatePathExistence(path, self.pathExists, pathExists).pipe(\n                  Effect.zipRight(\n                    validatePathType(path, self.pathType, fileSystem).pipe(\n                      Effect.when(() => self.pathExists !== \"no\" && pathExists)\n                    )\n                  )\n                )\n              )\n            )\n          )\n        )\n      })\n    }\n    case \"Redacted\": {\n      return attempt(value, getTypeNameInternal(self), Schema.decodeUnknown(Schema.String)).pipe(\n        Effect.map((value) => EffectRedacted.make(value))\n      )\n    }\n    case \"Secret\": {\n      return attempt(value, getTypeNameInternal(self), Schema.decodeUnknown(Schema.String)).pipe(\n        Effect.map((value) => EffectSecret.fromString(value))\n      )\n    }\n    case \"Text\": {\n      return attempt(value, getTypeNameInternal(self), Schema.decodeUnknown(Schema.String))\n    }\n  }\n}\n\nconst attempt = <E, A>(\n  option: Option.Option<string>,\n  typeName: string,\n  parse: (value: string) => Effect.Effect<A, E>\n): Effect.Effect<A, string> =>\n  Effect.orElseFail(\n    option,\n    () => `${typeName} options do not have a default value`\n  ).pipe(\n    Effect.flatMap((value) =>\n      Effect.orElseFail(\n        parse(value),\n        () => `'${value}' is not a ${typeName}`\n      )\n    )\n  )\n\nconst validatePathExistence = (\n  path: string,\n  shouldPathExist: Primitive.Primitive.PathExists,\n  pathExists: boolean\n): Effect.Effect<void, string> => {\n  if (shouldPathExist === \"no\" && pathExists) {\n    return Effect.fail(`Path '${path}' must not exist`)\n  }\n  if (shouldPathExist === \"yes\" && !pathExists) {\n    return Effect.fail(`Path '${path}' must exist`)\n  }\n  return Effect.void\n}\n\nconst validatePathType = (\n  path: string,\n  pathType: Primitive.Primitive.PathType,\n  fileSystem: FileSystem.FileSystem\n): Effect.Effect<void, string> => {\n  switch (pathType) {\n    case \"file\": {\n      const checkIsFile = fileSystem.stat(path).pipe(\n        Effect.map((info) => info.type === \"File\"),\n        Effect.orDie\n      )\n      return Effect.fail(`Expected path '${path}' to be a regular file`).pipe(\n        Effect.unlessEffect(checkIsFile),\n        Effect.asVoid\n      )\n    }\n    case \"directory\": {\n      const checkIsDirectory = fileSystem.stat(path).pipe(\n        Effect.map((info) => info.type === \"Directory\"),\n        Effect.orDie\n      )\n      return Effect.fail(`Expected path '${path}' to be a directory`).pipe(\n        Effect.unlessEffect(checkIsDirectory),\n        Effect.asVoid\n      )\n    }\n    case \"either\": {\n      return Effect.void\n    }\n  }\n}\n\nconst wizardInternal = (self: Instruction, help: HelpDoc.HelpDoc): Prompt.Prompt<any> => {\n  switch (self._tag) {\n    case \"Bool\": {\n      const primitiveHelp = InternalHelpDoc.p(\"Select true or false\")\n      const message = InternalHelpDoc.sequence(help, primitiveHelp)\n      const initial = Option.getOrElse(self.defaultValue, () => false)\n      return InternalTogglePrompt.toggle({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd(),\n        initial,\n        active: \"true\",\n        inactive: \"false\"\n      }).pipe(InternalPrompt.map((bool) => `${bool}`))\n    }\n    case \"Choice\": {\n      const primitiveHelp = InternalHelpDoc.p(\"Select one of the following choices\")\n      const message = InternalHelpDoc.sequence(help, primitiveHelp)\n      return InternalSelectPrompt.select({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd(),\n        choices: Arr.map(\n          self.alternatives,\n          ([title]) => ({ title, value: title })\n        )\n      })\n    }\n    case \"DateTime\": {\n      const primitiveHelp = InternalHelpDoc.p(\"Enter a date\")\n      const message = InternalHelpDoc.sequence(help, primitiveHelp)\n      return InternalDatePrompt.date({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd()\n      }).pipe(InternalPrompt.map((date) => date.toISOString()))\n    }\n    case \"Float\": {\n      const primitiveHelp = InternalHelpDoc.p(\"Enter a floating point value\")\n      const message = InternalHelpDoc.sequence(help, primitiveHelp)\n      return InternalNumberPrompt.float({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd()\n      }).pipe(InternalPrompt.map((value) => `${value}`))\n    }\n    case \"Integer\": {\n      const primitiveHelp = InternalHelpDoc.p(\"Enter an integer\")\n      const message = InternalHelpDoc.sequence(help, primitiveHelp)\n      return InternalNumberPrompt.integer({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd()\n      }).pipe(InternalPrompt.map((value) => `${value}`))\n    }\n    case \"Path\": {\n      const primitiveHelp = InternalHelpDoc.p(\"Select a file system path\")\n      const message = InternalHelpDoc.sequence(help, primitiveHelp)\n      return InternalFilePrompt.file({\n        type: self.pathType,\n        message: InternalHelpDoc.toAnsiText(message).trimEnd()\n      })\n    }\n    case \"Redacted\": {\n      const primitiveHelp = InternalHelpDoc.p(\"Enter some text (value will be redacted)\")\n      const message = InternalHelpDoc.sequence(help, primitiveHelp)\n      return InternalTextPrompt.hidden({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd()\n      })\n    }\n    case \"Secret\": {\n      const primitiveHelp = InternalHelpDoc.p(\"Enter some text (value will be redacted)\")\n      const message = InternalHelpDoc.sequence(help, primitiveHelp)\n      return InternalTextPrompt.hidden({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd()\n      })\n    }\n    case \"Text\": {\n      const primitiveHelp = InternalHelpDoc.p(\"Enter some text\")\n      const message = InternalHelpDoc.sequence(help, primitiveHelp)\n      return InternalTextPrompt.text({\n        message: InternalHelpDoc.toAnsiText(message).trimEnd()\n      })\n    }\n  }\n}\n\n// =============================================================================\n// Completion Internals\n// =============================================================================\n\n/** @internal */\nexport const getBashCompletions = (self: Instruction): string => {\n  switch (self._tag) {\n    case \"Bool\": {\n      return \"\\\"${cur}\\\"\"\n    }\n    case \"DateTime\":\n    case \"Float\":\n    case \"Integer\":\n    case \"Secret\":\n    case \"Redacted\":\n    case \"Text\": {\n      return \"$(compgen -f \\\"${cur}\\\")\"\n    }\n    case \"Path\": {\n      switch (self.pathType) {\n        case \"file\": {\n          return self.pathExists === \"yes\" || self.pathExists === \"either\"\n            ? \"$(compgen -f \\\"${cur}\\\")\"\n            : \"\"\n        }\n        case \"directory\": {\n          return self.pathExists === \"yes\" || self.pathExists === \"either\"\n            ? \"$(compgen -d \\\"${cur}\\\")\"\n            : \"\"\n        }\n        case \"either\": {\n          return self.pathExists === \"yes\" || self.pathExists === \"either\"\n            ? \"$(compgen -f \\\"${cur}\\\")\"\n            : \"\"\n        }\n      }\n    }\n    case \"Choice\": {\n      const choices = pipe(\n        Arr.map(self.alternatives, ([choice]) => choice),\n        Arr.join(\",\")\n      )\n      return `$(compgen -W \"${choices}\" -- \"\\${cur}\")`\n    }\n  }\n}\n\n/** @internal */\nexport const getFishCompletions = (self: Instruction): Array<string> => {\n  switch (self._tag) {\n    case \"Bool\": {\n      return Arr.empty()\n    }\n    case \"DateTime\":\n    case \"Float\":\n    case \"Integer\":\n    case \"Redacted\":\n    case \"Secret\":\n    case \"Text\": {\n      return Arr.make(\"-r\", \"-f\")\n    }\n    case \"Path\": {\n      switch (self.pathType) {\n        case \"file\": {\n          return self.pathExists === \"yes\" || self.pathExists === \"either\"\n            ? Arr.make(\"-r\", \"-F\")\n            : Arr.make(\"-r\")\n        }\n        case \"directory\": {\n          return self.pathExists === \"yes\" || self.pathExists === \"either\"\n            ? Arr.make(\n              \"-r\",\n              \"-f\",\n              \"-a\",\n              `\"(__fish_complete_directories (commandline -ct))\"`\n            )\n            : Arr.make(\"-r\")\n        }\n        case \"either\": {\n          return self.pathExists === \"yes\" || self.pathExists === \"either\"\n            ? Arr.make(\"-r\", \"-F\")\n            : Arr.make(\"-r\")\n        }\n      }\n    }\n    case \"Choice\": {\n      const choices = pipe(\n        Arr.map(self.alternatives, ([choice]) => `${choice}''`),\n        Arr.join(\",\")\n      )\n      return Arr.make(\"-r\", \"-f\", \"-a\", `\"{${choices}}\"`)\n    }\n  }\n}\n\n/** @internal */\nexport const getZshCompletions = (self: Instruction): string => {\n  switch (self._tag) {\n    case \"Bool\": {\n      return \"\"\n    }\n    case \"Choice\": {\n      const choices = pipe(\n        Arr.map(self.alternatives, ([name]) => name),\n        Arr.join(\" \")\n      )\n      return `:CHOICE:(${choices})`\n    }\n    case \"DateTime\": {\n      return \"\"\n    }\n    case \"Float\": {\n      return \"\"\n    }\n    case \"Integer\": {\n      return \"\"\n    }\n    case \"Path\": {\n      switch (self.pathType) {\n        case \"file\": {\n          return self.pathExists === \"yes\" || self.pathExists === \"either\"\n            ? \":PATH:_files\"\n            : \"\"\n        }\n        case \"directory\": {\n          return self.pathExists === \"yes\" || self.pathExists === \"either\"\n            ? \":PATH:_files -/\"\n            : \"\"\n        }\n        case \"either\": {\n          return self.pathExists === \"yes\" || self.pathExists === \"either\"\n            ? \":PATH:_files\"\n            : \"\"\n        }\n      }\n    }\n    case \"Redacted\":\n    case \"Secret\":\n    case \"Text\": {\n      return \"\"\n    }\n  }\n}\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/action.ts",
    "content": "import * as Data from \"effect/Data\"\nimport type { Prompt } from \"../../Prompt.js\"\n\n/** @internal */\nexport const Action = Data.taggedEnum<Prompt.ActionDefinition>()\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/ansi-utils.ts",
    "content": "import * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\n\nconst defaultFigures = {\n  arrowUp: Doc.text(\"↑\"),\n  arrowDown: Doc.text(\"↓\"),\n  arrowLeft: Doc.text(\"←\"),\n  arrowRight: Doc.text(\"→\"),\n  radioOn: Doc.text(\"◉\"),\n  radioOff: Doc.text(\"◯\"),\n  checkboxOn: Doc.text(\"☒\"),\n  checkboxOff: Doc.text(\"☐\"),\n  tick: Doc.text(\"✔\"),\n  cross: Doc.text(\"✖\"),\n  ellipsis: Doc.text(\"…\"),\n  pointerSmall: Doc.text(\"›\"),\n  line: Doc.text(\"─\"),\n  pointer: Doc.text(\"❯\")\n}\n\nconst windowsFigures = {\n  arrowUp: defaultFigures.arrowUp,\n  arrowDown: defaultFigures.arrowDown,\n  arrowLeft: defaultFigures.arrowLeft,\n  arrowRight: defaultFigures.arrowRight,\n  radioOn: Doc.text(\"(*)\"),\n  radioOff: Doc.text(\"( )\"),\n  checkboxOn: Doc.text(\"[*]\"),\n  checkboxOff: Doc.text(\"[ ]\"),\n  tick: Doc.text(\"√\"),\n  cross: Doc.text(\"×\"),\n  ellipsis: Doc.text(\"...\"),\n  pointerSmall: Doc.text(\"»\"),\n  line: Doc.text(\"─\"),\n  pointer: Doc.text(\">\")\n}\n\n/** @internal */\nexport const figures = Effect.map(\n  Effect.sync(() => process.platform === \"win32\"),\n  (isWindows) => isWindows ? windowsFigures : defaultFigures\n)\n\n/**\n * Clears all lines taken up by the specified `text`.\n *\n * @internal\n */\nexport function eraseText(text: string, columns: number): Doc.AnsiDoc {\n  if (columns === 0) {\n    return Doc.cat(Doc.eraseLine, Doc.cursorTo(0))\n  }\n  let rows = 0\n  const lines = text.split(/\\r?\\n/)\n  for (const line of lines) {\n    rows += 1 + Math.floor(Math.max(line.length - 1, 0) / columns)\n  }\n  return Doc.eraseLines(rows)\n}\n\n/** @internal */\nexport function lines(prompt: string, columns: number): number {\n  const lines = prompt.split(/\\r?\\n/)\n  return columns === 0\n    ? lines.length\n    : pipe(\n      Arr.map(lines, (line) => Math.ceil(line.length / columns)),\n      Arr.reduce(0, (left, right) => left + right)\n    )\n}\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/confirm.ts",
    "content": "import * as Terminal from \"@effect/platform/Terminal\"\nimport * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Optimize from \"@effect/printer/Optimize\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport type * as Prompt from \"../../Prompt.js\"\nimport * as InternalPrompt from \"../prompt.js\"\nimport { Action } from \"./action.js\"\nimport * as InternalAnsiUtils from \"./ansi-utils.js\"\n\ninterface Options extends Required<Prompt.Prompt.ConfirmOptions> {}\n\ninterface State {\n  readonly value: boolean\n}\n\nconst renderBeep = Doc.render(Doc.beep, { style: \"pretty\" })\n\nfunction handleClear(options: Options) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const clearOutput = InternalAnsiUtils.eraseText(options.message, columns)\n    const resetCurrentLine = Doc.cat(Doc.eraseLine, Doc.cursorLeft)\n    return clearOutput.pipe(\n      Doc.cat(resetCurrentLine),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nconst NEWLINE_REGEX = /\\r?\\n/\n\nfunction renderOutput(\n  confirm: Doc.AnsiDoc,\n  leadingSymbol: Doc.AnsiDoc,\n  trailingSymbol: Doc.AnsiDoc,\n  options: Options\n) {\n  const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold)\n  const prefix = Doc.cat(leadingSymbol, Doc.space)\n  return Arr.match(options.message.split(NEWLINE_REGEX), {\n    onEmpty: () => Doc.hsep([prefix, trailingSymbol, confirm]),\n    onNonEmpty: (promptLines) => {\n      const lines = Arr.map(promptLines, (line) => annotateLine(line))\n      return prefix.pipe(\n        Doc.cat(Doc.nest(Doc.vsep(lines), 2)),\n        Doc.cat(Doc.space),\n        Doc.cat(trailingSymbol),\n        Doc.cat(Doc.space),\n        Doc.cat(confirm)\n      )\n    }\n  })\n}\n\nfunction renderNextFrame(state: State, options: Options) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const leadingSymbol = Doc.annotate(Doc.text(\"?\"), Ansi.cyanBright)\n    const trailingSymbol = Doc.annotate(figures.pointerSmall, Ansi.blackBright)\n    // Marking these explicitly as present with `!` because they always will be\n    // and there is really no value in adding a `DeepRequired` type helper just\n    // for these internal cases\n    const confirmMessage = state.value\n      ? options.placeholder.defaultConfirm!\n      : options.placeholder.defaultDeny!\n    const confirm = Doc.annotate(Doc.text(confirmMessage), Ansi.blackBright)\n    const promptMsg = renderOutput(confirm, leadingSymbol, trailingSymbol, options)\n    return Doc.cursorHide.pipe(\n      Doc.cat(promptMsg),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction renderSubmission(value: boolean, options: Options) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const leadingSymbol = Doc.annotate(figures.tick, Ansi.green)\n    const trailingSymbol = Doc.annotate(figures.ellipsis, Ansi.blackBright)\n    const confirmMessage = value ? options.label.confirm : options.label.deny\n    const confirm = Doc.text(confirmMessage)\n    const promptMsg = renderOutput(confirm, leadingSymbol, trailingSymbol, options)\n    return promptMsg.pipe(\n      Doc.cat(Doc.hardLine),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction handleRender(options: Options) {\n  return (_: State, action: Prompt.Prompt.Action<State, boolean>) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({ state }) => renderNextFrame(state, options),\n      Submit: ({ value }) => renderSubmission(value, options)\n    })\n  }\n}\n\nconst TRUE_VALUE_REGEX = /^y|t$/\nconst FALSE_VALUE_REGEX = /^n|f$/\n\nfunction handleProcess(input: Terminal.UserInput, defaultValue: boolean) {\n  const value = Option.getOrElse(input.input, () => \"\")\n  if (input.key.name === \"enter\" || input.key.name === \"return\") {\n    return Effect.succeed(Action.Submit({ value: defaultValue }))\n  }\n  if (TRUE_VALUE_REGEX.test(value.toLowerCase())) {\n    return Effect.succeed(Action.Submit({ value: true }))\n  }\n  if (FALSE_VALUE_REGEX.test(value.toLowerCase())) {\n    return Effect.succeed(Action.Submit({ value: false }))\n  }\n  return Effect.succeed(Action.Beep())\n}\n\n/** @internal */\nexport const confirm = (options: Prompt.Prompt.ConfirmOptions): Prompt.Prompt<boolean> => {\n  const opts: Required<Prompt.Prompt.ConfirmOptions> = {\n    initial: false,\n    ...options,\n    label: {\n      confirm: \"yes\",\n      deny: \"no\",\n      ...options.label\n    },\n    placeholder: {\n      defaultConfirm: \"(Y/n)\",\n      defaultDeny: \"(y/N)\",\n      ...options.placeholder\n    }\n  }\n  const initialState: State = { value: opts.initial }\n  return InternalPrompt.custom(initialState, {\n    render: handleRender(opts),\n    process: (input) => handleProcess(input, opts.initial),\n    clear: () => handleClear(opts)\n  })\n}\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/date.ts",
    "content": "import * as Terminal from \"@effect/platform/Terminal\"\nimport * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Optimize from \"@effect/printer/Optimize\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport * as Match from \"effect/Match\"\nimport * as Option from \"effect/Option\"\nimport type * as Prompt from \"../../Prompt.js\"\nimport * as InternalPrompt from \"../prompt.js\"\nimport { Action } from \"./action.js\"\nimport * as InternalAnsiUtils from \"./ansi-utils.js\"\n\ninterface DateOptions extends Required<Prompt.Prompt.DateOptions> {}\n\ninterface State {\n  readonly typed: string\n  readonly cursor: number\n  readonly value: globalThis.Date\n  readonly dateParts: ReadonlyArray<DatePart>\n  readonly error: Option.Option<string>\n}\n\nconst renderBeep = Doc.render(Doc.beep, { style: \"pretty\" })\n\nfunction handleClear(options: DateOptions) {\n  return (state: State, _: Prompt.Prompt.Action<State, globalThis.Date>) => {\n    return Effect.gen(function*() {\n      const terminal = yield* Terminal.Terminal\n      const columns = yield* terminal.columns\n      const resetCurrentLine = Doc.cat(Doc.eraseLine, Doc.cursorLeft)\n      const clearError = Option.match(state.error, {\n        onNone: () => Doc.empty,\n        onSome: (error) =>\n          Doc.cursorDown(InternalAnsiUtils.lines(error, columns)).pipe(\n            Doc.cat(InternalAnsiUtils.eraseText(`\\n${error}`, columns))\n          )\n      })\n      const clearOutput = InternalAnsiUtils.eraseText(options.message, columns)\n      return clearError.pipe(\n        Doc.cat(clearOutput),\n        Doc.cat(resetCurrentLine),\n        Optimize.optimize(Optimize.Deep),\n        Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n      )\n    })\n  }\n}\n\nconst NEWLINE_REGEX = /\\r?\\n/\n\nfunction renderError(state: State, pointer: Doc.AnsiDoc) {\n  return Option.match(state.error, {\n    onNone: () => Doc.empty,\n    onSome: (error) => {\n      const errorLines = error.split(NEWLINE_REGEX)\n      if (Arr.isNonEmptyReadonlyArray(errorLines)) {\n        const annotateLine = (line: string): Doc.AnsiDoc =>\n          Doc.annotate(Doc.text(line), Ansi.combine(Ansi.italicized, Ansi.red))\n        const prefix = Doc.cat(Doc.annotate(pointer, Ansi.red), Doc.space)\n        const lines = Arr.map(errorLines, (str) => annotateLine(str))\n        return Doc.cursorSavePosition.pipe(\n          Doc.cat(Doc.hardLine),\n          Doc.cat(prefix),\n          Doc.cat(Doc.align(Doc.vsep(lines))),\n          Doc.cat(Doc.cursorRestorePosition)\n        )\n      }\n      return Doc.empty\n    }\n  })\n}\n\nfunction renderParts(state: State, submitted: boolean = false) {\n  return Arr.reduce(\n    state.dateParts,\n    Doc.empty as Doc.AnsiDoc,\n    (doc, part, currentIndex) => {\n      const partDoc = Doc.text(part.toString())\n      if (currentIndex === state.cursor && !submitted) {\n        const annotation = Ansi.combine(Ansi.underlined, Ansi.cyanBright)\n        return Doc.cat(doc, Doc.annotate(partDoc, annotation))\n      }\n      return Doc.cat(doc, partDoc)\n    }\n  )\n}\n\nfunction renderOutput(\n  leadingSymbol: Doc.AnsiDoc,\n  trailingSymbol: Doc.AnsiDoc,\n  parts: Doc.AnsiDoc,\n  options: DateOptions\n) {\n  const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold)\n  const prefix = Doc.cat(leadingSymbol, Doc.space)\n  return Arr.match(options.message.split(/\\r?\\n/), {\n    onEmpty: () => Doc.hsep([prefix, trailingSymbol, parts]),\n    onNonEmpty: (promptLines) => {\n      const lines = Arr.map(promptLines, (line) => annotateLine(line))\n      return prefix.pipe(\n        Doc.cat(Doc.nest(Doc.vsep(lines), 2)),\n        Doc.cat(Doc.space),\n        Doc.cat(trailingSymbol),\n        Doc.cat(Doc.space),\n        Doc.cat(parts)\n      )\n    }\n  })\n}\n\nfunction renderNextFrame(state: State, options: DateOptions) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const leadingSymbol = Doc.annotate(Doc.text(\"?\"), Ansi.cyanBright)\n    const trailingSymbol = Doc.annotate(figures.pointerSmall, Ansi.blackBright)\n    const parts = renderParts(state)\n    const promptMsg = renderOutput(leadingSymbol, trailingSymbol, parts, options)\n    const errorMsg = renderError(state, figures.pointerSmall)\n    return Doc.cursorHide.pipe(\n      Doc.cat(promptMsg),\n      Doc.cat(errorMsg),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction renderSubmission(state: State, options: DateOptions) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const leadingSymbol = Doc.annotate(figures.tick, Ansi.green)\n    const trailingSymbol = Doc.annotate(figures.ellipsis, Ansi.blackBright)\n    const parts = renderParts(state, true)\n    const promptMsg = renderOutput(leadingSymbol, trailingSymbol, parts, options)\n    return promptMsg.pipe(\n      Doc.cat(Doc.hardLine),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction processUp(state: State) {\n  state.dateParts[state.cursor].increment()\n  return Action.NextFrame({\n    state: { ...state, typed: \"\" }\n  })\n}\n\nfunction processDown(state: State) {\n  state.dateParts[state.cursor].decrement()\n  return Action.NextFrame({\n    state: { ...state, typed: \"\" }\n  })\n}\n\nfunction processCursorLeft(state: State) {\n  const previousPart = state.dateParts[state.cursor].previousPart()\n  return Option.match(previousPart, {\n    onNone: () => Action.Beep(),\n    onSome: (previous) =>\n      Action.NextFrame({\n        state: {\n          ...state,\n          typed: \"\",\n          cursor: state.dateParts.indexOf(previous)\n        }\n      })\n  })\n}\n\nfunction processCursorRight(state: State) {\n  const nextPart = state.dateParts[state.cursor].nextPart()\n  return Option.match(nextPart, {\n    onNone: () => Action.Beep(),\n    onSome: (next) =>\n      Action.NextFrame({\n        state: {\n          ...state,\n          typed: \"\",\n          cursor: state.dateParts.indexOf(next)\n        }\n      })\n  })\n}\n\nfunction processNext(state: State) {\n  const nextPart = state.dateParts[state.cursor].nextPart()\n  const cursor = Option.match(nextPart, {\n    onNone: () => state.dateParts.findIndex((part) => !part.isToken()),\n    onSome: (next) => state.dateParts.indexOf(next)\n  })\n  return Action.NextFrame({\n    state: { ...state, cursor }\n  })\n}\n\nfunction defaultProcessor(value: string, state: State) {\n  if (/\\d/.test(value)) {\n    const typed = state.typed + value\n    state.dateParts[state.cursor].setValue(typed)\n    return Action.NextFrame({\n      state: { ...state, typed }\n    })\n  }\n  return Action.Beep()\n}\n\nconst defaultLocales: Prompt.Prompt.DateOptions[\"locales\"] = {\n  months: [\n    \"January\",\n    \"February\",\n    \"March\",\n    \"April\",\n    \"May\",\n    \"June\",\n    \"July\",\n    \"August\",\n    \"September\",\n    \"October\",\n    \"November\",\n    \"December\"\n  ],\n  monthsShort: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"],\n  weekdays: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"],\n  weekdaysShort: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"]\n}\n\nfunction handleRender(options: DateOptions) {\n  return (state: State, action: Prompt.Prompt.Action<State, globalThis.Date>) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({ state }) => renderNextFrame(state, options),\n      Submit: () => renderSubmission(state, options)\n    })\n  }\n}\n\nfunction handleProcess(options: DateOptions) {\n  return (input: Terminal.UserInput, state: State) => {\n    switch (input.key.name) {\n      case \"left\": {\n        return Effect.succeed(processCursorLeft(state))\n      }\n      case \"right\": {\n        return Effect.succeed(processCursorRight(state))\n      }\n      case \"k\":\n      case \"up\": {\n        return Effect.succeed(processUp(state))\n      }\n      case \"j\":\n      case \"down\": {\n        return Effect.succeed(processDown(state))\n      }\n      case \"tab\": {\n        return Effect.succeed(processNext(state))\n      }\n      case \"enter\":\n      case \"return\": {\n        return Effect.match(options.validate(state.value), {\n          onFailure: (error) =>\n            Action.NextFrame({\n              state: {\n                ...state,\n                error: Option.some(error)\n              }\n            }),\n          onSuccess: (value) => Action.Submit({ value })\n        })\n      }\n      default: {\n        const value = Option.getOrElse(input.input, () => \"\")\n        return Effect.succeed(defaultProcessor(value, state))\n      }\n    }\n  }\n}\n\n/** @internal */\nexport const date = (options: Prompt.Prompt.DateOptions): Prompt.Prompt<globalThis.Date> => {\n  const opts: Required<Prompt.Prompt.DateOptions> = {\n    initial: new Date(),\n    dateMask: \"YYYY-MM-DD HH:mm:ss\",\n    validate: Effect.succeed,\n    ...options,\n    locales: {\n      ...defaultLocales,\n      ...options.locales\n    }\n  }\n  const dateParts = makeDateParts(opts.dateMask, opts.initial, opts.locales)\n  const initialCursorPosition = dateParts.findIndex((part) => !part.isToken())\n  const initialState: State = {\n    dateParts,\n    typed: \"\",\n    cursor: initialCursorPosition,\n    value: opts.initial,\n    error: Option.none()\n  }\n  return InternalPrompt.custom(initialState, {\n    render: handleRender(opts),\n    process: handleProcess(opts),\n    clear: handleClear(opts)\n  })\n}\n\nconst DATE_PART_REGEX =\n  /\\\\(.)|\"((?:\\\\[\"\\\\]|[^\"])+)\"|(D[Do]?|d{3,4}|d)|(M{1,4})|(YY(?:YY)?)|([aA])|([Hh]{1,2})|(m{1,2})|(s{1,2})|(S{1,4})|./g\n\nconst regexGroups: Record<number, (params: DatePartParams) => DatePart> = {\n  1: ({ token, ...opts }) => new Token({ token: token.replace(/\\\\(.)/g, \"$1\"), ...opts }),\n  2: (opts) => new Day(opts),\n  3: (opts) => new Month(opts),\n  4: (opts) => new Year(opts),\n  5: (opts) => new Meridiem(opts),\n  6: (opts) => new Hours(opts),\n  7: (opts) => new Minutes(opts),\n  8: (opts) => new Seconds(opts),\n  9: (opts) => new Milliseconds(opts)\n}\n\nconst makeDateParts = (\n  dateMask: string,\n  date: globalThis.Date,\n  locales: Prompt.Prompt.DateOptions[\"locales\"]\n) => {\n  const parts: Array<DatePart> = []\n  let result: RegExpExecArray | null = null\n  // eslint-disable-next-line no-cond-assign\n  while (result = DATE_PART_REGEX.exec(dateMask)) {\n    const match = result.shift()\n    const index = result.findIndex((group) => group !== undefined)\n    if (index in regexGroups) {\n      const token = (result[index] || match)!\n      parts.push(regexGroups[index]({ token, date, parts, locales }))\n    } else {\n      parts.push(new Token({ token: (result[index] || match)!, date, parts, locales }))\n    }\n  }\n  const orderedParts = parts.reduce((array, element) => {\n    const lastElement = array[array.length - 1]\n    if (element.isToken() && lastElement !== undefined && lastElement.isToken()) {\n      lastElement.setValue(element.token)\n    } else {\n      array.push(element)\n    }\n    return array\n  }, Arr.empty<DatePart>())\n  parts.splice(0, parts.length, ...orderedParts)\n  return parts\n}\n\ninterface DatePartParams {\n  readonly token: string\n  readonly locales: Prompt.Prompt.DateOptions[\"locales\"]\n  readonly date?: globalThis.Date\n  readonly parts?: ReadonlyArray<DatePart>\n}\n\nabstract class DatePart {\n  token: string\n  readonly date: globalThis.Date\n  readonly parts: ReadonlyArray<DatePart>\n  readonly locales: Prompt.Prompt.DateOptions[\"locales\"]\n\n  constructor(params: DatePartParams) {\n    this.token = params.token\n    this.locales = params.locales\n    this.date = params.date || new Date()\n    this.parts = params.parts || [this]\n  }\n\n  /**\n   * Increments this date part.\n   */\n  abstract increment(): void\n\n  /**\n   * Decrements this date part.\n   */\n  abstract decrement(): void\n\n  /**\n   * Sets the current value of this date part to the provided value.\n   */\n  abstract setValue(value: string): void\n\n  /**\n   * Returns `true` if this `DatePart` is a `Token`, `false` otherwise.\n   */\n  isToken(): this is Token {\n    return false\n  }\n\n  /**\n   * Retrieves the next date part in the list of parts.\n   */\n  nextPart(): Option.Option<DatePart> {\n    return Arr.findFirstIndex(this.parts, (part) => part === this).pipe(\n      Option.flatMap((currentPartIndex) =>\n        Arr.findFirst(this.parts.slice(currentPartIndex + 1), (part) => !part.isToken())\n      )\n    )\n  }\n\n  /**\n   * Retrieves the previous date part in the list of parts.\n   */\n  previousPart(): Option.Option<DatePart> {\n    return Arr.findFirstIndex(this.parts, (part) => part === this).pipe(\n      Option.flatMap((currentPartIndex) =>\n        Arr.findLast(this.parts.slice(0, currentPartIndex), (part) => !part.isToken())\n      )\n    )\n  }\n\n  toString() {\n    return String(this.date)\n  }\n}\n\nclass Token extends DatePart {\n  increment(): void {}\n\n  decrement(): void {}\n\n  setValue(value: string): void {\n    this.token = this.token + value\n  }\n\n  isToken(): this is Token {\n    return true\n  }\n\n  toString() {\n    return this.token\n  }\n}\n\nclass Milliseconds extends DatePart {\n  increment(): void {\n    this.date.setMilliseconds(this.date.getMilliseconds() + 1)\n  }\n\n  decrement(): void {\n    this.date.setMilliseconds(this.date.getMilliseconds() - 1)\n  }\n\n  setValue(value: string): void {\n    this.date.setMilliseconds(Number.parseInt(value.slice(-this.token.length)))\n  }\n\n  toString() {\n    const millis = `${this.date.getMilliseconds()}`\n    return millis.padStart(4, \"0\").substring(0, this.token.length)\n  }\n}\n\nclass Seconds extends DatePart {\n  increment(): void {\n    this.date.setSeconds(this.date.getSeconds() + 1)\n  }\n\n  decrement(): void {\n    this.date.setSeconds(this.date.getSeconds() - 1)\n  }\n\n  setValue(value: string): void {\n    this.date.setSeconds(Number.parseInt(value.slice(-2)))\n  }\n\n  toString() {\n    const seconds = `${this.date.getSeconds()}`\n    return this.token.length > 1\n      ? seconds.padStart(2, \"0\")\n      : seconds\n  }\n}\n\nclass Minutes extends DatePart {\n  increment(): void {\n    this.date.setMinutes(this.date.getMinutes() + 1)\n  }\n\n  decrement(): void {\n    this.date.setMinutes(this.date.getMinutes() - 1)\n  }\n\n  setValue(value: string): void {\n    this.date.setMinutes(Number.parseInt(value.slice(-2)))\n  }\n\n  toString() {\n    const minutes = `${this.date.getMinutes()}`\n    return this.token.length > 1\n      ? minutes.padStart(2, \"0\") :\n      minutes\n  }\n}\n\nclass Hours extends DatePart {\n  increment(): void {\n    this.date.setHours(this.date.getHours() + 1)\n  }\n\n  decrement(): void {\n    this.date.setHours(this.date.getHours() - 1)\n  }\n\n  setValue(value: string): void {\n    this.date.setHours(Number.parseInt(value.slice(-2)))\n  }\n\n  toString() {\n    const hours = /h/.test(this.token)\n      ? this.date.getHours() % 12 || 12\n      : this.date.getHours()\n    return this.token.length > 1\n      ? `${hours}`.padStart(2, \"0\")\n      : `${hours}`\n  }\n}\n\nclass Day extends DatePart {\n  increment(): void {\n    this.date.setDate(this.date.getDate() + 1)\n  }\n\n  decrement(): void {\n    this.date.setDate(this.date.getDate() - 1)\n  }\n\n  setValue(value: string): void {\n    this.date.setDate(Number.parseInt(value.slice(-2)))\n  }\n\n  toString() {\n    const date = this.date.getDate()\n    const day = this.date.getDay()\n    return Match.value(this.token).pipe(\n      Match.when(\"DD\", () => `${date}`.padStart(2, \"0\")),\n      Match.when(\"Do\", () => `${date}${this.ordinalIndicator(date)}`),\n      Match.when(\"d\", () => `${day + 1}`),\n      Match.when(\"ddd\", () => this.locales!.weekdaysShort[day]!),\n      Match.when(\"dddd\", () => this.locales!.weekdays[day]!),\n      Match.orElse(() => `${date}`)\n    )\n  }\n\n  private ordinalIndicator(day: number): string {\n    return Match.value(day % 10).pipe(\n      Match.when(1, () => \"st\"),\n      Match.when(2, () => \"nd\"),\n      Match.when(3, () => \"rd\"),\n      Match.orElse(() => \"th\")\n    )\n  }\n}\n\nclass Month extends DatePart {\n  increment(): void {\n    this.date.setMonth(this.date.getMonth() + 1)\n  }\n\n  decrement(): void {\n    this.date.setMonth(this.date.getMonth() - 1)\n  }\n\n  setValue(value: string): void {\n    const month = Number.parseInt(value.slice(-2)) - 1\n    this.date.setMonth(month < 0 ? 0 : month)\n  }\n\n  toString() {\n    const month = this.date.getMonth()\n    return Match.value(this.token.length).pipe(\n      Match.when(2, () => `${month + 1}`.padStart(2, \"0\")),\n      Match.when(3, () => this.locales!.monthsShort[month]!),\n      Match.when(4, () => this.locales!.months[month]!),\n      Match.orElse(() => `${month + 1}`)\n    )\n  }\n}\n\nclass Year extends DatePart {\n  increment(): void {\n    this.date.setFullYear(this.date.getFullYear() + 1)\n  }\n\n  decrement(): void {\n    this.date.setFullYear(this.date.getFullYear() - 1)\n  }\n\n  setValue(value: string): void {\n    this.date.setFullYear(Number.parseInt(value.slice(-4)))\n  }\n\n  toString() {\n    const year = `${this.date.getFullYear()}`.padStart(4, \"0\")\n    return this.token.length === 2\n      ? year.substring(-2)\n      : year\n  }\n}\n\nclass Meridiem extends DatePart {\n  increment(): void {\n    this.date.setHours((this.date.getHours() + 12) % 24)\n  }\n\n  decrement(): void {\n    this.increment()\n  }\n\n  setValue(_value: string): void {}\n\n  toString() {\n    const meridiem = this.date.getHours() > 12 ? \"pm\" : \"am\"\n    return /A/.test(this.token)\n      ? meridiem.toUpperCase()\n      : meridiem\n  }\n}\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/file.ts",
    "content": "import * as FileSystem from \"@effect/platform/FileSystem\"\nimport * as Path from \"@effect/platform/Path\"\nimport * as Terminal from \"@effect/platform/Terminal\"\nimport * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Optimize from \"@effect/printer/Optimize\"\nimport * as Arr from \"effect/Array\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport type * as Prompt from \"../../Prompt.js\"\nimport * as InternalPrompt from \"../prompt.js\"\nimport { Action } from \"./action.js\"\nimport * as InternalAnsiUtils from \"./ansi-utils.js\"\nimport { entriesToDisplay } from \"./utils.js\"\n\ninterface FileOptions extends Required<Omit<Prompt.Prompt.FileOptions, \"startingPath\">> {\n  readonly startingPath: Option.Option<string>\n}\n\ninterface State {\n  readonly cursor: number\n  readonly files: ReadonlyArray<string>\n  readonly path: Option.Option<string>\n  readonly confirm: Confirm\n}\n\nconst CONFIRM_MESSAGE = \"The selected directory contains files. Would you like to traverse the selected directory?\"\ntype Confirm = Data.TaggedEnum<{\n  readonly Show: {}\n  readonly Hide: {}\n}>\nconst Confirm = Data.taggedEnum<Confirm>()\n\nconst showConfirmation = Confirm.$is(\"Show\")\n\nconst renderBeep = Doc.render(Doc.beep, { style: \"pretty\" })\n\nfunction resolveCurrentPath(\n  path: Option.Option<string>,\n  options: FileOptions\n): Effect.Effect<string, never, FileSystem.FileSystem> {\n  return Option.match(path, {\n    onNone: () =>\n      Option.match(options.startingPath, {\n        onNone: () => Effect.sync(() => process.cwd()),\n        onSome: (path) =>\n          Effect.flatMap(FileSystem.FileSystem, (fs) =>\n            // Ensure the user provided starting path exists\n            Effect.orDie(fs.exists(path)).pipe(\n              Effect.filterOrDieMessage(\n                identity,\n                `The provided starting path '${path}' does not exist`\n              ),\n              Effect.as(path)\n            ))\n      }),\n    onSome: (path) => Effect.succeed(path)\n  })\n}\n\nfunction getFileList(directory: string, options: FileOptions) {\n  return Effect.gen(function*() {\n    const fs = yield* FileSystem.FileSystem\n    const path = yield* Path.Path\n    const files = yield* Effect.orDie(fs.readDirectory(directory)).pipe(\n      // Always prepend the `\"..\"` option to the file list but allow it\n      // to be filtered out if the user so desires\n      Effect.map((files) => [\"..\", ...files])\n    )\n    return yield* Effect.filter(files, (file) => {\n      const result = options.filter(file)\n      const userDefinedFilter = Effect.isEffect(result)\n        ? result\n        : Effect.succeed(result)\n      const directoryFilter = options.type === \"directory\"\n        ? Effect.map(\n          Effect.orDie(fs.stat(path.join(directory, file))),\n          (info) => info.type === \"Directory\"\n        )\n        : Effect.succeed(true)\n      return Effect.zipWith(userDefinedFilter, directoryFilter, (a, b) => a && b)\n    }, { concurrency: files.length })\n  })\n}\n\nfunction handleClear(options: FileOptions) {\n  return (state: State, _: Prompt.Prompt.Action<State, string>) => {\n    return Effect.gen(function*() {\n      const terminal = yield* Terminal.Terminal\n      const columns = yield* terminal.columns\n      const currentPath = yield* resolveCurrentPath(state.path, options)\n      const text = \"\\n\".repeat(Math.min(state.files.length, options.maxPerPage))\n      const clearPath = InternalAnsiUtils.eraseText(currentPath, columns)\n      const message = showConfirmation(state.confirm) ? CONFIRM_MESSAGE : options.message\n      const clearPrompt = InternalAnsiUtils.eraseText(`\\n${message}`, columns)\n      const clearOptions = InternalAnsiUtils.eraseText(text, columns)\n      return clearOptions.pipe(\n        Doc.cat(clearPath),\n        Doc.cat(clearPrompt),\n        Optimize.optimize(Optimize.Deep),\n        Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n      )\n    })\n  }\n}\n\nconst NEWLINE_REGEX = /\\r?\\n/\n\nfunction renderPrompt(\n  confirm: Doc.AnsiDoc,\n  message: string,\n  leadingSymbol: Doc.AnsiDoc,\n  trailingSymbol: Doc.AnsiDoc\n) {\n  const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold)\n  const prefix = Doc.cat(leadingSymbol, Doc.space)\n  return Arr.match(message.split(NEWLINE_REGEX), {\n    onEmpty: () => Doc.hsep([prefix, trailingSymbol, confirm]),\n    onNonEmpty: (promptLines) => {\n      const lines = Arr.map(promptLines, (line) => annotateLine(line))\n      return prefix.pipe(\n        Doc.cat(Doc.nest(Doc.vsep(lines), 2)),\n        Doc.cat(Doc.space),\n        Doc.cat(trailingSymbol),\n        Doc.cat(Doc.space),\n        Doc.cat(confirm)\n      )\n    }\n  })\n}\n\nfunction renderPrefix(\n  state: State,\n  toDisplay: { readonly startIndex: number; readonly endIndex: number },\n  currentIndex: number,\n  length: number,\n  figures: Effect.Effect.Success<typeof InternalAnsiUtils.figures>\n) {\n  let prefix: Doc.AnsiDoc = Doc.space\n  if (currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0) {\n    prefix = figures.arrowUp\n  } else if (currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < length) {\n    prefix = figures.arrowDown\n  }\n  return state.cursor === currentIndex\n    ? figures.pointer.pipe(Doc.annotate(Ansi.cyanBright), Doc.cat(prefix))\n    : prefix.pipe(Doc.cat(Doc.space))\n}\n\nfunction renderFileName(file: string, isSelected: boolean) {\n  return isSelected\n    ? Doc.annotate(Doc.text(file), Ansi.combine(Ansi.underlined, Ansi.cyanBright))\n    : Doc.text(file)\n}\n\nfunction renderFiles(\n  state: State,\n  files: ReadonlyArray<string>,\n  figures: Effect.Effect.Success<typeof InternalAnsiUtils.figures>,\n  options: FileOptions\n) {\n  const length = files.length\n  const toDisplay = entriesToDisplay(state.cursor, length, options.maxPerPage)\n  const documents: Array<Doc.AnsiDoc> = []\n  for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n    const isSelected = state.cursor === index\n    const prefix = renderPrefix(state, toDisplay, index, length, figures)\n    const fileName = renderFileName(files[index], isSelected)\n    documents.push(Doc.cat(prefix, fileName))\n  }\n  return Doc.vsep(documents)\n}\n\nfunction renderNextFrame(state: State, options: FileOptions) {\n  return Effect.gen(function*() {\n    const path = yield* Path.Path\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const currentPath = yield* resolveCurrentPath(state.path, options)\n    const selectedPath = state.files[state.cursor]\n    const resolvedPath = path.resolve(currentPath, selectedPath)\n    const resolvedPathMsg = figures.pointerSmall.pipe(\n      Doc.cat(Doc.space),\n      Doc.cat(Doc.text(resolvedPath)),\n      Doc.annotate(Ansi.blackBright)\n    )\n    if (showConfirmation(state.confirm)) {\n      const leadingSymbol = Doc.annotate(Doc.text(\"?\"), Ansi.cyanBright)\n      const trailingSymbol = Doc.annotate(figures.pointerSmall, Ansi.blackBright)\n      const confirm = Doc.annotate(Doc.text(\"(Y/n)\"), Ansi.blackBright)\n      const promptMsg = renderPrompt(confirm, CONFIRM_MESSAGE, leadingSymbol, trailingSymbol)\n      return Doc.cursorHide.pipe(\n        Doc.cat(promptMsg),\n        Doc.cat(Doc.hardLine),\n        Doc.cat(resolvedPathMsg),\n        Optimize.optimize(Optimize.Deep),\n        Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n      )\n    }\n    const leadingSymbol = Doc.annotate(figures.tick, Ansi.green)\n    const trailingSymbol = Doc.annotate(figures.ellipsis, Ansi.blackBright)\n    const promptMsg = renderPrompt(Doc.empty, options.message, leadingSymbol, trailingSymbol)\n    const files = renderFiles(state, state.files, figures, options)\n    return Doc.cursorHide.pipe(\n      Doc.cat(promptMsg),\n      Doc.cat(Doc.hardLine),\n      Doc.cat(resolvedPathMsg),\n      Doc.cat(Doc.hardLine),\n      Doc.cat(files),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction renderSubmission(value: string, options: FileOptions) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const leadingSymbol = Doc.annotate(figures.tick, Ansi.green)\n    const trailingSymbol = Doc.annotate(figures.ellipsis, Ansi.blackBright)\n    const promptMsg = renderPrompt(Doc.empty, options.message, leadingSymbol, trailingSymbol)\n    return promptMsg.pipe(\n      Doc.cat(Doc.space),\n      Doc.cat(Doc.annotate(Doc.text(value), Ansi.white)),\n      Doc.cat(Doc.hardLine),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction handleRender(options: FileOptions) {\n  return (_: State, action: Prompt.Prompt.Action<State, string>) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({ state }) => renderNextFrame(state, options),\n      Submit: ({ value }) => renderSubmission(value, options)\n    })\n  }\n}\n\nfunction processCursorUp(state: State) {\n  const cursor = state.cursor - 1\n  return Effect.succeed(Action.NextFrame({\n    state: { ...state, cursor: cursor < 0 ? state.files.length - 1 : cursor }\n  }))\n}\n\nfunction processCursorDown(state: State) {\n  return Effect.succeed(Action.NextFrame({\n    state: { ...state, cursor: (state.cursor + 1) % state.files.length }\n  }))\n}\n\nfunction processSelection(state: State, options: FileOptions) {\n  return Effect.gen(function*() {\n    const fs = yield* FileSystem.FileSystem\n    const path = yield* Path.Path\n    const currentPath = yield* resolveCurrentPath(state.path, options)\n    const selectedPath = state.files[state.cursor]\n    const resolvedPath = path.resolve(currentPath, selectedPath)\n    const info = yield* Effect.orDie(fs.stat(resolvedPath))\n    if (info.type === \"Directory\") {\n      const files = yield* getFileList(resolvedPath, options)\n      const filesWithoutParent = files.filter((file) => file !== \"..\")\n      // If the user selected a directory AND the prompt type can result with\n      // a directory, we must confirm:\n      //  - If the selected directory has any files\n      //  - Confirm whether or not the user wants to traverse those files\n      if (options.type === \"directory\" || options.type === \"either\") {\n        return filesWithoutParent.length === 0\n          // Directory is empty so it's safe to select it\n          ? Action.Submit({ value: resolvedPath })\n          // Directory has contents - show confirmation to user\n          : Action.NextFrame({\n            state: { ...state, confirm: Confirm.Show() }\n          })\n      }\n      return Action.NextFrame({\n        state: {\n          cursor: 0,\n          files,\n          path: Option.some(resolvedPath),\n          confirm: Confirm.Hide()\n        }\n      })\n    }\n    return Action.Submit({ value: resolvedPath })\n  })\n}\n\nfunction handleProcess(options: FileOptions) {\n  return (input: Terminal.UserInput, state: State) =>\n    Effect.gen(function*() {\n      switch (input.key.name) {\n        case \"k\":\n        case \"up\": {\n          return yield* processCursorUp(state)\n        }\n        case \"j\":\n        case \"down\":\n        case \"tab\": {\n          return yield* processCursorDown(state)\n        }\n        case \"enter\":\n        case \"return\": {\n          return yield* processSelection(state, options)\n        }\n        case \"y\":\n        case \"t\": {\n          if (showConfirmation(state.confirm)) {\n            const path = yield* Path.Path\n            const currentPath = yield* resolveCurrentPath(state.path, options)\n            const selectedPath = state.files[state.cursor]\n            const resolvedPath = path.resolve(currentPath, selectedPath)\n            const files = yield* getFileList(resolvedPath, options)\n            return Action.NextFrame({\n              state: {\n                cursor: 0,\n                files,\n                path: Option.some(resolvedPath),\n                confirm: Confirm.Hide()\n              }\n            })\n          }\n          return Action.Beep()\n        }\n        case \"n\":\n        case \"f\": {\n          if (showConfirmation(state.confirm)) {\n            const path = yield* Path.Path\n            const currentPath = yield* resolveCurrentPath(state.path, options)\n            const selectedPath = state.files[state.cursor]\n            const resolvedPath = path.resolve(currentPath, selectedPath)\n            return Action.Submit({ value: resolvedPath })\n          }\n          return Action.Beep()\n        }\n        default: {\n          return Action.Beep()\n        }\n      }\n    })\n}\n\n/** @internal */\nexport const file = (options: Prompt.Prompt.FileOptions = {}): Prompt.Prompt<string> => {\n  const opts: FileOptions = {\n    type: options.type ?? \"file\",\n    message: options.message ?? `Choose a file`,\n    startingPath: Option.fromNullable(options.startingPath),\n    maxPerPage: options.maxPerPage ?? 10,\n    filter: options.filter ?? (() => Effect.succeed(true))\n  }\n  const initialState: Effect.Effect<\n    State,\n    never,\n    Prompt.Prompt.Environment\n  > = Effect.gen(function*() {\n    const path = Option.none<string>()\n    const currentPath = yield* resolveCurrentPath(path, opts)\n    const files = yield* getFileList(currentPath, opts)\n    const confirm = Confirm.Hide()\n    return { cursor: 0, files, path, confirm }\n  })\n  return InternalPrompt.custom(initialState, {\n    render: handleRender(opts),\n    process: handleProcess(opts),\n    clear: handleClear(opts)\n  })\n}\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/list.ts",
    "content": "import type * as Prompt from \"../../Prompt.js\"\nimport * as InternalPrompt from \"../prompt.js\"\nimport * as InternalTextPrompt from \"./text.js\"\n\n/** @internal */\nexport const list = (options: Prompt.Prompt.ListOptions): Prompt.Prompt<Array<string>> =>\n  InternalTextPrompt.text(options).pipe(\n    InternalPrompt.map((output) => output.split(options.delimiter || \",\"))\n  )\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/multi-select.ts",
    "content": "import * as Terminal from \"@effect/platform/Terminal\"\nimport * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Optimize from \"@effect/printer/Optimize\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport * as Number from \"effect/Number\"\nimport * as Option from \"effect/Option\"\nimport type * as Prompt from \"../../Prompt.js\"\nimport * as InternalPrompt from \"../prompt.js\"\nimport { Action } from \"./action.js\"\nimport * as InternalAnsiUtils from \"./ansi-utils.js\"\nimport { entriesToDisplay } from \"./utils.js\"\n\ninterface SelectOptions<A> extends Required<Prompt.Prompt.SelectOptions<A>> {}\ninterface MultiSelectOptions extends Prompt.Prompt.MultiSelectOptions {}\n\ntype State = {\n  index: number\n  selectedIndices: Set<number>\n  error: Option.Option<string>\n}\n\nconst renderBeep = Doc.render(Doc.beep, { style: \"pretty\" })\n\nconst NEWLINE_REGEX = /\\r?\\n/\n\nfunction renderOutput<A>(\n  leadingSymbol: Doc.AnsiDoc,\n  trailingSymbol: Doc.AnsiDoc,\n  options: SelectOptions<A>\n) {\n  const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold)\n  const prefix = Doc.cat(leadingSymbol, Doc.space)\n  return Arr.match(options.message.split(NEWLINE_REGEX), {\n    onEmpty: () => Doc.hsep([prefix, trailingSymbol]),\n    onNonEmpty: (promptLines) => {\n      const lines = Arr.map(promptLines, (line) => annotateLine(line))\n      return prefix.pipe(\n        Doc.cat(Doc.nest(Doc.vsep(lines), 2)),\n        Doc.cat(Doc.space),\n        Doc.cat(trailingSymbol),\n        Doc.cat(Doc.space)\n      )\n    }\n  })\n}\n\nfunction renderError(state: State, pointer: Doc.AnsiDoc) {\n  return Option.match(state.error, {\n    onNone: () => Doc.empty,\n    onSome: (error) =>\n      Arr.match(error.split(NEWLINE_REGEX), {\n        onEmpty: () => Doc.empty,\n        onNonEmpty: (errorLines) => {\n          const annotateLine = (line: string): Doc.AnsiDoc =>\n            Doc.annotate(Doc.text(line), Ansi.combine(Ansi.italicized, Ansi.red))\n          const prefix = Doc.cat(Doc.annotate(pointer, Ansi.red), Doc.space)\n          const lines = Arr.map(errorLines, (str) => annotateLine(str))\n          return Doc.cursorSavePosition.pipe(\n            Doc.cat(Doc.hardLine),\n            Doc.cat(prefix),\n            Doc.cat(Doc.align(Doc.vsep(lines))),\n            Doc.cat(Doc.cursorRestorePosition)\n          )\n        }\n      })\n  })\n}\n\nfunction renderChoiceDescription<A>(\n  choice: Prompt.Prompt.SelectChoice<A>,\n  isHighlighted: boolean\n) {\n  if (!choice.disabled && choice.description && isHighlighted) {\n    return Doc.char(\"-\").pipe(\n      Doc.cat(Doc.space),\n      Doc.cat(Doc.text(choice.description)),\n      Doc.annotate(Ansi.blackBright)\n    )\n  }\n  return Doc.empty\n}\n\nconst metaOptionsCount = 2\n\nfunction renderChoices<A>(\n  state: State,\n  options: SelectOptions<A> & MultiSelectOptions,\n  figures: Effect.Effect.Success<typeof InternalAnsiUtils.figures>\n) {\n  const choices = options.choices\n  const totalChoices = choices.length\n  const selectedCount = state.selectedIndices.size\n  const allSelected = selectedCount === totalChoices\n\n  const selectAllText = allSelected\n    ? options?.selectNone ?? \"Select None\"\n    : options?.selectAll ?? \"Select All\"\n\n  const inverseSelectionText = options?.inverseSelection ?? \"Inverse Selection\"\n\n  const metaOptions = [\n    { title: selectAllText },\n    { title: inverseSelectionText }\n  ]\n  const allChoices = [...metaOptions, ...choices]\n  const toDisplay = entriesToDisplay(state.index, allChoices.length, options.maxPerPage)\n  const documents: Array<Doc.AnsiDoc> = []\n  for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n    const choice = allChoices[index]\n    const isHighlighted = state.index === index\n    let prefix: Doc.AnsiDoc = Doc.space\n    if (index === toDisplay.startIndex && toDisplay.startIndex > 0) {\n      prefix = figures.arrowUp\n    } else if (index === toDisplay.endIndex - 1 && toDisplay.endIndex < allChoices.length) {\n      prefix = figures.arrowDown\n    }\n    if (index < metaOptions.length) {\n      // Meta options\n      const title = isHighlighted\n        ? Doc.annotate(Doc.text(choice.title), Ansi.cyanBright)\n        : Doc.text(choice.title)\n      documents.push(\n        prefix.pipe(\n          Doc.cat(Doc.space),\n          Doc.cat(title)\n        )\n      )\n    } else {\n      // Regular choices\n      const choiceIndex = index - metaOptions.length\n      const isSelected = state.selectedIndices.has(choiceIndex)\n      const checkbox = isSelected ? figures.checkboxOn : figures.checkboxOff\n      const annotatedCheckbox = isHighlighted\n        ? Doc.annotate(checkbox, Ansi.cyanBright)\n        : checkbox\n      const title = Doc.text(choice.title)\n      const description = renderChoiceDescription(choice as Prompt.Prompt.SelectChoice<A>, isHighlighted)\n      documents.push(\n        prefix.pipe(\n          Doc.cat(Doc.space),\n          Doc.cat(annotatedCheckbox),\n          Doc.cat(Doc.space),\n          Doc.cat(title),\n          Doc.cat(Doc.space),\n          Doc.cat(description)\n        )\n      )\n    }\n  }\n  return Doc.vsep(documents)\n}\n\nfunction renderNextFrame<A>(state: State, options: SelectOptions<A>) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const choices = renderChoices(state, options, figures)\n    const leadingSymbol = Doc.annotate(Doc.text(\"?\"), Ansi.cyanBright)\n    const trailingSymbol = Doc.annotate(figures.pointerSmall, Ansi.blackBright)\n    const promptMsg = renderOutput(leadingSymbol, trailingSymbol, options)\n    const error = renderError(state, figures.pointer)\n    return Doc.cursorHide.pipe(\n      Doc.cat(promptMsg),\n      Doc.cat(Doc.hardLine),\n      Doc.cat(choices),\n      Doc.cat(error),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction renderSubmission<A>(state: State, options: SelectOptions<A>) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const selectedChoices = Array.from(state.selectedIndices).sort(Number.Order).map((index) =>\n      options.choices[index].title\n    )\n    const selectedText = selectedChoices.join(\", \")\n    const selected = Doc.text(selectedText)\n    const leadingSymbol = Doc.annotate(figures.tick, Ansi.green)\n    const trailingSymbol = Doc.annotate(figures.ellipsis, Ansi.blackBright)\n    const promptMsg = renderOutput(leadingSymbol, trailingSymbol, options)\n    return promptMsg.pipe(\n      Doc.cat(Doc.space),\n      Doc.cat(Doc.annotate(selected, Ansi.white)),\n      Doc.cat(Doc.hardLine),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction processCursorUp(state: State, totalChoices: number) {\n  const newIndex = state.index === 0 ? totalChoices - 1 : state.index - 1\n  return Effect.succeed(Action.NextFrame({ state: { ...state, index: newIndex } }))\n}\n\nfunction processCursorDown(state: State, totalChoices: number) {\n  const newIndex = (state.index + 1) % totalChoices\n  return Effect.succeed(Action.NextFrame({ state: { ...state, index: newIndex } }))\n}\n\nfunction processSpace<A>(\n  state: State,\n  options: SelectOptions<A>\n) {\n  const selectedIndices = new Set(state.selectedIndices)\n  if (state.index === 0) {\n    if (state.selectedIndices.size === options.choices.length) {\n      selectedIndices.clear()\n    } else {\n      for (let i = 0; i < options.choices.length; i++) {\n        selectedIndices.add(i)\n      }\n    }\n  } else if (state.index === 1) {\n    for (let i = 0; i < options.choices.length; i++) {\n      if (state.selectedIndices.has(i)) {\n        selectedIndices.delete(i)\n      } else {\n        selectedIndices.add(i)\n      }\n    }\n  } else {\n    const choiceIndex = state.index - metaOptionsCount\n    if (selectedIndices.has(choiceIndex)) {\n      selectedIndices.delete(choiceIndex)\n    } else {\n      selectedIndices.add(choiceIndex)\n    }\n  }\n  return Effect.succeed(Action.NextFrame({ state: { ...state, selectedIndices } }))\n}\n\nexport function handleClear<A>(options: SelectOptions<A>) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const clearPrompt = Doc.cat(Doc.eraseLine, Doc.cursorLeft)\n    const text = \"\\n\".repeat(Math.min(options.choices.length + 2, options.maxPerPage)) + options.message + 1\n    const clearOutput = InternalAnsiUtils.eraseText(text, columns)\n    return clearOutput.pipe(\n      Doc.cat(clearPrompt),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction handleProcess<A>(options: SelectOptions<A> & MultiSelectOptions) {\n  return (input: Terminal.UserInput, state: State) => {\n    const totalChoices = options.choices.length + metaOptionsCount\n    switch (input.key.name) {\n      case \"k\":\n      case \"up\": {\n        return processCursorUp({ ...state, error: Option.none() }, totalChoices)\n      }\n      case \"j\":\n      case \"down\":\n      case \"tab\": {\n        return processCursorDown({ ...state, error: Option.none() }, totalChoices)\n      }\n      case \"space\": {\n        return processSpace(state, options)\n      }\n      case \"enter\":\n      case \"return\": {\n        const selectedCount = state.selectedIndices.size\n        if (options.min !== undefined && selectedCount < options.min) {\n          return Effect.succeed(\n            Action.NextFrame({ state: { ...state, error: Option.some(`At least ${options.min} are required`) } })\n          )\n        }\n        if (options.max !== undefined && selectedCount > options.max) {\n          return Effect.succeed(\n            Action.NextFrame({ state: { ...state, error: Option.some(`At most ${options.max} choices are allowed`) } })\n          )\n        }\n        const selectedValues = Array.from(state.selectedIndices).sort(Number.Order).map((index) =>\n          options.choices[index].value\n        )\n        return Effect.succeed(Action.Submit({ value: selectedValues }))\n      }\n      default: {\n        return Effect.succeed(Action.Beep())\n      }\n    }\n  }\n}\n\nfunction handleRender<A>(options: SelectOptions<A>) {\n  return (state: State, action: Prompt.Prompt.Action<State, Array<A>>) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({ state }) => renderNextFrame(state, options),\n      Submit: () => renderSubmission(state, options)\n    })\n  }\n}\n\n/** @internal */\nexport const multiSelect = <const A>(\n  options: Prompt.Prompt.SelectOptions<A> & Prompt.Prompt.MultiSelectOptions\n): Prompt.Prompt<Array<A>> => {\n  const opts: SelectOptions<A> & MultiSelectOptions = {\n    maxPerPage: 10,\n    ...options\n  }\n  // Seed initial selection from choices marked as selected: true\n  const initialSelected = new Set<number>()\n  for (let i = 0; i < opts.choices.length; i++) {\n    const choice = opts.choices[i] as Prompt.Prompt.SelectChoice<A>\n    if (choice.selected === true) {\n      initialSelected.add(i)\n    }\n  }\n  return InternalPrompt.custom({ index: 0, selectedIndices: initialSelected, error: Option.none() }, {\n    render: handleRender(opts),\n    process: handleProcess(opts),\n    clear: () => handleClear(opts)\n  })\n}\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/number.ts",
    "content": "import * as Terminal from \"@effect/platform/Terminal\"\nimport * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Optimize from \"@effect/printer/Optimize\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport * as EffectNumber from \"effect/Number\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Prompt from \"../../Prompt.js\"\nimport * as InternalPrompt from \"../prompt.js\"\nimport { Action } from \"./action.js\"\nimport * as InternalAnsiUtils from \"./ansi-utils.js\"\n\ninterface IntegerOptions extends Required<Prompt.Prompt.IntegerOptions> {}\ninterface FloatOptions extends Required<Prompt.Prompt.FloatOptions> {}\n\ninterface State {\n  readonly cursor: number\n  readonly value: string\n  readonly error: Option.Option<string>\n}\n\nconst parseInt = Schema.NumberFromString.pipe(\n  Schema.int(),\n  Schema.decodeUnknown\n)\n\nconst parseFloat = Schema.decodeUnknown(Schema.NumberFromString)\n\nconst renderBeep = Doc.render(Doc.beep, { style: \"pretty\" })\n\nfunction handleClear(options: IntegerOptions) {\n  return (state: State, _: Prompt.Prompt.Action<State, number>) => {\n    return Effect.gen(function*() {\n      const terminal = yield* Terminal.Terminal\n      const columns = yield* terminal.columns\n      const resetCurrentLine = Doc.cat(Doc.eraseLine, Doc.cursorLeft)\n      const clearError = Option.match(state.error, {\n        onNone: () => Doc.empty,\n        onSome: (error) =>\n          Doc.cursorDown(InternalAnsiUtils.lines(error, columns)).pipe(\n            Doc.cat(InternalAnsiUtils.eraseText(`\\n${error}`, columns))\n          )\n      })\n      const clearOutput = InternalAnsiUtils.eraseText(options.message, columns)\n      return clearError.pipe(\n        Doc.cat(clearOutput),\n        Doc.cat(resetCurrentLine),\n        Optimize.optimize(Optimize.Deep),\n        Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n      )\n    })\n  }\n}\n\nfunction renderInput(state: State, submitted: boolean) {\n  const annotation = Option.match(state.error, {\n    onNone: () => Ansi.combine(Ansi.underlined, Ansi.cyanBright),\n    onSome: () => Ansi.red\n  })\n  const value = state.value === \"\" ? Doc.empty : Doc.text(`${state.value}`)\n  return submitted ? value : Doc.annotate(value, annotation)\n}\n\nconst NEWLINE_REGEX = /\\r?\\n/\n\nfunction renderError(state: State, pointer: Doc.AnsiDoc) {\n  return Option.match(state.error, {\n    onNone: () => Doc.empty,\n    onSome: (error) =>\n      Arr.match(error.split(NEWLINE_REGEX), {\n        onEmpty: () => Doc.empty,\n        onNonEmpty: (errorLines) => {\n          const annotateLine = (line: string): Doc.AnsiDoc =>\n            Doc.annotate(Doc.text(line), Ansi.combine(Ansi.italicized, Ansi.red))\n          const prefix = Doc.cat(Doc.annotate(pointer, Ansi.red), Doc.space)\n          const lines = Arr.map(errorLines, (str) => annotateLine(str))\n          return Doc.cursorSavePosition.pipe(\n            Doc.cat(Doc.hardLine),\n            Doc.cat(prefix),\n            Doc.cat(Doc.align(Doc.vsep(lines))),\n            Doc.cat(Doc.cursorRestorePosition)\n          )\n        }\n      })\n  })\n}\n\nfunction renderOutput(\n  state: State,\n  leadingSymbol: Doc.AnsiDoc,\n  trailingSymbol: Doc.AnsiDoc,\n  options: IntegerOptions,\n  submitted: boolean = false\n) {\n  const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold)\n  const prefix = Doc.cat(leadingSymbol, Doc.space)\n  return Arr.match(options.message.split(/\\r?\\n/), {\n    onEmpty: () => Doc.hsep([prefix, trailingSymbol, renderInput(state, submitted)]),\n    onNonEmpty: (promptLines) => {\n      const lines = Arr.map(promptLines, (line) => annotateLine(line))\n      return prefix.pipe(\n        Doc.cat(Doc.nest(Doc.vsep(lines), 2)),\n        Doc.cat(Doc.space),\n        Doc.cat(trailingSymbol),\n        Doc.cat(Doc.space),\n        Doc.cat(renderInput(state, submitted))\n      )\n    }\n  })\n}\n\nfunction renderNextFrame(state: State, options: IntegerOptions) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const leadingSymbol = Doc.annotate(Doc.text(\"?\"), Ansi.cyanBright)\n    const trailingSymbol = Doc.annotate(figures.pointerSmall, Ansi.blackBright)\n    const errorMsg = renderError(state, figures.pointerSmall)\n    const promptMsg = renderOutput(state, leadingSymbol, trailingSymbol, options)\n    return promptMsg.pipe(\n      Doc.cat(errorMsg),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction renderSubmission(nextState: State, options: IntegerOptions) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const leadingSymbol = Doc.annotate(figures.tick, Ansi.green)\n    const trailingSymbol = Doc.annotate(figures.ellipsis, Ansi.blackBright)\n    const promptMsg = renderOutput(nextState, leadingSymbol, trailingSymbol, options, true)\n    return promptMsg.pipe(\n      Doc.cat(Doc.hardLine),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction processBackspace(state: State) {\n  if (state.value.length <= 0) {\n    return Effect.succeed(Action.Beep())\n  }\n  const value = state.value.slice(0, state.value.length - 1)\n  return Effect.succeed(Action.NextFrame({\n    state: { ...state, value, error: Option.none() }\n  }))\n}\n\nfunction defaultIntProcessor(state: State, input: string) {\n  if (state.value.length === 0 && input === \"-\") {\n    return Effect.succeed(Action.NextFrame({\n      state: { ...state, value: \"-\", error: Option.none() }\n    }))\n  }\n  return Effect.match(parseInt(state.value + input), {\n    onFailure: () => Action.Beep(),\n    onSuccess: (value) =>\n      Action.NextFrame({\n        state: { ...state, value: `${value}`, error: Option.none() }\n      })\n  })\n}\n\nfunction defaultFloatProcessor(\n  state: State,\n  input: string\n) {\n  if (input === \".\" && state.value.includes(\".\")) {\n    return Effect.succeed(Action.Beep())\n  }\n  if (state.value.length === 0 && input === \"-\") {\n    return Effect.succeed(Action.NextFrame({\n      state: { ...state, value: \"-\", error: Option.none() }\n    }))\n  }\n  return Effect.match(parseFloat(state.value + input), {\n    onFailure: () => Action.Beep(),\n    onSuccess: (value) =>\n      Action.NextFrame({\n        state: {\n          ...state,\n          value: input === \".\" ? `${value}.` : `${value}`,\n          error: Option.none()\n        }\n      })\n  })\n}\n\nconst initialState: State = {\n  cursor: 0,\n  value: \"\",\n  error: Option.none()\n}\n\nfunction handleRenderInteger(options: IntegerOptions) {\n  return (state: State, action: Prompt.Prompt.Action<State, Number>) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({ state }) => renderNextFrame(state, options),\n      Submit: () => renderSubmission(state, options)\n    })\n  }\n}\n\nfunction handleProcessInteger(options: IntegerOptions) {\n  return (input: Terminal.UserInput, state: State) => {\n    switch (input.key.name) {\n      case \"backspace\": {\n        return processBackspace(state)\n      }\n      case \"k\":\n      case \"up\": {\n        return Effect.succeed(Action.NextFrame({\n          state: {\n            ...state,\n            value: state.value === \"\" || state.value === \"-\"\n              ? `${options.incrementBy}`\n              : `${Number.parseInt(state.value) + options.incrementBy}`,\n            error: Option.none()\n          }\n        }))\n      }\n      case \"j\":\n      case \"down\": {\n        return Effect.succeed(Action.NextFrame({\n          state: {\n            ...state,\n            value: state.value === \"\" || state.value === \"-\"\n              ? `-${options.decrementBy}`\n              : `${Number.parseInt(state.value) - options.decrementBy}`,\n            error: Option.none()\n          }\n        }))\n      }\n      case \"enter\":\n      case \"return\": {\n        return Effect.matchEffect(parseInt(state.value), {\n          onFailure: () =>\n            Effect.succeed(Action.NextFrame({\n              state: {\n                ...state,\n                error: Option.some(\"Must provide an integer value\")\n              }\n            })),\n          onSuccess: (n) =>\n            Effect.match(options.validate(n), {\n              onFailure: (error) =>\n                Action.NextFrame({\n                  state: {\n                    ...state,\n                    error: Option.some(error)\n                  }\n                }),\n              onSuccess: (value) => Action.Submit({ value })\n            })\n        })\n      }\n      default: {\n        const value = Option.getOrElse(input.input, () => \"\")\n        return defaultIntProcessor(state, value)\n      }\n    }\n  }\n}\n\n/** @internal */\nexport const integer = (options: Prompt.Prompt.IntegerOptions): Prompt.Prompt<number> => {\n  const opts: IntegerOptions = {\n    min: Number.NEGATIVE_INFINITY,\n    max: Number.POSITIVE_INFINITY,\n    incrementBy: 1,\n    decrementBy: 1,\n    validate: (n) => {\n      if (n < opts.min) {\n        return Effect.fail(`${n} must be greater than or equal to ${opts.min}`)\n      }\n      if (n > opts.max) {\n        return Effect.fail(`${n} must be less than or equal to ${opts.max}`)\n      }\n      return Effect.succeed(n)\n    },\n    ...options\n  }\n  return InternalPrompt.custom(initialState, {\n    render: handleRenderInteger(opts),\n    process: handleProcessInteger(opts),\n    clear: handleClear(opts)\n  })\n}\n\nfunction handleRenderFloat(options: FloatOptions) {\n  return (state: State, action: Prompt.Prompt.Action<State, number>) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({ state }) => renderNextFrame(state, options),\n      Submit: () => renderSubmission(state, options)\n    })\n  }\n}\n\nfunction handleProcessFloat(options: FloatOptions) {\n  return (input: Terminal.UserInput, state: State) => {\n    switch (input.key.name) {\n      case \"backspace\": {\n        return processBackspace(state)\n      }\n      case \"k\":\n      case \"up\": {\n        return Effect.succeed(Action.NextFrame({\n          state: {\n            ...state,\n            value: state.value === \"\" || state.value === \"-\"\n              ? `${options.incrementBy}`\n              : `${Number.parseFloat(state.value) + options.incrementBy}`,\n            error: Option.none()\n          }\n        }))\n      }\n      case \"j\":\n      case \"down\": {\n        return Effect.succeed(Action.NextFrame({\n          state: {\n            ...state,\n            value: state.value === \"\" || state.value === \"-\"\n              ? `-${options.decrementBy}`\n              : `${Number.parseFloat(state.value) - options.decrementBy}`,\n            error: Option.none()\n          }\n        }))\n      }\n      case \"enter\":\n      case \"return\": {\n        return Effect.matchEffect(parseFloat(state.value), {\n          onFailure: () =>\n            Effect.succeed(Action.NextFrame({\n              state: {\n                ...state,\n                error: Option.some(\"Must provide a floating point value\")\n              }\n            })),\n          onSuccess: (n) =>\n            Effect.flatMap(\n              Effect.sync(() => EffectNumber.round(n, options.precision)),\n              (rounded) =>\n                Effect.match(options.validate(rounded), {\n                  onFailure: (error) =>\n                    Action.NextFrame({\n                      state: {\n                        ...state,\n                        error: Option.some(error)\n                      }\n                    }),\n                  onSuccess: (value) => Action.Submit({ value })\n                })\n            )\n        })\n      }\n      default: {\n        const value = Option.getOrElse(input.input, () => \"\")\n        return defaultFloatProcessor(state, value)\n      }\n    }\n  }\n}\n\n/** @internal */\nexport const float = (options: Prompt.Prompt.FloatOptions): Prompt.Prompt<number> => {\n  const opts: FloatOptions = {\n    min: Number.NEGATIVE_INFINITY,\n    max: Number.POSITIVE_INFINITY,\n    incrementBy: 1,\n    decrementBy: 1,\n    precision: 2,\n    validate: (n) => {\n      if (n < opts.min) {\n        return Effect.fail(`${n} must be greater than or equal to ${opts.min}`)\n      }\n      if (n > opts.max) {\n        return Effect.fail(`${n} must be less than or equal to ${opts.max}`)\n      }\n      return Effect.succeed(n)\n    },\n    ...options\n  }\n  return InternalPrompt.custom(initialState, {\n    render: handleRenderFloat(opts),\n    process: handleProcessFloat(opts),\n    clear: handleClear(opts)\n  })\n}\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/select.ts",
    "content": "import * as Terminal from \"@effect/platform/Terminal\"\nimport * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Optimize from \"@effect/printer/Optimize\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Prompt from \"../../Prompt.js\"\nimport * as InternalPrompt from \"../prompt.js\"\nimport { Action } from \"./action.js\"\nimport * as InternalAnsiUtils from \"./ansi-utils.js\"\nimport { entriesToDisplay } from \"./utils.js\"\n\ntype State = number\n\ninterface SelectOptions<A> extends Required<Prompt.Prompt.SelectOptions<A>> {}\n\nconst renderBeep = Doc.render(Doc.beep, { style: \"pretty\" })\n\nconst NEWLINE_REGEX = /\\r?\\n/\n\nfunction renderOutput<A>(\n  leadingSymbol: Doc.AnsiDoc,\n  trailingSymbol: Doc.AnsiDoc,\n  options: SelectOptions<A>\n) {\n  const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold)\n  const prefix = Doc.cat(leadingSymbol, Doc.space)\n  return Arr.match(options.message.split(NEWLINE_REGEX), {\n    onEmpty: () => Doc.hsep([prefix, trailingSymbol]),\n    onNonEmpty: (promptLines) => {\n      const lines = Arr.map(promptLines, (line) => annotateLine(line))\n      return prefix.pipe(\n        Doc.cat(Doc.nest(Doc.vsep(lines), 2)),\n        Doc.cat(Doc.space),\n        Doc.cat(trailingSymbol),\n        Doc.cat(Doc.space)\n      )\n    }\n  })\n}\n\nfunction renderChoicePrefix<A>(\n  state: State,\n  choices: SelectOptions<A>[\"choices\"],\n  toDisplay: { readonly startIndex: number; readonly endIndex: number },\n  currentIndex: number,\n  figures: Effect.Effect.Success<typeof InternalAnsiUtils.figures>\n) {\n  let prefix: Doc.AnsiDoc = Doc.space\n  if (currentIndex === toDisplay.startIndex && toDisplay.startIndex > 0) {\n    prefix = figures.arrowUp\n  } else if (currentIndex === toDisplay.endIndex - 1 && toDisplay.endIndex < choices.length) {\n    prefix = figures.arrowDown\n  }\n  if (choices[currentIndex].disabled) {\n    const annotation = Ansi.combine(Ansi.bold, Ansi.blackBright)\n    return state === currentIndex\n      ? figures.pointer.pipe(Doc.annotate(annotation), Doc.cat(prefix))\n      : prefix.pipe(Doc.cat(Doc.space))\n  }\n  return state === currentIndex\n    ? figures.pointer.pipe(Doc.annotate(Ansi.cyanBright), Doc.cat(prefix))\n    : prefix.pipe(Doc.cat(Doc.space))\n}\n\nfunction renderChoiceTitle<A>(\n  choice: Prompt.Prompt.SelectChoice<A>,\n  isSelected: boolean\n) {\n  const title = Doc.text(choice.title)\n  if (isSelected) {\n    return choice.disabled\n      ? Doc.annotate(title, Ansi.combine(Ansi.underlined, Ansi.blackBright))\n      : Doc.annotate(title, Ansi.combine(Ansi.underlined, Ansi.cyanBright))\n  }\n  return choice.disabled\n    ? Doc.annotate(title, Ansi.combine(Ansi.strikethrough, Ansi.blackBright))\n    : title\n}\n\nfunction renderChoiceDescription<A>(\n  choice: Prompt.Prompt.SelectChoice<A>,\n  isSelected: boolean\n) {\n  if (!choice.disabled && choice.description && isSelected) {\n    return Doc.char(\"-\").pipe(\n      Doc.cat(Doc.space),\n      Doc.cat(Doc.text(choice.description)),\n      Doc.annotate(Ansi.blackBright)\n    )\n  }\n  return Doc.empty\n}\n\nfunction renderChoices<A>(\n  state: State,\n  options: SelectOptions<A>,\n  figures: Effect.Effect.Success<typeof InternalAnsiUtils.figures>\n) {\n  const choices = options.choices\n  const toDisplay = entriesToDisplay(state, choices.length, options.maxPerPage)\n  const documents: Array<Doc.AnsiDoc> = []\n  for (let index = toDisplay.startIndex; index < toDisplay.endIndex; index++) {\n    const choice = choices[index]\n    const isSelected = state === index\n    const prefix = renderChoicePrefix(state, choices, toDisplay, index, figures)\n    const title = renderChoiceTitle(choice, isSelected)\n    const description = renderChoiceDescription(choice, isSelected)\n    documents.push(prefix.pipe(Doc.cat(title), Doc.cat(Doc.space), Doc.cat(description)))\n  }\n  return Doc.vsep(documents)\n}\n\nfunction renderNextFrame<A>(state: State, options: SelectOptions<A>) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const choices = renderChoices(state, options, figures)\n    const leadingSymbol = Doc.annotate(Doc.text(\"?\"), Ansi.cyanBright)\n    const trailingSymbol = Doc.annotate(figures.pointerSmall, Ansi.blackBright)\n    const promptMsg = renderOutput(leadingSymbol, trailingSymbol, options)\n    return Doc.cursorHide.pipe(\n      Doc.cat(promptMsg),\n      Doc.cat(Doc.hardLine),\n      Doc.cat(choices),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction renderSubmission<A>(state: State, options: SelectOptions<A>) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const selected = Doc.text(options.choices[state].title)\n    const leadingSymbol = Doc.annotate(figures.tick, Ansi.green)\n    const trailingSymbol = Doc.annotate(figures.ellipsis, Ansi.blackBright)\n    const promptMsg = renderOutput(leadingSymbol, trailingSymbol, options)\n    return promptMsg.pipe(\n      Doc.cat(Doc.space),\n      Doc.cat(Doc.annotate(selected, Ansi.white)),\n      Doc.cat(Doc.hardLine),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction processCursorUp<A>(state: State, choices: Prompt.Prompt.SelectOptions<A>[\"choices\"]) {\n  if (state === 0) {\n    return Effect.succeed(Action.NextFrame({ state: choices.length - 1 }))\n  }\n  return Effect.succeed(Action.NextFrame({ state: state - 1 }))\n}\n\nfunction processCursorDown<A>(state: State, choices: Prompt.Prompt.SelectOptions<A>[\"choices\"]) {\n  if (state === choices.length - 1) {\n    return Effect.succeed(Action.NextFrame({ state: 0 }))\n  }\n  return Effect.succeed(Action.NextFrame({ state: state + 1 }))\n}\n\nfunction processNext<A>(state: State, choices: Prompt.Prompt.SelectOptions<A>[\"choices\"]) {\n  return Effect.succeed(Action.NextFrame({ state: (state + 1) % choices.length }))\n}\n\nfunction handleRender<A>(options: SelectOptions<A>) {\n  return (state: State, action: Prompt.Prompt.Action<State, A>) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({ state }) => renderNextFrame(state, options),\n      Submit: () => renderSubmission(state, options)\n    })\n  }\n}\n\nexport function handleClear<A>(options: SelectOptions<A>) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const clearPrompt = Doc.cat(Doc.eraseLine, Doc.cursorLeft)\n    const text = \"\\n\".repeat(Math.min(options.choices.length, options.maxPerPage)) + options.message\n    const clearOutput = InternalAnsiUtils.eraseText(text, columns)\n    return clearOutput.pipe(\n      Doc.cat(clearPrompt),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction handleProcess<A>(options: SelectOptions<A>) {\n  return (input: Terminal.UserInput, state: State) => {\n    switch (input.key.name) {\n      case \"k\":\n      case \"up\": {\n        return processCursorUp(state, options.choices)\n      }\n      case \"j\":\n      case \"down\": {\n        return processCursorDown(state, options.choices)\n      }\n      case \"tab\": {\n        return processNext(state, options.choices)\n      }\n      case \"enter\":\n      case \"return\": {\n        const selected = options.choices[state]\n        if (selected.disabled) {\n          return Effect.succeed(Action.Beep())\n        }\n        return Effect.succeed(Action.Submit({ value: selected.value }))\n      }\n      default: {\n        return Effect.succeed(Action.Beep())\n      }\n    }\n  }\n}\n\n/** @internal */\nexport const select = <const A>(options: Prompt.Prompt.SelectOptions<A>): Prompt.Prompt<A> => {\n  const opts: SelectOptions<A> = {\n    maxPerPage: 10,\n    ...options\n  }\n  // Validate and seed initial index from any choice marked selected: true\n  let initialIndex = 0\n  let seenSelected = -1\n  for (let i = 0; i < opts.choices.length; i++) {\n    const choice = opts.choices[i] as Prompt.Prompt.SelectChoice<A>\n    if (choice.selected === true) {\n      if (seenSelected !== -1) {\n        throw new Error(\"InvalidArgumentException: only a single choice can be selected by default for Prompt.select\")\n      }\n      seenSelected = i\n    }\n  }\n  if (seenSelected !== -1) {\n    initialIndex = seenSelected\n  }\n  return InternalPrompt.custom(initialIndex, {\n    render: handleRender(opts),\n    process: handleProcess(opts),\n    clear: () => handleClear(opts)\n  })\n}\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/text.ts",
    "content": "import * as Terminal from \"@effect/platform/Terminal\"\nimport * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Optimize from \"@effect/printer/Optimize\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Redacted from \"effect/Redacted\"\nimport type * as Prompt from \"../../Prompt.js\"\nimport * as InternalPrompt from \"../prompt.js\"\nimport { Action } from \"./action.js\"\nimport * as InternalAnsiUtils from \"./ansi-utils.js\"\n\ninterface Options extends Required<Prompt.Prompt.TextOptions> {\n  /**\n   * The type of the text option.\n   */\n  readonly type: \"hidden\" | \"password\" | \"text\"\n}\n\ninterface State {\n  readonly cursor: number\n  readonly value: string\n  readonly error: Option.Option<string>\n}\n\nfunction getValue(state: State, options: Options): string {\n  return state.value.length > 0 ? state.value : options.default\n}\n\nconst renderBeep = Doc.render(Doc.beep, { style: \"pretty\" })\n\nfunction renderClearScreen(state: State, options: Options) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    // Erase the current line and place the cursor in column one\n    const resetCurrentLine = Doc.cat(Doc.eraseLine, Doc.cursorLeft)\n    // Check for any error output\n    const clearError = Option.match(state.error, {\n      onNone: () => Doc.empty,\n      onSome: (error) =>\n        // If there was an error, move the cursor down to the final error line and\n        // then clear all lines of error output\n        Doc.cursorDown(InternalAnsiUtils.lines(error, columns)).pipe(\n          // Add a leading newline to the error message to ensure that the corrrect\n          // number of error lines are erased\n          Doc.cat(InternalAnsiUtils.eraseText(`\\n${error}`, columns))\n        )\n    })\n    // Ensure that the prior prompt output is cleaned up\n    // Calculate full rendered line: \"? \" + message + \" › \" + input\n    const inputValue = state.value.length > 0 ? state.value : options.default\n    const fullLine = `? ${options.message} \\u203a ${inputValue}`\n    const clearOutput = InternalAnsiUtils.eraseText(fullLine, columns)\n    // Concatenate and render all documents\n    return clearError.pipe(\n      Doc.cat(clearOutput),\n      Doc.cat(resetCurrentLine),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction renderInput(nextState: State, options: Options, submitted: boolean) {\n  const text = getValue(nextState, options)\n\n  const annotation = Option.match(nextState.error, {\n    onNone: () => {\n      if (submitted) {\n        return Ansi.white\n      }\n\n      if (nextState.value.length === 0) {\n        return Ansi.blackBright\n      }\n\n      return Ansi.combine(Ansi.underlined, Ansi.cyanBright)\n    },\n    onSome: () => Ansi.red\n  })\n\n  switch (options.type) {\n    case \"hidden\": {\n      return Doc.empty\n    }\n    case \"password\": {\n      return Doc.annotate(Doc.text(\"*\".repeat(text.length)), annotation)\n    }\n    case \"text\": {\n      return Doc.annotate(Doc.text(text), annotation)\n    }\n  }\n}\n\nfunction renderError(nextState: State, pointer: Doc.AnsiDoc) {\n  return Option.match(nextState.error, {\n    onNone: () => Doc.empty,\n    onSome: (error) =>\n      Arr.match(error.split(/\\r?\\n/), {\n        onEmpty: () => Doc.empty,\n        onNonEmpty: (errorLines) => {\n          const annotateLine = (line: string): Doc.AnsiDoc =>\n            Doc.text(line).pipe(\n              Doc.annotate(Ansi.combine(Ansi.italicized, Ansi.red))\n            )\n          const prefix = Doc.cat(Doc.annotate(pointer, Ansi.red), Doc.space)\n          const lines = Arr.map(errorLines, (str) => annotateLine(str))\n          return Doc.cursorSavePosition.pipe(\n            Doc.cat(Doc.hardLine),\n            Doc.cat(prefix),\n            Doc.cat(Doc.align(Doc.vsep(lines))),\n            Doc.cat(Doc.cursorRestorePosition)\n          )\n        }\n      })\n  })\n}\n\nfunction renderOutput(\n  nextState: State,\n  leadingSymbol: Doc.AnsiDoc,\n  trailingSymbol: Doc.AnsiDoc,\n  options: Options,\n  submitted: boolean = false\n) {\n  const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold)\n  const promptLines = options.message.split(/\\r?\\n/)\n  const prefix = Doc.cat(leadingSymbol, Doc.space)\n  if (Arr.isNonEmptyReadonlyArray(promptLines)) {\n    const lines = Arr.map(promptLines, (line) => annotateLine(line))\n    return prefix.pipe(\n      Doc.cat(Doc.nest(Doc.vsep(lines), 2)),\n      Doc.cat(Doc.space),\n      Doc.cat(trailingSymbol),\n      Doc.cat(Doc.space),\n      Doc.cat(renderInput(nextState, options, submitted))\n    )\n  }\n  return Doc.hsep([prefix, trailingSymbol, renderInput(nextState, options, submitted)])\n}\n\nfunction renderNextFrame(state: State, options: Options) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const leadingSymbol = Doc.annotate(Doc.text(\"?\"), Ansi.cyanBright)\n    const trailingSymbol = Doc.annotate(figures.pointerSmall, Ansi.blackBright)\n    const promptMsg = renderOutput(state, leadingSymbol, trailingSymbol, options)\n    const errorMsg = renderError(state, figures.pointerSmall)\n    const offset = state.cursor - state.value.length\n    return promptMsg.pipe(\n      Doc.cat(errorMsg),\n      Doc.cat(Doc.cursorMove(offset)),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction renderSubmission(state: State, options: Options) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const figures = yield* InternalAnsiUtils.figures\n    const leadingSymbol = Doc.annotate(figures.tick, Ansi.green)\n    const trailingSymbol = Doc.annotate(figures.ellipsis, Ansi.blackBright)\n    const promptMsg = renderOutput(state, leadingSymbol, trailingSymbol, options, true)\n    return promptMsg.pipe(\n      Doc.cat(Doc.hardLine),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction processBackspace(state: State) {\n  if (state.cursor <= 0) {\n    return Effect.succeed(Action.Beep())\n  }\n  const beforeCursor = state.value.slice(0, state.cursor - 1)\n  const afterCursor = state.value.slice(state.cursor)\n  const cursor = state.cursor - 1\n  const value = `${beforeCursor}${afterCursor}`\n  return Effect.succeed(\n    Action.NextFrame({\n      state: { ...state, cursor, value, error: Option.none() }\n    })\n  )\n}\n\nfunction processCursorLeft(state: State) {\n  if (state.cursor <= 0) {\n    return Effect.succeed(Action.Beep())\n  }\n  const cursor = state.cursor - 1\n  return Effect.succeed(\n    Action.NextFrame({\n      state: { ...state, cursor, error: Option.none() }\n    })\n  )\n}\n\nfunction processCursorRight(state: State) {\n  if (state.cursor >= state.value.length) {\n    return Effect.succeed(Action.Beep())\n  }\n  const cursor = Math.min(state.cursor + 1, state.value.length)\n  return Effect.succeed(\n    Action.NextFrame({\n      state: { ...state, cursor, error: Option.none() }\n    })\n  )\n}\n\nfunction processTab(state: State, options: Options) {\n  if (state.value === options.default) {\n    return Effect.succeed(Action.Beep())\n  }\n  const value = getValue(state, options)\n  const cursor = value.length\n  return Effect.succeed(\n    Action.NextFrame({\n      state: { ...state, value, cursor, error: Option.none() }\n    })\n  )\n}\n\nfunction defaultProcessor(input: string, state: State) {\n  const beforeCursor = state.value.slice(0, state.cursor)\n  const afterCursor = state.value.slice(state.cursor)\n  const value = `${beforeCursor}${input}${afterCursor}`\n  const cursor = state.cursor + input.length\n  return Effect.succeed(\n    Action.NextFrame({\n      state: { ...state, cursor, value, error: Option.none() }\n    })\n  )\n}\n\nconst initialState: State = {\n  cursor: 0,\n  value: \"\",\n  error: Option.none()\n}\n\nfunction handleRender(options: Options) {\n  return (state: State, action: Prompt.Prompt.Action<State, string>) => {\n    return Action.$match(action, {\n      Beep: () => Effect.succeed(renderBeep),\n      NextFrame: ({ state }) => renderNextFrame(state, options),\n      Submit: () => renderSubmission(state, options)\n    })\n  }\n}\n\nfunction handleProcess(options: Options) {\n  return (input: Terminal.UserInput, state: State) => {\n    switch (input.key.name) {\n      case \"backspace\": {\n        return processBackspace(state)\n      }\n      case \"left\": {\n        return processCursorLeft(state)\n      }\n      case \"right\": {\n        return processCursorRight(state)\n      }\n      case \"enter\":\n      case \"return\": {\n        const value = getValue(state, options)\n        return Effect.match(options.validate(value), {\n          onFailure: (error) =>\n            Action.NextFrame({\n              state: { ...state, value, error: Option.some(error) }\n            }),\n          onSuccess: (value) => Action.Submit({ value })\n        })\n      }\n      case \"tab\": {\n        return processTab(state, options)\n      }\n      default: {\n        const value = Option.getOrElse(input.input, () => \"\")\n        return defaultProcessor(value, state)\n      }\n    }\n  }\n}\n\nfunction handleClear(options: Options) {\n  return (state: State, _: Prompt.Prompt.Action<State, string>) => {\n    return renderClearScreen(state, options)\n  }\n}\n\nfunction basePrompt(\n  options: Prompt.Prompt.TextOptions,\n  type: Options[\"type\"]\n): Prompt.Prompt<string> {\n  const opts: Options = {\n    default: \"\",\n    type,\n    validate: Effect.succeed,\n    ...options\n  }\n\n  return InternalPrompt.custom(initialState, {\n    render: handleRender(opts),\n    process: handleProcess(opts),\n    clear: handleClear(opts)\n  })\n}\n\n/** @internal */\nexport const hidden = (\n  options: Prompt.Prompt.TextOptions\n): Prompt.Prompt<Redacted.Redacted> => basePrompt(options, \"hidden\").pipe(InternalPrompt.map(Redacted.make))\n\n/** @internal */\nexport const password = (\n  options: Prompt.Prompt.TextOptions\n): Prompt.Prompt<Redacted.Redacted> => basePrompt(options, \"password\").pipe(InternalPrompt.map(Redacted.make))\n\n/** @internal */\nexport const text = (\n  options: Prompt.Prompt.TextOptions\n): Prompt.Prompt<string> => basePrompt(options, \"text\")\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/toggle.ts",
    "content": "import * as Terminal from \"@effect/platform/Terminal\"\nimport * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport * as Optimize from \"@effect/printer/Optimize\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Prompt from \"../../Prompt.js\"\nimport * as InternalPrompt from \"../prompt.js\"\nimport { Action } from \"./action.js\"\nimport * as InternalAnsiUtils from \"./ansi-utils.js\"\n\ninterface ToggleOptions extends Required<Prompt.Prompt.ToggleOptions> {}\n\ntype State = boolean\n\nconst renderBeep = Doc.render(Doc.beep, { style: \"pretty\" })\n\nfunction handleClear(options: ToggleOptions) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const columns = yield* terminal.columns\n    const clearPrompt = Doc.cat(Doc.eraseLine, Doc.cursorLeft)\n    const clearOutput = InternalAnsiUtils.eraseText(options.message, columns)\n    return clearOutput.pipe(\n      Doc.cat(clearPrompt),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction renderToggle(\n  value: boolean,\n  options: ToggleOptions,\n  submitted: boolean = false\n) {\n  const separator = Doc.annotate(Doc.char(\"/\"), Ansi.blackBright)\n  const selectedAnnotation = Ansi.combine(Ansi.underlined, submitted ? Ansi.white : Ansi.cyanBright)\n  const inactive = value\n    ? Doc.text(options.inactive)\n    : Doc.annotate(Doc.text(options.inactive), selectedAnnotation)\n  const active = value\n    ? Doc.annotate(Doc.text(options.active), selectedAnnotation)\n    : Doc.text(options.active)\n  return Doc.hsep([active, separator, inactive])\n}\n\nfunction renderOutput(\n  toggle: Doc.AnsiDoc,\n  leadingSymbol: Doc.AnsiDoc,\n  trailingSymbol: Doc.AnsiDoc,\n  options: ToggleOptions\n) {\n  const annotateLine = (line: string): Doc.AnsiDoc => Doc.annotate(Doc.text(line), Ansi.bold)\n  const promptLines = options.message.split(/\\r?\\n/)\n  const prefix = Doc.cat(leadingSymbol, Doc.space)\n  if (Arr.isNonEmptyReadonlyArray(promptLines)) {\n    const lines = Arr.map(promptLines, (line) => annotateLine(line))\n    return prefix.pipe(\n      Doc.cat(Doc.nest(Doc.vsep(lines), 2)),\n      Doc.cat(Doc.space),\n      Doc.cat(trailingSymbol),\n      Doc.cat(Doc.space),\n      Doc.cat(toggle)\n    )\n  }\n  return Doc.hsep([prefix, trailingSymbol, toggle])\n}\n\nfunction renderNextFrame(state: State, options: ToggleOptions) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const figures = yield* InternalAnsiUtils.figures\n    const columns = yield* terminal.columns\n    const leadingSymbol = Doc.annotate(Doc.text(\"?\"), Ansi.cyanBright)\n    const trailingSymbol = Doc.annotate(figures.pointerSmall, Ansi.blackBright)\n    const toggle = renderToggle(state, options)\n    const promptMsg = renderOutput(toggle, leadingSymbol, trailingSymbol, options)\n    return Doc.cursorHide.pipe(\n      Doc.cat(promptMsg),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nfunction renderSubmission(value: boolean, options: ToggleOptions) {\n  return Effect.gen(function*() {\n    const terminal = yield* Terminal.Terminal\n    const figures = yield* InternalAnsiUtils.figures\n    const columns = yield* terminal.columns\n    const leadingSymbol = Doc.annotate(figures.tick, Ansi.green)\n    const trailingSymbol = Doc.annotate(figures.ellipsis, Ansi.blackBright)\n    const toggle = renderToggle(value, options, true)\n    const promptMsg = renderOutput(toggle, leadingSymbol, trailingSymbol, options)\n    return promptMsg.pipe(\n      Doc.cat(Doc.hardLine),\n      Optimize.optimize(Optimize.Deep),\n      Doc.render({ style: \"pretty\", options: { lineWidth: columns } })\n    )\n  })\n}\n\nconst activate = Effect.succeed(Action.NextFrame({ state: true }))\nconst deactivate = Effect.succeed(Action.NextFrame({ state: false }))\n\nfunction handleRender(options: ToggleOptions) {\n  return (state: State, action: Prompt.Prompt.Action<State, boolean>) => {\n    switch (action._tag) {\n      case \"Beep\": {\n        return Effect.succeed(renderBeep)\n      }\n      case \"NextFrame\": {\n        return renderNextFrame(state, options)\n      }\n      case \"Submit\": {\n        return renderSubmission(state, options)\n      }\n    }\n  }\n}\n\nfunction handleProcess(input: Terminal.UserInput, state: State) {\n  switch (input.key.name) {\n    case \"0\":\n    case \"j\":\n    case \"delete\":\n    case \"right\":\n    case \"down\": {\n      return deactivate\n    }\n    case \"1\":\n    case \"k\":\n    case \"left\":\n    case \"up\": {\n      return activate\n    }\n    case \" \":\n    case \"tab\": {\n      return state ? deactivate : activate\n    }\n    case \"enter\":\n    case \"return\": {\n      return Effect.succeed(Action.Submit({ value: state }))\n    }\n    default: {\n      return Effect.succeed(Action.Beep())\n    }\n  }\n}\n\n/** @internal */\nexport const toggle = (options: Prompt.Prompt.ToggleOptions): Prompt.Prompt<boolean> => {\n  const opts: ToggleOptions = {\n    initial: false,\n    active: \"on\",\n    inactive: \"off\",\n    ...options\n  }\n  return InternalPrompt.custom(opts.initial, {\n    render: handleRender(opts),\n    process: handleProcess,\n    clear: () => handleClear(opts)\n  })\n}\n"
  },
  {
    "path": "packages/cli/src/internal/prompt/utils.ts",
    "content": "/** @internal */\nexport const entriesToDisplay = (cursor: number, total: number, maxVisible?: number) => {\n  const max = maxVisible === undefined ? total : maxVisible\n  let startIndex = Math.min(total - max, cursor - Math.floor(max / 2))\n  if (startIndex < 0) {\n    startIndex = 0\n  }\n  const endIndex = Math.min(startIndex + max, total)\n  return { startIndex, endIndex }\n}\n"
  },
  {
    "path": "packages/cli/src/internal/prompt.ts",
    "content": "import * as Terminal from \"@effect/platform/Terminal\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport type * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport * as Effectable from \"effect/Effectable\"\nimport { dual } from \"effect/Function\"\nimport type * as Mailbox from \"effect/Mailbox\"\nimport * as Pipeable from \"effect/Pipeable\"\nimport type * as Prompt from \"../Prompt.js\"\nimport { Action } from \"./prompt/action.js\"\n\n/** @internal */\nconst PromptSymbolKey = \"@effect/cli/Prompt\"\n\n/** @internal */\nexport const PromptTypeId: Prompt.PromptTypeId = Symbol.for(\n  PromptSymbolKey\n) as Prompt.PromptTypeId\n\n/** @internal */\nconst proto = {\n  ...Effectable.CommitPrototype,\n  [PromptTypeId]: {\n    _Output: (_: never) => _\n  },\n  commit(): Effect.Effect<Terminal.Terminal, Terminal.QuitException, unknown> {\n    return run(this as any)\n  },\n  pipe() {\n    return Pipeable.pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\ntype Op<Tag extends string, Body = {}> = Prompt.Prompt<never> & Body & {\n  readonly _tag: Tag\n}\n\n/** @internal */\nexport type Primitive = Loop | OnSuccess | Succeed\n\n/** @internal */\nexport interface Loop extends\n  Op<\"Loop\", {\n    readonly initialState: unknown | Effect.Effect<unknown, never, Prompt.Prompt.Environment>\n    readonly render: Prompt.Prompt.Handlers<unknown, unknown>[\"render\"]\n    readonly process: Prompt.Prompt.Handlers<unknown, unknown>[\"process\"]\n    readonly clear: Prompt.Prompt.Handlers<unknown, unknown>[\"clear\"]\n  }>\n{}\n\n/** @internal */\nexport interface OnSuccess extends\n  Op<\"OnSuccess\", {\n    readonly prompt: Primitive\n    readonly onSuccess: (value: unknown) => Prompt.Prompt<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Succeed extends\n  Op<\"Succeed\", {\n    readonly value: unknown\n  }>\n{}\n\n/** @internal */\nexport const isPrompt = (u: unknown): u is Prompt.Prompt<unknown> =>\n  typeof u === \"object\" && u != null && PromptTypeId in u\n\nconst allTupled = <const T extends ArrayLike<Prompt.Prompt<any>>>(arg: T): Prompt.Prompt<\n  {\n    [K in keyof T]: [T[K]] extends [Prompt.Prompt<infer A>] ? A : never\n  }\n> => {\n  if (arg.length === 0) {\n    return succeed([]) as any\n  }\n  if (arg.length === 1) {\n    return map(arg[0], (x) => [x]) as any\n  }\n  let result = map(arg[0], (x) => [x])\n  for (let i = 1; i < arg.length; i++) {\n    const curr = arg[i]\n    result = flatMap(result, (tuple) => map(curr, (a) => [...tuple, a]))\n  }\n  return result as any\n}\n\n/** @internal */\nexport const all: <\n  const Arg extends Iterable<Prompt.Prompt<any>> | Record<string, Prompt.Prompt<any>>\n>(arg: Arg) => Prompt.All.Return<Arg> = function() {\n  if (arguments.length === 1) {\n    if (isPrompt(arguments[0])) {\n      return map(arguments[0], (x) => [x]) as any\n    } else if (Array.isArray(arguments[0])) {\n      return allTupled(arguments[0]) as any\n    } else {\n      const entries = Object.entries(arguments[0] as Readonly<{ [K: string]: Prompt.Prompt<any> }>)\n      let result = map(entries[0][1], (value) => ({ [entries[0][0]]: value }))\n      if (entries.length === 1) {\n        return result as any\n      }\n      const rest = entries.slice(1)\n      for (const [key, prompt] of rest) {\n        result = result.pipe(\n          flatMap((record) =>\n            prompt.pipe(map((value) => ({\n              ...record,\n              [key]: value\n            })))\n          )\n        )\n      }\n      return result as any\n    }\n  }\n  return allTupled(arguments[0]) as any\n}\n\n/** @internal */\nexport const custom = <State, Output>(\n  initialState: State | Effect.Effect<State, never, Prompt.Prompt.Environment>,\n  handlers: Prompt.Prompt.Handlers<State, Output>\n): Prompt.Prompt<Output> => {\n  const op = Object.create(proto)\n  op._tag = \"Loop\"\n  op.initialState = initialState\n  op.render = handlers.render\n  op.process = handlers.process\n  op.clear = handlers.clear\n  return op\n}\n\n/** @internal */\nexport const map = dual<\n  <Output, Output2>(\n    f: (output: Output) => Output2\n  ) => (\n    self: Prompt.Prompt<Output>\n  ) => Prompt.Prompt<Output2>,\n  <Output, Output2>(\n    self: Prompt.Prompt<Output>,\n    f: (output: Output) => Output2\n  ) => Prompt.Prompt<Output2>\n>(2, (self, f) => flatMap(self, (a) => succeed(f(a))))\n\n/** @internal */\nexport const flatMap = dual<\n  <Output, Output2>(\n    f: (output: Output) => Prompt.Prompt<Output2>\n  ) => (\n    self: Prompt.Prompt<Output>\n  ) => Prompt.Prompt<Output2>,\n  <Output, Output2>(\n    self: Prompt.Prompt<Output>,\n    f: (output: Output) => Prompt.Prompt<Output2>\n  ) => Prompt.Prompt<Output2>\n>(2, (self, f) => {\n  const op = Object.create(proto)\n  op._tag = \"OnSuccess\"\n  op.prompt = self\n  op.onSuccess = f\n  return op\n})\n\n/** @internal */\nexport const run: <Output>(\n  self: Prompt.Prompt<Output>\n) => Effect.Effect<\n  Output,\n  Terminal.QuitException,\n  Prompt.Prompt.Environment\n> = Effect.fnUntraced(\n  function*<Output>(self: Prompt.Prompt<Output>) {\n    const terminal = yield* Terminal.Terminal\n    const input = yield* terminal.readInput\n    return yield* runWithInput(self, terminal, input)\n  },\n  Effect.mapError(() => new Terminal.QuitException()),\n  Effect.scoped\n)\n\nconst runWithInput = <Output>(\n  prompt: Prompt.Prompt<Output>,\n  terminal: Terminal.Terminal,\n  input: Mailbox.ReadonlyMailbox<Terminal.UserInput>\n): Effect.Effect<Output, Cause.NoSuchElementException, Prompt.Prompt.Environment> =>\n  Effect.suspend(() => {\n    const op = prompt as Primitive\n    switch (op._tag) {\n      case \"Loop\": {\n        return runLoop(op, terminal, input)\n      }\n      case \"OnSuccess\": {\n        return Effect.flatMap(\n          runWithInput(op.prompt, terminal, input),\n          (a) => runWithInput(op.onSuccess(a), terminal, input)\n        ) as any\n      }\n      case \"Succeed\": {\n        return Effect.succeed(op.value)\n      }\n    }\n  })\n\nconst runLoop = Effect.fnUntraced(\n  function*(\n    loop: Loop,\n    terminal: Terminal.Terminal,\n    input: Mailbox.ReadonlyMailbox<Terminal.UserInput>\n  ) {\n    let state = Effect.isEffect(loop.initialState) ? yield* loop.initialState : loop.initialState\n    let action: Prompt.Prompt.Action<unknown, unknown> = Action.NextFrame({ state })\n    while (true) {\n      const msg = yield* loop.render(state, action)\n      yield* Effect.orDie(terminal.display(msg))\n      const event = yield* input.take\n      action = yield* loop.process(event, state)\n      switch (action._tag) {\n        case \"Beep\":\n          continue\n        case \"NextFrame\": {\n          yield* Effect.orDie(terminal.display(yield* loop.clear(state, action)))\n          state = action.state\n          continue\n        }\n        case \"Submit\": {\n          yield* Effect.orDie(terminal.display(yield* loop.clear(state, action)))\n          const msg = yield* loop.render(state, action)\n          yield* Effect.orDie(terminal.display(msg))\n          return action.value\n        }\n      }\n    }\n  },\n  (effect, _, terminal) =>\n    Effect.ensuring(\n      effect,\n      Effect.orDie(\n        terminal.display(Doc.render(Doc.cursorShow, { style: \"pretty\" }))\n      )\n    )\n)\n\n/** @internal */\nexport const succeed = <A>(value: A): Prompt.Prompt<A> => {\n  const op = Object.create(proto)\n  op._tag = \"Succeed\"\n  op.value = value\n  return op\n}\n"
  },
  {
    "path": "packages/cli/src/internal/usage.ts",
    "content": "import * as Arr from \"effect/Array\"\nimport { dual, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport type * as CliConfig from \"../CliConfig.js\"\nimport type * as HelpDoc from \"../HelpDoc.js\"\nimport type * as Span from \"../HelpDoc/Span.js\"\nimport type * as Usage from \"../Usage.js\"\nimport * as InternalCliConfig from \"./cliConfig.js\"\nimport * as InternalHelpDoc from \"./helpDoc.js\"\nimport * as InternalSpan from \"./helpDoc/span.js\"\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\n/** @internal */\nexport const empty: Usage.Usage = {\n  _tag: \"Empty\"\n}\n\n/** @internal */\nexport const mixed: Usage.Usage = {\n  _tag: \"Empty\"\n}\n\n/** @internal */\nexport const named = (\n  names: ReadonlyArray<string>,\n  acceptedValues: Option.Option<string>\n): Usage.Usage => ({\n  _tag: \"Named\",\n  names,\n  acceptedValues\n})\n\n/** @internal */\nexport const optional = (self: Usage.Usage): Usage.Usage => ({\n  _tag: \"Optional\",\n  usage: self\n})\n\n/** @internal */\nexport const repeated = (self: Usage.Usage): Usage.Usage => ({\n  _tag: \"Repeated\",\n  usage: self\n})\n\nexport const alternation = dual<\n  (that: Usage.Usage) => (self: Usage.Usage) => Usage.Usage,\n  (self: Usage.Usage, that: Usage.Usage) => Usage.Usage\n>(2, (self, that) => ({\n  _tag: \"Alternation\",\n  left: self,\n  right: that\n}))\n\n/** @internal */\nexport const concat = dual<\n  (that: Usage.Usage) => (self: Usage.Usage) => Usage.Usage,\n  (self: Usage.Usage, that: Usage.Usage) => Usage.Usage\n>(2, (self, that) => ({\n  _tag: \"Concat\",\n  left: self,\n  right: that\n}))\n\n// =============================================================================\n// Combinators\n// =============================================================================\n\n/** @internal */\nexport const getHelp = (self: Usage.Usage): HelpDoc.HelpDoc => {\n  const spans = enumerate(self, InternalCliConfig.defaultConfig)\n  if (Arr.isNonEmptyReadonlyArray(spans)) {\n    const head = Arr.headNonEmpty(spans)\n    const tail = Arr.tailNonEmpty(spans)\n    if (Arr.isNonEmptyReadonlyArray(tail)) {\n      return pipe(\n        Arr.map(spans, (span) => InternalHelpDoc.p(span)),\n        Arr.reduceRight(\n          InternalHelpDoc.empty,\n          (left, right) => InternalHelpDoc.sequence(left, right)\n        )\n      )\n    }\n    return InternalHelpDoc.p(head)\n  }\n  return InternalHelpDoc.empty\n}\n\n/** @internal */\nexport const enumerate = dual<\n  (config: CliConfig.CliConfig) => (self: Usage.Usage) => Array<Span.Span>,\n  (self: Usage.Usage, config: CliConfig.CliConfig) => Array<Span.Span>\n>(2, (self, config) => render(simplify(self, config), config))\n\n// =============================================================================\n// Internals\n// =============================================================================\n\nconst simplify = (self: Usage.Usage, config: CliConfig.CliConfig): Usage.Usage => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return empty\n    }\n    case \"Mixed\": {\n      return mixed\n    }\n    case \"Named\": {\n      if (Option.isNone(Arr.head(render(self, config)))) {\n        return empty\n      }\n      return self\n    }\n    case \"Optional\": {\n      if (self.usage._tag === \"Empty\") {\n        return empty\n      }\n      const usage = simplify(self.usage, config)\n      // No need to do anything for empty usage\n      return usage._tag === \"Empty\"\n        ? empty\n        // Avoid re-wrapping the usage in an optional instruction\n        : usage._tag === \"Optional\"\n        ? usage\n        : optional(usage)\n    }\n    case \"Repeated\": {\n      const usage = simplify(self.usage, config)\n      return usage._tag === \"Empty\" ? empty : repeated(usage)\n    }\n    case \"Alternation\": {\n      const leftUsage = simplify(self.left, config)\n      const rightUsage = simplify(self.right, config)\n      return leftUsage._tag === \"Empty\"\n        ? rightUsage\n        : rightUsage._tag === \"Empty\"\n        ? leftUsage\n        : alternation(leftUsage, rightUsage)\n    }\n    case \"Concat\": {\n      const leftUsage = simplify(self.left, config)\n      const rightUsage = simplify(self.right, config)\n      return leftUsage._tag === \"Empty\"\n        ? rightUsage\n        : rightUsage._tag === \"Empty\"\n        ? leftUsage\n        : concat(leftUsage, rightUsage)\n    }\n  }\n}\n\nconst render = (self: Usage.Usage, config: CliConfig.CliConfig): Array<Span.Span> => {\n  switch (self._tag) {\n    case \"Empty\": {\n      return Arr.of(InternalSpan.text(\"\"))\n    }\n    case \"Mixed\": {\n      return Arr.of(InternalSpan.text(\"<command>\"))\n    }\n    case \"Named\": {\n      const typeInfo = config.showTypes\n        ? Option.match(self.acceptedValues, {\n          onNone: () => InternalSpan.empty,\n          onSome: (s) => InternalSpan.concat(InternalSpan.space, InternalSpan.text(s))\n        })\n        : InternalSpan.empty\n      const namesToShow = config.showAllNames\n        ? self.names\n        : self.names.length > 1\n        ? pipe(\n          Arr.filter(self.names, (name) => name.startsWith(\"--\")),\n          Arr.head,\n          Option.map(Arr.of),\n          Option.getOrElse(() => self.names)\n        )\n        : self.names\n      const nameInfo = InternalSpan.text(Arr.join(namesToShow, \", \"))\n      return config.showAllNames && self.names.length > 1\n        ? Arr.of(InternalSpan.spans([\n          InternalSpan.text(\"(\"),\n          nameInfo,\n          typeInfo,\n          InternalSpan.text(\")\")\n        ]))\n        : Arr.of(InternalSpan.concat(nameInfo, typeInfo))\n    }\n    case \"Optional\": {\n      return Arr.map(render(self.usage, config), (span) =>\n        InternalSpan.spans([\n          InternalSpan.text(\"[\"),\n          span,\n          InternalSpan.text(\"]\")\n        ]))\n    }\n    case \"Repeated\": {\n      return Arr.map(\n        render(self.usage, config),\n        (span) => InternalSpan.concat(span, InternalSpan.text(\"...\"))\n      )\n    }\n    case \"Alternation\": {\n      if (\n        self.left._tag === \"Repeated\" ||\n        self.right._tag === \"Repeated\" ||\n        self.left._tag === \"Concat\" ||\n        self.right._tag === \"Concat\"\n      ) {\n        return Arr.appendAll(\n          render(self.left, config),\n          render(self.right, config)\n        )\n      }\n      return Arr.flatMap(\n        render(self.left, config),\n        (left) =>\n          Arr.map(\n            render(self.right, config),\n            (right) => InternalSpan.spans([left, InternalSpan.text(\"|\"), right])\n          )\n      )\n    }\n    case \"Concat\": {\n      const leftSpan = render(self.left, config)\n      const rightSpan = render(self.right, config)\n      const separator = Arr.isNonEmptyReadonlyArray(leftSpan) &&\n          Arr.isNonEmptyReadonlyArray(rightSpan)\n        ? InternalSpan.space\n        : InternalSpan.empty\n      return Arr.flatMap(\n        leftSpan,\n        (left) => Arr.map(rightSpan, (right) => InternalSpan.spans([left, separator, right]))\n      )\n    }\n  }\n}\n"
  },
  {
    "path": "packages/cli/src/internal/validationError.ts",
    "content": "import type * as HelpDoc from \"../HelpDoc.js\"\nimport type * as ValidationError from \"../ValidationError.js\"\n\nconst ValidationErrorSymbolKey = \"@effect/cli/ValidationError\"\n\n/** @internal */\nexport const ValidationErrorTypeId: ValidationError.ValidationErrorTypeId = Symbol.for(\n  ValidationErrorSymbolKey\n) as ValidationError.ValidationErrorTypeId\n\n/** @internal */\nexport const proto: ValidationError.ValidationError.Proto = {\n  [ValidationErrorTypeId]: ValidationErrorTypeId\n}\n\n/** @internal */\nexport const isValidationError = (u: unknown): u is ValidationError.ValidationError =>\n  typeof u === \"object\" && u != null && ValidationErrorTypeId in u\n\n/** @internal */\nexport const isCommandMismatch = (\n  self: ValidationError.ValidationError\n): self is ValidationError.CommandMismatch => self._tag === \"CommandMismatch\"\n\n/** @internal */\nexport const isCorrectedFlag = (\n  self: ValidationError.ValidationError\n): self is ValidationError.CorrectedFlag => self._tag === \"CorrectedFlag\"\n\n/** @internal */\nexport const isHelpRequested = (\n  self: ValidationError.ValidationError\n): self is ValidationError.HelpRequested => self._tag === \"HelpRequested\"\n\n/** @internal */\nexport const isInvalidArgument = (\n  self: ValidationError.ValidationError\n): self is ValidationError.InvalidArgument => self._tag === \"InvalidArgument\"\n\n/** @internal */\nexport const isInvalidValue = (\n  self: ValidationError.ValidationError\n): self is ValidationError.InvalidValue => self._tag === \"InvalidValue\"\n\n/** @internal */\nexport const isMultipleValuesDetected = (\n  self: ValidationError.ValidationError\n): self is ValidationError.MultipleValuesDetected => self._tag === \"MultipleValuesDetected\"\n\n/** @internal */\nexport const isMissingFlag = (\n  self: ValidationError.ValidationError\n): self is ValidationError.MissingFlag => self._tag === \"MissingFlag\"\n\n/** @internal */\nexport const isMissingValue = (\n  self: ValidationError.ValidationError\n): self is ValidationError.MissingValue => self._tag === \"MissingValue\"\n\n/** @internal */\nexport const isMissingSubcommand = (\n  self: ValidationError.ValidationError\n): self is ValidationError.MissingSubcommand => self._tag === \"MissingSubcommand\"\n\n/** @internal */\nexport const isNoBuiltInMatch = (\n  self: ValidationError.ValidationError\n): self is ValidationError.NoBuiltInMatch => self._tag === \"NoBuiltInMatch\"\n\n/** @internal */\nexport const isUnclusteredFlag = (\n  self: ValidationError.ValidationError\n): self is ValidationError.UnclusteredFlag => self._tag === \"UnclusteredFlag\"\n\n/** @internal */\nexport const commandMismatch = (error: HelpDoc.HelpDoc): ValidationError.ValidationError => {\n  const op = Object.create(proto)\n  op._tag = \"CommandMismatch\"\n  op.error = error\n  return op\n}\n\n/** @internal */\nexport const correctedFlag = (error: HelpDoc.HelpDoc): ValidationError.ValidationError => {\n  const op = Object.create(proto)\n  op._tag = \"CorrectedFlag\"\n  op.error = error\n  return op\n}\n\n/** @internal */\nexport const invalidArgument = (error: HelpDoc.HelpDoc): ValidationError.ValidationError => {\n  const op = Object.create(proto)\n  op._tag = \"InvalidArgument\"\n  op.error = error\n  return op\n}\n\n/** @internal */\nexport const invalidValue = (error: HelpDoc.HelpDoc): ValidationError.ValidationError => {\n  const op = Object.create(proto)\n  op._tag = \"InvalidValue\"\n  op.error = error\n  return op\n}\n\n/** @internal */\nexport const missingFlag = (error: HelpDoc.HelpDoc): ValidationError.ValidationError => {\n  const op = Object.create(proto)\n  op._tag = \"MissingFlag\"\n  op.error = error\n  return op\n}\n\n/** @internal */\nexport const missingValue = (error: HelpDoc.HelpDoc): ValidationError.ValidationError => {\n  const op = Object.create(proto)\n  op._tag = \"MissingValue\"\n  op.error = error\n  return op\n}\n\n/** @internal */\nexport const missingSubcommand = (error: HelpDoc.HelpDoc): ValidationError.ValidationError => {\n  const op = Object.create(proto)\n  op._tag = \"MissingSubcommand\"\n  op.error = error\n  return op\n}\n\n/** @internal */\nexport const multipleValuesDetected = (\n  error: HelpDoc.HelpDoc,\n  values: ReadonlyArray<unknown>\n): ValidationError.ValidationError => {\n  const op = Object.create(proto)\n  op._tag = \"MultipleValuesDetected\"\n  op.error = error\n  op.values = values\n  return op\n}\n\n/** @internal */\nexport const noBuiltInMatch = (error: HelpDoc.HelpDoc): ValidationError.ValidationError => {\n  const op = Object.create(proto)\n  op._tag = \"NoBuiltInMatch\"\n  op.error = error\n  return op\n}\n\n/** @internal */\nexport const unclusteredFlag = (\n  error: HelpDoc.HelpDoc,\n  unclustered: ReadonlyArray<string>,\n  rest: ReadonlyArray<string>\n): ValidationError.ValidationError => {\n  const op = Object.create(proto)\n  op._tag = \"UnclusteredFlag\"\n  op.error = error\n  op.unclustered = unclustered\n  op.rest = rest\n  return op\n}\n"
  },
  {
    "path": "packages/cli/test/Args.test.ts",
    "content": "import * as Args from \"@effect/cli/Args\"\nimport * as CliConfig from \"@effect/cli/CliConfig\"\nimport * as HelpDoc from \"@effect/cli/HelpDoc\"\nimport * as ValidationError from \"@effect/cli/ValidationError\"\nimport { FileSystem, Path } from \"@effect/platform\"\nimport { NodeContext } from \"@effect/platform-node\"\nimport { describe, expect, it } from \"@effect/vitest\"\nimport { pipe } from \"effect\"\nimport * as Array from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\n\nconst runEffect = <E, A>(\n  self: Effect.Effect<A, E, NodeContext.NodeContext>\n): Promise<A> => Effect.provide(self, NodeContext.layer).pipe(Effect.runPromise)\n\ndescribe(\"Args\", () => {\n  it(\"validates an valid argument with a default\", () =>\n    Effect.gen(function*() {\n      const args = Args.integer().pipe(Args.withDefault(0))\n      const result = yield* Args.validate(args, Array.empty(), CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), 0])\n    }).pipe(runEffect))\n\n  it(\"validates an valid optional argument\", () =>\n    Effect.gen(function*() {\n      const args = Args.integer().pipe(Args.optional)\n      let result = yield* Args.validate(args, Array.empty(), CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), Option.none()])\n\n      result = yield* Args.validate(args, [\"123\"], CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), Option.some(123)])\n    }).pipe(runEffect))\n\n  it(\"does not validate an invalid argument even when there is a default\", () =>\n    Effect.gen(function*() {\n      const args = Args.integer().pipe(Args.withDefault(0))\n      const result = yield* Effect.flip(\n        Args.validate(args, Array.of(\"abc\"), CliConfig.defaultConfig)\n      )\n      expect(result).toEqual(ValidationError.invalidArgument(HelpDoc.p(\"'abc' is not a integer\")))\n    }).pipe(runEffect))\n\n  it(\"should validate an existing file that is expected to exist\", () =>\n    Effect.gen(function*() {\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"Args.test.ts\")\n      const args = Args.file({ name: \"files\", exists: \"yes\" }).pipe(Args.repeated)\n      const result = yield* Args.validate(args, Array.of(filePath), CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), Array.of(filePath)])\n    }).pipe(runEffect))\n\n  it(\"should return an error when a file that is expected to exist is not found\", () =>\n    Effect.gen(function*() {\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"NotExist.test.ts\")\n      const args = Args.file({ name: \"files\", exists: \"yes\" }).pipe(Args.repeated)\n      const result = yield* Effect.flip(Args.validate(args, Array.of(filePath), CliConfig.defaultConfig))\n      expect(result).toEqual(ValidationError.invalidArgument(HelpDoc.p(\n        `Path '${filePath}' must exist`\n      )))\n    }).pipe(runEffect))\n\n  it(\"should validate a non-existent file that is expected not to exist\", () =>\n    Effect.gen(function*() {\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"NotExist.test.ts\")\n      const args = Args.file({ name: \"files\", exists: \"no\" }).pipe(Args.repeated)\n      const result = yield* Args.validate(args, Array.of(filePath), CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), Array.of(filePath)])\n    }).pipe(runEffect))\n\n  it(\"should validate a series of files\", () =>\n    Effect.gen(function*() {\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"NotExist.test.ts\")\n      const args = Args.file({ name: \"files\", exists: \"no\" }).pipe(Args.repeated)\n      const result = yield* Args.validate(args, Array.make(filePath, filePath), CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), Array.make(filePath, filePath)])\n    }).pipe(runEffect))\n\n  it(\"validates an valid argument with a Schema\", () =>\n    Effect.gen(function*() {\n      const args = Args.integer().pipe(Args.withSchema(Schema.Positive))\n      const result = yield* Args.validate(args, [\"123\"], CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), 123])\n    }).pipe(runEffect))\n\n  it(\"does not validate an invalid argument with a Schema\", () =>\n    Effect.gen(function*() {\n      const args = Args.integer().pipe(Args.withSchema(Schema.Positive))\n      const result = yield* Effect.flip(\n        Args.validate(args, Array.of(\"-123\"), CliConfig.defaultConfig)\n      )\n      expect(result).toEqual(ValidationError.invalidArgument(HelpDoc.p(\n        \"Positive\\n\" +\n          \"└─ Predicate refinement failure\\n\" +\n          \"   └─ Expected a positive number, actual -123\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"fileContent\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.json\")\n      const content = yield* fs.readFile(filePath)\n      const args = Args.fileContent({ name: \"files\" }).pipe(Args.repeated)\n      const result = yield* Args.validate(args, Array.of(filePath), CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), Array.of([filePath, content])])\n    }).pipe(runEffect))\n\n  it(\"fileText\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.json\")\n      const content = yield* fs.readFileString(filePath)\n      const args = Args.fileText({ name: \"files\" }).pipe(Args.repeated)\n      const result = yield* Args.validate(args, Array.of(filePath), CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), Array.of([filePath, content])])\n    }).pipe(runEffect))\n\n  it(\"fileParse\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.json\")\n      const content = yield* pipe(fs.readFileString(filePath), Effect.map(JSON.parse))\n      const args = Args.fileParse({ name: \"files\" }).pipe(Args.repeated)\n      const result = yield* Args.validate(args, Array.of(filePath), CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), Array.of(content)])\n    }).pipe(runEffect))\n\n  it(\"fileSchema\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.json\")\n      const content = yield* pipe(fs.readFileString(filePath), Effect.map(JSON.parse))\n      const args = Args.fileSchema(\n        Schema.Struct({\n          foo: Schema.Boolean,\n          bar: Schema.Literal(\"baz\")\n        }),\n        { name: \"files\" }\n      ).pipe(Args.repeated)\n      const result = yield* Args.validate(args, Array.of(filePath), CliConfig.defaultConfig)\n      expect(result).toEqual([Array.empty(), Array.of(content)])\n    }).pipe(runEffect))\n\n  it(\"displays default value in help when default wrapped in Option.Some (primitive)\", () =>\n    Effect.gen(function*() {\n      const option = Args.withDefault(Args.integer({ name: \"value\" }), Option.some(123))\n      const helpDoc = Args.getHelp(option)\n      yield* Effect.promise(() => expect(helpDoc).toMatchFileSnapshot(\"./snapshots/help-output/args-default-primitive\"))\n    }).pipe(runEffect))\n\n  it(\"displays default value in help when default wrapped in Option.Some (object)\", () =>\n    Effect.gen(function*() {\n      const defaultObject = { key: \"value\", number: 456 }\n      const option = Args.withDefault(Args.text({ name: \"config\" }), Option.some(defaultObject))\n      const helpDoc = Args.getHelp(option)\n      yield* Effect.promise(() => expect(helpDoc).toMatchFileSnapshot(\"./snapshots/help-output/args-default-object\"))\n    }).pipe(runEffect))\n\n  it(\"displays no default value in help when default is not Option.Some\", () =>\n    Effect.gen(function*() {\n      const option = Args.withDefault(Args.text({ name: \"name\" }), Option.none())\n      const helpDoc = Args.getHelp(option)\n      yield* Effect.promise(() => expect(helpDoc).toMatchFileSnapshot(\"./snapshots/help-output/args-no-default\"))\n    }).pipe(runEffect))\n})\n"
  },
  {
    "path": "packages/cli/test/AutoCorrect.test.ts",
    "content": "import * as AutoCorrect from \"@effect/cli/AutoCorrect\"\nimport * as CliConfig from \"@effect/cli/CliConfig\"\nimport { describe, expect, it } from \"@effect/vitest\"\n\ndescribe(\"AutoCorrect\", () => {\n  it(\"should calculate the correct Levenstein distance between two strings\", () => {\n    expect(AutoCorrect.levensteinDistance(\"\", \"\", CliConfig.defaultConfig)).toBe(0)\n    expect(AutoCorrect.levensteinDistance(\"--force\", \"\", CliConfig.defaultConfig)).toBe(7)\n    expect(AutoCorrect.levensteinDistance(\"\", \"--force\", CliConfig.defaultConfig)).toBe(7)\n    expect(AutoCorrect.levensteinDistance(\"--force\", \"force\", CliConfig.defaultConfig)).toBe(2)\n    expect(AutoCorrect.levensteinDistance(\"--force\", \"--forc\", CliConfig.defaultConfig)).toBe(1)\n    expect(AutoCorrect.levensteinDistance(\"foo\", \"bar\", CliConfig.defaultConfig)).toBe(3)\n    // By default, the configuration is case-insensitive so options are normalized\n    expect(AutoCorrect.levensteinDistance(\"--force\", \"--Force\", CliConfig.defaultConfig)).toBe(0)\n  })\n\n  it(\"should take into account the provided case-sensitivity\", () => {\n    const config = CliConfig.make({ isCaseSensitive: true })\n    expect(AutoCorrect.levensteinDistance(\"--force\", \"--force\", config)).toBe(0)\n    expect(AutoCorrect.levensteinDistance(\"--FORCE\", \"--force\", config)).toBe(5)\n  })\n\n  it(\"should calculate the correct Levenstein distance for non-ASCII characters\", () => {\n    expect(AutoCorrect.levensteinDistance(\"とんかつ\", \"とかつ\", CliConfig.defaultConfig)).toBe(1)\n    expect(AutoCorrect.levensteinDistance(\"¯\\\\_(ツ)_/¯\", \"_(ツ)_/¯\", CliConfig.defaultConfig)).toBe(\n      2\n    )\n  })\n})\n"
  },
  {
    "path": "packages/cli/test/CliApp.test.ts",
    "content": "import * as Args from \"@effect/cli/Args\"\nimport type * as CliApp from \"@effect/cli/CliApp\"\nimport * as CliConfig from \"@effect/cli/CliConfig\"\nimport * as Command from \"@effect/cli/Command\"\nimport * as HelpDoc from \"@effect/cli/HelpDoc\"\nimport * as ValidationError from \"@effect/cli/ValidationError\"\nimport { NodeContext } from \"@effect/platform-node\"\nimport { describe, expect, it } from \"@effect/vitest\"\nimport { Array, Console, Effect, FiberRef, Layer, LogLevel } from \"effect\"\nimport * as MockConsole from \"./services/MockConsole.js\"\n\nconst MainLive = Effect.gen(function*() {\n  const console = yield* MockConsole.make\n  return Layer.mergeAll(\n    Console.setConsole(console),\n    NodeContext.layer\n  )\n}).pipe(Layer.unwrapEffect)\n\nconst runEffect = <E, A>(\n  self: Effect.Effect<A, E, CliApp.CliApp.Environment>\n): Promise<A> =>\n  Effect.provide(self, MainLive).pipe(\n    Effect.runPromise\n  )\n\ndescribe(\"CliApp\", () => {\n  it(\"should return an error if excess arguments are provided\", () =>\n    Effect.gen(function*() {\n      const cli = Command.run(Command.make(\"foo\"), {\n        name: \"Test\",\n        version: \"1.0.0\"\n      })\n      const args = Array.make(\"node\", \"test.js\", \"--bar\")\n      const result = yield* Effect.flip(cli(args))\n      expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"Received unknown argument: '--bar'\"\n      )))\n    }).pipe(runEffect))\n\n  describe(\"Built-In Options Processing\", () => {\n    it(\"should display built-in options in help if `CliConfig.showBuiltIns` is true\", () => {\n      const CliConfigLive = CliConfig.layer({\n        showBuiltIns: true // this is the default\n      })\n      return Effect.gen(function*() {\n        const cli = Command.run(Command.make(\"foo\"), {\n          name: \"Test\",\n          version: \"1.0.0\"\n        })\n        yield* cli([])\n        const lines = yield* MockConsole.getLines()\n        const output = lines.join(\"\\n\")\n        expect(output).toContain(\"--completions sh | bash | fish | zsh\")\n        expect(output).toContain(\"(-h, --help)\")\n        expect(output).toContain(\"--wizard\")\n        expect(output).toContain(\"--version\")\n      }).pipe(\n        Effect.provide(Layer.mergeAll(MainLive, CliConfigLive)),\n        Effect.runPromise\n      )\n    })\n\n    it(\"should not display built-in options in help if `CliConfig.showBuiltIns` is false\", () => {\n      const CliConfigLive = CliConfig.layer({\n        showBuiltIns: false\n      })\n      return Effect.gen(function*() {\n        const cli = Command.run(Command.make(\"foo\"), {\n          name: \"Test\",\n          version: \"1.0.0\"\n        })\n        yield* cli([])\n        const lines = yield* MockConsole.getLines()\n        const output = lines.join(\"\\n\")\n        expect(output).not.toContain(\"--completions sh | bash | fish | zsh\")\n        expect(output).not.toContain(\"(-h, --help)\")\n        expect(output).not.toContain(\"--wizard\")\n        expect(output).not.toContain(\"--version\")\n      }).pipe(\n        Effect.provide(Layer.mergeAll(MainLive, CliConfigLive)),\n        Effect.runPromise\n      )\n    })\n\n    it(\"should set the minimum log level for a command\", () =>\n      Effect.gen(function*() {\n        let logLevel: LogLevel.LogLevel | undefined = undefined\n        const logging = Command.make(\"logging\").pipe(Command.withHandler(() =>\n          Effect.gen(function*() {\n            logLevel = yield* FiberRef.get(FiberRef.currentMinimumLogLevel)\n          })\n        ))\n        const cli = Command.run(logging, {\n          name: \"Test\",\n          version: \"1.0.0\"\n        })\n        yield* cli([\"node\", \"logging.js\", \"--log-level\", \"debug\"])\n        expect(logLevel).toEqual(LogLevel.Debug)\n      }).pipe(runEffect))\n\n    it(\"should set the minimum log level when using equals syntax (--log-level=...)\", () =>\n      Effect.gen(function*() {\n        let logLevel: LogLevel.LogLevel | undefined = undefined\n        const logging = Command.make(\"logging\").pipe(Command.withHandler(() =>\n          Effect.gen(function*() {\n            logLevel = yield* FiberRef.get(FiberRef.currentMinimumLogLevel)\n          })\n        ))\n        const cli = Command.run(logging, {\n          name: \"Test\",\n          version: \"1.0.0\"\n        })\n        yield* cli([\"node\", \"logging.js\", \"--log-level=debug\"])\n        expect(logLevel).toEqual(LogLevel.Debug)\n      }).pipe(runEffect))\n\n    it(\"should handle paths with spaces when using --log-level\", () =>\n      Effect.gen(function*() {\n        let executedValue: string | undefined = undefined\n        const cmd = Command.make(\"test\", { value: Args.text() }, ({ value }) =>\n          Effect.sync(() => {\n            executedValue = value\n          }))\n        const cli = Command.run(cmd, {\n          name: \"Test\",\n          version: \"1.0.0\"\n        })\n        // Simulate Windows path with spaces (e.g., \"C:\\Program Files\\nodejs\\node.exe\")\n        yield* cli([\"C:\\\\Program Files\\\\node.exe\", \"C:\\\\My Scripts\\\\test.js\", \"--log-level\", \"info\", \"hello\"])\n        expect(executedValue).toEqual(\"hello\")\n      }).pipe(runEffect))\n  })\n})\n"
  },
  {
    "path": "packages/cli/test/Command.test.ts",
    "content": "import { Args, Command, Options } from \"@effect/cli\"\nimport { NodeContext } from \"@effect/platform-node\"\nimport { assert, describe, it } from \"@effect/vitest\"\nimport { Config, ConfigProvider, Context, Effect, Layer } from \"effect\"\n\nconst git = Command.make(\"git\", {\n  verbose: Options.boolean(\"verbose\").pipe(\n    Options.withAlias(\"v\"),\n    Options.withFallbackConfig(Config.boolean(\"VERBOSE\"))\n  )\n}).pipe(\n  Command.withDescription(\"the stupid content tracker\"),\n  Command.provideEffectDiscard(() =>\n    Effect.flatMap(\n      Messages,\n      (_) => _.log(\"shared\")\n    )\n  )\n)\n\nconst clone = Command.make(\"clone\", {\n  repository: Args.text({ name: \"repository\" }).pipe(\n    Args.withFallbackConfig(Config.string(\"REPOSITORY\"))\n  )\n}, ({ repository }) =>\n  Effect.gen(function*() {\n    const { log } = yield* Messages\n    const { verbose } = yield* git\n    if (verbose) {\n      yield* log(`Cloning ${repository}`)\n    } else {\n      yield* log(\"Cloning\")\n    }\n  })).pipe(Command.withDescription(\"Clone a repository into a new directory\"))\n\nconst AddService = Context.GenericTag<\"AddService\">(\"AddService\")\n\nconst add = Command.make(\"add\", {\n  pathspec: Args.text({ name: \"pathspec\" })\n}).pipe(\n  Command.withHandler(({ pathspec }) =>\n    Effect.gen(function*() {\n      yield* AddService\n      const { log } = yield* Messages\n      const { verbose } = yield* git\n      if (verbose) {\n        yield* log(`Adding ${pathspec}`)\n      } else {\n        yield* log(`Adding`)\n      }\n    })\n  ),\n  Command.withDescription(\"Add file contents to the index\"),\n  Command.provideEffect(AddService, (_) => Effect.succeed(\"AddService\" as const))\n)\n\nconst run = git.pipe(\n  Command.withSubcommands([clone, add]),\n  Command.run({\n    name: \"git\",\n    version: \"1.0.0\"\n  })\n)\n\ndescribe(\"Command\", () => {\n  describe(\"git\", () => {\n    it(\"no sub-command\", () =>\n      Effect.gen(function*() {\n        const messages = yield* Messages\n        yield* run([\"--verbose\"])\n        yield* run([])\n        assert.deepStrictEqual(yield* messages.messages, [\"shared\", \"shared\"])\n      }).pipe(Effect.provide(EnvLive), Effect.runPromise))\n\n    it(\"add\", () =>\n      Effect.gen(function*() {\n        const messages = yield* Messages\n        yield* run([\"node\", \"git.js\", \"add\", \"file\"])\n        yield* run([\"node\", \"git.js\", \"--verbose\", \"add\", \"file\"])\n        assert.deepStrictEqual(yield* messages.messages, [\n          \"shared\",\n          \"Adding\",\n          \"shared\",\n          \"Adding file\"\n        ])\n      }).pipe(Effect.provide(EnvLive), Effect.runPromise))\n\n    it(\"clone\", () =>\n      Effect.gen(function*() {\n        const messages = yield* Messages\n        yield* run([\"node\", \"git.js\", \"clone\", \"repo\"])\n        yield* run([\"node\", \"git.js\", \"--verbose\", \"clone\", \"repo\"])\n        assert.deepStrictEqual(yield* messages.messages, [\n          \"shared\",\n          \"Cloning\",\n          \"shared\",\n          \"Cloning repo\"\n        ])\n      }).pipe(Effect.provide(EnvLive), Effect.runPromise))\n\n    it(\"withFallbackConfig Options boolean\", () =>\n      Effect.gen(function*() {\n        const messages = yield* Messages\n        yield* run([\"node\", \"git.js\", \"clone\", \"repo\"])\n        assert.deepStrictEqual(yield* messages.messages, [\n          \"shared\",\n          \"Cloning repo\"\n        ])\n      }).pipe(\n        Effect.withConfigProvider(ConfigProvider.fromMap(\n          new Map([[\"VERBOSE\", \"true\"]])\n        )),\n        Effect.provide(EnvLive),\n        Effect.runPromise\n      ))\n\n    it(\"withFallbackConfig Args\", () =>\n      Effect.gen(function*() {\n        const messages = yield* Messages\n        yield* run([\"node\", \"git.js\", \"clone\"])\n        assert.deepStrictEqual(yield* messages.messages, [\n          \"shared\",\n          \"Cloning repo\"\n        ])\n      }).pipe(\n        Effect.withConfigProvider(ConfigProvider.fromMap(\n          new Map([[\"VERBOSE\", \"true\"], [\"REPOSITORY\", \"repo\"]])\n        )),\n        Effect.provide(EnvLive),\n        Effect.runPromise\n      ))\n\n    it(\"options after positional args\", () =>\n      Effect.gen(function*() {\n        const messages = yield* Messages\n        // --verbose after the positional arg \"repo\"\n        yield* run([\"node\", \"git.js\", \"clone\", \"repo\", \"--verbose\"])\n        assert.deepStrictEqual(yield* messages.messages, [\n          \"shared\",\n          \"Cloning repo\"\n        ])\n      }).pipe(Effect.provide(EnvLive), Effect.runPromise))\n\n    it(\"options after positional args with alias\", () =>\n      Effect.gen(function*() {\n        const messages = yield* Messages\n        // -v after the positional arg \"repo\"\n        yield* run([\"node\", \"git.js\", \"clone\", \"repo\", \"-v\"])\n        assert.deepStrictEqual(yield* messages.messages, [\n          \"shared\",\n          \"Cloning repo\"\n        ])\n      }).pipe(Effect.provide(EnvLive), Effect.runPromise))\n  })\n})\n\n// --\n\ninterface Messages {\n  readonly log: (message: string) => Effect.Effect<void>\n  readonly messages: Effect.Effect<ReadonlyArray<string>>\n}\nconst Messages = Context.GenericTag<Messages>(\"Messages\")\nconst MessagesLive = Layer.sync(Messages, () => {\n  const messages: Array<string> = []\n  return Messages.of({\n    log: (message) => Effect.sync(() => messages.push(message)),\n    messages: Effect.sync(() => messages)\n  })\n})\nconst EnvLive = Layer.mergeAll(MessagesLive, NodeContext.layer)\n"
  },
  {
    "path": "packages/cli/test/CommandDescriptor.test.ts",
    "content": "import * as Args from \"@effect/cli/Args\"\nimport * as BuiltInOptions from \"@effect/cli/BuiltInOptions\"\nimport * as CliConfig from \"@effect/cli/CliConfig\"\nimport * as Descriptor from \"@effect/cli/CommandDescriptor\"\nimport * as CommandDirective from \"@effect/cli/CommandDirective\"\nimport * as HelpDoc from \"@effect/cli/HelpDoc\"\nimport * as Options from \"@effect/cli/Options\"\nimport * as ValidationError from \"@effect/cli/ValidationError\"\nimport * as NodeContext from \"@effect/platform-node/NodeContext\"\nimport * as Doc from \"@effect/printer/Doc\"\nimport { describe, expect, it } from \"@effect/vitest\"\nimport { Array, Effect, Option, pipe, String } from \"effect\"\nimport * as Grep from \"./utils/grep.js\"\nimport * as Tail from \"./utils/tail.js\"\nimport * as WordCount from \"./utils/wc.js\"\n\nconst runEffect = <E, A>(\n  self: Effect.Effect<A, E, NodeContext.NodeContext>\n): Promise<A> =>\n  Effect.provide(self, NodeContext.layer).pipe(\n    Effect.runPromise\n  )\n\ndescribe(\"Command\", () => {\n  describe(\"Standard Commands\", () => {\n    it(\"should validate a command with options followed by arguments\", () =>\n      Effect.gen(function*() {\n        const args1 = Array.make(\"tail\", \"-n\", \"100\", \"foo.log\")\n        const args2 = Array.make(\"grep\", \"--after\", \"2\", \"--before\", \"3\", \"fooBar\")\n        const result1 = yield* Descriptor.parse(Tail.command, args1, CliConfig.defaultConfig)\n        const result2 = yield* Descriptor.parse(Grep.command, args2, CliConfig.defaultConfig)\n        const expected1 = { name: \"tail\", options: 100, args: \"foo.log\" }\n        const expected2 = { name: \"grep\", options: [2, 3], args: \"fooBar\" }\n        expect(result1).toEqual(CommandDirective.userDefined(Array.empty(), expected1))\n        expect(result2).toEqual(CommandDirective.userDefined(Array.empty(), expected2))\n      }).pipe(runEffect))\n\n    it(\"should provide auto-correct suggestions for misspelled options\", () =>\n      Effect.gen(function*() {\n        const args1 = Array.make(\"grep\", \"--afte\", \"2\", \"--before\", \"3\", \"fooBar\")\n        const args2 = Array.make(\"grep\", \"--after\", \"2\", \"--efore\", \"3\", \"fooBar\")\n        const args3 = Array.make(\"grep\", \"--afte\", \"2\", \"--efore\", \"3\", \"fooBar\")\n        const result1 = yield* Effect.flip(Descriptor.parse(Grep.command, args1, CliConfig.defaultConfig))\n        const result2 = yield* Effect.flip(Descriptor.parse(Grep.command, args2, CliConfig.defaultConfig))\n        const result3 = yield* Effect.flip(Descriptor.parse(Grep.command, args3, CliConfig.defaultConfig))\n        expect(result1).toEqual(ValidationError.correctedFlag(HelpDoc.p(\n          \"The flag '--afte' is not recognized. Did you mean '--after'?\"\n        )))\n        expect(result2).toEqual(ValidationError.correctedFlag(HelpDoc.p(\n          \"The flag '--efore' is not recognized. Did you mean '--before'?\"\n        )))\n        expect(result3).toEqual(ValidationError.correctedFlag(HelpDoc.p(\n          \"The flag '--afte' is not recognized. Did you mean '--after'?\"\n        )))\n      }).pipe(runEffect))\n\n    it(\"should return an error if an option is missing\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\"grep\", \"--a\", \"2\", \"--before\", \"3\", \"fooBar\")\n        const result = yield* Effect.flip(Descriptor.parse(Grep.command, args, CliConfig.defaultConfig))\n        expect(result).toEqual(ValidationError.missingValue(HelpDoc.sequence(\n          HelpDoc.p(\"Expected to find option: '--after'\"),\n          HelpDoc.p(\"Expected to find option: '--before'\")\n        )))\n      }).pipe(runEffect))\n  })\n\n  describe(\"Commands with Clustered Options\", () => {\n    it(\"should treat clustered boolean options as un-clustered options\", () =>\n      Effect.gen(function*() {\n        const args1 = Array.make(\"wc\", \"-clw\", \"filename\")\n        const args2 = Array.make(\"wc\", \"-c\", \"-l\", \"-w\", \"filename\")\n        const result1 = yield* Descriptor.parse(WordCount.command, args1, CliConfig.defaultConfig)\n        const result2 = yield* Descriptor.parse(WordCount.command, args2, CliConfig.defaultConfig)\n        const expected = { name: \"wc\", options: [true, true, true, true], args: [\"filename\"] }\n        expect(result1).toEqual(CommandDirective.userDefined(Array.empty(), expected))\n        expect(result2).toEqual(CommandDirective.userDefined(Array.empty(), expected))\n      }).pipe(runEffect))\n\n    it(\"should not uncluster wrong clusters\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\"wc\", \"-clk\")\n        const result = yield* Descriptor.parse(WordCount.command, args, CliConfig.defaultConfig)\n        const expected = { name: \"wc\", options: [false, false, false, true], args: [\"-clk\"] }\n        expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected))\n      }).pipe(runEffect))\n\n    it(\"should not alter '-'\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\"wc\", \"-\")\n        const result = yield* Descriptor.parse(WordCount.command, args, CliConfig.defaultConfig)\n        const expected = { name: \"wc\", options: [false, false, false, true], args: [\"-\"] }\n        expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected))\n      }).pipe(runEffect))\n  })\n\n  describe(\"Subcommands without Options or Arguments\", () => {\n    const options = Options.boolean(\"verbose\").pipe(Options.withAlias(\"v\"))\n\n    const git = Descriptor.make(\"git\", options).pipe(Descriptor.withSubcommands([\n      [\"remote\", Descriptor.make(\"remote\")],\n      [\"log\", Descriptor.make(\"log\")]\n    ]))\n\n    it(\"should match the top-level command if no subcommands are specified\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\"git\", \"-v\")\n        const result = yield* Descriptor.parse(git, args, CliConfig.defaultConfig)\n        const expected = { name: \"git\", options: true, args: void 0, subcommand: Option.none() }\n        expect(result).toEqual(CommandDirective.userDefined([], expected))\n      }).pipe(runEffect))\n\n    it(\"should match the first subcommand without any surplus arguments\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\"git\", \"remote\")\n        const result = yield* Descriptor.parse(git, args, CliConfig.defaultConfig)\n        const expected = {\n          name: \"git\",\n          options: false,\n          args: void 0,\n          subcommand: Option.some([\"remote\", { name: \"remote\", options: void 0, args: void 0 }])\n        }\n        expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected))\n      }).pipe(runEffect))\n\n    it(\"matches the first subcommand with parent option after subcommand\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\"git\", \"remote\", \"-v\")\n        const result = yield* Descriptor.parse(git, args, CliConfig.defaultConfig)\n        // -v is recognized as git's verbose option, even after the subcommand\n        const expected = {\n          name: \"git\",\n          options: true,\n          args: void 0,\n          subcommand: Option.some([\"remote\", { name: \"remote\", options: void 0, args: void 0 }])\n        }\n        expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected))\n      }).pipe(runEffect))\n\n    it(\"matches the second subcommand without any surplus arguments\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\"git\", \"log\")\n        const result = yield* Descriptor.parse(git, args, CliConfig.defaultConfig)\n        const expected = {\n          name: \"git\",\n          options: false,\n          args: void 0,\n          subcommand: Option.some([\"log\", { name: \"log\", options: void 0, args: void 0 }])\n        }\n        expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected))\n      }).pipe(runEffect))\n\n    it(\"should return an error message for an unknown subcommand\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\"git\", \"abc\")\n        const result = yield* Effect.flip(Descriptor.parse(git, args, CliConfig.defaultConfig))\n        expect(result).toEqual(ValidationError.commandMismatch(HelpDoc.p(\n          \"Invalid subcommand for git - use one of 'remote', 'log'\"\n        )))\n      }).pipe(runEffect))\n  })\n\n  describe(\"Subcommands with Options and Arguments\", () => {\n    const options = Options.all([\n      Options.boolean(\"i\"),\n      Options.text(\"empty\").pipe(Options.withDefault(\"drop\"))\n    ])\n\n    const args = Args.all([Args.text(), Args.text()])\n\n    const git = Descriptor.make(\"git\").pipe(Descriptor.withSubcommands([\n      [\"rebase\", Descriptor.make(\"rebase\", options, args)]\n    ]))\n\n    it(\"should parse a subcommand with required options and arguments\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\"git\", \"rebase\", \"-i\", \"upstream\", \"branch\")\n        const result = yield* Descriptor.parse(git, args, CliConfig.defaultConfig)\n        const expected = {\n          name: \"git\",\n          options: void 0,\n          args: void 0,\n          subcommand: Option.some([\"rebase\", {\n            name: \"rebase\",\n            options: [true, \"drop\"],\n            args: [\"upstream\", \"branch\"]\n          }])\n        }\n        expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected))\n      }).pipe(runEffect))\n\n    it(\"should parse a subcommand with required and optional options and arguments\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\n          \"git\",\n          \"rebase\",\n          \"-i\",\n          \"--empty\",\n          \"ask\",\n          \"upstream\",\n          \"branch\"\n        )\n        const result = yield* Descriptor.parse(git, args, CliConfig.defaultConfig)\n        const expected = {\n          name: \"git\",\n          options: void 0,\n          args: void 0,\n          subcommand: Option.some([\"rebase\", {\n            name: \"rebase\",\n            options: [true, \"ask\"],\n            args: [\"upstream\", \"branch\"]\n          }])\n        }\n        expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected))\n      }).pipe(runEffect))\n  })\n\n  describe(\"Nested Subcommands\", () => {\n    const command = Descriptor.make(\"command\").pipe(Descriptor.withSubcommands([\n      [\n        \"sub\",\n        Descriptor.make(\"sub\").pipe(Descriptor.withSubcommands([\n          [\"subsub\", Descriptor.make(\"subsub\", Options.boolean(\"i\"), Args.text())]\n        ]))\n      ]\n    ]))\n\n    it(\"should properly parse deeply nested subcommands with options and arguments\", () =>\n      Effect.gen(function*() {\n        const args = Array.make(\"command\", \"sub\", \"subsub\", \"-i\", \"text\")\n        const result = yield* Descriptor.parse(command, args, CliConfig.defaultConfig)\n        const expected = {\n          name: \"command\",\n          options: void 0,\n          args: void 0,\n          subcommand: Option.some([\"sub\", {\n            name: \"sub\",\n            options: void 0,\n            args: void 0,\n            subcommand: Option.some([\"subsub\", {\n              name: \"subsub\",\n              options: true,\n              args: \"text\"\n            }])\n          }])\n        }\n        expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expected))\n      }).pipe(runEffect))\n  })\n\n  describe(\"Help Documentation\", () => {\n    it(\"should allow adding help documentation to a command\", () =>\n      Effect.gen(function*() {\n        const config = CliConfig.make({ showBuiltIns: false })\n        const cmd = Descriptor.make(\"tldr\").pipe(Descriptor.withDescription(\"this is some help\"))\n        const args = Array.of(\"tldr\")\n        const result = yield* Descriptor.parse(cmd, args, CliConfig.defaultConfig)\n        const expectedValue = { name: \"tldr\", options: void 0, args: void 0 }\n        const expectedDoc = HelpDoc.sequence(\n          HelpDoc.h1(\"DESCRIPTION\"),\n          HelpDoc.p(\"this is some help\")\n        )\n        expect(result).toEqual(CommandDirective.userDefined(Array.empty(), expectedValue))\n        expect(Descriptor.getHelp(cmd, config)).toEqual(expectedDoc)\n      }).pipe(runEffect))\n\n    it(\"should allow adding help documentation to subcommands\", () => {\n      const config = CliConfig.make({ showBuiltIns: false })\n      const cmd = Descriptor.make(\"command\").pipe(Descriptor.withSubcommands([\n        [\"sub\", Descriptor.make(\"sub\").pipe(Descriptor.withDescription(\"this is some help\"))]\n      ]))\n      const expected = HelpDoc.sequence(HelpDoc.h1(\"DESCRIPTION\"), HelpDoc.p(\"this is some help\"))\n      expect(Descriptor.getHelp(cmd, config)).not.toEqual(expected)\n    })\n\n    it(\"should correctly display help documentation for a command\", () => {\n      const config = CliConfig.make({ showBuiltIns: false })\n      const child2 = Descriptor.make(\"child2\").pipe(\n        Descriptor.withDescription(\"help 2\")\n      )\n      const child1 = Descriptor.make(\"child1\").pipe(\n        Descriptor.withSubcommands([[\"child2\", child2]]),\n        Descriptor.withDescription(\"help 1\")\n      )\n      const parent = Descriptor.make(\"parent\").pipe(\n        Descriptor.withSubcommands([[\"child1\", child1]])\n      )\n      const result = Doc.render(\n        Doc.unAnnotate(HelpDoc.toAnsiDoc(Descriptor.getHelp(parent, config))),\n        { style: \"pretty\" }\n      )\n      expect(result).toBe(String.stripMargin(\n        `|COMMANDS\n         |\n         |  - child1         help 1\n         |\n         |  - child1 child2  help 2\n         |`\n      ))\n    })\n  })\n\n  describe(\"Built-In Options Processing\", () => {\n    const command = Descriptor.make(\"command\", Options.text(\"a\"))\n    const params1 = Array.make(\"command\", \"--help\")\n    const params2 = Array.make(\"command\", \"-h\")\n    const params3 = Array.make(\"command\", \"--wizard\")\n    const params4 = Array.make(\"command\", \"--completions\", \"sh\")\n    const params5 = Array.make(\"command\", \"-a\", \"--help\")\n    const params6 = Array.make(\"command\", \"--help\", \"--wizard\", \"-b\")\n    const params7 = Array.make(\"command\", \"-hdf\", \"--help\")\n    const params8 = Array.make(\"command\", \"-af\", \"asdgf\", \"--wizard\")\n\n    const directiveType = <A>(directive: CommandDirective.CommandDirective<A>): string => {\n      if (CommandDirective.isBuiltIn(directive)) {\n        if (BuiltInOptions.isShowHelp(directive.option)) {\n          return \"help\"\n        }\n        if (BuiltInOptions.isShowWizard(directive.option)) {\n          return \"wizard\"\n        }\n        if (BuiltInOptions.isShowCompletions(directive.option)) {\n          return \"completions\"\n        }\n      }\n      return \"user\"\n    }\n\n    it(\"should trigger built-in options if they are alone\", () =>\n      Effect.gen(function*() {\n        const result1 = yield* pipe(\n          Descriptor.parse(command, params1, CliConfig.defaultConfig),\n          Effect.map(directiveType)\n        )\n        const result2 = yield* pipe(\n          Descriptor.parse(command, params2, CliConfig.defaultConfig),\n          Effect.map(directiveType)\n        )\n        const result3 = yield* pipe(\n          Descriptor.parse(command, params3, CliConfig.defaultConfig),\n          Effect.map(directiveType)\n        )\n        const result4 = yield* pipe(\n          Descriptor.parse(command, params4, CliConfig.defaultConfig),\n          Effect.map(directiveType)\n        )\n        expect(result1).toBe(\"help\")\n        expect(result2).toBe(\"help\")\n        expect(result3).toBe(\"wizard\")\n        expect(result4).toBe(\"completions\")\n      }).pipe(runEffect))\n\n    it(\"should not trigger help if an option matches\", () =>\n      Effect.gen(function*() {\n        const result = yield* pipe(\n          Descriptor.parse(command, params5, CliConfig.defaultConfig),\n          Effect.map(directiveType)\n        )\n        expect(result).toBe(\"user\")\n      }).pipe(runEffect))\n\n    it(\"should trigger help even if not alone\", () =>\n      Effect.gen(function*() {\n        const config = CliConfig.make({ finalCheckBuiltIn: true })\n        const result1 = yield* pipe(\n          Descriptor.parse(command, params6, config),\n          Effect.map(directiveType)\n        )\n        const result2 = yield* pipe(\n          Descriptor.parse(command, params7, config),\n          Effect.map(directiveType)\n        )\n        expect(result1).toBe(\"help\")\n        expect(result2).toBe(\"help\")\n      }).pipe(runEffect))\n\n    it(\"should trigger wizard even if not alone\", () =>\n      Effect.gen(function*() {\n        const config = CliConfig.make({ finalCheckBuiltIn: true })\n        const result = yield* pipe(\n          Descriptor.parse(command, params8, config),\n          Effect.map(directiveType)\n        )\n        expect(result).toBe(\"wizard\")\n      }).pipe(runEffect))\n  })\n\n  describe(\"End of Command Options Symbol\", () => {\n    const command = Descriptor.make(\n      \"cmd\",\n      Options.all([\n        Options.optional(Options.text(\"something\")),\n        Options.boolean(\"verbose\").pipe(Options.withAlias(\"v\"))\n      ]),\n      Args.repeated(Args.text())\n    )\n\n    it(\"should properly handle the end of command options symbol\", () =>\n      Effect.gen(function*() {\n        const args1 = Array.make(\"cmd\", \"-v\", \"--something\", \"abc\", \"something\")\n        const args2 = Array.make(\"cmd\", \"-v\", \"--\", \"--something\", \"abc\", \"something\")\n        const args3 = Array.make(\"cmd\", \"--\", \"-v\", \"--something\", \"abc\", \"something\")\n        const result1 = yield* Descriptor.parse(command, args1, CliConfig.defaultConfig)\n        const result2 = yield* Descriptor.parse(command, args2, CliConfig.defaultConfig)\n        const result3 = yield* Descriptor.parse(command, args3, CliConfig.defaultConfig)\n        const expected1 = {\n          name: \"cmd\",\n          options: [Option.some(\"abc\"), true],\n          args: Array.of(\"something\")\n        }\n        const expected2 = {\n          name: \"cmd\",\n          options: [Option.none(), true],\n          args: Array.make(\"--something\", \"abc\", \"something\")\n        }\n        const expected3 = {\n          name: \"cmd\",\n          options: [Option.none(), false],\n          args: Array.make(\"-v\", \"--something\", \"abc\", \"something\")\n        }\n        expect(result1).toEqual(CommandDirective.userDefined(Array.empty(), expected1))\n        expect(result2).toEqual(CommandDirective.userDefined(Array.empty(), expected2))\n        expect(result3).toEqual(CommandDirective.userDefined(Array.empty(), expected3))\n      }).pipe(runEffect))\n  })\n\n  describe(\"Completions\", () => {\n    const command = Descriptor.make(\"forge\").pipe(Descriptor.withSubcommands([\n      [\n        \"cache\",\n        Descriptor.make(\n          \"cache\",\n          Options.boolean(\"verbose\").pipe(\n            Options.withDescription(\"Output in verbose mode\")\n          )\n        ).pipe(\n          Descriptor.withDescription(\"The cache command does cache things\"),\n          Descriptor.withSubcommands([\n            [\"clean\", Descriptor.make(\"clean\")],\n            [\"ls\", Descriptor.make(\"ls\")]\n          ])\n        )\n      ]\n    ]))\n\n    it(\"should create completions for the bash shell\", () =>\n      Effect.gen(function*() {\n        const result = yield* Descriptor.getBashCompletions(command, \"forge\")\n        yield* Effect.promise(() => expect(result).toMatchFileSnapshot(\"./snapshots/bash-completions\"))\n      }).pipe(runEffect))\n\n    it(\"should create completions for the zsh shell\", () =>\n      Effect.gen(function*() {\n        const result = yield* Descriptor.getZshCompletions(command, \"forge\")\n        yield* Effect.promise(() => expect(result).toMatchFileSnapshot(\"./snapshots/zsh-completions\"))\n      }).pipe(runEffect))\n\n    it(\"should create completions for the fish shell\", () =>\n      Effect.gen(function*() {\n        const result = yield* Descriptor.getFishCompletions(command, \"forge\")\n        yield* Effect.promise(() => expect(result).toMatchFileSnapshot(\"./snapshots/fish-completions\"))\n      }).pipe(runEffect))\n  })\n})\n"
  },
  {
    "path": "packages/cli/test/ConfigFile.test.ts",
    "content": "import * as ConfigFile from \"@effect/cli/ConfigFile\"\nimport type { FileSystem } from \"@effect/platform\"\nimport { Path } from \"@effect/platform\"\nimport { NodeContext } from \"@effect/platform-node\"\nimport { assert, describe, it } from \"@effect/vitest\"\nimport * as Config from \"effect/Config\"\nimport * as Effect from \"effect/Effect\"\n\nconst runEffect = <E, A>(\n  self: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>\n): Promise<A> => Effect.provide(self, NodeContext.layer).pipe(Effect.runPromise)\n\ndescribe(\"ConfigFile\", () => {\n  it(\"loads json files\", () =>\n    Effect.gen(function*() {\n      const path = yield* Path.Path\n      const result = yield* Config.all([\n        Config.boolean(\"foo\"),\n        Config.string(\"bar\")\n      ]).pipe(\n        Effect.provide(ConfigFile.layer(\"config\", {\n          searchPaths: [path.join(__dirname, \"fixtures\")],\n          formats: [\"json\"]\n        }))\n      )\n      assert.deepStrictEqual(result, [true, \"baz\"])\n    }).pipe(runEffect))\n\n  it(\"loads yaml\", () =>\n    Effect.gen(function*() {\n      const path = yield* Path.Path\n      const result = yield* Config.integer(\"foo\").pipe(\n        Effect.provide(ConfigFile.layer(\"config-file\", {\n          searchPaths: [path.join(__dirname, \"fixtures\")]\n        }))\n      )\n      assert.deepStrictEqual(result, 123)\n    }).pipe(runEffect))\n})\n"
  },
  {
    "path": "packages/cli/test/Options.test.ts",
    "content": "import * as CliConfig from \"@effect/cli/CliConfig\"\nimport * as HelpDoc from \"@effect/cli/HelpDoc\"\nimport * as Options from \"@effect/cli/Options\"\nimport * as ValidationError from \"@effect/cli/ValidationError\"\nimport * as NodeContext from \"@effect/platform-node/NodeContext\"\nimport * as FileSystem from \"@effect/platform/FileSystem\"\nimport * as Path from \"@effect/platform/Path\"\nimport { assert, describe, expect, it } from \"@effect/vitest\"\nimport { BigDecimal, pipe } from \"effect\"\nimport * as Array from \"effect/Array\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { identity } from \"effect/Function\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\n\nconst firstName = Options.text(\"firstName\").pipe(Options.withAlias(\"f\"))\nconst lastName = Options.text(\"lastName\")\nconst age = Options.integer(\"age\")\nconst balance = Options.text(\"balance\").pipe(Options.withSchema(Schema.BigDecimal))\nconst ageOptional = Options.optional(age)\nconst verbose = Options.boolean(\"verbose\", { ifPresent: true })\nconst defs = Options.keyValueMap(\"defs\").pipe(Options.withAlias(\"d\"))\n\nconst runEffect = <E, A>(\n  self: Effect.Effect<A, E, NodeContext.NodeContext>\n): Promise<A> => Effect.provide(self, NodeContext.layer).pipe(Effect.runPromise)\n\nconst process = <A>(\n  options: Options.Options<A>,\n  args: ReadonlyArray<string>,\n  config: CliConfig.CliConfig\n): Effect.Effect<\n  [ReadonlyArray<string>, A],\n  ValidationError.ValidationError,\n  NodeContext.NodeContext\n> =>\n  Options.processCommandLine(options, args, config).pipe(\n    Effect.flatMap(([err, rest, a]) =>\n      Option.match(err, {\n        onNone: () => Effect.succeed([rest, a]),\n        onSome: Effect.fail\n      })\n    )\n  )\n\ndescribe(\"Options\", () => {\n  it(\"should validate without ambiguity\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--firstName\", \"--lastName\", \"--lastName\", \"--firstName\")\n      const result1 = yield* process(Options.all([firstName, lastName]), args, CliConfig.defaultConfig)\n      const result2 = yield* process(Options.all([lastName, firstName]), args, CliConfig.defaultConfig)\n      const expected1 = [Array.empty(), Array.make(\"--lastName\", \"--firstName\")]\n      const expected2 = [Array.empty(), Array.make(\"--firstName\", \"--lastName\")]\n      expect(result1).toEqual(expected1)\n      expect(result2).toEqual(expected2)\n    }).pipe(runEffect))\n\n  it(\"should not uncluster values\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--firstName\", \"-ab\")\n      const result = yield* process(firstName, args, CliConfig.defaultConfig)\n      const expected = [Array.empty(), \"-ab\"]\n      expect(result).toEqual(expected)\n    }).pipe(runEffect))\n\n  it(\"should return a HelpDoc if an option is not an exact match and it's a short option\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--ag\", \"20\")\n      const result = yield* Effect.flip(process(age, args, CliConfig.defaultConfig))\n      expect(result).toEqual(ValidationError.missingValue(HelpDoc.p(\n        \"Expected to find option: '--age'\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"should return a HelpDoc if there is a collision between arguments\", () =>\n    Effect.gen(function*() {\n      const options = Options.orElse(\n        Options.text(\"a\").pipe(Options.map(identity)),\n        Options.text(\"b\").pipe(Options.map(identity))\n      )\n      const args = Array.make(\"-a\", \"a\", \"-b\", \"b\")\n      const result = yield* Effect.flip(process(options, args, CliConfig.defaultConfig))\n      expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"Collision between two options detected - you can only \" +\n          \"specify one of either: ['-a', '-b']\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"validates a boolean option without a value\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--verbose\")\n      const result = yield* process(verbose, args, CliConfig.defaultConfig)\n      const expected = [Array.empty(), true]\n      expect(result).toEqual(expected)\n    }).pipe(runEffect))\n\n  it(\"validates a boolean option with a followup option\", () =>\n    Effect.gen(function*() {\n      const options = Options.all([Options.boolean(\"help\"), Options.boolean(\"v\")])\n      const args1 = Array.empty()\n      const args2 = Array.make(\"--help\")\n      const args3 = Array.make(\"--help\", \"-v\")\n      const result1 = yield* process(options, args1, CliConfig.defaultConfig)\n      const result2 = yield* process(options, args2, CliConfig.defaultConfig)\n      const result3 = yield* process(options, args3, CliConfig.defaultConfig)\n      const expected1 = [Array.empty(), [false, false]]\n      const expected2 = [Array.empty(), [true, false]]\n      const expected3 = [Array.empty(), [true, true]]\n      expect(result1).toEqual(expected1)\n      expect(result2).toEqual(expected2)\n      expect(result3).toEqual(expected3)\n    }).pipe(runEffect))\n\n  it(\"validates a boolean option with negation\", () =>\n    Effect.gen(function*() {\n      const option = Options.boolean(\"verbose\", { aliases: [\"v\"], negationNames: [\"silent\", \"s\"] })\n      const result1 = yield* process(option, [], CliConfig.defaultConfig)\n      const result2 = yield* process(option, [\"--verbose\"], CliConfig.defaultConfig)\n      const result3 = yield* process(option, [\"-v\"], CliConfig.defaultConfig)\n      const result4 = yield* process(option, [\"--silent\"], CliConfig.defaultConfig)\n      const result5 = yield* process(option, [\"-s\"], CliConfig.defaultConfig)\n      const result6 = yield* Effect.flip(process(option, [\"--verbose\", \"--silent\"], CliConfig.defaultConfig))\n      const result7 = yield* Effect.flip(process(option, [\"-v\", \"-s\"], CliConfig.defaultConfig))\n      expect(result1).toEqual([[], false])\n      expect(result2).toEqual([[], true])\n      expect(result3).toEqual([[], true])\n      expect(result4).toEqual([[], false])\n      expect(result5).toEqual([[], false])\n      expect(result6).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"Collision between two options detected - \" +\n          \"you can only specify one of either: ['--verbose', '--silent']\"\n      )))\n      expect(result7).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"Collision between two options detected - \" +\n          \"you can only specify one of either: ['--verbose', '--silent']\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"does not validate collision of boolean options with negation\", () =>\n    Effect.gen(function*() {\n      const option = Options.boolean(\"v\", { negationNames: [\"s\"] })\n      const args = Array.make(\"-v\", \"-s\")\n      const result = yield* Effect.flip(process(option, args, CliConfig.defaultConfig))\n      expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"Collision between two options detected - \" +\n          \"you can only specify one of either: ['-v', '-s']\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"validates a option with choices\", () =>\n    Effect.gen(function*() {\n      const option = Options.choice(\"animal\", [\"cat\", \"dog\"])\n      const args1 = Array.make(\"--animal\", \"cat\")\n      const args2 = Array.make(\"--animal\", \"dog\")\n      const result1 = yield* process(option, args1, CliConfig.defaultConfig)\n      const result2 = yield* process(option, args2, CliConfig.defaultConfig)\n      expect(result1).toEqual([[], \"cat\"])\n      expect(result2).toEqual([[], \"dog\"])\n    }).pipe(runEffect))\n\n  it(\"validates an option with choices that map to values\", () =>\n    Effect.gen(function*() {\n      type Animal = Dog | Cat\n      class Dog extends Data.TaggedClass(\"Dog\")<{}> {}\n      class Cat extends Data.TaggedClass(\"Dog\")<{}> {}\n      const cat = new Cat()\n      const dog = new Dog()\n      const option: Options.Options<Animal> = Options.choiceWithValue(\"animal\", [\n        [\"dog\", dog],\n        [\"cat\", cat]\n      ])\n      const args1 = Array.make(\"--animal\", \"cat\")\n      const args2 = Array.make(\"--animal\", \"dog\")\n      const result1 = yield* process(option, args1, CliConfig.defaultConfig)\n      const result2 = yield* process(option, args2, CliConfig.defaultConfig)\n      expect(result1).toEqual([[], cat])\n      expect(result2).toEqual([[], dog])\n    }).pipe(runEffect))\n\n  it(\"validates a text option\", () =>\n    Effect.gen(function*() {\n      const result = yield* process(firstName, [\"--firstName\", \"John\"], CliConfig.defaultConfig)\n      expect(result).toEqual([[], \"John\"])\n    }).pipe(runEffect))\n\n  it(\"validates a text option with an alternative format\", () =>\n    Effect.gen(function*() {\n      const result = yield* process(firstName, [\"--firstName=John\"], CliConfig.defaultConfig)\n      expect(result).toEqual([[], \"John\"])\n    }).pipe(runEffect))\n\n  it(\"validates a text option with an alias\", () =>\n    Effect.gen(function*() {\n      const result = yield* process(firstName, [\"-f\", \"John\"], CliConfig.defaultConfig)\n      expect(result).toEqual([[], \"John\"])\n    }).pipe(runEffect))\n\n  it(\"validates an integer option\", () =>\n    Effect.gen(function*() {\n      const result = yield* process(age, [\"--age\", \"100\"], CliConfig.defaultConfig)\n      expect(result).toEqual([[], 100])\n    }).pipe(runEffect))\n\n  it(\"validates an option and returns the remainder\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--firstName\", \"John\", \"--lastName\", \"Doe\")\n      const result = yield* process(firstName, args, CliConfig.defaultConfig)\n      expect(result).toEqual([[\"--lastName\", \"Doe\"], \"John\"])\n    }).pipe(runEffect))\n\n  it(\"does not validate when no valid values are passed\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--lastName\", \"Doe\")\n      const result = yield* Effect.either(process(firstName, args, CliConfig.defaultConfig))\n      expect(result).toEqual(Either.left(ValidationError.missingValue(HelpDoc.p(\n        \"Expected to find option: '--firstName'\"\n      ))))\n    }).pipe(runEffect))\n\n  it(\"does not validate when an option is passed without a corresponding value\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--firstName\")\n      const result = yield* Effect.either(process(firstName, args, CliConfig.defaultConfig))\n      expect(result).toEqual(Either.left(ValidationError.missingValue(HelpDoc.p(\n        \"Expected a value following option: '--firstName'\"\n      ))))\n    }).pipe(runEffect))\n\n  it(\"does not validate an invalid option value\", () =>\n    Effect.gen(function*() {\n      const option = Options.integer(\"t\")\n      const args = Array.make(\"-t\", \"abc\")\n      const result = yield* Effect.flip(process(option, args, CliConfig.defaultConfig))\n      expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p(\"'abc' is not a integer\")))\n    }).pipe(runEffect))\n\n  it(\"does not validate an invalid option value even when there is a default\", () =>\n    Effect.gen(function*() {\n      const option = Options.withDefault(Options.integer(\"t\"), 0)\n      const args = Array.make(\"-t\", \"abc\")\n      const result = yield* Effect.flip(process(option, args, CliConfig.defaultConfig))\n      expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p(\"'abc' is not a integer\")))\n    }).pipe(runEffect))\n\n  it(\"validates with case-sensitive configuration\", () =>\n    Effect.gen(function*() {\n      const config = CliConfig.make({ isCaseSensitive: true, autoCorrectLimit: 2 })\n      const option = Options.text(\"Firstname\").pipe(Options.withAlias(\"F\"))\n      const args1 = Array.make(\"--Firstname\", \"John\")\n      const args2 = Array.make(\"-F\", \"John\")\n      const args3 = Array.make(\"--firstname\", \"John\")\n      const args4 = Array.make(\"-f\", \"John\")\n      const result1 = yield* process(option, args1, config)\n      const result2 = yield* process(option, args2, config)\n      const result3 = yield* Effect.flip(process(option, args3, config))\n      const result4 = yield* Effect.flip(process(option, args4, config))\n      expect(result1).toEqual([[], \"John\"])\n      expect(result2).toEqual([[], \"John\"])\n      expect(result3).toEqual(ValidationError.correctedFlag(HelpDoc.p(\n        \"The flag '--firstname' is not recognized. Did you mean '--Firstname'?\"\n      )))\n      expect(result4).toEqual(ValidationError.missingValue(HelpDoc.p(\n        \"Expected to find option: '--Firstname'\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"validates an unsupplied optional option\", () =>\n    Effect.gen(function*() {\n      const result = yield* process(ageOptional, [], CliConfig.defaultConfig)\n      expect(result).toEqual([[], Option.none()])\n    }).pipe(runEffect))\n\n  it(\"validates an unsupplied optional option with remainder\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--bar\", \"baz\")\n      const result = yield* process(ageOptional, args, CliConfig.defaultConfig)\n      expect(result).toEqual([args, Option.none()])\n    }).pipe(runEffect))\n\n  it(\"validates a supplied optional option\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--age\", \"20\")\n      const result = yield* process(ageOptional, args, CliConfig.defaultConfig)\n      expect(result).toEqual([[], Option.some(20)])\n    }).pipe(runEffect))\n\n  it(\"validates using all and returns the specified structure\", () =>\n    Effect.gen(function*() {\n      const option1 = Options.all({\n        firstName: Options.text(\"firstName\"),\n        lastName: Options.text(\"lastName\")\n      })\n      const option2 = Options.all([Options.text(\"firstName\"), Options.text(\"lastName\")])\n      const args = Array.make(\"--firstName\", \"John\", \"--lastName\", \"Doe\")\n      const result1 = yield* process(option1, args, CliConfig.defaultConfig)\n      const result2 = yield* process(option2, args, CliConfig.defaultConfig)\n      expect(result1).toEqual([[], { firstName: \"John\", lastName: \"Doe\" }])\n      expect(result2).toEqual([[], [\"John\", \"Doe\"]])\n    }).pipe(runEffect))\n\n  it(\"validate provides a suggestion if a provided option is close to a specified option\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--firstme\", \"Alice\")\n      const result = yield* Effect.flip(process(firstName, args, CliConfig.defaultConfig))\n      expect(result).toEqual(ValidationError.correctedFlag(HelpDoc.p(\n        \"The flag '--firstme' is not recognized. Did you mean '--firstName'?\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"validate provides a suggestion if a provided option with a default is close to a specified option\", () =>\n    Effect.gen(function*() {\n      const option = firstName.pipe(Options.withDefault(\"Jack\"))\n      const args = Array.make(\"--firstme\", \"Alice\")\n      const result = yield* Effect.flip(process(option, args, CliConfig.defaultConfig))\n      expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"The flag '--firstme' is not recognized. Did you mean '--firstName'?\"\n      )))\n    }))\n\n  it(\"orElse - two options\", () =>\n    Effect.gen(function*() {\n      const option = Options.text(\"string\").pipe(\n        Options.map(Either.left),\n        Options.orElse(\n          Options.integer(\"integer\").pipe(\n            Options.map(Either.right)\n          )\n        )\n      )\n      const args1 = Array.make(\"--integer\", \"2\")\n      const args2 = Array.make(\"--string\", \"two\")\n      const result1 = yield* process(option, args1, CliConfig.defaultConfig)\n      const result2 = yield* process(option, args2, CliConfig.defaultConfig)\n      expect(result1).toEqual([[], Either.right(2)])\n      expect(result2).toEqual([[], Either.left(\"two\")])\n    }).pipe(runEffect))\n\n  it(\"orElse - option collision\", () =>\n    Effect.gen(function*() {\n      const option = Options.orElse(Options.text(\"string\"), Options.integer(\"integer\"))\n      const args = Array.make(\"--integer\", \"2\", \"--string\", \"two\")\n      const result = yield* Effect.flip(process(option, args, CliConfig.defaultConfig))\n      expect(result).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"Collision between two options detected - \" +\n          \"you can only specify one of either: ['--string', '--integer']\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"orElse - no options provided\", () =>\n    Effect.gen(function*() {\n      const option = Options.orElse(Options.text(\"string\"), Options.integer(\"integer\"))\n      const result = yield* Effect.flip(process(option, [], CliConfig.defaultConfig))\n      const error = ValidationError.missingValue(HelpDoc.sequence(\n        HelpDoc.p(\"Expected to find option: '--string'\"),\n        HelpDoc.p(\"Expected to find option: '--integer'\")\n      ))\n      expect(result).toEqual(error)\n    }).pipe(runEffect))\n\n  it(\"orElse - invalid option provided with a default\", () =>\n    Effect.gen(function*() {\n      const option = Options.integer(\"min\").pipe(\n        Options.orElse(Options.integer(\"max\")),\n        Options.withDefault(0)\n      )\n      const args = Array.make(\"--min\", \"abc\")\n      const result = yield* Effect.flip(process(option, args, CliConfig.defaultConfig))\n      const error = ValidationError.invalidValue(HelpDoc.sequence(\n        HelpDoc.p(\"'abc' is not a integer\"),\n        HelpDoc.p(\"Expected to find option: '--max'\")\n      ))\n      expect(result).toEqual(error)\n    }).pipe(runEffect))\n\n  it(\"keyValueMap - validates a missing option\", () =>\n    Effect.gen(function*() {\n      const result = yield* Effect.flip(process(defs, [], CliConfig.defaultConfig))\n      expect(result).toEqual(ValidationError.missingValue(HelpDoc.p(\n        \"Expected to find option: '--defs'\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"keyValueMap - validates repeated values\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"-d\", \"key1=v1\", \"-d\", \"key2=v2\", \"--verbose\")\n      const result = yield* process(defs, args, CliConfig.defaultConfig)\n      expect(result).toEqual([[\"--verbose\"], HashMap.make([\"key1\", \"v1\"], [\"key2\", \"v2\"])])\n    }).pipe(runEffect))\n\n  it(\"keyValueMap - validates different key/values\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"--defs\", \"key1=v1\", \"key2=v2\", \"--verbose\")\n      const result = yield* process(defs, args, CliConfig.defaultConfig)\n      expect(result).toEqual([[\"--verbose\"], HashMap.make([\"key1\", \"v1\"], [\"key2\", \"v2\"])])\n    }).pipe(runEffect))\n\n  it(\"keyValueMap - validates different key/values with alias\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"-d\", \"key1=v1\", \"key2=v2\", \"--verbose\")\n      const result = yield* process(defs, args, CliConfig.defaultConfig)\n      expect(result).toEqual([[\"--verbose\"], HashMap.make([\"key1\", \"v1\"], [\"key2\", \"v2\"])])\n    }).pipe(runEffect))\n\n  it(\"keyValueMap - validates key/values with equals in alias value\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"-d\", \"key1=v1\", \"key2=v2=vv\", \"--verbose\")\n      const result = yield* process(defs, args, CliConfig.defaultConfig)\n      expect(result).toEqual([[\"--verbose\"], HashMap.make([\"key1\", \"v1\"], [\"key2\", \"v2=vv\"])])\n    }).pipe(runEffect))\n\n  it(\"keyValueMap - validates key/values with equals in aliased longer value\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\"-d\", \"key1=v1\", \"key2=v2=1+1\", \"--verbose\")\n      const result = yield* process(defs, args, CliConfig.defaultConfig)\n      expect(result).toEqual([[\"--verbose\"], HashMap.make([\"key1\", \"v1\"], [\"key2\", \"v2=1+1\"])])\n    }).pipe(runEffect))\n\n  it(\"keyValueMap - validate should keep non-key-value parameters that follow the key-value pairs (each preceded by alias -d)\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\n        \"-d\",\n        \"key1=val1\",\n        \"-d\",\n        \"key2=val2\",\n        \"-d\",\n        \"key3=val3\",\n        \"arg1\",\n        \"arg2\",\n        \"--verbose\"\n      )\n      const result = yield* process(defs, args, CliConfig.defaultConfig)\n      expect(result).toEqual([\n        [\"arg1\", \"arg2\", \"--verbose\"],\n        HashMap.make([\"key1\", \"val1\"], [\"key2\", \"val2\"], [\"key3\", \"val3\"])\n      ])\n    }).pipe(runEffect))\n\n  it(\"keyValueMap - validate should keep non-key-value parameters that follow the key-value pairs (only the first key/value pair is preceded by alias)\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\n        \"-d\",\n        \"key1=val1\",\n        \"key2=val2\",\n        \"key3=val3\",\n        \"arg1\",\n        \"arg2\",\n        \"--verbose\"\n      )\n      const result = yield* process(defs, args, CliConfig.defaultConfig)\n      expect(result).toEqual([\n        [\"arg1\", \"arg2\", \"--verbose\"],\n        HashMap.make([\"key1\", \"val1\"], [\"key2\", \"val2\"], [\"key3\", \"val3\"])\n      ])\n    }).pipe(runEffect))\n\n  it(\"keyValueMap - validate should return an error for invalid key/value pairs\", () =>\n    Effect.gen(function*() {\n      const args = Array.make(\n        \"-d\",\n        \"key1=val1\",\n        \"key2=val2\",\n        \"--defs\",\n        \"key3=val3\",\n        \"key4=\",\n        \"arg1\",\n        \"arg2\",\n        \"--verbose\"\n      )\n      const result = yield* process(defs, args, CliConfig.defaultConfig)\n      expect(result).toEqual([\n        [\"key4=\", \"arg1\", \"arg2\", \"--verbose\"],\n        HashMap.make([\"key1\", \"val1\"], [\"key2\", \"val2\"], [\"key3\", \"val3\"])\n      ])\n    }).pipe(runEffect))\n\n  it(\"repeated\", () =>\n    Effect.gen(function*() {\n      const option = Options.integer(\"foo\").pipe(Options.repeated)\n      const args2 = [\"--foo\", \"1\", \"--foo\", \"2\", \"--foo\", \"3\"]\n      const args3 = [\"--foo\", \"v2\"]\n      const args4 = [\"--foo\", \"1\", \"--foo\", \"v2\", \"--foo\", \"3\"]\n      const args5 = [\"--foo\", \"1\", \"-d\", \"--foo\", \"2\"]\n      const args6 = [\"--foo\", \"1\", \"-f\", \"firstName\", \"--foo\", \"2\"]\n      const result1 = yield* process(option, [], CliConfig.defaultConfig)\n      const result2 = yield* process(option, args2, CliConfig.defaultConfig)\n      const result3 = yield* Effect.flip(process(option, args3, CliConfig.defaultConfig))\n      const result4 = yield* Effect.flip(process(option, args4, CliConfig.defaultConfig))\n      const result5 = yield* process(option, args5, CliConfig.defaultConfig)\n      const result6 = yield* process(option, args6, CliConfig.defaultConfig)\n      expect(result1).toEqual([Array.empty(), []])\n      expect(result2).toEqual([Array.empty(), [1, 2, 3]])\n      expect(result3).toEqual(ValidationError.invalidValue(HelpDoc.p(\"'v2' is not a integer\")))\n      expect(result4).toEqual(ValidationError.invalidValue(HelpDoc.p(\"'v2' is not a integer\")))\n      expect(result5).toEqual([[\"-d\"], [1, 2]])\n      expect(result6).toEqual([[\"-f\", \"firstName\"], [1, 2]])\n    }).pipe(runEffect))\n\n  it(\"atLeast\", () =>\n    Effect.gen(function*() {\n      const option = Options.integer(\"foo\").pipe(Options.atLeast(2))\n      const args1 = [\"--foo\", \"1\", \"--foo\", \"2\"]\n      const args2 = [\"--foo\", \"1\"]\n      const result1 = yield* process(option, args1, CliConfig.defaultConfig)\n      const result2 = yield* Effect.flip(process(option, args2, CliConfig.defaultConfig))\n      expect(result1).toEqual([Array.empty(), [1, 2]])\n      expect(result2).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"Expected at least 2 value(s) for option: '--foo'\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"atMost\", () =>\n    Effect.gen(function*() {\n      const option = Options.integer(\"foo\").pipe(Options.atMost(2))\n      const args1 = [\"--foo\", \"1\", \"--foo\", \"2\"]\n      const args2 = [\"--foo\", \"1\", \"--foo\", \"2\", \"--foo\", \"3\"]\n      const result1 = yield* process(option, args1, CliConfig.defaultConfig)\n      const result2 = yield* Effect.flip(process(option, args2, CliConfig.defaultConfig))\n      expect(result1).toEqual([Array.empty(), [1, 2]])\n      expect(result2).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"Expected at most 2 value(s) for option: '--foo'\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"between\", () =>\n    Effect.gen(function*() {\n      const option = Options.integer(\"foo\").pipe(Options.between(2, 3))\n      const args1 = [\"--foo\", \"1\"]\n      const args2 = [\"--foo\", \"1\", \"--foo\", \"2\"]\n      const args3 = [\"--foo\", \"1\", \"--foo\", \"2\", \"--foo\", \"3\"]\n      const args4 = [\"--foo\", \"1\", \"--foo\", \"2\", \"--foo\", \"3\", \"--foo\", \"4\"]\n      const result1 = yield* Effect.flip(process(option, args1, CliConfig.defaultConfig))\n      const result2 = yield* process(option, args2, CliConfig.defaultConfig)\n      const result3 = yield* process(option, args3, CliConfig.defaultConfig)\n      const result4 = yield* Effect.flip(process(option, args4, CliConfig.defaultConfig))\n      expect(result1).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"Expected at least 2 value(s) for option: '--foo'\"\n      )))\n      expect(result2).toEqual([Array.empty(), [1, 2]])\n      expect(result3).toEqual([Array.empty(), [1, 2, 3]])\n      expect(result4).toEqual(ValidationError.invalidValue(HelpDoc.p(\n        \"Expected at most 3 value(s) for option: '--foo'\"\n      )))\n    }).pipe(runEffect))\n\n  it(\"validates with a Schema\", () =>\n    Effect.gen(function*() {\n      const result = yield* process(balance, [\"--balance\", \"100.50\"], CliConfig.defaultConfig)\n      assert.deepStrictEqual(result, [[], BigDecimal.unsafeFromString(\"100.50\").pipe(BigDecimal.normalize)])\n    }).pipe(runEffect))\n\n  it(\"failure with a Schema\", () =>\n    Effect.gen(function*() {\n      const result = yield* process(balance, [\"--balance\", \"abc\"], CliConfig.defaultConfig).pipe(Effect.flip)\n      assert.deepStrictEqual(\n        result,\n        ValidationError.invalidValue(HelpDoc.p(\n          \"BigDecimal\\n\" +\n            \"└─ Transformation process failure\\n\" +\n            \"   └─ Unable to decode \\\"abc\\\" into a BigDecimal\"\n        ))\n      )\n    }).pipe(runEffect))\n\n  it(\"fileContent\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.json\")\n      const result = yield* process(Options.fileContent(\"config\"), [\"--config\", filePath], CliConfig.defaultConfig)\n      const content = yield* fs.readFile(filePath)\n      assert.deepStrictEqual(result, [[], [filePath, content]])\n    }).pipe(runEffect))\n\n  it(\"fileText\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.json\")\n      const result = yield* process(Options.fileText(\"config\"), [\"--config\", filePath], CliConfig.defaultConfig)\n      const content = yield* pipe(fs.readFileString(filePath))\n      assert.deepStrictEqual(result, [[], [filePath, content]])\n    }).pipe(runEffect))\n\n  it(\"fileParse\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.json\")\n      const result = yield* process(Options.fileParse(\"config\"), [\"--config\", filePath], CliConfig.defaultConfig)\n      const content = yield* pipe(fs.readFileString(filePath), Effect.map(JSON.parse))\n      assert.deepStrictEqual(result, [[], content])\n    }).pipe(runEffect))\n\n  it(\"fileSchema\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.json\")\n      const result = yield* process(\n        Options.fileSchema(\n          \"config\",\n          Schema.Struct({\n            foo: Schema.Boolean,\n            bar: Schema.Literal(\"baz\")\n          })\n        ),\n        [\"--config\", filePath],\n        CliConfig.defaultConfig\n      )\n      const content = yield* pipe(fs.readFileString(filePath), Effect.map(JSON.parse))\n      assert.deepStrictEqual(result, [[], content])\n    }).pipe(runEffect))\n\n  it(\"fileSchema yaml\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.yaml\")\n      const jsonPath = path.join(__dirname, \"fixtures/config.json\")\n      const result = yield* process(\n        Options.fileSchema(\n          \"config\",\n          Schema.Struct({\n            foo: Schema.Boolean,\n            bar: Schema.Literal(\"baz\")\n          })\n        ),\n        [\"--config\", filePath],\n        CliConfig.defaultConfig\n      )\n      const content = yield* pipe(fs.readFileString(jsonPath), Effect.map(JSON.parse))\n      assert.deepStrictEqual(result, [[], content])\n    }).pipe(runEffect))\n\n  it(\"fileSchema ini\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.ini\")\n      const jsonPath = path.join(__dirname, \"fixtures/config.json\")\n      const result = yield* process(\n        Options.fileSchema(\n          \"config\",\n          Schema.Struct({\n            foo: Schema.Boolean,\n            bar: Schema.Literal(\"baz\")\n          })\n        ),\n        [\"--config\", filePath],\n        CliConfig.defaultConfig\n      )\n      const content = yield* pipe(fs.readFileString(jsonPath), Effect.map(JSON.parse))\n      assert.deepStrictEqual(result, [[], content])\n    }).pipe(runEffect))\n\n  it(\"fileSchema toml\", () =>\n    Effect.gen(function*() {\n      const fs = yield* FileSystem.FileSystem\n      const path = yield* Path.Path\n      const filePath = path.join(__dirname, \"fixtures/config.toml\")\n      const jsonPath = path.join(__dirname, \"fixtures/config.json\")\n      const result = yield* process(\n        Options.fileSchema(\n          \"config\",\n          Schema.Struct({\n            foo: Schema.Boolean,\n            bar: Schema.Literal(\"baz\")\n          })\n        ),\n        [\"--config\", filePath],\n        CliConfig.defaultConfig\n      )\n      const content = yield* pipe(fs.readFileString(jsonPath), Effect.map(JSON.parse))\n      assert.deepStrictEqual(result, [[], content])\n    }).pipe(runEffect))\n\n  it(\"displays default value in help when default wrapped in Option.Some (primitive)\", () =>\n    Effect.gen(function*() {\n      const option = Options.withDefault(Options.integer(\"value\"), Option.some(123))\n      const helpDoc = Options.getHelp(option)\n      yield* Effect.promise(() =>\n        expect(helpDoc).toMatchFileSnapshot(\"./snapshots/help-output/options-default-primitive\")\n      )\n    }).pipe(runEffect))\n\n  it(\"displays default value in help when default wrapped in Option.Some (object)\", () =>\n    Effect.gen(function*() {\n      const defaultObject = { key: \"value\", number: 456 }\n      const option = Options.withDefault(Options.text(\"config\"), Option.some(defaultObject))\n      const helpDoc = Options.getHelp(option)\n      yield* Effect.promise(() => expect(helpDoc).toMatchFileSnapshot(\"./snapshots/help-output/options-default-object\"))\n    }).pipe(runEffect))\n\n  it(\"displays no default value in help when default is not Option.Some\", () =>\n    Effect.gen(function*() {\n      const option = Options.withDefault(Options.text(\"name\"), Option.none())\n      const helpDoc = Options.getHelp(option)\n      yield* Effect.promise(() => expect(helpDoc).toMatchFileSnapshot(\"./snapshots/help-output/options-no-default\"))\n    }).pipe(runEffect))\n\n  describe(\"options after positional arguments\", () => {\n    it(\"parses a text option that appears after positional args\", () =>\n      Effect.gen(function*() {\n        // Simulating: cmd positional --firstName John\n        const args = Array.make(\"positional\", \"--firstName\", \"John\")\n        const result = yield* process(firstName, args, CliConfig.defaultConfig)\n        // The \"positional\" should be in the leftover, firstName should be parsed\n        expect(result).toEqual([[\"positional\"], \"John\"])\n      }).pipe(runEffect))\n\n    it(\"parses a text option with alias that appears after positional args\", () =>\n      Effect.gen(function*() {\n        // Simulating: cmd positional -f John\n        const args = Array.make(\"positional\", \"-f\", \"John\")\n        const result = yield* process(firstName, args, CliConfig.defaultConfig)\n        expect(result).toEqual([[\"positional\"], \"John\"])\n      }).pipe(runEffect))\n\n    it(\"parses a boolean option that appears after positional args\", () =>\n      Effect.gen(function*() {\n        // Simulating: cmd positional --verbose\n        const args = Array.make(\"positional\", \"--verbose\")\n        const result = yield* process(verbose, args, CliConfig.defaultConfig)\n        expect(result).toEqual([[\"positional\"], true])\n      }).pipe(runEffect))\n\n    it(\"parses multiple options when some appear after positional args\", () =>\n      Effect.gen(function*() {\n        const options = Options.all([firstName, lastName])\n        // Simulating: cmd --firstName John positional --lastName Doe\n        const args = Array.make(\"--firstName\", \"John\", \"positional\", \"--lastName\", \"Doe\")\n        const result = yield* process(options, args, CliConfig.defaultConfig)\n        expect(result).toEqual([[\"positional\"], [\"John\", \"Doe\"]])\n      }).pipe(runEffect))\n\n    it(\"parses options interspersed with multiple positional args\", () =>\n      Effect.gen(function*() {\n        const options = Options.all([firstName, verbose])\n        // Simulating: cmd pos1 --firstName John pos2 --verbose pos3\n        const args = Array.make(\"pos1\", \"--firstName\", \"John\", \"pos2\", \"--verbose\", \"pos3\")\n        const result = yield* process(options, args, CliConfig.defaultConfig)\n        expect(result).toEqual([[\"pos1\", \"pos2\", \"pos3\"], [\"John\", true]])\n      }).pipe(runEffect))\n\n    it(\"parses text option with = syntax after positional args\", () =>\n      Effect.gen(function*() {\n        // Simulating: cmd positional --firstName=John\n        const args = Array.make(\"positional\", \"--firstName=John\")\n        const result = yield* process(firstName, args, CliConfig.defaultConfig)\n        expect(result).toEqual([[\"positional\"], \"John\"])\n      }).pipe(runEffect))\n\n    it(\"parses boolean option with explicit true value after positional args\", () =>\n      Effect.gen(function*() {\n        // Simulating: cmd positional --verbose true\n        const args = Array.make(\"positional\", \"--verbose\", \"true\")\n        const result = yield* process(verbose, args, CliConfig.defaultConfig)\n        expect(result).toEqual([[\"positional\"], true])\n      }).pipe(runEffect))\n\n    it(\"parses boolean option with explicit false value after positional args\", () =>\n      Effect.gen(function*() {\n        // Simulating: cmd positional --verbose false\n        const args = Array.make(\"positional\", \"--verbose\", \"false\")\n        const result = yield* process(verbose, args, CliConfig.defaultConfig)\n        expect(result).toEqual([[\"positional\"], false])\n      }).pipe(runEffect))\n\n    it(\"parses keyValueMap option that appears after positional args\", () =>\n      Effect.gen(function*() {\n        // Simulating: cmd positional --defs key=value\n        const args = Array.make(\"positional\", \"--defs\", \"key=value\")\n        const result = yield* process(defs, args, CliConfig.defaultConfig)\n        expect(result).toEqual([[\"positional\"], HashMap.make([\"key\", \"value\"])])\n      }).pipe(runEffect))\n\n    it(\"parses keyValueMap option with multiple values after positional args\", () =>\n      Effect.gen(function*() {\n        // Simulating: cmd positional --defs key1=value1 key2=value2\n        const args = Array.make(\"positional\", \"-d\", \"key1=value1\", \"key2=value2\")\n        const result = yield* process(defs, args, CliConfig.defaultConfig)\n        expect(result).toEqual([[\"positional\"], HashMap.make([\"key1\", \"value1\"], [\"key2\", \"value2\"])])\n      }).pipe(runEffect))\n  })\n})\n"
  },
  {
    "path": "packages/cli/test/Primitive.test.ts",
    "content": "import * as CliConfig from \"@effect/cli/CliConfig\"\nimport * as Primitive from \"@effect/cli/Primitive\"\nimport type { FileSystem } from \"@effect/platform\"\nimport { NodeFileSystem } from \"@effect/platform-node\"\nimport { describe, expect, it } from \"@effect/vitest\"\nimport { Array, Effect, Equal, Function, Option } from \"effect\"\nimport * as fc from \"effect/FastCheck\"\n\nconst runEffect = <E, A>(self: Effect.Effect<A, E, FileSystem.FileSystem>): Promise<A> =>\n  Effect.provide(self, NodeFileSystem.layer).pipe(Effect.runPromise)\n\ndescribe(\"Primitive\", () => {\n  describe(\"Bool\", () => {\n    it(\"validates that truthy text representations of a boolean return true\", () =>\n      fc.assert(fc.asyncProperty(trueValuesArb, (str) =>\n        Effect.gen(function*() {\n          const bool = Primitive.boolean(Option.none())\n          const result = yield* Primitive.validate(\n            bool,\n            Option.some(str),\n            CliConfig.defaultConfig\n          )\n          expect(result).toBe(true)\n        }).pipe(runEffect))))\n\n    it(\"validates that falsy text representations of a boolean return false\", () =>\n      fc.assert(fc.asyncProperty(falseValuesArb, (str) =>\n        Effect.gen(function*() {\n          const bool = Primitive.boolean(Option.none())\n          const result = yield* Primitive.validate(\n            bool,\n            Option.some(str),\n            CliConfig.defaultConfig\n          )\n          expect(result).toBe(false)\n        }).pipe(runEffect))))\n\n    it(\"validates that invalid boolean representations are rejected\", () =>\n      Effect.gen(function*() {\n        const bool = Primitive.boolean(Option.none())\n        const result = yield* Effect.flip(Primitive.validate(bool, Option.some(\"bad\"), CliConfig.defaultConfig))\n        expect(result).toBe(\"Unable to recognize 'bad' as a valid boolean\")\n      }).pipe(runEffect))\n\n    it(\"validates that the default value will be used if a value is not provided\", () =>\n      fc.assert(fc.asyncProperty(fc.boolean(), (value) =>\n        Effect.gen(function*() {\n          const bool = Primitive.boolean(Option.some(value))\n          const result = yield* Primitive.validate(bool, Option.none(), CliConfig.defaultConfig)\n          expect(result).toBe(value)\n        }).pipe(runEffect))))\n  })\n\n  describe(\"Choice\", () => {\n    it(\"validates a choice that is one of the alternatives\", () =>\n      fc.assert(\n        fc.asyncProperty(pairsArb, ([[selectedName, selectedValue], pairs]) =>\n          Effect.gen(function*() {\n            const alternatives = Function.unsafeCoerce<\n              ReadonlyArray<[string, number]>,\n              Array.NonEmptyReadonlyArray<[string, number]>\n            >(pairs)\n            const choice = Primitive.choice(alternatives)\n            const result = yield* Primitive.validate(\n              choice,\n              Option.some(selectedName),\n              CliConfig.defaultConfig\n            )\n            expect(result).toEqual(selectedValue)\n          }).pipe(runEffect))\n      ))\n\n    it(\"does not validate a choice that is not one of the alternatives\", () =>\n      fc.assert(fc.asyncProperty(pairsArb, ([tuple, pairs]) =>\n        Effect.gen(function*() {\n          const selectedName = tuple[0]\n          const alternatives = Function.unsafeCoerce<\n            ReadonlyArray<[string, number]>,\n            Array.NonEmptyReadonlyArray<[string, number]>\n          >(Array.filter(pairs, (pair) => !Equal.equals(tuple, pair)))\n          const choice = Primitive.choice(alternatives)\n          const result = yield* Effect.flip(Primitive.validate(\n            choice,\n            Option.some(selectedName),\n            CliConfig.defaultConfig\n          ))\n          expect(result).toMatch(/^Expected one of the following cases:\\s.*/)\n        }).pipe(runEffect))))\n  })\n\n  simplePrimitiveTestSuite(Primitive.date, fc.date({ noInvalidDate: true }), \"Date\")\n\n  simplePrimitiveTestSuite(\n    Primitive.float,\n    fc.float({ noNaN: true }).filter((n) => n !== 0),\n    \"Float\"\n  )\n\n  simplePrimitiveTestSuite(Primitive.integer, fc.integer(), \"Integer\")\n\n  describe(\"Text\", () => {\n    it(\"validates all user-defined text\", () =>\n      fc.assert(fc.asyncProperty(fc.string(), (str) =>\n        Effect.gen(function*() {\n          const result = yield* Primitive.validate(\n            Primitive.text,\n            Option.some(str),\n            CliConfig.defaultConfig\n          )\n          expect(result).toEqual(str)\n        }).pipe(runEffect))))\n  })\n})\n\nconst simplePrimitiveTestSuite = <A>(\n  primitive: Primitive.Primitive<A>,\n  arb: fc.Arbitrary<A>,\n  primitiveTypeName: string\n) => {\n  describe(`${primitiveTypeName}`, () => {\n    it(`validates that valid values are accepted`, () =>\n      fc.assert(fc.asyncProperty(arb, (value) =>\n        Effect.gen(function*() {\n          const str = value instanceof Date ? value.toISOString() : `${value}`\n          const result = yield* Primitive.validate(primitive, Option.some(str), CliConfig.defaultConfig)\n          expect(result).toEqual(value)\n        }).pipe(runEffect))))\n\n    it(`validates that invalid values are rejected`, () =>\n      Effect.gen(function*() {\n        const result = yield* Effect.flip(Primitive.validate(primitive, Option.some(\"bad\"), CliConfig.defaultConfig))\n        expect(result).toBe(`'bad' is not a ${Primitive.getTypeName(primitive)}`)\n      }).pipe(runEffect))\n  })\n}\n\nconst randomizeCharacterCases = (str: string): string => {\n  let result = \"\"\n  for (let i = 0; i < str.length; i++) {\n    const char = str[i]\n    result += Math.random() < 0.5 ? char.toLowerCase() : char.toUpperCase()\n  }\n  return result\n}\n\nconst trueValuesArb = fc.constantFrom(\"true\", \"1\", \"y\", \"yes\", \"on\").map(randomizeCharacterCases)\nconst falseValuesArb = fc.constantFrom(\"false\", \"0\", \"n\", \"no\", \"off\").map(randomizeCharacterCases)\n\nconst pairsArb = fc.array(fc.tuple(fc.string(), fc.float()), { minLength: 2, maxLength: 100 })\n  .map((pairs) => Array.dedupeWith(pairs, ([str1], [str2]) => str1 === str2))\n  .chain((pairs) => fc.tuple(fc.constantFrom(...pairs), fc.constant(pairs)))\n"
  },
  {
    "path": "packages/cli/test/Prompt.test.ts",
    "content": "import type * as CliApp from \"@effect/cli/CliApp\"\nimport * as Prompt from \"@effect/cli/Prompt\"\nimport { NodeFileSystem, NodePath } from \"@effect/platform-node\"\nimport * as Ansi from \"@effect/printer-ansi/Ansi\"\nimport * as Doc from \"@effect/printer-ansi/AnsiDoc\"\nimport { describe, expect, it } from \"@effect/vitest\"\nimport * as Console from \"effect/Console\"\nimport * as Effect from \"effect/Effect\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as Layer from \"effect/Layer\"\nimport * as Redacted from \"effect/Redacted\"\nimport * as MockConsole from \"./services/MockConsole.js\"\nimport * as MockTerminal from \"./services/MockTerminal.js\"\n\nconst MainLive = Effect.gen(function*() {\n  const console = yield* MockConsole.make\n  return Layer.mergeAll(\n    Console.setConsole(console),\n    NodeFileSystem.layer,\n    MockTerminal.layer,\n    NodePath.layer\n  )\n}).pipe(Layer.unwrapEffect)\n\nconst runEffect = <E, A>(\n  self: Effect.Effect<A, E, CliApp.CliApp.Environment>\n): Promise<A> => Effect.provide(self, MainLive).pipe(Effect.runPromise)\n\ndescribe(\"Prompt\", () => {\n  describe(\"text\", () => {\n    it(\"should use the prompt value when no default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.text({\n          message: \"This does not have a default\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toBe(\"\")\n      }).pipe(runEffect))\n\n    it(\"should use the default value when the default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.text({\n          message: \"This should have a default\",\n          default: \"default-value\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toBe(\"default-value\")\n      }).pipe(runEffect))\n\n    it(\"should render the default value when the default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.text({\n          message: \"Test Prompt\",\n          default: \"default-value\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n\n        yield* MockTerminal.inputKey(\"enter\")\n        yield* Fiber.join(fiber)\n\n        const lines = yield* MockConsole.getLines()\n\n        const unsubmittedValue = Doc.annotate(Doc.text(\"default-value\"), Ansi.blackBright).pipe(Doc.render({\n          style: \"pretty\"\n        }))\n\n        const submittedValue = Doc.annotate(Doc.text(\"default-value\"), Ansi.white).pipe(Doc.render({\n          style: \"pretty\"\n        }))\n\n        expect(lines).toEqual(\n          expect.arrayContaining([\n            expect.stringContaining(\n              unsubmittedValue\n            ),\n            expect.stringContaining(\n              submittedValue\n            )\n          ])\n        )\n\n        expect(lines.findIndex((line) => line.includes(unsubmittedValue))).toBeLessThan(\n          lines.findIndex((line) => line.includes(submittedValue))\n        )\n      }).pipe(runEffect))\n\n    it(\"should accept the default value when the tab is pressed\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.text({\n          message: \"Test Prompt\",\n          default: \"default-value\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n\n        yield* MockTerminal.inputKey(\"tab\")\n        yield* MockTerminal.inputKey(\"enter\")\n        yield* Fiber.join(fiber)\n\n        const lines = yield* MockConsole.getLines()\n\n        const unsubmittedValue = Doc.annotate(Doc.text(\"default-value\"), Ansi.blackBright).pipe(Doc.render({\n          style: \"pretty\"\n        }))\n\n        const enteredValue = Doc.annotate(Doc.text(\"default-value\"), Ansi.combine(Ansi.underlined, Ansi.cyanBright))\n          .pipe(Doc.render({\n            style: \"pretty\"\n          }))\n\n        expect(lines).toEqual(\n          expect.arrayContaining([\n            expect.stringContaining(\n              unsubmittedValue\n            ),\n            expect.stringContaining(\n              enteredValue\n            )\n          ])\n        )\n\n        expect(lines.findIndex((line) => line.includes(unsubmittedValue))).toBeLessThan(\n          lines.findIndex((line) => line.includes(enteredValue))\n        )\n      }).pipe(runEffect))\n  })\n\n  describe(\"hidden\", () => {\n    it(\"should use the prompt value when no default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.hidden({\n          message: \"This does not have a default\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual(Redacted.make(\"\"))\n      }).pipe(runEffect))\n\n    it(\"should use the default value when the default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.hidden({\n          message: \"This should have a default\",\n          default: \"default-value\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual(Redacted.make(\"default-value\"))\n      }).pipe(runEffect))\n\n    it(\"should not render the default value when the default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.hidden({\n          message: \"Test Prompt\",\n          default: \"default-value\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n\n        yield* MockTerminal.inputKey(\"enter\")\n        yield* Fiber.join(fiber)\n\n        const lines = yield* MockConsole.getLines({ stripAnsi: true })\n\n        expect(lines).not.toEqual(\n          expect.arrayContaining([\n            expect.stringContaining(\n              \"default-value\"\n            )\n          ])\n        )\n      }).pipe(runEffect))\n  })\n\n  describe(\"list\", () => {\n    it(\"should use the prompt value when no default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.list({\n          message: \"This does not have a default\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual([\"\"])\n      }).pipe(runEffect))\n\n    it(\"should use the default value when the default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.list({\n          message: \"This should have a default\",\n          default: \"default-value\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual([\"default-value\"])\n      }).pipe(runEffect))\n\n    it(\"should render the default value when the default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.list({\n          message: \"Test Prompt\",\n          default: \"default-value\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n\n        yield* MockTerminal.inputKey(\"enter\")\n        yield* Fiber.join(fiber)\n\n        const lines = yield* MockConsole.getLines()\n\n        const unsubmittedValue = Doc.annotate(Doc.text(\"default-value\"), Ansi.blackBright).pipe(Doc.render({\n          style: \"pretty\"\n        }))\n\n        const submittedValue = Doc.annotate(Doc.text(\"default-value\"), Ansi.white).pipe(Doc.render({\n          style: \"pretty\"\n        }))\n\n        expect(lines).toEqual(\n          expect.arrayContaining([\n            expect.stringContaining(\n              unsubmittedValue\n            ),\n            expect.stringContaining(\n              submittedValue\n            )\n          ])\n        )\n\n        expect(lines.findIndex((line) => line.includes(unsubmittedValue))).toBeLessThan(\n          lines.findIndex((line) => line.includes(submittedValue))\n        )\n      }).pipe(runEffect))\n  })\n\n  describe(\"password\", () => {\n    it(\"should use the prompt value when no default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.password({\n          message: \"This does not have a default\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual(Redacted.make(\"\"))\n      }).pipe(runEffect))\n\n    it(\"should use the default value when the default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.password({\n          message: \"This should have a default\",\n          default: \"default-value\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual(Redacted.make(\"default-value\"))\n      }).pipe(runEffect))\n\n    it(\"should render the redacted default value when the default is provided\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.password({\n          message: \"Test Prompt\",\n          default: \"default-value\"\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n\n        yield* MockTerminal.inputKey(\"enter\")\n        yield* Fiber.join(fiber)\n\n        const lines = yield* MockConsole.getLines()\n\n        const redactedValue = \"*\".repeat(\"default-value\".length)\n        const unsubmittedValue = Doc.annotate(Doc.text(redactedValue), Ansi.blackBright).pipe(Doc.render({\n          style: \"pretty\"\n        }))\n\n        const submittedValue = Doc.annotate(Doc.text(redactedValue), Ansi.white).pipe(Doc.render({\n          style: \"pretty\"\n        }))\n\n        expect(lines).toEqual(\n          expect.arrayContaining([\n            expect.stringContaining(\n              unsubmittedValue\n            ),\n            expect.stringContaining(\n              submittedValue\n            )\n          ])\n        )\n\n        expect(lines.findIndex((line) => line.includes(unsubmittedValue))).toBeLessThan(\n          lines.findIndex((line) => line.includes(submittedValue))\n        )\n      }).pipe(runEffect))\n  })\n\n  describe(\"Prompt.select\", () => {\n    it(\"should return the selected value when an option is chosen\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.select({\n          message: \"Select an option\",\n          choices: [\n            { title: \"Option 1\", value: 1 },\n            { title: \"Option 2\", value: 2 },\n            { title: \"Option 3\", value: 3 }\n          ]\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"down\")\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual(2)\n      }).pipe(runEffect))\n\n    it(\"should honor a single default selected choice\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.select({\n          message: \"Select an option\",\n          choices: [\n            { title: \"Option 1\", value: 1 },\n            { title: \"Option 2\", value: 2, selected: true },\n            { title: \"Option 3\", value: 3 }\n          ]\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        // Immediately submit without navigation\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual(2)\n      }).pipe(runEffect))\n\n    it(\"should throw if multiple default selected choices are provided\", () =>\n      Effect.gen(function*() {\n        expect(() =>\n          Prompt.select({\n            message: \"Select an option\",\n            choices: [\n              { title: \"Option 1\", value: 1, selected: true },\n              { title: \"Option 2\", value: 2, selected: true },\n              { title: \"Option 3\", value: 3 }\n            ]\n          })\n        ).toThrow()\n      }).pipe(runEffect))\n  })\n\n  describe(\"Prompt.selectMulti\", () => {\n    it(\"should return the selected values when multiple options are chosen\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.multiSelect({\n          message: \"Select multiple options\",\n          choices: [\n            { title: \"Option A\", value: \"A\" },\n            { title: \"Option B\", value: \"B\" },\n            { title: \"Option C\", value: \"C\" }\n          ]\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"down\")\n        yield* MockTerminal.inputKey(\"down\")\n        yield* MockTerminal.inputKey(\"space\")\n        yield* MockTerminal.inputKey(\"down\")\n        yield* MockTerminal.inputKey(\"space\")\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual([\"A\", \"B\"])\n      }).pipe(runEffect))\n\n    it(\"should select all options when 'Select All' is triggered\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.multiSelect({\n          message: \"Select multiple options\",\n          choices: [\n            { title: \"Option A\", value: \"A\" },\n            { title: \"Option B\", value: \"B\" },\n            { title: \"Option C\", value: \"C\" }\n          ]\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"space\") // Select All\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual([\"A\", \"B\", \"C\"])\n      }).pipe(runEffect))\n\n    it(\"should deselect all options when 'Select None' is triggered\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.multiSelect({\n          message: \"Select multiple options\",\n          choices: [\n            { title: \"Option A\", value: \"A\" },\n            { title: \"Option B\", value: \"B\" },\n            { title: \"Option C\", value: \"C\" }\n          ]\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"space\") // Select All\n        yield* MockTerminal.inputKey(\"space\") // Select None\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual([])\n      }).pipe(runEffect))\n\n    it(\"should inverse the selection when 'Inverse Selection' is triggered\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.multiSelect({\n          message: \"Select multiple options\",\n          choices: [\n            { title: \"Option A\", value: \"A\" },\n            { title: \"Option B\", value: \"B\" },\n            { title: \"Option C\", value: \"C\" }\n          ]\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        yield* MockTerminal.inputKey(\"space\")\n        yield* MockTerminal.inputKey(\"tab\")\n        yield* MockTerminal.inputKey(\"tab\")\n        yield* MockTerminal.inputKey(\"space\")\n        yield* MockTerminal.inputKey(\"up\")\n        yield* MockTerminal.inputKey(\"space\")\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual([\"A\"])\n      }).pipe(runEffect))\n\n    it(\"should preselect choices marked with selected: true\", () =>\n      Effect.gen(function*() {\n        const prompt = Prompt.multiSelect({\n          message: \"Select multiple options\",\n          choices: [\n            { title: \"Option A\", value: \"A\", selected: true },\n            { title: \"Option B\", value: \"B\", selected: true },\n            { title: \"Option C\", value: \"C\" }\n          ]\n        })\n\n        const fiber = yield* Effect.fork(prompt)\n        // Immediately submit without any navigation or toggling\n        yield* MockTerminal.inputKey(\"enter\")\n        const result = yield* Fiber.join(fiber)\n\n        expect(result).toEqual([\"A\", \"B\"])\n      }).pipe(runEffect))\n  })\n})\n"
  },
  {
    "path": "packages/cli/test/Wizard.test.ts",
    "content": "import type * as CliApp from \"@effect/cli/CliApp\"\nimport * as Command from \"@effect/cli/Command\"\nimport * as Options from \"@effect/cli/Options\"\nimport { NodeFileSystem, NodePath } from \"@effect/platform-node\"\nimport { describe, expect, it } from \"@effect/vitest\"\nimport { Array, Effect } from \"effect\"\nimport * as Console from \"effect/Console\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as Layer from \"effect/Layer\"\nimport * as MockConsole from \"./services/MockConsole.js\"\nimport * as MockTerminal from \"./services/MockTerminal.js\"\n\nconst MainLive = Effect.gen(function*() {\n  const console = yield* MockConsole.make\n  return Layer.mergeAll(\n    Console.setConsole(console),\n    NodeFileSystem.layer,\n    MockTerminal.layer,\n    NodePath.layer\n  )\n}).pipe(Layer.unwrapEffect)\n\nconst runEffect = <E, A>(\n  self: Effect.Effect<A, E, CliApp.CliApp.Environment>\n): Promise<A> => Effect.provide(self, MainLive).pipe(Effect.runPromise)\n\ndescribe(\"Wizard\", () => {\n  it(\"should quit the wizard when CTRL+C is entered\", () =>\n    Effect.gen(function*() {\n      const cli = Command.make(\"foo\", { message: Options.text(\"message\") }).pipe(\n        Command.run({\n          name: \"Test\",\n          version: \"1.0.0\"\n        })\n      )\n      const args = Array.make(\"node\", \"test\", \"--wizard\")\n      const fiber = yield* Effect.fork(cli(args))\n      yield* MockTerminal.inputKey(\"c\", { ctrl: true })\n      yield* Fiber.join(fiber)\n      const lines = yield* MockConsole.getLines({ stripAnsi: true })\n      const result = Array.some(lines, (line) => line.includes(\"Quitting wizard mode...\"))\n      expect(result).toBe(true)\n    }).pipe(runEffect))\n})\n"
  },
  {
    "path": "packages/cli/test/fixtures/config-file.toml",
    "content": "foo = 123\n"
  },
  {
    "path": "packages/cli/test/fixtures/config.ini",
    "content": "foo = true\nbar = baz\n"
  },
  {
    "path": "packages/cli/test/fixtures/config.json",
    "content": "{\n  \"foo\": true,\n  \"bar\": \"baz\"\n}\n"
  },
  {
    "path": "packages/cli/test/fixtures/config.toml",
    "content": "foo = true\nbar = \"baz\"\n"
  },
  {
    "path": "packages/cli/test/fixtures/config.yaml",
    "content": "foo: true\nbar: baz\n"
  },
  {
    "path": "packages/cli/test/services/MockConsole.ts",
    "content": "import * as Array from \"effect/Array\"\nimport * as Console from \"effect/Console\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Ref from \"effect/Ref\"\n\nexport interface MockConsole extends Console.Console {\n  readonly getLines: (\n    params?: Partial<{\n      readonly stripAnsi: boolean\n    }>\n  ) => Effect.Effect<ReadonlyArray<string>>\n}\n\nexport const MockConsole = Context.GenericTag<Console.Console, MockConsole>(\n  \"effect/Console\"\n)\nconst pattern = new RegExp(\n  [\n    \"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)\",\n    \"(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PRZcf-ntqry=><~]))\"\n  ].join(\"|\"),\n  \"g\"\n)\n\nconst stripAnsi = (str: string) => str.replace(pattern, \"\")\n\nexport const make = Effect.gen(function*() {\n  const lines = yield* Ref.make(Array.empty<string>())\n\n  const getLines: MockConsole[\"getLines\"] = (params = {}) =>\n    Ref.get(lines).pipe(Effect.map((lines) =>\n      params.stripAnsi || false\n        ? Array.map(lines, stripAnsi)\n        : lines\n    ))\n\n  const log: MockConsole[\"log\"] = (...args) => Ref.update(lines, Array.appendAll(args))\n\n  return MockConsole.of({\n    [Console.TypeId]: Console.TypeId,\n    getLines,\n    log,\n    unsafe: globalThis.console,\n    assert: () => Effect.void,\n    clear: Effect.void,\n    count: () => Effect.void,\n    countReset: () => Effect.void,\n    debug: () => Effect.void,\n    dir: () => Effect.void,\n    dirxml: () => Effect.void,\n    error: () => Effect.void,\n    group: () => Effect.void,\n    groupEnd: Effect.void,\n    info: () => Effect.void,\n    table: () => Effect.void,\n    time: () => Effect.void,\n    timeEnd: () => Effect.void,\n    timeLog: () => Effect.void,\n    trace: () => Effect.void,\n    warn: () => Effect.void\n  })\n})\n\nexport const getLines = (\n  params?: Partial<{\n    readonly stripAnsi?: boolean\n  }>\n): Effect.Effect<ReadonlyArray<string>> => Effect.consoleWith((console) => (console as MockConsole).getLines(params))\n"
  },
  {
    "path": "packages/cli/test/services/MockTerminal.ts",
    "content": "import type * as Terminal from \"@effect/platform/Terminal\"\nimport * as Array from \"effect/Array\"\nimport * as Console from \"effect/Console\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as Option from \"effect/Option\"\n\n// =============================================================================\n// Models\n// =============================================================================\n\nexport interface MockTerminal extends Terminal.Terminal {\n  readonly inputText: (text: string) => Effect.Effect<void>\n  readonly inputKey: (\n    key: string,\n    modifiers?: Partial<MockTerminal.Modifiers>\n  ) => Effect.Effect<void>\n}\n\nexport declare namespace MockTerminal {\n  export interface Modifiers {\n    readonly ctrl: boolean\n    readonly meta: boolean\n    readonly shift: boolean\n  }\n}\n\n// =============================================================================\n// Context\n// =============================================================================\n\nexport const MockTerminal = Context.GenericTag<Terminal.Terminal, MockTerminal>(\n  \"@effect/platform/Terminal\"\n)\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\nexport const make = Effect.gen(function*() {\n  const queue = yield* Effect.acquireRelease(\n    Mailbox.make<Terminal.UserInput>(),\n    (_) => _.shutdown\n  )\n\n  const inputText: MockTerminal[\"inputText\"] = (text: string) => {\n    const inputs = Array.map(text.split(\"\"), (key) => toUserInput(key))\n    return queue.offerAll(inputs).pipe(Effect.asVoid)\n  }\n\n  const inputKey: MockTerminal[\"inputKey\"] = (\n    key: string,\n    modifiers?: Partial<MockTerminal.Modifiers>\n  ) => {\n    const input = toUserInput(key, modifiers)\n    return shouldQuit(input) ? queue.end : queue.offer(input).pipe(Effect.asVoid)\n  }\n\n  const display: MockTerminal[\"display\"] = (input) => Console.log(input)\n\n  const readInput: MockTerminal[\"readInput\"] = Effect.succeed(queue)\n\n  return MockTerminal.of({\n    columns: Effect.succeed(80),\n    rows: Effect.succeed(24),\n    isTTY: Effect.succeed(true),\n    display,\n    readInput,\n    readLine: Effect.succeed(\"\"),\n    inputKey,\n    inputText\n  })\n})\n\n// =============================================================================\n// Layer\n// =============================================================================\n\nexport const layer = Layer.scoped(MockTerminal, make)\n\n// =============================================================================\n// Accessors\n// =============================================================================\n\nexport const { columns, readInput, readLine } = Effect.serviceConstants(MockTerminal)\nexport const { inputKey, inputText } = Effect.serviceFunctions(MockTerminal)\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nconst shouldQuit = (input: Terminal.UserInput): boolean =>\n  input.key.ctrl && (input.key.name === \"c\" || input.key.name === \"d\")\n\nconst toUserInput = (\n  key: string,\n  modifiers: Partial<MockTerminal.Modifiers> = {}\n): Terminal.UserInput => {\n  const { ctrl = false, meta = false, shift = false } = modifiers\n  return {\n    input: Option.some(key),\n    key: { name: key, ctrl, meta, shift }\n  }\n}\n"
  },
  {
    "path": "packages/cli/test/snapshots/bash-completions",
    "content": "[\n  \"function _forge_bash_completions() {\",\n  \"    local i cur prev opts cmd\",\n  \"    COMPREPLY=()\",\n  \"    cur=\"${COMP_WORDS[COMP_CWORD]}\"\",\n  \"    prev=\"${COMP_WORDS[COMP_CWORD-1]}\"\",\n  \"    cmd=\"\"\",\n  \"    opts=\"\"\",\n  \"    for i in \"${COMP_WORDS[@]}\"; do\",\n  \"        case \"${cmd},${i}\" in\",\n  \"            \",$1\")\",\n  \"                cmd=\"forge\"\",\n  \"                ;;\",\n  \"            forge,cache)\",\n  \"                cmd=\"forge__cache\"\",\n  \"                ;;\",\n  \"            forge,cache,clean)\",\n  \"                cmd=\"forge__cache__clean\"\",\n  \"                ;;\",\n  \"            forge,cache,ls)\",\n  \"                cmd=\"forge__cache__ls\"\",\n  \"                ;;\",\n  \"            *)\",\n  \"                ;;\",\n  \"        esac\",\n  \"    done\",\n  \"    case \"${cmd}\" in\",\n  \"        forge)\",\n  \"            opts=\"-h --completions --log-level --help --wizard --version cache\"\",\n  \"            if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then\",\n  \"                COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\",\n  \"                return 0\",\n  \"            fi\",\n  \"            case \"${prev}\" in\",\n  \"            *)\",\n  \"                COMPREPLY=()\",\n  \"                ;;\",\n  \"            esac\",\n  \"            COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\",\n  \"            return 0\",\n  \"            ;;\",\n  \"        forge__cache)\",\n  \"            opts=\"-h --verbose --completions --log-level --help --wizard --version clean ls\"\",\n  \"            if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then\",\n  \"                COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\",\n  \"                return 0\",\n  \"            fi\",\n  \"            case \"${prev}\" in\",\n  \"                --verbose)\",\n  \"                    COMPREPLY=( \"${cur}\" )\",\n  \"                    return 0\",\n  \"                    ;;\",\n  \"            *)\",\n  \"                COMPREPLY=()\",\n  \"                ;;\",\n  \"            esac\",\n  \"            COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\",\n  \"            return 0\",\n  \"            ;;\",\n  \"        forge__cache__clean)\",\n  \"            opts=\"-h --completions --log-level --help --wizard --version\"\",\n  \"            if [[ ${cur} == -* || ${COMP_CWORD} -eq 3 ]] ; then\",\n  \"                COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\",\n  \"                return 0\",\n  \"            fi\",\n  \"            case \"${prev}\" in\",\n  \"            *)\",\n  \"                COMPREPLY=()\",\n  \"                ;;\",\n  \"            esac\",\n  \"            COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\",\n  \"            return 0\",\n  \"            ;;\",\n  \"        forge__cache__ls)\",\n  \"            opts=\"-h --completions --log-level --help --wizard --version\"\",\n  \"            if [[ ${cur} == -* || ${COMP_CWORD} -eq 3 ]] ; then\",\n  \"                COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\",\n  \"                return 0\",\n  \"            fi\",\n  \"            case \"${prev}\" in\",\n  \"            *)\",\n  \"                COMPREPLY=()\",\n  \"                ;;\",\n  \"            esac\",\n  \"            COMPREPLY=( $(compgen -W \"${opts}\" -- \"${cur}\") )\",\n  \"            return 0\",\n  \"            ;;\",\n  \"    esac\",\n  \"}\",\n  \"complete -F _forge_bash_completions -o nosort -o bashdefault -o default forge\",\n]"
  },
  {
    "path": "packages/cli/test/snapshots/fish-completions",
    "content": "[\n  \"complete -c forge -n \"__fish_use_subcommand\" -l completions -r -f -a \"{sh'',bash'',fish'',zsh''}\" -d 'Generate a completion script for a specific shell.'\",\n  \"complete -c forge -n \"__fish_use_subcommand\" -l log-level -r -f -a \"{all'',trace'',debug'',info'',warning'',error'',fatal'',none''}\" -d 'Sets the minimum log level for a command.'\",\n  \"complete -c forge -n \"__fish_use_subcommand\" -s h -l help -d 'Show the help documentation for a command.'\",\n  \"complete -c forge -n \"__fish_use_subcommand\" -l wizard -d 'Start wizard mode for a command.'\",\n  \"complete -c forge -n \"__fish_use_subcommand\" -l version -d 'Show the version of the application.'\",\n  \"complete -c forge -n \"__fish_use_subcommand\" -f -a \"cache\" -d 'The cache command does cache things'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and not __fish_seen_subcommand_from clean; and not __fish_seen_subcommand_from ls\" -l completions -r -f -a \"{sh'',bash'',fish'',zsh''}\" -d 'Generate a completion script for a specific shell.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and not __fish_seen_subcommand_from clean; and not __fish_seen_subcommand_from ls\" -l log-level -r -f -a \"{all'',trace'',debug'',info'',warning'',error'',fatal'',none''}\" -d 'Sets the minimum log level for a command.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and not __fish_seen_subcommand_from clean; and not __fish_seen_subcommand_from ls\" -s h -l help -d 'Show the help documentation for a command.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and not __fish_seen_subcommand_from clean; and not __fish_seen_subcommand_from ls\" -l wizard -d 'Start wizard mode for a command.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and not __fish_seen_subcommand_from clean; and not __fish_seen_subcommand_from ls\" -l version -d 'Show the version of the application.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and not __fish_seen_subcommand_from clean; and not __fish_seen_subcommand_from ls\" -l verbose -d 'Output in verbose mode'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and not __fish_seen_subcommand_from clean; and not __fish_seen_subcommand_from ls\" -f -a \"clean\"\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and not __fish_seen_subcommand_from clean; and not __fish_seen_subcommand_from ls\" -f -a \"ls\"\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and __fish_seen_subcommand_from clean\" -l completions -r -f -a \"{sh'',bash'',fish'',zsh''}\" -d 'Generate a completion script for a specific shell.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and __fish_seen_subcommand_from clean\" -l log-level -r -f -a \"{all'',trace'',debug'',info'',warning'',error'',fatal'',none''}\" -d 'Sets the minimum log level for a command.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and __fish_seen_subcommand_from clean\" -s h -l help -d 'Show the help documentation for a command.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and __fish_seen_subcommand_from clean\" -l wizard -d 'Start wizard mode for a command.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and __fish_seen_subcommand_from clean\" -l version -d 'Show the version of the application.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and __fish_seen_subcommand_from ls\" -l completions -r -f -a \"{sh'',bash'',fish'',zsh''}\" -d 'Generate a completion script for a specific shell.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and __fish_seen_subcommand_from ls\" -l log-level -r -f -a \"{all'',trace'',debug'',info'',warning'',error'',fatal'',none''}\" -d 'Sets the minimum log level for a command.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and __fish_seen_subcommand_from ls\" -s h -l help -d 'Show the help documentation for a command.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and __fish_seen_subcommand_from ls\" -l wizard -d 'Start wizard mode for a command.'\",\n  \"complete -c forge -n \"__fish_seen_subcommand_from cache; and __fish_seen_subcommand_from ls\" -l version -d 'Show the version of the application.'\",\n]"
  },
  {
    "path": "packages/cli/test/snapshots/help-output/args-default-object",
    "content": "{\n  \"_tag\": \"DescriptionList\",\n  \"definitions\": [\n    [\n      {\n        \"_tag\": \"Weak\",\n        \"value\": {\n          \"_tag\": \"Text\",\n          \"value\": \"<config>\",\n        },\n      },\n      {\n        \"_tag\": \"Sequence\",\n        \"left\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"A user-defined piece of text.\",\n          },\n        },\n        \"right\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"This setting is optional. Defaults to: {\"key\":\"value\",\"number\":456}\",\n          },\n        },\n      },\n    ],\n  ],\n}"
  },
  {
    "path": "packages/cli/test/snapshots/help-output/args-default-primitive",
    "content": "{\n  \"_tag\": \"DescriptionList\",\n  \"definitions\": [\n    [\n      {\n        \"_tag\": \"Weak\",\n        \"value\": {\n          \"_tag\": \"Text\",\n          \"value\": \"<value>\",\n        },\n      },\n      {\n        \"_tag\": \"Sequence\",\n        \"left\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"An integer.\",\n          },\n        },\n        \"right\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"This setting is optional. Defaults to: 123\",\n          },\n        },\n      },\n    ],\n  ],\n}"
  },
  {
    "path": "packages/cli/test/snapshots/help-output/args-no-default",
    "content": "{\n  \"_tag\": \"DescriptionList\",\n  \"definitions\": [\n    [\n      {\n        \"_tag\": \"Weak\",\n        \"value\": {\n          \"_tag\": \"Text\",\n          \"value\": \"<name>\",\n        },\n      },\n      {\n        \"_tag\": \"Sequence\",\n        \"left\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"A user-defined piece of text.\",\n          },\n        },\n        \"right\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"This setting is optional.\",\n          },\n        },\n      },\n    ],\n  ],\n}"
  },
  {
    "path": "packages/cli/test/snapshots/help-output/options-default-object",
    "content": "{\n  \"_tag\": \"DescriptionList\",\n  \"definitions\": [\n    [\n      {\n        \"_tag\": \"Sequence\",\n        \"left\": {\n          \"_tag\": \"Text\",\n          \"value\": \"--config\",\n        },\n        \"right\": {\n          \"_tag\": \"Sequence\",\n          \"left\": {\n            \"_tag\": \"Text\",\n            \"value\": \" \",\n          },\n          \"right\": {\n            \"_tag\": \"Text\",\n            \"value\": \"text\",\n          },\n        },\n      },\n      {\n        \"_tag\": \"Sequence\",\n        \"left\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"A user-defined piece of text.\",\n          },\n        },\n        \"right\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"This setting is optional. Defaults to: {\"key\":\"value\",\"number\":456}\",\n          },\n        },\n      },\n    ],\n  ],\n}"
  },
  {
    "path": "packages/cli/test/snapshots/help-output/options-default-primitive",
    "content": "{\n  \"_tag\": \"DescriptionList\",\n  \"definitions\": [\n    [\n      {\n        \"_tag\": \"Sequence\",\n        \"left\": {\n          \"_tag\": \"Text\",\n          \"value\": \"--value\",\n        },\n        \"right\": {\n          \"_tag\": \"Sequence\",\n          \"left\": {\n            \"_tag\": \"Text\",\n            \"value\": \" \",\n          },\n          \"right\": {\n            \"_tag\": \"Text\",\n            \"value\": \"integer\",\n          },\n        },\n      },\n      {\n        \"_tag\": \"Sequence\",\n        \"left\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"An integer.\",\n          },\n        },\n        \"right\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"This setting is optional. Defaults to: 123\",\n          },\n        },\n      },\n    ],\n  ],\n}"
  },
  {
    "path": "packages/cli/test/snapshots/help-output/options-no-default",
    "content": "{\n  \"_tag\": \"DescriptionList\",\n  \"definitions\": [\n    [\n      {\n        \"_tag\": \"Sequence\",\n        \"left\": {\n          \"_tag\": \"Text\",\n          \"value\": \"--name\",\n        },\n        \"right\": {\n          \"_tag\": \"Sequence\",\n          \"left\": {\n            \"_tag\": \"Text\",\n            \"value\": \" \",\n          },\n          \"right\": {\n            \"_tag\": \"Text\",\n            \"value\": \"text\",\n          },\n        },\n      },\n      {\n        \"_tag\": \"Sequence\",\n        \"left\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"A user-defined piece of text.\",\n          },\n        },\n        \"right\": {\n          \"_tag\": \"Paragraph\",\n          \"value\": {\n            \"_tag\": \"Text\",\n            \"value\": \"This setting is optional.\",\n          },\n        },\n      },\n    ],\n  ],\n}"
  },
  {
    "path": "packages/cli/test/snapshots/zsh-completions",
    "content": "[\n  \"#compdef forge\",\n  \"\",\n  \"autoload -U is-at-least\",\n  \"\",\n  \"function _forge_zsh_completions() {\",\n  \"    typeset -A opt_args\",\n  \"    typeset -a _arguments_options\",\n  \"    local ret=1\",\n  \"\",\n  \"    if is-at-least 5.2; then\",\n  \"        _arguments_options=(-s -S -C)\",\n  \"    else\",\n  \"        _arguments_options=(-s -C)\",\n  \"    fi\",\n  \"\",\n  \"    local context curcontext=\"$curcontext\" state line\",\n  \"    _arguments \"${_arguments_options[@]}\" \\\",\n  \"        '--completions[Generate a completion script for a specific shell.]:CHOICE:(sh bash fish zsh)' \\\",\n  \"        '--log-level[Sets the minimum log level for a command.]:CHOICE:(all trace debug info warning error fatal none)' \\\",\n  \"        '-h[Show the help documentation for a command.]' \\\",\n  \"        '--help[Show the help documentation for a command.]' \\\",\n  \"        '--wizard[Start wizard mode for a command.]' \\\",\n  \"        '--version[Show the version of the application.]' \\\",\n  \"        \":: :_forge_commands\" \\\",\n  \"        \"*::: :->forge\" \\\",\n  \"        && ret=0\",\n  \"    case $state in\",\n  \"        (forge)\",\n  \"        words=($line[1] \"${words[@]}\")\",\n  \"        (( CURRENT += 1 ))\",\n  \"        curcontext=\"${curcontext%:*:*}:forge-command-$line[1]:\"\",\n  \"        case $line[1] in\",\n  \"            (cache)\",\n  \"            _arguments \"${_arguments_options[@]}\" \\\",\n  \"                '--completions[Generate a completion script for a specific shell.]:CHOICE:(sh bash fish zsh)' \\\",\n  \"                '--log-level[Sets the minimum log level for a command.]:CHOICE:(all trace debug info warning error fatal none)' \\\",\n  \"                '-h[Show the help documentation for a command.]' \\\",\n  \"                '--help[Show the help documentation for a command.]' \\\",\n  \"                '--wizard[Start wizard mode for a command.]' \\\",\n  \"                '--version[Show the version of the application.]' \\\",\n  \"                '--verbose[Output in verbose mode]' \\\",\n  \"                \":: :_forge__cache_commands\" \\\",\n  \"                \"*::: :->cache\" \\\",\n  \"                && ret=0\",\n  \"            case $state in\",\n  \"                (cache)\",\n  \"                words=($line[1] \"${words[@]}\")\",\n  \"                (( CURRENT += 1 ))\",\n  \"                curcontext=\"${curcontext%:*:*}:forge-cache-command-$line[1]:\"\",\n  \"                case $line[1] in\",\n  \"                    (clean)\",\n  \"                    _arguments \"${_arguments_options[@]}\" \\\",\n  \"                        '--completions[Generate a completion script for a specific shell.]:CHOICE:(sh bash fish zsh)' \\\",\n  \"                        '--log-level[Sets the minimum log level for a command.]:CHOICE:(all trace debug info warning error fatal none)' \\\",\n  \"                        '-h[Show the help documentation for a command.]' \\\",\n  \"                        '--help[Show the help documentation for a command.]' \\\",\n  \"                        '--wizard[Start wizard mode for a command.]' \\\",\n  \"                        '--version[Show the version of the application.]' \\\",\n  \"                        && ret=0\",\n  \"                    ;;\",\n  \"                    (ls)\",\n  \"                    _arguments \"${_arguments_options[@]}\" \\\",\n  \"                        '--completions[Generate a completion script for a specific shell.]:CHOICE:(sh bash fish zsh)' \\\",\n  \"                        '--log-level[Sets the minimum log level for a command.]:CHOICE:(all trace debug info warning error fatal none)' \\\",\n  \"                        '-h[Show the help documentation for a command.]' \\\",\n  \"                        '--help[Show the help documentation for a command.]' \\\",\n  \"                        '--wizard[Start wizard mode for a command.]' \\\",\n  \"                        '--version[Show the version of the application.]' \\\",\n  \"                        && ret=0\",\n  \"                    ;;\",\n  \"                esac\",\n  \"                ;;\",\n  \"            esac\",\n  \"            ;;\",\n  \"        esac\",\n  \"        ;;\",\n  \"    esac\",\n  \"}\",\n  \"\",\n  \"(( $+functions[_forge_commands] )) ||\",\n  \"_forge_commands() {\",\n  \"    local commands; commands=(\n        'cache:The cache command does cache things' \\\n    )\",\n  \"    _describe -t commands 'forge commands' commands \"$@\"\",\n  \"}\",\n  \"(( $+functions[_forge__cache_commands] )) ||\",\n  \"_forge__cache_commands() {\",\n  \"    local commands; commands=(\n        'clean:' \\\n        'ls:' \\\n    )\",\n  \"    _describe -t commands 'forge cache commands' commands \"$@\"\",\n  \"}\",\n  \"(( $+functions[_forge__cache__clean_commands] )) ||\",\n  \"_forge__cache__clean_commands() {\",\n  \"    local commands; commands=()\",\n  \"    _describe -t commands 'forge cache clean commands' commands \"$@\"\",\n  \"}\",\n  \"(( $+functions[_forge__cache__ls_commands] )) ||\",\n  \"_forge__cache__ls_commands() {\",\n  \"    local commands; commands=()\",\n  \"    _describe -t commands 'forge cache ls commands' commands \"$@\"\",\n  \"}\",\n  \"\",\n  \"if [ \"$funcstack[1]\" = \"_forge_zsh_completions\" ]; then\",\n  \"    _forge_zsh_completions \"$@\"\",\n  \"else\",\n  \"    compdef _forge_zsh_completions forge\",\n  \"fi\",\n]"
  },
  {
    "path": "packages/cli/test/utils/grep.ts",
    "content": "import * as Args from \"@effect/cli/Args\"\nimport * as Descriptor from \"@effect/cli/CommandDescriptor\"\nimport * as Options from \"@effect/cli/Options\"\n\nconst afterFlag = Options.integer(\"after\").pipe(Options.withAlias(\"A\"))\nconst beforeFlag = Options.integer(\"before\").pipe(Options.withAlias(\"B\"))\nexport const options: Options.Options<[number, number]> = Options.all([\n  afterFlag,\n  beforeFlag\n])\n\nexport const args: Args.Args<string> = Args.text()\n\nexport const command: Descriptor.Command<{\n  readonly name: \"grep\"\n  readonly options: [number, number]\n  readonly args: string\n}> = Descriptor.make(\"grep\", options, args)\n"
  },
  {
    "path": "packages/cli/test/utils/tail.ts",
    "content": "import * as Args from \"@effect/cli/Args\"\nimport * as Descriptor from \"@effect/cli/CommandDescriptor\"\nimport * as Options from \"@effect/cli/Options\"\n\nexport const options: Options.Options<number> = Options.integer(\"n\").pipe(\n  Options.withDefault(10)\n)\n\nexport const args: Args.Args<string> = Args.file({ name: \"file\" })\n\nexport const command: Descriptor.Command<{\n  readonly name: \"tail\"\n  readonly options: number\n  readonly args: string\n}> = Descriptor.make(\"tail\", options, args)\n"
  },
  {
    "path": "packages/cli/test/utils/wc.ts",
    "content": "import * as Args from \"@effect/cli/Args\"\nimport * as Descriptor from \"@effect/cli/CommandDescriptor\"\nimport * as Options from \"@effect/cli/Options\"\n\nconst bytesFlag = Options.boolean(\"c\")\nconst linesFlag = Options.boolean(\"l\")\nconst wordsFlag = Options.boolean(\"w\")\nconst charFlag = Options.boolean(\"m\", { ifPresent: false })\nexport const options: Options.Options<[boolean, boolean, boolean, boolean]> = Options.all([\n  bytesFlag,\n  linesFlag,\n  wordsFlag,\n  charFlag\n])\n\nexport const args: Args.Args<ReadonlyArray<string>> = Args.repeated(Args.file({ name: \"files\" }))\n\nexport const command: Descriptor.Command<{\n  readonly name: \"wc\"\n  readonly options: [boolean, boolean, boolean, boolean]\n  readonly args: ReadonlyArray<string>\n}> = Descriptor.make(\"wc\", options, args)\n"
  },
  {
    "path": "packages/cli/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"references\": [\n    { \"path\": \"../effect/tsconfig.build.json\" },\n    { \"path\": \"../printer/tsconfig.build.json\" },\n    { \"path\": \"../printer-ansi/tsconfig.build.json\" },\n    { \"path\": \"../platform/tsconfig.build.json\" },\n    { \"path\": \"../platform-node/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"types\": [\"node\"],\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true\n  }\n}\n"
  },
  {
    "path": "packages/cli/tsconfig.examples.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"examples\"],\n  \"references\": [\n    { \"path\": \"tsconfig.build.json\" },\n    { \"path\": \"../platform-node/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"types\": [\"node\"],\n    \"tsBuildInfoFile\": \".tsbuildinfo/examples.tsbuildinfo\",\n    \"rootDir\": \"examples\",\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "packages/cli/tsconfig.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" },\n    { \"path\": \"tsconfig.examples.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/cli/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"references\": [\n    { \"path\": \"../effect/tsconfig.src.json\" },\n    { \"path\": \"../printer/tsconfig.src.json\" },\n    { \"path\": \"../printer-ansi/tsconfig.src.json\" },\n    { \"path\": \"../platform/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"types\": [\"node\"],\n    \"outDir\": \"build/src\",\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\"\n  }\n}\n"
  },
  {
    "path": "packages/cli/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../vitest/tsconfig.src.json\" },\n    { \"path\": \"../platform-node/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"types\": [\"node\"],\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "packages/cli/vitest.config.ts",
    "content": "import { mergeConfig, type ViteUserConfig } from \"vitest/config\"\nimport shared from \"../../vitest.shared.js\"\n\nconst config: ViteUserConfig = {}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/cluster/CHANGELOG.md",
    "content": "# @effect/cluster\n\n## 0.58.0\n\n### Patch Changes\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n  - @effect/platform@0.96.0\n  - @effect/rpc@0.75.0\n  - @effect/sql@0.51.0\n  - @effect/workflow@0.18.0\n\n## 0.57.0\n\n### Patch Changes\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n  - @effect/platform@0.95.0\n  - @effect/rpc@0.74.0\n  - @effect/sql@0.50.0\n  - @effect/workflow@0.17.0\n\n## 0.56.4\n\n### Patch Changes\n\n- [#6056](https://github.com/Effect-TS/effect/pull/6056) [`52cd531`](https://github.com/Effect-TS/effect/commit/52cd53115fe14e2b9c36dd0d51eb490aead74ee6) Thanks @0xh3x! - use HttpLayerRouter variants for route registration in HttpRunner\n\n- Updated dependencies [[`d67c708`](https://github.com/Effect-TS/effect/commit/d67c7089ba8616b2d48ef7324312267a2a6f310a), [`a8c436f`](https://github.com/Effect-TS/effect/commit/a8c436f7004cc2a8ce2daec589ea7256b91c324f), [`598ff76`](https://github.com/Effect-TS/effect/commit/598ff7642fdee7f3379bca49e378a0e9647bbe75)]:\n  - @effect/platform@0.94.5\n  - effect@3.19.17\n  - @effect/rpc@0.73.1\n\n## 0.56.3\n\n### Patch Changes\n\n- [#6033](https://github.com/Effect-TS/effect/pull/6033) [`740a912`](https://github.com/Effect-TS/effect/commit/740a912142c2578defcf3e1e7d449535b074bd61) Thanks @tim-smart! - Add `PgClient.fromPool` and `PgClient.layerFromPool`.\n\n- Updated dependencies [[`22d9d27`](https://github.com/Effect-TS/effect/commit/22d9d27bc007db86d9e4748c17324fab5f950c7d)]:\n  - @effect/platform@0.94.4\n\n## 0.56.2\n\n### Patch Changes\n\n- [#6031](https://github.com/Effect-TS/effect/pull/6031) [`1781244`](https://github.com/Effect-TS/effect/commit/17812444c6c0d8f19f9fbc85d82f911dff5523ab) Thanks @tim-smart! - backport effect v4 MessageStorage improvements\n\n## 0.56.1\n\n### Patch Changes\n\n- [#5946](https://github.com/Effect-TS/effect/pull/5946) [`e88f289`](https://github.com/Effect-TS/effect/commit/e88f289c1d9fd4ec584ee793c264597aa84c9352) Thanks @vic-mo! - Fix HttpRunner double-slash routing\n\n## 0.56.0\n\n### Patch Changes\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n  - @effect/platform@0.94.0\n  - @effect/rpc@0.73.0\n  - @effect/sql@0.49.0\n  - @effect/workflow@0.16.0\n\n## 0.55.0\n\n### Patch Changes\n\n- Updated dependencies [[`811852a`](https://github.com/Effect-TS/effect/commit/811852a61868136bb7b3367450f02e5a8fb8a3f9), [`811852a`](https://github.com/Effect-TS/effect/commit/811852a61868136bb7b3367450f02e5a8fb8a3f9)]:\n  - @effect/sql@0.48.6\n  - @effect/workflow@0.15.0\n\n## 0.54.0\n\n### Patch Changes\n\n- [#5827](https://github.com/Effect-TS/effect/pull/5827) [`7bd4e82`](https://github.com/Effect-TS/effect/commit/7bd4e827bc246a39d71b48a105e0853352efdc3b) Thanks @tim-smart! - add TestRunner & SingleRunner modules\n  - `TestRunner` allows you to run a in-memory cluster for testing purposes.\n  - `SingleRunner` allows you to run a single node cluster simple deployment\n    scenarios.\n    - Message storage is backed by a SQL database\n    - Multiple nodes are not supported\n\n- Updated dependencies [[`7bd4e82`](https://github.com/Effect-TS/effect/commit/7bd4e827bc246a39d71b48a105e0853352efdc3b)]:\n  - @effect/workflow@0.14.0\n\n## 0.53.6\n\n### Patch Changes\n\n- [#5793](https://github.com/Effect-TS/effect/pull/5793) [`a2d965d`](https://github.com/Effect-TS/effect/commit/a2d965d2a22dcc018f81dbbcd55bfe33088d9411) Thanks @tim-smart! - allow advisory locks to be disabled\n\n- Updated dependencies [[`8ebd29e`](https://github.com/Effect-TS/effect/commit/8ebd29ec10976222c200901d9b72779af743e6d5)]:\n  - @effect/platform@0.93.4\n\n## 0.53.5\n\n### Patch Changes\n\n- [#5785](https://github.com/Effect-TS/effect/pull/5785) [`47bf3d2`](https://github.com/Effect-TS/effect/commit/47bf3d2324ab914f6a33e95cda7ff2aac01519a6) Thanks @tim-smart! - immediately set entity keep alive in EntityResource\n\n## 0.53.4\n\n### Patch Changes\n\n- [#5783](https://github.com/Effect-TS/effect/pull/5783) [`8b879fb`](https://github.com/Effect-TS/effect/commit/8b879fb3b886a7262c9c8d9b2050cc128c5eb6f8) Thanks @tim-smart! - add EntityResource.makeK8sPod\n\n## 0.53.3\n\n### Patch Changes\n\n- [#5781](https://github.com/Effect-TS/effect/pull/5781) [`df69cb5`](https://github.com/Effect-TS/effect/commit/df69cb5ed590045b18d1527162518ea0197ddd2e) Thanks @tim-smart! - provide seperate close scope to EntityResource via context\n\n## 0.53.2\n\n### Patch Changes\n\n- [#5778](https://github.com/Effect-TS/effect/pull/5778) [`af7916a`](https://github.com/Effect-TS/effect/commit/af7916a3f00acdfc8ce451eabd3f5fb02914d0bb) Thanks @tim-smart! - fix postgres unprocessed message ordering\n\n- [#5778](https://github.com/Effect-TS/effect/pull/5778) [`af7916a`](https://github.com/Effect-TS/effect/commit/af7916a3f00acdfc8ce451eabd3f5fb02914d0bb) Thanks @tim-smart! - add @effect/cluster EntityResource module\n\n  A `EntityResource` is a resource that can be acquired inside a cluster\n  entity, which will keep the entity alive even across restarts.\n\n  The resource will only be fully released when the idle time to live is\n  reached, or when the `close` effect is called.\n\n  By default, the `idleTimeToLive` is infinite, meaning the resource will only\n  be released when `close` is called.\n\n  ```ts\n  import { Entity, EntityResource } from \"@effect/cluster\"\n  import { Rpc } from \"@effect/rpc\"\n  import { Effect } from \"effect\"\n\n  const EntityA = Entity.make(\"EntityA\", [Rpc.make(\"method\")])\n\n  export const EntityALayer = EntityA.toLayer(\n    Effect.gen(function* () {\n      // When the entity receives a message, it will first acquire the resource\n      //\n      // If the entity restarts, the resource will be re-acquired in the new\n      // instance.\n      //\n      // It will only be released when the idle TTL is reached, or when the\n      // `close` effect is called.\n      const resource = yield* EntityResource.make({\n        acquire: Effect.acquireRelease(\n          Effect.logInfo(\"Acquiring Entity resource\"),\n          () => Effect.logInfo(\"Releasing Entity resource\")\n        ),\n        // If the resource is not used for 10 minutes, it will be released and the\n        // entity will be allowed to shut down.\n        idleTimeToLive: \"10 minutes\"\n      })\n\n      return EntityA.of({\n        method: Effect.fnUntraced(function* () {\n          yield* Effect.logInfo(\"EntityA.method called\")\n          // To access the resource, use `resource.get` inside an Effect.scoped\n          yield* resource.get\n        }, Effect.scoped)\n      })\n    }),\n    {\n      // After the resource is released, if the entity is not used for 1 minute,\n      // the entity will be shut down.\n      maxIdleTime: \"1 minute\"\n    }\n  )\n  ```\n\n- Updated dependencies [[`af7916a`](https://github.com/Effect-TS/effect/commit/af7916a3f00acdfc8ce451eabd3f5fb02914d0bb)]:\n  - effect@3.19.6\n\n## 0.53.1\n\n### Patch Changes\n\n- [#5775](https://github.com/Effect-TS/effect/pull/5775) [`b92632d`](https://github.com/Effect-TS/effect/commit/b92632ded7a976c9279985013c295260c6603b14) Thanks @tim-smart! - ensure ClusterCron's can be resumed if re-added\n\n## 0.53.0\n\n### Patch Changes\n\n- [#5771](https://github.com/Effect-TS/effect/pull/5771) [`794c790`](https://github.com/Effect-TS/effect/commit/794c790d736f62784bff800fda5a656026d93749) Thanks @tim-smart! - backport Entity keep alive from effect 4.0\n\n- [#5771](https://github.com/Effect-TS/effect/pull/5771) [`794c790`](https://github.com/Effect-TS/effect/commit/794c790d736f62784bff800fda5a656026d93749) Thanks @tim-smart! - add WorkflowEngine.makeUnsafe, which abstracts the serialization boundary\n\n- Updated dependencies [[`794c790`](https://github.com/Effect-TS/effect/commit/794c790d736f62784bff800fda5a656026d93749), [`794c790`](https://github.com/Effect-TS/effect/commit/794c790d736f62784bff800fda5a656026d93749), [`079975c`](https://github.com/Effect-TS/effect/commit/079975c69d80c62461da5c51fe89e02c44dfa2ea), [`794c790`](https://github.com/Effect-TS/effect/commit/794c790d736f62784bff800fda5a656026d93749), [`62f7636`](https://github.com/Effect-TS/effect/commit/62f76361ee01ed816687774c5302e7f8c5ff6a42)]:\n  - @effect/rpc@0.72.2\n  - @effect/workflow@0.13.0\n  - effect@3.19.5\n\n## 0.52.11\n\n### Patch Changes\n\n- [#5765](https://github.com/Effect-TS/effect/pull/5765) [`f38c215`](https://github.com/Effect-TS/effect/commit/f38c215f99920c9ce8809a01ddb38b1c96d18d44) Thanks @tim-smart! - add entityRegistrationTimeout to ShardingConfig\n\n## 0.52.10\n\n### Patch Changes\n\n- [#5748](https://github.com/Effect-TS/effect/pull/5748) [`b93fc63`](https://github.com/Effect-TS/effect/commit/b93fc638da9a4e840a02417e422c34c8a735413c) Thanks @tim-smart! - don't resume parent workflow when suspending on failure\n\n## 0.52.9\n\n### Patch Changes\n\n- [#5726](https://github.com/Effect-TS/effect/pull/5726) [`d34476e`](https://github.com/Effect-TS/effect/commit/d34476eebf1b61ce80b2127689d95d3b0c703aab) Thanks @tim-smart! - support and test against vitess for SqlRunnerStorage\n\n## 0.52.8\n\n### Patch Changes\n\n- [#5719](https://github.com/Effect-TS/effect/pull/5719) [`3689a18`](https://github.com/Effect-TS/effect/commit/3689a183c5ace2fc31faec1910347a12b0e70364) Thanks @tim-smart! - re-use resume parent messages for child workflows\n\n## 0.52.7\n\n### Patch Changes\n\n- [#5716](https://github.com/Effect-TS/effect/pull/5716) [`629b98d`](https://github.com/Effect-TS/effect/commit/629b98d3b696df6c928f0930b867ca3f27829af0) Thanks @tim-smart! - optimize Sharding shard release\n\n- Updated dependencies [[`7d28a90`](https://github.com/Effect-TS/effect/commit/7d28a908f965854cff386a19515141aea5b39eb7)]:\n  - effect@3.19.3\n\n## 0.52.6\n\n### Patch Changes\n\n- [#5705](https://github.com/Effect-TS/effect/pull/5705) [`84d22eb`](https://github.com/Effect-TS/effect/commit/84d22eb75985da4f3c626a59bcfa2b5a19a17fa2) Thanks @tim-smart! - use FiberMap to release shards concurrently\n\n- [#5705](https://github.com/Effect-TS/effect/pull/5705) [`84d22eb`](https://github.com/Effect-TS/effect/commit/84d22eb75985da4f3c626a59bcfa2b5a19a17fa2) Thanks @tim-smart! - if a shard lock fails to release, release all locks\n\n## 0.52.5\n\n### Patch Changes\n\n- [#5703](https://github.com/Effect-TS/effect/pull/5703) [`374f58c`](https://github.com/Effect-TS/effect/commit/374f58c10799109b61d8a131a025f3d03ce5aab5) Thanks @tim-smart! - close release FiberHandle after acquisition fiber\n\n- Updated dependencies [[`374f58c`](https://github.com/Effect-TS/effect/commit/374f58c10799109b61d8a131a025f3d03ce5aab5), [`374f58c`](https://github.com/Effect-TS/effect/commit/374f58c10799109b61d8a131a025f3d03ce5aab5)]:\n  - effect@3.19.2\n\n## 0.52.4\n\n### Patch Changes\n\n- [#5701](https://github.com/Effect-TS/effect/pull/5701) [`c00268d`](https://github.com/Effect-TS/effect/commit/c00268d6ae82fcceda6d71a99e1ec4c5072c1deb) Thanks @tim-smart! - add timeout to pg lock queries\n\n## 0.52.3\n\n### Patch Changes\n\n- [#5698](https://github.com/Effect-TS/effect/pull/5698) [`19e14ec`](https://github.com/Effect-TS/effect/commit/19e14ec89065ed938f0b3d27a9e8838dac81f3c8) Thanks @tim-smart! - add premptiveShutdown option to ShardingConfig\n\n## 0.52.2\n\n### Patch Changes\n\n- [#5695](https://github.com/Effect-TS/effect/pull/5695) [`63f2bf3`](https://github.com/Effect-TS/effect/commit/63f2bf393ef4bb3e46db59abdf1b2160e8ee71d4) Thanks @tim-smart! - tie cluster Entity lifetimes to Layer scope\n\n- Updated dependencies [[`63f2bf3`](https://github.com/Effect-TS/effect/commit/63f2bf393ef4bb3e46db59abdf1b2160e8ee71d4), [`63f2bf3`](https://github.com/Effect-TS/effect/commit/63f2bf393ef4bb3e46db59abdf1b2160e8ee71d4)]:\n  - effect@3.19.1\n  - @effect/workflow@0.12.2\n\n## 0.52.1\n\n### Patch Changes\n\n- [#5693](https://github.com/Effect-TS/effect/pull/5693) [`c7e572c`](https://github.com/Effect-TS/effect/commit/c7e572c3504ea9115df5fa1256d4791b03f33133) Thanks @tim-smart! - change workflow re-registration defect to a warning\n\n## 0.52.0\n\n### Patch Changes\n\n- [#5684](https://github.com/Effect-TS/effect/pull/5684) [`15100f6`](https://github.com/Effect-TS/effect/commit/15100f6ed1ae554c295fb8034623e942dcdc6a72) Thanks @tim-smart! - retry interrupted workflow activities\n\n- [#5689](https://github.com/Effect-TS/effect/pull/5689) [`0d77928`](https://github.com/Effect-TS/effect/commit/0d779286eec84e679b55e0dbcd7d0dd981c28f18) Thanks @tim-smart! - only store client interrupts as suspends\n\n- [#5691](https://github.com/Effect-TS/effect/pull/5691) [`c2133fa`](https://github.com/Effect-TS/effect/commit/c2133fad3a5c3f73c0e0920be779390d24aa253f) Thanks @tim-smart! - prevent interrupt suspends from propagating\n\n- Updated dependencies [[`15100f6`](https://github.com/Effect-TS/effect/commit/15100f6ed1ae554c295fb8034623e942dcdc6a72), [`571025c`](https://github.com/Effect-TS/effect/commit/571025ceaff6ef432a61bf65735a5a0f45118313), [`d43577b`](https://github.com/Effect-TS/effect/commit/d43577be59ae510812287b1cbffe6da15c040452)]:\n  - @effect/workflow@0.12.1\n  - @effect/sql@0.48.0\n  - @effect/rpc@0.72.1\n\n## 0.51.0\n\n### Minor Changes\n\n- [#5606](https://github.com/Effect-TS/effect/pull/5606) [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433) Thanks @tim-smart! - backport @effect/cluster from effect v4\n\n  @effect/cluster no longer requires a Shard Manager, and instead relies on the\n  `RunnerStorage` service to track runner state.\n\n  To migrate, remove any Shard Manager deployments and use the updated layers in\n  `@effect/platform-node` or `@effect/platform-bun`.\n\n  # Breaking Changes\n  - `ShardManager` module has been removed\n  - `EntityNotManagedByRunner` error has been removed\n  - Shard locks now use database advisory locks, which requires stable sessions\n    for database connections. This means load balancers or proxies that rotate\n    connections may cause issues.\n  - `@effect/platform-node/NodeClusterSocketRunner` is now\n    `@effect/cluster/NodeClusterSocket`\n  - `@effect/platform-node/NodeClusterHttpRunner` is now\n    `@effect/cluster/NodeClusterHttp`\n  - `@effect/platform-bun/BunClusterSocketRunner` is now\n    `@effect/cluster/BunClusterSocket`\n  - `@effect/platform-bun/BunClusterHttpRunner` is now\n    `@effect/cluster/BunClusterHttp`\n\n  # New Features\n  - `RunnerHealth.layerK8s` has been added, which uses the Kubernetes API to track\n    runner health and liveness. To use it, you will need a service account with\n    permissions to read pod information.\n\n### Patch Changes\n\n- Updated dependencies [[`27863ab`](https://github.com/Effect-TS/effect/commit/27863abed9047a3cb5d47b4136ff69d5456e2c74), [`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - @effect/workflow@0.12.0\n  - effect@3.19.0\n  - @effect/rpc@0.72.0\n  - @effect/platform@0.93.0\n  - @effect/sql@0.47.0\n\n## 0.50.6\n\n### Patch Changes\n\n- [#5642](https://github.com/Effect-TS/effect/pull/5642) [`b8e3c6d`](https://github.com/Effect-TS/effect/commit/b8e3c6d510aec858ac34bfe5eb2b8fc5506fd669) Thanks @tim-smart! - fix ReferenceError in NodeSocket.fromNet\n\n- Updated dependencies [[`b8e3c6d`](https://github.com/Effect-TS/effect/commit/b8e3c6d510aec858ac34bfe5eb2b8fc5506fd669)]:\n  - @effect/rpc@0.71.1\n  - @effect/workflow@0.11.5\n\n## 0.50.5\n\n### Patch Changes\n\n- [#5640](https://github.com/Effect-TS/effect/pull/5640) [`85ea731`](https://github.com/Effect-TS/effect/commit/85ea731c8305c040fc50b82c204f3e20371c50a4) Thanks @tim-smart! - use external interruption for workflow suspend\n\n- Updated dependencies [[`85ea731`](https://github.com/Effect-TS/effect/commit/85ea731c8305c040fc50b82c204f3e20371c50a4)]:\n  - @effect/workflow@0.11.4\n\n## 0.50.4\n\n### Patch Changes\n\n- [#5618](https://github.com/Effect-TS/effect/pull/5618) [`d2140c1`](https://github.com/Effect-TS/effect/commit/d2140c1604a575186075e0907ecc05d9ab197c23) Thanks @tim-smart! - don't restart an entity during shutdown\n\n## 0.50.3\n\n### Patch Changes\n\n- [#5602](https://github.com/Effect-TS/effect/pull/5602) [`64b764b`](https://github.com/Effect-TS/effect/commit/64b764b3207eb13cacb13da31343aaf425e966bf) Thanks @tim-smart! - guard against race conditions in NodeSocketServer\n\n- Updated dependencies [[`64b764b`](https://github.com/Effect-TS/effect/commit/64b764b3207eb13cacb13da31343aaf425e966bf)]:\n  - @effect/workflow@0.11.3\n\n## 0.50.2\n\n### Patch Changes\n\n- [#5590](https://github.com/Effect-TS/effect/pull/5590) [`f4c4702`](https://github.com/Effect-TS/effect/commit/f4c4702ab01900c42c0af4662dfb7a5973619646) Thanks @tim-smart! - add openTimeout options to NodeSocket.makeNet\n\n- Updated dependencies [[`f4c4702`](https://github.com/Effect-TS/effect/commit/f4c4702ab01900c42c0af4662dfb7a5973619646), [`f6987c0`](https://github.com/Effect-TS/effect/commit/f6987c04ebf1386dc37729dfea1631ce364a5a96)]:\n  - @effect/workflow@0.11.2\n  - @effect/platform@0.92.1\n\n## 0.50.1\n\n### Patch Changes\n\n- [#5585](https://github.com/Effect-TS/effect/pull/5585) [`cf17f2f`](https://github.com/Effect-TS/effect/commit/cf17f2f0319a57a886558b01549fea675cd78b69) Thanks @tim-smart! - keep socket error listener attached in NodeSocket\n\n- Updated dependencies [[`07802f7`](https://github.com/Effect-TS/effect/commit/07802f78fd410d800f0231129ee0866977399152), [`cf17f2f`](https://github.com/Effect-TS/effect/commit/cf17f2f0319a57a886558b01549fea675cd78b69)]:\n  - effect@3.18.1\n  - @effect/workflow@0.11.1\n\n## 0.50.0\n\n### Patch Changes\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2)]:\n  - effect@3.18.0\n  - @effect/platform@0.92.0\n  - @effect/rpc@0.71.0\n  - @effect/sql@0.46.0\n  - @effect/workflow@0.11.0\n\n## 0.49.6\n\n### Patch Changes\n\n- [#5581](https://github.com/Effect-TS/effect/pull/5581) [`dd7b459`](https://github.com/Effect-TS/effect/commit/dd7b4591b79ed88f3c0fcc607f9e42f22883f9bd) Thanks @tim-smart! - persist activity interrupts as \"Suspended\"\n\n- Updated dependencies [[`dd7b459`](https://github.com/Effect-TS/effect/commit/dd7b4591b79ed88f3c0fcc607f9e42f22883f9bd)]:\n  - @effect/rpc@0.70.2\n  - @effect/workflow@0.10.3\n\n## 0.49.5\n\n### Patch Changes\n\n- [#5577](https://github.com/Effect-TS/effect/pull/5577) [`c9e1e40`](https://github.com/Effect-TS/effect/commit/c9e1e4064cef4c4324318ec76b35bbbdc026dace) Thanks @tim-smart! - ignore non-client interrupts in workflow activities\n\n- Updated dependencies [[`c9e1e40`](https://github.com/Effect-TS/effect/commit/c9e1e4064cef4c4324318ec76b35bbbdc026dace)]:\n  - @effect/rpc@0.70.1\n  - @effect/workflow@0.10.2\n\n## 0.49.4\n\n### Patch Changes\n\n- [#5575](https://github.com/Effect-TS/effect/pull/5575) [`d0e97d7`](https://github.com/Effect-TS/effect/commit/d0e97d74a9e4d4a436ac8d148db81144cf872cc6) Thanks @tim-smart! - fix SqlMessageStorage last reply for sqlite\n\n- Updated dependencies [[`d0e97d7`](https://github.com/Effect-TS/effect/commit/d0e97d74a9e4d4a436ac8d148db81144cf872cc6)]:\n  - @effect/workflow@0.10.1\n\n## 0.49.3\n\n### Patch Changes\n\n- [#5563](https://github.com/Effect-TS/effect/pull/5563) [`fc7e32a`](https://github.com/Effect-TS/effect/commit/fc7e32af793214b542262f912a30c89f85068bb4) Thanks @tim-smart! - prevent EntityNotAssigned when sending to local runner\n\n## 0.49.2\n\n### Patch Changes\n\n- [#5561](https://github.com/Effect-TS/effect/pull/5561) [`1a9e601`](https://github.com/Effect-TS/effect/commit/1a9e60163d25da51294e7aaba33bbf0bde7fe231) Thanks @tim-smart! - optimize SqlShardStorage queries\n\n## 0.49.1\n\n### Patch Changes\n\n- [#5557](https://github.com/Effect-TS/effect/pull/5557) [`978b6ff`](https://github.com/Effect-TS/effect/commit/978b6ffc0b124d67d62a797211eff795f22cd1e6) Thanks @tim-smart! - allow NodeSocket.makeNet open to be interrupted\n\n## 0.49.0\n\n### Patch Changes\n\n- Updated dependencies [[`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a)]:\n  - @effect/platform@0.91.0\n  - @effect/rpc@0.70.0\n  - @effect/sql@0.45.0\n  - @effect/workflow@0.10.0\n\n## 0.48.16\n\n### Patch Changes\n\n- [#5543](https://github.com/Effect-TS/effect/pull/5543) [`2b9db9e`](https://github.com/Effect-TS/effect/commit/2b9db9e7f930d3ae269b123286c881ea34d3afca) Thanks @tim-smart! - propagate workflow interruption to unfinished children\n\n- Updated dependencies [[`2b9db9e`](https://github.com/Effect-TS/effect/commit/2b9db9e7f930d3ae269b123286c881ea34d3afca)]:\n  - @effect/workflow@0.9.6\n\n## 0.48.15\n\n### Patch Changes\n\n- [#5541](https://github.com/Effect-TS/effect/pull/5541) [`4f07ee0`](https://github.com/Effect-TS/effect/commit/4f07ee06e59fa81762761b12938224f5c931b119) Thanks @tim-smart! - backport MessageStorage.unregisterReplyHandler\n\n- Updated dependencies [[`ea95998`](https://github.com/Effect-TS/effect/commit/ea95998de2a7613d844c42e67e7f5b16652c5000)]:\n  - effect@3.17.14\n\n## 0.48.14\n\n### Patch Changes\n\n- [#5529](https://github.com/Effect-TS/effect/pull/5529) [`d9c8bce`](https://github.com/Effect-TS/effect/commit/d9c8bce027a45da82190303cc6eb6838074f4fb9) Thanks @tim-smart! - catch interruptions in Sharding storage loop\n\n## 0.48.13\n\n### Patch Changes\n\n- [#5527](https://github.com/Effect-TS/effect/pull/5527) [`e3dac95`](https://github.com/Effect-TS/effect/commit/e3dac9527ab8ff645c82b30ca2bba5a975b103df) Thanks @tim-smart! - attempt to prevent InterruptedException leaks into entity replies\n\n- Updated dependencies [[`e3dac95`](https://github.com/Effect-TS/effect/commit/e3dac9527ab8ff645c82b30ca2bba5a975b103df)]:\n  - @effect/rpc@0.69.4\n\n## 0.48.12\n\n### Patch Changes\n\n- [#5525](https://github.com/Effect-TS/effect/pull/5525) [`7edc074`](https://github.com/Effect-TS/effect/commit/7edc074f67d300957b749c9e20ea9706036dc0e0) Thanks @tim-smart! - backport ClusterWorkflowEngine partial entity clients\n\n## 0.48.11\n\n### Patch Changes\n\n- [#5519](https://github.com/Effect-TS/effect/pull/5519) [`92c533f`](https://github.com/Effect-TS/effect/commit/92c533fb52d6d3869728071e92596f80b4c7aa36) Thanks @tim-smart! - improve SqlMessageStorage insert queries\n\n## 0.48.10\n\n### Patch Changes\n\n- [#5517](https://github.com/Effect-TS/effect/pull/5517) [`de07e58`](https://github.com/Effect-TS/effect/commit/de07e5805496b80226ba6a5efc2b4c05e1aba4b8) Thanks @tim-smart! - backport cluster improvements from effect 4\n\n- Updated dependencies [[`de07e58`](https://github.com/Effect-TS/effect/commit/de07e5805496b80226ba6a5efc2b4c05e1aba4b8)]:\n  - @effect/platform@0.90.10\n  - @effect/rpc@0.69.3\n\n## 0.48.9\n\n### Patch Changes\n\n- [#5512](https://github.com/Effect-TS/effect/pull/5512) [`934c1d9`](https://github.com/Effect-TS/effect/commit/934c1d9517a7c8bcac1b362908fa474371f7f0fa) Thanks @tim-smart! - backport active shard latch changes from effect 4\n\n## 0.48.8\n\n### Patch Changes\n\n- [#5510](https://github.com/Effect-TS/effect/pull/5510) [`c2fed22`](https://github.com/Effect-TS/effect/commit/c2fed22a131fbd9ba54482af1886cc1e869a72cd) Thanks @tim-smart! - re-add two phase runner health check\n\n## 0.48.7\n\n### Patch Changes\n\n- [#5505](https://github.com/Effect-TS/effect/pull/5505) [`1c4b6ae`](https://github.com/Effect-TS/effect/commit/1c4b6ae81daf17bce1f67c0a0bc298dc4ce8f461) Thanks @tim-smart! - ensure ShardManager and Runner get fresh versions of the rpc protocol\n\n- [#5508](https://github.com/Effect-TS/effect/pull/5508) [`26d1267`](https://github.com/Effect-TS/effect/commit/26d12678b08ee3021f5529bed97b63377155a7fe) Thanks @tim-smart! - ensure runner detects when it has been externally unregistered\n\n## 0.48.6\n\n### Patch Changes\n\n- [#5501](https://github.com/Effect-TS/effect/pull/5501) [`a874567`](https://github.com/Effect-TS/effect/commit/a874567c59fa1b135268d8e86222a4afd693ae12) Thanks @tim-smart! - don't remove entities from map on shutdown\n\n## 0.48.5\n\n### Patch Changes\n\n- [#5486](https://github.com/Effect-TS/effect/pull/5486) [`85a60a0`](https://github.com/Effect-TS/effect/commit/85a60a0f06e596991dec1d64bdfccac8df880f84) Thanks @tim-smart! - add Workflow.poll api\n\n- Updated dependencies [[`85a60a0`](https://github.com/Effect-TS/effect/commit/85a60a0f06e596991dec1d64bdfccac8df880f84)]:\n  - @effect/workflow@0.9.4\n\n## 0.48.4\n\n### Patch Changes\n\n- [#5484](https://github.com/Effect-TS/effect/pull/5484) [`0a9ec23`](https://github.com/Effect-TS/effect/commit/0a9ec23dca104ac6fd7ea5841e98f5fa7796be40) Thanks @tim-smart! - fix multiple persisted requests subscribing to the same id\n\n- Updated dependencies [[`333be04`](https://github.com/Effect-TS/effect/commit/333be046b50e8300f5cb70b871448e0628b7b37c)]:\n  - @effect/platform@0.90.8\n\n## 0.48.3\n\n### Patch Changes\n\n- [#5472](https://github.com/Effect-TS/effect/pull/5472) [`fb00cd6`](https://github.com/Effect-TS/effect/commit/fb00cd6cf20da70592125c0c682225de51a977d5) Thanks @tim-smart! - ensure defects don't cause loops in ClusterCron\n\n## 0.48.2\n\n### Patch Changes\n\n- [#5415](https://github.com/Effect-TS/effect/pull/5415) [`4cb3af5`](https://github.com/Effect-TS/effect/commit/4cb3af5aeae8535a04f84fb0f64c3f2be19e2aed) Thanks @tim-smart! - fix rpc msgpack serialization when chunk contains partial frames\n\n- Updated dependencies [[`4cb3af5`](https://github.com/Effect-TS/effect/commit/4cb3af5aeae8535a04f84fb0f64c3f2be19e2aed)]:\n  - @effect/rpc@0.69.1\n  - @effect/workflow@0.9.2\n\n## 0.48.1\n\n### Patch Changes\n\n- [#5394](https://github.com/Effect-TS/effect/pull/5394) [`59547d9`](https://github.com/Effect-TS/effect/commit/59547d94dc625b19da62b5d1f3ddffa59efb0ff2) Thanks @tim-smart! - add DurableDeferred.withActivityAttempt, for scoping it to the current activity run\n\n- Updated dependencies [[`59547d9`](https://github.com/Effect-TS/effect/commit/59547d94dc625b19da62b5d1f3ddffa59efb0ff2)]:\n  - @effect/workflow@0.9.1\n\n## 0.48.0\n\n### Patch Changes\n\n- Updated dependencies [[`3e163b2`](https://github.com/Effect-TS/effect/commit/3e163b24cc2b647e25566ba29ef25c3f57609042)]:\n  - @effect/rpc@0.69.0\n  - @effect/workflow@0.9.0\n\n## 0.47.0\n\n### Minor Changes\n\n- [#5358](https://github.com/Effect-TS/effect/pull/5358) [`a949539`](https://github.com/Effect-TS/effect/commit/a94953971c2e908890dfda00f8560d317306c328) Thanks @tim-smart! - improve RunnerHealth by detecting if Runner is connected to the host\n\n### Patch Changes\n\n- Updated dependencies [[`a949539`](https://github.com/Effect-TS/effect/commit/a94953971c2e908890dfda00f8560d317306c328)]:\n  - effect@3.17.7\n\n## 0.46.4\n\n### Patch Changes\n\n- [#5350](https://github.com/Effect-TS/effect/pull/5350) [`d0b5fd1`](https://github.com/Effect-TS/effect/commit/d0b5fd1f7a292a47b9eeb058e5df57ace9a5ab14) Thanks @tim-smart! - add Migrator.fromRecord api\n\n- Updated dependencies [[`d0b5fd1`](https://github.com/Effect-TS/effect/commit/d0b5fd1f7a292a47b9eeb058e5df57ace9a5ab14)]:\n  - @effect/sql@0.44.1\n  - @effect/workflow@0.8.3\n\n## 0.46.3\n\n### Patch Changes\n\n- [#5345](https://github.com/Effect-TS/effect/pull/5345) [`58d56d5`](https://github.com/Effect-TS/effect/commit/58d56d549fa49d6d06cfedb975a046872ac44f85) Thanks @tim-smart! - increase size of entity_type on cluster_messages table\n\n- [#5345](https://github.com/Effect-TS/effect/pull/5345) [`58d56d5`](https://github.com/Effect-TS/effect/commit/58d56d549fa49d6d06cfedb975a046872ac44f85) Thanks @tim-smart! - log defects in Entity & Workflow proxy for HttpApi endpoints\n\n- Updated dependencies [[`58d56d5`](https://github.com/Effect-TS/effect/commit/58d56d549fa49d6d06cfedb975a046872ac44f85)]:\n  - @effect/workflow@0.8.2\n\n## 0.46.2\n\n### Patch Changes\n\n- [#5297](https://github.com/Effect-TS/effect/pull/5297) [`eedbab5`](https://github.com/Effect-TS/effect/commit/eedbab5a02f6752acbd835bfeff338b1fd7c0deb) Thanks @tim-smart! - Remove retry from ClusterCron in favour of user supplied retry\n\n## 0.46.1\n\n### Patch Changes\n\n- [#5283](https://github.com/Effect-TS/effect/pull/5283) [`de92b1c`](https://github.com/Effect-TS/effect/commit/de92b1c46a57761df9dd46e59e42d5a54beb6e34) Thanks @tim-smart! - disable tracing for ClusterCron client to disconnect parent span\n\n## 0.46.0\n\n### Patch Changes\n\n- Updated dependencies [[`5a0f4f1`](https://github.com/Effect-TS/effect/commit/5a0f4f176687a39d9fa46bb894bb7ac3175b0e87), [`e9cbd26`](https://github.com/Effect-TS/effect/commit/e9cbd2673401723aa811b0535202e4f57baf6d2c)]:\n  - effect@3.17.1\n  - @effect/rpc@0.68.0\n  - @effect/workflow@0.8.0\n\n## 0.45.0\n\n### Patch Changes\n\n- Updated dependencies [[`7813640`](https://github.com/Effect-TS/effect/commit/7813640279d9e3a3e7fc0a29bfb5c6d5fb3c270f)]:\n  - @effect/platform@0.90.0\n  - @effect/rpc@0.67.0\n  - @effect/sql@0.44.0\n  - @effect/workflow@0.7.0\n\n## 0.44.0\n\n### Patch Changes\n\n- Updated dependencies [[`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9), [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104), [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63), [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c), [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989), [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636), [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2), [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d)]:\n  - effect@3.17.0\n  - @effect/platform@0.89.0\n  - @effect/rpc@0.66.0\n  - @effect/sql@0.43.0\n  - @effect/workflow@0.6.0\n\n## 0.43.1\n\n### Patch Changes\n\n- [#5232](https://github.com/Effect-TS/effect/pull/5232) [`4ffbd67`](https://github.com/Effect-TS/effect/commit/4ffbd674af526059f983e20f2f00ee6699c7b956) Thanks @tim-smart! - retry RunnerHealth ping to relax down conditions\n\n## 0.43.0\n\n### Patch Changes\n\n- [#5211](https://github.com/Effect-TS/effect/pull/5211) [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48) Thanks @mattiamanzati! - Removed some unnecessary single-arg pipe calls\n\n- Updated dependencies [[`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec), [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38), [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48)]:\n  - effect@3.16.14\n  - @effect/sql@0.42.0\n  - @effect/platform@0.88.1\n  - @effect/rpc@0.65.1\n  - @effect/workflow@0.5.1\n\n## 0.42.0\n\n### Patch Changes\n\n- Updated dependencies [[`27206d7`](https://github.com/Effect-TS/effect/commit/27206d7f0558d7fe28de57bf54f1d0cc83acc92e), [`dbabf5e`](https://github.com/Effect-TS/effect/commit/dbabf5e76fa63b050d2b6c466713c7dc59f07d3c)]:\n  - @effect/platform@0.88.0\n  - @effect/rpc@0.65.0\n  - @effect/sql@0.41.0\n  - @effect/workflow@0.5.0\n\n## 0.41.18\n\n### Patch Changes\n\n- Updated dependencies [[`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7), [`5b7cd92`](https://github.com/Effect-TS/effect/commit/5b7cd923e786c38a0802faf0fe75498ab3cccf28), [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db)]:\n  - effect@3.16.13\n  - @effect/rpc@0.64.14\n  - @effect/platform@0.87.13\n  - @effect/sql@0.40.14\n  - @effect/workflow@0.4.14\n\n## 0.41.17\n\n### Patch Changes\n\n- [#5196](https://github.com/Effect-TS/effect/pull/5196) [`56b33c3`](https://github.com/Effect-TS/effect/commit/56b33c357cfc5f8976486f48e93032058c02d876) Thanks @tim-smart! - add discard methods to cluster EntityProxy's\n\n## 0.41.16\n\n### Patch Changes\n\n- Updated dependencies [[`ad6e968`](https://github.com/Effect-TS/effect/commit/ad6e9688d78db27a80396ad79d376bb7eaf668bf), [`32ba77a`](https://github.com/Effect-TS/effect/commit/32ba77ae304d2161362a73e8b61965332626cf2d), [`d5e25b2`](https://github.com/Effect-TS/effect/commit/d5e25b237f05670ee42b386cb40b2cb448fc11d7), [`a28efb8`](https://github.com/Effect-TS/effect/commit/a28efb8913d9a7ac65c1cb783b17f382b185f8be)]:\n  - @effect/workflow@0.4.13\n  - @effect/platform@0.87.12\n  - @effect/rpc@0.64.13\n  - @effect/sql@0.40.13\n\n## 0.41.15\n\n### Patch Changes\n\n- Updated dependencies [[`79a1947`](https://github.com/Effect-TS/effect/commit/79a1947359cbd89a47ea315cdd86a3d250f28f43), [`001392b`](https://github.com/Effect-TS/effect/commit/001392ba8bfcad101bb034348a7415012fb12f72), [`7bfb099`](https://github.com/Effect-TS/effect/commit/7bfb099cb5528511b8d63045c4fbb4dc9cb18528)]:\n  - @effect/rpc@0.64.12\n  - @effect/platform@0.87.11\n  - @effect/workflow@0.4.12\n  - @effect/sql@0.40.12\n\n## 0.41.14\n\n### Patch Changes\n\n- Updated dependencies [[`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0), [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0)]:\n  - @effect/platform@0.87.10\n  - @effect/rpc@0.64.11\n  - @effect/sql@0.40.11\n  - @effect/workflow@0.4.11\n\n## 0.41.13\n\n### Patch Changes\n\n- Updated dependencies [[`54514a2`](https://github.com/Effect-TS/effect/commit/54514a2f53166de27ad7e756dbf12194691fd4af)]:\n  - @effect/platform@0.87.9\n  - @effect/rpc@0.64.10\n  - @effect/sql@0.40.10\n  - @effect/workflow@0.4.10\n\n## 0.41.12\n\n### Patch Changes\n\n- Updated dependencies [[`4ce4f82`](https://github.com/Effect-TS/effect/commit/4ce4f824f6fdef492be1d35c05a490ffce518c89)]:\n  - @effect/platform@0.87.8\n  - @effect/rpc@0.64.9\n  - @effect/sql@0.40.9\n  - @effect/workflow@0.4.9\n\n## 0.41.11\n\n### Patch Changes\n\n- Updated dependencies [[`a9b617f`](https://github.com/Effect-TS/effect/commit/a9b617f125171ed76cd79ab46d7a924daf3b0e70), [`7e26e86`](https://github.com/Effect-TS/effect/commit/7e26e86524abcc93713d6ad7eee486638c98f7c2)]:\n  - @effect/platform@0.87.7\n  - @effect/rpc@0.64.8\n  - @effect/sql@0.40.8\n  - @effect/workflow@0.4.8\n\n## 0.41.10\n\n### Patch Changes\n\n- Updated dependencies [[`905da99`](https://github.com/Effect-TS/effect/commit/905da996aad665057b4ca6dba1a4af44fb8835bd)]:\n  - effect@3.16.12\n  - @effect/platform@0.87.6\n  - @effect/rpc@0.64.7\n  - @effect/sql@0.40.7\n  - @effect/workflow@0.4.7\n\n## 0.41.9\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.40.6\n\n## 0.41.8\n\n### Patch Changes\n\n- Updated dependencies [[`2fd8676`](https://github.com/Effect-TS/effect/commit/2fd8676c803cd40000dfc3231f5daecaa0e0ebd2)]:\n  - @effect/platform@0.87.5\n  - @effect/rpc@0.64.6\n  - @effect/sql@0.40.5\n  - @effect/workflow@0.4.6\n\n## 0.41.7\n\n### Patch Changes\n\n- [#5140](https://github.com/Effect-TS/effect/pull/5140) [`b01d2e0`](https://github.com/Effect-TS/effect/commit/b01d2e0d591418e10e9e362698205d848e97a9b7) Thanks @tim-smart! - remove dynamic cluster metrics that could cause memory leaks\n\n## 0.41.6\n\n### Patch Changes\n\n- [#5139](https://github.com/Effect-TS/effect/pull/5139) [`7fdc16b`](https://github.com/Effect-TS/effect/commit/7fdc16bd88b872f5918384e4acda3731aab018da) Thanks @tim-smart! - only register new runners if they are not present in the ShardManager state\n\n- Updated dependencies [[`e82a4fd`](https://github.com/Effect-TS/effect/commit/e82a4fd60f6528d08cef1a4aba0abe0d3ba741ad)]:\n  - @effect/platform@0.87.4\n  - @effect/rpc@0.64.5\n  - @effect/sql@0.40.4\n  - @effect/workflow@0.4.5\n\n## 0.41.5\n\n### Patch Changes\n\n- Updated dependencies [[`1b6e396`](https://github.com/Effect-TS/effect/commit/1b6e396d699f3cbbc56b68f99055cf746529bb9e), [`46c3216`](https://github.com/Effect-TS/effect/commit/46c321657d93393506278327418e36f8e7a77f86)]:\n  - @effect/platform@0.87.3\n  - @effect/sql@0.40.3\n  - @effect/rpc@0.64.4\n  - @effect/workflow@0.4.4\n\n## 0.41.4\n\n### Patch Changes\n\n- Updated dependencies [[`4fea68c`](https://github.com/Effect-TS/effect/commit/4fea68ca7a25a3c39a1ab68b3885534513ab0c81), [`b927954`](https://github.com/Effect-TS/effect/commit/b9279543cf5688dd8a577af80456959c615217d0), [`99590a6`](https://github.com/Effect-TS/effect/commit/99590a6ca9128eb1ede265b6670b655311995614), [`6c3e24c`](https://github.com/Effect-TS/effect/commit/6c3e24c2308f7d4a29b8f4270ab81bca22ac6bb4)]:\n  - @effect/platform@0.87.2\n  - effect@3.16.11\n  - @effect/rpc@0.64.3\n  - @effect/sql@0.40.2\n  - @effect/workflow@0.4.3\n\n## 0.41.3\n\n### Patch Changes\n\n- Updated dependencies [[`faad30e`](https://github.com/Effect-TS/effect/commit/faad30ec8742916be59f9db642d0fc98225b636c)]:\n  - effect@3.16.10\n  - @effect/platform@0.87.1\n  - @effect/rpc@0.64.2\n  - @effect/sql@0.40.1\n  - @effect/workflow@0.4.2\n\n## 0.41.2\n\n### Patch Changes\n\n- Updated dependencies [[`112a93a`](https://github.com/Effect-TS/effect/commit/112a93a9bab73e95e79f7b3502d1a7b1acd668fc)]:\n  - @effect/rpc@0.64.1\n  - @effect/workflow@0.4.1\n\n## 0.41.1\n\n### Patch Changes\n\n- [#5091](https://github.com/Effect-TS/effect/pull/5091) [`d5fd2c1`](https://github.com/Effect-TS/effect/commit/d5fd2c1526f06228853ed8317d9688c4af5f285a) Thanks @tim-smart! - fix unwrapping of DurableDeferred results\n\n- [#5089](https://github.com/Effect-TS/effect/pull/5089) [`9d189d7`](https://github.com/Effect-TS/effect/commit/9d189d744aa3307e055094c66f580453d95ff99d) Thanks @tim-smart! - propagate fiber refs to workflow activities\n\n## 0.41.0\n\n### Minor Changes\n\n- [#5086](https://github.com/Effect-TS/effect/pull/5086) [`867919c`](https://github.com/Effect-TS/effect/commit/867919c8be9a2f770699c0db852a3f566017ffd6) Thanks @tim-smart! - add Type generic to cluster entities\n\n### Patch Changes\n\n- Updated dependencies [[`b5bac9a`](https://github.com/Effect-TS/effect/commit/b5bac9ac2913fcd11b02322624f03b544eef53ba)]:\n  - @effect/rpc@0.64.0\n  - @effect/platform@0.87.0\n  - @effect/workflow@0.4.0\n  - @effect/sql@0.40.0\n\n## 0.40.0\n\n### Patch Changes\n\n- Updated dependencies [[`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`c23d25c`](https://github.com/Effect-TS/effect/commit/c23d25c3e7c541f1f63b28484d8c461d86c67e99), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07)]:\n  - effect@3.16.9\n  - @effect/platform@0.86.0\n  - @effect/rpc@0.63.0\n  - @effect/sql@0.39.0\n  - @effect/workflow@0.3.0\n\n## 0.39.5\n\n### Patch Changes\n\n- [#5070](https://github.com/Effect-TS/effect/pull/5070) [`ff90206`](https://github.com/Effect-TS/effect/commit/ff90206fc56f5c1eb1675603652462a83a27421d) Thanks @tim-smart! - use FIFO queue for shard assignment, to reduce churn\n\n## 0.39.4\n\n### Patch Changes\n\n- Updated dependencies [[`a8d99b2`](https://github.com/Effect-TS/effect/commit/a8d99b2ec2f55d9aa6e7d00a5138e80380716877)]:\n  - @effect/rpc@0.62.4\n  - @effect/workflow@0.2.4\n\n## 0.39.3\n\n### Patch Changes\n\n- Updated dependencies [[`914a191`](https://github.com/Effect-TS/effect/commit/914a191e7cb6341a3d0e965bccd27c336cf22e44)]:\n  - @effect/platform@0.85.2\n  - @effect/rpc@0.62.3\n  - @effect/sql@0.38.2\n  - @effect/workflow@0.2.3\n\n## 0.39.2\n\n### Patch Changes\n\n- Updated dependencies [[`ddfd1e4`](https://github.com/Effect-TS/effect/commit/ddfd1e43db60e3b779d18a221344423c5f3c7416)]:\n  - @effect/rpc@0.62.2\n  - @effect/workflow@0.2.2\n\n## 0.39.1\n\n### Patch Changes\n\n- Updated dependencies [[`8cb98d5`](https://github.com/Effect-TS/effect/commit/8cb98d53e68330228287ce2a2e0d8a4c86bcab3b), [`db2dd3c`](https://github.com/Effect-TS/effect/commit/db2dd3c3a8a77d791eae19e66153527e1cde4e6e)]:\n  - effect@3.16.8\n  - @effect/platform@0.85.1\n  - @effect/rpc@0.62.1\n  - @effect/sql@0.38.1\n  - @effect/workflow@0.2.1\n\n## 0.39.0\n\n### Patch Changes\n\n- [#5044](https://github.com/Effect-TS/effect/pull/5044) [`b7cc5c7`](https://github.com/Effect-TS/effect/commit/b7cc5c7b6b012f1c90458ce8d83ae287ea58a3d1) Thanks @tim-smart! - simplify and increase rebalance rate for ShardManager\n\n- Updated dependencies [[`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e)]:\n  - @effect/platform@0.85.0\n  - @effect/rpc@0.62.0\n  - @effect/sql@0.38.0\n  - @effect/workflow@0.2.0\n\n## 0.38.16\n\n### Patch Changes\n\n- [#5036](https://github.com/Effect-TS/effect/pull/5036) [`cbac1ac`](https://github.com/Effect-TS/effect/commit/cbac1ac61a4e15ad15828563b39eef412bcee66e) Thanks @tim-smart! - add .of helpers to RpcGroup, Entity and AiToolkit\n\n- Updated dependencies [[`1bb0d8a`](https://github.com/Effect-TS/effect/commit/1bb0d8ab96782e99434356266b38251554ea0294), [`cbac1ac`](https://github.com/Effect-TS/effect/commit/cbac1ac61a4e15ad15828563b39eef412bcee66e)]:\n  - effect@3.16.7\n  - @effect/rpc@0.61.15\n  - @effect/platform@0.84.11\n  - @effect/sql@0.37.12\n  - @effect/workflow@0.1.14\n\n## 0.38.15\n\n### Patch Changes\n\n- Updated dependencies [[`a5f7595`](https://github.com/Effect-TS/effect/commit/a5f75956ef9a15a83c416517ef493f0ee2f5ee8a), [`a02470c`](https://github.com/Effect-TS/effect/commit/a02470c75579e91525a25adb3f21b3650d042fdd), [`bf369b2`](https://github.com/Effect-TS/effect/commit/bf369b2902a0e0b195d957c18b9efd180942cf8b), [`f891d45`](https://github.com/Effect-TS/effect/commit/f891d45adffdafd3f94a2eca23faa354e3a409a8)]:\n  - effect@3.16.6\n  - @effect/platform@0.84.10\n  - @effect/rpc@0.61.14\n  - @effect/sql@0.37.11\n  - @effect/workflow@0.1.13\n\n## 0.38.14\n\n### Patch Changes\n\n- Updated dependencies [[`ee3a197`](https://github.com/Effect-TS/effect/commit/ee3a1973f54d7611ae99979edfed3020e94e1126), [`ee3a197`](https://github.com/Effect-TS/effect/commit/ee3a1973f54d7611ae99979edfed3020e94e1126)]:\n  - @effect/rpc@0.61.13\n  - @effect/workflow@0.1.12\n\n## 0.38.13\n\n### Patch Changes\n\n- Updated dependencies [[`e0d3d42`](https://github.com/Effect-TS/effect/commit/e0d3d424d8f4e6a8ada017160406991f02b3c068)]:\n  - @effect/rpc@0.61.12\n  - @effect/workflow@0.1.11\n\n## 0.38.12\n\n### Patch Changes\n\n- [#4750](https://github.com/Effect-TS/effect/pull/4750) [`dca92fd`](https://github.com/Effect-TS/effect/commit/dca92fd8cf41f07561f55d863def5a9f62275f53) Thanks @tim-smart! - add disableFatalDefects option to cluster entities\n\n- Updated dependencies [[`dca92fd`](https://github.com/Effect-TS/effect/commit/dca92fd8cf41f07561f55d863def5a9f62275f53), [`dca92fd`](https://github.com/Effect-TS/effect/commit/dca92fd8cf41f07561f55d863def5a9f62275f53)]:\n  - @effect/rpc@0.61.11\n  - @effect/workflow@0.1.10\n\n## 0.38.11\n\n### Patch Changes\n\n- [#5017](https://github.com/Effect-TS/effect/pull/5017) [`cc283b9`](https://github.com/Effect-TS/effect/commit/cc283b968235da3caf6c3e3a09b525fe09618fee) Thanks @tim-smart! - add more spans to ClusterWorkflowEngine\n\n- Updated dependencies [[`d350176`](https://github.com/Effect-TS/effect/commit/d3501768d42d7ff3ebc2d414c95cc1fcce15894a)]:\n  - @effect/workflow@0.1.9\n\n## 0.38.10\n\n### Patch Changes\n\n- [#5016](https://github.com/Effect-TS/effect/pull/5016) [`6e2e886`](https://github.com/Effect-TS/effect/commit/6e2e886f060c4ac057926b68d2e441c279480c30) Thanks @tim-smart! - fix ShardManager metrics\n\n- Updated dependencies [[`bf418ef`](https://github.com/Effect-TS/effect/commit/bf418ef14a0f2ec965535793d5cea8fa8ba177ac)]:\n  - effect@3.16.5\n  - @effect/platform@0.84.9\n  - @effect/rpc@0.61.10\n  - @effect/sql@0.37.10\n  - @effect/workflow@0.1.8\n\n## 0.38.9\n\n### Patch Changes\n\n- Updated dependencies [[`7bf6cb9`](https://github.com/Effect-TS/effect/commit/7bf6cb943810e403f472a901ed29ccbbf76a46b2), [`7bf6cb9`](https://github.com/Effect-TS/effect/commit/7bf6cb943810e403f472a901ed29ccbbf76a46b2)]:\n  - @effect/rpc@0.61.9\n  - @effect/workflow@0.1.7\n\n## 0.38.8\n\n### Patch Changes\n\n- Updated dependencies [[`2a9a0ef`](https://github.com/Effect-TS/effect/commit/2a9a0ef1181a4419e239edb2abfd95f359a4b7f7)]:\n  - @effect/workflow@0.1.6\n\n## 0.38.7\n\n### Patch Changes\n\n- [#4999](https://github.com/Effect-TS/effect/pull/4999) [`22166f8`](https://github.com/Effect-TS/effect/commit/22166f80c677cad6b4719e0e0253a9d06f964626) Thanks @tim-smart! - make registerEntity a no-op on clientOnly cluster\n\n## 0.38.6\n\n### Patch Changes\n\n- Updated dependencies [[`8b9db77`](https://github.com/Effect-TS/effect/commit/8b9db7742846af0f58fd8e8b7acb7f4f5ff487ec)]:\n  - @effect/platform@0.84.8\n  - @effect/rpc@0.61.8\n  - @effect/sql@0.37.9\n  - @effect/workflow@0.1.5\n\n## 0.38.5\n\n### Patch Changes\n\n- Updated dependencies [[`34333ab`](https://github.com/Effect-TS/effect/commit/34333ab08de42a5269ddb13f66de1536ad6f249f), [`74ab9a0`](https://github.com/Effect-TS/effect/commit/74ab9a0a9e16d6e019369d256e1e24175c8bc3f3), [`770008e`](https://github.com/Effect-TS/effect/commit/770008eca3aad2899a2ed951236e575793294b28), [`34333ab`](https://github.com/Effect-TS/effect/commit/34333ab08de42a5269ddb13f66de1536ad6f249f)]:\n  - @effect/workflow@0.1.4\n  - effect@3.16.4\n  - @effect/platform@0.84.7\n  - @effect/rpc@0.61.7\n  - @effect/sql@0.37.8\n\n## 0.38.4\n\n### Patch Changes\n\n- [#4984](https://github.com/Effect-TS/effect/pull/4984) [`7e59d0e`](https://github.com/Effect-TS/effect/commit/7e59d0e2e004d86b8d0778e99c6fcd173fcb682a) Thanks @tim-smart! - expose Sharding.pollStorage api\n\n## 0.38.3\n\n### Patch Changes\n\n- [#4983](https://github.com/Effect-TS/effect/pull/4983) [`59575c5`](https://github.com/Effect-TS/effect/commit/59575c5bf17a32c8b76c42e3794222b20e766581) Thanks @tim-smart! - do not resume already running workflows\n\n- Updated dependencies []:\n  - @effect/sql@0.37.7\n\n## 0.38.2\n\n### Patch Changes\n\n- [#4977](https://github.com/Effect-TS/effect/pull/4977) [`d244b63`](https://github.com/Effect-TS/effect/commit/d244b6345ea1d2ac88812562b0c170683913d502) Thanks @tim-smart! - add EntityProxy & EntityProxyServer, for deriving Rpc & HttpApi servers from cluster entities\n\n- Updated dependencies [[`d244b63`](https://github.com/Effect-TS/effect/commit/d244b6345ea1d2ac88812562b0c170683913d502), [`ceea77a`](https://github.com/Effect-TS/effect/commit/ceea77a13055f145520f763e3fce5b8ff15d728f)]:\n  - @effect/workflow@0.1.3\n  - @effect/platform@0.84.6\n  - @effect/rpc@0.61.6\n  - @effect/sql@0.37.6\n\n## 0.38.1\n\n### Patch Changes\n\n- [#4973](https://github.com/Effect-TS/effect/pull/4973) [`612c739`](https://github.com/Effect-TS/effect/commit/612c73979abc44825feae573c8902b6484923aaa) Thanks @tim-smart! - ignore runners that cannot be parsed\n\n## 0.38.0\n\n### Minor Changes\n\n- [#4969](https://github.com/Effect-TS/effect/pull/4969) [`3086405`](https://github.com/Effect-TS/effect/commit/308640563041004d790f08d2ba75cc3a85fdf752) Thanks @tim-smart! - add shard groups, to allow entities to target specific runners\n\n  If you need to migrate an existing cluster, you can run the following PostgreSQL queries:\n\n  ```sql\n  ALTER TABLE cluster_messages\n    ALTER COLUMN shard_id TYPE VARCHAR(50) USING format('default:%s', shard_id);\n\n  ALTER TABLE cluster_shards\n    ALTER COLUMN shard_id TYPE VARCHAR(50) USING format('default:%s', shard_id);\n\n  ALTER TABLE cluster_locks\n    ALTER COLUMN shard_id TYPE VARCHAR(50) USING format('default:%s', shard_id);\n  ```\n\n  To use shard groups, you can add a `ShardGroup` annotation when creating an\n  entity. You can then assign shard groups to specific runners in your layer\n  setup:\n\n  ```typescript\n  import { ClusterSchema, Entity } from \"@effect/cluster\"\n  import {\n    NodeClusterRunnerSocket,\n    NodeClusterShardManagerSocket\n  } from \"@effect/platform-node\"\n  import { Rpc } from \"@effect/rpc\"\n  import { Schema } from \"effect\"\n\n  const Counter = Entity.make(\"Counter\", [\n    Rpc.make(\"Increment\", {\n      payload: { id: Schema.String, amount: Schema.Number },\n      primaryKey: ({ id }) => id,\n      success: Schema.Number\n    })\n  ])\n    .annotate(ClusterSchema.ShardGroup, (_entityId) => \"someGroupName\")\n    .annotateRpcs(ClusterSchema.Persisted, true)\n\n  // Assign the shard group to a specific runner in your layer setup.\n  //\n  // Make sure to include the \"default\" shard group, if you want to run entities\n  // without a specific group.\n  //\n  NodeClusterRunnerSocket.layer({\n    shardingConfig: {\n      shardGroups: [\"default\", \"someGroupName\"]\n    }\n  })\n  ```\n\n### Patch Changes\n\n- [#4972](https://github.com/Effect-TS/effect/pull/4972) [`d0067ca`](https://github.com/Effect-TS/effect/commit/d0067caef053b2855d93dcef59ea585d0fad9d8c) Thanks @tim-smart! - optimize for requests with a WithExit reply\n\n- [#4966](https://github.com/Effect-TS/effect/pull/4966) [`8c79abe`](https://github.com/Effect-TS/effect/commit/8c79abeb47d070d8880b652d31626497d3005a4e) Thanks @tim-smart! - add ClusterCron module\n\n- Updated dependencies [[`ec52c6a`](https://github.com/Effect-TS/effect/commit/ec52c6a2211e76972462b15b9d5a9d6d56761b7a), [`71e1e6c`](https://github.com/Effect-TS/effect/commit/71e1e6c535c11a3ec498540a3af3c1a313a5319b)]:\n  - @effect/platform@0.84.5\n  - @effect/rpc@0.61.5\n  - @effect/sql@0.37.5\n\n## 0.37.2\n\n### Patch Changes\n\n- [#4958](https://github.com/Effect-TS/effect/pull/4958) [`6dfbae9`](https://github.com/Effect-TS/effect/commit/6dfbae946ea12ecee7234f5785335f3e7f8335b4) Thanks @tim-smart! - ensure Workflow.interrupt triggers compensation\n\n- Updated dependencies [[`b8aec45`](https://github.com/Effect-TS/effect/commit/b8aec45288834c499caeb3478a634ea5043fd611), [`b8aec45`](https://github.com/Effect-TS/effect/commit/b8aec45288834c499caeb3478a634ea5043fd611)]:\n  - @effect/workflow@0.1.2\n\n## 0.37.1\n\n### Patch Changes\n\n- Updated dependencies [[`fd60c73`](https://github.com/Effect-TS/effect/commit/fd60c73ea6d51c9b83279da60e7b6d605698b1d8)]:\n  - @effect/workflow@0.1.1\n\n## 0.37.0\n\n### Patch Changes\n\n- [#4945](https://github.com/Effect-TS/effect/pull/4945) [`a116aea`](https://github.com/Effect-TS/effect/commit/a116aeade97c83d8c96f17cdc5cf3b5a0bd9be74) Thanks @tim-smart! - add @effect/workflow package\n\n- Updated dependencies [[`87722fc`](https://github.com/Effect-TS/effect/commit/87722fce693a9b49284bbddbf82d30714c688261), [`36217ee`](https://github.com/Effect-TS/effect/commit/36217eeb1337edd9ac3f9a635b80a6385d22ae8f), [`a116aea`](https://github.com/Effect-TS/effect/commit/a116aeade97c83d8c96f17cdc5cf3b5a0bd9be74), [`a116aea`](https://github.com/Effect-TS/effect/commit/a116aeade97c83d8c96f17cdc5cf3b5a0bd9be74)]:\n  - effect@3.16.3\n  - @effect/rpc@0.61.4\n  - @effect/workflow@0.1.0\n  - @effect/platform@0.84.4\n  - @effect/sql@0.37.4\n\n## 0.36.3\n\n### Patch Changes\n\n- Updated dependencies [[`ab7684f`](https://github.com/Effect-TS/effect/commit/ab7684f1c2a0671bf091f255d220e3a4cc7f528e)]:\n  - @effect/platform@0.84.3\n  - @effect/rpc@0.61.3\n  - @effect/sql@0.37.3\n\n## 0.36.2\n\n### Patch Changes\n\n- Updated dependencies [[`0ddf148`](https://github.com/Effect-TS/effect/commit/0ddf148a247aa87af043d276b8453a714a400897), [`a77afb1`](https://github.com/Effect-TS/effect/commit/a77afb1f7191a57a68b09fcdee5e9f27a0682b0a)]:\n  - effect@3.16.2\n  - @effect/rpc@0.61.2\n  - @effect/platform@0.84.2\n  - @effect/sql@0.37.2\n\n## 0.36.1\n\n### Patch Changes\n\n- Updated dependencies [[`71174d0`](https://github.com/Effect-TS/effect/commit/71174d09691314a9b6b66189e456fd21e3eb6543), [`d615e6e`](https://github.com/Effect-TS/effect/commit/d615e6e5b944f6fd5e627e31752c7ca7e4e1c17d)]:\n  - @effect/platform@0.84.1\n  - effect@3.16.1\n  - @effect/rpc@0.61.1\n  - @effect/sql@0.37.1\n\n## 0.36.0\n\n### Patch Changes\n\n- Updated dependencies [[`ee0bd5d`](https://github.com/Effect-TS/effect/commit/ee0bd5d24864752c54cb359f67a67dd903971ec4), [`5189800`](https://github.com/Effect-TS/effect/commit/51898004e11766b8cf6d95e960b636f6d5db79ec), [`58bfeaa`](https://github.com/Effect-TS/effect/commit/58bfeaa64ded8c88f772b184311c0c0dbac10960), [`194d748`](https://github.com/Effect-TS/effect/commit/194d7486943f56f3267ef415395ac220a4b3e634), [`918c9ea`](https://github.com/Effect-TS/effect/commit/918c9ea1a57facb154f0fb26792021f337054dee), [`9198e6f`](https://github.com/Effect-TS/effect/commit/9198e6fcc1a3ff4fefb3363004de558d8de01f40), [`2a370bf`](https://github.com/Effect-TS/effect/commit/2a370bf625fdeede5659721468eb0d527e403279), [`58ccb91`](https://github.com/Effect-TS/effect/commit/58ccb91328c8df5d49808b673738bc09df355201), [`fd47834`](https://github.com/Effect-TS/effect/commit/fd478348203fa89462b0a1d067ce4de034353df4)]:\n  - effect@3.16.0\n  - @effect/platform@0.84.0\n  - @effect/rpc@0.61.0\n  - @effect/sql@0.37.0\n\n## 0.35.0\n\n### Patch Changes\n\n- Updated dependencies [[`5522520`](https://github.com/Effect-TS/effect/commit/55225206ab9af0ad60b1c0654690a8a096d625cd), [`cc5bb2b`](https://github.com/Effect-TS/effect/commit/cc5bb2b918a9450a975f702dabcea891bda382cb)]:\n  - @effect/platform@0.83.0\n  - effect@3.15.5\n  - @effect/rpc@0.60.0\n  - @effect/sql@0.36.0\n\n## 0.34.5\n\n### Patch Changes\n\n- [#4929](https://github.com/Effect-TS/effect/pull/4929) [`58c5fd3`](https://github.com/Effect-TS/effect/commit/58c5fd3dd30eceb6c8afea90406768b0e348f48f) Thanks @tim-smart! - disable tracing for internal sql queries\n\n- Updated dependencies [[`0617b9d`](https://github.com/Effect-TS/effect/commit/0617b9dc365f1963b36949ad7f9023ab6eb94524)]:\n  - @effect/platform@0.82.8\n  - @effect/rpc@0.59.9\n  - @effect/sql@0.35.8\n\n## 0.34.4\n\n### Patch Changes\n\n- Updated dependencies [[`f570554`](https://github.com/Effect-TS/effect/commit/f57055459524587b041340577dad85476bb35f81), [`78047e8`](https://github.com/Effect-TS/effect/commit/78047e8dfc8005b66f87afe50bb95981fea51561), [`c20b95a`](https://github.com/Effect-TS/effect/commit/c20b95a99ffe452b4774c844d397a905f713b6d6), [`94ada43`](https://github.com/Effect-TS/effect/commit/94ada430928d5685bdbef513e87562c20774a3a2)]:\n  - effect@3.15.4\n  - @effect/platform@0.82.7\n  - @effect/rpc@0.59.8\n  - @effect/sql@0.35.7\n\n## 0.34.3\n\n### Patch Changes\n\n- Updated dependencies [[`618903b`](https://github.com/Effect-TS/effect/commit/618903ba9ae96e2bfe6ee31f61c4359b915f2a36)]:\n  - @effect/platform@0.82.6\n  - @effect/rpc@0.59.7\n  - @effect/sql@0.35.6\n\n## 0.34.2\n\n### Patch Changes\n\n- Updated dependencies [[`7764a07`](https://github.com/Effect-TS/effect/commit/7764a07d960c60df81f14e1dc949518f4bbe494a), [`4577f54`](https://github.com/Effect-TS/effect/commit/4577f548d67273e576cdde423bdd34a4b910766a), [`30a0d9c`](https://github.com/Effect-TS/effect/commit/30a0d9cb51c84290d51b1361d72ff5cee33c13c7)]:\n  - @effect/platform@0.82.5\n  - effect@3.15.3\n  - @effect/rpc@0.59.6\n  - @effect/sql@0.35.5\n\n## 0.34.1\n\n### Patch Changes\n\n- [#4906](https://github.com/Effect-TS/effect/pull/4906) [`1627a02`](https://github.com/Effect-TS/effect/commit/1627a0299a07c3538ca15293f1ac3ffa7eeb45f3) Thanks @tim-smart! - add Entity.makeTestClient, for testing entity handlers\n\n- Updated dependencies [[`d45e8a8`](https://github.com/Effect-TS/effect/commit/d45e8a8ac8227192f504e39e6d04fdcf4fb1d225), [`89657ac`](https://github.com/Effect-TS/effect/commit/89657ac2fbda9ba38ac2962ce96949e536a464f9), [`d13b68e`](https://github.com/Effect-TS/effect/commit/d13b68e3a9456d0bfee9bca8273a7b44a9c69087)]:\n  - @effect/platform@0.82.4\n  - @effect/sql@0.35.4\n  - @effect/rpc@0.59.5\n\n## 0.34.0\n\n### Minor Changes\n\n- [#4883](https://github.com/Effect-TS/effect/pull/4883) [`eaf8405`](https://github.com/Effect-TS/effect/commit/eaf8405ab9bb52423050eb0d23dd7d3c21c18141) Thanks @tim-smart! - add EntityNotAssignedToRunner error\n\n### Patch Changes\n\n- Updated dependencies [[`b8722b8`](https://github.com/Effect-TS/effect/commit/b8722b817e2306fe8c8245f3f9e32d85b824b961), [`a328f4b`](https://github.com/Effect-TS/effect/commit/a328f4b4fe717dd53e5b04a30f387433c32f7328)]:\n  - effect@3.15.2\n  - @effect/platform@0.82.3\n  - @effect/rpc@0.59.4\n  - @effect/sql@0.35.3\n\n## 0.33.3\n\n### Patch Changes\n\n- Updated dependencies [[`739a3d4`](https://github.com/Effect-TS/effect/commit/739a3d4a4565915fe2e690003f4f9085cb4422fc)]:\n  - @effect/platform@0.82.2\n  - @effect/rpc@0.59.3\n  - @effect/sql@0.35.2\n\n## 0.33.2\n\n### Patch Changes\n\n- Updated dependencies [[`787ce70`](https://github.com/Effect-TS/effect/commit/787ce7042e35b657963473c6efe47752868cd811), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348)]:\n  - effect@3.15.1\n  - @effect/platform@0.82.1\n  - @effect/rpc@0.59.2\n  - @effect/sql@0.35.1\n\n## 0.33.1\n\n### Patch Changes\n\n- Updated dependencies [[`6495440`](https://github.com/Effect-TS/effect/commit/64954405eb57313722023b87c0d92761980e2713)]:\n  - @effect/rpc@0.59.1\n\n## 0.33.0\n\n### Patch Changes\n\n- Updated dependencies [[`c654595`](https://github.com/Effect-TS/effect/commit/c65459587b51da140b78098e81fdbfece65d53e2), [`d9f5dea`](https://github.com/Effect-TS/effect/commit/d9f5deae0f02f5de2b9fcb1cca8b142ba4bc2bba), [`49aa723`](https://github.com/Effect-TS/effect/commit/49aa7236a15e13f818c86edbca08c4af67c8dfaf), [`74c14d0`](https://github.com/Effect-TS/effect/commit/74c14d01d0cb48cf517a1b6e29a373a96ed0ff5b), [`e4f49b6`](https://github.com/Effect-TS/effect/commit/e4f49b66857e01b74ab6a9a0bc7132f44cd04cbb), [`6f02224`](https://github.com/Effect-TS/effect/commit/6f02224b3fc46a682ad2defb1a260841956c6780), [`1dcfd41`](https://github.com/Effect-TS/effect/commit/1dcfd41ff96abd706901293a00c1893cb29dd8fd), [`b21ab16`](https://github.com/Effect-TS/effect/commit/b21ab16b6f773e7ec4369db4e752c35e719f7870), [`fcf1822`](https://github.com/Effect-TS/effect/commit/fcf1822f98fcda60351d64e9d2c2c13563d7e6db), [`0061dd1`](https://github.com/Effect-TS/effect/commit/0061dd140740165e91569a684cce27a77b23229e), [`8421e6e`](https://github.com/Effect-TS/effect/commit/8421e6e49332bca8f96f482dfd48680e238b3a89), [`a9b3fb7`](https://github.com/Effect-TS/effect/commit/a9b3fb78abcfdb525318a956fd02fcadeb56143e), [`fa10f56`](https://github.com/Effect-TS/effect/commit/fa10f56b96bd9af070ba99ebc3279aa93954261e)]:\n  - effect@3.15.0\n  - @effect/platform@0.82.0\n  - @effect/rpc@0.59.0\n  - @effect/sql@0.35.0\n\n## 0.32.0\n\n### Patch Changes\n\n- Updated dependencies [[`cd6cd0e`](https://github.com/Effect-TS/effect/commit/cd6cd0eacd6b09d6dd48b30b32edeb4a3c3075f9)]:\n  - @effect/rpc@0.58.0\n\n## 0.31.1\n\n### Patch Changes\n\n- Updated dependencies [[`24a9ebb`](https://github.com/Effect-TS/effect/commit/24a9ebbb5af598f0bfd6ecc45307e528043fe011)]:\n  - effect@3.14.22\n  - @effect/platform@0.81.1\n  - @effect/rpc@0.57.1\n  - @effect/sql@0.34.1\n\n## 0.31.0\n\n### Patch Changes\n\n- Updated dependencies [[`672920f`](https://github.com/Effect-TS/effect/commit/672920f85da8abd5f9d4ad85e29248a2aca57ed8)]:\n  - @effect/platform@0.81.0\n  - @effect/rpc@0.57.0\n  - @effect/sql@0.34.0\n\n## 0.30.11\n\n### Patch Changes\n\n- Updated dependencies [[`2f3b7d4`](https://github.com/Effect-TS/effect/commit/2f3b7d4e1fa1ef8790b0ca4da22eb88872ee31df)]:\n  - effect@3.14.21\n  - @effect/platform@0.80.21\n  - @effect/rpc@0.56.9\n  - @effect/sql@0.33.21\n\n## 0.30.10\n\n### Patch Changes\n\n- Updated dependencies [[`17e2f30`](https://github.com/Effect-TS/effect/commit/17e2f3091408cf0fca9414d4af3bdf7b2765b378)]:\n  - effect@3.14.20\n  - @effect/platform@0.80.20\n  - @effect/rpc@0.56.8\n  - @effect/sql@0.33.20\n\n## 0.30.9\n\n### Patch Changes\n\n- [#4829](https://github.com/Effect-TS/effect/pull/4829) [`2d55bc5`](https://github.com/Effect-TS/effect/commit/2d55bc52c596afd8381f8ad1badc69efa0be8a78) Thanks @tim-smart! - sending persisted messages without MessageStorage is now a defect\n\n## 0.30.8\n\n### Patch Changes\n\n- [#4825](https://github.com/Effect-TS/effect/pull/4825) [`1b30f61`](https://github.com/Effect-TS/effect/commit/1b30f616e75580933284657cb2cefab5a7903323) Thanks @tim-smart! - ensure clientOnly mode without storage falls back to network messaging\n\n## 0.30.7\n\n### Patch Changes\n\n- [#4823](https://github.com/Effect-TS/effect/pull/4823) [`146af39`](https://github.com/Effect-TS/effect/commit/146af39d8d3b4e82aceb13de9749e6c4120c580b) Thanks @tim-smart! - fix sqlite SqlMessagetStorage.repliesFor\n\n- Updated dependencies [[`056a910`](https://github.com/Effect-TS/effect/commit/056a910d0a0b8b00b0dc9df4a070466b2b5c2f6c), [`e25e7bb`](https://github.com/Effect-TS/effect/commit/e25e7bbc1797733916f48f501425d9f2ef310d9f), [`3273d57`](https://github.com/Effect-TS/effect/commit/3273d572c2b3175a842677f19efeea4cd65ab016)]:\n  - effect@3.14.19\n  - @effect/platform@0.80.19\n  - @effect/rpc@0.56.7\n  - @effect/sql@0.33.19\n\n## 0.30.6\n\n### Patch Changes\n\n- Updated dependencies [[`b1164d4`](https://github.com/Effect-TS/effect/commit/b1164d49a1dfdf299e9971367b6fc6be4df0ddff)]:\n  - effect@3.14.18\n  - @effect/platform@0.80.18\n  - @effect/rpc@0.56.6\n  - @effect/sql@0.33.18\n\n## 0.30.5\n\n### Patch Changes\n\n- Updated dependencies [[`0b54681`](https://github.com/Effect-TS/effect/commit/0b54681cd89245e211d8f49272be0f1bf2f81813), [`41a59d5`](https://github.com/Effect-TS/effect/commit/41a59d5916a296b12b0d5ead9e859e05f40b4cce)]:\n  - effect@3.14.17\n  - @effect/platform@0.80.17\n  - @effect/rpc@0.56.5\n  - @effect/sql@0.33.17\n\n## 0.30.4\n\n### Patch Changes\n\n- Updated dependencies [[`ee14444`](https://github.com/Effect-TS/effect/commit/ee144441021ec77039e43396eaf90714687bb495), [`f1c8583`](https://github.com/Effect-TS/effect/commit/f1c8583f8c3ea9415f813795ca2940a897c9ba9a)]:\n  - effect@3.14.16\n  - @effect/platform@0.80.16\n  - @effect/rpc@0.56.4\n  - @effect/sql@0.33.16\n\n## 0.30.3\n\n### Patch Changes\n\n- Updated dependencies [[`239cc99`](https://github.com/Effect-TS/effect/commit/239cc995ce645946210a3c3d2cb52bd3547c0687), [`8b6c947`](https://github.com/Effect-TS/effect/commit/8b6c947eaa8e45a67ecb3c37d45cd27f3e41d165), [`c50a63b`](https://github.com/Effect-TS/effect/commit/c50a63bbecb9f560b9cae349c447eed877d1b9b6)]:\n  - effect@3.14.15\n  - @effect/platform@0.80.15\n  - @effect/rpc@0.56.3\n  - @effect/sql@0.33.15\n\n## 0.30.2\n\n### Patch Changes\n\n- [#4779](https://github.com/Effect-TS/effect/pull/4779) [`664293f`](https://github.com/Effect-TS/effect/commit/664293f975a282920a7208e966adaf4634c42ef4) Thanks @fubhy! - Fix `FiberRef` module import\n\n- Updated dependencies [[`6ed8d15`](https://github.com/Effect-TS/effect/commit/6ed8d1589beb181d30abc79afebdaabc1d101538)]:\n  - effect@3.14.14\n  - @effect/platform@0.80.14\n  - @effect/rpc@0.56.2\n  - @effect/sql@0.33.14\n\n## 0.30.1\n\n### Patch Changes\n\n- Updated dependencies [[`ee77788`](https://github.com/Effect-TS/effect/commit/ee77788747e7ebbde6bfa88256cde49dbbad3608), [`5fce6ba`](https://github.com/Effect-TS/effect/commit/5fce6ba19c3cc63cc0104e737e581ad989dedbf0), [`570e45f`](https://github.com/Effect-TS/effect/commit/570e45f8cb936e42ec48f67f21bb2b7252f36c0c)]:\n  - effect@3.14.13\n  - @effect/platform@0.80.13\n  - @effect/rpc@0.56.1\n  - @effect/sql@0.33.13\n\n## 0.30.0\n\n### Patch Changes\n\n- Updated dependencies [[`d6e1156`](https://github.com/Effect-TS/effect/commit/d6e115617fc1a26a846b55f407965a330145dbee), [`2c66c16`](https://github.com/Effect-TS/effect/commit/2c66c16375dc2fe128f7b4e78c5f5c27c25c0d19)]:\n  - @effect/rpc@0.56.0\n\n## 0.29.22\n\n### Patch Changes\n\n- Updated dependencies [[`c2ad9ee`](https://github.com/Effect-TS/effect/commit/c2ad9ee9f3c4c743390edf35ed9e85a20be33811), [`9c68654`](https://github.com/Effect-TS/effect/commit/9c686542b6eb3ea188cb70673ef2e41223633e89)]:\n  - effect@3.14.12\n  - @effect/platform@0.80.12\n  - @effect/rpc@0.55.17\n  - @effect/sql@0.33.12\n\n## 0.29.21\n\n### Patch Changes\n\n- Updated dependencies [[`e536127`](https://github.com/Effect-TS/effect/commit/e536127c1e6f2fb3a542c73ae919435a629a346b), [`b5ad11e`](https://github.com/Effect-TS/effect/commit/b5ad11e511424c6d5c32e34e7ee9d04f0110617d)]:\n  - effect@3.14.11\n  - @effect/rpc@0.55.16\n  - @effect/platform@0.80.11\n  - @effect/sql@0.33.11\n\n## 0.29.20\n\n### Patch Changes\n\n- Updated dependencies [[`d3df84e`](https://github.com/Effect-TS/effect/commit/d3df84e8af8e00a297e2329faeae625de0a95a71)]:\n  - @effect/rpc@0.55.15\n\n## 0.29.19\n\n### Patch Changes\n\n- Updated dependencies [[`bc7efa3`](https://github.com/Effect-TS/effect/commit/bc7efa3b031bb25e1ed3c8f2d3fb5e8da166cadc)]:\n  - effect@3.14.10\n  - @effect/platform@0.80.10\n  - @effect/rpc@0.55.14\n  - @effect/sql@0.33.10\n\n## 0.29.18\n\n### Patch Changes\n\n- Updated dependencies [[`d78249f`](https://github.com/Effect-TS/effect/commit/d78249f0b67f63cf4baf806ff090cba33293daf0)]:\n  - effect@3.14.9\n  - @effect/platform@0.80.9\n  - @effect/rpc@0.55.13\n  - @effect/sql@0.33.9\n\n## 0.29.17\n\n### Patch Changes\n\n- Updated dependencies [[`58eaca9`](https://github.com/Effect-TS/effect/commit/58eaca9ef14032fc310f4a0e3c09513bac1cb50a)]:\n  - @effect/rpc@0.55.12\n\n## 0.29.16\n\n### Patch Changes\n\n- [#4719](https://github.com/Effect-TS/effect/pull/4719) [`a79b732`](https://github.com/Effect-TS/effect/commit/a79b732bddea8bfca091c4fed0dd87aa0b1ab1f0) Thanks @tim-smart! - expire shard locks after 15 seconds\n\n- [#4719](https://github.com/Effect-TS/effect/pull/4719) [`a79b732`](https://github.com/Effect-TS/effect/commit/a79b732bddea8bfca091c4fed0dd87aa0b1ab1f0) Thanks @tim-smart! - ensure more persisted messages are eligible for the fast path\n\n## 0.29.15\n\n### Patch Changes\n\n- [#4714](https://github.com/Effect-TS/effect/pull/4714) [`6966708`](https://github.com/Effect-TS/effect/commit/6966708a3061a3eb4bcfcb4d5877657fb41a019a) Thanks @tim-smart! - reset shard last_read on acquistion\n\n## 0.29.14\n\n### Patch Changes\n\n- [#4712](https://github.com/Effect-TS/effect/pull/4712) [`da21953`](https://github.com/Effect-TS/effect/commit/da21953a3831bf5974ab6add8fcc7fad1c0ba472) Thanks @tim-smart! - attempt to use network for persisted messages where possible\n\n## 0.29.13\n\n### Patch Changes\n\n- [#4710](https://github.com/Effect-TS/effect/pull/4710) [`896fbbf`](https://github.com/Effect-TS/effect/commit/896fbbf6ed6c11e099747e8aafb67b28edc4e466) Thanks @tim-smart! - tighten cluster health checks to improve worst case recovery time\n\n- Updated dependencies [[`b3a2d32`](https://github.com/Effect-TS/effect/commit/b3a2d32772e6f7f20eacf2e18128e99324c4d378)]:\n  - effect@3.14.8\n  - @effect/platform@0.80.8\n  - @effect/rpc@0.55.11\n  - @effect/sql@0.33.8\n\n## 0.29.12\n\n### Patch Changes\n\n- Updated dependencies [[`b542a4b`](https://github.com/Effect-TS/effect/commit/b542a4bf195be0c9af1523e1ba96c953decc4d25)]:\n  - effect@3.14.7\n  - @effect/platform@0.80.7\n  - @effect/rpc@0.55.10\n  - @effect/sql@0.33.7\n\n## 0.29.11\n\n### Patch Changes\n\n- Updated dependencies [[`a1d4673`](https://github.com/Effect-TS/effect/commit/a1d4673a423dfed050c0a762664d9d64002cfa90)]:\n  - @effect/rpc@0.55.9\n\n## 0.29.10\n\n### Patch Changes\n\n- Updated dependencies [[`47618c1`](https://github.com/Effect-TS/effect/commit/47618c1ad84ebcc5a51133a3fff5aa5012d49d45), [`6077882`](https://github.com/Effect-TS/effect/commit/60778824a4794336c33807801f813f8751d1c7e4)]:\n  - effect@3.14.6\n  - @effect/platform@0.80.6\n  - @effect/rpc@0.55.8\n  - @effect/sql@0.33.6\n\n## 0.29.9\n\n### Patch Changes\n\n- Updated dependencies [[`4414042`](https://github.com/Effect-TS/effect/commit/44140423a2fb185f92f7db4d5b383f9b62a97bf9)]:\n  - @effect/rpc@0.55.7\n\n## 0.29.8\n\n### Patch Changes\n\n- Updated dependencies [[`40dbfef`](https://github.com/Effect-TS/effect/commit/40dbfeff239b6e567706752114f31b2fce7de4e3), [`85fba81`](https://github.com/Effect-TS/effect/commit/85fba815ac07eb13d4227a69ac76a18e4b94df18), [`5a5ebdd`](https://github.com/Effect-TS/effect/commit/5a5ebdddfaddd259538b4599a6676281faca778e)]:\n  - effect@3.14.5\n  - @effect/platform@0.80.5\n  - @effect/rpc@0.55.6\n  - @effect/sql@0.33.5\n\n## 0.29.7\n\n### Patch Changes\n\n- Updated dependencies [[`e4ba2c6`](https://github.com/Effect-TS/effect/commit/e4ba2c66a878e81b5e295d6d49aaf724b80a28ef), [`e3e5873`](https://github.com/Effect-TS/effect/commit/e3e5873f30080bb0e5eed8a876170acaa6ed47ff), [`26c060c`](https://github.com/Effect-TS/effect/commit/26c060c65914a623220a20356991784f974bfe18)]:\n  - effect@3.14.4\n  - @effect/rpc@0.55.5\n  - @effect/platform@0.80.4\n  - @effect/sql@0.33.4\n\n## 0.29.6\n\n### Patch Changes\n\n- [#4670](https://github.com/Effect-TS/effect/pull/4670) [`34f03d6`](https://github.com/Effect-TS/effect/commit/34f03d66875f21f266f102223a03cd14c2ed6ea6) Thanks @tim-smart! - fix Data.TaggedEnum with generics regression\n\n- Updated dependencies [[`0ec5e03`](https://github.com/Effect-TS/effect/commit/0ec5e0353a1db5d27c3500deba0df61001258e76), [`05c4d77`](https://github.com/Effect-TS/effect/commit/05c4d772acc42b7425add7b22f914c5ee3ff84bd), [`37aa8e1`](https://github.com/Effect-TS/effect/commit/37aa8e137725a902e70cd1e468ea98b873aa5056), [`34f03d6`](https://github.com/Effect-TS/effect/commit/34f03d66875f21f266f102223a03cd14c2ed6ea6)]:\n  - @effect/rpc@0.55.4\n  - effect@3.14.3\n  - @effect/platform@0.80.3\n  - @effect/sql@0.33.3\n\n## 0.29.5\n\n### Patch Changes\n\n- Updated dependencies [[`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`0a3e3e1`](https://github.com/Effect-TS/effect/commit/0a3e3e18eea5e0d1882f1a6c906198e6ef226a41)]:\n  - effect@3.14.2\n  - @effect/platform@0.80.2\n  - @effect/rpc@0.55.3\n  - @effect/sql@0.33.2\n\n## 0.29.4\n\n### Patch Changes\n\n- Updated dependencies [[`d2f11e5`](https://github.com/Effect-TS/effect/commit/d2f11e557de4639762124951252170fbf4d7c906)]:\n  - @effect/rpc@0.55.2\n\n## 0.29.3\n\n### Patch Changes\n\n- [#4637](https://github.com/Effect-TS/effect/pull/4637) [`18a7936`](https://github.com/Effect-TS/effect/commit/18a7936832158daa69e3c09a6caae55e3d6c0b86) Thanks @tim-smart! - fix clientOnly mode for SocketRunner\n\n## 0.29.2\n\n### Patch Changes\n\n- [#4626](https://github.com/Effect-TS/effect/pull/4626) [`3a99a2d`](https://github.com/Effect-TS/effect/commit/3a99a2dbaa38348c1f6e210a531fcfb99b5e73c5) Thanks @tim-smart! - add Sharding.activeEntityCount\n\n## 0.29.1\n\n### Patch Changes\n\n- [#4621](https://github.com/Effect-TS/effect/pull/4621) [`814733f`](https://github.com/Effect-TS/effect/commit/814733fe62bb3dc91c6cd632d16a8d2076b3755b) Thanks @tim-smart! - remove Sharding.make export\n\n- Updated dependencies [[`4a274fe`](https://github.com/Effect-TS/effect/commit/4a274fe9f623182b6b902827e0e83bd89ca3b05c)]:\n  - effect@3.14.1\n  - @effect/platform@0.80.1\n  - @effect/rpc@0.55.1\n  - @effect/sql@0.33.1\n\n## 0.29.0\n\n### Minor Changes\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`3131f8f`](https://github.com/Effect-TS/effect/commit/3131f8fd12ba9eb31b90fa2f42bf88b12309133c) Thanks @tim-smart! - refactor of @effect/cluster packages\n\n### Patch Changes\n\n- Updated dependencies [[`1f47e4e`](https://github.com/Effect-TS/effect/commit/1f47e4e12546ab691b29bfb7b5128bb17b93baa5), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`3131f8f`](https://github.com/Effect-TS/effect/commit/3131f8fd12ba9eb31b90fa2f42bf88b12309133c), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`04dff2d`](https://github.com/Effect-TS/effect/commit/04dff2d01ac68c260f29a6d4743381825c353c86), [`c7fac0c`](https://github.com/Effect-TS/effect/commit/c7fac0cd7eadcd5cc0c3a987051c5b57ad271638), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`ffaa3f3`](https://github.com/Effect-TS/effect/commit/ffaa3f3969df26610fcc02ad537340641d44e803), [`ab957c1`](https://github.com/Effect-TS/effect/commit/ab957c1fee714868f56c7ab4e802b9d449e9b666), [`35db9ce`](https://github.com/Effect-TS/effect/commit/35db9ce228f1416c8abacc6dc9c36fbd0f33ef0f), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`cf77ea9`](https://github.com/Effect-TS/effect/commit/cf77ea9ab4fc89e66a43f682a9926ccdee6c57ed), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`baaab60`](https://github.com/Effect-TS/effect/commit/baaab60b737f35dfab8e4a21bce28a195d19e899)]:\n  - effect@3.14.0\n  - @effect/platform@0.80.0\n  - @effect/rpc@0.55.0\n  - @effect/sql@0.33.0\n\n## 0.28.4\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.32.4\n\n## 0.28.3\n\n### Patch Changes\n\n- Updated dependencies [[`0c4803f`](https://github.com/Effect-TS/effect/commit/0c4803fcc69262d11a97ce49d0e9b4288df0651f), [`6f65ac4`](https://github.com/Effect-TS/effect/commit/6f65ac4eac1489cd6ea390e18b0908670722adad)]:\n  - effect@3.13.12\n  - @effect/sql@0.32.3\n\n## 0.28.2\n\n### Patch Changes\n\n- Updated dependencies [[`fad8cca`](https://github.com/Effect-TS/effect/commit/fad8cca9bbfcc2eaeb44b97c15dbe0a1eda75315), [`4296293`](https://github.com/Effect-TS/effect/commit/4296293049414d0cf2d915a26c552b09f946b9a0), [`9c241ab`](https://github.com/Effect-TS/effect/commit/9c241abe47ccf7a5257b98a4a64a63054a12741d), [`082b0c1`](https://github.com/Effect-TS/effect/commit/082b0c1b9f4252bcdd69608f2e4a9226f953ac3f), [`be12983`](https://github.com/Effect-TS/effect/commit/be12983bc7e7537b41cd8910fc4eb7d1da56ab07), [`de88127`](https://github.com/Effect-TS/effect/commit/de88127a5a5906ccece98af74787b5ae0e65e431)]:\n  - effect@3.13.11\n  - @effect/sql@0.32.2\n\n## 0.28.1\n\n### Patch Changes\n\n- Updated dependencies [[`527c964`](https://github.com/Effect-TS/effect/commit/527c9645229f5be9714a7e60a38a9e753c4bbfb1)]:\n  - effect@3.13.10\n  - @effect/sql@0.32.1\n\n## 0.28.0\n\n### Patch Changes\n\n- Updated dependencies [[`2976e52`](https://github.com/Effect-TS/effect/commit/2976e52538d9dc9ffdcbc84d4ac748cff9305971)]:\n  - effect@3.13.9\n  - @effect/sql@0.32.0\n\n## 0.27.1\n\n### Patch Changes\n\n- Updated dependencies [[`c65d336`](https://github.com/Effect-TS/effect/commit/c65d3362d07ec815ff3b46278314e8a31706ddc2), [`22d2ebb`](https://github.com/Effect-TS/effect/commit/22d2ebb4b11f5a44351a4736e65da391a3b647d0)]:\n  - effect@3.13.8\n  - @effect/sql@0.31.1\n\n## 0.27.0\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.31.0\n\n## 0.26.7\n\n### Patch Changes\n\n- Updated dependencies [[`840cc73`](https://github.com/Effect-TS/effect/commit/840cc7329908db7ca693ef47b07d4f845c29cadd), [`9bf8a74`](https://github.com/Effect-TS/effect/commit/9bf8a74b967f18d931743dd5196af326c9118e9c), [`87ba23c`](https://github.com/Effect-TS/effect/commit/87ba23c41c193503ed0c612b0d32d0b253794c64)]:\n  - effect@3.13.7\n  - @effect/sql@0.30.7\n\n## 0.26.6\n\n### Patch Changes\n\n- Updated dependencies [[`3154ce4`](https://github.com/Effect-TS/effect/commit/3154ce4692fa18b804982158d3c4c8a8a5fae386)]:\n  - effect@3.13.6\n  - @effect/sql@0.30.6\n\n## 0.26.5\n\n### Patch Changes\n\n- Updated dependencies [[`367bb35`](https://github.com/Effect-TS/effect/commit/367bb35f4c2a254e1fb211d96db2474a7aed9020), [`6cf11c3`](https://github.com/Effect-TS/effect/commit/6cf11c3a75773ceec2877c85ddc760f381f0866d), [`a0acec8`](https://github.com/Effect-TS/effect/commit/a0acec851f72e19466363d24b9cc218acd00006a)]:\n  - effect@3.13.5\n  - @effect/sql@0.30.5\n\n## 0.26.4\n\n### Patch Changes\n\n- Updated dependencies [[`17d9e89`](https://github.com/Effect-TS/effect/commit/17d9e89f9851663bdbb6c1e685601d97806114a4)]:\n  - effect@3.13.4\n  - @effect/sql@0.30.4\n\n## 0.26.3\n\n### Patch Changes\n\n- Updated dependencies [[`cc5588d`](https://github.com/Effect-TS/effect/commit/cc5588df07f9103513547cb429ce041b9436a8bd), [`623c8cd`](https://github.com/Effect-TS/effect/commit/623c8cd053ed6ee3d353aaa8778d484670fca2bb), [`00b4eb1`](https://github.com/Effect-TS/effect/commit/00b4eb1ece12a16e222e6220965bb4024d6752ac), [`f2aee98`](https://github.com/Effect-TS/effect/commit/f2aee989b0a600900ce83e7f460d02908620c80f), [`fb798eb`](https://github.com/Effect-TS/effect/commit/fb798eb9061f1191badc017d1aa649360254da20), [`2251b15`](https://github.com/Effect-TS/effect/commit/2251b1528810bb695b37ce388b653cec0c5bf80c), [`2e15c1e`](https://github.com/Effect-TS/effect/commit/2e15c1e33648add0b29fe274fbcb7294b7515085), [`a4979db`](https://github.com/Effect-TS/effect/commit/a4979db021aef16e731be64df196b72088fc4376), [`b74255a`](https://github.com/Effect-TS/effect/commit/b74255a304ad49d60bedb1a260fd697f370af27a), [`d7f6a5c`](https://github.com/Effect-TS/effect/commit/d7f6a5c7d26c1963dcd864ca62360d20d08c7b49), [`9dd8979`](https://github.com/Effect-TS/effect/commit/9dd8979e940915b1cc1b1f264f3d019c77a65a02), [`477b488`](https://github.com/Effect-TS/effect/commit/477b488284f47c5469d7fba3e4065fb7e3b6556e), [`10932cb`](https://github.com/Effect-TS/effect/commit/10932cbf58fc721ada631cebec42f773ce96d3cc), [`9f6c784`](https://github.com/Effect-TS/effect/commit/9f6c78468b3b5e9ebfc38ffdfb70702901ee977b), [`2c639ec`](https://github.com/Effect-TS/effect/commit/2c639ecee332de4266e36022c989c35ae4e02105), [`886aaa8`](https://github.com/Effect-TS/effect/commit/886aaa81e06dfd3cd9391e8ea987d8cd5ada1124)]:\n  - effect@3.13.3\n  - @effect/sql@0.30.3\n\n## 0.26.2\n\n### Patch Changes\n\n- Updated dependencies [[`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f)]:\n  - effect@3.13.2\n  - @effect/sql@0.30.2\n\n## 0.26.1\n\n### Patch Changes\n\n- Updated dependencies [[`b56a211`](https://github.com/Effect-TS/effect/commit/b56a2110569fd0ec0b57ac137743e926d49f51cc)]:\n  - effect@3.13.1\n  - @effect/sql@0.30.1\n\n## 0.26.0\n\n### Patch Changes\n\n- Updated dependencies [[`8baef83`](https://github.com/Effect-TS/effect/commit/8baef83e7ff0b7bc0738b680e1ef013065386cff), [`655bfe2`](https://github.com/Effect-TS/effect/commit/655bfe29e44cc3f0fb9b4e53038f50b891c188df), [`d90cbc2`](https://github.com/Effect-TS/effect/commit/d90cbc274e2742d18671fe65aa4764c057eb6cba), [`75632bd`](https://github.com/Effect-TS/effect/commit/75632bd44b8025101d652ccbaeef898c7086c91c), [`c874a2e`](https://github.com/Effect-TS/effect/commit/c874a2e4b17e9d71904ca8375bb77b020975cb1d), [`bf865e5`](https://github.com/Effect-TS/effect/commit/bf865e5833f77fd8f6c06944ca9d507b54488301), [`f98b2b7`](https://github.com/Effect-TS/effect/commit/f98b2b7592cf20f9d85313e7f1e964cb65878138), [`de8ce92`](https://github.com/Effect-TS/effect/commit/de8ce924923eaa4e1b761a97eb45ec967389f3d5), [`cf8b2dd`](https://github.com/Effect-TS/effect/commit/cf8b2dd112f8e092ed99d78fd728db0f91c29050), [`db426a5`](https://github.com/Effect-TS/effect/commit/db426a5fb41ab84d18e3c8753a7329b4de544245), [`6862444`](https://github.com/Effect-TS/effect/commit/6862444094906ad4f2cb077ff3b9cc0b73880c8c), [`5fc8a90`](https://github.com/Effect-TS/effect/commit/5fc8a90ba46a5fd9f3b643f0b5aeadc69d717339), [`546a492`](https://github.com/Effect-TS/effect/commit/546a492e60eb2b8b048a489a474b934ea0877005), [`65c4796`](https://github.com/Effect-TS/effect/commit/65c47966ce39055f02cf5c808daabb3ea6442b0b), [`9760fdc`](https://github.com/Effect-TS/effect/commit/9760fdc37bdaef9da8b150e46b86ddfbe2ad9221), [`5b471e7`](https://github.com/Effect-TS/effect/commit/5b471e7d4317e8ee5d72bbbd3e0c9775160949ab), [`4f810cc`](https://github.com/Effect-TS/effect/commit/4f810cc2770e9f1f266851d2cb6257112c12af49)]:\n  - effect@3.13.0\n  - @effect/sql@0.30.0\n\n## 0.25.1\n\n### Patch Changes\n\n- Updated dependencies [[`4018eae`](https://github.com/Effect-TS/effect/commit/4018eaed2733241676ddb8c52416f463a8c32e35), [`543d36d`](https://github.com/Effect-TS/effect/commit/543d36d1a11452560b01ab966a82529ad5fee8c9), [`f70a65a`](https://github.com/Effect-TS/effect/commit/f70a65ac80c6635d80b12beaf4d32a9cc59fa143), [`ba409f6`](https://github.com/Effect-TS/effect/commit/ba409f69c41aeaa29e475c0630735726eaf4dbac), [`3d2e356`](https://github.com/Effect-TS/effect/commit/3d2e3565e8a43d1bdb5daee8db3b90f56d71d859)]:\n  - effect@3.12.12\n  - @effect/sql@0.29.1\n\n## 0.25.0\n\n### Patch Changes\n\n- Updated dependencies [[`b6a032f`](https://github.com/Effect-TS/effect/commit/b6a032f07bffa020a848c813881879395134fa20), [`42ddd5f`](https://github.com/Effect-TS/effect/commit/42ddd5f144ce9f9d94a036679ebbd626446d37f5), [`2fe447c`](https://github.com/Effect-TS/effect/commit/2fe447c6354d334f9c591b8a8481818f5f0e797e)]:\n  - effect@3.12.11\n  - @effect/sql@0.29.0\n\n## 0.24.4\n\n### Patch Changes\n\n- Updated dependencies [[`e30f132`](https://github.com/Effect-TS/effect/commit/e30f132c336c9d0760bad39f82a55c7ce5159eb7), [`33fa667`](https://github.com/Effect-TS/effect/commit/33fa667c2623be1026e1ccee91bd44f73b09020a), [`87f5f28`](https://github.com/Effect-TS/effect/commit/87f5f2842e4196cb88d13f10f443ff0567e82832), [`4dbd170`](https://github.com/Effect-TS/effect/commit/4dbd170538e8fb7a36aa7c469c6f93b6c7000091)]:\n  - effect@3.12.10\n  - @effect/sql@0.28.4\n\n## 0.24.3\n\n### Patch Changes\n\n- Updated dependencies [[`1b4a4e9`](https://github.com/Effect-TS/effect/commit/1b4a4e904ef5227ec7d9114d4e417eca19eed940)]:\n  - effect@3.12.9\n  - @effect/sql@0.28.3\n\n## 0.24.2\n\n### Patch Changes\n\n- Updated dependencies [[`766113c`](https://github.com/Effect-TS/effect/commit/766113c0ea3512cdb887650ead8ba314236e22ee), [`712277f`](https://github.com/Effect-TS/effect/commit/712277f949052a24b46e4aa234063a6abf395c90), [`f269122`](https://github.com/Effect-TS/effect/commit/f269122508693b111142994dd48698ddc75f3d69), [`430c846`](https://github.com/Effect-TS/effect/commit/430c846cbac05b187e3d24ac8dfee0cf22506f7c), [`7b03057`](https://github.com/Effect-TS/effect/commit/7b03057507d2dab5e6793beb9c578dedaaeb15fe), [`a9c94c8`](https://github.com/Effect-TS/effect/commit/a9c94c807755610831211a686d2fad849ab38eb4), [`107e6f0`](https://github.com/Effect-TS/effect/commit/107e6f0557a1e2d3b0dce25d62fa1e2601521752), [`65c11b9`](https://github.com/Effect-TS/effect/commit/65c11b9266ec9447c31c26fe3ed35c73bd3b81fd), [`e386d2f`](https://github.com/Effect-TS/effect/commit/e386d2f1b3ab3ac2c14ee76de11f5963d32a3df4), [`9172efb`](https://github.com/Effect-TS/effect/commit/9172efba98bc6a82353e6ec2af61ac08f038ba64)]:\n  - effect@3.12.8\n  - @effect/sql@0.28.2\n\n## 0.24.1\n\n### Patch Changes\n\n- Updated dependencies [[`8dff1d1`](https://github.com/Effect-TS/effect/commit/8dff1d1bff76cdba643cad7f0bf864300f08bc61)]:\n  - effect@3.12.7\n  - @effect/sql@0.28.1\n\n## 0.24.0\n\n### Patch Changes\n\n- Updated dependencies [[`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`8b4e75d`](https://github.com/Effect-TS/effect/commit/8b4e75d35daea807c447ca760948a717aa66bb52), [`fc5e0f0`](https://github.com/Effect-TS/effect/commit/fc5e0f0d357a0051cfa01c1ede83ffdd3cb41ab1), [`004fd2b`](https://github.com/Effect-TS/effect/commit/004fd2bbd1459e64fb1b57f02eeb791ca5ea1ea5), [`b2a31be`](https://github.com/Effect-TS/effect/commit/b2a31be85c35d891351ce4f9a2cc93ece0c257f6), [`5514d05`](https://github.com/Effect-TS/effect/commit/5514d05b5cd586ff5868b8bd41c959e95e6c33cd), [`bf5f0ae`](https://github.com/Effect-TS/effect/commit/bf5f0ae9daa0170471678e22585e8ec14ce667bb), [`3b19bcf`](https://github.com/Effect-TS/effect/commit/3b19bcfd3aaadb6c9253428622df524537c8e626), [`b064b3b`](https://github.com/Effect-TS/effect/commit/b064b3b293615fd268cc5a5647d0981eb67750b8), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`f474678`](https://github.com/Effect-TS/effect/commit/f474678bf10b8f1c80e3dc096ddc7ecf20b2b23e), [`ee187d0`](https://github.com/Effect-TS/effect/commit/ee187d098007a402844c94d04f0cd8f07695377a)]:\n  - effect@3.12.6\n  - @effect/sql@0.28.0\n\n## 0.23.0\n\n### Patch Changes\n\n- Updated dependencies [[`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`507d546`](https://github.com/Effect-TS/effect/commit/507d546bd49db31000425fb5da88c434e4291bea), [`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8db239b`](https://github.com/Effect-TS/effect/commit/8db239b9c869a3707f6566b9d9dbdf53c4df03fc), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`3179a9f`](https://github.com/Effect-TS/effect/commit/3179a9f65d23369a6a9a1f80f7750566dd28df22), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e), [`1fcbe55`](https://github.com/Effect-TS/effect/commit/1fcbe55345042d8468f6a98c84081bd00b6bcf5a), [`d9a63d9`](https://github.com/Effect-TS/effect/commit/d9a63d9d385653865954cac895065360d54cc56b)]:\n  - @effect/sql@0.27.0\n  - effect@3.12.5\n\n## 0.22.1\n\n### Patch Changes\n\n- Updated dependencies [[`5b50ea4`](https://github.com/Effect-TS/effect/commit/5b50ea4a10cf9acd51f9624b2474d9d5ded74019), [`c170a68`](https://github.com/Effect-TS/effect/commit/c170a68b6266100774461fcd6c0e0fabb60112f2), [`a66c2eb`](https://github.com/Effect-TS/effect/commit/a66c2eb473245092cd41f04c2eb2b7b02cf53718)]:\n  - effect@3.12.4\n  - @effect/sql@0.26.1\n\n## 0.22.0\n\n### Patch Changes\n\n- Updated dependencies [[`d7dac48`](https://github.com/Effect-TS/effect/commit/d7dac48a477cdfeec509dbe9f33fce6a1b02b63d), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5)]:\n  - effect@3.12.3\n  - @effect/sql@0.26.0\n\n## 0.21.2\n\n### Patch Changes\n\n- Updated dependencies [[`734af82`](https://github.com/Effect-TS/effect/commit/734af82138e78b9c57a8355b1c6b80e80d38b222), [`b63c780`](https://github.com/Effect-TS/effect/commit/b63c78010893101520448ddda7019c487cf7eedd), [`c640d77`](https://github.com/Effect-TS/effect/commit/c640d77b33ad417876f4e8ffe8574ee6cbe5607f), [`0def088`](https://github.com/Effect-TS/effect/commit/0def0887cfdb6755729a64dfd52b3b9f46b0576c)]:\n  - effect@3.12.2\n  - @effect/sql@0.25.2\n\n## 0.21.1\n\n### Patch Changes\n\n- Updated dependencies [[`302b57d`](https://github.com/Effect-TS/effect/commit/302b57d2cbf9b9ccc17450945aeebfb33cfe8d43), [`0988083`](https://github.com/Effect-TS/effect/commit/0988083d4594938590df5a287e5b27d38526dd07), [`8b46be6`](https://github.com/Effect-TS/effect/commit/8b46be6a3b8160362ab5ea9171c5e6932505125c), [`bfe8027`](https://github.com/Effect-TS/effect/commit/bfe802734b450a4b4ee069d1125dd37995db2bff), [`16dd657`](https://github.com/Effect-TS/effect/commit/16dd657033d8afac2ffea567b3c8bb27c9b249b6), [`39db211`](https://github.com/Effect-TS/effect/commit/39db211414e90c8db8fdad7dc8ce5b4661bcfaef)]:\n  - effect@3.12.1\n  - @effect/sql@0.25.1\n\n## 0.21.0\n\n### Patch Changes\n\n- Updated dependencies [[`abb22a4`](https://github.com/Effect-TS/effect/commit/abb22a429b9c52c31e84856294f175d2064a9b4d), [`f369a89`](https://github.com/Effect-TS/effect/commit/f369a89e98bc682969803b9304adaf4557bb36c2), [`642376c`](https://github.com/Effect-TS/effect/commit/642376c63fd7d78754db991631a4d50a5dc79aa3), [`3d2b7a7`](https://github.com/Effect-TS/effect/commit/3d2b7a7e942a7157afae5b1cdbc6f3fef116428e), [`73f9c6f`](https://github.com/Effect-TS/effect/commit/73f9c6f2ff091512cf904cc54ab59965b86e87c8), [`17cb451`](https://github.com/Effect-TS/effect/commit/17cb4514590e8a86263f7aed009f24da8a237342), [`d801820`](https://github.com/Effect-TS/effect/commit/d80182060c2ee945d7e0e4728812abf9465a0d6a), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1), [`c11f3a6`](https://github.com/Effect-TS/effect/commit/c11f3a60a05c3b5fc8e7ce90136728154dc505b0), [`618f7e0`](https://github.com/Effect-TS/effect/commit/618f7e092a1011e5090dca1e69b5e9285689654b), [`c0ba834`](https://github.com/Effect-TS/effect/commit/c0ba834d1995cf5a8b250e4780fd43f3e3881151), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1)]:\n  - effect@3.12.0\n  - @effect/sql@0.25.0\n\n## 0.20.3\n\n### Patch Changes\n\n- Updated dependencies [[`39457d4`](https://github.com/Effect-TS/effect/commit/39457d4897d9bc7df8af5c05d352866bbeae82eb), [`a475cc2`](https://github.com/Effect-TS/effect/commit/a475cc25fd7c9f26b27a8e98f8fbe43cc9e6ee3e), [`199214e`](https://github.com/Effect-TS/effect/commit/199214e21c616d8a0ccd7ed5f92e944e6c580193), [`b3c160d`](https://github.com/Effect-TS/effect/commit/b3c160d7a1fdfc2d3fb2440530f1ab80efc65133)]:\n  - effect@3.11.10\n  - @effect/sql@0.24.3\n\n## 0.20.2\n\n### Patch Changes\n\n- Updated dependencies [[`1c08a0b`](https://github.com/Effect-TS/effect/commit/1c08a0b8505badcffb4d9cade5a746ea90c9557e), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd)]:\n  - effect@3.11.9\n  - @effect/sql@0.24.2\n\n## 0.20.1\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.24.1\n\n## 0.20.0\n\n### Patch Changes\n\n- Updated dependencies [[`1a6b52d`](https://github.com/Effect-TS/effect/commit/1a6b52dcf020d36e38a7bc90b648152cf5a8ccba)]:\n  - effect@3.11.8\n  - @effect/sql@0.24.0\n\n## 0.19.3\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.23.3\n\n## 0.19.2\n\n### Patch Changes\n\n- Updated dependencies [[`2408616`](https://github.com/Effect-TS/effect/commit/24086163b60b09cc6d0885bd565ef080dcbe866b), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`8d978c5`](https://github.com/Effect-TS/effect/commit/8d978c53f6fcc98d9d645ecba3e4b55d4297dd36), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e)]:\n  - effect@3.11.7\n  - @effect/sql@0.23.2\n\n## 0.19.1\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.23.1\n\n## 0.19.0\n\n### Patch Changes\n\n- Updated dependencies [[`662d1ce`](https://github.com/Effect-TS/effect/commit/662d1ce6fb7da384a95888d5b2bb5605bdf3208d), [`31c62d8`](https://github.com/Effect-TS/effect/commit/31c62d83cbdcf9850a8b5331faa239601c60f78a)]:\n  - effect@3.11.6\n  - @effect/sql@0.23.0\n\n## 0.18.7\n\n### Patch Changes\n\n- Updated dependencies [[`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`22905cf`](https://github.com/Effect-TS/effect/commit/22905cf5addfb1ff3d2a6135c52036be958ae911), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`1e59e4f`](https://github.com/Effect-TS/effect/commit/1e59e4fd778da18296812a2a32f36ca8ae50f60d), [`8d914e5`](https://github.com/Effect-TS/effect/commit/8d914e504e7a22d0ea628e8af265ee450ff9530f), [`03bb00f`](https://github.com/Effect-TS/effect/commit/03bb00faa74f9e168a54a8cc0828a664fbb1ab05), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`14e1149`](https://github.com/Effect-TS/effect/commit/14e1149f1af5a022f06eb8c2e4ba9fec17fe7426), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8)]:\n  - effect@3.11.5\n  - @effect/sql@0.22.7\n\n## 0.18.6\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.22.6\n\n## 0.18.5\n\n### Patch Changes\n\n- Updated dependencies [[`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f)]:\n  - effect@3.11.4\n  - @effect/sql@0.22.5\n\n## 0.18.4\n\n### Patch Changes\n\n- Updated dependencies [[`90906f7`](https://github.com/Effect-TS/effect/commit/90906f7f154b12c7182e8f39e3c55ef3937db857), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`343b6aa`](https://github.com/Effect-TS/effect/commit/343b6aa6ac4a74276bfc7c63ccbf4a1d72bc1bed), [`afba339`](https://github.com/Effect-TS/effect/commit/afba339adc11dad56b5a3b7ca94487e58f34d613)]:\n  - effect@3.11.3\n  - @effect/sql@0.22.4\n\n## 0.18.3\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.22.3\n\n## 0.18.2\n\n### Patch Changes\n\n- Updated dependencies [[`01cee56`](https://github.com/Effect-TS/effect/commit/01cee560b58d94b24cc20e98083251b73e658b41)]:\n  - effect@3.11.2\n  - @effect/sql@0.22.2\n\n## 0.18.1\n\n### Patch Changes\n\n- Updated dependencies [[`dd8a2d8`](https://github.com/Effect-TS/effect/commit/dd8a2d8e80d33b16719fc69361eaedf0b59d4620), [`a71bfef`](https://github.com/Effect-TS/effect/commit/a71bfef46f5061bb2502a61a333638a987b62273)]:\n  - effect@3.11.1\n  - @effect/sql@0.22.1\n\n## 0.18.0\n\n### Patch Changes\n\n- Updated dependencies [[`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`6e69493`](https://github.com/Effect-TS/effect/commit/6e694930048bbaf98110f35f41566aeb9752d471), [`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`5eff3f6`](https://github.com/Effect-TS/effect/commit/5eff3f6fa3aae7e86948a62cbfd63b8d6c3bdf92), [`d9fe79b`](https://github.com/Effect-TS/effect/commit/d9fe79bb5a3fe105d8e7a3bc2922a8ad936a5d10), [`251d189`](https://github.com/Effect-TS/effect/commit/251d189420bbba71990574e91098c499065f9a9b), [`5a259f3`](https://github.com/Effect-TS/effect/commit/5a259f3711b4369f55d885b568bdb21136155261), [`b4ce4ea`](https://github.com/Effect-TS/effect/commit/b4ce4ea7fd514a7e572f2dcd879c98f334981b0e), [`15fcc5a`](https://github.com/Effect-TS/effect/commit/15fcc5a0ea4bbf40ab48fa6a04fdda74f76f4c07), [`9bc9a47`](https://github.com/Effect-TS/effect/commit/9bc9a476800dc645903c888a68bb1d3baa3383c6), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb), [`1e2747c`](https://github.com/Effect-TS/effect/commit/1e2747c63a4820d1459cbbc88c71212983bd68bd), [`9264162`](https://github.com/Effect-TS/effect/commit/9264162a82783a651776fb7b87604564a63e7070), [`e0b9b09`](https://github.com/Effect-TS/effect/commit/e0b9b09e70c386b2da17d1f0a15b0511861c89e8), [`c36f3b9`](https://github.com/Effect-TS/effect/commit/c36f3b95df5ce9d71b66f22f26ce12eda8d3e848), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb)]:\n  - effect@3.11.0\n  - @effect/sql@0.22.0\n\n## 0.17.4\n\n### Patch Changes\n\n- Updated dependencies [[`3069614`](https://github.com/Effect-TS/effect/commit/30696149271129fc618f6f2ccd1d8f2f6c0f9cd7), [`09a5e52`](https://github.com/Effect-TS/effect/commit/09a5e522fd9b221f05d85b1d1c8a740d4973c302)]:\n  - effect@3.10.20\n  - @effect/sql@0.21.4\n\n## 0.17.3\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.21.3\n\n## 0.17.2\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.21.2\n\n## 0.17.1\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.21.1\n\n## 0.17.0\n\n### Patch Changes\n\n- Updated dependencies [[`e9dfea3`](https://github.com/Effect-TS/effect/commit/e9dfea3f394444ebd8929e5cfe05ce740cf84d6e), [`1b1ba09`](https://github.com/Effect-TS/effect/commit/1b1ba099bca49ff48ffe931cc1b607314a5eaafa)]:\n  - @effect/sql@0.21.0\n\n## 0.16.12\n\n### Patch Changes\n\n- Updated dependencies [[`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1), [`54addee`](https://github.com/Effect-TS/effect/commit/54addee438a644bf010646c52042c7b89c5fc0a7)]:\n  - effect@3.10.19\n  - @effect/sql@0.20.12\n\n## 0.16.11\n\n### Patch Changes\n\n- Updated dependencies [[`af409cf`](https://github.com/Effect-TS/effect/commit/af409cf1d2ff973be11cc079ea373eaeedca25de)]:\n  - effect@3.10.18\n  - @effect/sql@0.20.11\n\n## 0.16.10\n\n### Patch Changes\n\n- Updated dependencies [[`42c4ce6`](https://github.com/Effect-TS/effect/commit/42c4ce6f8d8c7d847e97757650a8ad9419a829d7)]:\n  - effect@3.10.17\n  - @effect/sql@0.20.10\n\n## 0.16.9\n\n### Patch Changes\n\n- Updated dependencies [[`4dca30c`](https://github.com/Effect-TS/effect/commit/4dca30cfcdafe4542e236489f71d6f171a5b4e38), [`1d99867`](https://github.com/Effect-TS/effect/commit/1d998671be3cd11043f232822e91dd8c98fccfa9), [`6dae414`](https://github.com/Effect-TS/effect/commit/6dae4147991a97ec14a99289bd25fadae7541e8d), [`6b0d737`](https://github.com/Effect-TS/effect/commit/6b0d737078bf63b97891e6bc47affc04b28f9cf7), [`d8356aa`](https://github.com/Effect-TS/effect/commit/d8356aad428a0c2290db52380220f81d9ec94232)]:\n  - effect@3.10.16\n  - @effect/sql@0.20.9\n\n## 0.16.8\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.20.8\n\n## 0.16.7\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.20.7\n\n## 0.16.6\n\n### Patch Changes\n\n- Updated dependencies [[`8398b32`](https://github.com/Effect-TS/effect/commit/8398b3208242a88239d4449910b7baf923cfe3b6), [`72e55b7`](https://github.com/Effect-TS/effect/commit/72e55b7c610784fcebdbadc592c876e23e76a986)]:\n  - effect@3.10.15\n  - @effect/sql@0.20.6\n\n## 0.16.5\n\n### Patch Changes\n\n- Updated dependencies [[`f983946`](https://github.com/Effect-TS/effect/commit/f9839467b4cad6e788297764ef9f9f0b9fd203f9), [`2d8a750`](https://github.com/Effect-TS/effect/commit/2d8a75081eb83a0a81f817fdf6f428369c5064ab)]:\n  - effect@3.10.14\n  - @effect/sql@0.20.5\n\n## 0.16.4\n\n### Patch Changes\n\n- Updated dependencies [[`995bbdf`](https://github.com/Effect-TS/effect/commit/995bbdffea2e332f203cd5b474cd6a1c77dfa6ae)]:\n  - effect@3.10.13\n  - @effect/sql@0.20.4\n\n## 0.16.3\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.20.3\n\n## 0.16.2\n\n### Patch Changes\n\n- Updated dependencies [[`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6)]:\n  - effect@3.10.12\n  - @effect/sql@0.20.2\n\n## 0.16.1\n\n### Patch Changes\n\n- Updated dependencies [[`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a)]:\n  - effect@3.10.11\n  - @effect/sql@0.20.1\n\n## 0.16.0\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.20.0\n\n## 0.15.0\n\n### Patch Changes\n\n- Updated dependencies [[`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`b631f40`](https://github.com/Effect-TS/effect/commit/b631f40abbe649b2a089764585b5c39f6a695ac6)]:\n  - effect@3.10.10\n  - @effect/sql@0.19.0\n\n## 0.14.16\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.18.16\n\n## 0.14.15\n\n### Patch Changes\n\n- Updated dependencies [[`a123e80`](https://github.com/Effect-TS/effect/commit/a123e80f111a625428a5b5622b7f55ee1073566b), [`bd5fcd3`](https://github.com/Effect-TS/effect/commit/bd5fcd3e6b603b1e505af90d6a00627c8eca6d41), [`0289d3b`](https://github.com/Effect-TS/effect/commit/0289d3b6391031d00329365bab9791b355031fe3), [`7386b71`](https://github.com/Effect-TS/effect/commit/7386b710e5be570e17f468928a6ed19d549a3e12), [`4211a23`](https://github.com/Effect-TS/effect/commit/4211a2355bb3af3f0e756e2aae9d293379f25662)]:\n  - effect@3.10.9\n  - @effect/sql@0.18.15\n\n## 0.14.14\n\n### Patch Changes\n\n- Updated dependencies [[`68b5c9e`](https://github.com/Effect-TS/effect/commit/68b5c9e44f34192cef26e1cadda5e661a027df41), [`9c9928d`](https://github.com/Effect-TS/effect/commit/9c9928dfeacd9ac33dc37eb0ca3d7d8c39175ada), [`6306e66`](https://github.com/Effect-TS/effect/commit/6306e6656092b350d4ede5746da6f245ec9f7e07), [`361c7f3`](https://github.com/Effect-TS/effect/commit/361c7f39a2c10ede9324847c3d3ba192a6f9b20a)]:\n  - effect@3.10.8\n  - @effect/sql@0.18.14\n\n## 0.14.13\n\n### Patch Changes\n\n- Updated dependencies [[`33f5b9f`](https://github.com/Effect-TS/effect/commit/33f5b9ffaebea4f1bd0e391b44c41fb6230e743a), [`50f0281`](https://github.com/Effect-TS/effect/commit/50f0281b0d2116726b8927a6217622d5f394f3e4)]:\n  - effect@3.10.7\n  - @effect/sql@0.18.13\n\n## 0.14.12\n\n### Patch Changes\n\n- Updated dependencies [[`ce1c21f`](https://github.com/Effect-TS/effect/commit/ce1c21ffc11902ac9ab453a51904207859d38552)]:\n  - effect@3.10.6\n  - @effect/sql@0.18.12\n\n## 0.14.11\n\n### Patch Changes\n\n- Updated dependencies [[`3a6d757`](https://github.com/Effect-TS/effect/commit/3a6d757badeebe00d8ef4d67530d073c8264dcfa), [`59d813a`](https://github.com/Effect-TS/effect/commit/59d813aa4973d1115cfc70cc3667508335f49693)]:\n  - effect@3.10.5\n  - @effect/sql@0.18.11\n\n## 0.14.10\n\n### Patch Changes\n\n- Updated dependencies [[`2367708`](https://github.com/Effect-TS/effect/commit/2367708be449f9526a2047e321302d7bfb16f18e)]:\n  - effect@3.10.4\n  - @effect/sql@0.18.10\n\n## 0.14.9\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.18.9\n\n## 0.14.8\n\n### Patch Changes\n\n- Updated dependencies [[`b9423d8`](https://github.com/Effect-TS/effect/commit/b9423d8bf8181a2389fdbce1e3c14ac6fe8d54f5)]:\n  - effect@3.10.3\n  - @effect/sql@0.18.8\n\n## 0.14.7\n\n### Patch Changes\n\n- Updated dependencies [[`714e119`](https://github.com/Effect-TS/effect/commit/714e11945e45e5a2554ee058e6c43f82a8e309cf), [`c1afd55`](https://github.com/Effect-TS/effect/commit/c1afd55c54e61f9c432823d21b3d016f79160a37)]:\n  - effect@3.10.2\n  - @effect/sql@0.18.7\n\n## 0.14.6\n\n### Patch Changes\n\n- Updated dependencies [[`9604d6b`](https://github.com/Effect-TS/effect/commit/9604d6b616435103dafea8b53637a9d1450b4750)]:\n  - effect@3.10.1\n  - @effect/sql@0.18.6\n\n## 0.14.5\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.18.5\n\n## 0.14.4\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.18.4\n\n## 0.14.3\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.18.3\n\n## 0.14.2\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.18.2\n\n## 0.14.1\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.18.1\n\n## 0.14.0\n\n### Patch Changes\n\n- Updated dependencies [[`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`c79c4c1`](https://github.com/Effect-TS/effect/commit/c79c4c178390fe61ff6dda88c9e058862349343a), [`38d30f0`](https://github.com/Effect-TS/effect/commit/38d30f08b8da62f9c3e308b9250738cb8d17bdb5), [`5821ce3`](https://github.com/Effect-TS/effect/commit/5821ce3455b47d25e0a40cae6ce22af9db5fa556)]:\n  - effect@3.10.0\n  - @effect/sql@0.18.0\n\n## 0.13.0\n\n### Patch Changes\n\n- [#3760](https://github.com/Effect-TS/effect/pull/3760) [`dacbf7d`](https://github.com/Effect-TS/effect/commit/dacbf7db59899065aee4e5dd95a6459880e09ceb) Thanks @tim-smart! - add sql-clickhouse & clickhouse dialect\n\n- Updated dependencies [[`dacbf7d`](https://github.com/Effect-TS/effect/commit/dacbf7db59899065aee4e5dd95a6459880e09ceb)]:\n  - @effect/sql@0.17.0\n\n## 0.12.6\n\n### Patch Changes\n\n- Updated dependencies [[`382556f`](https://github.com/Effect-TS/effect/commit/382556f8930780c0634de681077706113a8c8239), [`97cb014`](https://github.com/Effect-TS/effect/commit/97cb0145114b2cd2f378e98f6c4ff5bf2c1865f5)]:\n  - @effect/schema@0.75.5\n  - @effect/sql@0.16.6\n\n## 0.12.5\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.16.5\n\n## 0.12.4\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.16.4\n\n## 0.12.3\n\n### Patch Changes\n\n- Updated dependencies [[`61a99b2`](https://github.com/Effect-TS/effect/commit/61a99b2bf9d757870ef0c2ec9d4c877cdd364a3d)]:\n  - effect@3.9.2\n  - @effect/schema@0.75.4\n  - @effect/sql@0.16.3\n\n## 0.12.2\n\n### Patch Changes\n\n- Updated dependencies [[`360ec14`](https://github.com/Effect-TS/effect/commit/360ec14dd4102c526aef7433a8881ad4d9beab75)]:\n  - @effect/schema@0.75.3\n  - @effect/sql@0.16.2\n\n## 0.12.1\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.16.1\n\n## 0.12.0\n\n### Patch Changes\n\n- Updated dependencies [[`f02b354`](https://github.com/Effect-TS/effect/commit/f02b354ab5b0451143b82bb73dc866be29adec85)]:\n  - @effect/schema@0.75.2\n  - @effect/sql@0.16.0\n\n## 0.11.1\n\n### Patch Changes\n\n- Updated dependencies [[`3b2ad1d`](https://github.com/Effect-TS/effect/commit/3b2ad1d58a2e33dc1a72b7037396bd25ca1702a9)]:\n  - effect@3.9.1\n  - @effect/schema@0.75.1\n  - @effect/sql@0.15.1\n\n## 0.11.0\n\n### Patch Changes\n\n- Updated dependencies [[`ff3d1aa`](https://github.com/Effect-TS/effect/commit/ff3d1aab290b4d1173b2dfc7e4c76abb4babdc16), [`0ba66f2`](https://github.com/Effect-TS/effect/commit/0ba66f2451641fd6990e02ec1ed01c014db9dab0), [`bf77f51`](https://github.com/Effect-TS/effect/commit/bf77f51b323c383224ebf08adf77a7a6e8c9b3cd), [`016f9ad`](https://github.com/Effect-TS/effect/commit/016f9ad931a4b3d09a34e5caf13d87c5b8e9c984), [`0779681`](https://github.com/Effect-TS/effect/commit/07796813f07de035719728733096ba64ce333469), [`534129f`](https://github.com/Effect-TS/effect/commit/534129f8113ce1a8ec50828083e16da9c86326c6), [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda), [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03), [`9237ac6`](https://github.com/Effect-TS/effect/commit/9237ac69bc07de5b3b60076a0ad2921c21de7457), [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03), [`5b36494`](https://github.com/Effect-TS/effect/commit/5b364942e9a9003fdb8217324f8a2d8369c969da), [`c716adb`](https://github.com/Effect-TS/effect/commit/c716adb250ebbea1d1048d818ef7fed4f621d186), [`4986391`](https://github.com/Effect-TS/effect/commit/49863919cd8628c962a712fb1df30d2983820933), [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda), [`d1387ae`](https://github.com/Effect-TS/effect/commit/d1387aebd1ff01bbebde26be46d488956e4daef6)]:\n  - effect@3.9.0\n  - @effect/schema@0.75.0\n  - @effect/sql@0.15.0\n\n## 0.10.1\n\n### Patch Changes\n\n- Updated dependencies [[`88e85db`](https://github.com/Effect-TS/effect/commit/88e85db34bd402526e27a323e950d053fa34d232), [`83887ca`](https://github.com/Effect-TS/effect/commit/83887ca1b1793916913d8550a4db4450cd14a044), [`5266b6c`](https://github.com/Effect-TS/effect/commit/5266b6cd86d76c3886da041c8829bca04b1a3110), [`cdead5c`](https://github.com/Effect-TS/effect/commit/cdead5c9cfd54dc6c4f215d9732f654c4a12e991), [`766a8af`](https://github.com/Effect-TS/effect/commit/766a8af307b414aca3648d91c4eab7493a5ec862)]:\n  - effect@3.8.5\n  - @effect/schema@0.74.2\n  - @effect/sql@0.14.1\n\n## 0.10.0\n\n### Patch Changes\n\n- Updated dependencies [[`f100e20`](https://github.com/Effect-TS/effect/commit/f100e2087172d7e4ab8c0d1ee9a5780b9712382a)]:\n  - @effect/sql@0.14.0\n\n## 0.9.4\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.13.4\n\n## 0.9.3\n\n### Patch Changes\n\n- Updated dependencies [[`0a68746`](https://github.com/Effect-TS/effect/commit/0a68746c89651c364db2ee8c72dcfe552e1782ea), [`734eae6`](https://github.com/Effect-TS/effect/commit/734eae654f215e4adca457d04d2a1728b1a55c83), [`fd83d0e`](https://github.com/Effect-TS/effect/commit/fd83d0e548feff9ea2d53d370a0b626c4a1d940e), [`4509656`](https://github.com/Effect-TS/effect/commit/45096569d50262275ee984f44c456f5c83b62683), [`ad7e1de`](https://github.com/Effect-TS/effect/commit/ad7e1de948745c0751bfdac96671028ff4b7a727), [`090e41c`](https://github.com/Effect-TS/effect/commit/090e41c636d720b1c7d89684a739855765ed4382), [`090e41c`](https://github.com/Effect-TS/effect/commit/090e41c636d720b1c7d89684a739855765ed4382)]:\n  - @effect/sql@0.13.3\n  - @effect/schema@0.74.1\n  - effect@3.8.4\n\n## 0.9.2\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.13.2\n\n## 0.9.1\n\n### Patch Changes\n\n- Updated dependencies [[`d5c8e7e`](https://github.com/Effect-TS/effect/commit/d5c8e7e47373f9fd78637f24e36d6fb61ee35eb4)]:\n  - @effect/sql@0.13.1\n\n## 0.9.0\n\n### Patch Changes\n\n- Updated dependencies [[`de48aa5`](https://github.com/Effect-TS/effect/commit/de48aa54e98d97722a8a4c2c8f9e1fe1d4560ea2)]:\n  - @effect/schema@0.74.0\n  - @effect/sql@0.13.0\n\n## 0.8.6\n\n### Patch Changes\n\n- Updated dependencies [[`bb5ec6b`](https://github.com/Effect-TS/effect/commit/bb5ec6b4b6a6f537394596c5a596faf52cb2aef4)]:\n  - effect@3.8.3\n  - @effect/sql@0.12.6\n  - @effect/schema@0.73.4\n\n## 0.8.5\n\n### Patch Changes\n\n- Updated dependencies [[`e6440a7`](https://github.com/Effect-TS/effect/commit/e6440a74fb3f12f6422ed794c07cb44af91cbacc)]:\n  - @effect/schema@0.73.3\n  - @effect/sql@0.12.5\n\n## 0.8.4\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.12.4\n\n## 0.8.3\n\n### Patch Changes\n\n- Updated dependencies [[`f0d8ef1`](https://github.com/Effect-TS/effect/commit/f0d8ef1ce97ec2a87b09b3e24150cfeab85d6e2f)]:\n  - effect@3.8.2\n  - @effect/schema@0.73.2\n  - @effect/sql@0.12.3\n\n## 0.8.2\n\n### Patch Changes\n\n- Updated dependencies [[`10bf621`](https://github.com/Effect-TS/effect/commit/10bf6213f36d8ddb00f058a4609b85220f3d8334), [`f56ab78`](https://github.com/Effect-TS/effect/commit/f56ab785cbee0c1c43bd2c182c35602f486f61f0), [`ae36fa6`](https://github.com/Effect-TS/effect/commit/ae36fa68f754eeab9a54b6dc0f8b44db513aa2b6)]:\n  - effect@3.8.1\n  - @effect/schema@0.73.1\n  - @effect/sql@0.12.2\n\n## 0.8.1\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.12.1\n\n## 0.8.0\n\n### Patch Changes\n\n- Updated dependencies [[`fcfa6ee`](https://github.com/Effect-TS/effect/commit/fcfa6ee30ffd07d998bf22799357bf58580a116f), [`bb9931b`](https://github.com/Effect-TS/effect/commit/bb9931b62e249a3b801f2cb9d097aec0c8511af7), [`5798f76`](https://github.com/Effect-TS/effect/commit/5798f7619529de33e5ba06f551806f68fedc19db), [`5f0bfa1`](https://github.com/Effect-TS/effect/commit/5f0bfa17205398d4e4818bfbcf9e1b505b3b1fc5), [`7fdf9d9`](https://github.com/Effect-TS/effect/commit/7fdf9d9aa1e2c1c125cbf87991e6efbf4abb7b07), [`812a4e8`](https://github.com/Effect-TS/effect/commit/812a4e86e2d1aa23b477ef5829aa0e5c07784936), [`273565e`](https://github.com/Effect-TS/effect/commit/273565e7901639e8d0541930ab715aea9c80fbaa), [`569a801`](https://github.com/Effect-TS/effect/commit/569a8017ef0a0bc203e4312867cbdd37b0effbd7), [`aa1fa53`](https://github.com/Effect-TS/effect/commit/aa1fa5301e886b9657c8eb0d38cb87cef92a8305), [`02f6b06`](https://github.com/Effect-TS/effect/commit/02f6b0660e12bee1069532a9cc18d3ab855257be), [`12b893e`](https://github.com/Effect-TS/effect/commit/12b893e63cc6dfada4aca7773b4783940e2edf25), [`bbad27e`](https://github.com/Effect-TS/effect/commit/bbad27ec0a90860593f759405caa877e7f4a655f), [`adf7d7a`](https://github.com/Effect-TS/effect/commit/adf7d7a7dfce3a7021e9f3b0d847dc85be89d754), [`007289a`](https://github.com/Effect-TS/effect/commit/007289a52d5877f8e90e2dacf38171ff9bf603fd), [`42a8f99`](https://github.com/Effect-TS/effect/commit/42a8f99740eefdaf2c4544d2c345313f97547a36), [`eebfd29`](https://github.com/Effect-TS/effect/commit/eebfd29633fd5d38b505c5c0842036f61f05e913), [`040703d`](https://github.com/Effect-TS/effect/commit/040703d0e100cd5511e52d812c15492414262b5e)]:\n  - effect@3.8.0\n  - @effect/schema@0.73.0\n  - @effect/sql@0.12.0\n\n## 0.7.3\n\n### Patch Changes\n\n- Updated dependencies [[`ccd67df`](https://github.com/Effect-TS/effect/commit/ccd67df6b44ae7075a03759bc7866f6bc9ebb03e)]:\n  - @effect/sql@0.11.3\n\n## 0.7.2\n\n### Patch Changes\n\n- Updated dependencies [[`d8aff79`](https://github.com/Effect-TS/effect/commit/d8aff79d4cbedee33d0552ec43fdced007cae358), [`35a0f81`](https://github.com/Effect-TS/effect/commit/35a0f813141652d696461cd5d19fd146adaf85be), [`d8aff79`](https://github.com/Effect-TS/effect/commit/d8aff79d4cbedee33d0552ec43fdced007cae358)]:\n  - @effect/sql@0.11.2\n  - effect@3.7.3\n  - @effect/schema@0.72.4\n\n## 0.7.1\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.11.1\n\n## 0.7.0\n\n### Patch Changes\n\n- Updated dependencies [[`f6acb71`](https://github.com/Effect-TS/effect/commit/f6acb71b17a0e6b0d449e7f661c9e2c3d335fcac)]:\n  - @effect/schema@0.72.3\n  - @effect/sql@0.11.0\n\n## 0.6.4\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.10.4\n\n## 0.6.3\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.10.3\n\n## 0.6.2\n\n### Patch Changes\n\n- Updated dependencies [[`8a601d7`](https://github.com/Effect-TS/effect/commit/8a601d7a1f8ffe52ac9e6d67e9282a1495fe59c9), [`353ba19`](https://github.com/Effect-TS/effect/commit/353ba19f9b2b9e959f0a00d058c6d40a4bc02db7)]:\n  - effect@3.7.2\n  - @effect/schema@0.72.2\n  - @effect/sql@0.10.2\n\n## 0.6.1\n\n### Patch Changes\n\n- Updated dependencies [[`79859e7`](https://github.com/Effect-TS/effect/commit/79859e71040d8edf1868b8530b90c650f4321eff), [`f6a469c`](https://github.com/Effect-TS/effect/commit/f6a469c190b9f00eee5ea0cd4d5912a0ef8b46f5), [`dcb9ec0`](https://github.com/Effect-TS/effect/commit/dcb9ec0db443894dd204d87450f779c44b9ad7f1), [`79aa6b1`](https://github.com/Effect-TS/effect/commit/79aa6b136e1f29b36f34e88cb2ff162bff2bb4ed)]:\n  - effect@3.7.1\n  - @effect/schema@0.72.1\n  - @effect/sql@0.10.1\n\n## 0.6.0\n\n### Patch Changes\n\n- Updated dependencies [[`db89601`](https://github.com/Effect-TS/effect/commit/db89601ee9c1050c4e762b7bd7ec65a6a2799dfe), [`2f456cc`](https://github.com/Effect-TS/effect/commit/2f456cce5012b9fcb6b4e039190d527813b75b92), [`8745e41`](https://github.com/Effect-TS/effect/commit/8745e41ed96e3765dc6048efc2a9afbe05c8a1e9), [`e557838`](https://github.com/Effect-TS/effect/commit/e55783886b046d3c5f33447f455f9ccf2fa75922), [`d6e7e40`](https://github.com/Effect-TS/effect/commit/d6e7e40b1e2ad0c59aa02f07344d28601b14ebdc), [`8356321`](https://github.com/Effect-TS/effect/commit/8356321598da04bd77c1001f45a4e447bec5591d), [`192f2eb`](https://github.com/Effect-TS/effect/commit/192f2ebb2c4ddbf4bfd8baedd32140b2376868f4), [`718cb70`](https://github.com/Effect-TS/effect/commit/718cb70038629a6d58d02e407760e341f7c94474), [`e9d0310`](https://github.com/Effect-TS/effect/commit/e9d03107acbf204d9304f3e8aea0816b7d3c7dfb), [`6bf28f7`](https://github.com/Effect-TS/effect/commit/6bf28f7e3b1e5e0608ff567205fea0581d11666f)]:\n  - effect@3.7.0\n  - @effect/schema@0.72.0\n  - @effect/sql@0.10.0\n\n## 0.5.7\n\n### Patch Changes\n\n- Updated dependencies [[`e809286`](https://github.com/Effect-TS/effect/commit/e8092865900608c4df7a6b7991b1c13cc1e4ca2d)]:\n  - effect@3.6.8\n  - @effect/schema@0.71.4\n  - @effect/sql@0.9.7\n\n## 0.5.6\n\n### Patch Changes\n\n- Updated dependencies [[`50ec889`](https://github.com/Effect-TS/effect/commit/50ec8897a49b7d1fe84f63107f89d543c52f3dfc)]:\n  - effect@3.6.7\n  - @effect/sql@0.9.6\n  - @effect/schema@0.71.3\n\n## 0.5.5\n\n### Patch Changes\n\n- Updated dependencies [[`f960bf4`](https://github.com/Effect-TS/effect/commit/f960bf45239e9badac6e0ad3a602f4174cd7bbdf), [`46a575f`](https://github.com/Effect-TS/effect/commit/46a575f48a05457b782fb21f7827d338c9b59320)]:\n  - effect@3.6.6\n  - @effect/schema@0.71.2\n  - @effect/sql@0.9.5\n\n## 0.5.4\n\n### Patch Changes\n\n- Updated dependencies [[`14a47a8`](https://github.com/Effect-TS/effect/commit/14a47a8c1f3cff2186b8fe7a919a1d773888fb5b), [`35be739`](https://github.com/Effect-TS/effect/commit/35be739a413e32ed251f775714af2f87355e8664), [`f8326cc`](https://github.com/Effect-TS/effect/commit/f8326cc1095630a3fbee3f25d6b4e74edb905903), [`0c09841`](https://github.com/Effect-TS/effect/commit/0c0984173be3d58f050b300a1a8aa89d76ba49ae), [`8dd3959`](https://github.com/Effect-TS/effect/commit/8dd3959e967ca2b38ba601d94a80f1c50e9445e0), [`2cb6ebb`](https://github.com/Effect-TS/effect/commit/2cb6ebbf782b79643befa061c6adcf0366a7b8b3), [`5e9f51e`](https://github.com/Effect-TS/effect/commit/5e9f51e4a1169018d7f59a0db444c783cc1d5794), [`83a108a`](https://github.com/Effect-TS/effect/commit/83a108a254341721d20a82633b1e1d406d2368a3), [`f2c8dbb`](https://github.com/Effect-TS/effect/commit/f2c8dbb77e196c9a36cb3bf2ae3b82ce68e9874d), [`5e9f51e`](https://github.com/Effect-TS/effect/commit/5e9f51e4a1169018d7f59a0db444c783cc1d5794)]:\n  - effect@3.6.5\n  - @effect/sql@0.9.4\n  - @effect/schema@0.71.1\n\n## 0.5.3\n\n### Patch Changes\n\n- Updated dependencies [[`c3446d3`](https://github.com/Effect-TS/effect/commit/c3446d3e57b0cbfe9341d6f2aebf5f5d6fefefe3)]:\n  - @effect/sql@0.9.3\n\n## 0.5.2\n\n### Patch Changes\n\n- Updated dependencies [[`cfcfbdf`](https://github.com/Effect-TS/effect/commit/cfcfbdfe586b011a5edc28083fd5391edeee0023)]:\n  - @effect/sql@0.9.2\n\n## 0.5.1\n\n### Patch Changes\n\n- Updated dependencies [[`e9da539`](https://github.com/Effect-TS/effect/commit/e9da5396bba99b2ddc20c97c7955154e6da4cab5), [`4fabf75`](https://github.com/Effect-TS/effect/commit/4fabf75b44ea98b1773059bd589167d5d8f64f06)]:\n  - @effect/sql@0.9.1\n\n## 0.5.0\n\n### Patch Changes\n\n- Updated dependencies [[`c1987e2`](https://github.com/Effect-TS/effect/commit/c1987e25c8f5c48bdc9ad223d7a6f2c32f93f5a1), [`8295281`](https://github.com/Effect-TS/effect/commit/8295281ae9bd7441e680402540bf3c8682ec417b), [`c940df6`](https://github.com/Effect-TS/effect/commit/c940df63800bf3c4396d91cf28ec34938642fd2c), [`00b6c6d`](https://github.com/Effect-TS/effect/commit/00b6c6d4001f5de728b7d990a1b14560b4961a63), [`1ceed14`](https://github.com/Effect-TS/effect/commit/1ceed149dc64f4874e64b5cf2f954eba0a5a1f12), [`a07990d`](https://github.com/Effect-TS/effect/commit/a07990de977fb60ab4af1e8f3a2250454dedbb34), [`f8d95a6`](https://github.com/Effect-TS/effect/commit/f8d95a61ad0762147933c5c32bb6d7237e18eef4), [`0e42a8f`](https://github.com/Effect-TS/effect/commit/0e42a8f045ecb1fd3d080edf3d49fef16a9b0ca1)]:\n  - @effect/schema@0.71.0\n  - effect@3.6.4\n  - @effect/sql@0.9.0\n\n## 0.4.7\n\n### Patch Changes\n\n- Updated dependencies [[`04adcac`](https://github.com/Effect-TS/effect/commit/04adcace913e6fc483df266874a68005e9e04ccf)]:\n  - effect@3.6.3\n  - @effect/schema@0.70.4\n  - @effect/sql@0.8.7\n\n## 0.4.6\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.8.6\n\n## 0.4.5\n\n### Patch Changes\n\n- Updated dependencies [[`99ad841`](https://github.com/Effect-TS/effect/commit/99ad8415293a82d08bd7043c563b29e2b468ca74), [`fd4b2f6`](https://github.com/Effect-TS/effect/commit/fd4b2f6516b325740dde615f1cf0229edf13ca0c)]:\n  - @effect/schema@0.70.3\n  - effect@3.6.2\n  - @effect/sql@0.8.5\n\n## 0.4.4\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.8.4\n\n## 0.4.3\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.8.3\n\n## 0.4.2\n\n### Patch Changes\n\n- Updated dependencies [[`510a34d`](https://github.com/Effect-TS/effect/commit/510a34d4cc5d2f51347a53847f6c7db84d2b17c6), [`45dbb9f`](https://github.com/Effect-TS/effect/commit/45dbb9ffeaf93d9e4df99d0cd4920e41ba9a3978)]:\n  - effect@3.6.1\n  - @effect/schema@0.70.2\n  - @effect/sql@0.8.2\n\n## 0.4.1\n\n### Patch Changes\n\n- Updated dependencies [[`3dce357`](https://github.com/Effect-TS/effect/commit/3dce357efe4a4451d7d29859d08ac11713999b1a), [`657fc48`](https://github.com/Effect-TS/effect/commit/657fc48bb32daf2dc09c9335b3cbc3152bcbdd3b)]:\n  - @effect/schema@0.70.1\n  - @effect/sql@0.8.1\n\n## 0.4.0\n\n### Patch Changes\n\n- Updated dependencies [[`42d0706`](https://github.com/Effect-TS/effect/commit/42d07067e9823ceb8977eff9672d9a290941dad5)]:\n  - @effect/sql@0.8.0\n\n## 0.3.0\n\n### Patch Changes\n\n- Updated dependencies [[`1e0fe80`](https://github.com/Effect-TS/effect/commit/1e0fe802b36c257971296617473ce0abe730e8dc), [`8135294`](https://github.com/Effect-TS/effect/commit/8135294b591ea94fde7e6f94a504608f0e630520), [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987), [`3845646`](https://github.com/Effect-TS/effect/commit/3845646828e98f3c7cda1217f6cfe5f642ac0603), [`2d09078`](https://github.com/Effect-TS/effect/commit/2d09078c5948b37fc2f79ef858fe4ca3e4814085), [`4bce5a0`](https://github.com/Effect-TS/effect/commit/4bce5a0274203550ccf117d830721891b0a3d182), [`4ddbff0`](https://github.com/Effect-TS/effect/commit/4ddbff0bb4e3ffddfeb509c59835b83245fb975e), [`e74cc38`](https://github.com/Effect-TS/effect/commit/e74cc38cb420a320c4d7ef98180f19d452a8b316), [`bb069b4`](https://github.com/Effect-TS/effect/commit/bb069b49ef291c532a02c1e8e74271f6d1bb32ec), [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987), [`7d02174`](https://github.com/Effect-TS/effect/commit/7d02174af3bcbf054e5cdddb821c91d0f47e8285)]:\n  - effect@3.6.0\n  - @effect/schema@0.70.0\n  - @effect/sql@0.7.0\n\n## 0.2.3\n\n### Patch Changes\n\n- Updated dependencies [[`7c0da50`](https://github.com/Effect-TS/effect/commit/7c0da5050d30cb804f4eacb15995d0fb7f3a28d2), [`2fc0ff4`](https://github.com/Effect-TS/effect/commit/2fc0ff4c59c25977018f6ac70ced99b04a8c7b2b), [`6359644`](https://github.com/Effect-TS/effect/commit/635964446323cf55d4060559337e710e4a24496e), [`f262665`](https://github.com/Effect-TS/effect/commit/f262665c2773492c01e5dd0e8d6db235aafaaad8), [`7f41e42`](https://github.com/Effect-TS/effect/commit/7f41e428830bf3043b8be0d28dcd235d5747c942), [`9bbe7a6`](https://github.com/Effect-TS/effect/commit/9bbe7a681430ebf5c10167bb7140ba3742e46bb7), [`f566fd1`](https://github.com/Effect-TS/effect/commit/f566fd1d7eea531a0d981dd24037f14a603a1273)]:\n  - @effect/schema@0.69.3\n  - effect@3.5.9\n  - @effect/sql@0.6.3\n\n## 0.2.2\n\n### Patch Changes\n\n- Updated dependencies [[`1ba640c`](https://github.com/Effect-TS/effect/commit/1ba640c702f187a866023bf043c26e25cce941ef), [`c8c71bd`](https://github.com/Effect-TS/effect/commit/c8c71bd20eb87d23133dac6156b83bb08941597c), [`a26ce58`](https://github.com/Effect-TS/effect/commit/a26ce581ca7d407e1e81439b58c8045b3fa65231)]:\n  - effect@3.5.8\n  - @effect/sql@0.6.2\n  - @effect/schema@0.69.2\n\n## 0.2.1\n\n### Patch Changes\n\n- Updated dependencies [[`f241154`](https://github.com/Effect-TS/effect/commit/f241154added5d91e95866c39481f09cdb13bd4d)]:\n  - @effect/schema@0.69.1\n  - @effect/sql@0.6.1\n\n## 0.2.0\n\n### Patch Changes\n\n- Updated dependencies [[`20807a4`](https://github.com/Effect-TS/effect/commit/20807a45edeb4334e903dca5d708cd62a71702d8)]:\n  - @effect/schema@0.69.0\n  - @effect/sql@0.6.0\n\n## 0.1.3\n\n### Patch Changes\n\n- [#3310](https://github.com/Effect-TS/effect/pull/3310) [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc) Thanks @fubhy! - Added additional pure annotations to improve tree-shakeability\n\n- Updated dependencies [[`3afcc93`](https://github.com/Effect-TS/effect/commit/3afcc93413a3d910beb69e4ce9ae120e4adaffd5), [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc), [`6921c4f`](https://github.com/Effect-TS/effect/commit/6921c4fb8c45badff09b493043b85ca71302b560)]:\n  - effect@3.5.7\n  - @effect/schema@0.68.27\n  - @effect/sql@0.5.3\n\n## 0.1.2\n\n### Patch Changes\n\n- Updated dependencies [[`f0285d3`](https://github.com/Effect-TS/effect/commit/f0285d3af6a18829123bc1818331c67206becbc4), [`8ec4955`](https://github.com/Effect-TS/effect/commit/8ec49555ed3b3c98093fa4d135a4c57a3f16ebd1), [`3ac2d76`](https://github.com/Effect-TS/effect/commit/3ac2d76048da09e876cf6c3aee3397febd843fe9), [`cc327a1`](https://github.com/Effect-TS/effect/commit/cc327a1bccd22a4ee27ec7e58b53205e93b23e2c), [`4bfe4fb`](https://github.com/Effect-TS/effect/commit/4bfe4fb5c82f597c9beea9baa92e772593598b60), [`2b14d18`](https://github.com/Effect-TS/effect/commit/2b14d181462cad8359da4fa6bc6dfda0f742c398)]:\n  - @effect/schema@0.68.26\n  - effect@3.5.6\n  - @effect/sql@0.5.2\n\n## 0.1.1\n\n### Patch Changes\n\n- Updated dependencies [[`a9d7800`](https://github.com/Effect-TS/effect/commit/a9d7800f6a253192b653d77778b0674f39b1ca39)]:\n  - effect@3.5.5\n  - @effect/schema@0.68.25\n  - @effect/sql@0.5.1\n\n## 0.1.0\n\n### Patch Changes\n\n- Updated dependencies [[`53c0db0`](https://github.com/Effect-TS/effect/commit/53c0db06872d5b5edea2a706e83249908385325c), [`ed0dde4`](https://github.com/Effect-TS/effect/commit/ed0dde4888e6f1a97ad5bba06b755d26a6a1c52e), [`ca775ce`](https://github.com/Effect-TS/effect/commit/ca775cec53baebc1a43d9b8852a3ac6726178498), [`5be9cc0`](https://github.com/Effect-TS/effect/commit/5be9cc044025a9541b9b7acefa2d3fc05fa1301b), [`203658f`](https://github.com/Effect-TS/effect/commit/203658f8001c132b25764ab70344b171683b554c), [`eb1c4d4`](https://github.com/Effect-TS/effect/commit/eb1c4d44e54b9d8d201a366d1ff94face2a6dcd3)]:\n  - @effect/sql@0.5.0\n  - effect@3.5.4\n  - @effect/schema@0.68.24\n\n## 0.0.32\n\n### Patch Changes\n\n- Updated dependencies [[`edb0da3`](https://github.com/Effect-TS/effect/commit/edb0da383746d760f35d8582f5fb0cc0eeca9217), [`edb0da3`](https://github.com/Effect-TS/effect/commit/edb0da383746d760f35d8582f5fb0cc0eeca9217), [`c8d3fb0`](https://github.com/Effect-TS/effect/commit/c8d3fb0fe23585f6efb724af51fbab3ba1ad6e83), [`dabd028`](https://github.com/Effect-TS/effect/commit/dabd028decf9b7983ca16ebe0f48c05c11a84b68), [`786b2ab`](https://github.com/Effect-TS/effect/commit/786b2ab29d525c877bb84035dac9e2d6499339d1), [`fc57354`](https://github.com/Effect-TS/effect/commit/fc573547d41667016fce05eaee75960fcc6dce4d)]:\n  - effect@3.5.3\n  - @effect/schema@0.68.23\n  - @effect/sql@0.4.27\n\n## 0.0.31\n\n### Patch Changes\n\n- Updated dependencies [[`639208e`](https://github.com/Effect-TS/effect/commit/639208eeb8a44622994f832bc2d45d06ab636bc8), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5)]:\n  - effect@3.5.2\n  - @effect/schema@0.68.22\n  - @effect/sql@0.4.26\n\n## 0.0.30\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.4.25\n\n## 0.0.29\n\n### Patch Changes\n\n- Updated dependencies [[`55fdd76`](https://github.com/Effect-TS/effect/commit/55fdd761ee95afd73b6a892c13fee92b36c02837)]:\n  - effect@3.5.1\n  - @effect/schema@0.68.21\n  - @effect/sql@0.4.24\n\n## 0.0.28\n\n### Patch Changes\n\n- Updated dependencies [[`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`5ab348f`](https://github.com/Effect-TS/effect/commit/5ab348f265db3d283aa091ddca6d2d49137c16f2), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`3e04bf8`](https://github.com/Effect-TS/effect/commit/3e04bf8a7127e956cadb7684a8f4c661df57663b), [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`4626de5`](https://github.com/Effect-TS/effect/commit/4626de59c25b384216faa0be87bf0b8cd36357d0), [`f01e7db`](https://github.com/Effect-TS/effect/commit/f01e7db317827255d7901f523f2e28b43298e8df), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6), [`ac71f37`](https://github.com/Effect-TS/effect/commit/ac71f378f2413e5aa91c95f649ffe898d6a26114), [`8432360`](https://github.com/Effect-TS/effect/commit/8432360ce68614a419bb328083a4109d0fc8aa93), [`e4bf1bf`](https://github.com/Effect-TS/effect/commit/e4bf1bf2b4a970eacd77c9b77b5ea8c68bc84498), [`13cb861`](https://github.com/Effect-TS/effect/commit/13cb861a5eded15c55c6cdcf6a8acde8320367a6), [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6), [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3), [`9f66825`](https://github.com/Effect-TS/effect/commit/9f66825f1fce0fe8d10420c285f7dc4c71e8af8d)]:\n  - effect@3.5.0\n  - @effect/schema@0.68.20\n  - @effect/sql@0.4.23\n\n## 0.0.27\n\n### Patch Changes\n\n- Updated dependencies [[`7af137c`](https://github.com/Effect-TS/effect/commit/7af137c9433f6e74959b3887561ec1e6f12e10ee), [`ee4b3dc`](https://github.com/Effect-TS/effect/commit/ee4b3dc5f68d19dc3ae1c2d12901c5b8ffbebabb), [`097d25c`](https://github.com/Effect-TS/effect/commit/097d25cb5d13c049e01789651be56b09620186ef)]:\n  - effect@3.4.9\n  - @effect/schema@0.68.19\n  - @effect/sql@0.4.22\n\n## 0.0.26\n\n### Patch Changes\n\n- Updated dependencies [[`5d5cc6c`](https://github.com/Effect-TS/effect/commit/5d5cc6cfd7d63b07081290fb189b364999201fc5), [`a435e0f`](https://github.com/Effect-TS/effect/commit/a435e0fc5378b33a49bcec92ee235df6f16a2419), [`b5554db`](https://github.com/Effect-TS/effect/commit/b5554db36c4dd6f64fa5e6a62a29b2759c54217a), [`359ff8a`](https://github.com/Effect-TS/effect/commit/359ff8aa2e4e6389bf56d759baa804e2a7674a16), [`a9c4fb3`](https://github.com/Effect-TS/effect/commit/a9c4fb3bf3c6e92cd1c142b0605fddf7eb3c697c), [`f7534b9`](https://github.com/Effect-TS/effect/commit/f7534b94cba06b143a3d4f29275d92874a939559)]:\n  - @effect/schema@0.68.18\n  - effect@3.4.8\n  - @effect/sql@0.4.21\n\n## 0.0.25\n\n### Patch Changes\n\n- Updated dependencies [[`15967cf`](https://github.com/Effect-TS/effect/commit/15967cf18931fb6ede3083eb687a8dfff371cc56), [`2328e17`](https://github.com/Effect-TS/effect/commit/2328e17577112db17c29b7756942a0ff64a70ee0), [`a5737d6`](https://github.com/Effect-TS/effect/commit/a5737d6db2b921605c332eabbc5402ee3d17357b)]:\n  - @effect/schema@0.68.17\n  - effect@3.4.7\n  - @effect/sql@0.4.20\n\n## 0.0.24\n\n### Patch Changes\n\n- Updated dependencies [[`d006cec`](https://github.com/Effect-TS/effect/commit/d006cec022e8524dbfd6dc6df751fe4c86b10042), [`cb22726`](https://github.com/Effect-TS/effect/commit/cb2272656881aa5878a1c3fc0b12d8fbc66eb63c), [`e911cfd`](https://github.com/Effect-TS/effect/commit/e911cfdc79418462d7e9000976fded15ea6b738d)]:\n  - @effect/schema@0.68.16\n  - @effect/sql@0.4.19\n\n## 0.0.23\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.4.18\n\n## 0.0.22\n\n### Patch Changes\n\n- Updated dependencies [[`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`34faeb6`](https://github.com/Effect-TS/effect/commit/34faeb6305ba52af4d6f8bdd2e633bb6a5a7a35b), [`33735b1`](https://github.com/Effect-TS/effect/commit/33735b16b41bd26929d8f4754c190925db6323b7), [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`139d4b3`](https://github.com/Effect-TS/effect/commit/139d4b39fb3bff2eeaa7c0c809c581da42425a83)]:\n  - effect@3.4.6\n  - @effect/schema@0.68.15\n  - @effect/sql@0.4.17\n\n## 0.0.21\n\n### Patch Changes\n\n- Updated dependencies [[`61e5964`](https://github.com/Effect-TS/effect/commit/61e59640fd993216cca8ace0ac8abd9104e213ce)]:\n  - @effect/schema@0.68.14\n  - @effect/sql@0.4.16\n\n## 0.0.20\n\n### Patch Changes\n\n- Updated dependencies [[`cb76bcb`](https://github.com/Effect-TS/effect/commit/cb76bcb2f8858a90db4f785efee262cea1b9844e)]:\n  - @effect/schema@0.68.13\n  - @effect/sql@0.4.15\n\n## 0.0.19\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.4.14\n\n## 0.0.18\n\n### Patch Changes\n\n- Updated dependencies [[`a047af9`](https://github.com/Effect-TS/effect/commit/a047af99447dfffc729e9c8ef0ca143537927e91), [`d990544`](https://github.com/Effect-TS/effect/commit/d9905444b9e800850cb65899114ca0e502e68fe8)]:\n  - effect@3.4.5\n  - @effect/schema@0.68.12\n  - @effect/sql@0.4.13\n\n## 0.0.17\n\n### Patch Changes\n\n- Updated dependencies [[`72638e3`](https://github.com/Effect-TS/effect/commit/72638e3d99f0e93a24febf6c225256ce92d4a20b), [`d7dde2b`](https://github.com/Effect-TS/effect/commit/d7dde2b4af08b37af859d4c327c1f5c6f00cf9d9), [`9b2fc3b`](https://github.com/Effect-TS/effect/commit/9b2fc3b9dfd304a2bd0508ef2313cfc54357be0c), [`d71c192`](https://github.com/Effect-TS/effect/commit/d71c192b89fd1162423acddc5fd3d6270fbf2ef6)]:\n  - effect@3.4.4\n  - @effect/schema@0.68.11\n  - @effect/sql@0.4.12\n\n## 0.0.16\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.4.11\n\n## 0.0.15\n\n### Patch Changes\n\n- [#3079](https://github.com/Effect-TS/effect/pull/3079) [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd) Thanks @tim-smart! - update to typescript 5.5\n\n- Updated dependencies [[`c342739`](https://github.com/Effect-TS/effect/commit/c3427396226e1ad7b95b40595a23f9bdff3e3365), [`8898e5e`](https://github.com/Effect-TS/effect/commit/8898e5e238622f6337583d91ee23609c1f5ccdf7), [`ff78636`](https://github.com/Effect-TS/effect/commit/ff786367c522975f40f0f179a0ecdfcfab7ecbdb), [`c86bd4e`](https://github.com/Effect-TS/effect/commit/c86bd4e134c23146c216f9ff97e03781d55991b6), [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd), [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd)]:\n  - effect@3.4.3\n  - @effect/schema@0.68.10\n  - @effect/sql@0.4.10\n\n## 0.0.14\n\n### Patch Changes\n\n- Updated dependencies [[`0b47fdf`](https://github.com/Effect-TS/effect/commit/0b47fdfe449f42de89e0e88b61ae5140f629e5c4)]:\n  - @effect/schema@0.68.9\n  - @effect/sql@0.4.9\n\n## 0.0.13\n\n### Patch Changes\n\n- Updated dependencies [[`192261b`](https://github.com/Effect-TS/effect/commit/192261b2aec94e9913ceed83683fdcfbc9fca66f), [`3da1497`](https://github.com/Effect-TS/effect/commit/3da1497b5c9cc886d300258bc928fd68a4fefe6f)]:\n  - @effect/schema@0.68.8\n  - effect@3.4.2\n  - @effect/sql@0.4.8\n\n## 0.0.12\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.4.7\n\n## 0.0.11\n\n### Patch Changes\n\n- Updated dependencies [[`66a1910`](https://github.com/Effect-TS/effect/commit/66a19109ff90c4252123b8809b8c8a74681dba6a)]:\n  - effect@3.4.1\n  - @effect/schema@0.68.7\n  - @effect/sql@0.4.6\n\n## 0.0.10\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.4.5\n\n## 0.0.9\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.4.4\n\n## 0.0.8\n\n### Patch Changes\n\n- Updated dependencies [[`530fa9e`](https://github.com/Effect-TS/effect/commit/530fa9e36b8532589b948fc4faa37593f36b7f42)]:\n  - @effect/schema@0.68.6\n  - @effect/sql@0.4.3\n\n## 0.0.7\n\n### Patch Changes\n\n- Updated dependencies [[`1d62815`](https://github.com/Effect-TS/effect/commit/1d62815a50f34115606940ffa397442d75a20c81)]:\n  - @effect/schema@0.68.5\n  - @effect/sql@0.4.2\n\n## 0.0.6\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.4.1\n\n## 0.0.5\n\n### Patch Changes\n\n- [#3035](https://github.com/Effect-TS/effect/pull/3035) [`d33d8b0`](https://github.com/Effect-TS/effect/commit/d33d8b050b8e3c87dcde9587083e6c1cf733f72b) Thanks @tim-smart! - restructure sql modules to have flat imports\n\n- Updated dependencies [[`c0ce180`](https://github.com/Effect-TS/effect/commit/c0ce180861ad0938053c0e6145e813fa6404df3b), [`d33d8b0`](https://github.com/Effect-TS/effect/commit/d33d8b050b8e3c87dcde9587083e6c1cf733f72b), [`61707b6`](https://github.com/Effect-TS/effect/commit/61707b6ffc7397c2ba0dce22512b44955724f60f), [`9c1b5b3`](https://github.com/Effect-TS/effect/commit/9c1b5b39e6c19604ce834f072a114ad392c50a06), [`a35faf8`](https://github.com/Effect-TS/effect/commit/a35faf8d116f94899bfc03feab33b004c8ddfdf7), [`ff73c0c`](https://github.com/Effect-TS/effect/commit/ff73c0cacd66132bfad2e5211b3eae347729c667), [`984d516`](https://github.com/Effect-TS/effect/commit/984d516ccd9412dc41188f6a46b748dd20dd5848), [`8c3b8a2`](https://github.com/Effect-TS/effect/commit/8c3b8a2ce208eab753b6206a51605a424f104e98), [`017e2f9`](https://github.com/Effect-TS/effect/commit/017e2f9b371ce24ea4945e5d7390c934ad3c39cf), [`91bf8a2`](https://github.com/Effect-TS/effect/commit/91bf8a2e9d1959393b3cf7366cc1d584d3e666b7), [`c6a4a26`](https://github.com/Effect-TS/effect/commit/c6a4a266606575fd2c7165940c4072ad4c57d01f)]:\n  - effect@3.4.0\n  - @effect/sql@0.4.0\n  - @effect/schema@0.68.4\n\n## 0.0.4\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/sql@0.3.18\n\n## 0.0.3\n\n### Patch Changes\n\n- Updated dependencies [[`d473800`](https://github.com/Effect-TS/effect/commit/d47380012c3241d7287b66968d33a2414275ce7b)]:\n  - @effect/schema@0.68.3\n  - @effect/sql@0.3.17\n\n## 0.0.2\n\n### Patch Changes\n\n- Updated dependencies [[`eb341b3`](https://github.com/Effect-TS/effect/commit/eb341b3eb34ad64499371bc08b7f59e429979d8a)]:\n  - @effect/schema@0.68.2\n  - @effect/sql@0.3.16\n"
  },
  {
    "path": "packages/cluster/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023-present The Contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/cluster/README.md",
    "content": "## Documentation\n\n- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/cluster).\n\n.\n"
  },
  {
    "path": "packages/cluster/docgen.json",
    "content": "{\n  \"$schema\": \"../../node_modules/@effect/docgen/schema.json\",\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/cluster/src/\",\n  \"exclude\": [\"src/internal/**/*.ts\"],\n  \"examplesCompilerOptions\": {\n    \"noEmit\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"module\": \"ES2022\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n    \"paths\": {\n      \"effect\": [\"../../../effect/src/index.js\"],\n      \"effect/*\": [\"../../../effect/src/*.js\"],\n      \"@effect/cluster\": [\"../../../cluster/src/index.js\"],\n      \"@effect/cluster/*\": [\"../../../cluster/src/*.js\"],\n      \"@effect/experimental\": [\"../../../experimental/src/index.js\"],\n      \"@effect/experimental/*\": [\"../../../experimental/src/*.js\"],\n      \"@effect/platform\": [\"../../../platform/src/index.js\"],\n      \"@effect/platform/*\": [\"../../../platform/src/*.js\"],\n      \"@effect/platform-node\": [\"../../../platform-node/src/index.js\"],\n      \"@effect/platform-node/*\": [\"../../../platform-node/src/*.js\"],\n      \"@effect/platform-node-shared\": [\n        \"../../../platform-node-shared/src/index.js\"\n      ],\n      \"@effect/platform-node-shared/*\": [\n        \"../../../platform-node-shared/src/*.js\"\n      ],\n      \"@effect/rpc\": [\"../../../rpc/src/index.js\"],\n      \"@effect/rpc/*\": [\"../../../rpc/src/*.js\"],\n      \"@effect/sql\": [\"../../../sql/src/index.js\"],\n      \"@effect/sql/*\": [\"../../../sql/src/*.js\"],\n      \"@effect/workflow\": [\"../../../workflow/src/index.js\"],\n      \"@effect/workflow/*\": [\"../../../workflow/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/cluster/package.json",
    "content": "{\n  \"name\": \"@effect/cluster\",\n  \"type\": \"module\",\n  \"version\": \"0.58.0\",\n  \"description\": \"Unified interfaces for common cluster-specific services\",\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/cluster\"\n  },\n  \"homepage\": \"https://effect.website\",\n  \"license\": \"MIT\",\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"peerDependencies\": {\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/rpc\": \"workspace:^\",\n    \"@effect/sql\": \"workspace:^\",\n    \"@effect/workflow\": \"workspace:^\",\n    \"effect\": \"workspace:^\"\n  },\n  \"devDependencies\": {\n    \"@effect/platform\": \"workspace:^\",\n    \"@effect/platform-node\": \"workspace:^\",\n    \"@effect/rpc\": \"workspace:^\",\n    \"@effect/sql\": \"workspace:^\",\n    \"@effect/sql-mysql2\": \"workspace:^\",\n    \"@effect/sql-pg\": \"workspace:^\",\n    \"@effect/sql-sqlite-node\": \"workspace:^\",\n    \"@effect/workflow\": \"workspace:^\",\n    \"@testcontainers/mysql\": \"^10.25.0\",\n    \"@testcontainers/postgresql\": \"^10.25.0\",\n    \"@types/pg\": \"^8.15.6\",\n    \"effect\": \"workspace:^\",\n    \"pg\": \"^8.16.3\"\n  },\n  \"dependencies\": {\n    \"kubernetes-types\": \"^1.30.0\"\n  }\n}\n"
  },
  {
    "path": "packages/cluster/src/ClusterCron.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Rpc from \"@effect/rpc/Rpc\"\nimport * as Cron from \"effect/Cron\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as PrimaryKey from \"effect/PrimaryKey\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Schema from \"effect/Schema\"\nimport type { Scope } from \"effect/Scope\"\nimport * as ClusterSchema from \"./ClusterSchema.js\"\nimport { Persisted, Uninterruptible } from \"./ClusterSchema.js\"\nimport * as DeliverAt from \"./DeliverAt.js\"\nimport * as Entity from \"./Entity.js\"\nimport type { Sharding } from \"./Sharding.js\"\nimport * as Singleton from \"./Singleton.js\"\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = <E, R>(options: {\n  readonly name: string\n  readonly cron: Cron.Cron\n  readonly execute: Effect.Effect<void, E, R>\n\n  /**\n   * Choose a shard group to run this cron job on.\n   */\n  readonly shardGroup?: string | undefined\n\n  /**\n   * Whether to run the next cron job based from the time of the previous run.\n   *\n   * Defaults to `false`, meaning the next run will be calculated from the\n   * current time.\n   */\n  readonly calculateNextRunFromPrevious?: boolean | undefined\n\n  /**\n   * If set, the cron job will skip execution if the scheduled time is older\n   * than this duration.\n   *\n   * This is useful to prevent running jobs that were scheduled too far in the\n   * past.\n   *\n   * Defaults to \"1 day\".\n   */\n  readonly skipIfOlderThan?: Duration.DurationInput | undefined\n}): Layer.Layer<never, never, Sharding | Exclude<R, Scope>> => {\n  const CronEntity = Entity.make(`ClusterCron/${options.name}`, [\n    Rpc.make(\"run\", {\n      payload: CronPayload\n    })\n      .annotate(Persisted, true)\n      .annotate(Uninterruptible, true)\n  ])\n    .annotate(ClusterSchema.ShardGroup, () => options.shardGroup ?? \"default\")\n    .annotate(ClusterSchema.ClientTracingEnabled, false)\n\n  const InitialRun = Singleton.make(\n    `ClusterCron/${options.name}`,\n    Effect.gen(function*() {\n      const now = yield* DateTime.now\n      const next = DateTime.unsafeFromDate(Cron.next(options.cron, now))\n      const entityId = options.calculateNextRunFromPrevious ? \"initial\" : DateTime.formatIso(next)\n      const client = (yield* CronEntity.client)(entityId)\n      yield* client.run({ dateTime: next }, { discard: true })\n    }),\n    { shardGroup: options.shardGroup }\n  )\n\n  const skipIfOlderThan = Option.fromNullable(options.skipIfOlderThan).pipe(\n    Option.map(Duration.decode),\n    Option.getOrElse(() => Duration.days(1))\n  )\n\n  const effect = Effect.fnUntraced(function*(dateTime: DateTime.Utc) {\n    const now = yield* DateTime.now\n    if (DateTime.lessThan(dateTime, DateTime.subtractDuration(now, skipIfOlderThan))) {\n      return\n    }\n    return yield* options.execute\n  }, Effect.orDie)\n\n  const EntityLayer = CronEntity.toLayer(Effect.gen(function*() {\n    const makeClient = yield* CronEntity.client\n    return {\n      run: (request) =>\n        effect(request.payload.dateTime).pipe(\n          Effect.exit,\n          Effect.flatMap(Effect.fnUntraced(function*(exit) {\n            if (Exit.isFailure(exit)) {\n              yield* Effect.logWarning(exit.cause)\n            }\n            const now = yield* DateTime.now\n            const next = DateTime.unsafeFromDate(Cron.next(\n              options.cron,\n              options.calculateNextRunFromPrevious ? request.payload.dateTime : now\n            ))\n            const client = makeClient(DateTime.formatIso(next))\n            return yield* client.run({ dateTime: next }, { discard: true }).pipe(\n              Effect.tapErrorCause((cause) => Effect.logWarning(\"Failed to schedule next run, retrying\", cause)),\n              Effect.sandbox,\n              Effect.retry(retryPolicy),\n              Effect.orDie\n            )\n          })),\n          Effect.annotateLogs({\n            module: \"ClusterCron\",\n            name: options.name,\n            dateTime: request.payload.dateTime\n          })\n        )\n    }\n  }))\n\n  return Layer.merge(InitialRun, EntityLayer)\n}\n\nconst retryPolicy = Schedule.exponential(200, 1.5).pipe(\n  Schedule.union(Schedule.spaced(\"1 minute\"))\n)\n\nclass CronPayload extends Schema.Class<CronPayload>(\"@effect/cluster/ClusterCron/CronPayload\")({\n  dateTime: Schema.DateTimeUtc\n}) {\n  [PrimaryKey.symbol]() {\n    return \"\"\n  }\n  [DeliverAt.symbol]() {\n    return this.dateTime\n  }\n}\n"
  },
  {
    "path": "packages/cluster/src/ClusterError.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport { hasProperty, isTagged } from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport { EntityAddress } from \"./EntityAddress.js\"\nimport { RunnerAddress } from \"./RunnerAddress.js\"\nimport { SnowflakeFromString } from \"./Snowflake.js\"\n\n/**\n * @since 1.0.0\n * @category Symbols\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/cluster/ClusterError\")\n\n/**\n * @since 1.0.0\n * @category Symbols\n */\nexport type TypeId = typeof TypeId\n\n/**\n * Represents an error that occurs when a Runner receives a message for an entity\n * that it is not assigned to it.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class EntityNotAssignedToRunner extends Schema.TaggedError<EntityNotAssignedToRunner>()(\n  \"EntityNotAssignedToRunner\",\n  { address: EntityAddress }\n) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  static is(u: unknown): u is EntityNotAssignedToRunner {\n    return hasProperty(u, TypeId) && isTagged(u, \"EntityNotAssignedToRunner\")\n  }\n}\n\n/**\n * Represents an error that occurs when a message fails to be properly\n * deserialized by an entity.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class MalformedMessage extends Schema.TaggedError<MalformedMessage>()(\n  \"MalformedMessage\",\n  { cause: Schema.Defect }\n) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  static is(u: unknown): u is MalformedMessage {\n    return hasProperty(u, TypeId) && isTagged(u, \"MalformedMessage\")\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  static refail: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<\n    A,\n    MalformedMessage,\n    R\n  > = Effect.mapError((cause) => new MalformedMessage({ cause }))\n}\n\n/**\n * Represents an error that occurs when a message fails to be persisted into\n * cluster's mailbox storage.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class PersistenceError extends Schema.TaggedError<PersistenceError>()(\n  \"PersistenceError\",\n  { cause: Schema.Defect }\n) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  static refail<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, PersistenceError, R> {\n    return Effect.catchAllCause(effect, (cause) => Effect.fail(new PersistenceError({ cause: Cause.squash(cause) })))\n  }\n}\n\n/**\n * Represents an error that occurs when a Runner is not registered with the shard\n * manager.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class RunnerNotRegistered extends Schema.TaggedError<RunnerNotRegistered>()(\n  \"RunnerNotRegistered\",\n  { address: RunnerAddress }\n) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId\n}\n\n/**\n * Represents an error that occurs when a Runner is unresponsive.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class RunnerUnavailable extends Schema.TaggedError<RunnerUnavailable>()(\n  \"RunnerUnavailable\",\n  { address: RunnerAddress }\n) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  static is(u: unknown): u is RunnerUnavailable {\n    return hasProperty(u, TypeId) && isTagged(u, \"RunnerUnavailable\")\n  }\n}\n\n/**\n * Represents an error that occurs when the entities mailbox is full.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class MailboxFull extends Schema.TaggedError<MailboxFull>()(\n  \"MailboxFull\",\n  { address: EntityAddress }\n) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  static is(u: unknown): u is MailboxFull {\n    return hasProperty(u, TypeId) && isTagged(u, \"MailboxFull\")\n  }\n}\n\n/**\n * Represents an error that occurs when the entity is already processing a\n * request.\n *\n * @since 1.0.0\n * @category errors\n */\nexport class AlreadyProcessingMessage extends Schema.TaggedError<AlreadyProcessingMessage>()(\n  \"AlreadyProcessingMessage\",\n  {\n    envelopeId: SnowflakeFromString,\n    address: EntityAddress\n  }\n) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  static is(u: unknown): u is AlreadyProcessingMessage {\n    return hasProperty(u, TypeId) && isTagged(u, \"AlreadyProcessingMessage\")\n  }\n}\n"
  },
  {
    "path": "packages/cluster/src/ClusterMetrics.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Metric from \"effect/Metric\"\n\n/**\n * @since 1.0.0\n * @category metrics\n */\nexport const entities = Metric.gauge(\"effect_cluster_entities\", {\n  bigint: true\n})\n\n/**\n * @since 1.0.0\n * @category metrics\n */\nexport const singletons = Metric.gauge(\"effect_cluster_singletons\", {\n  bigint: true\n})\n\n/**\n * @since 1.0.0\n * @category metrics\n */\nexport const runners = Metric.gauge(\"effect_cluster_runners\", {\n  bigint: true\n})\n\n/**\n * @since 1.0.0\n * @category metrics\n */\nexport const runnersHealthy = Metric.gauge(\"effect_cluster_runners_healthy\", {\n  bigint: true\n})\n\n/**\n * @since 1.0.0\n * @category metrics\n */\nexport const shards = Metric.gauge(\"effect_cluster_shards\", {\n  bigint: true\n})\n"
  },
  {
    "path": "packages/cluster/src/ClusterSchema.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport { constFalse, constTrue } from \"effect/Function\"\nimport type { EntityId } from \"./EntityId.js\"\n\n/**\n * @since 1.0.0\n * @category Annotations\n */\nexport class Persisted extends Context.Reference<Persisted>()(\"@effect/cluster/ClusterSchema/Persisted\", {\n  defaultValue: constFalse\n}) {}\n\n/**\n * @since 1.0.0\n * @category Annotations\n */\nexport class Uninterruptible\n  extends Context.Reference<Uninterruptible>()(\"@effect/cluster/ClusterSchema/Uninterruptible\", {\n    defaultValue: (): boolean | \"client\" | \"server\" => false\n  })\n{\n  /**\n   * @since 1.0.0\n   */\n  static forServer(context: Context.Context<never>): boolean {\n    const value = Context.get(context, Uninterruptible)\n    return value === true || value === \"server\"\n  }\n  /**\n   * @since 1.0.0\n   */\n  static forClient(context: Context.Context<never>): boolean {\n    const value = Context.get(context, Uninterruptible)\n    return value === true || value === \"client\"\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Annotations\n */\nexport class ShardGroup extends Context.Reference<ShardGroup>()(\"@effect/cluster/ClusterSchema/ShardGroup\", {\n  defaultValue: (): (entityId: EntityId) => string => (_) => \"default\"\n}) {}\n\n/**\n * @since 1.0.0\n * @category Annotations\n */\nexport class ClientTracingEnabled\n  extends Context.Reference<ClientTracingEnabled>()(\"@effect/cluster/ClusterSchema/ClientTracingEnabled\", {\n    defaultValue: constTrue\n  })\n{}\n"
  },
  {
    "path": "packages/cluster/src/ClusterWorkflowEngine.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Rpc from \"@effect/rpc/Rpc\"\nimport * as RpcServer from \"@effect/rpc/RpcServer\"\nimport { DurableDeferred } from \"@effect/workflow\"\nimport * as Activity from \"@effect/workflow/Activity\"\nimport * as DurableClock from \"@effect/workflow/DurableClock\"\nimport * as Workflow from \"@effect/workflow/Workflow\"\nimport { makeUnsafe, WorkflowEngine, WorkflowInstance } from \"@effect/workflow/WorkflowEngine\"\nimport * as Arr from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberId from \"effect/FiberId\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport * as PrimaryKey from \"effect/PrimaryKey\"\nimport * as RcMap from \"effect/RcMap\"\nimport type * as Record from \"effect/Record\"\nimport * as Runtime from \"effect/Runtime\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as ClusterSchema from \"./ClusterSchema.js\"\nimport * as DeliverAt from \"./DeliverAt.js\"\nimport * as Entity from \"./Entity.js\"\nimport { EntityAddress } from \"./EntityAddress.js\"\nimport { EntityId } from \"./EntityId.js\"\nimport { EntityType } from \"./EntityType.js\"\nimport { MessageStorage } from \"./MessageStorage.js\"\nimport type { WithExitEncoded } from \"./Reply.js\"\nimport * as Reply from \"./Reply.js\"\nimport * as Sharding from \"./Sharding.js\"\nimport * as Snowflake from \"./Snowflake.js\"\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.gen(function*() {\n  const sharding = yield* Sharding.Sharding\n  const storage = yield* MessageStorage\n\n  const workflows = new Map<string, Workflow.Any>()\n  const entities = new Map<\n    string,\n    Entity.Entity<\n      string,\n      | Rpc.Rpc<\n        \"run\",\n        Schema.Struct<\n          Record<\n            typeof payloadParentKey,\n            Schema.optional<\n              Schema.Struct<{\n                workflowName: typeof Schema.String\n                executionId: typeof Schema.String\n              }>\n            >\n          >\n        >,\n        Schema.Schema<Workflow.Result<any, any>>\n      >\n      | Rpc.Rpc<\"deferred\", Schema.Struct<{ name: typeof Schema.String; exit: typeof ExitUnknown }>, typeof ExitUnknown>\n      | Rpc.Rpc<\n        \"activity\",\n        Schema.Struct<{ name: typeof Schema.String; attempt: typeof Schema.Number }>,\n        Schema.Schema<Workflow.Result<any, any>>\n      >\n      | Rpc.Rpc<\"resume\", Schema.Struct<{}>>\n    >\n  >()\n  const partialEntities = new Map<\n    string,\n    Entity.Entity<\n      string,\n      | Rpc.Rpc<\"deferred\", Schema.Struct<{ name: typeof Schema.String; exit: typeof ExitUnknown }>, typeof ExitUnknown>\n      | Rpc.Rpc<\n        \"activity\",\n        Schema.Struct<{ name: typeof Schema.String; attempt: typeof Schema.Number }>,\n        Schema.Schema<Workflow.Result<any, any>>\n      >\n      | Rpc.Rpc<\"resume\">\n    >\n  >()\n  const ensureEntity = (workflow: Workflow.Any) => {\n    let entity = entities.get(workflow.name)\n    if (!entity) {\n      entity = makeWorkflowEntity(workflow) as any\n      workflows.set(workflow.name, workflow)\n      entities.set(workflow.name, entity as any)\n    }\n    return entity!\n  }\n  const ensurePartialEntity = (workflowName: string) => {\n    let entity = partialEntities.get(workflowName)\n    if (!entity) {\n      entity = makePartialWorkflowEntity(workflowName) as any\n      partialEntities.set(workflowName, entity as any)\n    }\n    return entity!\n  }\n\n  const activities = new Map<string, {\n    readonly activity: Activity.Any\n    readonly runtime: Runtime.Runtime<any>\n  }>()\n  const interruptedActivities = new Set<string>()\n  const activityLatches = new Map<string, Effect.Latch>()\n  const clients = yield* RcMap.make({\n    lookup: Effect.fnUntraced(function*(workflowName: string) {\n      const entity = entities.get(workflowName)\n      if (!entity) {\n        return yield* Effect.dieMessage(`Workflow ${workflowName} not registered`)\n      }\n      return yield* entity.client\n    }),\n    idleTimeToLive: \"5 minutes\"\n  })\n  const clientsPartial = yield* RcMap.make({\n    lookup: Effect.fnUntraced(function*(workflowName: string) {\n      const entity = entities.get(workflowName) ?? ensurePartialEntity(workflowName)\n      return yield* entity.client\n    }),\n    idleTimeToLive: \"5 minutes\"\n  })\n  const clockClient = yield* ClockEntity.client\n\n  const requestIdFor = Effect.fnUntraced(function*(options: {\n    readonly workflow: Workflow.Any\n    readonly entityType: string\n    readonly executionId: string\n    readonly tag: string\n    readonly id: string\n  }) {\n    const shardGroup = Context.get(options.workflow.annotations, ClusterSchema.ShardGroup)(\n      options.executionId as EntityId\n    )\n    const entityId = EntityId.make(options.executionId)\n    const address = new EntityAddress({\n      entityType: EntityType.make(options.entityType),\n      entityId,\n      shardId: sharding.getShardId(entityId, shardGroup)\n    })\n    return yield* storage.requestIdForPrimaryKey({ address, tag: options.tag, id: options.id })\n  })\n\n  const replyForRequestId = Effect.fnUntraced(function*(requestId: Snowflake.Snowflake) {\n    const replies = yield* storage.repliesForUnfiltered([requestId])\n    return Arr.last(replies).pipe(\n      Option.filter((reply) => reply._tag === \"WithExit\"),\n      Option.map((reply) =>\n        reply as WithExitEncoded<Rpc.Rpc<string, Schema.Struct<{}>, Schema.Schema<Workflow.Result<any, any>>>>\n      )\n    )\n  })\n\n  const requestReply = Effect.fnUntraced(function*(options: {\n    readonly workflow: Workflow.Any\n    readonly entityType: string\n    readonly executionId: string\n    readonly tag: string\n    readonly id: string\n  }) {\n    const requestId = yield* requestIdFor(options)\n    if (Option.isNone(requestId)) {\n      return Option.none()\n    }\n    return yield* replyForRequestId(requestId.value)\n  })\n\n  const resetActivityAttempt = Effect.fnUntraced(\n    function*(options: {\n      readonly workflow: Workflow.Any\n      readonly executionId: string\n      readonly activity: Activity.Any\n      readonly attempt: number\n    }) {\n      const requestId = yield* requestIdFor({\n        workflow: options.workflow,\n        entityType: `Workflow/${options.workflow.name}`,\n        executionId: options.executionId,\n        tag: \"activity\",\n        id: activityPrimaryKey(options.activity.name, options.attempt)\n      })\n      if (Option.isNone(requestId)) return\n      yield* sharding.reset(requestId.value)\n    },\n    Effect.retry({\n      times: 3,\n      schedule: Schedule.exponential(250)\n    }),\n    Effect.orDie\n  )\n\n  const clearClock = Effect.fnUntraced(function*(options: {\n    readonly workflow: Workflow.Any\n    readonly executionId: string\n  }) {\n    const shardGroup = Context.get(options.workflow.annotations, ClusterSchema.ShardGroup)(\n      options.executionId as EntityId\n    )\n    const entityId = EntityId.make(options.executionId)\n    const shardId = sharding.getShardId(entityId, shardGroup)\n    const clockAddress = new EntityAddress({\n      entityType: ClockEntity.type,\n      entityId,\n      shardId\n    })\n    yield* storage.clearAddress(clockAddress)\n  })\n\n  const resume = Effect.fnUntraced(function*(workflow: Workflow.Any, executionId: string) {\n    const maybeReply = yield* requestReply({\n      workflow,\n      entityType: `Workflow/${workflow.name}`,\n      executionId,\n      tag: \"run\",\n      id: \"\"\n    })\n    const maybeSuspended = Option.filter(\n      maybeReply,\n      (reply) => reply.exit._tag === \"Success\" && reply.exit.value._tag === \"Suspended\"\n    )\n    if (Option.isNone(maybeSuspended)) return\n    yield* sharding.reset(Snowflake.Snowflake(maybeSuspended.value.requestId))\n    yield* sharding.pollStorage\n  })\n\n  const sendResumeParent = Effect.fnUntraced(function*(options: {\n    readonly workflowName: string\n    readonly executionId: string\n  }) {\n    const requestId = yield* requestIdFor({\n      workflow: workflows.get(options.workflowName)!,\n      entityType: `Workflow/${options.workflowName}`,\n      executionId: options.executionId,\n      tag: \"resume\",\n      id: \"\"\n    })\n    if (Option.isNone(requestId)) {\n      const client = (yield* RcMap.get(clientsPartial, options.workflowName))(options.executionId)\n      return yield* client.resume({} as any, { discard: true })\n    }\n    const reply = yield* replyForRequestId(requestId.value)\n    if (Option.isNone(reply)) return\n    yield* sharding.reset(requestId.value)\n  }, Effect.scoped)\n\n  const engine = makeUnsafe({\n    register: (workflow, execute) =>\n      Effect.suspend(() =>\n        sharding.registerEntity(\n          ensureEntity(workflow),\n          Effect.gen(function*() {\n            const address = yield* Entity.CurrentAddress\n            const executionId = address.entityId\n            return {\n              run: (request: Entity.Request<any>) => {\n                const instance = WorkflowInstance.initial(workflow, executionId)\n                const payload = request.payload\n                let parent: { workflowName: string; executionId: string } | undefined\n                if (payload[payloadParentKey]) {\n                  parent = payload[payloadParentKey]\n                }\n                return execute(workflow.payloadSchema.make(payload), executionId).pipe(\n                  Effect.onExit((exit) => {\n                    const suspendOnFailure = Context.get(workflow.annotations, Workflow.SuspendOnFailure)\n                    if (!instance.suspended && !(suspendOnFailure && exit._tag === \"Failure\")) {\n                      return parent ? ensureSuccess(sendResumeParent(parent)) : Effect.void\n                    }\n                    return engine.deferredResult(InterruptSignal).pipe(\n                      Effect.flatMap((maybeExit) => {\n                        if (maybeExit === undefined) {\n                          return Effect.void\n                        }\n                        instance.suspended = false\n                        instance.interrupted = true\n                        return Effect.zipRight(\n                          Effect.ignore(clearClock({ workflow, executionId })),\n                          Effect.withFiberRuntime<void>((fiber) => Effect.interruptible(Fiber.interrupt(fiber)))\n                        )\n                      }),\n                      Effect.orDie\n                    )\n                  }),\n                  Workflow.intoResult,\n                  Effect.provideService(WorkflowInstance, instance)\n                ) as any\n              },\n\n              activity(request: Entity.Request<any>) {\n                const activityId = `${executionId}/${request.payload.name}`\n                const instance = WorkflowInstance.initial(workflow, executionId)\n                interruptedActivities.delete(activityId)\n                return Effect.gen(function*() {\n                  let entry = activities.get(activityId)\n                  while (!entry) {\n                    const latch = Effect.unsafeMakeLatch()\n                    activityLatches.set(activityId, latch)\n                    yield* latch.await\n                    entry = activities.get(activityId)\n                  }\n                  const contextMap = new Map(entry.runtime.context.unsafeMap)\n                  contextMap.set(Activity.CurrentAttempt.key, request.payload.attempt)\n                  contextMap.set(WorkflowInstance.key, instance)\n                  const runtime = Runtime.make({\n                    context: Context.unsafeMake(contextMap),\n                    fiberRefs: entry.runtime.fiberRefs,\n                    runtimeFlags: Runtime.defaultRuntimeFlags\n                  })\n                  return yield* entry.activity.executeEncoded.pipe(\n                    Effect.provide(runtime)\n                  )\n                }).pipe(\n                  Workflow.intoResult,\n                  Effect.catchAllCause((cause) => {\n                    const interruptors = Cause.interruptors(cause)\n                    // we only want to store interrupts as suspends when the\n                    // client requested it\n                    const ids = Array.from(interruptors, (id) => Array.from(FiberId.ids(id))).flat()\n                    const suspend = ids.includes(RpcServer.fiberIdClientInterrupt.id)\n                    if (suspend) {\n                      interruptedActivities.add(activityId)\n                      return Effect.succeed(new Workflow.Suspended())\n                    }\n                    return Effect.failCause(cause)\n                  }),\n                  Effect.provideService(WorkflowInstance, instance),\n                  Effect.provideService(Activity.CurrentAttempt, request.payload.attempt),\n                  Effect.ensuring(Effect.sync(() => {\n                    activities.delete(activityId)\n                  })),\n                  Rpc.wrap({\n                    fork: true,\n                    uninterruptible: true\n                  })\n                )\n              },\n\n              deferred: Effect.fnUntraced(function*(request: Entity.Request<any>) {\n                yield* ensureSuccess(resume(workflow, executionId))\n                return request.payload.exit\n              }),\n\n              resume: () => ensureSuccess(resume(workflow, executionId))\n            }\n          })\n        ) as Effect.Effect<void, never, Scope.Scope>\n      ),\n\n    execute: (workflow, { discard, executionId, parent, payload }) => {\n      ensureEntity(workflow)\n      return RcMap.get(clients, workflow.name).pipe(\n        Effect.flatMap((make) =>\n          make(executionId).run(\n            parent ?\n              {\n                ...payload,\n                [payloadParentKey]: { workflowName: parent.workflow.name, executionId: parent.executionId }\n              } :\n              payload,\n            { discard }\n          )\n        ),\n        Effect.orDie,\n        Effect.scoped\n      )\n    },\n\n    poll: Effect.fnUntraced(function*(workflow, executionId) {\n      const entity = ensureEntity(workflow)\n      const exitSchema = Rpc.exitSchema(entity.protocol.requests.get(\"run\")!)\n      const oreply = yield* requestReply({\n        workflow,\n        entityType: `Workflow/${workflow.name}`,\n        executionId,\n        tag: \"run\",\n        id: \"\"\n      })\n      if (Option.isNone(oreply)) return undefined\n      const exit = yield* (Schema.decode(exitSchema)(oreply.value.exit) as Effect.Effect<\n        Exit.Exit<any, any>,\n        ParseResult.ParseError\n      >)\n      return yield* exit\n    }, Effect.orDie),\n\n    interrupt: Effect.fnUntraced(\n      function*(workflow, executionId) {\n        ensureEntity(workflow)\n        const oreply = yield* requestReply({\n          workflow,\n          entityType: `Workflow/${workflow.name}`,\n          executionId,\n          tag: \"run\",\n          id: \"\"\n        })\n        const nonSuspendedReply = oreply.pipe(\n          Option.filter((reply) => reply.exit._tag !== \"Success\" || reply.exit.value._tag !== \"Suspended\")\n        )\n        if (Option.isSome(nonSuspendedReply)) {\n          return\n        }\n\n        yield* engine.deferredDone(InterruptSignal, {\n          workflowName: workflow.name,\n          executionId,\n          deferredName: InterruptSignal.name,\n          exit: Exit.void\n        })\n      },\n      Effect.retry({\n        while: (e) => e._tag === \"PersistenceError\",\n        times: 3,\n        schedule: Schedule.exponential(250)\n      }),\n      Effect.orDie\n    ),\n\n    resume: (workflow, executionId) => ensureSuccess(resume(workflow, executionId)),\n\n    activityExecute: Effect.fnUntraced(\n      function*(activity, attempt) {\n        const runtime = yield* Effect.runtime<WorkflowInstance>()\n        const context = runtime.context\n        const instance = Context.get(context, WorkflowInstance)\n        yield* Effect.annotateCurrentSpan(\"executionId\", instance.executionId)\n        const activityId = `${instance.executionId}/${activity.name}`\n        const client = (yield* RcMap.get(clientsPartial, instance.workflow.name))(instance.executionId)\n        while (true) {\n          if (!activities.has(activityId)) {\n            activities.set(activityId, { activity, runtime })\n            const latch = activityLatches.get(activityId)\n            if (latch) {\n              yield* latch.release\n              activityLatches.delete(activityId)\n            }\n          }\n          const result = yield* Effect.orDie(client.activity({ name: activity.name, attempt }))\n          // If the activity has suspended and did not execute, we need to resume\n          // it by resetting the attempt and re-executing.\n          if (result._tag === \"Suspended\" && (activities.has(activityId) || interruptedActivities.has(activityId))) {\n            yield* resetActivityAttempt({\n              workflow: instance.workflow,\n              executionId: instance.executionId,\n              activity,\n              attempt\n            })\n            continue\n          }\n          activities.delete(activityId)\n          return result\n        }\n      },\n      Effect.scoped\n    ),\n\n    deferredResult: (deferred) =>\n      WorkflowInstance.pipe(\n        Effect.flatMap((instance) =>\n          requestReply({\n            workflow: instance.workflow,\n            entityType: `Workflow/${instance.workflow.name}`,\n            executionId: instance.executionId,\n            tag: \"deferred\",\n            id: deferred.name\n          })\n        ),\n        Effect.map((oreply) => {\n          if (Option.isNone(oreply)) {\n            return undefined\n          }\n          const reply = oreply.value\n          const decoded = decodeDeferredWithExit(reply as any)\n          return decoded.exit._tag === \"Success\"\n            ? decoded.exit.value\n            : decoded.exit\n        }),\n        Effect.retry({\n          while: (e) => e._tag === \"PersistenceError\",\n          times: 3,\n          schedule: Schedule.exponential(250)\n        }),\n        Effect.orDie\n      ),\n\n    deferredDone: Effect.fnUntraced(\n      function*({ deferredName, executionId, exit, workflowName }) {\n        const client = yield* RcMap.get(clientsPartial, workflowName)\n        return yield* Effect.orDie(\n          client(executionId).deferred({\n            name: deferredName,\n            exit\n          }, { discard: true })\n        )\n      },\n      Effect.scoped\n    ),\n\n    scheduleClock(workflow, options) {\n      const client = clockClient(options.executionId)\n      return DateTime.now.pipe(\n        Effect.flatMap((now) =>\n          client.run({\n            name: options.clock.name,\n            workflowName: workflow.name,\n            wakeUp: DateTime.addDuration(now, options.clock.duration)\n          }, { discard: true })\n        ),\n        Effect.orDie\n      )\n    }\n  })\n\n  return engine\n})\n\nconst retryPolicy = Schedule.exponential(200, 1.5).pipe(\n  Schedule.union(Schedule.spaced(\"1 minute\"))\n)\n\nconst ensureSuccess = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n  effect.pipe(\n    Effect.sandbox,\n    Effect.retry(retryPolicy),\n    Effect.orDie\n  )\n\nconst ActivityRpc = Rpc.make(\"activity\", {\n  payload: {\n    name: Schema.String,\n    attempt: Schema.Number\n  },\n  primaryKey: ({ attempt, name }) => activityPrimaryKey(name, attempt),\n  success: Workflow.Result({\n    success: Schema.Unknown,\n    error: Schema.Unknown\n  })\n})\n  .annotate(ClusterSchema.Persisted, true)\n  .annotate(ClusterSchema.Uninterruptible, \"server\")\n\nconst payloadParentKey = \"~@effect/workflow/parent\" as const\n\nconst makeWorkflowEntity = (workflow: Workflow.Any) =>\n  Entity.make(`Workflow/${workflow.name}`, [\n    Rpc.make(\"run\", {\n      payload: {\n        ...workflow.payloadSchema.fields,\n        [payloadParentKey]: Schema.optional(Schema.Struct({\n          workflowName: Schema.String,\n          executionId: Schema.String\n        }))\n      },\n      primaryKey: () => \"\",\n      success: Workflow.Result({\n        success: workflow.successSchema,\n        error: workflow.errorSchema\n      })\n    })\n      .annotate(ClusterSchema.Persisted, true)\n      .annotate(ClusterSchema.Uninterruptible, true),\n\n    DeferredRpc,\n    ResumeRpc,\n    ActivityRpc\n  ]).annotateContext(workflow.annotations)\n\nconst ExitUnknown = Schema.Exit({\n  success: Schema.Unknown,\n  failure: Schema.Unknown,\n  defect: Schema.Defect\n})\n\nconst DeferredRpc = Rpc.make(\"deferred\", {\n  payload: {\n    name: Schema.String,\n    exit: ExitUnknown\n  },\n  primaryKey: ({ name }) => name,\n  success: ExitUnknown\n})\n  .annotate(ClusterSchema.Persisted, true)\n  .annotate(ClusterSchema.Uninterruptible, true)\n\nconst decodeDeferredWithExit = Schema.decodeSync(Reply.WithExit.schema(DeferredRpc))\n\nconst ResumeRpc = Rpc.make(\"resume\", {\n  payload: {},\n  primaryKey: () => \"\"\n})\n  .annotate(ClusterSchema.Persisted, true)\n  .annotate(ClusterSchema.Uninterruptible, true)\n\nconst makePartialWorkflowEntity = (workflowName: string) =>\n  Entity.make(`Workflow/${workflowName}`, [\n    DeferredRpc,\n    ResumeRpc,\n    ActivityRpc\n  ])\n\nconst activityPrimaryKey = (activity: string, attempt: number) => `${activity}/${attempt}`\n\nclass ClockPayload extends Schema.Class<ClockPayload>(`Workflow/DurableClock/Run`)({\n  name: Schema.String,\n  workflowName: Schema.String,\n  wakeUp: Schema.DateTimeUtcFromNumber\n}) {\n  [PrimaryKey.symbol]() {\n    return this.name\n  }\n  [DeliverAt.symbol]() {\n    return this.wakeUp\n  }\n}\n\nconst ClockEntity = Entity.make(\"Workflow/-/DurableClock\", [\n  Rpc.make(\"run\", { payload: ClockPayload })\n    .annotate(ClusterSchema.Persisted, true)\n    .annotate(ClusterSchema.Uninterruptible, true)\n])\n\nconst ClockEntityLayer = ClockEntity.toLayer(Effect.gen(function*() {\n  const engine = yield* WorkflowEngine\n  const address = yield* Entity.CurrentAddress\n  const executionId = address.entityId\n  return {\n    run(request) {\n      const deferred = DurableClock.make({ name: request.payload.name, duration: Duration.zero }).deferred\n      return ensureSuccess(engine.deferredDone(deferred, {\n        workflowName: request.payload.workflowName,\n        executionId,\n        deferredName: deferred.name,\n        exit: Exit.void\n      }))\n    }\n  }\n}))\n\nconst InterruptSignal = DurableDeferred.make(\"Workflow/InterruptSignal\")\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer: Layer.Layer<\n  WorkflowEngine,\n  never,\n  Sharding.Sharding | MessageStorage\n> = ClockEntityLayer.pipe(\n  Layer.provideMerge(Layer.scoped(WorkflowEngine, make))\n)\n"
  },
  {
    "path": "packages/cluster/src/DeliverAt.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { DateTime } from \"effect/DateTime\"\nimport { hasProperty } from \"effect/Predicate\"\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport const symbol: unique symbol = Symbol.for(\"@effect/cluster/DeliverAt\")\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface DeliverAt {\n  [symbol](): DateTime\n}\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isDeliverAt = (self: unknown): self is DeliverAt => hasProperty(self, symbol)\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const toMillis = (self: unknown): number | null => {\n  if (isDeliverAt(self)) {\n    return self[symbol]().epochMillis\n  }\n  return null\n}\n"
  },
  {
    "path": "packages/cluster/src/Entity.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Headers from \"@effect/platform/Headers\"\nimport * as Rpc from \"@effect/rpc/Rpc\"\nimport * as RpcClient from \"@effect/rpc/RpcClient\"\nimport * as RpcGroup from \"@effect/rpc/RpcGroup\"\nimport * as RpcServer from \"@effect/rpc/RpcServer\"\nimport * as Arr from \"effect/Array\"\nimport type { Brand } from \"effect/Brand\"\nimport type * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport type { DurationInput } from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport * as Exit from \"effect/Exit\"\nimport { identity } from \"effect/Function\"\nimport * as Hash from \"effect/Hash\"\nimport * as Layer from \"effect/Layer\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Schedule from \"effect/Schedule\"\nimport { Scope } from \"effect/Scope\"\nimport type * as Stream from \"effect/Stream\"\nimport type { AlreadyProcessingMessage, MailboxFull, PersistenceError } from \"./ClusterError.js\"\nimport { ShardGroup } from \"./ClusterSchema.js\"\nimport * as ClusterSchema from \"./ClusterSchema.js\"\nimport { EntityAddress } from \"./EntityAddress.js\"\nimport type { EntityId } from \"./EntityId.js\"\nimport { EntityType } from \"./EntityType.js\"\nimport * as Envelope from \"./Envelope.js\"\nimport { hashString } from \"./internal/hash.js\"\nimport { ResourceMap } from \"./internal/resourceMap.js\"\nimport * as Message from \"./Message.js\"\nimport type * as Reply from \"./Reply.js\"\nimport { RunnerAddress } from \"./RunnerAddress.js\"\nimport * as ShardId from \"./ShardId.js\"\nimport type { Sharding } from \"./Sharding.js\"\nimport { ShardingConfig } from \"./ShardingConfig.js\"\nimport * as Snowflake from \"./Snowflake.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/cluster/Entity\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Entity<\n  in out Type extends string,\n  in out Rpcs extends Rpc.Any\n> extends Equal.Equal {\n  readonly [TypeId]: TypeId\n  /**\n   * The name of the entity type.\n   */\n  readonly type: Type & Brand<\"EntityType\">\n\n  /**\n   * A RpcGroup definition for messages which represents the messaging protocol\n   * that the entity is capable of processing.\n   */\n  readonly protocol: RpcGroup.RpcGroup<Rpcs>\n\n  /**\n   * Get the shard group for the given EntityId.\n   */\n  getShardGroup(entityId: EntityId): string\n\n  /**\n   * Get the ShardId for the given EntityId.\n   */\n  getShardId(entityId: EntityId): Effect.Effect<ShardId.ShardId, never, Sharding>\n\n  /**\n   * Annotate the entity with a value.\n   */\n  annotate<I, S>(tag: Context.Tag<I, S>, value: S): Entity<Type, Rpcs>\n\n  /**\n   * Annotate the Rpc's above this point with a value.\n   */\n  annotateRpcs<I, S>(tag: Context.Tag<I, S>, value: S): Entity<Type, Rpcs>\n\n  /**\n   * Annotate the entity with a context object.\n   */\n  annotateContext<S>(context: Context.Context<S>): Entity<Type, Rpcs>\n\n  /**\n   * Annotate the Rpc's above this point with a context object.\n   */\n  annotateRpcsContext<S>(context: Context.Context<S>): Entity<Type, Rpcs>\n\n  /**\n   * Create a client for this entity.\n   */\n  readonly client: Effect.Effect<\n    (\n      entityId: string\n    ) => RpcClient.RpcClient.From<\n      Rpcs,\n      MailboxFull | AlreadyProcessingMessage | PersistenceError\n    >,\n    never,\n    Sharding\n  >\n\n  /**\n   * Create a Layer from an Entity.\n   *\n   * It will register the entity with the Sharding service.\n   */\n  toLayer<\n    Handlers extends HandlersFrom<Rpcs>,\n    RX = never\n  >(\n    build: Handlers | Effect.Effect<Handlers, never, RX>,\n    options?: {\n      readonly maxIdleTime?: DurationInput | undefined\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly mailboxCapacity?: number | \"unbounded\" | undefined\n      readonly disableFatalDefects?: boolean | undefined\n      readonly defectRetryPolicy?: Schedule.Schedule<any, unknown> | undefined\n      readonly spanAttributes?: Record<string, string> | undefined\n    }\n  ): Layer.Layer<\n    never,\n    never,\n    | Exclude<RX, Scope | CurrentAddress | CurrentRunnerAddress>\n    | RpcGroup.HandlersContext<Rpcs, Handlers>\n    | Rpc.Context<Rpcs>\n    | Rpc.Middleware<Rpcs>\n    | Sharding\n  >\n\n  of<Handlers extends HandlersFrom<Rpcs>>(handlers: Handlers): Handlers\n\n  /**\n   * Create a Layer from an Entity.\n   *\n   * It will register the entity with the Sharding service.\n   */\n  toLayerMailbox<\n    R,\n    RX = never\n  >(\n    build:\n      | ((\n        mailbox: Mailbox.ReadonlyMailbox<Envelope.Request<Rpcs>>,\n        replier: Replier<Rpcs>\n      ) => Effect.Effect<never, never, R>)\n      | Effect.Effect<\n        (\n          mailbox: Mailbox.ReadonlyMailbox<Envelope.Request<Rpcs>>,\n          replier: Replier<Rpcs>\n        ) => Effect.Effect<never, never, R>,\n        never,\n        RX\n      >,\n    options?: {\n      readonly maxIdleTime?: DurationInput | undefined\n      readonly mailboxCapacity?: number | \"unbounded\" | undefined\n      readonly disableFatalDefects?: boolean | undefined\n      readonly defectRetryPolicy?: Schedule.Schedule<any, unknown> | undefined\n      readonly spanAttributes?: Record<string, string> | undefined\n    }\n  ): Layer.Layer<\n    never,\n    never,\n    | Exclude<RX, Scope | CurrentAddress | CurrentRunnerAddress>\n    | R\n    | Rpc.Context<Rpcs>\n    | Rpc.Middleware<Rpcs>\n    | Sharding\n  >\n}\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Any = Entity<string, Rpc.Any>\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type HandlersFrom<Rpc extends Rpc.Any> = {\n  readonly [Current in Rpc as Current[\"_tag\"]]: (\n    envelope: Request<Current>\n  ) => Rpc.ResultFrom<Current, any> | Rpc.Wrapper<Rpc.ResultFrom<Current, any>>\n}\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isEntity = (u: unknown): u is Any => Predicate.hasProperty(u, TypeId)\n\nconst Proto = {\n  [TypeId]: TypeId,\n  [Hash.symbol](this: Entity<string, any>): number {\n    return Hash.structure({ type: this.type })\n  },\n  [Equal.symbol](this: Entity<string, any>, that: Equal.Equal): boolean {\n    return isEntity(that) && this.type === that.type\n  },\n  annotate<I, S>(this: Entity<string, any>, tag: Context.Tag<I, S>, value: S) {\n    return fromRpcGroup(this.type, this.protocol.annotate(tag, value))\n  },\n  annotateRpcs<I, S>(this: Entity<string, any>, tag: Context.Tag<I, S>, value: S) {\n    return fromRpcGroup(this.type, this.protocol.annotateRpcs(tag, value))\n  },\n  annotateContext<S>(this: Entity<string, any>, context: Context.Context<S>) {\n    return fromRpcGroup(this.type, this.protocol.annotateContext(context))\n  },\n  annotateRpcsContext<S>(this: Entity<string, any>, context: Context.Context<S>) {\n    return fromRpcGroup(this.type, this.protocol.annotateRpcsContext(context))\n  },\n  getShardId(this: Entity<string, any>, entityId: EntityId) {\n    return Effect.map(shardingTag, (sharding) => sharding.getShardId(entityId, this.getShardGroup(entityId)))\n  },\n  get client() {\n    return shardingTag.pipe(\n      Effect.flatMap((sharding) => sharding.makeClient(this as any))\n    )\n  },\n  toLayer<\n    Rpcs extends Rpc.Any,\n    Handlers extends HandlersFrom<Rpcs>,\n    RX = never\n  >(\n    this: Entity<string, Rpcs>,\n    build: Handlers | Effect.Effect<Handlers, never, RX>,\n    options?: {\n      readonly maxIdleTime?: DurationInput | undefined\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly mailboxCapacity?: number | \"unbounded\" | undefined\n      readonly disableFatalDefects?: boolean | undefined\n      readonly defectRetryPolicy?: Schedule.Schedule<any, unknown> | undefined\n      readonly spanAttributes?: Record<string, string> | undefined\n    }\n  ): Layer.Layer<\n    never,\n    never,\n    | Exclude<RX, Scope | CurrentAddress | CurrentRunnerAddress>\n    | RpcGroup.HandlersContext<Rpcs, Handlers>\n    | Rpc.Context<Rpcs>\n    | Rpc.Middleware<Rpcs>\n    | Sharding\n  > {\n    return shardingTag.pipe(\n      Effect.flatMap((sharding) =>\n        sharding.registerEntity(\n          this,\n          Effect.isEffect(build) ? build : Effect.succeed(build),\n          options\n        )\n      ),\n      Layer.scopedDiscard\n    )\n  },\n  of: identity,\n  toLayerMailbox<\n    Rpcs extends Rpc.Any,\n    R,\n    RX = never\n  >(\n    this: Entity<string, Rpcs>,\n    build:\n      | ((\n        mailbox: Mailbox.ReadonlyMailbox<Envelope.Request<Rpcs>>,\n        replier: Replier<Rpcs>\n      ) => Effect.Effect<never, never, R>)\n      | Effect.Effect<\n        (\n          mailbox: Mailbox.ReadonlyMailbox<Envelope.Request<Rpcs>>,\n          replier: Replier<Rpcs>\n        ) => Effect.Effect<never, never, R>,\n        never,\n        RX\n      >,\n    options?: {\n      readonly maxIdleTime?: DurationInput | undefined\n      readonly mailboxCapacity?: number | \"unbounded\" | undefined\n      readonly disableFatalDefects?: boolean | undefined\n      readonly defectRetryPolicy?: Schedule.Schedule<any, unknown> | undefined\n      readonly spanAttributes?: Record<string, string> | undefined\n    }\n  ) {\n    const buildHandlers = Effect.gen(this, function*() {\n      const behaviour = Effect.isEffect(build) ? yield* build : build\n      const mailbox = yield* Mailbox.make<Envelope.Request<Rpcs>>()\n\n      // create the rpc handlers for the entity\n      const handler = (envelope: any) => {\n        return Effect.async<any, any>((resume) => {\n          mailbox.unsafeOffer(envelope)\n          resumes.set(envelope, resume)\n        })\n      }\n      const handlers: Record<string, any> = {}\n      for (const rpc of this.protocol.requests.keys()) {\n        handlers[rpc] = handler\n      }\n\n      // make the Replier for the behaviour\n      const resumes = new Map<Envelope.Request<any>, (exit: Exit.Exit<any, any>) => void>()\n      const complete = (request: Envelope.Request<any>, exit: Exit.Exit<any, any>) =>\n        Effect.sync(() => {\n          const resume = resumes.get(request)\n          if (resume) {\n            resumes.delete(request)\n            resume(exit)\n          }\n        })\n      const replier: Replier<Rpcs> = {\n        succeed: (request, value) => complete(request, Exit.succeed(value)),\n        fail: (request, error) => complete(request, Exit.fail(error)),\n        failCause: (request, cause) => complete(request, Exit.failCause(cause)),\n        complete\n      }\n\n      // fork the behaviour into the layer scope\n      yield* behaviour(mailbox, replier).pipe(\n        Effect.catchAllCause((cause) => {\n          const exit = Exit.failCause(cause)\n          for (const resume of resumes.values()) {\n            resume(exit)\n          }\n          return Effect.void\n        }),\n        Effect.interruptible,\n        Effect.forkScoped\n      )\n\n      return handlers as any\n    })\n\n    return this.toLayer(buildHandlers, {\n      ...options,\n      concurrency: \"unbounded\"\n    })\n  }\n}\n\n/**\n * Creates a new `Entity` of the specified `type` which will accept messages\n * that adhere to the provided `RpcGroup`.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fromRpcGroup = <const Type extends string, Rpcs extends Rpc.Any>(\n  /**\n   * The entity type name.\n   */\n  type: Type,\n  /**\n   * The schema definition for messages that the entity is capable of\n   * processing.\n   */\n  protocol: RpcGroup.RpcGroup<Rpcs>\n): Entity<Type, Rpcs> => {\n  const self = Object.create(Proto)\n  self.type = EntityType.make(type)\n  self.protocol = protocol\n  self.getShardGroup = Context.get(protocol.annotations, ShardGroup)\n  return self\n}\n\n/**\n * Creates a new `Entity` of the specified `type` which will accept messages\n * that adhere to the provided schemas.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <const Type extends string, Rpcs extends ReadonlyArray<Rpc.Any>>(\n  /**\n   * The entity type name.\n   */\n  type: Type,\n  /**\n   * The schema definition for messages that the entity is capable of\n   * processing.\n   */\n  protocol: Rpcs\n): Entity<Type, Rpcs[number]> => fromRpcGroup(type, RpcGroup.make(...protocol))\n\n/**\n * A Context.Tag to access the current entity address.\n *\n * @since 1.0.0\n * @category context\n */\nexport class CurrentAddress extends Context.Tag(\"@effect/cluster/Entity/EntityAddress\")<\n  CurrentAddress,\n  EntityAddress\n>() {}\n\n/**\n * A Context.Tag to access the current Runner address.\n *\n * @since 1.0.0\n * @category context\n */\nexport class CurrentRunnerAddress extends Context.Tag(\"@effect/cluster/Entity/RunnerAddress\")<\n  CurrentRunnerAddress,\n  RunnerAddress\n>() {}\n\n/**\n * @since 1.0.0\n * @category Replier\n */\nexport interface Replier<Rpcs extends Rpc.Any> {\n  readonly succeed: <R extends Rpcs>(\n    request: Envelope.Request<R>,\n    value: Replier.Success<R>\n  ) => Effect.Effect<void>\n\n  readonly fail: <R extends Rpcs>(\n    request: Envelope.Request<R>,\n    error: Rpc.Error<R>\n  ) => Effect.Effect<void>\n\n  readonly failCause: <R extends Rpcs>(\n    request: Envelope.Request<R>,\n    cause: Cause.Cause<Rpc.Error<R>>\n  ) => Effect.Effect<void>\n\n  readonly complete: <R extends Rpcs>(\n    request: Envelope.Request<R>,\n    exit: Exit.Exit<Replier.Success<R>, Rpc.Error<R>>\n  ) => Effect.Effect<void>\n}\n\n/**\n * @since 1.0.0\n * @category Replier\n */\nexport declare namespace Replier {\n  /**\n   * @since 1.0.0\n   * @category Replier\n   */\n  export type Success<R extends Rpc.Any> = Rpc.Success<R> extends Stream.Stream<infer _A, infer _E, infer _R> ?\n    Stream.Stream<_A, _E | Rpc.Error<R>, _R> | Mailbox.ReadonlyMailbox<_A, _E | Rpc.Error<R>>\n    : Rpc.Success<R>\n}\n\n/**\n * @since 1.0.0\n * @category Request\n */\nexport class Request<Rpc extends Rpc.Any> extends Data.Class<\n  Envelope.Request<Rpc> & {\n    readonly lastSentChunk: Option.Option<Reply.Chunk<Rpc>>\n  }\n> {\n  /**\n   * @since 1.0.0\n   */\n  get lastSentChunkValue(): Option.Option<Rpc.SuccessChunk<Rpc>> {\n    return this.lastSentChunk.pipe(Option.map((chunk) => Arr.lastNonEmpty(chunk.values)))\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  get nextSequence(): number {\n    if (Option.isNone(this.lastSentChunk)) {\n      return 0\n    }\n    return this.lastSentChunk.value.sequence + 1\n  }\n}\n\nconst shardingTag = Context.GenericTag<Sharding, Sharding[\"Type\"]>(\"@effect/cluster/Sharding\")\n\n/**\n * @since 1.0.0\n * @category Testing\n */\nexport const makeTestClient: <Type extends string, Rpcs extends Rpc.Any, LA, LE, LR>(\n  entity: Entity<Type, Rpcs>,\n  layer: Layer.Layer<LA, LE, LR>\n) => Effect.Effect<\n  (entityId: string) => Effect.Effect<RpcClient.RpcClient<Rpcs>>,\n  LE,\n  Scope | ShardingConfig | Exclude<LR, Sharding> | Rpc.MiddlewareClient<Rpcs>\n> = Effect.fnUntraced(function*<Type extends string, Rpcs extends Rpc.Any, LA, LE, LR>(\n  entity: Entity<Type, Rpcs>,\n  layer: Layer.Layer<LA, LE, LR>\n) {\n  const config = yield* ShardingConfig\n  const makeShardId = (entityId: string) =>\n    ShardId.make(\n      entity.getShardGroup(entityId as EntityId),\n      (Math.abs(hashString(entityId) % config.shardsPerGroup)) + 1\n    )\n  const snowflakeGen = yield* Snowflake.makeGenerator\n  const runnerAddress = new RunnerAddress({ host: \"localhost\", port: 3000 })\n  const entityMap = new Map<string, {\n    readonly context: Context.Context<Rpc.Context<Rpcs> | Rpc.Middleware<Rpcs> | LR>\n    readonly concurrency: number | \"unbounded\"\n    readonly build: Effect.Effect<\n      Context.Context<Rpc.ToHandler<Rpcs>>,\n      never,\n      Scope | CurrentAddress\n    >\n  }>()\n  const sharding = shardingTag.of({\n    ...({} as Sharding[\"Type\"]),\n    registerEntity: (entity, handlers, options) =>\n      Effect.contextWith((context) => {\n        entityMap.set(entity.type, {\n          context: context as any,\n          concurrency: options?.concurrency ?? 1,\n          build: entity.protocol.toHandlersContext(handlers).pipe(\n            Effect.provide(context.pipe(\n              Context.add(CurrentRunnerAddress, runnerAddress),\n              Context.omit(Scope)\n            ))\n          ) as any\n        })\n      })\n  })\n  yield* Layer.build(Layer.provide(layer, Layer.succeed(shardingTag, sharding)))\n  const entityEntry = entityMap.get(entity.type)\n  if (!entityEntry) {\n    return yield* Effect.dieMessage(`Entity.makeTestClient: ${entity.type} was not registered by layer`)\n  }\n\n  const map = yield* ResourceMap.make(Effect.fnUntraced(function*(entityId: string) {\n    const address = new EntityAddress({\n      entityType: entity.type,\n      entityId: entityId as EntityId,\n      shardId: makeShardId(entityId)\n    })\n    const handlers = yield* entityEntry.build.pipe(\n      Effect.provideService(CurrentAddress, address)\n    )\n\n    // eslint-disable-next-line prefer-const\n    let client!: Effect.Effect.Success<ReturnType<typeof RpcClient.makeNoSerialization<Rpcs, never>>>\n    const server = yield* RpcServer.makeNoSerialization(entity.protocol, {\n      concurrency: entityEntry.concurrency,\n      onFromServer(response) {\n        return client.write(response)\n      }\n    }).pipe(Effect.provide(handlers))\n\n    client = yield* RpcClient.makeNoSerialization(entity.protocol, {\n      supportsAck: true,\n      generateRequestId: () => snowflakeGen.unsafeNext() as any,\n      onFromClient({ message }) {\n        if (message._tag === \"Request\") {\n          return server.write(0, {\n            ...message,\n            payload: new Request({\n              ...message,\n              [Envelope.TypeId]: Envelope.TypeId,\n              address,\n              requestId: Snowflake.Snowflake(message.id),\n              lastSentChunk: Option.none()\n            }) as any\n          })\n        }\n        return server.write(0, message)\n      }\n    })\n    return client.client\n  }))\n\n  return (entityId: string) => map.get(entityId)\n})\n\n/**\n * @since 1.0.0\n * @category Keep alive\n */\nexport const keepAlive: (\n  enabled: boolean\n) => Effect.Effect<\n  void,\n  never,\n  Sharding | CurrentAddress\n> = Effect.fnUntraced(function*(enabled: boolean) {\n  const olatch = yield* Effect.serviceOption(KeepAliveLatch)\n  if (olatch._tag === \"None\") return\n  if (!enabled) {\n    yield* olatch.value.open\n    return\n  }\n  const sharding = yield* shardingTag\n  const address = yield* CurrentAddress\n  const requestId = yield* sharding.getSnowflake\n  const span = yield* Effect.orDie(Effect.currentSpan)\n  olatch.value.unsafeClose()\n  yield* Effect.orDie(sharding.sendOutgoing(\n    new Message.OutgoingRequest({\n      rpc: KeepAliveRpc,\n      context: Context.empty() as any,\n      envelope: Envelope.makeRequest({\n        requestId,\n        address,\n        tag: KeepAliveRpc._tag,\n        payload: void 0,\n        headers: Headers.empty,\n        traceId: span.traceId,\n        spanId: span.spanId,\n        sampled: span.sampled\n      }),\n      lastReceivedReply: Option.none(),\n      respond: () => Effect.void\n    }),\n    true\n  ))\n}, (effect, enabled) =>\n  Effect.withSpan(\n    effect,\n    \"Entity/keepAlive\",\n    { attributes: { enabled }, captureStackTrace: false }\n  ))\n\n/**\n * @since 1.0.0\n * @category Keep alive\n */\nexport const KeepAliveRpc = Rpc.make(\"Cluster/Entity/keepAlive\")\n  .annotate(ClusterSchema.Persisted, true)\n  .annotate(ClusterSchema.Uninterruptible, true)\n\n/**\n * @since 1.0.0\n * @category Keep alive\n */\nexport class KeepAliveLatch extends Context.Tag(\n  \"effect/cluster/Entity/KeepAliveLatch\"\n)<KeepAliveLatch, Effect.Latch>() {}\n"
  },
  {
    "path": "packages/cluster/src/EntityAddress.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Equal from \"effect/Equal\"\nimport * as Hash from \"effect/Hash\"\nimport * as Schema from \"effect/Schema\"\nimport { EntityId } from \"./EntityId.js\"\nimport { EntityType } from \"./EntityType.js\"\nimport { ShardId } from \"./ShardId.js\"\n\nconst SymbolKey = \"@effect/cluster/EntityAddress\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(SymbolKey)\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * Represents the unique address of an entity within the cluster.\n *\n * @since 1.0.0\n * @category models\n */\nexport class EntityAddress extends Schema.Class<EntityAddress>(SymbolKey)({\n  shardId: ShardId,\n  entityType: EntityType,\n  entityId: EntityId\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId;\n\n  /**\n   * @since 1.0.0\n   */\n  [Equal.symbol](that: EntityAddress): boolean {\n    return this.entityType === that.entityType && this.entityId === that.entityId &&\n      this.shardId[Equal.symbol](that.shardId)\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  [Hash.symbol]() {\n    return Hash.cached(this, Hash.string(`${this.entityType}:${this.entityId}:${this.shardId.toString()}`))\n  }\n}\n\n/**\n * Represents the unique address of an entity within the cluster.\n *\n * @since 1.0.0\n * @category schemas\n */\nexport const EntityAddressFromSelf: Schema.Schema<EntityAddress> = Schema.typeSchema(\n  EntityAddress\n)\n\n/**\n * @since 4.0.0\n * @category constructors\n */\nexport const make = (options: {\n  readonly shardId: ShardId\n  readonly entityType: EntityType\n  readonly entityId: EntityId\n}): EntityAddress => new EntityAddress(options, { disableValidation: true })\n"
  },
  {
    "path": "packages/cluster/src/EntityId.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Schema from \"effect/Schema\"\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const EntityId = Schema.NonEmptyTrimmedString.pipe(Schema.brand(\"EntityId\"))\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type EntityId = typeof EntityId.Type\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = (id: string): EntityId => id as EntityId\n"
  },
  {
    "path": "packages/cluster/src/EntityProxy.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as HttpApiEndpoint from \"@effect/platform/HttpApiEndpoint\"\nimport * as HttpApiGroup from \"@effect/platform/HttpApiGroup\"\nimport * as Rpc from \"@effect/rpc/Rpc\"\nimport * as RpcGroup from \"@effect/rpc/RpcGroup\"\nimport * as Schema from \"effect/Schema\"\nimport { AlreadyProcessingMessage, MailboxFull, PersistenceError } from \"./ClusterError.js\"\nimport type * as Entity from \"./Entity.js\"\n\nconst clientErrors = [\n  MailboxFull,\n  AlreadyProcessingMessage,\n  PersistenceError\n] as const\n\n/**\n * Derives an `RpcGroup` from an `Entity`.\n *\n * ```ts\n * import { ClusterSchema, Entity, EntityProxy, EntityProxyServer } from \"@effect/cluster\"\n * import { Rpc, RpcServer } from \"@effect/rpc\"\n * import { Layer, Schema } from \"effect\"\n *\n * export const Counter = Entity.make(\"Counter\", [\n *   Rpc.make(\"Increment\", {\n *     payload: { id: Schema.String, amount: Schema.Number },\n *     primaryKey: ({ id }) => id,\n *     success: Schema.Number\n *   })\n * ]).annotateRpcs(ClusterSchema.Persisted, true)\n *\n * // Use EntityProxy.toRpcGroup to create a `RpcGroup` from the Counter entity\n * export class MyRpcs extends EntityProxy.toRpcGroup(Counter) {}\n *\n * // Use EntityProxyServer.layerRpcHandlers to create a layer that implements\n * // the rpc handlers\n * const RpcServerLayer = RpcServer.layer(MyRpcs).pipe(\n *   Layer.provide(EntityProxyServer.layerRpcHandlers(Counter))\n * )\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const toRpcGroup = <Type extends string, Rpcs extends Rpc.Any>(\n  entity: Entity.Entity<Type, Rpcs>\n): RpcGroup.RpcGroup<ConvertRpcs<Rpcs, Type>> => {\n  const rpcs: Array<Rpc.Any> = []\n  for (const parentRpc_ of entity.protocol.requests.values()) {\n    const parentRpc = parentRpc_ as any as Rpc.AnyWithProps\n    const payloadSchema = Schema.Struct({\n      entityId: Schema.String,\n      payload: parentRpc.payloadSchema\n    })\n    const oldMake = payloadSchema.make\n    payloadSchema.make = (input: any, options?: Schema.MakeOptions) => {\n      return oldMake({\n        entityId: input.entityId,\n        payload: parentRpc.payloadSchema.make ? parentRpc.payloadSchema.make(input.payload, options) : input.payload\n      }, options)\n    }\n    const rpc = Rpc.make(`${entity.type}.${parentRpc._tag}`, {\n      payload: payloadSchema,\n      error: Schema.Union(parentRpc.errorSchema, ...clientErrors),\n      success: parentRpc.successSchema\n    }).annotateContext(parentRpc.annotations)\n    const rpcDiscard = Rpc.make(`${entity.type}.${parentRpc._tag}Discard`, {\n      payload: payloadSchema,\n      error: Schema.Union(...clientErrors)\n    }).annotateContext(parentRpc.annotations)\n    rpcs.push(rpc, rpcDiscard)\n  }\n  return RpcGroup.make(...rpcs) as any as RpcGroup.RpcGroup<ConvertRpcs<Rpcs, Type>>\n}\n\n/**\n * @since 1.0.0\n */\nexport type ConvertRpcs<Rpcs extends Rpc.Any, Prefix extends string> = Rpcs extends Rpc.Rpc<\n  infer _Tag,\n  infer _Payload,\n  infer _Success,\n  infer _Error,\n  infer _Middleware\n> ?\n    | Rpc.Rpc<\n      `${Prefix}.${_Tag}`,\n      Schema.Struct<{\n        entityId: typeof Schema.String\n        payload: _Payload\n      }>,\n      _Success,\n      Schema.Schema<\n        | _Error[\"Type\"]\n        | MailboxFull\n        | AlreadyProcessingMessage\n        | PersistenceError\n        | _Error[\"Encoded\"]\n        | typeof MailboxFull[\"Encoded\"]\n        | typeof AlreadyProcessingMessage[\"Encoded\"]\n        | typeof PersistenceError[\"Encoded\"],\n        _Error[\"Context\"]\n      >\n    >\n    | Rpc.Rpc<\n      `${Prefix}.${_Tag}Discard`,\n      Schema.Struct<{\n        entityId: typeof Schema.String\n        payload: _Payload\n      }>,\n      typeof Schema.Void,\n      Schema.Union<[\n        typeof MailboxFull,\n        typeof AlreadyProcessingMessage,\n        typeof PersistenceError\n      ]>\n    >\n  : never\n\nconst entityIdPath = Schema.Struct({\n  entityId: Schema.String\n})\n\n/**\n * Derives an `HttpApiGroup` from an `Entity`.\n *\n * ```ts\n * import { ClusterSchema, Entity, EntityProxy, EntityProxyServer } from \"@effect/cluster\"\n * import { HttpApi, HttpApiBuilder } from \"@effect/platform\"\n * import { Rpc } from \"@effect/rpc\"\n * import { Layer, Schema } from \"effect\"\n *\n * export const Counter = Entity.make(\"Counter\", [\n *   Rpc.make(\"Increment\", {\n *     payload: { id: Schema.String, amount: Schema.Number },\n *     primaryKey: ({ id }) => id,\n *     success: Schema.Number\n *   })\n * ]).annotateRpcs(ClusterSchema.Persisted, true)\n *\n * // Use EntityProxy.toHttpApiGroup to create a `HttpApiGroup` from the\n * // Counter entity\n * export class MyApi extends HttpApi.make(\"api\")\n *   .add(\n *     EntityProxy.toHttpApiGroup(\"counter\", Counter)\n *       .prefix(\"/counter\")\n *   )\n * {}\n *\n * // Use EntityProxyServer.layerHttpApi to create a layer that implements\n * // the handlers for the HttpApiGroup\n * const ApiLayer = HttpApiBuilder.api(MyApi).pipe(\n *   Layer.provide(EntityProxyServer.layerHttpApi(MyApi, \"counter\", Counter))\n * )\n * ```\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const toHttpApiGroup = <const Name extends string, Type extends string, Rpcs extends Rpc.Any>(\n  name: Name,\n  entity: Entity.Entity<Type, Rpcs>\n): HttpApiGroup.HttpApiGroup<Name, ConvertHttpApi<Rpcs>> => {\n  let group = HttpApiGroup.make(name)\n  for (const parentRpc_ of entity.protocol.requests.values()) {\n    const parentRpc = parentRpc_ as any as Rpc.AnyWithProps\n    const endpoint = HttpApiEndpoint.post(parentRpc._tag, `/${tagToPath(parentRpc._tag)}/:entityId`)\n      .setPath(entityIdPath)\n      .setPayload(parentRpc.payloadSchema)\n      .addSuccess(parentRpc.successSchema)\n      .addError(Schema.Union(parentRpc.errorSchema, ...clientErrors))\n      .annotateContext(parentRpc.annotations)\n    const endpointDiscard = HttpApiEndpoint.post(\n      `${parentRpc._tag}Discard`,\n      `/${tagToPath(parentRpc._tag)}/:entityId/discard`\n    )\n      .setPath(entityIdPath)\n      .setPayload(parentRpc.payloadSchema)\n      .addError(Schema.Union(...clientErrors))\n      .annotateContext(parentRpc.annotations)\n\n    group = group.add(endpoint).add(endpointDiscard) as any\n  }\n  return group as any as HttpApiGroup.HttpApiGroup<Name, ConvertHttpApi<Rpcs>>\n}\n\nconst tagToPath = (tag: string): string =>\n  tag\n    .replace(/[^a-zA-Z0-9]+/g, \"-\") // Replace non-alphanumeric characters with hyphen\n    .replace(/([a-z])([A-Z])/g, \"$1-$2\") // Insert hyphen before uppercase letters\n    .toLowerCase()\n\n/**\n * @since 1.0.0\n */\nexport type ConvertHttpApi<Rpcs extends Rpc.Any> = Rpcs extends Rpc.Rpc<\n  infer _Tag,\n  infer _Payload,\n  infer _Success,\n  infer _Error,\n  infer _Middleware\n> ?\n    | HttpApiEndpoint.HttpApiEndpoint<\n      _Tag,\n      \"POST\",\n      { readonly entityId: string },\n      never,\n      _Payload[\"Type\"],\n      never,\n      _Success[\"Type\"],\n      _Error[\"Type\"] | MailboxFull | AlreadyProcessingMessage | PersistenceError,\n      _Payload[\"Context\"] | _Success[\"Context\"],\n      _Error[\"Context\"]\n    >\n    | HttpApiEndpoint.HttpApiEndpoint<\n      `${_Tag}Discard`,\n      \"POST\",\n      { readonly entityId: string },\n      never,\n      _Payload[\"Type\"],\n      never,\n      void,\n      MailboxFull | AlreadyProcessingMessage | PersistenceError\n    >\n  : never\n"
  },
  {
    "path": "packages/cluster/src/EntityProxyServer.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as HttpApi from \"@effect/platform/HttpApi\"\nimport * as HttpApiBuilder from \"@effect/platform/HttpApiBuilder\"\nimport type { ApiGroup, HttpApiGroup } from \"@effect/platform/HttpApiGroup\"\nimport type * as Rpc from \"@effect/rpc/Rpc\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport type * as Entity from \"./Entity.js\"\nimport type { Sharding } from \"./Sharding.js\"\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerHttpApi = <\n  ApiId extends string,\n  Groups extends HttpApiGroup.Any,\n  ApiE,\n  ApiR,\n  Name extends HttpApiGroup.Name<Groups>,\n  Type extends string,\n  Rpcs extends Rpc.Any\n>(\n  api: HttpApi.HttpApi<ApiId, Groups, ApiE, ApiR>,\n  name: Name,\n  entity: Entity.Entity<Type, Rpcs>\n): Layer.Layer<ApiGroup<ApiId, Name>, never, Sharding | Rpc.Context<Rpcs>> =>\n  HttpApiBuilder.group(\n    api,\n    name,\n    Effect.fnUntraced(function*(handlers_) {\n      const client = yield* entity.client\n      let handlers = handlers_\n      for (const parentRpc_ of entity.protocol.requests.values()) {\n        const parentRpc = parentRpc_ as any as Rpc.AnyWithProps\n        handlers = handlers\n          .handle(\n            parentRpc._tag as any,\n            (({ path, payload }: { path: { entityId: string }; payload: any }) =>\n              (client(path.entityId) as any as Record<string, (p: any) => Effect.Effect<any>>)[parentRpc._tag](\n                payload\n              ).pipe(\n                Effect.tapDefect(Effect.logError),\n                Effect.annotateLogs({\n                  module: \"EntityProxyServer\",\n                  entity: entity.type,\n                  entityId: path.entityId,\n                  method: parentRpc._tag\n                })\n              )) as any\n          )\n          .handle(\n            `${parentRpc._tag}Discard` as any,\n            (({ path, payload }: { path: { entityId: string }; payload: any }) =>\n              (client(path.entityId) as any as Record<string, (p: any, o: {}) => Effect.Effect<any>>)[parentRpc._tag](\n                payload,\n                { discard: true }\n              ).pipe(\n                Effect.tapDefect(Effect.logError),\n                Effect.annotateLogs({\n                  module: \"EntityProxyServer\",\n                  entity: entity.type,\n                  entityId: path.entityId,\n                  method: `${parentRpc._tag}Discard`\n                })\n              )) as any\n          ) as any\n      }\n      return handlers as HttpApiBuilder.Handlers<never, never, never>\n    })\n  )\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerRpcHandlers = <\n  const Type extends string,\n  Rpcs extends Rpc.Any\n>(entity: Entity.Entity<Type, Rpcs>): Layer.Layer<RpcHandlers<Rpcs, Type>, never, Sharding | Rpc.Context<Rpcs>> =>\n  Layer.effectContext(Effect.gen(function*() {\n    const context = yield* Effect.context<never>()\n    const client = yield* entity.client\n    const handlers = new Map<string, Rpc.Handler<string>>()\n    for (const parentRpc_ of entity.protocol.requests.values()) {\n      const parentRpc = parentRpc_ as any as Rpc.AnyWithProps\n      const tag = `${entity.type}.${parentRpc._tag}` as const\n      const key = `@effect/rpc/Rpc/${tag}`\n      handlers.set(key, {\n        context,\n        tag,\n        handler: ({ entityId, payload }: any) => (client(entityId) as any)[parentRpc._tag](payload) as any\n      } as any)\n      handlers.set(`${key}Discard`, {\n        context,\n        tag,\n        handler: ({ entityId, payload }: any) =>\n          (client(entityId) as any)[parentRpc._tag](payload, { discard: true }) as any\n      } as any)\n    }\n    return Context.unsafeMake(handlers)\n  }))\n\n/**\n * @since 1.0.0\n */\nexport type RpcHandlers<Rpcs extends Rpc.Any, Prefix extends string> = Rpcs extends Rpc.Rpc<\n  infer _Tag,\n  infer _Payload,\n  infer _Success,\n  infer _Error,\n  infer _Middleware\n> ? Rpc.Handler<`${Prefix}.${_Tag}`> | Rpc.Handler<`${Prefix}.${_Tag}Discard`>\n  : never\n"
  },
  {
    "path": "packages/cluster/src/EntityResource.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as RcRef from \"effect/RcRef\"\nimport * as Scope from \"effect/Scope\"\nimport type * as v1 from \"kubernetes-types/core/v1.d.ts\"\nimport * as Entity from \"./Entity.js\"\nimport * as K8sHttpClient from \"./K8sHttpClient.js\"\nimport type { Sharding } from \"./Sharding.js\"\n\n/**\n * @since 1.0.0\n * @category Type ids\n */\nexport const TypeId: TypeId = \"~@effect/cluster/EntityResource\"\n\n/**\n * @since 1.0.0\n * @category Type ids\n */\nexport type TypeId = \"~@effect/cluster/EntityResource\"\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface EntityResource<out A, out E = never> {\n  readonly [TypeId]: TypeId\n  readonly get: Effect.Effect<A, E, Scope.Scope>\n  readonly close: Effect.Effect<void>\n}\n\n/**\n * A `Scope` that is only closed when the resource is explicitly closed.\n *\n * It is not closed during restarts, due to shard movement or node shutdowns.\n *\n * @since 1.0.0\n * @category Scope\n */\nexport class CloseScope extends Context.Tag(\"@effect/cluster/EntityResource/CloseScope\")<\n  CloseScope,\n  Scope.Scope\n>() {}\n\n/**\n * A `EntityResource` is a resource that can be acquired inside a cluster\n * entity, which will keep the entity alive even across restarts.\n *\n * The resource will only be fully released when the idle time to live is\n * reached, or when the `close` effect is called.\n *\n * By default, the `idleTimeToLive` is infinite, meaning the resource will only\n * be released when `close` is called.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const make: <A, E, R>(options: {\n  readonly acquire: Effect.Effect<A, E, R>\n  readonly idleTimeToLive?: Duration.DurationInput | undefined\n}) => Effect.Effect<\n  EntityResource<A, E>,\n  E,\n  Scope.Scope | Exclude<R, CloseScope> | Sharding | Entity.CurrentAddress\n> = Effect.fnUntraced(function*<A, E, R>(options: {\n  readonly acquire: Effect.Effect<A, E, R>\n  readonly idleTimeToLive?: Duration.DurationInput | undefined\n}) {\n  let shuttingDown = false\n\n  yield* Entity.keepAlive(true)\n\n  const ref = yield* RcRef.make({\n    acquire: Effect.gen(function*() {\n      const closeable = yield* Scope.make()\n\n      yield* Effect.addFinalizer(\n        Effect.fnUntraced(function*(exit) {\n          if (shuttingDown) return\n          yield* Scope.close(closeable, exit)\n          yield* Entity.keepAlive(false)\n        })\n      )\n\n      return yield* options.acquire.pipe(\n        Effect.provideService(CloseScope, closeable)\n      )\n    }),\n    idleTimeToLive: options.idleTimeToLive ?? Duration.infinity\n  })\n\n  yield* Effect.addFinalizer(() => {\n    shuttingDown = true\n    return Effect.void\n  })\n\n  // Initialize the resource\n  yield* Effect.scoped(RcRef.get(ref))\n\n  return identity<EntityResource<A, E>>({\n    [TypeId]: TypeId,\n    get: RcRef.get(ref),\n    close: RcRef.invalidate(ref)\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Kubernetes\n */\nexport const makeK8sPod: (\n  spec: v1.Pod,\n  options?: {\n    readonly idleTimeToLive?: Duration.DurationInput | undefined\n  } | undefined\n) => Effect.Effect<\n  EntityResource<K8sHttpClient.PodStatus>,\n  never,\n  Scope.Scope | Sharding | Entity.CurrentAddress | K8sHttpClient.K8sHttpClient\n> = Effect.fnUntraced(function*(spec: v1.Pod, options?: {\n  readonly idleTimeToLive?: Duration.DurationInput | undefined\n}) {\n  const createPod = yield* K8sHttpClient.makeCreatePod\n  return yield* make({\n    ...options,\n    acquire: Effect.gen(function*() {\n      const scope = yield* CloseScope\n      return yield* createPod(spec).pipe(\n        Scope.extend(scope)\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/cluster/src/EntityType.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Schema from \"effect/Schema\"\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const EntityType = Schema.NonEmptyTrimmedString.pipe(Schema.brand(\"EntityType\"))\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type EntityType = typeof EntityType.Type\n"
  },
  {
    "path": "packages/cluster/src/Envelope.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Headers from \"@effect/platform/Headers\"\nimport type * as Rpc from \"@effect/rpc/Rpc\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as PrimaryKey from \"effect/PrimaryKey\"\nimport type { ReadonlyRecord } from \"effect/Record\"\nimport * as Schema from \"effect/Schema\"\nimport { EntityAddress, EntityAddressFromSelf } from \"./EntityAddress.js\"\nimport { type Snowflake, SnowflakeFromString } from \"./Snowflake.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/cluster/Envelope\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Envelope<R extends Rpc.Any> = Request<R> | AckChunk | Interrupt\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Envelope {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Any = Envelope<any>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Encoded = Request.Encoded | typeof AckChunk.Encoded | typeof Interrupt.Encoded\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type PartialEncoded = Request.PartialEncoded | AckChunk | Interrupt\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Request<in out Rpc extends Rpc.Any> {\n  readonly [TypeId]: TypeId\n  readonly _tag: \"Request\"\n  readonly requestId: Snowflake\n  readonly address: EntityAddress\n  readonly tag: Rpc.Tag<Rpc>\n  readonly payload: Rpc.Payload<Rpc>\n  readonly headers: Headers.Headers\n  readonly traceId?: string | undefined\n  readonly spanId?: string | undefined\n  readonly sampled?: boolean | undefined\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport class AckChunk extends Schema.TaggedClass<AckChunk>(\"@effect/cluster/Envelope/AckChunk\")(\"AckChunk\", {\n  id: SnowflakeFromString,\n  address: EntityAddress,\n  requestId: SnowflakeFromString,\n  replyId: SnowflakeFromString\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId]: TypeId = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  withRequestId(requestId: Snowflake): AckChunk {\n    return new AckChunk({\n      ...this,\n      requestId\n    })\n  }\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport class Interrupt extends Schema.TaggedClass<Interrupt>(\"@effect/cluster/Envelope/Interrupt\")(\"Interrupt\", {\n  id: SnowflakeFromString,\n  address: EntityAddress,\n  requestId: SnowflakeFromString\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId]: TypeId = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  withRequestId(requestId: Snowflake): Interrupt {\n    return new Interrupt({\n      ...this,\n      requestId\n    })\n  }\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Request {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Any = Request<any>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Encoded {\n    readonly _tag: \"Request\"\n    readonly requestId: string\n    readonly address: typeof EntityAddress.Encoded\n    readonly tag: string\n    readonly payload: unknown\n    readonly headers: ReadonlyRecord<string, string>\n    readonly traceId?: string | undefined\n    readonly spanId?: string | undefined\n    readonly sampled?: boolean | undefined\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface PartialEncoded {\n    readonly _tag: \"Request\"\n    readonly requestId: Snowflake\n    readonly address: EntityAddress\n    readonly tag: string\n    readonly payload: unknown\n    readonly headers: Headers.Headers\n    readonly traceId?: string | undefined\n    readonly spanId?: string | undefined\n    readonly sampled?: boolean | undefined\n  }\n}\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isEnvelope = (u: unknown): u is Envelope<any> => Predicate.hasProperty(u, TypeId)\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeRequest = <Rpc extends Rpc.Any>(\n  options: {\n    readonly requestId: Snowflake\n    readonly address: EntityAddress\n    readonly tag: Rpc.Tag<Rpc>\n    readonly payload: Rpc.Payload<Rpc>\n    readonly headers: Headers.Headers\n    readonly traceId?: string | undefined\n    readonly spanId?: string | undefined\n    readonly sampled?: boolean | undefined\n  }\n): Request<Rpc> => ({\n  [TypeId]: TypeId,\n  _tag: \"Request\",\n  requestId: options.requestId,\n  tag: options.tag,\n  address: options.address,\n  payload: options.payload,\n  headers: options.headers,\n  traceId: options.traceId,\n  spanId: options.spanId,\n  sampled: options.sampled\n})\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const EnvelopeFromSelf: Schema.Schema<\n  Envelope.Any,\n  Envelope.Any\n> = Schema.declare(isEnvelope, {\n  typeConstructor: { _tag: \"effect/cluster/Envelope\" },\n  identifier: \"Envelope\"\n})\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const RequestFromSelf: Schema.Schema<\n  Request.Any,\n  Request.Any\n> = Schema.declare((u): u is Request.Any => isEnvelope(u) && u._tag === \"Request\", {\n  typeConstructor: { _tag: \"effect/cluster/Envelope.Request\" },\n  identifier: \"Envelope\"\n})\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const PartialEncodedRequest: Schema.Struct<\n  {\n    _tag: Schema.Literal<[\"Request\"]>\n    requestId: Schema.Schema<Snowflake, string>\n    address: typeof EntityAddress\n    tag: typeof Schema.String\n    payload: typeof Schema.Unknown\n    headers: Schema.Schema<Headers.Headers, ReadonlyRecord<string, string>>\n    traceId: Schema.optional<typeof Schema.String>\n    spanId: Schema.optional<typeof Schema.String>\n    sampled: Schema.optional<typeof Schema.Boolean>\n  }\n> = Schema.Struct({\n  _tag: Schema.Literal(\"Request\"),\n  requestId: SnowflakeFromString,\n  address: EntityAddress,\n  tag: Schema.String,\n  payload: Schema.Unknown,\n  headers: Headers.schema,\n  traceId: Schema.optional(Schema.String),\n  spanId: Schema.optional(Schema.String),\n  sampled: Schema.optional(Schema.Boolean)\n}) satisfies Schema.Schema<Request.PartialEncoded, Request.Encoded>\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const PartialEncoded: Schema.Union<\n  [\n    Schema.Struct<\n      {\n        _tag: Schema.Literal<[\"Request\"]>\n        requestId: Schema.Schema<Snowflake, string>\n        address: typeof EntityAddress\n        tag: typeof Schema.String\n        payload: typeof Schema.Unknown\n        headers: Schema.Schema<Headers.Headers, ReadonlyRecord<string, string>>\n        traceId: Schema.optional<typeof Schema.String>\n        spanId: Schema.optional<typeof Schema.String>\n        sampled: Schema.optional<typeof Schema.Boolean>\n      }\n    >,\n    typeof AckChunk,\n    typeof Interrupt\n  ]\n> = Schema.Union(PartialEncodedRequest, AckChunk, Interrupt) satisfies Schema.Schema<\n  Envelope.PartialEncoded,\n  Envelope.Encoded\n>\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const PartialEncodedArray: Schema.Schema<\n  Array<Envelope.PartialEncoded>,\n  Array<Envelope.Encoded>\n> = Schema.mutable(Schema.Array(PartialEncoded))\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const PartialEncodedRequestFromSelf: Schema.Struct<\n  {\n    _tag: Schema.Literal<[\"Request\"]>\n    requestId: Schema.Schema<Snowflake>\n    address: Schema.Schema<EntityAddress>\n    tag: typeof Schema.String\n    payload: typeof Schema.Unknown\n    headers: Schema.Schema<Headers.Headers>\n    traceId: Schema.optional<typeof Schema.String>\n    spanId: Schema.optional<typeof Schema.String>\n    sampled: Schema.optional<typeof Schema.Boolean>\n  }\n> = Schema.Struct({\n  _tag: Schema.Literal(\"Request\"),\n  requestId: Schema.typeSchema(SnowflakeFromString),\n  address: EntityAddressFromSelf,\n  tag: Schema.String,\n  payload: Schema.Unknown,\n  headers: Headers.schemaFromSelf,\n  traceId: Schema.optional(Schema.String),\n  spanId: Schema.optional(Schema.String),\n  sampled: Schema.optional(Schema.Boolean)\n}) satisfies Schema.Schema<Request.PartialEncoded>\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const PartialEncodedFromSelf: Schema.Union<\n  [\n    Schema.Struct<\n      {\n        _tag: Schema.Literal<[\"Request\"]>\n        requestId: Schema.Schema<Snowflake>\n        address: Schema.Schema<EntityAddress>\n        tag: typeof Schema.String\n        payload: typeof Schema.Unknown\n        headers: Schema.Schema<Headers.Headers>\n        traceId: Schema.optional<typeof Schema.String>\n        spanId: Schema.optional<typeof Schema.String>\n        sampled: Schema.optional<typeof Schema.Boolean>\n      }\n    >,\n    Schema.Schema<AckChunk>,\n    Schema.Schema<Interrupt>\n  ]\n> = Schema.Union(\n  PartialEncodedRequestFromSelf,\n  Schema.typeSchema(AckChunk),\n  Schema.typeSchema(Interrupt)\n) satisfies Schema.Schema<Envelope.PartialEncoded>\n\n/**\n * @since 1.0.0\n * @category primary key\n */\nexport const primaryKey = <R extends Rpc.Any>(envelope: Envelope<R>): string | null => {\n  if (envelope._tag !== \"Request\" || !(Predicate.hasProperty(envelope.payload, PrimaryKey.symbol))) {\n    return null\n  }\n  return primaryKeyByAddress({\n    address: envelope.address,\n    tag: envelope.tag,\n    id: PrimaryKey.value(envelope.payload)\n  })\n}\n\n/**\n * @since 1.0.0\n * @category primary key\n */\nexport const primaryKeyByAddress = (options: {\n  readonly address: EntityAddress\n  readonly tag: string\n  readonly id: string\n}): string =>\n  // hash the entity address to save space?\n  `${options.address.entityType}/${options.address.entityId}/${options.tag}/${options.id}`\n"
  },
  {
    "path": "packages/cluster/src/HttpRunner.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as HttpRouter from \"@effect/platform/HttpLayerRouter\"\nimport type * as HttpServer from \"@effect/platform/HttpServer\"\nimport type { HttpServerRequest } from \"@effect/platform/HttpServerRequest\"\nimport type { HttpServerResponse } from \"@effect/platform/HttpServerResponse\"\nimport * as Socket from \"@effect/platform/Socket\"\nimport * as RpcClient from \"@effect/rpc/RpcClient\"\nimport * as RpcSerialization from \"@effect/rpc/RpcSerialization\"\nimport * as RpcServer from \"@effect/rpc/RpcServer\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport type { Scope } from \"effect/Scope\"\nimport type { MessageStorage } from \"./MessageStorage.js\"\nimport type { RunnerHealth } from \"./RunnerHealth.js\"\nimport * as Runners from \"./Runners.js\"\nimport { RpcClientProtocol } from \"./Runners.js\"\nimport * as RunnerServer from \"./RunnerServer.js\"\nimport type { RunnerStorage } from \"./RunnerStorage.js\"\nimport * as Sharding from \"./Sharding.js\"\nimport type * as ShardingConfig from \"./ShardingConfig.js\"\n\nconst normalizePath = (path: string): string => path.startsWith(\"/\") ? path : `/${path}`\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerClientProtocolHttp = (options: {\n  readonly path: string\n  readonly https?: boolean | undefined\n}): Layer.Layer<\n  RpcClientProtocol,\n  never,\n  RpcSerialization.RpcSerialization | HttpClient.HttpClient\n> =>\n  Layer.effect(RpcClientProtocol)(\n    Effect.gen(function*() {\n      const serialization = yield* RpcSerialization.RpcSerialization\n      const client = yield* HttpClient.HttpClient\n      const https = options.https ?? false\n      return (address) => {\n        const clientWithUrl = HttpClient.mapRequest(\n          client,\n          HttpClientRequest.prependUrl(\n            `http${https ? \"s\" : \"\"}://${address.host}:${address.port}${normalizePath(options.path)}`\n          )\n        )\n        return RpcClient.makeProtocolHttp(clientWithUrl).pipe(\n          Effect.provideService(RpcSerialization.RpcSerialization, serialization)\n        )\n      }\n    })\n  )\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerClientProtocolHttpDefault: Layer.Layer<\n  Runners.RpcClientProtocol,\n  never,\n  RpcSerialization.RpcSerialization | HttpClient.HttpClient\n> = layerClientProtocolHttp({ path: \"/\" })\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerClientProtocolWebsocket = (options: {\n  readonly path: string\n  readonly https?: boolean | undefined\n}): Layer.Layer<\n  RpcClientProtocol,\n  never,\n  RpcSerialization.RpcSerialization | Socket.WebSocketConstructor\n> =>\n  Layer.effect(RpcClientProtocol)(\n    Effect.gen(function*() {\n      const serialization = yield* RpcSerialization.RpcSerialization\n      const https = options.https ?? false\n      const constructor = yield* Socket.WebSocketConstructor\n      return Effect.fnUntraced(function*(address) {\n        const socket = yield* Socket.makeWebSocket(\n          `ws${https ? \"s\" : \"\"}://${address.host}:${address.port}${normalizePath(options.path)}`\n        ).pipe(\n          Effect.provideService(Socket.WebSocketConstructor, constructor)\n        )\n        return yield* RpcClient.makeProtocolSocket().pipe(\n          Effect.provideService(Socket.Socket, socket),\n          Effect.provideService(RpcSerialization.RpcSerialization, serialization)\n        )\n      })\n    })\n  )\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerClientProtocolWebsocketDefault: Layer.Layer<\n  Runners.RpcClientProtocol,\n  never,\n  RpcSerialization.RpcSerialization | Socket.WebSocketConstructor\n> = layerClientProtocolWebsocket({ path: \"/\" })\n\n/**\n * @since 1.0.0\n * @category Http App\n */\nexport const toHttpEffect: Effect.Effect<\n  Effect.Effect<HttpServerResponse, never, Scope | HttpServerRequest>,\n  never,\n  Scope | RpcSerialization.RpcSerialization | Sharding.Sharding | MessageStorage\n> = Effect.gen(function*() {\n  const handlers = yield* Layer.build(RunnerServer.layerHandlers)\n  return yield* RpcServer.toHttpApp(Runners.Rpcs, {\n    spanPrefix: \"RunnerServer\",\n    disableTracing: true\n  }).pipe(Effect.provide(handlers))\n})\n\n/**\n * @since 1.0.0\n * @category Http App\n */\nexport const toHttpEffectWebsocket: Effect.Effect<\n  Effect.Effect<HttpServerResponse, never, Scope | HttpServerRequest>,\n  never,\n  Scope | RpcSerialization.RpcSerialization | Sharding.Sharding | MessageStorage\n> = Effect.gen(function*() {\n  const handlers = yield* Layer.build(RunnerServer.layerHandlers)\n  return yield* RpcServer.toHttpAppWebsocket(Runners.Rpcs, {\n    spanPrefix: \"RunnerServer\",\n    disableTracing: true\n  }).pipe(Effect.provide(handlers))\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerClient: Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  ShardingConfig.ShardingConfig | Runners.RpcClientProtocol | MessageStorage | RunnerStorage | RunnerHealth\n> = Sharding.layer.pipe(\n  Layer.provideMerge(Runners.layerRpc)\n)\n\n/**\n * A HTTP layer for the `Runners` services, that adds a route to the provided\n * `HttpRouter`.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layerHttpOptions = (options: {\n  readonly path: HttpRouter.PathInput\n}): Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  | RunnerStorage\n  | RunnerHealth\n  | RpcSerialization.RpcSerialization\n  | MessageStorage\n  | ShardingConfig.ShardingConfig\n  | Runners.RpcClientProtocol\n  | HttpRouter.HttpRouter\n> =>\n  RunnerServer.layerWithClients.pipe(\n    Layer.provide(RpcServer.layerProtocolHttpRouter(options))\n  )\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerWebsocketOptions = (options: {\n  readonly path: HttpRouter.PathInput\n}): Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  | ShardingConfig.ShardingConfig\n  | Runners.RpcClientProtocol\n  | MessageStorage\n  | RunnerStorage\n  | RunnerHealth\n  | RpcSerialization.RpcSerialization\n  | HttpRouter.HttpRouter\n> =>\n  RunnerServer.layerWithClients.pipe(\n    Layer.provide(RpcServer.layerProtocolWebsocketRouter(options))\n  )\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerHttp: Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  | RpcSerialization.RpcSerialization\n  | ShardingConfig.ShardingConfig\n  | HttpClient.HttpClient\n  | HttpServer.HttpServer\n  | MessageStorage\n  | RunnerStorage\n  | RunnerHealth\n> = HttpRouter.serve(layerHttpOptions({ path: \"/\" })).pipe(\n  Layer.provide(layerClientProtocolHttpDefault)\n)\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerHttpClientOnly: Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  | RpcSerialization.RpcSerialization\n  | ShardingConfig.ShardingConfig\n  | HttpClient.HttpClient\n  | MessageStorage\n  | RunnerStorage\n> = RunnerServer.layerClientOnly.pipe(\n  Layer.provide(layerClientProtocolHttpDefault)\n)\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerWebsocket: Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  | RpcSerialization.RpcSerialization\n  | ShardingConfig.ShardingConfig\n  | Socket.WebSocketConstructor\n  | HttpServer.HttpServer\n  | MessageStorage\n  | RunnerStorage\n  | RunnerHealth\n> = HttpRouter.serve(layerWebsocketOptions({ path: \"/\" })).pipe(\n  Layer.provide(layerClientProtocolWebsocketDefault)\n)\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerWebsocketClientOnly: Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  | ShardingConfig.ShardingConfig\n  | MessageStorage\n  | RunnerStorage\n  | RpcSerialization.RpcSerialization\n  | Socket.WebSocketConstructor\n> = RunnerServer.layerClientOnly.pipe(\n  Layer.provide(layerClientProtocolWebsocketDefault)\n)\n"
  },
  {
    "path": "packages/cluster/src/K8sHttpClient.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as FileSystem from \"@effect/platform/FileSystem\"\nimport * as HttpClient from \"@effect/platform/HttpClient\"\nimport type * as HttpClientError from \"@effect/platform/HttpClientError\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as HttpClientResponse from \"@effect/platform/HttpClientResponse\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Schema from \"effect/Schema\"\nimport type * as v1 from \"kubernetes-types/core/v1.d.ts\"\n\n/**\n * @since 1.0.0\n * @category Tags\n */\nexport class K8sHttpClient extends Context.Tag(\"@effect/cluster/K8sHttpClient\")<\n  K8sHttpClient,\n  HttpClient.HttpClient\n>() {}\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer: Layer.Layer<\n  K8sHttpClient,\n  never,\n  HttpClient.HttpClient | FileSystem.FileSystem\n> = Layer.effect(\n  K8sHttpClient,\n  Effect.gen(function*() {\n    const fs = yield* FileSystem.FileSystem\n    const token = yield* fs.readFileString(\"/var/run/secrets/kubernetes.io/serviceaccount/token\").pipe(\n      Effect.option\n    )\n    return (yield* HttpClient.HttpClient).pipe(\n      HttpClient.mapRequest(HttpClientRequest.prependUrl(\"https://kubernetes.default.svc/api\")),\n      token._tag === \"Some\" ? HttpClient.mapRequest(HttpClientRequest.bearerToken(token.value.trim())) : identity,\n      HttpClient.filterStatusOk,\n      HttpClient.retryTransient({\n        schedule: Schedule.spaced(5000)\n      })\n    )\n  })\n)\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const makeGetPods: (\n  options?: {\n    readonly namespace?: string | undefined\n    readonly labelSelector?: string | undefined\n  } | undefined\n) => Effect.Effect<\n  Effect.Effect<Map<string, Pod>, HttpClientError.HttpClientError | ParseResult.ParseError, never>,\n  never,\n  K8sHttpClient\n> = Effect.fnUntraced(function*(options?: {\n  readonly namespace?: string | undefined\n  readonly labelSelector?: string | undefined\n}) {\n  const client = yield* K8sHttpClient\n\n  const getPods = HttpClientRequest.get(\n    options?.namespace ? `/v1/namespaces/${options.namespace}/pods` : \"/v1/pods\"\n  ).pipe(\n    HttpClientRequest.setUrlParam(\"fieldSelector\", \"status.phase=Running\"),\n    options?.labelSelector ? HttpClientRequest.setUrlParam(\"labelSelector\", options.labelSelector) : identity\n  )\n\n  return yield* client.execute(getPods).pipe(\n    Effect.flatMap(HttpClientResponse.schemaBodyJson(PodList)),\n    Effect.map((list) => {\n      const pods = new Map<string, Pod>()\n      for (let i = 0; i < list.items.length; i++) {\n        const pod = list.items[i]\n        pods.set(pod.status.podIP, pod)\n      }\n      return pods\n    }),\n    Effect.tapErrorCause((cause) => Effect.logWarning(\"Failed to fetch pods from Kubernetes API\", cause)),\n    Effect.cachedWithTTL(\"10 seconds\")\n  )\n})\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const makeCreatePod = Effect.gen(function*() {\n  const client = yield* K8sHttpClient\n\n  return Effect.fnUntraced(function*(spec: v1.Pod) {\n    spec = {\n      apiVersion: \"v1\",\n      kind: \"Pod\",\n      metadata: {\n        namespace: \"default\",\n        ...spec.metadata\n      },\n      ...spec\n    }\n    const namespace = spec.metadata?.namespace ?? \"default\"\n    const name = spec.metadata!.name!\n    const readPodRaw = HttpClientRequest.get(`/v1/namespaces/${namespace}/pods/${name}`).pipe(\n      client.execute\n    )\n    const readPod = readPodRaw.pipe(\n      Effect.flatMap(HttpClientResponse.schemaBodyJson(Pod)),\n      Effect.asSome,\n      Effect.retry({\n        while: (e) => e._tag === \"ParseError\",\n        schedule: Schedule.spaced(\"1 seconds\")\n      }),\n      Effect.catchIf((err) => err._tag === \"ResponseError\" && err.response.status === 404, () => Effect.succeedNone),\n      Effect.orDie\n    )\n    const isPodFound = readPodRaw.pipe(\n      Effect.as(true),\n      Effect.catchIf(\n        (err) => err._tag === \"ResponseError\" && err.response.status === 404,\n        () => Effect.succeed(false)\n      )\n    )\n    const createPod = HttpClientRequest.post(`/v1/namespaces/${namespace}/pods`).pipe(\n      HttpClientRequest.bodyUnsafeJson(spec),\n      client.execute,\n      Effect.catchIf(\n        (err) => err._tag === \"ResponseError\" && err.response.status === 409,\n        () => readPod\n      ),\n      Effect.tapErrorCause(Effect.logInfo),\n      Effect.orDie\n    )\n    const deletePod = HttpClientRequest.del(`/v1/namespaces/${namespace}/pods/${name}`).pipe(\n      client.execute,\n      Effect.flatMap((res) => res.json),\n      Effect.catchIf(\n        (err) => err._tag === \"ResponseError\" && err.response.status === 404,\n        () => Effect.void\n      ),\n      Effect.tapErrorCause(Effect.logInfo),\n      Effect.orDie,\n      Effect.asVoid\n    )\n    yield* Effect.addFinalizer(Effect.fnUntraced(function*() {\n      yield* deletePod\n      yield* isPodFound.pipe(\n        Effect.repeat({\n          until: (found) => !found,\n          schedule: Schedule.spaced(\"3 seconds\")\n        }),\n        Effect.orDie\n      )\n    }))\n\n    let opod = Option.none<Pod>()\n    while (Option.isNone(opod) || !opod.value.isReady) {\n      if (Option.isNone(opod)) {\n        yield* createPod\n      }\n      yield* Effect.sleep(\"3 seconds\")\n      opod = yield* readPod\n    }\n    return opod.value.status\n  }, Effect.withSpan(\"K8sHttpClient.createPod\"))\n})\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class PodStatus extends Schema.Class<PodStatus>(\"@effect/cluster/K8sHttpClient/PodStatus\")({\n  phase: Schema.String,\n  conditions: Schema.Array(Schema.Struct({\n    type: Schema.String,\n    status: Schema.String,\n    lastTransitionTime: Schema.String\n  })),\n  podIP: Schema.String,\n  hostIP: Schema.String\n}) {}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport class Pod extends Schema.Class<Pod>(\"@effect/cluster/K8sHttpClient/Pod\")({\n  status: PodStatus\n}) {\n  get isReady(): boolean {\n    for (let i = 0; i < this.status.conditions.length; i++) {\n      const condition = this.status.conditions[i]\n      if (condition.type === \"Ready\") {\n        return condition.status === \"True\"\n      }\n    }\n    return false\n  }\n\n  get isReadyOrInitializing(): boolean {\n    let initializedAt: string | undefined\n    let readyAt: string | undefined\n    for (let i = 0; i < this.status.conditions.length; i++) {\n      const condition = this.status.conditions[i]\n      switch (condition.type) {\n        case \"Initialized\": {\n          if (condition.status !== \"True\") {\n            return true\n          }\n          initializedAt = condition.lastTransitionTime\n          break\n        }\n        case \"Ready\": {\n          if (condition.status === \"True\") {\n            return true\n          }\n          readyAt = condition.lastTransitionTime\n          break\n        }\n      }\n    }\n    // if the pod is still booting up, consider it ready as it would have\n    // already registered itself with RunnerStorage by now\n    return initializedAt === readyAt\n  }\n}\n\nconst PodList = Schema.Struct({\n  items: Schema.Array(Pod)\n})\n"
  },
  {
    "path": "packages/cluster/src/MachineId.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Schema from \"effect/Schema\"\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const MachineId = Schema.Int.pipe(\n  Schema.brand(\"MachineId\"),\n  Schema.annotations({\n    pretty: () => (machineId) => `MachineId(${machineId})`\n  })\n)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type MachineId = typeof MachineId.Type\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (shardId: number): MachineId => MachineId.make(shardId)\n"
  },
  {
    "path": "packages/cluster/src/Message.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Rpc from \"@effect/rpc/Rpc\"\nimport type { Context } from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\nimport type { PersistenceError } from \"./ClusterError.js\"\nimport { MalformedMessage } from \"./ClusterError.js\"\nimport type { EntityAddress } from \"./EntityAddress.js\"\nimport * as Envelope from \"./Envelope.js\"\nimport type * as Reply from \"./Reply.js\"\nimport type { Snowflake } from \"./Snowflake.js\"\n\n/**\n * @since 1.0.0\n * @category incoming\n */\nexport type Incoming<R extends Rpc.Any> = IncomingRequest<R> | IncomingEnvelope\n\n/**\n * @since 1.0.0\n * @category incoming\n */\nexport type IncomingLocal<R extends Rpc.Any> = IncomingRequestLocal<R> | IncomingEnvelope\n\n/**\n * @since 1.0.0\n * @category incoming\n */\nexport const incomingLocalFromOutgoing = <R extends Rpc.Any>(self: Outgoing<R>): IncomingLocal<R> => {\n  if (self._tag === \"OutgoingEnvelope\") {\n    return new IncomingEnvelope({ envelope: self.envelope })\n  }\n  return new IncomingRequestLocal({\n    envelope: self.envelope,\n    respond: self.respond,\n    lastSentReply: Option.none()\n  })\n}\n\n/**\n * @since 1.0.0\n * @category incoming\n */\nexport class IncomingRequest<R extends Rpc.Any> extends Data.TaggedClass(\"IncomingRequest\")<{\n  readonly envelope: Envelope.Request.PartialEncoded\n  readonly lastSentReply: Option.Option<Reply.ReplyEncoded<R>>\n  readonly respond: (reply: Reply.ReplyWithContext<R>) => Effect.Effect<void, MalformedMessage | PersistenceError>\n}> {}\n\n/**\n * @since 1.0.0\n * @category outgoing\n */\nexport class IncomingRequestLocal<R extends Rpc.Any> extends Data.TaggedClass(\"IncomingRequestLocal\")<{\n  readonly envelope: Envelope.Request<R>\n  readonly lastSentReply: Option.Option<Reply.Reply<R>>\n  readonly respond: (reply: Reply.Reply<R>) => Effect.Effect<void, MalformedMessage | PersistenceError>\n}> {}\n\n/**\n * @since 1.0.0\n * @category incoming\n */\nexport class IncomingEnvelope extends Data.TaggedClass(\"IncomingEnvelope\")<{\n  readonly _tag: \"IncomingEnvelope\"\n  readonly envelope: Envelope.AckChunk | Envelope.Interrupt\n}> {}\n\n/**\n * @since 1.0.0\n * @category outgoing\n */\nexport type Outgoing<R extends Rpc.Any> = OutgoingRequest<R> | OutgoingEnvelope\n\n/**\n * @since 1.0.0\n * @category outgoing\n */\nexport class OutgoingRequest<R extends Rpc.Any> extends Data.TaggedClass(\"OutgoingRequest\")<{\n  readonly envelope: Envelope.Request<R>\n  readonly context: Context<Rpc.Context<R>>\n  readonly lastReceivedReply: Option.Option<Reply.Reply<R>>\n  readonly rpc: R\n  readonly respond: (reply: Reply.Reply<R>) => Effect.Effect<void>\n}> {\n  /**\n   * @since 1.0.0\n   */\n  public encodedCache?: Envelope.Request.PartialEncoded\n}\n\n/**\n * @since 1.0.0\n * @category outgoing\n */\nexport class OutgoingEnvelope extends Data.TaggedClass(\"OutgoingEnvelope\")<{\n  readonly envelope: Envelope.AckChunk | Envelope.Interrupt\n  readonly rpc: Rpc.AnyWithProps\n}> {\n  /**\n   * @since 1.0.0\n   */\n  static interrupt(options: {\n    readonly address: EntityAddress\n    readonly id: Snowflake\n    readonly requestId: Snowflake\n  }): OutgoingEnvelope {\n    return new OutgoingEnvelope({\n      envelope: new Envelope.Interrupt(options),\n      rpc: neverRpc\n    })\n  }\n}\n\nconst neverRpc = Rpc.make(\"Never\", {\n  success: Schema.Never as any,\n  error: Schema.Never,\n  payload: {}\n})\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const serialize = <Rpc extends Rpc.Any>(\n  message: Outgoing<Rpc>\n): Effect.Effect<Envelope.Envelope.PartialEncoded, MalformedMessage> => {\n  if (message._tag !== \"OutgoingRequest\") {\n    return Effect.succeed(message.envelope)\n  }\n  return Effect.suspend(() =>\n    message.encodedCache\n      ? Effect.succeed(message.encodedCache)\n      : serializeRequest(message)\n  )\n}\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const serializeEnvelope = <Rpc extends Rpc.Any>(\n  message: Outgoing<Rpc>\n): Effect.Effect<Envelope.Envelope.Encoded, MalformedMessage> =>\n  Effect.flatMap(\n    serialize(message),\n    (envelope) => MalformedMessage.refail(Schema.encode(Envelope.PartialEncoded)(envelope))\n  )\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const serializeRequest = <Rpc extends Rpc.Any>(\n  self: OutgoingRequest<Rpc>\n): Effect.Effect<Envelope.Request.PartialEncoded, MalformedMessage> => {\n  const rpc = self.rpc as any as Rpc.AnyWithProps\n  return Schema.encode(rpc.payloadSchema)(self.envelope.payload).pipe(\n    Effect.locally(FiberRef.currentContext, self.context),\n    MalformedMessage.refail,\n    Effect.map((payload) => ({\n      ...self.envelope,\n      payload\n    }))\n  ) as any as Effect.Effect<Envelope.Request.PartialEncoded, MalformedMessage>\n}\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const deserializeLocal = <Rpc extends Rpc.Any>(\n  self: Outgoing<Rpc>,\n  encoded: Envelope.Envelope.PartialEncoded\n): Effect.Effect<\n  IncomingLocal<Rpc>,\n  MalformedMessage\n> => {\n  if (encoded._tag !== \"Request\") {\n    return Effect.succeed(new IncomingEnvelope({ envelope: encoded }))\n  } else if (self._tag !== \"OutgoingRequest\") {\n    return Effect.fail(\n      new MalformedMessage({ cause: new Error(\"Can only deserialize a Request with an OutgoingRequest message\") })\n    )\n  }\n  const rpc = self.rpc as any as Rpc.AnyWithProps\n  return Schema.decode(rpc.payloadSchema)(encoded.payload).pipe(\n    Effect.locally(FiberRef.currentContext, self.context),\n    MalformedMessage.refail,\n    Effect.map((payload) =>\n      new IncomingRequestLocal({\n        envelope: Envelope.makeRequest({\n          ...encoded,\n          payload\n        } as any),\n        lastSentReply: Option.none(),\n        respond: self.respond\n      })\n    )\n  ) as Effect.Effect<IncomingRequestLocal<Rpc>, MalformedMessage>\n}\n"
  },
  {
    "path": "packages/cluster/src/MessageStorage.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Rpc from \"@effect/rpc/Rpc\"\nimport * as Arr from \"effect/Array\"\nimport * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport { globalValue } from \"effect/GlobalValue\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport type { Predicate } from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type { PersistenceError } from \"./ClusterError.js\"\nimport { EntityNotAssignedToRunner, MalformedMessage } from \"./ClusterError.js\"\nimport * as DeliverAt from \"./DeliverAt.js\"\nimport type { EntityAddress } from \"./EntityAddress.js\"\nimport * as Envelope from \"./Envelope.js\"\nimport * as Message from \"./Message.js\"\nimport * as Reply from \"./Reply.js\"\nimport type { ShardId } from \"./ShardId.js\"\nimport type { ShardingConfig } from \"./ShardingConfig.js\"\nimport * as Snowflake from \"./Snowflake.js\"\n\n/**\n * @since 1.0.0\n * @category context\n */\nexport class MessageStorage extends Context.Tag(\"@effect/cluster/MessageStorage\")<MessageStorage, {\n  /**\n   * Save the provided message and its associated metadata.\n   */\n  readonly saveRequest: <R extends Rpc.Any>(\n    envelope: Message.OutgoingRequest<R>\n  ) => Effect.Effect<SaveResult<R>, PersistenceError | MalformedMessage>\n\n  /**\n   * Save the provided message and its associated metadata.\n   */\n  readonly saveEnvelope: (\n    envelope: Message.OutgoingEnvelope\n  ) => Effect.Effect<void, PersistenceError | MalformedMessage>\n\n  /**\n   * Save the provided `Reply` and its associated metadata.\n   */\n  readonly saveReply: <R extends Rpc.Any>(\n    reply: Reply.ReplyWithContext<R>\n  ) => Effect.Effect<void, PersistenceError | MalformedMessage>\n\n  /**\n   * Clear the `Reply`s for the given request id.\n   */\n  readonly clearReplies: (requestId: Snowflake.Snowflake) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Retrieves the replies for the specified requests.\n   *\n   * - Un-acknowledged chunk replies\n   * - WithExit replies\n   */\n  readonly repliesFor: <R extends Rpc.Any>(\n    requests: Iterable<Message.OutgoingRequest<R>>\n  ) => Effect.Effect<Array<Reply.Reply<R>>, PersistenceError | MalformedMessage>\n\n  /**\n   * Retrieves the encoded replies for the specified request ids.\n   */\n  readonly repliesForUnfiltered: <R extends Rpc.Any>(\n    requestIds: Iterable<Snowflake.Snowflake>\n  ) => Effect.Effect<Array<Reply.ReplyEncoded<R>>, PersistenceError | MalformedMessage>\n\n  /**\n   * Retrieves the request id for the specified primary key.\n   */\n  readonly requestIdForPrimaryKey: (\n    options: {\n      readonly address: EntityAddress\n      readonly tag: string\n      readonly id: string\n    }\n  ) => Effect.Effect<Option.Option<Snowflake.Snowflake>, PersistenceError>\n\n  /**\n   * For locally sent messages, register a handler to process the replies.\n   */\n  readonly registerReplyHandler: <R extends Rpc.Any>(\n    message: Message.OutgoingRequest<R> | Message.IncomingRequest<R>\n  ) => Effect.Effect<void, EntityNotAssignedToRunner>\n\n  /**\n   * Unregister the reply handler for the specified message.\n   */\n  readonly unregisterReplyHandler: (requestId: Snowflake.Snowflake) => Effect.Effect<void>\n\n  /**\n   * Unregister the reply handlers for the specified ShardId.\n   */\n  readonly unregisterShardReplyHandlers: (shardId: ShardId) => Effect.Effect<void>\n\n  /**\n   * Retrieves the unprocessed messages for the specified shards.\n   *\n   * A message is unprocessed when:\n   *\n   * - Requests that have no WithExit replies\n   *   - Or they have no unacknowledged chunk replies\n   * - The latest AckChunk envelope\n   * - All Interrupt's for unprocessed requests\n   */\n  readonly unprocessedMessages: (\n    shardIds: Iterable<ShardId>\n  ) => Effect.Effect<Array<Message.Incoming<any>>, PersistenceError>\n\n  /**\n   * Retrieves the unprocessed messages by id.\n   */\n  readonly unprocessedMessagesById: <R extends Rpc.Any>(\n    messageIds: Iterable<Snowflake.Snowflake>\n  ) => Effect.Effect<Array<Message.Incoming<R>>, PersistenceError>\n\n  /**\n   * Reset the mailbox state for the provided shards.\n   */\n  readonly resetShards: (\n    shardIds: Iterable<ShardId>\n  ) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Reset the mailbox state for the provided address.\n   */\n  readonly resetAddress: (\n    address: EntityAddress\n  ) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Clear all messages and replies for the provided address.\n   */\n  readonly clearAddress: (\n    address: EntityAddress\n  ) => Effect.Effect<void, PersistenceError>\n}>() {}\n\n/**\n * @since 1.0.0\n * @category SaveResult\n */\nexport type SaveResult<R extends Rpc.Any> = SaveResult.Success | SaveResult.Duplicate<R>\n\n/**\n * @since 1.0.0\n * @category SaveResult\n */\nexport const SaveResult = Data.taggedEnum<SaveResult.Constructor>()\n\n/**\n * @since 1.0.0\n * @category SaveResult\n */\nexport const SaveResultEncoded = Data.taggedEnum<SaveResult.Encoded>()\n\n/**\n * @since 1.0.0\n * @category SaveResult\n */\nexport declare namespace SaveResult {\n  /**\n   * @since 1.0.0\n   * @category SaveResult\n   */\n  export type Encoded = SaveResult.Success | SaveResult.DuplicateEncoded\n\n  /**\n   * @since 1.0.0\n   * @category SaveResult\n   */\n  export interface Success {\n    readonly _tag: \"Success\"\n  }\n\n  /**\n   * @since 1.0.0\n   * @category SaveResult\n   */\n  export interface Duplicate<R extends Rpc.Any> {\n    readonly _tag: \"Duplicate\"\n    readonly originalId: Snowflake.Snowflake\n    readonly lastReceivedReply: Option.Option<Reply.Reply<R>>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category SaveResult\n   */\n  export interface DuplicateEncoded {\n    readonly _tag: \"Duplicate\"\n    readonly originalId: Snowflake.Snowflake\n    readonly lastReceivedReply: Option.Option<Reply.ReplyEncoded<any>>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category SaveResult\n   */\n  export interface Constructor extends Data.TaggedEnum.WithGenerics<1> {\n    readonly taggedEnum: SaveResult<this[\"A\"] extends Rpc.Any ? this[\"A\"] : never>\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Encoded\n */\nexport type Encoded = {\n  /**\n   * Save the provided message and its associated metadata.\n   */\n  readonly saveEnvelope: (\n    options: {\n      readonly envelope: Envelope.Envelope.Encoded\n      readonly primaryKey: string | null\n      readonly deliverAt: number | null\n    }\n  ) => Effect.Effect<SaveResult.Encoded, PersistenceError>\n\n  /**\n   * Save the provided `Reply` and its associated metadata.\n   */\n  readonly saveReply: (\n    reply: Reply.ReplyEncoded<any>\n  ) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Remove the replies for the specified request.\n   */\n  readonly clearReplies: (requestId: Snowflake.Snowflake) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Retrieves the request id for the specified primary key.\n   */\n  readonly requestIdForPrimaryKey: (\n    primaryKey: string\n  ) => Effect.Effect<Option.Option<Snowflake.Snowflake>, PersistenceError>\n\n  /**\n   * Retrieves the replies for the specified requests.\n   *\n   * - Un-acknowledged chunk replies\n   * - WithExit replies\n   */\n  readonly repliesFor: (requestIds: Arr.NonEmptyArray<string>) => Effect.Effect<\n    Array<Reply.ReplyEncoded<any>>,\n    PersistenceError\n  >\n\n  /**\n   * Retrieves the replies for the specified request ids.\n   */\n  readonly repliesForUnfiltered: (requestIds: Arr.NonEmptyArray<string>) => Effect.Effect<\n    Array<Reply.ReplyEncoded<any>>,\n    PersistenceError\n  >\n\n  /**\n   * Retrieves the unprocessed messages for the given shards.\n   *\n   * A message is unprocessed when:\n   *\n   * - Requests that have no WithExit replies\n   *   - Or they have no unacknowledged chunk replies\n   * - The latest AckChunk envelope\n   * - All Interrupt's for unprocessed requests\n   */\n  readonly unprocessedMessages: (\n    shardIds: Arr.NonEmptyArray<string>,\n    now: number\n  ) => Effect.Effect<\n    Array<{\n      readonly envelope: Envelope.Envelope.Encoded\n      readonly lastSentReply: Option.Option<Reply.ReplyEncoded<any>>\n    }>,\n    PersistenceError\n  >\n\n  /**\n   * Retrieves the unprocessed messages by id.\n   */\n  readonly unprocessedMessagesById: (\n    messageIds: Arr.NonEmptyArray<Snowflake.Snowflake>,\n    now: number\n  ) => Effect.Effect<\n    Array<{\n      readonly envelope: Envelope.Envelope.Encoded\n      readonly lastSentReply: Option.Option<Reply.ReplyEncoded<any>>\n    }>,\n    PersistenceError\n  >\n\n  /**\n   * Reset the mailbox state for the provided address.\n   */\n  readonly resetAddress: (\n    address: EntityAddress\n  ) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Clear all messages and replies for the provided address.\n   */\n  readonly clearAddress: (\n    address: EntityAddress\n  ) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Reset the mailbox state for the provided shards.\n   */\n  readonly resetShards: (\n    shardIds: Arr.NonEmptyArray<string>\n  ) => Effect.Effect<void, PersistenceError>\n}\n\n/**\n * @since 1.0.0\n * @category Encoded\n */\nexport type EncodedUnprocessedOptions<A> = {\n  readonly existingShards: Array<number>\n  readonly newShards: Array<number>\n  readonly cursor: Option.Option<A>\n}\n\n/**\n * @since 1.0.0\n * @category Encoded\n */\nexport type EncodedRepliesOptions<A> = {\n  readonly existingRequests: Array<string>\n  readonly newRequests: Array<string>\n  readonly cursor: Option.Option<A>\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = (\n  storage: Omit<\n    MessageStorage[\"Type\"],\n    \"registerReplyHandler\" | \"unregisterReplyHandler\" | \"unregisterShardReplyHandlers\"\n  >\n): Effect.Effect<MessageStorage[\"Type\"]> =>\n  Effect.sync(() => {\n    type ReplyHandler = {\n      readonly message: Message.OutgoingRequest<any> | Message.IncomingRequest<any>\n      readonly shardSet: Set<ReplyHandler>\n      readonly respond: (reply: Reply.ReplyWithContext<any>) => Effect.Effect<void, PersistenceError | MalformedMessage>\n      readonly resume: (effect: Effect.Effect<void, EntityNotAssignedToRunner>) => void\n    }\n    const replyHandlers = new Map<Snowflake.Snowflake, Array<ReplyHandler>>()\n    const replyHandlersShard = new Map<string, Set<ReplyHandler>>()\n    return MessageStorage.of({\n      ...storage,\n      registerReplyHandler: (message) => {\n        const requestId = message.envelope.requestId\n        return Effect.async<void, EntityNotAssignedToRunner>((resume) => {\n          const shardId = message.envelope.address.shardId.toString()\n          let handlers = replyHandlers.get(requestId)\n          if (handlers === undefined) {\n            handlers = []\n            replyHandlers.set(requestId, handlers)\n          }\n          let shardSet = replyHandlersShard.get(shardId)\n          if (!shardSet) {\n            shardSet = new Set()\n            replyHandlersShard.set(shardId, shardSet)\n          }\n          const entry: ReplyHandler = {\n            message,\n            shardSet,\n            respond: message._tag === \"IncomingRequest\" ? message.respond : (reply) => message.respond(reply.reply),\n            resume\n          }\n          handlers.push(entry)\n          shardSet.add(entry)\n          return Effect.sync(() => {\n            const index = handlers.indexOf(entry)\n            handlers.splice(index, 1)\n            shardSet.delete(entry)\n          })\n        })\n      },\n      unregisterReplyHandler: (requestId) =>\n        Effect.sync(() => {\n          const handlers = replyHandlers.get(requestId)\n          if (!handlers) return Effect.void\n          replyHandlers.delete(requestId)\n          for (let i = 0; i < handlers.length; i++) {\n            const handler = handlers[i]\n            handler.shardSet.delete(handler)\n            handler.resume(Effect.fail(\n              new EntityNotAssignedToRunner({\n                address: handler.message.envelope.address\n              })\n            ))\n          }\n        }),\n      unregisterShardReplyHandlers: (shardId) =>\n        Effect.sync(() => {\n          const id = shardId.toString()\n          const shardSet = replyHandlersShard.get(id)\n          if (!shardSet) return\n          replyHandlersShard.delete(id)\n          shardSet.forEach((handler) => {\n            replyHandlers.delete(handler.message.envelope.requestId)\n            handler.resume(Effect.fail(\n              new EntityNotAssignedToRunner({\n                address: handler.message.envelope.address\n              })\n            ))\n          })\n        }),\n      saveReply(reply) {\n        const requestId = reply.reply.requestId\n        return Effect.flatMap(storage.saveReply(reply), () => {\n          const handlers = replyHandlers.get(requestId)\n          if (!handlers) {\n            return Effect.void\n          } else if (reply.reply._tag === \"WithExit\") {\n            replyHandlers.delete(requestId)\n            for (let i = 0; i < handlers.length; i++) {\n              const handler = handlers[i]\n              handler.shardSet.delete(handler)\n              handler.resume(Effect.void)\n            }\n          }\n          return handlers.length === 1\n            ? handlers[0].respond(reply)\n            : Effect.forEach(handlers, (handler) => handler.respond(reply))\n        })\n      }\n    })\n  })\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeEncoded: (encoded: Encoded) => Effect.Effect<\n  MessageStorage[\"Type\"],\n  never,\n  Snowflake.Generator\n> = Effect.fnUntraced(function*(encoded: Encoded) {\n  const snowflakeGen = yield* Snowflake.Generator\n  const clock = yield* Effect.clock\n\n  const storage: MessageStorage[\"Type\"] = yield* make({\n    saveRequest: (message) =>\n      Message.serializeEnvelope(message).pipe(\n        Effect.flatMap((envelope) =>\n          encoded.saveEnvelope({\n            envelope,\n            primaryKey: Envelope.primaryKey(message.envelope),\n            deliverAt: DeliverAt.toMillis(message.envelope.payload)\n          })\n        ),\n        Effect.flatMap((result) => {\n          if (result._tag === \"Success\" || result.lastReceivedReply._tag === \"None\") {\n            return Effect.succeed(result as SaveResult<any>)\n          }\n          const duplicate = result\n          const schema = Reply.Reply(message.rpc)\n          return Schema.decode(schema)(result.lastReceivedReply.value).pipe(\n            Effect.locally(FiberRef.currentContext, message.context),\n            MalformedMessage.refail,\n            Effect.map((reply) =>\n              SaveResult.Duplicate({\n                originalId: duplicate.originalId,\n                lastReceivedReply: Option.some(reply)\n              })\n            )\n          )\n        })\n      ),\n    saveEnvelope: (message) =>\n      Message.serializeEnvelope(message).pipe(\n        Effect.flatMap((envelope) =>\n          encoded.saveEnvelope({\n            envelope,\n            primaryKey: null,\n            deliverAt: null\n          })\n        ),\n        Effect.asVoid\n      ),\n    saveReply: (reply) => Effect.flatMap(Reply.serialize(reply), encoded.saveReply),\n    clearReplies: encoded.clearReplies,\n    repliesFor: Effect.fnUntraced(function*(messages) {\n      const requestIds = Arr.empty<string>()\n      const map = new Map<string, Message.OutgoingRequest<any>>()\n      for (const message of messages) {\n        const id = String(message.envelope.requestId)\n        requestIds.push(id)\n        map.set(id, message)\n      }\n      if (!Arr.isNonEmptyArray(requestIds)) return []\n      const encodedReplies = yield* encoded.repliesFor(requestIds)\n      return yield* decodeReplies(map, encodedReplies)\n    }),\n    repliesForUnfiltered: (ids) => {\n      const requestIds = Array.from(ids, String)\n      return Arr.isNonEmptyArray(requestIds)\n        ? encoded.repliesForUnfiltered(requestIds)\n        : Effect.succeed([])\n    },\n    requestIdForPrimaryKey(options) {\n      const primaryKey = Envelope.primaryKeyByAddress(options)\n      return encoded.requestIdForPrimaryKey(primaryKey)\n    },\n    unprocessedMessages: (shardIds) => {\n      const shards = Array.from(shardIds, (id) => id.toString())\n      if (!Arr.isNonEmptyArray(shards)) return Effect.succeed([])\n      return Effect.flatMap(\n        Effect.suspend(() => encoded.unprocessedMessages(shards, clock.unsafeCurrentTimeMillis())),\n        decodeMessages\n      )\n    },\n    unprocessedMessagesById(messageIds) {\n      const ids = Array.from(messageIds)\n      if (!Arr.isNonEmptyArray(ids)) return Effect.succeed([])\n      return Effect.flatMap(\n        Effect.suspend(() => encoded.unprocessedMessagesById(ids, clock.unsafeCurrentTimeMillis())),\n        decodeMessages\n      )\n    },\n    resetAddress: encoded.resetAddress,\n    clearAddress: encoded.clearAddress,\n    resetShards: (shardIds) => {\n      const shards = Array.from(shardIds, (id) => id.toString())\n      return Arr.isNonEmptyArray(shards)\n        ? encoded.resetShards(shards)\n        : Effect.void\n    }\n  })\n\n  const decodeMessages = (\n    envelopes: Array<{\n      readonly envelope: Envelope.Envelope.Encoded\n      readonly lastSentReply: Option.Option<Reply.ReplyEncoded<any>>\n    }>\n  ) => {\n    const messages: Array<Message.Incoming<any>> = []\n    let index = 0\n\n    // if we have a malformed message, we should not return it and update\n    // the storage with a defect\n    const decodeMessage = Effect.catchAll(\n      Effect.suspend(() => {\n        const envelope = envelopes[index]\n        if (!envelope) return Effect.succeed(undefined)\n        return decodeEnvelopeWithReply(envelope)\n      }),\n      (error) => {\n        const envelope = envelopes[index]\n        return storage.saveReply(Reply.ReplyWithContext.fromDefect({\n          id: snowflakeGen.unsafeNext(),\n          requestId: Snowflake.Snowflake(envelope.envelope.requestId),\n          defect: error.toString()\n        })).pipe(\n          Effect.forkDaemon,\n          Effect.asVoid\n        )\n      }\n    )\n    return Effect.as(\n      Effect.whileLoop({\n        while: () => index < envelopes.length,\n        body: () => decodeMessage,\n        step: (message) => {\n          const envelope = envelopes[index++]\n          if (!message) return\n          messages.push(\n            message.envelope._tag === \"Request\"\n              ? new Message.IncomingRequest({\n                envelope: message.envelope,\n                lastSentReply: envelope.lastSentReply,\n                respond: storage.saveReply\n              })\n              : new Message.IncomingEnvelope({\n                envelope: message.envelope\n              })\n          )\n        }\n      }),\n      messages\n    )\n  }\n\n  const decodeReplies = (\n    messages: Map<string, Message.OutgoingRequest<any>>,\n    encodedReplies: Array<Reply.ReplyEncoded<any>>\n  ) => {\n    const replies: Array<Reply.Reply<any>> = []\n    const ignoredRequests = new Set<string>()\n    let index = 0\n\n    const decodeReply: Effect.Effect<void | Reply.Reply<any>> = Effect.catchAll(\n      Effect.suspend(() => {\n        const reply = encodedReplies[index]\n        if (ignoredRequests.has(reply.requestId)) return Effect.void\n        const message = messages.get(reply.requestId)\n        if (!message) return Effect.void\n        const schema = Reply.Reply(message.rpc)\n        return Schema.decode(schema)(reply).pipe(\n          Effect.locally(FiberRef.currentContext, message.context)\n        ) as Effect.Effect<Reply.Reply<any>, ParseError>\n      }),\n      (error) => {\n        const reply = encodedReplies[index]\n        ignoredRequests.add(reply.requestId)\n        return Effect.succeed(\n          new Reply.WithExit({\n            id: snowflakeGen.unsafeNext(),\n            requestId: Snowflake.Snowflake(reply.requestId),\n            exit: Exit.die(error)\n          })\n        )\n      }\n    )\n\n    return Effect.as(\n      Effect.whileLoop({\n        while: () => index < encodedReplies.length,\n        body: () => decodeReply,\n        step: (reply) => {\n          index++\n          if (reply) replies.push(reply)\n        }\n      }),\n      replies\n    )\n  }\n\n  return storage\n})\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const noop: MessageStorage[\"Type\"] = globalValue(\n  \"@effect/cluster/MessageStorage/noop\",\n  () =>\n    Effect.runSync(make({\n      saveRequest: () => Effect.succeed(SaveResult.Success()),\n      saveEnvelope: () => Effect.void,\n      saveReply: () => Effect.void,\n      clearReplies: () => Effect.void,\n      repliesFor: () => Effect.succeed([]),\n      repliesForUnfiltered: () => Effect.succeed([]),\n      requestIdForPrimaryKey: () => Effect.succeedNone,\n      unprocessedMessages: () => Effect.succeed([]),\n      unprocessedMessagesById: () => Effect.succeed([]),\n      resetAddress: () => Effect.void,\n      clearAddress: () => Effect.void,\n      resetShards: () => Effect.void\n    }))\n)\n\n/**\n * @since 1.0.0\n * @category Memory\n */\nexport type MemoryEntry = {\n  readonly envelope: Envelope.Request.Encoded\n  lastReceivedChunk: Option.Option<Reply.ChunkEncoded<any>>\n  replies: Array<Reply.ReplyEncoded<any>>\n  deliverAt: number | null\n}\n\n/**\n * @since 1.0.0\n * @category Memory\n */\nexport class MemoryDriver extends Effect.Service<MemoryDriver>()(\"@effect/cluster/MessageStorage/MemoryDriver\", {\n  dependencies: [Snowflake.layerGenerator],\n  effect: Effect.gen(function*() {\n    const clock = yield* Effect.clock\n    const requests = new Map<string, MemoryEntry>()\n    const requestsByPrimaryKey = new Map<string, MemoryEntry>()\n    const unprocessed = new Set<Envelope.Envelope.Encoded>()\n    const replyIds = new Set<string>()\n\n    const journal: Array<Envelope.Envelope.Encoded> = []\n\n    const cursors = new WeakMap<{}, number>()\n\n    const unprocessedWith = (predicate: Predicate<Envelope.Envelope.Encoded>) => {\n      const messages: Array<{\n        readonly envelope: Envelope.Envelope.Encoded\n        readonly lastSentReply: Option.Option<Reply.ReplyEncoded<any>>\n      }> = []\n      const now = clock.unsafeCurrentTimeMillis()\n      for (const envelope of unprocessed) {\n        if (!predicate(envelope)) {\n          continue\n        }\n        if (envelope._tag === \"Request\") {\n          const entry = requests.get(envelope.requestId)\n          if (entry?.deliverAt && entry.deliverAt > now) {\n            continue\n          }\n          messages.push({\n            envelope,\n            lastSentReply: Option.fromNullable(entry?.replies[entry.replies.length - 1])\n          })\n        } else {\n          messages.push({\n            envelope,\n            lastSentReply: Option.none()\n          })\n        }\n      }\n      return messages\n    }\n\n    const replyLatch = yield* Effect.makeLatch()\n\n    function repliesFor(requestIds: Array<string>) {\n      const replies = Arr.empty<Reply.ReplyEncoded<any>>()\n      for (const requestId of requestIds) {\n        const request = requests.get(requestId)\n        if (!request) continue\n        else if (Option.isNone(request.lastReceivedChunk)) {\n          // eslint-disable-next-line no-restricted-syntax\n          replies.push(...request.replies)\n          continue\n        }\n        const sequence = request.lastReceivedChunk.value.sequence\n        for (const reply of request.replies) {\n          if (reply._tag === \"Chunk\" && reply.sequence <= sequence) {\n            continue\n          }\n          replies.push(reply)\n        }\n      }\n      return replies\n    }\n\n    const encoded: Encoded = {\n      saveEnvelope: ({ deliverAt, envelope: envelope_, primaryKey }) =>\n        Effect.sync(() => {\n          const envelope = JSON.parse(JSON.stringify(envelope_)) as Envelope.Envelope.Encoded\n          const existing = primaryKey\n            ? requestsByPrimaryKey.get(primaryKey)\n            : envelope._tag === \"Request\" && requests.get(envelope.requestId)\n          if (existing) {\n            return SaveResultEncoded.Duplicate({\n              originalId: Snowflake.Snowflake(existing.envelope.requestId),\n              lastReceivedReply: existing.replies.length === 1 && existing.replies[0]._tag === \"WithExit\"\n                ? Option.some(existing.replies[0])\n                : existing.lastReceivedChunk\n            })\n          }\n          if (envelope._tag === \"Request\") {\n            const entry: MemoryEntry = { envelope, replies: [], lastReceivedChunk: Option.none(), deliverAt }\n            requests.set(envelope.requestId, entry)\n            if (primaryKey) {\n              requestsByPrimaryKey.set(primaryKey, entry)\n            }\n          } else if (envelope._tag === \"AckChunk\") {\n            const entry = requests.get(envelope.requestId)\n            if (entry) {\n              entry.lastReceivedChunk = Arr.findFirst(\n                entry.replies,\n                (r): r is Reply.ChunkEncoded<any> => r._tag === \"Chunk\" && r.id === envelope.replyId\n              ).pipe(Option.orElse(() => entry.lastReceivedChunk))\n            }\n          }\n          unprocessed.add(envelope)\n          journal.push(envelope)\n          return SaveResultEncoded.Success()\n        }),\n      saveReply: (reply_) =>\n        Effect.sync(() => {\n          const reply = JSON.parse(JSON.stringify(reply_)) as Reply.ReplyEncoded<any>\n          const entry = requests.get(reply.requestId)\n          if (!entry || replyIds.has(reply.id)) return\n          if (reply._tag === \"WithExit\") {\n            unprocessed.delete(entry.envelope)\n          }\n          entry.replies.push(reply)\n          replyIds.add(reply.id)\n          replyLatch.unsafeOpen()\n        }),\n      clearReplies: (id) =>\n        Effect.sync(() => {\n          const entry = requests.get(String(id))\n          if (!entry) return\n          entry.replies = []\n          entry.lastReceivedChunk = Option.none()\n          unprocessed.add(entry.envelope)\n        }),\n      requestIdForPrimaryKey: (primaryKey) =>\n        Effect.sync(() => {\n          const entry = requestsByPrimaryKey.get(primaryKey)\n          return Option.fromNullable(entry?.envelope.requestId).pipe(Option.map(Snowflake.Snowflake))\n        }),\n      repliesFor: (requestIds) => Effect.sync(() => repliesFor(requestIds)),\n      repliesForUnfiltered: (requestIds) =>\n        Effect.sync(() => requestIds.flatMap((id) => requests.get(String(id))?.replies ?? [])),\n      unprocessedMessages: (shardIds) =>\n        Effect.sync(() => {\n          if (unprocessed.size === 0) return []\n          const now = clock.unsafeCurrentTimeMillis()\n          const messages = Arr.empty<{\n            envelope: Envelope.Envelope.Encoded\n            lastSentReply: Option.Option<Reply.ReplyEncoded<any>>\n          }>()\n          for (let index = 0; index < journal.length; index++) {\n            const envelope = journal[index]\n            const shardId = envelope.address.shardId\n            const shardIdStr = `${shardId.group}:${shardId.id}`\n            if (!unprocessed.has(envelope as any) || !shardIds.includes(shardIdStr)) {\n              continue\n            }\n            if (envelope._tag === \"Request\") {\n              const entry = requests.get(envelope.requestId)!\n              if (entry.deliverAt && entry.deliverAt > now) {\n                continue\n              }\n              messages.push({\n                envelope,\n                lastSentReply: Arr.last(entry.replies)\n              })\n            } else {\n              messages.push({\n                envelope,\n                lastSentReply: Option.none()\n              })\n              unprocessed.delete(envelope)\n            }\n          }\n          return messages\n        }),\n      unprocessedMessagesById: (ids) =>\n        Effect.sync(() => {\n          const envelopeIds = new Set<string>()\n          for (const id of ids) {\n            envelopeIds.add(String(id))\n          }\n          return unprocessedWith((envelope) => envelopeIds.has(envelope.requestId))\n        }),\n      resetAddress: () => Effect.void,\n      clearAddress: (address) =>\n        Effect.sync(() => {\n          for (let i = journal.length - 1; i >= 0; i--) {\n            const envelope = journal[i]\n            const sameAddress = address.entityType === envelope.address.entityType &&\n              address.entityId === envelope.address.entityId\n            if (!sameAddress || envelope._tag !== \"Request\") {\n              continue\n            }\n            unprocessed.delete(envelope)\n            requests.delete(envelope.requestId)\n            journal.splice(i, 1)\n          }\n        }),\n      resetShards: () => Effect.void\n    }\n\n    const storage = yield* makeEncoded(encoded)\n\n    return {\n      storage,\n      encoded,\n      requests,\n      requestsByPrimaryKey,\n      unprocessed,\n      replyIds,\n      journal,\n      cursors\n    } as const\n  })\n}) {}\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerNoop: Layer.Layer<MessageStorage> = Layer.succeed(MessageStorage, noop)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerMemory: Layer.Layer<\n  MessageStorage | MemoryDriver,\n  never,\n  ShardingConfig\n> = Layer.effect(MessageStorage, Effect.map(MemoryDriver, (_) => _.storage)).pipe(\n  Layer.provideMerge(MemoryDriver.Default)\n)\n\n// --- internal ---\n\nconst EnvelopeWithReply: Schema.Schema<{\n  readonly envelope: Envelope.Envelope.PartialEncoded\n  readonly lastSentReply: Option.Option<Reply.ReplyEncoded<any>>\n}, {\n  readonly envelope: Envelope.Envelope.Encoded\n  readonly lastSentReply: Schema.OptionEncoded<Reply.ReplyEncoded<any>>\n}> = Schema.Struct({\n  envelope: Envelope.PartialEncoded,\n  lastSentReply: Schema.OptionFromSelf(Reply.Encoded)\n}) as any\n\nconst decodeEnvelopeWithReply = Schema.decode(EnvelopeWithReply)\n"
  },
  {
    "path": "packages/cluster/src/Reply.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Rpc from \"@effect/rpc/Rpc\"\nimport type * as RpcSchema from \"@effect/rpc/RpcSchema\"\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as FiberId from \"effect/FiberId\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport { identity } from \"effect/Function\"\nimport type * as Option from \"effect/Option\"\nimport { hasProperty } from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport { MalformedMessage } from \"./ClusterError.js\"\nimport type { OutgoingRequest } from \"./Message.js\"\nimport { Snowflake, SnowflakeFromString } from \"./Snowflake.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/cluster/Reply\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isReply = (u: unknown): u is Reply<Rpc.Any> => hasProperty(u, TypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Reply<R extends Rpc.Any> = WithExit<R> | Chunk<R>\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport class ReplyWithContext<R extends Rpc.Any> extends Data.TaggedClass(\"ReplyWithContext\")<{\n  readonly reply: Reply<R>\n  readonly context: Context.Context<Rpc.Context<R>>\n  readonly rpc: R\n}> {\n  /**\n   * @since 1.0.0\n   */\n  static fromDefect(options: {\n    readonly id: Snowflake\n    readonly requestId: Snowflake\n    readonly defect: unknown\n  }): ReplyWithContext<any> {\n    return new ReplyWithContext({\n      reply: new WithExit({\n        requestId: options.requestId,\n        id: options.id,\n        exit: Exit.die(Schema.encodeSync(Schema.Defect)(options.defect))\n      }),\n      context: Context.empty() as any,\n      rpc: neverRpc\n    })\n  }\n  /**\n   * @since 1.0.0\n   */\n  static interrupt(options: {\n    readonly id: Snowflake\n    readonly requestId: Snowflake\n  }): ReplyWithContext<any> {\n    return new ReplyWithContext({\n      reply: new WithExit({\n        requestId: options.requestId,\n        id: options.id,\n        exit: Exit.interrupt(FiberId.none)\n      }),\n      context: Context.empty() as any,\n      rpc: neverRpc\n    })\n  }\n}\n\nconst neverRpc = Rpc.make(\"Never\", {\n  success: Schema.Never as any,\n  error: Schema.Never,\n  payload: {}\n})\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type ReplyEncoded<R extends Rpc.Any> = WithExitEncoded<R> | ChunkEncoded<R>\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface WithExitEncoded<R extends Rpc.Any> {\n  readonly _tag: \"WithExit\"\n  readonly requestId: string\n  readonly id: string\n  readonly exit: Rpc.ExitEncoded<R>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface ChunkEncoded<R extends Rpc.Any> {\n  readonly _tag: \"Chunk\"\n  readonly requestId: string\n  readonly id: string\n  readonly sequence: number\n  readonly values: NonEmptyReadonlyArray<Rpc.SuccessChunkEncoded<R>>\n}\n\nconst schemaCache = new WeakMap<Rpc.Any, Schema.Schema<Reply<Rpc.Any>, ReplyEncoded<Rpc.Any>, Rpc.Context<Rpc.Any>>>()\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Reply = <R extends Rpc.Any>(rpc: R): Schema.Schema<\n  Reply<R>,\n  ReplyEncoded<R>,\n  Rpc.Context<R>\n> => {\n  if (schemaCache.has(rpc)) {\n    return schemaCache.get(rpc) as any\n  }\n  const schema = Schema.Union(WithExit.schema(rpc), Chunk.schema(rpc))\n  schemaCache.set(rpc, schema)\n  return schema\n}\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Encoded = Schema.Union(\n  Schema.Struct({\n    _tag: Schema.Literal(\"WithExit\"),\n    requestId: Schema.String,\n    id: Schema.String,\n    exit: Schema.Unknown\n  }),\n  Schema.Struct({\n    _tag: Schema.Literal(\"Chunk\"),\n    requestId: Schema.String,\n    id: Schema.String,\n    sequence: Schema.Number,\n    values: Schema.Array(Schema.Unknown)\n  })\n)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport class Chunk<R extends Rpc.Any> extends Data.TaggedClass(\"Chunk\")<{\n  readonly requestId: Snowflake\n  readonly id: Snowflake\n  readonly sequence: number\n  readonly values: NonEmptyReadonlyArray<Rpc.SuccessChunk<R>>\n}> {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  static emptyFrom(requestId: Snowflake) {\n    return new Chunk({\n      requestId,\n      id: Snowflake(BigInt(0)),\n      sequence: 0,\n      values: [undefined]\n    })\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  static readonly schemaFromSelf: Schema.Schema<Chunk<never>> = Schema.declare(\n    (u): u is Chunk<never> => isReply(u) && u._tag === \"Chunk\",\n    {\n      typeConstructor: { _tag: \"effect/cluster/Reply.Chunk\" }\n    }\n  )\n\n  /**\n   * @since 1.0.0\n   */\n  static schema<R extends Rpc.Any>(rpc: R): Schema.Schema<\n    Chunk<R>,\n    ChunkEncoded<R>,\n    Rpc.Context<R>\n  > {\n    const successSchema = ((rpc as any as Rpc.AnyWithProps).successSchema as RpcSchema.Stream<any, any>).success\n    if (!successSchema) {\n      return Schema.Never as any\n    }\n    return Schema.transform(\n      Schema.Struct({\n        _tag: Schema.Literal(\"Chunk\"),\n        requestId: SnowflakeFromString,\n        id: SnowflakeFromString,\n        sequence: Schema.Number,\n        values: Schema.NonEmptyArray(successSchema)\n      }),\n      Chunk.schemaFromSelf,\n      {\n        decode: (encoded) => new Chunk(encoded as any),\n        encode: identity\n      }\n    ) as any\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  withRequestId(requestId: Snowflake): Chunk<R> {\n    return new Chunk({\n      ...this,\n      requestId\n    })\n  }\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport class WithExit<R extends Rpc.Any> extends Data.TaggedClass(\"WithExit\")<{\n  readonly requestId: Snowflake\n  readonly id: Snowflake\n  readonly exit: Rpc.Exit<R>\n}> {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  static schema<R extends Rpc.Any>(rpc: R): Schema.Schema<\n    WithExit<R>,\n    WithExitEncoded<R>,\n    Rpc.Context<R>\n  > {\n    return Schema.transform(\n      Schema.Struct({\n        _tag: Schema.Literal(\"WithExit\"),\n        requestId: SnowflakeFromString,\n        id: SnowflakeFromString,\n        exit: Rpc.exitSchema(rpc)\n      }),\n      Schema.declare((u): u is WithExit<R> => isReply(u) && u._tag === \"WithExit\"),\n      {\n        decode: (encoded) => new WithExit(encoded),\n        encode: identity\n      }\n    ) as any\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  withRequestId(requestId: Snowflake): WithExit<R> {\n    return new WithExit({\n      ...this,\n      requestId\n    })\n  }\n}\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const serialize = <R extends Rpc.Any>(\n  self: ReplyWithContext<R>\n): Effect.Effect<ReplyEncoded<R>, MalformedMessage> => {\n  const schema = Reply(self.rpc)\n  return MalformedMessage.refail(\n    Effect.locally(Schema.encode(schema)(self.reply), FiberRef.currentContext, self.context)\n  )\n}\n\n/**\n * @since 1.0.0\n * @category serialization / deserialization\n */\nexport const serializeLastReceived = <R extends Rpc.Any>(\n  self: OutgoingRequest<R>\n): Effect.Effect<Option.Option<ReplyEncoded<R>>, MalformedMessage> => {\n  if (self.lastReceivedReply._tag === \"None\") {\n    return Effect.succeedNone\n  }\n  const schema = Reply(self.rpc)\n  return Effect.asSome(MalformedMessage.refail(\n    Effect.locally(Schema.encode(schema)(self.lastReceivedReply.value), FiberRef.currentContext, self.context)\n  ))\n}\n"
  },
  {
    "path": "packages/cluster/src/Runner.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Equal from \"effect/Equal\"\nimport * as Hash from \"effect/Hash\"\nimport { NodeInspectSymbol } from \"effect/Inspectable\"\nimport * as Pretty from \"effect/Pretty\"\nimport * as Schema from \"effect/Schema\"\nimport { RunnerAddress } from \"./RunnerAddress.js\"\n\nconst SymbolKey = \"@effect/cluster/Runner\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(SymbolKey)\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * A `Runner` represents a physical application server that is capable of running\n * entities.\n *\n * Because a Runner represents a physical application server, a Runner must have a\n * unique `address` which can be used to communicate with the server.\n *\n * The version of a Runner is used during rebalancing to give priority to newer\n * application servers and slowly decommission older ones.\n *\n * @since 1.0.0\n * @category models\n */\nexport class Runner extends Schema.Class<Runner>(SymbolKey)({\n  address: RunnerAddress,\n  groups: Schema.Array(Schema.String),\n  weight: Schema.Number\n}) {\n  /**\n   * @since 1.0.0\n   */\n  static pretty = Pretty.make(this)\n\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  static readonly decodeSync = Schema.decodeSync(Schema.parseJson(Runner))\n\n  /**\n   * @since 1.0.0\n   */\n  static readonly encodeSync = Schema.encodeSync(Schema.parseJson(Runner));\n\n  /**\n   * @since 1.0.0\n   */\n  [NodeInspectSymbol](): string {\n    return this.toString()\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  [Equal.symbol](that: Runner): boolean {\n    return this.address[Equal.symbol](that.address) && this.weight === that.weight\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  [Hash.symbol](): number {\n    return Hash.cached(this, Hash.string(`${this.address.toString()}:${this.weight}`))\n  }\n}\n\n/**\n * A `Runner` represents a physical application server that is capable of running\n * entities.\n *\n * Because a Runner represents a physical application server, a Runner must have a\n * unique `address` which can be used to communicate with the server.\n *\n * The version of a Runner is used during rebalancing to give priority to newer\n * application servers and slowly decommission older ones.\n *\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (props: {\n  readonly address: RunnerAddress\n  readonly groups: ReadonlyArray<string>\n  readonly weight: number\n}): Runner => new Runner(props)\n"
  },
  {
    "path": "packages/cluster/src/RunnerAddress.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Equal from \"effect/Equal\"\nimport * as Hash from \"effect/Hash\"\nimport { NodeInspectSymbol } from \"effect/Inspectable\"\nimport * as PrimaryKey from \"effect/PrimaryKey\"\nimport * as Schema from \"effect/Schema\"\n\nconst SymbolKey = \"@effect/cluster/RunnerAddress\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(SymbolKey)\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport class RunnerAddress extends Schema.Class<RunnerAddress>(SymbolKey)({\n  host: Schema.NonEmptyString,\n  port: Schema.Int\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId;\n\n  /**\n   * @since 1.0.0\n   */\n  [PrimaryKey.symbol](): string {\n    return `${this.host}:${this.port}`\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  [Equal.symbol](that: RunnerAddress): boolean {\n    return this.host === that.host && this.port === that.port\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  [Hash.symbol]() {\n    return Hash.cached(this, Hash.string(this.toString()))\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  toString(): string {\n    return `RunnerAddress(${this.host}:${this.port})`\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  [NodeInspectSymbol](): string {\n    return this.toString()\n  }\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = (host: string, port: number): RunnerAddress => new RunnerAddress({ host, port })\n"
  },
  {
    "path": "packages/cluster/src/RunnerHealth.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schedule from \"effect/Schedule\"\nimport type * as Scope from \"effect/Scope\"\nimport * as K8s from \"./K8sHttpClient.js\"\nimport type { RunnerAddress } from \"./RunnerAddress.js\"\nimport * as Runners from \"./Runners.js\"\n\n/**\n * Represents the service used to check if a Runner is healthy.\n *\n * If a Runner is responsive, shards will not be re-assigned because the Runner may\n * still be processing messages. If a Runner is not responsive, then its\n * associated shards can and will be re-assigned to a different Runner.\n *\n * @since 1.0.0\n * @category models\n */\nexport class RunnerHealth extends Context.Tag(\"@effect/cluster/RunnerHealth\")<\n  RunnerHealth,\n  {\n    readonly isAlive: (address: RunnerAddress) => Effect.Effect<boolean>\n  }\n>() {}\n\n/**\n * A layer which will **always** consider a Runner healthy.\n *\n * This is useful for testing.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerNoop = Layer.succeed(RunnerHealth, {\n  isAlive: () => Effect.succeed(true)\n})\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const makePing: Effect.Effect<\n  RunnerHealth[\"Type\"],\n  never,\n  Runners.Runners | Scope.Scope\n> = Effect.gen(function*() {\n  const runners = yield* Runners.Runners\n  const schedule = Schedule.spaced(500)\n\n  function isAlive(address: RunnerAddress): Effect.Effect<boolean> {\n    return runners.ping(address).pipe(\n      Effect.timeout(10_000),\n      Effect.retry({ times: 5, schedule }),\n      Effect.isSuccess\n    )\n  }\n\n  return RunnerHealth.of({ isAlive })\n})\n\n/**\n * A layer which will ping a Runner directly to check if it is healthy.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerPing: Layer.Layer<\n  RunnerHealth,\n  never,\n  Runners.Runners\n> = Layer.scoped(RunnerHealth, makePing)\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const makeK8s = Effect.fnUntraced(function*(options?: {\n  readonly namespace?: string | undefined\n  readonly labelSelector?: string | undefined\n}) {\n  const allPods = yield* K8s.makeGetPods(options)\n\n  return RunnerHealth.of({\n    isAlive: (address) =>\n      allPods.pipe(\n        Effect.map((pods) => pods.get(address.host)?.isReadyOrInitializing ?? false),\n        Effect.catchAllCause(() => Effect.succeed(true))\n      )\n  })\n})\n\n/**\n * A layer which will check the Kubernetes API to see if a Runner is healthy.\n *\n * The provided HttpClient will need to add the pod's CA certificate to its\n * trusted root certificates in order to communicate with the Kubernetes API.\n *\n * The pod service account will also need to have permissions to list pods in\n * order to use this layer.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerK8s = (\n  options?: {\n    readonly namespace?: string | undefined\n    readonly labelSelector?: string | undefined\n  } | undefined\n): Layer.Layer<\n  RunnerHealth,\n  never,\n  K8s.K8sHttpClient\n> => Layer.effect(RunnerHealth, makeK8s(options))\n"
  },
  {
    "path": "packages/cluster/src/RunnerServer.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as RpcServer from \"@effect/rpc/RpcServer\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { constant } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as Option from \"effect/Option\"\nimport * as Runtime from \"effect/Runtime\"\nimport type * as ClusterError from \"./ClusterError.js\"\nimport * as Message from \"./Message.js\"\nimport * as MessageStorage from \"./MessageStorage.js\"\nimport * as Reply from \"./Reply.js\"\nimport * as RunnerHealth from \"./RunnerHealth.js\"\nimport * as Runners from \"./Runners.js\"\nimport type * as RunnerStorage from \"./RunnerStorage.js\"\nimport * as Sharding from \"./Sharding.js\"\nimport { ShardingConfig } from \"./ShardingConfig.js\"\n\nconst constVoid = constant(Effect.void)\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerHandlers = Runners.Rpcs.toLayer(Effect.gen(function*() {\n  const sharding = yield* Sharding.Sharding\n  const storage = yield* MessageStorage.MessageStorage\n\n  return {\n    Ping: () => Effect.void,\n    Notify: ({ envelope }) =>\n      sharding.notify(\n        envelope._tag === \"Request\"\n          ? new Message.IncomingRequest({\n            envelope,\n            respond: constVoid,\n            lastSentReply: Option.none()\n          })\n          : new Message.IncomingEnvelope({ envelope })\n      ),\n    Effect: ({ persisted, request }) => {\n      let replyEncoded:\n        | Effect.Effect<\n          Reply.ReplyEncoded<any>,\n          ClusterError.EntityNotAssignedToRunner\n        >\n        | undefined = undefined\n      let resume = (reply: Effect.Effect<Reply.ReplyEncoded<any>, ClusterError.EntityNotAssignedToRunner>) => {\n        replyEncoded = reply\n      }\n      const message = new Message.IncomingRequest({\n        envelope: request,\n        lastSentReply: Option.none(),\n        respond(reply) {\n          resume(Effect.orDie(Reply.serialize(reply)))\n          return Effect.void\n        }\n      })\n      if (persisted) {\n        return Effect.async<\n          Reply.ReplyEncoded<any>,\n          ClusterError.EntityNotAssignedToRunner\n        >((resume_) => {\n          resume = resume_\n          const parent = Option.getOrThrow(Fiber.getCurrentFiber())\n          const runtime = Runtime.make({\n            context: parent.currentContext,\n            runtimeFlags: Runtime.defaultRuntimeFlags,\n            fiberRefs: parent.getFiberRefs()\n          })\n          const onExit = (\n            exit: Exit.Exit<\n              any,\n              ClusterError.EntityNotAssignedToRunner\n            >\n          ) => {\n            if (exit._tag === \"Failure\") {\n              resume(exit as any)\n            }\n          }\n          const fiber = Runtime.runFork(runtime)(storage.registerReplyHandler(message))\n          fiber.addObserver(onExit)\n          Runtime.runFork(runtime)(Effect.catchTag(\n            sharding.notify(message, constWaitUntilRead),\n            \"AlreadyProcessingMessage\",\n            () => Effect.void\n          )).addObserver(onExit)\n          return Fiber.interrupt(fiber)\n        })\n      }\n      return Effect.zipRight(\n        sharding.send(message),\n        Effect.async<Reply.ReplyEncoded<any>, ClusterError.EntityNotAssignedToRunner>((resume_) => {\n          if (replyEncoded) {\n            resume_(replyEncoded)\n          } else {\n            resume = resume_\n          }\n        })\n      )\n    },\n    Stream: ({ persisted, request }) =>\n      Effect.flatMap(\n        Mailbox.make<Reply.ReplyEncoded<any>, ClusterError.EntityNotAssignedToRunner>(),\n        (mailbox) => {\n          const message = new Message.IncomingRequest({\n            envelope: request,\n            lastSentReply: Option.none(),\n            respond(reply) {\n              return Effect.flatMap(Reply.serialize(reply), (reply) => {\n                mailbox.unsafeOffer(reply)\n                return Effect.void\n              })\n            }\n          })\n          return Effect.as(\n            persisted ?\n              Effect.zipRight(\n                storage.registerReplyHandler(message).pipe(\n                  Effect.onError((cause) => mailbox.failCause(cause)),\n                  Effect.forkScoped,\n                  Effect.interruptible\n                ),\n                sharding.notify(message, constWaitUntilRead)\n              ) :\n              sharding.send(message),\n            mailbox\n          )\n        }\n      ),\n    Envelope: ({ envelope }) => sharding.send(new Message.IncomingEnvelope({ envelope }))\n  }\n}))\n\nconst constWaitUntilRead = { waitUntilRead: true } as const\n\n/**\n * The `RunnerServer` recieves messages from other Runners and forwards them to the\n * `Sharding` layer.\n *\n * It also responds to `Ping` requests.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layer: Layer.Layer<\n  never,\n  never,\n  RpcServer.Protocol | Sharding.Sharding | MessageStorage.MessageStorage\n> = RpcServer.layer(Runners.Rpcs, {\n  spanPrefix: \"RunnerServer\",\n  disableTracing: true\n}).pipe(Layer.provide(layerHandlers))\n\n/**\n * A `RunnerServer` layer that includes the `Runners` & `Sharding` clients.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layerWithClients: Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  | RpcServer.Protocol\n  | ShardingConfig\n  | Runners.RpcClientProtocol\n  | MessageStorage.MessageStorage\n  | RunnerStorage.RunnerStorage\n  | RunnerHealth.RunnerHealth\n> = layer.pipe(\n  Layer.provideMerge(Sharding.layer),\n  Layer.provideMerge(Runners.layerRpc)\n)\n\n/**\n * A `Runners` layer that is client only.\n *\n * It will not register with RunnerStorage and recieve shard assignments,\n * so this layer can be used to embed a cluster client inside another effect\n * application.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layerClientOnly: Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  | ShardingConfig\n  | Runners.RpcClientProtocol\n  | MessageStorage.MessageStorage\n  | RunnerStorage.RunnerStorage\n> = Sharding.layer.pipe(\n  Layer.provideMerge(Runners.layerRpc),\n  Layer.provide(RunnerHealth.layerNoop),\n  Layer.updateService(ShardingConfig, (config) => ({\n    ...config,\n    runnerAddress: Option.none()\n  }))\n)\n"
  },
  {
    "path": "packages/cluster/src/RunnerStorage.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport { isNonEmptyArray, type NonEmptyArray } from \"effect/Array\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as MutableHashMap from \"effect/MutableHashMap\"\nimport type { PersistenceError } from \"./ClusterError.js\"\nimport * as MachineId from \"./MachineId.js\"\nimport { Runner } from \"./Runner.js\"\nimport type { RunnerAddress } from \"./RunnerAddress.js\"\nimport { ShardId } from \"./ShardId.js\"\n\n/**\n * Represents a generic interface to the persistent storage required by the\n * cluster.\n *\n * @since 1.0.0\n * @category models\n */\nexport class RunnerStorage extends Context.Tag(\"@effect/cluster/RunnerStorage\")<RunnerStorage, {\n  /**\n   * Register a new runner with the cluster.\n   */\n  readonly register: (runner: Runner, healthy: boolean) => Effect.Effect<MachineId.MachineId, PersistenceError>\n\n  /**\n   * Unregister the runner with the given address.\n   */\n  readonly unregister: (address: RunnerAddress) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Get all runners registered with the cluster.\n   */\n  readonly getRunners: Effect.Effect<Array<readonly [runner: Runner, healthy: boolean]>, PersistenceError>\n\n  /**\n   * Set the health status of the given runner.\n   */\n  readonly setRunnerHealth: (address: RunnerAddress, healthy: boolean) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Try to acquire the given shard ids for processing.\n   *\n   * It returns an array of shards it was able to acquire.\n   */\n  readonly acquire: (\n    address: RunnerAddress,\n    shardIds: Iterable<ShardId>\n  ) => Effect.Effect<Array<ShardId>, PersistenceError>\n\n  /**\n   * Refresh the locks owned by the given runner.\n   */\n  readonly refresh: (\n    address: RunnerAddress,\n    shardIds: Iterable<ShardId>\n  ) => Effect.Effect<Array<ShardId>, PersistenceError>\n\n  /**\n   * Release the given shard ids.\n   */\n  readonly release: (\n    address: RunnerAddress,\n    shardId: ShardId\n  ) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Release all the shards assigned to the given runner.\n   */\n  readonly releaseAll: (address: RunnerAddress) => Effect.Effect<void, PersistenceError>\n}>() {}\n\n/**\n * @since 1.0.0\n * @category Encoded\n */\nexport interface Encoded {\n  /**\n   * Get all runners registered with the cluster.\n   */\n  readonly getRunners: Effect.Effect<Array<readonly [runner: string, healthy: boolean]>, PersistenceError>\n\n  /**\n   * Register a new runner with the cluster.\n   */\n  readonly register: (address: string, runner: string, healthy: boolean) => Effect.Effect<number, PersistenceError>\n\n  /**\n   * Unregister the runner with the given address.\n   */\n  readonly unregister: (address: string) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Set the health status of the given runner.\n   */\n  readonly setRunnerHealth: (address: string, healthy: boolean) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Acquire the lock on the given shards, returning the shards that were\n   * successfully locked.\n   */\n  readonly acquire: (\n    address: string,\n    shardIds: NonEmptyArray<string>\n  ) => Effect.Effect<Array<string>, PersistenceError>\n\n  /**\n   * Refresh the lock on the given shards, returning the shards that were\n   * successfully locked.\n   */\n  readonly refresh: (\n    address: string,\n    shardIds: Array<string>\n  ) => Effect.Effect<ReadonlyArray<string>, PersistenceError>\n\n  /**\n   * Release the lock on the given shard.\n   */\n  readonly release: (\n    address: string,\n    shardId: string\n  ) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Release the lock on all shards for the given runner.\n   */\n  readonly releaseAll: (address: string) => Effect.Effect<void, PersistenceError>\n}\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const makeEncoded = (encoded: Encoded) =>\n  RunnerStorage.of({\n    getRunners: Effect.gen(function*() {\n      const runners = yield* encoded.getRunners\n      const results: Array<[Runner, boolean]> = []\n      for (let i = 0; i < runners.length; i++) {\n        const [runner, healthy] = runners[i]\n        try {\n          results.push([Runner.decodeSync(runner), healthy])\n        } catch {\n          //\n        }\n      }\n      return results\n    }),\n    register: (runner, healthy) =>\n      Effect.map(\n        encoded.register(encodeRunnerAddress(runner.address), Runner.encodeSync(runner), healthy),\n        MachineId.make\n      ),\n    unregister: (address) => encoded.unregister(encodeRunnerAddress(address)),\n    setRunnerHealth: (address, healthy) => encoded.setRunnerHealth(encodeRunnerAddress(address), healthy),\n    acquire: (address, shardIds) => {\n      const arr = Array.from(shardIds, (id) => id.toString())\n      if (!isNonEmptyArray(arr)) return Effect.succeed([])\n      return encoded.acquire(encodeRunnerAddress(address), arr).pipe(\n        Effect.map((shards) => shards.map(ShardId.fromString))\n      )\n    },\n    refresh: (address, shardIds) =>\n      encoded.refresh(encodeRunnerAddress(address), Array.from(shardIds, (id) => id.toString())).pipe(\n        Effect.map((shards) => shards.map(ShardId.fromString))\n      ),\n    release(address, shardId) {\n      return encoded.release(encodeRunnerAddress(address), shardId.toString())\n    },\n    releaseAll(address) {\n      return encoded.releaseAll(encodeRunnerAddress(address))\n    }\n  })\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeMemory = Effect.gen(function*() {\n  const runners = MutableHashMap.empty<RunnerAddress, Runner>()\n  let acquired: Array<ShardId> = []\n  let id = 0\n\n  return RunnerStorage.of({\n    getRunners: Effect.sync(() => Array.from(MutableHashMap.values(runners), (runner) => [runner, true])),\n    register: (runner) =>\n      Effect.sync(() => {\n        MutableHashMap.set(runners, runner.address, runner)\n        return MachineId.make(id++)\n      }),\n    unregister: (address) =>\n      Effect.sync(() => {\n        MutableHashMap.remove(runners, address)\n      }),\n    setRunnerHealth: () => Effect.void,\n    acquire: (_address, shardIds) => {\n      acquired = Array.from(shardIds)\n      return Effect.succeed(Array.from(shardIds))\n    },\n    refresh: () => Effect.sync(() => acquired),\n    release: () => Effect.void,\n    releaseAll: () => Effect.void\n  })\n})\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerMemory: Layer.Layer<RunnerStorage> = Layer.effect(RunnerStorage)(makeMemory)\n\n// -------------------------------------------------------------------------------------\n// internal\n// -------------------------------------------------------------------------------------\n\nconst encodeRunnerAddress = (runnerAddress: RunnerAddress) => `${runnerAddress.host}:${runnerAddress.port}`\n"
  },
  {
    "path": "packages/cluster/src/Runners.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Rpc from \"@effect/rpc/Rpc\"\nimport * as RpcClient_ from \"@effect/rpc/RpcClient\"\nimport type { RpcClientError } from \"@effect/rpc/RpcClientError\"\nimport * as RpcGroup from \"@effect/rpc/RpcGroup\"\nimport * as RpcSchema from \"@effect/rpc/RpcSchema\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as RcMap from \"effect/RcMap\"\nimport * as Schema from \"effect/Schema\"\nimport type { Scope } from \"effect/Scope\"\nimport type { PersistenceError } from \"./ClusterError.js\"\nimport { AlreadyProcessingMessage, EntityNotAssignedToRunner, MailboxFull, RunnerUnavailable } from \"./ClusterError.js\"\nimport { Persisted } from \"./ClusterSchema.js\"\nimport * as Envelope from \"./Envelope.js\"\nimport * as Message from \"./Message.js\"\nimport * as MessageStorage from \"./MessageStorage.js\"\nimport * as Reply from \"./Reply.js\"\nimport type { RunnerAddress } from \"./RunnerAddress.js\"\nimport { ShardingConfig } from \"./ShardingConfig.js\"\nimport * as Snowflake from \"./Snowflake.js\"\n\n/**\n * @since 1.0.0\n * @category context\n */\nexport class Runners extends Context.Tag(\"@effect/cluster/Runners\")<Runners, {\n  /**\n   * Checks if a Runner is responsive.\n   */\n  readonly ping: (address: RunnerAddress) => Effect.Effect<void, RunnerUnavailable>\n\n  /**\n   * Send a message locally.\n   *\n   * This ensures that the message hits storage before being sent to the local\n   * entity.\n   */\n  readonly sendLocal: <R extends Rpc.Any>(\n    options: {\n      readonly message: Message.Outgoing<R>\n      readonly send: <Rpc extends Rpc.Any>(\n        message: Message.IncomingLocal<Rpc>\n      ) => Effect.Effect<\n        void,\n        EntityNotAssignedToRunner | MailboxFull | AlreadyProcessingMessage\n      >\n      readonly simulateRemoteSerialization: boolean\n    }\n  ) => Effect.Effect<\n    void,\n    EntityNotAssignedToRunner | MailboxFull | AlreadyProcessingMessage | PersistenceError\n  >\n\n  /**\n   * Send a message to a Runner.\n   */\n  readonly send: <R extends Rpc.Any>(\n    options: {\n      readonly address: RunnerAddress\n      readonly message: Message.Outgoing<R>\n    }\n  ) => Effect.Effect<\n    void,\n    | EntityNotAssignedToRunner\n    | RunnerUnavailable\n    | MailboxFull\n    | AlreadyProcessingMessage\n    | PersistenceError\n  >\n\n  /**\n   * Notify a Runner that a message is available, then read replies from storage.\n   */\n  readonly notify: <R extends Rpc.Any>(\n    options: {\n      readonly address: Option.Option<RunnerAddress>\n      readonly message: Message.Outgoing<R>\n      readonly discard: boolean\n    }\n  ) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Notify the current Runner that a message is available, then read replies from\n   * storage.\n   *\n   * This ensures that the message hits storage before being sent to the local\n   * entity.\n   */\n  readonly notifyLocal: <R extends Rpc.Any>(\n    options: {\n      readonly message: Message.Outgoing<R>\n      readonly notify: (\n        options: Message.IncomingLocal<any>\n      ) => Effect.Effect<void, EntityNotAssignedToRunner>\n      readonly discard: boolean\n      readonly storageOnly?: boolean | undefined\n    }\n  ) => Effect.Effect<void, PersistenceError>\n\n  /**\n   * Mark a Runner as unavailable.\n   */\n  readonly onRunnerUnavailable: (address: RunnerAddress) => Effect.Effect<void>\n}>() {}\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make: (options: Omit<Runners[\"Type\"], \"sendLocal\" | \"notifyLocal\">) => Effect.Effect<\n  Runners[\"Type\"],\n  never,\n  MessageStorage.MessageStorage | Snowflake.Generator | ShardingConfig | Scope\n> = Effect.fnUntraced(function*(options: Omit<Runners[\"Type\"], \"sendLocal\" | \"notifyLocal\">) {\n  const storage = yield* MessageStorage.MessageStorage\n  const runnersScope = yield* Effect.scope\n  const snowflakeGen = yield* Snowflake.Generator\n  const config = yield* ShardingConfig\n\n  const requestIdRewrites = new Map<Snowflake.Snowflake, Snowflake.Snowflake>()\n\n  function notifyWith<E>(\n    message: Message.Outgoing<any>,\n    afterPersist: (message: Message.Outgoing<any>, isDuplicate: boolean) => Effect.Effect<void, E>\n  ): Effect.Effect<void, E | PersistenceError> {\n    const rpc = message.rpc as any as Rpc.AnyWithProps\n    const persisted = Context.get(rpc.annotations, Persisted)\n    if (!persisted) {\n      return Effect.dieMessage(\"Runners.notify only supports persisted messages\")\n    }\n\n    if (message._tag === \"OutgoingEnvelope\") {\n      const rewriteId = requestIdRewrites.get(message.envelope.requestId)\n      const requestId = rewriteId ?? message.envelope.requestId\n      const entry = storageRequests.get(requestId)\n      if (rewriteId) {\n        message = new Message.OutgoingEnvelope({\n          ...message,\n          envelope: message.envelope.withRequestId(rewriteId)\n        })\n      }\n      return storage.saveEnvelope(message).pipe(\n        Effect.catchTag(\"MalformedMessage\", Effect.die),\n        Effect.zipRight(\n          entry ? Effect.zipRight(entry.latch.open, afterPersist(message, false)) : afterPersist(message, false)\n        )\n      )\n    }\n\n    // For requests, after persisting the request, we need to check if the\n    // request is a duplicate. If it is, we need to resume from the last\n    // received reply.\n    //\n    // Otherwise, we notify the remote entity and then reply from storage.\n    return Effect.flatMap(\n      Effect.catchTag(storage.saveRequest(message), \"MalformedMessage\", Effect.die),\n      MessageStorage.SaveResult.$match({\n        Success: () => afterPersist(message, false),\n        Duplicate: ({ lastReceivedReply, originalId }) => {\n          // If the last received reply is an exit, we can just return it\n          // as the response.\n          if (Option.isSome(lastReceivedReply) && lastReceivedReply.value._tag === \"WithExit\") {\n            return message.respond(lastReceivedReply.value.withRequestId(message.envelope.requestId))\n          }\n          requestIdRewrites.set(message.envelope.requestId, originalId)\n          return afterPersist(\n            new Message.OutgoingRequest({\n              ...message,\n              lastReceivedReply,\n              envelope: Envelope.makeRequest({\n                ...message.envelope,\n                requestId: originalId\n              }),\n              respond(reply) {\n                if (reply._tag === \"WithExit\") {\n                  requestIdRewrites.delete(message.envelope.requestId)\n                }\n                return message.respond(reply.withRequestId(message.envelope.requestId))\n              }\n            }),\n            true\n          )\n        }\n      })\n    )\n  }\n\n  type StorageRequestEntry = {\n    readonly latch: Effect.Latch\n    doneLatch: Effect.Latch | undefined\n    readonly messages: Set<Message.OutgoingRequest<any>>\n    replies: Array<Reply.Reply<any>>\n  }\n  const storageRequests = new Map<Snowflake.Snowflake, StorageRequestEntry>()\n  const waitingStorageRequests = new Map<Snowflake.Snowflake, Message.OutgoingRequest<any>>()\n  const replyFromStorage = Effect.fnUntraced(\n    function*(message: Message.OutgoingRequest<any>) {\n      let entry = storageRequests.get(message.envelope.requestId)\n      if (entry) {\n        entry.messages.add(message)\n        entry.doneLatch ??= Effect.unsafeMakeLatch(false)\n        return yield* entry.doneLatch.await\n      } else {\n        entry = {\n          latch: Effect.unsafeMakeLatch(false),\n          doneLatch: undefined,\n          replies: [],\n          messages: new Set([message])\n        }\n        storageRequests.set(message.envelope.requestId, entry)\n      }\n\n      while (true) {\n        // wait for the storage loop to notify us\n        entry.latch.unsafeClose()\n        waitingStorageRequests.set(message.envelope.requestId, message)\n        storageLatch.unsafeOpen()\n        yield* entry.latch.await\n\n        // send the replies back\n        for (let i = 0; i < entry.replies.length; i++) {\n          const reply = entry.replies[i]\n          // we have reached the end\n          if (reply._tag === \"WithExit\") {\n            for (const message of entry.messages) {\n              yield* message.respond(reply)\n            }\n            entry.doneLatch?.unsafeOpen()\n            return\n          }\n\n          entry.latch.unsafeClose()\n          for (const message of entry.messages) {\n            yield* message.respond(reply)\n          }\n          // wait for ack\n          yield* entry.latch.await\n        }\n        entry.replies = []\n      }\n    },\n    (effect, message) =>\n      Effect.ensuring(\n        effect,\n        Effect.sync(() => {\n          const entry = storageRequests.get(message.envelope.requestId)\n          if (!entry || entry.messages.size > 1) {\n            entry?.messages.delete(message)\n            return\n          }\n          storageRequests.delete(message.envelope.requestId)\n          waitingStorageRequests.delete(message.envelope.requestId)\n        })\n      )\n  )\n\n  const storageLatch = Effect.unsafeMakeLatch(false)\n  if (storage !== MessageStorage.noop) {\n    yield* Effect.gen(function*() {\n      const foundRequests = new Set<StorageRequestEntry>()\n\n      while (true) {\n        yield* storageLatch.await\n        storageLatch.unsafeClose()\n\n        const replies = yield* storage.repliesFor(waitingStorageRequests.values()).pipe(\n          Effect.catchAllCause((cause) =>\n            Effect.as(\n              Effect.annotateLogs(Effect.logDebug(cause), {\n                package: \"@effect/cluster\",\n                module: \"Runners\",\n                fiber: \"Read replies loop\"\n              }),\n              []\n            )\n          )\n        )\n\n        // put the replies into the storage requests and then open the latches\n        for (let i = 0; i < replies.length; i++) {\n          const reply = replies[i]\n          const entry = storageRequests.get(reply.requestId)\n          if (!entry) continue\n          entry.replies.push(reply)\n          waitingStorageRequests.delete(reply.requestId)\n          foundRequests.add(entry)\n        }\n\n        foundRequests.forEach((entry) => entry.latch.unsafeOpen())\n        foundRequests.clear()\n      }\n    }).pipe(\n      Effect.interruptible,\n      Effect.forkIn(runnersScope)\n    )\n\n    yield* Effect.suspend(() => {\n      if (waitingStorageRequests.size === 0) {\n        return storageLatch.await\n      }\n      return storageLatch.open\n    }).pipe(\n      Effect.delay(config.entityReplyPollInterval),\n      Effect.forever,\n      Effect.interruptible,\n      Effect.forkIn(runnersScope)\n    )\n  }\n\n  return Runners.of({\n    ...options,\n    sendLocal(options) {\n      const message = options.message\n      if (!options.simulateRemoteSerialization) {\n        return options.send(Message.incomingLocalFromOutgoing(message))\n      }\n      return Message.serialize(message).pipe(\n        Effect.flatMap((encoded) => Message.deserializeLocal(message, encoded)),\n        Effect.flatMap(options.send),\n        Effect.catchTag(\"MalformedMessage\", (error) => {\n          if (message._tag === \"OutgoingEnvelope\") {\n            return Effect.die(error)\n          }\n          return message.respond(\n            new Reply.WithExit({\n              id: snowflakeGen.unsafeNext(),\n              requestId: message.envelope.requestId,\n              exit: Exit.die(error)\n            })\n          )\n        })\n      )\n    },\n    notify(options_) {\n      const { discard, message } = options_\n      return notifyWith(message, (message, duplicate) => {\n        if (discard || message._tag === \"OutgoingEnvelope\") {\n          return options.notify(options_)\n        } else if (!duplicate && options_.address._tag === \"Some\") {\n          return Effect.catchAll(\n            options.send({\n              address: options_.address.value,\n              message\n            }),\n            (_) => replyFromStorage(message)\n          )\n        }\n        return options.notify(options_).pipe(\n          Effect.andThen(replyFromStorage(message))\n        )\n      })\n    },\n    notifyLocal(options) {\n      return notifyWith(options.message, (message, duplicate) => {\n        if (options.discard || message._tag === \"OutgoingEnvelope\") {\n          return Effect.catchTag(\n            options.notify(Message.incomingLocalFromOutgoing(message)),\n            \"EntityNotAssignedToRunner\",\n            () => Effect.void\n          )\n        } else if (!duplicate && options.storageOnly !== true) {\n          return options.notify(Message.incomingLocalFromOutgoing(message)).pipe(\n            Effect.andThen(storage.registerReplyHandler(message)),\n            Effect.catchTag(\"EntityNotAssignedToRunner\", () => replyFromStorage(message))\n          )\n        }\n        return options.notify(Message.incomingLocalFromOutgoing(message)).pipe(\n          Effect.catchTag(\"EntityNotAssignedToRunner\", () => Effect.void),\n          Effect.andThen(replyFromStorage(message))\n        )\n      })\n    }\n  })\n})\n\n/**\n * @since 1.0.0\n * @category No-op\n */\nexport const makeNoop: Effect.Effect<\n  Runners[\"Type\"],\n  never,\n  MessageStorage.MessageStorage | Snowflake.Generator | ShardingConfig | Scope\n> = make({\n  send: ({ message }) => Effect.fail(new EntityNotAssignedToRunner({ address: message.envelope.address })),\n  notify: () => Effect.void,\n  ping: () => Effect.void,\n  onRunnerUnavailable: () => Effect.void\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerNoop: Layer.Layer<\n  Runners,\n  never,\n  ShardingConfig | MessageStorage.MessageStorage\n> = Layer.scoped(Runners, makeNoop).pipe(Layer.provide([Snowflake.layerGenerator]))\n\nconst rpcErrors: Schema.Union<[\n  typeof EntityNotAssignedToRunner,\n  typeof MailboxFull,\n  typeof AlreadyProcessingMessage\n]> = Schema.Union(\n  EntityNotAssignedToRunner,\n  MailboxFull,\n  AlreadyProcessingMessage\n)\n\n/**\n * @since 1.0.0\n * @category Rpcs\n */\nexport class Rpcs extends RpcGroup.make(\n  Rpc.make(\"Ping\"),\n  Rpc.make(\"Notify\", {\n    payload: {\n      envelope: Envelope.PartialEncoded\n    },\n    success: Schema.Void,\n    error: Schema.Union(EntityNotAssignedToRunner, AlreadyProcessingMessage)\n  }),\n  Rpc.make(\"Effect\", {\n    payload: {\n      request: Envelope.PartialEncodedRequest,\n      persisted: Schema.Boolean\n    },\n    success: Schema.Object as Schema.Schema<Reply.ReplyEncoded<any>>,\n    error: rpcErrors\n  }),\n  Rpc.make(\"Stream\", {\n    payload: {\n      request: Envelope.PartialEncodedRequest,\n      persisted: Schema.Boolean\n    },\n    error: rpcErrors,\n    success: Schema.Object as Schema.Schema<Reply.ReplyEncoded<any>>,\n    stream: true\n  }),\n  Rpc.make(\"Envelope\", {\n    payload: {\n      envelope: Schema.Union(Envelope.AckChunk, Envelope.Interrupt),\n      persisted: Schema.Boolean\n    },\n    error: rpcErrors\n  })\n) {}\n\n/**\n * @since 1.0.0\n * @category Rpcs\n */\nexport interface RpcClient extends RpcClient_.FromGroup<typeof Rpcs, RpcClientError> {}\n\n/**\n * @since 1.0.0\n * @category Rpcs\n */\nexport const makeRpcClient: Effect.Effect<\n  RpcClient,\n  never,\n  RpcClient_.Protocol | Scope\n> = RpcClient_.make(Rpcs, { spanPrefix: \"Runners\", disableTracing: true })\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeRpc: Effect.Effect<\n  Runners[\"Type\"],\n  never,\n  Scope | RpcClientProtocol | MessageStorage.MessageStorage | Snowflake.Generator | ShardingConfig\n> = Effect.gen(function*() {\n  const makeClientProtocol = yield* RpcClientProtocol\n  const snowflakeGen = yield* Snowflake.Generator\n\n  const clients = yield* RcMap.make({\n    lookup: (address: RunnerAddress) =>\n      Effect.flatMap(\n        makeClientProtocol(address),\n        (protocol) => Effect.provideService(makeRpcClient, RpcClient_.Protocol, protocol)\n      ),\n    idleTimeToLive: \"3 minutes\"\n  })\n\n  return yield* make({\n    ping(address) {\n      return RcMap.get(clients, address).pipe(\n        Effect.flatMap((client) => client.Ping()),\n        Effect.catchAllCause(() => {\n          return Effect.zipRight(\n            RcMap.invalidate(clients, address),\n            Effect.fail(new RunnerUnavailable({ address }))\n          )\n        }),\n        Effect.scoped\n      )\n    },\n    send({ address, message }) {\n      const rpc = message.rpc as any as Rpc.AnyWithProps\n      const isPersisted = Context.get(rpc.annotations, Persisted)\n      if (message._tag === \"OutgoingEnvelope\") {\n        return RcMap.get(clients, address).pipe(\n          Effect.flatMap((client) =>\n            client.Envelope({\n              envelope: message.envelope,\n              persisted: isPersisted\n            })\n          ),\n          Effect.catchTag(\"RpcClientError\", Effect.die),\n          Effect.scoped,\n          Effect.catchAllDefect(() => Effect.fail(new RunnerUnavailable({ address })))\n        )\n      }\n      const isStream = RpcSchema.isStreamSchema(rpc.successSchema)\n      if (!isStream) {\n        return Effect.matchEffect(Message.serializeRequest(message), {\n          onSuccess: (request) =>\n            RcMap.get(clients, address).pipe(\n              Effect.flatMap((client) =>\n                client.Effect({\n                  request,\n                  persisted: isPersisted\n                })\n              ),\n              Effect.catchTag(\"RpcClientError\", Effect.die),\n              Effect.flatMap((reply) =>\n                Schema.decode(Reply.Reply(message.rpc))(reply).pipe(\n                  Effect.locally(FiberRef.currentContext, message.context),\n                  Effect.orDie\n                )\n              ),\n              Effect.flatMap(message.respond),\n              Effect.scoped,\n              Effect.catchAllDefect(() => Effect.fail(new RunnerUnavailable({ address })))\n            ),\n          onFailure: (error) =>\n            message.respond(\n              new Reply.WithExit({\n                id: snowflakeGen.unsafeNext(),\n                requestId: message.envelope.requestId,\n                exit: Exit.die(error)\n              })\n            )\n        })\n      }\n      return Effect.matchEffect(Message.serializeRequest(message), {\n        onSuccess: (request) =>\n          RcMap.get(clients, address).pipe(\n            Effect.flatMap((client) =>\n              client.Stream({\n                request,\n                persisted: isPersisted\n              }, { asMailbox: true })\n            ),\n            Effect.flatMap((mailbox) => {\n              const decode = Schema.decode(Reply.Reply(message.rpc))\n              return mailbox.take.pipe(\n                Effect.flatMap((reply) => Effect.orDie(decode(reply))),\n                Effect.flatMap(message.respond),\n                Effect.forever,\n                Effect.catchTag(\"RpcClientError\", Effect.die),\n                Effect.locally(FiberRef.currentContext, message.context),\n                Effect.catchIf(Cause.isNoSuchElementException, () => Effect.void),\n                Effect.catchAllDefect(() => Effect.fail(new RunnerUnavailable({ address })))\n              )\n            }),\n            Effect.scoped\n          ),\n        onFailure: (error) =>\n          message.respond(\n            new Reply.WithExit({\n              id: snowflakeGen.unsafeNext(),\n              requestId: message.envelope.requestId,\n              exit: Exit.die(error)\n            })\n          )\n      })\n    },\n    notify({ address, message }) {\n      if (Option.isNone(address)) {\n        return Effect.void\n      }\n      const envelope = message.envelope\n      return RcMap.get(clients, address.value).pipe(\n        Effect.flatMap((client) => client.Notify({ envelope })),\n        Effect.scoped,\n        Effect.ignore\n      )\n    },\n    onRunnerUnavailable: (address) => RcMap.invalidate(clients, address)\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerRpc: Layer.Layer<\n  Runners,\n  never,\n  MessageStorage.MessageStorage | RpcClientProtocol | ShardingConfig\n> = Layer.scoped(Runners, makeRpc).pipe(\n  Layer.provide(Snowflake.layerGenerator)\n)\n\n/**\n * @since 1.0.0\n * @category Client\n */\nexport class RpcClientProtocol extends Context.Tag(\"@effect/cluster/Runners/RpcClientProtocol\")<\n  RpcClientProtocol,\n  (address: RunnerAddress) => Effect.Effect<RpcClient_.Protocol[\"Type\"], never, Scope>\n>() {}\n"
  },
  {
    "path": "packages/cluster/src/ShardId.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Equal from \"effect/Equal\"\nimport * as Hash from \"effect/Hash\"\nimport * as S from \"effect/Schema\"\n\n/**\n * @since 1.0.0\n * @category Symbols\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/cluster/ShardId\")\n\n/**\n * @since 1.0.0\n * @category Symbols\n */\nexport type TypeId = typeof TypeId\n\nconst constDisableValidation = { disableValidation: true }\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (group: string, id: number): ShardId => {\n  const key = `${group}:${id}`\n  let shardId = shardIdCache.get(key)\n  if (!shardId) {\n    shardId = new ShardId({ group, id }, constDisableValidation)\n    shardIdCache.set(key, shardId)\n  }\n  return shardId\n}\n\nconst shardIdCache = new Map<string, ShardId>()\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport class ShardId extends S.Class<ShardId>(\"@effect/cluster/ShardId\")({\n  group: S.String,\n  id: S.Int\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId]: TypeId = TypeId;\n\n  /**\n   * @since 1.0.0\n   */\n  [Equal.symbol](that: ShardId): boolean {\n    return this.group === that.group && this.id === that.id\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  [Hash.symbol](): number {\n    return Hash.cached(this, Hash.string(this.toString()))\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  toString(): string {\n    return `${this.group}:${this.id}`\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  static toString(shardId: {\n    readonly group: string\n    readonly id: number\n  }): string {\n    return `${shardId.group}:${shardId.id}`\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  static fromStringEncoded(s: string): {\n    readonly group: string\n    readonly id: number\n  } {\n    const index = s.lastIndexOf(\":\")\n    if (index === -1) {\n      throw new Error(`Invalid ShardId format`)\n    }\n    const group = s.substring(0, index)\n    const id = Number(s.substring(index + 1))\n    if (isNaN(id)) {\n      throw new Error(`ShardId id must be a number`)\n    }\n    return { group, id }\n  }\n\n  /**\n   * @since 4.0.0\n   */\n  static fromString(s: string): ShardId {\n    const encoded = ShardId.fromStringEncoded(s)\n    return make(encoded.group, encoded.id)\n  }\n}\n"
  },
  {
    "path": "packages/cluster/src/Sharding.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Rpc from \"@effect/rpc/Rpc\"\nimport * as RpcClient from \"@effect/rpc/RpcClient\"\nimport { type FromServer, RequestId } from \"@effect/rpc/RpcMessage\"\nimport * as Arr from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport type { DurationInput } from \"effect/Duration\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Equal from \"effect/Equal\"\nimport type * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberMap from \"effect/FiberMap\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport * as FiberSet from \"effect/FiberSet\"\nimport { constant } from \"effect/Function\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as HashRing from \"effect/HashRing\"\nimport * as Layer from \"effect/Layer\"\nimport * as MutableHashMap from \"effect/MutableHashMap\"\nimport * as MutableHashSet from \"effect/MutableHashSet\"\nimport * as MutableRef from \"effect/MutableRef\"\nimport * as Option from \"effect/Option\"\nimport * as PubSub from \"effect/PubSub\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type { MailboxFull, PersistenceError } from \"./ClusterError.js\"\nimport { AlreadyProcessingMessage, EntityNotAssignedToRunner } from \"./ClusterError.js\"\nimport * as ClusterMetrics from \"./ClusterMetrics.js\"\nimport { Persisted, Uninterruptible } from \"./ClusterSchema.js\"\nimport * as ClusterSchema from \"./ClusterSchema.js\"\nimport type { CurrentAddress, CurrentRunnerAddress, Entity, HandlersFrom } from \"./Entity.js\"\nimport type { EntityAddress } from \"./EntityAddress.js\"\nimport { make as makeEntityAddress } from \"./EntityAddress.js\"\nimport type { EntityId } from \"./EntityId.js\"\nimport { make as makeEntityId } from \"./EntityId.js\"\nimport * as Envelope from \"./Envelope.js\"\nimport * as EntityManager from \"./internal/entityManager.js\"\nimport { EntityReaper } from \"./internal/entityReaper.js\"\nimport { joinAllDiscard } from \"./internal/fiber.js\"\nimport { hashString } from \"./internal/hash.js\"\nimport { internalInterruptors } from \"./internal/interruptors.js\"\nimport { ResourceMap } from \"./internal/resourceMap.js\"\nimport * as Message from \"./Message.js\"\nimport * as MessageStorage from \"./MessageStorage.js\"\nimport * as Reply from \"./Reply.js\"\nimport { Runner } from \"./Runner.js\"\nimport type { RunnerAddress } from \"./RunnerAddress.js\"\nimport * as RunnerHealth from \"./RunnerHealth.js\"\nimport { Runners } from \"./Runners.js\"\nimport { RunnerStorage } from \"./RunnerStorage.js\"\nimport type { ShardId } from \"./ShardId.js\"\nimport { make as makeShardId } from \"./ShardId.js\"\nimport { ShardingConfig } from \"./ShardingConfig.js\"\nimport { EntityRegistered, type ShardingRegistrationEvent, SingletonRegistered } from \"./ShardingRegistrationEvent.js\"\nimport { SingletonAddress } from \"./SingletonAddress.js\"\nimport * as Snowflake from \"./Snowflake.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport class Sharding extends Context.Tag(\"@effect/cluster/Sharding\")<Sharding, {\n  /**\n   * Returns a stream of events that occur when the runner registers entities or\n   * singletons.\n   */\n  readonly getRegistrationEvents: Stream.Stream<ShardingRegistrationEvent>\n\n  /**\n   * Returns the `ShardId` of the shard to which the entity at the specified\n   * `address` is assigned.\n   */\n  readonly getShardId: (entityId: EntityId, group: string) => ShardId\n\n  /**\n   * Returns `true` if the specified `shardId` is assigned to this runner.\n   */\n  readonly hasShardId: (shardId: ShardId) => boolean\n\n  /**\n   * Generate a Snowflake ID that is unique to this runner.\n   */\n  readonly getSnowflake: Effect.Effect<Snowflake.Snowflake>\n\n  /**\n   * Returns `true` if sharding is shutting down, `false` otherwise.\n   */\n  readonly isShutdown: Effect.Effect<boolean>\n\n  /**\n   * Constructs a `RpcClient` which can be used to send messages to the\n   * specified `Entity`.\n   */\n  readonly makeClient: <Type extends string, Rpcs extends Rpc.Any>(\n    entity: Entity<Type, Rpcs>\n  ) => Effect.Effect<\n    (\n      entityId: string\n    ) => RpcClient.RpcClient.From<\n      Rpcs,\n      MailboxFull | AlreadyProcessingMessage | PersistenceError\n    >\n  >\n\n  /**\n   * Registers a new entity with the runner.\n   */\n  readonly registerEntity: <Type extends string, Rpcs extends Rpc.Any, Handlers extends HandlersFrom<Rpcs>, RX>(\n    entity: Entity<Type, Rpcs>,\n    handlers: Effect.Effect<Handlers, never, RX>,\n    options?: {\n      readonly maxIdleTime?: DurationInput | undefined\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly mailboxCapacity?: number | \"unbounded\" | undefined\n      readonly disableFatalDefects?: boolean | undefined\n      readonly defectRetryPolicy?: Schedule.Schedule<any, unknown> | undefined\n      readonly spanAttributes?: Record<string, string> | undefined\n    }\n  ) => Effect.Effect<\n    void,\n    never,\n    | Scope.Scope\n    | Rpc.Context<Rpcs>\n    | Rpc.Middleware<Rpcs>\n    | Exclude<RX, Scope.Scope | CurrentAddress | CurrentRunnerAddress>\n  >\n\n  /**\n   * Registers a new singleton with the runner.\n   */\n  readonly registerSingleton: <E, R>(\n    name: string,\n    run: Effect.Effect<void, E, R>,\n    options?: {\n      readonly shardGroup?: string | undefined\n    }\n  ) => Effect.Effect<void, never, R | Scope.Scope>\n\n  /**\n   * Sends a message to the specified entity.\n   */\n  readonly send: (message: Message.Incoming<any>) => Effect.Effect<\n    void,\n    EntityNotAssignedToRunner | MailboxFull | AlreadyProcessingMessage\n  >\n\n  /**\n   * Sends an outgoing message\n   */\n  readonly sendOutgoing: (\n    message: Message.Outgoing<any>,\n    discard: boolean\n  ) => Effect.Effect<\n    void,\n    MailboxFull | AlreadyProcessingMessage | PersistenceError\n  >\n\n  /**\n   * Notify sharding that a message has been persisted to storage.\n   */\n  readonly notify: (message: Message.Incoming<any>, options?: {\n    readonly waitUntilRead?: boolean | undefined\n  }) => Effect.Effect<\n    void,\n    EntityNotAssignedToRunner | AlreadyProcessingMessage\n  >\n\n  /**\n   * Reset the state of a message\n   */\n  readonly reset: (requestId: Snowflake.Snowflake) => Effect.Effect<boolean>\n\n  /**\n   * Trigger a storage read, which will read all unprocessed messages.\n   */\n  readonly pollStorage: Effect.Effect<void>\n\n  /**\n   * Retrieves the active entity count for the current runner.\n   */\n  readonly activeEntityCount: Effect.Effect<number>\n}>() {}\n\n// -----------------------------------------------------------------------------\n// Implementation\n// -----------------------------------------------------------------------------\n\ninterface EntityManagerState {\n  readonly entity: Entity<any, any>\n  readonly manager: EntityManager.EntityManager\n  status: \"alive\" | \"closing\" | \"closed\"\n}\n\nconst make = Effect.gen(function*() {\n  const config = yield* ShardingConfig\n  const clock = yield* Effect.clock\n\n  const runnersService = yield* Runners\n  const runnerHealth = yield* RunnerHealth.RunnerHealth\n  const snowflakeGen = yield* Snowflake.Generator\n  const shardingScope = yield* Effect.scope\n  const isShutdown = MutableRef.make(false)\n  const fiberSet = yield* FiberSet.make()\n  const runFork = yield* FiberSet.runtime(fiberSet)<never>().pipe(\n    Effect.mapInputContext((context: Context.Context<never>) => Context.omit(Scope.Scope)(context))\n  )\n\n  const storage = yield* MessageStorage.MessageStorage\n  const storageEnabled = storage !== MessageStorage.noop\n  const runnerStorage = yield* RunnerStorage\n\n  const entityManagers = new Map<string, EntityManagerState>()\n\n  const shardAssignments = MutableHashMap.empty<ShardId, RunnerAddress>()\n  const selfShards = MutableHashSet.empty<ShardId>()\n\n  // the active shards are the ones that we have acquired the lock for\n  const acquiredShards = MutableHashSet.empty<ShardId>()\n  const activeShardsLatch = yield* Effect.makeLatch(false)\n\n  const events = yield* PubSub.unbounded<ShardingRegistrationEvent>()\n  const getRegistrationEvents: Stream.Stream<ShardingRegistrationEvent> = Stream.fromPubSub(events)\n\n  const isLocalRunner = (address: RunnerAddress) =>\n    Option.isSome(config.runnerAddress) && Equal.equals(address, config.runnerAddress.value)\n\n  function getShardId(entityId: EntityId, group: string): ShardId {\n    const id = Math.abs(hashString(entityId) % config.shardsPerGroup) + 1\n    return makeShardId(group, id)\n  }\n\n  function isEntityOnLocalShards(address: EntityAddress): boolean {\n    return MutableHashSet.has(acquiredShards, address.shardId)\n  }\n\n  yield* Scope.addFinalizer(\n    shardingScope,\n    Effect.logDebug(\"Shutdown complete\").pipe(Effect.annotateLogs({\n      package: \"@effect/cluster\",\n      module: \"Sharding\"\n    }))\n  )\n\n  // --- Shard acquisition ---\n  //\n  // Responsible for acquiring and releasing shards from RunnerStorage.\n  //\n  // This should be shutdown last, when all entities have been shutdown, to\n  // allow them to move to another runner.\n\n  const releasingShards = MutableHashSet.empty<ShardId>()\n  if (Option.isSome(config.runnerAddress)) {\n    const selfAddress = config.runnerAddress.value\n    yield* Scope.addFinalizerExit(shardingScope, () => {\n      // the locks expire over time, so if this fails we ignore it\n      return Effect.ignore(runnerStorage.releaseAll(selfAddress))\n    })\n\n    const releaseShardsMap = yield* FiberMap.make<ShardId>()\n    const releaseShard = Effect.fnUntraced(\n      function*(shardId: ShardId) {\n        const fibers = Arr.empty<Fiber.RuntimeFiber<void>>()\n        for (const state of entityManagers.values()) {\n          if (state.status === \"closed\") continue\n          fibers.push(yield* Effect.fork(state.manager.interruptShard(shardId)))\n        }\n        yield* joinAllDiscard(fibers)\n        yield* runnerStorage.release(selfAddress, shardId)\n        MutableHashSet.remove(releasingShards, shardId)\n        yield* storage.unregisterShardReplyHandlers(shardId)\n      },\n      Effect.sandbox,\n      (effect, shardId) =>\n        effect.pipe(\n          Effect.tapError((cause) =>\n            Effect.logDebug(`Could not release shard, retrying`, cause).pipe(\n              Effect.annotateLogs({\n                package: \"@effect/cluster\",\n                module: \"Sharding\",\n                fiber: \"releaseShard\",\n                runner: selfAddress,\n                shardId\n              })\n            )\n          ),\n          Effect.eventually,\n          FiberMap.run(releaseShardsMap, shardId, { onlyIfMissing: true })\n        )\n    )\n    const releaseShards = Effect.gen(function*() {\n      for (const shardId of releasingShards) {\n        if (FiberMap.unsafeHas(releaseShardsMap, shardId)) continue\n        yield* releaseShard(shardId)\n      }\n    })\n\n    yield* Effect.gen(function*() {\n      activeShardsLatch.unsafeOpen()\n\n      while (true) {\n        yield* activeShardsLatch.await\n        activeShardsLatch.unsafeClose()\n\n        // if a shard is no longer assigned to this runner, we release it\n        for (const shardId of acquiredShards) {\n          if (MutableHashSet.has(selfShards, shardId)) continue\n          MutableHashSet.remove(acquiredShards, shardId)\n          MutableHashSet.add(releasingShards, shardId)\n        }\n\n        if (MutableHashSet.size(releasingShards) > 0) {\n          yield* Effect.forkIn(syncSingletons, shardingScope)\n          yield* releaseShards\n        }\n\n        // if a shard has been assigned to this runner, we acquire it\n        const unacquiredShards = MutableHashSet.empty<ShardId>()\n        for (const shardId of selfShards) {\n          if (MutableHashSet.has(acquiredShards, shardId) || MutableHashSet.has(releasingShards, shardId)) continue\n          MutableHashSet.add(unacquiredShards, shardId)\n        }\n\n        if (MutableHashSet.size(unacquiredShards) === 0) {\n          continue\n        }\n\n        const oacquired = yield* runnerStorage.acquire(selfAddress, unacquiredShards).pipe(\n          Effect.timeoutOption(config.shardLockRefreshInterval)\n        )\n        if (Option.isNone(oacquired)) {\n          activeShardsLatch.unsafeOpen()\n          continue\n        }\n\n        const acquired = oacquired.value\n        yield* storage.resetShards(acquired).pipe(\n          Effect.ignore,\n          Effect.timeoutOption(config.shardLockRefreshInterval)\n        )\n        for (const shardId of acquired) {\n          if (MutableHashSet.has(releasingShards, shardId) || !MutableHashSet.has(selfShards, shardId)) {\n            continue\n          }\n          MutableHashSet.add(acquiredShards, shardId)\n        }\n        if (acquired.length > 0) {\n          yield* storageReadLatch.open\n          yield* Effect.forkIn(syncSingletons, shardingScope)\n\n          // update metrics\n          ClusterMetrics.shards.unsafeUpdate(BigInt(MutableHashSet.size(acquiredShards)), [])\n        }\n        yield* Effect.sleep(1000)\n        activeShardsLatch.unsafeOpen()\n      }\n    }).pipe(\n      Effect.catchAllCause((cause) => Effect.logWarning(\"Could not acquire/release shards\", cause)),\n      Effect.repeat(Schedule.spaced(config.entityMessagePollInterval)),\n      Effect.annotateLogs({\n        package: \"@effect/cluster\",\n        module: \"Sharding\",\n        fiber: \"Shard acquisition loop\",\n        runner: selfAddress\n      }),\n      Effect.forkIn(shardingScope),\n      Effect.interruptible\n    )\n\n    // refresh the shard locks every `shardLockRefreshInterval`\n    yield* Effect.suspend(() =>\n      runnerStorage.refresh(selfAddress, [\n        ...acquiredShards,\n        ...releasingShards\n      ])\n    ).pipe(\n      Effect.flatMap((acquired) => {\n        for (const shardId of acquiredShards) {\n          if (!acquired.includes(shardId)) {\n            MutableHashSet.remove(acquiredShards, shardId)\n            MutableHashSet.add(releasingShards, shardId)\n          }\n        }\n        for (let i = 0; i < acquired.length; i++) {\n          const shardId = acquired[i]\n          if (!MutableHashSet.has(selfShards, shardId)) {\n            MutableHashSet.remove(acquiredShards, shardId)\n            MutableHashSet.add(releasingShards, shardId)\n          }\n        }\n        return MutableHashSet.size(releasingShards) > 0\n          ? activeShardsLatch.open\n          : Effect.void\n      }),\n      Effect.retry({\n        times: 5,\n        schedule: Schedule.spaced(50)\n      }),\n      Effect.catchAllCause((cause) =>\n        Effect.logError(\"Could not refresh shard locks\", cause).pipe(\n          Effect.andThen(clearSelfShards)\n        )\n      ),\n      Effect.repeat(Schedule.fixed(config.shardLockRefreshInterval)),\n      Effect.forever,\n      Effect.forkIn(shardingScope),\n      Effect.interruptible\n    )\n\n    // open the shard latch every poll interval\n    yield* activeShardsLatch.open.pipe(\n      Effect.delay(config.entityMessagePollInterval),\n      Effect.forever,\n      Effect.forkIn(shardingScope),\n      Effect.interruptible\n    )\n  }\n\n  const clearSelfShards = Effect.sync(() => {\n    MutableHashSet.clear(selfShards)\n    activeShardsLatch.unsafeOpen()\n  })\n\n  // --- Storage inbox ---\n  //\n  // Responsible for reading unprocessed messages from storage and sending them\n  // to the appropriate entity manager.\n  //\n  // This should be shutdown before shard acquisition, to ensure no messages are\n  // being processed before the shards are released.\n  //\n  // It should also be shutdown after the entity managers, to ensure interrupt\n  // & ack envelopes can still be processed.\n\n  const storageReadLatch = yield* Effect.makeLatch(true)\n  const openStorageReadLatch = constant(storageReadLatch.open)\n\n  const storageReadLock = Effect.unsafeMakeSemaphore(1)\n  const withStorageReadLock = storageReadLock.withPermits(1)\n\n  if (storageEnabled && Option.isSome(config.runnerAddress)) {\n    const selfAddress = config.runnerAddress.value\n    const entityRegistrationTimeoutMillis = Duration.toMillis(config.entityRegistrationTimeout)\n    const storageStartMillis = clock.unsafeCurrentTimeMillis()\n\n    yield* Effect.gen(function*() {\n      yield* Effect.logDebug(\"Starting\")\n      yield* Effect.addFinalizer(() => Effect.logDebug(\"Shutting down\"))\n\n      let index = 0\n      let messages: Array<Message.Incoming<any>> = []\n      const removableNotifications = new Set<PendingNotification>()\n      const resetAddresses = MutableHashSet.empty<EntityAddress>()\n\n      const processMessages = Effect.whileLoop({\n        while: () => index < messages.length,\n        step: () => index++,\n        body: () => send\n      })\n\n      const send = Effect.catchAllCause(\n        Effect.suspend(() => {\n          const message = messages[index]\n          const address = message.envelope.address\n          if (!MutableHashSet.has(acquiredShards, address.shardId)) {\n            return Effect.void\n          }\n          const state = entityManagers.get(address.entityType)\n          if (!state) {\n            const sinceStart = clock.unsafeCurrentTimeMillis() - storageStartMillis\n            if (sinceStart < entityRegistrationTimeoutMillis) {\n              // reset address in the case that the entity is slow to register\n              MutableHashSet.add(resetAddresses, address)\n              return Effect.void\n            }\n            // if the entity did not register in time, we save a defect reply\n            return Effect.die(new Error(`Entity type '${address.entityType}' not registered`))\n          } else if (state.status === \"closed\") {\n            return Effect.void\n          }\n\n          const isProcessing = state.manager.isProcessingFor(message)\n\n          if (message._tag === \"IncomingEnvelope\" && isProcessing) {\n            // If the message might affect a currently processing request, we\n            // send it to the entity manager to be processed.\n            return state.manager.send(message)\n          } else if (isProcessing || state.status === \"closing\") {\n            // If the request is already processing, we skip it.\n            // Or if the entity is closing, we skip all incoming messages.\n            return Effect.void\n          } else if (message._tag === \"IncomingRequest\" && pendingNotifications.has(message.envelope.requestId)) {\n            const entry = pendingNotifications.get(message.envelope.requestId)!\n            pendingNotifications.delete(message.envelope.requestId)\n            removableNotifications.delete(entry)\n            entry.resume(Effect.void)\n          }\n\n          // If the entity was resuming in another fiber, we add the message\n          // id to the unprocessed set.\n          const resumptionState = MutableHashMap.get(entityResumptionState, address)\n          if (Option.isSome(resumptionState)) {\n            resumptionState.value.unprocessed.add(message.envelope.requestId)\n            if (message.envelope._tag === \"Interrupt\") {\n              resumptionState.value.interrupts.set(message.envelope.requestId, message as Message.IncomingEnvelope)\n            }\n            return Effect.void\n          }\n          return state.manager.send(message)\n        }),\n        (cause) => {\n          const message = messages[index]\n          const error = Cause.failureOrCause(cause)\n          // if we get a defect, then update storage\n          if (Either.isRight(error)) {\n            if (Cause.isInterrupted(cause)) {\n              return Effect.void\n            }\n            return Effect.ignore(storage.saveReply(Reply.ReplyWithContext.fromDefect({\n              id: snowflakeGen.unsafeNext(),\n              requestId: message.envelope.requestId,\n              defect: Cause.squash(cause)\n            })))\n          }\n          if (error.left._tag === \"MailboxFull\") {\n            // MailboxFull can only happen for requests, so this cast is safe\n            return resumeEntityFromStorage(message as Message.IncomingRequest<any>)\n          }\n          return Effect.void\n        }\n      )\n\n      while (true) {\n        // wait for the next poll interval, or if we get notified of a change\n        yield* storageReadLatch.await\n\n        // if we get notified of a change, ensure we start a read immediately\n        // next iteration\n        storageReadLatch.unsafeClose()\n\n        // the lock is used to ensure resuming entities have a garantee that no\n        // more items are added to the unprocessed set while the semaphore is\n        // acquired.\n        yield* storageReadLock.take(1)\n\n        entityManagers.forEach((state) => state.manager.clearProcessed())\n        if (pendingNotifications.size > 0) {\n          pendingNotifications.forEach((entry) => removableNotifications.add(entry))\n        }\n\n        messages = yield* storage.unprocessedMessages(acquiredShards)\n        index = 0\n        yield* processMessages\n\n        if (removableNotifications.size > 0) {\n          removableNotifications.forEach(({ message, resume }) => {\n            pendingNotifications.delete(message.envelope.requestId)\n            resume(Effect.fail(new EntityNotAssignedToRunner({ address: message.envelope.address })))\n          })\n          removableNotifications.clear()\n        }\n        if (MutableHashSet.size(resetAddresses) > 0) {\n          for (const address of resetAddresses) {\n            yield* Effect.logWarning(\"Could not find entity manager for address, retrying\").pipe(\n              Effect.annotateLogs({ address })\n            )\n            yield* Effect.forkIn(storage.resetAddress(address), shardingScope)\n          }\n          MutableHashSet.clear(resetAddresses)\n        }\n\n        // let the resuming entities check if they are done\n        yield* storageReadLock.release(1)\n      }\n    }).pipe(\n      Effect.scoped,\n      Effect.ensuring(storageReadLock.releaseAll),\n      Effect.catchAllCause((cause) => Effect.logWarning(\"Could not read messages from storage\", cause)),\n      Effect.forever,\n      Effect.annotateLogs({\n        package: \"@effect/cluster\",\n        module: \"Sharding\",\n        fiber: \"Storage read loop\",\n        runner: selfAddress\n      }),\n      Effect.withUnhandledErrorLogLevel(Option.none()),\n      Effect.forkIn(shardingScope),\n      Effect.interruptible\n    )\n\n    // open the storage latch every poll interval\n    yield* storageReadLatch.open.pipe(\n      Effect.delay(config.entityMessagePollInterval),\n      Effect.forever,\n      Effect.forkIn(shardingScope),\n      Effect.interruptible\n    )\n\n    // Resume unprocessed messages for entities that reached a full mailbox.\n    const entityResumptionState = MutableHashMap.empty<EntityAddress, {\n      unprocessed: Set<Snowflake.Snowflake>\n      interrupts: Map<Snowflake.Snowflake, Message.IncomingEnvelope>\n    }>()\n    const resumeEntityFromStorage = (lastReceivedMessage: Message.IncomingRequest<any>) => {\n      const address = lastReceivedMessage.envelope.address\n      const resumptionState = MutableHashMap.get(entityResumptionState, address)\n      if (Option.isSome(resumptionState)) {\n        resumptionState.value.unprocessed.add(lastReceivedMessage.envelope.requestId)\n        return Effect.void\n      }\n      MutableHashMap.set(entityResumptionState, address, {\n        unprocessed: new Set([lastReceivedMessage.envelope.requestId]),\n        interrupts: new Map()\n      })\n      return resumeEntityFromStorageImpl(address)\n    }\n    const resumeEntityFromStorageImpl = Effect.fnUntraced(\n      function*(address: EntityAddress) {\n        const state = entityManagers.get(address.entityType)\n        if (!state) {\n          MutableHashMap.remove(entityResumptionState, address)\n          return\n        }\n\n        const resumptionState = Option.getOrThrow(MutableHashMap.get(entityResumptionState, address))\n        let done = false\n\n        while (!done) {\n          // if the shard is no longer assigned to this runner, we stop\n          if (!MutableHashSet.has(acquiredShards, address.shardId)) {\n            return\n          }\n\n          // take a batch of unprocessed messages ids\n          const messageIds = Arr.empty<Snowflake.Snowflake>()\n          for (const id of resumptionState.unprocessed) {\n            if (messageIds.length === 1024) break\n            messageIds.push(id)\n          }\n\n          const messages = yield* storage.unprocessedMessagesById(messageIds)\n\n          // this should not happen, but we handle it just in case\n          if (messages.length === 0) {\n            yield* Effect.sleep(config.entityMessagePollInterval)\n            continue\n          }\n\n          let index = 0\n\n          const sendWithRetry: Effect.Effect<\n            void,\n            EntityNotAssignedToRunner\n          > = Effect.catchTags(\n            Effect.suspend(() => {\n              if (!MutableHashSet.has(acquiredShards, address.shardId)) {\n                return Effect.fail(new EntityNotAssignedToRunner({ address }))\n              }\n\n              const message = messages[index]\n              // check if this is a request that was interrupted\n              const interrupt = message._tag === \"IncomingRequest\" &&\n                resumptionState.interrupts.get(message.envelope.requestId)\n              return interrupt ?\n                Effect.flatMap(state.manager.send(message), () => {\n                  resumptionState.interrupts.delete(message.envelope.requestId)\n                  return state.manager.send(interrupt)\n                }) :\n                state.manager.send(message)\n            }),\n            {\n              MailboxFull: () => Effect.delay(sendWithRetry, config.sendRetryInterval),\n              AlreadyProcessingMessage: () => Effect.void\n            }\n          )\n\n          yield* Effect.whileLoop({\n            while: () => index < messages.length,\n            body: constant(sendWithRetry),\n            step: () => index++\n          })\n\n          for (const id of messageIds) {\n            resumptionState.unprocessed.delete(id)\n          }\n          if (resumptionState.unprocessed.size > 0) continue\n\n          // if we have caught up to the main storage loop, we let it take over\n          yield* withStorageReadLock(Effect.sync(() => {\n            if (resumptionState.unprocessed.size === 0) {\n              MutableHashMap.remove(entityResumptionState, address)\n              done = true\n            }\n          }))\n        }\n      },\n      Effect.retry({\n        while: (e) => e._tag === \"PersistenceError\",\n        schedule: Schedule.spaced(config.entityMessagePollInterval)\n      }),\n      Effect.catchAllCause((cause) => Effect.logDebug(\"Could not resume unprocessed messages\", cause)),\n      (effect, address) =>\n        Effect.annotateLogs(effect, {\n          package: \"@effect/cluster\",\n          module: \"Sharding\",\n          fiber: \"Resuming unprocessed messages\",\n          runner: selfAddress,\n          entity: address\n        }),\n      (effect, address) =>\n        Effect.ensuring(\n          effect,\n          Effect.sync(() => MutableHashMap.remove(entityResumptionState, address))\n        ),\n      Effect.withUnhandledErrorLogLevel(Option.none()),\n      Effect.forkIn(shardingScope),\n      Effect.interruptible\n    )\n  }\n\n  // --- Sending messages ---\n\n  const sendLocal = <M extends Message.Outgoing<any> | Message.Incoming<any>>(message: M) =>\n    Effect.suspend(function loop(): Effect.Effect<\n      void,\n      | EntityNotAssignedToRunner\n      | MailboxFull\n      | AlreadyProcessingMessage\n      | (M extends Message.Incoming<any> ? never : PersistenceError)\n    > {\n      const address = message.envelope.address\n      if (!isEntityOnLocalShards(address)) {\n        return Effect.fail(new EntityNotAssignedToRunner({ address }))\n      }\n      const state = entityManagers.get(address.entityType)\n      if (!state) {\n        return Effect.flatMap(waitForEntityManager(address.entityType), loop)\n      } else if (state.status === \"closed\" || (state.status === \"closing\" && message._tag === \"IncomingRequest\")) {\n        // if we are shutting down, we don't accept new requests\n        return Effect.fail(new EntityNotAssignedToRunner({ address }))\n      }\n\n      return message._tag === \"IncomingRequest\" || message._tag === \"IncomingEnvelope\" ?\n        state.manager.send(message) :\n        runnersService.sendLocal({\n          message,\n          send: state.manager.sendLocal,\n          simulateRemoteSerialization: config.simulateRemoteSerialization\n        }) as any\n    })\n\n  type PendingNotification = {\n    resume: (_: Effect.Effect<void, EntityNotAssignedToRunner>) => void\n    readonly message: Message.IncomingRequest<any>\n  }\n  const pendingNotifications = new Map<Snowflake.Snowflake, PendingNotification>()\n  const notifyLocal = <M extends Message.Outgoing<any> | Message.Incoming<any>>(\n    message: M,\n    discard: boolean,\n    options?: {\n      readonly waitUntilRead?: boolean | undefined\n    }\n  ) =>\n    Effect.suspend(function loop(): Effect.Effect<\n      void,\n      | EntityNotAssignedToRunner\n      | AlreadyProcessingMessage\n      | (M extends Message.Incoming<any> ? never : PersistenceError)\n    > {\n      const address = message.envelope.address\n      const state = entityManagers.get(address.entityType)\n      if (!state) {\n        return Effect.flatMap(waitForEntityManager(address.entityType), loop)\n      } else if (state.status === \"closed\" || !isEntityOnLocalShards(address)) {\n        return Effect.fail(new EntityNotAssignedToRunner({ address }))\n      }\n\n      const isLocal = isEntityOnLocalShards(address)\n      const notify = storageEnabled\n        ? openStorageReadLatch\n        : () => Effect.die(\"Sharding.notifyLocal: storage is disabled\")\n\n      if (message._tag === \"IncomingRequest\" || message._tag === \"IncomingEnvelope\") {\n        if (!isLocal) {\n          return Effect.fail(new EntityNotAssignedToRunner({ address }))\n        } else if (\n          message._tag === \"IncomingRequest\" && state.manager.isProcessingFor(message, { excludeReplies: true })\n        ) {\n          return Effect.fail(new AlreadyProcessingMessage({ address, envelopeId: message.envelope.requestId }))\n        } else if (message._tag === \"IncomingRequest\" && options?.waitUntilRead) {\n          if (!storageEnabled) return notify()\n          return Effect.async<void, EntityNotAssignedToRunner>((resume) => {\n            let entry = pendingNotifications.get(message.envelope.requestId)\n            if (entry) {\n              const prevResume = entry.resume\n              entry.resume = (effect) => {\n                prevResume(effect)\n                resume(effect)\n              }\n              return\n            }\n            entry = { resume, message }\n            pendingNotifications.set(message.envelope.requestId, entry)\n            storageReadLatch.unsafeOpen()\n          })\n        }\n        return notify()\n      }\n\n      return runnersService.notifyLocal({ message, notify, discard, storageOnly: !isLocal }) as any\n    })\n\n  function sendOutgoing(\n    message: Message.Outgoing<any>,\n    discard: boolean,\n    retries?: number\n  ): Effect.Effect<\n    void,\n    MailboxFull | AlreadyProcessingMessage | PersistenceError\n  > {\n    return Effect.catchIf(\n      Effect.suspend(() => {\n        const address = message.envelope.address\n        const isPersisted = Context.get(message.rpc.annotations, Persisted)\n        if (isPersisted && !storageEnabled) {\n          return Effect.die(\"Sharding.sendOutgoing: Persisted messages require MessageStorage\")\n        }\n        const maybeRunner = MutableHashMap.get(shardAssignments, address.shardId)\n        const runnerIsLocal = Option.isSome(maybeRunner) && isLocalRunner(maybeRunner.value)\n        if (isPersisted) {\n          return runnerIsLocal\n            ? notifyLocal(message, discard)\n            : runnersService.notify({ address: maybeRunner, message, discard })\n        } else if (Option.isNone(maybeRunner)) {\n          return Effect.fail(new EntityNotAssignedToRunner({ address }))\n        }\n        return runnerIsLocal\n          ? sendLocal(message)\n          : runnersService.send({ address: maybeRunner.value, message })\n      }),\n      (error) => error._tag === \"EntityNotAssignedToRunner\" || error._tag === \"RunnerUnavailable\",\n      (error) => {\n        if (retries === 0) {\n          return Effect.die(error)\n        }\n        return Effect.delay(sendOutgoing(message, discard, retries && retries - 1), config.sendRetryInterval)\n      }\n    )\n  }\n\n  const reset: Sharding[\"Type\"][\"reset\"] = (requestId) =>\n    Effect.matchCause(storage.clearReplies(requestId), {\n      onSuccess: () => true,\n      onFailure: () => false\n    })\n\n  // --- RunnerStorage sync ---\n  //\n  // This is responsible for syncing the local view of runners and shard\n  // assignments with RunnerStorage.\n  //\n  // It should be shutdown after the clients, so that they can still get correct\n  // shard assignments for outgoing messages (they could still be in use by\n  // entities that are shutting down).\n\n  const selfRunner = Option.isSome(config.runnerAddress) ?\n    new Runner({\n      address: config.runnerAddress.value,\n      groups: config.shardGroups,\n      weight: config.runnerShardWeight\n    }) :\n    undefined\n\n  let allRunners = MutableHashMap.empty<Runner, boolean>()\n  let healthyRunnerCount = 0\n\n  // update metrics\n  if (selfRunner) {\n    ClusterMetrics.runners.unsafeUpdate(BigInt(1), [])\n    ClusterMetrics.runnersHealthy.unsafeUpdate(BigInt(1), [])\n  }\n\n  yield* Effect.gen(function*() {\n    const hashRings = new Map<string, HashRing.HashRing<RunnerAddress>>()\n    let nextRunners = MutableHashMap.empty<Runner, boolean>()\n    const healthyRunners = MutableHashSet.empty<Runner>()\n    const withTimeout = Effect.timeout(Duration.seconds(5))\n\n    while (true) {\n      // Ensure the current runner is registered\n      if (selfRunner && !isShutdown.current && !MutableHashMap.has(allRunners, selfRunner)) {\n        yield* Effect.logDebug(\"Registering runner\", selfRunner)\n        const machineId = yield* withTimeout(runnerStorage.register(selfRunner, true))\n        yield* snowflakeGen.setMachineId(machineId)\n      }\n\n      const runners = yield* withTimeout(runnerStorage.getRunners)\n      let changed = false\n      for (let i = 0; i < runners.length; i++) {\n        const [runner, healthy] = runners[i]\n        MutableHashMap.set(nextRunners, runner, healthy)\n        const wasHealthy = MutableHashSet.has(healthyRunners, runner)\n        if (!healthy || wasHealthy) {\n          if (healthy === wasHealthy || !wasHealthy) {\n            // no change\n            MutableHashMap.remove(allRunners, runner)\n          }\n          continue\n        }\n        changed = true\n        MutableHashSet.add(healthyRunners, runner)\n        MutableHashMap.remove(allRunners, runner)\n        for (let j = 0; j < runner.groups.length; j++) {\n          const group = runner.groups[j]\n          let ring = hashRings.get(group)\n          if (!ring) {\n            ring = HashRing.make()\n            hashRings.set(group, ring)\n          }\n          HashRing.add(ring, runner.address, { weight: runner.weight })\n        }\n      }\n\n      // Remove runners that are no longer present or healthy\n      MutableHashMap.forEach(allRunners, (_, runner) => {\n        changed = true\n        MutableHashMap.remove(allRunners, runner)\n        MutableHashSet.remove(healthyRunners, runner)\n        runFork(runnersService.onRunnerUnavailable(runner.address))\n        for (let i = 0; i < runner.groups.length; i++) {\n          HashRing.remove(hashRings.get(runner.groups[i])!, runner.address)\n        }\n      })\n\n      // swap allRunners and nextRunners\n      const prevRunners = allRunners\n      allRunners = nextRunners\n      nextRunners = prevRunners\n      healthyRunnerCount = MutableHashSet.size(healthyRunners)\n\n      // Ensure the current runner is registered\n      if (selfRunner && !isShutdown.current && !MutableHashMap.has(allRunners, selfRunner)) {\n        continue\n      }\n\n      // Recompute shard assignments if the set of healthy runners has changed.\n      if (changed) {\n        MutableHashSet.clear(selfShards)\n        hashRings.forEach((ring, group) => {\n          const newAssignments = HashRing.getShards(ring, config.shardsPerGroup)\n          for (let i = 0; i < config.shardsPerGroup; i++) {\n            const shard = makeShardId(group, i + 1)\n            if (newAssignments) {\n              const runner = newAssignments[i]\n              MutableHashMap.set(shardAssignments, shard, runner)\n              if (isLocalRunner(runner)) {\n                MutableHashSet.add(selfShards, shard)\n              }\n            } else {\n              MutableHashMap.remove(shardAssignments, shard)\n            }\n          }\n        })\n        yield* Effect.logDebug(\"New shard assignments\", selfShards)\n        activeShardsLatch.unsafeOpen()\n\n        // update metrics\n        if (selfRunner) {\n          ClusterMetrics.runnersHealthy.unsafeUpdate(\n            BigInt(MutableHashSet.has(healthyRunners, selfRunner) ? 1 : 0),\n            []\n          )\n        }\n      }\n\n      if (selfRunner && MutableHashSet.size(healthyRunners) === 0) {\n        yield* Effect.logWarning(\"No healthy runners available\")\n        // to prevent a deadlock, we will mark the current node as healthy to\n        // start the health check singleton again\n        yield* withTimeout(runnerStorage.setRunnerHealth(selfRunner.address, true))\n      }\n\n      yield* Effect.sleep(config.refreshAssignmentsInterval)\n    }\n  }).pipe(\n    Effect.catchAllCause((cause) => Effect.logDebug(cause)),\n    Effect.repeat(Schedule.spaced(1000)),\n    Effect.annotateLogs({\n      package: \"@effect/cluster\",\n      module: \"Sharding\",\n      fiber: \"RunnerStorage sync\",\n      runner: config.runnerAddress\n    }),\n    Effect.forkIn(shardingScope),\n    Effect.interruptible\n  )\n\n  // --- Clients ---\n\n  type ClientRequestEntry = {\n    readonly rpc: Rpc.AnyWithProps\n    readonly services: Context.Context<never>\n    lastChunkId?: Snowflake.Snowflake\n  }\n  const clientRequests = new Map<Snowflake.Snowflake, ClientRequestEntry>()\n\n  const clients: ResourceMap<\n    Entity<any, any>,\n    (entityId: string) => RpcClient.RpcClient<\n      any,\n      MailboxFull | AlreadyProcessingMessage\n    >,\n    never\n  > = yield* ResourceMap.make(Effect.fnUntraced(function*(entity: Entity<string, any>) {\n    const client = yield* RpcClient.makeNoSerialization(entity.protocol, {\n      spanPrefix: `${entity.type}.client`,\n      disableTracing: !Context.get(entity.protocol.annotations, ClusterSchema.ClientTracingEnabled),\n      supportsAck: true,\n      generateRequestId: () => RequestId(snowflakeGen.unsafeNext()),\n      flatten: true,\n      onFromClient(options): Effect.Effect<\n        void,\n        MailboxFull | AlreadyProcessingMessage | PersistenceError\n      > {\n        const address = Context.unsafeGet(options.context, ClientAddressTag)\n        switch (options.message._tag) {\n          case \"Request\": {\n            const fiber = Option.getOrThrow(Fiber.getCurrentFiber())\n            const id = Snowflake.Snowflake(options.message.id)\n            const rpc = entity.protocol.requests.get(options.message.tag)!\n            let respond: (reply: Reply.Reply<any>) => Effect.Effect<void>\n            if (!options.discard) {\n              const entry: ClientRequestEntry = {\n                rpc: rpc as any,\n                services: fiber.currentContext\n              }\n              clientRequests.set(id, entry)\n              respond = makeClientRespond(entry, client.write)\n            } else {\n              respond = clientRespondDiscard\n            }\n            return sendOutgoing(\n              new Message.OutgoingRequest({\n                envelope: Envelope.makeRequest({\n                  requestId: id,\n                  address,\n                  tag: options.message.tag,\n                  payload: options.message.payload,\n                  headers: options.message.headers,\n                  traceId: options.message.traceId,\n                  spanId: options.message.spanId,\n                  sampled: options.message.sampled\n                }),\n                lastReceivedReply: Option.none(),\n                rpc,\n                context: fiber.currentContext as Context.Context<any>,\n                respond\n              }),\n              options.discard\n            )\n          }\n          case \"Ack\": {\n            const requestId = Snowflake.Snowflake(options.message.requestId)\n            const entry = clientRequests.get(requestId)\n            if (!entry) return Effect.void\n            return sendOutgoing(\n              new Message.OutgoingEnvelope({\n                envelope: new Envelope.AckChunk({\n                  id: snowflakeGen.unsafeNext(),\n                  address,\n                  requestId,\n                  replyId: entry.lastChunkId!\n                }),\n                rpc: entry.rpc\n              }),\n              false\n            )\n          }\n          case \"Interrupt\": {\n            const requestId = Snowflake.Snowflake(options.message.requestId)\n            const entry = clientRequests.get(requestId)!\n            if (!entry) return Effect.void\n            clientRequests.delete(requestId)\n            if (Uninterruptible.forClient(entry.rpc.annotations)) {\n              return Effect.void\n            }\n            // for durable messages, we ignore interrupts on shutdown or as a\n            // result of a shard being resassigned\n            const isTransientInterrupt = MutableRef.get(isShutdown) ||\n              options.message.interruptors.some((id) => internalInterruptors.has(id))\n            if (isTransientInterrupt && Context.get(entry.rpc.annotations, Persisted)) {\n              return Effect.void\n            }\n            return Effect.ignore(sendOutgoing(\n              new Message.OutgoingEnvelope({\n                envelope: new Envelope.Interrupt({\n                  id: snowflakeGen.unsafeNext(),\n                  address,\n                  requestId\n                }),\n                rpc: entry.rpc\n              }),\n              false,\n              3\n            ))\n          }\n        }\n        return Effect.void\n      }\n    })\n\n    yield* Scope.addFinalizer(\n      yield* Effect.scope,\n      Effect.fiberIdWith((fiberId) => {\n        internalInterruptors.add(fiberId)\n        return Effect.void\n      })\n    )\n\n    return (entityId: string) => {\n      const id = makeEntityId(entityId)\n      const address = ClientAddressTag.context(makeEntityAddress({\n        shardId: getShardId(id, entity.getShardGroup(entityId as EntityId)),\n        entityId: id,\n        entityType: entity.type\n      }))\n      const clientFn = function(tag: string, payload: any, options?: {\n        readonly context?: Context.Context<never>\n      }) {\n        const context = options?.context ? Context.merge(options.context, address) : address\n        return client.client(tag, payload, {\n          ...options,\n          context\n        })\n      }\n      const proxyClient: any = {}\n      return new Proxy(proxyClient, {\n        has(_, p) {\n          return entity.protocol.requests.has(p as string)\n        },\n        get(target, p) {\n          if (p in target) {\n            return target[p]\n          } else if (!entity.protocol.requests.has(p as string)) {\n            return undefined\n          }\n          return target[p] = (payload: any, options?: {}) => clientFn(p as string, payload, options)\n        }\n      })\n    }\n  }))\n\n  const makeClient = <Type extends string, Rpcs extends Rpc.Any>(entity: Entity<Type, Rpcs>): Effect.Effect<\n    (\n      entityId: string\n    ) => RpcClient.RpcClient.From<Rpcs, MailboxFull | AlreadyProcessingMessage>\n  > => clients.get(entity) as any\n\n  const clientRespondDiscard = (_reply: Reply.Reply<any>) => Effect.void\n\n  const makeClientRespond = (\n    entry: ClientRequestEntry,\n    write: (reply: FromServer<any>) => Effect.Effect<void>\n  ) =>\n  (reply: Reply.Reply<any>) => {\n    switch (reply._tag) {\n      case \"Chunk\": {\n        entry.lastChunkId = reply.id\n        return write({\n          _tag: \"Chunk\",\n          clientId: 0,\n          requestId: RequestId(reply.requestId),\n          values: reply.values\n        })\n      }\n      case \"WithExit\": {\n        clientRequests.delete(reply.requestId)\n        return write({\n          _tag: \"Exit\",\n          clientId: 0,\n          requestId: RequestId(reply.requestId),\n          exit: reply.exit\n        })\n      }\n    }\n  }\n\n  // --- Singletons ---\n\n  const singletons = new Map<ShardId, MutableHashMap.MutableHashMap<SingletonAddress, Effect.Effect<void>>>()\n  const singletonFibers = yield* FiberMap.make<SingletonAddress>()\n  const withSingletonLock = Effect.unsafeMakeSemaphore(1).withPermits(1)\n\n  const registerSingleton: Sharding[\"Type\"][\"registerSingleton\"] = Effect.fnUntraced(\n    function*(name, run, options) {\n      const shardGroup = options?.shardGroup ?? \"default\"\n      const address = new SingletonAddress({\n        shardId: getShardId(makeEntityId(name), shardGroup),\n        name\n      })\n\n      let map = singletons.get(address.shardId)\n      if (!map) {\n        map = MutableHashMap.empty()\n        singletons.set(address.shardId, map)\n      }\n      if (MutableHashMap.has(map, address)) {\n        return yield* Effect.die(`Singleton '${name}' is already registered`)\n      }\n\n      const context = yield* Effect.context<never>()\n      const wrappedRun = run.pipe(\n        Effect.locally(FiberRef.currentLogAnnotations, HashMap.empty()),\n        Effect.andThen(Effect.never),\n        Effect.scoped,\n        Effect.provide(context),\n        Effect.orDie,\n        Effect.interruptible\n      ) as Effect.Effect<never>\n      MutableHashMap.set(map, address, wrappedRun)\n\n      yield* PubSub.publish(events, SingletonRegistered({ address }))\n\n      // start if we are on the right shard\n      if (MutableHashSet.has(acquiredShards, address.shardId)) {\n        yield* Effect.logDebug(\"Starting singleton\", address)\n        yield* FiberMap.run(singletonFibers, address, wrappedRun)\n      }\n\n      yield* Effect.addFinalizer(() => {\n        const map = singletons.get(address.shardId)!\n        MutableHashMap.remove(map, address)\n        return FiberMap.remove(singletonFibers, address)\n      })\n    },\n    withSingletonLock\n  )\n\n  const syncSingletons = withSingletonLock(Effect.gen(function*() {\n    for (const [shardId, map] of singletons) {\n      for (const [address, run] of map) {\n        const running = FiberMap.unsafeHas(singletonFibers, address)\n        const shouldBeRunning = MutableHashSet.has(acquiredShards, shardId)\n        if (running && !shouldBeRunning) {\n          yield* Effect.logDebug(\"Stopping singleton\", address)\n          internalInterruptors.add(Option.getOrThrow(Fiber.getCurrentFiber()).id())\n          yield* FiberMap.remove(singletonFibers, address)\n        } else if (!running && shouldBeRunning) {\n          yield* Effect.logDebug(\"Starting singleton\", address)\n          yield* FiberMap.run(singletonFibers, address, run)\n        }\n      }\n    }\n    ClusterMetrics.singletons.unsafeUpdate(\n      BigInt(yield* FiberMap.size(singletonFibers)),\n      []\n    )\n  }))\n\n  // --- Entities ---\n\n  const context = yield* Effect.context<ShardingConfig>()\n  const reaper = yield* EntityReaper\n  const entityManagerLatches = new Map<string, Effect.Latch>()\n\n  const registerEntity: Sharding[\"Type\"][\"registerEntity\"] = Effect.fnUntraced(\n    function*(entity, build, options) {\n      if (Option.isNone(config.runnerAddress) || entityManagers.has(entity.type)) return\n      const scope = yield* Effect.scope\n      yield* Scope.addFinalizer(\n        scope,\n        Effect.sync(() => {\n          state.status = \"closed\"\n        })\n      )\n      const manager = yield* EntityManager.make(entity, build, {\n        ...options,\n        storage,\n        runnerAddress: config.runnerAddress.value,\n        sharding\n      }).pipe(\n        Effect.provide(context.pipe(\n          Context.add(EntityReaper, reaper),\n          Context.add(Scope.Scope, scope),\n          Context.add(Snowflake.Generator, snowflakeGen)\n        ))\n      ) as Effect.Effect<EntityManager.EntityManager>\n      const state: EntityManagerState = {\n        entity,\n        status: \"alive\",\n        manager\n      }\n      yield* Scope.addFinalizer(\n        scope,\n        Effect.fiberIdWith((id) => {\n          state.status = \"closing\"\n          internalInterruptors.add(id)\n          // if preemptive shutdown is enabled, we start shutting down Sharding\n          // too\n          return config.preemptiveShutdown ? shutdown() : Effect.void\n        })\n      )\n\n      // register entities while storage is idle\n      // this ensures message order is preserved\n      yield* withStorageReadLock(Effect.sync(() => {\n        entityManagers.set(entity.type, state)\n        if (entityManagerLatches.has(entity.type)) {\n          entityManagerLatches.get(entity.type)!.unsafeOpen()\n          entityManagerLatches.delete(entity.type)\n        }\n      }))\n\n      yield* PubSub.publish(events, EntityRegistered({ entity }))\n    }\n  )\n\n  const waitForEntityManager = (entityType: string) => {\n    let latch = entityManagerLatches.get(entityType)\n    if (!latch) {\n      latch = Effect.unsafeMakeLatch()\n      entityManagerLatches.set(entityType, latch)\n    }\n    return latch.await\n  }\n\n  // --- Runner health checks ---\n\n  if (selfRunner) {\n    const checkRunner = ([runner, healthy]: [Runner, boolean]) =>\n      Effect.flatMap(runnerHealth.isAlive(runner.address), (isAlive) => {\n        if (healthy === isAlive) return Effect.void\n        if (isAlive) {\n          healthyRunnerCount++\n          return Effect.logDebug(`Runner is healthy`, runner).pipe(\n            Effect.andThen(runnerStorage.setRunnerHealth(runner.address, isAlive))\n          )\n        }\n        if (healthyRunnerCount <= 1) {\n          // never mark the last runner as unhealthy, to prevent a deadlock\n          return Effect.void\n        }\n        healthyRunnerCount--\n        return Effect.logDebug(`Runner is unhealthy`, runner).pipe(\n          Effect.andThen(runnerStorage.setRunnerHealth(runner.address, isAlive))\n        )\n      })\n\n    yield* registerSingleton(\n      \"effect/cluster/Sharding/RunnerHealth\",\n      Effect.gen(function*() {\n        while (true) {\n          // Skip health checks if we are the only runner\n          if (MutableHashMap.size(allRunners) > 1) {\n            yield* Effect.forEach(allRunners, checkRunner, { discard: true, concurrency: 10 })\n          }\n          yield* Effect.sleep(config.runnerHealthCheckInterval)\n        }\n      }).pipe(\n        Effect.catchAllCause((cause) => Effect.logDebug(\"Runner health check failed\", cause)),\n        Effect.forever,\n        Effect.annotateLogs({\n          package: \"@effect/cluster\",\n          module: \"Sharding\",\n          fiber: \"Runner health check\"\n        })\n      )\n    )\n  }\n\n  // --- Finalization ---\n\n  const shutdown = Effect.fnUntraced(function*(exit?: Exit.Exit<unknown, unknown>) {\n    if (exit) {\n      yield* Effect.logDebug(\"Shutting down\", exit._tag === \"Failure\" ? exit.cause : {}).pipe(\n        Effect.annotateLogs({\n          package: \"@effect/cluster\",\n          module: \"Sharding\"\n        })\n      )\n    }\n\n    internalInterruptors.add(yield* Effect.fiberId)\n    if (isShutdown.current) return\n\n    MutableRef.set(isShutdown, true)\n    if (selfRunner) {\n      yield* Effect.ignore(runnerStorage.unregister(selfRunner.address))\n    }\n  })\n\n  yield* Scope.addFinalizerExit(shardingScope, shutdown)\n\n  const activeEntityCount = Effect.gen(function*() {\n    let count = 0\n    for (const state of entityManagers.values()) {\n      count += yield* state.manager.activeEntityCount\n    }\n    return count\n  })\n\n  const sharding = Sharding.of({\n    getRegistrationEvents,\n    getShardId,\n    hasShardId(shardId: ShardId) {\n      if (isShutdown.current) return false\n      return MutableHashSet.has(acquiredShards, shardId)\n    },\n    getSnowflake: Effect.sync(() => snowflakeGen.unsafeNext()),\n    isShutdown: Effect.sync(() => MutableRef.get(isShutdown)),\n    registerEntity,\n    registerSingleton,\n    makeClient,\n    send: sendLocal,\n    sendOutgoing: (message, discard) => sendOutgoing(message, discard),\n    notify: (message, options) => notifyLocal(message, false, options),\n    activeEntityCount,\n    pollStorage: storageReadLatch.open,\n    reset\n  })\n\n  return sharding\n})\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer.Layer<\n  Sharding,\n  never,\n  ShardingConfig | Runners | MessageStorage.MessageStorage | RunnerStorage | RunnerHealth.RunnerHealth\n> = Layer.scoped(Sharding)(make).pipe(\n  Layer.provide([Snowflake.layerGenerator, EntityReaper.Default])\n)\n\n// Utilities\n\nconst ClientAddressTag = Context.GenericTag<EntityAddress>(\"@effect/cluster/Sharding/ClientAddress\")\n"
  },
  {
    "path": "packages/cluster/src/ShardingConfig.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Config from \"effect/Config\"\nimport type { ConfigError } from \"effect/ConfigError\"\nimport * as ConfigProvider from \"effect/ConfigProvider\"\nimport * as Context from \"effect/Context\"\nimport type { DurationInput } from \"effect/Duration\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport { RunnerAddress } from \"./RunnerAddress.js\"\n\n/**\n * Represents the configuration for the `Sharding` service on a given runner.\n *\n * @since 1.0.0\n * @category models\n */\nexport class ShardingConfig extends Context.Tag(\"@effect/cluster/ShardingConfig\")<ShardingConfig, {\n  /**\n   * The address for the current runner that other runners can use to\n   * communicate with it.\n   *\n   * If `None`, the runner is not part of the cluster and will be in a client-only\n   * mode.\n   */\n  readonly runnerAddress: Option.Option<RunnerAddress>\n  /**\n   * The listen address for the current runner.\n   *\n   * Defaults to the `runnerAddress`.\n   */\n  readonly runnerListenAddress: Option.Option<RunnerAddress>\n  /**\n   * A number that determines how many shards this runner will be assigned\n   * relative to other runners.\n   *\n   * Defaults to `1`.\n   *\n   * A value of `2` means that this runner should be assigned twice as many\n   * shards as a runner with a weight of `1`.\n   */\n  readonly runnerShardWeight: number\n  /**\n   * The shard groups that are assigned to this runner.\n   *\n   * Defaults to `[\"default\"]`.\n   */\n  readonly shardGroups: ReadonlyArray<string>\n  /**\n   * The number of shards to allocate per shard group.\n   *\n   * **Note**: this value should be consistent across all runners.\n   */\n  readonly shardsPerGroup: number\n  /**\n   * Shard lock refresh interval.\n   */\n  readonly shardLockRefreshInterval: DurationInput\n  /**\n   * Shard lock expiration duration.\n   */\n  readonly shardLockExpiration: DurationInput\n  /**\n   * Disable the use of advisory locks for shard locking.\n   */\n  readonly shardLockDisableAdvisory: boolean\n  /**\n   * Start shutting down as soon as an Entity has started shutting down.\n   *\n   * Defaults to `true`.\n   */\n  readonly preemptiveShutdown: boolean\n  /**\n   * The default capacity of the mailbox for entities.\n   */\n  readonly entityMailboxCapacity: number | \"unbounded\"\n  /**\n   * The maximum duration of inactivity (i.e. without receiving a message)\n   * after which an entity will be interrupted.\n   */\n  readonly entityMaxIdleTime: DurationInput\n  /**\n   * If an entity does not register itself within this time after a message is\n   * sent to it, the message will be marked as failed.\n   *\n   * Defaults to 1 minute.\n   */\n  readonly entityRegistrationTimeout: DurationInput\n  /**\n   * The maximum duration of time to wait for an entity to terminate.\n   *\n   * By default this is set to 15 seconds to stay within kubernetes defaults.\n   */\n  readonly entityTerminationTimeout: DurationInput\n  /**\n   * The interval at which to poll for unprocessed messages from storage.\n   */\n  readonly entityMessagePollInterval: DurationInput\n  /**\n   * The interval at which to poll for client replies from storage.\n   */\n  readonly entityReplyPollInterval: DurationInput\n  /**\n   * The interval at which to poll for new runners and refresh shard\n   * assignments.\n   */\n  readonly refreshAssignmentsInterval: DurationInput\n  /**\n   * The interval to retry a send if EntityNotAssignedToRunner is returned.\n   */\n  readonly sendRetryInterval: DurationInput\n  /**\n   * The interval at which to check for unhealthy runners and report them\n   */\n  readonly runnerHealthCheckInterval: DurationInput\n  /**\n   * Simulate serialization and deserialization to remote runners for local\n   * entities.\n   */\n  readonly simulateRemoteSerialization: boolean\n}>() {}\n\nconst defaultRunnerAddress = RunnerAddress.make({ host: \"localhost\", port: 34431 })\n\n/**\n * @since 1.0.0\n * @category defaults\n */\nexport const defaults: ShardingConfig[\"Type\"] = {\n  runnerAddress: Option.some(defaultRunnerAddress),\n  runnerListenAddress: Option.none(),\n  runnerShardWeight: 1,\n  shardsPerGroup: 300,\n  shardGroups: [\"default\"],\n  preemptiveShutdown: true,\n  shardLockRefreshInterval: Duration.seconds(10),\n  shardLockExpiration: Duration.seconds(35),\n  shardLockDisableAdvisory: false,\n  entityMailboxCapacity: 4096,\n  entityMaxIdleTime: Duration.minutes(1),\n  entityRegistrationTimeout: Duration.minutes(1),\n  entityTerminationTimeout: Duration.seconds(15),\n  entityMessagePollInterval: Duration.seconds(10),\n  entityReplyPollInterval: Duration.millis(200),\n  sendRetryInterval: Duration.millis(100),\n  refreshAssignmentsInterval: Duration.seconds(3),\n  runnerHealthCheckInterval: Duration.minutes(1),\n  simulateRemoteSerialization: true\n}\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options?: Partial<ShardingConfig[\"Type\"]>): Layer.Layer<ShardingConfig> =>\n  Layer.succeed(ShardingConfig, { ...defaults, ...options })\n\n/**\n * @since 1.0.0\n * @category defaults\n */\nexport const layerDefaults: Layer.Layer<ShardingConfig> = layer()\n\n/**\n * @since 1.0.0\n * @category Config\n */\nexport const config: Config.Config<ShardingConfig[\"Type\"]> = Config.all({\n  runnerAddress: Config.all({\n    host: Config.string(\"host\").pipe(\n      Config.withDefault(defaultRunnerAddress.host),\n      Config.withDescription(\"The hostname or IP address of the runner.\")\n    ),\n    port: Config.integer(\"port\").pipe(\n      Config.withDefault(defaultRunnerAddress.port),\n      Config.withDescription(\"The port used for inter-runner communication.\")\n    )\n  }).pipe(Config.map((options) => RunnerAddress.make(options)), Config.option),\n  runnerListenAddress: Config.all({\n    host: Config.string(\"listenHost\").pipe(\n      Config.withDescription(\"The host to listen on.\")\n    ),\n    port: Config.integer(\"listenPort\").pipe(\n      Config.withDefault(defaultRunnerAddress.port),\n      Config.withDescription(\"The port to listen on.\")\n    )\n  }).pipe(Config.map((options) => RunnerAddress.make(options)), Config.option),\n  runnerShardWeight: Config.integer(\"runnerShardWeight\").pipe(\n    Config.withDefault(defaults.runnerShardWeight)\n  ),\n  shardGroups: Config.array(Config.string(\"shardGroups\")).pipe(\n    Config.withDefault([\"default\"]),\n    Config.withDescription(\"The shard groups that are assigned to this runner.\")\n  ),\n  shardsPerGroup: Config.integer(\"shardsPerGroup\").pipe(\n    Config.withDefault(defaults.shardsPerGroup),\n    Config.withDescription(\"The number of shards to allocate per shard group.\")\n  ),\n  preemptiveShutdown: Config.boolean(\"preemptiveShutdown\").pipe(\n    Config.withDefault(defaults.preemptiveShutdown),\n    Config.withDescription(\"Start shutting down as soon as an Entity has started shutting down.\")\n  ),\n  shardLockRefreshInterval: Config.duration(\"shardLockRefreshInterval\").pipe(\n    Config.withDefault(defaults.shardLockRefreshInterval),\n    Config.withDescription(\"Shard lock refresh interval.\")\n  ),\n  shardLockExpiration: Config.duration(\"shardLockExpiration\").pipe(\n    Config.withDefault(defaults.shardLockExpiration),\n    Config.withDescription(\"Shard lock expiration duration.\")\n  ),\n  shardLockDisableAdvisory: Config.boolean(\"shardLockDisableAdvisory\").pipe(\n    Config.withDefault(defaults.shardLockDisableAdvisory),\n    Config.withDescription(\"Disable the use of advisory locks for shard locking.\")\n  ),\n  entityMailboxCapacity: Config.integer(\"entityMailboxCapacity\").pipe(\n    Config.withDefault(defaults.entityMailboxCapacity),\n    Config.withDescription(\"The default capacity of the mailbox for entities.\")\n  ),\n  entityMaxIdleTime: Config.duration(\"entityMaxIdleTime\").pipe(\n    Config.withDefault(defaults.entityMaxIdleTime),\n    Config.withDescription(\n      \"The maximum duration of inactivity (i.e. without receiving a message) after which an entity will be interrupted.\"\n    )\n  ),\n  entityRegistrationTimeout: Config.duration(\"entityRegistrationTimeout\").pipe(\n    Config.withDefault(defaults.entityRegistrationTimeout),\n    Config.withDescription(\n      \"If an entity does not register itself within this time after a message is sent to it, the message will be marked as failed.\"\n    )\n  ),\n  entityTerminationTimeout: Config.duration(\"entityTerminationTimeout\").pipe(\n    Config.withDefault(defaults.entityTerminationTimeout),\n    Config.withDescription(\"The maximum duration of time to wait for an entity to terminate.\")\n  ),\n  entityMessagePollInterval: Config.duration(\"entityMessagePollInterval\").pipe(\n    Config.withDefault(defaults.entityMessagePollInterval),\n    Config.withDescription(\"The interval at which to poll for unprocessed messages from storage.\")\n  ),\n  entityReplyPollInterval: Config.duration(\"entityReplyPollInterval\").pipe(\n    Config.withDefault(defaults.entityReplyPollInterval),\n    Config.withDescription(\"The interval at which to poll for client replies from storage.\")\n  ),\n  sendRetryInterval: Config.duration(\"sendRetryInterval\").pipe(\n    Config.withDefault(defaults.sendRetryInterval),\n    Config.withDescription(\"The interval to retry a send if EntityNotAssignedToRunner is returned.\")\n  ),\n  refreshAssignmentsInterval: Config.duration(\"refreshAssignmentsInterval\").pipe(\n    Config.withDefault(defaults.refreshAssignmentsInterval),\n    Config.withDescription(\"The interval at which to refresh shard assignments.\")\n  ),\n  runnerHealthCheckInterval: Config.duration(\"runnerHealthCheckInterval\").pipe(\n    Config.withDefault(defaults.runnerHealthCheckInterval),\n    Config.withDescription(\"The interval at which to check for unhealthy runners and report them.\")\n  ),\n  simulateRemoteSerialization: Config.boolean(\"simulateRemoteSerialization\").pipe(\n    Config.withDefault(defaults.simulateRemoteSerialization),\n    Config.withDescription(\"Simulate serialization and deserialization to remote runners for local entities.\")\n  )\n})\n\n/**\n * @since 1.0.0\n * @category Config\n */\nexport const configFromEnv = config.pipe(\n  Effect.withConfigProvider(\n    ConfigProvider.fromEnv().pipe(\n      ConfigProvider.constantCase\n    )\n  )\n)\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerFromEnv = (options?: Partial<ShardingConfig[\"Type\"]> | undefined): Layer.Layer<\n  ShardingConfig,\n  ConfigError\n> =>\n  Layer.effect(\n    ShardingConfig,\n    options ? Effect.map(configFromEnv, (config) => ({ ...config, ...options })) : configFromEnv\n  )\n"
  },
  {
    "path": "packages/cluster/src/ShardingRegistrationEvent.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Data from \"effect/Data\"\nimport type { Entity } from \"./Entity.js\"\nimport type { SingletonAddress } from \"./SingletonAddress.js\"\n\n/**\n * Represents events that can occur when a runner registers entities or singletons.\n *\n * @since 1.0.0\n * @category models\n */\nexport type ShardingRegistrationEvent =\n  | EntityRegistered\n  | SingletonRegistered\n\n/**\n * Represents an event that occurs when a new entity is registered with a runner.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface EntityRegistered {\n  readonly _tag: \"EntityRegistered\"\n  readonly entity: Entity<any, any>\n}\n\n/**\n * Represents an event that occurs when a new singleton is registered with a\n * runner.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface SingletonRegistered {\n  readonly _tag: \"SingletonRegistered\"\n  readonly address: SingletonAddress\n}\n\n/**\n * @since 1.0.0\n * @category pattern matching\n */\nexport const {\n  /**\n   * @since 1.0.0\n   * @category pattern matching\n   */\n  $match: match,\n  /**\n   * @since 1.0.0\n   * @category constructors\n   */\n  EntityRegistered,\n  /**\n   * @since 1.0.0\n   * @category constructors\n   */\n  SingletonRegistered\n} = Data.taggedEnum<ShardingRegistrationEvent>()\n"
  },
  {
    "path": "packages/cluster/src/SingleRunner.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as SqlClient from \"@effect/sql/SqlClient\"\nimport type * as ConfigError from \"effect/ConfigError\"\nimport * as Layer from \"effect/Layer\"\nimport type * as MessageStorage from \"./MessageStorage.js\"\nimport * as RunnerHealth from \"./RunnerHealth.js\"\nimport * as Runners from \"./Runners.js\"\nimport * as RunnerStorage from \"./RunnerStorage.js\"\nimport * as Sharding from \"./Sharding.js\"\nimport * as ShardingConfig from \"./ShardingConfig.js\"\nimport * as SqlMessageStorage from \"./SqlMessageStorage.js\"\nimport * as SqlRunnerStorage from \"./SqlRunnerStorage.js\"\n\n/**\n * A sql backed single-node cluster, that can be used for running durable\n * entities and workflows.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options?: {\n  readonly shardingConfig?: Partial<ShardingConfig.ShardingConfig[\"Type\"]> | undefined\n  readonly runnerStorage?: \"memory\" | \"sql\" | undefined\n}): Layer.Layer<\n  | Sharding.Sharding\n  | Runners.Runners\n  | MessageStorage.MessageStorage,\n  ConfigError.ConfigError,\n  SqlClient.SqlClient\n> =>\n  Sharding.layer.pipe(\n    Layer.provideMerge(Runners.layerNoop),\n    Layer.provideMerge(SqlMessageStorage.layer),\n    Layer.provide([\n      options?.runnerStorage === \"memory\" ? RunnerStorage.layerMemory : Layer.orDie(SqlRunnerStorage.layer),\n      RunnerHealth.layerNoop\n    ]),\n    Layer.provide(ShardingConfig.layerFromEnv(options?.shardingConfig))\n  )\n"
  },
  {
    "path": "packages/cluster/src/Singleton.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport type { Scope } from \"effect/Scope\"\nimport { Sharding } from \"./Sharding.js\"\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <E, R>(\n  name: string,\n  run: Effect.Effect<void, E, R>,\n  options?: {\n    readonly shardGroup?: string | undefined\n  }\n): Layer.Layer<never, never, Sharding | Exclude<R, Scope>> =>\n  Layer.scopedDiscard(Effect.gen(function*() {\n    const sharding = yield* Sharding\n    yield* sharding.registerSingleton(name, run, options)\n  }))\n"
  },
  {
    "path": "packages/cluster/src/SingletonAddress.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Equal from \"effect/Equal\"\nimport * as Hash from \"effect/Hash\"\nimport * as Schema from \"effect/Schema\"\nimport { ShardId } from \"./ShardId.js\"\n\n/**\n * @since 1.0.0\n * @category Address\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/cluster/SingletonAddress\")\n\n/**\n * @since 1.0.0\n * @category Address\n */\nexport type TypeId = typeof TypeId\n\n/**\n * Represents the unique address of an singleton within the cluster.\n *\n * @since 1.0.0\n * @category Address\n */\nexport class SingletonAddress extends Schema.Class<SingletonAddress>(\"@effect/cluster/SingletonAddress\")({\n  shardId: ShardId,\n  name: Schema.NonEmptyTrimmedString\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId] = TypeId;\n  /**\n   * @since 1.0.0\n   */\n  [Hash.symbol]() {\n    return Hash.cached(this)(Hash.string(`${this.name}:${this.shardId.toString()}`))\n  }\n  /**\n   * @since 1.0.0\n   */\n  [Equal.symbol](that: SingletonAddress): boolean {\n    return this.name === that.name && this.shardId[Equal.symbol](that.shardId)\n  }\n}\n"
  },
  {
    "path": "packages/cluster/src/Snowflake.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Brand from \"effect/Brand\"\nimport * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\nimport type { MachineId } from \"./MachineId.js\"\n\n/**\n * @since 1.0.0\n * @category Symbols\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/cluster/Snowflake\")\n\n/**\n * @since 1.0.0\n * @category Symbols\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type Snowflake = Brand.Branded<bigint, TypeId>\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport const Snowflake = (input: string | bigint): Snowflake =>\n  typeof input === \"string\" ? BigInt(input) as Snowflake : input as Snowflake\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport declare namespace Snowflake {\n  /**\n   * @since 1.0.0\n   * @category Models\n   */\n  export interface Parts {\n    readonly timestamp: number\n    readonly machineId: MachineId\n    readonly sequence: number\n  }\n\n  /**\n   * @since 1.0.0\n   * @category Models\n   */\n  export interface Generator {\n    readonly unsafeNext: () => Snowflake\n    readonly setMachineId: (machineId: MachineId) => Effect.Effect<void>\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const SnowflakeFromBigInt: Schema.Schema<Snowflake, bigint> = Schema.BigIntFromSelf.pipe(\n  Schema.brand(TypeId)\n)\n\n/**\n * @since 1.0.0\n * @category Schemas\n */\nexport const SnowflakeFromString: Schema.Schema<Snowflake, string> = Schema.BigInt.pipe(\n  Schema.brand(TypeId)\n)\n\n/**\n * @since 1.0.0\n * @category Epoch\n */\nexport const constEpochMillis: number = Date.UTC(2025, 0, 1)\n\nconst sinceUnixEpoch = constEpochMillis - Date.UTC(1970, 0, 1)\nconst constBigInt12 = BigInt(12)\nconst constBigInt22 = BigInt(22)\nconst constBigInt1024 = BigInt(1024)\nconst constBigInt4096 = BigInt(4096)\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = (options: {\n  readonly machineId: MachineId\n  readonly sequence: number\n  readonly timestamp: number\n}): Snowflake =>\n  (BigInt(options.timestamp - constEpochMillis) << constBigInt22\n    | (BigInt(options.machineId % 1024) << constBigInt12)\n    | BigInt(options.sequence % 4096)) as Snowflake\n\n/**\n * @since 1.0.0\n * @category Parts\n */\nexport const timestamp = (snowflake: Snowflake): number => Number(snowflake >> constBigInt22) + sinceUnixEpoch\n\n/**\n * @since 1.0.0\n * @category Parts\n */\nexport const dateTime = (snowflake: Snowflake): DateTime.Utc => DateTime.unsafeMake(timestamp(snowflake))\n\n/**\n * @since 1.0.0\n * @category Parts\n */\nexport const machineId = (snowflake: Snowflake): MachineId =>\n  Number((snowflake >> constBigInt12) % constBigInt1024) as MachineId\n\n/**\n * @since 1.0.0\n * @category Parts\n */\nexport const sequence = (snowflake: Snowflake): number => Number(snowflake % constBigInt4096)\n\n/**\n * @since 1.0.0\n * @category Parts\n */\nexport const toParts = (snowflake: Snowflake): Snowflake.Parts => ({\n  timestamp: timestamp(snowflake),\n  machineId: machineId(snowflake),\n  sequence: sequence(snowflake)\n})\n\n/**\n * @since 1.0.0\n * @category Generator\n */\nexport const makeGenerator: Effect.Effect<Snowflake.Generator> = Effect.gen(function*() {\n  let machineId = Math.floor(Math.random() * 1024) as MachineId\n  const clock = yield* Effect.clock\n\n  let sequence = 0\n  let sequenceAt = Math.floor(clock.unsafeCurrentTimeMillis())\n\n  return identity<Snowflake.Generator>({\n    setMachineId: (newMachineId) =>\n      Effect.sync(() => {\n        machineId = newMachineId\n      }),\n    unsafeNext() {\n      let now = Math.floor(clock.unsafeCurrentTimeMillis())\n\n      // account for clock drift, only allow time to move forward\n      if (now < sequenceAt) {\n        now = sequenceAt\n      } else if (now > sequenceAt) {\n        // reset sequence if we're in a new millisecond\n        sequence = 0\n        sequenceAt = now\n      } else if (sequence >= 4096) {\n        // if we've hit the max sequence for this millisecond, go to the next\n        // millisecond\n        sequenceAt++\n        sequence = 0\n      }\n\n      return make({\n        machineId,\n        sequence: sequence++,\n        timestamp: sequenceAt\n      })\n    }\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Generator\n */\nexport class Generator extends Context.Tag(\"@effect/cluster/Snowflake/Generator\")<\n  Generator,\n  Snowflake.Generator\n>() {}\n\n/**\n * @since 1.0.0\n * @category Generator\n */\nexport const layerGenerator: Layer.Layer<Generator> = Layer.effect(Generator, makeGenerator)\n"
  },
  {
    "path": "packages/cluster/src/SocketRunner.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport { SocketServer } from \"@effect/platform/SocketServer\"\nimport type * as RpcSerialization from \"@effect/rpc/RpcSerialization\"\nimport * as RpcServer from \"@effect/rpc/RpcServer\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport type { MessageStorage } from \"./MessageStorage.js\"\nimport type { RunnerHealth } from \"./RunnerHealth.js\"\nimport type * as Runners from \"./Runners.js\"\nimport * as RunnerServer from \"./RunnerServer.js\"\nimport type * as RunnerStorage from \"./RunnerStorage.js\"\nimport type * as Sharding from \"./Sharding.js\"\nimport type { ShardingConfig } from \"./ShardingConfig.js\"\n\nconst withLogAddress = <A, E, R>(layer: Layer.Layer<A, E, R>): Layer.Layer<A, E, R | SocketServer> =>\n  Layer.effectDiscard(Effect.gen(function*() {\n    const server = yield* SocketServer\n    const address = server.address._tag === \"UnixAddress\"\n      ? server.address.path\n      : `${server.address.hostname}:${server.address.port}`\n    yield* Effect.annotateLogs(Effect.logInfo(`Listening on: ${address}`), {\n      package: \"@effect/cluster\",\n      service: \"Runner\"\n    })\n  })).pipe(Layer.provideMerge(layer))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer: Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  | Runners.RpcClientProtocol\n  | ShardingConfig\n  | RpcSerialization.RpcSerialization\n  | SocketServer\n  | MessageStorage\n  | RunnerStorage.RunnerStorage\n  | RunnerHealth\n> = RunnerServer.layerWithClients.pipe(\n  withLogAddress,\n  Layer.provide(RpcServer.layerProtocolSocketServer)\n)\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerClientOnly: Layer.Layer<\n  Sharding.Sharding | Runners.Runners,\n  never,\n  Runners.RpcClientProtocol | ShardingConfig | MessageStorage | RunnerStorage.RunnerStorage\n> = RunnerServer.layerClientOnly\n"
  },
  {
    "path": "packages/cluster/src/SqlMessageStorage.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Migrator from \"@effect/sql/Migrator\"\nimport * as SqlClient from \"@effect/sql/SqlClient\"\nimport type { Row } from \"@effect/sql/SqlConnection\"\nimport type { SqlError } from \"@effect/sql/SqlError\"\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Schedule from \"effect/Schedule\"\nimport { PersistenceError } from \"./ClusterError.js\"\nimport type * as Envelope from \"./Envelope.js\"\nimport * as MessageStorage from \"./MessageStorage.js\"\nimport { SaveResultEncoded } from \"./MessageStorage.js\"\nimport type * as Reply from \"./Reply.js\"\nimport { ShardId } from \"./ShardId.js\"\nimport type { ShardingConfig } from \"./ShardingConfig.js\"\nimport * as Snowflake from \"./Snowflake.js\"\n\nconst withTracerDisabled = Effect.withTracerEnabled(false)\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.fnUntraced(function*(options?: {\n  readonly prefix?: string | undefined\n}) {\n  const sql = (yield* SqlClient.SqlClient).withoutTransforms()\n  const prefix = options?.prefix ?? \"cluster\"\n  const table = (name: string) => `${prefix}_${name}`\n\n  yield* Effect.orDie(\n    Migrator.make({})({\n      loader: migrations(options),\n      table: table(\"migrations\")\n    })\n  )\n\n  const messageKindAckChunk = sql.literal(String(messageKind.AckChunk))\n  const messageKindInterrupt = sql.literal(String(messageKind.Interrupt))\n  const replyKindWithExit = sql.literal(String(replyKind.WithExit))\n\n  const messagesTable = table(\"messages\")\n  const messagesTableSql = sql(messagesTable)\n\n  const repliesTable = table(\"replies\")\n  const repliesTableSql = sql(repliesTable)\n\n  const envelopeToRow = (\n    envelope: Envelope.Envelope.Encoded,\n    message_id: string | null,\n    deliver_at: number | null\n  ): MessageRow => {\n    switch (envelope._tag) {\n      case \"Request\":\n        return {\n          id: envelope.requestId,\n          message_id,\n          shard_id: ShardId.toString(envelope.address.shardId),\n          entity_type: envelope.address.entityType,\n          entity_id: envelope.address.entityId,\n          kind: messageKind.Request,\n          tag: envelope.tag,\n          payload: JSON.stringify(envelope.payload),\n          headers: JSON.stringify(envelope.headers),\n          trace_id: envelope.traceId ?? null,\n          span_id: envelope.spanId ?? null,\n          sampled: envelope.sampled === undefined\n            ? null\n            : supportsBooleans\n            ? envelope.sampled\n            : envelope.sampled\n            ? 1\n            : 0,\n          request_id: envelope.requestId,\n          reply_id: null,\n          deliver_at\n        }\n      case \"AckChunk\":\n        return {\n          id: envelope.id,\n          message_id,\n          shard_id: ShardId.toString(envelope.address.shardId),\n          entity_type: envelope.address.entityType,\n          entity_id: envelope.address.entityId,\n          kind: messageKind.AckChunk,\n          tag: null,\n          payload: null,\n          headers: null,\n          trace_id: null,\n          span_id: null,\n          sampled: null,\n          request_id: envelope.requestId,\n          reply_id: envelope.replyId,\n          deliver_at\n        }\n      case \"Interrupt\":\n        return {\n          id: envelope.id,\n          message_id,\n          shard_id: ShardId.toString(envelope.address.shardId),\n          entity_type: envelope.address.entityType,\n          entity_id: envelope.address.entityId,\n          kind: messageKind.Interrupt,\n          payload: null,\n          tag: null,\n          headers: null,\n          trace_id: null,\n          span_id: null,\n          sampled: null,\n          request_id: envelope.requestId,\n          reply_id: null,\n          deliver_at\n        }\n    }\n  }\n\n  const replyToRow = (reply: Reply.ReplyEncoded<any>): ReplyRow => ({\n    id: reply.id,\n    kind: replyKind[reply._tag],\n    request_id: reply.requestId,\n    payload: reply._tag === \"WithExit\" ? JSON.stringify(reply.exit) : JSON.stringify(reply.values),\n    sequence: reply._tag === \"Chunk\" ? reply.sequence : null\n  })\n\n  const supportsBooleans = sql.onDialectOrElse({\n    mssql: () => false,\n    sqlite: () => false,\n    orElse: () => true\n  })\n\n  const messageFromRow = (row: MessageRow & ReplyJoinRow): {\n    readonly envelope: Envelope.Envelope.Encoded\n    readonly lastSentReply: Option.Option<Reply.ReplyEncoded<any>>\n  } => {\n    switch (Number(row.kind) as 0 | 1 | 2) {\n      case 0:\n        return {\n          envelope: {\n            _tag: \"Request\",\n            requestId: String(row.id),\n            address: {\n              shardId: ShardId.fromStringEncoded(row.shard_id),\n              entityType: row.entity_type,\n              entityId: row.entity_id\n            },\n            tag: row.tag!,\n            payload: JSON.parse(row.payload!),\n            headers: JSON.parse(row.headers!),\n            traceId: row.trace_id ?? undefined,\n            spanId: row.span_id ?? undefined,\n            sampled: !!row.sampled\n          },\n          lastSentReply: row.reply_reply_id ?\n            Option.some({\n              _tag: \"Chunk\",\n              id: String(row.reply_reply_id),\n              requestId: String(row.request_id),\n              sequence: Number(row.reply_sequence!),\n              values: JSON.parse(row.reply_payload!)\n            } as any) :\n            Option.none()\n        }\n      case 1:\n        return {\n          envelope: {\n            _tag: \"AckChunk\",\n            id: String(row.id),\n            requestId: String(row.request_id!),\n            replyId: String(row.reply_id!),\n            address: {\n              shardId: ShardId.fromStringEncoded(row.shard_id),\n              entityType: row.entity_type,\n              entityId: row.entity_id\n            }\n          },\n          lastSentReply: Option.none()\n        }\n      case 2:\n        return {\n          envelope: {\n            _tag: \"Interrupt\",\n            id: String(row.id),\n            requestId: String(row.request_id!),\n            address: {\n              shardId: ShardId.fromStringEncoded(row.shard_id),\n              entityType: row.entity_type,\n              entityId: row.entity_id\n            }\n          },\n          lastSentReply: Option.none()\n        }\n    }\n  }\n\n  const sqlFalse = sql.literal(supportsBooleans ? \"FALSE\" : \"0\")\n  const sqlTrue = sql.literal(supportsBooleans ? \"TRUE\" : \"1\")\n\n  const insertEnvelope: (\n    row: MessageRow,\n    message_id: string\n  ) => Effect.Effect<ReadonlyArray<Row>, SqlError> = sql.onDialectOrElse({\n    pg: () => (row, message_id) =>\n      sql`\n        INSERT INTO ${messagesTableSql} ${sql.insert(row)}\n        ON CONFLICT (message_id) DO NOTHING\n        RETURNING id\n      `.pipe(Effect.flatMap((rows) => {\n        // inserted a new row\n        if (rows.length > 0) return Effect.succeed([])\n        return sql`\n          SELECT m.id, r.id as reply_id, r.kind as reply_kind, r.payload as reply_payload, r.sequence as reply_sequence\n          FROM ${messagesTableSql} m\n          LEFT JOIN ${repliesTableSql} r ON r.id = m.last_reply_id\n          WHERE m.message_id = ${message_id}\n        `\n      })),\n    mysql: () => (row, message_id) =>\n      Effect.flatMap(\n        sql`INSERT IGNORE INTO ${messagesTableSql} ${sql.insert(row)}`.raw,\n        (row: any) => {\n          if (row.affectedRows > 0) {\n            return Effect.succeed([])\n          }\n          return sql`\n            SELECT m.id, r.id as reply_id, r.kind as reply_kind, r.payload as reply_payload, r.sequence as reply_sequence\n            FROM ${messagesTableSql} m\n            LEFT JOIN ${repliesTableSql} r ON r.id = m.last_reply_id\n            WHERE m.message_id = ${message_id}\n          `\n        }\n      ),\n    mssql: () => (row, message_id) =>\n      sql`\n        MERGE ${messagesTableSql} WITH (HOLDLOCK) AS target\n        USING (SELECT ${message_id} as message_id) AS source\n        ON target.message_id = source.message_id\n        WHEN NOT MATCHED THEN\n          INSERT ${sql.insert(row)}\n        OUTPUT\n          inserted.id,\n          CASE\n            WHEN inserted.id IS NULL THEN (\n              SELECT r.id, r.kind, r.payload\n              FROM ${repliesTableSql} r\n              WHERE r.id = target.last_reply_id\n            )\n          END as reply_id,\n          CASE\n            WHEN inserted.id IS NULL THEN (\n              SELECT r.kind\n              FROM ${repliesTableSql} r\n              WHERE r.id = target.last_reply_id\n            )\n          END as reply_kind,\n          CASE\n            WHEN inserted.id IS NULL THEN (\n              SELECT r.payload\n              FROM ${repliesTableSql} r\n              WHERE r.id = target.last_reply_id\n            )\n          END as reply_payload,\n          CASE\n            WHEN inserted.id IS NULL THEN (\n              SELECT r.sequence\n              FROM ${repliesTableSql} r\n              WHERE r.id = target.last_reply_id\n            )\n          END as reply_sequence;\n      `,\n    orElse: () => (row, message_id) =>\n      sql`\n        SELECT m.id, r.id as reply_id, r.kind as reply_kind, r.payload as reply_payload, r.sequence as reply_sequence\n        FROM ${messagesTableSql} m\n        LEFT JOIN ${repliesTableSql} r ON r.id = m.last_reply_id\n        WHERE m.message_id = ${message_id}\n      `.pipe(\n        Effect.tap(sql`INSERT OR IGNORE INTO ${messagesTableSql} ${sql.insert(row)}`),\n        sql.withTransaction,\n        Effect.retry({ times: 3 })\n      )\n  })\n\n  const tenMinutesAgo = sql.onDialectOrElse({\n    mssql: () => sql.literal(`DATEADD(MINUTE, -10, GETDATE())`),\n    mysql: () => sql.literal(`NOW() - INTERVAL 10 MINUTE`),\n    pg: () => sql.literal(`NOW() - INTERVAL '10 minutes'`),\n    orElse: () => sql.literal(`DATETIME('now', '-10 minute')`)\n  })\n  const sqlNowString = sql.onDialectOrElse({\n    pg: () => \"NOW()\",\n    mysql: () => \"NOW()\",\n    mssql: () => \"GETDATE()\",\n    orElse: () => \"CURRENT_TIMESTAMP\"\n  })\n  const sqlNow = sql.literal(sqlNowString)\n\n  const wrapString = sql.onDialectOrElse({\n    mssql: () => (s: string) => `N'${s}'`,\n    orElse: () => (s: string) => `'${s}'`\n  })\n  const forUpdate = sql.onDialectOrElse({\n    sqlite: () => sql.literal(\"\"),\n    orElse: () => sql.literal(\"FOR UPDATE\")\n  })\n\n  const getUnprocessedMessages = sql.onDialectOrElse({\n    pg: () => (shardIds: Arr.NonEmptyArray<string>, now: number) =>\n      sql<MessageJoinRow>`\n        WITH messages AS (\n          UPDATE ${messagesTableSql} m\n          SET last_read = ${sqlNow}\n          FROM (\n            SELECT m.*\n            FROM ${messagesTableSql} m\n            WHERE m.shard_id IN (${sql.literal(shardIds.map(wrapString).join(\",\"))})\n            AND NOT EXISTS (\n              SELECT 1 FROM ${repliesTableSql}\n              WHERE request_id = m.request_id\n              AND (kind = ${replyKindWithExit} OR acked = ${sqlFalse})\n            )\n            AND m.processed = ${sqlFalse}\n            AND (m.last_read IS NULL OR m.last_read < ${tenMinutesAgo})\n            AND (m.deliver_at IS NULL OR m.deliver_at <= ${sql.literal(String(now))})\n            FOR UPDATE\n          ) AS ids\n          LEFT JOIN ${repliesTableSql} r ON r.id = ids.last_reply_id\n          WHERE m.id = ids.id\n          RETURNING ids.*, r.id as reply_reply_id, r.kind as reply_kind, r.payload as reply_payload, r.sequence as reply_sequence\n        )\n        SELECT * FROM messages ORDER BY rowid ASC\n      `,\n    orElse: () => (shardIds: Arr.NonEmptyArray<string>, now: number) =>\n      sql<MessageJoinRow>`\n        SELECT m.*, r.id as reply_reply_id, r.kind as reply_kind, r.payload as reply_payload, r.sequence as reply_sequence\n        FROM ${messagesTableSql} m\n        LEFT JOIN ${repliesTableSql} r ON r.id = m.last_reply_id\n        WHERE m.shard_id IN (${sql.literal(shardIds.map(wrapString).join(\",\"))})\n        AND NOT EXISTS (\n          SELECT 1 FROM ${repliesTableSql}\n          WHERE request_id = m.request_id\n          AND (kind = ${replyKindWithExit} OR acked = ${sqlFalse})\n        )\n        AND processed = ${sqlFalse}\n        AND (m.last_read IS NULL OR m.last_read < ${tenMinutesAgo})\n        AND (m.deliver_at IS NULL OR m.deliver_at <= ${sql.literal(String(now))})\n        ORDER BY m.rowid ASC\n        ${forUpdate}\n      `.unprepared.pipe(\n        Effect.tap((rows) => {\n          if (rows.length === 0) {\n            return Effect.void\n          }\n          return sql`\n            UPDATE ${messagesTableSql}\n            SET last_read = ${sqlNow}\n            WHERE id IN (${sql.literal(rows.map((row) => row.id).join(\",\"))})\n          `.unprepared\n        }),\n        sql.withTransaction\n      )\n  })\n\n  return yield* MessageStorage.makeEncoded({\n    saveEnvelope: ({ deliverAt, envelope, primaryKey }) =>\n      Effect.suspend(() => {\n        const row = envelopeToRow(envelope, primaryKey, deliverAt)\n        let insert = primaryKey\n          ? insertEnvelope(row, primaryKey)\n          : Effect.as(sql`INSERT INTO ${messagesTableSql} ${sql.insert(row)}`.unprepared, [])\n        if (envelope._tag === \"AckChunk\") {\n          insert = sql`UPDATE ${repliesTableSql} SET acked = ${sqlTrue} WHERE id = ${envelope.replyId}`.pipe(\n            Effect.andThen(\n              sql`UPDATE ${messagesTableSql} SET processed = ${sqlTrue} WHERE processed = ${sqlFalse} AND request_id = ${envelope.requestId} AND kind = ${messageKindAckChunk}`\n            ),\n            Effect.andThen(insert),\n            sql.withTransaction\n          )\n        }\n        return insert.pipe(\n          Effect.map((rows) => {\n            if (rows.length === 0) {\n              return SaveResultEncoded.Success()\n            }\n            const row = rows[0]\n            const replyKindNum = typeof row.reply_kind === \"bigint\" ? Number(row.reply_kind) : row.reply_kind\n            return SaveResultEncoded.Duplicate({\n              originalId: Snowflake.Snowflake(row.id as any),\n              lastReceivedReply: row.reply_id ?\n                Option.some({\n                  id: String(row.reply_id),\n                  requestId: String(row.id),\n                  _tag: replyKindNum === replyKind.WithExit ? \"WithExit\" : \"Chunk\",\n                  ...(replyKindNum === replyKind.WithExit\n                    ? { exit: JSON.parse(row.reply_payload as string) }\n                    : {\n                      sequence: Number(row.reply_sequence),\n                      values: JSON.parse(row.reply_payload as string)\n                    })\n                } as any) :\n                Option.none()\n            })\n          })\n        )\n      }).pipe(\n        Effect.provideService(SqlClient.SafeIntegers, true),\n        PersistenceError.refail,\n        withTracerDisabled\n      ),\n\n    saveReply: (reply) =>\n      Effect.suspend(() => {\n        const row = replyToRow(reply)\n        const update = reply._tag === \"Chunk\" ?\n          sql`UPDATE ${messagesTableSql} SET last_reply_id = ${reply.id} WHERE id = ${reply.requestId}` :\n          sql`UPDATE ${messagesTableSql} SET processed = ${sqlTrue}, last_reply_id = ${reply.id} WHERE request_id = ${reply.requestId}`\n        return update.unprepared.pipe(\n          Effect.andThen(sql`INSERT INTO ${repliesTableSql} ${sql.insert(row)}`),\n          sql.withTransaction\n        )\n      }).pipe(\n        Effect.asVoid,\n        PersistenceError.refail,\n        withTracerDisabled\n      ),\n\n    clearReplies: Effect.fnUntraced(\n      function*(requestId) {\n        yield* sql`DELETE FROM ${repliesTableSql} WHERE request_id = ${String(requestId)} AND kind = 0`\n        yield* sql`DELETE FROM ${messagesTableSql} WHERE request_id = ${\n          String(requestId)\n        } AND kind = ${messageKindInterrupt}`\n        yield* sql`UPDATE ${messagesTableSql} SET processed = ${sqlFalse}, last_reply_id = NULL, last_read = NULL WHERE request_id = ${\n          String(requestId)\n        }`\n      },\n      sql.withTransaction,\n      PersistenceError.refail,\n      withTracerDisabled\n    ),\n\n    requestIdForPrimaryKey: (primaryKey) =>\n      sql<{ id: string | bigint }>`SELECT id FROM ${messagesTableSql} WHERE message_id = ${primaryKey}`.pipe(\n        Effect.map((rows) =>\n          Option.fromNullable(rows[0]?.id).pipe(\n            Option.map(Snowflake.Snowflake)\n          )\n        ),\n        Effect.provideService(SqlClient.SafeIntegers, true),\n        PersistenceError.refail,\n        withTracerDisabled\n      ),\n\n    repliesFor: (requestIds) =>\n      // replies where:\n      // - the request is in the list\n      // - the kind is WithExit\n      // - or the kind is Chunk and has not been acked yet\n      sql<ReplyRow>`\n        SELECT id, kind, request_id, payload, sequence\n        FROM ${repliesTableSql}\n        WHERE request_id IN (${sql.literal(requestIds.join(\",\"))})\n        AND (\n          kind = ${replyKindWithExit}\n          OR (\n            kind IS NULL\n            AND acked = ${sqlFalse}\n          )\n        )\n        ORDER BY rowid ASC\n      `.unprepared.pipe(\n        Effect.provideService(SqlClient.SafeIntegers, true),\n        Effect.map(Arr.map(replyFromRow)),\n        PersistenceError.refail,\n        withTracerDisabled\n      ),\n\n    repliesForUnfiltered: (requestIds) =>\n      sql<ReplyRow>`\n        SELECT id, kind, request_id, payload, sequence\n        FROM ${repliesTableSql}\n        WHERE request_id IN (${sql.literal(requestIds.join(\",\"))})\n        ORDER BY rowid ASC\n      `.unprepared.pipe(\n        Effect.provideService(SqlClient.SafeIntegers, true),\n        Effect.map(Arr.map(replyFromRow)),\n        PersistenceError.refail,\n        withTracerDisabled\n      ),\n\n    unprocessedMessages: Effect.fnUntraced(\n      function*(shardIds, now) {\n        const rows = yield* getUnprocessedMessages(shardIds, now)\n        if (rows.length === 0) {\n          return []\n        }\n        const messages: Array<{\n          readonly envelope: Envelope.Envelope.Encoded\n          readonly lastSentReply: Option.Option<Reply.ReplyEncoded<any>>\n        }> = new Array(rows.length)\n        const ids = new Array<string>(rows.length)\n        for (let i = 0; i < rows.length; i++) {\n          messages[i] = messageFromRow(rows[i])\n          ids[i] = String(rows[i].id)\n        }\n        return messages\n      },\n      Effect.provideService(SqlClient.SafeIntegers, true),\n      PersistenceError.refail,\n      withTracerDisabled\n    ),\n\n    unprocessedMessagesById(ids, now) {\n      const idArr = ids.map((id) => String(id))\n      return sql<MessageRow & ReplyJoinRow>`\n        SELECT m.*, r.id as reply_id, r.kind as reply_kind, r.payload as reply_payload, r.sequence as reply_sequence\n        FROM ${messagesTableSql} m\n        LEFT JOIN ${repliesTableSql} r ON r.id = m.last_reply_id\n        WHERE m.id IN (${sql.literal(idArr.join(\",\"))})\n        AND NOT EXISTS (\n          SELECT 1 FROM ${repliesTableSql}\n          WHERE request_id = m.request_id\n          AND (kind = ${replyKindWithExit} OR acked = ${sqlFalse})\n        )\n        AND m.processed = ${sqlFalse}\n        AND (m.deliver_at IS NULL OR m.deliver_at <= ${sql.literal(String(now))})\n        ORDER BY m.rowid ASC\n      `.unprepared.pipe(\n        Effect.map(Arr.map(messageFromRow)),\n        Effect.provideService(SqlClient.SafeIntegers, true),\n        PersistenceError.refail,\n        withTracerDisabled\n      )\n    },\n\n    resetAddress: (address) =>\n      sql`\n        UPDATE ${messagesTableSql}\n        SET last_read = NULL\n        WHERE processed = ${sqlFalse}\n        AND shard_id = ${address.shardId.toString()}\n        AND entity_type = ${address.entityType}\n        AND entity_id = ${address.entityId}\n      `.pipe(\n        Effect.asVoid,\n        PersistenceError.refail,\n        withTracerDisabled\n      ),\n\n    clearAddress: (address) =>\n      sql`\n        DELETE FROM ${repliesTableSql}\n        WHERE request_id IN (\n          SELECT id FROM ${messagesTableSql}\n          WHERE entity_type = ${address.entityType}\n          AND entity_id = ${address.entityId}\n        )\n      `.pipe(\n        Effect.andThen(\n          sql`\n            DELETE FROM ${messagesTableSql}\n            WHERE entity_type = ${address.entityType}\n            AND entity_id = ${address.entityId}\n          `\n        ),\n        sql.withTransaction,\n        Effect.asVoid,\n        PersistenceError.refail,\n        withTracerDisabled\n      ),\n\n    resetShards: (shardIds) =>\n      sql`\n        UPDATE ${messagesTableSql}\n        SET last_read = NULL\n        WHERE processed = ${sqlFalse}\n        AND shard_id IN (${sql.literal(shardIds.map(wrapString).join(\",\"))})\n      `.pipe(\n        Effect.asVoid,\n        PersistenceError.refail,\n        withTracerDisabled\n      )\n  })\n}, withTracerDisabled)\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer: Layer.Layer<\n  MessageStorage.MessageStorage,\n  never,\n  SqlClient.SqlClient | ShardingConfig\n> = Layer.scoped(MessageStorage.MessageStorage, make()).pipe(\n  Layer.provide(Snowflake.layerGenerator)\n)\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerWith = (options: {\n  readonly prefix?: string | undefined\n}): Layer.Layer<MessageStorage.MessageStorage, never, SqlClient.SqlClient | ShardingConfig> =>\n  Layer.scoped(MessageStorage.MessageStorage, make(options)).pipe(\n    Layer.provide(Snowflake.layerGenerator)\n  )\n\n// -------------------------------------------------------------------------------------------------\n// internal\n// -------------------------------------------------------------------------------------------------\n\nconst migrations = (options?: {\n  readonly prefix?: string | undefined\n}) => {\n  const prefix = options?.prefix ?? \"cluster\"\n  const table = (name: string) => `${prefix}_${name}`\n  const messagesTable = table(\"messages\")\n  const repliesTable = table(\"replies\")\n\n  return Migrator.fromRecord({\n    \"0001_create_tables\": Effect.gen(function*() {\n      const sql = (yield* SqlClient.SqlClient).withoutTransforms()\n      const messagesTableSql = sql(messagesTable)\n      const repliesTableSql = sql(repliesTable)\n\n      yield* sql.onDialectOrElse({\n        mssql: () =>\n          sql`\n            IF OBJECT_ID(N'${messagesTableSql}', N'U') IS NULL\n            CREATE TABLE ${messagesTableSql} (\n              id BIGINT PRIMARY KEY,\n              rowid BIGINT IDENTITY(1,1),\n              message_id VARCHAR(255),\n              shard_id VARCHAR(50) NOT NULL,\n              entity_type VARCHAR(150) NOT NULL,\n              entity_id VARCHAR(255) NOT NULL,\n              kind INT NOT NULL,\n              tag VARCHAR(50),\n              payload TEXT,\n              headers TEXT,\n              trace_id VARCHAR(32),\n              span_id VARCHAR(16),\n              sampled BIT,\n              processed BIT NOT NULL DEFAULT 0,\n              request_id BIGINT NOT NULL,\n              reply_id BIGINT,\n              last_reply_id BIGINT,\n              last_read DATETIME,\n              deliver_at BIGINT,\n              UNIQUE (message_id)\n            )\n          `,\n        mysql: () =>\n          sql`\n            CREATE TABLE IF NOT EXISTS ${messagesTableSql} (\n              id BIGINT NOT NULL,\n              rowid BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,\n              message_id VARCHAR(255),\n              shard_id VARCHAR(50) NOT NULL,\n              entity_type VARCHAR(150) NOT NULL,\n              entity_id VARCHAR(255) NOT NULL,\n              kind INT NOT NULL,\n              tag VARCHAR(50),\n              payload TEXT,\n              headers TEXT,\n              trace_id VARCHAR(32),\n              span_id VARCHAR(16),\n              sampled BOOLEAN,\n              processed BOOLEAN NOT NULL DEFAULT FALSE,\n              request_id BIGINT NOT NULL,\n              reply_id BIGINT,\n              last_reply_id BIGINT,\n              last_read DATETIME,\n              deliver_at BIGINT,\n              UNIQUE (id),\n              UNIQUE (message_id)\n            )\n          `,\n        pg: () =>\n          sql`\n            CREATE TABLE IF NOT EXISTS ${messagesTableSql} (\n              id BIGINT PRIMARY KEY,\n              rowid BIGSERIAL,\n              message_id VARCHAR(255),\n              shard_id VARCHAR(50) NOT NULL,\n              entity_type VARCHAR(150) NOT NULL,\n              entity_id VARCHAR(255) NOT NULL,\n              kind INT NOT NULL,\n              tag VARCHAR(50),\n              payload TEXT,\n              headers TEXT,\n              trace_id VARCHAR(32),\n              span_id VARCHAR(16),\n              sampled BOOLEAN,\n              processed BOOLEAN NOT NULL DEFAULT FALSE,\n              request_id BIGINT NOT NULL,\n              reply_id BIGINT,\n              last_reply_id BIGINT,\n              last_read TIMESTAMP,\n              deliver_at BIGINT,\n              UNIQUE (message_id)\n            )\n          `.pipe(Effect.ignore),\n        orElse: () =>\n          // sqlite\n          sql`\n            CREATE TABLE IF NOT EXISTS ${messagesTableSql} (\n              id INTEGER PRIMARY KEY,\n              message_id TEXT,\n              shard_id TEXT NOT NULL,\n              entity_type TEXT NOT NULL,\n              entity_id TEXT NOT NULL,\n              kind INTEGER NOT NULL,\n              tag TEXT,\n              payload TEXT,\n              headers TEXT,\n              trace_id TEXT,\n              span_id TEXT,\n              sampled BOOLEAN,\n              processed BOOLEAN NOT NULL DEFAULT FALSE,\n              request_id INTEGER NOT NULL,\n              reply_id INTEGER,\n              last_reply_id INTEGER,\n              last_read TEXT,\n              deliver_at INTEGER,\n              UNIQUE (message_id)\n            )\n          `\n      })\n\n      // Add message indexes optimized for the specific query patterns\n      const shardLookupIndex = `${messagesTable}_shard_idx`\n      const requestIdLookupIndex = `${messagesTable}_request_id_idx`\n      yield* sql.onDialectOrElse({\n        mssql: () =>\n          sql`\n            IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${shardLookupIndex})\n            CREATE INDEX ${sql(shardLookupIndex)} \n            ON ${messagesTableSql} (shard_id, processed, last_read, deliver_at);\n\n            IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${requestIdLookupIndex})\n            CREATE INDEX ${sql(requestIdLookupIndex)}\n            ON ${messagesTableSql} (request_id);\n          `,\n        mysql: () =>\n          sql`\n            CREATE INDEX ${sql(shardLookupIndex)}\n            ON ${messagesTableSql} (shard_id, processed, last_read, deliver_at);\n\n            CREATE INDEX ${sql(requestIdLookupIndex)}\n            ON ${messagesTableSql} (request_id);\n          `.unprepared.pipe(Effect.ignore),\n        pg: () =>\n          sql`\n            CREATE INDEX IF NOT EXISTS ${sql(shardLookupIndex)}\n            ON ${messagesTableSql} (shard_id, processed, last_read, deliver_at);\n\n            CREATE INDEX IF NOT EXISTS ${sql(requestIdLookupIndex)}\n            ON ${messagesTableSql} (request_id);\n          `.pipe(\n            Effect.tapDefect((error) =>\n              Effect.annotateLogs(Effect.logDebug(\"Failed to create indexes\", error), {\n                package: \"@effect/cluster\",\n                module: \"SqlMessageStorage\"\n              })\n            ),\n            Effect.retry({\n              schedule: Schedule.spaced(1000)\n            })\n          ),\n        orElse: () =>\n          // sqlite\n          Effect.all([\n            sql`\n              CREATE INDEX IF NOT EXISTS ${sql(shardLookupIndex)}\n              ON ${messagesTableSql} (shard_id, processed, last_read, deliver_at)\n            `,\n            sql`\n              CREATE INDEX IF NOT EXISTS ${sql(requestIdLookupIndex)}\n              ON ${messagesTableSql} (request_id)\n            `\n          ]).pipe(sql.withTransaction)\n      })\n\n      yield* sql.onDialectOrElse({\n        mssql: () =>\n          sql`\n            IF OBJECT_ID(N'${repliesTableSql}', N'U') IS NULL\n            CREATE TABLE ${repliesTableSql} (\n              id BIGINT PRIMARY KEY,\n              rowid BIGINT IDENTITY(1,1),\n              kind INT,\n              request_id BIGINT NOT NULL,\n              payload TEXT NOT NULL,\n              sequence INT,\n              acked BIT NOT NULL DEFAULT 0,\n              CONSTRAINT ${sql(repliesTable + \"_one_exit\")} UNIQUE (request_id, kind),\n              CONSTRAINT ${sql(repliesTable + \"_sequence\")} UNIQUE (request_id, sequence)\n            )\n          `,\n        mysql: () =>\n          sql`\n            CREATE TABLE IF NOT EXISTS ${repliesTableSql} (\n              id BIGINT NOT NULL,\n              rowid BIGINT AUTO_INCREMENT PRIMARY KEY,\n              kind INT,\n              request_id BIGINT NOT NULL,\n              payload TEXT NOT NULL,\n              sequence INT,\n              acked BOOLEAN NOT NULL DEFAULT FALSE,\n              UNIQUE (id),\n              UNIQUE (request_id, kind),\n              UNIQUE (request_id, sequence)\n            )\n          `,\n        pg: () =>\n          sql`\n            CREATE TABLE IF NOT EXISTS ${repliesTableSql} (\n              id BIGINT PRIMARY KEY,\n              rowid BIGSERIAL,\n              kind INT,\n              request_id BIGINT NOT NULL,\n              payload TEXT NOT NULL,\n              sequence INT,\n              acked BOOLEAN NOT NULL DEFAULT FALSE,\n              UNIQUE (request_id, kind),\n              UNIQUE (request_id, sequence)\n            )\n          `,\n        orElse: () =>\n          // sqlite\n          sql`\n            CREATE TABLE IF NOT EXISTS ${repliesTableSql} (\n              id INTEGER PRIMARY KEY,\n              kind INTEGER,\n              request_id INTEGER NOT NULL,\n              payload TEXT NOT NULL,\n              sequence INTEGER,\n              acked BOOLEAN NOT NULL DEFAULT FALSE,\n              UNIQUE (request_id, kind),\n              UNIQUE (request_id, sequence)\n            )\n          `\n      })\n\n      // Add reply indexes optimized for request_id lookups\n      const replyLookupIndex = `${repliesTable}_request_lookup_idx`\n      yield* sql.onDialectOrElse({\n        mssql: () =>\n          sql`\n            IF NOT EXISTS (SELECT * FROM sys.indexes WHERE name = ${replyLookupIndex})\n            CREATE INDEX ${sql(replyLookupIndex)}\n            ON ${repliesTableSql} (request_id, kind, acked);\n          `,\n        mysql: () =>\n          sql`\n            CREATE INDEX ${sql(replyLookupIndex)}\n            ON ${repliesTableSql} (request_id, kind, acked);\n          `.unprepared.pipe(Effect.ignore),\n        pg: () =>\n          sql`\n            CREATE INDEX IF NOT EXISTS ${sql(replyLookupIndex)}\n            ON ${repliesTableSql} (request_id, kind, acked);\n          `.pipe(\n            Effect.tapDefect((error) =>\n              Effect.annotateLogs(Effect.logDebug(\"Failed to create indexes\", error), {\n                package: \"@effect/cluster\",\n                module: \"SqlMessageStorage\"\n              })\n            ),\n            Effect.retry({\n              schedule: Schedule.spaced(1000)\n            })\n          ),\n        orElse: () =>\n          // sqlite\n          sql`\n            CREATE INDEX IF NOT EXISTS ${sql(replyLookupIndex)}\n            ON ${repliesTableSql} (request_id, kind, acked);\n          `\n      })\n    }),\n    \"0002_entity_type_size\": Effect.gen(function*() {\n      const sql = (yield* SqlClient.SqlClient).withoutTransforms()\n      const messagesTableSql = sql(messagesTable)\n\n      // resize entity_type to 150 characters\n      yield* sql.onDialectOrElse({\n        mssql: () =>\n          sql`\n            ALTER TABLE ${messagesTableSql} ALTER COLUMN entity_type VARCHAR(150) NOT NULL;\n          `,\n        mysql: () =>\n          sql`\n            ALTER TABLE ${messagesTableSql} MODIFY entity_type VARCHAR(150) NOT NULL;\n          `.unprepared.pipe(Effect.ignore),\n        pg: () =>\n          sql`\n            ALTER TABLE ${messagesTableSql} ALTER COLUMN entity_type TYPE VARCHAR(150);\n          `,\n        orElse: () =>\n          // sqlite\n          Effect.void\n      })\n    })\n  })\n}\n\nconst messageKind = {\n  \"Request\": 0,\n  \"AckChunk\": 1,\n  \"Interrupt\": 2\n} as const satisfies Record<Envelope.Envelope.Any[\"_tag\"], number>\n\nconst replyKind = {\n  \"WithExit\": 0,\n  \"Chunk\": null\n} as const satisfies Record<Reply.Reply<any>[\"_tag\"], number | null>\n\nconst replyFromRow = (row: ReplyRow): Reply.ReplyEncoded<any> =>\n  Number(row.kind) === replyKind.WithExit ?\n    {\n      _tag: \"WithExit\",\n      id: String(row.id),\n      requestId: String(row.request_id),\n      exit: JSON.parse(row.payload)\n    } :\n    {\n      _tag: \"Chunk\",\n      id: String(row.id),\n      requestId: String(row.request_id),\n      values: JSON.parse(row.payload),\n      sequence: Number(row.sequence!)\n    }\n\ntype MessageRow = {\n  readonly id: string | bigint\n  readonly message_id: string | null\n  readonly shard_id: string\n  readonly entity_type: string\n  readonly entity_id: string\n  readonly kind: 0 | 1 | 2 | 0n | 1n | 2n\n  readonly tag: string | null\n  readonly payload: string | null\n  readonly headers: string | null\n  readonly trace_id: string | null\n  readonly span_id: string | null\n  readonly sampled: boolean | number | bigint | null\n  readonly request_id: string | bigint | null\n  readonly reply_id: string | bigint | null\n  readonly deliver_at: number | bigint | null\n}\n\ntype ReplyRow = {\n  readonly id: string | bigint\n  readonly kind: 0 | null | 0n\n  readonly request_id: string | bigint\n  readonly payload: string\n  readonly sequence: number | bigint | null\n}\n\ntype ReplyJoinRow = {\n  readonly reply_reply_id: string | bigint | null\n  readonly reply_payload: string | null\n  readonly reply_sequence: number | bigint | null\n}\n\ntype MessageJoinRow = MessageRow & ReplyJoinRow & {\n  readonly sequence: number | bigint\n}\n"
  },
  {
    "path": "packages/cluster/src/SqlRunnerStorage.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as SqlClient from \"@effect/sql/SqlClient\"\nimport type { SqlError } from \"@effect/sql/SqlError\"\nimport type * as Statement from \"@effect/sql/Statement\"\nimport * as Arr from \"effect/Array\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Scope from \"effect/Scope\"\nimport { PersistenceError } from \"./ClusterError.js\"\nimport { ResourceRef } from \"./internal/resourceRef.js\"\nimport * as RunnerStorage from \"./RunnerStorage.js\"\nimport * as ShardId from \"./ShardId.js\"\nimport * as ShardingConfig from \"./ShardingConfig.js\"\n\nconst withTracerDisabled = Effect.withTracerEnabled(false)\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.fnUntraced(function*(options: {\n  readonly prefix?: string | undefined\n}) {\n  const config = yield* ShardingConfig.ShardingConfig\n  const disableAdvisoryLocks = config.shardLockDisableAdvisory\n  const sql = (yield* SqlClient.SqlClient).withoutTransforms()\n  const prefix = options?.prefix ?? \"cluster\"\n  const table = (name: string) => `${prefix}_${name}`\n\n  const acquireLockConn = sql.onDialectOrElse({\n    pg: () =>\n      Effect.fnUntraced(function*(scope: Scope.Scope) {\n        const conn = yield* Effect.orDie(sql.reserve).pipe(\n          Scope.extend(scope)\n        )\n        const pid = (yield* conn.executeValues(\"SELECT pg_backend_pid()\", []))[0][0] as number\n        yield* Scope.addFinalizerExit(scope, () => Effect.orDie(conn.executeRaw(\"SELECT pg_advisory_unlock_all()\", [])))\n        return [conn, pid] as const\n      }, Effect.orDie),\n    mysql: () =>\n      Effect.fnUntraced(function*(scope: Scope.Scope) {\n        const conn = yield* Effect.orDie(sql.reserve).pipe(\n          Scope.extend(scope)\n        )\n        // we need to get the connection id using IS_USED_LOCK to properly\n        // support vitess\n        let pid: number | undefined = undefined\n        while (pid === undefined) {\n          const address = `cluster:pid:${(Math.random() * Number.MAX_SAFE_INTEGER) | 0}`\n          const taken = (yield* conn.executeValues(\n            `SELECT GET_LOCK('${address}', 10), IS_USED_LOCK('${address}')`,\n            []\n          ))[0] as [1 | null, number]\n          if (taken[0] === null) continue\n          pid = taken[1]\n        }\n        yield* Scope.addFinalizerExit(scope, () => Effect.orDie(conn.executeRaw(\"SELECT RELEASE_ALL_LOCKS()\", [])))\n        return [conn, pid] as const\n      }, Effect.orDie),\n    orElse: () => undefined\n  })\n  const lockConn = acquireLockConn && (yield* ResourceRef.from(yield* Effect.scope, acquireLockConn))\n\n  const runnersTable = table(\"runners\")\n  const runnersTableSql = sql(runnersTable)\n\n  // Migrate old tables if they exist\n  // TODO: Remove in next major version\n  const hasOldTables = yield* sql`SELECT shard_id FROM ${sql(table(\"shards\"))} LIMIT 1`.pipe(\n    Effect.isSuccess\n  )\n  if (hasOldTables) {\n    yield* sql`DROP TABLE ${sql(table(\"shards\"))}`.pipe(Effect.ignore)\n    yield* sql`DROP TABLE ${runnersTableSql}`.pipe(Effect.ignore)\n  }\n\n  yield* sql.onDialectOrElse({\n    mssql: () =>\n      sql`\n        IF OBJECT_ID(N'${runnersTableSql}', N'U') IS NULL\n        CREATE TABLE ${runnersTableSql} (\n          machine_id INT IDENTITY PRIMARY KEY,\n          address VARCHAR(255) NOT NULL,\n          runner TEXT NOT NULL,\n          healthy BIT NOT NULL DEFAULT 1,\n          last_heartbeat DATETIME NOT NULL DEFAULT GETDATE(),\n          UNIQUE(address)\n        )\n      `,\n    mysql: () =>\n      sql`\n        CREATE TABLE IF NOT EXISTS ${runnersTableSql} (\n          machine_id INT AUTO_INCREMENT PRIMARY KEY,\n          address VARCHAR(255) NOT NULL,\n          runner TEXT NOT NULL,\n          healthy BOOLEAN NOT NULL DEFAULT TRUE,\n          last_heartbeat DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,\n          UNIQUE(address)\n        )\n      `,\n    pg: () =>\n      sql`\n        CREATE TABLE IF NOT EXISTS ${runnersTableSql} (\n          machine_id SERIAL PRIMARY KEY,\n          address VARCHAR(255) NOT NULL,\n          runner TEXT NOT NULL,\n          healthy BOOLEAN NOT NULL DEFAULT TRUE,\n          last_heartbeat TIMESTAMP NOT NULL DEFAULT NOW(),\n          UNIQUE(address)\n        )\n      `,\n    orElse: () =>\n      // sqlite\n      sql`\n        CREATE TABLE IF NOT EXISTS ${runnersTableSql} (\n          machine_id INTEGER PRIMARY KEY AUTOINCREMENT,\n          address TEXT NOT NULL,\n          runner TEXT NOT NULL,\n          healthy INTEGER NOT NULL DEFAULT 1,\n          last_heartbeat DATETIME NOT NULL DEFAULT (CURRENT_TIMESTAMP),\n          UNIQUE(address)\n        )\n      `\n  })\n\n  const locksTable = table(\"locks\")\n  const locksTableSql = sql(locksTable)\n\n  yield* sql.onDialectOrElse({\n    mssql: () =>\n      sql`\n        IF OBJECT_ID(N'${locksTableSql}', N'U') IS NULL\n        CREATE TABLE ${locksTableSql} (\n          shard_id VARCHAR(50) PRIMARY KEY,\n          address VARCHAR(255) NOT NULL,\n          acquired_at DATETIME NOT NULL\n        )\n      `,\n    mysql: () =>\n      sql`\n        CREATE TABLE IF NOT EXISTS ${locksTableSql} (\n          shard_id VARCHAR(50) PRIMARY KEY,\n          address VARCHAR(255) NOT NULL,\n          acquired_at DATETIME NOT NULL\n        )\n      `,\n    pg: () =>\n      sql`\n        CREATE TABLE IF NOT EXISTS ${locksTableSql} (\n          shard_id VARCHAR(50) PRIMARY KEY,\n          address VARCHAR(255) NOT NULL,\n          acquired_at TIMESTAMP NOT NULL\n        )\n      `,\n    orElse: () =>\n      // sqlite\n      sql`\n        CREATE TABLE IF NOT EXISTS ${locksTableSql} (\n          shard_id TEXT PRIMARY KEY,\n          address TEXT NOT NULL,\n          acquired_at DATETIME NOT NULL\n        )\n      `\n  })\n\n  const sqlNowString = sql.onDialectOrElse({\n    pg: () => \"NOW()\",\n    mysql: () => \"NOW()\",\n    mssql: () => \"GETDATE()\",\n    orElse: () => \"CURRENT_TIMESTAMP\"\n  })\n  const sqlNow = sql.literal(sqlNowString)\n\n  const expiresSeconds = sql.literal(Math.ceil(Duration.toSeconds(config.shardLockExpiration)).toString())\n  const lockExpiresAt = sql.onDialectOrElse({\n    pg: () => sql`${sqlNow} - INTERVAL '${expiresSeconds} seconds'`,\n    mysql: () => sql`DATE_SUB(${sqlNow}, INTERVAL ${expiresSeconds} SECOND)`,\n    mssql: () => sql`DATEADD(SECOND, -${expiresSeconds}, ${sqlNow})`,\n    orElse: () => sql`datetime(${sqlNow}, '-${expiresSeconds} seconds')`\n  })\n\n  const encodeBoolean = sql.onDialectOrElse({\n    mssql: () => (b: boolean) => (b ? 1 : 0),\n    sqlite: () => (b: boolean) => (b ? 1 : 0),\n    orElse: () => (b: boolean) => b\n  })\n\n  // Upsert runner and return machine_id\n  const insertRunner = sql.onDialectOrElse({\n    mssql: () => (address: string, runner: string, healthy: boolean) =>\n      sql`\n        MERGE ${runnersTableSql} AS target\n        USING (SELECT ${address} AS address, ${runner} AS runner, ${sqlNow} AS last_heartbeat, ${\n        encodeBoolean(healthy)\n      } AS healthy) AS source\n        ON target.address = source.address\n        WHEN MATCHED THEN\n          UPDATE SET runner = source.runner, last_heartbeat = source.last_heartbeat, healthy = source.healthy\n        WHEN NOT MATCHED THEN\n          INSERT (address, runner, last_heartbeat, healthy)\n          VALUES (source.address, source.runner, source.last_heartbeat, source.healthy)\n        OUTPUT INSERTED.machine_id;\n      `.values,\n    mysql: () => (address: string, runner: string, healthy: boolean) =>\n      sql<{ machine_id: number }>`\n        INSERT INTO ${runnersTableSql} (address, runner, last_heartbeat, healthy)\n        VALUES (${address}, ${runner}, ${sqlNow}, ${healthy})\n        ON DUPLICATE KEY UPDATE\n          runner = VALUES(runner),\n          last_heartbeat = VALUES(last_heartbeat),\n          healthy = VALUES(healthy);\n        SELECT machine_id FROM ${runnersTableSql} WHERE address = ${address};\n      `.unprepared.pipe(\n        Effect.map((results: any) => [[results[1][0].machine_id]])\n      ),\n    pg: () => (address: string, runner: string, healthy: boolean) =>\n      sql`\n        INSERT INTO ${runnersTableSql} (address, runner, last_heartbeat, healthy)\n        VALUES (${address}, ${runner}, ${sqlNow}, ${healthy})\n        ON CONFLICT (address) DO UPDATE\n        SET runner = EXCLUDED.runner,\n            last_heartbeat = EXCLUDED.last_heartbeat,\n            healthy = EXCLUDED.healthy\n        RETURNING machine_id\n      `.values,\n    orElse: () => (address: string, runner: string, healthy: boolean) =>\n      // sqlite\n      sql`\n        INSERT INTO ${runnersTableSql} (address, runner, last_heartbeat, healthy)\n        VALUES (${address}, ${runner}, ${sqlNow}, ${encodeBoolean(healthy)})\n        ON CONFLICT(address) DO UPDATE SET\n          runner = excluded.runner,\n          last_heartbeat = excluded.last_heartbeat,\n          healthy = excluded.healthy\n        RETURNING machine_id;\n      `.values\n  })\n\n  const execWithLockConn = <A>(effect: Statement.Statement<A>): Effect.Effect<unknown, SqlError> => {\n    if (!lockConn) return effect\n    const [query, params] = effect.compile()\n    return lockConn.await.pipe(\n      Effect.flatMap(([conn]) => conn.executeRaw(query, params)),\n      Effect.onError(() => lockConn.unsafeRebuild())\n    )\n  }\n  const execWithLockConnUnprepared = <A>(\n    effect: Statement.Statement<A>\n  ): Effect.Effect<ReadonlyArray<ReadonlyArray<any>>, SqlError> => {\n    if (!lockConn) return effect.values\n    const [query, params] = effect.compile()\n    return lockConn.await.pipe(\n      Effect.flatMap(([conn]) => conn.executeUnprepared(query, params, undefined)),\n      Effect.onError(() => lockConn.unsafeRebuild())\n    )\n  }\n  const execWithLockConnValues = <A>(\n    effect: Statement.Statement<A>\n  ): Effect.Effect<ReadonlyArray<ReadonlyArray<any>>, SqlError> => {\n    if (!lockConn) return effect.values\n    const [query, params] = effect.compile()\n    return lockConn.await.pipe(\n      Effect.flatMap(([conn]) => conn.executeValues(query, params)),\n      Effect.onError(() => lockConn.unsafeRebuild())\n    )\n  }\n\n  const acquireLock = sql.onDialectOrElse({\n    pg: () => {\n      if (disableAdvisoryLocks) {\n        return (address: string, shardIds: ReadonlyArray<string>) => {\n          const values = shardIds.map((shardId) =>\n            sql`(${stringLiteral(shardId)}, ${stringLiteral(address)}, ${sqlNow})`\n          )\n          return sql`\n            INSERT INTO ${locksTableSql} (shard_id, address, acquired_at) VALUES ${sql.csv(values)}\n            ON CONFLICT (shard_id) DO UPDATE\n            SET address = ${address}, acquired_at = ${sqlNow}\n            WHERE ${locksTableSql}.address = ${address}\n              OR ${locksTableSql}.acquired_at < ${lockExpiresAt}\n`.pipe(\n            Effect.andThen(acquiredLocks(address, shardIds))\n          )\n        }\n      }\n      return Effect.fnUntraced(function*(_address: string, shardIds: ReadonlyArray<string>) {\n        const [conn, pid] = yield* lockConn!.await\n        const acquiredShardIds: Array<string> = []\n        const toAcquire = new Map(shardIds.map((shardId) => [lockNumbers.get(shardId)!, shardId]))\n        const takenLocks = yield* conn.executeValues(\n          `SELECT objid FROM pg_locks WHERE locktype = 'advisory' AND granted = true AND pid = ${pid} ORDER BY objid`,\n          []\n        )\n        for (let i = 0; i < takenLocks.length; i++) {\n          const lockNum = takenLocks[i][0] as number\n          acquiredShardIds.push(lockNumbersReverse.get(lockNum)!)\n          toAcquire.delete(lockNum)\n        }\n        if (toAcquire.size === 0) {\n          return acquiredShardIds\n        }\n        const rows = yield* conn.executeUnprepared(`SELECT ${pgLocks(toAcquire)}`, [], undefined)\n        const results = rows[0] as Record<string, boolean>\n        for (const shardId in results) {\n          if (results[shardId]) {\n            acquiredShardIds.push(shardId)\n          }\n        }\n        return acquiredShardIds\n      }, Effect.onError(() => lockConn!.unsafeRebuild()))\n    },\n\n    mysql: () => {\n      if (disableAdvisoryLocks) {\n        return (address: string, shardIds: ReadonlyArray<string>) => {\n          const values = shardIds.map((shardId) =>\n            sql`(${stringLiteral(shardId)}, ${stringLiteral(address)}, ${sqlNow})`\n          )\n          return sql`\n            INSERT INTO ${locksTableSql} (shard_id, address, acquired_at) VALUES ${sql.csv(values)}\n            ON DUPLICATE KEY UPDATE\n            address = IF(address = VALUES(address) OR acquired_at < ${lockExpiresAt}, VALUES(address), address),\n            acquired_at = IF(address = VALUES(address) OR acquired_at < ${lockExpiresAt}, VALUES(acquired_at), acquired_at)\n`.unprepared.pipe(\n            Effect.andThen(acquiredLocks(address, shardIds))\n          )\n        }\n      }\n      return Effect.fnUntraced(function*(_address: string, shardIds: ReadonlyArray<string>) {\n        const [conn, pid] = yield* lockConn!.await\n        const takenLocks = (yield* conn.executeValues(`SELECT ${allMySqlTakenLocks}`, []))[0] as Array<number | null>\n        const acquiredShardIds: Array<string> = []\n        const toAcquire: Array<string> = []\n        for (let i = 0; i < shardIds.length; i++) {\n          const shardId = shardIds[i]\n          const lockTakenBy = takenLocks[shardIdsIndex.get(shardId)!]\n          if (lockTakenBy === pid) {\n            acquiredShardIds.push(shardId)\n          } else if (shardIds.includes(shardId)) {\n            toAcquire.push(shardId)\n          }\n        }\n        if (toAcquire.length === 0) {\n          return acquiredShardIds\n        }\n        const results = (yield* conn.executeValues(`SELECT ${mysqlLocks(toAcquire)}`, []))[0] as Array<number>\n        for (let i = 0; i < results.length; i++) {\n          if (results[i] === 1) {\n            acquiredShardIds.push(toAcquire[i])\n          }\n        }\n        return acquiredShardIds\n      }, Effect.onError(() => lockConn!.unsafeRebuild()))\n    },\n\n    mssql: () => (address: string, shardIds: ReadonlyArray<string>) => {\n      const values = shardIds.map((shardId) => sql`(${stringLiteral(shardId)}, ${stringLiteral(address)}, ${sqlNow})`)\n      return sql`\n        MERGE ${locksTableSql} WITH (HOLDLOCK) AS target\n        USING (SELECT * FROM (VALUES ${sql.csv(values)})) AS source (shard_id, address, acquired_at)\n        ON target.shard_id = source.shard_id\n        WHEN MATCHED AND (target.address = source.address OR DATEDIFF(SECOND, target.acquired_at, ${sqlNow}) > ${expiresSeconds}) THEN\n          UPDATE SET address = source.address, acquired_at = source.acquired_at\n        WHEN NOT MATCHED THEN\n          INSERT (shard_id, address, acquired_at)\n          VALUES (source.shard_id, source.address, source.acquired_at);\n      `.pipe(\n        Effect.andThen(acquiredLocks(address, shardIds)),\n        sql.withTransaction\n      )\n    },\n\n    orElse: () => (address: string, shardIds: ReadonlyArray<string>) => {\n      const values = shardIds.map((shardId) => sql`(${stringLiteral(shardId)}, ${stringLiteral(address)}, ${sqlNow})`)\n      return sql`\n        WITH source(shard_id, address, acquired_at) AS (VALUES ${sql.csv(values)})\n        INSERT INTO ${locksTableSql} (shard_id, address, acquired_at)\n        SELECT source.shard_id, source.address, source.acquired_at\n        FROM source\n        WHERE NOT EXISTS (\n          SELECT 1 FROM ${locksTableSql}\n          WHERE shard_id = source.shard_id\n          AND address != ${address}\n          AND (strftime('%s', ${sqlNow}) - strftime('%s', acquired_at)) <= ${expiresSeconds}\n        )\n        ON CONFLICT(shard_id) DO UPDATE\n        SET address = ${address}, acquired_at = ${sqlNow}\n      `.pipe(\n        Effect.andThen(acquiredLocks(address, shardIds)),\n        sql.withTransaction\n      )\n    }\n  })\n\n  const lockNumbers = new Map<string, number>()\n  const lockNumbersReverse = new Map<number, string>()\n  for (let i = 0; i < config.shardGroups.length; i++) {\n    const group = config.shardGroups[i]\n    const base = (i + 1) * 1000000\n    for (let shard = 1; shard <= config.shardsPerGroup; shard++) {\n      const shardId = ShardId.make(group, shard).toString()\n      const lockNum = base + shard\n      lockNumbers.set(shardId, lockNum)\n      lockNumbersReverse.set(lockNum, shardId)\n    }\n  }\n\n  const shardIdsIndex = new Map<string, number>()\n  const lockNames = new Map<string, string>()\n  const lockNamesReverse = new Map<string, string>()\n  {\n    let index = 0\n    for (let i = 0; i < config.shardGroups.length; i++) {\n      const group = config.shardGroups[i]\n      for (let shard = 1; shard <= config.shardsPerGroup; shard++) {\n        const shardId = ShardId.make(group, shard).toString()\n        const lockName = `${prefix}.${shardId}`\n        shardIdsIndex.set(shardId, index++)\n        lockNames.set(shardId, lockName)\n        lockNamesReverse.set(lockName, shardId)\n      }\n    }\n  }\n\n  const pgLocks = (shardIdsMap: Map<number, string>) =>\n    Array.from(\n      shardIdsMap.entries(),\n      ([lockNum, shardId]) => `pg_try_advisory_lock(${lockNum}) AS \"${shardId}\"`\n    ).join(\", \")\n\n  const mysqlLocks = (shardIds: ReadonlyArray<string>) =>\n    shardIds.map((shardId) => `GET_LOCK('${lockNames.get(shardId)!}', 0) AS \"${shardId}\"`).join(\", \")\n\n  const allMySqlTakenLocks = Array.from(\n    lockNames.entries(),\n    ([shardId, lockName]) => `IS_USED_LOCK('${lockName}') AS \"${shardId}\"`\n  ).join(\", \")\n\n  const acquiredLocks = (address: string, shardIds: ReadonlyArray<string>) =>\n    sql<{ shard_id: string }>`\n      SELECT shard_id FROM ${sql(locksTable)}\n      WHERE address = ${address}\n      AND acquired_at >= ${lockExpiresAt}\n      AND shard_id IN ${stringLiteralArr(shardIds)}\n    `.values.pipe(\n      Effect.map((rows) => rows.map((row) => row[0] as string))\n    )\n\n  const wrapString = sql.onDialectOrElse({\n    mssql: () => (s: string) => `N'${s}'`,\n    orElse: () => (s: string) => `'${s}'`\n  })\n  const stringLiteral = (s: string) => sql.literal(wrapString(s))\n  const stringLiteralArr = (arr: ReadonlyArray<string>) => sql.literal(`(${arr.map(wrapString).join(\",\")})`)\n\n  const refreshShards = sql.onDialectOrElse({\n    pg: () => {\n      if (!disableAdvisoryLocks) return acquireLock\n      return (address: string, shardIds: ReadonlyArray<string>) =>\n        sql`\n          UPDATE ${locksTableSql}\n          SET acquired_at = ${sqlNow}\n          WHERE address = ${address} AND shard_id IN ${stringLiteralArr(shardIds)}\n          RETURNING shard_id\n        `.pipe(\n          execWithLockConnValues,\n          Effect.map((rows) => rows.map((row) => row[0] as string))\n        )\n    },\n    mysql: () => {\n      if (!disableAdvisoryLocks) return acquireLock\n      return (address: string, shardIds: ReadonlyArray<string>) => {\n        const shardIdsStr = stringLiteralArr(shardIds)\n        return sql<Array<{ shard_id: string }>>`\n          UPDATE ${locksTableSql}\n          SET acquired_at = ${sqlNow}\n          WHERE address = ${address} AND shard_id IN ${shardIdsStr};\n          SELECT shard_id FROM ${locksTableSql} WHERE address = ${address} AND shard_id IN ${shardIdsStr}\n        `.pipe(\n          execWithLockConnUnprepared,\n          Effect.map((rows) => rows[1].map((row) => row.shard_id))\n        )\n      }\n    },\n    mssql: () => (address: string, shardIds: ReadonlyArray<string>) =>\n      sql`\n        UPDATE ${locksTableSql}\n        SET acquired_at = ${sqlNow}\n        OUTPUT inserted.shard_id\n        WHERE address = ${address} AND shard_id IN ${stringLiteralArr(shardIds)}\n      `.pipe(execWithLockConnValues, Effect.map((rows) => rows.map((row) => row[0] as string))),\n    orElse: () => (address: string, shardIds: ReadonlyArray<string>) =>\n      sql`\n        UPDATE ${locksTableSql}\n        SET acquired_at = ${sqlNow}\n        WHERE address = ${address} AND shard_id IN ${stringLiteralArr(shardIds)}\n        RETURNING shard_id\n      `.pipe(execWithLockConnValues, Effect.map((rows) => rows.map((row) => row[0] as string)))\n  })\n\n  return RunnerStorage.makeEncoded({\n    getRunners: sql`SELECT runner, healthy FROM ${runnersTableSql} WHERE last_heartbeat > ${lockExpiresAt}`.values.pipe(\n      PersistenceError.refail,\n      Effect.map(Arr.map(([runner, healthy]) => [String(runner), Boolean(healthy)] as const)),\n      withTracerDisabled\n    ),\n\n    register: (address, runner, healthy) =>\n      insertRunner(address, runner, healthy).pipe(\n        Effect.map((rows: any) => Number(rows[0][0])),\n        PersistenceError.refail,\n        withTracerDisabled\n      ),\n\n    unregister: (address) =>\n      sql`DELETE FROM ${runnersTableSql} WHERE address = ${address} OR last_heartbeat < ${lockExpiresAt}`.pipe(\n        Effect.asVoid,\n        PersistenceError.refail,\n        withTracerDisabled\n      ),\n\n    setRunnerHealth: (address, healthy) =>\n      sql`UPDATE ${runnersTableSql} SET healthy = ${encodeBoolean(healthy)} WHERE address = ${address}`\n        .pipe(\n          Effect.asVoid,\n          PersistenceError.refail,\n          withTracerDisabled\n        ),\n\n    acquire: (address, shardIds) =>\n      acquireLock(address, shardIds).pipe(\n        PersistenceError.refail,\n        withTracerDisabled\n      ),\n\n    refresh: (address, shardIds) =>\n      sql`UPDATE ${runnersTableSql} SET last_heartbeat = ${sqlNow} WHERE address = ${address}`.pipe(\n        execWithLockConn,\n        shardIds.length > 0 ?\n          Effect.andThen(refreshShards(address, shardIds)) :\n          Effect.as([]),\n        PersistenceError.refail\n      ),\n\n    release: sql.onDialectOrElse({\n      pg: () => {\n        if (disableAdvisoryLocks) {\n          return (address: string, shardId: string) =>\n            sql`DELETE FROM ${locksTableSql} WHERE address = ${address} AND shard_id = ${shardId}`.pipe(\n              PersistenceError.refail\n            )\n        }\n        return Effect.fnUntraced(\n          function*(_address, shardId) {\n            const lockNum = lockNumbers.get(shardId)!\n            for (let i = 0; i < 5; i++) {\n              const [conn] = yield* lockConn!.await\n              yield* conn.executeRaw(`SELECT pg_advisory_unlock(${lockNum})`, [])\n              const takenLocks = yield* conn.executeValues(\n                `SELECT 1 FROM pg_locks WHERE locktype = 'advisory' AND granted = true AND pid = pg_backend_pid() AND objid = ${lockNum}`,\n                []\n              )\n              if (takenLocks.length === 0) return\n            }\n            const [conn] = yield* lockConn!.await\n            yield* conn.executeRaw(`SELECT pg_advisory_unlock_all()`, [])\n          },\n          Effect.onError(() => lockConn!.unsafeRebuild()),\n          Effect.asVoid,\n          PersistenceError.refail\n        )\n      },\n      mysql: () => {\n        if (disableAdvisoryLocks) {\n          return (address: string, shardId: string) =>\n            sql`DELETE FROM ${locksTableSql} WHERE address = ${address} AND shard_id = ${shardId}`.pipe(\n              PersistenceError.refail\n            )\n        }\n        return Effect.fnUntraced(\n          function*(_address, shardId) {\n            const lockName = lockNames.get(shardId)!\n            while (true) {\n              const [conn, pid] = yield* lockConn!.await\n              yield* conn.executeRaw(`SELECT RELEASE_LOCK('${lockName}')`, [])\n              const takenLocks = yield* conn.executeValues(\n                `SELECT IS_USED_LOCK('${lockName}')`,\n                []\n              )\n              if (takenLocks.length === 0 || takenLocks[0][0] !== pid) return\n            }\n          },\n          Effect.onError(() => lockConn!.unsafeRebuild()),\n          Effect.asVoid,\n          PersistenceError.refail\n        )\n      },\n      orElse: () => (address, shardId) =>\n        sql`DELETE FROM ${locksTableSql} WHERE address = ${address} AND shard_id = ${shardId}`.pipe(\n          PersistenceError.refail\n        )\n    }),\n\n    releaseAll: sql.onDialectOrElse({\n      pg: () => (address) => {\n        if (disableAdvisoryLocks) {\n          return sql`DELETE FROM ${locksTableSql} WHERE address = ${address}`.pipe(\n            PersistenceError.refail,\n            withTracerDisabled\n          )\n        }\n        return sql`SELECT pg_advisory_unlock_all()`.pipe(\n          execWithLockConn,\n          Effect.asVoid,\n          PersistenceError.refail,\n          withTracerDisabled\n        )\n      },\n      mysql: () => (address) => {\n        if (disableAdvisoryLocks) {\n          return sql`DELETE FROM ${locksTableSql} WHERE address = ${address}`.pipe(\n            PersistenceError.refail,\n            withTracerDisabled\n          )\n        }\n        return sql`SELECT RELEASE_ALL_LOCKS()`.pipe(\n          execWithLockConn,\n          Effect.asVoid,\n          PersistenceError.refail,\n          withTracerDisabled\n        )\n      },\n      orElse: () => (address) =>\n        sql`DELETE FROM ${locksTableSql} WHERE address = ${address}`.pipe(\n          PersistenceError.refail,\n          withTracerDisabled\n        )\n    })\n  })\n}, withTracerDisabled)\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer: Layer.Layer<\n  RunnerStorage.RunnerStorage,\n  SqlError,\n  SqlClient.SqlClient | ShardingConfig.ShardingConfig\n> = Layer.scoped(RunnerStorage.RunnerStorage)(make({}))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerWith = (options: {\n  readonly prefix?: string | undefined\n}): Layer.Layer<RunnerStorage.RunnerStorage, SqlError, SqlClient.SqlClient | ShardingConfig.ShardingConfig> =>\n  Layer.scoped(RunnerStorage.RunnerStorage)(make(options))\n"
  },
  {
    "path": "packages/cluster/src/TestRunner.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Layer from \"effect/Layer\"\nimport * as MessageStorage from \"./MessageStorage.js\"\nimport * as RunnerHealth from \"./RunnerHealth.js\"\nimport * as Runners from \"./Runners.js\"\nimport * as RunnerStorage from \"./RunnerStorage.js\"\nimport * as Sharding from \"./Sharding.js\"\nimport * as ShardingConfig from \"./ShardingConfig.js\"\n\n/**\n * An in-memory cluster that can be used for testing purposes.\n *\n * MessageStorage is backed by an in-memory driver, and RunnerStorage is backed\n * by an in-memory driver.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layer: Layer.Layer<\n  Sharding.Sharding | Runners.Runners | MessageStorage.MessageStorage | MessageStorage.MemoryDriver\n> = Sharding.layer.pipe(\n  Layer.provideMerge(Runners.layerNoop),\n  Layer.provideMerge(MessageStorage.layerMemory),\n  Layer.provide([RunnerStorage.layerMemory, RunnerHealth.layerNoop]),\n  Layer.provide(ShardingConfig.layer())\n)\n"
  },
  {
    "path": "packages/cluster/src/index.ts",
    "content": "/**\n * @since 1.0.0\n */\nexport * as ClusterCron from \"./ClusterCron.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as ClusterError from \"./ClusterError.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as ClusterMetrics from \"./ClusterMetrics.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as ClusterSchema from \"./ClusterSchema.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as ClusterWorkflowEngine from \"./ClusterWorkflowEngine.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as DeliverAt from \"./DeliverAt.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Entity from \"./Entity.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EntityAddress from \"./EntityAddress.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EntityId from \"./EntityId.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EntityProxy from \"./EntityProxy.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EntityProxyServer from \"./EntityProxyServer.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EntityResource from \"./EntityResource.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EntityType from \"./EntityType.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Envelope from \"./Envelope.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as HttpRunner from \"./HttpRunner.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as K8sHttpClient from \"./K8sHttpClient.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as MachineId from \"./MachineId.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Message from \"./Message.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as MessageStorage from \"./MessageStorage.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Reply from \"./Reply.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Runner from \"./Runner.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as RunnerAddress from \"./RunnerAddress.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as RunnerHealth from \"./RunnerHealth.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as RunnerServer from \"./RunnerServer.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as RunnerStorage from \"./RunnerStorage.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Runners from \"./Runners.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as ShardId from \"./ShardId.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Sharding from \"./Sharding.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as ShardingConfig from \"./ShardingConfig.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as ShardingRegistrationEvent from \"./ShardingRegistrationEvent.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as SingleRunner from \"./SingleRunner.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Singleton from \"./Singleton.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as SingletonAddress from \"./SingletonAddress.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Snowflake from \"./Snowflake.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as SocketRunner from \"./SocketRunner.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as SqlMessageStorage from \"./SqlMessageStorage.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as SqlRunnerStorage from \"./SqlRunnerStorage.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as TestRunner from \"./TestRunner.js\"\n"
  },
  {
    "path": "packages/cluster/src/internal/entityManager.ts",
    "content": "import type * as Rpc from \"@effect/rpc/Rpc\"\nimport { RequestId } from \"@effect/rpc/RpcMessage\"\nimport * as RpcServer from \"@effect/rpc/RpcServer\"\nimport * as Arr from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport type { DurationInput } from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport * as Exit from \"effect/Exit\"\nimport type * as Fiber from \"effect/Fiber\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport { identity } from \"effect/Function\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as Metric from \"effect/Metric\"\nimport * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as Runtime from \"effect/Runtime\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Schema from \"effect/Schema\"\nimport * as Scope from \"effect/Scope\"\nimport { AlreadyProcessingMessage, EntityNotAssignedToRunner, MailboxFull, MalformedMessage } from \"../ClusterError.js\"\nimport * as ClusterMetrics from \"../ClusterMetrics.js\"\nimport { Persisted, Uninterruptible } from \"../ClusterSchema.js\"\nimport type { Entity, HandlersFrom } from \"../Entity.js\"\nimport { CurrentAddress, CurrentRunnerAddress, KeepAliveLatch, KeepAliveRpc, Request } from \"../Entity.js\"\nimport type { EntityAddress } from \"../EntityAddress.js\"\nimport type { EntityId } from \"../EntityId.js\"\nimport type * as Envelope from \"../Envelope.js\"\nimport * as Message from \"../Message.js\"\nimport * as MessageStorage from \"../MessageStorage.js\"\nimport * as Reply from \"../Reply.js\"\nimport type { RunnerAddress } from \"../RunnerAddress.js\"\nimport type { ShardId } from \"../ShardId.js\"\nimport type { Sharding } from \"../Sharding.js\"\nimport { ShardingConfig } from \"../ShardingConfig.js\"\nimport * as Snowflake from \"../Snowflake.js\"\nimport { EntityReaper } from \"./entityReaper.js\"\nimport { joinAllDiscard } from \"./fiber.js\"\nimport { internalInterruptors } from \"./interruptors.js\"\nimport { ResourceMap } from \"./resourceMap.js\"\nimport { ResourceRef } from \"./resourceRef.js\"\n\n/** @internal */\nexport interface EntityManager {\n  readonly sendLocal: <R extends Rpc.Any>(\n    message: Message.IncomingLocal<R>\n  ) => Effect.Effect<void, EntityNotAssignedToRunner | MailboxFull | AlreadyProcessingMessage>\n\n  readonly send: (\n    message: Message.Incoming<any>\n  ) => Effect.Effect<void, EntityNotAssignedToRunner | MailboxFull | AlreadyProcessingMessage>\n\n  readonly isProcessingFor: (message: Message.Incoming<any>, options?: {\n    readonly excludeReplies?: boolean\n  }) => boolean\n  readonly clearProcessed: () => void\n\n  readonly interruptShard: (shardId: ShardId) => Effect.Effect<void>\n\n  readonly activeEntityCount: Effect.Effect<number>\n}\n\n// Represents the entities managed by this entity manager\n/** @internal */\nexport type EntityState = {\n  readonly address: EntityAddress\n  readonly scope: Scope.Scope\n  readonly activeRequests: Map<bigint, {\n    readonly rpc: Rpc.AnyWithProps\n    readonly message: Message.IncomingRequestLocal<any>\n    sentReply: boolean\n    lastSentChunk: Option.Option<Reply.Chunk<Rpc.Any>>\n    sequence: number\n  }>\n  lastActiveCheck: number\n  write: RpcServer.RpcServer<any>[\"write\"]\n  readonly keepAliveLatch: Effect.Latch\n  keepAliveEnabled: boolean\n}\n\n/** @internal */\nexport const make = Effect.fnUntraced(function*<\n  Type extends string,\n  Rpcs extends Rpc.Any,\n  Handlers extends HandlersFrom<Rpcs>,\n  RX\n>(\n  entity: Entity<Type, Rpcs>,\n  buildHandlers: Effect.Effect<Handlers, never, RX>,\n  options: {\n    readonly sharding: Sharding[\"Type\"]\n    readonly storage: MessageStorage.MessageStorage[\"Type\"]\n    readonly runnerAddress: RunnerAddress\n    readonly maxIdleTime?: DurationInput | undefined\n    readonly concurrency?: number | \"unbounded\" | undefined\n    readonly mailboxCapacity?: number | \"unbounded\" | undefined\n    readonly disableFatalDefects?: boolean | undefined\n    readonly defectRetryPolicy?: Schedule.Schedule<any, unknown, never> | undefined\n    readonly spanAttributes?: Record<string, string> | undefined\n  }\n) {\n  const config = yield* ShardingConfig\n  const snowflakeGen = yield* Snowflake.Generator\n  const managerScope = yield* Effect.scope\n  const storageEnabled = options.storage !== MessageStorage.noop\n  const mailboxCapacity = options.mailboxCapacity ?? config.entityMailboxCapacity\n  const clock = yield* Effect.clock\n  const context = yield* Effect.context<Rpc.Context<Rpcs> | Rpc.Middleware<Rpcs> | RX>()\n  const retryDriver = yield* Schedule.driver(\n    options.defectRetryPolicy ? Schedule.andThen(options.defectRetryPolicy, defaultRetryPolicy) : defaultRetryPolicy\n  )\n  const entityRpcs = new Map(entity.protocol.requests)\n\n  // add internal rpcs\n  entityRpcs.set(KeepAliveRpc._tag, KeepAliveRpc as any)\n\n  const activeServers = new Map<EntityId, EntityState>()\n  const serverCloseLatches = new Map<EntityAddress, Effect.Latch>()\n  const processedRequestIds = new Set<Snowflake.Snowflake>()\n\n  const entities: ResourceMap<\n    EntityAddress,\n    EntityState,\n    EntityNotAssignedToRunner\n  > = yield* ResourceMap.make(Effect.fnUntraced(function*(address: EntityAddress) {\n    if (!options.sharding.hasShardId(address.shardId)) {\n      return yield* new EntityNotAssignedToRunner({ address })\n    }\n\n    const scope = yield* Effect.scope\n    const endLatch = Effect.unsafeMakeLatch()\n    const keepAliveLatch = Effect.unsafeMakeLatch(false)\n\n    // on shutdown, reset the storage for the entity\n    yield* Scope.addFinalizerExit(\n      scope,\n      () => {\n        serverCloseLatches.get(address)?.unsafeOpen()\n        serverCloseLatches.delete(address)\n        return Effect.void\n      }\n    )\n\n    const activeRequests: EntityState[\"activeRequests\"] = new Map()\n    let defectRequestIds: Array<bigint> = []\n\n    // the server is stored in a ref, so if there is a defect, we can\n    // swap the server without losing the active requests\n    const writeRef = yield* ResourceRef.from(\n      scope,\n      Effect.fnUntraced(function*(scope) {\n        let isShuttingDown = false\n\n        // Initiate the behavior for the entity\n        const handlers = yield* (entity.protocol.toHandlersContext(buildHandlers).pipe(\n          Effect.provide(context.pipe(\n            Context.add(CurrentAddress, address),\n            Context.add(CurrentRunnerAddress, options.runnerAddress),\n            Context.add(KeepAliveLatch, keepAliveLatch),\n            Context.add(Scope.Scope, scope)\n          )),\n          Effect.locally(FiberRef.currentLogAnnotations, HashMap.empty())\n        ) as Effect.Effect<Context.Context<Rpc.ToHandler<Rpcs>>>)\n\n        const server = yield* RpcServer.makeNoSerialization(entity.protocol, {\n          spanPrefix: `${entity.type}(${address.entityId})`,\n          spanAttributes: {\n            ...options.spanAttributes,\n            \"entity.type\": entity.type,\n            \"entity.id\": address.entityId\n          },\n          concurrency: options.concurrency ?? 1,\n          disableFatalDefects: options.disableFatalDefects,\n          onFromServer(response): Effect.Effect<void> {\n            switch (response._tag) {\n              case \"Exit\": {\n                const request = activeRequests.get(response.requestId)\n                if (!request) return Effect.void\n\n                request.sentReply = true\n\n                // For durable messages, ignore interrupts during shutdown.\n                // They will be retried when the entity is restarted.\n                // Also, if the request is uninterruptible, we ignore the\n                // interrupt.\n                if (\n                  storageEnabled &&\n                  Context.get(request.rpc.annotations, Persisted) &&\n                  Exit.isFailure(response.exit) &&\n                  Exit.isInterrupted(response.exit) &&\n                  (isShuttingDown || Uninterruptible.forServer(request.rpc.annotations))\n                ) {\n                  if (!isShuttingDown) {\n                    return server.write(0, {\n                      ...request.message.envelope,\n                      id: RequestId(request.message.envelope.requestId),\n                      tag: request.message.envelope.tag as any,\n                      payload: new Request({\n                        ...request.message.envelope,\n                        lastSentChunk: request.lastSentChunk\n                      } as any) as any\n                    }).pipe(\n                      Effect.forkIn(scope)\n                    )\n                  }\n                  activeRequests.delete(response.requestId)\n                  return options.storage.unregisterReplyHandler(request.message.envelope.requestId)\n                }\n                return retryRespond(\n                  4,\n                  Effect.suspend(() =>\n                    request.message.respond(\n                      new Reply.WithExit({\n                        requestId: Snowflake.Snowflake(response.requestId),\n                        id: snowflakeGen.unsafeNext(),\n                        exit: response.exit\n                      })\n                    )\n                  )\n                ).pipe(\n                  Effect.flatMap(() => {\n                    processedRequestIds.add(request.message.envelope.requestId)\n                    activeRequests.delete(response.requestId)\n\n                    // ensure that the reaper does not remove the entity as we haven't\n                    // been \"idle\" yet\n                    if (activeRequests.size === 0) {\n                      state.lastActiveCheck = clock.unsafeCurrentTimeMillis()\n                    }\n\n                    return Effect.void\n                  }),\n                  Effect.orDie\n                )\n              }\n              case \"Chunk\": {\n                const request = activeRequests.get(response.requestId)\n                if (!request) return Effect.void\n                const sequence = request.sequence\n                request.sequence++\n                if (!request.sentReply) {\n                  request.sentReply = true\n                }\n                return Effect.orDie(retryRespond(\n                  4,\n                  Effect.suspend(() => {\n                    const reply = new Reply.Chunk({\n                      requestId: Snowflake.Snowflake(response.requestId),\n                      id: snowflakeGen.unsafeNext(),\n                      sequence,\n                      values: response.values\n                    })\n                    request.lastSentChunk = Option.some(reply)\n                    return request.message.respond(reply)\n                  })\n                ))\n              }\n              case \"Defect\": {\n                return Effect.forkIn(onDefect(Cause.die(response.defect)), managerScope)\n              }\n              case \"ClientEnd\": {\n                return endLatch.open\n              }\n            }\n          }\n        }).pipe(\n          Scope.extend(scope),\n          Effect.provide(handlers)\n        )\n\n        yield* Scope.addFinalizer(\n          scope,\n          Effect.sync(() => {\n            isShuttingDown = true\n          })\n        )\n\n        if (defectRequestIds.length > 0) {\n          for (const id of defectRequestIds) {\n            const { lastSentChunk, message } = activeRequests.get(id)!\n            yield* server.write(0, {\n              ...message.envelope,\n              id: RequestId(message.envelope.requestId),\n              tag: message.envelope.tag as any,\n              payload: new Request({\n                ...message.envelope,\n                lastSentChunk\n              } as any) as any\n            })\n          }\n          defectRequestIds = []\n        }\n\n        return server.write\n      })\n    )\n\n    function onDefect(cause: Cause.Cause<never>): Effect.Effect<void> {\n      if (!activeServers.has(address.entityId)) {\n        return endLatch.open\n      }\n      const effect = writeRef.unsafeRebuild()\n      defectRequestIds = Array.from(activeRequests.keys())\n      return Effect.logError(\"Defect in entity, restarting\", cause).pipe(\n        Effect.andThen(Effect.ignore(retryDriver.next(void 0))),\n        Effect.flatMap(() => activeServers.has(address.entityId) ? effect : endLatch.open),\n        Effect.annotateLogs({\n          module: \"EntityManager\",\n          address,\n          runner: options.runnerAddress\n        }),\n        Effect.catchAllCause(onDefect)\n      )\n    }\n\n    const state: EntityState = {\n      scope,\n      address,\n      write(clientId, message) {\n        if (writeRef.state.current._tag !== \"Acquired\") {\n          return Effect.flatMap(writeRef.await, (write) => write(clientId, message))\n        }\n        return writeRef.state.current.value(clientId, message)\n      },\n      activeRequests,\n      lastActiveCheck: clock.unsafeCurrentTimeMillis(),\n      keepAliveLatch,\n      keepAliveEnabled: false\n    }\n\n    // During shutdown, signal that no more messages will be processed\n    // and wait for the fiber to complete.\n    //\n    // If the termination timeout is reached, let the server clean itself up\n    yield* Scope.addFinalizer(\n      scope,\n      Effect.withFiberRuntime((fiber) => {\n        activeServers.delete(address.entityId)\n        serverCloseLatches.set(address, Effect.unsafeMakeLatch(false))\n        internalInterruptors.add(fiber.id())\n        return state.write(0, { _tag: \"Eof\" }).pipe(\n          Effect.andThen(Effect.interruptible(endLatch.await)),\n          Effect.timeoutOption(config.entityTerminationTimeout)\n        )\n      })\n    )\n    activeServers.set(address.entityId, state)\n\n    return state\n  }, Effect.locally(FiberRef.currentLogAnnotations, HashMap.empty())))\n\n  const reaper = yield* EntityReaper\n  const maxIdleTime = Duration.toMillis(options.maxIdleTime ?? config.entityMaxIdleTime)\n  if (Number.isFinite(maxIdleTime)) {\n    yield* reaper.register({\n      maxIdleTime,\n      servers: activeServers,\n      entities\n    })\n  }\n\n  // update metrics for active servers\n  const gauge = ClusterMetrics.entities.pipe(Metric.tagged(\"type\", entity.type))\n  yield* Effect.sync(() => {\n    gauge.unsafeUpdate(BigInt(activeServers.size), [])\n  }).pipe(\n    Effect.andThen(Effect.sleep(1000)),\n    Effect.forever,\n    Effect.forkIn(managerScope)\n  )\n\n  function sendLocal<R extends Rpc.Any>(\n    message: Message.IncomingLocal<R>\n  ): Effect.Effect<void, EntityNotAssignedToRunner | MailboxFull | AlreadyProcessingMessage> {\n    return Effect.locally(\n      Effect.flatMap(\n        entities.get(message.envelope.address),\n        (server): Effect.Effect<void, EntityNotAssignedToRunner | MailboxFull | AlreadyProcessingMessage> => {\n          switch (message._tag) {\n            case \"IncomingRequestLocal\": {\n              // If the request is already running, then we might have more than\n              // one sender for the same request. In this case, the other senders\n              // should resume from storage only.\n              let entry = server.activeRequests.get(message.envelope.requestId)\n              if (entry || processedRequestIds.has(message.envelope.requestId)) {\n                return Effect.fail(\n                  new AlreadyProcessingMessage({\n                    envelopeId: message.envelope.requestId,\n                    address: message.envelope.address\n                  })\n                )\n              }\n\n              const rpc = entityRpcs.get(message.envelope.tag)! as any as Rpc.AnyWithProps\n              if (!storageEnabled && Context.get(rpc.annotations, Persisted)) {\n                return Effect.dieMessage(\n                  \"EntityManager.sendLocal: Cannot process a persisted message without MessageStorage\"\n                )\n              }\n\n              // Cluster internal RPCs\n\n              // keep-alive RPC\n              if (rpc._tag === KeepAliveRpc._tag) {\n                const msg = message as unknown as Message.IncomingRequestLocal<typeof KeepAliveRpc>\n                const reply = Effect.suspend(() =>\n                  Effect.orDie(retryRespond(\n                    4,\n                    msg.respond(\n                      new Reply.WithExit<typeof KeepAliveRpc>({\n                        requestId: message.envelope.requestId,\n                        id: snowflakeGen.unsafeNext(),\n                        exit: Exit.void\n                      })\n                    )\n                  ))\n                )\n\n                if (server.keepAliveEnabled) return reply\n                server.keepAliveEnabled = true\n                return server.keepAliveLatch.whenOpen(Effect.suspend(() => {\n                  server.keepAliveEnabled = false\n                  return reply\n                })).pipe(\n                  Effect.forkIn(server.scope),\n                  Effect.asVoid\n                )\n              }\n\n              if (mailboxCapacity !== \"unbounded\" && server.activeRequests.size >= mailboxCapacity) {\n                return Effect.fail(new MailboxFull({ address: message.envelope.address }))\n              }\n\n              entry = {\n                rpc,\n                message,\n                sentReply: false,\n                lastSentChunk: message.lastSentReply as any,\n                sequence: Option.match(message.lastSentReply, {\n                  onNone: () => 0,\n                  onSome: (reply) => reply._tag === \"Chunk\" ? reply.sequence + 1 : 0\n                })\n              }\n              server.activeRequests.set(message.envelope.requestId, entry)\n              return server.write(0, {\n                ...message.envelope,\n                id: RequestId(message.envelope.requestId),\n                payload: new Request({\n                  ...message.envelope,\n                  lastSentChunk: message.lastSentReply as any\n                })\n              })\n            }\n            case \"IncomingEnvelope\": {\n              const entry = server.activeRequests.get(message.envelope.requestId)\n              if (!entry) {\n                return Effect.void\n              } else if (\n                message.envelope._tag === \"AckChunk\" &&\n                Option.isSome(entry.lastSentChunk) &&\n                message.envelope.replyId !== entry.lastSentChunk.value.id\n              ) {\n                return Effect.void\n              }\n              return server.write(\n                0,\n                message.envelope._tag === \"AckChunk\"\n                  ? { _tag: \"Ack\", requestId: RequestId(message.envelope.requestId) }\n                  : { _tag: \"Interrupt\", requestId: RequestId(message.envelope.requestId), interruptors: [] }\n              )\n            }\n          }\n        }\n      ),\n      FiberRef.currentLogAnnotations,\n      HashMap.empty()\n    )\n  }\n\n  const decodeMessage = makeMessageDecode(entity, entityRpcs)\n\n  const runFork = Runtime.runFork(\n    yield* Effect.runtime<never>().pipe(\n      Effect.interruptible\n    )\n  )\n\n  return identity<EntityManager>({\n    interruptShard: (shardId: ShardId) =>\n      Effect.suspend(function loop(): Effect.Effect<void> {\n        const fibers = Arr.empty<Fiber.RuntimeFiber<void>>()\n        activeServers.forEach((state) => {\n          if (shardId[Equal.symbol](state.address.shardId)) {\n            fibers.push(runFork(entities.removeIgnore(state.address)))\n          }\n        })\n        serverCloseLatches.forEach((latch, address) => {\n          if (shardId[Equal.symbol](address.shardId)) {\n            fibers.push(runFork(latch.await))\n          }\n        })\n        if (fibers.length === 0) return Effect.void\n        return Effect.flatMap(joinAllDiscard(fibers), loop)\n      }),\n    isProcessingFor(message, options) {\n      if (options?.excludeReplies !== true && processedRequestIds.has(message.envelope.requestId)) {\n        return true\n      }\n      const state = activeServers.get(message.envelope.address.entityId)\n      if (!state) return false\n      const request = state.activeRequests.get(message.envelope.requestId)\n      if (request === undefined) {\n        return false\n      } else if (options?.excludeReplies && request.sentReply) {\n        return false\n      }\n      return true\n    },\n    clearProcessed() {\n      processedRequestIds.clear()\n    },\n    sendLocal,\n    send: (message) =>\n      decodeMessage(message).pipe(\n        Effect.matchEffect({\n          onFailure: (cause) => {\n            if (message._tag === \"IncomingEnvelope\") {\n              return Effect.die(new MalformedMessage({ cause }))\n            }\n            return Effect.orDie(message.respond(\n              new Reply.ReplyWithContext({\n                reply: new Reply.WithExit({\n                  id: snowflakeGen.unsafeNext(),\n                  requestId: message.envelope.requestId,\n                  exit: Exit.die(new MalformedMessage({ cause }))\n                }),\n                rpc: entityRpcs.get(message.envelope.tag)!,\n                context\n              })\n            ))\n          },\n          onSuccess: (decoded) => {\n            if (decoded._tag === \"IncomingEnvelope\") {\n              return sendLocal(\n                new Message.IncomingEnvelope(decoded)\n              )\n            }\n            const request = message as Message.IncomingRequest<any>\n            const rpc = entityRpcs.get(decoded.envelope.tag)!\n            return sendLocal(\n              new Message.IncomingRequestLocal({\n                envelope: decoded.envelope,\n                lastSentReply: decoded.lastSentReply,\n                respond: (reply) =>\n                  request.respond(\n                    new Reply.ReplyWithContext({\n                      reply,\n                      rpc,\n                      context\n                    })\n                  )\n              })\n            )\n          }\n        }),\n        Effect.provide(context as Context.Context<unknown>)\n      ),\n    activeEntityCount: Effect.sync(() => activeServers.size)\n  })\n})\n\nconst defaultRetryPolicy = Schedule.exponential(500, 1.5).pipe(\n  Schedule.union(Schedule.spaced(\"10 seconds\"))\n)\n\nconst makeMessageDecode = <Type extends string, Rpcs extends Rpc.Any>(\n  entity: Entity<Type, Rpcs>,\n  entityRpcs: Map<string, Rpcs>\n) => {\n  const decodeRequest = (\n    message: Message.IncomingRequest<Rpcs>,\n    rpc: Rpc.AnyWithProps\n  ) => {\n    const payload = Schema.decode(rpc.payloadSchema)(message.envelope.payload)\n    const lastSentReply = Option.isSome(message.lastSentReply)\n      ? Effect.asSome(Schema.decode(Reply.Reply(rpc as any))(message.lastSentReply.value))\n      : Effect.succeedNone\n    return Effect.flatMap(payload, (payload) =>\n      Effect.map(lastSentReply, (lastSentReply) => ({\n        _tag: \"IncomingRequest\" as const,\n        envelope: {\n          ...message.envelope,\n          payload\n        } as Envelope.Request.Any,\n        lastSentReply\n      })))\n  }\n\n  return (message: Message.Incoming<Rpcs>): Effect.Effect<\n    {\n      readonly _tag: \"IncomingRequest\"\n      readonly envelope: Envelope.Request.Any\n      readonly lastSentReply: Option.Option<Reply.Reply<Rpcs>>\n    } | {\n      readonly _tag: \"IncomingEnvelope\"\n      readonly envelope: Envelope.AckChunk | Envelope.Interrupt\n    },\n    ParseResult.ParseError,\n    Rpc.Context<Rpcs>\n  > => {\n    if (message._tag === \"IncomingEnvelope\") {\n      return Effect.succeed(message)\n    }\n    const rpc = entityRpcs.get(message.envelope.tag) as any as Rpc.AnyWithProps\n    if (!rpc) {\n      return Effect.fail(\n        new ParseResult.ParseError({\n          issue: new ParseResult.Unexpected(\n            message,\n            `Unknown tag ${message.envelope.tag} for entity type ${entity.type}`\n          )\n        })\n      )\n    }\n    return decodeRequest(message, rpc) as Effect.Effect<\n      {\n        readonly _tag: \"IncomingRequest\"\n        readonly envelope: Envelope.Request.Any\n        readonly lastSentReply: Option.Option<Reply.Reply<Rpcs>>\n      },\n      ParseResult.ParseError,\n      Rpc.Context<Rpcs>\n    >\n  }\n}\n\nconst retryRespond = <A, E, R>(times: number, effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  times === 0 ?\n    effect :\n    Effect.catchAll(effect, () => Effect.delay(retryRespond(times - 1, effect), 200))\n"
  },
  {
    "path": "packages/cluster/src/internal/entityReaper.ts",
    "content": "import * as Effect from \"effect/Effect\"\nimport type { EntityNotAssignedToRunner } from \"../ClusterError.js\"\nimport type { EntityAddress } from \"../EntityAddress.js\"\nimport type { EntityId } from \"../EntityId.js\"\nimport type { EntityState } from \"./entityManager.js\"\nimport type { ResourceMap } from \"./resourceMap.js\"\n\n/** @internal */\nexport class EntityReaper extends Effect.Service<EntityReaper>()(\"@effect/cluster/EntityReaper\", {\n  scoped: Effect.gen(function*() {\n    let currentResolution = 30_000\n    const registered: Array<{\n      readonly maxIdleTime: number\n      readonly servers: Map<EntityId, EntityState>\n      readonly entities: ResourceMap<EntityAddress, EntityState, EntityNotAssignedToRunner>\n    }> = []\n    const latch = yield* Effect.makeLatch()\n\n    const register = (options: {\n      readonly maxIdleTime: number\n      readonly servers: Map<EntityId, EntityState>\n      readonly entities: ResourceMap<EntityAddress, EntityState, EntityNotAssignedToRunner>\n    }) =>\n      Effect.suspend(() => {\n        currentResolution = Math.max(Math.min(currentResolution, options.maxIdleTime), 5000)\n        registered.push(options)\n        return latch.open\n      })\n\n    const clock = yield* Effect.clock\n    yield* Effect.gen(function*() {\n      while (true) {\n        yield* Effect.sleep(currentResolution)\n        const now = clock.unsafeCurrentTimeMillis()\n        for (const { entities, maxIdleTime, servers } of registered) {\n          for (const state of servers.values()) {\n            const duration = now - state.lastActiveCheck\n            if (state.keepAliveEnabled || state.activeRequests.size > 0 || duration < maxIdleTime) {\n              continue\n            }\n            yield* Effect.fork(entities.removeIgnore(state.address))\n          }\n        }\n      }\n    }).pipe(\n      latch.whenOpen,\n      Effect.interruptible,\n      Effect.forkScoped\n    )\n\n    return { register } as const\n  })\n}) {}\n"
  },
  {
    "path": "packages/cluster/src/internal/fiber.ts",
    "content": "import * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Exit from \"effect/Exit\"\nimport type * as Fiber from \"effect/Fiber\"\n\n/** @internal */\nexport const joinAllDiscard = <A, E>(fibers: ReadonlyArray<Fiber.RuntimeFiber<A, E>>) =>\n  Effect.async<void, E>((resume) => {\n    let cause: Cause.Cause<E> | undefined = undefined\n    let i = 0\n    function loop() {\n      while (i < fibers.length) {\n        const fiber = fibers[i]\n        const exit = fiber.unsafePoll()\n        if (exit) {\n          i++\n          if (exit._tag === \"Success\") continue\n          cause = cause ? Cause.parallel(cause, exit.cause) : exit.cause\n          continue\n        }\n        fiber.addObserver(onExit)\n        return\n      }\n      resume(cause ? Effect.failCause(cause) : Effect.void)\n    }\n    function onExit(exit: Exit.Exit<A, E>) {\n      i++\n      if (exit._tag === \"Failure\") {\n        cause = cause ? Cause.parallel(cause, exit.cause) : exit.cause\n      }\n      loop()\n    }\n    loop()\n    return Effect.sync(() => fibers[i].removeObserver(onExit))\n  })\n"
  },
  {
    "path": "packages/cluster/src/internal/hash.ts",
    "content": "/** @internal */\nexport const hashOptimize = (n: number): number => (n & 0xbfffffff) | ((n >>> 1) & 0x40000000)\n\n/** @internal */\nexport const hashString = (str: string) => {\n  let h = 5381, i = str.length\n  while (i) {\n    h = (h * 33) ^ str.charCodeAt(--i)\n  }\n  return hashOptimize(h)\n}\n"
  },
  {
    "path": "packages/cluster/src/internal/interruptors.ts",
    "content": "import type { FiberId } from \"effect/FiberId\"\n\n/** @internal */\nexport const internalInterruptors = new WeakSet<FiberId>()\n"
  },
  {
    "path": "packages/cluster/src/internal/resourceMap.ts",
    "content": "import * as Context from \"effect/Context\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as MutableHashMap from \"effect/MutableHashMap\"\nimport * as MutableRef from \"effect/MutableRef\"\nimport * as Option from \"effect/Option\"\nimport * as Scope from \"effect/Scope\"\n\nexport class ResourceMap<K, A, E> {\n  constructor(\n    readonly lookup: (key: K, scope: Scope.Scope) => Effect.Effect<A, E>,\n    readonly entries: MutableHashMap.MutableHashMap<K, {\n      readonly scope: Scope.CloseableScope\n      readonly deferred: Deferred.Deferred<A, E>\n    }>,\n    readonly isClosed: MutableRef.MutableRef<boolean>\n  ) {}\n\n  static make = Effect.fnUntraced(function*<K, A, E, R>(lookup: (key: K) => Effect.Effect<A, E, R>) {\n    const scope = yield* Effect.scope\n    const context = yield* Effect.context<R>()\n    const isClosed = MutableRef.make(false)\n\n    const entries = MutableHashMap.empty<K, {\n      scope: Scope.CloseableScope\n      deferred: Deferred.Deferred<A, E>\n    }>()\n\n    yield* Scope.addFinalizerExit(\n      scope,\n      (exit) => {\n        MutableRef.set(isClosed, true)\n        return Effect.forEach(entries, ([key, { scope }]) => {\n          MutableHashMap.remove(entries, key)\n          return Effect.exit(Scope.close(scope, exit))\n        }, { concurrency: \"unbounded\", discard: true })\n      }\n    )\n\n    return new ResourceMap(\n      (key, scope) => Effect.provide(lookup(key), Context.add(context, Scope.Scope, scope)),\n      entries,\n      isClosed\n    )\n  })\n\n  get(key: K): Effect.Effect<A, E> {\n    return Effect.withFiberRuntime((fiber) => {\n      if (MutableRef.get(this.isClosed)) {\n        return Effect.interrupt\n      }\n      const existing = MutableHashMap.get(this.entries, key)\n      if (Option.isSome(existing)) {\n        return Deferred.await(existing.value.deferred)\n      }\n      const scope = Effect.runSync(Scope.make())\n      const deferred = Deferred.unsafeMake<A, E>(fiber.id())\n      MutableHashMap.set(this.entries, key, { scope, deferred })\n      return Effect.onExit(this.lookup(key, scope), (exit) => {\n        if (exit._tag === \"Success\") {\n          return Deferred.done(deferred, exit)\n        }\n        MutableHashMap.remove(this.entries, key)\n        return Deferred.done(deferred, exit)\n      })\n    })\n  }\n\n  remove(key: K): Effect.Effect<void> {\n    return Effect.suspend(() => {\n      const entry = MutableHashMap.get(this.entries, key)\n      if (Option.isNone(entry)) {\n        return Effect.void\n      }\n      MutableHashMap.remove(this.entries, key)\n      return Scope.close(entry.value.scope, Exit.void)\n    })\n  }\n\n  removeIgnore(key: K): Effect.Effect<void> {\n    return Effect.catchAllCause(this.remove(key), (cause) =>\n      Effect.annotateLogs(Effect.logDebug(cause), {\n        module: \"ResourceMap\",\n        method: \"removeIgnore\",\n        key\n      }))\n  }\n}\n"
  },
  {
    "path": "packages/cluster/src/internal/resourceRef.ts",
    "content": "import * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as MutableRef from \"effect/MutableRef\"\nimport * as Option from \"effect/Option\"\nimport * as Scope from \"effect/Scope\"\nimport { internalInterruptors } from \"./interruptors.js\"\n\nexport type State<A> = {\n  readonly _tag: \"Closed\"\n} | {\n  readonly _tag: \"Acquiring\"\n  readonly scope: Scope.CloseableScope\n} | {\n  readonly _tag: \"Acquired\"\n  readonly scope: Scope.CloseableScope\n  readonly value: A\n}\n\nexport class ResourceRef<A, E = never> {\n  static from = Effect.fnUntraced(function*<A, E>(\n    parentScope: Scope.Scope,\n    acquire: (scope: Scope.Scope) => Effect.Effect<A, E>\n  ) {\n    const state = MutableRef.make<State<A>>({ _tag: \"Closed\" })\n\n    yield* Scope.addFinalizerExit(parentScope, (exit) => {\n      const s = MutableRef.get(state)\n      if (s._tag === \"Closed\") {\n        return Effect.void\n      }\n      const scope = s.scope\n      MutableRef.set(state, { _tag: \"Closed\" })\n      return Scope.close(scope, exit)\n    })\n\n    const scope = yield* Scope.make()\n    MutableRef.set(state, { _tag: \"Acquiring\", scope })\n    const value = yield* acquire(scope)\n    MutableRef.set(state, { _tag: \"Acquired\", scope, value })\n\n    return new ResourceRef(state, acquire)\n  })\n\n  constructor(\n    readonly state: MutableRef.MutableRef<State<A>>,\n    readonly acquire: (scope: Scope.Scope) => Effect.Effect<A, E>\n  ) {}\n\n  latch = Effect.unsafeMakeLatch(true)\n\n  unsafeGet(): Option.Option<A> {\n    if (this.state.current._tag === \"Acquired\") {\n      return Option.some(this.state.current.value)\n    }\n    return Option.none()\n  }\n\n  unsafeRebuild(): Effect.Effect<void, E> {\n    const s = this.state.current\n    if (s._tag === \"Closed\") {\n      return Effect.interrupt\n    }\n    const prevScope = s.scope\n    const scope = Effect.runSync(Scope.make())\n    this.latch.unsafeClose()\n    MutableRef.set(this.state, { _tag: \"Acquiring\", scope })\n    return Effect.fiberIdWith((fiberId) => {\n      internalInterruptors.add(fiberId)\n      return Scope.close(prevScope, Exit.void)\n    }).pipe(\n      Effect.andThen(this.acquire(scope)),\n      Effect.flatMap((value) => {\n        if (this.state.current._tag === \"Closed\") {\n          return Effect.interrupt\n        }\n        MutableRef.set(this.state, { _tag: \"Acquired\", scope, value })\n        return this.latch.open\n      })\n    )\n  }\n\n  await: Effect.Effect<A> = Effect.suspend(() => {\n    const s = this.state.current\n    if (s._tag === \"Closed\") {\n      return Effect.interrupt\n    } else if (s._tag === \"Acquired\") {\n      return Effect.succeed(s.value)\n    }\n    return Effect.zipRight(this.latch.await, this.await)\n  })\n}\n"
  },
  {
    "path": "packages/cluster/test/ClusterWorkflowEngine.test.ts",
    "content": "import { ClusterWorkflowEngine, MessageStorage, Runners, Sharding, ShardingConfig } from \"@effect/cluster\"\nimport { assert, describe, expect, it } from \"@effect/vitest\"\nimport { Activity, DurableClock, DurableDeferred, Workflow } from \"@effect/workflow\"\nimport { WorkflowInstance } from \"@effect/workflow/WorkflowEngine\"\nimport { DateTime, Effect, Exit, Fiber, Layer, Schema, TestClock } from \"effect\"\nimport * as Cause from \"effect/Cause\"\nimport * as Duration from \"effect/Duration\"\nimport * as RunnerHealth from \"../src/RunnerHealth.js\"\nimport * as RunnerStorage from \"../src/RunnerStorage.js\"\n\ndescribe.concurrent(\"ClusterWorkflowEngine\", () => {\n  it.effect(\"should run a workflow\", () =>\n    Effect.gen(function*() {\n      const sharding = yield* Sharding.Sharding\n      const driver = yield* MessageStorage.MemoryDriver\n      const flags = yield* Flags\n\n      const fiber = yield* EmailWorkflow.execute({\n        id: \"test-email-1\",\n        to: \"bob@example.com\"\n      }).pipe(Effect.fork)\n\n      yield* TestClock.adjust(1)\n      // resume after the clock\n      yield* TestClock.adjust(\"10 seconds\")\n      yield* sharding.pollStorage\n      yield* TestClock.adjust(5000)\n\n      // --- the workflow is suspended at this point\n\n      // - 1 initial request\n      // - 5 attempts to send email\n      // - 1 sleep activity\n      // - 1 durable clock run\n      // - 1 durable clock deferred set\n      expect(driver.requests.size).toEqual(9)\n      const executionId = driver.journal[0].address.entityId\n\n      // normal finalizer should run even after suspension\n      expect(flags.get(\"finalizer\")).toBeTruthy()\n      // but not compensation\n      expect(flags.get(\"compensation\")).toBeFalsy()\n      // ensuring will run\n      expect(flags.get(\"ensuring\")).toBeTruthy()\n      expect(flags.get(\"catchAllCause\")).toBeFalsy()\n\n      // --- resume the workflow using DurableDeferred.done\n\n      const token = yield* DurableDeferred.token(EmailTrigger).pipe(\n        Effect.provideService(WorkflowInstance, WorkflowInstance.initial(EmailWorkflow, executionId))\n      )\n      yield* DurableDeferred.done(EmailTrigger, {\n        token,\n        exit: Exit.succeed(\"done\")\n      })\n      yield* sharding.pollStorage\n\n      // - 1 DurableDeferred set\n      expect(driver.requests.size).toEqual(10)\n\n      // allow suspend polling to complete\n      yield* TestClock.adjust(10000)\n      expect(yield* Fiber.join(fiber)).toBeUndefined()\n\n      // --- the workflow is complete\n\n      // ensuring will run\n      expect(flags.get(\"ensuring\")).toBeTruthy()\n      expect(flags.get(\"catchAllCause\")).toBeFalsy()\n\n      // test deduplication\n      yield* EmailWorkflow.execute({\n        id: \"test-email-1\",\n        to: \"bob@example.com\"\n      })\n      expect(driver.requests.size).toEqual(10)\n\n      // test poll\n      expect(yield* EmailWorkflow.poll(executionId)).toEqual(new Workflow.Complete({ exit: Exit.void }))\n    }).pipe(Effect.provide(TestWorkflowLayer)))\n\n  it.effect(\"interrupt\", () =>\n    Effect.gen(function*() {\n      const sharding = yield* Sharding.Sharding\n      const driver = yield* MessageStorage.MemoryDriver\n      yield* TestClock.adjust(1)\n\n      const fiber = yield* EmailWorkflow.execute({\n        id: \"test-email-2\",\n        to: \"bob@example.com\"\n      }).pipe(Effect.fork)\n\n      yield* TestClock.adjust(1)\n      yield* TestClock.adjust(\"10 seconds\")\n      yield* sharding.pollStorage\n      yield* TestClock.adjust(1)\n\n      const envelope = driver.journal[0]\n      const executionId = envelope.address.entityId\n      yield* EmailWorkflow.interrupt(executionId)\n\n      // - 1 initial request\n      // - 5 attempts to send email\n      // - 1 sleep activity\n      // - 1 durable clock run\n      // - 1 durable clock deferred set\n      // - 1 interrupt signal set\n      expect(driver.requests.size).toEqual(10)\n      yield* TestClock.adjust(5000)\n      yield* sharding.pollStorage\n      yield* TestClock.adjust(5000)\n      // - clock cleared\n      expect(driver.requests.size).toEqual(9)\n\n      const result = driver.requests.get(envelope.requestId)!\n      const reply = result.replies[0]!\n      assert(\n        reply._tag === \"WithExit\" &&\n          reply.exit._tag === \"Success\"\n      )\n      const value = reply.exit.value as Workflow.ResultEncoded<any, any>\n      assert(value._tag === \"Complete\" && value.exit._tag === \"Failure\")\n\n      const exit = yield* Fiber.await(fiber)\n      assert(Exit.isInterrupted(exit))\n\n      const flags = yield* Flags\n      assert.isTrue(flags.get(\"compensation\"))\n    }).pipe(\n      Effect.provide(TestWorkflowLayer)\n    ))\n\n  it.effect(\"Workflow.withCompensation\", () =>\n    Effect.gen(function*() {\n      yield* TestClock.adjust(1)\n\n      const fiber = yield* EmailWorkflow.execute({\n        id: \"test-email-3\",\n        to: \"compensation\"\n      }).pipe(Effect.fork)\n\n      yield* TestClock.adjust(1)\n\n      const flags = yield* Flags\n      assert.isTrue(flags.get(\"compensation\"))\n\n      const error = yield* Fiber.join(fiber).pipe(\n        Effect.flip\n      )\n      expect(error).toBeInstanceOf(SendEmailError)\n    }).pipe(\n      Effect.provide(TestWorkflowLayer)\n    ))\n\n  it.effect(\"Activity.raceAll\", () =>\n    Effect.gen(function*() {\n      const flags = yield* Flags\n      yield* TestClock.adjust(1)\n\n      const fiber = yield* RaceWorkflow.execute({\n        id: \"race-1\"\n      }).pipe(Effect.fork)\n\n      yield* TestClock.adjust(1)\n      yield* TestClock.adjust(1000)\n\n      const result = yield* Fiber.join(fiber)\n      expect(result).toEqual(\"Activity3\")\n\n      expect(flags.get(\"interrupt1\")).toBeTruthy()\n      expect(flags.get(\"interrupt2\")).toBeTruthy()\n      expect(flags.get(\"interrupt3\")).toBeFalsy()\n    }).pipe(Effect.provide(TestWorkflowLayer)))\n\n  it.effect(\"Activity.raceAll durable\", () =>\n    Effect.gen(function*() {\n      const sharding = yield* Sharding.Sharding\n      yield* TestClock.adjust(1)\n\n      const fiber = yield* DurableRaceWorkflow.execute({\n        id: \"race-2\"\n      }).pipe(Effect.fork)\n\n      yield* TestClock.adjust(1)\n      yield* TestClock.adjust(1000)\n      yield* sharding.pollStorage\n      yield* TestClock.adjust(5000)\n\n      const result = yield* Fiber.join(fiber)\n      expect(result).toEqual(\"Activity3\")\n    }).pipe(Effect.provide(TestWorkflowLayer)))\n\n  it.effect(\"nested workflows\", () =>\n    Effect.gen(function*() {\n      const flags = yield* Flags\n      const sharding = yield* Sharding.Sharding\n      yield* TestClock.adjust(1)\n\n      yield* ParentWorkflow.execute({\n        id: \"123\"\n      }).pipe(Effect.fork)\n      yield* TestClock.adjust(1)\n      yield* TestClock.adjust(5000)\n\n      assert.isUndefined(flags.get(\"parent-end\"))\n      assert.isUndefined(flags.get(\"child-end\"))\n      assert.isTrue(flags.get(\"parent-suspended\"))\n      const token = flags.get(\"child-token\")\n      assert(typeof token === \"string\")\n\n      yield* DurableDeferred.done(ChildDeferred, {\n        token: DurableDeferred.Token.make(token),\n        exit: Exit.void\n      })\n      yield* sharding.pollStorage\n      yield* TestClock.adjust(5000)\n      assert.isTrue(flags.get(\"parent-end\"))\n      assert.isTrue(flags.get(\"child-end\"))\n    }).pipe(Effect.provide(TestWorkflowLayer)))\n\n  it.effect(\"SuspendOnFailure\", () =>\n    Effect.gen(function*() {\n      const flags = yield* Flags\n      yield* TestClock.adjust(1)\n\n      yield* SuspendOnFailureWorkflow.execute({\n        id: \"\"\n      }).pipe(Effect.fork)\n      yield* TestClock.adjust(1)\n\n      assert.isTrue(flags.get(\"suspended\"))\n      assert.include(flags.get(\"cause\"), \"boom\")\n    }).pipe(Effect.provide(TestWorkflowLayer)))\n\n  it.effect(\"catchAllCause activity\", () =>\n    Effect.gen(function*() {\n      const flags = yield* Flags\n      yield* TestClock.adjust(1)\n\n      const fiber = yield* CatchWorkflow.execute({\n        id: \"\"\n      }).pipe(Effect.fork)\n      yield* TestClock.adjust(1)\n      yield* Fiber.join(fiber)\n\n      assert.isTrue(flags.get(\"catch\"))\n    }).pipe(Effect.provide(TestWorkflowLayer)))\n})\n\nconst TestShardingConfig = ShardingConfig.layer({\n  shardsPerGroup: 300,\n  entityMailboxCapacity: 10,\n  entityTerminationTimeout: 0,\n  entityMessagePollInterval: 5000,\n  sendRetryInterval: 100\n})\n\nconst TestWorkflowEngine = ClusterWorkflowEngine.layer.pipe(\n  Layer.provideMerge(Sharding.layer),\n  Layer.provide(Runners.layerNoop),\n  Layer.provideMerge(MessageStorage.layerMemory),\n  Layer.provide(RunnerStorage.layerMemory),\n  Layer.provide(RunnerHealth.layerNoop),\n  Layer.provide(TestShardingConfig)\n)\n\nclass SendEmailError extends Schema.TaggedError<SendEmailError>(\"SendEmailError\")(\"SendEmailError\", {\n  message: Schema.String\n}) {}\n\nconst EmailWorkflow = Workflow.make({\n  name: \"EmailWorkflow\",\n  payload: {\n    to: Schema.String,\n    id: Schema.String\n  },\n  error: SendEmailError,\n  idempotencyKey(payload) {\n    return payload.id\n  }\n})\n\nclass Flags extends Effect.Service<Flags>()(\"Flags\", {\n  sync: () => new Map<string, boolean | string>()\n}) {}\n\nconst EmailWorkflowLayer = EmailWorkflow.toLayer(Effect.fn(function*(payload) {\n  const flags = yield* Flags\n\n  yield* Effect.addFinalizer(() =>\n    Effect.sync(() => {\n      flags.set(\"finalizer\", true)\n    })\n  )\n\n  yield* Activity.make({\n    name: \"SendEmail\",\n    error: SendEmailError,\n    execute: Effect.gen(function*() {\n      const attempt = yield* Activity.CurrentAttempt\n\n      if (attempt !== 5) {\n        return yield* new SendEmailError({\n          message: `Failed to send email for ${payload.id} on attempt ${attempt}`\n        })\n      }\n    })\n  }).pipe(\n    EmailWorkflow.withCompensation(Effect.fnUntraced(function*() {\n      flags.set(\"compensation\", true)\n    })),\n    Activity.retry({ times: 5 })\n  )\n\n  if (payload.to === \"compensation\") {\n    return yield* new SendEmailError({ message: `Compensation triggered` })\n  }\n\n  const result = yield* Activity.make({\n    name: \"Sleep\",\n    success: Schema.DateTimeUtc,\n    execute: Effect.gen(function*() {\n      // suspended inside Activity\n      yield* DurableClock.sleep({\n        name: \"Some sleep\",\n        duration: \"10 seconds\",\n        inMemoryThreshold: Duration.zero\n      })\n      return yield* DateTime.now\n    })\n  })\n  // test serialization from Activity\n  assert(DateTime.isUtc(result))\n\n  yield* DurableDeferred.token(EmailTrigger)\n  // suspended outside Activity\n  yield* DurableDeferred.await(EmailTrigger).pipe(\n    Effect.catchAllCause(() => {\n      flags.set(\"catchAllCause\", true)\n      return Effect.void\n    }),\n    Effect.ensuring(Effect.sync(() => {\n      flags.set(\"ensuring\", true)\n    }))\n  )\n})).pipe(\n  Layer.provideMerge(Flags.Default)\n)\n\nconst EmailTrigger = DurableDeferred.make(\"EmailTrigger\", {\n  success: Schema.String\n})\n\nconst RaceWorkflow = Workflow.make({\n  name: \"RaceWorkflow\",\n  payload: {\n    id: Schema.String\n  },\n  success: Schema.String,\n  idempotencyKey: ({ id }) => id\n})\n\nconst RaceWorkflowLayer = RaceWorkflow.toLayer(Effect.fnUntraced(function*() {\n  const flags = yield* Flags\n\n  yield* Effect.addFinalizer(() =>\n    Effect.sync(() => {\n      flags.set(\"finalizer\", true)\n    })\n  )\n\n  return yield* Activity.raceAll(\"race\", [\n    Activity.make({\n      name: \"Activity1\",\n      success: Schema.String,\n      error: Schema.Never,\n      execute: Effect.onInterrupt(Effect.delay(Effect.succeed(\"Activity1\"), 1000), () =>\n        Effect.sync(() => {\n          flags.set(\"interrupt1\", true)\n        }))\n    }),\n    Activity.make({\n      name: \"Activity2\",\n      success: Schema.String,\n      error: Schema.Never,\n      execute: Effect.onInterrupt(Effect.delay(Effect.succeed(\"Activity2\"), 500), () =>\n        Effect.sync(() => {\n          flags.set(\"interrupt2\", true)\n        }))\n    }),\n    Activity.make({\n      name: \"Activity3\",\n      success: Schema.String,\n      error: Schema.Never,\n      execute: Effect.onInterrupt(Effect.delay(Effect.succeed(\"Activity3\"), 100), () =>\n        Effect.sync(() => {\n          flags.set(\"interrupt3\", true)\n        }))\n    })\n  ])\n}))\n\nconst DurableRaceWorkflow = Workflow.make({\n  name: \"DurableRaceWorkflow\",\n  payload: {\n    id: Schema.String\n  },\n  success: Schema.String,\n  idempotencyKey: ({ id }) => id\n})\n\nconst DurableRaceWorkflowLayer = DurableRaceWorkflow.toLayer(Effect.fnUntraced(function*() {\n  const flags = yield* Flags\n\n  yield* Effect.addFinalizer(() =>\n    Effect.sync(() => {\n      flags.set(\"finalizer\", true)\n    })\n  )\n\n  return yield* Activity.raceAll(\"race\", [\n    Activity.make({\n      name: \"Activity1\",\n      success: Schema.String,\n      error: Schema.Never,\n      execute: DurableClock.sleep({\n        name: \"Activity1\",\n        duration: 50000,\n        inMemoryThreshold: Duration.zero\n      }).pipe(\n        Effect.as(\"Activity1\")\n      )\n    }),\n    Activity.make({\n      name: \"Activity2\",\n      success: Schema.String,\n      error: Schema.Never,\n      execute: DurableClock.sleep({\n        name: \"Activity2\",\n        duration: 10000,\n        inMemoryThreshold: Duration.zero\n      }).pipe(\n        Effect.as(\"Activity2\")\n      )\n    }),\n    Activity.make({\n      name: \"Activity3\",\n      success: Schema.String,\n      error: Schema.Never,\n      execute: DurableClock.sleep({\n        name: \"Activity3\",\n        duration: 1000,\n        inMemoryThreshold: Duration.zero\n      }).pipe(\n        Effect.as(\"Activity3\")\n      )\n    })\n  ])\n}))\n\nconst ParentWorkflow = Workflow.make({\n  name: \"ParentWorkflow\",\n  payload: {\n    id: Schema.String\n  },\n  idempotencyKey(payload) {\n    return payload.id\n  }\n})\n\nconst ChildWorkflow = Workflow.make({\n  name: \"ChildWorkflow\",\n  payload: {\n    id: Schema.String\n  },\n  idempotencyKey(payload) {\n    return payload.id\n  }\n})\n\nconst ParentWorkflowLayer = ParentWorkflow.toLayer(Effect.fnUntraced(function*({ id }) {\n  const flags = yield* Flags\n  const instance = yield* WorkflowInstance\n  yield* Effect.addFinalizer(() =>\n    Effect.sync(() => {\n      flags.set(\"parent-suspended\", instance.suspended)\n    })\n  )\n  yield* ChildWorkflow.execute({ id })\n  flags.set(\"parent-end\", true)\n}))\n\nconst ChildDeferred = DurableDeferred.make(\"ChildDeferred\")\nconst ChildWorkflowLayer = ChildWorkflow.toLayer(Effect.fnUntraced(function*() {\n  const flags = yield* Flags\n  flags.set(\"child-token\", yield* DurableDeferred.token(ChildDeferred))\n  yield* DurableDeferred.await(ChildDeferred)\n  flags.set(\"child-end\", true)\n}))\n\nconst SuspendOnFailureWorkflow = Workflow.make({\n  name: \"SuspendOnFailureWorkflow\",\n  payload: {\n    id: Schema.String\n  },\n  idempotencyKey(payload) {\n    return payload.id\n  }\n}).annotate(Workflow.SuspendOnFailure, true)\n\nconst SuspendOnFailureWorkflowLayer = SuspendOnFailureWorkflow.toLayer(Effect.fnUntraced(function*() {\n  const flags = yield* Flags\n  const instance = yield* WorkflowInstance\n  yield* Effect.addFinalizer(() =>\n    Effect.sync(() => {\n      flags.set(\"suspended\", instance.suspended)\n      flags.set(\"cause\", Cause.pretty(instance.cause!))\n    })\n  )\n  yield* Activity.make({\n    name: \"fail\",\n    execute: Effect.die(\"boom\")\n  })\n}))\n\nconst CatchWorkflow = Workflow.make({\n  name: \"CatchWorkflow\",\n  payload: {\n    id: Schema.String\n  },\n  idempotencyKey(payload) {\n    return payload.id\n  }\n})\n\nconst CatchWorkflowLayer = CatchWorkflow.toLayer(Effect.fnUntraced(function*() {\n  const flags = yield* Flags\n  yield* Activity.make({\n    name: \"fail\",\n    execute: Effect.die(\"boom\")\n  }).pipe(\n    Effect.catchAllCause((cause) =>\n      Activity.make({\n        name: \"log\",\n        execute: Effect.suspend(() => {\n          flags.set(\"catch\", true)\n          return Effect.log(cause)\n        })\n      })\n    )\n  )\n}))\n\nconst TestWorkflowLayer = EmailWorkflowLayer.pipe(\n  Layer.merge(RaceWorkflowLayer),\n  Layer.merge(DurableRaceWorkflowLayer),\n  Layer.merge(ParentWorkflowLayer),\n  Layer.merge(ChildWorkflowLayer),\n  Layer.merge(SuspendOnFailureWorkflowLayer),\n  Layer.merge(CatchWorkflowLayer),\n  Layer.provideMerge(Flags.Default),\n  Layer.provideMerge(TestWorkflowEngine)\n)\n"
  },
  {
    "path": "packages/cluster/test/Entity.test.ts",
    "content": "import { Entity, ShardingConfig } from \"@effect/cluster\"\nimport { assert, describe, it } from \"@effect/vitest\"\nimport { Effect } from \"effect\"\nimport { TestEntity, TestEntityLayer, User } from \"./TestEntity.js\"\n\ndescribe.concurrent(\"Entity\", () => {\n  describe(\"makeTestClient\", () => {\n    it.scoped(\"round trip\", () =>\n      Effect.gen(function*() {\n        const makeClient = yield* Entity.makeTestClient(TestEntity, TestEntityLayer)\n        const client = yield* makeClient(\"123\")\n        const user = yield* client.GetUser({ id: 1 })\n        assert.deepEqual(user, new User({ id: 1, name: \"User 1\" }))\n      }).pipe(Effect.provide(TestShardingConfig)))\n  })\n})\n\nconst TestShardingConfig = ShardingConfig.layer({\n  shardsPerGroup: 300,\n  entityMailboxCapacity: 10,\n  entityTerminationTimeout: 0,\n  entityMessagePollInterval: 5000,\n  sendRetryInterval: 100\n})\n"
  },
  {
    "path": "packages/cluster/test/HttpRunner.test.ts",
    "content": "import * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientError from \"@effect/platform/HttpClientError\"\nimport * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\nimport { RpcSerialization } from \"@effect/rpc\"\nimport { describe, expect, it } from \"@effect/vitest\"\nimport { Effect, Layer, Ref } from \"effect\"\nimport * as HttpRunner from \"../src/HttpRunner.js\"\nimport { MessageStorage, RunnerAddress, RunnerHealth, Runners, RunnerStorage, ShardingConfig } from \"../src/index.js\"\n\ndescribe(\"HttpRunner\", () => {\n  describe(\"layerClientProtocolHttp\", () => {\n    const makeUrlCapturingClient = (urlRef: Ref.Ref<Array<string>>) =>\n      HttpClient.make((request, url) =>\n        Ref.update(urlRef, (urls) => [...urls, url.toString()]).pipe(\n          Effect.flatMap(() =>\n            Effect.fail(\n              new HttpClientError.RequestError({\n                request,\n                reason: \"Transport\",\n                cause: new Error(\"Mock - URL captured\")\n              })\n            )\n          )\n        )\n      )\n\n    const testRequest = {\n      _tag: \"Request\" as const,\n      id: \"1\",\n      tag: \"test\",\n      payload: {},\n      headers: [] as ReadonlyArray<[string, string]>\n    }\n\n    it.scoped(\"path '/' produces http://host:port/\", () =>\n      Effect.gen(function*() {\n        const urlRef = yield* Ref.make<Array<string>>([])\n\n        const layer = HttpRunner.layerClientProtocolHttp({ path: \"/\" }).pipe(\n          Layer.provide(Layer.succeed(HttpClient.HttpClient, makeUrlCapturingClient(urlRef))),\n          Layer.provide(RpcSerialization.layerNdjson)\n        )\n\n        const makeProtocol = yield* Effect.provide(Runners.RpcClientProtocol, layer)\n        const protocol = yield* makeProtocol(RunnerAddress.make(\"localhost\", 3000))\n\n        yield* protocol.send(testRequest).pipe(Effect.ignore)\n\n        const urls = yield* Ref.get(urlRef)\n        expect(urls[0]).toBe(\"http://localhost:3000/\")\n      }))\n\n    it.scoped(\"path '' produces http://host:port/\", () =>\n      Effect.gen(function*() {\n        const urlRef = yield* Ref.make<Array<string>>([])\n\n        const layer = HttpRunner.layerClientProtocolHttp({ path: \"\" }).pipe(\n          Layer.provide(Layer.succeed(HttpClient.HttpClient, makeUrlCapturingClient(urlRef))),\n          Layer.provide(RpcSerialization.layerNdjson)\n        )\n\n        const makeProtocol = yield* Effect.provide(Runners.RpcClientProtocol, layer)\n        const protocol = yield* makeProtocol(RunnerAddress.make(\"localhost\", 3000))\n\n        yield* protocol.send(testRequest).pipe(Effect.ignore)\n\n        const urls = yield* Ref.get(urlRef)\n        expect(urls[0]).toBe(\"http://localhost:3000/\")\n      }))\n\n    it.scoped(\"path '/rpc' produces http://host:port/rpc\", () =>\n      Effect.gen(function*() {\n        const urlRef = yield* Ref.make<Array<string>>([])\n\n        const layer = HttpRunner.layerClientProtocolHttp({ path: \"/rpc\" }).pipe(\n          Layer.provide(Layer.succeed(HttpClient.HttpClient, makeUrlCapturingClient(urlRef))),\n          Layer.provide(RpcSerialization.layerNdjson)\n        )\n\n        const makeProtocol = yield* Effect.provide(Runners.RpcClientProtocol, layer)\n        const protocol = yield* makeProtocol(RunnerAddress.make(\"localhost\", 3000))\n\n        yield* protocol.send(testRequest).pipe(Effect.ignore)\n\n        const urls = yield* Ref.get(urlRef)\n        expect(urls[0]).toBe(\"http://localhost:3000/rpc\")\n      }))\n\n    it.scoped(\"path 'rpc' produces http://host:port/rpc\", () =>\n      Effect.gen(function*() {\n        const urlRef = yield* Ref.make<Array<string>>([])\n\n        const layer = HttpRunner.layerClientProtocolHttp({ path: \"rpc\" }).pipe(\n          Layer.provide(Layer.succeed(HttpClient.HttpClient, makeUrlCapturingClient(urlRef))),\n          Layer.provide(RpcSerialization.layerNdjson)\n        )\n\n        const makeProtocol = yield* Effect.provide(Runners.RpcClientProtocol, layer)\n        const protocol = yield* makeProtocol(RunnerAddress.make(\"localhost\", 3000))\n\n        yield* protocol.send(testRequest).pipe(Effect.ignore)\n\n        const urls = yield* Ref.get(urlRef)\n        expect(urls[0]).toBe(\"http://localhost:3000/rpc\")\n      }))\n  })\n\n  describe(\"layerHttpOptions\", () => {\n    const deps = Layer.mergeAll(\n      RunnerStorage.layerMemory,\n      RunnerHealth.layerNoop,\n      MessageStorage.layerNoop,\n      ShardingConfig.layerDefaults,\n      RpcSerialization.layerNdjson,\n      Layer.succeed(Runners.RpcClientProtocol, () => Effect.die(\"mock\"))\n    )\n\n    it.scoped(\"registers route on HttpLayerRouter so POST / is not 404\", () =>\n      Effect.gen(function*() {\n        const { dispose, handler } = HttpLayerRouter.toWebHandler(\n          HttpRunner.layerHttpOptions({ path: \"/\" }).pipe(Layer.provide(deps))\n        )\n        yield* Effect.addFinalizer(() => Effect.promise(() => dispose()))\n\n        const response = yield* Effect.promise(() =>\n          handler(\n            new Request(\"http://localhost/\", {\n              method: \"POST\",\n              headers: { \"content-type\": \"application/octet-stream\" },\n              body: new Uint8Array([])\n            })\n          )\n        )\n        expect(response.status).not.toBe(404)\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/cluster/test/MessageStorage.test.ts",
    "content": "import {\n  EntityAddress,\n  EntityId,\n  EntityType,\n  Envelope,\n  Message,\n  MessageStorage,\n  Reply,\n  ShardId,\n  ShardingConfig,\n  Snowflake\n} from \"@effect/cluster\"\nimport { Headers } from \"@effect/platform\"\nimport { Rpc, RpcSchema } from \"@effect/rpc\"\nimport { describe, expect, it } from \"@effect/vitest\"\nimport { Context, Effect, Exit, Layer, Option, PrimaryKey, Schema } from \"effect\"\nimport * as TestClock from \"effect/TestClock\"\n\nconst MemoryLive = MessageStorage.layerMemory.pipe(\n  Layer.provideMerge(Snowflake.layerGenerator),\n  Layer.provide(ShardingConfig.layerDefaults)\n)\n\ndescribe(\"MessageStorage\", () => {\n  describe(\"memory\", () => {\n    it.effect(\"saves a request\", () =>\n      Effect.gen(function*() {\n        const storage = yield* MessageStorage.MessageStorage\n        const request = yield* makeRequest()\n        const result = yield* storage.saveRequest(request)\n        expect(result._tag).toEqual(\"Success\")\n        const messages = yield* storage.unprocessedMessages([request.envelope.address.shardId])\n        expect(messages).toHaveLength(1)\n      }).pipe(Effect.provide(MemoryLive)))\n\n    it.effect(\"detects duplicates\", () =>\n      Effect.gen(function*() {\n        const storage = yield* MessageStorage.MessageStorage\n        yield* storage.saveRequest(\n          yield* makeRequest({\n            rpc: Rpc.fromTaggedRequest(PrimaryKeyTest),\n            payload: new PrimaryKeyTest({ id: 123 })\n          })\n        )\n        const result = yield* storage.saveRequest(\n          yield* makeRequest({\n            rpc: Rpc.fromTaggedRequest(PrimaryKeyTest),\n            payload: new PrimaryKeyTest({ id: 123 })\n          })\n        )\n        expect(result._tag).toEqual(\"Duplicate\")\n      }).pipe(Effect.provide(MemoryLive)))\n\n    it.effect(\"unprocessedMessages excludes complete requests\", () =>\n      Effect.gen(function*() {\n        const storage = yield* MessageStorage.MessageStorage\n        const request = yield* makeRequest()\n        yield* storage.saveRequest(request)\n        yield* storage.saveReply(yield* makeReply(request))\n        const messages = yield* storage.unprocessedMessages([request.envelope.address.shardId])\n        expect(messages).toHaveLength(0)\n      }).pipe(Effect.provide(MemoryLive)))\n\n    it.effect(\"repliesFor\", () =>\n      Effect.gen(function*() {\n        const storage = yield* MessageStorage.MessageStorage\n        const request = yield* makeRequest()\n        yield* storage.saveRequest(request)\n        let replies = yield* storage.repliesFor([request])\n        expect(replies).toHaveLength(0)\n        yield* storage.saveReply(yield* makeReply(request))\n        replies = yield* storage.repliesFor([request])\n        expect(replies).toHaveLength(1)\n        expect(replies[0].requestId).toEqual(request.envelope.requestId)\n      }).pipe(Effect.provide(MemoryLive)))\n\n    it.effect(\"registerReplyHandler\", () =>\n      Effect.gen(function*() {\n        const storage = yield* MessageStorage.MessageStorage\n        const latch = yield* Effect.makeLatch()\n        const request = yield* makeRequest()\n        yield* storage.saveRequest(request)\n        const fiber = yield* storage.registerReplyHandler(\n          new Message.OutgoingRequest({\n            ...request,\n            respond: () => latch.open\n          })\n        ).pipe(Effect.fork)\n        yield* TestClock.adjust(1)\n        yield* storage.saveReply(yield* makeReply(request))\n        yield* latch.await\n        yield* fiber.await\n      }).pipe(Effect.provide(MemoryLive)))\n\n    it.effect(\"unregisterReplyHandler\", () =>\n      Effect.gen(function*() {\n        const storage = yield* MessageStorage.MessageStorage\n        const request = yield* makeRequest()\n        yield* storage.saveRequest(request)\n        const fiber = yield* storage.registerReplyHandler(\n          new Message.OutgoingRequest({\n            ...request,\n            respond: () => Effect.void\n          })\n        ).pipe(Effect.fork)\n        yield* TestClock.adjust(1)\n        yield* storage.unregisterReplyHandler(request.envelope.requestId)\n        yield* fiber.await\n      }).pipe(Effect.provide(MemoryLive)))\n  })\n\n  describe(\"makeEncoded\", () => {\n    it.effect(\"guards empty id lists before delegating\", () =>\n      Effect.gen(function*() {\n        const encoded = {\n          saveEnvelope: () => Effect.succeed(MessageStorage.SaveResultEncoded.Success()),\n          saveReply: () => Effect.void,\n          clearReplies: () => Effect.void,\n          requestIdForPrimaryKey: () => Effect.succeed(Option.none()),\n          repliesFor: () => Effect.succeed([]),\n          repliesForUnfiltered: () => Effect.die(\"unexpected repliesForUnfiltered call\"),\n          unprocessedMessages: () => Effect.succeed([]),\n          unprocessedMessagesById: () => Effect.succeed([]),\n          resetAddress: () => Effect.void,\n          clearAddress: () => Effect.void,\n          resetShards: () => Effect.die(\"unexpected resetShards call\")\n        }\n\n        const storage = yield* MessageStorage.makeEncoded(encoded).pipe(\n          Effect.provide(Snowflake.layerGenerator)\n        )\n\n        const replies = yield* storage.repliesForUnfiltered([])\n        expect(replies).toEqual([])\n\n        yield* storage.resetShards([])\n      }))\n  })\n})\n\nexport const GetUserRpc = Rpc.make(\"GetUser\", {\n  payload: { id: Schema.Number }\n})\n\nexport const makeRequest = Effect.fnUntraced(function*(options?: {\n  readonly rpc?: Rpc.AnyWithProps\n  readonly payload?: any\n}) {\n  const snowflake = yield* Snowflake.Generator\n  const rpc = options?.rpc ?? GetUserRpc\n  return new Message.OutgoingRequest({\n    envelope: Envelope.makeRequest<any>({\n      requestId: snowflake.unsafeNext(),\n      address: EntityAddress.EntityAddress.make({\n        shardId: ShardId.make(\"default\", 1),\n        entityType: EntityType.EntityType.make(\"test\"),\n        entityId: EntityId.EntityId.make(\"1\")\n      }),\n      tag: rpc._tag,\n      payload: options?.payload ?? { id: 123 },\n      traceId: \"noop\",\n      spanId: \"noop\",\n      sampled: false,\n      headers: Headers.empty\n    }),\n    context: Context.empty() as any,\n    rpc,\n    lastReceivedReply: Option.none(),\n    respond() {\n      return Effect.void\n    }\n  })\n})\n\nexport class PrimaryKeyTest extends Schema.TaggedRequest<PrimaryKeyTest>()(\"PrimaryKeyTest\", {\n  success: Schema.Void,\n  failure: Schema.Never,\n  payload: {\n    id: Schema.Number\n  }\n}) {\n  [PrimaryKey.symbol]() {\n    return this.id.toString()\n  }\n}\n\nexport class StreamTest extends Schema.TaggedRequest<StreamTest>()(\"StreamTest\", {\n  success: RpcSchema.Stream({\n    success: Schema.Void,\n    failure: Schema.Never\n  }),\n  failure: Schema.Never,\n  payload: {\n    id: Schema.Number\n  }\n}) {\n  [PrimaryKey.symbol]() {\n    return this.id.toString()\n  }\n}\nexport const StreamRpc = Rpc.fromTaggedRequest(StreamTest)\n\nexport const makeReply = Effect.fnUntraced(function*(request: Message.OutgoingRequest<any>) {\n  const snowflake = yield* Snowflake.Generator\n  return new Reply.ReplyWithContext({\n    reply: new Reply.WithExit({\n      id: snowflake.unsafeNext(),\n      requestId: request.envelope.requestId,\n      exit: Exit.void as any\n    }),\n    context: request.context,\n    rpc: request.rpc\n  })\n})\n\nexport const makeAckChunk = Effect.fnUntraced(function*(\n  request: Message.OutgoingRequest<any>,\n  chunk: Reply.ReplyWithContext<any>\n) {\n  const snowflake = yield* Snowflake.Generator\n  return new Message.OutgoingEnvelope({\n    envelope: new Envelope.AckChunk({\n      id: snowflake.unsafeNext(),\n      address: request.envelope.address,\n      requestId: chunk.reply.requestId,\n      replyId: chunk.reply.id\n    }),\n    rpc: request.rpc\n  })\n})\n\nexport const makeChunkReply = Effect.fnUntraced(function*(request: Message.OutgoingRequest<any>, sequence = 0) {\n  const snowflake = yield* Snowflake.Generator\n  return new Reply.ReplyWithContext({\n    reply: new Reply.Chunk({\n      id: snowflake.unsafeNext(),\n      requestId: request.envelope.requestId,\n      sequence,\n      values: [undefined]\n    }),\n    context: request.context,\n    rpc: request.rpc\n  })\n})\n\nexport const makeEmptyReply = (request: Message.OutgoingRequest<any>) => {\n  return new Reply.ReplyWithContext({\n    reply: Reply.Chunk.emptyFrom(request.envelope.requestId),\n    context: request.context,\n    rpc: request.rpc\n  })\n}\n"
  },
  {
    "path": "packages/cluster/test/Sharding.test.ts",
    "content": "import {\n  MessageStorage,\n  RunnerAddress,\n  Runners,\n  RunnerStorage,\n  Sharding,\n  ShardingConfig,\n  Snowflake\n} from \"@effect/cluster\"\nimport { assert, describe, expect, it } from \"@effect/vitest\"\nimport {\n  Array,\n  Cause,\n  Chunk,\n  Effect,\n  Exit,\n  Fiber,\n  FiberId,\n  Layer,\n  Mailbox,\n  MutableRef,\n  Option,\n  Stream,\n  TestClock\n} from \"effect\"\nimport * as RunnerHealth from \"../src/RunnerHealth.js\"\nimport { TestEntity, TestEntityNoState, TestEntityState, User } from \"./TestEntity.js\"\n\ndescribe.concurrent(\"Sharding\", () => {\n  it.scoped(\"delivers a message\", () =>\n    Effect.gen(function*() {\n      yield* TestClock.adjust(1)\n      const makeClient = yield* TestEntity.client\n      const client = makeClient(\"1\")\n      const user = yield* client.GetUserVolatile({ id: 1 })\n      expect(user).toEqual(new User({ id: 1, name: \"User 1\" }))\n    }).pipe(Effect.provide(TestSharding)))\n\n  it.scoped(\"delivers a message via storage\", () =>\n    Effect.gen(function*() {\n      yield* TestClock.adjust(1)\n      const driver = yield* MessageStorage.MemoryDriver\n      const makeClient = yield* TestEntity.client\n      const client = makeClient(\"1\")\n      const user = yield* client.GetUser({ id: 1 })\n      expect(user).toEqual(new User({ id: 1, name: \"User 1\" }))\n      expect(driver.journal.length).toEqual(1)\n      expect(driver.unprocessed.size).toEqual(0)\n    }).pipe(Effect.provide(TestSharding)))\n\n  it.scoped(\"interrupts\", () =>\n    Effect.gen(function*() {\n      const driver = yield* MessageStorage.MemoryDriver\n      const state = yield* TestEntityState\n      const makeClient = yield* TestEntity.client\n      yield* TestClock.adjust(1)\n      const client = makeClient(\"1\")\n\n      const fiber = yield* client.Never().pipe(Effect.fork)\n      yield* TestClock.adjust(1)\n      yield* Fiber.interrupt(fiber)\n\n      yield* TestClock.adjust(1)\n      expect(driver.journal.length).toEqual(2)\n      expect(driver.replyIds.size).toEqual(1)\n      expect(state.interrupts.unsafeSize()).toEqual(Option.some(1))\n    }).pipe(Effect.provide(TestSharding)))\n\n  it.scoped(\"interrupts aren't sent for durable messages on shutdown\", () =>\n    Effect.gen(function*() {\n      let driver!: MessageStorage.MemoryDriver\n      yield* Effect.gen(function*() {\n        driver = yield* MessageStorage.MemoryDriver\n        const makeClient = yield* TestEntity.client\n        yield* TestClock.adjust(1)\n        const client = makeClient(\"1\")\n        yield* client.Never().pipe(Effect.fork)\n        yield* TestClock.adjust(1)\n      }).pipe(Effect.provide(TestSharding))\n\n      // request, client interrupt is dropped\n      expect(driver.journal.length).toEqual(1)\n      // server interrupt is not sent\n      expect(driver.replyIds.size).toEqual(0)\n    }))\n\n  it.scoped(\"interrupts are sent for volatile messages on shutdown\", () =>\n    Effect.gen(function*() {\n      let interrupted = false\n      const testClock = (yield* Effect.clock) as TestClock.TestClock\n\n      yield* Effect.gen(function*() {\n        const makeClient = yield* TestEntity.client\n        const client = makeClient(\"1\")\n        const fiber = yield* client.NeverVolatile().pipe(Effect.fork)\n        yield* TestClock.adjust(1)\n        const config = yield* ShardingConfig.ShardingConfig\n        ;(config as any).runnerAddress = Option.some(RunnerAddress.make(\"localhost\", 1234))\n        fiber.currentScheduler.scheduleTask(\n          () => {\n            fiber.unsafeInterruptAsFork(FiberId.none)\n            Effect.runFork(testClock.adjust(30000))\n          },\n          0,\n          fiber\n        )\n      }).pipe(\n        Effect.provide(TestShardingWithoutRunners.pipe(\n          Layer.provide(Layer.scoped(\n            Runners.Runners,\n            Effect.gen(function*() {\n              const runners = yield* Runners.makeNoop\n              return {\n                ...runners,\n                send(options) {\n                  if (options.message.envelope._tag === \"Interrupt\") {\n                    interrupted = true\n                    return Effect.void\n                  }\n                  return runners.send(options)\n                }\n              }\n            })\n          )),\n          Layer.provide([MessageStorage.layerMemory, Snowflake.layerGenerator]),\n          Layer.provideMerge(ShardingConfig.layer({\n            entityMailboxCapacity: 10,\n            entityTerminationTimeout: 30000,\n            entityMessagePollInterval: 5000,\n            sendRetryInterval: 100\n          }))\n        ))\n      )\n\n      assert.isTrue(interrupted)\n    }))\n\n  it.scoped(\"malformed message in storage\", () =>\n    Effect.gen(function*() {\n      const driver = yield* MessageStorage.MemoryDriver\n      const makeClient = yield* TestEntity.client\n      yield* TestClock.adjust(1)\n      const client = makeClient(\"1\")\n\n      const fiber = yield* client.Never().pipe(Effect.fork)\n      yield* TestClock.adjust(1)\n\n      const request = driver.journal[0]\n      yield* driver.encoded.saveEnvelope({\n        envelope: {\n          id: \"boom\",\n          _tag: \"Interrupt\",\n          requestId: request.requestId,\n          address: {\n            shardId: request.address.shardId\n          } as any\n        },\n        primaryKey: null,\n        deliverAt: null\n      })\n\n      // wait for storage to poll\n      yield* TestClock.adjust(5000)\n\n      const exit = fiber.unsafePoll()\n      assert(exit && Exit.isFailure(exit) && Cause.isDie(exit.cause))\n\n      // malformed message should be left in the database\n      expect(driver.journal.length).toEqual(2)\n      // defect reply should be sent\n      expect(driver.replyIds.size).toEqual(1)\n\n      const reply = driver.requests.get(request.requestId)!.replies[0]\n      assert(reply._tag === \"WithExit\" && reply.exit._tag === \"Failure\" && reply.exit.cause._tag === \"Die\")\n    }).pipe(Effect.provide(TestSharding)))\n\n  it.scoped(\"MailboxFull for volatile messages\", () =>\n    Effect.gen(function*() {\n      const makeClient = yield* TestEntity.client\n      yield* TestClock.adjust(1)\n      const client = makeClient(\"1\")\n\n      yield* client.NeverVolatile().pipe(Effect.fork, Effect.replicateEffect(10))\n      yield* TestClock.adjust(1)\n      const error = yield* client.NeverVolatile().pipe(Effect.flip)\n      assert.strictEqual(error._tag, \"MailboxFull\")\n    }).pipe(Effect.provide(TestSharding)))\n\n  it.scoped(\"durable messages are retried when mailbox is full\", () =>\n    Effect.gen(function*() {\n      const requestedIds = yield* Mailbox.make<Array<Snowflake.Snowflake>>()\n      yield* Effect.gen(function*() {\n        const state = yield* TestEntityState\n        const makeClient = yield* TestEntity.client\n        yield* TestClock.adjust(1)\n        const client = makeClient(\"1\")\n\n        const fibers = yield* client.NeverFork().pipe(Effect.fork, Effect.replicateEffect(11))\n        yield* TestClock.adjust(1)\n\n        // wait for entity to go into resume mode and request ids\n        const ids = yield* requestedIds.take\n        assert.strictEqual(ids.length, 1)\n\n        // test entity should still only have 10 requests\n        assert.deepStrictEqual(state.envelopes.unsafeSize(), Option.some(10))\n\n        // interrupt first request\n        yield* Fiber.interrupt(fibers[0])\n        yield* TestClock.adjust(100) // let retry happen\n\n        // last request should come through\n        assert.deepStrictEqual(state.envelopes.unsafeSize(), Option.some(11))\n\n        // interrupt second request, now the entity should be back in the main storage loop\n        yield* Fiber.interrupt(fibers[1])\n\n        // send another request within mailbox capacity\n        yield* client.NeverFork().pipe(Effect.fork)\n        yield* TestClock.adjust(1)\n        yield* Fiber.interruptAll(fibers)\n        yield* TestClock.adjust(100)\n\n        // no more ids should have been requested from entity catch up\n        assert.deepStrictEqual(requestedIds.unsafeSize(), Option.some(0))\n      }).pipe(Effect.provide(TestShardingWithoutStorage.pipe(\n        Layer.updateService(MessageStorage.MessageStorage, (storage) => ({\n          ...storage,\n          unprocessedMessagesById(messageIds) {\n            requestedIds.unsafeOffer(Array.fromIterable(messageIds))\n            return storage.unprocessedMessagesById(messageIds)\n          }\n        })),\n        Layer.provide(MessageStorage.layerMemory),\n        Layer.provide(TestShardingConfig)\n      )))\n    }))\n\n  it.scoped(\"interrupt for future request works while mailbox is full\", () =>\n    Effect.gen(function*() {\n      const state = yield* TestEntityState\n      const makeClient = yield* TestEntity.client\n      yield* TestClock.adjust(1)\n      const client = makeClient(\"1\")\n\n      const fibers = yield* client.NeverFork().pipe(\n        Effect.fork,\n        Effect.replicateEffect(12)\n      )\n      yield* TestClock.adjust(1)\n\n      // interrupt 11th request\n      yield* Fiber.interrupt(fibers[10])\n      yield* TestClock.adjust(100) // let retry happen\n      // interrupt first request, and let the 11th request come through\n      yield* Fiber.interrupt(fibers[0])\n      yield* TestClock.adjust(100) // let retry happen\n\n      assert.deepStrictEqual(state.envelopes.unsafeSize(), Option.some(11))\n      // second interrupt should be sent\n      assert.deepStrictEqual(state.interrupts.unsafeSize(), Option.some(2))\n    }).pipe(Effect.provide(TestSharding)))\n\n  it.scoped(\"delivers a durable stream\", () =>\n    Effect.gen(function*() {\n      const driver = yield* MessageStorage.MemoryDriver\n      yield* TestClock.adjust(1)\n      const makeClient = yield* TestEntity.client\n      const client = makeClient(\"1\")\n      const users = yield* client.GetAllUsers({ ids: [1, 2, 3] }).pipe(\n        Stream.runCollect\n      )\n      expect(Chunk.toReadonlyArray(users)).toEqual([\n        new User({ id: 1, name: \"User 1\" }),\n        new User({ id: 2, name: \"User 2\" }),\n        new User({ id: 3, name: \"User 3\" })\n      ])\n\n      // 1 request, 3 acks, 4 replies\n      expect(driver.journal.length).toEqual(4)\n      expect(driver.replyIds.size).toEqual(4)\n    }).pipe(Effect.provide(TestSharding)))\n\n  it.scoped(\"durable stream while mailbox is full\", () =>\n    Effect.gen(function*() {\n      const requestedIds = yield* Mailbox.make<Array<Snowflake.Snowflake>>()\n      yield* Effect.gen(function*() {\n        const state = yield* TestEntityState\n        const makeClient = yield* TestEntity.client\n        yield* TestClock.adjust(1)\n        const client = makeClient(\"1\")\n\n        const fibers = yield* client.NeverFork().pipe(Effect.fork, Effect.replicateEffect(10))\n        yield* TestClock.adjust(1)\n\n        const fiber = yield* client.GetAllUsers({ ids: [1, 2, 3] }).pipe(\n          Stream.runCollect,\n          Effect.fork\n        )\n\n        // wait for entity to go into resume mode and request ids\n        const ids = yield* requestedIds.take\n        assert.strictEqual(ids.length, 1)\n        assert.deepStrictEqual(state.envelopes.unsafeSize(), Option.some(10))\n\n        // make sure entity doesn't leave resume mode\n        yield* client.NeverFork().pipe(Effect.fork)\n        yield* TestClock.adjust(1)\n\n        // interrupt first request\n        yield* Fiber.interrupt(fibers[0])\n        yield* TestClock.adjust(100) // let retry happen\n\n        // last request should come through\n        assert.deepStrictEqual(state.envelopes.unsafeSize(), Option.some(11))\n\n        // acks should be allowed to be sent\n        const users = yield* Fiber.join(fiber)\n        expect(Chunk.toReadonlyArray(users)).toEqual([\n          new User({ id: 1, name: \"User 1\" }),\n          new User({ id: 2, name: \"User 2\" }),\n          new User({ id: 3, name: \"User 3\" })\n        ])\n\n        const driver = yield* MessageStorage.MemoryDriver\n        // 12 requests, 3 acks, 1 interrupt, 5 replies\n        assert.strictEqual(driver.journal.length, 12 + 3 + 1)\n        assert.strictEqual(driver.replyIds.size, 1 + 4)\n      }).pipe(Effect.provide(TestShardingWithoutStorage.pipe(\n        Layer.provideMerge(Layer.service(MessageStorage.MemoryDriver)),\n        Layer.updateService(MessageStorage.MessageStorage, (storage) => ({\n          ...storage,\n          unprocessedMessagesById(messageIds) {\n            requestedIds.unsafeOffer(Array.fromIterable(messageIds))\n            return storage.unprocessedMessagesById(messageIds)\n          }\n        })),\n        Layer.provide(MessageStorage.layerMemory),\n        Layer.provide(TestShardingConfig)\n      )))\n    }))\n\n  it.scoped(\"durable messages are retried on restart\", () =>\n    Effect.gen(function*() {\n      const EnvLayer = TestShardingWithoutState.pipe(\n        Layer.provide(Runners.layerNoop),\n        Layer.provide(TestShardingConfig)\n      )\n      const driver = yield* MessageStorage.MemoryDriver\n      const state = yield* TestEntityState\n\n      yield* Effect.gen(function*() {\n        yield* TestClock.adjust(1)\n        const makeClient = yield* TestEntity.client\n        const client = makeClient(\"1\")\n        yield* Effect.fork(client.RequestWithKey({ key: \"abc\" }))\n        yield* TestClock.adjust(1)\n      }).pipe(\n        Effect.provide(EnvLayer),\n        Effect.scoped\n      )\n\n      // only the request should be in the journal\n      expect(driver.journal.length).toEqual(1)\n      expect(driver.replyIds.size).toEqual(0)\n      expect(driver.unprocessed.size).toEqual(1)\n\n      // add response\n      yield* state.messages.offer(void 0)\n\n      yield* TestClock.adjust(5000).pipe(\n        Effect.provide(EnvLayer),\n        Effect.scoped\n      )\n\n      expect(driver.journal.length).toEqual(1)\n      expect(driver.replyIds.size).toEqual(1)\n      expect(driver.unprocessed.size).toEqual(0)\n\n      // the client should read the result from storage\n      yield* Effect.gen(function*() {\n        yield* TestClock.adjust(1)\n        const makeClient = yield* TestEntity.client\n        const client = makeClient(\"1\")\n        const result = yield* client.RequestWithKey({ key: \"abc\" })\n        expect(result).toEqual(void 0)\n      }).pipe(\n        Effect.provide(EnvLayer),\n        Effect.scoped\n      )\n\n      // the request should not hit the entity\n      expect(driver.journal.length).toEqual(1)\n      expect(driver.replyIds.size).toEqual(1)\n      expect(driver.unprocessed.size).toEqual(0)\n    }).pipe(Effect.provide(MessageStorage.layerMemory.pipe(\n      Layer.provide(TestShardingConfig),\n      Layer.merge(TestEntityState.Default)\n    ))))\n\n  it.scoped(\"durable streams are resumed on restart\", () =>\n    Effect.gen(function*() {\n      const EnvLayer = TestShardingWithoutState.pipe(\n        Layer.provide(Runners.layerNoop),\n        Layer.provide(TestShardingConfig)\n      )\n      const driver = yield* MessageStorage.MemoryDriver\n      const state = yield* TestEntityState\n\n      // first chunk\n      yield* state.streamMessages.offerAll([void 0, void 0])\n\n      yield* Effect.gen(function*() {\n        yield* TestClock.adjust(1)\n        const makeClient = yield* TestEntity.client\n        const client = makeClient(\"1\")\n        yield* Effect.fork(Stream.runDrain(client.StreamWithKey({ key: \"abc\" })))\n        yield* TestClock.adjust(1)\n        // second chunk\n        yield* state.streamMessages.offer(void 0)\n        yield* TestClock.adjust(1)\n      }).pipe(\n        Effect.provide(EnvLayer),\n        Effect.scoped\n      )\n\n      // 1 request, 2 acks, 2 replies\n      expect(driver.journal.length).toEqual(1 + 2)\n      expect(driver.replyIds.size).toEqual(2)\n      expect(driver.unprocessed.size).toEqual(1)\n\n      // third chunk\n      yield* state.streamMessages.offerAll([void 0, void 0])\n      yield* state.streamMessages.end\n\n      // the client should resume\n      yield* Effect.gen(function*() {\n        yield* TestClock.adjust(5000) // let the shards get assigned and storage poll\n        const makeClient = yield* TestEntity.client\n        const client = makeClient(\"1\")\n\n        // let the reply loop run\n        yield* TestClock.adjust(500).pipe(Effect.fork)\n\n        const results = Chunk.toReadonlyArray(\n          yield* Stream.runCollect(client.StreamWithKey({ key: \"abc\" }))\n        )\n        expect(results).toEqual([3, 4])\n      }).pipe(\n        Effect.provide(EnvLayer),\n        Effect.scoped\n      )\n\n      // 1 request, 3 acks, 4 replies (3 chunks + WithExit)\n      expect(driver.journal.length).toEqual(1 + 3)\n      expect(driver.replyIds.size).toEqual(4)\n      expect(driver.unprocessed.size).toEqual(0)\n    }).pipe(Effect.provide(MessageStorage.layerMemory.pipe(\n      Layer.provide(TestShardingConfig),\n      Layer.merge(TestEntityState.Default)\n    ))))\n\n  it.scoped(\"client discard option\", () =>\n    Effect.gen(function*() {\n      yield* TestClock.adjust(1)\n      const driver = yield* MessageStorage.MemoryDriver\n      const makeClient = yield* TestEntity.client\n      const client = makeClient(\"1\")\n      const result = yield* client.GetUser({ id: 123 }, { discard: true })\n      expect(result).toEqual(void 0)\n      yield* TestClock.adjust(1)\n      expect(driver.journal.length).toEqual(1)\n      expect(driver.unprocessed.size).toEqual(0)\n    }).pipe(Effect.provide(TestSharding)))\n\n  it.scoped(\"client discard with Never\", () =>\n    Effect.gen(function*() {\n      yield* TestClock.adjust(1)\n      const driver = yield* MessageStorage.MemoryDriver\n      const makeClient = yield* TestEntity.client\n      const client = makeClient(\"1\")\n      const result = yield* client.Never(void 0, { discard: true })\n      expect(result).toEqual(void 0)\n      yield* TestClock.adjust(1)\n      expect(driver.journal.length).toEqual(1)\n      // should still be processing\n      expect(driver.unprocessed.size).toEqual(1)\n    }).pipe(Effect.provide(TestSharding)))\n\n  it.scoped(\"defect when no MessageStorage\", () =>\n    Effect.gen(function*() {\n      const makeClient = yield* TestEntity.client\n      const client = makeClient(\"1\")\n      const cause = yield* client.Never().pipe(\n        Effect.sandbox,\n        Effect.flip\n      )\n      assert(Cause.isDie(cause))\n    }).pipe(Effect.provide(TestShardingWithoutStorage.pipe(\n      Layer.provide(MessageStorage.layerNoop)\n    ))))\n\n  it.scoped(\"restart on defect\", () =>\n    Effect.gen(function*() {\n      yield* TestClock.adjust(1)\n      const state = yield* TestEntityState\n      const makeClient = yield* TestEntity.client\n      const client = makeClient(\"1\")\n      MutableRef.set(state.defectTrigger, true)\n      const result = yield* client.GetUser({ id: 123 })\n      expect(result).toEqual(new User({ id: 123, name: \"User 123\" }))\n      expect(state.layerBuilds.current).toEqual(2)\n    }).pipe(Effect.provide(TestSharding)))\n})\n\nconst TestShardingConfig = ShardingConfig.layer({\n  entityMailboxCapacity: 10,\n  entityTerminationTimeout: 0,\n  entityMessagePollInterval: 5000,\n  sendRetryInterval: 100\n})\n\nconst TestShardingWithoutState = TestEntityNoState.pipe(\n  Layer.provideMerge(Sharding.layer),\n  Layer.provide(RunnerStorage.layerMemory),\n  Layer.provide(RunnerHealth.layerNoop)\n  // Layer.provide(Logger.minimumLogLevel(LogLevel.All)),\n  // Layer.provideMerge(Logger.pretty)\n)\n\nconst TestShardingWithoutRunners = TestShardingWithoutState.pipe(\n  Layer.provideMerge(TestEntityState.Default)\n)\n\nconst TestShardingWithoutStorage = TestShardingWithoutRunners.pipe(\n  Layer.provide(Runners.layerNoop),\n  Layer.provide(TestShardingConfig)\n)\n\nconst TestSharding = TestShardingWithoutStorage.pipe(\n  Layer.provideMerge(MessageStorage.layerMemory),\n  Layer.provide(TestShardingConfig)\n)\n"
  },
  {
    "path": "packages/cluster/test/SqlMessageStorage.test.ts",
    "content": "import { Message, MessageStorage, ShardingConfig, Snowflake, SqlMessageStorage } from \"@effect/cluster\"\nimport { FileSystem } from \"@effect/platform\"\nimport { NodeFileSystem } from \"@effect/platform-node\"\nimport { Rpc } from \"@effect/rpc\"\nimport { SqliteClient } from \"@effect/sql-sqlite-node\"\nimport { SqlClient } from \"@effect/sql/SqlClient\"\nimport { assert, describe, expect, it } from \"@effect/vitest\"\nimport { Effect, Fiber, Layer, TestClock } from \"effect\"\nimport { MysqlContainer } from \"./fixtures/utils-mysql.js\"\nimport { PgContainer } from \"./fixtures/utils-pg.js\"\nimport {\n  makeAckChunk,\n  makeChunkReply,\n  makeReply,\n  makeRequest,\n  PrimaryKeyTest,\n  StreamRpc,\n  StreamTest\n} from \"./MessageStorage.test.js\"\n\nconst StorageLive = SqlMessageStorage.layer.pipe(\n  Layer.provideMerge(Snowflake.layerGenerator),\n  Layer.provide(ShardingConfig.layerDefaults)\n)\n\nconst truncate = Effect.gen(function*() {\n  const sql = yield* SqlClient\n  yield* sql`DELETE FROM cluster_replies`\n  yield* sql`DELETE FROM cluster_messages`\n})\n\ndescribe(\"SqlMessageStorage\", () => {\n  ;([\n    [\"pg\", Layer.orDie(PgContainer.ClientLive)],\n    [\"mysql\", Layer.orDie(MysqlContainer.ClientLive)],\n    [\"sqlite\", Layer.orDie(SqliteLayer)]\n  ] as const).forEach(([label, layer]) => {\n    it.layer(StorageLive.pipe(Layer.provideMerge(layer)), {\n      timeout: 120000\n    })(label, (it) => {\n      it.effect(\"saveRequest\", () =>\n        Effect.gen(function*() {\n          const storage = yield* MessageStorage.MessageStorage\n          const request = yield* makeRequest({ payload: { id: 1 } })\n          const result = yield* storage.saveRequest(request)\n          expect(result._tag).toEqual(\"Success\")\n\n          for (let i = 2; i <= 5; i++) {\n            yield* storage.saveRequest(yield* makeRequest({ payload: { id: i } }))\n          }\n\n          yield* storage.saveReply(yield* makeReply(request))\n\n          let messages = yield* storage.unprocessedMessages([request.envelope.address.shardId])\n          expect(messages).toHaveLength(4)\n          expect(messages.map((m: any) => m.envelope.payload.id)).toEqual([2, 3, 4, 5])\n\n          for (let i = 6; i <= 10; i++) {\n            yield* storage.saveRequest(yield* makeRequest({ payload: { id: i } }))\n          }\n          messages = yield* storage.unprocessedMessages([request.envelope.address.shardId])\n          expect(messages).toHaveLength(5)\n          expect(messages.map((m: any) => m.envelope.payload.id)).toEqual([6, 7, 8, 9, 10])\n        }))\n\n      it.effect(\"saveReply + saveRequest duplicate\", () =>\n        Effect.gen(function*() {\n          const sql = yield* SqlClient\n          const storage = yield* MessageStorage.MessageStorage\n          const request = yield* makeRequest({\n            rpc: StreamRpc,\n            payload: new StreamTest({ id: 123 })\n          })\n          let result = yield* storage.saveRequest(request)\n          expect(result._tag).toEqual(\"Success\")\n\n          let chunk = yield* makeChunkReply(request, 0)\n          yield* storage.saveReply(chunk)\n          const ackChunk = yield* makeAckChunk(request, chunk)\n          yield* storage.saveEnvelope(ackChunk)\n\n          chunk = yield* makeChunkReply(request, 1)\n          yield* storage.saveReply(chunk)\n\n          result = yield* storage.saveRequest(\n            yield* makeRequest({\n              rpc: StreamRpc,\n              payload: new StreamTest({ id: 123 })\n            })\n          )\n          assert(result._tag === \"Duplicate\")\n          assert(result.lastReceivedReply._tag === \"Some\")\n          expect(result.lastReceivedReply.value._tag).toEqual(\"Chunk\")\n\n          // get the un-acked chunk\n          const replies = yield* storage.repliesFor([request])\n          expect(replies).toHaveLength(1)\n\n          yield* storage.saveReply(yield* makeReply(request))\n\n          result = yield* storage.saveRequest(\n            yield* makeRequest({\n              rpc: StreamRpc,\n              payload: new StreamTest({ id: 123 })\n            })\n          )\n          assert(result._tag === \"Duplicate\")\n          assert(result.lastReceivedReply._tag === \"Some\")\n          expect(result.lastReceivedReply.value._tag).toEqual(\"WithExit\")\n\n          // duplicate WithExit\n          const fiber = yield* storage.saveReply(yield* makeReply(request)).pipe(Effect.fork)\n          yield* TestClock.adjust(1)\n          while (!fiber.unsafePoll()) {\n            yield* sql`SELECT 1`\n            yield* TestClock.adjust(1000)\n          }\n          const error = yield* Effect.flip(Fiber.join(fiber))\n          expect(error._tag).toEqual(\"PersistenceError\")\n        }))\n\n      it.effect(\"detects duplicates\", () =>\n        Effect.gen(function*() {\n          yield* truncate\n\n          const storage = yield* MessageStorage.MessageStorage\n          yield* storage.saveRequest(\n            yield* makeRequest({\n              rpc: Rpc.fromTaggedRequest(PrimaryKeyTest),\n              payload: new PrimaryKeyTest({ id: 123 })\n            })\n          )\n          const result = yield* storage.saveRequest(\n            yield* makeRequest({\n              rpc: Rpc.fromTaggedRequest(PrimaryKeyTest),\n              payload: new PrimaryKeyTest({ id: 123 })\n            })\n          )\n          expect(result._tag).toEqual(\"Duplicate\")\n        }))\n\n      it.effect(\"unprocessedMessages\", () =>\n        Effect.gen(function*() {\n          yield* truncate\n\n          const storage = yield* MessageStorage.MessageStorage\n          const request = yield* makeRequest()\n          yield* storage.saveRequest(request)\n          let messages = yield* storage.unprocessedMessages([request.envelope.address.shardId])\n          expect(messages).toHaveLength(1)\n          messages = yield* storage.unprocessedMessages([request.envelope.address.shardId])\n          expect(messages).toHaveLength(0)\n          yield* storage.saveRequest(yield* makeRequest())\n          messages = yield* storage.unprocessedMessages([request.envelope.address.shardId])\n          expect(messages).toHaveLength(1)\n        }))\n\n      it.effect(\"unprocessedMessages excludes complete requests\", () =>\n        Effect.gen(function*() {\n          yield* truncate\n\n          const storage = yield* MessageStorage.MessageStorage\n          const request = yield* makeRequest()\n          yield* storage.saveRequest(request)\n          yield* storage.saveReply(yield* makeReply(request))\n          const messages = yield* storage.unprocessedMessages([request.envelope.address.shardId])\n          expect(messages).toHaveLength(0)\n        }))\n\n      it.effect(\"repliesFor\", () =>\n        Effect.gen(function*() {\n          yield* truncate\n\n          const storage = yield* MessageStorage.MessageStorage\n          const request = yield* makeRequest()\n          yield* storage.saveRequest(request)\n          let replies = yield* storage.repliesFor([request])\n          expect(replies).toHaveLength(0)\n          yield* storage.saveReply(yield* makeReply(request))\n          replies = yield* storage.repliesFor([request])\n          expect(replies).toHaveLength(1)\n          expect(replies[0].requestId).toEqual(request.envelope.requestId)\n        }))\n\n      it.effect(\"registerReplyHandler\", () =>\n        Effect.gen(function*() {\n          const storage = yield* MessageStorage.MessageStorage\n          const latch = yield* Effect.makeLatch()\n          const request = yield* makeRequest()\n          yield* storage.saveRequest(request)\n          const fiber = yield* storage.registerReplyHandler(\n            new Message.OutgoingRequest({\n              ...request,\n              respond: () => latch.open\n            })\n          ).pipe(Effect.fork)\n          yield* TestClock.adjust(1)\n          yield* storage.saveReply(yield* makeReply(request))\n          yield* latch.await\n          yield* fiber.await\n        }))\n\n      it.effect(\"unprocessedMessagesById\", () =>\n        Effect.gen(function*() {\n          yield* truncate\n\n          const storage = yield* MessageStorage.MessageStorage\n          const request = yield* makeRequest()\n          yield* storage.saveRequest(request)\n          let messages = yield* storage.unprocessedMessagesById([request.envelope.requestId])\n          expect(messages).toHaveLength(1)\n          yield* storage.saveReply(yield* makeReply(request))\n          messages = yield* storage.unprocessedMessagesById([request.envelope.requestId])\n          expect(messages).toHaveLength(0)\n        }))\n    })\n  })\n})\n\nconst SqliteLayer = Effect.gen(function*() {\n  const fs = yield* FileSystem.FileSystem\n  const dir = yield* fs.makeTempDirectoryScoped()\n  return SqliteClient.layer({\n    filename: dir + \"/test.db\"\n  })\n}).pipe(Layer.unwrapScoped, Layer.provide(NodeFileSystem.layer))\n"
  },
  {
    "path": "packages/cluster/test/SqlRunnerStorage.test.ts",
    "content": "import { Runner, RunnerAddress, RunnerStorage, ShardId, SqlRunnerStorage } from \"@effect/cluster\"\nimport { FileSystem } from \"@effect/platform\"\nimport { NodeFileSystem } from \"@effect/platform-node\"\nimport { SqliteClient } from \"@effect/sql-sqlite-node\"\nimport { describe, expect, it } from \"@effect/vitest\"\nimport { Effect, Layer } from \"effect\"\nimport * as ShardingConfig from \"../src/ShardingConfig.js\"\nimport { MysqlContainer } from \"./fixtures/utils-mysql.js\"\nimport { PgContainer } from \"./fixtures/utils-pg.js\"\n\nconst StorageLive = SqlRunnerStorage.layer\n\ndescribe(\"SqlRunnerStorage\", () => {\n  ;([\n    [\"pg\", Layer.orDie(PgContainer.ClientLive)],\n    [\"mysql\", Layer.orDie(MysqlContainer.ClientLive)],\n    [\"vitess\", Layer.orDie(MysqlContainer.ClientLiveVitess)],\n    [\"sqlite\", Layer.orDie(SqliteLayer)]\n  ] as const).flatMap(([label, layer]) =>\n    [\n      [label, StorageLive.pipe(Layer.provideMerge(layer), Layer.provide(ShardingConfig.layer()))],\n      [\n        label + \" (no advisory)\",\n        StorageLive.pipe(\n          Layer.provideMerge(layer),\n          Layer.provide(ShardingConfig.layer({\n            shardLockDisableAdvisory: true\n          }))\n        )\n      ]\n    ] as const\n  ).forEach(([label, layer]) => {\n    it.layer(layer, {\n      timeout: 60000\n    })(label, (it) => {\n      it.effect(\"getRunners\", () =>\n        Effect.gen(function*() {\n          const storage = yield* RunnerStorage.RunnerStorage\n\n          const runner = Runner.make({\n            address: runnerAddress1,\n            groups: [\"default\"],\n            weight: 1\n          })\n          const machineId = yield* storage.register(runner, true)\n          yield* storage.register(runner, true)\n          expect(machineId).toEqual(1)\n          expect(yield* storage.getRunners).toEqual([[runner, true]])\n\n          yield* storage.setRunnerHealth(runnerAddress1, false)\n          expect(yield* storage.getRunners).toEqual([[runner, false]])\n\n          yield* storage.unregister(runnerAddress1)\n          expect(yield* storage.getRunners).toEqual([])\n        }), 30_000)\n\n      it.effect(\"acquireShards\", () =>\n        Effect.gen(function*() {\n          const storage = yield* RunnerStorage.RunnerStorage\n\n          let acquired = yield* storage.acquire(runnerAddress1, [\n            ShardId.make(\"default\", 1),\n            ShardId.make(\"default\", 2),\n            ShardId.make(\"default\", 3)\n          ])\n          expect(acquired.map((_) => _.id)).toEqual([1, 2, 3])\n          acquired = yield* storage.acquire(runnerAddress1, [\n            ShardId.make(\"default\", 1),\n            ShardId.make(\"default\", 2),\n            ShardId.make(\"default\", 3)\n          ])\n          expect(acquired.map((_) => _.id)).toEqual([1, 2, 3])\n\n          const refreshed = yield* storage.refresh(runnerAddress1, [\n            ShardId.make(\"default\", 1),\n            ShardId.make(\"default\", 2),\n            ShardId.make(\"default\", 3)\n          ])\n          expect(refreshed.map((_) => _.id)).toEqual([1, 2, 3])\n\n          // smoke test release\n          yield* storage.release(runnerAddress1, ShardId.make(\"default\", 2))\n        }))\n    })\n  })\n})\n\nconst runnerAddress1 = RunnerAddress.make(\"localhost\", 1234)\n\nconst SqliteLayer = Effect.gen(function*() {\n  const fs = yield* FileSystem.FileSystem\n  const dir = yield* fs.makeTempDirectoryScoped()\n  return SqliteClient.layer({\n    filename: dir + \"/test.db\"\n  })\n}).pipe(Layer.unwrapScoped, Layer.provide(NodeFileSystem.layer))\n"
  },
  {
    "path": "packages/cluster/test/TestEntity.ts",
    "content": "import type { Envelope } from \"@effect/cluster\"\nimport { ClusterSchema, Entity } from \"@effect/cluster\"\nimport type { RpcGroup } from \"@effect/rpc\"\nimport { Rpc, RpcSchema } from \"@effect/rpc\"\nimport { Effect, Layer, Mailbox, MutableRef, Option, PrimaryKey, Schedule, Schema, Stream } from \"effect\"\n\nexport class User extends Schema.Class<User>(\"User\")({\n  id: Schema.Number,\n  name: Schema.String\n}) {}\n\nexport class StreamWithKey extends Schema.TaggedRequest<StreamWithKey>()(\"StreamWithKey\", {\n  success: RpcSchema.Stream({\n    success: Schema.Number,\n    failure: Schema.Never\n  }),\n  failure: Schema.Never,\n  payload: { key: Schema.String }\n}) {\n  [PrimaryKey.symbol]() {\n    return this.key\n  }\n}\n\nexport const TestEntity = Entity.make(\"TestEntity\", [\n  Rpc.make(\"GetUser\", {\n    success: User,\n    payload: { id: Schema.Number }\n  }),\n  Rpc.make(\"GetUserVolatile\", {\n    success: User,\n    payload: { id: Schema.Number }\n  }).annotate(ClusterSchema.Persisted, false),\n  Rpc.make(\"Never\"),\n  Rpc.make(\"NeverFork\"),\n  Rpc.make(\"NeverVolatile\").annotate(ClusterSchema.Persisted, false),\n  Rpc.make(\"RequestWithKey\", {\n    payload: { key: Schema.String },\n    primaryKey: ({ key }) => key\n  }),\n  Rpc.fromTaggedRequest(StreamWithKey),\n  Rpc.make(\"GetAllUsers\", {\n    success: User,\n    payload: { ids: Schema.Array(Schema.Number) },\n    stream: true\n  })\n]).annotateRpcs(ClusterSchema.Persisted, true)\n\nexport class TestEntityState extends Effect.Service<TestEntityState>()(\"TestEntityState\", {\n  effect: Effect.gen(function*() {\n    const messages = yield* Mailbox.make<void>()\n    const streamMessages = yield* Mailbox.make<void>()\n    const envelopes = yield* Mailbox.make<\n      RpcGroup.Rpcs<typeof TestEntity.protocol> extends infer R ? R extends Rpc.Any ? Envelope.Request<R> : never\n        : never\n    >()\n    const interrupts = yield* Mailbox.make<\n      RpcGroup.Rpcs<typeof TestEntity.protocol> extends infer R ? R extends Rpc.Any ? Envelope.Request<R> : never\n        : never\n    >()\n    const defectTrigger = MutableRef.make(false)\n    const layerBuilds = MutableRef.make(0)\n\n    return {\n      messages,\n      streamMessages,\n      envelopes,\n      interrupts,\n      defectTrigger,\n      layerBuilds\n    } as const\n  })\n}) {}\n\nexport const TestEntityNoState = TestEntity.toLayer(\n  Effect.gen(function*() {\n    const state = yield* TestEntityState\n\n    MutableRef.update(state.layerBuilds, (count) => count + 1)\n\n    const never = (envelope: any) =>\n      Effect.suspend(() => {\n        state.envelopes.unsafeOffer(envelope)\n        return Effect.never\n      }).pipe(Effect.onInterrupt(() => {\n        state.interrupts.unsafeOffer(envelope)\n        return Effect.void\n      }))\n    return {\n      GetUser: (envelope) =>\n        Effect.sync(() => {\n          state.envelopes.unsafeOffer(envelope)\n          if (state.defectTrigger.current) {\n            MutableRef.set(state.defectTrigger, false)\n            throw new Error(\"User not found\")\n          }\n          return new User({ id: envelope.payload.id, name: `User ${envelope.payload.id}` })\n        }),\n      GetUserVolatile: (envelope) =>\n        Effect.sync(() => {\n          state.envelopes.unsafeOffer(envelope)\n          return new User({ id: envelope.payload.id, name: `User ${envelope.payload.id}` })\n        }),\n      Never: never,\n      NeverFork: (envelope) => Rpc.fork(never(envelope)),\n      NeverVolatile: never,\n      RequestWithKey: (envelope) => {\n        state.envelopes.unsafeOffer(envelope)\n        return Effect.orDie(state.messages.take)\n      },\n      StreamWithKey: (envelope) => {\n        let sequence = envelope.lastSentChunkValue.pipe(\n          Option.map((value) => value + 1),\n          Option.getOrElse(() => 0)\n        )\n        return Mailbox.toStream(state.streamMessages).pipe(\n          Stream.map(() => sequence++)\n        )\n      },\n      GetAllUsers: (envelope) => {\n        state.envelopes.unsafeOffer(envelope)\n        return Stream.fromIterable(envelope.payload.ids.map((id) => new User({ id, name: `User ${id}` }))).pipe(\n          Stream.rechunk(1)\n        )\n      }\n    }\n  }),\n  { defectRetryPolicy: Schedule.forever }\n)\n\nexport const TestEntityLayer = TestEntityNoState.pipe(Layer.provideMerge(TestEntityState.Default))\n"
  },
  {
    "path": "packages/cluster/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"references\": [\n    { \"path\": \"../effect/tsconfig.build.json\" },\n    { \"path\": \"../platform/tsconfig.build.json\" },\n    { \"path\": \"../rpc/tsconfig.build.json\" },\n    { \"path\": \"../sql/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true\n  }\n}\n"
  },
  {
    "path": "packages/cluster/tsconfig.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/cluster/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"references\": [\n    { \"path\": \"../effect\" },\n    { \"path\": \"../platform\" },\n    { \"path\": \"../rpc\" },\n    { \"path\": \"../sql\" },\n    { \"path\": \"../workflow\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\",\n    \"outDir\": \"build/src\"\n  }\n}\n"
  },
  {
    "path": "packages/cluster/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../platform-node/tsconfig.src.json\" },\n    { \"path\": \"../sql-pg/tsconfig.src.json\" },\n    { \"path\": \"../sql-mysql2/tsconfig.src.json\" },\n    { \"path\": \"../sql-sqlite-node/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "packages/cluster/vitest.config.ts",
    "content": "import { mergeConfig, type UserConfigExport } from \"vitest/config\"\nimport shared from \"../../vitest.shared.js\"\n\nconst config: UserConfigExport = {}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/effect/CHANGELOG.md",
    "content": "# effect\n\n## 3.21.0\n\n### Minor Changes\n\n- [#5780](https://github.com/Effect-TS/effect/pull/5780) [`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109) Thanks @kitlangton! - Add `Cron.prev` and reverse iteration support, aligning next/prev lookup tables, fixing DST handling symmetry, and expanding cron backward/forward test coverage.\n\n- [#5780](https://github.com/Effect-TS/effect/pull/5780) [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31) Thanks @mattiamanzati! - Add type-level utils to asserting layer types\n\n- [#5780](https://github.com/Effect-TS/effect/pull/5780) [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098) Thanks @schickling! - RcMap: support dynamic `idleTimeToLive` values per key\n\n  The `idleTimeToLive` option can now be a function that receives the key and returns a duration, allowing different TTL values for different resources.\n\n  ```ts\n  const map =\n    yield *\n    RcMap.make({\n      lookup: (key: string) => acquireResource(key),\n      idleTimeToLive: (key: string) => {\n        if (key.startsWith(\"premium:\")) return Duration.minutes(10)\n        return Duration.minutes(1)\n      }\n    })\n  ```\n\n- [#5780](https://github.com/Effect-TS/effect/pull/5780) [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb) Thanks @mikearnaldi! - Fix annotateCurrentSpan, add Effect.currentPropagatedSpan\n\n### Patch Changes\n\n- [#5780](https://github.com/Effect-TS/effect/pull/5780) [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb) Thanks @mikearnaldi! - Add logs to first propagated span, in the following case before this fix the log would not be added to the `p` span because `Effect.fn` adds a fake span for the purpose of adding a stack frame.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  const f = Effect.fn(function* () {\n    yield* Effect.logWarning(\"FooBar\")\n    return yield* Effect.fail(\"Oops\")\n  })\n\n  const p = f().pipe(Effect.withSpan(\"p\"))\n  ```\n\n## 3.20.1\n\n### Patch Changes\n\n- [#6133](https://github.com/Effect-TS/effect/pull/6133) [`add06f4`](https://github.com/Effect-TS/effect/commit/add06f4521403cbf4b9a692f9b59fb9d3d48293c) Thanks @aniravi24! - Fix `Equal.equals` crash when comparing `null` values inside `structuralRegion`. Added null guard before `Object.getPrototypeOf` calls to prevent `TypeError: Cannot convert undefined or null to object`.\n\n- [#6093](https://github.com/Effect-TS/effect/pull/6093) [`a03b6a2`](https://github.com/Effect-TS/effect/commit/a03b6a29ed0b983b0440b8ef4be47f47c57d73d7) Thanks @luchersou! - avoid class for PrettyError to preserve error.name\n\n## 3.20.0\n\n### Minor Changes\n\n- [#6124](https://github.com/Effect-TS/effect/pull/6124) [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da) Thanks @mikearnaldi! - Fix scheduler task draining to isolate `AsyncLocalStorage` across fibers.\n\n### Patch Changes\n\n- [#6107](https://github.com/Effect-TS/effect/pull/6107) [`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54) Thanks @gcanti! - Backport `Types.VoidIfEmpty` to 3.x\n\n- [#6088](https://github.com/Effect-TS/effect/pull/6088) [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7) Thanks @taylorOntologize! - Schema: fix `Schema.omit` producing wrong result on Struct with `optionalWith({ default })` and index signatures\n\n  `getIndexSignatures` now handles `Transformation` AST nodes by delegating to `ast.to`, matching the existing behavior of `getPropertyKeys` and `getPropertyKeyIndexedAccess`. Previously, `Schema.omit` on a struct combining `Schema.optionalWith` (with `{ default }`, `{ as: \"Option\" }`, etc.) and `Schema.Record` would silently take the wrong code path, returning a Transformation with property signatures instead of a TypeLiteral with index signatures.\n\n- [#6086](https://github.com/Effect-TS/effect/pull/6086) [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada) Thanks @taylorOntologize! - Schema: fix `getPropertySignatures` crash on Struct with `optionalWith({ default })` and other Transformation-producing variants\n\n  `SchemaAST.getPropertyKeyIndexedAccess` now handles `Transformation` AST nodes by delegating to `ast.to`, matching the existing behavior of `getPropertyKeys`. Previously, calling `getPropertySignatures` on a `Schema.Struct` containing `Schema.optionalWith` with `{ default }`, `{ as: \"Option\" }`, `{ nullable: true }`, or similar options would throw `\"Unsupported schema (Transformation)\"`.\n\n- [#6097](https://github.com/Effect-TS/effect/pull/6097) [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2) Thanks @gcanti! - Fix TupleWithRest post-rest validation to check each tail index sequentially.\n\n## 3.19.19\n\n### Patch Changes\n\n- [#6079](https://github.com/Effect-TS/effect/pull/6079) [`4eb5c00`](https://github.com/Effect-TS/effect/commit/4eb5c008dfc7d2a97b191ca608948d994a2cce4c) Thanks @tim-smart! - add short circuit to fiber.await internals\n\n- [#6079](https://github.com/Effect-TS/effect/pull/6079) [`4eb5c00`](https://github.com/Effect-TS/effect/commit/4eb5c008dfc7d2a97b191ca608948d994a2cce4c) Thanks @tim-smart! - build ManagedRuntime synchronously if possible\n\n- [#6081](https://github.com/Effect-TS/effect/pull/6081) [`2d2bb13`](https://github.com/Effect-TS/effect/commit/2d2bb1364a906bd44800c6387b9575fddccdaf53) Thanks @tim-smart! - fix semaphore race condition where permits could be leaked\n\n## 3.19.18\n\n### Patch Changes\n\n- [#6062](https://github.com/Effect-TS/effect/pull/6062) [`12b1f1e`](https://github.com/Effect-TS/effect/commit/12b1f1eadf649e30dec581b7351ba3abb12f8004) Thanks @tim-smart! - prevent Stream.changes from writing empty chunks\n\n## 3.19.17\n\n### Patch Changes\n\n- [#6040](https://github.com/Effect-TS/effect/pull/6040) [`a8c436f`](https://github.com/Effect-TS/effect/commit/a8c436f7004cc2a8ce2daec589ea7256b91c324f) Thanks @jacobconley! - Fix `Stream.decodeText` to correctly handle multi-byte UTF-8 characters split across chunk boundaries.\n\n## 3.19.16\n\n### Patch Changes\n\n- [#6018](https://github.com/Effect-TS/effect/pull/6018) [`e71889f`](https://github.com/Effect-TS/effect/commit/e71889f35b081d13b7da2c04d2f81d6933056b49) Thanks @codewithkenzo! - fix(Match): handle null/undefined in `Match.tag` and `Match.tagStartsWith`\n\n  Added null checks to `discriminator` and `discriminatorStartsWith` predicates to prevent crashes when matching nullable union types.\n\n  Fixes #6017\n\n## 3.19.15\n\n### Patch Changes\n\n- [#5981](https://github.com/Effect-TS/effect/pull/5981) [`7e925ea`](https://github.com/Effect-TS/effect/commit/7e925eae4a9db556bcbf7e8b6a762ccf8588aa3b) Thanks @bxff! - Fix type inference loss in `Array.flatten` for complex nested structures like unions of Effects with contravariant requirements. Uses distributive indexed access (`T[number][number]`) in the `Flatten` type utility and adds `const` to the `flatten` generic parameter.\n\n- [#5970](https://github.com/Effect-TS/effect/pull/5970) [`d7e75d6`](https://github.com/Effect-TS/effect/commit/d7e75d6d15294bbcd7ac49a0e9005848379ea86f) Thanks @KhraksMamtsov! - fix Config.orElseIf signature\n\n- [#5996](https://github.com/Effect-TS/effect/pull/5996) [`4860d1e`](https://github.com/Effect-TS/effect/commit/4860d1e09b436061ea4aeca07605a669793560fc) Thanks @parischap! - fix Equal.equals plain object comparisons in structural mode\n\n## 3.19.14\n\n### Patch Changes\n\n- [#5924](https://github.com/Effect-TS/effect/pull/5924) [`488d6e8`](https://github.com/Effect-TS/effect/commit/488d6e870eda3dfc137f4940bb69416f61ed8fe3) Thanks @mikearnaldi! - Fix `Effect.retry` to respect `times: 0` option by using explicit undefined check instead of truthy check.\n\n## 3.19.13\n\n### Patch Changes\n\n- [#5911](https://github.com/Effect-TS/effect/pull/5911) [`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371) Thanks @mattiamanzati! - Add test for ensuring typeConstructor is attached\n\n- [#5910](https://github.com/Effect-TS/effect/pull/5910) [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3) Thanks @mattiamanzati! - Add typeConstructor annotation for Schema\n\n## 3.19.12\n\n### Patch Changes\n\n- [#5897](https://github.com/Effect-TS/effect/pull/5897) [`a6dfca9`](https://github.com/Effect-TS/effect/commit/a6dfca93b676eeffe4db64945b01e2004b395cb8) Thanks @fubhy! - Ensure `performance.now` is only used if it's available\n\n## 3.19.11\n\n### Patch Changes\n\n- [#5888](https://github.com/Effect-TS/effect/pull/5888) [`38abd67`](https://github.com/Effect-TS/effect/commit/38abd67998f676893866a72cb41bbd5edd07b169) Thanks @gcanti! - filter non-JSON values from schema examples and defaults, closes #5884\n\n  Introduce JsonValue type and update JsonSchemaAnnotations to use it for\n  type safety. Add validation to filter invalid values (BigInt, cyclic refs)\n  from examples and defaults, preventing infinite recursion on cycles.\n\n- [#5885](https://github.com/Effect-TS/effect/pull/5885) [`44e0b04`](https://github.com/Effect-TS/effect/commit/44e0b044480c5d8ab17fbdaf1c528f06796fa681) Thanks @gcanti! - feat(JSONSchema): add missing options for target JSON Schema version in make function, closes #5883\n\n## 3.19.10\n\n### Patch Changes\n\n- [#5874](https://github.com/Effect-TS/effect/pull/5874) [`bd08028`](https://github.com/Effect-TS/effect/commit/bd080284febb620e7e71f661bf9d850c402bb87f) Thanks @mattiamanzati! - Fix NoSuchElementException instantiation in fastPath and add corresponding test case\n\n- [#5878](https://github.com/Effect-TS/effect/pull/5878) [`6c5c2ba`](https://github.com/Effect-TS/effect/commit/6c5c2ba50ce49386e8d1e657230492ee900a6ec7) Thanks @Hoishin! - prevent crash from Hash and Equal with invalid Date object\n\n## 3.19.9\n\n### Patch Changes\n\n- [#5875](https://github.com/Effect-TS/effect/pull/5875) [`3f9bbfe`](https://github.com/Effect-TS/effect/commit/3f9bbfe9ef78303ecc6817b68ec9671f4d42d249) Thanks @gcanti! - Fix the arbitrary generator for BigDecimal to allow negative scales.\n\n## 3.19.8\n\n### Patch Changes\n\n- [#5815](https://github.com/Effect-TS/effect/pull/5815) [`f03b8e5`](https://github.com/Effect-TS/effect/commit/f03b8e55f12019cc855a1306e9cbfc7611a9e281) Thanks @lokhmakov! - Prevent multiple iterations over the same Iterable in Array.intersectionWith and Array.differenceWith\n\n## 3.19.7\n\n### Patch Changes\n\n- [#5813](https://github.com/Effect-TS/effect/pull/5813) [`7ef13d3`](https://github.com/Effect-TS/effect/commit/7ef13d30147dd50eae1cdbb67a1978141751cad5) Thanks @tim-smart! - fix SqlPersistedQueue batch size\n\n## 3.19.6\n\n### Patch Changes\n\n- [#5778](https://github.com/Effect-TS/effect/pull/5778) [`af7916a`](https://github.com/Effect-TS/effect/commit/af7916a3f00acdfc8ce451eabd3f5fb02914d0bb) Thanks @tim-smart! - add RcRef.invalidate api\n\n## 3.19.5\n\n### Patch Changes\n\n- [#5772](https://github.com/Effect-TS/effect/pull/5772) [`079975c`](https://github.com/Effect-TS/effect/commit/079975c69d80c62461da5c51fe89e02c44dfa2ea) Thanks @tim-smart! - backport Effect.gen optimization\n\n## 3.19.4\n\n### Patch Changes\n\n- [#5752](https://github.com/Effect-TS/effect/pull/5752) [`f445b87`](https://github.com/Effect-TS/effect/commit/f445b87bab342188a5c223cfc76c697d65594d1d) Thanks @janglad! - Fix Types.DeepMutable mapping over functions\n\n- [#5757](https://github.com/Effect-TS/effect/pull/5757) [`d2b68ac`](https://github.com/Effect-TS/effect/commit/d2b68ac9e1ac1d58d7387715843c448195f14675) Thanks @tim-smart! - add experimental PartitionedSemaphore module\n\n  A `PartitionedSemaphore` is a concurrency primitive that can be used to\n  control concurrent access to a resource across multiple partitions identified\n  by keys.\n\n  The total number of permits is shared across all partitions, with waiting\n  permits equally distributed among partitions using a round-robin strategy.\n\n  This is useful when you want to limit the total number of concurrent accesses\n  to a resource, while still allowing for fair distribution of access across\n  different partitions.\n\n  ```ts\n  import { Effect, PartitionedSemaphore } from \"effect\"\n\n  Effect.gen(function* () {\n    const semaphore = yield* PartitionedSemaphore.make<string>({ permits: 5 })\n\n    // Take the first 5 permits with key \"A\", then the following permits will be\n    // equally distributed between all the keys using a round-robin strategy\n    yield* Effect.log(\"A\").pipe(\n      Effect.delay(1000),\n      semaphore.withPermits(\"A\", 1),\n      Effect.replicateEffect(15, { concurrency: \"unbounded\" }),\n      Effect.fork\n    )\n    yield* Effect.log(\"B\").pipe(\n      Effect.delay(1000),\n      semaphore.withPermits(\"B\", 1),\n      Effect.replicateEffect(10, { concurrency: \"unbounded\" }),\n      Effect.fork\n    )\n    yield* Effect.log(\"C\").pipe(\n      Effect.delay(1000),\n      semaphore.withPermits(\"C\", 1),\n      Effect.replicateEffect(10, { concurrency: \"unbounded\" }),\n      Effect.fork\n    )\n\n    return yield* Effect.never\n  }).pipe(Effect.runFork)\n  ```\n\n## 3.19.3\n\n### Patch Changes\n\n- [#5712](https://github.com/Effect-TS/effect/pull/5712) [`7d28a90`](https://github.com/Effect-TS/effect/commit/7d28a908f965854cff386a19515141aea5b39eb7) Thanks @gcanti! - Use standard formatting function in Config error messages, closes #5709\n\n## 3.19.2\n\n### Patch Changes\n\n- [#5703](https://github.com/Effect-TS/effect/pull/5703) [`374f58c`](https://github.com/Effect-TS/effect/commit/374f58c10799109b61d8a131a025f3d03ce5aab5) Thanks @tim-smart! - preserve Layer.mergeAll context order\n\n- [#5703](https://github.com/Effect-TS/effect/pull/5703) [`374f58c`](https://github.com/Effect-TS/effect/commit/374f58c10799109b61d8a131a025f3d03ce5aab5) Thanks @tim-smart! - ensure FiberHandle.run state transition is atomic\n\n## 3.19.1\n\n### Patch Changes\n\n- [#5695](https://github.com/Effect-TS/effect/pull/5695) [`63f2bf3`](https://github.com/Effect-TS/effect/commit/63f2bf393ef4bb3e46db59abdf1b2160e8ee71d4) Thanks @tim-smart! - allow parallel finalization of merged layers\n\n## 3.19.0\n\n### Minor Changes\n\n- [#5606](https://github.com/Effect-TS/effect/pull/5606) [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a) Thanks @mikearnaldi! - Add Effect.fn.Return to allow typing returns on Effect.fn\n\n- [#5606](https://github.com/Effect-TS/effect/pull/5606) [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d) Thanks @fubhy! - Backport `Graph` module updates\n\n- [#5606](https://github.com/Effect-TS/effect/pull/5606) [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433) Thanks @tim-smart! - add experimental HashRing module\n\n### Patch Changes\n\n- [#5679](https://github.com/Effect-TS/effect/pull/5679) [`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c) Thanks @KhraksMamtsov! - `Array.window` signature has been improved\n\n## 3.18.5\n\n### Patch Changes\n\n- [#5669](https://github.com/Effect-TS/effect/pull/5669) [`a537469`](https://github.com/Effect-TS/effect/commit/a5374696bdabee005bf75d7b1b57f8bee7763cba) Thanks @fubhy! - Fix Graph.neighbors() returning self-loops in undirected graphs.\n\n  Graph.neighbors() now correctly returns the other endpoint for undirected graphs instead of always returning edge.target, which caused nodes to appear as their own neighbors when queried from the target side of an edge.\n\n- [#5628](https://github.com/Effect-TS/effect/pull/5628) [`52d5963`](https://github.com/Effect-TS/effect/commit/52d59635f35406bd27874ca0090f8642432928f4) Thanks @mikearnaldi! - Make sure AsEffect is computed\n\n- [#5671](https://github.com/Effect-TS/effect/pull/5671) [`463345d`](https://github.com/Effect-TS/effect/commit/463345d734fb462dc284d590193b7843dc104d78) Thanks @gcanti! - JSON Schema generation: add `jsonSchema2020-12` target and fix tuple output for:\n  - JSON Schema 2019-09\n  - OpenAPI 3.1\n\n## 3.18.4\n\n### Patch Changes\n\n- [#5617](https://github.com/Effect-TS/effect/pull/5617) [`6ae2f5d`](https://github.com/Effect-TS/effect/commit/6ae2f5da45a9ed9832605eca12b3e2bf2e2a1a67) Thanks @gcanti! - JSONSchema: Fix issue where invalid `default`s were included in the output.\n\n  Now they are ignored, similar to invalid `examples`.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.NonEmptyString.annotations({\n    default: \"\"\n  })\n\n  const jsonSchema = JSONSchema.make(schema)\n\n  console.log(JSON.stringify(jsonSchema, null, 2))\n  /*\n  Output:\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"description\": \"a non empty string\",\n    \"title\": \"nonEmptyString\",\n    \"default\": \"\",\n    \"minLength\": 1\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.NonEmptyString.annotations({\n    default: \"\"\n  })\n\n  const jsonSchema = JSONSchema.make(schema)\n\n  console.log(JSON.stringify(jsonSchema, null, 2))\n  /*\n  Output:\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"description\": \"a non empty string\",\n    \"title\": \"nonEmptyString\",\n    \"minLength\": 1\n  }\n  */\n  ```\n\n## 3.18.3\n\n### Patch Changes\n\n- [#5612](https://github.com/Effect-TS/effect/pull/5612) [`25fab81`](https://github.com/Effect-TS/effect/commit/25fab8147c8c58e637332cfd9e690f777898c813) Thanks @gcanti! - Fix JSON Schema generation with `topLevelReferenceStrategy: \"skip\"`, closes #5611\n\n  This patch fixes a bug that occurred when generating JSON Schemas with nested schemas that had identifiers, while using `topLevelReferenceStrategy: \"skip\"`.\n\n  Previously, the generator would still output `$ref` entries even though references were supposed to be skipped, leaving unresolved definitions.\n\n  **Before**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const A = Schema.Struct({ value: Schema.String }).annotations({\n    identifier: \"A\"\n  })\n  const B = Schema.Struct({ a: A }).annotations({ identifier: \"B\" })\n\n  const definitions = {}\n  console.log(\n    JSON.stringify(\n      JSONSchema.fromAST(B.ast, {\n        definitions,\n        topLevelReferenceStrategy: \"skip\"\n      }),\n      null,\n      2\n    )\n  )\n  /*\n  {\n    \"type\": \"object\",\n    \"required\": [\"a\"],\n    \"properties\": {\n      \"a\": {\n        \"$ref\": \"#/$defs/A\"\n      }\n    },\n    \"additionalProperties\": false\n  }\n  */\n  console.log(definitions)\n  /*\n  {\n    A: {\n      type: \"object\",\n      required: [\"value\"],\n      properties: { value: [Object] },\n      additionalProperties: false\n    }\n  }\n  */\n  ```\n\n  **After**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const A = Schema.Struct({ value: Schema.String }).annotations({\n    identifier: \"A\"\n  })\n  const B = Schema.Struct({ a: A }).annotations({ identifier: \"B\" })\n\n  const definitions = {}\n  console.log(\n    JSON.stringify(\n      JSONSchema.fromAST(B.ast, {\n        definitions,\n        topLevelReferenceStrategy: \"skip\"\n      }),\n      null,\n      2\n    )\n  )\n  /*\n  {\n    \"type\": \"object\",\n    \"required\": [\"a\"],\n    \"properties\": {\n      \"a\": {\n        \"type\": \"object\",\n        \"required\": [\"value\"],\n        \"properties\": {\n          \"value\": { \"type\": \"string\" }\n        },\n        \"additionalProperties\": false\n      }\n    },\n    \"additionalProperties\": false\n  }\n  */\n  console.log(definitions)\n  /*\n  {}\n  */\n  ```\n\n  Now schemas are correctly inlined, and no leftover `$ref` entries or unused definitions remain.\n\n## 3.18.2\n\n### Patch Changes\n\n- [#5598](https://github.com/Effect-TS/effect/pull/5598) [`8ba4757`](https://github.com/Effect-TS/effect/commit/8ba47576c75b8b91be4bf9c1dae13995b37018af) Thanks @cyberixae! - Fix Array Do documentation\n\n## 3.18.1\n\n### Patch Changes\n\n- [#5584](https://github.com/Effect-TS/effect/pull/5584) [`07802f7`](https://github.com/Effect-TS/effect/commit/07802f78fd410d800f0231129ee0866977399152) Thanks @indietyp! - Enable `console.group` use in `Logger.prettyFormat` when using Bun\n\n## 3.18.0\n\n### Minor Changes\n\n- [#5302](https://github.com/Effect-TS/effect/pull/5302) [`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa) Thanks @schickling! - Add experimental Graph module with comprehensive graph data structure support\n\n  This experimental module provides:\n  - Directed and undirected graph support\n  - Immutable and mutable graph variants\n  - Type-safe node and edge operations\n  - Graph algorithms: DFS, BFS, shortest paths, cycle detection, etc.\n\n  Example usage:\n\n  ```typescript\n  import { Graph } from \"effect\"\n\n  // Create a graph with mutations\n  const graph = Graph.directed<string, number>((mutable) => {\n    const nodeA = Graph.addNode(mutable, \"Node A\")\n    const nodeB = Graph.addNode(mutable, \"Node B\")\n    Graph.addEdge(mutable, nodeA, nodeB, 5)\n  })\n\n  console.log(\n    `Nodes: ${Graph.nodeCount(graph)}, Edges: ${Graph.edgeCount(graph)}`\n  )\n  ```\n\n- [#5302](https://github.com/Effect-TS/effect/pull/5302) [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137) Thanks @mikearnaldi! - Automatically set otel parent when present as external span\n\n- [#5302](https://github.com/Effect-TS/effect/pull/5302) [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c) Thanks @tim-smart! - add Effect.Semaphore.resize\n\n- [#5302](https://github.com/Effect-TS/effect/pull/5302) [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2) Thanks @mikearnaldi! - Introduce ReadonlyTag as the covariant side of a tag, enables:\n\n  ```ts\n  import type { Context } from \"effect\"\n  import { Effect } from \"effect\"\n\n  export class MyRequirement extends Effect.Service<MyRequirement>()(\n    \"MyRequirement\",\n    { succeed: () => 42 }\n  ) {}\n\n  export class MyUseCase extends Effect.Service<MyUseCase>()(\"MyUseCase\", {\n    dependencies: [MyRequirement.Default],\n    effect: Effect.gen(function* () {\n      const requirement = yield* MyRequirement\n      return Effect.fn(\"MyUseCase.execute\")(function* () {\n        return requirement()\n      })\n    })\n  }) {}\n\n  export function effectHandler<I, Args extends Array<any>, A, E, R>(\n    service: Context.ReadonlyTag<I, (...args: Args) => Effect.Effect<A, E, R>>\n  ) {\n    return Effect.fn(\"effectHandler\")(function* (...args: Args) {\n      const execute = yield* service\n      yield* execute(...args)\n    })\n  }\n\n  export const program = effectHandler(MyUseCase)\n  ```\n\n## 3.17.14\n\n### Patch Changes\n\n- [#5533](https://github.com/Effect-TS/effect/pull/5533) [`ea95998`](https://github.com/Effect-TS/effect/commit/ea95998de2a7613d844c42e67e7f5b16652c5000) Thanks @IMax153! - Preserve the precision of histogram boundary values\n\n## 3.17.13\n\n### Patch Changes\n\n- [#5462](https://github.com/Effect-TS/effect/pull/5462) [`51bfc78`](https://github.com/Effect-TS/effect/commit/51bfc78a7003e663f24941f7bc18485abf4caf15) Thanks @tim-smart! - ensure tracerLogger does not drop message items\n\n## 3.17.12\n\n### Patch Changes\n\n- [#5456](https://github.com/Effect-TS/effect/pull/5456) [`b359bdc`](https://github.com/Effect-TS/effect/commit/b359bdca4fe25bf0485d0f744c54ec3fed48af70) Thanks @tim-smart! - add preload options to LayerMap\n\n## 3.17.11\n\n### Patch Changes\n\n- [#5449](https://github.com/Effect-TS/effect/pull/5449) [`fb5e414`](https://github.com/Effect-TS/effect/commit/fb5e414943df05654db90952eb4f5339fc8cd9a1) Thanks @tim-smart! - Simplify Effect.raceAll implementation, ensure children fibers are awaited\n\n- [#5451](https://github.com/Effect-TS/effect/pull/5451) [`018363b`](https://github.com/Effect-TS/effect/commit/018363b9cbe3cdd553d59592cb24a0fc0fa47bdd) Thanks @mikearnaldi! - Fix Predicate.isIterable to allow strings\n\n## 3.17.10\n\n### Patch Changes\n\n- [#5368](https://github.com/Effect-TS/effect/pull/5368) [`3b26094`](https://github.com/Effect-TS/effect/commit/3b2609409ac1e8c6939d699584f00b1b99c47e2e) Thanks @gcanti! - ## Annotation Behavior\n\n  When you call `.annotations` on a schema, any identifier annotations that were previously set will now be removed. Identifiers are now always tied to the schema's `ast` reference (this was the intended behavior).\n\n  **Example**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.URL\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"$defs\": {\n      \"URL\": {\n        \"type\": \"string\",\n        \"description\": \"a string to be decoded into a URL\"\n      }\n    },\n    \"$ref\": \"#/$defs/URL\"\n  }\n  */\n\n  const annotated = Schema.URL.annotations({ description: \"description\" })\n\n  console.log(JSON.stringify(JSONSchema.make(annotated), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"description\": \"description\"\n  }\n  */\n  ```\n\n  ## OpenAPI 3.1 Compatibility\n\n  OpenAPI 3.1 does not allow `nullable: true`.\n  Instead, the schema will now correctly use `{ \"type\": \"null\" }` inside a union.\n\n  **Example**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.NullOr(Schema.String)\n\n  console.log(\n    JSON.stringify(\n      JSONSchema.fromAST(schema.ast, {\n        definitions: {},\n        target: \"openApi3.1\"\n      }),\n      null,\n      2\n    )\n  )\n  /*\n  {\n    \"anyOf\": [\n      {\n        \"type\": \"string\"\n      },\n      {\n        \"type\": \"null\"\n      }\n    ]\n  }\n  */\n  ```\n\n  ## Schema Description Deduplication\n\n  Previously, when a schema was reused, only the first description was kept.\n  Now, every property keeps its own description, even if the schema is reused.\n\n  **Example**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schemaWithAnIdentifier = Schema.String.annotations({\n    identifier: \"my-id\"\n  })\n\n  const schema = Schema.Struct({\n    a: schemaWithAnIdentifier.annotations({\n      description: \"a-description\"\n    }),\n    b: schemaWithAnIdentifier.annotations({\n      description: \"b-description\"\n    })\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [\n      \"a\",\n      \"b\"\n    ],\n    \"properties\": {\n      \"a\": {\n        \"type\": \"string\",\n        \"description\": \"a-description\"\n      },\n      \"b\": {\n        \"type\": \"string\",\n        \"description\": \"b-description\"\n      }\n    },\n    \"additionalProperties\": false\n  }\n  */\n  ```\n\n  ## Fragment Detection in Non-Refinement Schemas\n\n  This patch fixes the issue where fragments (e.g. `jsonSchema.format`) were not detected on non-refinement schemas.\n\n  **Example**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.UUID.pipe(\n    Schema.compose(Schema.String),\n    Schema.annotations({\n      identifier: \"UUID\",\n      title: \"title\",\n      description: \"description\",\n      jsonSchema: {\n        format: \"uuid\" // fragment\n      }\n    })\n  )\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"$defs\": {\n      \"UUID\": {\n        \"type\": \"string\",\n        \"description\": \"description\",\n        \"format\": \"uuid\",\n        \"pattern\": \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\",\n        \"title\": \"title\"\n      }\n    },\n    \"$ref\": \"#/$defs/UUID\"\n  }\n  */\n  ```\n\n  ## Nested Unions\n\n  Nested unions are no longer flattened. Instead, they remain as nested `anyOf` arrays.\n  This is fine because JSON Schema allows nested `anyOf`.\n\n  **Example**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Union(\n    Schema.NullOr(Schema.String),\n    Schema.Literal(\"a\", null)\n  )\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"anyOf\": [\n      {\n        \"anyOf\": [\n          {\n            \"type\": \"string\"\n          },\n          {\n            \"type\": \"null\"\n          }\n        ]\n      },\n      {\n        \"anyOf\": [\n          {\n            \"type\": \"string\",\n            \"enum\": [\n              \"a\"\n            ]\n          },\n          {\n            \"type\": \"null\"\n          }\n        ]\n      }\n    ]\n  }\n  */\n  ```\n\n  ## Refinements without `jsonSchema` annotation\n\n  Refinements that don't provide a `jsonSchema` annotation no longer cause errors.\n  They are simply ignored, so you can still generate a JSON Schema even when refinements can't easily be expressed.\n\n- [#5437](https://github.com/Effect-TS/effect/pull/5437) [`a33e491`](https://github.com/Effect-TS/effect/commit/a33e49153d944abd183fed93267fa7e52abae68b) Thanks @tim-smart! - ensure Effect.promise captures span on defect\n\n## 3.17.9\n\n### Patch Changes\n\n- [#5422](https://github.com/Effect-TS/effect/pull/5422) [`0271f14`](https://github.com/Effect-TS/effect/commit/0271f1450c0c861f589e26ff534a73dea7ea97b7) Thanks @gcanti! - backport `formatUnknown` from v4\n\n## 3.17.8\n\n### Patch Changes\n\n- [#5407](https://github.com/Effect-TS/effect/pull/5407) [`84bc300`](https://github.com/Effect-TS/effect/commit/84bc3003b42ad51210e9e1248efd04c5d0e3dd1e) Thanks @thewilkybarkid! - Fix Schema.Defect when seeing a null-prototype object\n\n## 3.17.7\n\n### Patch Changes\n\n- [#5358](https://github.com/Effect-TS/effect/pull/5358) [`a949539`](https://github.com/Effect-TS/effect/commit/a94953971c2e908890dfda00f8560d317306c328) Thanks @tim-smart! - expose RcMap.has api\n\n## 3.17.6\n\n### Patch Changes\n\n- [#5322](https://github.com/Effect-TS/effect/pull/5322) [`f187941`](https://github.com/Effect-TS/effect/commit/f187941946c675713b3539fc4d5480123037563a) Thanks @beezee! - Use non-greedy matching for Schema.String in Schema.TemplateLiteralParser\n\n## 3.17.5\n\n### Patch Changes\n\n- [#5315](https://github.com/Effect-TS/effect/pull/5315) [`5f98388`](https://github.com/Effect-TS/effect/commit/5f983881754fce7dc0e2d752145f3b865af27958) Thanks @patroza! - improve provide/merge apis to support readonly array inputs.\n\n## 3.17.4\n\n### Patch Changes\n\n- [#5306](https://github.com/Effect-TS/effect/pull/5306) [`7d7c55d`](https://github.com/Effect-TS/effect/commit/7d7c55dadeea2f9de16e60abff124085733e1953) Thanks @leonitousconforti! - Align RcMap.keys return type with internal signature\n\n## 3.17.3\n\n### Patch Changes\n\n- [#5275](https://github.com/Effect-TS/effect/pull/5275) [`3504555`](https://github.com/Effect-TS/effect/commit/35045558e7cac19c888fe677dda93c4741c7f8a8) Thanks @taylornz! - fix DateTime.makeZoned handling of DST transitions\n\n- [#5282](https://github.com/Effect-TS/effect/pull/5282) [`f6c7ca7`](https://github.com/Effect-TS/effect/commit/f6c7ca752fc9de5f7a2a6c439bbc6cca06566357) Thanks @beezee! - Improve inference on Metric.trackSuccessWith for use in Effect.pipe(...)\n\n- [#5275](https://github.com/Effect-TS/effect/pull/5275) [`3504555`](https://github.com/Effect-TS/effect/commit/35045558e7cac19c888fe677dda93c4741c7f8a8) Thanks @taylornz! - add DateTime.Disambiguation for handling DST edge cases\n\n  Added four disambiguation strategies to `DateTime.Zoned` constructors for handling DST edge cases:\n  - `'compatible'` - Maintains backward compatibility\n  - `'earlier'` - Choose earlier time during ambiguous periods (default)\n  - `'later'` - Choose later time during ambiguous periods\n  - `'reject'` - Throw error for ambiguous times\n\n## 3.17.2\n\n### Patch Changes\n\n- [#5277](https://github.com/Effect-TS/effect/pull/5277) [`6309e0a`](https://github.com/Effect-TS/effect/commit/6309e0abe16e82da8d0091fff1b9962fd9eeb585) Thanks @tim-smart! - Fix Layer.mock dual detection\n\n## 3.17.1\n\n### Patch Changes\n\n- [#5262](https://github.com/Effect-TS/effect/pull/5262) [`5a0f4f1`](https://github.com/Effect-TS/effect/commit/5a0f4f176687a39d9fa46bb894bb7ac3175b0e87) Thanks @tim-smart! - remove recursion from Sink fold loop\n\n## 3.17.0\n\n### Minor Changes\n\n- [#4949](https://github.com/Effect-TS/effect/pull/4949) [`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9) Thanks @fubhy! - Added `Random.fixed` to create a version of the `Random` service with fixed\n  values for testing.\n\n- [#4949](https://github.com/Effect-TS/effect/pull/4949) [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104) Thanks @dmaretskyi! - Add `Struct.entries` function\n\n- [#4949](https://github.com/Effect-TS/effect/pull/4949) [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63) Thanks @f15u! - Add `Layer.mock`\n\n  Creates a mock layer for testing purposes. You can provide a partial\n  implementation of the service, and any methods not provided will\n  throw an `UnimplementedError` defect when called.\n\n  ```ts\n  import { Context, Effect, Layer } from \"effect\"\n\n  class MyService extends Context.Tag(\"MyService\")<\n    MyService,\n    {\n      one: Effect.Effect<number>\n      two(): Effect.Effect<number>\n    }\n  >() {}\n\n  const MyServiceTest = Layer.mock(MyService, {\n    two: () => Effect.succeed(2)\n  })\n  ```\n\n- [#4949](https://github.com/Effect-TS/effect/pull/4949) [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c) Thanks @KhraksMamtsov! - Schedule output has been added into `CurrentIterationMetadata`\n\n- [#4949](https://github.com/Effect-TS/effect/pull/4949) [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989) Thanks @mikearnaldi! - Remove global state index by version, make version mismatch a warning message\n\n- [#4949](https://github.com/Effect-TS/effect/pull/4949) [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636) Thanks @devinjameson! - Array: add findFirstWithIndex function\n\n- [#4949](https://github.com/Effect-TS/effect/pull/4949) [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2) Thanks @vinassefranche! - Add HashMap.countBy\n\n  ```ts\n  import { HashMap } from \"effect\"\n\n  const map = HashMap.make([1, \"a\"], [2, \"b\"], [3, \"c\"])\n  const result = HashMap.countBy(map, (_v, key) => key % 2 === 1)\n  console.log(result) // 2\n  ```\n\n- [#4949](https://github.com/Effect-TS/effect/pull/4949) [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d) Thanks @tim-smart! - add Effect.ensure{Success,Error,Requirements}Type, for constraining Effect types\n\n## 3.16.17\n\n### Patch Changes\n\n- [#5246](https://github.com/Effect-TS/effect/pull/5246) [`aaa6ad0`](https://github.com/Effect-TS/effect/commit/aaa6ad0673f843a27954fd92821961cce33941ad) Thanks @mikearnaldi! - Copy over apply, bind, call into service proxy\n\n- [#5158](https://github.com/Effect-TS/effect/pull/5158) [`5b74ea5`](https://github.com/Effect-TS/effect/commit/5b74ea5e5862742e2fb60feefb765bc8681171f4) Thanks @cyberixae! - Clarify Tuple length requirements\n\n## 3.16.16\n\n### Patch Changes\n\n- [#5224](https://github.com/Effect-TS/effect/pull/5224) [`127e602`](https://github.com/Effect-TS/effect/commit/127e602ee647839198f44d19cff7d11f6e4b473b) Thanks @tim-smart! - prevent fiber leak when Stream.toAsyncIterable returns early\n\n## 3.16.15\n\n### Patch Changes\n\n- [#5222](https://github.com/Effect-TS/effect/pull/5222) [`15df9bf`](https://github.com/Effect-TS/effect/commit/15df9bf0c7a11e775c04e69516e47c5094146d55) Thanks @gcanti! - Schema.attachPropertySignature: simplify signature and fix parameter type to use Schema instead of SchemaClass\n\n## 3.16.14\n\n### Patch Changes\n\n- [#5213](https://github.com/Effect-TS/effect/pull/5213) [`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec) Thanks @gcanti! - Fix incorrect schema ID annotation in `Schema.lessThanOrEqualToDate`, closes #5212\n\n- [#5192](https://github.com/Effect-TS/effect/pull/5192) [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38) Thanks @nikelborm! - Updated deprecated OTel Resource attributes names and values.\n\n  Many of the attributes have undergone the process of deprecation not once, but twice. Most of the constants holding attribute names have been renamed. These are minor changes.\n\n  Additionally, there were numerous changes to the attribute keys themselves. These changes can be considered major.\n\n  In the `@opentelemetry/semantic-conventions` package, new attributes having ongoing discussion about them are going through a process called incubation, until a consensus about their necessity and form is reached. Otel team [recommends](https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv) devs to copy them directly into their code. Luckily, it's not necessary because all of the new attribute names and values came out of this process (some of them were changed again) and are now considered stable.\n\n  ## Reasoning for minor version bump\n\n  | Package                    | Major attribute changes                                                       | Major value changes               |\n  | -------------------------- | ----------------------------------------------------------------------------- | --------------------------------- |\n  | Clickhouse client          | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             |                                   |\n  | MsSQL client               | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             | `mssql` -> `microsoft.sql_server` |\n  | MySQL client               | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             |                                   |\n  | Pg client                  | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             |                                   |\n  | Bun SQLite client          | `db.system` -> `db.system.name`                                               |                                   |\n  | Node SQLite client         | `db.system` -> `db.system.name`                                               |                                   |\n  | React.Native SQLite client | `db.system` -> `db.system.name`                                               |                                   |\n  | Wasm SQLite client         | `db.system` -> `db.system.name`                                               |                                   |\n  | SQLite Do client           | `db.system` -> `db.system.name`                                               |                                   |\n  | LibSQL client              | `db.system` -> `db.system.name`                                               |                                   |\n  | D1 client                  | `db.system` -> `db.system.name`                                               |                                   |\n  | Kysely client              | `db.statement` -> `db.query.text`                                             |                                   |\n  | @effect/sql                | `db.statement` -> `db.query.text` <br/> `db.operation` -> `db.operation.name` |                                   |\n\n- [#5211](https://github.com/Effect-TS/effect/pull/5211) [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48) Thanks @mattiamanzati! - Removed some unnecessary single-arg pipe calls\n\n## 3.16.13\n\n### Patch Changes\n\n- [#5097](https://github.com/Effect-TS/effect/pull/5097) [`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7) Thanks @tim-smart! - remove completion helper overload from Effect.catchTag, to fix Effect.fn inference\n\n- [#5157](https://github.com/Effect-TS/effect/pull/5157) [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db) Thanks @cyberixae! - Clarify Array rotate example\n\n## 3.16.12\n\n### Patch Changes\n\n- [#5149](https://github.com/Effect-TS/effect/pull/5149) [`905da99`](https://github.com/Effect-TS/effect/commit/905da996aad665057b4ca6dba1a4af44fb8835bd) Thanks @milkyskies! - Fix `$match` to disallow invalid `_tag` keys in `TaggedEnum` handler objects.\n\n## 3.16.11\n\n### Patch Changes\n\n- [#5127](https://github.com/Effect-TS/effect/pull/5127) [`99590a6`](https://github.com/Effect-TS/effect/commit/99590a6ca9128eb1ede265b6670b655311995614) Thanks @tim-smart! - fix DateTime zone check to includes zones without \":\"\n\n- [#5123](https://github.com/Effect-TS/effect/pull/5123) [`6c3e24c`](https://github.com/Effect-TS/effect/commit/6c3e24c2308f7d4a29b8f4270ab81bca22ac6bb4) Thanks @gcanti! - Schema.equivalence: handle non-array and non-record inputs\n\n## 3.16.10\n\n### Patch Changes\n\n- [#5100](https://github.com/Effect-TS/effect/pull/5100) [`faad30e`](https://github.com/Effect-TS/effect/commit/faad30ec8742916be59f9db642d0fc98225b636c) Thanks @tim-smart! - relax Predicate.compose constraint on second refinement\n\n## 3.16.9\n\n### Patch Changes\n\n- [#5081](https://github.com/Effect-TS/effect/pull/5081) [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07) Thanks @tim-smart! - expose Stream.provideSomeContext\n\n- [#5082](https://github.com/Effect-TS/effect/pull/5082) [`c23d25c`](https://github.com/Effect-TS/effect/commit/c23d25c3e7c541f1f63b28484d8c461d86c67e99) Thanks @tim-smart! - fix Effect.filterOrFail return type inference\n\n## 3.16.8\n\n### Patch Changes\n\n- [#5047](https://github.com/Effect-TS/effect/pull/5047) [`8cb98d5`](https://github.com/Effect-TS/effect/commit/8cb98d53e68330228287ce2a2e0d8a4c86bcab3b) Thanks @tim-smart! - ensure Stream.toReadableStream ignores empty chunks\n\n- [#5046](https://github.com/Effect-TS/effect/pull/5046) [`db2dd3c`](https://github.com/Effect-TS/effect/commit/db2dd3c3a8a77d791eae19e66153527e1cde4e6e) Thanks @tim-smart! - ignore ReadableStream defect in bun due to controller bug\n\n## 3.16.7\n\n### Patch Changes\n\n- [#5033](https://github.com/Effect-TS/effect/pull/5033) [`1bb0d8a`](https://github.com/Effect-TS/effect/commit/1bb0d8ab96782e99434356266b38251554ea0294) Thanks @tim-smart! - ensure DateTime.make interprets strings without zone as UTC\n\n## 3.16.6\n\n### Patch Changes\n\n- [#5026](https://github.com/Effect-TS/effect/pull/5026) [`a5f7595`](https://github.com/Effect-TS/effect/commit/a5f75956ef9a15a83c416517ef493f0ee2f5ee8a) Thanks @KhraksMamtsov! - Add missing type variances\n\n- [#5031](https://github.com/Effect-TS/effect/pull/5031) [`a02470c`](https://github.com/Effect-TS/effect/commit/a02470c75579e91525a25adb3f21b3650d042fdd) Thanks @KhraksMamtsov! - Fix Context.add & Context.make signatures\n\n- [#5003](https://github.com/Effect-TS/effect/pull/5003) [`f891d45`](https://github.com/Effect-TS/effect/commit/f891d45adffdafd3f94a2eca23faa354e3a409a8) Thanks @beezee! - Ensure binding `__proto__` to lexical scope in do notation is preserved by `bind` and `let`\n\n## 3.16.5\n\n### Patch Changes\n\n- [#5008](https://github.com/Effect-TS/effect/pull/5008) [`bf418ef`](https://github.com/Effect-TS/effect/commit/bf418ef14a0f2ec965535793d5cea8fa8ba177ac) Thanks @jdharrisnz! - Record.findFirst: Accept ReadonlyRecord type input and optimise the loop\n\n## 3.16.4\n\n### Patch Changes\n\n- [#4994](https://github.com/Effect-TS/effect/pull/4994) [`74ab9a0`](https://github.com/Effect-TS/effect/commit/74ab9a0a9e16d6e019369d256e1e24175c8bc3f3) Thanks @tim-smart! - don't inherit interruption flag in Effect.addFinalizer\n\n- [#4986](https://github.com/Effect-TS/effect/pull/4986) [`770008e`](https://github.com/Effect-TS/effect/commit/770008eca3aad2899a2ed951236e575793294b28) Thanks @tim-smart! - ensure Cause.YieldableError extends Error\n\n## 3.16.3\n\n### Patch Changes\n\n- [#4952](https://github.com/Effect-TS/effect/pull/4952) [`87722fc`](https://github.com/Effect-TS/effect/commit/87722fce693a9b49284bbddbf82d30714c688261) Thanks @tim-smart! - improve Effect.catchTag auto-completion\n\n- [#4950](https://github.com/Effect-TS/effect/pull/4950) [`36217ee`](https://github.com/Effect-TS/effect/commit/36217eeb1337edd9ac3f9a635b80a6385d22ae8f) Thanks @tim-smart! - remove `this` type propagation from Effect.fn\n\n## 3.16.2\n\n### Patch Changes\n\n- [#4943](https://github.com/Effect-TS/effect/pull/4943) [`0ddf148`](https://github.com/Effect-TS/effect/commit/0ddf148a247aa87af043d276b8453a714a400897) Thanks @gcanti! - relax `Schema.brand` constraint, closes #4942\n\n## 3.16.1\n\n### Patch Changes\n\n- [#4936](https://github.com/Effect-TS/effect/pull/4936) [`71174d0`](https://github.com/Effect-TS/effect/commit/71174d09691314a9b6b66189e456fd21e3eb6543) Thanks @mattiamanzati! - Escape JSON Schema $id for empty struct\n\n- [#4937](https://github.com/Effect-TS/effect/pull/4937) [`d615e6e`](https://github.com/Effect-TS/effect/commit/d615e6e5b944f6fd5e627e31752c7ca7e4e1c17d) Thanks @tim-smart! - adjust ExecutionPlan `provides` & `requirements` types\n\n## 3.16.0\n\n### Minor Changes\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`ee0bd5d`](https://github.com/Effect-TS/effect/commit/ee0bd5d24864752c54cb359f67a67dd903971ec4) Thanks @KhraksMamtsov! - `Schedule.CurrentIterationMetadata` has been added\n\n  ```ts\n  import { Effect, Schedule } from \"effect\"\n\n  Effect.gen(function* () {\n    const currentIterationMetadata = yield* Schedule.CurrentIterationMetadata\n    //     ^? Schedule.IterationMetadata\n\n    console.log(currentIterationMetadata)\n  }).pipe(Effect.repeat(Schedule.recurs(2)))\n  // {\n  //   elapsed: Duration.zero,\n  //   elapsedSincePrevious: Duration.zero,\n  //   input: undefined,\n  //   now: 0,\n  //   recurrence: 0,\n  //   start: 0\n  // }\n  // {\n  //   elapsed: Duration.zero,\n  //   elapsedSincePrevious: Duration.zero,\n  //   input: undefined,\n  //   now: 0,\n  //   recurrence: 1,\n  //   start: 0\n  // }\n  // {\n  //   elapsed: Duration.zero,\n  //   elapsedSincePrevious: Duration.zero,\n  //   input: undefined,\n  //   now: 0,\n  //   recurrence: 2,\n  //   start: 0\n  // }\n\n  Effect.gen(function* () {\n    const currentIterationMetadata = yield* Schedule.CurrentIterationMetadata\n\n    console.log(currentIterationMetadata)\n  }).pipe(\n    Effect.schedule(\n      Schedule.intersect(Schedule.fibonacci(\"1 second\"), Schedule.recurs(3))\n    )\n  )\n  // {\n  //   elapsed: Duration.zero,\n  //   elapsedSincePrevious: Duration.zero,\n  //   recurrence: 1,\n  //   input: undefined,\n  //   now: 0,\n  //   start: 0\n  // },\n  // {\n  //   elapsed: Duration.seconds(1),\n  //   elapsedSincePrevious: Duration.seconds(1),\n  //   recurrence: 2,\n  //   input: undefined,\n  //   now: 1000,\n  //   start: 0\n  // },\n  // {\n  //   elapsed: Duration.seconds(2),\n  //   elapsedSincePrevious: Duration.seconds(1),\n  //   recurrence: 3,\n  //   input: undefined,\n  //   now: 2000,\n  //   start: 0\n  // }\n  ```\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`5189800`](https://github.com/Effect-TS/effect/commit/51898004e11766b8cf6d95e960b636f6d5db79ec) Thanks @vinassefranche! - Add HashMap.hasBy helper\n\n  ```ts\n  import { HashMap } from \"effect\"\n\n  const hm = HashMap.make([1, \"a\"])\n  HashMap.hasBy(hm, (value, key) => value === \"a\" && key === 1) // -> true\n  HashMap.hasBy(hm, (value) => value === \"b\") // -> false\n  ```\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`58bfeaa`](https://github.com/Effect-TS/effect/commit/58bfeaa64ded8c88f772b184311c0c0dbac10960) Thanks @jrudder! - Add round and sumAll to BigDecimal\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`194d748`](https://github.com/Effect-TS/effect/commit/194d7486943f56f3267ef415395ac220a4b3e634) Thanks @tim-smart! - add ExecutionPlan module\n\n  A `ExecutionPlan` can be used with `Effect.withExecutionPlan` or `Stream.withExecutionPlan`, allowing you to provide different resources for each step of execution until the effect succeeds or the plan is exhausted.\n\n  ```ts\n  import { type AiLanguageModel } from \"@effect/ai\"\n  import type { Layer } from \"effect\"\n  import { Effect, ExecutionPlan, Schedule } from \"effect\"\n\n  declare const layerBad: Layer.Layer<AiLanguageModel.AiLanguageModel>\n  declare const layerGood: Layer.Layer<AiLanguageModel.AiLanguageModel>\n\n  const ThePlan = ExecutionPlan.make(\n    {\n      // First try with the bad layer 2 times with a 3 second delay between attempts\n      provide: layerBad,\n      attempts: 2,\n      schedule: Schedule.spaced(3000)\n    },\n    // Then try with the bad layer 3 times with a 1 second delay between attempts\n    {\n      provide: layerBad,\n      attempts: 3,\n      schedule: Schedule.spaced(1000)\n    },\n    // Finally try with the good layer.\n    //\n    // If `attempts` is omitted, the plan will only attempt once, unless a schedule is provided.\n    {\n      provide: layerGood\n    }\n  )\n\n  declare const effect: Effect.Effect<\n    void,\n    never,\n    AiLanguageModel.AiLanguageModel\n  >\n  const withPlan: Effect.Effect<void> = Effect.withExecutionPlan(\n    effect,\n    ThePlan\n  )\n  ```\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`918c9ea`](https://github.com/Effect-TS/effect/commit/918c9ea1a57facb154f0fb26792021f337054dee) Thanks @thewilkybarkid! - Add Array.removeOption and Chunk.removeOption\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`9198e6f`](https://github.com/Effect-TS/effect/commit/9198e6fcc1a3ff4fefb3363004de558d8de01f40) Thanks @TylorS! - Add parameter support for Effect.Service\n\n  This allows you to pass parameters to the `effect` & `scoped` Effect.Service\n  constructors, which will also be reflected in the `.Default` layer.\n\n  ```ts\n  import type { Layer } from \"effect\"\n  import { Effect } from \"effect\"\n\n  class NumberService extends Effect.Service<NumberService>()(\"NumberService\", {\n    // You can now pass a function to the `effect` and `scoped` constructors\n    effect: Effect.fn(function* (input: number) {\n      return {\n        get: Effect.succeed(`The number is: ${input}`)\n      } as const\n    })\n  }) {}\n\n  // Pass the arguments to the `Default` layer\n  const CoolNumberServiceLayer: Layer.Layer<NumberService> =\n    NumberService.Default(6942)\n  ```\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`2a370bf`](https://github.com/Effect-TS/effect/commit/2a370bf625fdeede5659721468eb0d527e403279) Thanks @vinassefranche! - Add `Iterable.countBy` and `Array.countBy`\n\n  ```ts\n  import { Array, Iterable } from \"effect\"\n\n  const resultArray = Array.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0)\n  console.log(resultArray) // 2\n\n  const resultIterable = resultIterable.countBy(\n    [1, 2, 3, 4, 5],\n    (n) => n % 2 === 0\n  )\n  console.log(resultIterable) // 2\n  ```\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`58ccb91`](https://github.com/Effect-TS/effect/commit/58ccb91328c8df5d49808b673738bc09df355201) Thanks @KhraksMamtsov! - The `Config.port` and `Config.branded` functions have been added.\n\n  ```ts\n  import { Brand, Config } from \"effect\"\n\n  type DbPort = Brand.Branded<number, \"DbPort\">\n  const DbPort = Brand.nominal<DbPort>()\n\n  const dbPort: Config.Config<DbPort> = Config.branded(\n    Config.port(\"DB_PORT\"),\n    DbPort\n  )\n  ```\n\n  ```ts\n  import { Brand, Config } from \"effect\"\n\n  type Port = Brand.Branded<number, \"Port\">\n  const Port = Brand.refined<Port>(\n    (num) =>\n      !Number.isNaN(num) && Number.isInteger(num) && num >= 1 && num <= 65535,\n    (n) => Brand.error(`Expected ${n} to be an TCP port`)\n  )\n\n  const dbPort: Config.Config<Port> = Config.number(\"DB_PORT\").pipe(\n    Config.branded(Port)\n  )\n  ```\n\n- [#4891](https://github.com/Effect-TS/effect/pull/4891) [`fd47834`](https://github.com/Effect-TS/effect/commit/fd478348203fa89462b0a1d067ce4de034353df4) Thanks @tim-smart! - return a proxy Layer from LayerMap service\n\n  The new usage is:\n\n  ```ts\n  import { NodeRuntime } from \"@effect/platform-node\"\n  import { Context, Effect, FiberRef, Layer, LayerMap } from \"effect\"\n\n  class Greeter extends Context.Tag(\"Greeter\")<\n    Greeter,\n    {\n      greet: Effect.Effect<string>\n    }\n  >() {}\n\n  // create a service that wraps a LayerMap\n  class GreeterMap extends LayerMap.Service<GreeterMap>()(\"GreeterMap\", {\n    // define the lookup function for the layer map\n    //\n    // The returned Layer will be used to provide the Greeter service for the\n    // given name.\n    lookup: (name: string) =>\n      Layer.succeed(Greeter, {\n        greet: Effect.succeed(`Hello, ${name}!`)\n      }),\n\n    // If a layer is not used for a certain amount of time, it can be removed\n    idleTimeToLive: \"5 seconds\",\n\n    // Supply the dependencies for the layers in the LayerMap\n    dependencies: []\n  }) {}\n\n  // usage\n  const program: Effect.Effect<void, never, GreeterMap> = Effect.gen(\n    function* () {\n      // access and use the Greeter service\n      const greeter = yield* Greeter\n      yield* Effect.log(yield* greeter.greet)\n    }\n  ).pipe(\n    // use the GreeterMap service to provide a variant of the Greeter service\n    Effect.provide(GreeterMap.get(\"John\"))\n  )\n\n  // run the program\n  program.pipe(Effect.provide(GreeterMap.Default), NodeRuntime.runMain)\n  ```\n\n## 3.15.5\n\n### Patch Changes\n\n- [#4924](https://github.com/Effect-TS/effect/pull/4924) [`cc5bb2b`](https://github.com/Effect-TS/effect/commit/cc5bb2b918a9450a975f702dabcea891bda382cb) Thanks @KhraksMamtsov! - Fix type inference for Effect suptypes in NonGen case\n\n## 3.15.4\n\n### Patch Changes\n\n- [#4869](https://github.com/Effect-TS/effect/pull/4869) [`f570554`](https://github.com/Effect-TS/effect/commit/f57055459524587b041340577dad85476bb35f81) Thanks @IGassmann! - Fix summary metric’s min/max values when no samples\n\n- [#4917](https://github.com/Effect-TS/effect/pull/4917) [`78047e8`](https://github.com/Effect-TS/effect/commit/78047e8dfc8005b66f87afe50bb95981fea51561) Thanks @KhraksMamtsov! - Fix Effect.fn inference in case of use with pipe functions\n\n## 3.15.3\n\n### Patch Changes\n\n- [#4907](https://github.com/Effect-TS/effect/pull/4907) [`4577f54`](https://github.com/Effect-TS/effect/commit/4577f548d67273e576cdde423bdd34a4b910766a) Thanks @mattiamanzati! - Escape JSON-pointers\n\n## 3.15.2\n\n### Patch Changes\n\n- [#4659](https://github.com/Effect-TS/effect/pull/4659) [`b8722b8`](https://github.com/Effect-TS/effect/commit/b8722b817e2306fe8c8245f3f9e32d85b824b961) Thanks @KhraksMamtsov! - - The `HashMap.has/get` family has become more type-safe.\n  - Fix the related type errors in TestAnnotationsMap.ts.\n\n## 3.15.1\n\n### Patch Changes\n\n- [#4870](https://github.com/Effect-TS/effect/pull/4870) [`787ce70`](https://github.com/Effect-TS/effect/commit/787ce7042e35b657963473c6efe47752868cd811) Thanks @tim-smart! - ensure generic refinements work with Effect.filterOr\\*\n\n- [#4857](https://github.com/Effect-TS/effect/pull/4857) [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348) Thanks @tim-smart! - preserve explicit `this` in Effect.fn apis\n\n- [#4857](https://github.com/Effect-TS/effect/pull/4857) [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348) Thanks @tim-smart! - use span name as function name in Effect.fn\n\n## 3.15.0\n\n### Minor Changes\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`c654595`](https://github.com/Effect-TS/effect/commit/c65459587b51da140b78098e81fdbfece65d53e2) Thanks @tim-smart! - Add Layer.setRandom, for over-riding the default Random service\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`d9f5dea`](https://github.com/Effect-TS/effect/commit/d9f5deae0f02f5de2b9fcb1cca8b142ba4bc2bba) Thanks @KhraksMamtsov! - `Brand.unbranded` getter has been added\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`49aa723`](https://github.com/Effect-TS/effect/commit/49aa7236a15e13f818c86edbca08c4af67c8dfaf) Thanks @titouancreach! - Add Either.transposeMapOption\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`74c14d0`](https://github.com/Effect-TS/effect/commit/74c14d01d0cb48cf517a1b6e29a373a96ed0ff5b) Thanks @vinassefranche! - Add Record.findFirst\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`e4f49b6`](https://github.com/Effect-TS/effect/commit/e4f49b66857e01b74ab6a9a0bc7132f44cd04cbb) Thanks @KhraksMamtsov! - Default `never` type has been added to `MutableHasMap.empty` & `MutableList.empty` ctors\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`6f02224`](https://github.com/Effect-TS/effect/commit/6f02224b3fc46a682ad2defb1a260841956c6780) Thanks @tim-smart! - add Stream.toAsyncIterable\\* apis\n\n  ```ts\n  import { Stream } from \"effect\"\n\n  // Will print:\n  // 1\n  // 2\n  // 3\n  const stream = Stream.make(1, 2, 3)\n  for await (const result of Stream.toAsyncIterable(stream)) {\n    console.log(result)\n  }\n  ```\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`1dcfd41`](https://github.com/Effect-TS/effect/commit/1dcfd41ff96abd706901293a00c1893cb29dd8fd) Thanks @tim-smart! - improve Effect.filter\\* types to exclude candidates in fallback functions\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`b21ab16`](https://github.com/Effect-TS/effect/commit/b21ab16b6f773e7ec4369db4e752c35e719f7870) Thanks @KhraksMamtsov! - Simplified the creation of pipeable classes.\n\n  ```ts\n  class MyClass extends Pipeable.Class() {\n    constructor(public a: number) {\n      super()\n    }\n    methodA() {\n      return this.a\n    }\n  }\n  console.log(new MyClass(2).pipe((x) => x.methodA())) // 2\n  ```\n\n  ```ts\n  class A {\n    constructor(public a: number) {}\n    methodA() {\n      return this.a\n    }\n  }\n  class B extends Pipeable.Class(A) {\n    constructor(private b: string) {\n      super(b.length)\n    }\n    methodB() {\n      return [this.b, this.methodA()]\n    }\n  }\n  console.log(new B(\"pipe\").pipe((x) => x.methodB())) // ['pipe', 4]\n  ```\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`fcf1822`](https://github.com/Effect-TS/effect/commit/fcf1822f98fcda60351d64e9d2c2c13563d7e6db) Thanks @KhraksMamtsov! - property `message: string` has been added to `ConfigError.And` & `Or` members\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`0061dd1`](https://github.com/Effect-TS/effect/commit/0061dd140740165e91569a684cce27a77b23229e) Thanks @tim-smart! - allow catching multiple different tags in Effect.catchTag\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`8421e6e`](https://github.com/Effect-TS/effect/commit/8421e6e49332bca8f96f482dfd48680e238b3a89) Thanks @mlegenhausen! - Expose `Cause.isTimeoutException`\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`fa10f56`](https://github.com/Effect-TS/effect/commit/fa10f56b96bd9af070ba99ebc3279aa93954261e) Thanks @thewilkybarkid! - Support multiple values in Function.apply\n\n## 3.14.22\n\n### Patch Changes\n\n- [#4847](https://github.com/Effect-TS/effect/pull/4847) [`24a9ebb`](https://github.com/Effect-TS/effect/commit/24a9ebbb5af598f0bfd6ecc45307e528043fe011) Thanks @gcanti! - Schema: TaggedError no longer crashes when the `message` field is explicitly defined.\n\n  If you define a `message` field in your schema, `TaggedError` will no longer add its own `message` getter. This avoids a stack overflow caused by infinite recursion.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  class Todo extends Schema.TaggedError<Todo>()(\"Todo\", {\n    message: Schema.optional(Schema.String)\n  }) {}\n\n  // ❌ Throws \"Maximum call stack size exceeded\"\n  console.log(Todo.make({}))\n  ```\n\n  After\n\n  ```ts\n  // ✅ Works correctly\n  console.log(Todo.make({}))\n  ```\n\n## 3.14.21\n\n### Patch Changes\n\n- [#4837](https://github.com/Effect-TS/effect/pull/4837) [`2f3b7d4`](https://github.com/Effect-TS/effect/commit/2f3b7d4e1fa1ef8790b0ca4da22eb88872ee31df) Thanks @tim-smart! - fix Mailbox.fromStream\n\n## 3.14.20\n\n### Patch Changes\n\n- [#4832](https://github.com/Effect-TS/effect/pull/4832) [`17e2f30`](https://github.com/Effect-TS/effect/commit/17e2f3091408cf0fca9414d4af3bdf7b2765b378) Thanks @gcanti! - JSONSchema: respect annotations on declarations.\n\n  Previously, annotations added with `.annotations(...)` on `Schema.declare(...)` were not included in the generated JSON Schema output.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  class MyType {}\n\n  const schema = Schema.declare<MyType>((x) => x instanceof MyType, {\n    jsonSchema: {\n      type: \"my-type\"\n    }\n  }).annotations({\n    title: \"My Title\",\n    description: \"My Description\"\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"my-type\"\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  class MyType {}\n\n  const schema = Schema.declare<MyType>((x) => x instanceof MyType, {\n    jsonSchema: {\n      type: \"my-type\"\n    }\n  }).annotations({\n    title: \"My Title\",\n    description: \"My Description\"\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"description\": \"My Description\",\n    \"title\": \"My Title\",\n    \"type\": \"my-type\"\n  }\n  */\n  ```\n\n## 3.14.19\n\n### Patch Changes\n\n- [#4822](https://github.com/Effect-TS/effect/pull/4822) [`056a910`](https://github.com/Effect-TS/effect/commit/056a910d0a0b8b00b0dc9df4a070466b2b5c2f6c) Thanks @KhraksMamtsov! - fix `Layer.discard` jsdoc\n\n- [#4816](https://github.com/Effect-TS/effect/pull/4816) [`3273d57`](https://github.com/Effect-TS/effect/commit/3273d572c2b3175a842677f19efeea4cd65ab016) Thanks @mikearnaldi! - Fix captureStackTrace for bun\n\n## 3.14.18\n\n### Patch Changes\n\n- [#4809](https://github.com/Effect-TS/effect/pull/4809) [`b1164d4`](https://github.com/Effect-TS/effect/commit/b1164d49a1dfdf299e9971367b6fc6be4df0ddff) Thanks @tim-smart! - fix refinement narrowing in Match\n\n## 3.14.17\n\n### Patch Changes\n\n- [#4806](https://github.com/Effect-TS/effect/pull/4806) [`0b54681`](https://github.com/Effect-TS/effect/commit/0b54681cd89245e211d8f49272be0f1bf2f81813) Thanks @thewilkybarkid! - Match the JS API for locale arguments\n\n- [#4805](https://github.com/Effect-TS/effect/pull/4805) [`41a59d5`](https://github.com/Effect-TS/effect/commit/41a59d5916a296b12b0d5ead9e859e05f40b4cce) Thanks @mikearnaldi! - Implement stack cleaning for Bun\n\n## 3.14.16\n\n### Patch Changes\n\n- [#4800](https://github.com/Effect-TS/effect/pull/4800) [`ee14444`](https://github.com/Effect-TS/effect/commit/ee144441021ec77039e43396eaf90714687bb495) Thanks @tim-smart! - improve Match refinement resolution\n\n## 3.14.15\n\n### Patch Changes\n\n- [#4798](https://github.com/Effect-TS/effect/pull/4798) [`239cc99`](https://github.com/Effect-TS/effect/commit/239cc995ce645946210a3c3d2cb52bd3547c0687) Thanks @gcanti! - Schema: respect custom constructors in `make` for `Schema.Class`, closes #4797\n\n  Previously, the `make` method did not support custom constructors defined using `Schema.Class` or `Schema.TaggedError`, resulting in type errors when passing custom constructor arguments.\n\n  This update ensures that `make` now correctly uses the class constructor, allowing custom parameters and initialization logic.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  class MyError extends Schema.TaggedError<MyError>()(\"MyError\", {\n    message: Schema.String\n  }) {\n    constructor({ a, b }: { a: string; b: string }) {\n      super({ message: `${a}:${b}` })\n    }\n  }\n\n  // @ts-expect-error: Object literal may only specify known properties, and 'a' does not exist in type '{ readonly message: string; }'.ts(2353)\n  MyError.make({ a: \"1\", b: \"2\" })\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  class MyError extends Schema.TaggedError<MyError>()(\"MyError\", {\n    message: Schema.String\n  }) {\n    constructor({ a, b }: { a: string; b: string }) {\n      super({ message: `${a}:${b}` })\n    }\n  }\n\n  console.log(MyError.make({ a: \"1\", b: \"2\" }).message)\n  // Output: \"1:2\"\n  ```\n\n- [#4687](https://github.com/Effect-TS/effect/pull/4687) [`8b6c947`](https://github.com/Effect-TS/effect/commit/8b6c947eaa8e45a67ecb3c37d45cd27f3e41d165) Thanks @KhraksMamtsov! - Modify the signatures of `Either.liftPredicate` and `Effect.predicate` to make them reusable.\n\n- [#4794](https://github.com/Effect-TS/effect/pull/4794) [`c50a63b`](https://github.com/Effect-TS/effect/commit/c50a63bbecb9f560b9cae349c447eed877d1b9b6) Thanks @IGassmann! - Fix summary metric’s quantile value calculation\n\n## 3.14.14\n\n### Patch Changes\n\n- [#4786](https://github.com/Effect-TS/effect/pull/4786) [`6ed8d15`](https://github.com/Effect-TS/effect/commit/6ed8d1589beb181d30abc79afebdaabc1d101538) Thanks @tim-smart! - drop use of performance.timeOrigin in clock\n\n## 3.14.13\n\n### Patch Changes\n\n- [#4777](https://github.com/Effect-TS/effect/pull/4777) [`ee77788`](https://github.com/Effect-TS/effect/commit/ee77788747e7ebbde6bfa88256cde49dbbad3608) Thanks @gcanti! - JSONSchema: apply `encodeOption` to each example and retain successful results.\n\n  **Example**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.propertySignature(Schema.BigInt).annotations({\n      examples: [1n, 2n]\n    })\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"$defs\": {\n      \"BigInt\": {\n        \"type\": \"string\",\n        \"description\": \"a string to be decoded into a bigint\"\n      }\n    },\n    \"type\": \"object\",\n    \"required\": [\n      \"a\"\n    ],\n    \"properties\": {\n      \"a\": {\n        \"$ref\": \"#/$defs/BigInt\",\n        \"examples\": [\n          \"1\",\n          \"2\"\n        ]\n      }\n    },\n    \"additionalProperties\": false\n  }\n  */\n  ```\n\n- [#4701](https://github.com/Effect-TS/effect/pull/4701) [`5fce6ba`](https://github.com/Effect-TS/effect/commit/5fce6ba19c3cc63cc0104e737e581ad989dedbf0) Thanks @gcanti! - Fix `JSONSchema.make` for `Exit` schemas.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Exit({\n    failure: Schema.String,\n    success: Schema.Number,\n    defect: Schema.Defect\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  throws\n  Error: Missing annotation\n  at path: [\"cause\"][\"left\"]\n  details: Generating a JSON Schema for this schema requires an \"identifier\" annotation\n  schema (Suspend): CauseEncoded<string>\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Exit({\n    failure: Schema.String,\n    success: Schema.Number,\n    defect: Schema.Defect\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  Output:\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"$defs\": {\n      \"CauseEncoded0\": {\n        \"anyOf\": [\n          {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"Empty\"\n                ]\n              }\n            },\n            \"additionalProperties\": false\n          },\n          {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\",\n              \"error\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"Fail\"\n                ]\n              },\n              \"error\": {\n                \"type\": \"string\"\n              }\n            },\n            \"additionalProperties\": false\n          },\n          {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\",\n              \"defect\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"Die\"\n                ]\n              },\n              \"defect\": {\n                \"$ref\": \"#/$defs/Defect\"\n              }\n            },\n            \"additionalProperties\": false\n          },\n          {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\",\n              \"fiberId\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"Interrupt\"\n                ]\n              },\n              \"fiberId\": {\n                \"$ref\": \"#/$defs/FiberIdEncoded\"\n              }\n            },\n            \"additionalProperties\": false\n          },\n          {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\",\n              \"left\",\n              \"right\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"Sequential\"\n                ]\n              },\n              \"left\": {\n                \"$ref\": \"#/$defs/CauseEncoded0\"\n              },\n              \"right\": {\n                \"$ref\": \"#/$defs/CauseEncoded0\"\n              }\n            },\n            \"additionalProperties\": false\n          },\n          {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\",\n              \"left\",\n              \"right\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"Parallel\"\n                ]\n              },\n              \"left\": {\n                \"$ref\": \"#/$defs/CauseEncoded0\"\n              },\n              \"right\": {\n                \"$ref\": \"#/$defs/CauseEncoded0\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        ],\n        \"title\": \"CauseEncoded<string>\"\n      },\n      \"Defect\": {\n        \"$id\": \"/schemas/unknown\",\n        \"title\": \"unknown\"\n      },\n      \"FiberIdEncoded\": {\n        \"anyOf\": [\n          {\n            \"$ref\": \"#/$defs/FiberIdNoneEncoded\"\n          },\n          {\n            \"$ref\": \"#/$defs/FiberIdRuntimeEncoded\"\n          },\n          {\n            \"$ref\": \"#/$defs/FiberIdCompositeEncoded\"\n          }\n        ]\n      },\n      \"FiberIdNoneEncoded\": {\n        \"type\": \"object\",\n        \"required\": [\n          \"_tag\"\n        ],\n        \"properties\": {\n          \"_tag\": {\n            \"type\": \"string\",\n            \"enum\": [\n              \"None\"\n            ]\n          }\n        },\n        \"additionalProperties\": false\n      },\n      \"FiberIdRuntimeEncoded\": {\n        \"type\": \"object\",\n        \"required\": [\n          \"_tag\",\n          \"id\",\n          \"startTimeMillis\"\n        ],\n        \"properties\": {\n          \"_tag\": {\n            \"type\": \"string\",\n            \"enum\": [\n              \"Runtime\"\n            ]\n          },\n          \"id\": {\n            \"$ref\": \"#/$defs/Int\"\n          },\n          \"startTimeMillis\": {\n            \"$ref\": \"#/$defs/Int\"\n          }\n        },\n        \"additionalProperties\": false\n      },\n      \"Int\": {\n        \"type\": \"integer\",\n        \"description\": \"an integer\",\n        \"title\": \"int\"\n      },\n      \"FiberIdCompositeEncoded\": {\n        \"type\": \"object\",\n        \"required\": [\n          \"_tag\",\n          \"left\",\n          \"right\"\n        ],\n        \"properties\": {\n          \"_tag\": {\n            \"type\": \"string\",\n            \"enum\": [\n              \"Composite\"\n            ]\n          },\n          \"left\": {\n            \"$ref\": \"#/$defs/FiberIdEncoded\"\n          },\n          \"right\": {\n            \"$ref\": \"#/$defs/FiberIdEncoded\"\n          }\n        },\n        \"additionalProperties\": false\n      }\n    },\n    \"anyOf\": [\n      {\n        \"type\": \"object\",\n        \"required\": [\n          \"_tag\",\n          \"cause\"\n        ],\n        \"properties\": {\n          \"_tag\": {\n            \"type\": \"string\",\n            \"enum\": [\n              \"Failure\"\n            ]\n          },\n          \"cause\": {\n            \"$ref\": \"#/$defs/CauseEncoded0\"\n          }\n        },\n        \"additionalProperties\": false\n      },\n      {\n        \"type\": \"object\",\n        \"required\": [\n          \"_tag\",\n          \"value\"\n        ],\n        \"properties\": {\n          \"_tag\": {\n            \"type\": \"string\",\n            \"enum\": [\n              \"Success\"\n            ]\n          },\n          \"value\": {\n            \"type\": \"number\"\n          }\n        },\n        \"additionalProperties\": false\n      }\n    ],\n    \"title\": \"ExitEncoded<number, string, Defect>\"\n  }\n  */\n  ```\n\n- [#4775](https://github.com/Effect-TS/effect/pull/4775) [`570e45f`](https://github.com/Effect-TS/effect/commit/570e45f8cb936e42ec48f67f21bb2b7252f36c0c) Thanks @gcanti! - JSONSchema: preserve original key name when using `fromKey` followed by `annotations`, closes #4774.\n\n  Before:\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.propertySignature(Schema.String)\n      .pipe(Schema.fromKey(\"b\"))\n      .annotations({})\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [\n      \"a\"\n    ],\n    \"properties\": {\n      \"a\": {\n        \"type\": \"string\"\n      }\n    },\n    \"additionalProperties\": false\n  }\n  */\n  ```\n\n  After:\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.propertySignature(Schema.String)\n      .pipe(Schema.fromKey(\"b\"))\n      .annotations({})\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [\n      \"b\"\n    ],\n    \"properties\": {\n      \"b\": {\n        \"type\": \"string\"\n      }\n    },\n    \"additionalProperties\": false\n  }\n  */\n  ```\n\n## 3.14.12\n\n### Patch Changes\n\n- [#4770](https://github.com/Effect-TS/effect/pull/4770) [`c2ad9ee`](https://github.com/Effect-TS/effect/commit/c2ad9ee9f3c4c743390edf35ed9e85a20be33811) Thanks @gcanti! - Fixes a bug where non existing properties were allowed in the `make` constructor of a `Schema.Class`, closes #4767.\n\n  **Example**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  class A extends Schema.Class<A>(\"A\")({\n    a: Schema.String\n  }) {}\n\n  A.make({\n    a: \"a\",\n    // @ts-expect-error: Object literal may only specify known properties, and 'b' does not exist in type '{ readonly a: string; }'.ts(2353)\n    b: \"b\"\n  })\n  ```\n\n- [#4735](https://github.com/Effect-TS/effect/pull/4735) [`9c68654`](https://github.com/Effect-TS/effect/commit/9c686542b6eb3ea188cb70673ef2e41223633e89) Thanks @suddenlyGiovanni! - Improve `Number` module with comprehensive TsDocs and type-level tests\n\n## 3.14.11\n\n### Patch Changes\n\n- [#4756](https://github.com/Effect-TS/effect/pull/4756) [`e536127`](https://github.com/Effect-TS/effect/commit/e536127c1e6f2fb3a542c73ae919435a629a346b) Thanks @tim-smart! - allow Pool to acquire multiple items at once\n\n## 3.14.10\n\n### Patch Changes\n\n- [#4748](https://github.com/Effect-TS/effect/pull/4748) [`bc7efa3`](https://github.com/Effect-TS/effect/commit/bc7efa3b031bb25e1ed3c8f2d3fb5e8da166cadc) Thanks @tim-smart! - preserve refinement types in Match.when\n\n## 3.14.9\n\n### Patch Changes\n\n- [#4734](https://github.com/Effect-TS/effect/pull/4734) [`d78249f`](https://github.com/Effect-TS/effect/commit/d78249f0b67f63cf4baf806ff090cba33293daf0) Thanks @thewilkybarkid! - Allow Match.typeTags to specify a return type\n\n## 3.14.8\n\n### Patch Changes\n\n- [#4708](https://github.com/Effect-TS/effect/pull/4708) [`b3a2d32`](https://github.com/Effect-TS/effect/commit/b3a2d32772e6f7f20eacf2e18128e99324c4d378) Thanks @thewilkybarkid! - Make Match.valueTags dual\n\n## 3.14.7\n\n### Patch Changes\n\n- [#4706](https://github.com/Effect-TS/effect/pull/4706) [`b542a4b`](https://github.com/Effect-TS/effect/commit/b542a4bf195be0c9af1523e1ba96c953decc4d25) Thanks @IGassmann! - Fix summary metric’s quantile values\n\n## 3.14.6\n\n### Patch Changes\n\n- [#4674](https://github.com/Effect-TS/effect/pull/4674) [`47618c1`](https://github.com/Effect-TS/effect/commit/47618c1ad84ebcc5a51133a3fff5aa5012d49d45) Thanks @suddenlyGiovanni! - Improved TsDoc documentation for `MutableHashSet` module.\n\n- [#4699](https://github.com/Effect-TS/effect/pull/4699) [`6077882`](https://github.com/Effect-TS/effect/commit/60778824a4794336c33807801f813f8751d1c7e4) Thanks @gcanti! - Fix JSONSchema generation for record values that include `undefined`, closes #4697.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.partial(\n    Schema.Struct(\n      { foo: Schema.Number },\n      {\n        key: Schema.String,\n        value: Schema.Number\n      }\n    )\n  )\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  // throws\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.partial(\n    Schema.Struct(\n      { foo: Schema.Number },\n      {\n        key: Schema.String,\n        value: Schema.Number\n      }\n    )\n  )\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  Output:\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [],\n    \"properties\": {\n      \"foo\": {\n        \"type\": \"number\"\n      }\n    },\n    \"additionalProperties\": {\n      \"type\": \"number\"\n    }\n  }\n  */\n  ```\n\n## 3.14.5\n\n### Patch Changes\n\n- [#4676](https://github.com/Effect-TS/effect/pull/4676) [`40dbfef`](https://github.com/Effect-TS/effect/commit/40dbfeff239b6e567706752114f31b2fce7de4e3) Thanks @tim-smart! - allow Effect.fnUntraced to return non-effects\n\n- [#4682](https://github.com/Effect-TS/effect/pull/4682) [`5a5ebdd`](https://github.com/Effect-TS/effect/commit/5a5ebdddfaddd259538b4599a6676281faca778e) Thanks @thewilkybarkid! - ensure Equal considers URL by value\n\n## 3.14.4\n\n### Patch Changes\n\n- [#4667](https://github.com/Effect-TS/effect/pull/4667) [`e4ba2c6`](https://github.com/Effect-TS/effect/commit/e4ba2c66a878e81b5e295d6d49aaf724b80a28ef) Thanks @suddenlyGiovanni! - Fix: `HashSet.md` api docs; previously broken by issue with Docgen JsDoc parser.\n\n## 3.14.3\n\n### Patch Changes\n\n- [#4664](https://github.com/Effect-TS/effect/pull/4664) [`37aa8e1`](https://github.com/Effect-TS/effect/commit/37aa8e137725a902e70cd1e468ea98b873aa5056) Thanks @suddenlyGiovanni! - Improved TsDoc documentation for `HashSet` module.\n\n- [#4670](https://github.com/Effect-TS/effect/pull/4670) [`34f03d6`](https://github.com/Effect-TS/effect/commit/34f03d66875f21f266f102223a03cd14c2ed6ea6) Thanks @tim-smart! - fix Data.TaggedEnum with generics regression\n\n## 3.14.2\n\n### Patch Changes\n\n- [#4646](https://github.com/Effect-TS/effect/pull/4646) [`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865) Thanks @gcanti! - SchemaAST: add missing `getSchemaIdAnnotation` API\n\n- [#4646](https://github.com/Effect-TS/effect/pull/4646) [`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865) Thanks @gcanti! - Arbitrary: fix bug where annotations were ignored.\n\n  Before\n\n  ```ts\n  import { Arbitrary, Schema } from \"effect\"\n\n  const schema = Schema.Int.annotations({\n    arbitrary: (_, ctx) => (fc) => {\n      console.log(\"context: \", ctx)\n      return fc.integer()\n    }\n  }).pipe(Schema.greaterThan(0), Schema.lessThan(10))\n\n  Arbitrary.make(schema)\n  // No output ❌\n  ```\n\n  After\n\n  ```ts\n  import { Arbitrary, Schema } from \"effect\"\n\n  const schema = Schema.Int.annotations({\n    arbitrary: (_, ctx) => (fc) => {\n      console.log(\"context: \", ctx)\n      return fc.integer()\n    }\n  }).pipe(Schema.greaterThan(0), Schema.lessThan(10))\n\n  Arbitrary.make(schema)\n  /*\n  context:  {\n    maxDepth: 2,\n    constraints: {\n      _tag: 'NumberConstraints',\n      constraints: { min: 0, minExcluded: true, max: 10, maxExcluded: true },\n      isInteger: true\n    }\n  }\n  */\n  ```\n\n- [#4648](https://github.com/Effect-TS/effect/pull/4648) [`0a3e3e1`](https://github.com/Effect-TS/effect/commit/0a3e3e18eea5e0d1882f1a6c906198e6ef226a41) Thanks @gcanti! - Schema: `standardSchemaV1` now includes the schema, closes #4494.\n\n  This update fixes an issue where passing `Schema.standardSchemaV1(...)` directly to `JSONSchema.make` would throw a `TypeError`. The schema was missing from the returned object, causing the JSON schema generation to fail.\n\n  Now `standardSchemaV1` includes the schema itself, so it can be used with `JSONSchema.make` without issues.\n\n  **Example**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const Person = Schema.Struct({\n    name: Schema.optionalWith(Schema.NonEmptyString, { exact: true })\n  })\n\n  const standardSchema = Schema.standardSchemaV1(Person)\n\n  console.log(JSONSchema.make(standardSchema))\n  /*\n  {\n    '$schema': 'http://json-schema.org/draft-07/schema#',\n    '$defs': {\n      NonEmptyString: {\n        type: 'string',\n        description: 'a non empty string',\n        title: 'nonEmptyString',\n        minLength: 1\n      }\n    },\n    type: 'object',\n    required: [],\n    properties: { name: { '$ref': '#/$defs/NonEmptyString' } },\n    additionalProperties: false\n  }\n  */\n  ```\n\n## 3.14.1\n\n### Patch Changes\n\n- [#4620](https://github.com/Effect-TS/effect/pull/4620) [`4a274fe`](https://github.com/Effect-TS/effect/commit/4a274fe9f623182b6b902827e0e83bd89ca3b05c) Thanks @tim-smart! - remove Context.ValidTagsById usage\n\n## 3.14.0\n\n### Minor Changes\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`1f47e4e`](https://github.com/Effect-TS/effect/commit/1f47e4e12546ab691b29bfb7b5128bb17b93baa5) Thanks @vinassefranche! - Add DateTime.nowAsDate creator\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780) Thanks @tim-smart! - expose the Layer.MemoMap via Layer.CurrentMemoMap to the layers being built\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`04dff2d`](https://github.com/Effect-TS/effect/commit/04dff2d01ac68c260f29a6d4743381825c353c86) Thanks @tim-smart! - add Tracer Span.addLinks, for dynamically linking spans\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`c7fac0c`](https://github.com/Effect-TS/effect/commit/c7fac0cd7eadcd5cc0c3a987051c5b57ad271638) Thanks @LaureRC! - Add HashMap.every\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`ffaa3f3`](https://github.com/Effect-TS/effect/commit/ffaa3f3969df26610fcc02ad537340641d44e803) Thanks @vinassefranche! - Add Either.transposeOption\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`ab957c1`](https://github.com/Effect-TS/effect/commit/ab957c1fee714868f56c7ab4e802b9d449e9b666) Thanks @vinassefranche! - Make TestClock.setTime accept a DateTime.Input\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`35db9ce`](https://github.com/Effect-TS/effect/commit/35db9ce228f1416c8abacc6dc9c36fbd0f33ef0f) Thanks @LaureRC! - Add Effect.transposeMapOption\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`cf77ea9`](https://github.com/Effect-TS/effect/commit/cf77ea9ab4fc89e66a43f682a9926ccdee6c57ed) Thanks @f15u! - Add `Array.window` function\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780) Thanks @tim-smart! - add LayerMap module\n\n  A `LayerMap` allows you to create a map of Layer's that can be used to\n  dynamically access resources based on a key.\n\n  Here is an example of how you can use a `LayerMap` to create a service that\n  provides access to multiple OpenAI completions services.\n\n  ```ts\n  import { Completions } from \"@effect/ai\"\n  import { OpenAiClient, OpenAiCompletions } from \"@effect/ai-openai\"\n  import { FetchHttpClient } from \"@effect/platform\"\n  import { NodeRuntime } from \"@effect/platform-node\"\n  import { Config, Effect, Layer, LayerMap } from \"effect\"\n\n  // create the openai client layer\n  const OpenAiLayer = OpenAiClient.layerConfig({\n    apiKey: Config.redacted(\"OPENAI_API_KEY\")\n  }).pipe(Layer.provide(FetchHttpClient.layer))\n\n  // create a service that wraps a LayerMap\n  class AiClients extends LayerMap.Service<AiClients>()(\"AiClients\", {\n    // this LayerMap will provide the ai Completions service\n    provides: Completions.Completions,\n\n    // define the lookup function for the layer map\n    //\n    // The returned Layer will be used to provide the Completions service for the\n    // given model.\n    lookup: (model: OpenAiCompletions.Model) =>\n      OpenAiCompletions.layer({ model }),\n\n    // If a layer is not used for a certain amount of time, it can be removed\n    idleTimeToLive: \"5 seconds\",\n\n    // Supply the dependencies for the layers in the LayerMap\n    dependencies: [OpenAiLayer]\n  }) {}\n\n  // usage\n  Effect.gen(function* () {\n    // access and use the generic Completions service\n    const ai = yield* Completions.Completions\n    const response = yield* ai.create(\"Hello, world!\")\n    console.log(response.text)\n  }).pipe(\n    // use the AiClients service to provide a variant of the Completions service\n    AiClients.provide(\"gpt-4o\"),\n    // provide the LayerMap service\n    Effect.provide(AiClients.Default),\n    NodeRuntime.runMain\n  )\n  ```\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`baaab60`](https://github.com/Effect-TS/effect/commit/baaab60b737f35dfab8e4a21bce28a195d19e899) Thanks @vinassefranche! - Make Runtime.run\\* apis dual\n\n### Patch Changes\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce) Thanks @tim-smart! - preserve interruptors in channel executor .runIn\n\n## 3.13.12\n\n### Patch Changes\n\n- [#4610](https://github.com/Effect-TS/effect/pull/4610) [`0c4803f`](https://github.com/Effect-TS/effect/commit/0c4803fcc69262d11a97ce49d0e9b4288df0651f) Thanks @gcanti! - Preserve specific annotations (e.g., `arbitrary`) when using `Schema.typeSchema`, closes #4609.\n\n  Previously, annotations such as `arbitrary` were lost when calling `Schema.typeSchema` on a transformation. This update ensures that certain annotations, which depend only on the \"to\" side of the transformation, are preserved.\n\n  Annotations that are now retained:\n  - `examples`\n  - `default`\n  - `jsonSchema`\n  - `arbitrary`\n  - `pretty`\n  - `equivalence`\n\n  **Example**\n\n  Before\n\n  ```ts\n  import { Arbitrary, FastCheck, Schema } from \"effect\"\n\n  const schema = Schema.NumberFromString.annotations({\n    arbitrary: () => (fc) => fc.constant(1)\n  })\n\n  const to = Schema.typeSchema(schema) // ❌ Annotation is lost\n\n  console.log(FastCheck.sample(Arbitrary.make(to), 5))\n  /*\n  [\n    2.5223372357846707e-44,\n    -2.145443957806771e+25,\n    -3.4028179901346956e+38,\n    5.278086259208735e+29,\n    1.8216880036222622e-44\n  ]\n  */\n  ```\n\n  After\n\n  ```ts\n  import { Arbitrary, FastCheck, Schema } from \"effect\"\n\n  const schema = Schema.NumberFromString.annotations({\n    arbitrary: () => (fc) => fc.constant(1)\n  })\n\n  const to = Schema.typeSchema(schema) // ✅ Annotation is now preserved\n\n  console.log(FastCheck.sample(Arbitrary.make(to), 5))\n  /*\n  [ 1, 1, 1, 1, 1 ]\n  */\n  ```\n\n- [#4607](https://github.com/Effect-TS/effect/pull/4607) [`6f65ac4`](https://github.com/Effect-TS/effect/commit/6f65ac4eac1489cd6ea390e18b0908670722adad) Thanks @gcanti! - Add support for `jsonSchema` annotations on `SymbolFromSelf` index signatures.\n\n  **Before**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Record({\n    key: Schema.SymbolFromSelf.annotations({ jsonSchema: { type: \"string\" } }),\n    value: Schema.Number\n  })\n\n  JSONSchema.make(schema)\n  /*\n  throws:\n  Error: Unsupported index signature parameter\n  schema (SymbolKeyword): symbol\n  */\n  ```\n\n  **After**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Record({\n    key: Schema.SymbolFromSelf.annotations({ jsonSchema: { type: \"string\" } }),\n    value: Schema.Number\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  Output:\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [],\n    \"properties\": {},\n    \"additionalProperties\": {\n      \"type\": \"number\"\n    },\n    \"propertyNames\": {\n      \"type\": \"string\"\n    }\n  }\n  */\n  ```\n\n## 3.13.11\n\n### Patch Changes\n\n- [#4601](https://github.com/Effect-TS/effect/pull/4601) [`fad8cca`](https://github.com/Effect-TS/effect/commit/fad8cca9bbfcc2eaeb44b97c15dbe0a1eda75315) Thanks @gcanti! - Schema: enhance the internal `formatUnknown` function to handle various types including iterables, classes, and additional edge cases.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Array(Schema.Number)\n\n  Schema.decodeUnknownSync(schema)(new Set([1, 2]))\n  // throws Expected ReadonlyArray<number>, actual {}\n\n  class A {\n    constructor(readonly a: number) {}\n  }\n\n  Schema.decodeUnknownSync(schema)(new A(1))\n  // throws Expected ReadonlyArray<number>, actual {\"a\":1}\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Array(Schema.Number)\n\n  Schema.decodeUnknownSync(schema)(new Set([1, 2]))\n  // throws Expected ReadonlyArray<number>, actual Set([1,2])\n\n  class A {\n    constructor(readonly a: number) {}\n  }\n\n  Schema.decodeUnknownSync(schema)(new A(1))\n  // throws Expected ReadonlyArray<number>, actual A({\"a\":1})\n  ```\n\n- [#4606](https://github.com/Effect-TS/effect/pull/4606) [`4296293`](https://github.com/Effect-TS/effect/commit/4296293049414d0cf2d915a26c552b09f946b9a0) Thanks @gcanti! - Fix issue with generic filters when generating arbitraries, closes #4605.\n\n  Previously, applying a `filter` to a schema when generating arbitraries could cause a `TypeError` due to missing properties. This fix ensures that arbitraries are generated correctly when filters are used.\n\n  **Before**\n\n  ```ts\n  import { Arbitrary, Schema } from \"effect\"\n\n  const schema = Schema.BigIntFromSelf.pipe(Schema.filter(() => true))\n\n  Arbitrary.make(schema)\n  // TypeError: Cannot read properties of undefined (reading 'min')\n  ```\n\n  **After**\n\n  ```ts\n  import { Arbitrary, Schema } from \"effect\"\n\n  const schema = Schema.BigIntFromSelf.pipe(Schema.filter(() => true))\n\n  const result = Arbitrary.make(schema) // Works correctly\n  ```\n\n- [#4587](https://github.com/Effect-TS/effect/pull/4587) [`9c241ab`](https://github.com/Effect-TS/effect/commit/9c241abe47ccf7a5257b98a4a64a63054a12741d) Thanks @gcanti! - Schema: simplify `Struct` and `Record` return types.\n\n- [#4591](https://github.com/Effect-TS/effect/pull/4591) [`082b0c1`](https://github.com/Effect-TS/effect/commit/082b0c1b9f4252bcdd69608f2e4a9226f953ac3f) Thanks @IMax153! - Improve clarity of the `TimeoutException` error message\n\n- [#4604](https://github.com/Effect-TS/effect/pull/4604) [`be12983`](https://github.com/Effect-TS/effect/commit/be12983bc7e7537b41cd8910fc4eb7d1da56ab07) Thanks @gcanti! - Add support for refinements to `Schema.omit`, closes #4603.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.String,\n    b: Schema.String\n  })\n\n  const omitted = schema.pipe(\n    Schema.filter(() => true),\n    Schema.omit(\"a\")\n  )\n\n  console.log(String(omitted.ast))\n  // {} ❌\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.String,\n    b: Schema.String\n  })\n\n  const omitted = schema.pipe(\n    Schema.filter(() => true),\n    Schema.omit(\"a\")\n  )\n\n  console.log(String(omitted.ast))\n  // { readonly b: string }\n  ```\n\n- [#4593](https://github.com/Effect-TS/effect/pull/4593) [`de88127`](https://github.com/Effect-TS/effect/commit/de88127a5a5906ccece98af74787b5ae0e65e431) Thanks @gcanti! - Schema: export `Field` type.\n\n  Useful for creating a type that can be used to add custom constraints to the fields of a struct.\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const f = <Fields extends Record<\"a\" | \"b\", Schema.Struct.Field>>(\n    schema: Schema.Struct<Fields>\n  ) => {\n    return schema.omit(\"a\")\n  }\n\n  //      ┌─── Schema.Struct<{ b: typeof Schema.Number; }>\n  //      ▼\n  const result = f(Schema.Struct({ a: Schema.String, b: Schema.Number }))\n  ```\n\n## 3.13.10\n\n### Patch Changes\n\n- [#4578](https://github.com/Effect-TS/effect/pull/4578) [`527c964`](https://github.com/Effect-TS/effect/commit/527c9645229f5be9714a7e60a38a9e753c4bbfb1) Thanks @gcanti! - Allow `toString` Method to Be Overridden in Schema Classes, closes #4577.\n\n  Previously, attempting to override the `toString` method in schema classes caused a `TypeError` in the browser because the property was set as **read-only** (`writable: false`). This fix makes `toString` **writable**, allowing developers to override it when needed.\n\n## 3.13.9\n\n### Patch Changes\n\n- [#4579](https://github.com/Effect-TS/effect/pull/4579) [`2976e52`](https://github.com/Effect-TS/effect/commit/2976e52538d9dc9ffdcbc84d4ac748cff9305971) Thanks @giuliobracci! - Fix `Match.tags` throwing exception on `undefined` input value\n\n## 3.13.8\n\n### Patch Changes\n\n- [#4567](https://github.com/Effect-TS/effect/pull/4567) [`c65d336`](https://github.com/Effect-TS/effect/commit/c65d3362d07ec815ff3b46278314e8a31706ddc2) Thanks @rehos! - Schema: `standardSchemaV1` now returns all errors by default and supports custom options.\n\n  The `standardSchemaV1` now returns **all validation errors** by default (`ParseOptions = { errors: \"all\" }`). Additionally, it now accepts an optional `overrideOptions` parameter, allowing you to customize the default parsing behavior as needed.\n\n- [#4565](https://github.com/Effect-TS/effect/pull/4565) [`22d2ebb`](https://github.com/Effect-TS/effect/commit/22d2ebb4b11f5a44351a4736e65da391a3b647d0) Thanks @gcanti! - ParseResult.ArrayFormatter: correct `_tag` fields for `Refinement` and `Transformation` issues, closes #4564.\n\n  This update fixes an issue where `ParseResult.ArrayFormatter` incorrectly labeled **Refinement** and **Transformation** errors as `Type` in the output.\n\n  **Before**\n\n  ```ts\n  import { Effect, ParseResult, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.NonEmptyString,\n    b: Schema.NumberFromString\n  })\n\n  const input = { a: \"\", b: \"\" }\n\n  const program = Schema.decodeUnknown(schema, { errors: \"all\" })(input).pipe(\n    Effect.catchTag(\"ParseError\", (err) =>\n      ParseResult.ArrayFormatter.formatError(err).pipe(\n        Effect.map((err) => JSON.stringify(err, null, 2))\n      )\n    )\n  )\n\n  program.pipe(Effect.runPromise).then(console.log)\n  /*\n  [\n    {\n      \"_tag\": \"Type\", ❌\n      \"path\": [\n        \"a\"\n      ],\n      \"message\": \"Expected a non empty string, actual \\\"\\\"\"\n    },\n    {\n      \"_tag\": \"Type\", ❌\n      \"path\": [\n        \"b\"\n      ],\n      \"message\": \"Unable to decode \\\"\\\" into a number\"\n    }\n  ]\n  */\n  ```\n\n  **After**\n\n  ```ts\n  import { Effect, ParseResult, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.NonEmptyString,\n    b: Schema.NumberFromString\n  })\n\n  const input = { a: \"\", b: \"\" }\n\n  const program = Schema.decodeUnknown(schema, { errors: \"all\" })(input).pipe(\n    Effect.catchTag(\"ParseError\", (err) =>\n      ParseResult.ArrayFormatter.formatError(err).pipe(\n        Effect.map((err) => JSON.stringify(err, null, 2))\n      )\n    )\n  )\n\n  program.pipe(Effect.runPromise).then(console.log)\n  /*\n  [\n    {\n      \"_tag\": \"Refinement\", ✅\n      \"path\": [\n        \"a\"\n      ],\n      \"message\": \"Expected a non empty string, actual \\\"\\\"\"\n    },\n    {\n      \"_tag\": \"Transformation\", ✅\n      \"path\": [\n        \"b\"\n      ],\n      \"message\": \"Unable to decode \\\"\\\" into a number\"\n    }\n  ]\n  */\n  ```\n\n## 3.13.7\n\n### Patch Changes\n\n- [#4540](https://github.com/Effect-TS/effect/pull/4540) [`840cc73`](https://github.com/Effect-TS/effect/commit/840cc7329908db7ca693ef47b07d4f845c29cadd) Thanks @gcanti! - Add `additionalPropertiesStrategy` option to `OpenApi.fromApi`, closes #4531.\n\n  This update introduces the `additionalPropertiesStrategy` option in `OpenApi.fromApi`, allowing control over how additional properties are handled in the generated OpenAPI schema.\n  - When `\"strict\"` (default), additional properties are disallowed (`\"additionalProperties\": false`).\n  - When `\"allow\"`, additional properties are allowed (`\"additionalProperties\": true`), making APIs more flexible.\n\n  The `additionalPropertiesStrategy` option has also been added to:\n  - `JSONSchema.fromAST`\n  - `OpenApiJsonSchema.makeWithDefs`\n\n  **Example**\n\n  ```ts\n  import {\n    HttpApi,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    OpenApi\n  } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const api = HttpApi.make(\"api\").add(\n    HttpApiGroup.make(\"group\").add(\n      HttpApiEndpoint.get(\"get\", \"/\").addSuccess(\n        Schema.Struct({ a: Schema.String })\n      )\n    )\n  )\n\n  const schema = OpenApi.fromApi(api, {\n    additionalPropertiesStrategy: \"allow\"\n  })\n\n  console.log(JSON.stringify(schema, null, 2))\n  /*\n  {\n    \"openapi\": \"3.1.0\",\n    \"info\": {\n      \"title\": \"Api\",\n      \"version\": \"0.0.1\"\n    },\n    \"paths\": {\n      \"/\": {\n        \"get\": {\n          \"tags\": [\n            \"group\"\n          ],\n          \"operationId\": \"group.get\",\n          \"parameters\": [],\n          \"security\": [],\n          \"responses\": {\n            \"200\": {\n              \"description\": \"Success\",\n              \"content\": {\n                \"application/json\": {\n                  \"schema\": {\n                    \"type\": \"object\",\n                    \"required\": [\n                      \"a\"\n                    ],\n                    \"properties\": {\n                      \"a\": {\n                        \"type\": \"string\"\n                      }\n                    },\n                    \"additionalProperties\": true\n                  }\n                }\n              }\n            },\n            \"400\": {\n              \"description\": \"The request did not match the expected schema\",\n              \"content\": {\n                \"application/json\": {\n                  \"schema\": {\n                    \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    },\n    \"components\": {\n      \"schemas\": {\n        \"HttpApiDecodeError\": {\n          \"type\": \"object\",\n          \"required\": [\n            \"issues\",\n            \"message\",\n            \"_tag\"\n          ],\n          \"properties\": {\n            \"issues\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"$ref\": \"#/components/schemas/Issue\"\n              }\n            },\n            \"message\": {\n              \"type\": \"string\"\n            },\n            \"_tag\": {\n              \"type\": \"string\",\n              \"enum\": [\n                \"HttpApiDecodeError\"\n              ]\n            }\n          },\n          \"additionalProperties\": true,\n          \"description\": \"The request did not match the expected schema\"\n        },\n        \"Issue\": {\n          \"type\": \"object\",\n          \"required\": [\n            \"_tag\",\n            \"path\",\n            \"message\"\n          ],\n          \"properties\": {\n            \"_tag\": {\n              \"type\": \"string\",\n              \"enum\": [\n                \"Pointer\",\n                \"Unexpected\",\n                \"Missing\",\n                \"Composite\",\n                \"Refinement\",\n                \"Transformation\",\n                \"Type\",\n                \"Forbidden\"\n              ],\n              \"description\": \"The tag identifying the type of parse issue\"\n            },\n            \"path\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"$ref\": \"#/components/schemas/PropertyKey\"\n              },\n              \"description\": \"The path to the property where the issue occurred\"\n            },\n            \"message\": {\n              \"type\": \"string\",\n              \"description\": \"A descriptive message explaining the issue\"\n            }\n          },\n          \"additionalProperties\": true,\n          \"description\": \"Represents an error encountered while parsing a value to match the schema\"\n        },\n        \"PropertyKey\": {\n          \"anyOf\": [\n            {\n              \"type\": \"string\"\n            },\n            {\n              \"type\": \"number\"\n            },\n            {\n              \"type\": \"object\",\n              \"required\": [\n                \"_tag\",\n                \"key\"\n              ],\n              \"properties\": {\n                \"_tag\": {\n                  \"type\": \"string\",\n                  \"enum\": [\n                    \"symbol\"\n                  ]\n                },\n                \"key\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"additionalProperties\": true,\n              \"description\": \"an object to be decoded into a globally shared symbol\"\n            }\n          ]\n        }\n      },\n      \"securitySchemes\": {}\n    },\n    \"security\": [],\n    \"tags\": [\n      {\n        \"name\": \"group\"\n      }\n    ]\n  }\n  */\n  ```\n\n- [#4541](https://github.com/Effect-TS/effect/pull/4541) [`9bf8a74`](https://github.com/Effect-TS/effect/commit/9bf8a74b967f18d931743dd5196af326c9118e9c) Thanks @fubhy! - Disallowed excess properties for various function options\n\n- [#4554](https://github.com/Effect-TS/effect/pull/4554) [`87ba23c`](https://github.com/Effect-TS/effect/commit/87ba23c41c193503ed0c612b0d32d0b253794c64) Thanks @gcanti! - ConfigProvider: `fromEnv`: add missing `Partial` modifier.\n\n## 3.13.6\n\n### Patch Changes\n\n- [#4551](https://github.com/Effect-TS/effect/pull/4551) [`3154ce4`](https://github.com/Effect-TS/effect/commit/3154ce4692fa18b804982158d3c4c8a8a5fae386) Thanks @gcanti! - Arbitrary: `make` called on `Schema.Class` now respects property annotations, closes #4550.\n\n  Previously, when calling `Arbitrary.make` on a `Schema.Class`, property-specific annotations (such as `arbitrary`) were ignored, leading to unexpected values in generated instances.\n\n  Before\n\n  Even though `a` had an `arbitrary` annotation, the generated values were random:\n\n  ```ts\n  import { Arbitrary, FastCheck, Schema } from \"effect\"\n\n  class Class extends Schema.Class<Class>(\"Class\")({\n    a: Schema.NumberFromString.annotations({\n      arbitrary: () => (fc) => fc.constant(1)\n    })\n  }) {}\n\n  console.log(FastCheck.sample(Arbitrary.make(Class), 5))\n  /*\n  Example Output:\n  [\n    Class { a: 2.6624670822171524e-44 },\n    Class { a: 3.4028177873105996e+38 },\n    Class { a: 3.402820626847944e+38 },\n    Class { a: 3.783505853677006e-44 },\n    Class { a: 3243685 }\n  ]\n  */\n  ```\n\n  After\n\n  Now, the values respect the `arbitrary` annotation and return the expected constant:\n\n  ```ts\n  import { Arbitrary, FastCheck, Schema } from \"effect\"\n\n  class Class extends Schema.Class<Class>(\"Class\")({\n    a: Schema.NumberFromString.annotations({\n      arbitrary: () => (fc) => fc.constant(1)\n    })\n  }) {}\n\n  console.log(FastCheck.sample(Arbitrary.make(Class), 5))\n  /*\n  [\n    Class { a: 1 },\n    Class { a: 1 },\n    Class { a: 1 },\n    Class { a: 1 },\n    Class { a: 1 }\n  ]\n  */\n  ```\n\n## 3.13.5\n\n### Patch Changes\n\n- [#4530](https://github.com/Effect-TS/effect/pull/4530) [`367bb35`](https://github.com/Effect-TS/effect/commit/367bb35f4c2a254e1fb211d96db2474a7aed9020) Thanks @tim-smart! - Match.tag + Match.withReturnType can use literals without as const\n\n- [#4543](https://github.com/Effect-TS/effect/pull/4543) [`6cf11c3`](https://github.com/Effect-TS/effect/commit/6cf11c3a75773ceec2877c85ddc760f381f0866d) Thanks @gcanti! - Preserve branded primitive types in `DeepMutable` transformation, closes #4542.\n\n  Previously, applying `DeepMutable` to branded primitive types (e.g., `string & Brand.Brand<\"mybrand\">`) caused unexpected behavior, where `String` prototype methods were incorrectly inherited.\n\n  This fix ensures that branded types remain unchanged during transformation, preventing type inconsistencies.\n\n  **Example**\n\n  Before\n\n  ```ts\n  import type { Brand, Types } from \"effect\"\n\n  type T = string & Brand.Brand<\"mybrand\">\n\n  /*\n  type Result = {\n      [x: number]: string;\n      toString: () => string;\n      charAt: (pos: number) => string;\n      charCodeAt: (index: number) => number;\n      concat: (...strings: string[]) => string;\n      indexOf: (searchString: string, position?: number) => number;\n      ... 47 more ...;\n      [BrandTypeId]: {\n          ...;\n      };\n  }\n  */\n  type Result = Types.DeepMutable<T>\n  ```\n\n  After\n\n  ```ts\n  import type { Brand, Types } from \"effect\"\n\n  type T = string & Brand.Brand<\"mybrand\">\n\n  // type Result = string & Brand.Brand<\"mybrand\">\n  type Result = Types.DeepMutable<T>\n  ```\n\n- [#4546](https://github.com/Effect-TS/effect/pull/4546) [`a0acec8`](https://github.com/Effect-TS/effect/commit/a0acec851f72e19466363d24b9cc218acd00006a) Thanks @gcanti! - Schema.extend: add support for Transformation + Struct, closes #4536.\n\n  **Example**\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const A = Schema.Struct({\n    a: Schema.String\n  })\n\n  const B = Schema.Struct({\n    b: Schema.String\n  })\n\n  const C = Schema.Struct({\n    c: Schema.String\n  })\n\n  const AB = Schema.transform(A, B, {\n    strict: true,\n    decode: (a) => ({ b: a.a }),\n    encode: (b) => ({ a: b.b })\n  })\n\n  // Transformation + Struct\n  const schema = Schema.extend(AB, C)\n  /*\n  throws:\n  Error: Unsupported schema or overlapping types\n  details: cannot extend ({ readonly a: string } <-> { readonly b: string }) with { readonly c: string }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const A = Schema.Struct({\n    a: Schema.String\n  })\n\n  const B = Schema.Struct({\n    b: Schema.String\n  })\n\n  const C = Schema.Struct({\n    c: Schema.String\n  })\n\n  const AB = Schema.transform(A, B, {\n    strict: true,\n    decode: (a) => ({ b: a.a }),\n    encode: (b) => ({ a: b.b })\n  })\n\n  // Transformation + Struct\n  const schema = Schema.extend(AB, C)\n\n  console.log(Schema.decodeUnknownSync(schema)({ a: \"a\", c: \"c\" }))\n  // Output: { b: 'a', c: 'c' }\n\n  console.log(Schema.encodeSync(schema)({ b: \"b\", c: \"c\" }))\n  // Output: { a: 'b', c: 'c' }\n  ```\n\n## 3.13.4\n\n### Patch Changes\n\n- [#4533](https://github.com/Effect-TS/effect/pull/4533) [`17d9e89`](https://github.com/Effect-TS/effect/commit/17d9e89f9851663bdbb6c1e685601d97806114a4) Thanks @gcanti! - Schema: Export `MakeOptions` type, closes #4532.\n\n## 3.13.3\n\n### Patch Changes\n\n- [#4502](https://github.com/Effect-TS/effect/pull/4502) [`cc5588d`](https://github.com/Effect-TS/effect/commit/cc5588df07f9103513547cb429ce041b9436a8bd) Thanks @gcanti! - Schema: More Accurate Return Types for `DataFromSelf` and `Data`.\n\n  This update refines the return types of `DataFromSelf` and `Data`, making them clearer and more specific, especially when working with structured schemas.\n\n  **Before**\n\n  The return types were more generic, making it harder to see the underlying structure:\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const struct = Schema.Struct({ a: Schema.NumberFromString })\n\n  //       ┌─── Schema.DataFromSelf<Schema<{ readonly a: number; }, { readonly a: string; }>>\n  //       ▼\n  const schema1 = Schema.DataFromSelf(struct)\n\n  //       ┌─── Schema.Data<Schema<{ readonly a: number; }, { readonly a: string; }>>\n  //       ▼\n  const schema2 = Schema.Data(struct)\n  ```\n\n  **After**\n\n  Now, the return types clearly reflect the original schema structure:\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const struct = Schema.Struct({ a: Schema.NumberFromString })\n\n  //       ┌─── Schema.DataFromSelf<Schema.Struct<{ a: typeof Schema.NumberFromString; }>>\n  //       ▼\n  const schema1 = Schema.DataFromSelf(struct)\n\n  //       ┌─── Schema.Data<Schema.Struct<{ a: typeof Schema.NumberFromString; }>>\n  //       ▼\n  const schema2 = Schema.Data(struct)\n  ```\n\n- [#4510](https://github.com/Effect-TS/effect/pull/4510) [`623c8cd`](https://github.com/Effect-TS/effect/commit/623c8cd053ed6ee3d353aaa8778d484670fca2bb) Thanks @gcanti! - Schema: More Accurate Return Type for `compose`.\n\n  **Before**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  //      ┌─── SchemaClass<number | null, string>\n  //      ▼\n  const schema = Schema.compose(\n    Schema.NumberFromString,\n    Schema.NullOr(Schema.Number)\n  )\n\n  // @ts-expect-error: Property 'from' does not exist\n  schema.from\n\n  // @ts-expect-error: Property 'to' does not exist\n  schema.to\n  ```\n\n  **After**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  //      ┌─── transform<typeof Schema.NumberFromString, Schema.NullOr<typeof Schema.Number>>\n  //      ▼\n  const schema = Schema.compose(\n    Schema.NumberFromString,\n    Schema.NullOr(Schema.Number)\n  )\n\n  //      ┌─── typeof Schema.NumberFromString\n  //      ▼\n  schema.from\n\n  //      ┌─── Schema.NullOr<typeof Schema.Number>\n  //      ▼\n  schema.to\n  ```\n\n- [#4488](https://github.com/Effect-TS/effect/pull/4488) [`00b4eb1`](https://github.com/Effect-TS/effect/commit/00b4eb1ece12a16e222e6220965bb4024d6752ac) Thanks @gcanti! - Schema: more precise return types when filters are involved.\n\n  **Example** (with `Schema.maxLength`)\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  //      ┌─── Schema.filter<Schema.Schema<string, string, never>>\n  //      ▼\n  const schema = Schema.String.pipe(Schema.maxLength(10))\n\n  // Schema<string, string, never>\n  schema.from\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  //      ┌─── Schema.filter<typeof Schema.String>\n  //      ▼\n  const schema = Schema.String.pipe(Schema.maxLength(10))\n\n  // typeof Schema.String\n  schema.from\n  ```\n\n  String filters:\n  - `maxLength`\n  - `minLength`\n  - `length`\n  - `pattern`\n  - `startsWith`\n  - `endsWith`\n  - `includes`\n  - `lowercased`\n  - `capitalized`\n  - `uncapitalized`\n  - `uppercased`\n  - `nonEmptyString`\n  - `trimmed`\n\n  Number filters:\n  - `finite`\n  - `greaterThan`\n  - `greaterThanOrEqualTo`\n  - `lessThan`\n  - `lessThanOrEqualTo`\n  - `int`\n  - `multipleOf`\n  - `between`\n  - `nonNaN`\n  - `positive`\n  - `negative`\n  - `nonPositive`\n  - `nonNegative`\n\n  BigInt filters:\n  - `greaterThanBigInt`\n  - `greaterThanOrEqualToBigInt`\n  - `lessThanBigInt`\n  - `lessThanOrEqualToBigInt`\n  - `betweenBigInt`\n  - `positiveBigInt`\n  - `negativeBigInt`\n  - `nonNegativeBigInt`\n  - `nonPositiveBigInt`\n\n  Duration filters:\n  - `lessThanDuration`\n  - `lessThanOrEqualToDuration`\n  - `greaterThanDuration`\n  - `greaterThanOrEqualToDuration`\n  - `betweenDuration`\n\n  Array filters:\n  - `minItems`\n  - `maxItems`\n  - `itemsCount`\n\n  Date filters:\n  - `validDate`\n  - `lessThanDate`\n  - `lessThanOrEqualToDate`\n  - `greaterThanDate`\n  - `greaterThanOrEqualToDate`\n  - `betweenDate`\n\n  BigDecimal filters:\n  - `greaterThanBigDecimal`\n  - `greaterThanOrEqualToBigDecimal`\n  - `lessThanBigDecimal`\n  - `lessThanOrEqualToBigDecimal`\n  - `positiveBigDecimal`\n  - `nonNegativeBigDecimal`\n  - `negativeBigDecimal`\n  - `nonPositiveBigDecimal`\n  - `betweenBigDecimal`\n\n- [#4508](https://github.com/Effect-TS/effect/pull/4508) [`f2aee98`](https://github.com/Effect-TS/effect/commit/f2aee989b0a600900ce83e7f460d02908620c80f) Thanks @gcanti! - Schema: More Accurate Return Types for `ArrayEnsure` and `NonEmptyArrayEnsure`.\n\n  **Before**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema1 = Schema.ArrayEnsure(Schema.String)\n\n  // @ts-expect-error: Property 'from' does not exist\n  schema1.from\n\n  const schema2 = Schema.NonEmptyArrayEnsure(Schema.String)\n\n  // @ts-expect-error: Property 'from' does not exist\n  schema2.from\n  ```\n\n  **After**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema1 = Schema.ArrayEnsure(Schema.String)\n\n  //        ┌─── Schema.Union<[typeof Schema.String, Schema.Array$<typeof Schema.String>]>\n  //        ▼\n  schema1.from\n\n  const schema2 = Schema.NonEmptyArrayEnsure(Schema.String)\n\n  //        ┌─── Schema.Union<[typeof Schema.String, Schema.NonEmptyArray<typeof Schema.String>]>\n  //        ▼\n  schema2.from\n  ```\n\n- [#4509](https://github.com/Effect-TS/effect/pull/4509) [`fb798eb`](https://github.com/Effect-TS/effect/commit/fb798eb9061f1191badc017d1aa649360254da20) Thanks @gcanti! - Schema: More Accurate Return Types for:\n  - `transformLiteral`\n  - `clamp`\n  - `clampBigInt`\n  - `clampDuration`\n  - `clampBigDecimal`\n  - `head`\n  - `headNonEmpty`\n  - `headOrElse`\n\n- [#4524](https://github.com/Effect-TS/effect/pull/4524) [`2251b15`](https://github.com/Effect-TS/effect/commit/2251b1528810bb695b37ce388b653cec0c5bf80c) Thanks @gcanti! - Schema: More Accurate Return Type for `parseNumber`.\n\n  **Before**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.parseNumber(Schema.String)\n\n  //      ┌─── Schema<string>\n  //      ▼\n  schema.from\n  ```\n\n  **After**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.parseNumber(Schema.String)\n\n  //      ┌─── typeof Schema.String\n  //      ▼\n  schema.from\n  ```\n\n- [#4483](https://github.com/Effect-TS/effect/pull/4483) [`2e15c1e`](https://github.com/Effect-TS/effect/commit/2e15c1e33648add0b29fe274fbcb7294b7515085) Thanks @mikearnaldi! - Fix nested batching\n\n- [#4514](https://github.com/Effect-TS/effect/pull/4514) [`a4979db`](https://github.com/Effect-TS/effect/commit/a4979db021aef16e731be64df196b72088fc4376) Thanks @gcanti! - Schema: add missing `from` property to `brand` interface.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.String.pipe(Schema.brand(\"my-brand\"))\n\n  // @ts-expect-error: Property 'from' does not exist\n  schema.from\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.String.pipe(Schema.brand(\"my-brand\"))\n\n  //      ┌─── typeof Schema.String\n  //      ▼\n  schema.from\n  ```\n\n- [#4496](https://github.com/Effect-TS/effect/pull/4496) [`b74255a`](https://github.com/Effect-TS/effect/commit/b74255a304ad49d60bedb1a260fd697f370af27a) Thanks @tim-smart! - ensure fibers can't be added to Fiber{Handle,Set,Map} during closing\n\n- [#4419](https://github.com/Effect-TS/effect/pull/4419) [`d7f6a5c`](https://github.com/Effect-TS/effect/commit/d7f6a5c7d26c1963dcd864ca62360d20d08c7b49) Thanks @KhraksMamtsov! - Fix Context.Tag unification\n\n- [#4495](https://github.com/Effect-TS/effect/pull/4495) [`9dd8979`](https://github.com/Effect-TS/effect/commit/9dd8979e940915b1cc1b1f264f3d019c77a65a02) Thanks @KhraksMamtsov! - Simplify `sortWith`, `sort`, `reverse`, `sortBy`, `unzip`, `dedupe` signatures in Array module\n\n- [#4507](https://github.com/Effect-TS/effect/pull/4507) [`477b488`](https://github.com/Effect-TS/effect/commit/477b488284f47c5469d7fba3e4065fb7e3b6556e) Thanks @gcanti! - Schema: More Accurate Return Type for `parseJson(schema)`.\n\n  **Before**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  //      ┌─── Schema.SchemaClass<{ readonly a: number; }, string>\n  //      ▼\n  const schema = Schema.parseJson(\n    Schema.Struct({\n      a: Schema.NumberFromString\n    })\n  )\n\n  // @ts-expect-error: Property 'to' does not exist\n  schema.to\n  ```\n\n  **After**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  //      ┌─── Schema.transform<Schema.SchemaClass<unknown, string, never>, Schema.Struct<{ a: typeof Schema.NumberFromString; }>>\n  //      ▼\n  const schema = Schema.parseJson(\n    Schema.Struct({\n      a: Schema.NumberFromString\n    })\n  )\n\n  //      ┌─── Schema.Struct<{ a: typeof Schema.NumberFromString; }>\n  //      ▼\n  schema.to\n  ```\n\n- [#4519](https://github.com/Effect-TS/effect/pull/4519) [`10932cb`](https://github.com/Effect-TS/effect/commit/10932cbf58fc721ada631cebec42f773ce96d3cc) Thanks @gcanti! - Refactor `JSONSchema` to use `additionalProperties` instead of `patternProperties` for simple records, closes #4518.\n\n  This update improves how records are represented in JSON Schema by replacing `patternProperties` with `additionalProperties`, resolving issues in OpenAPI schema generation.\n\n  **Why the change?**\n  - **Fixes OpenAPI issues** – Previously, records were represented using `patternProperties`, which caused problems with OpenAPI tools.\n  - **Better schema compatibility** – Some tools, like `openapi-ts`, struggled with `patternProperties`, generating `Record<string, never>` instead of the correct type.\n  - **Fixes missing example values** – When using `patternProperties`, OpenAPI failed to generate proper response examples, displaying only `{}`.\n  - **Simplifies schema modification** – Users previously had to manually fix schemas with `OpenApi.Transform`, which was messy and lacked type safety.\n\n  **Before**\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Record({ key: Schema.String, value: Schema.Number })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [],\n    \"properties\": {},\n    \"patternProperties\": {\n      \"\": { // ❌ Empty string pattern\n        \"type\": \"number\"\n      }\n    }\n  }\n  */\n  ```\n\n  **After**\n\n  Now, `additionalProperties` is used instead, which properly represents an open-ended record:\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Record({ key: Schema.String, value: Schema.Number })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [],\n    \"properties\": {},\n    \"additionalProperties\": { // ✅ Represents unrestricted record keys\n      \"type\": \"number\"\n    }\n  }\n  */\n  ```\n\n- [#4501](https://github.com/Effect-TS/effect/pull/4501) [`9f6c784`](https://github.com/Effect-TS/effect/commit/9f6c78468b3b5e9ebfc38ffdfb70702901ee977b) Thanks @gcanti! - Schema: Add Missing `declare` API Interface to Expose Type Parameters.\n\n  **Example**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.OptionFromSelf(Schema.String)\n\n  //       ┌─── readonly [typeof Schema.String]\n  //       ▼\n  schema.typeParameters\n  ```\n\n- [#4487](https://github.com/Effect-TS/effect/pull/4487) [`2c639ec`](https://github.com/Effect-TS/effect/commit/2c639ecee332de4266e36022c989c35ae4e02105) Thanks @gcanti! - Schema: more precise return types when transformations are involved.\n  - `Chunk`\n  - `NonEmptyChunk`\n  - `Redacted`\n  - `Option`\n  - `OptionFromNullOr`\n  - `OptionFromUndefinedOr`\n  - `OptionFromNullishOr`\n  - `Either`\n  - `EitherFromUnion`\n  - `ReadonlyMap`\n  - `Map`\n  - `HashMap`\n  - `ReadonlySet`\n  - `Set`\n  - `HashSet`\n  - `List`\n  - `Cause`\n  - `Exit`\n  - `SortedSet`\n  - `head`\n  - `headNonEmpty`\n  - `headOrElse`\n\n  **Example** (with `Schema.Chunk`)\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Chunk(Schema.Number)\n\n  // Property 'from' does not exist on type 'Chunk<typeof Number$>'\n  schema.from\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Chunk(Schema.Number)\n\n  // Schema.Array$<typeof Schema.Number>\n  schema.from\n  ```\n\n- [#4492](https://github.com/Effect-TS/effect/pull/4492) [`886aaa8`](https://github.com/Effect-TS/effect/commit/886aaa81e06dfd3cd9391e8ea987d8cd5ada1124) Thanks @gcanti! - Schema: Improve `Literal` return type — now returns `SchemaClass` instead of `Schema`\n\n## 3.13.2\n\n### Patch Changes\n\n- [#4472](https://github.com/Effect-TS/effect/pull/4472) [`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f) Thanks @gcanti! - Fix `Schema.Enums` `toString()` method to display correct enum values.\n\n  Now, `toString()` correctly displays the actual enum values instead of internal numeric indices.\n\n  **Before**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  enum Fruits {\n    Apple = \"apple\",\n    Banana = \"banana\",\n    Cantaloupe = 0\n  }\n\n  const schema = Schema.Enums(Fruits)\n\n  console.log(String(schema))\n  // Output: <enum 3 value(s): 0 | 1 | 2> ❌ (incorrect)\n  ```\n\n  **After**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  enum Fruits {\n    Apple = \"apple\",\n    Banana = \"banana\",\n    Cantaloupe = 0\n  }\n\n  const schema = Schema.Enums(Fruits)\n\n  console.log(String(schema))\n  // Output: <enum 3 value(s): \"apple\" | \"banana\" | 0> ✅ (correct)\n  ```\n\n## 3.13.1\n\n### Patch Changes\n\n- [#4454](https://github.com/Effect-TS/effect/pull/4454) [`b56a211`](https://github.com/Effect-TS/effect/commit/b56a2110569fd0ec0b57ac137743e926d49f51cc) Thanks @FizzyElt! - fix Option filterMap example\n\n## 3.13.0\n\n### Minor Changes\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`8baef83`](https://github.com/Effect-TS/effect/commit/8baef83e7ff0b7bc0738b680e1ef013065386cff) Thanks @tim-smart! - add Promise based apis to Fiber{Handle,Set,Map} modules\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`655bfe2`](https://github.com/Effect-TS/effect/commit/655bfe29e44cc3f0fb9b4e53038f50b891c188df) Thanks @gcanti! - Add `Effect.transposeOption`, closes #3142.\n\n  Converts an `Option` of an `Effect` into an `Effect` of an `Option`.\n\n  **Details**\n\n  This function transforms an `Option<Effect<A, E, R>>` into an\n  `Effect<Option<A>, E, R>`. If the `Option` is `None`, the resulting `Effect`\n  will immediately succeed with a `None` value. If the `Option` is `Some`, the\n  inner `Effect` will be executed, and its result wrapped in a `Some`.\n\n  **Example**\n\n  ```ts\n  import { Effect, Option } from \"effect\"\n\n  //      ┌─── Option<Effect<number, never, never>>\n  //      ▼\n  const maybe = Option.some(Effect.succeed(42))\n\n  //      ┌─── Effect<Option<number>, never, never>\n  //      ▼\n  const result = Effect.transposeOption(maybe)\n\n  console.log(Effect.runSync(result))\n  // Output: { _id: 'Option', _tag: 'Some', value: 42 }\n  ```\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`d90cbc2`](https://github.com/Effect-TS/effect/commit/d90cbc274e2742d18671fe65aa4764c057eb6cba) Thanks @indietyp! - Add `Effect.whenLogLevel`, which conditionally executes an effect if the specified log level is enabled\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`75632bd`](https://github.com/Effect-TS/effect/commit/75632bd44b8025101d652ccbaeef898c7086c91c) Thanks @tim-smart! - add RcMap.touch, for reseting the idle timeout for an item\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`c874a2e`](https://github.com/Effect-TS/effect/commit/c874a2e4b17e9d71904ca8375bb77b020975cb1d) Thanks @LaureRC! - Add HashMap.some\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`bf865e5`](https://github.com/Effect-TS/effect/commit/bf865e5833f77fd8f6c06944ca9d507b54488301) Thanks @tim-smart! - allow accessing args in Effect.fn pipe\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`f98b2b7`](https://github.com/Effect-TS/effect/commit/f98b2b7592cf20f9d85313e7f1e964cb65878138) Thanks @tim-smart! - add RcMap.invalidate api, for removing a resource from an RcMap\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`de8ce92`](https://github.com/Effect-TS/effect/commit/de8ce924923eaa4e1b761a97eb45ec967389f3d5) Thanks @mikearnaldi! - Add Layer.updateService mirroring Effect.updateService\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`db426a5`](https://github.com/Effect-TS/effect/commit/db426a5fb41ab84d18e3c8753a7329b4de544245) Thanks @KhraksMamtsov! - `Differ` implements `Pipeable`\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`6862444`](https://github.com/Effect-TS/effect/commit/6862444094906ad4f2cb077ff3b9cc0b73880c8c) Thanks @thewilkybarkid! - Make it easy to convert a DateTime.Zoned to a DateTime.Utc\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`5fc8a90`](https://github.com/Effect-TS/effect/commit/5fc8a90ba46a5fd9f3b643f0b5aeadc69d717339) Thanks @gcanti! - Add missing `Either.void` constructor.\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`546a492`](https://github.com/Effect-TS/effect/commit/546a492e60eb2b8b048a489a474b934ea0877005) Thanks @vinassefranche! - Add `HashMap.toValues` and `HashSet.toValues` getters\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`65c4796`](https://github.com/Effect-TS/effect/commit/65c47966ce39055f02cf5c808daabb3ea6442b0b) Thanks @tim-smart! - add {FiberHandle,FiberSet,FiberMap}.awaitEmpty apis\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`9760fdc`](https://github.com/Effect-TS/effect/commit/9760fdc37bdaef9da8b150e46b86ddfbe2ad9221) Thanks @gcanti! - Schema: Add `standardSchemaV1` API to Generate a [Standard Schema v1](https://standardschema.dev/).\n\n  **Example**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    name: Schema.String\n  })\n\n  //      ┌─── StandardSchemaV1<{ readonly name: string; }>\n  //      ▼\n  const standardSchema = Schema.standardSchemaV1(schema)\n  ```\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`5b471e7`](https://github.com/Effect-TS/effect/commit/5b471e7d4317e8ee5d72bbbd3e0c9775160949ab) Thanks @fubhy! - Added `Duration.formatIso` and `Duration.fromIso` for formatting and parsing ISO8601 durations.\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`4f810cc`](https://github.com/Effect-TS/effect/commit/4f810cc2770e9f1f266851d2cb6257112c12af49) Thanks @tim-smart! - add Effect.filterEffect\\* apis\n\n  #### Effect.filterEffectOrElse\n\n  Filters an effect with an effectful predicate, falling back to an alternative\n  effect if the predicate fails.\n\n  ```ts\n  import { Effect, pipe } from \"effect\"\n\n  // Define a user interface\n  interface User {\n    readonly name: string\n  }\n\n  // Simulate an asynchronous authentication function\n  declare const auth: () => Promise<User | null>\n\n  const program = pipe(\n    Effect.promise(() => auth()),\n    // Use filterEffectOrElse with an effectful predicate\n    Effect.filterEffectOrElse({\n      predicate: (user) => Effect.succeed(user !== null),\n      orElse: (user) => Effect.fail(new Error(`Unauthorized user: ${user}`))\n    })\n  )\n  ```\n\n  #### Effect.filterEffectOrFail\n\n  Filters an effect with an effectful predicate, failing with a custom error if the predicate fails.\n\n  ```ts\n  import { Effect, pipe } from \"effect\"\n\n  // Define a user interface\n  interface User {\n    readonly name: string\n  }\n\n  // Simulate an asynchronous authentication function\n  declare const auth: () => Promise<User | null>\n\n  const program = pipe(\n    Effect.promise(() => auth()),\n    // Use filterEffectOrFail with an effectful predicate\n    Effect.filterEffectOrFail({\n      predicate: (user) => Effect.succeed(user !== null),\n      orFailWith: (user) => Effect.fail(new Error(`Unauthorized user: ${user}`))\n    })\n  )\n  ```\n\n### Patch Changes\n\n- [#4280](https://github.com/Effect-TS/effect/pull/4280) [`cf8b2dd`](https://github.com/Effect-TS/effect/commit/cf8b2dd112f8e092ed99d78fd728db0f91c29050) Thanks @KhraksMamtsov! - `Trie<out A>` type annotations have been aligned. The type parameter was made covariant because the structure is immutable.\n\n## 3.12.12\n\n### Patch Changes\n\n- [#4440](https://github.com/Effect-TS/effect/pull/4440) [`4018eae`](https://github.com/Effect-TS/effect/commit/4018eaed2733241676ddb8c52416f463a8c32e35) Thanks @gcanti! - Schema: add missing support for tuple annotations in `TaggedRequest`.\n\n- [#4439](https://github.com/Effect-TS/effect/pull/4439) [`543d36d`](https://github.com/Effect-TS/effect/commit/543d36d1a11452560b01ab966a82529ad5fee8c9) Thanks @gcanti! - Schedule: fix unsafe `tapOutput` signature.\n\n  Previously, `tapOutput` allowed using an output type that wasn't properly inferred, leading to potential runtime errors. Now, TypeScript correctly detects mismatches at compile time, preventing unexpected crashes.\n\n  **Before (Unsafe, Causes Runtime Error)**\n\n  ```ts\n  import { Effect, Schedule, Console } from \"effect\"\n\n  const schedule = Schedule.once.pipe(\n    Schedule.as<number | string>(1),\n    Schedule.tapOutput((s: string) => Console.log(s.trim())) // ❌ Runtime error\n  )\n\n  Effect.runPromise(Effect.void.pipe(Effect.schedule(schedule)))\n  // throws: TypeError: s.trim is not a function\n  ```\n\n  **After (Safe, Catches Type Error at Compile Time)**\n\n  ```ts\n  import { Console, Schedule } from \"effect\"\n\n  const schedule = Schedule.once.pipe(\n    Schedule.as<number | string>(1),\n    // ✅ Type Error: Type 'number' is not assignable to type 'string'\n    Schedule.tapOutput((s: string) => Console.log(s.trim()))\n  )\n  ```\n\n- [#4447](https://github.com/Effect-TS/effect/pull/4447) [`f70a65a`](https://github.com/Effect-TS/effect/commit/f70a65ac80c6635d80b12beaf4d32a9cc59fa143) Thanks @gcanti! - Preserve function `length` property in `Effect.fn` / `Effect.fnUntraced`, closes #4435\n\n  Previously, functions created with `Effect.fn` and `Effect.fnUntraced` always had a `.length` of `0`, regardless of their actual number of parameters. This has been fixed so that the `length` property correctly reflects the expected number of arguments.\n\n  **Before**\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  const fn1 = Effect.fn(\"fn1\")(function* (n: number) {\n    return n\n  })\n\n  console.log(fn1.length)\n  // Output: 0 ❌ (incorrect)\n\n  const fn2 = Effect.fnUntraced(function* (n: number) {\n    return n\n  })\n\n  console.log(fn2.length)\n  // Output: 0 ❌ (incorrect)\n  ```\n\n  **After**\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  const fn1 = Effect.fn(\"fn1\")(function* (n: number) {\n    return n\n  })\n\n  console.log(fn1.length)\n  // Output: 1 ✅ (correct)\n\n  const fn2 = Effect.fnUntraced(function* (n: number) {\n    return n\n  })\n\n  console.log(fn2.length)\n  // Output: 1 ✅ (correct)\n  ```\n\n- [#4422](https://github.com/Effect-TS/effect/pull/4422) [`ba409f6`](https://github.com/Effect-TS/effect/commit/ba409f69c41aeaa29e475c0630735726eaf4dbac) Thanks @mikearnaldi! - Fix Context.Tag inference using explicit generics\n\n- [#4432](https://github.com/Effect-TS/effect/pull/4432) [`3d2e356`](https://github.com/Effect-TS/effect/commit/3d2e3565e8a43d1bdb5daee8db3b90f56d71d859) Thanks @tim-smart! - use Map for Scope finalizers, to ensure they are always added\n\n## 3.12.11\n\n### Patch Changes\n\n- [#4430](https://github.com/Effect-TS/effect/pull/4430) [`b6a032f`](https://github.com/Effect-TS/effect/commit/b6a032f07bffa020a848c813881879395134fa20) Thanks @tim-smart! - ensure Channel executor catches defects in doneHalt\n\n- [#4426](https://github.com/Effect-TS/effect/pull/4426) [`42ddd5f`](https://github.com/Effect-TS/effect/commit/42ddd5f144ce9f9d94a036679ebbd626446d37f5) Thanks @gcanti! - Schema: add missing `description` annotation to `BooleanFromString`.\n\n- [#4404](https://github.com/Effect-TS/effect/pull/4404) [`2fe447c`](https://github.com/Effect-TS/effect/commit/2fe447c6354d334f9c591b8a8481818f5f0e797e) Thanks @gcanti! - Update `forEach` function in `Chunk` to include missing index parameter.\n\n## 3.12.10\n\n### Patch Changes\n\n- [#4412](https://github.com/Effect-TS/effect/pull/4412) [`e30f132`](https://github.com/Effect-TS/effect/commit/e30f132c336c9d0760bad39f82a55c7ce5159eb7) Thanks @KhraksMamtsov! - Fix STM unification\n\n- [#4403](https://github.com/Effect-TS/effect/pull/4403) [`33fa667`](https://github.com/Effect-TS/effect/commit/33fa667c2623be1026e1ccee91bd44f73b09020a) Thanks @gcanti! - Duration: fix `format` output when the input is zero.\n\n  Before\n\n  ```ts\n  import { Duration } from \"effect\"\n\n  console.log(Duration.format(Duration.zero))\n  // Output: \"\"\n  ```\n\n  After\n\n  ```ts\n  import { Duration } from \"effect\"\n\n  console.log(Duration.format(Duration.zero))\n  // Output: \"0\"\n  ```\n\n- [#4411](https://github.com/Effect-TS/effect/pull/4411) [`87f5f28`](https://github.com/Effect-TS/effect/commit/87f5f2842e4196cb88d13f10f443ff0567e82832) Thanks @gcanti! - Enhance `TagClass` and `ReferenceClass` to enforce `key` type narrowing, closes #4409.\n\n  The `key` property in `TagClass` and `ReferenceClass` now correctly retains its specific string value, just like in `Effect.Service`\n\n  ```ts\n  import { Context, Effect } from \"effect\"\n\n  // -------------------------------------------------------------------------------------\n  // `key` field\n  // -------------------------------------------------------------------------------------\n\n  class A extends Effect.Service<A>()(\"A\", { succeed: { a: \"value\" } }) {}\n\n  // $ExpectType \"A\"\n  A.key\n\n  class B extends Context.Tag(\"B\")<B, { a: \"value\" }>() {}\n\n  // $ExpectType \"B\"\n  B.key\n\n  class C extends Context.Reference<C>()(\"C\", { defaultValue: () => 0 }) {}\n\n  // $ExpectType \"C\"\n  C.key\n  ```\n\n- [#4397](https://github.com/Effect-TS/effect/pull/4397) [`4dbd170`](https://github.com/Effect-TS/effect/commit/4dbd170538e8fb7a36aa7c469c6f93b6c7000091) Thanks @thewilkybarkid! - Make Array.makeBy dual\n\n## 3.12.9\n\n### Patch Changes\n\n- [#4392](https://github.com/Effect-TS/effect/pull/4392) [`1b4a4e9`](https://github.com/Effect-TS/effect/commit/1b4a4e904ef5227ec7d9114d4e417eca19eed940) Thanks @gcanti! - Fix internal import in Schema.ts, closes #4391\n\n## 3.12.8\n\n### Patch Changes\n\n- [#4341](https://github.com/Effect-TS/effect/pull/4341) [`766113c`](https://github.com/Effect-TS/effect/commit/766113c0ea3512cdb887650ead8ba314236e22ee) Thanks @fubhy! - Improve `Duration.decode` Handling of High-Resolution Time\n  - **Ensured Immutability**: Added the `readonly` modifier to `[seconds: number, nanos: number]` in `DurationInput` to prevent accidental modifications.\n  - **Better Edge Case Handling**: Now correctly processes special values like `-Infinity` and `NaN` when they appear in the tuple representation of duration.\n\n- [#4333](https://github.com/Effect-TS/effect/pull/4333) [`712277f`](https://github.com/Effect-TS/effect/commit/712277f949052a24b46e4aa234063a6abf395c90) Thanks @gcanti! - Cron: `unsafeParse` now throws a more informative error instead of a generic one\n\n- [#4387](https://github.com/Effect-TS/effect/pull/4387) [`f269122`](https://github.com/Effect-TS/effect/commit/f269122508693b111142994dd48698ddc75f3d69) Thanks @KhraksMamtsov! - A more precise signature has been applied for `Effect.schedule`\n\n- [#4351](https://github.com/Effect-TS/effect/pull/4351) [`430c846`](https://github.com/Effect-TS/effect/commit/430c846cbac05b187e3d24ac8dfee0cf22506f7c) Thanks @tim-smart! - fix Layer.scope types to correctly use the Scope tag identifier\n\n- [#4344](https://github.com/Effect-TS/effect/pull/4344) [`7b03057`](https://github.com/Effect-TS/effect/commit/7b03057507d2dab5e6793beb9c578dedaaeb15fe) Thanks @IMax153! - Expose `Schedule.isSchedule`\n\n- [#4313](https://github.com/Effect-TS/effect/pull/4313) [`a9c94c8`](https://github.com/Effect-TS/effect/commit/a9c94c807755610831211a686d2fad849ab38eb4) Thanks @gcanti! - Schema: Update `Duration` Encoding to a Tagged Union Format.\n\n  This changeset fixes the `Duration` schema to support all possible duration types, including finite, infinite, and nanosecond durations. The encoding format has been updated from a tuple (`readonly [seconds: number, nanos: number]`) to a tagged union.\n\n  This update introduces a change to the encoding format. The previous tuple representation is replaced with a more expressive tagged union, which accommodates all duration types:\n\n  ```ts\n  type DurationEncoded =\n    | {\n        readonly _tag: \"Millis\"\n        readonly millis: number\n      }\n    | {\n        readonly _tag: \"Nanos\"\n        readonly nanos: string\n      }\n    | {\n        readonly _tag: \"Infinity\"\n      }\n  ```\n\n  **Rationale**\n\n  The `Duration` schema is primarily used to encode durations for transmission. The new tagged union format ensures clear and precise encoding for:\n  - Finite durations, such as milliseconds.\n  - Infinite durations, such as `Duration.infinity`.\n  - Nanosecond durations.\n\n  **Example**\n\n  ```ts\n  import { Duration, Schema } from \"effect\"\n\n  // Encoding a finite duration in milliseconds\n  console.log(Schema.encodeSync(Schema.Duration)(Duration.millis(1000)))\n  // Output: { _tag: 'Millis', millis: 1000 }\n\n  // Encoding an infinite duration\n  console.log(Schema.encodeSync(Schema.Duration)(Duration.infinity))\n  // Output: { _tag: 'Infinity' }\n\n  // Encoding a duration in nanoseconds\n  console.log(Schema.encodeSync(Schema.Duration)(Duration.nanos(1000n)))\n  // Output: { _tag: 'Nanos', nanos: '1000' }\n  ```\n\n- [#4331](https://github.com/Effect-TS/effect/pull/4331) [`107e6f0`](https://github.com/Effect-TS/effect/commit/107e6f0557a1e2d3b0dce25d62fa1e2601521752) Thanks @gcanti! - Schema: Improve encoding in `Defect` and add test for array-based defects.\n\n- [#4329](https://github.com/Effect-TS/effect/pull/4329) [`65c11b9`](https://github.com/Effect-TS/effect/commit/65c11b9266ec9447c31c26fe3ed35c73bd3b81fd) Thanks @gcanti! - Schema: Update `itemsCount` to allow `0` as a valid argument, closes #4328.\n\n- [#4330](https://github.com/Effect-TS/effect/pull/4330) [`e386d2f`](https://github.com/Effect-TS/effect/commit/e386d2f1b3ab3ac2c14ee76de11f5963d32a3df4) Thanks @gcanti! - Add missing overload for `Option.as`.\n\n- [#4352](https://github.com/Effect-TS/effect/pull/4352) [`9172efb`](https://github.com/Effect-TS/effect/commit/9172efba98bc6a82353e6ec2af61ac08f038ba64) Thanks @tim-smart! - optimize Stream.toReadableStream\n\n## 3.12.7\n\n### Patch Changes\n\n- [#4320](https://github.com/Effect-TS/effect/pull/4320) [`8dff1d1`](https://github.com/Effect-TS/effect/commit/8dff1d1bff76cdba643cad7f0bf864300f08bc61) Thanks @KhraksMamtsov! - Fix: Cannot find name 'MissingSelfGeneric'.\n\n## 3.12.6\n\n### Patch Changes\n\n- [#4307](https://github.com/Effect-TS/effect/pull/4307) [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd) Thanks @gcanti! - Schema: Enhance error messages for discriminated unions.\n\n  **Before**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Union(\n    Schema.Tuple(Schema.Literal(-1), Schema.Literal(0)).annotations({\n      identifier: \"A\"\n    }),\n    Schema.Tuple(Schema.NonNegativeInt, Schema.NonNegativeInt).annotations({\n      identifier: \"B\"\n    })\n  ).annotations({ identifier: \"AB\" })\n\n  Schema.decodeUnknownSync(schema)([-500, 0])\n  /*\n  throws:\n  ParseError: AB\n  ├─ { readonly 0: -1 }\n  │  └─ [\"0\"]\n  │     └─ Expected -1, actual -500\n  └─ B\n     └─ [0]\n        └─ NonNegativeInt\n           └─ From side refinement failure\n              └─ NonNegative\n                 └─ Predicate refinement failure\n                    └─ Expected a non-negative number, actual -500\n  */\n  ```\n\n  **After**\n\n  ```diff\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Union(\n    Schema.Tuple(Schema.Literal(-1), Schema.Literal(0)).annotations({\n      identifier: \"A\"\n    }),\n    Schema.Tuple(Schema.NonNegativeInt, Schema.NonNegativeInt).annotations({\n      identifier: \"B\"\n    })\n  ).annotations({ identifier: \"AB\" })\n\n  Schema.decodeUnknownSync(schema)([-500, 0])\n  /*\n  throws:\n  ParseError: AB\n  -├─ { readonly 0: -1 }\n  +├─ A\n  │  └─ [\"0\"]\n  │     └─ Expected -1, actual -500\n  └─ B\n     └─ [0]\n        └─ NonNegativeInt\n           └─ From side refinement failure\n              └─ NonNegative\n                 └─ Predicate refinement failure\n                    └─ Expected a non-negative number, actual -500\n  */\n  ```\n\n- [#4298](https://github.com/Effect-TS/effect/pull/4298) [`8b4e75d`](https://github.com/Effect-TS/effect/commit/8b4e75d35daea807c447ca760948a717aa66bb52) Thanks @KhraksMamtsov! - Added type-level validation for the `Effect.Service` function to ensure the `Self` generic parameter is provided. If the generic is missing, the `MissingSelfGeneric` type will be returned, indicating that the generic parameter must be specified. This improves type safety and prevents misuse of the `Effect.Service` function.\n\n  ```ts\n  type MissingSelfGeneric =\n    `Missing \\`Self\\` generic - use \\`class Self extends Service<Self>()...\\``\n  ```\n\n- [#4292](https://github.com/Effect-TS/effect/pull/4292) [`fc5e0f0`](https://github.com/Effect-TS/effect/commit/fc5e0f0d357a0051cfa01c1ede83ffdd3cb41ab1) Thanks @gcanti! - Improve `UnknownException` error messages\n\n  `UnknownException` error messages now include the name of the Effect api that\n  created the error.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  Effect.tryPromise(() =>\n    Promise.reject(new Error(\"The operation failed\"))\n  ).pipe(Effect.catchAllCause(Effect.logError), Effect.runFork)\n\n  // timestamp=2025-01-21T00:41:03.403Z level=ERROR fiber=#0 cause=\"UnknownException: An unknown error occurred in Effect.tryPromise\n  //     at fail (.../effect/packages/effect/src/internal/core-effect.ts:1654:19)\n  //     at <anonymous> (.../effect/packages/effect/src/internal/core-effect.ts:1674:26) {\n  //   [cause]: Error: The operation failed\n  //       at <anonymous> (.../effect/scratchpad/error.ts:4:24)\n  //       at .../effect/packages/effect/src/internal/core-effect.ts:1671:7\n  // }\"\n  ```\n\n- [#4309](https://github.com/Effect-TS/effect/pull/4309) [`004fd2b`](https://github.com/Effect-TS/effect/commit/004fd2bbd1459e64fb1b57f02eeb791ca5ea1ea5) Thanks @gcanti! - Schema: Enforce Finite Durations in `DurationFromNanos`.\n\n  This update ensures that `DurationFromNanos` only accepts finite durations. Previously, the schema did not explicitly enforce this constraint.\n\n  A filter has been added to validate that the duration is finite.\n\n  ```diff\n  DurationFromSelf\n  +.pipe(\n  +  filter((duration) => duration_.isFinite(duration), {\n  +    description: \"a finite duration\"\n  +  })\n  )\n  ```\n\n- [#4314](https://github.com/Effect-TS/effect/pull/4314) [`b2a31be`](https://github.com/Effect-TS/effect/commit/b2a31be85c35d891351ce4f9a2cc93ece0c257f6) Thanks @gcanti! - Duration: make `DurationValue` properties readonly.\n\n- [#4287](https://github.com/Effect-TS/effect/pull/4287) [`5514d05`](https://github.com/Effect-TS/effect/commit/5514d05b5cd586ff5868b8bd41c959e95e6c33cd) Thanks @gcanti! - Array: Fix `Either` import and correct `partition` example.\n\n- [#4301](https://github.com/Effect-TS/effect/pull/4301) [`bf5f0ae`](https://github.com/Effect-TS/effect/commit/bf5f0ae9daa0170471678e22585e8ec14ce667bb) Thanks @gcanti! - Schema: Fix `BigIntFromNumber` to enforce upper and lower bounds.\n\n  This update ensures the `BigIntFromNumber` schema adheres to safe integer limits by applying the following bounds:\n\n  ```diff\n  BigIntFromSelf\n  +  .pipe(\n  +    betweenBigInt(\n  +      BigInt(Number.MIN_SAFE_INTEGER),\n  +      BigInt(Number.MAX_SAFE_INTEGER)\n  +    )\n  +  )\n  ```\n\n- [#4228](https://github.com/Effect-TS/effect/pull/4228) [`3b19bcf`](https://github.com/Effect-TS/effect/commit/3b19bcfd3aaadb6c9253428622df524537c8e626) Thanks @fubhy! - Fixed conflicting `ParseError` tags between `Cron` and `Schema`\n\n- [#4294](https://github.com/Effect-TS/effect/pull/4294) [`b064b3b`](https://github.com/Effect-TS/effect/commit/b064b3b293615fd268cc5a5647d0981eb67750b8) Thanks @tim-smart! - ensure cause is rendered in FiberFailure\n\n- [#4307](https://github.com/Effect-TS/effect/pull/4307) [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd) Thanks @gcanti! - Schema: Add Support for Infinity in `Duration`.\n\n  This update adds support for encoding `Duration.infinity` in `Schema.Duration`.\n\n  **Before**\n\n  Attempting to encode `Duration.infinity` resulted in a `ParseError` due to the lack of support for `Infinity` in `Schema.Duration`:\n\n  ```ts\n  import { Duration, Schema } from \"effect\"\n\n  console.log(Schema.encodeUnknownSync(Schema.Duration)(Duration.infinity))\n  /*\n  throws:\n  ParseError: Duration\n  └─ Encoded side transformation failure\n     └─ HRTime\n        └─ [0]\n           └─ NonNegativeInt\n              └─ Predicate refinement failure\n                 └─ Expected an integer, actual Infinity\n  */\n  ```\n\n  **After**\n\n  The updated behavior successfully encodes `Duration.infinity` as `[ -1, 0 ]`:\n\n  ```ts\n  import { Duration, Schema } from \"effect\"\n\n  console.log(Schema.encodeUnknownSync(Schema.Duration)(Duration.infinity))\n  // Output: [ -1, 0 ]\n  ```\n\n- [#4300](https://github.com/Effect-TS/effect/pull/4300) [`f474678`](https://github.com/Effect-TS/effect/commit/f474678bf10b8f1c80e3dc096ddc7ecf20b2b23e) Thanks @gcanti! - Schema: update `pluck` type signature to respect optional fields.\n\n  **Before**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema1 = Schema.Struct({ a: Schema.optional(Schema.String) })\n\n  /*\n  const schema2: Schema.Schema<string | undefined, {\n      readonly a: string | undefined;\n  }, never>\n  */\n  const schema2 = Schema.pluck(schema1, \"a\")\n  ```\n\n  **After**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema1 = Schema.Struct({ a: Schema.optional(Schema.String) })\n\n  /*\n  const schema2: Schema.Schema<string | undefined, {\n      readonly a?: string | undefined;\n  }, never>\n  */\n  const schema2 = Schema.pluck(schema1, \"a\")\n  ```\n\n- [#4296](https://github.com/Effect-TS/effect/pull/4296) [`ee187d0`](https://github.com/Effect-TS/effect/commit/ee187d098007a402844c94d04f0cd8f07695377a) Thanks @gcanti! - fix: update `Cause.isCause` type from 'never' to 'unknown'\n\n## 3.12.5\n\n### Patch Changes\n\n- [#4273](https://github.com/Effect-TS/effect/pull/4273) [`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1) Thanks @gcanti! - Arbitrary: Fix bug adjusting array constraints for schemas with fixed and rest elements\n\n  This fix ensures that when a schema includes both fixed elements and a rest element, the constraints for the array are correctly adjusted. The adjustment now subtracts the number of values generated by the fixed elements from the overall constraints.\n\n- [#4259](https://github.com/Effect-TS/effect/pull/4259) [`507d546`](https://github.com/Effect-TS/effect/commit/507d546bd49db31000425fb5da88c434e4291bea) Thanks @gcanti! - Schema: improve error messages for invalid transformations\n\n  **Before**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  Schema.decodeUnknownSync(Schema.NumberFromString)(\"a\")\n  /*\n  throws:\n  ParseError: NumberFromString\n  └─ Transformation process failure\n     └─ Expected NumberFromString, actual \"a\"\n  */\n  ```\n\n  **After**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  Schema.decodeUnknownSync(Schema.NumberFromString)(\"a\")\n  /*\n  throws:\n  ParseError: NumberFromString\n  └─ Transformation process failure\n     └─ Unable to decode \"a\" into a number\n  */\n  ```\n\n- [#4273](https://github.com/Effect-TS/effect/pull/4273) [`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1) Thanks @gcanti! - Schema: Extend Support for Array filters, closes #4269.\n\n  Added support for `minItems`, `maxItems`, and `itemsCount` to all schemas where `A` extends `ReadonlyArray`, including `NonEmptyArray`.\n\n  **Example**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  // Previously, this would have caused an error\n  const schema = Schema.NonEmptyArray(Schema.String).pipe(Schema.maxItems(2))\n  ```\n\n- [#4257](https://github.com/Effect-TS/effect/pull/4257) [`8db239b`](https://github.com/Effect-TS/effect/commit/8db239b9c869a3707f6566b9d9dbdf53c4df03fc) Thanks @gcanti! - Schema: Correct `BigInt` and `BigIntFromNumber` identifier annotations to follow naming conventions\n\n- [#4276](https://github.com/Effect-TS/effect/pull/4276) [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be) Thanks @tim-smart! - fix formatting of time zone offsets that round to 60 minutes\n\n- [#4276](https://github.com/Effect-TS/effect/pull/4276) [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be) Thanks @tim-smart! - ensure DateTimeZonedFromSelf arbitrary generates in the range supported by the time zone database\n\n- [#4267](https://github.com/Effect-TS/effect/pull/4267) [`3179a9f`](https://github.com/Effect-TS/effect/commit/3179a9f65d23369a6a9a1f80f7750566dd28df22) Thanks @tim-smart! - ensure DateTime.Zoned produces valid dates\n\n- [#4264](https://github.com/Effect-TS/effect/pull/4264) [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e) Thanks @gcanti! - Relocate the `Issue` definition from `platform/HttpApiError` to `Schema` (renamed as `ArrayFormatterIssue`).\n\n- [#4266](https://github.com/Effect-TS/effect/pull/4266) [`1fcbe55`](https://github.com/Effect-TS/effect/commit/1fcbe55345042d8468f6a98c84081bd00b6bcf5a) Thanks @gcanti! - Schema: Replace the `TimeZoneFromSelf` interface with a class definition and fix the arbitraries for `DateTimeUtcFromSelf` and `DateTimeZonedFromSelf` (`fc.date({ noInvalidDate: true })`).\n\n- [#4279](https://github.com/Effect-TS/effect/pull/4279) [`d9a63d9`](https://github.com/Effect-TS/effect/commit/d9a63d9d385653865954cac895065360d54cc56b) Thanks @tim-smart! - improve performance of Effect.forkIn\n\n## 3.12.4\n\n### Patch Changes\n\n- [#4231](https://github.com/Effect-TS/effect/pull/4231) [`5b50ea4`](https://github.com/Effect-TS/effect/commit/5b50ea4a10cf9acd51f9624b2474d9d5ded74019) Thanks @KhraksMamtsov! - fix `Layer.retry` and `MetricPolling.retry` signatures\n\n- [#4253](https://github.com/Effect-TS/effect/pull/4253) [`c170a68`](https://github.com/Effect-TS/effect/commit/c170a68b6266100774461fcd6c0e0fabb60112f2) Thanks @sukovanej! - Use non-enumerable properties for mutable fields of `DateTime` objects.\n\n- [#4255](https://github.com/Effect-TS/effect/pull/4255) [`a66c2eb`](https://github.com/Effect-TS/effect/commit/a66c2eb473245092cd41f04c2eb2b7b02cf53718) Thanks @sukovanej! - Improve DateTime type preservation\n\n## 3.12.3\n\n### Patch Changes\n\n- [#4244](https://github.com/Effect-TS/effect/pull/4244) [`d7dac48`](https://github.com/Effect-TS/effect/commit/d7dac48a477cdfeec509dbe9f33fce6a1b02b63d) Thanks @gcanti! - Improve pattern handling by merging multiple patterns into a union, closes #4243.\n\n  Previously, the algorithm always prioritized the first pattern when multiple patterns were encountered.\n\n  This fix introduces a merging strategy that combines patterns into a union (e.g., `(?:${pattern1})|(?:${pattern2})`). By doing so, all patterns have an equal chance to generate values when using `FastCheck.stringMatching`.\n\n  **Example**\n\n  ```ts\n  import { Arbitrary, FastCheck, Schema } from \"effect\"\n\n  // /^[^A-Z]*$/ (given by Lowercase) + /^0x[0-9a-f]{40}$/\n  const schema = Schema.Lowercase.pipe(Schema.pattern(/^0x[0-9a-f]{40}$/))\n\n  const arb = Arbitrary.make(schema)\n\n  // Before this fix, the first pattern would always dominate,\n  // making it impossible to generate values\n  const sample = FastCheck.sample(arb, { numRuns: 100 })\n\n  console.log(sample)\n  ```\n\n- [#4252](https://github.com/Effect-TS/effect/pull/4252) [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5) Thanks @gcanti! - Fix: Correct `Arbitrary.make` to support nested `TemplateLiteral`s.\n\n  Previously, `Arbitrary.make` did not properly handle nested `TemplateLiteral` schemas, resulting in incorrect or empty outputs. This fix ensures that nested template literals are processed correctly, producing valid arbitrary values.\n\n  **Before**\n\n  ```ts\n  import { Arbitrary, FastCheck, Schema as S } from \"effect\"\n\n  const schema = S.TemplateLiteral(\n    \"<\",\n    S.TemplateLiteral(\"h\", S.Literal(1, 2)),\n    \">\"\n  )\n\n  const arb = Arbitrary.make(schema)\n\n  console.log(FastCheck.sample(arb, { numRuns: 10 }))\n  /*\n  Output:\n  [\n    '<>', '<>', '<>',\n    '<>', '<>', '<>',\n    '<>', '<>', '<>',\n    '<>'\n  ]\n  */\n  ```\n\n  **After**\n\n  ```ts\n  import { Arbitrary, FastCheck, Schema as S } from \"effect\"\n\n  const schema = S.TemplateLiteral(\n    \"<\",\n    S.TemplateLiteral(\"h\", S.Literal(1, 2)),\n    \">\"\n  )\n\n  const arb = Arbitrary.make(schema)\n\n  console.log(FastCheck.sample(arb, { numRuns: 10 }))\n  /*\n  Output:\n  [\n    '<h2>', '<h2>',\n    '<h2>', '<h2>',\n    '<h2>', '<h1>',\n    '<h2>', '<h1>',\n    '<h1>', '<h1>'\n  ]\n  */\n  ```\n\n- [#4252](https://github.com/Effect-TS/effect/pull/4252) [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5) Thanks @gcanti! - Fix: Allow `Schema.TemplateLiteral` to handle strings with linebreaks, closes #4251.\n\n  **Before**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteral(\"a: \", Schema.String)\n\n  console.log(Schema.decodeSync(schema)(\"a: b \\n c\"))\n  // throws: ParseError: Expected `a: ${string}`, actual \"a: b \\n c\"\n  ```\n\n  **After**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteral(\"a: \", Schema.String)\n\n  console.log(Schema.decodeSync(schema)(\"a: b \\n c\"))\n  /*\n  Output:\n  a: b\n   c\n  */\n  ```\n\n## 3.12.2\n\n### Patch Changes\n\n- [#4220](https://github.com/Effect-TS/effect/pull/4220) [`734af82`](https://github.com/Effect-TS/effect/commit/734af82138e78b9c57a8355b1c6b80e80d38b222) Thanks @KhraksMamtsov! - fix inference for contravariant type-parameters\n\n- [#4212](https://github.com/Effect-TS/effect/pull/4212) [`b63c780`](https://github.com/Effect-TS/effect/commit/b63c78010893101520448ddda7019c487cf7eedd) Thanks @KhraksMamtsov! - Refine `Effect.validateAll` return type to use `NonEmptyArray` for errors.\n\n  This refinement is possible because `Effect.validateAll` guarantees that when the input iterable is non-empty, any validation failure will produce at least one error. In such cases, the errors are inherently non-empty, making it safe and accurate to represent them using a `NonEmptyArray` type. This change aligns the return type with the function's actual behavior, improving type safety and making the API more predictable for developers.\n\n- [#4219](https://github.com/Effect-TS/effect/pull/4219) [`c640d77`](https://github.com/Effect-TS/effect/commit/c640d77b33ad417876f4e8ffe8574ee6cbe5607f) Thanks @whoisandy! - fix: ManagedRuntime.Context to work when Context is of type never\n\n- [#4236](https://github.com/Effect-TS/effect/pull/4236) [`0def088`](https://github.com/Effect-TS/effect/commit/0def0887cfdb6755729a64dfd52b3b9f46b0576c) Thanks @tim-smart! - fix color option for Logger.prettyLogger\n\n## 3.12.1\n\n### Patch Changes\n\n- [#4194](https://github.com/Effect-TS/effect/pull/4194) [`302b57d`](https://github.com/Effect-TS/effect/commit/302b57d2cbf9b9ccc17450945aeebfb33cfe8d43) Thanks @KhraksMamtsov! - take concurrentFinalizers option in account in `Effect.all` combinator\n\n- [#4202](https://github.com/Effect-TS/effect/pull/4202) [`0988083`](https://github.com/Effect-TS/effect/commit/0988083d4594938590df5a287e5b27d38526dd07) Thanks @mikearnaldi! - Remove internal EffectError make sure errors are raised with Effect.fail in Effect.try\n\n- [#4185](https://github.com/Effect-TS/effect/pull/4185) [`8b46be6`](https://github.com/Effect-TS/effect/commit/8b46be6a3b8160362ab5ea9171c5e6932505125c) Thanks @jessekelly881! - fixed incorrect type declaration in LibsqlClient.layer\n\n- [#4189](https://github.com/Effect-TS/effect/pull/4189) [`bfe8027`](https://github.com/Effect-TS/effect/commit/bfe802734b450a4b4ee069d1125dd37995db2bff) Thanks @tim-smart! - ensure Effect.timeoutTo sleep is interrupted\n\n- [#4190](https://github.com/Effect-TS/effect/pull/4190) [`16dd657`](https://github.com/Effect-TS/effect/commit/16dd657033d8afac2ffea567b3c8bb27c9b249b6) Thanks @IMax153! - extend `IterableIterator` instead of `Generator` in `SingleShotGen`\n\n- [#4196](https://github.com/Effect-TS/effect/pull/4196) [`39db211`](https://github.com/Effect-TS/effect/commit/39db211414e90c8db8fdad7dc8ce5b4661bcfaef) Thanks @mikearnaldi! - Avoid putting symbols in global to fix incompatibility with Temporal Sandbox.\n\n  After speaking with James Watkins-Harvey we realized current Effect escapes the Temporal Worker sandbox that doesn't look for symbols when restoring global context in the isolate they create leading to memory leaks.\n\n## 3.12.0\n\n### Minor Changes\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`abb22a4`](https://github.com/Effect-TS/effect/commit/abb22a429b9c52c31e84856294f175d2064a9b4d) Thanks @titouancreach! - Added encodeUriComponent/decodeUriComponent for both Encoding and Schema\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`f369a89`](https://github.com/Effect-TS/effect/commit/f369a89e98bc682969803b9304adaf4557bb36c2) Thanks @vinassefranche! - Add Runtime.Runtime.Context type extractor\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`642376c`](https://github.com/Effect-TS/effect/commit/642376c63fd7d78754db991631a4d50a5dc79aa3) Thanks @tim-smart! - add non-traced overload to Effect.fn\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`3d2b7a7`](https://github.com/Effect-TS/effect/commit/3d2b7a7e942a7157afae5b1cdbc6f3fef116428e) Thanks @mikearnaldi! - Update fast-check to latest version\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`73f9c6f`](https://github.com/Effect-TS/effect/commit/73f9c6f2ff091512cf904cc54ab59965b86e87c8) Thanks @wewelll! - add DateTimeUtcFromDate schema\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`17cb451`](https://github.com/Effect-TS/effect/commit/17cb4514590e8a86263f7aed009f24da8a237342) Thanks @fubhy! - Added support for `second` granularity to `Cron`.\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`d801820`](https://github.com/Effect-TS/effect/commit/d80182060c2ee945d7e0e4728812abf9465a0d6a) Thanks @fubhy! - Added `Cron.unsafeParse` and allow passing the `Cron.parse` time zone parameter as `string`.\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1) Thanks @mikearnaldi! - add Effect.fnUntraced - an untraced version of Effect.fn\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`c11f3a6`](https://github.com/Effect-TS/effect/commit/c11f3a60a05c3b5fc8e7ce90136728154dc505b0) Thanks @QuentinJanuel! - Add Context.mergeAll to combine multiple Contexts into one.\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`618f7e0`](https://github.com/Effect-TS/effect/commit/618f7e092a1011e5090dca1e69b5e9285689654b) Thanks @tim-smart! - add span annotation to disable propagation to the tracer\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`c0ba834`](https://github.com/Effect-TS/effect/commit/c0ba834d1995cf5a8b250e4780fd43f3e3881151) Thanks @titouancreach! - Add Schema.headNonEmpty for Schema.NonEmptyArray\n\n### Patch Changes\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1) Thanks @mikearnaldi! - Carry both call-site and definition site in Effect.fn, auto-trace to anon\n\n## 3.11.10\n\n### Patch Changes\n\n- [#4176](https://github.com/Effect-TS/effect/pull/4176) [`39457d4`](https://github.com/Effect-TS/effect/commit/39457d4897d9bc7df8af5c05d352866bbeae82eb) Thanks @mikearnaldi! - Fix Stream.scoped example\n\n- [#4181](https://github.com/Effect-TS/effect/pull/4181) [`a475cc2`](https://github.com/Effect-TS/effect/commit/a475cc25fd7c9f26b27a8e98f8fbe43cc9e6ee3e) Thanks @gcanti! - Schema: Fix `withDecodingDefault` implementation to align with its signature (now removes `undefined` from the AST).\n\n  Additionally, a new constraint has been added to the signature to prevent calling `withDecodingDefault` after `withConstructorDefault`, which previously led to the following issue:\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.optional(Schema.String).pipe(\n      Schema.withConstructorDefault(() => undefined), // this is invalidated by the following call to `withDecodingDefault`\n      Schema.withDecodingDefault(() => \"\")\n    )\n  })\n  ```\n\n- [#4175](https://github.com/Effect-TS/effect/pull/4175) [`199214e`](https://github.com/Effect-TS/effect/commit/199214e21c616d8a0ccd7ed5f92e944e6c580193) Thanks @gcanti! - Schema: refactor annotations:\n  - Export internal `Uint8` schema\n  - Export internal `NonNegativeInt` schema\n  - Remove title annotations that are identical to identifiers\n  - Avoid setting a title annotation when applying branding\n  - Add more title annotations to refinements\n  - Improve `toString` output and provide more precise error messages for refinements:\n\n    Before\n\n    ```ts\n    import { Schema } from \"effect\"\n\n    const schema = Schema.Number.pipe(\n      Schema.int({ identifier: \"MyInt\" }),\n      Schema.positive()\n    )\n\n    console.log(String(schema))\n    // Output: a positive number\n\n    Schema.decodeUnknownSync(schema)(1.1)\n    /*\n    throws:\n    ParseError: a positive number\n    └─ From side refinement failure\n      └─ MyInt\n          └─ Predicate refinement failure\n            └─ Expected MyInt, actual 1.1\n    */\n    ```\n\n    After\n    - `toString` now combines all refinements with `\" & \"` instead of showing only the last one.\n    - The last message (`\"Expected ...\"`) now uses the extended description to make the error message clearer.\n\n    ```ts\n    import { Schema } from \"effect\"\n\n    const schema = Schema.Number.pipe(\n      Schema.int({ identifier: \"MyInt\" }),\n      Schema.positive()\n    )\n\n    console.log(String(schema))\n    // Output: MyInt & positive // <= all the refinements\n\n    Schema.decodeUnknownSync(schema)(1.1)\n    /*\n    throws:\n    ParseError: MyInt & positive\n    └─ From side refinement failure\n      └─ MyInt\n          └─ Predicate refinement failure\n            └─ Expected an integer, actual 1.1 // <= extended description\n    */\n    ```\n\n- [#4182](https://github.com/Effect-TS/effect/pull/4182) [`b3c160d`](https://github.com/Effect-TS/effect/commit/b3c160d7a1fdfc2d3fb2440530f1ab80efc65133) Thanks @mikearnaldi! - Replace absolute imports with relative ones\n\n## 3.11.9\n\n### Patch Changes\n\n- [#4113](https://github.com/Effect-TS/effect/pull/4113) [`1c08a0b`](https://github.com/Effect-TS/effect/commit/1c08a0b8505badcffb4d9cade5a746ea90c9557e) Thanks @thewilkybarkid! - Schema: Support template literals in `Schema.Config`.\n\n  **Example**\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  // const config: Config<`a${string}`>\n  const config = Schema.Config(\n    \"A\",\n    Schema.TemplateLiteral(Schema.Literal(\"a\"), Schema.String)\n  )\n  ```\n\n- [#4174](https://github.com/Effect-TS/effect/pull/4174) [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd) Thanks @gcanti! - Schema: Add support for `TemplateLiteral` parameters in `TemplateLiteral`, closes #4166.\n\n  This update also adds support for `TemplateLiteral` and `TemplateLiteralParser` parameters in `TemplateLiteralParser`.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteralParser(\n    \"<\",\n    Schema.TemplateLiteralParser(\"h\", Schema.Literal(1, 2)),\n    \">\"\n  )\n  /*\n  throws:\n  Error: Unsupported template literal span\n  schema (TemplateLiteral): `h${\"1\" | \"2\"}`\n  */\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  // Schema<readonly [\"<\", readonly [\"h\", 2 | 1], \">\"], \"<h2>\" | \"<h1>\", never>\n  const schema = Schema.TemplateLiteralParser(\n    \"<\",\n    Schema.TemplateLiteralParser(\"h\", Schema.Literal(1, 2)),\n    \">\"\n  )\n\n  console.log(Schema.decodeUnknownSync(schema)(\"<h1>\"))\n  // Output: [ '<', [ 'h', 1 ], '>' ]\n  ```\n\n- [#4174](https://github.com/Effect-TS/effect/pull/4174) [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd) Thanks @gcanti! - Schema: Fix bug in `TemplateLiteralParser` where unions of numeric literals were not coerced correctly.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteralParser(\"a\", Schema.Literal(1, 2))\n\n  console.log(Schema.decodeUnknownSync(schema)(\"a1\"))\n  /*\n  throws:\n  ParseError: (`a${\"1\" | \"2\"}` <-> readonly [\"a\", 1 | 2])\n  └─ Type side transformation failure\n     └─ readonly [\"a\", 1 | 2]\n        └─ [1]\n           └─ 1 | 2\n              ├─ Expected 1, actual \"1\"\n              └─ Expected 2, actual \"1\"\n  */\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteralParser(\"a\", Schema.Literal(1, 2))\n\n  console.log(Schema.decodeUnknownSync(schema)(\"a1\"))\n  // Output: [ 'a', 1 ]\n\n  console.log(Schema.decodeUnknownSync(schema)(\"a2\"))\n  // Output: [ 'a', 2 ]\n\n  console.log(Schema.decodeUnknownSync(schema)(\"a3\"))\n  /*\n  throws:\n  ParseError: (`a${\"1\" | \"2\"}` <-> readonly [\"a\", 1 | 2])\n  └─ Encoded side transformation failure\n     └─ Expected `a${\"1\" | \"2\"}`, actual \"a3\"\n  */\n  ```\n\n## 3.11.8\n\n### Patch Changes\n\n- [#4150](https://github.com/Effect-TS/effect/pull/4150) [`1a6b52d`](https://github.com/Effect-TS/effect/commit/1a6b52dcf020d36e38a7bc90b648152cf5a8ccba) Thanks @gcanti! - Arbitrary: optimize date-based refinements\n\n## 3.11.7\n\n### Patch Changes\n\n- [#4137](https://github.com/Effect-TS/effect/pull/4137) [`2408616`](https://github.com/Effect-TS/effect/commit/24086163b60b09cc6d0885bd565ef080dcbe866b) Thanks @gcanti! - Arbitrary: fix bug where refinements in declarations raised an incorrect missing annotation error, closes #4136\n\n- [#4138](https://github.com/Effect-TS/effect/pull/4138) [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e) Thanks @gcanti! - JSONSchema: ignore never members in unions.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Union(Schema.String, Schema.Never)\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"anyOf\": [\n      {\n        \"type\": \"string\"\n      },\n      {\n        \"$id\": \"/schemas/never\",\n        \"not\": {},\n        \"title\": \"never\"\n      }\n    ]\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Union(Schema.String, Schema.Never)\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\"\n  }\n  */\n  ```\n\n- [#4138](https://github.com/Effect-TS/effect/pull/4138) [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e) Thanks @gcanti! - JSONSchema: handle the `nullable` keyword for OpenAPI target, closes #4075.\n\n  Before\n\n  ```ts\n  import { OpenApiJsonSchema } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const schema = Schema.NullOr(Schema.String)\n\n  console.log(JSON.stringify(OpenApiJsonSchema.make(schema), null, 2))\n  /*\n  {\n    \"anyOf\": [\n      {\n        \"type\": \"string\"\n      },\n      {\n        \"enum\": [\n          null\n        ]\n      }\n    ]\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { OpenApiJsonSchema } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const schema = Schema.NullOr(Schema.String)\n\n  console.log(JSON.stringify(OpenApiJsonSchema.make(schema), null, 2))\n  /*\n  {\n    \"type\": \"string\",\n    \"nullable\": true\n  }\n  */\n  ```\n\n- [#4128](https://github.com/Effect-TS/effect/pull/4128) [`8d978c5`](https://github.com/Effect-TS/effect/commit/8d978c53f6fcc98d9d645ecba3e4b55d4297dd36) Thanks @gcanti! - JSONSchema: add `type` for homogeneous enum schemas, closes #4127\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Literal(\"a\", \"b\")\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"enum\": [\n      \"a\",\n      \"b\"\n    ]\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Literal(\"a\", \"b\")\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"enum\": [\n      \"a\",\n      \"b\"\n    ]\n  }\n  */\n  ```\n\n- [#4138](https://github.com/Effect-TS/effect/pull/4138) [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e) Thanks @gcanti! - JSONSchema: use `{ \"type\": \"null\" }` to represent the `null` literal\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.NullOr(Schema.String)\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"anyOf\": [\n      {\n        \"type\": \"string\"\n      },\n      {\n        \"enum\": [\n          null\n        ]\n      }\n    ]\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.NullOr(Schema.String)\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"anyOf\": [\n      {\n        \"type\": \"string\"\n      },\n      {\n        \"type\": \"null\"\n      }\n    ]\n  }\n  */\n  ```\n\n- [#4138](https://github.com/Effect-TS/effect/pull/4138) [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e) Thanks @gcanti! - JSONSchema: handle empty native enums.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  enum Empty {}\n\n  const schema = Schema.Enums(Empty)\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"$comment\": \"/schemas/enums\",\n    \"anyOf\": [] // <= invalid schema!\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  enum Empty {}\n\n  const schema = Schema.Enums(Empty)\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"$id\": \"/schemas/never\",\n    \"not\": {}\n  }\n  */\n  ```\n\n## 3.11.6\n\n### Patch Changes\n\n- [#4118](https://github.com/Effect-TS/effect/pull/4118) [`662d1ce`](https://github.com/Effect-TS/effect/commit/662d1ce6fb7da384a95888d5b2bb5605bdf3208d) Thanks @gcanti! - Allow the transformation created by the Class API to be annotated on all its components: the type side, the transformation itself, and the encoded side.\n\n  **Example**\n\n  ```ts\n  import { Schema, SchemaAST } from \"effect\"\n\n  class A extends Schema.Class<A>(\"A\")(\n    {\n      a: Schema.NonEmptyString\n    },\n    [\n      { identifier: \"TypeID\" }, // annotations for the type side\n      { identifier: \"TransformationID\" }, // annotations for the the transformation itself\n      { identifier: \"EncodedID\" } // annotations for the the encoded side\n    ]\n  ) {}\n\n  console.log(SchemaAST.getIdentifierAnnotation(A.ast.to)) // Some(\"TypeID\")\n  console.log(SchemaAST.getIdentifierAnnotation(A.ast)) // Some(\"TransformationID\")\n  console.log(SchemaAST.getIdentifierAnnotation(A.ast.from)) // Some(\"EncodedID\")\n\n  A.make({ a: \"\" })\n  /*\n  ParseError: TypeID\n  └─ [\"a\"]\n     └─ NonEmptyString\n        └─ Predicate refinement failure\n           └─ Expected NonEmptyString, actual \"\"\n  */\n\n  Schema.encodeSync(A)({ a: \"\" })\n  /*\n  ParseError: TransformationID\n  └─ Type side transformation failure\n     └─ TypeID\n        └─ [\"a\"]\n           └─ NonEmptyString\n              └─ Predicate refinement failure\n                 └─ Expected NonEmptyString, actual \"\"\n  */\n  ```\n\n- [#4126](https://github.com/Effect-TS/effect/pull/4126) [`31c62d8`](https://github.com/Effect-TS/effect/commit/31c62d83cbdcf9850a8b5331faa239601c60f78a) Thanks @gcanti! - Rewrite the Arbitrary compiler from scratch, closes #2312\n\n## 3.11.5\n\n### Patch Changes\n\n- [#4019](https://github.com/Effect-TS/effect/pull/4019) [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8) Thanks @gcanti! - Add missing `jsonSchema` annotations to the following filters:\n  - `lowercased`\n  - `capitalized`\n  - `uncapitalized`\n  - `uppercased`\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.Uppercased\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  throws:\n  Error: Missing annotation\n  details: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\n  schema (Refinement): Uppercased\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Uppercased\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  Output:\n  {\n    \"$ref\": \"#/$defs/Uppercased\",\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"$defs\": {\n      \"Uppercased\": {\n        \"type\": \"string\",\n        \"description\": \"an uppercase string\",\n        \"title\": \"Uppercased\",\n        \"pattern\": \"^[^a-z]*$\"\n      }\n    }\n  }\n  */\n  ```\n\n- [#4111](https://github.com/Effect-TS/effect/pull/4111) [`22905cf`](https://github.com/Effect-TS/effect/commit/22905cf5addfb1ff3d2a6135c52036be958ae911) Thanks @gcanti! - JSONSchema: merge refinement fragments instead of just overwriting them.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  export const schema = Schema.String.pipe(\n    Schema.startsWith(\"a\"), // <= overwritten!\n    Schema.endsWith(\"c\")\n  )\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"description\": \"a string ending with \\\"c\\\"\",\n    \"pattern\": \"^.*c$\" // <= overwritten!\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  export const schema = Schema.String.pipe(\n    Schema.startsWith(\"a\"), // <= preserved!\n    Schema.endsWith(\"c\")\n  )\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"type\": \"string\",\n    \"description\": \"a string ending with \\\"c\\\"\",\n    \"pattern\": \"^.*c$\",\n    \"allOf\": [\n      {\n        \"pattern\": \"^a\" // <= preserved!\n      }\n    ],\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n  }\n  */\n  ```\n\n- [#4019](https://github.com/Effect-TS/effect/pull/4019) [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8) Thanks @gcanti! - JSONSchema: Correct the output order when generating a JSON Schema from a Union that includes literals and primitive schemas.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Union(Schema.Literal(1, 2), Schema.String)\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"anyOf\": [\n      {\n        \"type\": \"string\"\n      },\n      {\n        \"enum\": [\n          1,\n          2\n        ]\n      }\n    ]\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Union(Schema.Literal(1, 2), Schema.String)\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"anyOf\": [\n      {\n        \"enum\": [\n          1,\n          2\n        ]\n      },\n      {\n        \"type\": \"string\"\n      }\n    ]\n  }\n  */\n  ```\n\n- [#4107](https://github.com/Effect-TS/effect/pull/4107) [`1e59e4f`](https://github.com/Effect-TS/effect/commit/1e59e4fd778da18296812a2a32f36ca8ae50f60d) Thanks @tim-smart! - remove FnEffect type to improve return type of Effect.fn\n\n- [#4108](https://github.com/Effect-TS/effect/pull/4108) [`8d914e5`](https://github.com/Effect-TS/effect/commit/8d914e504e7a22d0ea628e8af265ee450ff9530f) Thanks @gcanti! - JSONSchema: represent `never` as `{\"not\":{}}`\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Never\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  throws:\n  Error: Missing annotation\n  details: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\n  schema (NeverKeyword): never\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Never\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$id\": \"/schemas/never\",\n    \"not\": {},\n    \"title\": \"never\",\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n  }\n  */\n  ```\n\n- [#4115](https://github.com/Effect-TS/effect/pull/4115) [`03bb00f`](https://github.com/Effect-TS/effect/commit/03bb00faa74f9e168a54a8cc0828a664fbb1ab05) Thanks @tim-smart! - avoid using non-namespaced \"async\" internally\n\n- [#4019](https://github.com/Effect-TS/effect/pull/4019) [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8) Thanks @gcanti! - JSONSchema: fix special case in `parseJson` handling to target the \"to\" side of the transformation only at the top level.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.parseJson(\n    Schema.Struct({\n      a: Schema.parseJson(\n        Schema.Struct({\n          b: Schema.String\n        })\n      )\n    })\n  )\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [\n      \"a\"\n    ],\n    \"properties\": {\n      \"a\": {\n        \"type\": \"object\",\n        \"required\": [\n          \"b\"\n        ],\n        \"properties\": {\n          \"b\": {\n            \"type\": \"string\"\n          }\n        },\n        \"additionalProperties\": false\n      }\n    },\n    \"additionalProperties\": false\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.parseJson(\n    Schema.Struct({\n      a: Schema.parseJson(\n        Schema.Struct({\n          b: Schema.String\n        })\n      )\n    })\n  )\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"type\": \"object\",\n    \"required\": [\n      \"a\"\n    ],\n    \"properties\": {\n      \"a\": {\n        \"type\": \"string\",\n        \"contentMediaType\": \"application/json\"\n      }\n    },\n    \"additionalProperties\": false,\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n  }\n  */\n  ```\n\n- [#4101](https://github.com/Effect-TS/effect/pull/4101) [`14e1149`](https://github.com/Effect-TS/effect/commit/14e1149f1af5a022f06eb8c2e4ba9fec17fe7426) Thanks @gcanti! - Schema: align the `make` constructor of structs with the behavior of the Class API constructors when all fields have a default.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.propertySignature(Schema.Number).pipe(\n      Schema.withConstructorDefault(() => 0)\n    )\n  })\n\n  // TypeScript error: Expected 1-2 arguments, but got 0.ts(2554)\n  console.log(schema.make())\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.propertySignature(Schema.Number).pipe(\n      Schema.withConstructorDefault(() => 0)\n    )\n  })\n\n  console.log(schema.make())\n  // Output: { a: 0 }\n  ```\n\n- [#4019](https://github.com/Effect-TS/effect/pull/4019) [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8) Thanks @gcanti! - JSONSchema: Fix issue where `identifier` is ignored when a refinement is applied to a schema, closes #4012\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.NonEmptyString\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"description\": \"a non empty string\",\n    \"title\": \"NonEmptyString\",\n    \"minLength\": 1\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.NonEmptyString\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"$ref\": \"#/$defs/NonEmptyString\",\n    \"$defs\": {\n      \"NonEmptyString\": {\n        \"type\": \"string\",\n        \"description\": \"a non empty string\",\n        \"title\": \"NonEmptyString\",\n        \"minLength\": 1\n      }\n    }\n  }\n  */\n  ```\n\n- [#4019](https://github.com/Effect-TS/effect/pull/4019) [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8) Thanks @gcanti! - JSONSchema: Use identifier with Class APIs to create a `$ref` instead of inlining the schema.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  class A extends Schema.Class<A>(\"A\")({\n    a: Schema.String\n  }) {}\n\n  console.log(JSON.stringify(JSONSchema.make(A), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [\n      \"a\"\n    ],\n    \"properties\": {\n      \"a\": {\n        \"type\": \"string\"\n      }\n    },\n    \"additionalProperties\": false\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  class A extends Schema.Class<A>(\"A\")({\n    a: Schema.String\n  }) {}\n\n  console.log(JSON.stringify(JSONSchema.make(A), null, 2))\n  /*\n  {\n    \"$ref\": \"#/$defs/A\",\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"$defs\": {\n      \"A\": {\n        \"type\": \"object\",\n        \"required\": [\n          \"a\"\n        ],\n        \"properties\": {\n          \"a\": {\n            \"type\": \"string\"\n          }\n        },\n        \"additionalProperties\": false\n      }\n    }\n  }\n  */\n  ```\n\n## 3.11.4\n\n### Patch Changes\n\n- [#4087](https://github.com/Effect-TS/effect/pull/4087) [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2) Thanks @tim-smart! - remove use of .unsafeAsync in non-suspended contexts\n\n- [#4010](https://github.com/Effect-TS/effect/pull/4010) [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f) Thanks @fubhy! - Add support for daylight savings time transitions\n\n- [#4010](https://github.com/Effect-TS/effect/pull/4010) [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f) Thanks @fubhy! - Improved efficiency of `Cron.next` lookup\n\n## 3.11.3\n\n### Patch Changes\n\n- [#4080](https://github.com/Effect-TS/effect/pull/4080) [`90906f7`](https://github.com/Effect-TS/effect/commit/90906f7f154b12c7182e8f39e3c55ef3937db857) Thanks @gcanti! - Fix the `Schema.TemplateLiteral` output type when the arguments include a branded type.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteral(\n    \"a \",\n    Schema.String.pipe(Schema.brand(\"MyBrand\"))\n  )\n\n  // type Type = `a ${Schema.brand<typeof Schema.String, \"MyBrand\"> & string}`\n  // | `a ${Schema.brand<typeof Schema.String, \"MyBrand\"> & number}`\n  // | `a ${Schema.brand<typeof Schema.String, \"MyBrand\"> & bigint}`\n  // | `a ${Schema.brand<...> & false}`\n  // | `a ${Schema.brand<...> & true}`\n  type Type = typeof schema.Type\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteral(\n    \"a \",\n    Schema.String.pipe(Schema.brand(\"MyBrand\"))\n  )\n\n  // type Type = `a ${string & Brand<\"MyBrand\">}`\n  type Type = typeof schema.Type\n  ```\n\n- [#4076](https://github.com/Effect-TS/effect/pull/4076) [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567) Thanks @gcanti! - Schema: fix bug in `Schema.TemplateLiteralParser` resulting in a runtime error.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteralParser(\"a\", \"b\")\n  // throws TypeError: Cannot read properties of undefined (reading 'replace')\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteralParser(\"a\", \"b\")\n\n  console.log(Schema.decodeUnknownSync(schema)(\"ab\"))\n  // Output: [ 'a', 'b' ]\n  ```\n\n- [#4076](https://github.com/Effect-TS/effect/pull/4076) [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567) Thanks @gcanti! - SchemaAST: fix `TemplateLiteral` model.\n\n  Added `Literal` and `Union` as valid types.\n\n- [#4083](https://github.com/Effect-TS/effect/pull/4083) [`343b6aa`](https://github.com/Effect-TS/effect/commit/343b6aa6ac4a74276bfc7c63ccbf4a1d72bc1bed) Thanks @gcanti! - Preserve `MissingMessageAnnotation`s on property signature declarations when another field is a property signature transformation.\n\n  Before\n\n  ```ts\n  import { Console, Effect, ParseResult, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.propertySignature(Schema.String).annotations({\n      missingMessage: () => \"message1\"\n    }),\n    b: Schema.propertySignature(Schema.String)\n      .annotations({ missingMessage: () => \"message2\" })\n      .pipe(Schema.fromKey(\"c\")), // <= transformation\n    d: Schema.propertySignature(Schema.String).annotations({\n      missingMessage: () => \"message3\"\n    })\n  })\n\n  Effect.runPromiseExit(\n    Schema.decodeUnknown(schema, { errors: \"all\" })({}).pipe(\n      Effect.tapError((error) =>\n        Console.log(ParseResult.ArrayFormatter.formatErrorSync(error))\n      )\n    )\n  )\n  /*\n  Output:\n  [\n    { _tag: 'Missing', path: [ 'a' ], message: 'is missing' }, // <= wrong\n    { _tag: 'Missing', path: [ 'c' ], message: 'message2' },\n    { _tag: 'Missing', path: [ 'd' ], message: 'is missing' } // <= wrong\n  ]\n  */\n  ```\n\n  After\n\n  ```ts\n  import { Console, Effect, ParseResult, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.propertySignature(Schema.String).annotations({\n      missingMessage: () => \"message1\"\n    }),\n    b: Schema.propertySignature(Schema.String)\n      .annotations({ missingMessage: () => \"message2\" })\n      .pipe(Schema.fromKey(\"c\")), // <= transformation\n    d: Schema.propertySignature(Schema.String).annotations({\n      missingMessage: () => \"message3\"\n    })\n  })\n\n  Effect.runPromiseExit(\n    Schema.decodeUnknown(schema, { errors: \"all\" })({}).pipe(\n      Effect.tapError((error) =>\n        Console.log(ParseResult.ArrayFormatter.formatErrorSync(error))\n      )\n    )\n  )\n  /*\n  Output:\n  [\n    { _tag: 'Missing', path: [ 'a' ], message: 'message1' },\n    { _tag: 'Missing', path: [ 'c' ], message: 'message2' },\n    { _tag: 'Missing', path: [ 'd' ], message: 'message3' }\n  ]\n  */\n  ```\n\n- [#4081](https://github.com/Effect-TS/effect/pull/4081) [`afba339`](https://github.com/Effect-TS/effect/commit/afba339adc11dad56b5a3b7ca94487e58f34d613) Thanks @gcanti! - Fix the behavior of `Schema.TemplateLiteralParser` when the arguments include literals other than string literals.\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteralParser(Schema.String, 1)\n\n  console.log(Schema.decodeUnknownSync(schema)(\"a1\"))\n  /*\n  throws\n  ParseError: (`${string}1` <-> readonly [string, 1])\n  └─ Type side transformation failure\n     └─ readonly [string, 1]\n        └─ [1]\n           └─ Expected 1, actual \"1\"\n  */\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.TemplateLiteralParser(Schema.String, 1)\n\n  console.log(Schema.decodeUnknownSync(schema)(\"a1\"))\n  // Output: [ 'a', 1 ]\n  ```\n\n## 3.11.2\n\n### Patch Changes\n\n- [#4063](https://github.com/Effect-TS/effect/pull/4063) [`01cee56`](https://github.com/Effect-TS/effect/commit/01cee560b58d94b24cc20e98083251b73e658b41) Thanks @tim-smart! - Micro adjustments\n  - rename Fiber to MicroFiber\n  - add Micro.fiberJoin api\n  - adjust output when inspecting Micro data types\n\n## 3.11.1\n\n### Patch Changes\n\n- [#4052](https://github.com/Effect-TS/effect/pull/4052) [`dd8a2d8`](https://github.com/Effect-TS/effect/commit/dd8a2d8e80d33b16719fc69361eaedf0b59d4620) Thanks @tim-smart! - ensure pool.get is interrupted on shutdown\n\n- [#4059](https://github.com/Effect-TS/effect/pull/4059) [`a71bfef`](https://github.com/Effect-TS/effect/commit/a71bfef46f5061bb2502a61a333638a987b62273) Thanks @IMax153! - Ensure that the current time zone context tag type is properly exported\n\n## 3.11.0\n\n### Minor Changes\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3) Thanks @IMax153! - Ensure scopes are preserved by stream / sink / channel operations\n\n  **NOTE**: This change does modify the public signature of several `Stream` / `Sink` / `Channel` methods. Namely, certain run methods that previously removed a `Scope` from the environment will no longer do so. This was a bug with the previous implementation of how scopes were propagated, and is why this change is being made in a minor release.\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`6e69493`](https://github.com/Effect-TS/effect/commit/6e694930048bbaf98110f35f41566aeb9752d471) Thanks @tim-smart! - add Context.Reference - a Tag with a default value\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3) Thanks @IMax153! - Add `Effect.scopedWith` to run an effect that depends on a `Scope`, and then closes the `Scope` after the effect has completed\n\n  ```ts\n  import { Effect, Scope } from \"effect\"\n\n  const program: Effect.Effect<void> = Effect.scopedWith((scope) =>\n    Effect.acquireRelease(Effect.log(\"Acquiring...\"), () =>\n      Effect.log(\"Releasing...\")\n    ).pipe(Scope.extend(scope))\n  )\n\n  Effect.runPromise(program)\n  // Output:\n  // timestamp=2024-11-26T16:44:54.158Z level=INFO fiber=#0 message=Acquiring...\n  // timestamp=2024-11-26T16:44:54.165Z level=INFO fiber=#0 message=Releasing...\n  ```\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`d9fe79b`](https://github.com/Effect-TS/effect/commit/d9fe79bb5a3fe105d8e7a3bc2922a8ad936a5d10) Thanks @tim-smart! - remove Env, EnvRef & FiberFlags from Micro\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`251d189`](https://github.com/Effect-TS/effect/commit/251d189420bbba71990574e91098c499065f9a9b) Thanks @KhraksMamtsov! - `Config.url` constructor has been added, which parses a string using `new URL()`\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`5a259f3`](https://github.com/Effect-TS/effect/commit/5a259f3711b4369f55d885b568bdb21136155261) Thanks @tim-smart! - use fiber based runtime for Micro module\n  - Improved performance\n  - Improved interruption model\n  - Consistency with the Effect data type\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`b4ce4ea`](https://github.com/Effect-TS/effect/commit/b4ce4ea7fd514a7e572f2dcd879c98f334981b0e) Thanks @SandroMaglione! - New methods `extractAll` and `extractSchema` to `UrlParams` (added `Schema.BooleanFromString`).\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`15fcc5a`](https://github.com/Effect-TS/effect/commit/15fcc5a0ea4bbf40ab48fa6a04fdda74f76f4c07) Thanks @fubhy! - Integrated `DateTime` with `Cron` to add timezone support for cron expressions.\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`9bc9a47`](https://github.com/Effect-TS/effect/commit/9bc9a476800dc645903c888a68bb1d3baa3383c6) Thanks @KhraksMamtsov! - `URL` and `URLFromSelf` schemas have been added\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb) Thanks @fubhy! - Added `BigDecimal.toExponential` for scientific notation formatting of `BigDecimal` values.\n\n  The implementation of `BigDecimal.format` now uses scientific notation for values with\n  at least 16 decimal places or trailing zeroes. Previously, extremely large or small values\n  could cause `OutOfMemory` errors when formatting.\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`1e2747c`](https://github.com/Effect-TS/effect/commit/1e2747c63a4820d1459cbbc88c71212983bd68bd) Thanks @KhraksMamtsov! - - JSONSchema module\n  - add `format?: string` optional field to `JsonSchema7String` interface\n  - Schema module\n    - add custom json schema annotation to `UUID` schema including `format: \"uuid\"`\n  - OpenApiJsonSchema module\n    - add `format?: string` optional field to `String` and ` Numeric` interfaces\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`e0b9b09`](https://github.com/Effect-TS/effect/commit/e0b9b09e70c386b2da17d1f0a15b0511861c89e8) Thanks @mikearnaldi! - Implement Effect.fn to define traced functions.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  const logExample = Effect.fn(\"example\")(function* <N extends number>(n: N) {\n    yield* Effect.annotateCurrentSpan(\"n\", n)\n    yield* Effect.logInfo(`got: ${n}`)\n    yield* Effect.fail(new Error())\n  }, Effect.delay(\"1 second\"))\n\n  Effect.runFork(logExample(100).pipe(Effect.catchAllCause(Effect.logError)))\n  ```\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`c36f3b9`](https://github.com/Effect-TS/effect/commit/c36f3b95df5ce9d71b66f22f26ce12eda8d3e848) Thanks @KhraksMamtsov! - `Config.redacted` has been made more flexible and can now wrap any other config. This allows to transform or validate config values before it’s hidden.\n\n  ```ts\n  import { Config } from \"effect\"\n\n  Effect.gen(function* () {\n    // can be any string including empty\n    const pass1 = yield* Config.redacted(\"PASSWORD\")\n    //    ^? Redacted<string>\n\n    // can't be empty string\n    const pass2 = yield* Config.redacted(Config.nonEmptyString(\"PASSWORD\"))\n    //    ^? Redacted<string>\n\n    const pass2 = yield* Config.redacted(Config.number(\"SECRET_NUMBER\"))\n    //    ^? Redacted<number>\n  })\n  ```\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb) Thanks @fubhy! - Added `BigDecimal.unsafeFromNumber` and `BigDecimal.safeFromNumber`.\n\n  Deprecated `BigDecimal.fromNumber` in favour of `BigDecimal.unsafeFromNumber`.\n\n  The current implementation of `BigDecimal.fromNumber` and `BigDecimal.unsafeFromNumber` now throws\n  a `RangeError` for numbers that are not finite such as `NaN`, `+Infinity` or `-Infinity`.\n\n### Patch Changes\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`5eff3f6`](https://github.com/Effect-TS/effect/commit/5eff3f6fa3aae7e86948a62cbfd63b8d6c3bdf92) Thanks @tim-smart! - fix multipart support for bun http server\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`9264162`](https://github.com/Effect-TS/effect/commit/9264162a82783a651776fb7b87604564a63e7070) Thanks @IMax153! - inherit child fibers created by merged streams\n\n## 3.10.20\n\n### Patch Changes\n\n- [#4042](https://github.com/Effect-TS/effect/pull/4042) [`3069614`](https://github.com/Effect-TS/effect/commit/30696149271129fc618f6f2ccd1d8f2f6c0f9cd7) Thanks @tim-smart! - catch logger defects from calling .toJSON on data types\n\n- [#4041](https://github.com/Effect-TS/effect/pull/4041) [`09a5e52`](https://github.com/Effect-TS/effect/commit/09a5e522fd9b221f05d85b1d1c8a740d4973c302) Thanks @tim-smart! - fix docs for Stream.partition\n\n## 3.10.19\n\n### Patch Changes\n\n- [#4007](https://github.com/Effect-TS/effect/pull/4007) [`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1) Thanks @gcanti! - Wrap JSDoc @example tags with a TypeScript fence, closes #4002\n\n- [#4013](https://github.com/Effect-TS/effect/pull/4013) [`54addee`](https://github.com/Effect-TS/effect/commit/54addee438a644bf010646c52042c7b89c5fc0a7) Thanks @thewilkybarkid! - Remove reference to non-existent function\n\n## 3.10.18\n\n### Patch Changes\n\n- [#4004](https://github.com/Effect-TS/effect/pull/4004) [`af409cf`](https://github.com/Effect-TS/effect/commit/af409cf1d2ff973be11cc079ea373eaeedca25de) Thanks @tim-smart! - fix behavour of Stream.partition to match the types\n\n## 3.10.17\n\n### Patch Changes\n\n- [#3998](https://github.com/Effect-TS/effect/pull/3998) [`42c4ce6`](https://github.com/Effect-TS/effect/commit/42c4ce6f8d8c7d847e97757650a8ad9419a829d7) Thanks @tim-smart! - ensure fiber observers are cleared after exit to prevent memory leaks\n\n## 3.10.16\n\n### Patch Changes\n\n- [#3918](https://github.com/Effect-TS/effect/pull/3918) [`4dca30c`](https://github.com/Effect-TS/effect/commit/4dca30cfcdafe4542e236489f71d6f171a5b4e38) Thanks @gcanti! - Use a specific annotation (`AutoTitleAnnotationId`) to add automatic titles (added by `Struct` and `Class` APIs), instead of `TitleAnnotationId`, to avoid interfering with user-defined titles.\n\n- [#3981](https://github.com/Effect-TS/effect/pull/3981) [`1d99867`](https://github.com/Effect-TS/effect/commit/1d998671be3cd11043f232822e91dd8c98fccfa9) Thanks @gcanti! - Stable filters such as `minItems`, `maxItems`, and `itemsCount` should be applied only if the from part fails with a `Composite` issue, closes #3980\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.Array(Schema.String).pipe(Schema.minItems(1))\n  })\n\n  Schema.decodeUnknownSync(schema)({}, { errors: \"all\" })\n  // throws: TypeError: Cannot read properties of undefined (reading 'length')\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.Array(Schema.String).pipe(Schema.minItems(1))\n  })\n\n  Schema.decodeUnknownSync(schema)({}, { errors: \"all\" })\n  /*\n  throws:\n  ParseError: { readonly a: an array of at least 1 items }\n  └─ [\"a\"]\n     └─ is missing\n  */\n  ```\n\n- [#3972](https://github.com/Effect-TS/effect/pull/3972) [`6dae414`](https://github.com/Effect-TS/effect/commit/6dae4147991a97ec14a99289bd25fadae7541e8d) Thanks @tim-smart! - add support for 0 capacity to Mailbox\n\n- [#3959](https://github.com/Effect-TS/effect/pull/3959) [`6b0d737`](https://github.com/Effect-TS/effect/commit/6b0d737078bf63b97891e6bc47affc04b28f9cf7) Thanks @gcanti! - Remove `Omit` from the `Class` interface definition to align type signatures with runtime behavior. This fix addresses the issue of being unable to override base class methods in extended classes without encountering type errors, closes #3958\n\n  Before\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  class Base extends Schema.Class<Base>(\"Base\")({\n    a: Schema.String\n  }) {\n    f() {\n      console.log(\"base\")\n    }\n  }\n\n  class Extended extends Base.extend<Extended>(\"Extended\")({}) {\n    // Class '{ readonly a: string; } & Omit<Base, \"a\">' defines instance member property 'f',\n    // but extended class 'Extended' defines it as instance member function.ts(2425)\n    // @ts-expect-error\n    override f() {\n      console.log(\"extended\")\n    }\n  }\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"effect\"\n\n  class Base extends Schema.Class<Base>(\"Base\")({\n    a: Schema.String\n  }) {\n    f() {\n      console.log(\"base\")\n    }\n  }\n\n  class Extended extends Base.extend<Extended>(\"Extended\")({}) {\n    // ok\n    override f() {\n      console.log(\"extended\")\n    }\n  }\n  ```\n\n- [#3971](https://github.com/Effect-TS/effect/pull/3971) [`d8356aa`](https://github.com/Effect-TS/effect/commit/d8356aad428a0c2290db52380220f81d9ec94232) Thanks @gcanti! - Refactor JSON Schema Generation to Include Transformation Annotations, closes #3016\n\n  When generating a JSON Schema, treat `TypeLiteralTransformations` (such as when `Schema.optionalWith` is used) as a special case. Annotations from the transformation itself will now be applied, unless there are user-defined annotations on the form side. This change ensures that the user's intended annotations are properly included in the schema.\n\n  **Before**\n\n  Annotations set on the transformation are ignored. However while using `Schema.optionalWith` internally generates a transformation schema, this is considered a technical detail. The user's intention is to add annotations to the \"struct\" schema, not to the transformation.\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.optionalWith(Schema.String, { default: () => \"\" })\n  }).annotations({\n    identifier: \"MyID\",\n    description: \"My description\",\n    title: \"My title\"\n  })\n\n  console.log(JSONSchema.make(schema))\n  /*\n  Output:\n  {\n    '$schema': 'http://json-schema.org/draft-07/schema#',\n    type: 'object',\n    required: [],\n    properties: { a: { type: 'string' } },\n    additionalProperties: false\n  }\n  */\n  ```\n\n  **After**\n\n  Annotations set on the transformation are now considered during JSON Schema generation:\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.optionalWith(Schema.String, { default: () => \"\" })\n  }).annotations({\n    identifier: \"MyID\",\n    description: \"My description\",\n    title: \"My title\"\n  })\n\n  console.log(JSONSchema.make(schema))\n  /*\n  Output:\n  {\n    '$schema': 'http://json-schema.org/draft-07/schema#',\n    '$ref': '#/$defs/MyID',\n    '$defs': {\n      MyID: {\n        type: 'object',\n        required: [],\n        properties: [Object],\n        additionalProperties: false,\n        description: 'My description',\n        title: 'My title'\n      }\n    }\n  }\n  */\n  ```\n\n## 3.10.15\n\n### Patch Changes\n\n- [#3936](https://github.com/Effect-TS/effect/pull/3936) [`8398b32`](https://github.com/Effect-TS/effect/commit/8398b3208242a88239d4449910b7baf923cfe3b6) Thanks @tim-smart! - allow DateTime.makeZoned to default to the local time zone\n\n- [#3917](https://github.com/Effect-TS/effect/pull/3917) [`72e55b7`](https://github.com/Effect-TS/effect/commit/72e55b7c610784fcebdbadc592c876e23e76a986) Thanks @SuttonKyle! - Allow Stream.split to use refinement for better type inference\n\n## 3.10.14\n\n### Patch Changes\n\n- [#3920](https://github.com/Effect-TS/effect/pull/3920) [`f983946`](https://github.com/Effect-TS/effect/commit/f9839467b4cad6e788297764ef9f9f0b9fd203f9) Thanks @gcanti! - remove redundant check in `JSONNumber` declaration\n\n- [#3924](https://github.com/Effect-TS/effect/pull/3924) [`2d8a750`](https://github.com/Effect-TS/effect/commit/2d8a75081eb83a0a81f817fdf6f428369c5064ab) Thanks @tim-smart! - ensure a ManagedRuntime can be built synchronously\n\n## 3.10.13\n\n### Patch Changes\n\n- [#3907](https://github.com/Effect-TS/effect/pull/3907) [`995bbdf`](https://github.com/Effect-TS/effect/commit/995bbdffea2e332f203cd5b474cd6a1c77dfa6ae) Thanks @arijoon! - Schema.BigDecimal Arbitrary's scale limited to the range 0-18\n\n## 3.10.12\n\n### Patch Changes\n\n- [#3904](https://github.com/Effect-TS/effect/pull/3904) [`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6) Thanks @tim-smart! - allow pool items te be used while being acquired\n\n## 3.10.11\n\n### Patch Changes\n\n- [#3903](https://github.com/Effect-TS/effect/pull/3903) [`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a) Thanks @tim-smart! - cache Schema.Class AST once generated\n\n## 3.10.10\n\n### Patch Changes\n\n- [#3893](https://github.com/Effect-TS/effect/pull/3893) [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28) Thanks @tim-smart! - support \"dropping\" & \"sliding\" strategies in Mailbox\n\n- [#3893](https://github.com/Effect-TS/effect/pull/3893) [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28) Thanks @tim-smart! - add Mailbox.fromStream api\n\n- [#3886](https://github.com/Effect-TS/effect/pull/3886) [`b631f40`](https://github.com/Effect-TS/effect/commit/b631f40abbe649b2a089764585b5c39f6a695ac6) Thanks @fubhy! - Optimized `Base64.decode` by not capturing the padding characters in the underlying array buffer.\n\n  Previously, the implementation first captured the padding characters in the underlying array buffer and\n  then returned a new subarray view of the buffer with the padding characters removed.\n\n  By not capturing the padding characters, we avoid the creation of another typed array instance for the\n  subarray view.\n\n## 3.10.9\n\n### Patch Changes\n\n- [#3883](https://github.com/Effect-TS/effect/pull/3883) [`a123e80`](https://github.com/Effect-TS/effect/commit/a123e80f111a625428a5b5622b7f55ee1073566b) Thanks @tim-smart! - add FromIterator primitive to improve Effect.gen performance\n\n- [#3880](https://github.com/Effect-TS/effect/pull/3880) [`bd5fcd3`](https://github.com/Effect-TS/effect/commit/bd5fcd3e6b603b1e505af90d6a00627c8eca6d41) Thanks @tim-smart! - refactor Effect.gen to improve performance\n\n- [#3881](https://github.com/Effect-TS/effect/pull/3881) [`0289d3b`](https://github.com/Effect-TS/effect/commit/0289d3b6391031d00329365bab9791b355031fe3) Thanks @tim-smart! - implement Effect.suspend using OP_COMMIT\n\n- [#3862](https://github.com/Effect-TS/effect/pull/3862) [`7386b71`](https://github.com/Effect-TS/effect/commit/7386b710e5be570e17f468928a6ed19d549a3e12) Thanks @furrycatherder! - fix the type signature of `use` in Effect.Service\n\n- [#3879](https://github.com/Effect-TS/effect/pull/3879) [`4211a23`](https://github.com/Effect-TS/effect/commit/4211a2355bb3af3f0e756e2aae9d293379f25662) Thanks @IMax153! - Return a sequential cause when both the `use` and `release` fail in `Effect.acquireUseRelease`\n\n## 3.10.8\n\n### Patch Changes\n\n- [#3868](https://github.com/Effect-TS/effect/pull/3868) [`68b5c9e`](https://github.com/Effect-TS/effect/commit/68b5c9e44f34192cef26e1cadda5e661a027df41) Thanks @tim-smart! - move \\_op check out of the fiber hot path\n\n- [#3849](https://github.com/Effect-TS/effect/pull/3849) [`9c9928d`](https://github.com/Effect-TS/effect/commit/9c9928dfeacd9ac33dc37eb0ca3d7d8c39175ada) Thanks @patroza! - improve: use literal `key` on Service\n\n- [#3872](https://github.com/Effect-TS/effect/pull/3872) [`6306e66`](https://github.com/Effect-TS/effect/commit/6306e6656092b350d4ede5746da6f245ec9f7e07) Thanks @KhraksMamtsov! - Fix `Config.integer` & `Config.number`\n\n- [#3869](https://github.com/Effect-TS/effect/pull/3869) [`361c7f3`](https://github.com/Effect-TS/effect/commit/361c7f39a2c10ede9324847c3d3ba192a6f9b20a) Thanks @KhraksMamtsov! - jsdoc-examples for class-based APIs have been added, e.g. `Schema.TaggedError`, `Effect.Service` and others\n\n## 3.10.7\n\n### Patch Changes\n\n- [#3867](https://github.com/Effect-TS/effect/pull/3867) [`33f5b9f`](https://github.com/Effect-TS/effect/commit/33f5b9ffaebea4f1bd0e391b44c41fb6230e743a) Thanks @tim-smart! - ensure Channel.mergeWith fibers can be interrupted\n\n- [#3865](https://github.com/Effect-TS/effect/pull/3865) [`50f0281`](https://github.com/Effect-TS/effect/commit/50f0281b0d2116726b8927a6217622d5f394f3e4) Thanks @tim-smart! - fix memory leak in Stream.retry\n\n## 3.10.6\n\n### Patch Changes\n\n- [#3858](https://github.com/Effect-TS/effect/pull/3858) [`ce1c21f`](https://github.com/Effect-TS/effect/commit/ce1c21ffc11902ac9ab453a51904207859d38552) Thanks @KhraksMamtsov! - fix `Tag.Proxy` type\n\n## 3.10.5\n\n### Patch Changes\n\n- [#3841](https://github.com/Effect-TS/effect/pull/3841) [`3a6d757`](https://github.com/Effect-TS/effect/commit/3a6d757badeebe00d8ef4d67530d073c8264dcfa) Thanks @KhraksMamtsov! - Support union of parameters in functions in `Effect.Tag.Proxy` type\n\n- [#3845](https://github.com/Effect-TS/effect/pull/3845) [`59d813a`](https://github.com/Effect-TS/effect/commit/59d813aa4973d1115cfc70cc3667508335f49693) Thanks @tim-smart! - ensure fiber refs are not inherited by ManagedRuntime\n\n## 3.10.4\n\n### Patch Changes\n\n- [#3842](https://github.com/Effect-TS/effect/pull/3842) [`2367708`](https://github.com/Effect-TS/effect/commit/2367708be449f9526a2047e321302d7bfb16f18e) Thanks @gcanti! - add support for `Schema.OptionFromUndefinedOr` in JSON Schema generation, closes #3839\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.OptionFromUndefinedOr(Schema.Number)\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  throws:\n  Error: Missing annotation\n  at path: [\"a\"]\n  details: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\n  schema (UndefinedKeyword): undefined\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.OptionFromUndefinedOr(Schema.Number)\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  Output:\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [],\n    \"properties\": {\n      \"a\": {\n        \"type\": \"number\"\n      }\n    },\n    \"additionalProperties\": false\n  }\n  */\n  ```\n\n## 3.10.3\n\n### Patch Changes\n\n- [#3833](https://github.com/Effect-TS/effect/pull/3833) [`b9423d8`](https://github.com/Effect-TS/effect/commit/b9423d8bf8181a2389fdbce1e3c14ac6fe8d54f5) Thanks @IMax153! - Ensure undefined JSON values are not coerced to empty string\n\n## 3.10.2\n\n### Patch Changes\n\n- [#3820](https://github.com/Effect-TS/effect/pull/3820) [`714e119`](https://github.com/Effect-TS/effect/commit/714e11945e45e5a2554ee058e6c43f82a8e309cf) Thanks @tim-smart! - simplify Match fail keys types\n\n- [#3825](https://github.com/Effect-TS/effect/pull/3825) [`c1afd55`](https://github.com/Effect-TS/effect/commit/c1afd55c54e61f9c432823d21b3d016f79160a37) Thanks @KhraksMamtsov! - - Make `MergeRight`, `MergeLeft` and `MergeRecord` in `Types` module homomorphic (preserve original `readonly` and optionality modifiers)\n  - `MergeRecord` now is alias for `MergeLeft`\n\n## 3.10.1\n\n### Patch Changes\n\n- [#3818](https://github.com/Effect-TS/effect/pull/3818) [`9604d6b`](https://github.com/Effect-TS/effect/commit/9604d6b616435103dafea8b53637a9d1450b4750) Thanks @tim-smart! - fix Channel.embedInput halting in uninterruptible region\n\n## 3.10.0\n\n### Minor Changes\n\n- [#3764](https://github.com/Effect-TS/effect/pull/3764) [`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf) Thanks @evelant! - add TSubscriptionRef\n\n- [#3764](https://github.com/Effect-TS/effect/pull/3764) [`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf) Thanks @evelant! - add Stream.fromTQueue & Stream.fromTPubSub\n\n- [#3764](https://github.com/Effect-TS/effect/pull/3764) [`c79c4c1`](https://github.com/Effect-TS/effect/commit/c79c4c178390fe61ff6dda88c9e058862349343a) Thanks @gcanti! - Merge Schema into Effect.\n\n  ### Modules\n\n  Before\n\n  ```ts\n  import {\n    Arbitrary,\n    AST,\n    FastCheck,\n    JSONSchema,\n    ParseResult,\n    Pretty,\n    Schema\n  } from \"@effect/schema\"\n  ```\n\n  After\n\n  ```ts\n  import {\n    Arbitrary,\n    SchemaAST, // changed\n    FastCheck,\n    JSONSchema,\n    ParseResult,\n    Pretty,\n    Schema\n  } from \"effect\"\n  ```\n\n  ### Formatters\n\n  `ArrayFormatter` / `TreeFormatter` merged into `ParseResult` module.\n\n  Before\n\n  ```ts\n  import { ArrayFormatter, TreeFormatter } from \"@effect/schema\"\n  ```\n\n  After\n\n  ```ts\n  import { ArrayFormatter, TreeFormatter } from \"effect/ParseResult\"\n  ```\n\n  ### Serializable\n\n  Merged into `Schema` module.\n\n  ### Equivalence\n\n  Merged into `Schema` module.\n\n  Before\n\n  ```ts\n  import { Equivalence } from \"@effect/schema\"\n\n  Equivalence.make(myschema)\n  ```\n\n  After\n\n  ```ts\n  import { Schema } from \"@effect/schema\"\n\n  Schema.equivalence(myschema)\n  ```\n\n- [#3764](https://github.com/Effect-TS/effect/pull/3764) [`38d30f0`](https://github.com/Effect-TS/effect/commit/38d30f08b8da62f9c3e308b9250738cb8d17bdb5) Thanks @tim-smart! - add option to .releaseLock a ReadableStream on finalization\n\n- [#3764](https://github.com/Effect-TS/effect/pull/3764) [`5821ce3`](https://github.com/Effect-TS/effect/commit/5821ce3455b47d25e0a40cae6ce22af9db5fa556) Thanks @patroza! - feat: implement Redactable. Used by Headers to not log sensitive information\n\n## 3.9.2\n\n### Patch Changes\n\n- [#3768](https://github.com/Effect-TS/effect/pull/3768) [`61a99b2`](https://github.com/Effect-TS/effect/commit/61a99b2bf9d757870ef0c2ec9d4c877cdd364a3d) Thanks @tim-smart! - allow tacit usage with do notation apis (.bind / .let)\n\n## 3.9.1\n\n### Patch Changes\n\n- [#3740](https://github.com/Effect-TS/effect/pull/3740) [`3b2ad1d`](https://github.com/Effect-TS/effect/commit/3b2ad1d58a2e33dc1a72b7037396bd25ca1702a9) Thanks @tim-smart! - revert deno Inspectable changes\n\n## 3.9.0\n\n### Minor Changes\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`ff3d1aa`](https://github.com/Effect-TS/effect/commit/ff3d1aab290b4d1173b2dfc7e4c76abb4babdc16) Thanks @vinassefranche! - Adds HashMap.HashMap.Entry type helper\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`0ba66f2`](https://github.com/Effect-TS/effect/commit/0ba66f2451641fd6990e02ec1ed01c014db9dab0) Thanks @tim-smart! - add deno support to Inspectable\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`bf77f51`](https://github.com/Effect-TS/effect/commit/bf77f51b323c383224ebf08adf77a7a6e8c9b3cd) Thanks @KhraksMamtsov! - `Latch` implements `Effect<void>` with `.await` semantic\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`0779681`](https://github.com/Effect-TS/effect/commit/07796813f07de035719728733096ba64ce333469) Thanks @KhraksMamtsov! - Effect.mapAccum & Array.mapAccum preserve non-emptiness\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`534129f`](https://github.com/Effect-TS/effect/commit/534129f8113ce1a8ec50828083e16da9c86326c6) Thanks @KhraksMamtsov! - `Pool` is now a subtype of `Effect`, equivalent to `Pool.get`\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda) Thanks @mikearnaldi! - Support providing an array of layers via Effect.provide and Layer.provide\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03) Thanks @leonitousconforti! - support ManagedRuntime in Effect.provide\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03) Thanks @leonitousconforti! - `ManagedRuntime<R, E>` is subtype of `Effect<Runtime<R>, E, never>`\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`5b36494`](https://github.com/Effect-TS/effect/commit/5b364942e9a9003fdb8217324f8a2d8369c969da) Thanks @KhraksMamtsov! - `Tuple.map` transforms each element of tuple using the given function, treating tuple homomorphically\n\n  ```ts\n  import { pipe, Tuple } from \"effect\"\n\n  const result = pipe(\n    //  ^? [string, string, string]\n    [\"a\", 1, false] as const,\n    T.map((el) => {\n      //^? \"a\" | 1 | false\n      return el.toString().toUppercase()\n    })\n  )\n  assert.deepStrictEqual(result, [\"A\", \"1\", \"FALSE\"])\n  ```\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`c716adb`](https://github.com/Effect-TS/effect/commit/c716adb250ebbea1d1048d818ef7fed4f621d186) Thanks @AlexGeb! - Add Array.pad function\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`4986391`](https://github.com/Effect-TS/effect/commit/49863919cd8628c962a712fb1df30d2983820933) Thanks @ianbollinger! - Add an `isRegExp` type guard\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda) Thanks @mikearnaldi! - Implement Effect.Service as a Tag and Layer with Opaque Type.\n\n  Namely the following is now possible:\n\n  ```ts\n  class Prefix extends Effect.Service<Prefix>()(\"Prefix\", {\n    sync: () => ({\n      prefix: \"PRE\"\n    })\n  }) {}\n\n  class Postfix extends Effect.Service<Postfix>()(\"Postfix\", {\n    sync: () => ({\n      postfix: \"POST\"\n    })\n  }) {}\n\n  const messages: Array<string> = []\n\n  class Logger extends Effect.Service<Logger>()(\"Logger\", {\n    accessors: true,\n    effect: Effect.gen(function* () {\n      const { prefix } = yield* Prefix\n      const { postfix } = yield* Postfix\n      return {\n        info: (message: string) =>\n          Effect.sync(() => {\n            messages.push(`[${prefix}][${message}][${postfix}]`)\n          })\n      }\n    }),\n    dependencies: [Prefix.Default, Postfix.Default]\n  }) {}\n\n  describe(\"Effect\", () => {\n    it.effect(\"Service correctly wires dependencies\", () =>\n      Effect.gen(function* () {\n        const { _tag } = yield* Logger\n        expect(_tag).toEqual(\"Logger\")\n        yield* Logger.info(\"Ok\")\n        expect(messages).toEqual([\"[PRE][Ok][POST]\"])\n        const { prefix } = yield* Prefix\n        expect(prefix).toEqual(\"PRE\")\n        const { postfix } = yield* Postfix\n        expect(postfix).toEqual(\"POST\")\n      }).pipe(Effect.provide([Logger.Default, Prefix.Default, Postfix.Default]))\n    )\n  })\n  ```\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`d1387ae`](https://github.com/Effect-TS/effect/commit/d1387aebd1ff01bbebde26be46d488956e4daef6) Thanks @KhraksMamtsov! - `Resource<A, E>` is subtype of `Effect<A, E>`.\n  `ScopedRed<A>` is subtype of `Effect<A>`.\n\n### Patch Changes\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`016f9ad`](https://github.com/Effect-TS/effect/commit/016f9ad931a4b3d09a34e5caf13d87c5b8e9c984) Thanks @tim-smart! - fix Unify for Deferred\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`9237ac6`](https://github.com/Effect-TS/effect/commit/9237ac69bc07de5b3b60076a0ad2921c21de7457) Thanks @leonitousconforti! - move ManagedRuntime.TypeId to fix circular imports\n\n## 3.8.5\n\n### Patch Changes\n\n- [#3734](https://github.com/Effect-TS/effect/pull/3734) [`88e85db`](https://github.com/Effect-TS/effect/commit/88e85db34bd402526e27a323e950d053fa34d232) Thanks @mikearnaldi! - Ensure random numbers are correctly distributed\n\n- [#3717](https://github.com/Effect-TS/effect/pull/3717) [`83887ca`](https://github.com/Effect-TS/effect/commit/83887ca1b1793916913d8550a4db4450cd14a044) Thanks @mikearnaldi! - Consider async operation in runSync as a defect, add span based stack\n\n- [#3731](https://github.com/Effect-TS/effect/pull/3731) [`5266b6c`](https://github.com/Effect-TS/effect/commit/5266b6cd86d76c3886da041c8829bca04b1a3110) Thanks @patroza! - Improve DX of type errors from inside `pipe` and `flow`\n\n- [#3699](https://github.com/Effect-TS/effect/pull/3699) [`cdead5c`](https://github.com/Effect-TS/effect/commit/cdead5c9cfd54dc6c4f215d9732f654c4a12e991) Thanks @jessekelly881! - added Stream.mergeWithTag\n\n  Combines a struct of streams into a single stream of tagged values where the tag is the key of the struct.\n\n  ```ts\n  import { Stream } from \"effect\"\n\n  // Stream.Stream<{ _tag: \"a\"; value: number; } | { _tag: \"b\"; value: string; }>\n  const stream = Stream.mergeWithTag(\n    {\n      a: Stream.make(0),\n      b: Stream.make(\"\")\n    },\n    { concurrency: 1 }\n  )\n  ```\n\n- [#3706](https://github.com/Effect-TS/effect/pull/3706) [`766a8af`](https://github.com/Effect-TS/effect/commit/766a8af307b414aca3648d91c4eab7493a5ec862) Thanks @fubhy! - Made `BigDecimal.scale` dual.\n\n## 3.8.4\n\n### Patch Changes\n\n- [#3661](https://github.com/Effect-TS/effect/pull/3661) [`4509656`](https://github.com/Effect-TS/effect/commit/45096569d50262275ee984f44c456f5c83b62683) Thanks @KhraksMamtsov! - `Micro.EnvRef` and `Micro.Handle` is subtype of `Micro`\n\n## 3.8.3\n\n### Patch Changes\n\n- [#3644](https://github.com/Effect-TS/effect/pull/3644) [`bb5ec6b`](https://github.com/Effect-TS/effect/commit/bb5ec6b4b6a6f537394596c5a596faf52cb2aef4) Thanks @tim-smart! - fix encoding of logs to tracer span events\n\n## 3.8.2\n\n### Patch Changes\n\n- [#3627](https://github.com/Effect-TS/effect/pull/3627) [`f0d8ef1`](https://github.com/Effect-TS/effect/commit/f0d8ef1ce97ec2a87b09b3e24150cfeab85d6e2f) Thanks @fubhy! - Revert cron schedule regression\n\n## 3.8.1\n\n### Patch Changes\n\n- [#3624](https://github.com/Effect-TS/effect/pull/3624) [`10bf621`](https://github.com/Effect-TS/effect/commit/10bf6213f36d8ddb00f058a4609b85220f3d8334) Thanks @fubhy! - Fixed double firing of cron schedules in cases where the current time matched the initial interval.\n\n- [#3623](https://github.com/Effect-TS/effect/pull/3623) [`ae36fa6`](https://github.com/Effect-TS/effect/commit/ae36fa68f754eeab9a54b6dc0f8b44db513aa2b6) Thanks @fubhy! - Allow CRLF characters in base64 encoded strings.\n\n## 3.8.0\n\n### Minor Changes\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`fcfa6ee`](https://github.com/Effect-TS/effect/commit/fcfa6ee30ffd07d998bf22799357bf58580a116f) Thanks @Schniz! - add `Logger.withLeveledConsole`\n\n  In browsers and different platforms, `console.error` renders differently than `console.info`. This helps to distinguish between different levels of logging. `Logger.withLeveledConsole` takes any logger and calls the respective `Console` method based on the log level. For instance, `Effect.logError` will call `Console.error` and `Effect.logInfo` will call `Console.info`.\n\n  To use it, you can replace the default logger with a `Logger.withLeveledConsole` logger:\n\n  ```ts\n  import { Logger, Effect } from \"effect\"\n\n  const loggerLayer = Logger.withLeveledConsole(Logger.stringLogger)\n\n  Effect.gen(function* () {\n    yield* Effect.logError(\"an error\")\n    yield* Effect.logInfo(\"an info\")\n  }).pipe(Effect.provide(loggerLayer))\n  ```\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`bb9931b`](https://github.com/Effect-TS/effect/commit/bb9931b62e249a3b801f2cb9d097aec0c8511af7) Thanks @KhraksMamtsov! - Made `Ref`, `SynchronizedRed` and `SubscriptionRef` a subtype of `Effect`\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`5798f76`](https://github.com/Effect-TS/effect/commit/5798f7619529de33e5ba06f551806f68fedc19db) Thanks @tim-smart! - add Semaphore.withPermitsIfAvailable\n\n  You can now use `Semaphore.withPermitsIfAvailable` to run an Effect only if the\n  Semaphore has enough permits available. This is useful when you want to run an\n  Effect only if you can acquire a permit without blocking.\n\n  It will return an `Option.Some` with the result of the Effect if the permits were\n  available, or `None` if they were not.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    const semaphore = yield* Effect.makeSemaphore(1)\n    semaphore.withPermitsIfAvailable(1)(Effect.void)\n  })\n  ```\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`5f0bfa1`](https://github.com/Effect-TS/effect/commit/5f0bfa17205398d4e4818bfbcf9e1b505b3b1fc5) Thanks @KhraksMamtsov! - The `Deferred<A>` is now a subtype of `Effect<A>`. This change simplifies handling of deferred values, removing the need for explicit call `Deffer.await`.\n\n  ```typescript\n  import { Effect, Deferred } from \"effect\"\n\n  Effect.gen(function* () {\n    const deferred = yield* Deferred.make<string>()\n\n    const before = yield* Deferred.await(deferred)\n    const after = yield* deferred\n  })\n  ```\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`812a4e8`](https://github.com/Effect-TS/effect/commit/812a4e86e2d1aa23b477ef5829aa0e5c07784936) Thanks @tim-smart! - add Logger.prettyLoggerDefault, to prevent duplicate pretty loggers\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`273565e`](https://github.com/Effect-TS/effect/commit/273565e7901639e8d0541930ab715aea9c80fbaa) Thanks @tim-smart! - add Effect.makeLatch, for creating a simple async latch\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    // Create a latch, starting in the closed state\n    const latch = yield* Effect.makeLatch(false)\n\n    // Fork a fiber that logs \"open sesame\" when the latch is opened\n    const fiber = yield* Effect.log(\"open sesame\").pipe(\n      latch.whenOpen,\n      Effect.fork\n    )\n\n    // Open the latch\n    yield* latch.open\n    yield* fiber.await\n  })\n  ```\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`569a801`](https://github.com/Effect-TS/effect/commit/569a8017ef0a0bc203e4312867cbdd37b0effbd7) Thanks @KhraksMamtsov! - `Dequeue<A>` and `Queue<A>` is subtype of `Effect<A>`. This means that now it can be used as an `Effect`, and when called, it will automatically extract and return an item from the queue, without having to explicitly use the `Queue.take` function.\n\n  ```ts\n  Effect.gen(function* () {\n    const queue = yield* Queue.unbounded<number>()\n    yield* Queue.offer(queue, 1)\n    yield* Queue.offer(queue, 2)\n    const oldWay = yield* Queue.take(queue)\n    const newWay = yield* queue\n  })\n  ```\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`aa1fa53`](https://github.com/Effect-TS/effect/commit/aa1fa5301e886b9657c8eb0d38cb87cef92a8305) Thanks @vinassefranche! - Add Number.round\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`02f6b06`](https://github.com/Effect-TS/effect/commit/02f6b0660e12bee1069532a9cc18d3ab855257be) Thanks @fubhy! - Add additional `Duration` conversion apis\n  - `Duration.toMinutes`\n  - `Duration.toHours`\n  - `Duration.toDays`\n  - `Duration.toWeeks`\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`12b893e`](https://github.com/Effect-TS/effect/commit/12b893e63cc6dfada4aca7773b4783940e2edf25) Thanks @KhraksMamtsov! - The `Fiber<A, E>` is now a subtype of `Effect<A, E>`. This change removes the need for explicit call `Fiber.join`.\n\n  ```typescript\n  import { Effect, Fiber } from \"effect\"\n\n  Effect.gen(function*() {\n    const fiber = yield* Effect.fork(Effect.succeed(1))\n\n    const oldWay = yield* Fiber.join(fiber)\n    const now = yield* fiber\n  }))\n  ```\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`bbad27e`](https://github.com/Effect-TS/effect/commit/bbad27ec0a90860593f759405caa877e7f4a655f) Thanks @dilame! - add `Stream.share` api\n\n  The `Stream.share` api is a ref counted variant of the broadcast apis.\n\n  It allows you to share a stream between multiple consumers, and will close the\n  upstream when the last consumer ends.\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`adf7d7a`](https://github.com/Effect-TS/effect/commit/adf7d7a7dfce3a7021e9f3b0d847dc85be89d754) Thanks @tim-smart! - add Mailbox module, a queue which can have done or failure signals\n\n  ```ts\n  import { Chunk, Effect, Mailbox } from \"effect\"\n  import * as assert from \"node:assert\"\n\n  Effect.gen(function* () {\n    const mailbox = yield* Mailbox.make<number, string>()\n\n    // add messages to the mailbox\n    yield* mailbox.offer(1)\n    yield* mailbox.offer(2)\n    yield* mailbox.offerAll([3, 4, 5])\n\n    // take messages from the mailbox\n    const [messages, done] = yield* mailbox.takeAll\n    assert.deepStrictEqual(Chunk.toReadonlyArray(messages), [1, 2, 3, 4, 5])\n    assert.strictEqual(done, false)\n\n    // signal that the mailbox is done\n    yield* mailbox.end\n    const [messages2, done2] = yield* mailbox.takeAll\n    assert.deepStrictEqual(messages2, Chunk.empty())\n    assert.strictEqual(done2, true)\n\n    // signal that the mailbox is failed\n    yield* mailbox.fail(\"boom\")\n  })\n  ```\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`007289a`](https://github.com/Effect-TS/effect/commit/007289a52d5877f8e90e2dacf38171ff9bf603fd) Thanks @mikearnaldi! - Cache some fiber references in the runtime to optimize reading in hot-paths\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`42a8f99`](https://github.com/Effect-TS/effect/commit/42a8f99740eefdaf2c4544d2c345313f97547a36) Thanks @fubhy! - Added `RcMap.keys` and `MutableHashMap.keys`.\n\n  These functions allow you to get a list of keys currently stored in the underlying hash map.\n\n  ```ts\n  const map = MutableHashMap.make([\n    [\"a\", \"a\"],\n    [\"b\", \"b\"],\n    [\"c\", \"c\"]\n  ])\n  const keys = MutableHashMap.keys(map) // [\"a\", \"b\", \"c\"]\n  ```\n\n  ```ts\n  Effect.gen(function* () {\n    const map = yield* RcMap.make({\n      lookup: (key) => Effect.succeed(key)\n    })\n\n    yield* RcMap.get(map, \"a\")\n    yield* RcMap.get(map, \"b\")\n    yield* RcMap.get(map, \"c\")\n\n    const keys = yield* RcMap.keys(map) // [\"a\", \"b\", \"c\"]\n  })\n  ```\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`eebfd29`](https://github.com/Effect-TS/effect/commit/eebfd29633fd5d38b505c5c0842036f61f05e913) Thanks @fubhy! - Add `Duration.parts` api\n\n  ```ts\n  const parts = Duration.parts(Duration.sum(\"5 minutes\", \"20 seconds\"))\n  assert.equal(parts.minutes, 5)\n  assert.equal(parts.seconds, 20)\n  ```\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`040703d`](https://github.com/Effect-TS/effect/commit/040703d0e100cd5511e52d812c15492414262b5e) Thanks @KhraksMamtsov! - The `FiberRef<A>` is now a subtype of `Effect<A>`. This change simplifies handling of deferred values, removing the need for explicit call `FiberRef.get`.\n\n  ```typescript\n  import { Effect, FiberRef } from \"effect\"\n\n  Effect.gen(function* () {\n    const fiberRef = yield* FiberRef.make(\"value\")\n\n    const before = yield* FiberRef.get(fiberRef)\n    const after = yield* fiberRef\n  })\n  ```\n\n## 3.7.3\n\n### Patch Changes\n\n- [#3592](https://github.com/Effect-TS/effect/pull/3592) [`35a0f81`](https://github.com/Effect-TS/effect/commit/35a0f813141652d696461cd5d19fd146adaf85be) Thanks @mikearnaldi! - TestClock yield with setTimeout(0)\n\n## 3.7.2\n\n### Patch Changes\n\n- [#3548](https://github.com/Effect-TS/effect/pull/3548) [`8a601d7`](https://github.com/Effect-TS/effect/commit/8a601d7a1f8ffe52ac9e6d67e9282a1495fe59c9) Thanks @tim-smart! - remove console.log statements from Micro\n\n- [#3546](https://github.com/Effect-TS/effect/pull/3546) [`353ba19`](https://github.com/Effect-TS/effect/commit/353ba19f9b2b9e959f0a00d058c6d40a4bc02db7) Thanks @tim-smart! - fix exported Stream types for `broadcast*` and `toPubSub`\n\n## 3.7.1\n\n### Patch Changes\n\n- [#3536](https://github.com/Effect-TS/effect/pull/3536) [`79859e7`](https://github.com/Effect-TS/effect/commit/79859e71040d8edf1868b8530b90c650f4321eff) Thanks @mikearnaldi! - Optimize Array.sortWith to avoid calling the map function excesively\n\n- [#3516](https://github.com/Effect-TS/effect/pull/3516) [`f6a469c`](https://github.com/Effect-TS/effect/commit/f6a469c190b9f00eee5ea0cd4d5912a0ef8b46f5) Thanks @KhraksMamtsov! - support tacit usage for `Effect.tapErrorTag` and `Effect.catchTag`\n\n- [#3543](https://github.com/Effect-TS/effect/pull/3543) [`dcb9ec0`](https://github.com/Effect-TS/effect/commit/dcb9ec0db443894dd204d87450f779c44b9ad7f1) Thanks @datner! - Align behavior of `Stream.empty` to act like `Stream.make()` to fix behavior with `NodeStream.toReadable`\n\n- [#3545](https://github.com/Effect-TS/effect/pull/3545) [`79aa6b1`](https://github.com/Effect-TS/effect/commit/79aa6b136e1f29b36f34e88cb2ff162bff2bb4ed) Thanks @tim-smart! - fix Micro.forEach for empty iterables\n\n## 3.7.0\n\n### Minor Changes\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`2f456cc`](https://github.com/Effect-TS/effect/commit/2f456cce5012b9fcb6b4e039190d527813b75b92) Thanks @vinassefranche! - preserve `Array.modify` `Array.modifyOption` non emptiness\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`8745e41`](https://github.com/Effect-TS/effect/commit/8745e41ed96e3765dc6048efc2a9afbe05c8a1e9) Thanks @patroza! - improve: type Fiber.awaitAll as Exit<A, E>[].\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`e557838`](https://github.com/Effect-TS/effect/commit/e55783886b046d3c5f33447f455f9ccf2fa75922) Thanks @titouancreach! - New constructor Config.nonEmptyString\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`d6e7e40`](https://github.com/Effect-TS/effect/commit/d6e7e40b1e2ad0c59aa02f07344d28601b14ebdc) Thanks @KhraksMamtsov! - preserve `Array.replace` `Array.replaceOption` non emptiness\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`8356321`](https://github.com/Effect-TS/effect/commit/8356321598da04bd77c1001f45a4e447bec5591d) Thanks @KhraksMamtsov! - add `Effect.bindAll` api\n\n  This api allows you to combine `Effect.all` with `Effect.bind`. It is useful\n  when you want to concurrently run multiple effects and then combine their\n  results in a Do notation pipeline.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  const result = Effect.Do.pipe(\n    Effect.bind(\"x\", () => Effect.succeed(2)),\n    Effect.bindAll(\n      ({ x }) => ({\n        a: Effect.succeed(x + 1),\n        b: Effect.succeed(\"foo\")\n      }),\n      { concurrency: 2 }\n    )\n  )\n  assert.deepStrictEqual(Effect.runSync(result), {\n    x: 2,\n    a: 3,\n    b: \"foo\"\n  })\n  ```\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`192f2eb`](https://github.com/Effect-TS/effect/commit/192f2ebb2c4ddbf4bfd8baedd32140b2376868f4) Thanks @tim-smart! - add `propagateInterruption` option to Fiber{Handle,Set,Map}\n\n  This option will send any external interrupts to the .join result.\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`718cb70`](https://github.com/Effect-TS/effect/commit/718cb70038629a6d58d02e407760e341f7c94474) Thanks @dilame! - feat(Stream): implement `race` operator, which accepts two upstreams and returns a stream that mirrors the first upstream to emit an item and interrupts the other upstream.\n\n  ```ts\n  import { Stream, Schedule, Console, Effect } from \"effect\"\n\n  const stream = Stream.fromSchedule(Schedule.spaced(\"2 millis\")).pipe(\n    Stream.race(Stream.fromSchedule(Schedule.spaced(\"1 millis\"))),\n    Stream.take(6),\n    Stream.tap((n) => Console.log(n))\n  )\n\n  Effect.runPromise(Stream.runDrain(stream))\n  // Output each millisecond from the first stream, the rest streams are interrupted\n  // 0\n  // 1\n  // 2\n  // 3\n  // 4\n  // 5\n  ```\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`e9d0310`](https://github.com/Effect-TS/effect/commit/e9d03107acbf204d9304f3e8aea0816b7d3c7dfb) Thanks @mikearnaldi! - Avoid automatic propagation of finalizer concurrency, closes #3440\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`6bf28f7`](https://github.com/Effect-TS/effect/commit/6bf28f7e3b1e5e0608ff567205fea0581d11666f) Thanks @tim-smart! - add Context.getOrElse api, for gettings a Tag's value with a fallback\n\n### Patch Changes\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`db89601`](https://github.com/Effect-TS/effect/commit/db89601ee9c1050c4e762b7bd7ec65a6a2799dfe) Thanks @juliusmarminge! - add `Micro.isMicroCause` guard\n\n## 3.6.8\n\n### Patch Changes\n\n- [#3510](https://github.com/Effect-TS/effect/pull/3510) [`e809286`](https://github.com/Effect-TS/effect/commit/e8092865900608c4df7a6b7991b1c13cc1e4ca2d) Thanks @fubhy! - Detect environment in Logger.pretty using process.stdout\n\n## 3.6.7\n\n### Patch Changes\n\n- [#3504](https://github.com/Effect-TS/effect/pull/3504) [`50ec889`](https://github.com/Effect-TS/effect/commit/50ec8897a49b7d1fe84f63107f89d543c52f3dfc) Thanks @datner! - improve the performance of Effect.partitionMap\n\n## 3.6.6\n\n### Patch Changes\n\n- [#3306](https://github.com/Effect-TS/effect/pull/3306) [`f960bf4`](https://github.com/Effect-TS/effect/commit/f960bf45239e9badac6e0ad3a602f4174cd7bbdf) Thanks @dilame! - Introduce left / right naming for Stream apis\n\n- [#3499](https://github.com/Effect-TS/effect/pull/3499) [`46a575f`](https://github.com/Effect-TS/effect/commit/46a575f48a05457b782fb21f7827d338c9b59320) Thanks @tim-smart! - fix nested Config.array, by ensuring path patches aren't applied twice in sequences\n\n## 3.6.5\n\n### Patch Changes\n\n- [#3474](https://github.com/Effect-TS/effect/pull/3474) [`14a47a8`](https://github.com/Effect-TS/effect/commit/14a47a8c1f3cff2186b8fe7a919a1d773888fb5b) Thanks @IMax153! - Add support for incrementing and decrementing a gauge based on its prior value\n\n- [#3490](https://github.com/Effect-TS/effect/pull/3490) [`0c09841`](https://github.com/Effect-TS/effect/commit/0c0984173be3d58f050b300a1a8aa89d76ba49ae) Thanks @tim-smart! - fix type error when .pipe() has no arguments\n\n## 3.6.4\n\n### Patch Changes\n\n- [#3404](https://github.com/Effect-TS/effect/pull/3404) [`8295281`](https://github.com/Effect-TS/effect/commit/8295281ae9bd7441e680402540bf3c8682ec417b) Thanks @KhraksMamtsov! - Fix `Cache<_, Value, _>` type parameter variance (covariant -> invariant)\n\n- [#3452](https://github.com/Effect-TS/effect/pull/3452) [`c940df6`](https://github.com/Effect-TS/effect/commit/c940df63800bf3c4396d91cf28ec34938642fd2c) Thanks @tim-smart! - ensure Scheduler tasks are added to a matching priority bucket\n\n- [#3459](https://github.com/Effect-TS/effect/pull/3459) [`00b6c6d`](https://github.com/Effect-TS/effect/commit/00b6c6d4001f5de728b7d990a1b14560b4961a63) Thanks @tim-smart! - ensure defects are caught in Effect.tryPromise\n\n- [#3458](https://github.com/Effect-TS/effect/pull/3458) [`f8d95a6`](https://github.com/Effect-TS/effect/commit/f8d95a61ad0762147933c5c32bb6d7237e18eef4) Thanks @thomasvargiu! - fix `DateTime.makeZonedFromString` for 0 offset\n\n## 3.6.3\n\n### Patch Changes\n\n- [#3444](https://github.com/Effect-TS/effect/pull/3444) [`04adcac`](https://github.com/Effect-TS/effect/commit/04adcace913e6fc483df266874a68005e9e04ccf) Thanks @tim-smart! - ensure Stream.toReadableStream pulls always result in a enqueue\n\n## 3.6.2\n\n### Patch Changes\n\n- [#3435](https://github.com/Effect-TS/effect/pull/3435) [`fd4b2f6`](https://github.com/Effect-TS/effect/commit/fd4b2f6516b325740dde615f1cf0229edf13ca0c) Thanks @Andarist! - ensure fiber is properly cleared in FiberHandle.unsafeSet\n\n## 3.6.1\n\n### Patch Changes\n\n- [#3405](https://github.com/Effect-TS/effect/pull/3405) [`510a34d`](https://github.com/Effect-TS/effect/commit/510a34d4cc5d2f51347a53847f6c7db84d2b17c6) Thanks @KhraksMamtsov! - Fix `Effect.repeat` with times option returns wrong value\n\n- [#3398](https://github.com/Effect-TS/effect/pull/3398) [`45dbb9f`](https://github.com/Effect-TS/effect/commit/45dbb9ffeaf93d9e4df99d0cd4920e41ba9a3978) Thanks @sukovanej! - Fix `Stream.asyncPush` type signature - allow the `register` effect to fail.\n\n## 3.6.0\n\n### Minor Changes\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`1e0fe80`](https://github.com/Effect-TS/effect/commit/1e0fe802b36c257971296617473ce0abe730e8dc) Thanks @tim-smart! - make List.Cons extend NonEmptyIterable\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`8135294`](https://github.com/Effect-TS/effect/commit/8135294b591ea94fde7e6f94a504608f0e630520) Thanks @tim-smart! - add DateTime module\n\n  The `DateTime` module provides functionality for working with time, including\n  support for time zones and daylight saving time.\n\n  It has two main data types: `DateTime.Utc` and `DateTime.Zoned`.\n\n  A `DateTime.Utc` represents a time in Coordinated Universal Time (UTC), and\n  a `DateTime.Zoned` contains both a UTC timestamp and a time zone.\n\n  There is also a `CurrentTimeZone` service, for setting a time zone contextually.\n\n  ```ts\n  import { DateTime, Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    // Get the current time in the current time zone\n    const now = yield* DateTime.nowInCurrentZone\n\n    // Math functions are included\n    const tomorrow = DateTime.add(now, 1, \"day\")\n\n    // Convert to a different time zone\n    // The UTC portion of the `DateTime` is preserved and only the time zone is\n    // changed\n    const sydneyTime = tomorrow.pipe(\n      DateTime.unsafeSetZoneNamed(\"Australia/Sydney\")\n    )\n  }).pipe(DateTime.withCurrentZoneNamed(\"America/New_York\"))\n  ```\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987) Thanks @tim-smart! - add Stream.asyncPush api\n\n  This api creates a stream from an external push-based resource.\n\n  You can use the `emit` helper to emit values to the stream. You can also use\n  the `emit` helper to signal the end of the stream by using apis such as\n  `emit.end` or `emit.fail`.\n\n  By default it uses an \"unbounded\" buffer size.\n  You can customize the buffer size and strategy by passing an object as the\n  second argument with the `bufferSize` and `strategy` fields.\n\n  ```ts\n  import { Effect, Stream } from \"effect\"\n\n  Stream.asyncPush<string>(\n    (emit) =>\n      Effect.acquireRelease(\n        Effect.gen(function* () {\n          yield* Effect.log(\"subscribing\")\n          return setInterval(() => emit.single(\"tick\"), 1000)\n        }),\n        (handle) =>\n          Effect.gen(function* () {\n            yield* Effect.log(\"unsubscribing\")\n            clearInterval(handle)\n          })\n      ),\n    { bufferSize: 16, strategy: \"dropping\" }\n  )\n  ```\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`3845646`](https://github.com/Effect-TS/effect/commit/3845646828e98f3c7cda1217f6cfe5f642ac0603) Thanks @mikearnaldi! - Implement Struct.keys as a typed alternative to Object.keys\n\n  ```ts\n  import { Struct } from \"effect\"\n\n  const symbol: unique symbol = Symbol()\n\n  const value = {\n    a: 1,\n    b: 2,\n    [symbol]: 3\n  }\n\n  const keys: Array<\"a\" | \"b\"> = Struct.keys(value)\n  ```\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`2d09078`](https://github.com/Effect-TS/effect/commit/2d09078c5948b37fc2f79ef858fe4ca3e4814085) Thanks @sukovanej! - Add `Random.choice`.\n\n  ```ts\n  import { Random } from \"effect\"\n\n  Effect.gen(function* () {\n    const randomItem = yield* Random.choice([1, 2, 3])\n    console.log(randomItem)\n  })\n  ```\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`4bce5a0`](https://github.com/Effect-TS/effect/commit/4bce5a0274203550ccf117d830721891b0a3d182) Thanks @vinassefranche! - Add onlyEffect option to Effect.tap\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`4ddbff0`](https://github.com/Effect-TS/effect/commit/4ddbff0bb4e3ffddfeb509c59835b83245fb975e) Thanks @KhraksMamtsov! - Support `Refinement` in `Predicate.tuple` and `Predicate.struct`\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`e74cc38`](https://github.com/Effect-TS/effect/commit/e74cc38cb420a320c4d7ef98180f19d452a8b316) Thanks @dilame! - Implement `Stream.onEnd` that adds an effect to be executed at the end of the stream.\n\n  ```ts\n  import { Console, Effect, Stream } from \"effect\"\n\n  const stream = Stream.make(1, 2, 3).pipe(\n    Stream.map((n) => n * 2),\n    Stream.tap((n) => Console.log(`after mapping: ${n}`)),\n    Stream.onEnd(Console.log(\"Stream ended\"))\n  )\n\n  Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n  // after mapping: 2\n  // after mapping: 4\n  // after mapping: 6\n  // Stream ended\n  // { _id: 'Chunk', values: [ 2, 4, 6 ] }\n  ```\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`bb069b4`](https://github.com/Effect-TS/effect/commit/bb069b49ef291c532a02c1e8e74271f6d1bb32ec) Thanks @dilame! - Implement `Stream.onStart` that adds an effect to be executed at the start of the stream.\n\n  ```ts\n  import { Console, Effect, Stream } from \"effect\"\n\n  const stream = Stream.make(1, 2, 3).pipe(\n    Stream.onStart(Console.log(\"Stream started\")),\n    Stream.map((n) => n * 2),\n    Stream.tap((n) => Console.log(`after mapping: ${n}`))\n  )\n\n  Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n  // Stream started\n  // after mapping: 2\n  // after mapping: 4\n  // after mapping: 6\n  // { _id: 'Chunk', values: [ 2, 4, 6 ] }\n  ```\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987) Thanks @tim-smart! - add `bufferSize` option to Stream.fromEventListener\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`7d02174`](https://github.com/Effect-TS/effect/commit/7d02174af3bcbf054e5cdddb821c91d0f47e8285) Thanks @fubhy! - Changed various function signatures to return `Array` instead of `ReadonlyArray`\n\n## 3.5.9\n\n### Patch Changes\n\n- [#3377](https://github.com/Effect-TS/effect/pull/3377) [`6359644`](https://github.com/Effect-TS/effect/commit/635964446323cf55d4060559337e710e4a24496e) Thanks @tim-smart! - add MicroScheduler to Micro module\n\n- [#3362](https://github.com/Effect-TS/effect/pull/3362) [`7f41e42`](https://github.com/Effect-TS/effect/commit/7f41e428830bf3043b8be0d28dcd235d5747c942) Thanks @IMax153! - Add `Service` and `Identifier` to `Context.Tag`.\n\n  These helpers can be used, for example, to extract the service shape from a tag:\n\n  ```ts\n  import * as Context from \"effect/Context\"\n\n  export class Foo extends Context.Tag(\"Foo\")<\n    Foo,\n    {\n      readonly foo: Effect.Effect<void>\n    }\n  >() {}\n\n  type ServiceShape = typeof Foo.Service\n  ```\n\n- [#3373](https://github.com/Effect-TS/effect/pull/3373) [`f566fd1`](https://github.com/Effect-TS/effect/commit/f566fd1d7eea531a0d981dd24037f14a603a1273) Thanks @KhraksMamtsov! - Add test for Hash.number(0.1) !== Has.number(0)\n\n## 3.5.8\n\n### Patch Changes\n\n- [#3345](https://github.com/Effect-TS/effect/pull/3345) [`1ba640c`](https://github.com/Effect-TS/effect/commit/1ba640c702f187a866023bf043c26e25cce941ef) Thanks @mikearnaldi! - Fix typo propety to property\n\n- [#3349](https://github.com/Effect-TS/effect/pull/3349) [`c8c71bd`](https://github.com/Effect-TS/effect/commit/c8c71bd20eb87d23133dac6156b83bb08941597c) Thanks @tim-smart! - ensure all Data.Error arguments are preserved in .toJSON\n\n- [#3355](https://github.com/Effect-TS/effect/pull/3355) [`a26ce58`](https://github.com/Effect-TS/effect/commit/a26ce581ca7d407e1e81439b58c8045b3fa65231) Thanks @tim-smart! - fix Hash.number not returning unique values\n\n## 3.5.7\n\n### Patch Changes\n\n- [#3288](https://github.com/Effect-TS/effect/pull/3288) [`3afcc93`](https://github.com/Effect-TS/effect/commit/3afcc93413a3d910beb69e4ce9ae120e4adaffd5) Thanks @mikearnaldi! - Forbid usage of property \"name\" in Effect.Tag\n\n- [#3310](https://github.com/Effect-TS/effect/pull/3310) [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc) Thanks @fubhy! - Added additional pure annotations to improve tree-shakeability\n\n## 3.5.6\n\n### Patch Changes\n\n- [#3294](https://github.com/Effect-TS/effect/pull/3294) [`cc327a1`](https://github.com/Effect-TS/effect/commit/cc327a1bccd22a4ee27ec7e58b53205e93b23e2c) Thanks @tim-smart! - correctly exclude symbols from Record.keys\n\n- [#3289](https://github.com/Effect-TS/effect/pull/3289) [`4bfe4fb`](https://github.com/Effect-TS/effect/commit/4bfe4fb5c82f597c9beea9baa92e772593598b60) Thanks @dilame! - Changed `Stream.groupByKey`/`Stream.grouped`/`Stream.groupedWithin` JSDoc category from `utils` to `grouping`\n\n- [#3295](https://github.com/Effect-TS/effect/pull/3295) [`2b14d18`](https://github.com/Effect-TS/effect/commit/2b14d181462cad8359da4fa6bc6dfda0f742c398) Thanks @tim-smart! - fix YieldableError rendering on bun\n\n## 3.5.5\n\n### Patch Changes\n\n- [#3266](https://github.com/Effect-TS/effect/pull/3266) [`a9d7800`](https://github.com/Effect-TS/effect/commit/a9d7800f6a253192b653d77778b0674f39b1ca39) Thanks @tim-smart! - use \"unbounded\" buffer for Stream.fromEventListener\n\n## 3.5.4\n\n### Patch Changes\n\n- [#3253](https://github.com/Effect-TS/effect/pull/3253) [`ed0dde4`](https://github.com/Effect-TS/effect/commit/ed0dde4888e6f1a97ad5bba06b755d26a6a1c52e) Thanks @tim-smart! - update dependencies\n\n- [#3247](https://github.com/Effect-TS/effect/pull/3247) [`ca775ce`](https://github.com/Effect-TS/effect/commit/ca775cec53baebc1a43d9b8852a3ac6726178498) Thanks @tim-smart! - if performance.timeOrigin is 0, use performance.now() directly in Clock\n\n  This is a workaround for cloudflare, where performance.now() cannot be used in\n  the global scope to calculate the origin.\n\n- [#3259](https://github.com/Effect-TS/effect/pull/3259) [`5be9cc0`](https://github.com/Effect-TS/effect/commit/5be9cc044025a9541b9b7acefa2d3fc05fa1301b) Thanks @IMax153! - expose `Channel.isChannel`\n\n- [#3250](https://github.com/Effect-TS/effect/pull/3250) [`203658f`](https://github.com/Effect-TS/effect/commit/203658f8001c132b25764ab70344b171683b554c) Thanks @gcanti! - add support for `Refinement`s to `Predicate.or`, closes #3243\n\n  ```ts\n  import { Predicate } from \"effect\"\n\n  // Refinement<unknown, string | number>\n  const isStringOrNumber = Predicate.or(Predicate.isString, Predicate.isNumber)\n  ```\n\n- [#3246](https://github.com/Effect-TS/effect/pull/3246) [`eb1c4d4`](https://github.com/Effect-TS/effect/commit/eb1c4d44e54b9d8d201a366d1ff94face2a6dcd3) Thanks @tim-smart! - render nested causes in Cause.pretty\n\n## 3.5.3\n\n### Patch Changes\n\n- [#3234](https://github.com/Effect-TS/effect/pull/3234) [`edb0da3`](https://github.com/Effect-TS/effect/commit/edb0da383746d760f35d8582f5fb0cc0eeca9217) Thanks @tim-smart! - do not add a error \"cause\" if the upstream error does not contain one\n\n- [#3236](https://github.com/Effect-TS/effect/pull/3236) [`c8d3fb0`](https://github.com/Effect-TS/effect/commit/c8d3fb0fe23585f6efb724af51fbab3ba1ad6e83) Thanks @tim-smart! - set Logger.pretty message color to deepskyblue on browsers\n\n- [#3240](https://github.com/Effect-TS/effect/pull/3240) [`dabd028`](https://github.com/Effect-TS/effect/commit/dabd028decf9b7983ca16ebe0f48c05c11a84b68) Thanks @tim-smart! - fix process .isTTY detection\n\n- [#3230](https://github.com/Effect-TS/effect/pull/3230) [`786b2ab`](https://github.com/Effect-TS/effect/commit/786b2ab29d525c877bb84035dac9e2d6499339d1) Thanks @KhraksMamtsov! - support heterogenous argument in `Option.firstSomeOf`\n\n- [#3238](https://github.com/Effect-TS/effect/pull/3238) [`fc57354`](https://github.com/Effect-TS/effect/commit/fc573547d41667016fce05eaee75960fcc6dce4d) Thanks @leonitousconforti! - Align Stream.run public function signatures\n\n## 3.5.2\n\n### Patch Changes\n\n- [#3228](https://github.com/Effect-TS/effect/pull/3228) [`639208e`](https://github.com/Effect-TS/effect/commit/639208eeb8a44622994f832bc2d45d06ab636bc8) Thanks @IMax153! - Render a more helpful error message when timing out an effect\n\n- [#3235](https://github.com/Effect-TS/effect/pull/3235) [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5) Thanks @tim-smart! - improve safari support for Logger.pretty\n\n- [#3235](https://github.com/Effect-TS/effect/pull/3235) [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5) Thanks @tim-smart! - fix span stack rendering when stack function returns undefined\n\n- [#3235](https://github.com/Effect-TS/effect/pull/3235) [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5) Thanks @tim-smart! - align UnsafeConsole group types with web apis\n\n## 3.5.1\n\n### Patch Changes\n\n- [#3220](https://github.com/Effect-TS/effect/pull/3220) [`55fdd76`](https://github.com/Effect-TS/effect/commit/55fdd761ee95afd73b6a892c13fee92b36c02837) Thanks @tim-smart! - fix Logger.pretty on bun\n\n## 3.5.0\n\n### Minor Changes\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce) Thanks @tim-smart! - add renderErrorCause option to Cause.pretty\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4) Thanks @tim-smart! - add RcRef module\n\n  An `RcRef` wraps a reference counted resource that can be acquired and released multiple times.\n\n  The resource is lazily acquired on the first call to `get` and released when the last reference is released.\n\n  ```ts\n  import { Effect, RcRef } from \"effect\"\n\n  Effect.gen(function* () {\n    const ref = yield* RcRef.make({\n      acquire: Effect.acquireRelease(Effect.succeed(\"foo\"), () =>\n        Effect.log(\"release foo\")\n      )\n    })\n\n    // will only acquire the resource once, and release it\n    // when the scope is closed\n    yield* RcRef.get(ref).pipe(Effect.andThen(RcRef.get(ref)), Effect.scoped)\n  })\n  ```\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`5ab348f`](https://github.com/Effect-TS/effect/commit/5ab348f265db3d283aa091ddca6d2d49137c16f2) Thanks @tim-smart! - allowing customizing Stream pubsub strategy\n\n  ```ts\n  import { Schedule, Stream } from \"effect\"\n\n  // toPubSub\n  Stream.fromSchedule(Schedule.spaced(1000)).pipe(\n    Stream.toPubSub({\n      capacity: 16, // or \"unbounded\"\n      strategy: \"dropping\" // or \"sliding\" / \"suspend\"\n    })\n  )\n\n  // also for the broadcast apis\n  Stream.fromSchedule(Schedule.spaced(1000)).pipe(\n    Stream.broadcastDynamic({\n      capacity: 16,\n      strategy: \"dropping\"\n    })\n  )\n  ```\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4) Thanks @tim-smart! - add Duration.isZero, for checking if a Duration is zero\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`3e04bf8`](https://github.com/Effect-TS/effect/commit/3e04bf8a7127e956cadb7684a8f4c661df57663b) Thanks @sukovanej! - Add `Success` type util for `Config`.\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3) Thanks @tim-smart! - add Logger.prettyLogger and Logger.pretty\n\n  `Logger.pretty` is a new logger that leverages the features of the `console` APIs to provide a more visually appealing output.\n\n  To try it out, provide it to your program:\n\n  ```ts\n  import { Effect, Logger } from \"effect\"\n\n  Effect.log(\"Hello, World!\").pipe(Effect.provide(Logger.pretty))\n  ```\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce) Thanks @tim-smart! - add .groupCollapsed to UnsafeConsole\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`4626de5`](https://github.com/Effect-TS/effect/commit/4626de59c25b384216faa0be87bf0b8cd36357d0) Thanks @giacomoran! - export Random.make taking hashable values as seed\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`f01e7db`](https://github.com/Effect-TS/effect/commit/f01e7db317827255d7901f523f2e28b43298e8df) Thanks @tim-smart! - add `replay` option to PubSub constructors\n\n  This option adds a replay buffer in front of the given PubSub. The buffer will\n  replay the last `n` messages to any new subscriber.\n\n  ```ts\n  Effect.gen(function*() {\n    const messages = [1, 2, 3, 4, 5]\n    const pubsub = yield* PubSub.bounded<number>({ capacity: 16, replay: 3 })\n    yield* PubSub.publishAll(pubsub, messages)\n    const sub = yield* PubSub.subscribe(pubsub)\n    assert.deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub)), [3, 4, 5])\n  }))\n  ```\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4) Thanks @tim-smart! - add RcMap module\n\n  An `RcMap` can contain multiple reference counted resources that can be indexed\n  by a key. The resources are lazily acquired on the first call to `get` and\n  released when the last reference is released.\n\n  Complex keys can extend `Equal` and `Hash` to allow lookups by value.\n\n  ```ts\n  import { Effect, RcMap } from \"effect\"\n\n  Effect.gen(function* () {\n    const map = yield* RcMap.make({\n      lookup: (key: string) =>\n        Effect.acquireRelease(Effect.succeed(`acquired ${key}`), () =>\n          Effect.log(`releasing ${key}`)\n        )\n    })\n\n    // Get \"foo\" from the map twice, which will only acquire it once\n    // It will then be released once the scope closes.\n    yield* RcMap.get(map, \"foo\").pipe(\n      Effect.andThen(RcMap.get(map, \"foo\")),\n      Effect.scoped\n    )\n  })\n  ```\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`ac71f37`](https://github.com/Effect-TS/effect/commit/ac71f378f2413e5aa91c95f649ffe898d6a26114) Thanks @dilame! - Ensure `Scope` is excluded from `R` in the `Channel` / `Stream` `run*` functions.\n\n  This fix ensures that `Scope` is now properly excluded from the resulting effect environment.\n  The affected functions include `run`, `runCollect`, `runCount`, `runDrain` and other non-scoped `run*` in both `Stream` and `Channel` modules.\n  This fix brings the type declaration in line with the runtime implementation.\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`8432360`](https://github.com/Effect-TS/effect/commit/8432360ce68614a419bb328083a4109d0fc8aa93) Thanks @dilame! - refactor(Stream/mergeLeft): rename `self`/`that` argument names to `left`/`right` for clarity\n\n  refactor(Stream/mergeRight): rename `self`/`that` argument names to `left`/`right` for clarity\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`e4bf1bf`](https://github.com/Effect-TS/effect/commit/e4bf1bf2b4a970eacd77c9b77b5ea8c68bc84498) Thanks @dilame! - feat(Stream): implement \"raceAll\" operator, which returns a stream that mirrors the first source stream to emit an item.\n\n  ```ts\n  import { Stream, Schedule, Console, Effect } from \"effect\"\n\n  const stream = Stream.raceAll(\n    Stream.fromSchedule(Schedule.spaced(\"1 millis\")),\n    Stream.fromSchedule(Schedule.spaced(\"2 millis\")),\n    Stream.fromSchedule(Schedule.spaced(\"4 millis\"))\n  ).pipe(Stream.take(6), Stream.tap(Console.log))\n\n  Effect.runPromise(Stream.runDrain(stream))\n  // Output only from the first stream, the rest streams are interrupted\n  // 0\n  // 1\n  // 2\n  // 3\n  // 4\n  // 5\n  ```\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`13cb861`](https://github.com/Effect-TS/effect/commit/13cb861a5eded15c55c6cdcf6a8acde8320367a6) Thanks @dilame! - refactor(Stream): use new built-in `Types.TupleOf` instead of `Stream.DynamicTuple` and deprecate it\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6) Thanks @tim-smart! - support ErrorOptions in YieldableError constructor\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`9f66825`](https://github.com/Effect-TS/effect/commit/9f66825f1fce0fe8d10420c285f7dc4c71e8af8d) Thanks @tim-smart! - allow customizing the output buffer for the Stream.async\\* apis\n\n  ```ts\n  import { Stream } from \"effect\"\n\n  Stream.async<string>(\n    (emit) => {\n      // ...\n    },\n    {\n      bufferSize: 16,\n      strategy: \"dropping\" // you can also use \"sliding\" or \"suspend\"\n    }\n  )\n  ```\n\n### Patch Changes\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce) Thanks @tim-smart! - include Error.cause stack in log output\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce) Thanks @tim-smart! - set stackTraceLimit to 1 in PrettyError to address performance issues\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6) Thanks @tim-smart! - ensure \"cause\" is rendered in Data.Error output\n\n- [#3048](https://github.com/Effect-TS/effect/pull/3048) [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3) Thanks @tim-smart! - fix types of UnsafeConsole.group\n\n## 3.4.9\n\n### Patch Changes\n\n- [#3210](https://github.com/Effect-TS/effect/pull/3210) [`7af137c`](https://github.com/Effect-TS/effect/commit/7af137c9433f6e74959b3887561ec1e6f12e10ee) Thanks @tim-smart! - prevent reclaim of manually invalidated pool items\n\n- [#3204](https://github.com/Effect-TS/effect/pull/3204) [`ee4b3dc`](https://github.com/Effect-TS/effect/commit/ee4b3dc5f68d19dc3ae1c2d12901c5b8ffbebabb) Thanks @gcanti! - Updated the JSDocs for the `Stream` module by adding examples to key functions.\n\n- [#3202](https://github.com/Effect-TS/effect/pull/3202) [`097d25c`](https://github.com/Effect-TS/effect/commit/097d25cb5d13c049e01789651be56b09620186ef) Thanks @tim-smart! - allow invalidated Pool items to be reclaimed with usage strategy\n\n## 3.4.8\n\n### Patch Changes\n\n- [#3181](https://github.com/Effect-TS/effect/pull/3181) [`a435e0f`](https://github.com/Effect-TS/effect/commit/a435e0fc5378b33a49bcec92ee235df6f16a2419) Thanks @KhraksMamtsov! - refactor `TrimEnd` & `TrimStart`\n\n- [#3176](https://github.com/Effect-TS/effect/pull/3176) [`b5554db`](https://github.com/Effect-TS/effect/commit/b5554db36c4dd6f64fa5e6a62a29b2759c54217a) Thanks @tim-smart! - allow Stream run fiber to close before trying to interrupt it\n\n- [#3175](https://github.com/Effect-TS/effect/pull/3175) [`a9c4fb3`](https://github.com/Effect-TS/effect/commit/a9c4fb3bf3c6e92cd1c142b0605fddf7eb3c697c) Thanks @tim-smart! - ensure fibers are interrupted in Stream.mergeWith\n\n## 3.4.7\n\n### Patch Changes\n\n- [#3161](https://github.com/Effect-TS/effect/pull/3161) [`a5737d6`](https://github.com/Effect-TS/effect/commit/a5737d6db2b921605c332eabbc5402ee3d17357b) Thanks @tim-smart! - ensure PubSub.publishAll does not increase size while there are no subscribers\n\n## 3.4.6\n\n### Patch Changes\n\n- [#3096](https://github.com/Effect-TS/effect/pull/3096) [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030) Thanks @gcanti! - Micro: align with `Effect` module (renamings and new combinators).\n\n  General naming convention rule: `<reference module (start with lowercase)><api (start with Uppercase)>`.\n  - `Failure` -> `MicroCause`\n    - `Failure.Expected<E>` -> `MicroCause.Fail<E>`\n    - `Failure.Unexpected` -> `MicroCause.Die`\n    - `Failure.Aborted` -> `MicroCause.Interrupt`\n    - `FailureExpected` -> `causeFail`\n    - `FailureUnexpected` -> `causeDie`\n    - `FailureAborted` -> `causeInterrupt`\n    - `failureIsExpected` -> `causeIsFail`\n    - `failureIsExpected` -> `causeIsFail`\n    - `failureIsUnexpected` -> `causeIsDie`\n    - `failureIsAborted` -> `causeIsInterrupt`\n    - `failureSquash` -> `causeSquash`\n    - `failureWithTrace` -> `causeWithTrace`\n  - `Result` -> `MicroExit`\n    - `ResultAborted` -> `exitInterrupt`\n    - `ResultSuccess` -> `exitSucceed`\n    - `ResultFail` -> `exitFail`\n    - `ResultFailUnexpected` -> `exitDie`\n    - `ResultFailWith` -> `exitFailCause`\n    - `resultIsSuccess` -> `exitIsSuccess`\n    - `resultIsFailure` -> `exitIsFailure`\n    - `resultIsAborted` -> `exitIsInterrupt`\n    - `resultIsFailureExpected` -> `exitIsFail`\n    - `resultIsFailureUnexpected` -> `exitIsDie`\n    - `resultVoid` -> `exitVoid`\n  - `DelayFn` -> `MicroSchedule`\n    - `delayExponential` -> `scheduleExponential`\n    - `delaySpaced` -> `scheduleSpaced`\n    - `delayWithMax` -> `scheduleWithMaxDelay`\n    - `delayWithMaxElapsed` -> `scheduleWithMaxElapsed`\n    - `delayWithRecurs` -> `scheduleRecurs` and make it a constructor\n    - add `scheduleAddDelay` combinator\n    - add `scheduleUnion` combinator\n    - add `scheduleIntersect` combinator\n  - `Handle`\n    - `abort` -> `interrupt`\n    - `unsafeAbort` -> `unsafeInterrupt`\n  - `provideServiceMicro` -> `provideServiceEffect`\n  - `fromResult` -> `fromExit`\n  - `fromResultSync` -> `fromExitSync`\n  - `failWith` -> `failCause`\n  - `failWithSync` -> `failCauseSync`\n  - `asResult` -> `exit`\n  - `filterOrFailWith` -> `filterOrFailCause`\n  - `repeatResult` -> `repeatExit`\n  - `catchFailure` -> `catchAllCause`\n  - `catchFailureIf` -> `catchCauseIf`\n  - `catchExpected` -> `catchAll`\n  - `catchUnexpected` -> `catchAllDefect`\n  - `tapFailure` -> `tapErrorCause`\n  - `tapFailureIf` -> `tapErrorCauseIf`\n  - `tapExpected` -> `tapError`\n  - `tapUnexpected` -> `tapDefect`\n  - `mapFailure` -> `mapErrorCause`\n  - `matchFailureMicro` -> `matchCauseEffect`\n  - `matchFailure` -> `matchCause`\n  - `matchMicro` -> `matchEffect`\n  - `onResult` -> `onExit`\n  - `onResultIf` -> `onExitIf`\n  - `onFailure` -> `onError`\n  - `onAbort` -> `onInterrupt`\n  - `abort` -> `interrupt`\n  - `runPromiseResult` -> `runPromiseExit`\n  - `runSyncResult` -> `runSyncExit`\n  - rename `delay` option to `schedule`\n\n- [#3096](https://github.com/Effect-TS/effect/pull/3096) [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030) Thanks @gcanti! - Micro: rename `timeout` to `timeoutOption`, and add a `timeout` that fails with a `TimeoutException`\n\n- [#3121](https://github.com/Effect-TS/effect/pull/3121) [`33735b1`](https://github.com/Effect-TS/effect/commit/33735b16b41bd26929d8f4754c190925db6323b7) Thanks @KhraksMamtsov! - Support for the tacit usage of external handlers for `Match.tag` and `Match.tagStartsWith` functions\n\n  ```ts\n  type Value = { _tag: \"A\"; a: string } | { _tag: \"B\"; b: number }\n  const handlerA = (_: { _tag: \"A\"; a: number }) => _.a\n\n  // $ExpectType string | number\n  pipe(\n    M.type<Value>(),\n    M.tag(\"A\", handlerA), // <-- no type issue\n    M.orElse((_) => _.b)\n  )(value)\n  ```\n\n- [#3096](https://github.com/Effect-TS/effect/pull/3096) [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030) Thanks @gcanti! - Micro: move MicroExit types to a namespace\n\n- [#3134](https://github.com/Effect-TS/effect/pull/3134) [`139d4b3`](https://github.com/Effect-TS/effect/commit/139d4b39fb3bff2eeaa7c0c809c581da42425a83) Thanks @tim-smart! - use Channel.acquireUseRelease for Channel.withSpan\n\n## 3.4.5\n\n### Patch Changes\n\n- [#3099](https://github.com/Effect-TS/effect/pull/3099) [`a047af9`](https://github.com/Effect-TS/effect/commit/a047af99447dfffc729e9c8ef0ca143537927e91) Thanks @tim-smart! - fix using unions with Match.withReturnType\n\n## 3.4.4\n\n### Patch Changes\n\n- [#3083](https://github.com/Effect-TS/effect/pull/3083) [`72638e3`](https://github.com/Effect-TS/effect/commit/72638e3d99f0e93a24febf6c225256ce92d4a20b) Thanks @gcanti! - Micro: add `NoSuchElementException` error and update `fromOption` to change the failure type from `Option.None<never>` to `NoSuchElementException`\n\n- [#3095](https://github.com/Effect-TS/effect/pull/3095) [`d7dde2b`](https://github.com/Effect-TS/effect/commit/d7dde2b4af08b37af859d4c327c1f5c6f00cf9d9) Thanks @tim-smart! - remove global AbortController from Micro\n\n- [#3085](https://github.com/Effect-TS/effect/pull/3085) [`9b2fc3b`](https://github.com/Effect-TS/effect/commit/9b2fc3b9dfd304a2bd0508ef2313cfc54357be0c) Thanks @gcanti! - Micro: add `zipWith`\n\n## 3.4.3\n\n### Patch Changes\n\n- [#3065](https://github.com/Effect-TS/effect/pull/3065) [`c342739`](https://github.com/Effect-TS/effect/commit/c3427396226e1ad7b95b40595a23f9bdff3e3365) Thanks @KhraksMamtsov! - Support `this` argument for `Micro.gen`\n\n- [#3067](https://github.com/Effect-TS/effect/pull/3067) [`8898e5e`](https://github.com/Effect-TS/effect/commit/8898e5e238622f6337583d91ee23609c1f5ccdf7) Thanks @KhraksMamtsov! - Cleanup signal \"abort\" event handler in `Micro.runFork`\n\n- [#3082](https://github.com/Effect-TS/effect/pull/3082) [`ff78636`](https://github.com/Effect-TS/effect/commit/ff786367c522975f40f0f179a0ecdfcfab7ecbdb) Thanks @gcanti! - Align the `Micro.catchIf` signature with `Effect.catchIf`\n\n- [#3078](https://github.com/Effect-TS/effect/pull/3078) [`c86bd4e`](https://github.com/Effect-TS/effect/commit/c86bd4e134c23146c216f9ff97e03781d55991b6) Thanks @KhraksMamtsov! - Support unification for Micro module\n\n- [#3079](https://github.com/Effect-TS/effect/pull/3079) [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd) Thanks @tim-smart! - update to typescript 5.5\n\n## 3.4.2\n\n### Patch Changes\n\n- [#3062](https://github.com/Effect-TS/effect/pull/3062) [`3da1497`](https://github.com/Effect-TS/effect/commit/3da1497b5c9cc886d300258bc928fd68a4fefe6f) Thanks @KhraksMamtsov! - Reuse centralized do-notation code\n\n## 3.4.1\n\n### Patch Changes\n\n- [#3056](https://github.com/Effect-TS/effect/pull/3056) [`66a1910`](https://github.com/Effect-TS/effect/commit/66a19109ff90c4252123b8809b8c8a74681dba6a) Thanks @gcanti! - add missing `TypeLambda` to `Micro` module\n\n## 3.4.0\n\n### Minor Changes\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`c0ce180`](https://github.com/Effect-TS/effect/commit/c0ce180861ad0938053c0e6145e813fa6404df3b) Thanks @LaureRC! - Make Option.liftPredicate dual\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`61707b6`](https://github.com/Effect-TS/effect/commit/61707b6ffc7397c2ba0dce22512b44955724f60f) Thanks @LaureRC! - Add Effect.liftPredicate\n\n  `Effect.liftPredicate` transforms a `Predicate` function into an `Effect` returning the input value if the predicate returns `true` or failing with specified error if the predicate fails.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  const isPositive = (n: number): boolean => n > 0\n\n  // succeeds with `1`\n  Effect.liftPredicate(1, isPositive, (n) => `${n} is not positive`)\n\n  // fails with `\"0 is not positive\"`\n  Effect.liftPredicate(0, isPositive, (n) => `${n} is not positive`)\n  ```\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`9c1b5b3`](https://github.com/Effect-TS/effect/commit/9c1b5b39e6c19604ce834f072a114ad392c50a06) Thanks @tim-smart! - add EventListener type to Stream to avoid use of dom lib\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`a35faf8`](https://github.com/Effect-TS/effect/commit/a35faf8d116f94899bfc03feab33b004c8ddfdf7) Thanks @gcanti! - Add `lastNonEmpty` function to `Chunk` module, closes #2946\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`ff73c0c`](https://github.com/Effect-TS/effect/commit/ff73c0cacd66132bfad2e5211b3eae347729c667) Thanks @dilame! - feat(Stream): implement Success, Error, Context type accessors\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`984d516`](https://github.com/Effect-TS/effect/commit/984d516ccd9412dc41188f6a46b748dd20dd5848) Thanks @tim-smart! - add Micro module\n\n  A lightweight alternative to Effect, for when bundle size really matters.\n\n  At a minimum, Micro adds 5kb gzipped to your bundle, and scales with the amount\n  of features you use.\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`8c3b8a2`](https://github.com/Effect-TS/effect/commit/8c3b8a2ce208eab753b6206a51605a424f104e98) Thanks @gcanti! - add `ManagedRuntime` type utils (`Context`, and `Error`)\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`017e2f9`](https://github.com/Effect-TS/effect/commit/017e2f9b371ce24ea4945e5d7390c934ad3c39cf) Thanks @LaureRC! - Add Either.liftPredicate\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`91bf8a2`](https://github.com/Effect-TS/effect/commit/91bf8a2e9d1959393b3cf7366cc1d584d3e666b7) Thanks @msensys! - Add `Tuple.at` api, to retrieve an element at a specified index from a tuple.\n\n  ```ts\n  import { Tuple } from \"effect\"\n\n  assert.deepStrictEqual(Tuple.at([1, \"hello\", true], 1), \"hello\")\n  ```\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`c6a4a26`](https://github.com/Effect-TS/effect/commit/c6a4a266606575fd2c7165940c4072ad4c57d01f) Thanks @datner! - add `ensure` util for Array, used to normalize `A | ReadonlyArray<A>`\n\n  ```ts\n  import { ensure } from \"effect/Array\"\n\n  // lets say you are not 100% sure if it's a member or a collection\n  declare const someValue: { foo: string } | Array<{ foo: string }>\n\n  // $ExpectType ({ foo: string })[]\n  const normalized = ensure(someValue)\n  ```\n\n## 3.3.5\n\n### Patch Changes\n\n- [#3012](https://github.com/Effect-TS/effect/pull/3012) [`6c89408`](https://github.com/Effect-TS/effect/commit/6c89408cd7b9204ec4c5828a46cd5312d8afb5e7) Thanks @tim-smart! - ensure Config.Wrap only destructures plain objects\n\n## 3.3.4\n\n### Patch Changes\n\n- [#3001](https://github.com/Effect-TS/effect/pull/3001) [`a67b8fe`](https://github.com/Effect-TS/effect/commit/a67b8fe2ace08419424811b5f0d9a5378eaea352) Thanks @tim-smart! - use Math.random for Hash.random\n\n## 3.3.3\n\n### Patch Changes\n\n- [#2999](https://github.com/Effect-TS/effect/pull/2999) [`06ede85`](https://github.com/Effect-TS/effect/commit/06ede85d6e84710e6622463be95ff3927fb30dad) Thanks @KhraksMamtsov! - Added tests for `Chunk.toArray` and `Chunk.toReadonlyArray` with use cases in the `pipe`\n\n- [#3000](https://github.com/Effect-TS/effect/pull/3000) [`7204ca5`](https://github.com/Effect-TS/effect/commit/7204ca5761c2b1d27999a624db23aa10b6e0504d) Thanks @tim-smart! - fix support for Predicates in Predicate.compose\n\n## 3.3.2\n\n### Patch Changes\n\n- [#2981](https://github.com/Effect-TS/effect/pull/2981) [`3572646`](https://github.com/Effect-TS/effect/commit/3572646d5e0804f85bc7f64633fb95722533f9dd) Thanks @tim-smart! - ensure multiline error messages are preserved in cause rendering\n\n- [#2970](https://github.com/Effect-TS/effect/pull/2970) [`1aed347`](https://github.com/Effect-TS/effect/commit/1aed347a125ed3847ec90863424810d6759cbc85) Thanks @gcanti! - Updated `Chunk.toArray` and `Chunk.toReadonlyArray`. Improved function signatures to preserve non-empty status of chunks during conversion.\n\n- [#2977](https://github.com/Effect-TS/effect/pull/2977) [`df4bf4b`](https://github.com/Effect-TS/effect/commit/df4bf4b62e7b316c6647da0271fc5544a84e7ba2) Thanks @tim-smart! - fix discard option in Effect.all\n\n- [#2917](https://github.com/Effect-TS/effect/pull/2917) [`f085f92`](https://github.com/Effect-TS/effect/commit/f085f92dfa204afb41823ffc27d437225137643d) Thanks @mikearnaldi! - Fix Unify for Stream\n\n## 3.3.1\n\n### Patch Changes\n\n- [#2952](https://github.com/Effect-TS/effect/pull/2952) [`eb98c5b`](https://github.com/Effect-TS/effect/commit/eb98c5b79ab50aa0cde239bd4e660dd19dbab612) Thanks @KhraksMamtsov! - Change `Config.array` to return `Array<A>` instead of `ReadonlyArray<A>`\n\n- [#2950](https://github.com/Effect-TS/effect/pull/2950) [`184fed8`](https://github.com/Effect-TS/effect/commit/184fed83ac36cba05a75a5a8013f740f9f696e3b) Thanks @gcanti! - Ensure `Chunk.reverse` preserves `NonEmpty` status, closes #2947\n\n- [#2954](https://github.com/Effect-TS/effect/pull/2954) [`6068e07`](https://github.com/Effect-TS/effect/commit/6068e073d4cc8b3c8583583fd5eb3efe43f7d5ba) Thanks @jessekelly881! - Fix runtime error in `Struct.evolve` by enhancing compile-time checks, closes #2953\n\n- [#2948](https://github.com/Effect-TS/effect/pull/2948) [`3a77e20`](https://github.com/Effect-TS/effect/commit/3a77e209783933bac3aaddba1b05ff6a9ac72b36) Thanks @gcanti! - Remove unnecessary `===` comparison in `getEquivalence` functions\n\n  In some `getEquivalence` functions that use `make`, there is an unnecessary `===` comparison. The `make` function already handles this comparison.\n\n## 3.3.0\n\n### Minor Changes\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`1f4ac00`](https://github.com/Effect-TS/effect/commit/1f4ac00a91c336c9c9c9b8c3ed9ceb9920ebc9bd) Thanks @dilame! - add `Stream.zipLatestAll` api\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`9305b76`](https://github.com/Effect-TS/effect/commit/9305b764cceeae4f16564435ae7172f79c2bf822) Thanks @mattrossman! - Add queuing strategy option for Stream.toReadableStream\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`0f40d98`](https://github.com/Effect-TS/effect/commit/0f40d989da10f68df3ecd72b36849401ad679bfb) Thanks @tim-smart! - add `timeToLiveStrategy` to `Pool` options\n\n  The `timeToLiveStrategy` determines how items are invalidated. If set to\n  \"creation\", then items are invalidated based on their creation time. If set\n  to \"usage\", then items are invalidated based on pool usage.\n\n  By default, the `timeToLiveStrategy` is set to \"usage\".\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`b761ef0`](https://github.com/Effect-TS/effect/commit/b761ef00eaf6c67b7ffe34798b98aae5347ab376) Thanks @tim-smart! - add Layer.annotateLogs & Layer.annotateSpans\n\n  This allows you to add log & span annotation to a Layer.\n\n  ```ts\n  import { Effect, Layer } from \"effect\"\n\n  Layer.effectDiscard(Effect.log(\"hello\")).pipe(\n    Layer.annotateLogs({\n      service: \"my-service\"\n    })\n  )\n  ```\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`b53f69b`](https://github.com/Effect-TS/effect/commit/b53f69bff1452a487b21198cd83961f844e02d36) Thanks @dilame! - Types: implement `TupleOf` and `TupleOfAtLeast` types\n\n  Predicate: implement `isTupleOf` and `isTupleOfAtLeast` type guards\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`0f40d98`](https://github.com/Effect-TS/effect/commit/0f40d989da10f68df3ecd72b36849401ad679bfb) Thanks @tim-smart! - add `concurrency` & `targetUtilization` option to `Pool.make` & `Pool.makeWithTTL`\n\n  This option allows you to specify the level of concurrent access per pool item.\n  I.e. setting `concurrency: 2` will allow each pool item to be in use by 2 concurrent tasks.\n\n  `targetUtilization` determines when to create new pool items. It is a value\n  between 0 and 1, where 1 means only create new pool items when all the existing\n  items are fully utilized.\n\n  A `targetUtilization` of 0.5 will create new pool items when the existing items are\n  50% utilized.\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`5bd549e`](https://github.com/Effect-TS/effect/commit/5bd549e4bd7144727db438ecca6b8dc9b3ef7e22) Thanks @KhraksMamtsov! - Support `this` argument for `{STM, Either, Option}.gen`\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`67f160a`](https://github.com/Effect-TS/effect/commit/67f160a213de0219a565d4bf653b3cbf24f58e8f) Thanks @KhraksMamtsov! - Introduced `Redacted<out T = string>` module - `Secret` generalization\n  `Secret extends Redacted`\n  The use of the `Redacted` has been replaced by the use of the `Redacted` in packages with version `0.*.*`\n\n## 3.2.9\n\n### Patch Changes\n\n- [#2921](https://github.com/Effect-TS/effect/pull/2921) [`8c5d280`](https://github.com/Effect-TS/effect/commit/8c5d280c0402284a4e58372867a15a431cb99461) Thanks @tim-smart! - remove usage of performance.timeOrigin\n\n- [#2912](https://github.com/Effect-TS/effect/pull/2912) [`6ba6d26`](https://github.com/Effect-TS/effect/commit/6ba6d269f5891e6b11aa35c5281dde4bf3273004) Thanks @mikearnaldi! - Remove toJSON from PrettyError and fix message generation\n\n- [#2923](https://github.com/Effect-TS/effect/pull/2923) [`3f28bf2`](https://github.com/Effect-TS/effect/commit/3f28bf274333611906175446b772243f34f1b6d5) Thanks @tim-smart! - only wrap objects with string keys in Config.Wrap\n\n- [#2914](https://github.com/Effect-TS/effect/pull/2914) [`5817820`](https://github.com/Effect-TS/effect/commit/58178204a770d1a78c06945ef438f9fffbb50afa) Thanks @mikearnaldi! - Fix id extraction in Context.Tag.Identifier\n\n## 3.2.8\n\n### Patch Changes\n\n- [#2894](https://github.com/Effect-TS/effect/pull/2894) [`fb91f17`](https://github.com/Effect-TS/effect/commit/fb91f17098b48497feca9ec976feb87e4a82451b) Thanks @mikearnaldi! - ensure Equal considers Date by value\n\n## 3.2.7\n\n### Patch Changes\n\n- [#2887](https://github.com/Effect-TS/effect/pull/2887) [`6801fca`](https://github.com/Effect-TS/effect/commit/6801fca44366be3ee1b6b99f54bd4f38a1b5e4f4) Thanks @mikearnaldi! - Ensure provide of runtime is additive on context\n\n## 3.2.6\n\n### Patch Changes\n\n- [#2879](https://github.com/Effect-TS/effect/pull/2879) [`cc8ac50`](https://github.com/Effect-TS/effect/commit/cc8ac5080daba8622ca2ff5dab5c37ddfab732ba) Thanks @TylorS! - Support tuples in Types.DeepMutable\n\n## 3.2.5\n\n### Patch Changes\n\n- [#2823](https://github.com/Effect-TS/effect/pull/2823) [`608b01f`](https://github.com/Effect-TS/effect/commit/608b01fc342dbae2a642b308a67b84ead530ecea) Thanks @gcanti! - Array: simplify signatures (`ReadonlyArray<any> | Iterable<any> = Iterable<any>`)\n\n- [#2834](https://github.com/Effect-TS/effect/pull/2834) [`031c712`](https://github.com/Effect-TS/effect/commit/031c7122a24ac42e48d6a434646b4f5d279d7442) Thanks @tim-smart! - attach Stream.toReadableStream fibers to scope\n\n- [#2744](https://github.com/Effect-TS/effect/pull/2744) [`a44e532`](https://github.com/Effect-TS/effect/commit/a44e532cf3a6a498b12a5aacf8124aa267e24ba0) Thanks @KhraksMamtsov! - make `Array.separate`, `Array.getRights`, `Array.getLefts`, `Array.getSomes` heterogeneous\n\n## 3.2.4\n\n### Patch Changes\n\n- [#2801](https://github.com/Effect-TS/effect/pull/2801) [`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3) Thanks @tim-smart! - ensure pool calls finalizer for failed acquisitions\n\n- [#2808](https://github.com/Effect-TS/effect/pull/2808) [`e313a01`](https://github.com/Effect-TS/effect/commit/e313a01b7e80f6cb7704055a190e5623c9d22c6d) Thanks @gcanti! - Array: fix `flatMapNullable` implementation and add descriptions / examples\n\n## 3.2.3\n\n### Patch Changes\n\n- [#2805](https://github.com/Effect-TS/effect/pull/2805) [`45578e8`](https://github.com/Effect-TS/effect/commit/45578e8faa80ae33d23e08f6f19467f818b7788f) Thanks @tim-smart! - fix internal cutpoint name preservation\n\n## 3.2.2\n\n### Patch Changes\n\n- [#2787](https://github.com/Effect-TS/effect/pull/2787) [`5d9266e`](https://github.com/Effect-TS/effect/commit/5d9266e8c740746ac9e186c3df6090a1b57fbe2a) Thanks @mikearnaldi! - Prohibit name clashes in Effect.Tag\n\n  The following now correctly flags a type error given that the property `context` exists already in `Tag`:\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  class LoaderArgs extends Effect.Tag(\"@services/LoaderContext\")<\n    LoaderArgs,\n    { context: number }\n  >() {}\n  ```\n\n- [#2797](https://github.com/Effect-TS/effect/pull/2797) [`9f8122e`](https://github.com/Effect-TS/effect/commit/9f8122e78884ab47c5e5f364d86eee1d1543cc61) Thanks @mikearnaldi! - Improve internalization of functions to clean stack traces\n\n- [#2798](https://github.com/Effect-TS/effect/pull/2798) [`6a6f670`](https://github.com/Effect-TS/effect/commit/6a6f6706b8613c8c7c10971b8d81a0f9e440a6f2) Thanks @mikearnaldi! - Avoid eager read of the stack when captured by a span\n\n## 3.2.1\n\n### Patch Changes\n\n- [#2779](https://github.com/Effect-TS/effect/pull/2779) [`c1e991d`](https://github.com/Effect-TS/effect/commit/c1e991dd5ba87901cd0e05697a8b4a267e7e954a) Thanks [@tim-smart](https://github.com/tim-smart)! - fix Config.Wrap for optional properties\n\n## 3.2.0\n\n### Minor Changes\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`146cadd`](https://github.com/Effect-TS/effect/commit/146cadd9d004634a3ff85c480bf92cf975c853e2) Thanks [@tim-smart](https://github.com/tim-smart)! - Add Stream.toReadableStreamEffect / .toReadableStreamRuntime\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e) Thanks [@tim-smart](https://github.com/tim-smart)! - add Cause.prettyErrors api\n\n  You can use this to extract `Error` instances from a `Cause`, that have clean stack traces and have had span information added to them.\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`963b4e7`](https://github.com/Effect-TS/effect/commit/963b4e7ac87e2468feb6a344f7ab4ee4ad711198) Thanks [@tim-smart](https://github.com/tim-smart)! - add Chunk.difference & Chunk.differenceWith\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`64c9414`](https://github.com/Effect-TS/effect/commit/64c9414e960e82058ca09bbb3976d6fbef303a8e) Thanks [@tim-smart](https://github.com/tim-smart)! - Improve causal rendering in vitest by rethrowing pretty errors\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e) Thanks [@tim-smart](https://github.com/tim-smart)! - add Effect.functionWithSpan\n\n  Allows you to define an effectful function that is wrapped with a span.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  const getTodo = Effect.functionWithSpan({\n    body: (id: number) => Effect.succeed(`Got todo ${id}!`),\n    options: (id) => ({\n      name: `getTodo-${id}`,\n      attributes: { id }\n    })\n  })\n  ```\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`2cbb76b`](https://github.com/Effect-TS/effect/commit/2cbb76bb52500a3f4bf27d1c91482518cbea56d7) Thanks [@tim-smart](https://github.com/tim-smart)! - Add do notation for Array\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`870c5fa`](https://github.com/Effect-TS/effect/commit/870c5fa52cd61e745e8e828d38c3f09f00737553) Thanks [@tim-smart](https://github.com/tim-smart)! - support $is & $match for Data.TaggedEnum with generics\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e) Thanks [@tim-smart](https://github.com/tim-smart)! - capture stack trace for tracing spans\n\n### Patch Changes\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e) Thanks [@tim-smart](https://github.com/tim-smart)! - add span stack trace to rendered causes\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`64c9414`](https://github.com/Effect-TS/effect/commit/64c9414e960e82058ca09bbb3976d6fbef303a8e) Thanks [@tim-smart](https://github.com/tim-smart)! - Consider Generator.next a cutpoint\n\n## 3.1.6\n\n### Patch Changes\n\n- [#2761](https://github.com/Effect-TS/effect/pull/2761) [`17fc22e`](https://github.com/Effect-TS/effect/commit/17fc22e132593c5caa563705a4748ba0f04a853c) Thanks [@KhraksMamtsov](https://github.com/KhraksMamtsov)! - Add `{ once: true }` to all `\"abort\"` event listeners for `AbortController` to automatically remove handlers after execution\n\n- [#2762](https://github.com/Effect-TS/effect/pull/2762) [`810f222`](https://github.com/Effect-TS/effect/commit/810f222268792b13067c7a7bf317b93a9bb8917b) Thanks [@tim-smart](https://github.com/tim-smart)! - fix Config.Wrap incorrectly wrapping functions & arrays\n\n- [#2773](https://github.com/Effect-TS/effect/pull/2773) [`596aaea`](https://github.com/Effect-TS/effect/commit/596aaea022648b2e06fb1ec22f1652043d6fe64e) Thanks [@tim-smart](https://github.com/tim-smart)! - fix for Infinity delays in Schedule\n\n## 3.1.5\n\n### Patch Changes\n\n- [#2750](https://github.com/Effect-TS/effect/pull/2750) [`6ac4847`](https://github.com/Effect-TS/effect/commit/6ac48479447c01a4f35d655552af93e47e562610) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure exponential schedules don't reach Infinity\n\n## 3.1.4\n\n### Patch Changes\n\n- [#2732](https://github.com/Effect-TS/effect/pull/2732) [`e41e911`](https://github.com/Effect-TS/effect/commit/e41e91122fa6dd12fc81e50dcad0db891be67146) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Call Equal.equals internally in order inputs were passed.\n\n## 3.1.3\n\n### Patch Changes\n\n- [#2706](https://github.com/Effect-TS/effect/pull/2706) [`1f6dc96`](https://github.com/Effect-TS/effect/commit/1f6dc96f51c7bb9c8d11415358308604ba7c7c8e) Thanks [@sukovanej](https://github.com/sukovanej)! - rebuild packages\n\n## 3.1.2\n\n### Patch Changes\n\n- [#2679](https://github.com/Effect-TS/effect/pull/2679) [`2e1cdf6`](https://github.com/Effect-TS/effect/commit/2e1cdf67d141281288fffe9a5c10d1379a800513) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure all type ids are annotated with `unique symbol`\n\n## 3.1.1\n\n### Patch Changes\n\n- [#2670](https://github.com/Effect-TS/effect/pull/2670) [`e5e56d1`](https://github.com/Effect-TS/effect/commit/e5e56d138dbed3204636f605229c6685f89659fc) Thanks [@tim-smart](https://github.com/tim-smart)! - Allow structural regions in equality for testing\n\n## 3.1.0\n\n### Minor Changes\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`c3c12c6`](https://github.com/Effect-TS/effect/commit/c3c12c6625633fe80e79f9db75a3b8cf8ca8b11d) Thanks [@github-actions](https://github.com/apps/github-actions)! - add SortedMap.lastOption & partition apis\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`ba64ea6`](https://github.com/Effect-TS/effect/commit/ba64ea6757810c5e74cad3863a7d19d4d38af66b) Thanks [@github-actions](https://github.com/apps/github-actions)! - add `Types.DeepMutable`, an alternative to `Types.Mutable` that makes all properties recursively mutable\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`b5de2d2`](https://github.com/Effect-TS/effect/commit/b5de2d2ce5b1afe8be90827bf898a95cec40eb2b) Thanks [@github-actions](https://github.com/apps/github-actions)! - add Effect.annotateLogsScoped\n\n  This api allows you to annotate logs until the Scope has been closed.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    yield* Effect.log(\"no annotations\")\n    yield* Effect.annotateLogsScoped({ foo: \"bar\" })\n    yield* Effect.log(\"annotated with foo=bar\")\n  }).pipe(Effect.scoped, Effect.andThen(Effect.log(\"no annotations again\")))\n  ```\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`a1c7ab8`](https://github.com/Effect-TS/effect/commit/a1c7ab8ffedacd18c1fc784f4ff5844f79498b83) Thanks [@github-actions](https://github.com/apps/github-actions)! - added Stream.fromEventListener, and BrowserStream.{fromEventListenerWindow, fromEventListenerDocument} for constructing a stream from addEventListener\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`a023f28`](https://github.com/Effect-TS/effect/commit/a023f28336f3865687d9a30c1883e36909906d85) Thanks [@github-actions](https://github.com/apps/github-actions)! - add `kind` property to `Tracer.Span`\n\n  This can be used to specify what kind of service created the span.\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`1c9454d`](https://github.com/Effect-TS/effect/commit/1c9454d532eae79b9f759aea77f59332cc6d18ed) Thanks [@github-actions](https://github.com/apps/github-actions)! - add Effect.timeoutOption\n\n  Returns an effect that will return `None` if the effect times out, otherwise it\n  will return `Some` of the produced value.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  // will return `None` after 500 millis\n  Effect.succeed(\"hello\").pipe(\n    Effect.delay(1000),\n    Effect.timeoutOption(\"500 millis\")\n  )\n  ```\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`92d56db`](https://github.com/Effect-TS/effect/commit/92d56dbb3f33e36636c2a2f1030c56492e39cf4d) Thanks [@github-actions](https://github.com/apps/github-actions)! - add $is & $match helpers to Data.TaggedEnum constructors\n\n  ```ts\n  import { Data } from \"effect\"\n\n  type HttpError = Data.TaggedEnum<{\n    NotFound: {}\n    InternalServerError: { reason: string }\n  }>\n  const { $is, $match, InternalServerError, NotFound } =\n    Data.taggedEnum<HttpError>()\n\n  // create a matcher\n  const matcher = $match({\n    NotFound: () => 0,\n    InternalServerError: () => 1\n  })\n\n  // true\n  $is(\"NotFound\")(NotFound())\n\n  // false\n  $is(\"NotFound\")(InternalServerError({ reason: \"fail\" }))\n  ```\n\n## 3.0.8\n\n### Patch Changes\n\n- [#2656](https://github.com/Effect-TS/effect/pull/2656) [`557707b`](https://github.com/Effect-TS/effect/commit/557707bc9e5f230c8964d2757012075c34339b5c) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n- [#2654](https://github.com/Effect-TS/effect/pull/2654) [`f4ed306`](https://github.com/Effect-TS/effect/commit/f4ed3068a70b50302d078a30d18ca3cfd2bc679c) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Actually fix Cause equality\n\n- [#2640](https://github.com/Effect-TS/effect/pull/2640) [`661004f`](https://github.com/Effect-TS/effect/commit/661004f4bf5f8b25f5a0678c21a3a822188ce461) Thanks [@patroza](https://github.com/patroza)! - fix: forEach NonEmpty overload causing inference issues for Iterables\n\n- [#2653](https://github.com/Effect-TS/effect/pull/2653) [`e79cb83`](https://github.com/Effect-TS/effect/commit/e79cb83d3b19098bc40a3012e2a059b8426306c2) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Consider type of failure in Cause equality\n\n## 3.0.7\n\n### Patch Changes\n\n- [#2637](https://github.com/Effect-TS/effect/pull/2637) [`18de56b`](https://github.com/Effect-TS/effect/commit/18de56b4a6b6d1f99230dfabf9147d59ea4dd759) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Avoid treating completed requests as interrupted when race conditions occur\n\n## 3.0.6\n\n### Patch Changes\n\n- [#2625](https://github.com/Effect-TS/effect/pull/2625) [`ffe4f4e`](https://github.com/Effect-TS/effect/commit/ffe4f4e95db35fff6869e360b072e3837befa0a1) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Avoid circularity on generators\n\n- [#2626](https://github.com/Effect-TS/effect/pull/2626) [`027418e`](https://github.com/Effect-TS/effect/commit/027418edaa6aa6c0ae4861b95832827b45adace4) Thanks [@fubhy](https://github.com/fubhy)! - Reintroduce custom `NoInfer` type\n\n- [#2609](https://github.com/Effect-TS/effect/pull/2609) [`ac1898e`](https://github.com/Effect-TS/effect/commit/ac1898eb7bc96880f911c276048e2ea3d6fe9c50) Thanks [@patroza](https://github.com/patroza)! - change: BatchedRequestResolver works with NonEmptyArray\n\n- [#2625](https://github.com/Effect-TS/effect/pull/2625) [`ffe4f4e`](https://github.com/Effect-TS/effect/commit/ffe4f4e95db35fff6869e360b072e3837befa0a1) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Make sure GenKind utilities are backward compatible\n\n## 3.0.5\n\n### Patch Changes\n\n- [#2611](https://github.com/Effect-TS/effect/pull/2611) [`6222404`](https://github.com/Effect-TS/effect/commit/62224044678751829ed2f128e05133a91c6b0569) Thanks [@tim-smart](https://github.com/tim-smart)! - simplify EffectGenerator type to improve inference\n\n- [#2608](https://github.com/Effect-TS/effect/pull/2608) [`868ed2a`](https://github.com/Effect-TS/effect/commit/868ed2a8fe94ee7f4206a6070f29dcf2a5ba1dc3) Thanks [@patroza](https://github.com/patroza)! - feat: foreach preserve non emptyness.\n\n## 3.0.4\n\n### Patch Changes\n\n- [#2602](https://github.com/Effect-TS/effect/pull/2602) [`9a24667`](https://github.com/Effect-TS/effect/commit/9a246672008a2b668d43fbfd2fe5508c54b2b920) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - allow use of generators (Effect.gen) without the adapter\n\n  Effect's data types now implement a Iterable that can be `yield*`'ed directly.\n\n  ```ts\n  Effect.gen(function* () {\n    const a = yield* Effect.success(1)\n    const b = yield* Effect.success(2)\n    return a + b\n  })\n  ```\n\n## 3.0.3\n\n### Patch Changes\n\n- [#2568](https://github.com/Effect-TS/effect/pull/2568) [`a7b4b84`](https://github.com/Effect-TS/effect/commit/a7b4b84bd5a25f51aba922f9259c3a58c98c6a4e) Thanks [@tim-smart](https://github.com/tim-smart)! - add Match.withReturnType api\n\n  Which can be used to constrain the return type of a match expression.\n\n  ```ts\n  import { Match } from \"effect\"\n\n  Match.type<string>().pipe(\n    Match.withReturnType<string>(),\n    Match.when(\"foo\", () => \"foo\"), // valid\n    Match.when(\"bar\", () => 123), // type error\n    Match.else(() => \"baz\")\n  )\n  ```\n\n## 3.0.2\n\n### Patch Changes\n\n- [#2562](https://github.com/Effect-TS/effect/pull/2562) [`2cecdbd`](https://github.com/Effect-TS/effect/commit/2cecdbd1cf30befce4e84796ccd953ea55ecfb86) Thanks [@fubhy](https://github.com/fubhy)! - Added provenance publishing\n\n## 3.0.1\n\n### Patch Changes\n\n- [#2539](https://github.com/Effect-TS/effect/pull/2539) [`3da0cfa`](https://github.com/Effect-TS/effect/commit/3da0cfa12c407fd930dc480be1ecc9217a8058f8) Thanks [@tim-smart](https://github.com/tim-smart)! - skip running effects in FiberHandle/Map if not required\n\n- [#2552](https://github.com/Effect-TS/effect/pull/2552) [`570e8d8`](https://github.com/Effect-TS/effect/commit/570e8d87e7c0e9ad4cd2686462fdb9b4812f7716) Thanks [@TylorS](https://github.com/TylorS)! - Improve typings of Array.isArray\n\n- [#2555](https://github.com/Effect-TS/effect/pull/2555) [`8edacca`](https://github.com/Effect-TS/effect/commit/8edacca37f8e37c01a63fec332b06d9361efaa7b) Thanks [@tim-smart](https://github.com/tim-smart)! - prevent use of `Array` as import name to solve bundler issues\n\n## 3.0.0\n\n### Major Changes\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`2fb7d9c`](https://github.com/Effect-TS/effect/commit/2fb7d9ca15037ff62a578bb9fe5732da5f4f317d) Thanks [@github-actions](https://github.com/apps/github-actions)! - Release Effect 3.0 🎉\n\n### Minor Changes\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3) Thanks [@github-actions](https://github.com/apps/github-actions)! - close FiberHandle/FiberSet/FiberMap when it is released\n\n  When they are closed, fibers can no longer be added to them.\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`d50a652`](https://github.com/Effect-TS/effect/commit/d50a652479f4d1d64f48da05c79fa847e6e51548) Thanks [@github-actions](https://github.com/apps/github-actions)! - add preregisteredWords option to frequency metric key type\n\n  You can use this to register a list of words to pre-populate the value of the\n  metric.\n\n  ```ts\n  import { Metric } from \"effect\"\n\n  const counts = Metric.frequency(\"counts\", {\n    preregisteredWords: [\"a\", \"b\", \"c\"]\n  }).register()\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`9a3bd47`](https://github.com/Effect-TS/effect/commit/9a3bd47ebd0750c7e498162734f6d21895de0cb2) Thanks [@github-actions](https://github.com/apps/github-actions)! - Bump TypeScript min requirement to version 5.4\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`be9d025`](https://github.com/Effect-TS/effect/commit/be9d025e42355260ace02dd135851a8935a4deba) Thanks [@github-actions](https://github.com/apps/github-actions)! - add unique identifier to Tracer.ParentSpan tag\n\n- [#2529](https://github.com/Effect-TS/effect/pull/2529) [`78b767c`](https://github.com/Effect-TS/effect/commit/78b767c2b1625186e17131761a0edbac25d21850) Thanks [@fubhy](https://github.com/fubhy)! - Renamed `ReadonlyArray` and `ReadonlyRecord` modules for better discoverability.\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`5c2b561`](https://github.com/Effect-TS/effect/commit/5c2b5614f583b88784ed68126ae939832fb3c092) Thanks [@github-actions](https://github.com/apps/github-actions)! - The signatures of the `HaltStrategy.match` `StreamHaltStrategy.match` functions have been changed to the generally accepted ones\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`a18f594`](https://github.com/Effect-TS/effect/commit/a18f5948f1439a147232448b2c443472fda0eceb) Thanks [@github-actions](https://github.com/apps/github-actions)! - support variadic arguments in Effect.log\n\n  This makes Effect.log more similar to console.log:\n\n  ```ts\n  Effect.log(\"hello\", { foo: \"bar\" }, Cause.fail(\"error\"))\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`2f96d93`](https://github.com/Effect-TS/effect/commit/2f96d938b90f8c19377583279e3c7afd9b509c50) Thanks [@github-actions](https://github.com/apps/github-actions)! - Fix ConfigError `_tag`, with the previous implementation catching the `ConfigError` with `Effect.catchTag` would show `And`, `Or`, etc.\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`5a2314b`](https://github.com/Effect-TS/effect/commit/5a2314b70ec79c2c02b51cef45a5ddec8327daa1) Thanks [@github-actions](https://github.com/apps/github-actions)! - replace use of `unit` terminology with `void`\n\n  For all the data types.\n\n  ```ts\n  Effect.unit // => Effect.void\n  Stream.unit // => Stream.void\n\n  // etc\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`271b79f`](https://github.com/Effect-TS/effect/commit/271b79fc0b66a6c11e07a8779ff8800493a7eac2) Thanks [@github-actions](https://github.com/apps/github-actions)! - Either: fix `getEquivalence` parameter order from `Either.getEquivalence(left, right)` to `Either.getEquivalence({ left, right })`\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`53d1c2a`](https://github.com/Effect-TS/effect/commit/53d1c2a77559081fbb89667e343346375c6d6650) Thanks [@github-actions](https://github.com/apps/github-actions)! - use LazyArg for Effect.if branches\n\n  Instead of:\n\n  ```ts\n  Effect.if(true, {\n    onTrue: Effect.succeed(\"true\"),\n    onFalse: Effect.succeed(\"false\")\n  })\n  ```\n\n  You should now write:\n\n  ```ts\n  Effect.if(true, {\n    onTrue: () => Effect.succeed(\"true\"),\n    onFalse: () => Effect.succeed(\"false\")\n  })\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`e7e1bbe`](https://github.com/Effect-TS/effect/commit/e7e1bbe68486fdf31c8f84b0880522d39adcaad3) Thanks [@github-actions](https://github.com/apps/github-actions)! - Replaced custom `NoInfer` type with the native `NoInfer` type from TypeScript 5.4\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`10c169e`](https://github.com/Effect-TS/effect/commit/10c169eadc874e91b4defca3f467b4e6a50fd8f3) Thanks [@github-actions](https://github.com/apps/github-actions)! - `Cache<Key, Error, Value>` has been changed to `Cache<Key, Value, Error = never>`.\n  `ScopedCache<Key, Error, Value>` has been changed to `ScopedCache<Key, Value, Error = never>`.\n  `Lookup<Key, Environment, Error, Value>` has been changed to `Lookup<Key, Value, Error = never, Environment = never>`\n\n### Patch Changes\n\n- [#2104](https://github.com/Effect-TS/effect/pull/2104) [`1499974`](https://github.com/Effect-TS/effect/commit/14999741d2e19c1747f6a7e19d68977f6429cdb8) Thanks [@IMax153](https://github.com/IMax153)! - don't run resolver if there are no incomplete requests\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3) Thanks [@github-actions](https://github.com/apps/github-actions)! - add FiberMap.has/unsafeHas api\n\n- [#2104](https://github.com/Effect-TS/effect/pull/2104) [`1499974`](https://github.com/Effect-TS/effect/commit/14999741d2e19c1747f6a7e19d68977f6429cdb8) Thanks [@IMax153](https://github.com/IMax153)! - add String casing transformation apis\n  - `snakeToCamel`\n  - `snakeToPascal`\n  - `snakeToKebab`\n  - `camelToSnake`\n  - `pascalToSnake`\n  - `kebabToSnake`\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3) Thanks [@github-actions](https://github.com/apps/github-actions)! - add FiberHandle module, for holding a reference to a running fiber\n\n  ```ts\n  import { Effect, FiberHandle } from \"effect\"\n\n  Effect.gen(function* (_) {\n    const handle = yield* _(FiberHandle.make())\n\n    // run some effects\n    yield* _(FiberHandle.run(handle, Effect.never))\n    // this will interrupt the previous fiber\n    yield* _(FiberHandle.run(handle, Effect.never))\n    // this will not run, as a fiber is already running\n    yield* _(FiberHandle.run(handle, Effect.never, { onlyIfMissing: true }))\n\n    yield* _(Effect.sleep(1000))\n  }).pipe(\n    Effect.scoped // The fiber will be interrupted when the scope is closed\n  )\n  ```\n\n- [#2521](https://github.com/Effect-TS/effect/pull/2521) [`6424181`](https://github.com/Effect-TS/effect/commit/64241815fe6a939e91e6947253e7dceea1306aa8) Thanks [@patroza](https://github.com/patroza)! - change return type of Fiber.joinAll to return an array\n\n## 2.4.19\n\n### Patch Changes\n\n- [#2503](https://github.com/Effect-TS/effect/pull/2503) [`41c8102`](https://github.com/Effect-TS/effect/commit/41c810228b1a50e4b41f19e735d7c62fe8d36871) Thanks [@gcanti](https://github.com/gcanti)! - Centralize error messages for bugs\n\n- [#2493](https://github.com/Effect-TS/effect/pull/2493) [`776ef2b`](https://github.com/Effect-TS/effect/commit/776ef2bb66db9aa9f68b7beab14f6986f9c1288b) Thanks [@gcanti](https://github.com/gcanti)! - add a `RegExp` module to `packages/effect`, closes #2488\n\n- [#2499](https://github.com/Effect-TS/effect/pull/2499) [`217147e`](https://github.com/Effect-TS/effect/commit/217147ea67c5c42c96f024775c41e5b070f81e4c) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure FIFO ordering when a Deferred is resolved\n\n- [#2502](https://github.com/Effect-TS/effect/pull/2502) [`90776ec`](https://github.com/Effect-TS/effect/commit/90776ec8e8671d835b65fc33ead1de6c864b81b9) Thanks [@tim-smart](https://github.com/tim-smart)! - make tracing spans cheaper to construct\n\n- [#2472](https://github.com/Effect-TS/effect/pull/2472) [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55) Thanks [@tim-smart](https://github.com/tim-smart)! - add Subscribable trait / module\n\n  Subscribable represents a resource that has a current value and can be subscribed to for updates.\n\n  The following data types are subscribable:\n  - A `SubscriptionRef`\n  - An `Actor` from the experimental `Machine` module\n\n- [#2500](https://github.com/Effect-TS/effect/pull/2500) [`232c353`](https://github.com/Effect-TS/effect/commit/232c353c2e6f743f38e57639ee30e324ffa9c2a9) Thanks [@tim-smart](https://github.com/tim-smart)! - simplify scope internals\n\n- [#2507](https://github.com/Effect-TS/effect/pull/2507) [`0ca835c`](https://github.com/Effect-TS/effect/commit/0ca835cbac8e69072a93ace83b534219faba24e8) Thanks [@gcanti](https://github.com/gcanti)! - ensure correct value is passed to mapping function in `mapAccum` loop, closes #2506\n\n- [#2472](https://github.com/Effect-TS/effect/pull/2472) [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55) Thanks [@tim-smart](https://github.com/tim-smart)! - add Readable module / trait\n\n  `Readable` is a common interface for objects that can be read from using a `get`\n  Effect.\n\n  For example, `Ref`'s implement `Readable`:\n\n  ```ts\n  import { Effect, Readable, Ref } from \"effect\"\n  import assert from \"assert\"\n\n  Effect.gen(function* (_) {\n    const ref = yield* _(Ref.make(123))\n    assert(Readable.isReadable(ref))\n\n    const result = yield* _(ref.get)\n    assert(result === 123)\n  })\n  ```\n\n- [#2498](https://github.com/Effect-TS/effect/pull/2498) [`e983740`](https://github.com/Effect-TS/effect/commit/e9837401145605aff5bc2ec7e73004f397c5d2d1) Thanks [@jessekelly881](https://github.com/jessekelly881)! - added {Readable, Subscribable}.unwrap\n\n- [#2494](https://github.com/Effect-TS/effect/pull/2494) [`e3e0924`](https://github.com/Effect-TS/effect/commit/e3e09247d46a35430fc60e4aa4032cc50814f212) Thanks [@thewilkybarkid](https://github.com/thewilkybarkid)! - Add `Duration.divide` and `Duration.unsafeDivide`.\n\n  ```ts\n  import { Duration, Option } from \"effect\"\n  import assert from \"assert\"\n\n  assert.deepStrictEqual(\n    Duration.divide(\"10 seconds\", 2),\n    Option.some(Duration.decode(\"5 seconds\"))\n  )\n  assert.deepStrictEqual(Duration.divide(\"10 seconds\", 0), Option.none())\n  assert.deepStrictEqual(Duration.divide(\"1 nano\", 1.5), Option.none())\n\n  assert.deepStrictEqual(\n    Duration.unsafeDivide(\"10 seconds\", 2),\n    Duration.decode(\"5 seconds\")\n  )\n  assert.deepStrictEqual(\n    Duration.unsafeDivide(\"10 seconds\", 0),\n    Duration.infinity\n  )\n  assert.throws(() => Duration.unsafeDivide(\"1 nano\", 1.5))\n  ```\n\n## 2.4.18\n\n### Patch Changes\n\n- [#2473](https://github.com/Effect-TS/effect/pull/2473) [`dadc690`](https://github.com/Effect-TS/effect/commit/dadc6906121c512bc32be22b52adbd1ada834594) Thanks [@tim-smart](https://github.com/tim-smart)! - add Logger.withConsoleLog/withConsoleError apis\n\n  These apis send a Logger's output to console.log/console.error respectively.\n\n  ```ts\n  import { Logger } from \"effect\"\n\n  // send output to stderr\n  const stderrLogger = Logger.withConsoleError(Logger.stringLogger)\n  ```\n\n## 2.4.17\n\n### Patch Changes\n\n- [#2461](https://github.com/Effect-TS/effect/pull/2461) [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613) Thanks [@tim-smart](https://github.com/tim-smart)! - add Inspectable.toStringUnknown/stringifyCircular\n\n- [#2462](https://github.com/Effect-TS/effect/pull/2462) [`607b2e7`](https://github.com/Effect-TS/effect/commit/607b2e7a7fd9318c57acf4e50ec61747eea74ad7) Thanks [@tim-smart](https://github.com/tim-smart)! - remove handled errors from Effect.retryOrElse\n\n- [#2461](https://github.com/Effect-TS/effect/pull/2461) [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613) Thanks [@tim-smart](https://github.com/tim-smart)! - improve formatting of Runtime failures\n\n- [#2415](https://github.com/Effect-TS/effect/pull/2415) [`8206caf`](https://github.com/Effect-TS/effect/commit/8206caf7c2d22c68be4313318b61cfdacf6222b6) Thanks [@tim-smart](https://github.com/tim-smart)! - add Iterable module\n\n  This module shares many apis compared to \"effect/ReadonlyArray\", but is fully lazy.\n\n  ```ts\n  import { Iterable, pipe } from \"effect\"\n\n  // Only 5 items will be generated & transformed\n  pipe(\n    Iterable.range(1, 100),\n    Iterable.map((i) => `item ${i}`),\n    Iterable.take(5)\n  )\n  ```\n\n- [#2438](https://github.com/Effect-TS/effect/pull/2438) [`7ddd654`](https://github.com/Effect-TS/effect/commit/7ddd65415b65ccb654ad04f4dbefe39402f15117) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Support Heterogeneous Effects in Effect Iterable apis\n\n  Including:\n  - `Effect.allSuccesses`\n  - `Effect.firstSuccessOf`\n  - `Effect.mergeAll`\n  - `Effect.reduceEffect`\n  - `Effect.raceAll`\n  - `Effect.forkAll`\n\n  For example:\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  class Foo extends Effect.Tag(\"Foo\")<Foo, 3>() {}\n  class Bar extends Effect.Tag(\"Bar\")<Bar, 4>() {}\n\n  // const program: Effect.Effect<(1 | 2 | 3 | 4)[], never, Foo | Bar>\n  export const program = Effect.allSuccesses([\n    Effect.succeed(1 as const),\n    Effect.succeed(2 as const),\n    Foo,\n    Bar\n  ])\n  ```\n\n  The above is now possible while before it was expecting all Effects to conform to the same type\n\n- [#2438](https://github.com/Effect-TS/effect/pull/2438) [`7ddd654`](https://github.com/Effect-TS/effect/commit/7ddd65415b65ccb654ad04f4dbefe39402f15117) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - add Effect.filterMap api\n\n  Which allows you to filter and map an Iterable of Effects in one step.\n\n  ```ts\n  import { Effect, Option } from \"effect\"\n\n  // resolves with `[\"even: 2\"]\n  Effect.filterMap(\n    [Effect.succeed(1), Effect.succeed(2), Effect.succeed(3)],\n    (i) => (i % 2 === 0 ? Option.some(`even: ${i}`) : Option.none())\n  )\n  ```\n\n- [#2461](https://github.com/Effect-TS/effect/pull/2461) [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613) Thanks [@tim-smart](https://github.com/tim-smart)! - use Inspectable.toStringUnknown for absurd runtime errors\n\n- [#2460](https://github.com/Effect-TS/effect/pull/2460) [`f456ba2`](https://github.com/Effect-TS/effect/commit/f456ba273bae21a6dcf8c966c50c97b5f0897d9f) Thanks [@tim-smart](https://github.com/tim-smart)! - use const type parameter for Config.withDefault\n\n  Which ensures that the fallback value type is not widened for literals.\n\n## 2.4.16\n\n### Patch Changes\n\n- [#2445](https://github.com/Effect-TS/effect/pull/2445) [`5170ce7`](https://github.com/Effect-TS/effect/commit/5170ce708c606283e8a30d273950f1a21c7eddc2) Thanks [@vecerek](https://github.com/vecerek)! - generate proper trace ids in default effect Tracer\n\n## 2.4.15\n\n### Patch Changes\n\n- [#2407](https://github.com/Effect-TS/effect/pull/2407) [`d7688c0`](https://github.com/Effect-TS/effect/commit/d7688c0c72717fe7876c871567f6946dabfc0546) Thanks [@thewilkybarkid](https://github.com/thewilkybarkid)! - Add Config.duration\n\n  This can be used to parse Duration's from environment variables:\n\n  ```ts\n  import { Config, Effect } from \"effect\"\n\n  Config.duration(\"CACHE_TTL\").pipe(\n    Effect.andThen((duration) => ...)\n  )\n  ```\n\n- [#2416](https://github.com/Effect-TS/effect/pull/2416) [`b3a4fac`](https://github.com/Effect-TS/effect/commit/b3a4face2acaca422f0b0530436e8f13129f3b3a) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Collect exits on forEach interrupt of residual requests\n\n## 2.4.14\n\n### Patch Changes\n\n- [#2404](https://github.com/Effect-TS/effect/pull/2404) [`6180c0c`](https://github.com/Effect-TS/effect/commit/6180c0cc51dee785cfce72220a52c9fc3b9bf9aa) Thanks [@patroza](https://github.com/patroza)! - fix interruption of parked Requests\n\n## 2.4.13\n\n### Patch Changes\n\n- [#2402](https://github.com/Effect-TS/effect/pull/2402) [`3336287`](https://github.com/Effect-TS/effect/commit/3336287ff55a25e56d759b83847bfaa21c40f499) Thanks [@tim-smart](https://github.com/tim-smart)! - add Duration.subtract api\n\n- [#2399](https://github.com/Effect-TS/effect/pull/2399) [`54b7c00`](https://github.com/Effect-TS/effect/commit/54b7c0077fa784ad2646b812d6a44641f672edcd) Thanks [@coleea](https://github.com/coleea)! - add BigInt.fromString and BigInt.fromNumber\n\n- [#2402](https://github.com/Effect-TS/effect/pull/2402) [`3336287`](https://github.com/Effect-TS/effect/commit/3336287ff55a25e56d759b83847bfaa21c40f499) Thanks [@tim-smart](https://github.com/tim-smart)! - remove use of bigint literals in Duration\n\n## 2.4.12\n\n### Patch Changes\n\n- [#2385](https://github.com/Effect-TS/effect/pull/2385) [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87) Thanks [@tim-smart](https://github.com/tim-smart)! - update typescript to 5.4\n\n## 2.4.11\n\n### Patch Changes\n\n- [#2384](https://github.com/Effect-TS/effect/pull/2384) [`2f488c4`](https://github.com/Effect-TS/effect/commit/2f488c436de52576562803c57ebc132ef40ccdd8) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n- [#2381](https://github.com/Effect-TS/effect/pull/2381) [`37ca592`](https://github.com/Effect-TS/effect/commit/37ca592a4101ad90adbf8c8b3f727faf3110cae5) Thanks [@tim-smart](https://github.com/tim-smart)! - add fiber ref for disabling the tracer\n\n  You can use it with the Effect.withTracerEnabled api:\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  Effect.succeed(42).pipe(\n    Effect.withSpan(\"my-span\"),\n    // the span will not be registered with the tracer\n    Effect.withTracerEnabled(false)\n  )\n  ```\n\n- [#2383](https://github.com/Effect-TS/effect/pull/2383) [`317b5b8`](https://github.com/Effect-TS/effect/commit/317b5b8e8c8c2207469b3ebfcf72bf3a9f7cbc60) Thanks [@tim-smart](https://github.com/tim-smart)! - add Duration.isFinite api, to determine if a duration is not Infinity\n\n## 2.4.10\n\n### Patch Changes\n\n- [#2375](https://github.com/Effect-TS/effect/pull/2375) [`9bab1f9`](https://github.com/Effect-TS/effect/commit/9bab1f9fa5b999740755e4e82485cb77c638643a) Thanks [@tim-smart](https://github.com/tim-smart)! - remove dangling variable in frequency metric hook\n\n- [#2373](https://github.com/Effect-TS/effect/pull/2373) [`9bbde5b`](https://github.com/Effect-TS/effect/commit/9bbde5be9a0168d1c2a0308bfc27167ed62f3968) Thanks [@patroza](https://github.com/patroza)! - Use incremental counters instead of up-down for runtime metrics\n\n## 2.4.9\n\n### Patch Changes\n\n- [#2357](https://github.com/Effect-TS/effect/pull/2357) [`71fd528`](https://github.com/Effect-TS/effect/commit/71fd5287500f9ce155a7d9f0df6ee3e0ac3aeb99) Thanks [@tim-smart](https://github.com/tim-smart)! - make more data types in /platform implement Inspectable\n\n## 2.4.8\n\n### Patch Changes\n\n- [#2354](https://github.com/Effect-TS/effect/pull/2354) [`bb0b69e`](https://github.com/Effect-TS/effect/commit/bb0b69e519698c7c76aa68217de423c78ad16566) Thanks [@tim-smart](https://github.com/tim-smart)! - add overload to Effect.filterOrFail that fails with NoSuchElementException\n\n  This allows you to perform a filterOrFail without providing a fallback failure\n  function.\n\n  Example:\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  // fails with NoSuchElementException\n  Effect.succeed(1).pipe(Effect.filterOrFail((n) => n === 0))\n  ```\n\n- [#2336](https://github.com/Effect-TS/effect/pull/2336) [`6b20bad`](https://github.com/Effect-TS/effect/commit/6b20badebb3a7ca4d38857753e8ecaa09d02ccfb) Thanks [@jessekelly881](https://github.com/jessekelly881)! - added Predicate.isTruthy\n\n- [#2351](https://github.com/Effect-TS/effect/pull/2351) [`4e64e9b`](https://github.com/Effect-TS/effect/commit/4e64e9b9876de6bfcbabe39e18a91a08e5f3fbb0) Thanks [@tim-smart](https://github.com/tim-smart)! - fix metrics not using labels from fiber ref\n\n- [#2266](https://github.com/Effect-TS/effect/pull/2266) [`3851a02`](https://github.com/Effect-TS/effect/commit/3851a022c481006aec1db36651e4b4fd727aa742) Thanks [@patroza](https://github.com/patroza)! - fix Effect.Tag generated proxy functions to work with andThen/tap, or others that do function/isEffect checks\n\n- [#2353](https://github.com/Effect-TS/effect/pull/2353) [`5f5fcd9`](https://github.com/Effect-TS/effect/commit/5f5fcd969ae30ed6fe61d566a571498d9e895e16) Thanks [@tim-smart](https://github.com/tim-smart)! - Types: add `Has` helper\n\n- [#2299](https://github.com/Effect-TS/effect/pull/2299) [`814e5b8`](https://github.com/Effect-TS/effect/commit/814e5b828f68210b9e8f336fd6ac688646835dd9) Thanks [@alex-dixon](https://github.com/alex-dixon)! - Prevent Effect.if from crashing when first argument is not an Effect\n\n## 2.4.7\n\n### Patch Changes\n\n- [#2328](https://github.com/Effect-TS/effect/pull/2328) [`eb93283`](https://github.com/Effect-TS/effect/commit/eb93283985913d7b04ca750e36ac8513e7b6cef6) Thanks [@tim-smart](https://github.com/tim-smart)! - set unhandled log level to none for fibers in FiberSet/Map\n\n## 2.4.6\n\n### Patch Changes\n\n- [#2290](https://github.com/Effect-TS/effect/pull/2290) [`4f35a7e`](https://github.com/Effect-TS/effect/commit/4f35a7e7c4eba598924aff24d1158b9056bb24be) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Remove function renaming from internals, introduce new cutpoint strategy\n\n- [#2311](https://github.com/Effect-TS/effect/pull/2311) [`9971186`](https://github.com/Effect-TS/effect/commit/99711862722188fbb5ed3ee75126ad5edf13f72f) Thanks [@tim-smart](https://github.com/tim-smart)! - add Channel.splitLines api\n\n  It splits strings on newlines. Handles both Windows newlines (`\\r\\n`) and UNIX\n  newlines (`\\n`).\n\n## 2.4.5\n\n### Patch Changes\n\n- [#2300](https://github.com/Effect-TS/effect/pull/2300) [`bce21c5`](https://github.com/Effect-TS/effect/commit/bce21c5ded2177114666ba229bd5029fa000dee3) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: fix `intersperse` signature\n\n- [#2303](https://github.com/Effect-TS/effect/pull/2303) [`c7d3036`](https://github.com/Effect-TS/effect/commit/c7d303630b7f0825cb2e584557c5767a67214d9f) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: fix `sort` signature, closes #2301\n\n## 2.4.4\n\n### Patch Changes\n\n- [#2172](https://github.com/Effect-TS/effect/pull/2172) [`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949) Thanks [@gcanti](https://github.com/gcanti)! - Brand: add `refined` overload\n\n  ```ts\n  export function refined<A extends Brand<any>>(\n    f: (unbranded: Brand.Unbranded<A>) => Option.Option<Brand.BrandErrors>\n  ): Brand.Constructor<A>\n  ```\n\n- [#2285](https://github.com/Effect-TS/effect/pull/2285) [`817a04c`](https://github.com/Effect-TS/effect/commit/817a04cb2df0f4140984dc97eb3e1bb14a6c4a38) Thanks [@tim-smart](https://github.com/tim-smart)! - add support for AbortSignal's to runPromise\n\n  If the signal is aborted, the effect execution will be interrupted.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  const controller = new AbortController()\n\n  Effect.runPromise(Effect.never, { signal: controller.signal })\n\n  // abort after 1 second\n  setTimeout(() => controller.abort(), 1000)\n  ```\n\n- [#2293](https://github.com/Effect-TS/effect/pull/2293) [`d90a99d`](https://github.com/Effect-TS/effect/commit/d90a99d03d074adc7cd2533f15419138264da5a2) Thanks [@tim-smart](https://github.com/tim-smart)! - add AbortSignal support to ManagedRuntime\n\n- [#2288](https://github.com/Effect-TS/effect/pull/2288) [`dd05faa`](https://github.com/Effect-TS/effect/commit/dd05faa621555ef3585ecd914ac13ecd89b710f4) Thanks [@tim-smart](https://github.com/tim-smart)! - optimize addition of blocked requests to parallel collection\n\n- [#2288](https://github.com/Effect-TS/effect/pull/2288) [`dd05faa`](https://github.com/Effect-TS/effect/commit/dd05faa621555ef3585ecd914ac13ecd89b710f4) Thanks [@tim-smart](https://github.com/tim-smart)! - use Chunk for request block collections\n\n- [#2280](https://github.com/Effect-TS/effect/pull/2280) [`802674b`](https://github.com/Effect-TS/effect/commit/802674b379b7559ad3ff09b33388891445a9e48b) Thanks [@jessekelly881](https://github.com/jessekelly881)! - added support for PromiseLike\n\n## 2.4.3\n\n### Patch Changes\n\n- [#2211](https://github.com/Effect-TS/effect/pull/2211) [`20e63fb`](https://github.com/Effect-TS/effect/commit/20e63fb9207210f3fe2d136ec40d0a2dbff3225e) Thanks [@tim-smart](https://github.com/tim-smart)! - add ManagedRuntime module, to make incremental adoption easier\n\n  You can use a ManagedRuntime to run Effect's that can use the\n  dependencies from the given Layer. For example:\n\n  ```ts\n  import { Console, Effect, Layer, ManagedRuntime } from \"effect\"\n\n  class Notifications extends Effect.Tag(\"Notifications\")<\n    Notifications,\n    { readonly notify: (message: string) => Effect.Effect<void> }\n  >() {\n    static Live = Layer.succeed(this, {\n      notify: (message) => Console.log(message)\n    })\n  }\n\n  async function main() {\n    const runtime = ManagedRuntime.make(Notifications.Live)\n    await runtime.runPromise(Notifications.notify(\"Hello, world!\"))\n    await runtime.dispose()\n  }\n\n  main()\n  ```\n\n- [#2211](https://github.com/Effect-TS/effect/pull/2211) [`20e63fb`](https://github.com/Effect-TS/effect/commit/20e63fb9207210f3fe2d136ec40d0a2dbff3225e) Thanks [@tim-smart](https://github.com/tim-smart)! - add Layer.toRuntimeWithMemoMap api\n\n  Similar to Layer.toRuntime, but allows you to share a Layer.MemoMap between\n  layer builds.\n\n  By sharing the MemoMap, layers are shared between each build - ensuring layers\n  are only built once between multiple calls to Layer.toRuntimeWithMemoMap.\n\n## 2.4.2\n\n### Patch Changes\n\n- [#2264](https://github.com/Effect-TS/effect/pull/2264) [`e03811e`](https://github.com/Effect-TS/effect/commit/e03811e80c93e986e6348b3b67ac2ed6d5fefff0) Thanks [@patroza](https://github.com/patroza)! - fix: unmatched function fallthrough in `andThen` and `tap`\n\n- [#2225](https://github.com/Effect-TS/effect/pull/2225) [`ac41d84`](https://github.com/Effect-TS/effect/commit/ac41d84776484cdce8165b7ca2c9c9b6377eee2d) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Add Effect.Tag to simplify access to service.\n\n  This change allows to define tags in the following way:\n\n  ```ts\n  class DemoTag extends Effect.Tag(\"DemoTag\")<\n    DemoTag,\n    {\n      readonly getNumbers: () => Array<number>\n      readonly strings: Array<string>\n    }\n  >() {}\n  ```\n\n  And use them like:\n\n  ```ts\n  DemoTag.getNumbers()\n  DemoTag.strings\n  ```\n\n  This fuses together `serviceFunctions` and `serviceConstants` in the static side of the tag.\n\n  Additionally it allows using the service like:\n\n  ```ts\n  DemoTag.use((_) => _.getNumbers())\n  ```\n\n  This is especially useful when having functions that contain generics in the service given that those can't be reliably transformed at the type level and because of that we can't put them on the tag.\n\n- [#2238](https://github.com/Effect-TS/effect/pull/2238) [`6137533`](https://github.com/Effect-TS/effect/commit/613753300c7705518ab1fea2f370b032851c2750) Thanks [@JJayet](https://github.com/JJayet)! - Request: swap Success and Error params\n\n- [#2270](https://github.com/Effect-TS/effect/pull/2270) [`f373529`](https://github.com/Effect-TS/effect/commit/f373529999f4b8bc92b634f6ea14f19271388eed) Thanks [@tim-smart](https://github.com/tim-smart)! - add structured logging apis\n  - Logger.json / Logger.jsonLogger\n  - Logger.structured / Logger.structuredLogger\n\n  `Logger.json` logs JSON serialized strings to the console.\n\n  `Logger.structured` logs structured objects, which is useful in the browser\n  where you can inspect objects logged to the console.\n\n- [#2257](https://github.com/Effect-TS/effect/pull/2257) [`1bf9f31`](https://github.com/Effect-TS/effect/commit/1bf9f31f07667de677673f7c29a4e7a26ebad3c8) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Make sure Effect.Tag works on primitives.\n\n  This change allows the following to work just fine:\n\n  ```ts\n  import { Effect, Layer } from \"effect\"\n\n  class DateTag extends Effect.Tag(\"DateTag\")<DateTag, Date>() {\n    static date = new Date(1970, 1, 1)\n    static Live = Layer.succeed(this, this.date)\n  }\n\n  class MapTag extends Effect.Tag(\"MapTag\")<MapTag, Map<string, string>>() {\n    static Live = Layer.effect(\n      this,\n      Effect.sync(() => new Map())\n    )\n  }\n\n  class NumberTag extends Effect.Tag(\"NumberTag\")<NumberTag, number>() {\n    static Live = Layer.succeed(this, 100)\n  }\n  ```\n\n- [#2244](https://github.com/Effect-TS/effect/pull/2244) [`e3ff789`](https://github.com/Effect-TS/effect/commit/e3ff789226f89e71eb28ca38ce79f90af6a03f1a) Thanks [@tim-smart](https://github.com/tim-smart)! - add FiberMap/FiberSet.join api\n\n  This api can be used to propogate failures back to a parent fiber, in case any of the fibers added to the FiberMap/FiberSet fail with an error.\n\n  Example:\n\n  ```ts\n  import { Effect, FiberSet } from \"effect\"\n\n  Effect.gen(function* (_) {\n    const set = yield* _(FiberSet.make())\n    yield* _(FiberSet.add(set, Effect.runFork(Effect.fail(\"error\"))))\n\n    // parent fiber will fail with \"error\"\n    yield* _(FiberSet.join(set))\n  })\n  ```\n\n- [#2238](https://github.com/Effect-TS/effect/pull/2238) [`6137533`](https://github.com/Effect-TS/effect/commit/613753300c7705518ab1fea2f370b032851c2750) Thanks [@JJayet](https://github.com/JJayet)! - make Effect.request dual\n\n- [#2263](https://github.com/Effect-TS/effect/pull/2263) [`507ba40`](https://github.com/Effect-TS/effect/commit/507ba4060ff043c1a8d541dae723fa6940633b00) Thanks [@thewilkybarkid](https://github.com/thewilkybarkid)! - Allow duration inputs to be singular\n\n- [#2255](https://github.com/Effect-TS/effect/pull/2255) [`e466afe`](https://github.com/Effect-TS/effect/commit/e466afe32f2de598ceafd8982bd0cfbd388e5671) Thanks [@jessekelly881](https://github.com/jessekelly881)! - added Either.Either.{Left,Right} and Option.Option.Value type utils\n\n- [#2270](https://github.com/Effect-TS/effect/pull/2270) [`f373529`](https://github.com/Effect-TS/effect/commit/f373529999f4b8bc92b634f6ea14f19271388eed) Thanks [@tim-smart](https://github.com/tim-smart)! - add Logger.batched, for batching logger output\n\n  It takes a duration window and an effectful function that processes the batched output.\n\n  Example:\n\n  ```ts\n  import { Console, Effect, Logger } from \"effect\"\n\n  const LoggerLive = Logger.replaceScoped(\n    Logger.defaultLogger,\n    Logger.logfmtLogger.pipe(\n      Logger.batched(\"500 millis\", (messages) =>\n        Console.log(\"BATCH\", messages.join(\"\\n\"))\n      )\n    )\n  )\n\n  Effect.gen(function* (_) {\n    yield* _(Effect.log(\"one\"))\n    yield* _(Effect.log(\"two\"))\n    yield* _(Effect.log(\"three\"))\n  }).pipe(Effect.provide(LoggerLive), Effect.runFork)\n  ```\n\n- [#2233](https://github.com/Effect-TS/effect/pull/2233) [`de74eb8`](https://github.com/Effect-TS/effect/commit/de74eb80a79eebde5ff645033765e7a617e92f27) Thanks [@gcanti](https://github.com/gcanti)! - Struct: make `pick` / `omit` dual\n\n## 2.4.1\n\n### Patch Changes\n\n- [#2219](https://github.com/Effect-TS/effect/pull/2219) [`a4a0006`](https://github.com/Effect-TS/effect/commit/a4a0006c7f19fc261df5cda16963d73457e4d6ac) Thanks [@KhraksMamtsov](https://github.com/KhraksMamtsov)! - fix documentation for `Predicate.isNull` `Predicate.isNotNull`\n\n- [#2223](https://github.com/Effect-TS/effect/pull/2223) [`0a37676`](https://github.com/Effect-TS/effect/commit/0a37676aa0eb2a21e17af2e6df9f81f52bbc8831) Thanks [@Schniz](https://github.com/Schniz)! - document Effect.zipLeft and Effect.zipRight\n\n- [#2224](https://github.com/Effect-TS/effect/pull/2224) [`6f503b7`](https://github.com/Effect-TS/effect/commit/6f503b774d893bf2af34f66202e270d8c45d5f31) Thanks [@jessekelly881](https://github.com/jessekelly881)! - added isSet and isMap to Predicate module\n\n## 2.4.0\n\n### Minor Changes\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2) Thanks [@github-actions](https://github.com/apps/github-actions)! - remove ReadonlyRecord.fromIterable (duplicate of fromEntries)\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`489fcf3`](https://github.com/Effect-TS/effect/commit/489fcf363ff2b2a953166b740cb9a62d7fc2a101) Thanks [@github-actions](https://github.com/apps/github-actions)! - - swap `Schedule` type parameters from `Schedule<out Env, in In, out Out>` to `Schedule<out Out, in In = unknown, out R = never>`, closes #2154\n  - swap `ScheduleDriver` type parameters from `ScheduleDriver<out Env, in In, out Out>` to `ScheduleDriver<out Out, in In = unknown, out R = never>`\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`7d9c3bf`](https://github.com/Effect-TS/effect/commit/7d9c3bff6c18d451e0e4781042945ec5c7be1b9f) Thanks [@github-actions](https://github.com/apps/github-actions)! - Consolidate `Effect.asyncOption`, `Effect.asyncEither`, `Stream.asyncOption`, `Stream.asyncEither`, and `Stream.asyncInterrupt`\n\n  This PR removes `Effect.asyncOption` and `Effect.asyncEither` as their behavior can be entirely implemented with the new signature of `Effect.async`, which optionally returns a cleanup `Effect` from the registration callback.\n\n  ```ts\n  declare const async: <A, E = never, R = never>(\n    register: (\n      callback: (_: Effect<A, E, R>) => void,\n      signal: AbortSignal\n    ) => void | Effect<void, never, R>,\n    blockingOn?: FiberId\n  ) => Effect<A, E, R>\n  ```\n\n  Additionally, this PR removes `Stream.asyncOption`, `Stream.asyncEither`, and `Stream.asyncInterrupt` as their behavior can be entirely implemented with the new signature of `Stream.async`, which can optionally return a cleanup `Effect` from the registration callback.\n\n  ```ts\n  declare const async: <A, E = never, R = never>(\n    register: (emit: Emit<R, E, A, void>) => Effect<void, never, R> | void,\n    outputBuffer?: number\n  ) => Stream<A, E, R>\n  ```\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`d8d278b`](https://github.com/Effect-TS/effect/commit/d8d278b2efb2966947029885e01f7b68348a021f) Thanks [@github-actions](https://github.com/apps/github-actions)! - swap `GroupBy` type parameters from `GroupBy<out R, out E, out K, out V>` to `GroupBy<out K, out V, out E = never, out R = never>`\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`14c5711`](https://github.com/Effect-TS/effect/commit/14c57110078f0862b8da5c7a2c5d980f54447484) Thanks [@github-actions](https://github.com/apps/github-actions)! - Remove Effect.unified and Effect.unifiedFn in favour of Unify.unify.\n\n  The `Unify` module fully replaces the need for specific unify functions, when before you did:\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  const effect = Effect.unified(\n    Math.random() > 0.5 ? Effect.succeed(\"OK\") : Effect.fail(\"NO\")\n  )\n  const effectFn = Effect.unifiedFn((n: number) =>\n    Math.random() > 0.5 ? Effect.succeed(\"OK\") : Effect.fail(\"NO\")\n  )\n  ```\n\n  You can now do:\n\n  ```ts\n  import { Effect, Unify } from \"effect\"\n\n  const effect = Unify.unify(\n    Math.random() > 0.5 ? Effect.succeed(\"OK\") : Effect.fail(\"NO\")\n  )\n  const effectFn = Unify.unify((n: number) =>\n    Math.random() > 0.5 ? Effect.succeed(\"OK\") : Effect.fail(\"NO\")\n  )\n  ```\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2) Thanks [@github-actions](https://github.com/apps/github-actions)! - add key type to ReadonlyRecord\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`585fcce`](https://github.com/Effect-TS/effect/commit/585fcce162d0f07a48d7cd984a9b722966fbebbe) Thanks [@github-actions](https://github.com/apps/github-actions)! - add support for optional property keys to `pick`, `omit` and `get`\n\n  Before:\n\n  ```ts\n  import { pipe } from \"effect/Function\"\n  import * as S from \"effect/Struct\"\n\n  const struct: {\n    a?: string\n    b: number\n    c: boolean\n  } = { b: 1, c: true }\n\n  // error\n  const x = pipe(struct, S.pick(\"a\", \"b\"))\n\n  const record: Record<string, number> = {}\n\n  const y = pipe(record, S.pick(\"a\", \"b\"))\n  console.log(y) // => { a: undefined, b: undefined }\n\n  // error\n  console.log(pipe(struct, S.get(\"a\")))\n  ```\n\n  Now\n\n  ```ts\n  import { pipe } from \"effect/Function\"\n  import * as S from \"effect/Struct\"\n\n  const struct: {\n    a?: string\n    b: number\n    c: boolean\n  } = { b: 1, c: true }\n\n  const x = pipe(struct, S.pick(\"a\", \"b\"))\n  console.log(x) // => { b: 1 }\n\n  const record: Record<string, number> = {}\n\n  const y = pipe(record, S.pick(\"a\", \"b\"))\n  console.log(y) // => {}\n\n  console.log(pipe(struct, S.get(\"a\"))) // => undefined\n  ```\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`a025b12`](https://github.com/Effect-TS/effect/commit/a025b121235ba01cfce8d62a775491880c575561) Thanks [@github-actions](https://github.com/apps/github-actions)! - Swap type params of Either from `Either<E, A>` to `Either<R, L = never>`.\n\n  Along the same line of the other changes this allows to shorten the most common types such as:\n\n  ```ts\n  import { Either } from \"effect\"\n\n  const right: Either.Either<string> = Either.right(\"ok\")\n  ```\n\n### Patch Changes\n\n- [#2193](https://github.com/Effect-TS/effect/pull/2193) [`b9cb3a9`](https://github.com/Effect-TS/effect/commit/b9cb3a9c9bfdd75536bd70b4e8b557c12d4923ff) Thanks [@jessekelly881](https://github.com/jessekelly881)! - added Number.parse, BigInt.toNumber, ParseResult.fromOption\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`93b412d`](https://github.com/Effect-TS/effect/commit/93b412d4a9ed762dc9fa5807e51fad0fc78a614a) Thanks [@github-actions](https://github.com/apps/github-actions)! - ReadonlyArray.groupBy: allow for grouping by symbols, closes #2180\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`55b26a6`](https://github.com/Effect-TS/effect/commit/55b26a6342b4826f1116e7a1eb660118c274458e) Thanks [@github-actions](https://github.com/apps/github-actions)! - Either: fix `fromOption` overloads order\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`2097739`](https://github.com/Effect-TS/effect/commit/20977393d2383bff709304e81ec7d51cafd57108) Thanks [@github-actions](https://github.com/apps/github-actions)! - Add Do notation methods `Do`, `bindTo`, `bind` and `let` to Either\n\n## 2.3.8\n\n### Patch Changes\n\n- [#2167](https://github.com/Effect-TS/effect/pull/2167) [`5ad2eec`](https://github.com/Effect-TS/effect/commit/5ad2eece0280b6db6a749d25cac1dcf6d33659a9) Thanks [@tim-smart](https://github.com/tim-smart)! - add Hash.cached\n\n  This api assists with adding a layer of caching, when hashing immutable data structures.\n\n  ```ts\n  import { Data, Hash } from \"effect\"\n\n  class User extends Data.Class<{\n    id: number\n    name: string\n  }> {\n    [Hash.symbol]() {\n      return Hash.cached(this, Hash.string(`${this.id}-${this.name}`))\n    }\n  }\n  ```\n\n- [#2187](https://github.com/Effect-TS/effect/pull/2187) [`e6d36c0`](https://github.com/Effect-TS/effect/commit/e6d36c0813d836f17eabb6a9c7849baffca12dbf) Thanks [@tim-smart](https://github.com/tim-smart)! - update development dependencies\n\n## 2.3.7\n\n### Patch Changes\n\n- [#2142](https://github.com/Effect-TS/effect/pull/2142) [`bc8404d`](https://github.com/Effect-TS/effect/commit/bc8404d54fd42072d200c0399cb39672837afa9f) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Expose version control via ModuleVersion.\n\n  This enables low level framework authors to run their own effect version which won't conflict with any other effect versions running on the same process.\n\n  Imagine cases where for example a function runtime is built on effect, we don't want lifecycle of the runtime to clash with lifecycle of user-land provided code.\n\n  To manually control the module version one can use:\n\n  ```ts\n  import * as ModuleVersion from \"effect/ModuleVersion\"\n\n  ModuleVersion.setCurrentVersion(\n    `my-effect-runtime-${ModuleVersion.getCurrentVersion()}`\n  )\n  ```\n\n  Note that this code performs side effects and should be executed before any module is imported ideally via an init script.\n\n  The resulting order of execution has to be:\n\n  ```ts\n  import * as ModuleVersion from \"effect/ModuleVersion\"\n\n  ModuleVersion.setCurrentVersion(\n    `my-effect-runtime-${ModuleVersion.getCurrentVersion()}`\n  )\n\n  import { Effect } from \"effect\"\n\n  // rest of code\n  ```\n\n- [#2159](https://github.com/Effect-TS/effect/pull/2159) [`2c5cbcd`](https://github.com/Effect-TS/effect/commit/2c5cbcd1161b4f40dab184999291e817314107de) Thanks [@IMax153](https://github.com/IMax153)! - Avoid incrementing cache hits for expired entries\n\n- [#2165](https://github.com/Effect-TS/effect/pull/2165) [`6565916`](https://github.com/Effect-TS/effect/commit/6565916ef254bf910e47d25fd0ef55e7cb420241) Thanks [@tim-smart](https://github.com/tim-smart)! - fix Hash implemention for Option.none\n\n## 2.3.6\n\n### Patch Changes\n\n- [#2145](https://github.com/Effect-TS/effect/pull/2145) [`b1163b2`](https://github.com/Effect-TS/effect/commit/b1163b2bd67b65bafbbb39fc4c67576e5cbaf444) Thanks [@tim-smart](https://github.com/tim-smart)! - add RequestResolver.aroundRequests api\n\n  This can be used to run side effects that introspect the requests being\n  executed.\n\n  Example:\n\n  ```ts\n  import { Effect, Request, RequestResolver } from \"effect\"\n\n  interface GetUserById extends Request.Request<unknown> {\n    readonly id: number\n  }\n\n  declare const resolver: RequestResolver.RequestResolver<GetUserById>\n\n  RequestResolver.aroundRequests(\n    resolver,\n    (requests) => Effect.log(`got ${requests.length} requests`),\n    (requests, _) => Effect.log(`finised running ${requests.length} requests`)\n  )\n  ```\n\n- [#2148](https://github.com/Effect-TS/effect/pull/2148) [`b46b869`](https://github.com/Effect-TS/effect/commit/b46b869e59a6da5aa235a9fcc25e1e0d24e9e8f8) Thanks [@riordanpawley](https://github.com/riordanpawley)! - Flipped scheduleForked types to match new <A, E, R> signature\n\n- [#2139](https://github.com/Effect-TS/effect/pull/2139) [`de1b226`](https://github.com/Effect-TS/effect/commit/de1b226282b5ab6c2809dd93f3bdb066f24a1333) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Introduce FiberId.Single, make FiberId.None behave like FiberId.Runtime, relax FiberRefs to use Single instead of Runtime.\n\n  This change is a precursor to enable easier APIs to modify the Runtime when patching FiberRefs.\n\n- [#2137](https://github.com/Effect-TS/effect/pull/2137) [`a663390`](https://github.com/Effect-TS/effect/commit/a66339090ae7b960f8a8b90a0dcdc505de5aaf3e) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Expose Random Tag and functions to use a specific random service implementation\n\n- [#2143](https://github.com/Effect-TS/effect/pull/2143) [`ff88f80`](https://github.com/Effect-TS/effect/commit/ff88f808c4ed9947a148045849e7410b00acad0a) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Fix Cause.pretty when toString is invalid\n\n  ```ts\n  import { Cause } from \"effect\"\n\n  console.log(Cause.pretty(Cause.fail([{ toString: \"\" }])))\n  ```\n\n  The code above used to throw now it prints:\n\n  ```bash\n  Error: [{\"toString\":\"\"}]\n  ```\n\n- [#2080](https://github.com/Effect-TS/effect/pull/2080) [`11be07b`](https://github.com/Effect-TS/effect/commit/11be07bf65d82cfdf994cdb9d8ca937f995cb4f0) Thanks [@KhraksMamtsov](https://github.com/KhraksMamtsov)! - Add functional analogue of `satisfies` operator.\n  This is a convenient operator to use in the `pipe` chain to localize type errors closer to their source.\n\n  ```ts\n  import { satisfies } from \"effect/Function\"\n\n  const test1 = satisfies<number>()(5 as const)\n  // ^? const test: 5\n\n  // @ts-expect-error\n  const test2 = satisfies<string>()(5)\n  // ^? Argument of type 'number' is not assignable to parameter of type 'string'\n  ```\n\n- [#2147](https://github.com/Effect-TS/effect/pull/2147) [`c568645`](https://github.com/Effect-TS/effect/commit/c5686451c87d26382135a1c63b00ef171bb24f62) Thanks [@tim-smart](https://github.com/tim-smart)! - generate a random span id for the built-in tracer\n\n  This ensures the same span id isn't used between application runs.\n\n- [#2144](https://github.com/Effect-TS/effect/pull/2144) [`88835e5`](https://github.com/Effect-TS/effect/commit/88835e575a0bfbeff9a3696a332f32192c940e12) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Fix withRandom and withClock types\n\n- [#2138](https://github.com/Effect-TS/effect/pull/2138) [`b415577`](https://github.com/Effect-TS/effect/commit/b415577f6c576073733929c858e5aac27b6d5880) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Fix internals of TestAnnotationsMap making it respect equality\n\n- [#2149](https://github.com/Effect-TS/effect/pull/2149) [`ff8046f`](https://github.com/Effect-TS/effect/commit/ff8046f57dfd073eba60ce6d3144ab060fbf93ce) Thanks [@tim-smart](https://github.com/tim-smart)! - add Runtime.updateFiberRefs/setFiberRef/deleteFiberRef\n\n  This change allows you to update fiber ref values inside a Runtime object.\n\n  Example:\n\n  ```ts\n  import { Effect, FiberRef, Runtime } from \"effect\"\n\n  const ref = FiberRef.unsafeMake(0)\n\n  const updatedRuntime = Runtime.defaultRuntime.pipe(\n    Runtime.setFiberRef(ref, 1)\n  )\n\n  // returns 1\n  const result = Runtime.runSync(updatedRuntime)(FiberRef.get(ref))\n  ```\n\n## 2.3.5\n\n### Patch Changes\n\n- [#2114](https://github.com/Effect-TS/effect/pull/2114) [`b881365`](https://github.com/Effect-TS/effect/commit/b8813650355322ea2fc1fbaa4f846bd87a7a05f3) Thanks [@IMax153](https://github.com/IMax153)! - Fix the ordering of results returned from batched requests\n\n## 2.3.4\n\n### Patch Changes\n\n- [#2107](https://github.com/Effect-TS/effect/pull/2107) [`17bda66`](https://github.com/Effect-TS/effect/commit/17bda66431c999a546920c10adb205e6c8bea7d1) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure large semaphore takes don't block smaller takes\n\n## 2.3.3\n\n### Patch Changes\n\n- [#2090](https://github.com/Effect-TS/effect/pull/2090) [`efd41d8`](https://github.com/Effect-TS/effect/commit/efd41d8131c3d90867608969ef7c4eef490eb5e6) Thanks [@hsubra89](https://github.com/hsubra89)! - Update `RateLimiter` to support passing in a custom `cost` per effect. This is really useful for API(s) that have a \"credit cost\" per endpoint.\n\n  Usage Example :\n\n  ```ts\n  import { Effect, RateLimiter } from \"effect\"\n  import { compose } from \"effect/Function\"\n\n  const program = Effect.scoped(\n    Effect.gen(function* ($) {\n      // Create a rate limiter that has an hourly limit of 1000 credits\n      const rateLimiter = yield* $(RateLimiter.make(1000, \"1 hours\"))\n      // Query API costs 1 credit per call ( 1 is the default cost )\n      const queryAPIRL = compose(rateLimiter, RateLimiter.withCost(1))\n      // Mutation API costs 5 credits per call\n      const mutationAPIRL = compose(rateLimiter, RateLimiter.withCost(5))\n      // ...\n      // Use the pre-defined rate limiters\n      yield* $(queryAPIRL(Effect.log(\"Sample Query\")))\n      yield* $(mutationAPIRL(Effect.log(\"Sample Mutation\")))\n\n      // Or set a cost on-the-fly\n      yield* $(\n        rateLimiter(Effect.log(\"Another query with a different cost\")).pipe(\n          RateLimiter.withCost(3)\n        )\n      )\n    })\n  )\n  ```\n\n- [#2097](https://github.com/Effect-TS/effect/pull/2097) [`0f83515`](https://github.com/Effect-TS/effect/commit/0f83515a9c01d13c7c15a3f026e02d22c3c6bb7f) Thanks [@IMax153](https://github.com/IMax153)! - Updates the `RateLimiter.make` constructor to take an object of `RateLimiter.Options`, which allows for specifying the rate-limiting algorithm to utilize:\n\n  You can choose from either the `token-bucket` or the `fixed-window` algorithms for rate-limiting.\n\n  ```ts\n  export declare namespace RateLimiter {\n    export interface Options {\n      /**\n       * The maximum number of requests that should be allowed.\n       */\n      readonly limit: number\n      /**\n       * The interval to utilize for rate-limiting requests. The semantics of the\n       * specified `interval` vary depending on the chosen `algorithm`:\n       *\n       * `token-bucket`: The maximum number of requests will be spread out over\n       * the provided interval if no tokens are available.\n       *\n       * For example, for a `RateLimiter` using the `token-bucket` algorithm with\n       * a `limit` of `10` and an `interval` of `1 seconds`, `1` request can be\n       * made every `100 millis`.\n       *\n       * `fixed-window`: The maximum number of requests will be reset during each\n       * interval. For example, for a `RateLimiter` using the `fixed-window`\n       * algorithm with a `limit` of `10` and an `interval` of `1 seconds`, a\n       * maximum of `10` requests can be made each second.\n       */\n      readonly interval: DurationInput\n      /**\n       * The algorithm to utilize for rate-limiting requests.\n       *\n       * Defaults to `token-bucket`.\n       */\n      readonly algorithm?: \"fixed-window\" | \"token-bucket\"\n    }\n  }\n  ```\n\n- [#2097](https://github.com/Effect-TS/effect/pull/2097) [`0f83515`](https://github.com/Effect-TS/effect/commit/0f83515a9c01d13c7c15a3f026e02d22c3c6bb7f) Thanks [@IMax153](https://github.com/IMax153)! - return the resulting available permits from Semaphore.release\n\n## 2.3.2\n\n### Patch Changes\n\n- [#2096](https://github.com/Effect-TS/effect/pull/2096) [`6654f5f`](https://github.com/Effect-TS/effect/commit/6654f5f0f6b9d97165ede5e04ca16776e2599328) Thanks [@tim-smart](https://github.com/tim-smart)! - default to `never` for Runtime returning functions\n\n  This includes:\n  - Effect.runtime\n  - FiberSet.makeRuntime\n\n  It prevents `unknown` from creeping into types, as well as `never` being a\n  useful default type for propogating Fiber Refs and other context.\n\n- [#2094](https://github.com/Effect-TS/effect/pull/2094) [`2eb11b4`](https://github.com/Effect-TS/effect/commit/2eb11b47752cedf233ef4c4395d9c4efc9b9e180) Thanks [@tim-smart](https://github.com/tim-smart)! - revert some type param adjustments in FiberSet\n\n  `makeRuntime` now has the R parameter first again.\n\n  Default to `unknown` for the A and E parameters instead of never.\n\n- [#2103](https://github.com/Effect-TS/effect/pull/2103) [`56c09bd`](https://github.com/Effect-TS/effect/commit/56c09bd369279a6a7785209d172739935818cba6) Thanks [@patroza](https://github.com/patroza)! - Expand Either and Option `andThen` to support the `map` case like Effects' `andThen`\n\n  For example:\n\n  ```ts\n  expect(pipe(Either.right(1), Either.andThen(2))).toStrictEqual(\n    Either.right(2)\n  )\n  expect(\n    pipe(\n      Either.right(1),\n      Either.andThen(() => 2)\n    )\n  ).toStrictEqual(Either.right(2))\n\n  expect(pipe(Option.some(1), Option.andThen(2))).toStrictEqual(Option.some(2))\n  expect(\n    pipe(\n      Option.some(1),\n      Option.andThen(() => 2)\n    )\n  ).toStrictEqual(Option.some(2))\n  ```\n\n- [#2098](https://github.com/Effect-TS/effect/pull/2098) [`71aa5b1`](https://github.com/Effect-TS/effect/commit/71aa5b1c180dcb8b53aefe232d12a97bd06b5447) Thanks [@ethanniser](https://github.com/ethanniser)! - removed `./internal/timeout` and replaced all usages with `setTimeout` directly\n\n  previously it was required to abstract away conditionally solving an bun had an issue with `setTimeout`, that caused incorrect behavior\n  that bug has since been fixed, and the `isBun` check is no longer needed\n  as such the timeout module is also no longer needed\n\n- [#2099](https://github.com/Effect-TS/effect/pull/2099) [`1700af8`](https://github.com/Effect-TS/effect/commit/1700af8af1131602887da721914c8562b6342393) Thanks [@tim-smart](https://github.com/tim-smart)! - optimize Effect.zip{Left,Right}\n\n  for the sequential case, avoid using Effect.all internally\n\n## 2.3.1\n\n### Patch Changes\n\n- [#2085](https://github.com/Effect-TS/effect/pull/2085) [`b5a8215`](https://github.com/Effect-TS/effect/commit/b5a8215ee2a97a8865d69ee55ce1b9835948c922) Thanks [@gcanti](https://github.com/gcanti)! - Fix Schedule typings (some APIs didn't have Effect parameters swapped).\n\n## 2.3.0\n\n### Minor Changes\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Runtime.AsyncFiberException` type parameters order from `AsyncFiberException<E, A>` to `AsyncFiberException<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Runtime.Cancel` type parameters order from `Cancel<E, A>` to `Cancel<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`c77f635`](https://github.com/Effect-TS/effect/commit/c77f635f8a26ca6d83cb569d911f8eee79033fd9) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Exit` type parameter order from `Exit<E, A>` to `Exit<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`e343a74`](https://github.com/Effect-TS/effect/commit/e343a74843dd9edf879417fa94cb51de7ed5b402) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Resource` type parameters order from `Resource<E, A>` to `Resource<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`acf1894`](https://github.com/Effect-TS/effect/commit/acf1894f45945dbe5c39451e36aabb4b5092f257) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `FiberMap` type parameters order from `FiberMap<K, E = unknown, A = unknown>` to `FiberMap<K, A = unknown, E = unknown>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c) Thanks [@github-actions](https://github.com/apps/github-actions)! - With this change we now require a string key to be provided for all tags and renames the dear old `Tag` to `GenericTag`, so when previously you could do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  interface Service {\n    readonly _: unique symbol\n  }\n  const Service = Context.Tag<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >()\n  ```\n\n  you are now mandated to do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  interface Service {\n    readonly _: unique symbol\n  }\n  const Service = Context.GenericTag<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >(\"Service\")\n  ```\n\n  This makes by default all tags globals and ensures better debuggaility when unexpected errors arise.\n\n  Furthermore we introduce a new way of constructing tags that should be considered the new default:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  class Service extends Context.Tag(\"Service\")<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >() {}\n\n  const program = Effect.flatMap(Service, ({ number }) => number).pipe(\n    Effect.flatMap((_) => Effect.log(`number: ${_}`))\n  )\n  ```\n\n  this will use \"Service\" as the key and will create automatically an opaque identifier (the class) to be used at the type level, it does something similar to the above in a single shot.\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`1a77f72`](https://github.com/Effect-TS/effect/commit/1a77f72cdaf43d6cdc91b6060f82832edcdbbcb3) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Effect` type parameters order from `Effect<R, E, A>` to `Effect<A, E = never, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`c986f0e`](https://github.com/Effect-TS/effect/commit/c986f0e0ce4d22ba08177ed351152718479ab63c) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `FiberSet` type parameters order from `FiberSet<E, A>` to `FiberSet<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Runtime.RunCallbackOptions` type parameters order from `RunCallbackOptions<E, A>` to `RunCallbackOptions<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`70dde23`](https://github.com/Effect-TS/effect/commit/70dde238f81125e353fd7bde5fc24ecd8969bf97) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `TDeferred` type parameters order from `TDeferred<E, A>` to `TDeferred<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`81b7425`](https://github.com/Effect-TS/effect/commit/81b7425320cbbe2a6cf547a3e3ab3549cdba14cf) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Streamable.Class` and `Effectable.Class` type parameters order from `Class<R, E, A>` to `Class<A, E = never, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`02c3461`](https://github.com/Effect-TS/effect/commit/02c34615d02f91269ea04036d0306fccf4e39e18) Thanks [@github-actions](https://github.com/apps/github-actions)! - With this change we remove the `Data.Data` type and we make `Equal.Equal` & `Hash.Hash` implicit traits.\n\n  The main reason is that `Data.Data<A>` was structurally equivalent to `A & Equal.Equal` but extending `Equal.Equal` doesn't mean that the equality is implemented by-value, so the type was simply adding noise without gaining any level of safety.\n\n  The module `Data` remains unchanged at the value level, all the functions previously available are supposed to work in exactly the same manner.\n\n  At the type level instead the functions return `Readonly` variants, so for example we have:\n\n  ```ts\n  import { Data } from \"effect\"\n\n  const obj = Data.struct({\n    a: 0,\n    b: 1\n  })\n  ```\n\n  will have the `obj` typed as:\n\n  ```ts\n  declare const obj: {\n    readonly a: number\n    readonly b: number\n  }\n  ```\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`0e56e99`](https://github.com/Effect-TS/effect/commit/0e56e998ab9815c4d096c239a553cb86a0f99af9) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Deferred` type parameters order from `Deferred<E, A>` to `Deferred<A, E>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`8b0ded9`](https://github.com/Effect-TS/effect/commit/8b0ded9f10ba0d96fcb9af24eff2dbd9341f85e3) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Fiber` type parameters order from `Fiber<E, A>` to `Fiber<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`8dd83e8`](https://github.com/Effect-TS/effect/commit/8dd83e854bfcaa6dab876994c5f813dcfb486c28) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Channel` type parameters order from `Channel<out Env, in InErr, in InElem, in InDone, out OutErr, out OutElem, out OutDone>` to `Channel<OutElem, InElem = unknown, OutErr = never, InErr = unknown, OutDone = void, InDone = unknown, Env = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`d75f6fe`](https://github.com/Effect-TS/effect/commit/d75f6fe6499deb0a5ee9ec94af3b5fd4eb03a2d0) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Take` type parameters order from `Take<E, A>` to `Take<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`7356e5c`](https://github.com/Effect-TS/effect/commit/7356e5cc16e9d70f18c02dee1dcb4ad539fd130a) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `STM` type parameters order from `STM<R, E, A>` to `STM<A, E = never, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`3077cde`](https://github.com/Effect-TS/effect/commit/3077cde08a60246821a940964a84dd7f7c8b9f54) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Stream` type parameters order from `Stream<R, E, A>` to `Stream<A, E = never, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`78f47ab`](https://github.com/Effect-TS/effect/commit/78f47abfe3cb0a8bbde818b1c5fc603270538b47) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Pool` type parameters order from `Pool<E, A>` to `Pool<A, E = never>`, and `KeyedPool` from `KeyedPool<E, A>` to `KeyedPool<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`52e5d20`](https://github.com/Effect-TS/effect/commit/52e5d2077582bf51f25861c7139fc920c2c24166) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Request` type parameters order from `Request<E, A>` to `Request<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`c6137ec`](https://github.com/Effect-TS/effect/commit/c6137ec62c6b5542d5062ae1a3c936cb915dee22) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `RuntimeFiber` type parameters order from `RuntimeFiber<E, A>` to `RuntimeFiber<A, E = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`f5ae081`](https://github.com/Effect-TS/effect/commit/f5ae08195e68e76faeac258c565d79da4e01e7d6) Thanks [@github-actions](https://github.com/apps/github-actions)! - Use `TimeoutException` instead of `NoSuchElementException` for timeout.\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`60686f5`](https://github.com/Effect-TS/effect/commit/60686f5c38bef1b93a3a0dda9b6596d46aceab03) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Layer` type parameters order from `Layer<RIn, E, ROut>` to `Layer<ROut, E = never, RIn = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c) Thanks [@github-actions](https://github.com/apps/github-actions)! - This change enables `Effect.serviceConstants` and `Effect.serviceMembers` to access any constant in the service, not only the effects, namely it is now possible to do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n\n  class NumberRepo extends Context.TagClass(\"NumberRepo\")<\n    NumberRepo,\n    {\n      readonly numbers: Array<number>\n    }\n  >() {\n    static numbers = Effect.serviceConstants(NumberRepo).numbers\n  }\n  ```\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e) Thanks [@github-actions](https://github.com/apps/github-actions)! - Rename ReadonlyRecord.update to .replace\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`8ee2931`](https://github.com/Effect-TS/effect/commit/8ee293159b4f7cb7af8558287a0a047f3a69743d) Thanks [@github-actions](https://github.com/apps/github-actions)! - enhance DX by swapping type parameters and adding defaults to:\n  - Effect\n    - async\n    - asyncOption\n    - asyncEither\n  - Stream\n    - asyncEffect\n    - asyncInterrupt\n    - asyncOption\n    - asyncScoped\n    - identity\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`6727474`](https://github.com/Effect-TS/effect/commit/672747497490a30d36dd49c06db19aabf09dc7f0) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Sink` type parameters order from `Sink<out R, out E, in In, out L, out Z>` to `Sink<out A, in In = unknown, out L = never, out E = never, out R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e) Thanks [@github-actions](https://github.com/apps/github-actions)! - rename ReadonlyRecord.upsert to .set\n\n### Patch Changes\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e) Thanks [@github-actions](https://github.com/apps/github-actions)! - add ReadonlyRecord.modify\n\n- [#2083](https://github.com/Effect-TS/effect/pull/2083) [`be19ce0`](https://github.com/Effect-TS/effect/commit/be19ce0b8bdf1fac80bb8d7e0b06a86986b47409) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Add `Ratelimiter` which limits the number of calls to a resource within a time window using the token bucket algorithm.\n\n  Usage Example:\n\n  ```ts\n  import { Effect, RateLimiter } from \"effect\"\n\n  // we need a scope because the rate limiter needs to allocate a state and a background job\n  const program = Effect.scoped(\n    Effect.gen(function* ($) {\n      // create a rate limiter that executes up to 10 requests within 2 seconds\n      const rateLimit = yield* $(RateLimiter.make(10, \"2 seconds\"))\n      // simulate repeated calls\n      for (let n = 0; n < 100; n++) {\n        // wrap the effect we want to limit with rateLimit\n        yield* $(rateLimit(Effect.log(\"Calling RateLimited Effect\")))\n      }\n    })\n  )\n\n  // will print 10 calls immediately and then throttle\n  program.pipe(Effect.runFork)\n  ```\n\n  Or, in a more real world scenario, with a dedicated Service + Layer:\n\n  ```ts\n  import { Context, Effect, Layer, RateLimiter } from \"effect\"\n\n  class ApiLimiter extends Context.Tag(\"@services/ApiLimiter\")<\n    ApiLimiter,\n    RateLimiter.RateLimiter\n  >() {\n    static Live = RateLimiter.make(10, \"2 seconds\").pipe(\n      Layer.scoped(ApiLimiter)\n    )\n  }\n\n  const program = Effect.gen(function* ($) {\n    const rateLimit = yield* $(ApiLimiter)\n    for (let n = 0; n < 100; n++) {\n      yield* $(rateLimit(Effect.log(\"Calling RateLimited Effect\")))\n    }\n  })\n\n  program.pipe(Effect.provide(ApiLimiter.Live), Effect.runFork)\n  ```\n\n- [#2084](https://github.com/Effect-TS/effect/pull/2084) [`4a5d01a`](https://github.com/Effect-TS/effect/commit/4a5d01a409e9b6dd53893e65f8e5c9247f568021) Thanks [@tim-smart](https://github.com/tim-smart)! - simplify RateLimiter implementation using semaphore\n\n- [#2084](https://github.com/Effect-TS/effect/pull/2084) [`4a5d01a`](https://github.com/Effect-TS/effect/commit/4a5d01a409e9b6dd53893e65f8e5c9247f568021) Thanks [@tim-smart](https://github.com/tim-smart)! - add Number.nextPow2\n\n  This function returns the next power of 2 from the given number.\n\n  ```ts\n  import { nextPow2 } from \"effect/Number\"\n\n  assert.deepStrictEqual(nextPow2(5), 8)\n  assert.deepStrictEqual(nextPow2(17), 32)\n  ```\n\n## 2.2.5\n\n### Patch Changes\n\n- [#2075](https://github.com/Effect-TS/effect/pull/2075) [`3ddfdbf`](https://github.com/Effect-TS/effect/commit/3ddfdbf914edea536aef207cec6695f33496258c) Thanks [@tim-smart](https://github.com/tim-smart)! - add apis for manipulating context to the Runtime module\n\n  These include:\n  - `Runtime.updateContext` for modifying the `Context` directly\n  - `Runtime.provideService` for adding services to an existing Runtime\n\n  Example:\n\n  ```ts\n  import { Context, Runtime } from \"effect\"\n\n  interface Name {\n    readonly _: unique symbol\n  }\n  const Name = Context.Tag<Name, string>(\"Name\")\n\n  const runtime: Runtime.Runtime<Name> = Runtime.defaultRuntime.pipe(\n    Runtime.provideService(Name, \"John\")\n  )\n  ```\n\n- [#2075](https://github.com/Effect-TS/effect/pull/2075) [`3ddfdbf`](https://github.com/Effect-TS/effect/commit/3ddfdbf914edea536aef207cec6695f33496258c) Thanks [@tim-smart](https://github.com/tim-smart)! - add apis for patching runtime flags to the Runtime module\n\n  The apis include:\n  - `Runtime.updateRuntimeFlags` for updating all the flags at once\n  - `Runtime.enableRuntimeFlag` for enabling a single runtime flag\n  - `Runtime.disableRuntimeFlag` for disabling a single runtime flag\n\n## 2.2.4\n\n### Patch Changes\n\n- [#2067](https://github.com/Effect-TS/effect/pull/2067) [`d0b911c`](https://github.com/Effect-TS/effect/commit/d0b911c75f284c7aa87f25aa96926e6bde7690d0) Thanks [@tim-smart](https://github.com/tim-smart)! - add releaseAll api to Semaphore\n\n  You can use `semphore.releaseAll` to atomically release all the permits of a\n  Semaphore.\n\n- [#2071](https://github.com/Effect-TS/effect/pull/2071) [`330e1a4`](https://github.com/Effect-TS/effect/commit/330e1a4e2c1fc0af6c80c80c81dd38c3e50fab78) Thanks [@tim-smart](https://github.com/tim-smart)! - add Option.orElseSome\n\n  Allows you to specify a default value for an Option, similar to\n  Option.getOrElse, except the return value is still an Option.\n\n  ```ts\n  import * as O from \"effect/Option\"\n  import { pipe } from \"effect/Function\"\n\n  assert.deepStrictEqual(\n    pipe(\n      O.none(),\n      O.orElseSome(() => \"b\")\n    ),\n    O.some(\"b\")\n  )\n  assert.deepStrictEqual(\n    pipe(\n      O.some(\"a\"),\n      O.orElseSome(() => \"b\")\n    ),\n    O.some(\"a\")\n  )\n  ```\n\n- [#2057](https://github.com/Effect-TS/effect/pull/2057) [`6928a2b`](https://github.com/Effect-TS/effect/commit/6928a2b0bae86a4bdfbece0aa32924207c2d5a70) Thanks [@joepjoosten](https://github.com/joepjoosten)! - Fix for possible stack overflow errors when using Array.push with spread operator arguments\n\n- [#2033](https://github.com/Effect-TS/effect/pull/2033) [`296bc1c`](https://github.com/Effect-TS/effect/commit/296bc1c9d24986d299d2669115d584cb27b73c60) Thanks [@rehos](https://github.com/rehos)! - Add toJSON for Secret\n\n## 2.2.3\n\n### Patch Changes\n\n- [#2004](https://github.com/Effect-TS/effect/pull/2004) [`22794e0`](https://github.com/Effect-TS/effect/commit/22794e0ba00e40281f30a22fa84412003c24877d) Thanks [@IMax153](https://github.com/IMax153)! - add documentation to Effect.intoDeferred\n\n- [#2007](https://github.com/Effect-TS/effect/pull/2007) [`f73e6c0`](https://github.com/Effect-TS/effect/commit/f73e6c033fb0729a9cfa5eb4bc39f79d3126e247) Thanks [@tim-smart](https://github.com/tim-smart)! - optimize fiber id hashing\n\n## 2.2.2\n\n### Patch Changes\n\n- [#1970](https://github.com/Effect-TS/effect/pull/1970) [`d404561`](https://github.com/Effect-TS/effect/commit/d404561e47ec2fa5f68709a308ee5d2ee959141d) Thanks [@IMax153](https://github.com/IMax153)! - execute acquire in `ScopedRef` uninterruptibly\n\n- [#1971](https://github.com/Effect-TS/effect/pull/1971) [`7b84a3c`](https://github.com/Effect-TS/effect/commit/7b84a3c7e4b9c8dc02294b0e3cc3ae3becea977b) Thanks [@IMax153](https://github.com/IMax153)! - race interruptibly in `Channel.mergeAllWith`\n\n## 2.2.1\n\n### Patch Changes\n\n- [#1964](https://github.com/Effect-TS/effect/pull/1964) [`84da31f`](https://github.com/Effect-TS/effect/commit/84da31f0643e8651b9d311b30526b1e4edfbdfb8) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: fix `sortWith` sig, closes #1961\n\n- [#1958](https://github.com/Effect-TS/effect/pull/1958) [`645bea2`](https://github.com/Effect-TS/effect/commit/645bea2551129f94a5b0e38347e28067dee531bb) Thanks [@gcanti](https://github.com/gcanti)! - Fix signatures related to predicates, closes #1916\n\n## 2.2.0\n\n### Minor Changes\n\n- [#1951](https://github.com/Effect-TS/effect/pull/1951) [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9) Thanks [@github-actions](https://github.com/apps/github-actions)! - make data-last FiberSet.run accept an Effect\n\n- [#1951](https://github.com/Effect-TS/effect/pull/1951) [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9) Thanks [@github-actions](https://github.com/apps/github-actions)! - make data-last FiberMap.run accept an Effect\n\n### Patch Changes\n\n- [#1957](https://github.com/Effect-TS/effect/pull/1957) [`202befc`](https://github.com/Effect-TS/effect/commit/202befc2ecbeb117c4fa85ef9b12a3d3a48273d2) Thanks [@IMax153](https://github.com/IMax153)! - cache `FiberId` hash in the constructor\n\n- [#1951](https://github.com/Effect-TS/effect/pull/1951) [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9) Thanks [@github-actions](https://github.com/apps/github-actions)! - add Fiber{Map,Set}.makeRuntime\n\n- [#1951](https://github.com/Effect-TS/effect/pull/1951) [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9) Thanks [@github-actions](https://github.com/apps/github-actions)! - add Fiber{Set,Map}.runtime api\n\n- [#1952](https://github.com/Effect-TS/effect/pull/1952) [`10df798`](https://github.com/Effect-TS/effect/commit/10df798639e556f9d88265ef7fc3cf8a3bbe3874) Thanks [@tim-smart](https://github.com/tim-smart)! - avoid sleep for zero duration in schedule\n\n## 2.1.2\n\n### Patch Changes\n\n- [#1949](https://github.com/Effect-TS/effect/pull/1949) [`21b9edd`](https://github.com/Effect-TS/effect/commit/21b9edde464f7c5624ef54ad1b5e264204a37625) Thanks [@TylorS](https://github.com/TylorS)! - Fix runFork with Scope\n\n## 2.1.1\n\n### Patch Changes\n\n- [#1934](https://github.com/Effect-TS/effect/pull/1934) [`a222524`](https://github.com/Effect-TS/effect/commit/a2225247e9de2e013d287320790fde88c081dbbd) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyRecord: add `mapKeys` / `mapEntries`\n\n## 2.1.0\n\n### Minor Changes\n\n- [#1919](https://github.com/Effect-TS/effect/pull/1919) [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02) Thanks [@github-actions](https://github.com/apps/github-actions)! - Add immediate:boolean flag to runFork/runCallback\n\n- [#1919](https://github.com/Effect-TS/effect/pull/1919) [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02) Thanks [@github-actions](https://github.com/apps/github-actions)! - Improve Effect.retry options\n\n- [#1919](https://github.com/Effect-TS/effect/pull/1919) [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02) Thanks [@github-actions](https://github.com/apps/github-actions)! - remove Effect.retry\\* variants\n\n- [#1919](https://github.com/Effect-TS/effect/pull/1919) [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02) Thanks [@github-actions](https://github.com/apps/github-actions)! - Allow providing Scope to Runtime.runFork\n\n- [#1919](https://github.com/Effect-TS/effect/pull/1919) [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02) Thanks [@github-actions](https://github.com/apps/github-actions)! - Add RunForkOptions to Effect.runFork\n\n### Patch Changes\n\n- [#1919](https://github.com/Effect-TS/effect/pull/1919) [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02) Thanks [@github-actions](https://github.com/apps/github-actions)! - add Effect.repeat options overload\n\n## 2.0.5\n\n### Patch Changes\n\n- [#1920](https://github.com/Effect-TS/effect/pull/1920) [`f7f19f6`](https://github.com/Effect-TS/effect/commit/f7f19f66a5fa349baa2412c1f9f15111c437df09) Thanks [@tim-smart](https://github.com/tim-smart)! - add FiberMap.remove\n\n## 2.0.4\n\n### Patch Changes\n\n- [#1897](https://github.com/Effect-TS/effect/pull/1897) [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51) Thanks [@tim-smart](https://github.com/tim-smart)! - add FiberSet module\n\n- [#1891](https://github.com/Effect-TS/effect/pull/1891) [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8) Thanks [@gcanti](https://github.com/gcanti)! - Types: add `MatchRecord`\n\n- [#1871](https://github.com/Effect-TS/effect/pull/1871) [`540b294`](https://github.com/Effect-TS/effect/commit/540b2941dd0a81e9688311583ce7e2e140d6e7a5) Thanks [@SandroMaglione](https://github.com/SandroMaglione)! - added Trie module\n\n- [#1897](https://github.com/Effect-TS/effect/pull/1897) [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51) Thanks [@tim-smart](https://github.com/tim-smart)! - add MutableHashMap.clear\n\n- [#1903](https://github.com/Effect-TS/effect/pull/1903) [`a3f96d6`](https://github.com/Effect-TS/effect/commit/a3f96d615b8b3e238dbfa01ef713c87e6f4532be) Thanks [@fubhy](https://github.com/fubhy)! - Converted value bag classes to object literals\n\n- [#1891](https://github.com/Effect-TS/effect/pull/1891) [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8) Thanks [@gcanti](https://github.com/gcanti)! - Struct: fix `pick` signature\n\n- [#1897](https://github.com/Effect-TS/effect/pull/1897) [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51) Thanks [@tim-smart](https://github.com/tim-smart)! - add FiberMap module\n\n- [#1891](https://github.com/Effect-TS/effect/pull/1891) [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8) Thanks [@gcanti](https://github.com/gcanti)! - Struct: add `get`\n\n- [#1891](https://github.com/Effect-TS/effect/pull/1891) [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8) Thanks [@gcanti](https://github.com/gcanti)! - Struct: fix `omit` signature\n\n- [#1894](https://github.com/Effect-TS/effect/pull/1894) [`25adce7`](https://github.com/Effect-TS/effect/commit/25adce7ae76ce834096dca1ed70a60ad1a349217) Thanks [@tim-smart](https://github.com/tim-smart)! - allow pre-validated cron expressions for Schedule.cron\n\n- [#1897](https://github.com/Effect-TS/effect/pull/1897) [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51) Thanks [@tim-smart](https://github.com/tim-smart)! - add MutableHashSet.clear\n\n## 2.0.3\n\n### Patch Changes\n\n- [#1884](https://github.com/Effect-TS/effect/pull/1884) [`87f7ef2`](https://github.com/Effect-TS/effect/commit/87f7ef28a3c27e2e4f2fcfa465f85bb2a45a3d6b) Thanks [@fubhy](https://github.com/fubhy)! - Added `Cron` module and `Schedule.cron` constructor\n\n- [#1885](https://github.com/Effect-TS/effect/pull/1885) [`1d3a06b`](https://github.com/Effect-TS/effect/commit/1d3a06bb58ad1ac123ae8f9d42b4345f9c9c53c0) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Avoid killing all fibers on interrupt\n\n## 2.0.2\n\n### Patch Changes\n\n- [#1850](https://github.com/Effect-TS/effect/pull/1850) [`d5a1949`](https://github.com/Effect-TS/effect/commit/d5a19499aac7c1d147674a35ac69992177c7536c) Thanks [@matheuspuel](https://github.com/matheuspuel)! - add index argument to many functions in ReadonlyArray\n\n## 2.0.1\n\n### Patch Changes\n\n- [#1859](https://github.com/Effect-TS/effect/pull/1859) [`16bd87d`](https://github.com/Effect-TS/effect/commit/16bd87d32611b966dc42ea4fc979764f97a49071) Thanks [@sukovanej](https://github.com/sukovanej)! - Include Config.LiteralValue in dts.\n\n## 2.0.0\n\n### Minor Changes\n\n- [`d0471ca`](https://github.com/Effect-TS/effect/commit/d0471ca7b544746674b9e1750202da72b0a21233) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Switch to monorepo structure\n\n### Patch Changes\n\n- [`d987daa`](https://github.com/Effect-TS/effect/commit/d987daafaddd43b6ade74916a08236c19ea0a9fa) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Switch effect dependency to caret\n\n- [#1797](https://github.com/Effect-TS/effect/pull/1797) [`7b5eaa3`](https://github.com/Effect-TS/effect/commit/7b5eaa3838c79bf4bdccf91b94d61bbc38a2ec95) Thanks [@matheuspuel](https://github.com/matheuspuel)! - make serviceFunctions and similar accept an Effect as the service\n\n- [#1854](https://github.com/Effect-TS/effect/pull/1854) [`0724211`](https://github.com/Effect-TS/effect/commit/072421149c36010748ff6b6ee19c15c6cffefe09) Thanks [@gcanti](https://github.com/gcanti)! - Add Option-returning overloads for findFirst and findLast in ReadonlyArray\n\n- [#1795](https://github.com/Effect-TS/effect/pull/1795) [`9f2bc5a`](https://github.com/Effect-TS/effect/commit/9f2bc5a19e0b678a0a85e84daac290922b0fd57d) Thanks [@matheuspuel](https://github.com/matheuspuel)! - add Config.literal\n\n- [#1848](https://github.com/Effect-TS/effect/pull/1848) [`04fb8b4`](https://github.com/Effect-TS/effect/commit/04fb8b428b19bba85a2c79910c5e363340d074e7) Thanks [@fubhy](https://github.com/fubhy)! - Avoid default parameter initilization\n\n- [#1847](https://github.com/Effect-TS/effect/pull/1847) [`bcf0900`](https://github.com/Effect-TS/effect/commit/bcf0900b58f449262556f80bff21e771a37272aa) Thanks [@fubhy](https://github.com/fubhy)! - Avoid inline creation & spreading of objects and arrays\n\n- [#1798](https://github.com/Effect-TS/effect/pull/1798) [`6299b84`](https://github.com/Effect-TS/effect/commit/6299b84c11e5d1fe79fa538df8935018c7613747) Thanks [@leonitousconforti](https://github.com/leonitousconforti)! - Uncommented linesIterator string function\n\n## 2.0.0-next.62\n\n### Minor Changes\n\n- [#1780](https://github.com/Effect-TS/effect/pull/1780) [`d6dd74e`](https://github.com/Effect-TS/effect/commit/d6dd74e191d3c798b08718b1326abc94982358ec) Thanks [@tim-smart](https://github.com/tim-smart)! - use NoSuchElementException for more optional apis\n\n### Patch Changes\n\n- [#1785](https://github.com/Effect-TS/effect/pull/1785) [`11a6910`](https://github.com/Effect-TS/effect/commit/11a6910f562e838b379ebc5edac94abb49d3a8e0) Thanks [@tim-smart](https://github.com/tim-smart)! - simplify Match extraction types\n\n- [#1782](https://github.com/Effect-TS/effect/pull/1782) [`1f398cf`](https://github.com/Effect-TS/effect/commit/1f398cf35008ec59f820338adeb2f4e2b928b1fb) Thanks [@tim-smart](https://github.com/tim-smart)! - add Layer.empty\n\n- [#1786](https://github.com/Effect-TS/effect/pull/1786) [`d27b68b`](https://github.com/Effect-TS/effect/commit/d27b68b7e3a57f77039fde78bf4c9924dc9d8226) Thanks [@tim-smart](https://github.com/tim-smart)! - only add one predicate in Match.discriminators\n\n## 2.0.0-next.61\n\n### Patch Changes\n\n- [#1768](https://github.com/Effect-TS/effect/pull/1768) [`7c6b90c`](https://github.com/Effect-TS/effect/commit/7c6b90c507835871bdefacdf0e0f84cb87febf16) Thanks [@gcanti](https://github.com/gcanti)! - Effect.mergeAll should work when Z is an iterable, closes #1765\n\n- [#1772](https://github.com/Effect-TS/effect/pull/1772) [`a1ba0c4`](https://github.com/Effect-TS/effect/commit/a1ba0c4dbbc8ee0a8d3652feabbf3c0accdbe3de) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyRecord: add `fromIterableBy`\n\n- [#1778](https://github.com/Effect-TS/effect/pull/1778) [`2c5a401`](https://github.com/Effect-TS/effect/commit/2c5a401a0be13b709c83365acf6a49a52896711f) Thanks [@IMax153](https://github.com/IMax153)! - add ConfigProvider.fromJson to support loading configuration from a JSON object\n\n- [#1770](https://github.com/Effect-TS/effect/pull/1770) [`d4d403e`](https://github.com/Effect-TS/effect/commit/d4d403e60d9ae81a69aa1190f50e6f9cb11651f3) Thanks [@tim-smart](https://github.com/tim-smart)! - adjust metric boundaries for timer histograms\n\n- [#1776](https://github.com/Effect-TS/effect/pull/1776) [`4c22ed5`](https://github.com/Effect-TS/effect/commit/4c22ed51b6f6458166d1151b1eaef0fe4ac2f5e4) Thanks [@fubhy](https://github.com/fubhy)! - Self-assign normalized `BigDecimal`\n\n## 2.0.0-next.60\n\n### Minor Changes\n\n- [#1755](https://github.com/Effect-TS/effect/pull/1755) [`0200f12`](https://github.com/Effect-TS/effect/commit/0200f1263dcfd769ed6b381036207a583b34964c) Thanks [@gcanti](https://github.com/gcanti)! - Effect: remove `config` API (since `Config` now implements `Effect`)\n\n- [#1747](https://github.com/Effect-TS/effect/pull/1747) [`83db34e`](https://github.com/Effect-TS/effect/commit/83db34eb4080909b3ae7536886d27870e77d8b7e) Thanks [@fubhy](https://github.com/fubhy)! - Generate proxy packages\n\n### Patch Changes\n\n- [#1756](https://github.com/Effect-TS/effect/pull/1756) [`7c1dcc7`](https://github.com/Effect-TS/effect/commit/7c1dcc732c735a6f3f64274be4b6daea6e9fdde6) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Fix stack filtering for first throw point\n\n- [#1753](https://github.com/Effect-TS/effect/pull/1753) [`1727ca5`](https://github.com/Effect-TS/effect/commit/1727ca5011d62b5353ed7c53bf1867dc37a41954) Thanks [@IMax153](https://github.com/IMax153)! - expose Console service tag\n\n- [#1749](https://github.com/Effect-TS/effect/pull/1749) [`299e8b5`](https://github.com/Effect-TS/effect/commit/299e8b5e085a624d1141b5fdaf00fc50203c57fa) Thanks [@IMax153](https://github.com/IMax153)! - fix the jsdoc for Effect.withConsoleScoped\n\n- [#1758](https://github.com/Effect-TS/effect/pull/1758) [`88d957d`](https://github.com/Effect-TS/effect/commit/88d957d724b390e005fb245b9deadfcdbd4a55d1) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Fix provideSomeRuntime internals, restore context and flags properly\n\n- [#1754](https://github.com/Effect-TS/effect/pull/1754) [`6a95cc0`](https://github.com/Effect-TS/effect/commit/6a95cc0f38914b63a3884697e410f79c75add185) Thanks [@tim-smart](https://github.com/tim-smart)! - make Config implement Effect\n\n## 2.0.0-next.59\n\n### Minor Changes\n\n- [#1743](https://github.com/Effect-TS/effect/pull/1743) [`143ee1e`](https://github.com/Effect-TS/effect/commit/143ee1e58ff98c9b8813622d14ef67a0e7f76874) Thanks [@tim-smart](https://github.com/tim-smart)! - rename FiberRefs.updatedAs to FiberRef.updateAs\n\n- [#1738](https://github.com/Effect-TS/effect/pull/1738) [`d4abb06`](https://github.com/Effect-TS/effect/commit/d4abb06a411cc088d1eb20d853c3a9da97d4f847) Thanks [@gcanti](https://github.com/gcanti)! - ReaonlyRecord: rename `fromIterable` to `fromIterableWith` and add standard `fromIterable` API\n\n- [#1743](https://github.com/Effect-TS/effect/pull/1743) [`143ee1e`](https://github.com/Effect-TS/effect/commit/143ee1e58ff98c9b8813622d14ef67a0e7f76874) Thanks [@tim-smart](https://github.com/tim-smart)! - use native js data types for Metrics\n\n### Patch Changes\n\n- [#1733](https://github.com/Effect-TS/effect/pull/1733) [`8177e4c`](https://github.com/Effect-TS/effect/commit/8177e4cc50eba7534b794ddaabb7754641060e9b) Thanks [@IMax153](https://github.com/IMax153)! - add `withConsoleScoped` to `Console`/`Effect` modules\n\n- [#1726](https://github.com/Effect-TS/effect/pull/1726) [`1152a2c`](https://github.com/Effect-TS/effect/commit/1152a2c900c43687876e042d1fc78570e48aebe0) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: fix the tacit use of unzip\n\n- [#1743](https://github.com/Effect-TS/effect/pull/1743) [`143ee1e`](https://github.com/Effect-TS/effect/commit/143ee1e58ff98c9b8813622d14ef67a0e7f76874) Thanks [@tim-smart](https://github.com/tim-smart)! - prefer Date.now() over new Date().getTime()\n\n- [#1735](https://github.com/Effect-TS/effect/pull/1735) [`cf4c044`](https://github.com/Effect-TS/effect/commit/cf4c044d799ae1249084abfd59d7f2ecd4a7c755) Thanks [@tim-smart](https://github.com/tim-smart)! - expose Layer MemoMap apis\n\n- [#1724](https://github.com/Effect-TS/effect/pull/1724) [`1884fa3`](https://github.com/Effect-TS/effect/commit/1884fa3f18c0ae85f62af338f1ac5863ad24f778) Thanks [@gcanti](https://github.com/gcanti)! - Chunk: fix the tacit use of flatten\n\n- [#1726](https://github.com/Effect-TS/effect/pull/1726) [`1152a2c`](https://github.com/Effect-TS/effect/commit/1152a2c900c43687876e042d1fc78570e48aebe0) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: fix the tacit use of reverse\n\n- [#1726](https://github.com/Effect-TS/effect/pull/1726) [`1152a2c`](https://github.com/Effect-TS/effect/commit/1152a2c900c43687876e042d1fc78570e48aebe0) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: fix the tacit use of dedupe\n\n- [#1743](https://github.com/Effect-TS/effect/pull/1743) [`143ee1e`](https://github.com/Effect-TS/effect/commit/143ee1e58ff98c9b8813622d14ef67a0e7f76874) Thanks [@tim-smart](https://github.com/tim-smart)! - add FiberRefs.updateManyAs\n\n- [#1737](https://github.com/Effect-TS/effect/pull/1737) [`9c26f58`](https://github.com/Effect-TS/effect/commit/9c26f58715c386885e25fa30662ad8c77576c22e) Thanks [@gcanti](https://github.com/gcanti)! - Chunk: add splitNonEmptyAt\n\n- [#1743](https://github.com/Effect-TS/effect/pull/1743) [`143ee1e`](https://github.com/Effect-TS/effect/commit/143ee1e58ff98c9b8813622d14ef67a0e7f76874) Thanks [@tim-smart](https://github.com/tim-smart)! - short circuit for empty patches\n\n- [#1736](https://github.com/Effect-TS/effect/pull/1736) [`8249277`](https://github.com/Effect-TS/effect/commit/82492774087746a1174353480465c439388f88f4) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: add splitWhere\n\n- [#1729](https://github.com/Effect-TS/effect/pull/1729) [`3c77e12`](https://github.com/Effect-TS/effect/commit/3c77e12d92030413e25f8a32ab84a4feb15c5164) Thanks [@jessekelly881](https://github.com/jessekelly881)! - updated BigDecimal.toString\n\n- [#1726](https://github.com/Effect-TS/effect/pull/1726) [`1152a2c`](https://github.com/Effect-TS/effect/commit/1152a2c900c43687876e042d1fc78570e48aebe0) Thanks [@gcanti](https://github.com/gcanti)! - Chunk > flatMap: fix return type\n\n- [#1736](https://github.com/Effect-TS/effect/pull/1736) [`8249277`](https://github.com/Effect-TS/effect/commit/82492774087746a1174353480465c439388f88f4) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: add split\n\n- [#1726](https://github.com/Effect-TS/effect/pull/1726) [`1152a2c`](https://github.com/Effect-TS/effect/commit/1152a2c900c43687876e042d1fc78570e48aebe0) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: fix sortBy signature\n\n- [#1726](https://github.com/Effect-TS/effect/pull/1726) [`1152a2c`](https://github.com/Effect-TS/effect/commit/1152a2c900c43687876e042d1fc78570e48aebe0) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: fix chop signature\n\n- [#1726](https://github.com/Effect-TS/effect/pull/1726) [`1152a2c`](https://github.com/Effect-TS/effect/commit/1152a2c900c43687876e042d1fc78570e48aebe0) Thanks [@gcanti](https://github.com/gcanti)! - List > flatMap: fix return type\n\n- [#1743](https://github.com/Effect-TS/effect/pull/1743) [`143ee1e`](https://github.com/Effect-TS/effect/commit/143ee1e58ff98c9b8813622d14ef67a0e7f76874) Thanks [@tim-smart](https://github.com/tim-smart)! - replace use of throw in fiber runtime\n\n- [#1743](https://github.com/Effect-TS/effect/pull/1743) [`143ee1e`](https://github.com/Effect-TS/effect/commit/143ee1e58ff98c9b8813622d14ef67a0e7f76874) Thanks [@tim-smart](https://github.com/tim-smart)! - optimize FiberRef.update/forkAs\n\n- [#1724](https://github.com/Effect-TS/effect/pull/1724) [`1884fa3`](https://github.com/Effect-TS/effect/commit/1884fa3f18c0ae85f62af338f1ac5863ad24f778) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: fix the tacit use of flatten\n\n- [#1727](https://github.com/Effect-TS/effect/pull/1727) [`9b5f72d`](https://github.com/Effect-TS/effect/commit/9b5f72d6bb9efd22f52c64c727b79f29d94507d3) Thanks [@photomoose](https://github.com/photomoose)! - Fix number of retries in retryN\n\n- [#1735](https://github.com/Effect-TS/effect/pull/1735) [`cf4c044`](https://github.com/Effect-TS/effect/commit/cf4c044d799ae1249084abfd59d7f2ecd4a7c755) Thanks [@tim-smart](https://github.com/tim-smart)! - fix memoization of Layer.effect/scoped\n\n- [#1726](https://github.com/Effect-TS/effect/pull/1726) [`1152a2c`](https://github.com/Effect-TS/effect/commit/1152a2c900c43687876e042d1fc78570e48aebe0) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: fix dedupeWith signature\n\n- [#1726](https://github.com/Effect-TS/effect/pull/1726) [`1152a2c`](https://github.com/Effect-TS/effect/commit/1152a2c900c43687876e042d1fc78570e48aebe0) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray > flatMap: fix return type\n\n- [#1743](https://github.com/Effect-TS/effect/pull/1743) [`143ee1e`](https://github.com/Effect-TS/effect/commit/143ee1e58ff98c9b8813622d14ef67a0e7f76874) Thanks [@tim-smart](https://github.com/tim-smart)! - optimize MutableHashMap\n\n- [#1745](https://github.com/Effect-TS/effect/pull/1745) [`c142caa`](https://github.com/Effect-TS/effect/commit/c142caa725646929d8086d8e63d7a406fd2415da) Thanks [@IMax153](https://github.com/IMax153)! - rename ConfigSecret to Secret\n\n- [#1733](https://github.com/Effect-TS/effect/pull/1733) [`8177e4c`](https://github.com/Effect-TS/effect/commit/8177e4cc50eba7534b794ddaabb7754641060e9b) Thanks [@IMax153](https://github.com/IMax153)! - export `Console` combinators from the `Effect` module to match other default services\n\n## 2.0.0-next.58\n\n### Patch Changes\n\n- [#1722](https://github.com/Effect-TS/effect/pull/1722) [`b5569e3`](https://github.com/Effect-TS/effect/commit/b5569e358534da41047a687afbc85dbe8517ddca) Thanks [@tim-smart](https://github.com/tim-smart)! - update build setup to put cjs in root directory\n\n- [#1720](https://github.com/Effect-TS/effect/pull/1720) [`56a0334`](https://github.com/Effect-TS/effect/commit/56a033456c3285ff95fdbeeddff2bda6a1e39bec) Thanks [@tim-smart](https://github.com/tim-smart)! - fix jsdoc for Inspectable.format\n\n## 2.0.0-next.57\n\n### Minor Changes\n\n- [#1701](https://github.com/Effect-TS/effect/pull/1701) [`739460b06`](https://github.com/Effect-TS/effect/commit/739460b0609cd490abbb0a8dfbe3dfe9f67a3680) Thanks [@fubhy](https://github.com/fubhy)! - Allow to set a custom description for timer metrics\n\n- [#1704](https://github.com/Effect-TS/effect/pull/1704) [`accf8a647`](https://github.com/Effect-TS/effect/commit/accf8a647b7a869d2de445e430dab07f08aac0cc) Thanks [@fubhy](https://github.com/fubhy)! - Renamed `ReadonlyArray.compact` and `ReadonlyRecord.compact` to `.getSomes`\n\n- [#1716](https://github.com/Effect-TS/effect/pull/1716) [`023b512bd`](https://github.com/Effect-TS/effect/commit/023b512bd0b3d5a91bbe85b262e8762e5ce3ac21) Thanks [@gcanti](https://github.com/gcanti)! - List: merge NonEmpty APIs into base ones\n\n- [#1717](https://github.com/Effect-TS/effect/pull/1717) [`869c9c31d`](https://github.com/Effect-TS/effect/commit/869c9c31de2d297bc2937ca6b0a417c10ed1a12f) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray: merge NonEmpty APIs into base ones\n\n- [#1713](https://github.com/Effect-TS/effect/pull/1713) [`906343263`](https://github.com/Effect-TS/effect/commit/906343263f6306965602422508ef3c7158dd7cc8) Thanks [@gcanti](https://github.com/gcanti)! - BigDecimal: rename `toString` to `format`\n\n- [#1688](https://github.com/Effect-TS/effect/pull/1688) [`9698427fe`](https://github.com/Effect-TS/effect/commit/9698427fea446a08b702d3f820db96753efad638) Thanks [@tim-smart](https://github.com/tim-smart)! - replace Layer.provide* with Layer.use*\n\n- [#1711](https://github.com/Effect-TS/effect/pull/1711) [`ff6fadb93`](https://github.com/Effect-TS/effect/commit/ff6fadb934fef37dec1f58eaeff40c0d027393bb) Thanks [@gcanti](https://github.com/gcanti)! - Chunk: merge NonEmpty APIs into base ones\n\n- [#1707](https://github.com/Effect-TS/effect/pull/1707) [`fb1a98fab`](https://github.com/Effect-TS/effect/commit/fb1a98fab613c7ec34abf35c348f3cadcc7d943d) Thanks [@gcanti](https://github.com/gcanti)! - Layer: rename `zipWithPar` to `zipWith` (standard)\n\n### Patch Changes\n\n- [#1690](https://github.com/Effect-TS/effect/pull/1690) [`eb6d7aada`](https://github.com/Effect-TS/effect/commit/eb6d7aada122b260b52e53ff2fd28bfe851b7f40) Thanks [@tim-smart](https://github.com/tim-smart)! - allow omission of Scope type in R of Stream.asyncScoped\n\n- [#1704](https://github.com/Effect-TS/effect/pull/1704) [`accf8a647`](https://github.com/Effect-TS/effect/commit/accf8a647b7a869d2de445e430dab07f08aac0cc) Thanks [@fubhy](https://github.com/fubhy)! - Added `.getLefts` and `.getRights`\n\n- [#1703](https://github.com/Effect-TS/effect/pull/1703) [`f8d27500d`](https://github.com/Effect-TS/effect/commit/f8d27500dae8eb23ff8b93e8b894a4ab4ec6ebad) Thanks [@jessekelly881](https://github.com/jessekelly881)! - improved Duration.toString\n\n- [#1689](https://github.com/Effect-TS/effect/pull/1689) [`a0bd532e8`](https://github.com/Effect-TS/effect/commit/a0bd532e85fa603b29e58c6a2670433b0346377a) Thanks [@FedericoBiccheddu](https://github.com/FedericoBiccheddu)! - improve `Pool`'s `makeWithTTL` JSDoc example\n\n- [#1715](https://github.com/Effect-TS/effect/pull/1715) [`8b1a7e8a1`](https://github.com/Effect-TS/effect/commit/8b1a7e8a1acddec126b4292fc24154f6df615f0a) Thanks [@tim-smart](https://github.com/tim-smart)! - only add onInterrupt in Effect.async if required\n\n- [#1694](https://github.com/Effect-TS/effect/pull/1694) [`33ffa62b4`](https://github.com/Effect-TS/effect/commit/33ffa62b444db82afc0e43154eb4b3576761c583) Thanks [@extremegf](https://github.com/extremegf)! - Add Either.filterOrLeft\n\n- [#1695](https://github.com/Effect-TS/effect/pull/1695) [`7ccd1eb0b`](https://github.com/Effect-TS/effect/commit/7ccd1eb0b71ec84033d2b106412ccfcac7753e4c) Thanks [@jessekelly881](https://github.com/jessekelly881)! - added Option.andThen\n\n- [#1706](https://github.com/Effect-TS/effect/pull/1706) [`8a1e98ce3`](https://github.com/Effect-TS/effect/commit/8a1e98ce33344347f6edec0fc89c4c22d8393e90) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Improve consistency between request batching and fiber environment.\n\n  In prior releases request batching required operators that act on fiber context such as `Effect.locally` to be aware of batching in order to avoid bugs where the effect executed post batching would lose the fiber environment (context, refs, and flags).\n\n  This change restructure how batching internally works, inside the fiber we now slice up the stack and restore the exact context that was destroyed, by rewriting the internals of forEach batching is now transparent to any other function that deals with fiber state.\n\n- [#1687](https://github.com/Effect-TS/effect/pull/1687) [`e4d90ed38`](https://github.com/Effect-TS/effect/commit/e4d90ed3896f6d00e8470e73e0d9f597504fc888) Thanks [@matheuspuel](https://github.com/matheuspuel)! - fix YieldableError.toString crashing on react-native\n\n- [#1681](https://github.com/Effect-TS/effect/pull/1681) [`e5cd27c7d`](https://github.com/Effect-TS/effect/commit/e5cd27c7d5988902b238d568d6d13470babb8ee9) Thanks [@matheuspuel](https://github.com/matheuspuel)! - forbid excess properties when matching tags\n\n- [#1692](https://github.com/Effect-TS/effect/pull/1692) [`37a7cfe94`](https://github.com/Effect-TS/effect/commit/37a7cfe94f3baa51fb465c1f6591f20d2aab5c7f) Thanks [@tim-smart](https://github.com/tim-smart)! - add PrimaryKey.value\n\n- [#1679](https://github.com/Effect-TS/effect/pull/1679) [`c1146e473`](https://github.com/Effect-TS/effect/commit/c1146e47343a39e0d168f10547df43d0728df50d) Thanks [@k44](https://github.com/k44)! - fix error value of `Effect.tryPromise`\n\n- [#1719](https://github.com/Effect-TS/effect/pull/1719) [`30893ed48`](https://github.com/Effect-TS/effect/commit/30893ed48592460b8bbef6388802893ed9f0f23f) Thanks [@tim-smart](https://github.com/tim-smart)! - add Request.failCause\n\n- [#1712](https://github.com/Effect-TS/effect/pull/1712) [`e2ccf5120`](https://github.com/Effect-TS/effect/commit/e2ccf512088e0dfb0e3816ec259d4f6736f5cf28) Thanks [@thewilkybarkid](https://github.com/thewilkybarkid)! - fix ReadonlyArray.difference description\n\n- [#1715](https://github.com/Effect-TS/effect/pull/1715) [`8b1a7e8a1`](https://github.com/Effect-TS/effect/commit/8b1a7e8a1acddec126b4292fc24154f6df615f0a) Thanks [@tim-smart](https://github.com/tim-smart)! - simplify Effect.tryCatch implementation\n\n- [#1684](https://github.com/Effect-TS/effect/pull/1684) [`aeb33b158`](https://github.com/Effect-TS/effect/commit/aeb33b158b14ea1a28fb78954adb717019f913a1) Thanks [@KhraksMamtsov](https://github.com/KhraksMamtsov)! - change typo in Either documentation\n\n- [#1699](https://github.com/Effect-TS/effect/pull/1699) [`06eb1d380`](https://github.com/Effect-TS/effect/commit/06eb1d3801ae6ef93412529af3ef37b509cba7ef) Thanks [@gcanti](https://github.com/gcanti)! - Config: standardize error messages\n\n- [#1683](https://github.com/Effect-TS/effect/pull/1683) [`a6a78ccad`](https://github.com/Effect-TS/effect/commit/a6a78ccad976c510cf0d6a33eee5e10697b310da) Thanks [@tim-smart](https://github.com/tim-smart)! - add default type to data class props generic\n\n- [#1718](https://github.com/Effect-TS/effect/pull/1718) [`3b0768ce6`](https://github.com/Effect-TS/effect/commit/3b0768ce68035fe8a2b017b736f24ab3bcce350b) Thanks [@KhraksMamtsov](https://github.com/KhraksMamtsov)! - get rid `absorb` mention\n\n- [#1686](https://github.com/Effect-TS/effect/pull/1686) [`9f4d2874d`](https://github.com/Effect-TS/effect/commit/9f4d2874da7568eafd14c183d127132788f86668) Thanks [@gcanti](https://github.com/gcanti)! - Types: add variance helpers\n\n- [#1697](https://github.com/Effect-TS/effect/pull/1697) [`e1a4b6a63`](https://github.com/Effect-TS/effect/commit/e1a4b6a63d73aa111015652bfe4584b767a53e61) Thanks [@tim-smart](https://github.com/tim-smart)! - expose currentConcurrency fiber ref\n\n## 2.0.0-next.56\n\n### Minor Changes\n\n- [#1671](https://github.com/Effect-TS/effect/pull/1671) [`c415248cd`](https://github.com/Effect-TS/effect/commit/c415248cd8e5a01144a0c9135da58cb0b0afc37d) Thanks [@tim-smart](https://github.com/tim-smart)! - support Promise in Effect.andThen and .tap\n\n- [#1671](https://github.com/Effect-TS/effect/pull/1671) [`c415248cd`](https://github.com/Effect-TS/effect/commit/c415248cd8e5a01144a0c9135da58cb0b0afc37d) Thanks [@tim-smart](https://github.com/tim-smart)! - add Cause.UnknownException and use it over `unknown`\n\n- [#1678](https://github.com/Effect-TS/effect/pull/1678) [`8ed7626a4`](https://github.com/Effect-TS/effect/commit/8ed7626a49f1a4fb1b9315d97008355f1b6962ef) Thanks [@tim-smart](https://github.com/tim-smart)! - use `new` for Cause error constructors\n\n### Patch Changes\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - TDeferred: fix E, A variance (from covariant to invariant)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - SynchronizedRef: fix A variance (from covariant to invariant)\n\n- [#1661](https://github.com/Effect-TS/effect/pull/1661) [`6c32d12d7`](https://github.com/Effect-TS/effect/commit/6c32d12d7be5eb829dc5d8fe576f4fda8217ea6d) Thanks [@fubhy](https://github.com/fubhy)! - Use `sideEffects: []` in package.json\n\n- [#1663](https://github.com/Effect-TS/effect/pull/1663) [`69bcb5b7a`](https://github.com/Effect-TS/effect/commit/69bcb5b7ab4c4faa873cf8132172e68fc8eb9b6d) Thanks [@tim-smart](https://github.com/tim-smart)! - add TaggedClass to /request\n\n- [#1676](https://github.com/Effect-TS/effect/pull/1676) [`995318829`](https://github.com/Effect-TS/effect/commit/9953188299848a96adf637b5a90093b4cc8792f6) Thanks [@tim-smart](https://github.com/tim-smart)! - support undefined values in TPubSub\n\n- [#1658](https://github.com/Effect-TS/effect/pull/1658) [`396428a73`](https://github.com/Effect-TS/effect/commit/396428a73871715a6aed632c2c5b5affb2e509ac) Thanks [@wmaurer](https://github.com/wmaurer)! - ReadonlyArray: Improved refinement typings for partition\n\n- [#1672](https://github.com/Effect-TS/effect/pull/1672) [`80bf68da5`](https://github.com/Effect-TS/effect/commit/80bf68da546fecf91e3ebcd43c8d4798841227df) Thanks [@tim-smart](https://github.com/tim-smart)! - add metric .register() for forcing addition to registry\n\n- [#1669](https://github.com/Effect-TS/effect/pull/1669) [`541330b11`](https://github.com/Effect-TS/effect/commit/541330b110fc3d5f463f34cb48490e25b29036ae) Thanks [@tim-smart](https://github.com/tim-smart)! - add PrimaryKey module\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - RedBlackTree: make Key invariant\n\n- [#1664](https://github.com/Effect-TS/effect/pull/1664) [`54ce5e638`](https://github.com/Effect-TS/effect/commit/54ce5e63882136d77b50ebe6613db4f349bb0195) Thanks [@gcanti](https://github.com/gcanti)! - PollingMetric: renamed to MetricPolling (standard)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - Deferred: fix E and A variance (from covariant to invariant)\n\n- [#1660](https://github.com/Effect-TS/effect/pull/1660) [`ecc334703`](https://github.com/Effect-TS/effect/commit/ecc3347037965df8f6e6e19423f4c0cfea7e04b7) Thanks [@gcanti](https://github.com/gcanti)! - HashMap: swap findFirst > predicate arguments (standard)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - TSet: fix A variance (from covariant to invariant)\n\n- [#1603](https://github.com/Effect-TS/effect/pull/1603) [`4e7a6912c`](https://github.com/Effect-TS/effect/commit/4e7a6912c782571f07a055eccae8aa973b4b5c6f) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Auto-flattening Effect.tap\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - RequestResolver: fix A variance (from covariant to contravariant)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - ScopedRef: fix A variance (from covariant to invariant)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - Reloadable: fix A variance (from covariant to invariant)\n\n- [#1660](https://github.com/Effect-TS/effect/pull/1660) [`ecc334703`](https://github.com/Effect-TS/effect/commit/ecc3347037965df8f6e6e19423f4c0cfea7e04b7) Thanks [@gcanti](https://github.com/gcanti)! - fix ReadonlyRecord.partition signature\n\n- [#1670](https://github.com/Effect-TS/effect/pull/1670) [`c3bfc90e4`](https://github.com/Effect-TS/effect/commit/c3bfc90e4af20c2f2e8e3c663690779d4332f86e) Thanks [@tim-smart](https://github.com/tim-smart)! - add Request.Class\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - Resource: fix E, A variance (from covariant to invariant)\n\n- [#1674](https://github.com/Effect-TS/effect/pull/1674) [`c687a8701`](https://github.com/Effect-TS/effect/commit/c687a870157e1c212f29ddb3264db0200d03466e) Thanks [@fubhy](https://github.com/fubhy)! - Allow hrtime as `Duration` input\n\n- [#1676](https://github.com/Effect-TS/effect/pull/1676) [`995318829`](https://github.com/Effect-TS/effect/commit/9953188299848a96adf637b5a90093b4cc8792f6) Thanks [@tim-smart](https://github.com/tim-smart)! - support undefined values in TQueue\n\n- [#1668](https://github.com/Effect-TS/effect/pull/1668) [`fc9bce6a2`](https://github.com/Effect-TS/effect/commit/fc9bce6a24b1fc46955d276ed0011a93378b3297) Thanks [@gcanti](https://github.com/gcanti)! - Config: propagate the path in validation, closes #1667\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - PubSub: fix A variance (from contravariant to invariant)\n\n- [#1676](https://github.com/Effect-TS/effect/pull/1676) [`995318829`](https://github.com/Effect-TS/effect/commit/9953188299848a96adf637b5a90093b4cc8792f6) Thanks [@tim-smart](https://github.com/tim-smart)! - support null values in PubSub\n\n- [#1655](https://github.com/Effect-TS/effect/pull/1655) [`0c6330db0`](https://github.com/Effect-TS/effect/commit/0c6330db0dac8264d9a9e2ca8babea01a054317a) Thanks [@gcanti](https://github.com/gcanti)! - interfaces: revert changing methods to props (RE: #1644)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - FiberRef: fix A variance (from covariant to invariant)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - StrategyVariance: fix A variance (from covariant to invariant)\n\n- [#1678](https://github.com/Effect-TS/effect/pull/1678) [`8ed7626a4`](https://github.com/Effect-TS/effect/commit/8ed7626a49f1a4fb1b9315d97008355f1b6962ef) Thanks [@tim-smart](https://github.com/tim-smart)! - Cause.YieldableError extends Inspectable\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - TMap: fix K, V variance (from covariant to invariant)\n\n- [#1665](https://github.com/Effect-TS/effect/pull/1665) [`a00b920b8`](https://github.com/Effect-TS/effect/commit/a00b920b8910f975ff61be48c1538de527fa290b) Thanks [@gcanti](https://github.com/gcanti)! - Chunk: fix partition signature (expose the index of the element)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - Pool: fix A variance (from covariant to invariant)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - Cache / ConsumerCache: fix Key variance (from contravariant to invariant)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - SubscriptionRef: fix A variance (from covariant to invariant)\n\n- [#1603](https://github.com/Effect-TS/effect/pull/1603) [`4e7a6912c`](https://github.com/Effect-TS/effect/commit/4e7a6912c782571f07a055eccae8aa973b4b5c6f) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Introduce Types.NoInfer\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - TPriorityQueue: fix A variance (from covariant to invariant)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - SortedSet: make A invariant\n\n- [#1654](https://github.com/Effect-TS/effect/pull/1654) [`d2b7e0ef0`](https://github.com/Effect-TS/effect/commit/d2b7e0ef022234ceba0c3b77afdc3285081ece97) Thanks [@wmaurer](https://github.com/wmaurer)! - Added refinement overloads to Sink.collectAllWhile, Stream.partition and Stream.takeWhile. Added dtslint tests for Sink and Stream functions with refinement overloads\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - SortedMap: make K invariant\n\n- [#1603](https://github.com/Effect-TS/effect/pull/1603) [`4e7a6912c`](https://github.com/Effect-TS/effect/commit/4e7a6912c782571f07a055eccae8aa973b4b5c6f) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Introduce Effect.andThen\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - TArray: fix A variance (from covariant to invariant)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - KeyedPool: fix A variance (from covariant to invariant)\n\n- [#1662](https://github.com/Effect-TS/effect/pull/1662) [`aa6787e16`](https://github.com/Effect-TS/effect/commit/aa6787e166ba51511de0ff96dbfd986f1c974f2d) Thanks [@gcanti](https://github.com/gcanti)! - TPubSub: make A invariant\n\n- [#1671](https://github.com/Effect-TS/effect/pull/1671) [`c415248cd`](https://github.com/Effect-TS/effect/commit/c415248cd8e5a01144a0c9135da58cb0b0afc37d) Thanks [@tim-smart](https://github.com/tim-smart)! - move internal exceptions into core\n\n## 2.0.0-next.55\n\n### Patch Changes\n\n- [#1648](https://github.com/Effect-TS/effect/pull/1648) [`b2cbb6a79`](https://github.com/Effect-TS/effect/commit/b2cbb6a7946590411ce2d48df19c1b4795415945) Thanks [@gcanti](https://github.com/gcanti)! - Cause: fix exception constructors (should respect `exactOptionalPropertyTypes: true` when creating `message` prop)\n\n- [#1613](https://github.com/Effect-TS/effect/pull/1613) [`2dee48696`](https://github.com/Effect-TS/effect/commit/2dee48696b70abde7dffea2a52f98dd0306f3649) Thanks [@gcanti](https://github.com/gcanti)! - Types: add Mutable helper\n\n- [#1621](https://github.com/Effect-TS/effect/pull/1621) [`33c06822d`](https://github.com/Effect-TS/effect/commit/33c06822d7b415849b29c2cd04f4b96f7e001557) Thanks [@gcanti](https://github.com/gcanti)! - SortedSet: make fromIterable dual\n\n- [#1608](https://github.com/Effect-TS/effect/pull/1608) [`a9082c91c`](https://github.com/Effect-TS/effect/commit/a9082c91c2e64864b8e8f573362f62462490a5df) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Fix off-by-one in Random.shuffle\n\n- [#1617](https://github.com/Effect-TS/effect/pull/1617) [`79719018b`](https://github.com/Effect-TS/effect/commit/79719018b327bc457a300a6b484eca58192633fb) Thanks [@gcanti](https://github.com/gcanti)! - HashMap: add entries\n\n- [#1628](https://github.com/Effect-TS/effect/pull/1628) [`ba1aa04a8`](https://github.com/Effect-TS/effect/commit/ba1aa04a8cf3ef98fb7444bcdff2196a22709736) Thanks [@gcanti](https://github.com/gcanti)! - TSet: replace toReadonlyArray with toArray\n\n- [#1625](https://github.com/Effect-TS/effect/pull/1625) [`cc9a03ac7`](https://github.com/Effect-TS/effect/commit/cc9a03ac7029b10b4fef838a3329962ad53c7936) Thanks [@gcanti](https://github.com/gcanti)! - TMap: rename reduceWithIndex / reduceWithIndexSTM to reduce / reduceSTM\n\n- [#1649](https://github.com/Effect-TS/effect/pull/1649) [`a3cda801a`](https://github.com/Effect-TS/effect/commit/a3cda801a8f8491ecc5286efa1364d9169a76aa5) Thanks [@gcanti](https://github.com/gcanti)! - interfaces: replace 0-arity functions with values\n\n- [#1625](https://github.com/Effect-TS/effect/pull/1625) [`cc9a03ac7`](https://github.com/Effect-TS/effect/commit/cc9a03ac7029b10b4fef838a3329962ad53c7936) Thanks [@gcanti](https://github.com/gcanti)! - TMap: removeIf returns `Array<[K, V]>` instead of `Array<readonly [K, V]>`\n\n- [#1642](https://github.com/Effect-TS/effect/pull/1642) [`b2fdff3b8`](https://github.com/Effect-TS/effect/commit/b2fdff3b83d566c37a499fa58f9f1492f8219e0f) Thanks [@gcanti](https://github.com/gcanti)! - TMap: merge removeIf / removeIfDiscard, retainIf / retainIf (`{ discard: boolean }` optional argument)\n\n- [#1631](https://github.com/Effect-TS/effect/pull/1631) [`af2854596`](https://github.com/Effect-TS/effect/commit/af2854596854ec6bf9e1d1dbe24535ed2a772430) Thanks [@gcanti](https://github.com/gcanti)! - Duration: refactor `between` with an `options` argument for `minimum` and `maximum` (standard)\n\n- [#1625](https://github.com/Effect-TS/effect/pull/1625) [`cc9a03ac7`](https://github.com/Effect-TS/effect/commit/cc9a03ac7029b10b4fef838a3329962ad53c7936) Thanks [@gcanti](https://github.com/gcanti)! - TMap: replace toReadonlyMap with toMap\n\n- [#1631](https://github.com/Effect-TS/effect/pull/1631) [`af2854596`](https://github.com/Effect-TS/effect/commit/af2854596854ec6bf9e1d1dbe24535ed2a772430) Thanks [@gcanti](https://github.com/gcanti)! - Duration: refactor `clamp` with an `options` argument for `minimum` and `maximum` (standard)\n\n- [#1638](https://github.com/Effect-TS/effect/pull/1638) [`4eedf057b`](https://github.com/Effect-TS/effect/commit/4eedf057b38c09ea1a6bc5b85c886edb02681d54) Thanks [@gcanti](https://github.com/gcanti)! - Predicate: exclude functions from `isRecord`\n\n- [#1645](https://github.com/Effect-TS/effect/pull/1645) [`d2e15f377`](https://github.com/Effect-TS/effect/commit/d2e15f377f55fb4a3f2114bd148f5e7eba52643a) Thanks [@tim-smart](https://github.com/tim-smart)! - add Logger.withSpanAnnotations\n\n- [#1611](https://github.com/Effect-TS/effect/pull/1611) [`8b22648aa`](https://github.com/Effect-TS/effect/commit/8b22648aa8153d31c2435c62e826e3211b2e2cd7) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure pool acquire is interruptible when allocated dynamically\n\n- [#1642](https://github.com/Effect-TS/effect/pull/1642) [`b2fdff3b8`](https://github.com/Effect-TS/effect/commit/b2fdff3b83d566c37a499fa58f9f1492f8219e0f) Thanks [@gcanti](https://github.com/gcanti)! - TSet: merge removeIf / removeIfDiscard, retainIf / retainIf (`{ discard: boolean }` optional argument)\n\n- [#1647](https://github.com/Effect-TS/effect/pull/1647) [`82006f69b`](https://github.com/Effect-TS/effect/commit/82006f69b9af9bc70a06ee1abfdc9c24777025c6) Thanks [@gcanti](https://github.com/gcanti)! - turn on exactOptionalPropertyTypes\n\n- [#1626](https://github.com/Effect-TS/effect/pull/1626) [`2e99983ef`](https://github.com/Effect-TS/effect/commit/2e99983ef3e3cf5884c831e8b25d94f4846f739a) Thanks [@gcanti](https://github.com/gcanti)! - Fix Ref Variance\n\n- [#1628](https://github.com/Effect-TS/effect/pull/1628) [`ba1aa04a8`](https://github.com/Effect-TS/effect/commit/ba1aa04a8cf3ef98fb7444bcdff2196a22709736) Thanks [@gcanti](https://github.com/gcanti)! - Chunk: add toArray\n\n- [#1619](https://github.com/Effect-TS/effect/pull/1619) [`66e6939ea`](https://github.com/Effect-TS/effect/commit/66e6939ea0f124c0a9c672ab5d8db7dc9d4ccaa2) Thanks [@gcanti](https://github.com/gcanti)! - remove readonly tuples from return type when possible\n\n- [#1631](https://github.com/Effect-TS/effect/pull/1631) [`af2854596`](https://github.com/Effect-TS/effect/commit/af2854596854ec6bf9e1d1dbe24535ed2a772430) Thanks [@gcanti](https://github.com/gcanti)! - Order: refactor `clamp` with an `options` argument for `minimum` and `maximum` (standard)\n\n- [#1628](https://github.com/Effect-TS/effect/pull/1628) [`ba1aa04a8`](https://github.com/Effect-TS/effect/commit/ba1aa04a8cf3ef98fb7444bcdff2196a22709736) Thanks [@gcanti](https://github.com/gcanti)! - TPriorityQueue: replace toArray with toChunk\n\n- [#1617](https://github.com/Effect-TS/effect/pull/1617) [`79719018b`](https://github.com/Effect-TS/effect/commit/79719018b327bc457a300a6b484eca58192633fb) Thanks [@gcanti](https://github.com/gcanti)! - SortedMap: change entries to return IterableIterator<[K, V]>\n\n- [#1644](https://github.com/Effect-TS/effect/pull/1644) [`6e2c84d4c`](https://github.com/Effect-TS/effect/commit/6e2c84d4c3b618e355b2ef9141cef973da4768b9) Thanks [@gcanti](https://github.com/gcanti)! - interfaces: add readonly modifiers when missing and remove bivariance by changing methods to props\n\n- [#1607](https://github.com/Effect-TS/effect/pull/1607) [`e7101ef05`](https://github.com/Effect-TS/effect/commit/e7101ef05125f3fc60ee5e3717eda30b6fa05c4d) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Remove potentially offenive language\n\n- [#1639](https://github.com/Effect-TS/effect/pull/1639) [`b27958bc5`](https://github.com/Effect-TS/effect/commit/b27958bc5206b4bdb5bcc0032041df6846f6ebbf) Thanks [@gcanti](https://github.com/gcanti)! - Match: fix record signature (remove any from the codomain)\n\n- [#1628](https://github.com/Effect-TS/effect/pull/1628) [`ba1aa04a8`](https://github.com/Effect-TS/effect/commit/ba1aa04a8cf3ef98fb7444bcdff2196a22709736) Thanks [@gcanti](https://github.com/gcanti)! - List: replace toReadonlyArray with toArray\n\n- [#1621](https://github.com/Effect-TS/effect/pull/1621) [`33c06822d`](https://github.com/Effect-TS/effect/commit/33c06822d7b415849b29c2cd04f4b96f7e001557) Thanks [@gcanti](https://github.com/gcanti)! - SortedMap: make fromIterable dual\n\n- [#1631](https://github.com/Effect-TS/effect/pull/1631) [`af2854596`](https://github.com/Effect-TS/effect/commit/af2854596854ec6bf9e1d1dbe24535ed2a772430) Thanks [@gcanti](https://github.com/gcanti)! - Number: refactor `between` with an `options` argument for `minimum` and `maximum` (standard)\n\n- [#1628](https://github.com/Effect-TS/effect/pull/1628) [`ba1aa04a8`](https://github.com/Effect-TS/effect/commit/ba1aa04a8cf3ef98fb7444bcdff2196a22709736) Thanks [@gcanti](https://github.com/gcanti)! - TSet: fix toChunk (was returning an array)\n\n- [#1631](https://github.com/Effect-TS/effect/pull/1631) [`af2854596`](https://github.com/Effect-TS/effect/commit/af2854596854ec6bf9e1d1dbe24535ed2a772430) Thanks [@gcanti](https://github.com/gcanti)! - Number: refactor `clamp` with an `options` argument for `minimum` and `maximum` (standard)\n\n- [#1631](https://github.com/Effect-TS/effect/pull/1631) [`af2854596`](https://github.com/Effect-TS/effect/commit/af2854596854ec6bf9e1d1dbe24535ed2a772430) Thanks [@gcanti](https://github.com/gcanti)! - BigDecimal: refactor `clamp` with an `options` argument for `minimum` and `maximum` (standard)\n\n- [#1631](https://github.com/Effect-TS/effect/pull/1631) [`af2854596`](https://github.com/Effect-TS/effect/commit/af2854596854ec6bf9e1d1dbe24535ed2a772430) Thanks [@gcanti](https://github.com/gcanti)! - BigInt: refactor `between` with an `options` argument for `minimum` and `maximum` (standard)\n\n- [#1631](https://github.com/Effect-TS/effect/pull/1631) [`af2854596`](https://github.com/Effect-TS/effect/commit/af2854596854ec6bf9e1d1dbe24535ed2a772430) Thanks [@gcanti](https://github.com/gcanti)! - BigInt: refactor `clamp` with an `options` argument for `minimum` and `maximum` (standard)\n\n- [#1617](https://github.com/Effect-TS/effect/pull/1617) [`79719018b`](https://github.com/Effect-TS/effect/commit/79719018b327bc457a300a6b484eca58192633fb) Thanks [@gcanti](https://github.com/gcanti)! - HashMap: add toEntries\n\n- [#1641](https://github.com/Effect-TS/effect/pull/1641) [`f0a4bf430`](https://github.com/Effect-TS/effect/commit/f0a4bf430c0d723e4d6e3f3fb48dcc7118338653) Thanks [@gcanti](https://github.com/gcanti)! - RedBlackTree: fix bug in Hash and Equal implementation\n\n- [#1625](https://github.com/Effect-TS/effect/pull/1625) [`cc9a03ac7`](https://github.com/Effect-TS/effect/commit/cc9a03ac7029b10b4fef838a3329962ad53c7936) Thanks [@gcanti](https://github.com/gcanti)! - TMap: fix toChunk (was returning an array)\n\n- [#1606](https://github.com/Effect-TS/effect/pull/1606) [`265f60842`](https://github.com/Effect-TS/effect/commit/265f608424c50d7bc9eac74e551db6d8db66cdb2) Thanks [@tim-smart](https://github.com/tim-smart)! - add Logger.mapInputOptions\n\n- [#1632](https://github.com/Effect-TS/effect/pull/1632) [`c86f87c1b`](https://github.com/Effect-TS/effect/commit/c86f87c1b7923ae8e66bb99d9282b35f38e16774) Thanks [@gcanti](https://github.com/gcanti)! - Either: rename `reverse` to `flip` (to align with `Effect.flip`)\n\n- [#1599](https://github.com/Effect-TS/effect/pull/1599) [`c3cb2dff7`](https://github.com/Effect-TS/effect/commit/c3cb2dff73f2e7293ab937bb6978995fb23d2547) Thanks [@gcanti](https://github.com/gcanti)! - add Refinement overloading to Effect.loop\n\n- [#1638](https://github.com/Effect-TS/effect/pull/1638) [`4eedf057b`](https://github.com/Effect-TS/effect/commit/4eedf057b38c09ea1a6bc5b85c886edb02681d54) Thanks [@gcanti](https://github.com/gcanti)! - Match: add `symbol` predicate\n\n- [#1640](https://github.com/Effect-TS/effect/pull/1640) [`9ea7edf77`](https://github.com/Effect-TS/effect/commit/9ea7edf775acc05b5a763310e6c4afecfda7a52c) Thanks [@gcanti](https://github.com/gcanti)! - fix link in \"please report an issue...\" message\n\n- [#1597](https://github.com/Effect-TS/effect/pull/1597) [`38643141d`](https://github.com/Effect-TS/effect/commit/38643141d55cdd8f47c96904a199f218bd890037) Thanks [@gcanti](https://github.com/gcanti)! - add Refinement overloading to Effect.iterate, closes #1596\n\n- [#1621](https://github.com/Effect-TS/effect/pull/1621) [`33c06822d`](https://github.com/Effect-TS/effect/commit/33c06822d7b415849b29c2cd04f4b96f7e001557) Thanks [@gcanti](https://github.com/gcanti)! - RedBlackTree: make fromIterable dual\n\n- [#1631](https://github.com/Effect-TS/effect/pull/1631) [`af2854596`](https://github.com/Effect-TS/effect/commit/af2854596854ec6bf9e1d1dbe24535ed2a772430) Thanks [@gcanti](https://github.com/gcanti)! - Order: refactor `between` with an `options` argument for `minimum` and `maximum` (standard)\n\n- [#1625](https://github.com/Effect-TS/effect/pull/1625) [`cc9a03ac7`](https://github.com/Effect-TS/effect/commit/cc9a03ac7029b10b4fef838a3329962ad53c7936) Thanks [@gcanti](https://github.com/gcanti)! - TMap: retainIf returns `Array<[K, V]>` instead of `Array<readonly [K, V]>`\n\n- [#1630](https://github.com/Effect-TS/effect/pull/1630) [`67025357e`](https://github.com/Effect-TS/effect/commit/67025357e9c705cf68d9b7e8ffb942f567720e88) Thanks [@gcanti](https://github.com/gcanti)! - Tuple: rename `tuple` to `make` (standard)\n\n- [#1628](https://github.com/Effect-TS/effect/pull/1628) [`ba1aa04a8`](https://github.com/Effect-TS/effect/commit/ba1aa04a8cf3ef98fb7444bcdff2196a22709736) Thanks [@gcanti](https://github.com/gcanti)! - TPriorityQueue: replace toReadonlyArray with toArray\n\n- [#1625](https://github.com/Effect-TS/effect/pull/1625) [`cc9a03ac7`](https://github.com/Effect-TS/effect/commit/cc9a03ac7029b10b4fef838a3329962ad53c7936) Thanks [@gcanti](https://github.com/gcanti)! - TMap: replace toReadonlyArray with toArray\n\n- [#1631](https://github.com/Effect-TS/effect/pull/1631) [`af2854596`](https://github.com/Effect-TS/effect/commit/af2854596854ec6bf9e1d1dbe24535ed2a772430) Thanks [@gcanti](https://github.com/gcanti)! - BigDecimal: refactor `between` with an `options` argument for `minimum` and `maximum` (standard)\n\n## 2.0.0-next.54\n\n### Patch Changes\n\n- [#1594](https://github.com/Effect-TS/effect/pull/1594) [`a3a31c722`](https://github.com/Effect-TS/effect/commit/a3a31c722dbf006f612f5909ff9b1a1f2d99c050) Thanks [@tim-smart](https://github.com/tim-smart)! - fix regression in process.hrtime detection\n\n## 2.0.0-next.53\n\n### Minor Changes\n\n- [#1562](https://github.com/Effect-TS/effect/pull/1562) [`0effd559e`](https://github.com/Effect-TS/effect/commit/0effd559e510a435eae98b201226515dfbc5fc2e) Thanks [@tim-smart](https://github.com/tim-smart)! - rename RequestResolver.fromFunctionEffect to fromEffect\n\n- [#1564](https://github.com/Effect-TS/effect/pull/1564) [`0eb0605b8`](https://github.com/Effect-TS/effect/commit/0eb0605b89a095242093539e70cc91976e541f83) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Isolate state by version and check for version correctness\n\n### Patch Changes\n\n- [#1586](https://github.com/Effect-TS/effect/pull/1586) [`3ed4997c6`](https://github.com/Effect-TS/effect/commit/3ed4997c667f462371f26f650ac51fe533e3c044) Thanks [@leonitousconforti](https://github.com/leonitousconforti)! - Fix List.map implementation of the index parameter and removed the index parameter from List.flatMapNonEmpty\n\n- [#1593](https://github.com/Effect-TS/effect/pull/1593) [`92f7316a2`](https://github.com/Effect-TS/effect/commit/92f7316a2f847582146c77b2b83bf65046bf0231) Thanks [@tim-smart](https://github.com/tim-smart)! - fix timeOrigin polyfill in clock\n\n- [#1568](https://github.com/Effect-TS/effect/pull/1568) [`a51fb6d80`](https://github.com/Effect-TS/effect/commit/a51fb6d80d22c912157b862432ee0ca5e0d14caa) Thanks [@tim-smart](https://github.com/tim-smart)! - add Stream.accumulate\n\n- [#1592](https://github.com/Effect-TS/effect/pull/1592) [`57d8f1792`](https://github.com/Effect-TS/effect/commit/57d8f17924e91e10617753382a91a3136043b421) Thanks [@gcanti](https://github.com/gcanti)! - Predicate: add hasProperty (+ internal refactoring to leverage it)\n\n- [#1562](https://github.com/Effect-TS/effect/pull/1562) [`0effd559e`](https://github.com/Effect-TS/effect/commit/0effd559e510a435eae98b201226515dfbc5fc2e) Thanks [@tim-smart](https://github.com/tim-smart)! - add RequestResolver.fromEffectTagged\n\n- [#1588](https://github.com/Effect-TS/effect/pull/1588) [`7c9d15c25`](https://github.com/Effect-TS/effect/commit/7c9d15c25f23f79ab4e7777a3b656119234586f9) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Fix fiber failure stack\n\n- [#1568](https://github.com/Effect-TS/effect/pull/1568) [`a51fb6d80`](https://github.com/Effect-TS/effect/commit/a51fb6d80d22c912157b862432ee0ca5e0d14caa) Thanks [@tim-smart](https://github.com/tim-smart)! - add Stream.accumulateChunks\n\n- [#1585](https://github.com/Effect-TS/effect/pull/1585) [`e0ef64102`](https://github.com/Effect-TS/effect/commit/e0ef64102b05c874e844f680f53746821609e1b6) Thanks [@gcanti](https://github.com/gcanti)! - Chunk: getEquivalence, resolve index out-of-bounds error when comparing chunks of different lengths\n\n## 2.0.0-next.52\n\n### Patch Changes\n\n- [#1565](https://github.com/Effect-TS/effect/pull/1565) [`98de6fe6e`](https://github.com/Effect-TS/effect/commit/98de6fe6e0cb89750cbc4ca795a880c56488a1e8) Thanks [@tim-smart](https://github.com/tim-smart)! - fix support for optional props in Data classes\n\n## 2.0.0-next.51\n\n### Minor Changes\n\n- [#1560](https://github.com/Effect-TS/effect/pull/1560) [`1395dc58c`](https://github.com/Effect-TS/effect/commit/1395dc58c9d1b384d22411722eff7aeeec129d36) Thanks [@tim-smart](https://github.com/tim-smart)! - use Proxy for TaggedEnum constructors\n\n### Patch Changes\n\n- [#1555](https://github.com/Effect-TS/effect/pull/1555) [`62140675c`](https://github.com/Effect-TS/effect/commit/62140675cd0b36d203b1d8fa94ea9f1732881488) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyArray / List / Chunk: merge mapNonEmpty with map\n\n- [#1559](https://github.com/Effect-TS/effect/pull/1559) [`6114c3893`](https://github.com/Effect-TS/effect/commit/6114c38936d650238172f09358e82a4af21200cb) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Avoid relying on captureStackTrace for Data.Error\n\n- [#1528](https://github.com/Effect-TS/effect/pull/1528) [`b45b7e452`](https://github.com/Effect-TS/effect/commit/b45b7e452681dfece0db4a85265c56cef149d721) Thanks [@fubhy](https://github.com/fubhy)! - Added BigDecimal module\n\n- [#1554](https://github.com/Effect-TS/effect/pull/1554) [`fe7d7c28b`](https://github.com/Effect-TS/effect/commit/fe7d7c28bb6cdbffe8af5b927e95eea8fec2d4d6) Thanks [@sukovanej](https://github.com/sukovanej)! - Fix `Struct.omit` and `Struct.pick` return types.\n\n- [#1547](https://github.com/Effect-TS/effect/pull/1547) [`c0569f8fe`](https://github.com/Effect-TS/effect/commit/c0569f8fe91707c2088adebd86562ec455a62bab) Thanks [@gcanti](https://github.com/gcanti)! - Data: improve DX (displayed types)\n\n  Previously, the displayed types of data used the Omit type to exclude certain fields.\n  This commit removes the use of Omit from the displayed types of data. This makes the types simpler and easier to understand.\n  It also enforces all fields as readonly.\n\n- [#1549](https://github.com/Effect-TS/effect/pull/1549) [`f82208687`](https://github.com/Effect-TS/effect/commit/f82208687e04fe191f8c18a56ceb10eb61376152) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Fix missing globalValue in Logger and Query\n\n- [#1557](https://github.com/Effect-TS/effect/pull/1557) [`15013f707`](https://github.com/Effect-TS/effect/commit/15013f7078358ccaf10f9a89b1d36df14b758a88) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Allow optional parameters to be used in TaggedEnum\n\n## 2.0.0-next.50\n\n### Minor Changes\n\n- [#1526](https://github.com/Effect-TS/effect/pull/1526) [`656955944`](https://github.com/Effect-TS/effect/commit/6569559440e8304c596edaaa21bcae4c8dba2568) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyRecord: remove useless alias toArray\n\n- [#1539](https://github.com/Effect-TS/effect/pull/1539) [`9c7dea219`](https://github.com/Effect-TS/effect/commit/9c7dea219ded2cb86a2a33d6ab98a629a891e365) Thanks [@tim-smart](https://github.com/tim-smart)! - remove sampled from span options\n\n- [#1530](https://github.com/Effect-TS/effect/pull/1530) [`7c3a6d59d`](https://github.com/Effect-TS/effect/commit/7c3a6d59de642a3691dff525bca981e5f6c05cd1) Thanks [@fubhy](https://github.com/fubhy)! - Change `divide` return type to `Option` and added a `unsafeDivide` operation that throws in case the divisor is `0`\n\n- [#1535](https://github.com/Effect-TS/effect/pull/1535) [`fd296a6d5`](https://github.com/Effect-TS/effect/commit/fd296a6d5206b1e4c072bad675f2f6a70b60a7f8) Thanks [@tim-smart](https://github.com/tim-smart)! - use context for tracer spans\n\n- [#1534](https://github.com/Effect-TS/effect/pull/1534) [`fb26bb770`](https://github.com/Effect-TS/effect/commit/fb26bb7707e7599a70892f06e485065e331b63e3) Thanks [@fubhy](https://github.com/fubhy)! - Removed optional math variants\n\n### Patch Changes\n\n- [#1537](https://github.com/Effect-TS/effect/pull/1537) [`9bd70154b`](https://github.com/Effect-TS/effect/commit/9bd70154b62c2f101b85a8d509e480d5281abe4b) Thanks [@patroza](https://github.com/patroza)! - fix: Either/Option gen when no yield executes, just a plain return\n\n- [#1526](https://github.com/Effect-TS/effect/pull/1526) [`656955944`](https://github.com/Effect-TS/effect/commit/6569559440e8304c596edaaa21bcae4c8dba2568) Thanks [@gcanti](https://github.com/gcanti)! - ReadonlyRecord: add missing APIs:\n  - keys\n  - values\n  - upsert\n  - update\n  - isSubrecord\n  - isSubrecordBy\n  - reduce\n  - every\n  - some\n  - union\n  - intersection\n  - difference\n  - getEquivalence\n  - singleton\n\n- [#1536](https://github.com/Effect-TS/effect/pull/1536) [`80800bfb0`](https://github.com/Effect-TS/effect/commit/80800bfb044585c836b8af585946881f2160ebb1) Thanks [@fubhy](https://github.com/fubhy)! - avoid use of bigint literals\n\n## 2.0.0-next.49\n\n### Patch Changes\n\n- [#1517](https://github.com/Effect-TS/effect/pull/1517) [`685a645b9`](https://github.com/Effect-TS/effect/commit/685a645b940f7785d8c1020eeaff1591bbb19535) Thanks [@tim-smart](https://github.com/tim-smart)! - fix off-by-one bug in Stream.fromIterable\n\n- [#1489](https://github.com/Effect-TS/effect/pull/1489) [`c2a11978f`](https://github.com/Effect-TS/effect/commit/c2a11978f9e3e7ce9df89715770a0fee564e1422) Thanks [@FedericoBiccheddu](https://github.com/FedericoBiccheddu)! - Add `Chunk.mapNonEmpty`\n\n- [#1516](https://github.com/Effect-TS/effect/pull/1516) [`ccbb23ba3`](https://github.com/Effect-TS/effect/commit/ccbb23ba3b52d6920f77d69809f46cd172be98cb) Thanks [@tim-smart](https://github.com/tim-smart)! - export Channel.suspend\n\n- [#1511](https://github.com/Effect-TS/effect/pull/1511) [`35ecb915a`](https://github.com/Effect-TS/effect/commit/35ecb915a56ff46580747f66cf69fb1b7c0c0061) Thanks [@tim-smart](https://github.com/tim-smart)! - improve Cause toJSON output\n\n- [#1489](https://github.com/Effect-TS/effect/pull/1489) [`c2a11978f`](https://github.com/Effect-TS/effect/commit/c2a11978f9e3e7ce9df89715770a0fee564e1422) Thanks [@FedericoBiccheddu](https://github.com/FedericoBiccheddu)! - Add `List.mapNonEmpty`\n\n- [#1519](https://github.com/Effect-TS/effect/pull/1519) [`43fdc45bf`](https://github.com/Effect-TS/effect/commit/43fdc45bfd9e81797b64e62af98fc9adc629151f) Thanks [@gcanti](https://github.com/gcanti)! - HashMap: add Key, Value type-level helpers\n\n- [#1525](https://github.com/Effect-TS/effect/pull/1525) [`f710599df`](https://github.com/Effect-TS/effect/commit/f710599df73d10b9b73bb1890fadd300f52829de) Thanks [@ahrjarrett](https://github.com/ahrjarrett)! - removes unnecessary type parameter from TaggedEnum\n\n- [#1521](https://github.com/Effect-TS/effect/pull/1521) [`2db755525`](https://github.com/Effect-TS/effect/commit/2db7555256e6bfd4420cb71251c386c355ded40f) Thanks [@ahrjarrett](https://github.com/ahrjarrett)! - enforce that members passed to TaggedEnum do not have a `_tag` property themselves\n\n- [#1529](https://github.com/Effect-TS/effect/pull/1529) [`df512220e`](https://github.com/Effect-TS/effect/commit/df512220ee21876621d6c966f1732477b4eac796) Thanks [@tim-smart](https://github.com/tim-smart)! - fix Channel.mergeAllWith unbounded concurrency\n\n## 2.0.0-next.48\n\n### Minor Changes\n\n- [#1484](https://github.com/Effect-TS/effect/pull/1484) [`4cdc1ebc6`](https://github.com/Effect-TS/effect/commit/4cdc1ebc6072db7e0038473b96c596759bff7601) Thanks [@fubhy](https://github.com/fubhy)! - Renamed `Bigint` to `BigInt`\n\n- [#1500](https://github.com/Effect-TS/effect/pull/1500) [`8c81e5830`](https://github.com/Effect-TS/effect/commit/8c81e58303efeb9fe408b889da6c74e3be672053) Thanks [@sukovanej](https://github.com/sukovanej)! - Allow log annotations to be any object.\n\n- [#1506](https://github.com/Effect-TS/effect/pull/1506) [`a4fbb7055`](https://github.com/Effect-TS/effect/commit/a4fbb705527aef50a27508825ceb31d69fc5f67d) Thanks [@tim-smart](https://github.com/tim-smart)! - move Effect.set\\* Layer apis to the Layer module\n\n- [#1500](https://github.com/Effect-TS/effect/pull/1500) [`8c81e5830`](https://github.com/Effect-TS/effect/commit/8c81e58303efeb9fe408b889da6c74e3be672053) Thanks [@sukovanej](https://github.com/sukovanej)! - add sampled flag to spans\n\n- [#1506](https://github.com/Effect-TS/effect/pull/1506) [`a4fbb7055`](https://github.com/Effect-TS/effect/commit/a4fbb705527aef50a27508825ceb31d69fc5f67d) Thanks [@tim-smart](https://github.com/tim-smart)! - refactor Effect span apis\n\n### Patch Changes\n\n- [#1504](https://github.com/Effect-TS/effect/pull/1504) [`f186416b9`](https://github.com/Effect-TS/effect/commit/f186416b9108a409eae23870129b1261ef2cc41c) Thanks [@kutyel](https://github.com/kutyel)! - feat: add `ap` method to `Effect`, `ap` and `zipWith` to `Either` ⚡️\n\n- [#1507](https://github.com/Effect-TS/effect/pull/1507) [`2397b5548`](https://github.com/Effect-TS/effect/commit/2397b5548b957b32acdb5baf091295babe5b36e9) Thanks [@tim-smart](https://github.com/tim-smart)! - allow message property on Data YieldableError\n\n- [#1501](https://github.com/Effect-TS/effect/pull/1501) [`4ca2abd06`](https://github.com/Effect-TS/effect/commit/4ca2abd06ee5e7c51abf77b094adab871693bdd5) Thanks [@tim-smart](https://github.com/tim-smart)! - add Match module\n\n- [#1500](https://github.com/Effect-TS/effect/pull/1500) [`8c81e5830`](https://github.com/Effect-TS/effect/commit/8c81e58303efeb9fe408b889da6c74e3be672053) Thanks [@sukovanej](https://github.com/sukovanej)! - allow tracing attributes to be unknown\n\n- [#1506](https://github.com/Effect-TS/effect/pull/1506) [`a4fbb7055`](https://github.com/Effect-TS/effect/commit/a4fbb705527aef50a27508825ceb31d69fc5f67d) Thanks [@tim-smart](https://github.com/tim-smart)! - add onEnd finalizer to Layer span apis\n\n- [#1503](https://github.com/Effect-TS/effect/pull/1503) [`6a928e49f`](https://github.com/Effect-TS/effect/commit/6a928e49f18355fdd6e82dc1b9f40f29c7aab639) Thanks [@VenomAV](https://github.com/VenomAV)! - Fix Stream.groupAdjacentBy when group spans multiple chunks\n\n- [#1500](https://github.com/Effect-TS/effect/pull/1500) [`8c81e5830`](https://github.com/Effect-TS/effect/commit/8c81e58303efeb9fe408b889da6c74e3be672053) Thanks [@sukovanej](https://github.com/sukovanej)! - add Tracer.externalSpan constructor\n\n- [#1506](https://github.com/Effect-TS/effect/pull/1506) [`a4fbb7055`](https://github.com/Effect-TS/effect/commit/a4fbb705527aef50a27508825ceb31d69fc5f67d) Thanks [@tim-smart](https://github.com/tim-smart)! - add Layer.withParentSpan api\n\n- [#1507](https://github.com/Effect-TS/effect/pull/1507) [`2397b5548`](https://github.com/Effect-TS/effect/commit/2397b5548b957b32acdb5baf091295babe5b36e9) Thanks [@tim-smart](https://github.com/tim-smart)! - add name getter to YieldableError\n\n## 2.0.0-next.47\n\n### Minor Changes\n\n- [#1495](https://github.com/Effect-TS/effect/pull/1495) [`01c479f0c`](https://github.com/Effect-TS/effect/commit/01c479f0c86d99344c0a5625bdc2c5564915d512) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Support rendezvous-like behaviour in Queue.bounded\n\n## 2.0.0-next.46\n\n### Minor Changes\n\n- [#1483](https://github.com/Effect-TS/effect/pull/1483) [`e68453bf4`](https://github.com/Effect-TS/effect/commit/e68453bf457f32502e5cd47273c298fb24f2feb0) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Include stack in Data.Error/Data.TaggedError\n\n- [#1483](https://github.com/Effect-TS/effect/pull/1483) [`e68453bf4`](https://github.com/Effect-TS/effect/commit/e68453bf457f32502e5cd47273c298fb24f2feb0) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Include Error module in Data\n\n### Patch Changes\n\n- [#1487](https://github.com/Effect-TS/effect/pull/1487) [`bd1748406`](https://github.com/Effect-TS/effect/commit/bd17484068436d0b605c179e47ad63cdbdfb39b0) Thanks [@fubhy](https://github.com/fubhy)! - Added bigint math functions for `abs`, `sqrt`, `lcm` and `gcd`\n\n- [#1491](https://github.com/Effect-TS/effect/pull/1491) [`6ff77385c`](https://github.com/Effect-TS/effect/commit/6ff77385c43e049fc864719574ced3691969c3f8) Thanks [@tim-smart](https://github.com/tim-smart)! - fix Layer.withSpan optional args\n\n- [#1492](https://github.com/Effect-TS/effect/pull/1492) [`471b5172b`](https://github.com/Effect-TS/effect/commit/471b5172bda5d29c4104414b4017f36a45b431c7) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure more failures are annotated with spans\n\n## 2.0.0-next.45\n\n### Patch Changes\n\n- [#1465](https://github.com/Effect-TS/effect/pull/1465) [`10a8fb9fe`](https://github.com/Effect-TS/effect/commit/10a8fb9fe513b219e678da71ebe80ce7ce61dd68) Thanks [@tim-smart](https://github.com/tim-smart)! - add incremental only counters\n\n- [#1472](https://github.com/Effect-TS/effect/pull/1472) [`1c56aa9c1`](https://github.com/Effect-TS/effect/commit/1c56aa9c1b267faea5f48e0f126cac579c30ae24) Thanks [@tim-smart](https://github.com/tim-smart)! - switch to build-utils prepare-v1\n\n- [#1480](https://github.com/Effect-TS/effect/pull/1480) [`c31de5410`](https://github.com/Effect-TS/effect/commit/c31de54105a42a7d27f5db797f1993b463fd7b66) Thanks [@tim-smart](https://github.com/tim-smart)! - refactor Effectable and Streamable public api\n\n- [#1463](https://github.com/Effect-TS/effect/pull/1463) [`8932e9b26`](https://github.com/Effect-TS/effect/commit/8932e9b264f85233069407e884b951bc87c159d4) Thanks [@gcanti](https://github.com/gcanti)! - Rename Hub to PubSub, closes #1462\n\n- [#1455](https://github.com/Effect-TS/effect/pull/1455) [`c3e99ce56`](https://github.com/Effect-TS/effect/commit/c3e99ce5677ba0092e598624f7234d489f48e131) Thanks [@TylorS](https://github.com/TylorS)! - add Streamable for creating custom Streams\n\n- [#1465](https://github.com/Effect-TS/effect/pull/1465) [`10a8fb9fe`](https://github.com/Effect-TS/effect/commit/10a8fb9fe513b219e678da71ebe80ce7ce61dd68) Thanks [@tim-smart](https://github.com/tim-smart)! - add bigint counter & gauge metrics\n\n- [#1473](https://github.com/Effect-TS/effect/pull/1473) [`6c967c9bc`](https://github.com/Effect-TS/effect/commit/6c967c9bc7c6279af201ea205432d62b2a1764be) Thanks [@tim-smart](https://github.com/tim-smart)! - support records in Effect.tagMetrics\n\n- [#1480](https://github.com/Effect-TS/effect/pull/1480) [`c31de5410`](https://github.com/Effect-TS/effect/commit/c31de54105a42a7d27f5db797f1993b463fd7b66) Thanks [@tim-smart](https://github.com/tim-smart)! - expose Effect prototype objects in Effectable module\n\n## 2.0.0-next.44\n\n### Patch Changes\n\n- [#1469](https://github.com/Effect-TS/effect/pull/1469) [`5a217ac18`](https://github.com/Effect-TS/effect/commit/5a217ac1842252636d4e529baa191ea0778e42ce) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Fix yield loop\n\n## 2.0.0-next.43\n\n### Patch Changes\n\n- [#1467](https://github.com/Effect-TS/effect/pull/1467) [`7e258a9c1`](https://github.com/Effect-TS/effect/commit/7e258a9c1fabeeb9319cb50655a0221bd1e38ac8) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Attempt at resolving TS issue with module discovery\n\n## 2.0.0-next.42\n\n### Patch Changes\n\n- [#1466](https://github.com/Effect-TS/effect/pull/1466) [`31c4068fe`](https://github.com/Effect-TS/effect/commit/31c4068fe830797162c554a57ec3e6cec8c4a834) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure all fiber refs are wrapped with globalValue\n\n- [#1459](https://github.com/Effect-TS/effect/pull/1459) [`e8fb7f73b`](https://github.com/Effect-TS/effect/commit/e8fb7f73bd3cbdb663585de1d8d3b196a9cbec98) Thanks [@fubhy](https://github.com/fubhy)! - Fix binding issue in timeout module\n\n- [#1466](https://github.com/Effect-TS/effect/pull/1466) [`31c4068fe`](https://github.com/Effect-TS/effect/commit/31c4068fe830797162c554a57ec3e6cec8c4a834) Thanks [@tim-smart](https://github.com/tim-smart)! - fix comparisons by reference\n\n- [#1461](https://github.com/Effect-TS/effect/pull/1461) [`90210ba28`](https://github.com/Effect-TS/effect/commit/90210ba28a6b078087a4d4c7b26b1b578e920476) Thanks [@gcanti](https://github.com/gcanti)! - Error: rename Tagged to TaggedClass (to align with the naming convention in the Data module)\n\n## 2.0.0-next.41\n\n### Patch Changes\n\n- [#1456](https://github.com/Effect-TS/effect/pull/1456) [`4bc30e5ff`](https://github.com/Effect-TS/effect/commit/4bc30e5ff0db46f7920cedeb9254bb09c50a5875) Thanks [@tim-smart](https://github.com/tim-smart)! - re-add types field to exports in package.json\n\n## 2.0.0-next.40\n\n### Patch Changes\n\n- [#1454](https://github.com/Effect-TS/effect/pull/1454) [`0a9afd299`](https://github.com/Effect-TS/effect/commit/0a9afd299aeb265f09d46f203294db5d970cf903) Thanks [@tim-smart](https://github.com/tim-smart)! - add Layer.withSpan\n\n- [#1451](https://github.com/Effect-TS/effect/pull/1451) [`44ea13d9c`](https://github.com/Effect-TS/effect/commit/44ea13d9c7dc57b94b1fe73984b0a62a05994cfe) Thanks [@fubhy](https://github.com/fubhy)! - Move types export condition to the top\n\n## 2.0.0-next.39\n\n### Patch Changes\n\n- [#1446](https://github.com/Effect-TS/effect/pull/1446) [`3f6f23149`](https://github.com/Effect-TS/effect/commit/3f6f23149d50ac63b94bbf452353156899750f7c) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Add sideEffects to package json\n\n- [#1445](https://github.com/Effect-TS/effect/pull/1445) [`52626a538`](https://github.com/Effect-TS/effect/commit/52626a538693be17667d9f5d28b632215d0e714f) Thanks [@gcanti](https://github.com/gcanti)! - Duration: add toSeconds\n\n- [#1450](https://github.com/Effect-TS/effect/pull/1450) [`713337c7c`](https://github.com/Effect-TS/effect/commit/713337c7c8eb55e50dcfe538c40dace280aee3f8) Thanks [@fubhy](https://github.com/fubhy)! - Hotfix type condition in package.json exports\n\n- [#1449](https://github.com/Effect-TS/effect/pull/1449) [`8f74d671d`](https://github.com/Effect-TS/effect/commit/8f74d671db4018156831e8305876360ec7d1ee3f) Thanks [@tim-smart](https://github.com/tim-smart)! - add preserveModules patch for preconstruct\n\n## 2.0.0-next.38\n\n### Patch Changes\n\n- [#1442](https://github.com/Effect-TS/effect/pull/1442) [`c5e4a2390`](https://github.com/Effect-TS/effect/commit/c5e4a2390168b335307004a6e5623e53bd22734e) Thanks [@tim-smart](https://github.com/tim-smart)! - add top level exports from Function\n\n## 2.0.0-next.37\n\n### Minor Changes\n\n- [#1434](https://github.com/Effect-TS/effect/pull/1434) [`61b95aefe`](https://github.com/Effect-TS/effect/commit/61b95aefede7c01e00aa05e56b5f65c11736a4fd) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Switch on \\_op to allow for yieldable tagged errors\n\n- [#1434](https://github.com/Effect-TS/effect/pull/1434) [`61b95aefe`](https://github.com/Effect-TS/effect/commit/61b95aefede7c01e00aa05e56b5f65c11736a4fd) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Unify ecosystem packages\n\n### Patch Changes\n\n- [#1434](https://github.com/Effect-TS/effect/pull/1434) [`61b95aefe`](https://github.com/Effect-TS/effect/commit/61b95aefede7c01e00aa05e56b5f65c11736a4fd) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - add Error module for creating error classes\n\n- [#1434](https://github.com/Effect-TS/effect/pull/1434) [`61b95aefe`](https://github.com/Effect-TS/effect/commit/61b95aefede7c01e00aa05e56b5f65c11736a4fd) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - add Effectable module for creating custom Effect's\n\n## 2.0.0-next.36\n\n### Patch Changes\n\n- [#1436](https://github.com/Effect-TS/effect/pull/1436) [`f7cb1b8be`](https://github.com/Effect-TS/effect/commit/f7cb1b8be7dd961cbe7def7210bfac876c7f95db) Thanks [@fubhy](https://github.com/fubhy)! - update dependencies\n\n## 2.0.0-next.35\n\n### Patch Changes\n\n- [#1435](https://github.com/Effect-TS/effect/pull/1435) [`f197821b7`](https://github.com/Effect-TS/effect/commit/f197821b7faa3796a861f4c2d14ce6605ba12234) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n- [#1432](https://github.com/Effect-TS/effect/pull/1432) [`b8b11c5a5`](https://github.com/Effect-TS/effect/commit/b8b11c5a5aee53e880d6f205fc19027b771966f0) Thanks [@gcanti](https://github.com/gcanti)! - move FiberRefsPatch from FiberRefs module to its own module\n\n## 2.0.0-next.34\n\n### Patch Changes\n\n- [#1428](https://github.com/Effect-TS/effect/pull/1428) [`d77e66834`](https://github.com/Effect-TS/effect/commit/d77e668346db402374e9a28a5f00840e75679387) Thanks [@gcanti](https://github.com/gcanti)! - expose /stm THub module\n\n## 2.0.0-next.33\n\n### Patch Changes\n\n- [#1426](https://github.com/Effect-TS/effect/pull/1426) [`92af22066`](https://github.com/Effect-TS/effect/commit/92af220665261946a440b62e283e3772e4c5fa72) Thanks [@tim-smart](https://github.com/tim-smart)! - expose /data GlobalValue & Types modules\n\n## 2.0.0-next.32\n\n### Patch Changes\n\n- [#1422](https://github.com/Effect-TS/effect/pull/1422) [`89759cc0c`](https://github.com/Effect-TS/effect/commit/89759cc0c934248ae3ecb0c394f5b1e0917b423f) Thanks [@gcanti](https://github.com/gcanti)! - update dependencies\n\n## 2.0.0-next.31\n\n### Patch Changes\n\n- [#1419](https://github.com/Effect-TS/effect/pull/1419) [`543dfb495`](https://github.com/Effect-TS/effect/commit/543dfb495c7cfd4799b27e0623d547cf0341a838) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 2.0.0-next.30\n\n### Patch Changes\n\n- [#1416](https://github.com/Effect-TS/effect/pull/1416) [`f464fb494`](https://github.com/Effect-TS/effect/commit/f464fb4948aec38621ca20d824d542980bc250f5) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 2.0.0-next.29\n\n### Patch Changes\n\n- [#1412](https://github.com/Effect-TS/effect/pull/1412) [`93f4c9f9a`](https://github.com/Effect-TS/effect/commit/93f4c9f9ab1da2bfe37a439383bb14d861441ea4) Thanks [@tim-smart](https://github.com/tim-smart)! - update peer deps\n\n## 2.0.0-next.28\n\n### Patch Changes\n\n- [#1410](https://github.com/Effect-TS/effect/pull/1410) [`a8ffb5fb9`](https://github.com/Effect-TS/effect/commit/a8ffb5fb9a4a4decc44dce811356136542813af0) Thanks [@tim-smart](https://github.com/tim-smart)! - update @effect/match\n\n## 2.0.0-next.27\n\n### Patch Changes\n\n- [#1408](https://github.com/Effect-TS/effect/pull/1408) [`a6b9f4f01`](https://github.com/Effect-TS/effect/commit/a6b9f4f01892c3cdc6ce56fa3a47c051b0064629) Thanks [@tim-smart](https://github.com/tim-smart)! - update /match\n\n## 2.0.0-next.26\n\n### Patch Changes\n\n- [#1404](https://github.com/Effect-TS/effect/pull/1404) [`6441df29e`](https://github.com/Effect-TS/effect/commit/6441df29ede8a8d33398fff4ae44d141741c64f9) Thanks [@tim-smart](https://github.com/tim-smart)! - expose Console module\n\n## 2.0.0-next.25\n\n### Patch Changes\n\n- [#1402](https://github.com/Effect-TS/effect/pull/1402) [`0844367c5`](https://github.com/Effect-TS/effect/commit/0844367c546184dd9105a3394fc019ed9ad0199e) Thanks [@tim-smart](https://github.com/tim-smart)! - use dependencies + peerDependencies for packages\n\n## 2.0.0-next.24\n\n### Minor Changes\n\n- [#1395](https://github.com/Effect-TS/effect/pull/1395) [`aecaeb88c`](https://github.com/Effect-TS/effect/commit/aecaeb88c5cc58da18e0291cdefdf3a30a14a759) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n### Patch Changes\n\n- [#1395](https://github.com/Effect-TS/effect/pull/1395) [`aecaeb88c`](https://github.com/Effect-TS/effect/commit/aecaeb88c5cc58da18e0291cdefdf3a30a14a759) Thanks [@tim-smart](https://github.com/tim-smart)! - switch to using peerDependencies\n\n- [#1397](https://github.com/Effect-TS/effect/pull/1397) [`9ffd45ba7`](https://github.com/Effect-TS/effect/commit/9ffd45ba78b989d704b0d23691a7afdd758a8674) Thanks [@tim-smart](https://github.com/tim-smart)! - switch to @effect/build-utils and @effect/eslint-plugin\n\n## 2.0.0-next.23\n\n### Patch Changes\n\n- [#1393](https://github.com/Effect-TS/effect/pull/1393) [`db1f1e677`](https://github.com/Effect-TS/effect/commit/db1f1e677570045126c15b0a5158866f2233363a) Thanks [@tim-smart](https://github.com/tim-smart)! - update packages\n\n## 2.0.0-next.22\n\n### Patch Changes\n\n- [#1389](https://github.com/Effect-TS/effect/pull/1389) [`02703a5c7`](https://github.com/Effect-TS/effect/commit/02703a5c7959692d61dbea734bb84b4e4b48c10e) Thanks [@tim-smart](https://github.com/tim-smart)! - update packages\n\n## 2.0.0-next.21\n\n### Patch Changes\n\n- [#1387](https://github.com/Effect-TS/effect/pull/1387) [`83401b13a`](https://github.com/Effect-TS/effect/commit/83401b13a98b4b961a3257d21feef0b5978cbf7e) Thanks [@tim-smart](https://github.com/tim-smart)! - update /stream\n\n## 2.0.0-next.20\n\n### Patch Changes\n\n- [#1385](https://github.com/Effect-TS/effect/pull/1385) [`a53697e15`](https://github.com/Effect-TS/effect/commit/a53697e1532f330d1a653332ec3fd1d74188efbf) Thanks [@tim-smart](https://github.com/tim-smart)! - add /stm, /stream and /match\n\n## 2.0.0-next.19\n\n### Minor Changes\n\n- [#1383](https://github.com/Effect-TS/effect/pull/1383) [`d9c229a87`](https://github.com/Effect-TS/effect/commit/d9c229a87133847b596f3ed2871904bb8ad90fb2) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io and /data\n\n## 2.0.0-next.18\n\n### Patch Changes\n\n- [#1381](https://github.com/Effect-TS/effect/pull/1381) [`bf5ebae41`](https://github.com/Effect-TS/effect/commit/bf5ebae41d4851bf2cd6228c6244ac268c20c92f) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io\n\n## 2.0.0-next.17\n\n### Patch Changes\n\n- [#1379](https://github.com/Effect-TS/effect/pull/1379) [`2e9b54d03`](https://github.com/Effect-TS/effect/commit/2e9b54d0393c3f3c7e63ba2d6507d36074be0b51) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io and /data\n\n## 2.0.0-next.16\n\n### Patch Changes\n\n- [#1376](https://github.com/Effect-TS/effect/pull/1376) [`f356fa23d`](https://github.com/Effect-TS/effect/commit/f356fa23d8dc075781432ce336ea0ed748cf8131) Thanks [@gcanti](https://github.com/gcanti)! - add Config/\\* modules\n\n## 2.0.0-next.15\n\n### Patch Changes\n\n- [#1374](https://github.com/Effect-TS/effect/pull/1374) [`37cb95bfd`](https://github.com/Effect-TS/effect/commit/37cb95bfd33bda273d30f62b3176bf410684ae96) Thanks [@gcanti](https://github.com/gcanti)! - remove fast-check from deps\n\n## 2.0.0-next.14\n\n### Patch Changes\n\n- [#1372](https://github.com/Effect-TS/effect/pull/1372) [`1322363d5`](https://github.com/Effect-TS/effect/commit/1322363d59ddca50b72758da47a1ef8b48a53bcc) Thanks [@gcanti](https://github.com/gcanti)! - upgrade to latest versions\n\n## 2.0.0-next.13\n\n### Patch Changes\n\n- [#1360](https://github.com/Effect-TS/effect/pull/1360) [`fef698b15`](https://github.com/Effect-TS/effect/commit/fef698b151dba7a4f9598a452cf6acbd1bee7567) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Elect selected modules to main export\n\n## 2.0.0-next.12\n\n### Patch Changes\n\n- [#1358](https://github.com/Effect-TS/effect/pull/1358) [`54152d7af`](https://github.com/Effect-TS/effect/commit/54152d7af3cf188b4e550d2e1879c0fe18ea2de7) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Restructure package\n\n## 2.0.0-next.11\n\n### Patch Changes\n\n- [#1356](https://github.com/Effect-TS/effect/pull/1356) [`9fcc559d2`](https://github.com/Effect-TS/effect/commit/9fcc559d2206fed5eeb44dd604d7cb3ed7c8465c) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update release\n\n## 2.0.0-next.10\n\n### Patch Changes\n\n- [#1353](https://github.com/Effect-TS/effect/pull/1353) [`6285a7712`](https://github.com/Effect-TS/effect/commit/6285a7712b0fd630f5031fec360eb42a68d9b788) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update @effect/io\n\n## 2.0.0-next.9\n\n### Patch Changes\n\n- [#1352](https://github.com/Effect-TS/effect/pull/1352) [`5220362c9`](https://github.com/Effect-TS/effect/commit/5220362c993fcd655229d90fdaf2a740c216b189) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update dependencies\n\n- [#1350](https://github.com/Effect-TS/effect/pull/1350) [`b18068ebe`](https://github.com/Effect-TS/effect/commit/b18068ebe8ba1c1ceebbd0ec088bd3587c318b29) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update @effect/io and remove LogLevel isolation\n\n## 2.0.0-next.8\n\n### Patch Changes\n\n- [#1348](https://github.com/Effect-TS/effect/pull/1348) [`a789742bd`](https://github.com/Effect-TS/effect/commit/a789742bd5ef48e3023f3e47499ee11e9874501e) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Isolate LogLevel export\n\n## 2.0.0-next.7\n\n### Patch Changes\n\n- [#1346](https://github.com/Effect-TS/effect/pull/1346) [`2d6cdbc2a`](https://github.com/Effect-TS/effect/commit/2d6cdbc2a842b25e56136735953e32f851094d74) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Add Logger extensions\n\n## 2.0.0-next.6\n\n### Patch Changes\n\n- [#1344](https://github.com/Effect-TS/effect/pull/1344) [`aa550d9f9`](https://github.com/Effect-TS/effect/commit/aa550d9f9eb743ce4f6f1d7902374855b57cffe8) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update @effect/io\n\n## 2.0.0-next.5\n\n### Patch Changes\n\n- [#1342](https://github.com/Effect-TS/effect/pull/1342) [`2c8c14f7c`](https://github.com/Effect-TS/effect/commit/2c8c14f7c9a6ca03ed38f52e9a78774403cbf8bd) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update @effect/io\n\n## 2.0.0-next.4\n\n### Patch Changes\n\n- [#1339](https://github.com/Effect-TS/effect/pull/1339) [`aabfb1d0f`](https://github.com/Effect-TS/effect/commit/aabfb1d0fc348ad70c83706fae8c84d8cd81017f) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update @effect/io\n\n- [#1341](https://github.com/Effect-TS/effect/pull/1341) [`a2b0eca61`](https://github.com/Effect-TS/effect/commit/a2b0eca6118d895746bc178e83dfe8cba0ef5edb) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Add Optic Re-Export\n\n## 2.0.0-next.3\n\n### Patch Changes\n\n- [#1337](https://github.com/Effect-TS/effect/pull/1337) [`4f805f5c1`](https://github.com/Effect-TS/effect/commit/4f805f5c1f7306c8af144a9a5d888121c0a1488d) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update docs\n\n## 2.0.0-next.2\n\n### Patch Changes\n\n- [#1333](https://github.com/Effect-TS/effect/pull/1333) [`b3dac7e1b`](https://github.com/Effect-TS/effect/commit/b3dac7e1be152b0882340bc57866bc8ce0a3eb47) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update repo in package.json\n\n- [#1335](https://github.com/Effect-TS/effect/pull/1335) [`3c7d4f2e4`](https://github.com/Effect-TS/effect/commit/3c7d4f2e440f2076b02f0dc985f598808b54b358) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update docs\n\n## 2.0.0-next.1\n\n### Patch Changes\n\n- [#1330](https://github.com/Effect-TS/core/pull/1330) [`75780dea1`](https://github.com/Effect-TS/core/commit/75780dea16555c8eef8053d3cd167a60cdd2e1d9) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update dependencies\n\n## 2.0.0-next.0\n\n### Major Changes\n\n- [#1321](https://github.com/Effect-TS/core/pull/1321) [`315a3ab42`](https://github.com/Effect-TS/core/commit/315a3ab42e626ef31fd0336214416cad86131654) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Bootstrap Ecosystem Package\n\n### Patch Changes\n\n- [#1329](https://github.com/Effect-TS/core/pull/1329) [`b015fdac5`](https://github.com/Effect-TS/core/commit/b015fdac5d9db44bae189e216a8d68b6739d8015) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Update to @effect/io@0.0.9\n\n- [#1324](https://github.com/Effect-TS/core/pull/1324) [`74fa4086e`](https://github.com/Effect-TS/core/commit/74fa4086e5b26c5f20706a3209e6c8345e187bcc) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Isolate Debug\n\n- [#1326](https://github.com/Effect-TS/core/pull/1326) [`edc131f65`](https://github.com/Effect-TS/core/commit/edc131f65d71b751f4f2dd4b46acd1fbef5f9804) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Add Remaining Effect Re-Exports\n\n- [#1323](https://github.com/Effect-TS/core/pull/1323) [`7f57f59de`](https://github.com/Effect-TS/core/commit/7f57f59deabfe6d2c06afd56ffc79bb22758290b) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Add fp-ts/data re-exports\n\n- [#1325](https://github.com/Effect-TS/core/pull/1325) [`52dacbf72`](https://github.com/Effect-TS/core/commit/52dacbf7252f0bfcbd9ed01b93bc0b26f0440da4) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Add fp-ts/core Re-Exports\n"
  },
  {
    "path": "packages/effect/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Effectful Technologies Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/effect/README.md",
    "content": "# `effect` Core Package\n\nThe `effect` package is the heart of the Effect framework, providing robust primitives for managing side effects, ensuring type safety, and supporting concurrency in your TypeScript applications.\n\n## Requirements\n\n- **TypeScript 5.4 or Newer:**\n  Ensure you are using a compatible TypeScript version.\n\n- **Strict Type-Checking:**\n  The `strict` flag must be enabled in your `tsconfig.json`. For example:\n\n  ```json\n  {\n    \"compilerOptions\": {\n      \"strict\": true\n      // ...other options\n    }\n  }\n  ```\n\n## Installation\n\nInstall the core package using your preferred package manager. For example, with npm:\n\n```bash\nnpm install effect\n```\n\n## Documentation\n\n- **Website:**\n  For detailed information and usage examples, visit the [Effect website](https://www.effect.website/).\n\n- **API Reference:**\n  For a complete API reference of the core package `effect`, see the [Effect API documentation](https://effect-ts.github.io/effect/).\n\n## Overview of Effect Modules\n\nThe `effect` package provides a collection of modules designed for functional programming in TypeScript. Below is a brief overview of the core modules:\n\n| Module   | Description                                                                                                                |\n| -------- | -------------------------------------------------------------------------------------------------------------------------- |\n| Effect   | The core abstraction for managing side effects, concurrency, and error handling in a structured way.                       |\n| Context  | A lightweight dependency injection mechanism that enables passing services through computations without direct references. |\n| Layer    | A system for managing dependencies, allowing for modular and composable resource allocation.                               |\n| Fiber    | Lightweight virtual threads with resource-safe cancellation capabilities, enabling many features in Effect.                |\n| Stream   | A powerful abstraction for handling asynchronous, event-driven data processing.                                            |\n| Schedule | A module for defining retry and repeat policies with composable schedules.                                                 |\n| Scope    | Manages the lifecycle of resources, ensuring proper acquisition and release.                                               |\n| Schema   | A powerful library for defining, validating, and transforming structured data with type-safe encoding and decoding.        |\n\nFor a comparison between `effect/Schema` and `zod`, see [Schema vs Zod](https://github.com/Effect-TS/effect/tree/main/packages/effect/schema-vs-zod.md).\n"
  },
  {
    "path": "packages/effect/benchmark/SchemaArray.ts",
    "content": "import * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport { Bench } from \"tinybench\"\n\n/*\n┌─────────┬──────────────────────────────────────────┬─────────────┬───────────────────┬──────────┬─────────┐\n│ (index) │ Task Name                                │ ops/sec     │ Average Time (ns) │ Margin   │ Samples │\n├─────────┼──────────────────────────────────────────┼─────────────┼───────────────────┼──────────┼─────────┤\n│ 0       │ 'Schema.decodeUnknownEither (good)'      │ '3,390,518' │ 294.9401324693781 │ '±0.32%' │ 3390519 │\n│ 1       │ 'ParseResult.decodeUnknownEither (good)' │ '3,388,065' │ 295.1536946952488 │ '±0.27%' │ 3388087 │\n│ 2       │ 'Schema.decodeUnknownEither (bad)'       │ '228,525'   │ 4375.873939945003 │ '±0.13%' │ 228526  │\n│ 3       │ 'ParseResult.decodeUnknownEither (bad)'  │ '3,236,794' │ 308.9476420349623 │ '±0.30%' │ 3236795 │\n└─────────┴──────────────────────────────────────────┴─────────────┴───────────────────┴──────────┴─────────┘\n*/\n\nconst bench = new Bench({ time: 1000 })\n\nconst schema = S.Array(S.String)\n\nconst good = [\"a\", \"b\", \"c\"]\n\nconst bad = [\"a\", 2, \"c\"]\n\nconst schemaDecodeUnknownEither = S.decodeUnknownEither(schema)\nconst parseResultDecodeUnknownEither = ParseResult.decodeUnknownEither(schema)\nconst options: ParseOptions = { errors: \"all\" }\n\nbench\n  .add(\"Schema.decodeUnknownEither (good)\", function() {\n    schemaDecodeUnknownEither(good, options)\n  })\n  .add(\"ParseResult.decodeUnknownEither (good)\", function() {\n    parseResultDecodeUnknownEither(good, options)\n  })\n  .add(\"Schema.decodeUnknownEither (bad)\", function() {\n    schemaDecodeUnknownEither(bad, options)\n  })\n  .add(\"ParseResult.decodeUnknownEither (bad)\", function() {\n    parseResultDecodeUnknownEither(bad, options)\n  })\n\nawait bench.run()\n\nconsole.table(bench.table())\n"
  },
  {
    "path": "packages/effect/benchmark/SchemaFilters.ts",
    "content": "import * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport { Bench } from \"tinybench\"\nimport { z } from \"zod\"\n\n/*\n┌─────────┬──────────────────────────────────────────┬─────────────┬────────────────────┬──────────┬─────────┐\n│ (index) │ Task Name                                │ ops/sec     │ Average Time (ns)  │ Margin   │ Samples │\n├─────────┼──────────────────────────────────────────┼─────────────┼────────────────────┼──────────┼─────────┤\n│ 0       │ 'Schema.decodeUnknownEither (good)'      │ '178,340'   │ 5607.258022552317  │ '±0.39%' │ 178341  │\n│ 1       │ 'ParseResult.decodeUnknownEither (good)' │ '178,705'   │ 5595.811024811139  │ '±0.15%' │ 178706  │\n│ 2       │ 'zod (good)'                             │ '1,745,923' │ 572.7628212909881  │ '±0.41%' │ 1745924 │\n│ 3       │ 'Schema.decodeUnknownEither (bad)'       │ '103,361'   │ 9674.739442547396  │ '±0.13%' │ 103363  │\n│ 4       │ 'ParseResult.decodeUnknownEither (bad)'  │ '187,992'   │ 5319.374051161494  │ '±0.23%' │ 187993  │\n│ 5       │ 'zod (bad)'                              │ '471,637'   │ 2120.2705459049216 │ '±2.25%' │ 471639  │\n└─────────┴──────────────────────────────────────────┴─────────────┴────────────────────┴──────────┴─────────┘\n*/\n\nconst bench = new Bench({ time: 1000 })\n\nconst UserZod = z.object({\n  name: z.string().min(3).max(20),\n  age: z.number().min(0).max(120),\n  address: z.object({\n    street: z.string().min(3).max(200),\n    number: z.number().min(0).max(120),\n    city: z.string().min(3).max(200),\n    country: z.string().min(3).max(200),\n    zip: z.string().min(3).max(200)\n  })\n})\n\nconst schema = S.Struct({\n  name: S.String.pipe(S.minLength(3), S.maxLength(20)),\n  age: S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(120)),\n  address: S.Struct({\n    street: S.String.pipe(S.minLength(3), S.maxLength(200)),\n    number: S.Number.pipe(S.greaterThanOrEqualTo(0), S.lessThanOrEqualTo(120)),\n    city: S.String.pipe(S.minLength(3), S.maxLength(200)),\n    country: S.String.pipe(S.minLength(3), S.maxLength(200)),\n    zip: S.String.pipe(S.minLength(3), S.maxLength(200))\n  })\n})\n\nconst good = {\n  name: \"Joe\",\n  age: 13,\n  address: {\n    street: \"Main Street\",\n    number: 12,\n    city: \"New York\",\n    country: \"USA\",\n    zip: \"12345\"\n  }\n}\n\nconst bad = {\n  name: \"Jo\",\n  age: 13,\n  address: {\n    street: \"Main Street\",\n    number: 12,\n    city: \"New York\",\n    country: \"USA\",\n    zip: \"12345\"\n  }\n}\n\nconst schemaDecodeUnknownEither = S.decodeUnknownEither(schema)\nconst parseResultDecodeUnknownEither = ParseResult.decodeUnknownEither(schema)\nconst options: ParseOptions = { errors: \"all\" }\n\nbench\n  .add(\"Schema.decodeUnknownEither (good)\", function() {\n    schemaDecodeUnknownEither(good, options)\n  })\n  .add(\"ParseResult.decodeUnknownEither (good)\", function() {\n    parseResultDecodeUnknownEither(good, options)\n  })\n  .add(\"zod (good)\", function() {\n    UserZod.safeParse(good)\n  })\n  .add(\"Schema.decodeUnknownEither (bad)\", function() {\n    schemaDecodeUnknownEither(bad, options)\n  })\n  .add(\"ParseResult.decodeUnknownEither (bad)\", function() {\n    parseResultDecodeUnknownEither(bad, options)\n  })\n  .add(\"zod (bad)\", function() {\n    UserZod.safeParse(bad)\n  })\n\nawait bench.run()\n\nconsole.table(bench.table())\n"
  },
  {
    "path": "packages/effect/benchmark/SchemaIndex.ts",
    "content": "import * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport { Bench } from \"tinybench\"\nimport { z } from \"zod\"\n\n/*\n┌─────────┬──────────────────────────────────────────┬───────────┬────────────────────┬──────────┬─────────┐\n│ (index) │ Task Name                                │ ops/sec   │ Average Time (ns)  │ Margin   │ Samples │\n├─────────┼──────────────────────────────────────────┼───────────┼────────────────────┼──────────┼─────────┤\n│ 0       │ 'Schema.decodeUnknownEither (good)'      │ '509,149' │ 1964.061260925078  │ '±1.79%' │ 509150  │\n│ 1       │ 'ParseResult.decodeUnknownEither (good)' │ '533,211' │ 1875.429060111383  │ '±0.29%' │ 533212  │\n│ 2       │ 'zod (good)'                             │ '678,945' │ 1472.8725318364138 │ '±0.25%' │ 678946  │\n│ 3       │ 'Schema.decodeUnknownEither (bad)'       │ '150,067' │ 6663.685855746499  │ '±0.15%' │ 150068  │\n│ 4       │ 'ParseResult.decodeUnknownEither (bad)'  │ '435,462' │ 2296.4078417675796 │ '±0.32%' │ 435463  │\n│ 5       │ 'zod (bad)'                              │ '252,755' │ 3956.3951281064533 │ '±2.17%' │ 252756  │\n└─────────┴──────────────────────────────────────────┴───────────┴────────────────────┴──────────┴─────────┘\n*/\n\nconst bench = new Bench({ time: 1000 })\n\nconst Vector = S.Tuple(S.Number, S.Number, S.Number)\nconst VectorZod = z.tuple([z.number(), z.number(), z.number()])\n\nconst Asteroid = S.Struct({\n  type: S.Literal(\"asteroid\"),\n  location: Vector,\n  mass: S.Number\n})\nconst AsteroidZod = z.object({\n  type: z.literal(\"asteroid\"),\n  location: VectorZod,\n  mass: z.number()\n})\n\nconst Planet = S.Struct({\n  type: S.Literal(\"planet\"),\n  location: Vector,\n  mass: S.Number,\n  population: S.Number,\n  habitable: S.Boolean\n})\nconst PlanetZod = z.object({\n  type: z.literal(\"planet\"),\n  location: VectorZod,\n  mass: z.number(),\n  population: z.number(),\n  habitable: z.boolean()\n})\n\nconst Rank = S.Union(\n  S.Literal(\"captain\"),\n  S.Literal(\"first mate\"),\n  S.Literal(\"officer\"),\n  S.Literal(\"ensign\")\n)\nconst RankZod = z.union([\n  z.literal(\"captain\"),\n  z.literal(\"first mate\"),\n  z.literal(\"officer\"),\n  z.literal(\"ensign\")\n])\n\nconst CrewMember = S.Struct({\n  name: S.String,\n  age: S.Number,\n  rank: Rank,\n  home: Planet\n})\nconst CrewMemberZod = z.object({\n  name: z.string(),\n  age: z.number(),\n  rank: RankZod,\n  home: PlanetZod\n})\n\nconst Ship = S.Struct({\n  type: S.Literal(\"ship\"),\n  location: Vector,\n  mass: S.Number,\n  name: S.String,\n  crew: S.Array(CrewMember)\n})\nconst ShipZod = z.object({\n  type: z.literal(\"ship\"),\n  location: VectorZod,\n  mass: z.number(),\n  name: z.string(),\n  crew: z.array(CrewMemberZod)\n})\n\nexport const schema = S.Union(Asteroid, Planet, Ship)\nexport const schemaZod = z.discriminatedUnion(\"type\", [AsteroidZod, PlanetZod, ShipZod])\n\nconst good = {\n  type: \"ship\",\n  location: [1, 2, 3],\n  mass: 4,\n  name: \"foo\",\n  crew: [\n    {\n      name: \"bar\",\n      age: 44,\n      rank: \"captain\",\n      home: {\n        type: \"planet\",\n        location: [5, 6, 7],\n        mass: 8,\n        population: 1000,\n        habitable: true\n      }\n    }\n  ]\n}\n\nconst bad = {\n  type: \"ship\",\n  location: [1, 2, \"a\"],\n  mass: 4,\n  name: \"foo\",\n  crew: [\n    {\n      name: \"bar\",\n      age: 44,\n      rank: \"captain\",\n      home: {\n        type: \"planet\",\n        location: [5, 6, 7],\n        mass: 8,\n        population: \"a\",\n        habitable: true\n      }\n    }\n  ]\n}\n\nexport const schemaDecodeUnknownEither = S.decodeUnknownEither(schema)\nexport const parseResultDecodeUnknownEither = ParseResult.decodeUnknownEither(schema)\nconst options: ParseOptions = { errors: \"all\" }\n\nbench\n  .add(\"Schema.decodeUnknownEither (good)\", function() {\n    schemaDecodeUnknownEither(good, options)\n  })\n  .add(\"ParseResult.decodeUnknownEither (good)\", function() {\n    parseResultDecodeUnknownEither(good, options)\n  })\n  .add(\"zod (good)\", function() {\n    schemaZod.safeParse(good)\n  })\n  .add(\"Schema.decodeUnknownEither (bad)\", function() {\n    schemaDecodeUnknownEither(bad, options)\n  })\n  .add(\"ParseResult.decodeUnknownEither (bad)\", function() {\n    parseResultDecodeUnknownEither(bad, options)\n  })\n  .add(\"zod (bad)\", function() {\n    schemaZod.safeParse(bad)\n  })\n\nawait bench.run()\n\nconsole.table(bench.table())\n"
  },
  {
    "path": "packages/effect/benchmark/SchemaPropertyOrder.ts",
    "content": "import * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport { Bench } from \"tinybench\"\n\n/*\n┌─────────┬────────────────────────────────────────────────────────────┬──────────────┬────────────────────┬──────────┬──────────┐\n│ (index) │ Task Name                                                  │ ops/sec      │ Average Time (ns)  │ Margin   │ Samples  │\n├─────────┼────────────────────────────────────────────────────────────┼──────────────┼────────────────────┼──────────┼──────────┤\n│ 0       │ 'decodeUnknownEither (valid input)'                        │ '1,286,800'  │ 777.1212922589341  │ '±0.29%' │ 1286801  │\n│ 1       │ 'decodeUnknownEitherPreserveInputKeyOrder (valid input)'   │ '843,338'    │ 1185.7631901288776 │ '±0.18%' │ 843339   │\n│ 2       │ 'decodeUnknownEither (invalid input)'                      │ '13,934,307' │ 71.76531493346903  │ '±0.31%' │ 13934308 │\n│ 3       │ 'decodeUnknownEitherPreserveInputKeyOrder (invalid input)' │ '13,450,784' │ 74.3451049138201   │ '±0.56%' │ 13450785 │\n└─────────┴────────────────────────────────────────────────────────────┴──────────────┴────────────────────┴──────────┴──────────┘\n*/\n\nconst bench = new Bench({ time: 1000 })\n\nconst schema = S.Struct({\n  a: S.Literal(\"a\"),\n  b: S.Array(S.String),\n  c: S.Record({ key: S.String, value: S.Number }),\n  d: S.NumberFromString,\n  e: S.Boolean\n})\n\nconst validInput = { a: \"a\", b: [\"b\"], c: { c: 1 }, d: \"1\", e: true }\n\nconst invalidInput = { b: [\"b\"], c: { c: 1 }, d: \"1\", e: true, a: null }\n\nconst decodeUnknownEither = ParseResult.decodeUnknownEither(schema)\nconst decodeUnknownEitherPreserveInputKeyOrder = ParseResult.decodeUnknownEither(schema, { propertyOrder: \"original\" })\n\nbench\n  .add(\"ParseResult.decodeUnknownEither (valid input)\", function() {\n    decodeUnknownEither(validInput)\n  })\n  .add(\"ParseResult.decodeUnknownEitherPreserveInputKeyOrder (valid input)\", function() {\n    decodeUnknownEitherPreserveInputKeyOrder(validInput)\n  })\n  .add(\"ParseResult.decodeUnknownEither (invalid input)\", function() {\n    decodeUnknownEither(invalidInput)\n  })\n  .add(\"ParseResult.decodeUnknownEitherPreserveInputKeyOrder (invalid input)\", function() {\n    decodeUnknownEitherPreserveInputKeyOrder(invalidInput)\n  })\n\nawait bench.run()\n\nconsole.table(bench.table())\n"
  },
  {
    "path": "packages/effect/benchmark/SchemaStruct.ts",
    "content": "import * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport { Bench } from \"tinybench\"\n\n/*\n┌─────────┬──────────────────────────────────────────┬──────────────┬───────────────────┬──────────┬──────────┐\n│ (index) │ Task Name                                │ ops/sec      │ Average Time (ns) │ Margin   │ Samples  │\n├─────────┼──────────────────────────────────────────┼──────────────┼───────────────────┼──────────┼──────────┤\n│ 0       │ 'ParseResult.decodeUnknownEither (good)' │ '1,253,290'  │ 797.8996777284824 │ '±0.23%' │ 1253291  │\n│ 1       │ 'ParseResult.decodeUnknownEither (bad)'  │ '13,713,888' │ 72.91877607298059 │ '±0.36%' │ 13713890 │\n└─────────┴──────────────────────────────────────────┴──────────────┴───────────────────┴──────────┴──────────┘\n*/\n\nconst bench = new Bench({ time: 1000 })\n\nconst schema = S.Struct({\n  a: S.Literal(\"a\"),\n  b: S.Array(S.String),\n  c: S.Record({ key: S.String, value: S.Number }),\n  d: S.NumberFromString,\n  e: S.Boolean\n})\n\nconst good = { a: \"a\", b: [\"b\"], c: { c: 1 }, d: \"1\", e: true }\n\nconst bad = { b: [\"b\"], c: { c: 1 }, d: \"1\", e: true, a: null }\n\nconst decodeUnknownEither = ParseResult.decodeUnknownEither(schema)\n\n// console.log(decodeUnknownEither(good))\n// console.log(decodeUnknownEither(bad))\n\nbench\n  .add(\"ParseResult.decodeUnknownEither (good)\", function() {\n    decodeUnknownEither(good)\n  })\n  .add(\"ParseResult.decodeUnknownEither (bad)\", function() {\n    decodeUnknownEither(bad)\n  })\n\nawait bench.run()\n\nconsole.table(bench.table())\n"
  },
  {
    "path": "packages/effect/benchmark/SchemaToString.ts",
    "content": "import * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport { Bench } from \"tinybench\"\n\n/*\n┌─────────┬─────────────────────────────────┬───────────┬────────────────────┬──────────┬─────────┐\n│ (index) │ Task Name                       │ ops/sec   │ Average Time (ns)  │ Margin   │ Samples │\n├─────────┼─────────────────────────────────┼───────────┼────────────────────┼──────────┼─────────┤\n│ 0       │ 'toString'                      │ '282,142' │ 3544.30530263047   │ '±1.79%' │ 282143  │\n│ 1       │ 'toJSON'                        │ '319,008' │ 3134.714130322425  │ '±0.45%' │ 319009  │\n│ 2       │ 'TreeFormatter.formatIssueSync' │ '35,271'  │ 28351.291506011636 │ '±0.18%' │ 35272   │\n└─────────┴─────────────────────────────────┴───────────┴────────────────────┴──────────┴─────────┘\n*/\n\nconst bench = new Bench({ time: 1000 })\n\nconst schema = S.Struct({\n  a: S.Literal(\"a\"),\n  b: S.Array(S.String),\n  c: S.Record({ key: S.String, value: S.Number }),\n  d: S.NumberFromString,\n  e: S.Boolean\n})\n\nconst result: any = ParseResult.decodeUnknownEither(schema)({ a: \"a\", b: [\"b\"], c: { c: \"c\" }, d: \"1\", e: true })\n\n// console.log(String(schema.ast))\n\nbench\n  .add(\"toString\", function() {\n    String(schema.ast)\n  })\n  .add(\"toJSON\", function() {\n    schema.ast.toJSON()\n  })\n  .add(\"TreeFormatter.formatIssueSync\", function() {\n    ParseResult.TreeFormatter.formatIssueSync(result.left)\n  })\n\nawait bench.run()\n\nconsole.table(bench.table())\n"
  },
  {
    "path": "packages/effect/benchmark/SchemaTreeFormatter.ts",
    "content": "import type * as Either from \"effect/Either\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport { Bench } from \"tinybench\"\n\n/*\n┌─────────┬────────────────────────────────────────┬──────────┬───────────────────┬──────────┬─────────┐\n│ (index) │ Task Name                              │ ops/sec  │ Average Time (ns) │ Margin   │ Samples │\n├─────────┼────────────────────────────────────────┼──────────┼───────────────────┼──────────┼─────────┤\n│ 0       │ 'TreeFormatter.formatIssueSync(issue)' │ '27,902' │ 35839.27072357856 │ '±0.29%' │ 27903   │\n└─────────┴────────────────────────────────────────┴──────────┴───────────────────┴──────────┴─────────┘\n*/\n\nconst bench = new Bench({ time: 1000 })\n\nconst schema = S.Struct({\n  a: S.Struct({\n    b: S.Struct({\n      c: S.NonEmptyString\n    })\n  })\n})\n\nconst decodeUnknownEither = S.decodeUnknownEither(schema)\nconst input = { a: { b: { c: \"\" } } }\nconst result = decodeUnknownEither(input)\nconst issue = (result as any as Either.Left<ParseResult.ParseError, unknown>).left.issue\n\n// console.log(issue)\n\nbench\n  .add(\"TreeFormatter.formatIssueSync(issue)\", function() {\n    ParseResult.TreeFormatter.formatIssueSync(issue)\n  })\n\nawait bench.run()\n\nconsole.table(bench.table())\n"
  },
  {
    "path": "packages/effect/benchmark/SchemaTuple.ts",
    "content": "import * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport { Bench } from \"tinybench\"\n\n/*\n┌─────────┬──────────────────────────────────────────┬─────────────┬────────────────────┬──────────┬─────────┐\n│ (index) │ Task Name                                │ ops/sec     │ Average Time (ns)  │ Margin   │ Samples │\n├─────────┼──────────────────────────────────────────┼─────────────┼────────────────────┼──────────┼─────────┤\n│ 0       │ 'Schema.decodeUnknownEither (good)'      │ '3,587,107' │ 278.7761790277582  │ '±0.37%' │ 3587108 │\n│ 1       │ 'ParseResult.decodeUnknownEither (good)' │ '3,586,893' │ 278.79274046012614 │ '±0.26%' │ 3586894 │\n│ 2       │ 'Schema.decodeUnknownEither (bad)'       │ '232,689'   │ 4297.571077399399  │ '±0.10%' │ 232690  │\n│ 3       │ 'ParseResult.decodeUnknownEither (bad)'  │ '3,927,039' │ 254.64472936358712 │ '±0.06%' │ 3927040 │\n└─────────┴──────────────────────────────────────────┴─────────────┴────────────────────┴──────────┴─────────┘\n*/\n\nconst bench = new Bench({ time: 1000 })\n\nconst schema = S.Tuple(S.String, S.Number)\n\nconst good = [\"a\", 1]\n\nconst bad = [\"a\", \"b\"]\n\nconst schemadecodeUnknownEither = S.decodeUnknownEither(schema)\nconst parseResultdecodeUnknownEither = ParseResult.decodeUnknownEither(schema)\nconst options: ParseOptions = { errors: \"all\" }\n\nbench\n  .add(\"Schema.decodeUnknownEither (good)\", function() {\n    schemadecodeUnknownEither(good, options)\n  })\n  .add(\"ParseResult.decodeUnknownEither (good)\", function() {\n    parseResultdecodeUnknownEither(good, options)\n  })\n  .add(\"Schema.decodeUnknownEither (bad)\", function() {\n    schemadecodeUnknownEither(bad, options)\n  })\n  .add(\"ParseResult.decodeUnknownEither (bad)\", function() {\n    parseResultdecodeUnknownEither(bad, options)\n  })\n\nawait bench.run()\n\nconsole.table(bench.table())\n"
  },
  {
    "path": "packages/effect/benchmark/SchemaUnion.ts",
    "content": "import * as RA from \"effect/Array\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport { Bench } from \"tinybench\"\nimport { z } from \"zod\"\n\n/*\n┌─────────┬──────────────────────────────────────────┬─────────────┬────────────────────┬──────────┬─────────┐\n│ (index) │ Task Name                                │ ops/sec     │ Average Time (ns)  │ Margin   │ Samples │\n├─────────┼──────────────────────────────────────────┼─────────────┼────────────────────┼──────────┼─────────┤\n│ 0       │ 'Schema.decodeUnknownEither (good)'      │ '2,777,583' │ 360.025132633242   │ '±0.31%' │ 2777584 │\n│ 1       │ 'ParseResult.decodeUnknownEither (good)' │ '2,763,947' │ 361.80132983691675 │ '±0.03%' │ 2763948 │\n│ 2       │ 'zod (good)'                             │ '3,335,028' │ 299.8475137697173  │ '±0.31%' │ 3335029 │\n│ 3       │ 'Schema.decodeUnknownEither (bad)'       │ '207,579'   │ 4817.437354273092  │ '±0.08%' │ 207580  │\n│ 4       │ 'ParseResult.decodeUnknownEither (bad)'  │ '1,707,747' │ 585.5667206168476  │ '±0.31%' │ 1707748 │\n│ 5       │ 'zod (bad)'                              │ '3,305,101' │ 302.5625463294264  │ '±0.24%' │ 3305102 │\n└─────────┴──────────────────────────────────────────┴─────────────┴────────────────────┴──────────┴─────────┘\n*/\n\nconst bench = new Bench({ time: 1000 })\n\nconst n = 100\nconst members = RA.makeBy(n, (i) =>\n  S.Struct({\n    kind: S.Literal(i),\n    a: S.String,\n    b: S.Number,\n    c: S.Boolean\n  }))\nconst schema = S.Union(...members)\n\nconst x = RA.makeBy(n, (i) =>\n  z.object({\n    kind: z.literal(i),\n    a: z.string(),\n    b: z.number(),\n    c: z.boolean()\n  }))\n\nconst schemaZod = z.discriminatedUnion(\"kind\", x)\n\nconst good = {\n  kind: n - 1,\n  a: \"a\",\n  b: 1,\n  c: true\n}\n\nconst bad = {\n  kind: n - 1,\n  a: \"a\",\n  b: 1,\n  c: \"c\"\n}\n\nconst schemaDecodeUnknownEither = S.decodeUnknownEither(schema)\nconst parseResultDecodeUnknownEither = ParseResult.decodeUnknownEither(schema)\nconst options: ParseOptions = { errors: \"all\" }\n\nbench\n  .add(\"Schema.decodeUnknownEither (good)\", function() {\n    schemaDecodeUnknownEither(good, options)\n  })\n  .add(\"ParseResult.decodeUnknownEither (good)\", function() {\n    parseResultDecodeUnknownEither(good, options)\n  })\n  .add(\"zod (good)\", function() {\n    schemaZod.safeParse(good)\n  })\n  .add(\"Schema.decodeUnknownEither (bad)\", function() {\n    schemaDecodeUnknownEither(bad, options)\n  })\n  .add(\"ParseResult.decodeUnknownEither (bad)\", function() {\n    parseResultDecodeUnknownEither(bad, options)\n  })\n  .add(\"zod (bad)\", function() {\n    schemaZod.safeParse(good)\n  })\n\nawait bench.run()\n\nconsole.table(bench.table())\n"
  },
  {
    "path": "packages/effect/benchmark/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"target\": \"ES2022\",\n    \"paths\": {\n      \"effect/*\": [\"../../effect/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/effect/docgen.json",
    "content": "{\n  \"$schema\": \"../../node_modules/@effect/docgen/schema.json\",\n  \"exclude\": [\"src/internal/**/*.ts\"],\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/effect/src/\",\n  \"examplesCompilerOptions\": {\n    \"noEmit\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"module\": \"ES2022\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2022\", \"DOM\"],\n    \"paths\": {\n      \"effect\": [\"../../../effect/src/index.js\"],\n      \"effect/*\": [\"../../../effect/src/*.js\"],\n      \"@effect/ai\": [\"../../../ai/ai/src/index.js\"],\n      \"@effect/platform\": [\"../../../platform/src/index.js\"],\n      \"@effect/platform/*\": [\"../../../platform/src/*.js\"],\n      \"@effect/printer\": [\"../../../printer/src/index.js\"],\n      \"@effect/printer/*\": [\"../../../printer/src/*.js\"],\n      \"@effect/printer-ansi\": [\"../../../printer-ansi/src/index.js\"],\n      \"@effect/printer-ansi/*\": [\"../../../printer-ansi/src/*.js\"],\n      \"@effect/typeclass\": [\"../../../typeclass/src/index.js\"],\n      \"@effect/typeclass/*\": [\"../../../typeclass/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/effect/dtslint/Array.tst.ts",
    "content": "import { Array, Effect, Either, Option, Order, Predicate } from \"effect\"\nimport { hole, identity, pipe } from \"effect/Function\"\nimport { describe, expect, it, when } from \"tstyche\"\n\ndeclare const nonEmptyReadonlyStrings: Array.NonEmptyReadonlyArray<string>\ndeclare const nonEmptyNumbers: Array.NonEmptyArray<number>\ndeclare const nonEmptyStrings: Array.NonEmptyArray<string>\ndeclare const readonlyNumbers: ReadonlyArray<number>\ndeclare const readonlyStrings: ReadonlyArray<string>\ndeclare const numbers: Array<number>\ndeclare const strings: Array<string>\ndeclare const iterNumbers: Iterable<number>\ndeclare const iterStrings: Iterable<string>\ndeclare const numbersOrStrings: Array<number | string>\n\ndeclare const primitiveNumber: number\ndeclare const primitiveNumberOrString: string | number\ndeclare const predicateNumbersOrStrings: Predicate.Predicate<number | string>\n\ndeclare const unknownValue: unknown\ndeclare const stringOrStringArrayOrNull: string | Array<string> | null\n\nconst symA = Symbol.for(\"a\")\nconst symB = Symbol.for(\"b\")\nconst symC = Symbol.for(\"c\")\n\ninterface A {\n  readonly a: string\n}\ninterface AB extends A {\n  readonly b: number\n}\ndeclare const ABs: ReadonlyArray<AB>\ndeclare const nonEmptyABs: Array.NonEmptyReadonlyArray<AB>\ndeclare const orderA: Order.Order<A>\n\ninterface Eff<R> {\n  readonly _R: (_: R) => void\n}\ninterface R1 {\n  readonly _r1: unique symbol\n}\ninterface R2 {\n  readonly _r2: unique symbol\n}\ninterface R3 {\n  readonly _r3: unique symbol\n}\ndeclare const arg1: Eff<R1 | R2>\ndeclare const arg2: Eff<R1 | R2 | R3>\n\ndescribe(\"Array\", () => {\n  it(\"isArray\", () => {\n    if (Array.isArray(unknownValue)) {\n      expect(unknownValue).type.toBe<Array<unknown>>()\n    }\n    if (Array.isArray(stringOrStringArrayOrNull)) {\n      expect(stringOrStringArrayOrNull).type.toBe<Array<string>>()\n    }\n  })\n\n  it(\"isEmptyReadonlyArray\", () => {\n    if (Array.isEmptyReadonlyArray(readonlyNumbers)) {\n      expect(readonlyNumbers).type.toBe<readonly []>()\n    }\n    // should play well with `Option.liftPredicate`\n    expect(Option.liftPredicate(Array.isEmptyReadonlyArray)).type.toBe<\n      <A>(a: ReadonlyArray<A>) => Option.Option<readonly []>\n    >()\n  })\n\n  it(\"isEmptyArray\", () => {\n    if (Array.isEmptyArray(numbers)) {\n      expect(numbers).type.toBe<[]>()\n    }\n    // should play well with `Option.liftPredicate`\n    expect(Option.liftPredicate(Array.isEmptyArray)).type.toBe<\n      <A>(a: Array<A>) => Option.Option<[]>\n    >()\n  })\n\n  it(\"isNonEmptyReadonlyArray\", () => {\n    if (Array.isNonEmptyReadonlyArray(readonlyNumbers)) {\n      expect(readonlyNumbers).type.toBe<readonly [number, ...Array<number>]>()\n    }\n    // should play well with `Option.liftPredicate`\n    expect(Option.liftPredicate(Array.isNonEmptyReadonlyArray)).type.toBe<\n      <A>(a: ReadonlyArray<A>) => Option.Option<readonly [A, ...Array<A>]>\n    >()\n  })\n\n  it(\"isNonEmptyArray\", () => {\n    if (Array.isNonEmptyArray(numbers)) {\n      expect(numbers).type.toBe<[number, ...Array<number>]>()\n    }\n    // should play well with `Option.liftPredicate`\n    expect(Option.liftPredicate(Array.isNonEmptyArray)).type.toBe<\n      <A>(a: Array<A>) => Option.Option<[A, ...Array<A>]>\n    >()\n  })\n\n  it(\"map\", () => {\n    expect(Array.map(readonlyStrings, (s, i) => {\n      expect(s).type.toBe<string>()\n      expect(i).type.toBe<number>()\n      return s + \"a\"\n    })).type.toBe<Array<string>>()\n    expect(pipe(\n      readonlyStrings,\n      Array.map((s, i) => {\n        expect(s).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return s + \"a\"\n      })\n    )).type.toBe<Array<string>>()\n\n    expect(Array.map(strings, (s, i) => {\n      expect(s).type.toBe<string>()\n      expect(i).type.toBe<number>()\n      return s + \"a\"\n    })).type.toBe<Array<string>>()\n    expect(pipe(\n      strings,\n      Array.map((s, i) => {\n        expect(s).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return s + \"a\"\n      })\n    )).type.toBe<Array<string>>()\n\n    expect(Array.map(nonEmptyReadonlyStrings, (s, i) => {\n      expect(s).type.toBe<string>()\n      expect(i).type.toBe<number>()\n      return s + \"a\"\n    })).type.toBe<[string, ...Array<string>]>()\n    expect(pipe(\n      nonEmptyReadonlyStrings,\n      Array.map((s, i) => {\n        expect(s).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return s + \"a\"\n      })\n    )).type.toBe<[string, ...Array<string>]>()\n\n    expect(Array.map(nonEmptyStrings, (s, i) => {\n      expect(s).type.toBe<string>()\n      expect(i).type.toBe<number>()\n      return s + \"a\"\n    })).type.toBe<[string, ...Array<string>]>()\n    expect(pipe(\n      nonEmptyStrings,\n      Array.map((s, i) => {\n        expect(s).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return s + \"a\"\n      })\n    )).type.toBe<[string, ...Array<string>]>()\n  })\n\n  it(\"groupBy\", () => {\n    expect(Array.groupBy([1, 2, 3], (n) => {\n      expect(n).type.toBe<number>()\n      return String(n)\n    })).type.toBe<Record<string, [number, ...Array<number>]>>()\n    expect(pipe(\n      [1, 2, 3],\n      Array.groupBy((n) => {\n        expect(n).type.toBe<number>()\n        return String(n)\n      })\n    )).type.toBe<Record<string, [number, ...Array<number>]>>()\n    expect(\n      Array.groupBy([1, 2, 3], (n) => n > 0 ? \"positive\" as const : \"negative\" as const)\n    ).type.toBe<Record<string, [number, ...Array<number>]>>()\n    expect(Array.groupBy([\"a\", \"b\"], Symbol.for)).type.toBe<Record<symbol, [string, ...Array<string>]>>()\n    expect(Array.groupBy([\"a\", \"b\"], (s) => s === \"a\" ? symA : s === \"b\" ? symB : symC)).type.toBe<\n      Record<symbol, [string, ...Array<string>]>\n    >()\n  })\n\n  it(\"some\", () => {\n    expect(Array.some(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return true\n    })).type.toBe<boolean>()\n    expect(pipe(\n      numbersOrStrings,\n      Array.some((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return true\n      })\n    )).type.toBe<boolean>()\n    if (Array.some(numbersOrStrings, Predicate.isString)) {\n      expect(numbersOrStrings).type.toBe<\n        Array<string | number> & readonly [string | number, ...Array<string | number>]\n      >()\n    }\n  })\n\n  it(\"every\", () => {\n    expect(Array.every(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return true\n    })).type.toBe<boolean>()\n    expect(pipe(\n      numbersOrStrings,\n      Array.every((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return true\n      })\n    )).type.toBe<boolean>()\n    if (Array.every(numbersOrStrings, Predicate.isString)) {\n      expect(numbersOrStrings).type.toBe<Array<string | number> & ReadonlyArray<string>>()\n    }\n    if (Array.every(Predicate.isString)(numbersOrStrings)) {\n      expect(numbersOrStrings).type.toBe<Array<string | number> & ReadonlyArray<string>>()\n    }\n  })\n\n  it(\"append\", () => {\n    expect(Array.append(numbersOrStrings, true))\n      .type.toBe<[string | number | boolean, ...Array<string | number | boolean>]>()\n    expect(pipe(numbersOrStrings, Array.append(true)))\n      .type.toBe<[string | number | boolean, ...Array<string | number | boolean>]>()\n    expect(Array.append(true)(numbersOrStrings))\n      .type.toBe<[string | number | boolean, ...Array<string | number | boolean>]>()\n  })\n\n  it(\"prepend\", () => {\n    expect(Array.prepend(numbersOrStrings, true))\n      .type.toBe<[string | number | boolean, ...Array<string | number | boolean>]>()\n    expect(pipe(numbersOrStrings, Array.prepend(true)))\n      .type.toBe<[string | number | boolean, ...Array<string | number | boolean>]>()\n    expect(Array.prepend(true)(numbersOrStrings))\n      .type.toBe<[string | number | boolean, ...Array<string | number | boolean>]>()\n  })\n\n  it(\"sort\", () => {\n    expect(Array.sort(ABs, orderA)).type.toBe<Array<AB>>()\n    expect(pipe(ABs, Array.sort(orderA))).type.toBe<Array<AB>>()\n    expect(Array.sort(orderA)(ABs)).type.toBe<Array<AB>>()\n    expect(Array.sort(nonEmptyABs, orderA)).type.toBe<[AB, ...Array<AB>]>()\n    expect(pipe(nonEmptyABs, Array.sort(orderA))).type.toBe<[AB, ...Array<AB>]>()\n    expect(Array.sort(orderA)(nonEmptyABs)).type.toBe<[AB, ...Array<AB>]>()\n\n    when(pipe).isCalledWith([1], expect(Array.sort).type.not.toBeCallableWith(Order.string))\n    expect(Array.sort).type.not.toBeCallableWith([1], Order.string)\n    expect(Array.sort(Order.string)).type.not.toBeCallableWith([1])\n  })\n\n  it(\"sortWith\", () => {\n    expect(pipe(\n      ABs,\n      Array.sortWith(identity, (a, b) => {\n        expect(a).type.toBe<AB>()\n        expect(b).type.toBe<AB>()\n        return 0\n      })\n    )).type.toBe<Array<AB>>()\n    expect(Array.sortWith(ABs, identity, (a, b) => {\n      expect(a).type.toBe<AB>()\n      expect(b).type.toBe<AB>()\n      return 0\n    })).type.toBe<Array<AB>>()\n    expect(pipe(\n      nonEmptyABs,\n      Array.sortWith(identity, (a, b) => {\n        expect(a).type.toBe<AB>()\n        expect(b).type.toBe<AB>()\n        return 0\n      })\n    )).type.toBe<\n      [AB, ...Array<AB>]\n    >()\n    expect(Array.sortWith(nonEmptyABs, identity, (a, b) => {\n      expect(a).type.toBe<AB>()\n      expect(b).type.toBe<AB>()\n      return 0\n    })).type.toBe<\n      [AB, ...Array<AB>]\n    >()\n  })\n\n  it(\"sortBy\", () => {\n    // Array\n    expect(pipe(\n      ABs,\n      Array.sortBy((a, b) => {\n        expect(a).type.toBe<AB>()\n        expect(b).type.toBe<AB>()\n        return 0\n      })\n    )).type.toBe<Array<AB>>()\n    expect(\n      pipe(\n        ABs,\n        Array.sortBy((a, b) => {\n          expect(a).type.toBe<AB>()\n          expect(b).type.toBe<AB>()\n          return 0\n        })\n      )\n    ).type.toBe<Array<AB>>()\n\n    // NonEmptyArray\n    expect(pipe(\n      nonEmptyABs,\n      Array.sortBy((a, b) => {\n        expect(a).type.toBe<AB>()\n        expect(b).type.toBe<AB>()\n        return 0\n      })\n    )).type.toBe<[AB, ...Array<AB>]>()\n    expect(\n      pipe(\n        nonEmptyABs,\n        Array.sortBy((a, b) => {\n          expect(a).type.toBe<AB>()\n          expect(b).type.toBe<AB>()\n          return 0\n        })\n      )\n    ).type.toBe<[AB, ...Array<AB>]>()\n  })\n\n  it(\"partition\", () => {\n    expect(Array.partition(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return true\n    })).type.toBe<[Array<string | number>, Array<string | number>]>()\n    expect(pipe(\n      numbersOrStrings,\n      Array.partition((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return true\n      })\n    )).type.toBe<[Array<string | number>, Array<string | number>]>()\n    expect(Array.partition(numbersOrStrings, predicateNumbersOrStrings))\n      .type.toBe<[excluded: Array<string | number>, satisfying: Array<string | number>]>()\n    expect(pipe(numbersOrStrings, Array.partition(predicateNumbersOrStrings)))\n      .type.toBe<[excluded: Array<string | number>, satisfying: Array<string | number>]>()\n    expect(Array.partition(numbersOrStrings, Predicate.isNumber))\n      .type.toBe<[excluded: Array<string>, satisfying: Array<number>]>()\n    expect(pipe(numbersOrStrings, Array.partition(Predicate.isNumber)))\n      .type.toBe<[excluded: Array<string>, satisfying: Array<number>]>()\n  })\n\n  it(\"filter\", () => {\n    expect(Array.filter(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return true\n    })).type.toBe<Array<string | number>>()\n    expect(pipe(\n      numbersOrStrings,\n      Array.filter((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return true\n      })\n    )).type.toBe<Array<string | number>>()\n\n    expect(Array.filter).type.not.toBeCallableWith(numbersOrStrings, (_item: string) => true)\n    when(pipe).isCalledWith(\n      numbersOrStrings,\n      expect(Array.filter).type.not.toBeCallableWith((_item: string) => true)\n    )\n\n    expect(Array.filter(numbers, predicateNumbersOrStrings)).type.toBe<Array<number>>()\n    expect(pipe(numbers, Array.filter(predicateNumbersOrStrings))).type.toBe<Array<number>>()\n\n    expect(Array.filter(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<Array<string | number>>()\n    expect(pipe(numbersOrStrings, Array.filter(predicateNumbersOrStrings))).type.toBe<Array<string | number>>()\n\n    expect(Array.filter(numbersOrStrings, Predicate.isNumber)).type.toBe<Array<number>>()\n    expect(pipe(numbersOrStrings, Array.filter(Predicate.isNumber))).type.toBe<Array<number>>()\n  })\n\n  it(\"takeWhile\", () => {\n    expect(Array.takeWhile(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return true\n    })).type.toBe<Array<string | number>>()\n    expect(pipe(\n      numbersOrStrings,\n      Array.takeWhile((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return true\n      })\n    )).type.toBe<Array<string | number>>()\n\n    expect(Array.takeWhile(numbers, predicateNumbersOrStrings)).type.toBe<Array<number>>()\n    expect(pipe(numbers, Array.takeWhile(predicateNumbersOrStrings))).type.toBe<Array<number>>()\n\n    expect(Array.takeWhile(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<Array<string | number>>()\n    expect(pipe(numbersOrStrings, Array.takeWhile(predicateNumbersOrStrings))).type.toBe<Array<string | number>>()\n\n    expect(Array.takeWhile(numbersOrStrings, Predicate.isNumber)).type.toBe<Array<number>>()\n    expect(pipe(numbersOrStrings, Array.takeWhile(Predicate.isNumber))).type.toBe<Array<number>>()\n  })\n\n  it(\"findFirst\", () => {\n    expect(Array.findFirst(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return true\n    })).type.toBe<Option.Option<string | number>>()\n    expect(pipe(\n      numbersOrStrings,\n      Array.findFirst((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return true\n      })\n    )).type.toBe<Option.Option<string | number>>()\n\n    expect(Array.findFirst(numbersOrStrings, Predicate.isNumber)).type.toBe<Option.Option<number>>()\n    expect(pipe(numbersOrStrings, Array.findFirst(Predicate.isNumber))).type.toBe<Option.Option<number>>()\n\n    expect(Array.findFirst(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return Option.some(true)\n    })).type.toBe<Option.Option<boolean>>()\n    expect(pipe(\n      numbersOrStrings,\n      Array.findFirst((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return Option.some(true)\n      })\n    )).type.toBe<Option.Option<boolean>>()\n\n    expect(Array.findFirst(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<Option.Option<string | number>>()\n    expect(pipe(numbersOrStrings, Array.findFirst(predicateNumbersOrStrings)))\n      .type.toBe<Option.Option<string | number>>()\n  })\n\n  it(\"findLast\", () => {\n    expect(Array.findLast(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return true\n    })).type.toBe<Option.Option<string | number>>()\n    expect(pipe(\n      numbersOrStrings,\n      Array.findLast((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return true\n      })\n    )).type.toBe<Option.Option<string | number>>()\n\n    expect(Array.findLast(numbersOrStrings, Predicate.isNumber)).type.toBe<Option.Option<number>>()\n    expect(pipe(numbersOrStrings, Array.findLast(Predicate.isNumber))).type.toBe<Option.Option<number>>()\n\n    expect(Array.findLast(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return Option.some(true)\n    })).type.toBe<Option.Option<boolean>>()\n    expect(pipe(\n      numbersOrStrings,\n      Array.findLast((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return Option.some(true)\n      })\n    )).type.toBe<Option.Option<boolean>>()\n\n    expect(Array.findLast(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<Option.Option<string | number>>()\n    expect(pipe(numbersOrStrings, Array.findLast(predicateNumbersOrStrings)))\n      .type.toBe<Option.Option<string | number>>()\n  })\n\n  it(\"liftPredicate\", () => {\n    expect(\n      pipe(\n        primitiveNumber,\n        Array.liftPredicate((n) => {\n          expect(n).type.toBe<number>()\n          return true\n        })\n      )\n    ).type.toBe<Array<number>>()\n    expect(pipe(\n      primitiveNumberOrString,\n      Array.liftPredicate((n): n is number => {\n        expect(n).type.toBe<string | number>()\n        return typeof n === \"number\"\n      })\n    )).type.toBe<Array<number>>()\n\n    expect(pipe(primitiveNumberOrString, Array.liftPredicate(Predicate.isString))).type.toBe<Array<string>>()\n    expect(pipe(primitiveNumberOrString, Array.liftPredicate(predicateNumbersOrStrings)))\n      .type.toBe<Array<string | number>>()\n    expect(pipe(primitiveNumber, Array.liftPredicate(predicateNumbersOrStrings))).type.toBe<Array<number>>()\n  })\n\n  it(\"span\", () => {\n    Array.span(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return true\n    })\n    pipe(\n      numbersOrStrings,\n      Array.span((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return true\n      })\n    )\n    expect(Array.span(numbers, predicateNumbersOrStrings)).type.toBe<[init: Array<number>, rest: Array<number>]>()\n    expect(pipe(numbers, Array.span(predicateNumbersOrStrings))).type.toBe<[init: Array<number>, rest: Array<number>]>()\n\n    expect(Array.span(numbersOrStrings, predicateNumbersOrStrings))\n      .type.toBe<[init: Array<string | number>, rest: Array<string | number>]>()\n    expect(pipe(numbersOrStrings, Array.span(predicateNumbersOrStrings)))\n      .type.toBe<[init: Array<string | number>, rest: Array<string | number>]>()\n\n    expect(Array.span(numbersOrStrings, Predicate.isNumber)).type.toBe<[init: Array<number>, rest: Array<string>]>()\n    expect(pipe(numbersOrStrings, Array.span(Predicate.isNumber)))\n      .type.toBe<[init: Array<number>, rest: Array<string>]>()\n  })\n\n  it(\"dropWhile\", () => {\n    expect(Array.dropWhile(numbersOrStrings, (item, i) => {\n      expect(item).type.toBe<string | number>()\n      expect(i).type.toBe<number>()\n      return true\n    })).type.toBe<Array<string | number>>()\n    expect(pipe(\n      numbersOrStrings,\n      Array.dropWhile((item, i) => {\n        expect(item).type.toBe<string | number>()\n        expect(i).type.toBe<number>()\n        return true\n      })\n    )).type.toBe<Array<string | number>>()\n\n    expect(Array.dropWhile(numbers, predicateNumbersOrStrings)).type.toBe<Array<number>>()\n    expect(pipe(numbers, Array.dropWhile(predicateNumbersOrStrings))).type.toBe<Array<number>>()\n\n    expect(Array.dropWhile(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<Array<string | number>>()\n    expect(pipe(numbersOrStrings, Array.dropWhile(predicateNumbersOrStrings))).type.toBe<Array<string | number>>()\n\n    expect(Array.dropWhile(numbersOrStrings, Predicate.isNumber)).type.toBe<Array<string | number>>()\n    expect(pipe(numbersOrStrings, Array.dropWhile(Predicate.isNumber))).type.toBe<Array<string | number>>()\n  })\n\n  it(\"flatMap\", () => {\n    expect(\n      Array.flatMap(strings, (item, i) => {\n        expect(item).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return Array.empty<number>()\n      })\n    ).type.toBe<Array<number>>()\n    expect(\n      pipe(\n        strings,\n        Array.flatMap((item, i) => {\n          expect(item).type.toBe<string>()\n          expect(i).type.toBe<number>()\n          return Array.empty<number>()\n        })\n      )\n    ).type.toBe<Array<number>>()\n\n    expect(\n      Array.flatMap(nonEmptyReadonlyStrings, (item, i) => {\n        expect(item).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return Array.empty<number>()\n      })\n    ).type.toBe<Array<number>>()\n    expect(\n      pipe(\n        nonEmptyReadonlyStrings,\n        Array.flatMap((item, i) => {\n          expect(item).type.toBe<string>()\n          expect(i).type.toBe<number>()\n          return Array.empty<number>()\n        })\n      )\n    ).type.toBe<Array<number>>()\n\n    expect(\n      Array.flatMap(nonEmptyReadonlyStrings, (item, i) => {\n        expect(item).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return Array.of(item.length)\n      })\n    ).type.toBe<[number, ...Array<number>]>()\n    expect(\n      pipe(\n        nonEmptyReadonlyStrings,\n        Array.flatMap((item, i) => {\n          expect(item).type.toBe<string>()\n          expect(i).type.toBe<number>()\n          return Array.of(item.length)\n        })\n      )\n    ).type.toBe<[number, ...Array<number>]>()\n  })\n\n  it(\"flatten\", () => {\n    // Mutable arrays\n    expect(Array.flatten(hole<Array<Array<number>>>())).type.toBe<Array<number>>()\n    expect(Array.flatten(hole<Array<Array.NonEmptyArray<number>>>())).type.toBe<Array<number>>()\n    expect(Array.flatten(hole<Array.NonEmptyArray<Array<number>>>())).type.toBe<Array<number>>()\n    expect(Array.flatten(hole<Array.NonEmptyReadonlyArray<Array.NonEmptyReadonlyArray<number>>>()))\n      .type.toBe<[number, ...Array<number>]>()\n\n    // Readonly arrays\n    expect(\n      hole<Effect.Effect<ReadonlyArray<ReadonlyArray<number>>>>().pipe(Effect.map((x) => {\n        expect(x).type.toBe<ReadonlyArray<ReadonlyArray<number>>>()\n        return Array.flatten(x)\n      }))\n    ).type.toBe<Effect.Effect<Array<number>, never, never>>()\n    expect(\n      hole<Effect.Effect<Array.NonEmptyReadonlyArray<Array.NonEmptyReadonlyArray<number>>>>().pipe(Effect.map((x) => {\n        expect(x).type.toBe<Array.NonEmptyReadonlyArray<Array.NonEmptyReadonlyArray<number>>>()\n        return Array.flatten(x)\n      }))\n    ).type.toBe<Effect.Effect<[number, ...Array<number>], never, never>>()\n\n    expect(Array.flatten([[arg1], [arg2]])).type.toBe<Array.NonEmptyArray<Eff<R1 | R2> | Eff<R1 | R2 | R3>>>()\n    expect(Array.flatten([[arg2], [arg1]])).type.toBe<Array.NonEmptyArray<Eff<R1 | R2> | Eff<R1 | R2 | R3>>>()\n  })\n\n  it(\"prependAll\", () => {\n    // Array + Array\n    expect(Array.prependAll(strings, numbers)).type.toBe<Array<string | number>>()\n    expect(pipe(strings, Array.prependAll(numbers))).type.toBe<Array<string | number>>()\n\n    // NonEmptyArray + Array\n    expect(Array.prependAll(nonEmptyStrings, numbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(nonEmptyStrings, Array.prependAll(numbers))).type.toBe<[string | number, ...Array<string | number>]>()\n\n    // Array + NonEmptyArray\n    expect(Array.prependAll(strings, nonEmptyNumbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(strings, Array.prependAll(nonEmptyNumbers))).type.toBe<[string | number, ...Array<string | number>]>()\n\n    // NonEmptyArray + NonEmptyArray\n    expect(Array.prependAll(nonEmptyStrings, nonEmptyNumbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(nonEmptyStrings, Array.prependAll(nonEmptyNumbers))).type.toBe<\n      [string | number, ...Array<string | number>]\n    >()\n\n    // Iterable + Array\n    expect(Array.prependAll(iterStrings, numbers)).type.toBe<Array<string | number>>()\n    expect(pipe(iterStrings, Array.prependAll(numbers))).type.toBe<Array<string | number>>()\n\n    // Iterable + NonEmptyArray\n    expect(Array.prependAll(iterStrings, nonEmptyNumbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(iterStrings, Array.prependAll(nonEmptyNumbers))).type.toBe<\n      [string | number, ...Array<string | number>]\n    >()\n\n    // Array + Iterable\n    expect(Array.prependAll(numbers, iterStrings)).type.toBe<Array<string | number>>()\n    expect(pipe(numbers, Array.prependAll(iterStrings))).type.toBe<Array<string | number>>()\n\n    // NonEmptyArray + Iterable\n    expect(Array.prependAll(nonEmptyStrings, iterNumbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(nonEmptyStrings, Array.prependAll(iterNumbers))).type.toBe<\n      [string | number, ...Array<string | number>]\n    >()\n  })\n\n  it(\"appendAll\", () => {\n    // Array + Array\n    expect(Array.appendAll(strings, numbers)).type.toBe<Array<string | number>>()\n    expect(pipe(strings, Array.appendAll(numbers))).type.toBe<Array<string | number>>()\n\n    // NonEmptyArray + Array\n    expect(Array.appendAll(nonEmptyStrings, numbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(nonEmptyStrings, Array.appendAll(numbers))).type.toBe<[string | number, ...Array<string | number>]>()\n\n    // Array + NonEmptyArray\n    expect(Array.appendAll(strings, nonEmptyNumbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(strings, Array.appendAll(nonEmptyNumbers))).type.toBe<[string | number, ...Array<string | number>]>()\n\n    // NonEmptyArray + NonEmptyArray\n    expect(Array.appendAll(nonEmptyStrings, nonEmptyNumbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(nonEmptyStrings, Array.appendAll(nonEmptyNumbers)))\n      .type.toBe<[string | number, ...Array<string | number>]>()\n\n    // Iterable + Array\n    expect(Array.appendAll(iterStrings, numbers)).type.toBe<Array<string | number>>()\n    expect(pipe(iterStrings, Array.appendAll(numbers))).type.toBe<Array<string | number>>()\n\n    // Iterable + NonEmptyArray\n    expect(Array.appendAll(iterStrings, nonEmptyNumbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(iterStrings, Array.appendAll(nonEmptyNumbers))).type.toBe<\n      [string | number, ...Array<string | number>]\n    >()\n\n    // Array + Iterable\n    expect(Array.appendAll(numbers, iterStrings)).type.toBe<Array<string | number>>()\n    expect(pipe(numbers, Array.appendAll(iterStrings))).type.toBe<Array<string | number>>()\n\n    // NonEmptyArray + Iterable\n    expect(Array.appendAll(nonEmptyStrings, iterNumbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(nonEmptyStrings, Array.appendAll(iterNumbers)))\n      .type.toBe<[string | number, ...Array<string | number>]>()\n  })\n\n  it(\"zip\", () => {\n    expect(Array.zip(strings, numbers)).type.toBe<Array<[string, number]>>()\n    expect(pipe(strings, Array.zip(numbers))).type.toBe<Array<[string, number]>>()\n    expect(Array.zip(numbers)(strings)).type.toBe<Array<[string, number]>>()\n\n    expect(Array.zip(nonEmptyStrings, nonEmptyNumbers)).type.toBe<[[string, number], ...Array<[string, number]>]>()\n    expect(pipe(nonEmptyStrings, Array.zip(nonEmptyNumbers)))\n      .type.toBe<[[string, number], ...Array<[string, number]>]>()\n    expect(Array.zip(nonEmptyNumbers)(nonEmptyStrings)).type.toBe<[[string, number], ...Array<[string, number]>]>()\n  })\n\n  it(\"intersperse\", () => {\n    expect(Array.intersperse(strings, \"a\")).type.toBe<Array<string>>()\n    expect(pipe(strings, Array.intersperse(\"a\"))).type.toBe<Array<string>>()\n    expect(Array.intersperse(\"a\")(strings)).type.toBe<Array<string>>()\n\n    expect(Array.intersperse(strings, 1)).type.toBe<Array<string | number>>()\n    expect(pipe(strings, Array.intersperse(1))).type.toBe<Array<string | number>>()\n    expect(Array.intersperse(1)(strings)).type.toBe<Array<string | number>>()\n\n    expect(Array.intersperse(nonEmptyStrings, \"a\")).type.toBe<[string, ...Array<string>]>()\n    expect(pipe(nonEmptyStrings, Array.intersperse(\"a\"))).type.toBe<[string, ...Array<string>]>()\n    expect(Array.intersperse(\"a\")(nonEmptyStrings)).type.toBe<[string, ...Array<string>]>()\n\n    expect(Array.intersperse(nonEmptyStrings, 1)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(nonEmptyStrings, Array.intersperse(1))).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(Array.intersperse(1)(nonEmptyStrings)).type.toBe<[string | number, ...Array<string | number>]>()\n  })\n\n  it(\"rotate\", () => {\n    expect(Array.rotate(strings, 10)).type.toBe<Array<string>>()\n    expect(pipe(strings, Array.rotate(10))).type.toBe<Array<string>>()\n    expect(Array.rotate(10)(strings)).type.toBe<Array<string>>()\n\n    expect(Array.rotate(nonEmptyStrings, 10)).type.toBe<[string, ...Array<string>]>()\n    expect(pipe(nonEmptyStrings, Array.rotate(10))).type.toBe<[string, ...Array<string>]>()\n    expect(Array.rotate(10)(nonEmptyStrings)).type.toBe<[string, ...Array<string>]>()\n  })\n\n  it(\"union\", () => {\n    expect(Array.union(strings, numbers)).type.toBe<Array<string | number>>()\n    expect(pipe(strings, Array.union(numbers))).type.toBe<Array<string | number>>()\n    expect(Array.union(numbers)(strings)).type.toBe<Array<string | number>>()\n\n    expect(Array.union(nonEmptyStrings, numbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(nonEmptyStrings, Array.union(numbers))).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(Array.union(numbers)(nonEmptyStrings)).type.toBe<[string | number, ...Array<string | number>]>()\n\n    expect(Array.union(strings, nonEmptyNumbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(strings, Array.union(nonEmptyNumbers))).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(Array.union(nonEmptyNumbers)(strings)).type.toBe<[string | number, ...Array<string | number>]>()\n\n    expect(Array.union(nonEmptyStrings, nonEmptyNumbers)).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(pipe(nonEmptyStrings, Array.union(nonEmptyNumbers)))\n      .type.toBe<[string | number, ...Array<string | number>]>()\n\n    expect(Array.union(nonEmptyNumbers)(nonEmptyStrings)).type.toBe<[string | number, ...Array<string | number>]>()\n  })\n\n  it(\"unionWith\", () => {\n    // Array + Array\n    expect(\n      Array.unionWith(strings, numbers, (a, b) => {\n        expect(a).type.toBe<string>()\n        expect(b).type.toBe<number>()\n        return true\n      })\n    ).type.toBe<Array<string | number>>()\n    expect(\n      pipe(\n        strings,\n        Array.unionWith(numbers, (a, b) => {\n          expect(a).type.toBe<string>()\n          expect(b).type.toBe<number>()\n          return true\n        })\n      )\n    ).type.toBe<Array<string | number>>()\n\n    // NonEmptyArray + Array\n    expect(\n      Array.unionWith(nonEmptyStrings, numbers, (a, b) => {\n        expect(a).type.toBe<string>()\n        expect(b).type.toBe<number>()\n        return true\n      })\n    ).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(\n      pipe(\n        nonEmptyStrings,\n        Array.unionWith(numbers, (a, b) => {\n          expect(a).type.toBe<string>()\n          expect(b).type.toBe<number>()\n          return true\n        })\n      )\n    ).type.toBe<[string | number, ...Array<string | number>]>()\n\n    // Array + NonEmptyArray\n    expect(\n      Array.unionWith(strings, nonEmptyNumbers, (a, b) => {\n        expect(a).type.toBe<string>()\n        expect(b).type.toBe<number>()\n        return true\n      })\n    ).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(\n      pipe(\n        strings,\n        Array.unionWith(nonEmptyNumbers, (a, b) => {\n          expect(a).type.toBe<string>()\n          expect(b).type.toBe<number>()\n          return true\n        })\n      )\n    ).type.toBe<[string | number, ...Array<string | number>]>()\n\n    // NonEmptyArray + NonEmptyArray\n    expect(\n      Array.unionWith(nonEmptyStrings, nonEmptyNumbers, (a, b) => {\n        expect(a).type.toBe<string>()\n        expect(b).type.toBe<number>()\n        return true\n      })\n    ).type.toBe<[string | number, ...Array<string | number>]>()\n    expect(\n      pipe(\n        nonEmptyStrings,\n        Array.unionWith(nonEmptyNumbers, (a, b) => {\n          expect(a).type.toBe<string>()\n          expect(b).type.toBe<number>()\n          return true\n        })\n      )\n    ).type.toBe<[string | number, ...Array<string | number>]>()\n  })\n\n  it(\"dedupe\", () => {\n    // Array\n    expect(Array.dedupe(strings)).type.toBe<Array<string>>()\n    expect(pipe(strings, Array.dedupe)).type.toBe<Array<string>>()\n\n    // NonEmptyArray\n    expect(Array.dedupe(nonEmptyStrings)).type.toBe<[string, ...Array<string>]>()\n    expect(pipe(nonEmptyStrings, Array.dedupe)).type.toBe<[string, ...Array<string>]>()\n  })\n\n  it(\"dedupeWith\", () => {\n    // Array\n    expect(\n      Array.dedupeWith(strings, (a, b) => {\n        expect(a).type.toBe<string>()\n        expect(b).type.toBe<string>()\n        return true\n      })\n    ).type.toBe<Array<string>>()\n    expect(pipe(\n      strings,\n      Array.dedupeWith((a, b) => {\n        expect(a).type.toBe<string>()\n        expect(b).type.toBe<string>()\n        return true\n      })\n    )).type.toBe<Array<string>>()\n\n    // NonEmptyArray\n    expect(\n      Array.dedupeWith(nonEmptyStrings, (a, b) => {\n        expect(a).type.toBe<string>()\n        expect(b).type.toBe<string>()\n        return true\n      })\n    ).type.toBe<[string, ...Array<string>]>()\n    expect(\n      pipe(\n        nonEmptyStrings,\n        Array.dedupeWith((a, b) => {\n          expect(a).type.toBe<string>()\n          expect(b).type.toBe<string>()\n          return true\n        })\n      )\n    ).type.toBe<[string, ...Array<string>]>()\n  })\n\n  it(\"chop\", () => {\n    // Array\n    expect(\n      Array.chop(strings, ([head, ...tail]) => {\n        expect(head).type.toBe<string>()\n        expect(tail).type.toBe<Array<string>>()\n        return [head, tail]\n      })\n    ).type.toBe<Array<string>>()\n    expect(\n      pipe(\n        strings,\n        Array.chop(([head, ...tail]) => {\n          expect(head).type.toBe<string>()\n          expect(tail).type.toBe<Array<string>>()\n          return [head, tail]\n        })\n      )\n    ).type.toBe<Array<string>>()\n\n    // NonEmptyArray\n    expect(\n      Array.chop(nonEmptyStrings, ([head, ...tail]) => {\n        expect(head).type.toBe<string>()\n        expect(tail).type.toBe<Array<string>>()\n        return [head, tail]\n      })\n    ).type.toBe<[string, ...Array<string>]>()\n    expect(\n      pipe(\n        nonEmptyStrings,\n        Array.chop(([head, ...tail]) => {\n          expect(head).type.toBe<string>()\n          expect(tail).type.toBe<Array<string>>()\n          return [head, tail]\n        })\n      )\n    ).type.toBe<[string, ...Array<string>]>()\n  })\n\n  it(\"chunksOf\", () => {\n    // Array\n    expect(Array.chunksOf(strings, 10)).type.toBe<Array<[string, ...Array<string>]>>()\n    expect(pipe(strings, Array.chunksOf(10))).type.toBe<Array<[string, ...Array<string>]>>()\n    expect(Array.chunksOf(10)(strings)).type.toBe<Array<[string, ...Array<string>]>>()\n\n    // NonEmptyArray\n    expect(Array.chunksOf(nonEmptyStrings, 10))\n      .type.toBe<[[string, ...Array<string>], ...Array<[string, ...Array<string>]>]>()\n    expect(pipe(nonEmptyStrings, Array.chunksOf(10)))\n      .type.toBe<[[string, ...Array<string>], ...Array<[string, ...Array<string>]>]>()\n    expect(Array.chunksOf(10)(nonEmptyStrings))\n      .type.toBe<[[string, ...Array<string>], ...Array<[string, ...Array<string>]>]>()\n  })\n\n  it(\"window\", () => {\n    const two: number = 2\n    // Array\n    expect(Array.window(strings, two)).type.toBe<Array<Array<string>>>()\n    expect(pipe(strings, Array.window(two))).type.toBe<Array<Array<string>>>()\n    expect(Array.window(two)(strings)).type.toBe<Array<Array<string>>>()\n\n    // NonEmptyArray\n    expect(Array.window(nonEmptyStrings, two)).type.toBe<Array<Array<string>>>()\n    expect(pipe(nonEmptyStrings, Array.window(two))).type.toBe<Array<Array<string>>>()\n    expect(Array.window(two)(nonEmptyStrings)).type.toBe<Array<Array<string>>>()\n\n    // literal + Array\n    expect(Array.window(strings, 2)).type.toBe<Array<[string, string]>>()\n    expect(pipe(strings, Array.window(2))).type.toBe<Array<[string, string]>>()\n    expect(Array.window(2)(strings)).type.toBe<Array<[string, string]>>()\n\n    // literal + NonEmptyArray\n    expect(Array.window(nonEmptyStrings, 2)).type.toBe<Array<[string, string]>>()\n    expect(pipe(nonEmptyStrings, Array.window(2))).type.toBe<Array<[string, string]>>()\n    expect(Array.window(2)(nonEmptyStrings)).type.toBe<Array<[string, string]>>()\n  })\n\n  it(\"reverse\", () => {\n    // Array\n    expect(Array.reverse(strings)).type.toBe<Array<string>>()\n    expect(pipe(strings, Array.reverse)).type.toBe<Array<string>>()\n\n    // NonEmptyArray\n    expect(Array.reverse(nonEmptyStrings)).type.toBe<[string, ...Array<string>]>()\n    expect(pipe(nonEmptyStrings, Array.reverse)).type.toBe<[string, ...Array<string>]>()\n  })\n\n  it(\"unzip\", () => {\n    // Array\n    expect(Array.unzip(hole<Iterable<[string, number]>>())).type.toBe<[Array<string>, Array<number>]>()\n    expect(pipe(hole<Iterable<[string, number]>>(), Array.unzip)).type.toBe<[Array<string>, Array<number>]>()\n\n    // NonEmptyArray\n    expect(Array.unzip(hole<Array.NonEmptyReadonlyArray<[string, number]>>()))\n      .type.toBe<[[string, ...Array<string>], [number, ...Array<number>]]>()\n    expect(pipe(hole<Array.NonEmptyReadonlyArray<[string, number]>>(), Array.unzip))\n      .type.toBe<[[string, ...Array<string>], [number, ...Array<number>]]>()\n  })\n\n  it(\"zipWith\", () => {\n    // Array + Array\n    expect(\n      Array.zipWith(strings, numbers, (a, b) => {\n        expect(a).type.toBe<string>()\n        expect(b).type.toBe<number>()\n        return [a, b] as [string, number]\n      })\n    ).type.toBe<Array<[string, number]>>()\n    expect(\n      pipe(\n        strings,\n        Array.zipWith(numbers, (a, b) => {\n          expect(a).type.toBe<string>()\n          expect(b).type.toBe<number>()\n          return [a, b] as [string, number]\n        })\n      )\n    ).type.toBe<Array<[string, number]>>()\n\n    // NonEmptyArray + NonEmptyArray\n    expect(\n      Array.zipWith(nonEmptyStrings, nonEmptyNumbers, (a, b) => {\n        expect(a).type.toBe<string>()\n        expect(b).type.toBe<number>()\n        return [a, b] as [string, number]\n      })\n    ).type.toBe<[[string, number], ...Array<[string, number]>]>()\n    expect(\n      pipe(\n        nonEmptyStrings,\n        Array.zipWith(nonEmptyNumbers, (a, b) => {\n          expect(a).type.toBe<string>()\n          expect(b).type.toBe<number>()\n          return [a, b] as [string, number]\n        })\n      )\n    ).type.toBe<[[string, number], ...Array<[string, number]>]>()\n  })\n\n  it(\"separate\", () => {\n    expect(Array.separate([])).type.toBe<[Array<unknown>, Array<unknown>]>()\n    expect(Array.separate([Either.right(1)])).type.toBe<[Array<never>, Array<number>]>()\n    expect(Array.separate([Either.left(\"a\")])).type.toBe<[Array<string>, Array<never>]>()\n    expect(Array.separate([Either.left(\"a\"), Either.right(1)])).type.toBe<[Array<string>, Array<number>]>()\n    expect(Array.separate(hole<Array<Either.Either<number, string>>>())).type.toBe<[Array<string>, Array<number>]>()\n    expect(Array.separate(hole<Iterable<Either.Either<number, string>>>())).type.toBe<[Array<string>, Array<number>]>()\n    expect(Array.separate(\n      hole<Iterable<Either.Either<number, string> | Either.Either<boolean, Date>>>()\n    )).type.toBe<[Array<string | Date>, Array<number | boolean>]>()\n    expect(Array.separate(\n      hole<Iterable<Either.Either<number, string>> | Iterable<Either.Either<boolean, Date>>>()\n    )).type.toBe<[Array<string | Date>, Array<number | boolean>]>()\n  })\n\n  it(\"getRights\", () => {\n    expect(Array.getRights([])).type.toBe<Array<unknown>>()\n    expect(Array.getRights([Either.left(\"a\")])).type.toBe<Array<never>>()\n    expect(Array.getRights([Either.right(1)])).type.toBe<Array<number>>()\n    expect(Array.getRights([Either.left(\"a\"), Either.right(1)])).type.toBe<Array<number>>()\n    expect(Array.getRights(hole<Array<Either.Either<number, string>>>())).type.toBe<Array<number>>()\n    expect(Array.getRights(hole<Iterable<Either.Either<number, string>>>())).type.toBe<Array<number>>()\n    expect(Array.getRights(\n      hole<Iterable<Either.Either<number, string> | Either.Either<boolean, Date>>>()\n    )).type.toBe<Array<number | boolean>>()\n    expect(Array.getRights(\n      hole<Iterable<Either.Either<number, string>> | Iterable<Either.Either<boolean, Date>>>()\n    )).type.toBe<Array<number | boolean>>()\n  })\n\n  it(\"getLefts\", () => {\n    expect(Array.getLefts([])).type.toBe<Array<unknown>>()\n    expect(Array.getLefts([Either.left(\"a\")])).type.toBe<Array<string>>()\n    expect(Array.getLefts([Either.right(1)])).type.toBe<Array<never>>()\n    expect(Array.getLefts([Either.left(\"a\"), Either.right(1)])).type.toBe<Array<string>>()\n    expect(Array.getLefts(hole<Array<Either.Either<number, string>>>())).type.toBe<Array<string>>()\n    expect(Array.getLefts(hole<Iterable<Either.Either<number, string>>>())).type.toBe<Array<string>>()\n    expect(Array.getLefts(hole<Iterable<Either.Either<number, string> | Either.Either<boolean, Date>>>()))\n      .type.toBe<Array<string | Date>>()\n    expect(Array.getLefts(hole<Iterable<Either.Either<number, string>> | Iterable<Either.Either<boolean, Date>>>()))\n      .type.toBe<Array<string | Date>>()\n  })\n\n  it(\"getSomes\", () => {\n    expect(Array.getSomes([])).type.toBe<Array<unknown>>()\n    expect(Array.getSomes([Option.none()])).type.toBe<Array<never>>()\n    expect(Array.getSomes([Option.some(1)])).type.toBe<Array<number>>()\n    expect(Array.getSomes([Option.none(), Option.some(1)])).type.toBe<Array<number>>()\n    expect(Array.getSomes(hole<Array<Option.Option<number>>>())).type.toBe<Array<number>>()\n    expect(Array.getSomes(hole<Iterable<Option.Option<number>>>())).type.toBe<Array<number>>()\n    expect(Array.getSomes(hole<Iterable<Option.Option<number> | Option.Option<string>>>()))\n      .type.toBe<Array<string | number>>()\n    expect(Array.getSomes(hole<Iterable<Option.Option<number>> | Iterable<Option.Option<string>>>()))\n      .type.toBe<Array<string | number>>()\n  })\n\n  it(\"replace\", () => {\n    expect(Array.replace([], 0, \"a\")).type.toBe<Array<string>>()\n    expect(Array.replace(numbers, 0, \"a\")).type.toBe<Array<string | number>>()\n    expect(Array.replace(nonEmptyNumbers, 0, \"a\" as const)).type.toBe<[number | \"a\", ...Array<number | \"a\">]>()\n    expect(Array.replace(new Set([1, 2] as const), 0, \"a\" as const)).type.toBe<Array<\"a\" | 1 | 2>>()\n    expect(pipe([], Array.replace(0, \"a\"))).type.toBe<Array<string>>()\n    expect(pipe(numbers, Array.replace(0, \"a\"))).type.toBe<Array<string | number>>()\n    expect(pipe(nonEmptyNumbers, Array.replace(0, \"a\" as const))).type.toBe<[number | \"a\", ...Array<number | \"a\">]>()\n    expect(pipe(new Set([1, 2] as const), Array.replace(0, \"a\" as const))).type.toBe<Array<\"a\" | 1 | 2>>()\n    expect(pipe(Array.of(1), Array.replace(0, \"a\" as const))).type.toBe<[number | \"a\", ...Array<number | \"a\">]>()\n  })\n\n  it(\"replaceOption\", () => {\n    expect(Array.replaceOption([], 0, \"a\")).type.toBe<Option.Option<Array<string>>>()\n    expect(Array.replaceOption(numbers, 0, \"a\")).type.toBe<Option.Option<Array<string | number>>>()\n    expect(Array.replaceOption(nonEmptyNumbers, 0, \"a\" as const))\n      .type.toBe<Option.Option<[number | \"a\", ...Array<number | \"a\">]>>()\n    expect(Array.replaceOption(new Set([1, 2] as const), 0, \"a\" as const))\n      .type.toBe<Option.Option<Array<\"a\" | 1 | 2>>>()\n    expect(pipe([], Array.replaceOption(0, \"a\"))).type.toBe<Option.Option<Array<string>>>()\n    expect(pipe(numbers, Array.replaceOption(0, \"a\"))).type.toBe<Option.Option<Array<string | number>>>()\n    expect(pipe(nonEmptyNumbers, Array.replaceOption(0, \"a\" as const)))\n      .type.toBe<Option.Option<[number | \"a\", ...Array<number | \"a\">]>>()\n    expect(pipe(new Set([1, 2] as const), Array.replaceOption(0, \"a\" as const)))\n      .type.toBe<Option.Option<Array<\"a\" | 1 | 2>>>()\n  })\n\n  it(\"modify\", () => {\n    // Empty Array\n    expect(Array.modify([], 0, (n) => {\n      expect(n).type.toBe<never>()\n      return \"a\"\n    })).type.toBe<Array<string>>()\n    expect(pipe(\n      [],\n      Array.modify(0, (n) => {\n        expect(n).type.toBe<never>()\n        return \"a\"\n      })\n    )).type.toBe<Array<string>>()\n\n    // Array\n    expect(Array.modify(numbers, 0, (n) => {\n      expect(n).type.toBe<number>()\n      return \"a\"\n    })).type.toBe<Array<string | number>>()\n    expect(pipe(\n      numbers,\n      Array.modify(0, (n) => {\n        expect(n).type.toBe<number>()\n        return \"a\"\n      })\n    )).type.toBe<Array<string | number>>()\n\n    // NonEmptyArray\n    expect(Array.modify(nonEmptyNumbers, 0, (n) => {\n      expect(n).type.toBe<number>()\n      return \"a\" as const\n    })).type.toBe<[number | \"a\", ...Array<number | \"a\">]>()\n    expect(pipe(\n      nonEmptyNumbers,\n      Array.modify(0, (n) => {\n        expect(n).type.toBe<number>()\n        return \"a\" as const\n      })\n    )).type.toBe<[number | \"a\", ...Array<number | \"a\">]>()\n\n    // Iterable\n    expect(Array.modify(new Set([1, 2] as const), 0, (n) => {\n      expect(n).type.toBe<1 | 2>()\n      return \"a\" as const\n    })).type.toBe<Array<\"a\" | 1 | 2>>()\n    expect(pipe(\n      new Set([1, 2] as const),\n      Array.modify(0, (n) => {\n        expect(n).type.toBe<1 | 2>()\n        return \"a\" as const\n      })\n    )).type.toBe<Array<\"a\" | 1 | 2>>()\n  })\n\n  it(\"modifyOption\", () => {\n    // Empty Array\n    expect(Array.modifyOption([], 0, (n) => {\n      expect(n).type.toBe<never>()\n      return \"a\"\n    })).type.toBe<Option.Option<Array<string>>>()\n    expect(pipe(\n      [],\n      Array.modifyOption(0, (n) => {\n        expect(n).type.toBe<never>()\n        return \"a\"\n      })\n    )).type.toBe<Option.Option<Array<string>>>()\n\n    // Array\n    expect(Array.modifyOption(numbers, 0, (n) => {\n      expect(n).type.toBe<number>()\n      return \"a\"\n    })).type.toBe<Option.Option<Array<string | number>>>()\n    expect(pipe(\n      numbers,\n      Array.modifyOption(0, (n) => {\n        expect(n).type.toBe<number>()\n        return \"a\"\n      })\n    )).type.toBe<Option.Option<Array<string | number>>>()\n\n    // NonEmptyArray\n    expect(Array.modifyOption(nonEmptyNumbers, 0, (n) => {\n      expect(n).type.toBe<number>()\n      return \"a\" as const\n    })).type.toBe<Option.Option<[number | \"a\", ...Array<number | \"a\">]>>()\n    expect(pipe(\n      nonEmptyNumbers,\n      Array.modifyOption(0, (n) => {\n        expect(n).type.toBe<number>()\n        return \"a\" as const\n      })\n    )).type.toBe<Option.Option<[number | \"a\", ...Array<number | \"a\">]>>()\n\n    // Iterable\n    expect(Array.modifyOption(new Set([1, 2] as const), 0, (n) => {\n      expect(n).type.toBe<1 | 2>()\n      return \"a\" as const\n    })).type.toBe<Option.Option<Array<\"a\" | 1 | 2>>>()\n    expect(pipe(\n      new Set([1, 2] as const),\n      Array.modifyOption(0, (n) => {\n        expect(n).type.toBe<1 | 2>()\n        return \"a\" as const\n      })\n    )).type.toBe<Option.Option<Array<\"a\" | 1 | 2>>>()\n  })\n\n  it(\"mapAccum\", () => {\n    // Array\n    expect(Array.mapAccum(strings, 0, (s, a, i) => {\n      expect(s).type.toBe<number>()\n      expect(a).type.toBe<string>()\n      expect(i).type.toBe<number>()\n      return [s + i, a]\n    })).type.toBe<[state: number, mappedArray: Array<string>]>()\n    expect(pipe(\n      strings,\n      Array.mapAccum(0, (s, a, i) => {\n        expect(s).type.toBe<number>()\n        expect(a).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return [s + i, a]\n      })\n    )).type.toBe<[state: number, mappedArray: Array<string>]>()\n\n    // NonEmptyArray\n    expect(Array.mapAccum(nonEmptyReadonlyStrings, 0, (s, a, i) => {\n      expect(s).type.toBe<number>()\n      expect(a).type.toBe<string>()\n      expect(i).type.toBe<number>()\n      return [s + i, a]\n    })).type.toBe<[state: number, mappedArray: [string, ...Array<string>]]>()\n    expect(pipe(\n      nonEmptyReadonlyStrings,\n      Array.mapAccum(0, (s, a, i) => {\n        expect(s).type.toBe<number>()\n        expect(a).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return [s + i, a]\n      })\n    )).type.toBe<[state: number, mappedArray: [string, ...Array<string>]]>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Cause.tst.ts",
    "content": "import type { Predicate } from \"effect\"\nimport { Cause, hole, pipe } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const cause1: Cause.Cause<\"err-1\">\ndeclare const cause2: Cause.Cause<\"err-2\">\n\ndescribe(\"Cause\", () => {\n  it(\"andThen\", () => {\n    expect(Cause.andThen(cause1, cause2)).type.toBe<Cause.Cause<\"err-2\">>()\n    expect(Cause.andThen(cause1, () => cause2)).type.toBe<Cause.Cause<\"err-2\">>()\n\n    expect(cause1.pipe(Cause.andThen(cause2))).type.toBe<Cause.Cause<\"err-2\">>()\n    expect(cause1.pipe(Cause.andThen(() => cause2))).type.toBe<Cause.Cause<\"err-2\">>()\n  })\n\n  it(\"filter\", () => {\n    const predicate = hole<Predicate.Predicate<Cause.Cause<string>>>()\n    expect(Cause.filter(cause1, predicate)).type.toBe<Cause.Cause<\"err-1\">>()\n    expect(pipe(cause1, Cause.filter(predicate))).type.toBe<Cause.Cause<\"err-1\">>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Chunk.tst.ts",
    "content": "import type { Option } from \"effect\"\nimport { Chunk, Effect, hole, pipe, Predicate } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const numbers: Chunk.Chunk<number>\ndeclare const strings: Chunk.Chunk<string>\ndeclare const nonEmptyNumbers: Chunk.NonEmptyChunk<number>\ndeclare const nonEmptyStrings: Chunk.NonEmptyChunk<string>\ndeclare const numbersOrStrings: Chunk.Chunk<number | string>\ndeclare const predicateNumbersOrStrings: Predicate.Predicate<number | string>\n\ndescribe(\"Chunk\", () => {\n  it(\"every\", () => {\n    if (Chunk.every(numbersOrStrings, Predicate.isString)) {\n      expect(numbersOrStrings).type.toBe<Chunk.Chunk<string>>()\n    }\n    if (Chunk.every(Predicate.isString)(numbersOrStrings)) {\n      expect(numbersOrStrings).type.toBe<Chunk.Chunk<string>>()\n    }\n\n    expect(Chunk.every(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })).type.toBe<boolean>()\n    expect(pipe(\n      numbersOrStrings,\n      Chunk.every((item) => {\n        expect(item).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<boolean>()\n  })\n\n  it(\"some\", () => {\n    if (Chunk.some(numbersOrStrings, Predicate.isString)) {\n      expect(numbersOrStrings).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n    }\n\n    expect(\n      Chunk.some(numbersOrStrings, (item) => {\n        expect(item).type.toBe<string | number>()\n        return true\n      })\n    ).type.toBe<boolean>()\n    expect(pipe(\n      numbersOrStrings,\n      Chunk.some((item) => {\n        expect(item).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<boolean>()\n  })\n\n  it(\"partition\", () => {\n    expect(Chunk.partition(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })).type.toBe<[excluded: Chunk.Chunk<string | number>, satisfying: Chunk.Chunk<string | number>]>()\n    expect(pipe(\n      numbersOrStrings,\n      Chunk.partition((item) => {\n        expect(item).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<[excluded: Chunk.Chunk<string | number>, satisfying: Chunk.Chunk<string | number>]>()\n\n    expect(Chunk.partition(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<\n      [excluded: Chunk.Chunk<string | number>, satisfying: Chunk.Chunk<string | number>]\n    >()\n    expect(pipe(numbersOrStrings, Chunk.partition(predicateNumbersOrStrings))).type.toBe<\n      [excluded: Chunk.Chunk<string | number>, satisfying: Chunk.Chunk<string | number>]\n    >()\n\n    expect(Chunk.partition(numbers, predicateNumbersOrStrings)).type.toBe<\n      [excluded: Chunk.Chunk<number>, satisfying: Chunk.Chunk<number>]\n    >()\n    expect(pipe(numbers, Chunk.partition(predicateNumbersOrStrings))).type.toBe<\n      [excluded: Chunk.Chunk<number>, satisfying: Chunk.Chunk<number>]\n    >()\n\n    expect(Chunk.partition(numbersOrStrings, Predicate.isNumber)).type.toBe<\n      [excluded: Chunk.Chunk<string>, satisfying: Chunk.Chunk<number>]\n    >()\n    expect(pipe(numbersOrStrings, Chunk.partition(Predicate.isNumber))).type.toBe<\n      [excluded: Chunk.Chunk<string>, satisfying: Chunk.Chunk<number>]\n    >()\n  })\n\n  it(\"append\", () => {\n    expect(Chunk.append(numbersOrStrings, true)).type.toBe<Chunk.NonEmptyChunk<string | number | boolean>>()\n    expect(pipe(numbersOrStrings, Chunk.append(true))).type.toBe<Chunk.NonEmptyChunk<string | number | boolean>>()\n    expect(Chunk.append(true)(numbersOrStrings)).type.toBe<Chunk.NonEmptyChunk<string | number | boolean>>()\n  })\n\n  it(\"prepend\", () => {\n    expect(Chunk.prepend(numbersOrStrings, true)).type.toBe<Chunk.NonEmptyChunk<string | number | boolean>>()\n    expect(pipe(numbersOrStrings, Chunk.prepend(true))).type.toBe<Chunk.NonEmptyChunk<string | number | boolean>>()\n    expect(Chunk.prepend(true)(numbersOrStrings)).type.toBe<Chunk.NonEmptyChunk<string | number | boolean>>()\n  })\n\n  it(\"map\", () => {\n    // Chunk\n    expect(Chunk.map(strings, (s, i) => {\n      expect(s).type.toBe<string>()\n      expect(i).type.toBe<number>()\n      return s + \"a\"\n    })).type.toBe<Chunk.Chunk<string>>()\n    expect(pipe(\n      strings,\n      Chunk.map((s, i) => {\n        expect(s).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return s + \"a\"\n      })\n    )).type.toBe<Chunk.Chunk<string>>()\n\n    // NonEmptyChunk\n    expect(Chunk.map(nonEmptyStrings, (s, i) => {\n      expect(s).type.toBe<string>()\n      expect(i).type.toBe<number>()\n      return s + \"a\"\n    })).type.toBe<Chunk.NonEmptyChunk<string>>()\n    expect(pipe(\n      nonEmptyStrings,\n      Chunk.map((s, i) => {\n        expect(s).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return s + \"a\"\n      })\n    )).type.toBe<Chunk.NonEmptyChunk<string>>()\n  })\n\n  it(\"filter\", () => {\n    Chunk.filter(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })\n    expect(\n      pipe(\n        numbersOrStrings,\n        Chunk.filter((item) => {\n          expect(item).type.toBe<string | number>()\n          return true\n        })\n      )\n    ).type.toBe<Chunk.Chunk<string | number>>()\n    expect(\n      Chunk.filter(numbersOrStrings, predicateNumbersOrStrings)\n    ).type.toBe<Chunk.Chunk<string | number>>()\n    expect(\n      pipe(numbersOrStrings, Chunk.filter(predicateNumbersOrStrings))\n    ).type.toBe<Chunk.Chunk<string | number>>()\n\n    expect(\n      Chunk.filter(numbers, predicateNumbersOrStrings)\n    ).type.toBe<Chunk.Chunk<number>>()\n    expect(\n      pipe(numbers, Chunk.filter(predicateNumbersOrStrings))\n    ).type.toBe<Chunk.Chunk<number>>()\n\n    expect(\n      Chunk.filter(numbersOrStrings, Predicate.isNumber)\n    ).type.toBe<Chunk.Chunk<number>>()\n    expect(\n      pipe(numbersOrStrings, Chunk.filter(Predicate.isNumber))\n    ).type.toBe<Chunk.Chunk<number>>()\n  })\n\n  it(\"takeWhile\", () => {\n    Chunk.takeWhile(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })\n    expect(\n      pipe(\n        numbersOrStrings,\n        Chunk.takeWhile((item) => {\n          expect(item).type.toBe<string | number>()\n          return true\n        })\n      )\n    ).type.toBe<Chunk.Chunk<string | number>>()\n\n    expect(\n      Chunk.takeWhile(numbersOrStrings, predicateNumbersOrStrings)\n    ).type.toBe<Chunk.Chunk<string | number>>()\n    expect(\n      pipe(numbersOrStrings, Chunk.takeWhile(predicateNumbersOrStrings))\n    ).type.toBe<Chunk.Chunk<string | number>>()\n\n    expect(Chunk.takeWhile(numbers, predicateNumbersOrStrings)).type.toBe<\n      Chunk.Chunk<number>\n    >()\n    expect(\n      pipe(numbers, Chunk.takeWhile(predicateNumbersOrStrings))\n    ).type.toBe<Chunk.Chunk<number>>()\n\n    expect(\n      Chunk.takeWhile(numbersOrStrings, Predicate.isNumber)\n    ).type.toBe<Chunk.Chunk<number>>()\n    expect(\n      pipe(numbersOrStrings, Chunk.takeWhile(Predicate.isNumber))\n    ).type.toBe<Chunk.Chunk<number>>()\n  })\n\n  it(\"findFirst\", () => {\n    Chunk.findFirst(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })\n    expect(\n      pipe(\n        numbersOrStrings,\n        Chunk.findFirst((_item) => {\n          expect(_item).type.toBe<string | number>()\n          return true\n        })\n      )\n    ).type.toBe<Option.Option<string | number>>()\n\n    expect(Chunk.findFirst(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<Option.Option<string | number>>()\n    expect(pipe(numbersOrStrings, Chunk.findFirst(predicateNumbersOrStrings))).type.toBe<\n      Option.Option<string | number>\n    >()\n\n    expect(Chunk.findFirst(numbersOrStrings, Predicate.isNumber)).type.toBe<Option.Option<number>>()\n    expect(pipe(numbersOrStrings, Chunk.findFirst(Predicate.isNumber))).type.toBe<Option.Option<number>>()\n  })\n\n  it(\"findLast\", () => {\n    Chunk.findLast(numbersOrStrings, (_item) => {\n      expect(_item).type.toBe<string | number>()\n      return true\n    })\n    expect(\n      pipe(\n        numbersOrStrings,\n        Chunk.findLast((_item) => {\n          expect(_item).type.toBe<string | number>()\n          return true\n        })\n      )\n    ).type.toBe<Option.Option<string | number>>()\n\n    expect(Chunk.findLast(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<Option.Option<string | number>>()\n    expect(pipe(numbersOrStrings, Chunk.findLast(predicateNumbersOrStrings))).type.toBe<\n      Option.Option<string | number>\n    >()\n\n    expect(Chunk.findLast(numbersOrStrings, Predicate.isNumber)).type.toBe<Option.Option<number>>()\n    expect(pipe(numbersOrStrings, Chunk.findLast(Predicate.isNumber))).type.toBe<Option.Option<number>>()\n  })\n\n  it(\"dropWhile\", () => {\n    Chunk.dropWhile(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })\n    expect(\n      pipe(\n        numbersOrStrings,\n        Chunk.dropWhile((item) => {\n          expect(item).type.toBe<string | number>()\n          return true\n        })\n      )\n    ).type.toBe<Chunk.Chunk<string | number>>()\n\n    expect(Chunk.dropWhile(numbers, predicateNumbersOrStrings)).type.toBe<Chunk.Chunk<number>>()\n    expect(pipe(numbers, Chunk.dropWhile(predicateNumbersOrStrings))).type.toBe<Chunk.Chunk<number>>()\n\n    expect(Chunk.dropWhile(numbersOrStrings, Predicate.isNumber)).type.toBe<Chunk.Chunk<string | number>>()\n    expect(pipe(numbersOrStrings, Chunk.dropWhile(Predicate.isNumber))).type.toBe<Chunk.Chunk<string | number>>()\n  })\n\n  it(\"splitWhere\", () => {\n    Chunk.splitWhere(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })\n    expect(\n      pipe(\n        numbersOrStrings,\n        Chunk.splitWhere((item) => {\n          expect(item).type.toBe<string | number>()\n          return true\n        })\n      )\n    ).type.toBe<\n      [beforeMatch: Chunk.Chunk<string | number>, fromMatch: Chunk.Chunk<string | number>]\n    >()\n\n    expect(Chunk.splitWhere(numbers, predicateNumbersOrStrings))\n      .type.toBe<[beforeMatch: Chunk.Chunk<number>, fromMatch: Chunk.Chunk<number>]>()\n    expect(pipe(numbers, Chunk.splitWhere(predicateNumbersOrStrings)))\n      .type.toBe<[beforeMatch: Chunk.Chunk<number>, fromMatch: Chunk.Chunk<number>]>()\n\n    expect(Chunk.splitWhere(numbersOrStrings, Predicate.isNumber))\n      .type.toBe<[beforeMatch: Chunk.Chunk<string | number>, fromMatch: Chunk.Chunk<string | number>]>()\n    expect(pipe(numbersOrStrings, Chunk.splitWhere(Predicate.isNumber)))\n      .type.toBe<[beforeMatch: Chunk.Chunk<string | number>, fromMatch: Chunk.Chunk<string | number>]>()\n  })\n\n  it(\"prependAll\", () => {\n    // Chunk + Chunk\n    expect(Chunk.prependAll(strings, numbers)).type.toBe<Chunk.Chunk<string | number>>()\n    expect(pipe(strings, Chunk.prependAll(numbers))).type.toBe<Chunk.Chunk<string | number>>()\n\n    // NonEmptyChunk + Chunk\n    expect(Chunk.prependAll(nonEmptyStrings, numbers)).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n    expect(pipe(nonEmptyStrings, Chunk.prependAll(numbers))).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n\n    // Chunk + NonEmptyChunk\n    expect(Chunk.prependAll(strings, nonEmptyNumbers)).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n    expect(pipe(strings, Chunk.prependAll(nonEmptyNumbers))).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n\n    // NonEmptyChunk + NonEmptyChunk\n    expect(Chunk.prependAll(nonEmptyStrings, nonEmptyNumbers)).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n    expect(pipe(nonEmptyStrings, Chunk.prependAll(nonEmptyNumbers))).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n  })\n\n  it(\"appendAll\", () => {\n    // Chunk + Chunk\n    expect(Chunk.appendAll(strings, numbers)).type.toBe<Chunk.Chunk<string | number>>()\n    expect(pipe(strings, Chunk.appendAll(numbers))).type.toBe<Chunk.Chunk<string | number>>()\n\n    // NonEmptyChunk + Chunk\n    expect(Chunk.appendAll(nonEmptyStrings, numbers)).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n    expect(pipe(nonEmptyStrings, Chunk.appendAll(numbers))).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n\n    // Chunk + NonEmptyChunk\n    expect(Chunk.appendAll(strings, nonEmptyNumbers)).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n    expect(pipe(strings, Chunk.appendAll(nonEmptyNumbers))).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n\n    // NonEmptyChunk + NonEmptyChunk\n    expect(Chunk.appendAll(nonEmptyStrings, nonEmptyNumbers)).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n    expect(pipe(nonEmptyStrings, Chunk.appendAll(nonEmptyNumbers))).type.toBe<Chunk.NonEmptyChunk<string | number>>()\n  })\n\n  it(\"flatMap\", () => {\n    // Chunk + Chunk\n    expect(\n      Chunk.flatMap(strings, (s, i) => {\n        expect(s).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return Chunk.empty<number>()\n      })\n    ).type.toBe<Chunk.Chunk<number>>()\n    expect(\n      pipe(\n        strings,\n        Chunk.flatMap((s, i) => {\n          expect(s).type.toBe<string>()\n          expect(i).type.toBe<number>()\n          return Chunk.empty<number>()\n        })\n      )\n    ).type.toBe<Chunk.Chunk<number>>()\n\n    // NonEmptyChunk + Chunk\n    expect(\n      Chunk.flatMap(nonEmptyStrings, (s, i) => {\n        expect(s).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return Chunk.empty<number>()\n      })\n    ).type.toBe<Chunk.Chunk<number>>()\n    expect(\n      pipe(\n        nonEmptyStrings,\n        Chunk.flatMap((s, i) => {\n          expect(s).type.toBe<string>()\n          expect(i).type.toBe<number>()\n          return Chunk.empty<number>()\n        })\n      )\n    ).type.toBe<Chunk.Chunk<number>>()\n\n    // NonEmptyChunk + NonEmptyChunk\n    expect(\n      Chunk.flatMap(nonEmptyStrings, (s, i) => {\n        expect(s).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return Chunk.of(s.length)\n      })\n    ).type.toBe<Chunk.NonEmptyChunk<number>>()\n    expect(\n      pipe(\n        nonEmptyStrings,\n        Chunk.flatMap((s, i) => {\n          expect(s).type.toBe<string>()\n          expect(i).type.toBe<number>()\n          return Chunk.of(s.length)\n        })\n      )\n    ).type.toBe<Chunk.NonEmptyChunk<number>>()\n  })\n\n  it(\"flatten\", () => {\n    expect(Chunk.flatten(hole<Chunk.Chunk<Chunk.Chunk<number>>>())).type.toBe<Chunk.Chunk<number>>()\n    expect(pipe(hole<Chunk.Chunk<Chunk.Chunk<number>>>(), Chunk.flatten)).type.toBe<Chunk.Chunk<number>>()\n\n    expect(Chunk.flatten(hole<Chunk.Chunk<Chunk.NonEmptyChunk<number>>>())).type.toBe<Chunk.Chunk<number>>()\n    expect(pipe(hole<Chunk.Chunk<Chunk.NonEmptyChunk<number>>>(), Chunk.flatten)).type.toBe<Chunk.Chunk<number>>()\n\n    expect(Chunk.flatten(hole<Chunk.NonEmptyChunk<Chunk.Chunk<number>>>())).type.toBe<Chunk.Chunk<number>>()\n    expect(pipe(hole<Chunk.NonEmptyChunk<Chunk.Chunk<number>>>(), Chunk.flatten)).type.toBe<Chunk.Chunk<number>>()\n\n    expect(Chunk.flatten(hole<Chunk.NonEmptyChunk<Chunk.NonEmptyChunk<number>>>()))\n      .type.toBe<Chunk.NonEmptyChunk<number>>()\n    expect(pipe(hole<Chunk.NonEmptyChunk<Chunk.NonEmptyChunk<number>>>(), Chunk.flatten))\n      .type.toBe<Chunk.NonEmptyChunk<number>>()\n\n    const nestedChunk = hole<Effect.Effect<Chunk.Chunk<Chunk.Chunk<number>>, never, never>>()\n    const nestedNonEmptyChunk = hole<Effect.Effect<Chunk.NonEmptyChunk<Chunk.NonEmptyChunk<number>>, never, never>>()\n\n    expect(nestedChunk.pipe(Effect.map((x) => {\n      expect(x).type.toBe<Chunk.Chunk<Chunk.Chunk<number>>>()\n      return Chunk.flatten(x)\n    }))).type.toBe<\n      Effect.Effect<Chunk.Chunk<number>, never, never>\n    >()\n    expect(nestedChunk.pipe(Effect.map(Chunk.flatten))).type.toBe<\n      Effect.Effect<Chunk.Chunk<number>, never, never>\n    >()\n    expect(nestedNonEmptyChunk.pipe(Effect.map((x) => {\n      expect(x).type.toBe<Chunk.NonEmptyChunk<Chunk.NonEmptyChunk<number>>>()\n      return Chunk.flatten(x)\n    }))).type.toBe<\n      Effect.Effect<Chunk.NonEmptyChunk<number>, never, never>\n    >()\n    expect(nestedNonEmptyChunk.pipe(Effect.map(Chunk.flatten))).type.toBe<\n      Effect.Effect<Chunk.NonEmptyChunk<number>, never, never>\n    >()\n  })\n\n  it(\"reverse\", () => {\n    // Chunk\n    expect(Chunk.reverse(numbers)).type.toBe<Chunk.Chunk<number>>()\n    expect(pipe(numbers, Chunk.reverse)).type.toBe<Chunk.Chunk<number>>()\n\n    // NonEmptyChunk\n    expect(Chunk.reverse(nonEmptyNumbers)).type.toBe<Chunk.NonEmptyChunk<number>>()\n    expect(pipe(nonEmptyNumbers, Chunk.reverse)).type.toBe<Chunk.NonEmptyChunk<number>>()\n  })\n\n  it(\"toArray\", () => {\n    // Chunk\n    expect(Chunk.toArray(hole<Chunk.Chunk<string>>())).type.toBe<Array<string>>()\n    expect(pipe(hole<Chunk.Chunk<string>>(), Chunk.toArray)).type.toBe<Array<string>>()\n\n    // NonEmptyChunk\n    expect(Chunk.toArray(hole<Chunk.NonEmptyChunk<string>>())).type.toBe<[string, ...Array<string>]>()\n    expect(pipe(hole<Chunk.NonEmptyChunk<string>>(), Chunk.toArray)).type.toBe<[string, ...Array<string>]>()\n  })\n\n  it(\"toReadonlyArray\", () => {\n    // Chunk\n    expect(Chunk.toReadonlyArray(hole<Chunk.Chunk<string>>())).type.toBe<ReadonlyArray<string>>()\n    expect(pipe(hole<Chunk.Chunk<string>>(), Chunk.toReadonlyArray)).type.toBe<ReadonlyArray<string>>()\n\n    // NonEmptyChunk\n    expect(Chunk.toReadonlyArray(hole<Chunk.NonEmptyChunk<string>>())).type.toBe<\n      readonly [string, ...Array<string>]\n    >()\n    expect(pipe(hole<Chunk.NonEmptyChunk<string>>(), Chunk.toReadonlyArray)).type.toBe<\n      readonly [string, ...Array<string>]\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Config.tst.ts",
    "content": "import { Brand, Config, hole, pipe } from \"effect\"\nimport { describe, expect, it, when } from \"tstyche\"\n\ndeclare const string: Config.Config<string>\ndeclare const number: Config.Config<number>\ndeclare const array: Array<Config.Config<string>>\ndeclare const record: Record<string, Config.Config<number>>\n\ntype Int = Brand.Branded<number, \"Int\">\nconst Int = Brand.refined<Int>(\n  (n) => Number.isInteger(n),\n  (n) => Brand.error(`Expected ${n} to be an integer`)\n)\n\ntype Str = Brand.Branded<string, \"Str\">\nconst Str = Brand.refined<Str>(\n  (n) => n.length > 2,\n  (n) => Brand.error(`Expected \"${n}\" to be longer than 2`)\n)\n\ndescribe(\"Config\", () => {\n  describe(\"all\", () => {\n    it(\"tuple\", () => {\n      expect(Config.all([string, number])).type.toBe<Config.Config<[string, number]>>()\n      expect(pipe([string, number] as const, Config.all)).type.toBe<Config.Config<[string, number]>>()\n    })\n\n    it(\"struct\", () => {\n      expect(Config.all({ a: string, b: number })).type.toBe<Config.Config<{ a: string; b: number }>>()\n      expect(pipe({ a: string, b: number }, Config.all)).type.toBe<Config.Config<{ a: string; b: number }>>()\n    })\n\n    it(\"array\", () => {\n      expect(Config.all(array)).type.toBe<Config.Config<Array<string>>>()\n      expect(pipe(array, Config.all)).type.toBe<Config.Config<Array<string>>>()\n    })\n\n    it(\"record\", () => {\n      expect(Config.all(record)).type.toBe<Config.Config<Record<string, number>>>()\n      expect(pipe(record, Config.all)).type.toBe<Config.Config<Record<string, number>>>()\n    })\n  })\n\n  it(\"branded\", () => {\n    expect(Config.branded).type.not.toBeCallableWith(\"NAME\", Int)\n    expect(Config.branded).type.not.toBeCallableWith(number, Str)\n    when(number.pipe).isCalledWith(expect(Config.branded).type.not.toBeCallableWith(Str))\n\n    expect(Config.branded(number, Int)).type.toBe<Config.Config<Int>>()\n    expect(Config.branded(\"NAME\", Str)).type.toBe<Config.Config<Str>>()\n    expect(number.pipe(Config.branded(Int))).type.toBe<Config.Config<Int>>()\n    expect(pipe([string, number] as const, Config.all)).type.toBe<Config.Config<[string, number]>>()\n  })\n\n  it(\"orElseIf\", () => {\n    expect(Config.orElseIf(number, {\n      if: hole(),\n      orElse: () => string\n    })).type.toBe<Config.Config<number | string>>()\n  })\n\n  it(\"Config.Success helper type\", () => {\n    expect(hole<Config.Config.Success<typeof string>>()).type.toBe<string>()\n    expect(hole<Config.Config.Success<typeof number>>()).type.toBe<number>()\n    const _config = Config.all({ a: string, b: number })\n    expect(hole<Config.Config.Success<typeof _config>>()).type.toBe<{ a: string; b: number }>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/ConfigProvider.tst.ts",
    "content": "import { ConfigProvider } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"ConfigProvider\", () => {\n  describe(\"fromEnv\", () => {\n    it(\"should accept a partial configuration\", () => {\n      expect(ConfigProvider.fromEnv({ pathDelim: \".\" })).type.toBe<ConfigProvider.ConfigProvider>()\n      expect(ConfigProvider.fromEnv({ seqDelim: \".\" })).type.toBe<ConfigProvider.ConfigProvider>()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Context.tst.ts",
    "content": "import { Context, Effect } from \"effect\"\nimport { describe, expect, it, when } from \"tstyche\"\n\ndescribe(\"Context\", () => {\n  it(\"`key` field\", () => {\n    class A extends Effect.Service<A>()(\"A\", { succeed: { a: \"value\" } }) {}\n    expect(A.key).type.toBe<\"A\">()\n\n    class B extends Context.Tag(\"B\")<B, { a: \"value\" }>() {}\n    expect(B.key).type.toBe<\"B\">()\n\n    class C extends Context.Reference<C>()(\"C\", { defaultValue: () => 0 }) {}\n    expect(C.key).type.toBe<\"C\">()\n  })\n  it(\"Tag with static fields\", () => {\n    class Foo extends Context.Tag(\"Foo\")<Foo, { readonly bar: string }>() {\n      static readonly StaticField = \"StaticField\"\n    }\n\n    when(Context.empty().pipe).isCalledWith(expect(Context.add).type.not.toBeCallableWith(Foo, 123))\n\n    const ctx = Context.empty().pipe(Context.add(Foo, { bar: \"2\" }))\n    expect(ctx).type.toBe<Context.Context<Foo>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Data.tst.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport * as Data from \"effect/Data\"\nimport { describe, expect, it, pick } from \"tstyche\"\n\ndeclare const readonlyStruct: { readonly a: string }\ndeclare const struct: { a: string }\n\ndeclare const readonlyArray: ReadonlyArray<string>\ndeclare const array: Array<string>\n\ndescribe(\"Data\", () => {\n  it(\"struct\", () => {\n    // Create a readonly struct from a mutable one\n    const struct1 = Data.struct(struct)\n    expect(struct1).type.toBe<{ readonly a: string }>()\n\n    // Create a readonly struct from a readonly one\n    const struct2 = Data.struct(readonlyStruct)\n    expect(struct2).type.toBe<{ readonly a: string }>()\n  })\n\n  it(\"unsafeStruct\", () => {\n    const struct3 = Data.unsafeStruct(struct)\n    expect(struct3).type.toBe<{ readonly a: string }>()\n\n    const struct4 = Data.unsafeStruct(readonlyStruct)\n    expect(struct4).type.toBe<{ readonly a: string }>()\n  })\n\n  it(\"tuple\", () => {\n    const tuple1 = Data.tuple(\"a\", 1)\n    expect(tuple1).type.toBe<readonly [string, number]>()\n  })\n\n  it(\"array\", () => {\n    const array1 = Data.array(array)\n    expect(array1).type.toBe<ReadonlyArray<string>>()\n\n    const array2 = Data.array(readonlyArray)\n    expect(array2).type.toBe<ReadonlyArray<string>>()\n  })\n\n  it(\"unsafeArray\", () => {\n    const array3 = Data.unsafeArray(array)\n    expect(array3).type.toBe<ReadonlyArray<string>>()\n\n    const array4 = Data.unsafeArray(readonlyArray)\n    expect(array4).type.toBe<ReadonlyArray<string>>()\n  })\n\n  it(\"case\", () => {\n    interface Person {\n      readonly name: string\n    }\n    const makePerson = Data.case<Person>()\n\n    expect(makePerson).type.toBe<(args: { readonly name: string }) => Person>()\n\n    const person = makePerson({ name: \"Mike\" })\n\n    // fields should be readonly\n    expect(person).type.toBe<{ readonly name: string }>()\n  })\n\n  it(\"tagged\", () => {\n    interface TaggedPerson {\n      readonly _tag: \"Person\"\n      readonly name: string\n      readonly optional?: string\n    }\n    const taggedPerson = Data.tagged<TaggedPerson>(\"Person\")\n\n    expect(taggedPerson).type.toBe<(args: { readonly name: string; readonly optional?: string }) => TaggedPerson>()\n  })\n\n  it(\"Class\", () => {\n    class Person extends Data.Class<{ name: string; age?: number }> {}\n    const person = new Person({ name: \"Mike\" })\n    // fields should be readonly\n    expect(person).type.toBe<{ readonly name: string; readonly age?: number }>()\n\n    class Void extends Data.Class {}\n    // void constructor\n    expect<ConstructorParameters<typeof Void>>().type.toBe<[args?: void]>()\n  })\n\n  it(\"TaggedClass\", () => {\n    class Person extends Data.TaggedClass(\"Person\")<{ name: string; age?: number }> {}\n    const person = new Person({ name: \"Mike\" })\n    // fields should be readonly\n    expect(person).type.toBe<{ readonly name: string; readonly age?: number; readonly _tag: \"Person\" }>()\n\n    class Void extends Data.TaggedClass(\"Void\") {}\n    // void constructor\n    expect<ConstructorParameters<typeof Void>>().type.toBe<[args?: void]>()\n  })\n\n  it(\"Error\", () => {\n    class Err extends Data.Error<{ message: string; a: number; optional?: string }> {}\n    const err = new Err({ message: \"Oh no!\", a: 1 })\n\n    // assignable to Error\n    expect<Err>().type.toBeAssignableTo<Error>()\n\n    // non-Error fields should be readonly\n    expect(pick(err, \"message\", \"a\", \"optional\")).type.toBe<\n      { message: string; readonly a: number; readonly optional?: string }\n    >()\n\n    class Void extends Data.Error {}\n    // void constructor\n    expect<ConstructorParameters<typeof Void>>().type.toBe<[args?: void]>()\n  })\n\n  it(\"TaggedError\", () => {\n    class Err extends Data.TaggedError(\"Foo\")<{ message?: string; a: number }> {}\n    // Test optional props are allowed\n    new Err({ a: 1 })\n\n    // assignable to Error\n    expect<Err>().type.toBeAssignableTo<Error>()\n\n    const err = new Err({ message: \"Oh no!\", a: 1 })\n\n    // non-Error fields should be readonly\n    expect(pick(err, \"message\", \"a\")).type.toBe<{ message: string; readonly a: number }>()\n\n    class Void extends Data.TaggedError(\"Foo\") {}\n    // void constructor\n    expect<ConstructorParameters<typeof Void>>().type.toBe<[args?: void]>()\n  })\n\n  describe(\"TaggedEnum\", () => {\n    it(\"should be able to create a tagged enum\", () => {\n      type TE = Data.TaggedEnum<{\n        A: { readonly required: string }\n        B: { readonly optional?: number }\n      }>\n      expect<Extract<TE, { _tag: \"A\" }>>().type.toBe<\n        { readonly _tag: \"A\"; readonly required: string }\n      >()\n      expect<Extract<TE, { _tag: \"B\" }>>().type.toBe<\n        { readonly _tag: \"B\"; readonly optional?: number }\n      >()\n    })\n\n    it(\"should raise an error if one of the variants has a _tag property\", () => {\n      // @ts-expect-error: It looks like you're trying to create a tagged enum, but one or more of its members already has a `_tag` property.\n      type TE = Data.TaggedEnum<{\n        A: { readonly _tag: \"A\" }\n        B: { readonly b: number }\n      }>\n    })\n  })\n\n  describe(\"taggedEnum\", () => {\n    it(\"should be able to create a concrete tagged enum\", () => {\n      type TE = Data.TaggedEnum<{\n        A: { readonly required: string }\n        B: { readonly optional?: number }\n      }>\n\n      const { $is, A, B } = Data.taggedEnum<TE>()\n      expect<Parameters<typeof A>>().type.toBe<[{ readonly required: string }]>()\n      expect<ReturnType<typeof A>>().type.toBe<{ readonly _tag: \"A\"; readonly required: string }>()\n      expect<Parameters<typeof B>>().type.toBe<[{ readonly optional?: number }]>()\n      expect<ReturnType<typeof B>>().type.toBe<{ readonly _tag: \"B\"; readonly optional?: number }>()\n      const isA = $is(\"A\")\n      expect(isA).type.toBe<\n        (u: unknown) => u is { readonly _tag: \"A\"; readonly required: string }\n      >()\n      const isB = $is(\"B\")\n      expect(isB).type.toBe<\n        (u: unknown) => u is { readonly _tag: \"B\"; readonly optional?: number }\n      >()\n    })\n\n    it(\"should be able to create a generic tagged enum\", () => {\n      type TE<T> = Data.TaggedEnum<{\n        A: { a: T }\n        B: { b?: T }\n      }>\n\n      interface TEDefinition extends Data.TaggedEnum.WithGenerics<1> {\n        readonly taggedEnum: TE<this[\"A\"]>\n      }\n\n      const { A, B } = Data.taggedEnum<TEDefinition>()\n      expect<typeof A>().type.toBe<(<A>(args: { readonly a: A }) => { readonly _tag: \"A\"; readonly a: A })>()\n      expect<typeof B>().type.toBe<(<B>(args: { readonly b?: B }) => { readonly _tag: \"B\"; readonly b?: B })>()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/DateTime.tst.ts",
    "content": "import * as DateTime from \"effect/DateTime\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const utc: DateTime.Utc\ndeclare const zoned: DateTime.Zoned\ndeclare const dateTime: DateTime.DateTime\n\ndescribe(\"DateTime\", () => {\n  it(\"min\", () => {\n    expect(DateTime.min(utc, zoned)).type.toBe<DateTime.Utc | DateTime.Zoned>()\n    expect(DateTime.min(utc, utc)).type.toBe<DateTime.Utc>()\n    expect(DateTime.min(zoned, zoned)).type.toBe<DateTime.Zoned>()\n    expect(DateTime.min(dateTime, zoned)).type.toBe<DateTime.DateTime>()\n    expect(DateTime.min(dateTime, utc)).type.toBe<DateTime.DateTime>()\n    expect(DateTime.min(dateTime, dateTime)).type.toBe<DateTime.DateTime>()\n\n    expect(utc.pipe(DateTime.min(zoned))).type.toBe<DateTime.Utc | DateTime.Zoned>()\n    expect(zoned.pipe(DateTime.min(utc))).type.toBe<DateTime.Utc | DateTime.Zoned>()\n    expect(utc.pipe(DateTime.min(utc))).type.toBe<DateTime.Utc>()\n    expect(zoned.pipe(DateTime.min(zoned))).type.toBe<DateTime.Zoned>()\n    expect(dateTime.pipe(DateTime.min(zoned))).type.toBe<DateTime.DateTime>()\n    expect(dateTime.pipe(DateTime.min(utc))).type.toBe<DateTime.DateTime>()\n    expect(dateTime.pipe(DateTime.min(dateTime))).type.toBe<DateTime.DateTime>()\n  })\n\n  it(\"max\", () => {\n    expect(DateTime.max(utc, zoned)).type.toBe<DateTime.Utc | DateTime.Zoned>()\n    expect(DateTime.max(utc, utc)).type.toBe<DateTime.Utc>()\n    expect(DateTime.max(zoned, zoned)).type.toBe<DateTime.Zoned>()\n    expect(DateTime.max(dateTime, zoned)).type.toBe<DateTime.DateTime>()\n    expect(DateTime.max(dateTime, utc)).type.toBe<DateTime.DateTime>()\n    expect(DateTime.max(dateTime, dateTime)).type.toBe<DateTime.DateTime>()\n\n    expect(utc.pipe(DateTime.max(zoned))).type.toBe<DateTime.Utc | DateTime.Zoned>()\n    expect(zoned.pipe(DateTime.max(utc))).type.toBe<DateTime.Utc | DateTime.Zoned>()\n    expect(utc.pipe(DateTime.max(utc))).type.toBe<DateTime.Utc>()\n    expect(zoned.pipe(DateTime.max(zoned))).type.toBe<DateTime.Zoned>()\n    expect(dateTime.pipe(DateTime.max(zoned))).type.toBe<DateTime.DateTime>()\n    expect(dateTime.pipe(DateTime.max(utc))).type.toBe<DateTime.DateTime>()\n    expect(dateTime.pipe(DateTime.max(dateTime))).type.toBe<DateTime.DateTime>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Duration.tst.ts",
    "content": "import type { Option } from \"effect\"\nimport { Duration } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Duration\", () => {\n  it(\"decode\", () => {\n    expect(Duration.decode(100)).type.toBe<Duration.Duration>()\n    expect(Duration.decode(10n)).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"1 nano\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"10 nanos\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"1 micro\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"10 micros\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"1 milli\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"10 millis\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"1 second\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"10 seconds\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"1 minute\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"10 minutes\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"1 hour\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"10 hours\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"1 day\")).type.toBe<Duration.Duration>()\n    expect(Duration.decode(\"10 days\")).type.toBe<Duration.Duration>()\n\n    expect(Duration.decode).type.not.toBeCallableWith(\"10 unknown\")\n  })\n\n  it(\"toMillis\", () => {\n    expect(Duration.toMillis(\"1 millis\")).type.toBe<number>()\n  })\n\n  it(\"toNanos\", () => {\n    expect(Duration.toNanos(\"1 millis\")).type.toBe<Option.Option<bigint>>()\n  })\n\n  it(\"unsafeToNanos\", () => {\n    expect(Duration.unsafeToNanos(\"1 millis\")).type.toBe<bigint>()\n  })\n\n  it(\"toHrTime\", () => {\n    expect(Duration.toHrTime(\"1 millis\")).type.toBe<[seconds: number, nanos: number]>()\n  })\n\n  it(\"match\", () => {\n    expect(Duration.match(\"100 millis\", {\n      onMillis: (n) => {\n        expect(n).type.toBe<number>()\n        return \"millis\"\n      },\n      onNanos: (bi) => {\n        expect(bi).type.toBe<bigint>()\n        return \"nanos\"\n      }\n    })).type.toBe<string>()\n  })\n\n  it(\"between\", () => {\n    expect(Duration.between(\"1 minutes\", { minimum: \"59 seconds\", maximum: \"61 seconds\" })).type.toBe<boolean>()\n  })\n\n  it(\"min\", () => {\n    expect(Duration.min(\"1 minutes\", \"2 millis\")).type.toBe<Duration.Duration>()\n  })\n\n  it(\"max\", () => {\n    expect(Duration.max(\"1 minutes\", \"2 millis\")).type.toBe<Duration.Duration>()\n  })\n\n  it(\"clamp\", () => {\n    expect(Duration.clamp(\"1 millis\", { minimum: \"2 millis\", maximum: \"3 millis\" })).type.toBe<Duration.Duration>()\n  })\n\n  it(\"divide\", () => {\n    expect(Duration.divide(\"1 seconds\", 2)).type.toBe<Option.Option<Duration.Duration>>()\n  })\n\n  it(\"unsafeDivide\", () => {\n    expect(Duration.unsafeDivide(\"1 seconds\", 2)).type.toBe<Duration.Duration>()\n  })\n\n  it(\"times\", () => {\n    expect(Duration.times(\"1 seconds\", 60)).type.toBe<Duration.Duration>()\n  })\n\n  it(\"sum\", () => {\n    expect(Duration.sum(\"30 seconds\", \"30 seconds\")).type.toBe<Duration.Duration>()\n  })\n\n  it(\"greaterThanOrEqualTo\", () => {\n    expect(Duration.greaterThanOrEqualTo(\"2 seconds\", \"2 seconds\")).type.toBe<boolean>()\n  })\n\n  it(\"greaterThan\", () => {\n    expect(Duration.greaterThan(\"2 seconds\", \"2 seconds\")).type.toBe<boolean>()\n  })\n\n  it(\"lessThanOrEqualTo\", () => {\n    expect(Duration.lessThanOrEqualTo(\"2 seconds\", \"2 seconds\")).type.toBe<boolean>()\n  })\n\n  it(\"lessThan\", () => {\n    expect(Duration.lessThan(\"2 seconds\", \"2 seconds\")).type.toBe<boolean>()\n  })\n\n  it(\"equals\", () => {\n    expect(Duration.equals(\"2 seconds\", \"2 seconds\")).type.toBe<boolean>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Effect.tst.ts",
    "content": "import type { Either, Types } from \"effect\"\nimport { Array as Arr, Context, Effect, hole, Option, pipe, Predicate, Schedule } from \"effect\"\nimport type { NonEmptyArray, NonEmptyReadonlyArray } from \"effect/Array\"\nimport type { Cause, NoSuchElementException, UnknownException } from \"effect/Cause\"\nimport type { Exit } from \"effect/Exit\"\nimport { describe, expect, it, when } from \"tstyche\"\n\nclass TestError1 {\n  readonly _tag = \"TestError1\"\n}\nclass TestError2 {\n  readonly _tag = \"TestError2\"\n}\n\nclass TestService extends Context.Tag(\"TestService\")<TestService, {}>() {}\n\ndeclare const string: Effect.Effect<string, \"err-1\", \"dep-1\">\ndeclare const number: Effect.Effect<number, \"err-2\", \"dep-2\">\ndeclare const boolean: Effect.Effect<boolean, never, \"dep-3\">\ndeclare const stringArray: Array<Effect.Effect<string, \"err-3\", \"dep-3\">>\ndeclare const numberRecord: Record<string, Effect.Effect<number, \"err-4\", \"dep-4\">>\n\ndeclare const numberArray: Array<number>\ndeclare const numberEffectIterable: Array<Effect.Effect<number>>\n\ndeclare const readonlyNonEmptyStrings: NonEmptyReadonlyArray<string>\ndeclare const strings: Array<string>\ndeclare const numbersArray: Array<number>\ndeclare const predicateNumbersOrStringsEffect: (input: number | string) => Effect.Effect<boolean>\ndeclare const primitiveNumber: number\ndeclare const primitiveNumberOrString: string | number\ndeclare const predicateNumbersOrStrings: Predicate.Predicate<number | string>\n\n// Tacit helpers\nconst tacitString = (s: string): Effect.Effect<string> => Effect.succeed(`string ${s}`)\nconst tacitStringCause = (s: Cause<string>): Effect.Effect<string> => Effect.succeed(`string ${s}`)\nconst tacitStringPredicate = (_s: string): boolean => true\nconst tacitStringError = (_s: string): \"a\" => \"a\"\nconst tacitStringErrorEffect = (_s: string): Effect.Effect<never, \"a\"> => Effect.fail(\"a\")\n\ndescribe(\"Effect\", () => {\n  describe(\"forEach\", () => {\n    it(\"array\", () => {\n      expect(Effect.forEach(strings, (a, i) => {\n        expect(a).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return string\n      })).type.toBe<Effect.Effect<Array<string>, \"err-1\", \"dep-1\">>()\n      expect(pipe(\n        strings,\n        Effect.forEach((a, i) => {\n          expect(a).type.toBe<string>()\n          expect(i).type.toBe<number>()\n          return string\n        })\n      )).type.toBe<Effect.Effect<Array<string>, \"err-1\", \"dep-1\">>()\n\n      expect(Effect.forEach(strings, (a, i) => {\n        expect(a).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return string\n      }, { discard: true })).type.toBe<Effect.Effect<void, \"err-1\", \"dep-1\">>()\n      expect(pipe(\n        strings,\n        Effect.forEach((a, i) => {\n          expect(a).type.toBe<string>()\n          expect(i).type.toBe<number>()\n          return string\n        }, { discard: true })\n      )).type.toBe<Effect.Effect<void, \"err-1\", \"dep-1\">>()\n    })\n\n    it(\"non empty array\", () => {\n      expect(Effect.forEach(readonlyNonEmptyStrings, (a, i) => {\n        expect(a).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return string\n      })).type.toBe<Effect.Effect<[string, ...Array<string>], \"err-1\", \"dep-1\">>()\n      expect(pipe(\n        readonlyNonEmptyStrings,\n        Effect.forEach((a, i) => {\n          expect(a).type.toBe<string>()\n          expect(i).type.toBe<number>()\n          return string\n        })\n      )).type.toBe<Effect.Effect<[string, ...Array<string>], \"err-1\", \"dep-1\">>()\n\n      expect(Effect.forEach(readonlyNonEmptyStrings, (a, i) => {\n        expect(a).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return string\n      }, { discard: true })).type.toBe<Effect.Effect<void, \"err-1\", \"dep-1\">>()\n      expect(pipe(\n        readonlyNonEmptyStrings,\n        Effect.forEach((a, i) => {\n          expect(a).type.toBe<string>()\n          expect(i).type.toBe<number>()\n          return string\n        }, { discard: true })\n      )).type.toBe<Effect.Effect<void, \"err-1\", \"dep-1\">>()\n    })\n\n    it(\"tuple as non empty array\", () => {\n      const tuple = [\"a\", \"b\"] as const\n      expect(Effect.forEach(tuple, (a, i) => {\n        expect(a).type.toBe<\"a\" | \"b\">()\n        expect(i).type.toBe<number>()\n        return string\n      })).type.toBe<Effect.Effect<[string, ...Array<string>], \"err-1\", \"dep-1\">>()\n      expect(pipe(\n        tuple,\n        Effect.forEach((a, i) => {\n          expect(a).type.toBe<\"a\" | \"b\">()\n          expect(i).type.toBe<number>()\n          return string\n        })\n      )).type.toBe<Effect.Effect<[string, ...Array<string>], \"err-1\", \"dep-1\">>()\n\n      expect(Effect.forEach(tuple, (a, i) => {\n        expect(a).type.toBe<\"a\" | \"b\">()\n        expect(i).type.toBe<number>()\n        return string\n      }, { discard: true })).type.toBe<Effect.Effect<void, \"err-1\", \"dep-1\">>()\n      expect(pipe(\n        tuple,\n        Effect.forEach((a, i) => {\n          expect(a).type.toBe<\"a\" | \"b\">()\n          expect(i).type.toBe<number>()\n          return string\n        }, { discard: true })\n      )).type.toBe<Effect.Effect<void, \"err-1\", \"dep-1\">>()\n    })\n  })\n\n  describe(\"all\", () => {\n    it(\"tuple\", () => {\n      expect(Effect.all([string, number])).type.toBe<\n        Effect.Effect<[string, number], \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all([string, number], undefined)).type.toBe<\n        Effect.Effect<[string, number], \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all([string, number], {})).type.toBe<\n        Effect.Effect<[string, number], \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all([string, number], { concurrency: \"unbounded\" })).type.toBe<\n        Effect.Effect<[string, number], \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all([string, number], { discard: true })).type.toBe<\n        Effect.Effect<void, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all([string, number], { discard: true, concurrency: \"unbounded\" })).type.toBe<\n        Effect.Effect<void, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all([string, number], { mode: \"validate\" })).type.toBe<\n        Effect.Effect<[string, number], [Option.Option<\"err-1\">, Option.Option<\"err-2\">], \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all([string, number], { mode: \"validate\", discard: true })).type.toBe<\n        Effect.Effect<void, [Option.Option<\"err-1\">, Option.Option<\"err-2\">], \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all([string, number], { mode: \"either\" })).type.toBe<\n        Effect.Effect<[Either.Either<string, \"err-1\">, Either.Either<number, \"err-2\">], never, \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all([string, number], { mode: \"either\", discard: true })).type.toBe<\n        Effect.Effect<void, never, \"dep-1\" | \"dep-2\">\n      >()\n    })\n\n    it(\"struct\", () => {\n      expect(Effect.all({ a: string, b: number })).type.toBe<\n        Effect.Effect<{ a: string; b: number }, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all({ a: string, b: number }, undefined)).type.toBe<\n        Effect.Effect<{ a: string; b: number }, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all({ a: string, b: number }, {})).type.toBe<\n        Effect.Effect<{ a: string; b: number }, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all({ a: string, b: number }, { concurrency: \"unbounded\" })).type.toBe<\n        Effect.Effect<{ a: string; b: number }, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all({ a: string, b: number }, { discard: true })).type.toBe<\n        Effect.Effect<void, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all({ a: string, b: number }, { discard: true, concurrency: \"unbounded\" })).type.toBe<\n        Effect.Effect<void, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all({ a: string, b: number }, { mode: \"validate\" })).type.toBe<\n        Effect.Effect<\n          { a: string; b: number },\n          { a: Option.Option<\"err-1\">; b: Option.Option<\"err-2\"> },\n          \"dep-1\" | \"dep-2\"\n        >\n      >()\n      expect(Effect.all({ a: string, b: number }, { mode: \"validate\", discard: true })).type.toBe<\n        Effect.Effect<void, { a: Option.Option<\"err-1\">; b: Option.Option<\"err-2\"> }, \"dep-1\" | \"dep-2\">\n      >()\n      expect(Effect.all({ a: string, b: number }, { mode: \"either\" })).type.toBe<\n        Effect.Effect<\n          { a: Either.Either<string, \"err-1\">; b: Either.Either<number, \"err-2\"> },\n          never,\n          \"dep-1\" | \"dep-2\"\n        >\n      >()\n      expect(Effect.all({ a: string, b: number }, { mode: \"either\", discard: true })).type.toBe<\n        Effect.Effect<void, never, \"dep-1\" | \"dep-2\">\n      >()\n    })\n\n    it(\"array\", () => {\n      expect(Effect.all(stringArray)).type.toBe<\n        Effect.Effect<Array<string>, \"err-3\", \"dep-3\">\n      >()\n      expect(Effect.all(stringArray, undefined)).type.toBe<\n        Effect.Effect<Array<string>, \"err-3\", \"dep-3\">\n      >()\n      expect(Effect.all(stringArray, {})).type.toBe<\n        Effect.Effect<Array<string>, \"err-3\", \"dep-3\">\n      >()\n      expect(Effect.all(stringArray, { concurrency: \"unbounded\" })).type.toBe<\n        Effect.Effect<Array<string>, \"err-3\", \"dep-3\">\n      >()\n      expect(Effect.all(stringArray, { discard: true })).type.toBe<\n        Effect.Effect<void, \"err-3\", \"dep-3\">\n      >()\n      expect(Effect.all(stringArray, { discard: true, concurrency: \"unbounded\" })).type.toBe<\n        Effect.Effect<void, \"err-3\", \"dep-3\">\n      >()\n      expect(Effect.all(stringArray, { mode: \"validate\" })).type.toBe<\n        Effect.Effect<Array<string>, Array<Option.Option<\"err-3\">>, \"dep-3\">\n      >()\n      expect(Effect.all(stringArray, { mode: \"validate\", discard: true })).type.toBe<\n        Effect.Effect<void, Array<Option.Option<\"err-3\">>, \"dep-3\">\n      >()\n      expect(Effect.all(stringArray, { mode: \"either\" })).type.toBe<\n        Effect.Effect<Array<Either.Either<string, \"err-3\">>, never, \"dep-3\">\n      >()\n      expect(Effect.all(stringArray, { mode: \"either\", discard: true })).type.toBe<\n        Effect.Effect<void, never, \"dep-3\">\n      >()\n    })\n\n    it(\"record\", () => {\n      expect(Effect.all(numberRecord)).type.toBe<\n        Effect.Effect<{ [x: string]: number }, \"err-4\", \"dep-4\">\n      >()\n      expect(Effect.all(numberRecord, undefined)).type.toBe<\n        Effect.Effect<{ [x: string]: number }, \"err-4\", \"dep-4\">\n      >()\n      expect(Effect.all(numberRecord, {})).type.toBe<\n        Effect.Effect<{ [x: string]: number }, \"err-4\", \"dep-4\">\n      >()\n      expect(Effect.all(numberRecord, { concurrency: \"unbounded\" })).type.toBe<\n        Effect.Effect<{ [x: string]: number }, \"err-4\", \"dep-4\">\n      >()\n      expect(Effect.all(numberRecord, { discard: true })).type.toBe<\n        Effect.Effect<void, \"err-4\", \"dep-4\">\n      >()\n      expect(Effect.all(numberRecord, { discard: true, concurrency: \"unbounded\" })).type.toBe<\n        Effect.Effect<void, \"err-4\", \"dep-4\">\n      >()\n      expect(Effect.all(numberRecord, { mode: \"validate\" })).type.toBe<\n        Effect.Effect<{ [x: string]: number }, { [x: string]: Option.Option<\"err-4\"> }, \"dep-4\">\n      >()\n      expect(Effect.all(numberRecord, { mode: \"validate\", discard: true })).type.toBe<\n        Effect.Effect<void, { [x: string]: Option.Option<\"err-4\"> }, \"dep-4\">\n      >()\n      expect(Effect.all(numberRecord, { mode: \"either\" })).type.toBe<\n        Effect.Effect<{ [x: string]: Either.Either<number, \"err-4\"> }, never, \"dep-4\">\n      >()\n      expect(Effect.all(numberRecord, { mode: \"either\", discard: true })).type.toBe<\n        Effect.Effect<void, never, \"dep-4\">\n      >()\n    })\n  })\n\n  describe(\"allWith\", () => {\n    it(\"tuple\", () => {\n      expect(pipe([string, number] as const, Effect.allWith())).type.toBe<\n        Effect.Effect<[string, number], \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe([string, number] as const, Effect.allWith(undefined))).type.toBe<\n        Effect.Effect<[string, number], \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe([string, number] as const, Effect.allWith({}))).type.toBe<\n        Effect.Effect<[string, number], \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe([string, number] as const, Effect.allWith({ concurrency: \"unbounded\" }))).type.toBe<\n        Effect.Effect<[string, number], \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe([string, number] as const, Effect.allWith({ discard: true }))).type.toBe<\n        Effect.Effect<void, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe([string, number] as const, Effect.allWith({ discard: true, concurrency: \"unbounded\" }))).type.toBe<\n        Effect.Effect<void, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe([string, number] as const, Effect.allWith({ mode: \"validate\" }))).type.toBe<\n        Effect.Effect<[string, number], [Option.Option<\"err-1\">, Option.Option<\"err-2\">], \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe([string, number] as const, Effect.allWith({ mode: \"validate\", discard: true }))).type.toBe<\n        Effect.Effect<void, [Option.Option<\"err-1\">, Option.Option<\"err-2\">], \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe([string, number] as const, Effect.allWith({ mode: \"either\" }))).type.toBe<\n        Effect.Effect<[Either.Either<string, \"err-1\">, Either.Either<number, \"err-2\">], never, \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe([string, number] as const, Effect.allWith({ mode: \"either\", discard: true }))).type.toBe<\n        Effect.Effect<void, never, \"dep-1\" | \"dep-2\">\n      >()\n    })\n\n    it(\"struct\", () => {\n      expect(pipe({ a: string, b: number }, Effect.allWith())).type.toBe<\n        Effect.Effect<{ a: string; b: number }, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe({ a: string, b: number }, Effect.allWith(undefined))).type.toBe<\n        Effect.Effect<{ a: string; b: number }, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe({ a: string, b: number }, Effect.allWith({}))).type.toBe<\n        Effect.Effect<{ a: string; b: number }, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe({ a: string, b: number }, Effect.allWith({ concurrency: \"unbounded\" }))).type.toBe<\n        Effect.Effect<{ a: string; b: number }, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe({ a: string, b: number }, Effect.allWith({ discard: true }))).type.toBe<\n        Effect.Effect<void, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe({ a: string, b: number }, Effect.allWith({ discard: true, concurrency: \"unbounded\" }))).type.toBe<\n        Effect.Effect<void, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe({ a: string, b: number }, Effect.allWith({ mode: \"validate\" }))).type.toBe<\n        Effect.Effect<\n          { a: string; b: number },\n          { a: Option.Option<\"err-1\">; b: Option.Option<\"err-2\"> },\n          \"dep-1\" | \"dep-2\"\n        >\n      >()\n      expect(pipe({ a: string, b: number }, Effect.allWith({ mode: \"validate\", discard: true }))).type.toBe<\n        Effect.Effect<void, { a: Option.Option<\"err-1\">; b: Option.Option<\"err-2\"> }, \"dep-1\" | \"dep-2\">\n      >()\n      expect(pipe({ a: string, b: number }, Effect.allWith({ mode: \"either\" }))).type.toBe<\n        Effect.Effect<\n          { a: Either.Either<string, \"err-1\">; b: Either.Either<number, \"err-2\"> },\n          never,\n          \"dep-1\" | \"dep-2\"\n        >\n      >()\n      expect(pipe({ a: string, b: number }, Effect.allWith({ mode: \"either\", discard: true }))).type.toBe<\n        Effect.Effect<void, never, \"dep-1\" | \"dep-2\">\n      >()\n    })\n\n    it(\"array\", () => {\n      expect(pipe(stringArray, Effect.allWith())).type.toBe<\n        Effect.Effect<Array<string>, \"err-3\", \"dep-3\">\n      >()\n      expect(pipe(stringArray, Effect.allWith(undefined))).type.toBe<\n        Effect.Effect<Array<string>, \"err-3\", \"dep-3\">\n      >()\n      expect(pipe(stringArray, Effect.allWith({}))).type.toBe<\n        Effect.Effect<Array<string>, \"err-3\", \"dep-3\">\n      >()\n      expect(pipe(stringArray, Effect.allWith({ concurrency: \"unbounded\" }))).type.toBe<\n        Effect.Effect<Array<string>, \"err-3\", \"dep-3\">\n      >()\n      expect(pipe(stringArray, Effect.allWith({ discard: true }))).type.toBe<\n        Effect.Effect<void, \"err-3\", \"dep-3\">\n      >()\n      expect(pipe(stringArray, Effect.allWith({ discard: true, concurrency: \"unbounded\" }))).type.toBe<\n        Effect.Effect<void, \"err-3\", \"dep-3\">\n      >()\n      expect(pipe(stringArray, Effect.allWith({ mode: \"validate\" }))).type.toBe<\n        Effect.Effect<Array<string>, Array<Option.Option<\"err-3\">>, \"dep-3\">\n      >()\n      expect(pipe(stringArray, Effect.allWith({ mode: \"validate\", discard: true }))).type.toBe<\n        Effect.Effect<void, Array<Option.Option<\"err-3\">>, \"dep-3\">\n      >()\n      expect(pipe(stringArray, Effect.allWith({ mode: \"either\" }))).type.toBe<\n        Effect.Effect<Array<Either.Either<string, \"err-3\">>, never, \"dep-3\">\n      >()\n      expect(pipe(stringArray, Effect.allWith({ mode: \"either\", discard: true }))).type.toBe<\n        Effect.Effect<void, never, \"dep-3\">\n      >()\n    })\n\n    it(\"record\", () => {\n      expect(pipe(numberRecord, Effect.allWith())).type.toBe<\n        Effect.Effect<{ [x: string]: number }, \"err-4\", \"dep-4\">\n      >()\n      expect(pipe(numberRecord, Effect.allWith(undefined))).type.toBe<\n        Effect.Effect<{ [x: string]: number }, \"err-4\", \"dep-4\">\n      >()\n      expect(pipe(numberRecord, Effect.allWith({}))).type.toBe<\n        Effect.Effect<{ [x: string]: number }, \"err-4\", \"dep-4\">\n      >()\n      expect(pipe(numberRecord, Effect.allWith({ concurrency: \"unbounded\" }))).type.toBe<\n        Effect.Effect<{ [x: string]: number }, \"err-4\", \"dep-4\">\n      >()\n      expect(pipe(numberRecord, Effect.allWith({ discard: true }))).type.toBe<\n        Effect.Effect<void, \"err-4\", \"dep-4\">\n      >()\n      expect(pipe(numberRecord, Effect.allWith({ discard: true, concurrency: \"unbounded\" }))).type.toBe<\n        Effect.Effect<void, \"err-4\", \"dep-4\">\n      >()\n      expect(pipe(numberRecord, Effect.allWith({ mode: \"validate\" }))).type.toBe<\n        Effect.Effect<{ [x: string]: number }, { [x: string]: Option.Option<\"err-4\"> }, \"dep-4\">\n      >()\n      expect(pipe(numberRecord, Effect.allWith({ mode: \"validate\", discard: true }))).type.toBe<\n        Effect.Effect<void, { [x: string]: Option.Option<\"err-4\"> }, \"dep-4\">\n      >()\n      expect(pipe(numberRecord, Effect.allWith({ mode: \"either\" }))).type.toBe<\n        Effect.Effect<{ [x: string]: Either.Either<number, \"err-4\"> }, never, \"dep-4\">\n      >()\n      expect(pipe(numberRecord, Effect.allWith({ mode: \"either\", discard: true }))).type.toBe<\n        Effect.Effect<void, never, \"dep-4\">\n      >()\n    })\n  })\n\n  it(\"filterOrFail\", () => {\n    expect(\n      Effect.succeed(\"a\" as const).pipe(\n        Effect.filterOrFail(\n          tacitStringPredicate,\n          (x) => {\n            expect(x).type.toBe<\"a\">()\n            return \"a\" as const\n          }\n        )\n      )\n    ).type.toBe<Effect.Effect<\"a\", \"a\">>()\n    expect(\n      Effect.succeed(\"a\" as const).pipe(\n        Effect.filterOrFail(\n          (x) => {\n            expect(x).type.toBe<\"a\">()\n            return true\n          },\n          tacitStringError\n        )\n      )\n    ).type.toBe<Effect.Effect<\"a\", \"a\">>()\n    expect(\n      Effect.succeed<\"a\" | \"b\">(\"a\").pipe(\n        Effect.filterOrFail(\n          (s): s is \"a\" => s === \"a\",\n          (x) => {\n            expect(x).type.toBe<\"b\">()\n            return \"a\" as const\n          }\n        )\n      )\n    ).type.toBe<Effect.Effect<\"a\", \"a\">>()\n  })\n\n  it(\"filterOrDie\", () => {\n    expect(\n      Effect.succeed(\"a\" as const).pipe(\n        Effect.filterOrDie(\n          tacitStringPredicate,\n          (x) => {\n            expect(x).type.toBe<\"a\">()\n            return \"fail\"\n          }\n        )\n      )\n    ).type.toBe<Effect.Effect<\"a\">>()\n\n    expect(\n      Effect.succeed<\"a\" | \"b\">(\"a\").pipe(\n        Effect.filterOrDie(\n          (s): s is \"a\" => s === \"a\",\n          (x) => {\n            expect(x).type.toBe<\"b\">()\n            return \"fail\"\n          }\n        )\n      )\n    ).type.toBe<Effect.Effect<\"a\">>()\n  })\n\n  it(\"filterOrDieMessage\", () => {\n    expect(\n      Effect.succeed(\"a\" as const).pipe(\n        Effect.filterOrDieMessage(\n          tacitStringPredicate,\n          \"fail\"\n        )\n      )\n    ).type.toBe<Effect.Effect<\"a\">>()\n  })\n\n  it(\"filterOrElse\", () => {\n    expect(\n      Effect.succeed(\"a\" as const).pipe(\n        Effect.filterOrElse(\n          tacitStringPredicate,\n          (x) => {\n            expect(x).type.toBe<\"a\">()\n            return Effect.fail(\"a\" as const)\n          }\n        )\n      )\n    ).type.toBe<Effect.Effect<\"a\", \"a\">>()\n    expect(\n      Effect.succeed(\"a\" as const).pipe(\n        Effect.filterOrElse(\n          (x) => {\n            expect(x).type.toBe<\"a\">()\n            return true\n          },\n          tacitStringErrorEffect\n        )\n      )\n    ).type.toBe<Effect.Effect<\"a\", \"a\">>()\n\n    expect(\n      Effect.succeed(numberArray).pipe(\n        Effect.filterOrElse(\n          Arr.isNonEmptyArray,\n          () => Effect.fail(\"a\" as const)\n        )\n      )\n    ).type.toBe<Effect.Effect<NonEmptyArray<number>, \"a\">>()\n  })\n\n  it(\"tap\", () => {\n    when(Effect.succeed(\"a\" as const).pipe).isCalledWith(\n      expect(Effect.tap).type.not.toBeCallableWith(tacitStringError, { onlyEffect: true })\n    )\n    when(Effect.succeed(\"a\" as const).pipe).isCalledWith(\n      expect(Effect.tap).type.not.toBeCallableWith(\"a\", { onlyEffect: true })\n    )\n\n    expect(Effect.succeed(\"a\" as const).pipe(Effect.tap(tacitString))).type.toBe<Effect.Effect<\"a\">>()\n\n    expect(Effect.succeed(\"a\" as const).pipe(Effect.tap(tacitString, { onlyEffect: true })))\n      .type.toBe<Effect.Effect<\"a\">>()\n\n    expect(Effect.succeed(\"a\" as const).pipe(Effect.tap(tacitString(\"a\"), { onlyEffect: true })))\n      .type.toBe<Effect.Effect<\"a\">>()\n  })\n\n  it(\"tapError\", () => {\n    expect(\n      Effect.fail(\"a\" as const).pipe(Effect.tapError(tacitString))\n    ).type.toBe<Effect.Effect<never, \"a\">>()\n  })\n\n  it(\"tapErrorCause\", () => {\n    expect(\n      Effect.fail(\"a\" as const).pipe(Effect.tapErrorCause(tacitStringCause))\n    ).type.toBe<Effect.Effect<never, \"a\">>()\n  })\n\n  it(\"tapDefect\", () => {\n    expect(\n      Effect.fail(\"a\" as const).pipe(Effect.tapDefect(tacitStringCause))\n    ).type.toBe<Effect.Effect<never, \"a\">>()\n  })\n\n  it(\"tapBoth\", () => {\n    expect(pipe(\n      Effect.succeed(\"a\" as const) as Effect.Effect<\"a\", \"a\">,\n      Effect.tapBoth({\n        onFailure: tacitString,\n        onSuccess: tacitString\n      })\n    )).type.toBe<Effect.Effect<\"a\", \"a\">>()\n  })\n\n  it(\"zip\", () => {\n    expect(Effect.zip(Effect.succeed(1), Effect.succeed(\"a\"))).type.toBe<\n      Effect.Effect<[number, string]>\n    >()\n  })\n\n  it(\"validate\", () => {\n    expect(Effect.validate(Effect.succeed(1), Effect.succeed(\"a\"))).type.toBe<\n      Effect.Effect<[number, string]>\n    >()\n  })\n\n  it(\"promise\", () => {\n    expect(Effect.promise<string>(\n      () =>\n        new Promise((resolve) => {\n          setTimeout(() => {\n            resolve(\"Async operation completed successfully!\")\n          }, 2000)\n        })\n    )).type.toBe<Effect.Effect<string>>()\n  })\n\n  it(\"tapErrorTag\", () => {\n    class TestError1 {\n      readonly _tag = \"TestError1\"\n    }\n    class TestError2 {\n      readonly _tag = \"TestError2\"\n    }\n\n    expect(pipe(\n      Effect.fail(new TestError1()),\n      Effect.tapErrorTag(\"TestError1\", (x) => {\n        expect(x).type.toBe<TestError1>()\n        return Effect.succeed(1)\n      })\n    )).type.toBe<Effect.Effect<never, TestError1>>()\n\n    expect(pipe(\n      Effect.fail(new TestError1()),\n      Effect.tapErrorTag(\"TestError1\", (x) => {\n        expect(x).type.toBe<TestError1>()\n        return Effect.fail(new Error(\"\"))\n      })\n    )).type.toBe<Effect.Effect<never, Error | TestError1>>()\n\n    expect(pipe(\n      Effect.fail<TestError1 | Error>(new TestError1()),\n      Effect.tapErrorTag(\"TestError1\", (x) => {\n        expect(x).type.toBe<TestError1>()\n        return Effect.succeed(1)\n      })\n    )).type.toBe<Effect.Effect<never, Error | TestError1>>()\n\n    expect(\n      hole<Effect.Effect<number, TestError1 | TestError2>>().pipe(\n        Effect.tapErrorTag(\"TestError1\", Effect.log)\n      )\n    ).type.toBe<Effect.Effect<number, TestError1 | TestError2>>()\n  })\n\n  it(\"catchIf\", () => {\n    expect(pipe(\n      Effect.fail<TestError1 | Error>(new TestError1()),\n      Effect.catchIf(\n        (error) => {\n          expect(error).type.toBe<TestError1 | Error>()\n          return true\n        },\n        Effect.succeed\n      ),\n      Effect.exit\n    )).type.toBe<Effect.Effect<Exit<Error | TestError1, Error | TestError1>, never, never>>()\n  })\n\n  it(\"catchTag\", () => {\n    expect(Effect.catchTag).type.not.toBeCallableWith(\n      hole<Effect.Effect<number, TestError1>>(),\n      \"wrong\",\n      () => Effect.succeed(1)\n    )\n    when(pipe).isCalledWith(\n      hole<Effect.Effect<number, TestError1>>(),\n      expect(Effect.catchTag).type.not.toBeCallableWith(\"wrong\", () => Effect.succeed(1))\n    )\n\n    expect(Effect.catchTag).type.not.toBeCallableWith(\n      hole<Effect.Effect<number, Error | TestError1>>(),\n      \"wrong\",\n      () => Effect.succeed(1)\n    )\n    when(pipe).isCalledWith(\n      hole<Effect.Effect<number, Error | TestError1>>(),\n      expect(Effect.catchTag).type.not.toBeCallableWith(\"wrong\", () => Effect.succeed(1))\n    )\n\n    expect(Effect.catchTag(\n      hole<Effect.Effect<number, Error | TestError1 | TestError2>>(),\n      \"TestError1\",\n      (e) => {\n        expect(e).type.toBe<TestError1>()\n        return Effect.succeed(1)\n      }\n    )).type.toBe<Effect.Effect<number, Error | TestError2>>()\n\n    expect(\n      Effect.catchTag(hole<Effect.Effect<number, TestError1>>(), \"TestError1\", (e) => {\n        expect(e).type.toBe<TestError1>()\n        return Effect.succeed(1)\n      })\n    ).type.toBe<\n      Effect.Effect<number>\n    >()\n\n    expect(\n      hole<Effect.Effect<number, TestError1 | TestError2>>().pipe(\n        Effect.catchTag(\"TestError1\", Effect.log)\n      )\n    ).type.toBe<Effect.Effect<number | void, TestError2>>()\n\n    expect(pipe(\n      hole<Effect.Effect<number, TestError1>>(),\n      Effect.catchTag(\"TestError1\", (e) => {\n        expect(e).type.toBe<TestError1>()\n        return Effect.succeed(1)\n      })\n    )).type.toBe<Effect.Effect<number>>()\n\n    expect(Effect.catchTag(hole<Effect.Effect<number, TestError1 | TestError2>>(), \"TestError1\", Effect.succeed)).type\n      .toBe<Effect.Effect<number | TestError1, TestError2>>()\n\n    expect(pipe(\n      hole<Effect.Effect<number, TestError1 | TestError2>>(),\n      Effect.catchTag(\"TestError1\", (e) => {\n        expect(e).type.toBe<TestError1>()\n        return Effect.succeed(1)\n      })\n    )).type.toBe<Effect.Effect<number, TestError2>>()\n\n    expect(\n      Effect.catchTag(\n        hole<Effect.Effect<number, TestError1 | Error>>(),\n        \"TestError1\",\n        (e) => {\n          expect(e).type.toBe<TestError1>()\n          return Effect.succeed(1)\n        }\n      )\n    ).type.toBe<Effect.Effect<number, Error>>()\n\n    expect(pipe(\n      hole<Effect.Effect<number, TestError1 | Error>>(),\n      Effect.catchTag(\"TestError1\", (e) => {\n        expect(e).type.toBe<TestError1>()\n        return Effect.succeed(1)\n      })\n    )).type.toBe<Effect.Effect<number, Error>>()\n\n    expect(pipe(\n      hole<Effect.Effect<number, TestError1 | Error>>(),\n      Effect.catchTag(\n        \"TestError1\",\n        Effect.fn(function*(e) {\n          expect(e).type.toBe<TestError1>()\n          return 1\n        })\n      )\n    )).type.toBe<Effect.Effect<number, Error>>()\n  })\n\n  it(\"catchTags\", () => {\n    expect(pipe(\n      Effect.fail<TestError1 | Error>(new Error()),\n      Effect.catchTags({\n        TestError1: (e) => {\n          expect(e).type.toBe<TestError1>()\n          return Effect.succeed(1)\n        }\n      })\n    )).type.toBe<Effect.Effect<number, Error>>()\n\n    when(pipe).isCalledWith(\n      Effect.fail(new TestError1()),\n      expect(Effect.catchTags).type.not.toBeCallableWith({\n        TestError1: () => Effect.succeed(1),\n        Other: () => Effect.succeed(1)\n      })\n    )\n\n    expect(Effect.catchTags).type.not.toBeCallableWith(Effect.fail(new TestError1()), {\n      TestError1: () => Effect.succeed(1),\n      Other: () => Effect.succeed(1)\n    })\n\n    when(pipe).isCalledWith(\n      Effect.fail(new TestError1() as TestError1 | string),\n      expect(Effect.catchTags).type.not.toBeCallableWith({\n        TestError1: () => Effect.succeed(1),\n        Other: () => Effect.succeed(1)\n      })\n    )\n\n    expect(Effect.catchTags).type.not.toBeCallableWith(Effect.fail(new TestError1() as TestError1 | string), {\n      TestError1: () => Effect.succeed(1),\n      Other: () => Effect.succeed(1)\n    })\n\n    expect(pipe(\n      Effect.fail(new TestError1() as unknown),\n      Effect.catchTags({\n        TestError1: () => Effect.succeed(1)\n      })\n    )).type.toBe<Effect.Effect<number, unknown>>()\n\n    expect(Effect.catchTags(Effect.fail(new TestError1() as unknown), {\n      TestError1: () => Effect.succeed(1)\n    })).type.toBe<Effect.Effect<number, unknown>>()\n  })\n\n  it(\"iterate\", () => {\n    // predicate\n    expect(Effect.iterate(100, {\n      while: (n) => {\n        expect(n).type.toBe<number>()\n        return n > 0\n      },\n      body: (n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(n - 1)\n      }\n    })).type.toBe<Effect.Effect<number>>()\n\n    // refinement\n    expect(Effect.iterate(100 as null | number, {\n      while: (n): n is number => {\n        expect(n).type.toBe<number | null>()\n        return Predicate.isNotNull(n) && n > 0\n      },\n      body: (n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(n - 1)\n      }\n    })).type.toBe<Effect.Effect<number | null>>()\n  })\n\n  it(\"loop\", () => {\n    // predicate\n    expect(Effect.loop(0, {\n      while: (n) => {\n        expect(n).type.toBe<number>()\n        return n < 5\n      },\n      step: (n) => {\n        expect(n).type.toBe<number>()\n        return n + 1\n      },\n      body: (n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(n * 2)\n      }\n    })).type.toBe<Effect.Effect<Array<number>>>()\n\n    expect(Effect.loop(0, {\n      while: (n) => {\n        expect(n).type.toBe<number>()\n        return n < 5\n      },\n      step: (n) => {\n        expect(n).type.toBe<number>()\n        return n + 1\n      },\n      body: (n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(n * 2)\n      },\n      discard: true\n    })).type.toBe<Effect.Effect<void>>()\n\n    // refinement\n    expect(Effect.loop(0 as null | number, {\n      while: (n): n is number => {\n        expect(n).type.toBe<number | null>()\n        return Predicate.isNotNull(n) && n < 5\n      },\n      step: (n) => {\n        expect(n).type.toBe<number>()\n        return n + 1\n      },\n      body: (n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(n * 2)\n      }\n    })).type.toBe<Effect.Effect<Array<number>>>()\n\n    expect(Effect.loop(0 as null | number, {\n      while: (n): n is number => {\n        expect(n).type.toBe<number | null>()\n        return Predicate.isNotNull(n) && n < 5\n      },\n      step: (n) => {\n        expect(n).type.toBe<number>()\n        return n + 1\n      },\n      body: (n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(n * 2)\n      },\n      discard: true\n    })).type.toBe<Effect.Effect<void>>()\n  })\n\n  it(\"dropWhile\", () => {\n    expect(Effect.dropWhile(numbersArray, (n) => {\n      expect(n).type.toBe<number>()\n      return Effect.succeed(true)\n    })).type.toBe<Effect.Effect<Array<number>>>()\n\n    expect(pipe(\n      numbersArray,\n      Effect.dropWhile((n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(true)\n      })\n    )).type.toBe<Effect.Effect<Array<number>>>()\n\n    expect(pipe(\n      numbersArray,\n      Effect.dropWhile((n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(true)\n      })\n    )).type.toBe<Effect.Effect<Array<number>>>()\n\n    expect(Effect.dropWhile(numbersArray, predicateNumbersOrStringsEffect)).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n    expect(pipe(numbersArray, Effect.dropWhile(predicateNumbersOrStringsEffect))).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n  })\n\n  it(\"dropUntil\", () => {\n    expect(Effect.dropUntil(numbersArray, (n) => {\n      expect(n).type.toBe<number>()\n      return Effect.succeed(true)\n    })).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n\n    expect(pipe(\n      numbersArray,\n      Effect.dropUntil((n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(true)\n      })\n    )).type.toBe<Effect.Effect<Array<number>>>()\n\n    expect(pipe(\n      numbersArray,\n      Effect.dropUntil((n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(true)\n      })\n    )).type.toBe<Effect.Effect<Array<number>>>()\n\n    expect(Effect.dropUntil(numbersArray, predicateNumbersOrStringsEffect)).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n    expect(pipe(numbersArray, Effect.dropUntil(predicateNumbersOrStringsEffect))).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n  })\n\n  it(\"andThen\", () => {\n    expect(Effect.andThen(string, number)).type.toBe<\n      Effect.Effect<number, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n    >()\n    expect(string.pipe(Effect.andThen(number))).type.toBe<\n      Effect.Effect<number, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n    >()\n\n    expect(Effect.andThen(string, () => number)).type.toBe<\n      Effect.Effect<number, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n    >()\n    expect(string.pipe(Effect.andThen(() => number))).type.toBe<\n      Effect.Effect<number, \"err-1\" | \"err-2\", \"dep-1\" | \"dep-2\">\n    >()\n\n    expect(Effect.andThen(string, Promise.resolve(123))).type.toBe<\n      Effect.Effect<number, \"err-1\" | UnknownException, \"dep-1\">\n    >()\n    expect(string.pipe(Effect.andThen(Promise.resolve(123)))).type.toBe<\n      Effect.Effect<number, \"err-1\" | UnknownException, \"dep-1\">\n    >()\n\n    expect(Effect.andThen(string, () => Promise.resolve(123))).type.toBe<\n      Effect.Effect<number, \"err-1\" | UnknownException, \"dep-1\">\n    >()\n    expect(string.pipe(Effect.andThen(() => Promise.resolve(123)))).type.toBe<\n      Effect.Effect<number, \"err-1\" | UnknownException, \"dep-1\">\n    >()\n\n    expect(Effect.andThen(string, 1)).type.toBe<\n      Effect.Effect<number, \"err-1\", \"dep-1\">\n    >()\n    expect(string.pipe(Effect.andThen(1))).type.toBe<\n      Effect.Effect<number, \"err-1\", \"dep-1\">\n    >()\n\n    expect(Effect.andThen(string, () => 1)).type.toBe<\n      Effect.Effect<number, \"err-1\", \"dep-1\">\n    >()\n    expect(string.pipe(Effect.andThen(() => 1))).type.toBe<\n      Effect.Effect<number, \"err-1\", \"dep-1\">\n    >()\n  })\n\n  it(\"retry\", () => {\n    expect(Effect.retry(string, Schedule.forever)).type.toBe<\n      Effect.Effect<string, \"err-1\", \"dep-1\">\n    >()\n    expect(string.pipe(Effect.retry(Schedule.forever))).type.toBe<\n      Effect.Effect<string, \"err-1\", \"dep-1\">\n    >()\n\n    expect(Effect.retry(string, { schedule: Schedule.forever })).type.toBe<\n      Effect.Effect<string, \"err-1\", \"dep-1\">\n    >()\n    expect(string.pipe(Effect.retry({ schedule: Schedule.forever }))).type.toBe<\n      Effect.Effect<string, \"err-1\", \"dep-1\">\n    >()\n\n    expect(Effect.retry(string, {\n      schedule: Schedule.forever,\n      until: (e) => {\n        expect(e).type.toBe<\"err-1\">()\n        return true\n      }\n    })).type.toBe<Effect.Effect<string, \"err-1\", \"dep-1\">>()\n    expect(string.pipe(Effect.retry({\n      schedule: Schedule.forever,\n      until: (e) => {\n        expect(e).type.toBe<\"err-1\">()\n        return true\n      }\n    }))).type.toBe<Effect.Effect<string, \"err-1\", \"dep-1\">>()\n\n    expect(Effect.retry(string, {\n      schedule: Schedule.forever,\n      until: (e) => {\n        expect(e).type.toBe<\"err-1\">()\n        return boolean\n      }\n    })).type.toBe<Effect.Effect<string, \"err-1\", \"dep-1\" | \"dep-3\">>()\n    expect(string.pipe(Effect.retry({\n      schedule: Schedule.forever,\n      until: (e) => {\n        expect(e).type.toBe<\"err-1\">()\n        return boolean\n      }\n    }))).type.toBe<Effect.Effect<string, \"err-1\", \"dep-1\" | \"dep-3\">>()\n\n    expect(Effect.retry(Effect.fail(\"\"), {\n      until: (e): e is \"err\" => {\n        expect(e).type.toBe<string>()\n        return true\n      }\n    })).type.toBe<Effect.Effect<never, \"err\">>()\n    expect(\n      Effect.fail(\"\").pipe(Effect.retry({\n        until: (e): e is \"err\" => {\n          expect(e).type.toBe<string>()\n          return true\n        }\n      }))\n    ).type.toBe<Effect.Effect<never, \"err\">>()\n\n    expect(Effect.retry(Effect.fail(\"\"), {\n      schedule: Schedule.forever,\n      until: (e): e is \"err\" => {\n        expect(e).type.toBe<string>()\n        return true\n      }\n    })).type.toBe<Effect.Effect<never, string>>()\n    expect(\n      Effect.fail(\"\").pipe(Effect.retry({\n        schedule: Schedule.forever,\n        until: (e): e is \"err\" => {\n          expect(e).type.toBe<string>()\n          return true\n        }\n      }))\n    ).type.toBe<Effect.Effect<never, string>>()\n  })\n\n  it(\"repeat\", () => {\n    expect(Effect.repeat(string, Schedule.forever)).type.toBe<\n      Effect.Effect<number, \"err-1\", \"dep-1\">\n    >()\n    expect(string.pipe(Effect.repeat(Schedule.forever))).type.toBe<\n      Effect.Effect<number, \"err-1\", \"dep-1\">\n    >()\n\n    expect(Effect.repeat(string, { schedule: Schedule.forever })).type.toBe<\n      Effect.Effect<number, \"err-1\", \"dep-1\">\n    >()\n    expect(string.pipe(Effect.repeat({ schedule: Schedule.forever }))).type.toBe<\n      Effect.Effect<number, \"err-1\", \"dep-1\">\n    >()\n\n    expect(Effect.repeat(string, {\n      schedule: Schedule.forever,\n      until: (e) => {\n        expect(e).type.toBe<string>()\n        return true\n      }\n    })).type.toBe<Effect.Effect<number, \"err-1\", \"dep-1\">>()\n    expect(string.pipe(Effect.repeat({\n      schedule: Schedule.forever,\n      until: (e) => {\n        expect(e).type.toBe<string>()\n        return true\n      }\n    }))).type.toBe<\n      Effect.Effect<number, \"err-1\", \"dep-1\">\n    >()\n    expect(Effect.repeat(string, {\n      schedule: Schedule.forever,\n      until: (e) => {\n        expect(e).type.toBe<string>()\n        return boolean\n      }\n    })).type.toBe<Effect.Effect<number, \"err-1\", \"dep-1\" | \"dep-3\">>()\n    expect(string.pipe(Effect.repeat({\n      schedule: Schedule.forever,\n      until: (e) => {\n        expect(e).type.toBe<string>()\n        return boolean\n      }\n    }))).type.toBe<Effect.Effect<number, \"err-1\", \"dep-1\" | \"dep-3\">>()\n\n    expect(Effect.repeat(Effect.succeed(123), {\n      until: (e): e is 123 => {\n        expect(e).type.toBe<number>()\n        return true\n      }\n    })).type.toBe<Effect.Effect<123>>()\n    expect(\n      Effect.succeed(123).pipe(Effect.repeat({\n        until: (e): e is 123 => {\n          expect(e).type.toBe<number>()\n          return true\n        }\n      }))\n    ).type.toBe<Effect.Effect<123>>()\n\n    expect(Effect.repeat(Effect.succeed(\"\"), {\n      schedule: Schedule.forever,\n      until: (e): e is \"hello\" => {\n        expect(e).type.toBe<string>()\n        return true\n      }\n    })).type.toBe<Effect.Effect<number>>()\n    expect(\n      Effect.succeed(\"\").pipe(Effect.repeat({\n        schedule: Schedule.forever,\n        until: (e): e is \"hello\" => {\n          expect(e).type.toBe<string>()\n          return true\n        }\n      }))\n    ).type.toBe<Effect.Effect<number>>()\n  })\n\n  it(\"filter\", () => {\n    expect(Effect.filter(numberArray, (n) => {\n      expect(n).type.toBe<number>()\n      return Effect.succeed(true)\n    })).type.toBe<Effect.Effect<Array<number>>>()\n    expect(pipe(\n      numberArray,\n      Effect.filter((n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(true)\n      })\n    )).type.toBe<Effect.Effect<Array<number>>>()\n\n    expect(Effect.filter(numberArray, (_n: unknown) => Effect.succeed(true))).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n    expect(pipe(numberArray, Effect.filter((_n: unknown) => Effect.succeed(true)))).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n  })\n\n  it(\"findFirst\", () => {\n    expect(Effect.findFirst(numberArray, (n) => {\n      expect(n).type.toBe<number>()\n      return Effect.succeed(true)\n    })).type.toBe<Effect.Effect<Option.Option<number>>>()\n    expect(pipe(\n      numberArray,\n      Effect.findFirst((n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(true)\n      })\n    )).type.toBe<Effect.Effect<Option.Option<number>>>()\n\n    expect(Effect.findFirst(numberArray, (_n: unknown) => Effect.succeed(true))).type.toBe<\n      Effect.Effect<Option.Option<number>>\n    >()\n    expect(pipe(numberArray, Effect.findFirst((_n: unknown) => Effect.succeed(true)))).type.toBe<\n      Effect.Effect<Option.Option<number>>\n    >()\n  })\n\n  it(\"reduceEffect\", () => {\n    expect(Effect.reduceEffect(numberEffectIterable, Effect.succeed(0), (n) => {\n      expect(n).type.toBe<number>()\n      return 0\n    })).type.toBe<Effect.Effect<number>>()\n    expect(pipe(\n      numberEffectIterable,\n      Effect.reduceEffect(Effect.succeed(0), (n) => {\n        expect(n).type.toBe<number>()\n        return 0\n      })\n    )).type.toBe<Effect.Effect<number>>()\n\n    expect(Effect.reduceEffect(numberEffectIterable, Effect.succeed(0), (_n: unknown): number | string => 0)).type.toBe<\n      Effect.Effect<string | number>\n    >()\n    expect(pipe(numberEffectIterable, Effect.reduceEffect(Effect.succeed(0), (_n: unknown): number | string => 0))).type\n      .toBe<Effect.Effect<string | number>>()\n  })\n\n  it(\"takeUntil\", () => {\n    expect(Effect.takeUntil(numberArray, (n) => {\n      expect(n).type.toBe<number>()\n      return Effect.succeed(true)\n    })).type.toBe<Effect.Effect<Array<number>>>()\n    expect(pipe(\n      numberArray,\n      Effect.takeUntil((n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(true)\n      })\n    )).type.toBe<Effect.Effect<Array<number>>>()\n\n    expect(Effect.takeUntil(numberArray, (_n: unknown) => Effect.succeed(true))).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n    expect(pipe(numberArray, Effect.takeUntil((_n: unknown) => Effect.succeed(true)))).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n  })\n\n  it(\"takeWhile\", () => {\n    expect(Effect.takeWhile(numberArray, (n) => {\n      expect(n).type.toBe<number>()\n      return Effect.succeed(true)\n    })).type.toBe<Effect.Effect<Array<number>>>()\n    expect(pipe(\n      numberArray,\n      Effect.takeWhile((n) => {\n        expect(n).type.toBe<number>()\n        return Effect.succeed(true)\n      })\n    )).type.toBe<Effect.Effect<Array<number>>>()\n\n    expect(Effect.takeWhile(numberArray, (_n: unknown) => Effect.succeed(true))).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n    expect(pipe(numberArray, Effect.takeWhile((_n: unknown) => Effect.succeed(true)))).type.toBe<\n      Effect.Effect<Array<number>>\n    >()\n  })\n\n  it(\"catchSome\", () => {\n    expect(pipe(\n      string,\n      Effect.catchSome((e) => {\n        expect(e).type.toBe<\"err-1\">()\n        return Option.some(Effect.succeed(1))\n      })\n    )).type.toBe<Effect.Effect<string | number, \"err-1\", \"dep-1\">>()\n\n    expect(Effect.catchSome(string, (e) => {\n      expect(e).type.toBe<\"err-1\">()\n      return Option.some(Effect.succeed(1))\n    })).type.toBe<\n      Effect.Effect<string | number, \"err-1\", \"dep-1\">\n    >()\n\n    expect(Effect.catchSome(string, (_e: string) => Option.some(Effect.succeed(1)))).type.toBe<\n      Effect.Effect<string | number, \"err-1\", \"dep-1\">\n    >()\n    expect(pipe(string, Effect.catchSome((_e: string) => Option.some(Effect.succeed(1))))).type.toBe<\n      Effect.Effect<string | number, \"err-1\", \"dep-1\">\n    >()\n  })\n\n  it(\"retryOrElse\", () => {\n    expect(Effect.retryOrElse(string, Schedule.forever, (e) => {\n      expect(e).type.toBe<\"err-1\">()\n      return Effect.succeed(0)\n    })).type.toBe<Effect.Effect<string | number, never, \"dep-1\">>()\n    expect(string.pipe(Effect.retryOrElse(Schedule.forever, (e) => {\n      expect(e).type.toBe<\"err-1\">()\n      return Effect.succeed(0)\n    }))).type.toBe<Effect.Effect<string | number, never, \"dep-1\">>()\n\n    expect(Effect.retryOrElse(string, Schedule.forever, (_e: string) => Effect.succeed(0))).type.toBe<\n      Effect.Effect<string | number, never, \"dep-1\">\n    >()\n    expect(string.pipe(Effect.retryOrElse(Schedule.forever, (_e: string) => Effect.succeed(0)))).type.toBe<\n      Effect.Effect<string | number, never, \"dep-1\">\n    >()\n  })\n\n  it(\"do notation\", () => {\n    expect(pipe(\n      Effect.Do,\n      Effect.bind(\"a\", (scope) => {\n        expect(scope).type.toBe<{}>()\n        return Effect.succeed(1)\n      }),\n      Effect.bind(\"b\", (scope) => {\n        expect(scope).type.toBe<{ a: number }>()\n        return Effect.succeed(\"b\")\n      }),\n      Effect.let(\"c\", (scope) => {\n        expect(scope).type.toBe<{ a: number; b: string }>()\n        return true\n      })\n    )).type.toBe<Effect.Effect<{ a: number; b: string; c: boolean }>>()\n\n    expect(pipe(\n      Effect.succeed(1),\n      Effect.bindTo(\"a\"),\n      Effect.bind(\"b\", (scope) => {\n        expect(scope).type.toBe<{ a: number }>()\n        return Effect.succeed(\"b\")\n      }),\n      Effect.let(\"c\", (scope) => {\n        expect(scope).type.toBe<{ a: number; b: string }>()\n        return true\n      })\n    )).type.toBe<Effect.Effect<{ a: number; b: string; c: boolean }>>()\n  })\n\n  it(\"liftPredicate\", () => {\n    expect(pipe(\n      primitiveNumberOrString,\n      Effect.liftPredicate(Predicate.isString, (sn) => {\n        expect(sn).type.toBe<number>()\n        return \"b\" as const\n      })\n    )).type.toBe<Effect.Effect<string, \"b\">>()\n    expect(Effect.liftPredicate(primitiveNumberOrString, Predicate.isString, (sn) => {\n      expect(sn).type.toBe<number>()\n      return \"b\" as const\n    })).type.toBe<Effect.Effect<string, \"b\">>()\n\n    expect(Effect.liftPredicate(hole<Predicate.Refinement<string | number, number>>(), (sn) => {\n      expect(sn).type.toBe<string>()\n      return \"b\" as const\n    })).type.toBe<(a: string | number) => Effect.Effect<number, \"b\">>()\n    expect(Effect.liftPredicate(Predicate.isString, (sn) => {\n      expect(sn).type.toBe<unknown>()\n      return \"b\" as const\n    })).type.toBe<(a: unknown) => Effect.Effect<string, \"b\">>()\n\n    expect(pipe(\n      primitiveNumberOrString,\n      Effect.liftPredicate(\n        (sn): sn is number => {\n          expect(sn).type.toBe<string | number>()\n          return typeof sn === \"number\"\n        },\n        (sn) => {\n          expect(sn).type.toBe<string>()\n          return \"b\" as const\n        }\n      )\n    )).type.toBe<Effect.Effect<number, \"b\">>()\n    expect(Effect.liftPredicate(primitiveNumberOrString, (sn): sn is number => {\n      expect(sn).type.toBe<string | number>()\n      return typeof sn === \"number\"\n    }, (sn) => {\n      expect(sn).type.toBe<string>()\n      return \"b\" as const\n    })).type.toBe<Effect.Effect<number, \"b\">>()\n\n    expect(pipe(\n      primitiveNumberOrString,\n      Effect.liftPredicate(predicateNumbersOrStrings, (sn) => {\n        expect(sn).type.toBe<string | number>()\n        return \"b\" as const\n      })\n    )).type.toBe<Effect.Effect<string | number, \"b\">>()\n    expect(Effect.liftPredicate(primitiveNumberOrString, predicateNumbersOrStrings, (sn) => {\n      expect(sn).type.toBe<string | number>()\n      return \"b\" as const\n    })).type.toBe<Effect.Effect<string | number, \"b\">>()\n\n    expect(pipe(\n      primitiveNumber,\n      Effect.liftPredicate(predicateNumbersOrStrings, (n) => {\n        expect(n).type.toBe<number>()\n        return \"b\" as const\n      })\n    )).type.toBe<Effect.Effect<number, \"b\">>()\n    expect(Effect.liftPredicate(primitiveNumber, predicateNumbersOrStrings, (n) => {\n      expect(n).type.toBe<number>()\n      return \"b\" as const\n    })).type.toBe<Effect.Effect<number, \"b\">>()\n\n    expect(pipe(\n      primitiveNumber,\n      Effect.liftPredicate(\n        (n) => {\n          expect(n).type.toBe<number>()\n          return true\n        },\n        (n) => {\n          expect(n).type.toBe<number>()\n          return \"b\" as const\n        }\n      )\n    )).type.toBe<Effect.Effect<number, \"b\">>()\n    expect(Effect.liftPredicate(\n      primitiveNumber,\n      (n) => {\n        expect(n).type.toBe<number>()\n        return true\n      },\n      (n) => {\n        expect(n).type.toBe<number>()\n        return \"b\" as const\n      }\n    )).type.toBe<Effect.Effect<number, \"b\">>()\n  })\n\n  it(\"mapAccum\", () => {\n    expect(Effect.mapAccum(strings, 0, (s, a, i) => {\n      expect(s).type.toBe<number>()\n      expect(a).type.toBe<string>()\n      expect(i).type.toBe<number>()\n      return Effect.succeed([s + i, a])\n    })).type.toBe<Effect.Effect<[number, Array<string>]>>()\n    expect(pipe(\n      strings,\n      Effect.mapAccum(0, (s, a, i) => {\n        expect(s).type.toBe<number>()\n        expect(a).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return Effect.succeed([s + i, a])\n      })\n    )).type.toBe<Effect.Effect<[number, Array<string>]>>()\n\n    expect(Effect.mapAccum(readonlyNonEmptyStrings, 0, (s, a, i) => {\n      expect(s).type.toBe<number>()\n      expect(a).type.toBe<string>()\n      expect(i).type.toBe<number>()\n      return Effect.succeed([s + i, a])\n    })).type.toBe<Effect.Effect<[number, [string, ...Array<string>]]>>()\n    expect(pipe(\n      readonlyNonEmptyStrings,\n      Effect.mapAccum(0, (s, a, i) => {\n        expect(s).type.toBe<number>()\n        expect(a).type.toBe<string>()\n        expect(i).type.toBe<number>()\n        return Effect.succeed([s + i, a])\n      })\n    )).type.toBe<Effect.Effect<[number, [string, ...Array<string>]]>>()\n  })\n\n  it(\"Tag.Proxy\", () => {\n    expect(hole<Types.Simplify<Effect.Tag.Proxy<\"R\", {}>>>()).type.toBe<{}>()\n    expect(hole<Types.Simplify<Effect.Tag.Proxy<\"R\", { a: () => 1 }>>>())\n      .type.toBe<{ a: () => Effect.Effect<1, never, \"R\"> }>()\n    expect(hole<Types.Simplify<Effect.Tag.Proxy<\"R\", { a: (...args: ReadonlyArray<number>) => void }>>>())\n      .type.toBe<{ a: (...args: ReadonlyArray<number>) => Effect.Effect<void, never, \"R\"> }>()\n    expect(hole<Types.Simplify<Effect.Tag.Proxy<\"R\", { a: (...args: [1] | [2, 3]) => void }>>>())\n      .type.toBe<{ a: (...args: Readonly<[1] | [2, 3]>) => Effect.Effect<void, never, \"R\"> }>()\n    expect(hole<Types.Simplify<Effect.Tag.Proxy<\"R\", { a: (...args: [1] | [2, 3]) => Effect.Effect<1, 2, 3> }>>>())\n      .type.toBe<{ a: (...args: Readonly<[1] | [2, 3]>) => Effect.Effect<1, 2, 3 | \"R\"> }>()\n    expect(hole<Types.Simplify<Effect.Tag.Proxy<\"R\", { a: 1 }>>>())\n      .type.toBe<{ a: Effect.Effect<1, never, \"R\"> }>()\n    expect(hole<Types.Simplify<Effect.Tag.Proxy<\"R\", { a: () => Promise<1> }>>>())\n      .type.toBe<{ a: () => Effect.Effect<1, UnknownException, \"R\"> }>()\n  })\n\n  it(\"transposeOption\", () => {\n    expect(Effect.transposeOption(Option.none())).type.toBe<Effect.Effect<Option.Option<never>>>()\n    expect(Effect.transposeOption(Option.some(string))).type.toBe<\n      Effect.Effect<Option.Option<string>, \"err-1\", \"dep-1\">\n    >()\n  })\n\n  it(\"transposeMapOption\", () => {\n    expect(Effect.transposeMapOption(Option.none(), (value) => {\n      expect(value).type.toBe<never>()\n      return string\n    })).type.toBe<\n      Effect.Effect<Option.Option<string>, \"err-1\", \"dep-1\">\n    >()\n    expect(pipe(\n      Option.none(),\n      Effect.transposeMapOption((value) => {\n        expect(value).type.toBe<never>()\n        return string\n      })\n    )).type.toBe<\n      Effect.Effect<Option.Option<string>, \"err-1\", \"dep-1\">\n    >()\n    expect(Effect.transposeMapOption(Option.some(42), (value) => {\n      expect(value).type.toBe<number>()\n      return string\n    })).type.toBe<\n      Effect.Effect<Option.Option<string>, \"err-1\", \"dep-1\">\n    >()\n    expect(pipe(\n      Option.some(42),\n      Effect.transposeMapOption((value) => {\n        expect(value).type.toBe<number>()\n        return string\n      })\n    )).type.toBe<\n      Effect.Effect<Option.Option<string>, \"err-1\", \"dep-1\">\n    >()\n  })\n\n  it(\"fn\", () => {\n    const fn = Effect.fn((a?: string) => Effect.succeed(a), Effect.asVoid)\n    expect(fn).type.toBe<(a?: string | undefined) => Effect.Effect<void, never, never>>()\n  })\n\n  it(\"fn returns Effect subtype\", () => {\n    const fnNonGen = Effect.fn((a?: string) => Effect.succeed(a), () => Option.some(\"test\"))\n    const fnGen = Effect.fn(function*(a?: string) {\n      return Effect.succeed(a)\n    }, () => Option.some(\"test\"))\n\n    expect(fnNonGen).type.toBe<\n      (a?: string | undefined) => Effect.Effect<string, NoSuchElementException, never>\n    >()\n\n    expect(fnGen).type.toBe<\n      (a?: string | undefined) => Effect.Effect<string, NoSuchElementException, never>\n    >()\n  })\n\n  it(\"ensureSuccessType\", () => {\n    expect(Effect.succeed(123).pipe(Effect.ensureSuccessType<number>())).type.toBe<\n      Effect.Effect<number, never, never>\n    >()\n  })\n\n  it(\"ensureErrorType\", () => {\n    const withoutError = Effect.succeed(\"no error\")\n    expect(withoutError.pipe(Effect.ensureErrorType<never>())).type.toBe<Effect.Effect<string, never, never>>()\n\n    const withError = Effect.fail(new TestError1())\n    expect(withError.pipe(Effect.ensureErrorType<TestError1>())).type.toBe<Effect.Effect<never, TestError1, never>>()\n  })\n\n  it(\"ensureRequirementsType\", () => {\n    const withoutRequirements = Effect.never\n    expect(withoutRequirements.pipe(Effect.ensureRequirementsType<never>())).type.toBe<\n      Effect.Effect<never, never, never>\n    >()\n\n    const withRequirement = Effect.flatMap(TestService, () => Effect.never)\n    expect(withRequirement.pipe(Effect.ensureRequirementsType<TestService>())).type.toBe<\n      Effect.Effect<never, never, TestService>\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Either.tst.ts",
    "content": "import { Array, Either, hole, Option, pipe, Predicate } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const string$string: Either.Either<string, string>\ndeclare const number$string: Either.Either<number, string>\ndeclare const boolean$string: Either.Either<boolean, string>\ndeclare const boolean$Error: Either.Either<boolean, Error>\ndeclare const literal$Error: Either.Either<\"a\", Error>\n\ndescribe(\"Either\", () => {\n  it(\"flip\", () => {\n    expect(Either.flip(number$string)).type.toBe<Either.Either<string, number>>()\n    expect(pipe(number$string, Either.flip)).type.toBe<Either.Either<string, number>>()\n  })\n\n  it(\"try\", () => {\n    expect(Either.try(() => 1)).type.toBe<Either.Either<number, unknown>>()\n    expect(Either.try({ try: () => 1, catch: () => new Error() })).type.toBe<Either.Either<number, Error>>()\n  })\n\n  describe(\"all\", () => {\n    it(\"tuple\", () => {\n      expect(Either.all([])).type.toBe<Either.Either<[], never>>()\n      expect(Either.all([number$string])).type.toBe<Either.Either<[number], string>>()\n      expect(Either.all([number$string, boolean$string])).type.toBe<Either.Either<[number, boolean], string>>()\n      expect(Either.all([number$string, boolean$Error])).type.toBe<Either.Either<[number, boolean], string | Error>>()\n      expect(pipe([number$string, boolean$string] as const, Either.all)).type.toBe<\n        Either.Either<[number, boolean], string>\n      >()\n      expect(pipe([number$string, boolean$Error] as const, Either.all)).type.toBe<\n        Either.Either<[number, boolean], string | Error>\n      >()\n    })\n\n    it(\"struct\", () => {\n      expect(Either.all({})).type.toBe<Either.Either<{}, never>>()\n      expect(Either.all({ a: number$string })).type.toBe<Either.Either<{ a: number }, string>>()\n      expect(Either.all({ a: number$string, b: boolean$string })).type.toBe<\n        Either.Either<{ a: number; b: boolean }, string>\n      >()\n      expect(Either.all({ a: number$string, b: boolean$Error })).type.toBe<\n        Either.Either<{ a: number; b: boolean }, string | Error>\n      >()\n      expect(pipe({ a: number$string, b: boolean$string }, Either.all)).type.toBe<\n        Either.Either<{ a: number; b: boolean }, string>\n      >()\n      expect(pipe({ a: number$string, b: boolean$Error }, Either.all)).type.toBe<\n        Either.Either<{ a: number; b: boolean }, string | Error>\n      >()\n    })\n\n    it(\"array\", () => {\n      const eitherArray = hole<Array<Either.Either<number, string>>>()\n      expect(Either.all(eitherArray)).type.toBe<Either.Either<Array<number>, string>>()\n      expect(pipe(eitherArray, Either.all)).type.toBe<Either.Either<Array<number>, string>>()\n    })\n\n    it(\"record\", () => {\n      const eitherRecord = hole<Record<string, Either.Either<number, string>>>()\n      expect(Either.all(eitherRecord)).type.toBe<Either.Either<{ [x: string]: number }, string>>()\n      expect(pipe(eitherRecord, Either.all)).type.toBe<Either.Either<{ [x: string]: number }, string>>()\n    })\n  })\n\n  it(\"andThen\", () => {\n    expect(Either.andThen(string$string, number$string)).type.toBe<Either.Either<number, string>>()\n    expect(string$string.pipe(Either.andThen(number$string))).type.toBe<Either.Either<number, string>>()\n\n    expect(Either.andThen(string$string, () => number$string)).type.toBe<Either.Either<number, string>>()\n    expect(string$string.pipe(Either.andThen(() => number$string))).type.toBe<Either.Either<number, string>>()\n  })\n\n  it(\"liftPredicate\", () => {\n    const primitiveNumber = hole<number>()\n    const stringOrNumber = hole<string | number>()\n    const predicateNumberOrString = hole<Predicate.Predicate<number | string>>()\n    const refinementNumberOrStringToNumber = hole<Predicate.Refinement<number | string, number>>()\n\n    expect(\n      Either.liftPredicate(predicateNumberOrString, (sn) => {\n        expect(sn).type.toBe<string | number>()\n        return \"b\" as const\n      })\n    ).type.toBe<(a: string | number) => Either.Either<string | number, \"b\">>()\n    expect(\n      Either.liftPredicate(refinementNumberOrStringToNumber, (sn) => {\n        expect(sn).type.toBe<string | number>()\n        return \"b\" as const\n      })\n    ).type.toBe<(a: string | number) => Either.Either<number, \"b\">>()\n\n    expect(\n      Either.liftPredicate(\n        stringOrNumber,\n        (sn): sn is number => {\n          expect(sn).type.toBe<string | number>()\n          return typeof sn === \"number\"\n        },\n        (sn) => {\n          expect(sn).type.toBe<string | number>()\n          return \"b\" as const\n        }\n      )\n    ).type.toBe<Either.Either<number, \"b\">>()\n    expect(\n      pipe(\n        stringOrNumber,\n        Either.liftPredicate(\n          (sn): sn is number => {\n            expect(sn).type.toBe<string | number>()\n            return typeof sn === \"number\"\n          },\n          (sn) => {\n            expect(sn).type.toBe<string | number>()\n            return \"b\" as const\n          }\n        )\n      )\n    ).type.toBe<Either.Either<number, \"b\">>()\n\n    expect(\n      Either.liftPredicate(stringOrNumber, predicateNumberOrString, (sn) => {\n        expect(sn).type.toBe<string | number>()\n        return \"b\" as const\n      })\n    ).type.toBe<Either.Either<string | number, \"b\">>()\n    expect(\n      pipe(\n        stringOrNumber,\n        Either.liftPredicate(predicateNumberOrString, (sn) => {\n          expect(sn).type.toBe<string | number>()\n          return \"b\" as const\n        })\n      )\n    ).type.toBe<Either.Either<string | number, \"b\">>()\n\n    expect(\n      Either.liftPredicate(primitiveNumber, predicateNumberOrString, (sn) => {\n        expect(sn).type.toBe<string | number>()\n        return \"b\" as const\n      })\n    ).type.toBe<Either.Either<number, \"b\">>()\n    expect(\n      pipe(\n        primitiveNumber,\n        Either.liftPredicate(predicateNumberOrString, (sn) => {\n          expect(sn).type.toBe<string | number>()\n          return \"b\" as const\n        })\n      )\n    ).type.toBe<Either.Either<number, \"b\">>()\n  })\n\n  it(\"fromNullable\", () => {\n    const nullableString = hole<string | null>()\n    const nullableObject = hole<{ a: string } | undefined>()\n\n    expect(\n      Either.fromNullable(\n        nullableString,\n        () => new Error()\n      )\n    ).type.toBe<Either.Either<string, Error>>()\n\n    expect(\n      pipe(\n        nullableString,\n        Either.fromNullable(() => new Error())\n      )\n    ).type.toBe<Either.Either<string, Error>>()\n\n    expect(\n      Either.fromNullable(nullableObject, () => new Error())\n    ).type.toBe<Either.Either<{ a: string }, Error>>()\n\n    expect(\n      pipe(\n        nullableObject,\n        Either.fromNullable(() => new Error())\n      )\n    ).type.toBe<\n      Either.Either<{ a: string }, Error>\n    >()\n  })\n\n  it(\"filterOrLeft\", () => {\n    const predicateUnknown = hole<Predicate.Predicate<unknown>>()\n\n    const arrayOfStrings$Error = hole<Either.Either<Array<string>, Error>>()\n    expect(\n      Either.filterOrLeft(arrayOfStrings$Error, Array.isNonEmptyArray, (ss) => {\n        expect(ss).type.toBe<Array<string>>()\n        return \"b\" as const\n      })\n    ).type.toBe<Either.Either<[string, ...Array<string>], \"b\" | Error>>()\n    expect(\n      pipe(\n        arrayOfStrings$Error,\n        Either.filterOrLeft(Array.isNonEmptyArray, (ss) => {\n          expect(ss).type.toBe<Array<string>>()\n          return \"b\" as const\n        })\n      )\n    ).type.toBe<Either.Either<[string, ...Array<string>], \"b\" | Error>>()\n\n    const readonlyArrayOfStrings$Error = hole<Either.Either<ReadonlyArray<string>, Error>>()\n    expect(\n      Either.filterOrLeft(readonlyArrayOfStrings$Error, Array.isNonEmptyReadonlyArray, (ss) => {\n        expect(ss).type.toBe<ReadonlyArray<string>>()\n        return \"b\" as const\n      })\n    ).type.toBe<Either.Either<readonly [string, ...Array<string>], \"b\" | Error>>()\n    expect(\n      pipe(\n        readonlyArrayOfStrings$Error,\n        Either.filterOrLeft(Array.isNonEmptyReadonlyArray, (ss) => {\n          expect(ss).type.toBe<ReadonlyArray<string>>()\n          return \"b\" as const\n        })\n      )\n    ).type.toBe<Either.Either<readonly [string, ...Array<string>], \"b\" | Error>>()\n\n    // @tstyche fixme -- This doesn't work but it should\n    expect(\n      Either.filterOrLeft(literal$Error, Predicate.isString, (a) => {\n        // @tstyche fixme -- This doesn't work but it should\n        expect(a).type.toBe<\"a\">()\n        return \"b\" as const\n      })\n    ).type.toBe<Either.Either<\"a\", \"b\" | Error>>()\n    expect(\n      pipe(\n        literal$Error,\n        Either.filterOrLeft(Predicate.isString, (a) => {\n          expect(a).type.toBe<\"a\">()\n          return \"b\" as const\n        })\n      )\n    ).type.toBe<Either.Either<\"a\", \"b\" | Error>>()\n\n    // @tstyche fixme -- This doesn't work but it should\n    expect(\n      Either.filterOrLeft(literal$Error, Predicate.isString, (_s: string) => \"b\" as const)\n    ).type.toBe<Either.Either<\"a\", \"b\" | Error>>()\n    expect(\n      pipe(\n        literal$Error,\n        Either.filterOrLeft(Predicate.isString, (_s: string) => \"b\" as const)\n      )\n    ).type.toBe<Either.Either<\"a\", \"b\" | Error>>()\n\n    expect(\n      Either.filterOrLeft(literal$Error, predicateUnknown, (a) => {\n        expect(a).type.toBe<\"a\">()\n        return \"b\" as const\n      })\n    ).type.toBe<Either.Either<\"a\", \"b\" | Error>>()\n    expect(\n      pipe(\n        literal$Error,\n        Either.filterOrLeft(predicateUnknown, (a) => {\n          expect(a).type.toBe<\"a\">()\n          return \"b\" as const\n        })\n      )\n    ).type.toBe<Either.Either<\"a\", \"b\" | Error>>()\n\n    expect(\n      Either.filterOrLeft(literal$Error, predicateUnknown, (_s: string) => \"b\" as const)\n    ).type.toBe<Either.Either<\"a\", \"b\" | Error>>()\n    expect(\n      pipe(\n        literal$Error,\n        Either.filterOrLeft(predicateUnknown, (_s: string) => \"b\" as const)\n      )\n    ).type.toBe<Either.Either<\"a\", \"b\" | Error>>()\n  })\n\n  it(\"type level helpers\", () => {\n    type R = Either.Either.Right<typeof number$string>\n    type L = Either.Either.Left<typeof number$string>\n    expect<R>().type.toBe<number>()\n    expect<L>().type.toBe<string>()\n  })\n\n  it(\"do notation\", () => {\n    expect(\n      pipe(\n        Either.Do,\n        Either.bind(\"a\", (scope) => {\n          expect(scope).type.toBe<{}>()\n          return Either.right(1)\n        }),\n        Either.bind(\"b\", (scope) => {\n          expect(scope).type.toBe<{ a: number }>()\n          return Either.right(\"b\")\n        }),\n        Either.let(\"c\", (scope) => {\n          expect(scope).type.toBe<{ a: number; b: string }>()\n          return true\n        })\n      )\n    ).type.toBe<Either.Either<{ a: number; b: string; c: boolean }, never>>()\n\n    expect(\n      pipe(\n        Either.right(1),\n        Either.bindTo(\"a\"),\n        Either.bind(\"b\", (scope) => {\n          expect(scope).type.toBe<{ a: number }>()\n          return Either.right(\"b\")\n        }),\n        Either.let(\"c\", (scope) => {\n          expect(scope).type.toBe<{ a: number; b: string }>()\n          return true\n        })\n      )\n    ).type.toBe<Either.Either<{ a: number; b: string; c: boolean }, never>>()\n  })\n})\n\nit(\"transposeMapOption\", () => {\n  expect(Either.transposeMapOption(Option.none(), (value) => {\n    expect(value).type.toBe<never>()\n    return string$string\n  })).type.toBe<\n    Either.Either<Option.Option<string>, string>\n  >()\n  expect(pipe(\n    Option.none(),\n    Either.transposeMapOption((value) => {\n      expect(value).type.toBe<never>()\n      return string$string\n    })\n  )).type.toBe<\n    Either.Either<Option.Option<string>, string>\n  >()\n  expect(Either.transposeMapOption(Option.some(42), (value) => {\n    expect(value).type.toBe<number>()\n    return string$string\n  })).type.toBe<\n    Either.Either<Option.Option<string>, string>\n  >()\n  expect(pipe(\n    Option.some(42),\n    Either.transposeMapOption((value) => {\n      expect(value).type.toBe<number>()\n      return string$string\n    })\n  )).type.toBe<\n    Either.Either<Option.Option<string>, string>\n  >()\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Equal.tst.ts",
    "content": "import { Data, Equal, Hash } from \"effect\"\n\nexport class MyClass extends Data.TaggedClass(\"mytag\")<{}> {\n  // should support `Hash.symbol` as method\n  [Hash.symbol]() {\n    return 0\n  }\n  // should support `Equal.symbol` as method\n  [Equal.symbol]() {\n    return false\n  }\n}\n"
  },
  {
    "path": "packages/effect/dtslint/Exit.tst.ts",
    "content": "import * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Predicate from \"effect/Predicate\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const number$string: Exit.Exit<number, string>\ndeclare const stringOrNumber$string: Exit.Exit<string | number, string>\n\ndescribe(\"Exit\", () => {\n  it(\"exists\", () => {\n    if (Exit.exists(stringOrNumber$string, Predicate.isString)) {\n      expect(stringOrNumber$string).type.toBe<Exit.Exit<string, never>>()\n    }\n    if (pipe(stringOrNumber$string, Exit.exists(Predicate.isString))) {\n      // @tstyche fixme -- This doesn't work but it should\n      expect(stringOrNumber$string).type.toBe<Exit.Exit<string, never>>()\n    }\n    if (Exit.exists(Predicate.isString)(stringOrNumber$string)) {\n      expect(stringOrNumber$string).type.toBe<Exit.Exit<string, never>>()\n    }\n\n    if (\n      pipe(\n        number$string,\n        Exit.exists((n) => {\n          expect(n).type.toBe<number>()\n          return true\n        })\n      )\n    ) {\n      expect(number$string).type.toBe<Exit.Exit<number, string>>()\n    }\n\n    if (\n      pipe(\n        number$string,\n        Exit.exists((_sn: string | number) => true)\n      )\n    ) {\n      expect(number$string).type.toBe<Exit.Exit<number, string>>()\n    }\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Fiber.tst.ts",
    "content": "import type { Effect, Exit } from \"effect\"\nimport { Fiber } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const string: Fiber.Fiber<string>\ndeclare const number: Fiber.Fiber<number>\ndeclare const arrayOfStringOrNumber: Array<Fiber.Fiber<string> | Fiber.Fiber<number>>\n\ndescribe(\"Fiber\", () => {\n  it(\"awaitAll\", () => {\n    expect(Fiber.awaitAll([string, number])).type.toBe<\n      Effect.Effect<[Exit.Exit<string>, Exit.Exit<number>]>\n    >()\n    expect(Fiber.awaitAll(new Set([string, number]))).type.toBe<\n      Effect.Effect<Array<Exit.Exit<string> | Exit.Exit<number>>>\n    >()\n    expect(Fiber.awaitAll(arrayOfStringOrNumber)).type.toBe<\n      Effect.Effect<Array<Exit.Exit<string> | Exit.Exit<number>>>\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Function.tst.ts",
    "content": "import { flow, Function, identity, Option, pipe } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Function\", () => {\n  describe(\"pipe\", () => {\n    it(\"We should only have one error for the missing definition\", () => {\n      const _x = (): number =>\n        pipe(\n          1,\n          // @ts-expect-error: Cannot find name 'add'\n          add(1),\n          identity\n        )\n\n      const _y = (): (n: number) => number =>\n        flow(\n          // @ts-expect-error: Cannot find name 'add'\n          add(1),\n          identity\n        )\n\n      const _z = (): number =>\n        Option.some(1).pipe(\n          // @ts-expect-error: Cannot find name 'add'\n          add(1),\n          identity\n        )\n    })\n\n    it(\"should preserve literal types (issue #5963)\", () => {\n      const result = pipe(\n        [1, 2, 3] as const,\n        (x) => x\n      )\n      expect(result).type.toBe<readonly [1, 2, 3]>()\n    })\n  })\n\n  it(\"apply\", () => {\n    const apply1 = Function.apply(\"a\")\n    const apply2 = Function.apply(\"a\", 1)\n\n    const countArgs = (...args: Array<unknown>) => args.length\n    const arg1 = (a: string) => a\n    const arg2 = (a: string, b: number) => `${a}${b}`\n    const arg3 = (a: number) => a\n\n    expect(apply1(countArgs)).type.toBe<number>()\n    expect(apply1(arg1)).type.toBe<string>()\n    expect(apply1).type.not.toBeCallableWith(arg2)\n    expect(apply1).type.not.toBeCallableWith(arg3)\n\n    expect(apply2(countArgs)).type.toBe<number>()\n    expect(apply2(arg1)).type.toBe<string>()\n    expect(apply2(arg2)).type.toBe<string>()\n    expect(apply1).type.not.toBeCallableWith(arg3)\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/HKT.tst.ts",
    "content": "import type { HKT } from \"effect\"\n\nexport function testIssue536<F extends HKT.TypeLambda, G extends HKT.TypeLambda, R, W, E, A>(\n  x: HKT.Kind<F, R, W, E, A>\n): HKT.Kind<G, R, W, E, A> {\n  // @ts-expect-error: Type 'Kind<F, R, W, E, A>' is not assignable to type 'Kind<G, R, W, E, A>'\n  return x\n}\n"
  },
  {
    "path": "packages/effect/dtslint/HashMap.tst.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type { Option } from \"effect\"\nimport { HashMap, hole, pipe, Predicate } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const literals: HashMap.HashMap<\"k\", \"v\">\ndeclare const string$numberOrString: HashMap.HashMap<string, number | string>\n\ndescribe(\"HashMap\", () => {\n  it(\"HashMap.Key type helper\", () => {\n    type K = HashMap.HashMap.Key<typeof literals>\n    expect(hole<K>()).type.toBe<\"k\">()\n  })\n\n  it(\"HashMap.Value type helper\", () => {\n    type V = HashMap.HashMap.Value<typeof literals>\n    expect<V>().type.toBe<\"v\">()\n  })\n\n  it(\"HashMap.Entry type helper\", () => {\n    expect<HashMap.HashMap.Entry<typeof literals>>().type.toBe<[\"k\", \"v\"]>()\n  })\n\n  it(\"filter\", () => {\n    // Predicate\n    expect(\n      HashMap.filter(string$numberOrString, (value, key) => {\n        expect(value).type.toBe<string | number>()\n        expect(key).type.toBe<string>()\n        return true\n      })\n    ).type.toBe<HashMap.HashMap<string, string | number>>()\n    expect(\n      pipe(\n        string$numberOrString,\n        HashMap.filter((value, key) => {\n          expect(value).type.toBe<string | number>()\n          expect(key).type.toBe<string>()\n          return true\n        })\n      )\n    ).type.toBe<HashMap.HashMap<string, string | number>>()\n\n    // Refinement\n    expect(HashMap.filter(string$numberOrString, Predicate.isNumber)).type.toBe<HashMap.HashMap<string, number>>()\n    expect(\n      pipe(string$numberOrString, HashMap.filter(Predicate.isNumber))\n    ).type.toBe<HashMap.HashMap<string, number>>()\n  })\n\n  it(\"findFirst\", () => {\n    // Predicate\n    expect(HashMap.findFirst(string$numberOrString, (value, key) => {\n      expect(value).type.toBe<string | number>()\n      expect(key).type.toBe<string>()\n      return true\n    })).type.toBe<Option.Option<[string, string | number]>>()\n    expect(pipe(\n      string$numberOrString,\n      HashMap.findFirst((value, key) => {\n        expect(value).type.toBe<string | number>()\n        expect(key).type.toBe<string>()\n        return true\n      })\n    )).type.toBe<Option.Option<[string, string | number]>>()\n\n    // Refinement\n    expect(HashMap.findFirst(string$numberOrString, Predicate.isNumber))\n      .type.toBe<Option.Option<[string, number]>>()\n    expect(\n      pipe(string$numberOrString, HashMap.findFirst(Predicate.isNumber))\n    ).type.toBe<Option.Option<[string, number]>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/HashSet.tst.ts",
    "content": "import { HashSet, pipe, Predicate } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const number: HashSet.HashSet<number>\ndeclare const numberOrString: HashSet.HashSet<number | string>\n\ndeclare const predicateNumberOrString: Predicate.Predicate<number | string>\n\ndescribe(\"HashSet\", () => {\n  it(\"every\", () => {\n    if (HashSet.every(numberOrString, Predicate.isString)) {\n      expect(numberOrString).type.toBe<HashSet.HashSet<string>>()\n    }\n    if (pipe(numberOrString, HashSet.every(Predicate.isString))) {\n      // @tstyche fixme -- This doesn't work but it should\n      expect(numberOrString).type.toBe<HashSet.HashSet<string>>()\n    }\n    if (HashSet.every(Predicate.isString)(numberOrString)) {\n      expect(numberOrString).type.toBe<HashSet.HashSet<string>>()\n    }\n\n    expect(HashSet.every(numberOrString, (value) => {\n      expect(value).type.toBe<string | number>()\n      return true\n    })).type.toBe<boolean>()\n    expect(pipe(\n      numberOrString,\n      HashSet.every((value) => {\n        expect(value).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<boolean>()\n  })\n\n  it(\"partition\", () => {\n    // Predicate\n    expect(HashSet.partition(numberOrString, (value) => {\n      expect(value).type.toBe<string | number>()\n      return true\n    })).type.toBe<[excluded: HashSet.HashSet<string | number>, satisfying: HashSet.HashSet<string | number>]>()\n    expect(pipe(\n      numberOrString,\n      HashSet.partition((value) => {\n        expect(value).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<[excluded: HashSet.HashSet<string | number>, satisfying: HashSet.HashSet<string | number>]>()\n\n    // Refinement\n    expect(HashSet.partition(numberOrString, Predicate.isNumber))\n      .type.toBe<[excluded: HashSet.HashSet<string>, satisfying: HashSet.HashSet<number>]>()\n\n    expect(pipe(numberOrString, HashSet.partition(Predicate.isNumber)))\n      .type.toBe<[excluded: HashSet.HashSet<string>, satisfying: HashSet.HashSet<number>]>()\n  })\n\n  it(\"filter\", () => {\n    // Predicate\n    expect(HashSet.filter(numberOrString, (value) => {\n      expect(value).type.toBe<string | number>()\n      return true\n    })).type.toBe<HashSet.HashSet<string | number>>()\n    expect(pipe(\n      numberOrString,\n      HashSet.filter((value) => {\n        expect(value).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<HashSet.HashSet<string | number>>()\n\n    expect(pipe(numberOrString, HashSet.filter(predicateNumberOrString)))\n      .type.toBe<HashSet.HashSet<string | number>>()\n    expect(pipe(number, HashSet.filter(predicateNumberOrString)))\n      .type.toBe<HashSet.HashSet<number>>()\n\n    // Refinement\n    expect(HashSet.filter(numberOrString, Predicate.isNumber))\n      .type.toBe<HashSet.HashSet<number>>()\n    expect(pipe(numberOrString, HashSet.filter(Predicate.isNumber)))\n      .type.toBe<HashSet.HashSet<number>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Layer.tst.ts",
    "content": "import { Context, Layer, Schedule } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ninterface In1 {}\ninterface Err1 {}\ninterface Out1 {}\n\ndeclare const layer1: Layer.Layer<Out1, Err1, In1>\n\ninterface In2 {}\ninterface Err2 {}\ninterface Out2 {}\n\ndeclare const layer2: Layer.Layer<Out2, Err2, In2>\n\ninterface In3 {}\ninterface Err3 {}\ninterface Out3 {}\n\ndeclare const layer3: Layer.Layer<Out3, Err3, In3>\n\nclass TestService1 extends Context.Tag(\"TestService1\")<TestService1, {}>() {}\n\ndescribe(\"Layer\", () => {\n  it(\"merge\", () => {\n    expect(Layer.merge).type.not.toBeCallableWith()\n\n    expect(Layer.merge(layer1, layer2)).type.toBe<Layer.Layer<Out1 | Out2, Err1 | Err2, In1 | In2>>()\n    expect(layer1.pipe(Layer.merge(layer2))).type.toBe<Layer.Layer<Out1 | Out2, Err1 | Err2, In1 | In2>>()\n  })\n\n  it(\"mergeAll\", () => {\n    expect(Layer.mergeAll).type.not.toBeCallableWith()\n\n    expect(Layer.mergeAll(layer1)).type.toBe<Layer.Layer<Out1, Err1, In1>>()\n    expect(Layer.mergeAll(layer1, layer2)).type.toBe<Layer.Layer<Out1 | Out2, Err1 | Err2, In1 | In2>>()\n    expect(Layer.mergeAll(layer1, layer2, layer3))\n      .type.toBe<Layer.Layer<Out1 | Out2 | Out3, Err1 | Err2 | Err3, In1 | In2 | In3>>()\n  })\n\n  it(\"retry\", () => {\n    expect(Layer.retry(layer1, Schedule.recurs(1))).type.toBe<Layer.Layer<Out1, Err1, In1>>()\n    expect(layer1.pipe(Layer.retry(Schedule.recurs(1)))).type.toBe<Layer.Layer<Out1, Err1, In1>>()\n  })\n\n  it(\"ensureSuccessType\", () => {\n    expect(layer1.pipe(Layer.ensureSuccessType<Out1>())).type.toBe<Layer.Layer<Out1, Err1, In1>>()\n  })\n\n  it(\"ensureErrorType\", () => {\n    const withoutError = Layer.succeed(TestService1, {})\n    expect(withoutError.pipe(Layer.ensureErrorType<never>())).type.toBe<Layer.Layer<TestService1, never, never>>()\n\n    const withError = layer1\n    expect(withError.pipe(Layer.ensureErrorType<Err1>())).type.toBe<Layer.Layer<Out1, Err1, In1>>()\n  })\n\n  it(\"ensureRequirementsType\", () => {\n    const withoutRequirements = Layer.succeed(TestService1, {})\n    expect(withoutRequirements.pipe(Layer.ensureRequirementsType<never>())).type.toBe<\n      Layer.Layer<TestService1, never, never>\n    >()\n\n    const withRequirement = layer1\n    expect(withRequirement.pipe(Layer.ensureRequirementsType<In1>())).type.toBe<\n      Layer.Layer<Out1, Err1, In1>\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/List.tst.ts",
    "content": "import type { Option } from \"effect\"\nimport { List, pipe, Predicate } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const number: List.List<number>\ndeclare const string: List.List<string>\ndeclare const nonEmptyNumber: List.Cons<number>\ndeclare const nonEmptyString: List.Cons<string>\ndeclare const numberOrString: List.List<number | string>\ndeclare const predicateNumberOrString: Predicate.Predicate<number | string>\n\ndescribe(\"List\", () => {\n  it(\"every\", () => {\n    if (List.every(numberOrString, Predicate.isString)) {\n      expect(numberOrString).type.toBe<List.List<string>>()\n    }\n    if (pipe(numberOrString, List.every(Predicate.isString))) {\n      // @tstyche fixme -- This doesn't work but it should\n      expect(numberOrString).type.toBe<List.List<string>>()\n    }\n    if (List.every(Predicate.isString)(numberOrString)) {\n      expect(numberOrString).type.toBe<List.List<string>>()\n    }\n\n    expect(\n      List.every(numberOrString, (value) => {\n        expect(value).type.toBe<string | number>()\n        return true\n      })\n    ).type.toBe<boolean>()\n    expect(pipe(\n      numberOrString,\n      List.every((value) => {\n        expect(value).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<boolean>()\n  })\n\n  it(\"some\", () => {\n    if (List.some(numberOrString, Predicate.isString)) {\n      expect(numberOrString).type.toBe<List.Cons<string | number>>()\n    }\n    if (pipe(numberOrString, List.some(Predicate.isString))) {\n      // @tstyche fixme -- This doesn't work but it should\n      expect(numberOrString).type.toBe<List.Cons<string | number>>()\n    }\n    if (List.some(Predicate.isString)(numberOrString)) {\n      expect(numberOrString).type.toBe<List.Cons<string | number>>()\n    }\n\n    expect(\n      List.some(numberOrString, (value) => {\n        expect(value).type.toBe<string | number>()\n        return true\n      })\n    ).type.toBe<boolean>()\n    expect(pipe(\n      numberOrString,\n      List.some((value) => {\n        expect(value).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<boolean>()\n  })\n\n  it(\"partition\", () => {\n    // Predicate\n    expect(List.partition(numberOrString, (value) => {\n      expect(value).type.toBe<string | number>()\n      return true\n    })).type.toBe<\n      [excluded: List.List<string | number>, satisfying: List.List<string | number>]\n    >()\n    expect(pipe(\n      numberOrString,\n      List.partition((value) => {\n        expect(value).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<\n      [excluded: List.List<string | number>, satisfying: List.List<string | number>]\n    >()\n    expect(List.partition(number, predicateNumberOrString)).type.toBe<\n      [excluded: List.List<number>, satisfying: List.List<number>]\n    >()\n    expect(pipe(number, List.partition(predicateNumberOrString))).type.toBe<\n      [excluded: List.List<number>, satisfying: List.List<number>]\n    >()\n\n    // Refinement\n    expect(List.partition(numberOrString, Predicate.isNumber)).type.toBe<\n      [excluded: List.List<string>, satisfying: List.List<number>]\n    >()\n\n    expect(pipe(numberOrString, List.partition(Predicate.isNumber))).type.toBe<\n      [excluded: List.List<string>, satisfying: List.List<number>]\n    >()\n  })\n\n  it(\"append\", () => {\n    expect(List.append(numberOrString, true)).type.toBe<List.Cons<string | number | boolean>>()\n    expect(pipe(numberOrString, List.append(true))).type.toBe<List.Cons<string | number | boolean>>()\n    expect(List.append(true)(numberOrString)).type.toBe<List.Cons<string | number | boolean>>()\n  })\n\n  it(\"prepend\", () => {\n    expect(List.prepend(numberOrString, true)).type.toBe<List.Cons<string | number | boolean>>()\n    expect(pipe(numberOrString, List.prepend(true))).type.toBe<List.Cons<string | number | boolean>>()\n    expect(List.prepend(true)(numberOrString)).type.toBe<List.Cons<string | number | boolean>>()\n  })\n\n  it(\"map\", () => {\n    expect(List.map(number, (n) => n + 1)).type.toBe<List.List<number>>()\n    expect(pipe(number, List.map((n) => n + 1))).type.toBe<List.List<number>>()\n    expect(List.map(nonEmptyNumber, (n) => n + 1)).type.toBe<List.Cons<number>>()\n    expect(pipe(nonEmptyNumber, List.map((n) => n + 1))).type.toBe<List.Cons<number>>()\n  })\n\n  it(\"filter\", () => {\n    // Predicate\n    expect(List.filter(numberOrString, (value) => {\n      expect(value).type.toBe<string | number>()\n      return true\n    })).type.toBe<List.List<number | string>>()\n    expect(pipe(\n      numberOrString,\n      List.filter((value) => {\n        expect(value).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<List.List<number | string>>()\n\n    expect(List.filter(number, predicateNumberOrString)).type.toBe<List.List<number>>()\n    expect(pipe(number, List.filter(predicateNumberOrString))).type.toBe<List.List<number>>()\n\n    // Refinement\n    expect(List.filter(numberOrString, Predicate.isNumber)).type.toBe<List.List<number>>()\n    expect(pipe(numberOrString, List.filter(Predicate.isNumber))).type.toBe<List.List<number>>()\n  })\n\n  it(\"findFirst\", () => {\n    // Predicate\n    expect(List.findFirst(numberOrString, (value) => {\n      expect(value).type.toBe<string | number>()\n      return true\n    })).type.toBe<Option.Option<string | number>>()\n    expect(pipe(\n      numberOrString,\n      List.findFirst((value) => {\n        expect(value).type.toBe<string | number>()\n        return true\n      })\n    )).type.toBe<Option.Option<string | number>>()\n\n    expect(List.findFirst(number, predicateNumberOrString)).type.toBe<Option.Option<number>>()\n    expect(pipe(number, List.findFirst(predicateNumberOrString))).type.toBe<Option.Option<number>>()\n\n    // Refinement\n    expect(List.findFirst(numberOrString, Predicate.isNumber)).type.toBe<Option.Option<number>>()\n    expect(pipe(numberOrString, List.findFirst(Predicate.isNumber))).type.toBe<Option.Option<number>>()\n  })\n\n  it(\"appendAll\", () => {\n    expect(List.appendAll(string, number)).type.toBe<List.List<string | number>>()\n    expect(pipe(string, List.appendAll(number))).type.toBe<List.List<string | number>>()\n    expect(List.appendAll(nonEmptyString, number)).type.toBe<List.Cons<string | number>>()\n    expect(pipe(nonEmptyString, List.appendAll(number))).type.toBe<List.Cons<string | number>>()\n    expect(List.appendAll(string, nonEmptyNumber)).type.toBe<List.Cons<string | number>>()\n    expect(pipe(string, List.appendAll(nonEmptyNumber))).type.toBe<List.Cons<string | number>>()\n    expect(List.appendAll(nonEmptyString, nonEmptyNumber)).type.toBe<List.Cons<string | number>>()\n    expect(pipe(nonEmptyString, List.appendAll(nonEmptyNumber))).type.toBe<List.Cons<string | number>>()\n  })\n\n  it(\"prependAll\", () => {\n    expect(List.prependAll(string, number)).type.toBe<List.List<string | number>>()\n    expect(pipe(string, List.prependAll(number))).type.toBe<List.List<string | number>>()\n    expect(List.prependAll(nonEmptyString, number)).type.toBe<List.Cons<string | number>>()\n    expect(pipe(nonEmptyString, List.prependAll(number))).type.toBe<List.Cons<string | number>>()\n    expect(List.prependAll(string, nonEmptyNumber)).type.toBe<List.Cons<string | number>>()\n    expect(pipe(string, List.prependAll(nonEmptyNumber))).type.toBe<List.Cons<string | number>>()\n    expect(List.prependAll(nonEmptyString, nonEmptyNumber)).type.toBe<List.Cons<string | number>>()\n    expect(pipe(nonEmptyString, List.prependAll(nonEmptyNumber))).type.toBe<List.Cons<string | number>>()\n  })\n\n  it(\"flatMap\", () => {\n    expect(\n      List.flatMap(string, (value) => {\n        expect(value).type.toBe<string>()\n        return List.empty<number>()\n      })\n    ).type.toBe<List.List<number>>()\n    expect(\n      pipe(\n        string,\n        List.flatMap((value) => {\n          expect(value).type.toBe<string>()\n          return List.empty<number>()\n        })\n      )\n    ).type.toBe<List.List<number>>()\n\n    expect(\n      List.flatMap(nonEmptyString, (value) => {\n        expect(value).type.toBe<string>()\n        return List.empty<number>()\n      })\n    ).type.toBe<List.List<number>>()\n    expect(\n      pipe(\n        nonEmptyString,\n        List.flatMap((value) => {\n          expect(value).type.toBe<string>()\n          return List.empty<number>()\n        })\n      )\n    ).type.toBe<List.List<number>>()\n\n    expect(\n      List.flatMap(nonEmptyString, (value) => {\n        expect(value).type.toBe<string>()\n        return List.of(value.length)\n      })\n    ).type.toBe<List.Cons<number>>()\n    expect(\n      pipe(\n        nonEmptyString,\n        List.flatMap((value) => {\n          expect(value).type.toBe<string>()\n          return List.of(value.length)\n        })\n      )\n    ).type.toBe<List.Cons<number>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/ManagedRuntime.tst.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type { ManagedRuntime } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const runtime: ManagedRuntime.ManagedRuntime<\"context\", \"error\">\n\ndescribe(\"ManagedRuntime\", () => {\n  it(\"ManagedRuntime.Context type helper\", () => {\n    expect<ManagedRuntime.ManagedRuntime.Context<typeof runtime>>().type.toBe<\"context\">()\n  })\n\n  it(\"ManagedRuntime.Error type helper\", () => {\n    expect<ManagedRuntime.ManagedRuntime.Error<typeof runtime>>().type.toBe<\"error\">()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Match.tst.ts",
    "content": "import { Either, hole, Match, Option, pipe, Predicate } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ntype Value = { _tag: \"A\"; a: number } | { _tag: \"B\"; b: number }\ndeclare const value: Value\ndeclare const handlerA: (_: { _tag: \"A\"; a: number }) => string\nconst isArray = (_: unknown): _ is ReadonlyArray<unknown> => Array.isArray(_)\n\ndescribe(\"Match\", () => {\n  it(\"type\", () => {\n    expect(\n      Match.type<Value>().pipe(\n        Match.when(Match.any, (v) => {\n          expect(v).type.toBe<Value>()\n          return \"a\"\n        }),\n        Match.exhaustive\n      )\n    ).type.toBe<(u: Value) => string>()\n  })\n\n  it(\"value\", () => {\n    expect(\n      Match.value(hole<Value>()).pipe(\n        Match.when(Match.any, (v) => {\n          expect(v).type.toBe<Value>()\n          return \"a\"\n        }),\n        Match.exhaustive\n      )\n    ).type.toBe<string>()\n  })\n\n  it(\"withReturnType\", () => {\n    expect(\n      Match.type<{ a: number } | { b: string }>().pipe(\n        Match.withReturnType<string>(),\n        Match.when({ a: Match.number }, (_) =>\n          // @ts-expect-error: Type 'number' is not assignable to type 'string'\n          _.a),\n        Match.when({ b: Match.string }, (_) => _.b),\n        Match.exhaustive\n      )\n    ).type.toBe<(u: { a: number } | { b: string }) => string>()\n  })\n\n  it(\"orElse\", () => {\n    expect(\n      Match.value(hole<string | number>()).pipe(\n        Match.when(Match.string, (s) => {\n          expect(s).type.toBe<string>()\n          return Symbol.for(s)\n        }),\n        Match.orElse((n) => {\n          expect(n).type.toBe<number>()\n          return true\n        })\n      )\n    ).type.toBe<boolean | symbol>()\n  })\n\n  it(\"option\", () => {\n    expect(\n      Match.value(hole<string | number>()).pipe(\n        Match.when(Match.string, (s) => {\n          expect(s).type.toBe<string>()\n          return Symbol.for(s)\n        }),\n        Match.option\n      )\n    ).type.toBe<Option.Option<symbol>>()\n  })\n\n  it(\"either\", () => {\n    expect(\n      Match.value(hole<string | number>()).pipe(\n        Match.when(Match.string, (s) => {\n          expect(s).type.toBe<string>()\n          return Symbol.for(s)\n        }),\n        Match.either\n      )\n    ).type.toBe<Either.Either<symbol, number>>()\n  })\n\n  describe(\"when\", () => {\n    it(\"schema exhaustive-literal\", () => {\n      expect(\n        pipe(\n          Match.value(hole<{ _tag: \"A\"; a: number | string } | { _tag: \"B\"; b: number }>()),\n          Match.when({ _tag: Match.is(\"A\", \"B\"), a: Match.number }, (v) => {\n            expect(v).type.toBe<{ _tag: \"A\"; a: number }>()\n            return Either.right(v._tag)\n          }),\n          Match.when({ _tag: Match.string, a: Match.string }, (v) => {\n            expect(v).type.toBe<{ _tag: \"A\"; a: string }>()\n            return Either.right(v._tag)\n          }),\n          Match.when({ b: Match.number }, (v) => {\n            expect(v).type.toBe<{ _tag: \"B\"; b: number }>()\n            return Either.left(v._tag)\n          }),\n          Match.orElse((v) => {\n            expect(v).type.toBe<{ _tag: \"A\"; a: number | string }>()\n            throw \"absurd\"\n          })\n        )\n      ).type.toBe<Either.Either<\"A\", \"B\">>()\n    })\n\n    it(\"tuples\", () => {\n      expect(\n        pipe(\n          Match.value(hole<[string, string]>()),\n          Match.when([\"yeah\"], (v) => {\n            expect(v).type.toBe<readonly [\"yeah\", string]>()\n            return true\n          }),\n          Match.option\n        )\n      ).type.toBe<Option.Option<boolean>>()\n    })\n\n    it(\"not literal\", () => {\n      expect(\n        pipe(\n          Match.value(hole<string | number>()),\n          Match.not(\"hi\", (v) => {\n            expect(v).type.toBe<string | number>()\n            return \"a\"\n          }),\n          Match.orElse((v) => {\n            expect(v).type.toBe<\"hi\">()\n            return \"b\"\n          })\n        )\n      ).type.toBe<string>()\n    })\n\n    it(\"literals\", () => {\n      expect(\n        pipe(\n          Match.value(hole<string>()),\n          Match.when(\"yeah\", (v) => {\n            expect(v).type.toBe<\"yeah\">()\n            return v === \"yeah\"\n          }),\n          Match.orElse((v) => {\n            expect(v).type.toBe<string>()\n            return \"nah\"\n          })\n        )\n      ).type.toBe<string | boolean>()\n    })\n\n    it(\"nested\", () => {\n      expect(\n        pipe(\n          Match.value(\n            hole<\n              | { foo: { bar: { baz: { qux: string } } } }\n              | { foo: { bar: { baz: { qux: number } } } }\n              | { foo: { bar: null } }\n            >()\n          ),\n          Match.when({ foo: { bar: { baz: { qux: 2 } } } }, (v) => {\n            expect(v).type.toBe<{ foo: { bar: { baz: { qux: 2 } } } }>()\n            return `literal ${v.foo.bar.baz.qux}`\n          }),\n          Match.when({ foo: { bar: { baz: { qux: \"b\" } } } }, (v) => {\n            expect(v).type.toBe<{ foo: { bar: { baz: { qux: \"b\" } } } }>()\n            return `literal ${v.foo.bar.baz.qux}`\n          }),\n          Match.when({ foo: { bar: { baz: { qux: Match.number } } } }, (v) => v.foo.bar.baz.qux),\n          Match.when({ foo: { bar: { baz: { qux: Match.string } } } }, (v) => v.foo.bar.baz.qux),\n          Match.when({ foo: { bar: null } }, (v) => v.foo.bar),\n          Match.exhaustive\n        )\n      ).type.toBe<string | number | null>()\n    })\n\n    it(\"deep recursive\", () => {\n      type A = null | string | number | { [K in string]: A }\n      expect(\n        pipe(\n          Match.value(hole<A>()),\n          Match.when(Predicate.isNull, (v) => {\n            expect(v).type.toBe<null>()\n            return \"null\"\n          }),\n          Match.when(Predicate.isBoolean, (v) => {\n            expect(v).type.toBe<boolean>()\n            return \"boolean\"\n          }),\n          Match.when(Predicate.isNumber, (v) => {\n            expect(v).type.toBe<number>()\n            return \"number\"\n          }),\n          Match.when(Predicate.isString, (v) => {\n            expect(v).type.toBe<string>()\n            return \"string\"\n          }),\n          Match.when(Match.record, (v) => {\n            expect(v).type.toBe<{ [x: string]: A }>()\n            return \"record\"\n          }),\n          Match.when(Predicate.isSymbol, (v) => {\n            expect(v).type.toBe<symbol>()\n            return \"symbol\"\n          }),\n          Match.when(Predicate.isReadonlyRecord, (v) => {\n            expect(v).type.toBe<{ readonly [x: string]: unknown; readonly [x: symbol]: unknown }>()\n            return \"readonlyrecord\"\n          }),\n          Match.exhaustive\n        )\n      ).type.toBe<string>()\n    })\n\n    it(\"instanceOf\", () => {\n      class Test {}\n      class Test2 {}\n      expect(\n        pipe(\n          Match.value<Test | Test2>(new Test()),\n          Match.when(Match.instanceOf(Test), (v) => {\n            expect(v).type.toBe<Test>()\n            return 1\n          }),\n          Match.orElse((v) => {\n            expect(v).type.toBe<Test | Test2>()\n            return 0\n          })\n        )\n      ).type.toBe<number>()\n\n      const match = pipe(\n        Match.type<Uint8Array | Uint16Array>(),\n        Match.when(Match.instanceOf(Uint8Array), (v) => {\n          // @tstyche if { target: \">=5.7\" } -- Before TypeScript 5.7, 'Uint8Array' was not generic\n          expect(v).type.toBe<Uint8Array<ArrayBuffer>>()\n          // @tstyche if { target: \"<5.7\" }\n          expect(v).type.toBe<Uint8Array>()\n          return \"uint8\"\n        }),\n        Match.when(Match.instanceOf(Uint16Array), (v) => {\n          // @tstyche if { target: \">=5.7\" } -- Before TypeScript 5.7, 'Uint16Array' was not generic\n          expect(v).type.toBe<Uint16Array<ArrayBuffer>>()\n          // @tstyche if { target: \"<5.7\" }\n          expect(v).type.toBe<Uint16Array>()\n          return \"uint16\"\n        }),\n        Match.orElse((v) => {\n          // @tstyche if { target: \">=5.7\" } -- Before TypeScript 5.7, 'Uint8Array' and 'Uint16Array' were not generic\n          expect(v).type.toBe<Uint8Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike>>()\n          // @tstyche if { target: \"<5.7\" }\n          expect(v).type.toBe<Uint8Array | Uint16Array>()\n          return \"a\"\n        })\n      )\n\n      expect(match(new Uint8Array())).type.toBe<string>()\n      expect(match(new Uint16Array())).type.toBe<string>()\n    })\n\n    it(\"instanceOf prop\", () => {\n      class Test {}\n      expect(\n        pipe(\n          Match.value<{ test: Test | null }>({ test: new Test() }),\n          Match.when({ test: Match.instanceOf(Test) }, ({ test }) => {\n            expect(test).type.toBe<Test>()\n            return 1\n          }),\n          Match.orElse(({ test }) => {\n            expect(test).type.toBe<Test | null>()\n            return 0\n          })\n        )\n      ).type.toBe<number>()\n    })\n\n    it(\"refinement with unknown\", () => {\n      const isArray = (_: unknown): _ is ReadonlyArray<unknown> => Array.isArray(_)\n      expect(\n        pipe(\n          Match.value(hole<string | Array<number>>()),\n          Match.when(isArray, (v) => {\n            expect(v).type.toBe<Array<number>>()\n            return \"array\"\n          }),\n          Match.when(Predicate.isString, (v) => {\n            expect(v).type.toBe<string>()\n            return \"string\"\n          }),\n          Match.exhaustive\n        )\n      ).type.toBe<string>()\n    })\n\n    it(\"refinement nested with unknown\", () => {\n      expect(\n        pipe(\n          Match.value(hole<{ readonly a: string | Array<number> }>()),\n          Match.when({ a: isArray }, (v) => {\n            expect(v).type.toBe<{ a: Array<number> }>()\n            return \"array\"\n          }),\n          Match.orElse((v) => {\n            expect(v).type.toBe<{ readonly a: string | Array<number> }>()\n            return \"fail\"\n          })\n        )\n      ).type.toBe<string>()\n    })\n\n    it(\"unknown refinement\", () => {\n      expect(\n        pipe(\n          Match.value(hole<unknown>()),\n          Match.when(Predicate.isReadonlyRecord, (v) => {\n            expect(v).type.toBe<{ readonly [x: string]: unknown; readonly [x: symbol]: unknown }>()\n            return \"record\"\n          }),\n          Match.orElse(() => \"unknown\")\n        )\n      ).type.toBe<string>()\n    })\n\n    it(\"any refinement\", () => {\n      expect(\n        pipe(\n          Match.value(hole<any>()),\n          Match.when(Predicate.isReadonlyRecord, (v) => {\n            expect(v).type.toBe<{ readonly [x: string]: unknown; readonly [x: symbol]: unknown }>()\n            return \"record\"\n          }),\n          Match.orElse(() => \"unknown\")\n        )\n      ).type.toBe<string>()\n    })\n\n    it(\"pattern type is not fixed by the function argument type\", () => {\n      type T =\n        | { resolveType: \"A\"; value: number }\n        | { resolveType: \"B\"; value: number }\n        | { resolveType: \"C\"; value: number }\n      const doStuff = (x: { value: number }) => x\n      expect(\n        pipe(\n          Match.value(hole<T>()),\n          Match.when({ resolveType: Match.is(\"A\", \"B\") }, doStuff),\n          Match.not({ resolveType: Match.is(\"A\", \"B\") }, doStuff),\n          Match.exhaustive\n        )\n      ).type.toBe<{ value: number }>()\n    })\n\n    it(\"non literal refinement\", () => {\n      const a: number = 1\n      const b: string = \"b\"\n      expect(\n        Match.value(hole<{ a: number; b: string }>()).pipe(\n          Match.when({ a, b }, (v) => {\n            expect(v).type.toBe<{ a: number; b: string }>()\n            return \"ok\"\n          }),\n          Match.either\n        )\n      ).type.toBe<Either.Either<string, { a: number; b: string }>>()\n    })\n  })\n\n  it(\"valueTags\", () => {\n    expect(\n      pipe(\n        value,\n        Match.valueTags({\n          A: (A) => {\n            expect(A).type.toBe<{ _tag: \"A\"; a: number }>()\n            return A.a\n          },\n          B: (B) => {\n            expect(B).type.toBe<{ _tag: \"B\"; b: number }>()\n            return \"B\"\n          }\n        })\n      )\n    ).type.toBe<string | number>()\n\n    expect(\n      Match.valueTags(value, {\n        A: (A) => {\n          expect(A).type.toBe<{ _tag: \"A\"; a: number }>()\n          return A.a\n        },\n        B: (B) => {\n          expect(B).type.toBe<{ _tag: \"B\"; b: number }>()\n          return \"B\"\n        }\n      })\n    ).type.toBe<string | number>()\n\n    pipe(\n      value,\n      Match.valueTags({\n        A: (_A) => _A.a,\n        B: () => \"B\",\n        // @ts-expect-error: Type '() => boolean' is not assignable to type 'never'\n        C: () => false\n      })\n    )\n\n    Match.valueTags(value, {\n      A: (_A) => _A.a,\n      B: () => \"B\",\n      // @ts-expect-error: Type '() => boolean' is not assignable to type 'never'\n      C: () => false\n    })\n  })\n\n  it(\"typeTags\", () => {\n    expect(\n      Match.typeTags<Value>()({\n        A: (A) => {\n          expect(A).type.toBe<{ _tag: \"A\"; a: number }>()\n          return A.a\n        },\n        B: (B) => {\n          expect(B).type.toBe<{ _tag: \"B\"; b: number }>()\n          return \"B\"\n        }\n      })(value)\n    ).type.toBe<string | number>()\n\n    expect(\n      Match.typeTags<Value, string | number>()({\n        A: (A) => {\n          expect(A).type.toBe<{ _tag: \"A\"; a: number }>()\n          return A.a\n        },\n        B: (B) => {\n          expect(B).type.toBe<{ _tag: \"B\"; b: number }>()\n          return \"B\"\n        }\n      })(value)\n    ).type.toBe<string | number>()\n\n    Match.typeTags<Value>()({\n      A: (_) => _.a,\n      B: () => \"B\",\n      // @ts-expect-error: Type '() => boolean' is not assignable to type 'never'\n      C: () => false\n    })(value)\n\n    Match.typeTags<Value, string>()({\n      // @ts-expect-error: Type 'number' is not assignable to type 'string'\n      A: (_) => _.a,\n      B: () => \"B\",\n      // @ts-expect-error: Type '() => boolean' is not assignable to type 'never'\n      C: () => false\n    })(value)\n  })\n\n  it(\"discriminators\", () => {\n    expect(\n      pipe(\n        Match.type<Value>(),\n        Match.discriminators(\"_tag\")({\n          A: (A) => {\n            expect(A).type.toBe<{ _tag: \"A\"; a: number }>()\n            return A.a\n          },\n          B: (B) => {\n            expect(B).type.toBe<{ _tag: \"B\"; b: number }>()\n            return \"B\"\n          }\n        }),\n        Match.exhaustive\n      )(value)\n    ).type.toBe<string | number>()\n\n    pipe(\n      Match.type<Value>(),\n      Match.discriminators(\"_tag\")({\n        A: (_) => _.a,\n        B: () => \"B\",\n        // @ts-expect-error: Type '() => boolean' is not assignable to type 'never'\n        C: () => false\n      }),\n      Match.exhaustive\n    )(value)\n  })\n\n  it(\"discriminatorsExhaustive\", () => {\n    expect(\n      pipe(\n        Match.type<Value>(),\n        Match.discriminatorsExhaustive(\"_tag\")({\n          A: (A) => {\n            expect(A).type.toBe<{ _tag: \"A\"; a: number }>()\n            return A.a\n          },\n          B: (B) => {\n            expect(B).type.toBe<{ _tag: \"B\"; b: number }>()\n            return \"B\"\n          }\n        })\n      )(value)\n    ).type.toBe<string | number>()\n\n    pipe(\n      Match.type<Value>(),\n      Match.discriminatorsExhaustive(\"_tag\")({\n        A: (_) => _.a,\n        B: () => \"B\",\n        // @ts-expect-error: Type '() => boolean' is not assignable to type 'never'\n        C: () => false\n      })\n    )(value)\n  })\n\n  it(\"tags\", () => {\n    expect(\n      pipe(\n        Match.type<Value>(),\n        Match.tags({\n          A: (A) => {\n            expect(A).type.toBe<{ _tag: \"A\"; a: number }>()\n            return A.a\n          },\n          B: (B) => {\n            expect(B).type.toBe<{ _tag: \"B\"; b: number }>()\n            return \"B\"\n          }\n        }),\n        Match.exhaustive\n      )(value)\n    ).type.toBe<string | number>()\n\n    pipe(\n      Match.type<Value>(),\n      Match.tags({\n        A: (_) => _.a,\n        B: () => \"B\",\n        // @ts-expect-error: Type '() => boolean' is not assignable to type 'never'\n        C: () => false\n      }),\n      Match.exhaustive\n    )(value)\n  })\n\n  it(\"tagsExhaustive\", () => {\n    expect(\n      pipe(\n        Match.type<Value>(),\n        Match.tagsExhaustive({\n          A: (A) => {\n            expect(A).type.toBe<{ _tag: \"A\"; a: number }>()\n            return A.a\n          },\n          B: (B) => {\n            expect(B).type.toBe<{ _tag: \"B\"; b: number }>()\n            return \"B\"\n          }\n        })\n      )(value)\n    ).type.toBe<string | number>()\n\n    pipe(\n      Match.type<Value>(),\n      Match.tagsExhaustive({\n        A: (_) => _.a,\n        B: () => \"B\",\n        // @ts-expect-error: Type '() => boolean' is not assignable to type 'never'\n        C: () => false\n      })\n    )(value)\n  })\n\n  it(\"tag\", () => {\n    expect(\n      pipe(\n        Match.type<Value>(),\n        Match.tag(\"A\", handlerA),\n        Match.orElse((B) => {\n          expect(B).type.toBe<{ _tag: \"B\"; b: number }>()\n          return B.b\n        })\n      )(value)\n    ).type.toBe<string | number>()\n  })\n\n  it(\"tagStartsWith\", () => {\n    expect(\n      pipe(\n        Match.type<Value>(),\n        Match.tagStartsWith(\"A\", handlerA),\n        Match.orElse((B) => {\n          expect(B).type.toBe<{ _tag: \"B\"; b: number }>()\n          return B.b\n        })\n      )(value)\n    ).type.toBe<string | number>()\n  })\n\n  it(\"Option.isSome\", () => {\n    expect(\n      pipe(\n        Match.type<{ maybeNumber: Option.Option<number> }>(),\n        Match.when({ maybeNumber: Option.isSome }, (v) => {\n          expect(v).type.toBe<{ maybeNumber: Option.Some<number> }>()\n          return v.maybeNumber.value\n        }),\n        Match.orElse((B) => {\n          expect(B).type.toBe<{ maybeNumber: Option.Option<number> }>()\n          return undefined\n        })\n      )({ maybeNumber: Option.some(1) })\n    ).type.toBe<number | undefined>()\n  })\n\n  it(\"whenOr refinement with pattern\", () => {\n    class Person {\n      get contactable() {\n        return true\n      }\n    }\n    expect(\n      pipe(\n        Match.type<{ maybeNumber: Option.Option<number>; person: Person }>(),\n        Match.whenOr({\n          maybeNumber: {\n            _tag: Match.is(\"Some\", \"None\")\n          },\n          person: { contactable: true }\n        }, ({ person }) => {\n          expect(person.contactable).type.toBe<true>()\n          return person.contactable\n        }),\n        Match.orElse(({ person }) => {\n          expect(person).type.toBe<Person>()\n          return false\n        })\n      )({ maybeNumber: Option.some(1), person: new Person() })\n    ).type.toBe<boolean>()\n  })\n\n  it(\".is prop\", () => {\n    Match.value<{ foo: string }>({ foo: \"bar\" }).pipe(\n      Match.when({ foo: Match.is(\"baz\") }, (_) => {\n        expect(_).type.toBe<{ foo: \"baz\" }>()\n        return true\n      }),\n      Match.when({ foo: (s): s is \"baz\" => s === \"baz\" }, (_) => {\n        expect(_).type.toBe<{ foo: \"baz\" }>()\n        return true\n      }),\n      Match.orElse((_) => {\n        expect(_).type.toBe<{ foo: string }>()\n        return true\n      })\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Micro.tst.ts",
    "content": "import { hole, Micro } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Micro\", () => {\n  it(\"catchCauseIf\", () => {\n    expect(\n      hole<Micro.Micro<number, string | number, \"a\">>().pipe(Micro.catchCauseIf(\n        (cause): cause is Micro.MicroCause<string> => true,\n        (cause) => {\n          expect(cause).type.toBe<Micro.MicroCause<string>>()\n          return hole<Micro.Micro<Date, boolean, \"b\">>()\n        }\n      ))\n    ).type.toBe<Micro.Micro<number | Date, number | boolean, \"a\" | \"b\">>()\n\n    expect(Micro.catchCauseIf(\n      hole<Micro.Micro<number, string | number, \"a\">>(),\n      (cause): cause is Micro.MicroCause<string> => true,\n      (cause) => {\n        expect(cause).type.toBe<Micro.MicroCause<string>>()\n        return hole<Micro.Micro<Date, boolean, \"b\">>()\n      }\n    )).type.toBe<Micro.Micro<number | Date, number | boolean, \"a\" | \"b\">>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Number.tst.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type { Option } from \"effect\"\nimport { HashSet, Number, pipe } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Number\", () => {\n  const a = 10\n  const b = -5\n\n  it(\"isNumber\", () => {\n    const value: unknown = 42\n    expect(value).type.not.toBeAssignableTo<number>()\n\n    if (Number.isNumber(value)) {\n      expect(value).type.toBe<number>()\n    }\n\n    // Type guard should properly narrow union types\n    const numOrString: number | string = 123\n    if (Number.isNumber(numOrString)) {\n      expect(numOrString).type.toBe<number>()\n      expect(numOrString).type.not.toBeAssignableFrom<string>()\n    }\n  })\n\n  it(\"sum\", () => {\n    const dataLast = Number.sum(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.sum\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.sum(a, b)).type.toBe<number>()\n    expect(pipe(a, Number.sum(b))).type.toBe<number>()\n  })\n\n  it(\"subtract\", () => {\n    const dataLast = Number.subtract(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.subtract\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.subtract(a, b)).type.toBe<number>()\n    expect(pipe(a, Number.subtract(b))).type.toBe<number>()\n  })\n\n  it(\"multiply\", () => {\n    const dataLast = Number.multiply(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.multiply\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.multiply(a, b)).type.toBe<number>()\n    expect(pipe(a, Number.multiply(b))).type.toBe<number>()\n  })\n\n  it(\"divide\", () => {\n    const dataLast = Number.divide(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.divide\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.divide(a, b)).type.toBe<Option.Option<number>>()\n    expect(pipe(a, Number.divide(b))).type.toBe<Option.Option<number>>()\n  })\n\n  it(\"unsafeDivide\", () => {\n    const dataLast = Number.unsafeDivide(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.unsafeDivide\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.unsafeDivide(a, b)).type.toBe<number>()\n    expect(pipe(a, Number.unsafeDivide(b))).type.toBe<number>()\n  })\n\n  it(\"increment\", () => {\n    type DataFirst = typeof Number.increment\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.increment(a)).type.toBe<number>()\n    expect(pipe(a, Number.increment)).type.toBe<number>()\n  })\n\n  it(\"decrement\", () => {\n    type DataFirst = typeof Number.decrement\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.decrement(a)).type.toBe<number>()\n    expect(pipe(a, Number.decrement)).type.toBe<number>()\n  })\n\n  it(\"Equivalence\", () => {\n    type DataFirst = typeof Number.Equivalence\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    // test the output type\n    expect(Number.Equivalence(a, b)).type.toBe<boolean>()\n  })\n\n  it(\"Order\", () => {\n    type DataFirst = typeof Number.Order\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    // test the output type\n    expect(Number.Order(a, b)).type.toBe<-1 | 0 | 1>()\n  })\n\n  it(\"lessThan\", () => {\n    const dataLast = Number.lessThan(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.lessThan\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.lessThan(a, b)).type.toBe<boolean>()\n    expect(pipe(a, Number.lessThan(b))).type.toBe<boolean>()\n  })\n\n  it(\"lessThanOrEqualTo\", () => {\n    const dataLast = Number.lessThanOrEqualTo(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.lessThanOrEqualTo\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.lessThanOrEqualTo(a, b)).type.toBe<boolean>()\n    expect(pipe(a, Number.lessThanOrEqualTo(b))).type.toBe<boolean>()\n  })\n\n  it(\"greaterThan\", () => {\n    const dataLast = Number.greaterThan(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.greaterThan\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.greaterThan(a, b)).type.toBe<boolean>()\n    expect(pipe(a, Number.greaterThan(b))).type.toBe<boolean>()\n  })\n\n  it(\"greaterThanOrEqualTo\", () => {\n    const dataLast = Number.greaterThanOrEqualTo(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.greaterThanOrEqualTo\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.greaterThanOrEqualTo(a, b)).type.toBe<boolean>()\n    expect(pipe(a, Number.greaterThanOrEqualTo(b))).type.toBe<boolean>()\n  })\n\n  it(\"between\", () => {\n    const options = { minimum: a, maximum: b }\n\n    const dataLast = Number.between(options)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.between\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<\n      [number, { minimum: number; maximum: number }]\n    >()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.between(a, options)).type.toBe<boolean>()\n    expect(pipe(a, Number.between(options))).type.toBe<boolean>()\n  })\n\n  it(\"clamp\", () => {\n    const options = { minimum: a, maximum: b }\n\n    const dataLast = Number.clamp(options)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.clamp\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<\n      [number, { minimum: number; maximum: number }]\n    >()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.clamp(a, options)).type.toBe<number>()\n    expect(pipe(a, Number.clamp(options))).type.toBe<number>()\n  })\n\n  it(\"min\", () => {\n    const dataLast = Number.min(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.min\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.min(a, b)).type.toBe<number>()\n    expect(pipe(a, Number.min(b))).type.toBe<number>()\n  })\n\n  it(\"max\", () => {\n    const dataLast = Number.max(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.max\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.max(a, b)).type.toBe<number>()\n    expect(pipe(a, Number.max(b))).type.toBe<number>()\n  })\n\n  it(\"sign\", () => {\n    type DataFirst = typeof Number.sign\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.sign(a)).type.toBe<-1 | 0 | 1>()\n  })\n\n  it(\"sumAll\", () => {\n    type DataFirst = typeof Number.sumAll\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<\n      [Iterable<number>]\n    >()\n\n    // test the output type\n    expect(Number.sumAll([a, b, a, b, a, b])).type.toBe<number>()\n    expect(Number.sumAll(HashSet.make(a, b, a, b, a, b))).type.toBe<number>()\n  })\n\n  it(\"multiplyAll\", () => {\n    type DataFirst = typeof Number.multiplyAll\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<\n      [Iterable<number>]\n    >()\n\n    // test the output type\n    expect(Number.multiplyAll([a, b, a, b, a, b])).type.toBe<number>()\n    expect(\n      Number.multiplyAll(HashSet.make(a, b, a, b, a, b))\n    ).type.toBe<number>()\n  })\n\n  it(\"remainder\", () => {\n    const dataLast = Number.remainder(a)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.remainder\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.remainder(a, b)).type.toBe<number>()\n    expect(pipe(a, Number.remainder(b))).type.toBe<number>()\n  })\n\n  it(\"nextPow2\", () => {\n    type DataFirst = typeof Number.nextPow2\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.nextPow2(a)).type.toBe<number>()\n  })\n\n  it(\"parse\", () => {\n    type DataFirst = typeof Number.parse\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[string]>()\n\n    // test the output type\n    expect(Number.parse(\"123\")).type.toBe<Option.Option<number>>()\n  })\n\n  it(\"round\", () => {\n    const dataLast = Number.round(2)\n    type DataLast = typeof dataLast\n    type DataFirst = typeof Number.round\n\n    // test the input type\n    expect<Parameters<DataFirst>>().type.toBeAssignableFrom<[number, number]>()\n\n    expect<Parameters<DataLast>>().type.toBeAssignableFrom<[number]>()\n\n    // test the output type\n    expect(Number.round(a, 2)).type.toBe<number>()\n    expect(pipe(a, Number.round(2))).type.toBe<number>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Option.tst.ts",
    "content": "import { hole, Option, pipe, Predicate } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const number: Option.Option<number>\ndeclare const string: Option.Option<string>\ndeclare const numberOrString: Option.Option<string | number>\n\ndeclare const primitiveNumber: number\ndeclare const primitiveNumberOrString: string | number\ndeclare const predicateNumbersOrStrings: Predicate.Predicate<number | string>\n\ndescribe(\"Option\", () => {\n  it(\"liftPredicate\", () => {\n    expect(\n      Option.liftPredicate(primitiveNumberOrString, Predicate.isString)\n    ).type.toBe<Option.Option<string>>()\n    expect(\n      pipe(primitiveNumberOrString, Option.liftPredicate(Predicate.isString))\n    ).type.toBe<Option.Option<string>>()\n\n    expect(\n      Option.liftPredicate(\n        primitiveNumberOrString,\n        (n): n is number => {\n          expect(n).type.toBe<string | number>()\n          return typeof n === \"number\"\n        }\n      )\n    ).type.toBe<Option.Option<number>>()\n    expect(\n      pipe(\n        primitiveNumberOrString,\n        Option.liftPredicate(\n          (n): n is number => {\n            expect(n).type.toBe<string | number>()\n            return typeof n === \"number\"\n          }\n        )\n      )\n    ).type.toBe<Option.Option<number>>()\n\n    expect(\n      Option.liftPredicate(primitiveNumber, predicateNumbersOrStrings)\n    ).type.toBe<Option.Option<number>>()\n    expect(\n      pipe(primitiveNumber, Option.liftPredicate(predicateNumbersOrStrings))\n    ).type.toBe<Option.Option<number>>()\n  })\n\n  it(\"getOrElse\", () => {\n    expect(Option.getOrElse(Option.some(\"a\"), () => null)).type.toBe<string | null>()\n    expect(pipe(Option.some(\"a\"), Option.getOrElse(() => null))).type.toBe<string | null>()\n  })\n\n  it(\"filter\", () => {\n    expect(Option.filter(number, predicateNumbersOrStrings)).type.toBe<Option.Option<number>>()\n    expect(pipe(number, Option.filter(predicateNumbersOrStrings))).type.toBe<Option.Option<number>>()\n\n    expect(pipe(numberOrString, Option.filter(Predicate.isString))).type.toBe<Option.Option<string>>()\n    expect(Option.filter(numberOrString, Predicate.isString)).type.toBe<Option.Option<string>>()\n\n    expect(\n      Option.filter(number, (value) => {\n        expect(value).type.toBe<number>()\n        return true\n      })\n    ).type.toBe<Option.Option<number>>()\n    expect(\n      pipe(\n        number,\n        Option.filter((value) => {\n          expect(value).type.toBe<number>()\n          return true\n        })\n      )\n    ).type.toBe<Option.Option<number>>()\n  })\n\n  describe(\"all\", () => {\n    it(\"tuple\", () => {\n      expect(Option.all([])).type.toBe<Option.Option<[]>>()\n      expect(Option.all([Option.some(1)])).type.toBe<Option.Option<[number]>>()\n      expect(Option.all([Option.some(1), Option.some(\"b\")])).type.toBe<Option.Option<[number, string]>>()\n      expect(pipe([Option.some(1), Option.some(\"b\")] as const, Option.all)).type.toBe<Option.Option<[number, string]>>()\n    })\n\n    it(\"struct\", () => {\n      expect(Option.all({})).type.toBe<Option.Option<{}>>()\n      expect(Option.all({ a: Option.some(1) })).type.toBe<Option.Option<{ a: number }>>()\n      expect(Option.all({ a: Option.some(1), b: Option.some(\"b\") }))\n        .type.toBe<Option.Option<{ a: number; b: string }>>()\n      expect(pipe({ a: Option.some(1), b: Option.some(\"b\") }, Option.all))\n        .type.toBe<Option.Option<{ a: number; b: string }>>()\n    })\n\n    it(\"array\", () => {\n      const optionArray = hole<Array<Option.Option<string>>>()\n      expect(Option.all(optionArray)).type.toBe<Option.Option<Array<string>>>()\n      expect(pipe(optionArray, Option.all)).type.toBe<Option.Option<Array<string>>>()\n    })\n\n    it(\"record\", () => {\n      const optionRecord = hole<Record<string, Option.Option<string>>>()\n      expect(Option.all(optionRecord)).type.toBe<Option.Option<{ [x: string]: string }>>()\n      expect(pipe(optionRecord, Option.all)).type.toBe<Option.Option<{ [x: string]: string }>>()\n    })\n  })\n\n  it(\"exists\", () => {\n    if (Option.exists(Predicate.isString)(numberOrString)) {\n      expect(numberOrString).type.toBe<Option.Option<string>>()\n    }\n    if (Option.exists(numberOrString, Predicate.isString)) {\n      expect(numberOrString).type.toBe<Option.Option<string>>()\n    }\n\n    expect(\n      Option.exists(number, (value) => {\n        expect(value).type.toBe<number>()\n        return true\n      })\n    ).type.toBe<boolean>()\n    expect(\n      pipe(\n        number,\n        Option.exists((value) => {\n          expect(value).type.toBe<number>()\n          return true\n        })\n      )\n    ).type.toBe<boolean>()\n  })\n\n  it(\"andThen\", () => {\n    expect(Option.andThen(numberOrString, numberOrString))\n      .type.toBe<Option.Option<string | number>>()\n    expect(Option.andThen(numberOrString, () => numberOrString))\n      .type.toBe<Option.Option<string | number>>()\n    expect(numberOrString.pipe(Option.andThen(numberOrString)))\n      .type.toBe<Option.Option<string | number>>()\n    expect(numberOrString.pipe(Option.andThen(() => numberOrString)))\n      .type.toBe<Option.Option<string | number>>()\n  })\n\n  it(\"Option.Value type helper\", () => {\n    type V = Option.Option.Value<typeof numberOrString>\n    expect<V>().type.toBe<string | number>()\n  })\n\n  it(\"do notation\", () => {\n    expect(\n      pipe(\n        Option.Do,\n        Option.bind(\"a\", (scope) => {\n          expect(scope).type.toBe<{}>()\n          return Option.some(1)\n        }),\n        Option.bind(\"b\", (scope) => {\n          expect(scope).type.toBe<{ a: number }>()\n          return Option.some(\"b\")\n        }),\n        Option.let(\"c\", (scope) => {\n          expect(scope).type.toBe<{ a: number; b: string }>()\n          return true\n        })\n      )\n    ).type.toBe<Option.Option<{ a: number; b: string; c: boolean }>>()\n\n    expect(\n      pipe(\n        Option.some(1),\n        Option.bindTo(\"a\"),\n        Option.bind(\"b\", (scope) => {\n          expect(scope).type.toBe<{ a: number }>()\n          return Option.some(\"b\")\n        }),\n        Option.let(\"c\", (scope) => {\n          expect(scope).type.toBe<{ a: number; b: string }>()\n          return true\n        })\n      )\n    ).type.toBe<Option.Option<{ a: number; b: string; c: boolean }>>()\n  })\n\n  describe(\"firstSomeOf\", () => {\n    it(\"should error for invalid type parameter\", () => {\n      expect(Option.firstSomeOf<number>).type.not.toBeCallableWith(\n        [number, string]\n      )\n      expect(pipe).type.not.toBeCallableWith(\n        [number, string],\n        Option.firstSomeOf<number>\n      )\n    })\n\n    it(\"should work for heterogeneous usage\", () => {\n      expect(Option.firstSomeOf([number, string])).type.toBe<Option.Option<string | number>>()\n      expect(pipe([number, string], Option.firstSomeOf)).type.toBe<Option.Option<string | number>>()\n    })\n\n    it(\"should work for heterogeneous usage of iterable union\", () => {\n      expect(\n        Option.firstSomeOf(\n          hole<\n            | Iterable<Option.Option<number>>\n            | [Option.Option<string>]\n          >()\n        )\n      ).type.toBe<Option.Option<string | number>>()\n      expect(\n        pipe(\n          hole<\n            | Iterable<Option.Option<number>>\n            | [Option.Option<string>]\n          >(),\n          Option.firstSomeOf\n        )\n      ).type.toBe<Option.Option<string | number>>()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/ParseResult.tst.ts",
    "content": "import type * as ParseResult from \"effect/ParseResult\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const issue: ParseResult.ParseIssue\n\ndescribe(\"ParseResult\", () => {\n  it(\"should always have an `actual` field\", () => {\n    expect(issue.actual)\n      .type.toBe<unknown>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Predicate.tst.ts",
    "content": "import { hole, pipe, Predicate } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const u: unknown\ndeclare const anys: ReadonlyArray<any>\ndeclare const unknowns: ReadonlyArray<unknown>\ndeclare const numberOrNull: ReadonlyArray<number | null>\ndeclare const numberOrUndefined: ReadonlyArray<number | undefined>\ndeclare const numberOrNullOrUndefined: ReadonlyArray<number | null | undefined>\n\ndescribe(\"Predicate\", () => {\n  it(\"isString\", () => {\n    expect(unknowns.filter(Predicate.isString)).type.toBe<Array<string>>()\n  })\n\n  it(\"isNumber\", () => {\n    expect(unknowns.filter(Predicate.isNumber)).type.toBe<Array<number>>()\n  })\n\n  it(\"isBoolean\", () => {\n    expect(unknowns.filter(Predicate.isBoolean)).type.toBe<Array<boolean>>()\n  })\n\n  it(\"isBigInt\", () => {\n    expect(unknowns.filter(Predicate.isBigInt)).type.toBe<Array<bigint>>()\n  })\n\n  it(\"isSymbol\", () => {\n    expect(unknowns.filter(Predicate.isSymbol)).type.toBe<Array<symbol>>()\n  })\n\n  it(\"isUndefined\", () => {\n    expect(unknowns.filter(Predicate.isUndefined)).type.toBe<Array<undefined>>()\n  })\n\n  it(\"isNotUndefined\", () => {\n    expect(numberOrUndefined.filter(Predicate.isNotUndefined)).type.toBe<Array<number>>()\n    expect(numberOrNullOrUndefined.filter(Predicate.isNotUndefined)).type.toBe<Array<number | null>>()\n  })\n\n  it(\"isNull\", () => {\n    expect(unknowns.filter(Predicate.isNull)).type.toBe<Array<null>>()\n  })\n\n  it(\"isNotNull\", () => {\n    expect(numberOrNull.filter(Predicate.isNotNull)).type.toBe<Array<number>>()\n    expect(numberOrNullOrUndefined.filter(Predicate.isNotNull)).type.toBe<Array<number | undefined>>()\n  })\n\n  it(\"isNever\", () => {\n    expect(unknowns.filter(Predicate.isNever)).type.toBe<Array<never>>()\n  })\n\n  it(\"isUnknown\", () => {\n    expect(anys.filter(Predicate.isUnknown)).type.toBe<Array<unknown>>()\n  })\n\n  it(\"isObject\", () => {\n    expect(anys.filter(Predicate.isObject)).type.toBe<Array<object>>()\n  })\n\n  it(\"isTagged\", () => {\n    expect(anys.filter(Predicate.isTagged(\"a\"))).type.toBe<Array<{ _tag: \"a\" }>>()\n  })\n\n  it(\"isNullable\", () => {\n    expect(numberOrNull.filter(Predicate.isNullable)).type.toBe<Array<null>>()\n    expect(numberOrUndefined.filter(Predicate.isNullable)).type.toBe<Array<undefined>>()\n    expect(numberOrNullOrUndefined.filter(Predicate.isNullable)).type.toBe<Array<null | undefined>>()\n\n    if (Predicate.isNullable(u)) {\n      expect(u).type.toBe<never>()\n    }\n  })\n\n  it(\"isNotNullable\", () => {\n    expect(numberOrNull.filter(Predicate.isNotNullable)).type.toBe<Array<number>>()\n    expect(numberOrUndefined.filter(Predicate.isNotNullable)).type.toBe<Array<number>>()\n    expect(numberOrNullOrUndefined.filter(Predicate.isNotNullable)).type.toBe<Array<number>>()\n\n    if (Predicate.isNotNullable(u)) {\n      expect(u).type.toBe<{}>()\n    }\n  })\n\n  it(\"isError\", () => {\n    expect(unknowns.filter(Predicate.isError)).type.toBe<Array<Error>>()\n  })\n\n  it(\"isDate\", () => {\n    expect(unknowns.filter(Predicate.isDate)).type.toBe<Array<Date>>()\n  })\n\n  it(\"isRecord\", () => {\n    expect(unknowns.filter(Predicate.isRecord)).type.toBe<Array<{ [x: string]: unknown; [x: symbol]: unknown }>>()\n  })\n\n  it(\"isReadonlyRecord\", () => {\n    expect(unknowns.filter(Predicate.isReadonlyRecord)).type.toBe<\n      Array<{ readonly [x: string]: unknown; readonly [x: symbol]: unknown }>\n    >()\n  })\n\n  it(\"isTupleOf\", () => {\n    if (Predicate.isTupleOf(unknowns, 3)) {\n      expect(unknowns).type.toBe<[unknown, unknown, unknown]>()\n    }\n  })\n\n  it(\"isTupleOfAtLeast\", () => {\n    if (Predicate.isTupleOfAtLeast(unknowns, 3)) {\n      expect(unknowns).type.toBe<[unknown, unknown, unknown, ...Array<unknown>]>()\n    }\n  })\n\n  it(\"isRegExp\", () => {\n    expect(unknowns.filter(Predicate.isRegExp)).type.toBe<Array<RegExp>>()\n  })\n\n  it(\"compose\", () => {\n    interface NonEmptyStringBrand {\n      readonly NonEmptyString: unique symbol\n    }\n    type NonEmptyString = string & NonEmptyStringBrand\n    const isNonEmptyString = hole<Predicate.Refinement<string, NonEmptyString>>()\n\n    expect(pipe(Predicate.isString, Predicate.compose(isNonEmptyString)))\n      .type.toBe<Predicate.Refinement<unknown, NonEmptyString>>()\n\n    expect(Predicate.compose(Predicate.isString, isNonEmptyString))\n      .type.toBe<Predicate.Refinement<unknown, NonEmptyString>>()\n\n    expect(\n      pipe(\n        Predicate.isString,\n        Predicate.compose((s): s is NonEmptyString => {\n          expect(s).type.toBe<string>()\n          return s.length > 0\n        })\n      )\n    ).type.toBe<Predicate.Refinement<unknown, NonEmptyString>>()\n\n    expect(Predicate.compose(Predicate.isString, (s): s is NonEmptyString => {\n      expect(s).type.toBe<string>()\n      return s.length > 0\n    }))\n      .type.toBe<Predicate.Refinement<unknown, NonEmptyString>>()\n\n    expect(pipe(Predicate.isString, Predicate.compose((s) => /^a/.test(s))))\n      .type.toBe<Predicate.Refinement<unknown, string>>()\n  })\n\n  it(\"and\", () => {\n    const isPositive = hole<Predicate.Predicate<number>>()\n    const isLessThan2 = hole<Predicate.Predicate<number>>()\n\n    expect(pipe(isPositive, Predicate.and(isLessThan2)))\n      .type.toBe<Predicate.Predicate<number>>()\n\n    expect(Predicate.and(isPositive, isLessThan2))\n      .type.toBe<Predicate.Predicate<number>>()\n\n    expect(pipe(Predicate.isNumber, Predicate.and(isPositive)))\n      .type.toBe<Predicate.Predicate<number>>()\n\n    expect(Predicate.and(Predicate.isNumber, isPositive))\n      .type.toBe<Predicate.Predicate<number>>()\n\n    const hasa = hole<Predicate.Refinement<unknown, { a: unknown }>>()\n    const hasb = hole<Predicate.Refinement<unknown, { b: unknown }>>()\n\n    expect(pipe(hasa, Predicate.and(hasb)))\n      .type.toBe<Predicate.Refinement<unknown, { a: unknown } & { b: unknown }>>()\n\n    expect(Predicate.and(hasa, hasb))\n      .type.toBe<Predicate.Refinement<unknown, { a: unknown } & { b: unknown }>>()\n  })\n\n  it(\"or\", () => {\n    expect(\n      pipe(\n        hole<Predicate.Predicate<number>>(),\n        Predicate.or(hole<Predicate.Predicate<number>>())\n      )\n    ).type.toBe<Predicate.Predicate<number>>()\n\n    expect(Predicate.or(hole<Predicate.Predicate<number>>(), hole<Predicate.Predicate<number>>()))\n      .type.toBe<Predicate.Predicate<number>>()\n\n    expect(pipe(Predicate.isString, Predicate.or(Predicate.isNumber)))\n      .type.toBe<Predicate.Refinement<unknown, string | number>>()\n\n    expect(Predicate.or(Predicate.isString, Predicate.isNumber))\n      .type.toBe<Predicate.Refinement<unknown, string | number>>()\n  })\n\n  it(\"tuple\", () => {\n    const isA = hole<Predicate.Refinement<string, \"a\">>()\n    const isTrue = hole<Predicate.Refinement<boolean, true>>()\n    const isOdd = hole<Predicate.Predicate<number>>()\n\n    expect(Predicate.tuple(isTrue, isA))\n      .type.toBe<Predicate.Refinement<readonly [boolean, string], readonly [true, \"a\"]>>()\n\n    expect(Predicate.tuple(isTrue, isOdd))\n      .type.toBe<Predicate.Refinement<readonly [boolean, number], readonly [true, number]>>()\n\n    expect(Predicate.tuple(isOdd, isOdd))\n      .type.toBe<Predicate.Predicate<readonly [number, number]>>()\n\n    expect(Predicate.tuple(...hole<Array<Predicate.Predicate<number>>>()))\n      .type.toBe<Predicate.Predicate<ReadonlyArray<number>>>()\n\n    expect(Predicate.tuple(...hole<Array<Predicate.Predicate<number> | Predicate.Refinement<boolean, true>>>()))\n      .type.toBe<Predicate.Refinement<ReadonlyArray<never>, ReadonlyArray<never>>>()\n\n    expect(Predicate.tuple(...hole<Array<Predicate.Refinement<boolean, true>>>()))\n      .type.toBe<Predicate.Refinement<ReadonlyArray<boolean>, ReadonlyArray<true>>>()\n  })\n\n  it(\"struct\", () => {\n    expect(\n      Predicate.struct({\n        a: hole<Predicate.Refinement<string, \"a\">>(),\n        true: hole<Predicate.Refinement<boolean, true>>()\n      })\n    ).type.toBe<\n      Predicate.Refinement<\n        { readonly a: string; readonly true: boolean },\n        { readonly a: \"a\"; readonly true: true }\n      >\n    >()\n\n    expect(\n      Predicate.struct({\n        odd: hole<Predicate.Predicate<number>>(),\n        true: hole<Predicate.Refinement<boolean, true>>()\n      })\n    ).type.toBe<\n      Predicate.Refinement<\n        { readonly odd: number; readonly true: boolean },\n        { readonly odd: number; readonly true: true }\n      >\n    >()\n\n    expect(\n      Predicate.struct({\n        odd: hole<Predicate.Predicate<number>>(),\n        odd1: hole<Predicate.Predicate<number>>()\n      })\n    ).type.toBe<Predicate.Predicate<{ readonly odd: number; readonly odd1: number }>>()\n  })\n\n  it(\"isUint8Array\", () => {\n    // @tstyche if { target: \">=5.7\" } -- Before TypeScript 5.7, 'Uint8Array' was not generic\n    expect(unknowns.filter(Predicate.isUint8Array)).type.toBe<Array<Uint8Array<ArrayBufferLike>>>()\n    // @tstyche if { target: \"<5.7\" }\n    expect(unknowns.filter(Predicate.isUint8Array)).type.toBe<Array<Uint8Array>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Random.tst.ts",
    "content": "import type { Array, Cause, Chunk, Effect } from \"effect\"\nimport { Random } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const array: Array<number>\ndeclare const nonEmptyArray: Array.NonEmptyArray<number>\n\ndeclare const readonlyArray: Array<number>\ndeclare const nonEmptyReadonlyArray: Array.NonEmptyArray<number>\n\ndeclare const chunk: Chunk.Chunk<number>\ndeclare const nonEmptyChunk: Chunk.NonEmptyChunk<number>\n\ndescribe(\"Random\", () => {\n  it(\"choice\", () => {\n    expect(Random.choice(array)).type.toBe<Effect.Effect<number, Cause.NoSuchElementException, never>>()\n    expect(Random.choice(nonEmptyArray)).type.toBe<Effect.Effect<number, never, never>>()\n    expect(Random.choice(readonlyArray)).type.toBe<Effect.Effect<number, Cause.NoSuchElementException, never>>()\n    expect(Random.choice(nonEmptyReadonlyArray)).type.toBe<Effect.Effect<number, never, never>>()\n    expect(Random.choice(chunk)).type.toBe<Effect.Effect<number, Cause.NoSuchElementException, never>>()\n    expect(Random.choice(nonEmptyChunk)).type.toBe<Effect.Effect<number, never, never>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Record.tst.ts",
    "content": "import type { Brand } from \"effect\"\nimport { Either, hole, Option, pipe, Predicate, Record } from \"effect\"\nimport { describe, expect, it, when } from \"tstyche\"\n\ndeclare const string$numbers: Record<string, number>\ndeclare const string$numbersOrStrings: Record<string, number | string>\ndeclare const string$structAB: Record<\"a\" | \"b\", number>\ndeclare const string$structCD: Record<\"c\" | \"d\", string>\n\ndeclare const predicateNumbersOrStrings: Predicate.Predicate<number | string>\n\nconst symA = Symbol.for(\"a\")\nconst symB = Symbol.for(\"b\")\n\ndeclare const symbol$numbers: Record<symbol, number>\ndeclare const template$numbers: Record<`a${string}`, number>\n\ndescribe(\"Record\", () => {\n  it(\"NonLiteralKey\", () => {\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<string>>()).type.toBe<string>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<symbol>>()).type.toBe<symbol>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<\"\">>()).type.toBe<string>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<\"a\">>()).type.toBe<string>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<\"a\" | \"b\">>()).type.toBe<string>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<typeof symA>>()).type.toBe<symbol>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<typeof symA | typeof symB>>()).type.toBe<symbol>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<\"a\" | typeof symA>>()).type.toBe<string | symbol>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<`${string}`>>()).type.toBe<string>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<`a${string}`>>()).type.toBe<`a${string}`>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<`${string}a`>>()).type.toBe<`${string}a`>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<`a${string}b${string}`>>()).type.toBe<`a${string}b${string}`>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<`a${number}`>>()).type.toBe<`a${number}`>()\n    expect(hole<Record.ReadonlyRecord.NonLiteralKey<`a${number}b${string}c${number}`>>()).type.toBe<\n      `a${number}b${string}c${number}`\n    >()\n  })\n\n  it(\"empty\", () => {\n    expect(Record.empty<never>()).type.not.toBeAssignableTo<Record<\"a\", number>>()\n\n    const empty1: Record<string, number> = Record.empty()\n    expect(empty1).type.toBe<Record<string, number>>()\n    const empty2: Record<symbol, number> = Record.empty()\n    expect(empty2).type.toBe<Record<symbol, number>>()\n    expect(Record.empty()).type.toBe<Record<never, never>>()\n    expect(Record.empty<\"a\">()).type.toBe<Record<string, never>>()\n    expect(Record.empty<`a${string}bc`>()).type.toBe<Record<`a${string}bc`, never>>()\n    expect(Record.empty<string>()).type.toBe<Record<string, never>>()\n  })\n\n  it(\"fromIterableWith and fromIterableBy\", () => {\n    expect(Record.fromIterableWith([1, 2], (n) => {\n      expect(n).type.toBe<number>()\n      return [String(n), n]\n    })).type.toBe<Record<string, number>>()\n    expect(Record.fromIterableWith([symA, symB], (s) => {\n      expect(s).type.toBe<symbol>()\n      return [String(s), s]\n    })).type.toBe<Record<string, symbol>>()\n    expect(Record.fromIterableWith([1, symA], (ns) => {\n      expect(ns).type.toBe<number | symbol>()\n      return [Predicate.isNumber(ns) ? String(ns) : ns, ns]\n    })).type.toBe<Record<string | symbol, number | symbol>>()\n  })\n\n  it(\"fromIterableBy\", () => {\n    expect(Record.fromIterableBy([1, 2], (n) => {\n      expect(n).type.toBe<number>()\n      return String(n)\n    })).type.toBe<Record<string, number>>()\n    expect(Record.fromIterableBy([symA, symB], (s) => {\n      expect(s).type.toBe<symbol>()\n      return String(s)\n    })).type.toBe<Record<string, symbol>>()\n    expect(Record.fromIterableBy([1, symA], (ns) => {\n      expect(ns).type.toBe<number | symbol>()\n      return Predicate.isNumber(ns) ? String(ns) : ns\n    })).type.toBe<Record<string | symbol, number | symbol>>()\n  })\n\n  it(\"fromEntries\", () => {\n    expect(Record.fromEntries([[\"a\", 1], [\"b\", 2]])).type.toBe<Record<string, number>>()\n    expect(Record.fromEntries([[symA, 1], [symB, 2]])).type.toBe<Record<symbol, number>>()\n    expect(Record.fromEntries([[\"a\", 1], [symB, 2]])).type.toBe<Record<string | symbol, number>>()\n  })\n\n  it(\"collect\", () => {\n    expect(Record.collect(string$numbers, (k, a) => {\n      expect(k).type.toBe<string>()\n      expect(a).type.toBe<number>()\n      return a\n    })).type.toBe<Array<number>>()\n    expect(pipe(\n      string$numbers,\n      Record.collect((k, a) => {\n        expect(k).type.toBe<string>()\n        expect(a).type.toBe<number>()\n        return a\n      })\n    )).type.toBe<Array<number>>()\n\n    expect(Record.collect(template$numbers, (k, a) => {\n      expect(k).type.toBe<`a${string}`>()\n      expect(a).type.toBe<number>()\n      return a\n    })).type.toBe<Array<number>>()\n    expect(pipe(\n      template$numbers,\n      Record.collect((k, a) => {\n        expect(k).type.toBe<`a${string}`>()\n        expect(a).type.toBe<number>()\n        return a\n      })\n    )).type.toBe<Array<number>>()\n\n    expect(Record.collect(string$structAB, (k, a) => {\n      expect(k).type.toBe<\"a\" | \"b\">()\n      expect(a).type.toBe<number>()\n      return a\n    })).type.toBe<Array<number>>()\n    expect(pipe(\n      string$structAB,\n      Record.collect((k, a) => {\n        expect(k).type.toBe<\"a\" | \"b\">()\n        expect(a).type.toBe<number>()\n        return a\n      })\n    )).type.toBe<Array<number>>()\n  })\n\n  it(\"toEntries\", () => {\n    expect(Record.toEntries(string$numbers)).type.toBe<Array<[string, number]>>()\n    expect(Record.toEntries(template$numbers)).type.toBe<Array<[`a${string}`, number]>>()\n    expect(Record.toEntries(symbol$numbers)).type.toBe<Array<[string, number]>>()\n    // Testing with branded records\n    const brandedRecord = hole<Record<string & Brand.Brand<\"brandedString\">, number>>()\n    expect(Record.toEntries(brandedRecord)).type.toBe<Array<[string & Brand.Brand<\"brandedString\">, number]>>()\n    expect(Record.toEntries(string$structAB)).type.toBe<Array<[\"a\" | \"b\", number]>>()\n  })\n\n  it(\"has\", () => {\n    expect(Record.has(string$numbers, \"a\")).type.toBe<boolean>()\n    expect(pipe(string$numbers, Record.has(\"a\"))).type.toBe<boolean>()\n    expect(Record.has).type.not.toBeCallableWith(string$numbers, symA)\n    expect(Record.has(template$numbers, \"a\")).type.toBe<boolean>()\n    expect(Record.has).type.not.toBeCallableWith(template$numbers, \"b\")\n    expect(Record.has(symbol$numbers, symA)).type.toBe<boolean>()\n    expect(Record.has).type.not.toBeCallableWith(symbol$numbers, \"a\")\n    expect(Record.has).type.not.toBeCallableWith(string$structAB, \"c\")\n    expect(Record.has).type.not.toBeCallableWith(string$structAB, symA)\n  })\n\n  it(\"get\", () => {\n    expect(Record.get(string$numbers, \"a\")).type.toBe<Option.Option<number>>()\n    expect(pipe(string$numbers, Record.get(\"a\"))).type.toBe<Option.Option<number>>()\n    when(pipe).isCalledWith(string$numbers, expect(Record.get).type.not.toBeCallableWith(symA))\n    expect(pipe(template$numbers, Record.get(\"a\"))).type.toBe<Option.Option<number>>()\n    when(pipe).isCalledWith(template$numbers, expect(Record.get).type.not.toBeCallableWith(\"b\"))\n    expect(pipe(symbol$numbers, Record.get(symA))).type.toBe<Option.Option<number>>()\n    when(pipe).isCalledWith(symbol$numbers, expect(Record.get).type.not.toBeCallableWith(\"a\"))\n    expect(pipe(string$structAB, Record.get(\"a\"))).type.toBe<Option.Option<number>>()\n    when(pipe).isCalledWith(string$structAB, expect(Record.get).type.not.toBeCallableWith(\"c\"))\n  })\n\n  it(\"modify, modifyOption, and replaceOption\", () => {\n    expect(pipe(string$numbers, Record.modify(\"a\", () => 2))).type.toBe<Record<string, number>>()\n    expect(pipe(string$numbers, Record.modify(\"a\", () => true))).type.toBe<Record<string, number | boolean>>()\n    expect(pipe(template$numbers, Record.modify(\"a\", () => 2))).type.toBe<Record<`a${string}`, number>>()\n    expect(pipe(template$numbers, Record.modify(\"a\", () => true))).type.toBe<\n      Record<`a${string}`, number | boolean>\n    >()\n    when(pipe).isCalledWith(template$numbers, expect(Record.modify).type.not.toBeCallableWith(\"b\", () => true))\n    expect(pipe(symbol$numbers, Record.modify(symA, () => 2))).type.toBe<Record<symbol, number>>()\n    expect(pipe(symbol$numbers, Record.modify(symA, () => true))).type.toBe<Record<symbol, number | boolean>>()\n    expect(pipe(string$structAB, Record.modify(\"a\", () => 2))).type.toBe<Record<\"a\" | \"b\", number>>()\n    expect(pipe(string$structAB, Record.modify(\"a\", () => true))).type.toBe<\n      Record<\"a\" | \"b\", number | boolean>\n    >()\n  })\n\n  it(\"modifyOption\", () => {\n    expect(pipe(string$numbers, Record.modifyOption(\"a\", () => 2)))\n      .type.toBe<Option.Option<Record<string, number>>>()\n    expect(pipe(string$numbers, Record.modifyOption(\"a\", () => true)))\n      .type.toBe<Option.Option<Record<string, number | boolean>>>()\n    expect(pipe(template$numbers, Record.modifyOption(\"a\", () => 2)))\n      .type.toBe<Option.Option<Record<`a${string}`, number>>>()\n    expect(pipe(template$numbers, Record.modifyOption(\"a\", () => true)))\n      .type.toBe<Option.Option<Record<`a${string}`, number | boolean>>>()\n    when(pipe).isCalledWith(\n      template$numbers,\n      expect(Record.modifyOption).type.not.toBeCallableWith(\"b\", () => true)\n    )\n    expect(pipe(symbol$numbers, Record.modifyOption(symA, () => 2)))\n      .type.toBe<Option.Option<Record<symbol, number>>>()\n    expect(pipe(symbol$numbers, Record.modifyOption(symA, () => true)))\n      .type.toBe<Option.Option<Record<symbol, number | boolean>>>()\n    expect(pipe(string$structAB, Record.modifyOption(\"a\", () => 2)))\n      .type.toBe<Option.Option<Record<\"a\" | \"b\", number>>>()\n    expect(pipe(string$structAB, Record.modifyOption(\"a\", () => true)))\n      .type.toBe<Option.Option<Record<\"a\" | \"b\", number | boolean>>>()\n  })\n\n  it(\"replaceOption\", () => {\n    expect(pipe(string$numbers, Record.replaceOption(\"a\", 2)))\n      .type.toBe<Option.Option<Record<string, number>>>()\n    expect(pipe(string$numbers, Record.replaceOption(\"a\", true)))\n      .type.toBe<Option.Option<Record<string, number | boolean>>>()\n    expect(pipe(template$numbers, Record.replaceOption(\"a\", 2)))\n      .type.toBe<Option.Option<Record<`a${string}`, number>>>()\n    expect(pipe(template$numbers, Record.replaceOption(\"a\", true)))\n      .type.toBe<Option.Option<Record<`a${string}`, number | boolean>>>()\n    when(pipe).isCalledWith(template$numbers, expect(Record.replaceOption).type.not.toBeCallableWith(\"b\", true))\n    expect(pipe(symbol$numbers, Record.replaceOption(symA, 2)))\n      .type.toBe<Option.Option<Record<symbol, number>>>()\n    expect(pipe(symbol$numbers, Record.replaceOption(symA, true)))\n      .type.toBe<Option.Option<Record<symbol, number | boolean>>>()\n    expect(pipe(string$structAB, Record.replaceOption(\"a\", 2)))\n      .type.toBe<Option.Option<Record<\"a\" | \"b\", number>>>()\n    expect(pipe(string$structAB, Record.replaceOption(\"a\", true)))\n      .type.toBe<Option.Option<Record<\"a\" | \"b\", number | boolean>>>()\n  })\n\n  it(\"remove\", () => {\n    expect(pipe(string$numbers, Record.remove(\"a\"))).type.toBe<Record<string, number>>()\n    expect(pipe(template$numbers, Record.remove(\"a\"))).type.toBe<Record<`a${string}`, number>>()\n    when(pipe).isCalledWith(template$numbers, expect(Record.remove).type.not.toBeCallableWith(\"b\"))\n    expect(pipe(symbol$numbers, Record.remove(symA))).type.toBe<Record<symbol, number>>()\n    expect(pipe(string$structAB, Record.remove(\"a\"))).type.toBe<Record<\"b\", number>>()\n  })\n\n  it(\"pop\", () => {\n    expect(pipe(string$numbers, Record.pop(\"a\"))).type.toBe<Option.Option<[number, Record<string, number>]>>()\n    expect(pipe(template$numbers, Record.pop(\"a\"))).type.toBe<\n      Option.Option<[number, Record<`a${string}`, number>]>\n    >()\n    when(pipe).isCalledWith(template$numbers, expect(Record.pop).type.not.toBeCallableWith(\"b\"))\n    expect(pipe(symbol$numbers, Record.pop(symA))).type.toBe<Option.Option<[number, Record<symbol, number>]>>()\n    expect(pipe(string$structAB, Record.pop(\"a\"))).type.toBe<Option.Option<[number, Record<\"b\", number>]>>()\n  })\n\n  it(\"map\", () => {\n    expect(Record.map(string$numbers, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<string>()\n      return v > 0\n    })).type.toBe<Record<string, boolean>>()\n    expect(pipe(\n      string$numbers,\n      Record.map((v, k) => {\n        expect(v).type.toBe<number>()\n        expect(k).type.toBe<string>()\n        return v > 0\n      })\n    )).type.toBe<Record<string, boolean>>()\n    expect(Record.map(template$numbers, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<`a${string}`>()\n      return v > 0\n    })).type.toBe<Record<`a${string}`, boolean>>()\n    expect(Record.map(symbol$numbers, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<string>()\n      return v + 1\n    })).type.toBe<Record<string, number>>()\n    expect(Record.map(string$structAB, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<\"a\" | \"b\">()\n      return v > 0\n    })).type.toBe<Record<\"a\" | \"b\", boolean>>()\n    expect(pipe(\n      string$structAB,\n      Record.map((v, k) => {\n        expect(v).type.toBe<number>()\n        expect(k).type.toBe<\"a\" | \"b\">()\n        return v > 0\n      })\n    )).type.toBe<Record<\"a\" | \"b\", boolean>>()\n  })\n\n  it(\"filterMap\", () => {\n    expect(Record.filterMap(string$numbers, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<string>()\n      return v > 0 ? Option.some(\"positive\") : Option.none()\n    }))\n      .type.toBe<Record<string, string>>()\n    expect(Record.filterMap(template$numbers, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<`a${string}`>()\n      return v > 0 ? Option.some(\"positive\") : Option.none()\n    }))\n      .type.toBe<Record<`a${string}`, string>>()\n    expect(Record.filterMap(symbol$numbers, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<string>()\n      return v > 0 ? Option.some(\"positive\") : Option.none()\n    }))\n      .type.toBe<Record<string, string>>()\n    expect(pipe(\n      string$structAB,\n      Record.filterMap((v, k) => {\n        expect(v).type.toBe<number>()\n        expect(k).type.toBe<\"a\" | \"b\">()\n        return k === \"a\" ? Option.some(v) : Option.none()\n      })\n    ))\n      .type.toBe<Record<string, number>>()\n    expect(Record.filterMap(string$structAB, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<\"a\" | \"b\">()\n      return k === \"a\" ? Option.some(v) : Option.none()\n    }))\n      .type.toBe<Record<string, number>>()\n  })\n\n  it(\"filter\", () => {\n    expect(Record.filter(string$numbers, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<string>()\n      return v > 0\n    })).type.toBe<Record<string, number>>()\n    expect(Record.filter(template$numbers, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<`a${string}`>()\n      return v > 0\n    })).type.toBe<Record<`a${string}`, number>>()\n    expect(pipe(\n      string$structAB,\n      Record.filter((v, k) => {\n        expect(v).type.toBe<number>()\n        expect(k).type.toBe<\"a\" | \"b\">()\n        return k === \"a\"\n      })\n    ))\n      .type.toBe<Record<string, number>>()\n    expect(Record.filter(string$structAB, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<\"a\" | \"b\">()\n      return k === \"a\"\n    }))\n      .type.toBe<Record<string, number>>()\n    expect(Record.filter(string$numbersOrStrings, predicateNumbersOrStrings))\n      .type.toBe<Record<string, string | number>>()\n    expect(Record.filter(string$numbers, predicateNumbersOrStrings))\n      .type.toBe<Record<string, number>>()\n    expect(pipe(string$numbersOrStrings, Record.filter(predicateNumbersOrStrings)))\n      .type.toBe<Record<string, string | number>>()\n    expect(pipe(string$numbers, Record.filter(predicateNumbersOrStrings)))\n      .type.toBe<Record<string, number>>()\n    expect(Record.filter(string$numbersOrStrings, Predicate.isNumber))\n      .type.toBe<Record<string, number>>()\n    expect(pipe(string$numbersOrStrings, Record.filter(Predicate.isNumber)))\n      .type.toBe<Record<string, number>>()\n  })\n\n  it(\"partitionMap\", () => {\n    expect(\n      Record.partitionMap(string$numbers, (v, k) => {\n        expect(v).type.toBe<number>()\n        expect(k).type.toBe<string>()\n        return v > 0 ? Either.right(\"positive\") : Either.left(false)\n      })\n    ).type.toBe<[left: Record<string, boolean>, right: Record<string, string>]>()\n    expect(\n      pipe(\n        string$structAB,\n        Record.partitionMap((v, k) => {\n          expect(v).type.toBe<number>()\n          expect(k).type.toBe<\"a\" | \"b\">()\n          return k === \"a\" ? Either.right(\"positive\") : Either.left(false)\n        })\n      )\n    ).type.toBe<[left: Record<string, boolean>, right: Record<string, string>]>()\n    expect(\n      Record.partitionMap(string$structAB, (v, k) => {\n        expect(v).type.toBe<number>()\n        expect(k).type.toBe<\"a\" | \"b\">()\n        return k === \"a\" ? Either.right(\"positive\") : Either.left(false)\n      })\n    ).type.toBe<[left: Record<string, boolean>, right: Record<string, string>]>()\n  })\n\n  it(\"partition\", () => {\n    expect(Record.partition(string$numbers, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<string>()\n      return v > 0\n    }))\n      .type.toBe<[excluded: Record<string, number>, satisfying: Record<string, number>]>()\n    expect(pipe(\n      string$structAB,\n      Record.partition((v, k) => {\n        expect(v).type.toBe<number>()\n        expect(k).type.toBe<\"a\" | \"b\">()\n        return k === \"a\"\n      })\n    ))\n      .type.toBe<[excluded: Record<string, number>, satisfying: Record<string, number>]>()\n    expect(Record.partition(string$structAB, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<\"a\" | \"b\">()\n      return k === \"a\"\n    }))\n      .type.toBe<[excluded: Record<string, number>, satisfying: Record<string, number>]>()\n    expect(Record.partition(string$numbersOrStrings, predicateNumbersOrStrings))\n      .type.toBe<\n      [excluded: Record<string, string | number>, satisfying: Record<string, string | number>]\n    >()\n    expect(pipe(string$numbersOrStrings, Record.partition(predicateNumbersOrStrings)))\n      .type.toBe<\n      [excluded: Record<string, string | number>, satisfying: Record<string, string | number>]\n    >()\n    expect(Record.partition(string$numbersOrStrings, Predicate.isNumber))\n      .type.toBe<[excluded: Record<string, string>, satisfying: Record<string, number>]>()\n    expect(pipe(string$numbersOrStrings, Record.partition(Predicate.isNumber)))\n      .type.toBe<[excluded: Record<string, string>, satisfying: Record<string, number>]>()\n  })\n\n  it(\"keys\", () => {\n    expect(Record.keys(string$structAB)).type.toBe<Array<\"a\" | \"b\">>()\n  })\n\n  it(\"values\", () => {\n    expect(Record.values(string$structAB)).type.toBe<Array<number>>()\n  })\n\n  it(\"set\", () => {\n    expect(Record.set(string$numbers, \"a\", 2)).type.toBe<Record<string, number>>()\n    expect(Record.set(string$numbers, \"a\", true)).type.toBe<Record<string, number | boolean>>()\n    expect(Record.set(template$numbers, \"a\", 2)).type.toBe<Record<`a${string}`, number>>()\n    expect(Record.set(template$numbers, \"a\", true)).type.toBe<Record<`a${string}`, number | boolean>>()\n    expect(Record.set(template$numbers, \"b\", true)).type.toBe<Record<\"b\" | `a${string}`, number | boolean>>()\n    expect(Record.set(string$structAB, \"a\", 2)).type.toBe<Record<\"a\" | \"b\", number>>()\n    expect(Record.set(string$structAB, \"a\", true)).type.toBe<Record<\"a\" | \"b\", number | boolean>>()\n    expect(Record.set(string$structAB, \"c\", true)).type.toBe<Record<\"a\" | \"b\" | \"c\", number | boolean>>()\n  })\n\n  it(\"reduce\", () => {\n    const result = Record.reduce(string$structAB, \"\", (acc, v, k) => {\n      expect(acc).type.toBe<string>()\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<\"a\" | \"b\">()\n      return typeof k === \"string\" ? k : acc\n    })\n    expect(result).type.toBe<string>()\n  })\n\n  it(\"some\", () => {\n    expect(Record.some(string$structAB, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<\"a\" | \"b\">()\n      return false\n    })).type.toBe<boolean>()\n    pipe(\n      string$numbersOrStrings,\n      Record.some((v, k) => {\n        expect(v).type.toBe<string | number>()\n        expect(k).type.toBe<string>()\n        return true\n      })\n    )\n  })\n\n  it(\"union\", () => {\n    expect(Record.union(string$numbers, string$numbers, (_, b) => b))\n      .type.toBe<Record<string, number>>()\n    expect(Record.union(string$numbers, string$numbersOrStrings, (_, b) => b))\n      .type.toBe<Record<string, string | number>>()\n    expect(Record.union(string$structAB, string$structCD, (_, b) => b))\n      .type.toBe<Record<\"a\" | \"b\" | \"c\" | \"d\", string | number>>()\n  })\n\n  it(\"singleton\", () => {\n    expect(Record.singleton(\"a\", 1)).type.toBe<Record<\"a\", number>>()\n  })\n\n  it(\"every\", () => {\n    pipe(\n      string$numbersOrStrings,\n      Record.every((v, k) => {\n        expect(v).type.toBe<string | number>()\n        expect(k).type.toBe<string>()\n        return true\n      })\n    )\n    Record.every(string$structAB, (v, k) => {\n      expect(v).type.toBe<number>()\n      expect(k).type.toBe<\"a\" | \"b\">()\n      return false\n    })\n    if (Record.every(string$numbersOrStrings, Predicate.isString)) {\n      expect(string$numbersOrStrings).type.toBe<Record.ReadonlyRecord<string, string>>()\n    }\n    if (Record.every(string$numbersOrStrings, Predicate.isString)) {\n      expect(string$numbersOrStrings).type.toBe<Record.ReadonlyRecord<string, string>>()\n    }\n  })\n\n  it(\"intersection\", () => {\n    expect(Record.intersection(string$numbers, string$numbers, (a, _) => a))\n      .type.toBe<Record<string, number>>()\n    expect(Record.intersection(string$numbers, string$numbersOrStrings, (_, b) => b))\n      .type.toBe<Record<string, string | number>>()\n    expect(Record.intersection(string$structAB, string$structCD, (_, b) => b))\n      .type.toBe<Record<never, string>>()\n    expect(Record.intersection(string$structAB, string$structCD, (a, _) => a))\n      .type.toBe<Record<never, number>>()\n    expect(Record.intersection(string$numbers, string$numbers, (a, _) => a))\n      .type.toBe<Record<string, number>>()\n    expect(Record.intersection(string$numbers, string$structCD, (a, _) => a))\n      .type.toBe<Record<string, number>>()\n    expect(Record.intersection(string$structAB, { c: 2 }, (a, _) => a))\n      .type.toBe<Record<never, number>>()\n    expect(Record.intersection(string$structAB, { b: 2 }, (a, _) => a))\n      .type.toBe<Record<\"b\", number>>()\n  })\n\n  it(\"findFirst\", () => {\n    expect(Record.findFirst(string$numbersOrStrings, (a, _) => predicateNumbersOrStrings(a)))\n      .type.toBe<Option.Option<[string, string | number]>>()\n    expect(pipe(string$numbersOrStrings, Record.findFirst((a, _) => predicateNumbersOrStrings(a))))\n      .type.toBe<Option.Option<[string, string | number]>>()\n    expect(Record.findFirst(string$numbersOrStrings, Predicate.isString))\n      .type.toBe<Option.Option<[string, string]>>()\n    expect(pipe(string$numbersOrStrings, Record.findFirst(Predicate.isString)))\n      .type.toBe<Option.Option<[string, string]>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/RedBlackTree.tst.ts",
    "content": "import type { Order } from \"effect\"\nimport { pipe, RedBlackTree } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const stringAndNumberIterable: Iterable<[string, number]>\ndeclare const stringOrUndefinedOrder: Order.Order<string | undefined>\n\ndescribe(\"RedBlackTree\", () => {\n  it(\"fromIterable\", () => {\n    expect(RedBlackTree.fromIterable(stringAndNumberIterable, stringOrUndefinedOrder)).type.toBe<\n      RedBlackTree.RedBlackTree<string, number>\n    >()\n    expect(pipe(stringAndNumberIterable, RedBlackTree.fromIterable(stringOrUndefinedOrder))).type.toBe<\n      RedBlackTree.RedBlackTree<string, number>\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Runtime.tst.ts",
    "content": "import type { Runtime } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Runtime\", () => {\n  it(\"Runtime.Context type helper\", () => {\n    type ContextOfRuntime = Runtime.Runtime.Context<Runtime.Runtime<{ foo: string }>>\n    expect<ContextOfRuntime>().type.toBe<{ foo: string }>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schedule.tst.ts",
    "content": "import { Console, Schedule } from \"effect\"\nimport { describe, expect, it, when } from \"tstyche\"\n\ndescribe(\"Schedule\", () => {\n  it(\"tapOutput\", () => {\n    expect(Schedule.once.pipe(\n      Schedule.as<number | string>(1),\n      Schedule.tapOutput((x) => {\n        expect(x).type.toBe<string | number>()\n        return Console.log(x)\n      })\n    )).type.toBe<Schedule.Schedule<string | number, unknown, never>>()\n\n    // The callback should not affect the type of the output (`number`)\n    expect(Schedule.once.pipe(\n      Schedule.as(1),\n      Schedule.tapOutput((x: string | number) => Console.log(x))\n    )).type.toBe<Schedule.Schedule<number, unknown, never>>()\n\n    expect(Schedule.tapOutput(\n      Schedule.once.pipe(\n        Schedule.as(1)\n      ),\n      (x: string | number) => Console.log(x)\n    )).type.toBe<Schedule.Schedule<number, unknown, never>>()\n\n    when(Schedule.once.pipe).isCalledWith(\n      Schedule.as<number | string>(1),\n      expect(Schedule.tapOutput).type.not.toBeCallableWith(\n        (s: string) => Console.log(s.trim())\n      )\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/Brand.tst.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { pipe, Schema } from \"effect\"\nimport { describe, expect, it, when } from \"tstyche\"\n\nconst Int1 = Symbol.for(\"Int\")\nconst Int2 = Symbol.for(\"Int\")\n\nconst schema1 = pipe(Schema.Number, Schema.int(), Schema.brand(Int1))\nconst schema2 = pipe(Schema.Number, Schema.int(), Schema.brand(Int2))\n\ntype A1 = Schema.Schema.Type<typeof schema1>\ntype A2 = Schema.Schema.Type<typeof schema2>\n\ndescribe(\"SchemaBrand\", () => {\n  it(\"should differentiate between branded schema types\", () => {\n    expect<A1>().type.not.toBeAssignableTo<A2>()\n    expect<A2>().type.not.toBeAssignableTo<A1>()\n  })\n\n  it(\"should raise an error when the brand is not assignable to the schema\", () => {\n    when(pipe).isCalledWith(\n      Schema.Number,\n      expect(Schema.brand).type.not.toBeCallableWith(\"UserId\", {\n        examples: [\"a\"]\n      })\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/Context.tst.ts",
    "content": "import type { Exit } from \"effect\"\nimport { Context, Effect, Option } from \"effect\"\nimport { hole } from \"effect/Function\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport { describe, expect, it } from \"tstyche\"\n\ninterface aContext extends S.Schema<string, string, \"aContext\"> {}\ninterface bContext extends S.Schema<number, number, \"bContext\"> {}\ninterface cContext extends S.Schema<boolean, boolean, \"cContext\"> {}\n\ndeclare const aContext: aContext\ndeclare const bContext: bContext\ndeclare const cContext: cContext\n\nconst Taga = Context.GenericTag<\"Taga\", string>(\"Taga\")\nconst Tagb = Context.GenericTag<\"Tagb\", number>(\"Tagb\")\nconst Tag1 = Context.GenericTag<\"Tag1\", string>(\"Tag1\")\nconst Tag2 = Context.GenericTag<\"Tag2\", number>(\"Tag2\")\n\ndeclare const myRequest: MyRequest\n\ndescribe(\"Schema Context\", () => {\n  it(\"declare: simple predicate\", () => {\n    const schema = S.declare((u): u is string => typeof u === \"string\")\n    expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n    expect(schema).type.toBe<S.declare<string>>()\n  })\n\n  it(\"declare: with contexts and options\", () => {\n    const schema = S.declare(\n      [aContext, bContext],\n      {\n        decode: (_a, _b) => () => ParseResult.succeed(\"a\"),\n        encode: (_a, _b) => () => ParseResult.succeed(1)\n      },\n      {\n        arbitrary: (_a, _b) => (fc) => fc.string(),\n        pretty: (_a, _b) => (s) => s,\n        equivalence: () => (_a, _b) => true\n      }\n    )\n    expect(S.asSchema(schema)).type.toBe<S.Schema<string, number, \"aContext\" | \"bContext\">>()\n    expect(schema).type.toBe<S.declare<string, number, readonly [aContext, bContext]>>()\n  })\n\n  it(\"declare errors\", () => {\n    expect(S.declare).type.not.toBeCallableWith(\n      [aContext, bContext],\n      {\n        decode: (_a: S.Schema<string, string>, _b: S.Schema<number, number>) => () =>\n          Taga.pipe(Effect.flatMap(ParseResult.succeed)),\n        encode: (_a: S.Schema<string, string>, _b: S.Schema<number, number>) => () => ParseResult.succeed(1)\n      }\n    )\n\n    expect(S.declare).type.not.toBeCallableWith(\n      [aContext, bContext],\n      {\n        decode: (_a: S.Schema<string, string>, _b: S.Schema<number, number>) => () => ParseResult.succeed(\"a\"),\n        encode: (_a: S.Schema<string, string>, _b: S.Schema<number, number>) => () =>\n          Tagb.pipe(Effect.flatMap(ParseResult.succeed))\n      }\n    )\n\n    expect(S.declare).type.not.toBeCallableWith(\n      [aContext, bContext],\n      {\n        decode: (_a: S.Schema<string, string>, _b: S.Schema<number, number>) => () =>\n          Taga.pipe(Effect.flatMap(ParseResult.succeed)),\n        encode: (_a: S.Schema<string, string>, _b: S.Schema<number, number>) => () =>\n          Tagb.pipe(Effect.flatMap(ParseResult.succeed))\n      }\n    )\n\n    expect(S.declare).type.not.toBeCallableWith(\n      [],\n      {\n        decode: () => () => Tag1.pipe(Effect.flatMap(ParseResult.succeed)),\n        encode: () => () => ParseResult.succeed(1)\n      }\n    )\n\n    expect(S.declare).type.not.toBeCallableWith(\n      [aContext, bContext],\n      {\n        decode: (_a: S.Schema<string, string>, _b: S.Schema<number, number>) => () =>\n          Tag1.pipe(Effect.flatMap(ParseResult.succeed)),\n        encode: (_a: S.Schema<string, string>, _b: S.Schema<number, number>) => () => ParseResult.succeed(1)\n      }\n    )\n\n    expect(S.declare).type.not.toBeCallableWith(\n      [aContext, bContext],\n      {\n        decode: (_a: S.Schema<string, string>, _b: S.Schema<number, number>) => () => ParseResult.succeed(\"a\"),\n        encode: (_a: S.Schema<string, string>, _b: S.Schema<number, number>) => () =>\n          Tag2.pipe(Effect.flatMap(ParseResult.succeed))\n      }\n    )\n  })\n\n  it(\"Union\", () => {\n    expect(S.asSchema(S.Union(aContext, bContext)))\n      .type.toBe<S.Schema<string | number, string | number, \"aContext\" | \"bContext\">>()\n    expect(S.Union(aContext, bContext))\n      .type.toBe<S.Union<[aContext, bContext]>>()\n  })\n\n  it(\"Tuple2\", () => {\n    const schema = S.Tuple(aContext, bContext)\n    expect(S.asSchema(schema))\n      .type.toBe<S.Schema<readonly [string, number], readonly [string, number], \"aContext\" | \"bContext\">>()\n    expect(schema).type.toBe<S.Tuple2<aContext, bContext>>()\n  })\n\n  it(\"TupleType\", () => {\n    expect(S.asSchema(S.Tuple([aContext], bContext)))\n      .type.toBe<\n      S.Schema<readonly [string, ...Array<number>], readonly [string, ...Array<number>], \"aContext\" | \"bContext\">\n    >()\n    expect(S.Tuple([aContext], bContext))\n      .type.toBe<S.TupleType<readonly [aContext], [bContext]>>()\n  })\n\n  it(\"OptionalElement\", () => {\n    expect(S.asSchema(S.Tuple(aContext, S.optionalElement(bContext))))\n      .type.toBe<S.Schema<readonly [string, number?], readonly [string, number?], \"aContext\" | \"bContext\">>()\n    expect(S.Tuple(aContext, S.optionalElement(bContext)))\n      .type.toBe<S.Tuple<[aContext, S.Element<bContext, \"?\">]>>()\n  })\n\n  it(\"Array\", () => {\n    expect(S.asSchema(S.Array(aContext)))\n      .type.toBe<S.Schema<ReadonlyArray<string>, ReadonlyArray<string>, \"aContext\">>()\n    expect(S.Array(aContext))\n      .type.toBe<S.Array$<aContext>>()\n  })\n\n  it(\"NonEmptyArray\", () => {\n    expect(S.asSchema(S.NonEmptyArray(aContext)))\n      .type.toBe<S.Schema<readonly [string, ...Array<string>], readonly [string, ...Array<string>], \"aContext\">>()\n    expect(S.NonEmptyArray(aContext))\n      .type.toBe<S.NonEmptyArray<aContext>>()\n  })\n\n  it(\"propertySignatureDeclaration\", () => {\n    expect(S.propertySignature(aContext))\n      .type.toBe<S.propertySignature<aContext>>()\n    expect(S.propertySignature(aContext).annotations({}))\n      .type.toBe<S.propertySignature<aContext>>()\n  })\n\n  it(\"optionalToOptional\", () => {\n    expect(S.optionalToOptional(aContext, S.String, { decode: (o) => o, encode: (o) => o }))\n      .type.toBe<S.PropertySignature<\"?:\", string, never, \"?:\", string, false, \"aContext\">>()\n  })\n\n  it(\"optionalToRequired\", () => {\n    expect(\n      S.optionalToRequired(aContext, S.String, { decode: Option.getOrElse(() => \"\"), encode: Option.some })\n    ).type.toBe<S.PropertySignature<\":\", string, never, \"?:\", string, false, \"aContext\">>()\n  })\n\n  it(\"requiredToOptional\", () => {\n    expect(\n      S.requiredToOptional(aContext, S.String, { decode: Option.some, encode: Option.getOrElse(() => \"\") })\n    ).type.toBe<S.PropertySignature<\"?:\", string, never, \":\", string, false, \"aContext\">>()\n  })\n\n  it(\"optional\", () => {\n    expect(S.optional(aContext))\n      .type.toBe<S.optional<aContext>>()\n  })\n\n  it(\"Struct\", () => {\n    expect(S.asSchema(S.Struct({ a: aContext, b: bContext })))\n      .type.toBe<\n      S.Schema<\n        { readonly a: string; readonly b: number },\n        { readonly a: string; readonly b: number },\n        \"aContext\" | \"bContext\"\n      >\n    >()\n    expect(S.Struct({ a: aContext, b: bContext }))\n      .type.toBe<S.Struct<{ a: aContext; b: bContext }>>()\n  })\n\n  it(\"pick\", () => {\n    expect(S.Struct({ a: aContext, b: bContext }).pipe(S.pick(\"a\")))\n      .type.toBe<S.SchemaClass<{ readonly a: string }, { readonly a: string }, \"aContext\" | \"bContext\">>()\n  })\n\n  it(\"omit\", () => {\n    expect(S.Struct({ a: aContext, b: bContext }).pipe(S.omit(\"b\")))\n      .type.toBe<S.SchemaClass<{ readonly a: string }, { readonly a: string }, \"aContext\" | \"bContext\">>()\n  })\n\n  it(\"partialWith\", () => {\n    expect(S.partialWith(S.Struct({ a: aContext, b: bContext }), { exact: true }))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a?: string; readonly b?: number },\n        { readonly a?: string; readonly b?: number },\n        \"aContext\" | \"bContext\"\n      >\n    >()\n  })\n\n  it(\"required\", () => {\n    expect(S.required(S.partialWith(S.Struct({ a: aContext, b: bContext }), { exact: true })))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a: string; readonly b: number },\n        { readonly a: string; readonly b: number },\n        \"aContext\" | \"bContext\"\n      >\n    >()\n  })\n\n  it(\"mutable\", () => {\n    expect(S.asSchema(S.mutable(S.Struct({ a: aContext, b: bContext }))))\n      .type.toBe<S.Schema<{ a: string; b: number }, { a: string; b: number }, \"aContext\" | \"bContext\">>()\n    expect(S.mutable(S.Struct({ a: aContext, b: bContext })))\n      .type.toBe<S.mutable<S.Struct<{ a: aContext; b: bContext }>>>()\n  })\n\n  it(\"Record\", () => {\n    expect(S.asSchema(S.Record({ key: aContext, value: bContext })))\n      .type.toBe<\n      S.Schema<{ readonly [x: string]: number }, { readonly [x: string]: number }, \"aContext\" | \"bContext\">\n    >()\n    expect(S.Record({ key: aContext, value: bContext }))\n      .type.toBe<S.Record$<aContext, bContext>>()\n  })\n\n  it(\"extend\", () => {\n    expect(\n      S.asSchema(S.Struct({ a: aContext, b: bContext }).pipe(S.extend(S.Struct({ c: cContext }))))\n    )\n      .type.toBe<\n      S.Schema<\n        { readonly a: string; readonly b: number } & { readonly c: boolean },\n        { readonly a: string; readonly b: number } & { readonly c: boolean },\n        \"aContext\" | \"bContext\" | \"cContext\"\n      >\n    >()\n    expect(S.Struct({ a: aContext, b: bContext }).pipe(S.extend(S.Struct({ c: cContext }))))\n      .type.toBe<S.extend<S.Struct<{ a: aContext; b: bContext }>, S.Struct<{ c: cContext }>>>()\n  })\n\n  it(\"compose\", () => {\n    expect(S.asSchema(aContext.pipe(S.compose(bContext, { strict: false }))))\n      .type.toBe<S.Schema<number, string, \"aContext\" | \"bContext\">>()\n  })\n\n  it(\"suspend\", () => {\n    expect(S.suspend(() => aContext))\n      .type.toBe<S.suspend<string, string, \"aContext\">>()\n  })\n\n  it(\"filter\", () => {\n    expect(aContext.pipe(S.filter(() => false)))\n      .type.toBe<S.filter<aContext>>()\n  })\n\n  it(\"transformOrFail\", () => {\n    expect(\n      S.asSchema(\n        S.transformOrFail(aContext, bContext, {\n          decode: () => ParseResult.succeed(1),\n          encode: () => ParseResult.succeed(\"\")\n        })\n      )\n    )\n      .type.toBe<S.Schema<number, string, \"aContext\" | \"bContext\">>()\n    expect(\n      S.transformOrFail(aContext, bContext, {\n        decode: () => ParseResult.succeed(1),\n        encode: () => ParseResult.succeed(\"\")\n      })\n    )\n      .type.toBe<S.transformOrFail<aContext, bContext, never>>()\n  })\n\n  it(\"transform\", () => {\n    expect(S.asSchema(S.transform(aContext, bContext, { decode: () => 1, encode: () => \"\" })))\n      .type.toBe<S.Schema<number, string, \"aContext\" | \"bContext\">>()\n    expect(S.transform(aContext, bContext, { decode: () => 1, encode: () => \"\" }))\n      .type.toBe<S.transform<aContext, bContext>>()\n  })\n\n  it(\"attachPropertySignature\", () => {\n    expect(S.Struct({ a: aContext }).pipe(S.attachPropertySignature(\"_tag\", \"A\")))\n      .type.toBe<S.SchemaClass<{ readonly a: string } & { readonly _tag: \"A\" }, { readonly a: string }, \"aContext\">>()\n    expect(S.attachPropertySignature(S.Struct({ a: aContext }), \"_tag\", \"A\"))\n      .type.toBe<S.SchemaClass<{ readonly a: string } & { readonly _tag: \"A\" }, { readonly a: string }, \"aContext\">>()\n  })\n\n  it(\"annotations\", () => {\n    expect(aContext.annotations({}))\n      .type.toBe<S.Schema<string, string, \"aContext\">>()\n  })\n\n  it(\"rename\", () => {\n    expect(S.rename(S.Struct({ a: aContext, b: bContext }), { a: \"c\", b: \"d\" }))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly c: string; readonly d: number },\n        { readonly a: string; readonly b: number },\n        \"aContext\" | \"bContext\"\n      >\n    >()\n  })\n})\n\nclass MyClass extends S.Class<MyClass>(\"MyClass\")({\n  a: aContext\n}) {}\n\ndescribe(\"Class\", () => {\n  it(\"Class\", () => {\n    expect<S.Schema.Context<typeof MyClass>>()\n      .type.toBe<\"aContext\">()\n  })\n\n  it(\"Class.transform\", () => {\n    class MyClassWithTransform extends MyClass.transformOrFail<MyClassWithTransform>(\n      \"MyClassWithTransform\"\n    )(\n      { b: bContext },\n      {\n        decode: (i) =>\n          Tag1.pipe(\n            Effect.flatMap((a) => ParseResult.succeed(i.a === a ? { ...i, b: 1 } : { ...i, b: 2 }))\n          ),\n        encode: (a) =>\n          Tag2.pipe(\n            Effect.flatMap((b) => ParseResult.succeed(a.b === b ? { a: \"a1\" } : { a: \"a2\" }))\n          )\n      }\n    ) {}\n    expect<S.Schema.Context<typeof MyClassWithTransform>>()\n      .type.toBe<\"aContext\" | \"bContext\" | \"Tag1\" | \"Tag2\">()\n    expect(MyClassWithTransform.fields)\n      .type.toBe<{ readonly a: aContext; readonly b: bContext }>()\n  })\n\n  it(\"Class.transformFrom\", () => {\n    class MyClassWithTransformFrom extends MyClass.transformOrFailFrom<MyClassWithTransformFrom>(\n      \"MyClassWithTransformFrom\"\n    )(\n      { b: bContext },\n      {\n        decode: (i) =>\n          Tag1.pipe(\n            Effect.flatMap((a) => ParseResult.succeed(i.a === a ? { ...i, b: 1 } : { ...i, b: 2 }))\n          ),\n        encode: (a) =>\n          Tag2.pipe(\n            Effect.flatMap((b) => ParseResult.succeed(a.b === b ? { a: \"a1\" } : { a: \"a2\" }))\n          )\n      }\n    ) {}\n    expect<S.Schema.Context<typeof MyClassWithTransformFrom>>()\n      .type.toBe<\"aContext\" | \"bContext\" | \"Tag1\" | \"Tag2\">()\n    expect(MyClassWithTransformFrom.fields)\n      .type.toBe<{ readonly a: aContext; readonly b: bContext }>()\n  })\n})\n\nclass MyRequest extends S.TaggedRequest<MyRequest>()(\"MyRequest\", {\n  failure: bContext,\n  success: cContext,\n  payload: { a: aContext }\n}) {}\n\ndescribe(\"TaggedRequest\", () => {\n  it(\"TaggedRequest\", () => {\n    expect<S.Schema.Context<typeof MyRequest>>()\n      .type.toBe<\"aContext\">()\n    expect(MyRequest.fields)\n      .type.toBe<{ readonly _tag: S.tag<\"MyRequest\">; readonly a: aContext }>()\n  })\n\n  it(\"exitSchema\", () => {\n    expect(S.exitSchema(myRequest))\n      .type.toBe<\n      S.Schema<Exit.Exit<boolean, number>, S.ExitEncoded<boolean, number, unknown>, \"bContext\" | \"cContext\">\n    >()\n  })\n})\n\ndescribe(\"TemplateLiteralParser\", () => {\n  it(\"TemplateLiteralParser\", () => {\n    expect(\n      S.asSchema(\n        S.TemplateLiteralParser(\n          hole<S.Schema<string, string, \"a\">>(),\n          \"a\",\n          hole<S.Schema<string, string, \"b\">>()\n        )\n      )\n    )\n      .type.toBe<S.Schema<readonly [string, \"a\", string], `${string}a${string}`, \"a\" | \"b\">>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/Generic.tst.ts",
    "content": "import { Either, Schema } from \"effect\"\n\nexport const f1 = <A extends object, I extends object, R>(\n  resultSchema: Schema.Schema<A, I, R>\n) => {\n  const left = Schema.Struct({\n    ok: Schema.Literal(false),\n    error: Schema.String\n  })\n  const right = <A, I, R>(\n    resultSchema: Schema.Schema<A, I, R>\n  ) => Schema.extend(Schema.Struct({ ok: Schema.Literal(true) }), resultSchema)\n  const union = Schema.Union(left, right(resultSchema))\n  const out = Schema.transform(\n    union,\n    Schema.EitherFromSelf({ left: Schema.String, right: Schema.typeSchema(resultSchema) }),\n    {\n      decode: (u) => u.ok ? Either.right(u) : Either.left(u.error),\n      encode: (a) => ({ ok: true as const, ...a })\n    }\n  )\n  return out\n}\n\ntype Model = { id: string } & Record<string, unknown>\n\nexport const f2 = <T extends Model>(schema: Schema.Schema<T>) => {\n  type Patch = Pick<T, \"id\"> & Partial<Omit<T, \"id\">>\n\n  const patch: Schema.Schema<Patch> = schema.pipe(\n    Schema.pick(\"id\"),\n    Schema.extend(schema.pipe(Schema.omit(\"id\"), Schema.partial))\n  )\n\n  return patch\n}\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/PropertySignature.tst.ts",
    "content": "import { Schema } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Schema Property Signature\", () => {\n  it(\"should have the correct field types\", () => {\n    const A = Schema.propertySignature(Schema.String)\n    expect(A).type.toBe<Schema.propertySignature<typeof Schema.String>>()\n\n    const AA = A.annotations({})\n    expect(AA).type.toBe<Schema.propertySignature<typeof Schema.String>>()\n\n    const B = Schema.optional(Schema.Number)\n    expect(B).type.toBe<Schema.optional<typeof Schema.Number>>()\n\n    const BB = B.annotations({})\n    expect(BB).type.toBe<Schema.optional<typeof Schema.Number>>()\n\n    const C = Schema.optionalWith(Schema.Boolean, { exact: true })\n    expect(C).type.toBe<Schema.optionalWith<typeof Schema.Boolean, { exact: true }>>()\n\n    const CC = C.annotations({})\n    expect(CC).type.toBe<Schema.optionalWith<typeof Schema.Boolean, { exact: true }>>()\n\n    const schema = Schema.Struct({\n      a: AA,\n      b: BB,\n      c: CC\n    })\n\n    expect(schema.fields.a.from).type.toBe<typeof Schema.String>()\n    expect(schema.fields.b.from).type.toBe<typeof Schema.Number>()\n    expect(schema.fields.c.from).type.toBe<typeof Schema.Boolean>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/Schema.tst.ts",
    "content": "/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\nimport type {\n  Arbitrary,\n  BigDecimal,\n  Cause,\n  Chunk,\n  Config,\n  DateTime,\n  Duration,\n  Either,\n  Equivalence,\n  Exit,\n  FiberId,\n  HashMap,\n  HashSet,\n  List,\n  Pretty,\n  Redacted,\n  SchemaAST,\n  SortedSet,\n  Types\n} from \"effect\"\nimport {\n  Brand,\n  Context,\n  Effect,\n  hole,\n  identity,\n  Number as N,\n  Option,\n  ParseResult,\n  pipe,\n  Schema as S,\n  String as Str\n} from \"effect\"\nimport { describe, expect, it, when } from \"tstyche\"\n\nclass A extends S.Class<A>(\"A\")({ a: S.NonEmptyString }) {}\ndeclare const anyNever: S.Schema<any>\ndeclare const neverAny: S.Schema<never, any>\ndeclare const anyNeverPropertySignature: S.PropertySignature<\"?:\", any, never, \"?:\", never, false>\ndeclare const neverAnyPropertySignature: S.PropertySignature<\"?:\", never, never, \"?:\", any, false>\nconst ServiceA = Context.GenericTag<\"ServiceA\", string>(\"ServiceA\")\ndeclare const aContext: S.Schema<string, string, \"a\">\ndeclare const bContext: S.Schema<number, number, \"b\">\ndeclare const cContext: S.Schema<boolean, boolean, \"c\">\n\ndescribe(\"Schema\", () => {\n  describe(\"SchemaClass\", () => {\n    it(\"the constructor should not be callable\", () => {\n      // @ts-expect-error! TODO use '.toHaveConstructSignatures()' when it will be implemented\n      new S.String()\n    })\n  })\n\n  describe(\"Type Level Helpers\", () => {\n    it(\"Schema.Encoded\", () => {\n      expect<S.Schema.Encoded<typeof S.Never>>().type.toBe<never>()\n      expect<S.Schema.Encoded<typeof S.NumberFromString>>().type.toBe<string>()\n    })\n\n    it(\"Schema.Type\", () => {\n      expect<S.Schema.Type<typeof S.Never>>().type.toBe<never>()\n      expect<S.Schema.Type<typeof S.NumberFromString>>().type.toBe<number>()\n    })\n\n    it(\"Schema.Context\", () => {\n      expect<S.Schema.Context<typeof S.Never>>().type.toBe<never>()\n      expect<S.Schema.Context<S.Schema<number, string, \"ctx\">>>().type.toBe<\"ctx\">()\n    })\n\n    it(\"Struct.Type\", () => {\n      expect(hole<Types.Simplify<S.Struct.Type<{}>>>()).type.toBe<{}>()\n      expect(hole<Types.Simplify<S.Struct.Type<{ a: S.Schema<number, string> }>>>()).type.toBe<{ readonly a: number }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Type<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\":\", number, never, \":\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: number; readonly b: number }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Type<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\":\", number, never, \"?:\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: number; readonly b: number }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Type<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\":\", number, \"c\", \":\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: number; readonly b: number }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Type<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\":\", number, \"c\", \"?:\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: number; readonly b: number }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Type<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\"?:\", number, never, \":\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: number; readonly b?: number }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Type<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\"?:\", number, never, \"?:\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: number; readonly b?: number }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Type<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\"?:\", number, \"c\", \":\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: number; readonly b?: number }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Type<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\"?:\", number, \"c\", \"?:\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: number; readonly b?: number }>()\n    })\n\n    it(\"Struct.Encoded\", () => {\n      expect(hole<Types.Simplify<S.Struct.Encoded<{}>>>()).type.toBe<{}>()\n      expect(hole<Types.Simplify<S.Struct.Encoded<{ a: S.Schema<number, string> }>>>()).type.toBe<\n        { readonly a: string }\n      >()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Encoded<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\":\", number, never, \":\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: string; readonly b: string }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Encoded<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\":\", number, never, \"?:\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: string; readonly b?: string }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Encoded<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\":\", number, \"c\", \":\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: string; readonly c: string }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Encoded<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\":\", number, \"c\", \"?:\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: string; readonly c?: string }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Encoded<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\"?:\", number, never, \":\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: string; readonly b: string }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Encoded<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\"?:\", number, never, \"?:\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: string; readonly b?: string }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Encoded<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\"?:\", number, \"c\", \":\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: string; readonly c: string }>()\n      expect(hole<\n        Types.Simplify<\n          S.Struct.Encoded<{\n            a: S.Schema<number, string>\n            b: S.PropertySignature<\"?:\", number, \"c\", \"?:\", string, false, \"context\">\n          }>\n        >\n      >()).type.toBe<{ readonly a: string; readonly c?: string }>()\n    })\n\n    it(\"Struct.Constructor\", () => {\n      expect(\n        hole<\n          S.Struct.Constructor<{\n            a: S.PropertySignature<\":\", string, never, \":\", string, true>\n            b: typeof S.Number\n            c: S.PropertySignature<\":\", boolean, never, \":\", boolean, true>\n          }>\n        >()\n      ).type.toBe<{ readonly a?: string } & { readonly b: number } & { readonly c?: boolean }>()\n    })\n\n    it(\"TupleType.Type\", () => {\n      expect(hole<S.TupleType.Type<[], []>>()).type.toBe<readonly []>()\n      expect(hole<S.TupleType.Type<[typeof S.NumberFromString], []>>()).type.toBe<readonly [number]>()\n      expect(hole<S.TupleType.Type<[], [typeof S.NumberFromString]>>()).type.toBe<ReadonlyArray<number>>()\n      expect(hole<S.TupleType.Type<[typeof S.NumberFromString], [typeof S.NumberFromString]>>()).type.toBe<\n        readonly [number, ...Array<number>]\n      >()\n      expect(\n        hole<S.TupleType.Type<[typeof S.NumberFromString], [typeof S.NumberFromString, typeof S.NumberFromString]>>()\n      ).type.toBe<readonly [number, ...Array<number>, number]>()\n      expect(\n        hole<S.TupleType.Type<[typeof S.NumberFromString, S.Element<typeof S.NumberFromString, \"?\">], []>>()\n      ).type.toBe<readonly [number, number?]>()\n      expect(\n        hole<\n          S.TupleType.Type<\n            [typeof S.NumberFromString, S.Element<typeof S.NumberFromString, \"?\">],\n            [typeof S.NumberFromString]\n          >\n        >()\n      ).type.toBe<readonly [number, number?, ...Array<number>]>()\n    })\n\n    it(\"TupleType.Encoded\", () => {\n      expect(hole<S.TupleType.Encoded<[], []>>()).type.toBe<readonly []>()\n      expect(hole<S.TupleType.Encoded<[typeof S.NumberFromString], []>>()).type.toBe<readonly [string]>()\n      expect(hole<S.TupleType.Encoded<[], [typeof S.NumberFromString]>>()).type.toBe<ReadonlyArray<string>>()\n      expect(hole<S.TupleType.Encoded<[typeof S.NumberFromString], [typeof S.NumberFromString]>>()).type.toBe<\n        readonly [string, ...Array<string>]\n      >()\n      expect(\n        hole<S.TupleType.Encoded<[typeof S.NumberFromString], [typeof S.NumberFromString, typeof S.NumberFromString]>>()\n      ).type.toBe<readonly [string, ...Array<string>, string]>()\n      expect(\n        hole<S.TupleType.Encoded<[typeof S.NumberFromString, S.Element<typeof S.NumberFromString, \"?\">], []>>()\n      ).type.toBe<readonly [string, string?]>()\n      expect(\n        hole<\n          S.TupleType.Encoded<\n            [typeof S.NumberFromString, S.Element<typeof S.NumberFromString, \"?\">],\n            [typeof S.NumberFromString]\n          >\n        >()\n      ).type.toBe<readonly [string, string?, ...Array<string>]>()\n    })\n\n    it(\"TupleType.Context\", () => {\n      expect(\n        hole<S.Schema.Context<S.TupleType<[typeof aContext], [typeof bContext, typeof cContext]>>>()\n      ).type.toBe<\"a\" | \"b\" | \"c\">()\n    })\n  })\n\n  it(\"annotations\", () => {\n    // should allow to add custom string annotations to a schema\n    expect(S.String.annotations({ a: 1 })).type.toBe<S.SchemaClass<string, string>>()\n    // should allow to add custom symbol annotations to a schema\n    expect(S.String.annotations({ [Symbol.for(\"a\")]: 1 })).type.toBe<S.SchemaClass<string, string>>()\n\n    interface AnnotatedString extends S.Annotable<AnnotatedString, string> {}\n    const AnnotatedString = hole<AnnotatedString>()\n\n    expect(hole<S.Schema<string>>().pipe(S.annotations({}))).type.toBe<S.Schema<string>>()\n    expect(AnnotatedString.pipe(S.annotations({}))).type.toBe<AnnotatedString>()\n\n    expect(S.Number.pipe(S.int(), S.brand(\"Int\"), S.annotations({})))\n      .type.toBe<S.brand<S.filter<typeof S.Number>, \"Int\">>()\n    expect(S.Struct({ a: AnnotatedString }).pipe(S.annotations({}))).type.toBe<S.Struct<{ a: AnnotatedString }>>()\n    expect(A.pipe(S.annotations({}))).type.toBe<S.SchemaClass<A, { readonly a: string }>>()\n    expect(S.Number.pipe(S.int(), S.brand(\"Int\")).make(1)).type.toBe<number & Brand.Brand<\"Int\">>()\n  })\n\n  it(\"Never\", () => {\n    expect(S.Never).type.toBeAssignableTo<S.Schema<never>>()\n    expect(S.Never).type.toBeAssignableTo<S.SchemaClass<never>>()\n  })\n\n  it(\"Primitives\", () => {\n    expect(S.asSchema(S.Void)).type.toBe<S.Schema<void, void>>()\n    expect(S.Void).type.toBe<typeof S.Void>()\n\n    expect(S.asSchema(S.Undefined)).type.toBe<S.Schema<undefined, undefined>>()\n    expect(S.Undefined).type.toBe<typeof S.Undefined>()\n\n    expect(S.asSchema(S.String)).type.toBe<S.Schema<string>>()\n    expect(S.String).type.toBe<typeof S.String>()\n\n    expect(S.asSchema(S.Number)).type.toBe<S.Schema<number>>()\n    expect(S.Number).type.toBe<typeof S.Number>()\n\n    expect(S.asSchema(S.Boolean)).type.toBe<S.Schema<boolean, boolean>>()\n    expect(S.Boolean).type.toBe<typeof S.Boolean>()\n\n    expect(S.asSchema(S.BigIntFromSelf)).type.toBe<S.Schema<bigint, bigint>>()\n    expect(S.BigIntFromSelf).type.toBe<typeof S.BigIntFromSelf>()\n\n    expect(S.asSchema(S.BigInt)).type.toBe<S.Schema<bigint, string>>()\n    expect(S.BigInt).type.toBe<typeof S.BigInt>()\n\n    expect(S.asSchema(S.SymbolFromSelf)).type.toBe<S.Schema<symbol, symbol>>()\n    expect(S.SymbolFromSelf).type.toBe<typeof S.SymbolFromSelf>()\n\n    expect(S.asSchema(S.Symbol)).type.toBe<S.Schema<symbol, string>>()\n    expect(S.Symbol).type.toBe<typeof S.Symbol>()\n\n    expect(S.asSchema(S.Unknown)).type.toBe<S.Schema<unknown, unknown>>()\n    expect(S.Unknown).type.toBe<typeof S.Unknown>()\n\n    expect(S.asSchema(S.Any)).type.toBe<S.Schema<any, any>>()\n    expect(S.Any).type.toBe<typeof S.Any>()\n\n    expect(S.asSchema(S.Object)).type.toBe<S.Schema<object, object>>()\n    expect(S.Object).type.toBe<typeof S.Object>()\n  })\n\n  it(\"Literal\", () => {\n    expect(S.asSchema(S.Null)).type.toBe<S.Schema<null, null>>()\n    expect(S.Null).type.toBe<typeof S.Null>()\n\n    expect(S.Literal()).type.toBe<S.Never>()\n    expect(S.Literal(...[])).type.toBe<S.Never>()\n    expect(S.Literal(...([] as Array<\"a\" | \"b\">))).type.toBe<S.SchemaClass<\"a\" | \"b\">>()\n    expect(S.Literal(...([] as Array<never>))).type.toBe<S.SchemaClass<never>>()\n    expect(S.asSchema(S.Literal(\"a\"))).type.toBe<S.Schema<\"a\">>()\n    expect(S.Literal(\"a\")).type.toBe<S.Literal<[\"a\"]>>()\n\n    expect(S.asSchema(S.Literal(\"a\", \"b\", \"c\"))).type.toBe<S.Schema<\"a\" | \"b\" | \"c\">>()\n    expect(S.Literal(\"a\", \"b\", \"c\")).type.toBe<S.Literal<[\"a\", \"b\", \"c\"]>>()\n\n    expect(S.Literal(1)).type.toBe<S.Literal<[1]>>()\n    expect(S.Literal(2n)).type.toBe<S.Literal<[2n]>>()\n    expect(S.Literal(true)).type.toBe<S.Literal<[true]>>()\n    expect(S.Literal(\"A\", \"B\")).type.toBe<S.Literal<[\"A\", \"B\"]>>()\n    expect(S.Literal(\"A\", \"B\").literals).type.toBe<readonly [\"A\", \"B\"]>()\n    expect(S.Literal(\"A\", \"B\").annotations({})).type.toBe<S.Literal<[\"A\", \"B\"]>>()\n  })\n\n  describe(\"Enums\", () => {\n    enum Fruits {\n      Apple,\n      Banana\n    }\n\n    const schema = S.Enums(Fruits)\n\n    it(\"Schema Type\", () => {\n      expect(S.asSchema(schema)).type.toBeAssignableTo<S.Schema<Fruits>>()\n      expect(schema).type.toBe<S.Enums<typeof Fruits>>()\n    })\n\n    it(\"should expose the enums field\", () => {\n      const enums = schema.enums\n      expect(enums).type.toBe<typeof Fruits>()\n      expect(enums.Apple).type.toBe<Fruits.Apple>()\n      expect(enums.Banana).type.toBe<Fruits.Banana>()\n    })\n  })\n\n  it(\"UndefinedOr\", () => {\n    expect(S.UndefinedOr(S.Never)).type.toBe<S.UndefinedOr<typeof S.Never>>()\n  })\n\n  it(\"NullishOr\", () => {\n    expect(S.NullishOr(S.Never)).type.toBe<S.NullishOr<typeof S.Never>>()\n  })\n\n  it(\"NullOr\", () => {\n    expect(S.NullOr(S.Never)).type.toBe<S.NullOr<typeof S.Never>>()\n    expect(S.asSchema(S.NullOr(S.String))).type.toBe<S.Schema<string | null, string | null>>()\n    expect(S.NullOr(S.String)).type.toBe<S.NullOr<typeof S.String>>()\n    expect(S.asSchema(S.NullOr(S.NumberFromString))).type.toBe<S.Schema<number | null, string | null>>()\n    expect(S.NullOr(S.NumberFromString)).type.toBe<S.NullOr<typeof S.NumberFromString>>()\n  })\n\n  describe(\"Union\", () => {\n    it(\"should allow Never members\", () => {\n      const schema = S.Union(S.String, S.Never)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n      expect(schema).type.toBe<S.Union<[typeof S.String, typeof S.Never]>>()\n    })\n\n    it(\"union of primitives\", () => {\n      const schema = S.Union(S.String, S.Number)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<string | number, string | number>>()\n      expect(schema).type.toBe<S.Union<[typeof S.String, typeof S.Number]>>()\n      expect(schema.annotations({})).type.toBe<S.Union<[typeof S.String, typeof S.Number]>>()\n      // should expose the members\n      expect(schema.members).type.toBe<readonly [typeof S.String, typeof S.Number]>()\n    })\n\n    it(\"primitive + transformation\", () => {\n      const schema = S.Union(S.Boolean, S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<number | boolean, string | boolean>>()\n      expect(schema).type.toBe<S.Union<[typeof S.Boolean, typeof S.NumberFromString]>>()\n      expect(schema.annotations({\n        pretty: () => (a) => {\n          expect(a).type.toBe<number | boolean>()\n          return \"-\"\n        }\n      })).type.toBe<S.Union<[typeof S.Boolean, typeof S.NumberFromString]>>()\n    })\n  })\n\n  it(\"keyof\", () => {\n    expect(S.keyof(S.Struct({ a: S.String, b: S.NumberFromString }))).type.toBe<S.SchemaClass<\"a\" | \"b\", \"a\" | \"b\">>()\n  })\n\n  describe(\"Tuple\", () => {\n    it(\"required elements\", () => {\n      expect(S.asSchema(S.Tuple(S.String, S.Number)))\n        .type.toBe<S.Schema<readonly [string, number], readonly [string, number]>>()\n      expect(S.Tuple(S.String, S.Number)).type.toBe<S.Tuple2<typeof S.String, typeof S.Number>>()\n      expect(S.asSchema(S.Tuple(S.String, S.NumberFromString)))\n        .type.toBe<S.Schema<readonly [string, number], readonly [string, string]>>()\n      expect(S.Tuple(S.String, S.NumberFromString)).type.toBe<S.Tuple2<typeof S.String, typeof S.NumberFromString>>()\n      expect(S.Tuple(S.String, S.Number).elements).type.toBe<readonly [typeof S.String, typeof S.Number]>()\n      expect(S.Tuple(S.String, S.Number).rest).type.toBe<readonly []>()\n    })\n\n    it(\"required elements + rest\", () => {\n      expect(S.asSchema(S.Tuple([S.String], S.Number, S.Boolean))).type.toBe<\n        S.Schema<readonly [string, ...Array<number>, boolean], readonly [string, ...Array<number>, boolean]>\n      >()\n      expect(S.Tuple([S.String], S.Number, S.Boolean)).type.toBe<\n        S.TupleType<readonly [typeof S.String], [typeof S.Number, typeof S.Boolean]>\n      >()\n      expect(S.Tuple([S.String], S.Number).elements).type.toBe<readonly [typeof S.String]>()\n      expect(S.Tuple([S.String], S.Number).rest).type.toBe<readonly [typeof S.Number]>()\n      expect(S.Tuple([S.String], S.Number, S.Boolean).rest).type.toBe<readonly [typeof S.Number, typeof S.Boolean]>()\n    })\n\n    it(\"optional elements\", () => {\n      expect(S.asSchema(S.Tuple(S.String, S.Number, S.optionalElement(S.Boolean))))\n        .type.toBe<S.Schema<readonly [string, number, boolean?], readonly [string, number, boolean?]>>()\n      expect(S.Tuple(S.String, S.Number, S.optionalElement(S.Boolean)))\n        .type.toBe<S.Tuple<[typeof S.String, typeof S.Number, S.Element<typeof S.Boolean, \"?\">]>>()\n      expect(\n        S.asSchema(S.Tuple(S.String, S.NumberFromString, S.optionalElement(S.NumberFromString)))\n      ).type.toBe<S.Schema<readonly [string, number, number?], readonly [string, string, string?]>>()\n      expect(\n        S.Tuple(S.String, S.NumberFromString, S.optionalElement(S.NumberFromString))\n      ).type.toBe<S.Tuple<[typeof S.String, typeof S.NumberFromString, S.Element<typeof S.NumberFromString, \"?\">]>>()\n    })\n\n    it(\"Array\", () => {\n      expect(S.asSchema(S.Array(S.Number))).type.toBe<S.Schema<ReadonlyArray<number>, ReadonlyArray<number>>>()\n      expect(S.Array(S.Number)).type.toBe<S.Array$<typeof S.Number>>()\n      expect(pipe(S.Number, S.Array)).type.toBe<S.Array$<typeof S.Number>>()\n      expect(S.asSchema(S.Array(S.NumberFromString)))\n        .type.toBe<S.Schema<ReadonlyArray<number>, ReadonlyArray<string>>>()\n      expect(S.Array(S.NumberFromString)).type.toBe<S.Array$<typeof S.NumberFromString>>()\n      expect(S.Array(S.String).value).type.toBe<typeof S.String>()\n      expect(S.Array(S.String).elements).type.toBe<readonly []>()\n      expect(S.Array(S.String).rest).type.toBe<readonly [typeof S.String]>()\n    })\n  })\n\n  it(\"NonEmptyArray\", () => {\n    const schema = S.NonEmptyArray(S.NumberFromString)\n    expect(S.asSchema(schema))\n      .type.toBe<S.Schema<readonly [number, ...Array<number>], readonly [string, ...Array<string>]>>()\n    expect(schema).type.toBe<S.NonEmptyArray<typeof S.NumberFromString>>()\n    expect(schema.annotations({\n      pretty: () => (nea) => {\n        expect(nea).type.toBe<readonly [number, ...Array<number>]>()\n        return \"-\"\n      }\n    })).type.toBe<S.NonEmptyArray<typeof S.NumberFromString>>()\n\n    // should support pipe\n    expect(pipe(S.NumberFromString, S.NonEmptyArray)).type.toBe<S.NonEmptyArray<typeof S.NumberFromString>>()\n\n    // should expose the value, elements and rest fields\n    expect(schema.value).type.toBe<typeof S.NumberFromString>()\n    expect(schema.elements).type.toBe<readonly [typeof S.NumberFromString]>()\n    expect(schema.rest).type.toBe<readonly [typeof S.NumberFromString]>()\n  })\n\n  describe(\"Struct\", () => {\n    it(\"baseline\", () => {\n      const schema = S.Struct({ a: S.String, b: S.NumberFromString })\n      expect(S.asSchema(schema))\n        .type.toBe<S.Schema<{ readonly a: string; readonly b: number }, { readonly a: string; readonly b: string }>>()\n      expect(schema).type.toBe<S.Struct<{ a: typeof S.String; b: typeof S.NumberFromString }>>()\n      expect(schema.annotations({\n        pretty: () => (a) => {\n          expect(a).type.toBe<{\n            readonly a: string\n            readonly b: number\n          }>()\n          return \"-\"\n        }\n      })).type.toBe<S.Struct<{ a: typeof S.String; b: typeof S.NumberFromString }>>()\n\n      // exposed fields\n      expect(schema.fields).type.toBe<{ readonly a: typeof S.String; readonly b: typeof S.NumberFromString }>()\n      expect(schema.records).type.toBe<readonly []>()\n    })\n\n    it(\"should accept Never as a field\", () => {\n      const schema = S.Struct({ a: S.Never, b: S.NumberFromString })\n      expect(S.asSchema(schema))\n        .type.toBe<S.Schema<{ readonly a: never; readonly b: number }, { readonly a: never; readonly b: string }>>()\n      expect(schema).type.toBe<S.Struct<{ a: typeof S.Never; b: typeof S.NumberFromString }>>()\n      expect(schema.annotations({\n        pretty: () => (a) => {\n          expect(a).type.toBe<{\n            readonly a: never\n            readonly b: number\n          }>()\n          return \"-\"\n        }\n      })).type.toBe<S.Struct<{ a: typeof S.Never; b: typeof S.NumberFromString }>>()\n\n      expect(S.asSchema(S.Struct({ a: anyNever }))).type.toBe<S.Schema<{ readonly a: any }, { readonly a: any }>>()\n      expect(S.asSchema(S.Struct({ a: neverAny }))).type.toBe<S.Schema<{ readonly a: never }, { readonly a: any }>>()\n      expect(S.asSchema(S.Struct({ a: anyNeverPropertySignature })))\n        .type.toBe<S.Schema<{ readonly a?: any }, { readonly a?: never }>>()\n      expect(S.asSchema(S.Struct({ a: neverAnyPropertySignature })))\n        .type.toBe<S.Schema<{ readonly a?: never }, { readonly a?: any }>>()\n    })\n\n    describe(\"make\", () => {\n      it(\"baseline\", () => {\n        const schema = S.Struct({ a: S.String, b: S.NumberFromString })\n        expect(schema.make).type.toBe<\n          (\n            props: { readonly a: string; readonly b: number },\n            options?: S.MakeOptions | undefined\n          ) => { readonly a: string; readonly b: number }\n        >()\n        expect(schema.annotations({}).make).type.toBe<\n          (\n            props: { readonly a: string; readonly b: number },\n            options?: S.MakeOptions | undefined\n          ) => { readonly a: string; readonly b: number }\n        >()\n      })\n\n      it(\"withConstructorDefault\", () => {\n        const schema = S.Struct({\n          a: S.propertySignature(S.String).pipe(S.withConstructorDefault(() => \"\")),\n          b: S.Number,\n          c: S.propertySignature(S.Boolean).pipe(S.withConstructorDefault(() => true))\n        })\n        expect(schema.make).type.toBe<\n          (\n            props: { readonly a?: string; readonly b: number; readonly c?: boolean },\n            options?: S.MakeOptions | undefined\n          ) => { readonly a: string; readonly b: number; readonly c: boolean }\n        >()\n        expect(schema.annotations({}).make).type.toBe<\n          (\n            props: { readonly a?: string; readonly b: number; readonly c?: boolean },\n            options?: S.MakeOptions | undefined\n          ) => { readonly a: string; readonly b: number; readonly c: boolean }\n        >()\n      })\n    })\n\n    it(\"pick\", () => {\n      expect(S.Struct({ a: S.String }).pick).type.not.toBeCallableWith(\"c\")\n      expect(S.Struct({ a: S.propertySignature(S.String).pipe(S.fromKey(\"c\")) }).pick)\n        .type.not.toBeCallableWith(\"c\")\n\n      expect(S.Struct({ a: S.String, b: S.Number, c: S.Boolean }).pick(\"a\", \"b\"))\n        .type.toBe<S.Struct<{ a: typeof S.String; b: typeof S.Number }>>()\n\n      const f = <Fields extends S.Struct.Fields, A extends { readonly a: string }>(\n        schema: S.Struct<Fields> & S.Schema<A, S.Struct.Encoded<Fields>, S.Struct.Context<Fields>>\n      ) => {\n        expect(schema.fields).type.toBe<Readonly<Fields>>()\n        const picked = schema.pick(\"a\") // existing field\n        expect(picked).type.toBe<S.Struct<{ a: Fields[\"a\"] }>>()\n\n        const e = S.encodeUnknown(schema)(null)\n        expect(e).type.toBe<\n          Effect.Effect<S.Struct.Encoded<Fields>, ParseResult.ParseError, S.Schema.Context<Fields[keyof Fields]>>\n        >()\n\n        return picked\n      }\n\n      when(f).isCalledWith(expect(S.Struct).type.not.toBeCallableWith({ b: S.String }))\n\n      when(f).isCalledWith(expect(S.Struct).type.not.toBeCallableWith({ a: S.Number }))\n    })\n\n    it(\"omit\", () => {\n      expect(S.Struct({ a: S.String }).omit).type.not.toBeCallableWith(\"c\")\n      expect(S.Struct({ a: S.propertySignature(S.String).pipe(S.fromKey(\"c\")) }).omit).type.not.toBeCallableWith(\"c\")\n\n      expect(S.Struct({ a: S.String, b: S.Number, c: S.Boolean }).omit(\"c\"))\n        .type.toBe<S.Struct<{ a: typeof S.String; b: typeof S.Number }>>()\n      expect(S.Struct({ a: S.Number, b: S.Number.pipe(S.propertySignature, S.fromKey(\"c\")) }).omit(\"b\"))\n        .type.toBe<S.Struct<{ a: typeof S.Number }>>()\n\n      const f = <Fields extends S.Struct.Fields, A extends { readonly a: string }>(\n        schema: S.Struct<Fields> & S.Schema<A, S.Struct.Encoded<Fields>, S.Struct.Context<Fields>>\n      ) => {\n        expect(schema.fields).type.toBe<Readonly<Fields>>()\n        const omitted = schema.omit(\"a\") // existing field\n        expect(omitted).type.toBe<S.Struct<{ [K in keyof Omit<Fields, \"a\">]: Omit<Fields, \"a\">[K] }>>()\n\n        const e = S.encodeUnknown(schema)(null)\n        expect(e).type.toBe<\n          Effect.Effect<S.Struct.Encoded<Fields>, ParseResult.ParseError, S.Schema.Context<Fields[keyof Fields]>>\n        >()\n\n        return omitted\n      }\n\n      when(f).isCalledWith(expect(S.Struct).type.not.toBeCallableWith({ b: S.String }))\n\n      when(f).isCalledWith(expect(S.Struct).type.not.toBeCallableWith({ a: S.Number }))\n    })\n  })\n\n  describe(\"Record\", () => {\n    it(\"baseline\", () => {\n      const schema = S.Record({ key: S.String, value: S.NumberFromString })\n      expect(S.asSchema(schema)).type.toBe<\n        S.Schema<{ readonly [x: string]: number }, { readonly [x: string]: string }>\n      >()\n      expect(schema).type.toBe<S.Record$<typeof S.String, typeof S.NumberFromString>>()\n      expect(schema.annotations({\n        pretty: () => (s) => {\n          expect(s).type.toBe<{ readonly [x: string]: number }>()\n          return \"-\"\n        }\n      })).type.toBe<S.Record$<typeof S.String, typeof S.NumberFromString>>()\n\n      // exposed fields\n      expect(schema.fields).type.toBe<{}>()\n      expect(schema.records).type.toBe<\n        readonly [{ readonly key: typeof S.String; readonly value: typeof S.NumberFromString }]\n      >()\n      expect(schema.key).type.toBe<typeof S.String>()\n      expect(schema.value).type.toBe<typeof S.NumberFromString>()\n    })\n\n    it(\"make\", () => {\n      const schema = S.Record({ key: S.String, value: S.NumberFromString })\n      const make = schema.make\n      expect(make).type.toBe<\n        (\n          props: void | { readonly [x: string]: number },\n          options?: S.MakeOptions | undefined\n        ) => { readonly [x: string]: number }\n      >()\n    })\n\n    it(\"keys as union of literals\", () => {\n      const schema = S.Record({ key: S.Union(S.Literal(\"a\"), S.Literal(\"b\")), value: S.NumberFromString })\n      expect(S.asSchema(schema)).type.toBe<\n        S.Schema<\n          { readonly a: number; readonly b: number },\n          { readonly a: string; readonly b: string }\n        >\n      >()\n      expect(schema).type.toBe<S.Record$<S.Union<[S.Literal<[\"a\"]>, S.Literal<[\"b\"]>]>, typeof S.NumberFromString>>()\n      expect(schema.annotations({\n        pretty: () => (s) => {\n          expect(s).type.toBe<{\n            readonly a: number\n            readonly b: number\n          }>()\n          return \"-\"\n        }\n      })).type.toBe<S.Record$<S.Union<[S.Literal<[\"a\"]>, S.Literal<[\"b\"]>]>, typeof S.NumberFromString>>()\n    })\n\n    it(\"keys as symbols\", () => {\n      const schema = S.Record({ key: S.SymbolFromSelf, value: S.NumberFromString })\n      expect(S.asSchema(schema)).type.toBe<\n        S.Schema<\n          { readonly [x: symbol]: number },\n          { readonly [x: symbol]: string }\n        >\n      >()\n      expect(schema).type.toBe<S.Record$<typeof S.SymbolFromSelf, typeof S.NumberFromString>>()\n      expect(schema.annotations({\n        pretty: () => (s) => {\n          expect(s).type.toBe<{ readonly [x: symbol]: number }>()\n          return \"-\"\n        }\n      })).type.toBe<S.Record$<typeof S.SymbolFromSelf, typeof S.NumberFromString>>()\n    })\n\n    it(\"keys as template literals\", () => {\n      const schema = S.Record({ key: S.TemplateLiteral(S.Literal(\"a\"), S.String), value: S.NumberFromString })\n      expect(S.asSchema(schema)).type.toBe<\n        S.Schema<{ readonly [x: `a${string}`]: number }, { readonly [x: `a${string}`]: string }>\n      >()\n      expect(schema).type.toBe<S.Record$<S.TemplateLiteral<`a${string}`>, typeof S.NumberFromString>>()\n      expect(schema.annotations({\n        pretty: () => (s) => {\n          expect(s).type.toBe<{ readonly [x: `a${string}`]: number }>()\n          return \"-\"\n        }\n      })).type.toBe<S.Record$<S.TemplateLiteral<`a${string}`>, typeof S.NumberFromString>>()\n    })\n\n    it(\"keys as branded types (string)\", () => {\n      const schema = S.Record({ key: S.String.pipe(S.brand(\"UserId\")), value: S.NumberFromString })\n      expect(S.asSchema(schema)).type.toBe<\n        S.Schema<{ readonly [x: string & Brand.Brand<\"UserId\">]: number }, { readonly [x: string]: string }>\n      >()\n      expect(schema).type.toBe<S.Record$<S.brand<typeof S.String, \"UserId\">, typeof S.NumberFromString>>()\n      expect(schema.annotations({\n        pretty: () => (s) => {\n          expect(s).type.toBe<{ readonly [x: string & Brand.Brand<\"UserId\">]: number }>()\n          return \"-\"\n        }\n      })).type.toBe<S.Record$<S.brand<typeof S.String, \"UserId\">, typeof S.NumberFromString>>()\n    })\n\n    it(\"keys as branded types (symbol)\", () => {\n      const schema = S.Record({ key: S.String.pipe(S.brand(Symbol.for(\"UserId\"))), value: S.NumberFromString })\n      expect(S.asSchema(schema)).type.toBe<\n        S.Schema<{ readonly [x: string & Brand.Brand<symbol>]: number }, { readonly [x: string]: string }>\n      >()\n      expect(schema).type.toBe<S.Record$<S.brand<typeof S.String, symbol>, typeof S.NumberFromString>>()\n      expect(schema.annotations({\n        pretty: () => (s) => {\n          expect(s).type.toBe<{ readonly [x: string & Brand.Brand<symbol>]: number }>()\n          return \"-\"\n        }\n      })).type.toBe<S.Record$<S.brand<typeof S.String, symbol>, typeof S.NumberFromString>>()\n    })\n  })\n\n  describe(\"TypeLiteral\", () => {\n    it(\"1 index signature\", () => {\n      const schema = S.Struct({ a: S.NumberFromString }, { key: S.String, value: S.NumberFromString })\n      expect(S.asSchema(schema)).type.toBe<\n        S.Schema<\n          { readonly [x: string]: number; readonly a: number },\n          { readonly [x: string]: string; readonly a: string }\n        >\n      >()\n      expect(schema).type.toBe<\n        S.TypeLiteral<\n          { a: typeof S.NumberFromString },\n          readonly [{ readonly key: typeof S.String; readonly value: typeof S.NumberFromString }]\n        >\n      >()\n      expect(schema.annotations({\n        pretty: () => (s) => {\n          expect(s).type.toBe<{ readonly [x: string]: number; readonly a: number }>()\n          return \"-\"\n        }\n      })).type.toBe<\n        S.TypeLiteral<\n          { a: typeof S.NumberFromString },\n          readonly [{ readonly key: typeof S.String; readonly value: typeof S.NumberFromString }]\n        >\n      >()\n\n      // exposed fields\n      expect(schema.fields).type.toBe<{ readonly a: typeof S.NumberFromString }>()\n      expect(schema.records).type.toBe<\n        readonly [{ readonly key: typeof S.String; readonly value: typeof S.NumberFromString }]\n      >()\n    })\n\n    it(\"make\", () => {\n      const schema = S.Struct({ a: S.NumberFromString }, { key: S.String, value: S.NumberFromString })\n      expect(schema.make).type.toBe<\n        (\n          props: void | { readonly [x: string]: number; readonly a: number },\n          options?: S.MakeOptions | undefined\n        ) => { readonly [x: string]: number; readonly a: number }\n      >()\n      expect(schema.annotations({}).make).type.toBe<\n        (\n          props: void | { readonly [x: string]: number; readonly a: number },\n          options?: S.MakeOptions | undefined\n        ) => { readonly [x: string]: number; readonly a: number }\n      >()\n    })\n\n    it(\"2 index signatures\", () => {\n      const schema = S.Struct(\n        { a: S.NumberFromString },\n        { key: S.String, value: S.NumberFromString },\n        { key: S.Symbol, value: S.NumberFromString }\n      )\n      expect(S.asSchema(schema)).type.toBe<\n        S.Schema<\n          { readonly [x: string]: number; readonly [x: symbol]: number; readonly a: number },\n          { readonly [x: string]: string; readonly a: string }\n        >\n      >()\n      expect(schema).type.toBe<\n        S.TypeLiteral<\n          { a: typeof S.NumberFromString },\n          readonly [\n            { readonly key: typeof S.String; readonly value: typeof S.NumberFromString },\n            { readonly key: typeof S.Symbol; readonly value: typeof S.NumberFromString }\n          ]\n        >\n      >()\n      expect(schema.annotations({\n        pretty: () => (s) => {\n          expect(s).type.toBe<{ readonly [x: string]: number; readonly [x: symbol]: number; readonly a: number }>()\n          return \"-\"\n        }\n      })).type.toBe<\n        S.TypeLiteral<\n          { a: typeof S.NumberFromString },\n          readonly [\n            { readonly key: typeof S.String; readonly value: typeof S.NumberFromString },\n            { readonly key: typeof S.Symbol; readonly value: typeof S.NumberFromString }\n          ]\n        >\n      >()\n\n      // exposed fields\n      expect(schema.fields).type.toBe<{ readonly a: typeof S.NumberFromString }>()\n      expect(schema.records).type.toBe<\n        readonly [\n          { readonly key: typeof S.String; readonly value: typeof S.NumberFromString },\n          { readonly key: typeof S.Symbol; readonly value: typeof S.NumberFromString }\n        ]\n      >()\n\n      expect(schema.make).type.toBe<\n        (\n          props: void | { readonly [x: string]: number; readonly [x: symbol]: number; readonly a: number },\n          options?: S.MakeOptions | undefined\n        ) => { readonly [x: string]: number; readonly [x: symbol]: number; readonly a: number }\n      >()\n      expect(schema.annotations({}).make).type.toBe<\n        (\n          props: void | { readonly [x: string]: number; readonly [x: symbol]: number; readonly a: number },\n          options?: S.MakeOptions | undefined\n        ) => { readonly [x: string]: number; readonly [x: symbol]: number; readonly a: number }\n      >()\n    })\n  })\n\n  it(\"optional\", () => {\n    expect(S.optional(S.Never)).type.toBe<S.optional<typeof S.Never>>()\n    expect(\n      S.asSchema(S.Struct({ a: S.String, b: S.Number, c: S.optional(S.Boolean) }))\n    ).type.toBe<\n      S.Schema<\n        { readonly a: string; readonly b: number; readonly c?: boolean | undefined },\n        { readonly a: string; readonly b: number; readonly c?: boolean | undefined },\n        never\n      >\n    >()\n    expect(S.Struct({ a: S.String, b: S.Number, c: S.optional(S.Boolean) }))\n      .type.toBe<S.Struct<{ a: typeof S.String; b: typeof S.Number; c: S.optional<typeof S.Boolean> }>>()\n    expect(\n      S.asSchema(S.Struct({ a: S.String, b: S.Number, c: S.optional(S.NumberFromString) }))\n    ).type.toBe<\n      S.Schema<\n        { readonly a: string; readonly b: number; readonly c?: number | undefined },\n        { readonly a: string; readonly b: number; readonly c?: string | undefined },\n        never\n      >\n    >()\n    expect(S.Struct({ a: S.String, b: S.Number, c: S.optional(S.NumberFromString) }))\n      .type.toBe<S.Struct<{ a: typeof S.String; b: typeof S.Number; c: S.optional<typeof S.NumberFromString> }>>()\n    expect(S.asSchema(S.Struct({ a: S.String.pipe(S.optional) })))\n      .type.toBe<S.Schema<{ readonly a?: string | undefined }, { readonly a?: string | undefined }>>()\n    expect(S.Struct({ a: S.String.pipe(S.optional) })).type.toBe<S.Struct<{ a: S.optional<typeof S.String> }>>()\n  })\n\n  describe(\"optionalWith\", () => {\n    it(\"{ exact: true }\", () => {\n      expect(\n        S.asSchema(S.Struct({ a: S.optionalWith(S.Never, { exact: true }) }))\n      ).type.toBe<S.Schema<{ readonly a?: never }, { readonly a?: never }>>()\n      expect(S.Struct({ a: S.optionalWith(S.Never, { exact: true }) }))\n        .type.toBe<S.Struct<{ a: S.optionalWith<typeof S.Never, { exact: true }> }>>()\n      expect(\n        S.asSchema(S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.Boolean, { exact: true }) }))\n      ).type.toBe<\n        S.Schema<\n          { readonly a: string; readonly b: number; readonly c?: boolean },\n          { readonly a: string; readonly b: number; readonly c?: boolean },\n          never\n        >\n      >()\n      expect(\n        S.asSchema(S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.NumberFromString, { exact: true }) }))\n      ).type.toBe<\n        S.Schema<\n          { readonly a: string; readonly b: number; readonly c?: number },\n          { readonly a: string; readonly b: number; readonly c?: string },\n          never\n        >\n      >()\n      expect(S.Struct({ a: S.Literal(\"a\", \"b\").pipe(S.optionalWith({ exact: true })) }))\n        .type.toBe<S.Struct<{ a: S.optionalWith<S.Literal<[\"a\", \"b\"]>, { exact: true }> }>>()\n    })\n\n    it(\"Type Level Errors\", () => {\n      expect(S.optionalWith).type.not.toBeCallableWith(S.String, { as: \"Option\", default: () => \"\" })\n      expect(S.optionalWith).type.not.toBeCallableWith(S.String, {\n        as: \"Option\",\n        exact: true,\n        onNoneEncoding: () => Option.some(null)\n      })\n      expect(S.optionalWith).type.not.toBeCallableWith(\n        { as: \"Option\", exact: true, onNoneEncoding: () => Option.some(null) }\n      )\n      expect(S.optionalWith).type.not.toBeCallableWith(S.String, {\n        as: \"Option\",\n        exact: true,\n        nullable: true,\n        onNoneEncoding: () => Option.some(1)\n      })\n      expect(S.optionalWith).type.not.toBeCallableWith(S.String, {\n        as: \"Option\",\n        onNoneEncoding: () => Option.some(null)\n      })\n      expect(S.optionalWith).type.not.toBeCallableWith({ as: \"Option\", onNoneEncoding: () => Option.some(null) })\n      expect(S.optionalWith).type.not.toBeCallableWith(\n        { as: \"Option\", exact: true, nullable: true, onNoneEncoding: () => Option.some(1) }\n      )\n      expect(S.optionalWith).type.not.toBeCallableWith(S.String, {\n        as: \"Option\",\n        nullable: true,\n        onNoneEncoding: () => Option.some(1)\n      })\n      expect(S.optionalWith).type.not.toBeCallableWith(\n        { as: \"Option\", nullable: true, onNoneEncoding: () => Option.some(1) }\n      )\n      expect(S.optionalWith).type.not.toBeCallableWith(S.String, { as: null })\n      expect(S.optionalWith).type.not.toBeCallableWith(S.String, { default: null })\n    })\n\n    it(\"used in a generic context\", () => {\n      type TypeWithValue<Value extends S.Schema.Any> = { value: S.optionalWith<Value, { nullable: true }> }\n      const makeTypeWithValue = <Value extends S.Schema.Any>(value: Value): TypeWithValue<Value> => ({\n        value: S.optionalWith(value, { nullable: true })\n      })\n      expect(makeTypeWithValue(S.String)).type.toBe<TypeWithValue<typeof S.String>>()\n    })\n\n    it(\"{ exact: true, default: () => A }\", () => {\n      expect(\n        S.asSchema(\n          S.Struct({\n            a: S.String,\n            b: S.Number,\n            c: S.optionalWith(S.Boolean, { exact: true, default: () => false })\n          })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: string; readonly b: number; readonly c: boolean },\n          { readonly a: string; readonly b: number; readonly c?: boolean },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({\n          a: S.String,\n          b: S.Number,\n          c: S.optionalWith(S.Boolean, { exact: true, default: () => false })\n        })\n      ).type.toBe<\n        S.Struct<{\n          a: typeof S.String\n          b: typeof S.Number\n          c: S.optionalWith<typeof S.Boolean, { exact: true; default: () => false }>\n        }>\n      >()\n\n      expect(\n        S.asSchema(\n          S.Struct({\n            a: S.String,\n            b: S.Number,\n            c: S.optionalWith(S.NumberFromString, { exact: true, default: () => 0 })\n          })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: string; readonly b: number; readonly c: number },\n          { readonly a: string; readonly b: number; readonly c?: string },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({\n          a: S.String,\n          b: S.Number,\n          c: S.optionalWith(S.NumberFromString, { exact: true, default: () => 0 })\n        })\n      ).type.toBe<\n        S.Struct<{\n          a: typeof S.String\n          b: typeof S.Number\n          c: S.optionalWith<typeof S.NumberFromString, { exact: true; default: () => number }>\n        }>\n      >()\n\n      expect(\n        S.Struct({ a: S.optionalWith(S.Literal(\"a\", \"b\"), { default: () => \"a\", exact: true }) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<S.Literal<[\"a\", \"b\"]>, { default: () => \"a\"; exact: true }>\n        }>\n      >()\n\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.Literal(\"a\", \"b\").pipe(S.optionalWith({ default: () => \"a\", exact: true })) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: \"a\" | \"b\" },\n          { readonly a?: \"a\" | \"b\" },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.Literal(\"a\", \"b\").pipe(S.optionalWith({ default: () => \"a\", exact: true })) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<S.Literal<[\"a\", \"b\"]>, { default: () => \"a\"; exact: true }>\n        }>\n      >()\n    })\n\n    it(\"{ default: () => A }\", () => {\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.Boolean, { default: () => false }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: string; readonly b: number; readonly c: boolean },\n          { readonly a: string; readonly b: number; readonly c?: boolean | undefined },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.Boolean, { default: () => false }) })\n      ).type.toBe<\n        S.Struct<{\n          a: typeof S.String\n          b: typeof S.Number\n          c: S.optionalWith<typeof S.Boolean, { default: () => false }>\n        }>\n      >()\n\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.NumberFromString, { default: () => 0 }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: string; readonly b: number; readonly c: number },\n          { readonly a: string; readonly b: number; readonly c?: string | undefined },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.NumberFromString, { default: () => 0 }) })\n      ).type.toBe<\n        S.Struct<{\n          a: typeof S.String\n          b: typeof S.Number\n          c: S.optionalWith<typeof S.NumberFromString, { default: () => number }>\n        }>\n      >()\n\n      expect(\n        S.Struct({ a: S.optionalWith(S.Literal(\"a\", \"b\"), { default: () => \"a\" }) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<S.Literal<[\"a\", \"b\"]>, { default: () => \"a\" }>\n        }>\n      >()\n\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.Literal(\"a\", \"b\").pipe(S.optionalWith({ default: () => \"a\" })) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: \"a\" | \"b\" },\n          { readonly a?: \"a\" | \"b\" | undefined },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.Literal(\"a\", \"b\").pipe(S.optionalWith({ default: () => \"a\" })) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<S.Literal<[\"a\", \"b\"]>, { default: () => \"a\" }>\n        }>\n      >()\n    })\n\n    it(\"{ exact: true, nullable: true, default: () => A }\", () => {\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.optionalWith(S.NumberFromString, { exact: true, nullable: true, default: () => 0 }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: number },\n          { readonly a?: string | null },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.optionalWith(S.NumberFromString, { exact: true, nullable: true, default: () => 0 }) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<typeof S.NumberFromString, { exact: true; nullable: true; default: () => number }>\n        }>\n      >()\n    })\n\n    it(\"{ nullable: true, default: () => A }\", () => {\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.optionalWith(S.NumberFromString, { nullable: true, default: () => 0 }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: number },\n          { readonly a?: string | null | undefined },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.optionalWith(S.NumberFromString, { nullable: true, default: () => 0 }) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<typeof S.NumberFromString, { nullable: true; default: () => number }>\n        }>\n      >()\n\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.optionalWith(S.NumberFromString, { exact: true, nullable: true, default: () => 0 }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: number },\n          { readonly a?: string | null },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.optionalWith(S.NumberFromString, { exact: true, nullable: true, default: () => 0 }) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<typeof S.NumberFromString, { exact: true; nullable: true; default: () => number }>\n        }>\n      >()\n\n      expect(\n        S.Struct({ a: S.optionalWith(S.Literal(\"a\", \"b\"), { default: () => \"a\", nullable: true }) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<S.Literal<[\"a\", \"b\"]>, { default: () => \"a\"; nullable: true }>\n        }>\n      >()\n\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.Literal(\"a\", \"b\").pipe(S.optionalWith({ default: () => \"a\", nullable: true })) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: \"a\" | \"b\" },\n          { readonly a?: \"a\" | \"b\" | null | undefined },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.Literal(\"a\", \"b\").pipe(S.optionalWith({ default: () => \"a\", nullable: true })) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<S.Literal<[\"a\", \"b\"]>, { default: () => \"a\"; nullable: true }>\n        }>\n      >()\n    })\n\n    it(\"{ exact: true, as: 'Option' }\", () => {\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.Boolean, { exact: true, as: \"Option\" }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: string; readonly b: number; readonly c: Option.Option<boolean> },\n          { readonly a: string; readonly b: number; readonly c?: boolean },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.Boolean, { exact: true, as: \"Option\" }) })\n      ).type.toBe<\n        S.Struct<{\n          a: typeof S.String\n          b: typeof S.Number\n          c: S.optionalWith<typeof S.Boolean, { exact: true; as: \"Option\" }>\n        }>\n      >()\n\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.NumberFromString, { exact: true, as: \"Option\" }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: string; readonly b: number; readonly c: Option.Option<number> },\n          { readonly a: string; readonly b: number; readonly c?: string },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.NumberFromString, { exact: true, as: \"Option\" }) })\n      ).type.toBe<\n        S.Struct<{\n          a: typeof S.String\n          b: typeof S.Number\n          c: S.optionalWith<typeof S.NumberFromString, { exact: true; as: \"Option\" }>\n        }>\n      >()\n\n      expect(\n        S.asSchema(S.Struct({ a: S.String.pipe(S.optionalWith({ exact: true, as: \"Option\" })) }))\n      ).type.toBe<\n        S.Schema<\n          { readonly a: Option.Option<string> },\n          { readonly a?: string },\n          never\n        >\n      >()\n\n      expect(\n        S.Struct({ a: S.String.pipe(S.optionalWith({ exact: true, as: \"Option\" })) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<typeof S.String, { exact: true; as: \"Option\" }>\n        }>\n      >()\n    })\n\n    it(\"{ as: 'Option' }\", () => {\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.Boolean, { as: \"Option\" }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: string; readonly b: number; readonly c: Option.Option<boolean> },\n          { readonly a: string; readonly b: number; readonly c?: boolean | undefined },\n          never\n        >\n      >()\n      expect(\n        S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.Boolean, { as: \"Option\" }) })\n      ).type.toBe<\n        S.Struct<{\n          a: typeof S.String\n          b: typeof S.Number\n          c: S.optionalWith<typeof S.Boolean, { as: \"Option\" }>\n        }>\n      >()\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.NumberFromString, { as: \"Option\" }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: string; readonly b: number; readonly c: Option.Option<number> },\n          { readonly a: string; readonly b: number; readonly c?: string | undefined },\n          never\n        >\n      >()\n      expect(\n        S.Struct({ a: S.String, b: S.Number, c: S.optionalWith(S.NumberFromString, { as: \"Option\" }) })\n      ).type.toBe<\n        S.Struct<{\n          a: typeof S.String\n          b: typeof S.Number\n          c: S.optionalWith<typeof S.NumberFromString, { as: \"Option\" }>\n        }>\n      >()\n      expect(\n        S.asSchema(S.Struct({ a: S.String.pipe(S.optionalWith({ as: \"Option\" })) }))\n      ).type.toBe<\n        S.Schema<\n          { readonly a: Option.Option<string> },\n          { readonly a?: string | undefined },\n          never\n        >\n      >()\n      expect(\n        S.Struct({ a: S.String.pipe(S.optionalWith({ as: \"Option\" })) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<typeof S.String, { as: \"Option\" }>\n        }>\n      >()\n    })\n\n    it(\"{ nullable: true, as: 'Option' }\", () => {\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.optionalWith(S.NumberFromString, { nullable: true, as: \"Option\" }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: Option.Option<number> },\n          { readonly a?: string | null | undefined },\n          never\n        >\n      >()\n      expect(\n        S.Struct({ a: S.optionalWith(S.NumberFromString, { nullable: true, as: \"Option\" }) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<typeof S.NumberFromString, { nullable: true; as: \"Option\" }>\n        }>\n      >()\n      expect(\n        S.asSchema(S.Struct({ a: S.String.pipe(S.optionalWith({ nullable: true, as: \"Option\" })) }))\n      ).type.toBe<\n        S.Schema<\n          { readonly a: Option.Option<string> },\n          { readonly a?: string | null | undefined },\n          never\n        >\n      >()\n      expect(\n        S.Struct({ a: S.String.pipe(S.optionalWith({ nullable: true, as: \"Option\" })) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<typeof S.String, { nullable: true; as: \"Option\" }>\n        }>\n      >()\n    })\n\n    it(\"{ exact: true, nullable: true, as: 'Option' }\", () => {\n      expect(\n        S.asSchema(\n          S.Struct({ a: S.optionalWith(S.NumberFromString, { exact: true, nullable: true, as: \"Option\" }) })\n        )\n      ).type.toBe<\n        S.Schema<\n          { readonly a: Option.Option<number> },\n          { readonly a?: string | null },\n          never\n        >\n      >()\n      expect(\n        S.Struct({ a: S.optionalWith(S.NumberFromString, { exact: true, nullable: true, as: \"Option\" }) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<typeof S.NumberFromString, { exact: true; nullable: true; as: \"Option\" }>\n        }>\n      >()\n      expect(\n        S.asSchema(S.Struct({ a: S.String.pipe(S.optionalWith({ exact: true, nullable: true, as: \"Option\" })) }))\n      ).type.toBe<\n        S.Schema<\n          { readonly a: Option.Option<string> },\n          { readonly a?: string | null },\n          never\n        >\n      >()\n      expect(\n        S.Struct({ a: S.String.pipe(S.optionalWith({ exact: true, nullable: true, as: \"Option\" })) })\n      ).type.toBe<\n        S.Struct<{\n          a: S.optionalWith<typeof S.String, { exact: true; nullable: true; as: \"Option\" }>\n        }>\n      >()\n    })\n  })\n\n  describe(\"pick\", () => {\n    it(\"required fields\", () => {\n      when(pipe).isCalledWith(\n        S.Struct({ a: S.propertySignature(S.Number).pipe(S.fromKey(\"c\")) }),\n        expect(S.pick).type.not.toBeCallableWith(\"a\")\n      )\n      expect(\n        pipe(S.Struct({ a: S.String, b: S.Number, c: S.Boolean }), S.pick(\"a\", \"b\"))\n      ).type.toBe<\n        S.SchemaClass<{ readonly a: string; readonly b: number }, { readonly a: string; readonly b: number }>\n      >()\n      expect(\n        pipe(S.Struct({ a: S.String, b: S.NumberFromString, c: S.Boolean }), S.pick(\"a\", \"b\"))\n      ).type.toBe<\n        S.SchemaClass<{ readonly a: string; readonly b: number }, { readonly a: string; readonly b: string }>\n      >()\n    })\n\n    it(\"optional fields\", () => {\n      expect(\n        pipe(\n          S.Struct({ a: S.optionalWith(S.String, { exact: true }), b: S.Number, c: S.Boolean }),\n          S.pick(\"a\", \"b\")\n        )\n      ).type.toBe<\n        S.SchemaClass<{ readonly a?: string; readonly b: number }, { readonly a?: string; readonly b: number }>\n      >()\n      expect(\n        pipe(\n          S.Struct({ a: S.optionalWith(S.String, { exact: true }), b: S.NumberFromString, c: S.Boolean }),\n          S.pick(\"a\", \"b\")\n        )\n      ).type.toBe<\n        S.SchemaClass<{ readonly a?: string; readonly b: number }, { readonly a?: string; readonly b: string }>\n      >()\n      expect(\n        pipe(\n          S.Struct({\n            a: S.optionalWith(S.String, { exact: true, default: () => \"\" }),\n            b: S.NumberFromString,\n            c: S.Boolean\n          }),\n          S.pick(\"a\", \"b\")\n        )\n      ).type.toBe<\n        S.SchemaClass<{ readonly a: string; readonly b: number }, { readonly a?: string; readonly b: string }>\n      >()\n    })\n  })\n\n  describe(\"omit\", () => {\n    it(\"required fields\", () => {\n      when(pipe).isCalledWith(\n        S.Struct({ a: S.propertySignature(S.Number).pipe(S.fromKey(\"c\")) }),\n        expect(S.omit).type.not.toBeCallableWith(\"a\")\n      )\n      expect(\n        pipe(S.Struct({ a: S.String, b: S.Number, c: S.Boolean }), S.omit(\"c\"))\n      ).type.toBe<\n        S.SchemaClass<{ readonly a: string; readonly b: number }, { readonly a: string; readonly b: number }>\n      >()\n      expect(\n        pipe(S.Struct({ a: S.String, b: S.NumberFromString, c: S.Boolean }), S.omit(\"c\"))\n      ).type.toBe<\n        S.SchemaClass<{ readonly a: string; readonly b: number }, { readonly a: string; readonly b: string }>\n      >()\n    })\n\n    it(\"optional fields\", () => {\n      expect(\n        pipe(\n          S.Struct({ a: S.optionalWith(S.String, { exact: true }), b: S.Number, c: S.Boolean }),\n          S.omit(\"c\")\n        )\n      ).type.toBe<\n        S.SchemaClass<{ readonly a?: string; readonly b: number }, { readonly a?: string; readonly b: number }>\n      >()\n      expect(\n        pipe(\n          S.Struct({ a: S.optionalWith(S.String, { exact: true }), b: S.NumberFromString, c: S.Boolean }),\n          S.omit(\"c\")\n        )\n      ).type.toBe<\n        S.SchemaClass<{ readonly a?: string; readonly b: number }, { readonly a?: string; readonly b: string }>\n      >()\n      expect(\n        pipe(\n          S.Struct({\n            a: S.optionalWith(S.String, { exact: true, default: () => \"\" }),\n            b: S.NumberFromString,\n            c: S.Boolean\n          }),\n          S.omit(\"c\")\n        )\n      ).type.toBe<\n        S.SchemaClass<{ readonly a: string; readonly b: number }, { readonly a?: string; readonly b: string }>\n      >()\n    })\n  })\n\n  it(\"brand\", () => {\n    const schema = pipe(S.Number, S.int(), S.brand(\"Int\"))\n    expect(S.asSchema(schema)).type.toBe<S.Schema<number & Brand.Brand<\"Int\">, number>>()\n    expect(schema).type.toBe<S.brand<S.filter<typeof S.Number>, \"Int\">>()\n    expect(schema.annotations({})).type.toBe<S.brand<S.filter<typeof S.Number>, \"Int\">>()\n    expect(schema.from).type.toBe<S.filter<typeof S.Number>>()\n\n    const schema2 = pipe(S.NumberFromString, S.int(), S.brand(\"Int\"))\n    expect(S.asSchema(schema2)).type.toBe<S.Schema<number & Brand.Brand<\"Int\">, string>>()\n    expect(schema2).type.toBe<S.brand<S.filter<typeof S.NumberFromString>, \"Int\">>()\n  })\n\n  it(\"partial\", () => {\n    expect(S.partial(S.Struct({ a: S.String, b: S.Number })))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a?: string | undefined; readonly b?: number | undefined },\n        { readonly a?: string | undefined; readonly b?: number | undefined },\n        never\n      >\n    >()\n    expect(S.partial(S.Struct({ a: S.String, b: S.NumberFromString })))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a?: string | undefined; readonly b?: number | undefined },\n        { readonly a?: string | undefined; readonly b?: string | undefined },\n        never\n      >\n    >()\n    expect(S.Struct({ a: S.String, b: S.Number }).pipe(S.partial))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a?: string | undefined; readonly b?: number | undefined },\n        { readonly a?: string | undefined; readonly b?: number | undefined },\n        never\n      >\n    >()\n  })\n\n  it(\"partialWith\", () => {\n    expect(S.partialWith(S.Struct({ a: S.String, b: S.Number }), { exact: true }))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a?: string; readonly b?: number },\n        { readonly a?: string; readonly b?: number },\n        never\n      >\n    >()\n    expect(S.partialWith(S.Struct({ a: S.String, b: S.NumberFromString }), { exact: true }))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a?: string; readonly b?: number },\n        { readonly a?: string; readonly b?: string },\n        never\n      >\n    >()\n    expect(S.Struct({ a: S.String, b: S.Number }).pipe(S.partialWith({ exact: true })))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a?: string; readonly b?: number },\n        { readonly a?: string; readonly b?: number },\n        never\n      >\n    >()\n  })\n\n  it(\"required with optionalWith\", () => {\n    expect(\n      S.required(\n        S.Struct({ a: S.optionalWith(S.String, { exact: true }), b: S.optionalWith(S.Number, { exact: true }) })\n      )\n    ).type.toBe<\n      S.SchemaClass<\n        { readonly a: string; readonly b: number },\n        { readonly a: string; readonly b: number },\n        never\n      >\n    >()\n    expect(\n      S.required(\n        S.Struct({\n          a: S.optionalWith(S.String, { exact: true }),\n          b: S.NumberFromString,\n          c: S.optionalWith(S.NumberFromString, { exact: true })\n        })\n      )\n    ).type.toBe<\n      S.SchemaClass<\n        { readonly a: string; readonly b: number; readonly c: number },\n        { readonly a: string; readonly b: string; readonly c: string },\n        never\n      >\n    >()\n  })\n\n  it(\"extend\", () => {\n    expect(\n      S.asSchema(\n        pipe(\n          S.Struct({ a: S.String, b: S.String }),\n          S.extend(S.Struct({ c: S.String }))\n        )\n      )\n    ).type.toBe<\n      S.Schema<\n        { readonly a: string; readonly b: string } & { readonly c: string },\n        { readonly a: string; readonly b: string } & { readonly c: string },\n        never\n      >\n    >()\n    expect(\n      pipe(\n        S.Struct({ a: S.String, b: S.String }),\n        S.extend(S.Struct({ c: S.String }))\n      )\n    ).type.toBe<S.extend<S.Struct<{ a: typeof S.String; b: typeof S.String }>, S.Struct<{ c: typeof S.String }>>>()\n    expect(\n      S.asSchema(S.extend(S.Struct({ a: S.String, b: S.String }), S.Struct({ c: S.String })))\n    ).type.toBe<\n      S.Schema<\n        { readonly a: string; readonly b: string } & { readonly c: string },\n        { readonly a: string; readonly b: string } & { readonly c: string },\n        never\n      >\n    >()\n    expect(\n      S.extend(S.Struct({ a: S.String, b: S.String }), S.Struct({ c: S.String }))\n    ).type.toBe<S.extend<S.Struct<{ a: typeof S.String; b: typeof S.String }>, S.Struct<{ c: typeof S.String }>>>()\n    expect(\n      S.asSchema(\n        S.extend(S.Struct({ a: S.String }), S.Union(S.Struct({ b: S.Number }), S.Struct({ c: S.Boolean })))\n      )\n    ).type.toBe<\n      S.Schema<\n        { readonly a: string } & ({ readonly b: number } | { readonly c: boolean }),\n        { readonly a: string } & ({ readonly b: number } | { readonly c: boolean }),\n        never\n      >\n    >()\n    expect(\n      S.extend(S.Struct({ a: S.String }), S.Union(S.Struct({ b: S.Number }), S.Struct({ c: S.Boolean })))\n    ).type.toBe<\n      S.extend<\n        S.Struct<{ a: typeof S.String }>,\n        S.Union<[S.Struct<{ b: typeof S.Number }>, S.Struct<{ c: typeof S.Boolean }>]>\n      >\n    >()\n    expect(\n      S.asSchema(\n        pipe(\n          S.Struct({ a: S.String, b: S.String }),\n          S.extend(S.Struct({ c: S.String })),\n          S.extend(S.Record({ key: S.String, value: S.String }))\n        )\n      )\n    ).type.toBe<\n      S.Schema<\n        { readonly a: string; readonly b: string } & { readonly c: string } & { readonly [x: string]: string }\n      >\n    >()\n    expect(\n      pipe(\n        S.Struct({ a: S.String, b: S.String }),\n        S.extend(S.Struct({ c: S.String })),\n        S.extend(S.Record({ key: S.String, value: S.String }))\n      )\n    ).type.toBe<\n      S.extend<\n        S.extend<S.Struct<{ a: typeof S.String; b: typeof S.String }>, S.Struct<{ c: typeof S.String }>>,\n        S.Record$<typeof S.String, typeof S.String>\n      >\n    >()\n  })\n\n  it(\"suspend\", () => {\n    interface SuspendIEqualA {\n      readonly a: number\n      readonly as: ReadonlyArray<SuspendIEqualA>\n    }\n    const SuspendIEqualA = S.Struct({\n      a: S.Number,\n      as: S.Array(S.suspend((): S.Schema<SuspendIEqualA> => SuspendIEqualA))\n    })\n    expect(SuspendIEqualA.fields)\n      .type.toBe<\n      { readonly a: typeof S.Number; readonly as: S.Array$<S.suspend<SuspendIEqualA, SuspendIEqualA, never>> }\n    >()\n\n    interface SuspendINotEqualA_A {\n      readonly a: string\n      readonly as: ReadonlyArray<SuspendINotEqualA_A>\n    }\n    interface SuspendINotEqualA_I {\n      readonly a: number\n      readonly as: ReadonlyArray<SuspendINotEqualA_I>\n    }\n    const SuspendINotEqualA = S.Struct({\n      a: S.NumberFromString,\n      as: S.Array(S.suspend((): S.Schema<SuspendINotEqualA_I, SuspendINotEqualA_A> => SuspendINotEqualA))\n    })\n    expect(SuspendINotEqualA.fields).type.toBe<\n      {\n        readonly a: typeof S.NumberFromString\n        readonly as: S.Array$<S.suspend<SuspendINotEqualA_I, SuspendINotEqualA_A, never>>\n      }\n    >()\n  })\n\n  it(\"rename\", () => {\n    expect(S.rename(S.Struct({ a: S.String, b: S.Number }), {}))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a: string; readonly b: number },\n        { readonly a: string; readonly b: number },\n        never\n      >\n    >()\n    expect(S.rename(S.Struct({ a: S.String, b: S.Number }), { a: \"c\" }))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly c: string; readonly b: number },\n        { readonly a: string; readonly b: number },\n        never\n      >\n    >()\n    expect(S.rename(S.Struct({ a: S.String, b: S.Number }), { a: \"c\", b: \"d\" }))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly c: string; readonly d: number },\n        { readonly a: string; readonly b: number },\n        never\n      >\n    >()\n    const a = Symbol.for(\"effect/Schema/dtslint/a\")\n    expect(S.rename(S.Struct({ a: S.String, b: S.Number }), { a }))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly [a]: string; readonly b: number },\n        { readonly a: string; readonly b: number },\n        never\n      >\n    >()\n    expect(S.rename).type.not.toBeCallableWith(S.Struct({ a: S.String, b: S.Number }), { c: \"d\" })\n    expect(S.rename).type.not.toBeCallableWith(S.Struct({ a: S.String, b: S.Number }), { a: \"c\", d: \"e\" })\n    expect(S.Struct({ a: S.String, b: S.Number }).pipe(S.rename({})))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a: string; readonly b: number },\n        { readonly a: string; readonly b: number },\n        never\n      >\n    >()\n    expect(S.Struct({ a: S.String, b: S.Number }).pipe(S.rename({ a: \"c\" })))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly c: string; readonly b: number },\n        { readonly a: string; readonly b: number },\n        never\n      >\n    >()\n    when(S.Struct({ a: S.String, b: S.Number }).pipe).isCalledWith(\n      expect(S.rename).type.not.toBeCallableWith({ c: \"d\" })\n    )\n    when(S.Struct({ a: S.String, b: S.Number }).pipe).isCalledWith(\n      expect(S.rename).type.not.toBeCallableWith({ a: \"c\", d: \"e\" })\n    )\n  })\n\n  describe(\"declare\", () => {\n    it(\"instanceOf\", () => {\n      class Test {\n        constructor(readonly name: string) {}\n      }\n      const schema = S.instanceOf(Test)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Test, Test>>()\n      expect(schema).type.toBe<S.instanceOf<Test>>()\n      expect(schema.annotations({})).type.toBe<S.instanceOf<Test>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly []>()\n    })\n  })\n\n  it(\"TemplateLiteral\", () => {\n    expect(S.TemplateLiteral(\"a\"))\n      .type.toBe<S.TemplateLiteral<\"a\">>()\n    expect(S.TemplateLiteral(S.Literal(\"a\")))\n      .type.toBe<S.TemplateLiteral<\"a\">>()\n    expect(S.TemplateLiteral(1))\n      .type.toBe<S.TemplateLiteral<\"1\">>()\n    expect(S.TemplateLiteral(S.Literal(1)))\n      .type.toBe<S.TemplateLiteral<\"1\">>()\n    expect(S.TemplateLiteral(S.String))\n      .type.toBe<S.TemplateLiteral<string>>()\n    expect(S.TemplateLiteral(S.Number))\n      .type.toBe<S.TemplateLiteral<`${number}`>>()\n    expect(S.TemplateLiteral(\"a\", \"b\"))\n      .type.toBe<S.TemplateLiteral<\"ab\">>()\n    expect(S.TemplateLiteral(S.Literal(\"a\"), S.Literal(\"b\")))\n      .type.toBe<S.TemplateLiteral<\"ab\">>()\n    expect(S.TemplateLiteral(\"a\", S.String))\n      .type.toBe<S.TemplateLiteral<`a${string}`>>()\n    expect(S.TemplateLiteral(S.Literal(\"a\"), S.String))\n      .type.toBe<S.TemplateLiteral<`a${string}`>>()\n    expect(S.TemplateLiteral(\"a\", S.Number))\n      .type.toBe<S.TemplateLiteral<`a${number}`>>()\n    expect(S.TemplateLiteral(S.Literal(\"a\"), S.Number))\n      .type.toBe<S.TemplateLiteral<`a${number}`>>()\n    expect(S.TemplateLiteral(S.String, \"a\"))\n      .type.toBe<S.TemplateLiteral<`${string}a`>>()\n    expect(S.TemplateLiteral(S.String, S.Literal(\"a\")))\n      .type.toBe<S.TemplateLiteral<`${string}a`>>()\n    expect(S.TemplateLiteral(S.Number, \"a\"))\n      .type.toBe<S.TemplateLiteral<`${number}a`>>()\n    expect(S.TemplateLiteral(S.Number, S.Literal(\"a\")))\n      .type.toBe<S.TemplateLiteral<`${number}a`>>()\n    expect(S.TemplateLiteral(S.String, 0))\n      .type.toBe<S.TemplateLiteral<`${string}0`>>()\n    expect(S.TemplateLiteral(S.String, true))\n      .type.toBe<S.TemplateLiteral<`${string}true`>>()\n    expect(S.TemplateLiteral(S.String, null))\n      .type.toBe<S.TemplateLiteral<`${string}null`>>()\n    expect(S.TemplateLiteral(S.String, 1n))\n      .type.toBe<S.TemplateLiteral<`${string}1`>>()\n    expect(S.TemplateLiteral(S.String, S.Literal(\"a\", 0)))\n      .type.toBe<S.TemplateLiteral<`${string}a` | `${string}0`>>()\n    expect(S.TemplateLiteral(S.String, S.Literal(\"/\"), S.Number))\n      .type.toBe<S.TemplateLiteral<`${string}/${number}`>>()\n    expect(S.TemplateLiteral(S.String, \"/\", S.Number))\n      .type.toBe<S.TemplateLiteral<`${string}/${number}`>>()\n    const EmailLocaleIDs = S.Literal(\"welcome_email\", \"email_heading\")\n    const FooterLocaleIDs = S.Literal(\"footer_title\", \"footer_sendoff\")\n    expect(S.asSchema(S.TemplateLiteral(S.Union(EmailLocaleIDs, FooterLocaleIDs), S.Literal(\"_id\"))))\n      .type.toBe<\n      S.Schema<\n        \"welcome_email_id\" | \"email_heading_id\" | \"footer_title_id\" | \"footer_sendoff_id\",\n        \"welcome_email_id\" | \"email_heading_id\" | \"footer_title_id\" | \"footer_sendoff_id\",\n        never\n      >\n    >()\n    expect(S.TemplateLiteral(S.Union(EmailLocaleIDs, FooterLocaleIDs), \"_id\"))\n      .type.toBe<\n      S.TemplateLiteral<\n        \"welcome_email_id\" | \"email_heading_id\" | \"footer_title_id\" | \"footer_sendoff_id\"\n      >\n    >()\n    expect(S.TemplateLiteral(S.String.pipe(S.brand(\"MyBrand\"))))\n      .type.toBe<S.TemplateLiteral<`${string & Brand.Brand<\"MyBrand\">}`>>()\n    expect(S.TemplateLiteral(S.Number.pipe(S.brand(\"MyBrand\"))))\n      .type.toBe<S.TemplateLiteral<`${number & Brand.Brand<\"MyBrand\">}`>>()\n    expect(S.TemplateLiteral(\"a\", S.String.pipe(S.brand(\"MyBrand\"))))\n      .type.toBe<S.TemplateLiteral<`a${string & Brand.Brand<\"MyBrand\">}`>>()\n    expect(S.TemplateLiteral(S.Literal(\"a\"), S.String.pipe(S.brand(\"MyBrand\"))))\n      .type.toBe<S.TemplateLiteral<`a${string & Brand.Brand<\"MyBrand\">}`>>()\n    expect(S.TemplateLiteral(S.Literal(\"a\").pipe(S.brand(\"L\")), S.String.pipe(S.brand(\"MyBrand\"))))\n      .type.toBe<S.TemplateLiteral<`${\"a\" & Brand.Brand<\"L\">}${string & Brand.Brand<\"MyBrand\">}`>>()\n    expect(S.TemplateLiteral(\"a\", S.Number.pipe(S.brand(\"MyBrand\"))))\n      .type.toBe<S.TemplateLiteral<`a${number & Brand.Brand<\"MyBrand\">}`>>()\n    expect(S.TemplateLiteral(S.Literal(\"a\"), S.Number.pipe(S.brand(\"MyBrand\"))))\n      .type.toBe<S.TemplateLiteral<`a${number & Brand.Brand<\"MyBrand\">}`>>()\n    expect(S.TemplateLiteral(\"a\", S.Union(S.Number, S.String)))\n      .type.toBe<S.TemplateLiteral<`a${string}` | `a${number}`>>()\n  })\n\n  it(\"attachPropertySignature\", () => {\n    expect(\n      pipe(S.Struct({ radius: S.Number }), S.attachPropertySignature(\"kind\", \"circle\"))\n    ).type.toBe<\n      S.SchemaClass<\n        { readonly radius: number } & { readonly kind: \"circle\" },\n        { readonly radius: number },\n        never\n      >\n    >()\n    expect(\n      pipe(S.Struct({ radius: S.NumberFromString }), S.attachPropertySignature(\"kind\", \"circle\"))\n    ).type.toBe<\n      S.SchemaClass<\n        { readonly radius: number } & { readonly kind: \"circle\" },\n        { readonly radius: string },\n        never\n      >\n    >()\n    expect(S.attachPropertySignature(S.Struct({ radius: S.Number }), \"kind\", \"circle\"))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly radius: number } & { readonly kind: \"circle\" },\n        { readonly radius: number },\n        never\n      >\n    >()\n    expect(S.attachPropertySignature(S.Struct({ radius: S.NumberFromString }), \"kind\", \"circle\"))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly radius: number } & { readonly kind: \"circle\" },\n        { readonly radius: string },\n        never\n      >\n    >()\n    const taggedStruct = <Name extends SchemaAST.LiteralValue | symbol, Fields extends S.Struct.Fields>(\n      name: Name,\n      fields: Fields\n    ) => S.Struct(fields).pipe(S.attachPropertySignature(\"_tag\", name))\n    expect(taggedStruct(\"A\", { a: S.String }))\n      .type.toBe<\n      S.SchemaClass<\n        { readonly a: string } & { readonly _tag: \"A\" },\n        { readonly a: string },\n        never\n      >\n    >()\n    // should work with generic code\n    const _f = <A, I, R>(B: S.Schema<A, I, R>, input: unknown) => {\n      const union = S.Union(\n        S.Struct({ code: S.Number }).pipe(S.attachPropertySignature(\"ok\", false)),\n        B.pipe(S.attachPropertySignature(\"ok\", true))\n      )\n      S.decodeUnknown(union)(input).pipe(Effect.flatMap((data) => {\n        if (!data.ok) {\n          expect(data.code).type.toBe<number>()\n        }\n        return Effect.succeed(data)\n      }))\n    }\n  })\n\n  it(\"filterEffect\", () => {\n    expect(\n      S.String.pipe(S.filterEffect((s) => {\n        expect(s).type.toBe<string>()\n        return Effect.succeed(undefined)\n      }))\n    ).type.toBe<S.filterEffect<typeof S.String>>()\n    expect(\n      S.filterEffect(S.String, (s) => {\n        expect(s).type.toBe<string>()\n        return Effect.succeed(undefined)\n      })\n    ).type.toBe<S.filterEffect<typeof S.String>>()\n\n    expect(\n      S.String.pipe(\n        S.filterEffect((s) =>\n          Effect.gen(function*() {\n            const str = yield* ServiceA\n            return str === s\n          })\n        )\n      )\n    ).type.toBe<S.filterEffect<typeof S.String, \"ServiceA\">>()\n    expect(\n      S.filterEffect(S.String, (s) =>\n        Effect.gen(function*() {\n          const str = yield* ServiceA\n          return str === s\n        }))\n    ).type.toBe<S.filterEffect<typeof S.String, \"ServiceA\">>()\n  })\n\n  describe(\"compose\", () => {\n    it(\"{ strict: true } should not allow incompatible types\", () => {\n      expect(S.compose).type.not.toBeCallableWith(\n        S.String,\n        S.Number\n      )\n      expect(S.compose).type.not.toBeCallableWith(\n        S.String,\n        S.Number,\n        { strict: true }\n      )\n      when(S.String.pipe).isCalledWith(\n        expect(S.compose).type.not.toBeCallableWith(S.Number, { strict: true })\n      )\n    })\n\n    it(\"{ strict: false } should allow incompatible types\", () => {\n      S.compose(S.String, S.Number, { strict: false })\n      S.String.pipe(S.compose(S.Number, { strict: false }))\n    })\n\n    it(\"data last\", () => {\n      // first overload\n      const schema1_1 = S.split(\",\").pipe(S.compose(S.Array(S.NumberFromString)))\n      expect(S.asSchema(schema1_1)).type.toBe<S.Schema<ReadonlyArray<number>, string>>()\n      expect(schema1_1)\n        .type.toBe<\n        S.transform<\n          S.transform<S.SchemaClass<string, string, never>, S.Array$<typeof S.String>>,\n          S.Array$<typeof S.NumberFromString>\n        >\n      >()\n      expect(schema1_1.annotations({}))\n        .type.toBe<\n        S.transform<\n          S.transform<S.SchemaClass<string, string, never>, S.Array$<typeof S.String>>,\n          S.Array$<typeof S.NumberFromString>\n        >\n      >()\n      const schema1_2 = S.Union(S.Null, S.String).pipe(S.compose(S.NumberFromString))\n      expect(S.asSchema(schema1_2)).type.toBe<S.Schema<number, string | null>>()\n      expect(schema1_2)\n        .type.toBe<S.transform<S.Union<[typeof S.Null, typeof S.String]>, typeof S.NumberFromString>>()\n      expect(schema1_2.annotations({}))\n        .type.toBe<S.transform<S.Union<[typeof S.Null, typeof S.String]>, typeof S.NumberFromString>>()\n      expect(schema1_2.to).type.toBe<typeof S.NumberFromString>()\n\n      // second overload\n      const schema2 = S.NumberFromString.pipe(S.compose(S.Union(S.Null, S.Number)))\n      expect(schema2)\n        .type.toBe<S.transform<typeof S.NumberFromString, S.Union<[typeof S.Null, typeof S.Number]>>>()\n      expect(schema2.annotations({}))\n        .type.toBe<S.transform<typeof S.NumberFromString, S.Union<[typeof S.Null, typeof S.Number]>>>()\n\n      // third overload\n      const schema3 = S.split(\",\").pipe(S.compose(S.Array(S.NumberFromString), { strict: true }))\n      expect(S.asSchema(schema3)).type.toBe<S.Schema<ReadonlyArray<number>, string>>()\n      expect(schema3).type.toBe<\n        S.transform<\n          S.transform<S.SchemaClass<string, string, never>, S.Array$<typeof S.String>>,\n          S.Array$<typeof S.NumberFromString>\n        >\n      >()\n      expect(schema3.annotations({})).type.toBe<\n        S.transform<\n          S.transform<S.SchemaClass<string, string, never>, S.Array$<typeof S.String>>,\n          S.Array$<typeof S.NumberFromString>\n        >\n      >()\n\n      // fourth overload\n      const schema4 = S.String.pipe(S.compose(S.Number, { strict: false }))\n      expect(S.asSchema(schema4)).type.toBe<S.Schema<number, string>>()\n      expect(schema4).type.toBe<S.transform<typeof S.String, typeof S.Number>>()\n      expect(schema4.annotations({})).type.toBe<S.transform<typeof S.String, typeof S.Number>>()\n      expect(schema4.from).type.toBe<typeof S.String>()\n      expect(schema4.to).type.toBe<typeof S.Number>()\n    })\n\n    it(\"data first\", () => {\n      // first overload\n      const schema1_1 = S.compose(S.split(\",\"), S.Array(S.NumberFromString))\n      expect(S.asSchema(schema1_1)).type.toBe<S.Schema<ReadonlyArray<number>, string>>()\n      expect(schema1_1)\n        .type.toBe<\n        S.transform<\n          S.transform<S.SchemaClass<string, string, never>, S.Array$<typeof S.String>>,\n          S.Array$<typeof S.NumberFromString>\n        >\n      >()\n      expect(schema1_1.annotations({}))\n        .type.toBe<\n        S.transform<\n          S.transform<S.SchemaClass<string, string, never>, S.Array$<typeof S.String>>,\n          S.Array$<typeof S.NumberFromString>\n        >\n      >()\n      const schema1_2 = S.compose(S.Union(S.Null, S.String), S.NumberFromString)\n      expect(S.asSchema(schema1_2)).type.toBe<S.Schema<number, string | null>>()\n      expect(schema1_2)\n        .type.toBe<S.transform<S.Union<[typeof S.Null, typeof S.String]>, typeof S.NumberFromString>>()\n      expect(schema1_2.annotations({}))\n        .type.toBe<S.transform<S.Union<[typeof S.Null, typeof S.String]>, typeof S.NumberFromString>>()\n      expect(schema1_2.to).type.toBe<typeof S.NumberFromString>()\n\n      // second overload\n      const schema2 = S.compose(S.NumberFromString, S.Union(S.Null, S.Number))\n      expect(schema2)\n        .type.toBe<S.transform<typeof S.NumberFromString, S.Union<[typeof S.Null, typeof S.Number]>>>()\n      expect(schema2.annotations({}))\n        .type.toBe<S.transform<typeof S.NumberFromString, S.Union<[typeof S.Null, typeof S.Number]>>>()\n\n      // third overload\n      const schema3 = S.compose(S.split(\",\"), S.Array(S.NumberFromString), { strict: true })\n      expect(S.asSchema(schema3)).type.toBe<S.Schema<ReadonlyArray<number>, string>>()\n      expect(schema3).type.toBe<\n        S.transform<\n          S.transform<S.SchemaClass<string, string, never>, S.Array$<typeof S.String>>,\n          S.Array$<typeof S.NumberFromString>\n        >\n      >()\n      expect(schema3.annotations({})).type.toBe<\n        S.transform<\n          S.transform<S.SchemaClass<string, string, never>, S.Array$<typeof S.String>>,\n          S.Array$<typeof S.NumberFromString>\n        >\n      >()\n\n      // fourth overload\n      const schema4 = S.compose(S.String, S.Number, { strict: false })\n      expect(S.asSchema(schema4)).type.toBe<S.Schema<number, string>>()\n      expect(schema4).type.toBe<S.transform<typeof S.String, typeof S.Number>>()\n      expect(schema4.annotations({})).type.toBe<S.transform<typeof S.String, typeof S.Number>>()\n      expect(schema4.from).type.toBe<typeof S.String>()\n      expect(schema4.to).type.toBe<typeof S.Number>()\n    })\n  })\n\n  it(\"fromBrand\", () => {\n    type Eur = number & Brand.Brand<\"Eur\">\n    const Eur = Brand.nominal<Eur>()\n    expect(S.Number.pipe(S.fromBrand(Eur)))\n      .type.toBe<S.BrandSchema<number & Brand.Brand<\"Eur\">, number>>()\n  })\n\n  it(\"mutable\", () => {\n    expect(S.asSchema(S.mutable(S.String)))\n      .type.toBe<S.Schema<string>>()\n    S.mutable(S.String)\n    expect(S.asSchema(S.mutable(S.Struct({ a: S.Number }))))\n      .type.toBe<S.Schema<{ a: number }, { a: number }>>()\n    S.mutable(S.Struct({ a: S.Number }))\n    expect(S.asSchema(S.mutable(S.Record({ key: S.String, value: S.Number }))))\n      .type.toBe<S.Schema<{ [x: string]: number }, { [x: string]: number }>>()\n    S.mutable(S.Record({ key: S.String, value: S.Number }))\n    expect(S.asSchema(S.mutable(S.Array(S.String))))\n      .type.toBe<S.Schema<Array<string>>>()\n    S.mutable(S.Array(S.String))\n    expect(S.asSchema(S.mutable(S.Union(S.Struct({ a: S.Number }), S.Array(S.String)))))\n      .type.toBe<S.Schema<Array<string> | { a: number }, Array<string> | { a: number }>>()\n    S.mutable(S.Union(S.Struct({ a: S.Number }), S.Array(S.String)))\n    expect(S.asSchema(S.mutable(S.Array(S.String).pipe(S.maxItems(2)))))\n      .type.toBe<S.Schema<Array<string>>>()\n    expect(S.asSchema(S.mutable(S.NonEmptyArray(S.String).pipe(S.maxItems(2)))))\n      .type.toBe<S.Schema<[string, ...Array<string>], [string, ...Array<string>]>>()\n    expect(S.asSchema(S.mutable(S.suspend(() => S.Array(S.String)))))\n      .type.toBe<S.Schema<Array<string>>>()\n    S.mutable(S.suspend(() => S.Array(S.String)))\n    expect(\n      S.asSchema(S.mutable(S.transform(S.Array(S.String), S.Array(S.String), { decode: identity, encode: identity })))\n    )\n      .type.toBe<S.Schema<Array<string>>>()\n    S.mutable(S.transform(S.Array(S.String), S.Array(S.String), { decode: identity, encode: identity }))\n    expect(S.asSchema(S.extend(S.mutable(S.Struct({ a: S.String })), S.mutable(S.Struct({ b: S.Number })))))\n      .type.toBe<S.Schema<{ a: string } & { b: number }, { a: string } & { b: number }>>()\n    expect(S.asSchema(S.extend(S.mutable(S.Struct({ a: S.String })), S.Struct({ b: S.Number }))))\n      .type.toBe<S.Schema<{ a: string } & { readonly b: number }, { a: string } & { readonly b: number }>>()\n    expect(\n      S.asSchema(\n        S.extend(S.mutable(S.Struct({ a: S.String })), S.mutable(S.Record({ key: S.String, value: S.String })))\n      )\n    )\n      .type.toBe<S.Schema<{ a: string } & { [x: string]: string }, { a: string } & { [x: string]: string }>>()\n    expect(S.asSchema(S.extend(S.mutable(S.Struct({ a: S.String })), S.Record({ key: S.String, value: S.String }))))\n      .type.toBe<\n      S.Schema<\n        { a: string } & { readonly [x: string]: string },\n        { a: string } & { readonly [x: string]: string },\n        never\n      >\n    >()\n  })\n\n  it(\"transform\", () => {\n    const transform1 = S.String.pipe(\n      S.transform(S.Number, { decode: (s) => s.length, encode: (n) => String(n) })\n    )\n    expect(transform1.from).type.toBe<typeof S.String>()\n    expect(transform1.to).type.toBe<typeof S.Number>()\n    transform1.annotations({})\n    expect(S.asSchema(transform1))\n      .type.toBe<S.Schema<number, string>>()\n    expect(\n      S.asSchema(\n        S.String.pipe(S.transform(S.Number, { strict: false, decode: (s) => s, encode: (n) => n }))\n      )\n    ).type.toBe<S.Schema<number, string>>()\n    S.String.pipe(S.transform(S.Number, { strict: false, decode: (s) => s, encode: (n) => n }))\n    when(S.String.pipe).isCalledWith(\n      expect(S.transform).type.not.toBeCallableWith(S.Number, (s: any) => s, (n: any) => String(n))\n    )\n    when(S.String.pipe).isCalledWith(\n      expect(S.transform).type.not.toBeCallableWith(S.Number, (s: any) => s.length, (n: any) => n)\n    )\n\n    // should receive the fromI value other than the fromA value\n    S.transform(\n      S.Struct({\n        a: S.String,\n        b: S.NumberFromString\n      }),\n      S.Struct({\n        a: S.NumberFromString\n      }),\n      {\n        strict: true,\n        decode: ({ a, b }, i) => {\n          expect(a).type.toBe<string>()\n          expect(b).type.toBe<number>()\n          expect(i).type.toBe<{ readonly a: string; readonly b: string }>()\n          return { a: a + i.b }\n        },\n        encode: (i, a) => {\n          expect(i).type.toBe<{ readonly a: string }>()\n          expect(a).type.toBe<{ readonly a: number }>()\n          return { ...i, b: a.a * 2 }\n        }\n      }\n    )\n  })\n\n  it(\"transformOrFail\", () => {\n    const transformOrFail1 = S.String.pipe(\n      S.transformOrFail(\n        S.Number,\n        { decode: (s) => ParseResult.succeed(s.length), encode: (n) => ParseResult.succeed(String(n)) }\n      )\n    )\n    expect(transformOrFail1.from).type.toBe<typeof S.String>()\n    expect(transformOrFail1.to).type.toBe<typeof S.Number>()\n    transformOrFail1.annotations({})\n    expect(S.asSchema(transformOrFail1))\n      .type.toBe<S.Schema<number, string>>()\n    expect(\n      S.asSchema(\n        S.String.pipe(\n          S.transformOrFail(\n            S.Number,\n            { strict: false, decode: (s) => ParseResult.succeed(s), encode: (n) => ParseResult.succeed(String(n)) }\n          )\n        )\n      )\n    ).type.toBe<S.Schema<number, string>>()\n    S.String.pipe(\n      S.transformOrFail(\n        S.Number,\n        { strict: false, decode: (s) => ParseResult.succeed(s), encode: (n) => ParseResult.succeed(String(n)) }\n      )\n    )\n    when(S.String.pipe).isCalledWith(\n      expect(S.transformOrFail).type.not.toBeCallableWith(\n        S.Number,\n        (s: any) => ParseResult.succeed(s),\n        (n: any) => ParseResult.succeed(String(n))\n      )\n    )\n    when(S.String.pipe).isCalledWith(\n      expect(S.transformOrFail).type.not.toBeCallableWith(\n        S.Number,\n        (s: any) => ParseResult.succeed(s.length),\n        (n: any) => ParseResult.succeed(n)\n      )\n    )\n\n    // should receive the fromI value other than the fromA value\n    S.transformOrFail(\n      S.Struct({\n        a: S.String,\n        b: S.NumberFromString\n      }),\n      S.Struct({\n        a: S.NumberFromString\n      }),\n      {\n        strict: true,\n        decode: ({ a, b }, _options, _ast, i) => {\n          expect(a).type.toBe<string>()\n          expect(b).type.toBe<number>()\n          expect(i).type.toBe<{ readonly a: string; readonly b: string }>()\n          return ParseResult.succeed({ a: a + i.b })\n        },\n        encode: (i, _options, _ast, a) => {\n          expect(i).type.toBe<{ readonly a: string }>()\n          expect(a).type.toBe<{ readonly a: number }>()\n          return ParseResult.succeed({ ...i, b: a.a * 2 })\n        }\n      }\n    )\n  })\n\n  it(\"transformLiteral\", () => {\n    const schema = S.transformLiteral(0, \"a\")\n    expect(S.asSchema(schema)).type.toBe<S.Schema<\"a\", 0>>()\n    expect(schema).type.toBe<S.transformLiteral<\"a\", 0>>()\n    expect(schema.annotations({})).type.toBe<S.transformLiteral<\"a\", 0>>()\n    expect(schema.from).type.toBe<S.Literal<[0]>>()\n    expect(schema.to).type.toBe<S.Literal<[\"a\"]>>()\n  })\n\n  it(\"transformLiterals\", () => {\n    const schema = S.transformLiterals([0, \"a\"], [1, \"b\"])\n    expect(S.asSchema(schema)).type.toBe<S.Schema<\"a\" | \"b\", 0 | 1>>()\n    expect(schema).type.toBe<S.Union<[S.transformLiteral<\"a\", 0>, S.transformLiteral<\"b\", 1>]>>()\n    expect(schema.annotations({})).type.toBe<S.Union<[S.transformLiteral<\"a\", 0>, S.transformLiteral<\"b\", 1>]>>()\n\n    expect(S.transformLiterals([0, \"a\"])).type.toBe<S.transformLiteral<\"a\", 0>>()\n    const pairs = hole<Array<readonly [0 | 1, \"a\" | \"b\"]>>()\n    expect(S.transformLiterals(...pairs)).type.toBe<S.Schema<\"a\" | \"b\", 0 | 1>>()\n  })\n\n  it(\"propertySignature\", () => {\n    expect(S.propertySignature(S.String)).type.toBe<S.propertySignature<typeof S.String>>()\n    expect(S.propertySignature(S.String).annotations({})).type.toBe<S.propertySignature<typeof S.String>>()\n  })\n\n  it(\"PropertySignature.annotations\", () => {\n    expect(S.optional(S.String).annotations({})).type.toBe<S.optional<typeof S.String>>()\n  })\n\n  it(\"TaggedClass\", () => {\n    class MyTaggedClass extends S.TaggedClass<MyTaggedClass>()(\"MyTaggedClass\", {\n      a: S.String\n    }) {}\n    expect(hole<ConstructorParameters<typeof MyTaggedClass>>()).type.toBe<\n      [props: { readonly a: string }, options?: S.MakeOptions | undefined]\n    >()\n    expect(hole<S.Schema.Encoded<typeof MyTaggedClass>>()).type.toBe<\n      { readonly a: string; readonly _tag: \"MyTaggedClass\" }\n    >()\n    expect(hole<S.Schema.Type<typeof MyTaggedClass>>()).type.toBe<MyTaggedClass>()\n    class VoidTaggedClass extends S.TaggedClass<VoidTaggedClass>()(\"VoidTaggedClass\", {}) {}\n    expect(hole<ConstructorParameters<typeof VoidTaggedClass>>()).type.toBe<\n      [props?: void | {}, options?: S.MakeOptions | undefined]\n    >()\n    expect(S.asSchema(S.Struct(MyTaggedClass.fields)))\n      .type.toBe<\n      S.Schema<\n        { readonly a: string; readonly _tag: \"MyTaggedClass\" },\n        { readonly a: string; readonly _tag: \"MyTaggedClass\" },\n        never\n      >\n    >()\n    expect(hole<Parameters<S.Struct<typeof MyTaggedClass.fields>[\"make\"]>>()).type.toBe<\n      [props: { readonly a: string; readonly _tag?: \"MyTaggedClass\" }, options?: S.MakeOptions | undefined]\n    >()\n  })\n\n  it(\"TaggedError\", () => {\n    class MyTaggedError extends S.TaggedError<MyTaggedError>()(\"MyTaggedError\", {\n      a: S.String\n    }) {}\n    expect(S.asSchema(S.Struct(MyTaggedError.fields)))\n      .type.toBe<\n      S.Schema<\n        { readonly a: string; readonly _tag: \"MyTaggedError\" },\n        { readonly a: string; readonly _tag: \"MyTaggedError\" },\n        never\n      >\n    >()\n    expect(hole<Parameters<S.Struct<typeof MyTaggedError.fields>[\"make\"]>>()).type.toBe<\n      [props: { readonly a: string; readonly _tag?: \"MyTaggedError\" }, options?: S.MakeOptions | undefined]\n    >()\n  })\n\n  it(\"TaggedRequest\", () => {\n    class MyTaggedRequest extends S.TaggedRequest<MyTaggedRequest>()(\"MyTaggedRequest\", {\n      failure: S.String,\n      success: S.Number,\n      payload: { a: S.String }\n    }) {}\n    expect(S.asSchema(S.Struct(MyTaggedRequest.fields)))\n      .type.toBe<\n      S.Schema<\n        { readonly a: string; readonly _tag: \"MyTaggedRequest\" },\n        { readonly a: string; readonly _tag: \"MyTaggedRequest\" },\n        never\n      >\n    >()\n    expect(hole<Parameters<S.Struct<typeof MyTaggedRequest.fields>[\"make\"]>>()).type.toBe<\n      [props: { readonly a: string; readonly _tag?: \"MyTaggedRequest\" }, options?: S.MakeOptions | undefined]\n    >()\n  })\n\n  it(\"TypeLiteral\", () => {\n    expect(S.asSchema(hole<S.TypeLiteral<{ a: typeof S.String }, []>>()))\n      .type.toBe<S.Schema<{ readonly a: string }, { readonly a: string }>>()\n    expect(S.asSchema(hole<S.TypeLiteral<{}, [{ key: typeof S.String; value: typeof S.Unknown }]>>()))\n      .type.toBe<S.Schema<{ readonly [x: string]: unknown }, { readonly [x: string]: unknown }>>()\n    expect(\n      S.asSchema(\n        hole<\n          S.TypeLiteral<\n            {},\n            [{ key: typeof S.String; value: typeof S.String }, { key: typeof S.Symbol; value: typeof S.Number }]\n          >\n        >()\n      )\n    ).type.toBe<\n      S.Schema<\n        { readonly [x: string]: string; readonly [x: symbol]: number },\n        { readonly [x: string]: never },\n        never\n      >\n    >()\n    expect(\n      S.asSchema(hole<S.TypeLiteral<{ a: typeof S.String }, [{ key: typeof S.String; value: typeof S.Unknown }]>>())\n    )\n      .type.toBe<\n      S.Schema<\n        { readonly [x: string]: unknown; readonly a: string },\n        { readonly [x: string]: unknown; readonly a: string },\n        never\n      >\n    >()\n  })\n\n  it(\"withConstructorDefault\", () => {\n    when(S.propertySignature(S.String).pipe).isCalledWith(\n      expect(S.withConstructorDefault).type.not.toBeCallableWith(() => 1)\n    )\n    expect(S.propertySignature(S.String).pipe(S.withConstructorDefault(() => \"a\")))\n      .type.toBe<S.PropertySignature<\":\", string, never, \":\", string, true>>()\n    expect(S.withConstructorDefault(S.propertySignature(S.String), () => \"a\"))\n      .type.toBe<S.PropertySignature<\":\", string, never, \":\", string, true>>()\n  })\n\n  it(\"withDecodingDefault\", () => {\n    when(S.Struct).isCalledWith({\n      a: when(S.optional(S.String).pipe).isCalledWith(\n        S.withConstructorDefault(() => undefined),\n        expect(S.withDecodingDefault).type.not.toBeCallableWith(() => \"\")\n      )\n    })\n    when(S.Struct).isCalledWith({\n      a: when(S.optional(S.String).pipe).isCalledWith(\n        expect(S.withDecodingDefault).type.not.toBeCallableWith(() => undefined)\n      )\n    })\n    expect(\n      S.asSchema(S.Struct({ a: S.optional(S.String).pipe(S.withDecodingDefault(() => \"\")) }))\n    ).type.toBe<\n      S.Schema<{ readonly a: string }, { readonly a?: string | undefined }>\n    >()\n    expect(S.Struct({ a: S.optional(S.String).pipe(S.withDecodingDefault(() => \"\")) }))\n      .type.toBe<S.Struct<{ a: S.PropertySignature<\":\", string, never, \"?:\", string | undefined, false> }>>()\n  })\n\n  it(\"withDefaults\", () => {\n    when(S.Struct).isCalledWith({\n      a: when(S.optional(S.String).pipe).isCalledWith(\n        expect(S.withDefaults).type.not.toBeCallableWith({\n          decoding: () => undefined,\n          constructor: () => undefined\n        })\n      )\n    })\n    expect(\n      S.asSchema(\n        S.Struct({ a: S.optional(S.String).pipe(S.withDefaults({ decoding: () => \"\", constructor: () => \"\" })) })\n      )\n    ).type.toBe<\n      S.Schema<{ readonly a: string }, { readonly a?: string | undefined }>\n    >()\n    expect(\n      S.Struct({ a: S.optional(S.String).pipe(S.withDefaults({ decoding: () => \"\", constructor: () => \"\" })) })\n    ).type.toBe<S.Struct<{ a: S.PropertySignature<\":\", string, never, \"?:\", string | undefined, true> }>>()\n    const make4 =\n      S.Struct({ a: S.optional(S.String).pipe(S.withDefaults({ decoding: () => \"\", constructor: () => \"\" })) }).make\n    expect(hole<Parameters<typeof make4>[0]>()).type.toBe<void | { readonly a?: string } | undefined>()\n  })\n\n  it(\"Schema.AsSchema\", () => {\n    const MyStruct = <X extends S.Schema.All>(x: X) => S.Struct({ x })\n    type MyStructReturnType<X extends S.Schema.All> = S.Schema.Type<ReturnType<typeof MyStruct<X>>>\n    function _AsSchemaTest1<X extends S.Schema.All>(obj: MyStructReturnType<S.Schema.AsSchema<X>>) {\n      expect(obj.x).type.toBe<S.Schema.Type<X>>()\n    }\n    type XStruct<X extends S.Schema.All> = S.Schema<\n      S.Struct.Type<{\n        expectedVersion: typeof S.Number\n        props: X\n      }>,\n      S.Struct.Encoded<{\n        expectedVersion: typeof S.Number\n        props: X\n      }>\n    >\n    const _AsSchemaTest2 = <X extends S.Schema.All>(\n      domainEvent: S.Schema.Type<XStruct<S.Schema.AsSchema<X>>>\n    ) => {\n      expect(domainEvent.expectedVersion).type.toBe<number>()\n      expect(domainEvent.props).type.toBe<S.Schema.Type<X>>()\n    }\n  })\n\n  it(\"Schema.is\", () => {\n    expect(hole<Array<string | number>>().filter(S.is(S.String)))\n      .type.toBe<Array<string>>()\n    expect(hole<Array<string | number>>().find(S.is(S.String)))\n      .type.toBe<string | undefined>()\n  })\n\n  it(\"TaggedStruct\", () => {\n    expect(S.tag(\"A\")).type.toBe<S.tag<\"A\">>()\n    const MyTaggedStruct = S.TaggedStruct(\"Product\", {\n      category: S.tag(\"Electronics\"),\n      name: S.String,\n      price: S.Number\n    })\n    expect(S.asSchema(MyTaggedStruct))\n      .type.toBe<\n      S.Schema<\n        { readonly _tag: \"Product\"; readonly name: string; readonly category: \"Electronics\"; readonly price: number },\n        { readonly _tag: \"Product\"; readonly name: string; readonly category: \"Electronics\"; readonly price: number },\n        never\n      >\n    >()\n    expect(hole<Parameters<typeof MyTaggedStruct[\"make\"]>>()).type.toBe<\n      [\n        props: {\n          readonly _tag?: \"Product\"\n          readonly name: string\n          readonly category?: \"Electronics\"\n          readonly price: number\n        },\n        options?: S.MakeOptions | undefined\n      ]\n    >()\n  })\n\n  describe(\"Optional Primitives\", () => {\n    it(\"optionalToOptional\", () => {\n      expect(\n        S.asSchema(S.Struct({ a: S.optionalToOptional(aContext, S.String, { decode: (o) => o, encode: (o) => o }) }))\n      ).type.toBe<S.Schema<{ readonly a?: string }, { readonly a?: string }, \"a\">>()\n      expect(\n        S.Struct({ a: S.optionalToOptional(aContext, S.String, { decode: (o) => o, encode: (o) => o }) })\n      ).type.toBe<S.Struct<{ a: S.PropertySignature<\"?:\", string, never, \"?:\", string, false, \"a\"> }>>()\n    })\n\n    it(\"optionalToRequired\", () => {\n      expect(\n        S.asSchema(\n          S.Struct({\n            a: S.optionalToRequired(aContext, S.String, { decode: Option.getOrElse(() => \"\"), encode: Option.some })\n          })\n        )\n      ).type.toBe<S.Schema<{ readonly a: string }, { readonly a?: string }, \"a\">>()\n      expect(\n        S.Struct({\n          a: S.optionalToRequired(aContext, S.String, { decode: Option.getOrElse(() => \"\"), encode: Option.some })\n        })\n      ).type.toBe<S.Struct<{ a: S.PropertySignature<\":\", string, never, \"?:\", string, false, \"a\"> }>>()\n    })\n\n    it(\"requiredToOptional\", () => {\n      expect(\n        S.asSchema(\n          S.Struct({\n            a: S.requiredToOptional(aContext, S.String, { decode: Option.some, encode: Option.getOrElse(() => \"\") })\n          })\n        )\n      ).type.toBe<S.Schema<{ readonly a?: string }, { readonly a: string }, \"a\">>()\n      expect(\n        S.Struct({\n          a: S.requiredToOptional(aContext, S.String, { decode: Option.some, encode: Option.getOrElse(() => \"\") })\n        })\n      ).type.toBe<S.Struct<{ a: S.PropertySignature<\"?:\", string, never, \":\", string, false, \"a\"> }>>()\n    })\n  })\n\n  it(\"TemplateLiteralParser\", () => {\n    expect(S.asSchema(S.TemplateLiteralParser(\"a\")))\n      .type.toBe<S.Schema<readonly [\"a\"], \"a\">>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Literal(\"a\"))))\n      .type.toBe<S.Schema<readonly [\"a\"], \"a\">>()\n    expect(S.asSchema(S.TemplateLiteralParser(1)))\n      .type.toBe<S.Schema<readonly [1], \"1\">>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Literal(1))))\n      .type.toBe<S.Schema<readonly [1], \"1\">>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String)))\n      .type.toBe<S.Schema<readonly [string], string>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Number)))\n      .type.toBe<S.Schema<readonly [number], `${number}`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(\"a\", \"b\")))\n      .type.toBe<S.Schema<readonly [\"a\", \"b\"], \"ab\">>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Literal(\"a\"), S.Literal(\"b\"))))\n      .type.toBe<S.Schema<readonly [\"a\", \"b\"], \"ab\">>()\n    expect(S.asSchema(S.TemplateLiteralParser(\"a\", S.String)))\n      .type.toBe<S.Schema<readonly [\"a\", string], `a${string}`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Literal(\"a\"), S.String)))\n      .type.toBe<S.Schema<readonly [\"a\", string], `a${string}`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(\"a\", S.Number)))\n      .type.toBe<S.Schema<readonly [\"a\", number], `a${number}`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Literal(\"a\"), S.Number)))\n      .type.toBe<S.Schema<readonly [\"a\", number], `a${number}`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String, \"a\")))\n      .type.toBe<S.Schema<readonly [string, \"a\"], `${string}a`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String, S.Literal(\"a\"))))\n      .type.toBe<S.Schema<readonly [string, \"a\"], `${string}a`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Number, \"a\")))\n      .type.toBe<S.Schema<readonly [number, \"a\"], `${number}a`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Number, S.Literal(\"a\"))))\n      .type.toBe<S.Schema<readonly [number, \"a\"], `${number}a`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String, 0)))\n      .type.toBe<S.Schema<readonly [string, 0], `${string}0`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String, true)))\n      .type.toBe<S.Schema<readonly [string, true], `${string}true`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String, null)))\n      .type.toBe<S.Schema<readonly [string, null], `${string}null`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String, 1n)))\n      .type.toBe<S.Schema<readonly [string, 1n], `${string}1`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String, S.Literal(\"a\", 0))))\n      .type.toBe<S.Schema<readonly [string, 0 | \"a\"], `${string}a` | `${string}0`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String, S.Literal(\"/\"), S.Number)))\n      .type.toBe<S.Schema<readonly [string, \"/\", number], `${string}/${number}`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String, \"/\", S.Number)))\n      .type.toBe<S.Schema<readonly [string, \"/\", number], `${string}/${number}`>>()\n    const EmailLocaleIDs = S.Literal(\"welcome_email\", \"email_heading\")\n    const FooterLocaleIDs = S.Literal(\"footer_title\", \"footer_sendoff\")\n    expect(S.asSchema(S.TemplateLiteralParser(S.Union(EmailLocaleIDs, FooterLocaleIDs), S.Literal(\"_id\"))))\n      .type.toBe<\n      S.Schema<\n        readonly [\"welcome_email\" | \"email_heading\" | \"footer_title\" | \"footer_sendoff\", \"_id\"],\n        \"welcome_email_id\" | \"email_heading_id\" | \"footer_title_id\" | \"footer_sendoff_id\",\n        never\n      >\n    >()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Union(EmailLocaleIDs, FooterLocaleIDs), \"_id\")))\n      .type.toBe<\n      S.Schema<\n        readonly [\"welcome_email\" | \"email_heading\" | \"footer_title\" | \"footer_sendoff\", \"_id\"],\n        \"welcome_email_id\" | \"email_heading_id\" | \"footer_title_id\" | \"footer_sendoff_id\",\n        never\n      >\n    >()\n    expect(S.asSchema(S.TemplateLiteralParser(S.String.pipe(S.brand(\"MyBrand\")))))\n      .type.toBe<S.Schema<readonly [string & Brand.Brand<\"MyBrand\">], string>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Number.pipe(S.brand(\"MyBrand\")))))\n      .type.toBe<S.Schema<readonly [number & Brand.Brand<\"MyBrand\">], `${number}`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(\"a\", S.String.pipe(S.brand(\"MyBrand\")))))\n      .type.toBe<S.Schema<readonly [\"a\", string & Brand.Brand<\"MyBrand\">], `a${string}`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Literal(\"a\"), S.String.pipe(S.brand(\"MyBrand\")))))\n      .type.toBe<S.Schema<readonly [\"a\", string & Brand.Brand<\"MyBrand\">], `a${string}`>>()\n    expect(\n      S.asSchema(\n        S.TemplateLiteralParser(S.Literal(\"a\").pipe(S.brand(\"L\")), S.String.pipe(S.brand(\"MyBrand\")))\n      )\n    ).type.toBe<\n      S.Schema<readonly [(\"a\" & Brand.Brand<\"L\">), string & Brand.Brand<\"MyBrand\">], `a${string}`>\n    >()\n    expect(S.asSchema(S.TemplateLiteralParser(\"a\", S.Number.pipe(S.brand(\"MyBrand\")))))\n      .type.toBe<S.Schema<readonly [\"a\", number & Brand.Brand<\"MyBrand\">], `a${number}`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(S.Literal(\"a\"), S.Number.pipe(S.brand(\"MyBrand\")))))\n      .type.toBe<S.Schema<readonly [\"a\", number & Brand.Brand<\"MyBrand\">], `a${number}`>>()\n    expect(S.asSchema(S.TemplateLiteralParser(\"a\", S.Union(S.Number, S.String))))\n      .type.toBe<S.Schema<readonly [\"a\", string | number], `a${string}` | `a${number}`>>()\n  })\n\n  describe(\"Filters\", () => {\n    it(\"filter\", () => {\n      S.String.pipe(S.filter((s, options, ast) => {\n        expect(s).type.toBe<string>()\n        expect(options).type.toBe<SchemaAST.ParseOptions>()\n        expect(ast).type.toBe<SchemaAST.Refinement>()\n        return undefined\n      }))\n      const predicateFilter1 = (u: unknown): boolean => typeof u === \"string\"\n      const FromFilter = S.Union(S.String, S.Number)\n      expect(pipe(FromFilter, S.filter(predicateFilter1)))\n        .type.toBe<S.filter<S.Union<[typeof S.String, typeof S.Number]>>>()\n      const FromRefinement = S.Struct({\n        a: S.optionalWith(S.String, { exact: true }),\n        b: S.optionalWith(S.Number, { exact: true })\n      })\n      expect(pipe(FromRefinement, S.filter(S.is(S.Struct({ b: S.Number })))))\n        .type.toBe<\n        S.refine<\n          { readonly a?: string; readonly b?: number } & { readonly b: number },\n          S.Schema<unknown, { readonly a?: string; readonly b?: number }>\n        >\n      >()\n      const LiteralFilter = S.Literal(\"a\", \"b\")\n      const predicateFilter2 = (u: unknown): u is \"a\" => typeof u === \"string\" && u === \"a\"\n      expect(pipe(LiteralFilter, S.filter(predicateFilter2)))\n        .type.toBe<S.refine<\"a\", S.Schema<unknown, \"a\" | \"b\">>>()\n      expect(pipe(LiteralFilter, S.filter(S.is(S.Literal(\"a\")))))\n        .type.toBe<S.refine<\"a\", S.Schema<unknown, \"a\" | \"b\">>>()\n      expect(pipe(LiteralFilter, S.filter(S.is(S.Literal(\"c\")))))\n        .type.toBe<S.refine<never, S.Schema<unknown, \"a\" | \"b\">>>()\n      const UnionFilter = hole<\n        S.Schema<\n          { readonly a: string } | { readonly b: string },\n          { readonly a: string } | { readonly b: string },\n          never\n        >\n      >()\n      expect(pipe(UnionFilter, S.filter(S.is(S.Struct({ b: S.String })))))\n        .type.toBe<\n        S.refine<\n          ({ readonly a: string } | { readonly b: string }) & { readonly b: string },\n          S.Schema<unknown, { readonly a: string } | { readonly b: string }>\n        >\n      >()\n      expect(pipe(S.Number, S.filter((n): n is number & Brand.Brand<\"MyNumber\"> => n > 0)))\n        .type.toBe<S.refine<number & Brand.Brand<\"MyNumber\">, S.Schema<number>>>()\n      // annotations\n      pipe(\n        S.String,\n        S.filter(\n          (s) => {\n            expect(s).type.toBe<string>()\n            return true\n          },\n          {\n            arbitrary: (from, ctx) => (fc) => {\n              expect(from).type.toBe<Arbitrary.LazyArbitrary<string>>()\n              expect(ctx).type.toBe<Arbitrary.ArbitraryGenerationContext>()\n              return fc.string()\n            },\n            pretty: (from) => (s) => {\n              expect(from).type.toBe<Pretty.Pretty<string>>()\n              expect(s).type.toBe<string>()\n              return s\n            },\n            equivalence: (from) => (a, b) => {\n              expect(from).type.toBe<Equivalence.Equivalence<string>>()\n              expect(a).type.toBe<string>()\n              expect(b).type.toBe<string>()\n              return true\n            }\n          }\n        )\n      )\n      pipe(\n        S.String,\n        S.filter((s) => {\n          expect(s).type.toBe<string>()\n          return true\n        })\n      ).annotations({\n        arbitrary: (...x) => (fc) => {\n          expect(x).type.toBe<Array<any>>()\n          return fc.string()\n        },\n        pretty: (...x) => (s) => {\n          expect(x).type.toBe<Array<any>>()\n          return s\n        },\n        equivalence: (...x) => (a, b) => {\n          expect(x).type.toBe<Array<any>>()\n          expect(a).type.toBe<string>()\n          expect(b).type.toBe<string>()\n          return true\n        }\n      })\n    })\n\n    describe(\"String Filters\", () => {\n      it(\"maxLength\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.maxLength).type.not.toBeCallableWith(5))\n        // should allow generic context\n        const _f1 = <A extends string>(schema: S.Schema<A>) => schema.pipe(S.maxLength(5))\n        const _f2 = <A extends string>(schema: S.Schema<A>) =>\n          when(schema.pipe).isCalledWith(\n            expect(S.greaterThan).type.not.toBeCallableWith(5)\n          )\n        // should allow string subtypes\n        pipe(\n          S.TemplateLiteral(\"a\", S.String),\n          S.maxLength(5, {\n            pretty: () => (s) => {\n              expect(s).type.toBe<`a${string}`>()\n              return \"-\"\n            }\n          })\n        )\n\n        const schema = pipe(\n          S.String,\n          S.maxLength(5, {\n            pretty: () => (s) => {\n              expect(s).type.toBe<string>()\n              return \"-\"\n            }\n          })\n        )\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"minLength\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.minLength).type.not.toBeCallableWith(5))\n\n        const schema = pipe(S.String, S.minLength(5))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"length\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.length).type.not.toBeCallableWith(5))\n\n        const schema = pipe(S.String, S.length(5))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"pattern\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.pattern).type.not.toBeCallableWith(/a/))\n\n        const schema = pipe(S.String, S.pattern(/a/))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"startsWith\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.startsWith).type.not.toBeCallableWith(\"a\"))\n\n        const schema = pipe(S.String, S.startsWith(\"a\"))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"endsWith\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.endsWith).type.not.toBeCallableWith(\"a\"))\n\n        const schema = pipe(S.String, S.endsWith(\"a\"))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"includes\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.includes).type.not.toBeCallableWith(\"a\"))\n\n        const schema = pipe(S.String, S.includes(\"a\"))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"lowercased\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lowercased).type.not.toBeCallableWith())\n\n        const schema = pipe(S.String, S.lowercased())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"uppercased\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.uppercased).type.not.toBeCallableWith())\n\n        const schema = pipe(S.String, S.uppercased())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"capitalized\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.capitalized).type.not.toBeCallableWith())\n\n        const schema = pipe(S.String, S.capitalized())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"uncapitalized\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.uncapitalized).type.not.toBeCallableWith())\n\n        const schema = pipe(S.String, S.uncapitalized())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"nonEmptyString\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.nonEmptyString).type.not.toBeCallableWith())\n\n        const schema = pipe(S.String, S.nonEmptyString())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n\n      it(\"trimmed\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.trimmed).type.not.toBeCallableWith())\n\n        const schema = pipe(S.String, S.trimmed())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<string>>()\n        expect(schema).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.String>>()\n        expect(schema.from).type.toBe<typeof S.String>()\n      })\n    })\n\n    describe(\"Number Filters\", () => {\n      it(\"finite\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.finite).type.not.toBeCallableWith())\n\n        const schema = pipe(S.Number, S.finite())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"greaterThan\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.greaterThan).type.not.toBeCallableWith(5))\n\n        const schema = pipe(S.Number, S.greaterThan(5))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"greaterThanOrEqualTo\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.greaterThanOrEqualTo).type.not.toBeCallableWith(5))\n\n        const schema = pipe(S.Number, S.greaterThanOrEqualTo(5))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"lessThan\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lessThan).type.not.toBeCallableWith(5))\n\n        const schema = pipe(S.Number, S.lessThan(5))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"lessThanOrEqualTo\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lessThanOrEqualTo).type.not.toBeCallableWith(5))\n\n        const schema = pipe(S.Number, S.lessThanOrEqualTo(5))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"int\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.int).type.not.toBeCallableWith())\n\n        const schema = pipe(S.Number, S.int())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"multipleOf\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.multipleOf).type.not.toBeCallableWith(5))\n\n        const schema = pipe(S.Number, S.multipleOf(5))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"between\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.between).type.not.toBeCallableWith(1, 5))\n\n        const schema = pipe(S.Number, S.between(1, 5))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"nonNaN\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.nonNaN).type.not.toBeCallableWith())\n\n        const schema = pipe(S.Number, S.nonNaN())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"positive\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.positive).type.not.toBeCallableWith())\n\n        const schema = pipe(S.Number, S.positive())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"negative\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.negative).type.not.toBeCallableWith())\n\n        const schema = pipe(S.Number, S.negative())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"nonPositive\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.nonPositive).type.not.toBeCallableWith())\n\n        const schema = pipe(S.Number, S.nonPositive())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n\n      it(\"nonNegative\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.nonNegative).type.not.toBeCallableWith())\n\n        const schema = pipe(S.Number, S.nonNegative())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n        expect(schema).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.Number>>()\n        expect(schema.from).type.toBe<typeof S.Number>()\n      })\n    })\n\n    describe(\"BigInt Filters\", () => {\n      it(\"greaterThanBigInt\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.greaterThanBigInt).type.not.toBeCallableWith(5n))\n\n        const schema = pipe(S.BigIntFromSelf, S.greaterThanBigInt(5n))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<bigint>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigIntFromSelf>()\n      })\n\n      it(\"greaterThanOrEqualToBigInt\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.greaterThanOrEqualToBigInt).type.not.toBeCallableWith(5n))\n\n        const schema = pipe(S.BigIntFromSelf, S.greaterThanOrEqualToBigInt(5n))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<bigint>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigIntFromSelf>()\n      })\n\n      it(\"lessThanBigInt\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lessThanBigInt).type.not.toBeCallableWith(5n))\n\n        const schema = pipe(S.BigIntFromSelf, S.lessThanBigInt(5n))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<bigint>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigIntFromSelf>()\n      })\n\n      it(\"lessThanOrEqualToBigInt\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lessThanOrEqualToBigInt).type.not.toBeCallableWith(5n))\n\n        const schema = pipe(S.BigIntFromSelf, S.lessThanOrEqualToBigInt(5n))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<bigint>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigIntFromSelf>()\n      })\n\n      it(\"betweenBigInt\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.betweenBigInt).type.not.toBeCallableWith(1n, 5n))\n\n        const schema = pipe(S.BigIntFromSelf, S.betweenBigInt(1n, 5n))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<bigint>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigIntFromSelf>()\n      })\n\n      it(\"positiveBigInt\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.positiveBigInt).type.not.toBeCallableWith())\n\n        const schema = pipe(S.BigIntFromSelf, S.positiveBigInt())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<bigint>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigIntFromSelf>()\n      })\n\n      it(\"negativeBigInt\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.negativeBigInt).type.not.toBeCallableWith())\n\n        const schema = pipe(S.BigIntFromSelf, S.negativeBigInt())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<bigint>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigIntFromSelf>()\n      })\n\n      it(\"nonNegativeBigInt\", () => {\n        expect(pipe).type.not.toBeCallableWith(S.Null, S.nonNegativeBigInt())\n\n        const schema = pipe(S.BigIntFromSelf, S.nonNegativeBigInt())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<bigint>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigIntFromSelf>()\n      })\n\n      it(\"nonPositiveBigInt\", () => {\n        expect(pipe).type.not.toBeCallableWith(S.Null, S.negativeBigInt())\n\n        const schema = pipe(S.BigIntFromSelf, S.nonPositiveBigInt())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<bigint>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigIntFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigIntFromSelf>()\n      })\n    })\n\n    describe(\"Duration filters\", () => {\n      it(\"lessThanDuration\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lessThanDuration).type.not.toBeCallableWith(\"10 millis\"))\n\n        const schema = pipe(S.DurationFromSelf, S.lessThanDuration(\"10 millis\"))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Duration.Duration>>()\n        expect(schema).type.toBe<S.filter<typeof S.DurationFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DurationFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DurationFromSelf>()\n      })\n\n      it(\"lessThanOrEqualToDuration\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lessThanOrEqualToDuration).type.not.toBeCallableWith(\"10 millis\"))\n\n        const schema = pipe(S.DurationFromSelf, S.lessThanOrEqualToDuration(\"10 millis\"))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Duration.Duration>>()\n        expect(schema).type.toBe<S.filter<typeof S.DurationFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DurationFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DurationFromSelf>()\n      })\n\n      it(\"greaterThanDuration\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.greaterThanDuration).type.not.toBeCallableWith(\"10 millis\"))\n\n        const schema = pipe(S.DurationFromSelf, S.greaterThanDuration(\"10 millis\"))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Duration.Duration>>()\n        expect(schema).type.toBe<S.filter<typeof S.DurationFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DurationFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DurationFromSelf>()\n      })\n\n      it(\"greaterThanOrEqualToDuration\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.greaterThanOrEqualToDuration).type.not.toBeCallableWith(\"10 millis\"))\n\n        const schema = pipe(S.DurationFromSelf, S.greaterThanOrEqualToDuration(\"10 millis\"))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Duration.Duration>>()\n        expect(schema).type.toBe<S.filter<typeof S.DurationFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DurationFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DurationFromSelf>()\n      })\n\n      it(\"betweenDuration\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.betweenDuration).type.not.toBeCallableWith(\"10 millis\", \"50 millis\"))\n\n        const schema = pipe(S.DurationFromSelf, S.betweenDuration(\"10 millis\", \"50 millis\"))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Duration.Duration>>()\n        expect(schema).type.toBe<S.filter<typeof S.DurationFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DurationFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DurationFromSelf>()\n      })\n    })\n\n    describe(\"Array Filters\", () => {\n      describe(\"Array\", () => {\n        it(\"minItems\", () => {\n          when(pipe).isCalledWith(S.Null, expect(S.minItems).type.not.toBeCallableWith(2))\n\n          const schema = S.Array(S.String).pipe(S.minItems(2))\n          expect(S.asSchema(schema)).type.toBe<S.Schema<ReadonlyArray<string>>>()\n          expect(schema).type.toBe<S.filter<S.Array$<typeof S.String>>>()\n          expect(schema.annotations({})).type.toBe<S.filter<S.Array$<typeof S.String>>>()\n          expect(schema.from).type.toBe<S.Array$<typeof S.String>>()\n        })\n\n        it(\"maxItems\", () => {\n          when(pipe).isCalledWith(S.Null, expect(S.maxItems).type.not.toBeCallableWith(2))\n\n          const schema = S.Array(S.String).pipe(S.maxItems(2))\n          expect(S.asSchema(schema)).type.toBe<S.Schema<ReadonlyArray<string>>>()\n          expect(schema).type.toBe<S.filter<S.Array$<typeof S.String>>>()\n          expect(schema.annotations({})).type.toBe<S.filter<S.Array$<typeof S.String>>>()\n          expect(schema.from).type.toBe<S.Array$<typeof S.String>>()\n        })\n\n        it(\"itemsCount\", () => {\n          when(pipe).isCalledWith(S.Null, expect(S.itemsCount).type.not.toBeCallableWith(2))\n\n          const schema = S.Array(S.String).pipe(S.itemsCount(2))\n          expect(S.asSchema(schema)).type.toBe<S.Schema<ReadonlyArray<string>>>()\n          expect(schema).type.toBe<S.filter<S.Array$<typeof S.String>>>()\n          expect(schema.annotations({})).type.toBe<S.filter<S.Array$<typeof S.String>>>()\n          expect(schema.from).type.toBe<S.Array$<typeof S.String>>()\n        })\n      })\n\n      describe(\"NonEmptyArray\", () => {\n        it(\"minItems\", () => {\n          const schema = S.NonEmptyArray(S.String).pipe(S.minItems(2))\n          expect(S.asSchema(schema)).type.toBe<S.Schema<readonly [string, ...Array<string>]>>()\n          expect(schema).type.toBe<S.filter<S.NonEmptyArray<typeof S.String>>>()\n          expect(schema.annotations({})).type.toBe<S.filter<S.NonEmptyArray<typeof S.String>>>()\n          expect(schema.from).type.toBe<S.NonEmptyArray<typeof S.String>>()\n        })\n\n        it(\"maxItems\", () => {\n          const schema = S.NonEmptyArray(S.String).pipe(S.maxItems(2))\n          expect(S.asSchema(schema)).type.toBe<S.Schema<readonly [string, ...Array<string>]>>()\n          expect(schema).type.toBe<S.filter<S.NonEmptyArray<typeof S.String>>>()\n          expect(schema.annotations({})).type.toBe<S.filter<S.NonEmptyArray<typeof S.String>>>()\n          expect(schema.from).type.toBe<S.NonEmptyArray<typeof S.String>>()\n        })\n\n        it(\"itemsCount\", () => {\n          const schema = S.NonEmptyArray(S.String).pipe(S.itemsCount(2))\n          expect(S.asSchema(schema)).type.toBe<S.Schema<readonly [string, ...Array<string>]>>()\n          expect(schema).type.toBe<S.filter<S.NonEmptyArray<typeof S.String>>>()\n          expect(schema.annotations({})).type.toBe<S.filter<S.NonEmptyArray<typeof S.String>>>()\n          expect(schema.from).type.toBe<S.NonEmptyArray<typeof S.String>>()\n        })\n      })\n    })\n\n    describe(\"Date Filters\", () => {\n      it(\"validDate\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.validDate).type.not.toBeCallableWith())\n\n        const schema = pipe(S.DateFromSelf, S.validDate())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Date>>()\n        expect(schema).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DateFromSelf>()\n      })\n\n      it(\"lessThanDate\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lessThanDate).type.not.toBeCallableWith(new Date()))\n\n        const schema = pipe(S.DateFromSelf, S.lessThanDate(new Date()))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Date>>()\n        expect(schema).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DateFromSelf>()\n      })\n\n      it(\"lessThanOrEqualToDate\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lessThanOrEqualToDate).type.not.toBeCallableWith(new Date()))\n\n        const schema = pipe(S.DateFromSelf, S.lessThanOrEqualToDate(new Date()))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Date>>()\n        expect(schema).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DateFromSelf>()\n      })\n\n      it(\"greaterThanDate\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.greaterThanDate).type.not.toBeCallableWith(new Date()))\n\n        const schema = pipe(S.DateFromSelf, S.greaterThanDate(new Date()))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Date>>()\n        expect(schema).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DateFromSelf>()\n      })\n\n      it(\"greaterThanOrEqualToDate\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.greaterThanOrEqualToDate).type.not.toBeCallableWith(new Date()))\n\n        const schema = pipe(S.DateFromSelf, S.greaterThanOrEqualToDate(new Date()))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Date>>()\n        expect(schema).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DateFromSelf>()\n      })\n\n      it(\"betweenDate\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.betweenDate).type.not.toBeCallableWith(new Date(0), new Date(100)))\n\n        const schema = pipe(S.DateFromSelf, S.betweenDate(new Date(0), new Date(100)))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<Date>>()\n        expect(schema).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.DateFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.DateFromSelf>()\n      })\n    })\n\n    describe(\"BigDecimal Filters\", () => {\n      const bd = hole<BigDecimal.BigDecimal>()\n\n      it(\"greaterThanBigDecimal\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.greaterThanBigDecimal).type.not.toBeCallableWith(bd))\n\n        const schema = pipe(S.BigDecimalFromSelf, S.greaterThanBigDecimal(bd))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigDecimalFromSelf>()\n      })\n\n      it(\"greaterThanOrEqualToBigDecimal\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.greaterThanOrEqualToBigDecimal).type.not.toBeCallableWith(bd))\n\n        const schema = pipe(S.BigDecimalFromSelf, S.greaterThanOrEqualToBigDecimal(bd))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigDecimalFromSelf>()\n      })\n\n      it(\"lessThanBigDecimal\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lessThanBigDecimal).type.not.toBeCallableWith(bd))\n\n        const schema = pipe(S.BigDecimalFromSelf, S.lessThanBigDecimal(bd))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigDecimalFromSelf>()\n      })\n\n      it(\"lessThanOrEqualToBigDecimal\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.lessThanOrEqualToBigDecimal).type.not.toBeCallableWith(bd))\n\n        const schema = pipe(S.BigDecimalFromSelf, S.lessThanOrEqualToBigDecimal(bd))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigDecimalFromSelf>()\n      })\n\n      it(\"positiveBigDecimal\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.positiveBigDecimal).type.not.toBeCallableWith())\n\n        const schema = pipe(S.BigDecimalFromSelf, S.positiveBigDecimal())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigDecimalFromSelf>()\n      })\n\n      it(\"nonNegativeBigDecimal\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.nonNegativeBigDecimal).type.not.toBeCallableWith())\n\n        const schema = pipe(S.BigDecimalFromSelf, S.nonNegativeBigDecimal())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigDecimalFromSelf>()\n      })\n\n      it(\"negativeBigDecimal\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.negativeBigDecimal).type.not.toBeCallableWith())\n\n        const schema = pipe(S.BigDecimalFromSelf, S.negativeBigDecimal())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigDecimalFromSelf>()\n      })\n\n      it(\"nonPositiveBigDecimal\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.nonPositiveBigDecimal).type.not.toBeCallableWith())\n\n        const schema = pipe(S.BigDecimalFromSelf, S.nonPositiveBigDecimal())\n        expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigDecimalFromSelf>()\n      })\n\n      it(\"betweenBigDecimal\", () => {\n        when(pipe).isCalledWith(S.Null, expect(S.betweenBigDecimal).type.not.toBeCallableWith(bd, bd))\n\n        const schema = pipe(S.BigDecimalFromSelf, S.betweenBigDecimal(bd, bd))\n        expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n        expect(schema).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.annotations({})).type.toBe<S.filter<typeof S.BigDecimalFromSelf>>()\n        expect(schema.from).type.toBe<typeof S.BigDecimalFromSelf>()\n      })\n    })\n  })\n\n  describe(\"Data Types\", () => {\n    it(\"Uint8ArrayFromSelf\", () => {\n      const schema = S.Uint8ArrayFromSelf\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Uint8Array>>()\n      expect(schema).type.toBe<typeof S.Uint8ArrayFromSelf>()\n      // TODO: should be typeof S.Uint8ArrayFromSelf\n      expect(schema.annotations({})).type.toBe<S.declare<Uint8Array>>()\n    })\n\n    it(\"DateFromSelf\", () => {\n      const schema = S.DateFromSelf\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Date>>()\n      expect(schema).type.toBe<typeof S.DateFromSelf>()\n      // TODO: should be typeof S.DateFromSelf\n      expect(schema.annotations({})).type.toBe<S.declare<Date>>()\n    })\n\n    it(\"DateTimeUtcFromSelf\", () => {\n      const schema = S.DateTimeUtcFromSelf\n      expect(S.asSchema(schema)).type.toBe<S.Schema<DateTime.Utc>>()\n      expect(schema).type.toBe<typeof S.DateTimeUtcFromSelf>()\n      // TODO: should be typeof S.DateTimeUtcFromSelf\n      expect(schema.annotations({})).type.toBe<S.declare<DateTime.Utc>>()\n    })\n\n    it(\"TimeZoneOffsetFromSelf\", () => {\n      const schema = S.TimeZoneOffsetFromSelf\n      expect(S.asSchema(schema)).type.toBe<S.Schema<DateTime.TimeZone.Offset>>()\n      expect(schema).type.toBe<typeof S.TimeZoneOffsetFromSelf>()\n      // TODO: should be typeof S.TimeZoneOffsetFromSelf\n      expect(schema.annotations({})).type.toBe<S.declare<DateTime.TimeZone.Offset>>()\n    })\n\n    it(\"TimeZoneNamedFromSelf\", () => {\n      const schema = S.TimeZoneNamedFromSelf\n      expect(S.asSchema(schema)).type.toBe<S.Schema<DateTime.TimeZone.Named>>()\n      expect(schema).type.toBe<typeof S.TimeZoneNamedFromSelf>()\n      // TODO: should be typeof S.TimeZoneNamedFromSelf\n      expect(schema.annotations({})).type.toBe<S.declare<DateTime.TimeZone.Named>>()\n    })\n\n    it(\"DateTimeZonedFromSelf\", () => {\n      const schema = S.DateTimeZonedFromSelf\n      expect(S.asSchema(schema)).type.toBe<S.Schema<DateTime.Zoned>>()\n      expect(schema).type.toBe<typeof S.DateTimeZonedFromSelf>()\n      // TODO: should be typeof S.DateTimeZonedFromSelf\n      expect(schema.annotations({})).type.toBe<S.declare<DateTime.Zoned>>()\n    })\n\n    it(\"DurationFromSelf\", () => {\n      const schema = S.DurationFromSelf\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Duration.Duration>>()\n      expect(schema).type.toBe<typeof S.DurationFromSelf>()\n      // TODO: should be typeof S.DurationFromSelf\n      expect(schema.annotations({})).type.toBe<S.declare<Duration.Duration>>()\n    })\n\n    it(\"Duration\", () => {\n      expect(S.asSchema(S.Duration))\n        .type.toBe<S.Schema<Duration.Duration, S.DurationEncoded | readonly [seconds: number, nanos: number]>>()\n    })\n\n    it(\"DurationFromMillis\", () => {\n      expect(S.asSchema(S.DurationFromMillis)).type.toBe<S.Schema<Duration.Duration, number>>()\n    })\n\n    it(\"DurationFromNanos\", () => {\n      expect(S.asSchema(S.DurationFromNanos)).type.toBe<S.Schema<Duration.Duration, bigint>>()\n    })\n\n    it(\"BigDecimalFromSelf\", () => {\n      const schema = S.BigDecimalFromSelf\n      expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n      expect(schema).type.toBe<typeof S.BigDecimalFromSelf>()\n      // TODO: should be typeof S.BigDecimalFromSelf\n      expect(schema.annotations({})).type.toBe<S.declare<BigDecimal.BigDecimal>>()\n    })\n\n    it(\"FiberIdFromSelf\", () => {\n      const schema = S.FiberIdFromSelf\n      expect(S.asSchema(schema)).type.toBe<S.Schema<FiberId.FiberId>>()\n      expect(schema).type.toBe<typeof S.FiberIdFromSelf>()\n      // TODO: should be typeof S.FiberIdFromSelf\n      expect(schema.annotations({})).type.toBe<S.declare<FiberId.FiberId>>()\n    })\n\n    it(\"BigDecimal\", () => {\n      expect(S.asSchema(S.BigDecimal)).type.toBe<S.Schema<BigDecimal.BigDecimal, string>>()\n    })\n\n    it(\"BigDecimalFromNumber\", () => {\n      expect(S.asSchema(S.BigDecimalFromNumber)).type.toBe<S.Schema<BigDecimal.BigDecimal, number>>()\n    })\n\n    it(\"ChunkFromSelf\", () => {\n      const schema = S.ChunkFromSelf(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Chunk.Chunk<number>, Chunk.Chunk<string>>>()\n      expect(schema).type.toBe<S.ChunkFromSelf<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.ChunkFromSelf<typeof S.NumberFromString>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString]>()\n    })\n\n    it(\"Chunk\", () => {\n      const schema = S.Chunk(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Chunk.Chunk<number>, ReadonlyArray<string>>>()\n      expect(schema).type.toBe<S.Chunk<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.Chunk<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<S.Array$<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.ChunkFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"NonEmptyChunkFromSelf\", () => {\n      const schema = S.NonEmptyChunkFromSelf(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Chunk.NonEmptyChunk<number>, Chunk.NonEmptyChunk<string>>>()\n      expect(schema).type.toBe<S.NonEmptyChunkFromSelf<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.NonEmptyChunkFromSelf<typeof S.NumberFromString>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString]>()\n    })\n\n    it(\"NonEmptyChunk\", () => {\n      const schema = S.NonEmptyChunk(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Chunk.NonEmptyChunk<number>, readonly [string, ...Array<string>]>>()\n      expect(schema).type.toBe<S.NonEmptyChunk<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.NonEmptyChunk<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<S.NonEmptyArray<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.NonEmptyChunkFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"DataFromSelf\", () => {\n      expect(S.DataFromSelf).type.not.toBeCallableWith(hole<S.Schema<string>>())\n      expect(S.DataFromSelf).type.not.toBeCallableWith(hole<S.Schema<{}, number>>())\n\n      // should allow generic context\n      const _f1 = <A extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>>(schema: S.Schema<A>) =>\n        S.DataFromSelf(schema)\n      const _f2 = <\n        A extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>,\n        I extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>\n      >(schema: S.Schema<A, I>) => S.DataFromSelf(schema)\n      const _f3 = <A extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>, I extends number>(\n        schema: S.Schema<A, I>\n      ) => expect(S.DataFromSelf).type.not.toBeCallableWith(schema)\n      const _f4 = <A extends string>(schema: S.Schema<A>) => expect(S.DataFromSelf).type.not.toBeCallableWith(schema)\n\n      // should allow mutable arguments\n      S.DataFromSelf(S.mutable(S.Struct({ a: S.NumberFromString })))\n\n      const schema = S.DataFromSelf(S.Struct({ a: S.NumberFromString }))\n      expect(schema)\n        .type.toBe<\n        S.DataFromSelf<\n          S.Struct<{\n            a: typeof S.NumberFromString\n          }>\n        >\n      >()\n      expect(schema.annotations({}))\n        .type.toBe<\n        S.DataFromSelf<\n          S.Struct<{\n            a: typeof S.NumberFromString\n          }>\n        >\n      >()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<\n        readonly [\n          S.Struct<{\n            a: typeof S.NumberFromString\n          }>\n        ]\n      >()\n    })\n\n    it(\"Data\", () => {\n      expect(S.Data).type.not.toBeCallableWith(hole<S.Schema<string>>())\n      expect(S.Data).type.not.toBeCallableWith(hole<S.Schema<{}, number>>())\n\n      const schema = S.Data(S.Struct({ a: S.NumberFromString }))\n      expect(schema)\n        .type.toBe<\n        S.Data<\n          S.Struct<{\n            a: typeof S.NumberFromString\n          }>\n        >\n      >()\n      expect(schema.annotations({}))\n        .type.toBe<\n        S.Data<\n          S.Struct<{\n            a: typeof S.NumberFromString\n          }>\n        >\n      >()\n      expect(schema.from).type.toBe<\n        S.Struct<{\n          a: typeof S.NumberFromString\n        }>\n      >()\n      expect(schema.to).type.toBe<S.DataFromSelf<S.SchemaClass<{ readonly a: number }>>>()\n    })\n\n    it(\"RedactedFromSelf\", () => {\n      const schema = S.RedactedFromSelf(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Redacted.Redacted<number>, Redacted.Redacted<string>>>()\n      expect(schema).type.toBe<S.RedactedFromSelf<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.RedactedFromSelf<typeof S.NumberFromString>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString]>()\n    })\n\n    it(\"Redacted\", () => {\n      const schema = S.Redacted(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Redacted.Redacted<number>, string>>()\n      expect(schema).type.toBe<S.Redacted<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.Redacted<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<typeof S.NumberFromString>()\n      expect(schema.to).type.toBe<S.RedactedFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"OptionFromSelf\", () => {\n      const schema = S.OptionFromSelf(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Option.Option<number>, Option.Option<string>>>()\n      expect(schema).type.toBe<S.OptionFromSelf<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.OptionFromSelf<typeof S.NumberFromString>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString]>()\n    })\n\n    it(\"Option\", () => {\n      const schema = S.Option(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Option.Option<number>, S.OptionEncoded<string>>>()\n      expect(schema).type.toBe<S.Option<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.Option<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<\n        S.Union<\n          [\n            S.Struct<{ _tag: S.Literal<[\"None\"]> }>,\n            S.Struct<{ _tag: S.Literal<[\"Some\"]>; value: typeof S.NumberFromString }>\n          ]\n        >\n      >()\n      expect(schema.to).type.toBe<S.OptionFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"OptionFromNullOr\", () => {\n      const schema = S.OptionFromNullOr(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Option.Option<number>, string | null>>()\n      expect(schema).type.toBe<S.OptionFromNullOr<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.OptionFromNullOr<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<S.NullOr<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.OptionFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"OptionFromUndefinedOr\", () => {\n      const schema = S.OptionFromUndefinedOr(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Option.Option<number>, string | undefined>>()\n      expect(schema).type.toBe<S.OptionFromUndefinedOr<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.OptionFromUndefinedOr<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<S.UndefinedOr<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.OptionFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"OptionFromNullishOr\", () => {\n      const schema = S.OptionFromNullishOr(S.NumberFromString, null)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Option.Option<number>, string | null | undefined>>()\n      expect(schema).type.toBe<S.OptionFromNullishOr<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.OptionFromNullishOr<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<S.NullishOr<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.OptionFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"EitherFromSelf\", () => {\n      const schema = S.EitherFromSelf({ right: S.NumberFromString, left: S.String })\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Either.Either<number, string>, Either.Either<string, string>>>()\n      expect(schema).type.toBe<S.EitherFromSelf<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.annotations({})).type.toBe<S.EitherFromSelf<typeof S.NumberFromString, typeof S.String>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString, typeof S.String]>()\n\n      // should allow never as right\n      expect(S.EitherFromSelf({ right: S.Never, left: S.String }))\n        .type.toBe<S.EitherFromSelf<typeof S.Never, typeof S.String>>()\n      // should allow never as left\n      expect(S.EitherFromSelf({ right: S.String, left: S.Never }))\n        .type.toBe<S.EitherFromSelf<typeof S.String, typeof S.Never>>()\n    })\n\n    it(\"Either\", () => {\n      const schema = S.Either({ right: S.NumberFromString, left: S.String })\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Either.Either<number, string>, S.EitherEncoded<string, string>>>()\n      expect(schema).type.toBe<S.Either<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.annotations({})).type.toBe<S.Either<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.from).type.toBe<\n        S.Union<[\n          S.Struct<{\n            _tag: S.Literal<[\"Right\"]>\n            right: typeof S.NumberFromString\n          }>,\n          S.Struct<{\n            _tag: S.Literal<[\"Left\"]>\n            left: typeof S.String\n          }>\n        ]>\n      >()\n      expect(schema.to).type.toBe<S.EitherFromSelf<S.SchemaClass<number>, S.SchemaClass<string>>>()\n\n      // should allow never as right\n      expect(S.Either({ right: S.Never, left: S.String })).type.toBe<S.Either<typeof S.Never, typeof S.String>>()\n      // should allow never as left\n      expect(S.Either({ right: S.String, left: S.Never })).type.toBe<S.Either<typeof S.String, typeof S.Never>>()\n    })\n\n    it(\"EitherFromUnion\", () => {\n      const schema = S.EitherFromUnion({ right: S.NumberFromString, left: S.Boolean })\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Either.Either<number, boolean>, string | boolean>>()\n      expect(schema).type.toBe<S.EitherFromUnion<typeof S.NumberFromString, typeof S.Boolean>>()\n      expect(schema.annotations({})).type.toBe<S.EitherFromUnion<typeof S.NumberFromString, typeof S.Boolean>>()\n      expect(schema.from).type.toBe<\n        S.Union<[\n          S.transform<\n            typeof S.NumberFromString,\n            S.Struct<{\n              _tag: S.Literal<[\"Right\"]>\n              right: S.SchemaClass<number>\n            }>\n          >,\n          S.transform<\n            typeof S.Boolean,\n            S.Struct<{\n              _tag: S.Literal<[\"Left\"]>\n              right: S.SchemaClass<boolean>\n            }>\n          >\n        ]>\n      >()\n      expect(schema.from.members[0].to.fields.right).type.toBe<S.SchemaClass<number>>()\n      expect(schema.to).type.toBe<S.EitherFromSelf<S.SchemaClass<number>, S.SchemaClass<boolean>>>()\n\n      // should allow never as right\n      expect(S.EitherFromUnion({ right: S.Never, left: S.String }))\n        .type.toBe<S.EitherFromUnion<typeof S.Never, typeof S.String>>()\n      // should allow never as left\n      expect(S.EitherFromUnion({ right: S.String, left: S.Never }))\n        .type.toBe<S.EitherFromUnion<typeof S.String, typeof S.Never>>()\n    })\n\n    it(\"ReadonlyMapFromSelf\", () => {\n      const schema = S.ReadonlyMapFromSelf({ key: S.NumberFromString, value: S.String })\n      expect(S.asSchema(schema)).type.toBe<S.Schema<ReadonlyMap<number, string>, ReadonlyMap<string, string>>>()\n      expect(schema).type.toBe<S.ReadonlyMapFromSelf<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.annotations({})).type.toBe<S.ReadonlyMapFromSelf<typeof S.NumberFromString, typeof S.String>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString, typeof S.String]>()\n    })\n\n    it(\"ReadonlyMap\", () => {\n      const schema = S.ReadonlyMap({ key: S.NumberFromString, value: S.String })\n      expect(S.asSchema(schema))\n        .type.toBe<S.Schema<ReadonlyMap<number, string>, ReadonlyArray<readonly [string, string]>>>()\n      expect(schema).type.toBe<S.ReadonlyMap$<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.annotations({})).type.toBe<S.ReadonlyMap$<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.from).type.toBe<S.Array$<S.Tuple2<typeof S.NumberFromString, typeof S.String>>>()\n      expect(schema.to).type.toBe<S.ReadonlyMapFromSelf<S.SchemaClass<number>, S.SchemaClass<string>>>()\n    })\n\n    it(\"MapFromSelf\", () => {\n      const schema = S.MapFromSelf({ key: S.NumberFromString, value: S.String })\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Map<number, string>, ReadonlyMap<string, string>>>()\n      expect(schema).type.toBe<S.MapFromSelf<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.annotations({})).type.toBe<S.MapFromSelf<typeof S.NumberFromString, typeof S.String>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString, typeof S.String]>()\n    })\n\n    it(\"Map\", () => {\n      const schema = S.Map({ key: S.NumberFromString, value: S.String })\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Map<number, string>, ReadonlyArray<readonly [string, string]>>>()\n      expect(schema).type.toBe<S.Map$<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.annotations({})).type.toBe<S.Map$<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.from).type.toBe<S.Array$<S.Tuple2<typeof S.NumberFromString, typeof S.String>>>()\n      expect(schema.to).type.toBe<S.MapFromSelf<S.SchemaClass<number>, S.SchemaClass<string>>>()\n    })\n\n    it(\"HashMapFromSelf\", () => {\n      const schema = S.HashMapFromSelf({ key: S.NumberFromString, value: S.String })\n      expect(S.asSchema(schema)).type.toBe<S.Schema<HashMap.HashMap<number, string>, HashMap.HashMap<string, string>>>()\n      expect(schema).type.toBe<S.HashMapFromSelf<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.annotations({})).type.toBe<S.HashMapFromSelf<typeof S.NumberFromString, typeof S.String>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString, typeof S.String]>()\n    })\n\n    it(\"HashMap\", () => {\n      const schema = S.HashMap({ key: S.NumberFromString, value: S.String })\n      expect(S.asSchema(schema))\n        .type.toBe<S.Schema<HashMap.HashMap<number, string>, ReadonlyArray<readonly [string, string]>>>()\n      expect(schema).type.toBe<S.HashMap<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.annotations({})).type.toBe<S.HashMap<typeof S.NumberFromString, typeof S.String>>()\n      expect(schema.from).type.toBe<S.Array$<S.Tuple2<typeof S.NumberFromString, typeof S.String>>>()\n      expect(schema.to).type.toBe<S.HashMapFromSelf<S.SchemaClass<number>, S.SchemaClass<string>>>()\n    })\n\n    it(\"ReadonlySetFromSelf\", () => {\n      const schema = S.ReadonlySetFromSelf(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<ReadonlySet<number>, ReadonlySet<string>>>()\n      expect(schema).type.toBe<S.ReadonlySetFromSelf<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.ReadonlySetFromSelf<typeof S.NumberFromString>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString]>()\n    })\n\n    it(\"ReadonlySet\", () => {\n      const schema = S.ReadonlySet(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<ReadonlySet<number>, ReadonlyArray<string>>>()\n      expect(schema).type.toBe<S.ReadonlySet$<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.ReadonlySet$<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<S.Array$<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.ReadonlySetFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"SetFromSelf\", () => {\n      const schema = S.SetFromSelf(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Set<number>, ReadonlySet<string>>>()\n      expect(schema).type.toBe<S.SetFromSelf<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.SetFromSelf<typeof S.NumberFromString>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString]>()\n    })\n\n    it(\"Set\", () => {\n      const schema = S.Set(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Set<number>, ReadonlyArray<string>>>()\n      expect(schema).type.toBe<S.Set$<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.Set$<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<S.Array$<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.SetFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"HashSetFromSelf\", () => {\n      const schema = S.HashSetFromSelf(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<HashSet.HashSet<number>, HashSet.HashSet<string>>>()\n      expect(schema).type.toBe<S.HashSetFromSelf<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.HashSetFromSelf<typeof S.NumberFromString>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString]>()\n    })\n\n    it(\"HashSet\", () => {\n      const schema = S.HashSet(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<HashSet.HashSet<number>, ReadonlyArray<string>>>()\n      expect(schema).type.toBe<S.HashSet<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.HashSet<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<S.Array$<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.HashSetFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"ListFromSelf\", () => {\n      const schema = S.ListFromSelf(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<List.List<number>, List.List<string>>>()\n      expect(schema).type.toBe<S.ListFromSelf<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.ListFromSelf<typeof S.NumberFromString>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString]>()\n    })\n\n    it(\"List\", () => {\n      const schema = S.List(S.NumberFromString)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<List.List<number>, ReadonlyArray<string>>>()\n      expect(schema).type.toBe<S.List<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.List<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<S.Array$<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.ListFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"CauseFromSelf\", () => {\n      const schema = S.CauseFromSelf({ error: S.String, defect: S.Unknown })\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Cause.Cause<string>, Cause.Cause<string>>>()\n      expect(schema).type.toBe<S.CauseFromSelf<typeof S.String, typeof S.Unknown>>()\n      expect(schema.annotations({})).type.toBe<S.CauseFromSelf<typeof S.String, typeof S.Unknown>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.String, typeof S.Unknown]>()\n\n      const defectWithR = S.CauseFromSelf({ error: S.String, defect: hole<S.Schema<unknown, unknown, \"a\">>() })\n      expect(S.asSchema(defectWithR)).type.toBe<S.Schema<Cause.Cause<string>, Cause.Cause<string>, \"a\">>()\n      expect(defectWithR).type.toBe<S.CauseFromSelf<typeof S.String, S.Schema<unknown, unknown, \"a\">>>()\n    })\n\n    it(\"Cause\", () => {\n      const schema = S.Cause({ error: S.String, defect: S.Defect })\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Cause.Cause<string>, S.CauseEncoded<string, unknown>>>()\n      expect(schema).type.toBe<S.Cause<typeof S.String, typeof S.Defect>>()\n      expect(schema.annotations({})).type.toBe<S.Cause<typeof S.String, typeof S.Defect>>()\n      expect(schema.from).type.toBe<\n        S.SchemaClass<S.CauseEncoded<string, unknown>, S.CauseEncoded<string, unknown>, never>\n      >()\n      expect(schema.to).type.toBe<S.CauseFromSelf<S.SchemaClass<string>, S.SchemaClass<unknown>>>()\n\n      const defectWithR = S.Cause({ error: S.String, defect: hole<S.Schema<unknown, unknown, \"a\">>() })\n      expect(S.asSchema(defectWithR)).type.toBe<S.Schema<Cause.Cause<string>, S.CauseEncoded<string, unknown>, \"a\">>()\n      expect(defectWithR).type.toBe<S.Cause<typeof S.String, S.Schema<unknown, unknown, \"a\">>>()\n    })\n\n    it(\"ExitFromSelf\", () => {\n      const schema = S.ExitFromSelf({ success: S.Number, failure: S.String, defect: S.Unknown })\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Exit.Exit<number, string>, Exit.Exit<number, string>>>()\n      expect(schema).type.toBe<S.ExitFromSelf<typeof S.Number, typeof S.String, typeof S.Unknown>>()\n      expect(schema.annotations({})).type.toBe<S.ExitFromSelf<typeof S.Number, typeof S.String, typeof S.Unknown>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.Number, typeof S.String, typeof S.Unknown]>()\n\n      const defectWithR = S.ExitFromSelf({\n        success: S.Number,\n        failure: S.String,\n        defect: hole<S.Schema<unknown, unknown, \"a\">>()\n      })\n      expect(S.asSchema(defectWithR)).type.toBe<S.Schema<Exit.Exit<number, string>, Exit.Exit<number, string>, \"a\">>()\n      expect(defectWithR).type.toBe<S.ExitFromSelf<typeof S.Number, typeof S.String, S.Schema<unknown, unknown, \"a\">>>()\n    })\n\n    it(\"Exit\", () => {\n      const schema = S.Exit({ success: S.NumberFromString, failure: S.String, defect: S.Defect })\n      expect(S.asSchema(schema))\n        .type.toBe<S.Schema<Exit.Exit<number, string>, S.ExitEncoded<string, string, unknown>>>()\n      expect(schema).type.toBe<S.Exit<typeof S.NumberFromString, typeof S.String, typeof S.Defect>>()\n      expect(schema.annotations({})).type.toBe<S.Exit<typeof S.NumberFromString, typeof S.String, typeof S.Defect>>()\n      expect(schema.from).type.toBe<\n        S.Union<[\n          S.Struct<{\n            _tag: S.Literal<[\"Failure\"]>\n            cause: S.SchemaClass<S.CauseEncoded<string, unknown>, S.CauseEncoded<string, unknown>, never>\n          }>,\n          S.Struct<{\n            _tag: S.Literal<[\"Success\"]>\n            value: typeof S.NumberFromString\n          }>\n        ]>\n      >()\n      expect(schema.to).type.toBe<\n        S.ExitFromSelf<S.SchemaClass<number>, S.SchemaClass<string>, S.SchemaClass<unknown>>\n      >()\n\n      const defectWithR = S.Exit({\n        success: S.Number,\n        failure: S.String,\n        defect: hole<S.Schema<unknown, unknown, \"a\">>()\n      })\n      expect(S.asSchema(defectWithR))\n        .type.toBe<S.Schema<Exit.Exit<number, string>, S.ExitEncoded<number, string, unknown>, \"a\">>()\n      expect(defectWithR).type.toBe<S.Exit<typeof S.Number, typeof S.String, S.Schema<unknown, unknown, \"a\">>>()\n    })\n\n    it(\"SortedSetFromSelf\", () => {\n      const schema = S.SortedSetFromSelf(S.NumberFromString, N.Order, Str.Order)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<SortedSet.SortedSet<number>, SortedSet.SortedSet<string>>>()\n      expect(schema).type.toBe<S.SortedSetFromSelf<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.SortedSetFromSelf<typeof S.NumberFromString>>()\n      // should expose the type parameters\n      expect(schema.typeParameters).type.toBe<readonly [typeof S.NumberFromString]>()\n    })\n\n    it(\"SortedSet\", () => {\n      const schema = S.SortedSet(S.NumberFromString, N.Order)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<SortedSet.SortedSet<number>, ReadonlyArray<string>>>()\n      expect(schema).type.toBe<S.SortedSet<typeof S.NumberFromString>>()\n      expect(schema.annotations({})).type.toBe<S.SortedSet<typeof S.NumberFromString>>()\n      expect(schema.from).type.toBe<S.Array$<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.SortedSetFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"Config\", () => {\n      expect(S.Config(\"A\", S.String))\n        .type.toBe<Config.Config<string>>()\n      expect(S.Config(\"A\", S.BooleanFromString))\n        .type.toBe<Config.Config<boolean>>()\n      expect(S.Config(\"A\", S.TemplateLiteral(S.Literal(\"a\"), S.String)))\n        .type.toBe<Config.Config<`a${string}`>>()\n\n      // passed schemas must be encodable to string\n      expect(S.Config).type.not.toBeCallableWith(\"A\", S.Boolean)\n    })\n\n    it(\"Defect\", () => {\n      const schema = S.Defect\n      expect(S.asSchema(schema)).type.toBe<S.Schema<unknown>>()\n      expect(schema).type.toBe<typeof S.Defect>()\n    })\n  })\n\n  describe(\"parseJson\", () => {\n    it(\"no arguments\", () => {\n      const schema = S.parseJson()\n      expect(S.asSchema(schema)).type.toBe<S.Schema<unknown, string>>()\n      expect(schema).type.toBe<S.SchemaClass<unknown, string>>()\n      expect(schema.annotations({})).type.toBe<S.SchemaClass<unknown, string>>()\n    })\n\n    it(\"single argument\", () => {\n      const schema = S.parseJson(S.Struct({ a: S.Number }))\n      expect(S.asSchema(schema)).type.toBe<S.Schema<{ readonly a: number }, string>>()\n      expect(schema).type.toBe<S.transform<S.SchemaClass<unknown, string>, S.Struct<{ a: typeof S.Number }>>>()\n      expect(schema.annotations({})).type.toBe<\n        S.transform<S.SchemaClass<unknown, string>, S.Struct<{ a: typeof S.Number }>>\n      >()\n      expect(schema.from).type.toBe<S.SchemaClass<unknown, string>>()\n      expect(schema.to).type.toBe<S.Struct<{ a: typeof S.Number }>>()\n    })\n  })\n\n  it(\"ArrayEnsure\", () => {\n    const schema = S.ArrayEnsure(S.NumberFromString)\n    expect(S.asSchema(schema)).type.toBe<S.Schema<ReadonlyArray<number>, string | ReadonlyArray<string>>>()\n    expect(schema).type.toBe<S.ArrayEnsure<typeof S.NumberFromString>>()\n    expect(schema.annotations({})).type.toBe<S.ArrayEnsure<typeof S.NumberFromString>>()\n    expect(schema.from).type.toBe<S.Union<[typeof S.NumberFromString, S.Array$<typeof S.NumberFromString>]>>()\n    expect(schema.to).type.toBe<S.Array$<S.SchemaClass<number>>>()\n  })\n\n  it(\"NonEmptyArrayEnsure\", () => {\n    const schema = S.NonEmptyArrayEnsure(S.NumberFromString)\n    expect(S.asSchema(schema)).type.toBe<\n      S.Schema<readonly [number, ...Array<number>], string | readonly [string, ...Array<string>]>\n    >()\n    expect(schema).type.toBe<S.NonEmptyArrayEnsure<typeof S.NumberFromString>>()\n    expect(schema.annotations({})).type.toBe<S.NonEmptyArrayEnsure<typeof S.NumberFromString>>()\n    expect(schema.from).type.toBe<S.Union<[typeof S.NumberFromString, S.NonEmptyArray<typeof S.NumberFromString>]>>()\n    expect(schema.to).type.toBe<S.NonEmptyArray<S.SchemaClass<number>>>()\n  })\n\n  it(\"ReadonlyMapFromRecord\", () => {\n    const schema = S.ReadonlyMapFromRecord({ key: S.NumberFromString, value: S.NumberFromString })\n    expect(S.asSchema(schema)).type.toBe<S.Schema<ReadonlyMap<number, number>, { readonly [x: string]: string }>>()\n    expect(schema).type.toBe<S.SchemaClass<ReadonlyMap<number, number>, { readonly [x: string]: string }>>()\n    expect(schema.annotations({})).type.toBe<\n      S.SchemaClass<ReadonlyMap<number, number>, { readonly [x: string]: string }>\n    >()\n  })\n\n  it(\"MapFromRecord\", () => {\n    const schema = S.MapFromRecord({ key: S.NumberFromString, value: S.NumberFromString })\n    expect(S.asSchema(schema)).type.toBe<S.Schema<Map<number, number>, { readonly [x: string]: string }>>()\n    expect(schema).type.toBe<S.SchemaClass<Map<number, number>, { readonly [x: string]: string }>>()\n    expect(schema.annotations({})).type.toBe<S.SchemaClass<Map<number, number>, { readonly [x: string]: string }>>()\n  })\n\n  describe(\"Transformations\", () => {\n    it(\"clamp\", () => {\n      when(S.String.pipe).isCalledWith(expect(S.clamp).type.not.toBeCallableWith(-1, 1))\n\n      const schema = S.Number.pipe(S.clamp(-1, 1))\n      expect(S.asSchema(schema)).type.toBe<S.Schema<number>>()\n      expect(schema).type.toBe<S.transform<typeof S.Number, S.filter<S.SchemaClass<number>>>>()\n      expect(schema.annotations({})).type.toBe<S.transform<typeof S.Number, S.filter<S.SchemaClass<number>>>>()\n      expect(schema.from).type.toBe<typeof S.Number>()\n      expect(schema.to).type.toBe<S.filter<S.SchemaClass<number>>>()\n    })\n\n    it(\"clampBigInt\", () => {\n      when(S.String.pipe).isCalledWith(expect(S.clampBigInt).type.not.toBeCallableWith(-1, 1))\n\n      const schema = S.BigIntFromSelf.pipe(S.clampBigInt(-1n, 1n))\n      expect(S.asSchema(schema)).type.toBe<S.Schema<bigint>>()\n      expect(schema).type.toBe<S.transform<typeof S.BigIntFromSelf, S.filter<S.SchemaClass<bigint>>>>()\n      expect(schema.annotations({})).type.toBe<\n        S.transform<typeof S.BigIntFromSelf, S.filter<S.SchemaClass<bigint>>>\n      >()\n      expect(schema.from).type.toBe<typeof S.BigIntFromSelf>()\n      expect(schema.to).type.toBe<S.filter<S.SchemaClass<bigint>>>()\n    })\n\n    it(\"clampDuration\", () => {\n      when(S.String.pipe).isCalledWith(expect(S.clampDuration).type.not.toBeCallableWith(-1, 1))\n\n      const schema = S.DurationFromSelf.pipe(S.clampDuration(-1, 1))\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Duration.Duration>>()\n      expect(schema).type.toBe<S.transform<typeof S.DurationFromSelf, S.filter<S.SchemaClass<Duration.Duration>>>>()\n      expect(schema.annotations({})).type.toBe<\n        S.transform<typeof S.DurationFromSelf, S.filter<S.SchemaClass<Duration.Duration>>>\n      >()\n      expect(schema.from).type.toBe<typeof S.DurationFromSelf>()\n      expect(schema.to).type.toBe<S.filter<S.SchemaClass<Duration.Duration>>>()\n    })\n\n    it(\"clampBigDecimal\", () => {\n      when(S.String.pipe).isCalledWith(expect(S.clampBigDecimal).type.not.toBeCallableWith(-1, 1))\n\n      const schema = S.BigDecimalFromSelf.pipe(\n        S.clampBigDecimal(hole<BigDecimal.BigDecimal>(), hole<BigDecimal.BigDecimal>())\n      )\n      expect(S.asSchema(schema)).type.toBe<S.Schema<BigDecimal.BigDecimal>>()\n      expect(schema).type.toBe<\n        S.transform<typeof S.BigDecimalFromSelf, S.filter<S.SchemaClass<BigDecimal.BigDecimal>>>\n      >()\n      expect(schema.annotations({})).type.toBe<\n        S.transform<typeof S.BigDecimalFromSelf, S.filter<S.SchemaClass<BigDecimal.BigDecimal>>>\n      >()\n      expect(schema.from).type.toBe<typeof S.BigDecimalFromSelf>()\n      expect(schema.to).type.toBe<S.filter<S.SchemaClass<BigDecimal.BigDecimal>>>()\n    })\n\n    it(\"head\", () => {\n      expect(S.String.pipe).type.not.toBeCallableWith(S.head)\n\n      const schema = S.head(S.Array(S.NumberFromString))\n\n      expect(S.asSchema(schema)).type.toBe<S.Schema<Option.Option<number>, ReadonlyArray<string>, never>>()\n      expect(schema)\n        .type.toBe<S.transform<S.Array$<typeof S.NumberFromString>, S.OptionFromSelf<S.SchemaClass<number>>>>()\n      expect(schema.annotations({}))\n        .type.toBe<S.transform<S.Array$<typeof S.NumberFromString>, S.OptionFromSelf<S.SchemaClass<number>>>>()\n      expect(schema.from).type.toBe<S.Array$<typeof S.NumberFromString>>()\n      expect(schema.to).type.toBe<S.OptionFromSelf<S.SchemaClass<number>>>()\n    })\n\n    it(\"headNonEmpty\", () => {\n      expect(S.String.pipe).type.not.toBeCallableWith(S.headNonEmpty)\n\n      const schema = S.headNonEmpty(S.NonEmptyArray(S.Number))\n      expect(S.asSchema(schema)).type.toBe<S.Schema<number, readonly [number, ...Array<number>]>>()\n      expect(schema)\n        .type.toBe<S.transform<S.NonEmptyArray<typeof S.Number>, S.SchemaClass<number>>>()\n      expect(schema.annotations({}))\n        .type.toBe<S.transform<S.NonEmptyArray<typeof S.Number>, S.SchemaClass<number>>>()\n      expect(schema.from).type.toBe<S.NonEmptyArray<typeof S.Number>>()\n      expect(schema.to).type.toBe<S.SchemaClass<number>>()\n    })\n\n    it(\"headOrElse\", () => {\n      expect(S.String.pipe).type.not.toBeCallableWith(S.headOrElse())\n      expect(S.headOrElse).type.not.toBeCallableWith(S.Array(S.Number), () => \"a\")\n      when(S.Array(S.Number).pipe).isCalledWith(expect(S.headOrElse).type.not.toBeCallableWith(() => \"a\"))\n\n      const schema = S.headOrElse(S.Array(S.Number))\n      expect(S.asSchema(schema)).type.toBe<S.Schema<number, ReadonlyArray<number>>>()\n      expect(schema).type.toBe<S.transform<S.Array$<typeof S.Number>, S.SchemaClass<number>>>()\n      expect(schema.annotations({})).type.toBe<S.transform<S.Array$<typeof S.Number>, S.SchemaClass<number>>>()\n      expect(schema.from).type.toBe<S.Array$<typeof S.Number>>()\n      expect(schema.to).type.toBe<S.SchemaClass<number>>()\n    })\n\n    it(\"pluck\", () => {\n      expect(S.pluck).type.not.toBeCallableWith(\n        S.Struct({ a: S.propertySignature(S.Number).pipe(S.fromKey(\"c\")) }),\n        \"a\"\n      )\n\n      expect(pipe(S.Struct({ a: S.String, b: S.Number }), S.pluck(\"a\")))\n        .type.toBe<S.SchemaClass<string, { readonly a: string }>>()\n      const schema = S.pluck(S.Struct({ a: S.String, b: S.Number }), \"a\")\n      expect(schema).type.toBe<S.SchemaClass<string, { readonly a: string }>>()\n      expect(schema.annotations({})).type.toBe<S.SchemaClass<string, { readonly a: string }>>()\n\n      // should support optional fields\n      expect(S.pluck(S.Struct({ a: S.optional(S.String), b: S.Number }), \"a\"))\n        .type.toBe<S.SchemaClass<string | undefined, { readonly a?: string | undefined }>>()\n      expect(pipe(S.Struct({ a: S.optional(S.String), b: S.Number }), S.pluck(\"a\")))\n        .type.toBe<S.SchemaClass<string | undefined, { readonly a?: string | undefined }>>()\n      expect(S.pluck(S.Struct({ a: S.optionalWith(S.String, { exact: true }), b: S.Number }), \"a\"))\n        .type.toBe<S.SchemaClass<string | undefined, { readonly a?: string }>>()\n      expect(pipe(S.Struct({ a: S.optionalWith(S.String, { exact: true }), b: S.Number }), S.pluck(\"a\")))\n        .type.toBe<S.SchemaClass<string | undefined, { readonly a?: string }>>()\n    })\n\n    it(\"parseNumber\", () => {\n      expect(S.parseNumber).type.not.toBeCallableWith(S.Null)\n\n      const schema = S.parseNumber(S.String)\n      expect(S.asSchema(schema)).type.toBe<S.Schema<number, string>>()\n      expect(schema).type.toBe<S.transformOrFail<typeof S.String, typeof S.Number>>()\n      expect(schema.annotations({})).type.toBe<S.transformOrFail<typeof S.String, typeof S.Number>>()\n      expect(schema.from).type.toBe<typeof S.String>()\n      expect(schema.to).type.toBe<typeof S.Number>()\n    })\n  })\n\n  it(\"standardSchemaV1\", () => {\n    const standardSchema = S.standardSchemaV1(S.NumberFromString)\n    expect(S.asSchema(standardSchema)).type.toBe<S.Schema<number, string>>()\n    expect(standardSchema).type.toBe<StandardSchemaV1<string, number> & S.SchemaClass<number, string, never>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/SchemaClass.tst.ts",
    "content": "import type { SchemaAST as AST } from \"effect\"\nimport { Schema as S } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ntype HasFields<Fields extends S.Struct.Fields> = S.Struct<Fields> | {\n  readonly [S.RefineSchemaId]: HasFields<Fields>\n}\n\ndeclare const checkForConflicts: <Fields extends S.Struct.Fields>(\n  fieldsOr: Fields | HasFields<Fields>\n) => S.Struct<Fields>\n\ndeclare const aContext: S.Schema<string, string, \"a\">\ndeclare const bContext: S.Schema<number, number, \"b\">\ndeclare const cContext: S.Schema<boolean, boolean, \"c\">\n\nclass WithContext extends S.Class<WithContext>(\"WithContext\")({ a: aContext, b: bContext }) {}\n\ndescribe(\"Schema.Class\", () => {\n  it(\"should check conflicts with fields/from keys\", () => {\n    expect(checkForConflicts({ fields: S.String })).type.toBe<\n      S.Struct<{ fields: typeof S.String }>\n    >()\n    expect(checkForConflicts({ from: S.String })).type.toBe<\n      S.Struct<{ from: typeof S.String }>\n    >()\n    expect(checkForConflicts(S.Struct({ fields: S.String }))).type.toBe<\n      S.Struct<{ fields: typeof S.String }>\n    >()\n    expect(checkForConflicts(S.Struct({ from: S.String }))).type.toBe<\n      S.Struct<{ from: typeof S.String }>\n    >()\n    expect(checkForConflicts(S.Struct({ fields: S.String }).pipe(S.filter(() => true)))).type.toBe<\n      S.Struct<{ fields: typeof S.String }>\n    >()\n    expect(checkForConflicts(S.Struct({ from: S.String }).pipe(S.filter(() => true)))).type.toBe<\n      S.Struct<{ from: typeof S.String }>\n    >()\n    expect(\n      checkForConflicts(S.Struct({ fields: S.String }).pipe(S.filter(() => true), S.filter(() => true)))\n    ).type.toBe<S.Struct<{ fields: typeof S.String }>>()\n    expect(\n      checkForConflicts(S.Struct({ from: S.String }).pipe(S.filter(() => true), S.filter(() => true)))\n    ).type.toBe<S.Struct<{ from: typeof S.String }>>()\n    expect(checkForConflicts({ fields: S.Struct({ a: S.String }) })).type.toBe<\n      S.Struct<{ fields: S.Struct<{ a: typeof S.String }> }>\n    >()\n    expect(checkForConflicts({ fields: S.Struct({ a: S.String }).pipe(S.filter(() => true)) })).type.toBe<\n      S.Struct<{ fields: S.filter<S.Struct<{ a: typeof S.String }>> }>\n    >()\n    expect(\n      checkForConflicts({ fields: S.Struct({ a: S.String }).pipe(S.filter(() => true), S.filter(() => true)) })\n    ).type.toBe<S.Struct<{ fields: S.filter<S.filter<S.Struct<{ a: typeof S.String }>>> }>>()\n    expect(checkForConflicts({ from: S.Struct({ a: S.String }) })).type.toBe<\n      S.Struct<{ from: S.Struct<{ a: typeof S.String }> }>\n    >()\n    expect(checkForConflicts({ from: S.Struct({ a: S.String }).pipe(S.filter(() => true)) })).type.toBe<\n      S.Struct<{ from: S.filter<S.Struct<{ a: typeof S.String }>> }>\n    >()\n    expect(\n      checkForConflicts({ from: S.Struct({ a: S.String }).pipe(S.filter(() => true), S.filter(() => true)) })\n    ).type.toBe<S.Struct<{ from: S.filter<S.filter<S.Struct<{ a: typeof S.String }>>> }>>()\n  })\n\n  it(\"A class with no fields should permit an empty argument in the constructor.\", () => {\n    class NoFields extends S.Class<NoFields>(\"NoFields\")({}) {}\n\n    expect(NoFields.ast).type.toBe<AST.Transformation>()\n\n    expect<ConstructorParameters<typeof NoFields>>().type.toBe<\n      [props?: void | {}, options?: S.MakeOptions | undefined]\n    >()\n\n    new NoFields()\n    NoFields.make()\n    new NoFields({})\n    NoFields.make({})\n  })\n\n  it(\"should reject non existing props\", () => {\n    class A extends S.Class<A>(\"A\")({\n      a: S.String\n    }) {}\n\n    expect(A).type.not.toBeConstructableWith({ a: \"a\", b: \"b\" })\n    expect(A.make).type.not.toBeCallableWith({ a: \"a\", b: \"b\" })\n  })\n\n  it(\"A class with all fields with a default should permit an empty argument in the constructor.\", () => {\n    class AllDefaultedFields extends S.Class<AllDefaultedFields>(\"AllDefaultedFields\")({\n      a: S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"\"))\n    }) {}\n\n    expect<ConstructorParameters<typeof AllDefaultedFields>>().type.toBe<\n      [props?: void | { readonly a?: string }, options?: S.MakeOptions | undefined]\n    >()\n\n    new AllDefaultedFields()\n    AllDefaultedFields.make()\n    new AllDefaultedFields({})\n    AllDefaultedFields.make({})\n  })\n\n  it(\"test Context\", () => {\n    expect<S.Schema.Type<typeof WithContext>>()\n      .type.toBe<WithContext>()\n    expect<S.Schema.Encoded<typeof WithContext>>()\n      .type.toBe<{ readonly a: string; readonly b: number }>()\n    expect<S.Schema.Context<typeof WithContext>>()\n      .type.toBe<\"a\" | \"b\">()\n  })\n\n  it(\"should be a constructor\", () => {\n    expect<ConstructorParameters<typeof WithContext>>()\n      .type.toBe<[props: { readonly a: string; readonly b: number }, options?: S.MakeOptions | undefined]>()\n  })\n\n  it(\"should expose a `fields` field\", () => {\n    expect(WithContext.fields).type.toBe<{ readonly a: typeof aContext; readonly b: typeof bContext }>()\n  })\n\n  it(\"can be extended with Class.extend\", () => {\n    class Extended extends WithContext.extend<Extended>(\"Extended\")({\n      c: cContext\n    }) {}\n\n    expect<S.Schema.Type<typeof Extended>>()\n      .type.toBe<Extended>()\n\n    expect<S.Schema.Encoded<typeof Extended>>()\n      .type.toBe<{ readonly a: string; readonly b: number; readonly c: boolean }>()\n\n    expect<S.Schema.Context<typeof Extended>>().type.toBe<\"a\" | \"b\" | \"c\">()\n\n    expect(Extended.fields)\n      .type.toBe<\n      {\n        readonly a: S.Schema<string, string, \"a\">\n        readonly b: S.Schema<number, number, \"b\">\n        readonly c: S.Schema<boolean, boolean, \"c\">\n      }\n    >()\n\n    expect<ConstructorParameters<typeof Extended>>()\n      .type.toBe<\n      [props: { readonly a: string; readonly b: number; readonly c: boolean }, options?: S.MakeOptions | undefined]\n    >()\n  })\n\n  it(\"can be extended with another Class `fields` field\", () => {\n    class ExtendedFromClassFields extends S.Class<ExtendedFromClassFields>(\"ExtendedFromClassFields\")({\n      ...WithContext.fields,\n      b: S.String,\n      c: cContext\n    }) {}\n\n    expect<S.Schema.Type<typeof ExtendedFromClassFields>>()\n      .type.toBe<ExtendedFromClassFields>()\n\n    expect<S.Schema.Encoded<typeof ExtendedFromClassFields>>()\n      .type.toBe<{ readonly a: string; readonly b: string; readonly c: boolean }>()\n\n    expect<S.Schema.Context<typeof ExtendedFromClassFields>>()\n      .type.toBe<\"a\" | \"c\">()\n\n    expect(ExtendedFromClassFields.fields)\n      .type.toBe<\n      {\n        readonly b: typeof S.String\n        readonly c: S.Schema<boolean, boolean, \"c\">\n        readonly a: S.Schema<string, string, \"a\">\n      }\n    >()\n\n    expect<ConstructorParameters<typeof ExtendedFromClassFields>>()\n      .type.toBe<\n      [props: { readonly a: string; readonly b: string; readonly c: boolean }, options?: S.MakeOptions | undefined]\n    >()\n  })\n\n  it(\"can be extended with another TaggedClass `fields` field\", () => {\n    class ExtendedFromTaggedClassFields\n      extends S.TaggedClass<ExtendedFromTaggedClassFields>()(\"ExtendedFromTaggedClassFields\", {\n        ...WithContext.fields,\n        b: S.String,\n        c: cContext\n      })\n    {}\n\n    expect<S.Schema.Type<typeof ExtendedFromTaggedClassFields>>()\n      .type.toBe<ExtendedFromTaggedClassFields>()\n\n    expect<S.Schema.Encoded<typeof ExtendedFromTaggedClassFields>>()\n      .type.toBe<\n      { readonly a: string; readonly b: string; readonly c: boolean; readonly _tag: \"ExtendedFromTaggedClassFields\" }\n    >()\n\n    expect<S.Schema.Context<typeof ExtendedFromTaggedClassFields>>()\n      .type.toBe<\"a\" | \"c\">()\n\n    expect(ExtendedFromTaggedClassFields.fields)\n      .type.toBe<\n      {\n        readonly _tag: S.tag<\"ExtendedFromTaggedClassFields\">\n        readonly b: typeof S.String\n        readonly c: S.Schema<boolean, boolean, \"c\">\n        readonly a: S.Schema<string, string, \"a\">\n      }\n    >()\n\n    expect<ConstructorParameters<typeof ExtendedFromTaggedClassFields>>()\n      .type.toBe<\n      [props: { readonly a: string; readonly b: string; readonly c: boolean }, options?: S.MakeOptions | undefined]\n    >()\n  })\n\n  it(\"should accept a HasFields as argument\", () => {\n    class _A extends S.Class<_A>(\"A\")(S.Struct({ a: S.String })) {}\n    class _B extends S.Class<_B>(\"B\")(S.Struct({ a: S.String }).pipe(S.filter(() => true))) {}\n    class _C extends S.Class<_C>(\"C\")(\n      S.Struct({ a: S.String }).pipe(S.filter(() => true), S.filter(() => true))\n    ) {}\n  })\n\n  it(\"users can override an instance member property\", () => {\n    class A extends S.Class<A>(\"A\")(S.Struct({ a: S.String })) {\n      readonly b: number = 1\n    }\n\n    class B extends A.extend<B>(\"B\")({ c: S.String }) {\n      override readonly b = 2\n    }\n\n    expect(new B({ a: \"a\", c: \"c\" }).b)\n      .type.toBe<2>()\n  })\n\n  it(\"users can override an instance member function\", () => {\n    class A extends S.Class<A>(\"A\")(S.Struct({ a: S.String })) {\n      b(): number {\n        return 1\n      }\n    }\n\n    class B extends A.extend<B>(\"B\")({ c: S.String }) {\n      override b(): 2 {\n        return 2\n      }\n    }\n\n    expect(new B({ a: \"a\", c: \"c\" }).b())\n      .type.toBe<2>()\n  })\n\n  it(\"users can override a field with an instance member property\", () => {\n    class A extends S.Class<A>(\"A\")(S.Struct({ a: S.String })) {}\n\n    class B extends A.extend<B>(\"B\")({\n      c: S.String\n    }) {\n      override readonly a = \"default\"\n    }\n\n    expect(new B({ a: \"a\", c: \"c\" }).a)\n      .type.toBe<\"default\">()\n  })\n\n  it(`users can't override an instance member property with a field`, () => {\n    class A extends S.Class<A>(\"A\")(S.Struct({ a: S.String })) {\n      readonly b = 1\n    }\n\n    class B extends A.extend<B>(\"B\")({ b: S.Number }) {}\n\n    expect(new B({ a: \"a\", b: 2 }).b)\n      .type.toBe<1>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/Serializable.tst.ts",
    "content": "import { Schema } from \"effect\"\nimport { hole } from \"effect/Function\"\nimport { describe, expect, it } from \"tstyche\"\n\nclass TR extends Schema.TaggedRequest<TR>()(\"TR\", {\n  failure: Schema.String,\n  success: Schema.NumberFromString,\n  payload: {\n    id: Schema.NumberFromString\n  }\n}) {}\n\nconst successSchema = <Req extends Schema.TaggedRequest.All>(req: Req) => Schema.successSchema(Schema.asWithResult(req))\n\nconst failureSchema = <Req extends Schema.TaggedRequest.All>(req: Req) => Schema.failureSchema(Schema.asWithResult(req))\n\nconst selfSchema = <Req extends Schema.TaggedRequest.All>(req: Req) =>\n  Schema.serializableSchema(Schema.asSerializable(req))\n\ndeclare const F: Schema.Schema<\"failure\", \"failure-encoded\", \"failure-context\">\ndeclare const S_: Schema.Schema<\"success\", \"success-encoded\", \"success-context\">\ndeclare const P: {\n  a: Schema.Schema<\"payload\", \"payload-encoded\", \"payload-context\">\n}\n\nclass Foo extends Schema.TaggedRequest<Foo>()(\"A\", {\n  failure: F,\n  success: S_,\n  payload: P\n}) {}\n\ndescribe(\"Schema Serializable\", () => {\n  it(\"Serializable type-level helpers\", () => {\n    expect(hole<Schema.Serializable.Type<InstanceType<typeof Foo>>>()).type.toBe<Foo>()\n\n    expect(hole<Schema.Serializable.Encoded<InstanceType<typeof Foo>>>()).type.toBe<\n      Schema.Struct.Encoded<\n        { readonly _tag: Schema.tag<\"A\"> } & { a: Schema.Schema<\"payload\", \"payload-encoded\", \"payload-context\"> }\n      >\n    >()\n\n    expect(hole<Schema.Serializable.Context<InstanceType<typeof Foo>>>()).type.toBe<\"payload-context\">()\n  })\n\n  it(\"successSchema\", () => {\n    expect(successSchema(new TR({ id: 1 }))).type.toBe<Schema.Schema<number, string, never>>()\n  })\n\n  it(\"failureSchema\", () => {\n    expect(failureSchema(new TR({ id: 1 }))).type.toBe<Schema.Schema<string, string, never>>()\n  })\n\n  it(\"selfSchema\", () => {\n    expect(selfSchema(new TR({ id: 1 }))).type.toBe<\n      Schema.Schema<\n        TR,\n        Schema.Struct.Encoded<{ readonly _tag: Schema.tag<\"TR\"> } & { id: typeof Schema.NumberFromString }>,\n        never\n      >\n    >()\n  })\n\n  it(\"WithResult type-level helpers\", () => {\n    expect(hole<Schema.WithResult.Success<InstanceType<typeof Foo>>>()).type.toBe<\"success\">()\n    expect(hole<Schema.WithResult.SuccessEncoded<InstanceType<typeof Foo>>>()).type.toBe<\"success-encoded\">()\n    expect(hole<Schema.WithResult.Failure<InstanceType<typeof Foo>>>()).type.toBe<\"failure\">()\n    expect(hole<Schema.WithResult.FailureEncoded<InstanceType<typeof Foo>>>()).type.toBe<\"failure-encoded\">()\n    expect(hole<Schema.WithResult.Context<InstanceType<typeof Foo>>>()).type.toBe<\n      \"failure-context\" | \"success-context\"\n    >()\n  })\n\n  it(\"SerializableWithResult type-level helpers\", () => {\n    expect(hole<Schema.SerializableWithResult.Context<InstanceType<typeof Foo>>>()).type.toBe<\n      \"failure-context\" | \"success-context\" | \"payload-context\"\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/TaggedClass.tst.ts",
    "content": "import { Schema } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Schema.TaggedClass\", () => {\n  it(\"Annotations as tuple\", () => {\n    // @ts-expect-error!\n    class _A extends Schema.TaggedClass<_A>()(\"A\", { id: Schema.Number }, [\n      undefined,\n      undefined,\n      {\n        pretty: () => (x) => {\n          expect(x).type.toBe<{ readonly _tag: \"A\"; readonly id: number }>()\n          return \"\"\n        }\n      }\n    ]) {}\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/TaggedError.tst.ts",
    "content": "import type { Unify } from \"effect\"\nimport { Effect, Schema } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Schema.TaggedError\", () => {\n  it(\"should be yieldable\", () => {\n    class Err extends Schema.TaggedError<Err>()(\"Err\", {}) {}\n\n    expect<Unify.Unify<Err>>().type.toBe<Err>()\n\n    expect(Effect.gen(function*($) {\n      return yield* $(new Err())\n    })).type.toBe<Effect.Effect<never, Err>>()\n  })\n\n  it(\"make should respect custom constructors\", () => {\n    class MyError extends Schema.TaggedError<MyError>()(\n      \"MyError\",\n      { message: Schema.String }\n    ) {\n      constructor({ a, b }: { a: string; b: string }) {\n        super({ message: `${a}:${b}` })\n      }\n    }\n\n    expect(MyError.make({ a: \"a\", b: \"b\" }).message).type.toBe<string>()\n    expect(new MyError({ a: \"a\", b: \"b\" }).message).type.toBe<string>()\n  })\n\n  it(\"Annotations as tuple\", () => {\n    // @ts-expect-error!\n    class _A extends Schema.TaggedError<_A>()(\"A\", { id: Schema.Number }, [\n      undefined,\n      undefined,\n      {\n        pretty: () => (x) => {\n          expect(x).type.toBe<{ readonly _tag: \"A\"; readonly id: number }>()\n          return \"\"\n        }\n      }\n    ]) {}\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/TaggedRequest.tst.ts",
    "content": "import { Schema } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Schema.TaggedRequest\", () => {\n  it(\"should expose fields, _tag, success and failure\", () => {\n    class A extends Schema.TaggedRequest<A>()(\"A\", {\n      failure: Schema.String,\n      success: Schema.Number,\n      payload: {\n        id: Schema.Number\n      }\n    }) {}\n\n    expect(A.fields)\n      .type.toBe<{ readonly _tag: Schema.tag<\"A\">; readonly id: typeof Schema.Number }>()\n\n    expect(A._tag)\n      .type.toBe<\"A\">()\n\n    expect(A.success)\n      .type.toBe<typeof Schema.Number>()\n\n    expect(A.failure)\n      .type.toBe<typeof Schema.String>()\n  })\n\n  it(\"Annotations as tuple\", () => {\n    // @ts-expect-error!\n    class _A extends Schema.TaggedRequest<_A>()(\"A\", {\n      failure: Schema.String,\n      success: Schema.Number,\n      payload: {\n        id: Schema.Number\n      }\n    }, [\n      undefined,\n      undefined,\n      {\n        pretty: () => (x) => {\n          expect(x).type.toBe<{ readonly _tag: \"A\"; readonly id: number }>()\n          return \"\"\n        }\n      }\n    ]) {}\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Schema/Userland.tst.ts",
    "content": "import { Schema as S } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Schema Userland\", () => {\n  it(\"goal: pass a Schema Class as a parameter to a function\", () => {\n    // Discord: https://discordapp.com/channels/795981131316985866/847382157861060618/1268580485412556883\n\n    class Person extends S.Class<Person>(\"Person\")({\n      id: S.Number,\n      name: S.String.pipe(S.nonEmptyString())\n    }) {\n      static create(id: number): Person {\n        return new Person({ id, name: \"<anonymous>\" })\n      }\n      update(id: number): Person {\n        return new Person({ id, name: this.name })\n      }\n    }\n\n    type ModelProto = { update(id: number): Person }\n    type ModelStatics = { create(id: number): Person }\n    type Model<\n      Self,\n      Fields extends S.Struct.Fields\n    > =\n      & S.Class<\n        Self,\n        Fields,\n        S.Struct.Encoded<Fields>,\n        S.Struct.Context<Fields>,\n        S.Struct.Constructor<Fields>,\n        ModelProto,\n        {}\n      >\n      & ModelStatics\n\n    function f1<Self, Fields extends S.Struct.Fields>(clazz: Model<Self, Fields>) {\n      return clazz.create(2).update(3)\n    }\n\n    expect(f1(Person)).type.toBe<Person>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/SchemaAST.tst.ts",
    "content": "import * as AST from \"effect/SchemaAST\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"SchemaAST\", () => {\n  it(\"annotations\", () => {\n    // should allow to add custom string annotations to a schema\n    expect(AST.annotations(AST.stringKeyword, { a: 1 })).type.toBe<AST.AST>()\n    // should allow to add custom symbol annotations to a schema\n    expect(AST.annotations(AST.stringKeyword, { [Symbol.for(\"a\")]: 1 })).type.toBe<AST.AST>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Sink.tst.ts",
    "content": "import type { Chunk } from \"effect\"\nimport { Predicate, Sink } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const predicate: Predicate.Predicate<number | string>\n\ndescribe(\"Sink\", () => {\n  it(\"collectAllWhile\", () => {\n    expect(Sink.collectAllWhile(predicate))\n      .type.toBe<Sink.Sink<Chunk.Chunk<string | number>, string | number, string | number, never, never>>()\n    expect(Sink.collectAllWhile(Predicate.isNumber))\n      .type.toBe<Sink.Sink<Chunk.Chunk<number>, unknown, unknown, never, never>>()\n    expect(Sink.collectAllWhile(Predicate.isString))\n      .type.toBe<Sink.Sink<Chunk.Chunk<string>, unknown, unknown, never, never>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/SortedMap.tst.ts",
    "content": "import type { Order } from \"effect\"\nimport { pipe, SortedMap } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const stringAndNumberIterable: Iterable<[string, number]>\ndeclare const stringOrUndefinedOrder: Order.Order<string | undefined>\n\ndescribe(\"SortedMap\", () => {\n  it(\"fromIterable\", () => {\n    expect(SortedMap.fromIterable(stringAndNumberIterable, stringOrUndefinedOrder))\n      .type.toBe<SortedMap.SortedMap<string, number>>()\n    expect(pipe(stringAndNumberIterable, SortedMap.fromIterable(stringOrUndefinedOrder)))\n      .type.toBe<SortedMap.SortedMap<string, number>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/SortedSet.tst.ts",
    "content": "import { pipe } from \"effect/Function\"\nimport type { Order } from \"effect/Order\"\nimport type * as Predicate from \"effect/Predicate\"\nimport * as SortedSet from \"effect/SortedSet\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const numbers: SortedSet.SortedSet<number>\ndeclare const numbersOrStrings: SortedSet.SortedSet<number | string>\ndeclare const stringIterable: Iterable<string>\ndeclare const stringOrUndefinedOrder: Order<string | undefined>\ndeclare const predicateNumbersOrStrings: Predicate.Predicate<number | string>\n\ndescribe(\"SortedSet\", () => {\n  it(\"every\", () => {\n    pipe(\n      numbersOrStrings,\n      SortedSet.every((_item) => {\n        expect(_item).type.toBe<string | number>()\n        return true\n      })\n    )\n  })\n\n  it(\"some\", () => {\n    pipe(\n      numbersOrStrings,\n      SortedSet.some((_item) => {\n        expect(_item).type.toBe<string | number>()\n        return true\n      })\n    )\n  })\n\n  it(\"partition\", () => {\n    SortedSet.partition(numbersOrStrings, (_item) => {\n      expect(_item).type.toBe<string | number>()\n      return true\n    })\n\n    pipe(\n      numbersOrStrings,\n      SortedSet.partition((_item) => {\n        expect(_item).type.toBe<string | number>()\n        return true\n      })\n    )\n    expect(SortedSet.partition(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<\n      [excluded: SortedSet.SortedSet<string | number>, satisfying: SortedSet.SortedSet<string | number>]\n    >()\n\n    expect(pipe(numbersOrStrings, SortedSet.partition(predicateNumbersOrStrings))).type.toBe<\n      [excluded: SortedSet.SortedSet<string | number>, satisfying: SortedSet.SortedSet<string | number>]\n    >()\n  })\n\n  it(\"fromIterable\", () => {\n    expect(SortedSet.fromIterable(stringIterable, stringOrUndefinedOrder)).type.toBe<\n      SortedSet.SortedSet<string>\n    >()\n\n    expect(pipe(stringIterable, SortedSet.fromIterable(stringOrUndefinedOrder))).type.toBe<\n      SortedSet.SortedSet<string>\n    >()\n  })\n\n  it(\"filter\", () => {\n    SortedSet.filter(numbersOrStrings, (_item) => {\n      expect(_item).type.toBe<string | number>()\n      return true\n    })\n\n    pipe(\n      numbersOrStrings,\n      SortedSet.filter((_item) => {\n        expect(_item).type.toBe<string | number>()\n        return true\n      })\n    )\n\n    expect(SortedSet.filter(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<\n      SortedSet.SortedSet<string | number>\n    >()\n\n    expect(SortedSet.filter(numbers, predicateNumbersOrStrings)).type.toBe<\n      SortedSet.SortedSet<number>\n    >()\n\n    expect(pipe(numbersOrStrings, SortedSet.filter(predicateNumbersOrStrings))).type.toBe<\n      SortedSet.SortedSet<string | number>\n    >()\n\n    expect(pipe(numbers, SortedSet.filter(predicateNumbersOrStrings))).type.toBe<\n      SortedSet.SortedSet<number>\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Stream.tst.ts",
    "content": "import type { Chunk, Effect, Scope } from \"effect\"\nimport { Cause, pipe, Predicate, Stream } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const numbers: Stream.Stream<number>\ndeclare const numbersOrStrings: Stream.Stream<number | string>\ndeclare const predicateNumbersOrStrings: Predicate.Predicate<number | string>\n\ndescribe(\"Stream\", () => {\n  it(\"filter\", () => {\n    Stream.filter(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })\n\n    pipe(\n      numbersOrStrings,\n      Stream.filter((item) => {\n        expect(item).type.toBe<string | number>()\n        return true\n      })\n    )\n\n    expect(Stream.filter(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(Stream.filter(numbers, predicateNumbersOrStrings)).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.filter(predicateNumbersOrStrings))).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(pipe(numbers, Stream.filter(predicateNumbersOrStrings))).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(Stream.filter(numbersOrStrings, Predicate.isNumber)).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.filter(Predicate.isNumber))).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n  })\n\n  it(\"find\", () => {\n    Stream.find(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })\n\n    pipe(\n      numbersOrStrings,\n      Stream.find((item) => {\n        expect(item).type.toBe<string | number>()\n        return true\n      })\n    )\n\n    expect(Stream.find(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.find(predicateNumbersOrStrings))).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(Stream.find(numbersOrStrings, Predicate.isNumber)).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.find(Predicate.isNumber))).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n  })\n\n  it(\"partition\", () => {\n    Stream.partition(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })\n\n    pipe(\n      numbersOrStrings,\n      Stream.partition((item) => {\n        expect(item).type.toBe<string | number>()\n        return true\n      })\n    )\n\n    // The expected type is an Effect that yields a tuple of two Streams.\n    expect(Stream.partition(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<\n      Effect.Effect<\n        [\n          excluded: Stream.Stream<string | number, never, never>,\n          satisfying: Stream.Stream<string | number, never, never>\n        ],\n        never,\n        Scope.Scope\n      >\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.partition(predicateNumbersOrStrings))).type.toBe<\n      Effect.Effect<\n        [\n          excluded: Stream.Stream<string | number, never, never>,\n          satisfying: Stream.Stream<string | number, never, never>\n        ],\n        never,\n        Scope.Scope\n      >\n    >()\n\n    expect(Stream.partition(numbersOrStrings, Predicate.isNumber)).type.toBe<\n      Effect.Effect<\n        [excluded: Stream.Stream<string>, satisfying: Stream.Stream<number>],\n        never,\n        Scope.Scope\n      >\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.partition(Predicate.isNumber)))\n      .type.toBe<\n      Effect.Effect<\n        [excluded: Stream.Stream<string>, satisfying: Stream.Stream<number>],\n        never,\n        Scope.Scope\n      >\n    >()\n  })\n\n  it(\"takeWhile\", () => {\n    Stream.takeWhile(numbersOrStrings, (item) => {\n      expect(item).type.toBe<string | number>()\n      return true\n    })\n\n    pipe(\n      numbersOrStrings,\n      Stream.takeWhile((item) => {\n        expect(item).type.toBe<string | number>()\n        return true\n      })\n    )\n\n    expect(Stream.takeWhile(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.takeWhile(predicateNumbersOrStrings))).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(Stream.takeWhile(numbersOrStrings, Predicate.isNumber)).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.takeWhile(Predicate.isNumber))).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    // Additional variations:\n    expect(Stream.takeWhile(numbersOrStrings, predicateNumbersOrStrings)).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(Stream.takeWhile(numbers, predicateNumbersOrStrings)).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.takeWhile(predicateNumbersOrStrings))).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(pipe(numbers, Stream.takeWhile(predicateNumbersOrStrings))).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(Stream.takeWhile(numbersOrStrings, Predicate.isNumber)).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.takeWhile(Predicate.isNumber))).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n  })\n\n  it(\"dropWhile\", () => {\n    expect(Stream.dropWhile(numbers, predicateNumbersOrStrings)).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(pipe(numbers, Stream.dropWhile(predicateNumbersOrStrings))).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(Stream.dropWhile(numbersOrStrings, Predicate.isNumber)).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.dropWhile(Predicate.isNumber))).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n  })\n\n  it(\"dropUntil\", () => {\n    expect(Stream.dropUntil(numbers, predicateNumbersOrStrings)).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(pipe(numbers, Stream.dropUntil(predicateNumbersOrStrings))).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(Stream.dropUntil(numbersOrStrings, Predicate.isNumber)).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.dropUntil(Predicate.isNumber))).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n  })\n\n  it(\"split\", () => {\n    expect(Stream.split(numbers, predicateNumbersOrStrings)).type.toBe<\n      Stream.Stream<Chunk.Chunk<number>, never, never>\n    >()\n\n    expect(pipe(numbers, Stream.split(predicateNumbersOrStrings))).type.toBe<\n      Stream.Stream<Chunk.Chunk<number>, never, never>\n    >()\n\n    expect(Stream.split(numbersOrStrings, Predicate.isNumber)).type.toBe<\n      Stream.Stream<Chunk.Chunk<string>, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.split(Predicate.isNumber))).type.toBe<\n      Stream.Stream<Chunk.Chunk<string>, never, never>\n    >()\n  })\n\n  it(\"takeUntil\", () => {\n    expect(Stream.takeUntil(numbers, predicateNumbersOrStrings)).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(pipe(numbers, Stream.takeUntil(predicateNumbersOrStrings))).type.toBe<\n      Stream.Stream<number, never, never>\n    >()\n\n    expect(Stream.takeUntil(numbersOrStrings, Predicate.isNumber)).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n\n    expect(pipe(numbersOrStrings, Stream.takeUntil(Predicate.isNumber))).type.toBe<\n      Stream.Stream<string | number, never, never>\n    >()\n  })\n\n  it(\"Do Notation\", () => {\n    expect(\n      pipe(\n        Stream.Do,\n        Stream.bind(\"a\", (scope) => {\n          expect(scope).type.toBe<{}>()\n          return Stream.succeed(1)\n        }),\n        Stream.bind(\"b\", (scope) => {\n          expect(scope).type.toBe<{ a: number }>()\n          return Stream.succeed(\"b\")\n        }),\n        Stream.let(\"c\", (scope) => {\n          expect(scope).type.toBe<{ a: number; b: string }>()\n          return true\n        })\n      )\n    ).type.toBe<Stream.Stream<{ a: number; b: string; c: boolean }, never, never>>()\n\n    expect(\n      pipe(\n        Stream.succeed(1),\n        Stream.bindTo(\"a\"),\n        Stream.bind(\"b\", (scope) => {\n          expect(scope).type.toBe<{ a: number }>()\n          return Stream.succeed(\"b\")\n        }),\n        Stream.let(\"c\", (scope) => {\n          expect(scope).type.toBe<{ a: number; b: string }>()\n          return true\n        })\n      )\n    ).type.toBe<Stream.Stream<{ a: number; b: string; c: boolean }, never, never>>()\n  })\n\n  it(\"zipLatestAll\", () => {\n    expect(Stream.zipLatestAll()).type.toBe<Stream.Stream<never, never, never>>()\n\n    expect(Stream.zipLatestAll(numbers, numbersOrStrings)).type.toBe<\n      Stream.Stream<[number, string | number], never, never>\n    >()\n\n    expect(Stream.zipLatestAll(numbers, numbersOrStrings, Stream.fail(new Error(\"\")))).type.toBe<\n      Stream.Stream<[number, string | number, never], Error, never>\n    >()\n  })\n\n  it(\"mergeWithTag\", () => {\n    expect(\n      Stream.mergeWithTag(\n        {\n          a: pipe(Stream.make(0), Stream.tap(() => new Cause.NoSuchElementException())),\n          b: Stream.make(\"\")\n        },\n        { concurrency: 1 }\n      )\n    ).type.toBe<\n      Stream.Stream<\n        { _tag: \"a\"; value: number } | { _tag: \"b\"; value: string },\n        Cause.NoSuchElementException,\n        never\n      >\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/String.tst.ts",
    "content": "import { hole, String as Str } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"String\", () => {\n  it(\"concat\", () => {\n    expect(Str.concat(Str.capitalize(\"foo\"), Str.capitalize(\"bar\")))\n      .type.toBe(\"FooBar\")\n  })\n\n  it(\"toUpperCase\", () => {\n    expect(Str.toUpperCase(\"foo\"))\n      .type.toBe(\"FOO\")\n  })\n\n  it(\"toLowerCase\", () => {\n    expect(Str.toLowerCase(\"BAR\"))\n      .type.toBe(\"bar\")\n  })\n\n  it(\"capitalize\", () => {\n    expect(Str.capitalize(\"foo\"))\n      .type.toBe(\"Foo\")\n  })\n\n  it(\"uncapitalize\", () => {\n    expect(Str.uncapitalize(\"BAR\"))\n      .type.toBe(\"bAR\")\n  })\n\n  it(\"trim\", () => {\n    expect(Str.trim(\"   foo   \")).type.toBe(\"foo\")\n    expect(\n      Str.trim(`\n  \\t     foo\n  \\r\\n\n`)\n    ).type.toBe(\"foo\")\n  })\n\n  it(\"trimEnd\", () => {\n    expect(\n      Str.trimEnd(` foo\n  \\r\\n\n`)\n    ).type.toBe(\" foo\")\n  })\n\n  it(\"trimStart\", () => {\n    expect(\n      Str.trimStart(`\n   \\r\\n\\t   foo `)\n    ).type.toBe(\"foo \")\n  })\n\n  describe(\"String type helpers\", () => {\n    type FooCapitalCase = \"Foo\"\n    type BarCapitalCase = \"Bar\"\n\n    it(\"Str.Concat\", () => {\n      type Test = Str.Concat<FooCapitalCase, BarCapitalCase>\n      expect(hole<Test>())\n        .type.toBe<\"FooBar\">()\n    })\n\n    type LeadingSpaces = \"   foo\"\n    type TrailingSpaces = \"bar   \"\n    type LeadingAndTrailingSpaces = \"   baz   \"\n\n    type NewLines = `\n        foo\n  `\n    type NewLinesAndTabs = `\n      \\t\\t  foo\n  `\n    type CarriageReturns = `\n    \\r\\n foo\n  `\n\n    it(\"Str.TrimStart\", () => {\n      expect<Str.TrimStart<LeadingSpaces>>()\n        .type.toBe<\"foo\">()\n    })\n\n    it(\"Str.TrimEnd\", () => {\n      expect<Str.TrimEnd<TrailingSpaces>>()\n        .type.toBe<\"bar\">()\n    })\n\n    it(\"Str.Trim\", () => {\n      expect<Str.Trim<LeadingAndTrailingSpaces>>()\n        .type.toBe<\"baz\">()\n      expect<Str.Trim<NewLines>>()\n        .type.toBe<\"foo\">()\n      expect<Str.Trim<NewLinesAndTabs>>()\n        .type.toBe<\"foo\">()\n      expect<Str.Trim<CarriageReturns>>()\n        .type.toBe<\"foo\">()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Struct.tst.ts",
    "content": "import { hole, pipe, Struct } from \"effect\"\nimport { describe, expect, it, when } from \"tstyche\"\n\nconst asym = Symbol.for(\"effect/dtslint/a\")\nconst bsym = Symbol.for(\"effect/dtslint/b\")\nconst csym = Symbol.for(\"effect/dtslint/c\")\nconst dsym = Symbol.for(\"effect/dtslint/d\")\n\ndeclare const string$numberRecord: Record<string, number>\ndeclare const symbol$numberRecord: Record<symbol, number>\ndeclare const number$numberRecord: Record<number, number>\ndeclare const templateLiteral$numberRecord: Record<`a${string}`, number>\n\nconst stringStruct = { a: \"a\", b: 1, c: true }\nconst symbolStruct = { [asym]: \"a\", [bsym]: 1, [csym]: true }\nconst numberStruct = { 1: \"a\", 2: 1, 3: true }\ndeclare const optionalStringStruct: { a?: string; b: number; c: boolean }\n\ndescribe(\"Struct\", () => {\n  describe(\"evolve\", () => {\n    it(\"evolves a single field\", () => {\n      expect(Struct.evolve({ a: 1 }, {\n        a: (n) => {\n          expect(n).type.toBe<number>()\n          return n > 0\n        }\n      }))\n        .type.toBe<{ a: boolean }>()\n      expect(pipe(\n        { a: 1 },\n        Struct.evolve({\n          a: (n) => {\n            expect(n).type.toBe<number>()\n            return n > 0\n          }\n        })\n      ))\n        .type.toBe<{ a: boolean }>()\n    })\n\n    it(\"evolves multiple fields\", () => {\n      expect(Struct.evolve({ a: \"a\", b: 1 }, {\n        a: (s) => {\n          expect(s).type.toBe<string>()\n          return s.length\n        }\n      }))\n        .type.toBe<{ a: number; b: number }>()\n      expect(pipe(\n        { a: \"a\", b: 1 },\n        Struct.evolve({\n          a: (s) => {\n            expect(s).type.toBe<string>()\n            return s.length\n          }\n        })\n      ))\n        .type.toBe<{ a: number; b: number }>()\n    })\n\n    it(\"errors\", () => {\n      expect(Struct.evolve).type.not.toBeCallableWith(\n        { a: \"a\", b: 1 },\n        { a: (n: number) => n }\n      )\n      expect(Struct.evolve).type.not.toBeCallableWith(\n        hole<{ a: \"a\"; b: 1 }>(),\n        hole<Record<string, string>>()\n      )\n      expect(Struct.evolve).type.not.toBeCallableWith(\n        hole<{ a: \"a\"; b: 1 }>(),\n        hole<Record<string, (s: string) => null>>()\n      )\n      when(pipe).isCalledWith(\n        { a: \"a\", b: 1 },\n        expect(Struct.evolve).type.not.toBeCallableWith({ a: (n: number) => n })\n      )\n\n      when(pipe).isCalledWith(\n        hole<{ a: \"a\"; b: 1 }>(),\n        expect(Struct.evolve).type.not.toBeCallableWith(hole<Record<string, string>>())\n      )\n\n      when(pipe).isCalledWith(\n        hole<{ a: \"a\"; b: 1 }>(),\n        expect(Struct.evolve).type.not.toBeCallableWith(hole<Record<string, (s: string) => null>>())\n      )\n    })\n  })\n\n  describe(\"get\", () => {\n    it(\"returns unknown when getting a key from an empty object\", () => {\n      expect(pipe({}, Struct.get(\"a\")))\n        .type.toBe<unknown>()\n    })\n\n    it(\"gets a required property\", () => {\n      expect(pipe(stringStruct, Struct.get(\"a\")))\n        .type.toBe<string>()\n      expect(Struct.get(\"a\")(stringStruct))\n        .type.toBe<string>()\n\n      expect(pipe(symbolStruct, Struct.get(asym)))\n        .type.toBe<string>()\n      expect(Struct.get(asym)(symbolStruct))\n        .type.toBe<string>()\n\n      expect(pipe(numberStruct, Struct.get(1)))\n        .type.toBe<string>()\n      expect(Struct.get(1)(numberStruct))\n        .type.toBe<string>()\n    })\n\n    it(\"gets an optional property\", () => {\n      expect(pipe(optionalStringStruct, Struct.get(\"a\")))\n        .type.toBe<string | undefined>()\n      expect(Struct.get(\"a\")(optionalStringStruct))\n        .type.toBe<string | undefined>()\n    })\n\n    it(\"record\", () => {\n      expect(pipe(string$numberRecord, Struct.get(\"a\")))\n        .type.toBe<number | undefined>()\n      expect(Struct.get(\"a\")(string$numberRecord))\n        .type.toBe<number | undefined>()\n\n      expect(pipe(symbol$numberRecord, Struct.get(asym)))\n        .type.toBe<number | undefined>()\n      expect(Struct.get(asym)(symbol$numberRecord))\n        .type.toBe<number | undefined>()\n\n      expect(pipe(number$numberRecord, Struct.get(1)))\n        .type.toBe<number | undefined>()\n      expect(Struct.get(1)(number$numberRecord))\n        .type.toBe<number | undefined>()\n\n      expect(pipe(templateLiteral$numberRecord, Struct.get(\"ab\")))\n        .type.toBe<number | undefined>()\n      expect(Struct.get(\"ab\")(templateLiteral$numberRecord))\n        .type.toBe<number | undefined>()\n    })\n\n    it(\"struct + record\", () => {\n      expect(pipe(hole<Record<string, number> & { a: boolean }>(), Struct.get(\"a\")))\n        .type.toBe<boolean>()\n      when(pipe).isCalledWith(\n        hole<Record<string, number> & { a: boolean }>(),\n        expect(Struct.get).type.not.toBeCallableWith(\"b\")\n      )\n    })\n  })\n\n  describe(\"pick\", () => {\n    it(\"errors when picking a non-existent key\", () => {\n      when(pipe).isCalledWith(\n        stringStruct,\n        expect(Struct.pick).type.not.toBeCallableWith(\"d\")\n      )\n      expect(Struct.pick(\"d\")).type.not.toBeCallableWith(\n        stringStruct\n      )\n\n      when(pipe).isCalledWith(\n        symbolStruct,\n        expect(Struct.pick).type.not.toBeCallableWith(dsym)\n      )\n      expect(Struct.pick(dsym)).type.not.toBeCallableWith(\n        symbolStruct\n      )\n\n      when(pipe).isCalledWith(\n        numberStruct,\n        expect(Struct.pick).type.not.toBeCallableWith(4)\n      )\n      expect(Struct.pick(4)).type.not.toBeCallableWith(\n        numberStruct\n      )\n    })\n\n    it(\"returns a string record with unknown values when picking a dynamic string key\", () => {\n      expect(pipe(stringStruct, Struct.pick(\"d\" as string)))\n        .type.toBe<{ [x: string]: unknown }>()\n      expect(Struct.pick(\"d\" as string)(stringStruct))\n        .type.toBe<{ [x: string]: unknown }>()\n    })\n\n    it(\"returns a symbol record with unknown values when picking a dynamic symbol key\", () => {\n      expect(pipe(symbolStruct, Struct.pick(dsym as symbol)))\n        .type.toBe<{ [x: symbol]: unknown }>()\n      expect(Struct.pick(dsym as symbol)(symbolStruct))\n        .type.toBe<{ [x: symbol]: unknown }>()\n    })\n\n    it(\"returns a number record with unknown values when picking a dynamic numeric key\", () => {\n      expect(pipe(numberStruct, Struct.pick(4 as number)))\n        .type.toBe<{ [x: number]: unknown }>()\n      expect(Struct.pick(4 as number)(numberStruct))\n        .type.toBe<{ [x: number]: unknown }>()\n    })\n\n    it(\"struct with required properties\", () => {\n      expect(pipe(stringStruct, Struct.pick(\"a\", \"b\")))\n        .type.toBe<{ a: string; b: number }>()\n      expect(Struct.pick(stringStruct, \"a\", \"b\"))\n        .type.toBe<{ a: string; b: number }>()\n\n      expect(Struct.pick(symbolStruct, asym, bsym))\n        .type.toBe<{ [asym]: string; [bsym]: number }>()\n      expect(pipe(symbolStruct, Struct.pick(asym, bsym)))\n        .type.toBe<{ [asym]: string; [bsym]: number }>()\n\n      expect(Struct.pick(numberStruct, 1, 2))\n        .type.toBe<{ 1: string; 2: number }>()\n      expect(pipe(numberStruct, Struct.pick(1, 2)))\n        .type.toBe<{ 1: string; 2: number }>()\n    })\n\n    it(\"record\", () => {\n      expect(Struct.pick(string$numberRecord, \"a\", \"b\"))\n        .type.toBe<{ a?: number; b?: number }>()\n      expect(pipe(string$numberRecord, Struct.pick(\"a\", \"b\")))\n        .type.toBe<{ a?: number; b?: number }>()\n\n      expect(Struct.pick(symbol$numberRecord, asym, bsym))\n        .type.toBe<{ [asym]?: number; [bsym]?: number }>()\n      expect(pipe(symbol$numberRecord, Struct.pick(asym, bsym)))\n        .type.toBe<{ [asym]?: number; [bsym]?: number }>()\n\n      expect(Struct.pick(number$numberRecord, 1, 2))\n        .type.toBe<{ 1?: number; 2?: number }>()\n      expect(pipe(number$numberRecord, Struct.pick(1, 2)))\n        .type.toBe<{ 1?: number; 2?: number }>()\n\n      expect(Struct.pick(templateLiteral$numberRecord, \"aa\", \"ab\"))\n        .type.toBe<{ aa?: number; ab?: number }>()\n      expect(pipe(templateLiteral$numberRecord, Struct.pick(\"aa\", \"ab\")))\n        .type.toBe<{ aa?: number; ab?: number }>()\n    })\n\n    it(\"struct + record\", () => {\n      const sr = hole<Record<string, number> & { a: boolean }>()\n\n      expect(Struct.pick(sr, \"a\"))\n        .type.toBe<{ a: boolean }>()\n      expect(pipe(sr, Struct.pick(\"a\")))\n        .type.toBe<{ a: boolean }>()\n\n      // @tstyche fixme -- This doesn't work but it should\n      expect(Struct.pick).type.not.toBeCallableWith(sr, \"b\")\n\n      when(pipe).isCalledWith(\n        sr,\n        expect(Struct.pick).type.not.toBeCallableWith(\"b\")\n      )\n    })\n\n    it(\"struct with optional properties\", () => {\n      expect(Struct.pick(optionalStringStruct, \"a\", \"b\"))\n        .type.toBe<{ a?: string; b: number }>()\n      expect(pipe(optionalStringStruct, Struct.pick(\"a\", \"b\")))\n        .type.toBe<{ a?: string; b: number }>()\n    })\n  })\n\n  describe(\"omit\", () => {\n    it(\"errors when omitting a non-existent key\", () => {\n      when(pipe).isCalledWith(\n        stringStruct,\n        expect(Struct.omit).type.not.toBeCallableWith(\"d\")\n      )\n      expect(Struct.omit(\"d\")).type.not.toBeCallableWith(\n        stringStruct\n      )\n\n      when(pipe).isCalledWith(\n        symbolStruct,\n        expect(Struct.omit).type.not.toBeCallableWith(dsym)\n      )\n      expect(Struct.omit(dsym)).type.not.toBeCallableWith(\n        symbolStruct\n      )\n\n      when(pipe).isCalledWith(\n        numberStruct,\n        expect(Struct.omit).type.not.toBeCallableWith(4)\n      )\n      expect(Struct.omit(4)).type.not.toBeCallableWith(\n        numberStruct\n      )\n    })\n\n    it(\"struct\", () => {\n      expect(Struct.omit(stringStruct, \"a\"))\n        .type.toBe<{ b: number; c: boolean }>()\n      expect(pipe(stringStruct, Struct.omit(\"a\")))\n        .type.toBe<{ b: number; c: boolean }>()\n\n      expect(Struct.omit(symbolStruct, asym))\n        .type.toBe<{ [bsym]: number; [csym]: boolean }>()\n      expect(pipe(symbolStruct, Struct.omit(asym)))\n        .type.toBe<{ [bsym]: number; [csym]: boolean }>()\n\n      expect(Struct.omit(numberStruct, 1))\n        .type.toBe<{ 2: number; 3: boolean }>()\n      expect(pipe(numberStruct, Struct.omit(1)))\n        .type.toBe<{ 2: number; 3: boolean }>()\n    })\n\n    it(\"record\", () => {\n      expect(Struct.omit(string$numberRecord, \"a\"))\n        .type.toBe<{ [x: string]: number }>()\n      expect(pipe(string$numberRecord, Struct.omit(\"a\")))\n        .type.toBe<{ [x: string]: number }>()\n\n      expect(Struct.omit(symbol$numberRecord, asym))\n        .type.toBe<{ [x: symbol]: number }>()\n      expect(pipe(symbol$numberRecord, Struct.omit(asym)))\n        .type.toBe<{ [x: symbol]: number }>()\n\n      expect(Struct.omit(number$numberRecord, 1))\n        .type.toBe<{ [x: number]: number }>()\n      expect(pipe(number$numberRecord, Struct.omit(1)))\n        .type.toBe<{ [x: number]: number }>()\n\n      expect(Struct.omit(templateLiteral$numberRecord, \"aa\"))\n        .type.toBe<{ [x: `a${string}`]: number }>()\n      expect(pipe(templateLiteral$numberRecord, Struct.omit(\"aa\")))\n        .type.toBe<{ [x: `a${string}`]: number }>()\n    })\n  })\n\n  describe(\"entries\", () => {\n    it(\"excludes symbol keys\", () => {\n      const c = Symbol(\"c\")\n      const value = { a: \"a\", b: 1, [c]: 2 }\n      // should not include symbol keys\n      expect(Struct.entries(value)).type.toBe<Array<[\"a\" | \"b\", string | number]>>()\n      // when the object is passed as a parameter, the values should be narrowed\n      expect(Struct.entries({ a: \"a\", b: 1, [c]: 2 })).type.toBe<Array<[\"a\" | \"b\", \"a\" | 1]>>()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/TMap.tst.ts",
    "content": "import type { STM } from \"effect\"\nimport { pipe, TMap } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const string$number: TMap.TMap<string, number>\n\ndescribe(\"TMap\", () => {\n  it(\"removeIf\", () => {\n    expect(TMap.removeIf(string$number, (key) => key === \"aa\"))\n      .type.toBe<STM.STM<Array<[string, number]>>>()\n    expect(pipe(string$number, TMap.removeIf((key) => key === \"aa\")))\n      .type.toBe<STM.STM<Array<[string, number]>>>()\n\n    expect(TMap.removeIf(string$number, (key) => key === \"aa\", { discard: false }))\n      .type.toBe<STM.STM<Array<[string, number]>>>()\n    expect(pipe(string$number, TMap.removeIf((key) => key === \"aa\", { discard: false })))\n      .type.toBe<STM.STM<Array<[string, number]>>>()\n\n    expect(TMap.removeIf(string$number, (key) => key === \"aa\", { discard: true }))\n      .type.toBe<STM.STM<void>>()\n    expect(pipe(string$number, TMap.removeIf((key) => key === \"aa\", { discard: true })))\n      .type.toBe<STM.STM<void>>()\n  })\n\n  it(\"retainIf\", () => {\n    expect(TMap.retainIf(string$number, (key) => key === \"aa\"))\n      .type.toBe<STM.STM<Array<[string, number]>>>()\n\n    expect(TMap.retainIf(string$number, (key) => key === \"aa\", { discard: false }))\n      .type.toBe<STM.STM<Array<[string, number]>>>()\n\n    expect(pipe(string$number, TMap.retainIf((key) => key === \"aa\")))\n      .type.toBe<STM.STM<Array<[string, number]>>>()\n\n    expect(pipe(string$number, TMap.retainIf((key) => key === \"aa\", { discard: false })))\n      .type.toBe<STM.STM<Array<[string, number]>>>()\n\n    expect(TMap.retainIf(string$number, (key) => key === \"aa\", { discard: true }))\n      .type.toBe<STM.STM<void>>()\n\n    expect(pipe(string$number, TMap.retainIf((key) => key === \"aa\", { discard: true })))\n      .type.toBe<STM.STM<void>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/TSet.tst.ts",
    "content": "import type { STM } from \"effect\"\nimport { pipe, TSet } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const string: TSet.TSet<string>\n\ndescribe(\"TSet\", () => {\n  it(\"removeIf\", () => {\n    expect(TSet.removeIf(string, (key) => key === \"aa\"))\n      .type.toBe<STM.STM<Array<string>>>()\n    expect(pipe(string, TSet.removeIf((key) => key === \"aa\")))\n      .type.toBe<STM.STM<Array<string>>>()\n\n    expect(TSet.removeIf(string, (key) => key === \"aa\", { discard: false }))\n      .type.toBe<STM.STM<Array<string>>>()\n    expect(pipe(string, TSet.removeIf((key) => key === \"aa\", { discard: false })))\n      .type.toBe<STM.STM<Array<string>>>()\n\n    expect(TSet.removeIf(string, (key) => key === \"aa\", { discard: true }))\n      .type.toBe<STM.STM<void>>()\n    expect(pipe(string, TSet.removeIf((key) => key === \"aa\", { discard: true })))\n      .type.toBe<STM.STM<void>>()\n  })\n\n  it(\"retainIf\", () => {\n    expect(TSet.retainIf(string, (key) => key === \"aa\"))\n      .type.toBe<STM.STM<Array<string>>>()\n    expect(pipe(string, TSet.retainIf((key) => key === \"aa\")))\n      .type.toBe<STM.STM<Array<string>>>()\n\n    expect(TSet.retainIf(string, (key) => key === \"aa\", { discard: false }))\n      .type.toBe<STM.STM<Array<string>>>()\n    expect(pipe(string, TSet.retainIf((key) => key === \"aa\", { discard: false })))\n      .type.toBe<STM.STM<Array<string>>>()\n\n    expect(TSet.retainIf(string, (key) => key === \"aa\", { discard: true }))\n      .type.toBe<STM.STM<void>>()\n    expect(pipe(string, TSet.retainIf((key) => key === \"aa\", { discard: true })))\n      .type.toBe<STM.STM<void>>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Tuple.tst.ts",
    "content": "import { hole, pipe } from \"effect/Function\"\nimport * as T from \"effect/Tuple\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const string$number: [string, number]\ndeclare const readonlyString$number: readonly [string, number]\ndeclare const arrayOfNumbers: Array<number>\n\ndescribe(\"Tuple\", () => {\n  it(\"make\", () => {\n    expect(T.make(\"a\", 1, true))\n      .type.toBe<[string, number, boolean]>()\n  })\n\n  it(\"appendElement\", () => {\n    expect(T.appendElement(T.make(\"a\", 1), true))\n      .type.toBe<[string, number, boolean]>()\n    expect(pipe(T.make(\"a\", 1), T.appendElement(true)))\n      .type.toBe<[string, number, boolean]>()\n  })\n\n  describe(\"at\", () => {\n    it(\"should return undefined for an empty tuple\", () => {\n      expect(T.at(hole<[]>(), 0))\n        .type.toBe<undefined>()\n      expect(pipe(hole<[]>(), T.at(0)))\n        .type.toBe<undefined>()\n\n      expect(T.at(hole<readonly []>(), 0))\n        .type.toBe<undefined>()\n      expect(pipe(hole<readonly []>(), T.at(0)))\n        .type.toBe<undefined>()\n    })\n\n    it(\"should return the first element for [string, number]\", () => {\n      expect(T.at(string$number, 0))\n        .type.toBe<string>()\n      expect(pipe(string$number, T.at(0)))\n        .type.toBe<string>()\n\n      expect(T.at(readonlyString$number, 0))\n        .type.toBe<string>()\n      expect(pipe(readonlyString$number, T.at(0)))\n        .type.toBe<string>()\n    })\n\n    it(\"should return the second element for [string, number]\", () => {\n      expect(T.at(string$number, 1))\n        .type.toBe<number>()\n      expect(pipe(string$number, T.at(1)))\n        .type.toBe<number>()\n\n      expect(T.at(readonlyString$number, 1))\n        .type.toBe<number>()\n      expect(pipe(readonlyString$number, T.at(1)))\n        .type.toBe<number>()\n    })\n\n    it(\"should return undefined for an out-of-bound index\", () => {\n      expect(T.at(string$number, 2))\n        .type.toBe<undefined>()\n      expect(pipe(string$number, T.at(2)))\n        .type.toBe<undefined>()\n\n      expect(T.at(readonlyString$number, 2))\n        .type.toBe<undefined>()\n      expect(pipe(readonlyString$number, T.at(2)))\n        .type.toBe<undefined>()\n    })\n\n    it(\"should return string | number for a negative index\", () => {\n      expect(T.at(string$number, -1))\n        .type.toBe<string | number>()\n      expect(pipe(string$number, T.at(-1)))\n        .type.toBe<string | number>()\n\n      expect(T.at(readonlyString$number, -1))\n        .type.toBe<string | number>()\n      expect(pipe(readonlyString$number, T.at(-1)))\n        .type.toBe<string | number>()\n    })\n\n    it(\"should work with arrays\", () => {\n      expect(T.at(arrayOfNumbers, 1))\n        .type.toBe<number>()\n      expect(pipe(arrayOfNumbers, T.at(1)))\n        .type.toBe<number>()\n\n      expect(T.at(arrayOfNumbers, -1))\n        .type.toBe<number>()\n      expect(pipe(arrayOfNumbers, T.at(-1)))\n        .type.toBe<number>()\n    })\n  })\n\n  it(\"map\", () => {\n    expect(pipe(\n      T.make(\"a\", 1),\n      T.appendElement(true),\n      T.map((x) => {\n        expect(x).type.toBe<string | number | boolean>()\n        return false as const\n      })\n    ))\n      .type.toBe<[false, false, false]>()\n\n    expect(T.map([\"a\", 1, false], (x) => {\n      expect(x).type.toBe<string | number | boolean>()\n      return false as const\n    }))\n      .type.toBe<[false, false, false]>()\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Types.tst.ts",
    "content": "import type { Brand, Types } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Types\", () => {\n  it(\"TupleOf\", () => {\n    expect<Types.TupleOf<-1, number>>()\n      .type.toBe<never>()\n    expect<Types.TupleOf<0, number>>()\n      .type.toBe<[]>()\n    expect<Types.TupleOf<3, number>>()\n      .type.toBe<[number, number, number]>()\n  })\n\n  it(\"TupleOfAtLeast\", () => {\n    expect<Types.TupleOfAtLeast<3, number>>()\n      .type.toBe<[number, number, number, ...Array<number>]>()\n  })\n\n  it(\"UnionToIntersection\", () => {\n    expect<Types.UnionToIntersection<{ a: string } | { b: number }>>()\n      .type.toBe<{ a: string } & { b: number }>()\n  })\n\n  it(\"Tags\", () => {\n    expect<Types.Tags<string | { _tag: \"a\" } | { _tag: \"b\" }> & unknown>()\n      .type.toBe<\"a\" | \"b\">()\n  })\n\n  it(\"ExcludeTag\", () => {\n    expect<Types.ExcludeTag<string | { _tag: \"a\" } | { _tag: \"b\" }, \"a\"> & unknown>()\n      .type.toBe<string | { _tag: \"b\" }>()\n  })\n\n  it(\"ExtractTag\", () => {\n    expect<Types.ExtractTag<string | { _tag: \"a\"; a: number } | { _tag: \"b\"; b: number }, \"b\"> & unknown>()\n      .type.toBe<{ _tag: \"b\"; b: number }>()\n  })\n\n  it(\"Simplify\", () => {\n    expect<Types.Simplify<object & { a: number } & { b: number }>>()\n      .type.toBe<{ a: number; b: number }>()\n  })\n\n  describe(\"Equals\", () => {\n    it(\"should return true for identical types\", () => {\n      expect<Types.Equals<{ a: number }, { a: number }>>()\n        .type.toBe<true>()\n    })\n    it(\"should return false for different types\", () => {\n      expect<Types.Equals<{ a: number }, { b: number }>>()\n        .type.toBe<false>()\n    })\n  })\n\n  describe(\"MergeRight\", () => {\n    it(\"mutable overwrites mutable\", () => {\n      expect<Types.MergeRight<{ a: number; b: number }, { a: string; c: boolean }>>()\n        .type.toBe<{ a: string; c: boolean; b: number }>()\n    })\n\n    it(\"mutable overwrites readonly\", () => {\n      expect<Types.MergeRight<{ readonly a: number; b: number }, { a: string; c: boolean }>>()\n        .type.toBe<{ a: string; c: boolean; b: number }>()\n    })\n\n    it(\"readonly overwrites mutable\", () => {\n      expect<Types.MergeRight<{ a: number; b: number }, { readonly a: string; c: boolean }>>()\n        .type.toBe<{ readonly a: string; c: boolean; b: number }>()\n    })\n\n    it(\"required overwrites optional\", () => {\n      expect<Types.MergeRight<{ a?: number; b: number }, { a: string; c: boolean }>>()\n        .type.toBe<{ a: string; c: boolean; b: number }>()\n    })\n\n    it(\"optional overwrites optional\", () => {\n      expect<Types.MergeRight<{ a?: number; b: number }, { a?: string; c: boolean }>>()\n        .type.toBe<{ a?: string; c: boolean; b: number }>()\n    })\n\n    it(\"optional overwrites required\", () => {\n      expect<Types.MergeRight<{ a: number; b: number }, { a?: string; c: boolean }>>()\n        .type.toBe<{ a?: string; c: boolean; b: number }>()\n    })\n\n    it(\"readonly optional overwrites mutable required\", () => {\n      expect<Types.MergeRight<{ a: number; b: number }, { readonly a?: string; c: boolean }>>()\n        .type.toBe<{ readonly a?: string; c: boolean; b: number }>()\n    })\n\n    it(\"mutable required overwrites readonly optional\", () => {\n      expect<Types.MergeRight<{ readonly a?: number; b: number }, { a: string; c: boolean }>>()\n        .type.toBe<{ a: string; c: boolean; b: number }>()\n    })\n\n    it(\"optionality of non involved keys must be preserved\", () => {\n      expect<Types.MergeRight<{ readonly a?: number; b: number }, { readonly c?: string }>>()\n        .type.toBe<{ readonly c?: string; readonly a?: number; b: number }>()\n    })\n  })\n\n  describe(\"Mutable\", () => {\n    it(\"should convert a readonly object to mutable\", () => {\n      expect<Types.Simplify<Types.Mutable<{ readonly a: string; readonly b: number }>>>()\n        .type.toBe<{ a: string; b: number }>()\n    })\n\n    it(\"should convert a ReadonlyArray to a mutable array\", () => {\n      expect<Types.Mutable<ReadonlyArray<string>>>()\n        .type.toBe<Array<string>>()\n    })\n\n    it(\"should convert a readonly tuple to a mutable tuple\", () => {\n      expect<Types.Mutable<readonly [string, number]>>()\n        .type.toBe<[string, number]>()\n    })\n\n    it(\"should convert a readonly record to a mutable record\", () => {\n      expect<Types.Simplify<Types.Mutable<{ readonly [x: string]: number }>>>()\n        .type.toBe<{ [x: string]: number }>()\n    })\n  })\n\n  describe(\"DeepMutable\", () => {\n    type TaggedValues<A> = {\n      readonly _tag: string\n      readonly value: ReadonlyArray<A>\n    }\n\n    it(\"primitives and literals\", () => {\n      expect<\n        [\n          Types.DeepMutable<string>,\n          Types.DeepMutable<number>,\n          Types.DeepMutable<boolean>,\n          Types.DeepMutable<bigint>,\n          Types.DeepMutable<symbol>,\n          Types.DeepMutable<never>,\n          Types.DeepMutable<null>,\n          Types.DeepMutable<\"a\">,\n          Types.DeepMutable<1>,\n          Types.DeepMutable<true>\n        ]\n      >().type.toBe<[string, number, boolean, bigint, symbol, never, null, \"a\", 1, true]>()\n    })\n\n    it(\"functions\", () => {\n      expect<Types.DeepMutable<(arg: 1) => 2>>().type.toBe<(arg: 1) => 2>()\n    })\n\n    it(\"built in objects\", () => {\n      expect<\n        [\n          Types.DeepMutable<String>,\n          Types.DeepMutable<Number>,\n          Types.DeepMutable<Boolean>,\n          Types.DeepMutable<BigInt>,\n          Types.DeepMutable<Symbol>,\n          Types.DeepMutable<Date>,\n          Types.DeepMutable<RegExp>,\n          Types.DeepMutable<Generator>\n        ]\n      >().type.toBeAssignableTo<[String, Number, Boolean, BigInt, Symbol, Date, RegExp, Generator]>()\n    })\n\n    describe(\"Branded\", () => {\n      it(\"should leave a string brand unchanged\", () => {\n        type T = string & Brand.Brand<\"mybrand\">\n        expect<Types.DeepMutable<T>>().type.toBe<T>()\n      })\n\n      it(\"should leave a number brand unchanged\", () => {\n        type T = number & Brand.Brand<\"mybrand\">\n        expect<Types.DeepMutable<T>>().type.toBe<T>()\n      })\n\n      it(\"should leave a boolean brand unchanged\", () => {\n        type T = boolean & Brand.Brand<\"mybrand\">\n        expect<Types.DeepMutable<T>>().type.toBe<T>()\n      })\n\n      it(\"should leave a bigint brand unchanged\", () => {\n        type T = bigint & Brand.Brand<\"mybrand\">\n        expect<Types.DeepMutable<T>>().type.toBe<T>()\n      })\n\n      it(\"should leave a symbol brand unchanged\", () => {\n        type T = symbol & Brand.Brand<\"mybrand\">\n        expect<Types.DeepMutable<T>>().type.toBe<T>()\n      })\n    })\n\n    describe(\"Index Signature\", () => {\n      it(\"should convert an readonly Index Signature to a mutable Index Signature\", () => {\n        expect<Types.DeepMutable<{ readonly [x: string]: number }>>()\n          .type.toBe<{ [x: string]: number }>()\n      })\n\n      it(\"should leave an Index Signature unchanged\", () => {\n        expect<Types.DeepMutable<{ [_: string]: number }>>()\n          .type.toBe<{ [x: string]: number }>()\n      })\n    })\n\n    describe(\"Struct\", () => {\n      it(\"should support an empty object\", () => {\n        expect<Types.DeepMutable<{}>>()\n          .type.toBe<{}>()\n      })\n\n      it(\"should deeply mutate nested structs\", () => {\n        expect<Types.DeepMutable<ReadonlyArray<TaggedValues<TaggedValues<TaggedValues<boolean>>>>>>()\n          .type.toBe<\n          Array<{\n            _tag: string\n            value: Array<{\n              _tag: string\n              value: Array<{\n                _tag: string\n                value: Array<boolean>\n              }>\n            }>\n          }>\n        >()\n      })\n    })\n\n    describe(\"Array\", () => {\n      it(\"should convert a readonly empty array to a mutable empty array\", () => {\n        expect<Types.DeepMutable<readonly []>>()\n          .type.toBe<[]>()\n      })\n\n      it(\"should leave a mutable empty array unchanged\", () => {\n        expect<Types.DeepMutable<[]>>()\n          .type.toBe<[]>()\n      })\n\n      it(\"should convert a readonly array to a mutable array\", () => {\n        expect<Types.DeepMutable<ReadonlyArray<string>>>()\n          .type.toBe<Array<string>>()\n      })\n\n      it(\"should leave a mutable array unchanged\", () => {\n        expect<Types.DeepMutable<Array<string>>>()\n          .type.toBe<Array<string>>()\n      })\n    })\n\n    describe(\"Tuple\", () => {\n      it(\"should convert a readonly tuple\", () => {\n        expect<Types.DeepMutable<readonly [string, number, boolean]>>()\n          .type.toBe<[string, number, boolean]>()\n      })\n\n      it(\"should leave a mutable tuple unchanged\", () => {\n        expect<Types.DeepMutable<[string, number, boolean]>>()\n          .type.toBe<[string, number, boolean]>()\n      })\n    })\n\n    describe(\"ReadonlySet\", () => {\n      it(\"should convert a ReadonlySet to a mutable Set\", () => {\n        expect<Types.DeepMutable<ReadonlySet<{ readonly value: TaggedValues<number> }>>>()\n          .type.toBe<Set<{ value: { _tag: string; value: Array<number> } }>>()\n      })\n\n      it(\"should leave a mutable Set unchanged\", () => {\n        expect<Types.DeepMutable<Set<{ readonly value: TaggedValues<number> }>>>()\n          .type.toBe<Set<{ value: { _tag: string; value: Array<number> } }>>()\n      })\n    })\n\n    describe(\"ReadonlyMap\", () => {\n      it(\"should convert a ReadonlyMap to a mutable Map\", () => {\n        expect<Types.DeepMutable<ReadonlyMap<TaggedValues<string>, ReadonlySet<TaggedValues<number>>>>>()\n          .type.toBe<Map<{ _tag: string; value: Array<string> }, Set<{ _tag: string; value: Array<number> }>>>()\n      })\n\n      it(\"should leave a mutable Map unchanged\", () => {\n        expect<Types.DeepMutable<Map<TaggedValues<string>, ReadonlySet<TaggedValues<number>>>>>()\n          .type.toBe<Map<{ _tag: string; value: Array<string> }, Set<{ _tag: string; value: Array<number> }>>>()\n      })\n    })\n\n    describe(\"Union\", () => {\n      it(\"should convert a readonly union to a mutable union\", () => {\n        type T =\n          | ReadonlySet<{ readonly value: TaggedValues<number> }>\n          | ReadonlyMap<TaggedValues<string>, ReadonlySet<TaggedValues<number>>>\n        expect<Types.DeepMutable<T>>()\n          .type.toBe<\n          | Set<{ value: { _tag: string; value: Array<number> } }>\n          | Map<{ _tag: string; value: Array<string> }, Set<{ _tag: string; value: Array<number> }>>\n        >()\n      })\n\n      it(\"should leave a mutable union unchanged\", () => {\n        type T =\n          | ReadonlySet<{ readonly value: TaggedValues<number> }>\n          | ReadonlyMap<TaggedValues<string>, ReadonlySet<TaggedValues<number>>>\n        expect<Types.DeepMutable<T>>()\n          .type.toBe<\n          | Set<{ value: { _tag: string; value: Array<number> } }>\n          | Map<{ _tag: string; value: Array<string> }, Set<{ _tag: string; value: Array<number> }>>\n        >()\n      })\n    })\n  })\n\n  describe(\"MatchRecord\", () => {\n    it(\"should yield 1 when matching a record type\", () => {\n      expect<Types.MatchRecord<{ [x: string]: number }, 1, 0>>().type.toBe<1>()\n    })\n\n    it(\"should yield 0 when not matching a record type\", () => {\n      expect<Types.MatchRecord<{ a: number }, 1, 0>>().type.toBe<0>()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/Unify.tst.ts",
    "content": "import type {\n  Context,\n  Deferred,\n  Effect,\n  Exit,\n  Fiber,\n  FiberRef,\n  ManagedRuntime,\n  Micro,\n  Option,\n  Pool,\n  Queue,\n  RcRef,\n  Ref,\n  Resource,\n  ScopedRef,\n  STM,\n  Stream,\n  SubscriptionRef,\n  SynchronizedRef\n} from \"effect\"\nimport { Either, Unify } from \"effect\"\nimport { describe, expect, it } from \"tstyche\"\n\ndescribe(\"Unify\", () => {\n  describe(\"Unify\", () => {\n    it(\"should unify Context types\", () => {\n      expect<Unify.Unify<Context.Tag<0, 1> | Context.Tag<\"a\", \"b\">>>()\n        .type.toBe<Context.Tag<0, 1> | Context.Tag<\"a\", \"b\">>()\n    })\n\n    it(\"should unify Option types\", () => {\n      expect<Unify.Unify<Option.Option<number> | Option.Option<string>>>()\n        .type.toBe<Option.Option<string | number>>()\n    })\n\n    it(\"should unify Either types\", () => {\n      expect<Unify.Unify<Either.Either<\"RA\", \"LA\"> | Either.Either<\"RB\", \"LB\">>>()\n        .type.toBe<Either.Either<\"RA\" | \"RB\", \"LA\" | \"LB\">>()\n    })\n\n    it(\"should unify a mixed union of Either, Option, and primitive value\", () => {\n      expect<\n        Unify.Unify<\n          | Either.Either<\"RA\", \"LA\">\n          | Either.Either<\"RB\", \"LB\">\n          | Option.Option<number>\n          | Option.Option<string>\n          | 0\n        >\n      >().type.toBe<0 | Option.Option<string | number> | Either.Either<\"RA\" | \"RB\", \"LA\" | \"LB\">>()\n    })\n\n    it(\"should unify a record type\", () => {\n      expect<Unify.Unify<{ [k: string]: string }>>()\n        .type.toBe<{ [k: string]: string }>()\n    })\n\n    it(\"should unify Stream types\", () => {\n      expect<Unify.Unify<Stream.Stream<0, 1, 2> | Stream.Stream<\"a\", \"b\", \"c\">>>()\n        .type.toBe<Stream.Stream<0 | \"a\", \"b\" | 1, \"c\" | 2>>()\n    })\n\n    it(\"should unify Micro types\", () => {\n      expect<Unify.Unify<Micro.Micro<0, 1, 2> | Micro.Micro<\"a\", \"b\", \"c\">>>()\n        .type.toBe<Micro.Micro<0 | \"a\", \"b\" | 1, \"c\" | 2>>()\n    })\n\n    it(\"should unify Effect types\", () => {\n      expect<\n        Unify.Unify<\n          | Effect.Effect<0, 1, 2>\n          | Effect.Effect<\"a\", \"b\", \"c\">\n        >\n      >().type.toBe<Effect.Effect<0 | \"a\", \"b\" | 1, \"c\" | 2>>()\n    })\n\n    it(\"should unify STM types\", () => {\n      expect<\n        Unify.Unify<\n          | STM.STM<0, 1, 2>\n          | STM.STM<\"a\", \"b\", \"c\">\n        >\n      >().type.toBe<STM.STM<0 | \"a\", \"b\" | 1, \"c\" | 2>>()\n    })\n\n    it(\"should unify Exit types\", () => {\n      expect<Unify.Unify<Exit.Exit<0, 1> | Exit.Exit<\"a\", \"b\">>>()\n        .type.toBe<Exit.Exit<0 | \"a\", \"b\" | 1>>()\n    })\n\n    it(\"should unify Ref types\", () => {\n      expect<Unify.Unify<Ref.Ref<1> | Ref.Ref<\"a\">>>()\n        .type.toBe<Ref.Ref<1> | Ref.Ref<\"a\">>()\n    })\n\n    it(\"should unify SynchronizedRef types\", () => {\n      expect<\n        Unify.Unify<\n          | SynchronizedRef.SynchronizedRef<1>\n          | SynchronizedRef.SynchronizedRef<\"a\">\n        >\n      >()\n        .type.toBe<SynchronizedRef.SynchronizedRef<1> | SynchronizedRef.SynchronizedRef<\"a\">>()\n    })\n\n    it(\"should unify SubscriptionRef types\", () => {\n      expect<\n        Unify.Unify<\n          | SubscriptionRef.SubscriptionRef<1>\n          | SubscriptionRef.SubscriptionRef<\"a\">\n        >\n      >()\n        .type.toBe<SubscriptionRef.SubscriptionRef<1> | SubscriptionRef.SubscriptionRef<\"a\">>()\n    })\n\n    it(\"should unify RcRef types\", () => {\n      expect<Unify.Unify<RcRef.RcRef<1, 2> | RcRef.RcRef<\"a\", \"b\">>>()\n        .type.toBe<RcRef.RcRef<\"a\" | 1, \"b\" | 2>>()\n    })\n\n    it(\"should unify Deferred types\", () => {\n      expect<Unify.Unify<Deferred.Deferred<1, 2> | Deferred.Deferred<\"a\", \"b\">>>()\n        .type.toBe<Deferred.Deferred<1, 2> | Deferred.Deferred<\"a\", \"b\">>()\n    })\n\n    it(\"should unify FiberRef types\", () => {\n      expect<Unify.Unify<FiberRef.FiberRef<1> | FiberRef.FiberRef<\"a\">>>()\n        .type.toBe<FiberRef.FiberRef<1> | FiberRef.FiberRef<\"a\">>()\n    })\n\n    it(\"should unify Fiber types\", () => {\n      expect<Unify.Unify<Fiber.Fiber<1, 2> | Fiber.Fiber<\"a\", \"b\">>>()\n        .type.toBe<Fiber.Fiber<\"a\" | 1, \"b\" | 2>>()\n    })\n\n    it(\"should unify RuntimeFiber types\", () => {\n      expect<Unify.Unify<Fiber.RuntimeFiber<1, 2> | Fiber.RuntimeFiber<\"a\", \"b\">>>()\n        .type.toBe<Fiber.RuntimeFiber<\"a\" | 1, \"b\" | 2>>()\n    })\n\n    it(\"should unify ManagedRuntime types\", () => {\n      expect<\n        Unify.Unify<\n          | ManagedRuntime.ManagedRuntime<1, 2>\n          | ManagedRuntime.ManagedRuntime<\"a\", \"b\">\n        >\n      >().type.toBe<ManagedRuntime.ManagedRuntime<1, 2> | ManagedRuntime.ManagedRuntime<\"a\", \"b\">>()\n    })\n\n    it(\"should unify Queue types\", () => {\n      expect<Unify.Unify<Queue.Queue<1> | Queue.Queue<\"a\">>>()\n        .type.toBe<Queue.Queue<1> | Queue.Queue<\"a\">>()\n    })\n\n    it(\"should unify Dequeue types\", () => {\n      expect<Unify.Unify<Queue.Dequeue<1> | Queue.Dequeue<\"a\">>>()\n        .type.toBe<Queue.Dequeue<\"a\" | 1>>()\n    })\n\n    it(\"should unify Pool types\", () => {\n      expect<\n        Unify.Unify<\n          | Pool.Pool<1, 2>\n          | Pool.Pool<\"a\", \"b\">\n          | Pool.Pool<\"a\", \"c\">\n        >\n      >()\n        .type.toBe<Pool.Pool<1, 2> | Pool.Pool<\"a\", \"b\" | \"c\">>()\n    })\n\n    it(\"should unify ScopedRef types\", () => {\n      expect<Unify.Unify<ScopedRef.ScopedRef<1> | ScopedRef.ScopedRef<\"a\">>>()\n        .type.toBe<ScopedRef.ScopedRef<1> | ScopedRef.ScopedRef<\"a\">>()\n    })\n\n    it(\"should unify Resource types\", () => {\n      expect<\n        Unify.Unify<\n          | Resource.Resource<1>\n          | Resource.Resource<never, 2>\n          | Resource.Resource<1, 2>\n          | Resource.Resource<\"a\", \"b\">\n          | Resource.Resource<any, any>\n        >\n      >()\n        .type.toBe<\n        | Resource.Resource<1, never>\n        | Resource.Resource<never, 2>\n        | Resource.Resource<1, 2>\n        | Resource.Resource<\"a\", \"b\">\n        | Resource.Resource<any, any>\n      >()\n    })\n\n    it(\"should unify a huge union\", () => {\n      expect<\n        Unify.Unify<\n          | Context.Tag<0, 1>\n          | Context.Tag<\"a\", \"b\">\n          | Either.Either<1, 0>\n          | Either.Either<\"a\", \"b\">\n          | Option.Option<number>\n          | Option.Option<string>\n          | Effect.Effect<\"a\", \"b\", \"R\">\n          | Effect.Effect<1, 0, \"R1\">\n          | STM.STM<0, 1, 2>\n          | STM.STM<\"a\", \"b\", \"c\">\n          | Ref.Ref<1>\n          | Ref.Ref<\"a\">\n          | SynchronizedRef.SynchronizedRef<1>\n          | SynchronizedRef.SynchronizedRef<\"a\">\n          | SubscriptionRef.SubscriptionRef<1>\n          | SubscriptionRef.SubscriptionRef<\"a\">\n          | RcRef.RcRef<1, 0>\n          | RcRef.RcRef<\"a\", \"b\">\n          | Deferred.Deferred<1, 0>\n          | Deferred.Deferred<\"a\", \"b\">\n          | FiberRef.FiberRef<1>\n          | FiberRef.FiberRef<\"a\">\n          | Fiber.Fiber<1, 0>\n          | Fiber.Fiber<\"a\", \"b\">\n          | Fiber.RuntimeFiber<1, 0>\n          | Fiber.RuntimeFiber<\"a\", \"b\">\n          | Queue.Queue<1>\n          | Queue.Queue<\"a\">\n          | Queue.Dequeue<1>\n          | Queue.Dequeue<\"a\">\n          | Pool.Pool<1, 2>\n          | Pool.Pool<\"a\", \"b\">\n          | Pool.Pool<\"a\", \"c\">\n          | ScopedRef.ScopedRef<1>\n          | ScopedRef.ScopedRef<\"a\">\n          | Resource.Resource<1, 0>\n          | Resource.Resource<\"a\", \"b\">\n          | Effect.Latch\n          | ManagedRuntime.ManagedRuntime<1, 0>\n          | ManagedRuntime.ManagedRuntime<\"a\", \"b\">\n          | 0\n        >\n      >()\n        .type.toBe<\n        | Context.Tag<0, 1>\n        | Context.Tag<\"a\", \"b\">\n        | 0\n        | Option.Option<string | number>\n        | STM.STM<0 | \"a\", \"b\" | 1, \"c\" | 2>\n        | Ref.Ref<1>\n        | Ref.Ref<\"a\">\n        | SynchronizedRef.SynchronizedRef<1>\n        | SynchronizedRef.SynchronizedRef<\"a\">\n        | SubscriptionRef.SubscriptionRef<1>\n        | SubscriptionRef.SubscriptionRef<\"a\">\n        | Deferred.Deferred<\"a\", \"b\">\n        | FiberRef.FiberRef<1>\n        | FiberRef.FiberRef<\"a\">\n        | ManagedRuntime.ManagedRuntime<\"a\", \"b\">\n        | Queue.Queue<1>\n        | Queue.Queue<\"a\">\n        | Queue.Dequeue<\"a\" | 1>\n        | Pool.Pool<1, 2>\n        | Pool.Pool<\"a\", \"b\" | \"c\">\n        | ScopedRef.ScopedRef<1>\n        | ScopedRef.ScopedRef<\"a\">\n        | Resource.Resource<\"a\", \"b\">\n        | Deferred.Deferred<1, 0>\n        | Resource.Resource<1, 0>\n        | Effect.Latch\n        | ManagedRuntime.ManagedRuntime<1, 0>\n        | RcRef.RcRef<\"a\" | 1, 0 | \"b\">\n        | Fiber.Fiber<\"a\" | 1, 0 | \"b\">\n        | Fiber.RuntimeFiber<\"a\" | 1, 0 | \"b\">\n        | Either.Either<\"a\" | 1, 0 | \"b\">\n        | Effect.Effect<\"a\" | 1, 0 | \"b\", \"R\" | \"R1\">\n      >()\n    })\n  })\n\n  describe(\"unify\", () => {\n    it(\"should infer the type of Unify.unify for a function\", () => {\n      function f<N>(n: N) {\n        return Math.random() > 0 ? Either.right(n) : Either.left(\"ok\")\n      }\n      type Expected = <N>(n: N) => Either.Either<N, string>\n      expect(Unify.unify(f))\n        .type.toBe<Expected>()\n    })\n\n    it(\"should unify a value using Unify.unify\", () => {\n      expect(\n        Unify.unify(Math.random() > 0 ? Either.right(10) : Either.left(\"ok\"))\n      ).type.toBe<Either.Either<number, string>>()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/dtslint/tsconfig.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\".\"],\n  \"references\": [\n    { \"path\": \"../tsconfig.src.json\" },\n  ],\n  \"compilerOptions\": {\n    \"incremental\": false,\n    \"composite\": false,\n    \"noUnusedLocals\": false,\n    \"plugins\": [\n      {\n        \"name\": \"@effect/language-server\",\n        \"diagnostics\": false\n      }\n    ]\n  }\n}\n"
  },
  {
    "path": "packages/effect/package.json",
    "content": "{\n  \"name\": \"effect\",\n  \"version\": \"3.21.0\",\n  \"type\": \"module\",\n  \"license\": \"MIT\",\n  \"description\": \"The missing standard library for TypeScript, for writing production-grade software.\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/effect\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"typescript\",\n    \"error-handling\",\n    \"concurrency\",\n    \"observability\"\n  ],\n  \"keywords\": [\n    \"typescript\",\n    \"error-handling\",\n    \"concurrency\",\n    \"observability\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"test-types\": \"tstyche\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"devDependencies\": {\n    \"ajv\": \"^8.17.1\",\n    \"ast-types\": \"^0.14.2\",\n    \"tinybench\": \"^4.0.1\",\n    \"zod\": \"^3.24.4\"\n  },\n  \"dependencies\": {\n    \"@standard-schema/spec\": \"^1.0.0\",\n    \"fast-check\": \"^3.23.1\"\n  }\n}\n"
  },
  {
    "path": "packages/effect/schema-vs-zod.md",
    "content": "# Schema vs. Zod: Key Differences and Features\n\n`effect/Schema` provides similar functionality to `zod` (v3), with additional features and key differences that may suit specific use cases. Below is a summary of the main distinctions:\n\n1. **Bidirectional Transformations**\n   `effect/Schema` supports both decoding (transforming raw data into validated data) and encoding (transforming validated data back into a format for external use). This makes it suitable for scenarios where data needs to be sent or received over a network. In contrast, `zod` focuses primarily on decoding.\n\n2. **Integration with `effect`**\n   `effect/Schema` is designed to integrate with the `effect` library, leveraging features such as dependency tracking during transformations. This integration allows developers to incorporate schemas directly into `effect` workflows.\n\n3. **Customizable Through Annotations**\n   Annotations in `effect/Schema` provide a way to attach metadata to schemas. This can include custom error messages, fallback values, or any other additional information to enhance schema behavior. Annotations offer a structured approach to schema customization that goes beyond basic validations.\n\n4. **Functional Programming Style**\n   `effect/Schema` uses a style based on combinators and transformations. This approach provides greater flexibility when composing schemas and enables better tree shaking for optimized bundle sizes. On the other hand, `zod` uses a chainable API for defining schemas.\n\n## Parse, don't validate\n\n`effect/Schema` adheres to the principle of [parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/). This means that schemas are designed to parse input data into a validated and usable form, rather than simply checking if the data matches a set of rules. For example, instead of validating that a string conforms to a URL format (like `zod`'s `z.string().url()`), `effect/Schema` provides a schema to parse a string directly into a `URL` object.\n\nThe distinction between parsing and validating lies in the outcome:\n\n- Validation checks if data satisfies a set of rules but does not modify or transform it.\n- Parsing not only checks validity but also converts the data into a desired format or type.\n\nFor instance, `Schema.URL` transforms a string into a `URL` object, enabling direct use in your code without additional processing.\n\n**Example** (Parsing URL strings into `URL` objects)\n\n```ts\nimport { Schema } from \"effect\"\n\n//                   ┌─── The output type\n//                   │      ┌─── The input type\n//                   ▼      ▼\n//      ┌─── Schema<URL, string, never>\n//      ▼\nconst schema = Schema.URL\n\n// Parse a valid URL string\nconsole.log(Schema.decodeUnknownSync(Schema.URL)(\"https://example.com\"))\n// Output: URL { href: 'https://example.com/', ... } (instance of URL)\n\n// Attempt to parse an invalid URL\nconsole.log(Schema.decodeUnknownSync(Schema.URL)(\"example.com\"))\n/*\nthrows:\nParseError: URL\n└─ Transformation process failure\n   └─ Unable to decode \"example.com\" into a URL. Invalid URL\n*/\n```\n\n## Basic usage\n\nHere are a couple of examples to introduce the basic usage of `zod` and `effect/Schema`.\n\nWhile both libraries provide similar parsing features, `effect/Schema` uses [Either](https://effect.website/docs/data-types/either/) for safe parsing. The result is either `Either.right` (on success) or `Either.left` (on failure). In contrast, `zod` returns an object with `success` and `error` fields for safe parsing.\n\n**Example** (Creating and using a schema for strings)\n\nZod\n\n```ts\nimport { z } from \"zod\"\n\n// creating a schema for strings\nconst mySchema = z.string()\n\n// parsing\nmySchema.parse(\"tuna\") // => \"tuna\"\nmySchema.parse(12) // => throws ZodError\n\n// \"safe\" parsing (doesn't throw error if validation fails)\nmySchema.safeParse(\"tuna\") // => { success: true; data: \"tuna\" }\nmySchema.safeParse(12) // => { success: false; error: ZodError }\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\n// creating a schema for strings\nconst mySchema = Schema.String\n\n// parsing\nSchema.decodeUnknownSync(mySchema)(\"tuna\") // => \"tuna\"\nSchema.decodeUnknownSync(mySchema)(12) // => throws ParseError\n\n// \"safe\" parsing (doesn't throw error if validation fails)\nSchema.decodeUnknownEither(mySchema)(\"tuna\") // => Either.right(\"tuna\")\nSchema.decodeUnknownEither(mySchema)(12) // => Either.left(ParseError)\n```\n\n**Example** (Creating and using a schema for objects)\n\nZod\n\n```ts\nimport { z } from \"zod\"\n\nconst User = z.object({\n  username: z.string()\n})\n\nUser.parse({ username: \"Ludwig\" })\n\n// extract the inferred type\ntype User = z.infer<typeof User>\n// { username: string }\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  username: Schema.String\n})\n\nSchema.decodeUnknownSync(User)({ username: \"Ludwig\" })\n\n// extract the inferred type\ntype User = typeof User.Type\n// { readonly username: string }\n```\n\n## Naming Conventions\n\nThe naming conventions in `effect/Schema` are designed to be straightforward and logical, **focusing primarily on compatibility with JSON serialization**. This approach simplifies the understanding and use of schemas, especially for developers who are integrating web technologies where JSON is a standard data interchange format.\n\n### Overview of Naming Strategies\n\n**JSON-Compatible Types**\n\nSchemas that naturally serialize to JSON-compatible formats are named directly after their data types.\n\nFor instance:\n\n- `Schema.Date`: serializes JavaScript Date objects to ISO-formatted strings, a typical method for representing dates in JSON.\n- `Schema.Number`: used directly as it maps precisely to the JSON number type, requiring no special transformation to remain JSON-compatible.\n\n**Non-JSON-Compatible Types**\n\nWhen dealing with types that do not have a direct representation in JSON, the naming strategy incorporates additional details to indicate the necessary transformation. This helps in setting clear expectations about the schema's behavior:\n\nFor instance:\n\n- `Schema.DateFromSelf`: indicates that the schema handles `Date` objects, which are not natively JSON-serializable.\n- `Schema.NumberFromString`: this naming suggests that the schema processes numbers that are initially represented as strings, emphasizing the transformation from string to number when decoding.\n\nThe primary goal of these schemas is to ensure that domain objects can be easily serialized (\"encoded\") and deserialized (\"decoded\") for transmission over network connections, thus facilitating their transfer between different parts of an application or across different applications.\n\n### Rationale\n\nWhile JSON's ubiquity justifies its primary consideration in naming, the conventions also accommodate serialization for other types of transport. For instance, converting a `Date` to a string is a universally useful method for various communication protocols, not just JSON. Thus, the selected naming conventions serve as sensible defaults that prioritize clarity and ease of use, facilitating the serialization and deserialization processes across diverse technological environments.\n\n## Primitives\n\n| Feature  | Zod           | Schema                  |\n| -------- | ------------- | ----------------------- |\n| Strings  | `z.string()`  | `Schema.String`         |\n| Numbers  | `z.number()`  | `Schema.Number`         |\n| BigInts  | `z.bigint()`  | `Schema.BigIntFromSelf` |\n| Booleans | `z.boolean()` | `Schema.Boolean`        |\n| Dates    | `z.date()`    | `Schema.DateFromSelf`   |\n| Symbols  | `z.symbol()`  | `Schema.SymbolFromSelf` |\n\n**Empty Types**\n\n| Feature   | Zod             | Schema             |\n| --------- | --------------- | ------------------ |\n| Undefined | `z.undefined()` | `Schema.Undefined` |\n| Null      | `z.null()`      | `Schema.Null`      |\n| Void      | `z.void()`      | `Schema.Void`      |\n\n**Catch-All Types**\n\n| Feature | Zod           | Schema           |\n| ------- | ------------- | ---------------- |\n| Any     | `z.any()`     | `Schema.Any`     |\n| Unknown | `z.unknown()` | `Schema.Unknown` |\n\n**Never Type**\n\n| Feature | Zod         | Schema         |\n| ------- | ----------- | -------------- |\n| Never   | `z.never()` | `Schema.Never` |\n\n## Coercion for primitives\n\nNo direct equivalent in `effect/Schema`.\n\n## Literals\n\n| Feature          | Zod                        | Schema                                       | Differences                                                                                         |\n| ---------------- | -------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------- |\n| String Literal   | `z.literal(\"tuna\")`        | `Schema.Literal(\"tuna\")`                     |                                                                                                     |\n| Number Literal   | `z.literal(12)`            | `Schema.Literal(12)`                         |                                                                                                     |\n| BigInt Literal   | `z.literal(2n)`            | `Schema.Literal(2n)`                         |                                                                                                     |\n| Boolean Literal  | `z.literal(true)`          | `Schema.Literal(true)`                       |                                                                                                     |\n| Unique Symbol    | `z.literal(Symbol(\"foo\"))` | `Schema.UniqueSymbolFromSelf(Symbol(\"foo\"))` | Zod uses `z.literal`, while `effect/Schema` has a specific function for unique symbols.             |\n| Retrieving Value | `tuna.value // \"tuna\"`     | `tuna.literals // [\"tuna\"]`                  | Zod uses `.value` for a single literal, while Schema returns an array of literals with `.literals`. |\n\n## Strings\n\nThe following tables compare the string handling features in `zod` and `effect/Schema`.\n\n**String Validations**\n\n| Feature                 | zod                             | effect/Schema                                   | Differences                                                               |\n| ----------------------- | ------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------- |\n| Max Length              | `z.string().max(5)`             | `Schema.String.pipe(Schema.maxLength(5))`       | None                                                                      |\n| Min Length              | `z.string().min(5)`             | `Schema.String.pipe(Schema.minLength(5))`       | None                                                                      |\n| Exact Length            | `z.string().length(5)`          | `Schema.String.pipe(Schema.length(5))`          | None                                                                      |\n| Pattern Matching        | `z.string().regex(regex)`       | `Schema.String.pipe(Schema.pattern(regex))`     | None                                                                      |\n| Includes Substring      | `z.string().includes(string)`   | `Schema.String.pipe(Schema.includes(string))`   | None                                                                      |\n| Starts With             | `z.string().startsWith(string)` | `Schema.String.pipe(Schema.startsWith(string))` | None                                                                      |\n| Ends With               | `z.string().endsWith(string)`   | `Schema.String.pipe(Schema.endsWith(string))`   | None                                                                      |\n| UUID Validation         | `z.string().uuid()`             | `Schema.UUID`                                   | None                                                                      |\n| ULID Validation         | `z.string().ulid()`             | `Schema.ULID`                                   | None                                                                      |\n| Email Validation        | `z.string().email()`            | Not available                                   | `zod` provides built-in email validation, while `effect/Schema` does not. |\n| URL Validation          | `z.string().url()`              | Not available (see [URLs](#urls))               | `zod` supports URL validation, while `effect/Schema` does not.            |\n| Emoji Validation        | `z.string().emoji()`            | Not available                                   | `zod` provides emoji validation, while `effect/Schema` does not.          |\n| Nano ID Validation      | `z.string().nanoid()`           | Not available                                   | `zod` supports Nano ID validation, while `effect/Schema` does not.        |\n| CUID Validation         | `z.string().cuid()`             | Not available                                   | `zod` supports CUID validation, while `effect/Schema` does not.           |\n| CUID2 Validation        | `z.string().cuid2()`            | Not available                                   | `zod` supports CUID2 validation, while `effect/Schema` does not.          |\n| ISO Datetime Validation | `z.string().datetime()`         | Not available (see [Datetimes](#datetimes))     | `zod` supports ISO datetime validation, while `effect/Schema` does not.   |\n| `YYYY-MM-DD` format     | `z.string().date()`             | Not available (see [Datetimes](#datetimes))     | `zod` supports ISO date validation, while `effect/Schema` does not.       |\n| ISO Time Validation     | `z.string().time()`             | Not available                                   | `zod` supports ISO time validation, while `effect/Schema` does not.       |\n| ISO Duration Validation | `z.string().duration()`         | Not available                                   | `zod` supports ISO duration validation, while `effect/Schema` does not.   |\n| IP Address Validation   | `z.string().ip()`               | Not available                                   | `zod` supports IP address validation, while `effect/Schema` does not.     |\n| Base64 Validation       | `z.string().base64()`           | Not available                                   | `zod` supports base64 validation, while `effect/Schema` does not.         |\n\n**String Transformations**\n\n| Feature         | zod                        | effect/Schema      | Differences                                    |\n| --------------- | -------------------------- | ------------------ | ---------------------------------------------- |\n| Trim Whitespace | `z.string().trim()`        | `Schema.Trim`      | Syntax differs, but functionality is the same. |\n| Lowercase       | `z.string().toLowerCase()` | `Schema.Lowercase` | Syntax differs, but functionality is the same. |\n| Uppercase       | `z.string().toUpperCase()` | `Schema.Uppercase` | Syntax differs, but functionality is the same. |\n\n## Custom Error Messages\n\n| Feature                      | zod                                                       | effect/Schema                                                                         | Differences                                          |\n| ---------------------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------- |\n| Schema-Level Messages        | `z.string({ required_error, invalid_type_error })`        | `Schema.String.annotations({ message: () => \"Custom error\" })`                        | `effect/Schema` uses annotations for error messages. |\n| Validation-Specific Messages | `z.string().min(5, { message: \"Must be 5+ characters\" })` | `Schema.String.pipe(Schema.minLength(5, { message: () => \"Must be 5+ characters\" }))` |                                                      |\n\n**Example** (Custom error messages for strings)\n\nYou can customize some common error messages when creating a string schema.\n\nZod\n\n```ts\nconst name = z.string({\n  required_error: \"Name is required\",\n  invalid_type_error: \"Name must be a string\"\n})\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst name = Schema.String.annotations({\n  // No direct equivalent for required error\n  message: () => \"Name must be a string\"\n})\n```\n\n**Example** (Custom error messages for string length)\n\nWhen using validation methods, you can pass in an additional argument to provide a custom error message.\n\nZod\n\n```ts\nz.string().min(5, { message: \"Must be 5 or more characters long\" })\n```\n\nSchema\n\n```ts\nSchema.String.pipe(\n  Schema.minLength(5, { message: () => \"Must be 5 or more characters long\" })\n)\n```\n\n## URLs\n\nIn `zod`, the `z.string().url()` method validates string URLs. In `effect/Schema`, there is no direct equivalent. However, you can use `Schema.URL` to parse string URLs into `URL` objects.\n\n**Example** (Parsing URL strings into `URL` objects)\n\n```ts\nimport { Schema } from \"effect\"\n\n// Parse a valid URL string\nconsole.log(Schema.decodeUnknownSync(Schema.URL)(\"https://example.com\"))\n// Output: URL { href: 'https://example.com/', ... }\n\n// Attempt to parse an invalid URL\nconsole.log(Schema.decodeUnknownSync(Schema.URL)(\"example.com\"))\n/*\nthrows:\nParseError: URL\n└─ Transformation process failure\n   └─ Unable to decode \"example.com\" into a URL. Invalid URL\n*/\n```\n\n## Datetimes\n\nIn `zod`, the `z.string().datetime()` method validates ISO 8601 datetime strings. In `effect/Schema`, there is no direct equivalent. However, you can use `Schema.Date`, which parses a string into a `Date` object using the `new Date()` constructor.\n\n**Example** (Parsing date strings into `Date` objects)\n\n```ts\nimport { Schema } from \"effect\"\n\n// Parse a valid ISO 8601 date string\nconsole.log(Schema.decodeUnknownSync(Schema.Date)(\"2020-01-01\"))\n// Output: 2020-01-01T00:00:00.000Z (as Date object)\n\n// Parse a less strict date format\nconsole.log(Schema.decodeUnknownSync(Schema.Date)(\"2020-1-1\"))\n// Output: 2019-12-31T23:00:00.000Z (as Date object)\n\n// Attempt to parse an invalid date\nconsole.log(Schema.decodeUnknownSync(Schema.Date)(\"2020-01-32\"))\n/*\nthrows:\nParseError: Date\n└─ Predicate refinement failure\n   └─ Expected a valid Date, actual Invalid Date\n*/\n```\n\n## Numbers\n\nThe following tables provide a detailed comparison of number validations and custom error handling in `zod` and `effect/Schema`.\n\n**Number Validations**\n\n| Feature                  | zod                        | effect/Schema                                        | Differences                                                                  |\n| ------------------------ | -------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------- |\n| Greater Than             | `z.number().gt(5)`         | `Schema.Number.pipe(Schema.greaterThan(5))`          | None                                                                         |\n| Greater Than or Equal To | `z.number().gte(5)`        | `Schema.Number.pipe(Schema.greaterThanOrEqualTo(5))` | None                                                                         |\n| Less Than                | `z.number().lt(5)`         | `Schema.Number.pipe(Schema.lessThan(5))`             | None                                                                         |\n| Less Than or Equal To    | `z.number().lte(5)`        | `Schema.Number.pipe(Schema.lessThanOrEqualTo(5))`    | None                                                                         |\n| Integer Validation       | `z.number().int()`         | `Schema.Number.pipe(Schema.int())`                   | None                                                                         |\n| Positive Numbers         | `z.number().positive()`    | `Schema.Number.pipe(Schema.positive())`              | None                                                                         |\n| Non-Negative Numbers     | `z.number().nonnegative()` | `Schema.Number.pipe(Schema.nonNegative())`           | None                                                                         |\n| Negative Numbers         | `z.number().negative()`    | `Schema.Number.pipe(Schema.negative())`              | None                                                                         |\n| Non-Positive Numbers     | `z.number().nonpositive()` | `Schema.Number.pipe(Schema.nonPositive())`           | None                                                                         |\n| Divisible by a Number    | `z.number().multipleOf(5)` | `Schema.Number.pipe(Schema.multipleOf(5))`           | None                                                                         |\n| Finite Numbers           | `z.number().finite()`      | `Schema.Number.pipe(Schema.finite())`                | None                                                                         |\n| Safe Numbers             | `z.number().safe()`        | Not available                                        | `zod` includes validation for safe integers, while `effect/Schema` does not. |\n\n**Custom Error Messages**\n\n| Feature                     | zod                                            | effect/Schema                                                                      | Differences                                             |\n| --------------------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------- |\n| Custom Error for Validation | `z.number().lte(5, { message: \"my message\" })` | `Schema.Number.pipe(Schema.lessThanOrEqualTo(5, { message: () => \"my message\" }))` | Syntax differs between chainable and functional styles. |\n\n**Example** (Custom error messages for numbers)\n\nZod\n\n```ts\nz.number().lte(5, { message: \"my message\" })\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nSchema.Number.pipe(Schema.lessThanOrEqualTo(5, { message: () => \"my message\" }))\n```\n\n## BigInts\n\n| Feature                  | zod                         | effect/Schema                                               | Differences                                                              |\n| ------------------------ | --------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------ |\n| Greater Than             | `z.bigint().gt(5n)`         | `Schema.BigInt.pipe(Schema.greaterThanBigInt(5n))`          |                                                                          |\n| Greater Than or Equal To | `z.bigint().gte(5n)`        | `Schema.BigInt.pipe(Schema.greaterThanOrEqualToBigInt(5n))` |                                                                          |\n| Less Than                | `z.bigint().lt(5n)`         | `Schema.BigInt.pipe(Schema.lessThanBigInt(5n))`             |                                                                          |\n| Less Than or Equal To    | `z.bigint().lte(5n)`        | `Schema.BigInt.pipe(Schema.lessThanOrEqualToBigInt(5n))`    |                                                                          |\n| Positive                 | `z.bigint().positive()`     | `Schema.BigInt.pipe(Schema.positiveBigInt())`               |                                                                          |\n| Non-Negative             | `z.bigint().nonnegative()`  | `Schema.BigInt.pipe(Schema.nonNegativeBigInt())`            |                                                                          |\n| Negative                 | `z.bigint().negative()`     | `Schema.BigInt.pipe(Schema.negativeBigInt())`               |                                                                          |\n| Non-Positive             | `z.bigint().nonpositive()`  | `Schema.BigInt.pipe(Schema.nonPositiveBigInt())`            |                                                                          |\n| Multiple Of              | `z.bigint().multipleOf(5n)` | Not available                                               | `zod` supports `.multipleOf`, which is not available in `effect/Schema`. |\n\n## Zod enums\n\nThe table below summarizes the differences between `zod` and `effect/Schema` for enums.\n\n| Feature           | zod                                               | effect/Schema                                               | Differences                                                            |\n| ----------------- | ------------------------------------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------- |\n| Defining an Enum  | `z.enum([\"Salmon\", \"Tuna\", \"Trout\"])`             | `Schema.Literal(\"Salmon\", \"Tuna\", \"Trout\")`                 | `zod` accepts an array, while `effect/Schema` uses variadic arguments. |\n| Retrieving Values | `FishEnum.options // [\"Salmon\", \"Tuna\", \"Trout\"]` | `FishEnum.literals // readonly [\"Salmon\", \"Tuna\", \"Trout\"]` | `.options` vs `.literals`, with similar behavior.                      |\n\n**Example** (Creating an enum schema)\n\n```ts\nconst FishEnum = z.enum([\"Salmon\", \"Tuna\", \"Trout\"])\n\nFishEnum.options // [\"Salmon\", \"Tuna\", \"Trout\"];\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst FishEnum = Schema.Literal(\"Salmon\", \"Tuna\", \"Trout\")\n\nFishEnum.literals // readonly [\"Salmon\", \"Tuna\", \"Trout\"]\n```\n\n## Native enums\n\nBoth `zod` and `effect/Schema` support working with native TypeScript `enum`s, enabling validation of enum values.\n\n| Feature               | zod                    | effect/Schema          | Differences |\n| --------------------- | ---------------------- | ---------------------- | ----------- |\n| Defining Native Enums | `z.nativeEnum(Fruits)` | `Schema.Enums(Fruits)` |             |\n\n**Example** (Creating a schema for a native enum)\n\nZod\n\n```ts\nenum Fruits {\n  Apple,\n  Banana\n}\n\nconst FruitEnum = z.nativeEnum(Fruits)\n\ntype FruitEnum = z.infer<typeof FruitEnum> // Fruits\n\nFruitEnum.parse(Fruits.Apple) // passes\nFruitEnum.parse(Fruits.Banana) // passes\nFruitEnum.parse(0) // passes\nFruitEnum.parse(1) // passes\nFruitEnum.parse(3) // fails\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nenum Fruits {\n  Apple,\n  Banana\n}\n\nconst FruitEnum = Schema.Enums(Fruits)\n\ntype FruitEnum = typeof FruitEnum.Type // Fruits\n\nSchema.decodeUnknownSync(FruitEnum)(Fruits.Apple) // passes\nSchema.decodeUnknownSync(FruitEnum)(Fruits.Banana) // passes\nSchema.decodeUnknownSync(FruitEnum)(0) // passes\nSchema.decodeUnknownSync(FruitEnum)(1) // passes\nSchema.decodeUnknownSync(FruitEnum)(3) // fails\n```\n\n## Optionals\n\nIn both `zod` and `effect/Schema`, you can mark a field as optional, indicating that the property may or may not be present in the object.\n\n**Example** (Defining an optional field)\n\nZod\n\n```ts\nconst user = z.object({\n  username: z.string().optional()\n})\n\ntype Type = z.infer<typeof user> // { username?: string | undefined };\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst user = Schema.Struct({\n  username: Schema.optional(Schema.String)\n})\n\ntype Type = typeof user.Type // { readonly username?: string | undefined };\n```\n\n## Nullables\n\nBoth `zod` and `effect/Schema` allow you to define nullable fields, meaning a value can either have the specified type or be `null`.\n\n**Example** (Defining a nullable string)\n\nZod\n\n```ts\nconst nullableString = z.nullable(z.string())\n\nnullableString.parse(\"asdf\") // => \"asdf\"\nnullableString.parse(null) // => null\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst nullableString = Schema.NullOr(Schema.String)\n\nSchema.decodeUnknownSync(nullableString)(\"asdf\") // => \"asdf\"\nSchema.decodeUnknownSync(nullableString)(null) // => null\n```\n\n## Objects\n\nBoth `zod` and `effect/Schema` support object schemas where all properties are required by default.\n\n**Example** (Defining and inferring types of an object schema)\n\nZod\n\n```ts\n// all properties are required by default\nconst Dog = z.object({\n  name: z.string(),\n  age: z.number()\n})\n\n// extract the inferred type like this\ntype Dog = z.infer<typeof Dog>\n\n// equivalent to:\ntype Dog = {\n  name: string\n  age: number\n}\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\n// all properties are required by default\nconst Dog = Schema.Struct({\n  name: Schema.String,\n  age: Schema.Number\n})\n\n// extract the inferred type like this\ntype Dog = typeof Dog.Type\n\n// equivalent to:\ntype Dog = {\n  readonly name: string\n  readonly age: number\n}\n```\n\n### shape\n\nBoth libraries allow access to the individual schemas of object fields.\n\n**Example** (Accessing object field schemas)\n\nZod\n\n```ts\nDog.shape.name // => string schema\nDog.shape.age // => number schema\n```\n\nSchema\n\n```ts\nDog.fields.name // => String schema\nDog.fields.age // => Number schema\n```\n\n### keyof\n\nBoth libraries allow extracting the keys of an object schema as a new schema.\n\n**Example** (Creating a schema of object keys)\n\nZod\n\n```ts\nconst keySchema = Dog.keyof()\nkeySchema // ZodEnum<[\"name\", \"age\"]>\n```\n\nSchema\n\n```ts\n//      ┌─── Schema<\"name\" | \"age\", \"name\" | \"age\", never>\n//      ▼\nconst keySchema = Schema.keyof(Dog)\n```\n\n### extend\n\nObjects can be extended to include additional properties.\n\n**Example** (Extending an object schema)\n\nZod\n\n```ts\nconst DogWithBreed = Dog.extend({\n  breed: z.string()\n})\n```\n\nSchema\n\n```ts\nconst DogWithBreed = Dog.pipe(\n  Schema.extend(\n    Schema.Struct({\n      breed: Schema.String\n    })\n  )\n)\n\n// Recommended alternative when working with structs\nconst DogWithBreed = Schema.Struct({\n  ...Dog.fields,\n  breed: Schema.String\n})\n```\n\n### pick / omit\n\nFields can be selected or removed from an object schema.\n\n**Example** (Selecting or omitting fields)\n\nZod\n\n```ts\nconst Recipe = z.object({\n  id: z.string(),\n  name: z.string(),\n  ingredients: z.array(z.string())\n})\n\nconst JustTheName = Recipe.pick({ name: true })\n\nconst NoIDRecipe = Recipe.omit({ id: true })\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst Recipe = Schema.Struct({\n  id: Schema.String,\n  name: Schema.String,\n  ingredients: Schema.Array(Schema.String)\n})\n\nconst JustTheName = Recipe.pick(\"name\")\n\nconst NoIDRecipe = Recipe.omit(\"id\")\n```\n\n### partial\n\nAll fields in an object schema can be made optional.\n\n**Example** (Making all fields optional)\n\nZod\n\n```ts\nconst user = z.object({\n  email: z.string(),\n  username: z.string()\n})\n\nconst partialUser = user.partial()\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst user = Schema.Struct({\n  email: Schema.String,\n  username: Schema.String\n})\n\nconst partialUser = Schema.partial(user)\n```\n\n### deepPartial\n\nThere is no direct equivalent for deeply making all fields optional in `effect/Schema`.\n\n### required\n\nBoth `zod` and `effect/Schema` allow you to make all fields in an object schema required.\n\n**Example** (Converting optional fields to required)\n\nZod\n\n```ts\nconst user = z\n  .object({\n    email: z.string(),\n    username: z.string()\n  })\n  .partial() // Makes all fields optional\n\nconst requiredUser = user.required() // Converts all fields back to required\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst user = Schema.Struct({\n  email: Schema.String,\n  username: Schema.String\n}).pipe(Schema.partial) // Makes all fields optional\n\nconst requiredUser = Schema.required(user) // Converts all fields back to required\n```\n\n### passthrough\n\nBoth `zod` and `effect/Schema` provide mechanisms to handle additional properties that are not explicitly defined in an object schema. By default, both libraries ignore or strip these extra properties, but they also allow configurations to preserve them.\n\n- In `zod`, passthrough behavior is enabled using the `.passthrough()` method.\n- In `effect/Schema`, passthrough is achieved by setting the `onExcessProperty` option to `\"preserve\"` during decoding.\n\n**Example** (Handling additional properties)\n\nZod\n\n```ts\nconst person = z.object({\n  name: z.string()\n})\n\nperson.parse({\n  name: \"bob dylan\",\n  extraKey: 61\n})\n// => { name: \"bob dylan\" }\n// extraKey has been stripped\n\nperson.passthrough().parse({\n  name: \"bob dylan\",\n  extraKey: 61\n})\n// => { name: \"bob dylan\", extraKey: 61 }\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst person = Schema.Struct({\n  name: Schema.String\n})\n\nSchema.decodeUnknownSync(person)(\n  {\n    name: \"bob dylan\",\n    extraKey: 61\n  },\n  { onExcessProperty: \"preserve\" }\n)\n// => { name: \"bob dylan\", extraKey: 61 }\n```\n\n### strict\n\nBoth `zod` and `effect/Schema` offer a way to enforce strict object schemas, meaning that any additional properties not defined in the schema will result in an error.\n\n- In `zod`, strict mode is enabled using the `.strict()` method when defining an object schema.\n- In `effect/Schema`, strict behavior is configured during decoding by setting the `onExcessProperty` option to `\"error\"`.\n\n**Example** (Enforcing strict object validation)\n\nZod\n\n```ts\nconst person = z\n  .object({\n    name: z.string()\n  })\n  .strict()\n\nperson.parse({\n  name: \"bob dylan\",\n  extraKey: 61\n})\n// => throws ZodError\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst person = Schema.Struct({\n  name: Schema.String\n})\n\nSchema.decodeUnknownSync(person)(\n  {\n    name: \"bob dylan\",\n    extraKey: 61\n  },\n  { onExcessProperty: \"error\" }\n)\n// => throws ParseError\n```\n\n### catch\n\nBoth `zod` and `effect/Schema` allow you to define fallback values when parsing fails.\n\n- In `zod`, fallback values are set using the `.catch()` method when defining the schema.\n- In `effect/Schema`, fallback values are specified using the `decodingFallback` annotation.\n\n**Example** (Defining a fallback value for parsing failures)\n\nZod\n\n```ts\nimport { z } from \"zod\"\n\nconst schema = z.number().catch(42)\n\nconsole.log(schema.parse(5)) // => 5\nconsole.log(schema.parse(\"tuna\")) // => 42\n```\n\nSchema\n\n```ts\nimport { Either, Schema } from \"effect\"\n\nconst schema = Schema.Number.annotations({\n  decodingFallback: () => Either.right(42)\n})\n\nconsole.log(Schema.decodeUnknownSync(schema)(5)) // => 5\nconsole.log(Schema.decodeUnknownSync(schema)(\"tuna\")) // => 42\n```\n\n### catchall\n\nBoth `zod` and `effect/Schema` allow you to handle additional properties that are not explicitly defined in an object schema by applying a \"catchall\" schema to validate those properties. This is useful when dealing with objects that may include dynamic keys with uniform value types.\n\n- In `zod`, catchall behavior is enabled using the `.catchall()` method, which applies a specified schema to all additional properties.\n- In `effect/Schema`, this is achieved by combining a `Schema.Record` schema with the main object schema. The `Schema.Record` defines the type for dynamic keys and their values.\n\n**Example** (Defining a catchall schema for additional properties)\n\nZod\n\n````ts\nconst person = z\n  .object({\n    name: z.string()\n  })\n  .catchall(z.string())\n\nperson.parse({\n  name: \"bob dylan\",\n  validExtraKey: \"foo\" // works fine\n})\n\nperson.parse({\n  name: \"bob dylan\",\n  validExtraKey: false // fails\n})\n// => throws ZodError```\n````\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst person = Schema.Struct(\n  {\n    name: Schema.String\n  },\n  Schema.Record({ key: Schema.String, value: Schema.String })\n)\n\nSchema.decodeUnknownSync(person)({\n  name: \"bob dylan\",\n  validExtraKey: \"foo\" // works fine\n})\n\nSchema.decodeUnknownSync(person)({\n  name: \"bob dylan\",\n  validExtraKey: true // fails\n})\n// => throws ParseError\n```\n\n## Arrays\n\nBoth `zod` and `effect/Schema` provide tools for defining schemas for arrays. These schemas validate that the input is an array and that each element in the array conforms to the specified schema.\n\n- In `zod`, array schemas are created using the `z.array()` method, which takes a schema for the array elements as an argument.\n- In `effect/Schema`, array schemas are created using `Schema.Array()`, which also takes the schema for the elements as an argument.\n\n**Example** (Defining an array schema for strings)\n\nZod\n\n```ts\nconst stringArray = z.array(z.string())\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst stringArray = Schema.Array(Schema.String)\n```\n\n### Accessing the Element Schema\n\n- In `zod`, the `.element` property is used to access the schema for the elements in the array.\n- In `effect/Schema`, the `.value` property serves the same purpose.\n\n**Example** (Accessing the schema for array elements)\n\nZod\n\n```ts\nstringArray.element // => string schema\n```\n\nSchema\n\n```ts\nstringArray.value // => String schema\n```\n\n### Defining Non-Empty Arrays\n\n- `zod` provides the `.nonempty()` method for array schemas to enforce that the array has at least one element.\n- `effect/Schema` uses `Schema.NonEmptyArray()` for the same functionality.\n\n**Example** (Enforcing arrays to have at least one element)\n\nZod\n\n```ts\nconst nonEmptyStrings = z.string().array().nonempty()\n// the inferred type is now\n// [string, ...string[]]\n\nnonEmptyStrings.parse([]) // throws: \"Array cannot be empty\"\nnonEmptyStrings.parse([\"Ariana Grande\"]) // passes\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst nonEmptyStrings = Schema.NonEmptyArray(Schema.String)\n// the inferred type is now\n// [string, ...string[]]\n\nSchema.decodeUnknownSync(nonEmptyStrings)([])\n/* throws:\nError: readonly [string, ...string[]]\n└─ [0]\n   └─ is missing\n*/\nSchema.decodeUnknownSync(nonEmptyStrings)([\"Ariana Grande\"]) // passes\n```\n\n### Array Length Validations\n\n- In `zod`, methods like `.min()`, `.max()`, and `.length()` are chained to set array length constraints.\n- In `effect/Schema`, length validations are applied using `pipe()` with combinators like `Schema.minItems()`, `Schema.maxItems()`, and `Schema.itemsCount()`.\n\n**Example** (Validating array length)\n\nZod\n\n```ts\nz.string().array().min(5) // must contain 5 or more items\nz.string().array().max(5) // must contain 5 or fewer items\nz.string().array().length(5) // must contain 5 items exactly\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nSchema.Array(Schema.String).pipe(Schema.minItems(5)) // must contain 5 or more items\nSchema.Array(Schema.String).pipe(Schema.maxItems(5)) // must contain 5 or fewer items\nSchema.Array(Schema.String).pipe(Schema.itemsCount(5)) // must contain 5 items exactly\n```\n\n## Tuples\n\nBoth `zod` and `effect/Schema` support tuples, allowing you to define fixed-length arrays where each element has a specific type.\n\n- In `zod`, tuples are created using the `z.tuple()` method, where the schema for each element is defined in an array.\n- In `effect/Schema`, tuples are defined using `Schema.Tuple()` and accept the schemas for the elements as arguments.\n\nTuples in `effect/Schema` are readonly by default, whereas tuples in `zod` are mutable unless explicitly marked as readonly in TypeScript.\n\n**Example** (Defining a tuple schema)\n\nZod\n\n```ts\nconst athleteSchema = z.tuple([\n  z.string(), // name\n  z.number(), // jersey number\n  z.object({\n    pointsScored: z.number()\n  }) // statistics\n])\n\ntype Athlete = z.infer<typeof athleteSchema>\n// type Athlete = [string, number, { pointsScored: number }]\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst athleteSchema = Schema.Tuple(\n  Schema.String, // name\n  Schema.Number, // jersey number\n  Schema.Struct({\n    pointsScored: Schema.Number\n  }) // statistics\n)\n\n// type Athlete = readonly [string, number, { readonly pointsScored: number }]\ntype Athlete = typeof athleteSchema.Type\n```\n\n### Variadic Tuples\n\n- `zod` supports variadic tuples with the `.rest()` method, allowing the tuple to include additional elements of a specific type.\n- `effect/Schema` handles this by combining a fixed tuple schema with a rest schema for additional elements.\n\n**Example** (Defining a variadic tuple schema)\n\nZod\n\n```ts\nconst variadicTuple = z.tuple([z.string()]).rest(z.number())\nconst result = variadicTuple.parse([\"hello\", 1, 2, 3])\n// => [string, ...number[]];\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst variadicTuple = Schema.Tuple([Schema.String], Schema.Number)\n\nconst result = Schema.decodeUnknownSync(variadicTuple)([\"hello\", 1, 2, 3])\n// => readonly [string, ...number[]];\n```\n\n## Unions\n\nBoth `zod` and `effect/Schema` support unions, which allow you to define a schema that accepts multiple types.\n\n- In `zod`, unions are created using the `z.union()` method, where the possible schemas are passed as an array.\n- In `effect/Schema`, unions are defined using `Schema.Union()`, where the schemas are passed as arguments.\n\n**Discriminated Unions**\n\n- In `zod`, discriminated unions require explicitly using the `z.discriminatedUnion()` method for better performance and error messages.\n- In `effect/Schema`, discriminated unions are automatically detected, so no additional configuration is needed.\n\n**Example** (Defining a union schema)\n\nZod\n\n```ts\nconst stringOrNumber = z.union([z.string(), z.number()])\n\nstringOrNumber.parse(\"foo\") // passes\nstringOrNumber.parse(14) // passes\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst stringOrNumber = Schema.Union(Schema.String, Schema.Number)\n\nSchema.decodeUnknownSync(stringOrNumber)(\"foo\") // passes\nSchema.decodeUnknownSync(stringOrNumber)(14) // passes\n```\n\n## Discriminated unions\n\nIn `zod`, discriminated unions must be explicitly declared using the `z.discriminatedUnion()` method.\nIn `effect/Schema`, discriminated unions are automatically detected based on shared properties. No special method is needed to handle them.\n\n## Records\n\nBoth `zod` and `effect/Schema` support record schemas, which are used to validate objects with dynamic keys. A record schema ensures that all keys in the object match a specified schema and that their corresponding values also conform to a schema.\n\n`effect/Schema` generates readonly types by default.\n\n**Example** (Defining a record schema)\n\nZod\n\n```ts\nconst User = z.object({ name: z.string() })\n\nconst UserStore = z.record(z.string(), User)\n\n// type UserStore = Record<string, { name: string }>\ntype UserStore = z.infer<typeof UserStore>\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({ name: Schema.String })\n\nconst UserStore = Schema.Record({ key: Schema.String, value: User })\n\n// type UserStore = { readonly [x: string]: { readonly name: string; }; }\ntype UserStore = typeof UserStore.Type\n```\n\n## Maps\n\nBoth `zod` and `effect/Schema` support schemas for `Map` objects, where keys and values can be validated using specified schemas.\n\n- In `zod`, maps are defined using the `z.map()` method, where the first argument is the key schema and the second is the value schema.\n- In `effect/Schema`, maps are defined using `Schema.Map()` or `Schema.ReadonlyMap()` for mutable or readonly maps, respectively. Both require an object specifying the `key` and `value` schemas.\n\n`effect/Schema` provides an explicit `Schema.ReadonlyMap()` schema to generate readonly maps.\n\n**Example** (Defining a schema for maps)\n\nZod\n\n```ts\nconst stringNumberMap = z.map(z.string(), z.number())\n\ntype StringNumberMap = z.infer<typeof stringNumberMap>\n// type StringNumberMap = Map<string, number>\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst map1 = Schema.Map({ key: Schema.String, value: Schema.Number })\n\n// type Map1 = Map<string, number>\ntype Map1 = typeof map1.Type\n\nconst map2 = Schema.ReadonlyMap({ key: Schema.String, value: Schema.Number })\n\n// type Map2 = ReadonlyMap<string, number>\ntype Map2 = typeof map2.Type\n```\n\n## Sets\n\nBoth `zod` and `effect/Schema` support schemas for `Set` objects, allowing you to validate sets where all elements conform to a specified schema.\n\n- In `zod`, sets are created using the `z.set()` method, where you pass the schema for the elements of the set.\n- In `effect/Schema`, sets are defined using `Schema.Set()` or `Schema.ReadonlySet()` for mutable or readonly sets, respectively. Both require the schema for the elements.\n\n`effect/Schema` includes `Schema.ReadonlySet()` to explicitly define readonly sets.\n\n**Example** (Defining a schema for sets)\n\nZod\n\n```ts\nconst numberSet = z.set(z.number())\ntype NumberSet = z.infer<typeof numberSet>\n// type NumberSet = Set<number>\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst set1 = Schema.Set(Schema.Number)\n\n// type Set1 = Set<number>\ntype Set1 = typeof set1.Type\n\nconst set2 = Schema.ReadonlySet(Schema.Number)\n\n// type Set2 = ReadonlySet<number>\ntype Set2 = typeof set2.Type\n```\n\n## Intersections\n\nIn `zod`, intersections are used to combine multiple schemas into one, requiring the input to satisfy all the combined schemas.\n\n`effect/Schema` does not have a direct equivalent for intersections. However, similar behavior can be achieved using `Schema.extend()` to merge two or more struct schemas, or by spreading fields from multiple schemas into a new `Schema.Struct()`.\n\n## Recursive types\n\nBoth `zod` and `effect/Schema` support defining recursive types, which are types that reference themselves. Recursive types are commonly used for hierarchical data structures such as trees, graphs, or nested categories.\n\n- In `zod`, recursion is achieved using the `z.lazy()` method, which defers the evaluation of the schema until it is referenced.\n- In `effect/Schema`, recursion is handled using the `Schema.suspend()` function, which delays the resolution of the schema.\n\n**Example** (Defining a recursive schema for categories)\n\nZod\n\n```ts\nconst baseCategorySchema = z.object({\n  name: z.string()\n})\n\ntype Category = z.infer<typeof baseCategorySchema> & {\n  subcategories: Category[]\n}\n\nconst categorySchema: z.ZodType<Category> = baseCategorySchema.extend({\n  subcategories: z.lazy(() => categorySchema.array())\n})\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst baseCategorySchema = Schema.Struct({\n  name: Schema.String\n})\n\ntype Category = Schema.Schema.Type<typeof baseCategorySchema> & {\n  readonly subcategories: ReadonlyArray<Category>\n}\n\nconst categorySchema: Schema.Schema<Category> = Schema.Struct({\n  ...baseCategorySchema.fields,\n  subcategories: Schema.suspend(() => Schema.Array(categorySchema))\n})\n```\n\n## Promises\n\nNo direct equivalent in `effect/Schema`.\n\n## Instanceof\n\nBoth `zod` and `effect/Schema` support validating instances of classes or constructors using their `instanceof` functionality.\n\n- In `zod`, the `z.instanceof()` method is used to create a schema that validates if an input is an instance of a specified class or constructor.\n- In `effect/Schema`, the `Schema.instanceOf()` method provides the same functionality, taking the target class as an argument.\n\n**Example** (Validating instances of a class)\n\nZod\n\n```ts\nclass Test {\n  name: string = \"name\"\n}\n\nconst TestSchema = z.instanceof(Test)\n\nconst blob: any = \"whatever\"\nTestSchema.parse(new Test()) // passes\nTestSchema.parse(blob) // throws\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nclass Test {\n  name: string = \"name\"\n}\n\nconst TestSchema = Schema.instanceOf(Test)\n\nconst blob: any = \"whatever\"\n\nSchema.decodeUnknownSync(TestSchema)(new Test()) // passes\nSchema.decodeUnknownSync(TestSchema)(blob) // throws\n```\n\n## Functions\n\nNo direct equivalent in `effect/Schema`.\n\n## Preprocess\n\nNo direct equivalent in `effect/Schema`.\n\n## Custom schemas\n\nBoth `zod` and `effect/Schema` allow you to define custom schemas for validation scenarios that fall outside the scope of built-in schema types.\n\n- In `zod`, custom schemas are created using the `z.custom()` method. This method allows you to define a validation function that returns a boolean indicating whether the input is valid.\n- In `effect/Schema`, custom schemas are created using the `Schema.declare()` function. This approach provides more flexibility by allowing you to define the input and output types, parsing logic, and error handling.\n\nSee the [Schema.declare](https://effect.website/docs/schema/advanced-usage/#declaring-new-data-types) documentation for more details.\n\n## refine / superRefine\n\nBoth `zod` and `effect/Schema` allow you to add custom validation rules to existing schemas. These rules are useful for applying constraints that go beyond the basic validation logic provided by the libraries' built-in schema types.\n\n- In `zod`, you can use `.refine()` to apply a single validation rule or `.superRefine()` for more complex validations that require access to the validation context (e.g., adding multiple errors).\n- In `effect/Schema`, you can use `Schema.filter()` for simple validations or `Schema.filterEffect()` to include asynchronous or effectful validation logic.\n\nSee the [Schema.filter](https://effect.website/docs/schema/filters/) and [Schema.filterEffect](https://effect.website/docs/schema/transformations/#effectful-filters) documentation for more details.\n\n## transform\n\nBoth `zod` and `effect/Schema` provide functionality to transform input data into a desired format during parsing. Transformations are useful when you need to derive new values, normalize input, or map raw data into a structure that is more convenient for further processing. While the capabilities of the two libraries overlap, there are differences in how transformations are defined and applied.\n\n- In `zod`, the `.transform()` method is used to apply a transformation function directly to the schema.\n- In `effect/Schema`, transformations are applied using `Schema.transform()` or `Schema.transformOrFail()` for additional error handling during the transformation process.\n\nSee the [transform](https://effect.website/docs/schema/transformations/#transform) and [transformOrFail](https://effect.website/docs/schema/transformations/#transformorfail) documentation for more details.\n\n## describe\n\nBoth `zod` and `effect/Schema` allow you to attach descriptive metadata to schemas. This feature is useful for documentation, error reporting, or providing additional context about a schema's purpose. The description does not affect validation or parsing; it serves purely as a human-readable explanation.\n\n- In `zod`, descriptions are added using the `.describe()` method, which accepts a string describing the schema.\n- In `effect/Schema`, descriptions are added using the `annotations()` method, where the `description` is included as a metadata property.\n\n**Example** (Adding a description to a schema)\n\nZod\n\n```ts\nconst documentedString = z\n  .string()\n  .describe(\"A useful bit of text, if you know what to do with it.\")\ndocumentedString.description // A useful bit of text…\n```\n\nSchema\n\n```ts\nimport { Schema, SchemaAST } from \"effect\"\n\nconst documentedString = Schema.String.annotations({\n  description: \"A useful bit of text, if you know what to do with it.\"\n})\n\nconsole.log(SchemaAST.getDescriptionAnnotation(documentedString.ast))\n/*\nOutput:\n{\n  _id: 'Option',\n  _tag: 'Some',\n  value: 'A useful bit of text, if you know what to do with it.'\n}\n*/\n```\n\n## nullish\n\nBoth `zod` and `effect/Schema` provide support for schemas that allow values to be `null` or `undefined` in addition to a specified type.\n\n- In `zod`, you use the `.nullish()` method to extend a schema to allow `null` or `undefined` values in addition to the specified type.\n- In `effect/Schema`, the equivalent is achieved with `Schema.NullishOr()`, where you pass the desired type.\n\n**Example** (Defining a schema that allows `null` or `undefined` values)\n\nZod\n\n```ts\nconst nullishString = z.string().nullish() // string | null | undefined\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst nullishString = Schema.NullishOr(Schema.String) // string | null | undefined\n```\n\n## brand\n\nBoth `zod` and `effect/Schema` support branding, a feature that allows you to tag types with a unique identifier without changing their runtime behavior. Branding is useful when you need stronger type distinctions for otherwise identical structures, preventing accidental misuse or mixing of similar types.\n\n- In `zod`, branding is applied using the `.brand<>()` method on a schema, where you specify the brand name as a generic type argument.\n- In `effect/Schema`, branding is achieved by using the `Schema.brand()` function in combination with the `pipe()` method.\n\n**Example** (Defining a branded schema)\n\nZod\n\n```ts\nconst Cat = z.object({ name: z.string() }).brand<\"Cat\">()\n```\n\nSchema\n\n```ts\nimport { Schema } from \"effect\"\n\nconst Cat = Schema.Struct({ name: Schema.String }).pipe(Schema.brand(\"Cat\"))\n```\n\n## readonly\n\nNo equivalent as it's the default behavior.\n"
  },
  {
    "path": "packages/effect/src/.index.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nexport {\n  /**\n   * @since 2.0.0\n   */\n  absurd,\n  /**\n   * @since 2.0.0\n   */\n  flow,\n  /**\n   * @since 2.0.0\n   */\n  hole,\n  /**\n   * @since 2.0.0\n   */\n  identity,\n  /**\n   * @since 2.0.0\n   */\n  pipe,\n  /**\n   * @since 2.0.0\n   */\n  unsafeCoerce\n} from \"./Function.js\"\n"
  },
  {
    "path": "packages/effect/src/Arbitrary.ts",
    "content": "/**\n * @since 3.10.0\n */\n\nimport * as Arr from \"./Array.js\"\nimport * as FastCheck from \"./FastCheck.js\"\nimport { globalValue } from \"./GlobalValue.js\"\nimport * as errors_ from \"./internal/schema/errors.js\"\nimport * as schemaId_ from \"./internal/schema/schemaId.js\"\nimport * as util_ from \"./internal/schema/util.js\"\nimport * as Option from \"./Option.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport type * as Schema from \"./Schema.js\"\nimport * as SchemaAST from \"./SchemaAST.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface LazyArbitrary<A> {\n  (fc: typeof FastCheck): FastCheck.Arbitrary<A>\n}\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport interface ArbitraryGenerationContext {\n  readonly maxDepth: number\n  readonly depthIdentifier?: string\n  readonly constraints?: StringConstraints | NumberConstraints | BigIntConstraints | DateConstraints | ArrayConstraints\n}\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type ArbitraryAnnotation<A, TypeParameters extends ReadonlyArray<any> = readonly []> = (\n  ...arbitraries: [\n    ...{ readonly [K in keyof TypeParameters]: LazyArbitrary<TypeParameters[K]> },\n    ctx: ArbitraryGenerationContext\n  ]\n) => LazyArbitrary<A>\n\n/**\n * Returns a LazyArbitrary for the `A` type of the provided schema.\n *\n * @category arbitrary\n * @since 3.10.0\n */\nexport const makeLazy = <A, I, R>(schema: Schema.Schema<A, I, R>): LazyArbitrary<A> => {\n  const description = getDescription(schema.ast, [])\n  return go(description, { maxDepth: 2 })\n}\n\n/**\n * Returns a fast-check Arbitrary for the `A` type of the provided schema.\n *\n * @category arbitrary\n * @since 3.10.0\n */\nexport const make = <A, I, R>(schema: Schema.Schema<A, I, R>): FastCheck.Arbitrary<A> => makeLazy(schema)(FastCheck)\n\ninterface StringConstraints {\n  readonly _tag: \"StringConstraints\"\n  readonly constraints: FastCheck.StringSharedConstraints\n  readonly pattern?: string\n}\n\n/** @internal */\nexport const makeStringConstraints = (options: {\n  readonly minLength?: number | undefined\n  readonly maxLength?: number | undefined\n  readonly pattern?: string | undefined\n}): StringConstraints => {\n  const out: Types.Mutable<StringConstraints> = {\n    _tag: \"StringConstraints\",\n    constraints: {}\n  }\n  if (Predicate.isNumber(options.minLength)) {\n    out.constraints.minLength = options.minLength\n  }\n  if (Predicate.isNumber(options.maxLength)) {\n    out.constraints.maxLength = options.maxLength\n  }\n  if (Predicate.isString(options.pattern)) {\n    out.pattern = options.pattern\n  }\n  return out\n}\n\ninterface NumberConstraints {\n  readonly _tag: \"NumberConstraints\"\n  readonly constraints: FastCheck.FloatConstraints\n  readonly isInteger: boolean\n}\n\n/** @internal */\nexport const makeNumberConstraints = (options: {\n  readonly isInteger?: boolean | undefined\n  readonly min?: unknown\n  readonly minExcluded?: boolean | undefined\n  readonly max?: unknown\n  readonly maxExcluded?: boolean | undefined\n  readonly noNaN?: boolean | undefined\n  readonly noDefaultInfinity?: boolean | undefined\n}): NumberConstraints => {\n  const out: Types.Mutable<NumberConstraints> = {\n    _tag: \"NumberConstraints\",\n    constraints: {},\n    isInteger: options.isInteger ?? false\n  }\n  if (Predicate.isNumber(options.min)) {\n    out.constraints.min = Math.fround(options.min)\n  }\n  if (Predicate.isBoolean(options.minExcluded)) {\n    out.constraints.minExcluded = options.minExcluded\n  }\n  if (Predicate.isNumber(options.max)) {\n    out.constraints.max = Math.fround(options.max)\n  }\n  if (Predicate.isBoolean(options.maxExcluded)) {\n    out.constraints.maxExcluded = options.maxExcluded\n  }\n  if (Predicate.isBoolean(options.noNaN)) {\n    out.constraints.noNaN = options.noNaN\n  }\n  if (Predicate.isBoolean(options.noDefaultInfinity)) {\n    out.constraints.noDefaultInfinity = options.noDefaultInfinity\n  }\n  return out\n}\n\ninterface BigIntConstraints {\n  readonly _tag: \"BigIntConstraints\"\n  readonly constraints: FastCheck.BigIntConstraints\n}\n\n/** @internal */\nexport const makeBigIntConstraints = (options: {\n  readonly min?: bigint | undefined\n  readonly max?: bigint | undefined\n}): BigIntConstraints => {\n  const out: Types.Mutable<BigIntConstraints> = {\n    _tag: \"BigIntConstraints\",\n    constraints: {}\n  }\n  if (Predicate.isBigInt(options.min)) {\n    out.constraints.min = options.min\n  }\n  if (Predicate.isBigInt(options.max)) {\n    out.constraints.max = options.max\n  }\n  return out\n}\n\ninterface ArrayConstraints {\n  readonly _tag: \"ArrayConstraints\"\n  readonly constraints: FastCheck.ArrayConstraints\n}\n\n/** @internal */\nexport const makeArrayConstraints = (options: {\n  readonly minLength?: unknown\n  readonly maxLength?: unknown\n}): ArrayConstraints => {\n  const out: Types.Mutable<ArrayConstraints> = {\n    _tag: \"ArrayConstraints\",\n    constraints: {}\n  }\n  if (Predicate.isNumber(options.minLength)) {\n    out.constraints.minLength = options.minLength\n  }\n  if (Predicate.isNumber(options.maxLength)) {\n    out.constraints.maxLength = options.maxLength\n  }\n  return out\n}\n\ninterface DateConstraints {\n  readonly _tag: \"DateConstraints\"\n  readonly constraints: FastCheck.DateConstraints\n}\n\n/** @internal */\nexport const makeDateConstraints = (options: {\n  readonly min?: Date | undefined\n  readonly max?: Date | undefined\n  readonly noInvalidDate?: boolean | undefined\n}): DateConstraints => {\n  const out: Types.Mutable<DateConstraints> = {\n    _tag: \"DateConstraints\",\n    constraints: {}\n  }\n  if (Predicate.isDate(options.min)) {\n    out.constraints.min = options.min\n  }\n  if (Predicate.isDate(options.max)) {\n    out.constraints.max = options.max\n  }\n  if (Predicate.isBoolean(options.noInvalidDate)) {\n    out.constraints.noInvalidDate = options.noInvalidDate\n  }\n  return out\n}\n\ntype Refinements = ReadonlyArray<SchemaAST.Refinement>\n\ninterface Base {\n  readonly path: ReadonlyArray<PropertyKey>\n  readonly refinements: Refinements\n  readonly annotations: ReadonlyArray<ArbitraryAnnotation<any, any>>\n}\n\ninterface StringKeyword extends Base {\n  readonly _tag: \"StringKeyword\"\n  readonly constraints: ReadonlyArray<StringConstraints>\n}\n\ninterface NumberKeyword extends Base {\n  readonly _tag: \"NumberKeyword\"\n  readonly constraints: ReadonlyArray<NumberConstraints>\n}\n\ninterface BigIntKeyword extends Base {\n  readonly _tag: \"BigIntKeyword\"\n  readonly constraints: ReadonlyArray<BigIntConstraints>\n}\n\ninterface DateFromSelf extends Base {\n  readonly _tag: \"DateFromSelf\"\n  readonly constraints: ReadonlyArray<DateConstraints>\n}\n\ninterface Declaration extends Base {\n  readonly _tag: \"Declaration\"\n  readonly typeParameters: ReadonlyArray<Description>\n  readonly ast: SchemaAST.AST\n}\n\ninterface TupleType extends Base {\n  readonly _tag: \"TupleType\"\n  readonly constraints: ReadonlyArray<ArrayConstraints>\n  readonly elements: ReadonlyArray<{\n    readonly isOptional: boolean\n    readonly description: Description\n  }>\n  readonly rest: ReadonlyArray<Description>\n}\n\ninterface TypeLiteral extends Base {\n  readonly _tag: \"TypeLiteral\"\n  readonly propertySignatures: ReadonlyArray<{\n    readonly isOptional: boolean\n    readonly name: PropertyKey\n    readonly value: Description\n  }>\n  readonly indexSignatures: ReadonlyArray<{\n    readonly parameter: Description\n    readonly value: Description\n  }>\n}\n\ninterface Union extends Base {\n  readonly _tag: \"Union\"\n  readonly members: ReadonlyArray<Description>\n}\n\ninterface Suspend extends Base {\n  readonly _tag: \"Suspend\"\n  readonly id: string\n  readonly ast: SchemaAST.AST\n  readonly description: () => Description\n}\n\ninterface Ref extends Base {\n  readonly _tag: \"Ref\"\n  readonly id: string\n  readonly ast: SchemaAST.AST\n}\n\ninterface NeverKeyword extends Base {\n  readonly _tag: \"NeverKeyword\"\n  readonly ast: SchemaAST.AST\n}\n\ninterface Keyword extends Base {\n  readonly _tag: \"Keyword\"\n  readonly value:\n    | \"UndefinedKeyword\"\n    | \"VoidKeyword\"\n    | \"UnknownKeyword\"\n    | \"AnyKeyword\"\n    | \"BooleanKeyword\"\n    | \"SymbolKeyword\"\n    | \"ObjectKeyword\"\n}\n\ninterface Literal extends Base {\n  readonly _tag: \"Literal\"\n  readonly literal: SchemaAST.LiteralValue\n}\n\ninterface UniqueSymbol extends Base {\n  readonly _tag: \"UniqueSymbol\"\n  readonly symbol: symbol\n}\n\ninterface Enums extends Base {\n  readonly _tag: \"Enums\"\n  readonly enums: ReadonlyArray<readonly [string, string | number]>\n  readonly ast: SchemaAST.AST\n}\n\ninterface TemplateLiteral extends Base {\n  readonly _tag: \"TemplateLiteral\"\n  readonly head: string\n  readonly spans: ReadonlyArray<{\n    readonly description: Description\n    readonly literal: string\n  }>\n}\n\ntype Description =\n  | Declaration\n  | NeverKeyword\n  | Keyword\n  | Literal\n  | UniqueSymbol\n  | Enums\n  | TemplateLiteral\n  | StringKeyword\n  | NumberKeyword\n  | BigIntKeyword\n  | DateFromSelf\n  | TupleType\n  | TypeLiteral\n  | Union\n  | Suspend\n  | Ref\n\nconst getArbitraryAnnotation = SchemaAST.getAnnotation<ArbitraryAnnotation<any, any>>(SchemaAST.ArbitraryAnnotationId)\n\nconst getASTConstraints = (ast: SchemaAST.AST) => {\n  const TypeAnnotationId = ast.annotations[SchemaAST.SchemaIdAnnotationId]\n  if (Predicate.isPropertyKey(TypeAnnotationId)) {\n    const out = ast.annotations[TypeAnnotationId]\n    if (Predicate.isReadonlyRecord(out)) {\n      return out\n    }\n  }\n}\n\nconst idMemoMap = globalValue(\n  Symbol.for(\"effect/Arbitrary/IdMemoMap\"),\n  () => new Map<SchemaAST.AST, string>()\n)\n\nlet counter = 0\n\nfunction wrapGetDescription(\n  f: (ast: SchemaAST.AST, description: Description) => Description,\n  g: (ast: SchemaAST.AST, path: ReadonlyArray<PropertyKey>) => Description\n): (ast: SchemaAST.AST, path: ReadonlyArray<PropertyKey>) => Description {\n  return (ast, path) => f(ast, g(ast, path))\n}\n\nfunction parseMeta(ast: SchemaAST.AST): [SchemaAST.SchemaIdAnnotation | undefined, Record<string | symbol, unknown>] {\n  const jsonSchema = SchemaAST.getJSONSchemaAnnotation(ast).pipe(\n    Option.filter(Predicate.isReadonlyRecord),\n    Option.getOrUndefined\n  )\n  const schemaId = Option.getOrElse(SchemaAST.getSchemaIdAnnotation(ast), () => undefined)\n  const schemaParams = Option.fromNullable(schemaId).pipe(\n    Option.map((id) => ast.annotations[id]),\n    Option.filter(Predicate.isReadonlyRecord),\n    Option.getOrUndefined\n  )\n  return [schemaId, { ...schemaParams, ...jsonSchema }]\n}\n\n/** @internal */\nexport const getDescription = wrapGetDescription(\n  (ast, description) => {\n    const annotation = getArbitraryAnnotation(ast)\n    if (Option.isSome(annotation)) {\n      return {\n        ...description,\n        annotations: [...description.annotations, annotation.value]\n      }\n    }\n    return description\n  },\n  (ast, path) => {\n    const [schemaId, meta] = parseMeta(ast)\n    switch (ast._tag) {\n      case \"Refinement\": {\n        const from = getDescription(ast.from, path)\n        switch (from._tag) {\n          case \"StringKeyword\":\n            return {\n              ...from,\n              constraints: [...from.constraints, makeStringConstraints(meta)],\n              refinements: [...from.refinements, ast]\n            }\n          case \"NumberKeyword\": {\n            const c = schemaId === schemaId_.NonNaNSchemaId ?\n              makeNumberConstraints({ noNaN: true }) :\n              schemaId === schemaId_.FiniteSchemaId || schemaId === schemaId_.JsonNumberSchemaId ?\n              makeNumberConstraints({ noDefaultInfinity: true, noNaN: true }) :\n              makeNumberConstraints({\n                isInteger: \"type\" in meta && meta.type === \"integer\",\n                noNaN: undefined,\n                noDefaultInfinity: undefined,\n                min: meta.exclusiveMinimum ?? meta.minimum,\n                minExcluded: \"exclusiveMinimum\" in meta ? true : undefined,\n                max: meta.exclusiveMaximum ?? meta.maximum,\n                maxExcluded: \"exclusiveMaximum\" in meta ? true : undefined\n              })\n            return {\n              ...from,\n              constraints: [...from.constraints, c],\n              refinements: [...from.refinements, ast]\n            }\n          }\n          case \"BigIntKeyword\": {\n            const c = getASTConstraints(ast)\n            return {\n              ...from,\n              constraints: c !== undefined ? [...from.constraints, makeBigIntConstraints(c)] : from.constraints,\n              refinements: [...from.refinements, ast]\n            }\n          }\n          case \"TupleType\":\n            return {\n              ...from,\n              constraints: [\n                ...from.constraints,\n                makeArrayConstraints({\n                  minLength: meta.minItems,\n                  maxLength: meta.maxItems\n                })\n              ],\n              refinements: [...from.refinements, ast]\n            }\n          case \"DateFromSelf\":\n            return {\n              ...from,\n              constraints: [...from.constraints, makeDateConstraints(meta)],\n              refinements: [...from.refinements, ast]\n            }\n          default:\n            return {\n              ...from,\n              refinements: [...from.refinements, ast]\n            }\n        }\n      }\n      case \"Declaration\": {\n        if (schemaId === schemaId_.DateFromSelfSchemaId) {\n          return {\n            _tag: \"DateFromSelf\",\n            constraints: [makeDateConstraints(meta)],\n            path,\n            refinements: [],\n            annotations: []\n          }\n        }\n        return {\n          _tag: \"Declaration\",\n          typeParameters: ast.typeParameters.map((ast) => getDescription(ast, path)),\n          path,\n          refinements: [],\n          annotations: [],\n          ast\n        }\n      }\n      case \"Literal\": {\n        return {\n          _tag: \"Literal\",\n          literal: ast.literal,\n          path,\n          refinements: [],\n          annotations: []\n        }\n      }\n      case \"UniqueSymbol\": {\n        return {\n          _tag: \"UniqueSymbol\",\n          symbol: ast.symbol,\n          path,\n          refinements: [],\n          annotations: []\n        }\n      }\n      case \"Enums\": {\n        return {\n          _tag: \"Enums\",\n          enums: ast.enums,\n          path,\n          refinements: [],\n          annotations: [],\n          ast\n        }\n      }\n      case \"TemplateLiteral\": {\n        return {\n          _tag: \"TemplateLiteral\",\n          head: ast.head,\n          spans: ast.spans.map((span) => ({\n            description: getDescription(span.type, path),\n            literal: span.literal\n          })),\n          path,\n          refinements: [],\n          annotations: []\n        }\n      }\n      case \"StringKeyword\":\n        return {\n          _tag: \"StringKeyword\",\n          constraints: [],\n          path,\n          refinements: [],\n          annotations: []\n        }\n      case \"NumberKeyword\":\n        return {\n          _tag: \"NumberKeyword\",\n          constraints: [],\n          path,\n          refinements: [],\n          annotations: []\n        }\n      case \"BigIntKeyword\":\n        return {\n          _tag: \"BigIntKeyword\",\n          constraints: [],\n          path,\n          refinements: [],\n          annotations: []\n        }\n      case \"TupleType\":\n        return {\n          _tag: \"TupleType\",\n          constraints: [],\n          elements: ast.elements.map((element, i) => ({\n            isOptional: element.isOptional,\n            description: getDescription(element.type, [...path, i])\n          })),\n          rest: ast.rest.map((element, i) => getDescription(element.type, [...path, i])),\n          path,\n          refinements: [],\n          annotations: []\n        }\n      case \"TypeLiteral\":\n        return {\n          _tag: \"TypeLiteral\",\n          propertySignatures: ast.propertySignatures.map((ps) => ({\n            isOptional: ps.isOptional,\n            name: ps.name,\n            value: getDescription(ps.type, [...path, ps.name])\n          })),\n          indexSignatures: ast.indexSignatures.map((is) => ({\n            parameter: getDescription(is.parameter, path),\n            value: getDescription(is.type, path)\n          })),\n          path,\n          refinements: [],\n          annotations: []\n        }\n      case \"Union\":\n        return {\n          _tag: \"Union\",\n          members: ast.types.map((member, i) => getDescription(member, [...path, i])),\n          path,\n          refinements: [],\n          annotations: []\n        }\n      case \"Suspend\": {\n        const memoId = idMemoMap.get(ast)\n        if (memoId !== undefined) {\n          return {\n            _tag: \"Ref\",\n            id: memoId,\n            ast,\n            path,\n            refinements: [],\n            annotations: []\n          }\n        }\n        counter++\n        const id = `__id-${counter}__`\n        idMemoMap.set(ast, id)\n        return {\n          _tag: \"Suspend\",\n          id,\n          ast,\n          description: () => getDescription(ast.f(), path),\n          path,\n          refinements: [],\n          annotations: []\n        }\n      }\n      case \"Transformation\":\n        return getDescription(ast.to, path)\n      case \"NeverKeyword\":\n        return {\n          _tag: \"NeverKeyword\",\n          path,\n          refinements: [],\n          annotations: [],\n          ast\n        }\n      default: {\n        return {\n          _tag: \"Keyword\",\n          value: ast._tag,\n          path,\n          refinements: [],\n          annotations: []\n        }\n      }\n    }\n  }\n)\n\nfunction getMax(n1: Date | undefined, n2: Date | undefined): Date | undefined\nfunction getMax(n1: bigint | undefined, n2: bigint | undefined): bigint | undefined\nfunction getMax(n1: number | undefined, n2: number | undefined): number | undefined\nfunction getMax(\n  n1: bigint | number | Date | undefined,\n  n2: bigint | number | Date | undefined\n): bigint | number | Date | undefined {\n  return n1 === undefined ? n2 : n2 === undefined ? n1 : n1 <= n2 ? n2 : n1\n}\n\nfunction getMin(n1: Date | undefined, n2: Date | undefined): Date | undefined\nfunction getMin(n1: bigint | undefined, n2: bigint | undefined): bigint | undefined\nfunction getMin(n1: number | undefined, n2: number | undefined): number | undefined\nfunction getMin(\n  n1: bigint | number | Date | undefined,\n  n2: bigint | number | Date | undefined\n): bigint | number | Date | undefined {\n  return n1 === undefined ? n2 : n2 === undefined ? n1 : n1 <= n2 ? n1 : n2\n}\n\nconst getOr = (a: boolean | undefined, b: boolean | undefined): boolean | undefined => {\n  return a === undefined ? b : b === undefined ? a : a || b\n}\n\nfunction mergePattern(pattern1: string | undefined, pattern2: string | undefined): string | undefined {\n  if (pattern1 === undefined) {\n    return pattern2\n  }\n  if (pattern2 === undefined) {\n    return pattern1\n  }\n  return `(?:${pattern1})|(?:${pattern2})`\n}\n\nfunction mergeStringConstraints(c1: StringConstraints, c2: StringConstraints): StringConstraints {\n  return makeStringConstraints({\n    minLength: getMax(c1.constraints.minLength, c2.constraints.minLength),\n    maxLength: getMin(c1.constraints.maxLength, c2.constraints.maxLength),\n    pattern: mergePattern(c1.pattern, c2.pattern)\n  })\n}\n\nfunction buildStringConstraints(description: StringKeyword): StringConstraints | undefined {\n  return description.constraints.length === 0\n    ? undefined\n    : description.constraints.reduce(mergeStringConstraints)\n}\n\nfunction mergeNumberConstraints(c1: NumberConstraints, c2: NumberConstraints): NumberConstraints {\n  return makeNumberConstraints({\n    isInteger: c1.isInteger || c2.isInteger,\n    min: getMax(c1.constraints.min, c2.constraints.min),\n    minExcluded: getOr(c1.constraints.minExcluded, c2.constraints.minExcluded),\n    max: getMin(c1.constraints.max, c2.constraints.max),\n    maxExcluded: getOr(c1.constraints.maxExcluded, c2.constraints.maxExcluded),\n    noNaN: getOr(c1.constraints.noNaN, c2.constraints.noNaN),\n    noDefaultInfinity: getOr(c1.constraints.noDefaultInfinity, c2.constraints.noDefaultInfinity)\n  })\n}\n\nfunction buildNumberConstraints(description: NumberKeyword): NumberConstraints | undefined {\n  return description.constraints.length === 0\n    ? undefined\n    : description.constraints.reduce(mergeNumberConstraints)\n}\n\nfunction mergeBigIntConstraints(c1: BigIntConstraints, c2: BigIntConstraints): BigIntConstraints {\n  return makeBigIntConstraints({\n    min: getMax(c1.constraints.min, c2.constraints.min),\n    max: getMin(c1.constraints.max, c2.constraints.max)\n  })\n}\n\nfunction buildBigIntConstraints(description: BigIntKeyword): BigIntConstraints | undefined {\n  return description.constraints.length === 0\n    ? undefined\n    : description.constraints.reduce(mergeBigIntConstraints)\n}\n\nfunction mergeDateConstraints(c1: DateConstraints, c2: DateConstraints): DateConstraints {\n  return makeDateConstraints({\n    min: getMax(c1.constraints.min, c2.constraints.min),\n    max: getMin(c1.constraints.max, c2.constraints.max),\n    noInvalidDate: getOr(c1.constraints.noInvalidDate, c2.constraints.noInvalidDate)\n  })\n}\n\nfunction buildDateConstraints(description: DateFromSelf): DateConstraints | undefined {\n  return description.constraints.length === 0\n    ? undefined\n    : description.constraints.reduce(mergeDateConstraints)\n}\n\nconst constArrayConstraints = makeArrayConstraints({})\n\nfunction mergeArrayConstraints(c1: ArrayConstraints, c2: ArrayConstraints): ArrayConstraints {\n  return makeArrayConstraints({\n    minLength: getMax(c1.constraints.minLength, c2.constraints.minLength),\n    maxLength: getMin(c1.constraints.maxLength, c2.constraints.maxLength)\n  })\n}\n\nfunction buildArrayConstraints(description: TupleType): ArrayConstraints | undefined {\n  return description.constraints.length === 0\n    ? undefined\n    : description.constraints.reduce(mergeArrayConstraints)\n}\n\nconst arbitraryMemoMap = globalValue(\n  Symbol.for(\"effect/Arbitrary/arbitraryMemoMap\"),\n  () => new WeakMap<SchemaAST.AST, LazyArbitrary<any>>()\n)\n\nfunction applyFilters(filters: ReadonlyArray<Predicate.Predicate<any>>, arb: LazyArbitrary<any>): LazyArbitrary<any> {\n  return (fc) => filters.reduce((arb, filter) => arb.filter(filter), arb(fc))\n}\n\nfunction absurd(message: string): LazyArbitrary<any> {\n  return () => {\n    throw new Error(message)\n  }\n}\n\nfunction getContextConstraints(description: Description): ArbitraryGenerationContext[\"constraints\"] {\n  switch (description._tag) {\n    case \"StringKeyword\":\n      return buildStringConstraints(description)\n    case \"NumberKeyword\":\n      return buildNumberConstraints(description)\n    case \"BigIntKeyword\":\n      return buildBigIntConstraints(description)\n    case \"DateFromSelf\":\n      return buildDateConstraints(description)\n    case \"TupleType\":\n      return buildArrayConstraints(description)\n  }\n}\n\nfunction wrapGo(\n  f: (description: Description, ctx: ArbitraryGenerationContext, lazyArb: LazyArbitrary<any>) => LazyArbitrary<any>,\n  g: (description: Description, ctx: ArbitraryGenerationContext) => LazyArbitrary<any>\n): (description: Description, ctx: ArbitraryGenerationContext) => LazyArbitrary<any> {\n  return (description, ctx) => f(description, ctx, g(description, ctx))\n}\n\nconst go = wrapGo(\n  (description, ctx, lazyArb) => {\n    const annotation: ArbitraryAnnotation<any, any> | undefined =\n      description.annotations[description.annotations.length - 1]\n\n    // error handling\n    if (annotation === undefined) {\n      switch (description._tag) {\n        case \"Declaration\":\n        case \"NeverKeyword\":\n          throw new Error(errors_.getArbitraryMissingAnnotationErrorMessage(description.path, description.ast))\n        case \"Enums\":\n          if (description.enums.length === 0) {\n            throw new Error(errors_.getArbitraryEmptyEnumErrorMessage(description.path))\n          }\n      }\n    }\n\n    const filters = description.refinements.map((ast) => (a: any) =>\n      Option.isNone(ast.filter(a, SchemaAST.defaultParseOption, ast))\n    )\n    if (annotation === undefined) {\n      return applyFilters(filters, lazyArb)\n    }\n\n    const constraints = getContextConstraints(description)\n    if (constraints !== undefined) {\n      ctx = { ...ctx, constraints }\n    }\n\n    if (description._tag === \"Declaration\") {\n      return applyFilters(filters, annotation(...description.typeParameters.map((p) => go(p, ctx)), ctx))\n    }\n    if (description.refinements.length > 0) {\n      // TODO(4.0): remove the `lazyArb` parameter\n      return applyFilters(filters, annotation(lazyArb, ctx))\n    }\n    return annotation(ctx)\n  },\n  (description, ctx) => {\n    switch (description._tag) {\n      case \"DateFromSelf\": {\n        const constraints = buildDateConstraints(description)\n        return (fc) => fc.date(constraints?.constraints)\n      }\n      case \"Declaration\":\n      case \"NeverKeyword\":\n        return absurd(`BUG: cannot generate an arbitrary for ${description._tag}`)\n      case \"Literal\":\n        return (fc) => fc.constant(description.literal)\n      case \"UniqueSymbol\":\n        return (fc) => fc.constant(description.symbol)\n      case \"Keyword\": {\n        switch (description.value) {\n          case \"UndefinedKeyword\":\n            return (fc) => fc.constant(undefined)\n          case \"VoidKeyword\":\n          case \"UnknownKeyword\":\n          case \"AnyKeyword\":\n            return (fc) => fc.anything()\n          case \"BooleanKeyword\":\n            return (fc) => fc.boolean()\n          case \"SymbolKeyword\":\n            return (fc) => fc.string().map((s) => Symbol.for(s))\n          case \"ObjectKeyword\":\n            return (fc) => fc.oneof(fc.object(), fc.array(fc.anything()))\n        }\n      }\n      case \"Enums\":\n        return (fc) => fc.oneof(...description.enums.map(([_, value]) => fc.constant(value)))\n      case \"TemplateLiteral\": {\n        return (fc) => {\n          const string = fc.string({ maxLength: 5 })\n          const number = fc.float({ noDefaultInfinity: true, noNaN: true })\n\n          const getTemplateLiteralArb = (description: TemplateLiteral) => {\n            const components: Array<FastCheck.Arbitrary<string | number>> = description.head !== \"\"\n              ? [fc.constant(description.head)]\n              : []\n\n            const getTemplateLiteralSpanTypeArb = (\n              description: Description\n            ): FastCheck.Arbitrary<string | number> => {\n              switch (description._tag) {\n                case \"StringKeyword\":\n                  return string\n                case \"NumberKeyword\":\n                  return number\n                case \"Literal\":\n                  return fc.constant(String(description.literal))\n                case \"Union\":\n                  return fc.oneof(...description.members.map(getTemplateLiteralSpanTypeArb))\n                case \"TemplateLiteral\":\n                  return getTemplateLiteralArb(description)\n                default:\n                  return fc.constant(\"\")\n              }\n            }\n\n            description.spans.forEach((span) => {\n              components.push(getTemplateLiteralSpanTypeArb(span.description))\n              if (span.literal !== \"\") {\n                components.push(fc.constant(span.literal))\n              }\n            })\n\n            return fc.tuple(...components).map((spans) => spans.join(\"\"))\n          }\n\n          return getTemplateLiteralArb(description)\n        }\n      }\n      case \"StringKeyword\": {\n        const constraints = buildStringConstraints(description)\n        const pattern = constraints?.pattern\n        return pattern !== undefined ?\n          (fc) => fc.stringMatching(new RegExp(pattern)) :\n          (fc) => fc.string(constraints?.constraints)\n      }\n      case \"NumberKeyword\": {\n        const constraints = buildNumberConstraints(description)\n        return constraints?.isInteger ?\n          (fc) => fc.integer(constraints.constraints) :\n          (fc) => fc.float(constraints?.constraints)\n      }\n      case \"BigIntKeyword\": {\n        const constraints = buildBigIntConstraints(description)\n        return (fc) => fc.bigInt(constraints?.constraints ?? {})\n      }\n      case \"TupleType\": {\n        const elements: Array<LazyArbitrary<any>> = []\n        let hasOptionals = false\n        for (const element of description.elements) {\n          elements.push(go(element.description, ctx))\n          if (element.isOptional) {\n            hasOptionals = true\n          }\n        }\n        const rest = description.rest.map((d) => go(d, ctx))\n        return (fc) => {\n          // ---------------------------------------------\n          // handle elements\n          // ---------------------------------------------\n          let output = fc.tuple(...elements.map((arb) => arb(fc)))\n          if (hasOptionals) {\n            const indexes = fc.tuple(\n              ...description.elements.map((element) => element.isOptional ? fc.boolean() : fc.constant(true))\n            )\n            output = output.chain((tuple) =>\n              indexes.map((booleans) => {\n                for (const [i, b] of booleans.reverse().entries()) {\n                  if (!b) {\n                    tuple.splice(booleans.length - i, 1)\n                  }\n                }\n                return tuple\n              })\n            )\n          }\n\n          // ---------------------------------------------\n          // handle rest element\n          // ---------------------------------------------\n          if (Arr.isNonEmptyReadonlyArray(rest)) {\n            const constraints = buildArrayConstraints(description) ?? constArrayConstraints\n            const [head, ...tail] = rest\n            const item = head(fc)\n            output = output.chain((as) => {\n              const len = as.length\n              // We must adjust the constraints for the rest element\n              // because the elements might have generated some values\n              const restArrayConstraints = subtractElementsLength(constraints.constraints, len)\n              if (restArrayConstraints.maxLength === 0) {\n                return fc.constant(as)\n              }\n              /*\n\n              `getSuspendedArray` is used to generate less values in\n              the context of a recursive schema. Without it, the following schema\n              would generate an big amount of values possibly leading to a stack\n              overflow:\n\n              ```ts\n              type A = ReadonlyArray<A | null>\n\n              const schema = S.Array(\n                S.NullOr(S.suspend((): S.Schema<A> => schema))\n              )\n              ```\n\n            */\n              const arr = ctx.depthIdentifier !== undefined\n                ? getSuspendedArray(fc, ctx.depthIdentifier, ctx.maxDepth, item, restArrayConstraints)\n                : fc.array(item, restArrayConstraints)\n              if (len === 0) {\n                return arr\n              }\n              return arr.map((rest) => [...as, ...rest])\n            })\n            // ---------------------------------------------\n            // handle post rest elements\n            // ---------------------------------------------\n            for (let j = 0; j < tail.length; j++) {\n              output = output.chain((as) => tail[j](fc).map((a) => [...as, a]))\n            }\n          }\n\n          return output\n        }\n      }\n      case \"TypeLiteral\": {\n        const propertySignatures: Array<LazyArbitrary<any>> = []\n        const requiredKeys: Array<PropertyKey> = []\n        for (const ps of description.propertySignatures) {\n          if (!ps.isOptional) {\n            requiredKeys.push(ps.name)\n          }\n          propertySignatures.push(go(ps.value, ctx))\n        }\n        const indexSignatures = description.indexSignatures.map((is) =>\n          [go(is.parameter, ctx), go(is.value, ctx)] as const\n        )\n        return (fc) => {\n          const pps: any = {}\n          for (let i = 0; i < propertySignatures.length; i++) {\n            const ps = description.propertySignatures[i]\n            pps[ps.name] = propertySignatures[i](fc)\n          }\n          let output = fc.record<any, any>(pps, { requiredKeys })\n          // ---------------------------------------------\n          // handle index signatures\n          // ---------------------------------------------\n          for (let i = 0; i < indexSignatures.length; i++) {\n            const key = indexSignatures[i][0](fc)\n            const value = indexSignatures[i][1](fc)\n            output = output.chain((o) => {\n              const item = fc.tuple(key, value)\n              /*\n\n              `getSuspendedArray` is used to generate less key/value pairs in\n              the context of a recursive schema. Without it, the following schema\n              would generate an big amount of values possibly leading to a stack\n              overflow:\n\n              ```ts\n              type A = { [_: string]: A }\n\n              const schema = S.Record({ key: S.String, value: S.suspend((): S.Schema<A> => schema) })\n              ```\n\n            */\n              const arr = ctx.depthIdentifier !== undefined ?\n                getSuspendedArray(fc, ctx.depthIdentifier, ctx.maxDepth, item, { maxLength: 2 }) :\n                fc.array(item)\n              return arr.map((tuples) => ({ ...Object.fromEntries(tuples), ...o }))\n            })\n          }\n\n          return output\n        }\n      }\n      case \"Union\": {\n        const members = description.members.map((member) => go(member, ctx))\n        return (fc) => fc.oneof(...members.map((arb) => arb(fc)))\n      }\n      case \"Suspend\": {\n        const memo = arbitraryMemoMap.get(description.ast)\n        if (memo) {\n          return memo\n        }\n        if (ctx.depthIdentifier === undefined) {\n          ctx = { ...ctx, depthIdentifier: description.id }\n        }\n        const get = util_.memoizeThunk(() => {\n          return go(description.description(), ctx)\n        })\n        const out: LazyArbitrary<any> = (fc) => fc.constant(null).chain(() => get()(fc))\n        arbitraryMemoMap.set(description.ast, out)\n        return out\n      }\n      case \"Ref\": {\n        const memo = arbitraryMemoMap.get(description.ast)\n        if (memo) {\n          return memo\n        }\n        throw new Error(`BUG: Ref ${JSON.stringify(description.id)} not found`)\n      }\n    }\n  }\n)\n\nfunction subtractElementsLength(\n  constraints: FastCheck.ArrayConstraints,\n  len: number\n): FastCheck.ArrayConstraints {\n  if (len === 0 || (constraints.minLength === undefined && constraints.maxLength === undefined)) {\n    return constraints\n  }\n  const out = { ...constraints }\n  if (out.minLength !== undefined) {\n    out.minLength = Math.max(out.minLength - len, 0)\n  }\n  if (out.maxLength !== undefined) {\n    out.maxLength = Math.max(out.maxLength - len, 0)\n  }\n  return out\n}\n\nconst getSuspendedArray = (\n  fc: typeof FastCheck,\n  depthIdentifier: string,\n  maxDepth: number,\n  item: FastCheck.Arbitrary<any>,\n  constraints: FastCheck.ArrayConstraints\n) => {\n  // In the context of a recursive schema, we don't want a `maxLength` greater than 2.\n  // The only exception is when `minLength` is also set, in which case we set\n  // `maxLength` to the minimum value, which is `minLength`.\n  const maxLengthLimit = Math.max(2, constraints.minLength ?? 0)\n  if (constraints.maxLength !== undefined && constraints.maxLength > maxLengthLimit) {\n    constraints = { ...constraints, maxLength: maxLengthLimit }\n  }\n  return fc.oneof(\n    { maxDepth, depthIdentifier },\n    fc.constant([]),\n    fc.array(item, constraints)\n  )\n}\n"
  },
  {
    "path": "packages/effect/src/Array.ts",
    "content": "/**\n * This module provides utility functions for working with arrays in TypeScript.\n *\n * @since 2.0.0\n */\n\nimport * as Either from \"./Either.js\"\nimport * as Equal from \"./Equal.js\"\nimport * as Equivalence from \"./Equivalence.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport { dual, identity } from \"./Function.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport * as internalArray from \"./internal/array.js\"\nimport * as internalDoNotation from \"./internal/doNotation.js\"\nimport * as moduleIterable from \"./Iterable.js\"\nimport * as Option from \"./Option.js\"\nimport * as Order from \"./Order.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport * as Record from \"./Record.js\"\nimport * as Tuple from \"./Tuple.js\"\nimport type { NoInfer, TupleOf } from \"./Types.js\"\n\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface ReadonlyArrayTypeLambda extends TypeLambda {\n  readonly type: ReadonlyArray<this[\"Target\"]>\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport type NonEmptyReadonlyArray<A> = readonly [A, ...Array<A>]\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport type NonEmptyArray<A> = [A, ...Array<A>]\n\n/**\n * Builds a `NonEmptyArray` from an non-empty collection of elements.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.make(1, 2, 3)\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = <Elements extends NonEmptyArray<any>>(\n  ...elements: Elements\n): NonEmptyArray<Elements[number]> => elements\n\n/**\n * Creates a new `Array` of the specified length.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.allocate<number>(3)\n * console.log(result) // [ <3 empty items> ]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const allocate = <A = never>(n: number): Array<A | undefined> => new Array(n)\n\n/**\n * Return a `NonEmptyArray` of length `n` with element `i` initialized with `f(i)`.\n *\n * **Note**. `n` is normalized to an integer >= 1.\n *\n * **Example**\n *\n * ```ts\n * import { makeBy } from \"effect/Array\"\n *\n * const result = makeBy(5, n => n * 2)\n * console.log(result) // [0, 2, 4, 6, 8]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const makeBy: {\n  <A>(f: (i: number) => A): (n: number) => NonEmptyArray<A>\n  <A>(n: number, f: (i: number) => A): NonEmptyArray<A>\n} = dual(2, <A>(n: number, f: (i: number) => A) => {\n  const max = Math.max(1, Math.floor(n))\n  const out = new Array(max)\n  for (let i = 0; i < max; i++) {\n    out[i] = f(i)\n  }\n  return out as NonEmptyArray<A>\n})\n\n/**\n * Return a `NonEmptyArray` containing a range of integers, including both endpoints.\n *\n * **Example**\n *\n * ```ts\n * import { range } from \"effect/Array\"\n *\n * const result = range(1, 3)\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const range = (start: number, end: number): NonEmptyArray<number> =>\n  start <= end ? makeBy(end - start + 1, (i) => start + i) : [start]\n\n/**\n * Return a `NonEmptyArray` containing a value repeated the specified number of times.\n *\n * **Note**. `n` is normalized to an integer >= 1.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.replicate(\"a\", 3)\n * console.log(result) // [\"a\", \"a\", \"a\"]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const replicate: {\n  (n: number): <A>(a: A) => NonEmptyArray<A>\n  <A>(a: A, n: number): NonEmptyArray<A>\n} = dual(2, <A>(a: A, n: number): NonEmptyArray<A> => makeBy(n, () => a))\n\n/**\n * Creates a new `Array` from an iterable collection of values.\n * If the input is already an array, it returns the input as-is.\n * Otherwise, it converts the iterable collection to an array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.fromIterable(new Set([1, 2, 3]))\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterable = <A>(collection: Iterable<A>): Array<A> =>\n  Array.isArray(collection) ? collection : Array.from(collection)\n\n/**\n * Creates a new `Array` from a value that might not be an iterable.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * console.log(Array.ensure(\"a\")) // [\"a\"]\n * console.log(Array.ensure([\"a\"])) // [\"a\"]\n * console.log(Array.ensure([\"a\", \"b\", \"c\"])) // [\"a\", \"b\", \"c\"]\n * ```\n *\n * @category constructors\n * @since 3.3.0\n */\nexport const ensure = <A>(self: ReadonlyArray<A> | A): Array<A> => Array.isArray(self) ? self : [self as A]\n\n/**\n * Takes a record and returns an array of tuples containing its keys and values.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.fromRecord({ a: 1, b: 2, c: 3 })\n * console.log(result) // [[\"a\", 1], [\"b\", 2], [\"c\", 3]]\n * ```\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const fromRecord: <K extends string, A>(self: Readonly<Record<K, A>>) => Array<[K, A]> = Record.toEntries\n\n/**\n * Converts an `Option` to an array.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Option } from \"effect\"\n *\n * console.log(Array.fromOption(Option.some(1))) // [1]\n * console.log(Array.fromOption(Option.none())) // []\n * ```\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const fromOption: <A>(self: Option.Option<A>) => Array<A> = Option.toArray\n\n/**\n * Matches the elements of an array, applying functions to cases of empty and non-empty arrays.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const match = Array.match({\n *   onEmpty: () => \"empty\",\n *   onNonEmpty: ([head, ...tail]) => `head: ${head}, tail: ${tail.length}`\n * })\n * console.log(match([])) // \"empty\"\n * console.log(match([1, 2, 3])) // \"head: 1, tail: 2\"\n * ```\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const match: {\n  <B, A, C = B>(\n    options: {\n      readonly onEmpty: LazyArg<B>\n      readonly onNonEmpty: (self: NonEmptyReadonlyArray<A>) => C\n    }\n  ): (self: ReadonlyArray<A>) => B | C\n  <A, B, C = B>(\n    self: ReadonlyArray<A>,\n    options: {\n      readonly onEmpty: LazyArg<B>\n      readonly onNonEmpty: (self: NonEmptyReadonlyArray<A>) => C\n    }\n  ): B | C\n} = dual(2, <A, B, C = B>(\n  self: ReadonlyArray<A>,\n  { onEmpty, onNonEmpty }: {\n    readonly onEmpty: LazyArg<B>\n    readonly onNonEmpty: (self: NonEmptyReadonlyArray<A>) => C\n  }\n): B | C => isNonEmptyReadonlyArray(self) ? onNonEmpty(self) : onEmpty())\n\n/**\n * Matches the elements of an array from the left, applying functions to cases of empty and non-empty arrays.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const matchLeft = Array.matchLeft({\n *   onEmpty: () => \"empty\",\n *   onNonEmpty: (head, tail) => `head: ${head}, tail: ${tail.length}`\n * })\n * console.log(matchLeft([])) // \"empty\"\n * console.log(matchLeft([1, 2, 3])) // \"head: 1, tail: 2\"\n * ```\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const matchLeft: {\n  <B, A, C = B>(\n    options: {\n      readonly onEmpty: LazyArg<B>\n      readonly onNonEmpty: (head: A, tail: Array<A>) => C\n    }\n  ): (self: ReadonlyArray<A>) => B | C\n  <A, B, C = B>(\n    self: ReadonlyArray<A>,\n    options: {\n      readonly onEmpty: LazyArg<B>\n      readonly onNonEmpty: (head: A, tail: Array<A>) => C\n    }\n  ): B | C\n} = dual(2, <A, B, C = B>(\n  self: ReadonlyArray<A>,\n  { onEmpty, onNonEmpty }: {\n    readonly onEmpty: LazyArg<B>\n    readonly onNonEmpty: (head: A, tail: Array<A>) => C\n  }\n): B | C => isNonEmptyReadonlyArray(self) ? onNonEmpty(headNonEmpty(self), tailNonEmpty(self)) : onEmpty())\n\n/**\n * Matches the elements of an array from the right, applying functions to cases of empty and non-empty arrays.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const matchRight = Array.matchRight({\n *   onEmpty: () => \"empty\",\n *   onNonEmpty: (init, last) => `init: ${init.length}, last: ${last}`\n * })\n * console.log(matchRight([])) // \"empty\"\n * console.log(matchRight([1, 2, 3])) // \"init: 2, last: 3\"\n * ```\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const matchRight: {\n  <B, A, C = B>(\n    options: {\n      readonly onEmpty: LazyArg<B>\n      readonly onNonEmpty: (init: Array<A>, last: A) => C\n    }\n  ): (self: ReadonlyArray<A>) => B | C\n  <A, B, C = B>(\n    self: ReadonlyArray<A>,\n    options: {\n      readonly onEmpty: LazyArg<B>\n      readonly onNonEmpty: (init: Array<A>, last: A) => C\n    }\n  ): B | C\n} = dual(2, <A, B, C = B>(\n  self: ReadonlyArray<A>,\n  { onEmpty, onNonEmpty }: {\n    readonly onEmpty: LazyArg<B>\n    readonly onNonEmpty: (init: Array<A>, last: A) => C\n  }\n): B | C =>\n  isNonEmptyReadonlyArray(self) ?\n    onNonEmpty(initNonEmpty(self), lastNonEmpty(self)) :\n    onEmpty())\n\n/**\n * Prepend an element to the front of an `Iterable`, creating a new `NonEmptyArray`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.prepend([2, 3, 4], 1)\n * console.log(result) // [1, 2, 3, 4]\n * ```\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const prepend: {\n  <B>(head: B): <A>(self: Iterable<A>) => NonEmptyArray<A | B>\n  <A, B>(self: Iterable<A>, head: B): NonEmptyArray<A | B>\n} = dual(2, <A, B>(self: Iterable<A>, head: B): NonEmptyArray<A | B> => [head, ...self])\n\n/**\n * Prepends the specified prefix array (or iterable) to the beginning of the specified array (or iterable).\n * If either array is non-empty, the result is also a non-empty array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.prependAll([2, 3], [0, 1])\n * console.log(result) // [0, 1, 2, 3]\n * ```\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const prependAll: {\n  <S extends Iterable<any>, T extends Iterable<any>>(\n    that: T\n  ): (self: S) => ReadonlyArray.OrNonEmpty<S, T, ReadonlyArray.Infer<S> | ReadonlyArray.Infer<T>>\n  <A, B>(self: Iterable<A>, that: NonEmptyReadonlyArray<B>): NonEmptyArray<A | B>\n  <A, B>(self: NonEmptyReadonlyArray<A>, that: Iterable<B>): NonEmptyArray<A | B>\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Array<A | B>\n} = dual(\n  2,\n  <A>(self: Iterable<A>, that: Iterable<A>): Array<A> => fromIterable(that).concat(fromIterable(self))\n)\n\n/**\n * Append an element to the end of an `Iterable`, creating a new `NonEmptyArray`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.append([1, 2, 3], 4);\n * console.log(result) // [1, 2, 3, 4]\n * ```\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const append: {\n  <B>(last: B): <A>(self: Iterable<A>) => NonEmptyArray<A | B>\n  <A, B>(self: Iterable<A>, last: B): NonEmptyArray<A | B>\n} = dual(2, <A, B>(self: Iterable<A>, last: B): Array<A | B> => [...self, last])\n\n/**\n * Concatenates two arrays (or iterables), combining their elements.\n * If either array is non-empty, the result is also a non-empty array.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const appendAll: {\n  <S extends Iterable<any>, T extends Iterable<any>>(\n    that: T\n  ): (self: S) => ReadonlyArray.OrNonEmpty<S, T, ReadonlyArray.Infer<S> | ReadonlyArray.Infer<T>>\n  <A, B>(self: Iterable<A>, that: NonEmptyReadonlyArray<B>): NonEmptyArray<A | B>\n  <A, B>(self: NonEmptyReadonlyArray<A>, that: Iterable<B>): NonEmptyArray<A | B>\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Array<A | B>\n} = dual(\n  2,\n  <A>(self: Iterable<A>, that: Iterable<A>): Array<A> => fromIterable(self).concat(fromIterable(that))\n)\n\n/**\n * Accumulates values from an `Iterable` starting from the left, storing\n * each intermediate result in an array. Useful for tracking the progression of\n * a value through a series of transformations.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\";\n *\n * const result = Array.scan([1, 2, 3, 4], 0, (acc, value) => acc + value)\n * console.log(result) // [0, 1, 3, 6, 10]\n *\n * // Explanation:\n * // This function starts with the initial value (0 in this case)\n * // and adds each element of the array to this accumulator one by one,\n * // keeping track of the cumulative sum after each addition.\n * // Each of these sums is captured in the resulting array.\n * ```\n *\n * @category folding\n * @since 2.0.0\n */\nexport const scan: {\n  <B, A>(b: B, f: (b: B, a: A) => B): (self: Iterable<A>) => NonEmptyArray<B>\n  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): NonEmptyArray<B>\n} = dual(3, <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): NonEmptyArray<B> => {\n  const out: NonEmptyArray<B> = [b]\n  let i = 0\n  for (const a of self) {\n    out[i + 1] = f(out[i], a)\n    i++\n  }\n  return out\n})\n\n/**\n * Accumulates values from an `Iterable` starting from the right, storing\n * each intermediate result in an array. Useful for tracking the progression of\n * a value through a series of transformations.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\";\n *\n * const result = Array.scanRight([1, 2, 3, 4], 0, (acc, value) => acc + value)\n * console.log(result) // [10, 9, 7, 4, 0]\n * ```\n *\n * @category folding\n * @since 2.0.0\n */\nexport const scanRight: {\n  <B, A>(b: B, f: (b: B, a: A) => B): (self: Iterable<A>) => NonEmptyArray<B>\n  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): NonEmptyArray<B>\n} = dual(3, <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): NonEmptyArray<B> => {\n  const input = fromIterable(self)\n  const out: NonEmptyArray<B> = new Array(input.length + 1) as any\n  out[input.length] = b\n  for (let i = input.length - 1; i >= 0; i--) {\n    out[i] = f(out[i + 1], input[i])\n  }\n  return out\n})\n\n/**\n * Determine if `unknown` is an Array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * console.log(Array.isArray(null)) // false\n * console.log(Array.isArray([1, 2, 3])) // true\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isArray: {\n  (self: unknown): self is Array<unknown>\n  <T>(self: T): self is Extract<T, ReadonlyArray<any>>\n} = Array.isArray\n\n/**\n * Determine if an `Array` is empty narrowing down the type to `[]`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * console.log(Array.isEmptyArray([])) // true\n * console.log(Array.isEmptyArray([1, 2, 3])) // false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEmptyArray = <A>(self: Array<A>): self is [] => self.length === 0\n\n/**\n * Determine if a `ReadonlyArray` is empty narrowing down the type to `readonly []`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * console.log(Array.isEmptyReadonlyArray([])) // true\n * console.log(Array.isEmptyReadonlyArray([1, 2, 3])) // false\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEmptyReadonlyArray: <A>(self: ReadonlyArray<A>) => self is readonly [] = isEmptyArray as any\n\n/**\n * Determine if an `Array` is non empty narrowing down the type to `NonEmptyArray`.\n *\n * An `Array` is considered to be a `NonEmptyArray` if it contains at least one element.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * console.log(Array.isNonEmptyArray([])) // false\n * console.log(Array.isNonEmptyArray([1, 2, 3])) // true\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isNonEmptyArray: <A>(self: Array<A>) => self is NonEmptyArray<A> = internalArray.isNonEmptyArray\n\n/**\n * Determine if a `ReadonlyArray` is non empty narrowing down the type to `NonEmptyReadonlyArray`.\n *\n * A `ReadonlyArray` is considered to be a `NonEmptyReadonlyArray` if it contains at least one element.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * console.log(Array.isNonEmptyReadonlyArray([])) // false\n * console.log(Array.isNonEmptyReadonlyArray([1, 2, 3])) // true\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isNonEmptyReadonlyArray: <A>(self: ReadonlyArray<A>) => self is NonEmptyReadonlyArray<A> =\n  internalArray.isNonEmptyArray\n\n/**\n * Return the number of elements in a `ReadonlyArray`.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const length = <A>(self: ReadonlyArray<A>): number => self.length\n\nconst isOutOfBounds = <A>(i: number, as: ReadonlyArray<A>): boolean => i < 0 || i >= as.length\n\nconst clamp = <A>(i: number, as: ReadonlyArray<A>): number => Math.floor(Math.min(Math.max(0, i), as.length))\n\n/**\n * This function provides a safe way to read a value at a particular index from a `ReadonlyArray`.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const get: {\n  (index: number): <A>(self: ReadonlyArray<A>) => Option.Option<A>\n  <A>(self: ReadonlyArray<A>, index: number): Option.Option<A>\n} = dual(2, <A>(self: ReadonlyArray<A>, index: number): Option.Option<A> => {\n  const i = Math.floor(index)\n  return isOutOfBounds(i, self) ? Option.none() : Option.some(self[i])\n})\n\n/**\n * Gets an element unsafely, will throw on out of bounds.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeGet: {\n  (index: number): <A>(self: ReadonlyArray<A>) => A\n  <A>(self: ReadonlyArray<A>, index: number): A\n} = dual(2, <A>(self: ReadonlyArray<A>, index: number): A => {\n  const i = Math.floor(index)\n  if (isOutOfBounds(i, self)) {\n    throw new Error(`Index ${i} out of bounds`)\n  }\n  return self[i]\n})\n\n/**\n * Return a tuple containing the first element, and a new `Array` of the remaining elements, if any.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\";\n *\n * const result = Array.unprepend([1, 2, 3, 4])\n * console.log(result) // [1, [2, 3, 4]]\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const unprepend = <A>(\n  self: NonEmptyReadonlyArray<A>\n): [firstElement: A, remainingElements: Array<A>] => [headNonEmpty(self), tailNonEmpty(self)]\n\n/**\n * Return a tuple containing a copy of the `NonEmptyReadonlyArray` without its last element, and that last element.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\";\n *\n * const result = Array.unappend([1, 2, 3, 4])\n * console.log(result) // [[1, 2, 3], 4]\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const unappend = <A>(\n  self: NonEmptyReadonlyArray<A>\n): [arrayWithoutLastElement: Array<A>, lastElement: A] => [initNonEmpty(self), lastNonEmpty(self)]\n\n/**\n * Get the first element of a `ReadonlyArray`, or `None` if the `ReadonlyArray` is empty.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const head: <A>(self: ReadonlyArray<A>) => Option.Option<A> = get(0)\n\n/**\n * Get the first element of a non empty array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.headNonEmpty([1, 2, 3, 4])\n * console.log(result) // 1\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const headNonEmpty: <A>(self: NonEmptyReadonlyArray<A>) => A = unsafeGet(0)\n\n/**\n * Get the last element in a `ReadonlyArray`, or `None` if the `ReadonlyArray` is empty.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const last = <A>(self: ReadonlyArray<A>): Option.Option<A> =>\n  isNonEmptyReadonlyArray(self) ? Option.some(lastNonEmpty(self)) : Option.none()\n\n/**\n * Get the last element of a non empty array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.lastNonEmpty([1, 2, 3, 4])\n * console.log(result) // 4\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const lastNonEmpty = <A>(self: NonEmptyReadonlyArray<A>): A => self[self.length - 1]\n\n/**\n * Get all but the first element of an `Iterable`, creating a new `Array`, or `None` if the `Iterable` is empty.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const tail = <A>(self: Iterable<A>): Option.Option<Array<A>> => {\n  const input = fromIterable(self)\n  return isNonEmptyReadonlyArray(input) ? Option.some(tailNonEmpty(input)) : Option.none()\n}\n\n/**\n * Get all but the first element of a `NonEmptyReadonlyArray`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.tailNonEmpty([1, 2, 3, 4])\n * console.log(result) // [2, 3, 4]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const tailNonEmpty = <A>(self: NonEmptyReadonlyArray<A>): Array<A> => self.slice(1)\n\n/**\n * Get all but the last element of an `Iterable`, creating a new `Array`, or `None` if the `Iterable` is empty.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const init = <A>(self: Iterable<A>): Option.Option<Array<A>> => {\n  const input = fromIterable(self)\n  return isNonEmptyReadonlyArray(input) ? Option.some(initNonEmpty(input)) : Option.none()\n}\n\n/**\n * Get all but the last element of a non empty array, creating a new array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.initNonEmpty([1, 2, 3, 4])\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const initNonEmpty = <A>(self: NonEmptyReadonlyArray<A>): Array<A> => self.slice(0, -1)\n\n/**\n * Keep only a max number of elements from the start of an `Iterable`, creating a new `Array`.\n *\n * **Note**. `n` is normalized to a non negative integer.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.take([1, 2, 3, 4, 5], 3)\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const take: {\n  (n: number): <A>(self: Iterable<A>) => Array<A>\n  <A>(self: Iterable<A>, n: number): Array<A>\n} = dual(2, <A>(self: Iterable<A>, n: number): Array<A> => {\n  const input = fromIterable(self)\n  return input.slice(0, clamp(n, input))\n})\n\n/**\n * Keep only a max number of elements from the end of an `Iterable`, creating a new `Array`.\n *\n * **Note**. `n` is normalized to a non negative integer.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.takeRight([1, 2, 3, 4, 5], 3)\n * console.log(result) // [3, 4, 5]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const takeRight: {\n  (n: number): <A>(self: Iterable<A>) => Array<A>\n  <A>(self: Iterable<A>, n: number): Array<A>\n} = dual(2, <A>(self: Iterable<A>, n: number): Array<A> => {\n  const input = fromIterable(self)\n  const i = clamp(n, input)\n  return i === 0 ? [] : input.slice(-i)\n})\n\n/**\n * Calculate the longest initial subarray for which all element satisfy the specified predicate, creating a new `Array`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.takeWhile([1, 3, 2, 4, 1, 2], x => x < 4)\n * console.log(result) // [1, 3, 2]\n *\n * // Explanation:\n * // - The function starts with the first element (`1`), which is less than `4`, so it adds `1` to the result.\n * // - The next element (`3`) is also less than `4`, so it adds `3`.\n * // - The next element (`2`) is again less than `4`, so it adds `2`.\n * // - The function then encounters `4`, which is not less than `4`. At this point, it stops checking further elements and finalizes the result.\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const takeWhile: {\n  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Array<B>\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Array<A>\n  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Array<B>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Array<A>\n} = dual(2, <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Array<A> => {\n  let i = 0\n  const out: Array<A> = []\n  for (const a of self) {\n    if (!predicate(a, i)) {\n      break\n    }\n    out.push(a)\n    i++\n  }\n  return out\n})\n\nconst spanIndex = <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): number => {\n  let i = 0\n  for (const a of self) {\n    if (!predicate(a, i)) {\n      break\n    }\n    i++\n  }\n  return i\n}\n\n/**\n * Split an `Iterable` into two parts:\n *\n * 1. the longest initial subarray for which all elements satisfy the specified predicate\n * 2. the remaining elements\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const span: {\n  <A, B extends A>(\n    refinement: (a: NoInfer<A>, i: number) => a is B\n  ): (self: Iterable<A>) => [init: Array<B>, rest: Array<Exclude<A, B>>]\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => [init: Array<A>, rest: Array<A>]\n  <A, B extends A>(\n    self: Iterable<A>,\n    refinement: (a: A, i: number) => a is B\n  ): [init: Array<B>, rest: Array<Exclude<A, B>>]\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): [init: Array<A>, rest: Array<A>]\n} = dual(\n  2,\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): [init: Array<A>, rest: Array<A>] =>\n    splitAt(self, spanIndex(self, predicate))\n)\n\n/**\n * Drop a max number of elements from the start of an `Iterable`, creating a new `Array`.\n *\n * **Note**. `n` is normalized to a non negative integer.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.drop([1, 2, 3, 4, 5], 2)\n * console.log(result) // [3, 4, 5]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const drop: {\n  (n: number): <A>(self: Iterable<A>) => Array<A>\n  <A>(self: Iterable<A>, n: number): Array<A>\n} = dual(2, <A>(self: Iterable<A>, n: number): Array<A> => {\n  const input = fromIterable(self)\n  return input.slice(clamp(n, input), input.length)\n})\n\n/**\n * Drop a max number of elements from the end of an `Iterable`, creating a new `Array`.\n *\n * **Note**. `n` is normalized to a non negative integer.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.dropRight([1, 2, 3, 4, 5], 2)\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const dropRight: {\n  (n: number): <A>(self: Iterable<A>) => Array<A>\n  <A>(self: Iterable<A>, n: number): Array<A>\n} = dual(2, <A>(self: Iterable<A>, n: number): Array<A> => {\n  const input = fromIterable(self)\n  return input.slice(0, input.length - clamp(n, input))\n})\n\n/**\n * Remove the longest initial subarray for which all element satisfy the specified predicate, creating a new `Array`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.dropWhile([1, 2, 3, 4, 5], x => x < 4)\n * console.log(result) // [4, 5]\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const dropWhile: {\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Array<A>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Array<A>\n} = dual(\n  2,\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Array<A> =>\n    fromIterable(self).slice(spanIndex(self, predicate))\n)\n\n/**\n * Return the first index for which a predicate holds.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.findFirstIndex([5, 3, 8, 9], x => x > 5)\n * console.log(result) // Option.some(2)\n * ```\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findFirstIndex: {\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option.Option<number>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option.Option<number>\n} = dual(2, <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option.Option<number> => {\n  let i = 0\n  for (const a of self) {\n    if (predicate(a, i)) {\n      return Option.some(i)\n    }\n    i++\n  }\n  return Option.none()\n})\n\n/**\n * Return the last index for which a predicate holds.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.findLastIndex([1, 3, 8, 9], x => x < 5)\n * console.log(result) // Option.some(1)\n * ```\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findLastIndex: {\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option.Option<number>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option.Option<number>\n} = dual(2, <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option.Option<number> => {\n  const input = fromIterable(self)\n  for (let i = input.length - 1; i >= 0; i--) {\n    if (predicate(input[i], i)) {\n      return Option.some(i)\n    }\n  }\n  return Option.none()\n})\n\n/**\n * Returns the first element that satisfies the specified\n * predicate, or `None` if no such element exists.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.findFirst([1, 2, 3, 4, 5], x => x > 3)\n * console.log(result) // Option.some(4)\n * ```\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findFirst: {\n  <A, B>(f: (a: NoInfer<A>, i: number) => Option.Option<B>): (self: Iterable<A>) => Option.Option<B>\n  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Option.Option<B>\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option.Option<A>\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option.Option<B>): Option.Option<B>\n  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Option.Option<B>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option.Option<A>\n} = moduleIterable.findFirst\n\n/**\n * Finds the last element in an iterable collection that satisfies the given predicate or refinement.\n * Returns an `Option` containing the found element, or `Option.none` if no element matches.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.findLast([1, 2, 3, 4, 5], n => n % 2 === 0)\n * console.log(result) // Option.some(4)\n * ```\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findLast: {\n  <A, B>(f: (a: NoInfer<A>, i: number) => Option.Option<B>): (self: Iterable<A>) => Option.Option<B>\n  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Option.Option<B>\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option.Option<A>\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option.Option<B>): Option.Option<B>\n  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Option.Option<B>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option.Option<A>\n} = dual(\n  2,\n  <A>(\n    self: Iterable<A>,\n    f: ((a: A, i: number) => boolean) | ((a: A, i: number) => Option.Option<A>)\n  ): Option.Option<A> => {\n    const input = fromIterable(self)\n    for (let i = input.length - 1; i >= 0; i--) {\n      const a = input[i]\n      const o = f(a, i)\n      if (Predicate.isBoolean(o)) {\n        if (o) {\n          return Option.some(a)\n        }\n      } else {\n        if (Option.isSome(o)) {\n          return o\n        }\n      }\n    }\n    return Option.none()\n  }\n)\n\n/**\n * Returns a tuple of the first element that satisfies the specified\n * predicate and its index, or `None` if no such element exists.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.findFirstWithIndex([1, 2, 3, 4, 5], x => x > 3)\n * console.log(result) // Option.some([4, 3])\n * ```\n *\n * @category elements\n * @since 3.17.0\n */\nexport const findFirstWithIndex: {\n  <A, B>(f: (a: NoInfer<A>, i: number) => Option.Option<B>): (self: Iterable<A>) => Option.Option<[B, number]>\n  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Option.Option<[B, number]>\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option.Option<[A, number]>\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option.Option<B>): Option.Option<[B, number]>\n  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Option.Option<[B, number]>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option.Option<[A, number]>\n} = dual(\n  2,\n  <A>(\n    self: Iterable<A>,\n    f: ((a: A, i: number) => boolean) | ((a: A, i: number) => Option.Option<A>)\n  ): Option.Option<[A, number]> => {\n    let i = 0\n    for (const a of self) {\n      const o = f(a, i)\n      if (Predicate.isBoolean(o)) {\n        if (o) {\n          return Option.some([a, i])\n        }\n      } else {\n        if (Option.isSome(o)) {\n          return Option.some([o.value, i])\n        }\n      }\n      i++\n    }\n    return Option.none()\n  }\n)\n\n/**\n * Counts all the element of the given array that pass the given predicate\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.countBy([1, 2, 3, 4, 5], n => n % 2 === 0)\n * console.log(result) // 2\n * ```\n *\n * @category folding\n * @since 3.16.0\n */\nexport const countBy: {\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => number\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): number\n} = dual(\n  2,\n  <A>(\n    self: Iterable<A>,\n    f: (a: A, i: number) => boolean\n  ): number => {\n    let count = 0\n    const as = fromIterable(self)\n    for (let i = 0; i < as.length; i++) {\n      const a = as[i]\n      if (f(a, i)) {\n        count++\n      }\n    }\n    return count\n  }\n)\n\n/**\n * Insert an element at the specified index, creating a new `NonEmptyArray`,\n * or return `None` if the index is out of bounds.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.insertAt(['a', 'b', 'c', 'e'], 3, 'd')\n * console.log(result) // Option.some(['a', 'b', 'c', 'd', 'e'])\n * ```\n *\n * @since 2.0.0\n */\nexport const insertAt: {\n  <B>(i: number, b: B): <A>(self: Iterable<A>) => Option.Option<NonEmptyArray<A | B>>\n  <A, B>(self: Iterable<A>, i: number, b: B): Option.Option<NonEmptyArray<A | B>>\n} = dual(3, <A, B>(self: Iterable<A>, i: number, b: B): Option.Option<NonEmptyArray<A | B>> => {\n  const out: Array<A | B> = Array.from(self)\n  //             v--- `= self.length` is ok, it means inserting in last position\n  if (i < 0 || i > out.length) {\n    return Option.none()\n  }\n  out.splice(i, 0, b)\n  return Option.some(out) as any\n})\n\n/**\n * Change the element at the specified index, creating a new `Array`,\n * or return a copy of the input if the index is out of bounds.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.replace(['a', 'b', 'c', 'd'], 1, 'z')\n * console.log(result) // ['a', 'z', 'c', 'd']\n * ```\n *\n * @since 2.0.0\n */\nexport const replace: {\n  <B>(\n    i: number,\n    b: B\n  ): <A, S extends Iterable<A> = Iterable<A>>(\n    self: S\n  ) => ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>\n  <A, B, S extends Iterable<A> = Iterable<A>>(\n    self: S,\n    i: number,\n    b: B\n  ): ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>\n} = dual(3, <A, B>(self: Iterable<A>, i: number, b: B): Array<A | B> => modify(self, i, () => b))\n\n/**\n * Replaces an element in an array with the given value, returning an option of the updated array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.replaceOption([1, 2, 3], 1, 4)\n * console.log(result) // Option.some([1, 4, 3])\n * ```\n *\n * @since 2.0.0\n */\nexport const replaceOption: {\n  <B>(\n    i: number,\n    b: B\n  ): <A, S extends Iterable<A> = Iterable<A>>(\n    self: S\n  ) => Option.Option<ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>>\n  <A, B, S extends Iterable<A> = Iterable<A>>(\n    self: S,\n    i: number,\n    b: B\n  ): Option.Option<ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>>\n} = dual(\n  3,\n  <A, B>(self: Iterable<A>, i: number, b: B): Option.Option<Array<A | B>> => modifyOption(self, i, () => b)\n)\n\n/**\n * Apply a function to the element at the specified index, creating a new `Array`,\n * or return a copy of the input if the index is out of bounds.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.modify([1, 2, 3, 4], 2, (n) => n * 2)\n * console.log(result) // [1, 2, 6, 4]\n * ```\n *\n * @since 2.0.0\n */\nexport const modify: {\n  <A, B, S extends Iterable<A> = Iterable<A>>(\n    i: number,\n    f: (a: ReadonlyArray.Infer<S>) => B\n  ): (self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>\n  <A, B, S extends Iterable<A> = Iterable<A>>(\n    self: S,\n    i: number,\n    f: (a: ReadonlyArray.Infer<S>) => B\n  ): ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>\n} = dual(\n  3,\n  <A, B>(self: Iterable<A>, i: number, f: (a: A) => B): Array<A | B> => {\n    const out: Array<A | B> = Array.from(self)\n    if (isOutOfBounds(i, out)) {\n      return out\n    }\n    const b = f(out[i] as A)\n    out[i] = b\n    return out\n  }\n)\n\n/**\n * Apply a function to the element at the specified index, creating a new `Array`,\n * or return `None` if the index is out of bounds.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const input = [1, 2, 3, 4]\n * const result = Array.modifyOption(input, 2, (n) => n * 2)\n * console.log(result) // Option.some([1, 2, 6, 4])\n *\n * const outOfBoundsResult = Array.modifyOption(input, 5, (n) => n * 2)\n * console.log(outOfBoundsResult) // Option.none()\n * ```\n *\n * @since 2.0.0\n */\nexport const modifyOption: {\n  <A, B, S extends Iterable<A> = Iterable<A>>(\n    i: number,\n    f: (a: ReadonlyArray.Infer<S>) => B\n  ): (self: S) => Option.Option<ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>>\n  <A, B, S extends Iterable<A> = Iterable<A>>(\n    self: S,\n    i: number,\n    f: (a: ReadonlyArray.Infer<S>) => B\n  ): Option.Option<ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>>\n} = dual(3, <A, B>(self: Iterable<A>, i: number, f: (a: A) => B): Option.Option<Array<A | B>> => {\n  const arr = fromIterable(self)\n  if (isOutOfBounds(i, arr)) {\n    return Option.none()\n  }\n  const out: Array<A | B> = Array.isArray(self) ? self.slice() : arr\n  const b = f(arr[i])\n  out[i] = b\n  return Option.some(out)\n})\n\n/**\n * Delete the element at the specified index, creating a new `Array`,\n * or return a copy of the input if the index is out of bounds.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const input = [1, 2, 3, 4]\n * const result = Array.remove(input, 2)\n * console.log(result) // [1, 2, 4]\n *\n * const outOfBoundsResult = Array.remove(input, 5)\n * console.log(outOfBoundsResult) // [1, 2, 3, 4]\n * ```\n *\n * @since 2.0.0\n */\nexport const remove: {\n  (i: number): <A>(self: Iterable<A>) => Array<A>\n  <A>(self: Iterable<A>, i: number): Array<A>\n} = dual(2, <A>(self: Iterable<A>, i: number): Array<A> => {\n  const out = Array.from(self)\n  if (isOutOfBounds(i, out)) {\n    return out\n  }\n  out.splice(i, 1)\n  return out\n})\n\n/**\n * Delete the element at the specified index, creating a new `Array`,\n * or return `None` if the index is out of bounds.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Array, Option } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4]\n * const result = Array.removeOption(numbers, 2)\n * assert.deepStrictEqual(result, Option.some([1, 2, 4]))\n *\n * const outOfBoundsResult = Array.removeOption(numbers, 5)\n * assert.deepStrictEqual(outOfBoundsResult, Option.none())\n * ```\n *\n * @since 3.16.0\n */\nexport const removeOption: {\n  (i: number): <A>(self: Iterable<A>) => Option.Option<Array<A>>\n  <A>(self: Iterable<A>, i: number): Option.Option<Array<A>>\n} = dual(2, <A>(self: Iterable<A>, i: number): Option.Option<Array<A>> => {\n  const arr = fromIterable(self)\n  if (isOutOfBounds(i, arr)) {\n    return Option.none()\n  }\n  const out = Array.isArray(self) ? self.slice() : arr\n  out.splice(i, 1)\n  return Option.some(out)\n})\n\n/**\n * Reverse an `Iterable`, creating a new `Array`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.reverse([1, 2, 3, 4])\n * console.log(result) // [4, 3, 2, 1]\n * ```\n *\n * @category elements\n * @since 2.0.0\n */\nexport const reverse = <S extends Iterable<any>>(\n  self: S\n): S extends NonEmptyReadonlyArray<infer A> ? NonEmptyArray<A> : S extends Iterable<infer A> ? Array<A> : never =>\n  Array.from(self).reverse() as any\n\n/**\n * Create a new array with elements sorted in increasing order based on the specified comparator.\n * If the input is a `NonEmptyReadonlyArray`, the output will also be a `NonEmptyReadonlyArray`.\n *\n * @category sorting\n * @since 2.0.0\n */\nexport const sort: {\n  <B>(\n    O: Order.Order<B>\n  ): <A extends B, S extends Iterable<A>>(self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>\n  <A extends B, B>(self: NonEmptyReadonlyArray<A>, O: Order.Order<B>): NonEmptyArray<A>\n  <A extends B, B>(self: Iterable<A>, O: Order.Order<B>): Array<A>\n} = dual(2, <A extends B, B>(self: Iterable<A>, O: Order.Order<B>): Array<A> => {\n  const out = Array.from(self)\n  out.sort(O)\n  return out\n})\n\n/**\n * Sorts an array based on a provided mapping function and order. The mapping\n * function transforms the elements into a value that can be compared, and the\n * order defines how those values should be sorted.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Order } from \"effect\"\n *\n * const result = Array.sortWith([\"aaa\", \"b\", \"cc\"], (s) => s.length, Order.number)\n * console.log(result) // [\"b\", \"cc\", \"aaa\"]\n *\n * // Explanation:\n * // The array of strings is sorted based on their lengths. The mapping function `(s) => s.length`\n * // converts each string into its length, and the `Order.number` specifies that the lengths should\n * // be sorted in ascending order.\n * ```\n *\n * @since 2.0.0\n * @category elements\n */\nexport const sortWith: {\n  <S extends Iterable<any>, B>(\n    f: (a: ReadonlyArray.Infer<S>) => B,\n    order: Order.Order<B>\n  ): (self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>\n  <A, B>(self: NonEmptyReadonlyArray<A>, f: (a: A) => B, O: Order.Order<B>): NonEmptyArray<A>\n  <A, B>(self: Iterable<A>, f: (a: A) => B, order: Order.Order<B>): Array<A>\n} = dual(\n  3,\n  <A, B>(self: Iterable<A>, f: (a: A) => B, order: Order.Order<B>): Array<A> =>\n    Array.from(self).map((a) => [a, f(a)] as const).sort(([, a], [, b]) => order(a, b)).map(([_]) => _)\n)\n\n/**\n * Sorts the elements of an `Iterable` in increasing order based on the provided\n * orders. The elements are compared using the first order in `orders`, then the\n * second order if the first comparison is equal, and so on.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Order, pipe } from \"effect\"\n *\n * const users = [\n *   { name: \"Alice\", age: 30 },\n *   { name: \"Bob\", age: 25 },\n *   { name: \"Charlie\", age: 30 }\n * ]\n *\n * const result = pipe(\n *   users,\n *   Array.sortBy(\n *     Order.mapInput(Order.number, (user: (typeof users)[number]) => user.age),\n *     Order.mapInput(Order.string, (user: (typeof users)[number]) => user.name)\n *   )\n * )\n *\n * console.log(result)\n * // [\n * //   { name: \"Bob\", age: 25 },\n * //   { name: \"Alice\", age: 30 },\n * //   { name: \"Charlie\", age: 30 }\n * // ]\n *\n * // Explanation:\n * // The array of users is sorted first by age in ascending order. When ages are equal,\n * // the users are further sorted by name in ascending order.\n * ```\n *\n * @category sorting\n * @since 2.0.0\n */\nexport const sortBy = <S extends Iterable<any>>(\n  ...orders: ReadonlyArray<Order.Order<ReadonlyArray.Infer<S>>>\n) => {\n  const sortByAll = sort(Order.combineAll(orders))\n  return (\n    self: S\n  ): S extends NonEmptyReadonlyArray<infer A> ? NonEmptyArray<A> : S extends Iterable<infer A> ? Array<A> : never => {\n    const input = fromIterable(self)\n    if (isNonEmptyReadonlyArray(input)) {\n      return sortByAll(input) as any\n    }\n    return [] as any\n  }\n}\n\n/**\n * Takes two `Iterable`s and returns an `Array` of corresponding pairs.\n * If one input `Iterable` is short, excess elements of the\n * longer `Iterable` are discarded.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.zip([1, 2, 3], ['a', 'b'])\n * console.log(result) // [[1, 'a'], [2, 'b']]\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zip: {\n  <B>(that: NonEmptyReadonlyArray<B>): <A>(self: NonEmptyReadonlyArray<A>) => NonEmptyArray<[A, B]>\n  <B>(that: Iterable<B>): <A>(self: Iterable<A>) => Array<[A, B]>\n  <A, B>(self: NonEmptyReadonlyArray<A>, that: NonEmptyReadonlyArray<B>): NonEmptyArray<[A, B]>\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Array<[A, B]>\n} = dual(\n  2,\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Array<[A, B]> => zipWith(self, that, Tuple.make)\n)\n\n/**\n * Apply a function to pairs of elements at the same index in two `Iterable`s, collecting the results in a new `Array`. If one\n * input `Iterable` is short, excess elements of the longer `Iterable` are discarded.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.zipWith([1, 2, 3], [4, 5, 6], (a, b) => a + b)\n * console.log(result) // [5, 7, 9]\n * ```\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith: {\n  <B, A, C>(that: NonEmptyReadonlyArray<B>, f: (a: A, b: B) => C): (self: NonEmptyReadonlyArray<A>) => NonEmptyArray<C>\n  <B, A, C>(that: Iterable<B>, f: (a: A, b: B) => C): (self: Iterable<A>) => Array<C>\n  <A, B, C>(self: NonEmptyReadonlyArray<A>, that: NonEmptyReadonlyArray<B>, f: (a: A, b: B) => C): NonEmptyArray<C>\n  <B, A, C>(self: Iterable<A>, that: Iterable<B>, f: (a: A, b: B) => C): Array<C>\n} = dual(3, <B, A, C>(self: Iterable<A>, that: Iterable<B>, f: (a: A, b: B) => C): Array<C> => {\n  const as = fromIterable(self)\n  const bs = fromIterable(that)\n  if (isNonEmptyReadonlyArray(as) && isNonEmptyReadonlyArray(bs)) {\n    const out: NonEmptyArray<C> = [f(headNonEmpty(as), headNonEmpty(bs))]\n    const len = Math.min(as.length, bs.length)\n    for (let i = 1; i < len; i++) {\n      out[i] = f(as[i], bs[i])\n    }\n    return out\n  }\n  return []\n})\n\n/**\n * This function is the inverse of `zip`. Takes an `Iterable` of pairs and return two corresponding `Array`s.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.unzip([[1, \"a\"], [2, \"b\"], [3, \"c\"]])\n * console.log(result) // [[1, 2, 3], ['a', 'b', 'c']]\n * ```\n *\n * @since 2.0.0\n */\nexport const unzip: <S extends Iterable<readonly [any, any]>>(\n  self: S\n) => S extends NonEmptyReadonlyArray<readonly [infer A, infer B]> ? [NonEmptyArray<A>, NonEmptyArray<B>]\n  : S extends Iterable<readonly [infer A, infer B]> ? [Array<A>, Array<B>]\n  : never = (<A, B>(self: Iterable<readonly [A, B]>): [Array<A>, Array<B>] => {\n    const input = fromIterable(self)\n    if (isNonEmptyReadonlyArray(input)) {\n      const fa: NonEmptyArray<A> = [input[0][0]]\n      const fb: NonEmptyArray<B> = [input[0][1]]\n      for (let i = 1; i < input.length; i++) {\n        fa[i] = input[i][0]\n        fb[i] = input[i][1]\n      }\n      return [fa, fb]\n    }\n    return [[], []]\n  }) as any\n\n/**\n * Places an element in between members of an `Iterable`.\n * If the input is a non-empty array, the result is also a non-empty array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.intersperse([1, 2, 3], 0)\n * console.log(result) // [1, 0, 2, 0, 3]\n * ```\n *\n * @since 2.0.0\n */\nexport const intersperse: {\n  <B>(\n    middle: B\n  ): <S extends Iterable<any>>(self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S> | B>\n  <A, B>(self: NonEmptyReadonlyArray<A>, middle: B): NonEmptyArray<A | B>\n  <A, B>(self: Iterable<A>, middle: B): Array<A | B>\n} = dual(2, <A, B>(self: Iterable<A>, middle: B): Array<A | B> => {\n  const input = fromIterable(self)\n  if (isNonEmptyReadonlyArray(input)) {\n    const out: NonEmptyArray<A | B> = [headNonEmpty(input)]\n    const tail = tailNonEmpty(input)\n    for (let i = 0; i < tail.length; i++) {\n      if (i < tail.length) {\n        out.push(middle)\n      }\n      out.push(tail[i])\n    }\n    return out\n  }\n  return []\n})\n\n/**\n * Apply a function to the head, creating a new `NonEmptyReadonlyArray`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.modifyNonEmptyHead([1, 2, 3], n => n * 10)\n * console.log(result) // [10, 2, 3]\n * ```\n *\n * @since 2.0.0\n */\nexport const modifyNonEmptyHead: {\n  <A, B>(f: (a: A) => B): (self: NonEmptyReadonlyArray<A>) => NonEmptyArray<A | B>\n  <A, B>(self: NonEmptyReadonlyArray<A>, f: (a: A) => B): NonEmptyArray<A | B>\n} = dual(\n  2,\n  <A, B>(\n    self: NonEmptyReadonlyArray<A>,\n    f: (a: A) => B\n  ): NonEmptyArray<A | B> => [f(headNonEmpty(self)), ...tailNonEmpty(self)]\n)\n\n/**\n * Change the head, creating a new `NonEmptyReadonlyArray`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.setNonEmptyHead([1, 2, 3], 10)\n * console.log(result) // [10, 2, 3]\n * ```\n *\n * @since 2.0.0\n */\nexport const setNonEmptyHead: {\n  <B>(b: B): <A>(self: NonEmptyReadonlyArray<A>) => NonEmptyArray<A | B>\n  <A, B>(self: NonEmptyReadonlyArray<A>, b: B): NonEmptyArray<A | B>\n} = dual(\n  2,\n  <A, B>(self: NonEmptyReadonlyArray<A>, b: B): NonEmptyArray<A | B> => modifyNonEmptyHead(self, () => b)\n)\n\n/**\n * Apply a function to the last element, creating a new `NonEmptyReadonlyArray`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.modifyNonEmptyLast([1, 2, 3], n => n * 2)\n * console.log(result) // [1, 2, 6]\n * ```\n *\n * @since 2.0.0\n */\nexport const modifyNonEmptyLast: {\n  <A, B>(f: (a: A) => B): (self: NonEmptyReadonlyArray<A>) => NonEmptyArray<A | B>\n  <A, B>(self: NonEmptyReadonlyArray<A>, f: (a: A) => B): NonEmptyArray<A | B>\n} = dual(\n  2,\n  <A, B>(self: NonEmptyReadonlyArray<A>, f: (a: A) => B): NonEmptyArray<A | B> =>\n    append(initNonEmpty(self), f(lastNonEmpty(self)))\n)\n\n/**\n * Change the last element, creating a new `NonEmptyReadonlyArray`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.setNonEmptyLast([1, 2, 3], 4)\n * console.log(result) // [1, 2, 4]\n * ```\n *\n * @since 2.0.0\n */\nexport const setNonEmptyLast: {\n  <B>(b: B): <A>(self: NonEmptyReadonlyArray<A>) => NonEmptyArray<A | B>\n  <A, B>(self: NonEmptyReadonlyArray<A>, b: B): NonEmptyArray<A | B>\n} = dual(\n  2,\n  <A, B>(self: NonEmptyReadonlyArray<A>, b: B): NonEmptyArray<A | B> => modifyNonEmptyLast(self, () => b)\n)\n\n/**\n * Rotate an `Iterable` by `n` steps.\n * If the input is a non-empty array, the result is also a non-empty array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.rotate(['a', 'b', 'c', 'd', 'e'], 2)\n * console.log(result) // [ 'd', 'e', 'a', 'b', 'c' ]\n * ```\n *\n * @since 2.0.0\n */\nexport const rotate: {\n  (n: number): <S extends Iterable<any>>(self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>\n  <A>(self: NonEmptyReadonlyArray<A>, n: number): NonEmptyArray<A>\n  <A>(self: Iterable<A>, n: number): Array<A>\n} = dual(2, <A>(self: Iterable<A>, n: number): Array<A> => {\n  const input = fromIterable(self)\n  if (isNonEmptyReadonlyArray(input)) {\n    const len = input.length\n    const m = Math.round(n) % len\n    if (isOutOfBounds(Math.abs(m), input) || m === 0) {\n      return copy(input)\n    }\n    if (m < 0) {\n      const [f, s] = splitNonEmptyAt(input, -m)\n      return appendAll(s, f)\n    } else {\n      return rotate(self, m - len)\n    }\n  }\n  return []\n})\n\n/**\n * Returns a function that checks if a `ReadonlyArray` contains a given value using a provided `isEquivalent` function.\n *\n * **Example**\n *\n * ```ts\n * import { Array, pipe } from \"effect\"\n *\n * const isEquivalent = (a: number, b: number) => a === b\n * const containsNumber = Array.containsWith(isEquivalent)\n * const result = pipe([1, 2, 3, 4], containsNumber(3))\n * console.log(result) // true\n * ```\n *\n * @category elements\n * @since 2.0.0\n */\nexport const containsWith = <A>(isEquivalent: (self: A, that: A) => boolean): {\n  (a: A): (self: Iterable<A>) => boolean\n  (self: Iterable<A>, a: A): boolean\n} =>\n  dual(2, (self: Iterable<A>, a: A): boolean => {\n    for (const i of self) {\n      if (isEquivalent(a, i)) {\n        return true\n      }\n    }\n    return false\n  })\n\nconst _equivalence = Equal.equivalence()\n\n/**\n * Returns a function that checks if a `ReadonlyArray` contains a given value using the default `Equivalence`.\n *\n * **Example**\n *\n * ```ts\n * import { Array, pipe } from \"effect\"\n *\n * const result = pipe(['a', 'b', 'c', 'd'], Array.contains('c'))\n * console.log(result) // true\n * ```\n *\n * @category elements\n * @since 2.0.0\n */\nexport const contains: {\n  <A>(a: A): (self: Iterable<A>) => boolean\n  <A>(self: Iterable<A>, a: A): boolean\n} = containsWith(_equivalence)\n\n/**\n * A useful recursion pattern for processing an `Iterable` to produce a new `Array`, often used for \"chopping\" up the input\n * `Iterable`. Typically chop is called with some function that will consume an initial prefix of the `Iterable` and produce a\n * value and the rest of the `Array`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.chop([1, 2, 3, 4, 5], (as): [number, Array<number>] => [as[0] * 2, as.slice(1)])\n * console.log(result) // [2, 4, 6, 8, 10]\n *\n * // Explanation:\n * // The `chopFunction` takes the first element of the array, doubles it, and then returns it along with the rest of the array.\n * // The `chop` function applies this `chopFunction` recursively to the input array `[1, 2, 3, 4, 5]`,\n * // resulting in a new array `[2, 4, 6, 8, 10]`.\n * ```\n *\n * @since 2.0.0\n */\nexport const chop: {\n  <S extends Iterable<any>, B>(\n    f: (as: NonEmptyReadonlyArray<ReadonlyArray.Infer<S>>) => readonly [B, ReadonlyArray<ReadonlyArray.Infer<S>>]\n  ): (self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>\n  <A, B>(\n    self: NonEmptyReadonlyArray<A>,\n    f: (as: NonEmptyReadonlyArray<A>) => readonly [B, ReadonlyArray<A>]\n  ): NonEmptyArray<B>\n  <A, B>(\n    self: Iterable<A>,\n    f: (as: NonEmptyReadonlyArray<A>) => readonly [B, ReadonlyArray<A>]\n  ): Array<B>\n} = dual(2, <A, B>(\n  self: Iterable<A>,\n  f: (as: NonEmptyReadonlyArray<A>) => readonly [B, ReadonlyArray<A>]\n): Array<B> => {\n  const input = fromIterable(self)\n  if (isNonEmptyReadonlyArray(input)) {\n    const [b, rest] = f(input)\n    const out: NonEmptyArray<B> = [b]\n    let next: ReadonlyArray<A> = rest\n    while (internalArray.isNonEmptyArray(next)) {\n      const [b, rest] = f(next)\n      out.push(b)\n      next = rest\n    }\n    return out\n  }\n  return []\n})\n\n/**\n * Splits an `Iterable` into two segments, with the first segment containing a maximum of `n` elements.\n * The value of `n` can be `0`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.splitAt([1, 2, 3, 4, 5], 3)\n * console.log(result) // [[1, 2, 3], [4, 5]]\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitAt: {\n  (n: number): <A>(self: Iterable<A>) => [beforeIndex: Array<A>, fromIndex: Array<A>]\n  <A>(self: Iterable<A>, n: number): [beforeIndex: Array<A>, fromIndex: Array<A>]\n} = dual(2, <A>(self: Iterable<A>, n: number): [Array<A>, Array<A>] => {\n  const input = Array.from(self)\n  const _n = Math.floor(n)\n  if (isNonEmptyReadonlyArray(input)) {\n    if (_n >= 1) {\n      return splitNonEmptyAt(input, _n)\n    }\n    return [[], input]\n  }\n  return [input, []]\n})\n\n/**\n * Splits a `NonEmptyReadonlyArray` into two segments, with the first segment containing a maximum of `n` elements.\n * The value of `n` must be `>= 1`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.splitNonEmptyAt([\"a\", \"b\", \"c\", \"d\", \"e\"], 3)\n * console.log(result) // [[\"a\", \"b\", \"c\"], [\"d\", \"e\"]]\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitNonEmptyAt: {\n  (n: number): <A>(self: NonEmptyReadonlyArray<A>) => [beforeIndex: NonEmptyArray<A>, fromIndex: Array<A>]\n  <A>(self: NonEmptyReadonlyArray<A>, n: number): [beforeIndex: NonEmptyArray<A>, fromIndex: Array<A>]\n} = dual(2, <A>(self: NonEmptyReadonlyArray<A>, n: number): [NonEmptyArray<A>, Array<A>] => {\n  const _n = Math.max(1, Math.floor(n))\n  return _n >= self.length ?\n    [copy(self), []] :\n    [prepend(self.slice(1, _n), headNonEmpty(self)), self.slice(_n)]\n})\n\n/**\n * Splits this iterable into `n` equally sized arrays.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.split([1, 2, 3, 4, 5, 6, 7, 8], 3)\n * console.log(result) // [[1, 2, 3], [4, 5, 6], [7, 8]]\n * ```\n *\n * @since 2.0.0\n * @category splitting\n */\nexport const split: {\n  (n: number): <A>(self: Iterable<A>) => Array<Array<A>>\n  <A>(self: Iterable<A>, n: number): Array<Array<A>>\n} = dual(2, <A>(self: Iterable<A>, n: number) => {\n  const input = fromIterable(self)\n  return chunksOf(input, Math.ceil(input.length / Math.floor(n)))\n})\n\n/**\n * Splits this iterable on the first element that matches this predicate.\n * Returns a tuple containing two arrays: the first one is before the match, and the second one is from the match onward.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.splitWhere([1, 2, 3, 4, 5], n => n > 3)\n * console.log(result) // [[1, 2, 3], [4, 5]]\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitWhere: {\n  <A>(\n    predicate: (a: NoInfer<A>, i: number) => boolean\n  ): (self: Iterable<A>) => [beforeMatch: Array<A>, fromMatch: Array<A>]\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): [beforeMatch: Array<A>, fromMatch: Array<A>]\n} = dual(\n  2,\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): [beforeMatch: Array<A>, fromMatch: Array<A>] =>\n    span(self, (a: A, i: number) => !predicate(a, i))\n)\n\n/**\n * Copies an array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.copy([1, 2, 3])\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @since 2.0.0\n */\nexport const copy: {\n  <A>(self: NonEmptyReadonlyArray<A>): NonEmptyArray<A>\n  <A>(self: ReadonlyArray<A>): Array<A>\n} = (<A>(self: ReadonlyArray<A>): Array<A> => self.slice()) as any\n\n/**\n * Pads an array.\n * Returns a new array of length `n` with the elements of `array` followed by `fill` elements if `array` is shorter than `n`.\n * If `array` is longer than `n`, the returned array will be a slice of `array` containing the `n` first elements of `array`.\n * If `n` is less than or equal to 0, the returned array will be an empty array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.pad([1, 2, 3], 6, 0)\n * console.log(result) // [1, 2, 3, 0, 0, 0]\n * ```\n *\n * @since 3.8.4\n */\nexport const pad: {\n  <A, T>(\n    n: number,\n    fill: T\n  ): (\n    self: Array<A>\n  ) => Array<A | T>\n  <A, T>(self: Array<A>, n: number, fill: T): Array<A | T>\n} = dual(3, <A, T>(self: Array<A>, n: number, fill: T): Array<A | T> => {\n  if (self.length >= n) {\n    return take(self, n)\n  }\n  return appendAll(\n    self,\n    makeBy(n - self.length, () => fill)\n  )\n})\n\n/**\n * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of\n * the `Iterable`. Note that `chunksOf(n)([])` is `[]`, not `[[]]`. This is intentional, and is consistent with a recursive\n * definition of `chunksOf`; it satisfies the property that\n *\n * ```ts skip-type-checking\n * chunksOf(n)(xs).concat(chunksOf(n)(ys)) == chunksOf(n)(xs.concat(ys)))\n * ```\n *\n * whenever `n` evenly divides the length of `self`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.chunksOf([1, 2, 3, 4, 5], 2)\n * console.log(result) // [[1, 2], [3, 4], [5]]\n *\n * // Explanation:\n * // The `chunksOf` function takes an array of numbers `[1, 2, 3, 4, 5]` and a number `2`.\n * // It splits the array into chunks of length 2. Since the array length is not evenly divisible by 2,\n * // the last chunk contains the remaining elements.\n * // The result is `[[1, 2], [3, 4], [5]]`.\n * ```\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const chunksOf: {\n  (\n    n: number\n  ): <S extends Iterable<any>>(\n    self: S\n  ) => ReadonlyArray.With<S, NonEmptyArray<ReadonlyArray.Infer<S>>>\n  <A>(self: NonEmptyReadonlyArray<A>, n: number): NonEmptyArray<NonEmptyArray<A>>\n  <A>(self: Iterable<A>, n: number): Array<NonEmptyArray<A>>\n} = dual(2, <A>(self: Iterable<A>, n: number): Array<NonEmptyArray<A>> => {\n  const input = fromIterable(self)\n  if (isNonEmptyReadonlyArray(input)) {\n    return chop(input, splitNonEmptyAt(n))\n  }\n  return []\n})\n\n/**\n * Creates sliding windows of size `n` from an `Iterable`.\n * If the number of elements is less than `n` or if `n` is not greater than zero,\n * an empty array is returned.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Array } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * assert.deepStrictEqual(Array.window(numbers, 3), [[1, 2, 3], [2, 3, 4], [3, 4, 5]])\n * assert.deepStrictEqual(Array.window(numbers, 6), [])\n * ```\n *\n * @category splitting\n * @since 3.13.2\n */\nexport const window: {\n  <N extends number = number>(\n    n: N\n  ): <A>(self: Iterable<A>) => Array<TupleOf<N, A>>\n  <A, N extends number = number>(\n    self: Iterable<A>,\n    n: N\n  ): Array<TupleOf<N, A>>\n} = dual(2, <A, const N extends number>(self: Iterable<A>, n: N): Array<Array<A>> => {\n  const input = fromIterable(self)\n  if (n > 0 && isNonEmptyReadonlyArray(input)) {\n    return Array.from(\n      { length: input.length - (n - 1) },\n      (_, index) => input.slice(index, index + n)\n    )\n  }\n  return []\n})\n\n/**\n * Group equal, consecutive elements of a `NonEmptyReadonlyArray` into `NonEmptyArray`s using the provided `isEquivalent` function.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.groupWith([\"a\", \"a\", \"b\", \"b\", \"b\", \"c\", \"a\"], (x, y) => x === y)\n * console.log(result) // [[\"a\", \"a\"], [\"b\", \"b\", \"b\"], [\"c\"], [\"a\"]]\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupWith: {\n  <A>(isEquivalent: (self: A, that: A) => boolean): (self: NonEmptyReadonlyArray<A>) => NonEmptyArray<NonEmptyArray<A>>\n  <A>(self: NonEmptyReadonlyArray<A>, isEquivalent: (self: A, that: A) => boolean): NonEmptyArray<NonEmptyArray<A>>\n} = dual(\n  2,\n  <A>(self: NonEmptyReadonlyArray<A>, isEquivalent: (self: A, that: A) => boolean): NonEmptyArray<NonEmptyArray<A>> =>\n    chop(self, (as) => {\n      const h = headNonEmpty(as)\n      const out: NonEmptyArray<A> = [h]\n      let i = 1\n      for (; i < as.length; i++) {\n        const a = as[i]\n        if (isEquivalent(a, h)) {\n          out.push(a)\n        } else {\n          break\n        }\n      }\n      return [out, as.slice(i)]\n    })\n)\n\n/**\n * Group equal, consecutive elements of a `NonEmptyReadonlyArray` into `NonEmptyArray`s.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.group([1, 1, 2, 2, 2, 3, 1])\n * console.log(result) // [[1, 1], [2, 2, 2], [3], [1]]\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const group: <A>(self: NonEmptyReadonlyArray<A>) => NonEmptyArray<NonEmptyArray<A>> = groupWith(\n  Equal.equivalence()\n)\n\n/**\n * Splits an `Iterable` into sub-non-empty-arrays stored in an object, based on the result of calling a `string`-returning\n * function on each element, and grouping the results according to values returned\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const people = [\n *   { name: \"Alice\", group: \"A\" },\n *   { name: \"Bob\", group: \"B\" },\n *   { name: \"Charlie\", group: \"A\" }\n * ]\n *\n * const result = Array.groupBy(people, person => person.group)\n * console.log(result)\n * // {\n * //  A: [{ name: \"Alice\", group: \"A\" }, { name: \"Charlie\", group: \"A\" }],\n * //  B: [{ name: \"Bob\", group: \"B\" }]\n * // }\n * ```\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupBy: {\n  <A, K extends string | symbol>(\n    f: (a: A) => K\n  ): (self: Iterable<A>) => Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>>\n  <A, K extends string | symbol>(\n    self: Iterable<A>,\n    f: (a: A) => K\n  ): Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>>\n} = dual(2, <A, K extends string | symbol>(\n  self: Iterable<A>,\n  f: (a: A) => K\n): Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>> => {\n  const out: Record<string | symbol, NonEmptyArray<A>> = {}\n  for (const a of self) {\n    const k = f(a)\n    if (Object.prototype.hasOwnProperty.call(out, k)) {\n      out[k].push(a)\n    } else {\n      out[k] = [a]\n    }\n  }\n  return out\n})\n\n/**\n * Calculates the union of two arrays using the provided equivalence relation.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const union = Array.unionWith([1, 2], [2, 3], (a, b) => a === b)\n * console.log(union) // [1, 2, 3]\n * ```\n *\n * @since 2.0.0\n */\nexport const unionWith: {\n  <S extends Iterable<any>, T extends Iterable<any>>(\n    that: T,\n    isEquivalent: (self: ReadonlyArray.Infer<S>, that: ReadonlyArray.Infer<T>) => boolean\n  ): (self: S) => ReadonlyArray.OrNonEmpty<S, T, ReadonlyArray.Infer<S> | ReadonlyArray.Infer<T>>\n  <A, B>(\n    self: NonEmptyReadonlyArray<A>,\n    that: Iterable<B>,\n    isEquivalent: (self: A, that: B) => boolean\n  ): NonEmptyArray<A | B>\n  <A, B>(\n    self: Iterable<A>,\n    that: NonEmptyReadonlyArray<B>,\n    isEquivalent: (self: A, that: B) => boolean\n  ): NonEmptyArray<A | B>\n  <A, B>(self: Iterable<A>, that: Iterable<B>, isEquivalent: (self: A, that: B) => boolean): Array<A | B>\n} = dual(3, <A>(self: Iterable<A>, that: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): Array<A> => {\n  const a = fromIterable(self)\n  const b = fromIterable(that)\n  if (isNonEmptyReadonlyArray(a)) {\n    if (isNonEmptyReadonlyArray(b)) {\n      const dedupe = dedupeWith(isEquivalent)\n      return dedupe(appendAll(a, b))\n    }\n    return a\n  }\n  return b\n})\n\n/**\n * Creates a union of two arrays, removing duplicates.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.union([1, 2], [2, 3])\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @since 2.0.0\n */\nexport const union: {\n  <T extends Iterable<any>>(\n    that: T\n  ): <S extends Iterable<any>>(\n    self: S\n  ) => ReadonlyArray.OrNonEmpty<S, T, ReadonlyArray.Infer<S> | ReadonlyArray.Infer<T>>\n  <A, B>(self: NonEmptyReadonlyArray<A>, that: ReadonlyArray<B>): NonEmptyArray<A | B>\n  <A, B>(self: ReadonlyArray<A>, that: NonEmptyReadonlyArray<B>): NonEmptyArray<A | B>\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Array<A | B>\n} = dual(2, <A, B>(self: Iterable<A>, that: Iterable<B>): Array<A | B> => unionWith(self, that, _equivalence))\n\n/**\n * Creates an `Array` of unique values that are included in all given `Iterable`s using the provided `isEquivalent` function.\n * The order and references of result values are determined by the first `Iterable`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]\n * const array2 = [{ id: 3 }, { id: 4 }, { id: 1 }]\n * const isEquivalent = (a: { id: number }, b: { id: number }) => a.id === b.id\n * const result = Array.intersectionWith(isEquivalent)(array2)(array1)\n * console.log(result) // [{ id: 1 }, { id: 3 }]\n * ```\n *\n * @since 2.0.0\n */\nexport const intersectionWith = <A>(isEquivalent: (self: A, that: A) => boolean): {\n  (that: Iterable<A>): (self: Iterable<A>) => Array<A>\n  (self: Iterable<A>, that: Iterable<A>): Array<A>\n} => {\n  const has = containsWith(isEquivalent)\n  return dual(\n    2,\n    (self: Iterable<A>, that: Iterable<A>): Array<A> => {\n      const bs = fromIterable(that)\n      return fromIterable(self).filter((a) => has(bs, a))\n    }\n  )\n}\n\n/**\n * Creates an `Array` of unique values that are included in all given `Iterable`s.\n * The order and references of result values are determined by the first `Iterable`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.intersection([1, 2, 3], [3, 4, 1])\n * console.log(result) // [1, 3]\n * ```\n *\n * @since 2.0.0\n */\nexport const intersection: {\n  <B>(that: Iterable<B>): <A>(self: Iterable<A>) => Array<A & B>\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Array<A & B>\n} = intersectionWith(_equivalence)\n\n/**\n * Creates a `Array` of values not included in the other given `Iterable` using the provided `isEquivalent` function.\n * The order and references of result values are determined by the first `Iterable`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const array1 = [1, 2, 3]\n * const array2 = [2, 3, 4]\n * const difference = Array.differenceWith<number>((a, b) => a === b)(array1, array2)\n * console.log(difference) // [1]\n * ```\n *\n * @since 2.0.0\n */\nexport const differenceWith = <A>(isEquivalent: (self: A, that: A) => boolean): {\n  (that: Iterable<A>): (self: Iterable<A>) => Array<A>\n  (self: Iterable<A>, that: Iterable<A>): Array<A>\n} => {\n  const has = containsWith(isEquivalent)\n  return dual(\n    2,\n    (self: Iterable<A>, that: Iterable<A>): Array<A> => {\n      const bs = fromIterable(that)\n      return fromIterable(self).filter((a) => !has(bs, a))\n    }\n  )\n}\n\n/**\n * Creates a `Array` of values not included in the other given `Iterable`.\n * The order and references of result values are determined by the first `Iterable`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const difference = Array.difference([1, 2, 3], [2, 3, 4])\n * console.log(difference) // [1]\n * ```\n *\n * @since 2.0.0\n */\nexport const difference: {\n  <A>(that: Iterable<A>): (self: Iterable<A>) => Array<A>\n  <A>(self: Iterable<A>, that: Iterable<A>): Array<A>\n} = differenceWith(_equivalence)\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport const empty: <A = never>() => Array<A> = () => []\n\n/**\n * Constructs a new `NonEmptyArray<A>` from the specified value.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const of = <A>(a: A): NonEmptyArray<A> => [a]\n\n/**\n * @since 2.0.0\n */\nexport declare namespace ReadonlyArray {\n  /**\n   * @since 2.0.0\n   */\n  export type Infer<S extends Iterable<any>> = S extends ReadonlyArray<infer A> ? A\n    : S extends Iterable<infer A> ? A\n    : never\n\n  /**\n   * @since 2.0.0\n   */\n  export type With<S extends Iterable<any>, A> = S extends NonEmptyReadonlyArray<any> ? NonEmptyArray<A>\n    : Array<A>\n\n  /**\n   * @since 2.0.0\n   */\n  export type OrNonEmpty<\n    S extends Iterable<any>,\n    T extends Iterable<any>,\n    A\n  > = S extends NonEmptyReadonlyArray<any> ? NonEmptyArray<A>\n    : T extends NonEmptyReadonlyArray<any> ? NonEmptyArray<A>\n    : Array<A>\n\n  /**\n   * @since 2.0.0\n   */\n  export type AndNonEmpty<\n    S extends Iterable<any>,\n    T extends Iterable<any>,\n    A\n  > = S extends NonEmptyReadonlyArray<any> ? T extends NonEmptyReadonlyArray<any> ? NonEmptyArray<A>\n    : Array<A>\n    : Array<A>\n\n  /**\n   * @since 2.0.0\n   */\n  export type Flatten<T extends ReadonlyArray<ReadonlyArray<any>>> = T extends\n    NonEmptyReadonlyArray<NonEmptyReadonlyArray<any>> ? NonEmptyArray<T[number][number]>\n    : Array<T[number][number]>\n}\n\n/**\n * @category mapping\n * @since 2.0.0\n */\nexport const map: {\n  <S extends ReadonlyArray<any>, B>(\n    f: (a: ReadonlyArray.Infer<S>, i: number) => B\n  ): (self: S) => ReadonlyArray.With<S, B>\n  <S extends ReadonlyArray<any>, B>(self: S, f: (a: ReadonlyArray.Infer<S>, i: number) => B): ReadonlyArray.With<S, B>\n} = dual(2, <A, B>(self: ReadonlyArray<A>, f: (a: A, i: number) => B): Array<B> => self.map(f))\n\n/**\n * Applies a function to each element in an array and returns a new array containing the concatenated mapped elements.\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap: {\n  <S extends ReadonlyArray<any>, T extends ReadonlyArray<any>>(\n    f: (a: ReadonlyArray.Infer<S>, i: number) => T\n  ): (self: S) => ReadonlyArray.AndNonEmpty<S, T, ReadonlyArray.Infer<T>>\n  <A, B>(self: NonEmptyReadonlyArray<A>, f: (a: A, i: number) => NonEmptyReadonlyArray<B>): NonEmptyArray<B>\n  <A, B>(self: ReadonlyArray<A>, f: (a: A, i: number) => ReadonlyArray<B>): Array<B>\n} = dual(\n  2,\n  <A, B>(self: ReadonlyArray<A>, f: (a: A, i: number) => ReadonlyArray<B>): Array<B> => {\n    if (isEmptyReadonlyArray(self)) {\n      return []\n    }\n    const out: Array<B> = []\n    for (let i = 0; i < self.length; i++) {\n      const inner = f(self[i], i)\n      for (let j = 0; j < inner.length; j++) {\n        out.push(inner[j])\n      }\n    }\n    return out\n  }\n)\n\n/**\n * Combines multiple arrays into a single array by concatenating all elements\n * from each nested array. This function ensures that the structure of nested\n * arrays is collapsed into a single, flat array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.flatten([[1, 2], [], [3, 4], [], [5, 6]])\n * console.log(result) // [1, 2, 3, 4, 5, 6]\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatten: <const S extends ReadonlyArray<ReadonlyArray<any>>>(\n  self: S\n) => ReadonlyArray.Flatten<S> = flatMap(\n  identity\n) as any\n\n/**\n * Applies a function to each element of the `Iterable` and filters based on the result, keeping the transformed values where the function returns `Some`.\n * This method combines filtering and mapping functionalities, allowing transformations and filtering of elements based on a single function pass.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Option } from \"effect\"\n *\n * const evenSquares = (x: number) => x % 2 === 0 ? Option.some(x * x) : Option.none()\n *\n * const result = Array.filterMap([1, 2, 3, 4, 5], evenSquares);\n * console.log(result) // [4, 16]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap: {\n  <A, B>(f: (a: A, i: number) => Option.Option<B>): (self: Iterable<A>) => Array<B>\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option.Option<B>): Array<B>\n} = dual(\n  2,\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option.Option<B>): Array<B> => {\n    const as = fromIterable(self)\n    const out: Array<B> = []\n    for (let i = 0; i < as.length; i++) {\n      const o = f(as[i], i)\n      if (Option.isSome(o)) {\n        out.push(o.value)\n      }\n    }\n    return out\n  }\n)\n\n/**\n * Applies a function to each element of the array and filters based on the result, stopping when a condition is not met.\n * This method combines filtering and mapping in a single pass, and short-circuits, i.e., stops processing, as soon as the function returns `None`.\n * This is useful when you need to transform an array but only up to the point where a certain condition holds true.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Option } from \"effect\"\n *\n * const toSquareTillOdd = (x: number) => x % 2 === 0 ? Option.some(x * x) : Option.none()\n *\n * const result = Array.filterMapWhile([2, 4, 5], toSquareTillOdd)\n * console.log(result) // [4, 16]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMapWhile: {\n  <A, B>(f: (a: A, i: number) => Option.Option<B>): (self: Iterable<A>) => Array<B>\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option.Option<B>): Array<B>\n} = dual(2, <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option.Option<B>) => {\n  let i = 0\n  const out: Array<B> = []\n  for (const a of self) {\n    const b = f(a, i)\n    if (Option.isSome(b)) {\n      out.push(b.value)\n    } else {\n      break\n    }\n    i++\n  }\n  return out\n})\n\n/**\n * Applies a function to each element of the `Iterable`, categorizing the results into two separate arrays.\n * This function is particularly useful for operations where each element can result in two possible types,\n * and you want to separate these types into different collections. For instance, separating validation results\n * into successes and failures.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Either } from \"effect\";\n *\n * const isEven = (x: number) => x % 2 === 0\n *\n * const result = Array.partitionMap([1, 2, 3, 4, 5], x =>\n *   isEven(x) ? Either.right(x) : Either.left(x)\n * )\n * console.log(result)\n * // [\n * //   [1, 3, 5],\n * //   [2, 4]\n * // ]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partitionMap: {\n  <A, B, C>(f: (a: A, i: number) => Either.Either<C, B>): (self: Iterable<A>) => [left: Array<B>, right: Array<C>]\n  <A, B, C>(self: Iterable<A>, f: (a: A, i: number) => Either.Either<C, B>): [left: Array<B>, right: Array<C>]\n} = dual(\n  2,\n  <A, B, C>(self: Iterable<A>, f: (a: A, i: number) => Either.Either<C, B>): [left: Array<B>, right: Array<C>] => {\n    const left: Array<B> = []\n    const right: Array<C> = []\n    const as = fromIterable(self)\n    for (let i = 0; i < as.length; i++) {\n      const e = f(as[i], i)\n      if (Either.isLeft(e)) {\n        left.push(e.left)\n      } else {\n        right.push(e.right)\n      }\n    }\n    return [left, right]\n  }\n)\n\n/**\n * Retrieves the `Some` values from an `Iterable` of `Option`s, collecting them into an array.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Option } from \"effect\"\n *\n * const result = Array.getSomes([Option.some(1), Option.none(), Option.some(2)])\n * console.log(result) // [1, 2]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\n\nexport const getSomes: <T extends Iterable<Option.Option<X>>, X = any>(\n  self: T\n) => Array<Option.Option.Value<ReadonlyArray.Infer<T>>> = filterMap(identity as any)\n\n/**\n * Retrieves the `Left` values from an `Iterable` of `Either`s, collecting them into an array.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Either } from \"effect\"\n *\n * const result = Array.getLefts([Either.right(1), Either.left(\"err\"), Either.right(2)])\n * console.log(result) // [\"err\"]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getLefts = <T extends Iterable<Either.Either<any, any>>>(\n  self: T\n): Array<Either.Either.Left<ReadonlyArray.Infer<T>>> => {\n  const out: Array<any> = []\n  for (const a of self) {\n    if (Either.isLeft(a)) {\n      out.push(a.left)\n    }\n  }\n\n  return out\n}\n\n/**\n * Retrieves the `Right` values from an `Iterable` of `Either`s, collecting them into an array.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Either } from \"effect\"\n *\n * const result = Array.getRights([Either.right(1), Either.left(\"err\"), Either.right(2)])\n * console.log(result) // [1, 2]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getRights = <T extends Iterable<Either.Either<any, any>>>(\n  self: T\n): Array<Either.Either.Right<ReadonlyArray.Infer<T>>> => {\n  const out: Array<any> = []\n  for (const a of self) {\n    if (Either.isRight(a)) {\n      out.push(a.right)\n    }\n  }\n\n  return out\n}\n\n/**\n * @category filtering\n * @since 2.0.0\n */\nexport const filter: {\n  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Array<B>\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Array<A>\n  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Array<B>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Array<A>\n} = dual(\n  2,\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Array<A> => {\n    const as = fromIterable(self)\n    const out: Array<A> = []\n    for (let i = 0; i < as.length; i++) {\n      if (predicate(as[i], i)) {\n        out.push(as[i])\n      }\n    }\n    return out\n  }\n)\n\n/**\n * Separate elements based on a predicate that also exposes the index of the element.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.partition([1, 2, 3, 4], n => n % 2 === 0)\n * console.log(result) // [[1, 3], [2, 4]]\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partition: {\n  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (\n    self: Iterable<A>\n  ) => [excluded: Array<Exclude<A, B>>, satisfying: Array<B>]\n  <A>(\n    predicate: (a: NoInfer<A>, i: number) => boolean\n  ): (self: Iterable<A>) => [excluded: Array<A>, satisfying: Array<A>]\n  <A, B extends A>(\n    self: Iterable<A>,\n    refinement: (a: A, i: number) => a is B\n  ): [excluded: Array<Exclude<A, B>>, satisfying: Array<B>]\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): [excluded: Array<A>, satisfying: Array<A>]\n} = dual(\n  2,\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): [excluded: Array<A>, satisfying: Array<A>] => {\n    const left: Array<A> = []\n    const right: Array<A> = []\n    const as = fromIterable(self)\n    for (let i = 0; i < as.length; i++) {\n      if (predicate(as[i], i)) {\n        right.push(as[i])\n      } else {\n        left.push(as[i])\n      }\n    }\n    return [left, right]\n  }\n)\n\n/**\n * Separates an `Iterable` into two arrays based on a predicate.\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const separate: <T extends Iterable<Either.Either<any, any>>>(\n  self: T\n) => [Array<Either.Either.Left<ReadonlyArray.Infer<T>>>, Array<Either.Either.Right<ReadonlyArray.Infer<T>>>] =\n  partitionMap(identity)\n\n/**\n * Reduces an array from the left.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.reduce([1, 2, 3], 0, (acc, n) => acc + n)\n * console.log(result) // 6\n * ```\n *\n * @category folding\n * @since 2.0.0\n */\nexport const reduce: {\n  <B, A>(b: B, f: (b: B, a: A, i: number) => B): (self: Iterable<A>) => B\n  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A, i: number) => B): B\n} = dual(\n  3,\n  <B, A>(self: Iterable<A>, b: B, f: (b: B, a: A, i: number) => B): B =>\n    fromIterable(self).reduce((b, a, i) => f(b, a, i), b)\n)\n\n/**\n * Reduces an array from the right.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.reduceRight([1, 2, 3], 0, (acc, n) => acc + n)\n * console.log(result) // 6\n * ```\n *\n * @category folding\n * @since 2.0.0\n */\nexport const reduceRight: {\n  <B, A>(b: B, f: (b: B, a: A, i: number) => B): (self: Iterable<A>) => B\n  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A, i: number) => B): B\n} = dual(\n  3,\n  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A, i: number) => B): B =>\n    fromIterable(self).reduceRight((b, a, i) => f(b, a, i), b)\n)\n\n/**\n * Lifts a predicate into an array.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const isEven = (n: number) => n % 2 === 0\n * const to = Array.liftPredicate(isEven)\n * console.log(to(1)) // []\n * console.log(to(2)) // [2]\n * ```\n *\n * @category lifting\n * @since 2.0.0\n */\nexport const liftPredicate: { // Note: I intentionally avoid using the NoInfer pattern here.\n  <A, B extends A>(refinement: Predicate.Refinement<A, B>): (a: A) => Array<B>\n  <A>(predicate: Predicate.Predicate<A>): <B extends A>(b: B) => Array<B>\n} = <A>(predicate: Predicate.Predicate<A>) => <B extends A>(b: B): Array<B> => predicate(b) ? [b] : []\n\n/**\n * @category lifting\n * @since 2.0.0\n */\nexport const liftOption = <A extends Array<unknown>, B>(\n  f: (...a: A) => Option.Option<B>\n) =>\n(...a: A): Array<B> => fromOption(f(...a))\n\n/**\n * @category conversions\n * @since 2.0.0\n */\nexport const fromNullable = <A>(a: A): Array<NonNullable<A>> => a == null ? empty() : [a as NonNullable<A>]\n\n/**\n * @category lifting\n * @since 2.0.0\n */\nexport const liftNullable = <A extends Array<unknown>, B>(\n  f: (...a: A) => B | null | undefined\n): (...a: A) => Array<NonNullable<B>> =>\n(...a) => fromNullable(f(...a))\n\n/**\n * Maps over an array and flattens the result, removing null and undefined values.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.flatMapNullable([1, 2, 3], n => (n % 2 === 0 ? null : n))\n * console.log(result) // [1, 3]\n *\n * // Explanation:\n * // The array of numbers [1, 2, 3] is mapped with a function that returns null for even numbers\n * // and the number itself for odd numbers. The resulting array [1, null, 3] is then flattened\n * // to remove null values, resulting in [1, 3].\n * ```\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMapNullable: {\n  <A, B>(f: (a: A) => B | null | undefined): (self: ReadonlyArray<A>) => Array<NonNullable<B>>\n  <A, B>(self: ReadonlyArray<A>, f: (a: A) => B | null | undefined): Array<NonNullable<B>>\n} = dual(\n  2,\n  <A, B>(self: ReadonlyArray<A>, f: (a: A) => B | null | undefined): Array<NonNullable<B>> =>\n    flatMap(self, (a) => fromNullable(f(a)))\n)\n\n/**\n * Lifts a function that returns an `Either` into a function that returns an array.\n * If the `Either` is a left, it returns an empty array.\n * If the `Either` is a right, it returns an array with the right value.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Either } from \"effect\"\n *\n * const parseNumber = (s: string): Either.Either<number, Error> =>\n *   isNaN(Number(s)) ? Either.left(new Error(\"Not a number\")) : Either.right(Number(s))\n *\n * const liftedParseNumber = Array.liftEither(parseNumber)\n *\n * const result1 = liftedParseNumber(\"42\")\n * console.log(result1) // [42]\n *\n * const result2 = liftedParseNumber(\"not a number\")\n * console.log(result2) // []\n *\n * // Explanation:\n * // The function parseNumber is lifted to return an array.\n * // When parsing \"42\", it returns an Either.left with the number 42, resulting in [42].\n * // When parsing \"not a number\", it returns an Either.right with an error, resulting in an empty array [].\n * ```\n *\n * @category lifting\n * @since 2.0.0\n */\nexport const liftEither = <A extends Array<unknown>, E, B>(\n  f: (...a: A) => Either.Either<B, E>\n) =>\n(...a: A): Array<B> => {\n  const e = f(...a)\n  return Either.isLeft(e) ? [] : [e.right]\n}\n\n/**\n * Check if a predicate holds true for every `ReadonlyArray` element.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const every: {\n  <A, B extends A>(\n    refinement: (a: NoInfer<A>, i: number) => a is B\n  ): (self: ReadonlyArray<A>) => self is ReadonlyArray<B>\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: ReadonlyArray<A>) => boolean\n  <A, B extends A>(self: ReadonlyArray<A>, refinement: (a: A, i: number) => a is B): self is ReadonlyArray<B>\n  <A>(self: ReadonlyArray<A>, predicate: (a: A, i: number) => boolean): boolean\n} = dual(\n  2,\n  <A, B extends A>(self: ReadonlyArray<A>, refinement: (a: A, i: number) => a is B): self is ReadonlyArray<B> =>\n    self.every(refinement)\n)\n\n/**\n * Check if a predicate holds true for some `ReadonlyArray` element.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const some: {\n  <A>(\n    predicate: (a: NoInfer<A>, i: number) => boolean\n  ): (self: ReadonlyArray<A>) => self is NonEmptyReadonlyArray<A>\n  <A>(self: ReadonlyArray<A>, predicate: (a: A, i: number) => boolean): self is NonEmptyReadonlyArray<A>\n} = dual(\n  2,\n  <A>(self: ReadonlyArray<A>, predicate: (a: A, i: number) => boolean): self is NonEmptyReadonlyArray<A> =>\n    self.some(predicate)\n)\n\n/**\n * Extends an array with a function that maps each subarray to a value.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.extend([1, 2, 3], as => as.length)\n * console.log(result) // [3, 2, 1]\n *\n * // Explanation:\n * // The function maps each subarray starting from each element to its length.\n * // The subarrays are: [1, 2, 3], [2, 3], [3].\n * // The lengths are: 3, 2, 1.\n * // Therefore, the result is [3, 2, 1].\n * ```\n *\n * @since 2.0.0\n */\nexport const extend: {\n  <A, B>(f: (as: ReadonlyArray<A>) => B): (self: ReadonlyArray<A>) => Array<B>\n  <A, B>(self: ReadonlyArray<A>, f: (as: ReadonlyArray<A>) => B): Array<B>\n} = dual(\n  2,\n  <A, B>(self: ReadonlyArray<A>, f: (as: ReadonlyArray<A>) => B): Array<B> => self.map((_, i, as) => f(as.slice(i)))\n)\n\n/**\n * Finds the minimum element in an array based on a comparator.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Order } from \"effect\"\n *\n * const result = Array.min([3, 1, 2], Order.number)\n * console.log(result) // 1\n * ```\n *\n * @since 2.0.0\n */\nexport const min: {\n  <A>(O: Order.Order<A>): (self: NonEmptyReadonlyArray<A>) => A\n  <A>(self: NonEmptyReadonlyArray<A>, O: Order.Order<A>): A\n} = dual(2, <A>(self: NonEmptyReadonlyArray<A>, O: Order.Order<A>): A => self.reduce(Order.min(O)))\n\n/**\n * Finds the maximum element in an array based on a comparator.\n *\n * **Example**\n *\n * ```ts\n * import { Array, Order } from \"effect\"\n *\n * const result = Array.max([3, 1, 2], Order.number)\n * console.log(result) // 3\n * ```\n *\n * @since 2.0.0\n */\nexport const max: {\n  <A>(O: Order.Order<A>): (self: NonEmptyReadonlyArray<A>) => A\n  <A>(self: NonEmptyReadonlyArray<A>, O: Order.Order<A>): A\n} = dual(2, <A>(self: NonEmptyReadonlyArray<A>, O: Order.Order<A>): A => self.reduce(Order.max(O)))\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport const unfold = <B, A>(b: B, f: (b: B) => Option.Option<readonly [A, B]>): Array<A> => {\n  const out: Array<A> = []\n  let next: B = b\n  let o: Option.Option<readonly [A, B]>\n  while (Option.isSome(o = f(next))) {\n    const [a, b] = o.value\n    out.push(a)\n    next = b\n  }\n  return out\n}\n\n/**\n * This function creates and returns a new `Order` for an array of values based on a given `Order` for the elements of the array.\n * The returned `Order` compares two arrays by applying the given `Order` to each element in the arrays.\n * If all elements are equal, the arrays are then compared based on their length.\n * It is useful when you need to compare two arrays of the same type and you have a specific way of comparing each element of the array.\n *\n * @category instances\n * @since 2.0.0\n */\nexport const getOrder: <A>(O: Order.Order<A>) => Order.Order<ReadonlyArray<A>> = Order.array\n\n/**\n * Creates an equivalence relation for arrays.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const eq = Array.getEquivalence<number>((a, b) => a === b)\n * console.log(eq([1, 2, 3], [1, 2, 3])) // true\n * ```\n *\n * @category instances\n * @since 2.0.0\n */\nexport const getEquivalence: <A>(\n  isEquivalent: Equivalence.Equivalence<A>\n) => Equivalence.Equivalence<ReadonlyArray<A>> = Equivalence.array\n\n/**\n * Performs a side-effect for each element of the `Iterable`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * Array.forEach([1, 2, 3], n => console.log(n)) // 1, 2, 3\n * ```\n *\n * @since 2.0.0\n */\nexport const forEach: {\n  <A>(f: (a: A, i: number) => void): (self: Iterable<A>) => void\n  <A>(self: Iterable<A>, f: (a: A, i: number) => void): void\n} = dual(2, <A>(self: Iterable<A>, f: (a: A, i: number) => void): void => fromIterable(self).forEach((a, i) => f(a, i)))\n\n/**\n * Remove duplicates from an `Iterable` using the provided `isEquivalent` function,\n * preserving the order of the first occurrence of each element.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.dedupeWith([1, 2, 2, 3, 3, 3], (a, b) => a === b)\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @since 2.0.0\n */\nexport const dedupeWith: {\n  <S extends Iterable<any>>(\n    isEquivalent: (self: ReadonlyArray.Infer<S>, that: ReadonlyArray.Infer<S>) => boolean\n  ): (self: S) => ReadonlyArray.With<S, ReadonlyArray.Infer<S>>\n  <A>(self: NonEmptyReadonlyArray<A>, isEquivalent: (self: A, that: A) => boolean): NonEmptyArray<A>\n  <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): Array<A>\n} = dual(\n  2,\n  <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): Array<A> => {\n    const input = fromIterable(self)\n    if (isNonEmptyReadonlyArray(input)) {\n      const out: NonEmptyArray<A> = [headNonEmpty(input)]\n      const rest = tailNonEmpty(input)\n      for (const r of rest) {\n        if (out.every((a) => !isEquivalent(r, a))) {\n          out.push(r)\n        }\n      }\n      return out\n    }\n    return []\n  }\n)\n\n/**\n * Remove duplicates from an `Iterable`, preserving the order of the first occurrence of each element.\n * The equivalence used to compare elements is provided by `Equal.equivalence()` from the `Equal` module.\n *\n * @since 2.0.0\n */\nexport const dedupe = <S extends Iterable<any>>(\n  self: S\n): S extends NonEmptyReadonlyArray<infer A> ? NonEmptyArray<A> : S extends Iterable<infer A> ? Array<A> : never =>\n  dedupeWith(self, Equal.equivalence()) as any\n\n/**\n * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.dedupeAdjacentWith([1, 1, 2, 2, 3, 3], (a, b) => a === b)\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @since 2.0.0\n */\nexport const dedupeAdjacentWith: {\n  <A>(isEquivalent: (self: A, that: A) => boolean): (self: Iterable<A>) => Array<A>\n  <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): Array<A>\n} = dual(2, <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): Array<A> => {\n  const out: Array<A> = []\n  let lastA: Option.Option<A> = Option.none()\n  for (const a of self) {\n    if (Option.isNone(lastA) || !isEquivalent(a, lastA.value)) {\n      out.push(a)\n      lastA = Option.some(a)\n    }\n  }\n  return out\n})\n\n/**\n * Deduplicates adjacent elements that are identical.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.dedupeAdjacent([1, 1, 2, 2, 3, 3])\n * console.log(result) // [1, 2, 3]\n * ```\n *\n * @since 2.0.0\n */\nexport const dedupeAdjacent: <A>(self: Iterable<A>) => Array<A> = dedupeAdjacentWith(Equal.equivalence())\n\n/**\n * Joins the elements together with \"sep\" in the middle.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const strings = [\"a\", \"b\", \"c\"]\n * const joined = Array.join(strings, \"-\")\n * console.log(joined) // \"a-b-c\"\n * ```\n *\n * @since 2.0.0\n * @category folding\n */\nexport const join: {\n  (sep: string): (self: Iterable<string>) => string\n  (self: Iterable<string>, sep: string): string\n} = dual(2, (self: Iterable<string>, sep: string): string => fromIterable(self).join(sep))\n\n/**\n * Statefully maps over the chunk, producing new elements of type `B`.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.mapAccum([1, 2, 3], 0, (acc, n) => [acc + n, acc + n])\n * console.log(result) // [6, [1, 3, 6]]\n * ```\n *\n * @since 2.0.0\n * @category folding\n */\nexport const mapAccum: {\n  <S, A, B, I extends Iterable<A> = Iterable<A>>(\n    s: S,\n    f: (s: S, a: ReadonlyArray.Infer<I>, i: number) => readonly [S, B]\n  ): (self: I) => [state: S, mappedArray: ReadonlyArray.With<I, B>]\n  <S, A, B, I extends Iterable<A> = Iterable<A>>(\n    self: I,\n    s: S,\n    f: (s: S, a: ReadonlyArray.Infer<I>, i: number) => readonly [S, B]\n  ): [state: S, mappedArray: ReadonlyArray.With<I, B>]\n} = dual(\n  3,\n  <S, A, B>(self: Iterable<A>, s: S, f: (s: S, a: A, i: number) => [S, B]): [state: S, mappedArray: Array<B>] => {\n    let i = 0\n    let s1 = s\n    const out: Array<B> = []\n    for (const a of self) {\n      const r = f(s1, a, i)\n      s1 = r[0]\n      out.push(r[1])\n      i++\n    }\n    return [s1, out]\n  }\n)\n\n/**\n * Zips this chunk crosswise with the specified chunk using the specified combiner.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.cartesianWith([1, 2], [\"a\", \"b\"], (a, b) => `${a}-${b}`)\n * console.log(result) // [\"1-a\", \"1-b\", \"2-a\", \"2-b\"]\n * ```\n *\n * @since 2.0.0\n * @category elements\n */\nexport const cartesianWith: {\n  <A, B, C>(that: ReadonlyArray<B>, f: (a: A, b: B) => C): (self: ReadonlyArray<A>) => Array<C>\n  <A, B, C>(self: ReadonlyArray<A>, that: ReadonlyArray<B>, f: (a: A, b: B) => C): Array<C>\n} = dual(\n  3,\n  <A, B, C>(self: ReadonlyArray<A>, that: ReadonlyArray<B>, f: (a: A, b: B) => C): Array<C> =>\n    flatMap(self, (a) => map(that, (b) => f(a, b)))\n)\n\n/**\n * Zips this chunk crosswise with the specified chunk.\n *\n * **Example**\n *\n * ```ts\n * import { Array } from \"effect\"\n *\n * const result = Array.cartesian([1, 2], [\"a\", \"b\"])\n * console.log(result) // [[1, \"a\"], [1, \"b\"], [2, \"a\"], [2, \"b\"]]\n * ```\n *\n * @since 2.0.0\n * @category elements\n */\nexport const cartesian: {\n  <B>(that: ReadonlyArray<B>): <A>(self: ReadonlyArray<A>) => Array<[A, B]>\n  <A, B>(self: ReadonlyArray<A>, that: ReadonlyArray<B>): Array<[A, B]>\n} = dual(\n  2,\n  <A, B>(self: ReadonlyArray<A>, that: ReadonlyArray<B>): Array<[A, B]> => cartesianWith(self, that, (a, b) => [a, b])\n)\n\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n\n/**\n * The \"do simulation\" for array allows you to sequentially apply operations to the elements of arrays, just as nested loops allow you to go through all combinations of elements in an arrays.\n *\n * It can be used to simulate \"array comprehension\".\n * It's a technique that allows you to create new arrays by iterating over existing ones and applying specific **conditions** or **transformations** to the elements. It's like assembling a new collection from pieces of other collections based on certain rules.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Array` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n * 5. Regular `Array` functions like `map` and `filter` can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope\n *\n * **Example**\n *\n * ```ts\n * import { Array, pipe } from \"effect\"\n *\n * const doResult = pipe(\n *   Array.Do,\n *   Array.bind(\"x\", () => [1, 3, 5]),\n *   Array.bind(\"y\", () => [2, 4, 6]),\n *   Array.filter(({ x, y }) => x < y), // condition\n *   Array.map(({ x, y }) => [x, y] as const) // transformation\n * )\n * console.log(doResult) // [[1, 2], [1, 4], [1, 6], [3, 4], [3, 6], [5, 6]]\n *\n * // equivalent\n * const x = [1, 3, 5],\n *       y = [2, 4, 6],\n *       result = [];\n * for(let i = 0; i < x.length; i++) {\n *   for(let j = 0; j < y.length; j++) {\n *     const _x = x[i], _y = y[j];\n *     if(_x < _y) result.push([_x, _y] as const)\n *   }\n * }\n * ```\n *\n * @see {@link bindTo}\n * @see {@link bind}\n * @see {@link let_ let}\n *\n * @category do notation\n * @since 3.2.0\n */\nexport const Do: ReadonlyArray<{}> = of({})\n\n/**\n * The \"do simulation\" for array allows you to sequentially apply operations to the elements of arrays, just as nested loops allow you to go through all combinations of elements in an arrays.\n *\n * It can be used to simulate \"array comprehension\".\n * It's a technique that allows you to create new arrays by iterating over existing ones and applying specific **conditions** or **transformations** to the elements. It's like assembling a new collection from pieces of other collections based on certain rules.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Array` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n * 5. Regular `Array` functions like `map` and `filter` can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope\n *\n * **Example**\n *\n * ```ts\n * import { Array, pipe } from \"effect\"\n *\n * const doResult = pipe(\n *   Array.Do,\n *   Array.bind(\"x\", () => [1, 3, 5]),\n *   Array.bind(\"y\", () => [2, 4, 6]),\n *   Array.filter(({ x, y }) => x < y), // condition\n *   Array.map(({ x, y }) => [x, y] as const) // transformation\n * )\n * console.log(doResult) // [[1, 2], [1, 4], [1, 6], [3, 4], [3, 6], [5, 6]]\n *\n * // equivalent\n * const x = [1, 3, 5],\n *       y = [2, 4, 6],\n *       result = [];\n * for(let i = 0; i < x.length; i++) {\n *   for(let j = 0; j < y.length; j++) {\n *     const _x = x[i], _y = y[j];\n *     if(_x < _y) result.push([_x, _y] as const)\n *   }\n * }\n * ```\n *\n * @see {@link bindTo}\n * @see {@link Do}\n * @see {@link let_ let}\n *\n * @category do notation\n * @since 3.2.0\n */\nexport const bind: {\n  <A extends object, N extends string, B>(\n    tag: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => ReadonlyArray<B>\n  ): (\n    self: ReadonlyArray<A>\n  ) => Array<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }>\n  <A extends object, N extends string, B>(\n    self: ReadonlyArray<A>,\n    tag: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => ReadonlyArray<B>\n  ): Array<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }>\n} = internalDoNotation.bind<ReadonlyArrayTypeLambda>(map, flatMap) as any\n\n/**\n * The \"do simulation\" for array allows you to sequentially apply operations to the elements of arrays, just as nested loops allow you to go through all combinations of elements in an arrays.\n *\n * It can be used to simulate \"array comprehension\".\n * It's a technique that allows you to create new arrays by iterating over existing ones and applying specific **conditions** or **transformations** to the elements. It's like assembling a new collection from pieces of other collections based on certain rules.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Array` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n * 5. Regular `Array` functions like `map` and `filter` can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope\n *\n * **Example**\n *\n * ```ts\n * import { Array, pipe } from \"effect\"\n *\n * const doResult = pipe(\n *   Array.Do,\n *   Array.bind(\"x\", () => [1, 3, 5]),\n *   Array.bind(\"y\", () => [2, 4, 6]),\n *   Array.filter(({ x, y }) => x < y), // condition\n *   Array.map(({ x, y }) => [x, y] as const) // transformation\n * )\n * console.log(doResult) // [[1, 2], [1, 4], [1, 6], [3, 4], [3, 6], [5, 6]]\n *\n * // equivalent\n * const x = [1, 3, 5],\n *       y = [2, 4, 6],\n *       result = [];\n * for(let i = 0; i < x.length; i++) {\n *   for(let j = 0; j < y.length; j++) {\n *     const _x = x[i], _y = y[j];\n *     if(_x < _y) result.push([_x, _y] as const)\n *   }\n * }\n * ```\n *\n * @see {@link bindTo}\n * @see {@link Do}\n * @see {@link let_ let}\n *\n * @category do notation\n * @since 3.2.0\n */\nexport const bindTo: {\n  <N extends string>(tag: N): <A>(self: ReadonlyArray<A>) => Array<{ [K in N]: A }>\n  <A, N extends string>(self: ReadonlyArray<A>, tag: N): Array<{ [K in N]: A }>\n} = internalDoNotation.bindTo<ReadonlyArrayTypeLambda>(map) as any\n\nconst let_: {\n  <N extends string, B, A extends object>(\n    tag: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): (self: ReadonlyArray<A>) => Array<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }>\n  <N extends string, A extends object, B>(\n    self: ReadonlyArray<A>,\n    tag: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): Array<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }>\n} = internalDoNotation.let_<ReadonlyArrayTypeLambda>(map) as any\n\nexport {\n  /**\n   * The \"do simulation\" for array allows you to sequentially apply operations to the elements of arrays, just as nested loops allow you to go through all combinations of elements in an arrays.\n   *\n   * It can be used to simulate \"array comprehension\".\n   * It's a technique that allows you to create new arrays by iterating over existing ones and applying specific **conditions** or **transformations** to the elements. It's like assembling a new collection from pieces of other collections based on certain rules.\n   *\n   * Here's how the do simulation works:\n   *\n   * 1. Start the do simulation using the `Do` value\n   * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Array` values\n   * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n   * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n   * 5. Regular `Array` functions like `map` and `filter` can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope\n   *\n   * **Example**\n   *\n   * ```ts\n   * import { Array, pipe } from \"effect\"\n   *\n   * const doResult = pipe(\n   *   Array.Do,\n   *   Array.bind(\"x\", () => [1, 3, 5]),\n   *   Array.bind(\"y\", () => [2, 4, 6]),\n   *   Array.filter(({ x, y }) => x < y), // condition\n   *   Array.map(({ x, y }) => [x, y] as const) // transformation\n   * )\n   * console.log(doResult) // [[1, 2], [1, 4], [1, 6], [3, 4], [3, 6], [5, 6]]\n   *\n   * // equivalent\n   * const x = [1, 3, 5],\n   *       y = [2, 4, 6],\n   *       result = [];\n   * for(let i = 0; i < x.length; i++) {\n   *   for(let j = 0; j < y.length; j++) {\n   *     const _x = x[i], _y = y[j];\n   *     if(_x < _y) result.push([_x, _y] as const)\n   *   }\n   * }\n   *\n   * ```\n   *\n   * @see {@link bindTo}\n   * @see {@link bind}\n   * @see {@link Do}\n   *\n   * @category do notation\n   * @since 3.2.0\n   */\n  let_ as let\n}\n"
  },
  {
    "path": "packages/effect/src/BigDecimal.ts",
    "content": "/**\n * This module provides utility functions and type class instances for working with the `BigDecimal` type in TypeScript.\n * It includes functions for basic arithmetic operations, as well as type class instances for `Equivalence` and `Order`.\n *\n * A `BigDecimal` allows storing any real number to arbitrary precision; which avoids common floating point errors\n * (such as 0.1 + 0.2 ≠ 0.3) at the cost of complexity.\n *\n * Internally, `BigDecimal` uses a `BigInt` object, paired with a 64-bit integer which determines the position of the\n * decimal point. Therefore, the precision *is not* actually arbitrary, but limited to 2<sup>63</sup> decimal places.\n *\n * It is not recommended to convert a floating point number to a decimal directly, as the floating point representation\n * may be unexpected.\n *\n * @module BigDecimal\n * @since 2.0.0\n * @see {@link module:BigInt} for more similar operations on `bigint` types\n * @see {@link module:Number} for more similar operations on `number` types\n */\n\nimport * as Equal from \"./Equal.js\"\nimport * as equivalence from \"./Equivalence.js\"\nimport { dual, pipe } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport { type Inspectable, NodeInspectSymbol } from \"./Inspectable.js\"\nimport * as Option from \"./Option.js\"\nimport * as order from \"./Order.js\"\nimport type { Ordering } from \"./Ordering.js\"\nimport { type Pipeable, pipeArguments } from \"./Pipeable.js\"\nimport { hasProperty } from \"./Predicate.js\"\n\nconst DEFAULT_PRECISION = 100\nconst FINITE_INT_REGEX = /^[+-]?\\d+$/\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/BigDecimal\")\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface BigDecimal extends Equal.Equal, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n  readonly value: bigint\n  readonly scale: number\n  /** @internal */\n  normalized?: BigDecimal\n}\n\nconst BigDecimalProto: Omit<BigDecimal, \"value\" | \"scale\" | \"normalized\"> = {\n  [TypeId]: TypeId,\n  [Hash.symbol](this: BigDecimal): number {\n    const normalized = normalize(this)\n    return pipe(\n      Hash.hash(normalized.value),\n      Hash.combine(Hash.number(normalized.scale)),\n      Hash.cached(this)\n    )\n  },\n  [Equal.symbol](this: BigDecimal, that: unknown): boolean {\n    return isBigDecimal(that) && equals(this, that)\n  },\n  toString(this: BigDecimal) {\n    return `BigDecimal(${format(this)})`\n  },\n  toJSON(this: BigDecimal) {\n    return {\n      _id: \"BigDecimal\",\n      value: String(this.value),\n      scale: this.scale\n    }\n  },\n  [NodeInspectSymbol](this: BigDecimal) {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n} as const\n\n/**\n * Checks if a given value is a `BigDecimal`.\n *\n * @since 2.0.0\n * @category guards\n */\nexport const isBigDecimal = (u: unknown): u is BigDecimal => hasProperty(u, TypeId)\n\n/**\n * Creates a `BigDecimal` from a `bigint` value and a scale.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make = (value: bigint, scale: number): BigDecimal => {\n  const o = Object.create(BigDecimalProto)\n  o.value = value\n  o.scale = scale\n  return o\n}\n\n/**\n * Internal function used to create pre-normalized `BigDecimal`s.\n *\n * @internal\n */\nexport const unsafeMakeNormalized = (value: bigint, scale: number): BigDecimal => {\n  if (value !== bigint0 && value % bigint10 === bigint0) {\n    throw new RangeError(\"Value must be normalized\")\n  }\n\n  const o = make(value, scale)\n  o.normalized = o\n  return o\n}\n\nconst bigint0 = BigInt(0)\nconst bigint1 = BigInt(1)\nconst bigint10 = BigInt(10)\nconst zero = unsafeMakeNormalized(bigint0, 0)\n\n/**\n * Normalizes a given `BigDecimal` by removing trailing zeros.\n *\n * **Example**\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { normalize, make, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(normalize(unsafeFromString(\"123.00000\")), normalize(make(123n, 0)))\n * assert.deepStrictEqual(normalize(unsafeFromString(\"12300000\")), normalize(make(123n, -5)))\n * ```\n *\n * @since 2.0.0\n * @category scaling\n */\nexport const normalize = (self: BigDecimal): BigDecimal => {\n  if (self.normalized === undefined) {\n    if (self.value === bigint0) {\n      self.normalized = zero\n    } else {\n      const digits = `${self.value}`\n\n      let trail = 0\n      for (let i = digits.length - 1; i >= 0; i--) {\n        if (digits[i] === \"0\") {\n          trail++\n        } else {\n          break\n        }\n      }\n\n      if (trail === 0) {\n        self.normalized = self\n      }\n\n      const value = BigInt(digits.substring(0, digits.length - trail))\n      const scale = self.scale - trail\n      self.normalized = unsafeMakeNormalized(value, scale)\n    }\n  }\n\n  return self.normalized\n}\n\n/**\n * Scales a given `BigDecimal` to the specified scale.\n *\n * If the given scale is smaller than the current scale, the value will be rounded down to\n * the nearest integer.\n *\n * @since 2.0.0\n * @category scaling\n */\nexport const scale: {\n  (scale: number): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, scale: number): BigDecimal\n} = dual(2, (self: BigDecimal, scale: number): BigDecimal => {\n  if (scale > self.scale) {\n    return make(self.value * bigint10 ** BigInt(scale - self.scale), scale)\n  }\n\n  if (scale < self.scale) {\n    return make(self.value / bigint10 ** BigInt(self.scale - scale), scale)\n  }\n\n  return self\n})\n\n/**\n * Provides an addition operation on `BigDecimal`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { sum, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(sum(unsafeFromString(\"2\"), unsafeFromString(\"3\")), unsafeFromString(\"5\"))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const sum: {\n  (that: BigDecimal): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, that: BigDecimal): BigDecimal\n} = dual(2, (self: BigDecimal, that: BigDecimal): BigDecimal => {\n  if (that.value === bigint0) {\n    return self\n  }\n\n  if (self.value === bigint0) {\n    return that\n  }\n\n  if (self.scale > that.scale) {\n    return make(scale(that, self.scale).value + self.value, self.scale)\n  }\n\n  if (self.scale < that.scale) {\n    return make(scale(self, that.scale).value + that.value, that.scale)\n  }\n\n  return make(self.value + that.value, self.scale)\n})\n\n/**\n * Provides a multiplication operation on `BigDecimal`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { multiply, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(multiply(unsafeFromString(\"2\"), unsafeFromString(\"3\")), unsafeFromString(\"6\"))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const multiply: {\n  (that: BigDecimal): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, that: BigDecimal): BigDecimal\n} = dual(2, (self: BigDecimal, that: BigDecimal): BigDecimal => {\n  if (that.value === bigint0 || self.value === bigint0) {\n    return zero\n  }\n\n  return make(self.value * that.value, self.scale + that.scale)\n})\n\n/**\n * Provides a subtraction operation on `BigDecimal`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { subtract, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(subtract(unsafeFromString(\"2\"), unsafeFromString(\"3\")), unsafeFromString(\"-1\"))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const subtract: {\n  (that: BigDecimal): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, that: BigDecimal): BigDecimal\n} = dual(2, (self: BigDecimal, that: BigDecimal): BigDecimal => {\n  if (that.value === bigint0) {\n    return self\n  }\n\n  if (self.value === bigint0) {\n    return make(-that.value, that.scale)\n  }\n\n  if (self.scale > that.scale) {\n    return make(self.value - scale(that, self.scale).value, self.scale)\n  }\n\n  if (self.scale < that.scale) {\n    return make(scale(self, that.scale).value - that.value, that.scale)\n  }\n\n  return make(self.value - that.value, self.scale)\n})\n\n/**\n * Internal function used for arbitrary precision division.\n */\nconst divideWithPrecision = (\n  num: bigint,\n  den: bigint,\n  scale: number,\n  precision: number\n): BigDecimal => {\n  const numNegative = num < bigint0\n  const denNegative = den < bigint0\n  const negateResult = numNegative !== denNegative\n\n  num = numNegative ? -num : num\n  den = denNegative ? -den : den\n\n  // Shift digits until numerator is larger than denominator (set scale appropriately).\n  while (num < den) {\n    num *= bigint10\n    scale++\n  }\n\n  // First division.\n  let quotient = num / den\n  let remainder = num % den\n\n  if (remainder === bigint0) {\n    // No remainder, return immediately.\n    return make(negateResult ? -quotient : quotient, scale)\n  }\n\n  // The quotient is guaranteed to be non-negative at this point. No need to consider sign.\n  let count = `${quotient}`.length\n\n  // Shift the remainder by 1 decimal; The quotient will be 1 digit upon next division.\n  remainder *= bigint10\n  while (remainder !== bigint0 && count < precision) {\n    const q = remainder / den\n    const r = remainder % den\n    quotient = quotient * bigint10 + q\n    remainder = r * bigint10\n\n    count++\n    scale++\n  }\n\n  if (remainder !== bigint0) {\n    // Round final number with remainder.\n    quotient += roundTerminal(remainder / den)\n  }\n\n  return make(negateResult ? -quotient : quotient, scale)\n}\n\n/**\n * Internal function used for rounding.\n *\n * Returns 1 if the most significant digit is >= 5, otherwise 0.\n *\n * This is used after dividing a number by a power of ten and rounding the last digit.\n *\n * @internal\n */\nexport const roundTerminal = (n: bigint): bigint => {\n  const pos = n >= bigint0 ? 0 : 1\n  return Number(`${n}`[pos]) < 5 ? bigint0 : bigint1\n}\n\n/**\n * Provides a division operation on `BigDecimal`s.\n *\n * If the dividend is not a multiple of the divisor the result will be a `BigDecimal` value\n * which represents the integer division rounded down to the nearest integer.\n *\n * If the divisor is `0`, the result will be `None`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigDecimal, Option } from \"effect\"\n *\n * assert.deepStrictEqual(BigDecimal.divide(BigDecimal.unsafeFromString(\"6\"), BigDecimal.unsafeFromString(\"3\")), Option.some(BigDecimal.unsafeFromString(\"2\")))\n * assert.deepStrictEqual(BigDecimal.divide(BigDecimal.unsafeFromString(\"6\"), BigDecimal.unsafeFromString(\"4\")), Option.some(BigDecimal.unsafeFromString(\"1.5\")))\n * assert.deepStrictEqual(BigDecimal.divide(BigDecimal.unsafeFromString(\"6\"), BigDecimal.unsafeFromString(\"0\")), Option.none())\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const divide: {\n  (that: BigDecimal): (self: BigDecimal) => Option.Option<BigDecimal>\n  (self: BigDecimal, that: BigDecimal): Option.Option<BigDecimal>\n} = dual(2, (self: BigDecimal, that: BigDecimal): Option.Option<BigDecimal> => {\n  if (that.value === bigint0) {\n    return Option.none()\n  }\n\n  if (self.value === bigint0) {\n    return Option.some(zero)\n  }\n\n  const scale = self.scale - that.scale\n  if (self.value === that.value) {\n    return Option.some(make(bigint1, scale))\n  }\n\n  return Option.some(divideWithPrecision(self.value, that.value, scale, DEFAULT_PRECISION))\n})\n\n/**\n * Provides an unsafe division operation on `BigDecimal`s.\n *\n * If the dividend is not a multiple of the divisor the result will be a `BigDecimal` value\n * which represents the integer division rounded down to the nearest integer.\n *\n * Throws a `RangeError` if the divisor is `0`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { unsafeDivide, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(unsafeDivide(unsafeFromString(\"6\"), unsafeFromString(\"3\")), unsafeFromString(\"2\"))\n * assert.deepStrictEqual(unsafeDivide(unsafeFromString(\"6\"), unsafeFromString(\"4\")), unsafeFromString(\"1.5\"))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const unsafeDivide: {\n  (that: BigDecimal): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, that: BigDecimal): BigDecimal\n} = dual(2, (self: BigDecimal, that: BigDecimal): BigDecimal => {\n  if (that.value === bigint0) {\n    throw new RangeError(\"Division by zero\")\n  }\n\n  if (self.value === bigint0) {\n    return zero\n  }\n\n  const scale = self.scale - that.scale\n  if (self.value === that.value) {\n    return make(bigint1, scale)\n  }\n  return divideWithPrecision(self.value, that.value, scale, DEFAULT_PRECISION)\n})\n\n/**\n * @since 2.0.0\n * @category instances\n */\nexport const Order: order.Order<BigDecimal> = order.make((self, that) => {\n  const scmp = order.number(sign(self), sign(that))\n  if (scmp !== 0) {\n    return scmp\n  }\n\n  if (self.scale > that.scale) {\n    return order.bigint(self.value, scale(that, self.scale).value)\n  }\n\n  if (self.scale < that.scale) {\n    return order.bigint(scale(self, that.scale).value, that.value)\n  }\n\n  return order.bigint(self.value, that.value)\n})\n\n/**\n * Returns `true` if the first argument is less than the second, otherwise `false`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { lessThan, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(lessThan(unsafeFromString(\"2\"), unsafeFromString(\"3\")), true)\n * assert.deepStrictEqual(lessThan(unsafeFromString(\"3\"), unsafeFromString(\"3\")), false)\n * assert.deepStrictEqual(lessThan(unsafeFromString(\"4\"), unsafeFromString(\"3\")), false)\n * ```\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const lessThan: {\n  (that: BigDecimal): (self: BigDecimal) => boolean\n  (self: BigDecimal, that: BigDecimal): boolean\n} = order.lessThan(Order)\n\n/**\n * Checks if a given `BigDecimal` is less than or equal to the provided one.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { lessThanOrEqualTo, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(lessThanOrEqualTo(unsafeFromString(\"2\"), unsafeFromString(\"3\")), true)\n * assert.deepStrictEqual(lessThanOrEqualTo(unsafeFromString(\"3\"), unsafeFromString(\"3\")), true)\n * assert.deepStrictEqual(lessThanOrEqualTo(unsafeFromString(\"4\"), unsafeFromString(\"3\")), false)\n * ```\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const lessThanOrEqualTo: {\n  (that: BigDecimal): (self: BigDecimal) => boolean\n  (self: BigDecimal, that: BigDecimal): boolean\n} = order.lessThanOrEqualTo(Order)\n\n/**\n * Returns `true` if the first argument is greater than the second, otherwise `false`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { greaterThan, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(greaterThan(unsafeFromString(\"2\"), unsafeFromString(\"3\")), false)\n * assert.deepStrictEqual(greaterThan(unsafeFromString(\"3\"), unsafeFromString(\"3\")), false)\n * assert.deepStrictEqual(greaterThan(unsafeFromString(\"4\"), unsafeFromString(\"3\")), true)\n * ```\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const greaterThan: {\n  (that: BigDecimal): (self: BigDecimal) => boolean\n  (self: BigDecimal, that: BigDecimal): boolean\n} = order.greaterThan(Order)\n\n/**\n * Checks if a given `BigDecimal` is greater than or equal to the provided one.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { greaterThanOrEqualTo, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(greaterThanOrEqualTo(unsafeFromString(\"2\"), unsafeFromString(\"3\")), false)\n * assert.deepStrictEqual(greaterThanOrEqualTo(unsafeFromString(\"3\"), unsafeFromString(\"3\")), true)\n * assert.deepStrictEqual(greaterThanOrEqualTo(unsafeFromString(\"4\"), unsafeFromString(\"3\")), true)\n * ```\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const greaterThanOrEqualTo: {\n  (that: BigDecimal): (self: BigDecimal) => boolean\n  (self: BigDecimal, that: BigDecimal): boolean\n} = order.greaterThanOrEqualTo(Order)\n\n/**\n * Checks if a `BigDecimal` is between a `minimum` and `maximum` value (inclusive).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigDecimal } from \"effect\"\n *\n * const between = BigDecimal.between({\n *   minimum: BigDecimal.unsafeFromString(\"1\"),\n *   maximum: BigDecimal.unsafeFromString(\"5\") }\n * )\n *\n * assert.deepStrictEqual(between(BigDecimal.unsafeFromString(\"3\")), true)\n * assert.deepStrictEqual(between(BigDecimal.unsafeFromString(\"0\")), false)\n * assert.deepStrictEqual(between(BigDecimal.unsafeFromString(\"6\")), false)\n * ```\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const between: {\n  (options: {\n    minimum: BigDecimal\n    maximum: BigDecimal\n  }): (self: BigDecimal) => boolean\n  (self: BigDecimal, options: {\n    minimum: BigDecimal\n    maximum: BigDecimal\n  }): boolean\n} = order.between(Order)\n\n/**\n * Restricts the given `BigDecimal` to be within the range specified by the `minimum` and `maximum` values.\n *\n * - If the `BigDecimal` is less than the `minimum` value, the function returns the `minimum` value.\n * - If the `BigDecimal` is greater than the `maximum` value, the function returns the `maximum` value.\n * - Otherwise, it returns the original `BigDecimal`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigDecimal } from \"effect\"\n *\n * const clamp = BigDecimal.clamp({\n *   minimum: BigDecimal.unsafeFromString(\"1\"),\n *   maximum: BigDecimal.unsafeFromString(\"5\") }\n * )\n *\n * assert.deepStrictEqual(clamp(BigDecimal.unsafeFromString(\"3\")), BigDecimal.unsafeFromString(\"3\"))\n * assert.deepStrictEqual(clamp(BigDecimal.unsafeFromString(\"0\")), BigDecimal.unsafeFromString(\"1\"))\n * assert.deepStrictEqual(clamp(BigDecimal.unsafeFromString(\"6\")), BigDecimal.unsafeFromString(\"5\"))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const clamp: {\n  (options: {\n    minimum: BigDecimal\n    maximum: BigDecimal\n  }): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, options: {\n    minimum: BigDecimal\n    maximum: BigDecimal\n  }): BigDecimal\n} = order.clamp(Order)\n\n/**\n * Returns the minimum between two `BigDecimal`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { min, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(min(unsafeFromString(\"2\"), unsafeFromString(\"3\")), unsafeFromString(\"2\"))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const min: {\n  (that: BigDecimal): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, that: BigDecimal): BigDecimal\n} = order.min(Order)\n\n/**\n * Returns the maximum between two `BigDecimal`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { max, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(max(unsafeFromString(\"2\"), unsafeFromString(\"3\")), unsafeFromString(\"3\"))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const max: {\n  (that: BigDecimal): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, that: BigDecimal): BigDecimal\n} = order.max(Order)\n\n/**\n * Determines the sign of a given `BigDecimal`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { sign, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(sign(unsafeFromString(\"-5\")), -1)\n * assert.deepStrictEqual(sign(unsafeFromString(\"0\")), 0)\n * assert.deepStrictEqual(sign(unsafeFromString(\"5\")), 1)\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const sign = (n: BigDecimal): Ordering => n.value === bigint0 ? 0 : n.value < bigint0 ? -1 : 1\n\n/**\n * Determines the absolute value of a given `BigDecimal`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { abs, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(abs(unsafeFromString(\"-5\")), unsafeFromString(\"5\"))\n * assert.deepStrictEqual(abs(unsafeFromString(\"0\")), unsafeFromString(\"0\"))\n * assert.deepStrictEqual(abs(unsafeFromString(\"5\")), unsafeFromString(\"5\"))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const abs = (n: BigDecimal): BigDecimal => n.value < bigint0 ? make(-n.value, n.scale) : n\n\n/**\n * Provides a negate operation on `BigDecimal`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { negate, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(negate(unsafeFromString(\"3\")), unsafeFromString(\"-3\"))\n * assert.deepStrictEqual(negate(unsafeFromString(\"-6\")), unsafeFromString(\"6\"))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const negate = (n: BigDecimal): BigDecimal => make(-n.value, n.scale)\n\n/**\n * Returns the remainder left over when one operand is divided by a second operand.\n *\n * If the divisor is `0`, the result will be `None`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigDecimal, Option } from \"effect\"\n *\n * assert.deepStrictEqual(BigDecimal.remainder(BigDecimal.unsafeFromString(\"2\"), BigDecimal.unsafeFromString(\"2\")), Option.some(BigDecimal.unsafeFromString(\"0\")))\n * assert.deepStrictEqual(BigDecimal.remainder(BigDecimal.unsafeFromString(\"3\"), BigDecimal.unsafeFromString(\"2\")), Option.some(BigDecimal.unsafeFromString(\"1\")))\n * assert.deepStrictEqual(BigDecimal.remainder(BigDecimal.unsafeFromString(\"-4\"), BigDecimal.unsafeFromString(\"2\")), Option.some(BigDecimal.unsafeFromString(\"0\")))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const remainder: {\n  (divisor: BigDecimal): (self: BigDecimal) => Option.Option<BigDecimal>\n  (self: BigDecimal, divisor: BigDecimal): Option.Option<BigDecimal>\n} = dual(2, (self: BigDecimal, divisor: BigDecimal): Option.Option<BigDecimal> => {\n  if (divisor.value === bigint0) {\n    return Option.none()\n  }\n\n  const max = Math.max(self.scale, divisor.scale)\n  return Option.some(make(scale(self, max).value % scale(divisor, max).value, max))\n})\n\n/**\n * Returns the remainder left over when one operand is divided by a second operand.\n *\n * Throws a `RangeError` if the divisor is `0`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { unsafeRemainder, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(unsafeRemainder(unsafeFromString(\"2\"), unsafeFromString(\"2\")), unsafeFromString(\"0\"))\n * assert.deepStrictEqual(unsafeRemainder(unsafeFromString(\"3\"), unsafeFromString(\"2\")), unsafeFromString(\"1\"))\n * assert.deepStrictEqual(unsafeRemainder(unsafeFromString(\"-4\"), unsafeFromString(\"2\")), unsafeFromString(\"0\"))\n * ```\n *\n * @since 2.0.0\n * @category math\n */\nexport const unsafeRemainder: {\n  (divisor: BigDecimal): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, divisor: BigDecimal): BigDecimal\n} = dual(2, (self: BigDecimal, divisor: BigDecimal): BigDecimal => {\n  if (divisor.value === bigint0) {\n    throw new RangeError(\"Division by zero\")\n  }\n\n  const max = Math.max(self.scale, divisor.scale)\n  return make(scale(self, max).value % scale(divisor, max).value, max)\n})\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence: equivalence.Equivalence<BigDecimal> = equivalence.make((self, that) => {\n  if (self.scale > that.scale) {\n    return scale(that, self.scale).value === self.value\n  }\n\n  if (self.scale < that.scale) {\n    return scale(self, that.scale).value === that.value\n  }\n\n  return self.value === that.value\n})\n\n/**\n * Checks if two `BigDecimal`s are equal.\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const equals: {\n  (that: BigDecimal): (self: BigDecimal) => boolean\n  (self: BigDecimal, that: BigDecimal): boolean\n} = dual(2, (self: BigDecimal, that: BigDecimal): boolean => Equivalence(self, that))\n\n/**\n * Creates a `BigDecimal` from a `bigint` value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromBigInt = (n: bigint): BigDecimal => make(n, 0)\n\n/**\n * Creates a `BigDecimal` from a `number` value.\n *\n * It is not recommended to convert a floating point number to a decimal directly,\n * as the floating point representation may be unexpected.\n *\n * Throws a `RangeError` if the number is not finite (`NaN`, `+Infinity` or `-Infinity`).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { unsafeFromNumber, make } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(unsafeFromNumber(123), make(123n, 0))\n * assert.deepStrictEqual(unsafeFromNumber(123.456), make(123456n, 3))\n * ```\n *\n * @since 3.11.0\n * @category constructors\n */\nexport const unsafeFromNumber = (n: number): BigDecimal =>\n  Option.getOrThrowWith(safeFromNumber(n), () => new RangeError(`Number must be finite, got ${n}`))\n\n/**\n * Creates a `BigDecimal` from a `number` value.\n *\n * It is not recommended to convert a floating point number to a decimal directly,\n * as the floating point representation may be unexpected.\n *\n * Throws a `RangeError` if the number is not finite (`NaN`, `+Infinity` or `-Infinity`).\n *\n * @since 2.0.0\n * @category constructors\n * @deprecated Use {@link unsafeFromNumber} instead.\n */\nexport const fromNumber: (n: number) => BigDecimal = unsafeFromNumber\n\n// TODO(4.0): Rename this to `fromNumber` after removing the current, unsafe implementation of `fromNumber`.\n/**\n * Creates a `BigDecimal` from a `number` value.\n *\n * It is not recommended to convert a floating point number to a decimal directly,\n * as the floating point representation may be unexpected.\n *\n * Returns `None` if the number is not finite (`NaN`, `+Infinity` or `-Infinity`).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigDecimal, Option } from \"effect\"\n *\n * assert.deepStrictEqual(BigDecimal.safeFromNumber(123), Option.some(BigDecimal.make(123n, 0)))\n * assert.deepStrictEqual(BigDecimal.safeFromNumber(123.456), Option.some(BigDecimal.make(123456n, 3)))\n * assert.deepStrictEqual(BigDecimal.safeFromNumber(Infinity), Option.none())\n * ```\n *\n * @since 3.11.0\n * @category constructors\n */\nexport const safeFromNumber = (n: number): Option.Option<BigDecimal> => {\n  if (!Number.isFinite(n)) {\n    return Option.none()\n  }\n\n  const string = `${n}`\n  if (string.includes(\"e\")) {\n    return fromString(string)\n  }\n\n  const [lead, trail = \"\"] = string.split(\".\")\n  return Option.some(make(BigInt(`${lead}${trail}`), trail.length))\n}\n\n/**\n * Parses a numerical `string` into a `BigDecimal`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigDecimal, Option } from \"effect\"\n *\n * assert.deepStrictEqual(BigDecimal.fromString(\"123\"), Option.some(BigDecimal.make(123n, 0)))\n * assert.deepStrictEqual(BigDecimal.fromString(\"123.456\"), Option.some(BigDecimal.make(123456n, 3)))\n * assert.deepStrictEqual(BigDecimal.fromString(\"123.abc\"), Option.none())\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromString = (s: string): Option.Option<BigDecimal> => {\n  if (s === \"\") {\n    return Option.some(zero)\n  }\n\n  let base: string\n  let exp: number\n  const seperator = s.search(/[eE]/)\n  if (seperator !== -1) {\n    const trail = s.slice(seperator + 1)\n    base = s.slice(0, seperator)\n    exp = Number(trail)\n    if (base === \"\" || !Number.isSafeInteger(exp) || !FINITE_INT_REGEX.test(trail)) {\n      return Option.none()\n    }\n  } else {\n    base = s\n    exp = 0\n  }\n\n  let digits: string\n  let offset: number\n  const dot = base.search(/\\./)\n  if (dot !== -1) {\n    const lead = base.slice(0, dot)\n    const trail = base.slice(dot + 1)\n    digits = `${lead}${trail}`\n    offset = trail.length\n  } else {\n    digits = base\n    offset = 0\n  }\n\n  if (!FINITE_INT_REGEX.test(digits)) {\n    return Option.none()\n  }\n\n  const scale = offset - exp\n  if (!Number.isSafeInteger(scale)) {\n    return Option.none()\n  }\n\n  return Option.some(make(BigInt(digits), scale))\n}\n\n/**\n * Parses a numerical `string` into a `BigDecimal`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { unsafeFromString, make } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(unsafeFromString(\"123\"), make(123n, 0))\n * assert.deepStrictEqual(unsafeFromString(\"123.456\"), make(123456n, 3))\n * assert.throws(() => unsafeFromString(\"123.abc\"))\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unsafeFromString = (s: string): BigDecimal =>\n  Option.getOrThrowWith(fromString(s), () => new Error(\"Invalid numerical string\"))\n\n/**\n * Formats a given `BigDecimal` as a `string`.\n *\n * If the scale of the `BigDecimal` is greater than or equal to 16, the `BigDecimal` will\n * be formatted in scientific notation.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { format, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(format(unsafeFromString(\"-5\")), \"-5\")\n * assert.deepStrictEqual(format(unsafeFromString(\"123.456\")), \"123.456\")\n * assert.deepStrictEqual(format(unsafeFromString(\"-0.00000123\")), \"-0.00000123\")\n * ```\n *\n * @since 2.0.0\n * @category conversions\n */\nexport const format = (n: BigDecimal): string => {\n  const normalized = normalize(n)\n  if (Math.abs(normalized.scale) >= 16) {\n    return toExponential(normalized)\n  }\n\n  const negative = normalized.value < bigint0\n  const absolute = negative ? `${normalized.value}`.substring(1) : `${normalized.value}`\n\n  let before: string\n  let after: string\n\n  if (normalized.scale >= absolute.length) {\n    before = \"0\"\n    after = \"0\".repeat(normalized.scale - absolute.length) + absolute\n  } else {\n    const location = absolute.length - normalized.scale\n    if (location > absolute.length) {\n      const zeros = location - absolute.length\n      before = `${absolute}${\"0\".repeat(zeros)}`\n      after = \"\"\n    } else {\n      after = absolute.slice(location)\n      before = absolute.slice(0, location)\n    }\n  }\n\n  const complete = after === \"\" ? before : `${before}.${after}`\n  return negative ? `-${complete}` : complete\n}\n\n/**\n * Formats a given `BigDecimal` as a `string` in scientific notation.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { toExponential, make } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(toExponential(make(123456n, -5)), \"1.23456e+10\")\n * ```\n *\n * @since 3.11.0\n * @category conversions\n */\nexport const toExponential = (n: BigDecimal): string => {\n  if (isZero(n)) {\n    return \"0e+0\"\n  }\n\n  const normalized = normalize(n)\n  const digits = `${abs(normalized).value}`\n  const head = digits.slice(0, 1)\n  const tail = digits.slice(1)\n\n  let output = `${isNegative(normalized) ? \"-\" : \"\"}${head}`\n  if (tail !== \"\") {\n    output += `.${tail}`\n  }\n\n  const exp = tail.length - normalized.scale\n  return `${output}e${exp >= 0 ? \"+\" : \"\"}${exp}`\n}\n\n/**\n * Converts a `BigDecimal` to a `number`.\n *\n * This function will produce incorrect results if the `BigDecimal` exceeds the 64-bit range of a `number`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { unsafeToNumber, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(unsafeToNumber(unsafeFromString(\"123.456\")), 123.456)\n * ```\n *\n * @since 2.0.0\n * @category conversions\n */\nexport const unsafeToNumber = (n: BigDecimal): number => Number(format(n))\n\n/**\n * Checks if a given `BigDecimal` is an integer.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isInteger, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(isInteger(unsafeFromString(\"0\")), true)\n * assert.deepStrictEqual(isInteger(unsafeFromString(\"1\")), true)\n * assert.deepStrictEqual(isInteger(unsafeFromString(\"1.1\")), false)\n * ```\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const isInteger = (n: BigDecimal): boolean => normalize(n).scale <= 0\n\n/**\n * Checks if a given `BigDecimal` is `0`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isZero, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(isZero(unsafeFromString(\"0\")), true)\n * assert.deepStrictEqual(isZero(unsafeFromString(\"1\")), false)\n * ```\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const isZero = (n: BigDecimal): boolean => n.value === bigint0\n\n/**\n * Checks if a given `BigDecimal` is negative.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isNegative, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(isNegative(unsafeFromString(\"-1\")), true)\n * assert.deepStrictEqual(isNegative(unsafeFromString(\"0\")), false)\n * assert.deepStrictEqual(isNegative(unsafeFromString(\"1\")), false)\n * ```\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const isNegative = (n: BigDecimal): boolean => n.value < bigint0\n\n/**\n * Checks if a given `BigDecimal` is positive.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isPositive, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(isPositive(unsafeFromString(\"-1\")), false)\n * assert.deepStrictEqual(isPositive(unsafeFromString(\"0\")), false)\n * assert.deepStrictEqual(isPositive(unsafeFromString(\"1\")), true)\n * ```\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const isPositive = (n: BigDecimal): boolean => n.value > bigint0\n\nconst isBigDecimalArgs = (args: IArguments) => isBigDecimal(args[0])\n\n/**\n * Calculate the ceiling of a `BigDecimal` at the given scale.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { ceil, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(ceil(unsafeFromString(\"145\"), -1), unsafeFromString(\"150\"))\n * assert.deepStrictEqual(ceil(unsafeFromString(\"-14.5\")), unsafeFromString(\"-14\"))\n * ```\n *\n * @since 3.16.0\n * @category math\n */\nexport const ceil: {\n  (scale: number): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, scale?: number): BigDecimal\n} = dual(isBigDecimalArgs, (self: BigDecimal, scale: number = 0): BigDecimal => {\n  const truncated = truncate(self, scale)\n\n  if (isPositive(self) && lessThan(truncated, self)) {\n    return sum(truncated, make(1n, scale))\n  }\n\n  return truncated\n})\n\n/**\n * Calculate the floor of a `BigDecimal` at the given scale.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { floor, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(floor(unsafeFromString(\"145\"), -1), unsafeFromString(\"140\"))\n * assert.deepStrictEqual(floor(unsafeFromString(\"-14.5\")), unsafeFromString(\"-15\"))\n * ```\n *\n * @since 3.16.0\n * @category math\n */\nexport const floor: {\n  (scale: number): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, scale?: number): BigDecimal\n} = dual(isBigDecimalArgs, (self: BigDecimal, scale: number = 0): BigDecimal => {\n  const truncated = truncate(self, scale)\n\n  if (isNegative(self) && greaterThan(truncated, self)) {\n    return sum(truncated, make(-1n, scale))\n  }\n\n  return truncated\n})\n\n/**\n * Truncate a `BigDecimal` at the given scale. This is the same operation as rounding away from zero.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { truncate, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(truncate(unsafeFromString(\"145\"), -1), unsafeFromString(\"140\"))\n * assert.deepStrictEqual(truncate(unsafeFromString(\"-14.5\")), unsafeFromString(\"-14\"))\n * ```\n *\n * @since 3.16.0\n * @category math\n */\nexport const truncate: {\n  (scale: number): (self: BigDecimal) => BigDecimal\n  (self: BigDecimal, scale?: number): BigDecimal\n} = dual(isBigDecimalArgs, (self: BigDecimal, scale: number = 0): BigDecimal => {\n  if (self.scale <= scale) {\n    return self\n  }\n\n  // BigInt division truncates towards zero\n  return make(self.value / (10n ** BigInt(self.scale - scale)), scale)\n})\n\n/**\n * Internal function used by `round` for `half-even` and `half-odd` rounding modes.\n *\n * Returns the digit at the position of the given `scale` within the `BigDecimal`.\n *\n * @internal\n */\nexport const digitAt: {\n  (scale: number): (self: BigDecimal) => bigint\n  (self: BigDecimal, scale: number): bigint\n} = dual(2, (self: BigDecimal, scale: number): bigint => {\n  if (self.scale < scale) {\n    return 0n\n  }\n\n  const scaled = self.value / (10n ** BigInt(self.scale - scale))\n  return scaled % 10n\n})\n\n/**\n * Rounding modes for `BigDecimal`.\n *\n * `ceil`: round towards positive infinity\n * `floor`: round towards negative infinity\n * `to-zero`: round towards zero\n * `from-zero`: round away from zero\n * `half-ceil`: round to the nearest neighbor; if equidistant round towards positive infinity\n * `half-floor`: round to the nearest neighbor; if equidistant round towards negative infinity\n * `half-to-zero`: round to the nearest neighbor; if equidistant round towards zero\n * `half-from-zero`: round to the nearest neighbor; if equidistant round away from zero\n * `half-even`: round to the nearest neighbor; if equidistant round to the neighbor with an even digit\n * `half-odd`: round to the nearest neighbor; if equidistant round to the neighbor with an odd digit\n *\n * @since 3.16.0\n * @category math\n */\nexport type RoundingMode =\n  | \"ceil\"\n  | \"floor\"\n  | \"to-zero\"\n  | \"from-zero\"\n  | \"half-ceil\"\n  | \"half-floor\"\n  | \"half-to-zero\"\n  | \"half-from-zero\"\n  | \"half-even\"\n  | \"half-odd\"\n\n/**\n * Rounds a `BigDecimal` at the given scale with the specified rounding mode.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { round, unsafeFromString } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(round(unsafeFromString(\"145\"), { mode: \"from-zero\", scale: -1 }), unsafeFromString(\"150\"))\n * assert.deepStrictEqual(round(unsafeFromString(\"-14.5\")), unsafeFromString(\"-15\"))\n * ```\n *\n * @since 3.16.0\n * @category math\n */\nexport const round: {\n  (options: { scale?: number; mode?: RoundingMode }): (self: BigDecimal) => BigDecimal\n  (n: BigDecimal, options?: { scale?: number; mode?: RoundingMode }): BigDecimal\n} = dual(isBigDecimalArgs, (self: BigDecimal, options?: { scale?: number; mode?: RoundingMode }): BigDecimal => {\n  const mode = options?.mode ?? \"half-from-zero\"\n  const scale = options?.scale ?? 0\n\n  switch (mode) {\n    case \"ceil\":\n      return ceil(self, scale)\n\n    case \"floor\":\n      return floor(self, scale)\n\n    case \"to-zero\":\n      return truncate(self, scale)\n\n    case \"from-zero\":\n      return (isPositive(self) ? ceil(self, scale) : floor(self, scale))\n\n    case \"half-ceil\":\n      return floor(sum(self, make(5n, scale + 1)), scale)\n\n    case \"half-floor\":\n      return ceil(sum(self, make(-5n, scale + 1)), scale)\n\n    case \"half-to-zero\":\n      return isNegative(self)\n        ? floor(sum(self, make(5n, scale + 1)), scale)\n        : ceil(sum(self, make(-5n, scale + 1)), scale)\n\n    case \"half-from-zero\":\n      return isNegative(self)\n        ? ceil(sum(self, make(-5n, scale + 1)), scale)\n        : floor(sum(self, make(5n, scale + 1)), scale)\n  }\n\n  const halfCeil = floor(sum(self, make(5n, scale + 1)), scale)\n  const halfFloor = ceil(sum(self, make(-5n, scale + 1)), scale)\n  const digit = digitAt(halfCeil, scale)\n\n  switch (mode) {\n    case \"half-even\":\n      return equals(halfCeil, halfFloor) ? halfCeil : (digit % 2n === 0n) ? halfCeil : halfFloor\n\n    case \"half-odd\":\n      return equals(halfCeil, halfFloor) ? halfCeil : (digit % 2n === 0n) ? halfFloor : halfCeil\n  }\n})\n\n/**\n * Takes an `Iterable` of `BigDecimal`s and returns their sum as a single `BigDecimal`\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { unsafeFromString, sumAll } from \"effect/BigDecimal\"\n *\n * assert.deepStrictEqual(sumAll([unsafeFromString(\"2\"), unsafeFromString(\"3\"), unsafeFromString(\"4\")]), unsafeFromString(\"9\"))\n * ```\n *\n * @category math\n * @since 3.16.0\n */\nexport const sumAll = (collection: Iterable<BigDecimal>): BigDecimal => {\n  let out = zero\n  for (const n of collection) {\n    out = sum(out, n)\n  }\n\n  return out\n}\n"
  },
  {
    "path": "packages/effect/src/BigInt.ts",
    "content": "/**\n * This module provides utility functions and type class instances for working with the `bigint` type in TypeScript.\n * It includes functions for basic arithmetic operations, as well as type class instances for\n * `Equivalence` and `Order`.\n *\n * @module BigInt\n * @since 2.0.0\n * @see {@link module:BigDecimal} for more similar operations on `BigDecimal` types\n * @see {@link module:Number} for more similar operations on `number` types\n */\n\nimport * as equivalence from \"./Equivalence.js\"\nimport { dual } from \"./Function.js\"\nimport * as Option from \"./Option.js\"\nimport * as order from \"./Order.js\"\nimport type { Ordering } from \"./Ordering.js\"\nimport * as predicate from \"./Predicate.js\"\n\nconst bigint0 = BigInt(0)\nconst bigint1 = BigInt(1)\nconst bigint2 = BigInt(2)\n\n/**\n * Tests if a value is a `bigint`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isBigInt } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(isBigInt(1n), true)\n * assert.deepStrictEqual(isBigInt(1), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isBigInt: (u: unknown) => u is bigint = predicate.isBigInt\n\n/**\n * Provides an addition operation on `bigint`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { sum } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(sum(2n, 3n), 5n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const sum: {\n  (that: bigint): (self: bigint) => bigint\n  (self: bigint, that: bigint): bigint\n} = dual(2, (self: bigint, that: bigint): bigint => self + that)\n\n/**\n * Provides a multiplication operation on `bigint`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { multiply } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(multiply(2n, 3n), 6n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const multiply: {\n  (that: bigint): (self: bigint) => bigint\n  (self: bigint, that: bigint): bigint\n} = dual(2, (self: bigint, that: bigint): bigint => self * that)\n\n/**\n * Provides a subtraction operation on `bigint`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { subtract } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(subtract(2n, 3n), -1n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const subtract: {\n  (that: bigint): (self: bigint) => bigint\n  (self: bigint, that: bigint): bigint\n} = dual(2, (self: bigint, that: bigint): bigint => self - that)\n\n/**\n * Provides a division operation on `bigint`s.\n *\n * If the dividend is not a multiple of the divisor the result will be a `bigint` value\n * which represents the integer division rounded down to the nearest integer.\n *\n * Returns `None` if the divisor is `0n`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigInt, Option } from \"effect\"\n *\n * assert.deepStrictEqual(BigInt.divide(6n, 3n), Option.some(2n))\n * assert.deepStrictEqual(BigInt.divide(6n, 0n), Option.none())\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const divide: {\n  (that: bigint): (self: bigint) => Option.Option<bigint>\n  (self: bigint, that: bigint): Option.Option<bigint>\n} = dual(\n  2,\n  (self: bigint, that: bigint): Option.Option<bigint> => that === bigint0 ? Option.none() : Option.some(self / that)\n)\n\n/**\n * Provides a division operation on `bigint`s.\n *\n * If the dividend is not a multiple of the divisor the result will be a `bigint` value\n * which represents the integer division rounded down to the nearest integer.\n *\n * Throws a `RangeError` if the divisor is `0n`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { unsafeDivide } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(unsafeDivide(6n, 3n), 2n)\n * assert.deepStrictEqual(unsafeDivide(6n, 4n), 1n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const unsafeDivide: {\n  (that: bigint): (self: bigint) => bigint\n  (self: bigint, that: bigint): bigint\n} = dual(2, (self: bigint, that: bigint): bigint => self / that)\n\n/**\n * Returns the result of adding `1n` to a given number.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { increment } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(increment(2n), 3n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const increment = (n: bigint): bigint => n + bigint1\n\n/**\n * Decrements a number by `1n`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { decrement } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(decrement(3n), 2n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const decrement = (n: bigint): bigint => n - bigint1\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence: equivalence.Equivalence<bigint> = equivalence.bigint\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Order: order.Order<bigint> = order.bigint\n\n/**\n * Returns `true` if the first argument is less than the second, otherwise `false`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { lessThan } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(lessThan(2n, 3n), true)\n * assert.deepStrictEqual(lessThan(3n, 3n), false)\n * assert.deepStrictEqual(lessThan(4n, 3n), false)\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const lessThan: {\n  (that: bigint): (self: bigint) => boolean\n  (self: bigint, that: bigint): boolean\n} = order.lessThan(Order)\n\n/**\n * Returns a function that checks if a given `bigint` is less than or equal to the provided one.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { lessThanOrEqualTo } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(lessThanOrEqualTo(2n, 3n), true)\n * assert.deepStrictEqual(lessThanOrEqualTo(3n, 3n), true)\n * assert.deepStrictEqual(lessThanOrEqualTo(4n, 3n), false)\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const lessThanOrEqualTo: {\n  (that: bigint): (self: bigint) => boolean\n  (self: bigint, that: bigint): boolean\n} = order.lessThanOrEqualTo(Order)\n\n/**\n * Returns `true` if the first argument is greater than the second, otherwise `false`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { greaterThan } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(greaterThan(2n, 3n), false)\n * assert.deepStrictEqual(greaterThan(3n, 3n), false)\n * assert.deepStrictEqual(greaterThan(4n, 3n), true)\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const greaterThan: {\n  (that: bigint): (self: bigint) => boolean\n  (self: bigint, that: bigint): boolean\n} = order.greaterThan(Order)\n\n/**\n * Returns a function that checks if a given `bigint` is greater than or equal to the provided one.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { greaterThanOrEqualTo } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(greaterThanOrEqualTo(2n, 3n), false)\n * assert.deepStrictEqual(greaterThanOrEqualTo(3n, 3n), true)\n * assert.deepStrictEqual(greaterThanOrEqualTo(4n, 3n), true)\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const greaterThanOrEqualTo: {\n  (that: bigint): (self: bigint) => boolean\n  (self: bigint, that: bigint): boolean\n} = order.greaterThanOrEqualTo(Order)\n\n/**\n * Checks if a `bigint` is between a `minimum` and `maximum` value (inclusive).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigInt } from \"effect\"\n *\n * const between = BigInt.between({ minimum: 0n, maximum: 5n })\n *\n * assert.deepStrictEqual(between(3n), true)\n * assert.deepStrictEqual(between(-1n), false)\n * assert.deepStrictEqual(between(6n), false)\n * ```\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const between: {\n  (options: {\n    minimum: bigint\n    maximum: bigint\n  }): (self: bigint) => boolean\n  (self: bigint, options: {\n    minimum: bigint\n    maximum: bigint\n  }): boolean\n} = order.between(Order)\n\n/**\n * Restricts the given `bigint` to be within the range specified by the `minimum` and `maximum` values.\n *\n * - If the `bigint` is less than the `minimum` value, the function returns the `minimum` value.\n * - If the `bigint` is greater than the `maximum` value, the function returns the `maximum` value.\n * - Otherwise, it returns the original `bigint`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigInt } from \"effect\"\n *\n * const clamp = BigInt.clamp({ minimum: 1n, maximum: 5n })\n *\n * assert.equal(clamp(3n), 3n)\n * assert.equal(clamp(0n), 1n)\n * assert.equal(clamp(6n), 5n)\n * ```\n *\n * @since 2.0.0\n */\nexport const clamp: {\n  (options: {\n    minimum: bigint\n    maximum: bigint\n  }): (self: bigint) => bigint\n  (self: bigint, options: {\n    minimum: bigint\n    maximum: bigint\n  }): bigint\n} = order.clamp(Order)\n\n/**\n * Returns the minimum between two `bigint`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { min } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(min(2n, 3n), 2n)\n * ```\n *\n * @since 2.0.0\n */\nexport const min: {\n  (that: bigint): (self: bigint) => bigint\n  (self: bigint, that: bigint): bigint\n} = order.min(Order)\n\n/**\n * Returns the maximum between two `bigint`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { max } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(max(2n, 3n), 3n)\n * ```\n *\n * @since 2.0.0\n */\nexport const max: {\n  (that: bigint): (self: bigint) => bigint\n  (self: bigint, that: bigint): bigint\n} = order.max(Order)\n\n/**\n * Determines the sign of a given `bigint`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { sign } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(sign(-5n), -1)\n * assert.deepStrictEqual(sign(0n), 0)\n * assert.deepStrictEqual(sign(5n), 1)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const sign = (n: bigint): Ordering => Order(n, bigint0)\n\n/**\n * Determines the absolute value of a given `bigint`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { abs } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(abs(-5n), 5n)\n * assert.deepStrictEqual(abs(0n), 0n)\n * assert.deepStrictEqual(abs(5n), 5n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const abs = (n: bigint): bigint => (n < bigint0 ? -n : n)\n\n/**\n * Determines the greatest common divisor of two `bigint`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { gcd } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(gcd(2n, 3n), 1n)\n * assert.deepStrictEqual(gcd(2n, 4n), 2n)\n * assert.deepStrictEqual(gcd(16n, 24n), 8n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const gcd: {\n  (that: bigint): (self: bigint) => bigint\n  (self: bigint, that: bigint): bigint\n} = dual(2, (self: bigint, that: bigint): bigint => {\n  while (that !== bigint0) {\n    const t = that\n    that = self % that\n    self = t\n  }\n  return self\n})\n\n/**\n * Determines the least common multiple of two `bigint`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { lcm } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(lcm(2n, 3n), 6n)\n * assert.deepStrictEqual(lcm(2n, 4n), 4n)\n * assert.deepStrictEqual(lcm(16n, 24n), 48n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const lcm: {\n  (that: bigint): (self: bigint) => bigint\n  (self: bigint, that: bigint): bigint\n} = dual(2, (self: bigint, that: bigint): bigint => (self * that) / gcd(self, that))\n\n/**\n * Determines the square root of a given `bigint` unsafely. Throws if the given `bigint` is negative.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { unsafeSqrt } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(unsafeSqrt(4n), 2n)\n * assert.deepStrictEqual(unsafeSqrt(9n), 3n)\n * assert.deepStrictEqual(unsafeSqrt(16n), 4n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const unsafeSqrt = (n: bigint): bigint => {\n  if (n < bigint0) {\n    throw new RangeError(\"Cannot take the square root of a negative number\")\n  }\n  if (n < bigint2) {\n    return n\n  }\n  let x = n / bigint2\n  while (x * x > n) {\n    x = ((n / x) + x) / bigint2\n  }\n  return x\n}\n\n/**\n * Determines the square root of a given `bigint` safely. Returns `none` if the given `bigint` is negative.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigInt, Option } from \"effect\"\n *\n * assert.deepStrictEqual(BigInt.sqrt(4n), Option.some(2n))\n * assert.deepStrictEqual(BigInt.sqrt(9n), Option.some(3n))\n * assert.deepStrictEqual(BigInt.sqrt(16n), Option.some(4n))\n * assert.deepStrictEqual(BigInt.sqrt(-1n), Option.none())\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const sqrt = (n: bigint): Option.Option<bigint> =>\n  greaterThanOrEqualTo(n, bigint0) ? Option.some(unsafeSqrt(n)) : Option.none<bigint>()\n\n/**\n * Takes an `Iterable` of `bigint`s and returns their sum as a single `bigint\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { sumAll } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(sumAll([2n, 3n, 4n]), 9n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const sumAll = (collection: Iterable<bigint>): bigint => {\n  let out = bigint0\n  for (const n of collection) {\n    out += n\n  }\n  return out\n}\n\n/**\n * Takes an `Iterable` of `bigint`s and returns their multiplication as a single `number`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { multiplyAll } from \"effect/BigInt\"\n *\n * assert.deepStrictEqual(multiplyAll([2n, 3n, 4n]), 24n)\n * ```\n *\n * @category math\n * @since 2.0.0\n */\nexport const multiplyAll = (collection: Iterable<bigint>): bigint => {\n  let out = bigint1\n  for (const n of collection) {\n    if (n === bigint0) {\n      return bigint0\n    }\n    out *= n\n  }\n  return out\n}\n\n/**\n * Takes a `bigint` and returns an `Option` of `number`.\n *\n * If the `bigint` is outside the safe integer range for JavaScript (`Number.MAX_SAFE_INTEGER`\n * and `Number.MIN_SAFE_INTEGER`), it returns `Option.none()`. Otherwise, it converts the `bigint`\n * to a number and returns `Option.some(number)`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigInt as BI, Option } from \"effect\"\n *\n * assert.deepStrictEqual(BI.toNumber(BigInt(42)), Option.some(42))\n * assert.deepStrictEqual(BI.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)), Option.none())\n * assert.deepStrictEqual(BI.toNumber(BigInt(Number.MIN_SAFE_INTEGER) - BigInt(1)), Option.none())\n * ```\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const toNumber = (b: bigint): Option.Option<number> => {\n  if (b > BigInt(Number.MAX_SAFE_INTEGER) || b < BigInt(Number.MIN_SAFE_INTEGER)) {\n    return Option.none()\n  }\n  return Option.some(Number(b))\n}\n\n/**\n * Takes a string and returns an `Option` of `bigint`.\n *\n * If the string is empty or contains characters that cannot be converted into a `bigint`,\n * it returns `Option.none()`, otherwise, it returns `Option.some(bigint)`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigInt as BI, Option } from \"effect\"\n *\n * assert.deepStrictEqual(BI.fromString(\"42\"), Option.some(BigInt(42)))\n * assert.deepStrictEqual(BI.fromString(\" \"), Option.none())\n * assert.deepStrictEqual(BI.fromString(\"a\"), Option.none())\n * ```\n *\n * @category conversions\n * @since 2.4.12\n */\nexport const fromString = (s: string): Option.Option<bigint> => {\n  try {\n    return s.trim() === \"\"\n      ? Option.none()\n      : Option.some(BigInt(s))\n  } catch {\n    return Option.none()\n  }\n}\n\n/**\n * Takes a number and returns an `Option` of `bigint`.\n *\n * If the number is outside the safe integer range for JavaScript (`Number.MAX_SAFE_INTEGER`\n * and `Number.MIN_SAFE_INTEGER`), it returns `Option.none()`. Otherwise, it attempts to\n * convert the number to a `bigint` and returns `Option.some(bigint)`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { BigInt as BI, Option } from \"effect\"\n *\n * assert.deepStrictEqual(BI.fromNumber(42), Option.some(BigInt(42)))\n * assert.deepStrictEqual(BI.fromNumber(Number.MAX_SAFE_INTEGER + 1), Option.none())\n * assert.deepStrictEqual(BI.fromNumber(Number.MIN_SAFE_INTEGER - 1), Option.none())\n * ```\n *\n * @category conversions\n * @since 2.4.12\n */\nexport const fromNumber = (n: number): Option.Option<bigint> => {\n  if (n > Number.MAX_SAFE_INTEGER || n < Number.MIN_SAFE_INTEGER) {\n    return Option.none()\n  }\n\n  try {\n    return Option.some(BigInt(n))\n  } catch {\n    return Option.none()\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/Boolean.ts",
    "content": "/**\n * This module provides utility functions and type class instances for working with the `boolean` type in TypeScript.\n * It includes functions for basic boolean operations, as well as type class instances for\n * `Equivalence` and `Order`.\n *\n * @since 2.0.0\n */\nimport * as equivalence from \"./Equivalence.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport { dual } from \"./Function.js\"\nimport * as order from \"./Order.js\"\nimport * as predicate from \"./Predicate.js\"\n\n/**\n * Tests if a value is a `boolean`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isBoolean } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(isBoolean(true), true)\n * assert.deepStrictEqual(isBoolean(\"true\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isBoolean: (input: unknown) => input is boolean = predicate.isBoolean\n\n/**\n * This function returns the result of either of the given functions depending on the value of the boolean parameter.\n * It is useful when you have to run one of two functions depending on the boolean value.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Boolean } from \"effect\"\n *\n * assert.deepStrictEqual(Boolean.match(true, { onFalse: () => \"It's false!\", onTrue: () => \"It's true!\" }), \"It's true!\")\n * ```\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const match: {\n  <A, B = A>(options: {\n    readonly onFalse: LazyArg<A>\n    readonly onTrue: LazyArg<B>\n  }): (value: boolean) => A | B\n  <A, B>(value: boolean, options: {\n    readonly onFalse: LazyArg<A>\n    readonly onTrue: LazyArg<B>\n  }): A | B\n} = dual(2, <A, B>(value: boolean, options: {\n  readonly onFalse: LazyArg<A>\n  readonly onTrue: LazyArg<B>\n}): A | B => value ? options.onTrue() : options.onFalse())\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence: equivalence.Equivalence<boolean> = equivalence.boolean\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Order: order.Order<boolean> = order.boolean\n\n/**\n * Negates the given boolean: `!self`\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { not } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(not(true), false)\n * assert.deepStrictEqual(not(false), true)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const not = (self: boolean): boolean => !self\n\n/**\n * Combines two boolean using AND: `self && that`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { and } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(and(true, true), true)\n * assert.deepStrictEqual(and(true, false), false)\n * assert.deepStrictEqual(and(false, true), false)\n * assert.deepStrictEqual(and(false, false), false)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const and: {\n  (that: boolean): (self: boolean) => boolean\n  (self: boolean, that: boolean): boolean\n} = dual(2, (self: boolean, that: boolean): boolean => self && that)\n\n/**\n * Combines two boolean using NAND: `!(self && that)`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { nand } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(nand(true, true), false)\n * assert.deepStrictEqual(nand(true, false), true)\n * assert.deepStrictEqual(nand(false, true), true)\n * assert.deepStrictEqual(nand(false, false), true)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const nand: {\n  (that: boolean): (self: boolean) => boolean\n  (self: boolean, that: boolean): boolean\n} = dual(2, (self: boolean, that: boolean): boolean => !(self && that))\n\n/**\n * Combines two boolean using OR: `self || that`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { or } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(or(true, true), true)\n * assert.deepStrictEqual(or(true, false), true)\n * assert.deepStrictEqual(or(false, true), true)\n * assert.deepStrictEqual(or(false, false), false)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const or: {\n  (that: boolean): (self: boolean) => boolean\n  (self: boolean, that: boolean): boolean\n} = dual(2, (self: boolean, that: boolean): boolean => self || that)\n\n/**\n * Combines two booleans using NOR: `!(self || that)`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { nor } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(nor(true, true), false)\n * assert.deepStrictEqual(nor(true, false), false)\n * assert.deepStrictEqual(nor(false, true), false)\n * assert.deepStrictEqual(nor(false, false), true)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const nor: {\n  (that: boolean): (self: boolean) => boolean\n  (self: boolean, that: boolean): boolean\n} = dual(2, (self: boolean, that: boolean): boolean => !(self || that))\n\n/**\n * Combines two booleans using XOR: `(!self && that) || (self && !that)`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { xor } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(xor(true, true), false)\n * assert.deepStrictEqual(xor(true, false), true)\n * assert.deepStrictEqual(xor(false, true), true)\n * assert.deepStrictEqual(xor(false, false), false)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const xor: {\n  (that: boolean): (self: boolean) => boolean\n  (self: boolean, that: boolean): boolean\n} = dual(2, (self: boolean, that: boolean): boolean => (!self && that) || (self && !that))\n\n/**\n * Combines two booleans using EQV (aka XNOR): `!xor(self, that)`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { eqv } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(eqv(true, true), true)\n * assert.deepStrictEqual(eqv(true, false), false)\n * assert.deepStrictEqual(eqv(false, true), false)\n * assert.deepStrictEqual(eqv(false, false), true)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const eqv: {\n  (that: boolean): (self: boolean) => boolean\n  (self: boolean, that: boolean): boolean\n} = dual(2, (self: boolean, that: boolean): boolean => !xor(self, that))\n\n/**\n * Combines two booleans using an implication: `(!self || that)`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { implies } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(implies(true, true), true)\n * assert.deepStrictEqual(implies(true, false), false)\n * assert.deepStrictEqual(implies(false, true), true)\n * assert.deepStrictEqual(implies(false, false), true)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const implies: {\n  (that: boolean): (self: boolean) => boolean\n  (self: boolean, that: boolean): boolean\n} = dual(2, (self, that) => self ? that : true)\n\n/**\n * This utility function is used to check if all the elements in a collection of boolean values are `true`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { every } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(every([true, true, true]), true)\n * assert.deepStrictEqual(every([true, false, true]), false)\n * ```\n *\n * @since 2.0.0\n */\nexport const every = (collection: Iterable<boolean>): boolean => {\n  for (const b of collection) {\n    if (!b) {\n      return false\n    }\n  }\n  return true\n}\n\n/**\n * This utility function is used to check if at least one of the elements in a collection of boolean values is `true`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { some } from \"effect/Boolean\"\n *\n * assert.deepStrictEqual(some([true, false, true]), true)\n * assert.deepStrictEqual(some([false, false, false]), false)\n * ```\n *\n * @since 2.0.0\n */\nexport const some = (collection: Iterable<boolean>): boolean => {\n  for (const b of collection) {\n    if (b) {\n      return true\n    }\n  }\n  return false\n}\n"
  },
  {
    "path": "packages/effect/src/Brand.ts",
    "content": "/**\n * This module provides types and utility functions to create and work with branded types,\n * which are TypeScript types with an added type tag to prevent accidental usage of a value in the wrong context.\n *\n * The `refined` and `nominal` functions are both used to create branded types in TypeScript.\n * The main difference between them is that `refined` allows for validation of the data, while `nominal` does not.\n *\n * The `nominal` function is used to create a new branded type that has the same underlying type as the input, but with a different name.\n * This is useful when you want to distinguish between two values of the same type that have different meanings.\n * The `nominal` function does not perform any validation of the input data.\n *\n * On the other hand, the `refined` function is used to create a new branded type that has the same underlying type as the input,\n * but with a different name, and it also allows for validation of the input data.\n * The `refined` function takes a predicate that is used to validate the input data.\n * If the input data fails the validation, a `BrandErrors` is returned, which provides information about the specific validation failure.\n *\n * @since 2.0.0\n */\nimport * as Arr from \"./Array.js\"\nimport * as Either from \"./Either.js\"\nimport { identity, unsafeCoerce } from \"./Function.js\"\nimport * as Option from \"./Option.js\"\nimport type { Predicate } from \"./Predicate.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const BrandTypeId: unique symbol = Symbol.for(\"effect/Brand\")\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type BrandTypeId = typeof BrandTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const RefinedConstructorsTypeId: unique symbol = Symbol.for(\"effect/Brand/Refined\")\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type RefinedConstructorsTypeId = typeof RefinedConstructorsTypeId\n\n/**\n * A generic interface that defines a branded type.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Brand<in out K extends string | symbol> {\n  readonly [BrandTypeId]: {\n    readonly [k in K]: K\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Brand {\n  /**\n   * Represents a list of refinement errors.\n   *\n   * @since 2.0.0\n   * @category models\n   */\n  export interface BrandErrors extends Array<RefinementError> {}\n\n  /**\n   * Represents an error that occurs when the provided value of the branded type does not pass the refinement predicate.\n   *\n   * @since 2.0.0\n   * @category models\n   */\n  export interface RefinementError {\n    readonly meta: unknown\n    readonly message: string\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Constructor<in out A extends Brand<any>> {\n    readonly [RefinedConstructorsTypeId]: RefinedConstructorsTypeId\n    /**\n     * Constructs a branded type from a value of type `A`, throwing an error if\n     * the provided `A` is not valid.\n     */\n    (args: Brand.Unbranded<A>): A\n    /**\n     * Constructs a branded type from a value of type `A`, returning `Some<A>`\n     * if the provided `A` is valid, `None` otherwise.\n     */\n    option(args: Brand.Unbranded<A>): Option.Option<A>\n    /**\n     * Constructs a branded type from a value of type `A`, returning `Right<A>`\n     * if the provided `A` is valid, `Left<BrandError>` otherwise.\n     */\n    either(args: Brand.Unbranded<A>): Either.Either<A, Brand.BrandErrors>\n    /**\n     * Attempts to refine the provided value of type `A`, returning `true` if\n     * the provided `A` is valid, `false` otherwise.\n     */\n    is(a: Brand.Unbranded<A>): a is Brand.Unbranded<A> & A\n  }\n\n  /**\n   * A utility type to extract a branded type from a `Brand.Constructor`.\n   *\n   * @since 2.0.0\n   * @category models\n   */\n  export type FromConstructor<A> = A extends Brand.Constructor<infer B> ? B : never\n\n  /**\n   * A utility type to extract the value type from a brand.\n   *\n   * @since 2.0.0\n   * @category models\n   */\n  export type Unbranded<P> = P extends infer Q & Brands<P> ? Q : P\n\n  /**\n   * A utility type to extract the brands from a branded type.\n   *\n   * @since 2.0.0\n   * @category models\n   */\n  export type Brands<P> = P extends Brand<any> ? Types.UnionToIntersection<\n      {\n        [k in keyof P[BrandTypeId]]: k extends string | symbol ? Brand<k>\n          : never\n      }[keyof P[BrandTypeId]]\n    >\n    : never\n\n  /**\n   * A utility type that checks that all brands have the same base type.\n   *\n   * @since 2.0.0\n   * @category models\n   */\n  export type EnsureCommonBase<\n    Brands extends readonly [Brand.Constructor<any>, ...Array<Brand.Constructor<any>>]\n  > = {\n    [B in keyof Brands]: Brand.Unbranded<Brand.FromConstructor<Brands[0]>> extends\n      Brand.Unbranded<Brand.FromConstructor<Brands[B]>>\n      ? Brand.Unbranded<Brand.FromConstructor<Brands[B]>> extends Brand.Unbranded<Brand.FromConstructor<Brands[0]>>\n        ? Brands[B]\n      : Brands[B]\n      : \"ERROR: All brands should have the same base type\"\n  }\n}\n\n/**\n * @category alias\n * @since 2.0.0\n */\nexport type Branded<A, K extends string | symbol> = A & Brand<K>\n\n/**\n * Returns a `BrandErrors` that contains a single `RefinementError`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const error = (message: string, meta?: unknown): Brand.BrandErrors => [{\n  message,\n  meta\n}]\n\n/**\n * Takes a variable number of `BrandErrors` and returns a single `BrandErrors` that contains all refinement errors.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const errors: (...errors: Array<Brand.BrandErrors>) => Brand.BrandErrors = (\n  ...errors: Array<Brand.BrandErrors>\n): Brand.BrandErrors => Arr.flatten(errors)\n\n/**\n * Returns a `Brand.Constructor` that can construct a branded type from an unbranded value using the provided `refinement`\n * predicate as validation of the input data.\n *\n * If you don't want to perform any validation but only distinguish between two values of the same type but with different meanings,\n * see {@link nominal}.\n *\n * **Example**\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Brand } from \"effect\"\n *\n * type Int = number & Brand.Brand<\"Int\">\n *\n * const Int = Brand.refined<Int>(\n *   (n) => Number.isInteger(n),\n *   (n) => Brand.error(`Expected ${n} to be an integer`)\n * )\n *\n * console.log(Int(1))\n * // 1\n *\n * assert.throws(() => Int(1.1))\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport function refined<A extends Brand<any>>(\n  f: (unbranded: Brand.Unbranded<A>) => Option.Option<Brand.BrandErrors>\n): Brand.Constructor<A>\nexport function refined<A extends Brand<any>>(\n  refinement: Predicate<Brand.Unbranded<A>>,\n  onFailure: (unbranded: Brand.Unbranded<A>) => Brand.BrandErrors\n): Brand.Constructor<A>\nexport function refined<A extends Brand<any>>(\n  ...args: [(unbranded: Brand.Unbranded<A>) => Option.Option<Brand.BrandErrors>] | [\n    Predicate<Brand.Unbranded<A>>,\n    (unbranded: Brand.Unbranded<A>) => Brand.BrandErrors\n  ]\n): Brand.Constructor<A> {\n  const either: (unbranded: Brand.Unbranded<A>) => Either.Either<A, Brand.BrandErrors> = args.length === 2 ?\n    (unbranded) => args[0](unbranded) ? Either.right(unbranded as A) : Either.left(args[1](unbranded)) :\n    (unbranded) => {\n      return Option.match(args[0](unbranded), {\n        onNone: () => Either.right(unbranded as A),\n        onSome: Either.left\n      })\n    }\n  return Object.assign((unbranded: Brand.Unbranded<A>) => Either.getOrThrowWith(either(unbranded), identity), {\n    [RefinedConstructorsTypeId]: RefinedConstructorsTypeId,\n    option: (args: any) => Option.getRight(either(args)),\n    either,\n    is: (args: any): args is Brand.Unbranded<A> & A => Either.isRight(either(args))\n  }) as any\n}\n\n/**\n * This function returns a `Brand.Constructor` that **does not apply any runtime checks**, it just returns the provided value.\n * It can be used to create nominal types that allow distinguishing between two values of the same type but with different meanings.\n *\n * If you also want to perform some validation, see {@link refined}.\n *\n * **Example**\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Brand } from \"effect\"\n *\n * type UserId = number & Brand.Brand<\"UserId\">\n *\n * const UserId = Brand.nominal<UserId>()\n *\n * console.log(UserId(1))\n * // 1\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const nominal = <A extends Brand<any>>(): Brand.Constructor<\n  A\n> => {\n  // @ts-expect-error\n  return Object.assign((args) => args, {\n    [RefinedConstructorsTypeId]: RefinedConstructorsTypeId,\n    option: (args: any) => Option.some(args),\n    either: (args: any) => Either.right(args),\n    is: (_args: any): _args is Brand.Unbranded<A> & A => true\n  })\n}\n\n/**\n * Combines two or more brands together to form a single branded type.\n * This API is useful when you want to validate that the input data passes multiple brand validators.\n *\n * **Example**\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Brand } from \"effect\"\n *\n * type Int = number & Brand.Brand<\"Int\">\n * const Int = Brand.refined<Int>(\n *   (n) => Number.isInteger(n),\n *   (n) => Brand.error(`Expected ${n} to be an integer`)\n * )\n * type Positive = number & Brand.Brand<\"Positive\">\n * const Positive = Brand.refined<Positive>(\n *   (n) => n > 0,\n *   (n) => Brand.error(`Expected ${n} to be positive`)\n * )\n *\n * const PositiveInt = Brand.all(Int, Positive)\n *\n * console.log(PositiveInt(1))\n * // 1\n *\n * assert.throws(() => PositiveInt(1.1))\n * ```\n *\n * @since 2.0.0\n * @category combining\n */\nexport const all: <Brands extends readonly [Brand.Constructor<any>, ...Array<Brand.Constructor<any>>]>(\n  ...brands: Brand.EnsureCommonBase<Brands>\n) => Brand.Constructor<\n  Types.UnionToIntersection<{ [B in keyof Brands]: Brand.FromConstructor<Brands[B]> }[number]> extends\n    infer X extends Brand<any> ? X : Brand<any>\n> = <\n  Brands extends readonly [Brand.Constructor<any>, ...Array<Brand.Constructor<any>>]\n>(...brands: Brand.EnsureCommonBase<Brands>): Brand.Constructor<\n  Types.UnionToIntersection<\n    {\n      [B in keyof Brands]: Brand.FromConstructor<Brands[B]>\n    }[number]\n  > extends infer X extends Brand<any> ? X : Brand<any>\n> => {\n  const either = (args: any): Either.Either<any, Brand.BrandErrors> => {\n    let result: Either.Either<any, Brand.BrandErrors> = Either.right(args)\n    for (const brand of brands) {\n      const nextResult = brand.either(args)\n      if (Either.isLeft(result) && Either.isLeft(nextResult)) {\n        result = Either.left([...result.left, ...nextResult.left])\n      } else {\n        result = Either.isLeft(result) ? result : nextResult\n      }\n    }\n    return result\n  }\n  // @ts-expect-error\n  return Object.assign((args) =>\n    Either.match(either(args), {\n      onLeft: (e) => {\n        throw e\n      },\n      onRight: identity\n    }), {\n    [RefinedConstructorsTypeId]: RefinedConstructorsTypeId,\n    option: (args: any) => Option.getRight(either(args)),\n    either,\n    is: (args: any): args is any => Either.isRight(either(args))\n  })\n}\n\n/**\n * Retrieves the unbranded value from a `Brand` instance.\n *\n * @since 3.15.0\n * @category getters\n */\nexport const unbranded: <A extends Brand<any>>(branded: A) => Brand.Unbranded<A> = unsafeCoerce\n"
  },
  {
    "path": "packages/effect/src/Cache.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type { Either } from \"./Either.js\"\nimport type * as Exit from \"./Exit.js\"\nimport * as internal from \"./internal/cache.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Predicate from \"./Predicate.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const CacheTypeId: unique symbol = internal.CacheTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type CacheTypeId = typeof CacheTypeId\n\n/**\n * @since 3.6.4\n * @category symbols\n */\nexport const ConsumerCacheTypeId: unique symbol = internal.ConsumerCacheTypeId\n\n/**\n * @since 3.6.4\n * @category symbols\n */\nexport type ConsumerCacheTypeId = typeof ConsumerCacheTypeId\n\n/**\n * A `Cache` is defined in terms of a lookup function that, given a key of\n * type `Key`, can either fail with an error of type `Error` or succeed with a\n * value of type `Value`. Getting a value from the cache will either return\n * the previous result of the lookup function if it is available or else\n * compute a new result with the lookup function, put it in the cache, and\n * return it.\n *\n * A cache also has a specified capacity and time to live. When the cache is\n * at capacity the least recently accessed values in the cache will be\n * removed to make room for new values. Getting a value with a life older than\n * the specified time to live will result in a new value being computed with\n * the lookup function and returned when available.\n *\n * The cache is safe for concurrent access. If multiple fibers attempt to get\n * the same key the lookup function will only be computed once and the result\n * will be returned to all fibers.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Cache<in out Key, in out Value, out Error = never>\n  extends ConsumerCache<Key, Value, Error>, Cache.Variance<Key, Value, Error>\n{\n  /**\n   * Retrieves the value associated with the specified key if it exists.\n   * Otherwise computes the value with the lookup function, puts it in the\n   * cache, and returns it.\n   */\n  get(key: Key): Effect.Effect<Value, Error>\n\n  /**\n   * Retrieves the value associated with the specified key if it exists as a left.\n   * Otherwise computes the value with the lookup function, puts it in the\n   * cache, and returns it as a right.\n   */\n  getEither(key: Key): Effect.Effect<Either<Value, Value>, Error>\n\n  /**\n   * Computes the value associated with the specified key, with the lookup\n   * function, and puts it in the cache. The difference between this and\n   * `get` method is that `refresh` triggers (re)computation of the value\n   * without invalidating it in the cache, so any request to the associated\n   * key can still be served while the value is being re-computed/retrieved\n   * by the lookup function. Additionally, `refresh` always triggers the\n   * lookup function, disregarding the last `Error`.\n   */\n  refresh(key: Key): Effect.Effect<void, Error>\n\n  /**\n   * Associates the specified value with the specified key in the cache.\n   */\n  set(key: Key, value: Value): Effect.Effect<void>\n}\n\n/**\n * A ConsumerCache models a portion of a cache which is safe to share without allowing to create new values or access existing ones.\n *\n * It can be used safely to give over control for request management without leaking writer side details.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface ConsumerCache<in out Key, out Value, out Error = never>\n  extends Cache.ConsumerVariance<Key, Value, Error>\n{\n  /**\n   * Retrieves the value associated with the specified key if it exists.\n   * Otherwise returns `Option.none`.\n   */\n  getOption(key: Key): Effect.Effect<Option.Option<Value>, Error>\n\n  /**\n   * Retrieves the value associated with the specified key if it exists and the\n   * lookup function has completed. Otherwise returns `Option.none`.\n   */\n  getOptionComplete(key: Key): Effect.Effect<Option.Option<Value>>\n\n  /**\n   * Returns statistics for this cache.\n   */\n  readonly cacheStats: Effect.Effect<CacheStats>\n\n  /**\n   * Returns whether a value associated with the specified key exists in the\n   * cache.\n   */\n  contains(key: Key): Effect.Effect<boolean>\n\n  /**\n   * Returns statistics for the specified entry.\n   */\n  entryStats(key: Key): Effect.Effect<Option.Option<EntryStats>>\n\n  /**\n   * Invalidates the value associated with the specified key.\n   */\n  invalidate(key: Key): Effect.Effect<void>\n\n  /**\n   * Invalidates the value associated with the specified key if the predicate holds.\n   */\n  invalidateWhen(key: Key, predicate: Predicate.Predicate<Value>): Effect.Effect<void>\n\n  /**\n   * Invalidates all values in the cache.\n   */\n  readonly invalidateAll: Effect.Effect<void>\n\n  /**\n   * Returns the approximate number of values in the cache.\n   */\n  readonly size: Effect.Effect<number>\n\n  /**\n   * Returns an approximation of the values in the cache.\n   */\n  readonly keys: Effect.Effect<Array<Key>>\n\n  /**\n   * Returns an approximation of the values in the cache.\n   */\n  readonly values: Effect.Effect<Array<Value>>\n\n  /**\n   * Returns an approximation of the values in the cache.\n   */\n  readonly entries: Effect.Effect<Array<[Key, Value]>>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Cache {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out Key, in out Value, out Error> {\n    readonly [CacheTypeId]: {\n      readonly _Key: Types.Invariant<Key>\n      readonly _Error: Types.Covariant<Error>\n      readonly _Value: Types.Invariant<Value>\n    }\n  }\n  /**\n   * @since 3.6.4\n   * @category models\n   */\n  export interface ConsumerVariance<in out Key, out Value, out Error> {\n    readonly [ConsumerCacheTypeId]: {\n      readonly _Key: Types.Invariant<Key>\n      readonly _Error: Types.Covariant<Error>\n      readonly _Value: Types.Covariant<Value>\n    }\n  }\n}\n\n/**\n * Constructs a new cache with the specified capacity, time to live, and\n * lookup function.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Key, Value, Error = never, Environment = never>(\n  options: {\n    readonly capacity: number\n    readonly timeToLive: Duration.DurationInput\n    readonly lookup: Lookup<Key, Value, Error, Environment>\n  }\n) => Effect.Effect<Cache<Key, Value, Error>, never, Environment> = internal.make\n\n/**\n * Constructs a new cache with the specified capacity, time to live, and\n * lookup function, where the time to live can depend on the `Exit` value\n * returned by the lookup function.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeWith: <Key, Value, Error = never, Environment = never>(\n  options: {\n    readonly capacity: number\n    readonly lookup: Lookup<Key, Value, Error, Environment>\n    readonly timeToLive: (exit: Exit.Exit<Value, Error>) => Duration.DurationInput\n  }\n) => Effect.Effect<Cache<Key, Value, Error>, never, Environment> = internal.makeWith\n\n/**\n * `CacheStats` represents a snapshot of statistics for the cache as of a\n * point in time.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface CacheStats {\n  readonly hits: number\n  readonly misses: number\n  readonly size: number\n}\n\n/**\n * Constructs a new `CacheStats` from the specified values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeCacheStats: (\n  options: {\n    readonly hits: number\n    readonly misses: number\n    readonly size: number\n  }\n) => CacheStats = internal.makeCacheStats\n\n/**\n * Represents a snapshot of statistics for an entry in the cache.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface EntryStats {\n  readonly loadedMillis: number\n}\n\n/**\n * Constructs a new `EntryStats` from the specified values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeEntryStats: (loadedMillis: number) => EntryStats = internal.makeEntryStats\n\n/**\n * A `Lookup` represents a lookup function that, given a key of type `Key`, can\n * return an effect that will either produce a value of type `Value` or fail\n * with an error of type `Error` using an environment of type `Environment`.\n *\n * @since 2.0.0\n * @category models\n */\nexport type Lookup<Key, Value, Error = never, Environment = never> = (\n  key: Key\n) => Effect.Effect<Value, Error, Environment>\n"
  },
  {
    "path": "packages/effect/src/Cause.ts",
    "content": "/**\n * The `Effect<A, E, R>` type is polymorphic in values of type `E` and we can\n * work with any error type that we want. However, there is a lot of information\n * that is not inside an arbitrary `E` value. So as a result, an `Effect` needs\n * somewhere to store things like unexpected errors or defects, stack and\n * execution traces, causes of fiber interruptions, and so forth.\n *\n * Effect-TS is very strict about preserving the full information related to a\n * failure. It captures all type of errors into the `Cause` data type. `Effect`\n * uses the `Cause<E>` data type to store the full story of failure. So its\n * error model is lossless. It doesn't throw information related to the failure\n * result. So we can figure out exactly what happened during the operation of\n * our effects.\n *\n * It is important to note that `Cause` is an underlying data type representing\n * errors occuring within an `Effect` workflow. Thus, we don't usually deal with\n * `Cause`s directly. Even though it is not a data type that we deal with very\n * often, the `Cause` of a failing `Effect` workflow can be accessed at any\n * time, which gives us total access to all parallel and sequential errors in\n * occurring within our codebase.\n *\n * @since 2.0.0\n */\nimport type * as Channel from \"./Channel.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type * as Equal from \"./Equal.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as internal from \"./internal/cause.js\"\nimport * as core from \"./internal/core.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport type * as Sink from \"./Sink.js\"\nimport type * as Stream from \"./Stream.js\"\nimport type { Span } from \"./Tracer.js\"\nimport type { Covariant, NoInfer } from \"./Types.js\"\n\n/**\n * A unique symbol identifying the `Cause` type.\n *\n * **Details**\n *\n * This provides a symbol that helps identify instances of the `Cause` data\n * type. This can be used for advanced operations such as refining types or\n * building internal utilities that check whether an unknown value is a `Cause`.\n *\n * @see {@link isCause} Check if a value is a `Cause`\n *\n * @since 2.0.0\n * @category Symbols\n */\nexport const CauseTypeId: unique symbol = internal.CauseTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type CauseTypeId = typeof CauseTypeId\n\n/**\n * A unique symbol identifying the `RuntimeException` type.\n *\n * **Details**\n *\n * This provides a symbol that identifies a `RuntimeException`. This is\n * typically used internally by the library to recognize checked exceptions that\n * occur during runtime.\n *\n * @see {@link RuntimeException} Create or work with a `RuntimeException`\n *\n * @since 2.0.0\n * @category Symbols\n */\nexport const RuntimeExceptionTypeId: unique symbol = core.RuntimeExceptionTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type RuntimeExceptionTypeId = typeof RuntimeExceptionTypeId\n\n/**\n * A unique symbol identifying the `InterruptedException` type.\n *\n * **Details**\n *\n * This provides a symbol that identifies an `InterruptedException`. This is\n * typically used internally to recognize when a fiber has been interrupted,\n * helping the framework handle interruption logic correctly.\n *\n * @see {@link InterruptedException} Create or work with an `InterruptedException`\n *\n * @since 2.0.0\n * @category Symbols\n */\nexport const InterruptedExceptionTypeId: unique symbol = core.InterruptedExceptionTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type InterruptedExceptionTypeId = typeof InterruptedExceptionTypeId\n\n/**\n * A unique symbol identifying the `IllegalArgumentException` type.\n *\n * **Details**\n *\n * This provides a symbol that identifies an `IllegalArgumentException`. This is\n * often used in scenarios where invalid arguments are supplied to methods that\n * expect specific input.\n *\n * @see {@link IllegalArgumentException} Create or work with an `IllegalArgumentException`\n *\n * @since 2.0.0\n * @category Symbols\n */\nexport const IllegalArgumentExceptionTypeId: unique symbol = core.IllegalArgumentExceptionTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type IllegalArgumentExceptionTypeId = typeof IllegalArgumentExceptionTypeId\n\n/**\n * A unique symbol identifying the `NoSuchElementException` type.\n *\n * **Details**\n *\n * This provides a symbol that identifies a `NoSuchElementException`. It helps\n * differentiate cases where a required element is missing within a data\n * structure.\n *\n * @see {@link NoSuchElementException} Create or work with a `NoSuchElementException`\n *\n * @since 2.0.0\n * @category Symbols\n */\nexport const NoSuchElementExceptionTypeId: unique symbol = core.NoSuchElementExceptionTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type NoSuchElementExceptionTypeId = typeof NoSuchElementExceptionTypeId\n\n/**\n * A unique symbol identifying the `InvalidPubSubCapacityException` type.\n *\n * **Details**\n *\n * This provides a symbol that identifies an `InvalidPubSubCapacityException`.\n * It indicates an error related to an invalid capacity passed to a `PubSub`\n * structure.\n *\n * @see {@link InvalidPubSubCapacityException} Create or work with an `InvalidPubSubCapacityException`\n *\n * @since 2.0.0\n * @category Symbols\n */\nexport const InvalidPubSubCapacityExceptionTypeId: unique symbol = core.InvalidPubSubCapacityExceptionTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type InvalidPubSubCapacityExceptionTypeId = typeof InvalidPubSubCapacityExceptionTypeId\n\n/**\n * A unique symbol identifying the `ExceededCapacityException` type.\n *\n * **Details**\n *\n * This provides a symbol that identifies an `ExceededCapacityException`. It\n * denotes situations where a resource has exceeded its configured capacity\n * limit.\n *\n * @see {@link ExceededCapacityException} Create or work with an `ExceededCapacityException`\n *\n * @since 3.5.0\n * @category Symbols\n */\nexport const ExceededCapacityExceptionTypeId: unique symbol = core.ExceededCapacityExceptionTypeId\n\n/**\n * @since 3.5.0\n * @category Symbols\n */\nexport type ExceededCapacityExceptionTypeId = typeof ExceededCapacityExceptionTypeId\n\n/**\n * A unique symbol identifying the `TimeoutException` type.\n *\n * **Details**\n *\n * This provides a symbol that identifies a `TimeoutException`. It helps the\n * framework recognize errors related to operations that fail to complete within\n * a given timeframe.\n *\n * @see {@link TimeoutException} Create or work with a `TimeoutException`\n *\n * @since 2.0.0\n * @category Symbols\n */\nexport const TimeoutExceptionTypeId: unique symbol = core.TimeoutExceptionTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type TimeoutExceptionTypeId = typeof TimeoutExceptionTypeId\n\n/**\n * A unique symbol identifying the `UnknownException` type.\n *\n * **Details**\n *\n * This provides a symbol that identifies an `UnknownException`. It is typically\n * used for generic or unexpected errors that do not fit other specific\n * exception categories.\n *\n * @see {@link UnknownException} Create or work with an `UnknownException`\n *\n * @since 2.0.0\n * @category Symbols\n */\nexport const UnknownExceptionTypeId: unique symbol = core.UnknownExceptionTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type UnknownExceptionTypeId = typeof UnknownExceptionTypeId\n\n/**\n * Represents the full history of a failure within an `Effect`.\n *\n * **Details**\n *\n * This type is a data structure that captures all information about why and how\n * an effect has failed, including parallel errors, sequential errors, defects,\n * and interruptions. It enables a \"lossless\" error model: no error-related\n * information is discarded, which helps in debugging and understanding the root\n * cause of failures.\n *\n * @since 2.0.0\n * @category Models\n */\nexport type Cause<E> =\n  | Empty\n  | Fail<E>\n  | Die\n  | Interrupt\n  | Sequential<E>\n  | Parallel<E>\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Cause {\n  /**\n   * This interface is used internally to manage the type variance of `Cause`.\n   *\n   * @since 2.0.0\n   * @category Models\n   */\n  export interface Variance<out E> {\n    readonly [CauseTypeId]: {\n      readonly _E: Covariant<E>\n    }\n  }\n}\n\n/**\n * Describes methods for reducing a `Cause<E>` into a value of type `Z` with\n * access to contextual information.\n *\n * **Details**\n *\n * This interface is meant for advanced transformations of `Cause`. By\n * implementing each method, you can define how different parts of the `Cause`\n * structure (like `Fail`, `Die`, or `Interrupt`) should be transformed into a\n * final type `Z`. The `context` parameter carries additional data needed during\n * this reduction.\n *\n * @see {@link reduceWithContext} Apply a `CauseReducer` to transform a `Cause`\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface CauseReducer<in C, in E, in out Z> {\n  emptyCase(context: C): Z\n  failCase(context: C, error: E): Z\n  dieCase(context: C, defect: unknown): Z\n  interruptCase(context: C, fiberId: FiberId.FiberId): Z\n  sequentialCase(context: C, left: Z, right: Z): Z\n  parallelCase(context: C, left: Z, right: Z): Z\n}\n\n/**\n * Represents an error object that can be yielded in `Effect.gen`.\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface YieldableError extends Pipeable, Inspectable, Error {\n  readonly [Effect.EffectTypeId]: Effect.Effect.VarianceStruct<never, this, never>\n  readonly [Stream.StreamTypeId]: Stream.Stream.VarianceStruct<never, this, never>\n  readonly [Sink.SinkTypeId]: Sink.Sink.VarianceStruct<never, unknown, never, this, never>\n  readonly [Channel.ChannelTypeId]: Channel.Channel.VarianceStruct<never, unknown, this, unknown, never, unknown, never>\n  [Symbol.iterator](): Effect.EffectGenerator<Effect.Effect<never, this, never>>\n}\n\n/**\n * Creates an error that occurs at runtime, extendable for other exception\n * types.\n *\n * @since 2.0.0\n * @category Errors\n */\nexport const YieldableError: new(message?: string | undefined) => YieldableError = core.YieldableError\n\n/**\n * An error representing a runtime error.\n *\n * **Details**\n *\n * This interface is used for errors that occur at runtime but are still\n * considered recoverable or typed.\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface RuntimeException extends YieldableError {\n  readonly _tag: \"RuntimeException\"\n  readonly [RuntimeExceptionTypeId]: RuntimeExceptionTypeId\n}\n\n/**\n * An error representing fiber interruption.\n *\n * **Details**\n *\n * This interface represents errors that occur when a fiber is forcefully\n * interrupted. Interruption can happen for various reasons, including\n * cancellations or system directives to halt operations. Code that deals with\n * concurrency might need to catch or handle these to ensure proper cleanup.\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface InterruptedException extends YieldableError {\n  readonly _tag: \"InterruptedException\"\n  readonly [InterruptedExceptionTypeId]: InterruptedExceptionTypeId\n}\n\n/**\n * An error representing an invalid argument passed to a method.\n *\n * **Details**\n *\n * This interface is used for signaling that a function or method received an\n * argument that does not meet its preconditions.\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface IllegalArgumentException extends YieldableError {\n  readonly _tag: \"IllegalArgumentException\"\n  readonly [IllegalArgumentExceptionTypeId]: IllegalArgumentExceptionTypeId\n}\n\n/**\n * An error that occurs when an expected element is missing.\n *\n * **Details**\n *\n * This interface indicates scenarios like looking up an item in a collection\n * or searching for data that should be present but isn't. It helps your code\n * signal a more specific issue rather than a general error.\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface NoSuchElementException extends YieldableError {\n  readonly _tag: \"NoSuchElementException\"\n  readonly [NoSuchElementExceptionTypeId]: NoSuchElementExceptionTypeId\n}\n\n/**\n * An error indicating invalid capacity for a `PubSub`.\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface InvalidPubSubCapacityException extends YieldableError {\n  readonly _tag: \"InvalidPubSubCapacityException\"\n  readonly [InvalidPubSubCapacityExceptionTypeId]: InvalidPubSubCapacityExceptionTypeId\n}\n\n/**\n * An error that occurs when resource capacity is exceeded.\n *\n * @since 3.5.0\n * @category Models\n */\nexport interface ExceededCapacityException extends YieldableError {\n  readonly _tag: \"ExceededCapacityException\"\n  readonly [ExceededCapacityExceptionTypeId]: ExceededCapacityExceptionTypeId\n}\n\n/**\n * An error representing a computation that timed out.\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface TimeoutException extends YieldableError {\n  readonly _tag: \"TimeoutException\"\n  readonly [TimeoutExceptionTypeId]: TimeoutExceptionTypeId\n}\n\n/**\n * A checked exception for handling unknown or unexpected errors.\n *\n * **Details**\n *\n * This interface captures errors that don't fall under known categories. It is\n * especially helpful for wrapping low-level or third-party library errors that\n * might provide little or no context, such as from a rejected promise.\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface UnknownException extends YieldableError {\n  readonly _tag: \"UnknownException\"\n  readonly [UnknownExceptionTypeId]: UnknownExceptionTypeId\n  readonly error: unknown\n}\n\n/**\n * Represents a lack of errors within a `Cause`.\n *\n * @see {@link empty} Construct a new `Empty` cause\n * @see {@link isEmptyType} Check if a `Cause` is an `Empty` type\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface Empty extends Cause.Variance<never>, Equal.Equal, Pipeable, Inspectable {\n  readonly _tag: \"Empty\"\n}\n\n/**\n * Represents an expected error within a `Cause`.\n *\n * **Details**\n *\n * This interface models a `Cause` that carries an expected or known error of\n * type `E`. For example, if you validate user input and find it invalid, you\n * might store that error within a `Fail`.\n *\n * @see {@link fail} Construct a `Fail` cause\n * @see {@link isFailType} Check if a `Cause` is a `Fail`\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface Fail<out E> extends Cause.Variance<E>, Equal.Equal, Pipeable, Inspectable {\n  readonly _tag: \"Fail\"\n  readonly error: E\n}\n\n/**\n * Represents an unexpected defect within a `Cause`.\n *\n * **Details**\n *\n * This interface models a `Cause` for errors that are typically unrecoverable or\n * unanticipated—like runtime exceptions or bugs. When code \"dies,\" it indicates a\n * severe failure that wasn't accounted for.\n *\n * @see {@link die} Construct a `Die` cause\n * @see {@link isDieType} Check if a `Cause` is a `Die`\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface Die extends Cause.Variance<never>, Equal.Equal, Pipeable, Inspectable {\n  readonly _tag: \"Die\"\n  readonly defect: unknown\n}\n\n/**\n * Represents fiber interruption within a `Cause`.\n *\n * **Details**\n *\n * This interface models a scenario where an effect was halted by an external\n * signal, carrying a `FiberId` that identifies which fiber was interrupted.\n * Interruption is a normal part of concurrency, used for cancellation or\n * resource cleanup.\n *\n * @see {@link interrupt} Construct an `Interrupt` cause\n * @see {@link isInterruptType} Check if a `Cause` is an `Interrupt`\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface Interrupt extends Cause.Variance<never>, Equal.Equal, Pipeable, Inspectable {\n  readonly _tag: \"Interrupt\"\n  readonly fiberId: FiberId.FiberId\n}\n\n/**\n * Represents parallel composition of two `Cause`s.\n *\n * **Details**\n *\n * This interface captures failures that happen simultaneously. In scenarios\n * with concurrency, more than one operation can fail in parallel. Instead of\n * losing information, this structure stores both errors together.\n *\n * @see {@link parallel} Combine two `Cause`s in parallel\n * @see {@link isParallelType} Check if a `Cause` is a `Parallel`\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface Parallel<out E> extends Cause.Variance<E>, Equal.Equal, Pipeable, Inspectable {\n  readonly _tag: \"Parallel\"\n  readonly left: Cause<E>\n  readonly right: Cause<E>\n}\n\n/**\n * Represents sequential composition of two `Cause`s.\n *\n * **Details**\n *\n * This interface models the scenario where one error follows another in\n * sequence, such as when a main effect fails and then a finalizer also fails.\n * It ensures both errors are retained in the final `Cause`.\n *\n * @see {@link sequential} Combine two `Cause`s sequentially\n * @see {@link isSequentialType} Check if a `Cause` is a `Sequential`\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface Sequential<out E> extends Cause.Variance<E>, Equal.Equal, Pipeable, Inspectable {\n  readonly _tag: \"Sequential\"\n  readonly left: Cause<E>\n  readonly right: Cause<E>\n}\n\n/**\n * Creates an `Empty` cause.\n *\n * **Details**\n *\n * This function returns a cause that signifies \"no error.\" It's commonly used\n * to represent an absence of failure conditions.\n *\n * @see {@link isEmpty} Check if a `Cause` is empty\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const empty: Cause<never> = internal.empty\n\n/**\n * Creates a `Fail` cause from an expected error.\n *\n * **Details**\n *\n * This function constructs a `Cause` carrying an error of type `E`. It's used\n * when you want to represent a known or anticipated failure in your effectful\n * computations.\n *\n * @see {@link isFailure} Check if a `Cause` contains a failure\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const fail: <E>(error: E) => Cause<E> = internal.fail\n\n/**\n * Creates a `Die` cause from an unexpected error.\n *\n * **Details**\n *\n * This function wraps an unhandled or unknown defect (like a runtime crash)\n * into a `Cause`. It's useful for capturing unforeseen issues in a structured\n * way.\n *\n * @see {@link isDie} Check if a `Cause` contains a defect\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const die: (defect: unknown) => Cause<never> = internal.die\n\n/**\n * Creates an `Interrupt` cause from a `FiberId`.\n *\n * **Details**\n *\n * This function represents a fiber that has been interrupted. It stores the\n * identifier of the interrupted fiber, enabling precise tracking of concurrent\n * cancellations.\n *\n * @see {@link isInterrupted} Check if a `Cause` contains an interruption\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const interrupt: (fiberId: FiberId.FiberId) => Cause<never> = internal.interrupt\n\n/**\n * Combines two `Cause`s in parallel.\n *\n * **Details**\n *\n * This function merges two errors that occurred simultaneously. Instead of\n * discarding one error, both are retained, allowing for richer error reporting\n * and debugging.\n *\n * @see {@link isParallelType} Check if a `Cause` is a `Parallel`\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const parallel: <E, E2>(left: Cause<E>, right: Cause<E2>) => Cause<E | E2> = internal.parallel\n\n/**\n * Combines two `Cause`s sequentially.\n *\n * **Details**\n *\n * This function merges two errors that occurred in sequence, such as a main\n * error followed by a finalization error. It preserves both errors for complete\n * failure information.\n *\n * @see {@link isSequentialType} Check if a `Cause` is a `Sequential`\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const sequential: <E, E2>(left: Cause<E>, right: Cause<E2>) => Cause<E | E2> = internal.sequential\n\n/**\n * Checks if a value is a `Cause`.\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isCause: (u: unknown) => u is Cause<unknown> = internal.isCause\n\n/**\n * Checks if a `Cause` is an `Empty` type.\n *\n * @see {@link empty} Create a new `Empty` cause\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isEmptyType: <E>(self: Cause<E>) => self is Empty = internal.isEmptyType\n\n/**\n * Checks if a `Cause` is a `Fail` type.\n *\n * @see {@link fail} Create a new `Fail` cause\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isFailType: <E>(self: Cause<E>) => self is Fail<E> = internal.isFailType\n\n/**\n * Checks if a `Cause` is a `Die` type.\n *\n * @see {@link die} Create a new `Die` cause\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isDieType: <E>(self: Cause<E>) => self is Die = internal.isDieType\n\n/**\n * Checks if a `Cause` is an `Interrupt` type.\n *\n * @see {@link interrupt} Create an `Interrupt` cause\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isInterruptType: <E>(self: Cause<E>) => self is Interrupt = internal.isInterruptType\n\n/**\n * Checks if a `Cause` is a `Sequential` type.\n *\n * @see {@link sequential} Combine two `Cause`s sequentially\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isSequentialType: <E>(self: Cause<E>) => self is Sequential<E> = internal.isSequentialType\n\n/**\n * Checks if a `Cause` is a `Parallel` type.\n *\n * @see {@link parallel} Combine two `Cause`s in parallel\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isParallelType: <E>(self: Cause<E>) => self is Parallel<E> = internal.isParallelType\n\n/**\n * Calculates the size of a `Cause`.\n *\n * **Details**\n *\n * This function returns the total number of `Cause` nodes in the semiring\n * structure, reflecting how many individual error elements are recorded.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const size: <E>(self: Cause<E>) => number = internal.size\n\n/**\n * Checks if a `Cause` is entirely empty.\n *\n * **Details**\n *\n * This function returns `true` if the `Cause` contains no errors, defects, or\n * interruptions. It's helpful for verifying if a computation truly had no\n * failures.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const isEmpty: <E>(self: Cause<E>) => boolean = internal.isEmpty\n\n/**\n * Checks if a `Cause` contains a failure.\n *\n * **Details**\n *\n * This function returns `true` if the `Cause` includes any `Fail` error. It's\n * commonly used to confirm whether a workflow encountered an anticipated error\n * versus just defects or interruptions.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const isFailure: <E>(self: Cause<E>) => boolean = internal.isFailure\n\n/**\n * Checks if a `Cause` contains a defect.\n *\n * **Details**\n *\n * This function returns `true` if the `Cause` includes any unexpected or\n * unhandled errors (`Die`). It's useful for differentiating known failures from\n * unexpected ones.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const isDie: <E>(self: Cause<E>) => boolean = internal.isDie\n\n/**\n * Checks if a `Cause` contains an interruption.\n *\n * **Details**\n *\n * This function returns `true` if the `Cause` includes any fiber interruptions.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const isInterrupted: <E>(self: Cause<E>) => boolean = internal.isInterrupted\n\n/**\n * Checks if a `Cause` contains only interruptions.\n *\n * **Details**\n *\n * This function returns `true` if the `Cause` has been interrupted but does not\n * contain any other failures, such as `Fail` or `Die`. It's helpful for\n * verifying purely \"cancellation\" scenarios.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const isInterruptedOnly: <E>(self: Cause<E>) => boolean = internal.isInterruptedOnly\n\n/**\n * Extracts all recoverable errors of type `E` from a `Cause`.\n *\n * **Details**\n *\n * This function returns a chunk of errors, providing a list of all `Fail`\n * values found in the cause. It's useful for collecting all known failures for\n * logging or combined error handling.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const failures: <E>(self: Cause<E>) => Chunk.Chunk<E> = internal.failures\n\n/**\n * Extracts all unrecoverable defects from a `Cause`.\n *\n * **Details**\n *\n * This function returns a chunk of values representing unexpected errors\n * (`Die`). It's handy for capturing or logging unanticipated failures that\n * might need special handling, such as bug reports.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const defects: <E>(self: Cause<E>) => Chunk.Chunk<unknown> = internal.defects\n\n/**\n * Collects all `FiberId`s responsible for interrupting a fiber.\n *\n * **Details**\n *\n * This function returns a set of IDs indicating which fibers caused\n * interruptions within this `Cause`. It's useful for debugging concurrency\n * issues or tracing cancellations.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const interruptors: <E>(self: Cause<E>) => HashSet.HashSet<FiberId.FiberId> = internal.interruptors\n\n/**\n * Retrieves the first `Fail` error in a `Cause`, if present.\n *\n * **Details**\n *\n * This function returns an `Option` containing the first recoverable error\n * (`E`) from the cause. It's often used to quickly check if there's a primary\n * error to handle or display.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const failureOption: <E>(self: Cause<E>) => Option.Option<E> = internal.failureOption\n\n/**\n * Splits a `Cause` into either its first `Fail` error or the rest of the cause\n * (which might only contain `Die` or `Interrupt`).\n *\n * **Details**\n *\n * This function either returns the checked error (`E`) or the remaining\n * `Cause<never>` with defects/interruptions. It helps you decide if there's a\n * recoverable path or if only unhandled issues remain.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const failureOrCause: <E>(self: Cause<E>) => Either.Either<Cause<never>, E> = internal.failureOrCause\n\n/**\n * Strips out failures with an error of `None` from a `Cause<Option<E>>`.\n *\n * **Details**\n *\n * This function turns a `Cause<Option<E>>` into an `Option<Cause<E>>`. If the\n * cause only contains failures of `None`, it becomes `None`; otherwise, it\n * returns a `Cause` of the remaining errors. It's helpful when working with\n * optional errors and filtering out certain error paths.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const flipCauseOption: <E>(self: Cause<Option.Option<E>>) => Option.Option<Cause<E>> = internal.flipCauseOption\n\n/**\n * Retrieves the first `Die` defect in a `Cause`, if present.\n *\n * **Details**\n *\n * This function returns an `Option` containing the first unexpected failure\n * (`Die`) discovered. It's helpful for diagnosing the primary defect in a chain\n * of errors.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const dieOption: <E>(self: Cause<E>) => Option.Option<unknown> = internal.dieOption\n\n/**\n * Retrieves the first `Interrupt` in a `Cause`, if present.\n *\n * **Details**\n *\n * This function returns an `Option` with the first fiber interruption\n * discovered. This is particularly useful for concurrency analysis or debugging\n * cancellations.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const interruptOption: <E>(self: Cause<E>) => Option.Option<FiberId.FiberId> = internal.interruptOption\n\n/**\n * Removes all `Fail` and `Interrupt` nodes, keeping only defects (`Die`) in a\n * `Cause`.\n *\n * **Details**\n *\n * This function strips a cause of recoverable errors and interruptions, leaving\n * only unexpected failures. If no defects remain, it returns `None`. It's\n * valuable for focusing only on unanticipated problems when both known errors\n * and defects could occur.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const keepDefects: <E>(self: Cause<E>) => Option.Option<Cause<never>> = internal.keepDefects\n\n// TODO(4.0): remove? what's the point of this API?\n/**\n * Linearizes a `Cause` into a set of parallel causes, each containing a\n * sequential chain of failures.\n *\n * **Details**\n *\n * This function reorganizes the cause structure so that you can analyze each\n * parallel branch separately, even if they have multiple sequential errors.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const linearize: <E>(self: Cause<E>) => HashSet.HashSet<Cause<E>> = internal.linearize\n\n/**\n * Removes `Fail` and `Interrupt` nodes from a `Cause`, keeping only defects\n * (`Die`).\n *\n * **Details**\n *\n * This function is similar to `keepDefects` but returns a `Cause<never>`\n * directly, which can still store `Die` or finalizer-related defects. It's\n * helpful for analyzing only the irrecoverable portion of the error.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const stripFailures: <E>(self: Cause<E>) => Cause<never> = internal.stripFailures\n\n/**\n * Removes matching defects from a `Cause` using a partial function, returning\n * the remainder.\n *\n * **Details**\n *\n * This function applies a user-defined extraction function to each defect\n * (`Die`). If the function matches the defect, that defect is removed. If all\n * defects match, the result is `None`. Otherwise, you get a `Cause` with the\n * unmatched defects.\n *\n * @since 2.0.0\n * @category Getters\n */\nexport const stripSomeDefects: {\n  (pf: (defect: unknown) => Option.Option<unknown>): <E>(self: Cause<E>) => Option.Option<Cause<E>>\n  <E>(self: Cause<E>, pf: (defect: unknown) => Option.Option<unknown>): Option.Option<Cause<E>>\n} = internal.stripSomeDefects\n\n/**\n * Replaces any errors in a `Cause` with a provided constant error.\n *\n * **Details**\n *\n * This function transforms all `Fail` errors into the specified error value,\n * preserving the structure of the `Cause`. It's useful when you no longer need\n * the original error details but still want to keep the cause shape.\n *\n * @see {@link map} Apply a custom transformation to `Fail` errors\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const as: {\n  <E2>(error: E2): <E>(self: Cause<E>) => Cause<E2>\n  <E, E2>(self: Cause<E>, error: E2): Cause<E2>\n} = internal.as\n\n/**\n * Transforms the errors in a `Cause` using a user-provided function.\n *\n * **Details**\n *\n * This function applies `f` to each `Fail` error while leaving defects (`Die`)\n * and interruptions untouched. It's useful for changing or simplifying error\n * types in your effectful workflows.\n *\n * @see {@link as} Replace errors with a single constant\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const map: {\n  <E, E2>(f: (e: E) => E2): (self: Cause<E>) => Cause<E2>\n  <E, E2>(self: Cause<E>, f: (e: E) => E2): Cause<E2>\n} = internal.map\n\n/**\n * Transforms errors in a `Cause` into new causes.\n *\n * **Details**\n *\n * This function applies a function `f` to each `Fail` error, converting it into\n * a new `Cause`. This is especially powerful for merging or restructuring error\n * types while preserving or combining cause information.\n *\n * @see {@link map} Apply a simpler transformation to errors\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const flatMap: {\n  <E, E2>(f: (e: E) => Cause<E2>): (self: Cause<E>) => Cause<E2>\n  <E, E2>(self: Cause<E>, f: (e: E) => Cause<E2>): Cause<E2>\n} = internal.flatMap\n\n/**\n * Sequences two `Cause`s. The second `Cause` can be dependent on the result of\n * the first `Cause`.\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const andThen: {\n  <E, E2>(f: (e: E) => Cause<E2>): (self: Cause<E>) => Cause<E2>\n  <E2>(f: Cause<E2>): <E>(self: Cause<E>) => Cause<E2>\n  <E, E2>(self: Cause<E>, f: (e: E) => Cause<E2>): Cause<E2>\n  <E, E2>(self: Cause<E>, f: Cause<E2>): Cause<E2>\n} = internal.andThen\n\n/**\n * Flattens a nested `Cause` structure.\n *\n * **Details**\n *\n * This function takes a `Cause<Cause<E>>` and merges the layers into a single\n * `Cause<E>`. It's useful for eliminating additional nesting created by\n * repeated transformations or compositions.\n *\n * @see {@link flatMap} Compose nested causes\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const flatten: <E>(self: Cause<Cause<E>>) => Cause<E> = internal.flatten\n\n/**\n * Checks if the current `Cause` contains or is equal to another `Cause`.\n *\n * **Details**\n *\n * This function returns `true` if `that` cause is part of or the same as\n * the current `Cause`. It's useful when you need to check for specific\n * error patterns or deduplicate repeated failures.\n *\n * @since 2.0.0\n * @category Elements\n */\nexport const contains: {\n  <E2>(that: Cause<E2>): <E>(self: Cause<E>) => boolean\n  <E, E2>(self: Cause<E>, that: Cause<E2>): boolean\n} = internal.contains\n\n/**\n * Extracts the most \"important\" defect from a `Cause`.\n *\n * **Details**\n *\n * This function reduces a `Cause` to a single, prioritized defect. It evaluates\n * the `Cause` in the following order of priority:\n *\n * 1. If the `Cause` contains a failure (e.g., from `Effect.fail`), it returns\n *    the raw error value.\n * 2. If there is no failure, it looks for the first defect (e.g., from\n *    `Effect.die`).\n * 3. If neither of the above is present, and the `Cause` stems from an\n *    interruption, it creates and returns an `InterruptedException`.\n *\n * This function ensures you can always extract a meaningful representation of\n * the primary issue from a potentially complex `Cause` structure.\n *\n * **When to Use**\n *\n * Use this function when you need to extract the most relevant error or defect\n * from a `Cause`, especially in scenarios where multiple errors or defects may\n * be present. It's particularly useful for simplifying error reporting or\n * logging.\n *\n * @see {@link squashWith} Allows transforming failures into defects when squashing.\n *\n * @since 2.0.0\n * @category Destructors\n */\nexport const squash: <E>(self: Cause<E>) => unknown = core.causeSquash\n\n/**\n * Extracts the most \"important\" defect from a `Cause`, transforming failures\n * into defects using a provided function.\n *\n * **Details**\n *\n * This function reduces a `Cause` to a single, prioritized defect, while\n * allowing you to transform recoverable failures into defects through a custom\n * function. It processes the `Cause` in the following order:\n *\n * 1. If the `Cause` contains a failure (e.g., from `Effect.fail`), it applies\n *    the provided function `f` to the error to transform it into a defect.\n * 2. If there is no failure, it looks for the first defect (e.g., from\n *    `Effect.die`) and returns it.\n * 3. If neither is present and the `Cause` stems from an interruption, it\n *    returns an `InterruptedException`.\n *\n * This function is particularly useful when you need custom handling or\n * transformation of errors while processing a `Cause`.\n *\n * @see {@link squash} Extracts the most \"important\" defect without transforming failures.\n *\n * @since 2.0.0\n * @category Destructors\n */\nexport const squashWith: {\n  <E>(f: (error: E) => unknown): (self: Cause<E>) => unknown\n  <E>(self: Cause<E>, f: (error: E) => unknown): unknown\n} = core.causeSquashWith\n\n/**\n * Searches a `Cause` using a partial function to extract information.\n *\n * **Details**\n *\n * This function allows you to search through a `Cause` using a custom partial\n * function. The partial function is applied to the `Cause`, and if it matches,\n * the result is returned wrapped in a `Some`. If no match is found, the result\n * is `None`.\n *\n * This is particularly useful when you are only interested in specific types of\n * errors, defects, or interruption causes within a potentially complex `Cause`\n * structure. By leveraging a partial function, you can focus on extracting only\n * the relevant information you care about.\n *\n * The partial function should return an `Option` indicating whether it matched\n * and the value it extracted.\n *\n * @since 2.0.0\n * @category Elements\n */\nexport const find: {\n  <E, Z>(pf: (cause: Cause<E>) => Option.Option<Z>): (self: Cause<E>) => Option.Option<Z>\n  <E, Z>(self: Cause<E>, pf: (cause: Cause<E>) => Option.Option<Z>): Option.Option<Z>\n} = internal.find\n\n/**\n * Preserves parts of a `Cause` that match a given predicate.\n *\n * **Details**\n *\n * This function allows you to retain only the parts of a `Cause` structure that\n * match a specified predicate or refinement. Any parts of the `Cause` that do\n * not match the provided condition are excluded from the result.\n *\n * You can use this function in two ways:\n * - With a `Predicate`: A function that evaluates whether a `Cause` should be\n *   retained based on its value.\n * - With a `Refinement`: A more specific predicate that can refine the type of\n *   the `Cause`.\n *\n * This is useful when you need to extract specific types of errors, defects, or\n * interruptions from a `Cause` while discarding unrelated parts.\n *\n * @since 2.0.0\n * @category Filtering\n */\nexport const filter: {\n  <E, EB extends E>(refinement: Refinement<Cause<NoInfer<E>>, Cause<EB>>): (self: Cause<E>) => Cause<EB>\n  <E>(predicate: Predicate<Cause<NoInfer<E>>>): (self: Cause<E>) => Cause<E>\n  <E, EB extends E>(self: Cause<E>, refinement: Refinement<Cause<E>, Cause<EB>>): Cause<EB>\n  <E>(self: Cause<E>, predicate: Predicate<Cause<E>>): Cause<E>\n} = internal.filter\n\n/**\n * Transforms a `Cause` into a single value using custom handlers for each\n * possible case.\n *\n * **Details**\n *\n * This function processes a `Cause` by applying a set of custom handlers to\n * each possible type of cause: `Empty`, `Fail`, `Die`, `Interrupt`,\n * `Sequential`, and `Parallel`. The result of this function is a single value\n * of type `Z`. This function allows you to define exactly how to handle each\n * part of a `Cause`, whether it's a failure, defect, interruption, or a\n * combination of these.\n *\n * The options parameter provides handlers for:\n * - `onEmpty`: Handles the case where the cause is `Empty`, meaning no errors\n *   occurred.\n * - `onFail`: Processes a failure with an error of type `E`.\n * - `onDie`: Processes a defect (unexpected error).\n * - `onInterrupt`: Handles a fiber interruption, providing the `FiberId` of the\n *   interruption.\n * - `onSequential`: Combines two sequential causes into a single value of type\n *   `Z`.\n * - `onParallel`: Combines two parallel causes into a single value of type `Z`.\n *\n * @since 2.0.0\n * @category Matching\n */\nexport const match: {\n  <Z, E>(\n    options: {\n      readonly onEmpty: Z\n      readonly onFail: (error: E) => Z\n      readonly onDie: (defect: unknown) => Z\n      readonly onInterrupt: (fiberId: FiberId.FiberId) => Z\n      readonly onSequential: (left: Z, right: Z) => Z\n      readonly onParallel: (left: Z, right: Z) => Z\n    }\n  ): (self: Cause<E>) => Z\n  <Z, E>(\n    self: Cause<E>,\n    options: {\n      readonly onEmpty: Z\n      readonly onFail: (error: E) => Z\n      readonly onDie: (defect: unknown) => Z\n      readonly onInterrupt: (fiberId: FiberId.FiberId) => Z\n      readonly onSequential: (left: Z, right: Z) => Z\n      readonly onParallel: (left: Z, right: Z) => Z\n    }\n  ): Z\n} = internal.match\n\n/**\n * Combines all parts of a `Cause` into a single value by starting with an\n * initial value.\n *\n * **Details**\n *\n * This function processes a `Cause` by starting with an initial value (`zero`)\n * and applying a custom function (`pf`) to combine all elements of the `Cause`\n * into a single result of type `Z`. The custom function determines how each\n * part of the `Cause` contributes to the final result. The function can return\n * an `Option` to either continue combining values or skip specific parts of the\n * `Cause`.\n *\n * This function is useful for tasks such as:\n * - Aggregating error messages from a `Cause` into a single string.\n * - Summarizing the structure of a `Cause` into a simplified result.\n * - Filtering or processing only specific parts of a `Cause`.\n *\n * The reduction proceeds in a top-down manner, visiting all nodes in the\n * `Cause` structure. This gives you complete control over how each part of the\n * `Cause` contributes to the final result.\n *\n * @since 2.0.0\n * @category Reducing\n */\nexport const reduce: {\n  <Z, E>(zero: Z, pf: (accumulator: Z, cause: Cause<E>) => Option.Option<Z>): (self: Cause<E>) => Z\n  <Z, E>(self: Cause<E>, zero: Z, pf: (accumulator: Z, cause: Cause<E>) => Option.Option<Z>): Z\n} = internal.reduce\n\n/**\n * Combines all parts of a `Cause` into a single value using a custom reducer\n * and a context.\n *\n * **Details**\n *\n * This function allows you to reduce a `Cause` into a single value of type `Z`\n * using a custom `CauseReducer`. A `CauseReducer` provides methods to handle\n * specific parts of the `Cause`, such as failures, defects, or interruptions.\n * Additionally, this function provides access to a `context` value, which can\n * be used to carry information or maintain state during the reduction process.\n *\n * This is particularly useful when the reduction process needs additional\n * context or configuration, such as:\n * - Aggregating error details with dynamic formatting.\n * - Collecting logs or statistics about the `Cause`.\n * - Performing stateful transformations based on the `context`.\n *\n * @see {@link reduce} To reduce a `Cause` without additional context.\n *\n * @since 2.0.0\n * @category Reducing\n */\nexport const reduceWithContext: {\n  <C, E, Z>(context: C, reducer: CauseReducer<C, E, Z>): (self: Cause<E>) => Z\n  <C, E, Z>(self: Cause<E>, context: C, reducer: CauseReducer<C, E, Z>): Z\n} = internal.reduceWithContext\n\n/**\n * Creates an error that indicates a `Fiber` was interrupted.\n *\n * **Details**\n *\n * This function constructs an `InterruptedException` recognized by the Effect\n * runtime. It is usually thrown or returned when a fiber's execution is\n * interrupted by external events or by another fiber. This is particularly\n * helpful in concurrent programs where fibers may halt each other before\n * completion.\n *\n * @since 2.0.0\n * @category Errors\n */\nexport const InterruptedException: new(message?: string | undefined) => InterruptedException = core.InterruptedException\n\n/**\n * Checks if a given unknown value is an `InterruptedException`.\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isInterruptedException: (u: unknown) => u is InterruptedException = core.isInterruptedException\n\n/**\n * Creates an error indicating an invalid method argument.\n *\n * **Details**\n *\n * This function constructs an `IllegalArgumentException`. It is typically\n * thrown or returned when an operation receives improper inputs, such as\n * out-of-range values or invalid object states.\n *\n * @since 2.0.0\n * @category Errors\n */\nexport const IllegalArgumentException: new(message?: string | undefined) => IllegalArgumentException =\n  core.IllegalArgumentException\n\n/**\n * Checks if a given unknown value is an `IllegalArgumentException`.\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isIllegalArgumentException: (u: unknown) => u is IllegalArgumentException = core.isIllegalArgumentException\n\n/**\n * Creates an error indicating a missing element.\n *\n * **Details**\n *\n * This function constructs a `NoSuchElementException`. It helps you clearly\n * communicate that a required element is unavailable.\n *\n * @since 2.0.0\n * @category Errors\n */\nexport const NoSuchElementException: new(message?: string | undefined) => NoSuchElementException =\n  core.NoSuchElementException\n\n/**\n * Checks if a given unknown value is a `NoSuchElementException`.\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isNoSuchElementException: (u: unknown) => u is NoSuchElementException = core.isNoSuchElementException\n\n/**\n * Creates an error for general runtime errors.\n *\n * **Details**\n *\n * This function constructs a `RuntimeException`, for errors that occur at\n * runtime but are not specifically typed or categorized as interruptions,\n * missing elements, or invalid arguments. It helps unify a wide range of\n * unexpected conditions under a single, recognizable error type.\n *\n * @since 2.0.0\n * @category Errors\n */\nexport const RuntimeException: new(message?: string | undefined) => RuntimeException = core.RuntimeException\n\n/**\n * Checks if a given unknown value is a `RuntimeException`.\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isRuntimeException: (u: unknown) => u is RuntimeException = core.isRuntimeException\n\n/**\n * Creates an error for operations that exceed their expected time.\n *\n * **Details**\n *\n * This function constructs a `TimeoutException`. It is typically used to signal\n * that an operation or fiber did not complete within a designated time limit,\n * allowing you to handle slow or hanging processes.\n *\n * @since 2.0.0\n * @category Errors\n */\nexport const TimeoutException: new(message?: string | undefined) => TimeoutException = core.TimeoutException\n\n/**\n * Checks if a given unknown value is a `TimeoutException`.\n *\n * @since 3.15.0\n * @category Guards\n */\nexport const isTimeoutException: (u: unknown) => u is TimeoutException = core.isTimeoutException\n\n/**\n * Creates an instance of `UnknownException`, an error object used to handle\n * unknown errors such as those from rejected promises.\n *\n * **Details**\n *\n * This function constructs an `UnknownException` with flexible behavior for\n * managing the error message and cause.\n *\n * The required `error` argument is passed as the `cause` to the global `Error`\n * constructor, ensuring that the original cause is preserved in the error chain\n * for debugging purposes. This ensures that the origin stack trace is\n * preserved.\n *\n * The `error` argument is always stored in the `error` property of the\n * `UnknownException` instance for reference, regardless of its type.\n *\n * Additionally, if you provide a `message` argument, it is used as the error\n * message. If no `message` is provided, the error message defaults to `\"An\n * unknown error occurred\"`.\n *\n * **When to Use**\n *\n * Use this function when you need to handle unexpected or unknown errors in\n * your application, particularly when the source of the error might not provide\n * a clear message. This is useful for wrapping generic errors thrown from\n * promises or external APIs.\n *\n * @since 2.0.0\n * @category Errors\n */\nexport const UnknownException: new(error: unknown, message?: string | undefined) => UnknownException =\n  core.UnknownException\n\n/**\n * Checks if a given unknown value is an `UnknownException`.\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isUnknownException: (u: unknown) => u is UnknownException = core.isUnknownException\n\n/**\n * Creates an error indicating resource capacity has been exceeded.\n *\n * **Details**\n *\n * This function constructs an `ExceededCapacityException`, signifying that an\n * operation or resource usage surpassed established limits. This can be\n * essential for concurrency or resource management situations, ensuring your\n * application doesn't go beyond acceptable thresholds.\n *\n * @since 3.5.0\n * @category Errors\n */\nexport const ExceededCapacityException: new(message?: string | undefined) => ExceededCapacityException =\n  core.ExceededCapacityException\n\n/**\n * Checks if a given unknown value is an `ExceededCapacityException`.\n *\n * @since 3.5.0\n * @category Guards\n */\nexport const isExceededCapacityException: (u: unknown) => u is ExceededCapacityException =\n  core.isExceededCapacityException\n\n/**\n * Converts a `Cause` into a human-readable string.\n *\n * **Details**\n *\n * This function pretty-prints the entire `Cause`, including any failures,\n * defects, and interruptions. It can be especially helpful for logging,\n * debugging, or displaying structured errors to users.\n *\n * You can optionally pass `options` to configure how the error cause is\n * rendered. By default, it includes essential details of all errors in the\n * `Cause`.\n *\n * @see {@link prettyErrors} Get a list of `PrettyError` objects instead of a single string.\n *\n * @since 2.0.0\n * @category Formatting\n */\nexport const pretty: <E>(cause: Cause<E>, options?: {\n  readonly renderErrorCause?: boolean | undefined\n}) => string = internal.pretty\n\n/**\n * A shape for prettified errors, optionally including a source span.\n *\n * @since 3.2.0\n * @category Models\n */\nexport interface PrettyError extends Error {\n  readonly span: Span | undefined\n}\n\n/**\n * Returns a list of prettified errors (`PrettyError`) from a `Cause`.\n *\n * **Details**\n *\n * This function inspects the entire `Cause` and produces an array of\n * `PrettyError` objects. Each object may include additional metadata, such as a\n * `Span`, to provide deeper insights into where and how the error occurred.\n *\n * @since 3.2.0\n * @category Formatting\n */\nexport const prettyErrors: <E>(cause: Cause<E>) => Array<PrettyError> = internal.prettyErrors\n\n/**\n * Retrieves the original, unproxied error instance from an error object.\n *\n * **Details**\n *\n * This function returns the underlying error object without any\n * library-specific wrapping or proxying that might occur during error handling.\n * This can be essential if you need direct access to the error's native\n * properties, such as stack traces or custom data fields, for detailed\n * debugging or integration with external systems.\n *\n * @since 2.0.0\n * @category Errors\n */\nexport const originalError: <E>(obj: E) => E = core.originalInstance\n"
  },
  {
    "path": "packages/effect/src/Channel.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as ChildExecutorDecision from \"./ChildExecutorDecision.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as Deferred from \"./Deferred.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport * as channel from \"./internal/channel.js\"\nimport * as core from \"./internal/core-stream.js\"\nimport * as sink from \"./internal/sink.js\"\nimport * as stream from \"./internal/stream.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type * as MergeDecision from \"./MergeDecision.js\"\nimport type * as MergeStrategy from \"./MergeStrategy.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate } from \"./Predicate.js\"\nimport type * as PubSub from \"./PubSub.js\"\nimport type * as Queue from \"./Queue.js\"\nimport type * as Ref from \"./Ref.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as SingleProducerAsyncInput from \"./SingleProducerAsyncInput.js\"\nimport type * as Sink from \"./Sink.js\"\nimport type * as Stream from \"./Stream.js\"\nimport type * as Tracer from \"./Tracer.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\nimport type * as UpstreamPullRequest from \"./UpstreamPullRequest.js\"\nimport type * as UpstreamPullStrategy from \"./UpstreamPullStrategy.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ChannelTypeId: unique symbol = core.ChannelTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ChannelTypeId = typeof ChannelTypeId\n\n/**\n * A `Channel` is a nexus of I/O operations, which supports both reading and\n * writing. A channel may read values of type `InElem` and write values of type\n * `OutElem`. When the channel finishes, it yields a value of type `OutDone`. A\n * channel may fail with a value of type `OutErr`.\n *\n * Channels are the foundation of Streams: both streams and sinks are built on\n * channels. Most users shouldn't have to use channels directly, as streams and\n * sinks are much more convenient and cover all common use cases. However, when\n * adding new stream and sink operators, or doing something highly specialized,\n * it may be useful to use channels directly.\n *\n * Channels compose in a variety of ways:\n *\n *  - **Piping**: One channel can be piped to another channel, assuming the\n *    input type of the second is the same as the output type of the first.\n *  - **Sequencing**: The terminal value of one channel can be used to create\n *    another channel, and both the first channel and the function that makes\n *    the second channel can be composed into a channel.\n *  - **Concatenating**: The output of one channel can be used to create other\n *    channels, which are all concatenated together. The first channel and the\n *    function that makes the other channels can be composed into a channel.\n *\n * @since 2.0.0\n * @category models\n */\n// export interface Channel<out Env, in InErr, in InElem, in InDone, out OutErr, out OutElem, out OutDone>\nexport interface Channel<\n  out OutElem,\n  in InElem = unknown,\n  out OutErr = never,\n  in InErr = unknown,\n  out OutDone = void,\n  in InDone = unknown,\n  out Env = never\n> extends\n  Channel.Variance<\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env\n  >,\n  Pipeable\n{\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: ChannelUnify<this>\n  [Unify.ignoreSymbol]?: ChannelUnifyIgnore\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface ChannelUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  Channel?: () => A[Unify.typeSymbol] extends\n    | Channel<\n      infer OutElem,\n      infer InElem,\n      infer OutErr,\n      infer InErr,\n      infer OutDone,\n      infer InDone,\n      infer Env\n    >\n    | infer _ ? Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n    : never\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface ChannelUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Channel?: true\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\ndeclare module \"./Effect.js\" {\n  interface Effect<A, E, R> extends Channel<never, unknown, E, unknown, A, unknown, R> {}\n  interface EffectUnifyIgnore {\n    Channel?: true\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Channel {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out OutElem, in InElem, out OutErr, in InErr, out OutDone, in InDone, out Env> {\n    readonly [ChannelTypeId]: VarianceStruct<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  }\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface VarianceStruct<out OutElem, in InElem, out OutErr, in InErr, out OutDone, in InDone, out Env> {\n    _Env: Types.Covariant<Env>\n    _InErr: Types.Contravariant<InErr>\n    _InElem: Types.Contravariant<InElem>\n    _InDone: Types.Contravariant<InDone>\n    _OutErr: Types.Covariant<OutErr>\n    _OutElem: Types.Covariant<OutElem>\n    _OutDone: Types.Covariant<OutDone>\n  }\n}\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ChannelExceptionTypeId: unique symbol = channel.ChannelExceptionTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ChannelExceptionTypeId = typeof ChannelExceptionTypeId\n\n/**\n * Represents a generic checked exception which occurs when a `Channel` is\n * executed.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface ChannelException<out E> {\n  readonly _tag: \"ChannelException\"\n  readonly [ChannelExceptionTypeId]: ChannelExceptionTypeId\n  readonly error: E\n}\n\n/**\n * @since 3.5.4\n * @category refinements\n */\nexport const isChannel: (u: unknown) => u is Channel<\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown\n> = core.isChannel\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const acquireUseRelease: <Acquired, OutErr, Env, OutElem1, InElem, InErr, OutDone, InDone>(\n  acquire: Effect.Effect<Acquired, OutErr, Env>,\n  use: (a: Acquired) => Channel<OutElem1, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  release: (a: Acquired, exit: Exit.Exit<OutDone, OutErr>) => Effect.Effect<any, never, Env>\n) => Channel<OutElem1, InElem, OutErr, InErr, OutDone, InDone, Env> = channel.acquireUseRelease\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const acquireReleaseOut: {\n  <Z, R2>(\n    release: (z: Z, e: Exit.Exit<unknown, unknown>) => Effect.Effect<unknown, never, R2>\n  ): <E, R>(self: Effect.Effect<Z, E, R>) => Channel<Z, unknown, E, unknown, void, unknown, R2 | R>\n  <Z, E, R, R2>(\n    self: Effect.Effect<Z, E, R>,\n    release: (z: Z, e: Exit.Exit<unknown, unknown>) => Effect.Effect<unknown, never, R2>\n  ): Channel<Z, unknown, E, unknown, void, unknown, R | R2>\n} = core.acquireReleaseOut\n\n/**\n * Returns a new channel that is the same as this one, except the terminal\n * value of the channel is the specified constant value.\n *\n * This method produces the same result as mapping this channel to the\n * specified constant value.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const as: {\n  <OutDone2>(\n    value: OutDone2\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone2>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    value: OutDone2\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>\n} = channel.as\n\n/**\n * @since 2.0.0\n * @category mapping\n */\nexport const asVoid: <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n) => Channel<OutElem, InElem, OutErr, InErr, void, InDone, Env> = channel.asVoid\n\n/**\n * Creates a channel backed by a buffer. When the buffer is empty, the channel\n * will simply passthrough its input as output. However, when the buffer is\n * non-empty, the value inside the buffer will be passed along as output.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const buffer: <InElem, InErr, InDone>(\n  options: { readonly empty: InElem; readonly isEmpty: Predicate<InElem>; readonly ref: Ref.Ref<InElem> }\n) => Channel<InElem, InElem, InErr, InErr, InDone, InDone, never> = channel.buffer\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const bufferChunk: <InElem, InErr, InDone>(\n  ref: Ref.Ref<Chunk.Chunk<InElem>>\n) => Channel<Chunk.Chunk<InElem>, Chunk.Chunk<InElem>, InErr, InErr, InDone, InDone> = channel.bufferChunk\n\n/**\n * Returns a new channel that is the same as this one, except if this channel\n * errors for any typed error, then the returned channel will switch over to\n * using the fallback channel returned by the specified error handler.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchAll: {\n  <OutErr, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    f: (error: OutErr) => Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n  ): <OutElem, InElem, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone1 | OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (error: OutErr) => Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n  ): Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone | OutDone1,\n    InDone & InDone1,\n    Env | Env1\n  >\n} = channel.catchAll\n\n/**\n * Returns a new channel that is the same as this one, except if this channel\n * errors for any typed error, then the returned channel will switch over to\n * using the fallback channel returned by the specified error handler.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchAllCause: {\n  <OutErr, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    f: (cause: Cause.Cause<OutErr>) => Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n  ): <OutElem, InElem, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone1 | OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (cause: Cause.Cause<OutErr>) => Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n  ): Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone | OutDone1,\n    InDone & InDone1,\n    Env | Env1\n  >\n} = core.catchAllCause\n\n/**\n * Concat sequentially a channel of channels.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const concatAll: <OutElem, InElem, OutErr, InErr, InDone, Env>(\n  channels: Channel<Channel<OutElem, InElem, OutErr, InErr, any, InDone, Env>, InElem, OutErr, InErr, any, InDone, Env>\n) => Channel<OutElem, InElem, OutErr, InErr, any, InDone, Env> = core.concatAll\n\n/**\n * Concat sequentially a channel of channels.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const concatAllWith: <\n  OutElem,\n  InElem2,\n  OutErr2,\n  InErr2,\n  OutDone,\n  InDone2,\n  Env2,\n  InElem,\n  OutErr,\n  InErr,\n  OutDone2,\n  InDone,\n  Env,\n  OutDone3\n>(\n  channels: Channel<\n    Channel<OutElem, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone2,\n    InDone,\n    Env\n  >,\n  f: (o: OutDone, o1: OutDone) => OutDone,\n  g: (o: OutDone, o2: OutDone2) => OutDone3\n) => Channel<OutElem, InElem & InElem2, OutErr2 | OutErr, InErr & InErr2, OutDone3, InDone & InDone2, Env2 | Env> =\n  core.concatAllWith\n\n/**\n * Returns a new channel whose outputs are fed to the specified factory\n * function, which creates new channels in response. These new channels are\n * sequentially concatenated together, and all their outputs appear as outputs\n * of the newly returned channel.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const concatMap: {\n  <OutElem, OutElem2, InElem2, OutErr2, InErr2, X, InDone2, Env2>(\n    f: (o: OutElem) => Channel<OutElem2, InElem2, OutErr2, InErr2, X, InDone2, Env2>\n  ): <Env, InErr, InElem, InDone, OutErr, OutDone>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem2, InElem & InElem2, OutErr2 | OutErr, InErr & InErr2, unknown, InDone & InDone2, Env2 | Env>\n  <Env, InErr, InElem, InDone, OutErr, OutDone, OutElem, OutElem2, Env2, InErr2, InElem2, InDone2, OutErr2, X>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (o: OutElem) => Channel<OutElem2, InElem2, OutErr2, InErr2, X, InDone2, Env2>\n  ): Channel<OutElem2, InElem & InElem2, OutErr | OutErr2, InErr & InErr2, unknown, InDone & InDone2, Env | Env2>\n} = channel.concatMap\n\n/**\n * Returns a new channel whose outputs are fed to the specified factory\n * function, which creates new channels in response. These new channels are\n * sequentially concatenated together, and all their outputs appear as outputs\n * of the newly returned channel. The provided merging function is used to\n * merge the terminal values of all channels into the single terminal value of\n * the returned channel.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const concatMapWith: {\n  <OutElem, OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2, OutDone2, OutDone3>(\n    f: (o: OutElem) => Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n    g: (o: OutDone, o1: OutDone) => OutDone,\n    h: (o: OutDone, o2: OutDone2) => OutDone3\n  ): <Env, InErr, InElem, InDone, OutErr>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>\n  ) => Channel<OutElem2, InElem & InElem2, OutErr2 | OutErr, InErr & InErr2, OutDone3, InDone & InDone2, Env2 | Env>\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone2,\n    InDone,\n    Env,\n    OutElem2,\n    InElem2,\n    OutErr2,\n    InErr2,\n    OutDone,\n    InDone2,\n    Env2,\n    OutDone3\n  >(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>,\n    f: (o: OutElem) => Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n    g: (o: OutDone, o1: OutDone) => OutDone,\n    h: (o: OutDone, o2: OutDone2) => OutDone3\n  ): Channel<OutElem2, InElem & InElem2, OutErr | OutErr2, InErr & InErr2, OutDone3, InDone & InDone2, Env | Env2>\n} = core.concatMapWith\n\n/**\n * Returns a new channel whose outputs are fed to the specified factory\n * function, which creates new channels in response. These new channels are\n * sequentially concatenated together, and all their outputs appear as outputs\n * of the newly returned channel. The provided merging function is used to\n * merge the terminal values of all channels into the single terminal value of\n * the returned channel.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const concatMapWithCustom: {\n  <OutElem, OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2, OutDone2, OutDone3>(\n    f: (o: OutElem) => Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n    g: (o: OutDone, o1: OutDone) => OutDone,\n    h: (o: OutDone, o2: OutDone2) => OutDone3,\n    onPull: (\n      upstreamPullRequest: UpstreamPullRequest.UpstreamPullRequest<OutElem>\n    ) => UpstreamPullStrategy.UpstreamPullStrategy<OutElem2>,\n    onEmit: (elem: OutElem2) => ChildExecutorDecision.ChildExecutorDecision\n  ): <Env, InErr, InElem, InDone, OutErr>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>\n  ) => Channel<OutElem2, InElem & InElem2, OutErr2 | OutErr, InErr & InErr2, OutDone3, InDone & InDone2, Env2 | Env>\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone2,\n    InDone,\n    Env,\n    OutElem2,\n    InElem2,\n    OutErr2,\n    InErr2,\n    OutDone,\n    InDone2,\n    Env2,\n    OutDone3\n  >(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>,\n    f: (o: OutElem) => Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n    g: (o: OutDone, o1: OutDone) => OutDone,\n    h: (o: OutDone, o2: OutDone2) => OutDone3,\n    onPull: (\n      upstreamPullRequest: UpstreamPullRequest.UpstreamPullRequest<OutElem>\n    ) => UpstreamPullStrategy.UpstreamPullStrategy<OutElem2>,\n    onEmit: (elem: OutElem2) => ChildExecutorDecision.ChildExecutorDecision\n  ): Channel<OutElem2, InElem & InElem2, OutErr | OutErr2, InErr & InErr2, OutDone3, InDone & InDone2, Env | Env2>\n} = core.concatMapWithCustom\n\n/**\n * Returns a new channel, which is the same as this one, except its outputs\n * are filtered and transformed by the specified partial function.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const collect: {\n  <OutElem, OutElem2>(\n    pf: (o: OutElem) => Option.Option<OutElem2>\n  ): <InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, unknown, never, unknown, void, unknown, never>\n  ) => Channel<OutElem2, InElem, OutErr, InErr, OutDone, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    pf: (o: OutElem) => Option.Option<OutElem2>\n  ): Channel<OutElem2, InElem, OutErr, InErr, OutDone, InDone, Env>\n} = channel.collect\n\n/**\n * Returns a new channel, which is the concatenation of all the channels that\n * are written out by this channel. This method may only be called on channels\n * that output other channels.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const concatOut: <OutElem, InElem, OutErr, InErr, InDone, Env, OutDone>(\n  self: Channel<\n    Channel<OutElem, InElem, OutErr, InErr, unknown, InDone, Env>,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env\n  >\n) => Channel<OutElem, InElem, OutErr, InErr, unknown, InDone, Env> = channel.concatOut\n\n/**\n * Returns a new channel which is the same as this one but applies the given\n * function to the input channel's done value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mapInput: {\n  <InDone0, InDone>(\n    f: (a: InDone0) => InDone\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone0, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InDone0>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (a: InDone0) => InDone\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone0, Env>\n} = channel.mapInput\n\n/**\n * Returns a new channel which is the same as this one but applies the given\n * effectual function to the input channel's done value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mapInputEffect: {\n  <InDone0, InDone, InErr, Env1>(\n    f: (i: InDone0) => Effect.Effect<InDone, InErr, Env1>\n  ): <OutElem, InElem, OutErr, OutDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone0, Env1 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InDone0, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (i: InDone0) => Effect.Effect<InDone, InErr, Env1>\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone0, Env | Env1>\n} = channel.mapInputEffect\n\n/**\n * Returns a new channel which is the same as this one but applies the given\n * function to the input channel's error value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mapInputError: {\n  <InErr0, InErr>(\n    f: (a: InErr0) => InErr\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr0, OutDone, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InErr0>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (a: InErr0) => InErr\n  ): Channel<OutElem, InElem, OutErr, InErr0, OutDone, InDone, Env>\n} = channel.mapInputError\n\n/**\n * Returns a new channel which is the same as this one but applies the given\n * effectual function to the input channel's error value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mapInputErrorEffect: {\n  <InErr0, InDone, InErr, Env1>(\n    f: (error: InErr0) => Effect.Effect<InDone, InErr, Env1>\n  ): <OutElem, InElem, OutErr, OutDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr0, OutDone, InDone, Env1 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InErr0, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (error: InErr0) => Effect.Effect<InDone, InErr, Env1>\n  ): Channel<OutElem, InElem, OutErr, InErr0, OutDone, InDone, Env | Env1>\n} = channel.mapInputErrorEffect\n\n/**\n * Returns a new channel which is the same as this one but applies the given\n * function to the input channel's output elements.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mapInputIn: {\n  <InElem0, InElem>(\n    f: (a: InElem0) => InElem\n  ): <OutElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem0, OutErr, InErr, OutDone, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InElem0>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (a: InElem0) => InElem\n  ): Channel<OutElem, InElem0, OutErr, InErr, OutDone, InDone, Env>\n} = channel.mapInputIn\n\n/**\n * Returns a new channel which is the same as this one but applies the given\n * effectual function to the input channel's output elements.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mapInputInEffect: {\n  <InElem0, InElem, InErr, Env1>(\n    f: (a: InElem0) => Effect.Effect<InElem, InErr, Env1>\n  ): <OutElem, OutErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem0, OutErr, InErr, OutDone, InDone, Env1 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InElem0, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (a: InElem0) => Effect.Effect<InElem, InErr, Env1>\n  ): Channel<OutElem, InElem0, OutErr, InErr, OutDone, InDone, Env | Env1>\n} = channel.mapInputInEffect\n\n/**\n * Returns a new channel, which is the same as this one, except that all the\n * outputs are collected and bundled into a tuple together with the terminal\n * value of this channel.\n *\n * As the channel returned from this channel collects all of this channel's\n * output into an in- memory chunk, it is not safe to call this method on\n * channels that output a large or unbounded number of values.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const doneCollect: <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n) => Channel<never, InElem, OutErr, InErr, [Chunk.Chunk<OutElem>, OutDone], InDone, Env> = channel.doneCollect\n\n/**\n * Returns a new channel which reads all the elements from upstream's output\n * channel and ignores them, then terminates with the upstream result value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const drain: <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n) => Channel<never, InElem, OutErr, InErr, OutDone, InDone, Env> = channel.drain\n\n/**\n * Returns a new channel which connects the given `AsyncInputProducer` as\n * this channel's input.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const embedInput: {\n  <InErr, InElem, InDone>(\n    input: SingleProducerAsyncInput.AsyncInputProducer<InErr, InElem, InDone>\n  ): <OutElem, OutErr, OutDone, Env>(\n    self: Channel<OutElem, unknown, OutErr, unknown, OutDone, unknown, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  <OutElem, OutErr, OutDone, Env, InErr, InElem, InDone>(\n    self: Channel<OutElem, unknown, OutErr, unknown, OutDone, unknown, Env>,\n    input: SingleProducerAsyncInput.AsyncInputProducer<InErr, InElem, InDone>\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n} = core.embedInput\n\n/**\n * Returns a new channel that collects the output and terminal value of this\n * channel, which it then writes as output of the returned channel.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const emitCollect: <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n) => Channel<[Chunk.Chunk<OutElem>, OutDone], InElem, OutErr, InErr, void, InDone, Env> = channel.emitCollect\n\n/**\n * Returns a new channel with an attached finalizer. The finalizer is\n * guaranteed to be executed so long as the channel begins execution (and\n * regardless of whether or not it completes).\n *\n * @since 2.0.0\n * @category utils\n */\nexport const ensuring: {\n  <Z, Env1>(\n    finalizer: Effect.Effect<Z, never, Env1>\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env1 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, Z, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    finalizer: Effect.Effect<Z, never, Env1>\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env | Env1>\n} = channel.ensuring\n\n/**\n * Returns a new channel with an attached finalizer. The finalizer is\n * guaranteed to be executed so long as the channel begins execution (and\n * regardless of whether or not it completes).\n *\n * @since 2.0.0\n * @category utils\n */\nexport const ensuringWith: {\n  <OutDone, OutErr, Env2>(\n    finalizer: (e: Exit.Exit<OutDone, OutErr>) => Effect.Effect<unknown, never, Env2>\n  ): <OutElem, InElem, InErr, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env2 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, Env2>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    finalizer: (e: Exit.Exit<OutDone, OutErr>) => Effect.Effect<unknown, never, Env2>\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env | Env2>\n} = core.ensuringWith\n\n/**\n * Accesses the whole context of the channel.\n *\n * @since 2.0.0\n * @category context\n */\nexport const context: <Env>() => Channel<never, unknown, never, unknown, Context.Context<Env>, unknown, Env> =\n  channel.context\n\n/**\n * Accesses the context of the channel with the specified function.\n *\n * @since 2.0.0\n * @category context\n */\nexport const contextWith: <Env, OutDone>(\n  f: (env: Context.Context<Env>) => OutDone\n) => Channel<never, unknown, never, unknown, OutDone, unknown, Env> = channel.contextWith\n\n/**\n * Accesses the context of the channel in the context of a channel.\n *\n * @since 2.0.0\n * @category context\n */\nexport const contextWithChannel: <Env, OutElem, InElem, OutErr, InErr, OutDone, InDone, Env1>(\n  f: (env: Context.Context<Env>) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env1>\n) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env | Env1> = channel.contextWithChannel\n\n/**\n * Accesses the context of the channel in the context of an effect.\n *\n * @since 2.0.0\n * @category context\n */\nexport const contextWithEffect: <Env, OutDone, OutErr, Env1>(\n  f: (env: Context.Context<Env>) => Effect.Effect<OutDone, OutErr, Env1>\n) => Channel<never, unknown, OutErr, unknown, OutDone, unknown, Env | Env1> = channel.contextWithEffect\n\n/**\n * Constructs a channel that fails immediately with the specified error.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fail: <E>(error: E) => Channel<never, unknown, E, unknown, never, unknown> = core.fail\n\n/**\n * Constructs a channel that succeeds immediately with the specified lazily\n * evaluated value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failSync: <E>(evaluate: LazyArg<E>) => Channel<never, unknown, E, unknown, never, unknown> = core.failSync\n\n/**\n * Constructs a channel that fails immediately with the specified `Cause`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCause: <E>(cause: Cause.Cause<E>) => Channel<never, unknown, E, unknown, never, unknown> =\n  core.failCause\n\n/**\n * Constructs a channel that succeeds immediately with the specified lazily\n * evaluated `Cause`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCauseSync: <E>(\n  evaluate: LazyArg<Cause.Cause<E>>\n) => Channel<never, unknown, E, unknown, never, unknown> = core.failCauseSync\n\n/**\n * Returns a new channel, which sequentially combines this channel, together\n * with the provided factory function, which creates a second channel based on\n * the terminal value of this channel. The result is a channel that will first\n * perform the functions of this channel, before performing the functions of\n * the created channel (including yielding its terminal value).\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMap: {\n  <OutDone, OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>(\n    f: (d: OutDone) => Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>\n  ): <OutElem, InElem, OutErr, InErr, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    OutDone2,\n    InDone & InDone1,\n    Env1 | Env\n  >\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (d: OutDone) => Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>\n  ): Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    OutDone2,\n    InDone & InDone1,\n    Env | Env1\n  >\n} = core.flatMap\n\n/**\n * Returns a new channel, which flattens the terminal value of this channel.\n * This function may only be called if the terminal value of this channel is\n * another channel of compatible types.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatten: <\n  OutElem,\n  InElem,\n  OutErr,\n  InErr,\n  OutElem1,\n  InElem1,\n  OutErr1,\n  InErr1,\n  OutDone2,\n  InDone1,\n  Env1,\n  InDone,\n  Env\n>(\n  self: Channel<\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>,\n    InDone,\n    Env\n  >\n) => Channel<\n  OutElem | OutElem1,\n  InElem & InElem1,\n  OutErr | OutErr1,\n  InErr & InErr1,\n  OutDone2,\n  InDone & InDone1,\n  Env1 | Env\n> = channel.flatten\n\n/**\n * Folds over the result of this channel.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const foldChannel: {\n  <\n    OutErr,\n    OutElem1,\n    InElem1,\n    OutErr1,\n    InErr1,\n    OutDone1,\n    InDone1,\n    Env1,\n    OutDone,\n    OutElem2,\n    InElem2,\n    OutErr2,\n    InErr2,\n    OutDone2,\n    InDone2,\n    Env2\n  >(\n    options: {\n      readonly onFailure: (error: OutErr) => Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n      readonly onSuccess: (done: OutDone) => Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone2, InDone2, Env2>\n    }\n  ): <Env, InErr, InElem, InDone, OutElem>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<\n    OutElem1 | OutElem2 | OutElem,\n    InElem & InElem1 & InElem2,\n    OutErr1 | OutErr2,\n    InErr & InErr1 & InErr2,\n    OutDone1 | OutDone2,\n    InDone & InDone1 & InDone2,\n    Env1 | Env2 | Env\n  >\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env,\n    OutElem1,\n    InElem1,\n    OutErr1,\n    InErr1,\n    OutDone1,\n    InDone1,\n    Env1,\n    OutElem2,\n    InElem2,\n    OutErr2,\n    InErr2,\n    OutDone2,\n    InDone2,\n    Env2\n  >(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    options: {\n      readonly onFailure: (error: OutErr) => Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n      readonly onSuccess: (done: OutDone) => Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone2, InDone2, Env2>\n    }\n  ): Channel<\n    OutElem | OutElem1 | OutElem2,\n    InElem & InElem1 & InElem2,\n    OutErr1 | OutErr2,\n    InErr & InErr1 & InErr2,\n    OutDone1 | OutDone2,\n    InDone & InDone1 & InDone2,\n    Env | Env1 | Env2\n  >\n} = channel.foldChannel\n\n/**\n * Folds over the result of this channel including any cause of termination.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const foldCauseChannel: {\n  <\n    OutErr,\n    OutElem1,\n    InElem1,\n    OutErr2,\n    InErr1,\n    OutDone2,\n    InDone1,\n    Env1,\n    OutDone,\n    OutElem2,\n    InElem2,\n    OutErr3,\n    InErr2,\n    OutDone3,\n    InDone2,\n    Env2\n  >(\n    options: {\n      readonly onFailure: (\n        c: Cause.Cause<OutErr>\n      ) => Channel<OutElem1, InElem1, OutErr2, InErr1, OutDone2, InDone1, Env1>\n      readonly onSuccess: (o: OutDone) => Channel<OutElem2, InElem2, OutErr3, InErr2, OutDone3, InDone2, Env2>\n    }\n  ): <Env, InErr, InElem, InDone, OutElem>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<\n    OutElem1 | OutElem2 | OutElem,\n    InElem & InElem1 & InElem2,\n    OutErr2 | OutErr3,\n    InErr & InErr1 & InErr2,\n    OutDone2 | OutDone3,\n    InDone & InDone1 & InDone2,\n    Env1 | Env2 | Env\n  >\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env,\n    OutElem1,\n    InElem1,\n    OutErr2,\n    InErr1,\n    OutDone2,\n    InDone1,\n    Env1,\n    OutElem2,\n    InElem2,\n    OutErr3,\n    InErr2,\n    OutDone3,\n    InDone2,\n    Env2\n  >(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    options: {\n      readonly onFailure: (\n        c: Cause.Cause<OutErr>\n      ) => Channel<OutElem1, InElem1, OutErr2, InErr1, OutDone2, InDone1, Env1>\n      readonly onSuccess: (o: OutDone) => Channel<OutElem2, InElem2, OutErr3, InErr2, OutDone3, InDone2, Env2>\n    }\n  ): Channel<\n    OutElem | OutElem1 | OutElem2,\n    InElem & InElem1 & InElem2,\n    OutErr2 | OutErr3,\n    InErr & InErr1 & InErr2,\n    OutDone2 | OutDone3,\n    InDone & InDone1 & InDone2,\n    Env | Env1 | Env2\n  >\n} = core.foldCauseChannel\n\n/**\n * Use an effect to end a channel.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEffect: <A, E, R>(\n  effect: Effect.Effect<A, E, R>\n) => Channel<never, unknown, E, unknown, A, unknown, R> = core.fromEffect\n\n/**\n * Constructs a channel from an `Either`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEither: <R, L>(either: Either.Either<R, L>) => Channel<never, unknown, L, unknown, R, unknown> =\n  channel.fromEither\n\n/**\n * Construct a `Channel` from an `AsyncInputConsumer`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromInput: <Err, Elem, Done>(\n  input: SingleProducerAsyncInput.AsyncInputConsumer<Err, Elem, Done>\n) => Channel<Elem, unknown, Err, unknown, Done, unknown> = channel.fromInput\n\n/**\n * Construct a `Channel` from a `PubSub`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromPubSub: <Done, Err, Elem>(\n  pubsub: PubSub.PubSub<Either.Either<Elem, Exit.Exit<Done, Err>>>\n) => Channel<Elem, unknown, Err, unknown, Done, unknown> = channel.fromPubSub\n\n/**\n * Construct a `Channel` from a `PubSub` within a scoped effect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromPubSubScoped: <Done, Err, Elem>(\n  pubsub: PubSub.PubSub<Either.Either<Elem, Exit.Exit<Done, Err>>>\n) => Effect.Effect<Channel<Elem, unknown, Err, unknown, Done, unknown>, never, Scope.Scope> = channel.fromPubSubScoped\n\n/**\n * Construct a `Channel` from an `Option`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromOption: <A>(\n  option: Option.Option<A>\n) => Channel<never, unknown, Option.Option<never>, unknown, A, unknown> = channel.fromOption\n\n/**\n * Construct a `Channel` from a `Queue`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromQueue: <Done, Err, Elem>(\n  queue: Queue.Dequeue<Either.Either<Elem, Exit.Exit<Done, Err>>>\n) => Channel<Elem, unknown, Err, unknown, Done, unknown> = channel.fromQueue\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const identity: <Elem, Err, Done>() => Channel<Elem, Elem, Err, Err, Done, Done> = channel.identityChannel\n\n/**\n * Returns a new channel, which is the same as this one, except it will be\n * interrupted when the specified effect completes. If the effect completes\n * successfully before the underlying channel is done, then the returned\n * channel will yield the success value of the effect as its terminal value.\n * On the other hand, if the underlying channel finishes first, then the\n * returned channel will yield the success value of the underlying channel as\n * its terminal value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const interruptWhen: {\n  <OutDone1, OutErr1, Env1>(\n    effect: Effect.Effect<OutDone1, OutErr1, Env1>\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr1 | OutErr, InErr, OutDone1 | OutDone, InDone, Env1 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone1, OutErr1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    effect: Effect.Effect<OutDone1, OutErr1, Env1>\n  ): Channel<OutElem, InElem, OutErr | OutErr1, InErr, OutDone | OutDone1, InDone, Env | Env1>\n} = channel.interruptWhen\n\n/**\n * Returns a new channel, which is the same as this one, except it will be\n * interrupted when the specified deferred is completed. If the deferred is\n * completed before the underlying channel is done, then the returned channel\n * will yield the value of the deferred. Otherwise, if the underlying channel\n * finishes first, then the returned channel will yield the value of the\n * underlying channel.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const interruptWhenDeferred: {\n  <OutDone1, OutErr1>(\n    deferred: Deferred.Deferred<OutDone1, OutErr1>\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr1 | OutErr, InErr, OutDone1 | OutDone, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone1, OutErr1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    deferred: Deferred.Deferred<OutDone1, OutErr1>\n  ): Channel<OutElem, InElem, OutErr | OutErr1, InErr, OutDone | OutDone1, InDone, Env>\n} = channel.interruptWhenDeferred\n\n/**\n * Returns a new channel, which is the same as this one, except the terminal\n * value of the returned channel is created by applying the specified function\n * to the terminal value of this channel.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <OutDone, OutDone2>(\n    f: (out: OutDone) => OutDone2\n  ): <OutElem, InElem, OutErr, InErr, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone2>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (out: OutDone) => OutDone2\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>\n} = channel.map\n\n/**\n * Returns a new channel, which is the same as this one, except the terminal\n * value of the returned channel is created by applying the specified\n * effectful function to the terminal value of this channel.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapEffect: {\n  <OutDone, OutDone1, OutErr1, Env1>(\n    f: (o: OutDone) => Effect.Effect<OutDone1, OutErr1, Env1>\n  ): <OutElem, InElem, OutErr, InErr, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr1 | OutErr, InErr, OutDone1, InDone, Env1 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone1, OutErr1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (o: OutDone) => Effect.Effect<OutDone1, OutErr1, Env1>\n  ): Channel<OutElem, InElem, OutErr | OutErr1, InErr, OutDone1, InDone, Env | Env1>\n} = channel.mapEffect\n\n/**\n * Returns a new channel, which is the same as this one, except the failure\n * value of the returned channel is created by applying the specified function\n * to the failure value of this channel.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapError: {\n  <OutErr, OutErr2>(\n    f: (err: OutErr) => OutErr2\n  ): <OutElem, InElem, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr2, InErr, OutDone, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutErr2>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (err: OutErr) => OutErr2\n  ): Channel<OutElem, InElem, OutErr2, InErr, OutDone, InDone, Env>\n} = channel.mapError\n\n/**\n * A more powerful version of `mapError` which also surfaces the `Cause`\n * of the channel failure.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapErrorCause: {\n  <OutErr, OutErr2>(\n    f: (cause: Cause.Cause<OutErr>) => Cause.Cause<OutErr2>\n  ): <OutElem, InElem, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr2, InErr, OutDone, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutErr2>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (cause: Cause.Cause<OutErr>) => Cause.Cause<OutErr2>\n  ): Channel<OutElem, InElem, OutErr2, InErr, OutDone, InDone, Env>\n} = channel.mapErrorCause\n\n/**\n * Maps the output of this channel using the specified function.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapOut: {\n  <OutElem, OutElem2>(\n    f: (o: OutElem) => OutElem2\n  ): <InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem2, InElem, OutErr, InErr, OutDone, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (o: OutElem) => OutElem2\n  ): Channel<OutElem2, InElem, OutErr, InErr, OutDone, InDone, Env>\n} = channel.mapOut\n\n/**\n * Creates a channel that is like this channel but the given effectful function\n * gets applied to each emitted output element.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapOutEffect: {\n  <OutElem, OutElem1, OutErr1, Env1>(\n    f: (o: OutElem) => Effect.Effect<OutElem1, OutErr1, Env1>\n  ): <InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem1, InElem, OutErr1 | OutErr, InErr, OutDone, InDone, Env1 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, OutErr1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (o: OutElem) => Effect.Effect<OutElem1, OutErr1, Env1>\n  ): Channel<OutElem1, InElem, OutErr | OutErr1, InErr, OutDone, InDone, Env | Env1>\n} = channel.mapOutEffect\n\n/**\n * Creates a channel that is like this channel but the given Effect function gets\n * applied to each emitted output element, taking `n` elements at once and\n * mapping them in parallel.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapOutEffectPar: {\n  <OutElem, OutElem1, OutErr1, Env1>(\n    f: (o: OutElem) => Effect.Effect<OutElem1, OutErr1, Env1>,\n    n: number\n  ): <InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem1, InElem, OutErr1 | OutErr, InErr, OutDone, InDone, Env1 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, OutErr1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (o: OutElem) => Effect.Effect<OutElem1, OutErr1, Env1>,\n    n: number\n  ): Channel<OutElem1, InElem, OutErr | OutErr1, InErr, OutDone, InDone, Env | Env1>\n} = channel.mapOutEffectPar\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const mergeAll: (\n  options: {\n    readonly concurrency: number | \"unbounded\"\n    readonly bufferSize?: number | undefined\n    readonly mergeStrategy?: MergeStrategy.MergeStrategy | undefined\n  }\n) => <OutElem, InElem1, OutErr1, InErr1, InDone1, Env1, InElem, OutErr, InErr, InDone, Env>(\n  channels: Channel<\n    Channel<OutElem, InElem1, OutErr1, InErr1, unknown, InDone1, Env1>,\n    InElem,\n    OutErr,\n    InErr,\n    unknown,\n    InDone,\n    Env\n  >\n) => Channel<OutElem, InElem & InElem1, OutErr1 | OutErr, InErr & InErr1, unknown, InDone & InDone1, Env1 | Env> =\n  channel.mergeAll\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const mergeAllUnbounded: <OutElem, InElem1, OutErr1, InErr1, InDone1, Env1, InElem, OutErr, InErr, InDone, Env>(\n  channels: Channel<\n    Channel<OutElem, InElem1, OutErr1, InErr1, unknown, InDone1, Env1>,\n    InElem,\n    OutErr,\n    InErr,\n    unknown,\n    InDone,\n    Env\n  >\n) => Channel<OutElem, InElem & InElem1, OutErr1 | OutErr, InErr & InErr1, unknown, InDone & InDone1, Env1 | Env> =\n  channel.mergeAllUnbounded\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const mergeAllUnboundedWith: <\n  OutElem,\n  InElem1,\n  OutErr1,\n  InErr1,\n  OutDone,\n  InDone1,\n  Env1,\n  InElem,\n  OutErr,\n  InErr,\n  InDone,\n  Env\n>(\n  channels: Channel<\n    Channel<OutElem, InElem1, OutErr1, InErr1, OutDone, InDone1, Env1>,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env\n  >,\n  f: (o1: OutDone, o2: OutDone) => OutDone\n) => Channel<OutElem, InElem & InElem1, OutErr1 | OutErr, InErr & InErr1, OutDone, InDone & InDone1, Env1 | Env> =\n  channel.mergeAllUnboundedWith\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const mergeAllWith: (\n  { bufferSize, concurrency, mergeStrategy }: {\n    readonly concurrency: number | \"unbounded\"\n    readonly bufferSize?: number | undefined\n    readonly mergeStrategy?: MergeStrategy.MergeStrategy | undefined\n  }\n) => <OutElem, InElem1, OutErr1, InErr1, OutDone, InDone1, Env1, InElem, OutErr, InErr, InDone, Env>(\n  channels: Channel<\n    Channel<OutElem, InElem1, OutErr1, InErr1, OutDone, InDone1, Env1>,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env\n  >,\n  f: (o1: OutDone, o2: OutDone) => OutDone\n) => Channel<OutElem, InElem & InElem1, OutErr1 | OutErr, InErr & InErr1, OutDone, InDone & InDone1, Env1 | Env> =\n  channel.mergeAllWith\n\n/**\n * Returns a new channel which creates a new channel for each emitted element\n * and merges some of them together. Different merge strategies control what\n * happens if there are more than the given maximum number of channels gets\n * created. See `Channel.mergeAll`.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mergeMap: {\n  <OutElem, OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>(\n    f: (outElem: OutElem) => Channel<OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>,\n    options: {\n      readonly concurrency: number | \"unbounded\"\n      readonly bufferSize?: number | undefined\n      readonly mergeStrategy?: MergeStrategy.MergeStrategy | undefined\n    }\n  ): <InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem1, InElem & InElem1, OutErr1 | OutErr, InErr & InErr1, unknown, InDone & InDone1, Env1 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (outElem: OutElem) => Channel<OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>,\n    options: {\n      readonly concurrency: number | \"unbounded\"\n      readonly bufferSize?: number | undefined\n      readonly mergeStrategy?: MergeStrategy.MergeStrategy | undefined\n    }\n  ): Channel<OutElem1, InElem & InElem1, OutErr | OutErr1, InErr & InErr1, unknown, InDone & InDone1, Env | Env1>\n} = channel.mergeMap\n\n/**\n * Returns a new channel which merges a number of channels emitted by this\n * channel using the back pressuring merge strategy. See `Channel.mergeAll`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mergeOut: {\n  (\n    n: number\n  ): <OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<\n      Channel<OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>,\n      InElem,\n      OutErr,\n      InErr,\n      OutDone,\n      InDone,\n      Env\n    >\n  ) => Channel<OutElem1, InElem & InElem1, OutErr1 | OutErr, InErr & InErr1, unknown, InDone & InDone1, Env1 | Env>\n  <OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<\n      Channel<OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>,\n      InElem,\n      OutErr,\n      InErr,\n      OutDone,\n      InDone,\n      Env\n    >,\n    n: number\n  ): Channel<OutElem1, InElem & InElem1, OutErr1 | OutErr, InErr & InErr1, unknown, InDone & InDone1, Env1 | Env>\n} = channel.mergeOut\n\n/**\n * Returns a new channel which merges a number of channels emitted by this\n * channel using the back pressuring merge strategy and uses a given function\n * to merge each completed subchannel's result value. See\n * `Channel.mergeAll`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mergeOutWith: {\n  <OutDone1>(\n    n: number,\n    f: (o1: OutDone1, o2: OutDone1) => OutDone1\n  ): <OutElem1, InElem1, OutErr1, InErr1, InDone1, Env1, InElem, OutErr, InErr, InDone, Env>(\n    self: Channel<\n      Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n      InElem,\n      OutErr,\n      InErr,\n      OutDone1,\n      InDone,\n      Env\n    >\n  ) => Channel<OutElem1, InElem & InElem1, OutErr1 | OutErr, InErr & InErr1, OutDone1, InDone & InDone1, Env1 | Env>\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1, InElem, OutErr, InErr, InDone, Env>(\n    self: Channel<\n      Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n      InElem,\n      OutErr,\n      InErr,\n      OutDone1,\n      InDone,\n      Env\n    >,\n    n: number,\n    f: (o1: OutDone1, o2: OutDone1) => OutDone1\n  ): Channel<OutElem1, InElem & InElem1, OutErr1 | OutErr, InErr & InErr1, OutDone1, InDone & InDone1, Env1 | Env>\n} = channel.mergeOutWith\n\n/**\n * Returns a new channel, which is the merge of this channel and the specified\n * channel, where the behavior of the returned channel on left or right early\n * termination is decided by the specified `leftDone` and `rightDone` merge\n * decisions.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mergeWith: {\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1, OutDone, OutErr, OutErr2, OutDone2, OutErr3, OutDone3>(\n    options: {\n      readonly other: Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n      readonly onSelfDone: (\n        exit: Exit.Exit<OutDone, OutErr>\n      ) => MergeDecision.MergeDecision<Env1, OutErr1, OutDone1, OutErr2, OutDone2>\n      readonly onOtherDone: (\n        ex: Exit.Exit<OutDone1, OutErr1>\n      ) => MergeDecision.MergeDecision<Env1, OutErr, OutDone, OutErr3, OutDone3>\n    }\n  ): <Env, InErr, InElem, InDone, OutElem>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr2 | OutErr3,\n    InErr & InErr1,\n    OutDone2 | OutDone3,\n    InDone & InDone1,\n    Env1 | Env\n  >\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env,\n    OutElem1,\n    InElem1,\n    OutErr1,\n    InErr1,\n    OutDone1,\n    InDone1,\n    Env1,\n    OutErr2,\n    OutDone2,\n    OutErr3,\n    OutDone3\n  >(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    options: {\n      readonly other: Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n      readonly onSelfDone: (\n        exit: Exit.Exit<OutDone, OutErr>\n      ) => MergeDecision.MergeDecision<Env1, OutErr1, OutDone1, OutErr2, OutDone2>\n      readonly onOtherDone: (\n        ex: Exit.Exit<OutDone1, OutErr1>\n      ) => MergeDecision.MergeDecision<Env1, OutErr, OutDone, OutErr3, OutDone3>\n    }\n  ): Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr2 | OutErr3,\n    InErr & InErr1,\n    OutDone2 | OutDone3,\n    InDone & InDone1,\n    Env | Env1\n  >\n} = channel.mergeWith\n\n/**\n * Returns a channel that never completes\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const never: Channel<never, unknown, never, unknown, never, unknown> = channel.never\n\n/**\n * Translates channel failure into death of the fiber, making all failures\n * unchecked and not a part of the type of the channel.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orDie: {\n  <E>(\n    error: LazyArg<E>\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, never, InErr, OutDone, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, E>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    error: LazyArg<E>\n  ): Channel<OutElem, InElem, never, InErr, OutDone, InDone, Env>\n} = channel.orDie\n\n/**\n * Keeps none of the errors, and terminates the fiber with them, using the\n * specified function to convert the `OutErr` into a defect.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orDieWith: {\n  <OutErr>(\n    f: (e: OutErr) => unknown\n  ): <OutElem, InElem, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, never, InErr, OutDone, InDone, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (e: OutErr) => unknown\n  ): Channel<OutElem, InElem, never, InErr, OutDone, InDone, Env>\n} = channel.orDieWith\n\n/**\n * Returns a new channel that will perform the operations of this one, until\n * failure, and then it will switch over to the operations of the specified\n * fallback channel.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElse: {\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    that: LazyArg<Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>>\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone1 | OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: LazyArg<Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>>\n  ): Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone | OutDone1,\n    InDone & InDone1,\n    Env | Env1\n  >\n} = channel.orElse\n\n/**\n * Returns a new channel that pipes the output of this channel into the\n * specified channel. The returned channel has the input type of this channel,\n * and the output type of the specified channel, terminating with the value of\n * the specified channel.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const pipeTo: {\n  <OutElem2, OutElem, OutErr2, OutErr, OutDone2, OutDone, Env2>(\n    that: Channel<OutElem2, OutElem, OutErr2, OutErr, OutDone2, OutDone, Env2>\n  ): <InElem, InErr, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem2, InElem, OutErr2, InErr, OutDone2, InDone, Env2 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2, OutErr2, OutDone2, Env2>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel<OutElem2, OutElem, OutErr2, OutErr, OutDone2, OutDone, Env2>\n  ): Channel<OutElem2, InElem, OutErr2, InErr, OutDone2, InDone, Env | Env2>\n} = core.pipeTo\n\n/**\n * Returns a new channel that pipes the output of this channel into the\n * specified channel and preserves this channel's failures without providing\n * them to the other channel for observation.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const pipeToOrFail: {\n  <OutElem2, OutElem, OutErr2, OutDone2, OutDone, Env2>(\n    that: Channel<OutElem2, OutElem, OutErr2, never, OutDone2, OutDone, Env2>\n  ): <InElem, OutErr, InErr, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem2, InElem, OutErr2 | OutErr, InErr, OutDone2, InDone, Env2 | Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2, OutErr2, OutDone2, Env2>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel<OutElem2, OutElem, OutErr2, never, OutDone2, OutDone, Env2>\n  ): Channel<OutElem2, InElem, OutErr | OutErr2, InErr, OutDone2, InDone, Env | Env2>\n} = channel.pipeToOrFail\n\n/**\n * Provides the channel with its required context, which eliminates its\n * dependency on `Env`.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideContext: {\n  <Env>(\n    env: Context.Context<Env>\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, never>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    env: Context.Context<Env>\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, never>\n} = core.provideContext\n\n/**\n * Provides a layer to the channel, which translates it to another level.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideLayer: {\n  <Env, OutErr2, Env0>(\n    layer: Layer.Layer<Env, OutErr2, Env0>\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr2 | OutErr, InErr, OutDone, InDone, Env0>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutErr2, Env0>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    layer: Layer.Layer<Env, OutErr2, Env0>\n  ): Channel<OutElem, InElem, OutErr | OutErr2, InErr, OutDone, InDone, Env0>\n} = channel.provideLayer\n\n/**\n * Transforms the context being provided to the channel with the specified\n * function.\n *\n * @since 2.0.0\n * @category context\n */\nexport const mapInputContext: {\n  <Env0, Env>(\n    f: (env: Context.Context<Env0>) => Context.Context<Env>\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env0>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, Env0>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (env: Context.Context<Env0>) => Context.Context<Env>\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env0>\n} = channel.mapInputContext\n\n/**\n * Splits the context into two parts, providing one part using the\n * specified layer and leaving the remainder `Env0`.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideSomeLayer: {\n  <R2, OutErr2, Env0>(\n    layer: Layer.Layer<R2, OutErr2, Env0>\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, R>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, R>\n  ) => Channel<OutElem, InElem, OutErr2 | OutErr, InErr, OutDone, InDone, Env0 | Exclude<R, R2>>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, R, R2, OutErr2, Env0>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, R>,\n    layer: Layer.Layer<R2, OutErr2, Env0>\n  ): Channel<OutElem, InElem, OutErr | OutErr2, InErr, OutDone, InDone, Env0 | Exclude<R, R2>>\n} = channel.provideSomeLayer\n\n/**\n * Provides the effect with the single service it requires. If the effect\n * requires more than one service use `provideContext` instead.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideService: {\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<Env, I>>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, I, S>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<Env, I>>\n} = channel.provideService\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const read: <In>() => Channel<never, In, Option.Option<never>, unknown, In, unknown> = channel.read\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const readOrFail: <E, In = unknown>(error: E) => Channel<never, In, E, unknown, In, unknown> = core.readOrFail\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const readWith: <\n  InElem,\n  OutElem,\n  OutErr,\n  InErr,\n  OutDone,\n  InDone,\n  Env,\n  OutElem2,\n  OutErr2,\n  OutDone2,\n  Env2,\n  OutElem3,\n  OutErr3,\n  OutDone3,\n  Env3\n>(\n  options: {\n    readonly onInput: (input: InElem) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n    readonly onFailure: (error: InErr) => Channel<OutElem2, InElem, OutErr2, InErr, OutDone2, InDone, Env2>\n    readonly onDone: (done: InDone) => Channel<OutElem3, InElem, OutErr3, InErr, OutDone3, InDone, Env3>\n  }\n) => Channel<\n  OutElem | OutElem2 | OutElem3,\n  InElem,\n  OutErr | OutErr2 | OutErr3,\n  InErr,\n  OutDone | OutDone2 | OutDone3,\n  InDone,\n  Env | Env2 | Env3\n> = core.readWith\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const readWithCause: <\n  InElem,\n  OutElem,\n  OutErr,\n  InErr,\n  OutDone,\n  InDone,\n  Env,\n  OutElem2,\n  OutErr2,\n  OutDone2,\n  Env2,\n  OutElem3,\n  OutErr3,\n  OutDone3,\n  Env3\n>(\n  options: {\n    readonly onInput: (input: InElem) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n    readonly onFailure: (cause: Cause.Cause<InErr>) => Channel<OutElem2, InElem, OutErr2, InErr, OutDone2, InDone, Env2>\n    readonly onDone: (done: InDone) => Channel<OutElem3, InElem, OutErr3, InErr, OutDone3, InDone, Env3>\n  }\n) => Channel<\n  OutElem | OutElem2 | OutElem3,\n  InElem,\n  OutErr | OutErr2 | OutErr3,\n  InErr,\n  OutDone | OutDone2 | OutDone3,\n  InDone,\n  Env | Env2 | Env3\n> = core.readWithCause\n\n/**\n * Creates a channel which repeatedly runs this channel.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const repeated: <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env> = channel.repeated\n\n/**\n * Runs a channel until the end is received.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const run: <OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel<never, unknown, OutErr, InErr, OutDone, InDone, Env>\n) => Effect.Effect<OutDone, OutErr, Env> = channel.run\n\n/**\n * Run the channel until it finishes with a done value or fails with an error\n * and collects its emitted output elements.\n *\n * The channel must not read any input.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runCollect: <OutElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, Env>\n) => Effect.Effect<[Chunk.Chunk<OutElem>, OutDone], OutErr, Env> = channel.runCollect\n\n/**\n * Runs a channel until the end is received.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runDrain: <OutElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, Env>\n) => Effect.Effect<OutDone, OutErr, Env> = channel.runDrain\n\n/**\n * Run the channel until it finishes with a done value or fails with an error.\n * The channel must not read any input or write any output.\n *\n * Closing the channel, which includes execution of all the finalizers\n * attached to the channel will be added to the current scope as a finalizer.\n *\n * @since 3.11.0\n * @category destructors\n */\nexport const runScoped: <OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel<never, unknown, OutErr, InErr, OutDone, InDone, Env>\n) => Effect.Effect<OutDone, OutErr, Env | Scope.Scope> = channel.runScoped\n\n/**\n * Use a scoped effect to emit an output element.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const scoped: <A, E, R>(\n  effect: Effect.Effect<A, E, R>\n) => Channel<A, unknown, E, unknown, unknown, unknown, Exclude<R, Scope.Scope>> = channel.scoped\n\n/**\n * Use a function that receives a scope and returns an effect to emit an output\n * element. The output element will be the result of the returned effect, if\n * successful.\n *\n * @since 3.11.0\n * @category constructors\n */\nexport const scopedWith: <A, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<A, E, R>\n) => Channel<A, unknown, E, unknown, unknown, unknown, R> = channel.scopedWith\n\n/**\n * Splits strings on newlines. Handles both Windows newlines (`\\r\\n`) and UNIX\n * newlines (`\\n`).\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const splitLines: <Err, Done>() => Channel<\n  Chunk.Chunk<string>,\n  Chunk.Chunk<string>,\n  Err,\n  Err,\n  Done,\n  Done,\n  never\n> = channel.splitLines\n\n/**\n * Constructs a channel that succeeds immediately with the specified value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeed: <A>(value: A) => Channel<never, unknown, never, unknown, A, unknown> = core.succeed\n\n/**\n * Lazily constructs a channel from the given side effect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const suspend: <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  evaluate: LazyArg<Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>>\n) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env> = core.suspend\n\n/**\n * Constructs a channel that succeeds immediately with the specified lazy value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sync: <OutDone>(\n  evaluate: LazyArg<OutDone>\n) => Channel<never, unknown, never, unknown, OutDone, unknown> = core.sync\n\n/**\n * Converts a `Channel` to a `PubSub`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toPubSub: <Done, Err, Elem>(\n  pubsub: PubSub.PubSub<Either.Either<Elem, Exit.Exit<Done, Err>>>\n) => Channel<never, Elem, never, Err, unknown, Done> = channel.toPubSub\n\n/**\n * Returns a scoped `Effect` that can be used to repeatedly pull elements from\n * the constructed `Channel`. The pull effect fails with the channel's failure\n * in case the channel fails, or returns either the channel's done value or an\n * emitted element.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toPull: <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n) => Effect.Effect<Effect.Effect<Either.Either<OutElem, OutDone>, OutErr, Env>, never, Scope.Scope | Env> =\n  channel.toPull\n\n/**\n * Returns an `Effect` that can be used to repeatedly pull elements from the\n * constructed `Channel` within the provided `Scope`. The pull effect fails\n * with the channel's failure in case the channel fails, or returns either the\n * channel's done value or an emitted element.\n *\n * @since 3.11.0\n * @category destructors\n */\nexport const toPullIn: {\n  (\n    scope: Scope.Scope\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Effect.Effect<Effect.Effect<Either.Either<OutElem, OutDone>, OutErr, Env>, never, Env>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    scope: Scope.Scope\n  ): Effect.Effect<Effect.Effect<Either.Either<OutElem, OutDone>, OutErr, Env>, never, Env>\n} = channel.toPullIn\n\n/**\n * Converts a `Channel` to a `Queue`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toQueue: <Done, Err, Elem>(\n  queue: Queue.Enqueue<Either.Either<Elem, Exit.Exit<Done, Err>>>\n) => Channel<never, Elem, never, Err, unknown, Done> = channel.toQueue\n\n/** Converts this channel to a `Sink`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toSink: <OutElem, InElem, OutErr, InErr, OutDone, Env>(\n  self: Channel<Chunk.Chunk<OutElem>, Chunk.Chunk<InElem>, OutErr, InErr, OutDone, unknown, Env>\n) => Sink.Sink<OutDone, InElem, OutElem, OutErr, Env> = sink.channelToSink\n\n/**\n * Converts this channel to a `Stream`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toStream: <OutElem, OutErr, OutDone, Env>(\n  self: Channel<Chunk.Chunk<OutElem>, unknown, OutErr, unknown, OutDone, unknown, Env>\n) => Stream.Stream<OutElem, OutErr, Env> = stream.channelToStream\n\nconst void_: Channel<never> = core.void\nexport {\n  /**\n   * @since 2.0.0\n   * @category constructors\n   */\n  void_ as void\n}\n\n/**\n * Constructs a `Channel` from an effect that will result in a `Channel` if\n * successful.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unwrap: <OutElem, InElem, OutErr, InErr, OutDone, InDone, R2, E, R>(\n  channel: Effect.Effect<Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, R2>, E, R>\n) => Channel<OutElem, InElem, E | OutErr, InErr, OutDone, InDone, R | R2> = channel.unwrap\n\n/**\n * Constructs a `Channel` from a scoped effect that will result in a\n * `Channel` if successful.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unwrapScoped: <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, E, R>(\n  self: Effect.Effect<Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>, E, R>\n) => Channel<OutElem, InElem, E | OutErr, InErr, OutDone, InDone, Env | Exclude<R, Scope.Scope>> = channel.unwrapScoped\n\n/**\n * Constructs a `Channel` from a function which receives a `Scope` and returns\n * an effect that will result in a `Channel` if successful.\n *\n * @since 3.11.0\n * @category constructors\n */\nexport const unwrapScopedWith: <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>, E, R>\n) => Channel<OutElem, InElem, E | OutErr, InErr, OutDone, InDone, R | Env> = channel.unwrapScopedWith\n\n/**\n * Updates a service in the context of this channel.\n *\n * @since 2.0.0\n * @category context\n */\nexport const updateService: {\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    f: (resource: Types.NoInfer<S>) => Types.NoInfer<S>\n  ): <OutElem, OutErr, InErr, OutDone, InDone, R>(\n    self: Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, R>\n  ) => Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, I | R>\n  <OutElem, OutErr, InErr, OutDone, InDone, R, I, S>(\n    self: Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, R>,\n    tag: Context.Tag<I, S>,\n    f: (resource: Types.NoInfer<S>) => Types.NoInfer<S>\n  ): Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, I | R>\n} = channel.updateService\n\n/**\n * Wraps the channel with a new span for tracing.\n *\n * @since 2.0.0\n * @category tracing\n */\nexport const withSpan: {\n  (\n    name: string,\n    options?: Tracer.SpanOptions | undefined\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<Env, Tracer.ParentSpan>>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    name: string,\n    options?: Tracer.SpanOptions | undefined\n  ): Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<Env, Tracer.ParentSpan>>\n} = channel.withSpan\n\n/**\n * Writes a single value to the channel.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const write: <OutElem>(out: OutElem) => Channel<OutElem> = core.write\n\n/**\n * Writes a sequence of values to the channel.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const writeAll: <OutElems extends Array<any>>(\n  ...outs: OutElems\n) => Channel<OutElems[number]> = channel.writeAll\n\n/**\n * Writes a `Chunk` of values to the channel.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const writeChunk: <OutElem>(\n  outs: Chunk.Chunk<OutElem>\n) => Channel<OutElem> = channel.writeChunk\n\n/**\n * Returns a new channel that is the sequential composition of this channel\n * and the specified channel. The returned channel terminates with a tuple of\n * the terminal values of both channels.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zip: {\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    that: Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    readonly [OutDone, OutDone1],\n    InDone & InDone1,\n    Env1 | Env\n  >\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    readonly [OutDone, OutDone1],\n    InDone & InDone1,\n    Env | Env1\n  >\n} = channel.zip\n\n/**\n * Returns a new channel that is the sequential composition of this channel\n * and the specified channel. The returned channel terminates with the\n * terminal value of this channel.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipLeft: {\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    that: Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    OutDone,\n    InDone & InDone1,\n    Env | Env1\n  >\n} = channel.zipLeft\n\n/**\n * Returns a new channel that is the sequential composition of this channel\n * and the specified channel. The returned channel terminates with the\n * terminal value of that channel.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipRight: {\n  <Env1, InErr1, InElem1, InDone1, OutErr1, OutElem1, OutDone1>(\n    that: Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ): <Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    OutDone1,\n    InDone & InDone1,\n    Env1 | Env\n  >\n  <Env, InErr, InElem, InDone, OutErr, OutElem, OutDone, Env1, InErr1, InElem1, InDone1, OutErr1, OutElem1, OutDone1>(\n    self: Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ): Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    OutDone1,\n    InDone & InDone1,\n    Env | Env1\n  >\n} = channel.zipRight\n\n/**\n * Represents a generic checked exception which occurs when a `Channel` is\n * executed.\n *\n * @since 2.0.0\n * @category errors\n */\nexport const ChannelException: <E>(error: E) => ChannelException<E> = channel.ChannelException\n\n/**\n * Returns `true` if the specified value is an `ChannelException`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isChannelException: (u: unknown) => u is ChannelException<unknown> = channel.isChannelException\n"
  },
  {
    "path": "packages/effect/src/ChildExecutorDecision.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/channel/childExecutorDecision.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ChildExecutorDecisionTypeId: unique symbol = internal.ChildExecutorDecisionTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ChildExecutorDecisionTypeId = typeof ChildExecutorDecisionTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type ChildExecutorDecision = Continue | Close | Yield\n\n/**\n * @since 2.0.0\n */\nexport declare namespace ChildExecutorDecision {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Proto {\n    readonly [ChildExecutorDecisionTypeId]: ChildExecutorDecisionTypeId\n  }\n}\n\n/**\n * Continue executing the current substream\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Continue extends ChildExecutorDecision.Proto {\n  readonly _tag: \"Continue\"\n}\n\n/**\n * Close the current substream with a given value and pass execution to the\n * next substream\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Close extends ChildExecutorDecision.Proto {\n  readonly _tag: \"Close\"\n  readonly value: unknown\n}\n\n/**\n * Pass execution to the next substream. This either pulls a new element\n * from upstream, or yields to an already created active substream.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Yield extends ChildExecutorDecision.Proto {\n  readonly _tag: \"Yield\"\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Continue: (_: void) => ChildExecutorDecision = internal.Continue\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Close: (value: unknown) => ChildExecutorDecision = internal.Close\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Yield: (_: void) => ChildExecutorDecision = internal.Yield\n\n/**\n * Returns `true` if the specified value is a `ChildExecutorDecision`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isChildExecutorDecision: (u: unknown) => u is ChildExecutorDecision = internal.isChildExecutorDecision\n\n/**\n * Returns `true` if the specified `ChildExecutorDecision` is a `Continue`,\n * `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isContinue: (self: ChildExecutorDecision) => self is Continue = internal.isContinue\n\n/**\n * Returns `true` if the specified `ChildExecutorDecision` is a `Close`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isClose: (self: ChildExecutorDecision) => self is Close = internal.isClose\n\n/**\n * Returns `true` if the specified `ChildExecutorDecision` is a `Yield`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isYield: (self: ChildExecutorDecision) => self is Yield = internal.isYield\n\n/**\n * Folds over a `ChildExecutorDecision` to produce a value of type `A`.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <A>(\n    options: {\n      readonly onContinue: () => A\n      readonly onClose: (value: unknown) => A\n      readonly onYield: () => A\n    }\n  ): (self: ChildExecutorDecision) => A\n  <A>(\n    self: ChildExecutorDecision,\n    options: {\n      readonly onContinue: () => A\n      readonly onClose: (value: unknown) => A\n      readonly onYield: () => A\n    }\n  ): A\n} = internal.match\n"
  },
  {
    "path": "packages/effect/src/Chunk.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as RA from \"./Array.js\"\nimport type { NonEmptyReadonlyArray } from \"./Array.js\"\nimport type { Either } from \"./Either.js\"\nimport * as Equal from \"./Equal.js\"\nimport * as Equivalence from \"./Equivalence.js\"\nimport { dual, identity, pipe } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport { format, type Inspectable, NodeInspectSymbol, toJSON } from \"./Inspectable.js\"\nimport type { NonEmptyIterable } from \"./NonEmptyIterable.js\"\nimport type { Option } from \"./Option.js\"\nimport * as O from \"./Option.js\"\nimport * as Order from \"./Order.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\nimport { hasProperty, type Predicate, type Refinement } from \"./Predicate.js\"\nimport type { Covariant, NoInfer } from \"./Types.js\"\n\nconst TypeId: unique symbol = Symbol.for(\"effect/Chunk\") as TypeId\n\n/**\n * @category symbol\n * @since 2.0.0\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface Chunk<out A> extends Iterable<A>, Equal.Equal, Pipeable, Inspectable {\n  readonly [TypeId]: {\n    readonly _A: Covariant<A>\n  }\n  readonly length: number\n  /** @internal */\n  right: Chunk<A>\n  /** @internal */\n  left: Chunk<A>\n  /** @internal */\n  backing: Backing<A>\n  /** @internal */\n  depth: number\n}\n\n/**\n * @category model\n * @since 2.0.0\n */\nexport interface NonEmptyChunk<out A> extends Chunk<A>, NonEmptyIterable<A> {}\n\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface ChunkTypeLambda extends TypeLambda {\n  readonly type: Chunk<this[\"Target\"]>\n}\n\ntype Backing<A> =\n  | IArray<A>\n  | IConcat<A>\n  | ISingleton<A>\n  | IEmpty\n  | ISlice<A>\n\ninterface IArray<A> {\n  readonly _tag: \"IArray\"\n  readonly array: ReadonlyArray<A>\n}\n\ninterface IConcat<A> {\n  readonly _tag: \"IConcat\"\n  readonly left: Chunk<A>\n  readonly right: Chunk<A>\n}\n\ninterface ISingleton<A> {\n  readonly _tag: \"ISingleton\"\n  readonly a: A\n}\n\ninterface IEmpty {\n  readonly _tag: \"IEmpty\"\n}\n\ninterface ISlice<A> {\n  readonly _tag: \"ISlice\"\n  readonly chunk: Chunk<A>\n  readonly offset: number\n  readonly length: number\n}\n\nfunction copy<A>(\n  src: ReadonlyArray<A>,\n  srcPos: number,\n  dest: Array<A>,\n  destPos: number,\n  len: number\n) {\n  for (let i = srcPos; i < Math.min(src.length, srcPos + len); i++) {\n    dest[destPos + i - srcPos] = src[i]!\n  }\n  return dest\n}\n\nconst emptyArray: ReadonlyArray<never> = []\n\n/**\n * Compares the two chunks of equal length using the specified function\n *\n * @category equivalence\n * @since 2.0.0\n */\nexport const getEquivalence = <A>(isEquivalent: Equivalence.Equivalence<A>): Equivalence.Equivalence<Chunk<A>> =>\n  Equivalence.make((self, that) =>\n    self.length === that.length && toReadonlyArray(self).every((value, i) => isEquivalent(value, unsafeGet(that, i)))\n  )\n\nconst _equivalence = getEquivalence(Equal.equals)\n\nconst ChunkProto: Omit<Chunk<unknown>, \"backing\" | \"depth\" | \"left\" | \"length\" | \"right\"> = {\n  [TypeId]: {\n    _A: (_: never) => _\n  },\n  toString<A>(this: Chunk<A>) {\n    return format(this.toJSON())\n  },\n  toJSON<A>(this: Chunk<A>) {\n    return {\n      _id: \"Chunk\",\n      values: toReadonlyArray(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]<A>(this: Chunk<A>) {\n    return this.toJSON()\n  },\n  [Equal.symbol]<A>(this: Chunk<A>, that: unknown): boolean {\n    return isChunk(that) && _equivalence(this, that)\n  },\n  [Hash.symbol]<A>(this: Chunk<A>): number {\n    return Hash.cached(this, Hash.array(toReadonlyArray(this)))\n  },\n  [Symbol.iterator]<A>(this: Chunk<A>): Iterator<A> {\n    switch (this.backing._tag) {\n      case \"IArray\": {\n        return this.backing.array[Symbol.iterator]()\n      }\n      case \"IEmpty\": {\n        return emptyArray[Symbol.iterator]()\n      }\n      default: {\n        return toReadonlyArray(this)[Symbol.iterator]()\n      }\n    }\n  },\n  pipe<A>(this: Chunk<A>) {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makeChunk = <A>(backing: Backing<A>): Chunk<A> => {\n  const chunk = Object.create(ChunkProto)\n  chunk.backing = backing\n  switch (backing._tag) {\n    case \"IEmpty\": {\n      chunk.length = 0\n      chunk.depth = 0\n      chunk.left = chunk\n      chunk.right = chunk\n      break\n    }\n    case \"IConcat\": {\n      chunk.length = backing.left.length + backing.right.length\n      chunk.depth = 1 + Math.max(backing.left.depth, backing.right.depth)\n      chunk.left = backing.left\n      chunk.right = backing.right\n      break\n    }\n    case \"IArray\": {\n      chunk.length = backing.array.length\n      chunk.depth = 0\n      chunk.left = _empty\n      chunk.right = _empty\n      break\n    }\n    case \"ISingleton\": {\n      chunk.length = 1\n      chunk.depth = 0\n      chunk.left = _empty\n      chunk.right = _empty\n      break\n    }\n    case \"ISlice\": {\n      chunk.length = backing.length\n      chunk.depth = backing.chunk.depth + 1\n      chunk.left = _empty\n      chunk.right = _empty\n      break\n    }\n  }\n  return chunk\n}\n\n/**\n * Checks if `u` is a `Chunk<unknown>`\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const isChunk: {\n  <A>(u: Iterable<A>): u is Chunk<A>\n  (u: unknown): u is Chunk<unknown>\n} = (u: unknown): u is Chunk<unknown> => hasProperty(u, TypeId)\n\nconst _empty = makeChunk<never>({ _tag: \"IEmpty\" })\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport const empty: <A = never>() => Chunk<A> = () => _empty\n\n/**\n * Builds a `NonEmptyChunk` from an non-empty collection of elements.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = <As extends readonly [any, ...ReadonlyArray<any>]>(...as: As): NonEmptyChunk<As[number]> =>\n  unsafeFromNonEmptyArray(as)\n\n/**\n * Builds a `NonEmptyChunk` from a single element.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const of = <A>(a: A): NonEmptyChunk<A> => makeChunk({ _tag: \"ISingleton\", a }) as any\n\n/**\n * Creates a new `Chunk` from an iterable collection of values.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterable = <A>(self: Iterable<A>): Chunk<A> =>\n  isChunk(self) ? self : unsafeFromArray(RA.fromIterable(self))\n\nconst copyToArray = <A>(self: Chunk<A>, array: Array<any>, initial: number): void => {\n  switch (self.backing._tag) {\n    case \"IArray\": {\n      copy(self.backing.array, 0, array, initial, self.length)\n      break\n    }\n    case \"IConcat\": {\n      copyToArray(self.left, array, initial)\n      copyToArray(self.right, array, initial + self.left.length)\n      break\n    }\n    case \"ISingleton\": {\n      array[initial] = self.backing.a\n      break\n    }\n    case \"ISlice\": {\n      let i = 0\n      let j = initial\n      while (i < self.length) {\n        array[j] = unsafeGet(self, i)\n        i += 1\n        j += 1\n      }\n      break\n    }\n  }\n}\n\nconst toArray_ = <A>(self: Chunk<A>): Array<A> => toReadonlyArray(self).slice()\n\n/**\n * Converts a `Chunk` into an `Array`. If the provided `Chunk` is non-empty\n * (`NonEmptyChunk`), the function will return a `NonEmptyArray`, ensuring the\n * non-empty property is preserved.\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const toArray: <S extends Chunk<any>>(\n  self: S\n) => S extends NonEmptyChunk<any> ? RA.NonEmptyArray<Chunk.Infer<S>> : Array<Chunk.Infer<S>> = toArray_ as any\n\nconst toReadonlyArray_ = <A>(self: Chunk<A>): ReadonlyArray<A> => {\n  switch (self.backing._tag) {\n    case \"IEmpty\": {\n      return emptyArray\n    }\n    case \"IArray\": {\n      return self.backing.array\n    }\n    default: {\n      const arr = new Array<A>(self.length)\n      copyToArray(self, arr, 0)\n      self.backing = {\n        _tag: \"IArray\",\n        array: arr\n      }\n      self.left = _empty\n      self.right = _empty\n      self.depth = 0\n      return arr\n    }\n  }\n}\n\n/**\n * Converts a `Chunk` into a `ReadonlyArray`. If the provided `Chunk` is\n * non-empty (`NonEmptyChunk`), the function will return a\n * `NonEmptyReadonlyArray`, ensuring the non-empty property is preserved.\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const toReadonlyArray: <S extends Chunk<any>>(\n  self: S\n) => S extends NonEmptyChunk<any> ? RA.NonEmptyReadonlyArray<Chunk.Infer<S>> : ReadonlyArray<Chunk.Infer<S>> =\n  toReadonlyArray_ as any\n\nconst reverseChunk = <A>(self: Chunk<A>): Chunk<A> => {\n  switch (self.backing._tag) {\n    case \"IEmpty\":\n    case \"ISingleton\":\n      return self\n    case \"IArray\": {\n      return makeChunk({ _tag: \"IArray\", array: RA.reverse(self.backing.array) })\n    }\n    case \"IConcat\": {\n      return makeChunk({ _tag: \"IConcat\", left: reverse(self.backing.right), right: reverse(self.backing.left) })\n    }\n    case \"ISlice\":\n      return unsafeFromArray(RA.reverse(toReadonlyArray(self)))\n  }\n}\n\n/**\n * Reverses the order of elements in a `Chunk`.\n * Importantly, if the input chunk is a `NonEmptyChunk`, the reversed chunk will also be a `NonEmptyChunk`.\n *\n * **Example**\n *\n * ```ts\n * import { Chunk } from \"effect\"\n *\n * const chunk = Chunk.make(1, 2, 3)\n * const result = Chunk.reverse(chunk)\n *\n * console.log(result)\n * // { _id: 'Chunk', values: [ 3, 2, 1 ] }\n * ```\n *\n * @since 2.0.0\n * @category elements\n */\nexport const reverse: <S extends Chunk<any>>(self: S) => Chunk.With<S, Chunk.Infer<S>> = reverseChunk as any\n\n/**\n * This function provides a safe way to read a value at a particular index from a `Chunk`.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const get: {\n  (index: number): <A>(self: Chunk<A>) => Option<A>\n  <A>(self: Chunk<A>, index: number): Option<A>\n} = dual(\n  2,\n  <A>(self: Chunk<A>, index: number): Option<A> =>\n    index < 0 || index >= self.length ? O.none() : O.some(unsafeGet(self, index))\n)\n\n/**\n * Wraps an array into a chunk without copying, unsafe on mutable arrays\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeFromArray = <A>(self: ReadonlyArray<A>): Chunk<A> =>\n  self.length === 0 ? empty() : self.length === 1 ? of(self[0]) : makeChunk({ _tag: \"IArray\", array: self })\n\n/**\n * Wraps an array into a chunk without copying, unsafe on mutable arrays\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeFromNonEmptyArray = <A>(self: NonEmptyReadonlyArray<A>): NonEmptyChunk<A> =>\n  unsafeFromArray(self) as any\n\n/**\n * Gets an element unsafely, will throw on out of bounds\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeGet: {\n  (index: number): <A>(self: Chunk<A>) => A\n  <A>(self: Chunk<A>, index: number): A\n} = dual(2, <A>(self: Chunk<A>, index: number): A => {\n  switch (self.backing._tag) {\n    case \"IEmpty\": {\n      throw new Error(`Index out of bounds`)\n    }\n    case \"ISingleton\": {\n      if (index !== 0) {\n        throw new Error(`Index out of bounds`)\n      }\n      return self.backing.a\n    }\n    case \"IArray\": {\n      if (index >= self.length || index < 0) {\n        throw new Error(`Index out of bounds`)\n      }\n      return self.backing.array[index]!\n    }\n    case \"IConcat\": {\n      return index < self.left.length\n        ? unsafeGet(self.left, index)\n        : unsafeGet(self.right, index - self.left.length)\n    }\n    case \"ISlice\": {\n      return unsafeGet(self.backing.chunk, index + self.backing.offset)\n    }\n  }\n})\n\n/**\n * Appends the specified element to the end of the `Chunk`.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const append: {\n  <A2>(a: A2): <A>(self: Chunk<A>) => NonEmptyChunk<A2 | A>\n  <A, A2>(self: Chunk<A>, a: A2): NonEmptyChunk<A | A2>\n} = dual(2, <A, A2>(self: Chunk<A>, a: A2): NonEmptyChunk<A | A2> => appendAll(self, of(a)))\n\n/**\n * Prepend an element to the front of a `Chunk`, creating a new `NonEmptyChunk`.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const prepend: {\n  <B>(elem: B): <A>(self: Chunk<A>) => NonEmptyChunk<B | A>\n  <A, B>(self: Chunk<A>, elem: B): NonEmptyChunk<A | B>\n} = dual(2, <A, B>(self: Chunk<A>, elem: B): NonEmptyChunk<A | B> => appendAll(of(elem), self))\n\n/**\n * Takes the first up to `n` elements from the chunk\n *\n * @since 2.0.0\n */\nexport const take: {\n  (n: number): <A>(self: Chunk<A>) => Chunk<A>\n  <A>(self: Chunk<A>, n: number): Chunk<A>\n} = dual(2, <A>(self: Chunk<A>, n: number): Chunk<A> => {\n  if (n <= 0) {\n    return _empty\n  } else if (n >= self.length) {\n    return self\n  } else {\n    switch (self.backing._tag) {\n      case \"ISlice\": {\n        return makeChunk({\n          _tag: \"ISlice\",\n          chunk: self.backing.chunk,\n          length: n,\n          offset: self.backing.offset\n        })\n      }\n      case \"IConcat\": {\n        if (n > self.left.length) {\n          return makeChunk({\n            _tag: \"IConcat\",\n            left: self.left,\n            right: take(self.right, n - self.left.length)\n          })\n        }\n\n        return take(self.left, n)\n      }\n      default: {\n        return makeChunk({\n          _tag: \"ISlice\",\n          chunk: self,\n          offset: 0,\n          length: n\n        })\n      }\n    }\n  }\n})\n\n/**\n * Drops the first up to `n` elements from the chunk\n *\n * @since 2.0.0\n */\nexport const drop: {\n  (n: number): <A>(self: Chunk<A>) => Chunk<A>\n  <A>(self: Chunk<A>, n: number): Chunk<A>\n} = dual(2, <A>(self: Chunk<A>, n: number): Chunk<A> => {\n  if (n <= 0) {\n    return self\n  } else if (n >= self.length) {\n    return _empty\n  } else {\n    switch (self.backing._tag) {\n      case \"ISlice\": {\n        return makeChunk({\n          _tag: \"ISlice\",\n          chunk: self.backing.chunk,\n          offset: self.backing.offset + n,\n          length: self.backing.length - n\n        })\n      }\n      case \"IConcat\": {\n        if (n > self.left.length) {\n          return drop(self.right, n - self.left.length)\n        }\n        return makeChunk({\n          _tag: \"IConcat\",\n          left: drop(self.left, n),\n          right: self.right\n        })\n      }\n      default: {\n        return makeChunk({\n          _tag: \"ISlice\",\n          chunk: self,\n          offset: n,\n          length: self.length - n\n        })\n      }\n    }\n  }\n})\n\n/**\n * Drops the last `n` elements.\n *\n * @since 2.0.0\n */\nexport const dropRight: {\n  (n: number): <A>(self: Chunk<A>) => Chunk<A>\n  <A>(self: Chunk<A>, n: number): Chunk<A>\n} = dual(2, <A>(self: Chunk<A>, n: number): Chunk<A> => take(self, Math.max(0, self.length - n)))\n\n/**\n * Drops all elements so long as the predicate returns true.\n *\n * @since 2.0.0\n */\nexport const dropWhile: {\n  <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => Chunk<A>\n  <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A>\n} = dual(2, <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A> => {\n  const arr = toReadonlyArray(self)\n  const len = arr.length\n  let i = 0\n  while (i < len && predicate(arr[i]!)) {\n    i++\n  }\n  return drop(self, i)\n})\n\n/**\n * Prepends the specified prefix chunk to the beginning of the specified chunk.\n * If either chunk is non-empty, the result is also a non-empty chunk.\n *\n * **Example**\n *\n * ```ts\n * import { Chunk } from \"effect\"\n *\n * const result = Chunk.make(1, 2).pipe(Chunk.prependAll(Chunk.make(\"a\", \"b\")), Chunk.toArray)\n *\n * console.log(result)\n * // [ \"a\", \"b\", 1, 2 ]\n * ```\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const prependAll: {\n  <S extends Chunk<any>, T extends Chunk<any>>(\n    that: T\n  ): (self: S) => Chunk.OrNonEmpty<S, T, Chunk.Infer<S> | Chunk.Infer<T>>\n  <A, B>(self: Chunk<A>, that: NonEmptyChunk<B>): NonEmptyChunk<A | B>\n  <A, B>(self: NonEmptyChunk<A>, that: Chunk<B>): NonEmptyChunk<A | B>\n  <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A | B>\n} = dual(2, <A, B>(self: NonEmptyChunk<A>, that: Chunk<B>): Chunk<A | B> => appendAll(that, self))\n\n/**\n * Concatenates two chunks, combining their elements.\n * If either chunk is non-empty, the result is also a non-empty chunk.\n *\n * **Example**\n *\n * ```ts\n * import { Chunk } from \"effect\"\n *\n * const result = Chunk.make(1, 2).pipe(Chunk.appendAll(Chunk.make(\"a\", \"b\")), Chunk.toArray)\n *\n * console.log(result)\n * // [ 1, 2, \"a\", \"b\" ]\n * ```\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const appendAll: {\n  <S extends Chunk<any>, T extends Chunk<any>>(\n    that: T\n  ): (self: S) => Chunk.OrNonEmpty<S, T, Chunk.Infer<S> | Chunk.Infer<T>>\n  <A, B>(self: Chunk<A>, that: NonEmptyChunk<B>): NonEmptyChunk<A | B>\n  <A, B>(self: NonEmptyChunk<A>, that: Chunk<B>): NonEmptyChunk<A | B>\n  <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A | B>\n} = dual(2, <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A | B> => {\n  if (self.backing._tag === \"IEmpty\") {\n    return that\n  }\n  if (that.backing._tag === \"IEmpty\") {\n    return self\n  }\n  const diff = that.depth - self.depth\n  if (Math.abs(diff) <= 1) {\n    return makeChunk<A | B>({ _tag: \"IConcat\", left: self, right: that })\n  } else if (diff < -1) {\n    if (self.left.depth >= self.right.depth) {\n      const nr = appendAll(self.right, that)\n      return makeChunk({ _tag: \"IConcat\", left: self.left, right: nr })\n    } else {\n      const nrr = appendAll(self.right.right, that)\n      if (nrr.depth === self.depth - 3) {\n        const nr = makeChunk({ _tag: \"IConcat\", left: self.right.left, right: nrr })\n        return makeChunk({ _tag: \"IConcat\", left: self.left, right: nr })\n      } else {\n        const nl = makeChunk({ _tag: \"IConcat\", left: self.left, right: self.right.left })\n        return makeChunk({ _tag: \"IConcat\", left: nl, right: nrr })\n      }\n    }\n  } else {\n    if (that.right.depth >= that.left.depth) {\n      const nl = appendAll(self, that.left)\n      return makeChunk({ _tag: \"IConcat\", left: nl, right: that.right })\n    } else {\n      const nll = appendAll(self, that.left.left)\n      if (nll.depth === that.depth - 3) {\n        const nl = makeChunk({ _tag: \"IConcat\", left: nll, right: that.left.right })\n        return makeChunk({ _tag: \"IConcat\", left: nl, right: that.right })\n      } else {\n        const nr = makeChunk({ _tag: \"IConcat\", left: that.left.right, right: that.right })\n        return makeChunk({ _tag: \"IConcat\", left: nll, right: nr })\n      }\n    }\n  }\n})\n\n/**\n * Returns a filtered and mapped subset of the elements.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterMap: {\n  <A, B>(f: (a: A, i: number) => Option<B>): (self: Chunk<A>) => Chunk<B>\n  <A, B>(self: Chunk<A>, f: (a: A, i: number) => Option<B>): Chunk<B>\n} = dual(\n  2,\n  <A, B>(self: Chunk<A>, f: (a: A, i: number) => Option<B>): Chunk<B> => unsafeFromArray(RA.filterMap(self, f))\n)\n\n/**\n * Returns a filtered and mapped subset of the elements.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filter: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Chunk<A>) => Chunk<B>\n  <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => Chunk<A>\n  <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): Chunk<B>\n  <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A>\n} = dual(\n  2,\n  <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A> => unsafeFromArray(RA.filter(self, predicate))\n)\n\n/**\n * Transforms all elements of the chunk for as long as the specified function returns some value\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterMapWhile: {\n  <A, B>(f: (a: A) => Option<B>): (self: Chunk<A>) => Chunk<B>\n  <A, B>(self: Chunk<A>, f: (a: A) => Option<B>): Chunk<B>\n} = dual(2, <A, B>(self: Chunk<A>, f: (a: A) => Option<B>) => unsafeFromArray(RA.filterMapWhile(self, f)))\n\n/**\n * Filter out optional values\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const compact = <A>(self: Chunk<Option<A>>): Chunk<A> => filterMap(self, identity)\n\n/**\n * Applies a function to each element in a chunk and returns a new chunk containing the concatenated mapped elements.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMap: {\n  <S extends Chunk<any>, T extends Chunk<any>>(\n    f: (a: Chunk.Infer<S>, i: number) => T\n  ): (self: S) => Chunk.AndNonEmpty<S, T, Chunk.Infer<T>>\n  <A, B>(self: NonEmptyChunk<A>, f: (a: A, i: number) => NonEmptyChunk<B>): NonEmptyChunk<B>\n  <A, B>(self: Chunk<A>, f: (a: A, i: number) => Chunk<B>): Chunk<B>\n} = dual(2, <A, B>(self: Chunk<A>, f: (a: A, i: number) => Chunk<B>) => {\n  if (self.backing._tag === \"ISingleton\") {\n    return f(self.backing.a, 0)\n  }\n  let out: Chunk<B> = _empty\n  let i = 0\n  for (const k of self) {\n    out = appendAll(out, f(k, i++))\n  }\n  return out\n})\n\n/**\n * Iterates over each element of a `Chunk` and applies a function to it.\n *\n * **Details**\n *\n * This function processes every element of the given `Chunk`, calling the\n * provided function `f` on each element. It does not return a new value;\n * instead, it is primarily used for side effects, such as logging or\n * accumulating data in an external variable.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const forEach: {\n  <A, B>(f: (a: A, index: number) => B): (self: Chunk<A>) => void\n  <A, B>(self: Chunk<A>, f: (a: A, index: number) => B): void\n} = dual(2, <A, B>(self: Chunk<A>, f: (a: A) => B): void => toReadonlyArray(self).forEach(f))\n\n/**\n * Flattens a chunk of chunks into a single chunk by concatenating all chunks.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatten: <S extends Chunk<Chunk<any>>>(self: S) => Chunk.Flatten<S> = flatMap(identity) as any\n\n/**\n * Groups elements in chunks of up to `n` elements.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const chunksOf: {\n  (n: number): <A>(self: Chunk<A>) => Chunk<Chunk<A>>\n  <A>(self: Chunk<A>, n: number): Chunk<Chunk<A>>\n} = dual(2, <A>(self: Chunk<A>, n: number) => {\n  const gr: Array<Chunk<A>> = []\n  let current: Array<A> = []\n  toReadonlyArray(self).forEach((a) => {\n    current.push(a)\n    if (current.length >= n) {\n      gr.push(unsafeFromArray(current))\n      current = []\n    }\n  })\n  if (current.length > 0) {\n    gr.push(unsafeFromArray(current))\n  }\n  return unsafeFromArray(gr)\n})\n\n/**\n * Creates a Chunk of unique values that are included in all given Chunks.\n *\n * The order and references of result values are determined by the Chunk.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const intersection: {\n  <A>(that: Chunk<A>): <B>(self: Chunk<B>) => Chunk<A & B>\n  <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A & B>\n} = dual(\n  2,\n  <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A & B> =>\n    unsafeFromArray(RA.intersection(toReadonlyArray(self), toReadonlyArray(that)))\n)\n\n/**\n * Determines if the chunk is empty.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const isEmpty = <A>(self: Chunk<A>): boolean => self.length === 0\n\n/**\n * Determines if the chunk is not empty.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const isNonEmpty = <A>(self: Chunk<A>): self is NonEmptyChunk<A> => self.length > 0\n\n/**\n * Returns the first element of this chunk if it exists.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const head: <A>(self: Chunk<A>) => Option<A> = get(0)\n\n/**\n * Returns the first element of this chunk.\n *\n * It will throw an error if the chunk is empty.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeHead = <A>(self: Chunk<A>): A => unsafeGet(self, 0)\n\n/**\n * Returns the first element of this non empty chunk.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const headNonEmpty: <A>(self: NonEmptyChunk<A>) => A = unsafeHead\n\n/**\n * Returns the last element of this chunk if it exists.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const last = <A>(self: Chunk<A>): Option<A> => get(self, self.length - 1)\n\n/**\n * Returns the last element of this chunk.\n *\n * It will throw an error if the chunk is empty.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeLast = <A>(self: Chunk<A>): A => unsafeGet(self, self.length - 1)\n\n/**\n * Returns the last element of this non empty chunk.\n *\n * @since 3.4.0\n * @category elements\n */\nexport const lastNonEmpty: <A>(self: NonEmptyChunk<A>) => A = unsafeLast\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Chunk {\n  /**\n   * @since 2.0.0\n   */\n  export type Infer<S extends Chunk<any>> = S extends Chunk<infer A> ? A : never\n\n  /**\n   * @since 2.0.0\n   */\n  export type With<S extends Chunk<any>, A> = S extends NonEmptyChunk<any> ? NonEmptyChunk<A> : Chunk<A>\n\n  /**\n   * @since 2.0.0\n   */\n  export type OrNonEmpty<S extends Chunk<any>, T extends Chunk<any>, A> = S extends NonEmptyChunk<any> ?\n    NonEmptyChunk<A>\n    : T extends NonEmptyChunk<any> ? NonEmptyChunk<A>\n    : Chunk<A>\n\n  /**\n   * @since 2.0.0\n   */\n  export type AndNonEmpty<S extends Chunk<any>, T extends Chunk<any>, A> = S extends NonEmptyChunk<any> ?\n    T extends NonEmptyChunk<any> ? NonEmptyChunk<A>\n    : Chunk<A> :\n    Chunk<A>\n\n  /**\n   * @since 2.0.0\n   */\n  export type Flatten<T extends Chunk<Chunk<any>>> = T extends NonEmptyChunk<NonEmptyChunk<infer A>> ? NonEmptyChunk<A>\n    : T extends Chunk<Chunk<infer A>> ? Chunk<A>\n    : never\n}\n\n/**\n * Transforms the elements of a chunk using the specified mapping function.\n * If the input chunk is non-empty, the resulting chunk will also be non-empty.\n *\n * **Example**\n *\n * ```ts\n * import { Chunk } from \"effect\"\n *\n * const result = Chunk.map(Chunk.make(1, 2), (n) => n + 1)\n *\n * console.log(result)\n * // { _id: 'Chunk', values: [ 2, 3 ] }\n * ```\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <S extends Chunk<any>, B>(f: (a: Chunk.Infer<S>, i: number) => B): (self: S) => Chunk.With<S, B>\n  <A, B>(self: NonEmptyChunk<A>, f: (a: A, i: number) => B): NonEmptyChunk<B>\n  <A, B>(self: Chunk<A>, f: (a: A, i: number) => B): Chunk<B>\n} = dual(2, <A, B>(self: Chunk<A>, f: (a: A, i: number) => B): Chunk<B> =>\n  self.backing._tag === \"ISingleton\" ?\n    of(f(self.backing.a, 0)) :\n    unsafeFromArray(pipe(toReadonlyArray(self), RA.map((a, i) => f(a, i)))))\n\n/**\n * Statefully maps over the chunk, producing new elements of type `B`.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const mapAccum: {\n  <S, A, B>(s: S, f: (s: S, a: A) => readonly [S, B]): (self: Chunk<A>) => [S, Chunk<B>]\n  <S, A, B>(self: Chunk<A>, s: S, f: (s: S, a: A) => readonly [S, B]): [S, Chunk<B>]\n} = dual(3, <S, A, B>(self: Chunk<A>, s: S, f: (s: S, a: A) => readonly [S, B]): [S, Chunk<B>] => {\n  const [s1, as] = RA.mapAccum(self, s, f)\n  return [s1, unsafeFromArray(as)]\n})\n\n/**\n * Separate elements based on a predicate that also exposes the index of the element.\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partition: {\n  <A, B extends A>(\n    refinement: (a: NoInfer<A>, i: number) => a is B\n  ): (self: Chunk<A>) => [excluded: Chunk<Exclude<A, B>>, satisfying: Chunk<B>]\n  <A>(\n    predicate: (a: NoInfer<A>, i: number) => boolean\n  ): (self: Chunk<A>) => [excluded: Chunk<A>, satisfying: Chunk<A>]\n  <A, B extends A>(\n    self: Chunk<A>,\n    refinement: (a: A, i: number) => a is B\n  ): [excluded: Chunk<Exclude<A, B>>, satisfying: Chunk<B>]\n  <A>(self: Chunk<A>, predicate: (a: A, i: number) => boolean): [excluded: Chunk<A>, satisfying: Chunk<A>]\n} = dual(\n  2,\n  <A>(self: Chunk<A>, predicate: (a: A, i: number) => boolean): [excluded: Chunk<A>, satisfying: Chunk<A>] =>\n    pipe(\n      RA.partition(toReadonlyArray(self), predicate),\n      ([l, r]) => [unsafeFromArray(l), unsafeFromArray(r)]\n    )\n)\n\n/**\n * Partitions the elements of this chunk into two chunks using f.\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partitionMap: {\n  <A, B, C>(f: (a: A) => Either<C, B>): (self: Chunk<A>) => [left: Chunk<B>, right: Chunk<C>]\n  <A, B, C>(self: Chunk<A>, f: (a: A) => Either<C, B>): [left: Chunk<B>, right: Chunk<C>]\n} = dual(2, <A, B, C>(self: Chunk<A>, f: (a: A) => Either<C, B>): [left: Chunk<B>, right: Chunk<C>] =>\n  pipe(\n    RA.partitionMap(toReadonlyArray(self), f),\n    ([l, r]) => [unsafeFromArray(l), unsafeFromArray(r)]\n  ))\n\n/**\n * Partitions the elements of this chunk into two chunks.\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const separate = <A, B>(self: Chunk<Either<B, A>>): [Chunk<A>, Chunk<B>] =>\n  pipe(\n    RA.separate(toReadonlyArray(self)),\n    ([l, r]) => [unsafeFromArray(l), unsafeFromArray(r)]\n  )\n\n/**\n * Retireves the size of the chunk\n *\n * @since 2.0.0\n * @category elements\n */\nexport const size = <A>(self: Chunk<A>): number => self.length\n\n/**\n * Sort the elements of a Chunk in increasing order, creating a new Chunk.\n *\n * @since 2.0.0\n * @category sorting\n */\nexport const sort: {\n  <B>(O: Order.Order<B>): <A extends B>(self: Chunk<A>) => Chunk<A>\n  <A extends B, B>(self: Chunk<A>, O: Order.Order<B>): Chunk<A>\n} = dual(\n  2,\n  <A extends B, B>(self: Chunk<A>, O: Order.Order<B>): Chunk<A> => unsafeFromArray(RA.sort(toReadonlyArray(self), O))\n)\n\n/**\n * @since 2.0.0\n * @category sorting\n */\nexport const sortWith: {\n  <A, B>(f: (a: A) => B, order: Order.Order<B>): (self: Chunk<A>) => Chunk<A>\n  <A, B>(self: Chunk<A>, f: (a: A) => B, order: Order.Order<B>): Chunk<A>\n} = dual(\n  3,\n  <A, B>(self: Chunk<A>, f: (a: A) => B, order: Order.Order<B>): Chunk<A> => sort(self, Order.mapInput(order, f))\n)\n\n/**\n *  Returns two splits of this chunk at the specified index.\n *\n * @since 2.0.0\n * @category splitting\n */\nexport const splitAt: {\n  (n: number): <A>(self: Chunk<A>) => [beforeIndex: Chunk<A>, fromIndex: Chunk<A>]\n  <A>(self: Chunk<A>, n: number): [beforeIndex: Chunk<A>, fromIndex: Chunk<A>]\n} = dual(2, <A>(self: Chunk<A>, n: number): [Chunk<A>, Chunk<A>] => [take(self, n), drop(self, n)])\n\n/**\n * Splits a `NonEmptyChunk` into two segments, with the first segment containing a maximum of `n` elements.\n * The value of `n` must be `>= 1`.\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitNonEmptyAt: {\n  (n: number): <A>(self: NonEmptyChunk<A>) => [beforeIndex: NonEmptyChunk<A>, fromIndex: Chunk<A>]\n  <A>(self: NonEmptyChunk<A>, n: number): [beforeIndex: NonEmptyChunk<A>, fromIndex: Chunk<A>]\n} = dual(2, <A>(self: NonEmptyChunk<A>, n: number): [Chunk<A>, Chunk<A>] => {\n  const _n = Math.max(1, Math.floor(n))\n  return _n >= self.length ?\n    [self, empty()] :\n    [take(self, _n), drop(self, _n)]\n})\n\n/**\n * Splits this chunk into `n` equally sized chunks.\n *\n * @since 2.0.0\n * @category splitting\n */\nexport const split: {\n  (n: number): <A>(self: Chunk<A>) => Chunk<Chunk<A>>\n  <A>(self: Chunk<A>, n: number): Chunk<Chunk<A>>\n} = dual(2, <A>(self: Chunk<A>, n: number) => chunksOf(self, Math.ceil(self.length / Math.floor(n))))\n\n/**\n * Splits this chunk on the first element that matches this predicate.\n * Returns a tuple containing two chunks: the first one is before the match, and the second one is from the match onward.\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const splitWhere: {\n  <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => [beforeMatch: Chunk<A>, fromMatch: Chunk<A>]\n  <A>(self: Chunk<A>, predicate: Predicate<A>): [beforeMatch: Chunk<A>, fromMatch: Chunk<A>]\n} = dual(2, <A>(self: Chunk<A>, predicate: Predicate<A>): [beforeMatch: Chunk<A>, fromMatch: Chunk<A>] => {\n  let i = 0\n  for (const a of toReadonlyArray(self)) {\n    if (predicate(a)) {\n      break\n    } else {\n      i++\n    }\n  }\n  return splitAt(self, i)\n})\n\n/**\n * Returns every elements after the first.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const tail = <A>(self: Chunk<A>): Option<Chunk<A>> => self.length > 0 ? O.some(drop(self, 1)) : O.none()\n\n/**\n * Returns every elements after the first.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const tailNonEmpty = <A>(self: NonEmptyChunk<A>): Chunk<A> => drop(self, 1)\n\n/**\n * Takes the last `n` elements.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const takeRight: {\n  (n: number): <A>(self: Chunk<A>) => Chunk<A>\n  <A>(self: Chunk<A>, n: number): Chunk<A>\n} = dual(2, <A>(self: Chunk<A>, n: number): Chunk<A> => drop(self, self.length - n))\n\n/**\n * Takes all elements so long as the predicate returns true.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const takeWhile: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Chunk<A>) => Chunk<B>\n  <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => Chunk<A>\n  <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): Chunk<B>\n  <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A>\n} = dual(2, <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A> => {\n  const out: Array<A> = []\n  for (const a of toReadonlyArray(self)) {\n    if (predicate(a)) {\n      out.push(a)\n    } else {\n      break\n    }\n  }\n  return unsafeFromArray(out)\n})\n\n/**\n * Creates a Chunks of unique values, in order, from all given Chunks.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const union: {\n  <A>(that: Chunk<A>): <B>(self: Chunk<B>) => Chunk<A | B>\n  <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A | B>\n} = dual(\n  2,\n  <A, B>(self: Chunk<A>, that: Chunk<B>) => unsafeFromArray(RA.union(toReadonlyArray(self), toReadonlyArray(that)))\n)\n\n/**\n * Remove duplicates from an array, keeping the first occurrence of an element.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const dedupe = <A>(self: Chunk<A>): Chunk<A> => unsafeFromArray(RA.dedupe(toReadonlyArray(self)))\n\n/**\n * Deduplicates adjacent elements that are identical.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const dedupeAdjacent = <A>(self: Chunk<A>): Chunk<A> => unsafeFromArray(RA.dedupeAdjacent(self))\n\n/**\n * Takes a `Chunk` of pairs and return two corresponding `Chunk`s.\n *\n * Note: The function is reverse of `zip`.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const unzip = <A, B>(self: Chunk<readonly [A, B]>): [Chunk<A>, Chunk<B>] => {\n  const [left, right] = RA.unzip(self)\n  return [unsafeFromArray(left), unsafeFromArray(right)]\n}\n\n/**\n * Zips this chunk pointwise with the specified chunk using the specified combiner.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWith: {\n  <A, B, C>(that: Chunk<B>, f: (a: A, b: B) => C): (self: Chunk<A>) => Chunk<C>\n  <A, B, C>(self: Chunk<A>, that: Chunk<B>, f: (a: A, b: B) => C): Chunk<C>\n} = dual(\n  3,\n  <A, B, C>(self: Chunk<A>, that: Chunk<B>, f: (a: A, b: B) => C): Chunk<C> =>\n    unsafeFromArray(RA.zipWith(self, that, f))\n)\n\n/**\n * Zips this chunk pointwise with the specified chunk.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zip: {\n  <B>(that: Chunk<B>): <A>(self: Chunk<A>) => Chunk<[A, B]>\n  <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<[A, B]>\n} = dual(\n  2,\n  <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<[A, B]> => zipWith(self, that, (a, b) => [a, b])\n)\n\n/**\n * Delete the element at the specified index, creating a new `Chunk`.\n *\n * @since 2.0.0\n */\nexport const remove: {\n  (i: number): <A>(self: Chunk<A>) => Chunk<A>\n  <A>(self: Chunk<A>, i: number): Chunk<A>\n} = dual(\n  2,\n  <A>(self: Chunk<A>, i: number): Chunk<A> => {\n    if (i < 0 || i >= self.length) return self\n    return unsafeFromArray(RA.remove(toReadonlyArray(self), i))\n  }\n)\n\n/**\n * @since 3.16.0\n */\nexport const removeOption: {\n  (i: number): <A>(self: Chunk<A>) => Option<Chunk<A>>\n  <A>(self: Chunk<A>, i: number): Option<Chunk<A>>\n} = dual(\n  2,\n  <A>(self: Chunk<A>, i: number): Option<Chunk<A>> => {\n    if (i < 0 || i >= self.length) return O.none()\n    return O.some(unsafeFromArray(RA.remove(toReadonlyArray(self), i)))\n  }\n)\n\n/**\n * @since 2.0.0\n */\nexport const modifyOption: {\n  <A, B>(i: number, f: (a: A) => B): (self: Chunk<A>) => Option<Chunk<A | B>>\n  <A, B>(self: Chunk<A>, i: number, f: (a: A) => B): Option<Chunk<A | B>>\n} = dual(\n  3,\n  <A, B>(self: Chunk<A>, i: number, f: (a: A) => B): Option<Chunk<A | B>> => {\n    if (i < 0 || i >= self.length) return O.none()\n    return O.some(unsafeFromArray(RA.modify(toReadonlyArray(self), i, f)))\n  }\n)\n\n/**\n * Apply a function to the element at the specified index, creating a new `Chunk`,\n * or returning the input if the index is out of bounds.\n *\n * @since 2.0.0\n */\nexport const modify: {\n  <A, B>(i: number, f: (a: A) => B): (self: Chunk<A>) => Chunk<A | B>\n  <A, B>(self: Chunk<A>, i: number, f: (a: A) => B): Chunk<A | B>\n} = dual(\n  3,\n  <A, B>(self: Chunk<A>, i: number, f: (a: A) => B): Chunk<A | B> => O.getOrElse(modifyOption(self, i, f), () => self)\n)\n\n/**\n * Change the element at the specified index, creating a new `Chunk`,\n * or returning the input if the index is out of bounds.\n *\n * @since 2.0.0\n */\nexport const replace: {\n  <B>(i: number, b: B): <A>(self: Chunk<A>) => Chunk<B | A>\n  <A, B>(self: Chunk<A>, i: number, b: B): Chunk<B | A>\n} = dual(3, <A, B>(self: Chunk<A>, i: number, b: B): Chunk<B | A> => modify(self, i, () => b))\n\n/**\n * @since 2.0.0\n */\nexport const replaceOption: {\n  <B>(i: number, b: B): <A>(self: Chunk<A>) => Option<Chunk<B | A>>\n  <A, B>(self: Chunk<A>, i: number, b: B): Option<Chunk<B | A>>\n} = dual(3, <A, B>(self: Chunk<A>, i: number, b: B): Option<Chunk<B | A>> => modifyOption(self, i, () => b))\n\n/**\n * Return a Chunk of length n with element i initialized with f(i).\n *\n * **Note**. `n` is normalized to an integer >= 1.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const makeBy: {\n  <A>(f: (i: number) => A): (n: number) => NonEmptyChunk<A>\n  <A>(n: number, f: (i: number) => A): NonEmptyChunk<A>\n} = dual(2, (n, f) => fromIterable(RA.makeBy(n, f)))\n\n/**\n * Create a non empty `Chunk` containing a range of integers, including both endpoints.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const range = (start: number, end: number): NonEmptyChunk<number> =>\n  start <= end ? makeBy(end - start + 1, (i) => start + i) : of(start)\n\n// -------------------------------------------------------------------------------------\n// re-exports from ReadonlyArray\n// -------------------------------------------------------------------------------------\n\n/**\n * Returns a function that checks if a `Chunk` contains a given value using the default `Equivalence`.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const contains: {\n  <A>(a: A): (self: Chunk<A>) => boolean\n  <A>(self: Chunk<A>, a: A): boolean\n} = RA.contains\n\n/**\n * Returns a function that checks if a `Chunk` contains a given value using a provided `isEquivalent` function.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const containsWith: <A>(\n  isEquivalent: (self: A, that: A) => boolean\n) => {\n  (a: A): (self: Chunk<A>) => boolean\n  (self: Chunk<A>, a: A): boolean\n} = RA.containsWith\n\n/**\n * Returns the first element that satisfies the specified\n * predicate, or `None` if no such element exists.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findFirst: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Chunk<A>) => Option<B>\n  <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => Option<A>\n  <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): Option<B>\n  <A>(self: Chunk<A>, predicate: Predicate<A>): Option<A>\n} = RA.findFirst\n\n/**\n * Return the first index for which a predicate holds.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findFirstIndex: {\n  <A>(predicate: Predicate<A>): (self: Chunk<A>) => Option<number>\n  <A>(self: Chunk<A>, predicate: Predicate<A>): Option<number>\n} = RA.findFirstIndex\n\n/**\n * Find the last element for which a predicate holds.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findLast: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Chunk<A>) => Option<B>\n  <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => Option<A>\n  <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): Option<B>\n  <A>(self: Chunk<A>, predicate: Predicate<A>): Option<A>\n} = RA.findLast\n\n/**\n * Return the last index for which a predicate holds.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findLastIndex: {\n  <A>(predicate: Predicate<A>): (self: Chunk<A>) => Option<number>\n  <A>(self: Chunk<A>, predicate: Predicate<A>): Option<number>\n} = RA.findLastIndex\n\n/**\n * Check if a predicate holds true for every `Chunk` element.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const every: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Chunk<A>) => self is Chunk<B>\n  <A>(predicate: Predicate<A>): (self: Chunk<A>) => boolean\n  <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): self is Chunk<B>\n  <A>(self: Chunk<A>, predicate: Predicate<A>): boolean\n} = dual(\n  2,\n  <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): self is Chunk<B> =>\n    RA.fromIterable(self).every(refinement)\n)\n\n/**\n * Check if a predicate holds true for some `Chunk` element.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const some: {\n  <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => self is NonEmptyChunk<A>\n  <A>(self: Chunk<A>, predicate: Predicate<A>): self is NonEmptyChunk<A>\n} = dual(\n  2,\n  <A>(self: Chunk<A>, predicate: Predicate<A>): self is NonEmptyChunk<A> => RA.fromIterable(self).some(predicate)\n)\n\n/**\n * Joins the elements together with \"sep\" in the middle.\n *\n * @category folding\n * @since 2.0.0\n */\nexport const join: {\n  (sep: string): (self: Chunk<string>) => string\n  (self: Chunk<string>, sep: string): string\n} = RA.join\n\n/**\n * @category folding\n * @since 2.0.0\n */\nexport const reduce: {\n  <B, A>(b: B, f: (b: B, a: A, i: number) => B): (self: Chunk<A>) => B\n  <A, B>(self: Chunk<A>, b: B, f: (b: B, a: A, i: number) => B): B\n} = RA.reduce\n\n/**\n * @category folding\n * @since 2.0.0\n */\nexport const reduceRight: {\n  <B, A>(b: B, f: (b: B, a: A, i: number) => B): (self: Chunk<A>) => B\n  <A, B>(self: Chunk<A>, b: B, f: (b: B, a: A, i: number) => B): B\n} = RA.reduceRight\n\n/**\n * Creates a `Chunk` of values not included in the other given `Chunk` using the provided `isEquivalent` function.\n * The order and references of result values are determined by the first `Chunk`.\n *\n * @since 3.2.0\n */\nexport const differenceWith = <A>(isEquivalent: (self: A, that: A) => boolean): {\n  (that: Chunk<A>): (self: Chunk<A>) => Chunk<A>\n  (self: Chunk<A>, that: Chunk<A>): Chunk<A>\n} => {\n  return dual(\n    2,\n    (self: Chunk<A>, that: Chunk<A>): Chunk<A> => unsafeFromArray(RA.differenceWith(isEquivalent)(that, self))\n  )\n}\n\n/**\n * Creates a `Chunk` of values not included in the other given `Chunk`.\n * The order and references of result values are determined by the first `Chunk`.\n *\n * @since 3.2.0\n */\nexport const difference: {\n  <A>(that: Chunk<A>): (self: Chunk<A>) => Chunk<A>\n  <A>(self: Chunk<A>, that: Chunk<A>): Chunk<A>\n} = dual(\n  2,\n  <A>(self: Chunk<A>, that: Chunk<A>): Chunk<A> => unsafeFromArray(RA.difference(that, self))\n)\n"
  },
  {
    "path": "packages/effect/src/Clock.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Context from \"./Context.js\"\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/clock.js\"\nimport * as defaultServices from \"./internal/defaultServices.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ClockTypeId: unique symbol = internal.ClockTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ClockTypeId = typeof ClockTypeId\n\n/**\n * Represents a time-based clock which provides functionality related to time\n * and scheduling.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Clock {\n  readonly [ClockTypeId]: ClockTypeId\n  /**\n   * Unsafely returns the current time in milliseconds.\n   */\n  unsafeCurrentTimeMillis(): number\n  /**\n   * Returns the current time in milliseconds.\n   */\n  readonly currentTimeMillis: Effect.Effect<number>\n  /**\n   * Unsafely returns the current time in nanoseconds.\n   */\n  unsafeCurrentTimeNanos(): bigint\n  /**\n   * Returns the current time in nanoseconds.\n   */\n  readonly currentTimeNanos: Effect.Effect<bigint>\n  /**\n   * Asynchronously sleeps for the specified duration.\n   */\n  sleep(duration: Duration.Duration): Effect.Effect<void>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type CancelToken = () => boolean\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type Task = () => void\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface ClockScheduler {\n  /**\n   * Unsafely schedules the specified task for the specified duration.\n   */\n  unsafeSchedule(task: Task, duration: Duration.Duration): CancelToken\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (_: void) => Clock = internal.make\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const sleep: (duration: Duration.DurationInput) => Effect.Effect<void> = defaultServices.sleep\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const currentTimeMillis: Effect.Effect<number> = defaultServices.currentTimeMillis\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const currentTimeNanos: Effect.Effect<bigint> = defaultServices.currentTimeNanos\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const clockWith: <A, E, R>(f: (clock: Clock) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> =\n  defaultServices.clockWith\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const Clock: Context.Tag<Clock, Clock> = internal.clockTag\n"
  },
  {
    "path": "packages/effect/src/Config.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Brand from \"./Brand.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as ConfigError from \"./ConfigError.js\"\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport type * as HashMap from \"./HashMap.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport * as internal from \"./internal/config.js\"\nimport type * as LogLevel from \"./LogLevel.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport type * as Redacted from \"./Redacted.js\"\nimport type * as Secret from \"./Secret.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ConfigTypeId: unique symbol = internal.ConfigTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ConfigTypeId = typeof ConfigTypeId\n\n/**\n * A `Config` describes the structure of some configuration data.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Config<out A> extends Config.Variance<A>, Effect.Effect<A, ConfigError.ConfigError> {}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Config {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out A> {\n    readonly [ConfigTypeId]: {\n      readonly _A: Types.Covariant<A>\n    }\n  }\n\n  /**\n   * @since 2.5.0\n   * @category models\n   */\n  export type Success<T extends Config<any>> = [T] extends [Config<infer _A>] ? _A : never\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Primitive<out A> extends Config<A> {\n    readonly description: string\n    parse(text: string): Either.Either<A, ConfigError.ConfigError>\n  }\n\n  /**\n   * Wraps a nested structure, converting all primitives to a `Config`.\n   *\n   * `Config.Wrap<{ key: string }>` becomes `{ key: Config<string> }`\n   *\n   * To create the resulting config, use the `unwrap` constructor.\n   *\n   * @since 2.0.0\n   * @category models\n   */\n  export type Wrap<A> = [NonNullable<A>] extends [infer T] ? [IsPlainObject<T>] extends [true] ?\n        | { readonly [K in keyof A]: Wrap<A[K]> }\n        | Config<A>\n    : Config<A>\n    : Config<A>\n\n  type IsPlainObject<A> = [A] extends [Record<string, any>]\n    ? [keyof A] extends [never] ? false : [keyof A] extends [string] ? true : false\n    : false\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type LiteralValue = string | number | boolean | null | bigint\n\n/**\n * Constructs a config from a tuple / struct / arguments of configs.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const all: <const Arg extends Iterable<Config<any>> | Record<string, Config<any>>>(\n  arg: Arg\n) => Config<\n  [Arg] extends [ReadonlyArray<Config<any>>] ? {\n      -readonly [K in keyof Arg]: [Arg[K]] extends [Config<infer A>] ? A : never\n    }\n    : [Arg] extends [Iterable<Config<infer A>>] ? Array<A>\n    : [Arg] extends [Record<string, Config<any>>] ? {\n        -readonly [K in keyof Arg]: [Arg[K]] extends [Config<infer A>] ? A : never\n      }\n    : never\n> = internal.all\n\n/**\n * Constructs a config for an array of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const array: <A>(config: Config<A>, name?: string) => Config<Array<A>> = internal.array\n\n/**\n * Constructs a config for a boolean value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const boolean: (name?: string) => Config<boolean> = internal.boolean\n\n/**\n * Constructs a config for a network port [1, 65535].\n *\n * @since 3.16.0\n * @category constructors\n */\nexport const port: (name?: string) => Config<number> = internal.port\n\n/**\n * Constructs a config for an URL value.\n *\n * @since 3.11.0\n * @category constructors\n */\nexport const url: (name?: string) => Config<URL> = internal.url\n\n/**\n * Constructs a config for a sequence of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const chunk: <A>(config: Config<A>, name?: string) => Config<Chunk.Chunk<A>> = internal.chunk\n\n/**\n * Constructs a config for a date value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const date: (name?: string) => Config<Date> = internal.date\n\n/**\n * Constructs a config that fails with the specified message.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fail: (message: string) => Config<never> = internal.fail\n\n/**\n * Constructs a config for a float value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const number: (name?: string) => Config<number> = internal.number\n\n/**\n * Constructs a config for a integer value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const integer: (name?: string) => Config<number> = internal.integer\n\n/**\n * Constructs a config for a literal value.\n *\n * **Example**\n *\n * ```ts\n * import { Config } from \"effect\"\n *\n * const config = Config.literal(\"http\", \"https\")(\"PROTOCOL\")\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const literal: <Literals extends ReadonlyArray<LiteralValue>>(...literals: Literals) => (\n  name?: string\n) => Config<Literals[number]> = internal.literal\n\n/**\n * Constructs a config for a `LogLevel` value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const logLevel: (name?: string) => Config<LogLevel.LogLevel> = internal.logLevel\n\n/**\n * Constructs a config for a duration value.\n *\n * @since 2.5.0\n * @category constructors\n */\nexport const duration: (name?: string) => Config<Duration.Duration> = internal.duration\n\n/**\n * This function returns `true` if the specified value is an `Config` value,\n * `false` otherwise.\n *\n * This function can be useful for checking the type of a value before\n * attempting to operate on it as an `Config` value. For example, you could\n * use `isConfig` to check the type of a value before using it as an\n * argument to a function that expects an `Config` value.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isConfig: (u: unknown) => u is Config<unknown> = internal.isConfig\n\n/**\n * Returns a  config whose structure is the same as this one, but which produces\n * a different value, constructed using the specified function.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): (self: Config<A>) => Config<B>\n  <A, B>(self: Config<A>, f: (a: A) => B): Config<B>\n} = internal.map\n\n/**\n * Returns a config whose structure is the same as this one, but which may\n * produce a different value, constructed using the specified function, which\n * may throw exceptions that will be translated into validation errors.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mapAttempt: {\n  <A, B>(f: (a: A) => B): (self: Config<A>) => Config<B>\n  <A, B>(self: Config<A>, f: (a: A) => B): Config<B>\n} = internal.mapAttempt\n\n/**\n * Returns a new config whose structure is the samea as this one, but which\n * may produce a different value, constructed using the specified fallible\n * function.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mapOrFail: {\n  <A, B>(f: (a: A) => Either.Either<B, ConfigError.ConfigError>): (self: Config<A>) => Config<B>\n  <A, B>(self: Config<A>, f: (a: A) => Either.Either<B, ConfigError.ConfigError>): Config<B>\n} = internal.mapOrFail\n\n/**\n * Returns a config that has this configuration nested as a property of the\n * specified name.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const nested: {\n  (name: string): <A>(self: Config<A>) => Config<A>\n  <A>(self: Config<A>, name: string): Config<A>\n} = internal.nested\n\n/**\n * Returns a config whose structure is preferentially described by this\n * config, but which falls back to the specified config if there is an issue\n * reading from this config.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const orElse: {\n  <A2>(that: LazyArg<Config<A2>>): <A>(self: Config<A>) => Config<A2 | A>\n  <A, A2>(self: Config<A>, that: LazyArg<Config<A2>>): Config<A | A2>\n} = internal.orElse\n\n/**\n * Returns configuration which reads from this configuration, but which falls\n * back to the specified configuration if reading from this configuration\n * fails with an error satisfying the specified predicate.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const orElseIf: {\n  <A2>(\n    options: {\n      readonly if: Predicate<ConfigError.ConfigError>\n      readonly orElse: LazyArg<Config<A2>>\n    }\n  ): <A>(self: Config<A>) => Config<A | A2>\n  <A, A2>(\n    self: Config<A>,\n    options: {\n      readonly if: Predicate<ConfigError.ConfigError>\n      readonly orElse: LazyArg<Config<A2>>\n    }\n  ): Config<A | A2>\n} = internal.orElseIf\n\n/**\n * Returns an optional version of this config, which will be `None` if the\n * data is missing from configuration, and `Some` otherwise.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const option: <A>(self: Config<A>) => Config<Option.Option<A>> = internal.option\n\n/**\n * Constructs a new primitive config.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const primitive: <A>(\n  description: string,\n  parse: (text: string) => Either.Either<A, ConfigError.ConfigError>\n) => Config<A> = internal.primitive\n\n/**\n * Returns a config that describes a sequence of values, each of which has the\n * structure of this config.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const repeat: <A>(self: Config<A>) => Config<Array<A>> = internal.repeat\n\n/**\n * Constructs a config for a secret value.\n *\n * @since 2.0.0\n * @category constructors\n * @deprecated\n */\nexport const secret: (name?: string) => Config<Secret.Secret> = internal.secret\n\n/**\n * Constructs a config for a redacted value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const redacted: {\n  (name?: string): Config<Redacted.Redacted>\n  <A>(config: Config<A>): Config<Redacted.Redacted<A>>\n} = internal.redacted\n\n/**\n * Constructs a config for a branded value.\n *\n * @since 3.16.0\n * @category constructors\n */\nexport const branded: {\n  <A, B extends Brand.Branded<A, any>>(\n    constructor: Brand.Brand.Constructor<B>\n  ): (config: Config<A>) => Config<B>\n  <B extends Brand.Branded<string, any>>(\n    name: string | undefined,\n    constructor: Brand.Brand.Constructor<B>\n  ): Config<B>\n  <A, B extends Brand.Branded<A, any>>(\n    config: Config<A>,\n    constructor: Brand.Brand.Constructor<B>\n  ): Config<B>\n} = internal.branded\n\n/**\n * Constructs a config for a sequence of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const hashSet: <A>(config: Config<A>, name?: string) => Config<HashSet.HashSet<A>> = internal.hashSet\n\n/**\n * Constructs a config for a string value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const string: (name?: string) => Config<string> = internal.string\n\n/**\n * Constructs a config for a non-empty string value.\n *\n * @since 3.7.0\n * @category constructors\n */\nexport const nonEmptyString: (name?: string) => Config<string> = internal.nonEmptyString\n\n/**\n * Constructs a config which contains the specified value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeed: <A>(value: A) => Config<A> = internal.succeed\n\n/**\n * Lazily constructs a config.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const suspend: <A>(config: LazyArg<Config<A>>) => Config<A> = internal.suspend\n\n/**\n * Constructs a config which contains the specified lazy value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sync: <A>(value: LazyArg<A>) => Config<A> = internal.sync\n\n/**\n * Constructs a config for a sequence of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const hashMap: <A>(config: Config<A>, name?: string) => Config<HashMap.HashMap<string, A>> = internal.hashMap\n\n/**\n * Constructs a config from some configuration wrapped with the `Wrap<A>` utility type.\n *\n * For example:\n *\n * ```\n * import { Config, unwrap } from \"./Config\"\n *\n * interface Options { key: string }\n *\n * const makeConfig = (config: Config.Wrap<Options>): Config<Options> => unwrap(config)\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unwrap: <A>(wrapped: Config.Wrap<A>) => Config<A> = internal.unwrap\n\n/**\n * Returns a config that describes the same structure as this one, but which\n * performs validation during loading.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const validate: {\n  <A, B extends A>(\n    options: {\n      readonly message: string\n      readonly validation: Refinement<A, B>\n    }\n  ): (self: Config<A>) => Config<B>\n  <A>(options: {\n    readonly message: string\n    readonly validation: Predicate<A>\n  }): (self: Config<A>) => Config<A>\n  <A, B extends A>(\n    self: Config<A>,\n    options: {\n      readonly message: string\n      readonly validation: Refinement<A, B>\n    }\n  ): Config<B>\n  <A>(self: Config<A>, options: {\n    readonly message: string\n    readonly validation: Predicate<A>\n  }): Config<A>\n} = internal.validate\n\n/**\n * Returns a config that describes the same structure as this one, but has the\n * specified default value in case the information cannot be found.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const withDefault: {\n  <const A2>(def: A2): <A>(self: Config<A>) => Config<A2 | A>\n  <A, const A2>(self: Config<A>, def: A2): Config<A | A2>\n} = internal.withDefault\n\n/**\n * Adds a description to this configuration, which is intended for humans.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const withDescription: {\n  (description: string): <A>(self: Config<A>) => Config<A>\n  <A>(self: Config<A>, description: string): Config<A>\n} = internal.withDescription\n\n/**\n * Returns a config that is the composition of this config and the specified\n * config.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zip: {\n  <B>(that: Config<B>): <A>(self: Config<A>) => Config<[A, B]>\n  <A, B>(self: Config<A>, that: Config<B>): Config<[A, B]>\n} = internal.zip\n\n/**\n * Returns a config that is the composes this config and the specified config\n * using the provided function.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWith: {\n  <B, A, C>(that: Config<B>, f: (a: A, b: B) => C): (self: Config<A>) => Config<C>\n  <A, B, C>(self: Config<A>, that: Config<B>, f: (a: A, b: B) => C): Config<C>\n} = internal.zipWith\n"
  },
  {
    "path": "packages/effect/src/ConfigError.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport * as internal from \"./internal/configError.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ConfigErrorTypeId: unique symbol = internal.ConfigErrorTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ConfigErrorTypeId = typeof ConfigErrorTypeId\n\n/**\n * The possible ways that loading configuration data may fail.\n *\n * @since 2.0.0\n * @category models\n */\nexport type ConfigError =\n  | And\n  | Or\n  | InvalidData\n  | MissingData\n  | SourceUnavailable\n  | Unsupported\n\n/**\n * @since 2.0.0\n */\nexport declare namespace ConfigError {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Proto {\n    readonly _tag: \"ConfigError\"\n    readonly [ConfigErrorTypeId]: ConfigErrorTypeId\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Reducer<C, Z> = ConfigErrorReducer<C, Z>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface ConfigErrorReducer<in C, in out Z> {\n  andCase(context: C, left: Z, right: Z): Z\n  orCase(context: C, left: Z, right: Z): Z\n  invalidDataCase(context: C, path: Array<string>, message: string): Z\n  missingDataCase(context: C, path: Array<string>, message: string): Z\n  sourceUnavailableCase(\n    context: C,\n    path: Array<string>,\n    message: string,\n    cause: Cause.Cause<unknown>\n  ): Z\n  unsupportedCase(context: C, path: Array<string>, message: string): Z\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface And extends ConfigError.Proto {\n  readonly _op: \"And\"\n  readonly left: ConfigError\n  readonly right: ConfigError\n  readonly message: string\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Or extends ConfigError.Proto {\n  readonly _op: \"Or\"\n  readonly left: ConfigError\n  readonly right: ConfigError\n  readonly message: string\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface InvalidData extends ConfigError.Proto {\n  readonly _op: \"InvalidData\"\n  readonly path: Array<string>\n  readonly message: string\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MissingData extends ConfigError.Proto {\n  readonly _op: \"MissingData\"\n  readonly path: Array<string>\n  readonly message: string\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface SourceUnavailable extends ConfigError.Proto {\n  readonly _op: \"SourceUnavailable\"\n  readonly path: Array<string>\n  readonly message: string\n  readonly cause: Cause.Cause<unknown>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Unsupported extends ConfigError.Proto {\n  readonly _op: \"Unsupported\"\n  readonly path: Array<string>\n  readonly message: string\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Options {\n  readonly pathDelim: string\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const And: (self: ConfigError, that: ConfigError) => ConfigError = internal.And\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Or: (self: ConfigError, that: ConfigError) => ConfigError = internal.Or\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const MissingData: (path: Array<string>, message: string, options?: Options) => ConfigError =\n  internal.MissingData\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const InvalidData: (path: Array<string>, message: string, options?: Options) => ConfigError =\n  internal.InvalidData\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const SourceUnavailable: (\n  path: Array<string>,\n  message: string,\n  cause: Cause.Cause<unknown>,\n  options?: Options\n) => ConfigError = internal.SourceUnavailable\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Unsupported: (path: Array<string>, message: string, options?: Options) => ConfigError =\n  internal.Unsupported\n\n/**\n * Returns `true` if the specified value is a `ConfigError`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isConfigError: (u: unknown) => u is ConfigError = internal.isConfigError\n\n/**\n * Returns `true` if the specified `ConfigError` is an `And`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isAnd: (self: ConfigError) => self is And = internal.isAnd\n\n/**\n * Returns `true` if the specified `ConfigError` is an `Or`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isOr: (self: ConfigError) => self is Or = internal.isOr\n\n/**\n * Returns `true` if the specified `ConfigError` is an `InvalidData`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isInvalidData: (self: ConfigError) => self is InvalidData = internal.isInvalidData\n\n/**\n * Returns `true` if the specified `ConfigError` is an `MissingData`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isMissingData: (self: ConfigError) => self is MissingData = internal.isMissingData\n\n/**\n * Returns `true` if the specified `ConfigError` contains only `MissingData` errors, `false` otherwise.\n *\n * @since 2.0.0\n * @categer getters\n */\nexport const isMissingDataOnly: (self: ConfigError) => boolean = internal.isMissingDataOnly\n\n/**\n * Returns `true` if the specified `ConfigError` is a `SourceUnavailable`,\n * `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isSourceUnavailable: (self: ConfigError) => self is SourceUnavailable = internal.isSourceUnavailable\n\n/**\n * Returns `true` if the specified `ConfigError` is an `Unsupported`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isUnsupported: (self: ConfigError) => self is Unsupported = internal.isUnsupported\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const prefixed: {\n  (prefix: Array<string>): (self: ConfigError) => ConfigError\n  (self: ConfigError, prefix: Array<string>): ConfigError\n} = internal.prefixed\n\n/**\n * @since 2.0.0\n * @category folding\n */\nexport const reduceWithContext: {\n  <C, Z>(context: C, reducer: ConfigErrorReducer<C, Z>): (self: ConfigError) => Z\n  <C, Z>(self: ConfigError, context: C, reducer: ConfigErrorReducer<C, Z>): Z\n} = internal.reduceWithContext\n"
  },
  {
    "path": "packages/effect/src/ConfigProvider.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Config from \"./Config.js\"\nimport type * as ConfigError from \"./ConfigError.js\"\nimport type * as PathPatch from \"./ConfigProviderPathPatch.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport * as internal from \"./internal/configProvider.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ConfigProviderTypeId: unique symbol = internal.ConfigProviderTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ConfigProviderTypeId = typeof ConfigProviderTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const FlatConfigProviderTypeId: unique symbol = internal.FlatConfigProviderTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type FlatConfigProviderTypeId = typeof FlatConfigProviderTypeId\n\n/**\n * A ConfigProvider is a service that provides configuration given a description\n * of the structure of that configuration.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface ConfigProvider extends ConfigProvider.Proto, Pipeable {\n  /**\n   * Loads the specified configuration, or fails with a config error.\n   */\n  load<A>(config: Config.Config<A>): Effect.Effect<A, ConfigError.ConfigError>\n  /**\n   * Flattens this config provider into a simplified config provider that knows\n   * only how to deal with flat (key/value) properties.\n   */\n  readonly flattened: ConfigProvider.Flat\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace ConfigProvider {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Proto {\n    readonly [ConfigProviderTypeId]: ConfigProviderTypeId\n  }\n\n  /**\n   * A simplified config provider that knows only how to deal with flat\n   * (key/value) properties. Because these providers are common, there is\n   * special support for implementing them.\n   *\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Flat {\n    readonly [FlatConfigProviderTypeId]: FlatConfigProviderTypeId\n    readonly patch: PathPatch.PathPatch\n    load<A>(\n      path: ReadonlyArray<string>,\n      config: Config.Config.Primitive<A>,\n      split?: boolean\n    ): Effect.Effect<Array<A>, ConfigError.ConfigError>\n    enumerateChildren(\n      path: ReadonlyArray<string>\n    ): Effect.Effect<HashSet.HashSet<string>, ConfigError.ConfigError>\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface FromMapConfig {\n    readonly pathDelim: string\n    readonly seqDelim: string\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface FromEnvConfig {\n    readonly pathDelim: string\n    readonly seqDelim: string\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type KeyComponent = KeyName | KeyIndex\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface KeyName {\n    readonly _tag: \"KeyName\"\n    readonly name: string\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface KeyIndex {\n    readonly _tag: \"KeyIndex\"\n    readonly index: number\n  }\n}\n\n/**\n * The service tag for `ConfigProvider`.\n *\n * @since 2.0.0\n * @category context\n */\nexport const ConfigProvider: Context.Tag<ConfigProvider, ConfigProvider> = internal.configProviderTag\n\n/**\n * Creates a new config provider.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (\n  options: {\n    readonly load: <A>(config: Config.Config<A>) => Effect.Effect<A, ConfigError.ConfigError>\n    readonly flattened: ConfigProvider.Flat\n  }\n) => ConfigProvider = internal.make\n\n/**\n * Creates a new flat config provider.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeFlat: (options: {\n  readonly load: <A>(\n    path: ReadonlyArray<string>,\n    config: Config.Config.Primitive<A>,\n    split: boolean\n  ) => Effect.Effect<Array<A>, ConfigError.ConfigError>\n  readonly enumerateChildren: (\n    path: ReadonlyArray<string>\n  ) => Effect.Effect<HashSet.HashSet<string>, ConfigError.ConfigError>\n  readonly patch: PathPatch.PathPatch\n}) => ConfigProvider.Flat = internal.makeFlat\n\n/**\n * A config provider that loads configuration from context variables\n *\n * **Options**:\n *\n * - `pathDelim`: The delimiter for the path segments (default: `\"_\"`).\n * - `seqDelim`: The delimiter for the sequence of values (default: `\",\"`).\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEnv: (options?: Partial<ConfigProvider.FromEnvConfig>) => ConfigProvider = internal.fromEnv\n\n/**\n * Constructs a new `ConfigProvider` from a key/value (flat) provider, where\n * nesting is embedded into the string keys.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromFlat: (flat: ConfigProvider.Flat) => ConfigProvider = internal.fromFlat\n\n/**\n * Constructs a new `ConfigProvider` from a JSON object.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromJson: (json: unknown) => ConfigProvider = internal.fromJson\n\n// TODO(4.0): use `_` for nested configs instead of `.` in next major\n/**\n * Constructs a ConfigProvider using a map and the specified delimiter string,\n * which determines how to split the keys in the map into path segments.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromMap: (map: Map<string, string>, config?: Partial<ConfigProvider.FromMapConfig>) => ConfigProvider =\n  internal.fromMap\n\n/**\n * Returns a new config provider that will automatically convert all property\n * names to constant case. This can be utilized to adapt the names of\n * configuration properties from the default naming convention of camel case\n * to the naming convention of a config provider.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const constantCase: (self: ConfigProvider) => ConfigProvider = internal.constantCase\n\n/**\n * Returns a new config provider that will automatically tranform all path\n * configuration names with the specified function. This can be utilized to\n * adapt the names of configuration properties from one naming convention to\n * another.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mapInputPath: {\n  (f: (path: string) => string): (self: ConfigProvider) => ConfigProvider\n  (self: ConfigProvider, f: (path: string) => string): ConfigProvider\n} = internal.mapInputPath\n\n/**\n * Returns a new config provider that will automatically convert all property\n * names to kebab case. This can be utilized to adapt the names of\n * configuration properties from the default naming convention of camel case\n * to the naming convention of a config provider.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const kebabCase: (self: ConfigProvider) => ConfigProvider = internal.kebabCase\n\n/**\n * Returns a new config provider that will automatically convert all property\n * names to lower case. This can be utilized to adapt the names of\n * configuration properties from the default naming convention of camel case\n * to the naming convention of a config provider.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const lowerCase: (self: ConfigProvider) => ConfigProvider = internal.lowerCase\n\n/**\n * Returns a new config provider that will automatically nest all\n * configuration under the specified property name. This can be utilized to\n * aggregate separate configuration sources that are all required to load a\n * single configuration value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const nested: {\n  (name: string): (self: ConfigProvider) => ConfigProvider\n  (self: ConfigProvider, name: string): ConfigProvider\n} = internal.nested\n\n/**\n * Returns a new config provider that preferentially loads configuration data\n * from this one, but which will fall back to the specified alternate provider\n * if there are any issues loading the configuration from this provider.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const orElse: {\n  (that: LazyArg<ConfigProvider>): (self: ConfigProvider) => ConfigProvider\n  (self: ConfigProvider, that: LazyArg<ConfigProvider>): ConfigProvider\n} = internal.orElse\n\n/**\n * Returns a new config provider that will automatically un-nest all\n * configuration under the specified property name. This can be utilized to\n * de-aggregate separate configuration sources that are all required to load a\n * single configuration value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const unnested: {\n  (name: string): (self: ConfigProvider) => ConfigProvider\n  (self: ConfigProvider, name: string): ConfigProvider\n} = internal.unnested\n\n/**\n * Returns a new config provider that will automatically convert all property\n * names to upper case. This can be utilized to adapt the names of\n * configuration properties from the default naming convention of camel case\n * to the naming convention of a config provider.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const snakeCase: (self: ConfigProvider) => ConfigProvider = internal.snakeCase\n\n/**\n * Returns a new config provider that will automatically convert all property\n * names to upper case. This can be utilized to adapt the names of\n * configuration properties from the default naming convention of camel case\n * to the naming convention of a config provider.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const upperCase: (self: ConfigProvider) => ConfigProvider = internal.upperCase\n\n/**\n * Returns a new config provider that transforms the config provider with the\n * specified function within the specified path.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const within: {\n  (path: ReadonlyArray<string>, f: (self: ConfigProvider) => ConfigProvider): (self: ConfigProvider) => ConfigProvider\n  (self: ConfigProvider, path: ReadonlyArray<string>, f: (self: ConfigProvider) => ConfigProvider): ConfigProvider\n} = internal.within\n"
  },
  {
    "path": "packages/effect/src/ConfigProviderPathPatch.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/configProvider/pathPatch.js\"\n\n/**\n * Represents a description of how to modify the path to a configuration\n * value.\n *\n * @since 2.0.0\n * @category models\n */\nexport type PathPatch = Empty | AndThen | MapName | Nested | Unnested\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Empty {\n  readonly _tag: \"Empty\"\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface AndThen {\n  readonly _tag: \"AndThen\"\n  readonly first: PathPatch\n  readonly second: PathPatch\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MapName {\n  readonly _tag: \"MapName\"\n  f(string: string): string\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Nested {\n  readonly _tag: \"Nested\"\n  readonly name: string\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Unnested {\n  readonly _tag: \"Unnested\"\n  readonly name: string\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: PathPatch = internal.empty\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const andThen: {\n  (that: PathPatch): (self: PathPatch) => PathPatch\n  (self: PathPatch, that: PathPatch): PathPatch\n} = internal.andThen\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const mapName: {\n  (f: (string: string) => string): (self: PathPatch) => PathPatch\n  (self: PathPatch, f: (string: string) => string): PathPatch\n} = internal.mapName\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const nested: {\n  (name: string): (self: PathPatch) => PathPatch\n  (self: PathPatch, name: string): PathPatch\n} = internal.nested\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const unnested: {\n  (name: string): (self: PathPatch) => PathPatch\n  (self: PathPatch, name: string): PathPatch\n} = internal.unnested\n"
  },
  {
    "path": "packages/effect/src/Console.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Context from \"./Context.js\"\nimport type { Effect } from \"./Effect.js\"\nimport * as internal from \"./internal/console.js\"\nimport * as defaultConsole from \"./internal/defaultServices/console.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type { Scope } from \"./Scope.js\"\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = defaultConsole.TypeId\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface Console {\n  readonly [TypeId]: TypeId\n  assert(condition: boolean, ...args: ReadonlyArray<any>): Effect<void>\n  readonly clear: Effect<void>\n  count(label?: string): Effect<void>\n  countReset(label?: string): Effect<void>\n  debug(...args: ReadonlyArray<any>): Effect<void>\n  dir(item: any, options?: any): Effect<void>\n  dirxml(...args: ReadonlyArray<any>): Effect<void>\n  error(...args: ReadonlyArray<any>): Effect<void>\n  group(options?: {\n    readonly label?: string | undefined\n    readonly collapsed?: boolean | undefined\n  }): Effect<void>\n  readonly groupEnd: Effect<void>\n  info(...args: ReadonlyArray<any>): Effect<void>\n  log(...args: ReadonlyArray<any>): Effect<void>\n  table(tabularData: any, properties?: ReadonlyArray<string>): Effect<void>\n  time(label?: string): Effect<void>\n  timeEnd(label?: string): Effect<void>\n  timeLog(label?: string, ...args: ReadonlyArray<any>): Effect<void>\n  trace(...args: ReadonlyArray<any>): Effect<void>\n  warn(...args: ReadonlyArray<any>): Effect<void>\n  readonly unsafe: UnsafeConsole\n}\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface UnsafeConsole {\n  assert(condition: boolean, ...args: ReadonlyArray<any>): void\n  clear(): void\n  count(label?: string): void\n  countReset(label?: string): void\n  debug(...args: ReadonlyArray<any>): void\n  dir(item: any, options?: any): void\n  dirxml(...args: ReadonlyArray<any>): void\n  error(...args: ReadonlyArray<any>): void\n  group(...args: ReadonlyArray<any>): void\n  groupCollapsed(...args: ReadonlyArray<any>): void\n  groupEnd(): void\n  info(...args: ReadonlyArray<any>): void\n  log(...args: ReadonlyArray<any>): void\n  table(tabularData: any, properties?: ReadonlyArray<string>): void\n  time(label?: string): void\n  timeEnd(label?: string): void\n  timeLog(label?: string, ...args: ReadonlyArray<any>): void\n  trace(...args: ReadonlyArray<any>): void\n  warn(...args: ReadonlyArray<any>): void\n}\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const Console: Context.Tag<Console, Console> = defaultConsole.consoleTag\n\n/**\n * @since 2.0.0\n * @category default services\n */\nexport const withConsole: {\n  <C extends Console>(console: C): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R, C extends Console>(effect: Effect<A, E, R>, console: C): Effect<A, E, R>\n} = internal.withConsole\n\n/**\n * @since 2.0.0\n * @category default services\n */\nexport const setConsole: <A extends Console>(console: A) => Layer.Layer<never> = internal.setConsole\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const consoleWith: <A, E, R>(f: (console: Console) => Effect<A, E, R>) => Effect<A, E, R> = internal.consoleWith\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const assert: (condition: boolean, ...args: ReadonlyArray<any>) => Effect<void> = internal.assert\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const clear: Effect<void> = internal.clear\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const count: (label?: string) => Effect<void> = internal.count\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const countReset: (label?: string) => Effect<void> = internal.countReset\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const debug: (...args: ReadonlyArray<any>) => Effect<void> = internal.debug\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const dir: (item: any, options?: any) => Effect<void> = internal.dir\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const dirxml: (...args: ReadonlyArray<any>) => Effect<void> = internal.dirxml\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const error: (...args: ReadonlyArray<any>) => Effect<void> = internal.error\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const group: (\n  options?: { label?: string | undefined; collapsed?: boolean | undefined } | undefined\n) => Effect<void, never, Scope> = internal.group\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const info: (...args: ReadonlyArray<any>) => Effect<void> = internal.info\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const log: (...args: ReadonlyArray<any>) => Effect<void> = internal.log\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const table: (tabularData: any, properties?: ReadonlyArray<string>) => Effect<void> = internal.table\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const time: (label?: string | undefined) => Effect<void, never, Scope> = internal.time\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const timeLog: (label?: string, ...args: ReadonlyArray<any>) => Effect<void> = internal.timeLog\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const trace: (...args: ReadonlyArray<any>) => Effect<void> = internal.trace\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const warn: (...args: ReadonlyArray<any>) => Effect<void> = internal.warn\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const withGroup: {\n  (options?: {\n    readonly label?: string | undefined\n    readonly collapsed?: boolean | undefined\n  }): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, options?: {\n    readonly label?: string | undefined\n    readonly collapsed?: boolean | undefined\n  }): Effect<A, E, R>\n} = internal.withGroup\n\n/**\n * @since 2.0.0\n * @category accessor\n */\nexport const withTime: {\n  (label?: string): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, label?: string): Effect<A, E, R>\n} = internal.withTime\n"
  },
  {
    "path": "packages/effect/src/Context.ts",
    "content": "/**\n * This module provides a data structure called `Context` that can be used for dependency injection in effectful\n * programs. It is essentially a table mapping `Tag`s to their implementations (called `Service`s), and can be used to\n * manage dependencies in a type-safe way. The `Context` data structure is essentially a way of providing access to a set\n * of related services that can be passed around as a single unit. This module provides functions to create, modify, and\n * query the contents of a `Context`, as well as a number of utility types for working with tags and services.\n *\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport type { Equal } from \"./Equal.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as internal from \"./internal/context.js\"\nimport type { Option } from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport const TagTypeId: unique symbol = internal.TagTypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TagTypeId = typeof TagTypeId\n\n/**\n * @since 3.5.9\n * @category models\n */\nexport interface Tag<in out Id, in out Value> extends Pipeable, Inspectable, ReadonlyTag<Id, Value> {\n  readonly _op: \"Tag\"\n  readonly Service: Value\n  readonly Identifier: Id\n  readonly [TagTypeId]: {\n    readonly _Service: Types.Invariant<Value>\n    readonly _Identifier: Types.Invariant<Id>\n  }\n  of(self: Value): Value\n  context(self: Value): Context<Id>\n  readonly stack?: string | undefined\n  readonly key: string\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: TagUnify<this>\n  [Unify.ignoreSymbol]?: TagUnifyIgnore\n}\n\n/**\n * @since 3.5.9\n * @category models\n */\nexport interface ReadonlyTag<in out Id, out Value> extends Pipeable, Inspectable, Effect.Effect<Value, never, Id> {\n  readonly _op: \"Tag\"\n  readonly Service: Value\n  readonly Identifier: Id\n  readonly [TagTypeId]: {\n    readonly _Service: Types.Covariant<Value>\n    readonly _Identifier: Types.Invariant<Id>\n  }\n  readonly stack?: string | undefined\n  readonly key: string\n}\n\n/**\n * @since 3.11.0\n * @category symbol\n */\nexport const ReferenceTypeId: unique symbol = internal.ReferenceTypeId\n\n/**\n * @since 3.11.0\n * @category symbol\n */\nexport type ReferenceTypeId = typeof ReferenceTypeId\n\n/**\n * @since 3.11.0\n * @category models\n */\nexport interface Reference<in out Id, in out Value> extends Pipeable, Inspectable {\n  readonly [ReferenceTypeId]: ReferenceTypeId\n  readonly defaultValue: () => Value\n\n  readonly _op: \"Tag\"\n  readonly Service: Value\n  readonly Identifier: Id\n  readonly [TagTypeId]: {\n    readonly _Service: Types.Invariant<Value>\n    readonly _Identifier: Types.Invariant<Id>\n  }\n  of(self: Value): Value\n  context(self: Value): Context<Id>\n  readonly stack?: string | undefined\n  readonly key: string\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: TagUnify<this>\n  [Unify.ignoreSymbol]?: TagUnifyIgnore\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface TagClassShape<Id, Shape> {\n  readonly [TagTypeId]: TagTypeId\n  readonly Type: Shape\n  readonly Id: Id\n}\n\n// TODO(4.0): move key narrowing to the Tag interface\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface TagClass<Self, Id extends string, Type> extends Tag<Self, Type> {\n  new(_: never): TagClassShape<Id, Type>\n  readonly key: Id\n}\n\n// TODO(4.0): move key narrowing to the Reference interface\n/**\n * @since 3.11.0\n * @category models\n */\nexport interface ReferenceClass<Self, Id extends string, Type> extends Reference<Self, Type> {\n  new(_: never): TagClassShape<Id, Type>\n  readonly key: Id\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface TagUnify<A extends { [Unify.typeSymbol]?: any }> {\n  Tag?: () => Extract<A[Unify.typeSymbol], Tag<any, any>>\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface TagUnifyIgnore {}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Tag {\n  /**\n   * @since 2.0.0\n   */\n  export type Service<T extends Tag<any, any> | TagClassShape<any, any>> = T extends Tag<any, any> ? T[\"Service\"]\n    : T extends TagClassShape<any, infer A> ? A\n    : never\n  /**\n   * @since 2.0.0\n   */\n  export type Identifier<T extends Tag<any, any> | TagClassShape<any, any>> = T extends Tag<any, any> ? T[\"Identifier\"]\n    : T extends TagClassShape<any, any> ? T\n    : never\n}\n\n/**\n * Creates a new `Tag` instance with an optional key parameter.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context } from \"effect\"\n *\n * assert.strictEqual(Context.GenericTag(\"PORT\").key === Context.GenericTag(\"PORT\").key, true)\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const GenericTag: <Identifier, Service = Identifier>(key: string) => Tag<Identifier, Service> =\n  internal.makeGenericTag\n\nconst TypeId: unique symbol = internal.TypeId as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type ValidTagsById<R> = R extends infer S ? Tag<S, any> : never\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Context<in Services> extends Equal, Pipeable, Inspectable {\n  readonly [TypeId]: {\n    readonly _Services: Types.Contravariant<Services>\n  }\n  readonly unsafeMap: Map<string, any>\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const unsafeMake: <Services>(unsafeMap: Map<string, any>) => Context<Services> = internal.makeContext\n\n/**\n * Checks if the provided argument is a `Context`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context } from \"effect\"\n *\n * assert.strictEqual(Context.isContext(Context.empty()), true)\n * ```\n *\n * @since 2.0.0\n * @category guards\n */\nexport const isContext: (input: unknown) => input is Context<never> = internal.isContext\n\n/**\n * Checks if the provided argument is a `Tag`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context } from \"effect\"\n *\n * assert.strictEqual(Context.isTag(Context.GenericTag(\"Tag\")), true)\n * ```\n *\n * @since 2.0.0\n * @category guards\n */\nexport const isTag: (input: unknown) => input is Tag<any, any> = internal.isTag\n\n/**\n * Checks if the provided argument is a `Reference`.\n *\n * @since 3.11.0\n * @category guards\n * @experimental\n */\nexport const isReference: (u: unknown) => u is Reference<any, any> = internal.isReference\n\n/**\n * Returns an empty `Context`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context } from \"effect\"\n *\n * assert.strictEqual(Context.isContext(Context.empty()), true)\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: () => Context<never> = internal.empty\n\n/**\n * Creates a new `Context` with a single service associated to the tag.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context } from \"effect\"\n *\n * const Port = Context.GenericTag<{ PORT: number }>(\"Port\")\n *\n * const Services = Context.make(Port, { PORT: 8080 })\n *\n * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 })\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <I, S>(tag: Tag<I, S>, service: Types.NoInfer<S>) => Context<I> = internal.make\n\n/**\n * Adds a service to a given `Context`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context, pipe } from \"effect\"\n *\n * const Port = Context.GenericTag<{ PORT: number }>(\"Port\")\n * const Timeout = Context.GenericTag<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const someContext = Context.make(Port, { PORT: 8080 })\n *\n * const Services = pipe(\n *   someContext,\n *   Context.add(Timeout, { TIMEOUT: 5000 })\n * )\n *\n * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 })\n * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 })\n * ```\n *\n * @since 2.0.0\n */\nexport const add: {\n  <I, S>(tag: Tag<I, S>, service: Types.NoInfer<S>): <Services>(self: Context<Services>) => Context<Services | I>\n  <Services, I, S>(self: Context<Services>, tag: Tag<I, S>, service: Types.NoInfer<S>): Context<Services | I>\n} = internal.add\n\n/**\n * Get a service from the context that corresponds to the given tag.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, Context } from \"effect\"\n *\n * const Port = Context.GenericTag<{ PORT: number }>(\"Port\")\n * const Timeout = Context.GenericTag<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const Services = pipe(\n *   Context.make(Port, { PORT: 8080 }),\n *   Context.add(Timeout, { TIMEOUT: 5000 })\n * )\n *\n * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 })\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const get: {\n  <I, S>(tag: Reference<I, S>): <Services>(self: Context<Services>) => S\n  <Services, I extends Services, S>(tag: Tag<I, S>): (self: Context<Services>) => S\n  <Services, I, S>(self: Context<Services>, tag: Reference<I, S>): S\n  <Services, I extends Services, S>(self: Context<Services>, tag: Tag<I, S>): S\n} = internal.get\n\n/**\n * Get a service from the context that corresponds to the given tag, or\n * use the fallback value.\n *\n * @since 3.7.0\n * @category getters\n */\nexport const getOrElse: {\n  <S, I, B>(tag: Tag<I, S>, orElse: LazyArg<B>): <Services>(self: Context<Services>) => S | B\n  <Services, S, I, B>(self: Context<Services>, tag: Tag<I, S>, orElse: LazyArg<B>): S | B\n} = internal.getOrElse\n\n/**\n * Get a service from the context that corresponds to the given tag.\n * This function is unsafe because if the tag is not present in the context, a runtime error will be thrown.\n *\n * For a safer version see {@link getOption}.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context } from \"effect\"\n *\n * const Port = Context.GenericTag<{ PORT: number }>(\"Port\")\n * const Timeout = Context.GenericTag<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const Services = Context.make(Port, { PORT: 8080 })\n *\n * assert.deepStrictEqual(Context.unsafeGet(Services, Port), { PORT: 8080 })\n * assert.throws(() => Context.unsafeGet(Services, Timeout))\n * ```\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeGet: {\n  <S, I>(tag: Tag<I, S>): <Services>(self: Context<Services>) => S\n  <Services, S, I>(self: Context<Services>, tag: Tag<I, S>): S\n} = internal.unsafeGet\n\n/**\n * Get the value associated with the specified tag from the context wrapped in an `Option` object. If the tag is not\n * found, the `Option` object will be `None`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context, Option } from \"effect\"\n *\n * const Port = Context.GenericTag<{ PORT: number }>(\"Port\")\n * const Timeout = Context.GenericTag<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const Services = Context.make(Port, { PORT: 8080 })\n *\n * assert.deepStrictEqual(Context.getOption(Services, Port), Option.some({ PORT: 8080 }))\n * assert.deepStrictEqual(Context.getOption(Services, Timeout), Option.none())\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const getOption: {\n  <S, I>(tag: Tag<I, S>): <Services>(self: Context<Services>) => Option<S>\n  <Services, S, I>(self: Context<Services>, tag: Tag<I, S>): Option<S>\n} = internal.getOption\n\n/**\n * Merges two `Context`s, returning a new `Context` containing the services of both.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context } from \"effect\"\n *\n * const Port = Context.GenericTag<{ PORT: number }>(\"Port\")\n * const Timeout = Context.GenericTag<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const firstContext = Context.make(Port, { PORT: 8080 })\n * const secondContext = Context.make(Timeout, { TIMEOUT: 5000 })\n *\n * const Services = Context.merge(firstContext, secondContext)\n *\n * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 })\n * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 })\n * ```\n *\n * @since 2.0.0\n */\nexport const merge: {\n  <R1>(that: Context<R1>): <Services>(self: Context<Services>) => Context<R1 | Services>\n  <Services, R1>(self: Context<Services>, that: Context<R1>): Context<Services | R1>\n} = internal.merge\n\n/**\n * Merges any number of `Context`s, returning a new `Context` containing the services of all.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context } from \"effect\"\n *\n * const Port = Context.GenericTag<{ PORT: number }>(\"Port\")\n * const Timeout = Context.GenericTag<{ TIMEOUT: number }>(\"Timeout\")\n * const Host = Context.GenericTag<{ HOST: string }>(\"Host\")\n *\n * const firstContext = Context.make(Port, { PORT: 8080 })\n * const secondContext = Context.make(Timeout, { TIMEOUT: 5000 })\n * const thirdContext = Context.make(Host, { HOST: \"localhost\" })\n *\n * const Services = Context.mergeAll(firstContext, secondContext, thirdContext)\n *\n * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 })\n * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 })\n * assert.deepStrictEqual(Context.get(Services, Host), { HOST: \"localhost\" })\n * ```\n *\n * @since 3.12.0\n */\nexport const mergeAll: <T extends Array<unknown>>(\n  ...ctxs: [...{ [K in keyof T]: Context<T[K]> }]\n) => Context<T[number]> = internal.mergeAll\n\n/**\n * Returns a new `Context` that contains only the specified services.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, Context, Option } from \"effect\"\n *\n * const Port = Context.GenericTag<{ PORT: number }>(\"Port\")\n * const Timeout = Context.GenericTag<{ TIMEOUT: number }>(\"Timeout\")\n *\n * const someContext = pipe(\n *   Context.make(Port, { PORT: 8080 }),\n *   Context.add(Timeout, { TIMEOUT: 5000 })\n * )\n *\n * const Services = pipe(someContext, Context.pick(Port))\n *\n * assert.deepStrictEqual(Context.getOption(Services, Port), Option.some({ PORT: 8080 }))\n * assert.deepStrictEqual(Context.getOption(Services, Timeout), Option.none())\n * ```\n *\n * @since 2.0.0\n */\nexport const pick: <Tags extends ReadonlyArray<Tag<any, any>>>(\n  ...tags: Tags\n) => <Services>(self: Context<Services>) => Context<Services & Tag.Identifier<Tags[number]>> = internal.pick\n\n/**\n * @since 2.0.0\n */\nexport const omit: <Tags extends ReadonlyArray<Tag<any, any>>>(\n  ...tags: Tags\n) => <Services>(self: Context<Services>) => Context<Exclude<Services, Tag.Identifier<Tags[number]>>> = internal.omit\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context, Layer } from \"effect\"\n *\n * class MyTag extends Context.Tag(\"MyTag\")<\n *  MyTag,\n *  { readonly myNum: number }\n * >() {\n *  static Live = Layer.succeed(this, { myNum: 108 })\n * }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const Tag: <const Id extends string>(id: Id) => <Self, Shape>() => TagClass<Self, Id, Shape> = internal.Tag\n\n/**\n * Creates a context tag with a default value.\n *\n * **Details**\n *\n * `Context.Reference` allows you to create a tag that can hold a value. You can\n * provide a default value for the service, which will automatically be used\n * when the context is accessed, or override it with a custom implementation\n * when needed.\n *\n * **Example** (Declaring a Tag with a default value)\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Context, Effect } from \"effect\"\n *\n * class SpecialNumber extends Context.Reference<SpecialNumber>()(\n *   \"SpecialNumber\",\n *   { defaultValue: () => 2048 }\n * ) {}\n *\n * //      ┌─── Effect<void, never, never>\n * //      ▼\n * const program = Effect.gen(function* () {\n *   const specialNumber = yield* SpecialNumber\n *   console.log(`The special number is ${specialNumber}`)\n * })\n *\n * // No need to provide the SpecialNumber implementation\n * Effect.runPromise(program)\n * // Output: The special number is 2048\n * ```\n *\n * **Example** (Overriding the default value)\n *\n * ```ts\n * import { Context, Effect } from \"effect\"\n *\n * class SpecialNumber extends Context.Reference<SpecialNumber>()(\n *   \"SpecialNumber\",\n *   { defaultValue: () => 2048 }\n * ) {}\n *\n * const program = Effect.gen(function* () {\n *   const specialNumber = yield* SpecialNumber\n *   console.log(`The special number is ${specialNumber}`)\n * })\n *\n * Effect.runPromise(program.pipe(Effect.provideService(SpecialNumber, -1)))\n * // Output: The special number is -1\n * ```\n *\n * @since 3.11.0\n * @category constructors\n * @experimental\n */\nexport const Reference: <Self>() => <const Id extends string, Service>(\n  id: Id,\n  options: { readonly defaultValue: () => Service }\n) => ReferenceClass<Self, Id, Service> = internal.Reference\n"
  },
  {
    "path": "packages/effect/src/Cron.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Arr from \"./Array.js\"\nimport * as Data from \"./Data.js\"\nimport type * as DateTime from \"./DateTime.js\"\nimport * as Either from \"./Either.js\"\nimport * as Equal from \"./Equal.js\"\nimport * as equivalence from \"./Equivalence.js\"\nimport { constVoid, dual, identity, pipe } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport { format, type Inspectable, NodeInspectSymbol } from \"./Inspectable.js\"\nimport * as dateTime from \"./internal/dateTime.js\"\nimport * as N from \"./Number.js\"\nimport * as Option from \"./Option.js\"\nimport { type Pipeable, pipeArguments } from \"./Pipeable.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport * as String from \"./String.js\"\nimport type { Mutable } from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/Cron\")\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Cron extends Pipeable, Equal.Equal, Inspectable {\n  readonly [TypeId]: TypeId\n  readonly tz: Option.Option<DateTime.TimeZone>\n  readonly seconds: ReadonlySet<number>\n  readonly minutes: ReadonlySet<number>\n  readonly hours: ReadonlySet<number>\n  readonly days: ReadonlySet<number>\n  readonly months: ReadonlySet<number>\n  readonly weekdays: ReadonlySet<number>\n  /** @internal */\n  readonly first: {\n    readonly second: number\n    readonly minute: number\n    readonly hour: number\n    readonly day: number\n    readonly month: number\n    readonly weekday: number\n  }\n  /** @internal */\n  readonly last: {\n    readonly second: number\n    readonly minute: number\n    readonly hour: number\n    readonly day: number\n    readonly month: number\n    readonly weekday: number\n  }\n  /** @internal */\n  readonly next: {\n    readonly second: ReadonlyArray<number | undefined>\n    readonly minute: ReadonlyArray<number | undefined>\n    readonly hour: ReadonlyArray<number | undefined>\n    readonly day: ReadonlyArray<number | undefined>\n    readonly month: ReadonlyArray<number | undefined>\n    readonly weekday: ReadonlyArray<number | undefined>\n  }\n  /** @internal */\n  readonly prev: {\n    readonly second: ReadonlyArray<number | undefined>\n    readonly minute: ReadonlyArray<number | undefined>\n    readonly hour: ReadonlyArray<number | undefined>\n    readonly day: ReadonlyArray<number | undefined>\n    readonly month: ReadonlyArray<number | undefined>\n    readonly weekday: ReadonlyArray<number | undefined>\n  }\n}\n\nconst CronProto = {\n  [TypeId]: TypeId,\n  [Equal.symbol](this: Cron, that: unknown) {\n    return isCron(that) && equals(this, that)\n  },\n  [Hash.symbol](this: Cron): number {\n    return pipe(\n      Hash.hash(this.tz),\n      Hash.combine(Hash.array(Arr.fromIterable(this.seconds))),\n      Hash.combine(Hash.array(Arr.fromIterable(this.minutes))),\n      Hash.combine(Hash.array(Arr.fromIterable(this.hours))),\n      Hash.combine(Hash.array(Arr.fromIterable(this.days))),\n      Hash.combine(Hash.array(Arr.fromIterable(this.months))),\n      Hash.combine(Hash.array(Arr.fromIterable(this.weekdays))),\n      Hash.cached(this)\n    )\n  },\n  toString(this: Cron) {\n    return format(this.toJSON())\n  },\n  toJSON(this: Cron) {\n    return {\n      _id: \"Cron\",\n      tz: this.tz,\n      seconds: Arr.fromIterable(this.seconds),\n      minutes: Arr.fromIterable(this.minutes),\n      hours: Arr.fromIterable(this.hours),\n      days: Arr.fromIterable(this.days),\n      months: Arr.fromIterable(this.months),\n      weekdays: Arr.fromIterable(this.weekdays)\n    }\n  },\n  [NodeInspectSymbol](this: Cron) {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/**\n * Checks if a given value is a `Cron` instance.\n *\n * @since 2.0.0\n * @category guards\n */\nexport const isCron = (u: unknown): u is Cron => hasProperty(u, TypeId)\n\n/**\n * Creates a `Cron` instance.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make = (values: {\n  readonly seconds?: Iterable<number> | undefined\n  readonly minutes: Iterable<number>\n  readonly hours: Iterable<number>\n  readonly days: Iterable<number>\n  readonly months: Iterable<number>\n  readonly weekdays: Iterable<number>\n  readonly tz?: DateTime.TimeZone | undefined\n}): Cron => {\n  const o: Mutable<Cron> = Object.create(CronProto)\n  o.seconds = new Set(Arr.sort(values.seconds ?? [0], N.Order))\n  o.minutes = new Set(Arr.sort(values.minutes, N.Order))\n  o.hours = new Set(Arr.sort(values.hours, N.Order))\n  o.days = new Set(Arr.sort(values.days, N.Order))\n  o.months = new Set(Arr.sort(values.months, N.Order))\n  o.weekdays = new Set(Arr.sort(values.weekdays, N.Order))\n  o.tz = Option.fromNullable(values.tz)\n\n  const seconds = Array.from(o.seconds)\n  const minutes = Array.from(o.minutes)\n  const hours = Array.from(o.hours)\n  const days = Array.from(o.days)\n  const months = Array.from(o.months)\n  const weekdays = Array.from(o.weekdays)\n\n  o.first = {\n    second: seconds[0] ?? 0,\n    minute: minutes[0] ?? 0,\n    hour: hours[0] ?? 0,\n    day: days[0] ?? 1,\n    month: (months[0] ?? 1) - 1,\n    weekday: weekdays[0] ?? 0\n  }\n\n  o.last = {\n    second: seconds[seconds.length - 1] ?? 59,\n    minute: minutes[minutes.length - 1] ?? 59,\n    hour: hours[hours.length - 1] ?? 23,\n    day: days[days.length - 1] ?? 31,\n    month: (months[months.length - 1] ?? 12) - 1,\n    weekday: weekdays[weekdays.length - 1] ?? 6\n  }\n\n  o.next = {\n    second: lookupTable(seconds, 60, \"next\"),\n    minute: lookupTable(minutes, 60, \"next\"),\n    hour: lookupTable(hours, 24, \"next\"),\n    day: lookupTable(days, 32, \"next\"),\n    month: lookupTable(months, 13, \"next\"),\n    weekday: lookupTable(weekdays, 7, \"next\")\n  }\n\n  o.prev = {\n    second: lookupTable(seconds, 60, \"prev\"),\n    minute: lookupTable(minutes, 60, \"prev\"),\n    hour: lookupTable(hours, 24, \"prev\"),\n    day: lookupTable(days, 32, \"prev\"),\n    month: lookupTable(months, 13, \"prev\"),\n    weekday: lookupTable(weekdays, 7, \"prev\")\n  }\n\n  return o\n}\n\nconst lookupTable = (\n  values: ReadonlyArray<number>,\n  size: number,\n  dir: \"next\" | \"prev\"\n): Array<number | undefined> => {\n  const result = new Array(size).fill(undefined)\n  if (values.length === 0) {\n    return result\n  }\n\n  let current: number | undefined = undefined\n\n  if (dir === \"next\") {\n    let index = values.length - 1\n    for (let i = size - 1; i >= 0; i--) {\n      while (index >= 0 && values[index] >= i) {\n        current = values[index--]\n      }\n      result[i] = current\n    }\n  } else {\n    let index = 0\n    for (let i = 0; i < size; i++) {\n      while (index < values.length && values[index] <= i) {\n        current = values[index++]\n      }\n      result[i] = current\n    }\n  }\n\n  return result\n}\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport const ParseErrorTypeId: unique symbol = Symbol.for(\"effect/Cron/errors/ParseError\")\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ParseErrorTypeId = typeof ParseErrorTypeId\n\n/**\n * Represents a checked exception which occurs when decoding fails.\n *\n * @since 2.0.0\n * @category models\n */\nexport class ParseError extends Data.TaggedError(\"CronParseError\")<{\n  readonly message: string\n  readonly input?: string\n}> {\n  /**\n   * @since 2.0.0\n   */\n  readonly [ParseErrorTypeId] = ParseErrorTypeId\n}\n\n/**\n * Returns `true` if the specified value is an `ParseError`, `false` otherwise.\n *\n * @since 2.0.0\n * @category guards\n */\nexport const isParseError = (u: unknown): u is ParseError => hasProperty(u, ParseErrorTypeId)\n\n/**\n * Parses a cron expression into a `Cron` instance.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Cron, Either } from \"effect\"\n *\n * // At 04:00 on every day-of-month from 8 through 14.\n * assert.deepStrictEqual(Cron.parse(\"0 0 4 8-14 * *\"), Either.right(Cron.make({\n *   seconds: [0],\n *   minutes: [0],\n *   hours: [4],\n *   days: [8, 9, 10, 11, 12, 13, 14],\n *   months: [],\n *   weekdays: []\n * })))\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const parse = (cron: string, tz?: DateTime.TimeZone | string): Either.Either<Cron, ParseError> => {\n  const segments = cron.split(\" \").filter(String.isNonEmpty)\n  if (segments.length !== 5 && segments.length !== 6) {\n    return Either.left(\n      new ParseError({\n        message: `Invalid number of segments in cron expression`,\n        input: cron\n      })\n    )\n  }\n\n  if (segments.length === 5) {\n    segments.unshift(\"0\")\n  }\n\n  const [seconds, minutes, hours, days, months, weekdays] = segments\n  const zone = tz === undefined || dateTime.isTimeZone(tz) ?\n    Either.right(tz) :\n    Either.fromOption(dateTime.zoneFromString(tz), () =>\n      new ParseError({\n        message: `Invalid time zone in cron expression`,\n        input: tz\n      }))\n\n  return Either.all({\n    tz: zone,\n    seconds: parseSegment(seconds, secondOptions),\n    minutes: parseSegment(minutes, minuteOptions),\n    hours: parseSegment(hours, hourOptions),\n    days: parseSegment(days, dayOptions),\n    months: parseSegment(months, monthOptions),\n    weekdays: parseSegment(weekdays, weekdayOptions)\n  }).pipe(Either.map(make))\n}\n\n/**\n * Parses a cron expression into a `Cron` instance.\n *\n * **Details**\n *\n * This function takes a cron expression as a string and attempts to parse it\n * into a `Cron` instance. If the expression is valid, the resulting `Cron`\n * instance will represent the schedule defined by the cron expression.\n *\n * If the expression is invalid, the function throws a `ParseError`.\n *\n * You can optionally provide a time zone (`tz`) to interpret the cron\n * expression in a specific time zone. If no time zone is provided, the cron\n * expression will use the default time zone.\n *\n * @example\n * ```ts\n * import { Cron } from \"effect\"\n *\n * // At 04:00 on every day-of-month from 8 through 14.\n * console.log(Cron.unsafeParse(\"0 4 8-14 * *\"))\n * // Output:\n * // {\n * //   _id: 'Cron',\n * //   tz: { _id: 'Option', _tag: 'None' },\n * //   seconds: [ 0 ],\n * //   minutes: [ 0 ],\n * //   hours: [ 4 ],\n * //   days: [\n * //      8,  9, 10, 11,\n * //     12, 13, 14\n * //   ],\n * //   months: [],\n * //   weekdays: []\n * // }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unsafeParse = (cron: string, tz?: DateTime.TimeZone | string): Cron =>\n  Either.getOrThrowWith(parse(cron, tz), identity)\n\n/**\n * Checks if a given `Date` falls within an active `Cron` time window.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Cron, Either } from \"effect\"\n *\n * const cron = Either.getOrThrow(Cron.parse(\"0 4 8-14 * *\"))\n * assert.deepStrictEqual(Cron.match(cron, new Date(\"2021-01-08 04:00:00\")), true)\n * assert.deepStrictEqual(Cron.match(cron, new Date(\"2021-01-08 05:00:00\")), false)\n * ```\n *\n * @throws `IllegalArgumentException` if the given `DateTime.Input` is invalid.\n *\n * @since 2.0.0\n */\nexport const match = (cron: Cron, date: DateTime.DateTime.Input): boolean => {\n  const parts = dateTime.unsafeMakeZoned(date, {\n    timeZone: Option.getOrUndefined(cron.tz)\n  }).pipe(dateTime.toParts)\n\n  if (cron.seconds.size !== 0 && !cron.seconds.has(parts.seconds)) {\n    return false\n  }\n\n  if (cron.minutes.size !== 0 && !cron.minutes.has(parts.minutes)) {\n    return false\n  }\n\n  if (cron.hours.size !== 0 && !cron.hours.has(parts.hours)) {\n    return false\n  }\n\n  if (cron.months.size !== 0 && !cron.months.has(parts.month)) {\n    return false\n  }\n\n  if (cron.days.size === 0 && cron.weekdays.size === 0) {\n    return true\n  }\n\n  if (cron.weekdays.size === 0) {\n    return cron.days.has(parts.day)\n  }\n\n  if (cron.days.size === 0) {\n    return cron.weekdays.has(parts.weekDay)\n  }\n\n  return cron.days.has(parts.day) || cron.weekdays.has(parts.weekDay)\n}\n\nconst daysInMonth = (date: Date): number =>\n  new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate()\n\n/**\n * Returns the next run `Date` for the given `Cron` instance.\n *\n * Uses the current time as a starting point if no value is provided for `startFrom`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Cron, Either } from \"effect\"\n *\n * const after = new Date(\"2021-01-01 00:00:00\")\n * const cron = Either.getOrThrow(Cron.parse(\"0 4 8-14 * *\"))\n * assert.deepStrictEqual(Cron.next(cron, after), new Date(\"2021-01-08 04:00:00\"))\n * ```\n *\n * @throws `IllegalArgumentException` if the given `DateTime.Input` is invalid.\n * @throws `Error` if the next run date cannot be found within 10,000 iterations.\n *\n * @since 2.0.0\n */\nexport const next = (cron: Cron, startFrom?: DateTime.DateTime.Input): Date => {\n  return stepCron(cron, startFrom, \"next\")\n}\n\n/**\n * Returns the previous run `Date` for the given `Cron` instance.\n *\n * Uses the current time as a starting point if no value is provided for `startFrom`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Cron, Either } from \"effect\"\n *\n * const before = new Date(\"2021-01-15 00:00:00\")\n * const cron = Either.getOrThrow(Cron.parse(\"0 4 8-14 * *\"))\n * assert.deepStrictEqual(Cron.prev(cron, before), new Date(\"2021-01-14 04:00:00\"))\n * ```\n *\n * @throws `IllegalArgumentException` if the given `DateTime.Input` is invalid.\n * @throws `Error` if the previous run date cannot be found within 10,000 iterations.\n *\n * @since 3.20.0\n */\nexport const prev = (cron: Cron, startFrom?: DateTime.DateTime.Input): Date => {\n  return stepCron(cron, startFrom, \"prev\")\n}\n\n/** @internal */\nconst stepCron = (cron: Cron, startFrom: DateTime.DateTime.Input | undefined, direction: \"next\" | \"prev\"): Date => {\n  const tz = Option.getOrUndefined(cron.tz)\n  const zoned = dateTime.unsafeMakeZoned(startFrom ?? new Date(), {\n    timeZone: tz\n  })\n\n  const prev = direction === \"prev\"\n  const tick = prev ? -1 : 1\n  const table = cron[direction]\n  const boundary = prev ? cron.last : cron.first\n\n  const needsStep = prev\n    ? (next: number, current: number) => next < current\n    : (next: number, current: number) => next > current\n\n  const utc = tz !== undefined && dateTime.isTimeZoneNamed(tz) && tz.id === \"UTC\"\n  const adjustDst = utc ? constVoid : (current: Date) => {\n    const adjusted = dateTime.unsafeMakeZoned(current, {\n      timeZone: zoned.zone,\n      adjustForTimeZone: true,\n      disambiguation: prev ? \"later\" : undefined\n    }).pipe(dateTime.toDate)\n\n    const drift = current.getTime() - adjusted.getTime()\n    if (prev ? drift !== 0 : drift > 0) {\n      current.setTime(adjusted.getTime())\n    }\n  }\n\n  const result = dateTime.mutate(zoned, (current) => {\n    current.setUTCSeconds(current.getUTCSeconds() + tick, 0)\n\n    for (let i = 0; i < 10_000; i++) {\n      if (cron.seconds.size !== 0) {\n        const currentSecond = current.getUTCSeconds()\n        const nextSecond = table.second[currentSecond]\n        if (nextSecond === undefined) {\n          current.setUTCMinutes(current.getUTCMinutes() + tick, boundary.second)\n          adjustDst(current)\n          continue\n        }\n        if (needsStep(nextSecond, currentSecond)) {\n          current.setUTCSeconds(nextSecond)\n          adjustDst(current)\n          continue\n        }\n      }\n\n      if (cron.minutes.size !== 0) {\n        const currentMinute = current.getUTCMinutes()\n        const nextMinute = table.minute[currentMinute]\n        if (nextMinute === undefined) {\n          current.setUTCHours(current.getUTCHours() + tick, boundary.minute, boundary.second)\n          adjustDst(current)\n          continue\n        }\n        if (needsStep(nextMinute, currentMinute)) {\n          current.setUTCMinutes(nextMinute, boundary.second)\n          adjustDst(current)\n          continue\n        }\n      }\n\n      if (cron.hours.size !== 0) {\n        const currentHour = current.getUTCHours()\n        const nextHour = table.hour[currentHour]\n        if (nextHour === undefined) {\n          current.setUTCDate(current.getUTCDate() + tick)\n          current.setUTCHours(boundary.hour, boundary.minute, boundary.second)\n          adjustDst(current)\n          continue\n        }\n        if (needsStep(nextHour, currentHour)) {\n          current.setUTCHours(nextHour, boundary.minute, boundary.second)\n          adjustDst(current)\n          continue\n        }\n      }\n\n      if (cron.weekdays.size !== 0 || cron.days.size !== 0) {\n        let a: number = prev ? -Infinity : Infinity\n        let b: number = prev ? -Infinity : Infinity\n\n        if (cron.weekdays.size !== 0) {\n          const currentWeekday = current.getUTCDay()\n          const nextWeekday = table.weekday[currentWeekday]\n          if (nextWeekday === undefined) {\n            a = prev\n              ? currentWeekday - 7 + boundary.weekday\n              : 7 - currentWeekday + boundary.weekday\n          } else {\n            a = nextWeekday - currentWeekday\n          }\n        }\n\n        // Only check day-of-month if weekday constraint not already satisfied (they're OR'd)\n        if (cron.days.size !== 0 && a !== 0) {\n          const currentDay = current.getUTCDate()\n          const nextDay = table.day[currentDay]\n          if (nextDay === undefined) {\n            if (prev) {\n              // When wrapping to previous month, calculate days back:\n              // Current day offset + gap from end of prev month to target day\n              // Example: June 3 → May 20 with boundary.day=20: -(3 + (31 - 20)) = -14\n              const prevMonthDays = daysInMonth(\n                new Date(Date.UTC(current.getUTCFullYear(), current.getUTCMonth(), 0))\n              )\n              b = -(currentDay + (prevMonthDays - boundary.day))\n            } else {\n              b = daysInMonth(current) - currentDay + boundary.day\n            }\n          } else {\n            b = nextDay - currentDay\n          }\n        }\n\n        const addDays = prev ? Math.max(a, b) : Math.min(a, b)\n        if (addDays !== 0) {\n          current.setUTCDate(current.getUTCDate() + addDays)\n          current.setUTCHours(boundary.hour, boundary.minute, boundary.second)\n          adjustDst(current)\n          continue\n        }\n      }\n\n      if (cron.months.size !== 0) {\n        const currentMonth = current.getUTCMonth() + 1\n        const nextMonth = table.month[currentMonth]\n        const clampBoundaryDay = (targetMonthIndex: number): number => {\n          if (cron.days.size !== 0) {\n            return boundary.day\n          }\n          const maxDayInMonth = daysInMonth(new Date(Date.UTC(current.getUTCFullYear(), targetMonthIndex, 1)))\n          return Math.min(boundary.day, maxDayInMonth)\n        }\n        if (nextMonth === undefined) {\n          current.setUTCFullYear(current.getUTCFullYear() + tick)\n          current.setUTCMonth(boundary.month, clampBoundaryDay(boundary.month))\n          current.setUTCHours(boundary.hour, boundary.minute, boundary.second)\n          adjustDst(current)\n          continue\n        }\n        if (needsStep(nextMonth, currentMonth)) {\n          const targetMonthIndex = nextMonth - 1\n          current.setUTCMonth(targetMonthIndex, clampBoundaryDay(targetMonthIndex))\n          current.setUTCHours(boundary.hour, boundary.minute, boundary.second)\n          adjustDst(current)\n          continue\n        }\n      }\n\n      return\n    }\n\n    throw new Error(\"Unable to find next cron date\")\n  })\n\n  return dateTime.toDateUtc(result)\n}\n\n/**\n * Returns an `IterableIterator` which yields the sequence of `Date`s that match the `Cron` instance.\n *\n * @since 2.0.0\n */\nexport const sequence = function*(cron: Cron, startFrom?: DateTime.DateTime.Input): IterableIterator<Date> {\n  while (true) {\n    yield startFrom = next(cron, startFrom)\n  }\n}\n\n/**\n * Returns an `IterableIterator` which yields the sequence of `Date`s that match the `Cron` instance,\n * in reverse direction.\n *\n * @since 3.20.0\n */\nexport const sequenceReverse = function*(cron: Cron, startFrom?: DateTime.DateTime.Input): IterableIterator<Date> {\n  while (true) {\n    yield startFrom = prev(cron, startFrom)\n  }\n}\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence: equivalence.Equivalence<Cron> = equivalence.make((self, that) =>\n  restrictionsEquals(self.seconds, that.seconds) &&\n  restrictionsEquals(self.minutes, that.minutes) &&\n  restrictionsEquals(self.hours, that.hours) &&\n  restrictionsEquals(self.days, that.days) &&\n  restrictionsEquals(self.months, that.months) &&\n  restrictionsEquals(self.weekdays, that.weekdays)\n)\n\nconst restrictionsArrayEquals = equivalence.array(equivalence.number)\nconst restrictionsEquals = (self: ReadonlySet<number>, that: ReadonlySet<number>): boolean =>\n  restrictionsArrayEquals(Arr.fromIterable(self), Arr.fromIterable(that))\n\n/**\n * Checks if two `Cron`s are equal.\n *\n * @since 2.0.0\n * @category predicates\n */\nexport const equals: {\n  (that: Cron): (self: Cron) => boolean\n  (self: Cron, that: Cron): boolean\n} = dual(2, (self: Cron, that: Cron): boolean => Equivalence(self, that))\n\ninterface SegmentOptions {\n  min: number\n  max: number\n  aliases?: Record<string, number> | undefined\n}\n\nconst secondOptions: SegmentOptions = {\n  min: 0,\n  max: 59\n}\n\nconst minuteOptions: SegmentOptions = {\n  min: 0,\n  max: 59\n}\n\nconst hourOptions: SegmentOptions = {\n  min: 0,\n  max: 23\n}\n\nconst dayOptions: SegmentOptions = {\n  min: 1,\n  max: 31\n}\n\nconst monthOptions: SegmentOptions = {\n  min: 1,\n  max: 12,\n  aliases: {\n    jan: 1,\n    feb: 2,\n    mar: 3,\n    apr: 4,\n    may: 5,\n    jun: 6,\n    jul: 7,\n    aug: 8,\n    sep: 9,\n    oct: 10,\n    nov: 11,\n    dec: 12\n  }\n}\n\nconst weekdayOptions: SegmentOptions = {\n  min: 0,\n  max: 6,\n  aliases: {\n    sun: 0,\n    mon: 1,\n    tue: 2,\n    wed: 3,\n    thu: 4,\n    fri: 5,\n    sat: 6\n  }\n}\n\nconst parseSegment = (\n  input: string,\n  options: SegmentOptions\n): Either.Either<ReadonlySet<number>, ParseError> => {\n  const capacity = options.max - options.min + 1\n  const values = new Set<number>()\n  const fields = input.split(\",\")\n\n  for (const field of fields) {\n    const [raw, step] = splitStep(field)\n    if (raw === \"*\" && step === undefined) {\n      return Either.right(new Set())\n    }\n\n    if (step !== undefined) {\n      if (!Number.isInteger(step)) {\n        return Either.left(new ParseError({ message: `Expected step value to be a positive integer`, input }))\n      }\n      if (step < 1) {\n        return Either.left(new ParseError({ message: `Expected step value to be greater than 0`, input }))\n      }\n      if (step > options.max) {\n        return Either.left(new ParseError({ message: `Expected step value to be less than ${options.max}`, input }))\n      }\n    }\n\n    if (raw === \"*\") {\n      for (let i = options.min; i <= options.max; i += step ?? 1) {\n        values.add(i)\n      }\n    } else {\n      const [left, right] = splitRange(raw, options.aliases)\n      if (!Number.isInteger(left)) {\n        return Either.left(new ParseError({ message: `Expected a positive integer`, input }))\n      }\n      if (left < options.min || left > options.max) {\n        return Either.left(\n          new ParseError({ message: `Expected a value between ${options.min} and ${options.max}`, input })\n        )\n      }\n\n      if (right === undefined) {\n        values.add(left)\n      } else {\n        if (!Number.isInteger(right)) {\n          return Either.left(new ParseError({ message: `Expected a positive integer`, input }))\n        }\n        if (right < options.min || right > options.max) {\n          return Either.left(\n            new ParseError({ message: `Expected a value between ${options.min} and ${options.max}`, input })\n          )\n        }\n        if (left > right) {\n          return Either.left(new ParseError({ message: `Invalid value range`, input }))\n        }\n\n        for (let i = left; i <= right; i += step ?? 1) {\n          values.add(i)\n        }\n      }\n    }\n\n    if (values.size >= capacity) {\n      return Either.right(new Set())\n    }\n  }\n\n  return Either.right(values)\n}\n\nconst splitStep = (input: string): [string, number | undefined] => {\n  const seperator = input.indexOf(\"/\")\n  if (seperator !== -1) {\n    return [input.slice(0, seperator), Number(input.slice(seperator + 1))]\n  }\n\n  return [input, undefined]\n}\n\nconst splitRange = (input: string, aliases?: Record<string, number>): [number, number | undefined] => {\n  const seperator = input.indexOf(\"-\")\n  if (seperator !== -1) {\n    return [aliasOrValue(input.slice(0, seperator), aliases), aliasOrValue(input.slice(seperator + 1), aliases)]\n  }\n\n  return [aliasOrValue(input, aliases), undefined]\n}\n\nfunction aliasOrValue(field: string, aliases?: Record<string, number>): number {\n  return aliases?.[field.toLocaleLowerCase()] ?? Number(field)\n}\n"
  },
  {
    "path": "packages/effect/src/Data.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport * as core from \"./internal/core.js\"\nimport * as internal from \"./internal/data.js\"\nimport { StructuralPrototype } from \"./internal/effectable.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport type * as Types from \"./Types.js\"\nimport type { Unify } from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Case {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Constructor<A, Tag extends keyof A = never> {\n    (\n      args: Types.VoidIfEmpty<{ readonly [P in keyof A as P extends Tag ? never : P]: A[P] }>\n    ): A\n  }\n}\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Data, Equal } from \"effect\"\n *\n * const alice = Data.struct({ name: \"Alice\", age: 30 })\n *\n * const bob = Data.struct({ name: \"Bob\", age: 40 })\n *\n * assert.deepStrictEqual(Equal.equals(alice, alice), true)\n * assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: \"Alice\", age: 30 })), true)\n *\n * assert.deepStrictEqual(Equal.equals(alice, { name: \"Alice\", age: 30 }), false)\n * assert.deepStrictEqual(Equal.equals(alice, bob), false)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const struct: <A extends Record<string, any>>(a: A) => { readonly [P in keyof A]: A[P] } = internal.struct\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport const unsafeStruct = <A extends Record<string, any>>(as: A): { readonly [P in keyof A]: A[P] } =>\n  Object.setPrototypeOf(as, StructuralPrototype)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Data, Equal } from \"effect\"\n *\n * const alice = Data.tuple(\"Alice\", 30)\n *\n * const bob = Data.tuple(\"Bob\", 40)\n *\n * assert.deepStrictEqual(Equal.equals(alice, alice), true)\n * assert.deepStrictEqual(Equal.equals(alice, Data.tuple(\"Alice\", 30)), true)\n *\n * assert.deepStrictEqual(Equal.equals(alice, [\"Alice\", 30]), false)\n * assert.deepStrictEqual(Equal.equals(alice, bob), false)\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const tuple = <As extends ReadonlyArray<any>>(...as: As): Readonly<As> => unsafeArray(as)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Data, Equal } from \"effect\"\n *\n * const alice = Data.struct({ name: \"Alice\", age: 30 })\n * const bob = Data.struct({ name: \"Bob\", age: 40 })\n *\n * const persons = Data.array([alice, bob])\n *\n * assert.deepStrictEqual(\n *   Equal.equals(\n *     persons,\n *     Data.array([\n *       Data.struct({ name: \"Alice\", age: 30 }),\n *       Data.struct({ name: \"Bob\", age: 40 })\n *     ])\n *   ),\n *   true\n * )\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const array = <As extends ReadonlyArray<any>>(as: As): Readonly<As> => unsafeArray(as.slice(0) as unknown as As)\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport const unsafeArray = <As extends ReadonlyArray<any>>(as: As): Readonly<As> =>\n  Object.setPrototypeOf(as, internal.ArrayProto)\n\nconst _case = <A>(): Case.Constructor<A> => (args) =>\n  (args === undefined ? Object.create(StructuralPrototype) : struct(args)) as any\n\nexport {\n  /**\n   * Provides a constructor for the specified `Case`.\n   *\n   * @example\n   * ```ts\n   * import * as assert from \"node:assert\"\n   * import { Data, Equal } from \"effect\"\n   *\n   * interface Person {\n   *   readonly name: string\n   * }\n   *\n   * // Creating a constructor for the specified Case\n   * const Person = Data.case<Person>()\n   *\n   * // Creating instances of Person\n   * const mike1 = Person({ name: \"Mike\" })\n   * const mike2 = Person({ name: \"Mike\" })\n   * const john = Person({ name: \"John\" })\n   *\n   * // Checking equality\n   * assert.deepStrictEqual(Equal.equals(mike1, mike2), true)\n   * assert.deepStrictEqual(Equal.equals(mike1, john), false)\n   *\n   * ```\n   * @since 2.0.0\n   * @category constructors\n   */\n  _case as case\n}\n\n/**\n * Provides a tagged constructor for the specified `Case`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Data } from \"effect\"\n *\n * interface Person {\n *   readonly _tag: \"Person\" // the tag\n *   readonly name: string\n * }\n *\n * const Person = Data.tagged<Person>(\"Person\")\n *\n * const mike = Person({ name: \"Mike\" })\n *\n * assert.deepEqual(mike, { _tag: \"Person\", name: \"Mike\" })\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const tagged = <A extends { readonly _tag: string }>(\n  tag: A[\"_tag\"]\n): Case.Constructor<A, \"_tag\"> =>\n(args) => {\n  const value = args === undefined ? Object.create(StructuralPrototype) : struct(args)\n  value._tag = tag\n  return value\n}\n\n/**\n * Provides a constructor for a Case Class.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Data, Equal } from \"effect\"\n *\n * class Person extends Data.Class<{ readonly name: string }> {}\n *\n * // Creating instances of Person\n * const mike1 = new Person({ name: \"Mike\" })\n * const mike2 = new Person({ name: \"Mike\" })\n * const john = new Person({ name: \"John\" })\n *\n * // Checking equality\n * assert.deepStrictEqual(Equal.equals(mike1, mike2), true)\n * assert.deepStrictEqual(Equal.equals(mike1, john), false)\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const Class: new<A extends Record<string, any> = {}>(\n  args: Types.VoidIfEmpty<{ readonly [P in keyof A]: A[P] }>\n) => Readonly<A> = internal.Structural as any\n\n/**\n * Provides a Tagged constructor for a Case Class.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Data, Equal } from \"effect\"\n *\n * class Person extends Data.TaggedClass(\"Person\")<{ readonly name: string }> {}\n *\n * // Creating instances of Person\n * const mike1 = new Person({ name: \"Mike\" })\n * const mike2 = new Person({ name: \"Mike\" })\n * const john = new Person({ name: \"John\" })\n *\n * // Checking equality\n * assert.deepStrictEqual(Equal.equals(mike1, mike2), true)\n * assert.deepStrictEqual(Equal.equals(mike1, john), false)\n *\n * assert.deepStrictEqual(mike1._tag, \"Person\")\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const TaggedClass = <Tag extends string>(\n  tag: Tag\n): new<A extends Record<string, any> = {}>(\n  args: Types.VoidIfEmpty<{ readonly [P in keyof A as P extends \"_tag\" ? never : P]: A[P] }>\n) => Readonly<A> & { readonly _tag: Tag } => {\n  class Base extends Class<any> {\n    readonly _tag = tag\n  }\n  return Base as any\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Structural: new<A>(\n  args: Types.VoidIfEmpty<{ readonly [P in keyof A]: A[P] }>\n) => {} = internal.Structural as any\n\n/**\n * Create a tagged enum data type, which is a union of `Data` structs.\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Data } from \"effect\"\n *\n * type HttpError = Data.TaggedEnum<{\n *   BadRequest: { readonly status: 400, readonly message: string }\n *   NotFound: { readonly status: 404, readonly message: string }\n * }>\n *\n * // Equivalent to:\n * type HttpErrorPlain =\n *   | {\n *     readonly _tag: \"BadRequest\"\n *     readonly status: 400\n *     readonly message: string\n *   }\n *   | {\n *     readonly _tag: \"NotFound\"\n *     readonly status: 404\n *     readonly message: string\n *   }\n * ```\n *\n * @since 2.0.0\n * @category models\n */\nexport type TaggedEnum<\n  A extends Record<string, Record<string, any>> & UntaggedChildren<A>\n> = keyof A extends infer Tag ?\n  Tag extends keyof A ? Types.Simplify<{ readonly _tag: Tag } & { readonly [K in keyof A[Tag]]: A[Tag][K] }>\n  : never\n  : never\n\ntype ChildrenAreTagged<A> = keyof A extends infer K ? K extends keyof A ? \"_tag\" extends keyof A[K] ? true\n    : false\n  : never\n  : never\n\ntype UntaggedChildren<A> = true extends ChildrenAreTagged<A>\n  ? \"It looks like you're trying to create a tagged enum, but one or more of its members already has a `_tag` property.\"\n  : unknown\n\n/**\n * @since 2.0.0\n */\nexport declare namespace TaggedEnum {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface WithGenerics<Count extends number> {\n    readonly taggedEnum: { readonly _tag: string }\n    readonly numberOfGenerics: Count\n\n    readonly A: unknown\n    readonly B: unknown\n    readonly C: unknown\n    readonly D: unknown\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Kind<\n    Z extends WithGenerics<number>,\n    A = unknown,\n    B = unknown,\n    C = unknown,\n    D = unknown\n  > = (Z & {\n    readonly A: A\n    readonly B: B\n    readonly C: C\n    readonly D: D\n  })[\"taggedEnum\"]\n\n  /**\n   * @since 2.0.0\n   */\n  export type Args<\n    A extends { readonly _tag: string },\n    K extends A[\"_tag\"],\n    E = Extract<A, { readonly _tag: K }>\n  > = { readonly [K in keyof E as K extends \"_tag\" ? never : K]: E[K] } extends infer T ? Types.VoidIfEmpty<T>\n    : never\n\n  /**\n   * @since 2.0.0\n   */\n  export type Value<\n    A extends { readonly _tag: string },\n    K extends A[\"_tag\"]\n  > = Extract<A, { readonly _tag: K }>\n\n  /**\n   * @since 3.1.0\n   */\n  export type Constructor<A extends { readonly _tag: string }> = Types.Simplify<\n    & {\n      readonly [Tag in A[\"_tag\"]]: Case.Constructor<Extract<A, { readonly _tag: Tag }>, \"_tag\">\n    }\n    & {\n      readonly $is: <Tag extends A[\"_tag\"]>(tag: Tag) => (u: unknown) => u is Extract<A, { readonly _tag: Tag }>\n      readonly $match: {\n        <\n          const Cases extends {\n            readonly [Tag in A[\"_tag\"]]: (args: Extract<A, { readonly _tag: Tag }>) => any\n          }\n        >(\n          cases: Cases & { [K in Exclude<keyof Cases, A[\"_tag\"]>]: never }\n        ): (value: A) => Unify<ReturnType<Cases[A[\"_tag\"]]>>\n        <\n          const Cases extends {\n            readonly [Tag in A[\"_tag\"]]: (args: Extract<A, { readonly _tag: Tag }>) => any\n          }\n        >(\n          value: A,\n          cases: Cases & { [K in Exclude<keyof Cases, A[\"_tag\"]>]: never }\n        ): Unify<ReturnType<Cases[A[\"_tag\"]]>>\n      }\n    }\n  >\n\n  /**\n   * @since 3.2.0\n   */\n  export interface GenericMatchers<Z extends WithGenerics<number>> {\n    readonly $is: <Tag extends Z[\"taggedEnum\"][\"_tag\"]>(\n      tag: Tag\n    ) => {\n      <T extends TaggedEnum.Kind<Z, any, any, any, any>>(\n        u: T\n      ): u is T & { readonly _tag: Tag }\n      (u: unknown): u is Extract<TaggedEnum.Kind<Z>, { readonly _tag: Tag }>\n    }\n    readonly $match: {\n      <\n        A,\n        B,\n        C,\n        D,\n        Cases extends {\n          readonly [Tag in Z[\"taggedEnum\"][\"_tag\"]]: (\n            args: Extract<TaggedEnum.Kind<Z, A, B, C, D>, { readonly _tag: Tag }>\n          ) => any\n        }\n      >(\n        cases: Cases & { [K in Exclude<keyof Cases, Z[\"taggedEnum\"][\"_tag\"]>]: never }\n      ): (self: TaggedEnum.Kind<Z, A, B, C, D>) => Unify<ReturnType<Cases[Z[\"taggedEnum\"][\"_tag\"]]>>\n      <\n        A,\n        B,\n        C,\n        D,\n        Cases extends {\n          readonly [Tag in Z[\"taggedEnum\"][\"_tag\"]]: (\n            args: Extract<TaggedEnum.Kind<Z, A, B, C, D>, { readonly _tag: Tag }>\n          ) => any\n        }\n      >(\n        self: TaggedEnum.Kind<Z, A, B, C, D>,\n        cases: Cases & { [K in Exclude<keyof Cases, Z[\"taggedEnum\"][\"_tag\"]>]: never }\n      ): Unify<ReturnType<Cases[Z[\"taggedEnum\"][\"_tag\"]]>>\n    }\n  }\n}\n\n/**\n * Create a constructor for a tagged union of `Data` structs.\n *\n * You can also pass a `TaggedEnum.WithGenerics` if you want to add generics to\n * the constructor.\n *\n * @example\n * ```ts\n * import { Data } from \"effect\"\n *\n * const { BadRequest, NotFound } = Data.taggedEnum<\n *   | { readonly _tag: \"BadRequest\"; readonly status: 400; readonly message: string }\n *   | { readonly _tag: \"NotFound\"; readonly status: 404; readonly message: string }\n * >()\n *\n * const notFound = NotFound({ status: 404, message: \"Not Found\" })\n * ```\n *\n * @example\n * import { Data } from \"effect\"\n *\n * type MyResult<E, A> = Data.TaggedEnum<{\n *   Failure: { readonly error: E }\n *   Success: { readonly value: A }\n * }>\n * interface MyResultDefinition extends Data.TaggedEnum.WithGenerics<2> {\n *   readonly taggedEnum: MyResult<this[\"A\"], this[\"B\"]>\n * }\n * const { Failure, Success } = Data.taggedEnum<MyResultDefinition>()\n *\n * const success = Success({ value: 1 })\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const taggedEnum: {\n  <Z extends TaggedEnum.WithGenerics<1>>(): Types.Simplify<\n    {\n      readonly [Tag in Z[\"taggedEnum\"][\"_tag\"]]: <A>(\n        args: TaggedEnum.Args<\n          TaggedEnum.Kind<Z, A>,\n          Tag,\n          Extract<TaggedEnum.Kind<Z, A>, { readonly _tag: Tag }>\n        >\n      ) => TaggedEnum.Value<TaggedEnum.Kind<Z, A>, Tag>\n    } & TaggedEnum.GenericMatchers<Z>\n  >\n\n  <Z extends TaggedEnum.WithGenerics<2>>(): Types.Simplify<\n    {\n      readonly [Tag in Z[\"taggedEnum\"][\"_tag\"]]: <A, B>(\n        args: TaggedEnum.Args<\n          TaggedEnum.Kind<Z, A, B>,\n          Tag,\n          Extract<TaggedEnum.Kind<Z, A, B>, { readonly _tag: Tag }>\n        >\n      ) => TaggedEnum.Value<TaggedEnum.Kind<Z, A, B>, Tag>\n    } & TaggedEnum.GenericMatchers<Z>\n  >\n\n  <Z extends TaggedEnum.WithGenerics<3>>(): Types.Simplify<\n    {\n      readonly [Tag in Z[\"taggedEnum\"][\"_tag\"]]: <A, B, C>(\n        args: TaggedEnum.Args<\n          TaggedEnum.Kind<Z, A, B, C>,\n          Tag,\n          Extract<TaggedEnum.Kind<Z, A, B, C>, { readonly _tag: Tag }>\n        >\n      ) => TaggedEnum.Value<TaggedEnum.Kind<Z, A, B, C>, Tag>\n    } & TaggedEnum.GenericMatchers<Z>\n  >\n\n  <Z extends TaggedEnum.WithGenerics<4>>(): Types.Simplify<\n    {\n      readonly [Tag in Z[\"taggedEnum\"][\"_tag\"]]: <A, B, C, D>(\n        args: TaggedEnum.Args<\n          TaggedEnum.Kind<Z, A, B, C, D>,\n          Tag,\n          Extract<TaggedEnum.Kind<Z, A, B, C, D>, { readonly _tag: Tag }>\n        >\n      ) => TaggedEnum.Value<TaggedEnum.Kind<Z, A, B, C, D>, Tag>\n    } & TaggedEnum.GenericMatchers<Z>\n  >\n\n  <A extends { readonly _tag: string }>(): TaggedEnum.Constructor<A>\n} = () =>\n  new Proxy({}, {\n    get(_target, tag, _receiver) {\n      if (tag === \"$is\") {\n        return Predicate.isTagged\n      } else if (tag === \"$match\") {\n        return taggedMatch\n      }\n      return tagged(tag as string)\n    }\n  }) as any\n\nfunction taggedMatch<\n  A extends { readonly _tag: string },\n  Cases extends {\n    readonly [K in A[\"_tag\"]]: (args: Extract<A, { readonly _tag: K }>) => any\n  }\n>(self: A, cases: Cases): ReturnType<Cases[A[\"_tag\"]]>\nfunction taggedMatch<\n  A extends { readonly _tag: string },\n  Cases extends {\n    readonly [K in A[\"_tag\"]]: (args: Extract<A, { readonly _tag: K }>) => any\n  }\n>(cases: Cases): (value: A) => ReturnType<Cases[A[\"_tag\"]]>\nfunction taggedMatch<\n  A extends { readonly _tag: string },\n  Cases extends {\n    readonly [K in A[\"_tag\"]]: (args: Extract<A, { readonly _tag: K }>) => any\n  }\n>(): any {\n  if (arguments.length === 1) {\n    const cases = arguments[0] as Cases\n    return function(value: A): ReturnType<Cases[A[\"_tag\"]]> {\n      return cases[value._tag as A[\"_tag\"]](value as any)\n    }\n  }\n  const value = arguments[0] as A\n  const cases = arguments[1] as Cases\n  return cases[value._tag as A[\"_tag\"]](value as any)\n}\n\n/**\n * Provides a constructor for a Case Class.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const Error: new<A extends Record<string, any> = {}>(\n  args: Types.VoidIfEmpty<{ readonly [P in keyof A]: A[P] }>\n) => Cause.YieldableError & Readonly<A> = (function() {\n  const plainArgsSymbol = Symbol.for(\"effect/Data/Error/plainArgs\")\n  const O = {\n    BaseEffectError: class extends core.YieldableError {\n      constructor(args: any) {\n        super(args?.message, args?.cause ? { cause: args.cause } : undefined)\n        if (args) {\n          Object.assign(this, args)\n          // @effect-diagnostics-next-line floatingEffect:off\n          Object.defineProperty(this, plainArgsSymbol, { value: args, enumerable: false })\n        }\n      }\n      toJSON() {\n        return { ...(this as any)[plainArgsSymbol], ...this }\n      }\n    } as any\n  }\n  return O.BaseEffectError\n})()\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const TaggedError = <Tag extends string>(tag: Tag): new<A extends Record<string, any> = {}>(\n  args: Types.VoidIfEmpty<{ readonly [P in keyof A as P extends \"_tag\" ? never : P]: A[P] }>\n) => Cause.YieldableError & { readonly _tag: Tag } & Readonly<A> => {\n  const O = {\n    BaseEffectError: class extends Error<{}> {\n      readonly _tag = tag\n    }\n  }\n  ;(O.BaseEffectError.prototype as any).name = tag\n  return O.BaseEffectError as any\n}\n"
  },
  {
    "path": "packages/effect/src/DateTime.ts",
    "content": "/**\n * @since 3.6.0\n */\nimport type { IllegalArgumentException } from \"./Cause.js\"\nimport * as Context from \"./Context.js\"\nimport type * as Duration from \"./Duration.js\"\nimport * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type * as equivalence from \"./Equivalence.js\"\nimport { dual, type LazyArg } from \"./Function.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as Internal from \"./internal/dateTime.js\"\nimport * as Layer from \"./Layer.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as order from \"./Order.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\n\n/**\n * @since 3.6.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Internal.TypeId\n\n/**\n * @since 3.6.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * A `DateTime` represents a point in time. It can optionally have a time zone\n * associated with it.\n *\n * @since 3.6.0\n * @category models\n */\nexport type DateTime = Utc | Zoned\n\n/**\n * @since 3.6.0\n * @category models\n */\nexport interface Utc extends DateTime.Proto {\n  readonly _tag: \"Utc\"\n  readonly epochMillis: number\n  partsUtc: DateTime.PartsWithWeekday | undefined\n}\n\n/**\n * @since 3.6.0\n * @category models\n */\nexport interface Zoned extends DateTime.Proto {\n  readonly _tag: \"Zoned\"\n  readonly epochMillis: number\n  readonly zone: TimeZone\n  adjustedEpochMillis: number | undefined\n  partsAdjusted: DateTime.PartsWithWeekday | undefined\n  partsUtc: DateTime.PartsWithWeekday | undefined\n}\n\n/**\n * @since 3.6.0\n * @category models\n */\nexport declare namespace DateTime {\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export type Input = DateTime | Partial<Parts> | Date | number | string\n\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export type PreserveZone<A extends DateTime.Input> = A extends Zoned ? Zoned : Utc\n\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export type Unit = UnitSingular | UnitPlural\n\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export type UnitSingular =\n    | \"milli\"\n    | \"second\"\n    | \"minute\"\n    | \"hour\"\n    | \"day\"\n    | \"week\"\n    | \"month\"\n    | \"year\"\n\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export type UnitPlural =\n    | \"millis\"\n    | \"seconds\"\n    | \"minutes\"\n    | \"hours\"\n    | \"days\"\n    | \"weeks\"\n    | \"months\"\n    | \"years\"\n\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export interface PartsWithWeekday {\n    readonly millis: number\n    readonly seconds: number\n    readonly minutes: number\n    readonly hours: number\n    readonly day: number\n    readonly weekDay: number\n    readonly month: number\n    readonly year: number\n  }\n\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export interface Parts {\n    readonly millis: number\n    readonly seconds: number\n    readonly minutes: number\n    readonly hours: number\n    readonly day: number\n    readonly month: number\n    readonly year: number\n  }\n\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export interface PartsForMath {\n    readonly millis: number\n    readonly seconds: number\n    readonly minutes: number\n    readonly hours: number\n    readonly days: number\n    readonly weeks: number\n    readonly months: number\n    readonly years: number\n  }\n\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export interface Proto extends Pipeable, Inspectable {\n    readonly [TypeId]: TypeId\n  }\n}\n\n/**\n * @since 3.6.0\n * @category type ids\n */\nexport const TimeZoneTypeId: unique symbol = Internal.TimeZoneTypeId\n\n/**\n * @since 3.6.0\n * @category type ids\n */\nexport type TimeZoneTypeId = typeof TimeZoneTypeId\n\n/**\n * @since 3.6.0\n * @category models\n */\nexport type TimeZone = TimeZone.Offset | TimeZone.Named\n\n/**\n * @since 3.6.0\n * @category models\n */\nexport declare namespace TimeZone {\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export interface Proto extends Inspectable {\n    readonly [TimeZoneTypeId]: TimeZoneTypeId\n  }\n\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export interface Offset extends Proto {\n    readonly _tag: \"Offset\"\n    readonly offset: number\n  }\n\n  /**\n   * @since 3.6.0\n   * @category models\n   */\n  export interface Named extends Proto {\n    readonly _tag: \"Named\"\n    readonly id: string\n    /** @internal */\n    readonly format: Intl.DateTimeFormat\n  }\n}\n\n/**\n * A `Disambiguation` is used to resolve ambiguities when a `DateTime` is\n * ambiguous, such as during a daylight saving time transition.\n *\n * For more information, see the [Temporal documentation](https://tc39.es/proposal-temporal/docs/timezone.html#ambiguity-due-to-dst-or-other-time-zone-offset-changes)\n *\n * - `\"compatible\"`: (default) Behavior matching Temporal API and legacy JavaScript Date and moment.js.\n *   For repeated times, chooses the earlier occurrence. For gap times, chooses the later interpretation.\n *\n * - `\"earlier\"`: For repeated times, always choose the earlier occurrence.\n *   For gap times, choose the time before the gap.\n *\n * - `\"later\"`: For repeated times, always choose the later occurrence.\n *   For gap times, choose the time after the gap.\n *\n * - `\"reject\"`: Throw an `RangeError` when encountering ambiguous or non-existent times.\n *\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // Fall-back example: 01:30 on Nov 2, 2025 in New York happens twice\n * const ambiguousTime = { year: 2025, month: 11, day: 2, hours: 1, minutes: 30 }\n * const timeZone = DateTime.zoneUnsafeMakeNamed(\"America/New_York\")\n *\n * DateTime.makeZoned(ambiguousTime, { timeZone, adjustForTimeZone: true, disambiguation: \"earlier\" })\n * // Earlier occurrence (DST time): 2025-11-02T05:30:00.000Z\n *\n * DateTime.makeZoned(ambiguousTime, { timeZone, adjustForTimeZone: true, disambiguation: \"later\" })\n * // Later occurrence (standard time): 2025-11-02T06:30:00.000Z\n *\n * // Gap example: 02:30 on Mar 9, 2025 in New York doesn't exist\n * const gapTime = { year: 2025, month: 3, day: 9, hours: 2, minutes: 30 }\n *\n * DateTime.makeZoned(gapTime, { timeZone, adjustForTimeZone: true, disambiguation: \"earlier\" })\n * // Time before gap: 2025-03-09T06:30:00.000Z (01:30 EST)\n *\n * DateTime.makeZoned(gapTime, { timeZone, adjustForTimeZone: true, disambiguation: \"later\" })\n * // Time after gap: 2025-03-09T07:30:00.000Z (03:30 EDT)\n * ```\n *\n * @since 3.18.0\n * @category models\n */\nexport type Disambiguation = \"compatible\" | \"earlier\" | \"later\" | \"reject\"\n\n// =============================================================================\n// guards\n// =============================================================================\n\n/**\n * @since 3.6.0\n * @category guards\n */\nexport const isDateTime: (u: unknown) => u is DateTime = Internal.isDateTime\n\n/**\n * @since 3.6.0\n * @category guards\n */\nexport const isTimeZone: (u: unknown) => u is TimeZone = Internal.isTimeZone\n\n/**\n * @since 3.6.0\n * @category guards\n */\nexport const isTimeZoneOffset: (u: unknown) => u is TimeZone.Offset = Internal.isTimeZoneOffset\n\n/**\n * @since 3.6.0\n * @category guards\n */\nexport const isTimeZoneNamed: (u: unknown) => u is TimeZone.Named = Internal.isTimeZoneNamed\n\n/**\n * @since 3.6.0\n * @category guards\n */\nexport const isUtc: (self: DateTime) => self is Utc = Internal.isUtc\n\n/**\n * @since 3.6.0\n * @category guards\n */\nexport const isZoned: (self: DateTime) => self is Zoned = Internal.isZoned\n\n// =============================================================================\n// instances\n// =============================================================================\n\n/**\n * @since 3.6.0\n * @category instances\n */\nexport const Equivalence: equivalence.Equivalence<DateTime> = Internal.Equivalence\n\n/**\n * @since 3.6.0\n * @category instances\n */\nexport const Order: order.Order<DateTime> = Internal.Order\n\n/**\n * @since 3.6.0\n */\nexport const clamp: {\n  <Min extends DateTime, Max extends DateTime>(\n    options: { readonly minimum: Min; readonly maximum: Max }\n  ): <A extends DateTime>(self: A) => A | Min | Max\n  <A extends DateTime, Min extends DateTime, Max extends DateTime>(\n    self: A,\n    options: { readonly minimum: Min; readonly maximum: Max }\n  ): A | Min | Max\n} = Internal.clamp\n\n// =============================================================================\n// constructors\n// =============================================================================\n\n/**\n * Create a `DateTime` from a `Date`.\n *\n * If the `Date` is invalid, an `IllegalArgumentException` will be thrown.\n *\n * @since 3.6.0\n * @category constructors\n */\nexport const unsafeFromDate: (date: Date) => Utc = Internal.unsafeFromDate\n\n/**\n * Create a `DateTime` from one of the following:\n *\n * - A `DateTime`\n * - A `Date` instance (invalid dates will throw an `IllegalArgumentException`)\n * - The `number` of milliseconds since the Unix epoch\n * - An object with the parts of a date\n * - A `string` that can be parsed by `Date.parse`\n *\n * @since 3.6.0\n * @category constructors\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // from Date\n * DateTime.unsafeMake(new Date())\n *\n * // from parts\n * DateTime.unsafeMake({ year: 2024 })\n *\n * // from string\n * DateTime.unsafeMake(\"2024-01-01\")\n * ```\n */\nexport const unsafeMake: <A extends DateTime.Input>(input: A) => DateTime.PreserveZone<A> = Internal.unsafeMake\n\n/**\n * Create a `DateTime.Zoned` using `DateTime.unsafeMake` and a time zone.\n *\n * The input is treated as UTC and then the time zone is attached, unless\n * `adjustForTimeZone` is set to `true`. In that case, the input is treated as\n * already in the time zone.\n *\n * When `adjustForTimeZone` is true and ambiguous times occur during DST transitions,\n * the `disambiguation` option controls how to resolve the ambiguity:\n * - `compatible` (default): Choose earlier time for repeated times, later for gaps\n * - `earlier`: Always choose the earlier of two possible times\n * - `later`: Always choose the later of two possible times\n * - `reject`: Throw an error when ambiguous times are encountered\n *\n * @since 3.6.0\n * @category constructors\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * DateTime.unsafeMakeZoned(new Date(), { timeZone: \"Europe/London\" })\n * ```\n */\nexport const unsafeMakeZoned: (input: DateTime.Input, options?: {\n  readonly timeZone?: number | string | TimeZone | undefined\n  readonly adjustForTimeZone?: boolean | undefined\n  readonly disambiguation?: Disambiguation | undefined\n}) => Zoned = Internal.unsafeMakeZoned\n\n/**\n * Create a `DateTime.Zoned` using `DateTime.make` and a time zone.\n *\n * The input is treated as UTC and then the time zone is attached, unless\n * `adjustForTimeZone` is set to `true`. In that case, the input is treated as\n * already in the time zone.\n *\n * When `adjustForTimeZone` is true and ambiguous times occur during DST transitions,\n * the `disambiguation` option controls how to resolve the ambiguity:\n * - `compatible` (default): Choose earlier time for repeated times, later for gaps\n * - `earlier`: Always choose the earlier of two possible times\n * - `later`: Always choose the later of two possible times\n * - `reject`: Throw an error when ambiguous times are encountered\n *\n * If the date time input or time zone is invalid, `None` will be returned.\n *\n * @since 3.6.0\n * @category constructors\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * DateTime.makeZoned(new Date(), { timeZone: \"Europe/London\" })\n * ```\n */\nexport const makeZoned: (\n  input: DateTime.Input,\n  options?: {\n    readonly timeZone?: number | string | TimeZone | undefined\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: Disambiguation | undefined\n  }\n) => Option.Option<Zoned> = Internal.makeZoned\n\n/**\n * Create a `DateTime` from one of the following:\n *\n * - A `DateTime`\n * - A `Date` instance (invalid dates will throw an `IllegalArgumentException`)\n * - The `number` of milliseconds since the Unix epoch\n * - An object with the parts of a date\n * - A `string` that can be parsed by `Date.parse`\n *\n * If the input is invalid, `None` will be returned.\n *\n * @since 3.6.0\n * @category constructors\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // from Date\n * DateTime.make(new Date())\n *\n * // from parts\n * DateTime.make({ year: 2024 })\n *\n * // from string\n * DateTime.make(\"2024-01-01\")\n * ```\n */\nexport const make: <A extends DateTime.Input>(input: A) => Option.Option<DateTime.PreserveZone<A>> = Internal.make\n\n/**\n * Create a `DateTime.Zoned` from a string.\n *\n * It uses the format: `YYYY-MM-DDTHH:mm:ss.sss+HH:MM[Time/Zone]`.\n *\n * @since 3.6.0\n * @category constructors\n */\nexport const makeZonedFromString: (input: string) => Option.Option<Zoned> = Internal.makeZonedFromString\n\n/**\n * Get the current time using the `Clock` service and convert it to a `DateTime`.\n *\n * @since 3.6.0\n * @category constructors\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.now\n * })\n * ```\n */\nexport const now: Effect.Effect<Utc> = Internal.now\n\n/**\n * Get the current time using the `Clock` service.\n *\n * @since 3.14.0\n * @category constructors\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.nowAsDate\n * })\n * ```\n */\nexport const nowAsDate: Effect.Effect<Date> = Internal.nowAsDate\n\n/**\n * Get the current time using `Date.now`.\n *\n * @since 3.6.0\n * @category constructors\n */\nexport const unsafeNow: LazyArg<Utc> = Internal.unsafeNow\n\n// =============================================================================\n// time zones\n// =============================================================================\n\n/**\n * For a `DateTime` returns a new `DateTime.Utc`.\n *\n * @since 3.13.0\n * @category time zones\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * const now = DateTime.unsafeMakeZoned({ year: 2024 }, { timeZone: \"Europe/London\" })\n *\n * // set as UTC\n * const utc: DateTime.Utc = DateTime.toUtc(now)\n * ```\n */\nexport const toUtc: (self: DateTime) => Utc = Internal.toUtc\n\n/**\n * Set the time zone of a `DateTime`, returning a new `DateTime.Zoned`.\n *\n * @since 3.6.0\n * @category time zones\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.now\n *   const zone = DateTime.zoneUnsafeMakeNamed(\"Europe/London\")\n *\n *   // set the time zone\n *   const zoned: DateTime.Zoned = DateTime.setZone(now, zone)\n * })\n * ```\n */\nexport const setZone: {\n  (zone: TimeZone, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: Disambiguation | undefined\n  }): (self: DateTime) => Zoned\n  (self: DateTime, zone: TimeZone, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: Disambiguation | undefined\n  }): Zoned\n} = Internal.setZone\n\n/**\n * Add a fixed offset time zone to a `DateTime`.\n *\n * The offset is in milliseconds.\n *\n * @since 3.6.0\n * @category time zones\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.now\n *\n *   // set the offset time zone in milliseconds\n *   const zoned: DateTime.Zoned = DateTime.setZoneOffset(now, 3 * 60 * 60 * 1000)\n * })\n * ```\n */\nexport const setZoneOffset: {\n  (offset: number, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: Disambiguation | undefined\n  }): (self: DateTime) => Zoned\n  (self: DateTime, offset: number, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: Disambiguation | undefined\n  }): Zoned\n} = Internal.setZoneOffset\n\n/**\n * Attempt to create a named time zone from a IANA time zone identifier.\n *\n * If the time zone is invalid, an `IllegalArgumentException` will be thrown.\n *\n * @since 3.6.0\n * @category time zones\n */\nexport const zoneUnsafeMakeNamed: (zoneId: string) => TimeZone.Named = Internal.zoneUnsafeMakeNamed\n\n/**\n * Create a fixed offset time zone.\n *\n * @since 3.6.0\n * @category time zones\n */\nexport const zoneMakeOffset: (offset: number) => TimeZone.Offset = Internal.zoneMakeOffset\n\n/**\n * Create a named time zone from a IANA time zone identifier. If the time zone\n * is invalid, `None` will be returned.\n *\n * @since 3.6.0\n * @category time zones\n */\nexport const zoneMakeNamed: (zoneId: string) => Option.Option<TimeZone.Named> = Internal.zoneMakeNamed\n\n/**\n * Create a named time zone from a IANA time zone identifier. If the time zone\n * is invalid, it will fail with an `IllegalArgumentException`.\n *\n * @since 3.6.0\n * @category time zones\n */\nexport const zoneMakeNamedEffect: (zoneId: string) => Effect.Effect<TimeZone.Named, IllegalArgumentException> =\n  Internal.zoneMakeNamedEffect\n\n/**\n * Create a named time zone from the system's local time zone.\n *\n * @since 3.6.0\n * @category time zones\n */\nexport const zoneMakeLocal: () => TimeZone.Named = Internal.zoneMakeLocal\n\n/**\n * Try parse a TimeZone from a string\n *\n * @since 3.6.0\n * @category time zones\n */\nexport const zoneFromString: (zone: string) => Option.Option<TimeZone> = Internal.zoneFromString\n\n/**\n * Format a `TimeZone` as a string.\n *\n * @since 3.6.0\n * @category time zones\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * // Outputs \"+03:00\"\n * DateTime.zoneToString(DateTime.zoneMakeOffset(3 * 60 * 60 * 1000))\n *\n * // Outputs \"Europe/London\"\n * DateTime.zoneToString(DateTime.zoneUnsafeMakeNamed(\"Europe/London\"))\n * ```\n */\nexport const zoneToString: (self: TimeZone) => string = Internal.zoneToString\n\n/**\n * Set the time zone of a `DateTime` from an IANA time zone identifier. If the\n * time zone is invalid, `None` will be returned.\n *\n * @since 3.6.0\n * @category time zones\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.now\n *   // set the time zone, returns an Option\n *   DateTime.setZoneNamed(now, \"Europe/London\")\n * })\n * ```\n */\nexport const setZoneNamed: {\n  (zoneId: string, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: Disambiguation | undefined\n  }): (self: DateTime) => Option.Option<Zoned>\n  (self: DateTime, zoneId: string, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: Disambiguation | undefined\n  }): Option.Option<Zoned>\n} = Internal.setZoneNamed\n\n/**\n * Set the time zone of a `DateTime` from an IANA time zone identifier. If the\n * time zone is invalid, an `IllegalArgumentException` will be thrown.\n *\n * @since 3.6.0\n * @category time zones\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.now\n *   // set the time zone\n *   DateTime.unsafeSetZoneNamed(now, \"Europe/London\")\n * })\n * ```\n */\nexport const unsafeSetZoneNamed: {\n  (zoneId: string, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: Disambiguation | undefined\n  }): (self: DateTime) => Zoned\n  (self: DateTime, zoneId: string, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: Disambiguation | undefined\n  }): Zoned\n} = Internal.unsafeSetZoneNamed\n\n// =============================================================================\n// comparisons\n// =============================================================================\n\n/**\n * Calulate the difference between two `DateTime` values, returning the number\n * of milliseconds the `other` DateTime is from `self`.\n *\n * If `other` is *after* `self`, the result will be a positive number.\n *\n * @since 3.6.0\n * @category comparisons\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.now\n *   const other = DateTime.add(now, { minutes: 1 })\n *\n *   // returns 60000\n *   DateTime.distance(now, other)\n * })\n * ```\n */\nexport const distance: {\n  (other: DateTime): (self: DateTime) => number\n  (self: DateTime, other: DateTime): number\n} = Internal.distance\n\n/**\n * Calulate the difference between two `DateTime` values.\n *\n * If the `other` DateTime is before `self`, the result will be a negative\n * `Duration`, returned as a `Left`.\n *\n * If the `other` DateTime is after `self`, the result will be a positive\n * `Duration`, returned as a `Right`.\n *\n * @since 3.6.0\n * @category comparisons\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.now\n *   const other = DateTime.add(now, { minutes: 1 })\n *\n *   // returns Either.right(Duration.minutes(1))\n *   DateTime.distanceDurationEither(now, other)\n *\n *   // returns Either.left(Duration.minutes(1))\n *   DateTime.distanceDurationEither(other, now)\n * })\n * ```\n */\nexport const distanceDurationEither: {\n  (other: DateTime): (self: DateTime) => Either.Either<Duration.Duration, Duration.Duration>\n  (self: DateTime, other: DateTime): Either.Either<Duration.Duration, Duration.Duration>\n} = Internal.distanceDurationEither\n\n/**\n * Calulate the distance between two `DateTime` values.\n *\n * @since 3.6.0\n * @category comparisons\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.now\n *   const other = DateTime.add(now, { minutes: 1 })\n *\n *   // returns Duration.minutes(1)\n *   DateTime.distanceDuration(now, other)\n * })\n * ```\n */\nexport const distanceDuration: {\n  (other: DateTime): (self: DateTime) => Duration.Duration\n  (self: DateTime, other: DateTime): Duration.Duration\n} = Internal.distanceDuration\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const min: {\n  <That extends DateTime>(that: That): <Self extends DateTime>(self: Self) => Self | That\n  <Self extends DateTime, That extends DateTime>(self: Self, that: That): Self | That\n} = Internal.min\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const max: {\n  <That extends DateTime>(that: That): <Self extends DateTime>(self: Self) => Self | That\n  <Self extends DateTime, That extends DateTime>(self: Self, that: That): Self | That\n} = Internal.max\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const greaterThan: {\n  (that: DateTime): (self: DateTime) => boolean\n  (self: DateTime, that: DateTime): boolean\n} = Internal.greaterThan\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const greaterThanOrEqualTo: {\n  (that: DateTime): (self: DateTime) => boolean\n  (self: DateTime, that: DateTime): boolean\n} = Internal.greaterThanOrEqualTo\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const lessThan: {\n  (that: DateTime): (self: DateTime) => boolean\n  (self: DateTime, that: DateTime): boolean\n} = Internal.lessThan\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const lessThanOrEqualTo: {\n  (that: DateTime): (self: DateTime) => boolean\n  (self: DateTime, that: DateTime): boolean\n} = Internal.lessThanOrEqualTo\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const between: {\n  (options: { minimum: DateTime; maximum: DateTime }): (self: DateTime) => boolean\n  (self: DateTime, options: { minimum: DateTime; maximum: DateTime }): boolean\n} = Internal.between\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const isFuture: (self: DateTime) => Effect.Effect<boolean> = Internal.isFuture\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const unsafeIsFuture: (self: DateTime) => boolean = Internal.unsafeIsFuture\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const isPast: (self: DateTime) => Effect.Effect<boolean> = Internal.isPast\n\n/**\n * @since 3.6.0\n * @category comparisons\n */\nexport const unsafeIsPast: (self: DateTime) => boolean = Internal.unsafeIsPast\n\n// =============================================================================\n// conversions\n// =============================================================================\n\n/**\n * Get the UTC `Date` of a `DateTime`.\n *\n * @since 3.6.0\n * @category conversions\n */\nexport const toDateUtc: (self: DateTime) => Date = Internal.toDateUtc\n\n/**\n * Convert a `DateTime` to a `Date`, applying the time zone first.\n *\n * @since 3.6.0\n * @category conversions\n */\nexport const toDate: (self: DateTime) => Date = Internal.toDate\n\n/**\n * Calculate the time zone offset of a `DateTime.Zoned` in milliseconds.\n *\n * @since 3.6.0\n * @category conversions\n */\nexport const zonedOffset: (self: Zoned) => number = Internal.zonedOffset\n\n/**\n * Calculate the time zone offset of a `DateTime` in milliseconds.\n *\n * The offset is formatted as \"±HH:MM\".\n *\n * @since 3.6.0\n * @category conversions\n */\nexport const zonedOffsetIso: (self: Zoned) => string = Internal.zonedOffsetIso\n\n/**\n * Get the milliseconds since the Unix epoch of a `DateTime`.\n *\n * @since 3.6.0\n * @category conversions\n */\nexport const toEpochMillis: (self: DateTime) => number = Internal.toEpochMillis\n\n/**\n * Remove the time aspect of a `DateTime`, first adjusting for the time\n * zone. It will return a `DateTime.Utc` only containing the date.\n *\n * @since 3.6.0\n * @category conversions\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // returns \"2024-01-01T00:00:00Z\"\n * DateTime.unsafeMakeZoned(\"2024-01-01T05:00:00Z\", {\n *   timeZone: \"Pacific/Auckland\",\n *   adjustForTimeZone: true\n * }).pipe(\n *   DateTime.removeTime,\n *   DateTime.formatIso\n * )\n * ```\n */\nexport const removeTime: (self: DateTime) => Utc = Internal.removeTime\n\n// =============================================================================\n// parts\n// =============================================================================\n\n/**\n * Get the different parts of a `DateTime` as an object.\n *\n * The parts will be time zone adjusted.\n *\n * @since 3.6.0\n * @category parts\n */\nexport const toParts: (self: DateTime) => DateTime.PartsWithWeekday = Internal.toParts\n\n/**\n * Get the different parts of a `DateTime` as an object.\n *\n * The parts will be in UTC.\n *\n * @since 3.6.0\n * @category parts\n */\nexport const toPartsUtc: (self: DateTime) => DateTime.PartsWithWeekday = Internal.toPartsUtc\n\n/**\n * Get a part of a `DateTime` as a number.\n *\n * The part will be in the UTC time zone.\n *\n * @since 3.6.0\n * @category parts\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { DateTime } from \"effect\"\n *\n * const now = DateTime.unsafeMake({ year: 2024 })\n * const year = DateTime.getPartUtc(now, \"year\")\n * assert.strictEqual(year, 2024)\n * ```\n */\nexport const getPartUtc: {\n  (part: keyof DateTime.PartsWithWeekday): (self: DateTime) => number\n  (self: DateTime, part: keyof DateTime.PartsWithWeekday): number\n} = Internal.getPartUtc\n\n/**\n * Get a part of a `DateTime` as a number.\n *\n * The part will be time zone adjusted.\n *\n * @since 3.6.0\n * @category parts\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { DateTime } from \"effect\"\n *\n * const now = DateTime.unsafeMakeZoned({ year: 2024 }, { timeZone: \"Europe/London\" })\n * const year = DateTime.getPart(now, \"year\")\n * assert.strictEqual(year, 2024)\n * ```\n */\nexport const getPart: {\n  (part: keyof DateTime.PartsWithWeekday): (self: DateTime) => number\n  (self: DateTime, part: keyof DateTime.PartsWithWeekday): number\n} = Internal.getPart\n\n/**\n * Set the different parts of a `DateTime` as an object.\n *\n * The Date will be time zone adjusted.\n *\n * @since 3.6.0\n * @category parts\n */\nexport const setParts: {\n  (parts: Partial<DateTime.PartsWithWeekday>): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(self: A, parts: Partial<DateTime.PartsWithWeekday>): A\n} = Internal.setParts\n\n/**\n * Set the different parts of a `DateTime` as an object.\n *\n * @since 3.6.0\n * @category parts\n */\nexport const setPartsUtc: {\n  (parts: Partial<DateTime.PartsWithWeekday>): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(self: A, parts: Partial<DateTime.PartsWithWeekday>): A\n} = Internal.setPartsUtc\n\n// =============================================================================\n// current time zone\n// =============================================================================\n\n/**\n * @since 3.11.0\n * @category current time zone\n */\nexport class CurrentTimeZone extends Context.Tag(\"effect/DateTime/CurrentTimeZone\")<CurrentTimeZone, TimeZone>() {}\n\n/**\n * Set the time zone of a `DateTime` to the current time zone, which is\n * determined by the `CurrentTimeZone` service.\n *\n * @since 3.6.0\n * @category current time zone\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.now\n *\n *   // set the time zone to \"Europe/London\"\n *   const zoned = yield* DateTime.setZoneCurrent(now)\n * }).pipe(DateTime.withCurrentZoneNamed(\"Europe/London\"))\n * ```\n */\nexport const setZoneCurrent = (self: DateTime): Effect.Effect<Zoned, never, CurrentTimeZone> =>\n  Effect.map(CurrentTimeZone, (zone) => setZone(self, zone))\n\n/**\n * Provide the `CurrentTimeZone` to an effect.\n *\n * @since 3.6.0\n * @category current time zone\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * const zone = DateTime.zoneUnsafeMakeNamed(\"Europe/London\")\n *\n * Effect.gen(function* () {\n *   const now = yield* DateTime.nowInCurrentZone\n * }).pipe(DateTime.withCurrentZone(zone))\n * ```\n */\nexport const withCurrentZone: {\n  (\n    zone: TimeZone\n  ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, CurrentTimeZone>>\n  <A, E, R>(effect: Effect.Effect<A, E, R>, zone: TimeZone): Effect.Effect<A, E, Exclude<R, CurrentTimeZone>>\n} = dual(\n  2,\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    zone: TimeZone\n  ): Effect.Effect<A, E, Exclude<R, CurrentTimeZone>> => Effect.provideService(effect, CurrentTimeZone, zone)\n)\n\n/**\n * Provide the `CurrentTimeZone` to an effect, using the system's local time\n * zone.\n *\n * @since 3.6.0\n * @category current time zone\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   // will use the system's local time zone\n *   const now = yield* DateTime.nowInCurrentZone\n * }).pipe(DateTime.withCurrentZoneLocal)\n * ```\n */\nexport const withCurrentZoneLocal = <A, E, R>(\n  effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, Exclude<R, CurrentTimeZone>> =>\n  Effect.provideServiceEffect(effect, CurrentTimeZone, Effect.sync(zoneMakeLocal))\n\n/**\n * Provide the `CurrentTimeZone` to an effect, using a offset.\n *\n * @since 3.6.0\n * @category current time zone\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   // will use the system's local time zone\n *   const now = yield* DateTime.nowInCurrentZone\n * }).pipe(DateTime.withCurrentZoneOffset(3 * 60 * 60 * 1000))\n * ```\n */\nexport const withCurrentZoneOffset: {\n  (offset: number): <A, E, R>(\n    effect: Effect.Effect<A, E, R>\n  ) => Effect.Effect<A, E, Exclude<R, CurrentTimeZone>>\n  <A, E, R>(effect: Effect.Effect<A, E, R>, offset: number): Effect.Effect<A, E, Exclude<R, CurrentTimeZone>>\n} = dual(\n  2,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, offset: number): Effect.Effect<A, E, Exclude<R, CurrentTimeZone>> =>\n    Effect.provideService(effect, CurrentTimeZone, zoneMakeOffset(offset))\n)\n\n/**\n * Provide the `CurrentTimeZone` to an effect using an IANA time zone\n * identifier.\n *\n * If the time zone is invalid, it will fail with an `IllegalArgumentException`.\n *\n * @since 3.6.0\n * @category current time zone\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   // will use the \"Europe/London\" time zone\n *   const now = yield* DateTime.nowInCurrentZone\n * }).pipe(DateTime.withCurrentZoneNamed(\"Europe/London\"))\n * ```\n */\nexport const withCurrentZoneNamed: {\n  (zone: string): <A, E, R>(\n    effect: Effect.Effect<A, E, R>\n  ) => Effect.Effect<A, E | IllegalArgumentException, Exclude<R, CurrentTimeZone>>\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    zone: string\n  ): Effect.Effect<A, E | IllegalArgumentException, Exclude<R, CurrentTimeZone>>\n} = dual(\n  2,\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    zone: string\n  ): Effect.Effect<A, E | IllegalArgumentException, Exclude<R, CurrentTimeZone>> =>\n    Effect.provideServiceEffect(effect, CurrentTimeZone, zoneMakeNamedEffect(zone))\n)\n\n/**\n * Get the current time as a `DateTime.Zoned`, using the `CurrentTimeZone`.\n *\n * @since 3.6.0\n * @category current time zone\n * @example\n * ```ts\n * import { DateTime, Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   // will use the \"Europe/London\" time zone\n *   const now = yield* DateTime.nowInCurrentZone\n * }).pipe(DateTime.withCurrentZoneNamed(\"Europe/London\"))\n * ```\n */\nexport const nowInCurrentZone: Effect.Effect<Zoned, never, CurrentTimeZone> = Effect.flatMap(now, setZoneCurrent)\n\n// =============================================================================\n// mapping\n// =============================================================================\n\n/**\n * Modify a `DateTime` by applying a function to a cloned `Date` instance.\n *\n * The `Date` will first have the time zone applied if possible, and then be\n * converted back to a `DateTime` within the same time zone.\n *\n * Supports `disambiguation` when the new wall clock time is ambiguous.\n *\n * @since 3.6.0\n * @category mapping\n */\nexport const mutate: {\n  (\n    f: (date: Date) => void,\n    options?: {\n      readonly disambiguation?: Disambiguation | undefined\n    }\n  ): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(\n    self: A,\n    f: (date: Date) => void,\n    options?: {\n      readonly disambiguation?: Disambiguation | undefined\n    }\n  ): A\n} = Internal.mutate\n\n/**\n * Modify a `DateTime` by applying a function to a cloned UTC `Date` instance.\n *\n * @since 3.6.0\n * @category mapping\n */\nexport const mutateUtc: {\n  (f: (date: Date) => void): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(self: A, f: (date: Date) => void): A\n} = Internal.mutateUtc\n\n/**\n * Transform a `DateTime` by applying a function to the number of milliseconds\n * since the Unix epoch.\n *\n * @since 3.6.0\n * @category mapping\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // add 10 milliseconds\n * DateTime.unsafeMake(0).pipe(\n *   DateTime.mapEpochMillis((millis) => millis + 10)\n * )\n * ```\n */\nexport const mapEpochMillis: {\n  (f: (millis: number) => number): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(self: A, f: (millis: number) => number): A\n} = Internal.mapEpochMillis\n\n/**\n * Using the time zone adjusted `Date`, apply a function to the `Date` and\n * return the result.\n *\n * @since 3.6.0\n * @category mapping\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // get the time zone adjusted date in milliseconds\n * DateTime.unsafeMakeZoned(0, { timeZone: \"Europe/London\" }).pipe(\n *   DateTime.withDate((date) => date.getTime())\n * )\n * ```\n */\nexport const withDate: {\n  <A>(f: (date: Date) => A): (self: DateTime) => A\n  <A>(self: DateTime, f: (date: Date) => A): A\n} = Internal.withDate\n\n/**\n * Using the time zone adjusted `Date`, apply a function to the `Date` and\n * return the result.\n *\n * @since 3.6.0\n * @category mapping\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // get the date in milliseconds\n * DateTime.unsafeMake(0).pipe(\n *   DateTime.withDateUtc((date) => date.getTime())\n * )\n * ```\n */\nexport const withDateUtc: {\n  <A>(f: (date: Date) => A): (self: DateTime) => A\n  <A>(self: DateTime, f: (date: Date) => A): A\n} = Internal.withDateUtc\n\n/**\n * @since 3.6.0\n * @category mapping\n */\nexport const match: {\n  <A, B>(options: {\n    readonly onUtc: (_: Utc) => A\n    readonly onZoned: (_: Zoned) => B\n  }): (self: DateTime) => A | B\n  <A, B>(self: DateTime, options: {\n    readonly onUtc: (_: Utc) => A\n    readonly onZoned: (_: Zoned) => B\n  }): A | B\n} = Internal.match\n\n// =============================================================================\n// math\n// =============================================================================\n\n/**\n * Add the given `Duration` to a `DateTime`.\n *\n * @since 3.6.0\n * @category math\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // add 5 minutes\n * DateTime.unsafeMake(0).pipe(\n *   DateTime.addDuration(\"5 minutes\")\n * )\n * ```\n */\nexport const addDuration: {\n  (duration: Duration.DurationInput): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(self: A, duration: Duration.DurationInput): A\n} = Internal.addDuration\n\n/**\n * Subtract the given `Duration` from a `DateTime`.\n *\n * @since 3.6.0\n * @category math\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // subtract 5 minutes\n * DateTime.unsafeMake(0).pipe(\n *   DateTime.subtractDuration(\"5 minutes\")\n * )\n * ```\n */\nexport const subtractDuration: {\n  (duration: Duration.DurationInput): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(self: A, duration: Duration.DurationInput): A\n} = Internal.subtractDuration\n\n/**\n * Add the given `amount` of `unit`'s to a `DateTime`.\n *\n * The time zone is taken into account when adding days, weeks, months, and\n * years.\n *\n * @since 3.6.0\n * @category math\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // add 5 minutes\n * DateTime.unsafeMake(0).pipe(\n *   DateTime.add({ minutes: 5 })\n * )\n * ```\n */\nexport const add: {\n  (parts: Partial<DateTime.PartsForMath>): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(self: A, parts: Partial<DateTime.PartsForMath>): A\n} = Internal.add\n\n/**\n * Subtract the given `amount` of `unit`'s from a `DateTime`.\n *\n * @since 3.6.0\n * @category math\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // subtract 5 minutes\n * DateTime.unsafeMake(0).pipe(\n *   DateTime.subtract({ minutes: 5 })\n * )\n * ```\n */\nexport const subtract: {\n  (parts: Partial<DateTime.PartsForMath>): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(self: A, parts: Partial<DateTime.PartsForMath>): A\n} = Internal.subtract\n\n/**\n * Converts a `DateTime` to the start of the given `part`.\n *\n * If the part is `week`, the `weekStartsOn` option can be used to specify the\n * day of the week that the week starts on. The default is 0 (Sunday).\n *\n * @since 3.6.0\n * @category math\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // returns \"2024-01-01T00:00:00Z\"\n * DateTime.unsafeMake(\"2024-01-01T12:00:00Z\").pipe(\n *   DateTime.startOf(\"day\"),\n *   DateTime.formatIso\n * )\n * ```\n */\nexport const startOf: {\n  (\n    part: DateTime.UnitSingular,\n    options?: { readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined }\n  ): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(\n    self: A,\n    part: DateTime.UnitSingular,\n    options?: { readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined }\n  ): A\n} = Internal.startOf\n\n/**\n * Converts a `DateTime` to the end of the given `part`.\n *\n * If the part is `week`, the `weekStartsOn` option can be used to specify the\n * day of the week that the week starts on. The default is 0 (Sunday).\n *\n * @since 3.6.0\n * @category math\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // returns \"2024-01-01T23:59:59.999Z\"\n * DateTime.unsafeMake(\"2024-01-01T12:00:00Z\").pipe(\n *   DateTime.endOf(\"day\"),\n *   DateTime.formatIso\n * )\n * ```\n */\nexport const endOf: {\n  (\n    part: DateTime.UnitSingular,\n    options?: { readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined }\n  ): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(\n    self: A,\n    part: DateTime.UnitSingular,\n    options?: { readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined }\n  ): A\n} = Internal.endOf\n\n/**\n * Converts a `DateTime` to the nearest given `part`.\n *\n * If the part is `week`, the `weekStartsOn` option can be used to specify the\n * day of the week that the week starts on. The default is 0 (Sunday).\n *\n * @since 3.6.0\n * @category math\n * @example\n * ```ts\n * import { DateTime } from \"effect\"\n *\n * // returns \"2024-01-02T00:00:00Z\"\n * DateTime.unsafeMake(\"2024-01-01T12:01:00Z\").pipe(\n *   DateTime.nearest(\"day\"),\n *   DateTime.formatIso\n * )\n * ```\n */\nexport const nearest: {\n  (\n    part: DateTime.UnitSingular,\n    options?: { readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined }\n  ): <A extends DateTime>(self: A) => A\n  <A extends DateTime>(\n    self: A,\n    part: DateTime.UnitSingular,\n    options?: { readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined }\n  ): A\n} = Internal.nearest\n\n// =============================================================================\n// formatting\n// =============================================================================\n\n/**\n * Format a `DateTime` as a string using the `DateTimeFormat` API.\n *\n * The `timeZone` option is set to the offset of the time zone.\n *\n * Note: On Node versions < 22, fixed \"Offset\" zones will set the time zone to\n * \"UTC\" and use the adjusted `Date`.\n *\n * @since 3.6.0\n * @category formatting\n */\nexport const format: {\n  (\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): (self: DateTime) => string\n  (\n    self: DateTime,\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): string\n} = Internal.format\n\n/**\n * Format a `DateTime` as a string using the `DateTimeFormat` API.\n *\n * It will use the system's local time zone & locale.\n *\n * @since 3.6.0\n * @category formatting\n */\nexport const formatLocal: {\n  (\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): (self: DateTime) => string\n  (\n    self: DateTime,\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): string\n} = Internal.formatLocal\n\n/**\n * Format a `DateTime` as a string using the `DateTimeFormat` API.\n *\n * This forces the time zone to be UTC.\n *\n * @since 3.6.0\n * @category formatting\n */\nexport const formatUtc: {\n  (\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): (self: DateTime) => string\n  (\n    self: DateTime,\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): string\n} = Internal.formatUtc\n\n/**\n * Format a `DateTime` as a string using the `DateTimeFormat` API.\n *\n * @since 3.6.0\n * @category formatting\n */\nexport const formatIntl: {\n  (format: Intl.DateTimeFormat): (self: DateTime) => string\n  (self: DateTime, format: Intl.DateTimeFormat): string\n} = Internal.formatIntl\n\n/**\n * Format a `DateTime` as a UTC ISO string.\n *\n * @since 3.6.0\n * @category formatting\n */\nexport const formatIso: (self: DateTime) => string = Internal.formatIso\n\n/**\n * Format a `DateTime` as a time zone adjusted ISO date string.\n *\n * @since 3.6.0\n * @category formatting\n */\nexport const formatIsoDate: (self: DateTime) => string = Internal.formatIsoDate\n\n/**\n * Format a `DateTime` as a UTC ISO date string.\n *\n * @since 3.6.0\n * @category formatting\n */\nexport const formatIsoDateUtc: (self: DateTime) => string = Internal.formatIsoDateUtc\n\n/**\n * Format a `DateTime.Zoned` as a ISO string with an offset.\n *\n * @since 3.6.0\n * @category formatting\n */\nexport const formatIsoOffset: (self: DateTime) => string = Internal.formatIsoOffset\n\n/**\n * Format a `DateTime.Zoned` as a string.\n *\n * It uses the format: `YYYY-MM-DDTHH:mm:ss.sss+HH:MM[Time/Zone]`.\n *\n * @since 3.6.0\n * @category formatting\n */\nexport const formatIsoZoned: (self: Zoned) => string = Internal.formatIsoZoned\n\n/**\n * Create a Layer from the given time zone.\n *\n * @since 3.6.0\n * @category current time zone\n */\nexport const layerCurrentZone = (zone: TimeZone): Layer.Layer<CurrentTimeZone> => Layer.succeed(CurrentTimeZone, zone)\n\n/**\n * Create a Layer from the given time zone offset.\n *\n * @since 3.6.0\n * @category current time zone\n */\nexport const layerCurrentZoneOffset = (offset: number): Layer.Layer<CurrentTimeZone> =>\n  Layer.succeed(CurrentTimeZone, Internal.zoneMakeOffset(offset))\n\n/**\n * Create a Layer from the given IANA time zone identifier.\n *\n * @since 3.6.0\n * @category current time zone\n */\nexport const layerCurrentZoneNamed = (\n  zoneId: string\n): Layer.Layer<CurrentTimeZone, IllegalArgumentException> =>\n  Layer.effect(CurrentTimeZone, Internal.zoneMakeNamedEffect(zoneId))\n\n/**\n * Create a Layer from the systems local time zone.\n *\n * @since 3.6.0\n * @category current time zone\n */\nexport const layerCurrentZoneLocal: Layer.Layer<CurrentTimeZone> = Layer.sync(CurrentTimeZone, zoneMakeLocal)\n"
  },
  {
    "path": "packages/effect/src/DefaultServices.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Clock from \"./Clock.js\"\nimport type * as ConfigProvider from \"./ConfigProvider.js\"\nimport type * as Console from \"./Console.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as FiberRef from \"./FiberRef.js\"\nimport * as internal from \"./internal/defaultServices.js\"\nimport type * as Random from \"./Random.js\"\nimport type * as Tracer from \"./Tracer.js\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type DefaultServices =\n  | Clock.Clock\n  | Console.Console\n  | Random.Random\n  | ConfigProvider.ConfigProvider\n  | Tracer.Tracer\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const liveServices: Context.Context<DefaultServices> = internal.liveServices\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentServices: FiberRef.FiberRef<Context.Context<DefaultServices>> = internal.currentServices\n"
  },
  {
    "path": "packages/effect/src/Deferred.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport * as core from \"./internal/core.js\"\nimport * as internal from \"./internal/deferred.js\"\nimport type * as MutableRef from \"./MutableRef.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const DeferredTypeId: unique symbol = internal.DeferredTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type DeferredTypeId = typeof DeferredTypeId\n\n/**\n * A `Deferred` represents an asynchronous variable that can be set exactly\n * once, with the ability for an arbitrary number of fibers to suspend (by\n * calling `Deferred.await`) and automatically resume when the variable is set.\n *\n * `Deferred` can be used for building primitive actions whose completions\n * require the coordinated action of multiple fibers, and for building\n * higher-level concurrent or asynchronous structures.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Deferred<in out A, in out E = never> extends Effect.Effect<A, E>, Deferred.Variance<A, E> {\n  /** @internal */\n  readonly state: MutableRef.MutableRef<internal.State<A, E>>\n  /** @internal */\n  readonly blockingOn: FiberId.FiberId\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: DeferredUnify<this>\n  readonly [Unify.ignoreSymbol]?: DeferredUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface DeferredUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  Deferred?: () => Extract<A[Unify.typeSymbol], Deferred<any, any>>\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface DeferredUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Deferred {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A, in out E> {\n    readonly [DeferredTypeId]: {\n      readonly _A: Types.Invariant<A>\n      readonly _E: Types.Invariant<E>\n    }\n  }\n}\n\n/**\n * Creates a new `Deferred`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A, E = never>() => Effect.Effect<Deferred<A, E>> = core.deferredMake\n\n/**\n * Creates a new `Deferred` from the specified `FiberId`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeAs: <A, E = never>(fiberId: FiberId.FiberId) => Effect.Effect<Deferred<A, E>> = core.deferredMakeAs\n\nconst _await: <A, E>(self: Deferred<A, E>) => Effect.Effect<A, E> = core.deferredAwait\n\nexport {\n  /**\n   * Retrieves the value of the `Deferred`, suspending the fiber running the\n   * workflow until the result is available.\n   *\n   * @since 2.0.0\n   * @category getters\n   */\n  _await as await\n}\n\n/**\n * Completes the deferred with the result of the specified effect. If the\n * deferred has already been completed, the method will produce false.\n *\n * Note that `Deferred.completeWith` will be much faster, so consider using\n * that if you do not need to memoize the result of the specified effect.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const complete: {\n  <A, E>(effect: Effect.Effect<A, E>): (self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, effect: Effect.Effect<A, E>): Effect.Effect<boolean>\n} = core.deferredComplete\n\n/**\n * Completes the deferred with the result of the specified effect. If the\n * deferred has already been completed, the method will produce false.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const completeWith: {\n  <A, E>(effect: Effect.Effect<A, E>): (self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, effect: Effect.Effect<A, E>): Effect.Effect<boolean>\n} = core.deferredCompleteWith\n\n/**\n * Exits the `Deferred` with the specified `Exit` value, which will be\n * propagated to all fibers waiting on the value of the `Deferred`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const done: {\n  <A, E>(exit: Exit.Exit<A, E>): (self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, exit: Exit.Exit<A, E>): Effect.Effect<boolean>\n} = core.deferredDone\n\n/**\n * Fails the `Deferred` with the specified error, which will be propagated to\n * all fibers waiting on the value of the `Deferred`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const fail: {\n  <E>(error: E): <A>(self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, error: E): Effect.Effect<boolean>\n} = core.deferredFail\n\n/**\n * Fails the `Deferred` with the specified error, which will be propagated to\n * all fibers waiting on the value of the `Deferred`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const failSync: {\n  <E>(evaluate: LazyArg<E>): <A>(self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, evaluate: LazyArg<E>): Effect.Effect<boolean>\n} = core.deferredFailSync\n\n/**\n * Fails the `Deferred` with the specified `Cause`, which will be propagated to\n * all fibers waiting on the value of the `Deferred`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const failCause: {\n  <E>(cause: Cause.Cause<E>): <A>(self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, cause: Cause.Cause<E>): Effect.Effect<boolean>\n} = core.deferredFailCause\n\n/**\n * Fails the `Deferred` with the specified `Cause`, which will be propagated to\n * all fibers waiting on the value of the `Deferred`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const failCauseSync: {\n  <E>(evaluate: LazyArg<Cause.Cause<E>>): <A>(self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, evaluate: LazyArg<Cause.Cause<E>>): Effect.Effect<boolean>\n} = core.deferredFailCauseSync\n\n/**\n * Kills the `Deferred` with the specified defect, which will be propagated to\n * all fibers waiting on the value of the `Deferred`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const die: {\n  (defect: unknown): <A, E>(self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, defect: unknown): Effect.Effect<boolean>\n} = core.deferredDie\n\n/**\n * Kills the `Deferred` with the specified defect, which will be propagated to\n * all fibers waiting on the value of the `Deferred`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const dieSync: {\n  (evaluate: LazyArg<unknown>): <A, E>(self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, evaluate: LazyArg<unknown>): Effect.Effect<boolean>\n} = core.deferredDieSync\n\n/**\n * Completes the `Deferred` with interruption. This will interrupt all fibers\n * waiting on the value of the `Deferred` with the `FiberId` of the fiber\n * calling this method.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const interrupt: <A, E>(self: Deferred<A, E>) => Effect.Effect<boolean> = core.deferredInterrupt\n\n/**\n * Completes the `Deferred` with interruption. This will interrupt all fibers\n * waiting on the value of the `Deferred` with the specified `FiberId`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const interruptWith: {\n  (fiberId: FiberId.FiberId): <A, E>(self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, fiberId: FiberId.FiberId): Effect.Effect<boolean>\n} = core.deferredInterruptWith\n\n/**\n * Returns `true` if this `Deferred` has already been completed with a value or\n * an error, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isDone: <A, E>(self: Deferred<A, E>) => Effect.Effect<boolean> = core.deferredIsDone\n\n/**\n * Returns a `Some<Effect<A, E, R>>` from the `Deferred` if this `Deferred` has\n * already been completed, `None` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const poll: <A, E>(\n  self: Deferred<A, E>\n) => Effect.Effect<Option.Option<Effect.Effect<A, E>>> = core.deferredPoll\n\n/**\n * Completes the `Deferred` with the specified value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const succeed: {\n  <A>(value: A): <E>(self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, value: A): Effect.Effect<boolean>\n} = core.deferredSucceed\n\n/**\n * Completes the `Deferred` with the specified lazily evaluated value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const sync: {\n  <A>(evaluate: LazyArg<A>): <E>(self: Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred<A, E>, evaluate: LazyArg<A>): Effect.Effect<boolean>\n} = core.deferredSync\n\n/**\n * Unsafely creates a new `Deferred` from the specified `FiberId`.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeMake: <A, E = never>(fiberId: FiberId.FiberId) => Deferred<A, E> = core.deferredUnsafeMake\n\n/**\n * Unsafely exits the `Deferred` with the specified `Exit` value, which will be\n * propagated to all fibers waiting on the value of the `Deferred`.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeDone: <A, E>(self: Deferred<A, E>, effect: Effect.Effect<A, E>) => void = core.deferredUnsafeDone\n"
  },
  {
    "path": "packages/effect/src/Differ.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { Chunk } from \"./Chunk.js\"\nimport type { Context } from \"./Context.js\"\nimport type { Either } from \"./Either.js\"\nimport type { Equal } from \"./Equal.js\"\nimport * as Dual from \"./Function.js\"\nimport type { HashMap } from \"./HashMap.js\"\nimport type { HashSet } from \"./HashSet.js\"\nimport * as internal from \"./internal/differ.js\"\nimport * as ChunkPatch from \"./internal/differ/chunkPatch.js\"\nimport * as ContextPatch from \"./internal/differ/contextPatch.js\"\nimport * as HashMapPatch from \"./internal/differ/hashMapPatch.js\"\nimport * as HashSetPatch from \"./internal/differ/hashSetPatch.js\"\nimport * as OrPatch from \"./internal/differ/orPatch.js\"\nimport * as ReadonlyArrayPatch from \"./internal/differ/readonlyArrayPatch.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport const TypeId: unique symbol = internal.DifferTypeId as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * A `Differ<Value, Patch>` knows how to compare an old value and new value of\n * type `Value` to produce a patch of type `Patch` that describes the\n * differences between those values. A `Differ` also knows how to apply a patch\n * to an old value to produce a new value that represents the old value updated\n * with the changes described by the patch.\n *\n * A `Differ` can be used to construct a `FiberRef` supporting compositional\n * updates using the `FiberRef.makePatch` constructor.\n *\n * The `Differ` companion object contains constructors for `Differ` values for\n * common data types such as `Chunk`, `HashMap`, and `HashSet``. In addition,\n * `Differ`values can be transformed using the `transform` operator and combined\n * using the `orElseEither` and `zip` operators. This allows creating `Differ`\n * values for arbitrarily complex data types compositionally.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Differ<in out Value, in out Patch> extends Pipeable {\n  readonly [TypeId]: {\n    readonly _V: Types.Invariant<Value>\n    readonly _P: Types.Invariant<Patch>\n  }\n  readonly empty: Patch\n  diff(oldValue: Value, newValue: Value): Patch\n  combine(first: Patch, second: Patch): Patch\n  patch(patch: Patch, oldValue: Value): Value\n}\n\nconst ChunkPatchTypeId: unique symbol = ChunkPatch.ChunkPatchTypeId as Differ.Chunk.TypeId\nconst ContextPatchTypeId: unique symbol = ContextPatch.ContextPatchTypeId as Differ.Context.TypeId\nconst HashMapPatchTypeId: unique symbol = HashMapPatch.HashMapPatchTypeId as Differ.HashMap.TypeId\nconst HashSetPatchTypeId: unique symbol = HashSetPatch.HashSetPatchTypeId as Differ.HashSet.TypeId\nconst OrPatchTypeId: unique symbol = OrPatch.OrPatchTypeId as Differ.Or.TypeId\nconst ReadonlyArrayPatchTypeId: unique symbol = ReadonlyArrayPatch\n  .ReadonlyArrayPatchTypeId as Differ.ReadonlyArray.TypeId\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Differ {\n  /**\n   * @since 2.0.0\n   */\n  export namespace Context {\n    /**\n     * @since 2.0.0\n     * @category symbol\n     */\n    export type TypeId = typeof ContextPatchTypeId\n    /**\n     * A `Patch<Input, Output>` describes an update that transforms a `Env<Input>`\n     * to a `Env<Output>` as a data structure. This allows combining updates to\n     * different services in the environment in a compositional way.\n     *\n     * @since 2.0.0\n     * @category models\n     */\n    export interface Patch<in Input, out Output> extends Equal {\n      readonly [ContextPatchTypeId]: {\n        readonly _Input: Types.Contravariant<Input>\n        readonly _Output: Types.Covariant<Output>\n      }\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  export namespace Chunk {\n    /**\n     * @since 2.0.0\n     * @category symbol\n     */\n    export type TypeId = typeof ChunkPatchTypeId\n    /**\n     * A patch which describes updates to a chunk of values.\n     *\n     * @since 2.0.0\n     * @category models\n     */\n    export interface Patch<in out Value, in out Patch> extends Equal {\n      readonly [ChunkPatchTypeId]: {\n        readonly _Value: Types.Invariant<Value>\n        readonly _Patch: Types.Invariant<Patch>\n      }\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  export namespace HashMap {\n    /**\n     * @since 2.0.0\n     * @category symbol\n     */\n    export type TypeId = typeof HashMapPatchTypeId\n    /**\n     * A patch which describes updates to a map of keys and values.\n     *\n     * @since 2.0.0\n     * @category models\n     */\n    export interface Patch<in out Key, in out Value, in out Patch> extends Equal {\n      readonly [HashMapPatchTypeId]: {\n        readonly _Key: Types.Invariant<Key>\n        readonly _Value: Types.Invariant<Value>\n        readonly _Patch: Types.Invariant<Patch>\n      }\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  export namespace HashSet {\n    /**\n     * @since 2.0.0\n     * @category symbol\n     */\n    export type TypeId = typeof HashSetPatchTypeId\n    /**\n     * A patch which describes updates to a set of values.\n     *\n     * @since 2.0.0\n     * @category models\n     */\n    export interface Patch<in out Value> extends Equal {\n      readonly [HashSetPatchTypeId]: {\n        readonly _Value: Types.Invariant<Value>\n      }\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  export namespace Or {\n    /**\n     * @since 2.0.0\n     * @category symbol\n     */\n    export type TypeId = typeof OrPatchTypeId\n    /**\n     * A patch which describes updates to either one value or another.\n     *\n     * @since 2.0.0\n     * @category models\n     */\n    export interface Patch<in out Value, in out Value2, in out Patch, in out Patch2> extends Equal {\n      readonly [OrPatchTypeId]: {\n        readonly _Value: Types.Invariant<Value>\n        readonly _Value2: Types.Invariant<Value2>\n        readonly _Patch: Types.Invariant<Patch>\n        readonly _Patch2: Types.Invariant<Patch2>\n      }\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  export namespace ReadonlyArray {\n    /**\n     * @since 2.0.0\n     * @category symbol\n     */\n    export type TypeId = typeof ReadonlyArrayPatchTypeId\n    /**\n     * A patch which describes updates to a ReadonlyArray of values.\n     *\n     * @since 2.0.0\n     * @category models\n     */\n    export interface Patch<in out Value, in out Patch> extends Equal {\n      readonly [ReadonlyArrayPatchTypeId]: {\n        readonly _Value: Types.Invariant<Value>\n        readonly _Patch: Types.Invariant<Patch>\n      }\n    }\n  }\n}\n\n/**\n * An empty patch that describes no changes.\n *\n * @since 2.0.0\n * @category patch\n */\nexport const empty: <Value, Patch>(self: Differ<Value, Patch>) => Patch = (\n  self\n) => self.empty\n\n/**\n * @since 2.0.0\n * @category patch\n */\nexport const diff: {\n  <Value>(oldValue: Value, newValue: Value): <Patch>(\n    self: Differ<Value, Patch>\n  ) => Patch\n  <Value, Patch>(\n    self: Differ<Value, Patch>,\n    oldValue: Value,\n    newValue: Value\n  ): Patch\n} = Dual.dual(\n  3,\n  <Value, Patch>(\n    self: Differ<Value, Patch>,\n    oldValue: Value,\n    newValue: Value\n  ): Patch => self.diff(oldValue, newValue)\n)\n\n/**\n * Combines two patches to produce a new patch that describes the updates of\n * the first patch and then the updates of the second patch. The combine\n * operation should be associative. In addition, if the combine operation is\n * commutative then joining multiple fibers concurrently will result in\n * deterministic `FiberRef` values.\n *\n * @since 2.0.0\n * @category patch\n */\nexport const combine: {\n  <Patch>(first: Patch, second: Patch): <Value>(\n    self: Differ<Value, Patch>\n  ) => Patch\n  <Value, Patch>(\n    self: Differ<Value, Patch>,\n    first: Patch,\n    second: Patch\n  ): Patch\n} = Dual.dual(\n  3,\n  <Value, Patch>(\n    self: Differ<Value, Patch>,\n    first: Patch,\n    second: Patch\n  ): Patch => self.combine(first, second)\n)\n\n/**\n * Applies a patch to an old value to produce a new value that is equal to the\n * old value with the updates described by the patch.\n *\n * @since 2.0.0\n * @category patch\n */\nexport const patch: {\n  <Patch, Value>(patch: Patch, oldValue: Value): (\n    self: Differ<Value, Patch>\n  ) => Value\n  <Patch, Value>(\n    self: Differ<Value, Patch>,\n    patch: Patch,\n    oldValue: Value\n  ): Value\n} = Dual.dual(\n  3,\n  <Patch, Value>(\n    self: Differ<Value, Patch>,\n    patch: Patch,\n    oldValue: Value\n  ): Value => self.patch(patch, oldValue)\n)\n\n/**\n * Constructs a new `Differ`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Value, Patch>(params: {\n  readonly empty: Patch\n  readonly diff: (oldValue: Value, newValue: Value) => Patch\n  readonly combine: (first: Patch, second: Patch) => Patch\n  readonly patch: (patch: Patch, oldValue: Value) => Value\n}) => Differ<Value, Patch> = internal.make\n\n/**\n * Constructs a differ that knows how to diff `Env` values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const environment: <A>() => Differ<\n  Context<A>,\n  Differ.Context.Patch<A, A>\n> = internal.environment\n\n/**\n * Constructs a differ that knows how to diff a `Chunk` of values given a\n * differ that knows how to diff the values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const chunk: <Value, Patch>(\n  differ: Differ<Value, Patch>\n) => Differ<Chunk<Value>, Differ.Chunk.Patch<Value, Patch>> = internal.chunk\n\n/**\n * Constructs a differ that knows how to diff a `HashMap` of keys and values given\n * a differ that knows how to diff the values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const hashMap: <Key, Value, Patch>(\n  differ: Differ<Value, Patch>\n) => Differ<HashMap<Key, Value>, Differ.HashMap.Patch<Key, Value, Patch>> = internal.hashMap\n\n/**\n * Constructs a differ that knows how to diff a `HashSet` of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const hashSet: <Value>() => Differ<\n  HashSet<Value>,\n  Differ.HashSet.Patch<Value>\n> = internal.hashSet\n\n/**\n * Combines this differ and the specified differ to produce a differ that\n * knows how to diff the sum of their values.\n *\n * @since 2.0.0\n */\nexport const orElseEither: {\n  <Value2, Patch2>(that: Differ<Value2, Patch2>): <Value, Patch>(\n    self: Differ<Value, Patch>\n  ) => Differ<\n    Either<Value2, Value>,\n    Differ.Or.Patch<Value, Value2, Patch, Patch2>\n  >\n  <Value, Patch, Value2, Patch2>(\n    self: Differ<Value, Patch>,\n    that: Differ<Value2, Patch2>\n  ): Differ<\n    Either<Value2, Value>,\n    Differ.Or.Patch<Value, Value2, Patch, Patch2>\n  >\n} = internal.orElseEither\n\n/**\n * Constructs a differ that knows how to diff a `ReadonlyArray` of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const readonlyArray: <Value, Patch>(\n  differ: Differ<Value, Patch>\n) => Differ<ReadonlyArray<Value>, Differ.ReadonlyArray.Patch<Value, Patch>> = internal.readonlyArray\n\n/**\n * Transforms the type of values that this differ knows how to differ using\n * the specified functions that map the new and old value types to each other.\n *\n * @since 2.0.0\n */\nexport const transform: {\n  <Value, Value2>(options: {\n    readonly toNew: (value: Value) => Value2\n    readonly toOld: (value: Value2) => Value\n  }): <Patch>(self: Differ<Value, Patch>) => Differ<Value2, Patch>\n  <Value, Patch, Value2>(\n    self: Differ<Value, Patch>,\n    options: {\n      readonly toNew: (value: Value) => Value2\n      readonly toOld: (value: Value2) => Value\n    }\n  ): Differ<Value2, Patch>\n} = internal.transform\n\n/**\n * Constructs a differ that just diffs two values by returning a function that\n * sets the value to the new value. This differ does not support combining\n * multiple updates to the value compositionally and should only be used when\n * there is no compositional way to update them.\n *\n * @since 2.0.0\n */\nexport const update: <A>() => Differ<A, (a: A) => A> = internal.update\n\n/**\n * A variant of `update` that allows specifying the function that will be used\n * to combine old values with new values.\n *\n * @since 2.0.0\n */\nexport const updateWith: <A>(f: (x: A, y: A) => A) => Differ<A, (a: A) => A> = internal.updateWith\n\n/**\n * Combines this differ and the specified differ to produce a new differ that\n * knows how to diff the product of their values.\n *\n * @since 2.0.0\n */\nexport const zip: {\n  <Value2, Patch2>(that: Differ<Value2, Patch2>): <Value, Patch>(\n    self: Differ<Value, Patch>\n  ) => Differ<\n    readonly [Value, Value2], // readonly because invariant\n    readonly [Patch, Patch2] // readonly because invariant\n  >\n  <Value, Patch, Value2, Patch2>(\n    self: Differ<Value, Patch>,\n    that: Differ<Value2, Patch2>\n  ): Differ<\n    readonly [Value, Value2], // readonly because invariant\n    readonly [Patch, Patch2] // readonly because invariant\n  >\n} = internal.zip\n"
  },
  {
    "path": "packages/effect/src/Duration.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\"\nimport type * as equivalence from \"./Equivalence.js\"\nimport { dual } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport { NodeInspectSymbol } from \"./Inspectable.js\"\nimport * as Option from \"./Option.js\"\nimport * as order from \"./Order.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\nimport { hasProperty, isBigInt, isNumber, isString } from \"./Predicate.js\"\n\nconst TypeId: unique symbol = Symbol.for(\"effect/Duration\")\n\nconst bigint0 = BigInt(0)\nconst bigint24 = BigInt(24)\nconst bigint60 = BigInt(60)\nconst bigint1e3 = BigInt(1_000)\nconst bigint1e6 = BigInt(1_000_000)\nconst bigint1e9 = BigInt(1_000_000_000)\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Duration extends Equal.Equal, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n  readonly value: DurationValue\n}\n/**\n * @since 2.0.0\n * @category models\n */\nexport type DurationValue =\n  | {\n    readonly _tag: \"Millis\"\n    readonly millis: number\n  }\n  | {\n    readonly _tag: \"Nanos\"\n    readonly nanos: bigint\n  }\n  | {\n    readonly _tag: \"Infinity\"\n  }\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type Unit =\n  | \"nano\"\n  | \"nanos\"\n  | \"micro\"\n  | \"micros\"\n  | \"milli\"\n  | \"millis\"\n  | \"second\"\n  | \"seconds\"\n  | \"minute\"\n  | \"minutes\"\n  | \"hour\"\n  | \"hours\"\n  | \"day\"\n  | \"days\"\n  | \"week\"\n  | \"weeks\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type DurationInput =\n  | Duration\n  | number // millis\n  | bigint // nanos\n  | readonly [seconds: number, nanos: number]\n  | `${number} ${Unit}`\n\nconst DURATION_REGEX = /^(-?\\d+(?:\\.\\d+)?)\\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/\n\n/**\n * @since 2.0.0\n */\nexport const decode = (input: DurationInput): Duration => {\n  if (isDuration(input)) {\n    return input\n  } else if (isNumber(input)) {\n    return millis(input)\n  } else if (isBigInt(input)) {\n    return nanos(input)\n  } else if (Array.isArray(input) && input.length === 2 && input.every(isNumber)) {\n    if (input[0] === -Infinity || input[1] === -Infinity || Number.isNaN(input[0]) || Number.isNaN(input[1])) {\n      return zero\n    }\n\n    if (input[0] === Infinity || input[1] === Infinity) {\n      return infinity\n    }\n\n    return nanos(BigInt(Math.round(input[0] * 1_000_000_000)) + BigInt(Math.round(input[1])))\n  } else if (isString(input)) {\n    const match = DURATION_REGEX.exec(input)\n    if (match) {\n      const [_, valueStr, unit] = match\n      const value = Number(valueStr)\n      switch (unit) {\n        case \"nano\":\n        case \"nanos\":\n          return nanos(BigInt(valueStr))\n        case \"micro\":\n        case \"micros\":\n          return micros(BigInt(valueStr))\n        case \"milli\":\n        case \"millis\":\n          return millis(value)\n        case \"second\":\n        case \"seconds\":\n          return seconds(value)\n        case \"minute\":\n        case \"minutes\":\n          return minutes(value)\n        case \"hour\":\n        case \"hours\":\n          return hours(value)\n        case \"day\":\n        case \"days\":\n          return days(value)\n        case \"week\":\n        case \"weeks\":\n          return weeks(value)\n      }\n    }\n  }\n  throw new Error(\"Invalid DurationInput\")\n}\n\n/**\n * @since 2.5.0\n */\nexport const decodeUnknown: (u: unknown) => Option.Option<Duration> = Option.liftThrowable(decode) as any\n\nconst zeroValue: DurationValue = { _tag: \"Millis\", millis: 0 }\nconst infinityValue: DurationValue = { _tag: \"Infinity\" }\n\nconst DurationProto: Omit<Duration, \"value\"> = {\n  [TypeId]: TypeId,\n  [Hash.symbol](this: Duration) {\n    return Hash.cached(this, Hash.structure(this.value))\n  },\n  [Equal.symbol](this: Duration, that: unknown): boolean {\n    return isDuration(that) && equals(this, that)\n  },\n  toString(this: Duration) {\n    return `Duration(${format(this)})`\n  },\n  toJSON(this: Duration) {\n    switch (this.value._tag) {\n      case \"Millis\":\n        return { _id: \"Duration\", _tag: \"Millis\", millis: this.value.millis }\n      case \"Nanos\":\n        return { _id: \"Duration\", _tag: \"Nanos\", hrtime: toHrTime(this) }\n      case \"Infinity\":\n        return { _id: \"Duration\", _tag: \"Infinity\" }\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n} as const\n\nconst make = (input: number | bigint): Duration => {\n  const duration = Object.create(DurationProto)\n  if (isNumber(input)) {\n    if (isNaN(input) || input <= 0) {\n      duration.value = zeroValue\n    } else if (!Number.isFinite(input)) {\n      duration.value = infinityValue\n    } else if (!Number.isInteger(input)) {\n      duration.value = { _tag: \"Nanos\", nanos: BigInt(Math.round(input * 1_000_000)) }\n    } else {\n      duration.value = { _tag: \"Millis\", millis: input }\n    }\n  } else if (input <= bigint0) {\n    duration.value = zeroValue\n  } else {\n    duration.value = { _tag: \"Nanos\", nanos: input }\n  }\n  return duration\n}\n\n/**\n * @since 2.0.0\n * @category guards\n */\nexport const isDuration = (u: unknown): u is Duration => hasProperty(u, TypeId)\n\n/**\n * @since 2.0.0\n * @category guards\n */\nexport const isFinite = (self: Duration): boolean => self.value._tag !== \"Infinity\"\n\n/**\n * @since 3.5.0\n * @category guards\n */\nexport const isZero = (self: Duration): boolean => {\n  switch (self.value._tag) {\n    case \"Millis\": {\n      return self.value.millis === 0\n    }\n    case \"Nanos\": {\n      return self.value.nanos === bigint0\n    }\n    case \"Infinity\": {\n      return false\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const zero: Duration = make(0)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const infinity: Duration = make(Infinity)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const nanos = (nanos: bigint): Duration => make(nanos)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const micros = (micros: bigint): Duration => make(micros * bigint1e3)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const millis = (millis: number): Duration => make(millis)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const seconds = (seconds: number): Duration => make(seconds * 1000)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const minutes = (minutes: number): Duration => make(minutes * 60_000)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const hours = (hours: number): Duration => make(hours * 3_600_000)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const days = (days: number): Duration => make(days * 86_400_000)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const weeks = (weeks: number): Duration => make(weeks * 604_800_000)\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const toMillis = (self: DurationInput): number =>\n  match(self, {\n    onMillis: (millis) => millis,\n    onNanos: (nanos) => Number(nanos) / 1_000_000\n  })\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const toSeconds = (self: DurationInput): number =>\n  match(self, {\n    onMillis: (millis) => millis / 1_000,\n    onNanos: (nanos) => Number(nanos) / 1_000_000_000\n  })\n\n/**\n * @since 3.8.0\n * @category getters\n */\nexport const toMinutes = (self: DurationInput): number =>\n  match(self, {\n    onMillis: (millis) => millis / 60_000,\n    onNanos: (nanos) => Number(nanos) / 60_000_000_000\n  })\n\n/**\n * @since 3.8.0\n * @category getters\n */\nexport const toHours = (self: DurationInput): number =>\n  match(self, {\n    onMillis: (millis) => millis / 3_600_000,\n    onNanos: (nanos) => Number(nanos) / 3_600_000_000_000\n  })\n\n/**\n * @since 3.8.0\n * @category getters\n */\nexport const toDays = (self: DurationInput): number =>\n  match(self, {\n    onMillis: (millis) => millis / 86_400_000,\n    onNanos: (nanos) => Number(nanos) / 86_400_000_000_000\n  })\n\n/**\n * @since 3.8.0\n * @category getters\n */\nexport const toWeeks = (self: DurationInput): number =>\n  match(self, {\n    onMillis: (millis) => millis / 604_800_000,\n    onNanos: (nanos) => Number(nanos) / 604_800_000_000_000\n  })\n\n/**\n * Get the duration in nanoseconds as a bigint.\n *\n * If the duration is infinite, returns `Option.none()`\n *\n * @since 2.0.0\n * @category getters\n */\nexport const toNanos = (self: DurationInput): Option.Option<bigint> => {\n  const _self = decode(self)\n  switch (_self.value._tag) {\n    case \"Infinity\":\n      return Option.none()\n    case \"Nanos\":\n      return Option.some(_self.value.nanos)\n    case \"Millis\":\n      return Option.some(BigInt(Math.round(_self.value.millis * 1_000_000)))\n  }\n}\n\n/**\n * Get the duration in nanoseconds as a bigint.\n *\n * If the duration is infinite, it throws an error.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const unsafeToNanos = (self: DurationInput): bigint => {\n  const _self = decode(self)\n  switch (_self.value._tag) {\n    case \"Infinity\":\n      throw new Error(\"Cannot convert infinite duration to nanos\")\n    case \"Nanos\":\n      return _self.value.nanos\n    case \"Millis\":\n      return BigInt(Math.round(_self.value.millis * 1_000_000))\n  }\n}\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const toHrTime = (self: DurationInput): [seconds: number, nanos: number] => {\n  const _self = decode(self)\n  switch (_self.value._tag) {\n    case \"Infinity\":\n      return [Infinity, 0]\n    case \"Nanos\":\n      return [\n        Number(_self.value.nanos / bigint1e9),\n        Number(_self.value.nanos % bigint1e9)\n      ]\n    case \"Millis\":\n      return [\n        Math.floor(_self.value.millis / 1000),\n        Math.round((_self.value.millis % 1000) * 1_000_000)\n      ]\n  }\n}\n\n/**\n * @since 2.0.0\n * @category pattern matching\n */\nexport const match: {\n  <A, B>(\n    options: {\n      readonly onMillis: (millis: number) => A\n      readonly onNanos: (nanos: bigint) => B\n    }\n  ): (self: DurationInput) => A | B\n  <A, B>(\n    self: DurationInput,\n    options: {\n      readonly onMillis: (millis: number) => A\n      readonly onNanos: (nanos: bigint) => B\n    }\n  ): A | B\n} = dual(2, <A, B>(\n  self: DurationInput,\n  options: {\n    readonly onMillis: (millis: number) => A\n    readonly onNanos: (nanos: bigint) => B\n  }\n): A | B => {\n  const _self = decode(self)\n  switch (_self.value._tag) {\n    case \"Nanos\":\n      return options.onNanos(_self.value.nanos)\n    case \"Infinity\":\n      return options.onMillis(Infinity)\n    case \"Millis\":\n      return options.onMillis(_self.value.millis)\n  }\n})\n\n/**\n * @since 2.0.0\n * @category pattern matching\n */\nexport const matchWith: {\n  <A, B>(\n    that: DurationInput,\n    options: {\n      readonly onMillis: (self: number, that: number) => A\n      readonly onNanos: (self: bigint, that: bigint) => B\n    }\n  ): (self: DurationInput) => A | B\n  <A, B>(\n    self: DurationInput,\n    that: DurationInput,\n    options: {\n      readonly onMillis: (self: number, that: number) => A\n      readonly onNanos: (self: bigint, that: bigint) => B\n    }\n  ): A | B\n} = dual(3, <A, B>(\n  self: DurationInput,\n  that: DurationInput,\n  options: {\n    readonly onMillis: (self: number, that: number) => A\n    readonly onNanos: (self: bigint, that: bigint) => B\n  }\n): A | B => {\n  const _self = decode(self)\n  const _that = decode(that)\n  if (_self.value._tag === \"Infinity\" || _that.value._tag === \"Infinity\") {\n    return options.onMillis(\n      toMillis(_self),\n      toMillis(_that)\n    )\n  } else if (_self.value._tag === \"Nanos\" || _that.value._tag === \"Nanos\") {\n    const selfNanos = _self.value._tag === \"Nanos\" ?\n      _self.value.nanos :\n      BigInt(Math.round(_self.value.millis * 1_000_000))\n    const thatNanos = _that.value._tag === \"Nanos\" ?\n      _that.value.nanos :\n      BigInt(Math.round(_that.value.millis * 1_000_000))\n    return options.onNanos(selfNanos, thatNanos)\n  }\n\n  return options.onMillis(\n    _self.value.millis,\n    _that.value.millis\n  )\n})\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Order: order.Order<Duration> = order.make((self, that) =>\n  matchWith(self, that, {\n    onMillis: (self, that) => (self < that ? -1 : self > that ? 1 : 0),\n    onNanos: (self, that) => (self < that ? -1 : self > that ? 1 : 0)\n  })\n)\n\n/**\n * Checks if a `Duration` is between a `minimum` and `maximum` value.\n *\n * @category predicates\n * @since 2.0.0\n */\nexport const between: {\n  (options: {\n    minimum: DurationInput\n    maximum: DurationInput\n  }): (self: DurationInput) => boolean\n  (self: DurationInput, options: {\n    minimum: DurationInput\n    maximum: DurationInput\n  }): boolean\n} = order.between(order.mapInput(Order, decode))\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence: equivalence.Equivalence<Duration> = (self, that) =>\n  matchWith(self, that, {\n    onMillis: (self, that) => self === that,\n    onNanos: (self, that) => self === that\n  })\n\nconst _min = order.min(Order)\n\n/**\n * @since 2.0.0\n */\nexport const min: {\n  (that: DurationInput): (self: DurationInput) => Duration\n  (self: DurationInput, that: DurationInput): Duration\n} = dual(2, (self: DurationInput, that: DurationInput): Duration => _min(decode(self), decode(that)))\n\nconst _max = order.max(Order)\n\n/**\n * @since 2.0.0\n * @category order\n */\nexport const max: {\n  (that: DurationInput): (self: DurationInput) => Duration\n  (self: DurationInput, that: DurationInput): Duration\n} = dual(2, (self: DurationInput, that: DurationInput): Duration => _max(decode(self), decode(that)))\n\nconst _clamp = order.clamp(Order)\n\n/**\n * @since 2.0.0\n * @category order\n */\nexport const clamp: {\n  (options: {\n    minimum: DurationInput\n    maximum: DurationInput\n  }): (self: DurationInput) => Duration\n  (self: DurationInput, options: {\n    minimum: DurationInput\n    maximum: DurationInput\n  }): Duration\n} = dual(\n  2,\n  (self: DurationInput, options: {\n    minimum: DurationInput\n    maximum: DurationInput\n  }): Duration =>\n    _clamp(decode(self), {\n      minimum: decode(options.minimum),\n      maximum: decode(options.maximum)\n    })\n)\n\n/**\n * @since 2.4.19\n * @category math\n */\nexport const divide: {\n  (by: number): (self: DurationInput) => Option.Option<Duration>\n  (self: DurationInput, by: number): Option.Option<Duration>\n} = dual(\n  2,\n  (self: DurationInput, by: number): Option.Option<Duration> =>\n    match(self, {\n      onMillis: (millis) => {\n        if (by === 0 || isNaN(by) || !Number.isFinite(by)) {\n          return Option.none()\n        }\n        return Option.some(make(millis / by))\n      },\n      onNanos: (nanos) => {\n        if (isNaN(by) || by <= 0 || !Number.isFinite(by)) {\n          return Option.none()\n        }\n        try {\n          return Option.some(make(nanos / BigInt(by)))\n        } catch {\n          return Option.none()\n        }\n      }\n    })\n)\n\n/**\n * @since 2.4.19\n * @category math\n */\nexport const unsafeDivide: {\n  (by: number): (self: DurationInput) => Duration\n  (self: DurationInput, by: number): Duration\n} = dual(\n  2,\n  (self: DurationInput, by: number): Duration =>\n    match(self, {\n      onMillis: (millis) => make(millis / by),\n      onNanos: (nanos) => {\n        if (isNaN(by) || by < 0 || Object.is(by, -0)) {\n          return zero\n        } else if (Object.is(by, 0) || !Number.isFinite(by)) {\n          return infinity\n        }\n        return make(nanos / BigInt(by))\n      }\n    })\n)\n\n/**\n * @since 2.0.0\n * @category math\n */\nexport const times: {\n  (times: number): (self: DurationInput) => Duration\n  (self: DurationInput, times: number): Duration\n} = dual(\n  2,\n  (self: DurationInput, times: number): Duration =>\n    match(self, {\n      onMillis: (millis) => make(millis * times),\n      onNanos: (nanos) => make(nanos * BigInt(times))\n    })\n)\n\n/**\n * @since 2.0.0\n * @category math\n */\nexport const subtract: {\n  (that: DurationInput): (self: DurationInput) => Duration\n  (self: DurationInput, that: DurationInput): Duration\n} = dual(\n  2,\n  (self: DurationInput, that: DurationInput): Duration =>\n    matchWith(self, that, {\n      onMillis: (self, that) => make(self - that),\n      onNanos: (self, that) => make(self - that)\n    })\n)\n\n/**\n * @since 2.0.0\n * @category math\n */\nexport const sum: {\n  (that: DurationInput): (self: DurationInput) => Duration\n  (self: DurationInput, that: DurationInput): Duration\n} = dual(\n  2,\n  (self: DurationInput, that: DurationInput): Duration =>\n    matchWith(self, that, {\n      onMillis: (self, that) => make(self + that),\n      onNanos: (self, that) => make(self + that)\n    })\n)\n\n/**\n * @since 2.0.0\n * @category predicates\n */\nexport const lessThan: {\n  (that: DurationInput): (self: DurationInput) => boolean\n  (self: DurationInput, that: DurationInput): boolean\n} = dual(\n  2,\n  (self: DurationInput, that: DurationInput): boolean =>\n    matchWith(self, that, {\n      onMillis: (self, that) => self < that,\n      onNanos: (self, that) => self < that\n    })\n)\n\n/**\n * @since 2.0.0\n * @category predicates\n */\nexport const lessThanOrEqualTo: {\n  (that: DurationInput): (self: DurationInput) => boolean\n  (self: DurationInput, that: DurationInput): boolean\n} = dual(\n  2,\n  (self: DurationInput, that: DurationInput): boolean =>\n    matchWith(self, that, {\n      onMillis: (self, that) => self <= that,\n      onNanos: (self, that) => self <= that\n    })\n)\n\n/**\n * @since 2.0.0\n * @category predicates\n */\nexport const greaterThan: {\n  (that: DurationInput): (self: DurationInput) => boolean\n  (self: DurationInput, that: DurationInput): boolean\n} = dual(\n  2,\n  (self: DurationInput, that: DurationInput): boolean =>\n    matchWith(self, that, {\n      onMillis: (self, that) => self > that,\n      onNanos: (self, that) => self > that\n    })\n)\n\n/**\n * @since 2.0.0\n * @category predicates\n */\nexport const greaterThanOrEqualTo: {\n  (that: DurationInput): (self: DurationInput) => boolean\n  (self: DurationInput, that: DurationInput): boolean\n} = dual(\n  2,\n  (self: DurationInput, that: DurationInput): boolean =>\n    matchWith(self, that, {\n      onMillis: (self, that) => self >= that,\n      onNanos: (self, that) => self >= that\n    })\n)\n\n/**\n * @since 2.0.0\n * @category predicates\n */\nexport const equals: {\n  (that: DurationInput): (self: DurationInput) => boolean\n  (self: DurationInput, that: DurationInput): boolean\n} = dual(2, (self: DurationInput, that: DurationInput): boolean => Equivalence(decode(self), decode(that)))\n\n/**\n * Converts a `Duration` to its parts.\n *\n * @since 3.8.0\n * @category conversions\n */\nexport const parts = (self: DurationInput): {\n  days: number\n  hours: number\n  minutes: number\n  seconds: number\n  millis: number\n  nanos: number\n} => {\n  const duration = decode(self)\n  if (duration.value._tag === \"Infinity\") {\n    return {\n      days: Infinity,\n      hours: Infinity,\n      minutes: Infinity,\n      seconds: Infinity,\n      millis: Infinity,\n      nanos: Infinity\n    }\n  }\n\n  const nanos = unsafeToNanos(duration)\n  const ms = nanos / bigint1e6\n  const sec = ms / bigint1e3\n  const min = sec / bigint60\n  const hr = min / bigint60\n  const days = hr / bigint24\n\n  return {\n    days: Number(days),\n    hours: Number(hr % bigint24),\n    minutes: Number(min % bigint60),\n    seconds: Number(sec % bigint60),\n    millis: Number(ms % bigint1e3),\n    nanos: Number(nanos % bigint1e6)\n  }\n}\n\n/**\n * Converts a `Duration` to a human readable string.\n *\n * @since 2.0.0\n * @category conversions\n * @example\n * ```ts\n * import { Duration } from \"effect\"\n *\n * Duration.format(Duration.millis(1000)) // \"1s\"\n * Duration.format(Duration.millis(1001)) // \"1s 1ms\"\n * ```\n */\nexport const format = (self: DurationInput): string => {\n  const duration = decode(self)\n  if (duration.value._tag === \"Infinity\") {\n    return \"Infinity\"\n  }\n  if (isZero(duration)) {\n    return \"0\"\n  }\n\n  const fragments = parts(duration)\n  const pieces = []\n  if (fragments.days !== 0) {\n    pieces.push(`${fragments.days}d`)\n  }\n\n  if (fragments.hours !== 0) {\n    pieces.push(`${fragments.hours}h`)\n  }\n\n  if (fragments.minutes !== 0) {\n    pieces.push(`${fragments.minutes}m`)\n  }\n\n  if (fragments.seconds !== 0) {\n    pieces.push(`${fragments.seconds}s`)\n  }\n\n  if (fragments.millis !== 0) {\n    pieces.push(`${fragments.millis}ms`)\n  }\n\n  if (fragments.nanos !== 0) {\n    pieces.push(`${fragments.nanos}ns`)\n  }\n\n  return pieces.join(\" \")\n}\n\n/**\n * Formats a Duration into an ISO8601 duration string.\n *\n * Months are assumed to be 30 days and years are assumed to be 365 days.\n *\n * Milliseconds and nanoseconds are expressed as fractional seconds.\n *\n * @example\n * ```ts\n * import { Duration } from \"effect\"\n *\n * Duration.unsafeFormatIso(Duration.days(1)) // => \"P1D\"\n * Duration.unsafeFormatIso(Duration.minutes(90)) // => \"PT1H30M\"\n * Duration.unsafeFormatIso(Duration.millis(1500)) // => \"PT1.5S\"\n * ```\n *\n * @throws `RangeError` If the duration is not finite.\n *\n * @since 3.13.0\n * @category conversions\n */\nexport const unsafeFormatIso = (self: DurationInput): string => {\n  const duration = decode(self)\n  if (!isFinite(duration)) {\n    throw new RangeError(\"Cannot format infinite duration\")\n  }\n\n  const fragments = []\n  const {\n    days,\n    hours,\n    millis,\n    minutes,\n    nanos,\n    seconds\n  } = parts(duration)\n\n  let rest = days\n  if (rest >= 365) {\n    const years = Math.floor(rest / 365)\n    rest %= 365\n    fragments.push(`${years}Y`)\n  }\n\n  if (rest >= 30) {\n    const months = Math.floor(rest / 30)\n    rest %= 30\n    fragments.push(`${months}M`)\n  }\n\n  if (rest >= 7) {\n    const weeks = Math.floor(rest / 7)\n    rest %= 7\n    fragments.push(`${weeks}W`)\n  }\n\n  if (rest > 0) {\n    fragments.push(`${rest}D`)\n  }\n\n  if (hours !== 0 || minutes !== 0 || seconds !== 0 || millis !== 0 || nanos !== 0) {\n    fragments.push(\"T\")\n\n    if (hours !== 0) {\n      fragments.push(`${hours}H`)\n    }\n\n    if (minutes !== 0) {\n      fragments.push(`${minutes}M`)\n    }\n\n    if (seconds !== 0 || millis !== 0 || nanos !== 0) {\n      const total = BigInt(seconds) * bigint1e9 + BigInt(millis) * bigint1e6 + BigInt(nanos)\n      const str = (Number(total) / 1e9).toFixed(9).replace(/\\.?0+$/, \"\")\n      fragments.push(`${str}S`)\n    }\n  }\n\n  return `P${fragments.join(\"\") || \"T0S\"}`\n}\n\n/**\n * Formats a Duration into an ISO8601 duration string.\n *\n * Months are assumed to be 30 days and years are assumed to be 365 days.\n *\n * Returns `Option.none()` if the duration is infinite.\n *\n * @example\n * ```ts\n * import { Duration, Option } from \"effect\"\n *\n * Duration.formatIso(Duration.days(1)) // => Option.some(\"P1D\")\n * Duration.formatIso(Duration.minutes(90)) // => Option.some(\"PT1H30M\")\n * Duration.formatIso(Duration.millis(1500)) // => Option.some(\"PT1.5S\")\n * Duration.formatIso(Duration.infinity) // => Option.none()\n * ```\n *\n * @since 3.13.0\n * @category conversions\n */\nexport const formatIso = (self: DurationInput): Option.Option<string> => {\n  const duration = decode(self)\n  return isFinite(duration) ? Option.some(unsafeFormatIso(duration)) : Option.none()\n}\n\n/**\n * Parses an ISO8601 duration string into a `Duration`.\n *\n * Months are assumed to be 30 days and years are assumed to be 365 days.\n *\n * @example\n * ```ts\n * import { Duration, Option } from \"effect\"\n *\n * Duration.fromIso(\"P1D\") // => Option.some(Duration.days(1))\n * Duration.fromIso(\"PT1H\") // => Option.some(Duration.hours(1))\n * Duration.fromIso(\"PT1M\") // => Option.some(Duration.minutes(1))\n * Duration.fromIso(\"PT1.5S\") // => Option.some(Duration.seconds(1.5))\n * ```\n *\n * @since 3.13.0\n * @category conversions\n */\nexport const fromIso = (iso: string): Option.Option<Duration> => {\n  const result = DURATION_ISO_REGEX.exec(iso)\n  if (result == null) {\n    return Option.none()\n  }\n\n  const [years, months, weeks, days, hours, mins, secs] = result.slice(1, 8).map((_) => _ ? Number(_) : 0)\n  const value = years * 365 * 24 * 60 * 60 +\n    months * 30 * 24 * 60 * 60 +\n    weeks * 7 * 24 * 60 * 60 +\n    days * 24 * 60 * 60 +\n    hours * 60 * 60 +\n    mins * 60 +\n    secs\n\n  return Option.some(seconds(value))\n}\n\nconst DURATION_ISO_REGEX =\n  /^P(?!$)(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)W)?(?:(\\d+)D)?(?:T(?!$)(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/\n"
  },
  {
    "path": "packages/effect/src/Effect.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as RA from \"./Array.js\"\nimport type * as Cause from \"./Cause.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Clock from \"./Clock.js\"\nimport type { ConfigProvider } from \"./ConfigProvider.js\"\nimport type { Console } from \"./Console.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as Deferred from \"./Deferred.js\"\nimport type * as Duration from \"./Duration.js\"\nimport type * as Either from \"./Either.js\"\nimport type { Equivalence } from \"./Equivalence.js\"\nimport type { ExecutionPlan } from \"./ExecutionPlan.js\"\nimport type { ExecutionStrategy } from \"./ExecutionStrategy.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport type * as FiberRef from \"./FiberRef.js\"\nimport type * as FiberRefs from \"./FiberRefs.js\"\nimport type * as FiberRefsPatch from \"./FiberRefsPatch.js\"\nimport type * as FiberStatus from \"./FiberStatus.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport { dual } from \"./Function.js\"\nimport type * as HashMap from \"./HashMap.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport * as internalCause from \"./internal/cause.js\"\nimport * as console_ from \"./internal/console.js\"\nimport { TagProto } from \"./internal/context.js\"\nimport * as effect from \"./internal/core-effect.js\"\nimport * as core from \"./internal/core.js\"\nimport * as defaultServices from \"./internal/defaultServices.js\"\nimport * as circular from \"./internal/effect/circular.js\"\nimport * as internalExecutionPlan from \"./internal/executionPlan.js\"\nimport * as fiberRuntime from \"./internal/fiberRuntime.js\"\nimport * as layer from \"./internal/layer.js\"\nimport * as option_ from \"./internal/option.js\"\nimport * as query from \"./internal/query.js\"\nimport * as runtime_ from \"./internal/runtime.js\"\nimport * as schedule_ from \"./internal/schedule.js\"\nimport * as internalTracer from \"./internal/tracer.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type * as LogLevel from \"./LogLevel.js\"\nimport type * as ManagedRuntime from \"./ManagedRuntime.js\"\nimport type * as Metric from \"./Metric.js\"\nimport type * as MetricLabel from \"./MetricLabel.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport * as Random from \"./Random.js\"\nimport type * as Ref from \"./Ref.js\"\nimport * as Request from \"./Request.js\"\nimport type { RequestBlock } from \"./RequestBlock.js\"\nimport type { RequestResolver } from \"./RequestResolver.js\"\nimport type * as Runtime from \"./Runtime.js\"\nimport type * as RuntimeFlags from \"./RuntimeFlags.js\"\nimport type * as RuntimeFlagsPatch from \"./RuntimeFlagsPatch.js\"\nimport type * as Schedule from \"./Schedule.js\"\nimport * as Scheduler from \"./Scheduler.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Supervisor from \"./Supervisor.js\"\nimport type * as Tracer from \"./Tracer.js\"\nimport type {\n  Concurrency,\n  Contravariant,\n  Covariant,\n  EqualsWith,\n  NoExcessProperties,\n  NoInfer,\n  NotFunction\n} from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\nimport { isGeneratorFunction, type YieldWrap } from \"./Utils.js\"\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport const EffectTypeId: unique symbol = core.EffectTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type EffectTypeId = typeof EffectTypeId\n\n/**\n * The `Effect` interface defines a value that describes a workflow or job,\n * which can succeed or fail.\n *\n * **Details**\n *\n * The `Effect` interface represents a computation that can model a workflow\n * involving various types of operations, such as synchronous, asynchronous,\n * concurrent, and parallel interactions. It operates within a context of type\n * `R`, and the result can either be a success with a value of type `A` or a\n * failure with an error of type `E`. The `Effect` is designed to handle complex\n * interactions with external resources, offering advanced features such as\n * fiber-based concurrency, scheduling, interruption handling, and scalability.\n * This makes it suitable for tasks that require fine-grained control over\n * concurrency and error management.\n *\n * To execute an `Effect` value, you need a `Runtime`, which provides the\n * environment necessary to run and manage the computation.\n *\n * @since 2.0.0\n * @category Models\n */\nexport interface Effect<out A, out E = never, out R = never> extends Effect.Variance<A, E, R>, Pipeable {\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: EffectUnify<this>\n  readonly [Unify.ignoreSymbol]?: EffectUnifyIgnore\n  [Symbol.iterator](): EffectGenerator<Effect<A, E, R>>\n}\n\n/**\n * @since 3.0.0\n * @category Models\n */\nexport interface EffectGenerator<T extends Effect<any, any, any>> {\n  next(...args: ReadonlyArray<any>): IteratorResult<YieldWrap<T>, Effect.Success<T>>\n}\n\n/**\n * @since 2.0.0\n * @category Models\n */\nexport interface EffectUnify<A extends { [Unify.typeSymbol]?: any }>\n  extends Either.EitherUnify<A>, Option.OptionUnify<A>, Context.TagUnify<A>\n{\n  Effect?: () => A[Unify.typeSymbol] extends Effect<infer A0, infer E0, infer R0> | infer _ ? Effect<A0, E0, R0> : never\n}\n\n/**\n * @category Models\n * @since 2.0.0\n */\nexport interface EffectUnifyIgnore {\n  Tag?: true\n  Option?: true\n  Either?: true\n}\n\n/**\n * @category Type lambdas\n * @since 2.0.0\n */\nexport interface EffectTypeLambda extends TypeLambda {\n  readonly type: Effect<this[\"Target\"], this[\"Out1\"], this[\"Out2\"]>\n}\n\n/**\n * @since 2.0.0\n * @category Models\n */\nexport interface Blocked<out A, out E> extends Effect<A, E> {\n  readonly _op: \"Blocked\"\n  readonly effect_instruction_i0: RequestBlock\n  readonly effect_instruction_i1: Effect<A, E>\n}\n\n/**\n * @since 2.0.0\n * @category Models\n */\ndeclare module \"./Context.js\" {\n  interface Tag<Id, Value> extends Effect<Value, never, Id> {\n    [Symbol.iterator](): EffectGenerator<Tag<Id, Value>>\n  }\n  interface Reference<Id, Value> extends Effect<Value> {\n    [Symbol.iterator](): EffectGenerator<Reference<Id, Value>>\n  }\n  interface TagUnifyIgnore {\n    Effect?: true\n    Either?: true\n    Option?: true\n  }\n}\n\n/**\n * @since 2.0.0\n * @category Models\n */\ndeclare module \"./Either.js\" {\n  interface Left<E, A> extends Effect<A, E> {\n    readonly _tag: \"Left\"\n    [Symbol.iterator](): EffectGenerator<Left<E, A>>\n  }\n  interface Right<E, A> extends Effect<A, E> {\n    readonly _tag: \"Right\"\n    [Symbol.iterator](): EffectGenerator<Right<E, A>>\n  }\n  interface EitherUnifyIgnore {\n    Effect?: true\n    Tag?: true\n    Option?: true\n  }\n}\n\n/**\n * @since 2.0.0\n * @category Models\n */\ndeclare module \"./Option.js\" {\n  interface None<A> extends Effect<A, Cause.NoSuchElementException> {\n    readonly _tag: \"None\"\n    [Symbol.iterator](): EffectGenerator<None<A>>\n  }\n  interface Some<A> extends Effect<A, Cause.NoSuchElementException> {\n    readonly _tag: \"Some\"\n    [Symbol.iterator](): EffectGenerator<Some<A>>\n  }\n  interface OptionUnifyIgnore {\n    Effect?: true\n    Tag?: true\n    Either?: true\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Effect {\n  /**\n   * @since 2.0.0\n   * @category Models\n   */\n  export interface Variance<out A, out E, out R> {\n    readonly [EffectTypeId]: VarianceStruct<A, E, R>\n  }\n  /**\n   * @since 2.0.0\n   * @category Models\n   */\n  export interface VarianceStruct<out A, out E, out R> {\n    readonly _V: string\n    readonly _A: Covariant<A>\n    readonly _E: Covariant<E>\n    readonly _R: Covariant<R>\n  }\n  /**\n   * @since 2.0.0\n   * @category Effect Type Extractors\n   */\n  export type Context<T extends Effect<any, any, any>> = [T] extends [Effect<infer _A, infer _E, infer _R>] ? _R : never\n  /**\n   * @since 2.0.0\n   * @category Effect Type Extractors\n   */\n  export type Error<T extends Effect<any, any, any>> = [T] extends [Effect<infer _A, infer _E, infer _R>] ? _E : never\n  /**\n   * @since 2.0.0\n   * @category Effect Type Extractors\n   */\n  export type Success<T extends Effect<any, any, any>> = [T] extends [Effect<infer _A, infer _E, infer _R>] ? _A : never\n  /**\n   * @since 3.15.5\n   * @category Effect Type Extractors\n   */\n  export type AsEffect<T extends Effect<any, any, any>> = Effect<\n    T extends Effect<infer _A, infer _E, infer _R> ? _A : never,\n    T extends Effect<infer _A, infer _E, infer _R> ? _E : never,\n    T extends Effect<infer _A, infer _E, infer _R> ? _R : never\n  > extends infer Q ? Q : never\n}\n\n/**\n * Checks if a given value is an `Effect` value.\n *\n * **When to Use**\n *\n * This function can be useful for checking the type of a value before\n * attempting to operate on it as an `Effect` value. For example, you could use\n * `Effect.isEffect` to check the type of a value before using it as an argument\n * to a function that expects an `Effect` value.\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isEffect: (u: unknown) => u is Effect<unknown, unknown, unknown> = core.isEffect\n\n/**\n * Returns an effect that caches its result for a specified `Duration`,\n * known as \"timeToLive\" (TTL).\n *\n * **Details**\n *\n * This function is used to cache the result of an effect for a specified amount\n * of time. This means that the first time the effect is evaluated, its result\n * is computed and stored.\n *\n * If the effect is evaluated again within the specified `timeToLive`, the\n * cached result will be used, avoiding recomputation.\n *\n * After the specified duration has passed, the cache expires, and the effect\n * will be recomputed upon the next evaluation.\n *\n * **When to Use**\n *\n * Use this function when you have an effect that involves costly operations or\n * computations, and you want to avoid repeating them within a short time frame.\n *\n * It's ideal for scenarios where the result of an effect doesn't change\n * frequently and can be reused for a specified duration.\n *\n * By caching the result, you can improve efficiency and reduce unnecessary\n * computations, especially in performance-critical applications.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * let i = 1\n * const expensiveTask = Effect.promise<string>(() => {\n *   console.log(\"expensive task...\")\n *   return new Promise((resolve) => {\n *     setTimeout(() => {\n *       resolve(`result ${i++}`)\n *     }, 100)\n *   })\n * })\n *\n * const program = Effect.gen(function* () {\n *   const cached = yield* Effect.cachedWithTTL(expensiveTask, \"150 millis\")\n *   yield* cached.pipe(Effect.andThen(Console.log))\n *   yield* cached.pipe(Effect.andThen(Console.log))\n *   yield* Effect.sleep(\"100 millis\")\n *   yield* cached.pipe(Effect.andThen(Console.log))\n * })\n *\n * Effect.runFork(program)\n * // Output:\n * // expensive task...\n * // result 1\n * // result 1\n * // expensive task...\n * // result 2\n * ```\n *\n * @see {@link cached} for a similar function that caches the result\n * indefinitely.\n * @see {@link cachedInvalidateWithTTL} for a similar function that includes an\n * additional effect for manually invalidating the cached value.\n *\n * @since 2.0.0\n * @category Caching\n */\nexport const cachedWithTTL: {\n  (timeToLive: Duration.DurationInput): <A, E, R>(self: Effect<A, E, R>) => Effect<Effect<A, E>, never, R>\n  <A, E, R>(self: Effect<A, E, R>, timeToLive: Duration.DurationInput): Effect<Effect<A, E>, never, R>\n} = circular.cached\n\n/**\n * Caches an effect's result for a specified duration and allows manual\n * invalidation before expiration.\n *\n * **Details**\n *\n * This function behaves similarly to {@link cachedWithTTL} by caching the\n * result of an effect for a specified period of time. However, it introduces an\n * additional feature: it provides an effect that allows you to manually\n * invalidate the cached result before it naturally expires.\n *\n * This gives you more control over the cache, allowing you to refresh the\n * result when needed, even if the original cache has not yet expired.\n *\n * Once the cache is invalidated, the next time the effect is evaluated, the\n * result will be recomputed, and the cache will be refreshed.\n *\n * **When to Use**\n *\n * Use this function when you have an effect whose result needs to be cached for\n * a certain period, but you also want the option to refresh the cache manually\n * before the expiration time.\n *\n * This is useful when you need to ensure that the cached data remains valid for\n * a certain period but still want to invalidate it if the underlying data\n * changes or if you want to force a recomputation.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * let i = 1\n * const expensiveTask = Effect.promise<string>(() => {\n *   console.log(\"expensive task...\")\n *   return new Promise((resolve) => {\n *     setTimeout(() => {\n *       resolve(`result ${i++}`)\n *     }, 100)\n *   })\n * })\n *\n * const program = Effect.gen(function* () {\n *   const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL(\n *     expensiveTask,\n *     \"1 hour\"\n *   )\n *   yield* cached.pipe(Effect.andThen(Console.log))\n *   yield* cached.pipe(Effect.andThen(Console.log))\n *   yield* invalidate\n *   yield* cached.pipe(Effect.andThen(Console.log))\n * })\n *\n * Effect.runFork(program)\n * // Output:\n * // expensive task...\n * // result 1\n * // result 1\n * // expensive task...\n * // result 2\n * ```\n *\n * @see {@link cached} for a similar function that caches the result\n * indefinitely.\n * @see {@link cachedWithTTL} for a similar function that caches the result for\n * a specified duration but does not include an effect for manual invalidation.\n *\n * @since 2.0.0\n * @category Caching\n */\nexport const cachedInvalidateWithTTL: {\n  (timeToLive: Duration.DurationInput): <A, E, R>(\n    self: Effect<A, E, R>\n  ) => Effect<[Effect<A, E>, Effect<void>], never, R>\n  <A, E, R>(\n    self: Effect<A, E, R>,\n    timeToLive: Duration.DurationInput\n  ): Effect<[Effect<A, E>, Effect<void>], never, R>\n} = circular.cachedInvalidateWithTTL\n\n/**\n * Returns an effect that lazily computes a result and caches it for subsequent\n * evaluations.\n *\n * **Details**\n *\n * This function wraps an effect and ensures that its result is computed only\n * once. Once the result is computed, it is cached, meaning that subsequent\n * evaluations of the same effect will return the cached result without\n * re-executing the logic.\n *\n * **When to Use**\n *\n * Use this function when you have an expensive or time-consuming operation that\n * you want to avoid repeating. The first evaluation will compute the result,\n * and all following evaluations will immediately return the cached value,\n * improving performance and reducing unnecessary work.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * let i = 1\n * const expensiveTask = Effect.promise<string>(() => {\n *   console.log(\"expensive task...\")\n *   return new Promise((resolve) => {\n *     setTimeout(() => {\n *       resolve(`result ${i++}`)\n *     }, 100)\n *   })\n * })\n *\n * const program = Effect.gen(function* () {\n *   console.log(\"non-cached version:\")\n *   yield* expensiveTask.pipe(Effect.andThen(Console.log))\n *   yield* expensiveTask.pipe(Effect.andThen(Console.log))\n *   console.log(\"cached version:\")\n *   const cached = yield* Effect.cached(expensiveTask)\n *   yield* cached.pipe(Effect.andThen(Console.log))\n *   yield* cached.pipe(Effect.andThen(Console.log))\n * })\n *\n * Effect.runFork(program)\n * // Output:\n * // non-cached version:\n * // expensive task...\n * // result 1\n * // expensive task...\n * // result 2\n * // cached version:\n * // expensive task...\n * // result 3\n * // result 3\n * ```\n *\n * @see {@link cachedWithTTL} for a similar function that includes a\n * time-to-live duration for the cached value.\n * @see {@link cachedInvalidateWithTTL} for a similar function that includes an\n * additional effect for manually invalidating the cached value.\n *\n * @since 2.0.0\n * @category Caching\n */\nexport const cached: <A, E, R>(self: Effect<A, E, R>) => Effect<Effect<A, E, R>> = effect.memoize\n\n/**\n * Returns a memoized version of a function with effects, reusing results for\n * the same inputs.\n *\n * **Details**\n *\n * This function creates a memoized version of a given function that performs an\n * effect. Memoization ensures that once a result is computed for a specific\n * input, it is stored and reused for subsequent calls with the same input,\n * reducing the need to recompute the result.\n *\n * The function can optionally take an `Equivalence` parameter to\n * determine how inputs are compared for caching purposes.\n *\n * **When to Use**\n *\n * Use this function when you have a function that performs an effect and you\n * want to avoid recomputing the result for the same input multiple times.\n *\n * It's ideal for functions that produce deterministic results based on their\n * inputs, and you want to improve performance by caching the output.\n *\n * This is particularly useful in scenarios where the function involves\n * expensive calculations or operations that should be avoided after the first\n * execution with the same parameters.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Random } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   const randomNumber = (n: number) => Random.nextIntBetween(1, n)\n *   console.log(\"non-memoized version:\")\n *   console.log(yield* randomNumber(10))\n *   console.log(yield* randomNumber(10))\n *\n *   console.log(\"memoized version:\")\n *   const memoized = yield* Effect.cachedFunction(randomNumber)\n *   console.log(yield* memoized(10))\n *   console.log(yield* memoized(10))\n * })\n *\n * Effect.runFork(program)\n * // Example Output:\n * // non-memoized version:\n * // 2\n * // 8\n * // memoized version:\n * // 5\n * // 5\n * ```\n *\n * @since 2.0.0\n * @category Caching\n */\nexport const cachedFunction: <A, B, E, R>(\n  f: (a: A) => Effect<B, E, R>,\n  eq?: Equivalence<A>\n) => Effect<(a: A) => Effect<B, E, R>> = circular.cachedFunction\n\n/**\n * Returns an effect that executes only once, regardless of how many times it's\n * called.\n *\n * **Details**\n *\n * This function ensures that a specific effect is executed only a single time,\n * no matter how many times it is invoked. The result of the effect will be\n * cached, and subsequent calls to the effect will immediately return the cached\n * result without re-executing the original logic.\n *\n * **When to Use**\n *\n * Use this function when you need to perform a task only once, regardless of\n * how many times the effect is triggered. It's particularly useful when you\n * have initialization tasks, logging, or other one-time actions that should not\n * be repeated. This can help optimize performance and avoid redundant actions.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   const task1 = Console.log(\"task1\")\n *   yield* Effect.repeatN(task1, 2)\n *   const task2 = yield* Effect.once(Console.log(\"task2\"))\n *   yield* Effect.repeatN(task2, 2)\n * })\n *\n * Effect.runFork(program)\n * // Output:\n * // task1\n * // task1\n * // task1\n * // task2\n * ```\n *\n * @since 2.0.0\n * @category Caching\n */\nexport const once: <A, E, R>(self: Effect<A, E, R>) => Effect<Effect<void, E, R>> = effect.once\n\n/**\n * Combines multiple effects into one, returning results based on the input\n * structure.\n *\n * **Details**\n *\n * Use this function when you need to run multiple effects and combine their\n * results into a single output. It supports tuples, iterables, structs, and\n * records, making it flexible for different input types.\n *\n * For instance, if the input is a tuple:\n *\n * ```ts skip-type-checking\n * //         ┌─── a tuple of effects\n * //         ▼\n * Effect.all([effect1, effect2, ...])\n * ```\n *\n * the effects are executed sequentially, and the result is a new effect\n * containing the results as a tuple. The results in the tuple match the order\n * of the effects passed to `Effect.all`.\n *\n * **Concurrency**\n *\n * You can control the execution order (e.g., sequential vs. concurrent) using\n * the `concurrency` option.\n *\n * **Short-Circuiting Behavior**\n *\n * This function stops execution on the first error it encounters, this is\n * called \"short-circuiting\". If any effect in the collection fails, the\n * remaining effects will not run, and the error will be propagated. To change\n * this behavior, you can use the `mode` option, which allows all effects to run\n * and collect results as `Either` or `Option`.\n *\n * **The `mode` option**\n *\n * The `{ mode: \"either\" }` option changes the behavior of `Effect.all` to\n * ensure all effects run, even if some fail. Instead of stopping on the first\n * failure, this mode collects both successes and failures, returning an array\n * of `Either` instances where each result is either a `Right` (success) or a\n * `Left` (failure).\n *\n * Similarly, the `{ mode: \"validate\" }` option uses `Option` to indicate\n * success or failure. Each effect returns `None` for success and `Some` with\n * the error for failure.\n *\n * **Example** (Combining Effects in Tuples)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const tupleOfEffects = [\n *   Effect.succeed(42).pipe(Effect.tap(Console.log)),\n *   Effect.succeed(\"Hello\").pipe(Effect.tap(Console.log))\n * ] as const\n *\n * //      ┌─── Effect<[number, string], never, never>\n * //      ▼\n * const resultsAsTuple = Effect.all(tupleOfEffects)\n *\n * Effect.runPromise(resultsAsTuple).then(console.log)\n * // Output:\n * // 42\n * // Hello\n * // [ 42, 'Hello' ]\n * ```\n *\n * **Example** (Combining Effects in Iterables)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const iterableOfEffects: Iterable<Effect.Effect<number>> = [1, 2, 3].map(\n *   (n) => Effect.succeed(n).pipe(Effect.tap(Console.log))\n * )\n *\n * //      ┌─── Effect<number[], never, never>\n * //      ▼\n * const resultsAsArray = Effect.all(iterableOfEffects)\n *\n * Effect.runPromise(resultsAsArray).then(console.log)\n * // Output:\n * // 1\n * // 2\n * // 3\n * // [ 1, 2, 3 ]\n * ```\n *\n * **Example** (Combining Effects in Structs)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const structOfEffects = {\n *   a: Effect.succeed(42).pipe(Effect.tap(Console.log)),\n *   b: Effect.succeed(\"Hello\").pipe(Effect.tap(Console.log))\n * }\n *\n * //      ┌─── Effect<{ a: number; b: string; }, never, never>\n * //      ▼\n * const resultsAsStruct = Effect.all(structOfEffects)\n *\n * Effect.runPromise(resultsAsStruct).then(console.log)\n * // Output:\n * // 42\n * // Hello\n * // { a: 42, b: 'Hello' }\n * ```\n *\n * **Example** (Combining Effects in Records)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const recordOfEffects: Record<string, Effect.Effect<number>> = {\n *   key1: Effect.succeed(1).pipe(Effect.tap(Console.log)),\n *   key2: Effect.succeed(2).pipe(Effect.tap(Console.log))\n * }\n *\n * //      ┌─── Effect<{ [x: string]: number; }, never, never>\n * //      ▼\n * const resultsAsRecord = Effect.all(recordOfEffects)\n *\n * Effect.runPromise(resultsAsRecord).then(console.log)\n * // Output:\n * // 1\n * // 2\n * // { key1: 1, key2: 2 }\n * ```\n *\n * **Example** (Short-Circuiting Behavior)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const program = Effect.all([\n *   Effect.succeed(\"Task1\").pipe(Effect.tap(Console.log)),\n *   Effect.fail(\"Task2: Oh no!\").pipe(Effect.tap(Console.log)),\n *   // Won't execute due to earlier failure\n *   Effect.succeed(\"Task3\").pipe(Effect.tap(Console.log))\n * ])\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // Task1\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: { _id: 'Cause', _tag: 'Fail', failure: 'Task2: Oh no!' }\n * // }\n * ```\n *\n * **Example** (Collecting Results with `mode: \"either\"`)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const effects = [\n *   Effect.succeed(\"Task1\").pipe(Effect.tap(Console.log)),\n *   Effect.fail(\"Task2: Oh no!\").pipe(Effect.tap(Console.log)),\n *   Effect.succeed(\"Task3\").pipe(Effect.tap(Console.log))\n * ]\n *\n * const program = Effect.all(effects, { mode: \"either\" })\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // Task1\n * // Task3\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Success',\n * //   value: [\n * //     { _id: 'Either', _tag: 'Right', right: 'Task1' },\n * //     { _id: 'Either', _tag: 'Left', left: 'Task2: Oh no!' },\n * //     { _id: 'Either', _tag: 'Right', right: 'Task3' }\n * //   ]\n * // }\n * ```\n *\n * **Example** (Collecting Results with `mode: \"validate\"`)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const effects = [\n *   Effect.succeed(\"Task1\").pipe(Effect.tap(Console.log)),\n *   Effect.fail(\"Task2: Oh no!\").pipe(Effect.tap(Console.log)),\n *   Effect.succeed(\"Task3\").pipe(Effect.tap(Console.log))\n * ]\n *\n * const program = Effect.all(effects, { mode: \"validate\" })\n *\n * Effect.runPromiseExit(program).then((result) => console.log(\"%o\", result))\n * // Output:\n * // Task1\n * // Task3\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Fail',\n * //     failure: [\n * //       { _id: 'Option', _tag: 'None' },\n * //       { _id: 'Option', _tag: 'Some', value: 'Task2: Oh no!' },\n * //       { _id: 'Option', _tag: 'None' }\n * //     ]\n * //   }\n * // }\n * ```\n *\n * @see {@link forEach} for iterating over elements and applying an effect.\n * @see {@link allWith} for a data-last version of this function.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const all: <\n  const Arg extends Iterable<Effect<any, any, any>> | Record<string, Effect<any, any, any>>,\n  O extends NoExcessProperties<{\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly discard?: boolean | undefined\n    readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }, O>\n>(arg: Arg, options?: O) => All.Return<Arg, O> = fiberRuntime.all\n\n/**\n * A data-last version of {@link all}, designed for use in pipelines.\n *\n * **When to Use**\n *\n * This function enables you to combine multiple effects and customize execution\n * options such as concurrency levels. This version is useful in functional\n * pipelines where you first define your data and then apply operations to it.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, pipe } from \"effect\"\n *\n * const task1 = Effect.succeed(1).pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Effect.log(\"task1 done\"))\n * )\n *\n * const task2 = Effect.succeed(\"hello\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Effect.log(\"task2 done\"))\n * )\n *\n * const program = pipe(\n *   [task1, task2],\n *   // Run both effects concurrently using the concurrent option\n *   Effect.allWith({ concurrency: 2 })\n * )\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // timestamp=... level=INFO fiber=#3 message=\"task2 done\"\n * // timestamp=... level=INFO fiber=#2 message=\"task1 done\"\n * // [ 1, 'hello' ]\n * ```\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const allWith: <\n  O extends NoExcessProperties<{\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly discard?: boolean | undefined\n    readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }, O>\n>(\n  options?: O\n) => <const Arg extends Iterable<Effect<any, any, any>> | Record<string, Effect<any, any, any>>>(\n  arg: Arg\n) => All.Return<Arg, O> = fiberRuntime.allWith\n\n/**\n * @since 2.0.0\n */\nexport declare namespace All {\n  /**\n   * @since 2.0.0\n   */\n  export type EffectAny = Effect<any, any, any>\n\n  /**\n   * @since 2.0.0\n   */\n  export type ReturnIterable<T extends Iterable<EffectAny>, Discard extends boolean, Mode> = [T] extends\n    [Iterable<Effect.Variance<infer R0, infer L0, infer R>>] ? Effect<\n      Discard extends true ? void : Mode extends \"either\" ? Array<Either.Either<R0, L0>> : Array<R0>,\n      Mode extends \"either\" ? never\n        : Mode extends \"validate\" ? Array<Option.Option<L0>>\n        : L0,\n      R\n    >\n    : never\n\n  /**\n   * @since 2.0.0\n   */\n  export type ReturnTuple<T extends ReadonlyArray<unknown>, Discard extends boolean, Mode> = Effect<\n    Discard extends true ? void\n      : T[number] extends never ? []\n      : Mode extends \"either\" ? {\n          -readonly [K in keyof T]: [T[K]] extends [Effect.Variance<infer _A, infer _E, infer _R>] ?\n            Either.Either<_A, _E>\n            : never\n        }\n      : { -readonly [K in keyof T]: [T[K]] extends [Effect.Variance<infer _A, infer _E, infer _R>] ? _A : never },\n    Mode extends \"either\" ? never\n      : T[number] extends never ? never\n      : Mode extends \"validate\" ? {\n          -readonly [K in keyof T]: [T[K]] extends [Effect.Variance<infer _A, infer _E, infer _R>] ? Option.Option<_E>\n            : never\n        }\n      : [T[number]] extends [{ [EffectTypeId]: { _E: (_: never) => infer E } }] ? E\n      : never,\n    T[number] extends never ? never\n      : [T[number]] extends [{ [EffectTypeId]: { _R: (_: never) => infer R } }] ? R\n      : never\n  > extends infer X ? X : never\n\n  /**\n   * @since 2.0.0\n   */\n  export type ReturnObject<T, Discard extends boolean, Mode> = [T] extends [{ [K: string]: EffectAny }] ? Effect<\n      Discard extends true ? void\n        : Mode extends \"either\" ? {\n            -readonly [K in keyof T]: [T[K]] extends [Effect.Variance<infer _A, infer _E, infer _R>] ?\n              Either.Either<_A, _E>\n              : never\n          }\n        : { -readonly [K in keyof T]: [T[K]] extends [Effect.Variance<infer _A, infer _E, infer _R>] ? _A : never },\n      Mode extends \"either\" ? never\n        : keyof T extends never ? never\n        : Mode extends \"validate\" ? {\n            -readonly [K in keyof T]: [T[K]] extends [Effect.Variance<infer _A, infer _E, infer _R>] ? Option.Option<_E>\n              : never\n          }\n        : [T[keyof T]] extends [{ [EffectTypeId]: { _E: (_: never) => infer E } }] ? E\n        : never,\n      keyof T extends never ? never\n        : [T[keyof T]] extends [{ [EffectTypeId]: { _R: (_: never) => infer R } }] ? R\n        : never\n    >\n    : never\n\n  /**\n   * @since 2.0.0\n   */\n  export type IsDiscard<A> = [Extract<A, { readonly discard: true }>] extends [never] ? false : true\n\n  /**\n   * @since 2.0.0\n   */\n  export type ExtractMode<A> = [A] extends [{ mode: infer M }] ? M : \"default\"\n\n  /**\n   * @since 2.0.0\n   */\n  export type Return<\n    Arg extends Iterable<EffectAny> | Record<string, EffectAny>,\n    O extends NoExcessProperties<{\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: boolean | undefined\n      readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }, O>\n  > = [Arg] extends [ReadonlyArray<EffectAny>] ? ReturnTuple<Arg, IsDiscard<O>, ExtractMode<O>>\n    : [Arg] extends [Iterable<EffectAny>] ? ReturnIterable<Arg, IsDiscard<O>, ExtractMode<O>>\n    : [Arg] extends [Record<string, EffectAny>] ? ReturnObject<Arg, IsDiscard<O>, ExtractMode<O>>\n    : never\n}\n\n/**\n * Evaluates and runs each effect in the iterable, collecting only the\n * successful results while discarding failures.\n *\n * **Details**\n *\n * This function function processes an iterable of effects and runs each one. If\n * an effect is successful, its result is collected; if it fails, the result is\n * discarded. This ensures that only successful outcomes are kept.\n *\n * **Options**\n *\n * The function also allows you to customize how the effects are handled by\n * specifying options such as concurrency, batching, and how finalizers behave.\n * These options provide flexibility in running the effects concurrently or\n * adjusting other execution details.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const tasks = [\n *   Effect.succeed(1),\n *   Effect.fail(\"Error 1\"),\n *   Effect.succeed(2),\n *   Effect.fail(\"Error 2\")\n * ]\n *\n * const program = Effect.gen(function*() {\n *   const successfulResults = yield* Effect.allSuccesses(tasks)\n *   console.log(successfulResults)\n * })\n *\n * Effect.runFork(program)\n * // Output: [1, 2]\n *\n * ```\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const allSuccesses: <X extends Effect<any, any, any>>(\n  elements: Iterable<X>,\n  options?:\n    | {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n    | undefined\n) => Effect<Array<Effect.Success<X>>, never, Effect.Context<X>> = fiberRuntime.allSuccesses\n\n/**\n * Drops elements until the effectful predicate returns `true`.\n *\n * **Details**\n *\n * This function processes a collection of elements and uses an effectful\n * predicate to determine when to stop dropping elements. It drops elements from\n * the beginning of the collection until the predicate returns `true`.\n *\n * The predicate is a function that takes an element and its index in the\n * collection and returns an effect that evaluates to a boolean.\n *\n * Once the predicate returns `true`, the remaining elements of the collection\n * are returned.\n *\n * **Note**: The first element for which the predicate returns `true` is also\n * dropped.\n *\n * **When to Use**\n *\n * This function allows you to conditionally skip over a part of the collection\n * based on some criteria defined in the predicate.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const predicate = (n: number, i: number) => Effect.succeed(n > 3)\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Effect.dropUntil(numbers, predicate)\n *   console.log(result)\n * })\n *\n * Effect.runFork(program)\n * // Output: [5, 6]\n * ```\n *\n * @see {@link dropWhile} for a similar function that drops elements while the\n * predicate returns `true`.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const dropUntil: {\n  <A, E, R>(\n    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>\n  ): (elements: Iterable<A>) => Effect<Array<A>, E, R>\n  <A, E, R>(elements: Iterable<A>, predicate: (a: A, i: number) => Effect<boolean, E, R>): Effect<Array<A>, E, R>\n} = effect.dropUntil\n\n/**\n * Drops elements as long as the predicate returns `true`.\n *\n * **Details**\n *\n * This function processes a collection of elements and uses a predicate to\n * decide whether to drop an element.\n *\n * The predicate is a function that takes an element and its index, and it\n * returns an effect that evaluates to a boolean.\n *\n * As long as the predicate returns `true`, elements will continue to be dropped\n * from the collection.\n *\n * Once the predicate returns `false`, the remaining elements are kept.\n *\n * **When to Use**\n *\n * This function allows you to discard elements from the start of a collection\n * based on a condition, and only keep the rest when the condition no longer\n * holds.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const predicate = (n: number, i: number) => Effect.succeed(n <= 3)\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Effect.dropWhile(numbers, predicate)\n *   console.log(result)\n * })\n *\n * Effect.runFork(program)\n * // Output: [4, 5, 6]\n * ```\n *\n * @see {@link dropUntil} for a similar function that drops elements until the\n * predicate returns `true`.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const dropWhile: {\n  <A, E, R>(\n    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>\n  ): (elements: Iterable<A>) => Effect<Array<A>, E, R>\n  <A, E, R>(elements: Iterable<A>, predicate: (a: A, i: number) => Effect<boolean, E, R>): Effect<Array<A>, E, R>\n} = effect.dropWhile\n\n/**\n * Takes elements from a collection until the effectful predicate returns\n * `true`.\n *\n * **Details**\n *\n * This function processes a collection of elements and uses an effectful\n * predicate to decide when to stop taking elements. The elements are taken from\n * the beginning of the collection until the predicate returns `true`.\n *\n * The predicate is a function that takes an element and its index in the\n * collection, and returns an effect that resolves to a boolean.\n *\n * Once the predicate returns `true`, the remaining elements of the collection\n * are discarded, and the function stops taking more elements.\n *\n * **Note**: The first element for which the predicate returns `true` is also\n * included in the result.\n *\n * **When to Use**\n *\n * Use this function when you want to conditionally take elements from a\n * collection based on a dynamic condition. For example, you may want to collect\n * numbers from a list until a certain threshold is reached, or gather items\n * until a specific condition is met.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const predicate = (n: number, i: number) => Effect.succeed(n > 3)\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Effect.takeUntil(numbers, predicate)\n *   console.log(result)\n * })\n *\n * Effect.runFork(program)\n * // Output: [ 1, 2, 3, 4 ]\n * ```\n *\n * @see {@link takeWhile} for a similar function that takes elements while the\n * predicate returns `true`.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const takeUntil: {\n  <A, R, E>(\n    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>\n  ): (elements: Iterable<A>) => Effect<Array<A>, E, R>\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>\n  ): Effect<Array<A>, E, R>\n} = effect.takeUntil\n\n/**\n * Takes elements as long as the predicate returns `true`.\n *\n * **Details**\n *\n * This function processes a collection of elements and uses a predicate to\n * decide whether to take an element.\n *\n * The predicate is a function that takes an element and its index, and it\n * returns an effect that evaluates to a boolean.\n *\n * As long as the predicate returns `true`, elements will continue to be taken\n * from the collection.\n *\n * Once the predicate returns `false`, the remaining elements are discarded.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const predicate = (n: number, i: number) => Effect.succeed(n <= 3)\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Effect.takeWhile(numbers, predicate)\n *   console.log(result)\n * })\n *\n * Effect.runFork(program)\n * // Output: [1, 2, 3]\n * ```\n *\n * @see {@link takeUntil} for a similar function that takes elements until the predicate returns `true`.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const takeWhile: {\n  <A, E, R>(\n    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>\n  ): (elements: Iterable<A>) => Effect<Array<A>, E, R>\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>\n  ): Effect<Array<A>, E, R>\n} = effect.takeWhile\n\n/**\n * Determines whether all elements of the iterable satisfy the effectful\n * predicate.\n *\n * **Details**\n *\n * This function checks whether every element in a given collection (an\n * iterable) satisfies a condition defined by an effectful predicate.\n *\n * The predicate is a function that takes an element and its index, and it\n * returns an effect that evaluates to a boolean.\n *\n * The function will process each element and return `true` if all elements\n * satisfy the predicate; otherwise, it returns `false`.\n *\n * **When to Use**\n *\n * This function is useful when you need to verify that all items in a\n * collection meet certain criteria, even when the evaluation of each item\n * involves effects, such as asynchronous checks or complex computations.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const numbers = [2, 4, 6, 8]\n * const predicate = (n: number, i: number) => Effect.succeed(n % 2 === 0)\n *\n * const program = Effect.gen(function*() {\n *   const allEven = yield* Effect.every(numbers, predicate)\n *   console.log(allEven)\n * })\n *\n * Effect.runFork(program)\n * // Output: true\n * ```\n *\n * @see {@link exists} for a similar function that returns a boolean indicating\n * whether **any** element satisfies the predicate.\n *\n * @since 2.0.0\n * @category Condition Checking\n */\nexport const every: {\n  <A, E, R>(predicate: (a: A, i: number) => Effect<boolean, E, R>): (elements: Iterable<A>) => Effect<boolean, E, R>\n  <A, E, R>(elements: Iterable<A>, predicate: (a: A, i: number) => Effect<boolean, E, R>): Effect<boolean, E, R>\n} = effect.every\n\n/**\n * Determines whether any element of the iterable satisfies the effectual\n * predicate.\n *\n * **Details**\n *\n * This function checks whether any element in a given collection (an iterable)\n * satisfies a condition defined by an effectful predicate.\n *\n * The predicate is a function that takes an element and its index, and it\n * returns an effect that evaluates to a boolean.\n *\n * The function will process each element, and if any element satisfies the\n * predicate (returns `true`), the function will immediately return `true`.\n *\n * If none of the elements satisfy the condition, it will return `false`.\n *\n * **When to Use**\n *\n * This function allows you to quickly check for a condition in a collection\n * without having to manually iterate over it.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4]\n * const predicate = (n: number, i: number) => Effect.succeed(n > 2)\n *\n * const program = Effect.gen(function*() {\n *   const hasLargeNumber = yield* Effect.exists(numbers, predicate)\n *   console.log(hasLargeNumber)\n * })\n *\n * Effect.runFork(program)\n * // Output: true\n * ```\n *\n * @see {@link every} for a similar function that checks if **all** elements\n * satisfy the predicate.\n *\n * @since 2.0.0\n * @category Condition Checking\n */\nexport const exists: {\n  <A, E, R>(\n    predicate: (a: A, i: number) => Effect<boolean, E, R>,\n    options?:\n      | {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): (elements: Iterable<A>) => Effect<boolean, E, R>\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: A, i: number) => Effect<boolean, E, R>,\n    options?:\n      | {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): Effect<boolean, E, R>\n} = fiberRuntime.exists\n\n/**\n * Filters an iterable using the specified effectful predicate.\n *\n * **Details**\n *\n * This function filters a collection (an iterable) by applying an effectful\n * predicate.\n *\n * The predicate is a function that takes an element and its index, and it\n * returns an effect that evaluates to a boolean.\n *\n * The function processes each element in the collection and keeps only those\n * that satisfy the condition defined by the predicate.\n *\n * **Options**\n *\n * You can also adjust the behavior with options such as concurrency, batching,\n * or whether to negate the condition.\n *\n * **When to Use**\n *\n * This function allows you to selectively keep or remove elements based on a\n * condition that may involve asynchronous or side-effect-causing operations.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const predicate = (n: number, i: number) => Effect.succeed(n % 2 === 0)\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Effect.filter(numbers, predicate)\n *   console.log(result)\n * })\n *\n * Effect.runFork(program)\n * // Output: [2, 4]\n * ```\n *\n * @since 2.0.0\n * @category Filtering\n */\nexport const filter: {\n  <A, E, R>(\n    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly negate?: boolean | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    } | undefined\n  ): (elements: Iterable<A>) => Effect<Array<A>, E, R>\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly negate?: boolean | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    } | undefined\n  ): Effect<Array<A>, E, R>\n} = fiberRuntime.filter\n\n/**\n * Filters and maps elements sequentially in one operation.\n *\n * This function processes each element one by one. It applies a function that\n * returns an `Option` to each element. If the function returns `Some`, the\n * element is kept; if it returns `None`, the element is removed. The operation\n * is done sequentially for each element.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect, Option } from \"effect\"\n *\n * const task = (n: number) =>\n *   Effect.succeed(n).pipe(\n *     Effect.delay(1000 - (n * 100)),\n *     Effect.tap(Console.log(`task${n} done`))\n *   )\n *\n * const program = Effect.filterMap(\n *   [task(1), task(2), task(3), task(4)],\n *   (n) => n % 2 === 0 ? Option.some(n) : Option.none()\n * )\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // task1 done\n * // task2 done\n * // task3 done\n * // task4 done\n * // [ 2, 4 ]\n * ```\n *\n * @since 2.0.0\n * @category Filtering\n */\nexport const filterMap: {\n  <Eff extends Effect<any, any, any>, B>(\n    pf: (a: Effect.Success<Eff>) => Option.Option<B>\n  ): (elements: Iterable<Eff>) => Effect<Array<B>, Effect.Error<Eff>, Effect.Context<Eff>>\n  <Eff extends Effect<any, any, any>, B>(\n    elements: Iterable<Eff>,\n    pf: (a: Effect.Success<Eff>) => Option.Option<B>\n  ): Effect<Array<B>, Effect.Error<Eff>, Effect.Context<Eff>>\n} = effect.filterMap\n\n/**\n * Returns the first element that satisfies the effectful predicate.\n *\n * **Details**\n *\n * This function processes a collection of elements and applies an effectful\n * predicate to each element.\n *\n * The predicate is a function that takes an element and its index in the\n * collection, and it returns an effect that evaluates to a boolean.\n *\n * The function stops as soon as it finds the first element for which the\n * predicate returns `true` and returns that element wrapped in an `Option`.\n *\n * If no element satisfies the predicate, the result will be `None`.\n *\n * **When to Use**\n *\n * This function allows you to efficiently find an element that meets a specific\n * condition, even when the evaluation involves effects like asynchronous\n * operations or side effects.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const predicate = (n: number, i: number) => Effect.succeed(n > 3)\n *\n * const program = Effect.gen(function*() {\n *   const result = yield* Effect.findFirst(numbers, predicate)\n *   console.log(result)\n * })\n *\n * Effect.runFork(program)\n * // Output: { _id: 'Option', _tag: 'Some', value: 4 }\n * ```\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const findFirst: {\n  <A, E, R>(\n    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>\n  ): (elements: Iterable<A>) => Effect<Option.Option<A>, E, R>\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>\n  ): Effect<Option.Option<A>, E, R>\n} = effect.findFirst\n\n/**\n * Executes an effectful operation for each element in an `Iterable`.\n *\n * **Details**\n *\n * This function applies a provided operation to each element in the iterable,\n * producing a new effect that returns an array of results.\n *\n * If any effect fails, the iteration stops immediately (short-circuiting), and\n * the error is propagated.\n *\n * **Concurrency**\n *\n * The `concurrency` option controls how many operations are performed\n * concurrently. By default, the operations are performed sequentially.\n *\n * **Discarding Results**\n *\n * If the `discard` option is set to `true`, the intermediate results are not\n * collected, and the final result of the operation is `void`.\n *\n * **Example** (Applying Effects to Iterable Elements)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const result = Effect.forEach([1, 2, 3, 4, 5], (n, index) =>\n *   Console.log(`Currently at index ${index}`).pipe(Effect.as(n * 2))\n * )\n *\n * Effect.runPromise(result).then(console.log)\n * // Output:\n * // Currently at index 0\n * // Currently at index 1\n * // Currently at index 2\n * // Currently at index 3\n * // Currently at index 4\n * // [ 2, 4, 6, 8, 10 ]\n * ```\n *\n * **Example** (Discarding Results)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * // Apply effects but discard the results\n * const result = Effect.forEach(\n *   [1, 2, 3, 4, 5],\n *   (n, index) =>\n *     Console.log(`Currently at index ${index}`).pipe(Effect.as(n * 2)),\n *   { discard: true }\n * )\n *\n * Effect.runPromise(result).then(console.log)\n * // Output:\n * // Currently at index 0\n * // Currently at index 1\n * // Currently at index 2\n * // Currently at index 3\n * // Currently at index 4\n * // undefined\n * ```\n *\n * @see {@link all} for combining multiple effects into one.\n *\n * @since 2.0.0\n * @category Looping\n */\nexport const forEach: {\n  <B, E, R, S extends Iterable<any>>(\n    f: (a: RA.ReadonlyArray.Infer<S>, i: number) => Effect<B, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    } | undefined\n  ): (\n    self: S\n  ) => Effect<RA.ReadonlyArray.With<S, B>, E, R>\n  <A, B, E, R>(\n    f: (a: A, i: number) => Effect<B, E, R>,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard: true\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): (self: Iterable<A>) => Effect<void, E, R>\n  <B, E, R, S extends Iterable<any>>(\n    self: S,\n    f: (a: RA.ReadonlyArray.Infer<S>, i: number) => Effect<B, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    } | undefined\n  ): Effect<RA.ReadonlyArray.With<S, B>, E, R>\n  <A, B, E, R>(\n    self: Iterable<A>,\n    f: (a: A, i: number) => Effect<B, E, R>,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard: true\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect<void, E, R>\n} = fiberRuntime.forEach\n\n/**\n * Returns the first element of the iterable if the collection is non-empty, or\n * fails with the error `NoSuchElementException` if the collection is empty.\n *\n * **When to Use**\n *\n * This function is useful when you need to retrieve the first item from a\n * collection and want to handle the case where the collection might be empty\n * without causing an unhandled exception.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * // Simulate an async operation\n * const fetchNumbers = Effect.succeed([1, 2, 3]).pipe(Effect.delay(\"100 millis\"))\n *\n * const program = Effect.gen(function*() {\n *   const firstElement = yield* Effect.head(fetchNumbers)\n *   console.log(firstElement)\n * })\n *\n * Effect.runFork(program)\n * // Output: 1\n * ```\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const head: <A, E, R>(self: Effect<Iterable<A>, E, R>) => Effect<A, Cause.NoSuchElementException | E, R> =\n  effect.head\n\n/**\n * Merges an `Iterable<Effect<A, E, R>>` to a single effect.\n *\n * **Details**\n *\n * This function takes an iterable of effects and combines them into a single\n * effect. It does this by iterating over each effect in the collection and\n * applying a function that accumulates results into a \"zero\" value, which\n * starts with an initial value and is updated with each effect's success.\n *\n * The provided function `f` is called for each element in the iterable,\n * allowing you to specify how to combine the results.\n *\n * **Options**\n *\n * The function also allows you to customize how the effects are handled by\n * specifying options such as concurrency, batching, and how finalizers behave.\n * These options provide flexibility in running the effects concurrently or\n * adjusting other execution details.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const numbers = [Effect.succeed(1), Effect.succeed(2), Effect.succeed(3)]\n * const add = (sum: number, value: number, i: number) => sum + value\n * const zero = 0\n *\n * const program = Effect.gen(function*() {\n *   const total = yield* Effect.mergeAll(numbers, zero, add)\n *   console.log(total)\n * })\n *\n * Effect.runFork(program)\n * // Output: 6\n * ```\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const mergeAll: {\n  <Z, Eff extends Effect<any, any, any>>(\n    zero: Z,\n    f: (z: Z, a: Effect.Success<Eff>, i: number) => Z,\n    options?:\n      | {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): (elements: Iterable<Eff>) => Effect<Z, Effect.Error<Eff>, Effect.Context<Eff>>\n  <Eff extends Effect<any, any, any>, Z>(\n    elements: Iterable<Eff>,\n    zero: Z,\n    f: (z: Z, a: Effect.Success<Eff>, i: number) => Z,\n    options?:\n      | {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): Effect<Z, Effect.Error<Eff>, Effect.Context<Eff>>\n} = fiberRuntime.mergeAll\n\n/**\n * Processes an iterable and applies an effectful function to each element,\n * categorizing the results into successes and failures.\n *\n * **Details**\n *\n * This function processes each element in the provided iterable by applying an\n * effectful function to it. The results are then categorized into two separate\n * lists: one for failures and another for successes. This separation allows you\n * to handle the two categories differently. Failures are collected in a list\n * without interrupting the processing of the remaining elements, so the\n * operation continues even if some elements fail. This is particularly useful\n * when you need to handle both successful and failed results separately,\n * without stopping the entire process on encountering a failure.\n *\n * **When to Use**\n *\n * Use this function when you want to process a collection of items and handle\n * errors or failures without interrupting the processing of other items. It's\n * useful when you need to distinguish between successful and failed results and\n * process them separately, for example, when logging errors while continuing to\n * work with valid data. The function ensures that failures are captured, while\n * successes are processed normally.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * //      ┌─── Effect<[string[], number[]], never, never>\n * //      ▼\n * const program = Effect.partition([0, 1, 2, 3, 4], (n) => {\n *   if (n % 2 === 0) {\n *     return Effect.succeed(n)\n *   } else {\n *     return Effect.fail(`${n} is not even`)\n *   }\n * })\n *\n * Effect.runPromise(program).then(console.log, console.error)\n * // Output:\n * // [ [ '1 is not even', '3 is not even' ], [ 0, 2, 4 ] ]\n * ```\n *\n * @see {@link validateAll} for a function that either collects all failures or all successes.\n * @see {@link validateFirst} for a function that stops at the first success.\n *\n * @since 2.0.0\n * @category Error Accumulation\n */\nexport const partition: {\n  <A, B, E, R>(\n    f: (a: A, i: number) => Effect<B, E, R>,\n    options?:\n      | {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): (elements: Iterable<A>) => Effect<[excluded: Array<E>, satisfying: Array<B>], never, R>\n  <A, B, E, R>(\n    elements: Iterable<A>,\n    f: (a: A, i: number) => Effect<B, E, R>,\n    options?:\n      | {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): Effect<[excluded: Array<E>, satisfying: Array<B>], never, R>\n} = fiberRuntime.partition\n\n/**\n * Reduces an `Iterable<A>` using an effectual function `f`, working\n * sequentially from left to right.\n *\n * **Details**\n *\n * This function takes an iterable and applies a function `f` to each element in\n * the iterable. The function works sequentially, starting with an initial value\n * `zero` and then combining it with each element in the collection. The\n * provided function `f` is called for each element in the iterable, allowing\n * you to accumulate a result based on the current value and the element being\n * processed.\n *\n * **When to Use**\n *\n * The function is often used for operations like summing a collection of\n * numbers or combining results from multiple tasks. It ensures that operations\n * are performed one after the other, maintaining the order of the elements.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const processOrder = (id: number) =>\n *   Effect.succeed({ id, price: 100 * id })\n *     .pipe(Effect.tap(() => Console.log(`Order ${id} processed`)), Effect.delay(500 - (id * 100)))\n *\n * const program = Effect.reduce(\n *   [1, 2, 3, 4],\n *   0,\n *   (acc, id, i) =>\n *     processOrder(id)\n *       .pipe(Effect.map((order) => acc + order.price))\n * )\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // Order 1 processed\n * // Order 2 processed\n * // Order 3 processed\n * // Order 4 processed\n * // 1000\n * ```\n *\n * @see {@link reduceWhile} for a similar function that stops the process based on a predicate.\n * @see {@link reduceRight} for a similar function that works from right to left.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const reduce: {\n  <Z, A, E, R>(zero: Z, f: (z: Z, a: A, i: number) => Effect<Z, E, R>): (elements: Iterable<A>) => Effect<Z, E, R>\n  <A, Z, E, R>(elements: Iterable<A>, zero: Z, f: (z: Z, a: A, i: number) => Effect<Z, E, R>): Effect<Z, E, R>\n} = effect.reduce\n\n/**\n * Reduces an `Iterable<A>` using an effectual function `body`, working\n * sequentially from left to right, stopping the process early when the\n * predicate `while` is not satisfied.\n *\n * **Details**\n *\n * This function processes a collection of elements, applying a function `body`\n * to reduce them to a single value, starting from the first element. It checks\n * the value of the accumulator against a predicate (`while`). If at any point\n * the predicate returns `false`, the reduction stops, and the accumulated\n * result is returned.\n *\n * **When to Use**\n *\n * Use this function when you need to reduce a collection of elements, but only\n * continue the process as long as a certain condition holds true. For example,\n * if you want to sum values in a list but stop as soon as the sum exceeds a\n * certain threshold, you can use this function.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const processOrder = (id: number) =>\n *   Effect.succeed({ id, price: 100 * id })\n *     .pipe(Effect.tap(() => Console.log(`Order ${id} processed`)), Effect.delay(500 - (id * 100)))\n *\n * const program = Effect.reduceWhile(\n *   [1, 2, 3, 4],\n *   0,\n *   {\n *     body: (acc, id, i) =>\n *       processOrder(id)\n *         .pipe(Effect.map((order) => acc + order.price)),\n *     while: (acc) => acc < 500\n *   }\n * )\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // Order 1 processed\n * // Order 2 processed\n * // Order 3 processed\n * // 600\n * ```\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const reduceWhile: {\n  <Z, A, E, R>(\n    zero: Z,\n    options: { readonly while: Predicate<Z>; readonly body: (s: Z, a: A, i: number) => Effect<Z, E, R> }\n  ): (elements: Iterable<A>) => Effect<Z, E, R>\n  <A, Z, E, R>(\n    elements: Iterable<A>,\n    zero: Z,\n    options: { readonly while: Predicate<Z>; readonly body: (s: Z, a: A, i: number) => Effect<Z, E, R> }\n  ): Effect<Z, E, R>\n} = effect.reduceWhile\n\n/**\n * Reduces an `Iterable<A>` using an effectual function `f`, working\n * sequentially from right to left.\n *\n * **Details**\n *\n * This function takes an iterable and applies a function `f` to each element in\n * the iterable. The function works sequentially, starting with an initial value\n * `zero` and then combining it with each element in the collection. The\n * provided function `f` is called for each element in the iterable, allowing\n * you to accumulate a result based on the current value and the element being\n * processed.\n *\n * **When to Use**\n *\n * The function is often used for operations like summing a collection of\n * numbers or combining results from multiple tasks. It ensures that operations\n * are performed one after the other, maintaining the order of the elements.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const processOrder = (id: number) =>\n *   Effect.succeed({ id, price: 100 * id })\n *     .pipe(Effect.tap(() => Console.log(`Order ${id} processed`)), Effect.delay(500 - (id * 100)))\n *\n * const program = Effect.reduceRight(\n *   [1, 2, 3, 4],\n *   0,\n *   (id, acc, i) =>\n *     processOrder(id)\n *       .pipe(Effect.map((order) => acc + order.price))\n * )\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // Order 4 processed\n * // Order 3 processed\n * // Order 2 processed\n * // Order 1 processed\n * // 1000\n * ```\n *\n * @see {@link reduce} for a similar function that works from left to right.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const reduceRight: {\n  <A, Z, R, E>(zero: Z, f: (a: A, z: Z, i: number) => Effect<Z, E, R>): (elements: Iterable<A>) => Effect<Z, E, R>\n  <A, Z, R, E>(elements: Iterable<A>, zero: Z, f: (a: A, z: Z, i: number) => Effect<Z, E, R>): Effect<Z, E, R>\n} = effect.reduceRight\n\n/**\n * Reduces an `Iterable<Effect<A, E, R>>` to a single effect.\n *\n * **Details**\n *\n * This function processes a collection of effects and combines them into one\n * single effect. It starts with an initial effect (`zero`) and applies a\n * function `f` to each element in the collection.\n *\n * **Options**\n *\n * The function also allows you to customize how the effects are handled by\n * specifying options such as concurrency, batching, and how finalizers behave.\n * These options provide flexibility in running the effects concurrently or\n * adjusting other execution details.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const processOrder = (id: number) =>\n *   Effect.succeed({ id, price: 100 * id })\n *     .pipe(Effect.tap(() => Console.log(`Order ${id} processed`)), Effect.delay(500 - (id * 100)))\n *\n * const program = Effect.reduceEffect(\n *   [processOrder(1), processOrder(2), processOrder(3), processOrder(4)],\n *   Effect.succeed(0),\n *   (acc, order, i) => acc + order.price\n * )\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // Order 1 processed\n * // Order 2 processed\n * // Order 3 processed\n * // Order 4 processed\n * // 1000\n * ```\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const reduceEffect: {\n  <Z, E, R, Eff extends Effect<any, any, any>>(\n    zero: Effect<Z, E, R>,\n    f: (z: NoInfer<Z>, a: Effect.Success<Eff>, i: number) => Z,\n    options?:\n      | {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): (elements: Iterable<Eff>) => Effect<Z, E | Effect.Error<Eff>, R | Effect.Context<Eff>>\n  <Eff extends Effect<any, any, any>, Z, E, R>(\n    elements: Iterable<Eff>,\n    zero: Effect<Z, E, R>,\n    f: (z: NoInfer<Z>, a: Effect.Success<Eff>, i: number) => Z,\n    options?:\n      | {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): Effect<Z, E | Effect.Error<Eff>, R | Effect.Context<Eff>>\n} = fiberRuntime.reduceEffect\n\n/**\n * Replicates the given effect `n` times.\n *\n * **Details**\n *\n * This function takes an effect and replicates it a specified number of times\n * (`n`). The result is an array of `n` effects, each of which is identical to\n * the original effect.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const task = Effect.succeed(\"Hello, World!\").pipe(\n *   Effect.tap(Console.log)\n * )\n *\n * const program = Effect.gen(function*() {\n *   // Replicate the task 3 times\n *   const tasks = Effect.replicate(task, 3)\n *   for (const t of tasks) {\n *     // Run each task\n *     yield* t\n *   }\n * })\n *\n * Effect.runFork(program)\n * // Output:\n * // Hello, World!\n * // Hello, World!\n * // Hello, World!\n * ```\n *\n * @since 2.0.0\n */\nexport const replicate: {\n  (n: number): <A, E, R>(self: Effect<A, E, R>) => Array<Effect<A, E, R>>\n  <A, E, R>(self: Effect<A, E, R>, n: number): Array<Effect<A, E, R>>\n} = fiberRuntime.replicate\n\n/**\n * Performs this effect the specified number of times and collects the results.\n *\n * **Details**\n *\n * This function repeats an effect multiple times and collects the results into\n * an array. You specify how many times to execute the effect, and it runs that\n * many times, either in sequence or concurrently depending on the provided\n * options.\n *\n * **Options**\n *\n * If the `discard` option is set to `true`, the intermediate results are not\n * collected, and the final result of the operation is `void`.\n *\n * The function also allows you to customize how the effects are handled by\n * specifying options such as concurrency, batching, and how finalizers behave.\n * These options provide flexibility in running the effects concurrently or\n * adjusting other execution details.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * let counter = 0\n *\n * const task = Effect.sync(() => ++counter).pipe(\n *   Effect.tap(() => Console.log(`Task completed`))\n * )\n *\n * const program = Effect.gen(function*() {\n *   // Replicate the task 3 times and collect the results\n *   const results = yield* Effect.replicateEffect(task, 3)\n *   yield* Console.log(`Results: ${results.join(\", \")}`)\n * })\n *\n * Effect.runFork(program)\n * // Output:\n * // Task completed\n * // Task completed\n * // Task completed\n * // Results: 1, 2, 3\n * ```\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const replicateEffect: {\n  (\n    n: number,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<Array<A>, E, R>\n  (\n    n: number,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard: true\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<void, E, R>\n  <A, E, R>(\n    self: Effect<A, E, R>,\n    n: number,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect<Array<A>, E, R>\n  <A, E, R>(\n    self: Effect<A, E, R>,\n    n: number,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard: true\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect<void, E, R>\n} = fiberRuntime.replicateEffect\n\n/**\n * Applies an effectful operation to each element in a collection while\n * collecting both successes and failures.\n *\n * **Details**\n *\n * This function allows you to apply an effectful operation to every item in a\n * collection.\n *\n * Unlike {@link forEach}, which would stop at the first error, this function\n * continues processing all elements, accumulating both successes and failures.\n *\n * **When to Use**\n *\n * Use this function when you want to process every item in a collection, even\n * if some items fail. This is particularly useful when you need to perform\n * operations on all elements without halting due to an error.\n *\n * Keep in mind that if there are any failures, **all successes will be lost**,\n * so this function is not suitable when you need to keep the successful results\n * in case of errors.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * //      ┌─── Effect<number[], [string, ...string[]], never>\n * //      ▼\n * const program = Effect.validateAll([1, 2, 3, 4, 5], (n) => {\n *   if (n < 4) {\n *     return Console.log(`item ${n}`).pipe(Effect.as(n))\n *   } else {\n *     return Effect.fail(`${n} is not less that 4`)\n *   }\n * })\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // item 1\n * // item 2\n * // item 3\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Fail',\n * //     failure: [ '4 is not less that 4', '5 is not less that 4' ]\n * //   }\n * // }\n * ```\n *\n * @see {@link forEach} for a similar function that stops at the first error.\n * @see {@link partition} when you need to separate successes and failures\n * instead of losing successes with errors.\n *\n * @since 2.0.0\n * @category Error Accumulation\n */\nexport const validateAll: {\n  <A, B, E, R>(\n    f: (a: A, i: number) => Effect<B, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    } | undefined\n  ): (elements: Iterable<A>) => Effect<Array<B>, RA.NonEmptyArray<E>, R>\n  <A, B, E, R>(\n    f: (a: A, i: number) => Effect<B, E, R>,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard: true\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): (elements: Iterable<A>) => Effect<void, RA.NonEmptyArray<E>, R>\n  <A, B, E, R>(\n    elements: Iterable<A>,\n    f: (a: A, i: number) => Effect<B, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    } | undefined\n  ): Effect<Array<B>, RA.NonEmptyArray<E>, R>\n  <A, B, E, R>(\n    elements: Iterable<A>,\n    f: (a: A, i: number) => Effect<B, E, R>,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard: true\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect<void, RA.NonEmptyArray<E>, R>\n} = fiberRuntime.validateAll\n\n/**\n * This function is similar to {@link validateAll} but with a key difference: it\n * returns the first successful result or all errors if none of the operations\n * succeed.\n *\n * **Details**\n *\n * This function processes a collection of elements and applies an effectful\n * operation to each. Unlike {@link validateAll}, which accumulates both\n * successes and failures, `Effect.validateFirst` stops and returns the first\n * success it encounters. If no success occurs, it returns all accumulated\n * errors. This can be useful when you are interested in the first successful\n * result and want to avoid processing further once a valid result is found.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * //      ┌─── Effect<number, string[], never>\n * //      ▼\n * const program = Effect.validateFirst([1, 2, 3, 4, 5], (n) => {\n *   if (n < 4) {\n *     return Effect.fail(`${n} is not less that 4`)\n *   } else {\n *     return Console.log(`item ${n}`).pipe(Effect.as(n))\n *   }\n * })\n *\n * Effect.runPromise(program).then(console.log, console.error)\n * // Output:\n * // item 4\n * // 4\n * ```\n *\n * @see {@link validateAll} for a similar function that accumulates all results.\n * @see {@link firstSuccessOf} for a similar function that processes multiple\n * effects and returns the first successful one or the last error.\n *\n * @since 2.0.0\n * @category Error Accumulation\n */\nexport const validateFirst: {\n  <A, B, E, R>(\n    f: (a: A, i: number) => Effect<B, E, R>,\n    options?:\n      | {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): (elements: Iterable<A>) => Effect<B, Array<E>, R>\n  <A, B, E, R>(\n    elements: Iterable<A>,\n    f: (a: A, i: number) => Effect<B, E, R>,\n    options?:\n      | {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): Effect<B, Array<E>, R>\n} = fiberRuntime.validateFirst\n\n/**\n * Creates an `Effect` from a callback-based asynchronous function.\n *\n * **Details**\n *\n * The `resume` function:\n * - Must be called exactly once. Any additional calls will be ignored.\n * - Can return an optional `Effect` that will be run if the `Fiber` executing\n *   this `Effect` is interrupted. This can be useful in scenarios where you\n *   need to handle resource cleanup if the operation is interrupted.\n * - Can receive an `AbortSignal` to handle interruption if needed.\n *\n * The `FiberId` of the fiber that may complete the async callback may also be\n * specified using the `blockingOn` argument. This is called the \"blocking\n * fiber\" because it suspends the fiber executing the `async` effect (i.e.\n * semantically blocks the fiber from making progress). Specifying this fiber id\n * in cases where it is known will improve diagnostics, but not affect the\n * behavior of the returned effect.\n *\n * **When to Use**\n *\n * Use `Effect.async` when dealing with APIs that use callback-style instead of\n * `async/await` or `Promise`.\n *\n * **Example** (Wrapping a Callback API)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import * as NodeFS from \"node:fs\"\n *\n * const readFile = (filename: string) =>\n *   Effect.async<Buffer, Error>((resume) => {\n *     NodeFS.readFile(filename, (error, data) => {\n *       if (error) {\n *         // Resume with a failed Effect if an error occurs\n *         resume(Effect.fail(error))\n *       } else {\n *         // Resume with a succeeded Effect if successful\n *         resume(Effect.succeed(data))\n *       }\n *     })\n *   })\n *\n * //      ┌─── Effect<Buffer, Error, never>\n * //      ▼\n * const program = readFile(\"example.txt\")\n * ```\n *\n * **Example** (Handling Interruption with Cleanup)\n *\n * ```ts\n * import { Effect, Fiber } from \"effect\"\n * import * as NodeFS from \"node:fs\"\n *\n * // Simulates a long-running operation to write to a file\n * const writeFileWithCleanup = (filename: string, data: string) =>\n *   Effect.async<void, Error>((resume) => {\n *     const writeStream = NodeFS.createWriteStream(filename)\n *\n *     // Start writing data to the file\n *     writeStream.write(data)\n *\n *     // When the stream is finished, resume with success\n *     writeStream.on(\"finish\", () => resume(Effect.void))\n *\n *     // In case of an error during writing, resume with failure\n *     writeStream.on(\"error\", (err) => resume(Effect.fail(err)))\n *\n *     // Handle interruption by returning a cleanup effect\n *     return Effect.sync(() => {\n *       console.log(`Cleaning up ${filename}`)\n *       NodeFS.unlinkSync(filename)\n *     })\n *   })\n *\n * const program = Effect.gen(function* () {\n *   const fiber = yield* Effect.fork(\n *     writeFileWithCleanup(\"example.txt\", \"Some long data...\")\n *   )\n *   // Simulate interrupting the fiber after 1 second\n *   yield* Effect.sleep(\"1 second\")\n *   yield* Fiber.interrupt(fiber) // This will trigger the cleanup\n * })\n *\n * // Run the program\n * Effect.runPromise(program)\n * // Output:\n * // Cleaning up example.txt\n * ```\n *\n * **Example** (Handling Interruption with AbortSignal)\n *\n * ```ts\n * import { Effect, Fiber } from \"effect\"\n *\n * // A task that supports interruption using AbortSignal\n * const interruptibleTask = Effect.async<void, Error>((resume, signal) => {\n *   // Handle interruption\n *   signal.addEventListener(\"abort\", () => {\n *     console.log(\"Abort signal received\")\n *     clearTimeout(timeoutId)\n *   })\n *\n *   // Simulate a long-running task\n *   const timeoutId = setTimeout(() => {\n *     console.log(\"Operation completed\")\n *     resume(Effect.void)\n *   }, 2000)\n * })\n *\n * const program = Effect.gen(function* () {\n *   const fiber = yield* Effect.fork(interruptibleTask)\n *   // Simulate interrupting the fiber after 1 second\n *   yield* Effect.sleep(\"1 second\")\n *   yield* Fiber.interrupt(fiber)\n * })\n *\n * // Run the program\n * Effect.runPromise(program)\n * // Output:\n * // Abort signal received\n * ```\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const async: <A, E = never, R = never>(\n  resume: (callback: (_: Effect<A, E, R>) => void, signal: AbortSignal) => void | Effect<void, never, R>,\n  blockingOn?: FiberId.FiberId\n) => Effect<A, E, R> = core.async\n\n/**\n * A variant of {@link async} where the registration function may return an `Effect`.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const asyncEffect: <A, E, R, R3, E2, R2>(\n  register: (callback: (_: Effect<A, E, R>) => void) => Effect<Effect<void, never, R3> | void, E2, R2>\n) => Effect<A, E | E2, R | R2 | R3> = runtime_.asyncEffect\n\n/**\n * Low level constructor that enables for custom stack tracing cutpoints.\n *\n * It is meant to be called with a bag of instructions that become available in\n * the \"this\" of the effect.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const throwingFunction = () => { throw new Error() }\n * const blowUp = Effect.custom(throwingFunction, function() {\n *   return Effect.succeed(this.effect_instruction_i0())\n * })\n * ```\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const custom: {\n  <X, A, E, R>(i0: X, body: (this: { effect_instruction_i0: X }) => Effect<A, E, R>): Effect<A, E, R>\n  <X, Y, A, E, R>(\n    i0: X,\n    i1: Y,\n    body: (this: { effect_instruction_i0: X; effect_instruction_i1: Y }) => Effect<A, E, R>\n  ): Effect<A, E, R>\n  <X, Y, Z, A, E, R>(\n    i0: X,\n    i1: Y,\n    i2: Z,\n    body: (this: { effect_instruction_i0: X; effect_instruction_i1: Y; effect_instruction_i2: Z }) => Effect<A, E, R>\n  ): Effect<A, E, R>\n} = core.custom\n\n/**\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const withFiberRuntime: <A, E = never, R = never>(\n  withRuntime: (\n    fiber: Fiber.RuntimeFiber<A, E>,\n    status: FiberStatus.Running\n  ) => Effect<A, E, R>\n) => Effect<A, E, R> = core.withFiberRuntime\n\n/**\n * Creates an `Effect` that represents a recoverable error.\n *\n * **When to Use**\n *\n * Use this function to explicitly signal an error in an `Effect`. The error\n * will keep propagating unless it is handled. You can handle the error with\n * functions like {@link catchAll} or {@link catchTag}.\n *\n * **Example** (Creating a Failed Effect)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * //      ┌─── Effect<never, Error, never>\n * //      ▼\n * const failure = Effect.fail(\n *   new Error(\"Operation failed due to network error\")\n * )\n * ```\n *\n * @see {@link succeed} to create an effect that represents a successful value.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const fail: <E>(error: E) => Effect<never, E> = core.fail\n\n/**\n * Creates an `Effect` that fails with the specified error, evaluated lazily.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const failSync: <E>(evaluate: LazyArg<E>) => Effect<never, E> = core.failSync\n\n/**\n * Creates an `Effect` that fails with the specified `Cause`.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const failCause: <E>(cause: Cause.Cause<E>) => Effect<never, E> = core.failCause\n\n/**\n * Creates an `Effect` that fails with the specified `Cause`, evaluated lazily.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const failCauseSync: <E>(evaluate: LazyArg<Cause.Cause<E>>) => Effect<never, E> = core.failCauseSync\n\n/**\n * Creates an effect that terminates a fiber with a specified error.\n *\n * **Details**\n *\n * This function is used to signal a defect, which represents a critical and\n * unexpected error in the code. When invoked, it produces an effect that does\n * not handle the error and instead terminates the fiber.\n *\n * The error channel of the resulting effect is of type `never`, indicating that\n * it cannot recover from this failure.\n *\n * **When to Use**\n *\n * Use this function when encountering unexpected conditions in your code that\n * should not be handled as regular errors but instead represent unrecoverable\n * defects.\n *\n * **Example** (Terminating on Division by Zero with a Specified Error)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const divide = (a: number, b: number) =>\n *   b === 0\n *     ? Effect.die(new Error(\"Cannot divide by zero\"))\n *     : Effect.succeed(a / b)\n *\n * //      ┌─── Effect<number, never, never>\n * //      ▼\n * const program = divide(1, 0)\n *\n * Effect.runPromise(program).catch(console.error)\n * // Output:\n * // (FiberFailure) Error: Cannot divide by zero\n * //   ...stack trace...\n * ```\n *\n * @see {@link dieSync} for a variant that throws a specified error, evaluated\n * lazily.\n * @see {@link dieMessage} for a variant that throws a `RuntimeException` with a\n * message.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const die: (defect: unknown) => Effect<never> = core.die\n\n/**\n * Creates an effect that terminates a fiber with a `RuntimeException`\n * containing the specified message.\n *\n * **Details**\n *\n * This function is used to signal a defect, representing a critical and\n * unexpected error in the code. When invoked, it produces an effect that\n * terminates the fiber with a `RuntimeException` carrying the given message.\n *\n * The resulting effect has an error channel of type `never`, indicating it does\n * not handle or recover from the error.\n *\n * **When to Use**\n *\n * Use this function when you want to terminate a fiber due to an unrecoverable\n * defect and include a clear explanation in the message.\n *\n * **Example** (Terminating on Division by Zero with a Specified Message)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const divide = (a: number, b: number) =>\n *   b === 0\n *     ? Effect.dieMessage(\"Cannot divide by zero\")\n *     : Effect.succeed(a / b)\n *\n * //      ┌─── Effect<number, never, never>\n * //      ▼\n * const program = divide(1, 0)\n *\n * Effect.runPromise(program).catch(console.error)\n * // Output:\n * // (FiberFailure) RuntimeException: Cannot divide by zero\n * //   ...stack trace...\n * ```\n *\n * @see {@link die} for a variant that throws a specified error.\n * @see {@link dieSync} for a variant that throws a specified error, evaluated\n * lazily.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const dieMessage: (message: string) => Effect<never> = core.dieMessage\n\n/**\n * Creates an effect that dies with the specified error, evaluated lazily.\n *\n * **Details**\n *\n * This function allows you to create an effect that will terminate with a fatal error.\n * The error is provided as a lazy argument, meaning it will only be evaluated when the effect runs.\n *\n * @see {@link die} if you don't need to evaluate the error lazily.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const dieSync: (evaluate: LazyArg<unknown>) => Effect<never> = core.dieSync\n\n/**\n * Provides a way to write effectful code using generator functions, simplifying\n * control flow and error handling.\n *\n * **When to Use**\n *\n * `Effect.gen` allows you to write code that looks and behaves like synchronous\n * code, but it can handle asynchronous tasks, errors, and complex control flow\n * (like loops and conditions). It helps make asynchronous code more readable\n * and easier to manage.\n *\n * The generator functions work similarly to `async/await` but with more\n * explicit control over the execution of effects. You can `yield*` values from\n * effects and return the final result at the end.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const addServiceCharge = (amount: number) => amount + 1\n *\n * const applyDiscount = (\n *   total: number,\n *   discountRate: number\n * ): Effect.Effect<number, Error> =>\n *   discountRate === 0\n *     ? Effect.fail(new Error(\"Discount rate cannot be zero\"))\n *     : Effect.succeed(total - (total * discountRate) / 100)\n *\n * const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))\n *\n * const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))\n *\n * export const program = Effect.gen(function* () {\n *   const transactionAmount = yield* fetchTransactionAmount\n *   const discountRate = yield* fetchDiscountRate\n *   const discountedAmount = yield* applyDiscount(\n *     transactionAmount,\n *     discountRate\n *   )\n *   const finalAmount = addServiceCharge(discountedAmount)\n *   return `Final amount to charge: ${finalAmount}`\n * })\n * ```\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const gen: {\n  <Eff extends YieldWrap<Effect<any, any, any>>, AEff>(\n    f: (resume: Adapter) => Generator<Eff, AEff, never>\n  ): Effect<\n    AEff,\n    [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n    [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n  >\n  <Self, Eff extends YieldWrap<Effect<any, any, any>>, AEff>(\n    self: Self,\n    f: (this: Self, resume: Adapter) => Generator<Eff, AEff, never>\n  ): Effect<\n    AEff,\n    [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n    [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n  >\n} = core.gen\n\n/**\n * @since 2.0.0\n * @category Models\n */\nexport interface Adapter {\n  <A, E, R>(self: Effect<A, E, R>): Effect<A, E, R>\n  <A, _A, _E, _R>(a: A, ab: (a: A) => Effect<_A, _E, _R>): Effect<_A, _E, _R>\n  <A, B, _A, _E, _R>(a: A, ab: (a: A) => B, bc: (b: B) => Effect<_A, _E, _R>): Effect<_A, _E, _R>\n  <A, B, C, _A, _E, _R>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => Effect<_A, _E, _R>): Effect<_A, _E, _R>\n  <A, B, C, D, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (g: H) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => R,\n    rs: (r: R) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => R,\n    rs: (r: R) => S,\n    st: (s: S) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, _A, _E, _R>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => R,\n    rs: (r: R) => S,\n    st: (s: S) => T,\n    tu: (s: T) => Effect<_A, _E, _R>\n  ): Effect<_A, _E, _R>\n}\n\n/**\n * An effect that that runs indefinitely and never produces any result. The\n * moral equivalent of `while(true) {}`, only without the wasted CPU cycles.\n *\n * **When to Use**\n *\n * It could be useful for long-running background tasks or to simulate waiting\n * behavior without actually consuming resources. This effect is ideal for cases\n * where you want to keep the program alive or in a certain state without\n * performing any active work.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const never: Effect<never> = core.never\n\n/**\n * Ensures the `Option` is `None`, returning `void`. Otherwise, raises a\n * `NoSuchElementException`.\n *\n * **Details**\n *\n * This function checks if the provided `Option` is `None`. If it is, it returns\n * an effect that produces no result (i.e., `void`). If the `Option` is not\n * `None` (i.e., it contains a value), the function will raise a\n * `NoSuchElementException` error.\n *\n * **When to Use**\n *\n * This is useful when you want to ensure that a certain value is absent (i.e.,\n * `None`) before continuing execution, and to handle cases where the value is\n * unexpectedly present.\n *\n * @since 2.0.0\n */\nexport const none: <A, E, R>(\n  self: Effect<Option.Option<A>, E, R>\n) => Effect<void, E | Cause.NoSuchElementException, R> = effect.none\n\n/**\n * Creates an `Effect` that represents an asynchronous computation guaranteed to\n * succeed.\n *\n * **Details**\n *\n * The provided function (`thunk`) returns a `Promise` that should never reject; if it does, the error\n * will be treated as a \"defect\".\n *\n * This defect is not a standard error but indicates a flaw in the logic that\n * was expected to be error-free. You can think of it similar to an unexpected\n * crash in the program, which can be further managed or logged using tools like\n * {@link catchAllDefect}.\n *\n * **Interruptions**\n *\n * An optional `AbortSignal` can be provided to allow for interruption of the\n * wrapped `Promise` API.\n *\n * **When to Use**\n *\n * Use this function when you are sure the operation will not reject.\n *\n * **Example** (Delayed Message)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const delay = (message: string) =>\n *   Effect.promise<string>(\n *     () =>\n *       new Promise((resolve) => {\n *         setTimeout(() => {\n *           resolve(message)\n *         }, 2000)\n *       })\n *   )\n *\n * //      ┌─── Effect<string, never, never>\n * //      ▼\n * const program = delay(\"Async operation completed successfully!\")\n * ```\n *\n * @see {@link tryPromise} for a version that can handle failures.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const promise: <A>(\n  evaluate: (signal: AbortSignal) => PromiseLike<A>\n) => Effect<A> = effect.promise\n\n/**\n * Creates an `Effect` that always succeeds with a given value.\n *\n * **When to Use**\n *\n * Use this function when you need an effect that completes successfully with a\n * specific value without any errors or external dependencies.\n *\n * **Example** (Creating a Successful Effect)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * // Creating an effect that represents a successful scenario\n * //\n * //      ┌─── Effect<number, never, never>\n * //      ▼\n * const success = Effect.succeed(42)\n * ```\n *\n * @see {@link fail} to create an effect that represents a failure.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const succeed: <A>(value: A) => Effect<A> = core.succeed\n\n/**\n * Returns an effect which succeeds with `None`.\n *\n * **When to Use**\n *\n * Use this function when you need to represent the absence of a value in your\n * code, especially when working with optional data. This can be helpful when\n * you want to indicate that no result is available without throwing an error or\n * performing additional logic.\n *\n * @see {@link succeedSome} to create an effect that succeeds with a `Some` value.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const succeedNone: Effect<Option.Option<never>> = effect.succeedNone\n\n/**\n * Returns an effect which succeeds with the value wrapped in a `Some`.\n *\n * @see {@link succeedNone} for a similar function that returns `None` when the value is absent.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const succeedSome: <A>(value: A) => Effect<Option.Option<A>> = effect.succeedSome\n\n/**\n * Delays the creation of an `Effect` until it is actually needed.\n *\n * **Details**\n *\n * The `Effect.suspend` function takes a thunk that represents the effect and\n * wraps it in a suspended effect. This means the effect will not be created\n * until it is explicitly needed, which is helpful in various scenarios:\n * - **Lazy Evaluation**: Helps optimize performance by deferring computations,\n *   especially when the effect might not be needed, or when its computation is\n *   expensive. This also ensures that any side effects or scoped captures are\n *   re-executed on each invocation.\n * - **Handling Circular Dependencies**: Useful in managing circular\n *   dependencies, such as recursive functions that need to avoid eager\n *   evaluation to prevent stack overflow.\n * - **Unifying Return Types**: Can help TypeScript unify return types in\n *   situations where multiple branches of logic return different effects,\n *   simplifying type inference.\n *\n * **When to Use**\n *\n * Use this function when you need to defer the evaluation of an effect until it\n * is required. This is particularly useful for optimizing expensive\n * computations, managing circular dependencies, or resolving type inference\n * issues.\n *\n * **Example** (Lazy Evaluation with Side Effects)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * let i = 0\n *\n * const bad = Effect.succeed(i++)\n *\n * const good = Effect.suspend(() => Effect.succeed(i++))\n *\n * console.log(Effect.runSync(bad)) // Output: 0\n * console.log(Effect.runSync(bad)) // Output: 0\n *\n * console.log(Effect.runSync(good)) // Output: 1\n * console.log(Effect.runSync(good)) // Output: 2\n * ```\n *\n * **Example** (Recursive Fibonacci)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const blowsUp = (n: number): Effect.Effect<number> =>\n *   n < 2\n *     ? Effect.succeed(1)\n *     : Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b)\n *\n * console.log(Effect.runSync(blowsUp(32)))\n * // crash: JavaScript heap out of memory\n *\n * const allGood = (n: number): Effect.Effect<number> =>\n *   n < 2\n *     ? Effect.succeed(1)\n *     : Effect.zipWith(\n *         Effect.suspend(() => allGood(n - 1)),\n *         Effect.suspend(() => allGood(n - 2)),\n *         (a, b) => a + b\n *       )\n *\n * console.log(Effect.runSync(allGood(32)))\n * // Output: 3524578\n * ```\n *\n * **Example** (Using Effect.suspend to Help TypeScript Infer Types)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * //   Without suspend, TypeScript may struggle with type inference.\n * //   Inferred type:\n * //     (a: number, b: number) =>\n * //       Effect<never, Error, never> | Effect<number, never, never>\n * const withoutSuspend = (a: number, b: number) =>\n *   b === 0\n *     ? Effect.fail(new Error(\"Cannot divide by zero\"))\n *     : Effect.succeed(a / b)\n *\n * //   Using suspend to unify return types.\n * //   Inferred type:\n * //     (a: number, b: number) => Effect<number, Error, never>\n * const withSuspend = (a: number, b: number) =>\n *   Effect.suspend(() =>\n *     b === 0\n *       ? Effect.fail(new Error(\"Cannot divide by zero\"))\n *       : Effect.succeed(a / b)\n *   )\n * ```\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const suspend: <A, E, R>(effect: LazyArg<Effect<A, E, R>>) => Effect<A, E, R> = core.suspend\n\n/**\n * Creates an `Effect` that represents a synchronous side-effectful computation.\n *\n * **Details**\n *\n * The provided function (`thunk`) must not throw errors; if it does, the error\n * will be treated as a \"defect\".\n *\n * This defect is not a standard error but indicates a flaw in the logic that\n * was expected to be error-free. You can think of it similar to an unexpected\n * crash in the program, which can be further managed or logged using tools like\n * {@link catchAllDefect}.\n *\n * **When to Use**\n *\n * Use this function when you are sure the operation will not fail.\n *\n * **Example** (Logging a Message)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const log = (message: string) =>\n *   Effect.sync(() => {\n *     console.log(message) // side effect\n *   })\n *\n * //      ┌─── Effect<void, never, never>\n * //      ▼\n * const program = log(\"Hello, World!\")\n * ```\n *\n * @see {@link try_ | try} for a version that can handle failures.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const sync: <A>(thunk: LazyArg<A>) => Effect<A> = core.sync\n\nconst _void: Effect<void> = core.void\n\nexport {\n  /**\n   * Represents an effect that does nothing and produces no value.\n   *\n   * **When to Use**\n   *\n   * Use this effect when you need to represent an effect that does nothing.\n   * This is useful in scenarios where you need to satisfy an effect-based\n   * interface or control program flow without performing any operations. For\n   * example, it can be used in situations where you want to return an effect\n   * from a function but do not need to compute or return any result.\n   *\n   * @since 2.0.0\n   * @category Creating Effects\n   */\n  _void as void\n}\n\n/**\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const yieldNow: (options?: {\n  readonly priority?: number | undefined\n}) => Effect<void> = core.yieldNow\n\nconst _catch: {\n  <N extends keyof E, K extends E[N] & string, E, A1, E1, R1>(\n    discriminator: N,\n    options: { readonly failure: K; readonly onFailure: (error: Extract<E, { [n in N]: K }>) => Effect<A1, E1, R1> }\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A1 | A, E1 | Exclude<E, { [n in N]: K }>, R1 | R>\n  <A, E, R, N extends keyof E, K extends E[N] & string, A1, E1, R1>(\n    self: Effect<A, E, R>,\n    discriminator: N,\n    options: { readonly failure: K; readonly onFailure: (error: Extract<E, { [n in N]: K }>) => Effect<A1, E1, R1> }\n  ): Effect<A | A1, E1 | Exclude<E, { [n in N]: K }>, R | R1>\n} = effect._catch\n\nexport {\n  /**\n   * Recovers from a specified error by catching it and handling it with a provided function.\n   *\n   * **Details**\n   *\n   * This function allows you to recover from specific errors that occur during\n   * the execution of an effect. It works by catching a specific type of error\n   * (identified by a discriminator) and then handling it using a provided\n   * handler function. The handler can return a new effect that helps recover\n   * from the error, allowing the program to continue. If the error doesn't\n   * match the specified type, the function allows the original effect to\n   * continue as it was.\n   *\n   * **Example**\n   *\n   * ```ts\n   * import { Console, Effect } from \"effect\"\n   *\n   * class NetworkError {\n   *   readonly _tag = \"NetworkError\"\n   * }\n   * class ValidationError {\n   *   readonly _tag = \"ValidationError\"\n   * }\n   *\n   * // Simulate an effect that may fail\n   * const task: Effect.Effect<never, NetworkError | ValidationError, never> = Effect.fail(new NetworkError())\n   *\n   * const program = Effect.gen(function*() {\n   *   const result = yield* Effect.catch(task, \"_tag\", {\n   *     failure: \"NetworkError\",\n   *     onFailure: (error) => Effect.succeed(`recovered from error: ${error._tag}`)\n   *   })\n   *   console.log(`Result: ${result}`)\n   * })\n   *\n   * Effect.runFork(program)\n   * // Output: Result: recovered from error: NetworkError\n   * ```\n   *\n   * @see {@link catchTag} for a version that can recover from errors based on a `_tag` discriminator.\n   *\n   * @since 2.0.0\n   * @category Error handling\n   */\n  _catch as catch\n}\n\n/**\n * Handles all errors in an effect by providing a fallback effect.\n *\n * **Details**\n *\n * This function catches any errors that may occur during the execution of an\n * effect and allows you to handle them by specifying a fallback effect. This\n * ensures that the program continues without failing by recovering from errors\n * using the provided fallback logic.\n *\n * **Note**: This function only handles recoverable errors. It will not recover\n * from unrecoverable defects.\n *\n * **Example** (Providing Recovery Logic for Recoverable Errors)\n *\n * ```ts\n * import { Effect, Random } from \"effect\"\n *\n * class HttpError {\n *   readonly _tag = \"HttpError\"\n * }\n *\n * class ValidationError {\n *   readonly _tag = \"ValidationError\"\n * }\n *\n * //      ┌─── Effect<string, HttpError | ValidationError, never>\n * //      ▼\n * const program = Effect.gen(function* () {\n *   const n1 = yield* Random.next\n *   const n2 = yield* Random.next\n *   if (n1 < 0.5) {\n *     yield* Effect.fail(new HttpError())\n *   }\n *   if (n2 < 0.5) {\n *     yield* Effect.fail(new ValidationError())\n *   }\n *   return \"some result\"\n * })\n *\n * //      ┌─── Effect<string, never, never>\n * //      ▼\n * const recovered = program.pipe(\n *   Effect.catchAll((error) =>\n *     Effect.succeed(`Recovering from ${error._tag}`)\n *   )\n * )\n * ```\n *\n * @see {@link catchAllCause} for a version that can recover from both\n * recoverable and unrecoverable errors.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const catchAll: {\n  <E, A2, E2, R2>(f: (e: E) => Effect<A2, E2, R2>): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Effect<A, E, R>, f: (e: E) => Effect<A2, E2, R2>): Effect<A2 | A, E2, R2 | R>\n} = core.catchAll\n\n/**\n * Handles both recoverable and unrecoverable errors by providing a recovery\n * effect.\n *\n * **When to Use**\n *\n * The `catchAllCause` function allows you to handle all errors, including\n * unrecoverable defects, by providing a recovery effect. The recovery logic is\n * based on the `Cause` of the error, which provides detailed information about\n * the failure.\n *\n * **When to Recover from Defects**\n *\n * Defects are unexpected errors that typically shouldn't be recovered from, as\n * they often indicate serious issues. However, in some cases, such as\n * dynamically loaded plugins, controlled recovery might be needed.\n *\n * **Example** (Recovering from All Errors)\n *\n * ```ts\n * import { Cause, Effect } from \"effect\"\n *\n * // Define an effect that may fail with a recoverable or unrecoverable error\n * const program = Effect.fail(\"Something went wrong!\")\n *\n * // Recover from all errors by examining the cause\n * const recovered = program.pipe(\n *   Effect.catchAllCause((cause) =>\n *     Cause.isFailure(cause)\n *       ? Effect.succeed(\"Recovered from a regular error\")\n *       : Effect.succeed(\"Recovered from a defect\")\n *   )\n * )\n *\n * Effect.runPromise(recovered).then(console.log)\n * // Output: \"Recovered from a regular error\"\n * ```\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const catchAllCause: {\n  <E, A2, E2, R2>(\n    f: (cause: Cause.Cause<E>) => Effect<A2, E2, R2>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    f: (cause: Cause.Cause<E>) => Effect<A2, E2, R2>\n  ): Effect<A | A2, E2, R | R2>\n} = core.catchAllCause\n\n/**\n * Recovers from all defects using a provided recovery function.\n *\n * **When to Use**\n *\n * There is no sensible way to recover from defects. This method should be used\n * only at the boundary between Effect and an external system, to transmit\n * information on a defect for diagnostic or explanatory purposes.\n *\n * **Details**\n *\n * `catchAllDefect` allows you to handle defects, which are unexpected errors\n * that usually cause the program to terminate. This function lets you recover\n * from these defects by providing a function that handles the error. However,\n * it does not handle expected errors (like those from {@link fail}) or\n * execution interruptions (like those from {@link interrupt}).\n *\n * **When to Recover from Defects**\n *\n * Defects are unexpected errors that typically shouldn't be recovered from, as\n * they often indicate serious issues. However, in some cases, such as\n * dynamically loaded plugins, controlled recovery might be needed.\n *\n * **Example** (Handling All Defects)\n *\n * ```ts\n * import { Effect, Cause, Console } from \"effect\"\n *\n * // Simulating a runtime error\n * const task = Effect.dieMessage(\"Boom!\")\n *\n * const program = Effect.catchAllDefect(task, (defect) => {\n *   if (Cause.isRuntimeException(defect)) {\n *     return Console.log(\n *       `RuntimeException defect caught: ${defect.message}`\n *     )\n *   }\n *   return Console.log(\"Unknown defect caught.\")\n * })\n *\n * // We get an Exit.Success because we caught all defects\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // RuntimeException defect caught: Boom!\n * // {\n * //   _id: \"Exit\",\n * //   _tag: \"Success\",\n * //   value: undefined\n * // }\n * ```\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const catchAllDefect: {\n  <A2, E2, R2>(\n    f: (defect: unknown) => Effect<A2, E2, R2>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    f: (defect: unknown) => Effect<A2, E2, R2>\n  ): Effect<A | A2, E | E2, R | R2>\n} = effect.catchAllDefect\n\n/**\n * Recovers from specific errors based on a predicate.\n *\n * **When to Use**\n *\n * `catchIf` works similarly to {@link catchSome}, but it allows you to\n * recover from errors by providing a predicate function. If the predicate\n * matches the error, the recovery effect is applied. This function doesn't\n * alter the error type, so the resulting effect still carries the original\n * error type unless a user-defined type guard is used to narrow the type.\n *\n * **Example** (Catching Specific Errors with a Predicate)\n *\n * ```ts\n * import { Effect, Random } from \"effect\"\n *\n * class HttpError {\n *   readonly _tag = \"HttpError\"\n * }\n *\n * class ValidationError {\n *   readonly _tag = \"ValidationError\"\n * }\n *\n * //      ┌─── Effect<string, HttpError | ValidationError, never>\n * //      ▼\n * const program = Effect.gen(function* () {\n *   const n1 = yield* Random.next\n *   const n2 = yield* Random.next\n *   if (n1 < 0.5) {\n *     yield* Effect.fail(new HttpError())\n *   }\n *   if (n2 < 0.5) {\n *     yield* Effect.fail(new ValidationError())\n *   }\n *   return \"some result\"\n * })\n *\n * //      ┌─── Effect<string, ValidationError, never>\n * //      ▼\n * const recovered = program.pipe(\n *   Effect.catchIf(\n *     // Only handle HttpError errors\n *     (error) => error._tag === \"HttpError\",\n *     () => Effect.succeed(\"Recovering from HttpError\")\n *   )\n * )\n * ```\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const catchIf: {\n  <E, EB extends E, A2, E2, R2>(\n    refinement: Refinement<NoInfer<E>, EB>,\n    f: (e: EB) => Effect<A2, E2, R2>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2 | Exclude<E, EB>, R2 | R>\n  <E, A2, E2, R2>(\n    predicate: Predicate<NoInfer<E>>,\n    f: (e: NoInfer<E>) => Effect<A2, E2, R2>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E | E2, R2 | R>\n  <A, E, R, EB extends E, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    refinement: Refinement<E, EB>,\n    f: (e: EB) => Effect<A2, E2, R2>\n  ): Effect<A | A2, E2 | Exclude<E, EB>, R | R2>\n  <A, E, R, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    predicate: Predicate<E>,\n    f: (e: E) => Effect<A2, E2, R2>\n  ): Effect<A | A2, E | E2, R | R2>\n} = core.catchIf\n\n/**\n * Catches and recovers from specific types of errors, allowing you to attempt\n * recovery only for certain errors.\n *\n * **Details**\n *\n * `catchSome` lets you selectively catch and handle errors of certain\n * types by providing a recovery effect for specific errors. If the error\n * matches a condition, recovery is attempted; if not, it doesn't affect the\n * program. This function doesn't alter the error type, meaning the error type\n * remains the same as in the original effect.\n *\n * **Example** (Handling Specific Errors with Effect.catchSome)\n *\n * ```ts\n * import { Effect, Random, Option } from \"effect\"\n *\n * class HttpError {\n *   readonly _tag = \"HttpError\"\n * }\n *\n * class ValidationError {\n *   readonly _tag = \"ValidationError\"\n * }\n *\n * //      ┌─── Effect<string, HttpError | ValidationError, never>\n * //      ▼\n * const program = Effect.gen(function* () {\n *   const n1 = yield* Random.next\n *   const n2 = yield* Random.next\n *   if (n1 < 0.5) {\n *     yield* Effect.fail(new HttpError())\n *   }\n *   if (n2 < 0.5) {\n *     yield* Effect.fail(new ValidationError())\n *   }\n *   return \"some result\"\n * })\n *\n * //      ┌─── Effect<string, HttpError | ValidationError, never>\n * //      ▼\n * const recovered = program.pipe(\n *   Effect.catchSome((error) => {\n *     // Only handle HttpError errors\n *     if (error._tag === \"HttpError\") {\n *       return Option.some(Effect.succeed(\"Recovering from HttpError\"))\n *     } else {\n *       return Option.none()\n *     }\n *   })\n * )\n * ```\n *\n * @see {@link catchIf} for a version that allows you to recover from errors based on a predicate.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const catchSome: {\n  <E, A2, E2, R2>(\n    pf: (e: NoInfer<E>) => Option.Option<Effect<A2, E2, R2>>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E | E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    pf: (e: NoInfer<E>) => Option.Option<Effect<A2, E2, R2>>\n  ): Effect<A | A2, E | E2, R | R2>\n} = core.catchSome\n\n/**\n * Recovers from specific causes using a provided partial function.\n *\n * @see {@link catchSome} for a version that allows you to recover from errors.\n * @see {@link catchSomeDefect} for a version that allows you to recover from defects.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const catchSomeCause: {\n  <E, A2, E2, R2>(\n    f: (cause: Cause.Cause<NoInfer<E>>) => Option.Option<Effect<A2, E2, R2>>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E | E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    f: (cause: Cause.Cause<NoInfer<E>>) => Option.Option<Effect<A2, E2, R2>>\n  ): Effect<A2 | A, E | E2, R2 | R>\n} = effect.catchSomeCause\n\n/**\n * Recovers from specific defects using a provided partial function.\n *\n * **Details**\n *\n * `catchSomeDefect` allows you to handle specific defects, which are\n * unexpected errors that can cause the program to stop. It uses a partial\n * function to catch only certain defects and ignores others. The function does\n * not handle expected errors (such as those caused by {@link fail}) or\n * interruptions in execution (like those caused by {@link interrupt}).\n *\n * This function provides a way to handle certain types of defects while\n * allowing others to propagate and cause failure in the program.\n *\n * **Note**: There is no sensible way to recover from defects. This method\n * should be used only at the boundary between Effect and an external system, to\n * transmit information on a defect for diagnostic or explanatory purposes.\n *\n * **How the Partial Function Works**\n *\n * The function provided to `catchSomeDefect` acts as a filter and a handler for defects:\n * - It receives the defect as an input.\n * - If the defect matches a specific condition (e.g., a certain error type), the function returns\n *   an `Option.some` containing the recovery logic.\n * - If the defect does not match, the function returns `Option.none`, allowing the defect to propagate.\n *\n * **Example** (Handling Specific Defects)\n *\n * ```ts\n * import { Effect, Cause, Option, Console } from \"effect\"\n *\n * // Simulating a runtime error\n * const task = Effect.dieMessage(\"Boom!\")\n *\n * const program = Effect.catchSomeDefect(task, (defect) => {\n *   if (Cause.isIllegalArgumentException(defect)) {\n *     return Option.some(\n *       Console.log(\n *         `Caught an IllegalArgumentException defect: ${defect.message}`\n *       )\n *     )\n *   }\n *   return Option.none()\n * })\n *\n * // Since we are only catching IllegalArgumentException\n * // we will get an Exit.Failure because we simulated a runtime error.\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Die',\n * //     defect: { _tag: 'RuntimeException' }\n * //   }\n * // }\n * ```\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const catchSomeDefect: {\n  <A2, E2, R2>(\n    pf: (defect: unknown) => Option.Option<Effect<A2, E2, R2>>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    pf: (defect: unknown) => Option.Option<Effect<A2, E2, R2>>\n  ): Effect<A | A2, E | E2, R | R2>\n} = effect.catchSomeDefect\n\n/**\n * Catches and handles specific errors by their `_tag` field, which is used as a\n * discriminator.\n *\n * **When to Use**\n *\n * `catchTag` is useful when your errors are tagged with a readonly `_tag` field\n * that identifies the error type. You can use this function to handle specific\n * error types by matching the `_tag` value. This allows for precise error\n * handling, ensuring that only specific errors are caught and handled.\n *\n * The error type must have a readonly `_tag` field to use `catchTag`. This\n * field is used to identify and match errors.\n *\n * **Example** (Handling Errors by Tag)\n *\n * ```ts\n * import { Effect, Random } from \"effect\"\n *\n * class HttpError {\n *   readonly _tag = \"HttpError\"\n * }\n *\n * class ValidationError {\n *   readonly _tag = \"ValidationError\"\n * }\n *\n * //      ┌─── Effect<string, HttpError | ValidationError, never>\n * //      ▼\n * const program = Effect.gen(function* () {\n *   const n1 = yield* Random.next\n *   const n2 = yield* Random.next\n *   if (n1 < 0.5) {\n *     yield* Effect.fail(new HttpError())\n *   }\n *   if (n2 < 0.5) {\n *     yield* Effect.fail(new ValidationError())\n *   }\n *   return \"some result\"\n * })\n *\n * //      ┌─── Effect<string, ValidationError, never>\n * //      ▼\n * const recovered = program.pipe(\n *   // Only handle HttpError errors\n *   Effect.catchTag(\"HttpError\", (_HttpError) =>\n *     Effect.succeed(\"Recovering from HttpError\")\n *   )\n * )\n * ```\n *\n * @see {@link catchTags} for a version that allows you to handle multiple error\n * types at once.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const catchTag: {\n  <E, const K extends RA.NonEmptyReadonlyArray<E extends { _tag: string } ? E[\"_tag\"] : never>, A1, E1, R1>(\n    ...args: [...tags: K, f: (e: Extract<NoInfer<E>, { _tag: K[number] }>) => Effect<A1, E1, R1>]\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A | A1, Exclude<E, { _tag: K[number] }> | E1, R | R1>\n  <A, E, R, const K extends RA.NonEmptyReadonlyArray<E extends { _tag: string } ? E[\"_tag\"] : never>, A1, E1, R1>(\n    self: Effect<A, E, R>,\n    ...args: [...tags: K, f: (e: Extract<NoInfer<E>, { _tag: K[number] }>) => Effect<A1, E1, R1>]\n  ): Effect<A | A1, Exclude<E, { _tag: K[number] }> | E1, R | R1>\n} = effect.catchTag\n\n/**\n * Handles multiple errors in a single block of code using their `_tag` field.\n *\n * **When to Use**\n *\n * `catchTags` is a convenient way to handle multiple error types at\n * once. Instead of using {@link catchTag} multiple times, you can pass an\n * object where each key is an error type's `_tag`, and the value is the handler\n * for that specific error. This allows you to catch and recover from multiple\n * error types in a single call.\n *\n * The error type must have a readonly `_tag` field to use `catchTag`. This\n * field is used to identify and match errors.\n *\n * **Example** (Handling Multiple Tagged Error Types at Once)\n *\n * ```ts\n * import { Effect, Random } from \"effect\"\n *\n * class HttpError {\n *   readonly _tag = \"HttpError\"\n * }\n *\n * class ValidationError {\n *   readonly _tag = \"ValidationError\"\n * }\n *\n * //      ┌─── Effect<string, HttpError | ValidationError, never>\n * //      ▼\n * const program = Effect.gen(function* () {\n *   const n1 = yield* Random.next\n *   const n2 = yield* Random.next\n *   if (n1 < 0.5) {\n *     yield* Effect.fail(new HttpError())\n *   }\n *   if (n2 < 0.5) {\n *     yield* Effect.fail(new ValidationError())\n *   }\n *   return \"some result\"\n * })\n *\n * //      ┌─── Effect<string, never, never>\n * //      ▼\n * const recovered = program.pipe(\n *   Effect.catchTags({\n *     HttpError: (_HttpError) =>\n *       Effect.succeed(`Recovering from HttpError`),\n *     ValidationError: (_ValidationError) =>\n *       Effect.succeed(`Recovering from ValidationError`)\n *   })\n * )\n * ```\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const catchTags: {\n  <\n    E,\n    Cases extends\n      & { [K in Extract<E, { _tag: string }>[\"_tag\"]]+?: ((error: Extract<E, { _tag: K }>) => Effect<any, any, any>) }\n      & (unknown extends E ? {} : { [K in Exclude<keyof Cases, Extract<E, { _tag: string }>[\"_tag\"]>]: never })\n  >(\n    cases: Cases\n  ): <A, R>(\n    self: Effect<A, E, R>\n  ) => Effect<\n    | A\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<infer A, any, any> ? A : never\n    }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<any, infer E, any> ? E : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<any, any, infer R> ? R : never\n    }[keyof Cases]\n  >\n  <\n    R,\n    E,\n    A,\n    Cases extends\n      & { [K in Extract<E, { _tag: string }>[\"_tag\"]]+?: ((error: Extract<E, { _tag: K }>) => Effect<any, any, any>) }\n      & (unknown extends E ? {} : { [K in Exclude<keyof Cases, Extract<E, { _tag: string }>[\"_tag\"]>]: never })\n  >(\n    self: Effect<A, E, R>,\n    cases: Cases\n  ): Effect<\n    | A\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<infer A, any, any> ? A : never\n    }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<any, infer E, any> ? E : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<any, any, infer R> ? R : never\n    }[keyof Cases]\n  >\n} = effect.catchTags\n\n/**\n * Retrieves the cause of a failure in an effect.\n *\n * **Details**\n *\n * This function allows you to expose the detailed cause of an effect, which\n * includes a more precise representation of failures, such as error messages\n * and defects.\n *\n * **When to Use**\n *\n * This function is helpful when you need to inspect the cause of a failure in\n * an effect, giving you more information than just the error message. It can be\n * used to log, handle, or analyze failures in more detail, including\n * distinguishing between different types of defects (e.g., runtime exceptions,\n * interruptions, etc.).\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * //      ┌─── Effect<number, string, never>\n * //      ▼\n * const program = Effect.fail(\"Oh uh!\").pipe(Effect.as(2))\n *\n * //      ┌─── Effect<void, never, never>\n * //      ▼\n * const recovered = Effect.gen(function* () {\n *   const cause = yield* Effect.cause(program)\n *   yield* Console.log(cause)\n * })\n * ```\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const cause: <A, E, R>(self: Effect<A, E, R>) => Effect<Cause.Cause<E>, never, R> = effect.cause\n\n/**\n * Runs an effect repeatedly until it succeeds, ignoring errors.\n *\n * **Details**\n *\n * This function takes an effect and runs it repeatedly until the effect\n * successfully completes. If the effect fails, it will ignore the error and\n * retry the operation. This is useful when you need to perform a task that may\n * fail occasionally, but you want to keep trying until it eventually succeeds.\n * It works by repeatedly executing the effect until it no longer throws an\n * error.\n *\n * **When to Use**\n *\n * Use this function when you want to retry an operation multiple times until it\n * succeeds. It is helpful in cases where the operation may fail temporarily\n * (e.g., a network request), and you want to keep trying without handling or\n * worrying about the errors.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * let counter = 0\n *\n * const effect = Effect.try(() => {\n *   counter++\n *   if (counter < 3) {\n *     console.log(\"running effect\")\n *     throw new Error(\"error\")\n *   } else {\n *     console.log(\"effect done\")\n *     return \"some result\"\n *   }\n * })\n *\n * const program = Effect.eventually(effect)\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // running effect\n * // running effect\n * // effect done\n * // some result\n * ```\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const eventually: <A, E, R>(self: Effect<A, E, R>) => Effect<A, never, R> = effect.eventually\n\n/**\n * Discards both the success and failure values of an effect.\n *\n * **When to Use**\n *\n * `ignore` allows you to run an effect without caring about its result, whether\n * it succeeds or fails. This is useful when you only care about the side\n * effects of the effect and do not need to handle or process its outcome.\n *\n * **Example** (Using Effect.ignore to Discard Values)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * //      ┌─── Effect<number, string, never>\n * //      ▼\n * const task = Effect.fail(\"Uh oh!\").pipe(Effect.as(5))\n *\n * //      ┌─── Effect<void, never, never>\n * //      ▼\n * const program = Effect.ignore(task)\n * ```\n *\n * @see {@link ignoreLogged} to log failures while ignoring them.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const ignore: <A, E, R>(self: Effect<A, E, R>) => Effect<void, never, R> = effect.ignore\n\n/**\n * Ignores the result of an effect but logs any failures.\n *\n * **Details**\n *\n * This function takes an effect and returns a new effect that ignores whether\n * the original effect succeeds or fails. However, if the effect fails, it will\n * log the failure at the Debug level, so you can keep track of any issues that\n * arise.\n *\n * **When to Use**\n *\n * This is useful in scenarios where you want to continue with your program\n * regardless of the result of the effect, but you still want to be aware of\n * potential failures that may need attention later.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const ignoreLogged: <A, E, R>(self: Effect<A, E, R>) => Effect<void, never, R> = effect.ignoreLogged\n\n/**\n * Combines all errors from concurrent operations into a single error.\n *\n * **Details**\n *\n * This function is used when you have multiple operations running at the same\n * time, and you want to capture all the errors that occur across those\n * operations. Instead of handling each error separately, it combines all the\n * errors into one unified error.\n *\n * **When to Use**\n *\n * When using this function, any errors that occur in the concurrently running\n * operations will be grouped together into a single error. This helps simplify\n * error handling in cases where you don't need to differentiate between each\n * failure, but simply want to know that multiple failures occurred.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const fail1 = Effect.fail(\"Oh uh!\")\n * const fail2 = Effect.fail(\"Oh no!\")\n * const die = Effect.dieMessage(\"Boom!\")\n *\n * // Run all effects concurrently and capture all errors\n * const program = Effect.all([fail1, fail2, die], {\n *   concurrency: \"unbounded\"\n * }).pipe(Effect.asVoid, Effect.parallelErrors)\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: { _id: 'Cause', _tag: 'Fail', failure: [ 'Oh uh!', 'Oh no!' ] }\n * // }\n * ```\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const parallelErrors: <A, E, R>(self: Effect<A, E, R>) => Effect<A, Array<E>, R> = effect.parallelErrors\n\n/**\n * Transforms an effect to expose detailed error causes.\n *\n * **Details**\n *\n * This function enhances an effect by providing detailed information about any\n * error, defect, or interruption that may occur during its execution. It\n * modifies the error channel of the effect so that it includes a full cause of\n * the failure, wrapped in a `Cause<E>` type.\n *\n * After applying this function, you can use operators like {@link catchAll} and\n * {@link catchTags} to handle specific types of errors.\n *\n * If you no longer need the detailed cause information, you can revert the\n * changes using {@link unsandbox} to return to the original error-handling\n * behavior.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * //      ┌─── Effect<string, Error, never>\n * //      ▼\n * const task = Effect.fail(new Error(\"Oh uh!\")).pipe(\n *   Effect.as(\"primary result\")\n * )\n *\n * //      ┌─── Effect<string, Cause<Error>, never>\n * //      ▼\n * const sandboxed = Effect.sandbox(task)\n *\n * const program = Effect.catchTags(sandboxed, {\n *   Die: (cause) =>\n *     Console.log(`Caught a defect: ${cause.defect}`).pipe(\n *       Effect.as(\"fallback result on defect\")\n *     ),\n *   Interrupt: (cause) =>\n *     Console.log(`Caught a defect: ${cause.fiberId}`).pipe(\n *       Effect.as(\"fallback result on fiber interruption\")\n *     ),\n *   Fail: (cause) =>\n *     Console.log(`Caught a defect: ${cause.error}`).pipe(\n *       Effect.as(\"fallback result on failure\")\n *     )\n * })\n *\n * // Restore the original error handling with unsandbox\n * const main = Effect.unsandbox(program)\n *\n * Effect.runPromise(main).then(console.log)\n * // Output:\n * // Caught a defect: Oh uh!\n * // fallback result on failure\n * ```\n *\n * @see {@link unsandbox} to restore the original error handling.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const sandbox: <A, E, R>(self: Effect<A, E, R>) => Effect<A, Cause.Cause<E>, R> = effect.sandbox\n\n/**\n * @since 2.0.0\n * @category Error handling\n */\nexport declare namespace Retry {\n  /**\n   * @since 2.0.0\n   * @category Error handling\n   */\n  export type Return<R, E, A, O extends NoExcessProperties<Options<E>, O>> = Effect<\n    A,\n    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer _R> } ? E\n      : O extends { until: Refinement<E, infer E2> } ? E2\n      : E)\n    | (O extends { while: (...args: Array<any>) => Effect<infer _A, infer E, infer _R> } ? E : never)\n    | (O extends { until: (...args: Array<any>) => Effect<infer _A, infer E, infer _R> } ? E : never),\n    | R\n    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer R> } ? R : never)\n    | (O extends { while: (...args: Array<any>) => Effect<infer _A, infer _E, infer R> } ? R : never)\n    | (O extends { until: (...args: Array<any>) => Effect<infer _A, infer _E, infer R> } ? R : never)\n  > extends infer Z ? Z : never\n\n  /**\n   * @since 2.0.0\n   * @category Error handling\n   */\n  export interface Options<E> {\n    while?: ((error: E) => boolean | Effect<boolean, any, any>) | undefined\n    until?: ((error: E) => boolean | Effect<boolean, any, any>) | undefined\n    times?: number | undefined\n    schedule?: Schedule.Schedule<any, E, any> | undefined\n  }\n}\n\n/**\n * Retries a failing effect based on a defined retry policy.\n *\n * **Details**\n *\n * The `Effect.retry` function takes an effect and a {@link Schedule} policy,\n * and will automatically retry the effect if it fails, following the rules of\n * the policy.\n *\n * If the effect ultimately succeeds, the result will be returned.\n *\n * If the maximum retries are exhausted and the effect still fails, the failure\n * is propagated.\n *\n * **When to Use**\n *\n * This can be useful when dealing with intermittent failures, such as network\n * issues or temporary resource unavailability. By defining a retry policy, you\n * can control the number of retries, the delay between them, and when to stop\n * retrying.\n *\n * **Example** (Retrying with a Fixed Delay)\n *\n * ```ts\n * import { Effect, Schedule } from \"effect\"\n *\n * let count = 0\n *\n * // Simulates an effect with possible failures\n * const task = Effect.async<string, Error>((resume) => {\n *   if (count <= 2) {\n *     count++\n *     console.log(\"failure\")\n *     resume(Effect.fail(new Error()))\n *   } else {\n *     console.log(\"success\")\n *     resume(Effect.succeed(\"yay!\"))\n *   }\n * })\n *\n * // Define a repetition policy using a fixed delay between retries\n * const policy = Schedule.fixed(\"100 millis\")\n *\n * const repeated = Effect.retry(task, policy)\n *\n * Effect.runPromise(repeated).then(console.log)\n * // Output:\n * // failure\n * // failure\n * // failure\n * // success\n * // yay!\n * ```\n *\n * **Example** (Retrying a Task up to 5 times)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * let count = 0\n *\n * // Simulates an effect with possible failures\n * const task = Effect.async<string, Error>((resume) => {\n *   if (count <= 2) {\n *     count++\n *     console.log(\"failure\")\n *     resume(Effect.fail(new Error()))\n *   } else {\n *     console.log(\"success\")\n *     resume(Effect.succeed(\"yay!\"))\n *   }\n * })\n *\n * // Retry the task up to 5 times\n * Effect.runPromise(Effect.retry(task, { times: 5 })).then(console.log)\n * // Output:\n * // failure\n * // failure\n * // failure\n * // success\n * ```\n *\n * **Example** (Retrying Until a Specific Condition is Met)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * let count = 0\n *\n * // Define an effect that simulates varying error on each invocation\n * const action = Effect.failSync(() => {\n *   console.log(`Action called ${++count} time(s)`)\n *   return `Error ${count}`\n * })\n *\n * // Retry the action until a specific condition is met\n * const program = Effect.retry(action, {\n *   until: (err) => err === \"Error 3\"\n * })\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // Action called 1 time(s)\n * // Action called 2 time(s)\n * // Action called 3 time(s)\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: { _id: 'Cause', _tag: 'Fail', failure: 'Error 3' }\n * // }\n * ```\n *\n * @see {@link retryOrElse} for a version that allows you to run a fallback.\n * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const retry: {\n  <E, O extends NoExcessProperties<Retry.Options<E>, O>>(\n    options: O\n  ): <A, R>(self: Effect<A, E, R>) => Retry.Return<R, E, A, O>\n  <B, E, R1>(policy: Schedule.Schedule<B, NoInfer<E>, R1>): <A, R>(self: Effect<A, E, R>) => Effect<A, E, R1 | R>\n  <A, E, R, O extends NoExcessProperties<Retry.Options<E>, O>>(\n    self: Effect<A, E, R>,\n    options: O\n  ): Retry.Return<R, E, A, O>\n  <A, E, R, B, R1>(self: Effect<A, E, R>, policy: Schedule.Schedule<B, NoInfer<E>, R1>): Effect<A, E, R1 | R>\n} = schedule_.retry_combined\n\n/**\n * Apply an `ExecutionPlan` to the effect, which allows you to fallback to\n * different resources in case of failure.\n *\n * @since 3.16.0\n * @category Error handling\n * @experimental\n */\nexport const withExecutionPlan: {\n  <Input, Provides, PlanE, PlanR>(\n    plan: ExecutionPlan<{ provides: Provides; input: Input; error: PlanE; requirements: PlanR }>\n  ): <A, E extends Input, R>(effect: Effect<A, E, R>) => Effect<A, E | PlanE, Exclude<R, Provides> | PlanR>\n  <A, E extends Input, R, Provides, Input, PlanE, PlanR>(\n    effect: Effect<A, E, R>,\n    plan: ExecutionPlan<{ provides: Provides; input: Input; error: PlanE; requirements: PlanR }>\n  ): Effect<A, E | PlanE, Exclude<R, Provides> | PlanR>\n} = internalExecutionPlan.withExecutionPlan\n\n/**\n * Retries a failing effect and runs a fallback effect if retries are exhausted.\n *\n * **Details**\n *\n * The `Effect.retryOrElse` function attempts to retry a failing effect multiple\n * times according to a defined {@link Schedule} policy.\n *\n * If the retries are exhausted and the effect still fails, it runs a fallback\n * effect instead.\n *\n * **When to Use**\n *\n * This function is useful when you want to handle failures gracefully by\n * specifying an alternative action after repeated failures.\n *\n * **Example** (Retrying with Fallback)\n *\n * ```ts\n * import { Effect, Schedule, Console } from \"effect\"\n *\n * let count = 0\n *\n * // Simulates an effect with possible failures\n * const task = Effect.async<string, Error>((resume) => {\n *   if (count <= 2) {\n *     count++\n *     console.log(\"failure\")\n *     resume(Effect.fail(new Error()))\n *   } else {\n *     console.log(\"success\")\n *     resume(Effect.succeed(\"yay!\"))\n *   }\n * })\n *\n * // Retry the task with a delay between retries and a maximum of 2 retries\n * const policy = Schedule.addDelay(Schedule.recurs(2), () => \"100 millis\")\n *\n * // If all retries fail, run the fallback effect\n * const repeated = Effect.retryOrElse(\n *   task,\n *   policy,\n *   // fallback\n *   () => Console.log(\"orElse\").pipe(Effect.as(\"default value\"))\n * )\n *\n * Effect.runPromise(repeated).then(console.log)\n * // Output:\n * // failure\n * // failure\n * // failure\n * // orElse\n * // default value\n * ```\n *\n * @see {@link retry} for a version that does not run a fallback effect.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const retryOrElse: {\n  <A1, E, R1, A2, E2, R2>(\n    policy: Schedule.Schedule<A1, NoInfer<E>, R1>,\n    orElse: (e: NoInfer<E>, out: A1) => Effect<A2, E2, R2>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2, R1 | R2 | R>\n  <A, E, R, A1, R1, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    policy: Schedule.Schedule<A1, NoInfer<E>, R1>,\n    orElse: (e: NoInfer<E>, out: A1) => Effect<A2, E2, R2>\n  ): Effect<A | A2, E2, R | R1 | R2>\n} = schedule_.retryOrElse_Effect\n\nconst try_: {\n  <A, E>(options: { readonly try: LazyArg<A>; readonly catch: (error: unknown) => E }): Effect<A, E>\n  <A>(thunk: LazyArg<A>): Effect<A, Cause.UnknownException>\n} = effect.try_\n\nexport {\n  /**\n   * Creates an `Effect` that represents a synchronous computation that might\n   * fail.\n   *\n   * **When to Use**\n   *\n   * In situations where you need to perform synchronous operations that might\n   * fail, such as parsing JSON, you can use the `try` constructor. This\n   * constructor is designed to handle operations that could throw exceptions by\n   * capturing those exceptions and transforming them into manageable errors.\n   *\n   * **Error Handling**\n   *\n   * There are two ways to handle errors with `try`:\n   *\n   * 1. If you don't provide a `catch` function, the error is caught and the\n   *    effect fails with an `UnknownException`.\n   * 2. If you provide a `catch` function, the error is caught and the `catch`\n   *    function maps it to an error of type `E`.\n   *\n   * **Example** (Safe JSON Parsing)\n   *\n   * ```ts\n   * import { Effect } from \"effect\"\n   *\n   * const parse = (input: string) =>\n   *   // This might throw an error if input is not valid JSON\n   *   Effect.try(() => JSON.parse(input))\n   *\n   * //      ┌─── Effect<any, UnknownException, never>\n   * //      ▼\n   * const program = parse(\"\")\n   *\n   * ```\n   *\n   * **Example** (Custom Error Handling)\n   *\n   * ```ts\n   * import { Effect } from \"effect\"\n   *\n   * const parse = (input: string) =>\n   *   Effect.try({\n   *     // JSON.parse may throw for bad input\n   *     try: () => JSON.parse(input),\n   *     // remap the error\n   *     catch: (unknown) => new Error(`something went wrong ${unknown}`)\n   *   })\n   *\n   * //      ┌─── Effect<any, Error, never>\n   * //      ▼\n   * const program = parse(\"\")\n   * ```\n   *\n   * @see {@link sync} if the effectful computation is synchronous and does not\n   * throw errors.\n   *\n   * @since 2.0.0\n   * @category Creating Effects\n   */\n  try_ as try\n}\n\n/**\n * Returns an effect that maps its success using the specified side-effecting\n * `try` function, converting any errors into typed failed effects using the\n * `catch` function.\n *\n * @see {@link tryPromise} for a version that works with asynchronous computations.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const tryMap: {\n  <A, B, E1>(\n    options: { readonly try: (a: A) => B; readonly catch: (error: unknown) => E1 }\n  ): <E, R>(self: Effect<A, E, R>) => Effect<B, E1 | E, R>\n  <A, E, R, B, E1>(self: Effect<A, E, R>, options: {\n    readonly try: (a: A) => B\n    readonly catch: (error: unknown) => E1\n  }): Effect<B, E | E1, R>\n} = effect.tryMap\n\n/**\n * Returns an effect that maps its success using the specified side-effecting\n * `try` function, converting any promise rejections into typed failed effects\n * using the `catch` function.\n *\n * An optional `AbortSignal` can be provided to allow for interruption of the\n * wrapped `Promise` API.\n *\n * @see {@link tryMap} for a version that works with synchronous computations.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const tryMapPromise: {\n  <A, B, E1>(\n    options: { readonly try: (a: A, signal: AbortSignal) => PromiseLike<B>; readonly catch: (error: unknown) => E1 }\n  ): <E, R>(self: Effect<A, E, R>) => Effect<B, E1 | E, R>\n  <A, E, R, B, E1>(\n    self: Effect<A, E, R>,\n    options: { readonly try: (a: A, signal: AbortSignal) => PromiseLike<B>; readonly catch: (error: unknown) => E1 }\n  ): Effect<B, E | E1, R>\n} = effect.tryMapPromise\n\n/**\n * Creates an `Effect` that represents an asynchronous computation that might\n * fail.\n *\n * **When to Use**\n *\n * In situations where you need to perform asynchronous operations that might\n * fail, such as fetching data from an API, you can use the `tryPromise`\n * constructor. This constructor is designed to handle operations that could\n * throw exceptions by capturing those exceptions and transforming them into\n * manageable errors.\n *\n * **Error Handling**\n *\n * There are two ways to handle errors with `tryPromise`:\n *\n * 1. If you don't provide a `catch` function, the error is caught and the\n *    effect fails with an `UnknownException`.\n * 2. If you provide a `catch` function, the error is caught and the `catch`\n *    function maps it to an error of type `E`.\n *\n * **Interruptions**\n *\n * An optional `AbortSignal` can be provided to allow for interruption of the\n * wrapped `Promise` API.\n *\n * **Example** (Fetching a TODO Item)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const getTodo = (id: number) =>\n *   // Will catch any errors and propagate them as UnknownException\n *   Effect.tryPromise(() =>\n *     fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)\n *   )\n *\n * //      ┌─── Effect<Response, UnknownException, never>\n * //      ▼\n * const program = getTodo(1)\n * ```\n *\n * **Example** (Custom Error Handling)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const getTodo = (id: number) =>\n *   Effect.tryPromise({\n *     try: () => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`),\n *     // remap the error\n *     catch: (unknown) => new Error(`something went wrong ${unknown}`)\n *   })\n *\n * //      ┌─── Effect<Response, Error, never>\n * //      ▼\n * const program = getTodo(1)\n * ```\n *\n * @see {@link promise} if the effectful computation is asynchronous and does not throw errors.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const tryPromise: {\n  <A, E>(\n    options: {\n      readonly try: (signal: AbortSignal) => PromiseLike<A>\n      readonly catch: (error: unknown) => E\n    }\n  ): Effect<A, E>\n  <A>(evaluate: (signal: AbortSignal) => PromiseLike<A>): Effect<A, Cause.UnknownException>\n} = effect.tryPromise\n\n/**\n * The `unsandbox` function is used to revert an effect that has been\n * sandboxed by {@link sandbox}. When you apply `unsandbox`, the\n * effect's error channel is restored to its original state, without the\n * detailed `Cause<E>` information. This means that any underlying causes of\n * errors, defects, or fiber interruptions are no longer exposed in the error\n * channel.\n *\n * This function is useful when you want to remove the detailed error tracking\n * provided by `sandbox` and return to the standard error handling for\n * your effect. Once unsandboxed, the effect behaves as if `sandbox` was\n * never applied.\n *\n * @see {@link sandbox} to expose the full cause of failures, defects, or interruptions.\n *\n * @since 2.0.0\n * @category Error handling\n */\nexport const unsandbox: <A, E, R>(self: Effect<A, Cause.Cause<E>, R>) => Effect<A, E, R> = effect.unsandbox\n\n/**\n * Allows interruption of the current fiber, even in uninterruptible regions.\n *\n * **Details**\n *\n * This effect checks whether any other fibers are attempting to interrupt the\n * current fiber. If so, it allows the current fiber to perform a\n * self-interruption.\n *\n * **When to Use**\n *\n * This is useful in situations where you want to allow interruption to happen\n * even in regions of the code that are normally uninterruptible.\n *\n * @since 2.0.0\n * @category Interruption\n */\nexport const allowInterrupt: Effect<void> = effect.allowInterrupt\n\n/**\n * Checks if interruption is allowed and executes a callback accordingly.\n *\n * **Details**\n *\n * This function checks the current interrupt status of the running fiber. It\n * then calls the provided callback, passing a boolean indicating whether\n * interruption is allowed.\n *\n * **When to Use**\n *\n * This is useful for handling specific logic based on whether the current\n * operation can be interrupted, such as when performing asynchronous operations\n * or handling cancellation.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.checkInterruptible((isInterruptible) => {\n *     if (isInterruptible) {\n *       return Console.log(\"You can interrupt this operation.\")\n *     } else {\n *       return Console.log(\"This operation cannot be interrupted.\")\n *     }\n *   })\n * })\n *\n * Effect.runPromise(program)\n * // Output: You can interrupt this operation.\n *\n * Effect.runPromise(program.pipe(Effect.uninterruptible))\n * // Output: This operation cannot be interrupted.\n *\n * ```\n *\n *  @since 2.0.0\n * @category Interruption\n */\nexport const checkInterruptible: <A, E, R>(f: (isInterruptible: boolean) => Effect<A, E, R>) => Effect<A, E, R> =\n  core.checkInterruptible\n\n/**\n * Provides a way to handle timeouts in uninterruptible effects, allowing them\n * to continue in the background while the main control flow proceeds with the\n * timeout error.\n *\n * **Details**\n *\n * The `disconnect` function allows an uninterruptible effect to continue\n * running in the background, while enabling the main control flow to\n * immediately recognize a timeout condition. This is useful when you want to\n * avoid blocking the program due to long-running tasks, especially when those\n * tasks do not need to affect the flow of the rest of the program.\n *\n * Without `disconnect`, an uninterruptible effect will ignore the\n * timeout and continue executing until it completes. The timeout error will\n * only be assessed after the effect finishes, which can cause delays in\n * recognizing a timeout.\n *\n * With `disconnect`, the uninterruptible effect proceeds in the\n * background while the main program flow can immediately handle the timeout\n * error or trigger alternative logic. This enables faster timeout handling\n * without waiting for the completion of the long-running task.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const longRunningTask = Effect.gen(function* () {\n *   console.log(\"Start heavy processing...\")\n *   yield* Effect.sleep(\"5 seconds\") // Simulate a long process\n *   console.log(\"Heavy processing done.\")\n *   return \"Data processed\"\n * })\n *\n * const timedEffect = longRunningTask.pipe(\n *   Effect.uninterruptible,\n *   // Allows the task to finish in the background if it times out\n *   Effect.disconnect,\n *   Effect.timeout(\"1 second\")\n * )\n *\n * Effect.runPromiseExit(timedEffect).then(console.log)\n * // Output:\n * // Start heavy processing...\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Fail',\n * //     failure: { _tag: 'TimeoutException' }\n * //   }\n * // }\n * // Heavy processing done.\n * ```\n *\n * @see {@link timeout} for a version that interrupts the effect.\n * @see {@link uninterruptible} for creating an uninterruptible effect.\n *\n * @since 2.0.0\n * @category Interruption\n */\nexport const disconnect: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R> = fiberRuntime.disconnect\n\n/**\n * Represents an effect that interrupts the current fiber.\n *\n * **Details**\n *\n * This effect models the explicit interruption of the fiber in which it runs.\n * When executed, it causes the fiber to stop its operation immediately,\n * capturing the interruption details such as the fiber's ID and its start time.\n * The resulting interruption can be observed in the `Exit` type if the effect\n * is run with functions like {@link runPromiseExit}.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   console.log(\"start\")\n *   yield* Effect.sleep(\"2 seconds\")\n *   yield* Effect.interrupt\n *   console.log(\"done\")\n *   return \"some result\"\n * })\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // start\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Interrupt',\n * //     fiberId: {\n * //       _id: 'FiberId',\n * //       _tag: 'Runtime',\n * //       id: 0,\n * //       startTimeMillis: ...\n * //     }\n * //   }\n * // }\n * ```\n *\n * @since 2.0.0\n * @category Interruption\n */\nexport const interrupt: Effect<never> = core.interrupt\n\n/**\n * @since 2.0.0\n * @category Interruption\n */\nexport const interruptWith: (fiberId: FiberId.FiberId) => Effect<never> = core.interruptWith\n\n/**\n * Marks an effect as interruptible.\n *\n * @since 2.0.0\n * @category Interruption\n */\nexport const interruptible: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R> = core.interruptible\n\n/**\n * This function behaves like {@link interruptible}, but it also provides a\n * `restore` function. This function can be used to restore the interruptibility\n * of any specific region of code.\n *\n * @since 2.0.0\n * @category Interruption\n */\nexport const interruptibleMask: <A, E, R>(\n  f: (restore: <AX, EX, RX>(effect: Effect<AX, EX, RX>) => Effect<AX, EX, RX>) => Effect<A, E, R>\n) => Effect<A, E, R> = core.interruptibleMask\n\n/**\n * Registers a cleanup effect to run when an effect is interrupted.\n *\n * **Details**\n *\n * This function allows you to specify an effect to run when the fiber is\n * interrupted. This effect will be executed when the fiber is interrupted,\n * allowing you to perform cleanup or other actions.\n *\n * **Example** (Running a Cleanup Action on Interruption)\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * // This handler is executed when the fiber is interrupted\n * const handler = Effect.onInterrupt((_fibers) => Console.log(\"Cleanup completed\"))\n *\n * const success = Console.log(\"Task completed\").pipe(Effect.as(\"some result\"), handler)\n *\n * Effect.runFork(success)\n * // Output:\n * // Task completed\n *\n * const failure = Console.log(\"Task failed\").pipe(Effect.andThen(Effect.fail(\"some error\")), handler)\n *\n * Effect.runFork(failure)\n * // Output:\n * // Task failed\n *\n * const interruption = Console.log(\"Task interrupted\").pipe(Effect.andThen(Effect.interrupt), handler)\n *\n * Effect.runFork(interruption)\n * // Output:\n * // Task interrupted\n * // Cleanup completed\n * ```\n *\n * @since 2.0.0\n * @category Interruption\n */\nexport const onInterrupt: {\n  <X, R2>(\n    cleanup: (interruptors: HashSet.HashSet<FiberId.FiberId>) => Effect<X, never, R2>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R2 | R>\n  <A, E, R, X, R2>(\n    self: Effect<A, E, R>,\n    cleanup: (interruptors: HashSet.HashSet<FiberId.FiberId>) => Effect<X, never, R2>\n  ): Effect<A, E, R | R2>\n} = core.onInterrupt\n\n/**\n * Marks an effect as uninterruptible.\n *\n * @since 2.0.0\n * @category Interruption\n */\nexport const uninterruptible: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R> = core.uninterruptible\n\n/**\n * This function behaves like {@link uninterruptible}, but it also provides a\n * `restore` function. This function can be used to restore the interruptibility\n * of any specific region of code.\n *\n * @since 2.0.0\n * @category Interruption\n */\nexport const uninterruptibleMask: <A, E, R>(\n  f: (restore: <AX, EX, RX>(effect: Effect<AX, EX, RX>) => Effect<AX, EX, RX>) => Effect<A, E, R>\n) => Effect<A, E, R> = core.uninterruptibleMask\n\n/**\n * Transforms a `Predicate` function into an `Effect` returning the input value if the predicate returns `true`\n * or failing with specified error if the predicate fails\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const isPositive = (n: number): boolean => n > 0\n *\n * // succeeds with `1`\n * Effect.liftPredicate(1, isPositive, n => `${n} is not positive`)\n *\n * // fails with `\"0 is not positive\"`\n * Effect.liftPredicate(0, isPositive, n => `${n} is not positive`)\n * ```\n *\n * @category Condition Checking\n * @since 3.4.0\n */\nexport const liftPredicate: {\n  <T extends A, E, B extends T = T, A = T>(\n    predicate: Refinement<T, B> | Predicate<T>,\n    orFailWith: (a: EqualsWith<T, B, A, Exclude<A, B>>) => E\n  ): (a: A) => Effect<EqualsWith<T, B, A, B>, E>\n  <A, E, B extends A = A>(\n    self: A,\n    predicate: Refinement<A, B> | Predicate<A>,\n    orFailWith: (a: EqualsWith<A, B, A, Exclude<A, B>>) => E\n  ): Effect<B, E>\n} = effect.liftPredicate\n\n/**\n * Replaces the value inside an effect with a constant value.\n *\n * **Details**\n *\n * This function allows you to ignore the original value inside an effect and\n * replace it with a constant value.\n *\n * **When to Use**\n *\n * It is useful when you no longer need the value produced by an effect but want\n * to ensure that the effect completes successfully with a specific constant\n * result instead. For instance, you can replace the value produced by a\n * computation with a predefined value, ignoring what was calculated before.\n *\n * **Example** (Replacing a Value)\n *\n * ```ts\n * import { pipe, Effect } from \"effect\"\n *\n * // Replaces the value 5 with the constant \"new value\"\n * const program = pipe(Effect.succeed(5), Effect.as(\"new value\"))\n *\n * Effect.runPromise(program).then(console.log)\n * // Output: \"new value\"\n * ```\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const as: {\n  <B>(value: B): <A, E, R>(self: Effect<A, E, R>) => Effect<B, E, R>\n  <A, E, R, B>(self: Effect<A, E, R>, value: B): Effect<B, E, R>\n} = core.as\n\n/**\n * This function maps the success value of an `Effect` value to a `Some` value\n * in an `Option` value. If the original `Effect` value fails, the returned\n * `Effect` value will also fail.\n *\n * @category Mapping\n * @since 2.0.0\n */\nexport const asSome: <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E, R> = effect.asSome\n\n/**\n * This function maps the error value of an `Effect` value to a `Some` value\n * in an `Option` value. If the original `Effect` value succeeds, the returned\n * `Effect` value will also succeed.\n *\n * @category Mapping\n * @since 2.0.0\n */\nexport const asSomeError: <A, E, R>(self: Effect<A, E, R>) => Effect<A, Option.Option<E>, R> = effect.asSomeError\n\n/**\n * This function maps the success value of an `Effect` value to `void`. If the\n * original `Effect` value succeeds, the returned `Effect` value will also\n * succeed. If the original `Effect` value fails, the returned `Effect` value\n * will fail with the same error.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const asVoid: <A, E, R>(self: Effect<A, E, R>) => Effect<void, E, R> = core.asVoid\n\n/**\n * Swaps the success and error channels of an effect.\n *\n * **Details**\n *\n * This function reverses the flow of an effect by swapping its success and\n * error channels. The success value becomes an error, and the error value\n * becomes a success.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * //      ┌─── Effect<number, string, never>\n * //      ▼\n * const program = Effect.fail(\"Oh uh!\").pipe(Effect.as(2))\n *\n * //      ┌─── Effect<string, number, never>\n * //      ▼\n * const flipped = Effect.flip(program)\n * ```\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const flip: <A, E, R>(self: Effect<A, E, R>) => Effect<E, A, R> = core.flip\n\n/**\n * Swaps the error/value parameters, applies the function `f` and flips the\n * parameters back\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const flipWith: {\n  <E, A, R, E2, A2, R2>(\n    f: (effect: Effect<E, A, R>) => Effect<E2, A2, R2>\n  ): (self: Effect<A, E, R>) => Effect<A2, E2, R2>\n  <A, E, R, E2, A2, R2>(\n    self: Effect<A, E, R>,\n    f: (effect: Effect<E, A, R>) => Effect<E2, A2, R2>\n  ): Effect<A2, E2, R2>\n} = effect.flipWith\n\n/**\n * Transforms the value inside an effect by applying a function to it.\n *\n * **Syntax**\n *\n * ```ts skip-type-checking\n * const mappedEffect = pipe(myEffect, Effect.map(transformation))\n * // or\n * const mappedEffect = Effect.map(myEffect, transformation)\n * // or\n * const mappedEffect = myEffect.pipe(Effect.map(transformation))\n * ```\n *\n * **Details**\n *\n * `map` takes a function and applies it to the value contained within an\n * effect, creating a new effect with the transformed value.\n *\n * It's important to note that effects are immutable, meaning that the original\n * effect is not modified. Instead, a new effect is returned with the updated\n * value.\n *\n * **Example** (Adding a Service Charge)\n *\n * ```ts\n * import { pipe, Effect } from \"effect\"\n *\n * const addServiceCharge = (amount: number) => amount + 1\n *\n * const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))\n *\n * const finalAmount = pipe(\n *   fetchTransactionAmount,\n *   Effect.map(addServiceCharge)\n * )\n *\n * Effect.runPromise(finalAmount).then(console.log)\n * // Output: 101\n * ```\n *\n * @see {@link mapError} for a version that operates on the error channel.\n * @see {@link mapBoth} for a version that operates on both channels.\n * @see {@link flatMap} or {@link andThen} for a version that can return a new effect.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): <E, R>(self: Effect<A, E, R>) => Effect<B, E, R>\n  <A, E, R, B>(self: Effect<A, E, R>, f: (a: A) => B): Effect<B, E, R>\n} = core.map\n\n/**\n * Applies a stateful transformation to each element of a collection, producing\n * new elements along with an updated state.\n *\n * **When to Use**\n *\n * Use `mapAccum` when you need to process each element of a collection while\n * keeping track of some state across iterations.\n *\n * **Details**\n *\n * `mapAccum` takes an initial state (`initial`) and a function (`f`) that is\n * applied to each element. This function returns a new state and a transformed\n * element. The final effect produces both the accumulated state and the\n * transformed collection.\n *\n * If the input collection is a non-empty array, the return type will match the\n * input collection type.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * // Define an initial state and a transformation function\n * const initialState = 0\n *\n * const transformation = (state: number, element: string) =>\n *   Effect.succeed<[number, string]>([state + element.length, element.toUpperCase()])\n *\n * // Apply mapAccum to transform an array of strings\n * const program = Effect.mapAccum([\"a\", \"bb\", \"ccc\"], initialState, transformation)\n *\n * Effect.runPromise(program).then(([finalState, transformedCollection]) => {\n *   console.log(finalState)\n *   console.log(transformedCollection)\n * })\n * // Output:\n * // 6\n * // [ 'A', 'BB', 'CCC' ]\n * ```\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const mapAccum: {\n  <S, A, B, E, R, I extends Iterable<A> = Iterable<A>>(\n    initial: S,\n    f: (state: S, a: RA.ReadonlyArray.Infer<I>, i: number) => Effect<readonly [S, B], E, R>\n  ): (elements: I) => Effect<[S, RA.ReadonlyArray.With<I, B>], E, R>\n  <A, S, B, E, R, I extends Iterable<A> = Iterable<A>>(\n    elements: I,\n    initial: S,\n    f: (state: S, a: RA.ReadonlyArray.Infer<I>, i: number) => Effect<readonly [S, B], E, R>\n  ): Effect<[S, RA.ReadonlyArray.With<I, B>], E, R>\n} = effect.mapAccum\n\n/**\n * Applies transformations to both the success and error channels of an effect.\n *\n * **Details**\n *\n * This function takes two map functions as arguments: one for the error channel\n * and one for the success channel. You can use it when you want to modify both\n * the error and the success values without altering the overall success or\n * failure status of the effect.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * //      ┌─── Effect<number, string, never>\n * //      ▼\n * const simulatedTask = Effect.fail(\"Oh no!\").pipe(Effect.as(1))\n *\n * //      ┌─── Effect<boolean, Error, never>\n * //      ▼\n * const modified = Effect.mapBoth(simulatedTask, {\n *   onFailure: (message) => new Error(message),\n *   onSuccess: (n) => n > 0\n * })\n * ```\n *\n * @see {@link map} for a version that operates on the success channel.\n * @see {@link mapError} for a version that operates on the error channel.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const mapBoth: {\n  <E, E2, A, A2>(\n    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n  ): <R>(self: Effect<A, E, R>) => Effect<A2, E2, R>\n  <A, E, R, E2, A2>(\n    self: Effect<A, E, R>,\n    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n  ): Effect<A2, E2, R>\n} = core.mapBoth\n\n/**\n * Transforms or modifies the error produced by an effect without affecting its\n * success value.\n *\n * **When to Use**\n *\n * This function is helpful when you want to enhance the error with additional\n * information, change the error type, or apply custom error handling while\n * keeping the original behavior of the effect's success values intact. It only\n * operates on the error channel and leaves the success channel unchanged.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * //      ┌─── Effect<number, string, never>\n * //      ▼\n * const simulatedTask = Effect.fail(\"Oh no!\").pipe(Effect.as(1))\n *\n * //      ┌─── Effect<number, Error, never>\n * //      ▼\n * const mapped = Effect.mapError(\n *   simulatedTask,\n *   (message) => new Error(message)\n * )\n * ```\n *\n * @see {@link map} for a version that operates on the success channel.\n * @see {@link mapBoth} for a version that operates on both channels.\n * @see {@link orElseFail} if you want to replace the error with a new one.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const mapError: {\n  <E, E2>(f: (e: E) => E2): <A, R>(self: Effect<A, E, R>) => Effect<A, E2, R>\n  <A, E, R, E2>(self: Effect<A, E, R>, f: (e: E) => E2): Effect<A, E2, R>\n} = core.mapError\n\n/**\n * Maps the cause of failure of an effect using a specified function.\n *\n * @see {@link sandbox} for a version that exposes the full cause of failures, defects, or interruptions.\n * @see {@link catchAllCause} for a version that can recover from all types of defects.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const mapErrorCause: {\n  <E, E2>(f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): <A, R>(self: Effect<A, E, R>) => Effect<A, E2, R>\n  <A, E, R, E2>(self: Effect<A, E, R>, f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): Effect<A, E2, R>\n} = effect.mapErrorCause\n\n/**\n * Combines both success and error channels of an effect into a single outcome.\n *\n * **Details**\n *\n * This function transforms an effect that may fail into one that always returns\n * a value, where both success and failure outcomes are handled as values in the\n * success channel.\n *\n * **When to Use**\n *\n * This can be useful when you want to continue execution regardless of the\n * error type and still capture both successful results and errors as part of\n * the outcome.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * //      ┌─── Effect<number, string, never>\n * //      ▼\n * const program = Effect.fail(\"Oh uh!\").pipe(Effect.as(2))\n *\n * //      ┌─── Effect<number | string, never, never>\n * //      ▼\n * const recovered = Effect.merge(program)\n * ```\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const merge: <A, E, R>(self: Effect<A, E, R>) => Effect<E | A, never, R> = effect.merge\n\n/**\n * Returns a new effect with the boolean value of this effect negated.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const negate: <E, R>(self: Effect<boolean, E, R>) => Effect<boolean, E, R> = effect.negate\n\n/**\n * Creates a scoped resource using an `acquire` and `release` effect.\n *\n * **Details**\n *\n * This function helps manage resources by combining two `Effect` values: one\n * for acquiring the resource and one for releasing it.\n *\n * `acquireRelease` does the following:\n *\n *   1. Ensures that the effect that acquires the resource will not be\n *      interrupted. Note that acquisition may still fail due to internal\n *      reasons (such as an uncaught exception).\n *   2. Ensures that the `release` effect will not be interrupted, and will be\n *      executed as long as the acquisition effect successfully acquires the\n *      resource.\n *\n * If the `acquire` function succeeds, the `release` function is added to the\n * list of finalizers for the scope. This ensures that the release will happen\n * automatically when the scope is closed.\n *\n * Both `acquire` and `release` run uninterruptibly, meaning they cannot be\n * interrupted while they are executing.\n *\n * Additionally, the `release` function can be influenced by the exit value when\n * the scope closes, allowing for custom handling of how the resource is\n * released based on the execution outcome.\n *\n * **When to Use**\n *\n * This function is used to ensure that an effect that represents the\n * acquisition of a resource (for example, opening a file, launching a thread,\n * etc.) will not be interrupted, and that the resource will always be released\n * when the `Effect` completes execution.\n *\n * **Example** (Defining a Simple Resource)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * // Define an interface for a resource\n * interface MyResource {\n *   readonly contents: string\n *   readonly close: () => Promise<void>\n * }\n *\n * // Simulate resource acquisition\n * const getMyResource = (): Promise<MyResource> =>\n *   Promise.resolve({\n *     contents: \"lorem ipsum\",\n *     close: () =>\n *       new Promise((resolve) => {\n *         console.log(\"Resource released\")\n *         resolve()\n *       })\n *   })\n *\n * // Define how the resource is acquired\n * const acquire = Effect.tryPromise({\n *   try: () =>\n *     getMyResource().then((res) => {\n *       console.log(\"Resource acquired\")\n *       return res\n *     }),\n *   catch: () => new Error(\"getMyResourceError\")\n * })\n *\n * // Define how the resource is released\n * const release = (res: MyResource) => Effect.promise(() => res.close())\n *\n * // Create the resource management workflow\n * //\n * //      ┌─── Effect<MyResource, Error, Scope>\n * //      ▼\n * const resource = Effect.acquireRelease(acquire, release)\n * ```\n *\n * @see {@link acquireUseRelease} for a version that automatically handles the scoping of resources.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const acquireRelease: {\n  <A, X, R2>(\n    release: (a: A, exit: Exit.Exit<unknown, unknown>) => Effect<X, never, R2>\n  ): <E, R>(acquire: Effect<A, E, R>) => Effect<A, E, Scope.Scope | R2 | R>\n  <A, E, R, X, R2>(\n    acquire: Effect<A, E, R>,\n    release: (a: A, exit: Exit.Exit<unknown, unknown>) => Effect<X, never, R2>\n  ): Effect<A, E, Scope.Scope | R | R2>\n} = fiberRuntime.acquireRelease\n\n/**\n * Creates a scoped resource with an interruptible acquire action.\n *\n * **Details**\n *\n * This function is similar to {@link acquireRelease}, but it allows the\n * acquisition of the resource to be interrupted. The `acquire` effect, which\n * represents the process of obtaining the resource, can be interrupted if\n * necessary.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const acquireReleaseInterruptible: {\n  <X, R2>(\n    release: (exit: Exit.Exit<unknown, unknown>) => Effect<X, never, R2>\n  ): <A, E, R>(acquire: Effect<A, E, R>) => Effect<A, E, Scope.Scope | R2 | R>\n  <A, E, R, X, R2>(\n    acquire: Effect<A, E, R>,\n    release: (exit: Exit.Exit<unknown, unknown>) => Effect<X, never, R2>\n  ): Effect<A, E, Scope.Scope | R | R2>\n} = fiberRuntime.acquireReleaseInterruptible\n\n/**\n * Many real-world operations involve working with resources that must be released when no longer needed, such as:\n *\n * - Database connections\n * - File handles\n * - Network requests\n *\n * This function ensures that a resource is:\n *\n * 1. **Acquired** properly.\n * 2. **Used** for its intended purpose.\n * 3. **Released** even if an error occurs.\n *\n * **Example** (Automatically Managing Resource Lifetime)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * // Define an interface for a resource\n * interface MyResource {\n *   readonly contents: string\n *   readonly close: () => Promise<void>\n * }\n *\n * // Simulate resource acquisition\n * const getMyResource = (): Promise<MyResource> =>\n *   Promise.resolve({\n *     contents: \"lorem ipsum\",\n *     close: () =>\n *       new Promise((resolve) => {\n *         console.log(\"Resource released\")\n *         resolve()\n *       })\n *   })\n *\n * // Define how the resource is acquired\n * const acquire = Effect.tryPromise({\n *   try: () =>\n *     getMyResource().then((res) => {\n *       console.log(\"Resource acquired\")\n *       return res\n *     }),\n *   catch: () => new Error(\"getMyResourceError\")\n * })\n *\n * // Define how the resource is released\n * const release = (res: MyResource) => Effect.promise(() => res.close())\n *\n * const use = (res: MyResource) => Console.log(`content is ${res.contents}`)\n *\n * //      ┌─── Effect<void, Error, never>\n * //      ▼\n * const program = Effect.acquireUseRelease(acquire, use, release)\n *\n * Effect.runPromise(program)\n * // Output:\n * // Resource acquired\n * // content is lorem ipsum\n * // Resource released\n * ```\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const acquireUseRelease: {\n  <A2, E2, R2, A, X, R3>(\n    use: (a: A) => Effect<A2, E2, R2>,\n    release: (a: A, exit: Exit.Exit<A2, E2>) => Effect<X, never, R3>\n  ): <E, R>(acquire: Effect<A, E, R>) => Effect<A2, E2 | E, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, X, R3>(\n    acquire: Effect<A, E, R>,\n    use: (a: A) => Effect<A2, E2, R2>,\n    release: (a: A, exit: Exit.Exit<A2, E2>) => Effect<X, never, R3>\n  ): Effect<A2, E | E2, R | R2 | R3>\n} = core.acquireUseRelease\n\n/**\n * Ensures a finalizer is added to the scope of the calling effect, guaranteeing\n * it runs when the scope is closed.\n *\n * **Details**\n *\n * This function adds a finalizer that will execute whenever the scope of the\n * effect is closed, regardless of whether the effect succeeds, fails, or is\n * interrupted. The finalizer receives the `Exit` value of the effect's scope,\n * allowing it to react differently depending on how the effect concludes.\n *\n * Finalizers are a reliable way to manage resource cleanup, ensuring that\n * resources such as file handles, network connections, or database transactions\n * are properly closed even in the event of an unexpected interruption or error.\n *\n * Finalizers operate in conjunction with Effect's scoped resources. If an\n * effect with a finalizer is wrapped in a scope, the finalizer will execute\n * automatically when the scope ends.\n *\n * **Example** (Adding a Finalizer on Success)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * //      ┌─── Effect<string, never, Scope>\n * //      ▼\n * const program = Effect.gen(function* () {\n *   yield* Effect.addFinalizer((exit) =>\n *     Console.log(`Finalizer executed. Exit status: ${exit._tag}`)\n *   )\n *   return \"some result\"\n * })\n *\n * // Wrapping the effect in a scope\n * //\n * //      ┌─── Effect<string, never, never>\n * //      ▼\n * const runnable = Effect.scoped(program)\n *\n * Effect.runPromiseExit(runnable).then(console.log)\n * // Output:\n * // Finalizer executed. Exit status: Success\n * // { _id: 'Exit', _tag: 'Success', value: 'some result' }\n * ```\n *\n * **Example** (Adding a Finalizer on Failure)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * //      ┌─── Effect<never, string, Scope>\n * //      ▼\n * const program = Effect.gen(function* () {\n *   yield* Effect.addFinalizer((exit) =>\n *     Console.log(`Finalizer executed. Exit status: ${exit._tag}`)\n *   )\n *   return yield* Effect.fail(\"Uh oh!\")\n * })\n *\n * // Wrapping the effect in a scope\n * //\n * //      ┌─── Effect<never, string, never>\n * //      ▼\n * const runnable = Effect.scoped(program)\n *\n * Effect.runPromiseExit(runnable).then(console.log)\n * // Output:\n * // Finalizer executed. Exit status: Failure\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: { _id: 'Cause', _tag: 'Fail', failure: 'Uh oh!' }\n * // }\n * ```\n *\n * **Example** (Adding a Finalizer on Interruption)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * //      ┌─── Effect<never, never, Scope>\n * //      ▼\n * const program = Effect.gen(function* () {\n *   yield* Effect.addFinalizer((exit) =>\n *     Console.log(`Finalizer executed. Exit status: ${exit._tag}`)\n *   )\n *   return yield* Effect.interrupt\n * })\n *\n * // Wrapping the effect in a scope\n * //\n * //      ┌─── Effect<never, never, never>\n * //      ▼\n * const runnable = Effect.scoped(program)\n *\n * Effect.runPromiseExit(runnable).then(console.log)\n * // Output:\n * // Finalizer executed. Exit status: Failure\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Interrupt',\n * //     fiberId: {\n * //       _id: 'FiberId',\n * //       _tag: 'Runtime',\n * //       id: 0,\n * //       startTimeMillis: ...\n * //     }\n * //   }\n * // }\n * ```\n *\n * @see {@link onExit} for attaching a finalizer directly to an effect.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const addFinalizer: <X, R>(\n  finalizer: (exit: Exit.Exit<unknown, unknown>) => Effect<X, never, R>\n) => Effect<void, never, Scope.Scope | R> = fiberRuntime.addFinalizer\n\n/**\n * Guarantees the execution of a finalizer when an effect starts execution.\n *\n * **Details**\n *\n * This function allows you to specify a `finalizer` effect that will always be\n * run once the effect starts execution, regardless of whether the effect\n * succeeds, fails, or is interrupted.\n *\n * **When to Use**\n *\n * This is useful when you need to ensure that certain cleanup or final steps\n * are executed in all cases, such as releasing resources or performing\n * necessary logging.\n *\n * While this function provides strong guarantees about executing the finalizer,\n * it is considered a low-level tool, which may not be ideal for more complex\n * resource management. For higher-level resource management with automatic\n * acquisition and release, see the {@link acquireRelease} family of functions.\n * For use cases where you need access to the result of an effect, consider\n * using {@link onExit}.\n *\n * **Example** (Running a Finalizer in All Outcomes)\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * // Define a cleanup effect\n * const handler = Effect.ensuring(Console.log(\"Cleanup completed\"))\n *\n * // Define a successful effect\n * const success = Console.log(\"Task completed\").pipe(\n *   Effect.as(\"some result\"),\n *   handler\n * )\n *\n * Effect.runFork(success)\n * // Output:\n * // Task completed\n * // Cleanup completed\n *\n * // Define a failing effect\n * const failure = Console.log(\"Task failed\").pipe(\n *   Effect.andThen(Effect.fail(\"some error\")),\n *   handler\n * )\n *\n * Effect.runFork(failure)\n * // Output:\n * // Task failed\n * // Cleanup completed\n *\n * // Define an interrupted effect\n * const interruption = Console.log(\"Task interrupted\").pipe(\n *   Effect.andThen(Effect.interrupt),\n *   handler\n * )\n *\n * Effect.runFork(interruption)\n * // Output:\n * // Task interrupted\n * // Cleanup completed\n * ```\n *\n * @see {@link onExit} for a version that provides access to the result of an\n * effect.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const ensuring: {\n  <X, R1>(finalizer: Effect<X, never, R1>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R1 | R>\n  <A, E, R, X, R1>(self: Effect<A, E, R>, finalizer: Effect<X, never, R1>): Effect<A, E, R1 | R>\n} = fiberRuntime.ensuring\n\n/**\n * Ensures a cleanup effect runs whenever the calling effect fails, providing\n * the failure cause to the cleanup effect.\n *\n * **Details**\n *\n * This function allows you to attach a cleanup effect that runs whenever the\n * calling effect fails. The cleanup effect receives the cause of the failure,\n * allowing you to perform actions such as logging, releasing resources, or\n * executing additional recovery logic based on the error. The cleanup effect\n * will execute even if the failure is due to interruption.\n *\n * Importantly, the cleanup effect itself is uninterruptible, ensuring that it\n * completes regardless of external interruptions.\n *\n * **Example** (Running Cleanup Only on Failure)\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * // This handler logs the failure cause when the effect fails\n * const handler = Effect.onError((cause) =>\n *   Console.log(`Cleanup completed: ${cause}`)\n * )\n *\n * // Define a successful effect\n * const success = Console.log(\"Task completed\").pipe(\n *   Effect.as(\"some result\"),\n *   handler\n * )\n *\n * Effect.runFork(success)\n * // Output:\n * // Task completed\n *\n * // Define a failing effect\n * const failure = Console.log(\"Task failed\").pipe(\n *   Effect.andThen(Effect.fail(\"some error\")),\n *   handler\n * )\n *\n * Effect.runFork(failure)\n * // Output:\n * // Task failed\n * // Cleanup completed: Error: some error\n *\n * // Define a failing effect\n * const defect = Console.log(\"Task failed with defect\").pipe(\n *   Effect.andThen(Effect.die(\"Boom!\")),\n *   handler\n * )\n *\n * Effect.runFork(defect)\n * // Output:\n * // Task failed with defect\n * // Cleanup completed: Error: Boom!\n *\n * // Define an interrupted effect\n * const interruption = Console.log(\"Task interrupted\").pipe(\n *   Effect.andThen(Effect.interrupt),\n *   handler\n * )\n *\n * Effect.runFork(interruption)\n * // Output:\n * // Task interrupted\n * // Cleanup completed: All fibers interrupted without errors.\n * ```\n *\n * @see {@link ensuring} for attaching a cleanup effect that runs on both success and failure.\n * @see {@link onExit} for attaching a cleanup effect that runs on all possible exits.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const onError: {\n  <E, X, R2>(\n    cleanup: (cause: Cause.Cause<E>) => Effect<X, never, R2>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A, E, R2 | R>\n  <A, E, R, X, R2>(\n    self: Effect<A, E, R>,\n    cleanup: (cause: Cause.Cause<E>) => Effect<X, never, R2>\n  ): Effect<A, E, R2 | R>\n} = core.onError\n\n/**\n * Guarantees that a cleanup function runs regardless of whether the effect\n * succeeds, fails, or is interrupted.\n *\n * **Details**\n *\n * This function ensures that a provided cleanup function is executed after the\n * effect completes, regardless of the outcome. The cleanup function is given\n * the `Exit` value of the effect, which provides detailed information about the\n * result:\n * - If the effect succeeds, the `Exit` contains the success value.\n * - If the effect fails, the `Exit` contains the error or failure cause.\n * - If the effect is interrupted, the `Exit` reflects the interruption.\n *\n * The cleanup function is guaranteed to run uninterruptibly, ensuring reliable\n * resource management even in complex or high-concurrency scenarios.\n *\n * **Example** (Running a Cleanup Function with the Effect’s Result)\n *\n * ```ts\n * import { Console, Effect, Exit } from \"effect\"\n *\n * // Define a cleanup effect that logs the result\n * const handler = Effect.onExit((exit) =>\n *   Console.log(`Cleanup completed: ${Exit.getOrElse(exit, String)}`)\n * )\n *\n * // Define a successful effect\n * const success = Console.log(\"Task completed\").pipe(\n *   Effect.as(\"some result\"),\n *   handler\n * )\n *\n * Effect.runFork(success)\n * // Output:\n * // Task completed\n * // Cleanup completed: some result\n *\n * // Define a failing effect\n * const failure = Console.log(\"Task failed\").pipe(\n *   Effect.andThen(Effect.fail(\"some error\")),\n *   handler\n * )\n *\n * Effect.runFork(failure)\n * // Output:\n * // Task failed\n * // Cleanup completed: Error: some error\n *\n * // Define an interrupted effect\n * const interruption = Console.log(\"Task interrupted\").pipe(\n *   Effect.andThen(Effect.interrupt),\n *   handler\n * )\n *\n * Effect.runFork(interruption)\n * // Output:\n * // Task interrupted\n * // Cleanup completed: All fibers interrupted without errors.\n * ```\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const onExit: {\n  <A, E, X, R2>(\n    cleanup: (exit: Exit.Exit<A, E>) => Effect<X, never, R2>\n  ): <R>(self: Effect<A, E, R>) => Effect<A, E, R2 | R>\n  <A, E, R, X, R2>(\n    self: Effect<A, E, R>,\n    cleanup: (exit: Exit.Exit<A, E>) => Effect<X, never, R2>\n  ): Effect<A, E, R | R2>\n} = core.onExit\n\n/**\n * Ensures that finalizers are run concurrently when the scope of an effect is\n * closed.\n *\n * **Details**\n *\n * This function modifies the behavior of finalizers within a scoped workflow to\n * allow them to run concurrently when the scope is closed.\n *\n * By default, finalizers are executed sequentially in reverse order of their\n * addition, but this function changes that behavior to execute all finalizers\n * concurrently.\n *\n * **When to Use**\n *\n * Running finalizers concurrently can improve performance when multiple\n * independent cleanup tasks need to be performed. However, it requires that\n * these tasks do not depend on the order of execution or introduce race\n * conditions.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * // Define a program that adds multiple finalizers\n * const program = Effect.gen(function*() {\n *   yield* Effect.addFinalizer(() => Console.log(\"Finalizer 1 executed\").pipe(Effect.delay(\"300 millis\")))\n *   yield* Effect.addFinalizer(() => Console.log(\"Finalizer 2 executed\").pipe(Effect.delay(\"100 millis\")))\n *   yield* Effect.addFinalizer(() => Console.log(\"Finalizer 3 executed\").pipe(Effect.delay(\"200 millis\")))\n *   return \"some result\"\n * })\n *\n * // Modify the program to ensure finalizers run in parallel\n * const modified = program.pipe(Effect.parallelFinalizers)\n *\n * const runnable = Effect.scoped(modified)\n *\n * Effect.runFork(runnable)\n * // Output:\n * // Finalizer 2 executed\n * // Finalizer 3 executed\n * // Finalizer 1 executed\n * ```\n *\n * @see {@link sequentialFinalizers} for a version that ensures finalizers are run sequentially.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const parallelFinalizers: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R> = fiberRuntime.parallelFinalizers\n\n/**\n * Ensures that finalizers are run sequentially in reverse order of their\n * addition.\n *\n * **Details**\n *\n * This function modifies the behavior of finalizers within a scoped workflow to\n * ensure they are run sequentially in reverse order when the scope is closed.\n *\n * By default, finalizers are executed sequentially, so this only changes the\n * behavior if the scope is configured to run finalizers concurrently.\n *\n * @see {@link parallelFinalizers} for a version that ensures finalizers are run concurrently.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const sequentialFinalizers: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R> =\n  fiberRuntime.sequentialFinalizers\n\n/**\n * Applies a custom execution strategy to finalizers within a scoped workflow.\n *\n * **Details**\n *\n * This function allows you to control how finalizers are executed in a scope by\n * applying a specified `ExecutionStrategy`. The `strategy` can dictate whether\n * finalizers run (e.g., sequentially or in parallel).\n *\n * Additionally, the function provides a `restore` operation, which ensures that\n * the effect passed to it is executed under the default execution strategy.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const finalizersMask: (\n  strategy: ExecutionStrategy\n) => <A, E, R>(\n  self: (restore: <A1, E1, R1>(self: Effect<A1, E1, R1>) => Effect<A1, E1, R1>) => Effect<A, E, R>\n) => Effect<A, E, R> = fiberRuntime.finalizersMask\n\n/**\n * Provides access to the current scope in a scoped workflow.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const scope: Effect<Scope.Scope, never, Scope.Scope> = fiberRuntime.scope\n\n/**\n * Accesses the current scope and uses it to perform the specified effect.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const scopeWith: <A, E, R>(f: (scope: Scope.Scope) => Effect<A, E, R>) => Effect<A, E, R | Scope.Scope> =\n  fiberRuntime.scopeWith\n\n/**\n * Creates a `Scope`, passes it to the specified effectful function, and closes\n * the scope when the effect completes (whether through success, failure, or\n * interruption).\n *\n * @since 3.11.0\n * @category Scoping, Resources & Finalization\n */\nexport const scopedWith: <A, E, R>(f: (scope: Scope.Scope) => Effect<A, E, R>) => Effect<A, E, R> =\n  fiberRuntime.scopedWith\n\n/**\n * Scopes all resources used in an effect to the lifetime of the effect.\n *\n * **Details**\n *\n * This function ensures that all resources used within an effect are tied to\n * its lifetime. Finalizers for these resources are executed automatically when\n * the effect completes, whether through success, failure, or interruption. This\n * guarantees proper resource cleanup without requiring explicit management.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const scoped: <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, Exclude<R, Scope.Scope>> =\n  fiberRuntime.scopedEffect\n\n/**\n * Scopes all resources acquired by one effect to the lifetime of another\n * effect.\n *\n * **Details**\n *\n * This function allows you to scope the resources acquired by one effect\n * (`self`) to the lifetime of another effect (`use`). This ensures that the\n * resources are cleaned up as soon as the `use` effect completes, regardless of\n * how the `use` effect ends (success, failure, or interruption).\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const acquire = Console.log(\"Acquiring resource\").pipe(\n *   Effect.as(1),\n *   Effect.tap(Effect.addFinalizer(() => Console.log(\"Releasing resource\")))\n * )\n * const use = (resource: number) => Console.log(`Using resource: ${resource}`)\n *\n * const program = acquire.pipe(Effect.using(use))\n *\n * Effect.runFork(program)\n * // Output:\n * // Acquiring resource\n * // Using resource: 1\n * // Releasing resource\n * ```\n *\n * @see {@link scopedWith} Manage scoped operations with a temporary scope.\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const using: {\n  <A, A2, E2, R2>(\n    use: (a: A) => Effect<A2, E2, R2>\n  ): <E, R>(self: Effect<A, E, R>) => Effect<A2, E2 | E, R2 | Exclude<R, Scope.Scope>>\n  <A, E, R, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    use: (a: A) => Effect<A2, E2, R2>\n  ): Effect<A2, E | E2, R2 | Exclude<R, Scope.Scope>>\n} = fiberRuntime.using\n\n/**\n * Returns the result of the effect and a finalizer to close its scope.\n *\n * **Details**\n *\n * This function allows you to retrieve both the result of an effect and a\n * finalizer that can be used to manually close its scope. This is useful for\n * workflows where you need early access to the result while retaining control\n * over the resource cleanup process.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const acquire = Console.log(\"Acquiring resource\").pipe(\n *   Effect.as(1),\n *   Effect.tap(Effect.addFinalizer(() => Console.log(\"Releasing resource\")))\n * )\n * const program = Effect.gen(function*() {\n *   const [finalizer, resource] = yield* Effect.withEarlyRelease(acquire)\n *   console.log(`Using resource: ${resource}`)\n *   yield* Effect.sleep(\"1 second\")\n *   yield* finalizer\n * })\n *\n * Effect.runFork(program.pipe(Effect.scoped))\n * // Output:\n * // Acquiring resource\n * // Using resource: 1\n * // Releasing resource\n * ```\n *\n * @since 2.0.0\n * @category Scoping, Resources & Finalization\n */\nexport const withEarlyRelease: <A, E, R>(\n  self: Effect<A, E, R>\n) => Effect<[finalizer: Effect<void>, result: A], E, R | Scope.Scope> = fiberRuntime.withEarlyRelease\n\n/**\n * Returns a new effect that will not succeed with its value before first\n * waiting for the end of all child fibers forked by the effect.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const awaitAllChildren: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R> = circular.awaitAllChildren\n\n/**\n * Returns a new workflow that will not supervise any fibers forked by this\n * workflow.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const daemonChildren: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R> = fiberRuntime.daemonChildren\n\n/**\n * Constructs an effect with information about the current `Fiber`.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const descriptor: Effect<Fiber.Fiber.Descriptor> = effect.descriptor\n\n/**\n * Constructs an effect based on information about the current `Fiber`.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const descriptorWith: <A, E, R>(f: (descriptor: Fiber.Fiber.Descriptor) => Effect<A, E, R>) => Effect<A, E, R> =\n  effect.descriptorWith\n\n/**\n * Returns a new workflow that executes this one and captures the changes in\n * `FiberRef` values.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const diffFiberRefs: <A, E, R>(\n  self: Effect<A, E, R>\n) => Effect<[FiberRefsPatch.FiberRefsPatch, A], E, R> = effect.diffFiberRefs\n\n/**\n * Acts on the children of this fiber (collected into a single fiber),\n * guaranteeing the specified callback will be invoked, whether or not this\n * effect succeeds.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const ensuringChild: {\n  <X, R2>(\n    f: (fiber: Fiber.Fiber<ReadonlyArray<unknown>, any>) => Effect<X, never, R2>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R2 | R>\n  <A, E, R, X, R2>(\n    self: Effect<A, E, R>,\n    f: (fiber: Fiber.Fiber<ReadonlyArray<unknown>, any>) => Effect<X, never, R2>\n  ): Effect<A, E, R | R2>\n} = circular.ensuringChild\n\n/**\n * Acts on the children of this fiber, guaranteeing the specified callback\n * will be invoked, whether or not this effect succeeds.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const ensuringChildren: {\n  <X, R2>(\n    children: (fibers: ReadonlyArray<Fiber.RuntimeFiber<any, any>>) => Effect<X, never, R2>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R2 | R>\n  <A, E, R, X, R2>(\n    self: Effect<A, E, R>,\n    children: (fibers: ReadonlyArray<Fiber.RuntimeFiber<any, any>>) => Effect<X, never, R2>\n  ): Effect<A, E, R | R2>\n} = circular.ensuringChildren\n\n/**\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const fiberId: Effect<FiberId.FiberId> = core.fiberId\n\n/**\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const fiberIdWith: <A, E, R>(f: (descriptor: FiberId.Runtime) => Effect<A, E, R>) => Effect<A, E, R> =\n  core.fiberIdWith\n\n/**\n * Creates a new fiber to run an effect concurrently.\n *\n * **Details**\n *\n * This function takes an effect and forks it into a separate fiber, allowing it\n * to run concurrently without blocking the original effect. The new fiber\n * starts execution immediately after being created, and the fiber object is\n * returned immediately without waiting for the effect to begin. This is useful\n * when you want to run tasks concurrently while continuing other tasks in the\n * parent fiber.\n *\n * The forked fiber is attached to the parent fiber's scope. This means that\n * when the parent fiber terminates, the child fiber will also be terminated\n * automatically. This feature, known as \"auto supervision,\" ensures that no\n * fibers are left running unintentionally. If you prefer not to have this auto\n * supervision behavior, you can use {@link forkDaemon} or {@link forkIn}.\n *\n * **When to Use**\n *\n * Use this function when you need to run an effect concurrently without\n * blocking the current execution flow. For example, you might use it to launch\n * background tasks or concurrent computations. However, working with fibers can\n * be complex, so before using this function directly, you might want to explore\n * higher-level functions like {@link raceWith}, {@link zip}, or others that can\n * manage concurrency for you.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const fib = (n: number): Effect.Effect<number> =>\n *   n < 2\n *     ? Effect.succeed(n)\n *     : Effect.zipWith(fib(n - 1), fib(n - 2), (a, b) => a + b)\n *\n * //      ┌─── Effect<RuntimeFiber<number, never>, never, never>\n * //      ▼\n * const fib10Fiber = Effect.fork(fib(10))\n * ```\n *\n * @see {@link forkWithErrorHandler} for a version that allows you to handle errors.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const fork: <A, E, R>(self: Effect<A, E, R>) => Effect<Fiber.RuntimeFiber<A, E>, never, R> = fiberRuntime.fork\n\n/**\n * Creates a long-running background fiber that is independent of its parent.\n *\n * **Details**\n *\n * This function creates a \"daemon\" fiber that runs in the background and is not\n * tied to the lifecycle of its parent fiber. Unlike normal fibers that stop\n * when the parent fiber terminates, a daemon fiber will continue running until\n * the global scope closes or the fiber completes naturally. This makes it\n * useful for tasks that need to run in the background independently, such as\n * periodic logging, monitoring, or background data processing.\n *\n * **Example** (Creating a Daemon Fiber)\n *\n * ```ts\n * import { Effect, Console, Schedule } from \"effect\"\n *\n * // Daemon fiber that logs a message repeatedly every second\n * const daemon = Effect.repeat(\n *   Console.log(\"daemon: still running!\"),\n *   Schedule.fixed(\"1 second\")\n * )\n *\n * const parent = Effect.gen(function* () {\n *   console.log(\"parent: started!\")\n *   // Daemon fiber running independently\n *   yield* Effect.forkDaemon(daemon)\n *   yield* Effect.sleep(\"3 seconds\")\n *   console.log(\"parent: finished!\")\n * })\n *\n * Effect.runFork(parent)\n * // Output:\n * // parent: started!\n * // daemon: still running!\n * // daemon: still running!\n * // daemon: still running!\n * // parent: finished!\n * // daemon: still running!\n * // daemon: still running!\n * // daemon: still running!\n * // daemon: still running!\n * // daemon: still running!\n * // ...etc...\n * ```\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const forkDaemon: <A, E, R>(self: Effect<A, E, R>) => Effect<Fiber.RuntimeFiber<A, E>, never, R> =\n  fiberRuntime.forkDaemon\n\n/**\n * Returns an effect that forks all of the specified values, and returns a\n * composite fiber that produces a list of their results, in order.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const forkAll: {\n  (\n    options?: { readonly discard?: false | undefined } | undefined\n  ): <Eff extends Effect<any, any, any>>(\n    effects: Iterable<Eff>\n  ) => Effect<Fiber.Fiber<Array<Effect.Success<Eff>>, Effect.Error<Eff>>, never, Effect.Context<Eff>>\n  (\n    options: { readonly discard: true }\n  ): <Eff extends Effect<any, any, any>>(effects: Iterable<Eff>) => Effect<void, never, Effect.Context<Eff>>\n  <Eff extends Effect<any, any, any>>(\n    effects: Iterable<Eff>,\n    options?: { readonly discard?: false | undefined } | undefined\n  ): Effect<Fiber.Fiber<Array<Effect.Success<Eff>>, Effect.Error<Eff>>, never, Effect.Context<Eff>>\n  <Eff extends Effect<any, any, any>>(\n    effects: Iterable<Eff>,\n    options: { readonly discard: true }\n  ): Effect<void, never, Effect.Context<Eff>>\n} = circular.forkAll\n\n/**\n * Forks an effect in a specific scope, allowing finer control over its\n * execution.\n *\n * **Details**\n *\n * There are some cases where we need more fine-grained control, so we want to\n * fork a fiber in a specific scope. We can use the `Effect.forkIn` operator\n * which takes the target scope as an argument.\n *\n * The fiber will be interrupted when the scope is closed.\n *\n * **Example** (Forking a Fiber in a Specific Scope)\n *\n * In this example, the child fiber is forked into the outerScope,\n * allowing it to outlive the inner scope but still be terminated\n * when the outerScope is closed.\n *\n * ```ts\n * import { Console, Effect, Schedule } from \"effect\"\n *\n * // Child fiber that logs a message repeatedly every second\n * const child = Effect.repeat(\n *   Console.log(\"child: still running!\"),\n *   Schedule.fixed(\"1 second\")\n * )\n *\n * const program = Effect.scoped(\n *   Effect.gen(function* () {\n *     yield* Effect.addFinalizer(() =>\n *       Console.log(\"The outer scope is about to be closed!\")\n *     )\n *\n *     // Capture the outer scope\n *     const outerScope = yield* Effect.scope\n *\n *     // Create an inner scope\n *     yield* Effect.scoped(\n *       Effect.gen(function* () {\n *         yield* Effect.addFinalizer(() =>\n *           Console.log(\"The inner scope is about to be closed!\")\n *         )\n *         // Fork the child fiber in the outer scope\n *         yield* Effect.forkIn(child, outerScope)\n *         yield* Effect.sleep(\"3 seconds\")\n *       })\n *     )\n *\n *     yield* Effect.sleep(\"5 seconds\")\n *   })\n * )\n *\n * Effect.runFork(program)\n * // Output:\n * // child: still running!\n * // child: still running!\n * // child: still running!\n * // The inner scope is about to be closed!\n * // child: still running!\n * // child: still running!\n * // child: still running!\n * // child: still running!\n * // child: still running!\n * // child: still running!\n * // The outer scope is about to be closed!\n * ```\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const forkIn: {\n  (scope: Scope.Scope): <A, E, R>(self: Effect<A, E, R>) => Effect<Fiber.RuntimeFiber<A, E>, never, R>\n  <A, E, R>(self: Effect<A, E, R>, scope: Scope.Scope): Effect<Fiber.RuntimeFiber<A, E>, never, R>\n} = circular.forkIn\n\n/**\n * Forks a fiber in a local scope, ensuring it outlives its parent.\n *\n * **Details**\n *\n * This function is used to create fibers that are tied to a local scope,\n * meaning they are not dependent on their parent fiber's lifecycle. Instead,\n * they will continue running until the scope they were created in is closed.\n * This is particularly useful when you need a fiber to run independently of the\n * parent fiber, but still want it to be terminated when the scope ends.\n *\n * Fibers created with this function are isolated from the parent fiber’s\n * termination, so they can run for a longer period. This behavior is different\n * from fibers created with {@link fork}, which are terminated when the parent fiber\n * terminates. With `forkScoped`, the child fiber will keep running until the\n * local scope ends, regardless of the state of the parent fiber.\n *\n * **Example** (Forking a Fiber in a Local Scope)\n *\n * In this example, the child fiber continues to run beyond the lifetime of the parent fiber.\n * The child fiber is tied to the local scope and will be terminated only when the scope ends.\n *\n * ```ts\n * import { Effect, Console, Schedule } from \"effect\"\n *\n * // Child fiber that logs a message repeatedly every second\n * const child = Effect.repeat(\n *   Console.log(\"child: still running!\"),\n *   Schedule.fixed(\"1 second\")\n * )\n *\n * //      ┌─── Effect<void, never, Scope>\n * //      ▼\n * const parent = Effect.gen(function* () {\n *   console.log(\"parent: started!\")\n *   // Child fiber attached to local scope\n *   yield* Effect.forkScoped(child)\n *   yield* Effect.sleep(\"3 seconds\")\n *   console.log(\"parent: finished!\")\n * })\n *\n * // Program runs within a local scope\n * const program = Effect.scoped(\n *   Effect.gen(function* () {\n *     console.log(\"Local scope started!\")\n *     yield* Effect.fork(parent)\n *     // Scope lasts for 5 seconds\n *     yield* Effect.sleep(\"5 seconds\")\n *     console.log(\"Leaving the local scope!\")\n *   })\n * )\n *\n * Effect.runFork(program)\n * // Output:\n * // Local scope started!\n * // parent: started!\n * // child: still running!\n * // child: still running!\n * // child: still running!\n * // parent: finished!\n * // child: still running!\n * // child: still running!\n * // Leaving the local scope!\n * ```\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const forkScoped: <A, E, R>(self: Effect<A, E, R>) => Effect<Fiber.RuntimeFiber<A, E>, never, Scope.Scope | R> =\n  circular.forkScoped\n\n/**\n * Like {@link fork} but handles an error with the provided handler.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const forkWithErrorHandler: {\n  <E, X>(\n    handler: (e: E) => Effect<X>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<Fiber.RuntimeFiber<A, E>, never, R>\n  <A, E, R, X>(\n    self: Effect<A, E, R>,\n    handler: (e: E) => Effect<X>\n  ): Effect<Fiber.RuntimeFiber<A, E>, never, R>\n} = fiberRuntime.forkWithErrorHandler\n\n/**\n * Creates an `Effect` value that represents the exit value of the specified\n * fiber.\n *\n * @see {@link fromFiberEffect} for creating an effect from a fiber obtained from an effect.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const fromFiber: <A, E>(fiber: Fiber.Fiber<A, E>) => Effect<A, E> = circular.fromFiber\n\n/**\n * Creates an `Effect` value that represents the exit value of a fiber obtained\n * from an effect.\n *\n * @see {@link fromFiber} for creating an effect from a fiber.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const fromFiberEffect: <A, E, R>(fiber: Effect<Fiber.Fiber<A, E>, E, R>) => Effect<A, E, R> =\n  circular.fromFiberEffect\n\n/**\n * Supervises child fibers by reporting them to a specified supervisor.\n *\n * **Details**\n *\n * This function takes a supervisor as an argument and returns an effect where\n * all child fibers forked within it are supervised by the provided supervisor.\n * This enables you to capture detailed information about these child fibers,\n * such as their status, through the supervisor.\n *\n * **Example** (Monitoring Fiber Count)\n *\n * ```ts\n * import { Effect, Supervisor, Schedule, Fiber, FiberStatus } from \"effect\"\n *\n * // Main program that monitors fibers while calculating a Fibonacci number\n * const program = Effect.gen(function* () {\n *   // Create a supervisor to track child fibers\n *   const supervisor = yield* Supervisor.track\n *\n *   // Start a Fibonacci calculation, supervised by the supervisor\n *   const fibFiber = yield* fib(20).pipe(\n *     Effect.supervised(supervisor),\n *     // Fork the Fibonacci effect into a fiber\n *     Effect.fork\n *   )\n *\n *   // Define a schedule to periodically monitor the fiber count every 500ms\n *   const policy = Schedule.spaced(\"500 millis\").pipe(\n *     Schedule.whileInputEffect((_) =>\n *       Fiber.status(fibFiber).pipe(\n *         // Continue while the Fibonacci fiber is not done\n *         Effect.andThen((status) => status !== FiberStatus.done)\n *       )\n *     )\n *   )\n *\n *   // Start monitoring the fibers, using the supervisor to track the count\n *   const monitorFiber = yield* monitorFibers(supervisor).pipe(\n *     // Repeat the monitoring according to the schedule\n *     Effect.repeat(policy),\n *     // Fork the monitoring into its own fiber\n *     Effect.fork\n *   )\n *\n *   // Join the monitor and Fibonacci fibers to ensure they complete\n *   yield* Fiber.join(monitorFiber)\n *   const result = yield* Fiber.join(fibFiber)\n *\n *   console.log(`fibonacci result: ${result}`)\n * })\n *\n * // Function to monitor and log the number of active fibers\n * const monitorFibers = (\n *   supervisor: Supervisor.Supervisor<Array<Fiber.RuntimeFiber<any, any>>>\n * ): Effect.Effect<void> =>\n *   Effect.gen(function* () {\n *     const fibers = yield* supervisor.value // Get the current set of fibers\n *     console.log(`number of fibers: ${fibers.length}`)\n *   })\n *\n * // Recursive Fibonacci calculation, spawning fibers for each recursive step\n * const fib = (n: number): Effect.Effect<number> =>\n *   Effect.gen(function* () {\n *     if (n <= 1) {\n *       return 1\n *     }\n *     yield* Effect.sleep(\"500 millis\") // Simulate work by delaying\n *\n *     // Fork two fibers for the recursive Fibonacci calls\n *     const fiber1 = yield* Effect.fork(fib(n - 2))\n *     const fiber2 = yield* Effect.fork(fib(n - 1))\n *\n *     // Join the fibers to retrieve their results\n *     const v1 = yield* Fiber.join(fiber1)\n *     const v2 = yield* Fiber.join(fiber2)\n *\n *     return v1 + v2 // Combine the results\n *   })\n *\n * Effect.runPromise(program)\n * // Output:\n * // number of fibers: 0\n * // number of fibers: 2\n * // number of fibers: 6\n * // number of fibers: 14\n * // number of fibers: 30\n * // number of fibers: 62\n * // number of fibers: 126\n * // number of fibers: 254\n * // number of fibers: 510\n * // number of fibers: 1022\n * // number of fibers: 2034\n * // number of fibers: 3795\n * // number of fibers: 5810\n * // number of fibers: 6474\n * // number of fibers: 4942\n * // number of fibers: 2515\n * // number of fibers: 832\n * // number of fibers: 170\n * // number of fibers: 18\n * // number of fibers: 0\n * // fibonacci result: 10946\n * ```\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const supervised: {\n  <X>(supervisor: Supervisor.Supervisor<X>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R, X>(self: Effect<A, E, R>, supervisor: Supervisor.Supervisor<X>): Effect<A, E, R>\n} = circular.supervised\n\n/**\n * Transplants specified effects so that when those effects fork other\n * effects, the forked effects will be governed by the scope of the fiber that\n * executes this effect.\n *\n * This can be used to \"graft\" deep grandchildren onto a higher-level scope,\n * effectively extending their lifespans into the parent scope.\n *\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const transplant: <A, E, R>(\n  f: (grafter: <A2, E2, R2>(effect: Effect<A2, E2, R2>) => Effect<A2, E2, R2>) => Effect<A, E, R>\n) => Effect<A, E, R> = core.transplant\n\n/**\n * @since 2.0.0\n * @category Supervision & Fibers\n */\nexport const withConcurrency: {\n  (concurrency: number | \"unbounded\"): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, concurrency: number | \"unbounded\"): Effect<A, E, R>\n} = core.withConcurrency\n\n/**\n * Sets the provided scheduler for usage in the wrapped effect\n *\n * @since 2.0.0\n * @category Scheduler\n */\nexport const withScheduler: {\n  (scheduler: Scheduler.Scheduler): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, scheduler: Scheduler.Scheduler): Effect<A, E, R>\n} = Scheduler.withScheduler\n\n/**\n * Sets the scheduling priority used when yielding\n *\n * @since 2.0.0\n * @category Scheduler\n */\nexport const withSchedulingPriority: {\n  (priority: number): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, priority: number): Effect<A, E, R>\n} = core.withSchedulingPriority\n\n/**\n * Sets the maximum number of operations before yield by the default schedulers\n *\n * @since 2.0.0\n * @category Scheduler\n */\nexport const withMaxOpsBeforeYield: {\n  (priority: number): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, priority: number): Effect<A, E, R>\n} = core.withMaxOpsBeforeYield\n\n/**\n * Retrieves the `Clock` service from the context.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const clock = yield* Effect.clock\n *   const currentTime = yield* clock.currentTimeMillis\n *   console.log(`Current time in milliseconds: ${currentTime}`)\n * })\n *\n * Effect.runFork(program)\n * // Example Output:\n * // Current time in milliseconds: 1735484796134\n * ```\n *\n * @since 2.0.0\n * @category Clock\n */\nexport const clock: Effect<Clock.Clock> = effect.clock\n\n/**\n * Retrieves the `Clock` service from the context and provides it to the\n * specified effectful function.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const program = Effect.clockWith((clock) =>\n *   clock.currentTimeMillis.pipe(\n *     Effect.map((currentTime) => `Current time is: ${currentTime}`),\n *     Effect.tap(Console.log)\n *   )\n * )\n *\n * Effect.runFork(program)\n * // Example Output:\n * // Current time is: 1735484929744\n * ```\n *\n * @since 2.0.0\n * @category Clock\n */\nexport const clockWith: <A, E, R>(f: (clock: Clock.Clock) => Effect<A, E, R>) => Effect<A, E, R> = effect.clockWith\n\n/**\n * Sets the implementation of the `Clock` service to the specified value and\n * restores it to its original value when the scope is closed.\n *\n * @since 2.0.0\n * @category Clock\n */\nexport const withClockScoped: <C extends Clock.Clock>(clock: C) => Effect<void, never, Scope.Scope> =\n  fiberRuntime.withClockScoped\n\n/**\n * Executes the specified workflow with the specified implementation of the\n * `Clock` service.\n *\n * @since 2.0.0\n * @category Clock\n */\nexport const withClock: {\n  <C extends Clock.Clock>(clock: C): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <C extends Clock.Clock, A, E, R>(effect: Effect<A, E, R>, clock: C): Effect<A, E, R>\n} = defaultServices.withClock\n\n/**\n * Retreives the `Console` service from the context\n *\n * @since 2.0.0\n * @category Console\n */\nexport const console: Effect<Console> = console_.console\n\n/**\n * Retreives the `Console` service from the context and provides it to the\n * specified effectful function.\n *\n * @since 2.0.0\n * @category Console\n */\nexport const consoleWith: <A, E, R>(f: (console: Console) => Effect<A, E, R>) => Effect<A, E, R> = console_.consoleWith\n\n/**\n * Sets the implementation of the console service to the specified value and\n * restores it to its original value when the scope is closed.\n *\n * @since 2.0.0\n * @category Creating Effects\n */\nexport const withConsoleScoped: <A extends Console>(console: A) => Effect<void, never, Scope.Scope> =\n  console_.withConsoleScoped\n\n/**\n * Executes the specified workflow with the specified implementation of the\n * console service.\n *\n * @since 2.0.0\n * @category Console\n */\nexport const withConsole: {\n  <C extends Console>(console: C): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R, C extends Console>(effect: Effect<A, E, R>, console: C): Effect<A, E, R>\n} = console_.withConsole\n\n/**\n * Delays the execution of an effect by a specified `Duration`.\n *\n * **Details\n *\n * This function postpones the execution of the provided effect by the specified\n * duration. The duration can be provided in various formats supported by the\n * `Duration` module.\n *\n * Internally, this function does not block the thread; instead, it uses an\n * efficient, non-blocking mechanism to introduce the delay.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const task = Console.log(\"Task executed\")\n *\n * const program = Console.log(\"start\").pipe(\n *   Effect.andThen(\n *     // Delays the log message by 2 seconds\n *     task.pipe(Effect.delay(\"2 seconds\"))\n *   )\n * )\n *\n * Effect.runFork(program)\n * // Output:\n * // start\n * // Task executed\n * ```\n *\n * @since 2.0.0\n * @category Delays & Timeouts\n */\nexport const delay: {\n  (duration: Duration.DurationInput): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, duration: Duration.DurationInput): Effect<A, E, R>\n} = effect.delay\n\n/**\n * Suspends the execution of an effect for a specified `Duration`.\n *\n * **Details**\n *\n * This function pauses the execution of an effect for a given duration. It is\n * asynchronous, meaning that it does not block the fiber executing the effect.\n * Instead, the fiber is suspended during the delay period and can resume once\n * the specified time has passed.\n *\n * The duration can be specified using various formats supported by the\n * `Duration` module, such as a string (`\"2 seconds\"`) or numeric value\n * representing milliseconds.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   console.log(\"Starting task...\")\n *   yield* Effect.sleep(\"3 seconds\") // Waits for 3 seconds\n *   console.log(\"Task completed!\")\n * })\n *\n * Effect.runFork(program)\n * // Output:\n * // Starting task...\n * // Task completed!\n * ```\n *\n * @since 2.0.0\n * @category Delays & Timeouts\n */\nexport const sleep: (duration: Duration.DurationInput) => Effect<void> = effect.sleep\n\n/**\n * Executes an effect and measures the time it takes to complete.\n *\n * **Details**\n *\n * This function wraps the provided effect and returns a new effect that, when\n * executed, performs the original effect and calculates its execution duration.\n *\n * The result of the new effect includes both the execution time (as a\n * `Duration`) and the original effect's result. This is useful for monitoring\n * performance or gaining insights into the time taken by specific operations.\n *\n * The original effect's behavior (success, failure, or interruption) remains\n * unchanged, and the timing information is provided alongside the result in a\n * tuple.\n *\n * **Example**\n *\n * ```ts\n * import { Duration, Effect } from \"effect\"\n *\n * const task = Effect.gen(function*() {\n *   yield* Effect.sleep(\"2 seconds\") // Simulates some work\n *   return \"some result\"\n * })\n *\n * const timedTask = task.pipe(Effect.timed)\n *\n * const program = Effect.gen(function*() {\n *   const [duration, result] = yield* timedTask\n *   console.log(`Task completed in ${Duration.toMillis(duration)} ms with result: ${result}`)\n * })\n *\n * Effect.runFork(program)\n * // Output: Task completed in 2003.749125 ms with result: some result\n * ```\n *\n * @since 2.0.0\n * @category Delays & Timeouts\n */\nexport const timed: <A, E, R>(self: Effect<A, E, R>) => Effect<[duration: Duration.Duration, result: A], E, R> =\n  effect.timed\n\n/**\n * Executes an effect and measures its execution time using a custom clock.\n *\n * **Details**\n *\n * This function extends the functionality of {@link timed} by allowing you to\n * specify a custom clock for measuring the execution duration. The provided\n * effect (`nanoseconds`) represents the clock and should return the current\n * time in nanoseconds. The timing information is computed using this custom\n * clock instead of the default system clock.\n *\n * @since 2.0.0\n * @category Delays & Timeouts\n */\nexport const timedWith: {\n  <E1, R1>(\n    nanoseconds: Effect<bigint, E1, R1>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<[Duration.Duration, A], E1 | E, R1 | R>\n  <A, E, R, E1, R1>(\n    self: Effect<A, E, R>,\n    nanoseconds: Effect<bigint, E1, R1>\n  ): Effect<[Duration.Duration, A], E | E1, R | R1>\n} = effect.timedWith\n\n/**\n * Adds a time limit to an effect, triggering a timeout if the effect exceeds\n * the duration.\n *\n * **Details**\n *\n * This function allows you to enforce a time limit on the execution of an\n * effect. If the effect does not complete within the given duration, it fails\n * with a `TimeoutException`. This is useful for preventing tasks from hanging\n * indefinitely, especially in scenarios where responsiveness or resource limits\n * are critical.\n *\n * The returned effect will either:\n * - Succeed with the original effect's result if it completes within the\n *   specified duration.\n * - Fail with a `TimeoutException` if the time limit is exceeded.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const task = Effect.gen(function* () {\n *   console.log(\"Start processing...\")\n *   yield* Effect.sleep(\"2 seconds\") // Simulates a delay in processing\n *   console.log(\"Processing complete.\")\n *   return \"Result\"\n * })\n *\n * // Output will show a TimeoutException as the task takes longer\n * // than the specified timeout duration\n * const timedEffect = task.pipe(Effect.timeout(\"1 second\"))\n *\n * Effect.runPromiseExit(timedEffect).then(console.log)\n * // Output:\n * // Start processing...\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Fail',\n * //     failure: { _tag: 'TimeoutException' }\n * //   }\n * // }\n * ```\n *\n * @see {@link timeoutFail} for a version that raises a custom error.\n * @see {@link timeoutFailCause} for a version that raises a custom defect.\n * @see {@link timeoutTo} for a version that allows specifying both success and\n * timeout handlers.\n *\n * @since 2.0.0\n * @category Delays & Timeouts\n */\nexport const timeout: {\n  (duration: Duration.DurationInput): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E | Cause.TimeoutException, R>\n  <A, E, R>(self: Effect<A, E, R>, duration: Duration.DurationInput): Effect<A, Cause.TimeoutException | E, R>\n} = circular.timeout\n\n/**\n * Gracefully handles timeouts by returning an `Option` that represents either\n * the result or a timeout.\n *\n * **Details**\n *\n * This function wraps the outcome of an effect in an `Option` type. If the\n * effect completes within the specified duration, it returns a `Some`\n * containing the result. If the effect times out, it returns a `None`. Unlike\n * other timeout methods, this approach does not raise errors or exceptions;\n * instead, it allows you to treat timeouts as a regular outcome, simplifying\n * the logic for handling delays.\n *\n * **When to Use**\n *\n * This is useful when you want to handle timeouts without causing the program\n * to fail, making it easier to manage situations where you expect tasks might\n * take too long but want to continue executing other tasks.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const task = Effect.gen(function* () {\n *   console.log(\"Start processing...\")\n *   yield* Effect.sleep(\"2 seconds\") // Simulates a delay in processing\n *   console.log(\"Processing complete.\")\n *   return \"Result\"\n * })\n *\n * const timedOutEffect = Effect.all([\n *   task.pipe(Effect.timeoutOption(\"3 seconds\")),\n *   task.pipe(Effect.timeoutOption(\"1 second\"))\n * ])\n *\n * Effect.runPromise(timedOutEffect).then(console.log)\n * // Output:\n * // Start processing...\n * // Processing complete.\n * // Start processing...\n * // [\n * //   { _id: 'Option', _tag: 'Some', value: 'Result' },\n * //   { _id: 'Option', _tag: 'None' }\n * // ]\n * ```\n *\n * @see {@link timeout} for a version that raises a `TimeoutException`.\n * @see {@link timeoutFail} for a version that raises a custom error.\n * @see {@link timeoutFailCause} for a version that raises a custom defect.\n * @see {@link timeoutTo} for a version that allows specifying both success and\n * timeout handlers.\n *\n * @since 3.1.0\n * @category Delays & Timeouts\n */\nexport const timeoutOption: {\n  (duration: Duration.DurationInput): <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E, R>\n  <A, E, R>(self: Effect<A, E, R>, duration: Duration.DurationInput): Effect<Option.Option<A>, E, R>\n} = circular.timeoutOption\n\n/**\n * Specifies a custom error to be produced when a timeout occurs.\n *\n * **Details**\n *\n * This function allows you to handle timeouts in a customized way by defining a\n * specific error to be raised when an effect exceeds the given duration. Unlike\n * default timeout behaviors that use generic exceptions, this function gives\n * you the flexibility to specify a meaningful error type that aligns with your\n * application's needs.\n *\n * When you apply this function, you provide:\n * - A `duration`: The time limit for the effect.\n * - An `onTimeout` function: A lazy evaluation function that generates the\n *   custom error if the timeout occurs.\n *\n * If the effect completes within the time limit, its result is returned\n * normally. Otherwise, the `onTimeout` function is triggered, and its output is\n * used as the error for the effect.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const task = Effect.gen(function* () {\n *   console.log(\"Start processing...\")\n *   yield* Effect.sleep(\"2 seconds\") // Simulates a delay in processing\n *   console.log(\"Processing complete.\")\n *   return \"Result\"\n * })\n *\n * class MyTimeoutError {\n *   readonly _tag = \"MyTimeoutError\"\n * }\n *\n * const program = task.pipe(\n *   Effect.timeoutFail({\n *     duration: \"1 second\",\n *     onTimeout: () => new MyTimeoutError() // Custom timeout error\n *   })\n * )\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // Start processing...\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Fail',\n * //     failure: MyTimeoutError { _tag: 'MyTimeoutError' }\n * //   }\n * // }\n * ```\n *\n * @see {@link timeout} for a version that raises a `TimeoutException`.\n * @see {@link timeoutFailCause} for a version that raises a custom defect.\n * @see {@link timeoutTo} for a version that allows specifying both success and\n * timeout handlers.\n *\n * @since 2.0.0\n * @category Delays & Timeouts\n */\nexport const timeoutFail: {\n  <E1>(\n    options: { readonly onTimeout: LazyArg<E1>; readonly duration: Duration.DurationInput }\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E1 | E, R>\n  <A, E, R, E1>(\n    self: Effect<A, E, R>,\n    options: { readonly onTimeout: LazyArg<E1>; readonly duration: Duration.DurationInput }\n  ): Effect<A, E | E1, R>\n} = circular.timeoutFail\n\n/**\n * Specifies a custom defect to be thrown when a timeout occurs.\n *\n * **Details**\n *\n * This function allows you to handle timeouts as exceptional cases by\n * generating a custom defect when an effect exceeds the specified duration. You\n * provide:\n * - A `duration`: The time limit for the effect.\n * - An `onTimeout` function: A lazy evaluation function that generates the\n *   custom defect (typically created using `Cause.die`).\n *\n * If the effect completes within the time limit, its result is returned\n * normally. Otherwise, the custom defect is triggered, and the effect fails\n * with that defect.\n *\n * **When to Use**\n *\n * This is especially useful when you need to treat timeouts as critical\n * failures in your application and wish to include meaningful information in\n * the defect.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Cause } from \"effect\"\n *\n * const task = Effect.gen(function* () {\n *   console.log(\"Start processing...\")\n *   yield* Effect.sleep(\"2 seconds\") // Simulates a delay in processing\n *   console.log(\"Processing complete.\")\n *   return \"Result\"\n * })\n *\n * const program = task.pipe(\n *   Effect.timeoutFailCause({\n *     duration: \"1 second\",\n *     onTimeout: () => Cause.die(\"Timed out!\") // Custom defect for timeout\n *   })\n * )\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // Start processing...\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: { _id: 'Cause', _tag: 'Die', defect: 'Timed out!' }\n * // }\n * ```\n *\n * @see {@link timeout} for a version that raises a `TimeoutException`.\n * @see {@link timeoutFail} for a version that raises a custom error.\n * @see {@link timeoutTo} for a version that allows specifying both success and\n * timeout handlers.\n *\n * @since 2.0.0\n * @category Delays & Timeouts\n */\nexport const timeoutFailCause: {\n  <E1>(\n    options: { readonly onTimeout: LazyArg<Cause.Cause<E1>>; readonly duration: Duration.DurationInput }\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E1 | E, R>\n  <A, E, R, E1>(\n    self: Effect<A, E, R>,\n    options: { readonly onTimeout: LazyArg<Cause.Cause<E1>>; readonly duration: Duration.DurationInput }\n  ): Effect<A, E | E1, R>\n} = circular.timeoutFailCause\n\n/**\n * Provides custom behavior for successful and timed-out operations.\n *\n * **Details**\n *\n * This function allows you to define distinct outcomes for an effect depending\n * on whether it completes within a specified time frame or exceeds the timeout\n * duration. You can provide:\n * - `onSuccess`: A handler for processing the result of the effect if it\n *   completes successfully within the time limit.\n * - `onTimeout`: A handler for generating a result when the effect times out.\n * - `duration`: The maximum allowed time for the effect to complete.\n *\n * **When to Use**\n *\n * Unlike {@link timeout}, which raises an exception for timeouts, this function\n * gives you full control over the behavior for both success and timeout\n * scenarios. It is particularly useful when you want to encapsulate timeouts\n * and successes into a specific data structure, like an `Either` type, to\n * represent these outcomes in a meaningful way.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Either } from \"effect\"\n *\n * const task = Effect.gen(function* () {\n *   console.log(\"Start processing...\")\n *   yield* Effect.sleep(\"2 seconds\") // Simulates a delay in processing\n *   console.log(\"Processing complete.\")\n *   return \"Result\"\n * })\n *\n * const program = task.pipe(\n *   Effect.timeoutTo({\n *     duration: \"1 second\",\n *     onSuccess: (result): Either.Either<string, string> =>\n *       Either.right(result),\n *     onTimeout: (): Either.Either<string, string> =>\n *       Either.left(\"Timed out!\")\n *   })\n * )\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // Start processing...\n * // {\n * //   _id: \"Either\",\n * //   _tag: \"Left\",\n * //   left: \"Timed out!\"\n * // }\n * ```\n *\n * @see {@link timeout} for a version that raises a `TimeoutException`.\n * @see {@link timeoutFail} for a version that raises a custom error.\n * @see {@link timeoutFailCause} for a version that raises a custom defect.\n *\n * @since 2.0.0\n * @category Delays & Timeouts\n */\nexport const timeoutTo: {\n  <A, B, B1>(\n    options: {\n      readonly onTimeout: LazyArg<B1>\n      readonly onSuccess: (a: A) => B\n      readonly duration: Duration.DurationInput\n    }\n  ): <E, R>(self: Effect<A, E, R>) => Effect<B | B1, E, R>\n  <A, E, R, B1, B>(\n    self: Effect<A, E, R>,\n    options: {\n      readonly onTimeout: LazyArg<B1>\n      readonly onSuccess: (a: A) => B\n      readonly duration: Duration.DurationInput\n    }\n  ): Effect<B1 | B, E, R>\n} = circular.timeoutTo\n\n/**\n * Allows working with the default configuration provider.\n *\n * **Details**\n *\n * This function retrieves the default configuration provider and passes it to\n * the provided function, which can use it to perform computations or retrieve\n * configuration values. The function can return an effect that leverages the\n * configuration provider for its operations.\n *\n * @since 2.0.0\n * @category Config\n */\nexport const configProviderWith: <A, E, R>(f: (provider: ConfigProvider) => Effect<A, E, R>) => Effect<A, E, R> =\n  defaultServices.configProviderWith\n\n/**\n * Executes an effect using a specific configuration provider.\n *\n * **Details**\n *\n * This function lets you run an effect with a specified configuration provider.\n * The custom provider will override the default configuration provider for the\n * duration of the effect's execution.\n *\n * **When to Use**\n *\n * This is particularly useful when you need to use a different set of\n * configuration values or sources for specific parts of your application.\n *\n * **Example**\n *\n * ```ts\n * import { Config, ConfigProvider, Effect } from \"effect\"\n *\n * const customProvider: ConfigProvider.ConfigProvider = ConfigProvider.fromMap(\n *   new Map([[\"custom-key\", \"custom-value\"]])\n * )\n *\n * const program = Effect.withConfigProvider(customProvider)(\n *   Effect.gen(function*() {\n *     const value = yield* Config.string(\"custom-key\")\n *     console.log(`Config value: ${value}`)\n *   })\n * )\n *\n * Effect.runPromise(program)\n * // Output:\n * // Config value: custom-value\n * ```\n *\n * @since 2.0.0\n * @category Config\n */\nexport const withConfigProvider: {\n  (provider: ConfigProvider): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, provider: ConfigProvider): Effect<A, E, R>\n} = defaultServices.withConfigProvider\n\n/**\n * Sets a configuration provider within a scope.\n *\n * **Details**\n *\n * This function sets the configuration provider to a specified value and\n * ensures that it is restored to its original value when the scope is closed.\n *\n * @since 2.0.0\n * @category Config\n */\nexport const withConfigProviderScoped: (provider: ConfigProvider) => Effect<void, never, Scope.Scope> =\n  fiberRuntime.withConfigProviderScoped\n\n/**\n * Accesses the full context of the effect.\n *\n * **Details**\n *\n * This function provides the ability to access the entire context required by\n * an effect. The context is a container that holds dependencies or environment\n * values needed by an effect to run. By using this function, you can retrieve\n * and work with the context directly within an effect.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const context: <R>() => Effect<Context.Context<R>, never, R> = core.context\n\n/**\n * Accesses the context and applies a transformation function.\n *\n * **Details**\n *\n * This function retrieves the context of the effect and applies a pure\n * transformation function to it. The result of the transformation is then\n * returned within the effect.\n *\n * @see {@link contextWithEffect} for a version that allows effectful transformations.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const contextWith: <R, A>(f: (context: Context.Context<R>) => A) => Effect<A, never, R> = effect.contextWith\n\n/**\n * Accesses the context and performs an effectful transformation.\n *\n * **Details**\n *\n * This function retrieves the context and allows you to transform it\n * effectually using another effect. It is useful when the transformation\n * involves asynchronous or effectful operations.\n *\n * @see {@link contextWith} for a version that allows pure transformations.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const contextWithEffect: <R2, A, E, R>(\n  f: (context: Context.Context<R2>) => Effect<A, E, R>\n) => Effect<A, E, R | R2> = core.contextWithEffect\n\n/**\n * Provides part of the required context while leaving the rest unchanged.\n *\n * **Details**\n *\n * This function allows you to transform the context required by an effect,\n * providing part of the context and leaving the rest to be fulfilled later.\n *\n * **Example**\n *\n * ```ts\n * import { Context, Effect } from \"effect\"\n *\n * class Service1 extends Context.Tag(\"Service1\")<Service1, { readonly port: number }>() {}\n * class Service2 extends Context.Tag(\"Service2\")<Service2, { readonly connection: string }>() {}\n *\n * const program = Effect.gen(function*() {\n *   const service1 = yield* Service1\n *   console.log(service1.port)\n *   const service2 = yield* Service2\n *   console.log(service2.connection)\n *   return \"some result\"\n * })\n *\n * //      ┌─── Effect<string, never, Service2>\n * //      ▼\n * const programWithService1 = Effect.mapInputContext(\n *   program,\n *   (ctx: Context.Context<Service2>) => Context.add(ctx, Service1, { port: 3000 })\n * )\n *\n * const runnable = programWithService1.pipe(\n *   Effect.provideService(Service2, { connection: \"localhost\" }),\n *   Effect.provideService(Service1, { port: 3001 })\n * )\n *\n * Effect.runPromise(runnable)\n * // Output:\n * // 3000\n * // localhost\n * ```\n *\n * @since 2.0.0\n * @category Context\n */\nexport const mapInputContext: {\n  <R2, R>(f: (context: Context.Context<R2>) => Context.Context<R>): <A, E>(self: Effect<A, E, R>) => Effect<A, E, R2>\n  <A, E, R, R2>(self: Effect<A, E, R>, f: (context: Context.Context<R2>) => Context.Context<R>): Effect<A, E, R2>\n} = core.mapInputContext\n\n/**\n * Provides necessary dependencies to an effect, removing its environmental\n * requirements.\n *\n * **Details**\n *\n * This function allows you to supply the required environment for an effect.\n * The environment can be provided in the form of one or more `Layer`s, a\n * `Context`, a `Runtime`, or a `ManagedRuntime`. Once the environment is\n * provided, the effect can run without requiring external dependencies.\n *\n * You can compose layers to create a modular and reusable way of setting up the\n * environment for effects. For example, layers can be used to configure\n * databases, logging services, or any other required dependencies.\n *\n * **Example**\n *\n * ```ts\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class Database extends Context.Tag(\"Database\")<\n *   Database,\n *   { readonly query: (sql: string) => Effect.Effect<Array<unknown>> }\n * >() {}\n *\n * const DatabaseLive = Layer.succeed(\n *   Database,\n *   {\n *     // Simulate a database query\n *     query: (sql: string) => Effect.log(`Executing query: ${sql}`).pipe(Effect.as([]))\n *   }\n * )\n *\n * //      ┌─── Effect<unknown[], never, Database>\n * //      ▼\n * const program = Effect.gen(function*() {\n *   const database = yield* Database\n *   const result = yield* database.query(\"SELECT * FROM users\")\n *   return result\n * })\n *\n * //      ┌─── Effect<unknown[], never, never>\n * //      ▼\n * const runnable = Effect.provide(program, DatabaseLive)\n *\n * Effect.runPromise(runnable).then(console.log)\n * // Output:\n * // timestamp=... level=INFO fiber=#0 message=\"Executing query: SELECT * FROM users\"\n * // []\n * ```\n *\n * @see {@link provideService} for providing a service to an effect.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const provide: {\n  <const Layers extends readonly [Layer.Layer.Any, ...Array<Layer.Layer.Any>]>(\n    layers: Layers\n  ): <A, E, R>(\n    self: Effect<A, E, R>\n  ) => Effect<\n    A,\n    E | { [k in keyof Layers]: Layer.Layer.Error<Layers[k]> }[number],\n    | { [k in keyof Layers]: Layer.Layer.Context<Layers[k]> }[number]\n    | Exclude<R, { [k in keyof Layers]: Layer.Layer.Success<Layers[k]> }[number]>\n  >\n  <ROut, E2, RIn>(\n    layer: Layer.Layer<ROut, E2, RIn>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E | E2, RIn | Exclude<R, ROut>>\n  <R2>(context: Context.Context<R2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, Exclude<R, R2>>\n  <R2>(runtime: Runtime.Runtime<R2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, Exclude<R, R2>>\n  <E2, R2>(\n    managedRuntime: ManagedRuntime.ManagedRuntime<R2, E2>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E | E2, Exclude<R, R2>>\n  <A, E, R, const Layers extends readonly [Layer.Layer.Any, ...Array<Layer.Layer.Any>]>(\n    self: Effect<A, E, R>,\n    layers: Layers\n  ): Effect<\n    A,\n    E | { [k in keyof Layers]: Layer.Layer.Error<Layers[k]> }[number],\n    | { [k in keyof Layers]: Layer.Layer.Context<Layers[k]> }[number]\n    | Exclude<R, { [k in keyof Layers]: Layer.Layer.Success<Layers[k]> }[number]>\n  >\n  <A, E, R, ROut, E2, RIn>(\n    self: Effect<A, E, R>,\n    layer: Layer.Layer<ROut, E2, RIn>\n  ): Effect<A, E | E2, RIn | Exclude<R, ROut>>\n  <A, E, R, R2>(self: Effect<A, E, R>, context: Context.Context<R2>): Effect<A, E, Exclude<R, R2>>\n  <A, E, R, R2>(self: Effect<A, E, R>, runtime: Runtime.Runtime<R2>): Effect<A, E, Exclude<R, R2>>\n  <A, E, E2, R, R2>(\n    self: Effect<A, E, R>,\n    runtime: ManagedRuntime.ManagedRuntime<R2, E2>\n  ): Effect<A, E | E2, Exclude<R, R2>>\n} = layer.effect_provide\n\n/**\n * Provides an implementation for a service in the context of an effect.\n *\n * **Details**\n *\n * This function allows you to supply a specific implementation for a service\n * required by an effect. Services are typically defined using `Context.Tag`,\n * which acts as a unique identifier for the service. By using this function,\n * you link the service to its concrete implementation, enabling the effect to\n * execute successfully without additional requirements.\n *\n * For example, you can use this function to provide a random number generator,\n * a logger, or any other service your effect depends on. Once the service is\n * provided, all parts of the effect that rely on the service will automatically\n * use the implementation you supplied.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Context } from \"effect\"\n *\n * // Declaring a tag for a service that generates random numbers\n * class Random extends Context.Tag(\"MyRandomService\")<\n *   Random,\n *   { readonly next: Effect.Effect<number> }\n * >() {}\n *\n * // Using the service\n * const program = Effect.gen(function* () {\n *   const random = yield* Random\n *   const randomNumber = yield* random.next\n *   console.log(`random number: ${randomNumber}`)\n * })\n *\n * // Providing the implementation\n * //\n * //      ┌─── Effect<void, never, never>\n * //      ▼\n * const runnable = Effect.provideService(program, Random, {\n *   next: Effect.sync(() => Math.random())\n * })\n *\n * // Run successfully\n * Effect.runPromise(runnable)\n * // Example Output:\n * // random number: 0.8241872233134417\n * ```\n *\n * @see {@link provide} for providing multiple layers to an effect.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const provideService: {\n  <I, S>(tag: Context.Tag<I, S>, service: NoInfer<S>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, Exclude<R, I>>\n  <A, E, R, I, S>(self: Effect<A, E, R>, tag: Context.Tag<I, S>, service: NoInfer<S>): Effect<A, E, Exclude<R, I>>\n} = effect.provideService\n\n/**\n * Dynamically provides an implementation for a service using an effect.\n *\n * **Details**\n *\n * This function allows you to provide an implementation for a service\n * dynamically by using another effect. The provided effect is executed to\n * produce the service implementation, which is then made available to the\n * consuming effect. This is particularly useful when the service implementation\n * itself requires asynchronous or resource-intensive initialization.\n *\n * For example, you can use this function to lazily initialize a database\n * connection or fetch configuration values from an external source before\n * making the service available to your effect.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const provideServiceEffect: {\n  <I, S, E1, R1>(\n    tag: Context.Tag<I, S>,\n    effect: Effect<NoInfer<S>, E1, R1>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E | E1, R1 | Exclude<R, I>>\n  <A, E, R, I, S, E1, R1>(\n    self: Effect<A, E, R>,\n    tag: Context.Tag<I, S>,\n    effect: Effect<NoInfer<S>, E1, R1>\n  ): Effect<A, E | E1, R1 | Exclude<R, I>>\n} = effect.provideServiceEffect\n\n/**\n * Creates a function that uses a service from the context to produce a value.\n *\n * @see {@link serviceFunctionEffect} for a version that returns an effect.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const serviceFunction: <T extends Effect<any, any, any>, Args extends Array<any>, A>(\n  getService: T,\n  f: (_: Effect.Success<T>) => (...args: Args) => A\n) => (...args: Args) => Effect<A, Effect.Error<T>, Effect.Context<T>> = effect.serviceFunction\n\n/**\n * Creates a function that uses a service from the context to produce an effect.\n *\n * @see {@link serviceFunction} for a version that returns a value.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const serviceFunctionEffect: <T extends Effect<any, any, any>, Args extends Array<any>, A, E, R>(\n  getService: T,\n  f: (_: Effect.Success<T>) => (...args: Args) => Effect<A, E, R>\n) => (...args: Args) => Effect<A, E | Effect.Error<T>, R | Effect.Context<T>> = effect.serviceFunctionEffect\n\n/**\n * @since 2.0.0\n * @category Context\n */\nexport const serviceFunctions: <S, SE, SR>(\n  getService: Effect<S, SE, SR>\n) => {\n  [k in keyof S as S[k] extends (...args: Array<any>) => Effect<any, any, any> ? k : never]: S[k] extends\n    (...args: infer Args) => Effect<infer A, infer E, infer R> ? (...args: Args) => Effect<A, SE | E, SR | R>\n    : never\n} = effect.serviceFunctions as any\n\n/**\n * @since 2.0.0\n * @category Context\n */\nexport const serviceConstants: <S, SE, SR>(\n  getService: Effect<S, SE, SR>\n) => {\n  [k in { [k in keyof S]: k }[keyof S]]: S[k] extends Effect<infer A, infer E, infer R> ? Effect<A, SE | E, SR | R>\n    : Effect<S[k], SE, SR>\n} = effect.serviceConstants\n\n/**\n * @since 2.0.0\n * @category Context\n */\nexport const serviceMembers: <S, SE, SR>(\n  getService: Effect<S, SE, SR>\n) => {\n  functions: {\n    [k in keyof S as S[k] extends (...args: Array<any>) => Effect<any, any, any> ? k : never]: S[k] extends\n      (...args: infer Args) => Effect<infer A, infer E, infer R> ? (...args: Args) => Effect<A, SE | E, SR | R>\n      : never\n  }\n  constants: {\n    [k in { [k in keyof S]: k }[keyof S]]: S[k] extends Effect<infer A, infer E, infer R> ? Effect<A, SE | E, SR | R>\n      : Effect<S[k], SE, SR>\n  }\n} = effect.serviceMembers as any\n\n/**\n * Retrieves an optional service from the context as an `Option`.\n *\n * **Details**\n *\n * This function retrieves a service from the context and wraps it in an\n * `Option`. If the service is available, it returns a `Some` containing the\n * service. If the service is not found, it returns a `None`. This approach is\n * useful when you want to handle the absence of a service gracefully without\n * causing an error.\n *\n * **When to Use**\n *\n * Use this function when:\n * - You need to access a service that may or may not be present in the context.\n * - You want to handle the absence of a service using the `Option` type instead\n *   of throwing an error.\n *\n * @see {@link serviceOptional} for a version that throws an error if the service is missing.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const serviceOption: <I, S>(tag: Context.Tag<I, S>) => Effect<Option.Option<S>> = effect.serviceOption\n\n/**\n * Retrieves a service from the context, throwing an error if it is missing.\n *\n * **Details**\n *\n * This function retrieves a required service from the context. If the service\n * is available, it returns the service. If the service is missing, it throws a\n * `NoSuchElementException`, which can be handled using Effect's error-handling\n * mechanisms. This is useful for services that are critical to the execution of\n * your effect.\n *\n * @see {@link serviceOption} for a version that returns an `Option` instead of throwing an error.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const serviceOptional: <I, S>(tag: Context.Tag<I, S>) => Effect<S, Cause.NoSuchElementException> =\n  effect.serviceOptional\n\n/**\n * Updates a service in the context with a new implementation.\n *\n * **Details**\n *\n * This function modifies the existing implementation of a service in the\n * context. It retrieves the current service, applies the provided\n * transformation function `f`, and replaces the old service with the\n * transformed one.\n *\n * **When to Use**\n *\n * This is useful for adapting or extending a service's behavior during the\n * execution of an effect.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const updateService: {\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    f: (service: NoInfer<S>) => NoInfer<S>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R | I>\n  <A, E, R, I, S>(\n    self: Effect<A, E, R>,\n    tag: Context.Tag<I, S>,\n    f: (service: NoInfer<S>) => NoInfer<S>\n  ): Effect<A, E, R | I>\n} = effect.updateService\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Effect` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n *\n * **Example**\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Effect, pipe } from \"effect\"\n *\n * const result = pipe(\n *   Effect.Do,\n *   Effect.bind(\"x\", () => Effect.succeed(2)),\n *   Effect.bind(\"y\", () => Effect.succeed(3)),\n *   Effect.let(\"sum\", ({ x, y }) => x + y)\n * )\n * assert.deepStrictEqual(Effect.runSync(result), { x: 2, y: 3, sum: 5 })\n * ```\n *\n * @see {@link bind}\n * @see {@link bindTo}\n * @see {@link let_ let}\n *\n * @category Do notation\n * @since 2.0.0\n */\nexport const Do: Effect<{}> = effect.Do\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Effect` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n *\n * **Example**\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Effect, pipe } from \"effect\"\n *\n * const result = pipe(\n *   Effect.Do,\n *   Effect.bind(\"x\", () => Effect.succeed(2)),\n *   Effect.bind(\"y\", () => Effect.succeed(3)),\n *   Effect.let(\"sum\", ({ x, y }) => x + y)\n * )\n * assert.deepStrictEqual(Effect.runSync(result), { x: 2, y: 3, sum: 5 })\n * ```\n *\n * @see {@link Do}\n * @see {@link bindTo}\n * @see {@link let_ let}\n *\n * @category Do notation\n * @since 2.0.0\n */\nexport const bind: {\n  <N extends string, A extends object, B, E2, R2>(\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => Effect<B, E2, R2>\n  ): <E1, R1>(self: Effect<A, E1, R1>) => Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E2 | E1, R2 | R1>\n  <A extends object, N extends string, E1, R1, B, E2, R2>(\n    self: Effect<A, E1, R1>,\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => Effect<B, E2, R2>\n  ): Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E1 | E2, R1 | R2>\n} = effect.bind\n\n/**\n * `bindAll` combines `all` with `bind`. It is useful\n * when you want to concurrently run multiple effects and then combine their\n * results in a Do notation pipeline.\n *\n * **Example**\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Effect, Either, pipe } from \"effect\"\n *\n * const result = pipe(\n *   Effect.Do,\n *   Effect.bind(\"x\", () => Effect.succeed(2)),\n *   Effect.bindAll(({ x }) => ({\n *     a: Effect.succeed(x),\n *     b: Effect.fail(\"oops\"),\n *   }), { concurrency: 2, mode: \"either\" })\n * )\n * assert.deepStrictEqual(Effect.runSync(result), { x: 2, a: Either.right(2), b: Either.left(\"oops\") })\n * ```\n *\n * @category Do notation\n * @since 3.7.0\n */\nexport const bindAll: {\n  <\n    A extends object,\n    X extends Record<string, Effect<any, any, any>>,\n    O extends NoExcessProperties<{\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }, O>\n  >(\n    f: (a: NoInfer<A>) => [Extract<keyof X, keyof A>] extends [never] ? X : `Duplicate keys`,\n    options?: undefined | O\n  ): <E1, R1>(\n    self: Effect<A, E1, R1>\n  ) => [All.ReturnObject<X, false, All.ExtractMode<O>>] extends [Effect<infer Success, infer Error, infer Context>]\n    ? Effect<\n      { [K in keyof A | keyof Success]: K extends keyof A ? A[K] : K extends keyof Success ? Success[K] : never },\n      E1 | Error,\n      R1 | Context\n    >\n    : never\n  <\n    A extends object,\n    X extends Record<string, Effect<any, any, any>>,\n    O extends NoExcessProperties<{\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }, O>,\n    E1,\n    R1\n  >(\n    self: Effect<A, E1, R1>,\n    f: (a: NoInfer<A>) => [Extract<keyof X, keyof A>] extends [never] ? X : `Duplicate keys`,\n    options?: undefined | {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): [All.ReturnObject<X, false, All.ExtractMode<O>>] extends [Effect<infer Success, infer Error, infer Context>]\n    ? Effect<\n      { [K in keyof A | keyof Success]: K extends keyof A ? A[K] : K extends keyof Success ? Success[K] : never },\n      E1 | Error,\n      R1 | Context\n    >\n    : never\n} = circular.bindAll\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Effect` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n *\n * **Example**\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Effect, pipe } from \"effect\"\n *\n * const result = pipe(\n *   Effect.Do,\n *   Effect.bind(\"x\", () => Effect.succeed(2)),\n *   Effect.bind(\"y\", () => Effect.succeed(3)),\n *   Effect.let(\"sum\", ({ x, y }) => x + y)\n * )\n * assert.deepStrictEqual(Effect.runSync(result), { x: 2, y: 3, sum: 5 })\n * ```\n *\n * @see {@link Do}\n * @see {@link bind}\n * @see {@link let_ let}\n *\n * @category Do notation\n * @since 2.0.0\n */\nexport const bindTo: {\n  <N extends string>(name: N): <A, E, R>(self: Effect<A, E, R>) => Effect<{ [K in N]: A }, E, R>\n  <A, E, R, N extends string>(self: Effect<A, E, R>, name: N): Effect<{ [K in N]: A }, E, R>\n} = effect.bindTo\n\nconst let_: {\n  <N extends string, A extends object, B>(\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): <E, R>(self: Effect<A, E, R>) => Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E, R>\n  <A extends object, N extends string, E, R, B>(\n    self: Effect<A, E, R>,\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E, R>\n} = effect.let_\n\nexport {\n  /**\n   * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n   *\n   * Here's how the do simulation works:\n   *\n   * 1. Start the do simulation using the `Do` value\n   * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Effect` values\n   * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n   * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n   *\n   * **Example**\n   *\n   * ```ts\n   * import * as assert from \"node:assert\"\n   * import { Effect, pipe } from \"effect\"\n   *\n   * const result = pipe(\n   *   Effect.Do,\n   *   Effect.bind(\"x\", () => Effect.succeed(2)),\n   *   Effect.bind(\"y\", () => Effect.succeed(3)),\n   *   Effect.let(\"sum\", ({ x, y }) => x + y)\n   * )\n   * assert.deepStrictEqual(Effect.runSync(result), { x: 2, y: 3, sum: 5 })\n   *\n   * ```\n   *\n   * @see {@link Do}\n   * @see {@link bind}\n   * @see {@link bindTo}\n   *\n   * @category Do notation\n   * @since 2.0.0\n   */\n  let_ as let\n}\n\n/**\n * Encapsulates the result of an effect in an `Option`.\n *\n * **Details**\n *\n * This function wraps the outcome of an effect in an `Option` type. If the\n * original effect succeeds, the success value is wrapped in `Option.some`. If\n * the effect fails, the failure is converted to `Option.none`.\n *\n * This is particularly useful for scenarios where you want to represent the\n * absence of a value explicitly, without causing the resulting effect to fail.\n * The resulting effect has an error type of `never`, meaning it cannot fail\n * directly. However, unrecoverable errors, also referred to as defects, are\n * not captured and will still result in failure.\n *\n * **Example** (Using Effect.option to Handle Errors)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const maybe1 = Effect.option(Effect.succeed(1))\n *\n * Effect.runPromiseExit(maybe1).then(console.log)\n * // Output:\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Success',\n * //   value: { _id: 'Option', _tag: 'Some', value: 1 }\n * // }\n *\n * const maybe2 = Effect.option(Effect.fail(\"Uh oh!\"))\n *\n * Effect.runPromiseExit(maybe2).then(console.log)\n * // Output:\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Success',\n * //   value: { _id: 'Option', _tag: 'None' }\n * // }\n *\n * const maybe3 = Effect.option(Effect.die(\"Boom!\"))\n *\n * Effect.runPromiseExit(maybe3).then(console.log)\n * // Output:\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: { _id: 'Cause', _tag: 'Die', defect: 'Boom!' }\n * // }\n * ```\n *\n * @see {@link either} for a version that uses `Either` instead.\n * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`.\n *\n * @since 2.0.0\n * @category Outcome Encapsulation\n */\nexport const option: <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, never, R> = effect.option\n\n/**\n * Encapsulates both success and failure of an `Effect` into an `Either` type.\n *\n * **Details**\n *\n * This function converts an effect that may fail into an effect that always\n * succeeds, wrapping the outcome in an `Either` type. The result will be\n * `Either.Left` if the effect fails, containing the recoverable error, or\n * `Either.Right` if it succeeds, containing the result.\n *\n * Using this function, you can handle recoverable errors explicitly without\n * causing the effect to fail. This is particularly useful in scenarios where\n * you want to chain effects and manage both success and failure in the same\n * logical flow.\n *\n * It's important to note that unrecoverable errors, often referred to as\n * \"defects,\" are still thrown and not captured within the `Either` type. Only\n * failures that are explicitly represented as recoverable errors in the effect\n * are encapsulated.\n *\n * The resulting effect cannot fail directly because all recoverable failures\n * are represented inside the `Either` type.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Either, Random } from \"effect\"\n *\n * class HttpError {\n *   readonly _tag = \"HttpError\"\n * }\n *\n * class ValidationError {\n *   readonly _tag = \"ValidationError\"\n * }\n *\n * //      ┌─── Effect<string, HttpError | ValidationError, never>\n * //      ▼\n * const program = Effect.gen(function* () {\n *   const n1 = yield* Random.next\n *   const n2 = yield* Random.next\n *   if (n1 < 0.5) {\n *     yield* Effect.fail(new HttpError())\n *   }\n *   if (n2 < 0.5) {\n *     yield* Effect.fail(new ValidationError())\n *   }\n *   return \"some result\"\n * })\n *\n * //      ┌─── Effect<string, never, never>\n * //      ▼\n * const recovered = Effect.gen(function* () {\n *   //      ┌─── Either<string, HttpError | ValidationError>\n *   //      ▼\n *   const failureOrSuccess = yield* Effect.either(program)\n *   return Either.match(failureOrSuccess, {\n *     onLeft: (error) => `Recovering from ${error._tag}`,\n *     onRight: (value) => value // Do nothing in case of success\n *   })\n * })\n * ```\n *\n * @see {@link option} for a version that uses `Option` instead.\n * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`.\n *\n * @since 2.0.0\n * @category Outcome Encapsulation\n */\nexport const either: <A, E, R>(self: Effect<A, E, R>) => Effect<Either.Either<A, E>, never, R> = core.either\n\n/**\n * Encapsulates both success and failure of an `Effect` using the `Exit` type.\n *\n * **Details**\n *\n * This function converts an effect into one that always succeeds, wrapping its\n * outcome in the `Exit` type. The `Exit` type provides explicit handling of\n * both success (`Exit.Success`) and failure (`Exit.Failure`) cases, including\n * defects (unrecoverable errors).\n *\n * Unlike {@link either} or {@link option}, this function also encapsulates\n * defects, which are typically unrecoverable and would otherwise terminate the\n * effect. With the `Exit` type, defects are represented in `Exit.Failure`,\n * allowing for detailed introspection and structured error handling.\n *\n * This makes the resulting effect robust and incapable of direct failure (its\n * error type is `never`). It is particularly useful for workflows where all\n * outcomes, including unexpected defects, must be managed and analyzed.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Cause, Console, Exit } from \"effect\"\n *\n * // Simulating a runtime error\n * const task = Effect.dieMessage(\"Boom!\")\n *\n * const program = Effect.gen(function* () {\n *   const exit = yield* Effect.exit(task)\n *   if (Exit.isFailure(exit)) {\n *     const cause = exit.cause\n *     if (\n *       Cause.isDieType(cause) &&\n *       Cause.isRuntimeException(cause.defect)\n *     ) {\n *       yield* Console.log(\n *         `RuntimeException defect caught: ${cause.defect.message}`\n *       )\n *     } else {\n *       yield* Console.log(\"Unknown failure caught.\")\n *     }\n *   }\n * })\n *\n * // We get an Exit.Success because we caught all failures\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // RuntimeException defect caught: Boom!\n * // {\n * //   _id: \"Exit\",\n * //   _tag: \"Success\",\n * //   value: undefined\n * // }\n * ```\n *\n * @see {@link option} for a version that uses `Option` instead.\n * @see {@link either} for a version that uses `Either` instead.\n *\n * @since 2.0.0\n * @category Outcome Encapsulation\n */\nexport const exit: <A, E, R>(self: Effect<A, E, R>) => Effect<Exit.Exit<A, E>, never, R> = core.exit\n\n/**\n * Converts an `Effect` into an operation that completes a `Deferred` with its result.\n *\n * **Details**\n *\n * The `intoDeferred` function takes an effect and a `Deferred` and ensures that the `Deferred`\n * is completed based on the outcome of the effect. If the effect succeeds, the `Deferred` is\n * completed with the success value. If the effect fails, the `Deferred` is completed with the\n * failure. Additionally, if the effect is interrupted, the `Deferred` will also be interrupted.\n *\n * **Example**\n *\n * ```ts\n * import { Deferred, Effect } from \"effect\"\n *\n * // Define an effect that succeeds\n * const successEffect = Effect.succeed(42)\n *\n * const program = Effect.gen(function*() {\n *   // Create a deferred\n *   const deferred = yield* Deferred.make<number, string>()\n *\n *   // Complete the deferred using the successEffect\n *   const isCompleted = yield* Effect.intoDeferred(successEffect, deferred)\n *\n *   // Access the value of the deferred\n *   const value = yield* Deferred.await(deferred)\n *   console.log(value)\n *\n *   return isCompleted\n * })\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // 42\n * // true\n * ```\n *\n * @since 2.0.0\n * @category Synchronization Utilities\n */\nexport const intoDeferred: {\n  <A, E>(deferred: Deferred.Deferred<A, E>): <R>(self: Effect<A, E, R>) => Effect<boolean, never, R>\n  <A, E, R>(self: Effect<A, E, R>, deferred: Deferred.Deferred<A, E>): Effect<boolean, never, R>\n} = core.intoDeferred\n\nconst if_: {\n  <A1, E1, R1, A2, E2, R2>(\n    options: { readonly onTrue: LazyArg<Effect<A1, E1, R1>>; readonly onFalse: LazyArg<Effect<A2, E2, R2>> }\n  ): <E = never, R = never>(self: boolean | Effect<boolean, E, R>) => Effect<A1 | A2, E1 | E2 | E, R1 | R2 | R>\n  <A1, E1, R1, A2, E2, R2, E = never, R = never>(\n    self: boolean | Effect<boolean, E, R>,\n    options: { readonly onTrue: LazyArg<Effect<A1, E1, R1>>; readonly onFalse: LazyArg<Effect<A2, E2, R2>> }\n  ): Effect<A1 | A2, E1 | E2 | E, R1 | R2 | R>\n} = core.if_\n\nexport {\n  /**\n   * Executes one of two effects based on a condition evaluated by an effectful predicate.\n   *\n   * Use `if` to run one of two effects depending on whether the predicate effect\n   * evaluates to `true` or `false`. If the predicate is `true`, the `onTrue` effect\n   * is executed. If it is `false`, the `onFalse` effect is executed instead.\n   *\n   * **Example** (Simulating a Coin Flip)\n   *\n   * ```ts\n   * import { Effect, Random, Console } from \"effect\"\n   *\n   * const flipTheCoin = Effect.if(Random.nextBoolean, {\n   *   onTrue: () => Console.log(\"Head\"), // Runs if the predicate is true\n   *   onFalse: () => Console.log(\"Tail\") // Runs if the predicate is false\n   * })\n   *\n   * Effect.runFork(flipTheCoin)\n   * ```\n   *\n   * @since 2.0.0\n   * @category Conditional Operators\n   */\n  if_ as if\n}\n\n/**\n * Filters an effect, dying with a custom defect if the predicate fails.\n *\n * **Details**\n *\n * This function applies a predicate to the result of an effect. If the\n * predicate evaluates to `false`, the effect dies with a custom defect\n * generated by the `orDieWith` function.\n *\n * **When to Use**\n *\n * This is useful for enforcing constraints on values and treating violations as\n * fatal program errors.\n *\n * @since 2.0.0\n * @category Filtering\n */\nexport const filterOrDie: {\n  <A, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>,\n    orDieWith: (a: EqualsWith<A, B, A, Exclude<A, B>>) => unknown\n  ): <E, R>(self: Effect<A, E, R>) => Effect<B, E, R>\n  <A>(\n    predicate: Predicate<NoInfer<A>>,\n    orDieWith: (a: NoInfer<A>) => unknown\n  ): <E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R, B extends A>(\n    self: Effect<A, E, R>,\n    refinement: Refinement<A, B>,\n    orDieWith: (a: EqualsWith<A, B, A, Exclude<A, B>>) => unknown\n  ): Effect<B, E, R>\n  <A, E, R>(self: Effect<A, E, R>, predicate: Predicate<A>, orDieWith: (a: A) => unknown): Effect<A, E, R>\n} = effect.filterOrDie\n\n/**\n * Filters an effect, dying with a custom message if the predicate fails.\n *\n * **Details**\n *\n * This function works like {@link filterOrDie} but allows you to specify a\n * custom error message to describe the reason for the failure. The message is\n * included in the defect when the predicate evaluates to `false`.\n *\n * @since 2.0.0\n * @category Filtering\n */\nexport const filterOrDieMessage: {\n  <A, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>,\n    message: string\n  ): <E, R>(self: Effect<A, E, R>) => Effect<B, E, R>\n  <A>(predicate: Predicate<NoInfer<A>>, message: string): <E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R, B extends A>(self: Effect<A, E, R>, refinement: Refinement<A, B>, message: string): Effect<B, E, R>\n  <A, E, R>(self: Effect<A, E, R>, predicate: Predicate<A>, message: string): Effect<A, E, R>\n} = effect.filterOrDieMessage\n\n/**\n * Filters an effect, providing an alternative effect if the predicate fails.\n *\n * **Details**\n *\n * This function applies a predicate to the result of an effect. If the\n * predicate evaluates to `false`, it executes the `orElse` effect instead. The\n * `orElse` effect can produce an alternative value or perform additional\n * computations.\n *\n * @since 2.0.0\n * @category Filtering\n */\nexport const filterOrElse: {\n  <A, C, E2, R2, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>,\n    orElse: (a: EqualsWith<A, B, NoInfer<A>, Exclude<NoInfer<A>, B>>) => Effect<C, E2, R2>\n  ): <E, R>(self: Effect<A, E, R>) => Effect<B | C, E2 | E, R2 | R>\n  <A, C, E2, R2>(\n    predicate: Predicate<NoInfer<A>>,\n    orElse: (a: NoInfer<A>) => Effect<C, E2, R2>\n  ): <E, R>(self: Effect<A, E, R>) => Effect<A | C, E2 | E, R2 | R>\n  <A, E, R, C, E2, R2, B extends A>(\n    self: Effect<A, E, R>,\n    refinement: Refinement<A, B>,\n    orElse: (a: EqualsWith<A, B, A, Exclude<A, B>>) => Effect<C, E2, R2>\n  ): Effect<B | C, E | E2, R | R2>\n  <A, E, R, C, E2, R2>(\n    self: Effect<A, E, R>,\n    predicate: Predicate<A>,\n    orElse: (a: A) => Effect<C, E2, R2>\n  ): Effect<A | C, E | E2, R | R2>\n} = effect.filterOrElse\n\n/**\n * Filters an effect, failing with a custom error if the predicate fails.\n *\n * **Details**\n *\n * This function applies a predicate to the result of an effect. If the\n * predicate evaluates to `false`, the effect fails with a custom error\n * generated by the `orFailWith` function.\n *\n * **When to Use**\n *\n * This is useful for enforcing constraints and treating violations as\n * recoverable errors.\n *\n * **Providing a Guard**\n *\n * In addition to the filtering capabilities discussed earlier, you have the\n * option to further refine and narrow down the type of the success channel by\n * providing a [user-defined type\n * guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates).\n * Let's explore this concept through an example:\n *\n * **Example**\n *\n * ```ts\n * import { Effect, pipe } from \"effect\"\n *\n * // Define a user interface\n * interface User {\n *   readonly name: string\n * }\n *\n * // Simulate an asynchronous authentication function\n * declare const auth: () => Promise<User | null>\n *\n * const program = pipe(\n *   Effect.promise(() => auth()),\n *   // Use filterOrFail with a custom type guard to ensure user is not null\n *   Effect.filterOrFail(\n *     (user): user is User => user !== null, // Type guard\n *     () => new Error(\"Unauthorized\")\n *   ),\n *   // 'user' now has the type `User` (not `User | null`)\n *   Effect.andThen((user) => user.name)\n * )\n * ```\n *\n * @since 2.0.0\n * @category Filtering\n */\nexport const filterOrFail: {\n  <A, E2, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>,\n    orFailWith: (a: EqualsWith<A, B, NoInfer<A>, Exclude<NoInfer<A>, B>>) => E2\n  ): <E, R>(self: Effect<A, E, R>) => Effect<NoInfer<B>, E2 | E, R>\n  <A, E2>(\n    predicate: Predicate<NoInfer<A>>,\n    orFailWith: (a: NoInfer<A>) => E2\n  ): <E, R>(self: Effect<A, E, R>) => Effect<A, E2 | E, R>\n  <A, E, R, E2, B extends A>(\n    self: Effect<A, E, R>,\n    refinement: Refinement<A, B>,\n    orFailWith: (a: EqualsWith<A, B, A, Exclude<A, B>>) => E2\n  ): Effect<NoInfer<B>, E2 | E, R>\n  <A, E, R, E2>(self: Effect<A, E, R>, predicate: Predicate<A>, orFailWith: (a: A) => E2): Effect<A, E2 | E, R>\n  <A, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>\n  ): <E, R>(self: Effect<A, E, R>) => Effect<NoInfer<B>, Cause.NoSuchElementException | E, R>\n  <A>(predicate: Predicate<NoInfer<A>>): <E, R>(self: Effect<A, E, R>) => Effect<A, Cause.NoSuchElementException | E, R>\n  <A, E, R, B extends A>(\n    self: Effect<A, E, R>,\n    refinement: Refinement<A, B>\n  ): Effect<NoInfer<B>, E | Cause.NoSuchElementException, R>\n  <A, E, R>(self: Effect<A, E, R>, predicate: Predicate<A>): Effect<A, E | Cause.NoSuchElementException, R>\n} = effect.filterOrFail\n\n/**\n * Filters an effect with an effectful predicate, falling back to an alternative\n * effect if the predicate fails.\n *\n * **Details**\n *\n * This function applies a predicate to the result of an effect. If the\n * predicate evaluates to `false`, the effect falls back to the `orElse`\n * effect. The `orElse` effect can produce an alternative value or perform\n * additional computations.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, pipe } from \"effect\"\n *\n * // Define a user interface\n * interface User {\n *   readonly name: string\n * }\n *\n * // Simulate an asynchronous authentication function\n * declare const auth: () => Promise<User | null>\n *\n * const program = pipe(\n *   Effect.promise(() => auth()),\n *   // Use filterEffectOrElse with an effectful predicate\n *   Effect.filterEffectOrElse({\n *     predicate: (user) => Effect.succeed(user !== null),\n *     orElse: (user) => Effect.fail(new Error(`Unauthorized user: ${user}`))\n *   }),\n * )\n * ```\n *\n * @since 3.13.0\n * @category Filtering\n */\nexport const filterEffectOrElse: {\n  <A, E2, R2, A2, E3, R3>(\n    options: {\n      readonly predicate: (a: NoInfer<A>) => Effect<boolean, E2, R2>\n      readonly orElse: (a: NoInfer<A>) => Effect<A2, E3, R3>\n    }\n  ): <E, R>(self: Effect<A, E, R>) => Effect<A | A2, E | E2 | E3, R | R2 | R3>\n  <A, E, R, E2, R2, A2, E3, R3>(\n    self: Effect<A, E, R>,\n    options: {\n      readonly predicate: (a: A) => Effect<boolean, E2, R2>\n      readonly orElse: (a: A) => Effect<A2, E3, R3>\n    }\n  ): Effect<A | A2, E | E2 | E3, R | R2 | R3>\n} = core.filterEffectOrElse\n\n/**\n * Filters an effect with an effectful predicate, failing with a custom error if the predicate fails.\n *\n * **Details**\n *\n * This function applies a predicate to the result of an effect. If the\n * predicate evaluates to `false`, the effect fails with a custom error\n * generated by the `orFailWith` function.\n *\n * **When to Use**\n *\n * This is useful for enforcing constraints and treating violations as\n * recoverable errors.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, pipe } from \"effect\"\n *\n * // Define a user interface\n * interface User {\n *   readonly name: string\n * }\n *\n * // Simulate an asynchronous authentication function\n * declare const auth: () => Promise<User | null>\n *\n * const program = pipe(\n *   Effect.promise(() => auth()),\n *   // Use filterEffectOrFail with an effectful predicate\n *   Effect.filterEffectOrFail({\n *     predicate: (user) => Effect.succeed(user !== null),\n *     orFailWith: () => new Error(\"Unauthorized\")\n *   }),\n * )\n * ```\n *\n * @since 3.13.0\n * @category Filtering\n */\nexport const filterEffectOrFail: {\n  <A, E2, R2, E3>(\n    options: {\n      readonly predicate: (a: NoInfer<A>) => Effect<boolean, E2, R2>\n      readonly orFailWith: (a: NoInfer<A>) => E3\n    }\n  ): <E, R>(self: Effect<A, E, R>) => Effect<A, E | E2 | E3, R | R2>\n  <A, E, R, E2, R2, E3>(\n    self: Effect<A, E, R>,\n    options: {\n      readonly predicate: (a: A) => Effect<boolean, E2, R2>\n      readonly orFailWith: (a: A) => E3\n    }\n  ): Effect<A, E | E2 | E3, R | R2>\n} = core.filterEffectOrFail\n\n/**\n * Executes an effect only if the condition is `false`.\n *\n * @see {@link unlessEffect} for a version that allows the condition to be an effect.\n * @see {@link when} for a version that executes the effect when the condition is `true`.\n *\n * @since 2.0.0\n * @category Conditional Operators\n */\nexport const unless: {\n  (condition: LazyArg<boolean>): <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E, R>\n  <A, E, R>(self: Effect<A, E, R>, condition: LazyArg<boolean>): Effect<Option.Option<A>, E, R>\n} = effect.unless\n\n/**\n * Conditionally execute an effect based on the result of another effect.\n *\n * @see {@link unless} for a version that allows the condition to be a boolean.\n * @see {@link whenEffect} for a version that executes the effect when the condition is `true`.\n *\n * @since 2.0.0\n * @category Conditional Operators\n */\nexport const unlessEffect: {\n  <E2, R2>(\n    condition: Effect<boolean, E2, R2>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(self: Effect<A, E, R>, condition: Effect<boolean, E2, R2>): Effect<Option.Option<A>, E | E2, R | R2>\n} = effect.unlessEffect\n\n/**\n * Conditionally executes an effect based on a boolean condition.\n *\n * **Details**\n *\n * This function allows you to run an effect only if a given condition evaluates\n * to `true`. If the condition is `true`, the effect is executed, and its result\n * is wrapped in an `Option.some`. If the condition is `false`, the effect is\n * skipped, and the result is `Option.none`.\n *\n * **When to Use**\n *\n * This function is useful for scenarios where you need to dynamically decide\n * whether to execute an effect based on runtime logic, while also representing\n * the skipped case explicitly.\n *\n * **Example** (Conditional Effect Execution)\n *\n * ```ts\n * import { Effect, Option } from \"effect\"\n *\n * const validateWeightOption = (\n *   weight: number\n * ): Effect.Effect<Option.Option<number>> =>\n *   // Conditionally execute the effect if the weight is non-negative\n *   Effect.succeed(weight).pipe(Effect.when(() => weight >= 0))\n *\n * // Run with a valid weight\n * Effect.runPromise(validateWeightOption(100)).then(console.log)\n * // Output:\n * // {\n * //   _id: \"Option\",\n * //   _tag: \"Some\",\n * //   value: 100\n * // }\n *\n * // Run with an invalid weight\n * Effect.runPromise(validateWeightOption(-5)).then(console.log)\n * // Output:\n * // {\n * //   _id: \"Option\",\n * //   _tag: \"None\"\n * // }\n * ```\n *\n * @see {@link whenEffect} for a version that allows the condition to be an effect.\n * @see {@link unless} for a version that executes the effect when the condition is `false`.\n *\n * @since 2.0.0\n * @category Conditional Operators\n */\nexport const when: {\n  (condition: LazyArg<boolean>): <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E, R>\n  <A, E, R>(self: Effect<A, E, R>, condition: LazyArg<boolean>): Effect<Option.Option<A>, E, R>\n} = effect.when\n\n/**\n * Conditionally executes an effect based on the result of another effect.\n *\n * **Details**\n *\n * This function allows you to run an effect only if a conditional effect\n * evaluating to a boolean resolves to `true`. If the conditional effect\n * evaluates to `true`, the specified effect is executed, and its result is\n * wrapped in `Option.some`. If the conditional effect evaluates to `false`, the\n * effect is skipped, and the result is `Option.none`.\n *\n * **When to Use**\n *\n * This function is particularly useful when the decision to execute an effect\n * depends on the result of another effect, such as a random value, a\n * user-provided input, or a network request result.\n *\n * **Example** (Using an Effect as a Condition)\n *\n * ```ts\n * import { Effect, Random } from \"effect\"\n *\n * const randomIntOption = Random.nextInt.pipe(\n *   Effect.whenEffect(Random.nextBoolean)\n * )\n *\n * console.log(Effect.runSync(randomIntOption))\n * // Example Output:\n * // { _id: 'Option', _tag: 'Some', value: 8609104974198840 }\n * ```\n *\n * @see {@link when} for a version that allows the condition to be a boolean.\n * @see {@link unlessEffect} for a version that executes the effect when the condition is `false`.\n *\n * @since 2.0.0\n * @category Conditional Operators\n */\nexport const whenEffect: {\n  <E, R>(\n    condition: Effect<boolean, E, R>\n  ): <A, E2, R2>(effect: Effect<A, E2, R2>) => Effect<Option.Option<A>, E | E2, R | R2>\n  <A, E2, R2, E, R>(self: Effect<A, E2, R2>, condition: Effect<boolean, E, R>): Effect<Option.Option<A>, E2 | E, R2 | R>\n} = core.whenEffect\n\n/**\n * Executes an effect conditionally based on the value of a `FiberRef` that\n * satisfies a predicate.\n *\n * **Details**\n *\n * This function enables you to execute an effect only when the value of a\n * specified `FiberRef` meets a certain condition defined by a predicate. If the\n * value satisfies the predicate, the effect is executed, and the result is\n * wrapped in an `Option.some`. If the predicate is not satisfied, the effect is\n * skipped, and the result is `Option.none`. In both cases, the current value of\n * the `FiberRef` is included in the result.\n *\n * @since 2.0.0\n * @category Conditional Operators\n */\nexport const whenFiberRef: {\n  <S>(\n    fiberRef: FiberRef.FiberRef<S>,\n    predicate: Predicate<S>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<[S, Option.Option<A>], E, R>\n  <A, E, R, S>(\n    self: Effect<A, E, R>,\n    fiberRef: FiberRef.FiberRef<S>,\n    predicate: Predicate<S>\n  ): Effect<[S, Option.Option<A>], E, R>\n} = effect.whenFiberRef\n\n/**\n * Executes an effect conditionally based on the value of a `Ref` that satisfies\n * a predicate.\n *\n * **Details**\n *\n * This function allows you to execute an effect only when the value of a\n * specified `Ref` meets a condition defined by a predicate. If the value\n * satisfies the predicate, the effect is executed, and the result is wrapped in\n * an `Option.some`. If the predicate is not satisfied, the effect is skipped,\n * and the result is `Option.none`. In both cases, the current value of the\n * `Ref` is included in the result.\n *\n * @since 2.0.0\n * @category Conditional Operators\n */\nexport const whenRef: {\n  <S>(ref: Ref.Ref<S>, predicate: Predicate<S>): <A, E, R>(self: Effect<A, E, R>) => Effect<[S, Option.Option<A>], E, R>\n  <A, E, R, S>(self: Effect<A, E, R>, ref: Ref.Ref<S>, predicate: Predicate<S>): Effect<[S, Option.Option<A>], E, R>\n} = effect.whenRef\n\n/**\n * Chains effects to produce new `Effect` instances, useful for combining\n * operations that depend on previous results.\n *\n * **Syntax**\n *\n * ```ts skip-type-checking\n * const flatMappedEffect = pipe(myEffect, Effect.flatMap(transformation))\n * // or\n * const flatMappedEffect = Effect.flatMap(myEffect, transformation)\n * // or\n * const flatMappedEffect = myEffect.pipe(Effect.flatMap(transformation))\n * ```\n *\n * **Details**\n *\n * `flatMap` lets you sequence effects so that the result of one effect can be\n * used in the next step. It is similar to `flatMap` used with arrays but works\n * specifically with `Effect` instances, allowing you to avoid deeply nested\n * effect structures.\n *\n * Since effects are immutable, `flatMap` always returns a new effect instead of\n * changing the original one.\n *\n * **When to Use**\n *\n * Use `flatMap` when you need to chain multiple effects, ensuring that each\n * step produces a new `Effect` while flattening any nested effects that may\n * occur.\n *\n * **Example**\n *\n * ```ts\n * import { pipe, Effect } from \"effect\"\n *\n * // Function to apply a discount safely to a transaction amount\n * const applyDiscount = (\n *   total: number,\n *   discountRate: number\n * ): Effect.Effect<number, Error> =>\n *   discountRate === 0\n *     ? Effect.fail(new Error(\"Discount rate cannot be zero\"))\n *     : Effect.succeed(total - (total * discountRate) / 100)\n *\n * // Simulated asynchronous task to fetch a transaction amount from database\n * const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))\n *\n * // Chaining the fetch and discount application using `flatMap`\n * const finalAmount = pipe(\n *   fetchTransactionAmount,\n *   Effect.flatMap((amount) => applyDiscount(amount, 5))\n * )\n *\n * Effect.runPromise(finalAmount).then(console.log)\n * // Output: 95\n * ```\n *\n * @see {@link tap} for a version that ignores the result of the effect.\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const flatMap: {\n  <A, B, E1, R1>(f: (a: A) => Effect<B, E1, R1>): <E, R>(self: Effect<A, E, R>) => Effect<B, E1 | E, R1 | R>\n  <A, E, R, B, E1, R1>(self: Effect<A, E, R>, f: (a: A) => Effect<B, E1, R1>): Effect<B, E | E1, R | R1>\n} = core.flatMap\n\n/**\n * Chains two actions, where the second action can depend on the result of the\n * first.\n *\n * **Syntax**\n *\n * ```ts skip-type-checking\n * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect))\n * // or\n * const transformedEffect = Effect.andThen(myEffect, anotherEffect)\n * // or\n * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect))\n * ```\n *\n * **When to Use**\n *\n * Use `andThen` when you need to run multiple actions in sequence, with the\n * second action depending on the result of the first. This is useful for\n * combining effects or handling computations that must happen in order.\n *\n * **Details**\n *\n * The second action can be:\n *\n * - A constant value (similar to {@link as})\n * - A function returning a value (similar to {@link map})\n * - A `Promise`\n * - A function returning a `Promise`\n * - An `Effect`\n * - A function returning an `Effect` (similar to {@link flatMap})\n *\n * **Note:** `andThen` works well with both `Option` and `Either` types,\n * treating them as effects.\n *\n * **Example** (Applying a Discount Based on Fetched Amount)\n *\n * ```ts\n * import { pipe, Effect } from \"effect\"\n *\n * // Function to apply a discount safely to a transaction amount\n * const applyDiscount = (\n *   total: number,\n *   discountRate: number\n * ): Effect.Effect<number, Error> =>\n *   discountRate === 0\n *     ? Effect.fail(new Error(\"Discount rate cannot be zero\"))\n *     : Effect.succeed(total - (total * discountRate) / 100)\n *\n * // Simulated asynchronous task to fetch a transaction amount from database\n * const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))\n *\n * // Using Effect.map and Effect.flatMap\n * const result1 = pipe(\n *   fetchTransactionAmount,\n *   Effect.map((amount) => amount * 2),\n *   Effect.flatMap((amount) => applyDiscount(amount, 5))\n * )\n *\n * Effect.runPromise(result1).then(console.log)\n * // Output: 190\n *\n * // Using Effect.andThen\n * const result2 = pipe(\n *   fetchTransactionAmount,\n *   Effect.andThen((amount) => amount * 2),\n *   Effect.andThen((amount) => applyDiscount(amount, 5))\n * )\n *\n * Effect.runPromise(result2).then(console.log)\n * // Output: 190\n * ```\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const andThen: {\n  <A, X>(\n    f: (a: NoInfer<A>) => X\n  ): <E, R>(\n    self: Effect<A, E, R>\n  ) => [X] extends [Effect<infer A1, infer E1, infer R1>] ? Effect<A1, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer A1>] ? Effect<A1, E | Cause.UnknownException, R>\n    : Effect<X, E, R>\n  <X>(\n    f: NotFunction<X>\n  ): <A, E, R>(\n    self: Effect<A, E, R>\n  ) => [X] extends [Effect<infer A1, infer E1, infer R1>] ? Effect<A1, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer A1>] ? Effect<A1, E | Cause.UnknownException, R>\n    : Effect<X, E, R>\n  <A, E, R, X>(\n    self: Effect<A, E, R>,\n    f: (a: NoInfer<A>) => X\n  ): [X] extends [Effect<infer A1, infer E1, infer R1>] ? Effect<A1, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer A1>] ? Effect<A1, E | Cause.UnknownException, R>\n    : Effect<X, E, R>\n  <A, E, R, X>(\n    self: Effect<A, E, R>,\n    f: NotFunction<X>\n  ): [X] extends [Effect<infer A1, infer E1, infer R1>] ? Effect<A1, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer A1>] ? Effect<A1, E | Cause.UnknownException, R>\n    : Effect<X, E, R>\n} = core.andThen\n\n/**\n * @since 2.0.0\n * @category Sequencing\n */\nexport const flatten: <A, E1, R1, E, R>(self: Effect<Effect<A, E1, R1>, E, R>) => Effect<A, E | E1, R | R1> =\n  core.flatten\n\n/**\n * Races two effects and returns the result of the first successful one.\n *\n * **Details**\n *\n * This function takes two effects and runs them concurrently. The first effect\n * that successfully completes will determine the result of the race, and the\n * other effect will be interrupted.\n *\n * If neither effect succeeds, the function will fail with a `Cause`\n * containing all the errors.\n *\n * **When to Use**\n *\n * This is useful when you want to run two effects concurrently, but only care\n * about the first one to succeed. It is commonly used in cases like timeouts,\n * retries, or when you want to optimize for the faster response without\n * worrying about the other effect.\n *\n * **Handling Success or Failure with Either**\n *\n * If you want to handle the result of whichever task completes first, whether\n * it succeeds or fails, you can use the `Effect.either` function. This function\n * wraps the result in an `Either` type, allowing you to see if the result\n * was a success (`Right`) or a failure (`Left`).\n *\n * **Example** (Both Tasks Succeed)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.succeed(\"task1\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task1 interrupted\"))\n * )\n * const task2 = Effect.succeed(\"task2\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task2 interrupted\"))\n * )\n *\n * const program = Effect.race(task1, task2)\n *\n * Effect.runFork(program)\n * // Output:\n * // task1 done\n * // task2 interrupted\n * ```\n *\n * **Example** (One Task Fails, One Succeeds)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.fail(\"task1\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task1 interrupted\"))\n * )\n * const task2 = Effect.succeed(\"task2\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task2 interrupted\"))\n * )\n *\n * const program = Effect.race(task1, task2)\n *\n * Effect.runFork(program)\n * // Output:\n * // task2 done\n * ```\n *\n * **Example** (Both Tasks Fail)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.fail(\"task1\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task1 interrupted\"))\n * )\n * const task2 = Effect.fail(\"task2\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task2 interrupted\"))\n * )\n *\n * const program = Effect.race(task1, task2)\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Parallel',\n * //     left: { _id: 'Cause', _tag: 'Fail', failure: 'task1' },\n * //     right: { _id: 'Cause', _tag: 'Fail', failure: 'task2' }\n * //   }\n * // }\n * ```\n *\n * **Example** (Handling Success or Failure with Either)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.fail(\"task1\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task1 interrupted\"))\n * )\n * const task2 = Effect.succeed(\"task2\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task2 interrupted\"))\n * )\n *\n * // Run both tasks concurrently, wrapping the result\n * // in Either to capture success or failure\n * const program = Effect.race(Effect.either(task1), Effect.either(task2))\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // task2 interrupted\n * // { _id: 'Either', _tag: 'Left', left: 'task1' }\n * ```\n *\n * @see {@link raceAll} for a version that handles multiple effects.\n * @see {@link raceFirst} for a version that returns the result of the first effect to complete.\n *\n * @since 2.0.0\n * @category Racing\n */\nexport const race: {\n  <A2, E2, R2>(that: Effect<A2, E2, R2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Effect<A, E, R>, that: Effect<A2, E2, R2>): Effect<A | A2, E | E2, R | R2>\n} = fiberRuntime.race\n\n/**\n * Races multiple effects and returns the first successful result.\n *\n * **Details**\n *\n * This function runs multiple effects concurrently and returns the result of\n * the first one to succeed. If one effect succeeds, the others will be\n * interrupted.\n *\n * If none of the effects succeed, the function will fail with the last error\n * encountered.\n *\n * **When to Use**\n *\n * This is useful when you want to race multiple effects, but only care about\n * the first one to succeed. It is commonly used in cases like timeouts,\n * retries, or when you want to optimize for the faster response without\n * worrying about the other effects.\n *\n * **Example** (All Tasks Succeed)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.succeed(\"task1\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task1 interrupted\"))\n * )\n * const task2 = Effect.succeed(\"task2\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task2 interrupted\"))\n * )\n *\n * const task3 = Effect.succeed(\"task3\").pipe(\n *   Effect.delay(\"150 millis\"),\n *   Effect.tap(Console.log(\"task3 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task3 interrupted\"))\n * )\n *\n * const program = Effect.raceAll([task1, task2, task3])\n *\n * Effect.runFork(program)\n * // Output:\n * // task1 done\n * // task2 interrupted\n * // task3 interrupted\n * ```\n *\n * **Example** (One Task Fails, Two Tasks Succeed)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.fail(\"task1\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task1 interrupted\"))\n * )\n * const task2 = Effect.succeed(\"task2\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task2 interrupted\"))\n * )\n *\n * const task3 = Effect.succeed(\"task3\").pipe(\n *   Effect.delay(\"150 millis\"),\n *   Effect.tap(Console.log(\"task3 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task3 interrupted\"))\n * )\n *\n * const program = Effect.raceAll([task1, task2, task3])\n *\n * Effect.runFork(program)\n * // Output:\n * // task3 done\n * // task2 interrupted\n * ```\n *\n * **Example** (All Tasks Fail)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.fail(\"task1\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task1 interrupted\"))\n * )\n * const task2 = Effect.fail(\"task2\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task2 interrupted\"))\n * )\n *\n * const task3 = Effect.fail(\"task3\").pipe(\n *   Effect.delay(\"150 millis\"),\n *   Effect.tap(Console.log(\"task3 done\")),\n *   Effect.onInterrupt(() => Console.log(\"task3 interrupted\"))\n * )\n *\n * const program = Effect.raceAll([task1, task2, task3])\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: { _id: 'Cause', _tag: 'Fail', failure: 'task2' }\n * // }\n * ```\n *\n * @see {@link race} for a version that handles only two effects.\n *\n * @since 2.0.0\n * @category Racing\n */\nexport const raceAll: <Eff extends Effect<any, any, any>>(\n  all: Iterable<Eff>\n) => Effect<Effect.Success<Eff>, Effect.Error<Eff>, Effect.Context<Eff>> = fiberRuntime.raceAll\n\n/**\n * Races two effects and returns the result of the first one to complete.\n *\n * **Details**\n *\n * This function takes two effects and runs them concurrently, returning the\n * result of the first one that completes, regardless of whether it succeeds or\n * fails.\n *\n * **When to Use**\n *\n * This function is useful when you want to race two operations, and you want to\n * proceed with whichever one finishes first, regardless of whether it succeeds\n * or fails.\n *\n * **Disconnecting Effects**\n *\n * The `Effect.raceFirst` function safely interrupts the “loser” effect once the other completes, but it will not resume until the loser is cleanly terminated.\n *\n * If you want a quicker return, you can disconnect the interrupt signal for both effects. Instead of calling:\n *\n * ```ts skip-type-checking\n * Effect.raceFirst(task1, task2)\n * ```\n *\n * You can use:\n *\n * ```ts skip-type-checking\n * Effect.raceFirst(Effect.disconnect(task1), Effect.disconnect(task2))\n * ```\n *\n * This allows both effects to complete independently while still terminating the losing effect in the background.\n *\n * **Example** (Both Tasks Succeed)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.succeed(\"task1\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() =>\n *     Console.log(\"task1 interrupted\").pipe(Effect.delay(\"100 millis\"))\n *   )\n * )\n * const task2 = Effect.succeed(\"task2\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() =>\n *     Console.log(\"task2 interrupted\").pipe(Effect.delay(\"100 millis\"))\n *   )\n * )\n *\n * const program = Effect.raceFirst(task1, task2).pipe(\n *   Effect.tap(Console.log(\"more work...\"))\n * )\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // task1 done\n * // task2 interrupted\n * // more work...\n * // { _id: 'Exit', _tag: 'Success', value: 'task1' }\n * ```\n *\n * **Example** (One Task Fails, One Succeeds)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.fail(\"task1\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() =>\n *     Console.log(\"task1 interrupted\").pipe(Effect.delay(\"100 millis\"))\n *   )\n * )\n * const task2 = Effect.succeed(\"task2\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() =>\n *     Console.log(\"task2 interrupted\").pipe(Effect.delay(\"100 millis\"))\n *   )\n * )\n *\n * const program = Effect.raceFirst(task1, task2).pipe(\n *   Effect.tap(Console.log(\"more work...\"))\n * )\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // task2 interrupted\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: { _id: 'Cause', _tag: 'Fail', failure: 'task1' }\n * // }\n * ```\n *\n * **Example** (Using Effect.disconnect for Quicker Return)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.succeed(\"task1\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() =>\n *     Console.log(\"task1 interrupted\").pipe(Effect.delay(\"100 millis\"))\n *   )\n * )\n * const task2 = Effect.succeed(\"task2\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() =>\n *     Console.log(\"task2 interrupted\").pipe(Effect.delay(\"100 millis\"))\n *   )\n * )\n *\n * // Race the two tasks with disconnect to allow quicker return\n * const program = Effect.raceFirst(\n *   Effect.disconnect(task1),\n *   Effect.disconnect(task2)\n * ).pipe(Effect.tap(Console.log(\"more work...\")))\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // task1 done\n * // more work...\n * // { _id: 'Exit', _tag: 'Success', value: 'task1' }\n * // task2 interrupted\n * ```\n *\n * @since 2.0.0\n * @category Racing\n */\nexport const raceFirst: {\n  <A2, E2, R2>(that: Effect<A2, E2, R2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Effect<A, E, R>, that: Effect<A2, E2, R2>): Effect<A | A2, E | E2, R | R2>\n} = circular.raceFirst\n\n/**\n * Races two effects and calls a finisher when the first one completes.\n *\n * **Details**\n *\n * This function runs two effects concurrently and calls a specified “finisher”\n * function once one of the effects completes, regardless of whether it succeeds\n * or fails.\n *\n * The finisher functions for each effect allow you to handle the results of\n * each effect as soon as they complete.\n *\n * The function takes two finisher callbacks, one for each effect, and allows\n * you to specify how to handle the result of the race.\n *\n * **When to Use**\n *\n * This function is useful when you need to react to the completion of either\n * effect without waiting for both to finish. It can be used whenever you want\n * to take action based on the first available result.\n *\n * **Example** (Handling Results of Concurrent Tasks)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Effect.succeed(\"task1\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Console.log(\"task1 done\")),\n *   Effect.onInterrupt(() =>\n *     Console.log(\"task1 interrupted\").pipe(Effect.delay(\"100 millis\"))\n *   )\n * )\n * const task2 = Effect.succeed(\"task2\").pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Console.log(\"task2 done\")),\n *   Effect.onInterrupt(() =>\n *     Console.log(\"task2 interrupted\").pipe(Effect.delay(\"100 millis\"))\n *   )\n * )\n *\n * const program = Effect.raceWith(task1, task2, {\n *   onSelfDone: (exit) => Console.log(`task1 exited with ${exit}`),\n *   onOtherDone: (exit) => Console.log(`task2 exited with ${exit}`)\n * })\n *\n * Effect.runFork(program)\n * // Output:\n * // task1 done\n * // task1 exited with {\n * //   \"_id\": \"Exit\",\n * //   \"_tag\": \"Success\",\n * //   \"value\": \"task1\"\n * // }\n * // task2 interrupted\n * ```\n *\n * @since 2.0.0\n * @category Racing\n */\nexport const raceWith: {\n  <A1, E1, R1, E, A, A2, E2, R2, A3, E3, R3>(\n    other: Effect<A1, E1, R1>,\n    options: {\n      readonly onSelfDone: (exit: Exit.Exit<A, E>, fiber: Fiber.Fiber<A1, E1>) => Effect<A2, E2, R2>\n      readonly onOtherDone: (exit: Exit.Exit<A1, E1>, fiber: Fiber.Fiber<A, E>) => Effect<A3, E3, R3>\n    }\n  ): <R>(self: Effect<A, E, R>) => Effect<A2 | A3, E2 | E3, R1 | R2 | R3 | R>\n  <A, E, R, A1, E1, R1, A2, E2, R2, A3, E3, R3>(\n    self: Effect<A, E, R>,\n    other: Effect<A1, E1, R1>,\n    options: {\n      readonly onSelfDone: (exit: Exit.Exit<A, E>, fiber: Fiber.Fiber<A1, E1>) => Effect<A2, E2, R2>\n      readonly onOtherDone: (exit: Exit.Exit<A1, E1>, fiber: Fiber.Fiber<A, E>) => Effect<A3, E3, R3>\n    }\n  ): Effect<A2 | A3, E2 | E3, R | R1 | R2 | R3>\n} = fiberRuntime.raceWith\n\n/**\n * Summarizes a effect by computing some value before and after execution, and\n * then combining the values to produce a summary, together with the result of\n * execution.\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const summarized: {\n  <B, E2, R2, C>(\n    summary: Effect<B, E2, R2>,\n    f: (start: B, end: B) => C\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<[C, A], E2 | E, R2 | R>\n  <A, E, R, B, E2, R2, C>(\n    self: Effect<A, E, R>,\n    summary: Effect<B, E2, R2>,\n    f: (start: B, end: B) => C\n  ): Effect<[C, A], E2 | E, R2 | R>\n} = effect.summarized\n\n/**\n * Runs a side effect with the result of an effect without changing the original\n * value.\n *\n * **Details**\n *\n * This function works similarly to `flatMap`, but it ignores the result of the\n * function passed to it. The value from the previous effect remains available\n * for the next part of the chain. Note that if the side effect fails, the\n * entire chain will fail too.\n *\n * **When to Use**\n *\n * Use this function when you want to perform a side effect, like logging or\n * tracking, without modifying the main value. This is useful when you need to\n * observe or record an action but want the original value to be passed to the\n * next step.\n *\n * **Example** (Logging a step in a pipeline)\n *\n * ```ts\n * import { Console, Effect, pipe } from \"effect\"\n *\n * // Function to apply a discount safely to a transaction amount\n * const applyDiscount = (\n *   total: number,\n *   discountRate: number\n * ): Effect.Effect<number, Error> =>\n *   discountRate === 0\n *     ? Effect.fail(new Error(\"Discount rate cannot be zero\"))\n *     : Effect.succeed(total - (total * discountRate) / 100)\n *\n * // Simulated asynchronous task to fetch a transaction amount from database\n * const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))\n *\n * const finalAmount = pipe(\n *   fetchTransactionAmount,\n *   // Log the fetched transaction amount\n *   Effect.tap((amount) => Console.log(`Apply a discount to: ${amount}`)),\n *   // `amount` is still available!\n *   Effect.flatMap((amount) => applyDiscount(amount, 5))\n * )\n *\n * Effect.runPromise(finalAmount).then(console.log)\n * // Output:\n * // Apply a discount to: 100\n * // 95\n * ```\n *\n * @see {@link flatMap} for a version that allows you to change the value.\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const tap: {\n  <A, X>(\n    f: (a: NoInfer<A>) => X\n  ): <E, R>(\n    self: Effect<A, E, R>\n  ) => [X] extends [Effect<infer _A1, infer E1, infer R1>] ? Effect<A, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer _A1>] ? Effect<A, E | Cause.UnknownException, R>\n    : Effect<A, E, R>\n  <A, X, E1, R1>(\n    f: (a: NoInfer<A>) => Effect<X, E1, R1>,\n    options: { onlyEffect: true }\n  ): <E, R>(\n    self: Effect<A, E, R>\n  ) => Effect<A, E | E1, R | R1>\n  <X>(\n    f: NotFunction<X>\n  ): <A, E, R>(\n    self: Effect<A, E, R>\n  ) => [X] extends [Effect<infer _A1, infer E1, infer R1>] ? Effect<A, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer _A1>] ? Effect<A, E | Cause.UnknownException, R>\n    : Effect<A, E, R>\n  <X, E1, R1>(\n    f: Effect<X, E1, R1>,\n    options: { onlyEffect: true }\n  ): <A, E, R>(\n    self: Effect<A, E, R>\n  ) => Effect<A, E | E1, R | R1>\n  <A, E, R, X>(\n    self: Effect<A, E, R>,\n    f: (a: NoInfer<A>) => X\n  ): [X] extends [Effect<infer _A1, infer E1, infer R1>] ? Effect<A, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer _A1>] ? Effect<A, E | Cause.UnknownException, R>\n    : Effect<A, E, R>\n  <A, E, R, X, E1, R1>(\n    self: Effect<A, E, R>,\n    f: (a: NoInfer<A>) => Effect<X, E1, R1>,\n    options: { onlyEffect: true }\n  ): Effect<A, E | E1, R | R1>\n  <A, E, R, X>(\n    self: Effect<A, E, R>,\n    f: NotFunction<X>\n  ): [X] extends [Effect<infer _A1, infer E1, infer R1>] ? Effect<A, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer _A1>] ? Effect<A, E | Cause.UnknownException, R>\n    : Effect<A, E, R>\n  <A, E, R, X, E1, R1>(\n    self: Effect<A, E, R>,\n    f: Effect<X, E1, R1>,\n    options: { onlyEffect: true }\n  ): Effect<A, E | E1, R | R1>\n} = core.tap\n\n/**\n * Allows you to inspect both success and failure outcomes of an effect and\n * perform side effects for each.\n *\n * **Details**\n *\n * This function enables you to handle both success and failure cases\n * separately, without modifying the main effect's result. It is particularly\n * useful for scenarios where you need to log, monitor, or perform additional\n * actions depending on whether the effect succeeded or failed.\n *\n * When the effect succeeds, the `onSuccess` handler is executed with the\n * success value. When the effect fails, the `onFailure` handler is executed\n * with the failure value. Both handlers can include side effects such as\n * logging or analytics, and neither modifies the original effect's output.\n *\n * If either the success or failure handler fails, the overall effect will also\n * fail.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Random, Console } from \"effect\"\n *\n * // Simulate a task that might fail\n * const task = Effect.filterOrFail(\n *   Random.nextRange(-1, 1),\n *   (n) => n >= 0,\n *   () => \"random number is negative\"\n * )\n *\n * // Use tapBoth to log both success and failure outcomes\n * const tapping = Effect.tapBoth(task, {\n *   onFailure: (error) => Console.log(`failure: ${error}`),\n *   onSuccess: (randomNumber) =>\n *     Console.log(`random number: ${randomNumber}`)\n * })\n *\n * Effect.runFork(tapping)\n * // Example Output:\n * // failure: random number is negative\n * ```\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const tapBoth: {\n  <E, X, E2, R2, A, X1, E3, R3>(\n    options: {\n      readonly onFailure: (e: NoInfer<E>) => Effect<X, E2, R2>\n      readonly onSuccess: (a: NoInfer<A>) => Effect<X1, E3, R3>\n    }\n  ): <R>(self: Effect<A, E, R>) => Effect<A, E | E2 | E3, R2 | R3 | R>\n  <A, E, R, X, E2, R2, X1, E3, R3>(\n    self: Effect<A, E, R>,\n    options: {\n      readonly onFailure: (e: E) => Effect<X, E2, R2>\n      readonly onSuccess: (a: A) => Effect<X1, E3, R3>\n    }\n  ): Effect<A, E | E2 | E3, R | R2 | R3>\n} = effect.tapBoth\n\n/**\n * Inspect severe errors or defects (non-recoverable failures) in an effect.\n *\n * **Details**\n *\n * This function is specifically designed to handle and inspect defects, which\n * are critical failures in your program, such as unexpected runtime exceptions\n * or system-level errors. Unlike normal recoverable errors, defects typically\n * indicate serious issues that cannot be addressed through standard error\n * handling.\n *\n * When a defect occurs in an effect, the function you provide to this function\n * will be executed, allowing you to log, monitor, or handle the defect in some\n * way. Importantly, this does not alter the main result of the effect. If no\n * defect occurs, the effect behaves as if this function was not used.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * // Simulate a task that fails with a recoverable error\n * const task1: Effect.Effect<number, string> = Effect.fail(\"NetworkError\")\n *\n * // tapDefect won't log anything because NetworkError is not a defect\n * const tapping1 = Effect.tapDefect(task1, (cause) =>\n *   Console.log(`defect: ${cause}`)\n * )\n *\n * Effect.runFork(tapping1)\n * // No Output\n *\n * // Simulate a severe failure in the system\n * const task2: Effect.Effect<number, string> = Effect.dieMessage(\n *   \"Something went wrong\"\n * )\n *\n * // Log the defect using tapDefect\n * const tapping2 = Effect.tapDefect(task2, (cause) =>\n *   Console.log(`defect: ${cause}`)\n * )\n *\n * Effect.runFork(tapping2)\n * // Output:\n * // defect: RuntimeException: Something went wrong\n * //   ... stack trace ...\n * ```\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const tapDefect: {\n  <X, E2, R2>(\n    f: (cause: Cause.Cause<never>) => Effect<X, E2, R2>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E2 | E, R2 | R>\n  <A, E, R, X, E2, R2>(\n    self: Effect<A, E, R>,\n    f: (cause: Cause.Cause<never>) => Effect<X, E2, R2>\n  ): Effect<A, E | E2, R | R2>\n} = effect.tapDefect\n\n/**\n * Execute a side effect on failure without modifying the original effect.\n *\n * **Details**\n *\n * This function allows you to inspect and react to the failure of an effect by\n * executing an additional effect. The failure value is passed to the provided\n * function, enabling you to log it, track it, or perform any other operation.\n * Importantly, the original failure remains intact and is re-propagated, so the\n * effect's behavior is unchanged.\n *\n * The side effect you provide is only executed when the effect fails. If the\n * effect succeeds, the function is ignored, and the success value is propagated\n * as usual.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * // Simulate a task that fails with an error\n * const task: Effect.Effect<number, string> = Effect.fail(\"NetworkError\")\n *\n * // Use tapError to log the error message when the task fails\n * const tapping = Effect.tapError(task, (error) =>\n *   Console.log(`expected error: ${error}`)\n * )\n *\n * Effect.runFork(tapping)\n * // Output:\n * // expected error: NetworkError\n * ```\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const tapError: {\n  <E, X, E2, R2>(\n    f: (e: NoInfer<E>) => Effect<X, E2, R2>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A, E | E2, R2 | R>\n  <A, E, R, X, E2, R2>(self: Effect<A, E, R>, f: (e: E) => Effect<X, E2, R2>): Effect<A, E | E2, R | R2>\n} = effect.tapError\n\n/**\n * Inspect errors matching a specific tag without altering the original effect.\n *\n * **Details**\n *\n * This function allows you to inspect and handle specific error types based on\n * their `_tag` property. It is particularly useful in applications where errors\n * are modeled with tagged types (e.g., union types with discriminating tags).\n * By targeting errors with a specific `_tag`, you can log or perform actions on\n * them while leaving the error channel and overall effect unchanged.\n *\n * If the error doesn't match the specified tag, this function does nothing, and\n * the effect proceeds as usual.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * class NetworkError {\n *   readonly _tag = \"NetworkError\"\n *   constructor(readonly statusCode: number) {}\n * }\n *\n * class ValidationError {\n *   readonly _tag = \"ValidationError\"\n *   constructor(readonly field: string) {}\n * }\n *\n * // Create a task that fails with a NetworkError\n * const task: Effect.Effect<number, NetworkError | ValidationError> =\n *   Effect.fail(new NetworkError(504))\n *\n * // Use tapErrorTag to inspect only NetworkError types and log the status code\n * const tapping = Effect.tapErrorTag(task, \"NetworkError\", (error) =>\n *   Console.log(`expected error: ${error.statusCode}`)\n * )\n *\n * Effect.runFork(tapping)\n * // Output:\n * // expected error: 504\n * ```\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const tapErrorTag: {\n  <K extends E extends { _tag: string } ? E[\"_tag\"] : never, E, A1, E1, R1>(\n    k: K,\n    f: (e: NoInfer<Extract<E, { _tag: K }>>) => Effect<A1, E1, R1>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A, E | E1, R1 | R>\n  <A, E, R, K extends E extends { _tag: string } ? E[\"_tag\"] : never, A1, E1, R1>(\n    self: Effect<A, E, R>,\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Effect<A1, E1, R1>\n  ): Effect<A, E | E1, R | R1>\n} = effect.tapErrorTag\n\n/**\n * Inspect the complete cause of an error, including failures and defects.\n *\n * **Details**\n *\n * This function provides access to the full cause of an error, including both\n * recoverable failures and irrecoverable defects. It allows you to handle, log,\n * or monitor specific error causes without modifying the result of the effect.\n * The full `Cause` object encapsulates the error and its contextual\n * information, making it useful for debugging and understanding failure\n * scenarios in complex workflows.\n *\n * The effect itself is not modified, and any errors or defects remain in the\n * error channel of the original effect.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * // Create a task that fails with a NetworkError\n * const task1: Effect.Effect<number, string> = Effect.fail(\"NetworkError\")\n *\n * const tapping1 = Effect.tapErrorCause(task1, (cause) =>\n *   Console.log(`error cause: ${cause}`)\n * )\n *\n * Effect.runFork(tapping1)\n * // Output:\n * // error cause: Error: NetworkError\n *\n * // Simulate a severe failure in the system\n * const task2: Effect.Effect<number, string> = Effect.dieMessage(\n *   \"Something went wrong\"\n * )\n *\n * const tapping2 = Effect.tapErrorCause(task2, (cause) =>\n *   Console.log(`error cause: ${cause}`)\n * )\n *\n * Effect.runFork(tapping2)\n * // Output:\n * // error cause: RuntimeException: Something went wrong\n * //   ... stack trace ...\n * ```\n *\n * @since 2.0.0\n * @category Sequencing\n */\nexport const tapErrorCause: {\n  <E, X, E2, R2>(\n    f: (cause: Cause.Cause<NoInfer<E>>) => Effect<X, E2, R2>\n  ): <A, R>(self: Effect<A, E, R>) => Effect<A, E | E2, R2 | R>\n  <A, E, R, X, E2, R2>(\n    self: Effect<A, E, R>,\n    f: (cause: Cause.Cause<E>) => Effect<X, E2, R2>\n  ): Effect<A, E | E2, R | R2>\n} = effect.tapErrorCause\n\n/**\n * Repeats an effect indefinitely until an error occurs.\n *\n * **Details**\n *\n * This function executes an effect repeatedly in an infinite loop. Each\n * iteration is executed sequentially, and the loop continues until the first\n * error occurs. If the effect succeeds, it starts over from the beginning. If\n * the effect fails, the error is propagated, and the loop stops.\n *\n * Be cautious when using this function, as it will run indefinitely unless an\n * error interrupts it. This makes it suitable for long-running processes or\n * continuous polling tasks, but you should ensure proper error handling or\n * combine it with other operators like `timeout` or `schedule` to prevent\n * unintentional infinite loops.\n *\n * @since 2.0.0\n * @category Repetition / Recursion\n */\nexport const forever: <A, E, R>(self: Effect<A, E, R>) => Effect<never, E, R> = effect.forever\n\n/**\n * Repeatedly updates a state through an effectful operation until a condition\n * is no longer met.\n *\n * **Details**\n *\n * This function provides a way to implement effectful loops, similar to a\n * `while` loop in JavaScript.\n *\n * ```ts skip-type-checking\n * let result = initial\n *\n * while (options.while(result)) {\n *   result = options.body(result)\n * }\n *\n * return result\n * ```\n *\n * It starts with an initial state, checks a\n * condition (`while`), and executes a body operation to update the state if the\n * condition evaluates to `true`. The process repeats until the condition\n * returns `false`.\n *\n * The state is passed between iterations, allowing the body operation to modify\n * it dynamically. The final state after the loop ends is returned as the result\n * of the effect.\n *\n * **When to Use**\n *\n * This is particularly useful for scenarios where looping logic involves\n * asynchronous or side-effectful operations, such as polling or iterative\n * computations that depend on external factors.\n *\n * **Example** (Effectful Iteration)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const result = Effect.iterate(\n *   // Initial result\n *   1,\n *   {\n *     // Condition to continue iterating\n *     while: (result) => result <= 5,\n *     // Operation to change the result\n *     body: (result) => Effect.succeed(result + 1)\n *   }\n * )\n *\n * Effect.runPromise(result).then(console.log)\n * // Output: 6\n * ```\n *\n * @since 2.0.0\n * @category Looping\n */\nexport const iterate: {\n  <A, B extends A, R, E>(\n    initial: A,\n    options: {\n      readonly while: Refinement<A, B>\n      readonly body: (b: B) => Effect<A, E, R>\n    }\n  ): Effect<A, E, R>\n  <A, R, E>(\n    initial: A,\n    options: {\n      readonly while: Predicate<A>\n      readonly body: (a: A) => Effect<A, E, R>\n    }\n  ): Effect<A, E, R>\n} = effect.iterate\n\n/**\n * Repeatedly executes a loop with a state, collecting results or discarding\n * them based on configuration.\n *\n * **Details**\n *\n * This function performs an effectful loop, starting with an initial state and\n * iterating as long as the `while` condition evaluates to `true`, similar to a\n * `while` loop in JavaScript.\n *\n * ```ts skip-type-checking\n * let state = initial\n * const result = []\n *\n * while (options.while(state)) {\n *   result.push(options.body(state)) // Perform the effectful operation\n *   state = options.step(state) // Update the state\n * }\n *\n * return result\n * ```\n *\n * During each iteration, the `step` function updates the state, and the `body`\n * effect is executed.\n *\n * The results of the body effect can be collected in an array or discarded\n * based on the `discard` option.\n *\n * **Discarding Intermediate Results**\n *\n * - If `discard` is `false` or not provided, the intermediate results are\n *   collected into an array and returned as the final result.\n * - If `discard` is `true`, the intermediate results are ignored, and the\n *   effect returns `void`.\n *\n * **When to Use**\n *\n * This is useful for implementing loops where you need to perform effectful\n * computations repeatedly, such as processing items in a list, generating\n * values, or performing iterative updates.\n *\n * **Example** (Looping with Collected Results)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * // A loop that runs 5 times, collecting each iteration's result\n * const result = Effect.loop(\n *   // Initial state\n *   1,\n *   {\n *     // Condition to continue looping\n *     while: (state) => state <= 5,\n *     // State update function\n *     step: (state) => state + 1,\n *     // Effect to be performed on each iteration\n *     body: (state) => Effect.succeed(state)\n *   }\n * )\n *\n * Effect.runPromise(result).then(console.log)\n * // Output: [1, 2, 3, 4, 5]\n * ```\n *\n * **Example** (Loop with Discarded Results)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const result = Effect.loop(\n *   // Initial state\n *   1,\n *   {\n *     // Condition to continue looping\n *     while: (state) => state <= 5,\n *     // State update function\n *     step: (state) => state + 1,\n *     // Effect to be performed on each iteration\n *     body: (state) => Console.log(`Currently at state ${state}`),\n *     // Discard intermediate results\n *     discard: true\n *   }\n * )\n *\n * Effect.runPromise(result).then(console.log)\n * // Output:\n * // Currently at state 1\n * // Currently at state 2\n * // Currently at state 3\n * // Currently at state 4\n * // Currently at state 5\n * // undefined\n * ```\n *\n * @since 2.0.0\n * @category Looping\n */\nexport const loop: {\n  <A, B extends A, C, E, R>(\n    initial: A,\n    options: {\n      readonly while: Refinement<A, B>\n      readonly step: (b: B) => A\n      readonly body: (b: B) => Effect<C, E, R>\n      readonly discard?: false | undefined\n    }\n  ): Effect<Array<C>, E, R>\n  <A, C, E, R>(\n    initial: A,\n    options: {\n      readonly while: (a: A) => boolean\n      readonly step: (a: A) => A\n      readonly body: (a: A) => Effect<C, E, R>\n      readonly discard?: false | undefined\n    }\n  ): Effect<Array<C>, E, R>\n  <A, B extends A, C, E, R>(\n    initial: A,\n    options: {\n      readonly while: Refinement<A, B>\n      readonly step: (b: B) => A\n      readonly body: (b: B) => Effect<C, E, R>\n      readonly discard: true\n    }\n  ): Effect<void, E, R>\n  <A, C, E, R>(\n    initial: A,\n    options: {\n      readonly while: (a: A) => boolean\n      readonly step: (a: A) => A\n      readonly body: (a: A) => Effect<C, E, R>\n      readonly discard: true\n    }\n  ): Effect<void, E, R>\n} = effect.loop\n\n/**\n * @since 2.0.0\n * @category Repetition / Recursion\n */\nexport declare namespace Repeat {\n  /**\n   * @since 2.0.0\n   * @category Repetition / Recursion\n   */\n  export type Return<R, E, A, O extends NoExcessProperties<Options<A>, O>> = Effect<\n    (O extends { schedule: Schedule.Schedule<infer Out, infer _I, infer _R> } ? Out\n      : O extends { until: Refinement<A, infer B> } ? B\n      : A),\n    | E\n    | (O extends { while: (...args: Array<any>) => Effect<infer _A, infer E, infer _R> } ? E : never)\n    | (O extends { until: (...args: Array<any>) => Effect<infer _A, infer E, infer _R> } ? E : never),\n    | R\n    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer R> } ? R : never)\n    | (O extends { while: (...args: Array<any>) => Effect<infer _A, infer _E, infer R> } ? R : never)\n    | (O extends { until: (...args: Array<any>) => Effect<infer _A, infer _E, infer R> } ? R : never)\n  > extends infer Z ? Z : never\n\n  /**\n   * @since 2.0.0\n   * @category Repetition / Recursion\n   */\n  export interface Options<A> {\n    while?: ((_: A) => boolean | Effect<boolean, any, any>) | undefined\n    until?: ((_: A) => boolean | Effect<boolean, any, any>) | undefined\n    times?: number | undefined\n    schedule?: Schedule.Schedule<any, A, any> | undefined\n  }\n}\n\n/**\n * Repeats an effect based on a specified schedule or until the first failure.\n *\n * **Details**\n *\n * This function executes an effect repeatedly according to the given schedule.\n * Each repetition occurs after the initial execution of the effect, meaning\n * that the schedule determines the number of additional repetitions. For\n * example, using `Schedule.once` will result in the effect being executed twice\n * (once initially and once as part of the repetition).\n *\n * If the effect succeeds, it is repeated according to the schedule. If it\n * fails, the repetition stops immediately, and the failure is returned.\n *\n * The schedule can also specify delays between repetitions, making it useful\n * for tasks like retrying operations with backoff, periodic execution, or\n * performing a series of dependent actions.\n *\n * You can combine schedules for more advanced repetition logic, such as adding\n * delays, limiting recursions, or dynamically adjusting based on the outcome of\n * each execution.\n *\n * **Example** (Success Example)\n *\n * ```ts\n * import { Effect, Schedule, Console } from \"effect\"\n *\n * const action = Console.log(\"success\")\n * const policy = Schedule.addDelay(Schedule.recurs(2), () => \"100 millis\")\n * const program = Effect.repeat(action, policy)\n *\n * Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`))\n * ```\n *\n * **Example** (Failure Example)\n *\n * ```ts\n * import { Effect, Schedule } from \"effect\"\n *\n * let count = 0\n *\n * // Define an async effect that simulates an action with possible failures\n * const action = Effect.async<string, string>((resume) => {\n *   if (count > 1) {\n *     console.log(\"failure\")\n *     resume(Effect.fail(\"Uh oh!\"))\n *   } else {\n *     count++\n *     console.log(\"success\")\n *     resume(Effect.succeed(\"yay!\"))\n *   }\n * })\n *\n * const policy = Schedule.addDelay(Schedule.recurs(2), () => \"100 millis\")\n * const program = Effect.repeat(action, policy)\n *\n * Effect.runPromiseExit(program).then(console.log)\n * ```\n *\n * @since 2.0.0\n * @category Repetition / Recursion\n */\nexport const repeat: {\n  <O extends NoExcessProperties<Repeat.Options<A>, O>, A>(\n    options: O\n  ): <E, R>(\n    self: Effect<A, E, R>\n  ) => Repeat.Return<R, E, A, O>\n  <B, A, R1>(\n    schedule: Schedule.Schedule<B, A, R1>\n  ): <E, R>(self: Effect<A, E, R>) => Effect<B, E, R1 | R>\n  <A, E, R, O extends NoExcessProperties<Repeat.Options<A>, O>>(\n    self: Effect<A, E, R>,\n    options: O\n  ): Repeat.Return<R, E, A, O>\n  <A, E, R, B, R1>(self: Effect<A, E, R>, schedule: Schedule.Schedule<B, A, R1>): Effect<B, E, R | R1>\n} = schedule_.repeat_combined\n\n/**\n * Repeats an effect a specified number of times or until the first failure.\n *\n * **Details**\n *\n * This function executes an effect initially and then repeats it the specified\n * number of times, as long as it succeeds. For example, calling\n * `repeatN(action, 2)` will execute `action` once initially and then repeat it\n * two additional times if there are no failures.\n *\n * If the effect fails during any repetition, the failure is returned, and no\n * further repetitions are attempted.\n *\n * **When to Use**\n *\n * This function is useful for tasks that need to be retried a fixed number of\n * times or for performing repeated actions without requiring a schedule.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const action = Console.log(\"success\")\n * const program = Effect.repeatN(action, 2)\n *\n * Effect.runPromise(program)\n * ```\n *\n * @since 2.0.0\n * @category Repetition / Recursion\n */\nexport const repeatN: {\n  (n: number): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, n: number): Effect<A, E, R>\n} = effect.repeatN\n\n/**\n * Repeats an effect with a schedule, handling failures using a custom handler.\n *\n * **Details**\n *\n * This function allows you to execute an effect repeatedly based on a specified\n * schedule. If the effect fails at any point, a custom failure handler is\n * invoked. The handler is provided with both the failure value and the output\n * of the schedule at the time of failure. This enables advanced error recovery\n * or alternative fallback logic while maintaining flexibility in how\n * repetitions are handled.\n *\n * For example, using a schedule with `recurs(2)` will allow for two additional\n * repetitions after the initial execution, provided the effect succeeds. If a\n * failure occurs during any iteration, the failure handler is invoked to handle\n * the situation.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Schedule } from \"effect\"\n *\n * let count = 0\n *\n * // Define an async effect that simulates an action with possible failures\n * const action = Effect.async<string, string>((resume) => {\n *   if (count > 1) {\n *     console.log(\"failure\")\n *     resume(Effect.fail(\"Uh oh!\"))\n *   } else {\n *     count++\n *     console.log(\"success\")\n *     resume(Effect.succeed(\"yay!\"))\n *   }\n * })\n *\n * const policy = Schedule.addDelay(\n *   Schedule.recurs(2), // Repeat for a maximum of 2 times\n *   () => \"100 millis\" // Add a delay of 100 milliseconds between repetitions\n * )\n *\n * const program = Effect.repeatOrElse(action, policy, () =>\n *   Effect.sync(() => {\n *     console.log(\"orElse\")\n *     return count - 1\n *   })\n * )\n *\n * Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`))\n * ```\n *\n * @since 2.0.0\n * @category Repetition / Recursion\n */\nexport const repeatOrElse: {\n  <R2, A, B, E, E2, R3>(\n    schedule: Schedule.Schedule<B, A, R2>,\n    orElse: (error: E, option: Option.Option<B>) => Effect<B, E2, R3>\n  ): <R>(self: Effect<A, E, R>) => Effect<B, E2, R2 | R3 | R>\n  <A, E, R, R2, B, E2, R3>(\n    self: Effect<A, E, R>,\n    schedule: Schedule.Schedule<B, A, R2>,\n    orElse: (error: E, option: Option.Option<B>) => Effect<B, E2, R3>\n  ): Effect<B, E2, R | R2 | R3>\n} = schedule_.repeatOrElse_Effect\n\n/**\n * Repeats an effect based on a specified schedule.\n *\n * **Details**\n *\n * This function allows you to execute an effect repeatedly according to a given\n * schedule. The schedule determines the timing and number of repetitions. Each\n * repetition can also depend on the decision of the schedule, providing\n * flexibility for complex workflows. This function does not modify the effect's\n * success or failure; it only controls its repetition.\n *\n * For example, you can use a schedule that recurs a specific number of times,\n * adds delays between repetitions, or customizes repetition behavior based on\n * external inputs. The effect runs initially and is repeated according to the\n * schedule.\n *\n * @see {@link scheduleFrom} for a variant that allows the schedule's decision\n * to depend on the result of this effect.\n *\n * @since 2.0.0\n * @category Repetition / Recursion\n */\nexport const schedule: {\n  <A, R2, Out>(\n    schedule: Schedule.Schedule<Out, NoInfer<A> | undefined, R2>\n  ): <E, R>(self: Effect<A, E, R>) => Effect<Out, E, R2 | R>\n  <A, E, R, R2, Out>(\n    self: Effect<A, E, R>,\n    schedule: Schedule.Schedule<Out, A | undefined, R2>\n  ): Effect<Out, E, R | R2>\n} = schedule_.schedule_Effect\n\n/**\n * Runs an effect repeatedly on a new fiber according to a given schedule.\n *\n * **Details**\n *\n * This function starts the provided effect on a new fiber and runs it\n * repeatedly based on the specified schedule. The repetitions are managed by\n * the schedule's rules, which define the timing and number of iterations. The\n * fiber is attached to the current scope, meaning it is automatically managed\n * and cleaned up when the scope is closed.\n *\n * The function returns a `RuntimeFiber` that allows you to monitor or interact\n * with the running fiber.\n *\n * **When to Use**\n *\n * This is particularly useful for concurrent execution of scheduled tasks or\n * when you want to continue processing without waiting for the repetitions to\n * complete.\n *\n * @since 2.0.0\n * @category Repetition / Recursion\n */\nexport const scheduleForked: {\n  <Out, R2>(\n    schedule: Schedule.Schedule<Out, unknown, R2>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<Fiber.RuntimeFiber<Out, E>, never, Scope.Scope | R2 | R>\n  <A, E, R, Out, R2>(\n    self: Effect<A, E, R>,\n    schedule: Schedule.Schedule<Out, unknown, R2>\n  ): Effect<Fiber.RuntimeFiber<Out, E>, never, Scope.Scope | R | R2>\n} = schedule_.scheduleForked\n\n/**\n * Runs an effect repeatedly according to a schedule, starting from a specified\n * input value.\n *\n * **Details**\n *\n * This function allows you to repeatedly execute an effect based on a schedule.\n * The schedule starts with the given `initial` input value, which is passed to\n * the first execution. Subsequent executions of the effect are controlled by\n * the schedule's rules, using the output of the previous iteration as the input\n * for the next one.\n *\n * The returned effect will complete when the schedule ends or the effect fails,\n * propagating the error.\n *\n * @since 2.0.0\n * @category Repetition / Recursion\n */\nexport const scheduleFrom: {\n  <R2, In, Out>(\n    initial: In,\n    schedule: Schedule.Schedule<Out, In, R2>\n  ): <E, R>(self: Effect<In, E, R>) => Effect<Out, E, R2 | R>\n  <In, E, R, R2, Out>(\n    self: Effect<In, E, R>,\n    initial: In,\n    schedule: Schedule.Schedule<Out, In, R2>\n  ): Effect<Out, E, R | R2>\n} = schedule_.scheduleFrom_Effect\n\n/**\n * @since 2.0.0\n * @category Repetition / Recursion\n */\nexport const whileLoop: <A, E, R>(\n  options: {\n    readonly while: LazyArg<boolean>\n    readonly body: LazyArg<Effect<A, E, R>>\n    readonly step: (a: A) => void\n  }\n) => Effect<void, E, R> = core.whileLoop\n\n/**\n * Returns a collection of all `FiberRef` values for the fiber running this\n * effect.\n *\n * @since 2.0.0\n * @category Fiber Refs\n */\nexport const getFiberRefs: Effect<FiberRefs.FiberRefs> = effect.fiberRefs\n\n/**\n * Inherits values from all `FiberRef` instances into current fiber.\n *\n * @since 2.0.0\n * @category Fiber Refs\n */\nexport const inheritFiberRefs: (childFiberRefs: FiberRefs.FiberRefs) => Effect<void> = effect.inheritFiberRefs\n\n/**\n * @since 2.0.0\n * @category Fiber Refs\n */\nexport const locally: {\n  <A>(self: FiberRef.FiberRef<A>, value: A): <B, E, R>(use: Effect<B, E, R>) => Effect<B, E, R>\n  <B, E, R, A>(use: Effect<B, E, R>, self: FiberRef.FiberRef<A>, value: A): Effect<B, E, R>\n} = core.fiberRefLocally\n\n/**\n * @since 2.0.0\n * @category Fiber Refs\n */\nexport const locallyWith: {\n  <A>(self: FiberRef.FiberRef<A>, f: (a: A) => A): <B, E, R>(use: Effect<B, E, R>) => Effect<B, E, R>\n  <B, E, R, A>(use: Effect<B, E, R>, self: FiberRef.FiberRef<A>, f: (a: A) => A): Effect<B, E, R>\n} = core.fiberRefLocallyWith\n\n/**\n * @since 2.0.0\n * @category Fiber Refs\n */\nexport const locallyScoped: {\n  <A>(value: A): (self: FiberRef.FiberRef<A>) => Effect<void, never, Scope.Scope>\n  <A>(self: FiberRef.FiberRef<A>, value: A): Effect<void, never, Scope.Scope>\n} = fiberRuntime.fiberRefLocallyScoped\n\n/**\n * @since 2.0.0\n * @category Fiber Refs\n */\nexport const locallyScopedWith: {\n  <A>(f: (a: A) => A): (self: FiberRef.FiberRef<A>) => Effect<void, never, Scope.Scope>\n  <A>(self: FiberRef.FiberRef<A>, f: (a: A) => A): Effect<void, never, Scope.Scope>\n} = fiberRuntime.fiberRefLocallyScopedWith\n\n/**\n * Applies the specified changes to the `FiberRef` values for the fiber\n * running this workflow.\n *\n * @since 2.0.0\n * @category Fiber Refs\n */\nexport const patchFiberRefs: (patch: FiberRefsPatch.FiberRefsPatch) => Effect<void> = effect.patchFiberRefs\n\n/**\n * Sets the `FiberRef` values for the fiber running this effect to the values\n * in the specified collection of `FiberRef` values.\n *\n * @since 2.0.0\n * @category Fiber Refs\n */\nexport const setFiberRefs: (fiberRefs: FiberRefs.FiberRefs) => Effect<void> = effect.setFiberRefs\n\n/**\n * Updates the `FiberRef` values for the fiber running this effect using the\n * specified function.\n *\n * @since 2.0.0\n * @category Fiber Refs\n */\nexport const updateFiberRefs: (\n  f: (fiberId: FiberId.Runtime, fiberRefs: FiberRefs.FiberRefs) => FiberRefs.FiberRefs\n) => Effect<void> = effect.updateFiberRefs\n\n/**\n * Checks if an effect has failed.\n *\n * **Details**\n *\n * This function evaluates whether an effect has resulted in a failure. It\n * returns a boolean value wrapped in an effect, with `true` indicating the\n * effect failed and `false` otherwise.\n *\n * The resulting effect cannot fail (`never` in the error channel) but retains\n * the context of the original effect.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const failure = Effect.fail(\"Uh oh!\")\n *\n * console.log(Effect.runSync(Effect.isFailure(failure)))\n * // Output: true\n *\n * const defect = Effect.dieMessage(\"BOOM!\")\n *\n * Effect.runSync(Effect.isFailure(defect))\n * // throws: BOOM!\n * ```\n *\n * @since 2.0.0\n * @category Condition Checking\n */\nexport const isFailure: <A, E, R>(self: Effect<A, E, R>) => Effect<boolean, never, R> = effect.isFailure\n\n/**\n * Checks if an effect has succeeded.\n *\n * **Details**\n *\n * This function evaluates whether an effect has resulted in a success. It\n * returns a boolean value wrapped in an effect, with `true` indicating the\n * effect succeeded and `false` otherwise.\n *\n * The resulting effect cannot fail (`never` in the error channel) but retains\n * the context of the original effect.\n *\n * @since 2.0.0\n * @category Condition Checking\n */\nexport const isSuccess: <A, E, R>(self: Effect<A, E, R>) => Effect<boolean, never, R> = effect.isSuccess\n\n/**\n * Handles both success and failure cases of an effect without performing side\n * effects.\n *\n * **Details**\n *\n * `match` lets you define custom handlers for both success and failure\n * scenarios. You provide separate functions to handle each case, allowing you\n * to process the result if the effect succeeds, or handle the error if the\n * effect fails.\n *\n * **When to Use**\n *\n * This is useful for structuring your code to respond differently to success or\n * failure without triggering side effects.\n *\n * **Example** (Handling Both Success and Failure Cases)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const success: Effect.Effect<number, Error> = Effect.succeed(42)\n *\n * const program1 = Effect.match(success, {\n *   onFailure: (error) => `failure: ${error.message}`,\n *   onSuccess: (value) => `success: ${value}`\n * })\n *\n * // Run and log the result of the successful effect\n * Effect.runPromise(program1).then(console.log)\n * // Output: \"success: 42\"\n *\n * const failure: Effect.Effect<number, Error> = Effect.fail(\n *   new Error(\"Uh oh!\")\n * )\n *\n * const program2 = Effect.match(failure, {\n *   onFailure: (error) => `failure: ${error.message}`,\n *   onSuccess: (value) => `success: ${value}`\n * })\n *\n * // Run and log the result of the failed effect\n * Effect.runPromise(program2).then(console.log)\n * // Output: \"failure: Uh oh!\"\n * ```\n *\n * @see {@link matchEffect} if you need to perform side effects in the handlers.\n *\n * @since 2.0.0\n * @category Matching\n */\nexport const match: {\n  <E, A2, A, A3>(\n    options: {\n      readonly onFailure: (error: E) => A2\n      readonly onSuccess: (value: A) => A3\n    }\n  ): <R>(self: Effect<A, E, R>) => Effect<A2 | A3, never, R>\n  <A, E, R, A2, A3>(\n    self: Effect<A, E, R>,\n    options: {\n      readonly onFailure: (error: E) => A2\n      readonly onSuccess: (value: A) => A3\n    }\n  ): Effect<A2 | A3, never, R>\n} = effect.match\n\n/**\n * Handles failures by matching the cause of failure.\n *\n * **Details**\n *\n * The `matchCause` function allows you to handle failures with access to the\n * full cause of the failure within a fiber.\n *\n * **When to Use**\n *\n * This is useful for differentiating between different types of errors, such as\n * regular failures, defects, or interruptions. You can provide specific\n * handling logic for each failure type based on the cause.\n *\n * **Example** (Handling Different Failure Causes)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const task: Effect.Effect<number, Error> = Effect.die(\"Uh oh!\")\n *\n * const program = Effect.matchCause(task, {\n *   onFailure: (cause) => {\n *     switch (cause._tag) {\n *       case \"Fail\":\n *         // Handle standard failure\n *         return `Fail: ${cause.error.message}`\n *       case \"Die\":\n *         // Handle defects (unexpected errors)\n *         return `Die: ${cause.defect}`\n *       case \"Interrupt\":\n *         // Handle interruption\n *         return `${cause.fiberId} interrupted!`\n *     }\n *     // Fallback for other causes\n *     return \"failed due to other causes\"\n *   },\n *   onSuccess: (value) =>\n *     // task completes successfully\n *     `succeeded with ${value} value`\n * })\n *\n * Effect.runPromise(program).then(console.log)\n * // Output: \"Die: Uh oh!\"\n * ```\n *\n * @see {@link matchCauseEffect} if you need to perform side effects in the\n * handlers.\n * @see {@link match} if you don't need to handle the cause of the failure.\n *\n * @since 2.0.0\n * @category Matching\n */\nexport const matchCause: {\n  <E, A2, A, A3>(\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => A2\n      readonly onSuccess: (a: A) => A3\n    }\n  ): <R>(self: Effect<A, E, R>) => Effect<A2 | A3, never, R>\n  <A, E, R, A2, A3>(\n    self: Effect<A, E, R>,\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => A2\n      readonly onSuccess: (a: A) => A3\n    }\n  ): Effect<A2 | A3, never, R>\n} = core.matchCause\n\n/**\n * Handles failures with access to the cause and allows performing side effects.\n *\n * **Details**\n *\n * The `matchCauseEffect` function works similarly to {@link matchCause}, but it\n * also allows you to perform additional side effects based on the failure\n * cause. This function provides access to the complete cause of the failure,\n * making it possible to differentiate between various failure types, and allows\n * you to respond accordingly while performing side effects (like logging or\n * other operations).\n *\n * **Example** (Handling Different Failure Causes with Side Effects)\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task: Effect.Effect<number, Error> = Effect.die(\"Uh oh!\")\n *\n * const program = Effect.matchCauseEffect(task, {\n *   onFailure: (cause) => {\n *     switch (cause._tag) {\n *       case \"Fail\":\n *         // Handle standard failure with a logged message\n *         return Console.log(`Fail: ${cause.error.message}`)\n *       case \"Die\":\n *         // Handle defects (unexpected errors) by logging the defect\n *         return Console.log(`Die: ${cause.defect}`)\n *       case \"Interrupt\":\n *         // Handle interruption and log the fiberId that was interrupted\n *         return Console.log(`${cause.fiberId} interrupted!`)\n *     }\n *     // Fallback for other causes\n *     return Console.log(\"failed due to other causes\")\n *   },\n *   onSuccess: (value) =>\n *     // Log success if the task completes successfully\n *     Console.log(`succeeded with ${value} value`)\n * })\n *\n * Effect.runPromise(program)\n * // Output: \"Die: Uh oh!\"\n * ```\n *\n * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure.\n * @see {@link matchEffect} if you don't need to handle the cause of the failure.\n *\n * @since 2.0.0\n * @category Matching\n */\nexport const matchCauseEffect: {\n  <E, A2, E2, R2, A, A3, E3, R3>(\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect<A2, E2, R2>\n      readonly onSuccess: (a: A) => Effect<A3, E3, R3>\n    }\n  ): <R>(self: Effect<A, E, R>) => Effect<A2 | A3, E2 | E3, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Effect<A, E, R>,\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect<A2, E2, R2>\n      readonly onSuccess: (a: A) => Effect<A3, E3, R3>\n    }\n  ): Effect<A2 | A3, E2 | E3, R2 | R3 | R>\n} = core.matchCauseEffect\n\n/**\n * Handles both success and failure cases of an effect, allowing for additional\n * side effects.\n *\n * **Details**\n *\n * The `matchEffect` function is similar to {@link match}, but it enables you to\n * perform side effects in the handlers for both success and failure outcomes.\n *\n * **When to Use**\n *\n * This is useful when you need to execute additional actions, like logging or\n * notifying users, based on whether an effect succeeds or fails.\n *\n * **Example** (Handling Both Success and Failure Cases with Side Effects)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const success: Effect.Effect<number, Error> = Effect.succeed(42)\n * const failure: Effect.Effect<number, Error> = Effect.fail(\n *   new Error(\"Uh oh!\")\n * )\n *\n * const program1 = Effect.matchEffect(success, {\n *   onFailure: (error) =>\n *     Effect.succeed(`failure: ${error.message}`).pipe(\n *       Effect.tap(Effect.log)\n *     ),\n *   onSuccess: (value) =>\n *     Effect.succeed(`success: ${value}`).pipe(Effect.tap(Effect.log))\n * })\n *\n * console.log(Effect.runSync(program1))\n * // Output:\n * // timestamp=... level=INFO fiber=#0 message=\"success: 42\"\n * // success: 42\n *\n * const program2 = Effect.matchEffect(failure, {\n *   onFailure: (error) =>\n *     Effect.succeed(`failure: ${error.message}`).pipe(\n *       Effect.tap(Effect.log)\n *     ),\n *   onSuccess: (value) =>\n *     Effect.succeed(`success: ${value}`).pipe(Effect.tap(Effect.log))\n * })\n *\n * console.log(Effect.runSync(program2))\n * // Output:\n * // timestamp=... level=INFO fiber=#1 message=\"failure: Uh oh!\"\n * // failure: Uh oh!\n * ```\n *\n * @see {@link match} if you don't need side effects and only want to handle the\n * result or failure.\n *\n * @since 2.0.0\n * @category Matching\n */\nexport const matchEffect: {\n  <E, A2, E2, R2, A, A3, E3, R3>(\n    options: {\n      readonly onFailure: (e: E) => Effect<A2, E2, R2>\n      readonly onSuccess: (a: A) => Effect<A3, E3, R3>\n    }\n  ): <R>(self: Effect<A, E, R>) => Effect<A2 | A3, E2 | E3, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Effect<A, E, R>,\n    options: {\n      readonly onFailure: (e: E) => Effect<A2, E2, R2>\n      readonly onSuccess: (a: A) => Effect<A3, E3, R3>\n    }\n  ): Effect<A2 | A3, E2 | E3, R2 | R3 | R>\n} = core.matchEffect\n\n/**\n * Logs one or more messages or error causes at the current log level.\n *\n * **Details**\n *\n * This function provides a simple way to log messages or error causes during\n * the execution of your effects. By default, logs are recorded at the `INFO`\n * level, but this can be adjusted using other logging utilities\n * (`Logger.withMinimumLogLevel`). Multiple items, including `Cause` instances,\n * can be logged in a single call. When logging `Cause` instances, detailed\n * error information is included in the log output.\n *\n * The log output includes useful metadata like the current timestamp, log\n * level, and fiber ID, making it suitable for debugging and tracking purposes.\n * This function does not interrupt or alter the effect's execution flow.\n *\n * **Example**\n *\n * ```ts\n * import { Cause, Effect } from \"effect\"\n *\n * const program = Effect.log(\n *   \"message1\",\n *   \"message2\",\n *   Cause.die(\"Oh no!\"),\n *   Cause.die(\"Oh uh!\")\n * )\n *\n * Effect.runFork(program)\n * // Output:\n * // timestamp=... level=INFO fiber=#0 message=message1 message=message2 cause=\"Error: Oh no!\n * // Error: Oh uh!\"\n * ```\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const log: (...message: ReadonlyArray<any>) => Effect<void, never, never> = effect.log\n\n/**\n * Logs messages or error causes at a specified log level.\n *\n * **Details**\n *\n * This function allows you to log one or more messages or error causes while\n * specifying the desired log level (e.g., DEBUG, INFO, ERROR). It provides\n * flexibility in categorizing logs based on their importance or severity,\n * making it easier to filter logs during debugging or production monitoring.\n *\n * **Example**\n *\n * ```ts\n * import { Cause, Effect, LogLevel } from \"effect\"\n *\n * const program = Effect.logWithLevel(\n *   LogLevel.Error,\n *   \"Critical error encountered\",\n *   Cause.die(\"System failure!\")\n * )\n *\n * Effect.runFork(program)\n * // Output:\n * // timestamp=... level=ERROR fiber=#0 message=Critical error encountered cause=\"Error: System failure!\"\n * ```\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const logWithLevel = (\n  level: LogLevel.LogLevel,\n  ...message: ReadonlyArray<any>\n): Effect<void> => effect.logWithLevel(level)(...message)\n\n/**\n * Logs messages at the TRACE log level.\n *\n * **Details**\n *\n * This function logs the specified messages at the TRACE level. TRACE logs are\n * typically used for very detailed diagnostic information. These messages are\n * not displayed by default. To view them, you must adjust the logging\n * configuration by setting the minimum log level to `LogLevel.Trace` using\n * `Logger.withMinimumLogLevel`.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Logger, LogLevel } from \"effect\"\n *\n * const program = Effect.logTrace(\"message1\").pipe(Logger.withMinimumLogLevel(LogLevel.Trace))\n *\n * Effect.runFork(program)\n * // timestamp=... level=TRACE fiber=#0 message=message1\n * ```\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const logTrace: (...message: ReadonlyArray<any>) => Effect<void, never, never> = effect.logTrace\n\n/**\n * Logs messages at the DEBUG log level.\n *\n * **Details**\n *\n * This function logs messages at the DEBUG level, which is typically used for\n * diagnosing application behavior during development. DEBUG messages provide\n * less detailed information than TRACE logs but are still not shown by default.\n * To view these logs, adjust the log level using `Logger.withMinimumLogLevel`.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Logger, LogLevel } from \"effect\"\n *\n * const program = Effect.logDebug(\"message1\").pipe(Logger.withMinimumLogLevel(LogLevel.Debug))\n *\n * Effect.runFork(program)\n * // timestamp=... level=DEBUG fiber=#0 message=message1\n * ```\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const logDebug: (...message: ReadonlyArray<any>) => Effect<void, never, never> = effect.logDebug\n\n/**\n * Logs messages at the INFO log level.\n *\n * **Details**\n *\n * This function logs messages at the INFO level, suitable for general\n * application events or operational messages. INFO logs are shown by default\n * and are commonly used for highlighting normal, non-error operations.\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const logInfo: (...message: ReadonlyArray<any>) => Effect<void, never, never> = effect.logInfo\n\n/**\n * Logs messages at the WARNING log level.\n *\n * **Details**\n *\n * This function logs messages at the WARNING level, suitable for highlighting\n * potential issues that are not errors but may require attention. These\n * messages indicate that something unexpected occurred or might lead to errors\n * in the future.\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const logWarning: (...message: ReadonlyArray<any>) => Effect<void, never, never> = effect.logWarning\n\n/**\n * Logs messages at the ERROR log level.\n *\n * **Details**\n *\n * This function logs messages at the ERROR level, suitable for reporting\n * application errors or failures. These logs are typically used for unexpected\n * issues that need immediate attention.\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const logError: (...message: ReadonlyArray<any>) => Effect<void, never, never> = effect.logError\n\n/**\n * Logs messages at the FATAL log level.\n *\n * **Details**\n *\n * This function logs messages at the FATAL level, suitable for reporting\n * critical errors that cause the application to terminate or stop functioning.\n * These logs are typically used for unrecoverable errors that require immediate\n * attention.\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const logFatal: (...message: ReadonlyArray<any>) => Effect<void, never, never> = effect.logFatal\n\n/**\n * Adds a log span to an effect for tracking and logging its execution duration.\n *\n * **Details**\n *\n * This function wraps an effect with a log span, providing performance\n * monitoring and debugging capabilities. The log span tracks the duration of\n * the wrapped effect and logs it with the specified label. This is particularly\n * useful when analyzing time-sensitive operations or understanding the\n * execution time of specific tasks in your application.\n *\n * The logged output will include the label and the total time taken for the\n * operation. The span information is included in the log metadata, making it\n * easy to trace performance metrics in logs.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.sleep(\"1 second\")\n *   yield* Effect.log(\"The job is finished!\")\n * }).pipe(Effect.withLogSpan(\"myspan\"))\n *\n * Effect.runFork(program)\n * // timestamp=... level=INFO fiber=#0 message=\"The job is finished!\" myspan=1011ms\n * ```\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const withLogSpan: {\n  (label: string): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(effect: Effect<A, E, R>, label: string): Effect<A, E, R>\n} = effect.withLogSpan\n\n/**\n * Adds custom annotations to log entries generated within an effect.\n *\n * **Details**\n *\n * This function allows you to enhance log messages by appending additional\n * context in the form of key-value pairs. These annotations are included in\n * every log message created during the execution of the effect, making the logs\n * more informative and easier to trace.\n *\n * The annotations can be specified as a single key-value pair or as a record of\n * multiple key-value pairs. This is particularly useful for tracking\n * operations, debugging, or associating specific metadata with logs for better\n * observability.\n *\n * The annotated key-value pairs will appear alongside the log message in the\n * output.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"message1\")\n *   yield* Effect.log(\"message2\")\n * }).pipe(Effect.annotateLogs(\"taskId\", \"1234\")) // Annotation as key/value pair\n *\n * Effect.runFork(program)\n * // timestamp=... level=INFO fiber=#0 message=message1 taskId=1234\n * // timestamp=... level=INFO fiber=#0 message=message2 taskId=1234\n * ```\n *\n * @see {@link annotateLogsScoped} to add log annotations with a limited scope.\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const annotateLogs: {\n  (key: string, value: unknown): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  (values: Record<string, unknown>): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(effect: Effect<A, E, R>, key: string, value: unknown): Effect<A, E, R>\n  <A, E, R>(effect: Effect<A, E, R>, values: Record<string, unknown>): Effect<A, E, R>\n} = effect.annotateLogs\n\n/**\n * Adds log annotations with a limited scope to enhance contextual logging.\n *\n * **Details**\n *\n * This function allows you to apply key-value annotations to log entries\n * generated within a specific scope of your effect computations. The\n * annotations are restricted to the defined `Scope`, ensuring that they are\n * only applied to logs produced during that scope. Once the scope ends, the\n * annotations are automatically removed, making it easier to manage\n * context-specific logging without affecting other parts of your application.\n *\n * The annotations can be provided as a single key-value pair or as a record of\n * multiple key-value pairs. This flexibility enables fine-grained control over\n * the additional metadata included in logs for specific tasks or operations.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"no annotations\")\n *   yield* Effect.annotateLogsScoped({ key: \"value\" })\n *   yield* Effect.log(\"message1\") // Annotation is applied to this log\n *   yield* Effect.log(\"message2\") // Annotation is applied to this log\n * }).pipe(Effect.scoped, Effect.andThen(Effect.log(\"no annotations again\")))\n *\n * Effect.runFork(program)\n * // timestamp=... level=INFO fiber=#0 message=\"no annotations\"\n * // timestamp=... level=INFO fiber=#0 message=message1 key=value\n * // timestamp=... level=INFO fiber=#0 message=message2 key=value\n * // timestamp=... level=INFO fiber=#0 message=\"no annotations again\"\n * ```\n *\n * @see {@link annotateLogs} to add custom annotations to log entries generated within an effect.\n *\n * @since 3.1.0\n * @category Logging\n */\nexport const annotateLogsScoped: {\n  (key: string, value: unknown): Effect<void, never, Scope.Scope>\n  (values: Record<string, unknown>): Effect<void, never, Scope.Scope>\n} = fiberRuntime.annotateLogsScoped\n\n/**\n * Retrieves the current log annotations for the current scope.\n *\n * **Details**\n *\n * This function provides access to the log annotations associated with the\n * current scope. Log annotations are key-value pairs that provide additional\n * context to log entries. They are often used to add metadata such as tags,\n * identifiers, or extra debugging information to logs.\n *\n * By using this function, you can inspect or utilize the annotations applied to\n * the current scope, making it easier to trace and debug specific sections of\n * your application.\n *\n * @see {@link annotateLogs} to add custom annotations to log entries generated within an effect.\n * @see {@link annotateLogsScoped} to add log annotations with a limited scope.\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const logAnnotations: Effect<HashMap.HashMap<string, unknown>> = effect.logAnnotations\n\n/**\n * Configures whether child fibers will log unhandled errors and at what log\n * level.\n *\n * **Details**\n *\n * This function allows you to control whether unhandled errors from child\n * fibers are logged and to specify the log level for these errors. By default,\n * unhandled errors are reported via the logger. However, using this function,\n * you can choose to suppress these logs by passing `Option.none` or adjust the\n * log level to a specific severity, such as `Error`, `Warning`, or `Info`.\n *\n * This configuration is scoped to the effect it is applied to, meaning the\n * changes only apply to the child fibers created within that effect's context.\n * It is especially useful when you want to reduce noise in logs or prioritize\n * certain types of errors.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Fiber, LogLevel, Option } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   const fiber = yield* Effect.fork(Effect.fail(\"Unhandled error!\"))\n *   yield* Fiber.join(fiber)\n * })\n *\n * Effect.runFork(program.pipe(Effect.withUnhandledErrorLogLevel(Option.some(LogLevel.Error))))\n * // Output:\n * // timestamp=... level=ERROR fiber=#1 message=\"Fiber terminated with an unhandled error\" cause=\"Error: Unhandled error!\"\n * ```\n *\n * @since 2.0.0\n * @category Logging\n */\nexport const withUnhandledErrorLogLevel: {\n  (level: Option.Option<LogLevel.LogLevel>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, level: Option.Option<LogLevel.LogLevel>): Effect<A, E, R>\n} = core.withUnhandledErrorLogLevel\n\n/**\n * Conditionally executes an effect based on the specified log level and currently enabled log level.\n *\n * **Details**\n *\n * This function runs the provided effect only if the specified log level is\n * enabled. If the log level is enabled, the effect is executed and its result\n * is wrapped in `Some`. If the log level is not enabled, the effect is not\n * executed and `None` is returned.\n *\n * This function is useful for conditionally executing logging-related effects\n * or other operations that depend on the current log level configuration.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Logger, LogLevel } from \"effect\"\n *\n * const program = Effect.gen(function* () {\n *   yield* Effect.whenLogLevel(Effect.logTrace(\"message1\"), LogLevel.Trace); // returns `None`\n *   yield* Effect.whenLogLevel(Effect.logDebug(\"message2\"), LogLevel.Debug); // returns `Some`\n * }).pipe(Logger.withMinimumLogLevel(LogLevel.Debug));\n *\n * Effect.runFork(program)\n * // timestamp=... level=DEBUG fiber=#0 message=message2\n * ```\n *\n * @see {@link FiberRef.currentMinimumLogLevel} to retrieve the current minimum log level.\n *\n * @since 3.13.0\n * @category Logging\n */\nexport const whenLogLevel: {\n  (level: LogLevel.LogLevel | LogLevel.Literal): <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E, R>\n  <A, E, R>(self: Effect<A, E, R>, level: LogLevel.LogLevel | LogLevel.Literal): Effect<Option.Option<A>, E, R>\n} = fiberRuntime.whenLogLevel\n\n/**\n * Converts an effect's failure into a fiber termination, removing the error\n * from the effect's type.\n *\n * **Details**\n *\n * The `orDie` function is used when you encounter errors that you do not want\n * to handle or recover from. It removes the error type from the effect and\n * ensures that any failure will terminate the fiber. This is useful for\n * propagating failures as defects, signaling that they should not be handled\n * within the effect.\n *\n * **When to Use*\n *\n * Use `orDie` when failures should be treated as unrecoverable defects and no\n * error handling is required.\n *\n * **Example** (Propagating an Error as a Defect)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const divide = (a: number, b: number) =>\n *   b === 0\n *     ? Effect.fail(new Error(\"Cannot divide by zero\"))\n *     : Effect.succeed(a / b)\n *\n * //      ┌─── Effect<number, never, never>\n * //      ▼\n * const program = Effect.orDie(divide(1, 0))\n *\n * Effect.runPromise(program).catch(console.error)\n * // Output:\n * // (FiberFailure) Error: Cannot divide by zero\n * //   ...stack trace...\n * ```\n *\n * @see {@link orDieWith} if you need to customize the error.\n *\n * @since 2.0.0\n * @category Converting Failures to Defects\n */\nexport const orDie: <A, E, R>(self: Effect<A, E, R>) => Effect<A, never, R> = core.orDie\n\n/**\n * Converts an effect's failure into a fiber termination with a custom error.\n *\n * **Details**\n *\n * The `orDieWith` function behaves like {@link orDie}, but it allows you to provide a mapping\n * function to transform the error before terminating the fiber. This is useful for cases where\n * you want to include a more detailed or user-friendly error when the failure is propagated\n * as a defect.\n *\n * **When to Use**\n *\n * Use `orDieWith` when failures should terminate the fiber as defects, and you want to customize\n * the error for clarity or debugging purposes.\n *\n * **Example** (Customizing Defect)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const divide = (a: number, b: number) =>\n *   b === 0\n *     ? Effect.fail(new Error(\"Cannot divide by zero\"))\n *     : Effect.succeed(a / b)\n *\n * //      ┌─── Effect<number, never, never>\n * //      ▼\n * const program = Effect.orDieWith(\n *   divide(1, 0),\n *   (error) => new Error(`defect: ${error.message}`)\n * )\n *\n * Effect.runPromise(program).catch(console.error)\n * // Output:\n * // (FiberFailure) Error: defect: Cannot divide by zero\n * //   ...stack trace...\n * ```\n *\n * @see {@link orDie} if you don't need to customize the error.\n *\n * @since 2.0.0\n * @category Converting Failures to Defects\n */\nexport const orDieWith: {\n  <E>(f: (error: E) => unknown): <A, R>(self: Effect<A, E, R>) => Effect<A, never, R>\n  <A, E, R>(self: Effect<A, E, R>, f: (error: E) => unknown): Effect<A, never, R>\n} = core.orDieWith\n\n/**\n * Attempts one effect, and if it fails, falls back to another effect.\n *\n * **Details**\n *\n * This function allows you to try executing an effect, and if it fails\n * (produces an error), a fallback effect is executed instead. The fallback\n * effect is defined as a lazy argument, meaning it will only be evaluated if\n * the first effect fails. This provides a way to recover from errors by\n * specifying an alternative path of execution.\n *\n * The error type of the resulting effect will be that of the fallback effect,\n * as the first effect's error is replaced when the fallback is executed.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const success = Effect.succeed(\"success\")\n * const failure = Effect.fail(\"failure\")\n * const fallback = Effect.succeed(\"fallback\")\n *\n * // Try the success effect first, fallback is not used\n * const program1 = Effect.orElse(success, () => fallback)\n * console.log(Effect.runSync(program1))\n * // Output: \"success\"\n *\n * // Try the failure effect first, fallback is used\n * const program2 = Effect.orElse(failure, () => fallback)\n * console.log(Effect.runSync(program2))\n * // Output: \"fallback\"\n * ```\n *\n * @see {@link catchAll} if you need to access the error in the fallback effect.\n *\n * @since 2.0.0\n * @category Fallback\n */\nexport const orElse: {\n  <A2, E2, R2>(that: LazyArg<Effect<A2, E2, R2>>): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Effect<A, E, R>, that: LazyArg<Effect<A2, E2, R2>>): Effect<A2 | A, E2, R2 | R>\n} = core.orElse\n\n/**\n * Replaces the failure of an effect with a custom failure value.\n *\n * **Details**\n *\n * This function allows you to handle the failure of an effect by replacing it\n * with a predefined failure value. If the effect fails, the new failure value\n * provided by the `evaluate` function will be returned instead of the original\n * failure. If the effect succeeds, the original success value is returned\n * unchanged.\n *\n * **When to Use**\n *\n * This is particularly useful when you want to standardize error handling or\n * provide a consistent failure value for specific operations. It simplifies\n * error management by ensuring that all failures are replaced with a controlled\n * alternative.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const validate = (age: number): Effect.Effect<number, string> => {\n *   if (age < 0) {\n *     return Effect.fail(\"NegativeAgeError\")\n *   } else if (age < 18) {\n *     return Effect.fail(\"IllegalAgeError\")\n *   } else {\n *     return Effect.succeed(age)\n *   }\n * }\n *\n * const program = Effect.orElseFail(validate(-1), () => \"invalid age\")\n *\n * console.log(Effect.runSyncExit(program))\n * // Output:\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: { _id: 'Cause', _tag: 'Fail', failure: 'invalid age' }\n * // }\n * ```\n *\n * @see {@link mapError} if you need to access the error to transform it.\n *\n * @since 2.0.0\n * @category Fallback\n */\nexport const orElseFail: {\n  <E2>(evaluate: LazyArg<E2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E2, R>\n  <A, E, R, E2>(self: Effect<A, E, R>, evaluate: LazyArg<E2>): Effect<A, E2, R>\n} = effect.orElseFail\n\n/**\n * Ensures the effect always succeeds by replacing failures with a default\n * success value.\n *\n * **Details**\n *\n * This function transforms an effect that may fail into one that cannot fail by\n * replacing any failure with a provided success value. If the original effect\n * fails, the failure is \"swallowed,\" and the specified success value is\n * returned instead. If the original effect succeeds, its value remains\n * unchanged.\n *\n * **When to Use**\n *\n * This is especially useful for providing default values in case of failure,\n * ensuring that an effect always completes successfully. By using this\n * function, you can avoid the need for complex error handling and guarantee a\n * fallback result.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const validate = (age: number): Effect.Effect<number, string> => {\n *   if (age < 0) {\n *     return Effect.fail(\"NegativeAgeError\")\n *   } else if (age < 18) {\n *     return Effect.fail(\"IllegalAgeError\")\n *   } else {\n *     return Effect.succeed(age)\n *   }\n * }\n *\n * const program = Effect.orElseSucceed(validate(-1), () => 18)\n *\n * console.log(Effect.runSyncExit(program))\n * // Output:\n * // { _id: 'Exit', _tag: 'Success', value: 18 }\n * ```\n *\n * @since 2.0.0\n * @category Fallback\n */\nexport const orElseSucceed: {\n  <A2>(evaluate: LazyArg<A2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, never, R>\n  <A, E, R, A2>(self: Effect<A, E, R>, evaluate: LazyArg<A2>): Effect<A | A2, never, R>\n} = effect.orElseSucceed\n\n/**\n * Runs a sequence of effects and returns the result of the first successful\n * one.\n *\n * **Details**\n *\n * This function allows you to execute a collection of effects in sequence,\n * stopping at the first success. If an effect succeeds, its result is\n * immediately returned, and no further effects in the sequence are executed.\n * However, if all the effects fail, the function will return the error of the\n * last effect.\n *\n * The execution is sequential, meaning that effects are evaluated one at a time\n * in the order they are provided. This ensures predictable behavior and avoids\n * unnecessary computations.\n *\n * If the collection of effects is empty, an `IllegalArgumentException` is\n * thrown, indicating that the operation is invalid without any effects to try.\n *\n * **When to Use**\n *\n * This is particularly useful when you have multiple fallback strategies or\n * alternative sources to obtain a result, such as attempting multiple APIs,\n * retrieving configurations, or accessing resources in a prioritized manner.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * interface Config {\n *   host: string\n *   port: number\n *   apiKey: string\n * }\n *\n * // Create a configuration object with sample values\n * const makeConfig = (name: string): Config => ({\n *   host: `${name}.example.com`,\n *   port: 8080,\n *   apiKey: \"12345-abcde\"\n * })\n *\n * // Simulate retrieving configuration from a remote node\n * const remoteConfig = (name: string): Effect.Effect<Config, Error> =>\n *   Effect.gen(function* () {\n *     // Simulate node3 being the only one with available config\n *     if (name === \"node3\") {\n *       yield* Console.log(`Config for ${name} found`)\n *       return makeConfig(name)\n *     } else {\n *       yield* Console.log(`Unavailable config for ${name}`)\n *       return yield* Effect.fail(new Error(`Config not found for ${name}`))\n *     }\n *   })\n *\n * // Define the master configuration and potential fallback nodes\n * const masterConfig = remoteConfig(\"master\")\n * const nodeConfigs = [\"node1\", \"node2\", \"node3\", \"node4\"].map(remoteConfig)\n *\n * // Attempt to find a working configuration,\n * // starting with the master and then falling back to other nodes\n * const config = Effect.firstSuccessOf([masterConfig, ...nodeConfigs])\n *\n * // Run the effect to retrieve the configuration\n * const result = Effect.runSync(config)\n *\n * console.log(result)\n * // Output:\n * // Unavailable config for master\n * // Unavailable config for node1\n * // Unavailable config for node2\n * // Config for node3 found\n * // { host: 'node3.example.com', port: 8080, apiKey: '12345-abcde' }\n * ```\n *\n * @since 2.0.0\n * @category Fallback\n */\nexport const firstSuccessOf: <Eff extends Effect<any, any, any>>(\n  effects: Iterable<Eff>\n) => Effect<Effect.Success<Eff>, Effect.Error<Eff>, Effect.Context<Eff>> = effect.firstSuccessOf\n\n/**\n * Retrieves the `Random` service from the context.\n *\n * @since 2.0.0\n * @category Random\n */\nexport const random: Effect<Random.Random> = effect.random\n\n/**\n * Retrieves the `Random` service from the context and uses it to run the\n * specified effect.\n *\n * @since 2.0.0\n * @category Random\n */\nexport const randomWith: <A, E, R>(f: (random: Random.Random) => Effect<A, E, R>) => Effect<A, E, R> =\n  defaultServices.randomWith\n\n/**\n * Executes the specified effect with the specified implementation of the\n * `Random` service.\n *\n * @since 2.0.0\n * @category Random\n */\nexport const withRandom: {\n  <X extends Random.Random>(value: X): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <X extends Random.Random, A, E, R>(effect: Effect<A, E, R>, value: X): Effect<A, E, R>\n} = defaultServices.withRandom\n\n/**\n * Executes the specified effect with a `Random` service that cycles through\n * a provided array of values.\n *\n * @example\n * ```ts\n * import { Effect, Random } from \"effect\"\n *\n * Effect.gen(function*() {\n *   console.log(yield* Random.next) // 0.2\n *   console.log(yield* Random.next) // 0.5\n *   console.log(yield* Random.next) // 0.8\n * }).pipe(Effect.withRandomFixed([0.2, 0.5, 0.8]))\n * ```\n *\n * @since 3.11.0\n * @category Random\n */\nexport const withRandomFixed: {\n  <T extends RA.NonEmptyArray<any>>(values: T): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <T extends RA.NonEmptyArray<any>, A, E, R>(effect: Effect<A, E, R>, values: T): Effect<A, E, R>\n} = dual(\n  2,\n  <T extends RA.NonEmptyArray<any>, A, E, R>(effect: Effect<A, E, R>, values: T): Effect<A, E, R> =>\n    withRandom(effect, Random.fixed(values))\n)\n\n/**\n * Sets the implementation of the `Random` service to the specified value and\n * restores it to its original value when the scope is closed.\n *\n * @since 2.0.0\n * @category Random\n */\nexport const withRandomScoped: <A extends Random.Random>(value: A) => Effect<void, never, Scope.Scope> =\n  fiberRuntime.withRandomScoped\n\n/**\n * Returns an effect that accesses the runtime, which can be used to (unsafely)\n * execute tasks.\n *\n * **When to Use**\n *\n * This is useful for integration with legacy code that must call back into\n * Effect code.\n *\n * @since 2.0.0\n * @category Runtime\n */\nexport const runtime: <R = never>() => Effect<Runtime.Runtime<R>, never, R> = runtime_.runtime\n\n/**\n * Retrieves an effect that succeeds with the current runtime flags, which\n * govern behavior and features of the runtime system.\n *\n * @since 2.0.0\n * @category Runtime\n */\nexport const getRuntimeFlags: Effect<RuntimeFlags.RuntimeFlags> = core.runtimeFlags\n\n/**\n * @since 2.0.0\n * @category Runtime\n */\nexport const patchRuntimeFlags: (patch: RuntimeFlagsPatch.RuntimeFlagsPatch) => Effect<void> = core.updateRuntimeFlags\n\n/**\n * @since 2.0.0\n * @category Runtime\n */\nexport const withRuntimeFlagsPatch: {\n  (update: RuntimeFlagsPatch.RuntimeFlagsPatch): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, update: RuntimeFlagsPatch.RuntimeFlagsPatch): Effect<A, E, R>\n} = core.withRuntimeFlags\n\n/**\n * @since 2.0.0\n * @category Runtime\n */\nexport const withRuntimeFlagsPatchScoped: (\n  update: RuntimeFlagsPatch.RuntimeFlagsPatch\n) => Effect<void, never, Scope.Scope> = fiberRuntime.withRuntimeFlagsScoped\n\n/**\n * Tags each metric in an effect with specific key-value pairs.\n *\n * **Details**\n *\n * This function allows you to tag all metrics in an effect with a set of\n * key-value pairs or a single key-value pair. Tags help you add metadata to\n * metrics, making it easier to filter and categorize them in monitoring\n * systems. The provided tags will apply to all metrics generated within the\n * effect's scope.\n *\n * @since 2.0.0\n * @category Metrics\n */\nexport const tagMetrics: {\n  (key: string, value: string): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  (values: Record<string, string>): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(effect: Effect<A, E, R>, key: string, value: string): Effect<A, E, R>\n  <A, E, R>(effect: Effect<A, E, R>, values: Record<string, string>): Effect<A, E, R>\n} = effect.tagMetrics\n\n/**\n * Adds labels to metrics within an effect using `MetricLabel` objects.\n *\n * **Details**\n *\n * This function allows you to label metrics using `MetricLabel` objects. Labels\n * help add structured metadata to metrics for categorization and filtering in\n * monitoring systems. The provided labels will apply to all metrics within the\n * effect's execution.\n *\n * @since 2.0.0\n * @category Metrics\n */\nexport const labelMetrics: {\n  (labels: Iterable<MetricLabel.MetricLabel>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, labels: Iterable<MetricLabel.MetricLabel>): Effect<A, E, R>\n} = effect.labelMetrics\n\n/**\n * Tags metrics within a scope with a specific key-value pair.\n *\n * **Details**\n *\n * This function tags all metrics within a scope with the provided key-value\n * pair. Once the scope is closed, the tag is automatically removed. This is\n * useful for applying temporary context-specific tags to metrics during scoped\n * operations.\n *\n * @since 2.0.0\n * @category Metrics\n */\nexport const tagMetricsScoped: (key: string, value: string) => Effect<void, never, Scope.Scope> =\n  fiberRuntime.tagMetricsScoped\n\n/**\n * Adds labels to metrics within a scope using `MetricLabel` objects.\n *\n * **Details**\n *\n * This function allows you to apply labels to all metrics generated within a\n * specific scope using an array of `MetricLabel` objects. These labels provide\n * additional metadata to metrics, which can be used for categorization,\n * filtering, or monitoring purposes. The labels are scoped and will be removed\n * automatically once the scope is closed, ensuring they are only applied\n * temporarily within the defined context.\n *\n * @since 2.0.0\n * @category Metrics\n */\nexport const labelMetricsScoped: (\n  labels: ReadonlyArray<MetricLabel.MetricLabel>\n) => Effect<void, never, Scope.Scope> = fiberRuntime.labelMetricsScoped\n\n/**\n * Retrieves the metric labels associated with the current scope.\n *\n * @since 2.0.0\n * @category Metrics\n */\nexport const metricLabels: Effect<ReadonlyArray<MetricLabel.MetricLabel>> = core.metricLabels\n\n/**\n * Associates a metric with the current effect, updating it as the effect progresses.\n *\n * @since 2.0.0\n * @category Metrics\n */\nexport const withMetric: {\n  <Type, In, Out>(metric: Metric.Metric<Type, In, Out>): <A extends In, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A extends In, E, R, Type, In, Out>(self: Effect<A, E, R>, metric: Metric.Metric<Type, In, Out>): Effect<A, E, R>\n} = effect.withMetric\n\n/**\n * @category Semaphore\n * @since 2.0.0\n */\nexport interface Permit {\n  readonly index: number\n}\n\n/**\n * A semaphore is a synchronization mechanism used to manage access to a shared\n * resource. In Effect, semaphores help control resource access or coordinate\n * tasks within asynchronous, concurrent operations.\n *\n * A semaphore acts as a generalized mutex, allowing a set number of permits to\n * be held and released concurrently. Permits act like tickets, giving tasks or\n * fibers controlled access to a shared resource. When no permits are available,\n * tasks trying to acquire one will wait until a permit is released.\n *\n * @category Semaphore\n * @since 2.0.0\n */\nexport interface Semaphore {\n  /**\n   * Adjusts the number of permits available in the semaphore.\n   */\n  resize(permits: number): Effect<void>\n\n  /**\n   * Runs an effect with the given number of permits and releases the permits\n   * when the effect completes.\n   *\n   * **Details**\n   *\n   * This function acquires the specified number of permits before executing\n   * the provided effect. Once the effect finishes, the permits are released.\n   * If insufficient permits are available, the function will wait until they\n   * are released by other tasks.\n   */\n  withPermits(permits: number): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n\n  /**\n   * Runs an effect only if the specified number of permits are immediately\n   * available.\n   *\n   * **Details**\n   *\n   * This function attempts to acquire the specified number of permits. If they\n   * are available, it runs the effect and releases the permits after the effect\n   * completes. If permits are not available, the effect does not execute, and\n   * the result is `Option.none`.\n   */\n  withPermitsIfAvailable(permits: number): <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E, R>\n\n  /**\n   * Acquires the specified number of permits and returns the resulting\n   * available permits, suspending the task if they are not yet available.\n   * Concurrent pending `take` calls are processed in a first-in, first-out manner.\n   */\n  take(permits: number): Effect<number>\n\n  /**\n   * Releases the specified number of permits and returns the resulting\n   * available permits.\n   */\n  release(permits: number): Effect<number>\n\n  /**\n   * Releases all permits held by this semaphore and returns the resulting available permits.\n   */\n  releaseAll: Effect<number>\n}\n\n/**\n * Unsafely creates a new Semaphore.\n *\n * @since 2.0.0\n * @category Semaphore\n */\nexport const unsafeMakeSemaphore: (permits: number) => Semaphore = circular.unsafeMakeSemaphore\n\n/**\n * Creates a new semaphore with the specified number of permits.\n *\n * **Details**\n *\n * This function initializes a semaphore that controls concurrent access to a\n * shared resource. The number of permits determines how many tasks can access\n * the resource concurrently.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * // Create a semaphore with 3 permits\n * const mutex = Effect.makeSemaphore(3)\n * ```\n *\n * @since 2.0.0\n * @category Semaphore\n */\nexport const makeSemaphore: (permits: number) => Effect<Semaphore> = circular.makeSemaphore\n\n/**\n * A `Latch` is a synchronization primitive that allows you to control the\n * execution of fibers based on an open or closed state. It acts as a gate,\n * where fibers can wait for the latch to open before proceeding.\n *\n * **Details**\n *\n * A `Latch` can be in one of two states: open or closed. Fibers can:\n * - Wait for the latch to open using `await`.\n * - Proceed only when the latch is open using `whenOpen`.\n * - Open the latch to release all waiting fibers using `open`.\n * - Close the latch to block fibers using `close`.\n *\n * Additionally, fibers can be released without changing the state of the latch\n * using `release`.\n *\n * @category Latch\n * @since 3.8.0\n */\nexport interface Latch extends Effect<void> {\n  /**\n   * Opens the latch, releasing all fibers waiting on it.\n   *\n   * **Details**\n   *\n   * Once the latch is opened, it remains open. Any fibers waiting on `await`\n   * will be released and can continue execution.\n   */\n  readonly open: Effect<void>\n\n  /**\n   * Opens the latch, releasing all fibers waiting on it.\n   *\n   * **Details**\n   *\n   * Once the latch is opened, it remains open. Any fibers waiting on `await`\n   * will be released and can continue execution.\n   */\n  readonly unsafeOpen: () => void\n\n  /**\n   * Releases all fibers waiting on the latch without opening it.\n   *\n   * **Details**\n   *\n   * This function lets waiting fibers proceed without permanently changing the\n   * state of the latch.\n   */\n  readonly release: Effect<void>\n\n  /**\n   * Waits for the latch to be opened.\n   *\n   * **Details**\n   *\n   * If the latch is already open, this effect completes immediately. Otherwise,\n   * it suspends the fiber until the latch is opened.\n   */\n  readonly await: Effect<void>\n\n  /**\n   * Closes the latch, blocking fibers from proceeding.\n   *\n   * **Details**\n   *\n   * This operation puts the latch into a closed state, requiring it to be\n   * reopened before waiting fibers can proceed.\n   */\n  readonly close: Effect<void>\n\n  /**\n   * Unsafely closes the latch, blocking fibers without effect guarantees.\n   *\n   * **Details**\n   *\n   * Use this operation cautiously, as it does not run within an effect context\n   * and bypasses runtime guarantees.\n   */\n  readonly unsafeClose: () => void\n\n  /**\n   * Runs the given effect only when the latch is open.\n   *\n   * **Details**\n   *\n   * This function ensures that the provided effect executes only if the latch\n   * is open. If the latch is closed, the fiber will wait until it opens.\n   */\n  readonly whenOpen: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: LatchUnify<this>\n  readonly [Unify.ignoreSymbol]?: LatchUnifyIgnore\n}\n\n/**\n * @category Models\n * @since 3.8.0\n */\nexport interface LatchUnify<A extends { [Unify.typeSymbol]?: any }> extends EffectUnify<A> {\n  Latch?: () => Latch\n}\n\n/**\n * @category Models\n * @since 3.8.0\n */\nexport interface LatchUnifyIgnore extends EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * @category Latch\n * @since 3.8.0\n */\nexport const unsafeMakeLatch: (open?: boolean | undefined) => Latch = circular.unsafeMakeLatch\n\n/**\n * Creates a new `Latch`, starting in the specified state.\n *\n * **Details**\n *\n * This function initializes a `Latch` safely, ensuring proper runtime\n * guarantees. By default, the latch starts in the closed state.\n *\n * **Example**\n *\n * ```ts\n * import { Console, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   // Create a latch, starting in the closed state\n *   const latch = yield* Effect.makeLatch(false)\n *\n *   // Fork a fiber that logs \"open sesame\" when the latch is opened\n *   const fiber = yield* Console.log(\"open sesame\").pipe(\n *     latch.whenOpen,\n *     Effect.fork\n *   )\n *\n *   yield* Effect.sleep(\"1 second\")\n *\n *   // Open the latch\n *   yield* latch.open\n *   yield* fiber.await\n * })\n *\n * Effect.runFork(program)\n * // Output: open sesame (after 1 second)\n * ```\n *\n * @category Latch\n * @since 3.8.0\n */\nexport const makeLatch: (open?: boolean | undefined) => Effect<Latch, never, never> = circular.makeLatch\n\n/**\n * Runs an effect in the background, returning a fiber that can be observed or\n * interrupted.\n *\n * Unless you specifically need a `Promise` or synchronous operation, `runFork`\n * is a good default choice.\n *\n * **Details**\n *\n * This function is the foundational way to execute an effect in the background.\n * It creates a \"fiber,\" a lightweight, cooperative thread of execution that can\n * be observed (to access its result), interrupted, or joined. Fibers are useful\n * for concurrent programming and allow effects to run independently of the main\n * program flow.\n *\n * Once the effect is running in a fiber, you can monitor its progress, cancel\n * it if necessary, or retrieve its result when it completes. If the effect\n * fails, the fiber will propagate the failure, which you can observe and\n * handle.\n *\n * **When to Use**\n *\n * Use this function when you need to run an effect in the background,\n * especially if the effect is long-running or performs periodic tasks. It's\n * suitable for tasks that need to run independently but might still need\n * observation or management, like logging, monitoring, or scheduled tasks.\n *\n * This function is ideal if you don't need the result immediately or if the\n * effect is part of a larger concurrent workflow.\n *\n * **Example** (Running an Effect in the Background)\n *\n * ```ts\n * import { Effect, Console, Schedule, Fiber } from \"effect\"\n *\n * //      ┌─── Effect<number, never, never>\n * //      ▼\n * const program = Effect.repeat(\n *   Console.log(\"running...\"),\n *   Schedule.spaced(\"200 millis\")\n * )\n *\n * //      ┌─── RuntimeFiber<number, never>\n * //      ▼\n * const fiber = Effect.runFork(program)\n *\n * setTimeout(() => {\n *   Effect.runFork(Fiber.interrupt(fiber))\n * }, 500)\n * ```\n *\n * @since 2.0.0\n * @category Running Effects\n */\nexport const runFork: <A, E>(\n  effect: Effect<A, E>,\n  options?: Runtime.RunForkOptions\n) => Fiber.RuntimeFiber<A, E> = runtime_.unsafeForkEffect\n\n/**\n * Executes an effect asynchronously and handles the result using a callback.\n *\n * **Details**\n *\n * This function runs an effect asynchronously and passes the result (`Exit`) to\n * a specified callback. The callback is invoked with the outcome of the effect:\n * - On success, the callback receives the successful result.\n * - On failure, the callback receives the failure information.\n *\n * **When to Use**\n *\n * This function is effectful and should only be invoked at the edges of your\n * program.\n *\n * @since 2.0.0\n * @category Running Effects\n */\nexport const runCallback: <A, E>(\n  effect: Effect<A, E>,\n  options?: Runtime.RunCallbackOptions<A, E> | undefined\n) => Runtime.Cancel<A, E> = runtime_.unsafeRunEffect\n\n/**\n * Executes an effect and returns the result as a `Promise`.\n *\n * **Details**\n *\n * This function runs an effect and converts its result into a `Promise`. If the\n * effect succeeds, the `Promise` will resolve with the successful result. If\n * the effect fails, the `Promise` will reject with an error, which includes the\n * failure details of the effect.\n *\n * The optional `options` parameter allows you to pass an `AbortSignal` for\n * cancellation, enabling more fine-grained control over asynchronous tasks.\n *\n * **When to Use**\n *\n * Use this function when you need to execute an effect and work with its result\n * in a promise-based system, such as when integrating with third-party\n * libraries that expect `Promise` results.\n *\n * **Example** (Running a Successful Effect as a Promise)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * Effect.runPromise(Effect.succeed(1)).then(console.log)\n * // Output: 1\n * ```\n *\n * **Example** (Handling a Failing Effect as a Rejected Promise)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * Effect.runPromise(Effect.fail(\"my error\")).catch(console.error)\n * // Output:\n * // (FiberFailure) Error: my error\n * ```\n *\n * @see {@link runPromiseExit} for a version that returns an `Exit` type instead\n * of rejecting.\n *\n * @since 2.0.0\n * @category Running Effects\n */\nexport const runPromise: <A, E>(\n  effect: Effect<A, E, never>,\n  options?: { readonly signal?: AbortSignal | undefined } | undefined\n) => Promise<A> = runtime_.unsafeRunPromiseEffect\n\n/**\n * Runs an effect and returns a `Promise` that resolves to an `Exit`,\n * representing the outcome.\n *\n * **Details**\n *\n * This function executes an effect and resolves to an `Exit` object. The `Exit`\n * type provides detailed information about the result of the effect:\n * - If the effect succeeds, the `Exit` will be of type `Success` and include\n *   the value produced by the effect.\n * - If the effect fails, the `Exit` will be of type `Failure` and contain a\n *   `Cause` object, detailing the failure.\n *\n * Using this function allows you to examine both successful results and failure\n * cases in a unified way, while still leveraging `Promise` for handling the\n * asynchronous behavior of the effect.\n *\n * **When to Use**\n *\n * Use this function when you need to understand the outcome of an effect,\n * whether it succeeded or failed, and want to work with this result using\n * `Promise` syntax. This is particularly useful when integrating with systems\n * that rely on promises but need more detailed error handling than a simple\n * rejection.\n *\n * **Example** (Handling Results as Exit)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * // Execute a successful effect and get the Exit result as a Promise\n * Effect.runPromiseExit(Effect.succeed(1)).then(console.log)\n * // Output:\n * // {\n * //   _id: \"Exit\",\n * //   _tag: \"Success\",\n * //   value: 1\n * // }\n *\n * // Execute a failing effect and get the Exit result as a Promise\n * Effect.runPromiseExit(Effect.fail(\"my error\")).then(console.log)\n * // Output:\n * // {\n * //   _id: \"Exit\",\n * //   _tag: \"Failure\",\n * //   cause: {\n * //     _id: \"Cause\",\n * //     _tag: \"Fail\",\n * //     failure: \"my error\"\n * //   }\n * // }\n * ```\n *\n * @since 2.0.0\n * @category Running Effects\n */\nexport const runPromiseExit: <A, E>(\n  effect: Effect<A, E, never>,\n  options?: { readonly signal?: AbortSignal } | undefined\n) => Promise<Exit.Exit<A, E>> = runtime_.unsafeRunPromiseExitEffect\n\n/**\n * Executes an effect synchronously, running it immediately and returning the\n * result.\n *\n * **Details**\n *\n * This function evaluates the provided effect synchronously, returning its\n * result directly. It is ideal for effects that do not fail or include\n * asynchronous operations. If the effect does fail or involves async tasks, it\n * will throw an error. Execution stops at the point of failure or asynchronous\n * operation, making it unsuitable for effects that require asynchronous\n * handling.\n *\n * **Important**: Attempting to run effects that involve asynchronous operations\n * or failures will result in exceptions being thrown, so use this function with\n * care for purely synchronous and error-free effects.\n *\n * **When to Use**\n *\n * Use this function when:\n * - You are sure that the effect will not fail or involve asynchronous\n *   operations.\n * - You need a direct, synchronous result from the effect.\n * - You are working within a context where asynchronous effects are not\n *   allowed.\n *\n * Avoid using this function for effects that can fail or require asynchronous\n * handling. For such cases, consider using {@link runPromise} or\n * {@link runSyncExit}.\n *\n * **Example** (Synchronous Logging)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const program = Effect.sync(() => {\n *   console.log(\"Hello, World!\")\n *   return 1\n * })\n *\n * const result = Effect.runSync(program)\n * // Output: Hello, World!\n *\n * console.log(result)\n * // Output: 1\n * ```\n *\n * **Example** (Incorrect Usage with Failing or Async Effects)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * try {\n *   // Attempt to run an effect that fails\n *   Effect.runSync(Effect.fail(\"my error\"))\n * } catch (e) {\n *   console.error(e)\n * }\n * // Output:\n * // (FiberFailure) Error: my error\n *\n * try {\n *   // Attempt to run an effect that involves async work\n *   Effect.runSync(Effect.promise(() => Promise.resolve(1)))\n * } catch (e) {\n *   console.error(e)\n * }\n * // Output:\n * // (FiberFailure) AsyncFiberException: Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work\n * ```\n *\n * @see {@link runSyncExit} for a version that returns an `Exit` type instead of\n * throwing an error.\n *\n * @since 2.0.0\n * @category Running Effects\n */\nexport const runSync: <A, E>(effect: Effect<A, E>) => A = runtime_.unsafeRunSyncEffect\n\n/**\n * Runs an effect synchronously and returns the result as an `Exit` type.\n *\n * **Details**\n *\n * This function executes the provided effect synchronously and returns an `Exit`\n * type that encapsulates the outcome of the effect:\n * - If the effect succeeds, the result is wrapped in a `Success`.\n * - If the effect fails, it returns a `Failure` containing a `Cause` that explains\n *   the failure.\n *\n * If the effect involves asynchronous operations, this function will return a `Failure`\n * with a `Die` cause, indicating that it cannot resolve the effect synchronously.\n * This makes the function suitable for use only with effects that are synchronous\n * in nature.\n *\n * **When to Use**\n *\n * Use this function when:\n * - You want to handle both success and failure outcomes in a structured way using the `Exit` type.\n * - You are working with effects that are purely synchronous and do not involve asynchronous operations.\n * - You need to debug or inspect failures, including their causes, in a detailed manner.\n *\n * Avoid using this function for effects that involve asynchronous operations, as it will fail with a `Die` cause.\n *\n * **Example** (Handling Results as Exit)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * console.log(Effect.runSyncExit(Effect.succeed(1)))\n * // Output:\n * // {\n * //   _id: \"Exit\",\n * //   _tag: \"Success\",\n * //   value: 1\n * // }\n *\n * console.log(Effect.runSyncExit(Effect.fail(\"my error\")))\n * // Output:\n * // {\n * //   _id: \"Exit\",\n * //   _tag: \"Failure\",\n * //   cause: {\n * //     _id: \"Cause\",\n * //     _tag: \"Fail\",\n * //     failure: \"my error\"\n * //   }\n * // }\n * ```\n *\n * **Example** (Asynchronous Operation Resulting in Die)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * console.log(Effect.runSyncExit(Effect.promise(() => Promise.resolve(1))))\n * // Output:\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Die',\n * //     defect: [Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work] {\n * //       fiber: [FiberRuntime],\n * //       _tag: 'AsyncFiberException',\n * //       name: 'AsyncFiberException'\n * //     }\n * //   }\n * // }\n * ```\n *\n * @since 2.0.0\n * @category Running Effects\n */\nexport const runSyncExit: <A, E>(effect: Effect<A, E>) => Exit.Exit<A, E> = runtime_.unsafeRunSyncExitEffect\n\n/**\n * Combines multiple effects and accumulates both successes and failures.\n *\n * **Details**\n *\n * This function allows you to combine multiple effects, continuing through all\n * effects even if some of them fail. Unlike other functions that stop execution\n * upon encountering an error, this function collects all errors into a `Cause`.\n * The final result includes all successes and the accumulated failures.\n *\n * By default, effects are executed sequentially, but you can control\n * concurrency and batching behavior using the `options` parameter. This\n * provides flexibility in scenarios where you want to maximize performance or\n * ensure specific ordering.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Console } from \"effect\"\n *\n * const task1 = Console.log(\"task1\").pipe(Effect.as(1))\n * const task2 = Effect.fail(\"Oh uh!\").pipe(Effect.as(2))\n * const task3 = Console.log(\"task2\").pipe(Effect.as(3))\n * const task4 = Effect.fail(\"Oh no!\").pipe(Effect.as(4))\n *\n * const program = task1.pipe(\n *   Effect.validate(task2),\n *   Effect.validate(task3),\n *   Effect.validate(task4)\n * )\n *\n * Effect.runPromiseExit(program).then(console.log)\n * // Output:\n * // task1\n * // task2\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Sequential',\n * //     left: { _id: 'Cause', _tag: 'Fail', failure: 'Oh uh!' },\n * //     right: { _id: 'Cause', _tag: 'Fail', failure: 'Oh no!' }\n * //   }\n * // }\n * ```\n *\n * @see {@link zip} for a version that stops at the first error.\n *\n * @since 2.0.0\n * @category Error Accumulation\n */\nexport const validate: {\n  <B, E1, R1>(\n    that: Effect<B, E1, R1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    } | undefined\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<[A, B], E1 | E, R1 | R>\n  <A, E, R, B, E1, R1>(\n    self: Effect<A, E, R>,\n    that: Effect<B, E1, R1>,\n    options?:\n      | {\n        readonly concurrent?: boolean | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): Effect<[A, B], E | E1, R | R1>\n} = fiberRuntime.validate\n\n/**\n * Sequentially combines two effects using a specified combiner function while\n * accumulating errors.\n *\n * **Details**\n *\n * This function combines two effects, `self` and `that`, into a single effect\n * by applying the provided combiner function to their results. If both effects\n * succeed, the combiner function is applied to their results to produce the\n * final value. If either effect fails, the failures are accumulated into a\n * combined `Cause`.\n *\n * By default, effects are executed sequentially. However, the execution mode\n * can be controlled using the `options` parameter to enable concurrency,\n * batching, or customized finalizer behavior.\n *\n * @since 2.0.0\n * @category Error Accumulation\n */\nexport const validateWith: {\n  <B, E1, R1, A, C>(\n    that: Effect<B, E1, R1>,\n    f: (a: A, b: B) => C,\n    options?:\n      | {\n        readonly concurrent?: boolean | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): <E, R>(self: Effect<A, E, R>) => Effect<C, E1 | E, R1 | R>\n  <A, E, R, B, E1, R1, C>(\n    self: Effect<A, E, R>,\n    that: Effect<B, E1, R1>,\n    f: (a: A, b: B) => C,\n    options?:\n      | {\n        readonly concurrent?: boolean | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): Effect<C, E | E1, R | R1>\n} = fiberRuntime.validateWith\n\n/**\n * Combines two effects into a single effect, producing a tuple of their\n * results.\n *\n * **Details**\n *\n * This function combines two effects, `self` and `that`, into one. It executes\n * the first effect (`self`) and then the second effect (`that`), collecting\n * their results into a tuple. Both effects must succeed for the resulting\n * effect to succeed. If either effect fails, the entire operation fails.\n *\n * By default, the effects are executed sequentially. If the `concurrent` option\n * is set to `true`, the effects will run concurrently, potentially improving\n * performance for independent operations.\n *\n * **Example** (Combining Two Effects Sequentially)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const task1 = Effect.succeed(1).pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Effect.log(\"task1 done\"))\n * )\n * const task2 = Effect.succeed(\"hello\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Effect.log(\"task2 done\"))\n * )\n *\n * // Combine the two effects together\n * //\n * //      ┌─── Effect<[number, string], never, never>\n * //      ▼\n * const program = Effect.zip(task1, task2)\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // timestamp=... level=INFO fiber=#0 message=\"task1 done\"\n * // timestamp=... level=INFO fiber=#0 message=\"task2 done\"\n * // [ 1, 'hello' ]\n * ```\n *\n * **Example** (Combining Two Effects Concurrently)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const task1 = Effect.succeed(1).pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Effect.log(\"task1 done\"))\n * )\n * const task2 = Effect.succeed(\"hello\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Effect.log(\"task2 done\"))\n * )\n *\n * // Run both effects concurrently using the concurrent option\n * const program = Effect.zip(task1, task2, { concurrent: true })\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // timestamp=... level=INFO fiber=#0 message=\"task2 done\"\n * // timestamp=... level=INFO fiber=#0 message=\"task1 done\"\n * // [ 1, 'hello' ]\n * ```\n *\n * @see {@link zipWith} for a version that combines the results with a custom\n * function.\n * @see {@link validate} for a version that accumulates errors.\n *\n * @since 2.0.0\n * @category Zipping\n */\nexport const zip: {\n  <A2, E2, R2>(\n    that: Effect<A2, E2, R2>,\n    options?:\n      | {\n        readonly concurrent?: boolean | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<[A, A2], E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    that: Effect<A2, E2, R2>,\n    options?:\n      | {\n        readonly concurrent?: boolean | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): Effect<[A, A2], E | E2, R | R2>\n} = fiberRuntime.zipOptions\n\n/**\n * Executes two effects sequentially, returning the result of the first effect\n * and ignoring the result of the second.\n *\n * **Details**\n *\n * This function allows you to run two effects in sequence, where the result of\n * the first effect is preserved, and the result of the second effect is\n * discarded. By default, the two effects are executed sequentially. If you need\n * them to run concurrently, you can pass the `{ concurrent: true }` option.\n *\n * The second effect will always be executed, even though its result is ignored.\n * This makes it useful for cases where you want to execute an effect for its\n * side effects while keeping the result of another effect.\n *\n * **When to Use**\n *\n * Use this function when you are only interested in the result of the first\n * effect but still need to run the second effect for its side effects, such as\n * logging or performing a cleanup action.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const task1 = Effect.succeed(1).pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Effect.log(\"task1 done\"))\n * )\n * const task2 = Effect.succeed(\"hello\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Effect.log(\"task2 done\"))\n * )\n *\n * const program = Effect.zipLeft(task1, task2)\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // timestamp=... level=INFO fiber=#0 message=\"task1 done\"\n * // timestamp=... level=INFO fiber=#0 message=\"task2 done\"\n * // 1\n * ```\n *\n * @see {@link zipRight} for a version that returns the result of the second\n * effect.\n *\n * @since 2.0.0\n * @category Zipping\n */\nexport const zipLeft: {\n  <A2, E2, R2>(\n    that: Effect<A2, E2, R2>,\n    options?:\n      | {\n        readonly concurrent?: boolean | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    that: Effect<A2, E2, R2>,\n    options?:\n      | {\n        readonly concurrent?: boolean | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n      | undefined\n  ): Effect<A, E | E2, R | R2>\n} = fiberRuntime.zipLeftOptions\n\n/**\n * Executes two effects sequentially, returning the result of the second effect\n * while ignoring the result of the first.\n *\n * **Details**\n *\n * This function allows you to run two effects in sequence, keeping the result\n * of the second effect and discarding the result of the first. By default, the\n * two effects are executed sequentially. If you need them to run concurrently,\n * you can pass the `{ concurrent: true }` option.\n *\n * The first effect will always be executed, even though its result is ignored.\n * This makes it useful for scenarios where the first effect is needed for its\n * side effects, but only the result of the second effect is important.\n *\n * **When to Use**\n *\n * Use this function when you are only interested in the result of the second\n * effect but still need to run the first effect for its side effects, such as\n * initialization or setup tasks.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const task1 = Effect.succeed(1).pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Effect.log(\"task1 done\"))\n * )\n * const task2 = Effect.succeed(\"hello\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Effect.log(\"task2 done\"))\n * )\n *\n * const program = Effect.zipRight(task1, task2)\n *\n * Effect.runPromise(program).then(console.log)\n * // Output:\n * // timestamp=... level=INFO fiber=#0 message=\"task1 done\"\n * // timestamp=... level=INFO fiber=#0 message=\"task2 done\"\n * // hello\n * ```\n *\n * @see {@link zipLeft} for a version that returns the result of the first\n * effect.\n *\n * @since 2.0.0\n * @category Zipping\n */\nexport const zipRight: {\n  <A2, E2, R2>(\n    that: Effect<A2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect<A, E, R>,\n    that: Effect<A2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect<A2, E2 | E, R2 | R>\n} = fiberRuntime.zipRightOptions\n\n/**\n * Combines two effects sequentially and applies a function to their results to\n * produce a single value.\n *\n * **Details**\n *\n * This function runs two effects in sequence (or concurrently, if the `{\n * concurrent: true }` option is provided) and combines their results using a\n * provided function. Unlike {@link zip}, which returns a tuple of the results,\n * this function processes the results with a custom function to produce a\n * single output.\n *\n * **Example** (Combining Effects with a Custom Function)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const task1 = Effect.succeed(1).pipe(\n *   Effect.delay(\"200 millis\"),\n *   Effect.tap(Effect.log(\"task1 done\"))\n * )\n * const task2 = Effect.succeed(\"hello\").pipe(\n *   Effect.delay(\"100 millis\"),\n *   Effect.tap(Effect.log(\"task2 done\"))\n * )\n *\n * const task3 = Effect.zipWith(\n *   task1,\n *   task2,\n *   // Combines results into a single value\n *   (number, string) => number + string.length\n * )\n *\n * Effect.runPromise(task3).then(console.log)\n * // Output:\n * // timestamp=... level=INFO fiber=#3 message=\"task1 done\"\n * // timestamp=... level=INFO fiber=#2 message=\"task2 done\"\n * // 6\n * ```\n *\n * @since 2.0.0\n * @category Zipping\n */\nexport const zipWith: {\n  <A2, E2, R2, A, B>(\n    that: Effect<A2, E2, R2>,\n    f: (a: A, b: A2) => B,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): <E, R>(self: Effect<A, E, R>) => Effect<B, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2, B>(\n    self: Effect<A, E, R>,\n    that: Effect<A2, E2, R2>,\n    f: (a: A, b: A2) => B,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect<B, E2 | E, R2 | R>\n} = fiberRuntime.zipWithOptions\n\n/**\n * Applies the function produced by one effect to the value produced by another effect.\n *\n * **Details**\n *\n * This function combines two effects:\n * - The first effect produces a function of type `(a: A) => B`.\n * - The second effect produces a value of type `A`.\n *\n * Once both effects complete successfully, the function is applied to the value, resulting in an effect that produces a value of type `B`.\n *\n * @since 2.0.0\n */\nexport const ap: {\n  <A, E2, R2>(that: Effect<A, E2, R2>): <B, R, E>(self: Effect<(a: A) => B, E, R>) => Effect<B, E | E2, R | R2>\n  <A, B, E, R, E2, R2>(self: Effect<(a: A) => B, E, R>, that: Effect<A, E2, R2>): Effect<B, E | E2, R | R2>\n} = dual(\n  2,\n  <A, B, E, R, E2, R2>(self: Effect<(a: A) => B, E, R>, that: Effect<A, E2, R2>): Effect<B, E | E2, R | R2> =>\n    zipWith(self, that, (f, a) => f(a))\n)\n\n/**\n * @category Requests & Batching\n * @since 2.0.0\n */\nexport const blocked: <A, E>(blockedRequests: RequestBlock, _continue: Effect<A, E>) => Blocked<A, E> = core.blocked\n\n/**\n * @category Requests & Batching\n * @since 2.0.0\n */\nexport const runRequestBlock: (blockedRequests: RequestBlock) => Effect<void> = core.runRequestBlock\n\n/**\n * @category Requests & Batching\n * @since 2.0.0\n */\nexport const step: <A, E, R>(self: Effect<A, E, R>) => Effect<Exit.Exit<A, E> | Blocked<A, E>, never, R> = core.step\n\n/**\n * @since 2.0.0\n * @category Requests & Batching\n */\nexport const request: {\n  <A extends Request.Request<any, any>, Ds extends RequestResolver<A> | Effect<RequestResolver<A>, any, any>>(\n    dataSource: Ds\n  ): (\n    self: A\n  ) => Effect<\n    Request.Request.Success<A>,\n    Request.Request.Error<A>,\n    [Ds] extends [Effect<any, any, any>] ? Effect.Context<Ds> : never\n  >\n  <\n    Ds extends RequestResolver<A> | Effect<RequestResolver<A>, any, any>,\n    A extends Request.Request<any, any>\n  >(\n    self: A,\n    dataSource: Ds\n  ): Effect<\n    Request.Request.Success<A>,\n    Request.Request.Error<A>,\n    [Ds] extends [Effect<any, any, any>] ? Effect.Context<Ds> : never\n  >\n} = dual((args) => Request.isRequest(args[0]), query.fromRequest)\n\n/**\n * @since 2.0.0\n * @category Requests & Batching\n */\nexport const cacheRequestResult: <A extends Request.Request<any, any>>(\n  request: A,\n  result: Request.Request.Result<A>\n) => Effect<void> = query.cacheRequest\n\n/**\n * @since 2.0.0\n * @category Requests & Batching\n */\nexport const withRequestBatching: {\n  (requestBatching: boolean): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, requestBatching: boolean): Effect<A, E, R>\n} = core.withRequestBatching\n\n/**\n * @since 2.0.0\n * @category Requests & Batching\n */\nexport const withRequestCaching: {\n  (strategy: boolean): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, strategy: boolean): Effect<A, E, R>\n} = query.withRequestCaching\n\n/**\n * @since 2.0.0\n * @category Requests & Batching\n */\nexport const withRequestCache: {\n  (cache: Request.Cache): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, cache: Request.Cache): Effect<A, E, R>\n} = query.withRequestCache\n\n/**\n * @since 2.0.0\n * @category Tracing\n */\nexport const tracer: Effect<Tracer.Tracer> = effect.tracer\n\n/**\n * @since 2.0.0\n * @category Tracing\n */\nexport const tracerWith: <A, E, R>(f: (tracer: Tracer.Tracer) => Effect<A, E, R>) => Effect<A, E, R> =\n  defaultServices.tracerWith\n\n/**\n * @since 2.0.0\n * @category Tracing\n */\nexport const withTracer: {\n  (value: Tracer.Tracer): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(effect: Effect<A, E, R>, value: Tracer.Tracer): Effect<A, E, R>\n} = defaultServices.withTracer\n\n/**\n * @since 2.0.0\n * @category Tracing\n */\nexport const withTracerScoped: (value: Tracer.Tracer) => Effect<void, never, Scope.Scope> =\n  fiberRuntime.withTracerScoped\n\n/**\n * Disable the tracer for the given Effect.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * Effect.succeed(42).pipe(\n *   Effect.withSpan(\"my-span\"),\n *   // the span will not be registered with the tracer\n *   Effect.withTracerEnabled(false)\n * )\n * ```\n *\n * @since 2.0.0\n * @category Tracing\n */\nexport const withTracerEnabled: {\n  (enabled: boolean): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(effect: Effect<A, E, R>, enabled: boolean): Effect<A, E, R>\n} = core.withTracerEnabled\n\n/**\n * @since 2.0.0\n * @category Tracing\n */\nexport const withTracerTiming: {\n  (enabled: boolean): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(effect: Effect<A, E, R>, enabled: boolean): Effect<A, E, R>\n} = core.withTracerTiming\n\n/**\n * Adds annotations to each span in the effect for enhanced traceability.\n *\n * **Details**\n *\n * This function lets you attach key-value annotations to all spans generated\n * during the execution of an effect. Annotations provide additional context,\n * such as metadata or labels, which can help you understand and debug\n * asynchronous workflows more effectively.\n *\n * You can either pass a single key-value pair or a record of key-value pairs to\n * annotate the spans. These annotations can then be visualized in tracing tools\n * that support span annotations.\n *\n * @since 2.0.0\n * @category Tracing\n */\nexport const annotateSpans: {\n  (key: string, value: unknown): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  (values: Record<string, unknown>): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(effect: Effect<A, E, R>, key: string, value: unknown): Effect<A, E, R>\n  <A, E, R>(effect: Effect<A, E, R>, values: Record<string, unknown>): Effect<A, E, R>\n} = effect.annotateSpans\n\n/**\n * Adds annotations to the currently active span for traceability.\n *\n * **Details**\n *\n * This function adds key-value annotations to the currently active span in the\n * effect's trace. These annotations help provide more context about the\n * operation being executed at a specific point in time. Unlike\n * {@link annotateSpans}, which applies to all spans in an effect, this function\n * focuses solely on the active span.\n *\n * You can either pass a single key-value pair or a record of key-value pairs to\n * annotate the span. These annotations are useful for adding metadata to\n * operations, especially in systems with detailed observability requirements.\n *\n * @since 2.0.0\n * @category Tracing\n */\nexport const annotateCurrentSpan: {\n  (key: string, value: unknown): Effect<void>\n  (values: Record<string, unknown>): Effect<void>\n} = effect.annotateCurrentSpan\n\n/**\n * @since 2.0.0\n * @category Tracing\n */\nexport const currentSpan: Effect<Tracer.Span, Cause.NoSuchElementException> = effect.currentSpan\n\n/**\n * @since 3.20.0\n * @category Tracing\n */\nexport const currentPropagatedSpan: Effect<Tracer.Span, Cause.NoSuchElementException> = effect.currentPropagatedSpan\n\n/**\n * @since 2.0.0\n * @category Tracing\n */\nexport const currentParentSpan: Effect<Tracer.AnySpan, Cause.NoSuchElementException> = effect.currentParentSpan\n\n/**\n * @since 2.0.0\n * @category Tracing\n */\nexport const spanAnnotations: Effect<HashMap.HashMap<string, unknown>> = effect.spanAnnotations\n\n/**\n * @since 2.0.0\n * @category Tracing\n */\nexport const spanLinks: Effect<Chunk.Chunk<Tracer.SpanLink>> = effect.spanLinks\n\n/**\n * For all spans in this effect, add a link with the provided span.\n *\n * @since 2.0.0\n * @category Tracing\n */\nexport const linkSpans: {\n  (\n    span: Tracer.AnySpan,\n    attributes?: Record<string, unknown>\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(\n    self: Effect<A, E, R>,\n    span: Tracer.AnySpan,\n    attributes?: Record<string, unknown>\n  ): Effect<A, E, R>\n} = effect.linkSpans\n\n/**\n * Add span links to the current span.\n *\n * @since 3.14.0\n * @category Tracing\n */\nexport const linkSpanCurrent: {\n  (span: Tracer.AnySpan, attributes?: Readonly<Record<string, unknown>> | undefined): Effect<void>\n  (links: ReadonlyArray<Tracer.SpanLink>): Effect<void>\n} = effect.linkSpanCurrent\n\n/**\n * Create a new span for tracing.\n *\n * @since 2.0.0\n * @category Tracing\n */\nexport const makeSpan: (\n  name: string,\n  options?: Tracer.SpanOptions\n) => Effect<Tracer.Span> = effect.makeSpan\n\n/**\n * Create a new span for tracing, and automatically close it when the Scope\n * finalizes.\n *\n * The span is not added to the current span stack, so no child spans will be\n * created for it.\n *\n * @since 2.0.0\n * @category Tracing\n */\nexport const makeSpanScoped: (\n  name: string,\n  options?: Tracer.SpanOptions | undefined\n) => Effect<Tracer.Span, never, Scope.Scope> = fiberRuntime.makeSpanScoped\n\n/**\n * Create a new span for tracing, and automatically close it when the effect\n * completes.\n *\n * The span is not added to the current span stack, so no child spans will be\n * created for it.\n *\n * @since 2.0.0\n * @category Tracing\n */\nexport const useSpan: {\n  <A, E, R>(name: string, evaluate: (span: Tracer.Span) => Effect<A, E, R>): Effect<A, E, R>\n  <A, E, R>(\n    name: string,\n    options: Tracer.SpanOptions,\n    evaluate: (span: Tracer.Span) => Effect<A, E, R>\n  ): Effect<A, E, R>\n} = effect.useSpan\n\n/**\n * Wraps the effect with a new span for tracing.\n *\n * @since 2.0.0\n * @category Tracing\n */\nexport const withSpan: {\n  (\n    name: string,\n    options?: Tracer.SpanOptions | undefined\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, Exclude<R, Tracer.ParentSpan>>\n  <A, E, R>(\n    self: Effect<A, E, R>,\n    name: string,\n    options?: Tracer.SpanOptions | undefined\n  ): Effect<A, E, Exclude<R, Tracer.ParentSpan>>\n} = effect.withSpan\n\n/**\n * Wraps a function that returns an effect with a new span for tracing.\n *\n * @since 3.2.0\n * @category Models\n */\nexport interface FunctionWithSpanOptions {\n  readonly name: string\n  readonly attributes?: Record<string, unknown> | undefined\n  readonly links?: ReadonlyArray<Tracer.SpanLink> | undefined\n  readonly parent?: Tracer.AnySpan | undefined\n  readonly root?: boolean | undefined\n  readonly context?: Context.Context<never> | undefined\n  readonly kind?: Tracer.SpanKind | undefined\n}\n\n/**\n * Wraps a function that returns an effect with a new span for tracing.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const getTodo = Effect.functionWithSpan({\n *   body: (id: number) => Effect.succeed(`Got todo ${id}!`),\n *   options: (id) => ({\n *     name: `getTodo-${id}`,\n *     attributes: { id }\n *   })\n * })\n * ```\n *\n * @since 3.2.0\n * @category Tracing\n */\nexport const functionWithSpan: <Args extends Array<any>, Ret extends Effect<any, any, any>>(\n  options: {\n    readonly body: (...args: Args) => Ret\n    readonly options: FunctionWithSpanOptions | ((...args: Args) => FunctionWithSpanOptions)\n    readonly captureStackTrace?: boolean | undefined\n  }\n) => (...args: Args) => Unify.Unify<Ret> = effect.functionWithSpan\n\n/**\n * Wraps the effect with a new span for tracing.\n *\n * The span is ended when the Scope is finalized.\n *\n * @since 2.0.0\n * @category Tracing\n */\nexport const withSpanScoped: {\n  (\n    name: string,\n    options?: Tracer.SpanOptions\n  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, Exclude<R, Tracer.ParentSpan> | Scope.Scope>\n  <A, E, R>(\n    self: Effect<A, E, R>,\n    name: string,\n    options?: Tracer.SpanOptions\n  ): Effect<A, E, Exclude<R, Tracer.ParentSpan> | Scope.Scope>\n} = fiberRuntime.withSpanScoped\n\n/**\n * Adds the provided span to the current span stack.\n *\n * @since 2.0.0\n * @category Tracing\n */\nexport const withParentSpan: {\n  (span: Tracer.AnySpan): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, Exclude<R, Tracer.ParentSpan>>\n  <A, E, R>(self: Effect<A, E, R>, span: Tracer.AnySpan): Effect<A, E, Exclude<R, Tracer.ParentSpan>>\n} = effect.withParentSpan\n\n/**\n * Safely handles nullable values by creating an effect that fails for `null` or\n * `undefined`.\n *\n * **Details**\n *\n * This function ensures that an input value is non-null and non-undefined\n * before processing it. If the value is valid, the effect succeeds with the\n * value. If the value is `null` or `undefined`, the effect fails with a\n * `NoSuchElementException`. This is particularly useful for avoiding\n * null-related errors by clearly separating valid values from invalid ones in\n * effectful computations.\n *\n * The failure with `NoSuchElementException` allows you to explicitly handle\n * cases where a value is expected but not provided, leading to safer and more\n * predictable code.\n *\n * **When to Use**\n *\n * Use this function when working with values that may be `null` or `undefined`\n * and you want to ensure that only non-null values are processed. It helps\n * enforce null-safety and makes error handling more explicit.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * //      ┌─── Effect<number, NoSuchElementException, never>\n * //      ▼\n * const maybe1 = Effect.fromNullable(1)\n *\n * Effect.runPromiseExit(maybe1).then(console.log)\n * // Output:\n * // { _id: 'Exit', _tag: 'Success', value: 1 }\n *\n * //      ┌─── Effect<number, NoSuchElementException, never>\n * //      ▼\n * const maybe2 = Effect.fromNullable(null as number | null)\n *\n * Effect.runPromiseExit(maybe2).then(console.log)\n * // Output:\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: {\n * //     _id: 'Cause',\n * //     _tag: 'Fail',\n * //     failure: { _tag: 'NoSuchElementException' }\n * //   }\n * // }\n * ```\n *\n * @since 2.0.0\n * @category Optional Wrapping & Unwrapping\n */\nexport const fromNullable: <A>(value: A) => Effect<NonNullable<A>, Cause.NoSuchElementException> = effect.fromNullable\n\n/**\n * Converts an effect that may fail with a `NoSuchElementException` into an\n * effect that succeeds with an `Option`.\n *\n * **Details**\n *\n * This function transforms an effect that might fail with\n * `Cause.NoSuchElementException` into an effect that succeeds with an `Option`\n * type. If the original effect succeeds, its value is wrapped in `Option.some`.\n * If it fails specifically due to a `NoSuchElementException`, the failure is\n * mapped to `Option.none`. Other types of failures remain unchanged and are\n * passed through as they are.\n *\n * This is useful when working with effects where you want to gracefully handle\n * the absence of a value while preserving other potential failures.\n *\n * **When to Use**\n *\n * Use this function when you need to handle missing values as `Option.none`\n * rather than throwing or propagating errors like `NoSuchElementException`.\n * It’s ideal for scenarios where you want to explicitly represent optionality\n * in a type-safe way while retaining other failure information.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * //      ┌─── Effect<number, NoSuchElementException, never>\n * //      ▼\n * const maybe1 = Effect.fromNullable(1)\n *\n * //      ┌─── Effect<Option<number>, never, never>\n * //      ▼\n * const option1 = Effect.optionFromOptional(maybe1)\n *\n * Effect.runPromise(option1).then(console.log)\n * // Output: { _id: 'Option', _tag: 'Some', value: 1 }\n *\n * //      ┌─── Effect<number, NoSuchElementException, never>\n * //      ▼\n * const maybe2 = Effect.fromNullable(null as number | null)\n *\n * //      ┌─── Effect<Option<number>, never, never>\n * //      ▼\n * const option2 = Effect.optionFromOptional(maybe2)\n *\n * Effect.runPromise(option2).then(console.log)\n * // Output: { _tag: 'None' }\n * ```\n *\n * @since 2.0.0\n * @category Optional Wrapping & Unwrapping\n */\nexport const optionFromOptional: <A, E, R>(\n  self: Effect<A, E, R>\n) => Effect<Option.Option<A>, Exclude<E, Cause.NoSuchElementException>, R> = effect.optionFromOptional\n\n/**\n * Converts an `Option` of an `Effect` into an `Effect` of an `Option`.\n *\n * **Details**\n *\n * This function transforms an `Option<Effect<A, E, R>>` into an\n * `Effect<Option<A>, E, R>`. If the `Option` is `None`, the resulting `Effect`\n * will immediately succeed with a `None` value. If the `Option` is `Some`, the\n * inner `Effect` will be executed, and its result wrapped in a `Some`.\n *\n * **Example**\n *\n * ```ts\n * import { Effect, Option } from \"effect\"\n *\n * //      ┌─── Option<Effect<number, never, never>>\n * //      ▼\n * const maybe = Option.some(Effect.succeed(42))\n *\n * //      ┌─── Effect<Option<number>, never, never>\n * //      ▼\n * const result = Effect.transposeOption(maybe)\n *\n * console.log(Effect.runSync(result))\n * // Output: { _id: 'Option', _tag: 'Some', value: 42 }\n * ```\n *\n * @since 3.13.0\n * @category Optional Wrapping & Unwrapping\n */\nexport const transposeOption = <A = never, E = never, R = never>(\n  self: Option.Option<Effect<A, E, R>>\n): Effect<Option.Option<A>, E, R> => {\n  return option_.isNone(self) ? succeedNone : map(self.value, option_.some)\n}\n\n/**\n * Applies an `Effect` on an `Option` and transposes the result.\n *\n * **Details**\n *\n * If the `Option` is `None`, the resulting `Effect` will immediately succeed with a `None` value.\n * If the `Option` is `Some`, the effectful operation will be executed on the inner value, and its result wrapped in a `Some`.\n *\n * @example\n * ```ts\n * import { Effect, Option, pipe } from \"effect\"\n *\n * //          ┌─── Effect<Option<number>, never, never>>\n * //          ▼\n * const noneResult = pipe(\n *   Option.none(),\n *   Effect.transposeMapOption(() => Effect.succeed(42)) // will not be executed\n * )\n * console.log(Effect.runSync(noneResult))\n * // Output: { _id: 'Option', _tag: 'None' }\n *\n * //          ┌─── Effect<Option<number>, never, never>>\n * //          ▼\n * const someSuccessResult = pipe(\n *   Option.some(42),\n *   Effect.transposeMapOption((value) => Effect.succeed(value * 2))\n * )\n * console.log(Effect.runSync(someSuccessResult))\n * // Output: { _id: 'Option', _tag: 'Some', value: 84 }\n * ```\n *\n * @since 3.14.0\n * @category Optional Wrapping & Unwrapping\n */\nexport const transposeMapOption = dual<\n  <A, B, E = never, R = never>(\n    f: (self: A) => Effect<B, E, R>\n  ) => (self: Option.Option<A>) => Effect<Option.Option<B>, E, R>,\n  <A, B, E = never, R = never>(\n    self: Option.Option<A>,\n    f: (self: A) => Effect<B, E, R>\n  ) => Effect<Option.Option<B>, E, R>\n>(2, (self, f) => option_.isNone(self) ? succeedNone : map(f(self.value), option_.some))\n\n/**\n * @since 2.0.0\n * @category Models\n */\nexport declare namespace Tag {\n  /**\n   * @since 2.0.0\n   * @category Models\n   */\n  export interface ProhibitedType {\n    Service?: `property \"Service\" is forbidden`\n    Identifier?: `property \"Identifier\" is forbidden`\n    _op?: `property \"_op\" is forbidden`\n    of?: `property \"of\" is forbidden`\n    context?: `property \"context\" is forbidden`\n    key?: `property \"key\" is forbidden`\n    stack?: `property \"stack\" is forbidden`\n    name?: `property \"name\" is forbidden`\n    pipe?: `property \"pipe\" is forbidden`\n    use?: `property \"use\" is forbidden`\n  }\n\n  /**\n   * @since 2.0.0\n   * @category Models\n   */\n  export type AllowedType = (Record<PropertyKey, any> & ProhibitedType) | string | number | symbol\n\n  /**\n   * @since 3.9.0\n   * @category Models\n   */\n  export type Proxy<Self, Type> = {\n    [\n      k in keyof Type as Type[k] extends ((...args: infer Args extends ReadonlyArray<any>) => infer Ret) ?\n        ((...args: Readonly<Args>) => Ret) extends Type[k] ? k : never\n        : k\n    ]: Type[k] extends (...args: infer Args extends ReadonlyArray<any>) => Effect<infer A, infer E, infer R> ?\n      (...args: Readonly<Args>) => Effect<A, E, Self | R>\n      : Type[k] extends (...args: infer Args extends ReadonlyArray<any>) => Promise<infer A> ?\n        (...args: Readonly<Args>) => Effect<A, Cause.UnknownException, Self>\n      : Type[k] extends (...args: infer Args extends ReadonlyArray<any>) => infer A ?\n        (...args: Readonly<Args>) => Effect<A, never, Self>\n      : Type[k] extends Effect<infer A, infer E, infer R> ? Effect<A, E, Self | R>\n      : Effect<Type[k], never, Self>\n  }\n}\n\nconst makeTagProxy = (TagClass: Context.Tag<any, any> & Record<PropertyKey, any>) => {\n  const cache = new Map()\n  return new Proxy(TagClass, {\n    get(target: any, prop: any, receiver) {\n      if (prop in target) {\n        return Reflect.get(target, prop, receiver)\n      }\n      if (cache.has(prop)) {\n        return cache.get(prop)\n      }\n      const fn = (...args: Array<any>) =>\n        core.andThen(target, (s: any) => {\n          if (typeof s[prop] === \"function\") {\n            cache.set(prop, (...args: Array<any>) => core.andThen(target, (s: any) => s[prop](...args)))\n            return s[prop](...args)\n          }\n          cache.set(prop, core.andThen(target, (s: any) => s[prop]))\n          return s[prop]\n        })\n      const cn = core.andThen(target, (s: any) => s[prop])\n      // @effect-diagnostics-next-line floatingEffect:off\n      Object.assign(fn, cn)\n      const apply = fn.apply\n      const bind = fn.bind\n      const call = fn.call\n      const proto = Object.setPrototypeOf({}, Object.getPrototypeOf(cn))\n      proto.apply = apply\n      proto.bind = bind\n      proto.call = call\n      Object.setPrototypeOf(fn, proto)\n      cache.set(prop, fn)\n      return fn\n    }\n  })\n}\n\n/**\n * Creates a unique tag for a dependency, embedding the service's methods as\n * static properties.\n *\n * **Details**\n *\n * This function allows you to define a `Tag` for a service or dependency in\n * your application. The `Tag` not only acts as an identifier but also provides\n * direct access to the service's methods via static properties. This makes it\n * easier to access and use the service in your code without manually managing\n * contexts.\n *\n * In the example below, the fields of the service (in this case, the `notify`\n * method) are turned into static properties of the Notifications class, making\n * it easier to access them.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * class Notifications extends Effect.Tag(\"Notifications\")<\n *   Notifications,\n *   { readonly notify: (message: string) => Effect.Effect<void> }\n * >() {}\n *\n * // Create an effect that depends on the Notifications service\n * const action = Notifications.notify(\"Hello, world!\")\n * ```\n *\n * @since 2.0.0\n * @category Context\n */\nexport const Tag: <const Id extends string>(id: Id) => <\n  Self,\n  Type extends Tag.AllowedType\n>() =>\n  & Context.TagClass<Self, Id, Type>\n  & (Type extends Record<PropertyKey, any> ? Tag.Proxy<Self, Type> : {})\n  & {\n    use: <X>(\n      body: (_: Type) => X\n    ) => [X] extends [Effect<infer A, infer E, infer R>] ? Effect<A, E, R | Self>\n      : [X] extends [PromiseLike<infer A>] ? Effect<A, Cause.UnknownException, Self>\n      : Effect<X, never, Self>\n  } = (id) => () => {\n    const limit = Error.stackTraceLimit\n    Error.stackTraceLimit = 2\n    const creationError = new Error()\n    Error.stackTraceLimit = limit\n    function TagClass() {}\n    Object.setPrototypeOf(TagClass, TagProto)\n    TagClass.key = id\n    Object.defineProperty(TagClass, \"use\", {\n      get() {\n        return (body: (_: any) => any) => core.andThen(this, body)\n      }\n    })\n    Object.defineProperty(TagClass, \"stack\", {\n      get() {\n        return creationError.stack\n      }\n    })\n    return makeTagProxy(TagClass as any)\n  }\n\ntype MissingSelfGeneric = `Missing \\`Self\\` generic - use \\`class Self extends Effect.Service<Self>()...\\``\n\n/**\n * Simplifies the creation and management of services in Effect by defining both\n * a `Tag` and a `Layer`.\n *\n * **Details**\n *\n * This function allows you to streamline the creation of services by combining\n * the definition of a `Context.Tag` and a `Layer` in a single step. It supports\n * various ways of providing the service implementation:\n * - Using an `effect` to define the service dynamically.\n * - Using `sync` or `succeed` to define the service statically.\n * - Using `scoped` to create services with lifecycle management.\n *\n * It also allows you to specify dependencies for the service, which will be\n * provided automatically when the service is used. Accessors can be optionally\n * generated for the service, making it more convenient to use.\n *\n * **Example**\n *\n * ```ts\n * import { Effect } from 'effect';\n *\n * class Prefix extends Effect.Service<Prefix>()(\"Prefix\", {\n *  sync: () => ({ prefix: \"PRE\" })\n * }) {}\n *\n * class Logger extends Effect.Service<Logger>()(\"Logger\", {\n *  accessors: true,\n *  effect: Effect.gen(function* () {\n *    const { prefix } = yield* Prefix\n *    return {\n *      info: (message: string) =>\n *        Effect.sync(() => {\n *          console.log(`[${prefix}][${message}]`)\n *        })\n *    }\n *  }),\n *  dependencies: [Prefix.Default]\n * }) {}\n * ```\n *\n * @since 3.9.0\n * @category Context\n * @experimental might be up for breaking changes\n */\nexport const Service: <Self = never>() => [Self] extends [never] ? MissingSelfGeneric : {\n  <\n    const Key extends string,\n    const Make extends\n      | {\n        readonly scoped:\n          | Effect<Service.AllowedType<Key, Make>, any, any>\n          | ((...args: any) => Effect<Service.AllowedType<Key, Make>, any, any>)\n        readonly dependencies?: ReadonlyArray<Layer.Layer.Any>\n        readonly accessors?: boolean\n        /** @deprecated */\n        readonly ಠ_ಠ: never\n      }\n      | {\n        readonly effect:\n          | Effect<Service.AllowedType<Key, Make>, any, any>\n          | ((...args: any) => Effect<Service.AllowedType<Key, Make>, any, any>)\n        readonly dependencies?: ReadonlyArray<Layer.Layer.Any>\n        readonly accessors?: boolean\n        /** @deprecated */\n        readonly ಠ_ಠ: never\n      }\n      | {\n        readonly sync: LazyArg<Service.AllowedType<Key, Make>>\n        readonly dependencies?: ReadonlyArray<Layer.Layer.Any>\n        readonly accessors?: boolean\n        /** @deprecated */\n        readonly ಠ_ಠ: never\n      }\n      | {\n        readonly succeed: Service.AllowedType<Key, Make>\n        readonly dependencies?: ReadonlyArray<Layer.Layer.Any>\n        readonly accessors?: boolean\n        /** @deprecated */\n        readonly ಠ_ಠ: never\n      }\n  >(\n    key: Key,\n    make: Make\n  ): Service.Class<Self, Key, Make>\n  <\n    const Key extends string,\n    const Make extends NoExcessProperties<{\n      readonly scoped:\n        | Effect<Service.AllowedType<Key, Make>, any, any>\n        | ((...args: any) => Effect<Service.AllowedType<Key, Make>, any, any>)\n      readonly dependencies?: ReadonlyArray<Layer.Layer.Any>\n      readonly accessors?: boolean\n    }, Make>\n  >(\n    key: Key,\n    make: Make\n  ): Service.Class<Self, Key, Make>\n  <\n    const Key extends string,\n    const Make extends NoExcessProperties<{\n      readonly effect:\n        | Effect<Service.AllowedType<Key, Make>, any, any>\n        | ((...args: any) => Effect<Service.AllowedType<Key, Make>, any, any>)\n      readonly dependencies?: ReadonlyArray<Layer.Layer.Any>\n      readonly accessors?: boolean\n    }, Make>\n  >(\n    key: Key,\n    make: Make\n  ): Service.Class<Self, Key, Make>\n  <\n    const Key extends string,\n    const Make extends NoExcessProperties<{\n      readonly sync: LazyArg<Service.AllowedType<Key, Make>>\n      readonly dependencies?: ReadonlyArray<Layer.Layer.Any>\n      readonly accessors?: boolean\n    }, Make>\n  >(\n    key: Key,\n    make: Make\n  ): Service.Class<Self, Key, Make>\n  <\n    const Key extends string,\n    const Make extends NoExcessProperties<{\n      readonly succeed: Service.AllowedType<Key, Make>\n      readonly dependencies?: ReadonlyArray<Layer.Layer.Any>\n      readonly accessors?: boolean\n    }, Make>\n  >(\n    key: Key,\n    make: Make\n  ): Service.Class<Self, Key, Make>\n} = function() {\n  return function() {\n    const [id, maker] = arguments\n    const proxy = \"accessors\" in maker ? maker[\"accessors\"] : false\n    const limit = Error.stackTraceLimit\n    Error.stackTraceLimit = 2\n    const creationError = new Error()\n    Error.stackTraceLimit = limit\n\n    let patchState: \"unchecked\" | \"plain\" | \"patched\" = \"unchecked\"\n    const TagClass: any = function(this: any, service: any) {\n      if (patchState === \"unchecked\") {\n        const proto = Object.getPrototypeOf(service)\n        if (proto === Object.prototype || proto === null) {\n          patchState = \"plain\"\n        } else {\n          const selfProto = Object.getPrototypeOf(this)\n          Object.setPrototypeOf(selfProto, proto)\n          patchState = \"patched\"\n        }\n      }\n      if (patchState === \"plain\") {\n        Object.assign(this, service)\n      } else if (patchState === \"patched\") {\n        Object.setPrototypeOf(service, Object.getPrototypeOf(this))\n        return service\n      }\n    }\n\n    TagClass.prototype._tag = id\n    Object.defineProperty(TagClass, \"make\", {\n      get() {\n        return (service: any) => new this(service)\n      }\n    })\n    Object.defineProperty(TagClass, \"use\", {\n      get() {\n        return (body: any) => core.andThen(this, body)\n      }\n    })\n    TagClass.key = id\n\n    Object.assign(TagClass, TagProto)\n\n    Object.defineProperty(TagClass, \"stack\", {\n      get() {\n        return creationError.stack\n      }\n    })\n\n    const hasDeps = \"dependencies\" in maker && maker.dependencies.length > 0\n    const layerName = hasDeps ? \"DefaultWithoutDependencies\" : \"Default\"\n    let layerCache: Layer.Layer.Any | undefined\n    let isFunction = false\n    if (\"effect\" in maker) {\n      isFunction = typeof maker.effect === \"function\"\n      Object.defineProperty(TagClass, layerName, {\n        get(this: any) {\n          if (isFunction) {\n            return function(this: typeof TagClass) {\n              return layer.fromEffect(TagClass, map(maker.effect.apply(null, arguments), (_) => new this(_)))\n            }.bind(this)\n          }\n          return layerCache ??= layer.fromEffect(TagClass, map(maker.effect, (_) => new this(_)))\n        }\n      })\n    } else if (\"scoped\" in maker) {\n      isFunction = typeof maker.scoped === \"function\"\n      Object.defineProperty(TagClass, layerName, {\n        get(this: any) {\n          if (isFunction) {\n            return function(this: typeof TagClass) {\n              return layer.scoped(TagClass, map(maker.scoped.apply(null, arguments), (_) => new this(_)))\n            }.bind(this)\n          }\n          return layerCache ??= layer.scoped(TagClass, map(maker.scoped, (_) => new this(_)))\n        }\n      })\n    } else if (\"sync\" in maker) {\n      Object.defineProperty(TagClass, layerName, {\n        get(this: any) {\n          return layerCache ??= layer.sync(TagClass, () => new this(maker.sync()))\n        }\n      })\n    } else {\n      Object.defineProperty(TagClass, layerName, {\n        get(this: any) {\n          return layerCache ??= layer.succeed(TagClass, new this(maker.succeed))\n        }\n      })\n    }\n\n    if (hasDeps) {\n      let layerWithDepsCache: Layer.Layer.Any | undefined\n      Object.defineProperty(TagClass, \"Default\", {\n        get(this: any) {\n          if (isFunction) {\n            return function(this: typeof TagClass) {\n              return layer.provide(\n                this.DefaultWithoutDependencies.apply(null, arguments),\n                maker.dependencies\n              )\n            }\n          }\n          return layerWithDepsCache ??= layer.provide(\n            this.DefaultWithoutDependencies,\n            maker.dependencies\n          )\n        }\n      })\n    }\n\n    return proxy === true ? makeTagProxy(TagClass) : TagClass\n  }\n} as any\n\n/**\n * @since 3.9.0\n * @category Context\n */\nexport declare namespace Service {\n  /**\n   * @since 3.9.0\n   */\n  export interface ProhibitedType {\n    Service?: `property \"Service\" is forbidden`\n    Identifier?: `property \"Identifier\" is forbidden`\n    Default?: `property \"Default\" is forbidden`\n    DefaultWithoutDependencies?: `property \"DefaultWithoutDependencies\" is forbidden`\n    _op_layer?: `property \"_op_layer\" is forbidden`\n    _op?: `property \"_op\" is forbidden`\n    of?: `property \"of\" is forbidden`\n    make?: `property \"make\" is forbidden`\n    context?: `property \"context\" is forbidden`\n    key?: `property \"key\" is forbidden`\n    stack?: `property \"stack\" is forbidden`\n    name?: `property \"name\" is forbidden`\n    pipe?: `property \"pipe\" is forbidden`\n    use?: `property \"use\" is forbidden`\n    _tag?: `property \"_tag\" is forbidden`\n  }\n\n  /**\n   * @since 3.9.0\n   */\n  export type AllowedType<Key extends string, Make> = MakeAccessors<Make> extends true ?\n      & Record<PropertyKey, any>\n      & {\n        readonly [K in Extract<keyof MakeService<Make>, keyof ProhibitedType>]: K extends \"_tag\" ? Key\n          : ProhibitedType[K]\n      }\n    : Record<PropertyKey, any> & { readonly _tag?: Key }\n\n  /**\n   * @since 3.9.0\n   */\n  export type Class<\n    Self,\n    Key extends string,\n    Make\n  > =\n    & {\n      new(_: MakeService<Make>): MakeService<Make> & {\n        readonly _tag: Key\n      }\n      readonly use: <X>(\n        body: (_: Self) => X\n      ) => [X] extends [Effect<infer A, infer E, infer R>] ? Effect<A, E, R | Self>\n        : [X] extends [PromiseLike<infer A>] ? Effect<A, Cause.UnknownException, Self>\n        : Effect<X, never, Self>\n      readonly make: (_: MakeService<Make>) => Self\n    }\n    & Context.Tag<Self, Self>\n    & { key: Key }\n    & (MakeAccessors<Make> extends true ? Tag.Proxy<Self, MakeService<Make>> : {})\n    & (MakeDeps<Make> extends never ? {\n        readonly Default: HasArguments<Make> extends true ?\n          (...args: MakeArguments<Make>) => Layer.Layer<Self, MakeError<Make>, MakeContext<Make>>\n          : Layer.Layer<Self, MakeError<Make>, MakeContext<Make>>\n      } :\n      {\n        readonly DefaultWithoutDependencies: HasArguments<Make> extends true\n          ? (...args: MakeArguments<Make>) => Layer.Layer<Self, MakeError<Make>, MakeContext<Make>>\n          : Layer.Layer<Self, MakeError<Make>, MakeContext<Make>>\n\n        readonly Default: HasArguments<Make> extends true ? (...args: MakeArguments<Make>) => Layer.Layer<\n            Self,\n            MakeError<Make> | MakeDepsE<Make>,\n            | Exclude<MakeContext<Make>, MakeDepsOut<Make>>\n            | MakeDepsIn<Make>\n          > :\n          Layer.Layer<\n            Self,\n            MakeError<Make> | MakeDepsE<Make>,\n            | Exclude<MakeContext<Make>, MakeDepsOut<Make>>\n            | MakeDepsIn<Make>\n          >\n      })\n\n  /**\n   * @since 3.9.0\n   */\n  export type MakeService<Make> = Make extends { readonly effect: Effect<infer _A, infer _E, infer _R> } ? _A\n    : Make extends { readonly scoped: Effect<infer _A, infer _E, infer _R> } ? _A\n    : Make extends { readonly effect: (...args: infer _Args) => Effect<infer _A, infer _E, infer _R> } ? _A\n    : Make extends { readonly scoped: (...args: infer _Args) => Effect<infer _A, infer _E, infer _R> } ? _A\n    : Make extends { readonly sync: LazyArg<infer A> } ? A\n    : Make extends { readonly succeed: infer A } ? A\n    : never\n\n  /**\n   * @since 3.9.0\n   */\n  export type MakeError<Make> = Make extends { readonly effect: Effect<infer _A, infer _E, infer _R> } ? _E\n    : Make extends { readonly scoped: Effect<infer _A, infer _E, infer _R> } ? _E\n    : Make extends { readonly effect: (...args: infer _Args) => Effect<infer _A, infer _E, infer _R> } ? _E\n    : Make extends { readonly scoped: (...args: infer _Args) => Effect<infer _A, infer _E, infer _R> } ? _E\n    : never\n\n  /**\n   * @since 3.9.0\n   */\n  export type MakeContext<Make> = Make extends { readonly effect: Effect<infer _A, infer _E, infer _R> } ? _R\n    : Make extends { readonly scoped: Effect<infer _A, infer _E, infer _R> } ? Exclude<_R, Scope.Scope>\n    : Make extends { readonly effect: (...args: infer _Args) => Effect<infer _A, infer _E, infer _R> } ? _R\n    : Make extends { readonly scoped: (...args: infer _Args) => Effect<infer _A, infer _E, infer _R> } ?\n      Exclude<_R, Scope.Scope>\n    : never\n\n  /**\n   * @since 3.9.0\n   */\n  export type MakeDeps<Make> = Make extends { readonly dependencies: ReadonlyArray<Layer.Layer.Any> }\n    ? Make[\"dependencies\"][number]\n    : never\n\n  /**\n   * @since 3.9.0\n   */\n  export type MakeDepsOut<Make> = Contravariant.Type<MakeDeps<Make>[Layer.LayerTypeId][\"_ROut\"]>\n\n  /**\n   * @since 3.9.0\n   */\n  export type MakeDepsE<Make> = Covariant.Type<MakeDeps<Make>[Layer.LayerTypeId][\"_E\"]>\n\n  /**\n   * @since 3.9.0\n   */\n  export type MakeDepsIn<Make> = Covariant.Type<MakeDeps<Make>[Layer.LayerTypeId][\"_RIn\"]>\n\n  /**\n   * @since 3.9.0\n   */\n  export type MakeAccessors<Make> = Make extends { readonly accessors: true } ? true\n    : false\n\n  /**\n   * @since 3.16.0\n   */\n  export type MakeArguments<Make> = Make extends\n    { readonly effect: (...args: infer Args) => Effect<infer _A, infer _E, infer _R> } ? Args\n    : Make extends { readonly scoped: (...args: infer Args) => Effect<infer _A, infer _E, infer _R> } ? Args\n    : never\n\n  /**\n   * @since 3.16.0\n   */\n  export type HasArguments<Make> = Make extends {\n    readonly scoped: (...args: ReadonlyArray<any>) => Effect<infer _A, infer _E, infer _R>\n  } ? true :\n    Make extends {\n      readonly effect: (...args: ReadonlyArray<any>) => Effect<infer _A, infer _E, infer _R>\n    } ? true :\n    false\n}\n\n/**\n * @since 3.11.0\n * @category Models\n */\nexport namespace fn {\n  /**\n   * @since 3.19.0\n   * @category Models\n   */\n  export type Return<A, E = never, R = never> = Generator<YieldWrap<Effect<any, E, R>>, A, any>\n  /**\n   * @since 3.11.0\n   * @category Models\n   */\n  export type Gen = {\n    <Eff extends YieldWrap<Effect<any, any, any>>, AEff, Args extends Array<any>>(\n      body: (...args: Args) => Generator<Eff, AEff, never>\n    ): (...args: Args) => Effect<\n      AEff,\n      [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n      [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n    >\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A extends Effect<any, any, any>\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A\n    ): (...args: Args) => Effect.AsEffect<A>\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B extends Effect<any, any, any>\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B\n    ): (...args: Args) => Effect.AsEffect<B>\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C extends Effect<any, any, any>\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C\n    ): (...args: Args) => Effect.AsEffect<C>\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D extends Effect<any, any, any>\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D\n    ): (...args: Args) => Effect.AsEffect<D>\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D,\n      E extends Effect<any, any, any>\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D,\n      e: (_: D, ...args: NoInfer<Args>) => E\n    ): (...args: Args) => Effect.AsEffect<E>\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D,\n      E,\n      F extends Effect<any, any, any>\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D,\n      e: (_: D, ...args: NoInfer<Args>) => E,\n      f: (_: E, ...args: NoInfer<Args>) => F\n    ): (...args: Args) => Effect.AsEffect<F>\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D,\n      E,\n      F,\n      G extends Effect<any, any, any>\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D,\n      e: (_: D, ...args: NoInfer<Args>) => E,\n      f: (_: E, ...args: NoInfer<Args>) => F,\n      g: (_: F, ...args: NoInfer<Args>) => G\n    ): (...args: Args) => Effect.AsEffect<G>\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D,\n      E,\n      F,\n      G,\n      H extends Effect<any, any, any>\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D,\n      e: (_: D, ...args: NoInfer<Args>) => E,\n      f: (_: E, ...args: NoInfer<Args>) => F,\n      g: (_: F, ...args: NoInfer<Args>) => G,\n      h: (_: G, ...args: NoInfer<Args>) => H\n    ): (...args: Args) => Effect.AsEffect<H>\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D,\n      E,\n      F,\n      G,\n      H,\n      I extends Effect<any, any, any>\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D,\n      e: (_: D, ...args: NoInfer<Args>) => E,\n      f: (_: E, ...args: NoInfer<Args>) => F,\n      g: (_: F, ...args: NoInfer<Args>) => G,\n      h: (_: G, ...args: NoInfer<Args>) => H,\n      i: (_: H, ...args: NoInfer<Args>) => I\n    ): (...args: Args) => Effect.AsEffect<I>\n  }\n\n  /**\n   * @since 3.11.0\n   * @category Models\n   */\n  export type NonGen = {\n    <Eff extends Effect<any, any, any>, Args extends Array<any>>(\n      body: (...args: Args) => Eff\n    ): (...args: Args) => Effect.AsEffect<Eff>\n    <Eff extends Effect<any, any, any>, A, Args extends Array<any>>(\n      body: (...args: Args) => A,\n      a: (_: A, ...args: NoInfer<Args>) => Eff\n    ): (...args: Args) => Effect.AsEffect<Eff>\n    <Eff extends Effect<any, any, any>, A, B, Args extends Array<any>>(\n      body: (...args: Args) => A,\n      a: (_: A, ...args: NoInfer<Args>) => B,\n      b: (_: B, ...args: NoInfer<Args>) => Eff\n    ): (...args: Args) => Effect.AsEffect<Eff>\n    <Eff extends Effect<any, any, any>, A, B, C, Args extends Array<any>>(\n      body: (...args: Args) => A,\n      a: (_: A, ...args: NoInfer<Args>) => B,\n      b: (_: B, ...args: NoInfer<Args>) => C,\n      c: (_: C, ...args: NoInfer<Args>) => Eff\n    ): (...args: Args) => Effect.AsEffect<Eff>\n    <Eff extends Effect<any, any, any>, A, B, C, D, Args extends Array<any>>(\n      body: (...args: Args) => A,\n      a: (_: A, ...args: NoInfer<Args>) => B,\n      b: (_: B, ...args: NoInfer<Args>) => C,\n      c: (_: C, ...args: NoInfer<Args>) => D,\n      d: (_: D, ...args: NoInfer<Args>) => Eff\n    ): (...args: Args) => Effect.AsEffect<Eff>\n    <Eff extends Effect<any, any, any>, A, B, C, D, E, Args extends Array<any>>(\n      body: (...args: Args) => A,\n      a: (_: A, ...args: NoInfer<Args>) => B,\n      b: (_: B, ...args: NoInfer<Args>) => C,\n      c: (_: C, ...args: NoInfer<Args>) => D,\n      d: (_: D, ...args: NoInfer<Args>) => E,\n      e: (_: E, ...args: NoInfer<Args>) => Eff\n    ): (...args: Args) => Effect.AsEffect<Eff>\n    <Eff extends Effect<any, any, any>, A, B, C, D, E, F, Args extends Array<any>>(\n      body: (...args: Args) => A,\n      a: (_: A, ...args: NoInfer<Args>) => B,\n      b: (_: B, ...args: NoInfer<Args>) => C,\n      c: (_: C, ...args: NoInfer<Args>) => D,\n      d: (_: D, ...args: NoInfer<Args>) => E,\n      e: (_: E, ...args: NoInfer<Args>) => F,\n      f: (_: F, ...args: NoInfer<Args>) => Eff\n    ): (...args: Args) => Effect.AsEffect<Eff>\n    <Eff extends Effect<any, any, any>, A, B, C, D, E, F, G, Args extends Array<any>>(\n      body: (...args: Args) => A,\n      a: (_: A, ...args: NoInfer<Args>) => B,\n      b: (_: B, ...args: NoInfer<Args>) => C,\n      c: (_: C, ...args: NoInfer<Args>) => D,\n      d: (_: D, ...args: NoInfer<Args>) => E,\n      e: (_: E, ...args: NoInfer<Args>) => F,\n      f: (_: F, ...args: NoInfer<Args>) => G,\n      g: (_: G, ...args: NoInfer<Args>) => Eff\n    ): (...args: Args) => Effect.AsEffect<Eff>\n    <Eff extends Effect<any, any, any>, A, B, C, D, E, F, G, H, Args extends Array<any>>(\n      body: (...args: Args) => A,\n      a: (_: A, ...args: NoInfer<Args>) => B,\n      b: (_: B, ...args: NoInfer<Args>) => C,\n      c: (_: C, ...args: NoInfer<Args>) => D,\n      d: (_: D, ...args: NoInfer<Args>) => E,\n      e: (_: E, ...args: NoInfer<Args>) => F,\n      f: (_: F, ...args: NoInfer<Args>) => G,\n      g: (_: G, ...args: NoInfer<Args>) => H,\n      h: (_: H, ...args: NoInfer<Args>) => Eff\n    ): (...args: Args) => Effect.AsEffect<Eff>\n    <Eff extends Effect<any, any, any>, A, B, C, D, E, F, G, H, I, Args extends Array<any>>(\n      body: (...args: Args) => A,\n      a: (_: A, ...args: NoInfer<Args>) => B,\n      b: (_: B, ...args: NoInfer<Args>) => C,\n      c: (_: C, ...args: NoInfer<Args>) => D,\n      d: (_: D, ...args: NoInfer<Args>) => E,\n      e: (_: E, ...args: NoInfer<Args>) => F,\n      f: (_: F, ...args: NoInfer<Args>) => G,\n      g: (_: G, ...args: NoInfer<Args>) => H,\n      h: (_: H, ...args: NoInfer<Args>) => I,\n      i: (_: H, ...args: NoInfer<Args>) => Eff\n    ): (...args: Args) => Effect.AsEffect<Eff>\n  }\n\n  /**\n   * @since 3.11.0\n   * @category Models\n   */\n  export type Untraced = {\n    <Eff extends YieldWrap<Effect<any, any, any>>, AEff, Args extends Array<any>>(\n      body: (...args: Args) => Generator<Eff, AEff, never>\n    ): (...args: Args) => Effect<\n      AEff,\n      [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n      [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n    >\n    <Eff extends YieldWrap<Effect<any, any, any>>, AEff, Args extends Array<any>, A>(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A\n    ): (...args: Args) => A\n    <Eff extends YieldWrap<Effect<any, any, any>>, AEff, Args extends Array<any>, A, B>(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B\n    ): (...args: Args) => B\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C\n    ): (...args: Args) => C\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D\n    ): (...args: Args) => D\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D,\n      E\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D,\n      e: (_: D, ...args: NoInfer<Args>) => E\n    ): (...args: Args) => E\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D,\n      E,\n      F\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D,\n      e: (_: D, ...args: NoInfer<Args>) => E,\n      f: (_: E, ...args: NoInfer<Args>) => F\n    ): (...args: Args) => F\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D,\n      E,\n      F,\n      G\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D,\n      e: (_: D, ...args: NoInfer<Args>) => E,\n      f: (_: E, ...args: NoInfer<Args>) => F,\n      g: (_: F, ...args: NoInfer<Args>) => G\n    ): (...args: Args) => G\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D,\n      E,\n      F,\n      G,\n      H\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D,\n      e: (_: D, ...args: NoInfer<Args>) => E,\n      f: (_: E, ...args: NoInfer<Args>) => F,\n      g: (_: F, ...args: NoInfer<Args>) => G,\n      h: (_: G, ...args: NoInfer<Args>) => H\n    ): (...args: Args) => H\n    <\n      Eff extends YieldWrap<Effect<any, any, any>>,\n      AEff,\n      Args extends Array<any>,\n      A,\n      B,\n      C,\n      D,\n      E,\n      F,\n      G,\n      H,\n      I\n    >(\n      body: (...args: Args) => Generator<Eff, AEff, never>,\n      a: (\n        _: Effect<\n          AEff,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,\n          [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never\n        >,\n        ...args: NoInfer<Args>\n      ) => A,\n      b: (_: A, ...args: NoInfer<Args>) => B,\n      c: (_: B, ...args: NoInfer<Args>) => C,\n      d: (_: C, ...args: NoInfer<Args>) => D,\n      e: (_: D, ...args: NoInfer<Args>) => E,\n      f: (_: E, ...args: NoInfer<Args>) => F,\n      g: (_: F, ...args: NoInfer<Args>) => G,\n      h: (_: G, ...args: NoInfer<Args>) => H,\n      i: (_: H, ...args: NoInfer<Args>) => I\n    ): (...args: Args) => I\n  }\n}\n\n/**\n * The `Effect.fn` function allows you to create traced functions that return an\n * effect. It provides two key features:\n *\n * - **Stack traces with location details** if an error occurs.\n * - **Automatic span creation** for tracing when a span name is provided.\n *\n * If a span name is passed as the first argument, the function's execution is\n * tracked using that name. If no name is provided, stack tracing still works,\n * but spans are not created.\n *\n * A function can be defined using either:\n *\n * - A generator function, allowing the use of `yield*` for effect composition.\n * - A regular function that returns an `Effect`.\n *\n * **Example** (Creating a Traced Function with a Span Name)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const myfunc = Effect.fn(\"myspan\")(function* <N extends number>(n: N) {\n *   yield* Effect.annotateCurrentSpan(\"n\", n) // Attach metadata to the span\n *   console.log(`got: ${n}`)\n *   yield* Effect.fail(new Error(\"Boom!\")) // Simulate failure\n * })\n *\n * Effect.runFork(myfunc(100).pipe(Effect.catchAllCause(Effect.logError)))\n * // Output:\n * // got: 100\n * // timestamp=... level=ERROR fiber=#0 cause=\"Error: Boom!\n * //     at <anonymous> (/.../index.ts:6:22) <= Raise location\n * //     at myspan (/.../index.ts:3:23)  <= Definition location\n * //     at myspan (/.../index.ts:9:16)\" <= Call location\n * ```\n *\n * `Effect.fn` automatically creates spans. The spans capture information about\n * the function execution, including metadata and error details.\n *\n * **Example** (Exporting Spans to the Console)\n *\n * ```ts skip-type-checking\n * import { Effect } from \"effect\"\n * import { NodeSdk } from \"@effect/opentelemetry\"\n * import {\n *   ConsoleSpanExporter,\n *   BatchSpanProcessor\n * } from \"@opentelemetry/sdk-trace-base\"\n *\n * const myfunc = Effect.fn(\"myspan\")(function* <N extends number>(n: N) {\n *   yield* Effect.annotateCurrentSpan(\"n\", n)\n *   console.log(`got: ${n}`)\n *   yield* Effect.fail(new Error(\"Boom!\"))\n * })\n *\n * const program = myfunc(100)\n *\n * const NodeSdkLive = NodeSdk.layer(() => ({\n *   resource: { serviceName: \"example\" },\n *   // Export span data to the console\n *   spanProcessor: new BatchSpanProcessor(new ConsoleSpanExporter())\n * }))\n *\n * Effect.runFork(program.pipe(Effect.provide(NodeSdkLive)))\n * // Output:\n * // got: 100\n * // {\n * //   resource: {\n * //     attributes: {\n * //       'service.name': 'example',\n * //       'telemetry.sdk.language': 'nodejs',\n * //       'telemetry.sdk.name': '@effect/opentelemetry',\n * //       'telemetry.sdk.version': '1.30.1'\n * //     }\n * //   },\n * //   instrumentationScope: { name: 'example', version: undefined, schemaUrl: undefined },\n * //   traceId: '22801570119e57a6e2aacda3dec9665b',\n * //   parentId: undefined,\n * //   traceState: undefined,\n * //   name: 'myspan',\n * //   id: '7af530c1e01bc0cb',\n * //   kind: 0,\n * //   timestamp: 1741182277518402.2,\n * //   duration: 4300.416,\n * //   attributes: {\n * //     n: 100,\n * //     'code.stacktrace': 'at <anonymous> (/.../index.ts:8:23)\\n' +\n * //       'at <anonymous> (/.../index.ts:14:17)'\n * //   },\n * //   status: { code: 2, message: 'Boom!' },\n * //   events: [\n * //     {\n * //       name: 'exception',\n * //       attributes: {\n * //         'exception.type': 'Error',\n * //         'exception.message': 'Boom!',\n * //         'exception.stacktrace': 'Error: Boom!\\n' +\n * //           '    at <anonymous> (/.../index.ts:11:22)\\n' +\n * //           '    at myspan (/.../index.ts:8:23)\\n' +\n * //           '    at myspan (/.../index.ts:14:17)'\n * //       },\n * //       time: [ 1741182277, 522702583 ],\n * //       droppedAttributesCount: 0\n * //     }\n * //   ],\n * //   links: []\n * // }\n * ```\n *\n * `Effect.fn` also acts as a pipe function, allowing you to create a pipeline\n * after the function definition using the effect returned by the generator\n * function as the starting value of the pipeline.\n *\n * **Example** (Creating a Traced Function with a Delay)\n *\n * ```ts\n * import { Effect } from \"effect\"\n *\n * const myfunc = Effect.fn(\n *   function* (n: number) {\n *     console.log(`got: ${n}`)\n *     yield* Effect.fail(new Error(\"Boom!\"))\n *   },\n *   // You can access both the created effect and the original arguments\n *   (effect, n) => Effect.delay(effect, `${n / 100} seconds`)\n * )\n *\n * Effect.runFork(myfunc(100).pipe(Effect.catchAllCause(Effect.logError)))\n * // Output:\n * // got: 100\n * // timestamp=... level=ERROR fiber=#0 cause=\"Error: Boom! (<= after 1 second)\n * ```\n *\n * @see {@link fnUntraced} for a version of this function that doesn't add a span.\n *\n * @since 3.11.0\n * @category Tracing\n */\nexport const fn:\n  & fn.Gen\n  & fn.NonGen\n  & ((\n    name: string,\n    options?: Tracer.SpanOptions\n  ) => fn.Gen & fn.NonGen) = function(nameOrBody: Function | string, ...pipeables: Array<any>) {\n    const limit = Error.stackTraceLimit\n    Error.stackTraceLimit = 2\n    const errorDef = new Error()\n    Error.stackTraceLimit = limit\n    if (typeof nameOrBody !== \"string\") {\n      return defineLength(nameOrBody.length, function(this: any, ...args: Array<any>) {\n        const limit = Error.stackTraceLimit\n        Error.stackTraceLimit = 2\n        const errorCall = new Error()\n        Error.stackTraceLimit = limit\n        return fnApply({\n          self: this,\n          body: nameOrBody,\n          args,\n          pipeables,\n          spanName: \"<anonymous>\",\n          spanOptions: {\n            context: internalTracer.DisablePropagation.context(true)\n          },\n          errorDef,\n          errorCall\n        })\n      }) as any\n    }\n    const name = nameOrBody\n    const options = pipeables[0]\n    return (body: Function, ...pipeables: Array<any>) =>\n      defineLength(\n        body.length,\n        ({\n          [name](this: any, ...args: Array<any>) {\n            const limit = Error.stackTraceLimit\n            Error.stackTraceLimit = 2\n            const errorCall = new Error()\n            Error.stackTraceLimit = limit\n            return fnApply({\n              self: this,\n              body,\n              args,\n              pipeables,\n              spanName: name,\n              spanOptions: options,\n              errorDef,\n              errorCall\n            })\n          }\n        })[name]\n      )\n  }\n\nfunction defineLength<F extends Function>(length: number, fn: F) {\n  return Object.defineProperty(fn, \"length\", {\n    value: length,\n    configurable: true\n  })\n}\n\nfunction fnApply(options: {\n  readonly self: any\n  readonly body: Function\n  readonly args: Array<any>\n  readonly pipeables: Array<any>\n  readonly spanName: string\n  readonly spanOptions: Tracer.SpanOptions\n  readonly errorDef: Error\n  readonly errorCall: Error\n}) {\n  let effect: Effect<any, any, any>\n  let fnError: any = undefined\n  if (isGeneratorFunction(options.body)) {\n    effect = core.fromIterator(() => options.body.apply(options.self, options.args))\n  } else {\n    try {\n      effect = options.body.apply(options.self, options.args)\n    } catch (error) {\n      fnError = error\n      effect = die(error)\n    }\n  }\n  if (options.pipeables.length > 0) {\n    try {\n      for (const x of options.pipeables) {\n        effect = x(effect, ...options.args)\n      }\n    } catch (error) {\n      effect = fnError\n        ? failCause(internalCause.sequential(\n          internalCause.die(fnError),\n          internalCause.die(error)\n        ))\n        : die(error)\n    }\n  }\n\n  let cache: false | string = false\n  const captureStackTrace = () => {\n    if (cache !== false) {\n      return cache\n    }\n    if (options.errorCall.stack) {\n      const stackDef = options.errorDef.stack!.trim().split(\"\\n\")\n      const stackCall = options.errorCall.stack.trim().split(\"\\n\")\n      let endStackDef = stackDef.slice(2).join(\"\\n\").trim()\n      if (!endStackDef.includes(`(`)) {\n        endStackDef = endStackDef.replace(/at (.*)/, \"at ($1)\")\n      }\n      let endStackCall = stackCall.slice(2).join(\"\\n\").trim()\n      if (!endStackCall.includes(`(`)) {\n        endStackCall = endStackCall.replace(/at (.*)/, \"at ($1)\")\n      }\n      cache = `${endStackDef}\\n${endStackCall}`\n      return cache\n    }\n  }\n  const opts: any = (options.spanOptions && \"captureStackTrace\" in options.spanOptions)\n    ? options.spanOptions\n    : { captureStackTrace, ...options.spanOptions }\n  return withSpan(effect, options.spanName, opts)\n}\n\n/**\n * Same as {@link fn}, but allows you to create a function that is not traced, for when performance is critical.\n *\n * @see {@link fn} for a version that includes tracing.\n *\n * @since 3.12.0\n * @category Tracing\n */\nexport const fnUntraced: fn.Untraced = core.fnUntraced\n\n// -----------------------------------------------------------------------------\n// Type constraints\n// -----------------------------------------------------------------------------\n\n/**\n * A no-op type constraint that enforces the success channel of an Effect conforms to\n * the specified success type `A`.\n *\n * @example\n * import { Effect } from \"effect\"\n *\n * // Ensure that the program does not expose any unhandled errors.\n * const program = Effect.succeed(42).pipe(Effect.ensureSuccessType<number>())\n *\n * @since 3.17.0\n * @category Type constraints\n */\nexport const ensureSuccessType = <A>() => <A2 extends A, E, R>(effect: Effect<A2, E, R>): Effect<A2, E, R> => effect\n\n/**\n * A no-op type constraint that enforces the error channel of an Effect conforms to\n * the specified error type `E`.\n *\n * @example\n * import { Effect } from \"effect\"\n *\n * // Ensure that the program does not expose any unhandled errors.\n * const program = Effect.succeed(42).pipe(Effect.ensureErrorType<never>())\n *\n * @since 3.17.0\n * @category Type constraints\n */\nexport const ensureErrorType = <E>() => <A, E2 extends E, R>(effect: Effect<A, E2, R>): Effect<A, E2, R> => effect\n\n/**\n * A no-op type constraint that enforces the requirements channel of an Effect conforms to\n * the specified requirements type `R`.\n *\n * @example\n * import { Effect } from \"effect\"\n *\n * // Ensure that the program does not have any requirements.\n * const program = Effect.succeed(42).pipe(Effect.ensureRequirementsType<never>())\n *\n * @since 3.17.0\n * @category Type constraints\n */\nexport const ensureRequirementsType = <R>() => <A, E, R2 extends R>(effect: Effect<A, E, R2>): Effect<A, E, R2> =>\n  effect\n"
  },
  {
    "path": "packages/effect/src/Effectable.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Channel from \"./Channel.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/effectable.js\"\nimport type * as Sink from \"./Sink.js\"\nimport type * as Stream from \"./Stream.js\"\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport const EffectTypeId: Effect.EffectTypeId = internal.EffectTypeId\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport type EffectTypeId = Effect.EffectTypeId\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport const StreamTypeId: Stream.StreamTypeId = internal.StreamTypeId\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport type StreamTypeId = Stream.StreamTypeId\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport const SinkTypeId: Sink.SinkTypeId = internal.SinkTypeId\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport type SinkTypeId = Sink.SinkTypeId\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport const ChannelTypeId: Channel.ChannelTypeId = internal.ChannelTypeId\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport type ChannelTypeId = Channel.ChannelTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface CommitPrimitive {\n  new<A, E = never, R = never>(): Effect.Effect<A, E, R>\n}\n\n/**\n * @since 2.0.0\n * @category prototypes\n */\nexport const EffectPrototype: Effect.Effect<never> = internal.EffectPrototype\n\n/**\n * @since 2.0.0\n * @category prototypes\n */\nexport const CommitPrototype: Effect.Effect<never> = internal.CommitPrototype\n\n/**\n * @since 2.0.0\n * @category prototypes\n */\nexport const StructuralCommitPrototype: Effect.Effect<never> = internal.StructuralCommitPrototype\n\nconst Base: CommitPrimitive = internal.Base\nconst StructuralBase: CommitPrimitive = internal.StructuralBase\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport abstract class Class<A, E = never, R = never> extends Base<A, E, R> {\n  /**\n   * @since 2.0.0\n   */\n  abstract commit(): Effect.Effect<A, E, R>\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport abstract class StructuralClass<A, E = never, R = never> extends StructuralBase<A, E, R> {\n  /**\n   * @since 2.0.0\n   */\n  abstract commit(): Effect.Effect<A, E, R>\n}\n"
  },
  {
    "path": "packages/effect/src/Either.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport * as Equivalence from \"./Equivalence.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport { constNull, constUndefined, dual, identity } from \"./Function.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as doNotation from \"./internal/doNotation.js\"\nimport * as either from \"./internal/either.js\"\nimport * as option_ from \"./internal/option.js\"\nimport type { Option } from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport { isFunction } from \"./Predicate.js\"\nimport type { Covariant, NoInfer, NotFunction } from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\nimport * as Gen from \"./Utils.js\"\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport type Either<A, E = never> = Left<E, A> | Right<E, A>\n\n/**\n * @category symbols\n * @since 2.0.0\n */\nexport const TypeId: unique symbol = either.TypeId\n\n/**\n * @category symbols\n * @since 2.0.0\n */\nexport type TypeId = typeof TypeId\n\n// TODO(4.0): flip the order of the type parameters\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface Left<out E, out A> extends Pipeable, Inspectable {\n  readonly _tag: \"Left\"\n  readonly _op: \"Left\"\n  readonly left: E\n  readonly [TypeId]: {\n    readonly _R: Covariant<A>\n    readonly _L: Covariant<E>\n  }\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: EitherUnify<this>\n  [Unify.ignoreSymbol]?: EitherUnifyIgnore\n}\n\n// TODO(4.0): flip the order of the type parameters\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface Right<out E, out A> extends Pipeable, Inspectable {\n  readonly _tag: \"Right\"\n  readonly _op: \"Right\"\n  readonly right: A\n  readonly [TypeId]: {\n    readonly _R: Covariant<A>\n    readonly _L: Covariant<E>\n  }\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: EitherUnify<this>\n  [Unify.ignoreSymbol]?: EitherUnifyIgnore\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface EitherUnify<A extends { [Unify.typeSymbol]?: any }> {\n  Either?: () => A[Unify.typeSymbol] extends Either<infer R0, infer L0> | infer _ ? Either<R0, L0> : never\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface EitherUnifyIgnore {}\n\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface EitherTypeLambda extends TypeLambda {\n  readonly type: Either<this[\"Target\"], this[\"Out1\"]>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Either {\n  /**\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type Left<T extends Either<any, any>> = [T] extends [Either<infer _A, infer _E>] ? _E : never\n  /**\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type Right<T extends Either<any, any>> = [T] extends [Either<infer _A, infer _E>] ? _A : never\n}\n\n/**\n * Constructs a new `Either` holding a `Right` value. This usually represents a successful value due to the right bias\n * of this structure.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const right: <A>(a: A) => Either<A> = either.right\n\nconst void_: Either<void> = right(void 0)\nexport {\n  /**\n   * @category constructors\n   * @since 3.13.0\n   */\n  void_ as void\n}\n\n/**\n * Constructs a new `Either` holding a `Left` value. This usually represents a failure, due to the right-bias of this\n * structure.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const left: <E>(e: E) => Either<never, E> = either.left\n\n/**\n * Takes a lazy default and a nullable value, if the value is not nully (`null` or `undefined`), turn it into a `Right`, if the value is nully use\n * the provided default as a `Left`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either } from \"effect\"\n *\n * assert.deepStrictEqual(Either.fromNullable(1, () => 'fallback'), Either.right(1))\n * assert.deepStrictEqual(Either.fromNullable(null, () => 'fallback'), Either.left('fallback'))\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromNullable: {\n  <A, E>(onNullable: (right: A) => E): (self: A) => Either<NonNullable<A>, E>\n  <A, E>(self: A, onNullable: (right: A) => E): Either<NonNullable<A>, E>\n} = dual(\n  2,\n  <A, E>(self: A, onNullable: (right: A) => E): Either<NonNullable<A>, E> =>\n    self == null ? left(onNullable(self)) : right(self)\n)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either, Option } from \"effect\"\n *\n * assert.deepStrictEqual(Either.fromOption(Option.some(1), () => 'error'), Either.right(1))\n * assert.deepStrictEqual(Either.fromOption(Option.none(), () => 'error'), Either.left('error'))\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromOption: {\n  <E>(onNone: () => E): <A>(self: Option<A>) => Either<A, E>\n  <A, E>(self: Option<A>, onNone: () => E): Either<A, E>\n} = either.fromOption\n\nconst try_: {\n  <A, E>(\n    options: {\n      readonly try: LazyArg<A>\n      readonly catch: (error: unknown) => E\n    }\n  ): Either<A, E>\n  <A>(evaluate: LazyArg<A>): Either<A, unknown>\n} = (<A, E>(\n  evaluate: LazyArg<A> | {\n    readonly try: LazyArg<A>\n    readonly catch: (error: unknown) => E\n  }\n) => {\n  if (isFunction(evaluate)) {\n    try {\n      return right(evaluate())\n    } catch (e) {\n      return left(e)\n    }\n  } else {\n    try {\n      return right(evaluate.try())\n    } catch (e) {\n      return left(evaluate.catch(e))\n    }\n  }\n}) as any\n\nexport {\n  /**\n   * Imports a synchronous side-effect into a pure `Either` value, translating any\n   * thrown exceptions into typed failed eithers creating with `Either.left`.\n   *\n   * @category constructors\n   * @since 2.0.0\n   */\n  try_ as try\n}\n\n/**\n * Tests if a value is a `Either`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either } from \"effect\"\n *\n * assert.deepStrictEqual(Either.isEither(Either.right(1)), true)\n * assert.deepStrictEqual(Either.isEither(Either.left(\"a\")), true)\n * assert.deepStrictEqual(Either.isEither({ right: 1 }), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEither: (input: unknown) => input is Either<unknown, unknown> = either.isEither\n\n/**\n * Determine if a `Either` is a `Left`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either } from \"effect\"\n *\n * assert.deepStrictEqual(Either.isLeft(Either.right(1)), false)\n * assert.deepStrictEqual(Either.isLeft(Either.left(\"a\")), true)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isLeft: <A, E>(self: Either<A, E>) => self is Left<E, A> = either.isLeft\n\n/**\n * Determine if a `Either` is a `Right`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either } from \"effect\"\n *\n * assert.deepStrictEqual(Either.isRight(Either.right(1)), true)\n * assert.deepStrictEqual(Either.isRight(Either.left(\"a\")), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isRight: <A, E>(self: Either<A, E>) => self is Right<E, A> = either.isRight\n\n/**\n * Converts a `Either` to an `Option` discarding the `Left`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either, Option } from \"effect\"\n *\n * assert.deepStrictEqual(Either.getRight(Either.right('ok')), Option.some('ok'))\n * assert.deepStrictEqual(Either.getRight(Either.left('err')), Option.none())\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getRight: <A, E>(self: Either<A, E>) => Option<A> = either.getRight\n\n/**\n * Converts a `Either` to an `Option` discarding the value.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either, Option } from \"effect\"\n *\n * assert.deepStrictEqual(Either.getLeft(Either.right('ok')), Option.none())\n * assert.deepStrictEqual(Either.getLeft(Either.left('err')), Option.some('err'))\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getLeft: <A, E>(self: Either<A, E>) => Option<E> = either.getLeft\n\n/**\n * @category equivalence\n * @since 2.0.0\n */\nexport const getEquivalence = <A, E>({ left, right }: {\n  right: Equivalence.Equivalence<A>\n  left: Equivalence.Equivalence<E>\n}): Equivalence.Equivalence<Either<A, E>> =>\n  Equivalence.make((x, y) =>\n    isLeft(x) ?\n      isLeft(y) && left(x.left, y.left) :\n      isRight(y) && right(x.right, y.right)\n  )\n\n/**\n * @category mapping\n * @since 2.0.0\n */\nexport const mapBoth: {\n  <E, E2, A, A2>(options: {\n    readonly onLeft: (left: E) => E2\n    readonly onRight: (right: A) => A2\n  }): (self: Either<A, E>) => Either<A2, E2>\n  <A, E, E2, A2>(self: Either<A, E>, options: {\n    readonly onLeft: (left: E) => E2\n    readonly onRight: (right: A) => A2\n  }): Either<A2, E2>\n} = dual(\n  2,\n  <A, E, E2, A2>(self: Either<A, E>, { onLeft, onRight }: {\n    readonly onLeft: (left: E) => E2\n    readonly onRight: (right: A) => A2\n  }): Either<A2, E2> => isLeft(self) ? left(onLeft(self.left)) : right(onRight(self.right))\n)\n\n/**\n * Maps the `Left` side of an `Either` value to a new `Either` value.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapLeft: {\n  <E, E2>(f: (left: E) => E2): <A>(self: Either<A, E>) => Either<A, E2>\n  <A, E, E2>(self: Either<A, E>, f: (left: E) => E2): Either<A, E2>\n} = dual(\n  2,\n  <A, E, E2>(self: Either<A, E>, f: (left: E) => E2): Either<A, E2> =>\n    isLeft(self) ? left(f(self.left)) : right(self.right)\n)\n\n/**\n * Maps the `Right` side of an `Either` value to a new `Either` value.\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map: {\n  <A, A2>(f: (right: A) => A2): <E>(self: Either<A, E>) => Either<A2, E>\n  <A, E, A2>(self: Either<A, E>, f: (right: A) => A2): Either<A2, E>\n} = dual(\n  2,\n  <A, E, A2>(self: Either<A, E>, f: (right: A) => A2): Either<A2, E> =>\n    isRight(self) ? right(f(self.right)) : left(self.left)\n)\n\n/**\n * Takes two functions and an `Either` value, if the value is a `Left` the inner value is applied to the `onLeft function,\n * if the value is a `Right` the inner value is applied to the `onRight` function.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, Either } from \"effect\"\n *\n * const onLeft  = (strings: ReadonlyArray<string>): string => `strings: ${strings.join(', ')}`\n *\n * const onRight = (value: number): string => `Ok: ${value}`\n *\n * assert.deepStrictEqual(pipe(Either.right(1), Either.match({ onLeft, onRight })), 'Ok: 1')\n * assert.deepStrictEqual(\n *   pipe(Either.left(['string 1', 'string 2']), Either.match({ onLeft, onRight })),\n *   'strings: string 1, string 2'\n * )\n * ```\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const match: {\n  <E, B, A, C = B>(options: {\n    readonly onLeft: (left: E) => B\n    readonly onRight: (right: A) => C\n  }): (self: Either<A, E>) => B | C\n  <A, E, B, C = B>(self: Either<A, E>, options: {\n    readonly onLeft: (left: E) => B\n    readonly onRight: (right: A) => C\n  }): B | C\n} = dual(\n  2,\n  <A, E, B, C = B>(self: Either<A, E>, { onLeft, onRight }: {\n    readonly onLeft: (left: E) => B\n    readonly onRight: (right: A) => C\n  }): B | C => isLeft(self) ? onLeft(self.left) : onRight(self.right)\n)\n\n/**\n * Transforms a `Predicate` function into a `Right` of the input value if the predicate returns `true`\n * or `Left` of the result of the provided function if the predicate returns false\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, Either } from \"effect\"\n *\n * const isPositive = (n: number): boolean => n > 0\n * const isPositiveEither = Either.liftPredicate(isPositive, n => `${n} is not positive`)\n *\n * assert.deepStrictEqual(\n *   isPositiveEither(1),\n *   Either.right(1)\n * )\n * assert.deepStrictEqual(\n *   isPositiveEither(0),\n *   Either.left(\"0 is not positive\")\n * )\n * ```\n *\n * @category lifting\n * @since 3.4.0\n */\nexport const liftPredicate: {\n  <A, B extends A, E>(refinement: Refinement<A, B>, orLeftWith: (a: A) => E): (a: A) => Either<B, E>\n  <B extends A, E, A = B>(\n    predicate: Predicate<A>,\n    orLeftWith: (a: A) => E\n  ): (a: B) => Either<B, E>\n  <A, E, B extends A>(\n    self: A,\n    refinement: Refinement<A, B>,\n    orLeftWith: (a: A) => E\n  ): Either<B, E>\n  <B extends A, E, A = B>(\n    self: B,\n    predicate: Predicate<A>,\n    orLeftWith: (a: A) => E\n  ): Either<B, E>\n} = dual(\n  3,\n  <A, E>(a: A, predicate: Predicate<A>, orLeftWith: (a: A) => E): Either<A, E> =>\n    predicate(a) ? right(a) : left(orLeftWith(a))\n)\n\n/**\n * Filter the right value with the provided function.\n * If the predicate fails, set the left value with the result of the provided function.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, Either } from \"effect\"\n *\n * const isPositive = (n: number): boolean => n > 0\n *\n * assert.deepStrictEqual(\n *   pipe(\n *     Either.right(1),\n *     Either.filterOrLeft(isPositive, n => `${n} is not positive`)\n *   ),\n *   Either.right(1)\n * )\n * assert.deepStrictEqual(\n *   pipe(\n *     Either.right(0),\n *     Either.filterOrLeft(isPositive, n => `${n} is not positive`)\n *   ),\n *   Either.left(\"0 is not positive\")\n * )\n * ```\n *\n * @since 2.0.0\n * @category filtering & conditionals\n */\nexport const filterOrLeft: {\n  <A, B extends A, E2>(\n    refinement: Refinement<NoInfer<A>, B>,\n    orLeftWith: (right: NoInfer<A>) => E2\n  ): <E>(self: Either<A, E>) => Either<B, E2 | E>\n  <A, E2>(\n    predicate: Predicate<NoInfer<A>>,\n    orLeftWith: (right: NoInfer<A>) => E2\n  ): <E>(self: Either<A, E>) => Either<A, E2 | E>\n  <A, E, B extends A, E2>(\n    self: Either<A, E>,\n    refinement: Refinement<A, B>,\n    orLeftWith: (right: A) => E2\n  ): Either<B, E | E2>\n  <A, E, E2>(self: Either<A, E>, predicate: Predicate<A>, orLeftWith: (right: A) => E2): Either<A, E | E2>\n} = dual(3, <A, E, E2>(\n  self: Either<A, E>,\n  predicate: Predicate<A>,\n  orLeftWith: (right: A) => E2\n): Either<A, E | E2> => flatMap(self, (r) => predicate(r) ? right(r) : left(orLeftWith(r))))\n\n/**\n * @category getters\n * @since 2.0.0\n */\nexport const merge: <A, E>(self: Either<A, E>) => E | A = match({\n  onLeft: identity,\n  onRight: identity\n})\n\n/**\n * Returns the wrapped value if it's a `Right` or a default value if is a `Left`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either } from \"effect\"\n *\n * assert.deepStrictEqual(Either.getOrElse(Either.right(1), (error) => error + \"!\"), 1)\n * assert.deepStrictEqual(Either.getOrElse(Either.left(\"not a number\"), (error) => error + \"!\"), \"not a number!\")\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrElse: {\n  <E, A2>(onLeft: (left: E) => A2): <A>(self: Either<A, E>) => A2 | A\n  <A, E, A2>(self: Either<A, E>, onLeft: (left: E) => A2): A | A2\n} = dual(\n  2,\n  <A, E, A2>(self: Either<A, E>, onLeft: (left: E) => A2): A | A2 => isLeft(self) ? onLeft(self.left) : self.right\n)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either } from \"effect\"\n *\n * assert.deepStrictEqual(Either.getOrNull(Either.right(1)), 1)\n * assert.deepStrictEqual(Either.getOrNull(Either.left(\"a\")), null)\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrNull: <A, E>(self: Either<A, E>) => A | null = getOrElse(constNull)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either } from \"effect\"\n *\n * assert.deepStrictEqual(Either.getOrUndefined(Either.right(1)), 1)\n * assert.deepStrictEqual(Either.getOrUndefined(Either.left(\"a\")), undefined)\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrUndefined: <A, E>(self: Either<A, E>) => A | undefined = getOrElse(constUndefined)\n\n/**\n * Extracts the value of an `Either` or throws if the `Either` is `Left`.\n *\n * If a default error is sufficient for your use case and you don't need to configure the thrown error, see {@link getOrThrow}.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Either.getOrThrowWith(Either.right(1), () => new Error('Unexpected Left')),\n *   1\n * )\n * assert.throws(() => Either.getOrThrowWith(Either.left(\"error\"), () => new Error('Unexpected Left')))\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrThrowWith: {\n  <E>(onLeft: (left: E) => unknown): <A>(self: Either<A, E>) => A\n  <A, E>(self: Either<A, E>, onLeft: (left: E) => unknown): A\n} = dual(2, <A, E>(self: Either<A, E>, onLeft: (left: E) => unknown): A => {\n  if (isRight(self)) {\n    return self.right\n  }\n  throw onLeft(self.left)\n})\n\n// TODO(4.0): by default should throw `L` (i.e getOrThrowWith with the identity function)\n/**\n * Extracts the value of an `Either` or throws if the `Either` is `Left`.\n *\n * The thrown error is a default error. To configure the error thrown, see  {@link getOrThrowWith}.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either } from \"effect\"\n *\n * assert.deepStrictEqual(Either.getOrThrow(Either.right(1)), 1)\n * assert.throws(() => Either.getOrThrow(Either.left(\"error\")))\n * ```\n *\n * @throws `Error(\"getOrThrow called on a Left\")`\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getOrThrow: <A, E>(self: Either<A, E>) => A = getOrThrowWith(() =>\n  new Error(\"getOrThrow called on a Left\")\n)\n\n/**\n * Returns `self` if it is a `Right` or `that` otherwise.\n *\n * @category error handling\n * @since 2.0.0\n */\nexport const orElse: {\n  <E, A2, E2>(that: (left: E) => Either<A2, E2>): <A>(self: Either<A, E>) => Either<A | A2, E2>\n  <A, E, A2, E2>(self: Either<A, E>, that: (left: E) => Either<A2, E2>): Either<A | A2, E2>\n} = dual(\n  2,\n  <A, E, A2, E2>(self: Either<A, E>, that: (left: E) => Either<A2, E2>): Either<A | A2, E2> =>\n    isLeft(self) ? that(self.left) : right(self.right)\n)\n\n/**\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap: {\n  <A, A2, E2>(f: (right: A) => Either<A2, E2>): <E>(self: Either<A, E>) => Either<A2, E | E2>\n  <A, E, A2, E2>(self: Either<A, E>, f: (right: A) => Either<A2, E2>): Either<A2, E | E2>\n} = dual(\n  2,\n  <A, E, A2, E2>(self: Either<A, E>, f: (right: A) => Either<A2, E2>): Either<A2, E | E2> =>\n    isLeft(self) ? left(self.left) : f(self.right)\n)\n\n/**\n * Executes a sequence of two `Either`s. The second `Either` can be dependent on the result of the first `Either`.\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const andThen: {\n  <A, A2, E2>(f: (right: A) => Either<A2, E2>): <E>(self: Either<A, E>) => Either<A2, E | E2>\n  <A2, E2>(f: Either<A2, E2>): <E, A>(self: Either<A, E>) => Either<A2, E | E2>\n  <A, A2>(f: (right: A) => A2): <E>(self: Either<A, E>) => Either<A2, E>\n  <A2>(right: NotFunction<A2>): <A, E>(self: Either<A, E>) => Either<A2, E>\n  <A, E, A2, E2>(self: Either<A, E>, f: (right: A) => Either<A2, E2>): Either<A2, E | E2>\n  <A, E, A2, E2>(self: Either<A, E>, f: Either<A2, E2>): Either<A2, E | E2>\n  <A, E, A2>(self: Either<A, E>, f: (right: A) => A2): Either<A2, E>\n  <A, E, A2>(self: Either<A, E>, f: NotFunction<A2>): Either<A2, E>\n} = dual(\n  2,\n  <A, E, A2, E2>(self: Either<A, E>, f: (right: A) => Either<A2, E2> | Either<A2, E2>): Either<A2, E | E2> =>\n    flatMap(self, (a) => {\n      const b = isFunction(f) ? f(a) : f\n      return isEither(b) ? b : right(b)\n    })\n)\n\n/**\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith: {\n  <A2, E2, A, B>(\n    that: Either<A2, E2>,\n    f: (right: A, right2: A2) => B\n  ): <E>(self: Either<A, E>) => Either<B, E2 | E>\n  <A, E, A2, E2, B>(\n    self: Either<A, E>,\n    that: Either<A2, E2>,\n    f: (right: A, right2: A2) => B\n  ): Either<B, E | E2>\n} = dual(\n  3,\n  <A, E, A2, E2, B>(self: Either<A, E>, that: Either<A2, E2>, f: (right: A, right2: A2) => B): Either<B, E | E2> =>\n    flatMap(self, (r) => map(that, (r2) => f(r, r2)))\n)\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const ap: {\n  <A, E2>(that: Either<A, E2>): <A2, E>(self: Either<(right: A) => A2, E>) => Either<A2, E | E2>\n  <A, A2, E, E2>(self: Either<(right: A) => A2, E>, that: Either<A, E2>): Either<A2, E | E2>\n} = dual(\n  2,\n  <A, E, A2, E2>(self: Either<(right: A) => A2, E>, that: Either<A, E2>): Either<A2, E | E2> =>\n    zipWith(self, that, (f, a) => f(a))\n)\n\n/**\n * Takes a structure of `Either`s and returns an `Either` of values with the same structure.\n *\n * - If a tuple is supplied, then the returned `Either` will contain a tuple with the same length.\n * - If a struct is supplied, then the returned `Either` will contain a struct with the same keys.\n * - If an iterable is supplied, then the returned `Either` will contain an array.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either } from \"effect\"\n *\n * assert.deepStrictEqual(Either.all([Either.right(1), Either.right(2)]), Either.right([1, 2]))\n * assert.deepStrictEqual(Either.all({ right: Either.right(1), b: Either.right(\"hello\") }), Either.right({ right: 1, b: \"hello\" }))\n * assert.deepStrictEqual(Either.all({ right: Either.right(1), b: Either.left(\"error\") }), Either.left(\"error\"))\n * ```\n *\n * @category combining\n * @since 2.0.0\n */\n// @ts-expect-error\nexport const all: <const I extends Iterable<Either<any, any>> | Record<string, Either<any, any>>>(\n  input: I\n) => [I] extends [ReadonlyArray<Either<any, any>>] ? Either<\n    { -readonly [K in keyof I]: [I[K]] extends [Either<infer A, any>] ? A : never },\n    I[number] extends never ? never : [I[number]] extends [Either<any, infer E>] ? E : never\n  >\n  : [I] extends [Iterable<Either<infer A, infer E>>] ? Either<Array<A>, E>\n  : Either<\n    { -readonly [K in keyof I]: [I[K]] extends [Either<infer A, any>] ? A : never },\n    I[keyof I] extends never ? never : [I[keyof I]] extends [Either<any, infer E>] ? E : never\n  > = (\n    input: Iterable<Either<any, any>> | Record<string, Either<any, any>>\n  ): Either<any, any> => {\n    if (Symbol.iterator in input) {\n      const out: Array<Either<any, any>> = []\n      for (const e of input) {\n        if (isLeft(e)) {\n          return e\n        }\n        out.push(e.right)\n      }\n      return right(out)\n    }\n\n    const out: Record<string, any> = {}\n    for (const key of Object.keys(input)) {\n      const e = input[key]\n      if (isLeft(e)) {\n        return e\n      }\n      out[key] = e.right\n    }\n    return right(out)\n  }\n\n/**\n * Returns an `Either` that swaps the error/success cases. This allows you to\n * use all methods on the error channel, possibly before flipping back.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const flip = <A, E>(self: Either<A, E>): Either<E, A> => isLeft(self) ? right(self.left) : left(self.right)\n\nconst adapter = Gen.adapter<EitherTypeLambda>()\n\n/**\n * @category generators\n * @since 2.0.0\n */\nexport const gen: Gen.Gen<EitherTypeLambda, Gen.Adapter<EitherTypeLambda>> = (...args) => {\n  const f = args.length === 1 ? args[0] : args[1].bind(args[0])\n  const iterator = f(adapter)\n  let state: IteratorResult<any> = iterator.next()\n  while (!state.done) {\n    const current = Gen.isGenKind(state.value)\n      ? state.value.value\n      : Gen.yieldWrapGet(state.value)\n    if (isLeft(current)) {\n      return current\n    }\n    state = iterator.next(current.right as never)\n  }\n  return right(state.value) as any\n}\n\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Either` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either, pipe } from \"effect\"\n *\n * const result = pipe(\n *   Either.Do,\n *   Either.bind(\"x\", () => Either.right(2)),\n *   Either.bind(\"y\", () => Either.right(3)),\n *   Either.let(\"sum\", ({ x, y }) => x + y)\n * )\n * assert.deepStrictEqual(result, Either.right({ x: 2, y: 3, sum: 5 }))\n * ```\n *\n * @see {@link bind}\n * @see {@link bindTo}\n * @see {@link let_ let}\n *\n * @category do notation\n * @since 2.0.0\n */\nexport const Do: Either<{}> = right({})\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Either` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either, pipe } from \"effect\"\n *\n * const result = pipe(\n *   Either.Do,\n *   Either.bind(\"x\", () => Either.right(2)),\n *   Either.bind(\"y\", () => Either.right(3)),\n *   Either.let(\"sum\", ({ x, y }) => x + y)\n * )\n * assert.deepStrictEqual(result, Either.right({ x: 2, y: 3, sum: 5 }))\n * ```\n *\n * @see {@link Do}\n * @see {@link bindTo}\n * @see {@link let_ let}\n *\n * @category do notation\n * @since 2.0.0\n */\nexport const bind: {\n  <N extends string, A extends object, B, E2>(\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => Either<B, E2>\n  ): <E>(self: Either<A, E>) => Either<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E | E2>\n  <A extends object, E, N extends string, B, E2>(\n    self: Either<A, E>,\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => Either<B, E2>\n  ): Either<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E | E2>\n} = doNotation.bind<EitherTypeLambda>(map, flatMap)\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Either` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either, pipe } from \"effect\"\n *\n * const result = pipe(\n *   Either.Do,\n *   Either.bind(\"x\", () => Either.right(2)),\n *   Either.bind(\"y\", () => Either.right(3)),\n *   Either.let(\"sum\", ({ x, y }) => x + y)\n * )\n * assert.deepStrictEqual(result, Either.right({ x: 2, y: 3, sum: 5 }))\n * ```\n *\n * @see {@link Do}\n * @see {@link bind}\n * @see {@link let_ let}\n *\n * @category do notation\n * @since 2.0.0\n */\nexport const bindTo: {\n  <N extends string>(name: N): <A, E>(self: Either<A, E>) => Either<{ [K in N]: A }, E>\n  <A, E, N extends string>(self: Either<A, E>, name: N): Either<{ [K in N]: A }, E>\n} = doNotation.bindTo<EitherTypeLambda>(map)\n\nconst let_: {\n  <N extends string, A extends object, B>(\n    name: Exclude<N, keyof A>,\n    f: (r: NoInfer<A>) => B\n  ): <E>(self: Either<A, E>) => Either<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E>\n  <A extends object, E, N extends string, B>(\n    self: Either<A, E>,\n    name: Exclude<N, keyof A>,\n    f: (r: NoInfer<A>) => B\n  ): Either<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E>\n} = doNotation.let_<EitherTypeLambda>(map)\n\nexport {\n  /**\n   * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n   *\n   * Here's how the do simulation works:\n   *\n   * 1. Start the do simulation using the `Do` value\n   * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Either` values\n   * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n   * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n   *\n   * @example\n   * ```ts\n   * import * as assert from \"node:assert\"\n   * import { Either, pipe } from \"effect\"\n   *\n   * const result = pipe(\n   *   Either.Do,\n   *   Either.bind(\"x\", () => Either.right(2)),\n   *   Either.bind(\"y\", () => Either.right(3)),\n   *   Either.let(\"sum\", ({ x, y }) => x + y)\n   * )\n   * assert.deepStrictEqual(result, Either.right({ x: 2, y: 3, sum: 5 }))\n   * ```\n   *\n   * @see {@link Do}\n   * @see {@link bindTo}\n   * @see {@link bind}\n   *\n   * @category do notation\n   * @since 2.0.0\n   */\n  let_ as let\n}\n\n/**\n * Converts an `Option` of an `Either` into an `Either` of an `Option`.\n *\n * **Details**\n *\n * This function transforms an `Option<Either<A, E>>` into an\n * `Either<Option<A>, E>`. If the `Option` is `None`, the resulting `Either`\n * will be a `Right` with a `None` value. If the `Option` is `Some`, the\n * inner `Either` will be executed, and its result wrapped in a `Some`.\n *\n * @example\n * ```ts\n * import { Effect, Either, Option } from \"effect\"\n *\n * //      ┌─── Option<Either<number, never>>\n * //      ▼\n * const maybe = Option.some(Either.right(42))\n *\n * //      ┌─── Either<Option<number>, never, never>\n * //      ▼\n * const result = Either.transposeOption(maybe)\n *\n * console.log(Effect.runSync(result))\n * // Output: { _id: 'Option', _tag: 'Some', value: 42 }\n * ```\n *\n * @since 3.14.0\n * @category Optional Wrapping & Unwrapping\n */\nexport const transposeOption = <A = never, E = never>(\n  self: Option<Either<A, E>>\n): Either<Option<A>, E> => {\n  return option_.isNone(self) ? right(option_.none) : map(self.value, option_.some)\n}\n\n/**\n * Applies an `Either` on an `Option` and transposes the result.\n *\n * **Details**\n *\n * If the `Option` is `None`, the resulting `Either` will immediately succeed with a `Right` value of `None`.\n * If the `Option` is `Some`, the transformation function will be applied to the inner value, and its result wrapped in a `Some`.\n *\n * @example\n * ```ts\n * import { Either, Option, pipe } from \"effect\"\n *\n * //          ┌─── Either<Option<number>, never>>\n * //          ▼\n * const noneResult = pipe(\n *   Option.none(),\n *   Either.transposeMapOption(() => Either.right(42)) // will not be executed\n * )\n * console.log(noneResult)\n * // Output: { _id: 'Either', _tag: 'Right', right: { _id: 'Option', _tag: 'None' } }\n *\n * //          ┌─── Either<Option<number>, never>>\n * //          ▼\n * const someRightResult = pipe(\n *   Option.some(42),\n *   Either.transposeMapOption((value) => Either.right(value * 2))\n * )\n * console.log(someRightResult)\n * // Output: { _id: 'Either', _tag: 'Right', right: { _id: 'Option', _tag: 'Some', value: 84 } }\n * ```\n *\n * @since 3.15.0\n * @category Optional Wrapping & Unwrapping\n */\nexport const transposeMapOption = dual<\n  <A, B, E = never>(\n    f: (self: A) => Either<B, E>\n  ) => (self: Option<A>) => Either<Option<B>, E>,\n  <A, B, E = never>(\n    self: Option<A>,\n    f: (self: A) => Either<B, E>\n  ) => Either<Option<B>, E>\n>(2, (self, f) => option_.isNone(self) ? right(option_.none) : map(f(self.value), option_.some))\n"
  },
  {
    "path": "packages/effect/src/Encoding.ts",
    "content": "/**\n * This module provides encoding & decoding functionality for:\n *\n * - base64 (RFC4648)\n * - base64 (URL)\n * - hex\n *\n * @since 2.0.0\n */\nimport * as Either from \"./Either.js\"\nimport * as Base64 from \"./internal/encoding/base64.js\"\nimport * as Base64Url from \"./internal/encoding/base64Url.js\"\nimport * as Common from \"./internal/encoding/common.js\"\nimport * as Hex from \"./internal/encoding/hex.js\"\n\n/**\n * Encodes the given value into a base64 (RFC4648) `string`.\n *\n * @category encoding\n * @since 2.0.0\n */\nexport const encodeBase64: (input: Uint8Array | string) => string = (input) =>\n  typeof input === \"string\" ? Base64.encode(Common.encoder.encode(input)) : Base64.encode(input)\n\n/**\n * Decodes a base64 (RFC4648) encoded `string` into a `Uint8Array`.\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeBase64 = (str: string): Either.Either<Uint8Array, DecodeException> => Base64.decode(str)\n\n/**\n * Decodes a base64 (RFC4648) encoded `string` into a UTF-8 `string`.\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeBase64String = (str: string) => Either.map(decodeBase64(str), (_) => Common.decoder.decode(_))\n\n/**\n * Encodes the given value into a base64 (URL) `string`.\n *\n * @category encoding\n * @since 2.0.0\n */\nexport const encodeBase64Url: (input: Uint8Array | string) => string = (input) =>\n  typeof input === \"string\" ? Base64Url.encode(Common.encoder.encode(input)) : Base64Url.encode(input)\n\n/**\n * Decodes a base64 (URL) encoded `string` into a `Uint8Array`.\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeBase64Url = (str: string): Either.Either<Uint8Array, DecodeException> => Base64Url.decode(str)\n\n/**\n * Decodes a base64 (URL) encoded `string` into a UTF-8 `string`.\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeBase64UrlString = (str: string) => Either.map(decodeBase64Url(str), (_) => Common.decoder.decode(_))\n\n/**\n * Encodes the given value into a hex `string`.\n *\n * @category encoding\n * @since 2.0.0\n */\nexport const encodeHex: (input: Uint8Array | string) => string = (input) =>\n  typeof input === \"string\" ? Hex.encode(Common.encoder.encode(input)) : Hex.encode(input)\n\n/**\n * Decodes a hex encoded `string` into a `Uint8Array`.\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeHex = (str: string): Either.Either<Uint8Array, DecodeException> => Hex.decode(str)\n\n/**\n * Decodes a hex encoded `string` into a UTF-8 `string`.\n *\n * @category decoding\n * @since 2.0.0\n */\nexport const decodeHexString = (str: string) => Either.map(decodeHex(str), (_) => Common.decoder.decode(_))\n\n/**\n * Encodes a UTF-8 `string` into a URI component `string`.\n *\n * @category encoding\n * @since 3.12.0\n */\nexport const encodeUriComponent = (str: string): Either.Either<string, EncodeException> =>\n  Either.try({\n    try: () => encodeURIComponent(str),\n    catch: (e) => EncodeException(str, e instanceof Error ? e.message : \"Invalid input\")\n  })\n\n/**\n * Decodes a URI component `string` into a UTF-8 `string`.\n *\n * @category decoding\n * @since 3.12.0\n */\nexport const decodeUriComponent = (str: string): Either.Either<string, DecodeException> =>\n  Either.try({\n    try: () => decodeURIComponent(str),\n    catch: (e) => DecodeException(str, e instanceof Error ? e.message : \"Invalid input\")\n  })\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const DecodeExceptionTypeId: unique symbol = Common.DecodeExceptionTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type DecodeExceptionTypeId = typeof DecodeExceptionTypeId\n\n/**\n * Represents a checked exception which occurs when decoding fails.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface DecodeException {\n  readonly _tag: \"DecodeException\"\n  readonly [DecodeExceptionTypeId]: DecodeExceptionTypeId\n  readonly input: string\n  readonly message?: string\n}\n\n/**\n * Creates a checked exception which occurs when decoding fails.\n *\n * @since 2.0.0\n * @category errors\n */\nexport const DecodeException: (input: string, message?: string) => DecodeException = Common.DecodeException\n\n/**\n * Returns `true` if the specified value is an `DecodeException`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isDecodeException: (u: unknown) => u is DecodeException = Common.isDecodeException\n\n/**\n * @since 3.12.0\n * @category symbols\n */\nexport const EncodeExceptionTypeId: unique symbol = Common.EncodeExceptionTypeId\n\n/**\n * @since 3.12.0\n * @category symbols\n */\nexport type EncodeExceptionTypeId = typeof EncodeExceptionTypeId\n\n/**\n * Represents a checked exception which occurs when encoding fails.\n *\n * @since 3.12.0\n * @category models\n */\nexport interface EncodeException {\n  readonly _tag: \"EncodeException\"\n  readonly [EncodeExceptionTypeId]: EncodeExceptionTypeId\n  readonly input: string\n  readonly message?: string\n}\n\n/**\n * Creates a checked exception which occurs when encoding fails.\n *\n * @since 3.12.0\n * @category errors\n */\nexport const EncodeException: (input: string, message?: string) => EncodeException = Common.EncodeException\n\n/**\n * Returns `true` if the specified value is an `EncodeException`, `false` otherwise.\n *\n * @since 3.12.0\n * @category refinements\n */\nexport const isEncodeException: (u: unknown) => u is EncodeException = Common.isEncodeException\n"
  },
  {
    "path": "packages/effect/src/Equal.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { Equivalence } from \"./Equivalence.js\"\nimport * as Hash from \"./Hash.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport { structuralRegionState } from \"./Utils.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const symbol: unique symbol = Symbol.for(\"effect/Equal\")\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Equal extends Hash.Hash {\n  [symbol](that: Equal): boolean\n}\n\n/**\n * @since 2.0.0\n * @category equality\n */\nexport function equals<B>(that: B): <A>(self: A) => boolean\nexport function equals<A, B>(self: A, that: B): boolean\nexport function equals(): any {\n  if (arguments.length === 1) {\n    return (self: unknown) => compareBoth(self, arguments[0])\n  }\n  return compareBoth(arguments[0], arguments[1])\n}\n\nfunction compareBoth(self: unknown, that: unknown): boolean {\n  if (self === that) {\n    return true\n  }\n  const selfType = typeof self\n  if (selfType !== typeof that) {\n    return false\n  }\n  if (selfType === \"object\" || selfType === \"function\") {\n    if (self !== null && that !== null) {\n      if (isEqual(self) && isEqual(that)) {\n        if (Hash.hash(self) === Hash.hash(that) && self[symbol](that)) {\n          return true\n        } else {\n          return structuralRegionState.enabled && structuralRegionState.tester\n            ? structuralRegionState.tester(self, that)\n            : false\n        }\n      } else if (self instanceof Date && that instanceof Date) {\n        const t1 = self.getTime()\n        const t2 = that.getTime()\n        return t1 === t2 || (Number.isNaN(t1) && Number.isNaN(t2))\n      } else if (self instanceof URL && that instanceof URL) {\n        return self.href === that.href\n      }\n    }\n    if (structuralRegionState.enabled) {\n      if (self === null || that === null) {\n        return false\n      }\n      if (Array.isArray(self) && Array.isArray(that)) {\n        return self.length === that.length && self.every((v, i) => compareBoth(v, that[i]))\n      }\n      if (Object.getPrototypeOf(self) === Object.prototype && Object.getPrototypeOf(that) === Object.prototype) {\n        const keysSelf = Object.keys(self as any)\n        const keysThat = Object.keys(that as any)\n        if (keysSelf.length === keysThat.length) {\n          for (const key of keysSelf) {\n            // @ts-expect-error\n            if (!(key in that && compareBoth(self[key], that[key]))) {\n              return structuralRegionState.tester ? structuralRegionState.tester(self, that) : false\n            }\n          }\n          return true\n        }\n      }\n      return structuralRegionState.tester ? structuralRegionState.tester(self, that) : false\n    }\n  }\n\n  return structuralRegionState.enabled && structuralRegionState.tester\n    ? structuralRegionState.tester(self, that)\n    : false\n}\n\n/**\n * @since 2.0.0\n * @category guards\n */\nexport const isEqual = (u: unknown): u is Equal => hasProperty(u, symbol)\n\n/**\n * @since 2.0.0\n * @category instances\n */\nexport const equivalence: <A>() => Equivalence<A> = () => equals\n"
  },
  {
    "path": "packages/effect/src/Equivalence.ts",
    "content": "/**\n * This module provides an implementation of the `Equivalence` type class, which defines a binary relation\n * that is reflexive, symmetric, and transitive. In other words, it defines a notion of equivalence between values of a certain type.\n * These properties are also known in mathematics as an \"equivalence relation\".\n *\n * @since 2.0.0\n */\nimport { dual } from \"./Function.js\"\nimport type { TypeLambda } from \"./HKT.js\"\n\n/**\n * @category type class\n * @since 2.0.0\n */\nexport interface Equivalence<in A> {\n  (self: A, that: A): boolean\n}\n\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface EquivalenceTypeLambda extends TypeLambda {\n  readonly type: Equivalence<this[\"Target\"]>\n}\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport const make = <A>(isEquivalent: (self: A, that: A) => boolean): Equivalence<A> => (self: A, that: A): boolean =>\n  self === that || isEquivalent(self, that)\n\nconst isStrictEquivalent = (x: unknown, y: unknown) => x === y\n\n/**\n * Return an `Equivalence` that uses strict equality (===) to compare values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const strict: <A>() => Equivalence<A> = () => isStrictEquivalent\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const string: Equivalence<string> = strict()\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const number: Equivalence<number> = strict()\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const boolean: Equivalence<boolean> = strict()\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const bigint: Equivalence<bigint> = strict()\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const symbol: Equivalence<symbol> = strict()\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const combine: {\n  <A>(that: Equivalence<A>): (self: Equivalence<A>) => Equivalence<A>\n  <A>(self: Equivalence<A>, that: Equivalence<A>): Equivalence<A>\n} = dual(2, <A>(self: Equivalence<A>, that: Equivalence<A>): Equivalence<A> => make((x, y) => self(x, y) && that(x, y)))\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const combineMany: {\n  <A>(collection: Iterable<Equivalence<A>>): (self: Equivalence<A>) => Equivalence<A>\n  <A>(self: Equivalence<A>, collection: Iterable<Equivalence<A>>): Equivalence<A>\n} = dual(2, <A>(self: Equivalence<A>, collection: Iterable<Equivalence<A>>): Equivalence<A> =>\n  make((x, y) => {\n    if (!self(x, y)) {\n      return false\n    }\n    for (const equivalence of collection) {\n      if (!equivalence(x, y)) {\n        return false\n      }\n    }\n    return true\n  }))\n\nconst isAlwaysEquivalent: Equivalence<unknown> = (_x, _y) => true\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const combineAll = <A>(collection: Iterable<Equivalence<A>>): Equivalence<A> =>\n  combineMany(isAlwaysEquivalent, collection)\n\n/**\n * @category mapping\n * @since 2.0.0\n */\nexport const mapInput: {\n  <B, A>(f: (b: B) => A): (self: Equivalence<A>) => Equivalence<B>\n  <A, B>(self: Equivalence<A>, f: (b: B) => A): Equivalence<B>\n} = dual(\n  2,\n  <A, B>(self: Equivalence<A>, f: (b: B) => A): Equivalence<B> => make((x, y) => self(f(x), f(y)))\n)\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Date: Equivalence<Date> = mapInput(number, (date) => date.getTime())\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const product: {\n  <B>(that: Equivalence<B>): <A>(self: Equivalence<A>) => Equivalence<readonly [A, B]> // readonly because invariant\n  <A, B>(self: Equivalence<A>, that: Equivalence<B>): Equivalence<readonly [A, B]> // readonly because invariant\n} = dual(\n  2,\n  <A, B>(self: Equivalence<A>, that: Equivalence<B>): Equivalence<readonly [A, B]> =>\n    make(([xa, xb], [ya, yb]) => self(xa, ya) && that(xb, yb))\n)\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const all = <A>(collection: Iterable<Equivalence<A>>): Equivalence<ReadonlyArray<A>> => {\n  return make((x, y) => {\n    const len = Math.min(x.length, y.length)\n\n    let collectionLength = 0\n    for (const equivalence of collection) {\n      if (collectionLength >= len) {\n        break\n      }\n      if (!equivalence(x[collectionLength], y[collectionLength])) {\n        return false\n      }\n      collectionLength++\n    }\n    return true\n  })\n}\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const productMany = <A>(\n  self: Equivalence<A>,\n  collection: Iterable<Equivalence<A>>\n): Equivalence<readonly [A, ...Array<A>]> /* readonly because invariant */ => {\n  const equivalence = all(collection)\n  return make((x, y) => !self(x[0], y[0]) ? false : equivalence(x.slice(1), y.slice(1)))\n}\n\n/**\n * Similar to `Promise.all` but operates on `Equivalence`s.\n *\n * ```ts skip-type-checking\n * [Equivalence<A>, Equivalence<B>, ...] -> Equivalence<[A, B, ...]>\n * ```\n *\n * Given a tuple of `Equivalence`s returns a new `Equivalence` that compares values of a tuple\n * by applying each `Equivalence` to the corresponding element of the tuple.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const tuple = <T extends ReadonlyArray<Equivalence<any>>>(\n  ...elements: T\n): Equivalence<Readonly<{ [I in keyof T]: [T[I]] extends [Equivalence<infer A>] ? A : never }>> => all(elements) as any\n\n/**\n * Creates a new `Equivalence` for an array of values based on a given `Equivalence` for the elements of the array.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const array = <A>(item: Equivalence<A>): Equivalence<ReadonlyArray<A>> =>\n  make((self, that) => {\n    if (self.length !== that.length) {\n      return false\n    }\n\n    for (let i = 0; i < self.length; i++) {\n      const isEq = item(self[i], that[i])\n      if (!isEq) {\n        return false\n      }\n    }\n\n    return true\n  })\n\n/**\n * Given a struct of `Equivalence`s returns a new `Equivalence` that compares values of a struct\n * by applying each `Equivalence` to the corresponding property of the struct.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const struct = <R extends Record<string, Equivalence<any>>>(\n  fields: R\n): Equivalence<{ readonly [K in keyof R]: [R[K]] extends [Equivalence<infer A>] ? A : never }> => {\n  const keys = Object.keys(fields)\n  return make((self, that) => {\n    for (const key of keys) {\n      if (!fields[key](self[key], that[key])) {\n        return false\n      }\n    }\n    return true\n  })\n}\n"
  },
  {
    "path": "packages/effect/src/ExecutionPlan.ts",
    "content": "/**\n * @since 3.16.0\n * @experimental\n */\nimport type { NonEmptyReadonlyArray } from \"./Array.js\"\nimport type * as Context from \"./Context.js\"\nimport * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/executionPlan.js\"\nimport * as Layer from \"./Layer.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\nimport type * as Schedule from \"./Schedule.js\"\n\n/**\n * @since 3.16.0\n * @category Symbols\n * @experimental\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 3.16.0\n * @category Symbols\n * @experimental\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 3.16.0\n * @category Guards\n * @experimental\n */\nexport const isExecutionPlan: (u: unknown) => u is ExecutionPlan<any> = internal.isExecutionPlan\n\n/**\n * A `ExecutionPlan` can be used with `Effect.withExecutionPlan` or `Stream.withExecutionPlan`, allowing you to provide different resources for each step of execution until the effect succeeds or the plan is exhausted.\n *\n * ```ts\n * import type { LanguageModel } from \"@effect/ai\"\n * import type { Layer } from \"effect\"\n * import { Effect, ExecutionPlan, Schedule } from \"effect\"\n *\n * declare const layerBad: Layer.Layer<LanguageModel.LanguageModel>\n * declare const layerGood: Layer.Layer<LanguageModel.LanguageModel>\n *\n * const ThePlan = ExecutionPlan.make(\n *   {\n *     // First try with the bad layer 2 times with a 3 second delay between attempts\n *     provide: layerBad,\n *     attempts: 2,\n *     schedule: Schedule.spaced(3000)\n *   },\n *   // Then try with the bad layer 3 times with a 1 second delay between attempts\n *   {\n *     provide: layerBad,\n *     attempts: 3,\n *     schedule: Schedule.spaced(1000)\n *   },\n *   // Finally try with the good layer.\n *   //\n *   // If `attempts` is omitted, the plan will only attempt once, unless a schedule is provided.\n *   {\n *     provide: layerGood\n *   }\n * )\n *\n * declare const effect: Effect.Effect<\n *   void,\n *   never,\n *   LanguageModel.LanguageModel\n * >\n * const withPlan: Effect.Effect<void> = Effect.withExecutionPlan(effect, ThePlan)\n * ```\n *\n * @since 3.16.0\n * @category Models\n * @experimental\n */\nexport interface ExecutionPlan<\n  Types extends {\n    provides: any\n    input: any\n    error: any\n    requirements: any\n  }\n> extends Pipeable {\n  readonly [TypeId]: TypeId\n  readonly steps: NonEmptyReadonlyArray<{\n    readonly provide:\n      | Context.Context<Types[\"provides\"]>\n      | Layer.Layer<Types[\"provides\"], Types[\"error\"], Types[\"requirements\"]>\n    readonly attempts?: number | undefined\n    readonly while?:\n      | ((input: Types[\"input\"]) => Effect.Effect<boolean, Types[\"error\"], Types[\"requirements\"]>)\n      | undefined\n    readonly schedule?: Schedule.Schedule<any, Types[\"input\"], Types[\"requirements\"]> | undefined\n  }>\n\n  /**\n   * Returns an equivalent `ExecutionPlan` with the requirements satisfied,\n   * using the current context.\n   */\n  readonly withRequirements: Effect.Effect<\n    ExecutionPlan<{\n      provides: Types[\"provides\"]\n      input: Types[\"input\"]\n      error: Types[\"error\"]\n      requirements: never\n    }>,\n    never,\n    Types[\"requirements\"]\n  >\n}\n\n/**\n * @since 3.16.0\n * @experimental\n */\nexport type TypesBase = {\n  provides: any\n  input: any\n  error: any\n  requirements: any\n}\n\n/**\n * Create an `ExecutionPlan`, which can be used with `Effect.withExecutionPlan` or `Stream.withExecutionPlan`, allowing you to provide different resources for each step of execution until the effect succeeds or the plan is exhausted.\n *\n * ```ts\n * import type { LanguageModel } from \"@effect/ai\"\n * import type { Layer } from \"effect\"\n * import { Effect, ExecutionPlan, Schedule } from \"effect\"\n *\n * declare const layerBad: Layer.Layer<LanguageModel.LanguageModel>\n * declare const layerGood: Layer.Layer<LanguageModel.LanguageModel>\n *\n * const ThePlan = ExecutionPlan.make(\n *   {\n *     // First try with the bad layer 2 times with a 3 second delay between attempts\n *     provide: layerBad,\n *     attempts: 2,\n *     schedule: Schedule.spaced(3000)\n *   },\n *   // Then try with the bad layer 3 times with a 1 second delay between attempts\n *   {\n *     provide: layerBad,\n *     attempts: 3,\n *     schedule: Schedule.spaced(1000)\n *   },\n *   // Finally try with the good layer.\n *   //\n *   // If `attempts` is omitted, the plan will only attempt once, unless a schedule is provided.\n *   {\n *     provide: layerGood\n *   }\n * )\n *\n * declare const effect: Effect.Effect<\n *   void,\n *   never,\n *   LanguageModel.LanguageModel\n * >\n * const withPlan: Effect.Effect<void> = Effect.withExecutionPlan(effect, ThePlan)\n * ```\n *\n * @since 3.16.0\n * @category Constructors\n * @experimental\n */\nexport const make = <const Steps extends NonEmptyReadonlyArray<make.Step>>(\n  ...steps: Steps & { [K in keyof Steps]: make.Step }\n): ExecutionPlan<{\n  provides: make.StepProvides<Steps>\n  input: make.StepInput<Steps>\n  error:\n    | (Steps[number][\"provide\"] extends Context.Context<infer _P> | Layer.Layer<infer _P, infer E, infer _R> ? E\n      : never)\n    | (Steps[number][\"while\"] extends (input: infer _I) => Effect.Effect<infer _A, infer _E, infer _R> ? _E : never)\n  requirements:\n    | (Steps[number][\"provide\"] extends Layer.Layer<infer _A, infer _E, infer R> ? R : never)\n    | (Steps[number][\"while\"] extends (input: infer _I) => Effect.Effect<infer _A, infer _E, infer R> ? R : never)\n    | (Steps[number][\"schedule\"] extends Schedule.Schedule<infer _O, infer _I, infer R> ? R : never)\n}> =>\n  makeProto(steps.map((options, i) => {\n    if (options.attempts && options.attempts < 1) {\n      throw new Error(`ExecutionPlan.make: step[${i}].attempts must be greater than 0`)\n    }\n    return {\n      schedule: options.schedule,\n      attempts: options.attempts,\n      while: options.while\n        ? (input: any) =>\n          Effect.suspend(() => {\n            const result = options.while!(input)\n            return typeof result === \"boolean\" ? Effect.succeed(result) : result\n          })\n        : undefined,\n      provide: options.provide\n    }\n  }) as any)\n\n/**\n * @since 3.16.0\n * @experimental\n */\nexport declare namespace make {\n  /**\n   * @since 3.16.0\n   * @experimental\n   */\n  export type Step = {\n    readonly provide: Context.Context<any> | Context.Context<never> | Layer.Layer.Any\n    readonly attempts?: number | undefined\n    readonly while?: ((input: any) => boolean | Effect.Effect<boolean, any, any>) | undefined\n    readonly schedule?: Schedule.Schedule<any, any, any> | undefined\n  }\n\n  /**\n   * @since 3.16.1\n   * @experimental\n   */\n  export type StepProvides<Steps extends ReadonlyArray<any>, Out = unknown> = Steps extends\n    readonly [infer Step, ...infer Rest] ? StepProvides<\n      Rest,\n      & Out\n      & (\n        (Step extends { readonly provide: Context.Context<infer P> | Layer.Layer<infer P, infer _E, infer _R> } ? P\n          : unknown)\n      )\n    > :\n    Out\n\n  /**\n   * @since 3.16.1\n   * @experimental\n   */\n  export type PlanProvides<Plans extends ReadonlyArray<any>, Out = unknown> = Plans extends\n    readonly [infer Plan, ...infer Rest] ?\n    PlanProvides<Rest, Out & (Plan extends ExecutionPlan<infer T> ? T[\"provides\"] : unknown)> :\n    Out\n\n  /**\n   * @since 3.16.0\n   * @experimental\n   */\n  export type StepInput<Steps extends ReadonlyArray<any>, Out = unknown> = Steps extends\n    readonly [infer Step, ...infer Rest] ? StepInput<\n      Rest,\n      & Out\n      & (\n        & (Step extends { readonly while: (input: infer I) => infer _ } ? I : unknown)\n        & (Step extends { readonly schedule: Schedule.Schedule<infer _O, infer I, infer _R> } ? I : unknown)\n      )\n    > :\n    Out\n\n  /**\n   * @since 3.16.0\n   * @experimental\n   */\n  export type PlanInput<Plans extends ReadonlyArray<any>, Out = unknown> = Plans extends\n    readonly [infer Plan, ...infer Rest] ?\n    PlanInput<Rest, Out & (Plan extends ExecutionPlan<infer T> ? T[\"input\"] : unknown)> :\n    Out\n}\n\nconst Proto: Omit<ExecutionPlan<any>, \"steps\"> = {\n  [TypeId]: TypeId,\n  get withRequirements() {\n    const self = this as any as ExecutionPlan<any>\n    return Effect.contextWith((context: Context.Context<any>) =>\n      makeProto(self.steps.map((step) => ({\n        ...step,\n        provide: Layer.isLayer(step.provide) ? Layer.provide(step.provide, Layer.succeedContext(context)) : step.provide\n      })) as any)\n    )\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makeProto = <Provides, In, PlanE, PlanR>(\n  steps: ExecutionPlan<{\n    provides: Provides\n    input: In\n    error: PlanE\n    requirements: PlanR\n  }>[\"steps\"]\n) => {\n  const self = Object.create(Proto)\n  self.steps = steps\n  return self\n}\n\n/**\n * @since 3.16.0\n * @category Combining\n * @experimental\n */\nexport const merge = <const Plans extends NonEmptyReadonlyArray<ExecutionPlan<any>>>(\n  ...plans: Plans\n): ExecutionPlan<{\n  provides: make.PlanProvides<Plans>\n  input: make.PlanInput<Plans>\n  error: Plans[number] extends ExecutionPlan<infer T> ? T[\"error\"] : never\n  requirements: Plans[number] extends ExecutionPlan<infer T> ? T[\"requirements\"] : never\n}> => makeProto(plans.flatMap((plan) => plan.steps) as any)\n"
  },
  {
    "path": "packages/effect/src/ExecutionStrategy.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { LazyArg } from \"./Function.js\"\nimport * as internal from \"./internal/executionStrategy.js\"\n\n/**\n * Describes a strategy for evaluating multiple effects, potentially in\n * parallel.\n *\n * There are 3 possible execution strategies: `Sequential`, `Parallel`,\n * `ParallelN`.\n *\n * @since 2.0.0\n * @category models\n */\nexport type ExecutionStrategy = Sequential | Parallel | ParallelN\n\n/**\n * Execute effects sequentially.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Sequential {\n  readonly _tag: \"Sequential\"\n}\n\n/**\n * Execute effects in parallel.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Parallel {\n  readonly _tag: \"Parallel\"\n}\n\n/**\n * Execute effects in parallel, up to the specified number of concurrent fibers.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface ParallelN {\n  readonly _tag: \"ParallelN\"\n  readonly parallelism: number\n}\n\n/**\n * Execute effects sequentially.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sequential: ExecutionStrategy = internal.sequential\n\n/**\n * Execute effects in parallel.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const parallel: ExecutionStrategy = internal.parallel\n\n/**\n * Execute effects in parallel, up to the specified number of concurrent fibers.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const parallelN: (parallelism: number) => ExecutionStrategy = internal.parallelN\n\n/**\n * Returns `true` if the specified `ExecutionStrategy` is an instance of\n * `Sequential`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isSequential: (self: ExecutionStrategy) => self is Sequential = internal.isSequential\n\n/**\n * Returns `true` if the specified `ExecutionStrategy` is an instance of\n * `Sequential`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isParallel: (self: ExecutionStrategy) => self is Parallel = internal.isParallel\n\n/**\n * Returns `true` if the specified `ExecutionStrategy` is an instance of\n * `Sequential`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isParallelN: (self: ExecutionStrategy) => self is ParallelN = internal.isParallelN\n\n/**\n * Folds over the specified `ExecutionStrategy` using the provided case\n * functions.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <A>(options: {\n    readonly onSequential: LazyArg<A>\n    readonly onParallel: LazyArg<A>\n    readonly onParallelN: (n: number) => A\n  }): (self: ExecutionStrategy) => A\n  <A>(self: ExecutionStrategy, options: {\n    readonly onSequential: LazyArg<A>\n    readonly onParallel: LazyArg<A>\n    readonly onParallelN: (n: number) => A\n  }): A\n} = internal.match\n"
  },
  {
    "path": "packages/effect/src/Exit.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as core from \"./internal/core.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport type { NoInfer } from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * An `Exit<A, E = never>` describes the result of a executing an `Effect` workflow.\n *\n * There are two possible values for an `Exit<A, E>`:\n *   - `Exit.Success` contain a success value of type `A`\n *   - `Exit.Failure` contains a failure `Cause` of type `E`\n *\n * @since 2.0.0\n * @category models\n */\nexport type Exit<A, E = never> = Success<A, E> | Failure<A, E>\n\n/**\n * Represents a failed `Effect` workflow containing the `Cause` of the failure\n * of type `E`.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Failure<out A, out E> extends Effect.Effect<A, E>, Pipeable, Inspectable {\n  readonly _tag: \"Failure\"\n  readonly _op: \"Failure\"\n  readonly cause: Cause.Cause<E>\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: ExitUnify<this>\n  [Unify.ignoreSymbol]?: ExitUnifyIgnore\n  /** @internal */\n  readonly effect_instruction_i0: Cause.Cause<E>\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface ExitUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  Exit?: () => A[Unify.typeSymbol] extends Exit<infer A0, infer E0> | infer _ ? Exit<A0, E0> : never\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface ExitUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * Represents a successful `Effect` workflow and containing the returned value\n * of type `A`.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Success<out A, out E> extends Effect.Effect<A, E>, Pipeable, Inspectable {\n  readonly _tag: \"Success\"\n  readonly _op: \"Success\"\n  readonly value: A\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: ExitUnify<this>\n  [Unify.ignoreSymbol]?: ExitUnifyIgnore\n  /** @internal */\n  readonly effect_instruction_i0: A\n}\n\n/**\n * Returns `true` if the specified value is an `Exit`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isExit: (u: unknown) => u is Exit<unknown, unknown> = core.exitIsExit\n\n/**\n * Returns `true` if the specified `Exit` is a `Failure`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isFailure: <A, E>(self: Exit<A, E>) => self is Failure<A, E> = core.exitIsFailure\n\n/**\n * Returns `true` if the specified `Exit` is a `Success`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isSuccess: <A, E>(self: Exit<A, E>) => self is Success<A, E> = core.exitIsSuccess\n\n/**\n * Returns `true` if the specified exit is a `Failure` **and** the `Cause` of\n * the failure was due to interruption, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isInterrupted: <A, E>(self: Exit<A, E>) => boolean = core.exitIsInterrupted\n\n/**\n * Maps the `Success` value of the specified exit to the provided constant\n * value.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const as: {\n  <A2>(value: A2): <A, E>(self: Exit<A, E>) => Exit<A2, E>\n  <A, E, A2>(self: Exit<A, E>, value: A2): Exit<A2, E>\n} = core.exitAs\n\n/**\n * Maps the `Success` value of the specified exit to a void.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const asVoid: <A, E>(self: Exit<A, E>) => Exit<void, E> = core.exitAsVoid\n\n/**\n * Returns a `Some<Cause<E>>` if the specified exit is a `Failure`, `None`\n * otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const causeOption: <A, E>(self: Exit<A, E>) => Option.Option<Cause.Cause<E>> = core.exitCauseOption\n\n/**\n * Collects all of the specified exit values into a `Some<Exit<List<A>, E>>`. If\n * the provided iterable contains no elements, `None` will be returned.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const all: <A, E>(\n  exits: Iterable<Exit<A, E>>,\n  options?: { readonly parallel?: boolean | undefined } | undefined\n) => Option.Option<Exit<Array<A>, E>> = core.exitCollectAll\n\n/**\n * Constructs a new `Exit.Failure` from the specified unrecoverable defect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const die: (defect: unknown) => Exit<never> = core.exitDie\n\n/**\n * Executes the predicate on the value of the specified exit if it is a\n * `Success`, otherwise returns `false`.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const exists: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): <E>(self: Exit<A, E>) => self is Exit<B>\n  <A>(predicate: Predicate<NoInfer<A>>): <E>(self: Exit<A, E>) => boolean\n  <A, E, B extends A>(self: Exit<A, E>, refinement: Refinement<A, B>): self is Exit<B>\n  <A, E>(self: Exit<A, E>, predicate: Predicate<A>): boolean\n} = core.exitExists\n\n/**\n * Constructs a new `Exit.Failure` from the specified recoverable error of type\n * `E`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fail: <E>(error: E) => Exit<never, E> = core.exitFail\n\n/**\n * Constructs a new `Exit.Failure` from the specified `Cause` of type `E`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCause: <E>(cause: Cause.Cause<E>) => Exit<never, E> = core.exitFailCause\n\n/**\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMap: {\n  <A, A2, E2>(f: (a: A) => Exit<A2, E2>): <E>(self: Exit<A, E>) => Exit<A2, E2 | E>\n  <A, E, E2, A2>(self: Exit<A, E>, f: (a: A) => Exit<A2, E2>): Exit<A2, E | E2>\n} = core.exitFlatMap\n\n/**\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMapEffect: {\n  <A, E, A2, E2, R>(\n    f: (a: A) => Effect.Effect<Exit<A2, E>, E2, R>\n  ): (self: Exit<A, E>) => Effect.Effect<Exit<A2, E>, E2, R>\n  <A, E, A2, E2, R>(self: Exit<A, E>, f: (a: A) => Effect.Effect<Exit<A2, E>, E2, R>): Effect.Effect<Exit<A2, E>, E2, R>\n} = core.exitFlatMapEffect\n\n/**\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatten: <A, E, E2>(self: Exit<Exit<A, E>, E2>) => Exit<A, E | E2> = core.exitFlatten\n\n/**\n * @since 2.0.0\n * @category traversing\n */\nexport const forEachEffect: {\n  <A, B, E2, R>(f: (a: A) => Effect.Effect<B, E2, R>): <E>(self: Exit<A, E>) => Effect.Effect<Exit<B, E2 | E>, never, R>\n  <A, E, B, E2, R>(self: Exit<A, E>, f: (a: A) => Effect.Effect<B, E2, R>): Effect.Effect<Exit<B, E | E2>, never, R>\n} = core.exitForEachEffect\n\n/**\n * Converts an `Either<R, L>` into an `Exit<R, L>`.\n *\n * @since 2.0.0\n * @category conversions\n */\nexport const fromEither: <R, L>(either: Either.Either<R, L>) => Exit<R, L> = core.exitFromEither\n\n/**\n * Converts an `Option<A>` into an `Exit<void, A>`.\n *\n * @since 2.0.0\n * @category conversions\n */\nexport const fromOption: <A>(option: Option.Option<A>) => Exit<A, void> = core.exitFromOption\n\n/**\n * Returns the `A` if specified exit is a `Success`, otherwise returns the\n * alternate `A` value computed from the specified function which receives the\n * `Cause<E>` of the exit `Failure`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const getOrElse: {\n  <E, A2>(orElse: (cause: Cause.Cause<E>) => A2): <A>(self: Exit<A, E>) => A2 | A\n  <A, E, A2>(self: Exit<A, E>, orElse: (cause: Cause.Cause<E>) => A2): A | A2\n} = core.exitGetOrElse\n\n/**\n * Constructs a new `Exit.Failure` from the specified `FiberId` indicating that\n * the `Fiber` running an `Effect` workflow was terminated due to interruption.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const interrupt: (fiberId: FiberId.FiberId) => Exit<never> = core.exitInterrupt\n\n/**\n * Maps over the `Success` value of the specified exit using the provided\n * function.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): <E>(self: Exit<A, E>) => Exit<B, E>\n  <A, E, B>(self: Exit<A, E>, f: (a: A) => B): Exit<B, E>\n} = core.exitMap\n\n/**\n * Maps over the `Success` and `Failure` cases of the specified exit using the\n * provided functions.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapBoth: {\n  <E, A, E2, A2>(\n    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n  ): (self: Exit<A, E>) => Exit<A2, E2>\n  <A, E, E2, A2>(\n    self: Exit<A, E>,\n    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n  ): Exit<A2, E2>\n} = core.exitMapBoth\n\n/**\n * Maps over the error contained in the `Failure` of the specified exit using\n * the provided function.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapError: {\n  <E, E2>(f: (e: E) => E2): <A>(self: Exit<A, E>) => Exit<A, E2>\n  <A, E, E2>(self: Exit<A, E>, f: (e: E) => E2): Exit<A, E2>\n} = core.exitMapError\n\n/**\n * Maps over the `Cause` contained in the `Failure` of the specified exit using\n * the provided function.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapErrorCause: {\n  <E, E2>(f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): <A>(self: Exit<A, E>) => Exit<A, E2>\n  <E, A, E2>(self: Exit<A, E>, f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): Exit<A, E2>\n} = core.exitMapErrorCause\n\n/**\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <E, A, Z1, Z2>(\n    options: { readonly onFailure: (cause: Cause.Cause<E>) => Z1; readonly onSuccess: (a: A) => Z2 }\n  ): (self: Exit<A, E>) => Z1 | Z2\n  <A, E, Z1, Z2>(\n    self: Exit<A, E>,\n    options: { readonly onFailure: (cause: Cause.Cause<E>) => Z1; readonly onSuccess: (a: A) => Z2 }\n  ): Z1 | Z2\n} = core.exitMatch\n\n/**\n * @since 2.0.0\n * @category folding\n */\nexport const matchEffect: {\n  <E, A2, E2, R, A, A3, E3, R2>(\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<A2, E2, R>\n      readonly onSuccess: (a: A) => Effect.Effect<A3, E3, R2>\n    }\n  ): (self: Exit<A, E>) => Effect.Effect<A2 | A3, E2 | E3, R | R2>\n  <A, E, A2, E2, R, A3, E3, R2>(\n    self: Exit<A, E>,\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<A2, E2, R>\n      readonly onSuccess: (a: A) => Effect.Effect<A3, E3, R2>\n    }\n  ): Effect.Effect<A2 | A3, E2 | E3, R | R2>\n} = core.exitMatchEffect\n\n/**\n * Constructs a new `Exit.Success` containing the specified value of type `A`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeed: <A>(value: A) => Exit<A> = core.exitSucceed\n\nconst void_: Exit<void> = core.exitVoid\nexport {\n  /**\n   * Represents an `Exit` which succeeds with `undefined`.\n   *\n   * @since 2.0.0\n   * @category constructors\n   */\n  void_ as void\n}\n\n/**\n * Sequentially zips the this result with the specified result or else returns\n * the failed `Cause<E | E2>`.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zip: {\n  <A2, E2>(that: Exit<A2, E2>): <A, E>(self: Exit<A, E>) => Exit<[A, A2], E2 | E>\n  <A, E, A2, E2>(self: Exit<A, E>, that: Exit<A2, E2>): Exit<[A, A2], E | E2>\n} = core.exitZip\n\n/**\n * Sequentially zips the this result with the specified result discarding the\n * second element of the tuple or else returns the failed `Cause<E | E2>`.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipLeft: {\n  <A2, E2>(that: Exit<A2, E2>): <A, E>(self: Exit<A, E>) => Exit<A, E2 | E>\n  <A, E, A2, E2>(self: Exit<A, E>, that: Exit<A2, E2>): Exit<A, E | E2>\n} = core.exitZipLeft\n\n/**\n * Sequentially zips the this result with the specified result discarding the\n * first element of the tuple or else returns the failed `Cause<E | E2>`.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipRight: {\n  <A2, E2>(that: Exit<A2, E2>): <A, E>(self: Exit<A, E>) => Exit<A2, E2 | E>\n  <A, E, A2, E2>(self: Exit<A, E>, that: Exit<A2, E2>): Exit<A2, E | E2>\n} = core.exitZipRight\n\n/**\n * Parallelly zips the this result with the specified result or else returns\n * the failed `Cause<E | E2>`.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipPar: {\n  <A2, E2>(that: Exit<A2, E2>): <A, E>(self: Exit<A, E>) => Exit<[A, A2], E2 | E>\n  <A, E, A2, E2>(self: Exit<A, E>, that: Exit<A2, E2>): Exit<[A, A2], E | E2>\n} = core.exitZipPar\n\n/**\n * Parallelly zips the this result with the specified result discarding the\n * second element of the tuple or else returns the failed `Cause<E | E2>`.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipParLeft: {\n  <A2, E2>(that: Exit<A2, E2>): <A, E>(self: Exit<A, E>) => Exit<A, E2 | E>\n  <A, E, A2, E2>(self: Exit<A, E>, that: Exit<A2, E2>): Exit<A, E | E2>\n} = core.exitZipParLeft\n\n/**\n * Parallelly zips the this result with the specified result discarding the\n * first element of the tuple or else returns the failed `Cause<E | E2>`.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipParRight: {\n  <A2, E2>(that: Exit<A2, E2>): <A, E>(self: Exit<A, E>) => Exit<A2, E2 | E>\n  <A, E, A2, E2>(self: Exit<A, E>, that: Exit<A2, E2>): Exit<A2, E | E2>\n} = core.exitZipParRight\n\n/**\n * Zips this exit together with that exit using the specified combination\n * functions.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWith: {\n  <B, E2, A, C, E>(\n    that: Exit<B, E2>,\n    options: {\n      readonly onSuccess: (a: A, b: B) => C\n      readonly onFailure: (cause: Cause.Cause<E>, cause2: Cause.Cause<E2>) => Cause.Cause<any>\n    }\n  ): (self: Exit<A, E>) => Exit<C, any>\n  <A, E, B, E2, C>(\n    self: Exit<A, E>,\n    that: Exit<B, E2>,\n    options: {\n      readonly onSuccess: (a: A, b: B) => C\n      readonly onFailure: (cause: Cause.Cause<E>, cause2: Cause.Cause<E2>) => Cause.Cause<E | E2>\n    }\n  ): Exit<C, E | E2>\n} = core.exitZipWith\n"
  },
  {
    "path": "packages/effect/src/FastCheck.ts",
    "content": "/**\n * @since 3.10.0\n */\n\n/**\n * @category re-exports\n * @since 3.10.0\n */\nexport * from \"fast-check\"\n"
  },
  {
    "path": "packages/effect/src/Fiber.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type { Context } from \"./Context.js\"\nimport type { DefaultServices } from \"./DefaultServices.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport type { FiberRef } from \"./FiberRef.js\"\nimport type * as FiberRefs from \"./FiberRefs.js\"\nimport type * as FiberStatus from \"./FiberStatus.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport * as core from \"./internal/core.js\"\nimport * as circular from \"./internal/effect/circular.js\"\nimport * as internal from \"./internal/fiber.js\"\nimport * as fiberRuntime from \"./internal/fiberRuntime.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as order from \"./Order.js\"\nimport type * as RuntimeFlags from \"./RuntimeFlags.js\"\nimport type { Scheduler } from \"./Scheduler.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type { Supervisor } from \"./Supervisor.js\"\nimport type { AnySpan, Tracer } from \"./Tracer.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const FiberTypeId: unique symbol = internal.FiberTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type FiberTypeId = typeof FiberTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const RuntimeFiberTypeId: unique symbol = internal.RuntimeFiberTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type RuntimeFiberTypeId = typeof RuntimeFiberTypeId\n\n/**\n * A fiber is a lightweight thread of execution that never consumes more than a\n * whole thread (but may consume much less, depending on contention and\n * asynchronicity). Fibers are spawned by forking effects, which run\n * concurrently with the parent effect.\n *\n * Fibers can be joined, yielding their result to other fibers, or interrupted,\n * which terminates the fiber, safely releasing all resources.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Fiber<out A, out E = never> extends Effect.Effect<A, E>, Fiber.Variance<A, E> {\n  /**\n   * The identity of the fiber.\n   */\n  id(): FiberId.FiberId\n\n  /**\n   * Awaits the fiber, which suspends the awaiting fiber until the result of the\n   * fiber has been determined.\n   */\n  readonly await: Effect.Effect<Exit.Exit<A, E>>\n\n  /**\n   * Retrieves the immediate children of the fiber.\n   */\n  readonly children: Effect.Effect<Array<Fiber.Runtime<any, any>>>\n\n  /**\n   * Inherits values from all `FiberRef` instances into current fiber. This\n   * will resume immediately.\n   */\n  readonly inheritAll: Effect.Effect<void>\n\n  /**\n   * Tentatively observes the fiber, but returns immediately if it is not\n   * already done.\n   */\n  readonly poll: Effect.Effect<Option.Option<Exit.Exit<A, E>>>\n\n  /**\n   * In the background, interrupts the fiber as if interrupted from the\n   * specified fiber. If the fiber has already exited, the returned effect will\n   * resume immediately. Otherwise, the effect will resume when the fiber exits.\n   */\n  interruptAsFork(fiberId: FiberId.FiberId): Effect.Effect<void>\n\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: FiberUnify<this>\n  readonly [Unify.ignoreSymbol]?: FiberUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface FiberUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  Fiber?: () => A[Unify.typeSymbol] extends Fiber<infer A0, infer E0> | infer _ ? Fiber<A0, E0> : never\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface FiberUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * A runtime fiber that is executing an effect. Runtime fibers have an\n * identity and a trace.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface RuntimeFiber<out A, out E = never> extends Fiber<A, E>, Fiber.RuntimeVariance<A, E> {\n  /**\n   * Reads the current number of ops that have occurred since the last yield\n   */\n  get currentOpCount(): number\n\n  /**\n   * Reads the current value of a fiber ref\n   */\n  getFiberRef<X>(fiberRef: FiberRef<X>): X\n\n  /**\n   * The identity of the fiber.\n   */\n  id(): FiberId.Runtime\n\n  /**\n   * The status of the fiber.\n   */\n  readonly status: Effect.Effect<FiberStatus.FiberStatus>\n\n  /**\n   * Returns the current `RuntimeFlags` the fiber is running with.\n   */\n  readonly runtimeFlags: Effect.Effect<RuntimeFlags.RuntimeFlags>\n\n  /**\n   * Adds an observer to the list of observers.\n   */\n  addObserver(observer: (exit: Exit.Exit<A, E>) => void): void\n\n  /**\n   * Removes the specified observer from the list of observers that will be\n   * notified when the fiber exits.\n   */\n  removeObserver(observer: (exit: Exit.Exit<A, E>) => void): void\n\n  /**\n   * Retrieves all fiber refs of the fiber.\n   */\n  getFiberRefs(): FiberRefs.FiberRefs\n\n  /**\n   * Unsafely observes the fiber, but returns immediately if it is not\n   * already done.\n   */\n  unsafePoll(): Exit.Exit<A, E> | null\n\n  /**\n   * In the background, interrupts the fiber as if interrupted from the\n   * specified fiber. If the fiber has already exited, the returned effect will\n   * resume immediately. Otherwise, the effect will resume when the fiber exits.\n   */\n  unsafeInterruptAsFork(fiberId: FiberId.FiberId): void\n\n  /**\n   * Gets the current context\n   */\n  get currentContext(): Context<never>\n\n  /**\n   * Gets the current context\n   */\n  get currentDefaultServices(): Context<DefaultServices>\n\n  /**\n   * Gets the current scheduler\n   */\n  get currentScheduler(): Scheduler\n\n  /**\n   * Gets the current tracer\n   */\n  get currentTracer(): Tracer\n\n  /**\n   * Gets the current span\n   */\n  get currentSpan(): AnySpan | undefined\n\n  /**\n   * Gets the current supervisor\n   */\n  get currentSupervisor(): Supervisor<unknown>\n\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: RuntimeFiberUnify<this>\n  readonly [Unify.ignoreSymbol]?: RuntimeFiberUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface RuntimeFiberUnify<A extends { [Unify.typeSymbol]?: any }> extends FiberUnify<A> {\n  RuntimeFiber?: () => A[Unify.typeSymbol] extends RuntimeFiber<infer A0, infer E0> | infer _ ? RuntimeFiber<A0, E0>\n    : never\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface RuntimeFiberUnifyIgnore extends FiberUnifyIgnore {\n  Fiber?: true\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Fiber {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Runtime<A, E = never> = RuntimeFiber<A, E>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out A, out E> {\n    readonly [FiberTypeId]: {\n      readonly _A: Types.Covariant<A>\n      readonly _E: Types.Covariant<E>\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  export interface RuntimeVariance<out A, out E> {\n    readonly [RuntimeFiberTypeId]: {\n      readonly _A: Types.Covariant<A>\n      readonly _E: Types.Covariant<E>\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Dump {\n    /**\n     * The fiber's unique identifier.\n     */\n    readonly id: FiberId.Runtime\n    /**\n     * The status of the fiber.\n     */\n    readonly status: FiberStatus.FiberStatus\n  }\n\n  /**\n   * A record containing information about a `Fiber`.\n   *\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Descriptor {\n    /**\n     * The fiber's unique identifier.\n     */\n    readonly id: FiberId.FiberId\n    /**\n     * The status of the fiber.\n     */\n    readonly status: FiberStatus.FiberStatus\n    /**\n     * The set of fibers attempting to interrupt the fiber or its ancestors.\n     */\n    readonly interruptors: HashSet.HashSet<FiberId.FiberId>\n  }\n}\n\n/**\n * @since 2.0.0\n * @category instances\n */\nexport const Order: order.Order<RuntimeFiber<unknown, unknown>> = internal.Order\n\n/**\n * Returns `true` if the specified value is a `Fiber`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isFiber: (u: unknown) => u is Fiber<unknown, unknown> = internal.isFiber\n\n/**\n * Returns `true` if the specified `Fiber` is a `RuntimeFiber`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isRuntimeFiber: <A, E>(self: Fiber<A, E>) => self is RuntimeFiber<A, E> = internal.isRuntimeFiber\n\n/**\n * The identity of the fiber.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const id: <A, E>(self: Fiber<A, E>) => FiberId.FiberId = internal.id\n\nconst _await: <A, E>(self: Fiber<A, E>) => Effect.Effect<Exit.Exit<A, E>> = internal._await\n\nexport {\n  /**\n   * Awaits the fiber, which suspends the awaiting fiber until the result of the\n   * fiber has been determined.\n   *\n   * @since 2.0.0\n   * @category getters\n   */\n  _await as await\n}\n\n/**\n * Awaits on all fibers to be completed, successfully or not.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const awaitAll: <const T extends Iterable<Fiber<any, any>>>(\n  fibers: T\n) => Effect.Effect<\n  [T] extends [ReadonlyArray<infer U>]\n    ? number extends T[\"length\"] ? Array<U extends Fiber<infer A, infer E> ? Exit.Exit<A, E> : never>\n    : { -readonly [K in keyof T]: T[K] extends Fiber<infer A, infer E> ? Exit.Exit<A, E> : never }\n    : Array<T extends Iterable<infer U> ? U extends Fiber<infer A, infer E> ? Exit.Exit<A, E> : never : never>\n> = fiberRuntime.fiberAwaitAll\n\n/**\n * Retrieves the immediate children of the fiber.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const children: <A, E>(self: Fiber<A, E>) => Effect.Effect<Array<RuntimeFiber<any, any>>> = internal.children\n\n/**\n * Collects all fibers into a single fiber producing an in-order list of the\n * results.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const all: <A, E>(fibers: Iterable<Fiber<A, E>>) => Fiber<ReadonlyArray<A>, E> = fiberRuntime.fiberAll\n\n/**\n * A fiber that is done with the specified `Exit` value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const done: <A, E>(exit: Exit.Exit<A, E>) => Fiber<A, E> = internal.done\n\n/**\n * @since 2.0.0\n * @category destructors\n */\nexport const dump: <A, E>(self: RuntimeFiber<A, E>) => Effect.Effect<Fiber.Dump> = internal.dump\n\n/**\n * @since 2.0.0\n * @category destructors\n */\nexport const dumpAll: (\n  fibers: Iterable<RuntimeFiber<unknown, unknown>>\n) => Effect.Effect<Array<Fiber.Dump>> = internal.dumpAll\n\n/**\n * A fiber that has already failed with the specified value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fail: <E>(error: E) => Fiber<never, E> = internal.fail\n\n/**\n * Creates a `Fiber` that has already failed with the specified cause.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCause: <E>(cause: Cause.Cause<E>) => Fiber<never, E> = internal.failCause\n\n/**\n * Lifts an `Effect` into a `Fiber`.\n *\n * @since 2.0.0\n * @category conversions\n */\nexport const fromEffect: <A, E>(effect: Effect.Effect<A, E>) => Effect.Effect<Fiber<A, E>> = internal.fromEffect\n\n/**\n * Gets the current fiber if one is running.\n *\n * @since 2.0.0\n * @category utilities\n */\nexport const getCurrentFiber: () => Option.Option<RuntimeFiber<any, any>> = internal.getCurrentFiber\n\n/**\n * Inherits values from all `FiberRef` instances into current fiber. This\n * will resume immediately.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const inheritAll: <A, E>(self: Fiber<A, E>) => Effect.Effect<void> = internal.inheritAll\n\n/**\n * Interrupts the fiber from whichever fiber is calling this method. If the\n * fiber has already exited, the returned effect will resume immediately.\n * Otherwise, the effect will resume when the fiber exits.\n *\n * @since 2.0.0\n * @category interruption\n */\nexport const interrupt: <A, E>(self: Fiber<A, E>) => Effect.Effect<Exit.Exit<A, E>> = core.interruptFiber\n\n/**\n * Constructrs a `Fiber` that is already interrupted.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const interrupted: (fiberId: FiberId.FiberId) => Fiber<never> = internal.interrupted\n\n/**\n * Interrupts the fiber as if interrupted from the specified fiber. If the\n * fiber has already exited, the returned effect will resume immediately.\n * Otherwise, the effect will resume when the fiber exits.\n *\n * @since 2.0.0\n * @category interruption\n */\nexport const interruptAs: {\n  (fiberId: FiberId.FiberId): <A, E>(self: Fiber<A, E>) => Effect.Effect<Exit.Exit<A, E>>\n  <A, E>(self: Fiber<A, E>, fiberId: FiberId.FiberId): Effect.Effect<Exit.Exit<A, E>>\n} = core.interruptAsFiber\n\n/**\n * Interrupts the fiber as if interrupted from the specified fiber. If the\n * fiber has already exited, the returned effect will resume immediately.\n * Otherwise, the effect will resume when the fiber exits.\n *\n * @since 2.0.0\n * @category interruption\n */\nexport const interruptAsFork: {\n  (fiberId: FiberId.FiberId): <A, E>(self: Fiber<A, E>) => Effect.Effect<void>\n  <A, E>(self: Fiber<A, E>, fiberId: FiberId.FiberId): Effect.Effect<void>\n} = internal.interruptAsFork\n\n/**\n * Interrupts all fibers, awaiting their interruption.\n *\n * @since 2.0.0\n * @category interruption\n */\nexport const interruptAll: (fibers: Iterable<Fiber<any, any>>) => Effect.Effect<void> = internal.interruptAll\n\n/**\n * Interrupts all fibers as by the specified fiber, awaiting their\n * interruption.\n *\n * @since 2.0.0\n * @category interruption\n */\nexport const interruptAllAs: {\n  (fiberId: FiberId.FiberId): (fibers: Iterable<Fiber<any, any>>) => Effect.Effect<void>\n  (fibers: Iterable<Fiber<any, any>>, fiberId: FiberId.FiberId): Effect.Effect<void>\n} = internal.interruptAllAs\n\n/**\n * Interrupts the fiber from whichever fiber is calling this method. The\n * interruption will happen in a separate daemon fiber, and the returned\n * effect will always resume immediately without waiting.\n *\n * @since 2.0.0\n * @category interruption\n */\nexport const interruptFork: <A, E>(self: Fiber<A, E>) => Effect.Effect<void> = fiberRuntime.fiberInterruptFork\n\n/**\n * Joins the fiber, which suspends the joining fiber until the result of the\n * fiber has been determined. Attempting to join a fiber that has erred will\n * result in a catchable error. Joining an interrupted fiber will result in an\n * \"inner interruption\" of this fiber, unlike interruption triggered by\n * another fiber, \"inner interruption\" can be caught and recovered.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const join: <A, E>(self: Fiber<A, E>) => Effect.Effect<A, E> = internal.join\n\n/**\n * Joins all fibers, awaiting their _successful_ completion. Attempting to\n * join a fiber that has erred will result in a catchable error, _if_ that\n * error does not result from interruption.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const joinAll: <A, E>(fibers: Iterable<Fiber<A, E>>) => Effect.Effect<Array<A>, E> = fiberRuntime.fiberJoinAll\n\n/**\n * Maps over the value the Fiber computes.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): <E>(self: Fiber<A, E>) => Fiber<B, E>\n  <A, E, B>(self: Fiber<A, E>, f: (a: A) => B): Fiber<B, E>\n} = internal.map\n\n/**\n * Effectually maps over the value the fiber computes.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapEffect: {\n  <A, A2, E2>(f: (a: A) => Effect.Effect<A2, E2>): <E>(self: Fiber<A, E>) => Fiber<A2, E2 | E>\n  <A, E, A2, E2>(self: Fiber<A, E>, f: (a: A) => Effect.Effect<A2, E2>): Fiber<A2, E | E2>\n} = internal.mapEffect\n\n/**\n * Passes the success of this fiber to the specified callback, and continues\n * with the fiber that it returns.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapFiber: {\n  <E, E2, A, B>(f: (a: A) => Fiber<B, E2>): (self: Fiber<A, E>) => Effect.Effect<Fiber<B, E | E2>>\n  <A, E, E2, B>(self: Fiber<A, E>, f: (a: A) => Fiber<B, E2>): Effect.Effect<Fiber<B, E | E2>>\n} = internal.mapFiber\n\n/**\n * Folds over the `Fiber` or `RuntimeFiber`.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <A, E, Z>(\n    options: {\n      readonly onFiber: (fiber: Fiber<A, E>) => Z\n      readonly onRuntimeFiber: (fiber: RuntimeFiber<A, E>) => Z\n    }\n  ): (self: Fiber<A, E>) => Z\n  <A, E, Z>(\n    self: Fiber<A, E>,\n    options: {\n      readonly onFiber: (fiber: Fiber<A, E>) => Z\n      readonly onRuntimeFiber: (fiber: RuntimeFiber<A, E>) => Z\n    }\n  ): Z\n} = internal.match\n\n/**\n * A fiber that never fails or succeeds.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const never: Fiber<never> = internal.never\n\n/**\n * Returns a fiber that prefers `this` fiber, but falls back to the `that` one\n * when `this` one fails. Interrupting the returned fiber will interrupt both\n * fibers, sequentially, from left to right.\n *\n * @since 2.0.0\n * @category alternatives\n */\nexport const orElse: {\n  <A2, E2>(that: Fiber<A2, E2>): <A, E>(self: Fiber<A, E>) => Fiber<A2 | A, E2 | E>\n  <A, E, A2, E2>(self: Fiber<A, E>, that: Fiber<A2, E2>): Fiber<A | A2, E | E2>\n} = internal.orElse\n\n/**\n * Returns a fiber that prefers `this` fiber, but falls back to the `that` one\n * when `this` one fails. Interrupting the returned fiber will interrupt both\n * fibers, sequentially, from left to right.\n *\n * @since 2.0.0\n * @category alternatives\n */\nexport const orElseEither: {\n  <A2, E2>(that: Fiber<A2, E2>): <A, E>(self: Fiber<A, E>) => Fiber<Either.Either<A2, A>, E2 | E>\n  <A, E, A2, E2>(self: Fiber<A, E>, that: Fiber<A2, E2>): Fiber<Either.Either<A2, A>, E | E2>\n} = internal.orElseEither\n\n/**\n * Tentatively observes the fiber, but returns immediately if it is not\n * already done.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const poll: <A, E>(self: Fiber<A, E>) => Effect.Effect<Option.Option<Exit.Exit<A, E>>> = internal.poll\n\n/**\n * Pretty-prints a `RuntimeFiber`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const pretty: <A, E>(self: RuntimeFiber<A, E>) => Effect.Effect<string> = internal.pretty\n\n/**\n * Returns a chunk containing all root fibers.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const roots: Effect.Effect<Array<RuntimeFiber<any, any>>> = internal.roots\n\n/**\n * Returns a chunk containing all root fibers.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unsafeRoots: (_: void) => Array<RuntimeFiber<any, any>> = internal.unsafeRoots\n\n/**\n * Converts this fiber into a scoped effect. The fiber is interrupted when the\n * scope is closed.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const scoped: <A, E>(self: Fiber<A, E>) => Effect.Effect<Fiber<A, E>, never, Scope.Scope> =\n  fiberRuntime.fiberScoped\n\n/**\n * Returns the `FiberStatus` of a `RuntimeFiber`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const status: <A, E>(self: RuntimeFiber<A, E>) => Effect.Effect<FiberStatus.FiberStatus> = internal.status\n\n/**\n * Returns a fiber that has already succeeded with the specified value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeed: <A>(value: A) => Fiber<A> = internal.succeed\n\nconst void_: Fiber<void> = internal.void\nexport {\n  /**\n   * A fiber that has already succeeded with unit.\n   *\n   * @since 2.0.0\n   * @category constructors\n   */\n  void_ as void\n}\n\n/**\n * Zips this fiber and the specified fiber together, producing a tuple of\n * their output.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zip: {\n  <A2, E2>(that: Fiber<A2, E2>): <A, E>(self: Fiber<A, E>) => Fiber<[A, A2], E2 | E>\n  <A, E, A2, E2>(self: Fiber<A, E>, that: Fiber<A2, E2>): Fiber<[A, A2], E | E2>\n} = circular.zipFiber\n\n/**\n * Same as `zip` but discards the output of that `Fiber`.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipLeft: {\n  <A2, E2>(that: Fiber<A2, E2>): <A, E>(self: Fiber<A, E>) => Fiber<A, E2 | E>\n  <A, E, A2, E2>(self: Fiber<A, E>, that: Fiber<A2, E2>): Fiber<A, E | E2>\n} = circular.zipLeftFiber\n\n/**\n * Same as `zip` but discards the output of this `Fiber`.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipRight: {\n  <A2, E2>(that: Fiber<A2, E2>): <A, E>(self: Fiber<A, E>) => Fiber<A2, E2 | E>\n  <A, E, A2, E2>(self: Fiber<A, E>, that: Fiber<A2, E2>): Fiber<A2, E | E2>\n} = circular.zipRightFiber\n\n/**\n * Zips this fiber with the specified fiber, combining their results using the\n * specified combiner function. Both joins and interruptions are performed in\n * sequential order from left to right.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWith: {\n  <B, E2, A, C>(that: Fiber<B, E2>, f: (a: A, b: B) => C): <E>(self: Fiber<A, E>) => Fiber<C, E2 | E>\n  <A, E, B, E2, C>(self: Fiber<A, E>, that: Fiber<B, E2>, f: (a: A, b: B) => C): Fiber<C, E | E2>\n} = circular.zipWithFiber\n"
  },
  {
    "path": "packages/effect/src/FiberHandle.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { NoSuchElementException } from \"./Cause.js\"\nimport * as Cause from \"./Cause.js\"\nimport * as Deferred from \"./Deferred.js\"\nimport * as Effect from \"./Effect.js\"\nimport * as Exit from \"./Exit.js\"\nimport * as Fiber from \"./Fiber.js\"\nimport * as FiberId from \"./FiberId.js\"\nimport { constFalse, dual } from \"./Function.js\"\nimport * as HashSet from \"./HashSet.js\"\nimport * as Inspectable from \"./Inspectable.js\"\nimport * as Option from \"./Option.js\"\nimport { type Pipeable, pipeArguments } from \"./Pipeable.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport * as Runtime from \"./Runtime.js\"\nimport type * as Scope from \"./Scope.js\"\n\n/**\n * @since 2.0.0\n * @categories type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/FiberHandle\")\n\n/**\n * @since 2.0.0\n * @categories type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @categories models\n */\nexport interface FiberHandle<out A = unknown, out E = unknown> extends Pipeable, Inspectable.Inspectable {\n  readonly [TypeId]: TypeId\n  readonly deferred: Deferred.Deferred<void, unknown>\n  /** @internal */\n  state: {\n    readonly _tag: \"Open\"\n    fiber: Fiber.RuntimeFiber<A, E> | undefined\n  } | {\n    readonly _tag: \"Closed\"\n  }\n}\n\n/**\n * @since 2.0.0\n * @categories refinements\n */\nexport const isFiberHandle = (u: unknown): u is FiberHandle => Predicate.hasProperty(u, TypeId)\n\nconst Proto = {\n  [TypeId]: TypeId,\n  toString(this: FiberHandle) {\n    return Inspectable.format(this.toJSON())\n  },\n  toJSON(this: FiberHandle) {\n    return {\n      _id: \"FiberHandle\",\n      state: this.state\n    }\n  },\n  [Inspectable.NodeInspectSymbol](this: FiberHandle) {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst unsafeMake = <A = unknown, E = unknown>(\n  deferred: Deferred.Deferred<void, E>\n): FiberHandle<A, E> => {\n  const self = Object.create(Proto)\n  self.state = { _tag: \"Open\", fiber: undefined }\n  self.deferred = deferred\n  return self\n}\n\n/**\n * A FiberHandle can be used to store a single fiber.\n * When the associated Scope is closed, the contained fiber will be interrupted.\n *\n * You can add a fiber to the handle using `FiberHandle.run`, and the fiber will\n * be automatically removed from the FiberHandle when it completes.\n *\n * @example\n * ```ts\n * import { Effect, FiberHandle } from \"effect\"\n *\n * Effect.gen(function*() {\n *   const handle = yield* FiberHandle.make()\n *\n *   // run some effects\n *   yield* FiberHandle.run(handle, Effect.never)\n *   // this will interrupt the previous fiber\n *   yield* FiberHandle.run(handle, Effect.never)\n *\n *   yield* Effect.sleep(1000)\n * }).pipe(\n *   Effect.scoped // The fiber will be interrupted when the scope is closed\n * )\n * ```\n *\n * @since 2.0.0\n * @categories constructors\n */\nexport const make = <A = unknown, E = unknown>(): Effect.Effect<FiberHandle<A, E>, never, Scope.Scope> =>\n  Effect.acquireRelease(\n    Effect.map(Deferred.make<void, E>(), (deferred) => unsafeMake<A, E>(deferred)),\n    (handle) =>\n      Effect.withFiberRuntime((parent) => {\n        const state = handle.state\n        if (state._tag === \"Closed\") return Effect.void\n        handle.state = { _tag: \"Closed\" }\n        return state.fiber ?\n          Effect.intoDeferred(\n            Effect.asVoid(Fiber.interruptAs(state.fiber, FiberId.combine(parent.id(), internalFiberId))),\n            handle.deferred\n          ) :\n          Deferred.done(handle.deferred, Exit.void)\n      })\n  )\n\n/**\n * Create an Effect run function that is backed by a FiberHandle.\n *\n * @since 2.0.0\n * @categories constructors\n */\nexport const makeRuntime = <R, E = unknown, A = unknown>(): Effect.Effect<\n  <XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>,\n    options?:\n      | Runtime.RunForkOptions & {\n        readonly onlyIfMissing?: boolean | undefined\n      }\n      | undefined\n  ) => Fiber.RuntimeFiber<XA, XE>,\n  never,\n  Scope.Scope | R\n> =>\n  Effect.flatMap(\n    make<A, E>(),\n    (self) => runtime(self)<R>()\n  )\n\n/**\n * Create an Effect run function that is backed by a FiberHandle.\n *\n * @since 3.13.0\n * @categories constructors\n */\nexport const makeRuntimePromise = <R = never, A = unknown, E = unknown>(): Effect.Effect<\n  <XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>,\n    options?: Runtime.RunForkOptions | undefined\n  ) => Promise<XA>,\n  never,\n  Scope.Scope | R\n> =>\n  Effect.flatMap(\n    make<A, E>(),\n    (self) => runtimePromise(self)<R>()\n  )\n\nconst internalFiberIdId = -1\nconst internalFiberId = FiberId.make(internalFiberIdId, 0)\nconst isInternalInterruption = Cause.reduceWithContext(undefined, {\n  emptyCase: constFalse,\n  failCase: constFalse,\n  dieCase: constFalse,\n  interruptCase: (_, fiberId) => HashSet.has(FiberId.ids(fiberId), internalFiberIdId),\n  sequentialCase: (_, left, right) => left || right,\n  parallelCase: (_, left, right) => left || right\n})\n\n/**\n * Set the fiber in a FiberHandle. When the fiber completes, it will be removed from the FiberHandle.\n * If a fiber is already running, it will be interrupted unless `options.onlyIfMissing` is set.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const unsafeSet: {\n  <A, E, XE extends E, XA extends A>(\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly interruptAs?: FiberId.FiberId | undefined\n      readonly onlyIfMissing?: boolean | undefined\n      readonly propagateInterruption?: boolean | undefined\n    }\n  ): (self: FiberHandle<A, E>) => void\n  <A, E, XE extends E, XA extends A>(\n    self: FiberHandle<A, E>,\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly interruptAs?: FiberId.FiberId | undefined\n      readonly onlyIfMissing?: boolean | undefined\n      readonly propagateInterruption?: boolean | undefined\n    }\n  ): void\n} = dual((args) => isFiberHandle(args[0]), <A, E, XE extends E, XA extends A>(\n  self: FiberHandle<A, E>,\n  fiber: Fiber.RuntimeFiber<XA, XE>,\n  options?: {\n    readonly interruptAs?: FiberId.FiberId | undefined\n    readonly onlyIfMissing?: boolean | undefined\n    readonly propagateInterruption?: boolean | undefined\n  }\n): void => {\n  if (self.state._tag === \"Closed\") {\n    fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId))\n    return\n  } else if (self.state.fiber !== undefined) {\n    if (options?.onlyIfMissing === true) {\n      fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId))\n      return\n    } else if (self.state.fiber === fiber) {\n      return\n    }\n    self.state.fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId))\n    self.state.fiber = undefined\n  }\n\n  self.state.fiber = fiber\n  fiber.addObserver((exit) => {\n    if (self.state._tag === \"Open\" && fiber === self.state.fiber) {\n      self.state.fiber = undefined\n    }\n    if (\n      Exit.isFailure(exit) &&\n      (\n        options?.propagateInterruption === true ?\n          !isInternalInterruption(exit.cause) :\n          !Cause.isInterruptedOnly(exit.cause)\n      )\n    ) {\n      Deferred.unsafeDone(self.deferred, exit as any)\n    }\n  })\n})\n\n/**\n * Set the fiber in the FiberHandle. When the fiber completes, it will be removed from the FiberHandle.\n * If a fiber already exists in the FiberHandle, it will be interrupted unless `options.onlyIfMissing` is set.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const set: {\n  <A, E, XE extends E, XA extends A>(\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly onlyIfMissing?: boolean\n      readonly propagateInterruption?: boolean | undefined\n    }\n  ): (self: FiberHandle<A, E>) => Effect.Effect<void>\n  <A, E, XE extends E, XA extends A>(\n    self: FiberHandle<A, E>,\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly onlyIfMissing?: boolean\n      readonly propagateInterruption?: boolean | undefined\n    }\n  ): Effect.Effect<void>\n} = dual((args) => isFiberHandle(args[0]), <A, E, XE extends E, XA extends A>(\n  self: FiberHandle<A, E>,\n  fiber: Fiber.RuntimeFiber<XA, XE>,\n  options?: {\n    readonly onlyIfMissing?: boolean\n    readonly propagateInterruption?: boolean | undefined\n  }\n): Effect.Effect<void> =>\n  Effect.fiberIdWith(\n    (fiberId) =>\n      Effect.sync(() =>\n        unsafeSet(self, fiber, {\n          interruptAs: fiberId,\n          onlyIfMissing: options?.onlyIfMissing,\n          propagateInterruption: options?.propagateInterruption\n        })\n      )\n  ))\n\n/**\n * Retrieve the fiber from the FiberHandle.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const unsafeGet = <A, E>(self: FiberHandle<A, E>): Option.Option<Fiber.RuntimeFiber<A, E>> =>\n  self.state._tag === \"Closed\" ? Option.none() : Option.fromNullable(self.state.fiber)\n\n/**\n * Retrieve the fiber from the FiberHandle.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const get = <A, E>(self: FiberHandle<A, E>): Effect.Effect<Fiber.RuntimeFiber<A, E>, NoSuchElementException> =>\n  Effect.suspend(() => unsafeGet(self))\n\n/**\n * @since 2.0.0\n * @categories combinators\n */\nexport const clear = <A, E>(self: FiberHandle<A, E>): Effect.Effect<void> =>\n  Effect.uninterruptibleMask((restore) =>\n    Effect.withFiberRuntime((fiber) => {\n      if (self.state._tag === \"Closed\" || self.state.fiber === undefined) {\n        return Effect.void\n      }\n      return Effect.zipRight(\n        restore(Fiber.interruptAs(self.state.fiber, FiberId.combine(fiber.id(), internalFiberId))),\n        Effect.sync(() => {\n          if (self.state._tag === \"Open\") {\n            self.state.fiber = undefined\n          }\n        })\n      )\n    })\n  )\n\nconst constInterruptedFiber = (function() {\n  let fiber: Fiber.RuntimeFiber<never, never> | undefined = undefined\n  return () => {\n    if (fiber === undefined) {\n      fiber = Effect.runFork(Effect.interrupt)\n    }\n    return fiber\n  }\n})()\n\n/**\n * Run an Effect and add the forked fiber to the FiberHandle.\n * When the fiber completes, it will be removed from the FiberHandle.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const run: {\n  <A, E>(\n    self: FiberHandle<A, E>,\n    options?: {\n      readonly onlyIfMissing?: boolean\n      readonly propagateInterruption?: boolean | undefined\n    }\n  ): <R, XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>\n  ) => Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R>\n  <A, E, R, XE extends E, XA extends A>(\n    self: FiberHandle<A, E>,\n    effect: Effect.Effect<XA, XE, R>,\n    options?: {\n      readonly onlyIfMissing?: boolean\n      readonly propagateInterruption?: boolean | undefined\n    }\n  ): Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R>\n} = function() {\n  const self = arguments[0] as FiberHandle\n  if (Effect.isEffect(arguments[1])) {\n    return runImpl(self, arguments[1], arguments[2]) as any\n  }\n  const options = arguments[1]\n  return (effect: Effect.Effect<unknown, unknown, any>) => runImpl(self, effect, options)\n}\n\nconst runImpl = <A, E, R, XE extends E, XA extends A>(\n  self: FiberHandle<A, E>,\n  effect: Effect.Effect<XA, XE, R>,\n  options?: {\n    readonly onlyIfMissing?: boolean\n    readonly propagateInterruption?: boolean | undefined\n  }\n): Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R> =>\n  Effect.withFiberRuntime((parent) => {\n    if (self.state._tag === \"Closed\") {\n      return Effect.interrupt\n    } else if (self.state.fiber !== undefined && options?.onlyIfMissing === true) {\n      return Effect.sync(constInterruptedFiber)\n    }\n    const runtime = Runtime.make<R>({\n      context: parent.currentContext as any,\n      fiberRefs: parent.getFiberRefs(),\n      runtimeFlags: Runtime.defaultRuntime.runtimeFlags\n    })\n    const fiber = Runtime.runFork(runtime)(effect)\n    unsafeSet(self, fiber, { ...options, interruptAs: parent.id() })\n    return Effect.succeed(fiber)\n  })\n\n/**\n * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberHandle.\n *\n * @example\n * ```ts\n * import { Context, Effect, FiberHandle } from \"effect\"\n *\n * interface Users {\n *   readonly _: unique symbol\n * }\n * const Users = Context.GenericTag<Users, {\n *    getAll: Effect.Effect<Array<unknown>>\n * }>(\"Users\")\n *\n * Effect.gen(function*() {\n *   const handle = yield* FiberHandle.make()\n *   const run = yield* FiberHandle.runtime(handle)<Users>()\n *\n *   // run an effect and set the fiber in the handle\n *   run(Effect.andThen(Users, _ => _.getAll))\n *\n *   // this will interrupt the previous fiber\n *   run(Effect.andThen(Users, _ => _.getAll))\n * }).pipe(\n *   Effect.scoped // The fiber will be interrupted when the scope is closed\n * )\n * ```\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const runtime: <A, E>(\n  self: FiberHandle<A, E>\n) => <R = never>() => Effect.Effect<\n  <XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>,\n    options?:\n      | Runtime.RunForkOptions & {\n        readonly onlyIfMissing?: boolean | undefined\n        readonly propagateInterruption?: boolean | undefined\n      }\n      | undefined\n  ) => Fiber.RuntimeFiber<XA, XE>,\n  never,\n  R\n> = <A, E>(self: FiberHandle<A, E>) => <R>() =>\n  Effect.map(\n    Effect.runtime<R>(),\n    (runtime) => {\n      const runFork = Runtime.runFork(runtime)\n      return <XE extends E, XA extends A>(\n        effect: Effect.Effect<XA, XE, R>,\n        options?:\n          | Runtime.RunForkOptions & {\n            readonly onlyIfMissing?: boolean | undefined\n            readonly propagateInterruption?: boolean | undefined\n          }\n          | undefined\n      ) => {\n        if (self.state._tag === \"Closed\") {\n          return constInterruptedFiber()\n        } else if (self.state.fiber !== undefined && options?.onlyIfMissing === true) {\n          return constInterruptedFiber()\n        }\n        const fiber = runFork(effect, options)\n        unsafeSet(self, fiber, options)\n        return fiber\n      }\n    }\n  )\n\n/**\n * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberHandle.\n *\n * The returned run function will return Promise's that will resolve when the\n * fiber completes.\n *\n * @since 3.13.0\n * @categories combinators\n */\nexport const runtimePromise = <A, E>(self: FiberHandle<A, E>): <R = never>() => Effect.Effect<\n  <XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>,\n    options?:\n      | Runtime.RunForkOptions & { readonly propagateInterruption?: boolean | undefined }\n      | undefined\n  ) => Promise<XA>,\n  never,\n  R\n> =>\n<R>() =>\n  Effect.map(\n    runtime(self)<R>(),\n    (runFork) =>\n    <XE extends E, XA extends A>(\n      effect: Effect.Effect<XA, XE, R>,\n      options?:\n        | Runtime.RunForkOptions & { readonly propagateInterruption?: boolean | undefined }\n        | undefined\n    ): Promise<XA> =>\n      new Promise((resolve, reject) =>\n        runFork(effect, options).addObserver((exit) => {\n          if (Exit.isSuccess(exit)) {\n            resolve(exit.value)\n          } else {\n            reject(Cause.squash(exit.cause))\n          }\n        })\n      )\n  )\n\n/**\n * If any of the Fiber's in the handle terminate with a failure,\n * the returned Effect will terminate with the first failure that occurred.\n *\n * @since 2.0.0\n * @categories combinators\n * @example\n * ```ts\n * import { Effect, FiberHandle } from \"effect\";\n *\n * Effect.gen(function* (_) {\n *   const handle = yield* _(FiberHandle.make());\n *   yield* _(FiberHandle.set(handle, Effect.runFork(Effect.fail(\"error\"))));\n *\n *   // parent fiber will fail with \"error\"\n *   yield* _(FiberHandle.join(handle));\n * });\n * ```\n */\nexport const join = <A, E>(self: FiberHandle<A, E>): Effect.Effect<void, E> =>\n  Deferred.await(self.deferred as Deferred.Deferred<void, E>)\n\n/**\n * Wait for the fiber in the FiberHandle to complete.\n *\n * @since 3.13.0\n * @categories combinators\n */\nexport const awaitEmpty = <A, E>(self: FiberHandle<A, E>): Effect.Effect<void, E> =>\n  Effect.suspend(() => {\n    if (self.state._tag === \"Closed\" || self.state.fiber === undefined) {\n      return Effect.void\n    }\n    return Fiber.await(self.state.fiber)\n  })\n"
  },
  {
    "path": "packages/effect/src/FiberId.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Equal from \"./Equal.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as internal from \"./internal/fiberId.js\"\nimport type * as Option from \"./Option.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const FiberIdTypeId: unique symbol = internal.FiberIdTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type FiberIdTypeId = typeof FiberIdTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type Single = None | Runtime\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type FiberId = Single | Composite\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface None extends Equal.Equal, Inspectable {\n  readonly [FiberIdTypeId]: FiberIdTypeId\n  readonly _tag: \"None\"\n  readonly id: -1\n  readonly startTimeMillis: -1\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Runtime extends Equal.Equal, Inspectable {\n  readonly [FiberIdTypeId]: FiberIdTypeId\n  readonly _tag: \"Runtime\"\n  readonly id: number\n  readonly startTimeMillis: number\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Composite extends Equal.Equal, Inspectable {\n  readonly [FiberIdTypeId]: FiberIdTypeId\n  readonly _tag: \"Composite\"\n  readonly left: FiberId\n  readonly right: FiberId\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const none: None = internal.none\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const runtime: (id: number, startTimeMillis: number) => Runtime = internal.runtime\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const composite: (left: FiberId, right: FiberId) => Composite = internal.composite\n\n/**\n * Returns `true` if the specified unknown value is a `FiberId`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isFiberId: (self: unknown) => self is FiberId = internal.isFiberId\n\n/**\n * Returns `true` if the `FiberId` is a `None`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isNone: (self: FiberId) => self is None = internal.isNone\n\n/**\n * Returns `true` if the `FiberId` is a `Runtime`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isRuntime: (self: FiberId) => self is Runtime = internal.isRuntime\n\n/**\n * Returns `true` if the `FiberId` is a `Composite`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isComposite: (self: FiberId) => self is Composite = internal.isComposite\n\n/**\n * Combine two `FiberId`s.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const combine: {\n  (that: FiberId): (self: FiberId) => FiberId\n  (self: FiberId, that: FiberId): FiberId\n} = internal.combine\n\n/**\n * Combines a set of `FiberId`s into a single `FiberId`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const combineAll: (fiberIds: HashSet.HashSet<FiberId>) => FiberId = internal.combineAll\n\n/**\n * Returns this `FiberId` if it is not `None`, otherwise returns that `FiberId`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const getOrElse: {\n  (that: FiberId): (self: FiberId) => FiberId\n  (self: FiberId, that: FiberId): FiberId\n} = internal.getOrElse\n\n/**\n * Get the set of identifiers for this `FiberId`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const ids: (self: FiberId) => HashSet.HashSet<number> = internal.ids\n\n/**\n * Creates a new `FiberId`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (id: number, startTimeSeconds: number) => FiberId = internal.make\n\n/**\n * Creates a string representing the name of the current thread of execution\n * represented by the specified `FiberId`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const threadName: (self: FiberId) => string = internal.threadName\n\n/**\n * Convert a `FiberId` into an `Option<FiberId>`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toOption: (self: FiberId) => Option.Option<FiberId> = internal.toOption\n\n/**\n * Convert a `FiberId` into a `HashSet<FiberId>`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toSet: (self: FiberId) => HashSet.HashSet<Runtime> = internal.toSet\n\n/**\n * Unsafely creates a new `FiberId`.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeMake: (_: void) => Runtime = internal.unsafeMake\n"
  },
  {
    "path": "packages/effect/src/FiberMap.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { NoSuchElementException } from \"./Cause.js\"\nimport * as Cause from \"./Cause.js\"\nimport * as Deferred from \"./Deferred.js\"\nimport * as Effect from \"./Effect.js\"\nimport * as Exit from \"./Exit.js\"\nimport * as Fiber from \"./Fiber.js\"\nimport * as FiberId from \"./FiberId.js\"\nimport { constFalse, constVoid, dual } from \"./Function.js\"\nimport * as HashSet from \"./HashSet.js\"\nimport * as Inspectable from \"./Inspectable.js\"\nimport * as Iterable from \"./Iterable.js\"\nimport * as MutableHashMap from \"./MutableHashMap.js\"\nimport * as Option from \"./Option.js\"\nimport { type Pipeable, pipeArguments } from \"./Pipeable.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport * as Runtime from \"./Runtime.js\"\nimport type * as Scope from \"./Scope.js\"\n\n/**\n * @since 2.0.0\n * @categories type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/FiberMap\")\n\n/**\n * @since 2.0.0\n * @categories type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @categories models\n */\nexport interface FiberMap<in out K, out A = unknown, out E = unknown>\n  extends Pipeable, Inspectable.Inspectable, Iterable<[K, Fiber.RuntimeFiber<A, E>]>\n{\n  readonly [TypeId]: TypeId\n  readonly deferred: Deferred.Deferred<void, unknown>\n  /** @internal */\n  state: {\n    readonly _tag: \"Open\"\n    readonly backing: MutableHashMap.MutableHashMap<K, Fiber.RuntimeFiber<A, E>>\n  } | {\n    readonly _tag: \"Closed\"\n  }\n}\n\n/**\n * @since 2.0.0\n * @categories refinements\n */\nexport const isFiberMap = (u: unknown): u is FiberMap<unknown> => Predicate.hasProperty(u, TypeId)\n\nconst Proto = {\n  [TypeId]: TypeId,\n  [Symbol.iterator](this: FiberMap<unknown>) {\n    if (this.state._tag === \"Closed\") {\n      return Iterable.empty()\n    }\n    return this.state.backing[Symbol.iterator]()\n  },\n  toString(this: FiberMap<unknown>) {\n    return Inspectable.format(this.toJSON())\n  },\n  toJSON(this: FiberMap<unknown>) {\n    return {\n      _id: \"FiberMap\",\n      state: this.state\n    }\n  },\n  [Inspectable.NodeInspectSymbol](this: FiberMap<unknown>) {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst unsafeMake = <K, A = unknown, E = unknown>(\n  backing: MutableHashMap.MutableHashMap<K, Fiber.RuntimeFiber<A, E>>,\n  deferred: Deferred.Deferred<void, E>\n): FiberMap<K, A, E> => {\n  const self = Object.create(Proto)\n  self.state = { _tag: \"Open\", backing }\n  self.deferred = deferred\n  return self\n}\n\n/**\n * A FiberMap can be used to store a collection of fibers, indexed by some key.\n * When the associated Scope is closed, all fibers in the map will be interrupted.\n *\n * You can add fibers to the map using `FiberMap.set` or `FiberMap.run`, and the fibers will\n * be automatically removed from the FiberMap when they complete.\n *\n * @example\n * ```ts\n * import { Effect, FiberMap } from \"effect\"\n *\n * Effect.gen(function*() {\n *   const map = yield* FiberMap.make<string>()\n *\n *   // run some effects and add the fibers to the map\n *   yield* FiberMap.run(map, \"fiber a\", Effect.never)\n *   yield* FiberMap.run(map, \"fiber b\", Effect.never)\n *\n *   yield* Effect.sleep(1000)\n * }).pipe(\n *   Effect.scoped // The fibers will be interrupted when the scope is closed\n * )\n * ```\n *\n * @since 2.0.0\n * @categories constructors\n */\nexport const make = <K, A = unknown, E = unknown>(): Effect.Effect<FiberMap<K, A, E>, never, Scope.Scope> =>\n  Effect.acquireRelease(\n    Effect.map(Deferred.make<void, E>(), (deferred) =>\n      unsafeMake<K, A, E>(\n        MutableHashMap.empty(),\n        deferred\n      )),\n    (map) =>\n      Effect.withFiberRuntime((parent) => {\n        const state = map.state\n        if (state._tag === \"Closed\") return Effect.void\n        map.state = { _tag: \"Closed\" }\n        return Fiber.interruptAllAs(\n          Iterable.map(state.backing, ([, fiber]) => fiber),\n          FiberId.combine(parent.id(), internalFiberId)\n        ).pipe(\n          Effect.intoDeferred(map.deferred)\n        )\n      })\n  )\n\n/**\n * Create an Effect run function that is backed by a FiberMap.\n *\n * @since 2.0.0\n * @categories constructors\n */\nexport const makeRuntime = <R, K, E = unknown, A = unknown>(): Effect.Effect<\n  <XE extends E, XA extends A>(\n    key: K,\n    effect: Effect.Effect<XA, XE, R>,\n    options?:\n      | Runtime.RunForkOptions & {\n        readonly onlyIfMissing?: boolean | undefined\n      }\n      | undefined\n  ) => Fiber.RuntimeFiber<XA, XE>,\n  never,\n  Scope.Scope | R\n> =>\n  Effect.flatMap(\n    make<K, A, E>(),\n    (self) => runtime(self)<R>()\n  )\n\n/**\n * Create an Effect run function that is backed by a FiberMap.\n *\n * @since 3.13.0\n * @categories constructors\n */\nexport const makeRuntimePromise = <R, K, A = unknown, E = unknown>(): Effect.Effect<\n  <XE extends E, XA extends A>(\n    key: K,\n    effect: Effect.Effect<XA, XE, R>,\n    options?:\n      | Runtime.RunForkOptions & {\n        readonly onlyIfMissing?: boolean | undefined\n      }\n      | undefined\n  ) => Promise<XA>,\n  never,\n  Scope.Scope | R\n> =>\n  Effect.flatMap(\n    make<K, A, E>(),\n    (self) => runtimePromise(self)<R>()\n  )\n\nconst internalFiberIdId = -1\nconst internalFiberId = FiberId.make(internalFiberIdId, 0)\nconst isInternalInterruption = Cause.reduceWithContext(undefined, {\n  emptyCase: constFalse,\n  failCase: constFalse,\n  dieCase: constFalse,\n  interruptCase: (_, fiberId) => HashSet.has(FiberId.ids(fiberId), internalFiberIdId),\n  sequentialCase: (_, left, right) => left || right,\n  parallelCase: (_, left, right) => left || right\n})\n\n/**\n * Add a fiber to the FiberMap. When the fiber completes, it will be removed from the FiberMap.\n * If the key already exists in the FiberMap, the previous fiber will be interrupted.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const unsafeSet: {\n  <K, A, E, XE extends E, XA extends A>(\n    key: K,\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly interruptAs?: FiberId.FiberId | undefined\n      readonly onlyIfMissing?: boolean | undefined\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): (self: FiberMap<K, A, E>) => void\n  <K, A, E, XE extends E, XA extends A>(\n    self: FiberMap<K, A, E>,\n    key: K,\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly interruptAs?: FiberId.FiberId | undefined\n      readonly onlyIfMissing?: boolean | undefined\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): void\n} = dual((args) => isFiberMap(args[0]), <K, A, E, XE extends E, XA extends A>(\n  self: FiberMap<K, A, E>,\n  key: K,\n  fiber: Fiber.RuntimeFiber<XA, XE>,\n  options?: {\n    readonly interruptAs?: FiberId.FiberId | undefined\n    readonly onlyIfMissing?: boolean | undefined\n    readonly propagateInterruption?: boolean | undefined\n  } | undefined\n): void => {\n  if (self.state._tag === \"Closed\") {\n    fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId))\n    return\n  }\n\n  const previous = MutableHashMap.get(self.state.backing, key)\n  if (previous._tag === \"Some\") {\n    if (options?.onlyIfMissing === true) {\n      fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId))\n      return\n    } else if (previous.value === fiber) {\n      return\n    }\n    previous.value.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId))\n  }\n\n  MutableHashMap.set(self.state.backing, key, fiber)\n  fiber.addObserver((exit) => {\n    if (self.state._tag === \"Closed\") {\n      return\n    }\n    const current = MutableHashMap.get(self.state.backing, key)\n    if (Option.isSome(current) && fiber === current.value) {\n      MutableHashMap.remove(self.state.backing, key)\n    }\n    if (\n      Exit.isFailure(exit) &&\n      (\n        options?.propagateInterruption === true ?\n          !isInternalInterruption(exit.cause) :\n          !Cause.isInterruptedOnly(exit.cause)\n      )\n    ) {\n      Deferred.unsafeDone(self.deferred, exit as any)\n    }\n  })\n})\n\n/**\n * Add a fiber to the FiberMap. When the fiber completes, it will be removed from the FiberMap.\n * If the key already exists in the FiberMap, the previous fiber will be interrupted.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const set: {\n  <K, A, E, XE extends E, XA extends A>(\n    key: K,\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly onlyIfMissing?: boolean | undefined\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): (self: FiberMap<K, A, E>) => Effect.Effect<void>\n  <K, A, E, XE extends E, XA extends A>(\n    self: FiberMap<K, A, E>,\n    key: K,\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly onlyIfMissing?: boolean | undefined\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): Effect.Effect<void>\n} = dual((args) => isFiberMap(args[0]), <K, A, E, XE extends E, XA extends A>(\n  self: FiberMap<K, A, E>,\n  key: K,\n  fiber: Fiber.RuntimeFiber<XA, XE>,\n  options?: {\n    readonly onlyIfMissing?: boolean | undefined\n    readonly propagateInterruption?: boolean | undefined\n  } | undefined\n): Effect.Effect<void> =>\n  Effect.fiberIdWith(\n    (fiberId) =>\n      Effect.sync(() =>\n        unsafeSet(self, key, fiber, {\n          ...options,\n          interruptAs: fiberId\n        })\n      )\n  ))\n\n/**\n * Retrieve a fiber from the FiberMap.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const unsafeGet: {\n  <K>(key: K): <A, E>(self: FiberMap<K, A, E>) => Option.Option<Fiber.RuntimeFiber<A, E>>\n  <K, A, E>(self: FiberMap<K, A, E>, key: K): Option.Option<Fiber.RuntimeFiber<A, E>>\n} = dual<\n  <K>(\n    key: K\n  ) => <A, E>(self: FiberMap<K, A, E>) => Option.Option<Fiber.RuntimeFiber<A, E>>,\n  <K, A, E>(\n    self: FiberMap<K, A, E>,\n    key: K\n  ) => Option.Option<Fiber.RuntimeFiber<A, E>>\n>(2, (self, key) => self.state._tag === \"Closed\" ? Option.none() : MutableHashMap.get(self.state.backing, key))\n\n/**\n * Retrieve a fiber from the FiberMap.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const get: {\n  <K>(key: K): <A, E>(self: FiberMap<K, A, E>) => Effect.Effect<Fiber.RuntimeFiber<A, E>, NoSuchElementException>\n  <K, A, E>(self: FiberMap<K, A, E>, key: K): Effect.Effect<Fiber.RuntimeFiber<A, E>, NoSuchElementException>\n} = dual<\n  <K>(\n    key: K\n  ) => <A, E>(self: FiberMap<K, A, E>) => Effect.Effect<Fiber.RuntimeFiber<A, E>, NoSuchElementException>,\n  <K, A, E>(\n    self: FiberMap<K, A, E>,\n    key: K\n  ) => Effect.Effect<Fiber.RuntimeFiber<A, E>, NoSuchElementException>\n>(2, (self, key) => Effect.suspend(() => unsafeGet(self, key)))\n\n/**\n * Check if a key exists in the FiberMap.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const unsafeHas: {\n  <K>(key: K): <A, E>(self: FiberMap<K, A, E>) => boolean\n  <K, A, E>(self: FiberMap<K, A, E>, key: K): boolean\n} = dual(\n  2,\n  <K, A, E>(self: FiberMap<K, A, E>, key: K): boolean =>\n    self.state._tag === \"Closed\" ? false : MutableHashMap.has(self.state.backing, key)\n)\n\n/**\n * Check if a key exists in the FiberMap.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const has: {\n  <K>(key: K): <A, E>(self: FiberMap<K, A, E>) => Effect.Effect<boolean>\n  <K, A, E>(self: FiberMap<K, A, E>, key: K): Effect.Effect<boolean>\n} = dual(\n  2,\n  <K, A, E>(self: FiberMap<K, A, E>, key: K): Effect.Effect<boolean> => Effect.sync(() => unsafeHas(self, key))\n)\n\n/**\n * Remove a fiber from the FiberMap, interrupting it if it exists.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const remove: {\n  <K>(key: K): <A, E>(self: FiberMap<K, A, E>) => Effect.Effect<void>\n  <K, A, E>(self: FiberMap<K, A, E>, key: K): Effect.Effect<void>\n} = dual<\n  <K>(\n    key: K\n  ) => <A, E>(self: FiberMap<K, A, E>) => Effect.Effect<void>,\n  <K, A, E>(\n    self: FiberMap<K, A, E>,\n    key: K\n  ) => Effect.Effect<void>\n>(2, (self, key) =>\n  Effect.withFiberRuntime((removeFiber) => {\n    if (self.state._tag === \"Closed\") {\n      return Effect.void\n    }\n    const fiber = MutableHashMap.get(self.state.backing, key)\n    if (fiber._tag === \"None\") {\n      return Effect.void\n    }\n    // will be removed by the observer\n    return Fiber.interruptAs(fiber.value, FiberId.combine(removeFiber.id(), internalFiberId))\n  }))\n\n/**\n * @since 2.0.0\n * @categories combinators\n */\nexport const clear = <K, A, E>(self: FiberMap<K, A, E>): Effect.Effect<void> =>\n  Effect.withFiberRuntime((clearFiber) => {\n    if (self.state._tag === \"Closed\") {\n      return Effect.void\n    }\n\n    return Effect.forEach(self.state.backing, ([, fiber]) =>\n      // will be removed by the observer\n      Fiber.interruptAs(fiber, FiberId.combine(clearFiber.id(), internalFiberId)))\n  })\n\nconst constInterruptedFiber = (function() {\n  let fiber: Fiber.RuntimeFiber<never, never> | undefined = undefined\n  return () => {\n    if (fiber === undefined) {\n      fiber = Effect.runFork(Effect.interrupt)\n    }\n    return fiber\n  }\n})()\n\n/**\n * Run an Effect and add the forked fiber to the FiberMap.\n * When the fiber completes, it will be removed from the FiberMap.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const run: {\n  <K, A, E>(\n    self: FiberMap<K, A, E>,\n    key: K,\n    options?: {\n      readonly onlyIfMissing?: boolean | undefined\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): <R, XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>\n  ) => Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R>\n  <K, A, E, R, XE extends E, XA extends A>(\n    self: FiberMap<K, A, E>,\n    key: K,\n    effect: Effect.Effect<XA, XE, R>,\n    options?: {\n      readonly onlyIfMissing?: boolean | undefined\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R>\n} = function() {\n  const self = arguments[0]\n  if (Effect.isEffect(arguments[2])) {\n    return runImpl(self, arguments[1], arguments[2], arguments[3]) as any\n  }\n  const key = arguments[1]\n  const options = arguments[2]\n  return (effect: Effect.Effect<any, any, any>) => runImpl(self, key, effect, options)\n}\n\nconst runImpl = <K, A, E, R, XE extends E, XA extends A>(\n  self: FiberMap<K, A, E>,\n  key: K,\n  effect: Effect.Effect<XA, XE, R>,\n  options?: {\n    readonly onlyIfMissing?: boolean\n    readonly propagateInterruption?: boolean | undefined\n  }\n) =>\n  Effect.withFiberRuntime((parent) => {\n    if (self.state._tag === \"Closed\") {\n      return Effect.interrupt\n    } else if (options?.onlyIfMissing === true && unsafeHas(self, key)) {\n      return Effect.sync(constInterruptedFiber)\n    }\n    const runtime = Runtime.make<R>({\n      context: parent.currentContext as any,\n      fiberRefs: parent.getFiberRefs(),\n      runtimeFlags: Runtime.defaultRuntime.runtimeFlags\n    })\n    const fiber = Runtime.runFork(runtime)(effect)\n    unsafeSet(self, key, fiber, { ...options, interruptAs: parent.id() })\n    return Effect.succeed(fiber)\n  })\n\n/**\n * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberMap.\n *\n * @example\n * ```ts\n * import { Context, Effect, FiberMap } from \"effect\"\n *\n * interface Users {\n *   readonly _: unique symbol\n * }\n * const Users = Context.GenericTag<Users, {\n *    getAll: Effect.Effect<Array<unknown>>\n * }>(\"Users\")\n *\n * Effect.gen(function*() {\n *   const map = yield* FiberMap.make<string>()\n *   const run = yield* FiberMap.runtime(map)<Users>()\n *\n *   // run some effects and add the fibers to the map\n *   run(\"effect-a\", Effect.andThen(Users, _ => _.getAll))\n *   run(\"effect-b\", Effect.andThen(Users, _ => _.getAll))\n * }).pipe(\n *   Effect.scoped // The fibers will be interrupted when the scope is closed\n * )\n * ```\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const runtime: <K, A, E>(\n  self: FiberMap<K, A, E>\n) => <R = never>() => Effect.Effect<\n  <XE extends E, XA extends A>(\n    key: K,\n    effect: Effect.Effect<XA, XE, R>,\n    options?:\n      | Runtime.RunForkOptions & {\n        readonly onlyIfMissing?: boolean | undefined\n        readonly propagateInterruption?: boolean | undefined\n      }\n      | undefined\n  ) => Fiber.RuntimeFiber<XA, XE>,\n  never,\n  R\n> = <K, A, E>(self: FiberMap<K, A, E>) => <R>() =>\n  Effect.map(\n    Effect.runtime<R>(),\n    (runtime) => {\n      const runFork = Runtime.runFork(runtime)\n      return <XE extends E, XA extends A>(\n        key: K,\n        effect: Effect.Effect<XA, XE, R>,\n        options?:\n          | Runtime.RunForkOptions & {\n            readonly onlyIfMissing?: boolean | undefined\n            readonly propagateInterruption?: boolean | undefined\n          }\n          | undefined\n      ) => {\n        if (self.state._tag === \"Closed\") {\n          return constInterruptedFiber()\n        } else if (options?.onlyIfMissing === true && unsafeHas(self, key)) {\n          return constInterruptedFiber()\n        }\n        const fiber = runFork(effect, options)\n        unsafeSet(self, key, fiber, options)\n        return fiber\n      }\n    }\n  )\n\n/**\n * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberMap.\n *\n * @since 3.13.0\n * @categories combinators\n */\nexport const runtimePromise = <K, A, E>(self: FiberMap<K, A, E>): <R = never>() => Effect.Effect<\n  <XE extends E, XA extends A>(\n    key: K,\n    effect: Effect.Effect<XA, XE, R>,\n    options?:\n      | Runtime.RunForkOptions & {\n        readonly onlyIfMissing?: boolean | undefined\n        readonly propagateInterruption?: boolean | undefined\n      }\n      | undefined\n  ) => Promise<XA>,\n  never,\n  R\n> =>\n<R>() =>\n  Effect.map(\n    runtime(self)<R>(),\n    (runFork) =>\n    <XE extends E, XA extends A>(\n      key: K,\n      effect: Effect.Effect<XA, XE, R>,\n      options?:\n        | Runtime.RunForkOptions & { readonly propagateInterruption?: boolean | undefined }\n        | undefined\n    ): Promise<XA> =>\n      new Promise((resolve, reject) =>\n        runFork(key, effect, options).addObserver((exit) => {\n          if (Exit.isSuccess(exit)) {\n            resolve(exit.value)\n          } else {\n            reject(Cause.squash(exit.cause))\n          }\n        })\n      )\n  )\n\n/**\n * @since 2.0.0\n * @categories combinators\n */\nexport const size = <K, A, E>(self: FiberMap<K, A, E>): Effect.Effect<number> =>\n  Effect.sync(() => self.state._tag === \"Closed\" ? 0 : MutableHashMap.size(self.state.backing))\n\n/**\n * Join all fibers in the FiberMap. If any of the Fiber's in the map terminate with a failure,\n * the returned Effect will terminate with the first failure that occurred.\n *\n * @since 2.0.0\n * @categories combinators\n * @example\n * ```ts\n * import { Effect, FiberMap } from \"effect\";\n *\n * Effect.gen(function* (_) {\n *   const map = yield* _(FiberMap.make());\n *   yield* _(FiberMap.set(map, \"a\", Effect.runFork(Effect.fail(\"error\"))));\n *\n *   // parent fiber will fail with \"error\"\n *   yield* _(FiberMap.join(map));\n * });\n * ```\n */\nexport const join = <K, A, E>(self: FiberMap<K, A, E>): Effect.Effect<void, E> =>\n  Deferred.await(self.deferred as Deferred.Deferred<void, E>)\n\n/**\n * Wait for the FiberMap to be empty.\n *\n * @since 3.13.0\n * @categories combinators\n */\nexport const awaitEmpty = <K, A, E>(self: FiberMap<K, A, E>): Effect.Effect<void, E> =>\n  Effect.whileLoop({\n    while: () => self.state._tag === \"Open\" && MutableHashMap.size(self.state.backing) > 0,\n    body: () => Fiber.await(Iterable.unsafeHead(self)[1]),\n    step: constVoid\n  })\n"
  },
  {
    "path": "packages/effect/src/FiberRef.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as Differ from \"./Differ.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport type * as HashMap from \"./HashMap.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport * as core from \"./internal/core.js\"\nimport * as fiberRuntime from \"./internal/fiberRuntime.js\"\nimport * as query from \"./internal/query.js\"\nimport type * as List from \"./List.js\"\nimport type * as Logger from \"./Logger.js\"\nimport type * as LogLevel from \"./LogLevel.js\"\nimport type * as LogSpan from \"./LogSpan.js\"\nimport type * as MetricLabel from \"./MetricLabel.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Request from \"./Request.js\"\nimport type * as RuntimeFlags from \"./RuntimeFlags.js\"\nimport * as Scheduler from \"./Scheduler.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Supervisor from \"./Supervisor.js\"\nimport type * as Tracer from \"./Tracer.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const FiberRefTypeId: unique symbol = core.FiberRefTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type FiberRefTypeId = typeof FiberRefTypeId\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface FiberRef<in out A> extends Effect.Effect<A>, Variance<A> {\n  /** @internal */\n  readonly initial: A\n  /** @internal */\n  diff(oldValue: A, newValue: A): unknown\n  /** @internal */\n  combine(first: unknown, second: unknown): unknown\n  /** @internal */\n  patch(patch: unknown): (oldValue: A) => A\n  /** @internal */\n  readonly fork: unknown\n  /** @internal */\n  join(oldValue: A, newValue: A): A\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: FiberRefUnify<this>\n  readonly [Unify.ignoreSymbol]?: FiberRefUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface FiberRefUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  FiberRef?: () => Extract<A[Unify.typeSymbol], FiberRef<any>>\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface FiberRefUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Variance<in out A> {\n  readonly [FiberRefTypeId]: {\n    readonly _A: Types.Invariant<A>\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A>(\n  initial: A,\n  options?: {\n    readonly fork?: ((a: A) => A) | undefined\n    readonly join?: ((left: A, right: A) => A) | undefined\n  }\n) => Effect.Effect<FiberRef<A>, never, Scope.Scope> = fiberRuntime.fiberRefMake\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const makeWith: <Value>(ref: LazyArg<FiberRef<Value>>) => Effect.Effect<FiberRef<Value>, never, Scope.Scope> =\n  fiberRuntime.fiberRefMakeWith\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const makeContext: <A>(\n  initial: Context.Context<A>\n) => Effect.Effect<FiberRef<Context.Context<A>>, never, Scope.Scope> = fiberRuntime.fiberRefMakeContext\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const makeRuntimeFlags: (\n  initial: RuntimeFlags.RuntimeFlags\n) => Effect.Effect<FiberRef<RuntimeFlags.RuntimeFlags>, never, Scope.Scope> = fiberRuntime.fiberRefMakeRuntimeFlags\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const unsafeMake: <Value>(\n  initial: Value,\n  options?: {\n    readonly fork?: ((a: Value) => Value) | undefined\n    readonly join?: ((left: Value, right: Value) => Value) | undefined\n  }\n) => FiberRef<Value> = core.fiberRefUnsafeMake\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const unsafeMakeHashSet: <A>(initial: HashSet.HashSet<A>) => FiberRef<HashSet.HashSet<A>> =\n  core.fiberRefUnsafeMakeHashSet\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const unsafeMakeContext: <A>(initial: Context.Context<A>) => FiberRef<Context.Context<A>> =\n  core.fiberRefUnsafeMakeContext\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const unsafeMakeSupervisor: (initial: Supervisor.Supervisor<any>) => FiberRef<Supervisor.Supervisor<any>> =\n  fiberRuntime.fiberRefUnsafeMakeSupervisor\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const unsafeMakePatch: <Value, Patch>(\n  initial: Value,\n  options: {\n    readonly differ: Differ.Differ<Value, Patch>\n    readonly fork: Patch\n    readonly join?: ((oldV: Value, newV: Value) => Value) | undefined\n  }\n) => FiberRef<Value> = core.fiberRefUnsafeMakePatch\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const get: <A>(self: FiberRef<A>) => Effect.Effect<A> = core.fiberRefGet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndSet: {\n  <A>(value: A): (self: FiberRef<A>) => Effect.Effect<A>\n  <A>(self: FiberRef<A>, value: A): Effect.Effect<A>\n} = core.fiberRefGetAndSet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdate: {\n  <A>(f: (a: A) => A): (self: FiberRef<A>) => Effect.Effect<A>\n  <A>(self: FiberRef<A>, f: (a: A) => A): Effect.Effect<A>\n} = core.fiberRefGetAndUpdate\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdateSome: {\n  <A>(pf: (a: A) => Option.Option<A>): (self: FiberRef<A>) => Effect.Effect<A>\n  <A>(self: FiberRef<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<A>\n} = core.fiberRefGetAndUpdateSome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getWith: {\n  <A, B, E, R>(f: (a: A) => Effect.Effect<B, E, R>): (self: FiberRef<A>) => Effect.Effect<B, E, R>\n  <A, B, E, R>(self: FiberRef<A>, f: (a: A) => Effect.Effect<B, E, R>): Effect.Effect<B, E, R>\n} = core.fiberRefGetWith\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const set: {\n  <A>(value: A): (self: FiberRef<A>) => Effect.Effect<void>\n  <A>(self: FiberRef<A>, value: A): Effect.Effect<void>\n} = core.fiberRefSet\n\nconst _delete: <A>(self: FiberRef<A>) => Effect.Effect<void> = core.fiberRefDelete\n\nexport {\n  /**\n   * @since 2.0.0\n   * @category utils\n   */\n  _delete as delete\n}\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const reset: <A>(self: FiberRef<A>) => Effect.Effect<void> = core.fiberRefReset\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modify: {\n  <A, B>(f: (a: A) => readonly [B, A]): (self: FiberRef<A>) => Effect.Effect<B>\n  <A, B>(self: FiberRef<A>, f: (a: A) => readonly [B, A]): Effect.Effect<B>\n} = core.fiberRefModify\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modifySome: <A, B>(\n  self: FiberRef<A>,\n  def: B,\n  f: (a: A) => Option.Option<readonly [B, A]>\n) => Effect.Effect<B> = core.fiberRefModifySome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const update: {\n  <A>(f: (a: A) => A): (self: FiberRef<A>) => Effect.Effect<void>\n  <A>(self: FiberRef<A>, f: (a: A) => A): Effect.Effect<void>\n} = core.fiberRefUpdate\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSome: {\n  <A>(pf: (a: A) => Option.Option<A>): (self: FiberRef<A>) => Effect.Effect<void>\n  <A>(self: FiberRef<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<void>\n} = core.fiberRefUpdateSome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateAndGet: {\n  <A>(f: (a: A) => A): (self: FiberRef<A>) => Effect.Effect<A>\n  <A>(self: FiberRef<A>, f: (a: A) => A): Effect.Effect<A>\n} = core.fiberRefUpdateAndGet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSomeAndGet: {\n  <A>(pf: (a: A) => Option.Option<A>): (self: FiberRef<A>) => Effect.Effect<A>\n  <A>(self: FiberRef<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<A>\n} = core.fiberRefUpdateSomeAndGet\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentConcurrency: FiberRef<number | \"unbounded\"> = core.currentConcurrency\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentRequestBatchingEnabled: FiberRef<boolean> = core.currentRequestBatching\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentRequestCache: FiberRef<Request.Cache> = query.currentCache as any\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentRequestCacheEnabled: FiberRef<boolean> = query.currentCacheEnabled\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentContext: FiberRef<Context.Context<never>> = core.currentContext\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentSchedulingPriority: FiberRef<number> = core.currentSchedulingPriority\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentMaxOpsBeforeYield: FiberRef<number> = core.currentMaxOpsBeforeYield\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const unhandledErrorLogLevel: FiberRef<Option.Option<LogLevel.LogLevel>> = core.currentUnhandledErrorLogLevel\n\n/**\n * @since 3.17.0\n * @category fiberRefs\n */\nexport const versionMismatchErrorLogLevel: FiberRef<Option.Option<LogLevel.LogLevel>> =\n  core.currentVersionMismatchErrorLogLevel\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentLogAnnotations: FiberRef<HashMap.HashMap<string, unknown>> = core.currentLogAnnotations\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentLoggers: FiberRef<HashSet.HashSet<Logger.Logger<unknown, any>>> = fiberRuntime.currentLoggers\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentLogLevel: FiberRef<LogLevel.LogLevel> = core.currentLogLevel\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentMinimumLogLevel: FiberRef<LogLevel.LogLevel> = fiberRuntime.currentMinimumLogLevel\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentLogSpan: FiberRef<List.List<LogSpan.LogSpan>> = core.currentLogSpan\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentRuntimeFlags: FiberRef<RuntimeFlags.RuntimeFlags> = fiberRuntime.currentRuntimeFlags\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentScheduler: FiberRef<Scheduler.Scheduler> = Scheduler.currentScheduler\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentSupervisor: FiberRef<Supervisor.Supervisor<any>> = fiberRuntime.currentSupervisor\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentMetricLabels: FiberRef<ReadonlyArray<MetricLabel.MetricLabel>> = core.currentMetricLabels\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentTracerEnabled: FiberRef<boolean> = core.currentTracerEnabled\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentTracerTimingEnabled: FiberRef<boolean> = core.currentTracerTimingEnabled\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentTracerSpanAnnotations: FiberRef<HashMap.HashMap<string, unknown>> =\n  core.currentTracerSpanAnnotations\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentTracerSpanLinks: FiberRef<Chunk.Chunk<Tracer.SpanLink>> = core.currentTracerSpanLinks\n\n/**\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const interruptedCause: FiberRef<Cause.Cause<never>> = core.currentInterruptedCause\n"
  },
  {
    "path": "packages/effect/src/FiberRefs.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Arr from \"./Array.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport type * as FiberRef from \"./FiberRef.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport * as internal from \"./internal/fiberRefs.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const FiberRefsSym: unique symbol = internal.FiberRefsSym\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type FiberRefsSym = typeof FiberRefsSym\n\n/**\n * `FiberRefs` is a data type that represents a collection of `FiberRef` values.\n *\n * This allows safely propagating `FiberRef` values across fiber boundaries, for\n * example between an asynchronous producer and consumer.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface FiberRefs extends Pipeable {\n  readonly [FiberRefsSym]: FiberRefsSym\n  readonly locals: Map<FiberRef.FiberRef<any>, Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, any]>>\n}\n\nconst delete_: {\n  <A>(fiberRef: FiberRef.FiberRef<A>): (self: FiberRefs) => FiberRefs\n  <A>(self: FiberRefs, fiberRef: FiberRef.FiberRef<A>): FiberRefs\n} = internal.delete_\n\nexport {\n  /**\n   * Deletes the specified `FiberRef` from the `FibterRefs`.\n   *\n   * @since 2.0.0\n   * @category utils\n   */\n  delete_ as delete\n}\n\n/**\n * Returns a set of each `FiberRef` in this collection.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const fiberRefs: (self: FiberRefs) => HashSet.HashSet<FiberRef.FiberRef<any>> = internal.fiberRefs\n\n/**\n * Forks this collection of fiber refs as the specified child fiber id. This\n * will potentially modify the value of the fiber refs, as determined by the\n * individual fiber refs that make up the collection.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const forkAs: {\n  (childId: FiberId.Single): (self: FiberRefs) => FiberRefs\n  (self: FiberRefs, childId: FiberId.Single): FiberRefs\n} = internal.forkAs\n\n/**\n * Gets the value of the specified `FiberRef` in this collection of `FiberRef`\n * values if it exists or `None` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const get: {\n  <A>(fiberRef: FiberRef.FiberRef<A>): (self: FiberRefs) => Option.Option<A>\n  <A>(self: FiberRefs, fiberRef: FiberRef.FiberRef<A>): Option.Option<A>\n} = internal.get\n\n/**\n * Gets the value of the specified `FiberRef` in this collection of `FiberRef`\n * values if it exists or the `initial` value of the `FiberRef` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const getOrDefault: {\n  <A>(fiberRef: FiberRef.FiberRef<A>): (self: FiberRefs) => A\n  <A>(self: FiberRefs, fiberRef: FiberRef.FiberRef<A>): A\n} = internal.getOrDefault\n\n/**\n * Joins this collection of fiber refs to the specified collection, as the\n * specified fiber id. This will perform diffing and merging to ensure\n * preservation of maximum information from both child and parent refs.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const joinAs: {\n  (fiberId: FiberId.Single, that: FiberRefs): (self: FiberRefs) => FiberRefs\n  (self: FiberRefs, fiberId: FiberId.Single, that: FiberRefs): FiberRefs\n} = internal.joinAs\n\n/**\n * Set each ref to either its value or its default.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const setAll: (self: FiberRefs) => Effect.Effect<void> = internal.setAll\n\n/**\n * Updates the value of the specified `FiberRef` using the provided `FiberId`\n *\n * @since 2.0.0\n * @category utils\n */\nexport const updateAs: {\n  <A>(\n    options: {\n      readonly fiberId: FiberId.Single\n      readonly fiberRef: FiberRef.FiberRef<A>\n      readonly value: A\n    }\n  ): (self: FiberRefs) => FiberRefs\n  <A>(\n    self: FiberRefs,\n    options: {\n      readonly fiberId: FiberId.Single\n      readonly fiberRef: FiberRef.FiberRef<A>\n      readonly value: A\n    }\n  ): FiberRefs\n} = internal.updateAs\n\n/**\n * Updates the values of the specified `FiberRef` & value pairs using the provided `FiberId`\n *\n * @since 2.0.0\n * @category utils\n */\nexport const updateManyAs: {\n  (\n    options: {\n      readonly forkAs?: FiberId.Single | undefined\n      readonly entries: readonly [\n        readonly [\n          FiberRef.FiberRef<any>,\n          readonly [readonly [FiberId.Single, any], ...Array<readonly [FiberId.Single, any]>]\n        ],\n        ...Array<\n          readonly [\n            FiberRef.FiberRef<any>,\n            readonly [readonly [FiberId.Single, any], ...Array<readonly [FiberId.Single, any]>]\n          ]\n        >\n      ]\n    }\n  ): (self: FiberRefs) => FiberRefs\n  (\n    self: FiberRefs,\n    options: {\n      readonly forkAs?: FiberId.Single | undefined\n      readonly entries: readonly [\n        readonly [\n          FiberRef.FiberRef<any>,\n          readonly [readonly [FiberId.Single, any], ...Array<readonly [FiberId.Single, any]>]\n        ],\n        ...Array<\n          readonly [\n            FiberRef.FiberRef<any>,\n            readonly [readonly [FiberId.Single, any], ...Array<readonly [FiberId.Single, any]>]\n          ]\n        >\n      ]\n    }\n  ): FiberRefs\n} = internal.updateManyAs\n\n/**\n * Note: it will not copy the provided Map, make sure to provide a fresh one.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeMake: (\n  fiberRefLocals: Map<FiberRef.FiberRef<any>, Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, any]>>\n) => FiberRefs = internal.unsafeMake\n\n/**\n * The empty collection of `FiberRef` values.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const empty: () => FiberRefs = internal.empty\n"
  },
  {
    "path": "packages/effect/src/FiberRefsPatch.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as FiberId from \"./FiberId.js\"\nimport type * as FiberRef from \"./FiberRef.js\"\nimport type * as FiberRefs from \"./FiberRefs.js\"\nimport * as internal from \"./internal/fiberRefs/patch.js\"\n\n/**\n * A `FiberRefsPatch` captures the changes in `FiberRef` values made by a single\n * fiber as a value. This allows fibers to apply the changes made by a workflow\n * without inheriting all the `FiberRef` values of the fiber that executed the\n * workflow.\n *\n * @since 2.0.0\n * @category models\n */\nexport type FiberRefsPatch = Empty | Add | Remove | Update | AndThen\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Empty {\n  readonly _tag: \"Empty\"\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Add {\n  readonly _tag: \"Add\"\n  readonly fiberRef: FiberRef.FiberRef<unknown>\n  readonly value: unknown\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Remove {\n  readonly _tag: \"Remove\"\n  readonly fiberRef: FiberRef.FiberRef<unknown>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Update {\n  readonly _tag: \"Update\"\n  readonly fiberRef: FiberRef.FiberRef<unknown>\n  readonly patch: unknown\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface AndThen {\n  readonly _tag: \"AndThen\"\n  readonly first: FiberRefsPatch\n  readonly second: FiberRefsPatch\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: FiberRefsPatch = internal.empty\n\n/**\n * Constructs a patch that describes the changes between the specified\n * collections of `FiberRef`\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const diff: (oldValue: FiberRefs.FiberRefs, newValue: FiberRefs.FiberRefs) => FiberRefsPatch = internal.diff\n\n/**\n * Combines this patch and the specified patch to create a new patch that\n * describes applying the changes from this patch and the specified patch\n * sequentially.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const combine: {\n  (that: FiberRefsPatch): (self: FiberRefsPatch) => FiberRefsPatch\n  (self: FiberRefsPatch, that: FiberRefsPatch): FiberRefsPatch\n} = internal.combine\n\n/**\n * Applies the changes described by this patch to the specified collection\n * of `FiberRef` values.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const patch: {\n  (fiberId: FiberId.Runtime, oldValue: FiberRefs.FiberRefs): (self: FiberRefsPatch) => FiberRefs.FiberRefs\n  (self: FiberRefsPatch, fiberId: FiberId.Runtime, oldValue: FiberRefs.FiberRefs): FiberRefs.FiberRefs\n} = internal.patch\n"
  },
  {
    "path": "packages/effect/src/FiberSet.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Cause from \"./Cause.js\"\nimport * as Deferred from \"./Deferred.js\"\nimport * as Effect from \"./Effect.js\"\nimport * as Exit from \"./Exit.js\"\nimport * as Fiber from \"./Fiber.js\"\nimport * as FiberId from \"./FiberId.js\"\nimport { constFalse, constVoid, dual } from \"./Function.js\"\nimport * as HashSet from \"./HashSet.js\"\nimport * as Inspectable from \"./Inspectable.js\"\nimport * as Iterable from \"./Iterable.js\"\nimport { type Pipeable, pipeArguments } from \"./Pipeable.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport * as Runtime from \"./Runtime.js\"\nimport type * as Scope from \"./Scope.js\"\n\n/**\n * @since 2.0.0\n * @categories type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/FiberSet\")\n\n/**\n * @since 2.0.0\n * @categories type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @categories models\n */\nexport interface FiberSet<out A = unknown, out E = unknown>\n  extends Pipeable, Inspectable.Inspectable, Iterable<Fiber.RuntimeFiber<A, E>>\n{\n  readonly [TypeId]: TypeId\n  readonly deferred: Deferred.Deferred<void, unknown>\n  /** @internal */\n  state: {\n    readonly _tag: \"Open\"\n    readonly backing: Set<Fiber.RuntimeFiber<A, E>>\n  } | {\n    readonly _tag: \"Closed\"\n  }\n}\n\n/**\n * @since 2.0.0\n * @categories refinements\n */\nexport const isFiberSet = (u: unknown): u is FiberSet<unknown, unknown> => Predicate.hasProperty(u, TypeId)\n\nconst Proto = {\n  [TypeId]: TypeId,\n  [Symbol.iterator](this: FiberSet<unknown, unknown>) {\n    if (this.state._tag === \"Closed\") {\n      return Iterable.empty()\n    }\n    return this.state.backing[Symbol.iterator]()\n  },\n  toString(this: FiberSet<unknown, unknown>) {\n    return Inspectable.format(this.toJSON())\n  },\n  toJSON(this: FiberSet<unknown, unknown>) {\n    return {\n      _id: \"FiberMap\",\n      state: this.state\n    }\n  },\n  [Inspectable.NodeInspectSymbol](this: FiberSet<unknown, unknown>) {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst unsafeMake = <A, E>(\n  backing: Set<Fiber.RuntimeFiber<A, E>>,\n  deferred: Deferred.Deferred<void, unknown>\n): FiberSet<A, E> => {\n  const self = Object.create(Proto)\n  self.state = { _tag: \"Open\", backing }\n  self.deferred = deferred\n  return self\n}\n\n/**\n * A FiberSet can be used to store a collection of fibers.\n * When the associated Scope is closed, all fibers in the set will be interrupted.\n *\n * You can add fibers to the set using `FiberSet.add` or `FiberSet.run`, and the fibers will\n * be automatically removed from the FiberSet when they complete.\n *\n * @example\n * ```ts\n * import { Effect, FiberSet } from \"effect\"\n *\n * Effect.gen(function*() {\n *   const set = yield* FiberSet.make()\n *\n *   // run some effects and add the fibers to the set\n *   yield* FiberSet.run(set, Effect.never)\n *   yield* FiberSet.run(set, Effect.never)\n *\n *   yield* Effect.sleep(1000)\n * }).pipe(\n *   Effect.scoped // The fibers will be interrupted when the scope is closed\n * )\n * ```\n *\n * @since 2.0.0\n * @categories constructors\n */\nexport const make = <A = unknown, E = unknown>(): Effect.Effect<FiberSet<A, E>, never, Scope.Scope> =>\n  Effect.acquireRelease(\n    Effect.map(Deferred.make<void, unknown>(), (deferred) => unsafeMake(new Set(), deferred)),\n    (set) =>\n      Effect.withFiberRuntime((parent) => {\n        const state = set.state\n        if (state._tag === \"Closed\") return Effect.void\n        set.state = { _tag: \"Closed\" }\n        const fibers = state.backing\n        return Fiber.interruptAllAs(fibers, FiberId.combine(parent.id(), internalFiberId)).pipe(\n          Effect.intoDeferred(set.deferred)\n        )\n      })\n  )\n\n/**\n * Create an Effect run function that is backed by a FiberSet.\n *\n * @since 2.0.0\n * @categories constructors\n */\nexport const makeRuntime = <R = never, A = unknown, E = unknown>(): Effect.Effect<\n  <XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>,\n    options?: Runtime.RunForkOptions | undefined\n  ) => Fiber.RuntimeFiber<XA, XE>,\n  never,\n  Scope.Scope | R\n> =>\n  Effect.flatMap(\n    make<A, E>(),\n    (self) => runtime(self)<R>()\n  )\n\n/**\n * Create an Effect run function that is backed by a FiberSet.\n *\n * @since 3.13.0\n * @categories constructors\n */\nexport const makeRuntimePromise = <R = never, A = unknown, E = unknown>(): Effect.Effect<\n  <XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>,\n    options?: Runtime.RunForkOptions | undefined\n  ) => Promise<XA>,\n  never,\n  Scope.Scope | R\n> =>\n  Effect.flatMap(\n    make<A, E>(),\n    (self) => runtimePromise(self)<R>()\n  )\n\nconst internalFiberIdId = -1\nconst internalFiberId = FiberId.make(internalFiberIdId, 0)\nconst isInternalInterruption = Cause.reduceWithContext(undefined, {\n  emptyCase: constFalse,\n  failCase: constFalse,\n  dieCase: constFalse,\n  interruptCase: (_, fiberId) => HashSet.has(FiberId.ids(fiberId), internalFiberIdId),\n  sequentialCase: (_, left, right) => left || right,\n  parallelCase: (_, left, right) => left || right\n})\n\n/**\n * Add a fiber to the FiberSet. When the fiber completes, it will be removed.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const unsafeAdd: {\n  <A, E, XE extends E, XA extends A>(\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly interruptAs?: FiberId.FiberId | undefined\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): (self: FiberSet<A, E>) => void\n  <A, E, XE extends E, XA extends A>(\n    self: FiberSet<A, E>,\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly interruptAs?: FiberId.FiberId | undefined\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): void\n} = dual((args) => isFiberSet(args[0]), <A, E, XE extends E, XA extends A>(\n  self: FiberSet<A, E>,\n  fiber: Fiber.RuntimeFiber<XA, XE>,\n  options?: {\n    readonly interruptAs?: FiberId.FiberId | undefined\n    readonly propagateInterruption?: boolean | undefined\n  } | undefined\n): void => {\n  if (self.state._tag === \"Closed\") {\n    fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId))\n    return\n  } else if (self.state.backing.has(fiber)) {\n    return\n  }\n  self.state.backing.add(fiber)\n  fiber.addObserver((exit) => {\n    if (self.state._tag === \"Closed\") {\n      return\n    }\n    self.state.backing.delete(fiber)\n    if (\n      Exit.isFailure(exit) &&\n      (\n        options?.propagateInterruption === true ?\n          !isInternalInterruption(exit.cause) :\n          !Cause.isInterruptedOnly(exit.cause)\n      )\n    ) {\n      Deferred.unsafeDone(self.deferred, exit as any)\n    }\n  })\n})\n\n/**\n * Add a fiber to the FiberSet. When the fiber completes, it will be removed.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const add: {\n  <A, E, XE extends E, XA extends A>(\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): (self: FiberSet<A, E>) => Effect.Effect<void>\n  <A, E, XE extends E, XA extends A>(\n    self: FiberSet<A, E>,\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): Effect.Effect<void>\n} = dual(\n  (args) => isFiberSet(args[0]),\n  <A, E, XE extends E, XA extends A>(\n    self: FiberSet<A, E>,\n    fiber: Fiber.RuntimeFiber<XA, XE>,\n    options?: {\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): Effect.Effect<void> =>\n    Effect.fiberIdWith((fiberId) =>\n      Effect.sync(() =>\n        unsafeAdd(self, fiber, {\n          ...options,\n          interruptAs: fiberId\n        })\n      )\n    )\n)\n\n/**\n * @since 2.0.0\n * @categories combinators\n */\nexport const clear = <A, E>(self: FiberSet<A, E>): Effect.Effect<void> =>\n  Effect.withFiberRuntime((clearFiber) => {\n    if (self.state._tag === \"Closed\") {\n      return Effect.void\n    }\n    return Effect.forEach(self.state.backing, (fiber) =>\n      // will be removed by the observer\n      Fiber.interruptAs(fiber, FiberId.combine(clearFiber.id(), internalFiberId)))\n  })\n\nconst constInterruptedFiber = (function() {\n  let fiber: Fiber.RuntimeFiber<never, never> | undefined = undefined\n  return () => {\n    if (fiber === undefined) {\n      fiber = Effect.runFork(Effect.interrupt)\n    }\n    return fiber\n  }\n})()\n\n/**\n * Fork an Effect and add the forked fiber to the FiberSet.\n * When the fiber completes, it will be removed from the FiberSet.\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const run: {\n  <A, E>(\n    self: FiberSet<A, E>,\n    options?: {\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): <R, XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>\n  ) => Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R>\n  <A, E, R, XE extends E, XA extends A>(\n    self: FiberSet<A, E>,\n    effect: Effect.Effect<XA, XE, R>,\n    options?: {\n      readonly propagateInterruption?: boolean | undefined\n    } | undefined\n  ): Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R>\n} = function() {\n  const self = arguments[0] as FiberSet<any, any>\n  if (!Effect.isEffect(arguments[1])) {\n    const options = arguments[1]\n    return (effect: Effect.Effect<any, any, any>) => runImpl(self, effect, options)\n  }\n  return runImpl(self, arguments[1], arguments[2]) as any\n}\n\nconst runImpl = <A, E, R, XE extends E, XA extends A>(\n  self: FiberSet<A, E>,\n  effect: Effect.Effect<XA, XE, R>,\n  options?: {\n    readonly propagateInterruption?: boolean | undefined\n  }\n): Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R> =>\n  Effect.fiberIdWith((fiberId) => {\n    if (self.state._tag === \"Closed\") {\n      return Effect.sync(constInterruptedFiber)\n    }\n    return Effect.tap(\n      Effect.forkDaemon(effect),\n      (fiber) =>\n        unsafeAdd(self, fiber, {\n          ...options,\n          interruptAs: fiberId\n        })\n    )\n  })\n\n/**\n * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberSet.\n *\n * @example\n * ```ts\n * import { Context, Effect, FiberSet } from \"effect\"\n *\n * interface Users {\n *   readonly _: unique symbol\n * }\n * const Users = Context.GenericTag<Users, {\n *    getAll: Effect.Effect<Array<unknown>>\n * }>(\"Users\")\n *\n * Effect.gen(function*() {\n *   const set = yield* FiberSet.make()\n *   const run = yield* FiberSet.runtime(set)<Users>()\n *\n *   // run some effects and add the fibers to the set\n *   run(Effect.andThen(Users, _ => _.getAll))\n * }).pipe(\n *   Effect.scoped // The fibers will be interrupted when the scope is closed\n * )\n * ```\n *\n * @since 2.0.0\n * @categories combinators\n */\nexport const runtime: <A, E>(\n  self: FiberSet<A, E>\n) => <R = never>() => Effect.Effect<\n  <XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>,\n    options?:\n      | Runtime.RunForkOptions & { readonly propagateInterruption?: boolean | undefined }\n      | undefined\n  ) => Fiber.RuntimeFiber<XA, XE>,\n  never,\n  R\n> = <A, E>(self: FiberSet<A, E>) => <R>() =>\n  Effect.map(\n    Effect.runtime<R>(),\n    (runtime) => {\n      const runFork = Runtime.runFork(runtime)\n      return <XE extends E, XA extends A>(\n        effect: Effect.Effect<XA, XE, R>,\n        options?:\n          | Runtime.RunForkOptions & { readonly propagateInterruption?: boolean | undefined }\n          | undefined\n      ) => {\n        if (self.state._tag === \"Closed\") {\n          return constInterruptedFiber()\n        }\n        const fiber = runFork(effect, options)\n        unsafeAdd(self, fiber)\n        return fiber\n      }\n    }\n  )\n\n/**\n * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberSet.\n *\n * The returned run function will return Promise's.\n *\n * @since 3.13.0\n * @categories combinators\n */\nexport const runtimePromise = <A, E>(self: FiberSet<A, E>): <R = never>() => Effect.Effect<\n  <XE extends E, XA extends A>(\n    effect: Effect.Effect<XA, XE, R>,\n    options?:\n      | Runtime.RunForkOptions & { readonly propagateInterruption?: boolean | undefined }\n      | undefined\n  ) => Promise<XA>,\n  never,\n  R\n> =>\n<R>() =>\n  Effect.map(\n    runtime(self)<R>(),\n    (runFork) =>\n    <XE extends E, XA extends A>(\n      effect: Effect.Effect<XA, XE, R>,\n      options?:\n        | Runtime.RunForkOptions & { readonly propagateInterruption?: boolean | undefined }\n        | undefined\n    ): Promise<XA> =>\n      new Promise((resolve, reject) =>\n        runFork(effect, options).addObserver((exit) => {\n          if (Exit.isSuccess(exit)) {\n            resolve(exit.value)\n          } else {\n            reject(Cause.squash(exit.cause))\n          }\n        })\n      )\n  )\n\n/**\n * @since 2.0.0\n * @categories combinators\n */\nexport const size = <A, E>(self: FiberSet<A, E>): Effect.Effect<number> =>\n  Effect.sync(() => self.state._tag === \"Closed\" ? 0 : self.state.backing.size)\n\n/**\n * Join all fibers in the FiberSet. If any of the Fiber's in the set terminate with a failure,\n * the returned Effect will terminate with the first failure that occurred.\n *\n * @since 2.0.0\n * @categories combinators\n * @example\n * ```ts\n * import { Effect, FiberSet } from \"effect\";\n *\n * Effect.gen(function* (_) {\n *   const set = yield* _(FiberSet.make());\n *   yield* _(FiberSet.add(set, Effect.runFork(Effect.fail(\"error\"))));\n *\n *   // parent fiber will fail with \"error\"\n *   yield* _(FiberSet.join(set));\n * });\n * ```\n */\nexport const join = <A, E>(self: FiberSet<A, E>): Effect.Effect<void, E> =>\n  Deferred.await(self.deferred as Deferred.Deferred<void, E>)\n\n/**\n * Wait until the fiber set is empty.\n *\n * @since 3.13.0\n * @categories combinators\n */\nexport const awaitEmpty = <A, E>(self: FiberSet<A, E>): Effect.Effect<void> =>\n  Effect.whileLoop({\n    while: () => self.state._tag === \"Open\" && self.state.backing.size > 0,\n    body: () => Fiber.await(Iterable.unsafeHead(self)),\n    step: constVoid\n  })\n"
  },
  {
    "path": "packages/effect/src/FiberStatus.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Equal from \"./Equal.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport * as internal from \"./internal/fiberStatus.js\"\nimport type * as RuntimeFlags from \"./RuntimeFlags.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const FiberStatusTypeId: unique symbol = internal.FiberStatusTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type FiberStatusTypeId = typeof FiberStatusTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type FiberStatus = Done | Running | Suspended\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Done extends Equal.Equal {\n  readonly _tag: \"Done\"\n  readonly [FiberStatusTypeId]: FiberStatusTypeId\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Running extends Equal.Equal {\n  readonly _tag: \"Running\"\n  readonly [FiberStatusTypeId]: FiberStatusTypeId\n  readonly runtimeFlags: RuntimeFlags.RuntimeFlags\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Suspended extends Equal.Equal {\n  readonly _tag: \"Suspended\"\n  readonly [FiberStatusTypeId]: FiberStatusTypeId\n  readonly runtimeFlags: RuntimeFlags.RuntimeFlags\n  readonly blockingOn: FiberId.FiberId\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const done: FiberStatus = internal.done\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const running: (runtimeFlags: RuntimeFlags.RuntimeFlags) => FiberStatus = internal.running\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const suspended: (runtimeFlags: RuntimeFlags.RuntimeFlags, blockingOn: FiberId.FiberId) => FiberStatus =\n  internal.suspended\n\n/**\n * Returns `true` if the specified value is a `FiberStatus`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isFiberStatus: (u: unknown) => u is FiberStatus = internal.isFiberStatus\n\n/**\n * Returns `true` if the specified `FiberStatus` is `Done`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isDone: (self: FiberStatus) => self is Done = internal.isDone\n\n/**\n * Returns `true` if the specified `FiberStatus` is `Running`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isRunning: (self: FiberStatus) => self is Running = internal.isRunning\n\n/**\n * Returns `true` if the specified `FiberStatus` is `Suspended`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isSuspended: (self: FiberStatus) => self is Suspended = internal.isSuspended\n"
  },
  {
    "path": "packages/effect/src/Function.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { TypeLambda } from \"./HKT.js\"\n\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface FunctionTypeLambda extends TypeLambda {\n  readonly type: (a: this[\"In\"]) => this[\"Target\"]\n}\n\n/**\n * Tests if a value is a `function`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isFunction } from \"effect/Predicate\"\n *\n * assert.deepStrictEqual(isFunction(isFunction), true)\n * assert.deepStrictEqual(isFunction(\"function\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isFunction = (input: unknown): input is Function => typeof input === \"function\"\n\n/**\n * Creates a function that can be used in a data-last (aka `pipe`able) or\n * data-first style.\n *\n * The first parameter to `dual` is either the arity of the uncurried function\n * or a predicate that determines if the function is being used in a data-first\n * or data-last style.\n *\n * Using the arity is the most common use case, but there are some cases where\n * you may want to use a predicate. For example, if you have a function that\n * takes an optional argument, you can use a predicate to determine if the\n * function is being used in a data-first or data-last style.\n *\n * You can pass either the arity of the uncurried function or a predicate\n * which determines if the function is being used in a data-first or\n * data-last style.\n *\n * **Example** (Using arity to determine data-first or data-last style)\n *\n * ```ts\n * import { dual, pipe } from \"effect/Function\"\n *\n * const sum = dual<\n *   (that: number) => (self: number) => number,\n *   (self: number, that: number) => number\n * >(2, (self, that) => self + that)\n *\n * console.log(sum(2, 3)) // 5\n * console.log(pipe(2, sum(3))) // 5\n * ```\n *\n * **Example** (Using call signatures to define the overloads)\n *\n * ```ts\n * import { dual, pipe } from \"effect/Function\"\n *\n * const sum: {\n *   (that: number): (self: number) => number\n *   (self: number, that: number): number\n * } = dual(2, (self: number, that: number): number => self + that)\n *\n * console.log(sum(2, 3)) // 5\n * console.log(pipe(2, sum(3))) // 5\n * ```\n *\n * **Example** (Using a predicate to determine data-first or data-last style)\n *\n * ```ts\n * import { dual, pipe } from \"effect/Function\"\n *\n * const sum = dual<\n *   (that: number) => (self: number) => number,\n *   (self: number, that: number) => number\n * >(\n *   (args) => args.length === 2,\n *   (self, that) => self + that\n * )\n *\n * console.log(sum(2, 3)) // 5\n * console.log(pipe(2, sum(3))) // 5\n * ```\n *\n * @since 2.0.0\n */\nexport const dual: {\n  <DataLast extends (...args: Array<any>) => any, DataFirst extends (...args: Array<any>) => any>(\n    arity: Parameters<DataFirst>[\"length\"],\n    body: DataFirst\n  ): DataLast & DataFirst\n  <DataLast extends (...args: Array<any>) => any, DataFirst extends (...args: Array<any>) => any>(\n    isDataFirst: (args: IArguments) => boolean,\n    body: DataFirst\n  ): DataLast & DataFirst\n} = function(arity, body) {\n  if (typeof arity === \"function\") {\n    return function() {\n      if (arity(arguments)) {\n        // @ts-expect-error\n        return body.apply(this, arguments)\n      }\n      return ((self: any) => body(self, ...arguments)) as any\n    }\n  }\n\n  switch (arity) {\n    case 0:\n    case 1:\n      throw new RangeError(`Invalid arity ${arity}`)\n\n    case 2:\n      return function(a, b) {\n        if (arguments.length >= 2) {\n          return body(a, b)\n        }\n        return function(self: any) {\n          return body(self, a)\n        }\n      }\n\n    case 3:\n      return function(a, b, c) {\n        if (arguments.length >= 3) {\n          return body(a, b, c)\n        }\n        return function(self: any) {\n          return body(self, a, b)\n        }\n      }\n\n    case 4:\n      return function(a, b, c, d) {\n        if (arguments.length >= 4) {\n          return body(a, b, c, d)\n        }\n        return function(self: any) {\n          return body(self, a, b, c)\n        }\n      }\n\n    case 5:\n      return function(a, b, c, d, e) {\n        if (arguments.length >= 5) {\n          return body(a, b, c, d, e)\n        }\n        return function(self: any) {\n          return body(self, a, b, c, d)\n        }\n      }\n\n    default:\n      return function() {\n        if (arguments.length >= arity) {\n          // @ts-expect-error\n          return body.apply(this, arguments)\n        }\n        const args = arguments\n        return function(self: any) {\n          return body(self, ...args)\n        }\n      }\n  }\n}\n/**\n * Apply a function to given values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, apply } from \"effect/Function\"\n * import { length } from \"effect/String\"\n *\n * assert.deepStrictEqual(pipe(length, apply(\"hello\")), 5)\n * ```\n *\n * @since 2.0.0\n */\nexport const apply = <A extends ReadonlyArray<unknown>>(...a: A) => <B>(self: (...a: A) => B): B => self(...a)\n\n/**\n * A lazy argument.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { LazyArg, constant } from \"effect/Function\"\n *\n * const constNull: LazyArg<null> = constant(null)\n * ```\n *\n * @since 2.0.0\n */\nexport interface LazyArg<A> {\n  (): A\n}\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { FunctionN } from \"effect/Function\"\n *\n * const sum: FunctionN<[number, number], number> = (a, b) => a + b\n * ```\n *\n * @since 2.0.0\n */\nexport interface FunctionN<A extends ReadonlyArray<unknown>, B> {\n  (...args: A): B\n}\n\n/**\n * The identity function, i.e. A function that returns its input argument.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { identity } from \"effect/Function\"\n *\n * assert.deepStrictEqual(identity(5), 5)\n * ```\n *\n * @since 2.0.0\n */\nexport const identity = <A>(a: A): A => a\n\n/**\n * A function that ensures that the type of an expression matches some type,\n * without changing the resulting type of that expression.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { satisfies } from \"effect/Function\"\n *\n * const test1 = satisfies<number>()(5 as const)\n *     //^? const test: 5\n *     // @ts-expect-error\n * const test2 = satisfies<string>()(5)\n *     //^? Argument of type 'number' is not assignable to parameter of type 'string'\n *\n * assert.deepStrictEqual(satisfies<number>()(5), 5)\n * ```\n *\n * @since 2.0.0\n */\nexport const satisfies = <A>() => <B extends A>(b: B) => b\n\n/**\n * Casts the result to the specified type.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { unsafeCoerce, identity } from \"effect/Function\"\n *\n * assert.deepStrictEqual(unsafeCoerce, identity)\n * ```\n *\n * @since 2.0.0\n */\nexport const unsafeCoerce: <A, B>(a: A) => B = identity as any\n\n/**\n * Creates a constant value that never changes.\n *\n * This is useful when you want to pass a value to a higher-order function (a function that takes another function as its argument)\n * and want that inner function to always use the same value, no matter how many times it is called.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { constant } from \"effect/Function\"\n *\n * const constNull = constant(null)\n *\n * assert.deepStrictEqual(constNull(), null)\n * assert.deepStrictEqual(constNull(), null)\n * ```\n *\n * @since 2.0.0\n */\nexport const constant = <A>(value: A): LazyArg<A> => () => value\n\n/**\n * A thunk that returns always `true`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { constTrue } from \"effect/Function\"\n *\n * assert.deepStrictEqual(constTrue(), true)\n * ```\n *\n * @since 2.0.0\n */\nexport const constTrue: LazyArg<boolean> = constant(true)\n\n/**\n * A thunk that returns always `false`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { constFalse } from \"effect/Function\"\n *\n * assert.deepStrictEqual(constFalse(), false)\n * ```\n *\n * @since 2.0.0\n */\nexport const constFalse: LazyArg<boolean> = constant(false)\n\n/**\n * A thunk that returns always `null`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { constNull } from \"effect/Function\"\n *\n * assert.deepStrictEqual(constNull(), null)\n * ```\n *\n * @since 2.0.0\n */\nexport const constNull: LazyArg<null> = constant(null)\n\n/**\n * A thunk that returns always `undefined`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { constUndefined } from \"effect/Function\"\n *\n * assert.deepStrictEqual(constUndefined(), undefined)\n * ```\n *\n * @since 2.0.0\n */\nexport const constUndefined: LazyArg<undefined> = constant(undefined)\n\n/**\n * A thunk that returns always `void`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { constVoid } from \"effect/Function\"\n *\n * assert.deepStrictEqual(constVoid(), undefined)\n * ```\n *\n * @since 2.0.0\n */\nexport const constVoid: LazyArg<void> = constUndefined\n\n/**\n * Reverses the order of arguments for a curried function.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { flip } from \"effect/Function\"\n *\n * const f = (a: number) => (b: string) => a - b.length\n *\n * assert.deepStrictEqual(flip(f)('aaa')(2), -1)\n * ```\n *\n * @since 2.0.0\n */\nexport const flip = <A extends Array<unknown>, B extends Array<unknown>, C>(\n  f: (...a: A) => (...b: B) => C\n): (...b: B) => (...a: A) => C =>\n(...b) =>\n(...a) => f(...a)(...b)\n\n/**\n * Composes two functions, `ab` and `bc` into a single function that takes in an argument `a` of type `A` and returns a result of type `C`.\n * The result is obtained by first applying the `ab` function to `a` and then applying the `bc` function to the result of `ab`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { compose } from \"effect/Function\"\n *\n * const increment = (n: number) => n + 1;\n * const square = (n: number) => n * n;\n *\n * assert.strictEqual(compose(increment, square)(2), 9);\n * ```\n *\n * @since 2.0.0\n */\nexport const compose: {\n  <B, C>(bc: (b: B) => C): <A>(self: (a: A) => B) => (a: A) => C\n  <A, B, C>(self: (a: A) => B, bc: (b: B) => C): (a: A) => C\n} = dual(2, <A, B, C>(ab: (a: A) => B, bc: (b: B) => C): (a: A) => C => (a) => bc(ab(a)))\n\n/**\n * The `absurd` function is a stub for cases where a value of type `never` is encountered in your code,\n * meaning that it should be impossible for this code to be executed.\n *\n * This function is particularly useful when it's necessary to specify that certain cases are impossible.\n *\n * @since 2.0.0\n */\nexport const absurd = <A>(_: never): A => {\n  throw new Error(\"Called `absurd` function which should be uncallable\")\n}\n\n/**\n * Creates a   version of this function: instead of `n` arguments, it accepts a single tuple argument.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { tupled } from \"effect/Function\"\n *\n * const sumTupled = tupled((x: number, y: number): number => x + y)\n *\n * assert.deepStrictEqual(sumTupled([1, 2]), 3)\n * ```\n *\n * @since 2.0.0\n */\nexport const tupled = <A extends ReadonlyArray<unknown>, B>(f: (...a: A) => B): (a: A) => B => (a) => f(...a)\n\n/**\n * Inverse function of `tupled`\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { untupled } from \"effect/Function\"\n *\n * const getFirst = untupled(<A, B>(tuple: [A, B]): A => tuple[0])\n *\n * assert.deepStrictEqual(getFirst(1, 2), 1)\n * ```\n *\n * @since 2.0.0\n */\nexport const untupled = <A extends ReadonlyArray<unknown>, B>(f: (a: A) => B): (...a: A) => B => (...a) => f(a)\n\n/**\n * Pipes the value of an expression into a pipeline of functions.\n *\n * **Details**\n *\n * The `pipe` function is a utility that allows us to compose functions in a\n * readable and sequential manner. It takes the output of one function and\n * passes it as the input to the next function in the pipeline. This enables us\n * to build complex transformations by chaining multiple functions together.\n *\n * ```ts skip-type-checking\n * import { pipe } from \"effect\"\n *\n * const result = pipe(input, func1, func2, ..., funcN)\n * ```\n *\n * In this syntax, `input` is the initial value, and `func1`, `func2`, ...,\n * `funcN` are the functions to be applied in sequence. The result of each\n * function becomes the input for the next function, and the final result is\n * returned.\n *\n * Here's an illustration of how `pipe` works:\n *\n * ```\n * ┌───────┐    ┌───────┐    ┌───────┐    ┌───────┐    ┌───────┐    ┌────────┐\n * │ input │───►│ func1 │───►│ func2 │───►│  ...  │───►│ funcN │───►│ result │\n * └───────┘    └───────┘    └───────┘    └───────┘    └───────┘    └────────┘\n * ```\n *\n * It's important to note that functions passed to `pipe` must have a **single\n * argument** because they are only called with a single argument.\n *\n * **When to Use**\n *\n * This is useful in combination with data-last functions as a simulation of\n * methods:\n *\n * ```ts skip-type-checking\n * as.map(f).filter(g)\n * ```\n *\n * becomes:\n *\n * ```ts skip-type-checking\n * import { pipe, Array } from \"effect\"\n *\n * pipe(as, Array.map(f), Array.filter(g))\n * ```\n *\n * **Example** (Chaining Arithmetic Operations)\n *\n * ```ts\n * import { pipe } from \"effect\"\n *\n * // Define simple arithmetic operations\n * const increment = (x: number) => x + 1\n * const double = (x: number) => x * 2\n * const subtractTen = (x: number) => x - 10\n *\n * // Sequentially apply these operations using `pipe`\n * const result = pipe(5, increment, double, subtractTen)\n *\n * console.log(result)\n * // Output: 2\n * ```\n *\n * @since 2.0.0\n */\nexport function pipe<A>(a: A): A\nexport function pipe<A, B = never>(a: A, ab: (a: A) => B): B\nexport function pipe<A, B = never, C = never>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C\n): C\nexport function pipe<A, B = never, C = never, D = never>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D\n): D\nexport function pipe<A, B = never, C = never, D = never, E = never>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E\n): E\nexport function pipe<A, B = never, C = never, D = never, E = never, F = never>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F\n): F\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G\n): G\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H\n): H\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I\n): I\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J\n): J\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never,\n  K = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J,\n  jk: (j: J) => K\n): K\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never,\n  K = never,\n  L = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J,\n  jk: (j: J) => K,\n  kl: (k: K) => L\n): L\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never,\n  K = never,\n  L = never,\n  M = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J,\n  jk: (j: J) => K,\n  kl: (k: K) => L,\n  lm: (l: L) => M\n): M\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never,\n  K = never,\n  L = never,\n  M = never,\n  N = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J,\n  jk: (j: J) => K,\n  kl: (k: K) => L,\n  lm: (l: L) => M,\n  mn: (m: M) => N\n): N\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never,\n  K = never,\n  L = never,\n  M = never,\n  N = never,\n  O = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J,\n  jk: (j: J) => K,\n  kl: (k: K) => L,\n  lm: (l: L) => M,\n  mn: (m: M) => N,\n  no: (n: N) => O\n): O\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never,\n  K = never,\n  L = never,\n  M = never,\n  N = never,\n  O = never,\n  P = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J,\n  jk: (j: J) => K,\n  kl: (k: K) => L,\n  lm: (l: L) => M,\n  mn: (m: M) => N,\n  no: (n: N) => O,\n  op: (o: O) => P\n): P\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never,\n  K = never,\n  L = never,\n  M = never,\n  N = never,\n  O = never,\n  P = never,\n  Q = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J,\n  jk: (j: J) => K,\n  kl: (k: K) => L,\n  lm: (l: L) => M,\n  mn: (m: M) => N,\n  no: (n: N) => O,\n  op: (o: O) => P,\n  pq: (p: P) => Q\n): Q\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never,\n  K = never,\n  L = never,\n  M = never,\n  N = never,\n  O = never,\n  P = never,\n  Q = never,\n  R = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J,\n  jk: (j: J) => K,\n  kl: (k: K) => L,\n  lm: (l: L) => M,\n  mn: (m: M) => N,\n  no: (n: N) => O,\n  op: (o: O) => P,\n  pq: (p: P) => Q,\n  qr: (q: Q) => R\n): R\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never,\n  K = never,\n  L = never,\n  M = never,\n  N = never,\n  O = never,\n  P = never,\n  Q = never,\n  R = never,\n  S = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J,\n  jk: (j: J) => K,\n  kl: (k: K) => L,\n  lm: (l: L) => M,\n  mn: (m: M) => N,\n  no: (n: N) => O,\n  op: (o: O) => P,\n  pq: (p: P) => Q,\n  qr: (q: Q) => R,\n  rs: (r: R) => S\n): S\nexport function pipe<\n  A,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never,\n  K = never,\n  L = never,\n  M = never,\n  N = never,\n  O = never,\n  P = never,\n  Q = never,\n  R = never,\n  S = never,\n  T = never\n>(\n  a: A,\n  ab: (a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J,\n  jk: (j: J) => K,\n  kl: (k: K) => L,\n  lm: (l: L) => M,\n  mn: (m: M) => N,\n  no: (n: N) => O,\n  op: (o: O) => P,\n  pq: (p: P) => Q,\n  qr: (q: Q) => R,\n  rs: (r: R) => S,\n  st: (s: S) => T\n): T\nexport function pipe(\n  a: unknown,\n  ab?: Function,\n  bc?: Function,\n  cd?: Function,\n  de?: Function,\n  ef?: Function,\n  fg?: Function,\n  gh?: Function,\n  hi?: Function\n): unknown {\n  switch (arguments.length) {\n    case 1:\n      return a\n    case 2:\n      return ab!(a)\n    case 3:\n      return bc!(ab!(a))\n    case 4:\n      return cd!(bc!(ab!(a)))\n    case 5:\n      return de!(cd!(bc!(ab!(a))))\n    case 6:\n      return ef!(de!(cd!(bc!(ab!(a)))))\n    case 7:\n      return fg!(ef!(de!(cd!(bc!(ab!(a))))))\n    case 8:\n      return gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))\n    case 9:\n      return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))\n    default: {\n      let ret = arguments[0]\n      for (let i = 1; i < arguments.length; i++) {\n        ret = arguments[i](ret)\n      }\n      return ret\n    }\n  }\n}\n\n/**\n * Performs left-to-right function composition. The first argument may have any arity, the remaining arguments must be unary.\n *\n * See also [`pipe`](#pipe).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { flow } from \"effect/Function\"\n *\n * const len = (s: string): number => s.length\n * const double = (n: number): number => n * 2\n *\n * const f = flow(len, double)\n *\n * assert.strictEqual(f('aaa'), 6)\n * ```\n *\n * @since 2.0.0\n */\nexport function flow<A extends ReadonlyArray<unknown>, B = never>(\n  ab: (...a: A) => B\n): (...a: A) => B\nexport function flow<A extends ReadonlyArray<unknown>, B = never, C = never>(\n  ab: (...a: A) => B,\n  bc: (b: B) => C\n): (...a: A) => C\nexport function flow<\n  A extends ReadonlyArray<unknown>,\n  B = never,\n  C = never,\n  D = never\n>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D): (...a: A) => D\nexport function flow<\n  A extends ReadonlyArray<unknown>,\n  B = never,\n  C = never,\n  D = never,\n  E = never\n>(\n  ab: (...a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E\n): (...a: A) => E\nexport function flow<\n  A extends ReadonlyArray<unknown>,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never\n>(\n  ab: (...a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F\n): (...a: A) => F\nexport function flow<\n  A extends ReadonlyArray<unknown>,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never\n>(\n  ab: (...a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G\n): (...a: A) => G\nexport function flow<\n  A extends ReadonlyArray<unknown>,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never\n>(\n  ab: (...a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H\n): (...a: A) => H\nexport function flow<\n  A extends ReadonlyArray<unknown>,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never\n>(\n  ab: (...a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I\n): (...a: A) => I\nexport function flow<\n  A extends ReadonlyArray<unknown>,\n  B = never,\n  C = never,\n  D = never,\n  E = never,\n  F = never,\n  G = never,\n  H = never,\n  I = never,\n  J = never\n>(\n  ab: (...a: A) => B,\n  bc: (b: B) => C,\n  cd: (c: C) => D,\n  de: (d: D) => E,\n  ef: (e: E) => F,\n  fg: (f: F) => G,\n  gh: (g: G) => H,\n  hi: (h: H) => I,\n  ij: (i: I) => J\n): (...a: A) => J\nexport function flow(\n  ab: Function,\n  bc?: Function,\n  cd?: Function,\n  de?: Function,\n  ef?: Function,\n  fg?: Function,\n  gh?: Function,\n  hi?: Function,\n  ij?: Function\n): unknown {\n  switch (arguments.length) {\n    case 1:\n      return ab\n    case 2:\n      return function(this: unknown) {\n        return bc!(ab.apply(this, arguments))\n      }\n    case 3:\n      return function(this: unknown) {\n        return cd!(bc!(ab.apply(this, arguments)))\n      }\n    case 4:\n      return function(this: unknown) {\n        return de!(cd!(bc!(ab.apply(this, arguments))))\n      }\n    case 5:\n      return function(this: unknown) {\n        return ef!(de!(cd!(bc!(ab.apply(this, arguments)))))\n      }\n    case 6:\n      return function(this: unknown) {\n        return fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments))))))\n      }\n    case 7:\n      return function(this: unknown) {\n        return gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments)))))))\n      }\n    case 8:\n      return function(this: unknown) {\n        return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments))))))))\n      }\n    case 9:\n      return function(this: unknown) {\n        return ij!(hi!(gh!(fg!(ef!(de!(cd!(bc!(ab.apply(this, arguments)))))))))\n      }\n  }\n  return\n}\n\n/**\n * Type hole simulation.\n *\n * @since 2.0.0\n */\nexport const hole: <T>() => T = unsafeCoerce(absurd)\n\n/**\n * The SK combinator, also known as the \"S-K combinator\" or \"S-combinator\", is a fundamental combinator in the\n * lambda calculus and the SKI combinator calculus.\n *\n * This function is useful for discarding the first argument passed to it and returning the second argument.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { SK } from \"effect/Function\";\n *\n * assert.deepStrictEqual(SK(0, \"hello\"), \"hello\")\n * ```\n *\n * @since 2.0.0\n */\nexport const SK = <A, B>(_: A, b: B): B => b\n"
  },
  {
    "path": "packages/effect/src/GlobalValue.ts",
    "content": "/**\n * The `GlobalValue` module ensures that a single instance of a value is created globally,\n * even when modules are imported multiple times (e.g., due to mixing CommonJS and ESM builds)\n * or during hot-reloading in development environments like Next.js or Remix.\n *\n * It achieves this by using a versioned global store, identified by a unique `Symbol` tied to\n * the current version of the `effect` library. The store holds values that are keyed by an identifier,\n * allowing the reuse of previously computed instances across imports or reloads.\n *\n * This pattern is particularly useful in scenarios where frequent reloading can cause services or\n * single-instance objects to be recreated unnecessarily, such as in development environments with hot-reloading.\n *\n * @since 2.0.0\n */\nconst globalStoreId = `effect/GlobalValue`\n\nlet globalStore: Map<unknown, any>\n\n/**\n * Retrieves or computes a global value associated with the given `id`. If the value for this `id`\n * has already been computed, it will be returned from the global store. If it does not exist yet,\n * the provided `compute` function will be executed to compute the value, store it, and then return it.\n *\n * This ensures that even in cases where the module is imported multiple times (e.g., in mixed environments\n * like CommonJS and ESM, or during hot-reloading in development), the value is computed only once and reused\n * thereafter.\n *\n * @example\n * ```ts\n * import { globalValue } from \"effect/GlobalValue\"\n *\n * // This cache will persist as long as the module is running,\n * // even if reloaded or imported elsewhere\n * const myCache = globalValue(\n *   Symbol.for(\"myCache\"),\n *   () => new WeakMap<object, number>()\n * )\n * ```\n *\n * @since 2.0.0\n */\nexport const globalValue = <A>(id: unknown, compute: () => A): A => {\n  if (!globalStore) {\n    // @ts-expect-error\n    globalThis[globalStoreId] ??= new Map()\n    // @ts-expect-error\n    globalStore = globalThis[globalStoreId] as Map<unknown, any>\n  }\n  if (!globalStore.has(id)) {\n    globalStore.set(id, compute())\n  }\n  return globalStore.get(id)!\n}\n"
  },
  {
    "path": "packages/effect/src/Graph.ts",
    "content": "/**\n * @experimental\n * @since 3.18.0\n */\n\nimport * as Data from \"./Data.js\"\nimport * as Equal from \"./Equal.js\"\nimport { dual } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport { format, NodeInspectSymbol } from \"./Inspectable.js\"\nimport * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\nimport type { Mutable } from \"./Types.js\"\n\n/**\n * Unique identifier for Graph instances.\n *\n * @since 3.18.0\n * @category symbol\n */\nexport const TypeId: \"~effect/Graph\" = \"~effect/Graph\" as const\n\n/**\n * Type identifier for Graph instances.\n *\n * @since 3.18.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * Node index for node identification using plain numbers.\n *\n * @since 3.18.0\n * @category models\n */\nexport type NodeIndex = number\n\n/**\n * Edge index for edge identification using plain numbers.\n *\n * @since 3.18.0\n * @category models\n */\nexport type EdgeIndex = number\n\n/**\n * Edge data containing source, target, and user data.\n *\n * @since 3.18.0\n * @category models\n */\nexport class Edge<E> extends Data.Class<{\n  readonly source: NodeIndex\n  readonly target: NodeIndex\n  readonly data: E\n}> {}\n\n/**\n * Graph type for distinguishing directed and undirected graphs.\n *\n * @since 3.18.0\n * @category models\n */\nexport type Kind = \"directed\" | \"undirected\"\n\n/**\n * Graph prototype interface.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface Proto<out N, out E> extends Iterable<readonly [NodeIndex, N]>, Equal.Equal, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n  readonly nodes: Map<NodeIndex, N>\n  readonly edges: Map<EdgeIndex, Edge<E>>\n  readonly adjacency: Map<NodeIndex, Array<EdgeIndex>>\n  readonly reverseAdjacency: Map<NodeIndex, Array<EdgeIndex>>\n  nextNodeIndex: NodeIndex\n  nextEdgeIndex: EdgeIndex\n  isAcyclic: Option.Option<boolean>\n}\n\n/**\n * Immutable graph interface.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface Graph<out N, out E, T extends Kind = \"directed\"> extends Proto<N, E> {\n  readonly type: T\n  readonly mutable: false\n}\n\n/**\n * Mutable graph interface.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface MutableGraph<out N, out E, T extends Kind = \"directed\"> extends Proto<N, E> {\n  readonly type: T\n  readonly mutable: true\n}\n\n/**\n * Directed graph type alias.\n *\n * @since 3.18.0\n * @category models\n */\nexport type DirectedGraph<N, E> = Graph<N, E, \"directed\">\n\n/**\n * Undirected graph type alias.\n *\n * @since 3.18.0\n * @category models\n */\nexport type UndirectedGraph<N, E> = Graph<N, E, \"undirected\">\n\n/**\n * Mutable directed graph type alias.\n *\n * @since 3.18.0\n * @category models\n */\nexport type MutableDirectedGraph<N, E> = MutableGraph<N, E, \"directed\">\n\n/**\n * Mutable undirected graph type alias.\n *\n * @since 3.18.0\n * @category models\n */\nexport type MutableUndirectedGraph<N, E> = MutableGraph<N, E, \"undirected\">\n\n// =============================================================================\n// Proto Objects\n// =============================================================================\n\n/** @internal */\nconst ProtoGraph = {\n  [TypeId]: TypeId,\n  [Symbol.iterator](this: Graph<any, any>) {\n    return this.nodes[Symbol.iterator]()\n  },\n  [NodeInspectSymbol](this: Graph<any, any>) {\n    return this.toJSON()\n  },\n  [Equal.symbol](this: Graph<any, any>, that: Equal.Equal): boolean {\n    if (isGraph(that)) {\n      if (\n        this.nodes.size !== that.nodes.size ||\n        this.edges.size !== that.edges.size ||\n        this.type !== that.type\n      ) {\n        return false\n      }\n      // Compare nodes\n      for (const [nodeIndex, nodeData] of this.nodes) {\n        if (!that.nodes.has(nodeIndex)) {\n          return false\n        }\n        const otherNodeData = that.nodes.get(nodeIndex)!\n        if (!Equal.equals(nodeData, otherNodeData)) {\n          return false\n        }\n      }\n      // Compare edges\n      for (const [edgeIndex, edgeData] of this.edges) {\n        if (!that.edges.has(edgeIndex)) {\n          return false\n        }\n        const otherEdge = that.edges.get(edgeIndex)!\n        if (!Equal.equals(edgeData, otherEdge)) {\n          return false\n        }\n      }\n      return true\n    }\n    return false\n  },\n  [Hash.symbol](this: Graph<any, any>): number {\n    let hash = Hash.string(\"Graph\")\n    hash = hash ^ Hash.string(this.type)\n    hash = hash ^ Hash.number(this.nodes.size)\n    hash = hash ^ Hash.number(this.edges.size)\n    for (const [nodeIndex, nodeData] of this.nodes) {\n      hash = hash ^ (Hash.hash(nodeIndex) + Hash.hash(nodeData))\n    }\n    for (const [edgeIndex, edgeData] of this.edges) {\n      hash = hash ^ (Hash.hash(edgeIndex) + Hash.hash(edgeData))\n    }\n    return hash\n  },\n  toJSON(this: Graph<any, any>) {\n    return {\n      _id: \"Graph\",\n      nodeCount: this.nodes.size,\n      edgeCount: this.edges.size,\n      type: this.type\n    }\n  },\n  toString(this: Graph<any, any>) {\n    return format(this)\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n// =============================================================================\n// Errors\n// =============================================================================\n\n/**\n * Error thrown when a graph operation fails.\n *\n * @since 3.18.0\n * @category errors\n */\nexport class GraphError extends Data.TaggedError(\"GraphError\")<{\n  readonly message: string\n}> {}\n\n/** @internal */\nconst missingNode = (node: number) => new GraphError({ message: `Node ${node} does not exist` })\n\n// =============================================================================\n// Constructors\n// =============================================================================\n\n/** @internal */\nexport const isGraph = (u: unknown): u is Graph<unknown, unknown> => typeof u === \"object\" && u !== null && TypeId in u\n\n/**\n * Creates a directed graph, optionally with initial mutations.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * // Directed graph with initial nodes and edges\n * const graph = Graph.directed<string, string>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, \"A->B\")\n *   Graph.addEdge(mutable, b, c, \"B->C\")\n * })\n * ```\n *\n * @since 3.18.0\n * @category constructors\n */\nexport const directed = <N, E>(mutate?: (mutable: MutableDirectedGraph<N, E>) => void): DirectedGraph<N, E> => {\n  const graph: Mutable<DirectedGraph<N, E>> = Object.create(ProtoGraph)\n  graph.type = \"directed\"\n  graph.nodes = new Map()\n  graph.edges = new Map()\n  graph.adjacency = new Map()\n  graph.reverseAdjacency = new Map()\n  graph.nextNodeIndex = 0\n  graph.nextEdgeIndex = 0\n  graph.isAcyclic = Option.some(true)\n  graph.mutable = false\n\n  if (mutate) {\n    const mutable = beginMutation(graph as DirectedGraph<N, E>)\n    mutate(mutable as MutableDirectedGraph<N, E>)\n    return endMutation(mutable)\n  }\n\n  return graph\n}\n\n/**\n * Creates an undirected graph, optionally with initial mutations.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * // Undirected graph with initial nodes and edges\n * const graph = Graph.undirected<string, string>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, \"A-B\")\n *   Graph.addEdge(mutable, b, c, \"B-C\")\n * })\n * ```\n *\n * @since 3.18.0\n * @category constructors\n */\nexport const undirected = <N, E>(mutate?: (mutable: MutableUndirectedGraph<N, E>) => void): UndirectedGraph<N, E> => {\n  const graph: Mutable<UndirectedGraph<N, E>> = Object.create(ProtoGraph)\n  graph.type = \"undirected\"\n  graph.nodes = new Map()\n  graph.edges = new Map()\n  graph.adjacency = new Map()\n  graph.reverseAdjacency = new Map()\n  graph.nextNodeIndex = 0\n  graph.nextEdgeIndex = 0\n  graph.isAcyclic = Option.some(true)\n  graph.mutable = false\n\n  if (mutate) {\n    const mutable = beginMutation(graph)\n    mutate(mutable as MutableUndirectedGraph<N, E>)\n    return endMutation(mutable)\n  }\n\n  return graph\n}\n\n// =============================================================================\n// Scoped Mutable API\n// =============================================================================\n\n/**\n * Creates a mutable scope for safe graph mutations by copying the data structure.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>()\n * const mutable = Graph.beginMutation(graph)\n * // Now mutable can be safely modified without affecting original graph\n * ```\n *\n * @since 3.18.0\n * @category mutations\n */\nexport const beginMutation = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T>\n): MutableGraph<N, E, T> => {\n  // Copy adjacency maps with deep cloned arrays\n  const adjacency = new Map<NodeIndex, Array<EdgeIndex>>()\n  const reverseAdjacency = new Map<NodeIndex, Array<EdgeIndex>>()\n\n  for (const [nodeIndex, edges] of graph.adjacency) {\n    adjacency.set(nodeIndex, [...edges])\n  }\n\n  for (const [nodeIndex, edges] of graph.reverseAdjacency) {\n    reverseAdjacency.set(nodeIndex, [...edges])\n  }\n\n  const mutable: Mutable<MutableGraph<N, E, T>> = Object.create(ProtoGraph)\n  mutable.type = graph.type\n  mutable.nodes = new Map(graph.nodes)\n  mutable.edges = new Map(graph.edges)\n  mutable.adjacency = adjacency\n  mutable.reverseAdjacency = reverseAdjacency\n  mutable.nextNodeIndex = graph.nextNodeIndex\n  mutable.nextEdgeIndex = graph.nextEdgeIndex\n  mutable.isAcyclic = graph.isAcyclic\n  mutable.mutable = true\n\n  return mutable\n}\n\n/**\n * Converts a mutable graph back to an immutable graph, ending the mutation scope.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>()\n * const mutable = Graph.beginMutation(graph)\n * // ... perform mutations on mutable ...\n * const newGraph = Graph.endMutation(mutable)\n * ```\n *\n * @since 3.18.0\n * @category mutations\n */\nexport const endMutation = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>\n): Graph<N, E, T> => {\n  const graph: Mutable<Graph<N, E, T>> = Object.create(ProtoGraph)\n  graph.type = mutable.type\n  graph.nodes = new Map(mutable.nodes)\n  graph.edges = new Map(mutable.edges)\n  graph.adjacency = mutable.adjacency\n  graph.reverseAdjacency = mutable.reverseAdjacency\n  graph.nextNodeIndex = mutable.nextNodeIndex\n  graph.nextEdgeIndex = mutable.nextEdgeIndex\n  graph.isAcyclic = mutable.isAcyclic\n  graph.mutable = false\n\n  return graph\n}\n\n/**\n * Performs scoped mutations on a graph, automatically managing the mutation lifecycle.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>()\n * const newGraph = Graph.mutate(graph, (mutable) => {\n *   // Safe mutations go here\n *   // mutable gets automatically converted back to immutable\n * })\n * ```\n *\n * @since 3.18.0\n * @category mutations\n */\nexport const mutate: {\n  <N, E, T extends Kind = \"directed\">(\n    f: (mutable: MutableGraph<N, E, T>) => void\n  ): (graph: Graph<N, E, T>) => Graph<N, E, T>\n  <N, E, T extends Kind = \"directed\">(\n    graph: Graph<N, E, T>,\n    f: (mutable: MutableGraph<N, E, T>) => void\n  ): Graph<N, E, T>\n} = dual(2, <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T>,\n  f: (mutable: MutableGraph<N, E, T>) => void\n): Graph<N, E, T> => {\n  const mutable = beginMutation(graph)\n  f(mutable)\n  return endMutation(mutable)\n})\n\n// =============================================================================\n// Basic Node Operations\n// =============================================================================\n\n/**\n * Adds a new node to a mutable graph and returns its index.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const result = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   console.log(nodeA) // NodeIndex with value 0\n *   console.log(nodeB) // NodeIndex with value 1\n * })\n * ```\n *\n * @since 3.18.0\n * @category mutations\n */\nexport const addNode = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  data: N\n): NodeIndex => {\n  const nodeIndex = mutable.nextNodeIndex\n\n  // Add node data\n  mutable.nodes.set(nodeIndex, data)\n\n  // Initialize empty adjacency lists\n  mutable.adjacency.set(nodeIndex, [])\n  mutable.reverseAdjacency.set(nodeIndex, [])\n\n  // Update graph allocators\n  mutable.nextNodeIndex = mutable.nextNodeIndex + 1\n\n  return nodeIndex\n}\n\n/**\n * Gets the data associated with a node index, if it exists.\n *\n * @example\n * ```ts\n * import { Graph, Option } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   Graph.addNode(mutable, \"Node A\")\n * })\n *\n * const nodeIndex = 0\n * const nodeData = Graph.getNode(graph, nodeIndex)\n *\n * if (Option.isSome(nodeData)) {\n *   console.log(nodeData.value) // \"Node A\"\n * }\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const getNode = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  nodeIndex: NodeIndex\n): Option.Option<N> => graph.nodes.has(nodeIndex) ? Option.some(graph.nodes.get(nodeIndex)!) : Option.none()\n\n/**\n * Checks if a node with the given index exists in the graph.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   Graph.addNode(mutable, \"Node A\")\n * })\n *\n * const nodeIndex = 0\n * const exists = Graph.hasNode(graph, nodeIndex)\n * console.log(exists) // true\n *\n * const nonExistentIndex = 999\n * const notExists = Graph.hasNode(graph, nonExistentIndex)\n * console.log(notExists) // false\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const hasNode = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  nodeIndex: NodeIndex\n): boolean => graph.nodes.has(nodeIndex)\n\n/**\n * Returns the number of nodes in the graph.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const emptyGraph = Graph.directed<string, number>()\n * console.log(Graph.nodeCount(emptyGraph)) // 0\n *\n * const graphWithNodes = Graph.mutate(emptyGraph, (mutable) => {\n *   Graph.addNode(mutable, \"Node A\")\n *   Graph.addNode(mutable, \"Node B\")\n *   Graph.addNode(mutable, \"Node C\")\n * })\n *\n * console.log(Graph.nodeCount(graphWithNodes)) // 3\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const nodeCount = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>\n): number => graph.nodes.size\n\n/**\n * Finds the first node that matches the given predicate.\n *\n * @example\n * ```ts\n * import { Graph, Option } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   Graph.addNode(mutable, \"Node A\")\n *   Graph.addNode(mutable, \"Node B\")\n *   Graph.addNode(mutable, \"Node C\")\n * })\n *\n * const result = Graph.findNode(graph, (data) => data.startsWith(\"Node B\"))\n * console.log(result) // Option.some(1)\n *\n * const notFound = Graph.findNode(graph, (data) => data === \"Node D\")\n * console.log(notFound) // Option.none()\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const findNode = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  predicate: (data: N) => boolean\n): Option.Option<NodeIndex> => {\n  for (const [index, data] of graph.nodes) {\n    if (predicate(data)) {\n      return Option.some(index)\n    }\n  }\n  return Option.none()\n}\n\n/**\n * Finds all nodes that match the given predicate.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   Graph.addNode(mutable, \"Start A\")\n *   Graph.addNode(mutable, \"Node B\")\n *   Graph.addNode(mutable, \"Start C\")\n * })\n *\n * const result = Graph.findNodes(graph, (data) => data.startsWith(\"Start\"))\n * console.log(result) // [0, 2]\n *\n * const empty = Graph.findNodes(graph, (data) => data === \"Not Found\")\n * console.log(empty) // []\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const findNodes = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  predicate: (data: N) => boolean\n): Array<NodeIndex> => {\n  const results: Array<NodeIndex> = []\n  for (const [index, data] of graph.nodes) {\n    if (predicate(data)) {\n      results.push(index)\n    }\n  }\n  return results\n}\n\n/**\n * Finds the first edge that matches the given predicate.\n *\n * @example\n * ```ts\n * import { Graph, Option } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   const nodeC = Graph.addNode(mutable, \"Node C\")\n *   Graph.addEdge(mutable, nodeA, nodeB, 10)\n *   Graph.addEdge(mutable, nodeB, nodeC, 20)\n * })\n *\n * const result = Graph.findEdge(graph, (data) => data > 15)\n * console.log(result) // Option.some(1)\n *\n * const notFound = Graph.findEdge(graph, (data) => data > 100)\n * console.log(notFound) // Option.none()\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const findEdge = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  predicate: (data: E, source: NodeIndex, target: NodeIndex) => boolean\n): Option.Option<EdgeIndex> => {\n  for (const [edgeIndex, edgeData] of graph.edges) {\n    if (predicate(edgeData.data, edgeData.source, edgeData.target)) {\n      return Option.some(edgeIndex)\n    }\n  }\n  return Option.none()\n}\n\n/**\n * Finds all edges that match the given predicate.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   const nodeC = Graph.addNode(mutable, \"Node C\")\n *   Graph.addEdge(mutable, nodeA, nodeB, 10)\n *   Graph.addEdge(mutable, nodeB, nodeC, 20)\n *   Graph.addEdge(mutable, nodeC, nodeA, 30)\n * })\n *\n * const result = Graph.findEdges(graph, (data) => data >= 20)\n * console.log(result) // [1, 2]\n *\n * const empty = Graph.findEdges(graph, (data) => data > 100)\n * console.log(empty) // []\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const findEdges = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  predicate: (data: E, source: NodeIndex, target: NodeIndex) => boolean\n): Array<EdgeIndex> => {\n  const results: Array<EdgeIndex> = []\n  for (const [edgeIndex, edgeData] of graph.edges) {\n    if (predicate(edgeData.data, edgeData.source, edgeData.target)) {\n      results.push(edgeIndex)\n    }\n  }\n  return results\n}\n\n/**\n * Updates a single node's data by applying a transformation function.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   Graph.addNode(mutable, \"Node A\")\n *   Graph.addNode(mutable, \"Node B\")\n *   Graph.updateNode(mutable, 0, (data) => data.toUpperCase())\n * })\n *\n * const nodeData = Graph.getNode(graph, 0)\n * console.log(nodeData) // Option.some(\"NODE A\")\n * ```\n *\n * @since 3.18.0\n * @category transformations\n */\nexport const updateNode = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  index: NodeIndex,\n  f: (data: N) => N\n): void => {\n  if (!mutable.nodes.has(index)) {\n    return\n  }\n\n  const currentData = mutable.nodes.get(index)!\n  const newData = f(currentData)\n  mutable.nodes.set(index, newData)\n}\n\n/**\n * Updates a single edge's data by applying a transformation function.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const result = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   const edgeIndex = Graph.addEdge(mutable, nodeA, nodeB, 10)\n *   Graph.updateEdge(mutable, edgeIndex, (data) => data * 2)\n * })\n *\n * const edgeData = Graph.getEdge(result, 0)\n * console.log(edgeData) // Option.some({ source: 0, target: 1, data: 20 })\n * ```\n *\n * @since 3.18.0\n * @category mutations\n */\nexport const updateEdge = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  edgeIndex: EdgeIndex,\n  f: (data: E) => E\n): void => {\n  if (!mutable.edges.has(edgeIndex)) {\n    return\n  }\n\n  const currentEdge = mutable.edges.get(edgeIndex)!\n  const newData = f(currentEdge.data)\n  mutable.edges.set(edgeIndex, {\n    ...currentEdge,\n    data: newData\n  })\n}\n\n/**\n * Creates a new graph with transformed node data using the provided mapping function.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   Graph.addNode(mutable, \"node a\")\n *   Graph.addNode(mutable, \"node b\")\n *   Graph.addNode(mutable, \"node c\")\n *   Graph.mapNodes(mutable, (data) => data.toUpperCase())\n * })\n *\n * const nodeData = Graph.getNode(graph, 0)\n * console.log(nodeData) // Option.some(\"NODE A\")\n * ```\n *\n * @since 3.18.0\n * @category transformations\n */\nexport const mapNodes = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  f: (data: N) => N\n): void => {\n  // Transform existing node data in place\n  for (const [index, data] of mutable.nodes) {\n    const newData = f(data)\n    mutable.nodes.set(index, newData)\n  }\n}\n\n/**\n * Transforms all edge data in a mutable graph using the provided mapping function.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, 10)\n *   Graph.addEdge(mutable, b, c, 20)\n *   Graph.mapEdges(mutable, (data) => data * 2)\n * })\n *\n * const edgeData = Graph.getEdge(graph, 0)\n * console.log(edgeData) // Option.some({ source: 0, target: 1, data: 20 })\n * ```\n *\n * @since 3.18.0\n * @category transformations\n */\nexport const mapEdges = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  f: (data: E) => E\n): void => {\n  // Transform existing edge data in place\n  for (const [index, edgeData] of mutable.edges) {\n    const newData = f(edgeData.data)\n    mutable.edges.set(index, {\n      ...edgeData,\n      data: newData\n    })\n  }\n}\n\n/**\n * Reverses all edge directions in a mutable graph by swapping source and target nodes.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, 1)  // A -> B\n *   Graph.addEdge(mutable, b, c, 2)  // B -> C\n *   Graph.reverse(mutable)           // Now B -> A, C -> B\n * })\n *\n * const edge0 = Graph.getEdge(graph, 0)\n * console.log(edge0) // Option.some({ source: 1, target: 0, data: 1 }) - B -> A\n * ```\n *\n * @since 3.18.0\n * @category transformations\n */\nexport const reverse = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>\n): void => {\n  // Reverse all edges by swapping source and target\n  for (const [index, edgeData] of mutable.edges) {\n    mutable.edges.set(index, {\n      source: edgeData.target,\n      target: edgeData.source,\n      data: edgeData.data\n    })\n  }\n\n  // Clear and rebuild adjacency lists with reversed directions\n  mutable.adjacency.clear()\n  mutable.reverseAdjacency.clear()\n\n  // Rebuild adjacency lists with reversed directions\n  for (const [edgeIndex, edgeData] of mutable.edges) {\n    // Add to forward adjacency (source -> target)\n    const sourceEdges = mutable.adjacency.get(edgeData.source) || []\n    sourceEdges.push(edgeIndex)\n    mutable.adjacency.set(edgeData.source, sourceEdges)\n\n    // Add to reverse adjacency (target <- source)\n    const targetEdges = mutable.reverseAdjacency.get(edgeData.target) || []\n    targetEdges.push(edgeIndex)\n    mutable.reverseAdjacency.set(edgeData.target, targetEdges)\n  }\n\n  // Invalidate cycle flag since edge directions changed\n  mutable.isAcyclic = Option.none()\n}\n\n/**\n * Filters and optionally transforms nodes in a mutable graph using a predicate function.\n * Nodes that return Option.none are removed along with all their connected edges.\n *\n * @example\n * ```ts\n * import { Graph, Option } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"active\")\n *   const b = Graph.addNode(mutable, \"inactive\")\n *   const c = Graph.addNode(mutable, \"active\")\n *   Graph.addEdge(mutable, a, b, 1)\n *   Graph.addEdge(mutable, b, c, 2)\n *\n *   // Keep only \"active\" nodes and transform to uppercase\n *   Graph.filterMapNodes(mutable, (data) =>\n *     data === \"active\" ? Option.some(data.toUpperCase()) : Option.none()\n *   )\n * })\n *\n * console.log(Graph.nodeCount(graph)) // 2 (only \"active\" nodes remain)\n * ```\n *\n * @since 3.18.0\n * @category transformations\n */\nexport const filterMapNodes = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  f: (data: N) => Option.Option<N>\n): void => {\n  const nodesToRemove: Array<NodeIndex> = []\n\n  // First pass: identify nodes to remove and transform data for nodes to keep\n  for (const [index, data] of mutable.nodes) {\n    const result = f(data)\n    if (Option.isSome(result)) {\n      // Transform node data\n      mutable.nodes.set(index, result.value)\n    } else {\n      // Mark for removal\n      nodesToRemove.push(index)\n    }\n  }\n\n  // Second pass: remove filtered out nodes and their edges\n  for (const nodeIndex of nodesToRemove) {\n    removeNode(mutable, nodeIndex)\n  }\n}\n\n/**\n * Filters and optionally transforms edges in a mutable graph using a predicate function.\n * Edges that return Option.none are removed from the graph.\n *\n * @example\n * ```ts\n * import { Graph, Option } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, 5)\n *   Graph.addEdge(mutable, b, c, 15)\n *   Graph.addEdge(mutable, c, a, 25)\n *\n *   // Keep only edges with weight >= 10 and double their weight\n *   Graph.filterMapEdges(mutable, (data) =>\n *     data >= 10 ? Option.some(data * 2) : Option.none()\n *   )\n * })\n *\n * console.log(Graph.edgeCount(graph)) // 2 (edges with weight 5 removed)\n * ```\n *\n * @since 3.18.0\n * @category transformations\n */\nexport const filterMapEdges = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  f: (data: E) => Option.Option<E>\n): void => {\n  const edgesToRemove: Array<EdgeIndex> = []\n\n  // First pass: identify edges to remove and transform data for edges to keep\n  for (const [index, edgeData] of mutable.edges) {\n    const result = f(edgeData.data)\n    if (Option.isSome(result)) {\n      // Transform edge data\n      mutable.edges.set(index, {\n        ...edgeData,\n        data: result.value\n      })\n    } else {\n      // Mark for removal\n      edgesToRemove.push(index)\n    }\n  }\n\n  // Second pass: remove filtered out edges\n  for (const edgeIndex of edgesToRemove) {\n    removeEdge(mutable, edgeIndex)\n  }\n}\n\n/**\n * Filters nodes by removing those that don't match the predicate.\n * This function modifies the mutable graph in place.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   Graph.addNode(mutable, \"active\")\n *   Graph.addNode(mutable, \"inactive\")\n *   Graph.addNode(mutable, \"pending\")\n *   Graph.addNode(mutable, \"active\")\n *\n *   // Keep only \"active\" nodes\n *   Graph.filterNodes(mutable, (data) => data === \"active\")\n * })\n *\n * console.log(Graph.nodeCount(graph)) // 2 (only \"active\" nodes remain)\n * ```\n *\n * @since 3.18.0\n * @category transformations\n */\nexport const filterNodes = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  predicate: (data: N) => boolean\n): void => {\n  const nodesToRemove: Array<NodeIndex> = []\n\n  // Identify nodes to remove\n  for (const [index, data] of mutable.nodes) {\n    if (!predicate(data)) {\n      nodesToRemove.push(index)\n    }\n  }\n\n  // Remove filtered out nodes (this also removes connected edges)\n  for (const nodeIndex of nodesToRemove) {\n    removeNode(mutable, nodeIndex)\n  }\n}\n\n/**\n * Filters edges by removing those that don't match the predicate.\n * This function modifies the mutable graph in place.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *\n *   Graph.addEdge(mutable, a, b, 5)\n *   Graph.addEdge(mutable, b, c, 15)\n *   Graph.addEdge(mutable, c, a, 25)\n *\n *   // Keep only edges with weight >= 10\n *   Graph.filterEdges(mutable, (data) => data >= 10)\n * })\n *\n * console.log(Graph.edgeCount(graph)) // 2 (edge with weight 5 removed)\n * ```\n *\n * @since 3.18.0\n * @category transformations\n */\nexport const filterEdges = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  predicate: (data: E) => boolean\n): void => {\n  const edgesToRemove: Array<EdgeIndex> = []\n\n  // Identify edges to remove\n  for (const [index, edgeData] of mutable.edges) {\n    if (!predicate(edgeData.data)) {\n      edgesToRemove.push(index)\n    }\n  }\n\n  // Remove filtered out edges\n  for (const edgeIndex of edgesToRemove) {\n    removeEdge(mutable, edgeIndex)\n  }\n}\n\n// =============================================================================\n// Cycle Flag Management (Internal)\n// =============================================================================\n\n/** @internal */\nconst invalidateCycleFlagOnRemoval = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>\n): void => {\n  // Only invalidate if the graph had cycles (removing edges/nodes cannot introduce cycles in acyclic graphs)\n  // If already unknown (null) or acyclic (true), no need to change\n  if (Option.isSome(mutable.isAcyclic) && mutable.isAcyclic.value === false) {\n    mutable.isAcyclic = Option.none()\n  }\n}\n\n/** @internal */\nconst invalidateCycleFlagOnAddition = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>\n): void => {\n  // Only invalidate if the graph was acyclic (adding edges cannot remove cycles from cyclic graphs)\n  // If already unknown (null) or cyclic (false), no need to change\n  if (Option.isSome(mutable.isAcyclic) && mutable.isAcyclic.value === true) {\n    mutable.isAcyclic = Option.none()\n  }\n}\n\n// =============================================================================\n// Edge Operations\n// =============================================================================\n\n/**\n * Adds a new edge to a mutable graph and returns its index.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const result = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   const edge = Graph.addEdge(mutable, nodeA, nodeB, 42)\n *   console.log(edge) // EdgeIndex with value 0\n * })\n * ```\n *\n * @since 3.18.0\n * @category mutations\n */\nexport const addEdge = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  source: NodeIndex,\n  target: NodeIndex,\n  data: E\n): EdgeIndex => {\n  // Validate that both nodes exist\n  if (!mutable.nodes.has(source)) {\n    throw missingNode(source)\n  }\n  if (!mutable.nodes.has(target)) {\n    throw missingNode(target)\n  }\n\n  const edgeIndex = mutable.nextEdgeIndex\n\n  // Create edge data\n  const edgeData = new Edge({ source, target, data })\n  mutable.edges.set(edgeIndex, edgeData)\n\n  // Update adjacency lists\n  const sourceAdjacency = mutable.adjacency.get(source)\n  if (sourceAdjacency !== undefined) {\n    sourceAdjacency.push(edgeIndex)\n  }\n\n  const targetReverseAdjacency = mutable.reverseAdjacency.get(target)\n  if (targetReverseAdjacency !== undefined) {\n    targetReverseAdjacency.push(edgeIndex)\n  }\n\n  // For undirected graphs, add reverse connections\n  if (mutable.type === \"undirected\") {\n    const targetAdjacency = mutable.adjacency.get(target)\n    if (targetAdjacency !== undefined) {\n      targetAdjacency.push(edgeIndex)\n    }\n\n    const sourceReverseAdjacency = mutable.reverseAdjacency.get(source)\n    if (sourceReverseAdjacency !== undefined) {\n      sourceReverseAdjacency.push(edgeIndex)\n    }\n  }\n\n  // Update allocators\n  mutable.nextEdgeIndex = mutable.nextEdgeIndex + 1\n\n  // Only invalidate cycle flag if the graph was acyclic\n  // Adding edges cannot remove cycles from cyclic graphs\n  invalidateCycleFlagOnAddition(mutable)\n\n  return edgeIndex\n}\n\n/**\n * Removes a node and all its incident edges from a mutable graph.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const result = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   Graph.addEdge(mutable, nodeA, nodeB, 42)\n *\n *   // Remove nodeA and all edges connected to it\n *   Graph.removeNode(mutable, nodeA)\n * })\n * ```\n *\n * @since 3.18.0\n * @category mutations\n */\nexport const removeNode = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  nodeIndex: NodeIndex\n): void => {\n  // Check if node exists\n  if (!mutable.nodes.has(nodeIndex)) {\n    return // Node doesn't exist, nothing to remove\n  }\n\n  // Collect all incident edges for removal\n  const edgesToRemove: Array<EdgeIndex> = []\n\n  // Get outgoing edges\n  const outgoingEdges = mutable.adjacency.get(nodeIndex)\n  if (outgoingEdges !== undefined) {\n    for (const edge of outgoingEdges) {\n      edgesToRemove.push(edge)\n    }\n  }\n\n  // Get incoming edges\n  const incomingEdges = mutable.reverseAdjacency.get(nodeIndex)\n  if (incomingEdges !== undefined) {\n    for (const edge of incomingEdges) {\n      edgesToRemove.push(edge)\n    }\n  }\n\n  // Remove all incident edges\n  for (const edgeIndex of edgesToRemove) {\n    removeEdgeInternal(mutable, edgeIndex)\n  }\n\n  // Remove the node itself\n  mutable.nodes.delete(nodeIndex)\n  mutable.adjacency.delete(nodeIndex)\n  mutable.reverseAdjacency.delete(nodeIndex)\n\n  // Only invalidate cycle flag if the graph wasn't already known to be acyclic\n  // Removing nodes cannot introduce cycles in an acyclic graph\n  invalidateCycleFlagOnRemoval(mutable)\n}\n\n/**\n * Removes an edge from a mutable graph.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const result = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   const edge = Graph.addEdge(mutable, nodeA, nodeB, 42)\n *\n *   // Remove the edge\n *   Graph.removeEdge(mutable, edge)\n * })\n * ```\n *\n * @since 3.18.0\n * @category mutations\n */\nexport const removeEdge = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  edgeIndex: EdgeIndex\n): void => {\n  const wasRemoved = removeEdgeInternal(mutable, edgeIndex)\n\n  // Only invalidate cycle flag if an edge was actually removed\n  // and only if the graph wasn't already known to be acyclic\n  if (wasRemoved) {\n    invalidateCycleFlagOnRemoval(mutable)\n  }\n}\n\n/** @internal */\nconst removeEdgeInternal = <N, E, T extends Kind = \"directed\">(\n  mutable: MutableGraph<N, E, T>,\n  edgeIndex: EdgeIndex\n): boolean => {\n  // Get edge data\n  const edge = mutable.edges.get(edgeIndex)\n  if (edge === undefined) {\n    return false // Edge doesn't exist, no mutation occurred\n  }\n\n  const { source, target } = edge\n\n  // Remove from adjacency lists\n  const sourceAdjacency = mutable.adjacency.get(source)\n  if (sourceAdjacency !== undefined) {\n    const index = sourceAdjacency.indexOf(edgeIndex)\n    if (index !== -1) {\n      sourceAdjacency.splice(index, 1)\n    }\n  }\n\n  const targetReverseAdjacency = mutable.reverseAdjacency.get(target)\n  if (targetReverseAdjacency !== undefined) {\n    const index = targetReverseAdjacency.indexOf(edgeIndex)\n    if (index !== -1) {\n      targetReverseAdjacency.splice(index, 1)\n    }\n  }\n\n  // For undirected graphs, remove reverse connections\n  if (mutable.type === \"undirected\") {\n    const targetAdjacency = mutable.adjacency.get(target)\n    if (targetAdjacency !== undefined) {\n      const index = targetAdjacency.indexOf(edgeIndex)\n      if (index !== -1) {\n        targetAdjacency.splice(index, 1)\n      }\n    }\n\n    const sourceReverseAdjacency = mutable.reverseAdjacency.get(source)\n    if (sourceReverseAdjacency !== undefined) {\n      const index = sourceReverseAdjacency.indexOf(edgeIndex)\n      if (index !== -1) {\n        sourceReverseAdjacency.splice(index, 1)\n      }\n    }\n  }\n\n  // Remove edge data\n  mutable.edges.delete(edgeIndex)\n\n  return true // Edge was successfully removed\n}\n\n// =============================================================================\n// Edge Query Operations\n// =============================================================================\n\n/**\n * Gets the edge data associated with an edge index, if it exists.\n *\n * @example\n * ```ts\n * import { Graph, Option } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   Graph.addEdge(mutable, nodeA, nodeB, 42)\n * })\n *\n * const edgeIndex = 0\n * const edgeData = Graph.getEdge(graph, edgeIndex)\n *\n * if (Option.isSome(edgeData)) {\n *   console.log(edgeData.value.data) // 42\n *   console.log(edgeData.value.source) // NodeIndex(0)\n *   console.log(edgeData.value.target) // NodeIndex(1)\n * }\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const getEdge = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  edgeIndex: EdgeIndex\n): Option.Option<Edge<E>> => graph.edges.has(edgeIndex) ? Option.some(graph.edges.get(edgeIndex)!) : Option.none()\n\n/**\n * Checks if an edge exists between two nodes in the graph.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   const nodeC = Graph.addNode(mutable, \"Node C\")\n *   Graph.addEdge(mutable, nodeA, nodeB, 42)\n * })\n *\n * const nodeA = 0\n * const nodeB = 1\n * const nodeC = 2\n *\n * const hasAB = Graph.hasEdge(graph, nodeA, nodeB)\n * console.log(hasAB) // true\n *\n * const hasAC = Graph.hasEdge(graph, nodeA, nodeC)\n * console.log(hasAC) // false\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const hasEdge = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  source: NodeIndex,\n  target: NodeIndex\n): boolean => {\n  const adjacencyList = graph.adjacency.get(source)\n  if (adjacencyList === undefined) {\n    return false\n  }\n\n  // Check if any edge in the adjacency list connects to the target\n  for (const edgeIndex of adjacencyList) {\n    const edge = graph.edges.get(edgeIndex)\n    if (edge !== undefined && edge.target === target) {\n      return true\n    }\n  }\n\n  return false\n}\n\n/**\n * Returns the number of edges in the graph.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const emptyGraph = Graph.directed<string, number>()\n * console.log(Graph.edgeCount(emptyGraph)) // 0\n *\n * const graphWithEdges = Graph.mutate(emptyGraph, (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   const nodeC = Graph.addNode(mutable, \"Node C\")\n *   Graph.addEdge(mutable, nodeA, nodeB, 1)\n *   Graph.addEdge(mutable, nodeB, nodeC, 2)\n *   Graph.addEdge(mutable, nodeC, nodeA, 3)\n * })\n *\n * console.log(Graph.edgeCount(graphWithEdges)) // 3\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const edgeCount = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>\n): number => graph.edges.size\n\n/**\n * Returns the neighboring nodes (targets of outgoing edges) for a given node.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   const nodeC = Graph.addNode(mutable, \"Node C\")\n *   Graph.addEdge(mutable, nodeA, nodeB, 1)\n *   Graph.addEdge(mutable, nodeA, nodeC, 2)\n * })\n *\n * const nodeA = 0\n * const nodeB = 1\n * const nodeC = 2\n *\n * const neighborsA = Graph.neighbors(graph, nodeA)\n * console.log(neighborsA) // [NodeIndex(1), NodeIndex(2)]\n *\n * const neighborsB = Graph.neighbors(graph, nodeB)\n * console.log(neighborsB) // []\n * ```\n *\n * @since 3.18.0\n * @category getters\n */\nexport const neighbors = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  nodeIndex: NodeIndex\n): Array<NodeIndex> => {\n  // For undirected graphs, use the specialized helper that returns the other endpoint\n  if (graph.type === \"undirected\") {\n    return getUndirectedNeighbors(graph as any, nodeIndex)\n  }\n\n  const adjacencyList = graph.adjacency.get(nodeIndex)\n  if (adjacencyList === undefined) {\n    return []\n  }\n\n  const result: Array<NodeIndex> = []\n  for (const edgeIndex of adjacencyList) {\n    const edge = graph.edges.get(edgeIndex)\n    if (edge !== undefined) {\n      result.push(edge.target)\n    }\n  }\n\n  return result\n}\n\n/**\n * Get neighbors of a node in a specific direction for bidirectional traversal.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, string>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   Graph.addEdge(mutable, a, b, \"A->B\")\n * })\n *\n * const nodeA = 0\n * const nodeB = 1\n *\n * // Get outgoing neighbors (nodes that nodeA points to)\n * const outgoing = Graph.neighborsDirected(graph, nodeA, \"outgoing\")\n *\n * // Get incoming neighbors (nodes that point to nodeB)\n * const incoming = Graph.neighborsDirected(graph, nodeB, \"incoming\")\n * ```\n *\n * @since 3.18.0\n * @category queries\n */\nexport const neighborsDirected = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  nodeIndex: NodeIndex,\n  direction: Direction\n): Array<NodeIndex> => {\n  const adjacencyMap = direction === \"incoming\"\n    ? graph.reverseAdjacency\n    : graph.adjacency\n\n  const adjacencyList = adjacencyMap.get(nodeIndex)\n  if (adjacencyList === undefined) {\n    return []\n  }\n\n  const result: Array<NodeIndex> = []\n  for (const edgeIndex of adjacencyList) {\n    const edge = graph.edges.get(edgeIndex)\n    if (edge !== undefined) {\n      // For incoming direction, we want the source node instead of target\n      const neighborNode = direction === \"incoming\"\n        ? edge.source\n        : edge.target\n      result.push(neighborNode)\n    }\n  }\n\n  return result\n}\n\n// =============================================================================\n// GraphViz Export\n// =============================================================================\n\n/**\n * Configuration options for GraphViz DOT format generation from graphs.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface GraphVizOptions<N, E> {\n  readonly nodeLabel?: (data: N) => string\n  readonly edgeLabel?: (data: E) => string\n  readonly graphName?: string\n}\n\n/**\n * Exports a graph to GraphViz DOT format for visualization.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const nodeA = Graph.addNode(mutable, \"Node A\")\n *   const nodeB = Graph.addNode(mutable, \"Node B\")\n *   const nodeC = Graph.addNode(mutable, \"Node C\")\n *   Graph.addEdge(mutable, nodeA, nodeB, 1)\n *   Graph.addEdge(mutable, nodeB, nodeC, 2)\n *   Graph.addEdge(mutable, nodeC, nodeA, 3)\n * })\n *\n * const dot = Graph.toGraphViz(graph)\n * console.log(dot)\n * // digraph G {\n * //   \"0\" [label=\"Node A\"];\n * //   \"1\" [label=\"Node B\"];\n * //   \"2\" [label=\"Node C\"];\n * //   \"0\" -> \"1\" [label=\"1\"];\n * //   \"1\" -> \"2\" [label=\"2\"];\n * //   \"2\" -> \"0\" [label=\"3\"];\n * // }\n * ```\n *\n * @since 3.18.0\n * @category utils\n */\nexport const toGraphViz = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  options?: GraphVizOptions<N, E>\n): string => {\n  const {\n    edgeLabel = (data: E) => String(data),\n    graphName = \"G\",\n    nodeLabel = (data: N) => String(data)\n  } = options ?? {}\n\n  const isDirected = graph.type === \"directed\"\n  const graphType = isDirected ? \"digraph\" : \"graph\"\n  const edgeOperator = isDirected ? \"->\" : \"--\"\n\n  const lines: Array<string> = []\n  lines.push(`${graphType} ${graphName} {`)\n\n  // Add nodes\n  for (const [nodeIndex, nodeData] of graph.nodes) {\n    const label = nodeLabel(nodeData).replace(/\"/g, \"\\\\\\\"\")\n    lines.push(`  \"${nodeIndex}\" [label=\"${label}\"];`)\n  }\n\n  // Add edges\n  for (const [, edgeData] of graph.edges) {\n    const label = edgeLabel(edgeData.data).replace(/\"/g, \"\\\\\\\"\")\n    lines.push(`  \"${edgeData.source}\" ${edgeOperator} \"${edgeData.target}\" [label=\"${label}\"];`)\n  }\n\n  lines.push(\"}\")\n  return lines.join(\"\\n\")\n}\n\n// =============================================================================\n// Mermaid Export\n// =============================================================================\n\n/**\n * Mermaid node shape types.\n *\n * @since 3.18.0\n * @category models\n */\nexport type MermaidNodeShape =\n  | \"rectangle\"\n  | \"rounded\"\n  | \"circle\"\n  | \"diamond\"\n  | \"hexagon\"\n  | \"stadium\"\n  | \"subroutine\"\n  | \"cylindrical\"\n\n/**\n * Mermaid diagram direction types.\n *\n * @since 3.18.0\n * @category models\n */\nexport type MermaidDirection = \"TB\" | \"TD\" | \"BT\" | \"LR\" | \"RL\"\n\n/**\n * Mermaid diagram type.\n *\n * @since 3.18.0\n * @category models\n */\nexport type MermaidDiagramType = \"flowchart\" | \"graph\"\n\n/**\n * Configuration options for Mermaid diagram generation.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface MermaidOptions<N, E> {\n  readonly nodeLabel?: (data: N) => string\n  readonly edgeLabel?: (data: E) => string\n  readonly diagramType?: MermaidDiagramType\n  readonly direction?: MermaidDirection\n  readonly nodeShape?: (data: N) => MermaidNodeShape\n}\n\n/** @internal */\nconst escapeMermaidLabel = (label: string): string => {\n  // Escape special characters for Mermaid using HTML entity codes\n  // According to: https://mermaid.js.org/syntax/flowchart.html#special-characters-that-break-syntax\n  return label\n    .replace(/#/g, \"#35;\")\n    .replace(/\"/g, \"#quot;\")\n    .replace(/</g, \"#lt;\")\n    .replace(/>/g, \"#gt;\")\n    .replace(/&/g, \"#amp;\")\n    .replace(/\\[/g, \"#91;\")\n    .replace(/\\]/g, \"#93;\")\n    .replace(/\\{/g, \"#123;\")\n    .replace(/\\}/g, \"#125;\")\n    .replace(/\\(/g, \"#40;\")\n    .replace(/\\)/g, \"#41;\")\n    .replace(/\\|/g, \"#124;\")\n    .replace(/\\\\/g, \"#92;\")\n    .replace(/\\n/g, \"<br/>\")\n}\n\n/** @internal */\nconst formatMermaidNode = (nodeId: string, label: string, shape: MermaidNodeShape): string => {\n  switch (shape) {\n    case \"rectangle\":\n      return `${nodeId}[\"${label}\"]`\n    case \"rounded\":\n      return `${nodeId}(\"${label}\")`\n    case \"circle\":\n      return `${nodeId}((\"${label}\"))`\n    case \"diamond\":\n      return `${nodeId}{\"${label}\"}`\n    case \"hexagon\":\n      return `${nodeId}{{\"${label}\"}}`\n    case \"stadium\":\n      return `${nodeId}([\"${label}\"])`\n    case \"subroutine\":\n      return `${nodeId}[[\"${label}\"]]`\n    case \"cylindrical\":\n      return `${nodeId}[(\"${label}\")]`\n  }\n}\n\n/**\n * Exports a graph to Mermaid diagram format for visualization.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n *   const app = Graph.addNode(mutable, \"App\")\n *   const db = Graph.addNode(mutable, \"Database\")\n *   const cache = Graph.addNode(mutable, \"Cache\")\n *   Graph.addEdge(mutable, app, db, 1)\n *   Graph.addEdge(mutable, app, cache, 2)\n * })\n *\n * const mermaid = Graph.toMermaid(graph)\n * console.log(mermaid)\n * // flowchart TD\n * //   0[\"App\"]\n * //   1[\"Database\"]\n * //   2[\"Cache\"]\n * //   0 -->|\"1\"| 1\n * //   0 -->|\"2\"| 2\n * ```\n *\n * @since 3.18.0\n * @category utils\n */\nexport const toMermaid = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  options?: MermaidOptions<N, E>\n): string => {\n  // Extract and validate options with defaults\n  const {\n    diagramType,\n    direction = \"TD\",\n    edgeLabel = (data: E) => String(data),\n    nodeLabel = (data: N) => String(data),\n    nodeShape = () => \"rectangle\" as const\n  } = options ?? {}\n\n  // Auto-detect diagram type if not specified\n  const finalDiagramType = diagramType ??\n    (graph.type === \"directed\" ? \"flowchart\" : \"graph\")\n\n  // Generate diagram header\n  const lines: Array<string> = []\n  lines.push(`${finalDiagramType} ${direction}`)\n\n  // Add nodes\n  for (const [nodeIndex, nodeData] of graph.nodes) {\n    const nodeId = String(nodeIndex)\n    const label = escapeMermaidLabel(nodeLabel(nodeData))\n    const shape = nodeShape(nodeData)\n    const formattedNode = formatMermaidNode(nodeId, label, shape)\n    lines.push(`  ${formattedNode}`)\n  }\n\n  // Add edges\n  const edgeOperator = finalDiagramType === \"flowchart\" ? \"-->\" : \"---\"\n  for (const [, edgeData] of graph.edges) {\n    const sourceId = String(edgeData.source)\n    const targetId = String(edgeData.target)\n    const label = escapeMermaidLabel(edgeLabel(edgeData.data))\n\n    if (label) {\n      lines.push(`  ${sourceId} ${edgeOperator}|\"${label}\"| ${targetId}`)\n    } else {\n      lines.push(`  ${sourceId} ${edgeOperator} ${targetId}`)\n    }\n  }\n\n  return lines.join(\"\\n\")\n}\n\n// =============================================================================\n// Direction Types for Bidirectional Traversal\n// =============================================================================\n\n/**\n * Direction for graph traversal, indicating which edges to follow.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, string>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   Graph.addEdge(mutable, a, b, \"A->B\")\n * })\n *\n * // Follow outgoing edges (normal direction)\n * const outgoingNodes = Array.from(Graph.indices(Graph.dfs(graph, { start: [0], direction: \"outgoing\" })))\n *\n * // Follow incoming edges (reverse direction)\n * const incomingNodes = Array.from(Graph.indices(Graph.dfs(graph, { start: [1], direction: \"incoming\" })))\n * ```\n *\n * @since 3.18.0\n * @category models\n */\nexport type Direction = \"outgoing\" | \"incoming\"\n\n// =============================================================================\n\n// =============================================================================\n// Graph Structure Analysis Algorithms (Phase 5A)\n// =============================================================================\n\n/**\n * Checks if the graph is acyclic (contains no cycles).\n *\n * Uses depth-first search to detect back edges, which indicate cycles.\n * For directed graphs, any back edge creates a cycle. For undirected graphs,\n * a back edge that doesn't go to the immediate parent creates a cycle.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * // Acyclic directed graph (DAG)\n * const dag = Graph.directed<string, string>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, \"A->B\")\n *   Graph.addEdge(mutable, b, c, \"B->C\")\n * })\n * console.log(Graph.isAcyclic(dag)) // true\n *\n * // Cyclic directed graph\n * const cyclic = Graph.directed<string, string>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   Graph.addEdge(mutable, a, b, \"A->B\")\n *   Graph.addEdge(mutable, b, a, \"B->A\") // Creates cycle\n * })\n * console.log(Graph.isAcyclic(cyclic)) // false\n * ```\n *\n * @since 3.18.0\n * @category algorithms\n */\nexport const isAcyclic = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>\n): boolean => {\n  // Use existing cycle flag if available\n  if (Option.isSome(graph.isAcyclic)) {\n    return graph.isAcyclic.value\n  }\n\n  // Stack-safe DFS cycle detection using iterative approach\n  const visited = new Set<NodeIndex>()\n  const recursionStack = new Set<NodeIndex>()\n\n  // Stack entry: [node, neighbors, neighborIndex, isFirstVisit]\n  type DfsStackEntry = [NodeIndex, Array<NodeIndex>, number, boolean]\n\n  // Get all nodes to handle disconnected components\n  for (const startNode of graph.nodes.keys()) {\n    if (visited.has(startNode)) {\n      continue // Already processed this component\n    }\n\n    // Iterative DFS with explicit stack\n    const stack: Array<DfsStackEntry> = [[startNode, [], 0, true]]\n\n    while (stack.length > 0) {\n      const [node, neighbors, neighborIndex, isFirstVisit] = stack[stack.length - 1]\n\n      // First visit to this node\n      if (isFirstVisit) {\n        if (recursionStack.has(node)) {\n          // Back edge found - cycle detected\n          graph.isAcyclic = Option.some(false)\n          return false\n        }\n\n        if (visited.has(node)) {\n          stack.pop()\n          continue\n        }\n\n        visited.add(node)\n        recursionStack.add(node)\n\n        // Get neighbors for this node\n        const nodeNeighbors = Array.from(neighborsDirected(graph, node, \"outgoing\"))\n        stack[stack.length - 1] = [node, nodeNeighbors, 0, false]\n        continue\n      }\n\n      // Process next neighbor\n      if (neighborIndex < neighbors.length) {\n        const neighbor = neighbors[neighborIndex]\n        stack[stack.length - 1] = [node, neighbors, neighborIndex + 1, false]\n\n        if (recursionStack.has(neighbor)) {\n          // Back edge found - cycle detected\n          graph.isAcyclic = Option.some(false)\n          return false\n        }\n\n        if (!visited.has(neighbor)) {\n          stack.push([neighbor, [], 0, true])\n        }\n      } else {\n        // Done with this node - backtrack\n        recursionStack.delete(node)\n        stack.pop()\n      }\n    }\n  }\n\n  // Cache the result\n  graph.isAcyclic = Option.some(true)\n  return true\n}\n\n/**\n * Checks if an undirected graph is bipartite.\n *\n * A bipartite graph is one whose vertices can be divided into two disjoint sets\n * such that no two vertices within the same set are adjacent. Uses BFS coloring\n * to determine bipartiteness.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * // Bipartite graph (alternating coloring possible)\n * const bipartite = Graph.undirected<string, string>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   const d = Graph.addNode(mutable, \"D\")\n *   Graph.addEdge(mutable, a, b, \"edge\") // Set 1: {A, C}, Set 2: {B, D}\n *   Graph.addEdge(mutable, b, c, \"edge\")\n *   Graph.addEdge(mutable, c, d, \"edge\")\n * })\n * console.log(Graph.isBipartite(bipartite)) // true\n *\n * // Non-bipartite graph (odd cycle)\n * const triangle = Graph.undirected<string, string>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, \"edge\")\n *   Graph.addEdge(mutable, b, c, \"edge\")\n *   Graph.addEdge(mutable, c, a, \"edge\") // Triangle (3-cycle)\n * })\n * console.log(Graph.isBipartite(triangle)) // false\n * ```\n *\n * @since 3.18.0\n * @category algorithms\n */\nexport const isBipartite = <N, E>(\n  graph: Graph<N, E, \"undirected\"> | MutableGraph<N, E, \"undirected\">\n): boolean => {\n  const coloring = new Map<NodeIndex, 0 | 1>()\n  const discovered = new Set<NodeIndex>()\n  let isBipartiteGraph = true\n\n  // Get all nodes to handle disconnected components\n  for (const startNode of graph.nodes.keys()) {\n    if (!discovered.has(startNode)) {\n      // Start BFS coloring from this component\n      const queue: Array<NodeIndex> = [startNode]\n      coloring.set(startNode, 0) // Color start node with 0\n      discovered.add(startNode)\n\n      while (queue.length > 0 && isBipartiteGraph) {\n        const current = queue.shift()!\n        const currentColor = coloring.get(current)!\n        const neighborColor: 0 | 1 = currentColor === 0 ? 1 : 0\n\n        // Get all neighbors for undirected graph\n        const nodeNeighbors = getUndirectedNeighbors(graph, current)\n        for (const neighbor of nodeNeighbors) {\n          if (!discovered.has(neighbor)) {\n            // Color unvisited neighbor with opposite color\n            coloring.set(neighbor, neighborColor)\n            discovered.add(neighbor)\n            queue.push(neighbor)\n          } else {\n            // Check if neighbor has the same color (conflict)\n            if (coloring.get(neighbor) === currentColor) {\n              isBipartiteGraph = false\n              break\n            }\n          }\n        }\n      }\n\n      // Early exit if not bipartite\n      if (!isBipartiteGraph) {\n        break\n      }\n    }\n  }\n\n  return isBipartiteGraph\n}\n\n/**\n * Get neighbors for undirected graphs by checking both adjacency and reverse adjacency.\n * For undirected graphs, we need to find the other endpoint of each edge incident to the node.\n */\nconst getUndirectedNeighbors = <N, E>(\n  graph: Graph<N, E, \"undirected\"> | MutableGraph<N, E, \"undirected\">,\n  nodeIndex: NodeIndex\n): Array<NodeIndex> => {\n  const neighbors = new Set<NodeIndex>()\n\n  // Check edges where this node is the source\n  const adjacencyList = graph.adjacency.get(nodeIndex)\n  if (adjacencyList !== undefined) {\n    for (const edgeIndex of adjacencyList) {\n      const edge = graph.edges.get(edgeIndex)\n      if (edge !== undefined) {\n        // For undirected graphs, the neighbor is the other endpoint\n        const otherNode = edge.source === nodeIndex ? edge.target : edge.source\n        neighbors.add(otherNode)\n      }\n    }\n  }\n\n  return Array.from(neighbors)\n}\n\n/**\n * Find connected components in an undirected graph.\n * Each component is represented as an array of node indices.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.undirected<string, string>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   const d = Graph.addNode(mutable, \"D\")\n *   Graph.addEdge(mutable, a, b, \"edge\") // Component 1: A-B\n *   Graph.addEdge(mutable, c, d, \"edge\") // Component 2: C-D\n * })\n *\n * const components = Graph.connectedComponents(graph)\n * console.log(components) // [[0, 1], [2, 3]]\n * ```\n *\n * @since 3.18.0\n * @category algorithms\n */\nexport const connectedComponents = <N, E>(\n  graph: Graph<N, E, \"undirected\"> | MutableGraph<N, E, \"undirected\">\n): Array<Array<NodeIndex>> => {\n  const visited = new Set<NodeIndex>()\n  const components: Array<Array<NodeIndex>> = []\n  for (const startNode of graph.nodes.keys()) {\n    if (!visited.has(startNode)) {\n      // DFS to find all nodes in this component\n      const component: Array<NodeIndex> = []\n      const stack: Array<NodeIndex> = [startNode]\n\n      while (stack.length > 0) {\n        const current = stack.pop()!\n        if (!visited.has(current)) {\n          visited.add(current)\n          component.push(current)\n\n          // Add all unvisited neighbors to stack\n          const nodeNeighbors = getUndirectedNeighbors(graph, current)\n          for (const neighbor of nodeNeighbors) {\n            if (!visited.has(neighbor)) {\n              stack.push(neighbor)\n            }\n          }\n        }\n      }\n\n      components.push(component)\n    }\n  }\n\n  return components\n}\n\n/**\n * Find strongly connected components in a directed graph using Kosaraju's algorithm.\n * Each SCC is represented as an array of node indices.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, string>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, \"A->B\")\n *   Graph.addEdge(mutable, b, c, \"B->C\")\n *   Graph.addEdge(mutable, c, a, \"C->A\") // Creates SCC: A-B-C\n * })\n *\n * const sccs = Graph.stronglyConnectedComponents(graph)\n * console.log(sccs) // [[0, 1, 2]]\n * ```\n *\n * @since 3.18.0\n * @category algorithms\n */\nexport const stronglyConnectedComponents = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>\n): Array<Array<NodeIndex>> => {\n  const visited = new Set<NodeIndex>()\n  const finishOrder: Array<NodeIndex> = []\n  // Iterate directly over node keys\n\n  // Step 1: Stack-safe DFS on original graph to get finish times\n  // Stack entry: [node, neighbors, neighborIndex, isFirstVisit]\n  type DfsStackEntry = [NodeIndex, Array<NodeIndex>, number, boolean]\n\n  for (const startNode of graph.nodes.keys()) {\n    if (visited.has(startNode)) {\n      continue\n    }\n\n    const stack: Array<DfsStackEntry> = [[startNode, [], 0, true]]\n\n    while (stack.length > 0) {\n      const [node, nodeNeighbors, neighborIndex, isFirstVisit] = stack[stack.length - 1]\n\n      if (isFirstVisit) {\n        if (visited.has(node)) {\n          stack.pop()\n          continue\n        }\n\n        visited.add(node)\n        const nodeNeighborsList = neighbors(graph, node)\n        stack[stack.length - 1] = [node, nodeNeighborsList, 0, false]\n        continue\n      }\n\n      // Process next neighbor\n      if (neighborIndex < nodeNeighbors.length) {\n        const neighbor = nodeNeighbors[neighborIndex]\n        stack[stack.length - 1] = [node, nodeNeighbors, neighborIndex + 1, false]\n\n        if (!visited.has(neighbor)) {\n          stack.push([neighbor, [], 0, true])\n        }\n      } else {\n        // Done with this node - add to finish order (post-order)\n        finishOrder.push(node)\n        stack.pop()\n      }\n    }\n  }\n\n  // Step 2: Stack-safe DFS on transpose graph in reverse finish order\n  visited.clear()\n  const sccs: Array<Array<NodeIndex>> = []\n\n  for (let i = finishOrder.length - 1; i >= 0; i--) {\n    const startNode = finishOrder[i]\n    if (visited.has(startNode)) {\n      continue\n    }\n\n    const scc: Array<NodeIndex> = []\n    const stack: Array<NodeIndex> = [startNode]\n\n    while (stack.length > 0) {\n      const node = stack.pop()!\n\n      if (visited.has(node)) {\n        continue\n      }\n\n      visited.add(node)\n      scc.push(node)\n\n      // Use reverse adjacency (transpose graph)\n      const reverseAdjacency = graph.reverseAdjacency.get(node)\n      if (reverseAdjacency !== undefined) {\n        for (const edgeIndex of reverseAdjacency) {\n          const edge = graph.edges.get(edgeIndex)\n          if (edge !== undefined) {\n            const predecessor = edge.source\n            if (!visited.has(predecessor)) {\n              stack.push(predecessor)\n            }\n          }\n        }\n      }\n    }\n\n    sccs.push(scc)\n  }\n\n  return sccs\n}\n\n// =============================================================================\n// Path Finding Algorithms (Phase 5B)\n// =============================================================================\n\n/**\n * Result of a shortest path computation containing the path and total distance.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface PathResult<E> {\n  readonly path: Array<NodeIndex>\n  readonly distance: number\n  readonly costs: Array<E>\n}\n\n/**\n * Configuration for Dijkstra's algorithm.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface DijkstraConfig<E> {\n  source: NodeIndex\n  target: NodeIndex\n  cost: (edgeData: E) => number\n}\n\n/**\n * Configuration for A* algorithm.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface AstarConfig<E, N> {\n  source: NodeIndex\n  target: NodeIndex\n  cost: (edgeData: E) => number\n  heuristic: (sourceNodeData: N, targetNodeData: N) => number\n}\n\n/**\n * Configuration for Bellman-Ford algorithm.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface BellmanFordConfig<E> {\n  source: NodeIndex\n  target: NodeIndex\n  cost: (edgeData: E) => number\n}\n\n/**\n * Find the shortest path between two nodes using Dijkstra's algorithm.\n *\n * Dijkstra's algorithm works with non-negative edge weights and finds the shortest\n * path from a source node to a target node in O((V + E) log V) time complexity.\n *\n * @example\n * ```ts\n * import { Graph, Option } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, 5)\n *   Graph.addEdge(mutable, a, c, 10)\n *   Graph.addEdge(mutable, b, c, 2)\n * })\n *\n * const result = Graph.dijkstra(graph, { source: 0, target: 2, cost: (edgeData) => edgeData })\n * if (Option.isSome(result)) {\n *   console.log(result.value.path) // [0, 1, 2] - shortest path A->B->C\n *   console.log(result.value.distance) // 7 - total distance\n * }\n * ```\n *\n * @since 3.18.0\n * @category algorithms\n */\nexport const dijkstra = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  config: DijkstraConfig<E>\n): Option.Option<PathResult<E>> => {\n  const { cost, source, target } = config\n  // Validate that source and target nodes exist\n  if (!graph.nodes.has(source)) {\n    throw missingNode(source)\n  }\n  if (!graph.nodes.has(target)) {\n    throw missingNode(target)\n  }\n\n  // Early return if source equals target\n  if (source === target) {\n    return Option.some({\n      path: [source],\n      distance: 0,\n      costs: []\n    })\n  }\n\n  // Distance tracking and priority queue simulation\n  const distances = new Map<NodeIndex, number>()\n  const previous = new Map<NodeIndex, { node: NodeIndex; edgeData: E } | null>()\n  const visited = new Set<NodeIndex>()\n\n  // Initialize distances\n  // Iterate directly over node keys\n  for (const node of graph.nodes.keys()) {\n    distances.set(node, node === source ? 0 : Infinity)\n    previous.set(node, null)\n  }\n\n  // Simple priority queue using array (can be optimized with proper heap)\n  const priorityQueue: Array<{ node: NodeIndex; distance: number }> = [\n    { node: source, distance: 0 }\n  ]\n\n  while (priorityQueue.length > 0) {\n    // Find minimum distance node (priority queue extract-min)\n    let minIndex = 0\n    for (let i = 1; i < priorityQueue.length; i++) {\n      if (priorityQueue[i].distance < priorityQueue[minIndex].distance) {\n        minIndex = i\n      }\n    }\n\n    const current = priorityQueue.splice(minIndex, 1)[0]\n    const currentNode = current.node\n\n    // Skip if already visited (can happen with duplicate entries)\n    if (visited.has(currentNode)) {\n      continue\n    }\n\n    visited.add(currentNode)\n\n    // Early termination if we reached the target\n    if (currentNode === target) {\n      break\n    }\n\n    // Get current distance\n    const currentDistance = distances.get(currentNode)!\n\n    // Examine all outgoing edges\n    const adjacencyList = graph.adjacency.get(currentNode)\n    if (adjacencyList !== undefined) {\n      for (const edgeIndex of adjacencyList) {\n        const edge = graph.edges.get(edgeIndex)\n        if (edge !== undefined) {\n          const neighbor = edge.target\n          const weight = cost(edge.data)\n\n          // Validate non-negative weights\n          if (weight < 0) {\n            throw new Error(`Dijkstra's algorithm requires non-negative edge weights, found ${weight}`)\n          }\n\n          const newDistance = currentDistance + weight\n          const neighborDistance = distances.get(neighbor)!\n\n          // Relaxation step\n          if (newDistance < neighborDistance) {\n            distances.set(neighbor, newDistance)\n            previous.set(neighbor, { node: currentNode, edgeData: edge.data })\n\n            // Add to priority queue if not visited\n            if (!visited.has(neighbor)) {\n              priorityQueue.push({ node: neighbor, distance: newDistance })\n            }\n          }\n        }\n      }\n    }\n  }\n\n  // Check if target is reachable\n  const targetDistance = distances.get(target)!\n  if (targetDistance === Infinity) {\n    return Option.none() // No path exists\n  }\n\n  // Reconstruct path\n  const path: Array<NodeIndex> = []\n  const costs: Array<E> = []\n  let currentNode: NodeIndex | null = target\n\n  while (currentNode !== null) {\n    path.unshift(currentNode)\n    const prev: { node: NodeIndex; edgeData: E } | null = previous.get(currentNode)!\n    if (prev !== null) {\n      costs.unshift(prev.edgeData)\n      currentNode = prev.node\n    } else {\n      currentNode = null\n    }\n  }\n\n  return Option.some({\n    path,\n    distance: targetDistance,\n    costs\n  })\n}\n\n/**\n * Result of all-pairs shortest path computation.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface AllPairsResult<E> {\n  readonly distances: Map<NodeIndex, Map<NodeIndex, number>>\n  readonly paths: Map<NodeIndex, Map<NodeIndex, Array<NodeIndex> | null>>\n  readonly costs: Map<NodeIndex, Map<NodeIndex, Array<E>>>\n}\n\n/**\n * Find shortest paths between all pairs of nodes using Floyd-Warshall algorithm.\n *\n * Floyd-Warshall algorithm computes shortest paths between all pairs of nodes in O(V³) time.\n * It can handle negative edge weights and detect negative cycles.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, 3)\n *   Graph.addEdge(mutable, b, c, 2)\n *   Graph.addEdge(mutable, a, c, 7)\n * })\n *\n * const result = Graph.floydWarshall(graph, (edgeData) => edgeData)\n * const distanceAToC = result.distances.get(0)?.get(2) // 5 (A->B->C)\n * const pathAToC = result.paths.get(0)?.get(2) // [0, 1, 2]\n * ```\n *\n * @since 3.18.0\n * @category algorithms\n */\nexport const floydWarshall = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  cost: (edgeData: E) => number\n): AllPairsResult<E> => {\n  // Get all nodes for Floyd-Warshall algorithm (needs array for nested iteration)\n  const allNodes = Array.from(graph.nodes.keys())\n\n  // Initialize distance matrix\n  const dist = new Map<NodeIndex, Map<NodeIndex, number>>()\n  const next = new Map<NodeIndex, Map<NodeIndex, NodeIndex | null>>()\n  const edgeMatrix = new Map<NodeIndex, Map<NodeIndex, E | null>>()\n\n  // Initialize with infinity for all pairs\n  for (const i of allNodes) {\n    dist.set(i, new Map())\n    next.set(i, new Map())\n    edgeMatrix.set(i, new Map())\n\n    for (const j of allNodes) {\n      dist.get(i)!.set(j, i === j ? 0 : Infinity)\n      next.get(i)!.set(j, null)\n      edgeMatrix.get(i)!.set(j, null)\n    }\n  }\n\n  // Set edge weights\n  for (const [, edgeData] of graph.edges) {\n    const weight = cost(edgeData.data)\n    const i = edgeData.source\n    const j = edgeData.target\n\n    // Use minimum weight if multiple edges exist\n    const currentWeight = dist.get(i)!.get(j)!\n    if (weight < currentWeight) {\n      dist.get(i)!.set(j, weight)\n      next.get(i)!.set(j, j)\n      edgeMatrix.get(i)!.set(j, edgeData.data)\n    }\n  }\n\n  // Floyd-Warshall main loop\n  for (const k of allNodes) {\n    for (const i of allNodes) {\n      for (const j of allNodes) {\n        const distIK = dist.get(i)!.get(k)!\n        const distKJ = dist.get(k)!.get(j)!\n        const distIJ = dist.get(i)!.get(j)!\n\n        if (distIK !== Infinity && distKJ !== Infinity && distIK + distKJ < distIJ) {\n          dist.get(i)!.set(j, distIK + distKJ)\n          next.get(i)!.set(j, next.get(i)!.get(k)!)\n        }\n      }\n    }\n  }\n\n  // Check for negative cycles\n  for (const i of allNodes) {\n    if (dist.get(i)!.get(i)! < 0) {\n      throw new Error(`Negative cycle detected involving node ${i}`)\n    }\n  }\n\n  // Build result paths and edge weights\n  const paths = new Map<NodeIndex, Map<NodeIndex, Array<NodeIndex> | null>>()\n  const resultCosts = new Map<NodeIndex, Map<NodeIndex, Array<E>>>()\n\n  for (const i of allNodes) {\n    paths.set(i, new Map())\n    resultCosts.set(i, new Map())\n\n    for (const j of allNodes) {\n      if (i === j) {\n        paths.get(i)!.set(j, [i])\n        resultCosts.get(i)!.set(j, [])\n      } else if (dist.get(i)!.get(j)! === Infinity) {\n        paths.get(i)!.set(j, null)\n        resultCosts.get(i)!.set(j, [])\n      } else {\n        // Reconstruct path iteratively\n        const path: Array<NodeIndex> = []\n        const weights: Array<E> = []\n        let current = i\n\n        path.push(current)\n        while (current !== j) {\n          const nextNode = next.get(current)!.get(j)!\n          if (nextNode === null) break\n\n          const edgeData = edgeMatrix.get(current)!.get(nextNode)!\n          if (edgeData !== null) {\n            weights.push(edgeData)\n          }\n\n          current = nextNode\n          path.push(current)\n        }\n\n        paths.get(i)!.set(j, path)\n        resultCosts.get(i)!.set(j, weights)\n      }\n    }\n  }\n\n  return {\n    distances: dist,\n    paths,\n    costs: resultCosts\n  }\n}\n\n/**\n * Find the shortest path between two nodes using A* pathfinding algorithm.\n *\n * A* is an extension of Dijkstra's algorithm that uses a heuristic function to guide\n * the search towards the target, potentially finding paths faster than Dijkstra's.\n * The heuristic must be admissible (never overestimate the actual cost).\n *\n * @example\n * ```ts\n * import { Graph, Option } from \"effect\"\n *\n * const graph = Graph.directed<{x: number, y: number}, number>((mutable) => {\n *   const a = Graph.addNode(mutable, {x: 0, y: 0})\n *   const b = Graph.addNode(mutable, {x: 1, y: 0})\n *   const c = Graph.addNode(mutable, {x: 2, y: 0})\n *   Graph.addEdge(mutable, a, b, 1)\n *   Graph.addEdge(mutable, b, c, 1)\n * })\n *\n * // Manhattan distance heuristic\n * const heuristic = (nodeData: {x: number, y: number}, targetData: {x: number, y: number}) =>\n *   Math.abs(nodeData.x - targetData.x) + Math.abs(nodeData.y - targetData.y)\n *\n * const result = Graph.astar(graph, { source: 0, target: 2, cost: (edgeData) => edgeData, heuristic })\n * if (Option.isSome(result)) {\n *   console.log(result.value.path) // [0, 1, 2] - shortest path\n *   console.log(result.value.distance) // 2 - total distance\n * }\n * ```\n *\n * @since 3.18.0\n * @category algorithms\n */\nexport const astar = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  config: AstarConfig<E, N>\n): Option.Option<PathResult<E>> => {\n  const { cost, heuristic, source, target } = config\n  // Validate that source and target nodes exist\n  if (!graph.nodes.has(source)) {\n    throw missingNode(source)\n  }\n  if (!graph.nodes.has(target)) {\n    throw missingNode(target)\n  }\n\n  // Early return if source equals target\n  if (source === target) {\n    return Option.some({\n      path: [source],\n      distance: 0,\n      costs: []\n    })\n  }\n\n  // Get target node data for heuristic calculations\n  const targetNodeData = graph.nodes.get(target)\n  if (targetNodeData === undefined) {\n    throw new Error(`Target node ${target} data not found`)\n  }\n\n  // Distance tracking (g-score) and f-score (g + h)\n  const gScore = new Map<NodeIndex, number>()\n  const fScore = new Map<NodeIndex, number>()\n  const previous = new Map<NodeIndex, { node: NodeIndex; edgeData: E } | null>()\n  const visited = new Set<NodeIndex>()\n\n  // Initialize scores\n  // Iterate directly over node keys\n  for (const node of graph.nodes.keys()) {\n    gScore.set(node, node === source ? 0 : Infinity)\n    fScore.set(node, Infinity)\n    previous.set(node, null)\n  }\n\n  // Calculate initial f-score for source\n  const sourceNodeData = graph.nodes.get(source)\n  if (sourceNodeData !== undefined) {\n    const h = heuristic(sourceNodeData, targetNodeData)\n    fScore.set(source, h)\n  }\n\n  // Priority queue using f-score (total estimated cost)\n  const openSet: Array<{ node: NodeIndex; fScore: number }> = [\n    { node: source, fScore: fScore.get(source)! }\n  ]\n\n  while (openSet.length > 0) {\n    // Find node with lowest f-score\n    let minIndex = 0\n    for (let i = 1; i < openSet.length; i++) {\n      if (openSet[i].fScore < openSet[minIndex].fScore) {\n        minIndex = i\n      }\n    }\n\n    const current = openSet.splice(minIndex, 1)[0]\n    const currentNode = current.node\n\n    // Skip if already visited\n    if (visited.has(currentNode)) {\n      continue\n    }\n\n    visited.add(currentNode)\n\n    // Early termination if we reached the target\n    if (currentNode === target) {\n      break\n    }\n\n    // Get current g-score\n    const currentGScore = gScore.get(currentNode)!\n\n    // Examine all outgoing edges\n    const adjacencyList = graph.adjacency.get(currentNode)\n    if (adjacencyList !== undefined) {\n      for (const edgeIndex of adjacencyList) {\n        const edge = graph.edges.get(edgeIndex)\n        if (edge !== undefined) {\n          const neighbor = edge.target\n          const weight = cost(edge.data)\n\n          // Validate non-negative weights\n          if (weight < 0) {\n            throw new Error(`A* algorithm requires non-negative edge weights, found ${weight}`)\n          }\n\n          const tentativeGScore = currentGScore + weight\n          const neighborGScore = gScore.get(neighbor)!\n\n          // If this path to neighbor is better than any previous one\n          if (tentativeGScore < neighborGScore) {\n            // Update g-score and previous\n            gScore.set(neighbor, tentativeGScore)\n            previous.set(neighbor, { node: currentNode, edgeData: edge.data })\n\n            // Calculate f-score using heuristic\n            const neighborNodeData = graph.nodes.get(neighbor)\n            if (neighborNodeData !== undefined) {\n              const h = heuristic(neighborNodeData, targetNodeData)\n              const f = tentativeGScore + h\n              fScore.set(neighbor, f)\n\n              // Add to open set if not visited\n              if (!visited.has(neighbor)) {\n                openSet.push({ node: neighbor, fScore: f })\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n\n  // Check if target is reachable\n  const targetGScore = gScore.get(target)!\n  if (targetGScore === Infinity) {\n    return Option.none() // No path exists\n  }\n\n  // Reconstruct path\n  const path: Array<NodeIndex> = []\n  const costs: Array<E> = []\n  let currentNode: NodeIndex | null = target\n\n  while (currentNode !== null) {\n    path.unshift(currentNode)\n    const prev: { node: NodeIndex; edgeData: E } | null = previous.get(currentNode)!\n    if (prev !== null) {\n      costs.unshift(prev.edgeData)\n      currentNode = prev.node\n    } else {\n      currentNode = null\n    }\n  }\n\n  return Option.some({\n    path,\n    distance: targetGScore,\n    costs\n  })\n}\n\n/**\n * Find the shortest path between two nodes using Bellman-Ford algorithm.\n *\n * Bellman-Ford algorithm can handle negative edge weights and detects negative cycles.\n * It has O(VE) time complexity, slower than Dijkstra's but more versatile.\n * Returns Option.none() if a negative cycle is detected that affects the path.\n *\n * @example\n * ```ts\n * import { Graph, Option } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, -1)  // Negative weight allowed\n *   Graph.addEdge(mutable, b, c, 3)\n *   Graph.addEdge(mutable, a, c, 5)\n * })\n *\n * const result = Graph.bellmanFord(graph, { source: 0, target: 2, cost: (edgeData) => edgeData })\n * if (Option.isSome(result)) {\n *   console.log(result.value.path) // [0, 1, 2] - shortest path A->B->C\n *   console.log(result.value.distance) // 2 - total distance\n * }\n * ```\n *\n * @since 3.18.0\n * @category algorithms\n */\nexport const bellmanFord = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  config: BellmanFordConfig<E>\n): Option.Option<PathResult<E>> => {\n  const { cost, source, target } = config\n  // Validate that source and target nodes exist\n  if (!graph.nodes.has(source)) {\n    throw missingNode(source)\n  }\n  if (!graph.nodes.has(target)) {\n    throw missingNode(target)\n  }\n\n  // Early return if source equals target\n  if (source === target) {\n    return Option.some({\n      path: [source],\n      distance: 0,\n      costs: []\n    })\n  }\n\n  // Initialize distances and predecessors\n  const distances = new Map<NodeIndex, number>()\n  const previous = new Map<NodeIndex, { node: NodeIndex; edgeData: E } | null>()\n  // Iterate directly over node keys\n\n  for (const node of graph.nodes.keys()) {\n    distances.set(node, node === source ? 0 : Infinity)\n    previous.set(node, null)\n  }\n\n  // Collect all edges for relaxation\n  const edges: Array<{ source: NodeIndex; target: NodeIndex; weight: number; edgeData: E }> = []\n  for (const [, edgeData] of graph.edges) {\n    const weight = cost(edgeData.data)\n    edges.push({\n      source: edgeData.source,\n      target: edgeData.target,\n      weight,\n      edgeData: edgeData.data\n    })\n  }\n\n  // Relax edges up to V-1 times\n  const nodeCount = graph.nodes.size\n  for (let i = 0; i < nodeCount - 1; i++) {\n    let hasUpdate = false\n\n    for (const edge of edges) {\n      const sourceDistance = distances.get(edge.source)!\n      const targetDistance = distances.get(edge.target)!\n\n      // Relaxation step\n      if (sourceDistance !== Infinity && sourceDistance + edge.weight < targetDistance) {\n        distances.set(edge.target, sourceDistance + edge.weight)\n        previous.set(edge.target, { node: edge.source, edgeData: edge.edgeData })\n        hasUpdate = true\n      }\n    }\n\n    // Early termination if no updates\n    if (!hasUpdate) {\n      break\n    }\n  }\n\n  // Check for negative cycles\n  for (const edge of edges) {\n    const sourceDistance = distances.get(edge.source)!\n    const targetDistance = distances.get(edge.target)!\n\n    if (sourceDistance !== Infinity && sourceDistance + edge.weight < targetDistance) {\n      // Negative cycle detected - check if it affects the path to target\n      const affectedNodes = new Set<NodeIndex>()\n      const queue = [edge.target]\n\n      while (queue.length > 0) {\n        const node = queue.shift()!\n        if (affectedNodes.has(node)) continue\n        affectedNodes.add(node)\n\n        // Add all nodes reachable from this node\n        const adjacencyList = graph.adjacency.get(node)\n        if (adjacencyList !== undefined) {\n          for (const edgeIndex of adjacencyList) {\n            const edge = graph.edges.get(edgeIndex)\n            if (edge !== undefined) {\n              queue.push(edge.target)\n            }\n          }\n        }\n      }\n\n      // If target is affected by negative cycle, return null\n      if (affectedNodes.has(target)) {\n        return Option.none()\n      }\n    }\n  }\n\n  // Check if target is reachable\n  const targetDistance = distances.get(target)!\n  if (targetDistance === Infinity) {\n    return Option.none() // No path exists\n  }\n\n  // Reconstruct path\n  const path: Array<NodeIndex> = []\n  const costs: Array<E> = []\n  let currentNode: NodeIndex | null = target\n\n  while (currentNode !== null) {\n    path.unshift(currentNode)\n    const prev: { node: NodeIndex; edgeData: E } | null = previous.get(currentNode)!\n    if (prev !== null) {\n      costs.unshift(prev.edgeData)\n      currentNode = prev.node\n    } else {\n      currentNode = null\n    }\n  }\n\n  return Option.some({\n    path,\n    distance: targetDistance,\n    costs\n  })\n}\n\n/**\n * Concrete class for iterables that produce [NodeIndex, NodeData] tuples.\n *\n * This class provides a common abstraction for all iterables that return node data,\n * including traversal iterators (DFS, BFS, etc.) and element iterators (nodes, externals).\n * It uses a mapEntry function pattern for flexible iteration and transformation.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   Graph.addEdge(mutable, a, b, 1)\n * })\n *\n * // Both traversal and element iterators return NodeWalker\n * const dfsNodes: Graph.NodeWalker<string> = Graph.dfs(graph, { start: [0] })\n * const allNodes: Graph.NodeWalker<string> = Graph.nodes(graph)\n *\n * // Common interface for working with node iterables\n * function processNodes<N>(nodeIterable: Graph.NodeWalker<N>): Array<number> {\n *   return Array.from(Graph.indices(nodeIterable))\n * }\n *\n * // Access node data using values() or entries()\n * const nodeData = Array.from(Graph.values(dfsNodes)) // [\"A\", \"B\"]\n * const nodeEntries = Array.from(Graph.entries(allNodes)) // [[0, \"A\"], [1, \"B\"]]\n * ```\n *\n * @since 3.18.0\n * @category models\n */\nexport class Walker<T, N> implements Iterable<[T, N]> {\n  /**\n   * @since 3.18.0\n   */\n  // @ts-ignore\n  readonly [Symbol.iterator]: () => Iterator<[T, N]>\n\n  /**\n   * Visits each element and maps it to a value using the provided function.\n   *\n   * Takes a function that receives the index and data,\n   * and returns an iterable of the mapped values. Skips elements that\n   * no longer exist in the graph.\n   *\n   * @example\n   * ```ts\n   * import { Graph } from \"effect\"\n   *\n   * const graph = Graph.directed<string, number>((mutable) => {\n   *   const a = Graph.addNode(mutable, \"A\")\n   *   const b = Graph.addNode(mutable, \"B\")\n   *   Graph.addEdge(mutable, a, b, 1)\n   * })\n   *\n   * const dfs = Graph.dfs(graph, { start: [0] })\n   *\n   * // Map to just the node data\n   * const values = Array.from(dfs.visit((index, data) => data))\n   * console.log(values) // [\"A\", \"B\"]\n   *\n   * // Map to custom objects\n   * const custom = Array.from(dfs.visit((index, data) => ({ id: index, name: data })))\n   * console.log(custom) // [{ id: 0, name: \"A\" }, { id: 1, name: \"B\" }]\n   * ```\n   *\n   * @since 3.18.0\n   * @category iterators\n   */\n  readonly visit: <U>(f: (index: T, data: N) => U) => Iterable<U>\n\n  constructor(\n    /**\n     * Visits each element and maps it to a value using the provided function.\n     *\n     * Takes a function that receives the index and data,\n     * and returns an iterable of the mapped values. Skips elements that\n     * no longer exist in the graph.\n     *\n     * @example\n     * ```ts\n     * import { Graph } from \"effect\"\n     *\n     * const graph = Graph.directed<string, number>((mutable) => {\n     *   const a = Graph.addNode(mutable, \"A\")\n     *   const b = Graph.addNode(mutable, \"B\")\n     *   Graph.addEdge(mutable, a, b, 1)\n     * })\n     *\n     * const dfs = Graph.dfs(graph, { start: [0] })\n     *\n     * // Map to just the node data\n     * const values = Array.from(dfs.visit((index, data) => data))\n     * console.log(values) // [\"A\", \"B\"]\n     *\n     * // Map to custom objects\n     * const custom = Array.from(dfs.visit((index, data) => ({ id: index, name: data })))\n     * console.log(custom) // [{ id: 0, name: \"A\" }, { id: 1, name: \"B\" }]\n     * ```\n     *\n     * @since 3.18.0\n     * @category iterators\n     */\n    visit: <U>(f: (index: T, data: N) => U) => Iterable<U>\n  ) {\n    this.visit = visit\n    this[Symbol.iterator] = visit((index, data) => [index, data] as [T, N])[Symbol.iterator]\n  }\n}\n\n/**\n * Type alias for node iteration using Walker.\n * NodeWalker is represented as Walker<NodeIndex, N>.\n *\n * @since 3.18.0\n * @category models\n */\nexport type NodeWalker<N> = Walker<NodeIndex, N>\n\n/**\n * Type alias for edge iteration using Walker.\n * EdgeWalker is represented as Walker<EdgeIndex, Edge<E>>.\n *\n * @since 3.18.0\n * @category models\n */\nexport type EdgeWalker<E> = Walker<EdgeIndex, Edge<E>>\n\n/**\n * Returns an iterator over the indices in the walker.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   Graph.addEdge(mutable, a, b, 1)\n * })\n *\n * const dfs = Graph.dfs(graph, { start: [0] })\n * const indices = Array.from(Graph.indices(dfs))\n * console.log(indices) // [0, 1]\n * ```\n *\n * @since 3.18.0\n * @category utilities\n */\nexport const indices = <T, N>(walker: Walker<T, N>): Iterable<T> => walker.visit((index, _) => index)\n\n/**\n * Returns an iterator over the values (data) in the walker.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   Graph.addEdge(mutable, a, b, 1)\n * })\n *\n * const dfs = Graph.dfs(graph, { start: [0] })\n * const values = Array.from(Graph.values(dfs))\n * console.log(values) // [\"A\", \"B\"]\n * ```\n *\n * @since 3.18.0\n * @category utilities\n */\nexport const values = <T, N>(walker: Walker<T, N>): Iterable<N> => walker.visit((_, data) => data)\n\n/**\n * Returns an iterator over [index, data] entries in the walker.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   Graph.addEdge(mutable, a, b, 1)\n * })\n *\n * const dfs = Graph.dfs(graph, { start: [0] })\n * const entries = Array.from(Graph.entries(dfs))\n * console.log(entries) // [[0, \"A\"], [1, \"B\"]]\n * ```\n *\n * @since 3.18.0\n * @category utilities\n */\nexport const entries = <T, N>(walker: Walker<T, N>): Iterable<[T, N]> =>\n  walker.visit((index, data) => [index, data] as [T, N])\n\n/**\n * Configuration for graph search iterators.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface SearchConfig {\n  readonly start?: Array<NodeIndex>\n  readonly direction?: Direction\n}\n\n/**\n * Creates a new DFS iterator with optional configuration.\n *\n * The iterator maintains a stack of nodes to visit and tracks discovered nodes.\n * It provides lazy evaluation of the depth-first search.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, 1)\n *   Graph.addEdge(mutable, b, c, 1)\n * })\n *\n * // Start from a specific node\n * const dfs1 = Graph.dfs(graph, { start: [0] })\n * for (const nodeIndex of Graph.indices(dfs1)) {\n *   console.log(nodeIndex) // Traverses in DFS order: 0, 1, 2\n * }\n *\n * // Empty iterator (no starting nodes)\n * const dfs2 = Graph.dfs(graph)\n * // Can be used programmatically\n * ```\n *\n * @since 3.18.0\n * @category iterators\n */\nexport const dfs = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  config: SearchConfig = {}\n): NodeWalker<N> => {\n  const start = config.start ?? []\n  const direction = config.direction ?? \"outgoing\"\n\n  // Validate that all start nodes exist\n  for (const nodeIndex of start) {\n    if (!hasNode(graph, nodeIndex)) {\n      throw missingNode(nodeIndex)\n    }\n  }\n\n  return new Walker((f) => ({\n    [Symbol.iterator]: () => {\n      const stack = [...start]\n      const discovered = new Set<NodeIndex>()\n\n      const nextMapped = () => {\n        while (stack.length > 0) {\n          const current = stack.pop()!\n\n          if (discovered.has(current)) {\n            continue\n          }\n\n          discovered.add(current)\n\n          const nodeDataOption = graph.nodes.get(current)\n          if (nodeDataOption === undefined) {\n            continue\n          }\n\n          const neighbors = neighborsDirected(graph, current, direction)\n          for (let i = neighbors.length - 1; i >= 0; i--) {\n            const neighbor = neighbors[i]\n            if (!discovered.has(neighbor)) {\n              stack.push(neighbor)\n            }\n          }\n\n          return { done: false, value: f(current, nodeDataOption) }\n        }\n\n        return { done: true, value: undefined } as const\n      }\n\n      return { next: nextMapped }\n    }\n  }))\n}\n\n/**\n * Creates a new BFS iterator with optional configuration.\n *\n * The iterator maintains a queue of nodes to visit and tracks discovered nodes.\n * It provides lazy evaluation of the breadth-first search.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, 1)\n *   Graph.addEdge(mutable, b, c, 1)\n * })\n *\n * // Start from a specific node\n * const bfs1 = Graph.bfs(graph, { start: [0] })\n * for (const nodeIndex of Graph.indices(bfs1)) {\n *   console.log(nodeIndex) // Traverses in BFS order: 0, 1, 2\n * }\n *\n * // Empty iterator (no starting nodes)\n * const bfs2 = Graph.bfs(graph)\n * // Can be used programmatically\n * ```\n *\n * @since 3.18.0\n * @category iterators\n */\nexport const bfs = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  config: SearchConfig = {}\n): NodeWalker<N> => {\n  const start = config.start ?? []\n  const direction = config.direction ?? \"outgoing\"\n\n  // Validate that all start nodes exist\n  for (const nodeIndex of start) {\n    if (!hasNode(graph, nodeIndex)) {\n      throw missingNode(nodeIndex)\n    }\n  }\n\n  return new Walker((f) => ({\n    [Symbol.iterator]: () => {\n      const queue = [...start]\n      const discovered = new Set<NodeIndex>()\n\n      const nextMapped = () => {\n        while (queue.length > 0) {\n          const current = queue.shift()!\n\n          if (!discovered.has(current)) {\n            discovered.add(current)\n\n            const neighbors = neighborsDirected(graph, current, direction)\n            for (const neighbor of neighbors) {\n              if (!discovered.has(neighbor)) {\n                queue.push(neighbor)\n              }\n            }\n\n            const nodeData = getNode(graph, current)\n            if (Option.isSome(nodeData)) {\n              return { done: false, value: f(current, nodeData.value) }\n            }\n            return nextMapped()\n          }\n        }\n\n        return { done: true, value: undefined } as const\n      }\n\n      return { next: nextMapped }\n    }\n  }))\n}\n\n/**\n * Configuration options for topological sort iterator.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface TopoConfig {\n  readonly initials?: Array<NodeIndex>\n}\n\n/**\n * Creates a new topological sort iterator with optional configuration.\n *\n * The iterator uses Kahn's algorithm to lazily produce nodes in topological order.\n * Throws an error if the graph contains cycles.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, 1)\n *   Graph.addEdge(mutable, b, c, 1)\n * })\n *\n * // Standard topological sort\n * const topo1 = Graph.topo(graph)\n * for (const nodeIndex of Graph.indices(topo1)) {\n *   console.log(nodeIndex) // 0, 1, 2 (topological order)\n * }\n *\n * // With initial nodes\n * const topo2 = Graph.topo(graph, { initials: [0] })\n *\n * // Throws error for cyclic graph\n * const cyclicGraph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   Graph.addEdge(mutable, a, b, 1)\n *   Graph.addEdge(mutable, b, a, 2) // Creates cycle\n * })\n *\n * try {\n *   Graph.topo(cyclicGraph) // Throws: \"Cannot perform topological sort on cyclic graph\"\n * } catch (error) {\n *   console.log((error as Error).message)\n * }\n * ```\n *\n * @since 3.18.0\n * @category iterators\n */\nexport const topo = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  config: TopoConfig = {}\n): NodeWalker<N> => {\n  // Check if graph is acyclic first\n  if (!isAcyclic(graph)) {\n    throw new Error(\"Cannot perform topological sort on cyclic graph\")\n  }\n\n  const initials = config.initials ?? []\n\n  // Validate that all initial nodes exist\n  for (const nodeIndex of initials) {\n    if (!hasNode(graph, nodeIndex)) {\n      throw missingNode(nodeIndex)\n    }\n  }\n\n  return new Walker((f) => ({\n    [Symbol.iterator]: () => {\n      const inDegree = new Map<NodeIndex, number>()\n      const remaining = new Set<NodeIndex>()\n      const queue = [...initials]\n\n      // Initialize in-degree counts\n      for (const [nodeIndex] of graph.nodes) {\n        inDegree.set(nodeIndex, 0)\n        remaining.add(nodeIndex)\n      }\n\n      // Calculate in-degrees\n      for (const [, edgeData] of graph.edges) {\n        const currentInDegree = inDegree.get(edgeData.target) || 0\n        inDegree.set(edgeData.target, currentInDegree + 1)\n      }\n\n      // Add nodes with zero in-degree to queue if no initials provided\n      if (initials.length === 0) {\n        for (const [nodeIndex, degree] of inDegree) {\n          if (degree === 0) {\n            queue.push(nodeIndex)\n          }\n        }\n      }\n\n      const nextMapped = () => {\n        while (queue.length > 0) {\n          const current = queue.shift()!\n\n          if (remaining.has(current)) {\n            remaining.delete(current)\n\n            // Process outgoing edges, reducing in-degree of targets\n            const neighbors = neighborsDirected(graph, current, \"outgoing\")\n            for (const neighbor of neighbors) {\n              if (remaining.has(neighbor)) {\n                const currentInDegree = inDegree.get(neighbor) || 0\n                const newInDegree = currentInDegree - 1\n                inDegree.set(neighbor, newInDegree)\n\n                // If in-degree becomes 0, add to queue\n                if (newInDegree === 0) {\n                  queue.push(neighbor)\n                }\n              }\n            }\n\n            const nodeData = getNode(graph, current)\n            if (Option.isSome(nodeData)) {\n              return { done: false, value: f(current, nodeData.value) }\n            }\n            return nextMapped()\n          }\n        }\n\n        return { done: true, value: undefined } as const\n      }\n\n      return { next: nextMapped }\n    }\n  }))\n}\n\n/**\n * Creates a new DFS postorder iterator with optional configuration.\n *\n * The iterator maintains a stack with visit state tracking and emits nodes\n * in postorder (after all descendants have been processed). Essential for\n * dependency resolution and tree destruction algorithms.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const root = Graph.addNode(mutable, \"root\")\n *   const child1 = Graph.addNode(mutable, \"child1\")\n *   const child2 = Graph.addNode(mutable, \"child2\")\n *   Graph.addEdge(mutable, root, child1, 1)\n *   Graph.addEdge(mutable, root, child2, 1)\n * })\n *\n * // Postorder: children before parents\n * const postOrder = Graph.dfsPostOrder(graph, { start: [0] })\n * for (const node of postOrder) {\n *   console.log(node) // 1, 2, 0\n * }\n * ```\n *\n * @since 3.18.0\n * @category iterators\n */\nexport const dfsPostOrder = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  config: SearchConfig = {}\n): NodeWalker<N> => {\n  const start = config.start ?? []\n  const direction = config.direction ?? \"outgoing\"\n\n  // Validate that all start nodes exist\n  for (const nodeIndex of start) {\n    if (!hasNode(graph, nodeIndex)) {\n      throw missingNode(nodeIndex)\n    }\n  }\n\n  return new Walker((f) => ({\n    [Symbol.iterator]: () => {\n      const stack: Array<{ node: NodeIndex; visitedChildren: boolean }> = []\n      const discovered = new Set<NodeIndex>()\n      const finished = new Set<NodeIndex>()\n\n      // Initialize stack with start nodes\n      for (let i = start.length - 1; i >= 0; i--) {\n        stack.push({ node: start[i], visitedChildren: false })\n      }\n\n      const nextMapped = () => {\n        while (stack.length > 0) {\n          const current = stack[stack.length - 1]\n\n          if (!discovered.has(current.node)) {\n            discovered.add(current.node)\n            current.visitedChildren = false\n          }\n\n          if (!current.visitedChildren) {\n            current.visitedChildren = true\n            const neighbors = neighborsDirected(graph, current.node, direction)\n\n            for (let i = neighbors.length - 1; i >= 0; i--) {\n              const neighbor = neighbors[i]\n              if (!discovered.has(neighbor) && !finished.has(neighbor)) {\n                stack.push({ node: neighbor, visitedChildren: false })\n              }\n            }\n          } else {\n            const nodeToEmit = stack.pop()!.node\n\n            if (!finished.has(nodeToEmit)) {\n              finished.add(nodeToEmit)\n\n              const nodeData = getNode(graph, nodeToEmit)\n              if (Option.isSome(nodeData)) {\n                return { done: false, value: f(nodeToEmit, nodeData.value) }\n              }\n              return nextMapped()\n            }\n          }\n        }\n\n        return { done: true, value: undefined } as const\n      }\n\n      return { next: nextMapped }\n    }\n  }))\n}\n\n/**\n * Creates an iterator over all node indices in the graph.\n *\n * The iterator produces node indices in the order they were added to the graph.\n * This provides access to all nodes regardless of connectivity.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, 1)\n * })\n *\n * const indices = Array.from(Graph.indices(Graph.nodes(graph)))\n * console.log(indices) // [0, 1, 2]\n * ```\n *\n * @since 3.18.0\n * @category iterators\n */\nexport const nodes = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>\n): NodeWalker<N> =>\n  new Walker((f) => ({\n    [Symbol.iterator]() {\n      const nodeMap = graph.nodes\n      const iterator = nodeMap.entries()\n\n      return {\n        next() {\n          const result = iterator.next()\n          if (result.done) {\n            return { done: true, value: undefined }\n          }\n          const [nodeIndex, nodeData] = result.value\n          return { done: false, value: f(nodeIndex, nodeData) }\n        }\n      }\n    }\n  }))\n\n/**\n * Creates an iterator over all edge indices in the graph.\n *\n * The iterator produces edge indices in the order they were added to the graph.\n * This provides access to all edges regardless of connectivity.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const a = Graph.addNode(mutable, \"A\")\n *   const b = Graph.addNode(mutable, \"B\")\n *   const c = Graph.addNode(mutable, \"C\")\n *   Graph.addEdge(mutable, a, b, 1)\n *   Graph.addEdge(mutable, b, c, 2)\n * })\n *\n * const indices = Array.from(Graph.indices(Graph.edges(graph)))\n * console.log(indices) // [0, 1]\n * ```\n *\n * @since 3.18.0\n * @category iterators\n */\nexport const edges = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>\n): EdgeWalker<E> =>\n  new Walker((f) => ({\n    [Symbol.iterator]() {\n      const edgeMap = graph.edges\n      const iterator = edgeMap.entries()\n\n      return {\n        next() {\n          const result = iterator.next()\n          if (result.done) {\n            return { done: true, value: undefined }\n          }\n          const [edgeIndex, edgeData] = result.value\n          return { done: false, value: f(edgeIndex, edgeData) }\n        }\n      }\n    }\n  }))\n\n/**\n * Configuration for externals iterator.\n *\n * @since 3.18.0\n * @category models\n */\nexport interface ExternalsConfig {\n  readonly direction?: Direction\n}\n\n/**\n * Creates an iterator over external nodes (nodes without edges in specified direction).\n *\n * External nodes are nodes that have no outgoing edges (direction=\"outgoing\") or\n * no incoming edges (direction=\"incoming\"). These are useful for finding\n * sources, sinks, or isolated nodes.\n *\n * @example\n * ```ts\n * import { Graph } from \"effect\"\n *\n * const graph = Graph.directed<string, number>((mutable) => {\n *   const source = Graph.addNode(mutable, \"source\")     // 0 - no incoming\n *   const middle = Graph.addNode(mutable, \"middle\")     // 1 - has both\n *   const sink = Graph.addNode(mutable, \"sink\")         // 2 - no outgoing\n *   const isolated = Graph.addNode(mutable, \"isolated\") // 3 - no edges\n *\n *   Graph.addEdge(mutable, source, middle, 1)\n *   Graph.addEdge(mutable, middle, sink, 2)\n * })\n *\n * // Nodes with no outgoing edges (sinks + isolated)\n * const sinks = Array.from(Graph.indices(Graph.externals(graph, { direction: \"outgoing\" })))\n * console.log(sinks) // [2, 3]\n *\n * // Nodes with no incoming edges (sources + isolated)\n * const sources = Array.from(Graph.indices(Graph.externals(graph, { direction: \"incoming\" })))\n * console.log(sources) // [0, 3]\n * ```\n *\n * @since 3.18.0\n * @category iterators\n */\nexport const externals = <N, E, T extends Kind = \"directed\">(\n  graph: Graph<N, E, T> | MutableGraph<N, E, T>,\n  config: ExternalsConfig = {}\n): NodeWalker<N> => {\n  const direction = config.direction ?? \"outgoing\"\n\n  return new Walker((f) => ({\n    [Symbol.iterator]: () => {\n      const nodeMap = graph.nodes\n      const adjacencyMap = direction === \"incoming\"\n        ? graph.reverseAdjacency\n        : graph.adjacency\n\n      const nodeIterator = nodeMap.entries()\n\n      const nextMapped = () => {\n        let current = nodeIterator.next()\n        while (!current.done) {\n          const [nodeIndex, nodeData] = current.value\n          const adjacencyList = adjacencyMap.get(nodeIndex)\n\n          // Node is external if it has no edges in the specified direction\n          if (adjacencyList === undefined || adjacencyList.length === 0) {\n            return { done: false, value: f(nodeIndex, nodeData) }\n          }\n          current = nodeIterator.next()\n        }\n\n        return { done: true, value: undefined } as const\n      }\n\n      return { next: nextMapped }\n    }\n  }))\n}\n"
  },
  {
    "path": "packages/effect/src/GroupBy.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/groupBy.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate } from \"./Predicate.js\"\nimport type * as Queue from \"./Queue.js\"\nimport type * as Stream from \"./Stream.js\"\nimport type * as Take from \"./Take.js\"\nimport type { Covariant, NoInfer } from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const GroupByTypeId: unique symbol = internal.GroupByTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type GroupByTypeId = typeof GroupByTypeId\n\n/**\n * Representation of a grouped stream. This allows to filter which groups will\n * be processed. Once this is applied all groups will be processed in parallel\n * and the results will be merged in arbitrary order.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface GroupBy<out K, out V, out E = never, out R = never> extends GroupBy.Variance<K, V, E, R>, Pipeable {\n  readonly grouped: Stream.Stream<readonly [K, Queue.Dequeue<Take.Take<V, E>>], E, R>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace GroupBy {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out K, out V, out E, out R> {\n    readonly [GroupByTypeId]: {\n      readonly _K: Covariant<K>\n      readonly _V: Covariant<V>\n      readonly _E: Covariant<E>\n      readonly _R: Covariant<R>\n    }\n  }\n}\n\n/**\n * Run the function across all groups, collecting the results in an\n * arbitrary order.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const evaluate: {\n  <K, V, E, A, E2, R2>(\n    f: (key: K, stream: Stream.Stream<V, E, never>) => Stream.Stream<A, E2, R2>,\n    options?: { readonly bufferSize?: number | undefined } | undefined\n  ): <R>(self: GroupBy<K, V, E, R>) => Stream.Stream<A, E | E2, R2 | R>\n  <K, V, E, R, A, E2, R2>(\n    self: GroupBy<K, V, E, R>,\n    f: (key: K, stream: Stream.Stream<V, E, never>) => Stream.Stream<A, E2, R2>,\n    options?: { readonly bufferSize?: number | undefined } | undefined\n  ): Stream.Stream<A, E | E2, R | R2>\n} = internal.evaluate\n\n/**\n * Filter the groups to be processed.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const filter: {\n  <K>(predicate: Predicate<NoInfer<K>>): <V, E, R>(self: GroupBy<K, V, E, R>) => GroupBy<K, V, E, R>\n  <K, V, E, R>(self: GroupBy<K, V, E, R>, predicate: Predicate<K>): GroupBy<K, V, E, R>\n} = internal.filter\n\n/**\n * Only consider the first `n` groups found in the `Stream`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const first: {\n  (n: number): <K, V, E, R>(self: GroupBy<K, V, E, R>) => GroupBy<K, V, E, R>\n  <K, V, E, R>(self: GroupBy<K, V, E, R>, n: number): GroupBy<K, V, E, R>\n} = internal.first\n\n/**\n * Constructs a `GroupBy` from a `Stream`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <K, V, E, R>(\n  grouped: Stream.Stream<readonly [K, Queue.Dequeue<Take.Take<V, E>>], E, R>\n) => GroupBy<K, V, E, R> = internal.make\n"
  },
  {
    "path": "packages/effect/src/HKT.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n */\nexport declare const URI: unique symbol\n\n/**\n * @since 2.0.0\n */\nexport interface TypeClass<F extends TypeLambda> {\n  readonly [URI]?: F\n}\n\n/**\n * @since 2.0.0\n */\nexport interface TypeLambda {\n  readonly In: unknown\n  readonly Out2: unknown\n  readonly Out1: unknown\n  readonly Target: unknown\n}\n\n/**\n * @since 2.0.0\n */\nexport type Kind<F extends TypeLambda, In, Out2, Out1, Target> = F extends {\n  readonly type: unknown\n} ? (F & {\n    readonly In: In\n    readonly Out2: Out2\n    readonly Out1: Out1\n    readonly Target: Target\n  })[\"type\"]\n  : {\n    readonly F: F\n    readonly In: Types.Contravariant<In>\n    readonly Out2: Types.Covariant<Out2>\n    readonly Out1: Types.Covariant<Out1>\n    readonly Target: Types.Invariant<Target>\n  }\n"
  },
  {
    "path": "packages/effect/src/Hash.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport { pipe } from \"./Function.js\"\nimport { globalValue } from \"./GlobalValue.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport { structuralRegionState } from \"./Utils.js\"\n\n/** @internal */\nconst randomHashCache = globalValue(\n  Symbol.for(\"effect/Hash/randomHashCache\"),\n  () => new WeakMap<object, number>()\n)\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const symbol: unique symbol = Symbol.for(\"effect/Hash\")\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Hash {\n  [symbol](): number\n}\n\n/**\n * @since 2.0.0\n * @category hashing\n */\nexport const hash: <A>(self: A) => number = <A>(self: A) => {\n  if (structuralRegionState.enabled === true) {\n    return 0\n  }\n\n  switch (typeof self) {\n    case \"number\":\n      return number(self)\n    case \"bigint\":\n      return string(self.toString(10))\n    case \"boolean\":\n      return string(String(self))\n    case \"symbol\":\n      return string(String(self))\n    case \"string\":\n      return string(self)\n    case \"undefined\":\n      return string(\"undefined\")\n    case \"function\":\n    case \"object\": {\n      if (self === null) {\n        return string(\"null\")\n      } else if (self instanceof Date) {\n        if (Number.isNaN(self.getTime())) {\n          return string(\"Invalid Date\")\n        }\n        return hash(self.toISOString())\n      } else if (self instanceof URL) {\n        return hash(self.href)\n      } else if (isHash(self)) {\n        return self[symbol]()\n      } else {\n        return random(self)\n      }\n    }\n    default:\n      throw new Error(\n        `BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`\n      )\n  }\n}\n\n/**\n * @since 2.0.0\n * @category hashing\n */\nexport const random: <A extends object>(self: A) => number = (self) => {\n  if (!randomHashCache.has(self)) {\n    randomHashCache.set(self, number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)))\n  }\n  return randomHashCache.get(self)!\n}\n\n/**\n * @since 2.0.0\n * @category hashing\n */\nexport const combine: (b: number) => (self: number) => number = (b) => (self) => (self * 53) ^ b\n\n/**\n * @since 2.0.0\n * @category hashing\n */\nexport const optimize = (n: number): number => (n & 0xbfffffff) | ((n >>> 1) & 0x40000000)\n\n/**\n * @since 2.0.0\n * @category guards\n */\nexport const isHash = (u: unknown): u is Hash => hasProperty(u, symbol)\n\n/**\n * @since 2.0.0\n * @category hashing\n */\nexport const number = (n: number) => {\n  if (n !== n || n === Infinity) {\n    return 0\n  }\n  let h = n | 0\n  if (h !== n) {\n    h ^= n * 0xffffffff\n  }\n  while (n > 0xffffffff) {\n    h ^= n /= 0xffffffff\n  }\n  return optimize(h)\n}\n\n/**\n * @since 2.0.0\n * @category hashing\n */\nexport const string = (str: string) => {\n  let h = 5381, i = str.length\n  while (i) {\n    h = (h * 33) ^ str.charCodeAt(--i)\n  }\n  return optimize(h)\n}\n\n/**\n * @since 2.0.0\n * @category hashing\n */\nexport const structureKeys = <A extends object>(o: A, keys: ReadonlyArray<keyof A>) => {\n  let h = 12289\n  for (let i = 0; i < keys.length; i++) {\n    h ^= pipe(string(keys[i]! as string), combine(hash((o as any)[keys[i]!])))\n  }\n  return optimize(h)\n}\n\n/**\n * @since 2.0.0\n * @category hashing\n */\nexport const structure = <A extends object>(o: A) =>\n  structureKeys(o, Object.keys(o) as unknown as ReadonlyArray<keyof A>)\n\n/**\n * @since 2.0.0\n * @category hashing\n */\nexport const array = <A>(arr: ReadonlyArray<A>) => {\n  let h = 6151\n  for (let i = 0; i < arr.length; i++) {\n    h = pipe(h, combine(hash(arr[i])))\n  }\n  return optimize(h)\n}\n\n/**\n * @since 2.0.0\n * @category hashing\n */\nexport const cached: {\n  (self: object): (hash: number) => number\n  (self: object, hash: number): number\n} = function() {\n  if (arguments.length === 1) {\n    const self = arguments[0] as object\n    return function(hash: number) {\n      Object.defineProperty(self, symbol, {\n        value() {\n          return hash\n        },\n        enumerable: false\n      })\n      return hash\n    } as any\n  }\n  const self = arguments[0] as object\n  const hash = arguments[1] as number\n  Object.defineProperty(self, symbol, {\n    value() {\n      return hash\n    },\n    enumerable: false\n  })\n\n  return hash\n}\n"
  },
  {
    "path": "packages/effect/src/HashMap.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport type { Equal } from \"./Equal.js\"\nimport type { HashSet } from \"./HashSet.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as HM from \"./internal/hashMap.js\"\nimport * as keySet_ from \"./internal/hashMap/keySet.js\"\nimport type { Option } from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { NoInfer } from \"./Types.js\"\n\nconst TypeId: unique symbol = HM.HashMapTypeId as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface HashMap<out Key, out Value> extends Iterable<[Key, Value]>, Equal, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace HashMap {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type UpdateFn<V> = (option: Option<V>) => Option<V>\n  /**\n   * This type-level utility extracts the key type `K` from a `HashMap<K, V>` type.\n   *\n   * @example\n   * ```ts\n   * import { HashMap } from \"effect\"\n   *\n   * declare const hm: HashMap.HashMap<string, number>\n   *\n   * // $ExpectType string\n   * type K = HashMap.HashMap.Key<typeof hm>\n   *\n   * ```\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type Key<T extends HashMap<any, any>> = [T] extends [HashMap<infer _K, infer _V>] ? _K : never\n  /**\n   * This type-level utility extracts the value type `V` from a `HashMap<K, V>` type.\n   *\n   * @example\n   * ```ts\n   * import { HashMap } from \"effect\"\n   *\n   * declare const hm: HashMap.HashMap<string, number>\n   *\n   * // $ExpectType number\n   * type V = HashMap.HashMap.Value<typeof hm>\n   *\n   * ```\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type Value<T extends HashMap<any, any>> = [T] extends [HashMap<infer _K, infer _V>] ? _V : never\n\n  /**\n   * This type-level utility extracts the entry type `[K, V]` from a `HashMap<K, V>` type.\n   *\n   * @example\n   * ```ts\n   * import { HashMap } from \"effect\"\n   *\n   * declare const hm: HashMap.HashMap<string, number>\n   *\n   * // $ExpectType [string, number]\n   * type V = HashMap.HashMap.Entry<typeof hm>\n   *\n   * ```\n   * @since 3.9.0\n   * @category type-level\n   */\n  export type Entry<T extends HashMap<any, any>> = [Key<T>, Value<T>]\n}\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isHashMap: {\n  <K, V>(u: Iterable<readonly [K, V]>): u is HashMap<K, V>\n  (u: unknown): u is HashMap<unknown, unknown>\n} = HM.isHashMap\n\n/**\n * Creates a new `HashMap`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: <K = never, V = never>() => HashMap<K, V> = HM.empty\n\n/**\n * Constructs a new `HashMap` from an array of key/value pairs.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Entries extends ReadonlyArray<readonly [any, any]>>(\n  ...entries: Entries\n) => HashMap<\n  Entries[number] extends readonly [infer K, any] ? K : never,\n  Entries[number] extends readonly [any, infer V] ? V : never\n> = HM.make\n\n/**\n * Creates a new `HashMap` from an iterable collection of key/value pairs.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: <K, V>(entries: Iterable<readonly [K, V]>) => HashMap<K, V> = HM.fromIterable\n\n/**\n * Checks if the `HashMap` contains any entries.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const isEmpty: <K, V>(self: HashMap<K, V>) => boolean = HM.isEmpty\n\n/**\n * Safely lookup the value for the specified key in the `HashMap` using the\n * internal hashing function.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const get: {\n  <K1 extends K, K>(key: K1): <V>(self: HashMap<K, V>) => Option<V>\n  <K1 extends K, K, V>(self: HashMap<K, V>, key: K1): Option<V>\n} = HM.get\n\n/**\n * Lookup the value for the specified key in the `HashMap` using a custom hash.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const getHash: {\n  <K1 extends K, K>(key: K1, hash: number): <V>(self: HashMap<K, V>) => Option<V>\n  <K1 extends K, K, V>(self: HashMap<K, V>, key: K1, hash: number): Option<V>\n} = HM.getHash\n\n/**\n * Unsafely lookup the value for the specified key in the `HashMap` using the\n * internal hashing function.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeGet: {\n  <K1 extends K, K>(key: K1): <V>(self: HashMap<K, V>) => V\n  <K1 extends K, K, V>(self: HashMap<K, V>, key: K1): V\n} = HM.unsafeGet\n\n/**\n * Checks if the specified key has an entry in the `HashMap`.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const has: {\n  <K1 extends K, K>(key: K1): <K, V>(self: HashMap<K, V>) => boolean\n  <K1 extends K, K, V>(self: HashMap<K, V>, key: K1): boolean\n} = HM.has\n\n/**\n * Checks if the specified key has an entry in the `HashMap` using a custom\n * hash.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const hasHash: {\n  <K1 extends K, K>(key: K1, hash: number): <V>(self: HashMap<K, V>) => boolean\n  <K1 extends K, K, V>(self: HashMap<K, V>, key: K1, hash: number): boolean\n} = HM.hasHash\n\n/**\n * Checks if an element matching the given predicate exists in the given `HashMap`.\n *\n * @example\n * ```ts\n * import { HashMap } from \"effect\"\n *\n * const hm = HashMap.make([1, 'a'])\n * HashMap.hasBy(hm, (value, key) => value === 'a' && key === 1); // -> true\n * HashMap.hasBy(hm, (value) => value === 'b'); // -> false\n *\n * ```\n *\n * @since 3.16.0\n * @category elements\n */\nexport const hasBy: {\n  <K, V>(predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean): (self: HashMap<K, V>) => boolean\n  <K, V>(self: HashMap<K, V>, predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean): boolean\n} = HM.hasBy\n\n/**\n * Sets the specified key to the specified value using the internal hashing\n * function.\n *\n * @since 2.0.0\n */\nexport const set: {\n  <K, V>(key: K, value: V): (self: HashMap<K, V>) => HashMap<K, V>\n  <K, V>(self: HashMap<K, V>, key: K, value: V): HashMap<K, V>\n} = HM.set\n\n/**\n * Returns an `IterableIterator` of the keys within the `HashMap`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const keys: <K, V>(self: HashMap<K, V>) => IterableIterator<K> = HM.keys\n\n/**\n * Returns a `HashSet` of keys within the `HashMap`.\n *\n * @since 2.0.0\n * @category getter\n */\nexport const keySet: <K, V>(self: HashMap<K, V>) => HashSet<K> = keySet_.keySet\n\n/**\n * Returns an `IterableIterator` of the values within the `HashMap`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const values: <K, V>(self: HashMap<K, V>) => IterableIterator<V> = HM.values\n\n/**\n * Returns an `Array` of the values within the `HashMap`.\n *\n * @since 3.13.0\n * @category getters\n */\nexport const toValues = <K, V>(self: HashMap<K, V>): Array<V> => Array.from(values(self))\n\n/**\n * Returns an `IterableIterator` of the entries within the `HashMap`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const entries: <K, V>(self: HashMap<K, V>) => IterableIterator<[K, V]> = HM.entries\n\n/**\n * Returns an `Array<[K, V]>` of the entries within the `HashMap`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const toEntries = <K, V>(self: HashMap<K, V>): Array<[K, V]> => Array.from(entries(self))\n\n/**\n * Returns the number of entries within the `HashMap`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <K, V>(self: HashMap<K, V>) => number = HM.size\n\n/**\n * Counts all the element of the given HashMap that pass the given predicate\n *\n * **Example**\n *\n * ```ts\n * import { HashMap } from \"effect\"\n *\n * const map = HashMap.make([1, \"a\"], [2, \"b\"], [3, \"c\"])\n * const result = HashMap.countBy(map, (_v, key) => key % 2 === 1)\n * console.log(result) // 2\n * ```\n *\n * @since 3.17.0\n * @category folding\n */\nexport const countBy: {\n  <K, V>(predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean): (self: HashMap<K, V>) => number\n  <K, V>(self: HashMap<K, V>, predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean): number\n} = HM.countBy\n\n/**\n * Marks the `HashMap` as mutable.\n *\n * @since 2.0.0\n */\nexport const beginMutation: <K, V>(self: HashMap<K, V>) => HashMap<K, V> = HM.beginMutation\n\n/**\n * Marks the `HashMap` as immutable.\n *\n * @since 2.0.0\n */\nexport const endMutation: <K, V>(self: HashMap<K, V>) => HashMap<K, V> = HM.endMutation\n\n/**\n * Mutates the `HashMap` within the context of the provided function.\n *\n * @since 2.0.0\n */\nexport const mutate: {\n  <K, V>(f: (self: HashMap<K, V>) => void): (self: HashMap<K, V>) => HashMap<K, V>\n  <K, V>(self: HashMap<K, V>, f: (self: HashMap<K, V>) => void): HashMap<K, V>\n} = HM.mutate\n\n/**\n * Set or remove the specified key in the `HashMap` using the specified\n * update function. The value of the specified key will be computed using the\n * provided hash.\n *\n * The update function will be invoked with the current value of the key if it\n * exists, or `None` if no such value exists.\n *\n * @since 2.0.0\n */\nexport const modifyAt: {\n  <K, V>(key: K, f: HashMap.UpdateFn<V>): (self: HashMap<K, V>) => HashMap<K, V>\n  <K, V>(self: HashMap<K, V>, key: K, f: HashMap.UpdateFn<V>): HashMap<K, V>\n} = HM.modifyAt\n\n/**\n * Alter the value of the specified key in the `HashMap` using the specified\n * update function. The value of the specified key will be computed using the\n * provided hash.\n *\n * The update function will be invoked with the current value of the key if it\n * exists, or `None` if no such value exists.\n *\n * This function will always either update or insert a value into the `HashMap`.\n *\n * @since 2.0.0\n */\nexport const modifyHash: {\n  <K, V>(key: K, hash: number, f: HashMap.UpdateFn<V>): (self: HashMap<K, V>) => HashMap<K, V>\n  <K, V>(self: HashMap<K, V>, key: K, hash: number, f: HashMap.UpdateFn<V>): HashMap<K, V>\n} = HM.modifyHash\n\n/**\n * Updates the value of the specified key within the `HashMap` if it exists.\n *\n * @since 2.0.0\n */\nexport const modify: {\n  <K, V>(key: K, f: (v: V) => V): (self: HashMap<K, V>) => HashMap<K, V>\n  <K, V>(self: HashMap<K, V>, key: K, f: (v: V) => V): HashMap<K, V>\n} = HM.modify\n\n/**\n * Performs a union of this `HashMap` and that `HashMap`.\n *\n * @since 2.0.0\n */\nexport const union: {\n  <K1, V1>(that: HashMap<K1, V1>): <K0, V0>(self: HashMap<K0, V0>) => HashMap<K1 | K0, V1 | V0>\n  <K0, V0, K1, V1>(self: HashMap<K0, V0>, that: HashMap<K1, V1>): HashMap<K0 | K1, V0 | V1>\n} = HM.union\n\n/**\n * Remove the entry for the specified key in the `HashMap` using the internal\n * hashing function.\n *\n * @since 2.0.0\n */\nexport const remove: {\n  <K>(key: K): <V>(self: HashMap<K, V>) => HashMap<K, V>\n  <K, V>(self: HashMap<K, V>, key: K): HashMap<K, V>\n} = HM.remove\n\n/**\n * Removes all entries in the `HashMap` which have the specified keys.\n *\n * @since 2.0.0\n */\nexport const removeMany: {\n  <K>(keys: Iterable<K>): <V>(self: HashMap<K, V>) => HashMap<K, V>\n  <K, V>(self: HashMap<K, V>, keys: Iterable<K>): HashMap<K, V>\n} = HM.removeMany\n\n/**\n * Maps over the entries of the `HashMap` using the specified function.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <A, V, K>(f: (value: V, key: K) => A): (self: HashMap<K, V>) => HashMap<K, A>\n  <K, V, A>(self: HashMap<K, V>, f: (value: V, key: K) => A): HashMap<K, A>\n} = HM.map\n\n/**\n * Chains over the entries of the `HashMap` using the specified function.\n *\n * **NOTE**: the hash and equal of both maps have to be the same.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMap: {\n  <A, K, B>(f: (value: A, key: K) => HashMap<K, B>): (self: HashMap<K, A>) => HashMap<K, B>\n  <K, A, B>(self: HashMap<K, A>, f: (value: A, key: K) => HashMap<K, B>): HashMap<K, B>\n} = HM.flatMap\n\n/**\n * Applies the specified function to the entries of the `HashMap`.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const forEach: {\n  <V, K>(f: (value: V, key: K) => void): (self: HashMap<K, V>) => void\n  <V, K>(self: HashMap<K, V>, f: (value: V, key: K) => void): void\n} = HM.forEach\n\n/**\n * Reduces the specified state over the entries of the `HashMap`.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const reduce: {\n  <Z, V, K>(zero: Z, f: (accumulator: Z, value: V, key: K) => Z): (self: HashMap<K, V>) => Z\n  <K, V, Z>(self: HashMap<K, V>, zero: Z, f: (accumulator: Z, value: V, key: K) => Z): Z\n} = HM.reduce\n\n/**\n * Filters entries out of a `HashMap` using the specified predicate.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filter: {\n  <K, A, B extends A>(f: (a: NoInfer<A>, k: K) => a is B): (self: HashMap<K, A>) => HashMap<K, B>\n  <K, A>(f: (a: NoInfer<A>, k: K) => boolean): (self: HashMap<K, A>) => HashMap<K, A>\n  <K, A, B extends A>(self: HashMap<K, A>, f: (a: A, k: K) => a is B): HashMap<K, B>\n  <K, A>(self: HashMap<K, A>, f: (a: A, k: K) => boolean): HashMap<K, A>\n} = HM.filter\n\n/**\n * Filters out `None` values from a `HashMap` of `Options`s.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const compact: <K, A>(self: HashMap<K, Option<A>>) => HashMap<K, A> = HM.compact\n\n/**\n * Maps over the entries of the `HashMap` using the specified partial function\n * and filters out `None` values.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterMap: {\n  <A, K, B>(f: (value: A, key: K) => Option<B>): (self: HashMap<K, A>) => HashMap<K, B>\n  <K, A, B>(self: HashMap<K, A>, f: (value: A, key: K) => Option<B>): HashMap<K, B>\n} = HM.filterMap\n\n/**\n * Returns the first element that satisfies the specified\n * predicate, or `None` if no such element exists.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findFirst: {\n  <K, A, B extends A>(predicate: (a: NoInfer<A>, k: K) => a is B): (self: HashMap<K, A>) => Option<[K, B]>\n  <K, A>(predicate: (a: NoInfer<A>, k: K) => boolean): (self: HashMap<K, A>) => Option<[K, A]>\n  <K, A, B extends A>(self: HashMap<K, A>, predicate: (a: A, k: K) => a is B): Option<[K, B]>\n  <K, A>(self: HashMap<K, A>, predicate: (a: A, k: K) => boolean): Option<[K, A]>\n} = HM.findFirst\n\n/**\n * Checks if any entry in a hashmap meets a specific condition.\n *\n * @since 3.13.0\n * @category elements\n */\nexport const some: {\n  <K, A>(predicate: (a: NoInfer<A>, k: K) => boolean): (self: HashMap<K, A>) => boolean\n  <K, A>(self: HashMap<K, A>, predicate: (a: A, k: K) => boolean): boolean\n} = HM.some\n\n/**\n * Checks if all entries in a hashmap meets a specific condition.\n *\n * @param self - The hashmap to check.\n * @param predicate - The condition to test entries (value, key).\n *\n * @since 3.14.0\n * @category elements\n */\nexport const every: {\n  <K, A>(predicate: (a: NoInfer<A>, k: K) => boolean): (self: HashMap<K, A>) => boolean\n  <K, A>(self: HashMap<K, A>, predicate: (a: A, k: K) => boolean): boolean\n} = HM.every\n"
  },
  {
    "path": "packages/effect/src/HashRing.ts",
    "content": "/**\n * @since 3.19.0\n * @experimental\n */\nimport { dual } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport * as Inspectable from \"./Inspectable.js\"\nimport * as Iterable from \"./Iterable.js\"\nimport { type Pipeable, pipeArguments } from \"./Pipeable.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport * as PrimaryKey from \"./PrimaryKey.js\"\n\nconst TypeId = \"~effect/cluster/HashRing\" as const\n\n/**\n * @since 3.19.0\n * @category Models\n * @experimental\n */\nexport interface HashRing<A extends PrimaryKey.PrimaryKey> extends Pipeable, Iterable<A> {\n  readonly [TypeId]: typeof TypeId\n  readonly baseWeight: number\n  totalWeightCache: number\n  readonly nodes: Map<string, [node: A, weight: number]>\n  ring: Array<[hash: number, node: string]>\n}\n\n/**\n * @since 3.19.0\n * @category Guards\n * @experimental\n */\nexport const isHashRing = (u: unknown): u is HashRing<any> => hasProperty(u, TypeId)\n\n/**\n * @since 3.19.0\n * @category Constructors\n * @experimental\n */\nexport const make = <A extends PrimaryKey.PrimaryKey>(options?: {\n  readonly baseWeight?: number | undefined\n}): HashRing<A> => {\n  const self = Object.create(Proto)\n  self.baseWeight = Math.max(options?.baseWeight ?? 128, 1)\n  self.totalWeightCache = 0\n  self.nodes = new Map()\n  self.ring = []\n  return self\n}\n\nconst Proto = {\n  [TypeId]: TypeId,\n  [Symbol.iterator]<A extends PrimaryKey.PrimaryKey>(this: HashRing<A>): Iterator<A> {\n    return Iterable.map(this.nodes.values(), ([n]) => n)[Symbol.iterator]()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  ...Inspectable.BaseProto,\n  toJSON(this: HashRing<any>) {\n    return {\n      _id: \"HashRing\",\n      baseWeight: this.baseWeight,\n      nodes: this.ring.map(([, n]) => this.nodes.get(n)![0])\n    }\n  }\n}\n\n/**\n * Add new nodes to the ring. If a node already exists in the ring, it\n * will be updated. For example, you can use this to update the node's weight.\n *\n * @since 3.19.0\n * @category Combinators\n * @experimental\n */\nexport const addMany: {\n  <A extends PrimaryKey.PrimaryKey>(nodes: Iterable<A>, options?: {\n    readonly weight?: number | undefined\n  }): (self: HashRing<A>) => HashRing<A>\n  <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, nodes: Iterable<A>, options?: {\n    readonly weight?: number | undefined\n  }): HashRing<A>\n} = dual(\n  (args) => isHashRing(args[0]),\n  <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, nodes: Iterable<A>, options?: {\n    readonly weight?: number | undefined\n  }): HashRing<A> => {\n    const weight = Math.max(options?.weight ?? 1, 0.1)\n    const keys: Array<string> = []\n    let toRemove: Set<string> | undefined\n    for (const node of nodes) {\n      const key = PrimaryKey.value(node)\n      const entry = self.nodes.get(key)\n      if (entry) {\n        if (entry[1] === weight) continue\n        toRemove ??= new Set()\n        toRemove.add(key)\n        self.totalWeightCache -= entry[1]\n        self.totalWeightCache += weight\n        entry[1] = weight\n      } else {\n        self.nodes.set(key, [node, weight])\n        self.totalWeightCache += weight\n      }\n      keys.push(key)\n    }\n    if (toRemove) {\n      self.ring = self.ring.filter(([, n]) => !toRemove.has(n))\n    }\n    addNodesToRing(self, keys, Math.round(weight * self.baseWeight))\n    return self\n  }\n)\n\nfunction addNodesToRing<A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, keys: Array<string>, weight: number) {\n  for (let i = weight; i > 0; i--) {\n    for (let j = 0; j < keys.length; j++) {\n      const key = keys[j]\n      self.ring.push([\n        Hash.string(`${key}:${i}`),\n        key\n      ])\n    }\n  }\n  self.ring.sort((a, b) => a[0] - b[0])\n}\n\n/**\n * Add a new node to the ring. If the node already exists in the ring, it\n * will be updated. For example, you can use this to update the node's weight.\n *\n * @since 3.19.0\n * @category Combinators\n * @experimental\n */\nexport const add: {\n  <A extends PrimaryKey.PrimaryKey>(node: A, options?: {\n    readonly weight?: number | undefined\n  }): (self: HashRing<A>) => HashRing<A>\n  <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A, options?: {\n    readonly weight?: number | undefined\n  }): HashRing<A>\n} = dual((args) => isHashRing(args[0]), <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A, options?: {\n  readonly weight?: number | undefined\n}): HashRing<A> => addMany(self, [node], options))\n\n/**\n * Removes the node from the ring. No-op's if the node does not exist.\n *\n * @since 3.19.0\n * @category Combinators\n * @experimental\n */\nexport const remove: {\n  <A extends PrimaryKey.PrimaryKey>(node: A): (self: HashRing<A>) => HashRing<A>\n  <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A): HashRing<A>\n} = dual(2, <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A): HashRing<A> => {\n  const key = PrimaryKey.value(node)\n  const entry = self.nodes.get(key)\n  if (entry) {\n    self.nodes.delete(key)\n    self.ring = self.ring.filter(([, n]) => n !== key)\n    self.totalWeightCache -= entry[1]\n  }\n  return self\n})\n\n/**\n * @since 3.19.0\n * @category Combinators\n * @experimental\n */\nexport const has: {\n  <A extends PrimaryKey.PrimaryKey>(node: A): (self: HashRing<A>) => boolean\n  <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A): boolean\n} = dual(\n  2,\n  <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A): boolean => self.nodes.has(PrimaryKey.value(node))\n)\n\n/**\n * Gets the node which should handle the given input. Returns undefined if\n * the hashring has no elements with weight.\n *\n * @since 3.19.0\n * @category Combinators\n * @experimental\n */\nexport const get = <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, input: string): A | undefined => {\n  if (self.ring.length === 0) {\n    return undefined\n  }\n  const index = getIndexForInput(self, Hash.string(input))[0]\n  const node = self.ring[index][1]!\n  return self.nodes.get(node)![0]\n}\n\n/**\n * Distributes `count` shards across the nodes in the ring, attempting to\n * balance the number of shards allocated to each node. Returns undefined if\n * the hashring has no elements with weight.\n *\n * @since 3.19.0\n * @category Combinators\n * @experimental\n */\nexport const getShards = <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, count: number): Array<A> | undefined => {\n  if (self.ring.length === 0) {\n    return undefined\n  }\n\n  const shards = new Array<A>(count)\n\n  // for tracking how many shards have been allocated to each node\n  const allocations = new Map<string, number>()\n  // for tracking which shards still need to be allocated\n  const remaining = new Set<number>()\n  // for tracking which nodes have reached the max allocation\n  const exclude = new Set<string>()\n\n  // First pass - allocate the closest nodes, skipping nodes that have reached\n  // max\n  const distances = new Array<[shard: number, node: string, distance: number]>(count)\n  for (let shard = 0; shard < count; shard++) {\n    const hash = (shardHashes[shard] ??= Hash.string(`shard-${shard}`))\n    const [index, distance] = getIndexForInput(self, hash)\n    const node = self.ring[index][1]!\n    distances[shard] = [shard, node, distance]\n    remaining.add(shard)\n  }\n  distances.sort((a, b) => a[2] - b[2])\n  for (let i = 0; i < count; i++) {\n    const [shard, node] = distances[i]\n    if (exclude.has(node)) continue\n    const [value, weight] = self.nodes.get(node)!\n    shards[shard] = value\n    remaining.delete(shard)\n    const nodeCount = (allocations.get(node) ?? 0) + 1\n    allocations.set(node, nodeCount)\n    const maxPerNode = Math.max(1, Math.floor(count * (weight / self.totalWeightCache)))\n    if (nodeCount >= maxPerNode) {\n      exclude.add(node)\n    }\n  }\n\n  // Second pass - allocate any remaining shards, skipping nodes that have\n  // reached max\n  let allAtMax = exclude.size === self.nodes.size\n  remaining.forEach((shard) => {\n    const index = getIndexForInput(self, shardHashes[shard], allAtMax ? undefined : exclude)[0]\n    const node = self.ring[index][1]\n    const [value, weight] = self.nodes.get(node)!\n    shards[shard] = value\n\n    if (allAtMax) return\n    const nodeCount = (allocations.get(node) ?? 0) + 1\n    allocations.set(node, nodeCount)\n    const maxPerNode = Math.max(1, Math.floor(count * (weight / self.totalWeightCache)))\n    if (nodeCount >= maxPerNode) {\n      exclude.add(node)\n      if (exclude.size === self.nodes.size) {\n        allAtMax = true\n      }\n    }\n  })\n\n  return shards\n}\n\nconst shardHashes: Array<number> = []\n\nfunction getIndexForInput<A extends PrimaryKey.PrimaryKey>(\n  self: HashRing<A>,\n  hash: number,\n  exclude?: ReadonlySet<string> | undefined\n): readonly [index: number, distance: number] {\n  const ring = self.ring\n  const len = ring.length\n\n  let mid: number\n  let lo = 0\n  let hi = len - 1\n\n  while (lo <= hi) {\n    mid = ((lo + hi) / 2) >>> 0\n    if (ring[mid][0] >= hash) {\n      hi = mid - 1\n    } else {\n      lo = mid + 1\n    }\n  }\n  const a = lo === len ? lo - 1 : lo\n  const distA = Math.abs(ring[a][0] - hash)\n  if (exclude === undefined) {\n    const b = lo - 1\n    if (b < 0) {\n      return [a, distA]\n    }\n    const distB = Math.abs(ring[b][0] - hash)\n    return distA <= distB ? [a, distA] : [b, distB]\n  } else if (!exclude.has(ring[a][1])) {\n    return [a, distA]\n  }\n  const range = Math.max(lo, len - lo)\n  for (let i = 1; i < range; i++) {\n    let index = lo - i\n    if (index >= 0 && index < len && !exclude.has(ring[index][1])) {\n      return [index, Math.abs(ring[index][0] - hash)]\n    }\n    index = lo + i\n    if (index >= 0 && index < len && !exclude.has(ring[index][1])) {\n      return [index, Math.abs(ring[index][0] - hash)]\n    }\n  }\n  return [a, distA]\n}\n"
  },
  {
    "path": "packages/effect/src/HashSet.ts",
    "content": "/**\n * # HashSet\n *\n * An immutable `HashSet` provides a collection of unique values with efficient\n * lookup, insertion and removal. Once created, a `HashSet` cannot be modified;\n * any operation that would alter the set instead returns a new `HashSet` with\n * the changes. This immutability offers benefits like predictable state\n * management and easier reasoning about your code.\n *\n * ## What Problem Does It Solve?\n *\n * `HashSet` solves the problem of maintaining an unsorted collection where each\n * value appears exactly once, with fast operations for checking membership and\n * adding/removing values.\n *\n * ## When to Use\n *\n * Use `HashSet` when you need:\n *\n * - A collection with no duplicate values\n * - Efficient membership testing (**`O(1)`** average complexity)\n * - Set operations like union, intersection, and difference\n * - An immutable data structure that preserves functional programming patterns\n *\n * ## Advanced Features\n *\n * HashSet provides operations for:\n *\n * - Transforming sets with map and flatMap\n * - Filtering elements with filter\n * - Combining sets with union, intersection and difference\n * - Performance optimizations via mutable operations in controlled contexts\n *\n * ## Performance Characteristics\n *\n * - **Lookup** operations ({@link module:HashSet.has}): **`O(1)`** average time\n *   complexity\n * - **Insertion** operations ({@link module:HashSet.add}): **`O(1)`** average time\n *   complexity\n * - **Removal** operations ({@link module:HashSet.remove}): **`O(1)`** average\n *   time complexity\n * - **Set** operations ({@link module:HashSet.union},\n *   {@link module:HashSet.intersection}): **`O(n)`** where n is the size of the\n *   smaller set\n * - **Iteration**: **`O(n)`** where n is the size of the set\n *\n * The HashSet data structure implements the following traits:\n *\n * - {@link Iterable}: allows iterating over the values in the set\n * - {@link Equal}: allows comparing two sets for value-based equality\n * - {@link Pipeable}: allows chaining operations with the pipe operator\n * - {@link Inspectable}: allows inspecting the contents of the set\n *\n * ## Operations Reference\n *\n * | Category     | Operation                           | Description                                 | Complexity |\n * | ------------ | ----------------------------------- | ------------------------------------------- | ---------- |\n * | constructors | {@link module:HashSet.empty}        | Creates an empty HashSet                    | O(1)       |\n * | constructors | {@link module:HashSet.fromIterable} | Creates a HashSet from an iterable          | O(n)       |\n * | constructors | {@link module:HashSet.make}         | Creates a HashSet from multiple values      | O(n)       |\n * |              |                                     |                                             |            |\n * | elements     | {@link module:HashSet.has}          | Checks if a value exists in the set         | O(1) avg   |\n * | elements     | {@link module:HashSet.some}         | Checks if any element satisfies a predicate | O(n)       |\n * | elements     | {@link module:HashSet.every}        | Checks if all elements satisfy a predicate  | O(n)       |\n * | elements     | {@link module:HashSet.isSubset}     | Checks if a set is a subset of another      | O(n)       |\n * |              |                                     |                                             |            |\n * | getters      | {@link module:HashSet.values}       | Gets an iterator of all values              | O(1)       |\n * | getters      | {@link module:HashSet.toValues}     | Gets an array of all values                 | O(n)       |\n * | getters      | {@link module:HashSet.size}         | Gets the number of elements                 | O(1)       |\n * |              |                                     |                                             |            |\n * | mutations    | {@link module:HashSet.add}          | Adds a value to the set                     | O(1) avg   |\n * | mutations    | {@link module:HashSet.remove}       | Removes a value from the set                | O(1) avg   |\n * | mutations    | {@link module:HashSet.toggle}       | Toggles a value's presence                  | O(1) avg   |\n * |              |                                     |                                             |            |\n * | operations   | {@link module:HashSet.difference}   | Computes set difference (A - B)             | O(n)       |\n * | operations   | {@link module:HashSet.intersection} | Computes set intersection (A ∩ B)           | O(n)       |\n * | operations   | {@link module:HashSet.union}        | Computes set union (A ∪ B)                  | O(n)       |\n * |              |                                     |                                             |            |\n * | mapping      | {@link module:HashSet.map}          | Transforms each element                     | O(n)       |\n * |              |                                     |                                             |            |\n * | sequencing   | {@link module:HashSet.flatMap}      | Transforms and flattens elements            | O(n)       |\n * |              |                                     |                                             |            |\n * | traversing   | {@link module:HashSet.forEach}      | Applies a function to each element          | O(n)       |\n * |              |                                     |                                             |            |\n * | folding      | {@link module:HashSet.reduce}       | Reduces the set to a single value           | O(n)       |\n * |              |                                     |                                             |            |\n * | filtering    | {@link module:HashSet.filter}       | Keeps elements that satisfy a predicate     | O(n)       |\n * |              |                                     |                                             |            |\n * | partitioning | {@link module:HashSet.partition}    | Splits into two sets by a predicate         | O(n)       |\n *\n * ## Notes\n *\n * ### Composability with the Effect Ecosystem:\n *\n * This `HashSet` is designed to work seamlessly within the Effect ecosystem. It\n * implements the {@link Iterable}, {@link Equal}, {@link Pipeable}, and\n * {@link Inspectable} traits from Effect. This ensures compatibility with other\n * Effect data structures and functionalities. For example, you can easily use\n * Effect's `pipe` method to chain operations on the `HashSet`.\n *\n * **Equality of Elements with Effect's {@link Equal `Equal`} Trait:**\n *\n * This `HashSet` relies on Effect's {@link Equal} trait to determine the\n * uniqueness of elements within the set. The way equality is checked depends on\n * the type of the elements:\n *\n * - **Primitive Values:** For primitive JavaScript values like strings, numbers,\n *   booleans, `null`, and `undefined`, equality is determined by their value\n *   (similar to the `===` operator).\n * - **Objects and Custom Types:** For objects and other custom types, equality is\n *   determined by whether those types implement the {@link Equal} interface\n *   themselves. If an element type implements `Equal`, the `HashSet` will\n *   delegate to that implementation to perform the equality check. This allows\n *   you to define custom logic for determining when two instances of your\n *   objects should be considered equal based on their properties, rather than\n *   just their object identity.\n *\n * ```ts\n * import { Equal, Hash, HashSet } from \"effect\"\n *\n * class Person implements Equal.Equal {\n *   constructor(\n *     readonly id: number, // Unique identifier\n *     readonly name: string,\n *     readonly age: number\n *   ) {}\n *\n *   // Define equality based on id, name, and age\n *   [Equal.symbol](that: Equal.Equal): boolean {\n *     if (that instanceof Person) {\n *       return (\n *         Equal.equals(this.id, that.id) &&\n *         Equal.equals(this.name, that.name) &&\n *         Equal.equals(this.age, that.age)\n *       )\n *     }\n *     return false\n *   }\n *\n *   // Generate a hash code based on the unique id\n *   [Hash.symbol](): number {\n *     return Hash.hash(this.id)\n *   }\n * }\n *\n * // Creating a HashSet with objects that implement the Equal interface\n * const set = HashSet.empty().pipe(\n *   HashSet.add(new Person(1, \"Alice\", 30)),\n *   HashSet.add(new Person(1, \"Alice\", 30))\n * )\n *\n * // HashSet recognizes them as equal, so only one element is stored\n * console.log(HashSet.size(set))\n * // Output: 1\n * ```\n *\n * **Simplifying Equality and Hashing with `Data` and `Schema`:**\n *\n * Effect's {@link Data} and {@link Schema `Schema.Data`} modules offer powerful\n * ways to automatically handle the implementation of both the {@link Equal} and\n * {@link Hash} traits for your custom data structures.\n *\n * - **`Data` Module:** By using constructors like `Data.struct`, `Data.tuple`,\n *   `Data.array`, or `Data.case` to define your data types, Effect\n *   automatically generates the necessary implementations for value-based\n *   equality and consistent hashing. This significantly reduces boilerplate and\n *   ensures correctness.\n *\n * ```ts\n * import { HashSet, Data, Equal } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * // Data.* implements the `Equal` traits for us\n * const person1 = Data.struct({ id: 1, name: \"Alice\", age: 30 })\n * const person2 = Data.struct({ id: 1, name: \"Alice\", age: 30 })\n *\n * assert(Equal.equals(person1, person2))\n *\n * const set = HashSet.empty().pipe(\n *   HashSet.add(person1),\n *   HashSet.add(person2)\n * )\n *\n * // HashSet recognizes them as equal, so only one element is stored\n * console.log(HashSet.size(set)) // Output: 1\n * ```\n *\n * - **`Schema` Module:** When defining data schemas using the {@link Schema}\n *   module, you can use `Schema.Data` to automatically include the `Equal` and\n *   `Hash` traits in the decoded objects. This is particularly important when\n *   working with `HashSet`. **For decoded objects to be correctly recognized as\n *   equal within a `HashSet`, ensure that the schema for those objects is\n *   defined using `Schema.Data`.**\n *\n * ```ts\n * import { Equal, HashSet, Schema } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * // Schema.Data implements the `Equal` traits for us\n * const PersonSchema = Schema.Data(\n *   Schema.Struct({\n *     id: Schema.Number,\n *     name: Schema.String,\n *     age: Schema.Number\n *   })\n * )\n *\n * const Person = Schema.decode(PersonSchema)\n *\n * const person1 = Person({ id: 1, name: \"Alice\", age: 30 })\n * const person2 = Person({ id: 1, name: \"Alice\", age: 30 })\n *\n * assert(Equal.equals(person1, person2)) // Output: true\n *\n * const set = HashSet.empty().pipe(\n *   HashSet.add(person1),\n *   HashSet.add(person2)\n * )\n *\n * // HashSet thanks to Schema.Data implementation of the `Equal` trait, recognizes the two Person as equal, so only one element is stored\n * console.log(HashSet.size(set)) // Output: 1\n * ```\n *\n * ### Interoperability with the JavaScript Runtime:\n *\n * To interoperate with the regular JavaScript runtime, Effect's `HashSet`\n * provides methods to access its elements in formats readily usable by\n * JavaScript APIs: {@link values `HashSet.values`},\n * {@link toValues `HashSet.toValues`}\n *\n * ```ts\n * import { HashSet } from \"effect\"\n *\n * const hashSet: HashSet.HashSet<number> = HashSet.make(1, 2, 3)\n *\n * // Using HashSet.values to convert HashSet.HashSet<A> to IterableIterator<A>\n * const iterable: IterableIterator<number> = HashSet.values(hashSet)\n *\n * console.log(...iterable) // Logs:  1 2 3\n *\n * // Using HashSet.toValues to convert HashSet.HashSet<A> to Array<A>\n * const array: Array<number> = HashSet.toValues(hashSet)\n *\n * console.log(array) // Logs: [ 1, 2, 3 ]\n * ```\n *\n * Be mindful of performance implications (both time and space complexity) when\n * frequently converting between Effect's immutable HashSet and mutable\n * JavaScript data structures, especially for large collections.\n *\n * @module HashSet\n * @since 2.0.0\n */\n\nimport type { Equal } from \"./Equal.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as HS from \"./internal/hashSet.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport type { NoInfer } from \"./Types.js\"\n\nconst TypeId: unique symbol = HS.HashSetTypeId as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @memberof HashSet\n * @since 2.0.0\n * @category models\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet } from \"effect\"\n *\n * let numberSet: HashSet.HashSet<number>\n * ```\n *\n * @interface\n */\nexport interface HashSet<out A> extends Iterable<A>, Equal, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n}\n\n/**\n * @memberof HashSet\n * @since 2.0.0\n * @category refinements\n */\nexport const isHashSet: {\n  /**\n   * Type guard function to determine if a given iterable is a `HashSet`.\n   *\n   * This overload preserves the type of the iterable's elements.\n   *\n   * @example\n   *\n   * ```ts\n   * import { HashSet } from \"effect\"\n   *\n   * const numberIterable: Iterable<1 | 2 | 3> = [1, 2, 3]\n   *\n   * if (\n   *   // if passed an Iterable<A> the type guard that preserves the type parameter <A>\n   *   HashSet.isHashSet(numberIterable)\n   * ) {\n   *   const HashSet: HashSet.HashSet<1 | 2 | 3> = numberIterable\n   * }\n   * ```\n   *\n   * @param u - The iterable input to be checked.\n   * @returns A boolean indicating whether the provided iterable is a `HashSet`.\n   */\n  <A>(u: Iterable<A>): u is HashSet<A>\n\n  /**\n   * Type guard function that checks if the provided value is a `HashSet` of\n   * unknown type.\n   *\n   * @example\n   *\n   * ```ts\n   * import { HashSet } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * // Check if a value is a HashSet\n   * const set = HashSet.make(1, 2, 3)\n   *\n   * assert.equal(HashSet.isHashSet(set), true) // true\n   * assert.equal(HashSet.isHashSet(HashSet.empty()), true)\n   *\n   * // Works with any type\n   * assert.equal(HashSet.isHashSet(null), false) // false\n   * assert.equal(HashSet.isHashSet({}), false) // false\n   * assert.equal(HashSet.isHashSet([1, 2, 3]), false) // false\n   * ```\n   *\n   * @param u - The value to check.\n   * @returns A boolean indicating whether the value is a `HashSet<unknown>`.\n   */\n  (u: unknown): u is HashSet<unknown>\n} = HS.isHashSet\n\n/**\n * Creates an empty `HashSet`.\n *\n * Time complexity: **`O(1)`**\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category constructors\n * @example\n *\n * ```ts\n * import { HashSet, pipe } from \"effect\"\n *\n * console.log(\n *   pipe(\n *     // Provide a type argument to create a HashSet of a specific type\n *     HashSet.empty<number>(),\n *     HashSet.add(1),\n *     HashSet.add(1), // Notice the duplicate\n *     HashSet.add(2),\n *     HashSet.toValues\n *   )\n * ) // Output: [1, 2]\n * ```\n *\n * @see Other `HashSet` constructors are {@link module:HashSet.make} {@link module:HashSet.fromIterable}\n */\nexport const empty: <A = never>() => HashSet<A> = HS.empty\n\n/**\n * Creates a new `HashSet` from an iterable collection of values.\n *\n * Time complexity: **`O(n)`** where n is the number of elements in the iterable\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category constructors\n * @example\n *\n * ```ts\n * // Creating a HashSet from an Array\n * import { HashSet, pipe } from \"effect\"\n *\n * console.log(\n *   pipe(\n *     [1, 2, 3, 4, 5, 1, 2, 3], // Array<number> is an Iterable<number>;  Note the duplicates.\n *     HashSet.fromIterable,\n *     HashSet.toValues\n *   )\n * ) // Output: [1, 2, 3, 4, 5]\n * ```\n *\n * @example\n *\n * ```ts\n * // Creating a HashSet from a Set\n * import { HashSet, pipe } from \"effect\"\n *\n * console.log(\n *   pipe(\n *     new Set([\"apple\", \"banana\", \"orange\", \"apple\"]), // Set<string> is an Iterable<string>\n *     HashSet.fromIterable,\n *     HashSet.toValues\n *   )\n * ) // Output: [\"apple\", \"banana\", \"orange\"]\n * ```\n *\n * @example\n *\n * ```ts\n * // Creating a HashSet from a Generator\n * import { HashSet } from \"effect\"\n *\n * // Generator functions return iterables\n * function* fibonacci(n: number): Generator<number, void, unknown> {\n *   let [a, b] = [0, 1]\n *   for (let i = 0; i < n; i++) {\n *     yield a\n *     ;[a, b] = [b, a + b]\n *   }\n * }\n *\n * // Create a HashSet from the first 10 Fibonacci numbers\n * const fibonacciSet = HashSet.fromIterable(fibonacci(10))\n *\n * console.log(HashSet.toValues(fibonacciSet))\n * // Outputs: [0, 1, 2, 3, 5, 8, 13, 21, 34] but in unsorted order\n * ```\n *\n * @example\n *\n * ```ts\n * //  Creating a HashSet from another HashSet\n * import { HashSet, pipe } from \"effect\"\n *\n * console.log(\n *   pipe(\n *     // since HashSet implements the Iterable interface, we can use it to create a new HashSet\n *     HashSet.make(1, 2, 3, 4),\n *     HashSet.fromIterable,\n *     HashSet.toValues // turns the HashSet back into an array\n *   )\n * ) // Output: [1, 2, 3, 4]\n * ```\n *\n * @example\n *\n * ```ts\n * // Creating a HashSet from other Effect's data structures like Chunk\n * import { Chunk, HashSet, pipe } from \"effect\"\n *\n * console.log(\n *   pipe(\n *     Chunk.make(1, 2, 3, 4), // Iterable<number>\n *     HashSet.fromIterable,\n *     HashSet.toValues // turns the HashSet back into an array\n *   )\n * ) // Outputs: [1, 2, 3, 4]\n * ```\n *\n * @see Other `HashSet` constructors are {@link module:HashSet.empty} {@link module:HashSet.make}\n */\nexport const fromIterable: <A>(elements: Iterable<A>) => HashSet<A> = HS.fromIterable\n\n/**\n * Construct a new `HashSet` from a variable number of values.\n *\n * Time complexity: **`O(n)`** where n is the number of elements\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category constructors\n * @example\n *\n * ```ts\n * import { Equal, Hash, HashSet, pipe } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * class Character implements Equal.Equal {\n *   readonly name: string\n *   readonly trait: string\n *\n *   constructor(name: string, trait: string) {\n *     this.name = name\n *     this.trait = trait\n *   }\n *\n *   // Define equality based on name, and trait\n *   [Equal.symbol](that: Equal.Equal): boolean {\n *     if (that instanceof Character) {\n *       return (\n *         Equal.equals(this.name, that.name) &&\n *         Equal.equals(this.trait, that.trait)\n *       )\n *     }\n *     return false\n *   }\n *\n *   // Generate a hash code based on the sum of the character's name and trait\n *   [Hash.symbol](): number {\n *     return Hash.hash(this.name + this.trait)\n *   }\n *\n *   static readonly of = (name: string, trait: string): Character => {\n *     return new Character(name, trait)\n *   }\n * }\n *\n * assert.strictEqual(\n *   Equal.equals(\n *     HashSet.make(\n *       Character.of(\"Alice\", \"Curious\"),\n *       Character.of(\"Alice\", \"Curious\"),\n *       Character.of(\"White Rabbit\", \"Always late\"),\n *       Character.of(\"Mad Hatter\", \"Tea enthusiast\")\n *     ),\n *     // Is the same as adding each character to an empty set\n *     pipe(\n *       HashSet.empty(),\n *       HashSet.add(Character.of(\"Alice\", \"Curious\")),\n *       HashSet.add(Character.of(\"Alice\", \"Curious\")), // Alice tried to attend twice!\n *       HashSet.add(Character.of(\"White Rabbit\", \"Always late\")),\n *       HashSet.add(Character.of(\"Mad Hatter\", \"Tea enthusiast\"))\n *     )\n *   ),\n *   true,\n *   \"`HashSet.make` and `HashSet.empty() + HashSet.add()` should be equal\"\n * )\n *\n * assert.strictEqual(\n *   Equal.equals(\n *     HashSet.make(\n *       Character.of(\"Alice\", \"Curious\"),\n *       Character.of(\"Alice\", \"Curious\"),\n *       Character.of(\"White Rabbit\", \"Always late\"),\n *       Character.of(\"Mad Hatter\", \"Tea enthusiast\")\n *     ),\n *     HashSet.fromIterable([\n *       Character.of(\"Alice\", \"Curious\"),\n *       Character.of(\"Alice\", \"Curious\"),\n *       Character.of(\"White Rabbit\", \"Always late\"),\n *       Character.of(\"Mad Hatter\", \"Tea enthusiast\")\n *     ])\n *   ),\n *   true,\n *   \"`HashSet.make` and `HashSet.fromIterable` should be equal\"\n * )\n * ```\n *\n * @see Other `HashSet` constructors are {@link module:HashSet.fromIterable} {@link module:HashSet.empty}\n */\nexport const make: <As extends ReadonlyArray<any>>(...elements: As) => HashSet<As[number]> = HS.make\n\n/**\n * Checks if the specified value exists in the `HashSet`.\n *\n * Time complexity: **`O(1)`** average\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category elements\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(HashSet.make(0, 1, 2), HashSet.has(3)) // false\n *\n * // or piped with the pipe function\n * HashSet.make(0, 1, 2).pipe(HashSet.has(3)) // false\n *\n * // or with `data-first` API\n * HashSet.has(HashSet.make(0, 1, 2), 3) // false\n * ```\n *\n * @returns A `boolean` signaling the presence of the value in the HashSet\n * @see Other `HashSet` elements are {@link module:HashSet.some} {@link module:HashSet.every} {@link module:HashSet.isSubset}\n */\nexport const has: {\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-last` a.k.a. `pipeable` API\n   * import * as assert from \"node:assert/strict\"\n   * import { HashSet, pipe } from \"effect\"\n   *\n   * const set = HashSet.make(0, 1, 2)\n   *\n   * assert.equal(pipe(set, HashSet.has(0)), true)\n   * assert.equal(pipe(set, HashSet.has(1)), true)\n   * assert.equal(pipe(set, HashSet.has(2)), true)\n   * assert.equal(pipe(set, HashSet.has(3)), false)\n   * ```\n   */\n  <A>(value: A): (self: HashSet<A>) => boolean\n\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-first` API\n   * import * as assert from \"node:assert/strict\"\n   * import { HashSet, pipe } from \"effect\"\n   *\n   * const set = HashSet.make(0, 1, 2)\n   *\n   * assert.equal(HashSet.has(set, 0), true)\n   * assert.equal(HashSet.has(set, 1), true)\n   * assert.equal(HashSet.has(set, 2), true)\n   * assert.equal(HashSet.has(set, 3), false)\n   * ```\n   */\n  <A>(self: HashSet<A>, value: A): boolean\n} = HS.has\n\n/**\n * Check if a predicate holds true for some `HashSet` element.\n *\n * Time complexity: **`O(n)`** where n is the number of elements in the set\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category elements\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * const set: HashSet.HashSet<number> = HashSet.make(0, 1, 2)\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(\n *   set,\n *   HashSet.some((n) => n > 0)\n * ) // true\n *\n * // or piped with the pipe function\n * set.pipe(HashSet.some((n) => n > 0)) // true\n *\n * // or with `data-first` API\n * HashSet.some(set, (n) => n > 0) // true\n * ```\n *\n * @see Other `HashSet` elements are {@link module:HashSet.has} {@link module:HashSet.every} {@link module:HashSet.isSubset}\n */\nexport const some: {\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-last` a.k.a. `pipeable` API\n   * import * as assert from \"node:assert/strict\"\n   * import { HashSet, pipe } from \"effect\"\n   *\n   * const set = HashSet.make(0, 1, 2)\n   *\n   * assert.equal(\n   *   pipe(\n   *     set,\n   *     HashSet.some((n) => n > 0)\n   *   ),\n   *   true\n   * )\n   *\n   * assert.equal(\n   *   pipe(\n   *     set,\n   *     HashSet.some((n) => n > 2)\n   *   ),\n   *   false\n   * )\n   * ```\n   */\n  <A>(f: Predicate<A>): (self: HashSet<A>) => boolean\n\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-first` API\n   * import * as assert from \"node:assert/strict\"\n   * import { HashSet } from \"effect\"\n   *\n   * const set = HashSet.make(0, 1, 2)\n   *\n   * assert.equal(\n   *   HashSet.some(set, (n) => n > 0),\n   *   true\n   * )\n   *\n   * assert.equal(\n   *   HashSet.some(set, (n) => n > 2),\n   *   false\n   * )\n   * ```\n   */\n  <A>(self: HashSet<A>, f: Predicate<A>): boolean\n} = HS.some\n\n/**\n * Check if a predicate holds true for every `HashSet` element.\n *\n * Time complexity is **`O(n)`** as it needs to traverse the whole HashSet\n * collection\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category elements\n * @example\n *\n * ```ts\n * // Syntax with Refinement\n * import { HashSet, pipe, Predicate } from \"effect\"\n *\n * const numberOrString = HashSet.make(1, \"1\", \"one\", \"uno\")\n *\n * // with `data-last`, a.k.a. `pipeable` API and `Refinement`\n * pipe(\n *   numberOrString, // HashSet.HashSet<number | string>\n *   HashSet.every(Predicate.isString)\n * ) // HashSet.HashSet<string>\n *\n * // or piped with the pipe function and  `Refinement`\n * numberOrString // HashSet.HashSet<number | string>\n *   .pipe(HashSet.every(Predicate.isString)) // HashSet.HashSet<string>\n *\n * // or with `data-first` API and `Refinement`\n * HashSet.every(\n *   numberOrString, // HashSet.HashSet<number | string>\n *   Predicate.isString\n * ) // HashSet.HashSet<string>\n * ```\n *\n * @example\n *\n * ```ts\n * // Syntax with Predicate\n * import { HashSet, pipe } from \"effect\"\n *\n * const set = HashSet.make(1, 2, 3)\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(\n *   set,\n *   HashSet.every((n) => n >= 0)\n * ) // true\n *\n * // or piped with the pipe function\n * set.pipe(HashSet.every((n) => n >= 0)) // true\n *\n * // or with `data-first` API\n * HashSet.every(set, (n) => n >= 0) // true\n * ```\n *\n * @returns A boolean once it has evaluated that whole collection fulfill the\n *   Predicate function\n * @see Other `HashSet` elements are {@link module:HashSet.has} {@link module:HashSet.some} {@link module:HashSet.isSubset}\n */\nexport const every: {\n  /**\n   * @example\n   *\n   * ```ts\n   * import * as assert from \"node:assert/strict\"\n   * import { Effect, HashSet, pipe, Predicate } from \"effect\"\n   *\n   * const numberOrString: HashSet.HashSet<number | string> = HashSet.make(\n   *   1,\n   *   \"1\",\n   *   \"one\",\n   *   \"uno\"\n   * )\n   *\n   * assert.equal(\n   *   pipe(\n   *     numberOrString, // HashSet.HashSet<number | string>\n   *     HashSet.every(Predicate.isString)\n   *   ), // HashSet.HashSet<string>\n   *   false\n   * )\n   * ```\n   */\n  <A, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>\n  ): (self: HashSet<A>) => self is HashSet<B>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import * as assert from \"node:assert/strict\"\n   * import { HashSet, pipe } from \"effect\"\n   *\n   * const set = HashSet.make(0, 1, 2)\n   *\n   * assert.equal(\n   *   pipe(\n   *     set,\n   *     HashSet.every((n) => n >= 0)\n   *   ),\n   *   true\n   * )\n   * ```\n   */\n  <A>(predicate: Predicate<A>): (self: HashSet<A>) => boolean\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import * as assert from \"node:assert/strict\"\n   * import { Effect, HashSet, pipe, Predicate } from \"effect\"\n   *\n   * const numberOrString: HashSet.HashSet<number | string> = HashSet.make(\n   *   1,\n   *   \"1\",\n   *   \"one\",\n   *   \"uno\"\n   * )\n   *\n   * assert.equal(\n   *   HashSet.every(\n   *     numberOrString, // HashSet.HashSet<number | string>\n   *     Predicate.isString\n   *   ), // HashSet.HashSet<string>\n   *   false\n   * )\n   * ```\n   */\n  <A, B extends A>(\n    self: HashSet<A>,\n    refinement: Refinement<A, B>\n  ): self is HashSet<B>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import * as assert from \"node:assert/strict\"\n   * import { HashSet } from \"effect\"\n   *\n   * const set = HashSet.make(0, 1, 2)\n   *\n   * assert.equal(\n   *   HashSet.every(set, (n) => n >= 0),\n   *   true\n   * )\n   * ```\n   */\n  <A>(self: HashSet<A>, predicate: Predicate<A>): boolean\n} = HS.every\n\n/**\n * Returns `true` if and only if every element in the this `HashSet` is an\n * element of the second set,\n *\n * **NOTE**: the hash and equal of both sets must be the same.\n *\n * Time complexity analysis is of **`O(n)`**\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category elements\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * const set1 = HashSet.make(0, 1)\n * const set2 = HashSet.make(1, 2)\n * const set3 = HashSet.make(0, 1, 2)\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(set1, HashSet.isSubset(set2)) // false\n * pipe(set1, HashSet.isSubset(set3)) // true\n *\n * // or piped with the pipe function\n * set1.pipe(HashSet.isSubset(set2)) // false\n * set1.pipe(HashSet.isSubset(set3)) // true\n *\n * // or with `data-first` API\n * HashSet.isSubset(set1, set2) // false\n * HashSet.isSubset(set1, set3) // true)\n * ```\n *\n * @see Other `HashSet` elements are {@link module:HashSet.has} {@link module:HashSet.some} {@link module:HashSet.every}\n */\nexport const isSubset: {\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * assert.equal(\n   *   pipe(\n   *     HashSet.make(0, 1), //\n   *     HashSet.isSubset(HashSet.make(1, 2))\n   *   ),\n   *   false\n   * )\n   *\n   * assert.equal(\n   *   pipe(\n   *     HashSet.make(0, 1), //\n   *     HashSet.isSubset(HashSet.make(0, 1, 2))\n   *   ),\n   *   true\n   * )\n   * ```\n   */\n  <A>(that: HashSet<A>): (self: HashSet<A>) => boolean\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * assert.equal(HashSet.isSubset(set1, set2), false)\n   *\n   * assert.equal(HashSet.isSubset(set1, set3), true)\n   * ```\n   */\n  <A>(self: HashSet<A>, that: HashSet<A>): boolean\n} = HS.isSubset\n\n/**\n * Returns an `IterableIterator` of the values in the `HashSet`.\n *\n * Time complexity: **`O(1)`**\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category getters\n * @example\n *\n * ```ts\n * import { HashSet, pipe } from \"effect\"\n *\n * const numberIterable = pipe(\n *   HashSet.make(0, 1, 1, 2), // HashSet.HashSet<number>\n *   HashSet.values // takes an HashSet<A> and returns an IterableIterator<A>\n * )\n *\n * for (const number of numberIterable) {\n *   console.log(number) // it will logs: 0, 1, 2\n * }\n * ```\n *\n * @see Other `HashSet` getters are {@link module:HashSet.toValues} {@link module:HashSet.size}\n */\nexport const values: <A>(self: HashSet<A>) => IterableIterator<A> = HS.values\n\n/**\n * Returns an `Array` of the values within the `HashSet`.\n *\n * Time complexity: **`O(n)`** where n is the number of elements in the set\n *\n * @memberof HashSet\n * @since 3.13.0\n * @category getters\n * @example\n *\n * ```ts\n * import { HashSet, pipe } from \"effect\"\n * import { deepStrictEqual } from \"node:assert/strict\"\n *\n * deepStrictEqual(\n *   pipe(\n *     HashSet.make(0, 1, 1, 2), // HashSet<number>\n *     HashSet.toValues // takes an HashSet<A> and returns an Array<A>\n *   ),\n *   Array.of(0, 1, 2)\n * )\n * ```\n *\n * @see Other `HashSet` getters are {@link module:HashSet.values} {@link module:HashSet.size}\n */\nexport const toValues = <A>(self: HashSet<A>): Array<A> => Array.from(values(self))\n\n/**\n * Calculates the number of values in the `HashSet`.\n *\n * Time complexity: **`O(1)`**\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category getters\n * @example\n *\n * ```ts\n * import { HashSet, pipe } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * assert.deepStrictEqual(pipe(HashSet.empty(), HashSet.size), 0)\n *\n * assert.deepStrictEqual(\n *   pipe(HashSet.make(1, 2, 2, 3, 4, 3), HashSet.size),\n *   4\n * )\n * ```\n *\n * @see Other `HashSet` getters are {@link module:HashSet.values} {@link module:HashSet.toValues}\n */\nexport const size: <A>(self: HashSet<A>) => number = HS.size\n\n/**\n * Creates a new mutable version of the `HashSet`\n *\n * When a `HashSet` is mutable, operations like {@link add} and {@link remove}\n * modify the data structure in place instead of creating a new one, which is\n * more efficient when performing multiple operations.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @example\n *\n * ```ts\n * import { HashSet } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * const UPPER_BOUND = 10_000\n *\n * const immutableSet = HashSet.empty<number>().pipe(HashSet.add(0))\n *\n * // Create a mutable version of the immutableSet\n * const mutableSet = HashSet.beginMutation(immutableSet)\n *\n * for (let i = 1; i < UPPER_BOUND; i++) {\n *   // Operations now modify the set in place instead of creating new instances\n *   // This is more efficient when making multiple changes\n *   const pointerToMutableSet = HashSet.add(mutableSet, i)\n *\n *   // the two sets have the same identity, hence `add` is mutating mutableSet and not returning a new HashSet instance\n *   assert(Object.is(mutableSet, pointerToMutableSet))\n *   assert.equal(HashSet.has(mutableSet, i), true) // `i` is in the mutableSet\n *   assert.equal(HashSet.has(immutableSet, i), false) // `i` is not in the immutableSet\n * }\n *\n * const next = UPPER_BOUND + 1\n * // When done, mark the set as immutable again\n * HashSet.endMutation(mutableSet).pipe(\n *   HashSet.add(next) // since this returns a new HashSet, it will not be logged as part of the mutableSet\n * )\n * assert.equal(HashSet.has(mutableSet, next), false)\n *\n * console.log(HashSet.toValues(immutableSet)) // [0]\n * console.log(HashSet.toValues(mutableSet).sort((a, b) => a - b)) // [0, 1, 2, 3, ...rest]\n * ```\n *\n * @see Other `HashSet` mutations are {@link module:HashSet.add} {@link module:HashSet.remove} {@link module:HashSet.toggle} {@link module:HashSet.endMutation} {@link module:HashSet.mutate}\n */\nexport const beginMutation: <A>(self: HashSet<A>) => HashSet<A> = HS.beginMutation\n\n/**\n * Makes the `HashSet` immutable again.\n *\n * After calling `endMutation`, operations like {@link add} and {@link remove}\n * will create new instances of the `HashSet` instead of modifying the existing\n * one.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @example\n *\n * ```ts\n * import { HashSet } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * // Create a mutable set\n * const mutableSet = HashSet.beginMutation(HashSet.empty<number>())\n *\n * // Add some elements to the mutable set\n * HashSet.add(mutableSet, 1)\n * HashSet.add(mutableSet, 2)\n *\n * // Before endMutation, operations modify the set in place\n * const sameSet = HashSet.add(mutableSet, 3)\n * assert(Object.is(mutableSet, sameSet)) // true - same object reference\n * assert.deepStrictEqual(HashSet.toValues(mutableSet).sort(), [1, 2, 3])\n *\n * // Make the set immutable again\n * const immutableSet = HashSet.endMutation(mutableSet)\n *\n * // endMutation returns the same set instance, now made immutable\n * assert(Object.is(mutableSet, immutableSet)) // true - same object reference\n *\n * // After endMutation, operations create new instances\n * const newSet = HashSet.add(immutableSet, 4)\n * assert(!Object.is(immutableSet, newSet)) // false - different object references\n *\n * // The original set remains unchanged\n * assert.deepStrictEqual(HashSet.toValues(immutableSet).sort(), [1, 2, 3])\n *\n * // The new set contains the added element\n * assert.deepStrictEqual(HashSet.toValues(newSet).sort(), [1, 2, 3, 4])\n * ```\n *\n * @see Other `HashSet` mutations are {@link module:HashSet.add} {@link module:HashSet.remove} {@link module:HashSet.toggle} {@link module:HashSet.beginMutation} {@link module:HashSet.mutate}\n */\nexport const endMutation: <A>(self: HashSet<A>) => HashSet<A> = HS.endMutation\n\n/**\n * Mutates the `HashSet` within the context of the provided function.\n *\n * You can consider it a functional abstraction on top of the lower-level\n * mutation primitives of {@link module:HashSet.beginMutation} `->` `mutable\n * context` `->` {@link HashSet.endMutation}.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with data-last, a.k.a. pipeable API\n * pipe(\n *   HashSet.make(1, 2, 3),\n *   HashSet.mutate((set) => {\n *     HashSet.add(set, 4)\n *     HashSet.remove(set, 1)\n *   })\n * )\n *\n * // or piped with the pipe function\n * HashSet.make(1, 2, 3).pipe(\n *   HashSet.mutate((set) => {\n *     HashSet.add(set, 4)\n *     HashSet.remove(set, 1)\n *   })\n * )\n *\n * // or with data-first API\n * HashSet.mutate(HashSet.make(1, 2, 3), (set) => {\n *   HashSet.add(set, 4)\n *   HashSet.remove(set, 1)\n * })\n * ```\n *\n * @see Other `HashSet` mutations are {@link module:HashSet.add} {@link module:HashSet.remove} {@link module:HashSet.toggle} {@link module:HashSet.beginMutation} {@link module:HashSet.endMutation}\n */\nexport const mutate: {\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-last` a.k.a. `pipeable` API\n   * import { HashSet, pipe } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * // Create a set with initial values\n   * const immutableSet = HashSet.make(1, 2, 3)\n   *\n   * // Use mutate to perform multiple operations efficiently\n   * const result = pipe(\n   *   immutableSet,\n   *   HashSet.mutate((set) => {\n   *     assert.equal(Object.is(immutableSet, set), false)\n   *\n   *     // The set is temporarily mutable inside this function\n   *     const mod1 = HashSet.add(set, 4)\n   *     const mod2 = HashSet.remove(set, 1)\n   *     assert.equal(Object.is(mod1, mod2), true) // they are the same object by reference\n   *   })\n   * )\n   *\n   * // The original set is unchanged\n   * assert.equal(Object.is(immutableSet, result), false)\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(immutableSet).sort(),\n   *   [1, 2, 3]\n   * )\n   *\n   * // The result contains the mutations\n   * assert.deepStrictEqual(HashSet.toValues(result).sort(), [2, 3, 4])\n   * ```\n   */\n  <A>(f: (set: HashSet<A>) => void): (self: HashSet<A>) => HashSet<A>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-first` API\n   * import { HashSet } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * // Create a set with initial values\n   * const immutableSet = HashSet.make(1, 2, 3)\n   *\n   * // Use mutate with data-first API\n   * const result = HashSet.mutate(immutableSet, (set) => {\n   *   // The set is temporarily mutable inside this function\n   *   HashSet.add(set, 4)\n   *   HashSet.remove(set, 1)\n   * })\n   *\n   * // The original set is unchanged\n   * assert.equal(Object.is(immutableSet, result), false)\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(immutableSet).sort(),\n   *   [1, 2, 3]\n   * )\n   *\n   * // The result contains the mutations\n   * assert.deepStrictEqual(HashSet.toValues(result).sort(), [2, 3, 4])\n   * ```\n   */\n  <A>(self: HashSet<A>, f: (set: HashSet<A>) => void): HashSet<A>\n} = HS.mutate\n\n/**\n * Adds a value to the `HashSet`.\n *\n * Time complexity: **`O(1)`** average\n *\n * @remarks\n * Remember that a `HashSet` is a collection of unique values, so adding a value\n * that already exists in the `HashSet` will not add a duplicate.\n *\n * Remember that HashSet is an immutable data structure, so the `add` function,\n * like all other functions that modify the HashSet, will return a new HashSet\n * with the added value.\n * @memberof HashSet\n * @since 2.0.0\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with data-last, a.k.a. pipeable API\n * pipe(HashSet.empty(), HashSet.add(0), HashSet.add(0))\n *\n * // or piped with the pipe function\n * HashSet.empty().pipe(HashSet.add(0))\n *\n * // or with data-first API\n * HashSet.add(HashSet.empty(), 0)\n * ```\n *\n * @see Other `HashSet` mutations are {@link module:HashSet.remove} {@link module:HashSet.toggle} {@link module:HashSet.beginMutation} {@link module:HashSet.endMutation} {@link module:HashSet.mutate}\n */\nexport const add: {\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-last` a.k.a. `pipeable` API\n   * import { HashSet, pipe } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * assert.deepStrictEqual(\n   *   pipe(\n   *     HashSet.empty<number>(), // HashSet.HashSet<number>\n   *     HashSet.add(0),\n   *     HashSet.add(1),\n   *     HashSet.add(1),\n   *     HashSet.add(2),\n   *     HashSet.toValues\n   *   ),\n   *   Array.of(0, 1, 2)\n   * )\n   * ```\n   */\n  <A>(value: A): (self: HashSet<A>) => HashSet<A>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-first` API\n   * import { HashSet, pipe } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * const empty = HashSet.empty<number>()\n   * const withZero = HashSet.add(empty, 0)\n   * const withOne = HashSet.add(withZero, 1)\n   * const withTwo = HashSet.add(withOne, 2)\n   * const withTwoTwo = HashSet.add(withTwo, 2)\n   *\n   * assert.deepStrictEqual(HashSet.toValues(withTwoTwo), Array.of(0, 1, 2))\n   * ```\n   */\n  <A>(self: HashSet<A>, value: A): HashSet<A>\n} = HS.add\n\n/**\n * Removes a value from the `HashSet`.\n *\n * Time complexity: **`O(1)`** average\n *\n * @memberof HashSet\n * @since 2.0.0\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(HashSet.make(0, 1, 2), HashSet.remove(0))\n *\n * // or piped with the pipe function\n * HashSet.make(0, 1, 2).pipe(HashSet.remove(0))\n *\n * // or with `data-first` API\n * HashSet.remove(HashSet.make(0, 1, 2), 0)\n * ```\n *\n * @see Other `HashSet` mutations are {@link module:HashSet.add} {@link module:HashSet.toggle} {@link module:HashSet.beginMutation} {@link module:HashSet.endMutation} {@link module:HashSet.mutate}\n */\nexport const remove: {\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-last` a.k.a. `pipeable` API\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const set = HashSet.make(0, 1, 2)\n   * const result = pipe(set, HashSet.remove(0))\n   *\n   * assert.equal(pipe(result, HashSet.has(0)), false) // it has correctly removed 0\n   * assert.equal(pipe(set, HashSet.has(0)), true) // it does not mutate the original set\n   * assert.equal(pipe(result, HashSet.has(1)), true)\n   * assert.equal(pipe(result, HashSet.has(2)), true)\n   * ```\n   */\n  <A>(value: A): (self: HashSet<A>) => HashSet<A>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-first` API\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const set = HashSet.make(0, 1, 2)\n   * const result = HashSet.remove(set, 0)\n   *\n   * assert.equal(HashSet.has(result, 0), false) // it has correctly removed 0\n   * assert.equal(HashSet.has(set, 0), true) // it does not mutate the original set\n   * assert.equal(HashSet.has(result, 1), true)\n   * assert.equal(HashSet.has(result, 2), true)\n   * ```\n   */\n  <A>(self: HashSet<A>, value: A): HashSet<A>\n} = HS.remove\n\n/**\n * Computes the set difference `(A - B)` between this `HashSet` and the\n * specified `Iterable<A>`.\n *\n * Time complexity: **`O(n)`** where n is the number of elements in the set\n *\n * **NOTE**: the hash and equal of the values in both the set and the iterable\n * must be the same; meaning we cannot compute a difference between a `HashSet\n * of bananas` and a `HashSet of elephants` as they are not the same type and\n * won't implement the Equal trait in the same way.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with data-last, a.k.a. pipeable API\n * pipe(HashSet.make(1, 2, 3), HashSet.difference(HashSet.make(3, 4, 5)))\n *\n * // or piped with the pipe function\n * HashSet.make(1, 2, 3).pipe(HashSet.difference(HashSet.make(3, 4, 5)))\n *\n * // or with data-first API\n * HashSet.difference(HashSet.make(1, 2, 3), HashSet.make(3, 4, 5))\n * ```\n *\n * @see Other `HashSet` operations are {@link module:HashSet.intersection} {@link module:HashSet.union}\n */\nexport const difference: {\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-last` a.k.a. `pipeable` API\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * // Create two sets with some overlapping elements\n   * const thisSet = HashSet.make(1, 2, 3)\n   * const thatIterable = HashSet.make(3, 4, 5)\n   *\n   * // Compute the difference (elements in thisSet that are not in thatIterable)\n   * const result = pipe(thisSet, HashSet.difference(thatIterable))\n   *\n   * // The result contains only elements from thisSet that are not in thatIterable\n   * assert.deepStrictEqual(HashSet.toValues(result).sort(), [1, 2])\n   *\n   * // The original sets are unchanged\n   * assert.deepStrictEqual(HashSet.toValues(thisSet).sort(), [1, 2, 3])\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(thatIterable).sort(),\n   *   [3, 4, 5]\n   * )\n   *\n   * // You can also use arrays or other iterables\n   * const diffWithArray = pipe(thisSet, HashSet.difference([3, 4]))\n   * assert.deepStrictEqual(HashSet.toValues(diffWithArray).sort(), [1, 2])\n   * ```\n   */\n  <A>(that: Iterable<A>): (self: HashSet<A>) => HashSet<A>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-first` API\n   * import { HashSet } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * // Create two sets with some overlapping elements\n   * const thisSet = HashSet.make(1, 2, 3)\n   * const thatIterable = HashSet.make(3, 4, 5)\n   *\n   * // Compute the difference using data-first API\n   * const result = HashSet.difference(thisSet, thatIterable)\n   *\n   * // The result contains only elements from thisSet that are not in thatIterable\n   * assert.deepStrictEqual(HashSet.toValues(result).sort(), [1, 2])\n   *\n   * // The original sets are unchanged\n   * assert.deepStrictEqual(HashSet.toValues(thisSet).sort(), [1, 2, 3])\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(thatIterable).sort(),\n   *   [3, 4, 5]\n   * )\n   *\n   * // You can also compute the difference in the other direction\n   * const reverseResult = HashSet.difference(thatIterable, thisSet)\n   * assert.deepStrictEqual(HashSet.toValues(reverseResult).sort(), [4, 5])\n   * ```\n   */\n  <A>(self: HashSet<A>, that: Iterable<A>): HashSet<A>\n} = HS.difference\n\n/**\n * Returns a `HashSet` of values which are present in both this set and that\n * `Iterable<A>`. Computes set intersection (A ∩ B)\n *\n * Time complexity: **`O(n)`** where n is the number of elements in the smaller\n * set\n *\n * **NOTE**: the hash and equal of the values in both the set and the iterable\n * must be the same.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with data-last, a.k.a. pipeable API\n * pipe(HashSet.make(1, 2, 3), HashSet.intersection(HashSet.make(2, 3, 4)))\n *\n * // or piped with the pipe function\n * HashSet.make(1, 2, 3).pipe(HashSet.intersection(HashSet.make(2, 3, 4)))\n *\n * // or with data-first API\n * HashSet.intersection(HashSet.make(1, 2, 3), HashSet.make(2, 3, 4))\n * ```\n *\n * @see Other `HashSet` operations are {@link module:HashSet.difference} {@link module:HashSet.union}\n */\nexport const intersection: {\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-last` a.k.a. `pipeable` API\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * // Create two sets with some overlapping elements\n   * const set1 = HashSet.make(1, 2, 3)\n   * const set2 = HashSet.make(2, 3, 4)\n   *\n   * // Compute the intersection (elements that are in both sets)\n   * const result = pipe(set1, HashSet.intersection(set2))\n   *\n   * // The result contains only elements that are in both sets\n   * assert.deepStrictEqual(HashSet.toValues(result).sort(), [2, 3])\n   *\n   * // The original sets are unchanged\n   * assert.deepStrictEqual(HashSet.toValues(set1).sort(), [1, 2, 3])\n   * assert.deepStrictEqual(HashSet.toValues(set2).sort(), [2, 3, 4])\n   *\n   * // You can also use arrays or other iterables\n   * const intersectWithArray = pipe(set1, HashSet.intersection([2, 3, 5]))\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(intersectWithArray).sort(),\n   *   [2, 3]\n   * )\n   * ```\n   */\n  <A>(that: Iterable<A>): (self: HashSet<A>) => HashSet<A>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-first` API\n   * import { HashSet } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * // Create two sets with some overlapping elements\n   * const set1 = HashSet.make(1, 2, 3)\n   * const set2 = HashSet.make(2, 3, 4)\n   *\n   * // Compute the intersection using data-first API\n   * const result = HashSet.intersection(set1, set2)\n   *\n   * // The result contains only elements that are in both sets\n   * assert.deepStrictEqual(HashSet.toValues(result).sort(), [2, 3])\n   *\n   * // The original sets are unchanged\n   * assert.deepStrictEqual(HashSet.toValues(set1).sort(), [1, 2, 3])\n   * assert.deepStrictEqual(HashSet.toValues(set2).sort(), [2, 3, 4])\n   *\n   * // You can also use arrays or other iterables\n   * const intersectWithArray = HashSet.intersection(set1, [2, 3, 5])\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(intersectWithArray).sort(),\n   *   [2, 3]\n   * )\n   * ```\n   */\n  <A>(self: HashSet<A>, that: Iterable<A>): HashSet<A>\n} = HS.intersection\n\n/**\n * Computes the set union `( self ∪ that )` between this `HashSet` and the\n * specified `Iterable<A>`.\n *\n * Time complexity: **`O(n)`** where n is the number of elements in the set\n *\n * **NOTE**: the hash and equal of the values in both the set and the iterable\n * must be the same.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with data-last, a.k.a. pipeable API\n * pipe(HashSet.make(1, 2, 3), HashSet.union(HashSet.make(3, 4, 5)))\n *\n * // or piped with the pipe function\n * HashSet.make(1, 2, 3).pipe(HashSet.union(HashSet.make(3, 4, 5)))\n *\n * // or with data-first API\n * HashSet.union(HashSet.make(1, 2, 3), HashSet.make(3, 4, 5))\n * ```\n *\n * @see Other `HashSet` operations are {@link module:HashSet.difference} {@link module:HashSet.intersection}\n */\nexport const union: {\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-last` a.k.a. `pipeable` API\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * // Create two sets with some overlapping elements\n   * const selfSet = HashSet.make(1, 2, 3)\n   * const thatIterable = HashSet.make(3, 4, 5)\n   *\n   * // Compute the union (all elements from both sets)\n   * const result = pipe(selfSet, HashSet.union(thatIterable))\n   *\n   * // The result contains all elements from both sets (without duplicates)\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(result).sort(),\n   *   [1, 2, 3, 4, 5]\n   * )\n   *\n   * // The original sets are unchanged\n   * assert.deepStrictEqual(HashSet.toValues(selfSet).sort(), [1, 2, 3])\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(thatIterable).sort(),\n   *   [3, 4, 5]\n   * )\n   *\n   * // You can also use arrays or other iterables\n   * const unionWithArray = pipe(selfSet, HashSet.union([4, 5, 6]))\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(unionWithArray).sort(),\n   *   [1, 2, 3, 4, 5, 6]\n   * )\n   * ```\n   */\n  <A>(that: Iterable<A>): (self: HashSet<A>) => HashSet<A>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-first` API\n   * import { HashSet } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * // Create two sets with some overlapping elements\n   * const selfSet = HashSet.make(1, 2, 3)\n   * const thatIterable = HashSet.make(3, 4, 5)\n   *\n   * // Compute the union using data-first API\n   * const result = HashSet.union(selfSet, thatIterable)\n   *\n   * // The result contains all elements from both sets (without duplicates)\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(result).sort(),\n   *   [1, 2, 3, 4, 5]\n   * )\n   *\n   * // The original sets are unchanged\n   * assert.deepStrictEqual(HashSet.toValues(selfSet).sort(), [1, 2, 3])\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(thatIterable).sort(),\n   *   [3, 4, 5]\n   * )\n   *\n   * // You can also use arrays or other iterables\n   * const unionWithArray = HashSet.union(selfSet, [4, 5, 6])\n   * assert.deepStrictEqual(\n   *   HashSet.toValues(unionWithArray).sort(),\n   *   [1, 2, 3, 4, 5, 6]\n   * )\n   * ```\n   */\n  <A>(self: HashSet<A>, that: Iterable<A>): HashSet<A>\n} = HS.union\n\n/**\n * Checks if a value is present in the `HashSet`. If it is present, the value\n * will be removed from the `HashSet`, otherwise the value will be added to the\n * `HashSet`.\n *\n * Time complexity: **`O(1)`** average\n *\n * @memberof HashSet\n * @since 2.0.0\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(HashSet.make(0, 1, 2), HashSet.toggle(0))\n *\n * // or piped with the pipe function\n * HashSet.make(0, 1, 2).pipe(HashSet.toggle(0))\n *\n * // or with `data-first` API\n * HashSet.toggle(HashSet.make(0, 1, 2), 0)\n * ```\n *\n * @returns A new `HashSet` where the toggled value is being either added or\n *   removed based on the initial `HashSet` state.\n * @see Other `HashSet` mutations are {@link module:HashSet.add} {@link module:HashSet.remove} {@link module:HashSet.beginMutation} {@link module:HashSet.endMutation} {@link module:HashSet.mutate}\n */\nexport const toggle: {\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-last` a.k.a. `pipeable` API\n   * import { HashSet, pipe } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * // arrange\n   * let set = HashSet.make(0, 1, 2)\n   *\n   * // assert 1: 0 is in the set\n   * assert.equal(pipe(set, HashSet.has(0)), true)\n   *\n   * // act 2: toggle 0 once on the set\n   * set = pipe(set, HashSet.toggle(0))\n   *\n   * // assert 2: 0 is not in the set any longer\n   * assert.equal(pipe(set, HashSet.has(0)), false)\n   *\n   * // act 3: toggle 0 once again on the set\n   * set = pipe(set, HashSet.toggle(0))\n   *\n   * // assert 3: 0 in now back in the set\n   * assert.equal(pipe(set, HashSet.has(0)), true)\n   * ```\n   */\n  <A>(value: A): (self: HashSet<A>) => HashSet<A>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * // `data-first` API\n   * import { HashSet, pipe } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * // arrange\n   * let set = HashSet.make(0, 1, 2)\n   *\n   * // assert 1: 0 is in the set\n   * assert.equal(HashSet.has(set, 0), true)\n   *\n   * // act 2: toggle 0 once on the set\n   * set = HashSet.toggle(set, 0)\n   *\n   * // assert 2: 0 is not in the set any longer\n   * assert.equal(HashSet.has(set, 0), false)\n   *\n   * // act 3: toggle 0 once again on the set\n   * set = HashSet.toggle(set, 0)\n   *\n   * // assert 3: 0 in now back in the set\n   * assert.equal(HashSet.has(set, 0), true)\n   * ```\n   */\n  <A>(self: HashSet<A>, value: A): HashSet<A>\n} = HS.toggle\n\n/**\n * Maps over the values of the `HashSet` using the specified function.\n *\n * The time complexity is of **`O(n)`**.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category mapping\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(\n *   HashSet.make(0, 1, 2), // HashSet.HashSet<number>\n *   HashSet.map(String) // HashSet.HashSet<string>\n * )\n *\n * // or piped with the pipe method\n * HashSet.make(0, 1, 2).pipe(HashSet.map(String))\n *\n * // or with `data-first` API\n * HashSet.map(HashSet.make(0, 1, 2), String)\n * ```\n */\nexport const map: {\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * assert.deepStrictEqual(\n   *   pipe(\n   *     HashSet.make(0, 1, 2), //    HashSet.HashSet<number>\n   *     HashSet.map((n) => String(n + 1)) // HashSet.HashSet<String>\n   *   ),\n   *   HashSet.make(\"1\", \"2\", \"3\")\n   * )\n   * ```\n   */\n  <A, B>(f: (a: A) => B): (self: HashSet<A>) => HashSet<B>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * assert.deepStrictEqual(\n   *   HashSet.map(\n   *     HashSet.make(0, 1, 2), //    HashSet.HashSet<number>\n   *     (n) => String(n + 1)\n   *   ), // HashSet.HashSet<String>\n   *   HashSet.make(\"1\", \"2\", \"3\")\n   * )\n   * ```\n   */\n  <A, B>(self: HashSet<A>, f: (a: A) => B): HashSet<B>\n} = HS.map\n\n/**\n * Chains over the values of the `HashSet` using the specified function.\n *\n * The time complexity is of **`O(n)`**.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category sequencing\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(\n *   HashSet.make(0, 1, 2), // HashSet.HashSet<number>\n *   HashSet.flatMap((n) => Array.of(String(n))) // HashSet.HashSet<string>\n * )\n *\n * // or piped with the pipe method\n * HashSet.make(0, 1, 2) // HashSet.HashSet<number>\n *   .pipe(\n *     HashSet.flatMap((n) => Array.of(String(n))) // HashSet.HashSet<string>\n *   )\n *\n * // or with `data-first` API\n * HashSet.flatMap(HashSet.make(0, 1, 2), (n) => Array.of(String(n)))\n * ```\n */\nexport const flatMap: {\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe, List } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * assert.deepStrictEqual(\n   *   pipe(\n   *     HashSet.make(0, 1, 2),\n   *     HashSet.flatMap((n) => List.of(String(n * n))) // needs to return an Iterable\n   *   ),\n   *   HashSet.make(\"0\", \"1\", \"4\")\n   * )\n   * ```\n   */\n  <A, B>(f: (a: A) => Iterable<B>): (self: HashSet<A>) => HashSet<B>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe, List } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * assert.deepStrictEqual(\n   *   HashSet.flatMap(HashSet.make(0, 1, 2), (n) =>\n   *     List.of(String(n * n * n))\n   *   ), // needs to return an Iterable\n   *   HashSet.make(\"0\", \"1\", \"8\")\n   * )\n   * ```\n   */\n  <A, B>(self: HashSet<A>, f: (a: A) => Iterable<B>): HashSet<B>\n} = HS.flatMap\n\n/**\n * Applies the specified function to the values of the `HashSet`.\n *\n * The time complexity is of **`O(n)`**.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category traversing\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(HashSet.make(0, 1, 2), HashSet.forEach(console.log)) // logs: 0 1 2\n *\n * // or piped with the pipe method\n * HashSet.make(0, 1, 2).pipe(HashSet.forEach(console.log)) // logs: 0 1 2\n *\n * // or with `data-first` API\n * HashSet.forEach(HashSet.make(0, 1, 2), console.log) // logs: 0 1 2\n * ```\n */\nexport const forEach: {\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const result: Array<number> = []\n   *\n   * pipe(\n   *   HashSet.make(0, 1, 2),\n   *   HashSet.forEach((n): void => {\n   *     result.push(n)\n   *   })\n   * )\n   *\n   * assert.deepStrictEqual(result, [0, 1, 2])\n   * ```\n   */\n  <A>(f: (value: A) => void): (self: HashSet<A>) => void\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const result: Array<number> = []\n   *\n   * HashSet.forEach(HashSet.make(0, 1, 2), (n): void => {\n   *   result.push(n)\n   * })\n   *\n   * assert.deepStrictEqual(result, [0, 1, 2])\n   * ```\n   */\n  <A>(self: HashSet<A>, f: (value: A) => void): void\n} = HS.forEach\n\n/**\n * Reduces the specified state over the values of the `HashSet`.\n *\n * The time complexity is of **`O(n)`**.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category folding\n * @example\n *\n * ```ts\n * // Syntax\n * import { HashSet, pipe } from \"effect\"\n *\n * const sum = (a: number, b: number): number => a + b\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(HashSet.make(0, 1, 2), HashSet.reduce(0, sum))\n *\n * // or with the pipe method\n * HashSet.make(0, 1, 2).pipe(HashSet.reduce(0, sum))\n *\n * // or with `data-first` API\n * HashSet.reduce(HashSet.make(0, 1, 2), 0, sum)\n * ```\n */\nexport const reduce: {\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * assert.equal(\n   *   pipe(\n   *     HashSet.make(0, 1, 2),\n   *     HashSet.reduce(10, (accumulator, value) => accumulator + value)\n   *   ),\n   *   13\n   * )\n   * ```\n   */\n  <A, Z>(zero: Z, f: (accumulator: Z, value: A) => Z): (self: HashSet<A>) => Z\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * assert.equal(\n   *   HashSet.reduce(\n   *     HashSet.make(0, 1, 2),\n   *     -3,\n   *     (accumulator, value) => accumulator + value\n   *   ),\n   *   0\n   * )\n   * ```\n   */\n  <A, Z>(self: HashSet<A>, zero: Z, f: (accumulator: Z, value: A) => Z): Z\n} = HS.reduce\n\n/**\n * Filters values out of a `HashSet` using the specified predicate.\n *\n * The time complexity is of **`O(n)`**.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category filtering\n * @example\n *\n * ```ts\n * // Syntax with  Predicate\n * import { HashSet, type Predicate, pipe } from \"effect\"\n *\n * const filterPositiveNumbers: Predicate.Predicate<number> = (n) => n > 0\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(\n *   HashSet.make(-2, -1, 0, 1, 2),\n *   HashSet.filter(filterPositiveNumbers)\n * )\n *\n * // or with the pipe method\n * HashSet.make(-2, -1, 0, 1, 2).pipe(HashSet.filter(filterPositiveNumbers))\n *\n * // or with `data-first` API\n * HashSet.filter(HashSet.make(-2, -1, 0, 1, 2), filterPositiveNumbers)\n * ```\n *\n * @example\n *\n * ```ts\n * /// Syntax with Refinement\n * import { HashSet, pipe } from \"effect\"\n *\n * const stringRefinement = (value: unknown): value is string =>\n *   typeof value === \"string\"\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(\n *   HashSet.make(1, \"unos\", 2, \"two\", 3, \"trois\", 4, \"vier\"), // // HashSet.HashSet<number | string>\n *   HashSet.filter(stringRefinement)\n * ) // HashSet.HashSet<string>\n *\n * // or with the pipe method\n * HashSet.make(1, \"unos\", 2, \"two\", 3, \"trois\", 4, \"vier\") // HashSet.HashSet<number | string>\n *   .pipe(HashSet.filter(stringRefinement)) // HashSet.HashSet<string>\n *\n * // or with `data-first` API\n * HashSet.filter(\n *   HashSet.make(1, \"unos\", 2, \"two\", 3, \"trois\", 4, \"vier\"), // HashSet.HashSet<number | string>\n *   stringRefinement\n * ) // HashSet.HashSet<string>\n * ```\n */\nexport const filter: {\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe, Predicate } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const numbersAndStringsHashSet: HashSet.HashSet<number | string> =\n   *   HashSet.make(1, \"unos\", 2, \"two\", 3, \"trois\", 4, \"vier\")\n   *\n   * const stringRefinement: Predicate.Refinement<\n   *   string | number,\n   *   string\n   * > = (value) => typeof value === \"string\"\n   *\n   * const stringHashSet: HashSet.HashSet<string> = pipe(\n   *   numbersAndStringsHashSet,\n   *   HashSet.filter(stringRefinement)\n   * )\n   *\n   * assert.equal(\n   *   pipe(stringHashSet, HashSet.every(Predicate.isString)),\n   *   true\n   * )\n   * ```\n   */\n  <A, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>\n  ): (self: HashSet<A>) => HashSet<B>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe, type Predicate } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const filterPositiveNumbers: Predicate.Predicate<number> = (n) => n > 0\n   *\n   * assert.deepStrictEqual(\n   *   pipe(\n   *     HashSet.make(-2, -1, 0, 1, 2),\n   *     HashSet.filter(filterPositiveNumbers)\n   *   ),\n   *   HashSet.make(1, 2)\n   * )\n   * ```\n   */\n  <A>(predicate: Predicate<NoInfer<A>>): (self: HashSet<A>) => HashSet<A>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, Predicate } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const numbersAndStringsHashSet: HashSet.HashSet<number | string> =\n   *   HashSet.make(1, \"unos\", 2, \"two\", 3, \"trois\", 4, \"vier\")\n   *\n   * const stringRefinement: Predicate.Refinement<\n   *   string | number,\n   *   string\n   * > = (value) => typeof value === \"string\"\n   *\n   * const stringHashSet: HashSet.HashSet<string> = HashSet.filter(\n   *   numbersAndStringsHashSet,\n   *   stringRefinement\n   * )\n   *\n   * assert.equal(HashSet.every(stringHashSet, Predicate.isString), true)\n   * ```\n   */\n  <A, B extends A>(\n    self: HashSet<A>,\n    refinement: Refinement<A, B>\n  ): HashSet<B>\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe, type Predicate } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const filterPositiveNumbers: Predicate.Predicate<number> = (n) => n > 0\n   *\n   * assert.deepStrictEqual(\n   *   HashSet.filter(HashSet.make(-2, -1, 0, 1, 2), filterPositiveNumbers),\n   *   HashSet.make(1, 2)\n   * )\n   * ```\n   */\n  <A>(self: HashSet<A>, predicate: Predicate<A>): HashSet<A>\n} = HS.filter\n\n/**\n * Partition the values of a `HashSet` using the specified predicate.\n *\n * If a value matches the predicate, it will be placed into the `HashSet` on the\n * right side of the resulting `Tuple`, otherwise the value will be placed into\n * the left side.\n *\n * Time complexity is of **`O(n)`**.\n *\n * @memberof HashSet\n * @since 2.0.0\n * @category partitioning\n * @example\n *\n * ```ts\n * // Syntax with Predicate\n * import { HashSet, pipe, Predicate } from \"effect\"\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(\n *   HashSet.make(0, 1, 2, 3, 4, 5),\n *   HashSet.partition((n) => n % 2 === 0)\n * )\n *\n * // or with the pipe method\n * HashSet.make(0, 1, 2, 3, 4, 5).pipe(\n *   HashSet.partition((n) => n % 2 === 0)\n * )\n *\n * // or with `data-first` API\n * HashSet.partition(HashSet.make(0, 1, 2, 3, 4, 5), (n) => n % 2 === 0)\n * ```\n *\n * @example\n *\n * ```ts\n * // Syntax with Refinement\n * import { HashSet, pipe, Predicate } from \"effect\"\n *\n * const stringRefinement: Predicate.Refinement<string | number, string> = (\n *   value\n * ) => typeof value === \"string\"\n *\n * // with `data-last`, a.k.a. `pipeable` API\n * pipe(\n *   HashSet.make(1, \"unos\", 2, \"two\", 3, \"trois\", 4, \"vier\"),\n *   HashSet.partition(stringRefinement)\n * )\n *\n * // or with the pipe method\n * HashSet.make(1, \"unos\", 2, \"two\", 3, \"trois\", 4, \"vier\").pipe(\n *   HashSet.partition(stringRefinement)\n * )\n *\n * // or with `data-first` API\n * HashSet.partition(\n *   HashSet.make(1, \"unos\", 2, \"two\", 3, \"trois\", 4, \"vier\"),\n *   stringRefinement\n * )\n * ```\n */\nexport const partition: {\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe, Predicate } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const numbersAndStringsHashSet: HashSet.HashSet<number | string> =\n   *   HashSet.make(1, \"unos\", 2, \"two\", 3, \"trois\", 4, \"vier\")\n   *\n   * const stringRefinement: Predicate.Refinement<\n   *   string | number,\n   *   string\n   * > = (value) => typeof value === \"string\"\n   *\n   * const [\n   *   excluded, // HashSet.HashSet<number>\n   *   satisfying // HashSet.HashSet<string>\n   * ] = pipe(numbersAndStringsHashSet, HashSet.partition(stringRefinement))\n   *\n   * assert.equal(pipe(satisfying, HashSet.every(Predicate.isString)), true)\n   * assert.equal(pipe(excluded, HashSet.every(Predicate.isNumber)), true)\n   *\n   * assert.deepStrictEqual(excluded, HashSet.make(1, 2, 3, 4))\n   * assert.deepStrictEqual(\n   *   satisfying,\n   *   HashSet.make(\"unos\", \"two\", \"trois\", \"vier\")\n   * )\n   * ```\n   */\n  <A, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>\n  ): (\n    self: HashSet<A>\n  ) => [excluded: HashSet<Exclude<A, B>>, satisfying: HashSet<B>]\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const [excluded, satisfying] = pipe(\n   *   HashSet.make(0, 1, 2, 3, 4, 5),\n   *   HashSet.partition((n) => n % 2 === 0)\n   * )\n   *\n   * assert.deepStrictEqual(excluded, HashSet.make(1, 3, 5))\n   * assert.deepStrictEqual(satisfying, HashSet.make(0, 2, 4))\n   * ```\n   */\n  <A>(\n    predicate: Predicate<NoInfer<A>>\n  ): (self: HashSet<A>) => [excluded: HashSet<A>, satisfying: HashSet<A>]\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet, pipe, Predicate } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const numbersAndStringsHashSet: HashSet.HashSet<number | string> =\n   *   HashSet.make(1, \"unos\", 2, \"two\", 3, \"trois\", 4, \"vier\")\n   *\n   * const stringRefinement: Predicate.Refinement<\n   *   string | number,\n   *   string\n   * > = (value) => typeof value === \"string\"\n   *\n   * const [\n   *   excluded, // HashSet.HashSet<number>\n   *   satisfying // HashSet.HashSet<string>\n   * ] = HashSet.partition(numbersAndStringsHashSet, stringRefinement)\n   *\n   * assert.equal(HashSet.every(satisfying, Predicate.isString), true)\n   * assert.equal(HashSet.every(excluded, Predicate.isNumber), true)\n   *\n   * assert.deepStrictEqual(excluded, HashSet.make(1, 2, 3, 4))\n   * assert.deepStrictEqual(\n   *   satisfying,\n   *   HashSet.make(\"unos\", \"two\", \"trois\", \"vier\")\n   * )\n   * ```\n   */\n  <A, B extends A>(\n    self: HashSet<A>,\n    refinement: Refinement<A, B>\n  ): [excluded: HashSet<Exclude<A, B>>, satisfying: HashSet<B>]\n\n  /**\n   * @example\n   *\n   * ```ts\n   * import { HashSet } from \"effect\"\n   * import * as assert from \"node:assert/strict\"\n   *\n   * const [excluded, satisfying] = HashSet.partition(\n   *   HashSet.make(0, 1, 2, 3, 4, 5),\n   *   (n) => n % 2 === 0\n   * )\n   *\n   * assert.deepStrictEqual(excluded, HashSet.make(1, 3, 5))\n   * assert.deepStrictEqual(satisfying, HashSet.make(0, 2, 4))\n   * ```\n   */\n  <A>(\n    self: HashSet<A>,\n    predicate: Predicate<A>\n  ): [excluded: HashSet<A>, satisfying: HashSet<A>]\n} = HS.partition\n"
  },
  {
    "path": "packages/effect/src/Inspectable.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as FiberRefs from \"./FiberRefs.js\"\nimport { globalValue } from \"./GlobalValue.js\"\nimport * as Predicate from \"./Predicate.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const NodeInspectSymbol = Symbol.for(\"nodejs.util.inspect.custom\")\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type NodeInspectSymbol = typeof NodeInspectSymbol\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Inspectable {\n  toString(): string\n  toJSON(): unknown\n  [NodeInspectSymbol](): unknown\n}\n\n/**\n * @since 2.0.0\n */\nexport const toJSON = (x: unknown): unknown => {\n  try {\n    if (\n      Predicate.hasProperty(x, \"toJSON\") && Predicate.isFunction(x[\"toJSON\"]) &&\n      x[\"toJSON\"].length === 0\n    ) {\n      return x.toJSON()\n    } else if (Array.isArray(x)) {\n      return x.map(toJSON)\n    }\n  } catch {\n    return {}\n  }\n  return redact(x)\n}\n\nconst CIRCULAR = \"[Circular]\"\n\n/** @internal */\nexport function formatDate(date: Date): string {\n  try {\n    return date.toISOString()\n  } catch {\n    return \"Invalid Date\"\n  }\n}\n\nfunction safeToString(input: any): string {\n  try {\n    const s = input.toString()\n    return typeof s === \"string\" ? s : String(s)\n  } catch {\n    return \"[toString threw]\"\n  }\n}\n\n/** @internal */\nexport function formatPropertyKey(name: PropertyKey): string {\n  return Predicate.isString(name) ? JSON.stringify(name) : String(name)\n}\n\n/** @internal */\nexport function formatUnknown(\n  input: unknown,\n  options?: {\n    readonly space?: number | string | undefined\n    readonly ignoreToString?: boolean | undefined\n  }\n): string {\n  const space = options?.space ?? 0\n  const seen = new WeakSet<object>()\n  const gap = !space ? \"\" : (Predicate.isNumber(space) ? \" \".repeat(space) : space)\n  const ind = (d: number) => gap.repeat(d)\n\n  const wrap = (v: unknown, body: string): string => {\n    const ctor = (v as any)?.constructor\n    return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body\n  }\n\n  const ownKeys = (o: object): Array<PropertyKey> => {\n    try {\n      return Reflect.ownKeys(o)\n    } catch {\n      return [\"[ownKeys threw]\"]\n    }\n  }\n\n  function go(v: unknown, d = 0): string {\n    if (Array.isArray(v)) {\n      if (seen.has(v)) return CIRCULAR\n      seen.add(v)\n      if (!gap || v.length <= 1) return `[${v.map((x) => go(x, d)).join(\",\")}]`\n      const inner = v.map((x) => go(x, d + 1)).join(\",\\n\" + ind(d + 1))\n      return `[\\n${ind(d + 1)}${inner}\\n${ind(d)}]`\n    }\n\n    if (Predicate.isDate(v)) return formatDate(v)\n\n    if (\n      !options?.ignoreToString &&\n      Predicate.hasProperty(v, \"toString\") &&\n      Predicate.isFunction(v[\"toString\"]) &&\n      v[\"toString\"] !== Object.prototype.toString &&\n      v[\"toString\"] !== Array.prototype.toString\n    ) {\n      const s = safeToString(v)\n      if (v instanceof Error && v.cause) {\n        return `${s} (cause: ${go(v.cause, d)})`\n      }\n      return s\n    }\n\n    if (Predicate.isString(v)) return JSON.stringify(v)\n\n    if (\n      Predicate.isNumber(v) ||\n      v == null ||\n      Predicate.isBoolean(v) ||\n      Predicate.isSymbol(v)\n    ) return String(v)\n\n    if (Predicate.isBigInt(v)) return String(v) + \"n\"\n\n    if (v instanceof Set || v instanceof Map) {\n      if (seen.has(v)) return CIRCULAR\n      seen.add(v)\n      return `${v.constructor.name}(${go(Array.from(v), d)})`\n    }\n\n    if (Predicate.isObject(v)) {\n      if (seen.has(v)) return CIRCULAR\n      seen.add(v)\n      const keys = ownKeys(v)\n      if (!gap || keys.length <= 1) {\n        const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${go((v as any)[k], d)}`).join(\",\")}}`\n        return wrap(v, body)\n      }\n      const body = `{\\n${\n        keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${go((v as any)[k], d + 1)}`).join(\",\\n\")\n      }\\n${ind(d)}}`\n      return wrap(v, body)\n    }\n\n    return String(v)\n  }\n\n  return go(input, 0)\n}\n\n/**\n * @since 2.0.0\n */\nexport const format = (x: unknown): string => JSON.stringify(x, null, 2)\n\n/**\n * @since 2.0.0\n */\nexport const BaseProto: Inspectable = {\n  toJSON() {\n    return toJSON(this)\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  toString() {\n    return format(this.toJSON())\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport abstract class Class {\n  /**\n   * @since 2.0.0\n   */\n  abstract toJSON(): unknown\n  /**\n   * @since 2.0.0\n   */\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  }\n  /**\n   * @since 2.0.0\n   */\n  toString() {\n    return format(this.toJSON())\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport const toStringUnknown = (u: unknown, whitespace: number | string | undefined = 2): string => {\n  if (typeof u === \"string\") {\n    return u\n  }\n  try {\n    return typeof u === \"object\" ? stringifyCircular(u, whitespace) : String(u)\n  } catch {\n    return String(u)\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport const stringifyCircular = (obj: unknown, whitespace?: number | string | undefined): string => {\n  let cache: Array<unknown> = []\n  const retVal = JSON.stringify(\n    obj,\n    (_key, value) =>\n      typeof value === \"object\" && value !== null\n        ? cache.includes(value)\n          ? undefined // circular reference\n          : cache.push(value) && (redactableState.fiberRefs !== undefined && isRedactable(value)\n            ? value[symbolRedactable](redactableState.fiberRefs)\n            : value)\n        : value,\n    whitespace\n  )\n  ;(cache as any) = undefined\n  return retVal\n}\n\n/**\n * @since 3.10.0\n * @category redactable\n */\nexport interface Redactable {\n  readonly [symbolRedactable]: (fiberRefs: FiberRefs.FiberRefs) => unknown\n}\n\n/**\n * @since 3.10.0\n * @category redactable\n */\nexport const symbolRedactable: unique symbol = Symbol.for(\"effect/Inspectable/Redactable\")\n\n/**\n * @since 3.10.0\n * @category redactable\n */\nexport const isRedactable = (u: unknown): u is Redactable =>\n  typeof u === \"object\" && u !== null && symbolRedactable in u\n\nconst redactableState = globalValue(\"effect/Inspectable/redactableState\", () => ({\n  fiberRefs: undefined as FiberRefs.FiberRefs | undefined\n}))\n\n/**\n * @since 3.10.0\n * @category redactable\n */\nexport const withRedactableContext = <A>(context: FiberRefs.FiberRefs, f: () => A): A => {\n  const prev = redactableState.fiberRefs\n  redactableState.fiberRefs = context\n  try {\n    return f()\n  } finally {\n    redactableState.fiberRefs = prev\n  }\n}\n\n/**\n * @since 3.10.0\n * @category redactable\n */\nexport const redact = (u: unknown): unknown => {\n  if (isRedactable(u) && redactableState.fiberRefs !== undefined) {\n    return u[symbolRedactable](redactableState.fiberRefs)\n  }\n  return u\n}\n"
  },
  {
    "path": "packages/effect/src/Iterable.ts",
    "content": "/**\n * This module provides utility functions for working with Iterables in TypeScript.\n *\n * @since 2.0.0\n */\n\nimport type { NonEmptyArray } from \"./Array.js\"\nimport type { Either } from \"./Either.js\"\nimport * as E from \"./Either.js\"\nimport * as Equal from \"./Equal.js\"\nimport { dual, identity } from \"./Function.js\"\nimport type { Option } from \"./Option.js\"\nimport * as O from \"./Option.js\"\nimport { isBoolean } from \"./Predicate.js\"\nimport type * as Record from \"./Record.js\"\nimport * as Tuple from \"./Tuple.js\"\nimport type { NoInfer } from \"./Types.js\"\n\n/**\n * Return a `Iterable` with element `i` initialized with `f(i)`.\n *\n * If the `length` is not specified, the `Iterable` will be infinite.\n *\n * **Note**. `length` is normalized to an integer >= 1.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { makeBy } from \"effect/Iterable\"\n *\n * assert.deepStrictEqual(Array.from(makeBy(n => n * 2, { length: 5 })), [0, 2, 4, 6, 8])\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const makeBy = <A>(f: (i: number) => A, options?: {\n  readonly length?: number\n}): Iterable<A> => {\n  const max = options?.length !== undefined ? Math.max(1, Math.floor(options.length)) : Infinity\n  return {\n    [Symbol.iterator]() {\n      let i = 0\n      return {\n        next(): IteratorResult<A> {\n          if (i < max) {\n            return { value: f(i++), done: false }\n          }\n          return { done: true, value: undefined }\n        }\n      }\n    }\n  }\n}\n\n/**\n * Return a `Iterable` containing a range of integers, including both endpoints.\n *\n * If `end` is omitted, the range will not have an upper bound.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { range } from \"effect/Iterable\"\n *\n * assert.deepStrictEqual(Array.from(range(1, 3)), [1, 2, 3])\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const range = (start: number, end?: number): Iterable<number> => {\n  if (end === undefined) {\n    return makeBy((i) => start + i)\n  }\n  return makeBy((i) => start + i, {\n    length: start <= end ? end - start + 1 : 1\n  })\n}\n\n/**\n * Return a `Iterable` containing a value repeated the specified number of times.\n *\n * **Note**. `n` is normalized to an integer >= 1.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { replicate } from \"effect/Iterable\"\n *\n * assert.deepStrictEqual(Array.from(replicate(\"a\", 3)), [\"a\", \"a\", \"a\"])\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const replicate: {\n  (n: number): <A>(a: A) => Iterable<A>\n  <A>(a: A, n: number): Iterable<A>\n} = dual(2, <A>(a: A, n: number): Iterable<A> => makeBy(() => a, { length: n }))\n\n/**\n * Takes a record and returns an Iterable of tuples containing its keys and values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { fromRecord } from \"effect/Iterable\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * assert.deepStrictEqual(Array.from(fromRecord(x)), [[\"a\", 1], [\"b\", 2], [\"c\", 3]])\n * ```\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const fromRecord = <K extends string, A>(self: Readonly<Record<K, A>>): Iterable<[K, A]> => ({\n  *[Symbol.iterator]() {\n    for (const key in self) {\n      if (Object.prototype.hasOwnProperty.call(self, key)) {\n        yield [key, self[key]]\n      }\n    }\n  }\n})\n\n/**\n * Prepend an element to the front of an `Iterable`, creating a new `Iterable`.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const prepend: {\n  <B>(head: B): <A>(self: Iterable<A>) => Iterable<A | B>\n  <A, B>(self: Iterable<A>, head: B): Iterable<A | B>\n} = dual(2, <A, B>(self: Iterable<A>, head: B): Iterable<A | B> => prependAll(self, [head]))\n\n/**\n * Prepends the specified prefix iterable to the beginning of the specified iterable.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Iterable } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Array.from(Iterable.prependAll([1, 2], [\"a\", \"b\"])),\n *   [\"a\", \"b\", 1, 2]\n * )\n * ```\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const prependAll: {\n  <B>(that: Iterable<B>): <A>(self: Iterable<A>) => Iterable<A | B>\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Iterable<A | B>\n} = dual(\n  2,\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Iterable<A | B> => appendAll(that, self)\n)\n\n/**\n * Append an element to the end of an `Iterable`, creating a new `Iterable`.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const append: {\n  <B>(last: B): <A>(self: Iterable<A>) => Iterable<A | B>\n  <A, B>(self: Iterable<A>, last: B): Iterable<A | B>\n} = dual(2, <A, B>(self: Iterable<A>, last: B): Iterable<A | B> => appendAll(self, [last]))\n\n/**\n * Concatenates two iterables, combining their elements.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const appendAll: {\n  <B>(that: Iterable<B>): <A>(self: Iterable<A>) => Iterable<A | B>\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Iterable<A | B>\n} = dual(\n  2,\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Iterable<A | B> => ({\n    [Symbol.iterator]() {\n      const iterA = self[Symbol.iterator]()\n      let doneA = false\n      let iterB: Iterator<B>\n      return {\n        next() {\n          if (!doneA) {\n            const r = iterA.next()\n            if (r.done) {\n              doneA = true\n              iterB = that[Symbol.iterator]()\n              return iterB.next()\n            }\n            return r\n          }\n          return iterB.next()\n        }\n      }\n    }\n  })\n)\n\n/**\n * Reduce an `Iterable` from the left, keeping all intermediate results instead of only the final result.\n *\n * @category folding\n * @since 2.0.0\n */\nexport const scan: {\n  <B, A>(b: B, f: (b: B, a: A) => B): (self: Iterable<A>) => Iterable<B>\n  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): Iterable<B>\n} = dual(3, <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A) => B): Iterable<B> => ({\n  [Symbol.iterator]() {\n    let acc = b\n    let iterator: Iterator<A> | undefined\n    function next() {\n      if (iterator === undefined) {\n        iterator = self[Symbol.iterator]()\n        return { done: false, value: acc }\n      }\n      const result = iterator.next()\n      if (result.done) {\n        return result\n      }\n      acc = f(acc, result.value)\n      return { done: false, value: acc }\n    }\n    return { next }\n  }\n}))\n\n/**\n * Determine if an `Iterable` is empty\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isEmpty } from \"effect/Iterable\"\n *\n * assert.deepStrictEqual(isEmpty([]), true);\n * assert.deepStrictEqual(isEmpty([1, 2, 3]), false);\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEmpty = <A>(self: Iterable<A>): self is Iterable<never> => {\n  const iterator = self[Symbol.iterator]()\n  return iterator.next().done === true\n}\n\n/**\n * Return the number of elements in a `Iterable`.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const size = <A>(self: Iterable<A>): number => {\n  const iterator = self[Symbol.iterator]()\n  let count = 0\n  while (!iterator.next().done) {\n    count++\n  }\n  return count\n}\n\n/**\n * Get the first element of a `Iterable`, or `None` if the `Iterable` is empty.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const head = <A>(self: Iterable<A>): Option<A> => {\n  const iterator = self[Symbol.iterator]()\n  const result = iterator.next()\n  return result.done ? O.none() : O.some(result.value)\n}\n\n/**\n * Get the first element of a `Iterable`, or throw an error if the `Iterable` is empty.\n *\n * @category getters\n * @since 3.3.0\n */\nexport const unsafeHead = <A>(self: Iterable<A>): A => {\n  const iterator = self[Symbol.iterator]()\n  const result = iterator.next()\n  if (result.done) throw new Error(\"unsafeHead: empty iterable\")\n  return result.value\n}\n\n/**\n * Keep only a max number of elements from the start of an `Iterable`, creating a new `Iterable`.\n *\n * **Note**. `n` is normalized to a non negative integer.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const take: {\n  (n: number): <A>(self: Iterable<A>) => Iterable<A>\n  <A>(self: Iterable<A>, n: number): Iterable<A>\n} = dual(2, <A>(self: Iterable<A>, n: number): Iterable<A> => ({\n  [Symbol.iterator]() {\n    let i = 0\n    const iterator = self[Symbol.iterator]()\n    return {\n      next() {\n        if (i < n) {\n          i++\n          return iterator.next()\n        }\n        return { done: true, value: undefined }\n      }\n    }\n  }\n}))\n\n/**\n * Calculate the longest initial Iterable for which all element satisfy the specified predicate, creating a new `Iterable`.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const takeWhile: {\n  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Iterable<B>\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Iterable<A>\n  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Iterable<B>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Iterable<A>\n} = dual(2, <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Iterable<A> => ({\n  [Symbol.iterator]() {\n    const iterator = self[Symbol.iterator]()\n    let i = 0\n    return {\n      next() {\n        const result = iterator.next()\n        if (result.done || !predicate(result.value, i++)) {\n          return { done: true, value: undefined }\n        }\n        return result\n      }\n    }\n  }\n}))\n\n/**\n * Drop a max number of elements from the start of an `Iterable`\n *\n * **Note**. `n` is normalized to a non negative integer.\n *\n * @category getters\n * @since 2.0.0\n */\nexport const drop: {\n  (n: number): <A>(self: Iterable<A>) => Iterable<A>\n  <A>(self: Iterable<A>, n: number): Iterable<A>\n} = dual(2, <A>(self: Iterable<A>, n: number): Iterable<A> => ({\n  [Symbol.iterator]() {\n    const iterator = self[Symbol.iterator]()\n    let i = 0\n    return {\n      next() {\n        while (i < n) {\n          const result = iterator.next()\n          if (result.done) {\n            return { done: true, value: undefined }\n          }\n          i++\n        }\n        return iterator.next()\n      }\n    }\n  }\n}))\n\n/**\n * Returns the first element that satisfies the specified\n * predicate, or `None` if no such element exists.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findFirst: {\n  <A, B>(f: (a: NoInfer<A>, i: number) => Option<B>): (self: Iterable<A>) => Option<B>\n  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Option<B>\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option<A>\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>): Option<B>\n  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Option<B>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option<A>\n} = dual(\n  2,\n  <A>(self: Iterable<A>, f: ((a: A, i: number) => boolean) | ((a: A, i: number) => Option<A>)): Option<A> => {\n    let i = 0\n    for (const a of self) {\n      const o = f(a, i)\n      if (isBoolean(o)) {\n        if (o) {\n          return O.some(a)\n        }\n      } else {\n        if (O.isSome(o)) {\n          return o\n        }\n      }\n      i++\n    }\n    return O.none()\n  }\n)\n\n/**\n * Find the last element for which a predicate holds.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findLast: {\n  <A, B>(f: (a: NoInfer<A>, i: number) => Option<B>): (self: Iterable<A>) => Option<B>\n  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Option<B>\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Option<A>\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>): Option<B>\n  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Option<B>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Option<A>\n} = dual(\n  2,\n  <A>(self: Iterable<A>, f: ((a: A, i: number) => boolean) | ((a: A, i: number) => Option<A>)): Option<A> => {\n    let i = 0\n    let last: Option<A> = O.none()\n    for (const a of self) {\n      const o = f(a, i)\n      if (isBoolean(o)) {\n        if (o) {\n          last = O.some(a)\n        }\n      } else {\n        if (O.isSome(o)) {\n          last = o\n        }\n      }\n      i++\n    }\n    return last\n  }\n)\n\n/**\n * Takes two `Iterable`s and returns an `Iterable` of corresponding pairs.\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zip: {\n  <B>(that: Iterable<B>): <A>(self: Iterable<A>) => Iterable<[A, B]>\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Iterable<[A, B]>\n} = dual(\n  2,\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Iterable<[A, B]> => zipWith(self, that, Tuple.make)\n)\n\n/**\n * Apply a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one\n * input `Iterable` is short, excess elements of the longer `Iterable` are discarded.\n *\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith: {\n  <B, A, C>(that: Iterable<B>, f: (a: A, b: B) => C): (self: Iterable<A>) => Iterable<C>\n  <A, B, C>(self: Iterable<A>, that: Iterable<B>, f: (a: A, b: B) => C): Iterable<C>\n} = dual(3, <B, A, C>(self: Iterable<A>, that: Iterable<B>, f: (a: A, b: B) => C): Iterable<C> => ({\n  [Symbol.iterator]() {\n    const selfIterator = self[Symbol.iterator]()\n    const thatIterator = that[Symbol.iterator]()\n    return {\n      next() {\n        const selfResult = selfIterator.next()\n        const thatResult = thatIterator.next()\n        if (selfResult.done || thatResult.done) {\n          return { done: true, value: undefined }\n        }\n        return { done: false, value: f(selfResult.value, thatResult.value) }\n      }\n    }\n  }\n}))\n\n/**\n * Places an element in between members of an `Iterable`.\n * If the input is a non-empty array, the result is also a non-empty array.\n *\n * @since 2.0.0\n */\nexport const intersperse: {\n  <B>(middle: B): <A>(self: Iterable<A>) => Iterable<A | B>\n  <A, B>(self: Iterable<A>, middle: B): Iterable<A | B>\n} = dual(2, <A, B>(self: Iterable<A>, middle: B): Iterable<A | B> => ({\n  [Symbol.iterator]() {\n    const iterator = self[Symbol.iterator]()\n    let next = iterator.next()\n    let emitted = false\n    return {\n      next() {\n        if (next.done) {\n          return next\n        } else if (emitted) {\n          emitted = false\n          return { done: false, value: middle }\n        }\n        emitted = true\n        const result = next\n        next = iterator.next()\n        return result\n      }\n    }\n  }\n}))\n\n/**\n * Returns a function that checks if an `Iterable` contains a given value using a provided `isEquivalent` function.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const containsWith = <A>(isEquivalent: (self: A, that: A) => boolean): {\n  (a: A): (self: Iterable<A>) => boolean\n  (self: Iterable<A>, a: A): boolean\n} =>\n  dual(2, (self: Iterable<A>, a: A): boolean => {\n    for (const i of self) {\n      if (isEquivalent(a, i)) {\n        return true\n      }\n    }\n    return false\n  })\n\nconst _equivalence = Equal.equivalence()\n\n/**\n * Returns a function that checks if a `Iterable` contains a given value using the default `Equivalence`.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const contains: {\n  <A>(a: A): (self: Iterable<A>) => boolean\n  <A>(self: Iterable<A>, a: A): boolean\n} = containsWith(_equivalence)\n\n/**\n * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of\n * the `Iterable`.\n *\n * @category splitting\n * @since 2.0.0\n */\nexport const chunksOf: {\n  (n: number): <A>(self: Iterable<A>) => Iterable<Array<A>>\n  <A>(self: Iterable<A>, n: number): Iterable<Array<A>>\n} = dual(2, <A>(self: Iterable<A>, n: number): Iterable<Array<A>> => {\n  const safeN = Math.max(1, Math.floor(n))\n  return ({\n    [Symbol.iterator]() {\n      let iterator: Iterator<A> | undefined = self[Symbol.iterator]()\n      return {\n        next() {\n          if (iterator === undefined) {\n            return { done: true, value: undefined }\n          }\n\n          const chunk: Array<A> = []\n          for (let i = 0; i < safeN; i++) {\n            const result = iterator.next()\n            if (result.done) {\n              iterator = undefined\n              return chunk.length === 0 ? { done: true, value: undefined } : { done: false, value: chunk }\n            }\n            chunk.push(result.value)\n          }\n\n          return { done: false, value: chunk }\n        }\n      }\n    }\n  })\n})\n\n/**\n * Group equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function.\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupWith: {\n  <A>(isEquivalent: (self: A, that: A) => boolean): (self: Iterable<A>) => Iterable<NonEmptyArray<A>>\n  <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): Iterable<NonEmptyArray<A>>\n} = dual(\n  2,\n  <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): Iterable<NonEmptyArray<A>> => ({\n    [Symbol.iterator]() {\n      const iterator = self[Symbol.iterator]()\n      let nextResult: IteratorResult<A> | undefined\n      return {\n        next() {\n          let result: IteratorResult<A>\n          if (nextResult !== undefined) {\n            if (nextResult.done) {\n              return { done: true, value: undefined }\n            }\n            result = nextResult\n            nextResult = undefined\n          } else {\n            result = iterator.next()\n            if (result.done) {\n              return { done: true, value: undefined }\n            }\n          }\n          const chunk: NonEmptyArray<A> = [result.value]\n\n          while (true) {\n            const next = iterator.next()\n            if (next.done || !isEquivalent(result.value, next.value)) {\n              nextResult = next\n              return { done: false, value: chunk }\n            }\n            chunk.push(next.value)\n          }\n        }\n      }\n    }\n  })\n)\n\n/**\n * Group equal, consecutive elements of an `Iterable` into `NonEmptyArray`s.\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const group: <A>(self: Iterable<A>) => Iterable<NonEmptyArray<A>> = groupWith(\n  Equal.equivalence()\n)\n\n/**\n * Splits an `Iterable` into sub-non-empty-arrays stored in an object, based on the result of calling a `string`-returning\n * function on each element, and grouping the results according to values returned\n *\n * @category grouping\n * @since 2.0.0\n */\nexport const groupBy: {\n  <A, K extends string | symbol>(\n    f: (a: A) => K\n  ): (self: Iterable<A>) => Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>>\n  <A, K extends string | symbol>(\n    self: Iterable<A>,\n    f: (a: A) => K\n  ): Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>>\n} = dual(2, <A, K extends string | symbol>(\n  self: Iterable<A>,\n  f: (a: A) => K\n): Record<Record.ReadonlyRecord.NonLiteralKey<K>, NonEmptyArray<A>> => {\n  const out: Record<string | symbol, NonEmptyArray<A>> = {}\n  for (const a of self) {\n    const k = f(a)\n    if (Object.prototype.hasOwnProperty.call(out, k)) {\n      out[k].push(a)\n    } else {\n      out[k] = [a]\n    }\n  }\n  return out\n})\n\nconst constEmpty: Iterable<never> = {\n  [Symbol.iterator]() {\n    return constEmptyIterator\n  }\n}\nconst constEmptyIterator: Iterator<never> = {\n  next() {\n    return { done: true, value: undefined }\n  }\n}\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = <A = never>(): Iterable<A> => constEmpty\n\n/**\n * Constructs a new `Iterable<A>` from the specified value.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const of = <A>(a: A): Iterable<A> => [a]\n\n/**\n * @category mapping\n * @since 2.0.0\n */\nexport const map: {\n  <A, B>(\n    f: (a: NoInfer<A>, i: number) => B\n  ): (self: Iterable<A>) => Iterable<B>\n  <A, B>(self: Iterable<A>, f: (a: NoInfer<A>, i: number) => B): Iterable<B>\n} = dual(2, <A, B>(self: Iterable<A>, f: (a: A, i: number) => B): Iterable<B> => ({\n  [Symbol.iterator]() {\n    const iterator = self[Symbol.iterator]()\n    let i = 0\n    return {\n      next() {\n        const result = iterator.next()\n        if (result.done) {\n          return { done: true, value: undefined }\n        }\n        return { done: false, value: f(result.value, i++) }\n      }\n    }\n  }\n}))\n\n/**\n * Applies a function to each element in an Iterable and returns a new Iterable containing the concatenated mapped elements.\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap: {\n  <A, B>(\n    f: (a: NoInfer<A>, i: number) => Iterable<B>\n  ): (self: Iterable<A>) => Iterable<B>\n  <A, B>(self: Iterable<A>, f: (a: NoInfer<A>, i: number) => Iterable<B>): Iterable<B>\n} = dual(\n  2,\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Iterable<B>): Iterable<B> => flatten(map(self, f))\n)\n\n/**\n * Flattens an Iterable of Iterables into a single Iterable\n *\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatten = <A>(self: Iterable<Iterable<A>>): Iterable<A> => ({\n  [Symbol.iterator]() {\n    const outerIterator = self[Symbol.iterator]()\n    let innerIterator: Iterator<A> | undefined\n    function next() {\n      if (innerIterator === undefined) {\n        const next = outerIterator.next()\n        if (next.done) {\n          return next\n        }\n        innerIterator = next.value[Symbol.iterator]()\n      }\n      const result = innerIterator.next()\n      if (result.done) {\n        innerIterator = undefined\n        return next()\n      }\n      return result\n    }\n    return { next }\n  }\n})\n\n/**\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap: {\n  <A, B>(f: (a: A, i: number) => Option<B>): (self: Iterable<A>) => Iterable<B>\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>): Iterable<B>\n} = dual(\n  2,\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>): Iterable<B> => ({\n    [Symbol.iterator]() {\n      const iterator = self[Symbol.iterator]()\n      let i = 0\n      return {\n        next() {\n          let result = iterator.next()\n          while (!result.done) {\n            const b = f(result.value, i++)\n            if (O.isSome(b)) {\n              return { done: false, value: b.value }\n            }\n            result = iterator.next()\n          }\n          return { done: true, value: undefined }\n        }\n      }\n    }\n  })\n)\n\n/**\n * Transforms all elements of the `Iterable` for as long as the specified function returns some value\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMapWhile: {\n  <A, B>(f: (a: A, i: number) => Option<B>): (self: Iterable<A>) => Iterable<B>\n  <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>): Iterable<B>\n} = dual(2, <A, B>(self: Iterable<A>, f: (a: A, i: number) => Option<B>) => ({\n  [Symbol.iterator]() {\n    const iterator = self[Symbol.iterator]()\n    let i = 0\n    return {\n      next() {\n        const result = iterator.next()\n        if (result.done) {\n          return { done: true, value: undefined }\n        }\n        const b = f(result.value, i++)\n        if (O.isSome(b)) {\n          return { done: false, value: b.value }\n        }\n        return { done: true, value: undefined }\n      }\n    }\n  }\n}))\n\n/**\n * Retrieves the `Some` values from an `Iterable` of `Option`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Iterable, Option } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Array.from(Iterable.getSomes([Option.some(1), Option.none(), Option.some(2)])),\n *   [1, 2]\n * )\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getSomes: <A>(self: Iterable<Option<A>>) => Iterable<A> = filterMap(identity)\n\n/**\n * Retrieves the `Left` values from an `Iterable` of `Either`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Iterable, Either } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Array.from(Iterable.getLefts([Either.right(1), Either.left(\"err\"), Either.right(2)])),\n *   [\"err\"]\n * )\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getLefts = <R, L>(self: Iterable<Either<R, L>>): Iterable<L> => filterMap(self, E.getLeft)\n\n/**\n * Retrieves the `Right` values from an `Iterable` of `Either`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Iterable, Either } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Array.from(Iterable.getRights([Either.right(1), Either.left(\"err\"), Either.right(2)])),\n *   [1, 2]\n * )\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getRights = <R, L>(self: Iterable<Either<R, L>>): Iterable<R> => filterMap(self, E.getRight)\n\n/**\n * @category filtering\n * @since 2.0.0\n */\nexport const filter: {\n  <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Iterable<A>) => Iterable<B>\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => Iterable<A>\n  <A, B extends A>(self: Iterable<A>, refinement: (a: A, i: number) => a is B): Iterable<B>\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Iterable<A>\n} = dual(\n  2,\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): Iterable<A> => ({\n    [Symbol.iterator]() {\n      const iterator = self[Symbol.iterator]()\n      let i = 0\n      return {\n        next() {\n          let result = iterator.next()\n          while (!result.done) {\n            if (predicate(result.value, i++)) {\n              return { done: false, value: result.value }\n            }\n            result = iterator.next()\n          }\n          return { done: true, value: undefined }\n        }\n      }\n    }\n  })\n)\n\n/**\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMapNullable: {\n  <A, B>(f: (a: A) => B | null | undefined): (self: Iterable<A>) => Iterable<NonNullable<B>>\n  <A, B>(self: Iterable<A>, f: (a: A) => B | null | undefined): Iterable<NonNullable<B>>\n} = dual(\n  2,\n  <A, B>(self: Iterable<A>, f: (a: A) => B | null | undefined): Iterable<NonNullable<B>> =>\n    filterMap(self, (a) => {\n      const b = f(a)\n      return b == null ? O.none() : O.some(b)\n    })\n)\n\n/**\n * Check if a predicate holds true for some `Iterable` element.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const some: {\n  <A>(predicate: (a: A, i: number) => boolean): (self: Iterable<A>) => boolean\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): boolean\n} = dual(\n  2,\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): boolean => {\n    let i = 0\n    for (const a of self) {\n      if (predicate(a, i++)) {\n        return true\n      }\n    }\n    return false\n  }\n)\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport const unfold = <B, A>(b: B, f: (b: B) => Option<readonly [A, B]>): Iterable<A> => ({\n  [Symbol.iterator]() {\n    let next = b\n    return {\n      next() {\n        const o = f(next)\n        if (O.isNone(o)) {\n          return { done: true, value: undefined }\n        }\n        const [a, b] = o.value\n        next = b\n        return { done: false, value: a }\n      }\n    }\n  }\n})\n\n/**\n * Iterate over the `Iterable` applying `f`.\n *\n * @since 2.0.0\n */\nexport const forEach: {\n  <A>(f: (a: A, i: number) => void): (self: Iterable<A>) => void\n  <A>(self: Iterable<A>, f: (a: A, i: number) => void): void\n} = dual(2, <A>(self: Iterable<A>, f: (a: A, i: number) => void): void => {\n  let i = 0\n  for (const a of self) {\n    f(a, i++)\n  }\n})\n\n/**\n * @category folding\n * @since 2.0.0\n */\nexport const reduce: {\n  <B, A>(b: B, f: (b: B, a: A, i: number) => B): (self: Iterable<A>) => B\n  <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A, i: number) => B): B\n} = dual(3, <A, B>(self: Iterable<A>, b: B, f: (b: B, a: A, i: number) => B): B => {\n  if (Array.isArray(self)) {\n    return self.reduce(f, b)\n  }\n  let i = 0\n  let result = b\n  for (const n of self) {\n    result = f(result, n, i++)\n  }\n  return result\n})\n\n/**\n * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function.\n *\n * @since 2.0.0\n */\nexport const dedupeAdjacentWith: {\n  <A>(isEquivalent: (self: A, that: A) => boolean): (self: Iterable<A>) => Iterable<A>\n  <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): Iterable<A>\n} = dual(2, <A>(self: Iterable<A>, isEquivalent: (self: A, that: A) => boolean): Iterable<A> => ({\n  [Symbol.iterator]() {\n    const iterator = self[Symbol.iterator]()\n    let first = true\n    let last: A\n    function next(): IteratorResult<A> {\n      const result = iterator.next()\n      if (result.done) {\n        return { done: true, value: undefined }\n      }\n      if (first) {\n        first = false\n        last = result.value\n        return result\n      }\n      const current = result.value\n      if (isEquivalent(last, current)) {\n        return next()\n      }\n      last = current\n      return result\n    }\n    return { next }\n  }\n}))\n\n/**\n * Deduplicates adjacent elements that are identical.\n *\n * @since 2.0.0\n */\nexport const dedupeAdjacent: <A>(self: Iterable<A>) => Iterable<A> = dedupeAdjacentWith(Equal.equivalence())\n\n/**\n * Zips this Iterable crosswise with the specified Iterable using the specified combiner.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const cartesianWith: {\n  <A, B, C>(that: Iterable<B>, f: (a: A, b: B) => C): (self: Iterable<A>) => Iterable<C>\n  <A, B, C>(self: Iterable<A>, that: Iterable<B>, f: (a: A, b: B) => C): Iterable<C>\n} = dual(\n  3,\n  <A, B, C>(self: Iterable<A>, that: Iterable<B>, f: (a: A, b: B) => C): Iterable<C> =>\n    flatMap(self, (a) => map(that, (b) => f(a, b)))\n)\n\n/**\n * Zips this Iterable crosswise with the specified Iterable.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const cartesian: {\n  <B>(that: Iterable<B>): <A>(self: Iterable<A>) => Iterable<[A, B]>\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Iterable<[A, B]>\n} = dual(\n  2,\n  <A, B>(self: Iterable<A>, that: Iterable<B>): Iterable<[A, B]> => cartesianWith(self, that, (a, b) => [a, b])\n)\n\n/**\n * Counts all the element of the given iterable that pass the given predicate\n *\n * **Example**\n *\n * ```ts\n * import { Iterable } from \"effect\"\n *\n * const result = Iterable.countBy([1, 2, 3, 4, 5], n => n % 2 === 0)\n * console.log(result) // 2\n * ```\n *\n * @category folding\n * @since 3.16.0\n */\nexport const countBy: {\n  <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Iterable<A>) => number\n  <A>(self: Iterable<A>, predicate: (a: A, i: number) => boolean): number\n} = dual(\n  2,\n  <A>(\n    self: Iterable<A>,\n    f: (a: A, i: number) => boolean\n  ): number => {\n    let count = 0\n    let i = 0\n    for (const a of self) {\n      if (f(a, i)) {\n        count++\n      }\n      i++\n    }\n    return count\n  }\n)\n"
  },
  {
    "path": "packages/effect/src/JSONSchema.ts",
    "content": "/**\n * @since 3.10.0\n */\n\nimport * as Arr from \"./Array.js\"\nimport * as errors_ from \"./internal/schema/errors.js\"\nimport * as schemaId_ from \"./internal/schema/schemaId.js\"\nimport * as Option from \"./Option.js\"\nimport * as ParseResult from \"./ParseResult.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport * as Record from \"./Record.js\"\nimport type * as Schema from \"./Schema.js\"\nimport * as AST from \"./SchemaAST.js\"\n\ntype JsonValue = string | number | boolean | null | Array<JsonValue> | { [key: string]: JsonValue }\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchemaAnnotations {\n  title?: string\n  description?: string\n  default?: JsonValue\n  examples?: Array<JsonValue>\n}\n\n/**\n * @category model\n * @since 3.11.5\n */\nexport interface JsonSchema7Never extends JsonSchemaAnnotations {\n  $id: \"/schemas/never\"\n  not: {}\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Any extends JsonSchemaAnnotations {\n  $id: \"/schemas/any\"\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Unknown extends JsonSchemaAnnotations {\n  $id: \"/schemas/unknown\"\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Void extends JsonSchemaAnnotations {\n  $id: \"/schemas/void\"\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7object extends JsonSchemaAnnotations {\n  $id: \"/schemas/object\"\n  anyOf: [\n    { type: \"object\" },\n    { type: \"array\" }\n  ]\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7empty extends JsonSchemaAnnotations {\n  $id: \"/schemas/%7B%7D\"\n  anyOf: [\n    { type: \"object\" },\n    { type: \"array\" }\n  ]\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Ref extends JsonSchemaAnnotations {\n  $ref: string\n}\n\n/**\n * @category model\n * @since 3.11.7\n */\nexport interface JsonSchema7Null extends JsonSchemaAnnotations {\n  type: \"null\"\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7String extends JsonSchemaAnnotations {\n  type: \"string\"\n  minLength?: number\n  maxLength?: number\n  pattern?: string\n  format?: string\n  contentMediaType?: string\n  allOf?: Array<{\n    minLength?: number\n    maxLength?: number\n    pattern?: string\n  }>\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Numeric extends JsonSchemaAnnotations {\n  minimum?: number\n  exclusiveMinimum?: number\n  maximum?: number\n  exclusiveMaximum?: number\n  multipleOf?: number\n  allOf?: Array<{\n    minimum?: number\n    exclusiveMinimum?: number\n    maximum?: number\n    exclusiveMaximum?: number\n    multipleOf?: number\n  }>\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Number extends JsonSchema7Numeric {\n  type: \"number\"\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Integer extends JsonSchema7Numeric {\n  type: \"integer\"\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Boolean extends JsonSchemaAnnotations {\n  type: \"boolean\"\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Array extends JsonSchemaAnnotations {\n  type: \"array\"\n  items?: JsonSchema7 | Array<JsonSchema7> | false\n  prefixItems?: Array<JsonSchema7>\n  minItems?: number\n  maxItems?: number\n  additionalItems?: JsonSchema7 | boolean\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Enum extends JsonSchemaAnnotations {\n  type?: \"string\" | \"number\" | \"boolean\"\n  enum: Array<string | number | boolean>\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Enums extends JsonSchemaAnnotations {\n  $comment: \"/schemas/enums\"\n  anyOf: Array<{\n    type: \"string\" | \"number\"\n    title: string\n    enum: [string | number]\n  }>\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7AnyOf extends JsonSchemaAnnotations {\n  anyOf: Array<JsonSchema7>\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface JsonSchema7Object extends JsonSchemaAnnotations {\n  type: \"object\"\n  required: Array<string>\n  properties: Record<string, JsonSchema7>\n  additionalProperties?: boolean | JsonSchema7\n  patternProperties?: Record<string, JsonSchema7>\n  propertyNames?: JsonSchema7\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport type JsonSchema7 =\n  | JsonSchema7Never\n  | JsonSchema7Any\n  | JsonSchema7Unknown\n  | JsonSchema7Void\n  | JsonSchema7object\n  | JsonSchema7empty\n  | JsonSchema7Ref\n  | JsonSchema7Null\n  | JsonSchema7String\n  | JsonSchema7Number\n  | JsonSchema7Integer\n  | JsonSchema7Boolean\n  | JsonSchema7Array\n  | JsonSchema7Enum\n  | JsonSchema7Enums\n  | JsonSchema7AnyOf\n  | JsonSchema7Object\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport type JsonSchema7Root = JsonSchema7 & {\n  $schema?: string\n  $defs?: Record<string, JsonSchema7>\n}\n\n/**\n * Generates a JSON Schema from a schema.\n *\n * **Options**\n *\n * - `target`: The target JSON Schema version. Possible values are:\n *   - `\"jsonSchema7\"`: JSON Schema draft-07 (default behavior).\n *   - `\"jsonSchema2019-09\"`: JSON Schema draft-2019-09.\n *   - `\"jsonSchema2020-12\"`: JSON Schema draft-2020-12.\n *   - `\"openApi3.1\"`: OpenAPI 3.1.\n *\n * @category encoding\n * @since 3.10.0\n */\nexport const make = <A, I, R>(schema: Schema.Schema<A, I, R>, options?: {\n  readonly target?: Target | undefined\n}): JsonSchema7Root => {\n  const definitions: Record<string, any> = {}\n  const target = options?.target ?? \"jsonSchema7\"\n  const ast = AST.isTransformation(schema.ast) && isParseJsonTransformation(schema.ast.from)\n    // Special case top level `parseJson` transformations\n    ? schema.ast.to\n    : schema.ast\n  const jsonSchema = fromAST(ast, {\n    definitions,\n    target\n  })\n  const out: JsonSchema7Root = {\n    $schema: getMetaSchemaUri(target),\n    $defs: {},\n    ...jsonSchema\n  }\n  if (Record.isEmptyRecord(definitions)) {\n    delete out.$defs\n  } else {\n    out.$defs = definitions\n  }\n  return out\n}\n\ntype Target = \"jsonSchema7\" | \"jsonSchema2019-09\" | \"openApi3.1\" | \"jsonSchema2020-12\"\n\ntype TopLevelReferenceStrategy = \"skip\" | \"keep\"\n\ntype AdditionalPropertiesStrategy = \"allow\" | \"strict\"\n\n/** @internal */\nexport function getMetaSchemaUri(target: Target) {\n  switch (target) {\n    case \"jsonSchema7\":\n      return \"http://json-schema.org/draft-07/schema#\"\n    case \"jsonSchema2019-09\":\n      return \"https://json-schema.org/draft/2019-09/schema\"\n    case \"jsonSchema2020-12\":\n    case \"openApi3.1\":\n      return \"https://json-schema.org/draft/2020-12/schema\"\n  }\n}\n\n/**\n * Returns a JSON Schema with additional options and definitions.\n *\n * **Warning**\n *\n * This function is experimental and subject to change.\n *\n * **Options**\n *\n * - `definitions`: A record of definitions that are included in the schema.\n * - `definitionPath`: The path to the definitions within the schema (defaults\n *   to \"#/$defs/\").\n * - `target`: Which spec to target. Possible values are:\n *   - `'jsonSchema7'`: JSON Schema draft-07 (default behavior).\n *   - `'jsonSchema2019-09'`: JSON Schema draft-2019-09.\n *   - `'openApi3.1'`: OpenAPI 3.1.\n * - `topLevelReferenceStrategy`: Controls the handling of the top-level\n *   reference. Possible values are:\n *   - `\"keep\"`: Keep the top-level reference (default behavior).\n *   - `\"skip\"`: Skip the top-level reference.\n * - `additionalPropertiesStrategy`: Controls the handling of additional properties. Possible values are:\n *   - `\"strict\"`: Disallow additional properties (default behavior).\n *   - `\"allow\"`: Allow additional properties.\n *\n * @category encoding\n * @since 3.11.5\n * @experimental\n */\nexport const fromAST = (ast: AST.AST, options: {\n  readonly definitions: Record<string, JsonSchema7>\n  readonly definitionPath?: string | undefined\n  readonly target?: Target | undefined\n  readonly topLevelReferenceStrategy?: TopLevelReferenceStrategy | undefined\n  readonly additionalPropertiesStrategy?: AdditionalPropertiesStrategy | undefined\n}): JsonSchema7 => {\n  const definitionPath = options.definitionPath ?? \"#/$defs/\"\n  const getRef = (id: string) => definitionPath + id\n  const target = options.target ?? \"jsonSchema7\"\n  const topLevelReferenceStrategy = options.topLevelReferenceStrategy ?? \"keep\"\n  const additionalPropertiesStrategy = options.additionalPropertiesStrategy ?? \"strict\"\n  return go(\n    ast,\n    options.definitions,\n    \"handle-identifier\",\n    [],\n    {\n      getRef,\n      target,\n      topLevelReferenceStrategy,\n      additionalPropertiesStrategy\n    },\n    \"handle-annotation\",\n    \"handle-errors\"\n  )\n}\n\nconst constNever: JsonSchema7Never = {\n  $id: \"/schemas/never\",\n  not: {}\n}\n\nconst constAny: JsonSchema7Any = {\n  $id: \"/schemas/any\"\n}\n\nconst constUnknown: JsonSchema7Unknown = {\n  $id: \"/schemas/unknown\"\n}\n\nconst constVoid: JsonSchema7Void = {\n  $id: \"/schemas/void\"\n}\n\nconst constObject: JsonSchema7object = {\n  $id: \"/schemas/object\",\n  \"anyOf\": [\n    { \"type\": \"object\" },\n    { \"type\": \"array\" }\n  ]\n}\n\nconst constEmptyStruct: JsonSchema7empty = {\n  $id: \"/schemas/%7B%7D\",\n  \"anyOf\": [\n    { \"type\": \"object\" },\n    { \"type\": \"array\" }\n  ]\n}\n\nfunction getRawDescription(annotated: AST.Annotated | undefined): string | undefined {\n  if (annotated !== undefined) return Option.getOrUndefined(AST.getDescriptionAnnotation(annotated))\n}\n\nfunction getRawTitle(annotated: AST.Annotated | undefined): string | undefined {\n  if (annotated !== undefined) return Option.getOrUndefined(AST.getTitleAnnotation(annotated))\n}\n\nfunction getRawDefault(annotated: AST.Annotated | undefined): Option.Option<unknown> {\n  if (annotated !== undefined) return AST.getDefaultAnnotation(annotated)\n  return Option.none()\n}\n\nfunction encodeDefault(ast: AST.AST, def: unknown): Option.Option<unknown> {\n  const getOption = ParseResult.getOption(ast, false)\n  return getOption(def)\n}\n\nfunction getRawExamples(annotated: AST.Annotated | undefined): ReadonlyArray<unknown> | undefined {\n  if (annotated !== undefined) return Option.getOrUndefined(AST.getExamplesAnnotation(annotated))\n}\n\nfunction encodeExamples(ast: AST.AST, examples: ReadonlyArray<unknown>): Array<JsonValue> | undefined {\n  const getOption = ParseResult.getOption(ast, false)\n  const out = Arr.filterMap(examples, (e) => getOption(e).pipe(Option.filter(isJsonValue)))\n  return out.length > 0 ? out : undefined\n}\n\nfunction filterBuiltIn(ast: AST.AST, annotation: string | undefined, key: symbol): string | undefined {\n  if (annotation !== undefined) {\n    switch (ast._tag) {\n      case \"StringKeyword\":\n        return annotation !== AST.stringKeyword.annotations[key] ? annotation : undefined\n      case \"NumberKeyword\":\n        return annotation !== AST.numberKeyword.annotations[key] ? annotation : undefined\n      case \"BooleanKeyword\":\n        return annotation !== AST.booleanKeyword.annotations[key] ? annotation : undefined\n    }\n  }\n  return annotation\n}\n\nfunction isJsonValue(value: unknown, visited: Set<unknown> = new Set()): value is JsonValue {\n  if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n    return true\n  }\n  if (Array.isArray(value) || typeof value === \"object\") {\n    // Check for cyclic references\n    if (visited.has(value)) {\n      return false\n    }\n    visited.add(value)\n    try {\n      if (Array.isArray(value)) {\n        return value.every((item) => isJsonValue(item, visited))\n      }\n      // Exclude non-plain objects (Date, RegExp, etc.) by checking constructor\n      const proto = Object.getPrototypeOf(value)\n      if (proto !== null && proto !== Object.prototype) {\n        return false\n      }\n      // JSON only allows string keys, so exclude objects with Symbol keys\n      if (Object.getOwnPropertySymbols(value).length > 0) {\n        return false\n      }\n      // Check all values are JSON values\n      return Object.values(value).every((v) => isJsonValue(v, visited))\n    } finally {\n      visited.delete(value)\n    }\n  }\n  return false\n}\n\nfunction pruneJsonSchemaAnnotations(\n  ast: AST.AST,\n  description: string | undefined,\n  title: string | undefined,\n  def: Option.Option<unknown>,\n  examples: ReadonlyArray<unknown> | undefined\n): JsonSchemaAnnotations | undefined {\n  const out: JsonSchemaAnnotations = {}\n  if (description !== undefined) out.description = description\n  if (title !== undefined) out.title = title\n  if (Option.isSome(def)) {\n    const o = encodeDefault(ast, def.value)\n    if (Option.isSome(o) && isJsonValue(o.value)) {\n      out.default = o.value\n    }\n  }\n  if (examples !== undefined) {\n    const encodedExamples = encodeExamples(ast, examples)\n    if (encodedExamples !== undefined) {\n      out.examples = encodedExamples\n    }\n  }\n  if (Object.keys(out).length === 0) {\n    return undefined\n  }\n  return out\n}\n\nfunction getContextJsonSchemaAnnotations(ast: AST.AST, annotated: AST.Annotated): JsonSchemaAnnotations | undefined {\n  return pruneJsonSchemaAnnotations(\n    ast,\n    getRawDescription(annotated),\n    getRawTitle(annotated),\n    getRawDefault(annotated),\n    getRawExamples(annotated)\n  )\n}\n\nfunction getJsonSchemaAnnotations(ast: AST.AST): JsonSchemaAnnotations | undefined {\n  return pruneJsonSchemaAnnotations(\n    ast,\n    filterBuiltIn(ast, getRawDescription(ast), AST.DescriptionAnnotationId),\n    filterBuiltIn(ast, getRawTitle(ast), AST.TitleAnnotationId),\n    getRawDefault(ast),\n    getRawExamples(ast)\n  )\n}\n\nfunction mergeJsonSchemaAnnotations(\n  jsonSchema: JsonSchema7,\n  jsonSchemaAnnotations: JsonSchemaAnnotations | undefined\n): JsonSchema7 {\n  if (jsonSchemaAnnotations) {\n    if (\"$ref\" in jsonSchema) {\n      return { allOf: [jsonSchema], ...jsonSchemaAnnotations } as any\n    }\n    return { ...jsonSchema, ...jsonSchemaAnnotations }\n  }\n  return jsonSchema\n}\n\nconst pruneUndefined = (ast: AST.AST): AST.AST | undefined => {\n  if (Option.isNone(AST.getJSONSchemaAnnotation(ast))) {\n    return AST.pruneUndefined(ast, pruneUndefined, (ast) => pruneUndefined(ast.from))\n  }\n}\n\nconst isParseJsonTransformation = (ast: AST.AST): boolean =>\n  ast.annotations[AST.SchemaIdAnnotationId] === AST.ParseJsonSchemaId\n\nconst isOverrideAnnotation = (ast: AST.AST, jsonSchema: JsonSchema7): boolean => {\n  if (AST.isRefinement(ast)) {\n    const schemaId = ast.annotations[AST.SchemaIdAnnotationId]\n    if (schemaId === schemaId_.IntSchemaId) {\n      return \"type\" in jsonSchema && jsonSchema.type !== \"integer\"\n    }\n  }\n  return (\"type\" in jsonSchema) || (\"oneOf\" in jsonSchema) || (\"anyOf\" in jsonSchema) || (\"$ref\" in jsonSchema)\n}\n\nconst mergeRefinements = (from: any, jsonSchema: any, ast: AST.AST): any => {\n  const out: any = { ...from, ...getJsonSchemaAnnotations(ast), ...jsonSchema }\n  out.allOf ??= []\n\n  const handle = (name: string, filter: (i: any) => boolean) => {\n    if (name in jsonSchema && name in from) {\n      out.allOf.unshift({ [name]: from[name] })\n      out.allOf = out.allOf.filter(filter)\n    }\n  }\n\n  handle(\"minLength\", (i) => i.minLength > jsonSchema.minLength)\n  handle(\"maxLength\", (i) => i.maxLength < jsonSchema.maxLength)\n  handle(\"pattern\", (i) => i.pattern !== jsonSchema.pattern)\n  handle(\"minItems\", (i) => i.minItems > jsonSchema.minItems)\n  handle(\"maxItems\", (i) => i.maxItems < jsonSchema.maxItems)\n  handle(\"minimum\", (i) => i.minimum > jsonSchema.minimum)\n  handle(\"maximum\", (i) => i.maximum < jsonSchema.maximum)\n  handle(\"exclusiveMinimum\", (i) => i.exclusiveMinimum > jsonSchema.exclusiveMinimum)\n  handle(\"exclusiveMaximum\", (i) => i.exclusiveMaximum < jsonSchema.exclusiveMaximum)\n  handle(\"multipleOf\", (i) => i.multipleOf !== jsonSchema.multipleOf)\n\n  if (out.allOf.length === 0) {\n    delete out.allOf\n  }\n  return out\n}\n\ntype GoOptions = {\n  readonly getRef: (id: string) => string\n  readonly target: Target\n  readonly topLevelReferenceStrategy: TopLevelReferenceStrategy\n  readonly additionalPropertiesStrategy: AdditionalPropertiesStrategy\n}\n\nfunction isContentSchemaSupported(options: GoOptions): boolean {\n  switch (options.target) {\n    case \"jsonSchema7\":\n      return false\n    case \"jsonSchema2019-09\":\n    case \"jsonSchema2020-12\":\n    case \"openApi3.1\":\n      return true\n  }\n}\n\nfunction getAdditionalProperties(options: GoOptions): boolean {\n  switch (options.additionalPropertiesStrategy) {\n    case \"allow\":\n      return true\n    case \"strict\":\n      return false\n  }\n}\n\nfunction addASTAnnotations(jsonSchema: JsonSchema7, ast: AST.AST): JsonSchema7 {\n  return addAnnotations(jsonSchema, getJsonSchemaAnnotations(ast))\n}\n\nfunction addAnnotations(jsonSchema: JsonSchema7, annotations: JsonSchemaAnnotations | undefined): JsonSchema7 {\n  if (annotations === undefined || Object.keys(annotations).length === 0) {\n    return jsonSchema\n  }\n  if (\"$ref\" in jsonSchema) {\n    return { allOf: [jsonSchema], ...annotations } as any\n  }\n  return { ...jsonSchema, ...annotations }\n}\n\nfunction getIdentifierAnnotation(ast: AST.AST): string | undefined {\n  const identifier = Option.getOrUndefined(AST.getJSONIdentifier(ast))\n  if (identifier === undefined) {\n    if (AST.isSuspend(ast)) {\n      return getIdentifierAnnotation(ast.f())\n    }\n    if (AST.isTransformation(ast) && AST.isTypeLiteral(ast.from) && AST.isDeclaration(ast.to)) {\n      const to = ast.to\n      const surrogate = AST.getSurrogateAnnotation(to)\n      if (Option.isSome(surrogate)) {\n        return getIdentifierAnnotation(to)\n      }\n    }\n  }\n  return identifier\n}\n\nfunction go(\n  ast: AST.AST,\n  $defs: Record<string, JsonSchema7>,\n  identifier: \"handle-identifier\" | \"ignore-identifier\",\n  path: ReadonlyArray<PropertyKey>,\n  options: GoOptions,\n  annotation: \"handle-annotation\" | \"ignore-annotation\",\n  errors: \"handle-errors\" | \"ignore-errors\"\n): JsonSchema7 {\n  if (\n    identifier === \"handle-identifier\" &&\n    (options.topLevelReferenceStrategy !== \"skip\" || AST.isSuspend(ast))\n  ) {\n    const id = getIdentifierAnnotation(ast)\n    if (id !== undefined) {\n      const escapedId = id.replace(/~/ig, \"~0\").replace(/\\//ig, \"~1\")\n      const out = { $ref: options.getRef(escapedId) }\n      if (!Record.has($defs, id)) {\n        $defs[id] = out\n        $defs[id] = go(ast, $defs, \"ignore-identifier\", path, options, \"handle-annotation\", errors)\n      }\n      return out\n    }\n  }\n  if (annotation === \"handle-annotation\") {\n    const hook = AST.getJSONSchemaAnnotation(ast)\n    if (Option.isSome(hook)) {\n      const handler = hook.value as JsonSchema7\n      if (isOverrideAnnotation(ast, handler)) {\n        switch (ast._tag) {\n          case \"Declaration\":\n            return addASTAnnotations(handler, ast)\n          default:\n            return handler\n        }\n      } else {\n        switch (ast._tag) {\n          case \"Refinement\": {\n            const t = AST.getTransformationFrom(ast)\n            if (t === undefined) {\n              return mergeRefinements(\n                go(ast.from, $defs, identifier, path, options, \"handle-annotation\", errors),\n                handler,\n                ast\n              )\n            } else {\n              return go(t, $defs, identifier, path, options, \"handle-annotation\", errors)\n            }\n          }\n          default:\n            return {\n              ...go(ast, $defs, identifier, path, options, \"ignore-annotation\", errors),\n              ...handler\n            } as any\n        }\n      }\n    }\n  }\n  const surrogate = AST.getSurrogateAnnotation(ast)\n  if (Option.isSome(surrogate)) {\n    return go(surrogate.value, $defs, identifier, path, options, \"handle-annotation\", errors)\n  }\n  switch (ast._tag) {\n    // Unsupported\n    case \"Declaration\":\n    case \"UndefinedKeyword\":\n    case \"BigIntKeyword\":\n    case \"UniqueSymbol\":\n    case \"SymbolKeyword\": {\n      if (errors === \"ignore-errors\") return addASTAnnotations(constAny, ast)\n      throw new Error(errors_.getJSONSchemaMissingAnnotationErrorMessage(path, ast))\n    }\n    case \"Suspend\": {\n      if (identifier === \"handle-identifier\") {\n        if (errors === \"ignore-errors\") return addASTAnnotations(constAny, ast)\n        throw new Error(errors_.getJSONSchemaMissingIdentifierAnnotationErrorMessage(path, ast))\n      }\n      return go(ast.f(), $defs, \"ignore-identifier\", path, options, \"handle-annotation\", errors)\n    }\n    // Primitives\n    case \"NeverKeyword\":\n      return addASTAnnotations(constNever, ast)\n    case \"VoidKeyword\":\n      return addASTAnnotations(constVoid, ast)\n    case \"UnknownKeyword\":\n      return addASTAnnotations(constUnknown, ast)\n    case \"AnyKeyword\":\n      return addASTAnnotations(constAny, ast)\n    case \"ObjectKeyword\":\n      return addASTAnnotations(constObject, ast)\n    case \"StringKeyword\":\n      return addASTAnnotations({ type: \"string\" }, ast)\n    case \"NumberKeyword\":\n      return addASTAnnotations({ type: \"number\" }, ast)\n    case \"BooleanKeyword\":\n      return addASTAnnotations({ type: \"boolean\" }, ast)\n    case \"Literal\": {\n      const literal = ast.literal\n      if (literal === null) {\n        return addASTAnnotations({ type: \"null\" }, ast)\n      } else if (Predicate.isString(literal)) {\n        return addASTAnnotations({ type: \"string\", enum: [literal] }, ast)\n      } else if (Predicate.isNumber(literal)) {\n        return addASTAnnotations({ type: \"number\", enum: [literal] }, ast)\n      } else if (Predicate.isBoolean(literal)) {\n        return addASTAnnotations({ type: \"boolean\", enum: [literal] }, ast)\n      }\n      if (errors === \"ignore-errors\") return addASTAnnotations(constAny, ast)\n      throw new Error(errors_.getJSONSchemaMissingAnnotationErrorMessage(path, ast))\n    }\n    case \"Enums\": {\n      const anyOf = ast.enums.map((e) => {\n        const type: \"string\" | \"number\" = Predicate.isNumber(e[1]) ? \"number\" : \"string\"\n        return { type, title: e[0], enum: [e[1]] }\n      })\n      return anyOf.length >= 1 ?\n        addASTAnnotations({\n          $comment: \"/schemas/enums\",\n          anyOf\n        }, ast) :\n        addASTAnnotations(constNever, ast)\n    }\n    case \"TupleType\": {\n      const elements = ast.elements.map((e, i) =>\n        mergeJsonSchemaAnnotations(\n          go(e.type, $defs, \"handle-identifier\", path.concat(i), options, \"handle-annotation\", errors),\n          getContextJsonSchemaAnnotations(e.type, e)\n        )\n      )\n      const rest = ast.rest.map((type) =>\n        mergeJsonSchemaAnnotations(\n          go(type.type, $defs, \"handle-identifier\", path, options, \"handle-annotation\", errors),\n          getContextJsonSchemaAnnotations(type.type, type)\n        )\n      )\n      const output: JsonSchema7Array = { type: \"array\" }\n      // ---------------------------------------------\n      // handle elements\n      // ---------------------------------------------\n      const len = ast.elements.length\n      if (len > 0) {\n        output.minItems = len - ast.elements.filter((element) => element.isOptional).length\n        if (options.target === \"jsonSchema7\") {\n          output.items = elements\n        } else {\n          output.prefixItems = elements\n        }\n      }\n      // ---------------------------------------------\n      // handle rest element\n      // ---------------------------------------------\n      const restLength = rest.length\n      if (restLength > 0) {\n        const head = rest[0]\n        const isHomogeneous = restLength === 1 && ast.elements.every((e) => e.type === ast.rest[0].type)\n        if (isHomogeneous) {\n          if (options.target === \"jsonSchema7\") {\n            output.items = head\n          } else {\n            output.items = head\n            delete output.prefixItems\n          }\n        } else {\n          if (options.target === \"jsonSchema7\") {\n            output.additionalItems = head\n          } else {\n            output.items = head\n          }\n        }\n\n        // ---------------------------------------------\n        // handle post rest elements\n        // ---------------------------------------------\n        if (restLength > 1) {\n          if (errors === \"ignore-errors\") return addASTAnnotations(constAny, ast)\n          throw new Error(errors_.getJSONSchemaUnsupportedPostRestElementsErrorMessage(path))\n        }\n      } else {\n        if (len > 0) {\n          if (options.target === \"jsonSchema7\") {\n            output.additionalItems = false\n          } else {\n            output.items = false\n          }\n        } else {\n          output.maxItems = 0\n        }\n      }\n\n      return addASTAnnotations(output, ast)\n    }\n    case \"TypeLiteral\": {\n      if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) {\n        return addASTAnnotations(constEmptyStruct, ast)\n      }\n      const output: JsonSchema7Object = {\n        type: \"object\",\n        required: [],\n        properties: {},\n        additionalProperties: getAdditionalProperties(options)\n      }\n      let patternProperties: JsonSchema7 | undefined = undefined\n      let propertyNames: JsonSchema7 | undefined = undefined\n      for (const is of ast.indexSignatures) {\n        const pruned = pruneUndefined(is.type) ?? is.type\n        const parameter = is.parameter\n        switch (parameter._tag) {\n          case \"StringKeyword\": {\n            output.additionalProperties = go(\n              pruned,\n              $defs,\n              \"handle-identifier\",\n              path,\n              options,\n              \"handle-annotation\",\n              errors\n            )\n            break\n          }\n          case \"TemplateLiteral\": {\n            patternProperties = go(pruned, $defs, \"handle-identifier\", path, options, \"handle-annotation\", errors)\n            propertyNames = {\n              type: \"string\",\n              pattern: AST.getTemplateLiteralRegExp(parameter).source\n            }\n            break\n          }\n          case \"Refinement\": {\n            patternProperties = go(pruned, $defs, \"handle-identifier\", path, options, \"handle-annotation\", errors)\n            propertyNames = go(parameter, $defs, \"handle-identifier\", path, options, \"handle-annotation\", errors)\n            break\n          }\n          case \"SymbolKeyword\": {\n            const indexSignaturePath = path.concat(\"[symbol]\")\n            output.additionalProperties = go(\n              pruned,\n              $defs,\n              \"handle-identifier\",\n              indexSignaturePath,\n              options,\n              \"handle-annotation\",\n              errors\n            )\n            propertyNames = go(\n              parameter,\n              $defs,\n              \"handle-identifier\",\n              indexSignaturePath,\n              options,\n              \"handle-annotation\",\n              errors\n            )\n            break\n          }\n        }\n      }\n      // ---------------------------------------------\n      // handle property signatures\n      // ---------------------------------------------\n      for (let i = 0; i < ast.propertySignatures.length; i++) {\n        const ps = ast.propertySignatures[i]\n        const name = ps.name\n        if (Predicate.isString(name)) {\n          const pruned = pruneUndefined(ps.type)\n          const type = pruned ?? ps.type\n          output.properties[name] = mergeJsonSchemaAnnotations(\n            go(type, $defs, \"handle-identifier\", path.concat(ps.name), options, \"handle-annotation\", errors),\n            getContextJsonSchemaAnnotations(type, ps)\n          )\n          // ---------------------------------------------\n          // handle optional property signatures\n          // ---------------------------------------------\n          if (!ps.isOptional && pruned === undefined) {\n            output.required.push(name)\n          }\n        } else {\n          if (errors === \"ignore-errors\") return addASTAnnotations(constAny, ast)\n          throw new Error(errors_.getJSONSchemaUnsupportedKeyErrorMessage(name, path))\n        }\n      }\n      // ---------------------------------------------\n      // handle index signatures\n      // ---------------------------------------------\n      if (patternProperties !== undefined) {\n        delete output.additionalProperties\n        output.patternProperties = { \"\": patternProperties }\n      }\n      if (propertyNames !== undefined) {\n        output.propertyNames = propertyNames\n      }\n\n      return addASTAnnotations(output, ast)\n    }\n    case \"Union\": {\n      const members: Array<JsonSchema7> = ast.types.map((t) =>\n        go(t, $defs, \"handle-identifier\", path, options, \"handle-annotation\", errors)\n      )\n      const anyOf = compactUnion(members)\n      switch (anyOf.length) {\n        case 0:\n          return constNever\n        case 1:\n          return addASTAnnotations(anyOf[0], ast)\n        default:\n          return addASTAnnotations({ anyOf }, ast)\n      }\n    }\n    case \"Refinement\":\n      return go(ast.from, $defs, identifier, path, options, \"handle-annotation\", errors)\n    case \"TemplateLiteral\": {\n      const regex = AST.getTemplateLiteralRegExp(ast)\n      return addASTAnnotations({\n        type: \"string\",\n        title: String(ast),\n        description: \"a template literal\",\n        pattern: regex.source\n      }, ast)\n    }\n    case \"Transformation\": {\n      if (isParseJsonTransformation(ast.from)) {\n        const out: JsonSchema7String & { contentSchema?: JsonSchema7 } = {\n          \"type\": \"string\",\n          \"contentMediaType\": \"application/json\"\n        }\n        if (isContentSchemaSupported(options)) {\n          out[\"contentSchema\"] = go(ast.to, $defs, identifier, path, options, \"handle-annotation\", errors)\n        }\n        return out\n      }\n      const from = go(ast.from, $defs, identifier, path, options, \"handle-annotation\", errors)\n      if (\n        ast.transformation._tag === \"TypeLiteralTransformation\" &&\n        isJsonSchema7Object(from)\n      ) {\n        const to = go(ast.to, {}, \"ignore-identifier\", path, options, \"handle-annotation\", \"ignore-errors\")\n        if (isJsonSchema7Object(to)) {\n          for (const t of ast.transformation.propertySignatureTransformations) {\n            const toKey = t.to\n            const fromKey = t.from\n            if (Predicate.isString(toKey) && Predicate.isString(fromKey)) {\n              const toProperty = to.properties[toKey]\n              if (Predicate.isRecord(toProperty)) {\n                const fromProperty = from.properties[fromKey]\n                if (Predicate.isRecord(fromProperty)) {\n                  const annotations: JsonSchemaAnnotations = {}\n                  if (Predicate.isString(toProperty.title)) annotations.title = toProperty.title\n                  if (Predicate.isString(toProperty.description)) annotations.description = toProperty.description\n                  if (Array.isArray(toProperty.examples)) annotations.examples = toProperty.examples\n                  if (Object.hasOwn(toProperty, \"default\") && toProperty.default !== undefined) {\n                    annotations.default = toProperty.default\n                  }\n                  from.properties[fromKey] = addAnnotations(fromProperty, annotations)\n                }\n              }\n            }\n          }\n        }\n      }\n      return addASTAnnotations(from, ast)\n    }\n  }\n}\n\nfunction isJsonSchema7Object(jsonSchema: unknown): jsonSchema is JsonSchema7Object {\n  return Predicate.isRecord(jsonSchema) && jsonSchema.type === \"object\" && Predicate.isRecord(jsonSchema.properties)\n}\n\nfunction isNeverWithoutCustomAnnotations(jsonSchema: JsonSchema7): boolean {\n  return jsonSchema === constNever || (Predicate.hasProperty(jsonSchema, \"$id\") && jsonSchema.$id === constNever.$id &&\n    Object.keys(jsonSchema).length === 3 && jsonSchema.title === AST.neverKeyword.annotations[AST.TitleAnnotationId])\n}\n\nfunction isAny(jsonSchema: JsonSchema7): jsonSchema is JsonSchema7Any {\n  return \"$id\" in jsonSchema && jsonSchema.$id === constAny.$id\n}\n\nfunction isUnknown(jsonSchema: JsonSchema7): jsonSchema is JsonSchema7Unknown {\n  return \"$id\" in jsonSchema && jsonSchema.$id === constUnknown.$id\n}\n\nfunction isVoid(jsonSchema: JsonSchema7): jsonSchema is JsonSchema7Void {\n  return \"$id\" in jsonSchema && jsonSchema.$id === constVoid.$id\n}\n\nfunction isCompactableLiteral(jsonSchema: JsonSchema7 | undefined): jsonSchema is JsonSchema7Enum {\n  return Predicate.hasProperty(jsonSchema, \"enum\") && \"type\" in jsonSchema && Object.keys(jsonSchema).length === 2\n}\n\nfunction compactUnion(members: Array<JsonSchema7>): Array<JsonSchema7> {\n  const out: Array<JsonSchema7> = []\n  for (const m of members) {\n    if (isNeverWithoutCustomAnnotations(m)) continue\n    if (isAny(m) || isUnknown(m) || isVoid(m)) return [m]\n    if (isCompactableLiteral(m) && out.length > 0) {\n      const last = out[out.length - 1]\n      if (isCompactableLiteral(last) && last.type === m.type) {\n        out[out.length - 1] = {\n          type: last.type,\n          enum: [...last.enum, ...m.enum]\n        } as JsonSchema7Enum\n        continue\n      }\n    }\n    out.push(m)\n  }\n  return out\n}\n"
  },
  {
    "path": "packages/effect/src/KeyedPool.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/keyedPool.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const KeyedPoolTypeId: unique symbol = internal.KeyedPoolTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type KeyedPoolTypeId = typeof KeyedPoolTypeId\n\n/**\n * A `KeyedPool<K, A, E>` is a pool of `Pool`s of items of type `A`. Each pool\n * in the `KeyedPool` is associated with a key of type `K`.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface KeyedPool<in K, in out A, out E = never> extends KeyedPool.Variance<K, A, E>, Pipeable {\n  /**\n   * Retrieves an item from the pool belonging to the given key in a scoped\n   * effect. Note that if acquisition fails, then the returned effect will fail\n   * for that same reason. Retrying a failed acquisition attempt will repeat the\n   * acquisition attempt.\n   */\n  get(key: K): Effect.Effect<A, E, Scope.Scope>\n\n  /**\n   * Invalidates the specified item. This will cause the pool to eventually\n   * reallocate the item, although this reallocation may occur lazily rather\n   * than eagerly.\n   */\n  invalidate(item: A): Effect.Effect<void>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace KeyedPool {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in K, in out A, out E> {\n    readonly [KeyedPoolTypeId]: {\n      readonly _K: Types.Contravariant<K>\n      readonly _A: Types.Invariant<A>\n      readonly _E: Types.Covariant<E>\n    }\n  }\n}\n\n/**\n * Makes a new pool of the specified fixed size. The pool is returned in a\n * `Scope`, which governs the lifetime of the pool. When the pool is shutdown\n * because the `Scope` is closed, the individual items allocated by the pool\n * will be released in some unspecified order.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <K, A, E, R>(\n  options: {\n    readonly acquire: (key: K) => Effect.Effect<A, E, R>\n    readonly size: number\n  }\n) => Effect.Effect<KeyedPool<K, A, E>, never, Scope.Scope | R> = internal.make\n\n/**\n * Makes a new pool of the specified fixed size. The pool is returned in a\n * `Scope`, which governs the lifetime of the pool. When the pool is shutdown\n * because the `Scope` is closed, the individual items allocated by the pool\n * will be released in some unspecified order.\n *\n * The size of the underlying pools can be configured per key.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeWith: <K, A, E, R>(\n  options: {\n    readonly acquire: (key: K) => Effect.Effect<A, E, R>\n    readonly size: (key: K) => number\n  }\n) => Effect.Effect<KeyedPool<K, A, E>, never, Scope.Scope | R> = internal.makeWith\n\n/**\n * Makes a new pool with the specified minimum and maximum sizes and time to\n * live before a pool whose excess items are not being used will be shrunk\n * down to the minimum size. The pool is returned in a `Scope`, which governs\n * the lifetime of the pool. When the pool is shutdown because the `Scope` is\n * used, the individual items allocated by the pool will be released in some\n * unspecified order.\n *\n * The size of the underlying pools can be configured per key.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeWithTTL: <K, A, E, R>(\n  options: {\n    readonly acquire: (key: K) => Effect.Effect<A, E, R>\n    readonly min: (key: K) => number\n    readonly max: (key: K) => number\n    readonly timeToLive: Duration.DurationInput\n  }\n) => Effect.Effect<KeyedPool<K, A, E>, never, Scope.Scope | R> = internal.makeWithTTL\n\n/**\n * Makes a new pool with the specified minimum and maximum sizes and time to\n * live before a pool whose excess items are not being used will be shrunk\n * down to the minimum size. The pool is returned in a `Scope`, which governs\n * the lifetime of the pool. When the pool is shutdown because the `Scope` is\n * used, the individual items allocated by the pool will be released in some\n * unspecified order.\n *\n * The size of the underlying pools can be configured per key.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeWithTTLBy: <K, A, E, R>(\n  options: {\n    readonly acquire: (key: K) => Effect.Effect<A, E, R>\n    readonly min: (key: K) => number\n    readonly max: (key: K) => number\n    readonly timeToLive: (key: K) => Duration.DurationInput\n  }\n) => Effect.Effect<KeyedPool<K, A, E>, never, Scope.Scope | R> = internal.makeWithTTLBy\n\n/**\n * Retrieves an item from the pool belonging to the given key in a scoped\n * effect. Note that if acquisition fails, then the returned effect will fail\n * for that same reason. Retrying a failed acquisition attempt will repeat the\n * acquisition attempt.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const get: {\n  <K>(key: K): <A, E>(self: KeyedPool<K, A, E>) => Effect.Effect<A, E, Scope.Scope>\n  <K, A, E>(self: KeyedPool<K, A, E>, key: K): Effect.Effect<A, E, Scope.Scope>\n} = internal.get\n\n/**\n * Invalidates the specified item. This will cause the pool to eventually\n * reallocate the item, although this reallocation may occur lazily rather\n * than eagerly.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const invalidate: {\n  <A>(item: A): <K, E>(self: KeyedPool<K, A, E>) => Effect.Effect<void>\n  <K, A, E>(self: KeyedPool<K, A, E>, item: A): Effect.Effect<void>\n} = internal.invalidate\n"
  },
  {
    "path": "packages/effect/src/Layer.ts",
    "content": "/**\n * A `Layer<ROut, E, RIn>` describes how to build one or more services in your\n * application. Services can be injected into effects via\n * `Effect.provideService`. Effects can require services via `Effect.service`.\n *\n * Layer can be thought of as recipes for producing bundles of services, given\n * their dependencies (other services).\n *\n * Construction of services can be effectful and utilize resources that must be\n * acquired and safely released when the services are done being utilized.\n *\n * By default layers are shared, meaning that if the same layer is used twice\n * the layer will only be allocated a single time.\n *\n * Because of their excellent composition properties, layers are the idiomatic\n * way in Effect-TS to create services that depend on other services.\n *\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Clock from \"./Clock.js\"\nimport type { ConfigProvider } from \"./ConfigProvider.js\"\nimport * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type { FiberRef } from \"./FiberRef.js\"\nimport { dual, type LazyArg } from \"./Function.js\"\nimport { clockTag } from \"./internal/clock.js\"\nimport * as core from \"./internal/core.js\"\nimport * as defaultServices from \"./internal/defaultServices.js\"\nimport * as fiberRuntime from \"./internal/fiberRuntime.js\"\nimport * as internal from \"./internal/layer.js\"\nimport * as circularLayer from \"./internal/layer/circular.js\"\nimport * as query from \"./internal/query.js\"\nimport { randomTag } from \"./internal/random.js\"\nimport type { LogLevel } from \"./LogLevel.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Random from \"./Random.js\"\nimport type * as Request from \"./Request.js\"\nimport type * as Runtime from \"./Runtime.js\"\nimport type * as Schedule from \"./Schedule.js\"\nimport * as Scheduler from \"./Scheduler.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Stream from \"./Stream.js\"\nimport type * as Tracer from \"./Tracer.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const LayerTypeId: unique symbol = internal.LayerTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type LayerTypeId = typeof LayerTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Layer<in ROut, out E = never, out RIn = never> extends Layer.Variance<ROut, E, RIn>, Pipeable {}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Layer {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in ROut, out E, out RIn> {\n    readonly [LayerTypeId]: {\n      readonly _ROut: Types.Contravariant<ROut>\n      readonly _E: Types.Covariant<E>\n      readonly _RIn: Types.Covariant<RIn>\n    }\n  }\n  /**\n   * @since 3.9.0\n   * @category type-level\n   */\n  export interface Any {\n    readonly [LayerTypeId]: {\n      readonly _ROut: Types.Contravariant<never>\n      readonly _E: Types.Covariant<any>\n      readonly _RIn: Types.Covariant<any>\n    }\n  }\n  /**\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type Context<T extends Any> = [T] extends [Layer<infer _ROut, infer _E, infer _RIn>] ? _RIn\n    : never\n  /**\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type Error<T extends Any> = [T] extends [Layer<infer _ROut, infer _E, infer _RIn>] ? _E\n    : never\n  /**\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type Success<T extends Any> = [T] extends [Layer<infer _ROut, infer _E, infer _RIn>] ? _ROut\n    : never\n}\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MemoMapTypeId: unique symbol = internal.MemoMapTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MemoMapTypeId = typeof MemoMapTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MemoMap {\n  readonly [MemoMapTypeId]: MemoMapTypeId\n\n  /** @internal */\n  readonly getOrElseMemoize: <RIn, E, ROut>(\n    layer: Layer<ROut, E, RIn>,\n    scope: Scope.Scope\n  ) => Effect.Effect<Context.Context<ROut>, E, RIn>\n}\n\n/**\n * @since 3.13.0\n * @category models\n */\nexport interface CurrentMemoMap {\n  readonly _: unique symbol\n}\n\n/**\n * @since 3.13.0\n * @category models\n */\nexport const CurrentMemoMap: Context.Reference<CurrentMemoMap, MemoMap> = internal.CurrentMemoMap\n\n/**\n * Returns `true` if the specified value is a `Layer`, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isLayer: (u: unknown) => u is Layer<unknown, unknown, unknown> = internal.isLayer\n\n/**\n * Returns `true` if the specified `Layer` is a fresh version that will not be\n * shared, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isFresh: <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => boolean = internal.isFresh\n\n/**\n * @since 3.3.0\n * @category tracing\n */\nexport const annotateLogs: {\n  (key: string, value: unknown): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R>\n  (values: Record<string, unknown>): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R>\n  <A, E, R>(self: Layer<A, E, R>, key: string, value: unknown): Layer<A, E, R>\n  <A, E, R>(self: Layer<A, E, R>, values: Record<string, unknown>): Layer<A, E, R>\n} = internal.annotateLogs\n\n/**\n * @since 3.3.0\n * @category tracing\n */\nexport const annotateSpans: {\n  (key: string, value: unknown): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R>\n  (values: Record<string, unknown>): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R>\n  <A, E, R>(self: Layer<A, E, R>, key: string, value: unknown): Layer<A, E, R>\n  <A, E, R>(self: Layer<A, E, R>, values: Record<string, unknown>): Layer<A, E, R>\n} = internal.annotateSpans\n\n/**\n * Builds a layer into a scoped value.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const build: <RIn, E, ROut>(\n  self: Layer<ROut, E, RIn>\n) => Effect.Effect<Context.Context<ROut>, E, Scope.Scope | RIn> = internal.build\n\n/**\n * Builds a layer into an `Effect` value. Any resources associated with this\n * layer will be released when the specified scope is closed unless their scope\n * has been extended. This allows building layers where the lifetime of some of\n * the services output by the layer exceed the lifetime of the effect the\n * layer is provided to.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const buildWithScope: {\n  (scope: Scope.Scope): <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Effect.Effect<Context.Context<ROut>, E, RIn>\n  <RIn, E, ROut>(self: Layer<ROut, E, RIn>, scope: Scope.Scope): Effect.Effect<Context.Context<ROut>, E, RIn>\n} = internal.buildWithScope\n\n/**\n * Recovers from all errors.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchAll: {\n  <E, RIn2, E2, ROut2>(\n    onError: (error: E) => Layer<ROut2, E2, RIn2>\n  ): <RIn, ROut>(self: Layer<ROut, E, RIn>) => Layer<ROut & ROut2, E2, RIn2 | RIn>\n  <RIn, E, ROut, RIn2, E2, ROut2>(\n    self: Layer<ROut, E, RIn>,\n    onError: (error: E) => Layer<ROut2, E2, RIn2>\n  ): Layer<ROut & ROut2, E2, RIn | RIn2>\n} = internal.catchAll\n\n/**\n * Recovers from all errors.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchAllCause: {\n  <E, RIn2, E2, ROut2>(\n    onError: (cause: Cause.Cause<E>) => Layer<ROut2, E2, RIn2>\n  ): <RIn, ROut>(self: Layer<ROut, E, RIn>) => Layer<ROut & ROut2, E2, RIn2 | RIn>\n  <RIn, E, ROut, RIn2, E2, ROut22>(\n    self: Layer<ROut, E, RIn>,\n    onError: (cause: Cause.Cause<E>) => Layer<ROut22, E2, RIn2>\n  ): Layer<ROut & ROut22, E2, RIn | RIn2>\n} = internal.catchAllCause\n\n/**\n * Constructs a `Layer` that passes along the specified context as an\n * output.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const context: <R>() => Layer<R, never, R> = internal.context\n\n/**\n * Constructs a layer that dies with the specified defect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const die: (defect: unknown) => Layer<unknown> = internal.die\n\n/**\n * Constructs a layer that dies with the specified defect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dieSync: (evaluate: LazyArg<unknown>) => Layer<unknown> = internal.dieSync\n\n/**\n * Replaces the layer's output with `never` and includes the layer only for its\n * side-effects.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const discard: <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Layer<never, E, RIn> = internal.discard\n\n/**\n * Constructs a layer from the specified effect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const effect: {\n  <I, S>(tag: Context.Tag<I, S>): <E, R>(effect: Effect.Effect<Types.NoInfer<S>, E, R>) => Layer<I, E, R>\n  <I, S, E, R>(tag: Context.Tag<I, S>, effect: Effect.Effect<Types.NoInfer<S>, E, R>): Layer<I, E, R>\n} = internal.fromEffect\n\n/**\n * Constructs a layer from the specified effect, discarding its output.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const effectDiscard: <X, E, R>(effect: Effect.Effect<X, E, R>) => Layer<never, E, R> = internal.fromEffectDiscard\n\n/**\n * Constructs a layer from the specified effect, which must return one or more\n * services.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const effectContext: <A, E, R>(effect: Effect.Effect<Context.Context<A>, E, R>) => Layer<A, E, R> =\n  internal.fromEffectContext\n\n/**\n * A Layer that constructs an empty Context.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: Layer<never> = internal.empty\n\n/**\n * Extends the scope of this layer, returning a new layer that when provided\n * to an effect will not immediately release its associated resources when\n * that effect completes execution but instead when the scope the resulting\n * effect depends on is closed.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const extendScope: <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Layer<ROut, E, Scope.Scope | RIn> =\n  internal.extendScope\n\n/**\n * Constructs a layer that fails with the specified error.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fail: <E>(error: E) => Layer<unknown, E> = internal.fail\n\n/**\n * Constructs a layer that fails with the specified error.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failSync: <E>(evaluate: LazyArg<E>) => Layer<unknown, E> = internal.failSync\n\n/**\n * Constructs a layer that fails with the specified cause.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCause: <E>(cause: Cause.Cause<E>) => Layer<unknown, E> = internal.failCause\n\n/**\n * Constructs a layer that fails with the specified cause.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCauseSync: <E>(evaluate: LazyArg<Cause.Cause<E>>) => Layer<unknown, E> = internal.failCauseSync\n\n/**\n * Constructs a layer dynamically based on the output of this layer.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMap: {\n  <A, A2, E2, R2>(\n    f: (context: Context.Context<A>) => Layer<A2, E2, R2>\n  ): <E, R>(self: Layer<A, E, R>) => Layer<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Layer<A, E, R>,\n    f: (context: Context.Context<A>) => Layer<A2, E2, R2>\n  ): Layer<A2, E | E2, R | R2>\n} = internal.flatMap\n\n/**\n * Flattens layers nested in the context of an effect.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatten: {\n  <I, A, E2, R2>(tag: Context.Tag<I, Layer<A, E2, R2>>): <E, R>(self: Layer<I, E, R>) => Layer<A, E2 | E, R2 | R>\n  <I, E, R, A, E2, R2>(self: Layer<I, E, R>, tag: Context.Tag<I, Layer<A, E2, R2>>): Layer<A, E | E2, R | R2>\n} = internal.flatten\n\n/**\n * Creates a fresh version of this layer that will not be shared.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const fresh: <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R> = internal.fresh\n\n/**\n * @since 3.17.0\n * @category Testing\n */\nexport type PartialEffectful<A extends object> = Types.Simplify<\n  & {\n    [\n      K in keyof A as A[K] extends\n        | Effect.Effect<any, any, any>\n        | Stream.Stream<any, any, any>\n        | ((...args: any) => Effect.Effect<any, any, any> | Stream.Stream<any, any, any>) ? K\n        : never\n    ]?: A[K]\n  }\n  & {\n    [\n      K in keyof A as A[K] extends\n        | Effect.Effect<any, any, any>\n        | Stream.Stream<any, any, any>\n        | ((...args: any) => Effect.Effect<any, any, any> | Stream.Stream<any, any, any>) ? never\n        : K\n    ]: A[K]\n  }\n>\n\n/**\n * Creates a mock layer for testing purposes. You can provide a partial\n * implementation of the service, and any methods not provided will\n * throw an `UnimplementedError` defect when called.\n *\n * **Example**\n *\n * ```ts\n * import { Context, Effect, Layer } from \"effect\"\n *\n * class MyService extends Context.Tag(\"MyService\")<\n *   MyService,\n *   {\n *     one: Effect.Effect<number>\n *     two(): Effect.Effect<number>\n *   }\n * >() {}\n *\n * const MyServiceTest = Layer.mock(MyService, {\n *   two: () => Effect.succeed(2)\n * })\n * ```\n *\n * @since 3.17.0\n * @category Testing\n */\nexport const mock: {\n  <I, S extends object>(tag: Context.Tag<I, S>): (service: PartialEffectful<S>) => Layer<I>\n  <I, S extends object>(tag: Context.Tag<I, S>, service: PartialEffectful<S>): Layer<I>\n} = internal.mock\n\nconst fromFunction: <I1, S1, I2, S2>(\n  tagA: Context.Tag<I1, S1>,\n  tagB: Context.Tag<I2, S2>,\n  f: (a: Types.NoInfer<S1>) => Types.NoInfer<S2>\n) => Layer<I2, never, I1> = internal.fromFunction\n\nexport {\n  /**\n   * Constructs a layer from the context using the specified function.\n   *\n   * @since 2.0.0\n   * @category constructors\n   */\n  fromFunction as function\n}\n\n/**\n * Builds this layer and uses it until it is interrupted. This is useful when\n * your entire application is a layer, such as an HTTP server.\n *\n * @since 2.0.0\n * @category conversions\n */\nexport const launch: <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Effect.Effect<never, E, RIn> = internal.launch\n\n/**\n * Returns a new layer whose output is mapped by the specified function.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <A, B>(f: (context: Context.Context<A>) => Context.Context<B>): <E, R>(self: Layer<A, E, R>) => Layer<B, E, R>\n  <A, E, R, B>(self: Layer<A, E, R>, f: (context: Context.Context<A>) => Context.Context<B>): Layer<B, E, R>\n} = internal.map\n\n/**\n * Returns a layer with its error channel mapped using the specified function.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapError: {\n  <E, E2>(f: (error: E) => E2): <A, R>(self: Layer<A, E, R>) => Layer<A, E2, R>\n  <A, E, R, E2>(self: Layer<A, E, R>, f: (error: E) => E2): Layer<A, E2, R>\n} = internal.mapError\n\n/**\n * Feeds the error or output services of this layer into the input of either\n * the specified `failure` or `success` layers, resulting in a new layer with\n * the inputs of this layer, and the error or outputs of the specified layer.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <E, A2, E2, R2, A, A3, E3, R3>(\n    options: {\n      readonly onFailure: (error: E) => Layer<A2, E2, R2>\n      readonly onSuccess: (context: Context.Context<A>) => Layer<A3, E3, R3>\n    }\n  ): <R>(self: Layer<A, E, R>) => Layer<A2 & A3, E2 | E3, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Layer<A, E, R>,\n    options: {\n      readonly onFailure: (error: E) => Layer<A2, E2, R2>\n      readonly onSuccess: (context: Context.Context<A>) => Layer<A3, E3, R3>\n    }\n  ): Layer<A2 & A3, E2 | E3, R | R2 | R3>\n} = internal.match\n\n/**\n * Feeds the error or output services of this layer into the input of either\n * the specified `failure` or `success` layers, resulting in a new layer with\n * the inputs of this layer, and the error or outputs of the specified layer.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const matchCause: {\n  <E, A2, E2, R2, A, A3, E3, R3>(\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Layer<A2, E2, R2>\n      readonly onSuccess: (context: Context.Context<A>) => Layer<A3, E3, R3>\n    }\n  ): <R>(self: Layer<A, E, R>) => Layer<A2 & A3, E2 | E3, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Layer<A, E, R>,\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Layer<A2, E2, R2>\n      readonly onSuccess: (context: Context.Context<A>) => Layer<A3, E3, R3>\n    }\n  ): Layer<A2 & A3, E2 | E3, R | R2 | R3>\n} = internal.matchCause\n\n/**\n * Returns a scoped effect that, if evaluated, will return the lazily computed\n * result of this layer.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const memoize: <RIn, E, ROut>(\n  self: Layer<ROut, E, RIn>\n) => Effect.Effect<Layer<ROut, E, RIn>, never, Scope.Scope> = internal.memoize\n\n/**\n * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const merge: {\n  <RIn2, E2, ROut2>(\n    that: Layer<ROut2, E2, RIn2>\n  ): <RIn, E1, ROut>(self: Layer<ROut, E1, RIn>) => Layer<ROut2 | ROut, E2 | E1, RIn2 | RIn>\n  <RIn, E1, ROut, RIn2, E2, ROut2>(\n    self: Layer<ROut, E1, RIn>,\n    that: Layer<ROut2, E2, RIn2>\n  ): Layer<ROut | ROut2, E1 | E2, RIn | RIn2>\n} = internal.merge\n\n/**\n * Combines all the provided layers concurrently, creating a new layer with merged input, error, and output types.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const mergeAll: <Layers extends readonly [Layer<never, any, any>, ...Array<Layer<never, any, any>>]>(\n  ...layers: Layers\n) => Layer<\n  { [k in keyof Layers]: Layer.Success<Layers[k]> }[number],\n  { [k in keyof Layers]: Layer.Error<Layers[k]> }[number],\n  { [k in keyof Layers]: Layer.Context<Layers[k]> }[number]\n> = internal.mergeAll\n\n/**\n * Translates effect failure into death of the fiber, making all failures\n * unchecked and not a part of the type of the layer.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orDie: <A, E, R>(self: Layer<A, E, R>) => Layer<A, never, R> = internal.orDie\n\n/**\n * Executes this layer and returns its output, if it succeeds, but otherwise\n * executes the specified layer.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElse: {\n  <A2, E2, R2>(that: LazyArg<Layer<A2, E2, R2>>): <A, E, R>(self: Layer<A, E, R>) => Layer<A & A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Layer<A, E, R>, that: LazyArg<Layer<A2, E2, R2>>): Layer<A & A2, E | E2, R | R2>\n} = internal.orElse\n\n/**\n * Returns a new layer that produces the outputs of this layer but also\n * passes through the inputs.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const passthrough: <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Layer<RIn | ROut, E, RIn> = internal.passthrough\n\n/**\n * Projects out part of one of the services output by this layer using the\n * specified function.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const project: {\n  <I1, S1, I2, S2>(\n    tagA: Context.Tag<I1, S1>,\n    tagB: Context.Tag<I2, S2>,\n    f: (a: Types.NoInfer<S1>) => Types.NoInfer<S2>\n  ): <RIn, E>(self: Layer<I1, E, RIn>) => Layer<I2, E, RIn>\n  <RIn, E, I1, S1, I2, S2>(\n    self: Layer<I1, E, RIn>,\n    tagA: Context.Tag<I1, S1>,\n    tagB: Context.Tag<I2, S2>,\n    f: (a: Types.NoInfer<S1>) => Types.NoInfer<S2>\n  ): Layer<I2, E, RIn>\n} = internal.project\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const locallyEffect: {\n  <RIn, E, ROut, RIn2, E2, ROut2>(\n    f: (_: Effect.Effect<RIn, E, Context.Context<ROut>>) => Effect.Effect<RIn2, E2, Context.Context<ROut2>>\n  ): (self: Layer<ROut, E, RIn>) => Layer<ROut2, E2, RIn2>\n  <RIn, E, ROut, RIn2, E2, ROut2>(\n    self: Layer<ROut, E, RIn>,\n    f: (_: Effect.Effect<RIn, E, Context.Context<ROut>>) => Effect.Effect<RIn2, E2, Context.Context<ROut2>>\n  ): Layer<ROut2, E2, RIn2>\n} = internal.locallyEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const locally: {\n  <X>(\n    ref: FiberRef<X>,\n    value: X\n  ): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R>\n  <A, E, R, X>(\n    self: Layer<A, E, R>,\n    ref: FiberRef<X>,\n    value: X\n  ): Layer<A, E, R>\n} = internal.fiberRefLocally\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const locallyWith: {\n  <X>(ref: FiberRef<X>, value: (_: X) => X): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R>\n  <A, E, R, X>(self: Layer<A, E, R>, ref: FiberRef<X>, value: (_: X) => X): Layer<A, E, R>\n} = internal.fiberRefLocallyWith\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const locallyScoped: <A>(self: FiberRef<A>, value: A) => Layer<never> = internal.fiberRefLocallyScoped\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const fiberRefLocallyScopedWith: <A>(self: FiberRef<A>, value: (_: A) => A) => Layer<never> =\n  internal.fiberRefLocallyScopedWith\n\n/**\n * Retries constructing this layer according to the specified schedule.\n *\n * @since 2.0.0\n * @category retrying\n */\nexport const retry: {\n  <X, E, RIn2>(\n    schedule: Schedule.Schedule<X, NoInfer<E>, RIn2>\n  ): <ROut, RIn>(self: Layer<ROut, E, RIn>) => Layer<ROut, E, RIn2 | RIn>\n  <ROut, E, RIn, X, RIn2>(\n    self: Layer<ROut, E, RIn>,\n    schedule: Schedule.Schedule<X, E, RIn2>\n  ): Layer<ROut, E, RIn | RIn2>\n} = internal.retry\n\n/**\n * A layer that constructs a scope and closes it when the workflow the layer\n * is provided to completes execution, whether by success, failure, or\n * interruption. This can be used to close a scope when providing a layer to a\n * workflow.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const scope: Layer<Scope.Scope> = internal.scope\n\n/**\n * Constructs a layer from the specified scoped effect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const scoped: {\n  <I, S>(\n    tag: Context.Tag<I, S>\n  ): <E, R>(effect: Effect.Effect<Types.NoInfer<S>, E, R>) => Layer<I, E, Exclude<R, Scope.Scope>>\n  <I, S, E, R>(\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<Types.NoInfer<S>, E, R>\n  ): Layer<I, E, Exclude<R, Scope.Scope>>\n} = internal.scoped\n\n/**\n * Constructs a layer from the specified scoped effect, discarding its output.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const scopedDiscard: <X, E, R>(effect: Effect.Effect<X, E, R>) => Layer<never, E, Exclude<R, Scope.Scope>> =\n  internal.scopedDiscard\n\n/**\n * Constructs a layer from the specified scoped effect, which must return one\n * or more services.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const scopedContext: <A, E, R>(\n  effect: Effect.Effect<Context.Context<A>, E, R>\n) => Layer<A, E, Exclude<R, Scope.Scope>> = internal.scopedContext\n\n/**\n * Constructs a layer that accesses and returns the specified service from the\n * context.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const service: <I, S>(tag: Context.Tag<I, S>) => Layer<I, never, I> = internal.service\n\n/**\n * Constructs a layer from the specified value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeed: {\n  <I, S>(tag: Context.Tag<I, S>): (resource: Types.NoInfer<S>) => Layer<I>\n  <I, S>(tag: Context.Tag<I, S>, resource: Types.NoInfer<S>): Layer<I>\n} = internal.succeed\n\n/**\n * Constructs a layer from the specified value, which must return one or more\n * services.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeedContext: <A>(context: Context.Context<A>) => Layer<A> = internal.succeedContext\n\n/**\n * Lazily constructs a layer. This is useful to avoid infinite recursion when\n * creating layers that refer to themselves.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const suspend: <RIn, E, ROut>(evaluate: LazyArg<Layer<ROut, E, RIn>>) => Layer<ROut, E, RIn> = internal.suspend\n\n/**\n * Lazily constructs a layer from the specified value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sync: {\n  <I, S>(tag: Context.Tag<I, S>): (evaluate: LazyArg<Types.NoInfer<S>>) => Layer<I>\n  <I, S>(tag: Context.Tag<I, S>, evaluate: LazyArg<Types.NoInfer<S>>): Layer<I>\n} = internal.sync\n\n/**\n * Lazily constructs a layer from the specified value, which must return one or more\n * services.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const syncContext: <A>(evaluate: LazyArg<Context.Context<A>>) => Layer<A> = internal.syncContext\n\n/**\n * Performs the specified effect if this layer succeeds.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tap: {\n  <ROut, XR extends ROut, RIn2, E2, X>(\n    f: (context: Context.Context<XR>) => Effect.Effect<X, E2, RIn2>\n  ): <RIn, E>(self: Layer<ROut, E, RIn>) => Layer<ROut, E2 | E, RIn2 | RIn>\n  <RIn, E, ROut, XR extends ROut, RIn2, E2, X>(\n    self: Layer<ROut, E, RIn>,\n    f: (context: Context.Context<XR>) => Effect.Effect<X, E2, RIn2>\n  ): Layer<ROut, E | E2, RIn | RIn2>\n} = internal.tap\n\n/**\n * Performs the specified effect if this layer fails.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tapError: {\n  <E, XE extends E, RIn2, E2, X>(\n    f: (e: XE) => Effect.Effect<X, E2, RIn2>\n  ): <RIn, ROut>(self: Layer<ROut, E, RIn>) => Layer<ROut, E | E2, RIn2 | RIn>\n  <RIn, E, XE extends E, ROut, RIn2, E2, X>(\n    self: Layer<ROut, E, RIn>,\n    f: (e: XE) => Effect.Effect<X, E2, RIn2>\n  ): Layer<ROut, E | E2, RIn | RIn2>\n} = internal.tapError\n\n/**\n * Performs the specified effect if this layer fails.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tapErrorCause: {\n  <E, XE extends E, RIn2, E2, X>(\n    f: (cause: Cause.Cause<XE>) => Effect.Effect<X, E2, RIn2>\n  ): <RIn, ROut>(self: Layer<ROut, E, RIn>) => Layer<ROut, E | E2, RIn2 | RIn>\n  <RIn, E, XE extends E, ROut, RIn2, E2, X>(\n    self: Layer<ROut, E, RIn>,\n    f: (cause: Cause.Cause<XE>) => Effect.Effect<X, E2, RIn2>\n  ): Layer<ROut, E | E2, RIn | RIn2>\n} = internal.tapErrorCause\n\n/**\n * Converts a layer that requires no services into a scoped runtime, which can\n * be used to execute effects.\n *\n * @since 2.0.0\n * @category conversions\n */\nexport const toRuntime: <RIn, E, ROut>(\n  self: Layer<ROut, E, RIn>\n) => Effect.Effect<Runtime.Runtime<ROut>, E, Scope.Scope | RIn> = internal.toRuntime\n\n/**\n * Converts a layer that requires no services into a scoped runtime, which can\n * be used to execute effects.\n *\n * @since 2.0.0\n * @category conversions\n */\nexport const toRuntimeWithMemoMap: {\n  (\n    memoMap: MemoMap\n  ): <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Effect.Effect<Runtime.Runtime<ROut>, E, Scope.Scope | RIn>\n  <RIn, E, ROut>(\n    self: Layer<ROut, E, RIn>,\n    memoMap: MemoMap\n  ): Effect.Effect<Runtime.Runtime<ROut>, E, Scope.Scope | RIn>\n} = internal.toRuntimeWithMemoMap\n\n/**\n * Feeds the output services of this builder into the input of the specified\n * builder, resulting in a new builder with the inputs of this builder as\n * well as any leftover inputs, and the outputs of the specified builder.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const provide: {\n  <RIn, E, ROut>(\n    that: Layer<ROut, E, RIn>\n  ): <RIn2, E2, ROut2>(self: Layer<ROut2, E2, RIn2>) => Layer<ROut2, E | E2, RIn | Exclude<RIn2, ROut>>\n  <const Layers extends readonly [Layer.Any, ...Array<Layer.Any>]>(\n    that: Layers\n  ): <A, E, R>(\n    self: Layer<A, E, R>\n  ) => Layer<\n    A,\n    E | { [k in keyof Layers]: Layer.Error<Layers[k]> }[number],\n    | { [k in keyof Layers]: Layer.Context<Layers[k]> }[number]\n    | Exclude<R, { [k in keyof Layers]: Layer.Success<Layers[k]> }[number]>\n  >\n  <RIn2, E2, ROut2, RIn, E, ROut>(\n    self: Layer<ROut2, E2, RIn2>,\n    that: Layer<ROut, E, RIn>\n  ): Layer<ROut2, E | E2, RIn | Exclude<RIn2, ROut>>\n  <A, E, R, const Layers extends readonly [Layer.Any, ...Array<Layer.Any>]>(\n    self: Layer<A, E, R>,\n    that: Layers\n  ): Layer<\n    A,\n    E | { [k in keyof Layers]: Layer.Error<Layers[k]> }[number],\n    | { [k in keyof Layers]: Layer.Context<Layers[k]> }[number]\n    | Exclude<R, { [k in keyof Layers]: Layer.Success<Layers[k]> }[number]>\n  >\n} = internal.provide\n\n/**\n * Feeds the output services of this layer into the input of the specified\n * layer, resulting in a new layer with the inputs of this layer, and the\n * outputs of both layers.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const provideMerge: {\n  <RIn, E, ROut>(\n    self: Layer<ROut, E, RIn>\n  ): <RIn2, E2, ROut2>(that: Layer<ROut2, E2, RIn2>) => Layer<ROut | ROut2, E | E2, RIn | Exclude<RIn2, ROut>>\n  <RIn2, E2, ROut2, RIn, E, ROut>(\n    that: Layer<ROut2, E2, RIn2>,\n    self: Layer<ROut, E, RIn>\n  ): Layer<ROut2 | ROut, E2 | E, RIn | Exclude<RIn2, ROut>>\n} = internal.provideMerge\n\n/**\n * Combines this layer with the specified layer concurrently, creating a new layer with merged input types and\n * combined output types using the provided function.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWith: {\n  <B, E2, R2, A, C>(\n    that: Layer<B, E2, R2>,\n    f: (a: Context.Context<A>, b: Context.Context<B>) => Context.Context<C>\n  ): <E, R>(self: Layer<A, E, R>) => Layer<C, E2 | E, R2 | R>\n  <A, E, R, B, E2, R2, C>(\n    self: Layer<A, E, R>,\n    that: Layer<B, E2, R2>,\n    f: (a: Context.Context<A>, b: Context.Context<B>) => Context.Context<C>\n  ): Layer<C, E | E2, R | R2>\n} = internal.zipWith\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const unwrapEffect: <A, E1, R1, E, R>(self: Effect.Effect<Layer<A, E1, R1>, E, R>) => Layer<A, E | E1, R | R1> =\n  internal.unwrapEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const unwrapScoped: <A, E1, R1, E, R>(\n  self: Effect.Effect<Layer<A, E1, R1>, E, R>\n) => Layer<A, E | E1, R1 | Exclude<R, Scope.Scope>> = internal.unwrapScoped\n\n/**\n * @since 2.0.0\n * @category clock\n */\nexport const setClock: <A extends Clock.Clock>(clock: A) => Layer<never> = <A extends Clock.Clock>(\n  clock: A\n): Layer<never> =>\n  scopedDiscard(\n    fiberRuntime.fiberRefLocallyScopedWith(defaultServices.currentServices, Context.add(clockTag, clock))\n  )\n\n/**\n * Sets the current `ConfigProvider`.\n *\n * @since 2.0.0\n * @category config\n */\nexport const setConfigProvider: (configProvider: ConfigProvider) => Layer<never> = circularLayer.setConfigProvider\n\n/**\n * Adds the provided span to the span stack.\n *\n * @since 2.0.0\n * @category tracing\n */\nexport const parentSpan: (span: Tracer.AnySpan) => Layer<Tracer.ParentSpan> = circularLayer.parentSpan\n\n/**\n * @since 3.15.0\n * @category Random\n */\nexport const setRandom = <A extends Random.Random>(random: A): Layer<never> =>\n  scopedDiscard(\n    fiberRuntime.fiberRefLocallyScopedWith(defaultServices.currentServices, Context.add(randomTag, random))\n  )\n\n/**\n * @since 2.0.0\n * @category requests & batching\n */\nexport const setRequestBatching: (requestBatching: boolean) => Layer<never> = (\n  requestBatching: boolean\n) =>\n  scopedDiscard(\n    fiberRuntime.fiberRefLocallyScoped(core.currentRequestBatching, requestBatching)\n  )\n\n/**\n * @since 2.0.0\n * @category requests & batching\n */\nexport const setRequestCaching: (requestCaching: boolean) => Layer<never> = (\n  requestCaching: boolean\n) =>\n  scopedDiscard(\n    fiberRuntime.fiberRefLocallyScoped(query.currentCacheEnabled, requestCaching)\n  )\n\n/**\n * @since 2.0.0\n * @category requests & batching\n */\nexport const setRequestCache: {\n  <E, R>(\n    cache: Effect.Effect<Request.Cache, E, R>\n  ): Layer<never, E, Exclude<R, Scope.Scope>>\n  (\n    cache: Request.Cache\n  ): Layer<never>\n} = (<E, R>(cache: Request.Cache | Effect.Effect<Request.Cache, E, R>) =>\n  scopedDiscard(\n    core.isEffect(cache) ?\n      core.flatMap(cache, (x) => fiberRuntime.fiberRefLocallyScoped(query.currentCache as any, x)) :\n      fiberRuntime.fiberRefLocallyScoped(query.currentCache as any, cache)\n  )) as any\n\n/**\n * @since 2.0.0\n * @category scheduler\n */\nexport const setScheduler: (scheduler: Scheduler.Scheduler) => Layer<never> = (\n  scheduler: Scheduler.Scheduler\n): Layer<never> =>\n  scopedDiscard(\n    fiberRuntime.fiberRefLocallyScoped(Scheduler.currentScheduler, scheduler)\n  )\n\n/**\n * Create and add a span to the current span stack.\n *\n * The span is ended when the Layer is released.\n *\n * @since 2.0.0\n * @category tracing\n */\nexport const span: (\n  name: string,\n  options?: Tracer.SpanOptions & {\n    readonly onEnd?:\n      | ((span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>)\n      | undefined\n  }\n) => Layer<Tracer.ParentSpan> = circularLayer.span\n\n/**\n * Create a Layer that sets the current Tracer\n *\n * @since 2.0.0\n * @category tracing\n */\nexport const setTracer: (tracer: Tracer.Tracer) => Layer<never> = circularLayer.setTracer\n\n/**\n * @since 2.0.0\n * @category tracing\n */\nexport const setTracerEnabled: (enabled: boolean) => Layer<never> = (enabled: boolean) =>\n  scopedDiscard(\n    fiberRuntime.fiberRefLocallyScoped(core.currentTracerEnabled, enabled)\n  )\n\n/**\n * @since 2.0.0\n * @category tracing\n */\nexport const setTracerTiming: (enabled: boolean) => Layer<never> = (enabled: boolean) =>\n  scopedDiscard(\n    fiberRuntime.fiberRefLocallyScoped(core.currentTracerTimingEnabled, enabled)\n  )\n\n/**\n * @since 2.0.0\n * @category logging\n */\nexport const setUnhandledErrorLogLevel: (level: Option.Option<LogLevel>) => Layer<never> = (\n  level: Option.Option<LogLevel>\n): Layer<never> =>\n  scopedDiscard(\n    fiberRuntime.fiberRefLocallyScoped(core.currentUnhandledErrorLogLevel, level)\n  )\n\n/**\n * @since 3.17.0\n * @category logging\n */\nexport const setVersionMismatchErrorLogLevel: (level: Option.Option<LogLevel>) => Layer<never> = (\n  level: Option.Option<LogLevel>\n): Layer<never> =>\n  scopedDiscard(\n    fiberRuntime.fiberRefLocallyScoped(core.currentVersionMismatchErrorLogLevel, level)\n  )\n\n/**\n * @since 2.0.0\n * @category tracing\n */\nexport const withSpan: {\n  (\n    name: string,\n    options?: Tracer.SpanOptions & {\n      readonly onEnd?:\n        | ((span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>)\n        | undefined\n    }\n  ): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, Exclude<R, Tracer.ParentSpan>>\n  <A, E, R>(\n    self: Layer<A, E, R>,\n    name: string,\n    options?: Tracer.SpanOptions & {\n      readonly onEnd?:\n        | ((span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>)\n        | undefined\n    }\n  ): Layer<A, E, Exclude<R, Tracer.ParentSpan>>\n} = internal.withSpan\n\n/**\n * @since 2.0.0\n * @category tracing\n */\nexport const withParentSpan: {\n  (span: Tracer.AnySpan): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, Exclude<R, Tracer.ParentSpan>>\n  <A, E, R>(self: Layer<A, E, R>, span: Tracer.AnySpan): Layer<A, E, Exclude<R, Tracer.ParentSpan>>\n} = internal.withParentSpan\n\n// -----------------------------------------------------------------------------\n// memo map\n// -----------------------------------------------------------------------------\n\n/**\n * Constructs a `MemoMap` that can be used to build additional layers.\n *\n * @since 2.0.0\n * @category memo map\n */\nexport const makeMemoMap: Effect.Effect<MemoMap> = internal.makeMemoMap\n\n/**\n * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize\n * the layer construction.\n *\n * @since 2.0.0\n * @category memo map\n */\nexport const buildWithMemoMap: {\n  (\n    memoMap: MemoMap,\n    scope: Scope.Scope\n  ): <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Effect.Effect<Context.Context<ROut>, E, RIn>\n  <RIn, E, ROut>(\n    self: Layer<ROut, E, RIn>,\n    memoMap: MemoMap,\n    scope: Scope.Scope\n  ): Effect.Effect<Context.Context<ROut>, E, RIn>\n} = internal.buildWithMemoMap\n\n/**\n * Updates a service in the context with a new implementation.\n *\n * **Details**\n *\n * This function modifies the existing implementation of a service in the\n * context. It retrieves the current service, applies the provided\n * transformation function `f`, and replaces the old service with the\n * transformed one.\n *\n * **When to Use**\n *\n * This is useful for adapting or extending a service's behavior during the\n * creation of a layer.\n *\n * @since 3.13.0\n * @category utils\n */\nexport const updateService = dual<\n  <I, A>(\n    tag: Context.Tag<I, A>,\n    f: (a: A) => A\n  ) => <A1, E1, R1>(layer: Layer<A1, E1, R1>) => Layer<A1, E1, I | R1>,\n  <A1, E1, R1, I, A>(\n    layer: Layer<A1, E1, R1>,\n    tag: Context.Tag<I, A>,\n    f: (a: A) => A\n  ) => Layer<A1, E1, I | R1>\n>(3, (layer, tag, f) =>\n  provide(\n    layer,\n    map(context(), (c) => Context.add(c, tag, f(Context.unsafeGet(c, tag))))\n  ))\n\n// -----------------------------------------------------------------------------\n// Type constraints\n// -----------------------------------------------------------------------------\n\n/**\n * A no-op type constraint that enforces the success channel of a Layer conforms to\n * the specified success type `ROut`.\n *\n * @example\n * import { Layer } from \"effect\"\n *\n * // Ensure that the layer produces the expected services.\n * const program = Layer.succeed(MyService, new MyServiceImpl()).pipe(Layer.ensureSuccessType<MyService>())\n *\n * @since 3.20.0\n * @category Type constraints\n */\nexport const ensureSuccessType =\n  <ROut>() => <ROut2 extends ROut, E, RIn>(layer: Layer<ROut2, E, RIn>): Layer<ROut2, E, RIn> => layer\n\n/**\n * A no-op type constraint that enforces the error channel of a Layer conforms to\n * the specified error type `E`.\n *\n * @example\n * import { Layer } from \"effect\"\n *\n * // Ensure that the layer does not expose any unhandled errors.\n * const program = Layer.succeed(MyService, new MyServiceImpl()).pipe(Layer.ensureErrorType<never>())\n *\n * @since 3.20.0\n * @category Type constraints\n */\nexport const ensureErrorType = <E>() => <ROut, E2 extends E, RIn>(layer: Layer<ROut, E2, RIn>): Layer<ROut, E2, RIn> =>\n  layer\n\n/**\n * A no-op type constraint that enforces the requirements channel of a Layer conforms to\n * the specified requirements type `RIn`.\n *\n * @example\n * import { Layer } from \"effect\"\n *\n * // Ensure that the layer does not have any requirements.\n * const program = Layer.succeed(MyService, new MyServiceImpl()).pipe(Layer.ensureRequirementsType<never>())\n *\n * @since 3.20.0\n * @category Type constraints\n */\nexport const ensureRequirementsType =\n  <RIn>() => <ROut, E, RIn2 extends RIn>(layer: Layer<ROut, E, RIn2>): Layer<ROut, E, RIn2> => layer\n"
  },
  {
    "path": "packages/effect/src/LayerMap.ts",
    "content": "/**\n * @since 3.14.0\n * @experimental\n */\nimport * as Context from \"./Context.js\"\nimport type * as Duration from \"./Duration.js\"\nimport * as Effect from \"./Effect.js\"\nimport * as FiberRefsPatch from \"./FiberRefsPatch.js\"\nimport { identity } from \"./Function.js\"\nimport * as core from \"./internal/core.js\"\nimport * as Layer from \"./Layer.js\"\nimport * as RcMap from \"./RcMap.js\"\nimport * as Runtime from \"./Runtime.js\"\nimport * as Scope from \"./Scope.js\"\nimport type { Mutable, NoExcessProperties } from \"./Types.js\"\n\n/**\n * @since 3.14.0\n * @category Symbols\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/LayerMap\")\n\n/**\n * @since 3.14.0\n * @category Symbols\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 3.14.0\n * @category Models\n * @experimental\n */\nexport interface LayerMap<in K, in out I, out E = never> {\n  readonly [TypeId]: TypeId\n\n  /**\n   * The internal RcMap that stores the resources.\n   */\n  readonly rcMap: RcMap.RcMap<K, {\n    readonly layer: Layer.Layer<I, E>\n    readonly runtimeEffect: Effect.Effect<Runtime.Runtime<I>, E, Scope.Scope>\n  }, E>\n\n  /**\n   * Retrieves a Layer for the resources associated with the key.\n   */\n  get(key: K): Layer.Layer<I, E>\n\n  /**\n   * Retrieves a Runtime for the resources associated with the key.\n   */\n  runtime(key: K): Effect.Effect<Runtime.Runtime<I>, E, Scope.Scope>\n\n  /**\n   * Invalidates the resource associated with the key.\n   */\n  invalidate(key: K): Effect.Effect<void>\n}\n\n/**\n * @since 3.14.0\n * @category Constructors\n * @experimental\n *\n * A `LayerMap` allows you to create a map of Layer's that can be used to\n * dynamically access resources based on a key.\n *\n * ```ts\n * import { NodeRuntime } from \"@effect/platform-node\"\n * import { Context, Effect, FiberRef, Layer, LayerMap } from \"effect\"\n *\n * class Greeter extends Context.Tag(\"Greeter\")<Greeter, {\n *   greet: Effect.Effect<string>\n * }>() {}\n *\n * // create a service that wraps a LayerMap\n * class GreeterMap extends LayerMap.Service<GreeterMap>()(\"GreeterMap\", {\n *   // define the lookup function for the layer map\n *   //\n *   // The returned Layer will be used to provide the Greeter service for the\n *   // given name.\n *   lookup: (name: string) =>\n *     Layer.succeed(Greeter, {\n *       greet: Effect.succeed(`Hello, ${name}!`)\n *     }).pipe(\n *       Layer.merge(Layer.locallyScoped(FiberRef.currentConcurrency, 123))\n *     ),\n *\n *   // If a layer is not used for a certain amount of time, it can be removed\n *   idleTimeToLive: \"5 seconds\",\n *\n *   // Supply the dependencies for the layers in the LayerMap\n *   dependencies: []\n * }) {}\n *\n * // usage\n * const program: Effect.Effect<void, never, GreeterMap> = Effect.gen(function*() {\n *   // access and use the Greeter service\n *   const greeter = yield* Greeter\n *   yield* Effect.log(yield* greeter.greet)\n * }).pipe(\n *   // use the GreeterMap service to provide a variant of the Greeter service\n *   Effect.provide(GreeterMap.get(\"John\"))\n * )\n *\n * // run the program\n * program.pipe(\n *   Effect.provide(GreeterMap.Default),\n *   NodeRuntime.runMain\n * )\n * ```\n */\nexport const make: <\n  K,\n  L extends Layer.Layer<any, any, any>,\n  PreloadKeys extends Iterable<K> | undefined = undefined\n>(\n  lookup: (key: K) => L,\n  options?: {\n    readonly idleTimeToLive?: Duration.DurationInput | undefined\n    readonly preloadKeys?: PreloadKeys\n  } | undefined\n) => Effect.Effect<\n  LayerMap<\n    K,\n    L extends Layer.Layer<infer _A, infer _E, infer _R> ? _A : never,\n    L extends Layer.Layer<infer _A, infer _E, infer _R> ? _E : never\n  >,\n  PreloadKeys extends undefined ? never : L extends Layer.Layer<infer _A, infer _E, infer _R> ? _E : never,\n  Scope.Scope | (L extends Layer.Layer<infer _A, infer _E, infer _R> ? _R : never)\n> = Effect.fnUntraced(function*<I, K, EL, RL>(\n  lookup: (key: K) => Layer.Layer<I, EL, RL>,\n  options?: {\n    readonly idleTimeToLive?: Duration.DurationInput | undefined\n    readonly preloadKeys?: Iterable<K> | undefined\n  } | undefined\n) {\n  const context = yield* Effect.context<never>()\n\n  // If we are inside another layer build, use the current memo map,\n  // otherwise create a new one.\n  const memoMap = context.unsafeMap.has(Layer.CurrentMemoMap.key)\n    ? Context.get(context, Layer.CurrentMemoMap)\n    : yield* Layer.makeMemoMap\n\n  const rcMap = yield* RcMap.make({\n    lookup: (key: K) =>\n      Effect.scopeWith((scope) => Effect.diffFiberRefs(Layer.buildWithMemoMap(lookup(key), memoMap, scope))).pipe(\n        Effect.map(([patch, context]) => ({\n          layer: Layer.scopedContext(\n            core.withFiberRuntime<Context.Context<I>, any, Scope.Scope>((fiber) => {\n              const scope = Context.unsafeGet(fiber.currentContext, Scope.Scope)\n              const oldRefs = fiber.getFiberRefs()\n              const newRefs = FiberRefsPatch.patch(patch, fiber.id(), oldRefs)\n              const revert = FiberRefsPatch.diff(newRefs, oldRefs)\n              fiber.setFiberRefs(newRefs)\n              return Effect.as(\n                Scope.addFinalizerExit(scope, () => {\n                  fiber.setFiberRefs(FiberRefsPatch.patch(revert, fiber.id(), fiber.getFiberRefs()))\n                  return Effect.void\n                }),\n                context\n              )\n            })\n          ),\n          runtimeEffect: Effect.withFiberRuntime<Runtime.Runtime<I>, any, Scope.Scope>((fiber) => {\n            const fiberRefs = FiberRefsPatch.patch(patch, fiber.id(), fiber.getFiberRefs())\n            return Effect.succeed(Runtime.make({\n              context,\n              fiberRefs,\n              runtimeFlags: Runtime.defaultRuntime.runtimeFlags\n            }))\n          })\n        } as const))\n      ),\n    idleTimeToLive: options?.idleTimeToLive\n  })\n\n  if (options?.preloadKeys) {\n    for (const key of options.preloadKeys) {\n      yield* (RcMap.get(rcMap, key) as Effect.Effect<any, EL, RL | Scope.Scope>)\n    }\n  }\n\n  return identity<LayerMap<K, Exclude<I, Scope.Scope>, any>>({\n    [TypeId]: TypeId,\n    rcMap,\n    get: (key) => Layer.unwrapScoped(Effect.map(RcMap.get(rcMap, key), ({ layer }) => layer)),\n    runtime: (key) => Effect.flatMap(RcMap.get(rcMap, key), ({ runtimeEffect }) => runtimeEffect),\n    invalidate: (key) => RcMap.invalidate(rcMap, key)\n  })\n})\n\n/**\n * @since 3.14.0\n * @category Constructors\n * @experimental\n */\nexport const fromRecord = <\n  const Layers extends Record<string, Layer.Layer<any, any, any>>,\n  const Preload extends boolean = false\n>(\n  layers: Layers,\n  options?: {\n    readonly idleTimeToLive?: Duration.DurationInput | undefined\n    readonly preload?: Preload | undefined\n  } | undefined\n): Effect.Effect<\n  LayerMap<\n    keyof Layers,\n    Layers[keyof Layers] extends Layer.Layer<infer _A, infer _E, infer _R> ? _A : never,\n    Preload extends true ? never : Layers[keyof Layers] extends Layer.Layer<infer _A, infer _E, infer _R> ? _E : never\n  >,\n  Preload extends true ? never : Layers[keyof Layers] extends Layer.Layer<infer _A, infer _E, infer _R> ? _E : never,\n  Scope.Scope | (Layers[keyof Layers] extends Layer.Layer<infer _A, infer _E, infer _R> ? _R : never)\n> =>\n  make((key: keyof Layers) => layers[key], {\n    ...options,\n    preloadKeys: options?.preload ? Object.keys(layers) : undefined\n  }) as any\n\n/**\n * @since 3.14.0\n * @category Service\n */\nexport interface TagClass<\n  in out Self,\n  in out Id extends string,\n  in out K,\n  in out I,\n  in out E,\n  in out R,\n  in out LE,\n  in out Deps extends Layer.Layer<any, any, any>\n> extends Context.TagClass<Self, Id, LayerMap<K, I, E>> {\n  /**\n   * A default layer for the `LayerMap` service.\n   */\n  readonly Default: Layer.Layer<\n    Self,\n    (Deps extends Layer.Layer<infer _A, infer _E, infer _R> ? _E : never) | LE,\n    | Exclude<R, (Deps extends Layer.Layer<infer _A, infer _E, infer _R> ? _A : never)>\n    | (Deps extends Layer.Layer<infer _A, infer _E, infer _R> ? _R : never)\n  >\n\n  /**\n   * A default layer for the `LayerMap` service without the dependencies provided.\n   */\n  readonly DefaultWithoutDependencies: Layer.Layer<Self, LE, R>\n\n  /**\n   * Retrieves a Layer for the resources associated with the key.\n   */\n  readonly get: (key: K) => Layer.Layer<I, E, Self>\n\n  /**\n   * Retrieves a Runtime for the resources associated with the key.\n   */\n  readonly runtime: (key: K) => Effect.Effect<Runtime.Runtime<I>, E, Scope.Scope | Self>\n\n  /**\n   * Invalidates the resource associated with the key.\n   */\n  readonly invalidate: (key: K) => Effect.Effect<void, never, Self>\n}\n\n/**\n * @since 3.14.0\n * @category Service\n * @experimental\n *\n * Create a `LayerMap` service that provides a dynamic set of resources based on\n * a key.\n *\n * ```ts\n * import { NodeRuntime } from \"@effect/platform-node\"\n * import { Context, Effect, FiberRef, Layer, LayerMap } from \"effect\"\n *\n * class Greeter extends Context.Tag(\"Greeter\")<Greeter, {\n *   greet: Effect.Effect<string>\n * }>() {}\n *\n * // create a service that wraps a LayerMap\n * class GreeterMap extends LayerMap.Service<GreeterMap>()(\"GreeterMap\", {\n *   // define the lookup function for the layer map\n *   //\n *   // The returned Layer will be used to provide the Greeter service for the\n *   // given name.\n *   lookup: (name: string) =>\n *     Layer.succeed(Greeter, {\n *       greet: Effect.succeed(`Hello, ${name}!`)\n *     }).pipe(\n *       Layer.merge(Layer.locallyScoped(FiberRef.currentConcurrency, 123))\n *     ),\n *\n *   // If a layer is not used for a certain amount of time, it can be removed\n *   idleTimeToLive: \"5 seconds\",\n *\n *   // Supply the dependencies for the layers in the LayerMap\n *   dependencies: []\n * }) {}\n *\n * // usage\n * const program: Effect.Effect<void, never, GreeterMap> = Effect.gen(function*() {\n *   // access and use the Greeter service\n *   const greeter = yield* Greeter\n *   yield* Effect.log(yield* greeter.greet)\n * }).pipe(\n *   // use the GreeterMap service to provide a variant of the Greeter service\n *   Effect.provide(GreeterMap.get(\"John\"))\n * )\n *\n * // run the program\n * program.pipe(\n *   Effect.provide(GreeterMap.Default),\n *   NodeRuntime.runMain\n * )\n * ```\n */\nexport const Service = <Self>() =>\n<\n  const Id extends string,\n  Options extends\n    | NoExcessProperties<\n      {\n        readonly lookup: (key: any) => Layer.Layer<any, any, any>\n        readonly dependencies?: ReadonlyArray<Layer.Layer<any, any, any>>\n        readonly idleTimeToLive?: Duration.DurationInput | undefined\n        readonly preloadKeys?:\n          | Iterable<Options extends { readonly lookup: (key: infer K) => any } ? K : never>\n          | undefined\n      },\n      Options\n    >\n    | NoExcessProperties<{\n      readonly layers: Record<string, Layer.Layer<any, any, any>>\n      readonly dependencies?: ReadonlyArray<Layer.Layer<any, any, any>>\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n      readonly preload?: boolean\n    }, Options>\n>(\n  id: Id,\n  options: Options\n): TagClass<\n  Self,\n  Id,\n  Options extends { readonly lookup: (key: infer K) => any } ? K\n    : Options extends { readonly layers: infer Layers } ? keyof Layers\n    : never,\n  Service.Success<Options>,\n  Options extends { readonly preload: true } ? never : Service.Error<Options>,\n  Service.Context<Options>,\n  Options extends { readonly preload: true } ? Service.Error<Options>\n    : Options extends { readonly preloadKey: Iterable<any> } ? Service.Error<Options>\n    : never,\n  Options extends { readonly dependencies: ReadonlyArray<any> } ? Options[\"dependencies\"][number] : never\n> => {\n  const Err = globalThis.Error as any\n  const limit = Err.stackTraceLimit\n  Err.stackTraceLimit = 2\n  const creationError = new Err()\n  Err.stackTraceLimit = limit\n\n  function TagClass() {}\n  const TagClass_ = TagClass as any as Mutable<TagClass<Self, Id, string, any, any, any, any, any>>\n  Object.setPrototypeOf(TagClass, Object.getPrototypeOf(Context.GenericTag<Self, any>(id)))\n  TagClass.key = id\n  Object.defineProperty(TagClass, \"stack\", {\n    get() {\n      return creationError.stack\n    }\n  })\n\n  TagClass_.DefaultWithoutDependencies = Layer.scoped(\n    TagClass_,\n    \"lookup\" in options\n      ? make(options.lookup, options)\n      : fromRecord(options.layers as any, options)\n  )\n  TagClass_.Default = options.dependencies && options.dependencies.length > 0 ?\n    Layer.provide(TagClass_.DefaultWithoutDependencies, options.dependencies as any) :\n    TagClass_.DefaultWithoutDependencies\n\n  TagClass_.get = (key: string) => Layer.unwrapScoped(Effect.map(TagClass_, (layerMap) => layerMap.get(key)))\n  TagClass_.runtime = (key: string) => Effect.flatMap(TagClass_, (layerMap) => layerMap.runtime(key))\n  TagClass_.invalidate = (key: string) => Effect.flatMap(TagClass_, (layerMap) => layerMap.invalidate(key))\n\n  return TagClass as any\n}\n\n/**\n * @since 3.14.0\n * @category Service\n * @experimental\n */\nexport declare namespace Service {\n  /**\n   * @since 3.14.0\n   * @category Service\n   * @experimental\n   */\n  export type Key<Options> = Options extends { readonly lookup: (key: infer K) => any } ? K\n    : Options extends { readonly layers: infer Layers } ? keyof Layers\n    : never\n\n  /**\n   * @since 3.14.0\n   * @category Service\n   * @experimental\n   */\n  export type Layers<Options> = Options extends { readonly lookup: (key: infer _K) => infer Layers } ? Layers\n    : Options extends { readonly layers: infer Layers } ? Layers[keyof Layers]\n    : never\n\n  /**\n   * @since 3.14.0\n   * @category Service\n   * @experimental\n   */\n  export type Success<Options> = Layers<Options> extends Layer.Layer<infer _A, infer _E, infer _R> ? _A : never\n\n  /**\n   * @since 3.14.0\n   * @category Service\n   * @experimental\n   */\n  export type Error<Options> = Layers<Options> extends Layer.Layer<infer _A, infer _E, infer _R> ? _E : never\n\n  /**\n   * @since 3.14.0\n   * @category Service\n   * @experimental\n   */\n  export type Context<Options> = Layers<Options> extends Layer.Layer<infer _A, infer _E, infer _R> ? _R : never\n}\n"
  },
  {
    "path": "packages/effect/src/List.ts",
    "content": "/**\n * A data type for immutable linked lists representing ordered collections of elements of type `A`.\n *\n * This data type is optimal for last-in-first-out (LIFO), stack-like access patterns. If you need another access pattern, for example, random access or FIFO, consider using a collection more suited to this than `List`.\n *\n * **Performance**\n *\n * - Time: `List` has `O(1)` prepend and head/tail access. Most other operations are `O(n)` on the number of elements in the list. This includes the index-based lookup of elements, `length`, `append` and `reverse`.\n * - Space: `List` implements structural sharing of the tail list. This means that many operations are either zero- or constant-memory cost.\n *\n * @since 2.0.0\n */\n\n/**\n * This file is ported from\n *\n * Scala (https://www.scala-lang.org)\n *\n * Copyright EPFL and Lightbend, Inc.\n *\n * Licensed under Apache License 2.0\n * (http://www.apache.org/licenses/LICENSE-2.0).\n */\nimport * as Arr from \"./Array.js\"\nimport * as Chunk from \"./Chunk.js\"\nimport * as Either from \"./Either.js\"\nimport * as Equal from \"./Equal.js\"\nimport * as Equivalence from \"./Equivalence.js\"\nimport { dual, identity, unsafeCoerce } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport { format, type Inspectable, NodeInspectSymbol, toJSON } from \"./Inspectable.js\"\nimport type { nonEmpty, NonEmptyIterable } from \"./NonEmptyIterable.js\"\nimport * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\nimport { hasProperty, type Predicate, type Refinement } from \"./Predicate.js\"\nimport type { NoInfer } from \"./Types.js\"\n\n/**\n * Represents an immutable linked list of elements of type `A`.\n *\n * A `List` is optimal for last-in-first-out (LIFO), stack-like access patterns.\n * If you need another access pattern, for example, random access or FIFO,\n * consider using a collection more suited for that other than `List`.\n *\n * @since 2.0.0\n * @category models\n */\nexport type List<A> = Cons<A> | Nil<A>\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/List\")\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Nil<out A> extends Iterable<A>, Equal.Equal, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n  readonly _tag: \"Nil\"\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Cons<out A> extends NonEmptyIterable<A>, Equal.Equal, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n  readonly _tag: \"Cons\"\n  readonly head: A\n  readonly tail: List<A>\n}\n\n/**\n * Converts the specified `List` to an `Array`.\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const toArray = <A>(self: List<A>): Array<A> => Arr.fromIterable(self)\n\n/**\n * @category equivalence\n * @since 2.0.0\n */\nexport const getEquivalence = <A>(isEquivalent: Equivalence.Equivalence<A>): Equivalence.Equivalence<List<A>> =>\n  Equivalence.mapInput(Arr.getEquivalence(isEquivalent), toArray<A>)\n\nconst _equivalence = getEquivalence(Equal.equals)\n\nconst ConsProto: Omit<Cons<unknown>, \"head\" | \"tail\" | typeof nonEmpty> = {\n  [TypeId]: TypeId,\n  _tag: \"Cons\",\n  toString(this: Cons<unknown>) {\n    return format(this.toJSON())\n  },\n  toJSON(this: Cons<unknown>) {\n    return {\n      _id: \"List\",\n      _tag: \"Cons\",\n      values: toArray(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  [Equal.symbol](this: Cons<unknown>, that: unknown): boolean {\n    return isList(that) &&\n      this._tag === that._tag &&\n      _equivalence(this, that)\n  },\n  [Hash.symbol](this: Cons<unknown>): number {\n    return Hash.cached(this, Hash.array(toArray(this)))\n  },\n  [Symbol.iterator](this: Cons<unknown>): Iterator<unknown> {\n    let done = false\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    let self: List<unknown> = this\n    return {\n      next() {\n        if (done) {\n          return this.return!()\n        }\n        if (self._tag === \"Nil\") {\n          done = true\n          return this.return!()\n        }\n        const value: unknown = self.head\n        self = self.tail\n        return { done, value }\n      },\n      return(value?: unknown) {\n        if (!done) {\n          done = true\n        }\n        return { done: true, value }\n      }\n    }\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\ninterface MutableCons<A> extends Cons<A> {\n  head: A\n  tail: List<A>\n}\n\nconst makeCons = <A>(head: A, tail: List<A>): MutableCons<A> => {\n  const cons = Object.create(ConsProto)\n  cons.head = head\n  cons.tail = tail\n  return cons\n}\n\nconst NilHash = Hash.string(\"Nil\")\nconst NilProto: Nil<unknown> = {\n  [TypeId]: TypeId,\n  _tag: \"Nil\",\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"List\",\n      _tag: \"Nil\"\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  [Hash.symbol](): number {\n    return NilHash\n  },\n  [Equal.symbol](that: unknown): boolean {\n    return isList(that) && this._tag === that._tag\n  },\n  [Symbol.iterator](): Iterator<unknown> {\n    return {\n      next() {\n        return { done: true, value: undefined }\n      }\n    }\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n} as const\n\nconst _Nil = Object.create(NilProto) as Nil<never>\n\n/**\n * Returns `true` if the specified value is a `List`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isList: {\n  <A>(u: Iterable<A>): u is List<A>\n  (u: unknown): u is List<unknown>\n} = (u: unknown): u is List<unknown> => hasProperty(u, TypeId)\n\n/**\n * Returns `true` if the specified value is a `List.Nil<A>`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isNil = <A>(self: List<A>): self is Nil<A> => self._tag === \"Nil\"\n\n/**\n * Returns `true` if the specified value is a `List.Cons<A>`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isCons = <A>(self: List<A>): self is Cons<A> => self._tag === \"Cons\"\n\n/**\n * Returns the number of elements contained in the specified `List`\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size = <A>(self: List<A>): number => {\n  let these = self\n  let len = 0\n  while (!isNil(these)) {\n    len += 1\n    these = these.tail\n  }\n  return len\n}\n\n/**\n * Constructs a new empty `List<A>`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const nil = <A = never>(): List<A> => _Nil\n\n/**\n * Constructs a new `List.Cons<A>` from the specified `head` and `tail` values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const cons = <A>(head: A, tail: List<A>): Cons<A> => makeCons(head, tail)\n\n/**\n * Constructs a new empty `List<A>`.\n *\n * Alias of {@link nil}.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty = nil\n\n/**\n * Constructs a new `List<A>` from the specified value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const of = <A>(value: A): Cons<A> => makeCons(value, _Nil)\n\n/**\n * Creates a new `List` from an iterable collection of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable = <A>(prefix: Iterable<A>): List<A> => {\n  const iterator = prefix[Symbol.iterator]()\n  let next: IteratorResult<A>\n  if ((next = iterator.next()) && !next.done) {\n    const result = makeCons(next.value, _Nil)\n    let curr = result\n    while ((next = iterator.next()) && !next.done) {\n      const temp = makeCons(next.value, _Nil)\n      curr.tail = temp\n      curr = temp\n    }\n    return result\n  } else {\n    return _Nil\n  }\n}\n\n/**\n * Constructs a new `List<A>` from the specified values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make = <Elements extends readonly [any, ...Array<any>]>(\n  ...elements: Elements\n): Cons<Elements[number]> => fromIterable(elements) as any\n\n/**\n * Appends the specified element to the end of the `List`, creating a new `Cons`.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const append: {\n  <B>(element: B): <A>(self: List<A>) => Cons<A | B>\n  <A, B>(self: List<A>, element: B): Cons<A | B>\n} = dual(2, <A, B>(self: List<A>, element: B): Cons<A | B> => appendAll(self, of(element)))\n\n/**\n * Concatenates two lists, combining their elements.\n * If either list is non-empty, the result is also a non-empty list.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { List } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   List.make(1, 2).pipe(List.appendAll(List.make(\"a\", \"b\")), List.toArray),\n *   [1, 2, \"a\", \"b\"]\n * )\n * ```\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const appendAll: {\n  <S extends List<any>, T extends List<any>>(that: T): (self: S) => List.OrNonEmpty<S, T, List.Infer<S> | List.Infer<T>>\n  <A, B>(self: List<A>, that: Cons<B>): Cons<A | B>\n  <A, B>(self: Cons<A>, that: List<B>): Cons<A | B>\n  <A, B>(self: List<A>, that: List<B>): List<A | B>\n} = dual(2, <A, B>(self: List<A>, that: List<B>): List<A | B> => prependAll(that, self))\n\n/**\n * Prepends the specified element to the beginning of the list.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const prepend: {\n  <B>(element: B): <A>(self: List<A>) => Cons<A | B>\n  <A, B>(self: List<A>, element: B): Cons<A | B>\n} = dual(2, <A, B>(self: List<A>, element: B): Cons<A | B> => cons<A | B>(element, self))\n\n/**\n * Prepends the specified prefix list to the beginning of the specified list.\n * If either list is non-empty, the result is also a non-empty list.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { List } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   List.make(1, 2).pipe(List.prependAll(List.make(\"a\", \"b\")), List.toArray),\n *   [\"a\", \"b\", 1, 2]\n * )\n * ```\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const prependAll: {\n  <S extends List<any>, T extends List<any>>(that: T): (self: S) => List.OrNonEmpty<S, T, List.Infer<S> | List.Infer<T>>\n  <A, B>(self: List<A>, that: Cons<B>): Cons<A | B>\n  <A, B>(self: Cons<A>, that: List<B>): Cons<A | B>\n  <A, B>(self: List<A>, that: List<B>): List<A | B>\n} = dual(2, <A, B>(self: List<A>, prefix: List<B>): List<A | B> => {\n  if (isNil(self)) {\n    return prefix\n  } else if (isNil(prefix)) {\n    return self\n  } else {\n    const result = makeCons<A | B>(prefix.head, self)\n    let curr = result\n    let that = prefix.tail\n    while (!isNil(that)) {\n      const temp = makeCons<A | B>(that.head, self)\n      curr.tail = temp\n      curr = temp\n      that = that.tail\n    }\n    return result\n  }\n})\n\n/**\n * Prepends the specified prefix list (in reverse order) to the beginning of the\n * specified list.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const prependAllReversed: {\n  <B>(prefix: List<B>): <A>(self: List<A>) => List<A | B>\n  <A, B>(self: List<A>, prefix: List<B>): List<A | B>\n} = dual(2, <A, B>(self: List<A>, prefix: List<B>): List<A | B> => {\n  let out: List<A | B> = self\n  let pres = prefix\n  while (isCons(pres)) {\n    out = makeCons(pres.head, out)\n    pres = pres.tail\n  }\n  return out\n})\n\n/**\n * Drops the first `n` elements from the specified list.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const drop: {\n  (n: number): <A>(self: List<A>) => List<A>\n  <A>(self: List<A>, n: number): List<A>\n} = dual(2, <A>(self: List<A>, n: number): List<A> => {\n  if (n <= 0) {\n    return self\n  }\n  if (n >= size(self)) {\n    return _Nil\n  }\n  let these = self\n  let i = 0\n  while (!isNil(these) && i < n) {\n    these = these.tail\n    i += 1\n  }\n  return these\n})\n\n/**\n * Check if a predicate holds true for every `List` element.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const every: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: List<A>) => self is List<B>\n  <A>(predicate: Predicate<A>): (self: List<A>) => boolean\n  <A, B extends A>(self: List<A>, refinement: Refinement<A, B>): self is List<B>\n  <A>(self: List<A>, predicate: Predicate<A>): boolean\n} = dual(2, <A, B extends A>(self: List<A>, refinement: Refinement<A, B>): self is List<B> => {\n  for (const a of self) {\n    if (!refinement(a)) {\n      return false\n    }\n  }\n  return true\n})\n\n/**\n * Check if a predicate holds true for some `List` element.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const some: {\n  <A>(predicate: Predicate<NoInfer<A>>): (self: List<A>) => self is Cons<A>\n  <A>(self: List<A>, predicate: Predicate<A>): self is Cons<A>\n} = dual(2, <A>(self: List<A>, predicate: Predicate<A>): self is Cons<A> => {\n  let these = self\n  while (!isNil(these)) {\n    if (predicate(these.head)) {\n      return true\n    }\n    these = these.tail\n  }\n  return false\n})\n\n/**\n * Filters a list using the specified predicate.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const filter: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: List<A>) => List<B>\n  <A>(predicate: Predicate<NoInfer<A>>): (self: List<A>) => List<A>\n  <A, B extends A>(self: List<A>, refinement: Refinement<A, B>): List<B>\n  <A>(self: List<A>, predicate: Predicate<A>): List<A>\n} = dual(2, <A>(self: List<A>, predicate: Predicate<A>): List<A> => noneIn(self, predicate, false))\n\n// everything seen so far is not included\nconst noneIn = <A>(\n  self: List<A>,\n  predicate: Predicate<A>,\n  isFlipped: boolean\n): List<A> => {\n  while (true) {\n    if (isNil(self)) {\n      return _Nil\n    } else {\n      if (predicate(self.head) !== isFlipped) {\n        return allIn(self, self.tail, predicate, isFlipped)\n      } else {\n        self = self.tail\n      }\n    }\n  }\n}\n\n// everything from 'start' is included, if everything from this point is in we can return the origin\n// start otherwise if we discover an element that is out we must create a new partial list.\nconst allIn = <A>(\n  start: List<A>,\n  remaining: List<A>,\n  predicate: Predicate<A>,\n  isFlipped: boolean\n): List<A> => {\n  while (true) {\n    if (isNil(remaining)) {\n      return start\n    } else {\n      if (predicate(remaining.head) !== isFlipped) {\n        remaining = remaining.tail\n      } else {\n        return partialFill(start, remaining, predicate, isFlipped)\n      }\n    }\n  }\n}\n\n// we have seen elements that should be included then one that should be excluded, start building\nconst partialFill = <A>(\n  origStart: List<A>,\n  firstMiss: List<A>,\n  predicate: Predicate<A>,\n  isFlipped: boolean\n): List<A> => {\n  const newHead = makeCons<A>(unsafeHead(origStart)!, _Nil)\n  let toProcess = unsafeTail(origStart)! as Cons<A>\n  let currentLast = newHead\n\n  // we know that all elements are :: until at least firstMiss.tail\n  while (!(toProcess === firstMiss)) {\n    const newElem = makeCons(unsafeHead(toProcess)!, _Nil)\n    currentLast.tail = newElem\n    currentLast = unsafeCoerce(newElem)\n    toProcess = unsafeCoerce(toProcess.tail)\n  }\n\n  // at this point newHead points to a list which is a duplicate of all the 'in' elements up to the first miss.\n  // currentLast is the last element in that list.\n\n  // now we are going to try and share as much of the tail as we can, only moving elements across when we have to.\n  let next = firstMiss.tail\n  let nextToCopy: Cons<A> = unsafeCoerce(next) // the next element we would need to copy to our list if we cant share.\n  while (!isNil(next)) {\n    // generally recommended is next.isNonEmpty but this incurs an extra method call.\n    const head = unsafeHead(next)!\n    if (predicate(head) !== isFlipped) {\n      next = next.tail\n    } else {\n      // its not a match - do we have outstanding elements?\n      while (!(nextToCopy === next)) {\n        const newElem = makeCons(unsafeHead(nextToCopy)!, _Nil)\n        currentLast.tail = newElem\n        currentLast = newElem\n        nextToCopy = unsafeCoerce(nextToCopy.tail)\n      }\n      nextToCopy = unsafeCoerce(next.tail)\n      next = next.tail\n    }\n  }\n\n  // we have remaining elements - they are unchanged attach them to the end\n  if (!isNil(nextToCopy)) {\n    currentLast.tail = nextToCopy\n  }\n  return newHead\n}\n\n/**\n * Filters and maps a list using the specified partial function. The resulting\n * list may be smaller than the input list due to the possibility of the partial\n * function not being defined for some elements.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const filterMap: {\n  <A, B>(f: (a: A) => Option.Option<B>): (self: List<A>) => List<B>\n  <A, B>(self: List<A>, f: (a: A) => Option.Option<B>): List<B>\n} = dual(2, <A, B>(self: List<A>, f: (a: A) => Option.Option<B>): List<B> => {\n  const bs: Array<B> = []\n  for (const a of self) {\n    const oa = f(a)\n    if (Option.isSome(oa)) {\n      bs.push(oa.value)\n    }\n  }\n  return fromIterable(bs)\n})\n\n/**\n * Removes all `None` values from the specified list.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const compact = <A>(self: List<Option.Option<A>>): List<A> => filterMap(self, identity)\n\n/**\n * Returns the first element that satisfies the specified\n * predicate, or `None` if no such element exists.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findFirst: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: List<A>) => Option.Option<B>\n  <A>(predicate: Predicate<NoInfer<A>>): (self: List<A>) => Option.Option<A>\n  <A, B extends A>(self: List<A>, refinement: Refinement<A, B>): Option.Option<B>\n  <A>(self: List<A>, predicate: Predicate<A>): Option.Option<A>\n} = dual(2, <A>(self: List<A>, predicate: Predicate<A>): Option.Option<A> => {\n  let these = self\n  while (!isNil(these)) {\n    if (predicate(these.head)) {\n      return Option.some(these.head)\n    }\n    these = these.tail\n  }\n  return Option.none()\n})\n\n/**\n * Applies a function to each element in a list and returns a new list containing the concatenated mapped elements.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMap: {\n  <S extends List<any>, T extends List<any>>(\n    f: (a: List.Infer<S>, i: number) => T\n  ): (self: S) => List.AndNonEmpty<S, T, List.Infer<T>>\n  <A, B>(self: Cons<A>, f: (a: A, i: number) => Cons<B>): Cons<B>\n  <A, B>(self: List<A>, f: (a: A, i: number) => List<B>): List<B>\n} = dual(2, <A, B>(self: List<A>, f: (a: A) => List<B>): List<B> => {\n  let rest = self\n  let head: MutableCons<B> | undefined = undefined\n  let tail: MutableCons<B> | undefined = undefined\n  while (!isNil(rest)) {\n    let bs = f(rest.head)\n    while (!isNil(bs)) {\n      const next = makeCons(bs.head, _Nil)\n      if (tail === undefined) {\n        head = next\n      } else {\n        tail.tail = next\n      }\n      tail = next\n      bs = bs.tail\n    }\n    rest = rest.tail\n  }\n  if (head === undefined) {\n    return _Nil\n  }\n  return head\n})\n\n/**\n * Applies the specified function to each element of the `List`.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const forEach: {\n  <A, B>(f: (a: A) => B): (self: List<A>) => void\n  <A, B>(self: List<A>, f: (a: A) => B): void\n} = dual(2, <A, B>(self: List<A>, f: (a: A) => B): void => {\n  let these = self\n  while (!isNil(these)) {\n    f(these.head)\n    these = these.tail\n  }\n})\n\n/**\n * Returns the first element of the specified list, or `None` if the list is\n * empty.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const head = <A>(self: List<A>): Option.Option<A> => isNil(self) ? Option.none() : Option.some(self.head)\n\n/**\n * Returns the last element of the specified list, or `None` if the list is\n * empty.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const last = <A>(self: List<A>): Option.Option<A> => isNil(self) ? Option.none() : Option.some(unsafeLast(self)!)\n\n/**\n * @since 2.0.0\n */\nexport declare namespace List {\n  /**\n   * @since 2.0.0\n   */\n  export type Infer<S extends List<any>> = S extends List<infer A> ? A : never\n\n  /**\n   * @since 2.0.0\n   */\n  export type With<S extends List<any>, A> = S extends Cons<any> ? Cons<A> : List<A>\n\n  /**\n   * @since 2.0.0\n   */\n  export type OrNonEmpty<S extends List<any>, T extends List<any>, A> = S extends Cons<any> ? Cons<A>\n    : T extends Cons<any> ? Cons<A>\n    : List<A>\n\n  /**\n   * @since 2.0.0\n   */\n  export type AndNonEmpty<S extends List<any>, T extends List<any>, A> = S extends Cons<any> ?\n    T extends Cons<any> ? Cons<A>\n    : List<A> :\n    List<A>\n}\n\n/**\n * Applies the specified mapping function to each element of the list.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <S extends List<any>, B>(f: (a: List.Infer<S>, i: number) => B): (self: S) => List.With<S, B>\n  <S extends List<any>, B>(self: S, f: (a: List.Infer<S>, i: number) => B): List.With<S, B>\n} = dual(2, <A, B>(self: List<A>, f: (a: A, i: number) => B): List<B> => {\n  if (isNil(self)) {\n    return self as unknown as List<B>\n  } else {\n    let i = 0\n    const head = makeCons(f(self.head, i++), _Nil)\n    let nextHead = head\n    let rest = self.tail\n    while (!isNil(rest)) {\n      const next = makeCons(f(rest.head, i++), _Nil)\n      nextHead.tail = next\n      nextHead = next\n      rest = rest.tail\n    }\n    return head\n  }\n})\n\n/**\n * Partition a list into two lists, where the first list contains all elements\n * that did not satisfy the specified predicate, and the second list contains\n * all elements that did satisfy the specified predicate.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const partition: {\n  <A, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>\n  ): (self: List<A>) => [excluded: List<Exclude<A, B>>, satisfying: List<B>]\n  <A>(predicate: Predicate<NoInfer<A>>): (self: List<A>) => [excluded: List<A>, satisfying: List<A>]\n  <A, B extends A>(self: List<A>, refinement: Refinement<A, B>): [excluded: List<Exclude<A, B>>, satisfying: List<B>]\n  <A>(self: List<A>, predicate: Predicate<A>): [excluded: List<A>, satisfying: List<A>]\n} = dual(2, <A>(self: List<A>, predicate: Predicate<A>): [excluded: List<A>, satisfying: List<A>] => {\n  const left: Array<A> = []\n  const right: Array<A> = []\n  for (const a of self) {\n    if (predicate(a)) {\n      right.push(a)\n    } else {\n      left.push(a)\n    }\n  }\n  return [fromIterable(left), fromIterable(right)]\n})\n\n/**\n * Partition a list into two lists, where the first list contains all elements\n * for which the specified function returned a `Left`, and the second list\n * contains all elements for which the specified function returned a `Right`.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const partitionMap: {\n  <A, B, C>(f: (a: A) => Either.Either<C, B>): (self: List<A>) => [left: List<B>, right: List<C>]\n  <A, B, C>(self: List<A>, f: (a: A) => Either.Either<C, B>): [left: List<B>, right: List<C>]\n} = dual(2, <A, B, C>(self: List<A>, f: (a: A) => Either.Either<C, B>): [left: List<B>, right: List<C>] => {\n  const left: Array<B> = []\n  const right: Array<C> = []\n  for (const a of self) {\n    const e = f(a)\n    if (Either.isLeft(e)) {\n      left.push(e.left)\n    } else {\n      right.push(e.right)\n    }\n  }\n  return [fromIterable(left), fromIterable(right)]\n})\n\n/**\n * Folds over the elements of the list using the specified function, using the\n * specified initial value.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const reduce: {\n  <Z, A>(zero: Z, f: (b: Z, a: A) => Z): (self: List<A>) => Z\n  <A, Z>(self: List<A>, zero: Z, f: (b: Z, a: A) => Z): Z\n} = dual(3, <A, Z>(self: List<A>, zero: Z, f: (b: Z, a: A) => Z): Z => {\n  let acc = zero\n  let these = self\n  while (!isNil(these)) {\n    acc = f(acc, these.head)\n    these = these.tail\n  }\n  return acc\n})\n\n/**\n * Folds over the elements of the list using the specified function, beginning\n * with the last element of the list, using the specified initial value.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const reduceRight: {\n  <Z, A>(zero: Z, f: (accumulator: Z, value: A) => Z): (self: List<A>) => Z\n  <Z, A>(self: List<A>, zero: Z, f: (accumulator: Z, value: A) => Z): Z\n} = dual(3, <Z, A>(self: List<A>, zero: Z, f: (accumulator: Z, value: A) => Z): Z => {\n  let acc = zero\n  let these = reverse(self)\n  while (!isNil(these)) {\n    acc = f(acc, these.head)\n    these = these.tail\n  }\n  return acc\n})\n\n/**\n * Returns a new list with the elements of the specified list in reverse order.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const reverse = <A>(self: List<A>): List<A> => {\n  let result = empty<A>()\n  let these = self\n  while (!isNil(these)) {\n    result = prepend(result, these.head)\n    these = these.tail\n  }\n  return result\n}\n\n/**\n * Splits the specified list into two lists at the specified index.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const splitAt: {\n  (n: number): <A>(self: List<A>) => [beforeIndex: List<A>, fromIndex: List<A>]\n  <A>(self: List<A>, n: number): [beforeIndex: List<A>, fromIndex: List<A>]\n} = dual(2, <A>(self: List<A>, n: number): [List<A>, List<A>] => [take(self, n), drop(self, n)])\n\n/**\n * Returns the tail of the specified list, or `None` if the list is empty.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const tail = <A>(self: List<A>): Option.Option<List<A>> => isNil(self) ? Option.none() : Option.some(self.tail)\n\n/**\n * Takes the specified number of elements from the beginning of the specified\n * list.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const take: {\n  (n: number): <A>(self: List<A>) => List<A>\n  <A>(self: List<A>, n: number): List<A>\n} = dual(2, <A>(self: List<A>, n: number): List<A> => {\n  if (n <= 0) {\n    return _Nil\n  }\n  if (n >= size(self)) {\n    return self\n  }\n  let these = make(unsafeHead(self))\n  let current = unsafeTail(self)!\n  for (let i = 1; i < n; i++) {\n    these = makeCons(unsafeHead(current), these)\n    current = unsafeTail(current!)\n  }\n  return reverse(these)\n})\n\n/**\n * Converts the specified `List` to a `Chunk`.\n *\n * @since 2.0.0\n * @category conversions\n */\nexport const toChunk = <A>(self: List<A>): Chunk.Chunk<A> => Chunk.fromIterable(self)\n\nconst getExpectedListToBeNonEmptyErrorMessage = \"Expected List to be non-empty\"\n\n/**\n * Unsafely returns the first element of the specified `List`.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeHead = <A>(self: List<A>): A => {\n  if (isNil(self)) {\n    throw new Error(getExpectedListToBeNonEmptyErrorMessage)\n  }\n  return self.head\n}\n\n/**\n * Unsafely returns the last element of the specified `List`.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeLast = <A>(self: List<A>): A => {\n  if (isNil(self)) {\n    throw new Error(getExpectedListToBeNonEmptyErrorMessage)\n  }\n  let these = self\n  let scout = self.tail\n  while (!isNil(scout)) {\n    these = scout\n    scout = scout.tail\n  }\n  return these.head\n}\n\n/**\n * Unsafely returns the tail of the specified `List`.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeTail = <A>(self: List<A>): List<A> => {\n  if (isNil(self)) {\n    throw new Error(getExpectedListToBeNonEmptyErrorMessage)\n  }\n  return self.tail\n}\n"
  },
  {
    "path": "packages/effect/src/LogLevel.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport { dual, pipe } from \"./Function.js\"\nimport * as core from \"./internal/core.js\"\nimport * as number from \"./Number.js\"\nimport * as order from \"./Order.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\n\n/**\n * A `LogLevel` represents the log level associated with an individual logging\n * operation. Log levels are used both to describe the granularity (or\n * importance) of individual log statements, as well as to enable tuning\n * verbosity of log output.\n *\n * @since 2.0.0\n * @category model\n * @property ordinal - The priority of the log message. Larger values indicate higher priority.\n * @property label - A label associated with the log level.\n * @property syslog -The syslog severity level of the log level.\n */\nexport type LogLevel = All | Fatal | Error | Warning | Info | Debug | Trace | None\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport type Literal = LogLevel[\"_tag\"]\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface All extends Pipeable {\n  readonly _tag: \"All\"\n  readonly label: \"ALL\"\n  readonly syslog: 0\n  readonly ordinal: number\n}\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface Fatal extends Pipeable {\n  readonly _tag: \"Fatal\"\n  readonly label: \"FATAL\"\n  readonly syslog: 2\n  readonly ordinal: number\n}\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface Error extends Pipeable {\n  readonly _tag: \"Error\"\n  readonly label: \"ERROR\"\n  readonly syslog: 3\n  readonly ordinal: number\n}\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface Warning extends Pipeable {\n  readonly _tag: \"Warning\"\n  readonly label: \"WARN\"\n  readonly syslog: 4\n  readonly ordinal: number\n}\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface Info extends Pipeable {\n  readonly _tag: \"Info\"\n  readonly label: \"INFO\"\n  readonly syslog: 6\n  readonly ordinal: number\n}\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface Debug extends Pipeable {\n  readonly _tag: \"Debug\"\n  readonly label: \"DEBUG\"\n  readonly syslog: 7\n  readonly ordinal: number\n}\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface Trace extends Pipeable {\n  readonly _tag: \"Trace\"\n  readonly label: \"TRACE\"\n  readonly syslog: 7\n  readonly ordinal: number\n}\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface None extends Pipeable {\n  readonly _tag: \"None\"\n  readonly label: \"OFF\"\n  readonly syslog: 7\n  readonly ordinal: number\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const All: LogLevel = core.logLevelAll\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Fatal: LogLevel = core.logLevelFatal\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Error: LogLevel = core.logLevelError\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Warning: LogLevel = core.logLevelWarning\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Info: LogLevel = core.logLevelInfo\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Debug: LogLevel = core.logLevelDebug\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Trace: LogLevel = core.logLevelTrace\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const None: LogLevel = core.logLevelNone\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const allLevels = core.allLogLevels\n\n/**\n * Temporarily sets a `LogLevel` for an `Effect` workflow.\n *\n * **Details**\n *\n * This function allows you to apply a specific `LogLevel` locally to an\n * `Effect` workflow. Once the workflow completes, the `LogLevel` reverts to its\n * previous state.\n *\n * **When to Use**\n *\n * This is particularly useful when you want to adjust the verbosity of logging\n * for specific parts of your program without affecting the global log level.\n *\n * @example\n * ```ts\n * import { Effect, LogLevel } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"message1\")\n *   yield* Effect.gen(function*() {\n *     yield* Effect.log(\"message2\")\n *     yield* Effect.log(\"message3\")\n *   }).pipe(LogLevel.locally(LogLevel.Warning))\n * })\n *\n * Effect.runFork(program)\n * // timestamp=... level=INFO fiber=#0 message=message1\n * // timestamp=... level=WARN fiber=#0 message=message2\n * // timestamp=... level=WARN fiber=#0 message=message3\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const locally: {\n  (self: LogLevel): <A, E, R>(use: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(use: Effect.Effect<A, E, R>, self: LogLevel): Effect.Effect<A, E, R>\n} = dual(\n  2,\n  <A, E, R>(use: Effect.Effect<A, E, R>, self: LogLevel): Effect.Effect<A, E, R> =>\n    core.fiberRefLocally(use, core.currentLogLevel, self)\n)\n\n/**\n * @since 2.0.0\n * @category instances\n */\nexport const Order: order.Order<LogLevel> = pipe(\n  number.Order,\n  order.mapInput((level: LogLevel) => level.ordinal)\n)\n\n/**\n * @since 2.0.0\n * @category ordering\n */\nexport const lessThan: {\n  (that: LogLevel): (self: LogLevel) => boolean\n  (self: LogLevel, that: LogLevel): boolean\n} = order.lessThan(Order)\n\n/**\n * @since 2.0.0\n * @category ordering\n */\nexport const lessThanEqual: {\n  (that: LogLevel): (self: LogLevel) => boolean\n  (self: LogLevel, that: LogLevel): boolean\n} = order.lessThanOrEqualTo(Order)\n\n/**\n * @since 2.0.0\n * @category ordering\n */\nexport const greaterThan: {\n  (that: LogLevel): (self: LogLevel) => boolean\n  (self: LogLevel, that: LogLevel): boolean\n} = order.greaterThan(Order)\n\n/**\n * @since 2.0.0\n * @category ordering\n */\nexport const greaterThanEqual: {\n  (that: LogLevel): (self: LogLevel) => boolean\n  (self: LogLevel, that: LogLevel): boolean\n} = order.greaterThanOrEqualTo(Order)\n\n/**\n * @since 2.0.0\n * @category conversions\n */\nexport const fromLiteral = (literal: Literal): LogLevel => {\n  switch (literal) {\n    case \"All\":\n      return All\n    case \"Debug\":\n      return Debug\n    case \"Error\":\n      return Error\n    case \"Fatal\":\n      return Fatal\n    case \"Info\":\n      return Info\n    case \"Trace\":\n      return Trace\n    case \"None\":\n      return None\n    case \"Warning\":\n      return Warning\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/LogSpan.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/logSpan.js\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface LogSpan {\n  readonly label: string\n  readonly startTime: number\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (label: string, startTime: number) => LogSpan = internal.make\n\n/**\n * @since 2.0.0\n * @category destructors\n */\nexport const render: (now: number) => (self: LogSpan) => string = internal.render\n"
  },
  {
    "path": "packages/effect/src/Logger.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type { DurationInput } from \"./Duration.js\"\nimport type { Effect } from \"./Effect.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport type * as FiberRefs from \"./FiberRefs.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport type * as HashMap from \"./HashMap.js\"\nimport * as fiberRuntime from \"./internal/fiberRuntime.js\"\nimport * as circular from \"./internal/layer/circular.js\"\nimport * as internalCircular from \"./internal/logger-circular.js\"\nimport * as internal from \"./internal/logger.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type * as List from \"./List.js\"\nimport type * as LogLevel from \"./LogLevel.js\"\nimport type * as LogSpan from \"./LogSpan.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Scope } from \"./Scope.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const LoggerTypeId: unique symbol = internal.LoggerTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type LoggerTypeId = typeof LoggerTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Logger<in Message, out Output> extends Logger.Variance<Message, Output>, Pipeable {\n  log(options: Logger.Options<Message>): Output\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Logger {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in Message, out Output> {\n    readonly [LoggerTypeId]: {\n      readonly _Message: Types.Contravariant<Message>\n      readonly _Output: Types.Covariant<Output>\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Options<out Message> {\n    readonly fiberId: FiberId.FiberId\n    readonly logLevel: LogLevel.LogLevel\n    readonly message: Message\n    readonly cause: Cause.Cause<unknown>\n    readonly context: FiberRefs.FiberRefs\n    readonly spans: List.List<LogSpan.LogSpan>\n    readonly annotations: HashMap.HashMap<string, unknown>\n    readonly date: Date\n  }\n}\n\n/**\n * Creates a custom logger that formats log messages according to the provided\n * function.\n *\n * @example\n * ```ts\n * import { Effect, Logger, LogLevel } from \"effect\"\n *\n * const logger = Logger.make(({ logLevel, message }) => {\n *   globalThis.console.log(`[${logLevel.label}] ${message}`)\n * })\n *\n * const task1 = Effect.logDebug(\"task1 done\")\n * const task2 = Effect.logDebug(\"task2 done\")\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"start\")\n *   yield* task1\n *   yield* task2\n *   yield* Effect.log(\"done\")\n * }).pipe(\n *   Logger.withMinimumLogLevel(LogLevel.Debug),\n *   Effect.provide(Logger.replace(Logger.defaultLogger, logger))\n * )\n *\n * Effect.runFork(program)\n * // [INFO] start\n * // [DEBUG] task1 done\n * // [DEBUG] task2 done\n * // [INFO] done\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make: <Message, Output>(log: (options: Logger.Options<Message>) => Output) => Logger<Message, Output> =\n  internal.makeLogger\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const add: <B>(logger: Logger<unknown, B>) => Layer.Layer<never> = circular.addLogger\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const addEffect: <A, E, R>(effect: Effect<Logger<unknown, A>, E, R>) => Layer.Layer<never, E, R> =\n  circular.addLoggerEffect\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const addScoped: <A, E, R>(\n  effect: Effect<Logger<unknown, A>, E, R>\n) => Layer.Layer<never, E, Exclude<R, Scope>> = circular.addLoggerScoped\n\n/**\n * @since 2.0.0\n * @category mapping\n */\nexport const mapInput: {\n  <Message, Message2>(\n    f: (message: Message2) => Message\n  ): <Output>(self: Logger<Message, Output>) => Logger<Message2, Output>\n  <Output, Message, Message2>(\n    self: Logger<Message, Output>,\n    f: (message: Message2) => Message\n  ): Logger<Message2, Output>\n} = internal.mapInput\n\n/**\n * @since 2.0.0\n * @category mapping\n */\nexport const mapInputOptions: {\n  <Message, Message2>(\n    f: (options: Logger.Options<Message2>) => Logger.Options<Message>\n  ): <Output>(self: Logger<Message, Output>) => Logger<Message2, Output>\n  <Output, Message, Message2>(\n    self: Logger<Message, Output>,\n    f: (options: Logger.Options<Message2>) => Logger.Options<Message>\n  ): Logger<Message2, Output>\n} = internal.mapInputOptions\n\n/**\n * Returns a version of this logger that only logs messages when the log level\n * satisfies the specified predicate.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterLogLevel: {\n  (\n    f: (logLevel: LogLevel.LogLevel) => boolean\n  ): <Message, Output>(self: Logger<Message, Output>) => Logger<Message, Option.Option<Output>>\n  <Message, Output>(\n    self: Logger<Message, Output>,\n    f: (logLevel: LogLevel.LogLevel) => boolean\n  ): Logger<Message, Option.Option<Output>>\n} = internal.filterLogLevel\n\n/**\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <Output, Output2>(\n    f: (output: Output) => Output2\n  ): <Message>(self: Logger<Message, Output>) => Logger<Message, Output2>\n  <Message, Output, Output2>(\n    self: Logger<Message, Output>,\n    f: (output: Output) => Output2\n  ): Logger<Message, Output2>\n} = internal.map\n\n/**\n * Creates a batched logger that groups log messages together and processes them\n * in intervals.\n *\n * @example\n * ```ts\n * import { Console, Effect, Logger } from \"effect\"\n *\n * const LoggerLive = Logger.replaceScoped(\n *   Logger.defaultLogger,\n *   Logger.logfmtLogger.pipe(\n *     Logger.batched(\"500 millis\", (messages) => Console.log(\"BATCH\", `[\\n${messages.join(\"\\n\")}\\n]`))\n *   )\n * )\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"one\")\n *   yield* Effect.log(\"two\")\n *   yield* Effect.log(\"three\")\n * }).pipe(Effect.provide(LoggerLive))\n *\n * Effect.runFork(program)\n * // BATCH [\n * // timestamp=... level=INFO fiber=#0 message=one\n * // timestamp=... level=INFO fiber=#0 message=two\n * // timestamp=... level=INFO fiber=#0 message=three\n * // ]\n * ```\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const batched: {\n  <Output, R>(\n    window: DurationInput,\n    f: (messages: Array<Types.NoInfer<Output>>) => Effect<void, never, R>\n  ): <Message>(self: Logger<Message, Output>) => Effect<Logger<Message, void>, never, R | Scope>\n  <Message, Output, R>(\n    self: Logger<Message, Output>,\n    window: DurationInput,\n    f: (messages: Array<Types.NoInfer<Output>>) => Effect<void, never, R>\n  ): Effect<Logger<Message, void>, never, Scope | R>\n} = fiberRuntime.batchedLogger\n\n/**\n * @since 2.0.0\n * @category console\n */\nexport const withConsoleLog: <M, O>(self: Logger<M, O>) => Logger<M, void> = fiberRuntime.loggerWithConsoleLog\n\n/**\n * Takes a `Logger<M, O>` and returns a logger that calls the respective `Console` method\n * based on the log level.\n *\n * @example\n * ```ts\n * import { Logger, Effect } from \"effect\"\n *\n * const loggerLayer = Logger.replace(\n *   Logger.defaultLogger,\n *   Logger.withLeveledConsole(Logger.stringLogger),\n * )\n *\n * Effect.gen(function* () {\n *   yield* Effect.logError(\"an error\")\n *   yield* Effect.logInfo(\"an info\")\n * }).pipe(Effect.provide(loggerLayer))\n * ```\n *\n * @since 3.8.0\n * @category console\n */\nexport const withLeveledConsole: <M, O>(self: Logger<M, O>) => Logger<M, void> = fiberRuntime.loggerWithLeveledLog\n\n/**\n * @since 2.0.0\n * @category console\n */\nexport const withConsoleError: <M, O>(self: Logger<M, O>) => Logger<M, void> = fiberRuntime.loggerWithConsoleError\n\n/**\n * A logger that does nothing in response to logging events.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const none: Logger<unknown, void> = internal.none\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const remove: <A>(logger: Logger<unknown, A>) => Layer.Layer<never> = circular.removeLogger\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const replace: {\n  <B>(that: Logger<unknown, B>): <A>(self: Logger<unknown, A>) => Layer.Layer<never>\n  <A, B>(self: Logger<unknown, A>, that: Logger<unknown, B>): Layer.Layer<never>\n} = circular.replaceLogger\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const replaceEffect: {\n  <B, E, R>(that: Effect<Logger<unknown, B>, E, R>): <A>(self: Logger<unknown, A>) => Layer.Layer<never, E, R>\n  <A, B, E, R>(self: Logger<unknown, A>, that: Effect<Logger<unknown, B>, E, R>): Layer.Layer<never, E, R>\n} = circular.replaceLoggerEffect\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const replaceScoped: {\n  <B, E, R>(\n    that: Effect<Logger<unknown, B>, E, R>\n  ): <A>(self: Logger<unknown, A>) => Layer.Layer<never, E, Exclude<R, Scope>>\n  <A, B, E, R>(\n    self: Logger<unknown, A>,\n    that: Effect<Logger<unknown, B>, E, R>\n  ): Layer.Layer<never, E, Exclude<R, Scope>>\n} = circular.replaceLoggerScoped\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const simple: <A, B>(log: (a: A) => B) => Logger<A, B> = internal.simple\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const succeed: <A>(value: A) => Logger<unknown, A> = internal.succeed\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const sync: <A>(evaluate: LazyArg<A>) => Logger<unknown, A> = internal.sync\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const test: {\n  <Message>(input: Message): <Output>(self: Logger<Message, Output>) => Output\n  <Message, Output>(self: Logger<Message, Output>, input: Message): Output\n} = internalCircular.test\n\n/**\n * Sets the minimum log level for subsequent logging operations, allowing\n * control over which log messages are displayed based on their severity.\n *\n * @example\n * ```ts\n * import { Effect, Logger, LogLevel } from \"effect\"\n *\n * const program = Effect.logDebug(\"message1\").pipe(Logger.withMinimumLogLevel(LogLevel.Debug))\n *\n * Effect.runFork(program)\n * // timestamp=... level=DEBUG fiber=#0 message=message1\n * ```\n *\n * @since 2.0.0\n * @category context\n */\nexport const withMinimumLogLevel: {\n  (level: LogLevel.LogLevel): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>\n  <A, E, R>(self: Effect<A, E, R>, level: LogLevel.LogLevel): Effect<A, E, R>\n} = circular.withMinimumLogLevel\n\n/**\n * @since 2.0.0\n * @category tracing\n */\nexport const withSpanAnnotations: <Message, Output>(self: Logger<Message, Output>) => Logger<Message, Output> =\n  fiberRuntime.loggerWithSpanAnnotations\n\n/**\n * Combines this logger with the specified logger to produce a new logger that\n * logs to both this logger and that logger.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zip: {\n  <Message2, Output2>(\n    that: Logger<Message2, Output2>\n  ): <Message, Output>(self: Logger<Message, Output>) => Logger<Message & Message2, [Output, Output2]>\n  <Message, Output, Message2, Output2>(\n    self: Logger<Message, Output>,\n    that: Logger<Message2, Output2>\n  ): Logger<Message & Message2, [Output, Output2]>\n} = internal.zip\n\n/**\n * @since 2.0.0\n * @category zipping\n */\nexport const zipLeft: {\n  <Message2, Output2>(\n    that: Logger<Message2, Output2>\n  ): <Message, Output>(self: Logger<Message, Output>) => Logger<Message & Message2, Output>\n  <Message, Output, Message2, Output2>(\n    self: Logger<Message, Output>,\n    that: Logger<Message2, Output2>\n  ): Logger<Message & Message2, Output>\n} = internal.zipLeft\n\n/**\n * @since 2.0.0\n * @category zipping\n */\nexport const zipRight: {\n  <Message2, Output2>(\n    that: Logger<Message2, Output2>\n  ): <Message, Output>(self: Logger<Message, Output>) => Logger<Message & Message2, Output2>\n  <Message, Output, Message2, Output2>(\n    self: Logger<Message, Output>,\n    that: Logger<Message2, Output2>\n  ): Logger<Message & Message2, Output2>\n} = internal.zipRight\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const defaultLogger: Logger<unknown, void> = fiberRuntime.defaultLogger\n\n/**\n * The `jsonLogger` logger formats log entries as JSON objects, making them easy to\n * integrate with logging systems that consume JSON data.\n *\n * @example\n * ```ts\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"message1\", \"message2\").pipe(\n *   Effect.annotateLogs({ key1: \"value1\", key2: \"value2\" }),\n *   Effect.withLogSpan(\"myspan\")\n * )\n *\n * Effect.runFork(program.pipe(Effect.provide(Logger.json)))\n * // {\"message\":[\"message1\",\"message2\"],\"logLevel\":\"INFO\",\"timestamp\":\"...\",\"annotations\":{\"key2\":\"value2\",\"key1\":\"value1\"},\"spans\":{\"myspan\":0},\"fiberId\":\"#0\"}\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const jsonLogger: Logger<unknown, string> = internal.jsonLogger\n\n/**\n * This logger outputs logs in a human-readable format that is easy to read\n * during development or in a production console.\n *\n * @example\n * ```ts\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"message1\", \"message2\").pipe(\n *   Effect.annotateLogs({ key1: \"value1\", key2: \"value2\" }),\n *   Effect.withLogSpan(\"myspan\")\n * )\n *\n * Effect.runFork(program.pipe(Effect.provide(Logger.logFmt)))\n * // timestamp=... level=INFO fiber=#0 message=message1 message=message2 myspan=0ms key2=value2 key1=value1\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const logfmtLogger: Logger<unknown, string> = internal.logfmtLogger\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const stringLogger: Logger<unknown, string> = internal.stringLogger\n\n/**\n * The pretty logger utilizes the capabilities of the console API to generate\n * visually engaging and color-enhanced log outputs. This feature is\n * particularly useful for improving the readability of log messages during\n * development and debugging processes.\n *\n * @example\n * ```ts\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"message1\", \"message2\").pipe(\n *   Effect.annotateLogs({ key1: \"value1\", key2: \"value2\" }),\n *   Effect.withLogSpan(\"myspan\")\n * )\n *\n * Effect.runFork(program.pipe(Effect.provide(Logger.pretty)))\n * //         green --v                      v-- bold and cyan\n * // [07:51:54.434] INFO (#0) myspan=1ms: message1\n * //   message2\n * //    v-- bold\n * //   key2: value2\n * //   key1: value1\n * ```\n *\n * @since 3.5.0\n * @category constructors\n */\nexport const prettyLogger: (\n  options?: {\n    readonly colors?: \"auto\" | boolean | undefined\n    readonly stderr?: boolean | undefined\n    readonly formatDate?: ((date: Date) => string) | undefined\n    readonly mode?: \"browser\" | \"tty\" | \"auto\" | undefined\n  }\n) => Logger<unknown, void> = internal.prettyLogger\n\n/**\n * A default version of the pretty logger.\n *\n * @since 3.8.0\n * @category constructors\n */\nexport const prettyLoggerDefault: Logger<unknown, void> = internal.prettyLoggerDefault\n\n/**\n * The structured logger provides detailed log outputs, structured in a way that\n * retains comprehensive traceability of the events, suitable for deeper\n * analysis and troubleshooting.\n *\n * @example\n * ```ts\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"message1\", \"message2\").pipe(\n *   Effect.annotateLogs({ key1: \"value1\", key2: \"value2\" }),\n *   Effect.withLogSpan(\"myspan\")\n * )\n *\n * Effect.runFork(program.pipe(Effect.provide(Logger.structured)))\n * // {\n * //   message: [ 'message1', 'message2' ],\n * //   logLevel: 'INFO',\n * //   timestamp: '2024-07-09T14:05:41.623Z',\n * //   cause: undefined,\n * //   annotations: { key2: 'value2', key1: 'value1' },\n * //   spans: { myspan: 0 },\n * //   fiberId: '#0'\n * // }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const structuredLogger: Logger<\n  unknown,\n  {\n    readonly logLevel: string\n    readonly fiberId: string\n    readonly timestamp: string\n    readonly message: unknown\n    readonly cause: string | undefined\n    readonly annotations: Record<string, unknown>\n    readonly spans: Record<string, number>\n  }\n> = internal.structuredLogger\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const tracerLogger: Logger<unknown, void> = fiberRuntime.tracerLogger\n\n/**\n * The `json` logger formats log entries as JSON objects, making them easy to\n * integrate with logging systems that consume JSON data.\n *\n * @example\n * ```ts\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"message1\", \"message2\").pipe(\n *   Effect.annotateLogs({ key1: \"value1\", key2: \"value2\" }),\n *   Effect.withLogSpan(\"myspan\")\n * )\n *\n * Effect.runFork(program.pipe(Effect.provide(Logger.json)))\n * // {\"message\":[\"message1\",\"message2\"],\"logLevel\":\"INFO\",\"timestamp\":\"...\",\"annotations\":{\"key2\":\"value2\",\"key1\":\"value1\"},\"spans\":{\"myspan\":0},\"fiberId\":\"#0\"}\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const json: Layer.Layer<never> = replace(fiberRuntime.defaultLogger, fiberRuntime.jsonLogger)\n\n/**\n * This logger outputs logs in a human-readable format that is easy to read\n * during development or in a production console.\n *\n * @example\n * ```ts\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"message1\", \"message2\").pipe(\n *   Effect.annotateLogs({ key1: \"value1\", key2: \"value2\" }),\n *   Effect.withLogSpan(\"myspan\")\n * )\n *\n * Effect.runFork(program.pipe(Effect.provide(Logger.logFmt)))\n * // timestamp=... level=INFO fiber=#0 message=message1 message=message2 myspan=0ms key2=value2 key1=value1\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const logFmt: Layer.Layer<never> = replace(fiberRuntime.defaultLogger, fiberRuntime.logFmtLogger)\n\n/**\n * The pretty logger utilizes the capabilities of the console API to generate\n * visually engaging and color-enhanced log outputs. This feature is\n * particularly useful for improving the readability of log messages during\n * development and debugging processes.\n *\n * @example\n * ```ts\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"message1\", \"message2\").pipe(\n *   Effect.annotateLogs({ key1: \"value1\", key2: \"value2\" }),\n *   Effect.withLogSpan(\"myspan\")\n * )\n *\n * Effect.runFork(program.pipe(Effect.provide(Logger.pretty)))\n * //         green --v                      v-- bold and cyan\n * // [07:51:54.434] INFO (#0) myspan=1ms: message1\n * //   message2\n * //    v-- bold\n * //   key2: value2\n * //   key1: value1\n * ```\n *\n * @since 3.5.0\n * @category constructors\n */\nexport const pretty: Layer.Layer<never> = replace(fiberRuntime.defaultLogger, fiberRuntime.prettyLogger)\n\n/**\n * The structured logger provides detailed log outputs, structured in a way that\n * retains comprehensive traceability of the events, suitable for deeper\n * analysis and troubleshooting.\n *\n * @example\n * ```ts\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"message1\", \"message2\").pipe(\n *   Effect.annotateLogs({ key1: \"value1\", key2: \"value2\" }),\n *   Effect.withLogSpan(\"myspan\")\n * )\n *\n * Effect.runFork(program.pipe(Effect.provide(Logger.structured)))\n * // {\n * //   message: [ 'message1', 'message2' ],\n * //   logLevel: 'INFO',\n * //   timestamp: '2024-07-09T14:05:41.623Z',\n * //   cause: undefined,\n * //   annotations: { key2: 'value2', key1: 'value1' },\n * //   spans: { myspan: 0 },\n * //   fiberId: '#0'\n * // }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const structured: Layer.Layer<never> = replace(fiberRuntime.defaultLogger, fiberRuntime.structuredLogger)\n\n/**\n * Sets the minimum log level for logging operations, allowing control over\n * which log messages are displayed based on their severity.\n *\n * @example\n * ```ts\n * import { Effect, Logger, LogLevel } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n *   yield* Effect.log(\"Executing task...\")\n *   yield* Effect.sleep(\"100 millis\")\n *   console.log(\"task done\")\n * })\n *\n * // Logging disabled using a layer\n * Effect.runFork(program.pipe(Effect.provide(Logger.minimumLogLevel(LogLevel.None))))\n * // task done\n * ```\n *\n * @since 2.0.0\n * @category context\n */\nexport const minimumLogLevel: (level: LogLevel.LogLevel) => Layer.Layer<never> = circular.minimumLogLevel\n\n/**\n * Returns `true` if the specified value is a `Logger`, otherwise returns `false`.\n *\n * @since 1.0.0\n * @category guards\n */\nexport const isLogger: (u: unknown) => u is Logger<unknown, unknown> = internal.isLogger\n"
  },
  {
    "path": "packages/effect/src/Mailbox.ts",
    "content": "/**\n * @since 3.8.0\n * @experimental\n */\nimport type { Cause, NoSuchElementException } from \"./Cause.js\"\nimport type { Channel } from \"./Channel.js\"\nimport type { Chunk } from \"./Chunk.js\"\nimport type { Effect } from \"./Effect.js\"\nimport type { Exit } from \"./Exit.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as internal from \"./internal/mailbox.js\"\nimport type { Option } from \"./Option.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport type { Scope } from \"./Scope.js\"\nimport type { Stream } from \"./Stream.js\"\n\n/**\n * @since 3.8.0\n * @experimental\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 3.8.0\n * @experimental\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 3.8.0\n * @experimental\n * @category type ids\n */\nexport const ReadonlyTypeId: unique symbol = internal.ReadonlyTypeId\n\n/**\n * @since 3.8.0\n * @experimental\n * @category type ids\n */\nexport type ReadonlyTypeId = typeof ReadonlyTypeId\n\n/**\n * @since 3.8.0\n * @experimental\n * @category guards\n */\nexport const isMailbox = <A = unknown, E = unknown>(u: unknown): u is Mailbox<A, E> => hasProperty(u, TypeId)\n\n/**\n * @since 3.8.0\n * @experimental\n * @category guards\n */\nexport const isReadonlyMailbox = <A = unknown, E = unknown>(u: unknown): u is ReadonlyMailbox<A, E> =>\n  hasProperty(u, ReadonlyTypeId)\n\n/**\n * A `Mailbox` is a queue that can be signaled to be done or failed.\n *\n * @since 3.8.0\n * @experimental\n * @category models\n */\nexport interface Mailbox<in out A, in out E = never> extends ReadonlyMailbox<A, E> {\n  readonly [TypeId]: TypeId\n  /**\n   * Add a message to the mailbox. Returns `false` if the mailbox is done.\n   */\n  readonly offer: (message: A) => Effect<boolean>\n  /**\n   * Add a message to the mailbox. Returns `false` if the mailbox is done.\n   */\n  readonly unsafeOffer: (message: A) => boolean\n  /**\n   * Add multiple messages to the mailbox. Returns the remaining messages that\n   * were not added.\n   */\n  readonly offerAll: (messages: Iterable<A>) => Effect<Chunk<A>>\n  /**\n   * Add multiple messages to the mailbox. Returns the remaining messages that\n   * were not added.\n   */\n  readonly unsafeOfferAll: (messages: Iterable<A>) => Chunk<A>\n  /**\n   * Fail the mailbox with an error. If the mailbox is already done, `false` is\n   * returned.\n   */\n  readonly fail: (error: E) => Effect<boolean>\n  /**\n   * Fail the mailbox with a cause. If the mailbox is already done, `false` is\n   * returned.\n   */\n  readonly failCause: (cause: Cause<E>) => Effect<boolean>\n  /**\n   * Signal that the mailbox is complete. If the mailbox is already done, `false` is\n   * returned.\n   */\n  readonly end: Effect<boolean>\n  /**\n   * Signal that the mailbox is done. If the mailbox is already done, `false` is\n   * returned.\n   */\n  readonly done: (exit: Exit<void, E>) => Effect<boolean>\n  /**\n   * Signal that the mailbox is done. If the mailbox is already done, `false` is\n   * returned.\n   */\n  readonly unsafeDone: (exit: Exit<void, E>) => boolean\n  /**\n   * Shutdown the mailbox, canceling any pending operations.\n   * If the mailbox is already done, `false` is returned.\n   */\n  readonly shutdown: Effect<boolean>\n}\n\n/**\n * A `ReadonlyMailbox` represents a mailbox that can only be read from.\n *\n * @since 3.8.0\n * @experimental\n * @category models\n */\nexport interface ReadonlyMailbox<out A, out E = never>\n  extends Effect<readonly [messages: Chunk<A>, done: boolean], E>, Inspectable\n{\n  readonly [ReadonlyTypeId]: ReadonlyTypeId\n  /**\n   * Take all messages from the mailbox, returning an empty Chunk if the mailbox\n   * is empty or done.\n   */\n  readonly clear: Effect<Chunk<A>, E>\n  /**\n   * Take all messages from the mailbox, or wait for messages to be available.\n   *\n   * If the mailbox is done, the `done` flag will be `true`. If the mailbox\n   * fails, the Effect will fail with the error.\n   */\n  readonly takeAll: Effect<readonly [messages: Chunk<A>, done: boolean], E>\n  /**\n   * Take a specified number of messages from the mailbox. It will only take\n   * up to the capacity of the mailbox.\n   *\n   * If the mailbox is done, the `done` flag will be `true`. If the mailbox\n   * fails, the Effect will fail with the error.\n   */\n  readonly takeN: (n: number) => Effect<readonly [messages: Chunk<A>, done: boolean], E>\n  /**\n   * Take a single message from the mailbox, or wait for a message to be\n   * available.\n   *\n   * If the mailbox is done, it will fail with `NoSuchElementException`. If the\n   * mailbox fails, the Effect will fail with the error.\n   */\n  readonly take: Effect<A, E | NoSuchElementException>\n  /** Wait for the mailbox to be done. */\n  readonly await: Effect<void, E>\n  /**\n   * Check the size of the mailbox.\n   *\n   * If the mailbox is complete, it will return `None`.\n   */\n  readonly size: Effect<Option<number>>\n  /**\n   * Check the size of the mailbox.\n   *\n   * If the mailbox is complete, it will return `None`.\n   */\n  readonly unsafeSize: () => Option<number>\n}\n\n/**\n * A `Mailbox` is a queue that can be signaled to be done or failed.\n *\n * @since 3.8.0\n * @experimental\n * @category constructors\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Effect, Mailbox } from \"effect\"\n *\n * Effect.gen(function*() {\n *   const mailbox = yield* Mailbox.make<number, string>()\n *\n *   // add messages to the mailbox\n *   yield* mailbox.offer(1)\n *   yield* mailbox.offer(2)\n *   yield* mailbox.offerAll([3, 4, 5])\n *\n *   // take messages from the mailbox\n *   const [messages, done] = yield* mailbox.takeAll\n *   assert.deepStrictEqual(messages, [1, 2, 3, 4, 5])\n *   assert.strictEqual(done, false)\n *\n *   // signal that the mailbox is done\n *   yield* mailbox.end\n *   const [messages2, done2] = yield* mailbox.takeAll\n *   assert.deepStrictEqual(messages2, [])\n *   assert.strictEqual(done2, true)\n *\n *   // signal that the mailbox has failed\n *   yield* mailbox.fail(\"boom\")\n * })\n * ```\n */\nexport const make: <A, E = never>(\n  capacity?: number | {\n    readonly capacity?: number\n    readonly strategy?: \"suspend\" | \"dropping\" | \"sliding\"\n  } | undefined\n) => Effect<Mailbox<A, E>> = internal.make\n\n/**\n * Run an `Effect` into a `Mailbox`, where success ends the mailbox and failure\n * fails the mailbox.\n *\n * @since 3.8.0\n * @experimental\n * @category combinators\n */\nexport const into: {\n  <A, E>(self: Mailbox<A, E>): <AX, EX extends E, RX>(effect: Effect<AX, EX, RX>) => Effect<boolean, never, RX>\n  <AX, E, EX extends E, RX, A>(effect: Effect<AX, EX, RX>, self: Mailbox<A, E>): Effect<boolean, never, RX>\n} = internal.into\n\n/**\n * Create a `Channel` from a `Mailbox`.\n *\n * @since 3.8.0\n * @experimental\n * @category conversions\n */\nexport const toChannel: <A, E>(self: ReadonlyMailbox<A, E>) => Channel<Chunk<A>, unknown, E> = internal.toChannel\n\n/**\n * Create a `Stream` from a `Mailbox`.\n *\n * @since 3.8.0\n * @experimental\n * @category conversions\n */\nexport const toStream: <A, E>(self: ReadonlyMailbox<A, E>) => Stream<A, E> = internal.toStream\n\n/**\n * Create a `ReadonlyMailbox` from a `Stream`.\n *\n * @since 3.11.0\n * @experimental\n * @category conversions\n */\nexport const fromStream: {\n  (\n    options?: {\n      readonly capacity?: number | undefined\n      readonly strategy?: \"suspend\" | \"dropping\" | \"sliding\" | undefined\n    }\n  ): <A, E, R>(self: Stream<A, E, R>) => Effect<ReadonlyMailbox<A, E>, never, R | Scope>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    options?: {\n      readonly capacity?: number | undefined\n      readonly strategy?: \"suspend\" | \"dropping\" | \"sliding\" | undefined\n    }\n  ): Effect<ReadonlyMailbox<A, E>, never, R | Scope>\n} = internal.fromStream\n"
  },
  {
    "path": "packages/effect/src/ManagedRuntime.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport * as internal from \"./internal/managedRuntime.js\"\nimport * as circular from \"./internal/managedRuntime/circular.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type * as Runtime from \"./Runtime.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 3.9.0\n * @category symbol\n */\nexport const TypeId: unique symbol = circular.TypeId as TypeId\n\n/**\n * @since 3.9.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * Checks if the provided argument is a `ManagedRuntime`.\n *\n * @since 3.9.0\n * @category guards\n */\nexport const isManagedRuntime: (input: unknown) => input is ManagedRuntime<unknown, unknown> = internal.isManagedRuntime\n\n/**\n * @since 3.4.0\n */\nexport declare namespace ManagedRuntime {\n  /**\n   * @category type-level\n   * @since 3.4.0\n   */\n  export type Context<T extends ManagedRuntime<never, any>> = [T] extends [ManagedRuntime<infer R, infer _E>] ? R\n    : never\n  /**\n   * @category type-level\n   * @since 3.4.0\n   */\n  export type Error<T extends ManagedRuntime<never, any>> = [T] extends [ManagedRuntime<infer _R, infer E>] ? E : never\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface ManagedRuntime<in R, out ER> extends Effect.Effect<Runtime.Runtime<R>, ER> {\n  readonly [TypeId]: TypeId\n  readonly memoMap: Layer.MemoMap\n  readonly runtimeEffect: Effect.Effect<Runtime.Runtime<R>, ER>\n  readonly runtime: () => Promise<Runtime.Runtime<R>>\n\n  /**\n   * Executes the effect using the provided Scheduler or using the global\n   * Scheduler if not provided\n   */\n  readonly runFork: <A, E>(\n    self: Effect.Effect<A, E, R>,\n    options?: Runtime.RunForkOptions\n  ) => Fiber.RuntimeFiber<A, E | ER>\n\n  /**\n   * Executes the effect synchronously returning the exit.\n   *\n   * This method is effectful and should only be invoked at the edges of your\n   * program.\n   */\n  readonly runSyncExit: <A, E>(effect: Effect.Effect<A, E, R>) => Exit.Exit<A, ER | E>\n\n  /**\n   * Executes the effect synchronously throwing in case of errors or async boundaries.\n   *\n   * This method is effectful and should only be invoked at the edges of your\n   * program.\n   */\n  readonly runSync: <A, E>(effect: Effect.Effect<A, E, R>) => A\n\n  /**\n   * Executes the effect asynchronously, eventually passing the exit value to\n   * the specified callback.\n   *\n   * This method is effectful and should only be invoked at the edges of your\n   * program.\n   */\n  readonly runCallback: <A, E>(\n    effect: Effect.Effect<A, E, R>,\n    options?: Runtime.RunCallbackOptions<A, E | ER> | undefined\n  ) => Runtime.Cancel<A, E | ER>\n\n  /**\n   * Runs the `Effect`, returning a JavaScript `Promise` that will be resolved\n   * with the value of the effect once the effect has been executed, or will be\n   * rejected with the first error or exception throw by the effect.\n   *\n   * This method is effectful and should only be used at the edges of your\n   * program.\n   */\n  readonly runPromise: <A, E>(effect: Effect.Effect<A, E, R>, options?: {\n    readonly signal?: AbortSignal | undefined\n  }) => Promise<A>\n\n  /**\n   * Runs the `Effect`, returning a JavaScript `Promise` that will be resolved\n   * with the `Exit` state of the effect once the effect has been executed.\n   *\n   * This method is effectful and should only be used at the edges of your\n   * program.\n   */\n  readonly runPromiseExit: <A, E>(effect: Effect.Effect<A, E, R>, options?: {\n    readonly signal?: AbortSignal | undefined\n  }) => Promise<Exit.Exit<A, ER | E>>\n\n  /**\n   * Dispose of the resources associated with the runtime.\n   */\n  readonly dispose: () => Promise<void>\n\n  /**\n   * Dispose of the resources associated with the runtime.\n   */\n  readonly disposeEffect: Effect.Effect<void, never, never>\n\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: ManagedRuntimeUnify<this>\n  readonly [Unify.ignoreSymbol]?: ManagedRuntimeUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.9.0\n */\nexport interface ManagedRuntimeUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  ManagedRuntime?: () => Extract<A[Unify.typeSymbol], ManagedRuntime<any, any>>\n}\n\n/**\n * @category models\n * @since 3.9.0\n */\nexport interface ManagedRuntimeUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * Convert a Layer into an ManagedRuntime, that can be used to run Effect's using\n * your services.\n *\n * @since 2.0.0\n * @category runtime class\n * @example\n * ```ts\n * import { Console, Effect, Layer, ManagedRuntime } from \"effect\"\n *\n * class Notifications extends Effect.Tag(\"Notifications\")<\n *   Notifications,\n *   { readonly notify: (message: string) => Effect.Effect<void> }\n * >() {\n *   static Live = Layer.succeed(this, { notify: (message) => Console.log(message) })\n * }\n *\n * async function main() {\n *   const runtime = ManagedRuntime.make(Notifications.Live)\n *   await runtime.runPromise(Notifications.notify(\"Hello, world!\"))\n *   await runtime.dispose()\n * }\n *\n * main()\n * ```\n */\nexport const make: <R, E>(\n  layer: Layer.Layer<R, E, never>,\n  memoMap?: Layer.MemoMap | undefined\n) => ManagedRuntime<R, E> = internal.make\n"
  },
  {
    "path": "packages/effect/src/Match.ts",
    "content": "/**\n * The `effect/match` module provides a type-safe pattern matching system for\n * TypeScript. Inspired by functional programming, it simplifies conditional\n * logic by replacing verbose if/else or switch statements with a structured and\n * expressive API.\n *\n * This module supports matching against types, values, and discriminated unions\n * while enforcing exhaustiveness checking to ensure all cases are handled.\n *\n * Although pattern matching is not yet a native JavaScript feature,\n * `effect/match` offers a reliable implementation that is available today.\n *\n * **How Pattern Matching Works**\n *\n * Pattern matching follows a structured process:\n *\n * - **Creating a matcher**: Define a `Matcher` that operates on either a\n *   specific `Match.type` or `Match.value`.\n *\n * - **Defining patterns**: Use combinators such as `Match.when`, `Match.not`,\n *   and `Match.tag` to specify matching conditions.\n *\n * - **Completing the match**: Apply a finalizer such as `Match.exhaustive`,\n *   `Match.orElse`, or `Match.option` to determine how unmatched cases should\n *   be handled.\n *\n * @since 1.0.0\n */\nimport type * as Either from \"./Either.js\"\nimport * as internal from \"./internal/matcher.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport type * as T from \"./Types.js\"\nimport type { Unify } from \"./Unify.js\"\n\n/**\n * @category Symbols\n * @since 1.0.0\n */\nexport const MatcherTypeId: unique symbol = internal.TypeId\n\n/**\n * @category Symbols\n * @since 1.0.0\n */\nexport type MatcherTypeId = typeof MatcherTypeId\n\n/**\n * Pattern matching follows a structured process:\n *\n * - **Creating a matcher**: Define a `Matcher` that operates on either a\n *   specific `Match.type` or `Match.value`.\n *\n * - **Defining patterns**: Use combinators such as `Match.when`, `Match.not`,\n *   and `Match.tag` to specify matching conditions.\n *\n * - **Completing the match**: Apply a finalizer such as `Match.exhaustive`,\n *   `Match.orElse`, or `Match.option` to determine how unmatched cases should\n *   be handled.\n *\n * @example\n * ```ts\n * import { Match } from \"effect\"\n *\n * // Simulated dynamic input that can be a string or a number\n * const input: string | number = \"some input\"\n *\n * //      ┌─── string\n * //      ▼\n * const result = Match.value(input).pipe(\n *   // Match if the value is a number\n *   Match.when(Match.number, (n) => `number: ${n}`),\n *   // Match if the value is a string\n *   Match.when(Match.string, (s) => `string: ${s}`),\n *   // Ensure all possible cases are covered\n *   Match.exhaustive\n * )\n *\n * console.log(result)\n * // Output: \"string: some input\"\n * ```\n *\n * @category Model\n * @since 1.0.0\n */\nexport type Matcher<Input, Filters, RemainingApplied, Result, Provided, Return = any> =\n  | TypeMatcher<Input, Filters, RemainingApplied, Result, Return>\n  | ValueMatcher<Input, Filters, RemainingApplied, Result, Provided, Return>\n\n/**\n * @category Model\n * @since 1.0.0\n */\nexport interface TypeMatcher<in Input, out Filters, out Remaining, out Result, out Return = any> extends Pipeable {\n  readonly _tag: \"TypeMatcher\"\n  readonly [MatcherTypeId]: {\n    readonly _input: T.Contravariant<Input>\n    readonly _filters: T.Covariant<Filters>\n    readonly _remaining: T.Covariant<Remaining>\n    readonly _result: T.Covariant<Result>\n    readonly _return: T.Covariant<Return>\n  }\n  readonly cases: ReadonlyArray<Case>\n  add<I, R, RA, A>(_case: Case): TypeMatcher<I, R, RA, A>\n}\n\n/**\n * @category Model\n * @since 1.0.0\n */\nexport interface ValueMatcher<in Input, out Filters, out Remaining, out Result, out Provided, out Return = any>\n  extends Pipeable\n{\n  readonly _tag: \"ValueMatcher\"\n  readonly [MatcherTypeId]: {\n    readonly _input: T.Contravariant<Input>\n    readonly _filters: T.Covariant<Filters>\n    readonly _remaining: T.Covariant<Remaining>\n    readonly _result: T.Covariant<Result>\n    readonly _provided: T.Covariant<Result>\n    readonly _return: T.Covariant<Return>\n  }\n  readonly provided: Provided\n  readonly value: Either.Either<Provided, Remaining>\n  add<I, R, RA, A, Pr>(_case: Case): ValueMatcher<I, R, RA, A, Pr>\n}\n\n/**\n * @category Model\n * @since 1.0.0\n */\nexport type Case = When | Not\n\n/**\n * @category Model\n * @since 1.0.0\n */\nexport interface When {\n  readonly _tag: \"When\"\n  guard(u: unknown): boolean\n  evaluate(input: unknown): any\n}\n\n/**\n * @category Model\n * @since 1.0.0\n */\nexport interface Not {\n  readonly _tag: \"Not\"\n  guard(u: unknown): boolean\n  evaluate(input: unknown): any\n}\n\n/**\n * Creates a matcher for a specific type.\n *\n * **Details**\n *\n * This function defines a `Matcher` that operates on a given type, allowing you\n * to specify conditions for handling different cases. Once the matcher is\n * created, you can use pattern-matching functions like {@link when} to define\n * how different values should be processed.\n *\n * **Example** (Matching Numbers and Strings)\n *\n * ```ts\n * import { Match } from \"effect\"\n *\n * // Create a matcher for values that are either strings or numbers\n * //\n * //      ┌─── (u: string | number) => string\n * //      ▼\n * const match = Match.type<string | number>().pipe(\n *   // Match when the value is a number\n *   Match.when(Match.number, (n) => `number: ${n}`),\n *   // Match when the value is a string\n *   Match.when(Match.string, (s) => `string: ${s}`),\n *   // Ensure all possible cases are handled\n *   Match.exhaustive\n * )\n *\n * console.log(match(0))\n * // Output: \"number: 0\"\n *\n * console.log(match(\"hello\"))\n * // Output: \"string: hello\"\n * ```\n *\n * @see {@link value} for creating a matcher from a specific value.\n *\n * @category Creating a matcher\n * @since 1.0.0\n */\nexport const type: <I>() => Matcher<I, Types.Without<never>, I, never, never> = internal.type\n\n/**\n * Creates a matcher from a specific value.\n *\n * **Details**\n *\n * This function allows you to define a `Matcher` directly from a given value,\n * rather than from a type. This is useful when working with known values,\n * enabling structured pattern matching on objects, primitives, or any data\n * structure.\n *\n * Once the matcher is created, you can use pattern-matching functions like\n * {@link when} to define how different cases should be handled.\n *\n * **Example** (Matching an Object by Property)\n *\n * ```ts\n * import { Match } from \"effect\"\n *\n * const input = { name: \"John\", age: 30 }\n *\n * // Create a matcher for the specific object\n * const result = Match.value(input).pipe(\n *   // Match when the 'name' property is \"John\"\n *   Match.when(\n *     { name: \"John\" },\n *     (user) => `${user.name} is ${user.age} years old`\n *   ),\n *   // Provide a fallback if no match is found\n *   Match.orElse(() => \"Oh, not John\")\n * )\n *\n * console.log(result)\n * // Output: \"John is 30 years old\"\n * ```\n *\n * @see {@link type} for creating a matcher from a specific type.\n *\n * @category Creating a matcher\n * @since 1.0.0\n */\nexport const value: <const I>(\n  i: I\n) => Matcher<I, Types.Without<never>, I, never, I> = internal.value\n\n/**\n * @category Creating a matcher\n * @since 1.0.0\n */\nexport const valueTags: {\n  <\n    const I,\n    P extends\n      & { readonly [Tag in Types.Tags<\"_tag\", I> & string]: (_: Extract<I, { readonly _tag: Tag }>) => any }\n      & { readonly [Tag in Exclude<keyof P, Types.Tags<\"_tag\", I>>]: never }\n  >(fields: P): (input: I) => Unify<ReturnType<P[keyof P]>>\n  <\n    const I,\n    P extends\n      & { readonly [Tag in Types.Tags<\"_tag\", I> & string]: (_: Extract<I, { readonly _tag: Tag }>) => any }\n      & { readonly [Tag in Exclude<keyof P, Types.Tags<\"_tag\", I>>]: never }\n  >(input: I, fields: P): Unify<ReturnType<P[keyof P]>>\n} = internal.valueTags\n\n/**\n * @category Creating a matcher\n * @since 1.0.0\n */\nexport const typeTags: {\n  <I, Ret>(): <\n    P extends\n      & {\n        readonly [Tag in Types.Tags<\"_tag\", I> & string]: (\n          _: Extract<I, { readonly _tag: Tag }>\n        ) => Ret\n      }\n      & { readonly [Tag in Exclude<keyof P, Types.Tags<\"_tag\", I>>]: never }\n  >(fields: P) => (input: I) => Ret\n  <I>(): <\n    P extends\n      & {\n        readonly [Tag in Types.Tags<\"_tag\", I> & string]: (\n          _: Extract<I, { readonly _tag: Tag }>\n        ) => any\n      }\n      & { readonly [Tag in Exclude<keyof P, Types.Tags<\"_tag\", I>>]: never }\n  >(fields: P) => (input: I) => Unify<ReturnType<P[keyof P]>>\n} = internal.typeTags\n\n/**\n * Ensures that all branches of a matcher return a specific type.\n *\n * **Details**\n *\n * This function enforces a consistent return type across all pattern-matching\n * branches. By specifying a return type, TypeScript will check that every\n * matching condition produces a value of the expected type.\n *\n * **Important:** This function must be the first step in the matcher pipeline.\n * If used later, TypeScript will not enforce type consistency correctly.\n *\n * **Example** (Validating Return Type Consistency)\n *\n * ```ts\n * import { Match } from \"effect\"\n *\n * const match = Match.type<{ a: number } | { b: string }>().pipe(\n *   // Ensure all branches return a string\n *   Match.withReturnType<string>(),\n *   // ❌ Type error: 'number' is not assignable to type 'string'\n *   // @ts-expect-error\n *   Match.when({ a: Match.number }, (_) => _.a),\n *   // ✅ Correct: returns a string\n *   Match.when({ b: Match.string }, (_) => _.b),\n *   Match.exhaustive\n * )\n * ```\n *\n * @since 1.0.0\n */\nexport const withReturnType: <Ret>() => <I, F, R, A, Pr, _>(\n  self: Matcher<I, F, R, A, Pr, _>\n) => [Ret] extends [[A] extends [never] ? any : A] ? Matcher<I, F, R, A, Pr, Ret>\n  : \"withReturnType constraint does not extend Result type\" = internal.withReturnType\n\n/**\n * Defines a condition for matching values.\n *\n * **Details**\n *\n * This function enables pattern matching by checking whether a given value\n * satisfies a condition. It supports both direct value comparisons and\n * predicate functions. If the condition is met, the associated function is\n * executed.\n *\n * This function is useful when defining matchers that need to check for\n * specific values or apply logical conditions to determine a match. It works\n * well with structured objects and primitive types.\n *\n * **Example** (Matching with Values and Predicates)\n *\n * ```ts\n * import { Match } from \"effect\"\n *\n * // Create a matcher for objects with an \"age\" property\n * const match = Match.type<{ age: number }>().pipe(\n *   // Match when age is greater than 18\n *   Match.when({ age: (age) => age > 18 }, (user) => `Age: ${user.age}`),\n *   // Match when age is exactly 18\n *   Match.when({ age: 18 }, () => \"You can vote\"),\n *   // Fallback case for all other ages\n *   Match.orElse((user) => `${user.age} is too young`)\n * )\n *\n * console.log(match({ age: 20 }))\n * // Output: \"Age: 20\"\n *\n * console.log(match({ age: 18 }))\n * // Output: \"You can vote\"\n *\n * console.log(match({ age: 4 }))\n * // Output: \"4 is too young\"\n * ```\n *\n * @see {@link whenOr} Use this when multiple patterns should match in a single\n * condition.\n * @see {@link whenAnd} Use this when a value must match all provided patterns.\n * @see {@link orElse} Provides a fallback when no patterns match.\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const when: <\n  R,\n  const P extends Types.PatternPrimitive<R> | Types.PatternBase<R>,\n  Ret,\n  Fn extends (_: Types.WhenMatch<R, P>) => Ret\n>(\n  pattern: P,\n  f: Fn\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddWithout<F, Types.PForExclude<P>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Types.PForExclude<P>>>,\n  A | ReturnType<Fn>,\n  Pr,\n  Ret\n> = internal.when\n\n/**\n * Matches one of multiple patterns in a single condition.\n *\n * **Details**\n *\n * This function allows defining a condition where a value matches any of the\n * provided patterns. If a match is found, the associated function is executed.\n * It simplifies cases where multiple patterns share the same handling logic.\n *\n * Unlike {@link when}, which requires separate conditions for each pattern,\n * this function enables combining them into a single statement, making the\n * matcher more concise.\n *\n * @example\n * ```ts\n * import { Match } from \"effect\"\n *\n * type ErrorType =\n *   | { readonly _tag: \"NetworkError\"; readonly message: string }\n *   | { readonly _tag: \"TimeoutError\"; readonly duration: number }\n *   | { readonly _tag: \"ValidationError\"; readonly field: string }\n *\n * const handleError = Match.type<ErrorType>().pipe(\n *   Match.whenOr(\n *     { _tag: \"NetworkError\" },\n *     { _tag: \"TimeoutError\" },\n *     () => \"Retry the request\"\n *   ),\n *   Match.when({ _tag: \"ValidationError\" }, (_) => `Invalid field: ${_.field}`),\n *   Match.exhaustive\n * )\n *\n * console.log(handleError({ _tag: \"NetworkError\", message: \"No connection\" }))\n * // Output: \"Retry the request\"\n *\n * console.log(handleError({ _tag: \"ValidationError\", field: \"email\" }))\n * // Output: \"Invalid field: email\"\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const whenOr: <\n  R,\n  const P extends ReadonlyArray<Types.PatternPrimitive<R> | Types.PatternBase<R>>,\n  Ret,\n  Fn extends (_: Types.WhenMatch<R, P[number]>) => Ret\n>(\n  ...args: [...patterns: P, f: Fn]\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddWithout<F, Types.PForExclude<P[number]>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Types.PForExclude<P[number]>>>,\n  A | ReturnType<Fn>,\n  Pr,\n  Ret\n> = internal.whenOr\n\n/**\n * Matches a value that satisfies all provided patterns.\n *\n * **Details**\n *\n * This function allows defining a condition where a value must match all the\n * given patterns simultaneously. If the value satisfies every pattern, the\n * associated function is executed.\n *\n * Unlike {@link when}, which matches a single pattern at a time, this function\n * ensures that multiple conditions are met before executing the callback. It is\n * useful when checking for values that need to fulfill multiple criteria at\n * once.\n *\n * @example\n * ```ts\n * import { Match } from \"effect\"\n *\n * type User = { readonly age: number; readonly role: \"admin\" | \"user\" }\n *\n * const checkUser = Match.type<User>().pipe(\n *   Match.whenAnd(\n *     { age: (n) => n >= 18 },\n *     { role: \"admin\" },\n *     () => \"Admin access granted\"\n *   ),\n *   Match.orElse(() => \"Access denied\")\n * )\n *\n * console.log(checkUser({ age: 20, role: \"admin\" }))\n * // Output: \"Admin access granted\"\n *\n * console.log(checkUser({ age: 20, role: \"user\" }))\n * // Output: \"Access denied\"\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const whenAnd: <\n  R,\n  const P extends ReadonlyArray<Types.PatternPrimitive<R> | Types.PatternBase<R>>,\n  Ret,\n  Fn extends (_: Types.WhenMatch<R, T.UnionToIntersection<P[number]>>) => Ret\n>(\n  ...args: [...patterns: P, f: Fn]\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddWithout<F, Types.PForExclude<T.UnionToIntersection<P[number]>>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Types.PForExclude<T.UnionToIntersection<P[number]>>>>,\n  A | ReturnType<Fn>,\n  Pr\n> = internal.whenAnd\n\n/**\n * Matches values based on a specified discriminant field.\n *\n * **Details**\n *\n * This function is used to define pattern matching on objects that follow a\n * **discriminated union** structure, where a specific field (e.g., `type`,\n * `kind`, `_tag`) determines the variant of the object. It allows matching\n * multiple values of the discriminant and provides a function to handle the\n * matched cases.\n *\n * @example\n * ```ts\n * import { Match, pipe } from \"effect\"\n *\n * const match = pipe(\n *   Match.type<{ type: \"A\"; a: string } | { type: \"B\"; b: number } | { type: \"C\"; c: boolean }>(),\n *   Match.discriminator(\"type\")(\"A\", \"B\", (_) => `A or B: ${_.type}`),\n *   Match.discriminator(\"type\")(\"C\", (_) => `C(${_.c})`),\n *   Match.exhaustive\n * )\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const discriminator: <D extends string>(\n  field: D\n) => <R, P extends Types.Tags<D, R> & string, Ret, Fn extends (_: Extract<R, Record<D, P>>) => Ret>(\n  ...pattern: [first: P, ...values: Array<P>, f: Fn]\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddWithout<F, Extract<R, Record<D, P>>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<D, P>>>>,\n  A | ReturnType<Fn>,\n  Pr,\n  Ret\n> = internal.discriminator\n\n/**\n * Matches values where a specified field starts with a given prefix.\n *\n * **Details**\n *\n * This function is useful for working with discriminated unions where the\n * discriminant field follows a hierarchical or namespaced structure. It allows\n * you to match values based on whether the specified field starts with a given\n * prefix, making it easier to handle grouped cases.\n *\n * Instead of checking for exact matches, this function lets you match values\n * that share a common prefix. For example, if your discriminant field contains\n * hierarchical names like `\"A\"`, `\"A.A\"`, and `\"B\"`, you can match all values\n * starting with `\"A\"` using a single rule.\n *\n * @example\n * ```ts\n * import { Match, pipe } from \"effect\"\n *\n * const match = pipe(\n *   Match.type<{ type: \"A\" } | { type: \"B\" } | { type: \"A.A\" } | {}>(),\n *   Match.discriminatorStartsWith(\"type\")(\"A\", (_) => 1 as const),\n *   Match.discriminatorStartsWith(\"type\")(\"B\", (_) => 2 as const),\n *   Match.orElse((_) => 3 as const)\n * )\n *\n * console.log(match({ type: \"A\" })) // 1\n * console.log(match({ type: \"B\" })) // 2\n * console.log(match({ type: \"A.A\" })) // 1\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const discriminatorStartsWith: <D extends string>(\n  field: D\n) => <R, P extends string, Ret, Fn extends (_: Extract<R, Record<D, `${P}${string}`>>) => Ret>(\n  pattern: P,\n  f: Fn\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddWithout<F, Extract<R, Record<D, `${P}${string}`>>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<D, `${P}${string}`>>>>,\n  A | ReturnType<Fn>,\n  Pr,\n  Ret\n> = internal.discriminatorStartsWith\n\n/**\n * Matches values based on a field that serves as a discriminator, mapping each\n * possible value to a corresponding handler.\n *\n * **Details**\n *\n * This function simplifies working with discriminated unions by letting you\n * define a set of handlers for each possible value of a given field. Instead of\n * chaining multiple calls to {@link discriminator}, this function allows\n * defining all possible cases at once using an object where the keys are the\n * possible values of the field, and the values are the corresponding handler\n * functions.\n *\n * @example\n * ```ts\n * import { Match, pipe } from \"effect\"\n *\n * const match = pipe(\n *   Match.type<{ type: \"A\"; a: string } | { type: \"B\"; b: number } | { type: \"C\"; c: boolean }>(),\n *   Match.discriminators(\"type\")({\n *     A: (a) => a.a,\n *     B: (b) => b.b,\n *     C: (c) => c.c\n *   }),\n *   Match.exhaustive\n * )\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const discriminators: <D extends string>(\n  field: D\n) => <\n  R,\n  Ret,\n  P extends\n    & { readonly [Tag in Types.Tags<D, R> & string]?: ((_: Extract<R, Record<D, Tag>>) => Ret) | undefined }\n    & { readonly [Tag in Exclude<keyof P, Types.Tags<D, R>>]: never }\n>(\n  fields: P\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddWithout<F, Extract<R, Record<D, keyof P>>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<D, keyof P>>>>,\n  A | ReturnType<P[keyof P] & {}>,\n  Pr,\n  Ret\n> = internal.discriminators\n\n/**\n * Matches values based on a discriminator field and **ensures all cases are\n * handled**.\n *\n * **Details*+\n *\n * This function is similar to {@link discriminators}, but **requires that all\n * possible cases** are explicitly handled. It is useful when working with\n * discriminated unions, where a specific field (e.g., `\"type\"`) determines the\n * shape of an object. Each possible value of the field must have a\n * corresponding handler, ensuring **exhaustiveness checking** at compile time.\n *\n * This function **does not require** `Match.exhaustive` at the end of the\n * pipeline because it enforces exhaustiveness by design.\n *\n * @example\n * ```ts\n * import { Match, pipe } from \"effect\"\n *\n * const match = pipe(\n *   Match.type<{ type: \"A\"; a: string } | { type: \"B\"; b: number } | { type: \"C\"; c: boolean }>(),\n *   Match.discriminatorsExhaustive(\"type\")({\n *     A: (a) => a.a,\n *     B: (b) => b.b,\n *     C: (c) => c.c\n *   })\n * )\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const discriminatorsExhaustive: <D extends string>(\n  field: D\n) => <\n  R,\n  Ret,\n  P extends\n    & { readonly [Tag in Types.Tags<D, R> & string]: (_: Extract<R, Record<D, Tag>>) => Ret }\n    & { readonly [Tag in Exclude<keyof P, Types.Tags<D, R>>]: never }\n>(\n  fields: P\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => [Pr] extends [never] ? (u: I) => Unify<A | ReturnType<P[keyof P]>> : Unify<A | ReturnType<P[keyof P]>> =\n  internal.discriminatorsExhaustive\n\n/**\n * The `Match.tag` function allows pattern matching based on the `_tag` field in\n * a [Discriminated Union](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions).\n * You can specify multiple tags to match within a single pattern.\n *\n * **Note**\n *\n * The `Match.tag` function relies on the convention within the Effect ecosystem\n * of naming the tag field as `\"_tag\"`. Ensure that your discriminated unions\n * follow this naming convention for proper functionality.\n *\n * **Example** (Matching a Discriminated Union by Tag)\n *\n * ```ts\n * import { Match } from \"effect\"\n *\n * type Event =\n *   | { readonly _tag: \"fetch\" }\n *   | { readonly _tag: \"success\"; readonly data: string }\n *   | { readonly _tag: \"error\"; readonly error: Error }\n *   | { readonly _tag: \"cancel\" }\n *\n * // Create a Matcher for Either<number, string>\n * const match = Match.type<Event>().pipe(\n *   // Match either \"fetch\" or \"success\"\n *   Match.tag(\"fetch\", \"success\", () => `Ok!`),\n *   // Match \"error\" and extract the error message\n *   Match.tag(\"error\", (event) => `Error: ${event.error.message}`),\n *   // Match \"cancel\"\n *   Match.tag(\"cancel\", () => \"Cancelled\"),\n *   Match.exhaustive\n * )\n *\n * console.log(match({ _tag: \"success\", data: \"Hello\" }))\n * // Output: \"Ok!\"\n *\n * console.log(match({ _tag: \"error\", error: new Error(\"Oops!\") }))\n * // Output: \"Error: Oops!\"\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const tag: <\n  R,\n  P extends Types.Tags<\"_tag\", R> & string,\n  Ret,\n  Fn extends (_: Extract<R, Record<\"_tag\", P>>) => Ret\n>(\n  ...pattern: [first: P, ...values: Array<P>, f: Fn]\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddWithout<F, Extract<R, Record<\"_tag\", P>>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<\"_tag\", P>>>>,\n  ReturnType<Fn> | A,\n  Pr,\n  Ret\n> = internal.tag\n\n/**\n * Matches values where the `_tag` field starts with a given prefix.\n *\n * **Details**\n *\n * This function allows you to match on values in a **discriminated union**\n * based on whether the `_tag` field starts with a specified prefix. It is\n * useful for handling hierarchical or namespaced tags, where multiple related\n * cases share a common prefix.\n *\n * @example\n * ```ts\n * import { Match, pipe } from \"effect\"\n *\n * const match = pipe(\n *   Match.type<{ _tag: \"A\" } | { _tag: \"B\" } | { _tag: \"A.A\" } | {}>(),\n *   Match.tagStartsWith(\"A\", (_) => 1 as const),\n *   Match.tagStartsWith(\"B\", (_) => 2 as const),\n *   Match.orElse((_) => 3 as const)\n * )\n *\n * console.log(match({ _tag: \"A\" })) // 1\n * console.log(match({ _tag: \"B\" })) // 2\n * console.log(match({ _tag: \"A.A\" })) // 1\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const tagStartsWith: <\n  R,\n  P extends string,\n  Ret,\n  Fn extends (_: Extract<R, Record<\"_tag\", `${P}${string}`>>) => Ret\n>(\n  pattern: P,\n  f: Fn\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddWithout<F, Extract<R, Record<\"_tag\", `${P}${string}`>>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<\"_tag\", `${P}${string}`>>>>,\n  ReturnType<Fn> | A,\n  Pr,\n  Ret\n> = internal.tagStartsWith\n\n/**\n * Matches values based on their `_tag` field, mapping each tag to a\n * corresponding handler.\n *\n * **Details**\n *\n * This function provides a way to handle discriminated unions by mapping `_tag`\n * values to specific functions. Each handler receives the matched value and\n * returns a transformed result. If all possible tags are handled, you can\n * enforce exhaustiveness using `Match.exhaustive` to ensure no case is missed.\n *\n * @example\n * ```ts\n * import { Match, pipe } from \"effect\"\n *\n * const match = pipe(\n *   Match.type<{ _tag: \"A\"; a: string } | { _tag: \"B\"; b: number } | { _tag: \"C\"; c: boolean }>(),\n *   Match.tags({\n *     A: (a) => a.a,\n *     B: (b) => b.b,\n *     C: (c) => c.c\n *   }),\n *   Match.exhaustive\n * )\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const tags: <\n  R,\n  Ret,\n  P extends\n    & { readonly [Tag in Types.Tags<\"_tag\", R> & string]?: ((_: Extract<R, Record<\"_tag\", Tag>>) => Ret) | undefined }\n    & { readonly [Tag in Exclude<keyof P, Types.Tags<\"_tag\", R>>]: never }\n>(\n  fields: P\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddWithout<F, Extract<R, Record<\"_tag\", keyof P>>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<\"_tag\", keyof P>>>>,\n  A | ReturnType<P[keyof P] & {}>,\n  Pr,\n  Ret\n> = internal.tags\n\n/**\n * Matches values based on their `_tag` field and requires handling of all\n * possible cases.\n *\n * **Details**\n *\n * This function is designed for **discriminated unions** where every possible\n * `_tag` value must have a corresponding handler. Unlike {@link tags}, this\n * function ensures **exhaustiveness**, meaning all cases must be explicitly\n * handled. If a `_tag` value is missing from the mapping, TypeScript will\n * report an error.\n *\n * @example\n * ```ts\n * import { Match, pipe } from \"effect\"\n *\n * const match = pipe(\n *   Match.type<{ _tag: \"A\"; a: string } | { _tag: \"B\"; b: number } | { _tag: \"C\"; c: boolean }>(),\n *   Match.tagsExhaustive({\n *     A: (a) => a.a,\n *     B: (b) => b.b,\n *     C: (c) => c.c\n *   })\n * )\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const tagsExhaustive: <\n  R,\n  Ret,\n  P extends\n    & { readonly [Tag in Types.Tags<\"_tag\", R> & string]: (_: Extract<R, Record<\"_tag\", Tag>>) => Ret }\n    & { readonly [Tag in Exclude<keyof P, Types.Tags<\"_tag\", R>>]: never }\n>(\n  fields: P\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => [Pr] extends [never] ? (u: I) => Unify<A | ReturnType<P[keyof P]>> : Unify<A | ReturnType<P[keyof P]>> =\n  internal.tagsExhaustive\n\n/**\n * Excludes a specific value from matching while allowing all others.\n *\n * **Details**\n *\n * This function is useful when you need to **handle all values except one or\n * more specific cases**. Instead of listing all possible matches manually, this\n * function simplifies the logic by allowing you to specify values to exclude.\n * Any excluded value will bypass the provided function and continue matching\n * through other cases.\n *\n * **Example** (Ignoring a Specific Value)\n *\n * ```ts\n * import { Match } from \"effect\"\n *\n * // Create a matcher for string or number values\n * const match = Match.type<string | number>().pipe(\n *   // Match any value except \"hi\", returning \"ok\"\n *   Match.not(\"hi\", () => \"ok\"),\n *   // Fallback case for when the value is \"hi\"\n *   Match.orElse(() => \"fallback\")\n * )\n *\n * console.log(match(\"hello\"))\n * // Output: \"ok\"\n *\n * console.log(match(\"hi\"))\n * // Output: \"fallback\"\n * ```\n *\n * @category Defining patterns\n * @since 1.0.0\n */\nexport const not: <\n  R,\n  const P extends Types.PatternPrimitive<R> | Types.PatternBase<R>,\n  Ret,\n  Fn extends (_: Types.NotMatch<R, P>) => Ret\n>(\n  pattern: P,\n  f: Fn\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddOnly<F, Types.WhenMatch<R, P>>,\n  Types.ApplyFilters<I, Types.AddOnly<F, Types.WhenMatch<R, P>>>,\n  A | ReturnType<Fn>,\n  Pr,\n  Ret\n> = internal.not\n\n/**\n * Matches non-empty strings.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const nonEmptyString: SafeRefinement<string, never> = internal.nonEmptyString\n\n/**\n * Matches a specific set of literal values (e.g., `Match.is(\"a\", 42, true)`).\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const is: <\n  Literals extends ReadonlyArray<string | number | bigint | boolean | null>\n>(...literals: Literals) => SafeRefinement<Literals[number]> = internal.is\n\n/**\n * Matches values of type `string`.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const string: Predicate.Refinement<unknown, string> = Predicate.isString\n\n/**\n * Matches values of type `number`.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const number: Predicate.Refinement<unknown, number> = Predicate.isNumber\n\n/**\n * Matches any value without restrictions.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const any: SafeRefinement<unknown, any> = internal.any\n\n/**\n * Matches any defined (non-null and non-undefined) value.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const defined: <A>(u: A) => u is A & {} = internal.defined\n\n/**\n * Matches values of type `boolean`.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const boolean: Predicate.Refinement<unknown, boolean> = Predicate.isBoolean\n\nconst _undefined: Predicate.Refinement<unknown, undefined> = Predicate.isUndefined\nexport {\n  /**\n   * Matches the value `undefined`.\n   *\n   * @category Predicates\n   * @since 1.0.0\n   */\n  _undefined as undefined\n}\n\nconst _null: Predicate.Refinement<unknown, null> = Predicate.isNull\nexport {\n  /**\n   * Matches the value `null`.\n   *\n   * @category Predicates\n   * @since 1.0.0\n   */\n  _null as null\n}\n\n/**\n * Matches values of type `bigint`.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const bigint: Predicate.Refinement<unknown, bigint> = Predicate.isBigInt\n\n/**\n * Matches values of type `symbol`.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const symbol: Predicate.Refinement<unknown, symbol> = Predicate.isSymbol\n\n/**\n * Matches values that are instances of `Date`.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const date: Predicate.Refinement<unknown, Date> = Predicate.isDate\n\n/**\n * Matches objects where keys are `string` or `symbol` and values are `unknown`.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const record: Predicate.Refinement<unknown, { [x: string | symbol]: unknown }> = Predicate.isRecord\n\n/**\n * Matches instances of a given class.\n *\n * @category Predicates\n * @since 1.0.0\n */\nexport const instanceOf: <A extends abstract new(...args: any) => any>(\n  constructor: A\n) => SafeRefinement<InstanceType<A>, never> = internal.instanceOf\n\n/**\n * @category Predicates\n * @since 1.0.0\n */\nexport const instanceOfUnsafe: <A extends abstract new(...args: any) => any>(\n  constructor: A\n) => SafeRefinement<InstanceType<A>, InstanceType<A>> = internal.instanceOf\n\n/**\n * Provides a fallback value when no patterns match.\n *\n * **Details**\n *\n * This function ensures that a matcher always returns a valid result, even if\n * no defined patterns match. It acts as a default case, similar to the\n * `default` clause in a `switch` statement or the final `else` in an `if-else`\n * chain.\n *\n * **Example** (Providing a Default Value When No Patterns Match)\n *\n * ```ts\n * import { Match } from \"effect\"\n *\n * // Create a matcher for string or number values\n * const match = Match.type<string | number>().pipe(\n *   // Match when the value is \"a\"\n *   Match.when(\"a\", () => \"ok\"),\n *   // Fallback when no patterns match\n *   Match.orElse(() => \"fallback\")\n * )\n *\n * console.log(match(\"a\"))\n * // Output: \"ok\"\n *\n * console.log(match(\"b\"))\n * // Output: \"fallback\"\n * ```\n *\n * @category Completion\n * @since 1.0.0\n */\nexport const orElse: <RA, Ret, F extends (_: RA) => Ret>(\n  f: F\n) => <I, R, A, Pr>(\n  self: Matcher<I, R, RA, A, Pr, Ret>\n) => [Pr] extends [never] ? (input: I) => Unify<ReturnType<F> | A> : Unify<ReturnType<F> | A> = internal.orElse\n\n// TODO(4.0): Rename to \"orThrow\"? Like Either.getOrThrow\n/**\n * Throws an error if no pattern matches.\n *\n * **Details**\n *\n * This function finalizes a matcher by ensuring that if no patterns match, an\n * error is thrown. It is useful when all cases should be covered, and any\n * unexpected input should trigger an error instead of returning a default\n * value.\n *\n * When used, this function removes the need for an explicit fallback case and\n * ensures that an unmatched value is never silently ignored.\n *\n * @category Completion\n * @since 1.0.0\n */\nexport const orElseAbsurd: <I, R, RA, A, Pr, Ret>(\n  self: Matcher<I, R, RA, A, Pr, Ret>\n) => [Pr] extends [never] ? (input: I) => Unify<A> : Unify<A> = internal.orElseAbsurd\n\n/**\n * Wraps the match result in an `Either`, distinguishing matched and unmatched\n * cases.\n *\n * **Details**\n *\n * This function ensures that the result of a matcher is always wrapped in an\n * `Either`, allowing clear differentiation between successful matches\n * (`Right(value)`) and cases where no pattern matched (`Left(unmatched\n * value)`).\n *\n * This approach is particularly useful when handling optional values or when an\n * unmatched case should be explicitly handled rather than returning a default\n * value or throwing an error.\n *\n * **Example** (Extracting a User Role with `Match.either`)\n *\n * ```ts\n * import { Match } from \"effect\"\n *\n * type User = { readonly role: \"admin\" | \"editor\" | \"viewer\" }\n *\n * // Create a matcher to extract user roles\n * const getRole = Match.type<User>().pipe(\n *   Match.when({ role: \"admin\" }, () => \"Has full access\"),\n *   Match.when({ role: \"editor\" }, () => \"Can edit content\"),\n *   Match.either // Wrap the result in an Either\n * )\n *\n * console.log(getRole({ role: \"admin\" }))\n * // Output: { _id: 'Either', _tag: 'Right', right: 'Has full access' }\n *\n * console.log(getRole({ role: \"viewer\" }))\n * // Output: { _id: 'Either', _tag: 'Left', left: { role: 'viewer' } }\n * ```\n *\n * @category Completion\n * @since 1.0.0\n */\nexport const either: <I, F, R, A, Pr, Ret>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => [Pr] extends [never] ? (input: I) => Either.Either<Unify<A>, R> : Either.Either<Unify<A>, R> = internal.either\n\n/**\n * Wraps the match result in an `Option`, representing an optional match.\n *\n * **Details**\n *\n * This function ensures that the result of a matcher is wrapped in an `Option`,\n * making it easy to handle cases where no pattern matches. If a match is found,\n * it returns `Some(value)`, otherwise, it returns `None`.\n *\n * This is useful in cases where a missing match is expected and should be\n * handled explicitly rather than throwing an error or returning a default\n * value.\n *\n * **Example** (Extracting a User Role with `Match.option`)\n *\n * ```ts\n * import { Match } from \"effect\"\n *\n * type User = { readonly role: \"admin\" | \"editor\" | \"viewer\" }\n *\n * // Create a matcher to extract user roles\n * const getRole = Match.type<User>().pipe(\n *   Match.when({ role: \"admin\" }, () => \"Has full access\"),\n *   Match.when({ role: \"editor\" }, () => \"Can edit content\"),\n *   Match.option // Wrap the result in an Option\n * )\n *\n * console.log(getRole({ role: \"admin\" }))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'Has full access' }\n *\n * console.log(getRole({ role: \"viewer\" }))\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Completion\n * @since 1.0.0\n */\nexport const option: <I, F, R, A, Pr, Ret>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => [Pr] extends [never] ? (input: I) => Option.Option<Unify<A>> : Option.Option<Unify<A>> = internal.option\n\n/**\n * The `Match.exhaustive` method finalizes the pattern matching process by\n * ensuring that all possible cases are accounted for. If any case is missing,\n * TypeScript will produce a type error. This is particularly useful when\n * working with unions, as it helps prevent unintended gaps in pattern matching.\n *\n * **Example** (Ensuring All Cases Are Covered)\n *\n * ```ts\n * import { Match } from \"effect\"\n *\n * // Create a matcher for string or number values\n * const match = Match.type<string | number>().pipe(\n *   // Match when the value is a number\n *   Match.when(Match.number, (n) => `number: ${n}`),\n *   // Mark the match as exhaustive, ensuring all cases are handled\n *   // TypeScript will throw an error if any case is missing\n *   // @ts-expect-error Type 'string' is not assignable to type 'never'\n *   Match.exhaustive\n * )\n * ```\n *\n * @category Completion\n * @since 1.0.0\n */\nexport const exhaustive: <I, F, A, Pr, Ret>(\n  self: Matcher<I, F, never, A, Pr, Ret>\n) => [Pr] extends [never] ? (u: I) => Unify<A> : Unify<A> = internal.exhaustive\n\n/**\n * @since 1.0.0\n * @category Symbols\n */\nexport const SafeRefinementId = Symbol.for(\"effect/SafeRefinement\")\n\n/**\n * @since 1.0.0\n * @category Symbols\n */\nexport type SafeRefinementId = typeof SafeRefinementId\n\n/**\n * @category Model\n * @since 1.0.0\n */\nexport interface SafeRefinement<in A, out R = A> {\n  readonly [SafeRefinementId]: (a: A) => R\n}\n\nconst Fail = Symbol.for(\"effect/Fail\")\ntype Fail = typeof Fail\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Types {\n  /**\n   * @since 1.0.0\n   */\n  export type WhenMatch<R, P> =\n    // check for any\n    [0] extends [1 & R] ? ResolvePred<P> :\n      P extends SafeRefinement<infer SP, never> ? SP\n      : P extends Predicate.Refinement<infer _R, infer RP>\n      // try to narrow refinement\n        ? [Extract<R, RP>] extends [infer X] ? [X] extends [never]\n            // fallback to original refinement\n            ? RP\n          : X\n        : never\n      : P extends PredicateA<infer PP> ? PP\n      : ExtractMatch<R, P>\n\n  /**\n   * @since 1.0.0\n   */\n  export type NotMatch<R, P> = Exclude<R, ExtractMatch<R, PForNotMatch<P>>>\n\n  type PForNotMatch<P> = [ToInvertedRefinement<P>] extends [infer X] ? X\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type PForMatch<P> = [ResolvePred<P>] extends [infer X] ? X\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type PForExclude<P> = [SafeRefinementR<ToSafeRefinement<P>>] extends [infer X] ? X\n    : never\n\n  // utilities\n  type PredicateA<A> = Predicate.Predicate<A> | Predicate.Refinement<A, A>\n\n  type SafeRefinementR<A> = A extends never ? never\n    : A extends SafeRefinement<infer _, infer R> ? R\n    : A extends Function ? A\n    : A extends Record<string, any> ? { [K in keyof A]: SafeRefinementR<A[K]> }\n    : A\n\n  type ResolvePred<A, Input = any> = A extends never ? never\n    : A extends SafeRefinement<infer _A, infer _R> ? _A\n    : A extends Predicate.Refinement<Input, infer P> ? P\n    : A extends Predicate.Predicate<infer P> ? P\n    : A extends Record<string, any> ? { [K in keyof A]: ResolvePred<A[K]> }\n    : A\n\n  type ToSafeRefinement<A> = A extends never ? never\n    : A extends Predicate.Refinement<any, infer P> ? SafeRefinement<P, P>\n    : A extends Predicate.Predicate<infer P> ? SafeRefinement<P, never>\n    : A extends SafeRefinement<any> ? A\n    : A extends Record<string, any> ? { [K in keyof A]: ToSafeRefinement<A[K]> }\n    : NonLiteralsTo<A, never>\n\n  type ToInvertedRefinement<A> = A extends never ? never\n    : A extends Predicate.Refinement<any, infer P> ? SafeRefinement<P>\n    : A extends Predicate.Predicate<infer _P> ? SafeRefinement<never>\n    : A extends SafeRefinement<infer _A, infer _R> ? SafeRefinement<_R>\n    : A extends Record<string, any> ? { [K in keyof A]: ToInvertedRefinement<A[K]> }\n    : NonLiteralsTo<A, never>\n\n  type NonLiteralsTo<A, T> = [A] extends [string | number | boolean | bigint] ? [string] extends [A] ? T\n    : [number] extends [A] ? T\n    : [boolean] extends [A] ? T\n    : [bigint] extends [A] ? T\n    : A\n    : A\n\n  /**\n   * @since 1.0.0\n   */\n  export type PatternBase<A> = A extends ReadonlyArray<infer _T> ? ReadonlyArray<any> | PatternPrimitive<A>\n    : A extends Record<string, any> ? Partial<\n        { [K in keyof A]: PatternPrimitive<A[K] & {}> | PatternBase<A[K] & {}> }\n      >\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type PatternPrimitive<A> = PredicateA<A> | A | SafeRefinement<any>\n\n  /**\n   * @since 1.0.0\n   */\n  export interface Without<out X> {\n    readonly _tag: \"Without\"\n    readonly _X: X\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  export interface Only<out X> {\n    readonly _tag: \"Only\"\n    readonly _X: X\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  export type AddWithout<A, X> = [A] extends [Without<infer WX>] ? Without<X | WX>\n    : [A] extends [Only<infer OX>] ? Only<Exclude<OX, X>>\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type AddOnly<A, X> = [A] extends [Without<infer WX>] ? [X] extends [WX] ? never\n    : Only<X>\n    : [A] extends [Only<infer OX>] ? [X] extends [OX] ? Only<X>\n      : never\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type ApplyFilters<I, A> = A extends Only<infer X> ? X\n    : A extends Without<infer X> ? Exclude<I, X>\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type Tags<D extends string, P> = P extends Record<D, infer X> ? X : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type ArrayToIntersection<A extends ReadonlyArray<any>> = T.UnionToIntersection<\n    A[number]\n  >\n\n  /**\n   * @since 1.0.0\n   */\n  export type ExtractMatch<I, P> = [ExtractAndNarrow<I, P>] extends [infer EI] ? EI\n    : never\n\n  type Replace<A, B> = A extends Function ? A\n    : A extends Record<string | number, any> ? { [K in keyof A]: K extends keyof B ? Replace<A[K], B[K]> : A[K] }\n    : [B] extends [A] ? B\n    : A\n\n  type MaybeReplace<I, P> = [P] extends [I] ? P\n    : [I] extends [P] ? Replace<I, P>\n    : Fail\n\n  type BuiltInObjects =\n    | Function\n    | Date\n    | RegExp\n    | Generator\n    | { readonly [Symbol.toStringTag]: string }\n\n  type IsPlainObject<T> = T extends BuiltInObjects ? false\n    : T extends Record<string, any> ? true\n    : false\n\n  type Simplify<A> = { [K in keyof A]: A[K] } & {}\n\n  type ExtractAndNarrow<Input, P> = P extends Predicate.Refinement<infer _In, infer _Out> ?\n    _Out extends Input ? Extract<_Out, Input>\n    : Extract<Input, _Out> :\n    P extends SafeRefinement<infer _In, infer _R> ? [0] extends [1 & _R] ? Input\n      : _In extends Input ? Extract<_In, Input>\n      : Extract<Input, _In>\n    : P extends Predicate.Predicate<infer _In> ? Extract<Input, _In>\n    : Input extends infer I ? Exclude<\n        I extends ReadonlyArray<any> ? P extends ReadonlyArray<any> ? {\n              readonly [K in keyof I]: K extends keyof P ? ExtractAndNarrow<I[K], P[K]>\n                : I[K]\n            } extends infer R ? Fail extends R[keyof R] ? never\n              : R\n            : never\n          : never\n          : IsPlainObject<I> extends true ? string extends keyof I ? I extends P ? I\n              : never\n            : symbol extends keyof I ? I extends P ? I\n              : never\n            : Simplify<\n              & { [RK in Extract<keyof I, keyof P>]-?: ExtractAndNarrow<I[RK], P[RK]> }\n              & Omit<I, keyof P>\n            > extends infer R ? keyof P extends NonFailKeys<R> ? R\n              : never\n            : never\n          : MaybeReplace<I, P> extends infer R ? [I] extends [R] ? I\n            : R\n          : never,\n        Fail\n      > :\n    never\n\n  type NonFailKeys<A> = keyof A & {} extends infer K ? K extends keyof A ? A[K] extends Fail ? never : K\n    : never :\n    never\n}\n"
  },
  {
    "path": "packages/effect/src/MergeDecision.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport * as internal from \"./internal/channel/mergeDecision.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MergeDecisionTypeId: unique symbol = internal.MergeDecisionTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MergeDecisionTypeId = typeof MergeDecisionTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MergeDecision<out R, in E0, in Z0, out E, out Z> extends MergeDecision.Variance<R, E0, Z0, E, Z> {}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace MergeDecision {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out R, in E0, in Z0, out E, out Z> {\n    readonly [MergeDecisionTypeId]: {\n      _R: Types.Covariant<R>\n      _E0: Types.Contravariant<E0>\n      _Z0: Types.Contravariant<Z0>\n      _E: Types.Covariant<E>\n      _Z: Types.Covariant<Z>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Done: <Z, E, R>(effect: Effect.Effect<Z, E, R>) => MergeDecision<R, unknown, unknown, E, Z> = internal.Done\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Await: <R, E0, Z0, E, Z>(\n  f: (exit: Exit.Exit<Z0, E0>) => Effect.Effect<Z, E, R>\n) => MergeDecision<R, E0, Z0, E, Z> = internal.Await\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const AwaitConst: <Z, E, R>(effect: Effect.Effect<Z, E, R>) => MergeDecision<R, unknown, unknown, E, Z> =\n  internal.AwaitConst\n\n/**\n * Returns `true` if the specified value is a `MergeDecision`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isMergeDecision: (u: unknown) => u is MergeDecision<unknown, unknown, unknown, unknown, unknown> =\n  internal.isMergeDecision\n\n/**\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <R, E0, Z0, E, Z, Z2>(\n    options: {\n      readonly onDone: (effect: Effect.Effect<Z, E, R>) => Z2\n      readonly onAwait: (f: (exit: Exit.Exit<Z0, E0>) => Effect.Effect<Z, E, R>) => Z2\n    }\n  ): (self: MergeDecision<R, E0, Z0, E, Z>) => Z2\n  <R, E0, Z0, E, Z, Z2>(\n    self: MergeDecision<R, E0, Z0, E, Z>,\n    options: {\n      readonly onDone: (effect: Effect.Effect<Z, E, R>) => Z2\n      readonly onAwait: (f: (exit: Exit.Exit<Z0, E0>) => Effect.Effect<Z, E, R>) => Z2\n    }\n  ): Z2\n} = internal.match\n"
  },
  {
    "path": "packages/effect/src/MergeState.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport * as internal from \"./internal/channel/mergeState.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MergeStateTypeId: unique symbol = internal.MergeStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MergeStateTypeId = typeof MergeStateTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> =\n  | BothRunning<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>\n  | LeftDone<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>\n  | RightDone<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>\n\n/**\n * @since 2.0.0\n */\nexport declare namespace MergeState {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Proto {\n    readonly [MergeStateTypeId]: MergeStateTypeId\n  }\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface BothRunning<_Env, out Err, out Err1, _Err2, out Elem, out Done, out Done1, _Done2>\n  extends MergeState.Proto\n{\n  readonly _tag: \"BothRunning\"\n  readonly left: Fiber.Fiber<Either.Either<Elem, Done>, Err>\n  readonly right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface LeftDone<out Env, _Err, in Err1, out Err2, _Elem, _Done, in Done1, out Done2>\n  extends MergeState.Proto\n{\n  readonly _tag: \"LeftDone\"\n  f(exit: Exit.Exit<Done1, Err1>): Effect.Effect<Done2, Err2, Env>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface RightDone<out Env, in Err, _Err1, out Err2, _Elem, in Done, _Done1, out Done2>\n  extends MergeState.Proto\n{\n  readonly _tag: \"RightDone\"\n  f(exit: Exit.Exit<Done, Err>): Effect.Effect<Done2, Err2, Env>\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const BothRunning: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  left: Fiber.Fiber<Either.Either<Elem, Done>, Err>,\n  right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1>\n) => MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.BothRunning\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const LeftDone: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  f: (exit: Exit.Exit<Done1, Err1>) => Effect.Effect<Done2, Err2, Env>\n) => MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.LeftDone\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const RightDone: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  f: (exit: Exit.Exit<Done, Err>) => Effect.Effect<Done2, Err2, Env>\n) => MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.RightDone\n\n/**\n * Returns `true` if the specified value is a `MergeState`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isMergeState: (\n  u: unknown\n) => u is MergeState<unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown> = internal.isMergeState\n\n/**\n * Returns `true` if the specified `MergeState` is a `BothRunning`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isBothRunning: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  self: MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>\n) => self is BothRunning<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.isBothRunning\n\n/**\n * Returns `true` if the specified `MergeState` is a `LeftDone`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isLeftDone: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  self: MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>\n) => self is LeftDone<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.isLeftDone\n\n/**\n * Returns `true` if the specified `MergeState` is a `RightDone`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isRightDone: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  self: MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>\n) => self is RightDone<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.isRightDone\n\n/**\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <Env, Err, Err1, Err2, Elem, Done, Done1, Done2, Z>(\n    options: {\n      readonly onBothRunning: (\n        left: Fiber.Fiber<Either.Either<Elem, Done>, Err>,\n        right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1>\n      ) => Z\n      readonly onLeftDone: (f: (exit: Exit.Exit<Done1, Err1>) => Effect.Effect<Done2, Err2, Env>) => Z\n      readonly onRightDone: (f: (exit: Exit.Exit<Done, Err>) => Effect.Effect<Done2, Err2, Env>) => Z\n    }\n  ): (self: MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>) => Z\n  <Env, Err, Err1, Err2, Elem, Done, Done1, Done2, Z>(\n    self: MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>,\n    options: {\n      readonly onBothRunning: (\n        left: Fiber.Fiber<Either.Either<Elem, Done>, Err>,\n        right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1>\n      ) => Z\n      readonly onLeftDone: (f: (exit: Exit.Exit<Done1, Err1>) => Effect.Effect<Done2, Err2, Env>) => Z\n      readonly onRightDone: (f: (exit: Exit.Exit<Done, Err>) => Effect.Effect<Done2, Err2, Env>) => Z\n    }\n  ): Z\n} = internal.match\n"
  },
  {
    "path": "packages/effect/src/MergeStrategy.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/channel/mergeStrategy.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MergeStrategyTypeId: unique symbol = internal.MergeStrategyTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MergeStrategyTypeId = typeof MergeStrategyTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type MergeStrategy = BackPressure | BufferSliding\n\n/**\n * @since 2.0.0\n */\nexport declare namespace MergeStrategy {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Proto {\n    readonly [MergeStrategyTypeId]: MergeStrategyTypeId\n  }\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface BackPressure extends MergeStrategy.Proto {\n  readonly _tag: \"BackPressure\"\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface BufferSliding extends MergeStrategy.Proto {\n  readonly _tag: \"BufferSliding\"\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const BackPressure: (_: void) => MergeStrategy = internal.BackPressure\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const BufferSliding: (_: void) => MergeStrategy = internal.BufferSliding\n\n/**\n * Returns `true` if the specified value is a `MergeStrategy`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isMergeStrategy: (u: unknown) => u is MergeStrategy = internal.isMergeStrategy\n\n/**\n * Returns `true` if the specified `MergeStrategy` is a `BackPressure`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isBackPressure: (self: MergeStrategy) => self is BackPressure = internal.isBackPressure\n\n/**\n * Returns `true` if the specified `MergeStrategy` is a `BufferSliding`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isBufferSliding: (self: MergeStrategy) => self is BufferSliding = internal.isBufferSliding\n\n/**\n * Folds an `MergeStrategy` into a value of type `A`.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <A>(options: {\n    readonly onBackPressure: () => A\n    readonly onBufferSliding: () => A\n  }): (self: MergeStrategy) => A\n  <A>(self: MergeStrategy, options: {\n    readonly onBackPressure: () => A\n    readonly onBufferSliding: () => A\n  }): A\n} = internal.match\n"
  },
  {
    "path": "packages/effect/src/Metric.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport * as fiberRuntime from \"./internal/fiberRuntime.js\"\nimport * as internal from \"./internal/metric.js\"\nimport type * as MetricBoundaries from \"./MetricBoundaries.js\"\nimport type * as MetricKey from \"./MetricKey.js\"\nimport type * as MetricKeyType from \"./MetricKeyType.js\"\nimport type * as MetricLabel from \"./MetricLabel.js\"\nimport type * as MetricPair from \"./MetricPair.js\"\nimport type * as MetricRegistry from \"./MetricRegistry.js\"\nimport type * as MetricState from \"./MetricState.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MetricTypeId: unique symbol = internal.MetricTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MetricTypeId = typeof MetricTypeId\n\n/**\n * A `Metric<Type, In, Out>` represents a concurrent metric which accepts\n * updates of type `In` and are aggregated to a stateful value of type `Out`.\n *\n * For example, a counter metric would have type `Metric<number, number>`,\n * representing the fact that the metric can be updated with numbers (the amount\n * to increment or decrement the counter by), and the state of the counter is a\n * number.\n *\n * There are five primitive metric types supported by Effect:\n *\n *   - Counters\n *   - Frequencies\n *   - Gauges\n *   - Histograms\n *   - Summaries\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Metric<in out Type, in In, out Out> extends Metric.Variance<Type, In, Out>, Pipeable {\n  /**\n   * The type of the underlying primitive metric. For example, this could be\n   * `MetricKeyType.Counter` or `MetricKeyType.Gauge`.\n   */\n  readonly keyType: Type\n  unsafeUpdate(input: In, extraTags: ReadonlyArray<MetricLabel.MetricLabel>): void\n  unsafeValue(extraTags: ReadonlyArray<MetricLabel.MetricLabel>): Out\n  unsafeModify(input: In, extraTags: ReadonlyArray<MetricLabel.MetricLabel>): void\n  register(): this\n  <A extends In, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MetricApply {\n  <Type, In, Out>(\n    keyType: Type,\n    unsafeUpdate: (input: In, extraTags: ReadonlyArray<MetricLabel.MetricLabel>) => void,\n    unsafeValue: (extraTags: ReadonlyArray<MetricLabel.MetricLabel>) => Out,\n    unsafeModify: (input: In, extraTags: ReadonlyArray<MetricLabel.MetricLabel>) => void\n  ): Metric<Type, In, Out>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Metric {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Counter<In extends number | bigint>\n    extends Metric<MetricKeyType.MetricKeyType.Counter<In>, In, MetricState.MetricState.Counter<In>>\n  {}\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Gauge<In extends number | bigint>\n    extends Metric<MetricKeyType.MetricKeyType.Gauge<In>, In, MetricState.MetricState.Gauge<In>>\n  {}\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Frequency<In>\n    extends Metric<MetricKeyType.MetricKeyType.Frequency, In, MetricState.MetricState.Frequency>\n  {}\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Histogram<In>\n    extends Metric<MetricKeyType.MetricKeyType.Histogram, In, MetricState.MetricState.Histogram>\n  {}\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Summary<In>\n    extends Metric<MetricKeyType.MetricKeyType.Summary, In, MetricState.MetricState.Summary>\n  {}\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out Type, in In, out Out> {\n    readonly [MetricTypeId]: {\n      readonly _Type: Types.Invariant<Type>\n      readonly _In: Types.Contravariant<In>\n      readonly _Out: Types.Covariant<Out>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category globals\n */\nexport const globalMetricRegistry: MetricRegistry.MetricRegistry = internal.globalMetricRegistry\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: MetricApply = internal.make\n\n/**\n * Returns a new metric that is powered by this one, but which accepts updates\n * of the specified new type, which must be transformable to the input type of\n * this metric.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapInput: {\n  <In, In2>(f: (input: In2) => In): <Type, Out>(self: Metric<Type, In, Out>) => Metric<Type, In2, Out>\n  <Type, In, Out, In2>(self: Metric<Type, In, Out>, f: (input: In2) => In): Metric<Type, In2, Out>\n} = internal.mapInput\n\n/**\n * Represents a Counter metric that tracks cumulative numerical values over time.\n * Counters can be incremented and decremented and provide a running total of changes.\n *\n * **Options**\n *\n * - description - A description of the counter.\n * - bigint - Indicates if the counter uses 'bigint' data type.\n * - incremental - Set to 'true' for a counter that only increases. With this configuration, Effect ensures that non-incremental updates have no impact on the counter, making it exclusively suitable for counting upwards.\n *\n * @example\n * ```ts\n * import { Metric } from \"effect\"\n *\n * const numberCounter = Metric.counter(\"count\", {\n *   description: \"A number counter\"\n * });\n *\n * const bigintCounter = Metric.counter(\"count\", {\n *   description: \"A bigint counter\",\n *   bigint: true\n * });\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const counter: {\n  (\n    name: string,\n    options?: {\n      readonly description?: string | undefined\n      readonly bigint?: false | undefined\n      readonly incremental?: boolean | undefined\n    }\n  ): Metric.Counter<number>\n  (\n    name: string,\n    options: {\n      readonly description?: string | undefined\n      readonly bigint: true\n      readonly incremental?: boolean | undefined\n    }\n  ): Metric.Counter<bigint>\n} = internal.counter\n\n/**\n * Creates a Frequency metric to count occurrences of events.\n * Frequency metrics are used to count the number of times specific events or incidents occur.\n *\n * @example\n * ```ts\n * import { Metric } from \"effect\"\n *\n * const errorFrequency = Metric.frequency(\"error_frequency\", {\n *    description: \"Counts the occurrences of errors.\"\n * });\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const frequency: (\n  name: string,\n  options?:\n    | { readonly description?: string | undefined; readonly preregisteredWords?: ReadonlyArray<string> | undefined }\n    | undefined\n) => Metric.Frequency<string> = internal.frequency\n\n/**\n * Returns a new metric that is powered by this one, but which accepts updates\n * of any type, and translates them to updates with the specified constant\n * update value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const withConstantInput: {\n  <In>(input: In): <Type, Out>(self: Metric<Type, In, Out>) => Metric<Type, unknown, Out>\n  <Type, In, Out>(self: Metric<Type, In, Out>, input: In): Metric<Type, unknown, Out>\n} = internal.withConstantInput\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const fromMetricKey: <Type extends MetricKeyType.MetricKeyType<any, any>>(\n  key: MetricKey.MetricKey<Type>\n) => Metric<Type, MetricKeyType.MetricKeyType.InType<Type>, MetricKeyType.MetricKeyType.OutType<Type>> =\n  internal.fromMetricKey\n\n/**\n * Represents a Gauge metric that tracks and reports a single numerical value at a specific moment.\n * Gauges are suitable for metrics that represent instantaneous values, such as memory usage or CPU load.\n *\n * **Options**\n *\n * - description - A description of the gauge metric.\n * - bigint - Indicates if the counter uses 'bigint' data type.\n *\n * @example\n * ```ts\n * import { Metric } from \"effect\"\n *\n * const numberGauge = Metric.gauge(\"memory_usage\", {\n *   description: \"A gauge for memory usage\"\n * });\n *\n * const bigintGauge = Metric.gauge(\"cpu_load\", {\n *   description: \"A gauge for CPU load\",\n *   bigint: true\n * });\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const gauge: {\n  (name: string, options?: {\n    readonly description?: string | undefined\n    readonly bigint?: false | undefined\n  }): Metric.Gauge<number>\n  (name: string, options: {\n    readonly description?: string | undefined\n    readonly bigint: true\n  }): Metric.Gauge<bigint>\n} = internal.gauge\n\n/**\n * Represents a Histogram metric that records observations in specified value boundaries.\n * Histogram metrics are useful for measuring the distribution of values within a range.\n *\n * @example\n * ```ts\n * import { Metric, MetricBoundaries } from \"effect\"\n *\n * const latencyHistogram = Metric.histogram(\"latency_histogram\",\n *   MetricBoundaries.linear({ start: 0, width: 10, count: 11 }),\n *   \"Measures the distribution of request latency.\"\n * );\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const histogram: (\n  name: string,\n  boundaries: MetricBoundaries.MetricBoundaries,\n  description?: string\n) => Metric<MetricKeyType.MetricKeyType.Histogram, number, MetricState.MetricState.Histogram> = internal.histogram\n\n/**\n * @since 2.0.0\n * @category combinators\n */\nexport const increment: (\n  self: Metric.Counter<number> | Metric.Counter<bigint> | Metric.Gauge<number> | Metric.Gauge<bigint>\n) => Effect.Effect<void> = internal.increment\n\n/**\n * @since 2.0.0\n * @category combinators\n */\nexport const incrementBy: {\n  (amount: number): (self: Metric.Counter<number> | Metric.Counter<number>) => Effect.Effect<void>\n  (amount: bigint): (self: Metric.Counter<bigint> | Metric.Gauge<bigint>) => Effect.Effect<void>\n  (self: Metric.Counter<number> | Metric.Gauge<number>, amount: number): Effect.Effect<void>\n  (self: Metric.Counter<bigint> | Metric.Gauge<bigint>, amount: bigint): Effect.Effect<void>\n} = internal.incrementBy\n\n/**\n * Returns a new metric that is powered by this one, but which outputs a new\n * state type, determined by transforming the state type of this metric by the\n * specified function.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <Out, Out2>(f: (out: Out) => Out2): <Type, In>(self: Metric<Type, In, Out>) => Metric<Type, In, Out2>\n  <Type, In, Out, Out2>(self: Metric<Type, In, Out>, f: (out: Out) => Out2): Metric<Type, In, Out2>\n} = internal.map\n\n/**\n * @since 2.0.0\n * @category mapping\n */\nexport const mapType: {\n  <Type, Type2>(f: (type: Type) => Type2): <In, Out>(self: Metric<Type, In, Out>) => Metric<Type2, In, Out>\n  <Type, In, Out, Type2>(self: Metric<Type, In, Out>, f: (type: Type) => Type2): Metric<Type2, In, Out>\n} = internal.mapType\n\n/**\n * Modifies the metric with the specified update message. For example, if the\n * metric were a gauge, the update would increment the method by the provided\n * amount.\n *\n * @since 3.6.5\n * @category utils\n */\nexport const modify: {\n  <In>(input: In): <Type, Out>(self: Metric<Type, In, Out>) => Effect.Effect<void>\n  <Type, In, Out>(self: Metric<Type, In, Out>, input: In): Effect.Effect<void>\n} = internal.modify\n\n/**\n * @since 2.0.0\n * @category aspects\n */\nexport const set: {\n  (value: number): (self: Metric.Gauge<number>) => Effect.Effect<void>\n  (value: bigint): (self: Metric.Gauge<bigint>) => Effect.Effect<void>\n  (self: Metric.Gauge<number>, value: number): Effect.Effect<void>\n  (self: Metric.Gauge<bigint>, value: bigint): Effect.Effect<void>\n} = internal.set\n\n/**\n * Captures a snapshot of all metrics recorded by the application.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const snapshot: Effect.Effect<Array<MetricPair.MetricPair.Untyped>> = internal.snapshot\n\n/**\n * Creates a metric that ignores input and produces constant output.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeed: <Out>(out: Out) => Metric<void, unknown, Out> = internal.succeed\n\n/**\n * Creates a metric that ignores input and produces constant output.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sync: <Out>(evaluate: LazyArg<Out>) => Metric<void, unknown, Out> = internal.sync\n\n/**\n * Creates a Summary metric that records observations and calculates quantiles.\n * Summary metrics provide statistical information about a set of values, including quantiles.\n *\n * **Options**\n *\n * - name - The name of the Summary metric.\n * - maxAge - The maximum age of observations to retain.\n * - maxSize - The maximum number of observations to keep.\n * - error - The error percentage when calculating quantiles.\n * - quantiles - An `Chunk` of quantiles to calculate (e.g., [0.5, 0.9]).\n * - description - An optional description of the Summary metric.\n *\n * @example\n * ```ts\n * import { Metric, Chunk } from \"effect\"\n *\n * const responseTimesSummary = Metric.summary({\n *   name: \"response_times_summary\",\n *   maxAge: \"60 seconds\", // Retain observations for 60 seconds.\n *   maxSize: 1000, // Keep a maximum of 1000 observations.\n *   error: 0.01, // Allow a 1% error when calculating quantiles.\n *   quantiles: [0.5, 0.9, 0.99], // Calculate 50th, 90th, and 99th percentiles.\n *   description: \"Measures the distribution of response times.\"\n * });\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const summary: (\n  options: {\n    readonly name: string\n    readonly maxAge: Duration.DurationInput\n    readonly maxSize: number\n    readonly error: number\n    readonly quantiles: ReadonlyArray<number>\n    readonly description?: string | undefined\n  }\n) => Metric.Summary<number> = internal.summary\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const summaryTimestamp: (\n  options: {\n    readonly name: string\n    readonly maxAge: Duration.DurationInput\n    readonly maxSize: number\n    readonly error: number\n    readonly quantiles: ReadonlyArray<number>\n    readonly description?: string | undefined\n  }\n) => Metric.Summary<readonly [value: number, timestamp: number]> // readonly because contravariant\n = internal.summaryTimestamp\n\n/**\n * Returns a new metric, which is identical in every way to this one, except\n * the specified tags have been added to the tags of this metric.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const tagged: {\n  <Type, In, Out>(key: string, value: string): (self: Metric<Type, In, Out>) => Metric<Type, In, Out>\n  <Type, In, Out>(self: Metric<Type, In, Out>, key: string, value: string): Metric<Type, In, Out>\n} = internal.tagged\n\n/**\n * Returns a new metric, which is identical in every way to this one, except\n * dynamic tags are added based on the update values. Note that the metric\n * returned by this method does not return any useful information, due to the\n * dynamic nature of the added tags.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const taggedWithLabelsInput: {\n  <In>(\n    f: (input: In) => Iterable<MetricLabel.MetricLabel>\n  ): <Type, Out>(self: Metric<Type, In, Out>) => Metric<Type, In, void>\n  <Type, In, Out>(\n    self: Metric<Type, In, Out>,\n    f: (input: In) => Iterable<MetricLabel.MetricLabel>\n  ): Metric<Type, In, void>\n} = internal.taggedWithLabelsInput\n\n/**\n * Returns a new metric, which is identical in every way to this one, except\n * the specified tags have been added to the tags of this metric.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const taggedWithLabels: {\n  <Type, In, Out>(extraTags: Iterable<MetricLabel.MetricLabel>): (self: Metric<Type, In, Out>) => Metric<Type, In, Out>\n  <Type, In, Out>(self: Metric<Type, In, Out>, extraTags: Iterable<MetricLabel.MetricLabel>): Metric<Type, In, Out>\n} = internal.taggedWithLabels\n\n/**\n * Creates a timer metric, based on a histogram, which keeps track of\n * durations in milliseconds. The unit of time will automatically be added to\n * the metric as a tag (i.e. `\"time_unit: milliseconds\"`).\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const timer: (\n  name: string,\n  description?: string\n) => Metric<MetricKeyType.MetricKeyType.Histogram, Duration.Duration, MetricState.MetricState.Histogram> =\n  internal.timer\n\n/**\n * Creates a timer metric, based on a histogram created from the provided\n * boundaries, which keeps track of durations in milliseconds. The unit of time\n * will automatically be added to the metric as a tag (i.e.\n * `\"time_unit: milliseconds\"`).\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const timerWithBoundaries: (\n  name: string,\n  boundaries: ReadonlyArray<number>,\n  description?: string\n) => Metric<MetricKeyType.MetricKeyType.Histogram, Duration.Duration, MetricState.MetricState.Histogram> =\n  internal.timerWithBoundaries\n\n/**\n * Returns an aspect that will update this metric with the specified constant\n * value every time the aspect is applied to an effect, regardless of whether\n * that effect fails or succeeds.\n *\n * @since 2.0.0\n * @category aspects\n */\nexport const trackAll: {\n  <In>(\n    input: In\n  ): <Type, Out>(self: Metric<Type, In, Out>) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <Type, In, Out>(\n    self: Metric<Type, In, Out>,\n    input: In\n  ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n} = internal.trackAll\n\n/**\n * Returns an aspect that will update this metric with the defects of the\n * effects that it is applied to.\n *\n * @since 2.0.0\n * @category aspects\n */\nexport const trackDefect: {\n  <Type, Out>(metric: Metric<Type, unknown, Out>): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R, Type, Out>(self: Effect.Effect<A, E, R>, metric: Metric<Type, unknown, Out>): Effect.Effect<A, E, R>\n} = internal.trackDefect\n\n/**\n * Returns an aspect that will update this metric with the result of applying\n * the specified function to the defect throwables of the effects that the\n * aspect is applied to.\n *\n * @since 2.0.0\n * @category aspects\n */\nexport const trackDefectWith: {\n  <Type, In, Out>(\n    metric: Metric<Type, In, Out>,\n    f: (defect: unknown) => In\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R, Type, In, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric<Type, In, Out>,\n    f: (defect: unknown) => In\n  ): Effect.Effect<A, E, R>\n} = internal.trackDefectWith\n\n/**\n * Returns an aspect that will update this metric with the duration that the\n * effect takes to execute. To call this method, the input type of the metric\n * must be `Duration`.\n *\n * @since 2.0.0\n * @category aspects\n */\nexport const trackDuration: {\n  <Type, Out>(\n    metric: Metric<Type, Duration.Duration, Out>\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R, Type, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric<Type, Duration.Duration, Out>\n  ): Effect.Effect<A, E, R>\n} = internal.trackDuration\n\n/**\n * Returns an aspect that will update this metric with the duration that the\n * effect takes to execute. To call this method, you must supply a function\n * that can convert the `Duration` to the input type of this metric.\n *\n * @since 2.0.0\n * @category aspects\n */\nexport const trackDurationWith: {\n  <Type, In, Out>(\n    metric: Metric<Type, In, Out>,\n    f: (duration: Duration.Duration) => In\n  ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R, Type, In, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric<Type, In, Out>,\n    f: (duration: Duration.Duration) => In\n  ): Effect.Effect<A, E, R>\n} = internal.trackDurationWith\n\n/**\n * Returns an aspect that will update this metric with the failure value of\n * the effects that it is applied to.\n *\n * @since 2.0.0\n * @category aspects\n */\nexport const trackError: {\n  <Type, In, Out>(\n    metric: Metric<Type, In, Out>\n  ): <A, E extends In, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E extends In, R, Type, In, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric<Type, In, Out>\n  ): Effect.Effect<A, E, R>\n} = internal.trackError\n\n/**\n * Returns an aspect that will update this metric with the result of applying\n * the specified function to the error value of the effects that the aspect is\n * applied to.\n *\n * @since 2.0.0\n * @category aspects\n */\nexport const trackErrorWith: {\n  <Type, In, Out, In2>(\n    metric: Metric<Type, In, Out>,\n    f: (error: In2) => In\n  ): <A, E extends In2, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E extends In2, R, Type, In, Out, In2>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric<Type, In, Out>,\n    f: (error: In2) => In\n  ): Effect.Effect<A, E, R>\n} = internal.trackErrorWith\n\n/**\n * Returns an aspect that will update this metric with the success value of\n * the effects that it is applied to.\n *\n * @since 2.0.0\n * @category aspects\n */\nexport const trackSuccess: {\n  <Type, In, Out>(\n    metric: Metric<Type, In, Out>\n  ): <A extends In, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A extends In, E, R, Type, In, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric<Type, In, Out>\n  ): Effect.Effect<A, E, R>\n} = internal.trackSuccess\n\n/**\n * Returns an aspect that will update this metric with the result of applying\n * the specified function to the success value of the effects that the aspect is\n * applied to.\n *\n * @since 2.0.0\n * @category aspects\n */\nexport const trackSuccessWith: {\n  <Type, In, Out, A>(\n    metric: Metric<Type, In, Out>,\n    f: (value: Types.NoInfer<A>) => In\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R, Type, In, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric<Type, In, Out>,\n    f: (value: Types.NoInfer<A>) => In\n  ): Effect.Effect<A, E, R>\n} = internal.trackSuccessWith\n\n/**\n * Updates the metric with the specified update message. For example, if the\n * metric were a counter, the update would increment the method by the\n * provided amount.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const update: {\n  <In>(input: In): <Type, Out>(self: Metric<Type, In, Out>) => Effect.Effect<void>\n  <Type, In, Out>(self: Metric<Type, In, Out>, input: In): Effect.Effect<void>\n} = internal.update\n\n/**\n * Retrieves a snapshot of the value of the metric at this moment in time.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const value: <Type, In, Out>(self: Metric<Type, In, Out>) => Effect.Effect<Out> = internal.value\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const withNow: <Type, In, Out>(self: Metric<Type, readonly [In, number], Out>) => Metric<Type, In, Out> =\n  internal.withNow\n\n/**\n * @since 2.0.0\n * @category zipping\n */\nexport const zip: {\n  <Type2, In2, Out2>(\n    that: Metric<Type2, In2, Out2>\n  ): <Type, In, Out>(\n    self: Metric<Type, In, Out>\n  ) => Metric<\n    readonly [Type, Type2], // readonly because invariant\n    readonly [In, In2], // readonly because contravariant\n    [Out, Out2]\n  >\n  <Type, In, Out, Type2, In2, Out2>(\n    self: Metric<Type, In, Out>,\n    that: Metric<Type2, In2, Out2>\n  ): Metric<\n    readonly [Type, Type2], // readonly because invariant\n    readonly [In, In2], // readonly because contravariant\n    [Out, Out2]\n  >\n} = internal.zip\n\n/**\n * Unsafely captures a snapshot of all metrics recorded by the application.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeSnapshot: (_: void) => ReadonlyArray<MetricPair.MetricPair.Untyped> = internal.unsafeSnapshot\n\n/**\n * @since 2.0.0\n * @category metrics\n */\nexport const fiberStarted: Metric.Counter<number> = fiberRuntime.fiberStarted\n\n/**\n * @since 2.0.0\n * @category metrics\n */\nexport const fiberSuccesses: Metric.Counter<number> = fiberRuntime.fiberSuccesses\n\n/**\n * @since 2.0.0\n * @category metrics\n */\nexport const fiberFailures: Metric.Counter<number> = fiberRuntime.fiberFailures\n\n/**\n * @since 2.0.0\n * @category metrics\n */\nexport const fiberLifetimes: Metric<MetricKeyType.MetricKeyType.Histogram, number, MetricState.MetricState.Histogram> =\n  fiberRuntime.fiberLifetimes\n\n/**\n * @since 2.0.0\n * @category metrics\n */\nexport const fiberActive: Metric.Counter<number> = fiberRuntime.fiberActive\n"
  },
  {
    "path": "packages/effect/src/MetricBoundaries.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Equal from \"./Equal.js\"\nimport * as internal from \"./internal/metric/boundaries.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MetricBoundariesTypeId: unique symbol = internal.MetricBoundariesTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MetricBoundariesTypeId = typeof MetricBoundariesTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MetricBoundaries extends Equal.Equal, Pipeable {\n  readonly [MetricBoundariesTypeId]: MetricBoundariesTypeId\n  readonly values: ReadonlyArray<number>\n}\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isMetricBoundaries: (u: unknown) => u is MetricBoundaries = internal.isMetricBoundaries\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: (iterable: Iterable<number>) => MetricBoundaries = internal.fromIterable\n\n/**\n * A helper method to create histogram bucket boundaries for a histogram\n * with linear increasing values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const linear: (\n  options: {\n    readonly start: number\n    readonly width: number\n    readonly count: number\n  }\n) => MetricBoundaries = internal.linear\n\n/**\n * A helper method to create histogram bucket boundaries for a histogram\n * with exponentially increasing values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const exponential: (\n  options: {\n    readonly start: number\n    readonly factor: number\n    readonly count: number\n  }\n) => MetricBoundaries = internal.exponential\n"
  },
  {
    "path": "packages/effect/src/MetricHook.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { LazyArg } from \"./Function.js\"\nimport * as internal from \"./internal/metric/hook.js\"\nimport type * as MetricKey from \"./MetricKey.js\"\nimport type * as MetricState from \"./MetricState.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MetricHookTypeId: unique symbol = internal.MetricHookTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MetricHookTypeId = typeof MetricHookTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MetricHook<in In, out Out> extends MetricHook.Variance<In, Out>, Pipeable {\n  get(): Out\n  update(input: In): void\n  modify(input: In): void\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace MetricHook {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Root = MetricHook<any, MetricState.MetricState.Untyped>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Untyped = MetricHook<any, any>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Counter<A extends (number | bigint)> = MetricHook<A, MetricState.MetricState.Counter<A>>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Gauge<A extends (number | bigint)> = MetricHook<A, MetricState.MetricState.Gauge<A>>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Frequency = MetricHook<string, MetricState.MetricState.Frequency>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Histogram = MetricHook<number, MetricState.MetricState.Histogram>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Summary = MetricHook<readonly [number, number], MetricState.MetricState.Summary>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in In, out Out> {\n    readonly [MetricHookTypeId]: {\n      readonly _In: Types.Contravariant<In>\n      readonly _Out: Types.Covariant<Out>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <In, Out>(options: {\n  readonly get: LazyArg<Out>\n  readonly update: (input: In) => void\n  readonly modify: (input: In) => void\n}) => MetricHook<In, Out> = internal.make\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const counter: <A extends (number | bigint)>(key: MetricKey.MetricKey.Counter<A>) => MetricHook.Counter<A> =\n  internal.counter\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const frequency: (_key: MetricKey.MetricKey.Frequency) => MetricHook.Frequency = internal.frequency\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const gauge: {\n  (key: MetricKey.MetricKey.Gauge<number>, startAt: number): MetricHook.Gauge<number>\n  (key: MetricKey.MetricKey.Gauge<bigint>, startAt: bigint): MetricHook.Gauge<bigint>\n} = internal.gauge\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const histogram: (key: MetricKey.MetricKey.Histogram) => MetricHook.Histogram = internal.histogram\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const summary: (key: MetricKey.MetricKey.Summary) => MetricHook.Summary = internal.summary\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const onUpdate: {\n  <In, Out>(f: (input: In) => void): (self: MetricHook<In, Out>) => MetricHook<In, Out>\n  <In, Out>(self: MetricHook<In, Out>, f: (input: In) => void): MetricHook<In, Out>\n} = internal.onUpdate\n\n/**\n * @since 3.6.5\n * @category utils\n */\nexport const onModify: {\n  <In, Out>(f: (input: In) => void): (self: MetricHook<In, Out>) => MetricHook<In, Out>\n  <In, Out>(self: MetricHook<In, Out>, f: (input: In) => void): MetricHook<In, Out>\n} = internal.onModify\n"
  },
  {
    "path": "packages/effect/src/MetricKey.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Duration from \"./Duration.js\"\nimport type * as Equal from \"./Equal.js\"\nimport * as internal from \"./internal/metric/key.js\"\nimport type * as MetricBoundaries from \"./MetricBoundaries.js\"\nimport type * as MetricKeyType from \"./MetricKeyType.js\"\nimport type * as MetricLabel from \"./MetricLabel.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MetricKeyTypeId: unique symbol = internal.MetricKeyTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MetricKeyTypeId = typeof MetricKeyTypeId\n\n/**\n * A `MetricKey` is a unique key associated with each metric. The key is based\n * on a combination of the metric type, the name and tags associated with the\n * metric, an optional description of the key, and any other information to\n * describe a metric, such as the boundaries of a histogram. In this way, it is\n * impossible to ever create different metrics with conflicting keys.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface MetricKey<out Type extends MetricKeyType.MetricKeyType<any, any>>\n  extends MetricKey.Variance<Type>, Equal.Equal, Pipeable\n{\n  readonly name: string\n  readonly keyType: Type\n  readonly description: Option.Option<string>\n  readonly tags: ReadonlyArray<MetricLabel.MetricLabel>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace MetricKey {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Untyped = MetricKey<any>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Counter<A extends (number | bigint)> = MetricKey<MetricKeyType.MetricKeyType.Counter<A>>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Gauge<A extends (number | bigint)> = MetricKey<MetricKeyType.MetricKeyType.Gauge<A>>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Frequency = MetricKey<MetricKeyType.MetricKeyType.Frequency>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Histogram = MetricKey<MetricKeyType.MetricKeyType.Histogram>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Summary = MetricKey<MetricKeyType.MetricKeyType.Summary>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out Type> {\n    readonly [MetricKeyTypeId]: {\n      _Type: Types.Covariant<Type>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isMetricKey: (u: unknown) => u is MetricKey<MetricKeyType.MetricKeyType<unknown, unknown>> =\n  internal.isMetricKey\n\n/**\n * Creates a metric key for a counter, with the specified name.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const counter: {\n  (\n    name: string,\n    options?: {\n      readonly description?: string | undefined\n      readonly bigint?: false | undefined\n      readonly incremental?: boolean | undefined\n    }\n  ): MetricKey.Counter<number>\n  (\n    name: string,\n    options: {\n      readonly description?: string | undefined\n      readonly bigint: true\n      readonly incremental?: boolean | undefined\n    }\n  ): MetricKey.Counter<bigint>\n} = internal.counter\n\n/**\n * Creates a metric key for a categorical frequency table, with the specified\n * name.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const frequency: (\n  name: string,\n  options?:\n    | {\n      readonly description?: string | undefined\n      readonly preregisteredWords?: ReadonlyArray<string> | undefined\n    }\n    | undefined\n) => MetricKey.Frequency = internal.frequency\n\n/**\n * Creates a metric key for a gauge, with the specified name.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const gauge: {\n  (name: string, options?: {\n    readonly description?: string | undefined\n    readonly bigint?: false | undefined\n  }): MetricKey.Gauge<number>\n  (name: string, options: {\n    readonly description?: string | undefined\n    readonly bigint: true\n  }): MetricKey.Gauge<bigint>\n} = internal.gauge\n\n/**\n * Creates a metric key for a histogram, with the specified name and boundaries.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const histogram: (\n  name: string,\n  boundaries: MetricBoundaries.MetricBoundaries,\n  description?: string\n) => MetricKey.Histogram = internal.histogram\n\n/**\n * Creates a metric key for a summary, with the specified name, maxAge,\n * maxSize, error, and quantiles.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const summary: (\n  options: {\n    readonly name: string\n    readonly maxAge: Duration.DurationInput\n    readonly maxSize: number\n    readonly error: number\n    readonly quantiles: ReadonlyArray<number>\n    readonly description?: string | undefined\n  }\n) => MetricKey.Summary = internal.summary\n\n/**\n * Returns a new `MetricKey` with the specified tag appended.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const tagged: {\n  (\n    key: string,\n    value: string\n  ): <Type extends MetricKeyType.MetricKeyType<any, any>>(self: MetricKey<Type>) => MetricKey<Type>\n  <Type extends MetricKeyType.MetricKeyType<any, any>>(\n    self: MetricKey<Type>,\n    key: string,\n    value: string\n  ): MetricKey<Type>\n} = internal.tagged\n\n/**\n * Returns a new `MetricKey` with the specified tags appended.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const taggedWithLabels: {\n  (\n    extraTags: ReadonlyArray<MetricLabel.MetricLabel>\n  ): <Type extends MetricKeyType.MetricKeyType<any, any>>(self: MetricKey<Type>) => MetricKey<Type>\n  <Type extends MetricKeyType.MetricKeyType<any, any>>(\n    self: MetricKey<Type>,\n    extraTags: ReadonlyArray<MetricLabel.MetricLabel>\n  ): MetricKey<Type>\n} = internal.taggedWithLabels\n"
  },
  {
    "path": "packages/effect/src/MetricKeyType.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Duration from \"./Duration.js\"\nimport type * as Equal from \"./Equal.js\"\nimport * as internal from \"./internal/metric/keyType.js\"\nimport type * as MetricBoundaries from \"./MetricBoundaries.js\"\nimport type * as MetricState from \"./MetricState.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MetricKeyTypeTypeId: unique symbol = internal.MetricKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MetricKeyTypeTypeId = typeof MetricKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const CounterKeyTypeTypeId: unique symbol = internal.CounterKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type CounterKeyTypeTypeId = typeof CounterKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const FrequencyKeyTypeTypeId: unique symbol = internal.FrequencyKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type FrequencyKeyTypeTypeId = typeof FrequencyKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const GaugeKeyTypeTypeId: unique symbol = internal.GaugeKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type GaugeKeyTypeTypeId = typeof GaugeKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const HistogramKeyTypeTypeId: unique symbol = internal.HistogramKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type HistogramKeyTypeTypeId = typeof HistogramKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const SummaryKeyTypeTypeId: unique symbol = internal.SummaryKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type SummaryKeyTypeTypeId = typeof SummaryKeyTypeTypeId\n\n/**\n * @since 2.0.0\n * @category modelz\n */\nexport interface MetricKeyType<in In, out Out> extends MetricKeyType.Variance<In, Out>, Equal.Equal, Pipeable {}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace MetricKeyType {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Untyped = MetricKeyType<any, any>\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Counter<A extends (number | bigint)> = MetricKeyType<A, MetricState.MetricState.Counter<A>> & {\n    readonly [CounterKeyTypeTypeId]: CounterKeyTypeTypeId\n    readonly incremental: boolean\n    readonly bigint: boolean\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Frequency = MetricKeyType<string, MetricState.MetricState.Frequency> & {\n    readonly [FrequencyKeyTypeTypeId]: FrequencyKeyTypeTypeId\n    readonly preregisteredWords: ReadonlyArray<string>\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Gauge<A extends (number | bigint)> = MetricKeyType<A, MetricState.MetricState.Gauge<A>> & {\n    readonly [GaugeKeyTypeTypeId]: GaugeKeyTypeTypeId\n    readonly bigint: boolean\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Histogram = MetricKeyType<number, MetricState.MetricState.Histogram> & {\n    readonly [HistogramKeyTypeTypeId]: HistogramKeyTypeTypeId\n    readonly boundaries: MetricBoundaries.MetricBoundaries\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type Summary = MetricKeyType<readonly [number, number], MetricState.MetricState.Summary> & {\n    readonly [SummaryKeyTypeTypeId]: SummaryKeyTypeTypeId\n    readonly maxAge: Duration.Duration\n    readonly maxSize: number\n    readonly error: number\n    readonly quantiles: ReadonlyArray<number>\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in In, out Out> {\n    readonly [MetricKeyTypeTypeId]: {\n      readonly _In: Types.Contravariant<In>\n      readonly _Out: Types.Covariant<Out>\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type InType<Type extends MetricKeyType<any, any>> = [Type] extends [\n    {\n      readonly [MetricKeyTypeTypeId]: {\n        readonly _In: (_: infer In) => void\n      }\n    }\n  ] ? In\n    : never\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export type OutType<Type extends MetricKeyType<any, any>> = [Type] extends [\n    {\n      readonly [MetricKeyTypeTypeId]: {\n        readonly _Out: (_: never) => infer Out\n      }\n    }\n  ] ? Out\n    : never\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const counter: <A extends number | bigint>() => MetricKeyType.Counter<A> = internal.counter\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const frequency: (\n  options?: {\n    readonly preregisteredWords?: ReadonlyArray<string> | undefined\n  } | undefined\n) => MetricKeyType.Frequency = internal.frequency\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const gauge: <A extends number | bigint>() => MetricKeyType.Gauge<A> = internal.gauge\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const histogram: (boundaries: MetricBoundaries.MetricBoundaries) => MetricKeyType.Histogram = internal.histogram\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const summary: (\n  options: {\n    readonly maxAge: Duration.DurationInput\n    readonly maxSize: number\n    readonly error: number\n    readonly quantiles: ReadonlyArray<number>\n  }\n) => MetricKeyType.Summary = internal.summary\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isMetricKeyType: (u: unknown) => u is MetricKeyType<unknown, unknown> = internal.isMetricKeyType\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isCounterKey: (u: unknown) => u is MetricKeyType.Counter<number | bigint> = internal.isCounterKey\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isFrequencyKey: (u: unknown) => u is MetricKeyType.Frequency = internal.isFrequencyKey\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isGaugeKey: (u: unknown) => u is MetricKeyType.Gauge<number | bigint> = internal.isGaugeKey\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isHistogramKey: (u: unknown) => u is MetricKeyType.Histogram = internal.isHistogramKey\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isSummaryKey: (u: unknown) => u is MetricKeyType.Summary = internal.isSummaryKey\n"
  },
  {
    "path": "packages/effect/src/MetricLabel.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Equal from \"./Equal.js\"\nimport * as internal from \"./internal/metric/label.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MetricLabelTypeId: unique symbol = internal.MetricLabelTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MetricLabelTypeId = typeof MetricLabelTypeId\n\n/**\n * A `MetricLabel` represents a key value pair that allows analyzing metrics at\n * an additional level of granularity.\n *\n * For example if a metric tracks the response time of a service labels could\n * be used to create separate versions that track response times for different\n * clients.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface MetricLabel extends Equal.Equal, Pipeable {\n  readonly [MetricLabelTypeId]: MetricLabelTypeId\n  readonly key: string\n  readonly value: string\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (key: string, value: string) => MetricLabel = internal.make\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isMetricLabel: (u: unknown) => u is MetricLabel = internal.isMetricLabel\n"
  },
  {
    "path": "packages/effect/src/MetricPair.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/metric/pair.js\"\nimport type * as MetricKey from \"./MetricKey.js\"\nimport type * as MetricKeyType from \"./MetricKeyType.js\"\nimport type * as MetricState from \"./MetricState.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MetricPairTypeId: unique symbol = internal.MetricPairTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MetricPairTypeId = typeof MetricPairTypeId\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface MetricPair<out Type extends MetricKeyType.MetricKeyType<any, any>>\n  extends MetricPair.Variance<Type>, Pipeable\n{\n  readonly metricKey: MetricKey.MetricKey<Type>\n  readonly metricState: MetricState.MetricState<MetricKeyType.MetricKeyType.OutType<Type>>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace MetricPair {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Untyped extends MetricPair<MetricKeyType.MetricKeyType<any, any>> {}\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out Type extends MetricKeyType.MetricKeyType<any, any>> {\n    readonly [MetricPairTypeId]: {\n      readonly _Type: Types.Covariant<Type>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Type extends MetricKeyType.MetricKeyType<any, any>>(\n  metricKey: MetricKey.MetricKey<Type>,\n  metricState: MetricState.MetricState<MetricKeyType.MetricKeyType.OutType<Type>>\n) => MetricPair.Untyped = internal.make\n\n/**\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeMake: <Type extends MetricKeyType.MetricKeyType<any, any>>(\n  metricKey: MetricKey.MetricKey<Type>,\n  metricState: MetricState.MetricState.Untyped\n) => MetricPair.Untyped = internal.unsafeMake\n"
  },
  {
    "path": "packages/effect/src/MetricPolling.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport * as internal from \"./internal/metric/polling.js\"\nimport type * as Metric from \"./Metric.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Schedule from \"./Schedule.js\"\nimport type * as Scope from \"./Scope.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MetricPollingTypeId: unique symbol = internal.MetricPollingTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MetricPollingTypeId = typeof MetricPollingTypeId\n\n/**\n * A `MetricPolling` is a combination of a metric and an effect that polls for\n * updates to the metric.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface MetricPolling<in out Type, in out In, out R, out E, out Out> extends Pipeable {\n  readonly [MetricPollingTypeId]: MetricPollingTypeId\n  /**\n   * The metric that this `MetricPolling` polls to update.\n   */\n  readonly metric: Metric.Metric<Type, In, Out>\n  /**\n   * An effect that polls a value that may be fed to the metric.\n   */\n  readonly poll: Effect.Effect<In, E, R>\n}\n\n/**\n * Constructs a new polling metric from a metric and poll effect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Type, In, Out, R, E>(\n  metric: Metric.Metric<Type, In, Out>,\n  poll: Effect.Effect<In, E, R>\n) => MetricPolling<Type, In, R, E, Out> = internal.make\n\n/**\n * Collects all of the polling metrics into a single polling metric, which\n * polls for, updates, and produces the outputs of all individual metrics.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAll: <R, E, Out>(\n  iterable: Iterable<MetricPolling<any, any, R, E, Out>>\n) => MetricPolling<Array<any>, Array<any>, R, E, Array<Out>> = internal.collectAll\n\n/**\n * Returns an effect that will launch the polling metric in a background\n * fiber, using the specified schedule.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const launch: {\n  <A2, R2>(\n    schedule: Schedule.Schedule<A2, unknown, R2>\n  ): <Type, In, R, E, Out>(\n    self: MetricPolling<Type, In, R, E, Out>\n  ) => Effect.Effect<Fiber.Fiber<A2, E>, never, R2 | R | Scope.Scope>\n  <Type, In, R, E, Out, A2, R2>(\n    self: MetricPolling<Type, In, R, E, Out>,\n    schedule: Schedule.Schedule<A2, unknown, R2>\n  ): Effect.Effect<Fiber.Fiber<A2, E>, never, Scope.Scope | R | R2>\n} = internal.launch\n\n/**\n * An effect that polls a value that may be fed to the metric.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const poll: <Type, In, R, E, Out>(self: MetricPolling<Type, In, R, E, Out>) => Effect.Effect<In, E, R> =\n  internal.poll\n\n/**\n * An effect that polls for a value and uses the value to update the metric.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const pollAndUpdate: <Type, In, R, E, Out>(\n  self: MetricPolling<Type, In, R, E, Out>\n) => Effect.Effect<void, E, R> = internal.pollAndUpdate\n\n/**\n * Returns a new polling metric whose poll function will be retried with the\n * specified retry policy.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const retry: {\n  <X, E, R2>(\n    policy: Schedule.Schedule<X, NoInfer<E>, R2>\n  ): <Type, In, R, Out>(self: MetricPolling<Type, In, R, E, Out>) => MetricPolling<Type, In, R2 | R, E, Out>\n  <Type, In, R, E, Out, X, R2>(\n    self: MetricPolling<Type, In, R, E, Out>,\n    policy: Schedule.Schedule<X, E, R2>\n  ): MetricPolling<Type, In, R | R2, E, Out>\n} = internal.retry\n\n/**\n * Zips this polling metric with the specified polling metric.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const zip: {\n  <Type2, In2, R2, E2, Out2>(\n    that: MetricPolling<Type2, In2, R2, E2, Out2>\n  ): <Type, In, R, E, Out>(\n    self: MetricPolling<Type, In, R, E, Out>\n  ) => MetricPolling<\n    readonly [Type, Type2], // readonly because invariant\n    readonly [In, In2], // readonly because contravariant\n    R2 | R,\n    E2 | E,\n    [Out, Out2]\n  >\n  <Type, In, R, E, Out, Type2, In2, R2, E2, Out2>(\n    self: MetricPolling<Type, In, R, E, Out>,\n    that: MetricPolling<Type2, In2, R2, E2, Out2>\n  ): MetricPolling<\n    readonly [Type, Type2], // readonly because invariant\n    readonly [In, In2], // readonly because contravariant\n    R | R2,\n    E | E2,\n    [Out, Out2]\n  >\n} = internal.zip\n"
  },
  {
    "path": "packages/effect/src/MetricRegistry.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/metric/registry.js\"\nimport type * as MetricHook from \"./MetricHook.js\"\nimport type * as MetricKey from \"./MetricKey.js\"\nimport type * as MetricKeyType from \"./MetricKeyType.js\"\nimport type * as MetricPair from \"./MetricPair.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MetricRegistryTypeId: unique symbol = internal.MetricRegistryTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MetricRegistryTypeId = typeof MetricRegistryTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MetricRegistry {\n  readonly [MetricRegistryTypeId]: MetricRegistryTypeId\n  snapshot(): Array<MetricPair.MetricPair.Untyped>\n  get<Type extends MetricKeyType.MetricKeyType<any, any>>(\n    key: MetricKey.MetricKey<Type>\n  ): MetricHook.MetricHook<\n    MetricKeyType.MetricKeyType.InType<typeof key[\"keyType\"]>,\n    MetricKeyType.MetricKeyType.OutType<typeof key[\"keyType\"]>\n  >\n  getCounter<A extends (number | bigint)>(\n    key: MetricKey.MetricKey.Counter<A>\n  ): MetricHook.MetricHook.Counter<A>\n  getFrequency(key: MetricKey.MetricKey.Frequency): MetricHook.MetricHook.Frequency\n  getGauge<A extends (number | bigint)>(key: MetricKey.MetricKey.Gauge<A>): MetricHook.MetricHook.Gauge<A>\n  getHistogram(key: MetricKey.MetricKey.Histogram): MetricHook.MetricHook.Histogram\n  getSummary(key: MetricKey.MetricKey.Summary): MetricHook.MetricHook.Summary\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (_: void) => MetricRegistry = internal.make\n"
  },
  {
    "path": "packages/effect/src/MetricState.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Equal from \"./Equal.js\"\nimport * as internal from \"./internal/metric/state.js\"\nimport type * as MetricKeyType from \"./MetricKeyType.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const MetricStateTypeId: unique symbol = internal.MetricStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type MetricStateTypeId = typeof MetricStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const CounterStateTypeId: unique symbol = internal.CounterStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type CounterStateTypeId = typeof CounterStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const FrequencyStateTypeId: unique symbol = internal.FrequencyStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type FrequencyStateTypeId = typeof FrequencyStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const GaugeStateTypeId: unique symbol = internal.GaugeStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type GaugeStateTypeId = typeof GaugeStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const HistogramStateTypeId: unique symbol = internal.HistogramStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type HistogramStateTypeId = typeof HistogramStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const SummaryStateTypeId: unique symbol = internal.SummaryStateTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type SummaryStateTypeId = typeof SummaryStateTypeId\n\n/**\n * A `MetricState` describes the state of a metric. The type parameter of a\n * metric state corresponds to the type of the metric key (`MetricStateType`).\n * This phantom type parameter is used to tie keys to their expected states.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface MetricState<in A> extends MetricState.Variance<A>, Equal.Equal, Pipeable {}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace MetricState {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Untyped extends MetricState<any> {}\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Counter<in out A extends (number | bigint)>\n    extends MetricState<MetricKeyType.MetricKeyType.Counter<A>>\n  {\n    readonly [CounterStateTypeId]: CounterStateTypeId\n    readonly count: A\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Frequency extends MetricState<MetricKeyType.MetricKeyType.Frequency> {\n    readonly [FrequencyStateTypeId]: FrequencyStateTypeId\n    readonly occurrences: ReadonlyMap<string, number>\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Gauge<in out A extends (number | bigint)> extends MetricState<MetricKeyType.MetricKeyType.Gauge<A>> {\n    readonly [GaugeStateTypeId]: GaugeStateTypeId\n    readonly value: A\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Histogram extends MetricState<MetricKeyType.MetricKeyType.Histogram> {\n    readonly [HistogramStateTypeId]: HistogramStateTypeId\n    readonly buckets: ReadonlyArray<readonly [number, number]>\n    readonly count: number\n    readonly min: number\n    readonly max: number\n    readonly sum: number\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Summary extends MetricState<MetricKeyType.MetricKeyType.Summary> {\n    readonly [SummaryStateTypeId]: SummaryStateTypeId\n    readonly error: number\n    readonly quantiles: ReadonlyArray<readonly [number, Option.Option<number>]>\n    readonly count: number\n    readonly min: number\n    readonly max: number\n    readonly sum: number\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in A> {\n    readonly [MetricStateTypeId]: {\n      readonly _A: Types.Contravariant<A>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const counter: {\n  (count: number): MetricState.Counter<number>\n  (count: bigint): MetricState.Counter<bigint>\n} = internal.counter\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const frequency: (occurrences: ReadonlyMap<string, number>) => MetricState.Frequency = internal.frequency\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const gauge: {\n  (count: number): MetricState.Gauge<number>\n  (count: bigint): MetricState.Gauge<bigint>\n} = internal.gauge\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const histogram: (\n  options: {\n    readonly buckets: ReadonlyArray<readonly [number, number]>\n    readonly count: number\n    readonly min: number\n    readonly max: number\n    readonly sum: number\n  }\n) => MetricState.Histogram = internal.histogram\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const summary: (\n  options: {\n    readonly error: number\n    readonly quantiles: ReadonlyArray<readonly [number, Option.Option<number>]>\n    readonly count: number\n    readonly min: number\n    readonly max: number\n    readonly sum: number\n  }\n) => MetricState.Summary = internal.summary\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isMetricState: (u: unknown) => u is MetricState.Counter<number | bigint> = internal.isMetricState\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isCounterState: (u: unknown) => u is MetricState.Counter<number | bigint> = internal.isCounterState\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isFrequencyState: (u: unknown) => u is MetricState.Frequency = internal.isFrequencyState\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isGaugeState: (u: unknown) => u is MetricState.Gauge<number | bigint> = internal.isGaugeState\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isHistogramState: (u: unknown) => u is MetricState.Histogram = internal.isHistogramState\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isSummaryState: (u: unknown) => u is MetricState.Summary = internal.isSummaryState\n"
  },
  {
    "path": "packages/effect/src/Micro.ts",
    "content": "/**\n * A lightweight alternative to the `Effect` data type, with a subset of the functionality.\n *\n * @since 3.4.0\n * @experimental\n */\nimport * as Arr from \"./Array.js\"\nimport type { Channel } from \"./Channel.js\"\nimport * as Context from \"./Context.js\"\nimport type { Effect, EffectUnify, EffectUnifyIgnore } from \"./Effect.js\"\nimport * as Effectable from \"./Effectable.js\"\nimport * as Either from \"./Either.js\"\nimport * as Equal from \"./Equal.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport { constTrue, constVoid, dual, identity } from \"./Function.js\"\nimport { globalValue } from \"./GlobalValue.js\"\nimport * as Hash from \"./Hash.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport { format, NodeInspectSymbol, toStringUnknown } from \"./Inspectable.js\"\nimport * as InternalContext from \"./internal/context.js\"\nimport * as doNotation from \"./internal/doNotation.js\"\nimport { StructuralPrototype } from \"./internal/effectable.js\"\nimport * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport { hasProperty, isIterable, isTagged } from \"./Predicate.js\"\nimport type { Sink } from \"./Sink.js\"\nimport type { Stream } from \"./Stream.js\"\nimport type { Concurrency, Covariant, Equals, NoExcessProperties, NotFunction, Simplify } from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\nimport { SingleShotGen, YieldWrap, yieldWrapGet } from \"./Utils.js\"\n\n/**\n * @since 3.4.0\n * @experimental\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/Micro\")\n\n/**\n * @since 3.4.0\n * @experimental\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 3.4.0\n * @experimental\n * @category MicroExit\n */\nexport const MicroExitTypeId: unique symbol = Symbol.for(\n  \"effect/Micro/MicroExit\"\n)\n\n/**\n * @since 3.4.0\n * @experimental\n * @category MicroExit\n */\nexport type MicroExitTypeId = typeof TypeId\n\n/**\n * A lightweight alternative to the `Effect` data type, with a subset of the functionality.\n *\n * @since 3.4.0\n * @experimental\n * @category models\n */\nexport interface Micro<out A, out E = never, out R = never> extends Effect<A, E, R> {\n  readonly [TypeId]: Micro.Variance<A, E, R>\n  [Symbol.iterator](): MicroIterator<Micro<A, E, R>>\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: MicroUnify<this>\n  [Unify.ignoreSymbol]?: MicroUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.4.3\n */\nexport interface MicroUnify<A extends { [Unify.typeSymbol]?: any }> extends EffectUnify<A> {\n  Micro?: () => A[Unify.typeSymbol] extends Micro<infer A0, infer E0, infer R0> | infer _ ? Micro<A0, E0, R0> : never\n}\n\n/**\n * @category models\n * @since 3.4.3\n */\nexport interface MicroUnifyIgnore extends EffectUnifyIgnore {\n  Effect?: true\n}\n/**\n * @category type lambdas\n * @since 3.4.1\n */\nexport interface MicroTypeLambda extends TypeLambda {\n  readonly type: Micro<this[\"Target\"], this[\"Out1\"], this[\"Out2\"]>\n}\n\n/**\n * @since 3.4.0\n * @experimental\n */\nexport declare namespace Micro {\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export interface Variance<A, E, R> {\n    _A: Covariant<A>\n    _E: Covariant<E>\n    _R: Covariant<R>\n  }\n\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export type Success<T> = T extends Micro<infer _A, infer _E, infer _R> ? _A : never\n\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export type Error<T> = T extends Micro<infer _A, infer _E, infer _R> ? _E : never\n\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export type Context<T> = T extends Micro<infer _A, infer _E, infer _R> ? _R : never\n}\n\n/**\n * @since 3.4.0\n * @experimental\n * @category guards\n */\nexport const isMicro = (u: unknown): u is Micro<any, any, any> => typeof u === \"object\" && u !== null && TypeId in u\n\n/**\n * @since 3.4.0\n * @experimental\n * @category models\n */\nexport interface MicroIterator<T extends Micro<any, any, any>> {\n  next(...args: ReadonlyArray<any>): IteratorResult<YieldWrap<T>, Micro.Success<T>>\n}\n\n// ----------------------------------------------------------------------------\n// MicroCause\n// ----------------------------------------------------------------------------\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport const MicroCauseTypeId = Symbol.for(\"effect/Micro/MicroCause\")\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport type MicroCauseTypeId = typeof MicroCauseTypeId\n\n/**\n * A `MicroCause` is a data type that represents the different ways a `Micro` can fail.\n *\n * **Details**\n *\n * `MicroCause` comes in three forms:\n *\n * - `Die`: Indicates an unforeseen defect that wasn't planned for in the system's logic.\n * - `Fail`: Covers anticipated errors that are recognized and typically handled within the application.\n * - `Interrupt`: Signifies an operation that has been purposefully stopped.\n *\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport type MicroCause<E> =\n  | MicroCause.Die\n  | MicroCause.Fail<E>\n  | MicroCause.Interrupt\n\n/**\n * @since 3.6.6\n * @experimental\n * @category guards\n */\nexport const isMicroCause = (self: unknown): self is MicroCause<unknown> => hasProperty(self, MicroCauseTypeId)\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport declare namespace MicroCause {\n  /**\n   * @since 3.4.6\n   * @experimental\n   */\n  export type Error<T> = T extends MicroCause.Fail<infer E> ? E : never\n\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export interface Proto<Tag extends string, E> extends Pipeable, globalThis.Error {\n    readonly [MicroCauseTypeId]: {\n      _E: Covariant<E>\n    }\n    readonly _tag: Tag\n    readonly traces: ReadonlyArray<string>\n  }\n\n  /**\n   * @since 3.4.6\n   * @experimental\n   * @category MicroCause\n   */\n  export interface Die extends Proto<\"Die\", never> {\n    readonly defect: unknown\n  }\n\n  /**\n   * @since 3.4.6\n   * @experimental\n   * @category MicroCause\n   */\n  export interface Fail<E> extends Proto<\"Fail\", E> {\n    readonly error: E\n  }\n\n  /**\n   * @since 3.4.6\n   * @experimental\n   * @category MicroCause\n   */\n  export interface Interrupt extends Proto<\"Interrupt\", never> {}\n}\n\nconst microCauseVariance = {\n  _E: identity\n}\n\nabstract class MicroCauseImpl<Tag extends string, E> extends globalThis.Error implements MicroCause.Proto<Tag, E> {\n  readonly [MicroCauseTypeId]: {\n    _E: Covariant<E>\n  }\n  constructor(\n    readonly _tag: Tag,\n    originalError: unknown,\n    readonly traces: ReadonlyArray<string>\n  ) {\n    const causeName = `MicroCause.${_tag}`\n    let name: string\n    let message: string\n    let stack: string\n    if (originalError instanceof globalThis.Error) {\n      name = `(${causeName}) ${originalError.name}`\n      message = originalError.message as string\n      const messageLines = message.split(\"\\n\").length\n      stack = originalError.stack\n        ? `(${causeName}) ${\n          originalError.stack\n            .split(\"\\n\")\n            .slice(0, messageLines + 3)\n            .join(\"\\n\")\n        }`\n        : `${name}: ${message}`\n    } else {\n      name = causeName\n      message = toStringUnknown(originalError, 0)\n      stack = `${name}: ${message}`\n    }\n    if (traces.length > 0) {\n      stack += `\\n    ${traces.join(\"\\n    \")}`\n    }\n    super(message)\n    this[MicroCauseTypeId] = microCauseVariance\n    this.name = name\n    this.stack = stack\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n  toString() {\n    return this.stack\n  }\n  [NodeInspectSymbol]() {\n    return this.stack\n  }\n}\n\nclass Fail<E> extends MicroCauseImpl<\"Fail\", E> implements MicroCause.Fail<E> {\n  constructor(\n    readonly error: E,\n    traces: ReadonlyArray<string> = []\n  ) {\n    super(\"Fail\", error, traces)\n  }\n}\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport const causeFail = <E>(\n  error: E,\n  traces: ReadonlyArray<string> = []\n): MicroCause<E> => new Fail(error, traces)\n\nclass Die extends MicroCauseImpl<\"Die\", never> implements MicroCause.Die {\n  constructor(\n    readonly defect: unknown,\n    traces: ReadonlyArray<string> = []\n  ) {\n    super(\"Die\", defect, traces)\n  }\n}\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport const causeDie = (\n  defect: unknown,\n  traces: ReadonlyArray<string> = []\n): MicroCause<never> => new Die(defect, traces)\n\nclass Interrupt extends MicroCauseImpl<\"Interrupt\", never> implements MicroCause.Interrupt {\n  constructor(traces: ReadonlyArray<string> = []) {\n    super(\"Interrupt\", \"interrupted\", traces)\n  }\n}\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport const causeInterrupt = (\n  traces: ReadonlyArray<string> = []\n): MicroCause<never> => new Interrupt(traces)\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport const causeIsFail = <E>(\n  self: MicroCause<E>\n): self is MicroCause.Fail<E> => self._tag === \"Fail\"\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport const causeIsDie = <E>(self: MicroCause<E>): self is MicroCause.Die => self._tag === \"Die\"\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport const causeIsInterrupt = <E>(\n  self: MicroCause<E>\n): self is MicroCause.Interrupt => self._tag === \"Interrupt\"\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport const causeSquash = <E>(self: MicroCause<E>): unknown =>\n  self._tag === \"Fail\" ? self.error : self._tag === \"Die\" ? self.defect : self\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroCause\n */\nexport const causeWithTrace: {\n  (trace: string): <E>(self: MicroCause<E>) => MicroCause<E>\n  <E>(self: MicroCause<E>, trace: string): MicroCause<E>\n} = dual(2, <E>(self: MicroCause<E>, trace: string): MicroCause<E> => {\n  const traces = [...self.traces, trace]\n  switch (self._tag) {\n    case \"Die\":\n      return causeDie(self.defect, traces)\n    case \"Interrupt\":\n      return causeInterrupt(traces)\n    case \"Fail\":\n      return causeFail(self.error, traces)\n  }\n})\n\n// ----------------------------------------------------------------------------\n// MicroFiber\n// ----------------------------------------------------------------------------\n\n/**\n * @since 3.11.0\n * @experimental\n * @category MicroFiber\n */\nexport const MicroFiberTypeId = Symbol.for(\"effect/Micro/MicroFiber\")\n\n/**\n * @since 3.11.0\n * @experimental\n * @category MicroFiber\n */\nexport type MicroFiberTypeId = typeof MicroFiberTypeId\n\n/**\n * @since 3.11.0\n * @experimental\n * @category MicroFiber\n */\nexport interface MicroFiber<out A, out E = never> {\n  readonly [MicroFiberTypeId]: MicroFiber.Variance<A, E>\n\n  readonly currentOpCount: number\n  readonly getRef: <I, A>(ref: Context.Reference<I, A>) => A\n  readonly context: Context.Context<never>\n  readonly addObserver: (cb: (exit: MicroExit<A, E>) => void) => () => void\n  readonly unsafeInterrupt: () => void\n  readonly unsafePoll: () => MicroExit<A, E> | undefined\n}\n\n/**\n * @since 3.11.0\n * @experimental\n * @category MicroFiber\n */\nexport declare namespace MicroFiber {\n  /**\n   * @since 3.11.0\n   * @experimental\n   * @category MicroFiber\n   */\n  export interface Variance<out A, out E = never> {\n    readonly _A: Covariant<A>\n    readonly _E: Covariant<E>\n  }\n}\n\nconst fiberVariance = {\n  _A: identity,\n  _E: identity\n}\n\nclass MicroFiberImpl<in out A = any, in out E = any> implements MicroFiber<A, E> {\n  readonly [MicroFiberTypeId]: MicroFiber.Variance<A, E>\n\n  readonly _stack: Array<Primitive> = []\n  readonly _observers: Array<(exit: MicroExit<A, E>) => void> = []\n  _exit: MicroExit<A, E> | undefined\n  public _children: Set<MicroFiberImpl<any, any>> | undefined\n\n  public currentOpCount = 0\n\n  constructor(\n    public context: Context.Context<never>,\n    public interruptible = true\n  ) {\n    this[MicroFiberTypeId] = fiberVariance\n  }\n\n  getRef<I, A>(ref: Context.Reference<I, A>): A {\n    return InternalContext.unsafeGetReference(this.context, ref)\n  }\n\n  addObserver(cb: (exit: MicroExit<A, E>) => void): () => void {\n    if (this._exit) {\n      cb(this._exit)\n      return constVoid\n    }\n    this._observers.push(cb)\n    return () => {\n      const index = this._observers.indexOf(cb)\n      if (index >= 0) {\n        this._observers.splice(index, 1)\n      }\n    }\n  }\n\n  _interrupted = false\n  unsafeInterrupt(): void {\n    if (this._exit) {\n      return\n    }\n    this._interrupted = true\n    if (this.interruptible) {\n      this.evaluate(exitInterrupt as any)\n    }\n  }\n\n  unsafePoll(): MicroExit<A, E> | undefined {\n    return this._exit\n  }\n\n  evaluate(effect: Primitive): void {\n    if (this._exit) {\n      return\n    } else if (this._yielded !== undefined) {\n      const yielded = this._yielded as () => void\n      this._yielded = undefined\n      yielded()\n    }\n    const exit = this.runLoop(effect)\n    if (exit === Yield) {\n      return\n    }\n\n    // the interruptChildren middlware is added in Micro.fork, so it can be\n    // tree-shaken if not used\n    const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this)\n    if (interruptChildren !== undefined) {\n      return this.evaluate(flatMap(interruptChildren, () => exit) as any)\n    }\n\n    this._exit = exit\n    for (let i = 0; i < this._observers.length; i++) {\n      this._observers[i](exit)\n    }\n    this._observers.length = 0\n  }\n\n  runLoop(effect: Primitive): MicroExit<A, E> | Yield {\n    let yielding = false\n    let current: Primitive | Yield = effect\n    this.currentOpCount = 0\n    try {\n      while (true) {\n        this.currentOpCount++\n        if (!yielding && this.getRef(CurrentScheduler).shouldYield(this as any)) {\n          yielding = true\n          const prev = current\n          current = flatMap(yieldNow, () => prev as any) as any\n        }\n        current = (current as any)[evaluate](this)\n        if (current === Yield) {\n          const yielded = this._yielded!\n          if (MicroExitTypeId in yielded) {\n            this._yielded = undefined\n            return yielded\n          }\n          return Yield\n        }\n      }\n    } catch (error) {\n      if (!hasProperty(current, evaluate)) {\n        return exitDie(`MicroFiber.runLoop: Not a valid effect: ${String(current)}`)\n      }\n      return exitDie(error)\n    }\n  }\n\n  getCont<S extends successCont | failureCont>(\n    symbol: S\n  ): Primitive & Record<S, (value: any, fiber: MicroFiberImpl) => Primitive> | undefined {\n    while (true) {\n      const op = this._stack.pop()\n      if (!op) return undefined\n      const cont = op[ensureCont] && op[ensureCont](this)\n      if (cont) return { [symbol]: cont } as any\n      if (op[symbol]) return op as any\n    }\n  }\n\n  // cancel the yielded operation, or for the yielded exit value\n  _yielded: MicroExit<any, any> | (() => void) | undefined = undefined\n  yieldWith(value: MicroExit<any, any> | (() => void)): Yield {\n    this._yielded = value\n    return Yield\n  }\n\n  children(): Set<MicroFiber<any, any>> {\n    return this._children ??= new Set()\n  }\n}\n\nconst fiberMiddleware = globalValue(\"effect/Micro/fiberMiddleware\", () => ({\n  interruptChildren: undefined as ((fiber: MicroFiberImpl) => Micro<void> | undefined) | undefined\n}))\n\nconst fiberInterruptChildren = (fiber: MicroFiberImpl) => {\n  if (fiber._children === undefined || fiber._children.size === 0) {\n    return undefined\n  }\n  return fiberInterruptAll(fiber._children)\n}\n\n/**\n * @since 3.11.0\n * @experimental\n * @category MicroFiber\n */\nexport const fiberAwait = <A, E>(self: MicroFiber<A, E>): Micro<MicroExit<A, E>> =>\n  async((resume) => sync(self.addObserver((exit) => resume(succeed(exit)))))\n\n/**\n * @since 3.11.2\n * @experimental\n * @category MicroFiber\n */\nexport const fiberJoin = <A, E>(self: MicroFiber<A, E>): Micro<A, E> => flatten(fiberAwait(self))\n\n/**\n * @since 3.11.0\n * @experimental\n * @category MicroFiber\n */\nexport const fiberInterrupt = <A, E>(self: MicroFiber<A, E>): Micro<void> =>\n  suspend(() => {\n    self.unsafeInterrupt()\n    return asVoid(fiberAwait(self))\n  })\n\n/**\n * @since 3.11.0\n * @experimental\n * @category MicroFiber\n */\nexport const fiberInterruptAll = <A extends Iterable<MicroFiber<any, any>>>(fibers: A): Micro<void> =>\n  suspend(() => {\n    for (const fiber of fibers) fiber.unsafeInterrupt()\n    const iter = fibers[Symbol.iterator]()\n    const wait: Micro<void> = suspend(() => {\n      let result = iter.next()\n      while (!result.done) {\n        if (result.value.unsafePoll()) {\n          result = iter.next()\n          continue\n        }\n        const fiber = result.value\n        return async((resume) => {\n          fiber.addObserver((_) => {\n            resume(wait)\n          })\n        })\n      }\n      return exitVoid\n    })\n    return wait\n  })\n\nconst identifier = Symbol.for(\"effect/Micro/identifier\")\ntype identifier = typeof identifier\n\nconst args = Symbol.for(\"effect/Micro/args\")\ntype args = typeof args\n\nconst evaluate = Symbol.for(\"effect/Micro/evaluate\")\ntype evaluate = typeof evaluate\n\nconst successCont = Symbol.for(\"effect/Micro/successCont\")\ntype successCont = typeof successCont\n\nconst failureCont = Symbol.for(\"effect/Micro/failureCont\")\ntype failureCont = typeof failureCont\n\nconst ensureCont = Symbol.for(\"effect/Micro/ensureCont\")\ntype ensureCont = typeof ensureCont\n\nconst Yield = Symbol.for(\"effect/Micro/Yield\")\ntype Yield = typeof Yield\n\ninterface Primitive {\n  readonly [identifier]: string\n  readonly [successCont]: ((value: unknown, fiber: MicroFiberImpl) => Primitive | Yield) | undefined\n  readonly [failureCont]:\n    | ((cause: MicroCause<unknown>, fiber: MicroFiberImpl) => Primitive | Yield)\n    | undefined\n  readonly [ensureCont]:\n    | ((fiber: MicroFiberImpl) =>\n      | ((value: unknown, fiber: MicroFiberImpl) => Primitive | Yield)\n      | undefined)\n    | undefined\n  [evaluate](fiber: MicroFiberImpl): Primitive | Yield\n}\n\nconst microVariance = {\n  _A: identity,\n  _E: identity,\n  _R: identity\n}\n\nconst MicroProto = {\n  ...Effectable.EffectPrototype,\n  _op: \"Micro\",\n  [TypeId]: microVariance,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  [Symbol.iterator]() {\n    return new SingleShotGen(new YieldWrap(this)) as any\n  },\n  toJSON(this: Primitive) {\n    return {\n      _id: \"Micro\",\n      op: this[identifier],\n      ...(args in this ? { args: this[args] } : undefined)\n    }\n  },\n  toString() {\n    return format(this)\n  },\n  [NodeInspectSymbol]() {\n    return format(this)\n  }\n}\n\nfunction defaultEvaluate(_fiber: MicroFiberImpl): Primitive | Yield {\n  return exitDie(`Micro.evaluate: Not implemented`) as any\n}\n\nconst makePrimitiveProto = <Op extends string>(options: {\n  readonly op: Op\n  readonly eval?: (fiber: MicroFiberImpl) => Primitive | Micro<any, any, any> | Yield\n  readonly contA?: (this: Primitive, value: any, fiber: MicroFiberImpl) => Primitive | Micro<any, any, any> | Yield\n  readonly contE?: (\n    this: Primitive,\n    cause: MicroCause<any>,\n    fiber: MicroFiberImpl\n  ) => Primitive | Micro<any, any, any> | Yield\n  readonly ensure?: (this: Primitive, fiber: MicroFiberImpl) => void | ((value: any, fiber: MicroFiberImpl) => void)\n}): Primitive => ({\n  ...MicroProto,\n  [identifier]: options.op,\n  [evaluate]: options.eval ?? defaultEvaluate,\n  [successCont]: options.contA,\n  [failureCont]: options.contE,\n  [ensureCont]: options.ensure\n} as any)\n\nconst makePrimitive = <Fn extends (...args: Array<any>) => any, Single extends boolean = true>(options: {\n  readonly op: string\n  readonly single?: Single\n  readonly eval?: (\n    this: Primitive & { readonly [args]: Single extends true ? Parameters<Fn>[0] : Parameters<Fn> },\n    fiber: MicroFiberImpl\n  ) => Primitive | Micro<any, any, any> | Yield\n  readonly contA?: (\n    this: Primitive & { readonly [args]: Single extends true ? Parameters<Fn>[0] : Parameters<Fn> },\n    value: any,\n    fiber: MicroFiberImpl\n  ) => Primitive | Micro<any, any, any> | Yield\n  readonly contE?: (\n    this: Primitive & { readonly [args]: Single extends true ? Parameters<Fn>[0] : Parameters<Fn> },\n    cause: MicroCause<any>,\n    fiber: MicroFiberImpl\n  ) => Primitive | Micro<any, any, any> | Yield\n  readonly ensure?: (\n    this: Primitive & { readonly [args]: Single extends true ? Parameters<Fn>[0] : Parameters<Fn> },\n    fiber: MicroFiberImpl\n  ) => void | ((value: any, fiber: MicroFiberImpl) => void)\n}): Fn => {\n  const Proto = makePrimitiveProto(options as any)\n  return function() {\n    const self = Object.create(Proto)\n    self[args] = options.single === false ? arguments : arguments[0]\n    return self\n  } as Fn\n}\n\nconst makeExit = <Fn extends (...args: Array<any>) => any, Prop extends string>(options: {\n  readonly op: \"Success\" | \"Failure\"\n  readonly prop: Prop\n  readonly eval: (\n    this:\n      & MicroExit<unknown, unknown>\n      & { [args]: Parameters<Fn>[0] },\n    fiber: MicroFiberImpl<unknown, unknown>\n  ) => Primitive | Yield\n}): Fn => {\n  const Proto = {\n    ...makePrimitiveProto(options),\n    [MicroExitTypeId]: MicroExitTypeId,\n    _tag: options.op,\n    get [options.prop](): any {\n      return (this as any)[args]\n    },\n    toJSON(this: any) {\n      return {\n        _id: \"MicroExit\",\n        _tag: options.op,\n        [options.prop]: this[args]\n      }\n    },\n    [Equal.symbol](this: any, that: any): boolean {\n      return isMicroExit(that) && that._tag === options.op &&\n        Equal.equals(this[args], (that as any)[args])\n    },\n    [Hash.symbol](this: any): number {\n      return Hash.cached(this, Hash.combine(Hash.string(options.op))(Hash.hash(this[args])))\n    }\n  }\n  return function(value: unknown) {\n    const self = Object.create(Proto)\n    self[args] = value\n    self[successCont] = undefined\n    self[failureCont] = undefined\n    self[ensureCont] = undefined\n    return self\n  } as Fn\n}\n\n/**\n * Creates a `Micro` effect that will succeed with the specified constant value.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const succeed: <A>(value: A) => Micro<A> = makeExit({\n  op: \"Success\",\n  prop: \"value\",\n  eval(fiber) {\n    const cont = fiber.getCont(successCont)\n    return cont ? cont[successCont](this[args], fiber) : fiber.yieldWith(this)\n  }\n})\n\n/**\n * Creates a `Micro` effect that will fail with the specified `MicroCause`.\n *\n * @since 3.4.6\n * @experimental\n * @category constructors\n */\nexport const failCause: <E>(cause: MicroCause<E>) => Micro<never, E> = makeExit({\n  op: \"Failure\",\n  prop: \"cause\",\n  eval(fiber) {\n    let cont = fiber.getCont(failureCont)\n    while (causeIsInterrupt(this[args]) && cont && fiber.interruptible) {\n      cont = fiber.getCont(failureCont)\n    }\n    return cont ? cont[failureCont](this[args], fiber) : fiber.yieldWith(this)\n  }\n})\n\n/**\n * Creates a `Micro` effect that fails with the given error.\n *\n * This results in a `Fail` variant of the `MicroCause` type, where the error is\n * tracked at the type level.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const fail = <E>(error: E): Micro<never, E> => failCause(causeFail(error))\n\n/**\n * Creates a `Micro` effect that succeeds with a lazily evaluated value.\n *\n * If the evaluation of the value throws an error, the effect will fail with a\n * `Die` variant of the `MicroCause` type.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const sync: <A>(evaluate: LazyArg<A>) => Micro<A> = makePrimitive({\n  op: \"Sync\",\n  eval(fiber): Primitive | Yield {\n    const value = this[args]()\n    const cont = fiber.getCont(successCont)\n    return cont ? cont[successCont](value, fiber) : fiber.yieldWith(exitSucceed(value))\n  }\n})\n\n/**\n * Lazily creates a `Micro` effect from the given side-effect.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const suspend: <A, E, R>(evaluate: LazyArg<Micro<A, E, R>>) => Micro<A, E, R> = makePrimitive({\n  op: \"Suspend\",\n  eval(_fiber) {\n    return this[args]()\n  }\n})\n\n/**\n * Pause the execution of the current `Micro` effect, and resume it on the next\n * scheduler tick.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const yieldNowWith: (priority?: number) => Micro<void> = makePrimitive({\n  op: \"Yield\",\n  eval(fiber) {\n    let resumed = false\n    fiber.getRef(CurrentScheduler).scheduleTask(() => {\n      if (resumed) return\n      fiber.evaluate(exitVoid as any)\n    }, this[args] ?? 0)\n    return fiber.yieldWith(() => {\n      resumed = true\n    })\n  }\n})\n\n/**\n * Pause the execution of the current `Micro` effect, and resume it on the next\n * scheduler tick.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const yieldNow: Micro<void> = yieldNowWith(0)\n\n/**\n * Creates a `Micro` effect that will succeed with the value wrapped in `Some`.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const succeedSome = <A>(a: A): Micro<Option.Option<A>> => succeed(Option.some(a))\n\n/**\n * Creates a `Micro` effect that succeeds with `None`.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const succeedNone: Micro<Option.Option<never>> = succeed(Option.none())\n\n/**\n * Creates a `Micro` effect that will fail with the lazily evaluated `MicroCause`.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const failCauseSync = <E>(evaluate: LazyArg<MicroCause<E>>): Micro<never, E> =>\n  suspend(() => failCause(evaluate()))\n\n/**\n * Creates a `Micro` effect that will die with the specified error.\n *\n * This results in a `Die` variant of the `MicroCause` type, where the error is\n * not tracked at the type level.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const die = (defect: unknown): Micro<never> => exitDie(defect)\n\n/**\n * Creates a `Micro` effect that will fail with the lazily evaluated error.\n *\n * This results in a `Fail` variant of the `MicroCause` type, where the error is\n * tracked at the type level.\n *\n * @since 3.4.6\n * @experimental\n * @category constructors\n */\nexport const failSync = <E>(error: LazyArg<E>): Micro<never, E> => suspend(() => fail(error()))\n\n/**\n * Converts an `Option` into a `Micro` effect, that will fail with\n * `NoSuchElementException` if the option is `None`. Otherwise, it will succeed with the\n * value of the option.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const fromOption = <A>(option: Option.Option<A>): Micro<A, NoSuchElementException> =>\n  option._tag === \"Some\" ? succeed(option.value) : fail(new NoSuchElementException({}))\n\n/**\n * Converts an `Either` into a `Micro` effect, that will fail with the left side\n * of the either if it is a `Left`. Otherwise, it will succeed with the right\n * side of the either.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const fromEither = <R, L>(either: Either.Either<R, L>): Micro<R, L> =>\n  either._tag === \"Right\" ? succeed(either.right) : fail(either.left)\n\nconst void_: Micro<void> = succeed(void 0)\nexport {\n  /**\n   * A `Micro` effect that will succeed with `void` (`undefined`).\n   *\n   * @since 3.4.0\n   * @experimental\n   * @category constructors\n   */\n  void_ as void\n}\n\nconst try_ = <A, E>(options: {\n  try: LazyArg<A>\n  catch: (error: unknown) => E\n}): Micro<A, E> =>\n  suspend(() => {\n    try {\n      return succeed(options.try())\n    } catch (err) {\n      return fail(options.catch(err))\n    }\n  })\nexport {\n  /**\n   * The `Micro` equivalent of a try / catch block, which allows you to map\n   * thrown errors to a specific error type.\n   *\n   * @example\n   * ```ts\n   * import { Micro } from \"effect\"\n   *\n   * Micro.try({\n   *   try: () => { throw new Error(\"boom\") },\n   *   catch: (cause) => new Error(\"caught\", { cause })\n   * })\n   * ```\n   *\n   * @since 3.4.0\n   * @experimental\n   * @category constructors\n   */\n  try_ as try\n}\n\n/**\n * Wrap a `Promise` into a `Micro` effect.\n *\n * Any errors will result in a `Die` variant of the `MicroCause` type, where the\n * error is not tracked at the type level.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const promise = <A>(evaluate: (signal: AbortSignal) => PromiseLike<A>): Micro<A> =>\n  asyncOptions<A>(function(resume, signal) {\n    evaluate(signal!).then(\n      (a) => resume(succeed(a)),\n      (e) => resume(die(e))\n    )\n  }, evaluate.length !== 0)\n\n/**\n * Wrap a `Promise` into a `Micro` effect. Any errors will be caught and\n * converted into a specific error type.\n *\n * @example\n * ```ts\n * import { Micro } from \"effect\"\n *\n * Micro.tryPromise({\n *   try: () => Promise.resolve(\"success\"),\n *   catch: (cause) => new Error(\"caught\", { cause })\n * })\n * ```\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const tryPromise = <A, E>(options: {\n  readonly try: (signal: AbortSignal) => PromiseLike<A>\n  readonly catch: (error: unknown) => E\n}): Micro<A, E> =>\n  asyncOptions<A, E>(function(resume, signal) {\n    try {\n      options.try(signal!).then(\n        (a) => resume(succeed(a)),\n        (e) => resume(fail(options.catch(e)))\n      )\n    } catch (err) {\n      resume(fail(options.catch(err)))\n    }\n  }, options.try.length !== 0)\n\n/**\n * Create a `Micro` effect using the current `MicroFiber`.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const withMicroFiber: <A, E = never, R = never>(\n  evaluate: (fiber: MicroFiberImpl<A, E>) => Micro<A, E, R>\n) => Micro<A, E, R> = makePrimitive({\n  op: \"WithMicroFiber\",\n  eval(fiber) {\n    return this[args](fiber)\n  }\n})\n\n/**\n * Flush any yielded effects that are waiting to be executed.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const yieldFlush: Micro<void> = withMicroFiber((fiber) => {\n  fiber.getRef(CurrentScheduler).flush()\n  return exitVoid\n})\n\nconst asyncOptions: <A, E = never, R = never>(\n  register: (\n    resume: (effect: Micro<A, E, R>) => void,\n    signal?: AbortSignal\n  ) => void | Micro<void, never, R>,\n  withSignal: boolean\n) => Micro<A, E, R> = makePrimitive({\n  op: \"Async\",\n  single: false,\n  eval(fiber) {\n    const register = this[args][0]\n    let resumed = false\n    let yielded: boolean | Primitive = false\n    const controller = this[args][1] ? new AbortController() : undefined\n    const onCancel = register((effect) => {\n      if (resumed) return\n      resumed = true\n      if (yielded) {\n        fiber.evaluate(effect as any)\n      } else {\n        yielded = effect as any\n      }\n    }, controller?.signal)\n    if (yielded !== false) return yielded\n    yielded = true\n    fiber._yielded = () => {\n      resumed = true\n    }\n    if (controller === undefined && onCancel === undefined) {\n      return Yield\n    }\n    fiber._stack.push(asyncFinalizer(() => {\n      resumed = true\n      controller?.abort()\n      return onCancel ?? exitVoid\n    }))\n    return Yield\n  }\n})\nconst asyncFinalizer: (onInterrupt: () => Micro<void, any, any>) => Primitive = makePrimitive({\n  op: \"AsyncFinalizer\",\n  ensure(fiber) {\n    if (fiber.interruptible) {\n      fiber.interruptible = false\n      fiber._stack.push(setInterruptible(true))\n    }\n  },\n  contE(cause, _fiber) {\n    return causeIsInterrupt(cause)\n      ? flatMap(this[args](), () => failCause(cause))\n      : failCause(cause)\n  }\n})\n\n/**\n * Create a `Micro` effect from an asynchronous computation.\n *\n * You can return a cleanup effect that will be run when the effect is aborted.\n * It is also passed an `AbortSignal` that is triggered when the effect is\n * aborted.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const async = <A, E = never, R = never>(\n  register: (\n    resume: (effect: Micro<A, E, R>) => void,\n    signal: AbortSignal\n  ) => void | Micro<void, never, R>\n): Micro<A, E, R> => asyncOptions(register as any, register.length >= 2)\n\n/**\n * A `Micro` that will never succeed or fail. It wraps `setInterval` to prevent\n * the Javascript runtime from exiting.\n *\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const never: Micro<never> = async<never>(function() {\n  const interval = setInterval(constVoid, 2147483646)\n  return sync(() => clearInterval(interval))\n})\n\n/**\n * @since 3.4.0\n * @experimental\n * @category constructors\n */\nexport const gen = <Self, Eff extends YieldWrap<Micro<any, any, any>>, AEff>(\n  ...args:\n    | [self: Self, body: (this: Self) => Generator<Eff, AEff, never>]\n    | [body: () => Generator<Eff, AEff, never>]\n): Micro<\n  AEff,\n  [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Micro<infer _A, infer E, infer _R>>] ? E : never,\n  [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Micro<infer _A, infer _E, infer R>>] ? R : never\n> => suspend(() => fromIterator(args.length === 1 ? args[0]() : args[1].call(args[0]) as any))\n\nconst fromIterator: (\n  iterator: Iterator<any, YieldWrap<Micro<any, any, any>>>\n) => Micro<any, any, any> = makePrimitive({\n  op: \"Iterator\",\n  contA(value, fiber) {\n    const state = this[args].next(value)\n    if (state.done) return succeed(state.value)\n    fiber._stack.push(this)\n    return yieldWrapGet(state.value)\n  },\n  eval(this: any, fiber: MicroFiberImpl) {\n    return this[successCont](undefined, fiber)\n  }\n})\n\n// ----------------------------------------------------------------------------\n// mapping & sequencing\n// ----------------------------------------------------------------------------\n\n/**\n * Create a `Micro` effect that will replace the success value of the given\n * effect.\n *\n * @since 3.4.0\n * @experimental\n * @category mapping & sequencing\n */\nexport const as: {\n  <A, B>(value: B): <E, R>(self: Micro<A, E, R>) => Micro<B, E, R>\n  <A, E, R, B>(self: Micro<A, E, R>, value: B): Micro<B, E, R>\n} = dual(2, <A, E, R, B>(self: Micro<A, E, R>, value: B): Micro<B, E, R> => map(self, (_) => value))\n\n/**\n * Wrap the success value of this `Micro` effect in a `Some`.\n *\n * @since 3.4.0\n * @experimental\n * @category mapping & sequencing\n */\nexport const asSome = <A, E, R>(self: Micro<A, E, R>): Micro<Option.Option<A>, E, R> => map(self, Option.some)\n\n/**\n * Swap the error and success types of the `Micro` effect.\n *\n * @since 3.4.0\n * @experimental\n * @category mapping & sequencing\n */\nexport const flip = <A, E, R>(self: Micro<A, E, R>): Micro<E, A, R> =>\n  matchEffect(self, {\n    onFailure: succeed,\n    onSuccess: fail\n  })\n\n/**\n * A more flexible version of `flatMap` that combines `map` and `flatMap` into a\n * single API.\n *\n * It also lets you directly pass a `Micro` effect, which will be executed after\n * the current effect.\n *\n * @since 3.4.0\n * @experimental\n * @category mapping & sequencing\n */\nexport const andThen: {\n  <A, X>(\n    f: (a: A) => X\n  ): <E, R>(\n    self: Micro<A, E, R>\n  ) => [X] extends [Micro<infer A1, infer E1, infer R1>] ? Micro<A1, E | E1, R | R1>\n    : Micro<X, E, R>\n  <X>(\n    f: NotFunction<X>\n  ): <A, E, R>(\n    self: Micro<A, E, R>\n  ) => [X] extends [Micro<infer A1, infer E1, infer R1>] ? Micro<A1, E | E1, R | R1>\n    : Micro<X, E, R>\n  <A, E, R, X>(\n    self: Micro<A, E, R>,\n    f: (a: A) => X\n  ): [X] extends [Micro<infer A1, infer E1, infer R1>] ? Micro<A1, E | E1, R | R1>\n    : Micro<X, E, R>\n  <A, E, R, X>(\n    self: Micro<A, E, R>,\n    f: NotFunction<X>\n  ): [X] extends [Micro<infer A1, infer E1, infer R1>] ? Micro<A1, E | E1, R | R1>\n    : Micro<X, E, R>\n} = dual(\n  2,\n  <A, E, R, B, E2, R2>(self: Micro<A, E, R>, f: any): Micro<B, E | E2, R | R2> =>\n    flatMap(self, (a) => {\n      const value = isMicro(f) ? f : typeof f === \"function\" ? f(a) : f\n      return isMicro(value) ? value : succeed(value)\n    })\n)\n\n/**\n * Execute a side effect from the success value of the `Micro` effect.\n *\n * It is similar to the `andThen` api, but the success value is ignored.\n *\n * @since 3.4.0\n * @experimental\n * @category mapping & sequencing\n */\nexport const tap: {\n  <A, X>(\n    f: (a: NoInfer<A>) => X\n  ): <E, R>(\n    self: Micro<A, E, R>\n  ) => [X] extends [Micro<infer _A1, infer E1, infer R1>] ? Micro<A, E | E1, R | R1>\n    : Micro<A, E, R>\n  <X>(\n    f: NotFunction<X>\n  ): <A, E, R>(\n    self: Micro<A, E, R>\n  ) => [X] extends [Micro<infer _A1, infer E1, infer R1>] ? Micro<A, E | E1, R | R1>\n    : Micro<A, E, R>\n  <A, E, R, X>(\n    self: Micro<A, E, R>,\n    f: (a: NoInfer<A>) => X\n  ): [X] extends [Micro<infer _A1, infer E1, infer R1>] ? Micro<A, E | E1, R | R1>\n    : Micro<A, E, R>\n  <A, E, R, X>(\n    self: Micro<A, E, R>,\n    f: NotFunction<X>\n  ): [X] extends [Micro<infer _A1, infer E1, infer R1>] ? Micro<A, E | E1, R | R1>\n    : Micro<A, E, R>\n} = dual(\n  2,\n  <A, E, R, B, E2, R2>(self: Micro<A, E, R>, f: (a: A) => Micro<B, E2, R2>): Micro<A, E | E2, R | R2> =>\n    flatMap(self, (a) => {\n      const value = isMicro(f) ? f : typeof f === \"function\" ? f(a) : f\n      return isMicro(value) ? as(value, a) : succeed(a)\n    })\n)\n\n/**\n * Replace the success value of the `Micro` effect with `void`.\n *\n * @since 3.4.0\n * @experimental\n * @category mapping & sequencing\n */\nexport const asVoid = <A, E, R>(self: Micro<A, E, R>): Micro<void, E, R> => flatMap(self, (_) => exitVoid)\n\n/**\n * Access the `MicroExit` of the given `Micro` effect.\n *\n * @since 3.4.6\n * @experimental\n * @category mapping & sequencing\n */\nexport const exit = <A, E, R>(self: Micro<A, E, R>): Micro<MicroExit<A, E>, never, R> =>\n  matchCause(self, {\n    onFailure: exitFailCause,\n    onSuccess: exitSucceed\n  })\n\n/**\n * Replace the error type of the given `Micro` with the full `MicroCause` object.\n *\n * @since 3.4.0\n * @experimental\n * @category mapping & sequencing\n */\nexport const sandbox = <A, E, R>(self: Micro<A, E, R>): Micro<A, MicroCause<E>, R> => catchAllCause(self, fail)\n\n/**\n * Returns an effect that races all the specified effects,\n * yielding the value of the first effect to succeed with a value. Losers of\n * the race will be interrupted immediately\n *\n * @since 3.4.0\n * @experimental\n * @category sequencing\n */\nexport const raceAll = <Eff extends Micro<any, any, any>>(\n  all: Iterable<Eff>\n): Micro<Micro.Success<Eff>, Micro.Error<Eff>, Micro.Context<Eff>> =>\n  withMicroFiber((parent) =>\n    async((resume) => {\n      const effects = Arr.fromIterable(all)\n      const len = effects.length\n      let doneCount = 0\n      let done = false\n      const fibers = new Set<MicroFiber<any, any>>()\n      const causes: Array<MicroCause<any>> = []\n      const onExit = (exit: MicroExit<any, any>) => {\n        doneCount++\n        if (exit._tag === \"Failure\") {\n          causes.push(exit.cause)\n          if (doneCount >= len) {\n            resume(failCause(causes[0]))\n          }\n          return\n        }\n        done = true\n        resume(fibers.size === 0 ? exit : flatMap(uninterruptible(fiberInterruptAll(fibers)), () => exit))\n      }\n\n      for (let i = 0; i < len; i++) {\n        if (done) break\n        const fiber = unsafeFork(parent, interruptible(effects[i]), true, true)\n        fibers.add(fiber)\n        fiber.addObserver((exit) => {\n          fibers.delete(fiber)\n          onExit(exit)\n        })\n      }\n\n      return fiberInterruptAll(fibers)\n    })\n  )\n\n/**\n * Returns an effect that races all the specified effects,\n * yielding the value of the first effect to succeed or fail. Losers of\n * the race will be interrupted immediately.\n *\n * @since 3.4.0\n * @experimental\n * @category sequencing\n */\nexport const raceAllFirst = <Eff extends Micro<any, any, any>>(\n  all: Iterable<Eff>\n): Micro<Micro.Success<Eff>, Micro.Error<Eff>, Micro.Context<Eff>> =>\n  withMicroFiber((parent) =>\n    async((resume) => {\n      let done = false\n      const fibers = new Set<MicroFiber<any, any>>()\n      const onExit = (exit: MicroExit<any, any>) => {\n        done = true\n        resume(fibers.size === 0 ? exit : flatMap(fiberInterruptAll(fibers), () => exit))\n      }\n\n      for (const effect of all) {\n        if (done) break\n        const fiber = unsafeFork(parent, interruptible(effect), true, true)\n        fibers.add(fiber)\n        fiber.addObserver((exit) => {\n          fibers.delete(fiber)\n          onExit(exit)\n        })\n      }\n\n      return fiberInterruptAll(fibers)\n    })\n  )\n\n/**\n * Returns an effect that races two effects, yielding the value of the first\n * effect to succeed. Losers of the race will be interrupted immediately.\n *\n * @since 3.4.0\n * @experimental\n * @category sequencing\n */\nexport const race: {\n  <A2, E2, R2>(that: Micro<A2, E2, R2>): <A, E, R>(self: Micro<A, E, R>) => Micro<A | A2, E | E2, R | R2>\n  <A, E, R, A2, E2, R2>(self: Micro<A, E, R>, that: Micro<A2, E2, R2>): Micro<A | A2, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, A2, E2, R2>(self: Micro<A, E, R>, that: Micro<A2, E2, R2>): Micro<A | A2, E | E2, R | R2> =>\n    raceAll([self, that])\n)\n\n/**\n * Returns an effect that races two effects, yielding the value of the first\n * effect to succeed *or* fail. Losers of the race will be interrupted immediately.\n *\n * @since 3.4.0\n * @experimental\n * @category sequencing\n */\nexport const raceFirst: {\n  <A2, E2, R2>(that: Micro<A2, E2, R2>): <A, E, R>(self: Micro<A, E, R>) => Micro<A | A2, E | E2, R | R2>\n  <A, E, R, A2, E2, R2>(self: Micro<A, E, R>, that: Micro<A2, E2, R2>): Micro<A | A2, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, A2, E2, R2>(self: Micro<A, E, R>, that: Micro<A2, E2, R2>): Micro<A | A2, E | E2, R | R2> =>\n    raceAllFirst([self, that])\n)\n\n/**\n * Map the success value of this `Micro` effect to another `Micro` effect, then\n * flatten the result.\n *\n * @since 3.4.0\n * @experimental\n * @category mapping & sequencing\n */\nexport const flatMap: {\n  <A, B, E2, R2>(\n    f: (a: A) => Micro<B, E2, R2>\n  ): <E, R>(self: Micro<A, E, R>) => Micro<B, E | E2, R | R2>\n  <A, E, R, B, E2, R2>(\n    self: Micro<A, E, R>,\n    f: (a: A) => Micro<B, E2, R2>\n  ): Micro<B, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, B, E2, R2>(\n    self: Micro<A, E, R>,\n    f: (a: A) => Micro<B, E2, R2>\n  ): Micro<B, E | E2, R | R2> => {\n    const onSuccess = Object.create(OnSuccessProto)\n    onSuccess[args] = self\n    onSuccess[successCont] = f\n    return onSuccess\n  }\n)\nconst OnSuccessProto = makePrimitiveProto({\n  op: \"OnSuccess\",\n  eval(this: any, fiber: MicroFiberImpl): Primitive {\n    fiber._stack.push(this)\n    return this[args]\n  }\n})\n\n// ----------------------------------------------------------------------------\n// mapping & sequencing\n// ----------------------------------------------------------------------------\n\n/**\n * Flattens any nested `Micro` effects, merging the error and requirement types.\n *\n * @since 3.4.0\n * @experimental\n * @category mapping & sequencing\n */\nexport const flatten = <A, E, R, E2, R2>(\n  self: Micro<Micro<A, E, R>, E2, R2>\n): Micro<A, E | E2, R | R2> => flatMap(self, identity)\n\n/**\n * Transforms the success value of the `Micro` effect with the specified\n * function.\n *\n * @since 3.4.0\n * @experimental\n * @category mapping & sequencing\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): <E, R>(self: Micro<A, E, R>) => Micro<B, E, R>\n  <A, E, R, B>(self: Micro<A, E, R>, f: (a: A) => B): Micro<B, E, R>\n} = dual(\n  2,\n  <A, E, R, B>(self: Micro<A, E, R>, f: (a: A) => B): Micro<B, E, R> => flatMap(self, (a) => succeed(f(a)))\n)\n\n// ----------------------------------------------------------------------------\n// MicroExit\n// ----------------------------------------------------------------------------\n\n/**\n * The `MicroExit` type is used to represent the result of a `Micro` computation. It\n * can either be successful, containing a value of type `A`, or it can fail,\n * containing an error of type `E` wrapped in a `MicroCause`.\n *\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport type MicroExit<A, E = never> =\n  | MicroExit.Success<A, E>\n  | MicroExit.Failure<A, E>\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport declare namespace MicroExit {\n  /**\n   * @since 3.4.6\n   * @experimental\n   * @category MicroExit\n   */\n  export interface Proto<out A, out E = never> extends Micro<A, E> {\n    readonly [MicroExitTypeId]: MicroExitTypeId\n  }\n\n  /**\n   * @since 3.4.6\n   * @experimental\n   * @category MicroExit\n   */\n  export interface Success<out A, out E> extends Proto<A, E> {\n    readonly _tag: \"Success\"\n    readonly value: A\n  }\n\n  /**\n   * @since 3.4.6\n   * @experimental\n   * @category MicroExit\n   */\n  export interface Failure<out A, out E> extends Proto<A, E> {\n    readonly _tag: \"Failure\"\n    readonly cause: MicroCause<E>\n  }\n}\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const isMicroExit = (u: unknown): u is MicroExit<unknown, unknown> => hasProperty(u, MicroExitTypeId)\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitSucceed: <A>(a: A) => MicroExit<A, never> = succeed as any\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitFailCause: <E>(cause: MicroCause<E>) => MicroExit<never, E> = failCause as any\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitInterrupt: MicroExit<never> = exitFailCause(causeInterrupt())\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitFail = <E>(e: E): MicroExit<never, E> => exitFailCause(causeFail(e))\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitDie = (defect: unknown): MicroExit<never> => exitFailCause(causeDie(defect))\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitIsSuccess = <A, E>(\n  self: MicroExit<A, E>\n): self is MicroExit.Success<A, E> => self._tag === \"Success\"\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitIsFailure = <A, E>(\n  self: MicroExit<A, E>\n): self is MicroExit.Failure<A, E> => self._tag === \"Failure\"\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitIsInterrupt = <A, E>(\n  self: MicroExit<A, E>\n): self is MicroExit.Failure<A, E> & {\n  readonly cause: MicroCause.Interrupt\n} => exitIsFailure(self) && self.cause._tag === \"Interrupt\"\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitIsFail = <A, E>(\n  self: MicroExit<A, E>\n): self is MicroExit.Failure<A, E> & {\n  readonly cause: MicroCause.Fail<E>\n} => exitIsFailure(self) && self.cause._tag === \"Fail\"\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitIsDie = <A, E>(\n  self: MicroExit<A, E>\n): self is MicroExit.Failure<A, E> & {\n  readonly cause: MicroCause.Die\n} => exitIsFailure(self) && self.cause._tag === \"Die\"\n\n/**\n * @since 3.4.6\n * @experimental\n * @category MicroExit\n */\nexport const exitVoid: MicroExit<void> = exitSucceed(void 0)\n\n/**\n * @since 3.11.0\n * @experimental\n * @category MicroExit\n */\nexport const exitVoidAll = <I extends Iterable<MicroExit<any, any>>>(\n  exits: I\n): MicroExit<void, I extends Iterable<MicroExit<infer _A, infer _E>> ? _E : never> => {\n  for (const exit of exits) {\n    if (exit._tag === \"Failure\") {\n      return exit\n    }\n  }\n  return exitVoid\n}\n\n// ----------------------------------------------------------------------------\n// scheduler\n// ----------------------------------------------------------------------------\n\n/**\n * @since 3.5.9\n * @experimental\n * @category scheduler\n */\nexport interface MicroScheduler {\n  readonly scheduleTask: (task: () => void, priority: number) => void\n  readonly shouldYield: (fiber: MicroFiber<unknown, unknown>) => boolean\n  readonly flush: () => void\n}\n\nconst setImmediate = \"setImmediate\" in globalThis\n  ? globalThis.setImmediate\n  : (f: () => void) => setTimeout(f, 0)\n\n/**\n * @since 3.5.9\n * @experimental\n * @category scheduler\n */\nexport class MicroSchedulerDefault implements MicroScheduler {\n  private tasks: Array<() => void> = []\n  private running = false\n\n  /**\n   * @since 3.5.9\n   */\n  scheduleTask(task: () => void, _priority: number) {\n    this.tasks.push(task)\n    if (!this.running) {\n      this.running = true\n      setImmediate(this.afterScheduled)\n    }\n  }\n\n  /**\n   * @since 3.5.9\n   */\n  afterScheduled = () => {\n    this.running = false\n    this.runTasks()\n  }\n\n  /**\n   * @since 3.5.9\n   */\n  runTasks() {\n    const tasks = this.tasks\n    this.tasks = []\n    for (let i = 0, len = tasks.length; i < len; i++) {\n      tasks[i]()\n    }\n  }\n\n  /**\n   * @since 3.5.9\n   */\n  shouldYield(fiber: MicroFiber<unknown, unknown>) {\n    return fiber.currentOpCount >= fiber.getRef(MaxOpsBeforeYield)\n  }\n\n  /**\n   * @since 3.5.9\n   */\n  flush() {\n    while (this.tasks.length > 0) {\n      this.runTasks()\n    }\n  }\n}\n\n/**\n * Access the given `Context.Tag` from the environment.\n *\n * @since 3.4.0\n * @experimental\n * @category environment\n */\nexport const service: {\n  <I, S>(tag: Context.Reference<I, S>): Micro<S>\n  <I, S>(tag: Context.Tag<I, S>): Micro<S, never, I>\n} =\n  (<I, S>(tag: Context.Tag<I, S>): Micro<S, never, I> =>\n    withMicroFiber((fiber) => succeed(Context.unsafeGet(fiber.context, tag)))) as any\n\n/**\n * Access the given `Context.Tag` from the environment, without tracking the\n * dependency at the type level.\n *\n * It will return an `Option` of the service, depending on whether it is\n * available in the environment or not.\n *\n * @since 3.4.0\n * @experimental\n * @category environment\n */\nexport const serviceOption = <I, S>(\n  tag: Context.Tag<I, S>\n): Micro<Option.Option<S>> => withMicroFiber((fiber) => succeed(Context.getOption(fiber.context, tag)))\n\n/**\n * Update the Context with the given mapping function.\n *\n * @since 3.11.0\n * @experimental\n * @category environment\n */\nexport const updateContext: {\n  <R2, R>(\n    f: (context: Context.Context<R2>) => Context.Context<NoInfer<R>>\n  ): <A, E>(self: Micro<A, E, R>) => Micro<A, E, R2>\n  <A, E, R, R2>(self: Micro<A, E, R>, f: (context: Context.Context<R2>) => Context.Context<NoInfer<R>>): Micro<A, E, R2>\n} = dual(\n  2,\n  <A, E, R, R2>(\n    self: Micro<A, E, R>,\n    f: (context: Context.Context<R2>) => Context.Context<NoInfer<R>>\n  ): Micro<A, E, R2> =>\n    withMicroFiber<A, E, R2>((fiber) => {\n      const prev = fiber.context as Context.Context<R2>\n      fiber.context = f(prev)\n      return onExit(\n        self as any,\n        () => {\n          fiber.context = prev\n          return void_\n        }\n      )\n    })\n)\n\n/**\n * Update the service for the given `Context.Tag` in the environment.\n *\n * @since 3.11.0\n * @experimental\n * @category environment\n */\nexport const updateService: {\n  <I, A>(\n    tag: Context.Reference<I, A>,\n    f: (value: A) => A\n  ): <XA, E, R>(self: Micro<XA, E, R>) => Micro<XA, E, R>\n  <I, A>(\n    tag: Context.Tag<I, A>,\n    f: (value: A) => A\n  ): <XA, E, R>(self: Micro<XA, E, R>) => Micro<XA, E, R | I>\n  <XA, E, R, I, A>(\n    self: Micro<XA, E, R>,\n    tag: Context.Reference<I, A>,\n    f: (value: A) => A\n  ): Micro<XA, E, R>\n  <XA, E, R, I, A>(\n    self: Micro<XA, E, R>,\n    tag: Context.Tag<I, A>,\n    f: (value: A) => A\n  ): Micro<XA, E, R | I>\n} = dual(\n  3,\n  <XA, E, R, I, A>(\n    self: Micro<XA, E, R>,\n    tag: Context.Reference<I, A>,\n    f: (value: A) => A\n  ): Micro<XA, E, R> =>\n    withMicroFiber((fiber) => {\n      const prev = Context.unsafeGet(fiber.context, tag)\n      fiber.context = Context.add(fiber.context, tag, f(prev))\n      return onExit(\n        self,\n        () => {\n          fiber.context = Context.add(fiber.context, tag, prev)\n          return void_\n        }\n      )\n    })\n)\n\n/**\n * Access the current `Context` from the environment.\n *\n * @since 3.4.0\n * @experimental\n * @category environment\n */\nexport const context = <R>(): Micro<Context.Context<R>> => getContext as any\nconst getContext = withMicroFiber((fiber) => succeed(fiber.context))\n\n/**\n * Merge the given `Context` with the current context.\n *\n * @since 3.4.0\n * @experimental\n * @category environment\n */\nexport const provideContext: {\n  <XR>(\n    context: Context.Context<XR>\n  ): <A, E, R>(self: Micro<A, E, R>) => Micro<A, E, Exclude<R, XR>>\n  <A, E, R, XR>(\n    self: Micro<A, E, R>,\n    context: Context.Context<XR>\n  ): Micro<A, E, Exclude<R, XR>>\n} = dual(\n  2,\n  <A, E, R, XR>(\n    self: Micro<A, E, R>,\n    provided: Context.Context<XR>\n  ): Micro<A, E, Exclude<R, XR>> => updateContext(self, Context.merge(provided)) as any\n)\n\n/**\n * Add the provided service to the current context.\n *\n * @since 3.4.0\n * @experimental\n * @category environment\n */\nexport const provideService: {\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    service: S\n  ): <A, E, R>(self: Micro<A, E, R>) => Micro<A, E, Exclude<R, I>>\n  <A, E, R, I, S>(\n    self: Micro<A, E, R>,\n    tag: Context.Tag<I, S>,\n    service: S\n  ): Micro<A, E, Exclude<R, I>>\n} = dual(\n  3,\n  <A, E, R, I, S>(\n    self: Micro<A, E, R>,\n    tag: Context.Tag<I, S>,\n    service: S\n  ): Micro<A, E, Exclude<R, I>> => updateContext(self, Context.add(tag, service)) as any\n)\n\n/**\n * Create a service using the provided `Micro` effect, and add it to the\n * current context.\n *\n * @since 3.4.6\n * @experimental\n * @category environment\n */\nexport const provideServiceEffect: {\n  <I, S, E2, R2>(\n    tag: Context.Tag<I, S>,\n    acquire: Micro<S, E2, R2>\n  ): <A, E, R>(self: Micro<A, E, R>) => Micro<A, E | E2, Exclude<R, I> | R2>\n  <A, E, R, I, S, E2, R2>(\n    self: Micro<A, E, R>,\n    tag: Context.Tag<I, S>,\n    acquire: Micro<S, E2, R2>\n  ): Micro<A, E | E2, Exclude<R, I> | R2>\n} = dual(\n  3,\n  <A, E, R, I, S, E2, R2>(\n    self: Micro<A, E, R>,\n    tag: Context.Tag<I, S>,\n    acquire: Micro<S, E2, R2>\n  ): Micro<A, E | E2, Exclude<R, I> | R2> => flatMap(acquire, (service) => provideService(self, tag, service))\n)\n\n// ========================================================================\n// References\n// ========================================================================\n\n/**\n * @since 3.11.0\n * @experimental\n * @category references\n */\nexport class MaxOpsBeforeYield extends Context.Reference<MaxOpsBeforeYield>()<\n  \"effect/Micro/currentMaxOpsBeforeYield\",\n  number\n>(\n  \"effect/Micro/currentMaxOpsBeforeYield\",\n  { defaultValue: () => 2048 }\n) {}\n\n/**\n * @since 3.11.0\n * @experimental\n * @category environment refs\n */\nexport class CurrentConcurrency extends Context.Reference<CurrentConcurrency>()<\n  \"effect/Micro/currentConcurrency\",\n  \"unbounded\" | number\n>(\n  \"effect/Micro/currentConcurrency\",\n  { defaultValue: () => \"unbounded\" }\n) {}\n\n/**\n * @since 3.11.0\n * @experimental\n * @category environment refs\n */\nexport class CurrentScheduler extends Context.Reference<CurrentScheduler>()<\n  \"effect/Micro/currentScheduler\",\n  MicroScheduler\n>(\n  \"effect/Micro/currentScheduler\",\n  { defaultValue: () => new MicroSchedulerDefault() }\n) {}\n\n/**\n * If you have a `Micro` that uses `concurrency: \"inherit\"`, you can use this\n * api to control the concurrency of that `Micro` when it is run.\n *\n * @example\n * ```ts\n * import * as Micro from \"effect/Micro\"\n *\n * Micro.forEach([1, 2, 3], (n) => Micro.succeed(n), {\n *   concurrency: \"inherit\"\n * }).pipe(\n *   Micro.withConcurrency(2) // use a concurrency of 2\n * )\n * ```\n *\n * @since 3.4.0\n * @experimental\n * @category environment refs\n */\nexport const withConcurrency: {\n  (\n    concurrency: \"unbounded\" | number\n  ): <A, E, R>(self: Micro<A, E, R>) => Micro<A, E, R>\n  <A, E, R>(\n    self: Micro<A, E, R>,\n    concurrency: \"unbounded\" | number\n  ): Micro<A, E, R>\n} = dual(\n  2,\n  <A, E, R>(\n    self: Micro<A, E, R>,\n    concurrency: \"unbounded\" | number\n  ): Micro<A, E, R> => provideService(self, CurrentConcurrency, concurrency)\n)\n\n// ----------------------------------------------------------------------------\n// zipping\n// ----------------------------------------------------------------------------\n\n/**\n * Combine two `Micro` effects into a single effect that produces a tuple of\n * their results.\n *\n * @since 3.4.0\n * @experimental\n * @category zipping\n */\nexport const zip: {\n  <A2, E2, R2>(\n    that: Micro<A2, E2, R2>,\n    options?:\n      | { readonly concurrent?: boolean | undefined }\n      | undefined\n  ): <A, E, R>(self: Micro<A, E, R>) => Micro<[A, A2], E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Micro<A, E, R>,\n    that: Micro<A2, E2, R2>,\n    options?: { readonly concurrent?: boolean | undefined }\n  ): Micro<[A, A2], E | E2, R | R2>\n} = dual((args) => isMicro(args[1]), <A, E, R, A2, E2, R2>(\n  self: Micro<A, E, R>,\n  that: Micro<A2, E2, R2>,\n  options?: { readonly concurrent?: boolean | undefined }\n): Micro<[A, A2], E | E2, R | R2> => zipWith(self, that, (a, a2) => [a, a2], options))\n\n/**\n * The `Micro.zipWith` function combines two `Micro` effects and allows you to\n * apply a function to the results of the combined effects, transforming them\n * into a single value.\n *\n * @since 3.4.3\n * @experimental\n * @category zipping\n */\nexport const zipWith: {\n  <A2, E2, R2, A, B>(\n    that: Micro<A2, E2, R2>,\n    f: (a: A, b: A2) => B,\n    options?: { readonly concurrent?: boolean | undefined }\n  ): <E, R>(self: Micro<A, E, R>) => Micro<B, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2, B>(\n    self: Micro<A, E, R>,\n    that: Micro<A2, E2, R2>,\n    f: (a: A, b: A2) => B,\n    options?: { readonly concurrent?: boolean | undefined }\n  ): Micro<B, E2 | E, R2 | R>\n} = dual((args) => isMicro(args[1]), <A, E, R, A2, E2, R2, B>(\n  self: Micro<A, E, R>,\n  that: Micro<A2, E2, R2>,\n  f: (a: A, b: A2) => B,\n  options?: { readonly concurrent?: boolean | undefined }\n): Micro<B, E2 | E, R2 | R> =>\n  options?.concurrent\n    // Use `all` exclusively for concurrent cases, as it introduces additional overhead due to the management of concurrency\n    ? map(all([self, that], { concurrency: 2 }), ([a, a2]) => f(a, a2))\n    : flatMap(self, (a) => map(that, (a2) => f(a, a2))))\n\n// ----------------------------------------------------------------------------\n// filtering & conditionals\n// ----------------------------------------------------------------------------\n\n/**\n * Filter the specified effect with the provided function, failing with specified\n * `MicroCause` if the predicate fails.\n *\n * In addition to the filtering capabilities discussed earlier, you have the option to further\n * refine and narrow down the type of the success channel by providing a\n *\n * @since 3.4.0\n * @experimental\n * @category filtering & conditionals\n */\nexport const filterOrFailCause: {\n  <A, B extends A, E2>(\n    refinement: Refinement<A, B>,\n    orFailWith: (a: NoInfer<A>) => MicroCause<E2>\n  ): <E, R>(self: Micro<A, E, R>) => Micro<B, E2 | E, R>\n  <A, E2>(\n    predicate: Predicate<NoInfer<A>>,\n    orFailWith: (a: NoInfer<A>) => MicroCause<E2>\n  ): <E, R>(self: Micro<A, E, R>) => Micro<A, E2 | E, R>\n  <A, E, R, B extends A, E2>(\n    self: Micro<A, E, R>,\n    refinement: Refinement<A, B>,\n    orFailWith: (a: A) => MicroCause<E2>\n  ): Micro<B, E | E2, R>\n  <A, E, R, E2>(\n    self: Micro<A, E, R>,\n    predicate: Predicate<A>,\n    orFailWith: (a: A) => MicroCause<E2>\n  ): Micro<A, E | E2, R>\n} = dual((args) => isMicro(args[0]), <A, E, R, B extends A, E2>(\n  self: Micro<A, E, R>,\n  refinement: Refinement<A, B>,\n  orFailWith: (a: A) => MicroCause<E2>\n): Micro<B, E | E2, R> => flatMap(self, (a) => refinement(a) ? succeed(a) : failCause(orFailWith(a))))\n\n/**\n * Filter the specified effect with the provided function, failing with specified\n * error if the predicate fails.\n *\n * In addition to the filtering capabilities discussed earlier, you have the option to further\n * refine and narrow down the type of the success channel by providing a\n *\n * @since 3.4.0\n * @experimental\n * @category filtering & conditionals\n */\nexport const filterOrFail: {\n  <A, B extends A, E2>(\n    refinement: Refinement<A, B>,\n    orFailWith: (a: NoInfer<A>) => E2\n  ): <E, R>(self: Micro<A, E, R>) => Micro<B, E2 | E, R>\n  <A, E2>(\n    predicate: Predicate<NoInfer<A>>,\n    orFailWith: (a: NoInfer<A>) => E2\n  ): <E, R>(self: Micro<A, E, R>) => Micro<A, E2 | E, R>\n  <A, E, R, B extends A, E2>(\n    self: Micro<A, E, R>,\n    refinement: Refinement<A, B>,\n    orFailWith: (a: A) => E2\n  ): Micro<B, E | E2, R>\n  <A, E, R, E2>(self: Micro<A, E, R>, predicate: Predicate<A>, orFailWith: (a: A) => E2): Micro<A, E | E2, R>\n} = dual((args) => isMicro(args[0]), <A, E, R, B extends A, E2>(\n  self: Micro<A, E, R>,\n  refinement: Refinement<A, B>,\n  orFailWith: (a: A) => E2\n): Micro<B, E | E2, R> => flatMap(self, (a) => refinement(a) ? succeed(a) : fail(orFailWith(a))))\n\n/**\n * The moral equivalent of `if (p) exp`.\n *\n * @since 3.4.0\n * @experimental\n * @category filtering & conditionals\n */\nexport const when: {\n  <E2 = never, R2 = never>(\n    condition: LazyArg<boolean> | Micro<boolean, E2, R2>\n  ): <A, E, R>(self: Micro<A, E, R>) => Micro<Option.Option<A>, E | E2, R | R2>\n  <A, E, R, E2 = never, R2 = never>(\n    self: Micro<A, E, R>,\n    condition: LazyArg<boolean> | Micro<boolean, E2, R2>\n  ): Micro<Option.Option<A>, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, E2 = never, R2 = never>(\n    self: Micro<A, E, R>,\n    condition: LazyArg<boolean> | Micro<boolean, E2, R2>\n  ): Micro<Option.Option<A>, E | E2, R | R2> =>\n    flatMap(isMicro(condition) ? condition : sync(condition), (pass) => pass ? asSome(self) : succeedNone)\n)\n\n// ----------------------------------------------------------------------------\n// repetition\n// ----------------------------------------------------------------------------\n\n/**\n * Repeat the given `Micro` using the provided options.\n *\n * The `while` predicate will be checked after each iteration, and can use the\n * fall `MicroExit` of the effect to determine if the repetition should continue.\n *\n * @since 3.4.6\n * @experimental\n * @category repetition\n */\nexport const repeatExit: {\n  <A, E>(options: {\n    while: Predicate<MicroExit<A, E>>\n    times?: number | undefined\n    schedule?: MicroSchedule | undefined\n  }): <R>(self: Micro<A, E, R>) => Micro<A, E, R>\n  <A, E, R>(self: Micro<A, E, R>, options: {\n    while: Predicate<MicroExit<A, E>>\n    times?: number | undefined\n    schedule?: MicroSchedule | undefined\n  }): Micro<A, E, R>\n} = dual(2, <A, E, R>(self: Micro<A, E, R>, options: {\n  while: Predicate<MicroExit<A, E>>\n  times?: number | undefined\n  schedule?: MicroSchedule | undefined\n}): Micro<A, E, R> =>\n  suspend(() => {\n    const startedAt = options.schedule ? Date.now() : 0\n    let attempt = 0\n\n    const loop: Micro<A, E, R> = flatMap(exit(self), (exit) => {\n      if (options.while !== undefined && !options.while(exit)) {\n        return exit\n      } else if (options.times !== undefined && attempt >= options.times) {\n        return exit\n      }\n      attempt++\n      let delayEffect = yieldNow\n      if (options.schedule !== undefined) {\n        const elapsed = Date.now() - startedAt\n        const duration = options.schedule(attempt, elapsed)\n        if (Option.isNone(duration)) {\n          return exit\n        }\n        delayEffect = sleep(duration.value)\n      }\n      return flatMap(delayEffect, () => loop)\n    })\n\n    return loop\n  }))\n\n/**\n * Repeat the given `Micro` effect using the provided options. Only successful\n * results will be repeated.\n *\n * @since 3.4.0\n * @experimental\n * @category repetition\n */\nexport const repeat: {\n  <A, E>(\n    options?: {\n      while?: Predicate<A> | undefined\n      times?: number | undefined\n      schedule?: MicroSchedule | undefined\n    } | undefined\n  ): <R>(self: Micro<A, E, R>) => Micro<A, E, R>\n  <A, E, R>(\n    self: Micro<A, E, R>,\n    options?: {\n      while?: Predicate<A> | undefined\n      times?: number | undefined\n      schedule?: MicroSchedule | undefined\n    } | undefined\n  ): Micro<A, E, R>\n} = dual((args) => isMicro(args[0]), <A, E, R>(\n  self: Micro<A, E, R>,\n  options?: {\n    while?: Predicate<A> | undefined\n    times?: number | undefined\n    schedule?: MicroSchedule | undefined\n  } | undefined\n): Micro<A, E, R> =>\n  repeatExit(self, {\n    ...options,\n    while: (exit) => exit._tag === \"Success\" && (options?.while === undefined || options.while(exit.value))\n  }))\n\n/**\n * Replicates the given effect `n` times.\n *\n * @since 3.11.0\n * @experimental\n * @category repetition\n */\nexport const replicate: {\n  (n: number): <A, E, R>(self: Micro<A, E, R>) => Array<Micro<A, E, R>>\n  <A, E, R>(self: Micro<A, E, R>, n: number): Array<Micro<A, E, R>>\n} = dual(\n  2,\n  <A, E, R>(self: Micro<A, E, R>, n: number): Array<Micro<A, E, R>> => Array.from({ length: n }, () => self)\n)\n\n/**\n * Performs this effect the specified number of times and collects the\n * results.\n *\n * @since 3.11.0\n * @category repetition\n */\nexport const replicateEffect: {\n  (\n    n: number,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly discard?: false | undefined\n    }\n  ): <A, E, R>(self: Micro<A, E, R>) => Micro<Array<A>, E, R>\n  (\n    n: number,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly discard: true\n    }\n  ): <A, E, R>(self: Micro<A, E, R>) => Micro<void, E, R>\n  <A, E, R>(\n    self: Micro<A, E, R>,\n    n: number,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly discard?: false | undefined\n    }\n  ): Micro<Array<A>, E, R>\n  <A, E, R>(\n    self: Micro<A, E, R>,\n    n: number,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly discard: true\n    }\n  ): Micro<void, E, R>\n} = dual(\n  (args) => isMicro(args[0]),\n  <A, E, R>(\n    self: Micro<A, E, R>,\n    n: number,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly discard: true\n    }\n  ): Micro<void, E, R> => all(replicate(self, n), options)\n)\n\n/**\n * Repeat the given `Micro` effect forever, only stopping if the effect fails.\n *\n * @since 3.4.0\n * @experimental\n * @category repetition\n */\nexport const forever = <A, E, R>(self: Micro<A, E, R>): Micro<never, E, R> => repeat(self) as any\n\n// ----------------------------------------------------------------------------\n// scheduling\n// ----------------------------------------------------------------------------\n\n/**\n * The `MicroSchedule` type represents a function that can be used to calculate\n * the delay between repeats.\n *\n * The function takes the current attempt number and the elapsed time since the\n * first attempt, and returns the delay for the next attempt. If the function\n * returns `None`, the repetition will stop.\n *\n * @since 3.4.6\n * @experimental\n * @category scheduling\n */\nexport type MicroSchedule = (attempt: number, elapsed: number) => Option.Option<number>\n\n/**\n * Create a `MicroSchedule` that will stop repeating after the specified number\n * of attempts.\n *\n * @since 3.4.6\n * @experimental\n * @category scheduling\n */\nexport const scheduleRecurs = (n: number): MicroSchedule => (attempt) => attempt <= n ? Option.some(0) : Option.none()\n\n/**\n * Create a `MicroSchedule` that will generate a constant delay.\n *\n * @since 3.4.6\n * @experimental\n * @category scheduling\n */\nexport const scheduleSpaced = (millis: number): MicroSchedule => () => Option.some(millis)\n\n/**\n * Create a `MicroSchedule` that will generate a delay with an exponential backoff.\n *\n * @since 3.4.6\n * @experimental\n * @category scheduling\n */\nexport const scheduleExponential = (baseMillis: number, factor = 2): MicroSchedule => (attempt) =>\n  Option.some(Math.pow(factor, attempt) * baseMillis)\n\n/**\n * Returns a new `MicroSchedule` with an added calculated delay to each delay\n * returned by this schedule.\n *\n * @since 3.4.6\n * @experimental\n * @category scheduling\n */\nexport const scheduleAddDelay: {\n  (f: () => number): (self: MicroSchedule) => MicroSchedule\n  (self: MicroSchedule, f: () => number): MicroSchedule\n} = dual(\n  2,\n  (self: MicroSchedule, f: () => number): MicroSchedule => (attempt, elapsed) =>\n    Option.map(self(attempt, elapsed), (duration) => duration + f())\n)\n\n/**\n * Transform a `MicroSchedule` to one that will have a delay that will never exceed\n * the specified maximum.\n *\n * @since 3.4.6\n * @experimental\n * @category scheduling\n */\nexport const scheduleWithMaxDelay: {\n  (max: number): (self: MicroSchedule) => MicroSchedule\n  (self: MicroSchedule, max: number): MicroSchedule\n} = dual(\n  2,\n  (self: MicroSchedule, max: number): MicroSchedule => (attempt, elapsed) =>\n    Option.map(self(attempt, elapsed), (duration) => Math.min(duration, max))\n)\n\n/**\n * Transform a `MicroSchedule` to one that will stop repeating after the specified\n * amount of time.\n *\n * @since 3.4.6\n * @experimental\n * @category scheduling\n */\nexport const scheduleWithMaxElapsed: {\n  (max: number): (self: MicroSchedule) => MicroSchedule\n  (self: MicroSchedule, max: number): MicroSchedule\n} = dual(\n  2,\n  (self: MicroSchedule, max: number): MicroSchedule => (attempt, elapsed) =>\n    elapsed < max ? self(attempt, elapsed) : Option.none()\n)\n\n/**\n * Combines two `MicroSchedule`s, by recurring if either schedule wants to\n * recur, using the minimum of the two durations between recurrences.\n *\n * @since 3.4.6\n * @experimental\n * @category scheduling\n */\nexport const scheduleUnion: {\n  (that: MicroSchedule): (self: MicroSchedule) => MicroSchedule\n  (self: MicroSchedule, that: MicroSchedule): MicroSchedule\n} = dual(\n  2,\n  (self: MicroSchedule, that: MicroSchedule): MicroSchedule => (attempt, elapsed) =>\n    Option.zipWith(self(attempt, elapsed), that(attempt, elapsed), (d1, d2) => Math.min(d1, d2))\n)\n\n/**\n * Combines two `MicroSchedule`s, by recurring only if both schedules want to\n * recur, using the maximum of the two durations between recurrences.\n *\n * @since 3.4.6\n * @experimental\n * @category scheduling\n */\nexport const scheduleIntersect: {\n  (that: MicroSchedule): (self: MicroSchedule) => MicroSchedule\n  (self: MicroSchedule, that: MicroSchedule): MicroSchedule\n} = dual(\n  2,\n  (self: MicroSchedule, that: MicroSchedule): MicroSchedule => (attempt, elapsed) =>\n    Option.zipWith(self(attempt, elapsed), that(attempt, elapsed), (d1, d2) => Math.max(d1, d2))\n)\n\n// ----------------------------------------------------------------------------\n// error handling\n// ----------------------------------------------------------------------------\n\n/**\n * Catch the full `MicroCause` object of the given `Micro` effect, allowing you to\n * recover from any kind of cause.\n *\n * @since 3.4.6\n * @experimental\n * @category error handling\n */\nexport const catchAllCause: {\n  <E, B, E2, R2>(\n    f: (cause: NoInfer<MicroCause<E>>) => Micro<B, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A | B, E2, R | R2>\n  <A, E, R, B, E2, R2>(\n    self: Micro<A, E, R>,\n    f: (cause: NoInfer<MicroCause<E>>) => Micro<B, E2, R2>\n  ): Micro<A | B, E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, B, E2, R2>(\n    self: Micro<A, E, R>,\n    f: (cause: NoInfer<MicroCause<E>>) => Micro<B, E2, R2>\n  ): Micro<A | B, E2, R | R2> => {\n    const onFailure = Object.create(OnFailureProto)\n    onFailure[args] = self\n    onFailure[failureCont] = f\n    return onFailure\n  }\n)\nconst OnFailureProto = makePrimitiveProto({\n  op: \"OnFailure\",\n  eval(this: any, fiber: MicroFiberImpl): Primitive {\n    fiber._stack.push(this as any)\n    return this[args]\n  }\n})\n\n/**\n * Selectively catch a `MicroCause` object of the given `Micro` effect,\n * using the provided predicate to determine if the failure should be caught.\n *\n * @since 3.4.6\n * @experimental\n * @category error handling\n */\nexport const catchCauseIf: {\n  <E, B, E2, R2, EB extends MicroCause<E>>(\n    refinement: Refinement<MicroCause<E>, EB>,\n    f: (cause: EB) => Micro<B, E2, R2>\n  ): <A, R>(\n    self: Micro<A, E, R>\n  ) => Micro<A | B, Exclude<E, MicroCause.Error<EB>> | E2, R | R2>\n  <E, B, E2, R2>(\n    predicate: Predicate<MicroCause<NoInfer<E>>>,\n    f: (cause: NoInfer<MicroCause<E>>) => Micro<B, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A | B, E | E2, R | R2>\n  <A, E, R, B, E2, R2, EB extends MicroCause<E>>(\n    self: Micro<A, E, R>,\n    refinement: Refinement<MicroCause<E>, EB>,\n    f: (cause: EB) => Micro<B, E2, R2>\n  ): Micro<A | B, Exclude<E, MicroCause.Error<EB>> | E2, R | R2>\n  <A, E, R, B, E2, R2>(\n    self: Micro<A, E, R>,\n    predicate: Predicate<MicroCause<NoInfer<E>>>,\n    f: (cause: NoInfer<MicroCause<E>>) => Micro<B, E2, R2>\n  ): Micro<A | B, E | E2, R | R2>\n} = dual(\n  3,\n  <A, E, R, B, E2, R2>(\n    self: Micro<A, E, R>,\n    predicate: Predicate<MicroCause<E>>,\n    f: (cause: MicroCause<E>) => Micro<B, E2, R2>\n  ): Micro<A | B, E | E2, R | R2> =>\n    catchAllCause(self, (cause) => predicate(cause) ? f(cause) : failCause(cause) as any)\n)\n\n/**\n * Catch the error of the given `Micro` effect, allowing you to recover from it.\n *\n * It only catches expected errors.\n *\n * @since 3.4.6\n * @experimental\n * @category error handling\n */\nexport const catchAll: {\n  <E, B, E2, R2>(\n    f: (e: NoInfer<E>) => Micro<B, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A | B, E2, R | R2>\n  <A, E, R, B, E2, R2>(self: Micro<A, E, R>, f: (e: NoInfer<E>) => Micro<B, E2, R2>): Micro<A | B, E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, B, E2, R2>(\n    self: Micro<A, E, R>,\n    f: (a: NoInfer<E>) => Micro<B, E2, R2>\n  ): Micro<A | B, E2, R | R2> => catchCauseIf(self, causeIsFail, (cause) => f(cause.error))\n)\n\n/**\n * Catch any unexpected errors of the given `Micro` effect, allowing you to recover from them.\n *\n * @since 3.4.6\n * @experimental\n * @category error handling\n */\nexport const catchAllDefect: {\n  <E, B, E2, R2>(\n    f: (defect: unknown) => Micro<B, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A | B, E | E2, R | R2>\n  <A, E, R, B, E2, R2>(self: Micro<A, E, R>, f: (defect: unknown) => Micro<B, E2, R2>): Micro<A | B, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, B, E2, R2>(self: Micro<A, E, R>, f: (defect: unknown) => Micro<B, E2, R2>): Micro<A | B, E | E2, R | R2> =>\n    catchCauseIf(self, causeIsDie, (die) => f(die.defect))\n)\n\n/**\n * Perform a side effect using the full `MicroCause` object of the given `Micro`.\n *\n * @since 3.4.6\n * @experimental\n * @category error handling\n */\nexport const tapErrorCause: {\n  <E, B, E2, R2>(\n    f: (cause: NoInfer<MicroCause<E>>) => Micro<B, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A, E | E2, R | R2>\n  <A, E, R, B, E2, R2>(\n    self: Micro<A, E, R>,\n    f: (cause: NoInfer<MicroCause<E>>) => Micro<B, E2, R2>\n  ): Micro<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, B, E2, R2>(\n    self: Micro<A, E, R>,\n    f: (cause: NoInfer<MicroCause<E>>) => Micro<B, E2, R2>\n  ): Micro<A, E | E2, R | R2> => tapErrorCauseIf(self, constTrue, f)\n)\n\n/**\n * Perform a side effect using if a `MicroCause` object matches the specified\n * predicate.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const tapErrorCauseIf: {\n  <E, B, E2, R2, EB extends MicroCause<E>>(\n    refinement: Refinement<MicroCause<E>, EB>,\n    f: (a: EB) => Micro<B, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A, E | E2, R | R2>\n  <E, B, E2, R2>(\n    predicate: (cause: NoInfer<MicroCause<E>>) => boolean,\n    f: (a: NoInfer<MicroCause<E>>) => Micro<B, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A, E | E2, R | R2>\n  <A, E, R, B, E2, R2, EB extends MicroCause<E>>(\n    self: Micro<A, E, R>,\n    refinement: Refinement<MicroCause<E>, EB>,\n    f: (a: EB) => Micro<B, E2, R2>\n  ): Micro<A, E | E2, R | R2>\n  <A, E, R, B, E2, R2>(\n    self: Micro<A, E, R>,\n    predicate: (cause: NoInfer<MicroCause<E>>) => boolean,\n    f: (a: NoInfer<MicroCause<E>>) => Micro<B, E2, R2>\n  ): Micro<A, E | E2, R | R2>\n} = dual(\n  3,\n  <A, E, R, B, E2, R2, EB extends MicroCause<E>>(\n    self: Micro<A, E, R>,\n    refinement: Refinement<MicroCause<E>, EB>,\n    f: (a: EB) => Micro<B, E2, R2>\n  ): Micro<A, E | E2, R | R2> => catchCauseIf(self, refinement, (cause) => andThen(f(cause), failCause(cause)))\n)\n\n/**\n * Perform a side effect from expected errors of the given `Micro`.\n *\n * @since 3.4.6\n * @experimental\n * @category error handling\n */\nexport const tapError: {\n  <E, B, E2, R2>(\n    f: (e: NoInfer<E>) => Micro<B, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A, E | E2, R | R2>\n  <A, E, R, B, E2, R2>(self: Micro<A, E, R>, f: (e: NoInfer<E>) => Micro<B, E2, R2>): Micro<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, B, E2, R2>(self: Micro<A, E, R>, f: (e: NoInfer<E>) => Micro<B, E2, R2>): Micro<A, E | E2, R | R2> =>\n    tapErrorCauseIf(self, causeIsFail, (fail) => f(fail.error))\n)\n\n/**\n * Perform a side effect from unexpected errors of the given `Micro`.\n *\n * @since 3.4.6\n * @experimental\n * @category error handling\n */\nexport const tapDefect: {\n  <E, B, E2, R2>(\n    f: (defect: unknown) => Micro<B, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A, E | E2, R | R2>\n  <A, E, R, B, E2, R2>(self: Micro<A, E, R>, f: (defect: unknown) => Micro<B, E2, R2>): Micro<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, B, E2, R2>(self: Micro<A, E, R>, f: (defect: unknown) => Micro<B, E2, R2>): Micro<A, E | E2, R | R2> =>\n    tapErrorCauseIf(self, causeIsDie, (die) => f(die.defect))\n)\n\n/**\n * Catch any expected errors that match the specified predicate.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const catchIf: {\n  <E, EB extends E, A2, E2, R2>(\n    refinement: Refinement<NoInfer<E>, EB>,\n    f: (e: EB) => Micro<A2, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A2 | A, E2 | Exclude<E, EB>, R2 | R>\n  <E, A2, E2, R2>(\n    predicate: Predicate<NoInfer<E>>,\n    f: (e: NoInfer<E>) => Micro<A2, E2, R2>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A2 | A, E | E2, R2 | R>\n  <A, E, R, EB extends E, A2, E2, R2>(\n    self: Micro<A, E, R>,\n    refinement: Refinement<E, EB>,\n    f: (e: EB) => Micro<A2, E2, R2>\n  ): Micro<A | A2, E2 | Exclude<E, EB>, R | R2>\n  <A, E, R, A2, E2, R2>(\n    self: Micro<A, E, R>,\n    predicate: Predicate<E>,\n    f: (e: E) => Micro<A2, E2, R2>\n  ): Micro<A | A2, E | E2, R | R2>\n} = dual(\n  3,\n  <A, E, R, A2, E2, R2>(\n    self: Micro<A, E, R>,\n    predicate: Predicate<E>,\n    f: (e: E) => Micro<A2, E2, R2>\n  ): Micro<A | A2, E | E2, R | R2> =>\n    catchCauseIf(\n      self,\n      (f): f is MicroCause.Fail<E> => causeIsFail(f) && predicate(f.error),\n      (fail) => f(fail.error)\n    )\n)\n\n/**\n * Recovers from the specified tagged error.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const catchTag: {\n  <K extends E extends { _tag: string } ? E[\"_tag\"] : never, E, A1, E1, R1>(\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Micro<A1, E1, R1>\n  ): <A, R>(self: Micro<A, E, R>) => Micro<A1 | A, E1 | Exclude<E, { _tag: K }>, R1 | R>\n  <A, E, R, K extends E extends { _tag: string } ? E[\"_tag\"] : never, R1, E1, A1>(\n    self: Micro<A, E, R>,\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Micro<A1, E1, R1>\n  ): Micro<A | A1, E1 | Exclude<E, { _tag: K }>, R | R1>\n} = dual(3, <A, E, R, K extends E extends { _tag: string } ? E[\"_tag\"] : never, R1, E1, A1>(\n  self: Micro<A, E, R>,\n  k: K,\n  f: (e: Extract<E, { _tag: K }>) => Micro<A1, E1, R1>\n): Micro<A | A1, E1 | Exclude<E, { _tag: K }>, R | R1> =>\n  catchIf(self, isTagged(k) as Refinement<E, Extract<E, { _tag: K }>>, f) as any)\n\n/**\n * Transform the full `MicroCause` object of the given `Micro` effect.\n *\n * @since 3.4.6\n * @experimental\n * @category error handling\n */\nexport const mapErrorCause: {\n  <E, E2>(f: (e: MicroCause<E>) => MicroCause<E2>): <A, R>(self: Micro<A, E, R>) => Micro<A, E2, R>\n  <A, E, R, E2>(self: Micro<A, E, R>, f: (e: MicroCause<E>) => MicroCause<E2>): Micro<A, E2, R>\n} = dual(\n  2,\n  <A, E, R, E2>(self: Micro<A, E, R>, f: (e: MicroCause<E>) => MicroCause<E2>): Micro<A, E2, R> =>\n    catchAllCause(self, (cause) => failCause(f(cause)))\n)\n\n/**\n * Transform any expected errors of the given `Micro` effect.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const mapError: {\n  <E, E2>(f: (e: E) => E2): <A, R>(self: Micro<A, E, R>) => Micro<A, E2, R>\n  <A, E, R, E2>(self: Micro<A, E, R>, f: (e: E) => E2): Micro<A, E2, R>\n} = dual(\n  2,\n  <A, E, R, E2>(self: Micro<A, E, R>, f: (e: E) => E2): Micro<A, E2, R> => catchAll(self, (error) => fail(f(error)))\n)\n\n/**\n * Elevate any expected errors of the given `Micro` effect to unexpected errors,\n * resulting in an error type of `never`.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const orDie = <A, E, R>(self: Micro<A, E, R>): Micro<A, never, R> => catchAll(self, die)\n\n/**\n * Recover from all errors by succeeding with the given value.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const orElseSucceed: {\n  <B>(f: LazyArg<B>): <A, E, R>(self: Micro<A, E, R>) => Micro<A | B, never, R>\n  <A, E, R, B>(self: Micro<A, E, R>, f: LazyArg<B>): Micro<A | B, never, R>\n} = dual(\n  2,\n  <A, E, R, B>(self: Micro<A, E, R>, f: LazyArg<B>): Micro<A | B, never, R> => catchAll(self, (_) => sync(f))\n)\n\n/**\n * Ignore any expected errors of the given `Micro` effect, returning `void`.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const ignore = <A, E, R>(self: Micro<A, E, R>): Micro<void, never, R> =>\n  matchEffect(self, { onFailure: (_) => void_, onSuccess: (_) => void_ })\n\n/**\n * Ignore any expected errors of the given `Micro` effect, returning `void`.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const ignoreLogged = <A, E, R>(self: Micro<A, E, R>): Micro<void, never, R> =>\n  matchEffect(self, {\n    // eslint-disable-next-line no-console\n    onFailure: (error) => sync(() => console.error(error)),\n    onSuccess: (_) => void_\n  })\n\n/**\n * Replace the success value of the given `Micro` effect with an `Option`,\n * wrapping the success value in `Some` and returning `None` if the effect fails\n * with an expected error.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const option = <A, E, R>(self: Micro<A, E, R>): Micro<Option.Option<A>, never, R> =>\n  match(self, { onFailure: Option.none, onSuccess: Option.some })\n\n/**\n * Replace the success value of the given `Micro` effect with an `Either`,\n * wrapping the success value in `Right` and wrapping any expected errors with\n * a `Left`.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const either = <A, E, R>(self: Micro<A, E, R>): Micro<Either.Either<A, E>, never, R> =>\n  match(self, { onFailure: Either.left, onSuccess: Either.right })\n\n/**\n * Retry the given `Micro` effect using the provided options.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const retry: {\n  <A, E>(\n    options?: {\n      while?: Predicate<E> | undefined\n      times?: number | undefined\n      schedule?: MicroSchedule | undefined\n    } | undefined\n  ): <R>(self: Micro<A, E, R>) => Micro<A, E, R>\n  <A, E, R>(\n    self: Micro<A, E, R>,\n    options?: {\n      while?: Predicate<E> | undefined\n      times?: number | undefined\n      schedule?: MicroSchedule | undefined\n    } | undefined\n  ): Micro<A, E, R>\n} = dual((args) => isMicro(args[0]), <A, E, R>(\n  self: Micro<A, E, R>,\n  options?: {\n    while?: Predicate<E> | undefined\n    times?: number | undefined\n    schedule?: MicroSchedule | undefined\n  } | undefined\n): Micro<A, E, R> =>\n  repeatExit(self, {\n    ...options,\n    while: (exit) =>\n      exit._tag === \"Failure\" && exit.cause._tag === \"Fail\" &&\n      (options?.while === undefined || options.while(exit.cause.error))\n  }))\n\n/**\n * Add a stack trace to any failures that occur in the effect. The trace will be\n * added to the `traces` field of the `MicroCause` object.\n *\n * @since 3.4.0\n * @experimental\n * @category error handling\n */\nexport const withTrace: {\n  (name: string): <A, E, R>(self: Micro<A, E, R>) => Micro<A, E, R>\n  <A, E, R>(self: Micro<A, E, R>, name: string): Micro<A, E, R>\n} = function() {\n  const prevLimit = globalThis.Error.stackTraceLimit\n  globalThis.Error.stackTraceLimit = 2\n  const error = new globalThis.Error()\n  globalThis.Error.stackTraceLimit = prevLimit\n  function generate(name: string, cause: MicroCause<any>) {\n    const stack = error.stack\n    if (!stack) {\n      return cause\n    }\n    const line = stack.split(\"\\n\")[2]?.trim().replace(/^at /, \"\")\n    if (!line) {\n      return cause\n    }\n    const lineMatch = line.match(/\\((.*)\\)$/)\n    return causeWithTrace(cause, `at ${name} (${lineMatch ? lineMatch[1] : line})`)\n  }\n  const f = (name: string) => (self: Micro<any, any, any>) => onError(self, (cause) => failCause(generate(name, cause)))\n  if (arguments.length === 2) {\n    return f(arguments[1])(arguments[0])\n  }\n  return f(arguments[0])\n} as any\n\n// ----------------------------------------------------------------------------\n// pattern matching\n// ----------------------------------------------------------------------------\n\n/**\n * @since 3.4.6\n * @experimental\n * @category pattern matching\n */\nexport const matchCauseEffect: {\n  <E, A2, E2, R2, A, A3, E3, R3>(options: {\n    readonly onFailure: (cause: MicroCause<E>) => Micro<A2, E2, R2>\n    readonly onSuccess: (a: A) => Micro<A3, E3, R3>\n  }): <R>(self: Micro<A, E, R>) => Micro<A2 | A3, E2 | E3, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Micro<A, E, R>,\n    options: {\n      readonly onFailure: (cause: MicroCause<E>) => Micro<A2, E2, R2>\n      readonly onSuccess: (a: A) => Micro<A3, E3, R3>\n    }\n  ): Micro<A2 | A3, E2 | E3, R2 | R3 | R>\n} = dual(\n  2,\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Micro<A, E, R>,\n    options: {\n      readonly onFailure: (cause: MicroCause<E>) => Micro<A2, E2, R2>\n      readonly onSuccess: (a: A) => Micro<A3, E3, R3>\n    }\n  ): Micro<A2 | A3, E2 | E3, R2 | R3 | R> => {\n    const primitive = Object.create(OnSuccessAndFailureProto)\n    primitive[args] = self\n    primitive[successCont] = options.onSuccess\n    primitive[failureCont] = options.onFailure\n    return primitive\n  }\n)\nconst OnSuccessAndFailureProto = makePrimitiveProto({\n  op: \"OnSuccessAndFailure\",\n  eval(this: any, fiber: MicroFiberImpl): Primitive {\n    fiber._stack.push(this)\n    return this[args]\n  }\n})\n\n/**\n * @since 3.4.6\n * @experimental\n * @category pattern matching\n */\nexport const matchCause: {\n  <E, A2, A, A3>(\n    options: {\n      readonly onFailure: (cause: MicroCause<E>) => A2\n      readonly onSuccess: (a: A) => A3\n    }\n  ): <R>(self: Micro<A, E, R>) => Micro<A2 | A3, never, R>\n  <A, E, R, A2, A3>(\n    self: Micro<A, E, R>,\n    options: {\n      readonly onFailure: (cause: MicroCause<E>) => A2\n      readonly onSuccess: (a: A) => A3\n    }\n  ): Micro<A2 | A3, never, R>\n} = dual(\n  2,\n  <A, E, R, A2, A3>(\n    self: Micro<A, E, R>,\n    options: {\n      readonly onFailure: (cause: MicroCause<E>) => A2\n      readonly onSuccess: (a: A) => A3\n    }\n  ): Micro<A2 | A3, never, R> =>\n    matchCauseEffect(self, {\n      onFailure: (cause) => sync(() => options.onFailure(cause)),\n      onSuccess: (value) => sync(() => options.onSuccess(value))\n    })\n)\n\n/**\n * @since 3.4.6\n * @experimental\n * @category pattern matching\n */\nexport const matchEffect: {\n  <E, A2, E2, R2, A, A3, E3, R3>(\n    options: {\n      readonly onFailure: (e: E) => Micro<A2, E2, R2>\n      readonly onSuccess: (a: A) => Micro<A3, E3, R3>\n    }\n  ): <R>(self: Micro<A, E, R>) => Micro<A2 | A3, E2 | E3, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Micro<A, E, R>,\n    options: {\n      readonly onFailure: (e: E) => Micro<A2, E2, R2>\n      readonly onSuccess: (a: A) => Micro<A3, E3, R3>\n    }\n  ): Micro<A2 | A3, E2 | E3, R2 | R3 | R>\n} = dual(\n  2,\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Micro<A, E, R>,\n    options: {\n      readonly onFailure: (e: E) => Micro<A2, E2, R2>\n      readonly onSuccess: (a: A) => Micro<A3, E3, R3>\n    }\n  ): Micro<A2 | A3, E2 | E3, R2 | R3 | R> =>\n    matchCauseEffect(self, {\n      onFailure: (cause) => cause._tag === \"Fail\" ? options.onFailure(cause.error) : failCause(cause),\n      onSuccess: options.onSuccess\n    })\n)\n\n/**\n * @since 3.4.0\n * @experimental\n * @category pattern matching\n */\nexport const match: {\n  <E, A2, A, A3>(\n    options: {\n      readonly onFailure: (error: E) => A2\n      readonly onSuccess: (value: A) => A3\n    }\n  ): <R>(self: Micro<A, E, R>) => Micro<A2 | A3, never, R>\n  <A, E, R, A2, A3>(\n    self: Micro<A, E, R>,\n    options: {\n      readonly onFailure: (error: E) => A2\n      readonly onSuccess: (value: A) => A3\n    }\n  ): Micro<A2 | A3, never, R>\n} = dual(\n  2,\n  <A, E, R, A2, A3>(\n    self: Micro<A, E, R>,\n    options: {\n      readonly onFailure: (error: E) => A2\n      readonly onSuccess: (value: A) => A3\n    }\n  ): Micro<A2 | A3, never, R> =>\n    matchEffect(self, {\n      onFailure: (error) => sync(() => options.onFailure(error)),\n      onSuccess: (value) => sync(() => options.onSuccess(value))\n    })\n)\n\n// ----------------------------------------------------------------------------\n// delays & timeouts\n// ----------------------------------------------------------------------------\n\n/**\n * Create a `Micro` effect that will sleep for the specified duration.\n *\n * @since 3.4.0\n * @experimental\n * @category delays & timeouts\n */\nexport const sleep = (millis: number): Micro<void> =>\n  async((resume) => {\n    const timeout = setTimeout(() => {\n      resume(void_)\n    }, millis)\n    return sync(() => {\n      clearTimeout(timeout)\n    })\n  })\n\n/**\n * Returns an effect that will delay the execution of this effect by the\n * specified duration.\n *\n * @since 3.4.0\n * @experimental\n * @category delays & timeouts\n */\nexport const delay: {\n  (millis: number): <A, E, R>(self: Micro<A, E, R>) => Micro<A, E, R>\n  <A, E, R>(self: Micro<A, E, R>, millis: number): Micro<A, E, R>\n} = dual(\n  2,\n  <A, E, R>(self: Micro<A, E, R>, millis: number): Micro<A, E, R> => andThen(sleep(millis), self)\n)\n\n/**\n * Returns an effect that will timeout this effect, that will execute the\n * fallback effect if the timeout elapses before the effect has produced a value.\n *\n * If the timeout elapses, the running effect will be safely interrupted.\n *\n * @since 3.4.0\n * @experimental\n * @category delays & timeouts\n */\nexport const timeoutOrElse: {\n  <A2, E2, R2>(options: {\n    readonly duration: number\n    readonly onTimeout: LazyArg<Micro<A2, E2, R2>>\n  }): <A, E, R>(self: Micro<A, E, R>) => Micro<A | A2, E | E2, R | R2>\n  <A, E, R, A2, E2, R2>(self: Micro<A, E, R>, options: {\n    readonly duration: number\n    readonly onTimeout: LazyArg<Micro<A2, E2, R2>>\n  }): Micro<A | A2, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, A2, E2, R2>(self: Micro<A, E, R>, options: {\n    readonly duration: number\n    readonly onTimeout: LazyArg<Micro<A2, E2, R2>>\n  }): Micro<A | A2, E | E2, R | R2> =>\n    raceFirst(self, andThen(interruptible(sleep(options.duration)), options.onTimeout))\n)\n\n/**\n * Returns an effect that will timeout this effect, that will fail with a\n * `TimeoutException` if the timeout elapses before the effect has produced a\n * value.\n *\n * If the timeout elapses, the running effect will be safely interrupted.\n *\n * @since 3.4.0\n * @experimental\n * @category delays & timeouts\n */\nexport const timeout: {\n  (millis: number): <A, E, R>(self: Micro<A, E, R>) => Micro<A, E | TimeoutException, R>\n  <A, E, R>(self: Micro<A, E, R>, millis: number): Micro<A, E | TimeoutException, R>\n} = dual(\n  2,\n  <A, E, R>(self: Micro<A, E, R>, millis: number): Micro<A, E | TimeoutException, R> =>\n    timeoutOrElse(self, { duration: millis, onTimeout: () => fail(new TimeoutException()) })\n)\n\n/**\n * Returns an effect that will timeout this effect, succeeding with a `None`\n * if the timeout elapses before the effect has produced a value; and `Some` of\n * the produced value otherwise.\n *\n * If the timeout elapses, the running effect will be safely interrupted.\n *\n * @since 3.4.0\n * @experimental\n * @category delays & timeouts\n */\nexport const timeoutOption: {\n  (millis: number): <A, E, R>(self: Micro<A, E, R>) => Micro<Option.Option<A>, E, R>\n  <A, E, R>(self: Micro<A, E, R>, millis: number): Micro<Option.Option<A>, E, R>\n} = dual(\n  2,\n  <A, E, R>(self: Micro<A, E, R>, millis: number): Micro<Option.Option<A>, E, R> =>\n    raceFirst(\n      asSome(self),\n      as(interruptible(sleep(millis)), Option.none())\n    )\n)\n\n// ----------------------------------------------------------------------------\n// resources & finalization\n// ----------------------------------------------------------------------------\n\n/**\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const MicroScopeTypeId: unique symbol = Symbol.for(\"effect/Micro/MicroScope\")\n\n/**\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport type MicroScopeTypeId = typeof MicroScopeTypeId\n\n/**\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport interface MicroScope {\n  readonly [MicroScopeTypeId]: MicroScopeTypeId\n  readonly addFinalizer: (finalizer: (exit: MicroExit<unknown, unknown>) => Micro<void>) => Micro<void>\n  readonly fork: Micro<MicroScope.Closeable>\n}\n\n/**\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport declare namespace MicroScope {\n  /**\n   * @since 3.4.0\n   * @experimental\n   * @category resources & finalization\n   */\n  export interface Closeable extends MicroScope {\n    readonly close: (exit: MicroExit<any, any>) => Micro<void>\n  }\n}\n\n/**\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const MicroScope: Context.Tag<MicroScope, MicroScope> = Context.GenericTag<MicroScope>(\"effect/Micro/MicroScope\")\n\nclass MicroScopeImpl implements MicroScope.Closeable {\n  readonly [MicroScopeTypeId]: MicroScopeTypeId\n  state: {\n    readonly _tag: \"Open\"\n    readonly finalizers: Set<(exit: MicroExit<any, any>) => Micro<void>>\n  } | {\n    readonly _tag: \"Closed\"\n    readonly exit: MicroExit<any, any>\n  } = { _tag: \"Open\", finalizers: new Set() }\n\n  constructor() {\n    this[MicroScopeTypeId] = MicroScopeTypeId\n  }\n\n  unsafeAddFinalizer(finalizer: (exit: MicroExit<any, any>) => Micro<void>): void {\n    if (this.state._tag === \"Open\") {\n      this.state.finalizers.add(finalizer)\n    }\n  }\n  addFinalizer(finalizer: (exit: MicroExit<any, any>) => Micro<void>): Micro<void> {\n    return suspend(() => {\n      if (this.state._tag === \"Open\") {\n        this.state.finalizers.add(finalizer)\n        return void_\n      }\n      return finalizer(this.state.exit)\n    })\n  }\n  unsafeRemoveFinalizer(finalizer: (exit: MicroExit<any, any>) => Micro<void>): void {\n    if (this.state._tag === \"Open\") {\n      this.state.finalizers.delete(finalizer)\n    }\n  }\n  close(microExit: MicroExit<any, any>): Micro<void> {\n    return suspend(() => {\n      if (this.state._tag === \"Open\") {\n        const finalizers = Array.from(this.state.finalizers).reverse()\n        this.state = { _tag: \"Closed\", exit: microExit }\n        return flatMap(\n          forEach(finalizers, (finalizer) => exit(finalizer(microExit))),\n          exitVoidAll\n        )\n      }\n      return void_\n    })\n  }\n  get fork() {\n    return sync(() => {\n      const newScope = new MicroScopeImpl()\n      if (this.state._tag === \"Closed\") {\n        newScope.state = this.state\n        return newScope\n      }\n      function fin(exit: MicroExit<any, any>) {\n        return newScope.close(exit)\n      }\n      this.state.finalizers.add(fin)\n      newScope.unsafeAddFinalizer((_) => sync(() => this.unsafeRemoveFinalizer(fin)))\n      return newScope\n    })\n  }\n}\n\n/**\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const scopeMake: Micro<MicroScope.Closeable> = sync(() => new MicroScopeImpl())\n\n/**\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const scopeUnsafeMake = (): MicroScope.Closeable => new MicroScopeImpl()\n\n/**\n * Access the current `MicroScope`.\n *\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const scope: Micro<MicroScope, never, MicroScope> = service(MicroScope)\n\n/**\n * Provide a `MicroScope` to an effect.\n *\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const provideScope: {\n  (scope: MicroScope): <A, E, R>(self: Micro<A, E, R>) => Micro<A, E, Exclude<R, MicroScope>>\n  <A, E, R>(self: Micro<A, E, R>, scope: MicroScope): Micro<A, E, Exclude<R, MicroScope>>\n} = dual(\n  2,\n  <A, E, R>(self: Micro<A, E, R>, scope: MicroScope): Micro<A, E, Exclude<R, MicroScope>> =>\n    provideService(self, MicroScope, scope)\n)\n\n/**\n * Provide a `MicroScope` to the given effect, closing it after the effect has\n * finished executing.\n *\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const scoped = <A, E, R>(self: Micro<A, E, R>): Micro<A, E, Exclude<R, MicroScope>> =>\n  suspend(() => {\n    const scope = new MicroScopeImpl()\n    return onExit(provideService(self, MicroScope, scope), (exit) => scope.close(exit))\n  })\n\n/**\n * Create a resource with a cleanup `Micro` effect, ensuring the cleanup is\n * executed when the `MicroScope` is closed.\n *\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const acquireRelease = <A, E, R>(\n  acquire: Micro<A, E, R>,\n  release: (a: A, exit: MicroExit<unknown, unknown>) => Micro<void>\n): Micro<A, E, R | MicroScope> =>\n  uninterruptible(flatMap(\n    scope,\n    (scope) => tap(acquire, (a) => scope.addFinalizer((exit) => release(a, exit)))\n  ))\n\n/**\n * Add a finalizer to the current `MicroScope`.\n *\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const addFinalizer = (\n  finalizer: (exit: MicroExit<unknown, unknown>) => Micro<void>\n): Micro<void, never, MicroScope> => flatMap(scope, (scope) => scope.addFinalizer(finalizer))\n\n/**\n * When the `Micro` effect is completed, run the given finalizer effect with the\n * `MicroExit` of the executed effect.\n *\n * @since 3.4.6\n * @experimental\n * @category resources & finalization\n */\nexport const onExit: {\n  <A, E, XE, XR>(\n    f: (exit: MicroExit<A, E>) => Micro<void, XE, XR>\n  ): <R>(self: Micro<A, E, R>) => Micro<A, E | XE, R | XR>\n  <A, E, R, XE, XR>(\n    self: Micro<A, E, R>,\n    f: (exit: MicroExit<A, E>) => Micro<void, XE, XR>\n  ): Micro<A, E | XE, R | XR>\n} = dual(\n  2,\n  <A, E, R, XE, XR>(\n    self: Micro<A, E, R>,\n    f: (exit: MicroExit<A, E>) => Micro<void, XE, XR>\n  ): Micro<A, E | XE, R | XR> =>\n    uninterruptibleMask((restore) =>\n      matchCauseEffect(restore(self), {\n        onFailure: (cause) => flatMap(f(exitFailCause(cause)), () => failCause(cause)),\n        onSuccess: (a) => flatMap(f(exitSucceed(a)), () => succeed(a))\n      })\n    )\n)\n\n/**\n * Regardless of the result of the this `Micro` effect, run the finalizer effect.\n *\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const ensuring: {\n  <XE, XR>(\n    finalizer: Micro<void, XE, XR>\n  ): <A, E, R>(self: Micro<A, E, R>) => Micro<A, E | XE, R | XR>\n  <A, E, R, XE, XR>(\n    self: Micro<A, E, R>,\n    finalizer: Micro<void, XE, XR>\n  ): Micro<A, E | XE, R | XR>\n} = dual(\n  2,\n  <A, E, R, XE, XR>(\n    self: Micro<A, E, R>,\n    finalizer: Micro<void, XE, XR>\n  ): Micro<A, E | XE, R | XR> => onExit(self, (_) => finalizer)\n)\n\n/**\n * When the `Micro` effect is completed, run the given finalizer effect if it\n * matches the specified predicate.\n *\n * @since 3.4.6\n * @experimental\n * @category resources & finalization\n */\nexport const onExitIf: {\n  <A, E, XE, XR, B extends MicroExit<A, E>>(\n    refinement: Refinement<MicroExit<A, E>, B>,\n    f: (exit: B) => Micro<void, XE, XR>\n  ): <R>(self: Micro<A, E, R>) => Micro<A, E | XE, R | XR>\n  <A, E, XE, XR>(\n    predicate: Predicate<MicroExit<NoInfer<A>, NoInfer<E>>>,\n    f: (exit: MicroExit<NoInfer<A>, NoInfer<E>>) => Micro<void, XE, XR>\n  ): <R>(self: Micro<A, E, R>) => Micro<A, E | XE, R | XR>\n  <A, E, R, XE, XR, B extends MicroExit<A, E>>(\n    self: Micro<A, E, R>,\n    refinement: Refinement<MicroExit<A, E>, B>,\n    f: (exit: B) => Micro<void, XE, XR>\n  ): Micro<A, E | XE, R | XR>\n  <A, E, R, XE, XR>(\n    self: Micro<A, E, R>,\n    predicate: Predicate<MicroExit<NoInfer<A>, NoInfer<E>>>,\n    f: (exit: MicroExit<NoInfer<A>, NoInfer<E>>) => Micro<void, XE, XR>\n  ): Micro<A, E | XE, R | XR>\n} = dual(\n  3,\n  <A, E, R, XE, XR, B extends MicroExit<A, E>>(\n    self: Micro<A, E, R>,\n    refinement: Refinement<MicroExit<A, E>, B>,\n    f: (exit: B) => Micro<void, XE, XR>\n  ): Micro<A, E | XE, R | XR> => onExit(self, (exit) => (refinement(exit) ? f(exit) : exitVoid))\n)\n\n/**\n * When the `Micro` effect fails, run the given finalizer effect with the\n * `MicroCause` of the executed effect.\n *\n * @since 3.4.6\n * @experimental\n * @category resources & finalization\n */\nexport const onError: {\n  <A, E, XE, XR>(\n    f: (cause: MicroCause<NoInfer<E>>) => Micro<void, XE, XR>\n  ): <R>(self: Micro<A, E, R>) => Micro<A, E | XE, R | XR>\n  <A, E, R, XE, XR>(\n    self: Micro<A, E, R>,\n    f: (cause: MicroCause<NoInfer<E>>) => Micro<void, XE, XR>\n  ): Micro<A, E | XE, R | XR>\n} = dual(\n  2,\n  <A, E, R, XE, XR>(\n    self: Micro<A, E, R>,\n    f: (cause: MicroCause<NoInfer<E>>) => Micro<void, XE, XR>\n  ): Micro<A, E | XE, R | XR> => onExitIf(self, exitIsFailure, (exit) => f(exit.cause))\n)\n\n/**\n * If this `Micro` effect is aborted, run the finalizer effect.\n *\n * @since 3.4.6\n * @experimental\n * @category resources & finalization\n */\nexport const onInterrupt: {\n  <XE, XR>(\n    finalizer: Micro<void, XE, XR>\n  ): <A, E, R>(self: Micro<A, E, R>) => Micro<A, E | XE, R | XR>\n  <A, E, R, XE, XR>(self: Micro<A, E, R>, finalizer: Micro<void, XE, XR>): Micro<A, E | XE, R | XR>\n} = dual(\n  2,\n  <A, E, R, XE, XR>(self: Micro<A, E, R>, finalizer: Micro<void, XE, XR>): Micro<A, E | XE, R | XR> =>\n    onExitIf(self, exitIsInterrupt, (_) => finalizer)\n)\n\n/**\n * Acquire a resource, use it, and then release the resource when the `use`\n * effect has completed.\n *\n * @since 3.4.0\n * @experimental\n * @category resources & finalization\n */\nexport const acquireUseRelease = <Resource, E, R, A, E2, R2, E3, R3>(\n  acquire: Micro<Resource, E, R>,\n  use: (a: Resource) => Micro<A, E2, R2>,\n  release: (a: Resource, exit: MicroExit<A, E2>) => Micro<void, E3, R3>\n): Micro<A, E | E2 | E3, R | R2 | R3> =>\n  uninterruptibleMask((restore) =>\n    flatMap(\n      acquire,\n      (a) =>\n        flatMap(\n          exit(restore(use(a))),\n          (exit) => andThen(release(a, exit), exit)\n        )\n    )\n  )\n\n// ----------------------------------------------------------------------------\n// interruption\n// ----------------------------------------------------------------------------\n\n/**\n * Abort the current `Micro` effect.\n *\n * @since 3.4.6\n * @experimental\n * @category interruption\n */\nexport const interrupt: Micro<never> = failCause(causeInterrupt())\n\n/**\n * Flag the effect as uninterruptible, which means that when the effect is\n * interrupted, it will be allowed to continue running until completion.\n *\n * @since 3.4.0\n * @experimental\n * @category flags\n */\nexport const uninterruptible = <A, E, R>(\n  self: Micro<A, E, R>\n): Micro<A, E, R> =>\n  withMicroFiber((fiber) => {\n    if (!fiber.interruptible) return self\n    fiber.interruptible = false\n    fiber._stack.push(setInterruptible(true))\n    return self\n  })\n\nconst setInterruptible: (interruptible: boolean) => Primitive = makePrimitive({\n  op: \"SetInterruptible\",\n  ensure(fiber) {\n    fiber.interruptible = this[args]\n    if (fiber._interrupted && fiber.interruptible) {\n      return () => exitInterrupt\n    }\n  }\n})\n\n/**\n * Flag the effect as interruptible, which means that when the effect is\n * interrupted, it will be interrupted immediately.\n *\n * @since 3.4.0\n * @experimental\n * @category flags\n */\nexport const interruptible = <A, E, R>(\n  self: Micro<A, E, R>\n): Micro<A, E, R> =>\n  withMicroFiber((fiber) => {\n    if (fiber.interruptible) return self\n    fiber.interruptible = true\n    fiber._stack.push(setInterruptible(false))\n    if (fiber._interrupted) return exitInterrupt\n    return self\n  })\n\n/**\n * Wrap the given `Micro` effect in an uninterruptible region, preventing the\n * effect from being aborted.\n *\n * You can use the `restore` function to restore a `Micro` effect to the\n * interruptibility state before the `uninterruptibleMask` was applied.\n *\n * @example\n * ```ts\n * import * as Micro from \"effect/Micro\"\n *\n * Micro.uninterruptibleMask((restore) =>\n *   Micro.sleep(1000).pipe( // uninterruptible\n *     Micro.andThen(restore(Micro.sleep(1000))) // interruptible\n *   )\n * )\n * ```\n *\n * @since 3.4.0\n * @experimental\n * @category interruption\n */\nexport const uninterruptibleMask = <A, E, R>(\n  f: (\n    restore: <A, E, R>(effect: Micro<A, E, R>) => Micro<A, E, R>\n  ) => Micro<A, E, R>\n): Micro<A, E, R> =>\n  withMicroFiber((fiber) => {\n    if (!fiber.interruptible) return f(identity)\n    fiber.interruptible = false\n    fiber._stack.push(setInterruptible(true))\n    return f(interruptible)\n  })\n\n// ========================================================================\n// collecting & elements\n// ========================================================================\n\n/**\n * @since 3.4.0\n * @experimental\n */\nexport declare namespace All {\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export type MicroAny = Micro<any, any, any>\n\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export type ReturnIterable<T extends Iterable<MicroAny>, Discard extends boolean> = [T] extends\n    [Iterable<Micro<infer A, infer E, infer R>>] ? Micro<\n      Discard extends true ? void : Array<A>,\n      E,\n      R\n    >\n    : never\n\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export type ReturnTuple<T extends ReadonlyArray<unknown>, Discard extends boolean> = Micro<\n    Discard extends true ? void\n      : T[number] extends never ? []\n      : { -readonly [K in keyof T]: T[K] extends Micro<infer _A, infer _E, infer _R> ? _A : never },\n    T[number] extends never ? never\n      : T[number] extends Micro<infer _A, infer _E, infer _R> ? _E\n      : never,\n    T[number] extends never ? never\n      : T[number] extends Micro<infer _A, infer _E, infer _R> ? _R\n      : never\n  > extends infer X ? X : never\n\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export type ReturnObject<T, Discard extends boolean> = [T] extends [{ [K: string]: MicroAny }] ? Micro<\n      Discard extends true ? void :\n        { -readonly [K in keyof T]: [T[K]] extends [Micro<infer _A, infer _E, infer _R>] ? _A : never },\n      keyof T extends never ? never\n        : T[keyof T] extends Micro<infer _A, infer _E, infer _R> ? _E\n        : never,\n      keyof T extends never ? never\n        : T[keyof T] extends Micro<infer _A, infer _E, infer _R> ? _R\n        : never\n    >\n    : never\n\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export type IsDiscard<A> = [Extract<A, { readonly discard: true }>] extends [never] ? false : true\n\n  /**\n   * @since 3.4.0\n   * @experimental\n   */\n  export type Return<\n    Arg extends Iterable<MicroAny> | Record<string, MicroAny>,\n    O extends NoExcessProperties<{\n      readonly concurrency?: Concurrency | undefined\n      readonly discard?: boolean | undefined\n    }, O>\n  > = [Arg] extends [ReadonlyArray<MicroAny>] ? ReturnTuple<Arg, IsDiscard<O>>\n    : [Arg] extends [Iterable<MicroAny>] ? ReturnIterable<Arg, IsDiscard<O>>\n    : [Arg] extends [Record<string, MicroAny>] ? ReturnObject<Arg, IsDiscard<O>>\n    : never\n}\n\n/**\n * Runs all the provided effects in sequence respecting the structure provided in input.\n *\n * Supports multiple arguments, a single argument tuple / array or record / struct.\n *\n * @since 3.4.0\n * @experimental\n * @category collecting & elements\n */\nexport const all = <\n  const Arg extends Iterable<Micro<any, any, any>> | Record<string, Micro<any, any, any>>,\n  O extends NoExcessProperties<{\n    readonly concurrency?: Concurrency | undefined\n    readonly discard?: boolean | undefined\n  }, O>\n>(arg: Arg, options?: O): All.Return<Arg, O> => {\n  if (Array.isArray(arg) || isIterable(arg)) {\n    return (forEach as any)(arg, identity, options)\n  } else if (options?.discard) {\n    return (forEach as any)(Object.values(arg), identity, options)\n  }\n  return suspend(() => {\n    const out: Record<string, unknown> = {}\n    return as(\n      forEach(Object.entries(arg), ([key, effect]) =>\n        map(effect, (value) => {\n          out[key] = value\n        }), {\n        discard: true,\n        concurrency: options?.concurrency\n      }),\n      out\n    )\n  }) as any\n}\n\n/**\n * @since 3.11.0\n * @experimental\n * @category collecting & elements\n */\nexport const whileLoop: <A, E, R>(options: {\n  readonly while: LazyArg<boolean>\n  readonly body: LazyArg<Micro<A, E, R>>\n  readonly step: (a: A) => void\n}) => Micro<void, E, R> = makePrimitive({\n  op: \"While\",\n  contA(value, fiber) {\n    this[args].step(value)\n    if (this[args].while()) {\n      fiber._stack.push(this)\n      return this[args].body()\n    }\n    return exitVoid\n  },\n  eval(fiber) {\n    if (this[args].while()) {\n      fiber._stack.push(this)\n      return this[args].body()\n    }\n    return exitVoid\n  }\n})\n\n/**\n * For each element of the provided iterable, run the effect and collect the\n * results.\n *\n * If the `discard` option is set to `true`, the results will be discarded and\n * the effect will return `void`.\n *\n * The `concurrency` option can be set to control how many effects are run\n * concurrently. By default, the effects are run sequentially.\n *\n * @since 3.4.0\n * @experimental\n * @category collecting & elements\n */\nexport const forEach: {\n  <A, B, E, R>(iterable: Iterable<A>, f: (a: A, index: number) => Micro<B, E, R>, options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly discard?: false | undefined\n  }): Micro<Array<B>, E, R>\n  <A, B, E, R>(iterable: Iterable<A>, f: (a: A, index: number) => Micro<B, E, R>, options: {\n    readonly concurrency?: Concurrency | undefined\n    readonly discard: true\n  }): Micro<void, E, R>\n} = <\n  A,\n  B,\n  E,\n  R\n>(iterable: Iterable<A>, f: (a: A, index: number) => Micro<B, E, R>, options?: {\n  readonly concurrency?: Concurrency | undefined\n  readonly discard?: boolean | undefined\n}): Micro<any, E, R> =>\n  withMicroFiber((parent) => {\n    const concurrencyOption = options?.concurrency === \"inherit\"\n      ? parent.getRef(CurrentConcurrency)\n      : options?.concurrency ?? 1\n    const concurrency = concurrencyOption === \"unbounded\"\n      ? Number.POSITIVE_INFINITY\n      : Math.max(1, concurrencyOption)\n\n    const items = Arr.fromIterable(iterable)\n    let length = items.length\n    if (length === 0) {\n      return options?.discard ? void_ : succeed([])\n    }\n\n    const out: Array<B> | undefined = options?.discard ? undefined : new Array(length)\n    let index = 0\n\n    if (concurrency === 1) {\n      return as(\n        whileLoop({\n          while: () => index < items.length,\n          body: () => f(items[index], index),\n          step: out ?\n            (b) => out[index++] = b :\n            (_) => index++\n        }),\n        out as any\n      )\n    }\n    return async((resume) => {\n      const fibers = new Set<MicroFiber<unknown, unknown>>()\n      let result: MicroExit<any, any> | undefined = undefined\n      let inProgress = 0\n      let doneCount = 0\n      let pumping = false\n      let interrupted = false\n      function pump() {\n        pumping = true\n        while (inProgress < concurrency && index < length) {\n          const currentIndex = index\n          const item = items[currentIndex]\n          index++\n          inProgress++\n          try {\n            const child = unsafeFork(parent, f(item, currentIndex), true, true)\n            fibers.add(child)\n            child.addObserver((exit) => {\n              fibers.delete(child)\n              if (interrupted) {\n                return\n              } else if (exit._tag === \"Failure\") {\n                if (result === undefined) {\n                  result = exit\n                  length = index\n                  fibers.forEach((fiber) => fiber.unsafeInterrupt())\n                }\n              } else if (out !== undefined) {\n                out[currentIndex] = exit.value\n              }\n              doneCount++\n              inProgress--\n              if (doneCount === length) {\n                resume(result ?? succeed(out))\n              } else if (!pumping && inProgress < concurrency) {\n                pump()\n              }\n            })\n          } catch (err) {\n            result = exitDie(err)\n            length = index\n            fibers.forEach((fiber) => fiber.unsafeInterrupt())\n          }\n        }\n        pumping = false\n      }\n      pump()\n\n      return suspend(() => {\n        interrupted = true\n        index = length\n        return fiberInterruptAll(fibers)\n      })\n    })\n  })\n\n/**\n * Effectfully filter the elements of the provided iterable.\n *\n * Use the `concurrency` option to control how many elements are processed\n * concurrently.\n *\n * @since 3.4.0\n * @experimental\n * @category collecting & elements\n */\nexport const filter = <A, E, R>(iterable: Iterable<A>, f: (a: NoInfer<A>) => Micro<boolean, E, R>, options?: {\n  readonly concurrency?: Concurrency | undefined\n  readonly negate?: boolean | undefined\n}): Micro<Array<A>, E, R> =>\n  filterMap(iterable, (a) =>\n    map(f(a), (pass) => {\n      pass = options?.negate ? !pass : pass\n      return pass ? Option.some(a) : Option.none()\n    }), options)\n\n/**\n * Effectfully filter the elements of the provided iterable.\n *\n * Use the `concurrency` option to control how many elements are processed\n * concurrently.\n *\n * @since 3.4.0\n * @experimental\n * @category collecting & elements\n */\nexport const filterMap = <A, B, E, R>(\n  iterable: Iterable<A>,\n  f: (a: NoInfer<A>) => Micro<Option.Option<B>, E, R>,\n  options?: {\n    readonly concurrency?: Concurrency | undefined\n  }\n): Micro<Array<B>, E, R> =>\n  suspend(() => {\n    const out: Array<B> = []\n    return as(\n      forEach(iterable, (a) =>\n        map(f(a), (o) => {\n          if (o._tag === \"Some\") {\n            out.push(o.value)\n          }\n        }), {\n        discard: true,\n        concurrency: options?.concurrency\n      }),\n      out\n    )\n  })\n\n// ----------------------------------------------------------------------------\n// do notation\n// ----------------------------------------------------------------------------\n\n/**\n * Start a do notation block.\n *\n * @since 3.4.0\n * @experimental\n * @category do notation\n */\nexport const Do: Micro<{}> = succeed({})\n\n/**\n * Bind the success value of this `Micro` effect to the provided name.\n *\n * @since 3.4.0\n * @experimental\n * @category do notation\n */\nexport const bindTo: {\n  <N extends string>(name: N): <A, E, R>(self: Micro<A, E, R>) => Micro<{ [K in N]: A }, E, R>\n  <A, E, R, N extends string>(self: Micro<A, E, R>, name: N): Micro<{ [K in N]: A }, E, R>\n} = doNotation.bindTo<MicroTypeLambda>(map)\n\n/**\n * Bind the success value of this `Micro` effect to the provided name.\n *\n * @since 3.4.0\n * @experimental\n * @category do notation\n */\nexport const bind: {\n  <N extends string, A extends Record<string, any>, B, E2, R2>(\n    name: N,\n    f: (a: NoInfer<A>) => Micro<B, E2, R2>\n  ): <E, R>(self: Micro<A, E, R>) => Micro<Simplify<Omit<A, N> & { [K in N]: B }>, E | E2, R | R2>\n  <A extends Record<string, any>, E, R, B, E2, R2, N extends string>(\n    self: Micro<A, E, R>,\n    name: N,\n    f: (a: NoInfer<A>) => Micro<B, E2, R2>\n  ): Micro<Simplify<Omit<A, N> & { [K in N]: B }>, E | E2, R | R2>\n} = doNotation.bind<MicroTypeLambda>(map, flatMap)\n\nconst let_: {\n  <N extends string, A extends Record<string, any>, B>(\n    name: N,\n    f: (a: NoInfer<A>) => B\n  ): <E, R>(self: Micro<A, E, R>) => Micro<Simplify<Omit<A, N> & { [K in N]: B }>, E, R>\n  <A extends Record<string, any>, E, R, B, N extends string>(\n    self: Micro<A, E, R>,\n    name: N,\n    f: (a: NoInfer<A>) => B\n  ): Micro<Simplify<Omit<A, N> & { [K in N]: B }>, E, R>\n} = doNotation.let_<MicroTypeLambda>(map)\n\nexport {\n  /**\n   * Bind the result of a synchronous computation to the given name.\n   *\n   * @since 3.4.0\n   * @experimental\n   * @category do notation\n   */\n  let_ as let\n}\n\n// ----------------------------------------------------------------------------\n// fibers & forking\n// ----------------------------------------------------------------------------\n\n/**\n * Run the `Micro` effect in a new `MicroFiber` that can be awaited, joined, or\n * aborted.\n *\n * When the parent `Micro` finishes, this `Micro` will be aborted.\n *\n * @since 3.4.0\n * @experimental\n * @category fiber & forking\n */\nexport const fork = <A, E, R>(\n  self: Micro<A, E, R>\n): Micro<MicroFiber<A, E>, never, R> =>\n  withMicroFiber((fiber) => {\n    fiberMiddleware.interruptChildren ??= fiberInterruptChildren\n    return succeed(unsafeFork(fiber, self))\n  })\n\nconst unsafeFork = <FA, FE, A, E, R>(\n  parent: MicroFiberImpl<FA, FE>,\n  effect: Micro<A, E, R>,\n  immediate = false,\n  daemon = false\n): MicroFiber<A, E> => {\n  const child = new MicroFiberImpl<A, E>(parent.context, parent.interruptible)\n  if (!daemon) {\n    parent.children().add(child)\n    child.addObserver(() => parent.children().delete(child))\n  }\n  if (immediate) {\n    child.evaluate(effect as any)\n  } else {\n    parent.getRef(CurrentScheduler).scheduleTask(() => child.evaluate(effect as any), 0)\n  }\n  return child\n}\n\n/**\n * Run the `Micro` effect in a new `MicroFiber` that can be awaited, joined, or\n * aborted.\n *\n * It will not be aborted when the parent `Micro` finishes.\n *\n * @since 3.4.0\n * @experimental\n * @category fiber & forking\n */\nexport const forkDaemon = <A, E, R>(\n  self: Micro<A, E, R>\n): Micro<MicroFiber<A, E>, never, R> => withMicroFiber((fiber) => succeed(unsafeFork(fiber, self, false, true)))\n\n/**\n * Run the `Micro` effect in a new `MicroFiber` that can be awaited, joined, or\n * aborted.\n *\n * The lifetime of the handle will be attached to the provided `MicroScope`.\n *\n * @since 3.4.0\n * @experimental\n * @category fiber & forking\n */\nexport const forkIn: {\n  (scope: MicroScope): <A, E, R>(self: Micro<A, E, R>) => Micro<MicroFiber<A, E>, never, R>\n  <A, E, R>(self: Micro<A, E, R>, scope: MicroScope): Micro<MicroFiber<A, E>, never, R>\n} = dual(\n  2,\n  <A, E, R>(self: Micro<A, E, R>, scope: MicroScope): Micro<MicroFiber<A, E>, never, R> =>\n    uninterruptibleMask((restore) =>\n      flatMap(scope.fork, (scope) =>\n        tap(\n          restore(forkDaemon(onExit(self, (exit) => scope.close(exit)))),\n          (fiber) => scope.addFinalizer((_) => fiberInterrupt(fiber))\n        ))\n    )\n)\n\n/**\n * Run the `Micro` effect in a new `MicroFiber` that can be awaited, joined, or\n * aborted.\n *\n * The lifetime of the handle will be attached to the current `MicroScope`.\n *\n * @since 3.4.0\n * @experimental\n * @category fiber & forking\n */\nexport const forkScoped = <A, E, R>(self: Micro<A, E, R>): Micro<MicroFiber<A, E>, never, R | MicroScope> =>\n  flatMap(scope, (scope) => forkIn(self, scope))\n\n// ----------------------------------------------------------------------------\n// execution\n// ----------------------------------------------------------------------------\n\n/**\n * Execute the `Micro` effect and return a `MicroFiber` that can be awaited, joined,\n * or aborted.\n *\n * You can listen for the result by adding an observer using the handle's\n * `addObserver` method.\n *\n * @example\n * ```ts\n * import * as Micro from \"effect/Micro\"\n *\n * const handle = Micro.succeed(42).pipe(\n *   Micro.delay(1000),\n *   Micro.runFork\n * )\n *\n * handle.addObserver((exit) => {\n *   console.log(exit)\n * })\n * ```\n *\n * @since 3.4.0\n * @experimental\n * @category execution\n */\nexport const runFork = <A, E>(\n  effect: Micro<A, E>,\n  options?: {\n    readonly signal?: AbortSignal | undefined\n    readonly scheduler?: MicroScheduler | undefined\n  } | undefined\n): MicroFiberImpl<A, E> => {\n  const fiber = new MicroFiberImpl<A, E>(CurrentScheduler.context(\n    options?.scheduler ?? new MicroSchedulerDefault()\n  ))\n  fiber.evaluate(effect as any)\n  if (options?.signal) {\n    if (options.signal.aborted) {\n      fiber.unsafeInterrupt()\n    } else {\n      const abort = () => fiber.unsafeInterrupt()\n      options.signal.addEventListener(\"abort\", abort, { once: true })\n      fiber.addObserver(() => options.signal!.removeEventListener(\"abort\", abort))\n    }\n  }\n  return fiber\n}\n\n/**\n * Execute the `Micro` effect and return a `Promise` that resolves with the\n * `MicroExit` of the computation.\n *\n * @since 3.4.6\n * @experimental\n * @category execution\n */\nexport const runPromiseExit = <A, E>(\n  effect: Micro<A, E>,\n  options?: {\n    readonly signal?: AbortSignal | undefined\n    readonly scheduler?: MicroScheduler | undefined\n  } | undefined\n): Promise<MicroExit<A, E>> =>\n  new Promise((resolve, _reject) => {\n    const handle = runFork(effect, options)\n    handle.addObserver(resolve)\n  })\n\n/**\n * Execute the `Micro` effect and return a `Promise` that resolves with the\n * successful value of the computation.\n *\n * @since 3.4.0\n * @experimental\n * @category execution\n */\nexport const runPromise = <A, E>(\n  effect: Micro<A, E>,\n  options?: {\n    readonly signal?: AbortSignal | undefined\n    readonly scheduler?: MicroScheduler | undefined\n  } | undefined\n): Promise<A> =>\n  runPromiseExit(effect, options).then((exit) => {\n    if (exit._tag === \"Failure\") {\n      throw exit.cause\n    }\n    return exit.value\n  })\n\n/**\n * Attempt to execute the `Micro` effect synchronously and return the `MicroExit`.\n *\n * If any asynchronous effects are encountered, the function will return a\n * `CauseDie` containing the `MicroFiber`.\n *\n * @since 3.4.6\n * @experimental\n * @category execution\n */\nexport const runSyncExit = <A, E>(effect: Micro<A, E>): MicroExit<A, E> => {\n  const scheduler = new MicroSchedulerDefault()\n  const fiber = runFork(effect, { scheduler })\n  scheduler.flush()\n  return fiber._exit ?? exitDie(fiber)\n}\n\n/**\n * Attempt to execute the `Micro` effect synchronously and return the success\n * value.\n *\n * @since 3.4.0\n * @experimental\n * @category execution\n */\nexport const runSync = <A, E>(effect: Micro<A, E>): A => {\n  const exit = runSyncExit(effect)\n  if (exit._tag === \"Failure\") throw exit.cause\n  return exit.value\n}\n\n// ----------------------------------------------------------------------------\n// Errors\n// ----------------------------------------------------------------------------\n\n/**\n * @since 3.4.0\n * @experimental\n * @category errors\n */\nexport interface YieldableError extends Pipeable, Inspectable, Readonly<Error> {\n  readonly [Effectable.EffectTypeId]: Effect.VarianceStruct<never, this, never>\n  readonly [Effectable.StreamTypeId]: Stream.VarianceStruct<never, this, never>\n  readonly [Effectable.SinkTypeId]: Sink.VarianceStruct<never, unknown, never, this, never>\n  readonly [Effectable.ChannelTypeId]: Channel.VarianceStruct<never, unknown, this, unknown, never, unknown, never>\n  readonly [TypeId]: Micro.Variance<never, this, never>\n  [Symbol.iterator](): MicroIterator<Micro<never, this, never>>\n}\n\nconst YieldableError: new(message?: string) => YieldableError = (function() {\n  class YieldableError extends globalThis.Error {}\n  // @effect-diagnostics-next-line floatingEffect:off\n  Object.assign(YieldableError.prototype, MicroProto, StructuralPrototype, {\n    [identifier]: \"Failure\",\n    [evaluate]() {\n      return fail(this)\n    },\n    toString(this: Error) {\n      return this.message ? `${this.name}: ${this.message}` : this.name\n    },\n    toJSON() {\n      return { ...this }\n    },\n    [NodeInspectSymbol](this: Error): string {\n      const stack = this.stack\n      if (stack) {\n        return `${this.toString()}\\n${stack.split(\"\\n\").slice(1).join(\"\\n\")}`\n      }\n      return this.toString()\n    }\n  })\n  return YieldableError as any\n})()\n\n/**\n * @since 3.4.0\n * @experimental\n * @category errors\n */\nexport const Error: new<A extends Record<string, any> = {}>(\n  args: Equals<A, {}> extends true ? void\n    : { readonly [P in keyof A]: A[P] }\n) => YieldableError & Readonly<A> = (function() {\n  return class extends YieldableError {\n    constructor(args: any) {\n      super()\n      if (args) {\n        Object.assign(this, args)\n      }\n    }\n  } as any\n})()\n\n/**\n * @since 3.4.0\n * @experimental\n * @category errors\n */\nexport const TaggedError = <Tag extends string>(tag: Tag): new<A extends Record<string, any> = {}>(\n  args: Equals<A, {}> extends true ? void\n    : { readonly [P in keyof A as P extends \"_tag\" ? never : P]: A[P] }\n) => YieldableError & { readonly _tag: Tag } & Readonly<A> => {\n  class Base extends Error<{}> {\n    readonly _tag = tag\n  }\n  ;(Base.prototype as any).name = tag\n  return Base as any\n}\n\n/**\n * Represents a checked exception which occurs when an expected element was\n * unable to be found.\n *\n * @since 3.4.4\n * @experimental\n * @category errors\n */\nexport class NoSuchElementException extends TaggedError(\"NoSuchElementException\")<{ message?: string | undefined }> {}\n\n/**\n * Represents a checked exception which occurs when a timeout occurs.\n *\n * @since 3.4.4\n * @experimental\n * @category errors\n */\nexport class TimeoutException extends TaggedError(\"TimeoutException\") {}\n"
  },
  {
    "path": "packages/effect/src/ModuleVersion.ts",
    "content": "/**\n * @since 2.0.0\n *\n * Enables low level framework authors to run on their own isolated effect version\n */\nimport * as internal from \"./internal/version.js\"\n\n/**\n * @since 2.0.0\n * @category version\n */\nexport const getCurrentVersion: () => string = internal.getCurrentVersion\n\n/**\n * @since 2.0.0\n * @category version\n */\nexport const setCurrentVersion: (version: string) => void = internal.setCurrentVersion\n"
  },
  {
    "path": "packages/effect/src/MutableHashMap.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { NonEmptyArray } from \"./Array.js\"\nimport * as Equal from \"./Equal.js\"\nimport { dual } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport { format, type Inspectable, NodeInspectSymbol, toJSON } from \"./Inspectable.js\"\nimport * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\n\nconst TypeId: unique symbol = Symbol.for(\"effect/MutableHashMap\") as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MutableHashMap<out K, out V> extends Iterable<[K, V]>, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n  /** @internal */\n  readonly referential: Map<K, V>\n  /** @internal */\n  readonly buckets: Map<number, NonEmptyArray<readonly [K & Equal.Equal, V]>>\n  /** @internal */\n  bucketsSize: number\n}\n\nconst MutableHashMapProto: Omit<MutableHashMap<unknown, unknown>, \"referential\" | \"buckets\" | \"bucketsSize\"> = {\n  [TypeId]: TypeId,\n  [Symbol.iterator](this: MutableHashMap<unknown, unknown>): Iterator<[unknown, unknown]> {\n    return new MutableHashMapIterator(this)\n  },\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"MutableHashMap\",\n      values: Array.from(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nclass MutableHashMapIterator<K, V> implements IterableIterator<[K, V]> {\n  readonly referentialIterator: Iterator<[K, V]>\n  bucketIterator: Iterator<[K, V]> | undefined\n\n  constructor(readonly self: MutableHashMap<K, V>) {\n    this.referentialIterator = self.referential[Symbol.iterator]()\n  }\n  next(): IteratorResult<[K, V]> {\n    if (this.bucketIterator !== undefined) {\n      return this.bucketIterator.next()\n    }\n    const result = this.referentialIterator.next()\n    if (result.done) {\n      this.bucketIterator = new BucketIterator(this.self.buckets.values())\n      return this.next()\n    }\n    return result\n  }\n\n  [Symbol.iterator](): IterableIterator<[K, V]> {\n    return new MutableHashMapIterator(this.self)\n  }\n}\n\nclass BucketIterator<K, V> implements Iterator<[K, V]> {\n  constructor(readonly backing: Iterator<NonEmptyArray<readonly [K, V]>>) {}\n  currentBucket: Iterator<readonly [K, V]> | undefined\n  next(): IteratorResult<[K, V]> {\n    if (this.currentBucket === undefined) {\n      const result = this.backing.next()\n      if (result.done) {\n        return result\n      }\n      this.currentBucket = result.value[Symbol.iterator]()\n    }\n    const result = this.currentBucket.next()\n    if (result.done) {\n      this.currentBucket = undefined\n      return this.next()\n    }\n    return result as IteratorResult<[K, V]>\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const empty = <K = never, V = never>(): MutableHashMap<K, V> => {\n  const self = Object.create(MutableHashMapProto)\n  self.referential = new Map()\n  self.buckets = new Map()\n  self.bucketsSize = 0\n  return self\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Entries extends Array<readonly [any, any]>>(\n  ...entries: Entries\n) => MutableHashMap<\n  Entries[number] extends readonly [infer K, any] ? K : never,\n  Entries[number] extends readonly [any, infer V] ? V : never\n> = (...entries) => fromIterable(entries)\n\n/**\n * Creates a new `MutableHashMap` from an iterable collection of key/value pairs.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable = <K, V>(entries: Iterable<readonly [K, V]>): MutableHashMap<K, V> => {\n  const self = empty<K, V>()\n  for (const [key, value] of entries) {\n    set(self, key, value)\n  }\n  return self\n}\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const get: {\n  <K>(key: K): <V>(self: MutableHashMap<K, V>) => Option.Option<V>\n  <K, V>(self: MutableHashMap<K, V>, key: K): Option.Option<V>\n} = dual<\n  <K>(key: K) => <V>(self: MutableHashMap<K, V>) => Option.Option<V>,\n  <K, V>(self: MutableHashMap<K, V>, key: K) => Option.Option<V>\n>(2, <K, V>(self: MutableHashMap<K, V>, key: K): Option.Option<V> => {\n  if (Equal.isEqual(key) === false) {\n    return self.referential.has(key) ? Option.some(self.referential.get(key)!) : Option.none()\n  }\n\n  const hash = key[Hash.symbol]()\n  const bucket = self.buckets.get(hash)\n  if (bucket === undefined) {\n    return Option.none()\n  }\n\n  return getFromBucket(self, bucket, key)\n})\n\n/**\n * @since 3.8.0\n * @category elements\n */\nexport const keys = <K, V>(self: MutableHashMap<K, V>): Array<K> => {\n  const keys = Array.from(self.referential.keys())\n  for (const bucket of self.buckets.values()) {\n    for (let i = 0, len = bucket.length; i < len; i++) {\n      keys.push(bucket[i][0])\n    }\n  }\n  return keys\n}\n\n/**\n * @since 3.8.0\n * @category elements\n */\nexport const values = <K, V>(self: MutableHashMap<K, V>): Array<V> => {\n  const values = Array.from(self.referential.values())\n  for (const bucket of self.buckets.values()) {\n    for (let i = 0, len = bucket.length; i < len; i++) {\n      values.push(bucket[i][1])\n    }\n  }\n  return values\n}\n\nconst getFromBucket = <K, V>(\n  self: MutableHashMap<K, V>,\n  bucket: NonEmptyArray<readonly [K & Equal.Equal, V]>,\n  key: K & Equal.Equal,\n  remove = false\n): Option.Option<V> => {\n  for (let i = 0, len = bucket.length; i < len; i++) {\n    if (key[Equal.symbol](bucket[i][0])) {\n      const value = bucket[i][1]\n      if (remove) {\n        bucket.splice(i, 1)\n        self.bucketsSize--\n      }\n      return Option.some(value)\n    }\n  }\n\n  return Option.none()\n}\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const has: {\n  <K>(key: K): <V>(self: MutableHashMap<K, V>) => boolean\n  <K, V>(self: MutableHashMap<K, V>, key: K): boolean\n} = dual<\n  <K>(key: K) => <V>(self: MutableHashMap<K, V>) => boolean,\n  <K, V>(self: MutableHashMap<K, V>, key: K) => boolean\n>(2, (self, key) => Option.isSome(get(self, key)))\n\n/**\n * @since 2.0.0\n */\nexport const set: {\n  <K, V>(key: K, value: V): (self: MutableHashMap<K, V>) => MutableHashMap<K, V>\n  <K, V>(self: MutableHashMap<K, V>, key: K, value: V): MutableHashMap<K, V>\n} = dual<\n  <K, V>(key: K, value: V) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>,\n  <K, V>(self: MutableHashMap<K, V>, key: K, value: V) => MutableHashMap<K, V>\n>(3, <K, V>(self: MutableHashMap<K, V>, key: K, value: V) => {\n  if (Equal.isEqual(key) === false) {\n    self.referential.set(key, value)\n    return self\n  }\n\n  const hash = key[Hash.symbol]()\n  const bucket = self.buckets.get(hash)\n  if (bucket === undefined) {\n    self.buckets.set(hash, [[key, value]])\n    self.bucketsSize++\n    return self\n  }\n\n  removeFromBucket(self, bucket, key)\n  bucket.push([key, value])\n  self.bucketsSize++\n  return self\n})\n\nconst removeFromBucket = <K, V>(\n  self: MutableHashMap<K, V>,\n  bucket: NonEmptyArray<readonly [K & Equal.Equal, V]>,\n  key: K & Equal.Equal\n) => {\n  for (let i = 0, len = bucket.length; i < len; i++) {\n    if (key[Equal.symbol](bucket[i][0])) {\n      bucket.splice(i, 1)\n      self.bucketsSize--\n      return\n    }\n  }\n}\n\n/**\n * Updates the value of the specified key within the `MutableHashMap` if it exists.\n *\n * @since 2.0.0\n */\nexport const modify: {\n  <K, V>(key: K, f: (v: V) => V): (self: MutableHashMap<K, V>) => MutableHashMap<K, V>\n  <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V): MutableHashMap<K, V>\n} = dual<\n  <K, V>(key: K, f: (v: V) => V) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>,\n  <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V) => MutableHashMap<K, V>\n>(3, <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V) => {\n  if (Equal.isEqual(key) === false) {\n    if (self.referential.has(key)) {\n      self.referential.set(key, f(self.referential.get(key)!))\n    }\n    return self\n  }\n\n  const hash = key[Hash.symbol]()\n  const bucket = self.buckets.get(hash)\n  if (bucket === undefined) {\n    return self\n  }\n\n  const value = getFromBucket(self, bucket, key, true)\n  if (Option.isNone(value)) {\n    return self\n  }\n  bucket.push([key, f(value.value)])\n  self.bucketsSize++\n  return self\n})\n\n/**\n * Set or remove the specified key in the `MutableHashMap` using the specified\n * update function.\n *\n * @since 2.0.0\n */\nexport const modifyAt: {\n  <K, V>(key: K, f: (value: Option.Option<V>) => Option.Option<V>): (self: MutableHashMap<K, V>) => MutableHashMap<K, V>\n  <K, V>(self: MutableHashMap<K, V>, key: K, f: (value: Option.Option<V>) => Option.Option<V>): MutableHashMap<K, V>\n} = dual<\n  <K, V>(\n    key: K,\n    f: (value: Option.Option<V>) => Option.Option<V>\n  ) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>,\n  <K, V>(\n    self: MutableHashMap<K, V>,\n    key: K,\n    f: (value: Option.Option<V>) => Option.Option<V>\n  ) => MutableHashMap<K, V>\n>(3, (self, key, f) => {\n  if (Equal.isEqual(key) === false) {\n    const result = f(get(self, key))\n    if (Option.isSome(result)) {\n      set(self, key, result.value)\n    } else {\n      remove(self, key)\n    }\n    return self\n  }\n\n  const hash = key[Hash.symbol]()\n  const bucket = self.buckets.get(hash)\n  if (bucket === undefined) {\n    const result = f(Option.none())\n    return Option.isSome(result) ? set(self, key, result.value) : self\n  }\n\n  const result = f(getFromBucket(self, bucket, key, true))\n  if (Option.isNone(result)) {\n    if (bucket.length === 0) {\n      self.buckets.delete(hash)\n    }\n    return self\n  }\n  bucket.push([key, result.value])\n  self.bucketsSize++\n  return self\n})\n\n/**\n * @since 2.0.0\n */\nexport const remove: {\n  <K>(key: K): <V>(self: MutableHashMap<K, V>) => MutableHashMap<K, V>\n  <K, V>(self: MutableHashMap<K, V>, key: K): MutableHashMap<K, V>\n} = dual<\n  <K>(key: K) => <V>(self: MutableHashMap<K, V>) => MutableHashMap<K, V>,\n  <K, V>(self: MutableHashMap<K, V>, key: K) => MutableHashMap<K, V>\n>(2, <K, V>(self: MutableHashMap<K, V>, key: K) => {\n  if (Equal.isEqual(key) === false) {\n    self.referential.delete(key)\n    return self\n  }\n\n  const hash = key[Hash.symbol]()\n  const bucket = self.buckets.get(hash)\n  if (bucket === undefined) {\n    return self\n  }\n  removeFromBucket(self, bucket, key)\n  if (bucket.length === 0) {\n    self.buckets.delete(hash)\n  }\n  return self\n})\n\n/**\n * @since 2.0.0\n */\nexport const clear = <K, V>(self: MutableHashMap<K, V>) => {\n  self.referential.clear()\n  self.buckets.clear()\n  self.bucketsSize = 0\n  return self\n}\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const size = <K, V>(self: MutableHashMap<K, V>): number => {\n  return self.referential.size + self.bucketsSize\n}\n\n/**\n * @since 2.0.0\n */\nexport const isEmpty = <K, V>(self: MutableHashMap<K, V>): boolean => size(self) === 0\n\n/**\n * @since 2.0.0\n */\nexport const forEach: {\n  <K, V>(f: (value: V, key: K) => void): (self: MutableHashMap<K, V>) => void\n  <K, V>(self: MutableHashMap<K, V>, f: (value: V, key: K) => void): void\n} = dual(2, <K, V>(self: MutableHashMap<K, V>, f: (value: V, key: K) => void) => {\n  self.referential.forEach(f)\n  for (const bucket of self.buckets.values()) {\n    for (const [key, value] of bucket) {\n      f(value, key)\n    }\n  }\n})\n"
  },
  {
    "path": "packages/effect/src/MutableHashSet.ts",
    "content": "/**\n * # MutableHashSet\n *\n * A mutable `MutableHashSet` provides a collection of unique values with\n * efficient lookup, insertion and removal. Unlike its immutable sibling\n * {@link module:HashSet}, a `MutableHashSet` can be modified in-place;\n * operations like add, remove, and clear directly modify the original set\n * rather than creating a new one. This mutability offers benefits like improved\n * performance in scenarios where you need to build or modify a set\n * incrementally.\n *\n * ## What Problem Does It Solve?\n *\n * `MutableHashSet` solves the problem of maintaining an unsorted collection\n * where each value appears exactly once, with fast operations for checking\n * membership and adding/removing values, in contexts where mutability is\n * preferred for performance or implementation simplicity.\n *\n * ## When to Use\n *\n * Use `MutableHashSet` when you need:\n *\n * - A collection with no duplicate values\n * - Efficient membership testing (**`O(1)`** average complexity)\n * - In-place modifications for better performance\n * - A set that will be built or modified incrementally\n * - Local mutability in otherwise immutable code\n *\n * ## Advanced Features\n *\n * MutableHashSet provides operations for:\n *\n * - Adding and removing elements with direct mutation\n * - Checking for element existence\n * - Clearing all elements at once\n * - Converting to/from other collection types\n *\n * ## Performance Characteristics\n *\n * - **Lookup** operations ({@link module:MutableHashSet.has}): **`O(1)`** average\n *   time complexity\n * - **Insertion** operations ({@link module:MutableHashSet.add}): **`O(1)`**\n *   average time complexity\n * - **Removal** operations ({@link module:MutableHashSet.remove}): **`O(1)`**\n *   average time complexity\n * - **Iteration**: **`O(n)`** where n is the size of the set\n *\n * The MutableHashSet data structure implements the following traits:\n *\n * - {@link Iterable}: allows iterating over the values in the set\n * - {@link Pipeable}: allows chaining operations with the pipe operator\n * - {@link Inspectable}: allows inspecting the contents of the set\n *\n * ## Operations Reference\n *\n * | Category     | Operation                                  | Description                         | Complexity |\n * | ------------ | ------------------------------------------ | ----------------------------------- | ---------- |\n * | constructors | {@link module:MutableHashSet.empty}        | Creates an empty MutableHashSet     | O(1)       |\n * | constructors | {@link module:MutableHashSet.fromIterable} | Creates a set from an iterable      | O(n)       |\n * | constructors | {@link module:MutableHashSet.make}         | Creates a set from multiple values  | O(n)       |\n * |              |                                            |                                     |            |\n * | elements     | {@link module:MutableHashSet.has}          | Checks if a value exists in the set | O(1) avg   |\n * | elements     | {@link module:MutableHashSet.add}          | Adds a value to the set             | O(1) avg   |\n * | elements     | {@link module:MutableHashSet.remove}       | Removes a value from the set        | O(1) avg   |\n * | elements     | {@link module:MutableHashSet.size}         | Gets the number of elements         | O(1)       |\n * | elements     | {@link module:MutableHashSet.clear}        | Removes all values from the set     | O(1)       |\n *\n * ## Notes\n *\n * ### Mutability Considerations:\n *\n * Unlike most data structures in the Effect ecosystem, `MutableHashSet` is\n * mutable. This means that operations like `add`, `remove`, and `clear` modify\n * the original set rather than creating a new one. This can lead to more\n * efficient code in some scenarios, but requires careful handling to avoid\n * unexpected side effects.\n *\n * ### When to Choose `MutableHashSet` vs {@link module:HashSet}:\n *\n * - Use `MutableHashSet` when you need to build or modify a set incrementally and\n *   performance is a priority\n * - Use `HashSet` when you want immutability guarantees and functional\n *   programming patterns\n * - Consider using {@link module:HashSet}'s bounded mutation context (via\n *   {@link module:HashSet.beginMutation}, {@link module:HashSet.endMutation}, and\n *   {@link module:HashSet.mutate} methods) when you need temporary mutability\n *   within an otherwise immutable context - this approach might be sufficient\n *   for many use cases without requiring a separate `MutableHashSet`\n * - `MutableHashSet` is often useful for local operations where the mutability is\n *   contained and doesn't leak into the broader application\n *\n * @module MutableHashSet\n * @since 2.0.0\n */\nimport * as Dual from \"./Function.js\"\nimport { format, type Inspectable, NodeInspectSymbol, toJSON } from \"./Inspectable.js\"\nimport * as MutableHashMap from \"./MutableHashMap.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\n\nconst TypeId: unique symbol = Symbol.for(\"effect/MutableHashSet\") as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MutableHashSet<out V> extends Iterable<V>, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n\n  /** @internal */\n  readonly keyMap: MutableHashMap.MutableHashMap<V, boolean>\n}\n\nconst MutableHashSetProto: Omit<MutableHashSet<unknown>, \"keyMap\"> = {\n  [TypeId]: TypeId,\n  [Symbol.iterator](this: MutableHashSet<unknown>): Iterator<unknown> {\n    return Array.from(this.keyMap)\n      .map(([_]) => _)[Symbol.iterator]()\n  },\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"MutableHashSet\",\n      values: Array.from(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst fromHashMap = <V>(\n  keyMap: MutableHashMap.MutableHashMap<V, boolean>\n): MutableHashSet<V> => {\n  const set = Object.create(MutableHashSetProto)\n  set.keyMap = keyMap\n  return set\n}\n\n/**\n * Creates an empty mutable hash set.\n *\n * This function initializes and returns an empty `MutableHashSet` instance,\n * which allows for efficient storage and manipulation of unique elements.\n *\n * Time complexity: **`O(1)`**\n *\n * @memberof MutableHashSet\n * @since 2.0.0\n * @category constructors\n * @example\n *\n * ```ts\n * import { MutableHashSet } from \"effect\"\n *\n * type T = unknown // replace with your type\n *\n * // in places where the type can't be inferred, replace with your type\n * const set: MutableHashSet.MutableHashSet<T> = MutableHashSet.empty<T>()\n * ```\n *\n * @template K - The type of the elements to be stored in the hash set. Defaults\n *   to `never` if not specified.\n * @returns A new mutable instance of `MutableHashSet` containing no elements\n *   for the specified type `K`.\n * @see Other `MutableHashSet` constructors are {@link module:MutableHashSet.make} {@link module:MutableHashSet.fromIterable}\n */\nexport const empty = <K = never>(): MutableHashSet<K> => fromHashMap(MutableHashMap.empty())\n\n/**\n * Creates a new `MutableHashSet` from an iterable collection of values.\n * Duplicate values are omitted.\n *\n * Time complexity: **`O(n)`** where n is the number of elements in the iterable\n *\n * Creating a `MutableHashSet` from an {@link Array}\n *\n * ```ts\n * import { MutableHashSet } from \"effect\"\n *\n * const array: Iterable<number> = [1, 2, 3, 4, 5, 1, 2, 3] // Array<T> is also Iterable<T>\n * const mutableHashSet: MutableHashSet.MutableHashSet<number> =\n *   MutableHashSet.fromIterable(array)\n *\n * console.log(\n *   // MutableHashSet.MutableHashSet<T> is also an Iterable<T>\n *   Array.from(mutableHashSet)\n * ) // Output: [1, 2, 3, 4, 5]\n * ```\n *\n * Creating a `MutableHashSet` from a {@link Set}\n *\n * ```ts\n * import { MutableHashSet, pipe } from \"effect\"\n *\n * console.log(\n *   pipe(\n *     // Set<string> is an Iterable<string>\n *     new Set([\"apple\", \"banana\", \"orange\", \"apple\"]),\n *     // constructs MutableHashSet from an Iterable Set\n *     MutableHashSet.fromIterable,\n *     // since MutableHashSet it is itself an Iterable, we can pass it to other functions expecting an Iterable\n *     Array.from\n *   )\n * ) // Output: [\"apple\", \"banana\", \"orange\"]\n * ```\n *\n * Creating a `MutableHashSet` from a {@link Generator}\n *\n * ```ts\n * import { MutableHashSet } from \"effect\"\n *\n * // Generator functions return iterables\n * function* fibonacci(n: number): Generator<number, void, never> {\n *   let [a, b] = [0, 1]\n *   for (let i = 0; i < n; i++) {\n *     yield a\n *     ;[a, b] = [b, a + b]\n *   }\n * }\n *\n * // Create a MutableHashSet from the first 10 Fibonacci numbers\n * const fibonacciSet = MutableHashSet.fromIterable(fibonacci(10))\n *\n * console.log(Array.from(fibonacciSet))\n * // Outputs: [0, 1, 2, 3, 5, 8, 13, 21, 34] but in unsorted order\n * ```\n *\n * Creating a `MutableHashSet` from another {@link module:MutableHashSet}\n *\n * ```ts\n * import { MutableHashSet, pipe } from \"effect\"\n *\n * console.log(\n *   pipe(\n *     MutableHashSet.make(1, 2, 3, 4),\n *     MutableHashSet.fromIterable,\n *     Array.from\n *   )\n * ) // Output: [1, 2, 3, 4]\n * ```\n *\n * Creating a `MutableHashSet` from an {@link module:HashSet}\n *\n * ```ts\n * import { HashSet, MutableHashSet, pipe } from \"effect\"\n *\n * console.log(\n *   pipe(\n *     HashSet.make(1, 2, 3, 4), // it works also with its immutable HashSet sibling\n *     MutableHashSet.fromIterable,\n *     Array.from\n *   )\n * ) // Output: [1, 2, 3, 4]\n * ```\n *\n * Creating a `MutableHashSet` from other Effect's data structures like\n * {@link Chunk}\n *\n * ```ts\n * import { Chunk, MutableHashSet, pipe } from \"effect\"\n *\n * console.log(\n *   pipe(\n *     Chunk.make(1, 2, 3, 4), //  Chunk is also an Iterable<T>\n *     MutableHashSet.fromIterable,\n *     Array.from\n *   )\n * ) // Outputs: [1, 2, 3, 4]\n * ```\n *\n * @memberof MutableHashSet\n * @since 2.0.0\n * @category constructors\n * @template K - The type of elements to be stored in the resulting\n *   `MutableHashSet`.\n * @param keys - An `Iterable` collection containing the keys to be added to the\n *   `MutableHashSet`.\n * @returns A new `MutableHashSet` containing just the unique elements from the\n *   provided iterable.\n * @see Other `MutableHashSet` constructors are {@link module:MutableHashSet.empty} {@link module:MutableHashSet.make}\n */\nexport const fromIterable = <K = never>(keys: Iterable<K>): MutableHashSet<K> =>\n  fromHashMap(\n    MutableHashMap.fromIterable(Array.from(keys).map((k) => [k, true]))\n  )\n\n/**\n * Construct a new `MutableHashSet` from a variable number of values.\n *\n * Time complexity: **`O(n)`** where n is the number of elements\n *\n * @memberof MutableHashSet\n * @since 2.0.0\n * @category constructors\n * @example\n *\n * ```ts\n * import { Equal, Hash, MutableHashSet } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * class Character implements Equal.Equal {\n *   readonly name: string\n *   readonly trait: string\n *\n *   constructor(name: string, trait: string) {\n *     this.name = name\n *     this.trait = trait\n *   }\n *\n *   // Define equality based on name, and trait\n *   [Equal.symbol](that: Equal.Equal): boolean {\n *     if (that instanceof Character) {\n *       return (\n *         Equal.equals(this.name, that.name) &&\n *         Equal.equals(this.trait, that.trait)\n *       )\n *     }\n *     return false\n *   }\n *\n *   // Generate a hash code based on the sum of the character's name and trait\n *   [Hash.symbol](): number {\n *     return Hash.hash(this.name + this.trait)\n *   }\n *\n *   static readonly of = (name: string, trait: string): Character => {\n *     return new Character(name, trait)\n *   }\n * }\n *\n * const mutableCharacterHashSet = MutableHashSet.make(\n *   Character.of(\"Alice\", \"Curious\"),\n *   Character.of(\"Alice\", \"Curious\"),\n *   Character.of(\"White Rabbit\", \"Always late\"),\n *   Character.of(\"Mad Hatter\", \"Tea enthusiast\")\n * )\n *\n * assert.equal(\n *   MutableHashSet.has(\n *     mutableCharacterHashSet,\n *     Character.of(\"Alice\", \"Curious\")\n *   ),\n *   true\n * )\n * assert.equal(\n *   MutableHashSet.has(\n *     mutableCharacterHashSet,\n *     Character.of(\"Fluffy\", \"Kind\")\n *   ),\n *   false\n * )\n * ```\n *\n * @see Other `MutableHashSet` constructors are {@link module:MutableHashSet.fromIterable} {@link module:MutableHashSet.empty}\n */\nexport const make = <Keys extends ReadonlyArray<unknown>>(\n  ...keys: Keys\n): MutableHashSet<Keys[number]> => fromIterable(keys)\n\n/**\n * **Checks** whether the `MutableHashSet` contains the given element, and\n * **adds** it if not.\n *\n * Time complexity: **`O(1)`** average\n *\n * **Syntax**\n *\n * ```ts\n * import { MutableHashSet, pipe } from \"effect\"\n *\n * // with data-last, a.k.a. pipeable API\n * pipe(\n *   MutableHashSet.empty(),\n *   MutableHashSet.add(0),\n *   MutableHashSet.add(0)\n * )\n *\n * // or piped with the pipe function\n * MutableHashSet.empty().pipe(MutableHashSet.add(0))\n *\n * // or with data-first API\n * MutableHashSet.add(MutableHashSet.empty(), 0)\n * ```\n *\n * @memberof MutableHashSet\n * @since 2.0.0\n * @category elements\n * @see Other `MutableHashSet` elements are {@link module:MutableHashSet.remove} {@link module:MutableHashSet.size} {@link module:MutableHashSet.clear} {@link module:MutableHashSet.has}\n */\nexport const add: {\n  /**\n   * `data-last` a.k.a. `pipeable` API\n   *\n   * ```ts\n   * import { MutableHashSet, pipe } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * const mutableHashSet = pipe(\n   *   MutableHashSet.empty<number>(), // MutableHashSet.MutableHashSet<number>\n   *   MutableHashSet.add(0),\n   *   MutableHashSet.add(1),\n   *   MutableHashSet.add(1),\n   *   MutableHashSet.add(2)\n   * )\n   *\n   * assert.deepStrictEqual(\n   *   Array.from(mutableHashSet), // remember that MutableHashSet is also an Iterable\n   *   Array.of(0, 1, 2)\n   * )\n   * ```\n   *\n   * @template V - The type of elements stored in the `MutableHashSet`.\n   * @param key - The key to be added to the `MutableHashSet` if not already\n   *   present.\n   * @returns A function that accepts a `MutableHashSet` and returns the\n   *   reference of the updated `MutableHashSet` including the key.\n   */\n  <V>(key: V): (self: MutableHashSet<V>) => MutableHashSet<V>\n\n  /**\n   * `data-first` API\n   *\n   * ```ts\n   * import { MutableHashSet } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * const empty = MutableHashSet.empty<number>()\n   * const withZero = MutableHashSet.add(empty, 0)\n   * const withOne = MutableHashSet.add(withZero, 1)\n   * const withTwo = MutableHashSet.add(withOne, 2)\n   * const withTwoTwo = MutableHashSet.add(withTwo, 2)\n   *\n   * assert(Object.is(withTwoTwo, empty)) // proof that it does mutate the original set\n   *\n   * assert.deepStrictEqual(\n   *   Array.from(withTwoTwo), // remember that MutableHashSet is also an Iterable\n   *   Array.of(0, 1, 2)\n   * )\n   * ```\n   *\n   * @template V - The type of elements stored in the `MutableHashSet`.\n   * @param self - The `MutableHashSet` instance from which the key should be\n   *   added to.\n   * @param key - The key to be added to the `MutableHashSet` if not already\n   *   present.\n   * @returns The reference of the updated `MutableHashSet` including the key.\n   */\n  <V>(self: MutableHashSet<V>, key: V): MutableHashSet<V>\n} = Dual.dual<\n  <V>(key: V) => (self: MutableHashSet<V>) => MutableHashSet<V>,\n  <V>(self: MutableHashSet<V>, key: V) => MutableHashSet<V>\n>(2, (self, key) => (MutableHashMap.set(self.keyMap, key, true), self))\n\n/**\n * Checks if the specified value exists in the `MutableHashSet`.\n *\n * Time complexity: `O(1)` average\n *\n * **Syntax**\n *\n * ```ts\n * import { MutableHashSet, pipe } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * assert.equal(\n *   // with `data-last`, a.k.a. `pipeable` API\n *   pipe(MutableHashSet.make(0, 1, 2), MutableHashSet.has(3)),\n *   false\n * )\n *\n * assert.equal(\n *   // or piped with the pipe function\n *   MutableHashSet.make(0, 1, 2).pipe(MutableHashSet.has(3)),\n *   false\n * )\n *\n * assert.equal(\n *   // or with `data-first` API\n *   MutableHashSet.has(MutableHashSet.make(0, 1, 2), 3),\n *   false\n * )\n * ```\n *\n * @memberof MutableHashSet\n * @since 2.0.0\n * @category elements\n * @see Other `MutableHashSet` elements are {@link module:MutableHashSet.add} {@link module:MutableHashSet.remove} {@link module:MutableHashSet.size} {@link module:MutableHashSet.clear}\n */\nexport const has: {\n  /**\n   * `data-last` a.k.a. `pipeable` API\n   *\n   * ```ts\n   * import * as assert from \"node:assert/strict\"\n   * import { MutableHashSet, pipe } from \"effect\"\n   *\n   * const set = MutableHashSet.make(0, 1, 2)\n   *\n   * assert.equal(pipe(set, MutableHashSet.has(0)), true)\n   * assert.equal(pipe(set, MutableHashSet.has(1)), true)\n   * assert.equal(pipe(set, MutableHashSet.has(2)), true)\n   * assert.equal(pipe(set, MutableHashSet.has(3)), false)\n   * ```\n   */\n  <V>(key: V): (self: MutableHashSet<V>) => boolean\n\n  /**\n   * `data-first` API\n   *\n   * ```ts\n   * import * as assert from \"node:assert/strict\"\n   * import { MutableHashSet, pipe } from \"effect\"\n   *\n   * const set = MutableHashSet.make(0, 1, 2)\n   *\n   * assert.equal(MutableHashSet.has(set, 0), true)\n   * assert.equal(MutableHashSet.has(set, 1), true)\n   * assert.equal(MutableHashSet.has(set, 2), true)\n   * assert.equal(MutableHashSet.has(set, 3), false)\n   * ```\n   */\n  <V>(self: MutableHashSet<V>, key: V): boolean\n} = Dual.dual<\n  <V>(key: V) => (self: MutableHashSet<V>) => boolean,\n  <V>(self: MutableHashSet<V>, key: V) => boolean\n>(2, (self, key) => MutableHashMap.has(self.keyMap, key))\n\n/**\n * Removes a value from the `MutableHashSet`.\n *\n * Time complexity: **`O(1)`** average\n *\n * **Syntax**\n *\n * ```ts\n * import { MutableHashSet, pipe } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * assert.equal(\n *   // with `data-last`, a.k.a. `pipeable` API\n *   pipe(\n *     MutableHashSet.make(0, 1, 2),\n *     MutableHashSet.remove(0),\n *     MutableHashSet.has(0)\n *   ),\n *   false\n * )\n *\n * assert.equal(\n *   // or piped with the pipe function\n *   MutableHashSet.make(0, 1, 2).pipe(\n *     MutableHashSet.remove(0),\n *     MutableHashSet.has(0)\n *   ),\n *   false\n * )\n *\n * assert.equal(\n *   // or with `data-first` API\n *   MutableHashSet.remove(MutableHashSet.make(0, 1, 2), 0).pipe(\n *     MutableHashSet.has(0)\n *   ),\n *   false\n * )\n * ```\n *\n * @memberof MutableHashSet\n * @since 2.0.0\n * @category elements\n * @see Other `MutableHashSet` elements are {@link module:MutableHashSet.add} {@link module:MutableHashSet.has} {@link module:MutableHashSet.size} {@link module:MutableHashSet.clear}\n */\nexport const remove: {\n  /**\n   * `data-last` a.k.a. `pipeable` API\n   *\n   * ```ts\n   * import { MutableHashSet, pipe } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * const set: MutableHashSet.MutableHashSet<number> = MutableHashSet.make(\n   *   0,\n   *   1,\n   *   2\n   * )\n   * const result: MutableHashSet.MutableHashSet<number> = pipe(\n   *   set,\n   *   MutableHashSet.remove(0)\n   * )\n   *\n   * assert(Object.is(set, result)) // set and result have the same identity\n   * assert.equal(pipe(result, MutableHashSet.has(0)), false) // it has correctly removed 0\n   * assert.equal(pipe(set, MutableHashSet.has(0)), false) // another proof that we are mutating the original MutableHashSet\n   * assert.equal(pipe(result, MutableHashSet.has(1)), true)\n   * assert.equal(pipe(result, MutableHashSet.has(2)), true)\n   * ```\n   *\n   * @template V - The type of the elements in the `MutableHashSet`.\n   * @param key - The key to be removed from the `MutableHashSet`.\n   * @returns A function that takes a `MutableHashSet` as input and returns the\n   *   reference to the same `MutableHashSet` with the specified key removed.\n   */\n  <V>(key: V): (self: MutableHashSet<V>) => MutableHashSet<V>\n\n  /**\n   * `data-first` API\n   *\n   * ```ts\n   * import { MutableHashSet, pipe } from \"effect\"\n   * import assert from \"node:assert/strict\"\n   *\n   * const set = MutableHashSet.make(0, 1, 2)\n   * const result = MutableHashSet.remove(set, 0)\n   *\n   * assert(Object.is(set, result)) // set and result have the same identity\n   * assert.equal(MutableHashSet.has(result, 0), false) // it has correctly removed 0\n   * assert.equal(MutableHashSet.has(set, 0), false) // it mutates the original MutableHashSet\n   * assert.equal(MutableHashSet.has(result, 1), true)\n   * assert.equal(MutableHashSet.has(result, 2), true)\n   * ```\n   *\n   * @template V - The type of the elements in the `MutableHashSet`.\n   * @param self - The `MutableHashSet` to which the key will be removed from.\n   * @param key - The value to be removed from the `MutableHashSet` if present.\n   * @returns The reference to the updated `MutableHashSet`.\n   */\n  <V>(self: MutableHashSet<V>, key: V): MutableHashSet<V>\n} = Dual.dual<\n  <V>(key: V) => (self: MutableHashSet<V>) => MutableHashSet<V>,\n  <V>(self: MutableHashSet<V>, key: V) => MutableHashSet<V>\n>(2, (self, key) => (MutableHashMap.remove(self.keyMap, key), self))\n\n/**\n * Calculates the number of values in the `HashSet`.\n *\n * Time complexity: **`O(1)`**\n *\n * @memberof MutableHashSet\n * @since 2.0.0\n * @category elements\n * @example\n *\n * ```ts\n * import { MutableHashSet } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * assert.equal(MutableHashSet.size(MutableHashSet.empty()), 0)\n *\n * assert.equal(\n *   MutableHashSet.size(MutableHashSet.make(1, 2, 2, 3, 4, 3)),\n *   4\n * )\n * ```\n *\n * @template V - The type of the elements to be stored in the `MutableHashSet`.\n * @param self - The `MutableHashSet` instance for which the size is to be\n *   determined.\n * @returns The total number of elements within the `MutableHashSet`.\n * @see Other `MutableHashSet` elements are {@link module:MutableHashSet.add} {@link module:MutableHashSet.has} {@link module:MutableHashSet.remove} {@link module:MutableHashSet.clear}\n */\nexport const size = <V>(self: MutableHashSet<V>): number => MutableHashMap.size(self.keyMap)\n\n/**\n * Removes all values from the `MutableHashSet`.\n *\n * This function operates by delegating the clearing action to the underlying\n * key map associated with the given `MutableHashSet`. It ensures that the hash\n * set becomes empty while maintaining its existence and structure.\n *\n * @memberof MutableHashSet\n * @since 2.0.0\n * @category elements\n * @example\n *\n * ```ts\n * import { MutableHashSet, pipe } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * assert.deepStrictEqual(\n *   pipe(\n *     MutableHashSet.make(1, 2, 3, 4),\n *     MutableHashSet.clear,\n *     MutableHashSet.size\n *   ),\n *   0\n * )\n * ```\n *\n * @param self - The `MutableHashSet` to clear.\n * @returns The same `MutableHashSet` after all elements have been removed.\n * @see Other `MutableHashSet` elements are {@link module:MutableHashSet.add} {@link module:MutableHashSet.has} {@link module:MutableHashSet.remove} {@link module:MutableHashSet.size}\n */\nexport const clear = <V>(self: MutableHashSet<V>): MutableHashSet<V> => (\n  MutableHashMap.clear(self.keyMap), self\n)\n"
  },
  {
    "path": "packages/effect/src/MutableList.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Dual from \"./Function.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"./Inspectable.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\n\nconst TypeId: unique symbol = Symbol.for(\"effect/MutableList\") as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface MutableList<out A> extends Iterable<A>, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n\n  /** @internal */\n  head: LinkedListNode<A> | undefined\n  /** @internal */\n  tail: LinkedListNode<A> | undefined\n}\n\nconst MutableListProto: Omit<MutableList<unknown>, \"head\" | \"tail\"> = {\n  [TypeId]: TypeId,\n  [Symbol.iterator](this: MutableList<unknown>): Iterator<unknown> {\n    let done = false\n    let head: LinkedListNode<unknown> | undefined = this.head\n    return {\n      next() {\n        if (done) {\n          return this.return!()\n        }\n        if (head == null) {\n          done = true\n          return this.return!()\n        }\n        const value = head.value\n        head = head.next\n        return { done, value }\n      },\n      return(value?: unknown) {\n        if (!done) {\n          done = true\n        }\n        return { done: true, value }\n      }\n    }\n  },\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"MutableList\",\n      values: Array.from(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\ninterface MutableListImpl<A> extends MutableList<A> {\n  _length: number\n}\n\n/** @internal */\ninterface LinkedListNode<T> {\n  removed: boolean\n  value: T\n  prev: LinkedListNode<T> | undefined\n  next: LinkedListNode<T> | undefined\n}\n\n/** @internal */\nconst makeNode = <T>(value: T): LinkedListNode<T> => ({\n  value,\n  removed: false,\n  prev: undefined,\n  next: undefined\n})\n\n/**\n * Creates an empty `MutableList`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty = <A = never>(): MutableList<A> => {\n  const list = Object.create(MutableListProto)\n  list.head = undefined\n  list.tail = undefined\n  list._length = 0\n  return list\n}\n\n/**\n * Creates a new `MutableList` from an iterable collection of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable = <A>(iterable: Iterable<A>): MutableList<A> => {\n  const list = empty<A>()\n  for (const element of iterable) {\n    append(list, element)\n  }\n  return list\n}\n\n/**\n * Creates a new `MutableList` from the specified elements.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make = <A>(...elements: ReadonlyArray<A>): MutableList<A> => fromIterable(elements)\n\n/**\n * Returns `true` if the list contains zero elements, `false`, otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isEmpty = <A>(self: MutableList<A>): boolean => length(self) === 0\n\n/**\n * Returns the length of the list.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const length = <A>(self: MutableList<A>): number => (self as MutableListImpl<A>)._length\n\n/**\n * Returns the last element of the list, if it exists.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const tail = <A>(self: MutableList<A>): A | undefined => self.tail === undefined ? undefined : self.tail.value\n\n/**\n * Returns the first element of the list, if it exists.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const head = <A>(self: MutableList<A>): A | undefined => self.head === undefined ? undefined : self.head.value\n\n/**\n * Executes the specified function `f` for each element in the list.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const forEach: {\n  <A>(f: (element: A) => void): (self: MutableList<A>) => void\n  <A>(self: MutableList<A>, f: (element: A) => void): void\n} = Dual.dual<\n  <A>(f: (element: A) => void) => (self: MutableList<A>) => void,\n  <A>(self: MutableList<A>, f: (element: A) => void) => void\n>(2, (self, f) => {\n  let current = self.head\n  while (current !== undefined) {\n    f(current.value)\n    current = current.next\n  }\n})\n\n/**\n * Removes all elements from the doubly-linked list.\n *\n * @since 2.0.0\n */\nexport const reset = <A>(self: MutableList<A>): MutableList<A> => {\n  ;(self as MutableListImpl<A>)._length = 0\n  self.head = undefined\n  self.tail = undefined\n  return self\n}\n\n/**\n * Appends the specified element to the end of the `MutableList`.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const append: {\n  <A>(value: A): (self: MutableList<A>) => MutableList<A>\n  <A>(self: MutableList<A>, value: A): MutableList<A>\n} = Dual.dual<\n  <A>(value: A) => (self: MutableList<A>) => MutableList<A>,\n  <A>(self: MutableList<A>, value: A) => MutableList<A>\n>(2, <A>(self: MutableList<A>, value: A) => {\n  const node = makeNode(value)\n  if (self.head === undefined) {\n    self.head = node\n  }\n  if (self.tail === undefined) {\n    self.tail = node\n  } else {\n    self.tail.next = node\n    node.prev = self.tail\n    self.tail = node\n  }\n  ;(self as MutableListImpl<A>)._length += 1\n  return self\n})\n\n/**\n * Removes the first value from the list and returns it, if it exists.\n *\n * @since 0.0.1\n */\nexport const shift = <A>(self: MutableList<A>): A | undefined => {\n  const head = self.head\n  if (head !== undefined) {\n    remove(self, head)\n    return head.value\n  }\n  return undefined\n}\n\n/**\n * Removes the last value from the list and returns it, if it exists.\n *\n * @since 0.0.1\n */\nexport const pop = <A>(self: MutableList<A>): A | undefined => {\n  const tail = self.tail\n  if (tail !== undefined) {\n    remove(self, tail)\n    return tail.value\n  }\n  return undefined\n}\n\n/**\n * Prepends the specified value to the beginning of the list.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const prepend: {\n  <A>(value: A): (self: MutableList<A>) => MutableList<A>\n  <A>(self: MutableList<A>, value: A): MutableList<A>\n} = Dual.dual<\n  <A>(value: A) => (self: MutableList<A>) => MutableList<A>,\n  <A>(self: MutableList<A>, value: A) => MutableList<A>\n>(2, <A>(self: MutableList<A>, value: A) => {\n  const node = makeNode(value)\n  node.next = self.head\n  if (self.head !== undefined) {\n    self.head.prev = node\n  }\n  self.head = node\n  if (self.tail === undefined) {\n    self.tail = node\n  }\n  ;(self as MutableListImpl<A>)._length += 1\n  return self\n})\n\nconst remove = <A>(self: MutableList<A>, node: LinkedListNode<A>): void => {\n  if (node.removed) {\n    return\n  }\n  node.removed = true\n  if (node.prev !== undefined && node.next !== undefined) {\n    node.prev.next = node.next\n    node.next.prev = node.prev\n  } else if (node.prev !== undefined) {\n    self.tail = node.prev\n    node.prev.next = undefined\n  } else if (node.next !== undefined) {\n    self.head = node.next\n    node.next.prev = undefined\n  } else {\n    self.tail = undefined\n    self.head = undefined\n  }\n  if ((self as MutableListImpl<A>)._length > 0) {\n    ;(self as MutableListImpl<A>)._length -= 1\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/MutableQueue.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Chunk from \"./Chunk.js\"\nimport * as Dual from \"./Function.js\"\nimport { format, type Inspectable, NodeInspectSymbol, toJSON } from \"./Inspectable.js\"\nimport * as MutableList from \"./MutableList.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\n\nconst TypeId: unique symbol = Symbol.for(\"effect/MutableQueue\") as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport const EmptyMutableQueue = Symbol.for(\"effect/mutable/MutableQueue/Empty\")\n\n/**\n * @since 2.0.0\n * @category model\n */\nexport interface MutableQueue<out A> extends Iterable<A>, Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n\n  /** @internal */\n  queue: MutableList.MutableList<A>\n  /** @internal */\n  capacity: number | undefined\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace MutableQueue {\n  /**\n   * @since 2.0.0\n   */\n  export type Empty = typeof EmptyMutableQueue\n}\n\nconst MutableQueueProto: Omit<MutableQueue<unknown>, \"queue\" | \"capacity\"> = {\n  [TypeId]: TypeId,\n  [Symbol.iterator]<A>(this: MutableQueue<A>): Iterator<A> {\n    return Array.from(this.queue)[Symbol.iterator]()\n  },\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"MutableQueue\",\n      values: Array.from(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst make = <A>(capacity: number | undefined): MutableQueue<A> => {\n  const queue = Object.create(MutableQueueProto)\n  queue.queue = MutableList.empty()\n  queue.capacity = capacity\n  return queue\n}\n\n/**\n * Creates a new bounded `MutableQueue`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const bounded = <A>(capacity: number): MutableQueue<A> => make(capacity)\n\n/**\n * Creates a new unbounded `MutableQueue`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unbounded = <A>(): MutableQueue<A> => make(undefined)\n\n/**\n * Returns the current number of elements in the queue.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const length = <A>(self: MutableQueue<A>): number => MutableList.length(self.queue)\n\n/**\n * Returns `true` if the queue is empty, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isEmpty = <A>(self: MutableQueue<A>): boolean => MutableList.isEmpty(self.queue)\n\n/**\n * Returns `true` if the queue is full, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isFull = <A>(self: MutableQueue<A>): boolean =>\n  self.capacity === undefined ? false : MutableList.length(self.queue) === self.capacity\n\n/**\n * The **maximum** number of elements that a queue can hold.\n *\n * **Note**: unbounded queues can still implement this interface with\n * `capacity = Infinity`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const capacity = <A>(self: MutableQueue<A>): number => self.capacity === undefined ? Infinity : self.capacity\n\n/**\n * Offers an element to the queue.\n *\n * Returns whether the enqueue was successful or not.\n *\n * @since 2.0.0\n */\nexport const offer: {\n  <A>(self: MutableQueue<A>, value: A): boolean\n  <A>(value: A): (self: MutableQueue<A>) => boolean\n} = Dual.dual<\n  <A>(value: A) => (self: MutableQueue<A>) => boolean,\n  <A>(self: MutableQueue<A>, value: A) => boolean\n>(2, <A>(self: MutableQueue<A>, value: A) => {\n  const queueLength = MutableList.length(self.queue)\n  if (self.capacity !== undefined && queueLength === self.capacity) {\n    return false\n  }\n  MutableList.append(value)(self.queue)\n  return true\n})\n\n/**\n * Enqueues a collection of values into the queue.\n *\n * Returns a `Chunk` of the values that were **not** able to be enqueued.\n *\n * @since 2.0.0\n */\nexport const offerAll: {\n  <A>(values: Iterable<A>): (self: MutableQueue<A>) => Chunk.Chunk<A>\n  <A>(self: MutableQueue<A>, values: Iterable<A>): Chunk.Chunk<A>\n} = Dual.dual<\n  <A>(values: Iterable<A>) => (self: MutableQueue<A>) => Chunk.Chunk<A>,\n  <A>(self: MutableQueue<A>, values: Iterable<A>) => Chunk.Chunk<A>\n>(2, <A>(self: MutableQueue<A>, values: Iterable<A>) => {\n  const iterator = values[Symbol.iterator]()\n  let next: IteratorResult<A> | undefined\n  let remainder = Chunk.empty<A>()\n  let offering = true\n  while (offering && (next = iterator.next()) && !next.done) {\n    offering = offer(next.value)(self)\n  }\n  while (next != null && !next.done) {\n    remainder = Chunk.prepend<A>(next.value)(remainder)\n    next = iterator.next()\n  }\n  return Chunk.reverse(remainder)\n})\n\n/**\n * Dequeues an element from the queue.\n *\n * Returns either an element from the queue, or the `def` param.\n *\n * **Note**: if there is no meaningful default for your type, you can always\n * use `poll(MutableQueue.EmptyMutableQueue)`.\n *\n * @since 2.0.0\n */\nexport const poll: {\n  <D>(def: D): <A>(self: MutableQueue<A>) => D | A\n  <A, D>(self: MutableQueue<A>, def: D): A | D\n} = Dual.dual<\n  <D>(def: D) => <A>(self: MutableQueue<A>) => A | D,\n  <A, D>(self: MutableQueue<A>, def: D) => A | D\n>(2, (self, def) => {\n  if (MutableList.isEmpty(self.queue)) {\n    return def\n  }\n  return MutableList.shift(self.queue)!\n})\n\n/**\n * Dequeues up to `n` elements from the queue.\n *\n * Returns a `List` of up to `n` elements.\n *\n * @since 2.0.0\n */\nexport const pollUpTo: {\n  (n: number): <A>(self: MutableQueue<A>) => Chunk.Chunk<A>\n  <A>(self: MutableQueue<A>, n: number): Chunk.Chunk<A>\n} = Dual.dual<\n  (n: number) => <A>(self: MutableQueue<A>) => Chunk.Chunk<A>,\n  <A>(self: MutableQueue<A>, n: number) => Chunk.Chunk<A>\n>(2, <A>(self: MutableQueue<A>, n: number) => {\n  let result = Chunk.empty<A>()\n  let count = 0\n  while (count < n) {\n    const element = poll(EmptyMutableQueue)(self)\n    if (element === EmptyMutableQueue) {\n      break\n    }\n    result = Chunk.prepend(element)(result)\n    count += 1\n  }\n  return Chunk.reverse(result)\n})\n"
  },
  {
    "path": "packages/effect/src/MutableRef.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\"\nimport * as Dual from \"./Function.js\"\nimport { format, type Inspectable, NodeInspectSymbol, toJSON } from \"./Inspectable.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\n\nconst TypeId: unique symbol = Symbol.for(\"effect/MutableRef\") as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface MutableRef<out T> extends Pipeable, Inspectable {\n  readonly [TypeId]: TypeId\n  current: T\n}\n\nconst MutableRefProto: Omit<MutableRef<unknown>, \"current\"> = {\n  [TypeId]: TypeId,\n  toString<A>(this: MutableRef<A>): string {\n    return format(this.toJSON())\n  },\n  toJSON<A>(this: MutableRef<A>) {\n    return {\n      _id: \"MutableRef\",\n      current: toJSON(this.current)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make = <T>(value: T): MutableRef<T> => {\n  const ref = Object.create(MutableRefProto)\n  ref.current = value\n  return ref\n}\n\n/**\n * @since 2.0.0\n * @category general\n */\nexport const compareAndSet: {\n  <T>(oldValue: T, newValue: T): (self: MutableRef<T>) => boolean\n  <T>(self: MutableRef<T>, oldValue: T, newValue: T): boolean\n} = Dual.dual<\n  <T>(oldValue: T, newValue: T) => (self: MutableRef<T>) => boolean,\n  <T>(self: MutableRef<T>, oldValue: T, newValue: T) => boolean\n>(3, (self, oldValue, newValue) => {\n  if (Equal.equals(oldValue, self.current)) {\n    self.current = newValue\n    return true\n  }\n  return false\n})\n\n/**\n * @since 2.0.0\n * @category numeric\n */\nexport const decrement = (self: MutableRef<number>): MutableRef<number> => update(self, (n) => n - 1)\n\n/**\n * @since 2.0.0\n * @category numeric\n */\nexport const decrementAndGet = (self: MutableRef<number>): number => updateAndGet(self, (n) => n - 1)\n\n/**\n * @since 2.0.0\n * @category general\n */\nexport const get = <T>(self: MutableRef<T>): T => self.current\n\n/**\n * @since 2.0.0\n * @category numeric\n */\nexport const getAndDecrement = (self: MutableRef<number>): number => getAndUpdate(self, (n) => n - 1)\n\n/**\n * @since 2.0.0\n * @category numeric\n */\nexport const getAndIncrement = (self: MutableRef<number>): number => getAndUpdate(self, (n) => n + 1)\n\n/**\n * @since 2.0.0\n * @category general\n */\nexport const getAndSet: {\n  <T>(value: T): (self: MutableRef<T>) => T\n  <T>(self: MutableRef<T>, value: T): T\n} = Dual.dual<\n  <T>(value: T) => (self: MutableRef<T>) => T,\n  <T>(self: MutableRef<T>, value: T) => T\n>(2, (self, value) => {\n  const ret = self.current\n  self.current = value\n  return ret\n})\n\n/**\n * @since 2.0.0\n * @category general\n */\nexport const getAndUpdate: {\n  <T>(f: (value: T) => T): (self: MutableRef<T>) => T\n  <T>(self: MutableRef<T>, f: (value: T) => T): T\n} = Dual.dual<\n  <T>(f: (value: T) => T) => (self: MutableRef<T>) => T,\n  <T>(self: MutableRef<T>, f: (value: T) => T) => T\n>(2, (self, f) => getAndSet(self, f(get(self))))\n\n/**\n * @since 2.0.0\n * @category numeric\n */\nexport const increment = (self: MutableRef<number>): MutableRef<number> => update(self, (n) => n + 1)\n\n/**\n * @since 2.0.0\n * @category numeric\n */\nexport const incrementAndGet = (self: MutableRef<number>): number => updateAndGet(self, (n) => n + 1)\n\n/**\n * @since 2.0.0\n * @category general\n */\nexport const set: {\n  <T>(value: T): (self: MutableRef<T>) => MutableRef<T>\n  <T>(self: MutableRef<T>, value: T): MutableRef<T>\n} = Dual.dual<\n  <T>(value: T) => (self: MutableRef<T>) => MutableRef<T>,\n  <T>(self: MutableRef<T>, value: T) => MutableRef<T>\n>(2, (self, value) => {\n  self.current = value\n  return self\n})\n\n/**\n * @since 2.0.0\n * @category general\n */\nexport const setAndGet: {\n  <T>(value: T): (self: MutableRef<T>) => T\n  <T>(self: MutableRef<T>, value: T): T\n} = Dual.dual<\n  <T>(value: T) => (self: MutableRef<T>) => T,\n  <T>(self: MutableRef<T>, value: T) => T\n>(2, (self, value) => {\n  self.current = value\n  return self.current\n})\n\n/**\n * @since 2.0.0\n * @category general\n */\nexport const update: {\n  <T>(f: (value: T) => T): (self: MutableRef<T>) => MutableRef<T>\n  <T>(self: MutableRef<T>, f: (value: T) => T): MutableRef<T>\n} = Dual.dual<\n  <T>(f: (value: T) => T) => (self: MutableRef<T>) => MutableRef<T>,\n  <T>(self: MutableRef<T>, f: (value: T) => T) => MutableRef<T>\n>(2, (self, f) => set(self, f(get(self))))\n\n/**\n * @since 2.0.0\n * @category general\n */\nexport const updateAndGet: {\n  <T>(f: (value: T) => T): (self: MutableRef<T>) => T\n  <T>(self: MutableRef<T>, f: (value: T) => T): T\n} = Dual.dual<\n  <T>(f: (value: T) => T) => (self: MutableRef<T>) => T,\n  <T>(self: MutableRef<T>, f: (value: T) => T) => T\n>(2, (self, f) => setAndGet(self, f(get(self))))\n\n/**\n * @since 2.0.0\n * @category boolean\n */\nexport const toggle = (self: MutableRef<boolean>): MutableRef<boolean> => update(self, (_) => !_)\n"
  },
  {
    "path": "packages/effect/src/NonEmptyIterable.ts",
    "content": "/**\n * @since 2.0.0\n */\n\n/**\n * @category symbol\n * @since 2.0.0\n */\nexport declare const nonEmpty: unique symbol\n\n/**\n * @category model\n * @since 2.0.0\n */\nexport interface NonEmptyIterable<out A> extends Iterable<A> {\n  readonly [nonEmpty]: A\n}\n\n/**\n * @category getters\n * @since 2.0.0\n */\nexport const unprepend = <A>(self: NonEmptyIterable<A>): [firstElement: A, remainingElements: Iterator<A>] => {\n  const iterator = self[Symbol.iterator]()\n  const next = iterator.next()\n  if (next.done) {\n    throw new Error(\n      \"BUG: NonEmptyIterator should not be empty - please report an issue at https://github.com/Effect-TS/effect/issues\"\n    )\n  }\n  return [next.value, iterator]\n}\n"
  },
  {
    "path": "packages/effect/src/Number.ts",
    "content": "/**\n * # Number\n *\n * This module provides utility functions and type class instances for working\n * with the `number` type in TypeScript. It includes functions for basic\n * arithmetic operations, as well as type class instances for `Equivalence` and\n * `Order`.\n *\n * ## Operations Reference\n *\n * | Category     | Operation                                  | Description                                             | Domain                         | Co-domain             |\n * | ------------ | ------------------------------------------ | ------------------------------------------------------- | ------------------------------ | --------------------- |\n * | constructors | {@link module:Number.parse}                | Safely parses a string to a number                      | `string`                       | `Option<number>`      |\n * |              |                                            |                                                         |                                |                       |\n * | math         | {@link module:Number.sum}                  | Adds two numbers                                        | `number`, `number`             | `number`              |\n * | math         | {@link module:Number.sumAll}               | Sums all numbers in a collection                        | `Iterable<number>`             | `number`              |\n * | math         | {@link module:Number.subtract}             | Subtracts one number from another                       | `number`, `number`             | `number`              |\n * | math         | {@link module:Number.multiply}             | Multiplies two numbers                                  | `number`, `number`             | `number`              |\n * | math         | {@link module:Number.multiplyAll}          | Multiplies all numbers in a collection                  | `Iterable<number>`             | `number`              |\n * | math         | {@link module:Number.divide}               | Safely divides handling division by zero                | `number`, `number`             | `Option<number>`      |\n * | math         | {@link module:Number.unsafeDivide}         | Divides but misbehaves for division by zero             | `number`, `number`             | `number`              |\n * | math         | {@link module:Number.remainder}            | Calculates remainder of division                        | `number`, `number`             | `number`              |\n * | math         | {@link module:Number.increment}            | Adds 1 to a number                                      | `number`                       | `number`              |\n * | math         | {@link module:Number.decrement}            | Subtracts 1 from a number                               | `number`                       | `number`              |\n * | math         | {@link module:Number.sign}                 | Determines the sign of a number                         | `number`                       | `Ordering`            |\n * | math         | {@link module:Number.nextPow2}             | Finds the next power of 2                               | `number`                       | `number`              |\n * | math         | {@link module:Number.round}                | Rounds a number with specified precision                | `number`, `number`             | `number`              |\n * |              |                                            |                                                         |                                |                       |\n * | predicates   | {@link module:Number.between}              | Checks if a number is in a range                        | `number`, `{minimum, maximum}` | `boolean`             |\n * | predicates   | {@link module:Number.lessThan}             | Checks if one number is less than another               | `number`, `number`             | `boolean`             |\n * | predicates   | {@link module:Number.lessThanOrEqualTo}    | Checks if one number is less than or equal              | `number`, `number`             | `boolean`             |\n * | predicates   | {@link module:Number.greaterThan}          | Checks if one number is greater than another            | `number`, `number`             | `boolean`             |\n * | predicates   | {@link module:Number.greaterThanOrEqualTo} | Checks if one number is greater or equal                | `number`, `number`             | `boolean`             |\n * |              |                                            |                                                         |                                |                       |\n * | guards       | {@link module:Number.isNumber}             | Type guard for JavaScript numbers                       | `unknown`                      | `boolean`             |\n * |              |                                            |                                                         |                                |                       |\n * | comparison   | {@link module:Number.min}                  | Returns the minimum of two numbers                      | `number`, `number`             | `number`              |\n * | comparison   | {@link module:Number.max}                  | Returns the maximum of two numbers                      | `number`, `number`             | `number`              |\n * | comparison   | {@link module:Number.clamp}                | Restricts a number to a range                           | `number`, `{minimum, maximum}` | `number`              |\n * |              |                                            |                                                         |                                |                       |\n * | instances    | {@link module:Number.Equivalence}          | Equivalence instance for numbers                        |                                | `Equivalence<number>` |\n * | instances    | {@link module:Number.Order}                | Order instance for numbers                              |                                | `Order<number>`       |\n * |              |                                            |                                                         |                                |                       |\n * | errors       | {@link module:Number.DivisionByZeroError}  | Error thrown by unsafeDivide                            |                                |                       |\n *\n * ## Composition Patterns and Type Safety\n *\n * When building function pipelines, understanding how types flow through\n * operations is critical:\n *\n * ### Composing with type-preserving operations\n *\n * Most operations in this module are type-preserving (`number → number`),\n * making them easily composable in pipelines:\n *\n * ```ts\n * import { pipe } from \"effect\"\n * import * as Number from \"effect/Number\"\n *\n * const result = pipe(\n *   10,\n *   Number.increment, // number → number\n *   Number.multiply(2), // number → number\n *   Number.round(1) // number → number\n * ) // Result: number (21)\n * ```\n *\n * ### Working with Option results\n *\n * Operations that might fail (like division by zero) return Option types and\n * require Option combinators:\n *\n * ```ts\n * import { pipe, Option } from \"effect\"\n * import * as Number from \"effect/Number\"\n *\n * const result = pipe(\n *   10,\n *   Number.divide(0), // number → Option<number>\n *   Option.getOrElse(() => 0) // Option<number> → number\n * ) // Result: number (0)\n * ```\n *\n * ### Composition best practices\n *\n * - Chain type-preserving operations for maximum composability\n * - Use Option combinators when working with potentially failing operations\n * - Consider using Effect for operations that might fail with specific errors\n * - Remember that all operations maintain JavaScript's floating-point precision\n *   limitations\n *\n * @module Number\n * @since 2.0.0\n * @see {@link module:BigInt} for more similar operations on `bigint` types\n * @see {@link module:BigDecimal} for more similar operations on `BigDecimal` types\n */\n\nimport * as equivalence from \"./Equivalence.js\"\nimport { dual } from \"./Function.js\"\nimport * as option from \"./internal/option.js\"\nimport * as _Iterable from \"./Iterable.js\"\nimport type { Option } from \"./Option.js\"\nimport * as order from \"./Order.js\"\nimport type { Ordering } from \"./Ordering.js\"\nimport * as predicate from \"./Predicate.js\"\n\n/**\n * Type guard that tests if a value is a member of the set of JavaScript\n * numbers.\n *\n * @memberof Number\n * @since 2.0.0\n * @category guards\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import * as Number from \"effect/Number\"\n *\n * // Regular numbers\n * assert.equal(Number.isNumber(2), true)\n * assert.equal(Number.isNumber(-3.14), true)\n * assert.equal(Number.isNumber(0), true)\n *\n * // Special numeric values\n * assert.equal(Number.isNumber(Infinity), true)\n * assert.equal(Number.isNumber(NaN), true)\n *\n * // Non-number values\n * assert.equal(Number.isNumber(\"2\"), false)\n * assert.equal(Number.isNumber(true), false)\n * assert.equal(Number.isNumber(null), false)\n * assert.equal(Number.isNumber(undefined), false)\n * assert.equal(Number.isNumber({}), false)\n * assert.equal(Number.isNumber([]), false)\n *\n * // Using as a type guard in conditionals\n * function processValue(value: unknown): string {\n *   if (Number.isNumber(value)) {\n *     // TypeScript now knows 'value' is a number\n *     return `Numeric value: ${value.toFixed(2)}`\n *   }\n *   return \"Not a number\"\n * }\n *\n * assert.strictEqual(processValue(42), \"Numeric value: 42.00\")\n * assert.strictEqual(processValue(\"hello\"), \"Not a number\")\n *\n * // Filtering for numbers in an array\n * const mixed = [1, \"two\", 3, false, 5]\n * const onlyNumbers = mixed.filter(Number.isNumber)\n * assert.equal(onlyNumbers, [1, 3, 5])\n * ```\n *\n * @param input - The value to test for membership in the set of JavaScript\n *   numbers\n *\n * @returns `true` if the input is a JavaScript number, `false` otherwise\n */\nexport const isNumber: (input: unknown) => input is number = predicate.isNumber\n\n/**\n * Returns the additive inverse of a number, effectively negating it.\n *\n * @memberof Number\n * @since 3.14.6\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { pipe } from \"effect\"\n * import * as Number from \"effect/Number\"\n *\n * assert.equal(\n *   Number.negate(5), //\n *   -5\n * )\n *\n * assert.equal(\n *   Number.negate(-5), //\n *   5\n * )\n *\n * assert.equal(\n *   Number.negate(0), //\n *   0\n * )\n * ```\n *\n * @param n - The number value to be negated.\n *\n * @returns The negated number value.\n */\nexport const negate = (n: number): number => multiply(n, -1)\n\n/**\n * Performs addition in the set of JavaScript numbers.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { pipe } from \"effect\"\n * import * as Number from \"effect/Number\"\n *\n * // Data-first style (direct application)\n * assert.equal(Number.sum(2, 3), 5)\n * assert.equal(Number.sum(-10, 5), -5)\n * assert.equal(Number.sum(0.1, 0.2), 0.30000000000000004) // Note: floating-point precision limitation\n *\n * // Data-last style (pipeable)\n * assert.equal(\n *   pipe(\n *     10,\n *     Number.sum(5) // 10 + 5 = 15\n *   ),\n *   15\n * )\n *\n * // Chaining multiple additions\n * assert.equal(\n *   pipe(\n *     1,\n *     Number.sum(2), // 1 + 2 = 3\n *     Number.sum(3), // 3 + 3 = 6\n *     Number.sum(4) // 6 + 4 = 10\n *   ),\n *   10\n * )\n *\n * // Identity property: a + 0 = a\n * assert.equal(Number.sum(42, 0), 42)\n *\n * // Commutative property: a + b = b + a\n * assert.equal(Number.sum(5, 3), Number.sum(3, 5))\n * ```\n */\nexport const sum: {\n  /**\n   * Returns a function that adds a specified number to its argument.\n   *\n   * @param that - The number to add to the input of the resulting function\n   *\n   * @returns A function that takes a number and returns the sum of that number\n   *   and `that`\n   */\n  (that: number): (self: number) => number\n\n  /**\n   * Adds two numbers together.\n   *\n   * @param self - The first addend\n   * @param that - The second addend\n   *\n   * @returns The sum of the two numbers\n   */\n  (self: number, that: number): number\n} = dual(2, (self: number, that: number): number => self + that)\n\n/**\n * Computes the sum of all elements in an iterable collection of numbers.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import * as Number from \"effect/Number\"\n *\n * // Basic sums\n * assert.equal(Number.sumAll([2, 3, 4]), 9) // 2 + 3 + 4 = 9\n * assert.equal(Number.sumAll([1.1, 2.2, 3.3]), 6.6) // 1.1 + 2.2 + 3.3 = 6.6\n *\n * // Empty collection returns the additive identity (0)\n * assert.equal(Number.sumAll([]), 0)\n *\n * // Single element collection\n * assert.equal(Number.sumAll([42]), 42)\n *\n * // Sums with negative numbers\n * assert.equal(Number.sumAll([2, -3, 4]), 3) // 2 + (-3) + 4 = 3\n * assert.equal(Number.sumAll([-2, -3, -4]), -9) // (-2) + (-3) + (-4) = -9\n *\n * // Works with any iterable\n * assert.equal(Number.sumAll(new Set([2, 3, 4])), 9)\n *\n * // Using with generated sequences\n * function* range(start: number, end: number) {\n *   for (let i = start; i <= end; i++) yield i\n * }\n *\n * // Compute sum of first 5 natural numbers: 1 + 2 + 3 + 4 + 5 = 15\n * assert.equal(Number.sumAll(range(1, 5)), 15)\n *\n * // Floating point precision example\n * assert.equal(\n *   Number.sumAll([0.1, 0.2]),\n *   0.30000000000000004 // Note IEEE 754 precision limitation\n * )\n * ```\n *\n * @param collection - An `iterable` containing the `numbers` to sum\n *\n * @returns The sum of all numbers in the collection, or 0 if the collection is\n *   empty\n */\nexport const sumAll = (collection: Iterable<number>): number => _Iterable.reduce(collection, 0, sum)\n\n/**\n * Performs subtraction in the set of JavaScript numbers.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { pipe } from \"effect\"\n * import * as Number from \"effect/Number\"\n *\n * // Data-first style (direct application)\n * assert.equal(Number.subtract(2, 3), -1) // 2 - 3 = -1\n * assert.equal(Number.subtract(10, 5), 5) // 10 - 5 = 5\n * assert.equal(Number.subtract(0.3, 0.1), 0.19999999999999998) // Note: floating-point precision limitation\n *\n * // Data-last style (pipeable)\n * assert.equal(\n *   pipe(\n *     10,\n *     Number.subtract(5) // 10 - 5 = 5\n *   ),\n *   5\n * )\n *\n * // Chaining multiple subtractions\n * assert.equal(\n *   pipe(\n *     20,\n *     Number.subtract(5), // 20 - 5 = 15\n *     Number.subtract(3), // 15 - 3 = 12\n *     Number.subtract(2) // 12 - 2 = 10\n *   ),\n *   10\n * )\n *\n * // Right identity property: a - 0 = a\n * assert.equal(Number.subtract(42, 0), 42)\n *\n * // Self-annihilation property: a - a = 0\n * assert.equal(Number.subtract(42, 42), 0)\n *\n * // Non-commutative property: a - b ≠ b - a\n * assert.equal(Number.subtract(5, 3), 2) // 5 - 3 = 2\n * assert.equal(Number.subtract(3, 5), -2) // 3 - 5 = -2\n *\n * // Inverse relation: a - b = -(b - a)\n * assert.equal(Number.subtract(5, 3), -Number.subtract(3, 5))\n * ```\n */\nexport const subtract: {\n  /**\n   * Returns a function that subtracts a specified number from its argument.\n   *\n   * @param subtrahend - The number to subtract from the input of the resulting\n   *   function\n   *\n   * @returns A function that takes a minuend and returns the difference of\n   *   subtracting the subtrahend from it\n   */\n  (subtrahend: number): (minuend: number) => number\n\n  /**\n   * Subtracts the subtrahend from the minuend and returns the difference.\n   *\n   * @param minuend - The number from which another number is to be subtracted\n   * @param subtrahend - The number to subtract from the minuend\n   *\n   * @returns The difference of the minuend minus the subtrahend\n   */\n  (minuend: number, subtrahend: number): number\n} = dual(\n  2,\n  (minuend: number, subtrahend: number): number => minuend - subtrahend\n)\n\n/**\n * Performs **multiplication** in the set of JavaScript numbers.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { pipe } from \"effect\"\n * import * as Number from \"effect/Number\"\n *\n * // Data-first style (direct application)\n * assert.equal(Number.multiply(2, 3), 6) // 2 × 3 = 6\n * assert.equal(Number.multiply(-4, 5), -20) // (-4) × 5 = -20\n * assert.equal(Number.multiply(-3, -2), 6) // (-3) × (-2) = 6\n * assert.equal(Number.multiply(0.1, 0.2), 0.020000000000000004) // Note: floating-point precision limitation\n *\n * // Data-last style (pipeable)\n * assert.equal(\n *   pipe(\n *     10,\n *     Number.multiply(5) // 10 × 5 = 50\n *   ),\n *   50\n * )\n *\n * // Chaining multiple multiplications\n * assert.equal(\n *   pipe(\n *     2,\n *     Number.multiply(3), // 2 × 3 = 6\n *     Number.multiply(4), // 6 × 4 = 24\n *     Number.multiply(0.5) // 24 × 0.5 = 12\n *   ),\n *   12\n * )\n *\n * // Identity property: a × 1 = a\n * assert.equal(Number.multiply(42, 1), 42)\n *\n * // Zero property: a × 0 = 0\n * assert.equal(Number.multiply(42, 0), 0)\n *\n * // Commutative property: a × b = b × a\n * assert.equal(Number.multiply(5, 3), Number.multiply(3, 5))\n *\n * // Associative property: (a × b) × c = a × (b × c)\n * const a = 2,\n *   b = 3,\n *   c = 4\n * assert.equal(\n *   Number.multiply(Number.multiply(a, b), c),\n *   Number.multiply(a, Number.multiply(b, c))\n * )\n * ```\n */\nexport const multiply: {\n  /**\n   * Returns a function that multiplies a specified number with its argument.\n   *\n   * @param multiplicand - The number to multiply with the input of the\n   *   resulting function\n   *\n   * @returns A function that takes a multiplier and returns the product of that\n   *   multiplier and the multiplicand\n   */\n  (multiplicand: number): (multiplier: number) => number\n\n  /**\n   * Multiplies two numbers together.\n   *\n   * @param multiplier - The first factor\n   * @param multiplicand - The second factor\n   *\n   * @returns The product of the two numbers\n   */\n  (multiplier: number, multiplicand: number): number\n} = dual(\n  2,\n  (multiplier: number, multiplicand: number): number => multiplier * multiplicand\n)\n\n/**\n * Computes the product of all elements in an iterable collection of numbers.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import * as Number from \"effect/Number\"\n *\n * // Basic products\n * assert.equal(Number.multiplyAll([2, 3, 4]), 24) // 2 × 3 × 4 = 24\n * assert.equal(Number.multiplyAll([1.5, 2, 3]), 9) // 1.5 × 2 × 3 = 9\n *\n * // Empty collection returns the multiplicative identity (1)\n * assert.equal(Number.multiplyAll([]), 1)\n *\n * // Single element collection\n * assert.equal(Number.multiplyAll([42]), 42)\n *\n * // Products with negative numbers\n * assert.equal(Number.multiplyAll([2, -3, 4]), -24) // 2 × (-3) × 4 = -24\n * assert.equal(Number.multiplyAll([-2, -3]), 6) // (-2) × (-3) = 6\n *\n * // Zero property - if any element is zero, product is zero\n * assert.equal(Number.multiplyAll([2, 0, 3]), 0)\n *\n * // Works with any iterable\n * assert.equal(Number.multiplyAll(new Set([2, 3, 4])), 24)\n *\n * // Using with generated sequences\n * function* range(start: number, end: number) {\n *   for (let i = start; i <= end; i++) yield i\n * }\n *\n * // Compute factorial: 5! = 5 × 4 × 3 × 2 × 1 = 120\n * assert.equal(Number.multiplyAll(range(1, 5)), 120)\n * ```\n *\n * @param collection - An `iterable` containing the `numbers` to multiply\n *\n * @returns The product of all numbers in the collection, or 1 if the collection\n *   is empty\n */\nexport const multiplyAll = (collection: Iterable<number>): number => {\n  let out = 1\n  for (const n of collection) {\n    if (n === 0) {\n      return 0\n    }\n    out *= n\n  }\n  return out\n}\n\n/**\n * Performs division in the set of JavaScript numbers, returning the result\n * wrapped in an `Option` to handle division by zero.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { pipe, Option } from \"effect\"\n * import * as Number from \"effect/Number\"\n *\n * // Data-first style (direct application)\n * assert.equal(Number.divide(6, 3), Option.some(2)) // 6 ÷ 3 = 2\n * assert.equal(Number.divide(-8, 4), Option.some(-2)) // (-8) ÷ 4 = -2\n * assert.equal(Number.divide(-10, -5), Option.some(2)) // (-10) ÷ (-5) = 2\n * assert.equal(Number.divide(1, 3), Option.some(0.3333333333333333)) // Note: floating-point approximation\n *\n * // Handling division by zero\n * assert.equal(Number.divide(6, 0), Option.none()) // 6 ÷ 0 is undefined\n *\n * // Data-last style (pipeable)\n * assert.equal(\n *   pipe(\n *     10,\n *     Number.divide(2) // 10 ÷ 2 = 5\n *   ),\n *   Option.some(5)\n * )\n *\n * // Chaining multiple divisions using Option combinators\n * assert.equal(\n *   pipe(\n *     Option.some(24),\n *     Option.flatMap((n) => Number.divide(n, 2)), // 24 ÷ 2 = 12\n *     Option.flatMap(Number.divide(3)), // 12 ÷ 3 = 4\n *     Option.flatMap(Number.divide(2)) // 4 ÷ 2 = 2\n *   ),\n *   Option.some(2)\n * )\n *\n * // Division-by-one property: a ÷ 1 = a\n * assert.equal(Number.divide(42, 1), Option.some(42))\n *\n * // Self-division property: a ÷ a = 1 (for a ≠ 0)\n * assert.equal(Number.divide(42, 42), Option.some(1))\n *\n * // Non-commutative property: a ÷ b ≠ b ÷ a\n * assert.notDeepStrictEqual(\n *   Number.divide(6, 3), // 6 ÷ 3 = 2\n *   Number.divide(3, 6) // 3 ÷ 6 = 0.5\n * )\n * ```\n */\nexport const divide: {\n  /**\n   * Returns a function that divides its input by a specified divisor.\n   *\n   * @param divisor - The number to divide by\n   *\n   * @returns A function that takes a dividend and returns the quotient wrapped\n   *   in an Option (Option.none() if divisor is 0)\n   */\n  (divisor: number): (dividend: number) => Option<number>\n\n  /**\n   * Divides the dividend by the divisor and returns the quotient wrapped in an\n   * Option.\n   *\n   * @param dividend - The number to be divided\n   * @param divisor - The number to divide by\n   *\n   * @returns Some(quotient) if the divisor is not 0, None otherwise\n   */\n  (dividend: number, divisor: number): Option<number>\n} = dual(2, (dividend: number, divisor: number) => divisor === 0 ? option.none : option.some(dividend / divisor))\n\n/**\n * Performs division in the set of JavaScript numbers, but misbehaves for\n * division by zero.\n *\n * Unlike {@link module:Number.divide} which returns an Option, this function\n * directly returns a number or `Infinity` or `NaN`.\n *\n * - If the `divisor` is zero, it returns `Infinity`.\n * - If both the `dividend` and the `divisor` are zero, then it returns `NaN`.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { pipe } from \"effect\"\n * import * as Number from \"effect/Number\"\n *\n * // Data-first style (direct application)\n * assert.equal(Number.unsafeDivide(6, 3), 2) // 6 ÷ 3 = 2\n * assert.equal(Number.unsafeDivide(-8, 4), -2) // (-8) ÷ 4 = -2\n * assert.equal(Number.unsafeDivide(-10, -5), 2) // (-10) ÷ (-5) = 2\n * assert.equal(Number.unsafeDivide(1, 3), 0.3333333333333333)\n *\n * // Data-last style (pipeable)\n * assert.equal(\n *   pipe(\n *     10,\n *     Number.unsafeDivide(2) // 10 ÷ 2 = 5\n *   ),\n *   5\n * )\n *\n * // Chaining multiple divisions\n * assert.equal(\n *   pipe(\n *     24,\n *     Number.unsafeDivide(2), // 24 ÷ 2 = 12\n *     Number.unsafeDivide(3), // 12 ÷ 3 = 4\n *     Number.unsafeDivide(2) // 4 ÷ 2 = 2\n *   ),\n *   2\n * )\n *\n * assert.equal(Number.unsafeDivide(6, 0), Infinity)\n *\n * assert.equal(Number.unsafeDivide(0, 0), NaN)\n *\n * // Compare with safe division\n * const safeResult = Number.divide(6, 3) // Option.some(2)\n * const unsafeResult = Number.unsafeDivide(6, 3) // 2 directly\n * ```\n *\n * @throws - An {@link module:Number.DivisionByZeroError} if the divisor is zero.\n * @see {@link module:Number.divide} - Safe division returning an Option\n */\nexport const unsafeDivide: {\n  /**\n   * Returns a function that divides its input by a specified divisor.\n   *\n   * @param divisor - The number to divide by\n   *\n   * @returns A function that takes a dividend and returns the quotient\n   * @throws - An {@link module:Number.DivisionByZeroError} if the divisor is\n   *   zero\n   */\n  (divisor: number): (dividend: number) => number\n\n  /**\n   * Divides the dividend by the divisor and returns the quotient.\n   *\n   * If the divisor is zero, it returns Infinity.\n   *\n   * @param dividend - The number to be divided\n   * @param divisor - The number to divide by\n   *\n   * @returns The quotient of the division\n   */\n  (dividend: number, divisor: number): number\n} = dual(2, (dividend: number, divisor: number): number => dividend / divisor)\n\n/**\n * Returns the result of adding `1` to a given number.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { increment } from \"effect/Number\"\n *\n * assert.equal(increment(2), 3)\n * ```\n */\nexport const increment = (n: number): number => sum(n, 1)\n\n/**\n * Decrements a number by `1`.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { decrement } from \"effect/Number\"\n *\n * assert.equal(decrement(3), 2)\n * ```\n */\nexport const decrement = (n: number): number => subtract(n, 1)\n\n/**\n * @memberof Number\n * @since 2.0.0\n * @category instances\n */\nexport const Equivalence: equivalence.Equivalence<number> = equivalence.number\n\n/**\n * @memberof Number\n * @since 2.0.0\n * @category instances\n */\nexport const Order: order.Order<number> = order.number\n\n/**\n * Returns `true` if the first argument is less than the second, otherwise\n * `false`.\n *\n * @memberof Number\n * @since 2.0.0\n * @category predicates\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { lessThan } from \"effect/Number\"\n *\n * assert.equal(lessThan(2, 3), true)\n * assert.equal(lessThan(3, 3), false)\n * assert.equal(lessThan(4, 3), false)\n * ```\n */\nexport const lessThan: {\n  (that: number): (self: number) => boolean\n  (self: number, that: number): boolean\n} = order.lessThan(Order)\n\n/**\n * Returns a function that checks if a given `number` is less than or equal to\n * the provided one.\n *\n * @memberof Number\n * @since 2.0.0\n * @category predicates\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { lessThanOrEqualTo } from \"effect/Number\"\n *\n * assert.equal(lessThanOrEqualTo(2, 3), true)\n * assert.equal(lessThanOrEqualTo(3, 3), true)\n * assert.equal(lessThanOrEqualTo(4, 3), false)\n * ```\n */\nexport const lessThanOrEqualTo: {\n  (that: number): (self: number) => boolean\n  (self: number, that: number): boolean\n} = order.lessThanOrEqualTo(Order)\n\n/**\n * Returns `true` if the first argument is greater than the second, otherwise\n * `false`.\n *\n * @memberof Number\n * @since 2.0.0\n * @category predicates\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { greaterThan } from \"effect/Number\"\n *\n * assert.equal(greaterThan(2, 3), false)\n * assert.equal(greaterThan(3, 3), false)\n * assert.equal(greaterThan(4, 3), true)\n * ```\n */\nexport const greaterThan: {\n  (that: number): (self: number) => boolean\n  (self: number, that: number): boolean\n} = order.greaterThan(Order)\n\n/**\n * Returns a function that checks if a given `number` is greater than or equal\n * to the provided one.\n *\n * @memberof Number\n * @since 2.0.0\n * @category predicates\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { greaterThanOrEqualTo } from \"effect/Number\"\n *\n * assert.equal(greaterThanOrEqualTo(2, 3), false)\n * assert.equal(greaterThanOrEqualTo(3, 3), true)\n * assert.equal(greaterThanOrEqualTo(4, 3), true)\n * ```\n */\nexport const greaterThanOrEqualTo: {\n  (that: number): (self: number) => boolean\n  (self: number, that: number): boolean\n} = order.greaterThanOrEqualTo(Order)\n\n/**\n * Checks if a `number` is between a `minimum` and `maximum` value (inclusive).\n *\n * @memberof Number\n * @since 2.0.0\n * @category predicates\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { Number } from \"effect\"\n *\n * const between = Number.between({ minimum: 0, maximum: 5 })\n *\n * assert.equal(between(3), true)\n * assert.equal(between(-1), false)\n * assert.equal(between(6), false)\n * ```\n */\nexport const between: {\n  (options: { minimum: number; maximum: number }): (self: number) => boolean\n  (\n    self: number,\n    options: {\n      minimum: number\n      maximum: number\n    }\n  ): boolean\n} = order.between(Order)\n\n/**\n * Restricts the given `number` to be within the range specified by the\n * `minimum` and `maximum` values.\n *\n * - If the `number` is less than the `minimum` value, the function returns the\n *   `minimum` value.\n * - If the `number` is greater than the `maximum` value, the function returns the\n *   `maximum` value.\n * - Otherwise, it returns the original `number`.\n *\n * @memberof Number\n * @since 2.0.0\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { Number } from \"effect\"\n *\n * const clamp = Number.clamp({ minimum: 1, maximum: 5 })\n *\n * assert.equal(clamp(3), 3)\n * assert.equal(clamp(0), 1)\n * assert.equal(clamp(6), 5)\n * ```\n */\nexport const clamp: {\n  (options: { minimum: number; maximum: number }): (self: number) => number\n  (\n    self: number,\n    options: {\n      minimum: number\n      maximum: number\n    }\n  ): number\n} = order.clamp(Order)\n\n/**\n * Returns the minimum between two `number`s.\n *\n * @memberof Number\n * @since 2.0.0\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { min } from \"effect/Number\"\n *\n * assert.equal(min(2, 3), 2)\n * ```\n */\nexport const min: {\n  (that: number): (self: number) => number\n  (self: number, that: number): number\n} = order.min(Order)\n\n/**\n * Returns the maximum between two `number`s.\n *\n * @memberof Number\n * @since 2.0.0\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { max } from \"effect/Number\"\n *\n * assert.equal(max(2, 3), 3)\n * ```\n */\nexport const max: {\n  (that: number): (self: number) => number\n  (self: number, that: number): number\n} = order.max(Order)\n\n/**\n * Determines the sign of a given `number`.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { sign } from \"effect/Number\"\n *\n * assert.equal(sign(-5), -1)\n * assert.equal(sign(0), 0)\n * assert.equal(sign(5), 1)\n * ```\n */\nexport const sign = (n: number): Ordering => Order(n, 0)\n\n/**\n * Returns the remainder left over when one operand is divided by a second\n * operand.\n *\n * It always takes the sign of the dividend.\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { remainder } from \"effect/Number\"\n *\n * assert.equal(remainder(2, 2), 0)\n * assert.equal(remainder(3, 2), 1)\n * assert.equal(remainder(-4, 2), -0)\n * ```\n */\nexport const remainder: {\n  (divisor: number): (dividend: number) => number\n  (dividend: number, divisor: number): number\n} = dual(2, (dividend: number, divisor: number): number => {\n  // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\n  const selfDecCount = (dividend.toString().split(\".\")[1] || \"\").length\n  const divisorDecCount = (divisor.toString().split(\".\")[1] || \"\").length\n  const decCount = selfDecCount > divisorDecCount ? selfDecCount : divisorDecCount\n  const selfInt = parseInt(dividend.toFixed(decCount).replace(\".\", \"\"))\n  const divisorInt = parseInt(divisor.toFixed(decCount).replace(\".\", \"\"))\n  return (selfInt % divisorInt) / Math.pow(10, decCount)\n})\n\n/**\n * Returns the next power of 2 greater than or equal to the given number.\n *\n * - For `positive` inputs, returns the smallest power of 2 that is >= the input\n * - For `zero`, returns 2\n * - For `negative` inputs, returns NaN (as logarithms of negative numbers are\n *   undefined)\n * - For `NaN` input, returns NaN\n * - For `Infinity`, returns Infinity\n *\n * @memberof Number\n * @since 2.0.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { nextPow2 } from \"effect/Number\"\n *\n * assert.equal(nextPow2(5), 8)\n * assert.equal(nextPow2(17), 32)\n * assert.equal(nextPow2(0), 2)\n * assert.equal(Number.isNaN(nextPow2(-1)), true) // Negative inputs result in NaN\n * ```\n */\nexport const nextPow2 = (n: number): number => {\n  const nextPow = Math.ceil(Math.log(n) / Math.log(2))\n  return Math.max(Math.pow(2, nextPow), 2)\n}\n\n/**\n * Tries to parse a `number` from a `string` using the `Number()` function. The\n * following special string values are supported: \"NaN\", \"Infinity\",\n * \"-Infinity\".\n *\n * @memberof Number\n * @since 2.0.0\n * @category constructors\n */\nexport const parse: {\n  (s: string): Option<number>\n} = (s) => {\n  if (s === \"NaN\") {\n    return option.some(NaN)\n  }\n  if (s === \"Infinity\") {\n    return option.some(Infinity)\n  }\n  if (s === \"-Infinity\") {\n    return option.some(-Infinity)\n  }\n  if (s.trim() === \"\") {\n    return option.none\n  }\n  const n = Number(s)\n  return Number.isNaN(n) ? option.none : option.some(n)\n}\n\n/**\n * Returns the number rounded with the given precision.\n *\n * @memberof Number\n * @since 3.8.0\n * @category math\n * @example\n *\n * ```ts\n * import * as assert from \"node:assert/strict\"\n * import { round } from \"effect/Number\"\n *\n * assert.equal(round(1.1234, 2), 1.12)\n * assert.equal(round(1.567, 2), 1.57)\n * ```\n */\nexport const round: {\n  (precision: number): (self: number) => number\n  (self: number, precision: number): number\n} = dual(2, (self: number, precision: number): number => {\n  const factor = Math.pow(10, precision)\n  return Math.round(self * factor) / factor\n})\n"
  },
  {
    "path": "packages/effect/src/Option.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { Either } from \"./Either.js\"\nimport * as Equal from \"./Equal.js\"\nimport * as Equivalence from \"./Equivalence.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport { constNull, constUndefined, dual, identity, isFunction } from \"./Function.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as doNotation from \"./internal/doNotation.js\"\nimport * as either from \"./internal/either.js\"\nimport * as option from \"./internal/option.js\"\nimport type { Order } from \"./Order.js\"\nimport * as order from \"./Order.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport type { Covariant, NoInfer, NotFunction } from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\nimport * as Gen from \"./Utils.js\"\n\n/**\n * The `Option` data type represents optional values. An `Option<A>` can either\n * be `Some<A>`, containing a value of type `A`, or `None`, representing the\n * absence of a value.\n *\n * **When to Use**\n *\n * You can use `Option` in scenarios like:\n *\n * - Using it for initial values\n * - Returning values from functions that are not defined for all possible\n *   inputs (referred to as “partial functions”)\n * - Managing optional fields in data structures\n * - Handling optional function arguments\n *\n * @category Models\n * @since 2.0.0\n */\nexport type Option<A> = None<A> | Some<A>\n\n/**\n * @category Symbols\n * @since 2.0.0\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/Option\")\n\n/**\n * @category Symbols\n * @since 2.0.0\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @category Models\n * @since 2.0.0\n */\nexport interface None<out A> extends Pipeable, Inspectable {\n  readonly _tag: \"None\"\n  readonly _op: \"None\"\n  readonly [TypeId]: {\n    readonly _A: Covariant<A>\n  }\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: OptionUnify<this>\n  [Unify.ignoreSymbol]?: OptionUnifyIgnore\n}\n\n/**\n * @category Models\n * @since 2.0.0\n */\nexport interface Some<out A> extends Pipeable, Inspectable {\n  readonly _tag: \"Some\"\n  readonly _op: \"Some\"\n  readonly value: A\n  readonly [TypeId]: {\n    readonly _A: Covariant<A>\n  }\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: OptionUnify<this>\n  [Unify.ignoreSymbol]?: OptionUnifyIgnore\n}\n\n/**\n * @category Models\n * @since 2.0.0\n */\nexport interface OptionUnify<A extends { [Unify.typeSymbol]?: any }> {\n  Option?: () => A[Unify.typeSymbol] extends Option<infer A0> | infer _ ? Option<A0> : never\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Option {\n  /**\n   * Extracts the type of the value contained in an `Option`.\n   *\n   * **Example** (Getting the Value Type of an Option)\n   *\n   * ```ts\n   * import { Option } from \"effect\"\n   *\n   * // Declare an Option holding a string\n   * declare const myOption: Option.Option<string>\n   *\n   * // Extract the type of the value within the Option\n   * //\n   * //      ┌─── string\n   * //      ▼\n   * type MyType = Option.Option.Value<typeof myOption>\n   * ```\n   *\n   * @since 2.0.0\n   * @category Type-level Utils\n   */\n  export type Value<T extends Option<any>> = [T] extends [Option<infer _A>] ? _A : never\n}\n\n/**\n * @category Models\n * @since 2.0.0\n */\nexport interface OptionUnifyIgnore {}\n\n/**\n * @category Type Lambdas\n * @since 2.0.0\n */\nexport interface OptionTypeLambda extends TypeLambda {\n  readonly type: Option<this[\"Target\"]>\n}\n\n/**\n * Represents the absence of a value by creating an empty `Option`.\n *\n * `Option.none` returns an `Option<never>`, which is a subtype of `Option<A>`.\n * This means you can use it in place of any `Option<A>` regardless of the type\n * `A`.\n *\n * **Example** (Creating an Option with No Value)\n *\n * ```ts\n * import { Option } from \"effect\"\n *\n * // An Option holding no value\n * //\n * //      ┌─── Option<never>\n * //      ▼\n * const noValue = Option.none()\n *\n * console.log(noValue)\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @see {@link some} for the opposite operation.\n *\n * @category Constructors\n * @since 2.0.0\n */\nexport const none = <A = never>(): Option<A> => option.none\n\n/**\n * Wraps the given value into an `Option` to represent its presence.\n *\n * **Example** (Creating an Option with a Value)\n *\n * ```ts\n * import { Option } from \"effect\"\n *\n * // An Option holding the number 1\n * //\n * //      ┌─── Option<number>\n * //      ▼\n * const value = Option.some(1)\n *\n * console.log(value)\n * // Output: { _id: 'Option', _tag: 'Some', value: 1 }\n * ```\n *\n * @see {@link none} for the opposite operation.\n *\n * @category Constructors\n * @since 2.0.0\n */\nexport const some: <A>(value: A) => Option<A> = option.some\n\n/**\n * Determines whether the given value is an `Option`.\n *\n * **Details**\n *\n * This function checks if a value is an instance of `Option`. It returns `true`\n * if the value is either `Option.some` or `Option.none`, and `false` otherwise.\n * This is particularly useful when working with unknown values or when you need\n * to ensure type safety in your code.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.isOption(Option.some(1)))\n * // Output: true\n *\n * console.log(Option.isOption(Option.none()))\n * // Output: true\n *\n * console.log(Option.isOption({}))\n * // Output: false\n * ```\n *\n * @category Guards\n * @since 2.0.0\n */\nexport const isOption: (input: unknown) => input is Option<unknown> = option.isOption\n\n/**\n * Checks whether an `Option` represents the absence of a value (`None`).\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.isNone(Option.some(1)))\n * // Output: false\n *\n * console.log(Option.isNone(Option.none()))\n * // Output: true\n * ```\n *\n * @see {@link isSome} for the opposite check.\n *\n * @category Guards\n * @since 2.0.0\n */\nexport const isNone: <A>(self: Option<A>) => self is None<A> = option.isNone\n\n/**\n * Checks whether an `Option` contains a value (`Some`).\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.isSome(Option.some(1)))\n * // Output: true\n *\n * console.log(Option.isSome(Option.none()))\n * // Output: false\n * ```\n *\n * @see {@link isNone} for the opposite check.\n *\n * @category Guards\n * @since 2.0.0\n */\nexport const isSome: <A>(self: Option<A>) => self is Some<A> = option.isSome\n\n/**\n * Performs pattern matching on an `Option` to handle both `Some` and `None`\n * cases.\n *\n * **Details**\n *\n * This function allows you to match against an `Option` and handle both\n * scenarios: when the `Option` is `None` (i.e., contains no value), and when\n * the `Option` is `Some` (i.e., contains a value). It executes one of the\n * provided functions based on the case:\n *\n * - If the `Option` is `None`, the `onNone` function is executed and its result\n *   is returned.\n * - If the `Option` is `Some`, the `onSome` function is executed with the\n *   contained value, and its result is returned.\n *\n * This function provides a concise and functional way to handle optional values\n * without resorting to `if` or manual checks, making your code more declarative\n * and readable.\n *\n * **Example** (Pattern Matching with Option)\n *\n * ```ts\n * import { Option } from \"effect\"\n *\n * const foo = Option.some(1)\n *\n * const message = Option.match(foo, {\n *   onNone: () => \"Option is empty\",\n *   onSome: (value) => `Option has a value: ${value}`\n * })\n *\n * console.log(message)\n * // Output: \"Option has a value: 1\"\n * ```\n *\n * @category Pattern matching\n * @since 2.0.0\n */\nexport const match: {\n  <B, A, C = B>(options: {\n    readonly onNone: LazyArg<B>\n    readonly onSome: (a: A) => C\n  }): (self: Option<A>) => B | C\n  <A, B, C = B>(self: Option<A>, options: {\n    readonly onNone: LazyArg<B>\n    readonly onSome: (a: A) => C\n  }): B | C\n} = dual(\n  2,\n  <A, B, C = B>(self: Option<A>, { onNone, onSome }: {\n    readonly onNone: LazyArg<B>\n    readonly onSome: (a: A) => C\n  }): B | C => isNone(self) ? onNone() : onSome(self.value)\n)\n\n/**\n * Converts an `Option`-returning function into a type guard.\n *\n * **Details**\n *\n * This function transforms a function that returns an `Option` into a type\n * guard, ensuring type safety when validating or narrowing types. The returned\n * type guard function checks whether the input satisfies the condition defined\n * in the original `Option`-returning function.\n *\n * If the original function returns `Option.some`, the type guard evaluates to\n * `true`, confirming the input is of the desired type. If the function returns\n * `Option.none`, the type guard evaluates to `false`.\n *\n * This utility is especially useful for validating types in union types,\n * filtering arrays, or ensuring safe handling of specific subtypes.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * type MyData = string | number\n *\n * const parseString = (data: MyData): Option.Option<string> =>\n *   typeof data === \"string\" ? Option.some(data) : Option.none()\n *\n * //      ┌─── (a: MyData) => a is string\n * //      ▼\n * const isString = Option.toRefinement(parseString)\n *\n * console.log(isString(\"a\"))\n * // Output: true\n *\n * console.log(isString(1))\n * // Output: false\n * ```\n *\n * @category Conversions\n * @since 2.0.0\n */\nexport const toRefinement = <A, B extends A>(f: (a: A) => Option<B>): (a: A) => a is B => (a: A): a is B => isSome(f(a))\n\n/**\n * Converts an `Iterable` into an `Option`, wrapping the first element if it\n * exists.\n *\n * **Details**\n *\n * This function takes an `Iterable` (e.g., an array, a generator, or any object\n * implementing the `Iterable` interface) and returns an `Option` based on its\n * content:\n *\n * - If the `Iterable` contains at least one element, the first element is\n *   wrapped in a `Some` and returned.\n * - If the `Iterable` is empty, `None` is returned, representing the absence of\n *   a value.\n *\n * This utility is useful for safely handling collections that might be empty,\n * ensuring you explicitly handle both cases where a value exists or doesn't.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.fromIterable([1, 2, 3]))\n * // Output: { _id: 'Option', _tag: 'Some', value: 1 }\n *\n * console.log(Option.fromIterable([]))\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Constructors\n * @since 2.0.0\n */\nexport const fromIterable = <A>(collection: Iterable<A>): Option<A> => {\n  for (const a of collection) {\n    return some(a)\n  }\n  return none()\n}\n\n/**\n * Converts an `Either` into an `Option` by discarding the error and extracting\n * the right value.\n *\n * **Details**\n *\n * This function takes an `Either` and returns an `Option` based on its value:\n *\n * - If the `Either` is a `Right`, its value is wrapped in a `Some` and\n *   returned.\n * - If the `Either` is a `Left`, the error is discarded, and `None` is\n *   returned.\n *\n * This is particularly useful when you only care about the success case\n * (`Right`) of an `Either` and want to handle the result using `Option`. By\n * using this function, you can convert `Either` into a simpler structure for\n * cases where error handling is not required.\n *\n * @example\n * ```ts\n * import { Either, Option } from \"effect\"\n *\n * console.log(Option.getRight(Either.right(\"ok\")))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'ok' }\n *\n * console.log(Option.getRight(Either.left(\"err\")))\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @see {@link getLeft} for the opposite operation.\n *\n * @category Conversions\n * @since 2.0.0\n */\nexport const getRight: <R, L>(self: Either<R, L>) => Option<R> = either.getRight\n\n/**\n * Converts an `Either` into an `Option` by discarding the right value and\n * extracting the left value.\n *\n * **Details**\n *\n * This function transforms an `Either` into an `Option` as follows:\n *\n * - If the `Either` is a `Left`, its value is wrapped in a `Some` and returned.\n * - If the `Either` is a `Right`, the value is discarded, and `None` is\n *   returned.\n *\n * This utility is useful when you only care about the error case (`Left`) of an\n * `Either` and want to handle it as an `Option`. By discarding the right value,\n * it simplifies error-focused workflows.\n *\n * @example\n * ```ts\n * import { Either, Option } from \"effect\"\n *\n * console.log(Option.getLeft(Either.right(\"ok\")))\n * // Output: { _id: 'Option', _tag: 'None' }\n *\n * console.log(Option.getLeft(Either.left(\"err\")))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'err' }\n * ```\n *\n * @see {@link getRight} for the opposite operation.\n *\n * @category Conversions\n * @since 2.0.0\n */\nexport const getLeft: <R, L>(self: Either<R, L>) => Option<L> = either.getLeft\n\n/**\n * Returns the value contained in the `Option` if it is `Some`, otherwise\n * evaluates and returns the result of `onNone`.\n *\n * **Details**\n *\n * This function allows you to provide a fallback value or computation for when\n * an `Option` is `None`. If the `Option` contains a value (`Some`), that value\n * is returned. If it is empty (`None`), the `onNone` function is executed, and\n * its result is returned instead.\n *\n * This utility is helpful for safely handling `Option` values by ensuring you\n * always receive a meaningful result, whether or not the `Option` contains a\n * value. It is particularly useful for providing default values or alternative\n * logic when working with optional values.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.some(1).pipe(Option.getOrElse(() => 0)))\n * // Output: 1\n *\n * console.log(Option.none().pipe(Option.getOrElse(() => 0)))\n * // Output: 0\n * ```\n *\n * @see {@link getOrNull} for a version that returns `null` instead of executing a function.\n * @see {@link getOrUndefined} for a version that returns `undefined` instead of executing a function.\n *\n * @category Getters\n * @since 2.0.0\n */\nexport const getOrElse: {\n  <B>(onNone: LazyArg<B>): <A>(self: Option<A>) => B | A\n  <A, B>(self: Option<A>, onNone: LazyArg<B>): A | B\n} = dual(\n  2,\n  <A, B>(self: Option<A>, onNone: LazyArg<B>): A | B => isNone(self) ? onNone() : self.value\n)\n\n/**\n * Returns the provided `Option` `that` if the current `Option` (`self`) is\n * `None`; otherwise, it returns `self`.\n *\n * **Details**\n *\n * This function provides a fallback mechanism for `Option` values. If the\n * current `Option` is `None` (i.e., it contains no value), the `that` function\n * is evaluated, and its resulting `Option` is returned. If the current `Option`\n * is `Some` (i.e., it contains a value), the original `Option` is returned\n * unchanged.\n *\n * This is particularly useful for chaining fallback values or computations,\n * allowing you to provide alternative `Option` values when the first one is\n * empty.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.none().pipe(Option.orElse(() => Option.none())))\n * // Output: { _id: 'Option', _tag: 'None' }\n *\n * console.log(Option.some(\"a\").pipe(Option.orElse(() => Option.none())))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'a' }\n *\n * console.log(Option.none().pipe(Option.orElse(() => Option.some(\"b\"))))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'b' }\n *\n * console.log(Option.some(\"a\").pipe(Option.orElse(() => Option.some(\"b\"))))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'a' }\n * ```\n *\n * @category Error handling\n * @since 2.0.0\n */\nexport const orElse: {\n  <B>(that: LazyArg<Option<B>>): <A>(self: Option<A>) => Option<B | A>\n  <A, B>(self: Option<A>, that: LazyArg<Option<B>>): Option<A | B>\n} = dual(\n  2,\n  <A, B>(self: Option<A>, that: LazyArg<Option<B>>): Option<A | B> => isNone(self) ? that() : self\n)\n\n/**\n * Returns the provided default value wrapped in `Some` if the current `Option`\n * (`self`) is `None`; otherwise, returns `self`.\n *\n * **Details**\n *\n * This function provides a way to supply a default value for cases where an\n * `Option` is `None`. If the current `Option` is empty (`None`), the `onNone`\n * function is executed to compute the default value, which is then wrapped in a\n * `Some`. If the current `Option` contains a value (`Some`), it is returned as\n * is.\n *\n * This is particularly useful for handling optional values where a fallback\n * default needs to be provided explicitly in case of absence.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.none().pipe(Option.orElseSome(() => \"b\")))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'b' }\n *\n * console.log(Option.some(\"a\").pipe(Option.orElseSome(() => \"b\")))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'a' }\n * ```\n *\n * @category Error handling\n * @since 2.0.0\n */\nexport const orElseSome: {\n  <B>(onNone: LazyArg<B>): <A>(self: Option<A>) => Option<B | A>\n  <A, B>(self: Option<A>, onNone: LazyArg<B>): Option<A | B>\n} = dual(\n  2,\n  <A, B>(self: Option<A>, onNone: LazyArg<B>): Option<A | B> => isNone(self) ? some(onNone()) : self\n)\n\n/**\n * Similar to {@link orElse}, but returns an `Either` wrapped in an `Option` to\n * indicate the source of the value.\n *\n * **Details**\n *\n * This function allows you to provide a fallback `Option` in case the current\n * `Option` (`self`) is `None`. However, unlike `orElse`, it returns the value\n * wrapped in an `Either` object, providing additional information about where\n * the value came from:\n *\n * - If the value is from the fallback `Option` (`that`), it is wrapped in an\n *   `Either.right`.\n * - If the value is from the original `Option` (`self`), it is wrapped in an\n *   `Either.left`.\n *\n * This is especially useful when you need to differentiate between values\n * originating from the primary `Option` and those coming from the fallback,\n * while still maintaining the `Option`-style handling.\n *\n * @category Error handling\n * @since 2.0.0\n */\nexport const orElseEither: {\n  <B>(that: LazyArg<Option<B>>): <A>(self: Option<A>) => Option<Either<B, A>>\n  <A, B>(self: Option<A>, that: LazyArg<Option<B>>): Option<Either<B, A>>\n} = dual(\n  2,\n  <A, B>(self: Option<A>, that: LazyArg<Option<B>>): Option<Either<B, A>> =>\n    isNone(self) ? map(that(), either.right) : map(self, either.left)\n)\n\n/**\n * Returns the first `Some` value found in an `Iterable` collection of\n * `Option`s, or `None` if no `Some` is found.\n *\n * **Details**\n *\n * This function iterates over a collection of `Option` values and returns the\n * first `Some` it encounters. If the collection contains only `None` values,\n * the result will also be `None`. This utility is useful for efficiently\n * finding the first valid value in a sequence of potentially empty or invalid\n * options.\n *\n * The iteration stops as soon as a `Some` is found, making this function\n * efficient for large collections.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.firstSomeOf([\n *   Option.none(),\n *   Option.some(1),\n *   Option.some(2)\n * ]))\n * // Output: { _id: 'Option', _tag: 'Some', value: 1 }\n * ```\n *\n * @category Error handling\n * @since 2.0.0\n */\nexport const firstSomeOf = <T, C extends Iterable<Option<T>> = Iterable<Option<T>>>(\n  collection: C\n): [C] extends [Iterable<Option<infer A>>] ? Option<A> : never => {\n  let out: Option<unknown> = none()\n  for (out of collection) {\n    if (isSome(out)) {\n      return out as any\n    }\n  }\n  return out as any\n}\n\n/**\n * Converts a nullable value into an `Option`. Returns `None` if the value is\n * `null` or `undefined`, otherwise wraps the value in a `Some`.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.fromNullable(undefined))\n * // Output: { _id: 'Option', _tag: 'None' }\n *\n * console.log(Option.fromNullable(null))\n * // Output: { _id: 'Option', _tag: 'None' }\n *\n * console.log(Option.fromNullable(1))\n * // Output: { _id: 'Option', _tag: 'Some', value: 1 }\n * ```\n *\n * @category Conversions\n * @since 2.0.0\n */\nexport const fromNullable = <A>(\n  nullableValue: A\n): Option<NonNullable<A>> => (nullableValue == null ? none() : some(nullableValue as NonNullable<A>))\n\n/**\n * Lifts a function that returns `null` or `undefined` into the `Option`\n * context.\n *\n * **Details**\n *\n * This function takes a function `f` that might return `null` or `undefined`\n * and transforms it into a function that returns an `Option`. The resulting\n * function will return:\n * - `Some` if the original function produces a non-null, non-undefined value.\n * - `None` if the original function produces `null` or `undefined`.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * const parse = (s: string): number | undefined => {\n *   const n = parseFloat(s)\n *   return isNaN(n) ? undefined : n\n * }\n *\n * const parseOption = Option.liftNullable(parse)\n *\n * console.log(parseOption(\"1\"))\n * // Output: { _id: 'Option', _tag: 'Some', value: 1 }\n *\n * console.log(parseOption(\"not a number\"))\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Conversions\n * @since 2.0.0\n */\nexport const liftNullable = <A extends ReadonlyArray<unknown>, B>(\n  f: (...a: A) => B | null | undefined\n): (...a: A) => Option<NonNullable<B>> =>\n(...a) => fromNullable(f(...a))\n\n/**\n * Returns the value contained in the `Option` if it is `Some`; otherwise,\n * returns `null`.\n *\n * **Details**\n *\n * This function provides a way to extract the value of an `Option` while\n * falling back to `null` if the `Option` is `None`.\n *\n * It is particularly useful in scenarios where `null` is an acceptable\n * placeholder for the absence of a value, such as when interacting with APIs or\n * systems that use `null` as a default for missing values.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.getOrNull(Option.some(1)))\n * // Output: 1\n *\n * console.log(Option.getOrNull(Option.none()))\n * // Output: null\n * ```\n *\n * @category Getters\n * @since 2.0.0\n */\nexport const getOrNull: <A>(self: Option<A>) => A | null = getOrElse(constNull)\n\n/**\n * Returns the value contained in the `Option` if it is `Some`; otherwise,\n * returns `undefined`.\n *\n * **Details**\n *\n * This function provides a way to extract the value of an `Option` while\n * falling back to `undefined` if the `Option` is `None`.\n *\n * It is particularly useful in scenarios where `undefined` is an acceptable\n * placeholder for the absence of a value, such as when interacting with APIs or\n * systems that use `undefined` as a default for missing values.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.getOrUndefined(Option.some(1)))\n * // Output: 1\n *\n * console.log(Option.getOrUndefined(Option.none()))\n * // Output: undefined\n * ```\n *\n * @category Getters\n * @since 2.0.0\n */\nexport const getOrUndefined: <A>(self: Option<A>) => A | undefined = getOrElse(constUndefined)\n\n/**\n * Lifts a function that throws exceptions into a function that returns an\n * `Option`.\n *\n * **Details**\n *\n * This utility function takes a function `f` that might throw an exception and\n * transforms it into a safer function that returns an `Option`. If the original\n * function executes successfully, the result is wrapped in a `Some`. If an\n * exception is thrown, the result is `None`, allowing the developer to handle\n * errors in a functional, type-safe way.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * const parse = Option.liftThrowable(JSON.parse)\n *\n * console.log(parse(\"1\"))\n * // Output: { _id: 'Option', _tag: 'Some', value: 1 }\n *\n * console.log(parse(\"\"))\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Conversions\n * @since 2.0.0\n */\nexport const liftThrowable = <A extends ReadonlyArray<unknown>, B>(\n  f: (...a: A) => B\n): (...a: A) => Option<B> =>\n(...a) => {\n  try {\n    return some(f(...a))\n  } catch {\n    return none()\n  }\n}\n\n/**\n * Extracts the value of an `Option` or throws an error if the `Option` is\n * `None`, using a custom error factory.\n *\n * **Details**\n *\n * This function allows you to extract the value of an `Option` when it is\n * `Some`. If the `Option` is `None`, it throws an error generated by the\n * provided `onNone` function. This utility is particularly useful when you need\n * a fail-fast behavior for empty `Option` values and want to provide a custom\n * error message or object.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Option } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Option.getOrThrowWith(Option.some(1), () => new Error('Unexpected None')),\n *   1\n * )\n * assert.throws(() => Option.getOrThrowWith(Option.none(), () => new Error('Unexpected None')))\n * ```\n *\n * @see {@link getOrThrow} for a version that throws a default error.\n *\n * @category Conversions\n * @since 2.0.0\n */\nexport const getOrThrowWith: {\n  (onNone: () => unknown): <A>(self: Option<A>) => A\n  <A>(self: Option<A>, onNone: () => unknown): A\n} = dual(2, <A>(self: Option<A>, onNone: () => unknown): A => {\n  if (isSome(self)) {\n    return self.value\n  }\n  throw onNone()\n})\n\n/**\n * Extracts the value of an `Option` or throws a default error if the `Option`\n * is `None`.\n *\n * **Details**\n *\n * This function extracts the value from an `Option` if it is `Some`. If the\n * `Option` is `None`, it throws a default error. It is useful for fail-fast\n * scenarios where the absence of a value is treated as an exceptional case and\n * a default error is sufficient.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Option } from \"effect\"\n *\n * assert.deepStrictEqual(Option.getOrThrow(Option.some(1)), 1)\n * assert.throws(() => Option.getOrThrow(Option.none()))\n * ```\n *\n * @see {@link getOrThrowWith} for a version that allows you to provide a custom error.\n *\n * @category Conversions\n * @since 2.0.0\n */\nexport const getOrThrow: <A>(self: Option<A>) => A = getOrThrowWith(() => new Error(\"getOrThrow called on a None\"))\n\n/**\n * Transforms the value inside a `Some` to a new value using the provided\n * function, while leaving `None` unchanged.\n *\n * **Details**\n *\n * This function applies a mapping function `f` to the value inside an `Option`\n * if it is a `Some`. If the `Option` is `None`, it remains unchanged. The\n * result is a new `Option` with the transformed value (if it was a `Some`) or\n * still `None`.\n *\n * This utility is particularly useful for chaining transformations in a\n * functional way without needing to manually handle `None` cases.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * // Mapping over a `Some`\n * const someValue = Option.some(2)\n *\n * console.log(Option.map(someValue, (n) => n * 2))\n * // Output: { _id: 'Option', _tag: 'Some', value: 4 }\n *\n * // Mapping over a `None`\n * const noneValue = Option.none<number>()\n *\n * console.log(Option.map(noneValue, (n) => n * 2))\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Mapping\n * @since 2.0.0\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): (self: Option<A>) => Option<B>\n  <A, B>(self: Option<A>, f: (a: A) => B): Option<B>\n} = dual(\n  2,\n  <A, B>(self: Option<A>, f: (a: A) => B): Option<B> => isNone(self) ? none() : some(f(self.value))\n)\n\n/**\n * Replaces the value inside a `Some` with the specified constant value, leaving\n * `None` unchanged.\n *\n * **Details**\n *\n * This function transforms an `Option` by replacing the value inside a `Some`\n * with the given constant value `b`. If the `Option` is `None`, it remains\n * unchanged.\n *\n * This is useful when you want to preserve the presence of a value (`Some`) but\n * replace its content with a fixed value.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * // Replacing the value of a `Some`\n * const someValue = Option.some(42)\n *\n * console.log(Option.as(someValue, \"new value\"))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'new value' }\n *\n * // Replacing a `None` (no effect)\n * const noneValue = Option.none<number>()\n *\n * console.log(Option.as(noneValue, \"new value\"))\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Mapping\n * @since 2.0.0\n */\nexport const as: {\n  <B>(b: B): <X>(self: Option<X>) => Option<B>\n  <X, B>(self: Option<X>, b: B): Option<B>\n} = dual(2, <X, B>(self: Option<X>, b: B): Option<B> => map(self, () => b))\n\n/**\n * Replaces the value inside a `Some` with the constant value `void`, leaving\n * `None` unchanged.\n *\n * **Details**\n *\n * This function transforms an `Option` by replacing the value inside a `Some`\n * with `void`. If the `Option` is `None`, it remains unchanged.\n *\n * This is particularly useful in scenarios where the presence or absence of a\n * value is significant, but the actual content of the value is irrelevant.\n *\n * @category Mapping\n * @since 2.0.0\n */\nexport const asVoid: <_>(self: Option<_>) => Option<void> = as(undefined)\n\nconst void_: Option<void> = some(undefined)\nexport {\n  /**\n   * @since 2.0.0\n   */\n  void_ as void\n}\n\n/**\n * Applies a function to the value of a `Some` and flattens the resulting\n * `Option`. If the input is `None`, it remains `None`.\n *\n * **Details**\n *\n * This function allows you to chain computations that return `Option` values.\n * If the input `Option` is `Some`, the provided function `f` is applied to the\n * contained value, and the resulting `Option` is returned. If the input is\n * `None`, the function is not applied, and the result remains `None`.\n *\n * This utility is particularly useful for sequencing operations that may fail\n * or produce optional results, enabling clean and concise workflows for\n * handling such cases.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * interface Address {\n *   readonly city: string\n *   readonly street: Option.Option<string>\n * }\n *\n * interface User {\n *   readonly id: number\n *   readonly username: string\n *   readonly email: Option.Option<string>\n *   readonly address: Option.Option<Address>\n * }\n *\n * const user: User = {\n *   id: 1,\n *   username: \"john_doe\",\n *   email: Option.some(\"john.doe@example.com\"),\n *   address: Option.some({\n *     city: \"New York\",\n *     street: Option.some(\"123 Main St\")\n *   })\n * }\n *\n * // Use flatMap to extract the street value\n * const street = user.address.pipe(\n *   Option.flatMap((address) => address.street)\n * )\n *\n * console.log(street)\n * // Output: { _id: 'Option', _tag: 'Some', value: '123 Main St' }\n * ```\n *\n * @category Sequencing\n * @since 2.0.0\n */\nexport const flatMap: {\n  <A, B>(f: (a: A) => Option<B>): (self: Option<A>) => Option<B>\n  <A, B>(self: Option<A>, f: (a: A) => Option<B>): Option<B>\n} = dual(\n  2,\n  <A, B>(self: Option<A>, f: (a: A) => Option<B>): Option<B> => isNone(self) ? none() : f(self.value)\n)\n\n/**\n * Chains two `Option`s together. The second `Option` can either be a static\n * value or depend on the result of the first `Option`.\n *\n * **Details**\n *\n * This function enables sequencing of two `Option` computations. If the first\n * `Option` is `Some`, the second `Option` is evaluated. The second `Option` can\n * either:\n *\n * - Be a static `Option` value.\n * - Be a function that produces an `Option`, optionally based on the value of\n *   the first `Option`.\n *\n * If the first `Option` is `None`, the function skips the evaluation of the\n * second `Option` and directly returns `None`.\n *\n * @category Sequencing\n * @since 2.0.0\n */\nexport const andThen: {\n  <A, B>(f: (a: A) => Option<B>): (self: Option<A>) => Option<B>\n  <B>(f: Option<B>): <A>(self: Option<A>) => Option<B>\n  <A, B>(f: (a: A) => B): (self: Option<A>) => Option<B>\n  <B>(f: NotFunction<B>): <A>(self: Option<A>) => Option<B>\n  <A, B>(self: Option<A>, f: (a: A) => Option<B>): Option<B>\n  <A, B>(self: Option<A>, f: Option<B>): Option<B>\n  <A, B>(self: Option<A>, f: (a: A) => B): Option<B>\n  <A, B>(self: Option<A>, f: NotFunction<B>): Option<B>\n} = dual(\n  2,\n  <A, B>(self: Option<A>, f: (a: A) => Option<B> | Option<B>): Option<B> =>\n    flatMap(self, (a) => {\n      const b = isFunction(f) ? f(a) : f\n      return isOption(b) ? b : some(b)\n    })\n)\n\n/**\n * Combines `flatMap` and `fromNullable`, transforming the value inside a `Some`\n * using a function that may return `null` or `undefined`.\n *\n * **Details**\n *\n * This function applies a transformation function `f` to the value inside a\n * `Some`. The function `f` may return a value, `null`, or `undefined`. If `f`\n * returns a value, it is wrapped in a `Some`. If `f` returns `null` or\n * `undefined`, the result is `None`. If the input `Option` is `None`, the\n * function is not applied, and `None` is returned.\n *\n * This utility is particularly useful when working with deeply nested optional\n * values or chaining computations that may result in `null` or `undefined` at\n * some point.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * interface Employee {\n *   company?: {\n *     address?: {\n *       street?: {\n *         name?: string\n *       }\n *     }\n *   }\n * }\n *\n * const employee1: Employee = { company: { address: { street: { name: \"high street\" } } } }\n *\n * // Extracting a deeply nested property\n * console.log(\n *   Option.some(employee1)\n *     .pipe(Option.flatMapNullable((employee) => employee.company?.address?.street?.name))\n * )\n * // Output: { _id: 'Option', _tag: 'Some', value: 'high street' }\n *\n * const employee2: Employee = { company: { address: { street: {} } } }\n *\n * // Property does not exist\n * console.log(\n *   Option.some(employee2)\n *     .pipe(Option.flatMapNullable((employee) => employee.company?.address?.street?.name))\n * )\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Sequencing\n * @since 2.0.0\n */\nexport const flatMapNullable: {\n  <A, B>(f: (a: A) => B | null | undefined): (self: Option<A>) => Option<NonNullable<B>>\n  <A, B>(self: Option<A>, f: (a: A) => B | null | undefined): Option<NonNullable<B>>\n} = dual(\n  2,\n  <A, B>(self: Option<A>, f: (a: A) => B | null | undefined): Option<NonNullable<B>> =>\n    isNone(self) ? none() : fromNullable(f(self.value))\n)\n\n/**\n * Flattens an `Option` of `Option` into a single `Option`.\n *\n * **Details**\n *\n * This function takes an `Option` that wraps another `Option` and flattens it\n * into a single `Option`. If the outer `Option` is `Some`, the function\n * extracts the inner `Option`. If the outer `Option` is `None`, the result\n * remains `None`.\n *\n * This is useful for simplifying nested `Option` structures that may arise\n * during functional operations.\n *\n * @category Sequencing\n * @since 2.0.0\n */\nexport const flatten: <A>(self: Option<Option<A>>) => Option<A> = flatMap(identity)\n\n/**\n * Combines two `Option`s, keeping the value from the second `Option` if both\n * are `Some`.\n *\n * **Details**\n *\n * This function takes two `Option`s and returns the second one if the first is\n * `Some`. If the first `Option` is `None`, the result will also be `None`,\n * regardless of the second `Option`. It effectively \"zips\" the two `Option`s\n * while discarding the value from the first `Option`.\n *\n * This is particularly useful when sequencing computations where the result of\n * the first computation is not needed, and you only care about the result of\n * the second computation.\n *\n * @category Zipping\n * @since 2.0.0\n */\nexport const zipRight: {\n  <B>(that: Option<B>): <_>(self: Option<_>) => Option<B>\n  <X, B>(self: Option<X>, that: Option<B>): Option<B>\n} = dual(2, <X, B>(self: Option<X>, that: Option<B>): Option<B> => flatMap(self, () => that))\n\n/**\n * Combines two `Option`s, keeping the value from the first `Option` if both are\n * `Some`.\n *\n * **Details**\n *\n * This function takes two `Option`s and returns the first one if it is `Some`.\n * If either the first `Option` or the second `Option` is `None`, the result\n * will be `None`. This operation \"zips\" the two `Option`s while discarding the\n * value from the second `Option`.\n *\n * This is useful when sequencing computations where the second `Option`\n * represents a dependency or condition that must hold, but its value is\n * irrelevant.\n *\n * @category Zipping\n * @since 2.0.0\n */\nexport const zipLeft: {\n  <_>(that: Option<_>): <A>(self: Option<A>) => Option<A>\n  <A, X>(self: Option<A>, that: Option<X>): Option<A>\n} = dual(2, <A, X>(self: Option<A>, that: Option<X>): Option<A> => tap(self, () => that))\n\n/**\n * Composes two functions that return `Option` values, creating a new function\n * that chains them together.\n *\n * **Details**\n *\n * This function allows you to compose two computations, each represented by a\n * function that returns an `Option`. The result of the first function is passed\n * to the second function if it is `Some`. If the first function returns `None`,\n * the composed function short-circuits and returns `None` without invoking the\n * second function.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * const parse = (s: string): Option.Option<number> => isNaN(Number(s)) ? Option.none() : Option.some(Number(s))\n *\n * const double = (n: number): Option.Option<number> => n > 0 ? Option.some(n * 2) : Option.none()\n *\n * const parseAndDouble = Option.composeK(parse, double)\n *\n * console.log(parseAndDouble(\"42\"))\n * // Output: { _id: 'Option', _tag: 'Some', value: 84 }\n *\n * console.log(parseAndDouble(\"not a number\"))\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Sequencing\n * @since 2.0.0\n */\nexport const composeK: {\n  <B, C>(bfc: (b: B) => Option<C>): <A>(afb: (a: A) => Option<B>) => (a: A) => Option<C>\n  <A, B, C>(afb: (a: A) => Option<B>, bfc: (b: B) => Option<C>): (a: A) => Option<C>\n} = dual(2, <A, B, C>(afb: (a: A) => Option<B>, bfc: (b: B) => Option<C>) => (a: A): Option<C> => flatMap(afb(a), bfc))\n\n/**\n * Applies the provided function `f` to the value of the `Option` if it is\n * `Some` and returns the original `Option`, unless `f` returns `None`, in which\n * case it returns `None`.\n *\n * **Details**\n *\n * This function allows you to perform additional computations on the value of\n * an `Option` without modifying its original value. If the `Option` is `Some`,\n * the provided function `f` is executed with the value, and its result\n * determines whether the original `Option` is returned (`Some`) or the result\n * is `None` if `f` returns `None`. If the input `Option` is `None`, the\n * function is not executed, and `None` is returned.\n *\n * This is particularly useful for applying side conditions or performing\n * validation checks while retaining the original `Option`'s value.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * const getInteger = (n: number) => Number.isInteger(n) ? Option.some(n) : Option.none()\n *\n * console.log(Option.tap(Option.none(), getInteger))\n * // Output: { _id: 'Option', _tag: 'None' }\n *\n * console.log(Option.tap(Option.some(1), getInteger))\n * // Output: { _id: 'Option', _tag: 'Some', value: 1 }\n *\n * console.log(Option.tap(Option.some(1.14), getInteger))\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Sequencing\n * @since 2.0.0\n */\nexport const tap: {\n  <A, X>(f: (a: A) => Option<X>): (self: Option<A>) => Option<A>\n  <A, X>(self: Option<A>, f: (a: A) => Option<X>): Option<A>\n} = dual(2, <A, X>(self: Option<A>, f: (a: A) => Option<X>): Option<A> => flatMap(self, (a) => map(f(a), () => a)))\n\n/**\n * Combines two `Option` values into a single `Option` containing a tuple of\n * their values if both are `Some`.\n *\n * **Details**\n *\n * This function takes two `Option`s and combines their values into a tuple `[A,\n * B]` if both are `Some`. If either of the `Option`s is `None`, the result is\n * `None`. This is particularly useful for combining multiple `Option` values\n * into a single one, ensuring both contain valid values.\n *\n * @category Combining\n * @since 2.0.0\n */\nexport const product = <A, B>(self: Option<A>, that: Option<B>): Option<[A, B]> =>\n  isSome(self) && isSome(that) ? some([self.value, that.value]) : none()\n\n/**\n * Combines an `Option` with a collection of `Option`s into a single `Option`\n * containing a tuple of their values if all are `Some`.\n *\n * **Details**\n *\n * This function takes a primary `Option` and a collection of `Option`s and\n * combines their values into a tuple `[A, ...Array<A>]` if all are `Some`. If\n * the primary `Option` or any `Option` in the collection is `None`, the result\n * is `None`.\n *\n * @category Combining\n * @since 2.0.0\n */\nexport const productMany = <A>(\n  self: Option<A>,\n  collection: Iterable<Option<A>>\n): Option<[A, ...Array<A>]> => {\n  if (isNone(self)) {\n    return none()\n  }\n  const out: [A, ...Array<A>] = [self.value]\n  for (const o of collection) {\n    if (isNone(o)) {\n      return none()\n    }\n    out.push(o.value)\n  }\n  return some(out)\n}\n\n/**\n * Combines a structure of `Option`s into a single `Option` containing the\n * values with the same structure.\n *\n * **Details**\n *\n * This function takes a structure of `Option`s (a tuple, struct, or iterable)\n * and produces a single `Option` that contains the values from the input\n * structure if all `Option`s are `Some`. If any `Option` in the input is\n * `None`, the result is `None`. The structure of the input is preserved in the\n * output.\n *\n * - If the input is a tuple (e.g., an array), the result will be an `Option`\n *   containing a tuple with the same length.\n * - If the input is a struct (e.g., an object), the result will be an `Option`\n *   containing a struct with the same keys.\n * - If the input is an iterable, the result will be an `Option` containing an\n *   array.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * const maybeName: Option.Option<string> = Option.some(\"John\")\n * const maybeAge: Option.Option<number> = Option.some(25)\n *\n * //      ┌─── Option<[string, number]>\n * //      ▼\n * const tuple = Option.all([maybeName, maybeAge])\n * console.log(tuple)\n * // Output:\n * // { _id: 'Option', _tag: 'Some', value: [ 'John', 25 ] }\n *\n * //      ┌─── Option<{ name: string; age: number; }>\n * //      ▼\n * const struct = Option.all({ name: maybeName, age: maybeAge })\n * console.log(struct)\n * // Output:\n * // { _id: 'Option', _tag: 'Some', value: { name: 'John', age: 25 } }\n * ```\n *\n * @category Combining\n * @since 2.0.0\n */\n// @ts-expect-error\nexport const all: <const I extends Iterable<Option<any>> | Record<string, Option<any>>>(\n  input: I\n) => [I] extends [ReadonlyArray<Option<any>>] ? Option<\n    { -readonly [K in keyof I]: [I[K]] extends [Option<infer A>] ? A : never }\n  >\n  : [I] extends [Iterable<Option<infer A>>] ? Option<Array<A>>\n  : Option<{ -readonly [K in keyof I]: [I[K]] extends [Option<infer A>] ? A : never }> = (\n    input: Iterable<Option<any>> | Record<string, Option<any>>\n  ): Option<any> => {\n    if (Symbol.iterator in input) {\n      const out: Array<Option<any>> = []\n      for (const o of (input as Iterable<Option<any>>)) {\n        if (isNone(o)) {\n          return none()\n        }\n        out.push(o.value)\n      }\n      return some(out)\n    }\n\n    const out: Record<string, any> = {}\n    for (const key of Object.keys(input)) {\n      const o = input[key]\n      if (isNone(o)) {\n        return none()\n      }\n      out[key] = o.value\n    }\n    return some(out)\n  }\n\n/**\n * Combines two `Option` values into a new `Option` by applying a provided\n * function to their values.\n *\n * **Details**\n *\n * This function takes two `Option` values (`self` and `that`) and a combining\n * function `f`. If both `Option` values are `Some`, the function `f` is applied\n * to their values, and the result is wrapped in a new `Some`. If either\n * `Option` is `None`, the result is `None`.\n *\n * This utility is useful for combining two optional computations into a single\n * result while maintaining type safety and avoiding explicit checks for `None`.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * const maybeName: Option.Option<string> = Option.some(\"John\")\n * const maybeAge: Option.Option<number> = Option.some(25)\n *\n * // Combine the name and age into a person object\n * const person = Option.zipWith(maybeName, maybeAge, (name, age) => ({\n *   name: name.toUpperCase(),\n *   age\n * }))\n *\n * console.log(person)\n * // Output:\n * // { _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }\n * ```\n *\n * @category Zipping\n * @since 2.0.0\n */\nexport const zipWith: {\n  <B, A, C>(that: Option<B>, f: (a: A, b: B) => C): (self: Option<A>) => Option<C>\n  <A, B, C>(self: Option<A>, that: Option<B>, f: (a: A, b: B) => C): Option<C>\n} = dual(\n  3,\n  <A, B, C>(self: Option<A>, that: Option<B>, f: (a: A, b: B) => C): Option<C> =>\n    map(product(self, that), ([a, b]) => f(a, b))\n)\n\n/**\n * Applies a function inside a `Some` to a value inside another `Some`,\n * combining them into a new `Option`.\n *\n * **Details**\n *\n * This function allows you to apply a function wrapped in an `Option` (`self`)\n * to a value wrapped in another `Option` (`that`). If both `Option`s are\n * `Some`, the function is applied to the value, and the result is wrapped in a\n * new `Some`. If either `Option` is `None`, the result is `None`.\n *\n * @category Combining\n * @since 2.0.0\n */\nexport const ap: {\n  <A>(that: Option<A>): <B>(self: Option<(a: A) => B>) => Option<B>\n  <A, B>(self: Option<(a: A) => B>, that: Option<A>): Option<B>\n} = dual(2, <A, B>(self: Option<(a: A) => B>, that: Option<A>): Option<B> => zipWith(self, that, (f, a) => f(a)))\n\n/**\n * Reduces an `Iterable` of `Option<A>` to a single value of type `B`, ignoring\n * elements that are `None`.\n *\n * **Details**\n *\n * This function takes an initial value of type `B` and a reducing function `f`\n * that combines the accumulator with values of type `A`. It processes an\n * iterable of `Option<A>`, applying `f` only to the `Some` values while\n * ignoring the `None` values. The result is a single value of type `B`.\n *\n * This utility is particularly useful for aggregating values from an iterable\n * of `Option`s while skipping the absent (`None`) values.\n *\n * @example\n * ```ts\n * import { Option, pipe } from \"effect\"\n *\n * const iterable = [Option.some(1), Option.none(), Option.some(2), Option.none()]\n *\n * console.log(pipe(iterable, Option.reduceCompact(0, (b, a) => b + a)))\n * // Output: 3\n * ```\n *\n * @category Reducing\n * @since 2.0.0\n */\nexport const reduceCompact: {\n  <B, A>(b: B, f: (b: B, a: A) => B): (self: Iterable<Option<A>>) => B\n  <A, B>(self: Iterable<Option<A>>, b: B, f: (b: B, a: A) => B): B\n} = dual(\n  3,\n  <A, B>(self: Iterable<Option<A>>, b: B, f: (b: B, a: A) => B): B => {\n    let out: B = b\n    for (const oa of self) {\n      if (isSome(oa)) {\n        out = f(out, oa.value)\n      }\n    }\n    return out\n  }\n)\n\n/**\n * Converts an `Option` into an `Array`.\n * If the input is `None`, an empty array is returned.\n * If the input is `Some`, its value is wrapped in a single-element array.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.toArray(Option.some(1)))\n * // Output: [1]\n *\n * console.log(Option.toArray(Option.none()))\n * // Output: []\n * ```\n *\n * @category Conversions\n * @since 2.0.0\n */\nexport const toArray = <A>(self: Option<A>): Array<A> => isNone(self) ? [] : [self.value]\n\n/**\n * Splits an `Option` into two `Option`s based on the result of a mapping\n * function that produces an `Either`.\n *\n * **Details**\n *\n * This function takes an `Option` and a mapping function `f` that converts its\n * value into an `Either`. It returns a tuple of two `Option`s:\n *\n * - The first `Option` (`left`) contains the value from the `Left` side of the\n *   `Either` if it exists, otherwise `None`.\n * - The second `Option` (`right`) contains the value from the `Right` side of\n *   the `Either` if it exists, otherwise `None`.\n *\n * If the input `Option` is `None`, both returned `Option`s are `None`.\n *\n * This utility is useful for filtering and categorizing the contents of an\n * `Option` based on a bifurcating computation.\n *\n * @category Filtering\n * @since 2.0.0\n */\nexport const partitionMap: {\n  <A, B, C>(f: (a: A) => Either<C, B>): (self: Option<A>) => [left: Option<B>, right: Option<C>]\n  <A, B, C>(self: Option<A>, f: (a: A) => Either<C, B>): [left: Option<B>, right: Option<C>]\n} = dual(2, <A, B, C>(\n  self: Option<A>,\n  f: (a: A) => Either<C, B>\n): [excluded: Option<B>, satisfying: Option<C>] => {\n  if (isNone(self)) {\n    return [none(), none()]\n  }\n  const e = f(self.value)\n  return either.isLeft(e) ? [some(e.left), none()] : [none(), some(e.right)]\n})\n\n// TODO(4.0): remove?\n/**\n * Alias of {@link flatMap}.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * // Transform and filter numbers\n * const transformEven = (n: Option.Option<number>): Option.Option<string> =>\n *   Option.filterMap(n, (n) => (n % 2 === 0 ? Option.some(`Even: ${n}`) : Option.none()))\n *\n * console.log(transformEven(Option.none()))\n * // Output: { _id: 'Option', _tag: 'None' }\n *\n * console.log(transformEven(Option.some(1)))\n * // Output: { _id: 'Option', _tag: 'None' }\n *\n * console.log(transformEven(Option.some(2)))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'Even: 2' }\n * ```\n *\n * @category Filtering\n * @since 2.0.0\n */\nexport const filterMap: {\n  <A, B>(f: (a: A) => Option<B>): (self: Option<A>) => Option<B>\n  <A, B>(self: Option<A>, f: (a: A) => Option<B>): Option<B>\n} = flatMap\n\n/**\n * Filters an `Option` using a predicate. If the predicate is not satisfied or the `Option` is `None` returns `None`.\n *\n * If you need to change the type of the `Option` in addition to filtering, see `filterMap`.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * const removeEmptyString = (input: Option.Option<string>) =>\n *   Option.filter(input, (value) => value !== \"\")\n *\n * console.log(removeEmptyString(Option.none()))\n * // Output: { _id: 'Option', _tag: 'None' }\n *\n * console.log(removeEmptyString(Option.some(\"\")))\n * // Output: { _id: 'Option', _tag: 'None' }\n *\n * console.log(removeEmptyString(Option.some(\"a\")))\n * // Output: { _id: 'Option', _tag: 'Some', value: 'a' }\n * ```\n *\n * @category Filtering\n * @since 2.0.0\n */\nexport const filter: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Option<A>) => Option<B>\n  <A>(predicate: Predicate<NoInfer<A>>): (self: Option<A>) => Option<A>\n  <A, B extends A>(self: Option<A>, refinement: Refinement<A, B>): Option<B>\n  <A>(self: Option<A>, predicate: Predicate<A>): Option<A>\n} = dual(\n  2,\n  <A>(self: Option<A>, predicate: Predicate<A>): Option<A> =>\n    filterMap(self, (b) => (predicate(b) ? option.some(b) : option.none))\n)\n\n/**\n * Creates an `Equivalence` instance for comparing `Option` values, using a\n * provided `Equivalence` for the inner type.\n *\n * **Details**\n *\n * This function takes an `Equivalence` instance for a specific type `A` and\n * produces an `Equivalence` instance for `Option<A>`. The resulting\n * `Equivalence` determines whether two `Option` values are equivalent:\n *\n * - Two `None`s are considered equivalent.\n * - A `Some` and a `None` are not equivalent.\n * - Two `Some` values are equivalent if their inner values are equivalent\n *   according to the provided `Equivalence`.\n *\n * **Example** (Comparing Optional Numbers for Equivalence)\n *\n * ```ts\n * import { Number, Option } from \"effect\"\n *\n * const isEquivalent = Option.getEquivalence(Number.Equivalence)\n *\n * console.log(isEquivalent(Option.none(), Option.none()))\n * // Output: true\n *\n * console.log(isEquivalent(Option.none(), Option.some(1)))\n * // Output: false\n *\n * console.log(isEquivalent(Option.some(1), Option.none()))\n * // Output: false\n *\n * console.log(isEquivalent(Option.some(1), Option.some(2)))\n * // Output: false\n *\n * console.log(isEquivalent(Option.some(1), Option.some(1)))\n * // Output: true\n * ```\n *\n * @category Equivalence\n * @since 2.0.0\n */\nexport const getEquivalence = <A>(isEquivalent: Equivalence.Equivalence<A>): Equivalence.Equivalence<Option<A>> =>\n  Equivalence.make((x, y) => isNone(x) ? isNone(y) : isNone(y) ? false : isEquivalent(x.value, y.value))\n\n/**\n * Creates an `Order` instance for comparing `Option` values, using a provided\n * `Order` for the inner type.\n *\n * **Details**\n *\n * This function produces an `Order` instance for `Option<A>`, allowing `Option`\n * values to be compared:\n *\n * - `None` is always considered less than any `Some` value.\n * - If both are `Some`, their inner values are compared using the provided\n *   `Order` instance.\n *\n * @example\n * ```ts\n * import { Number, Option } from \"effect\"\n *\n * const order = Option.getOrder(Number.Order)\n *\n * console.log(order(Option.none(), Option.none()))\n * // Output: 0\n *\n * console.log(order(Option.none(), Option.some(1)))\n * // Output: -1\n *\n * console.log(order(Option.some(1), Option.none()))\n * // Output: 1\n *\n * console.log(order(Option.some(1), Option.some(2)))\n * // Output: -1\n *\n * console.log(order(Option.some(1), Option.some(1)))\n * // Output: 0\n * ```\n *\n * @category Sorting\n * @since 2.0.0\n */\nexport const getOrder = <A>(O: Order<A>): Order<Option<A>> =>\n  order.make((self, that) => isSome(self) ? (isSome(that) ? O(self.value, that.value) : 1) : -1)\n\n/**\n * Lifts a binary function to work with `Option` values, allowing the function\n * to operate on two `Option`s.\n *\n * **Details**\n *\n * This function takes a binary function `f` and returns a new function that\n * applies `f` to the values of two `Option`s (`self` and `that`). If both\n * `Option`s are `Some`, the binary function `f` is applied to their values, and\n * the result is wrapped in a new `Some`. If either `Option` is `None`, the\n * result is `None`.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * // A binary function to add two numbers\n * const add = (a: number, b: number): number => a + b\n *\n * // Lift the `add` function to work with `Option` values\n * const addOptions = Option.lift2(add)\n *\n * // Both `Option`s are `Some`\n * console.log(addOptions(Option.some(2), Option.some(3)))\n * // Output: { _id: 'Option', _tag: 'Some', value: 5 }\n *\n * // One `Option` is `None`\n * console.log(addOptions(Option.some(2), Option.none()))\n * // Output: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Lifting\n * @since 2.0.0\n */\nexport const lift2 = <A, B, C>(f: (a: A, b: B) => C): {\n  (that: Option<B>): (self: Option<A>) => Option<C>\n  (self: Option<A>, that: Option<B>): Option<C>\n} => dual(2, (self: Option<A>, that: Option<B>): Option<C> => zipWith(self, that, f))\n\n/**\n * Lifts a `Predicate` or `Refinement` into the `Option` context, returning a\n * `Some` of the input value if the predicate is satisfied, or `None` otherwise.\n *\n * **Details**\n *\n * This function transforms a `Predicate` (or a more specific `Refinement`) into\n * a function that produces an `Option`. If the predicate evaluates to `true`,\n * the input value is wrapped in a `Some`. If the predicate evaluates to\n * `false`, the result is `None`.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * // Check if a number is positive\n * const isPositive = (n: number) => n > 0\n *\n * //      ┌─── (b: number) => Option<number>\n * //      ▼\n * const parsePositive = Option.liftPredicate(isPositive)\n *\n * console.log(parsePositive(1))\n * // Output: { _id: 'Option', _tag: 'Some', value: 1 }\n *\n * console.log(parsePositive(-1))\n * // OUtput: { _id: 'Option', _tag: 'None' }\n * ```\n *\n * @category Lifting\n * @since 2.0.0\n */\nexport const liftPredicate: { // Note: I intentionally avoid using the NoInfer pattern here.\n  <A, B extends A>(refinement: Refinement<A, B>): (a: A) => Option<B>\n  <B extends A, A = B>(predicate: Predicate<A>): (b: B) => Option<B>\n  <A, B extends A>(\n    self: A,\n    refinement: Refinement<A, B>\n  ): Option<B>\n  <B extends A, A = B>(\n    self: B,\n    predicate: Predicate<A>\n  ): Option<B>\n} = dual(\n  2,\n  <B extends A, A = B>(b: B, predicate: Predicate<A>): Option<B> => predicate(b) ? some(b) : none()\n)\n\n/**\n * Returns a function that checks if an `Option` contains a specified value,\n * using a provided equivalence function.\n *\n * **Details**\n *\n * This function allows you to check whether an `Option` contains a specific\n * value. It uses an equivalence function `isEquivalent` to compare the value\n * inside the `Option` to the provided value. If the `Option` is `Some` and the\n * equivalence function returns `true`, the result is `true`. If the `Option` is\n * `None` or the values are not equivalent, the result is `false`.\n *\n * @example\n * ```ts\n * import { Number, Option } from \"effect\"\n *\n * const contains = Option.containsWith(Number.Equivalence)\n *\n * console.log(Option.some(2).pipe(contains(2)))\n * // Output: true\n *\n * console.log(Option.some(1).pipe(contains(2)))\n * // Output: false\n *\n * console.log(Option.none().pipe(contains(2)))\n * // Output: false\n * ```\n *\n * @see {@link contains} for a version that uses the default `Equivalence`.\n *\n * @category Elements\n * @since 2.0.0\n */\nexport const containsWith = <A>(isEquivalent: (self: A, that: A) => boolean): {\n  (a: A): (self: Option<A>) => boolean\n  (self: Option<A>, a: A): boolean\n} => dual(2, (self: Option<A>, a: A): boolean => isNone(self) ? false : isEquivalent(self.value, a))\n\nconst _equivalence = Equal.equivalence()\n\n/**\n * Returns a function that checks if an `Option` contains a specified value\n * using the default `Equivalence`.\n *\n * **Details**\n *\n * This function allows you to check whether an `Option` contains a specific\n * value. It uses the default `Equivalence` for equality comparison. If the\n * `Option` is `Some` and its value is equivalent to the provided value, the\n * result is `true`. If the `Option` is `None` or the values are not equivalent,\n * the result is `false`.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * console.log(Option.some(2).pipe(Option.contains(2)))\n * // Output: true\n *\n * console.log(Option.some(1).pipe(Option.contains(2)))\n * // Output: false\n *\n * console.log(Option.none().pipe(Option.contains(2)))\n * // Output: false\n * ```\n *\n * @see {@link containsWith} for a version that allows you to specify a custom equivalence function.\n *\n * @category Elements\n * @since 2.0.0\n */\nexport const contains: {\n  <A>(a: A): (self: Option<A>) => boolean\n  <A>(self: Option<A>, a: A): boolean\n} = containsWith(_equivalence)\n\n/**\n * Checks if a value in an `Option` satisfies a given predicate or refinement.\n *\n * **Details**\n *\n * This function allows you to check if a value inside a `Some` meets a\n * specified condition. If the `Option` is `None`, the result is `false`. If the\n * `Option` is `Some`, the provided predicate or refinement is applied to the\n * value:\n *\n * - If the condition is met, the result is `true`.\n * - If the condition is not met, the result is `false`.\n *\n * @example\n * ```ts\n * import { Option } from \"effect\"\n *\n * const isEven = (n: number) => n % 2 === 0\n *\n * console.log(Option.some(2).pipe(Option.exists(isEven)))\n * // Output: true\n *\n * console.log(Option.some(1).pipe(Option.exists(isEven)))\n * // Output: false\n *\n * console.log(Option.none().pipe(Option.exists(isEven)))\n * // Output: false\n * ```\n *\n * @category Elements\n * @since 2.0.0\n */\nexport const exists: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Option<A>) => self is Option<B>\n  <A>(predicate: Predicate<NoInfer<A>>): (self: Option<A>) => boolean\n  <A, B extends A>(self: Option<A>, refinement: Refinement<A, B>): self is Option<B>\n  <A>(self: Option<A>, predicate: Predicate<A>): boolean\n} = dual(\n  2,\n  <A, B extends A>(self: Option<A>, refinement: Refinement<A, B>): self is Option<B> =>\n    isNone(self) ? false : refinement(self.value)\n)\n\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Option` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n * 5. Regular `Option` functions like `map` and `filter` can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Option, pipe } from \"effect\"\n *\n * const result = pipe(\n *   Option.Do,\n *   Option.bind(\"x\", () => Option.some(2)),\n *   Option.bind(\"y\", () => Option.some(3)),\n *   Option.let(\"sum\", ({ x, y }) => x + y),\n *   Option.filter(({ x, y }) => x * y > 5)\n * )\n * assert.deepStrictEqual(result, Option.some({ x: 2, y: 3, sum: 5 }))\n * ```\n *\n * @see {@link Do}\n * @see {@link bind}\n * @see {@link let_ let}\n *\n * @category Do notation\n * @since 2.0.0\n */\nexport const bindTo: {\n  <N extends string>(name: N): <A>(self: Option<A>) => Option<{ [K in N]: A }>\n  <A, N extends string>(self: Option<A>, name: N): Option<{ [K in N]: A }>\n} = doNotation.bindTo<OptionTypeLambda>(map)\n\nconst let_: {\n  <N extends string, A extends object, B>(\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): (self: Option<A>) => Option<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }>\n  <A extends object, N extends string, B>(\n    self: Option<A>,\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): Option<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }>\n} = doNotation.let_<OptionTypeLambda>(map)\n\nexport {\n  /**\n   * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n   *\n   * Here's how the do simulation works:\n   *\n   * 1. Start the do simulation using the `Do` value\n   * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Option` values\n   * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n   * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n   * 5. Regular `Option` functions like `map` and `filter` can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope\n   *\n   * @example\n   * ```ts\n   * import * as assert from \"node:assert\"\n   * import { Option, pipe } from \"effect\"\n   *\n   * const result = pipe(\n   *   Option.Do,\n   *   Option.bind(\"x\", () => Option.some(2)),\n   *   Option.bind(\"y\", () => Option.some(3)),\n   *   Option.let(\"sum\", ({ x, y }) => x + y),\n   *   Option.filter(({ x, y }) => x * y > 5)\n   * )\n   * assert.deepStrictEqual(result, Option.some({ x: 2, y: 3, sum: 5 }))\n   * ```\n   *\n   * @see {@link Do}\n   * @see {@link bind}\n   * @see {@link bindTo}\n   *\n   * @category Do notation\n   * @since 2.0.0\n   */\n  let_ as let\n}\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Option` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n * 5. Regular `Option` functions like `map` and `filter` can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Option, pipe } from \"effect\"\n *\n * const result = pipe(\n *   Option.Do,\n *   Option.bind(\"x\", () => Option.some(2)),\n *   Option.bind(\"y\", () => Option.some(3)),\n *   Option.let(\"sum\", ({ x, y }) => x + y),\n *   Option.filter(({ x, y }) => x * y > 5)\n * )\n * assert.deepStrictEqual(result, Option.some({ x: 2, y: 3, sum: 5 }))\n * ```\n *\n * @see {@link Do}\n * @see {@link bindTo}\n * @see {@link let_ let}\n *\n * @category Do notation\n * @since 2.0.0\n */\nexport const bind: {\n  <N extends string, A extends object, B>(\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => Option<B>\n  ): (self: Option<A>) => Option<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }>\n  <A extends object, N extends string, B>(\n    self: Option<A>,\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => Option<B>\n  ): Option<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }>\n} = doNotation.bind<OptionTypeLambda>(map, flatMap)\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Option` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n * 5. Regular `Option` functions like `map` and `filter` can still be used within the do simulation. These functions will receive the accumulated variables as arguments within the scope\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Option, pipe } from \"effect\"\n *\n * const result = pipe(\n *   Option.Do,\n *   Option.bind(\"x\", () => Option.some(2)),\n *   Option.bind(\"y\", () => Option.some(3)),\n *   Option.let(\"sum\", ({ x, y }) => x + y),\n *   Option.filter(({ x, y }) => x * y > 5)\n * )\n * assert.deepStrictEqual(result, Option.some({ x: 2, y: 3, sum: 5 }))\n * ```\n *\n * @see {@link bindTo}\n * @see {@link bind}\n * @see {@link let_ let}\n *\n * @category Do notation\n * @since 2.0.0\n */\nexport const Do: Option<{}> = some({})\n\nconst adapter = Gen.adapter<OptionTypeLambda>()\n\n/**\n * Similar to `Effect.gen`, `Option.gen` provides a more readable,\n * generator-based syntax for working with `Option` values, making code that\n * involves `Option` easier to write and understand. This approach is similar to\n * using `async/await` but tailored for `Option`.\n *\n * **Example** (Using `Option.gen` to Create a Combined Value)\n *\n * ```ts\n * import { Option } from \"effect\"\n *\n * const maybeName: Option.Option<string> = Option.some(\"John\")\n * const maybeAge: Option.Option<number> = Option.some(25)\n *\n * const person = Option.gen(function* () {\n *   const name = (yield* maybeName).toUpperCase()\n *   const age = yield* maybeAge\n *   return { name, age }\n * })\n *\n * console.log(person)\n * // Output:\n * // { _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }\n * ```\n *\n * @category Generators\n * @since 2.0.0\n */\nexport const gen: Gen.Gen<OptionTypeLambda, Gen.Adapter<OptionTypeLambda>> = (...args) => {\n  const f = args.length === 1 ? args[0] : args[1].bind(args[0])\n  const iterator = f(adapter)\n  let state: IteratorResult<any> = iterator.next()\n  while (!state.done) {\n    const current = Gen.isGenKind(state.value)\n      ? state.value.value\n      : Gen.yieldWrapGet(state.value)\n    if (isNone(current)) {\n      return current\n    }\n    state = iterator.next(current.value as never)\n  }\n  return some(state.value)\n}\n\n/**\n * Merges two optional values, applying a function if both exist.\n * Unlike {@link zipWith}, this function returns `None` only if both inputs are `None`.\n *\n * @internal\n */\nexport const mergeWith = <A>(f: (a1: A, a2: A) => A) => (o1: Option<A>, o2: Option<A>): Option<A> => {\n  if (isNone(o1)) {\n    return o2\n  } else if (isNone(o2)) {\n    return o1\n  }\n  return some(f(o1.value, o2.value))\n}\n"
  },
  {
    "path": "packages/effect/src/Order.ts",
    "content": "/**\n * This module provides an implementation of the `Order` type class which is used to define a total ordering on some type `A`.\n * An order is defined by a relation `<=`, which obeys the following laws:\n *\n * - either `x <= y` or `y <= x` (totality)\n * - if `x <= y` and `y <= x`, then `x == y` (antisymmetry)\n * - if `x <= y` and `y <= z`, then `x <= z` (transitivity)\n *\n * The truth table for compare is defined as follows:\n *\n * | `x <= y` | `x >= y` | Ordering |                       |\n * | -------- | -------- | -------- | --------------------- |\n * | `true`   | `true`   | `0`      | corresponds to x == y |\n * | `true`   | `false`  | `< 0`    | corresponds to x < y  |\n * | `false`  | `true`   | `> 0`    | corresponds to x > y  |\n *\n * @since 2.0.0\n */\nimport { dual } from \"./Function.js\"\nimport type { TypeLambda } from \"./HKT.js\"\n\n/**\n * @category type class\n * @since 2.0.0\n */\nexport interface Order<in A> {\n  (self: A, that: A): -1 | 0 | 1\n}\n\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface OrderTypeLambda extends TypeLambda {\n  readonly type: Order<this[\"Target\"]>\n}\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport const make = <A>(\n  compare: (self: A, that: A) => -1 | 0 | 1\n): Order<A> =>\n(self, that) => self === that ? 0 : compare(self, that)\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const string: Order<string> = make((self, that) => self < that ? -1 : 1)\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const number: Order<number> = make((self, that) => self < that ? -1 : 1)\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const boolean: Order<boolean> = make((self, that) => self < that ? -1 : 1)\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const bigint: Order<bigint> = make((self, that) => self < that ? -1 : 1)\n\n/**\n * @since 2.0.0\n */\nexport const reverse = <A>(O: Order<A>): Order<A> => make((self, that) => O(that, self))\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const combine: {\n  <A>(that: Order<A>): (self: Order<A>) => Order<A>\n  <A>(self: Order<A>, that: Order<A>): Order<A>\n} = dual(2, <A>(self: Order<A>, that: Order<A>): Order<A> =>\n  make((a1, a2) => {\n    const out = self(a1, a2)\n    if (out !== 0) {\n      return out\n    }\n    return that(a1, a2)\n  }))\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const combineMany: {\n  <A>(collection: Iterable<Order<A>>): (self: Order<A>) => Order<A>\n  <A>(self: Order<A>, collection: Iterable<Order<A>>): Order<A>\n} = dual(2, <A>(self: Order<A>, collection: Iterable<Order<A>>): Order<A> =>\n  make((a1, a2) => {\n    let out = self(a1, a2)\n    if (out !== 0) {\n      return out\n    }\n    for (const O of collection) {\n      out = O(a1, a2)\n      if (out !== 0) {\n        return out\n      }\n    }\n    return out\n  }))\n\n/**\n * @since 2.0.0\n */\nexport const empty = <A>(): Order<A> => make(() => 0)\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const combineAll = <A>(collection: Iterable<Order<A>>): Order<A> => combineMany(empty(), collection)\n\n/**\n * @category mapping\n * @since 2.0.0\n */\nexport const mapInput: {\n  <B, A>(f: (b: B) => A): (self: Order<A>) => Order<B>\n  <A, B>(self: Order<A>, f: (b: B) => A): Order<B>\n} = dual(\n  2,\n  <A, B>(self: Order<A>, f: (b: B) => A): Order<B> => make((b1, b2) => self(f(b1), f(b2)))\n)\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Date: Order<Date> = mapInput(number, (date) => date.getTime())\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const product: {\n  <B>(that: Order<B>): <A>(self: Order<A>) => Order<readonly [A, B]> // readonly because invariant\n  <A, B>(self: Order<A>, that: Order<B>): Order<readonly [A, B]> // readonly because invariant\n} = dual(2, <A, B>(self: Order<A>, that: Order<B>): Order<readonly [A, B]> =>\n  make(([xa, xb], [ya, yb]) => {\n    const o = self(xa, ya)\n    return o !== 0 ? o : that(xb, yb)\n  }))\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const all = <A>(collection: Iterable<Order<A>>): Order<ReadonlyArray<A>> => {\n  return make((x, y) => {\n    const len = Math.min(x.length, y.length)\n    let collectionLength = 0\n    for (const O of collection) {\n      if (collectionLength >= len) {\n        break\n      }\n      const o = O(x[collectionLength], y[collectionLength])\n      if (o !== 0) {\n        return o\n      }\n      collectionLength++\n    }\n    return 0\n  })\n}\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const productMany: {\n  <A>(collection: Iterable<Order<A>>): (self: Order<A>) => Order<readonly [A, ...Array<A>]> // readonly because invariant\n  <A>(self: Order<A>, collection: Iterable<Order<A>>): Order<readonly [A, ...Array<A>]> // readonly because invariant\n} = dual(2, <A>(self: Order<A>, collection: Iterable<Order<A>>): Order<readonly [A, ...Array<A>]> => {\n  const O = all(collection)\n  return make((x, y) => {\n    const o = self(x[0], y[0])\n    return o !== 0 ? o : O(x.slice(1), y.slice(1))\n  })\n})\n\n/**\n * Similar to `Promise.all` but operates on `Order`s.\n *\n * ```\n * [Order<A>, Order<B>, ...] -> Order<[A, B, ...]>\n * ```\n *\n * This function creates and returns a new `Order` for a tuple of values based on the given `Order`s for each element in the tuple.\n * The returned `Order` compares two tuples of the same type by applying the corresponding `Order` to each element in the tuple.\n * It is useful when you need to compare two tuples of the same type and you have a specific way of comparing each element\n * of the tuple.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const tuple = <T extends ReadonlyArray<Order<any>>>(\n  ...elements: T\n): Order<Readonly<{ [I in keyof T]: [T[I]] extends [Order<infer A>] ? A : never }>> => all(elements) as any\n\n/**\n * This function creates and returns a new `Order` for an array of values based on a given `Order` for the elements of the array.\n * The returned `Order` compares two arrays by applying the given `Order` to each element in the arrays.\n * If all elements are equal, the arrays are then compared based on their length.\n * It is useful when you need to compare two arrays of the same type and you have a specific way of comparing each element of the array.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const array = <A>(O: Order<A>): Order<ReadonlyArray<A>> =>\n  make((self, that) => {\n    const aLen = self.length\n    const bLen = that.length\n    const len = Math.min(aLen, bLen)\n    for (let i = 0; i < len; i++) {\n      const o = O(self[i], that[i])\n      if (o !== 0) {\n        return o\n      }\n    }\n    return number(aLen, bLen)\n  })\n\n/**\n * This function creates and returns a new `Order` for a struct of values based on the given `Order`s\n * for each property in the struct.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const struct = <R extends { readonly [x: string]: Order<any> }>(\n  fields: R\n): Order<{ [K in keyof R]: [R[K]] extends [Order<infer A>] ? A : never }> => {\n  const keys = Object.keys(fields)\n  return make((self, that) => {\n    for (const key of keys) {\n      const o = fields[key](self[key], that[key])\n      if (o !== 0) {\n        return o\n      }\n    }\n    return 0\n  })\n}\n\n/**\n * Test whether one value is _strictly less than_ another.\n *\n * @since 2.0.0\n */\nexport const lessThan = <A>(O: Order<A>): {\n  (that: A): (self: A) => boolean\n  (self: A, that: A): boolean\n} => dual(2, (self: A, that: A) => O(self, that) === -1)\n\n/**\n * Test whether one value is _strictly greater than_ another.\n *\n * @since 2.0.0\n */\nexport const greaterThan = <A>(O: Order<A>): {\n  (that: A): (self: A) => boolean\n  (self: A, that: A): boolean\n} => dual(2, (self: A, that: A) => O(self, that) === 1)\n\n/**\n * Test whether one value is _non-strictly less than_ another.\n *\n * @since 2.0.0\n */\nexport const lessThanOrEqualTo = <A>(O: Order<A>): {\n  (that: A): (self: A) => boolean\n  (self: A, that: A): boolean\n} => dual(2, (self: A, that: A) => O(self, that) !== 1)\n\n/**\n * Test whether one value is _non-strictly greater than_ another.\n *\n * @since 2.0.0\n */\nexport const greaterThanOrEqualTo = <A>(O: Order<A>): {\n  (that: A): (self: A) => boolean\n  (self: A, that: A): boolean\n} => dual(2, (self: A, that: A) => O(self, that) !== -1)\n\n/**\n * Take the minimum of two values. If they are considered equal, the first argument is chosen.\n *\n * @since 2.0.0\n */\nexport const min = <A>(O: Order<A>): {\n  (that: A): (self: A) => A\n  (self: A, that: A): A\n} => dual(2, (self: A, that: A) => self === that || O(self, that) < 1 ? self : that)\n\n/**\n * Take the maximum of two values. If they are considered equal, the first argument is chosen.\n *\n * @since 2.0.0\n */\nexport const max = <A>(O: Order<A>): {\n  (that: A): (self: A) => A\n  (self: A, that: A): A\n} => dual(2, (self: A, that: A) => self === that || O(self, that) > -1 ? self : that)\n\n/**\n * Clamp a value between a minimum and a maximum.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Order, Number } from \"effect\"\n *\n * const clamp = Order.clamp(Number.Order)({ minimum: 1, maximum: 5 })\n *\n * assert.equal(clamp(3), 3)\n * assert.equal(clamp(0), 1)\n * assert.equal(clamp(6), 5)\n * ```\n *\n * @since 2.0.0\n */\nexport const clamp = <A>(O: Order<A>): {\n  (options: {\n    minimum: A\n    maximum: A\n  }): (self: A) => A\n  (self: A, options: {\n    minimum: A\n    maximum: A\n  }): A\n} =>\n  dual(\n    2,\n    (self: A, options: {\n      minimum: A\n      maximum: A\n    }): A => min(O)(options.maximum, max(O)(options.minimum, self))\n  )\n\n/**\n * Test whether a value is between a minimum and a maximum (inclusive).\n *\n * @since 2.0.0\n */\nexport const between = <A>(O: Order<A>): {\n  (options: {\n    minimum: A\n    maximum: A\n  }): (self: A) => boolean\n  (self: A, options: {\n    minimum: A\n    maximum: A\n  }): boolean\n} =>\n  dual(\n    2,\n    (self: A, options: {\n      minimum: A\n      maximum: A\n    }): boolean => !lessThan(O)(self, options.minimum) && !greaterThan(O)(self, options.maximum)\n  )\n"
  },
  {
    "path": "packages/effect/src/Ordering.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { LazyArg } from \"./Function.js\"\nimport { dual } from \"./Function.js\"\n\n/**\n * @category model\n * @since 2.0.0\n */\nexport type Ordering = -1 | 0 | 1\n\n/**\n * Inverts the ordering of the input `Ordering`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { reverse } from \"effect/Ordering\"\n *\n * assert.deepStrictEqual(reverse(1), -1)\n * assert.deepStrictEqual(reverse(-1), 1)\n * assert.deepStrictEqual(reverse(0), 0)\n * ```\n *\n * @since 2.0.0\n */\nexport const reverse = (o: Ordering): Ordering => (o === -1 ? 1 : o === 1 ? -1 : 0)\n\n/**\n * Depending on the `Ordering` parameter given to it, returns a value produced by one of the 3 functions provided as parameters.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Ordering } from \"effect\"\n * import { constant } from \"effect/Function\"\n *\n * const toMessage = Ordering.match({\n *   onLessThan: constant('less than'),\n *   onEqual: constant('equal'),\n *   onGreaterThan: constant('greater than')\n * })\n *\n * assert.deepStrictEqual(toMessage(-1), \"less than\")\n * assert.deepStrictEqual(toMessage(0), \"equal\")\n * assert.deepStrictEqual(toMessage(1), \"greater than\")\n * ```\n *\n * @category pattern matching\n * @since 2.0.0\n */\nexport const match: {\n  <A, B, C = B>(\n    options: {\n      readonly onLessThan: LazyArg<A>\n      readonly onEqual: LazyArg<B>\n      readonly onGreaterThan: LazyArg<C>\n    }\n  ): (self: Ordering) => A | B | C\n  <A, B, C = B>(\n    o: Ordering,\n    options: {\n      readonly onLessThan: LazyArg<A>\n      readonly onEqual: LazyArg<B>\n      readonly onGreaterThan: LazyArg<C>\n    }\n  ): A | B | C\n} = dual(2, <A, B, C = B>(\n  self: Ordering,\n  { onEqual, onGreaterThan, onLessThan }: {\n    readonly onLessThan: LazyArg<A>\n    readonly onEqual: LazyArg<B>\n    readonly onGreaterThan: LazyArg<C>\n  }\n): A | B | C => self === -1 ? onLessThan() : self === 0 ? onEqual() : onGreaterThan())\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const combine: {\n  (that: Ordering): (self: Ordering) => Ordering\n  (self: Ordering, that: Ordering): Ordering\n} = dual(2, (self: Ordering, that: Ordering): Ordering => self !== 0 ? self : that)\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const combineMany: {\n  (collection: Iterable<Ordering>): (self: Ordering) => Ordering\n  (self: Ordering, collection: Iterable<Ordering>): Ordering\n} = dual(2, (self: Ordering, collection: Iterable<Ordering>): Ordering => {\n  let ordering = self\n  if (ordering !== 0) {\n    return ordering\n  }\n  for (ordering of collection) {\n    if (ordering !== 0) {\n      return ordering\n    }\n  }\n  return ordering\n})\n\n/**\n * @category combining\n * @since 2.0.0\n */\nexport const combineAll = (collection: Iterable<Ordering>): Ordering => combineMany(0, collection)\n"
  },
  {
    "path": "packages/effect/src/ParseResult.ts",
    "content": "/**\n * @since 3.10.0\n */\n\nimport * as Arr from \"./Array.js\"\nimport * as Cause from \"./Cause.js\"\nimport { TaggedError } from \"./Data.js\"\nimport * as Effect from \"./Effect.js\"\nimport * as Either from \"./Either.js\"\nimport * as Exit from \"./Exit.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport { dual } from \"./Function.js\"\nimport { globalValue } from \"./GlobalValue.js\"\nimport * as Inspectable from \"./Inspectable.js\"\nimport * as util_ from \"./internal/schema/util.js\"\nimport * as Option from \"./Option.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport * as Scheduler from \"./Scheduler.js\"\nimport type * as Schema from \"./Schema.js\"\nimport * as AST from \"./SchemaAST.js\"\nimport type { Concurrency } from \"./Types.js\"\n\n/**\n * `ParseIssue` is a type that represents the different types of errors that can occur when decoding/encoding a value.\n *\n * @category model\n * @since 3.10.0\n */\nexport type ParseIssue =\n  // leaf\n  | Type\n  | Missing\n  | Unexpected\n  | Forbidden\n  // composite\n  | Pointer\n  | Refinement\n  | Transformation\n  | Composite\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport type SingleOrNonEmpty<A> = A | Arr.NonEmptyReadonlyArray<A>\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport type Path = SingleOrNonEmpty<PropertyKey>\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class Pointer {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Pointer\"\n  constructor(\n    readonly path: Path,\n    readonly actual: unknown,\n    readonly issue: ParseIssue\n  ) {}\n}\n\n/**\n * Error that occurs when an unexpected key or index is present.\n *\n * @category model\n * @since 3.10.0\n */\nexport class Unexpected {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Unexpected\"\n  constructor(\n    readonly actual: unknown,\n    /**\n     * @since 3.10.0\n     */\n    readonly message?: string\n  ) {}\n}\n\n/**\n * Error that occurs when a required key or index is missing.\n *\n * @category model\n * @since 3.10.0\n */\nexport class Missing {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Missing\"\n  /**\n   * @since 3.10.0\n   */\n  readonly actual = undefined\n  constructor(\n    /**\n     * @since 3.10.0\n     */\n    readonly ast: AST.Type,\n    /**\n     * @since 3.10.0\n     */\n    readonly message?: string\n  ) {}\n}\n\n/**\n * Error that contains multiple issues.\n *\n * @category model\n * @since 3.10.0\n */\nexport class Composite {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Composite\"\n  constructor(\n    readonly ast: AST.AST,\n    readonly actual: unknown,\n    readonly issues: SingleOrNonEmpty<ParseIssue>,\n    readonly output?: unknown\n  ) {}\n}\n\n/**\n * Error that occurs when a refinement has an error.\n *\n * @category model\n * @since 3.10.0\n */\nexport class Refinement {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Refinement\"\n  constructor(\n    readonly ast: AST.Refinement,\n    readonly actual: unknown,\n    readonly kind: \"From\" | \"Predicate\",\n    readonly issue: ParseIssue\n  ) {}\n}\n\n/**\n * Error that occurs when a transformation has an error.\n *\n * @category model\n * @since 3.10.0\n */\nexport class Transformation {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Transformation\"\n  constructor(\n    readonly ast: AST.Transformation,\n    readonly actual: unknown,\n    readonly kind: \"Encoded\" | \"Transformation\" | \"Type\",\n    readonly issue: ParseIssue\n  ) {}\n}\n\n/**\n * The `Type` variant of the `ParseIssue` type represents an error that occurs when the `actual` value is not of the expected type.\n * The `ast` field specifies the expected type, and the `actual` field contains the value that caused the error.\n *\n * @category model\n * @since 3.10.0\n */\nexport class Type {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Type\"\n  constructor(\n    readonly ast: AST.AST,\n    readonly actual: unknown,\n    readonly message?: string\n  ) {}\n}\n\n/**\n * The `Forbidden` variant of the `ParseIssue` type represents a forbidden operation, such as when encountering an Effect that is not allowed to execute (e.g., using `runSync`).\n *\n * @category model\n * @since 3.10.0\n */\nexport class Forbidden {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Forbidden\"\n  constructor(\n    readonly ast: AST.AST,\n    readonly actual: unknown,\n    readonly message?: string\n  ) {}\n}\n\n/**\n * @category type id\n * @since 3.10.0\n */\nexport const ParseErrorTypeId: unique symbol = Symbol.for(\"effect/Schema/ParseErrorTypeId\")\n\n/**\n * @category type id\n * @since 3.10.0\n */\nexport type ParseErrorTypeId = typeof ParseErrorTypeId\n\n/**\n * @since 3.10.0\n */\nexport const isParseError = (u: unknown): u is ParseError => Predicate.hasProperty(u, ParseErrorTypeId)\n\n/**\n * @since 3.10.0\n */\nexport class ParseError extends TaggedError(\"ParseError\")<{ readonly issue: ParseIssue }> {\n  /**\n   * @since 3.10.0\n   */\n  readonly [ParseErrorTypeId] = ParseErrorTypeId\n\n  get message() {\n    return this.toString()\n  }\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return TreeFormatter.formatIssueSync(this.issue)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON() {\n    return {\n      _id: \"ParseError\",\n      message: this.toString()\n    }\n  }\n  /**\n   * @since 3.10.0\n   */\n  [Inspectable.NodeInspectSymbol]() {\n    return this.toJSON()\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const parseError = (issue: ParseIssue): ParseError => new ParseError({ issue })\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const succeed: <A>(a: A) => Either.Either<A, ParseIssue> = Either.right\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const fail: (issue: ParseIssue) => Either.Either<never, ParseIssue> = Either.left\n\nconst _try: <A>(options: {\n  try: LazyArg<A>\n  catch: (e: unknown) => ParseIssue\n}) => Either.Either<A, ParseIssue> = Either.try\n\nexport {\n  /**\n   * @category constructors\n   * @since 3.10.0\n   */\n  _try as try\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const fromOption: {\n  (onNone: () => ParseIssue): <A>(self: Option.Option<A>) => Either.Either<A, ParseIssue>\n  <A>(self: Option.Option<A>, onNone: () => ParseIssue): Either.Either<A, ParseIssue>\n} = Either.fromOption\n\nconst isEither: <A, E, R>(self: Effect.Effect<A, E, R>) => self is Either.Either<A, E> = Either.isEither as any\n\n/**\n * @category optimisation\n * @since 3.10.0\n */\nexport const flatMap: {\n  <A, B, E1, R1>(\n    f: (a: A) => Effect.Effect<B, E1, R1>\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E1 | E, R1 | R>\n  <A, E, R, B, E1, R1>(\n    self: Effect.Effect<A, E, R>,\n    f: (a: A) => Effect.Effect<B, E1, R1>\n  ): Effect.Effect<B, E | E1, R | R1>\n} = dual(2, <A, E, R, B, E1, R1>(\n  self: Effect.Effect<A, E, R>,\n  f: (a: A) => Effect.Effect<B, E1, R1>\n): Effect.Effect<B, E | E1, R | R1> => {\n  return isEither(self) ?\n    Either.match(self, { onLeft: Either.left, onRight: f }) :\n    Effect.flatMap(self, f)\n})\n\n/**\n * @category optimisation\n * @since 3.10.0\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E, R>\n  <A, E, R, B>(self: Effect.Effect<A, E, R>, f: (a: A) => B): Effect.Effect<B, E, R>\n} = dual(2, <A, E, R, B>(self: Effect.Effect<A, E, R>, f: (a: A) => B): Effect.Effect<B, E, R> => {\n  return isEither(self) ?\n    Either.map(self, f) :\n    Effect.map(self, f)\n})\n\n/**\n * @category optimisation\n * @since 3.10.0\n */\nexport const mapError: {\n  <E, E2>(f: (e: E) => E2): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E2, R>\n  <A, E, R, E2>(self: Effect.Effect<A, E, R>, f: (e: E) => E2): Effect.Effect<A, E2, R>\n} = dual(2, <A, E, R, E2>(self: Effect.Effect<A, E, R>, f: (e: E) => E2): Effect.Effect<A, E2, R> => {\n  return isEither(self) ?\n    Either.mapLeft(self, f) :\n    Effect.mapError(self, f)\n})\n\n// TODO(4.0): remove\n/**\n * @category optimisation\n * @since 3.10.0\n */\nexport const eitherOrUndefined = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Either.Either<A, E> | undefined => {\n  if (isEither(self)) {\n    return self\n  }\n}\n\n/**\n * @category optimisation\n * @since 3.10.0\n */\nexport const mapBoth: {\n  <E, E2, A, A2>(\n    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n  ): <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2, E2, R>\n  <A, E, R, E2, A2>(\n    self: Effect.Effect<A, E, R>,\n    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n  ): Effect.Effect<A2, E2, R>\n} = dual(2, <A, E, R, E2, A2>(\n  self: Effect.Effect<A, E, R>,\n  options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n): Effect.Effect<A2, E2, R> => {\n  return isEither(self) ?\n    Either.mapBoth(self, { onLeft: options.onFailure, onRight: options.onSuccess }) :\n    Effect.mapBoth(self, options)\n})\n\n/**\n * @category optimisation\n * @since 3.10.0\n */\nexport const orElse: {\n  <E, A2, E2, R2>(\n    f: (e: E) => Effect.Effect<A2, E2, R2>\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (e: E) => Effect.Effect<A2, E2, R2>\n  ): Effect.Effect<A2 | A, E2, R2 | R>\n} = dual(2, <A, E, R, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  f: (e: E) => Effect.Effect<A2, E2, R2>\n): Effect.Effect<A2 | A, E2, R2 | R> => {\n  return isEither(self) ?\n    Either.match(self, { onLeft: f, onRight: Either.right }) :\n    Effect.catchAll(self, f)\n})\n\n/**\n * @since 3.10.0\n */\nexport type DecodeUnknown<Out, R> = (u: unknown, options?: AST.ParseOptions) => Effect.Effect<Out, ParseIssue, R>\n\n/**\n * @since 3.10.0\n */\nexport type DeclarationDecodeUnknown<Out, R> = (\n  u: unknown,\n  options: AST.ParseOptions,\n  ast: AST.Declaration\n) => Effect.Effect<Out, ParseIssue, R>\n\n/** @internal */\nexport const mergeInternalOptions = (\n  options: InternalOptions | undefined,\n  overrideOptions: InternalOptions | number | undefined\n): InternalOptions | undefined => {\n  if (overrideOptions === undefined || Predicate.isNumber(overrideOptions)) {\n    return options\n  }\n  if (options === undefined) {\n    return overrideOptions\n  }\n  return { ...options, ...overrideOptions }\n}\n\nconst getEither = (ast: AST.AST, isDecoding: boolean, options?: AST.ParseOptions) => {\n  const parser = goMemo(ast, isDecoding)\n  return (u: unknown, overrideOptions?: AST.ParseOptions): Either.Either<any, ParseIssue> =>\n    parser(u, mergeInternalOptions(options, overrideOptions)) as any\n}\n\nconst getSync = (ast: AST.AST, isDecoding: boolean, options?: AST.ParseOptions) => {\n  const parser = getEither(ast, isDecoding, options)\n  return (input: unknown, overrideOptions?: AST.ParseOptions) =>\n    Either.getOrThrowWith(parser(input, overrideOptions), parseError)\n}\n\n/** @internal */\nexport const getOption = (ast: AST.AST, isDecoding: boolean, options?: AST.ParseOptions) => {\n  const parser = getEither(ast, isDecoding, options)\n  return (input: unknown, overrideOptions?: AST.ParseOptions): Option.Option<any> =>\n    Option.getRight(parser(input, overrideOptions))\n}\n\nconst getEffect = <R>(ast: AST.AST, isDecoding: boolean, options?: AST.ParseOptions) => {\n  const parser = goMemo(ast, isDecoding)\n  return (input: unknown, overrideOptions?: AST.ParseOptions): Effect.Effect<any, ParseIssue, R> =>\n    parser(input, { ...mergeInternalOptions(options, overrideOptions), isEffectAllowed: true })\n}\n\n/**\n * @throws `ParseError`\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeUnknownSync = <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => A => getSync(schema.ast, true, options)\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeUnknownOption = <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => Option.Option<A> => getOption(schema.ast, true, options)\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeUnknownEither = <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => Either.Either<A, ParseIssue> =>\n  getEither(schema.ast, true, options)\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeUnknownPromise = <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => {\n  const parser = decodeUnknown(schema, options)\n  return (u: unknown, overrideOptions?: AST.ParseOptions): Promise<A> => Effect.runPromise(parser(u, overrideOptions))\n}\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeUnknown = <A, I, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => Effect.Effect<A, ParseIssue, R> =>\n  getEffect(schema.ast, true, options)\n\n/**\n * @throws `ParseError`\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeUnknownSync = <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => I => getSync(schema.ast, false, options)\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeUnknownOption = <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => Option.Option<I> => getOption(schema.ast, false, options)\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeUnknownEither = <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => Either.Either<I, ParseIssue> =>\n  getEither(schema.ast, false, options)\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeUnknownPromise = <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => {\n  const parser = encodeUnknown(schema, options)\n  return (u: unknown, overrideOptions?: AST.ParseOptions): Promise<I> => Effect.runPromise(parser(u, overrideOptions))\n}\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeUnknown = <A, I, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => Effect.Effect<I, ParseIssue, R> =>\n  getEffect(schema.ast, false, options)\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeSync: <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => (i: I, overrideOptions?: AST.ParseOptions) => A = decodeUnknownSync\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeOption: <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => (i: I, overrideOptions?: AST.ParseOptions) => Option.Option<A> = decodeUnknownOption\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeEither: <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => (i: I, overrideOptions?: AST.ParseOptions) => Either.Either<A, ParseIssue> = decodeUnknownEither\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodePromise: <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => (i: I, overrideOptions?: AST.ParseOptions) => Promise<A> = decodeUnknownPromise\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decode: <A, I, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: AST.ParseOptions\n) => (i: I, overrideOptions?: AST.ParseOptions) => Effect.Effect<A, ParseIssue, R> = decodeUnknown\n\n/**\n * @throws `ParseError`\n * @category validation\n * @since 3.10.0\n */\nexport const validateSync = <A, I, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => A => getSync(AST.typeAST(schema.ast), true, options)\n\n/**\n * @category validation\n * @since 3.10.0\n */\nexport const validateOption = <A, I, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => Option.Option<A> =>\n  getOption(AST.typeAST(schema.ast), true, options)\n\n/**\n * @category validation\n * @since 3.10.0\n */\nexport const validateEither = <A, I, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: AST.ParseOptions\n): (u: unknown, overrideOptions?: AST.ParseOptions) => Either.Either<A, ParseIssue> =>\n  getEither(AST.typeAST(schema.ast), true, options)\n\n/**\n * @category validation\n * @since 3.10.0\n */\nexport const validatePromise = <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => {\n  const parser = validate(schema, options)\n  return (u: unknown, overrideOptions?: AST.ParseOptions): Promise<A> => Effect.runPromise(parser(u, overrideOptions))\n}\n\n/**\n * @category validation\n * @since 3.10.0\n */\nexport const validate = <A, I, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: AST.ParseOptions\n): (a: unknown, overrideOptions?: AST.ParseOptions) => Effect.Effect<A, ParseIssue, R> =>\n  getEffect(AST.typeAST(schema.ast), true, options)\n\n/**\n * By default the option `exact` is set to `true`.\n *\n * @category validation\n * @since 3.10.0\n */\nexport const is = <A, I, R>(schema: Schema.Schema<A, I, R>, options?: AST.ParseOptions) => {\n  const parser = goMemo(AST.typeAST(schema.ast), true)\n  return (u: unknown, overrideOptions?: AST.ParseOptions | number): u is A =>\n    Either.isRight(parser(u, { exact: true, ...mergeInternalOptions(options, overrideOptions) }) as any)\n}\n\n/**\n * By default the option `exact` is set to `true`.\n *\n * @throws `ParseError`\n * @category validation\n * @since 3.10.0\n */\nexport const asserts = <A, I, R>(schema: Schema.Schema<A, I, R>, options?: AST.ParseOptions) => {\n  const parser = goMemo(AST.typeAST(schema.ast), true)\n  return (u: unknown, overrideOptions?: AST.ParseOptions): asserts u is A => {\n    const result: Either.Either<any, ParseIssue> = parser(u, {\n      exact: true,\n      ...mergeInternalOptions(options, overrideOptions)\n    }) as any\n    if (Either.isLeft(result)) {\n      throw parseError(result.left)\n    }\n  }\n}\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeSync: <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => (a: A, overrideOptions?: AST.ParseOptions) => I = encodeUnknownSync\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeOption: <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => (input: A, overrideOptions?: AST.ParseOptions) => Option.Option<I> = encodeUnknownOption\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeEither: <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => (a: A, overrideOptions?: AST.ParseOptions) => Either.Either<I, ParseIssue> = encodeUnknownEither\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodePromise: <A, I>(\n  schema: Schema.Schema<A, I, never>,\n  options?: AST.ParseOptions\n) => (a: A, overrideOptions?: AST.ParseOptions) => Promise<I> = encodeUnknownPromise\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encode: <A, I, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: AST.ParseOptions\n) => (a: A, overrideOptions?: AST.ParseOptions) => Effect.Effect<I, ParseIssue, R> = encodeUnknown\n\ninterface InternalOptions extends AST.ParseOptions {\n  readonly isEffectAllowed?: boolean\n}\n\ninterface Parser {\n  (i: any, options?: InternalOptions): Effect.Effect<any, ParseIssue, any>\n}\n\nconst decodeMemoMap = globalValue(\n  Symbol.for(\"effect/ParseResult/decodeMemoMap\"),\n  () => new WeakMap<AST.AST, Parser>()\n)\nconst encodeMemoMap = globalValue(\n  Symbol.for(\"effect/ParseResult/encodeMemoMap\"),\n  () => new WeakMap<AST.AST, Parser>()\n)\n\nconst goMemo = (ast: AST.AST, isDecoding: boolean): Parser => {\n  const memoMap = isDecoding ? decodeMemoMap : encodeMemoMap\n  const memo = memoMap.get(ast)\n  if (memo) {\n    return memo\n  }\n  const raw = go(ast, isDecoding)\n  const parseOptionsAnnotation = AST.getParseOptionsAnnotation(ast)\n  const parserWithOptions: Parser = Option.isSome(parseOptionsAnnotation)\n    ? (i, options) => raw(i, mergeInternalOptions(options, parseOptionsAnnotation.value))\n    : raw\n  const decodingFallbackAnnotation = AST.getDecodingFallbackAnnotation(ast)\n  const parser: Parser = isDecoding && Option.isSome(decodingFallbackAnnotation)\n    ? (i, options) =>\n      handleForbidden(orElse(parserWithOptions(i, options), decodingFallbackAnnotation.value), ast, i, options)\n    : parserWithOptions\n  memoMap.set(ast, parser)\n  return parser\n}\n\nconst getConcurrency = (ast: AST.AST): Concurrency | undefined =>\n  Option.getOrUndefined(AST.getConcurrencyAnnotation(ast))\n\nconst getBatching = (ast: AST.AST): boolean | \"inherit\" | undefined =>\n  Option.getOrUndefined(AST.getBatchingAnnotation(ast))\n\nconst go = (ast: AST.AST, isDecoding: boolean): Parser => {\n  switch (ast._tag) {\n    case \"Refinement\": {\n      if (isDecoding) {\n        const from = goMemo(ast.from, true)\n        return (i, options) => {\n          options = options ?? AST.defaultParseOption\n          const allErrors = options?.errors === \"all\"\n          const result = flatMap(\n            orElse(from(i, options), (ef) => {\n              const issue = new Refinement(ast, i, \"From\", ef)\n              if (allErrors && AST.hasStableFilter(ast) && isComposite(ef)) {\n                return Option.match(\n                  ast.filter(i, options, ast),\n                  {\n                    onNone: () => Either.left<ParseIssue>(issue),\n                    onSome: (ep) => Either.left(new Composite(ast, i, [issue, new Refinement(ast, i, \"Predicate\", ep)]))\n                  }\n                )\n              }\n              return Either.left(issue)\n            }),\n            (a) =>\n              Option.match(\n                ast.filter(a, options, ast),\n                {\n                  onNone: () => Either.right(a),\n                  onSome: (ep) => Either.left(new Refinement(ast, i, \"Predicate\", ep))\n                }\n              )\n          )\n          return handleForbidden(result, ast, i, options)\n        }\n      } else {\n        const from = goMemo(AST.typeAST(ast), true)\n        const to = goMemo(dropRightRefinement(ast.from), false)\n        return (i, options) => handleForbidden(flatMap(from(i, options), (a) => to(a, options)), ast, i, options)\n      }\n    }\n    case \"Transformation\": {\n      const transform = getFinalTransformation(ast.transformation, isDecoding)\n      const from = isDecoding ? goMemo(ast.from, true) : goMemo(ast.to, false)\n      const to = isDecoding ? goMemo(ast.to, true) : goMemo(ast.from, false)\n      return (i, options) =>\n        handleForbidden(\n          flatMap(\n            mapError(\n              from(i, options),\n              (e) => new Transformation(ast, i, isDecoding ? \"Encoded\" : \"Type\", e)\n            ),\n            (a) =>\n              flatMap(\n                mapError(\n                  transform(a, options ?? AST.defaultParseOption, ast, i),\n                  (e) => new Transformation(ast, i, \"Transformation\", e)\n                ),\n                (i2) =>\n                  mapError(\n                    to(i2, options),\n                    (e) => new Transformation(ast, i, isDecoding ? \"Type\" : \"Encoded\", e)\n                  )\n              )\n          ),\n          ast,\n          i,\n          options\n        )\n    }\n    case \"Declaration\": {\n      const parse = isDecoding\n        ? ast.decodeUnknown(...ast.typeParameters)\n        : ast.encodeUnknown(...ast.typeParameters)\n      return (i, options) => handleForbidden(parse(i, options ?? AST.defaultParseOption, ast), ast, i, options)\n    }\n    case \"Literal\":\n      return fromRefinement(ast, (u): u is typeof ast.literal => u === ast.literal)\n    case \"UniqueSymbol\":\n      return fromRefinement(ast, (u): u is typeof ast.symbol => u === ast.symbol)\n    case \"UndefinedKeyword\":\n      return fromRefinement(ast, Predicate.isUndefined)\n    case \"NeverKeyword\":\n      return fromRefinement(ast, Predicate.isNever)\n    case \"UnknownKeyword\":\n    case \"AnyKeyword\":\n    case \"VoidKeyword\":\n      return Either.right\n    case \"StringKeyword\":\n      return fromRefinement(ast, Predicate.isString)\n    case \"NumberKeyword\":\n      return fromRefinement(ast, Predicate.isNumber)\n    case \"BooleanKeyword\":\n      return fromRefinement(ast, Predicate.isBoolean)\n    case \"BigIntKeyword\":\n      return fromRefinement(ast, Predicate.isBigInt)\n    case \"SymbolKeyword\":\n      return fromRefinement(ast, Predicate.isSymbol)\n    case \"ObjectKeyword\":\n      return fromRefinement(ast, Predicate.isObject)\n    case \"Enums\":\n      return fromRefinement(ast, (u): u is any => ast.enums.some(([_, value]) => value === u))\n    case \"TemplateLiteral\": {\n      const regex = AST.getTemplateLiteralRegExp(ast)\n      return fromRefinement(ast, (u): u is any => Predicate.isString(u) && regex.test(u))\n    }\n    case \"TupleType\": {\n      const elements = ast.elements.map((e) => goMemo(e.type, isDecoding))\n      const rest = ast.rest.map((annotatedAST) => goMemo(annotatedAST.type, isDecoding))\n      let requiredTypes: Array<AST.Type> = ast.elements.filter((e) => !e.isOptional)\n      if (ast.rest.length > 0) {\n        requiredTypes = requiredTypes.concat(ast.rest.slice(1))\n      }\n      const requiredLen = requiredTypes.length\n      const expectedIndexes = ast.elements.length > 0 ? ast.elements.map((_, i) => i).join(\" | \") : \"never\"\n      const concurrency = getConcurrency(ast)\n      const batching = getBatching(ast)\n      return (input: unknown, options) => {\n        if (!Arr.isArray(input)) {\n          return Either.left(new Type(ast, input))\n        }\n        const allErrors = options?.errors === \"all\"\n        const es: Array<[number, ParseIssue]> = []\n        let stepKey = 0\n        const output: Array<[number, any]> = []\n        // ---------------------------------------------\n        // handle missing indexes\n        // ---------------------------------------------\n        const len = input.length\n        for (let i = len; i <= requiredLen - 1; i++) {\n          const e = new Pointer(i, input, new Missing(requiredTypes[i - len]))\n          if (allErrors) {\n            es.push([stepKey++, e])\n            continue\n          } else {\n            return Either.left(new Composite(ast, input, e, output))\n          }\n        }\n\n        // ---------------------------------------------\n        // handle excess indexes\n        // ---------------------------------------------\n        if (ast.rest.length === 0) {\n          for (let i = ast.elements.length; i <= len - 1; i++) {\n            const e = new Pointer(i, input, new Unexpected(input[i], `is unexpected, expected: ${expectedIndexes}`))\n            if (allErrors) {\n              es.push([stepKey++, e])\n              continue\n            } else {\n              return Either.left(new Composite(ast, input, e, output))\n            }\n          }\n        }\n\n        let i = 0\n        type State = {\n          es: typeof es\n          output: typeof output\n        }\n        let queue:\n          | Array<(_: State) => Effect.Effect<void, ParseIssue, any>>\n          | undefined = undefined\n\n        // ---------------------------------------------\n        // handle elements\n        // ---------------------------------------------\n        for (; i < elements.length; i++) {\n          if (len < i + 1) {\n            if (ast.elements[i].isOptional) {\n              // the input element is missing\n              continue\n            }\n          } else {\n            const parser = elements[i]\n            const te = parser(input[i], options)\n            if (isEither(te)) {\n              if (Either.isLeft(te)) {\n                // the input element is present but is not valid\n                const e = new Pointer(i, input, te.left)\n                if (allErrors) {\n                  es.push([stepKey++, e])\n                  continue\n                } else {\n                  return Either.left(new Composite(ast, input, e, sortByIndex(output)))\n                }\n              }\n              output.push([stepKey++, te.right])\n            } else {\n              const nk = stepKey++\n              const index = i\n              if (!queue) {\n                queue = []\n              }\n              queue.push(({ es, output }: State) =>\n                Effect.flatMap(Effect.either(te), (t) => {\n                  if (Either.isLeft(t)) {\n                    // the input element is present but is not valid\n                    const e = new Pointer(index, input, t.left)\n                    if (allErrors) {\n                      es.push([nk, e])\n                      return Effect.void\n                    } else {\n                      return Either.left(new Composite(ast, input, e, sortByIndex(output)))\n                    }\n                  }\n                  output.push([nk, t.right])\n                  return Effect.void\n                })\n              )\n            }\n          }\n        }\n        // ---------------------------------------------\n        // handle rest element\n        // ---------------------------------------------\n        if (Arr.isNonEmptyReadonlyArray(rest)) {\n          const [head, ...tail] = rest\n          for (; i < len - tail.length; i++) {\n            const te = head(input[i], options)\n            if (isEither(te)) {\n              if (Either.isLeft(te)) {\n                const e = new Pointer(i, input, te.left)\n                if (allErrors) {\n                  es.push([stepKey++, e])\n                  continue\n                } else {\n                  return Either.left(new Composite(ast, input, e, sortByIndex(output)))\n                }\n              } else {\n                output.push([stepKey++, te.right])\n              }\n            } else {\n              const nk = stepKey++\n              const index = i\n              if (!queue) {\n                queue = []\n              }\n              queue.push(\n                ({ es, output }: State) =>\n                  Effect.flatMap(Effect.either(te), (t) => {\n                    if (Either.isLeft(t)) {\n                      const e = new Pointer(index, input, t.left)\n                      if (allErrors) {\n                        es.push([nk, e])\n                        return Effect.void\n                      } else {\n                        return Either.left(new Composite(ast, input, e, sortByIndex(output)))\n                      }\n                    } else {\n                      output.push([nk, t.right])\n                      return Effect.void\n                    }\n                  })\n              )\n            }\n          }\n          // ---------------------------------------------\n          // handle post rest elements\n          // ---------------------------------------------\n          for (let j = 0; j < tail.length; j++) {\n            const index = i + j\n            if (len < index + 1) {\n              continue\n            } else {\n              const te = tail[j](input[index], options)\n              if (isEither(te)) {\n                if (Either.isLeft(te)) {\n                  // the input element is present but is not valid\n                  const e = new Pointer(index, input, te.left)\n                  if (allErrors) {\n                    es.push([stepKey++, e])\n                    continue\n                  } else {\n                    return Either.left(new Composite(ast, input, e, sortByIndex(output)))\n                  }\n                }\n                output.push([stepKey++, te.right])\n              } else {\n                const nk = stepKey++\n                if (!queue) {\n                  queue = []\n                }\n                queue.push(\n                  ({ es, output }: State) =>\n                    Effect.flatMap(Effect.either(te), (t) => {\n                      if (Either.isLeft(t)) {\n                        // the input element is present but is not valid\n                        const e = new Pointer(index, input, t.left)\n                        if (allErrors) {\n                          es.push([nk, e])\n                          return Effect.void\n                        } else {\n                          return Either.left(new Composite(ast, input, e, sortByIndex(output)))\n                        }\n                      }\n                      output.push([nk, t.right])\n                      return Effect.void\n                    })\n                )\n              }\n            }\n          }\n        }\n\n        // ---------------------------------------------\n        // compute result\n        // ---------------------------------------------\n        const computeResult = ({ es, output }: State) =>\n          Arr.isNonEmptyArray(es) ?\n            Either.left(new Composite(ast, input, sortByIndex(es), sortByIndex(output))) :\n            Either.right(sortByIndex(output))\n        if (queue && queue.length > 0) {\n          const cqueue = queue\n          return Effect.suspend(() => {\n            const state: State = {\n              es: Arr.copy(es),\n              output: Arr.copy(output)\n            }\n            return Effect.flatMap(\n              Effect.forEach(cqueue, (f) => f(state), { concurrency, batching, discard: true }),\n              () => computeResult(state)\n            )\n          })\n        }\n        return computeResult({ output, es })\n      }\n    }\n    case \"TypeLiteral\": {\n      if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) {\n        return fromRefinement(ast, Predicate.isNotNullable)\n      }\n\n      const propertySignatures: Array<readonly [Parser, AST.PropertySignature]> = []\n      const expectedKeysMap: Record<PropertyKey, null> = {}\n      const expectedKeys: Array<PropertyKey> = []\n      for (const ps of ast.propertySignatures) {\n        propertySignatures.push([goMemo(ps.type, isDecoding), ps])\n        expectedKeysMap[ps.name] = null\n        expectedKeys.push(ps.name)\n      }\n\n      const indexSignatures = ast.indexSignatures.map((is) =>\n        [\n          goMemo(is.parameter, isDecoding),\n          goMemo(is.type, isDecoding),\n          is.parameter\n        ] as const\n      )\n      const expectedAST = AST.Union.make(\n        ast.indexSignatures.map((is): AST.AST => is.parameter).concat(\n          expectedKeys.map((key) => Predicate.isSymbol(key) ? new AST.UniqueSymbol(key) : new AST.Literal(key))\n        )\n      )\n      const expected = goMemo(expectedAST, isDecoding)\n      const concurrency = getConcurrency(ast)\n      const batching = getBatching(ast)\n      return (input: unknown, options) => {\n        if (!Predicate.isRecord(input)) {\n          return Either.left(new Type(ast, input))\n        }\n        const allErrors = options?.errors === \"all\"\n        const es: Array<[number, ParseIssue]> = []\n        let stepKey = 0\n\n        // ---------------------------------------------\n        // handle excess properties\n        // ---------------------------------------------\n        const onExcessPropertyError = options?.onExcessProperty === \"error\"\n        const onExcessPropertyPreserve = options?.onExcessProperty === \"preserve\"\n        const output: Record<PropertyKey, unknown> = {}\n        let inputKeys: Array<PropertyKey> | undefined\n        if (onExcessPropertyError || onExcessPropertyPreserve) {\n          inputKeys = Reflect.ownKeys(input)\n          for (const key of inputKeys) {\n            const te = expected(key, options)\n            if (isEither(te) && Either.isLeft(te)) {\n              // key is unexpected\n              if (onExcessPropertyError) {\n                const e = new Pointer(\n                  key,\n                  input,\n                  new Unexpected(input[key], `is unexpected, expected: ${String(expectedAST)}`)\n                )\n                if (allErrors) {\n                  es.push([stepKey++, e])\n                  continue\n                } else {\n                  return Either.left(new Composite(ast, input, e, output))\n                }\n              } else {\n                // preserve key\n                output[key] = input[key]\n              }\n            }\n          }\n        }\n\n        // ---------------------------------------------\n        // handle property signatures\n        // ---------------------------------------------\n        type State = {\n          es: typeof es\n          output: typeof output\n        }\n        let queue:\n          | Array<(state: State) => Effect.Effect<void, ParseIssue, any>>\n          | undefined = undefined\n\n        const isExact = options?.exact === true\n        for (let i = 0; i < propertySignatures.length; i++) {\n          const ps = propertySignatures[i][1]\n          const name = ps.name\n          const hasKey = Object.prototype.hasOwnProperty.call(input, name)\n          if (!hasKey) {\n            if (ps.isOptional) {\n              continue\n            } else if (isExact) {\n              const e = new Pointer(name, input, new Missing(ps))\n              if (allErrors) {\n                es.push([stepKey++, e])\n                continue\n              } else {\n                return Either.left(new Composite(ast, input, e, output))\n              }\n            }\n          }\n          const parser = propertySignatures[i][0]\n          const te = parser(input[name], options)\n          if (isEither(te)) {\n            if (Either.isLeft(te)) {\n              const e = new Pointer(name, input, hasKey ? te.left : new Missing(ps))\n              if (allErrors) {\n                es.push([stepKey++, e])\n                continue\n              } else {\n                return Either.left(new Composite(ast, input, e, output))\n              }\n            }\n            output[name] = te.right\n          } else {\n            const nk = stepKey++\n            const index = name\n            if (!queue) {\n              queue = []\n            }\n            queue.push(\n              ({ es, output }: State) =>\n                Effect.flatMap(Effect.either(te), (t) => {\n                  if (Either.isLeft(t)) {\n                    const e = new Pointer(index, input, hasKey ? t.left : new Missing(ps))\n                    if (allErrors) {\n                      es.push([nk, e])\n                      return Effect.void\n                    } else {\n                      return Either.left(new Composite(ast, input, e, output))\n                    }\n                  }\n                  output[index] = t.right\n                  return Effect.void\n                })\n            )\n          }\n        }\n\n        // ---------------------------------------------\n        // handle index signatures\n        // ---------------------------------------------\n        for (let i = 0; i < indexSignatures.length; i++) {\n          const indexSignature = indexSignatures[i]\n          const parameter = indexSignature[0]\n          const type = indexSignature[1]\n          const keys = util_.getKeysForIndexSignature(input, indexSignature[2])\n          for (const key of keys) {\n            // ---------------------------------------------\n            // handle keys\n            // ---------------------------------------------\n            const keu = parameter(key, options)\n            if (isEither(keu) && Either.isRight(keu)) {\n              // ---------------------------------------------\n              // handle values\n              // ---------------------------------------------\n              const vpr = type(input[key], options)\n              if (isEither(vpr)) {\n                if (Either.isLeft(vpr)) {\n                  const e = new Pointer(key, input, vpr.left)\n                  if (allErrors) {\n                    es.push([stepKey++, e])\n                    continue\n                  } else {\n                    return Either.left(new Composite(ast, input, e, output))\n                  }\n                } else {\n                  if (!Object.prototype.hasOwnProperty.call(expectedKeysMap, key)) {\n                    output[key] = vpr.right\n                  }\n                }\n              } else {\n                const nk = stepKey++\n                const index = key\n                if (!queue) {\n                  queue = []\n                }\n                queue.push(\n                  ({ es, output }: State) =>\n                    Effect.flatMap(\n                      Effect.either(vpr),\n                      (tv) => {\n                        if (Either.isLeft(tv)) {\n                          const e = new Pointer(index, input, tv.left)\n                          if (allErrors) {\n                            es.push([nk, e])\n                            return Effect.void\n                          } else {\n                            return Either.left(new Composite(ast, input, e, output))\n                          }\n                        } else {\n                          if (!Object.prototype.hasOwnProperty.call(expectedKeysMap, key)) {\n                            output[key] = tv.right\n                          }\n                          return Effect.void\n                        }\n                      }\n                    )\n                )\n              }\n            }\n          }\n        }\n        // ---------------------------------------------\n        // compute result\n        // ---------------------------------------------\n        const computeResult = ({ es, output }: State) => {\n          if (Arr.isNonEmptyArray(es)) {\n            return Either.left(new Composite(ast, input, sortByIndex(es), output))\n          }\n          if (options?.propertyOrder === \"original\") {\n            // preserve input keys order\n            const keys = inputKeys || Reflect.ownKeys(input)\n            for (const name of expectedKeys) {\n              if (keys.indexOf(name) === -1) {\n                keys.push(name)\n              }\n            }\n            const out: any = {}\n            for (const key of keys) {\n              if (Object.prototype.hasOwnProperty.call(output, key)) {\n                out[key] = output[key]\n              }\n            }\n            return Either.right(out)\n          }\n          return Either.right(output)\n        }\n        if (queue && queue.length > 0) {\n          const cqueue = queue\n          return Effect.suspend(() => {\n            const state: State = {\n              es: Arr.copy(es),\n              output: Object.assign({}, output)\n            }\n            return Effect.flatMap(\n              Effect.forEach(cqueue, (f) => f(state), { concurrency, batching, discard: true }),\n              () => computeResult(state)\n            )\n          })\n        }\n        return computeResult({ es, output })\n      }\n    }\n    case \"Union\": {\n      const searchTree = getSearchTree(ast.types, isDecoding)\n      const ownKeys = Reflect.ownKeys(searchTree.keys)\n      const ownKeysLen = ownKeys.length\n      const astTypesLen = ast.types.length\n      const map = new Map<any, Parser>()\n      for (let i = 0; i < astTypesLen; i++) {\n        map.set(ast.types[i], goMemo(ast.types[i], isDecoding))\n      }\n      const concurrency = getConcurrency(ast) ?? 1\n      const batching = getBatching(ast)\n      return (input, options) => {\n        const es: Array<[number, ParseIssue]> = []\n        let stepKey = 0\n        let candidates: Array<AST.AST> = []\n        if (ownKeysLen > 0) {\n          if (Predicate.isRecordOrArray(input)) {\n            for (let i = 0; i < ownKeysLen; i++) {\n              const name = ownKeys[i]\n              const buckets = searchTree.keys[name].buckets\n              // for each property that should contain a literal, check if the input contains that property\n              if (Object.prototype.hasOwnProperty.call(input, name)) {\n                const literal = String(input[name])\n                // check that the value obtained from the input for the property corresponds to an existing bucket\n                if (Object.prototype.hasOwnProperty.call(buckets, literal)) {\n                  // retrive the minimal set of candidates for decoding\n                  candidates = candidates.concat(buckets[literal])\n                } else {\n                  const { candidates, literals } = searchTree.keys[name]\n                  const literalsUnion = AST.Union.make(literals)\n                  const errorAst = candidates.length === astTypesLen\n                    ? new AST.TypeLiteral([new AST.PropertySignature(name, literalsUnion, false, true)], [])\n                    : AST.Union.make(candidates)\n                  es.push([\n                    stepKey++,\n                    new Composite(errorAst, input, new Pointer(name, input, new Type(literalsUnion, input[name])))\n                  ])\n                }\n              } else {\n                const { candidates, literals } = searchTree.keys[name]\n                const fakePropertySignature = new AST.PropertySignature(name, AST.Union.make(literals), false, true)\n                const errorAst = candidates.length === astTypesLen\n                  ? new AST.TypeLiteral([fakePropertySignature], [])\n                  : AST.Union.make(candidates)\n                es.push([\n                  stepKey++,\n                  new Composite(errorAst, input, new Pointer(name, input, new Missing(fakePropertySignature)))\n                ])\n              }\n            }\n          } else {\n            const errorAst = searchTree.candidates.length === astTypesLen\n              ? ast\n              : AST.Union.make(searchTree.candidates)\n            es.push([stepKey++, new Type(errorAst, input)])\n          }\n        }\n        if (searchTree.otherwise.length > 0) {\n          candidates = candidates.concat(searchTree.otherwise)\n        }\n\n        let queue:\n          | Array<(state: State) => Effect.Effect<unknown, ParseIssue, any>>\n          | undefined = undefined\n\n        type State = {\n          finalResult?: any\n          es: typeof es\n        }\n\n        for (let i = 0; i < candidates.length; i++) {\n          const candidate = candidates[i]\n          const pr = map.get(candidate)!(input, options)\n          // the members of a union are ordered based on which one should be decoded first,\n          // therefore if one member has added a task, all subsequent members must\n          // also add a task to the queue even if they are synchronous\n          if (isEither(pr) && (!queue || queue.length === 0)) {\n            if (Either.isRight(pr)) {\n              return pr\n            } else {\n              es.push([stepKey++, pr.left])\n            }\n          } else {\n            const nk = stepKey++\n            if (!queue) {\n              queue = []\n            }\n            queue.push(\n              (state) =>\n                Effect.suspend(() => {\n                  if (\"finalResult\" in state) {\n                    return Effect.void\n                  } else {\n                    return Effect.flatMap(Effect.either(pr), (t) => {\n                      if (Either.isRight(t)) {\n                        state.finalResult = t\n                      } else {\n                        state.es.push([nk, t.left])\n                      }\n                      return Effect.void\n                    })\n                  }\n                })\n            )\n          }\n        }\n\n        // ---------------------------------------------\n        // compute result\n        // ---------------------------------------------\n        const computeResult = (es: State[\"es\"]) =>\n          Arr.isNonEmptyArray(es) ?\n            es.length === 1 && es[0][1]._tag === \"Type\" ?\n              Either.left(es[0][1]) :\n              Either.left(new Composite(ast, input, sortByIndex(es))) :\n            // this should never happen\n            Either.left(new Type(ast, input))\n\n        if (queue && queue.length > 0) {\n          const cqueue = queue\n          return Effect.suspend(() => {\n            const state: State = { es: Arr.copy(es) }\n            return Effect.flatMap(\n              Effect.forEach(cqueue, (f) => f(state), { concurrency, batching, discard: true }),\n              () => {\n                if (\"finalResult\" in state) {\n                  return state.finalResult\n                }\n                return computeResult(state.es)\n              }\n            )\n          })\n        }\n        return computeResult(es)\n      }\n    }\n    case \"Suspend\": {\n      const get = util_.memoizeThunk(() => goMemo(ast.f(), isDecoding))\n      return (a, options) => get()(a, options)\n    }\n  }\n}\n\nconst fromRefinement = <A>(ast: AST.AST, refinement: (u: unknown) => u is A): Parser => (u) =>\n  refinement(u) ? Either.right(u) : Either.left(new Type(ast, u))\n\n/** @internal */\nexport const getLiterals = (\n  ast: AST.AST,\n  isDecoding: boolean\n): ReadonlyArray<[PropertyKey, AST.Literal]> => {\n  switch (ast._tag) {\n    case \"Declaration\": {\n      const annotation = AST.getSurrogateAnnotation(ast)\n      if (Option.isSome(annotation)) {\n        return getLiterals(annotation.value, isDecoding)\n      }\n      break\n    }\n    case \"TypeLiteral\": {\n      const out: Array<[PropertyKey, AST.Literal]> = []\n      for (let i = 0; i < ast.propertySignatures.length; i++) {\n        const propertySignature = ast.propertySignatures[i]\n        const type = isDecoding ? AST.encodedAST(propertySignature.type) : AST.typeAST(propertySignature.type)\n        if (AST.isLiteral(type) && !propertySignature.isOptional) {\n          out.push([propertySignature.name, type])\n        }\n      }\n      return out\n    }\n    case \"TupleType\": {\n      const out: Array<[PropertyKey, AST.Literal]> = []\n      for (let i = 0; i < ast.elements.length; i++) {\n        const element = ast.elements[i]\n        const type = isDecoding ? AST.encodedAST(element.type) : AST.typeAST(element.type)\n        if (AST.isLiteral(type) && !element.isOptional) {\n          out.push([i, type])\n        }\n      }\n      return out\n    }\n    case \"Refinement\":\n      return getLiterals(ast.from, isDecoding)\n    case \"Suspend\":\n      return getLiterals(ast.f(), isDecoding)\n    case \"Transformation\":\n      return getLiterals(isDecoding ? ast.from : ast.to, isDecoding)\n  }\n  return []\n}\n\n/**\n * The purpose of the algorithm is to narrow down the pool of possible\n * candidates for decoding as much as possible.\n *\n * This function separates the schemas into two groups, `keys` and `otherwise`:\n *\n * - `keys`: the schema has at least one property with a literal value\n * - `otherwise`: the schema has no properties with a literal value\n *\n * If a schema has at least one property with a literal value, so it ends up in\n * `keys`, first a namespace is created for the name of the property containing\n * the literal, and then within this namespace a \"bucket\" is created for the\n * literal value in which to store all the schemas that have the same property\n * and literal value.\n *\n * @internal\n */\nexport const getSearchTree = (\n  members: ReadonlyArray<AST.AST>,\n  isDecoding: boolean\n): {\n  keys: {\n    readonly [key: PropertyKey]: {\n      buckets: { [literal: string]: ReadonlyArray<AST.AST> }\n      literals: ReadonlyArray<AST.Literal> // this is for error messages\n      candidates: ReadonlyArray<AST.AST>\n    }\n  }\n  otherwise: ReadonlyArray<AST.AST>\n  candidates: ReadonlyArray<AST.AST>\n} => {\n  const keys: {\n    [key: PropertyKey]: {\n      buckets: { [literal: string]: Array<AST.AST> }\n      literals: Array<AST.Literal>\n      candidates: Array<AST.AST>\n    }\n  } = {}\n  const otherwise: Array<AST.AST> = []\n  const candidates: Array<AST.AST> = []\n  for (let i = 0; i < members.length; i++) {\n    const member = members[i]\n    const tags = getLiterals(member, isDecoding)\n    if (tags.length > 0) {\n      candidates.push(member)\n      for (let j = 0; j < tags.length; j++) {\n        const [key, literal] = tags[j]\n        const hash = String(literal.literal)\n        keys[key] = keys[key] || { buckets: {}, literals: [], candidates: [] }\n        const buckets = keys[key].buckets\n        if (Object.prototype.hasOwnProperty.call(buckets, hash)) {\n          if (j < tags.length - 1) {\n            continue\n          }\n          buckets[hash].push(member)\n          keys[key].literals.push(literal)\n          keys[key].candidates.push(member)\n        } else {\n          buckets[hash] = [member]\n          keys[key].literals.push(literal)\n          keys[key].candidates.push(member)\n          break\n        }\n      }\n    } else {\n      otherwise.push(member)\n    }\n  }\n  return { keys, otherwise, candidates }\n}\n\nconst dropRightRefinement = (ast: AST.AST): AST.AST => AST.isRefinement(ast) ? dropRightRefinement(ast.from) : ast\n\nconst handleForbidden = <A, R>(\n  effect: Effect.Effect<A, ParseIssue, R>,\n  ast: AST.AST,\n  actual: unknown,\n  options: InternalOptions | undefined\n): Effect.Effect<A, ParseIssue, R> => {\n  // If effects are allowed, return the original effect\n  if (options?.isEffectAllowed === true) {\n    return effect\n  }\n\n  // If the effect is already an Either, return it directly\n  if (isEither(effect)) {\n    return effect\n  }\n\n  // Otherwise, attempt to execute the effect synchronously\n  const scheduler = new Scheduler.SyncScheduler()\n  const fiber = Effect.runFork(effect as Effect.Effect<A, ParseIssue>, { scheduler })\n  scheduler.flush()\n  const exit = fiber.unsafePoll()\n\n  if (exit) {\n    if (Exit.isSuccess(exit)) {\n      // If the effect successfully resolves, wrap the value in a Right\n      return Either.right(exit.value)\n    }\n    const cause = exit.cause\n    if (Cause.isFailType(cause)) {\n      // The effect executed synchronously but failed due to a ParseIssue\n      return Either.left(cause.error)\n    }\n    // The effect executed synchronously but failed due to a defect (e.g., a missing dependency)\n    return Either.left(new Forbidden(ast, actual, Cause.pretty(cause)))\n  }\n\n  // The effect could not be resolved synchronously, meaning it performs async work\n  return Either.left(\n    new Forbidden(\n      ast,\n      actual,\n      \"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work\"\n    )\n  )\n}\n\nconst compare = ([a]: [number, ...Array<unknown>], [b]: [number, ...Array<unknown>]) => a > b ? 1 : a < b ? -1 : 0\n\nfunction sortByIndex<T>(\n  es: Arr.NonEmptyArray<[number, T]>\n): Arr.NonEmptyArray<T>\nfunction sortByIndex<T>(es: Array<[number, T]>): Array<T>\nfunction sortByIndex(es: Array<[number, any]>) {\n  return es.sort(compare).map((t) => t[1])\n}\n\n// -------------------------------------------------------------------------------------\n// transformations interpreter\n// -------------------------------------------------------------------------------------\n\n/** @internal */\nexport const getFinalTransformation = (\n  transformation: AST.TransformationKind,\n  isDecoding: boolean\n): (\n  fromA: any,\n  options: AST.ParseOptions,\n  self: AST.Transformation,\n  fromI: any\n) => Effect.Effect<any, ParseIssue, any> => {\n  switch (transformation._tag) {\n    case \"FinalTransformation\":\n      return isDecoding ? transformation.decode : transformation.encode\n    case \"ComposeTransformation\":\n      return Either.right\n    case \"TypeLiteralTransformation\":\n      return (input) => {\n        let out: Effect.Effect<any, ParseIssue, any> = Either.right(input)\n\n        // ---------------------------------------------\n        // handle property signature transformations\n        // ---------------------------------------------\n        for (const pst of transformation.propertySignatureTransformations) {\n          const [from, to] = isDecoding ?\n            [pst.from, pst.to] :\n            [pst.to, pst.from]\n          const transformation = isDecoding ? pst.decode : pst.encode\n          const f = (input: any) => {\n            const o = transformation(\n              Object.prototype.hasOwnProperty.call(input, from) ?\n                Option.some(input[from]) :\n                Option.none()\n            )\n            delete input[from]\n            if (Option.isSome(o)) {\n              input[to] = o.value\n            }\n            return input\n          }\n          out = map(out, f)\n        }\n        return out\n      }\n  }\n}\n\n// ----------------\n// Formatters\n// ----------------\n\ninterface Forest<A> extends ReadonlyArray<Tree<A>> {}\n\ninterface Tree<A> {\n  readonly value: A\n  readonly forest: Forest<A>\n}\n\nconst makeTree = <A>(value: A, forest: Forest<A> = []): Tree<A> => ({\n  value,\n  forest\n})\n\n/**\n * @category formatting\n * @since 3.10.0\n */\nexport interface ParseResultFormatter<A> {\n  readonly formatIssue: (issue: ParseIssue) => Effect.Effect<A>\n  readonly formatIssueSync: (issue: ParseIssue) => A\n  readonly formatError: (error: ParseError) => Effect.Effect<A>\n  readonly formatErrorSync: (error: ParseError) => A\n}\n\n/**\n * @category formatting\n * @since 3.10.0\n */\nexport const TreeFormatter: ParseResultFormatter<string> = {\n  formatIssue: (issue) => map(formatTree(issue), drawTree),\n  formatIssueSync: (issue) => {\n    const e = TreeFormatter.formatIssue(issue)\n    return isEither(e) ? Either.getOrThrow(e) : Effect.runSync(e)\n  },\n  formatError: (error) => TreeFormatter.formatIssue(error.issue),\n  formatErrorSync: (error) => TreeFormatter.formatIssueSync(error.issue)\n}\n\nconst drawTree = (tree: Tree<string>): string => tree.value + draw(\"\\n\", tree.forest)\n\nconst draw = (indentation: string, forest: Forest<string>): string => {\n  let r = \"\"\n  const len = forest.length\n  let tree: Tree<string>\n  for (let i = 0; i < len; i++) {\n    tree = forest[i]\n    const isLast = i === len - 1\n    r += indentation + (isLast ? \"└\" : \"├\") + \"─ \" + tree.value\n    r += draw(indentation + (len > 1 && !isLast ? \"│  \" : \"   \"), tree.forest)\n  }\n  return r\n}\n\nconst formatTransformationKind = (kind: Transformation[\"kind\"]): string => {\n  switch (kind) {\n    case \"Encoded\":\n      return \"Encoded side transformation failure\"\n    case \"Transformation\":\n      return \"Transformation process failure\"\n    case \"Type\":\n      return \"Type side transformation failure\"\n  }\n}\n\nconst formatRefinementKind = (kind: Refinement[\"kind\"]): string => {\n  switch (kind) {\n    case \"From\":\n      return \"From side refinement failure\"\n    case \"Predicate\":\n      return \"Predicate refinement failure\"\n  }\n}\n\nconst getAnnotated = (issue: ParseIssue): Option.Option<AST.Annotated> =>\n  \"ast\" in issue ? Option.some(issue.ast) : Option.none()\n\ninterface CurrentMessage {\n  readonly message: string\n  readonly override: boolean\n}\n\n// TODO: replace with Either.void when 3.13 lands\nconst Either_void = Either.right(undefined)\n\nconst getCurrentMessage = (issue: ParseIssue): Effect.Effect<CurrentMessage | undefined> =>\n  getAnnotated(issue).pipe(\n    Option.flatMap(AST.getMessageAnnotation),\n    Option.match({\n      onNone: () => Either_void,\n      onSome: (messageAnnotation) => {\n        const union = messageAnnotation(issue)\n        if (Predicate.isString(union)) {\n          return Either.right({ message: union, override: false })\n        }\n        if (Effect.isEffect(union)) {\n          return Effect.map(union, (message) => ({ message, override: false }))\n        }\n        if (Predicate.isString(union.message)) {\n          return Either.right({ message: union.message, override: union.override })\n        }\n        return Effect.map(union.message, (message) => ({ message, override: union.override }))\n      }\n    })\n  )\n\nconst createParseIssueGuard =\n  <T extends ParseIssue[\"_tag\"]>(tag: T) => (issue: ParseIssue): issue is Extract<ParseIssue, { _tag: T }> =>\n    issue._tag === tag\n\n/**\n * Returns `true` if the value is a `Composite`.\n *\n * @category guards\n * @since 3.10.0\n */\nexport const isComposite = createParseIssueGuard(\"Composite\")\n\nconst isRefinement = createParseIssueGuard(\"Refinement\")\nconst isTransformation = createParseIssueGuard(\"Transformation\")\n\nconst getMessage = (issue: ParseIssue): Effect.Effect<string | undefined> =>\n  flatMap(getCurrentMessage(issue), (currentMessage) => {\n    if (currentMessage !== undefined) {\n      const useInnerMessage = !currentMessage.override && (\n        isComposite(issue) ||\n        (isRefinement(issue) && issue.kind === \"From\") ||\n        (isTransformation(issue) && issue.kind !== \"Transformation\")\n      )\n      return useInnerMessage\n        ? isTransformation(issue) || isRefinement(issue) ? getMessage(issue.issue) : Either_void\n        : Either.right(currentMessage.message)\n    }\n    return Either_void\n  })\n\nconst getParseIssueTitleAnnotation = (issue: ParseIssue): string | undefined =>\n  getAnnotated(issue).pipe(\n    Option.flatMap(AST.getParseIssueTitleAnnotation),\n    Option.flatMapNullable((annotation) => annotation(issue)),\n    Option.getOrUndefined\n  )\n\n/** @internal */\nexport function getRefinementExpected(ast: AST.Refinement): string {\n  return AST.getDescriptionAnnotation(ast).pipe(\n    Option.orElse(() => AST.getTitleAnnotation(ast)),\n    Option.orElse(() => AST.getAutoTitleAnnotation(ast)),\n    Option.orElse(() => AST.getIdentifierAnnotation(ast)),\n    Option.getOrElse(() => `{ ${ast.from} | filter }`)\n  )\n}\n\nfunction getDefaultTypeMessage(issue: Type): string {\n  if (issue.message !== undefined) {\n    return issue.message\n  }\n  const expected = AST.isRefinement(issue.ast) ? getRefinementExpected(issue.ast) : String(issue.ast)\n  return `Expected ${expected}, actual ${Inspectable.formatUnknown(issue.actual)}`\n}\n\nconst formatTypeMessage = (issue: Type): Effect.Effect<string> =>\n  map(\n    getMessage(issue),\n    (message) => message ?? getParseIssueTitleAnnotation(issue) ?? getDefaultTypeMessage(issue)\n  )\n\nconst getParseIssueTitle = (\n  issue: Forbidden | Transformation | Refinement | Composite\n): string => getParseIssueTitleAnnotation(issue) ?? String(issue.ast)\n\nconst formatForbiddenMessage = (issue: Forbidden): string => issue.message ?? \"is forbidden\"\n\nconst formatUnexpectedMessage = (issue: Unexpected): string => issue.message ?? \"is unexpected\"\n\nconst formatMissingMessage = (issue: Missing): Effect.Effect<string> => {\n  const missingMessageAnnotation = AST.getMissingMessageAnnotation(issue.ast)\n  if (Option.isSome(missingMessageAnnotation)) {\n    const annotation = missingMessageAnnotation.value()\n    return Predicate.isString(annotation) ? Either.right(annotation) : annotation\n  }\n  return Either.right(issue.message ?? \"is missing\")\n}\n\nconst formatTree = (issue: ParseIssue): Effect.Effect<Tree<string>> => {\n  switch (issue._tag) {\n    case \"Type\":\n      return map(formatTypeMessage(issue), makeTree)\n    case \"Forbidden\":\n      return Either.right(makeTree(getParseIssueTitle(issue), [makeTree(formatForbiddenMessage(issue))]))\n    case \"Unexpected\":\n      return Either.right(makeTree(formatUnexpectedMessage(issue)))\n    case \"Missing\":\n      return map(formatMissingMessage(issue), makeTree)\n    case \"Transformation\":\n      return flatMap(getMessage(issue), (message) => {\n        if (message !== undefined) {\n          return Either.right(makeTree(message))\n        }\n        return map(\n          formatTree(issue.issue),\n          (tree) => makeTree(getParseIssueTitle(issue), [makeTree(formatTransformationKind(issue.kind), [tree])])\n        )\n      })\n    case \"Refinement\":\n      return flatMap(getMessage(issue), (message) => {\n        if (message !== undefined) {\n          return Either.right(makeTree(message))\n        }\n        return map(\n          formatTree(issue.issue),\n          (tree) => makeTree(getParseIssueTitle(issue), [makeTree(formatRefinementKind(issue.kind), [tree])])\n        )\n      })\n    case \"Pointer\":\n      return map(formatTree(issue.issue), (tree) => makeTree(util_.formatPath(issue.path), [tree]))\n    case \"Composite\":\n      return flatMap(getMessage(issue), (message) => {\n        if (message !== undefined) {\n          return Either.right(makeTree(message))\n        }\n        const parseIssueTitle = getParseIssueTitle(issue)\n        return util_.isNonEmpty(issue.issues)\n          ? map(Effect.forEach(issue.issues, formatTree), (forest) => makeTree(parseIssueTitle, forest))\n          : map(formatTree(issue.issues), (tree) => makeTree(parseIssueTitle, [tree]))\n      })\n  }\n}\n\n/**\n * Represents an issue returned by the {@link ArrayFormatter} formatter.\n *\n * @category model\n * @since 3.10.0\n */\nexport interface ArrayFormatterIssue {\n  /**\n   * The tag identifying the type of parse issue.\n   */\n  readonly _tag: ParseIssue[\"_tag\"]\n\n  /**\n   * The path to the property where the issue occurred.\n   */\n  readonly path: ReadonlyArray<PropertyKey>\n\n  /**\n   * A descriptive message explaining the issue.\n   */\n  readonly message: string\n}\n\nconst makeArrayFormatterIssue = (\n  _tag: ArrayFormatterIssue[\"_tag\"],\n  path: ArrayFormatterIssue[\"path\"],\n  message: ArrayFormatterIssue[\"message\"]\n): ArrayFormatterIssue => ({ _tag, path, message })\n\n/**\n * @category formatting\n * @since 3.10.0\n */\nexport const ArrayFormatter: ParseResultFormatter<Array<ArrayFormatterIssue>> = {\n  formatIssue: (issue) => getArrayFormatterIssues(issue, undefined, []),\n  formatIssueSync: (issue) => {\n    const e = ArrayFormatter.formatIssue(issue)\n    return isEither(e) ? Either.getOrThrow(e) : Effect.runSync(e)\n  },\n  formatError: (error) => ArrayFormatter.formatIssue(error.issue),\n  formatErrorSync: (error) => ArrayFormatter.formatIssueSync(error.issue)\n}\n\nconst getArrayFormatterIssues = (\n  issue: ParseIssue,\n  parentTag: ArrayFormatterIssue[\"_tag\"] | undefined,\n  path: ReadonlyArray<PropertyKey>\n): Effect.Effect<Array<ArrayFormatterIssue>> => {\n  const _tag = issue._tag\n  switch (_tag) {\n    case \"Type\":\n      return map(formatTypeMessage(issue), (message) => [makeArrayFormatterIssue(parentTag ?? _tag, path, message)])\n    case \"Forbidden\":\n      return Either.right([makeArrayFormatterIssue(_tag, path, formatForbiddenMessage(issue))])\n    case \"Unexpected\":\n      return Either.right([makeArrayFormatterIssue(_tag, path, formatUnexpectedMessage(issue))])\n    case \"Missing\":\n      return map(formatMissingMessage(issue), (message) => [makeArrayFormatterIssue(_tag, path, message)])\n    case \"Pointer\":\n      return getArrayFormatterIssues(issue.issue, undefined, path.concat(issue.path))\n    case \"Composite\":\n      return flatMap(getMessage(issue), (message) => {\n        if (message !== undefined) {\n          return Either.right([makeArrayFormatterIssue(_tag, path, message)])\n        }\n        return util_.isNonEmpty(issue.issues)\n          ? map(Effect.forEach(issue.issues, (issue) => getArrayFormatterIssues(issue, undefined, path)), Arr.flatten)\n          : getArrayFormatterIssues(issue.issues, undefined, path)\n      })\n    case \"Refinement\":\n      return flatMap(getMessage(issue), (message) => {\n        if (message !== undefined) {\n          return Either.right([makeArrayFormatterIssue(_tag, path, message)])\n        }\n        return getArrayFormatterIssues(issue.issue, issue.kind === \"Predicate\" ? _tag : undefined, path)\n      })\n    case \"Transformation\":\n      return flatMap(getMessage(issue), (message) => {\n        if (message !== undefined) {\n          return Either.right([makeArrayFormatterIssue(_tag, path, message)])\n        }\n        return getArrayFormatterIssues(issue.issue, issue.kind === \"Transformation\" ? _tag : undefined, path)\n      })\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/PartitionedSemaphore.ts",
    "content": "/**\n * @since 3.19.4\n * @experimental\n */\nimport * as Effect from \"./Effect.js\"\nimport * as Iterable from \"./Iterable.js\"\nimport * as MutableHashMap from \"./MutableHashMap.js\"\nimport * as Option from \"./Option.js\"\n\n/**\n * @since 3.19.4\n * @category Models\n * @experimental\n */\nexport const TypeId: TypeId = \"~effect/PartitionedSemaphore\"\n\n/**\n * @since 3.19.4\n * @category Models\n * @experimental\n */\nexport type TypeId = \"~effect/PartitionedSemaphore\"\n\n/**\n * A `PartitionedSemaphore` is a concurrency primitive that can be used to\n * control concurrent access to a resource across multiple partitions identified\n * by keys.\n *\n * The total number of permits is shared across all partitions, with waiting\n * permits equally distributed among partitions using a round-robin strategy.\n *\n * This is useful when you want to limit the total number of concurrent accesses\n * to a resource, while still allowing for fair distribution of access across\n * different partitions.\n *\n * @since 3.19.4\n * @category Models\n * @experimental\n */\nexport interface PartitionedSemaphore<in K> {\n  readonly [TypeId]: TypeId\n\n  readonly withPermits: (\n    key: K,\n    permits: number\n  ) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n}\n\n/**\n * A `PartitionedSemaphore` is a concurrency primitive that can be used to\n * control concurrent access to a resource across multiple partitions identified\n * by keys.\n *\n * The total number of permits is shared across all partitions, with waiting\n * permits equally distributed among partitions using a round-robin strategy.\n *\n * This is useful when you want to limit the total number of concurrent accesses\n * to a resource, while still allowing for fair distribution of access across\n * different partitions.\n *\n * @since 3.19.4\n * @category Constructors\n * @experimental\n */\nexport const makeUnsafe = <K = unknown>(options: {\n  readonly permits: number\n}): PartitionedSemaphore<K> => {\n  const maxPermits = Math.max(0, options.permits)\n\n  if (!Number.isFinite(maxPermits)) {\n    return {\n      [TypeId]: TypeId,\n      withPermits: () => (effect) => effect\n    }\n  }\n\n  let totalPermits = maxPermits\n  let waitingPermits = 0\n\n  type Waiter = {\n    permits: number\n    readonly resume: () => void\n  }\n  const partitions = MutableHashMap.empty<K, Set<Waiter>>()\n\n  const take = (key: K, permits: number) =>\n    Effect.async<void>((resume) => {\n      if (maxPermits < permits) {\n        return resume(Effect.never)\n      } else if (totalPermits >= permits) {\n        totalPermits -= permits\n        return resume(Effect.void)\n      }\n\n      const needed = permits - totalPermits\n      const taken = permits - needed\n      if (totalPermits > 0) {\n        totalPermits = 0\n      }\n      waitingPermits += needed\n\n      const waiters = Option.getOrElse(\n        MutableHashMap.get(partitions, key),\n        () => {\n          const set = new Set<Waiter>()\n          MutableHashMap.set(partitions, key, set)\n          return set\n        }\n      )\n\n      const entry: Waiter = {\n        permits: needed,\n        resume() {\n          cleanup()\n          resume(Effect.void)\n        }\n      }\n      function cleanup() {\n        waiters.delete(entry)\n        if (waiters.size === 0) {\n          MutableHashMap.remove(partitions, key)\n        }\n      }\n      waiters.add(entry)\n      return Effect.sync(() => {\n        cleanup()\n        waitingPermits -= entry.permits\n        if (taken > 0) {\n          releaseUnsafe(taken)\n        }\n      })\n    })\n\n  let iterator = partitions[Symbol.iterator]()\n  const releaseUnsafe = (permits: number) => {\n    while (permits > 0) {\n      if (waitingPermits === 0) {\n        totalPermits += permits\n        return\n      }\n\n      let state = iterator.next()\n      if (state.done) {\n        iterator = partitions[Symbol.iterator]()\n        state = iterator.next()\n        if (state.done) return\n      }\n\n      const entry = Iterable.unsafeHead(state.value[1])\n      entry.permits--\n      waitingPermits--\n      if (entry.permits === 0) entry.resume()\n      permits--\n    }\n  }\n\n  return {\n    [TypeId]: TypeId,\n    withPermits: (key, permits) => {\n      const takePermits = take(key, permits)\n      const release: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> = Effect.matchCauseEffect({\n        onFailure(cause) {\n          releaseUnsafe(permits)\n          return Effect.failCause(cause)\n        },\n        onSuccess(value) {\n          releaseUnsafe(permits)\n          return Effect.succeed(value)\n        }\n      })\n      return (effect) =>\n        Effect.uninterruptibleMask((restore) =>\n          Effect.flatMap(\n            restore(takePermits),\n            () => release(restore(effect))\n          )\n        )\n    }\n  }\n}\n\n/**\n * A `PartitionedSemaphore` is a concurrency primitive that can be used to\n * control concurrent access to a resource across multiple partitions identified\n * by keys.\n *\n * The total number of permits is shared across all partitions, with waiting\n * permits equally distributed among partitions using a round-robin strategy.\n *\n * This is useful when you want to limit the total number of concurrent accesses\n * to a resource, while still allowing for fair distribution of access across\n * different partitions.\n *\n * @since 3.19.4\n * @category Constructors\n * @experimental\n */\nexport const make = <K = unknown>(options: {\n  readonly permits: number\n}): Effect.Effect<PartitionedSemaphore<K>> => Effect.sync(() => makeUnsafe<K>(options))\n"
  },
  {
    "path": "packages/effect/src/Pipeable.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport type { Ctor } from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category Models\n */\nexport interface Pipeable {\n  pipe<A>(this: A): A\n  pipe<A, B = never>(this: A, ab: (_: A) => B): B\n  pipe<A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C\n  pipe<A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D\n  pipe<A, B = never, C = never, D = never, E = never>(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E\n  ): E\n  pipe<A, B = never, C = never, D = never, E = never, F = never>(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F\n  ): F\n  pipe<A, B = never, C = never, D = never, E = never, F = never, G = never>(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G\n  ): G\n  pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never>(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H\n  ): H\n  pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never>(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I\n  ): I\n  pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never>(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J\n  ): J\n  pipe<A, B = never, C = never, D = never, E = never, F = never, G = never, H = never, I = never, J = never, K = never>(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K\n  ): K\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L\n  ): L\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never,\n    M = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L,\n    lm: (_: L) => M\n  ): M\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never,\n    M = never,\n    N = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L,\n    lm: (_: L) => M,\n    mn: (_: M) => N\n  ): N\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never,\n    M = never,\n    N = never,\n    O = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L,\n    lm: (_: L) => M,\n    mn: (_: M) => N,\n    no: (_: N) => O\n  ): O\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never,\n    M = never,\n    N = never,\n    O = never,\n    P = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L,\n    lm: (_: L) => M,\n    mn: (_: M) => N,\n    no: (_: N) => O,\n    op: (_: O) => P\n  ): P\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never,\n    M = never,\n    N = never,\n    O = never,\n    P = never,\n    Q = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L,\n    lm: (_: L) => M,\n    mn: (_: M) => N,\n    no: (_: N) => O,\n    op: (_: O) => P,\n    pq: (_: P) => Q\n  ): Q\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never,\n    M = never,\n    N = never,\n    O = never,\n    P = never,\n    Q = never,\n    R = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L,\n    lm: (_: L) => M,\n    mn: (_: M) => N,\n    no: (_: N) => O,\n    op: (_: O) => P,\n    pq: (_: P) => Q,\n    qr: (_: Q) => R\n  ): R\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never,\n    M = never,\n    N = never,\n    O = never,\n    P = never,\n    Q = never,\n    R = never,\n    S = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L,\n    lm: (_: L) => M,\n    mn: (_: M) => N,\n    no: (_: N) => O,\n    op: (_: O) => P,\n    pq: (_: P) => Q,\n    qr: (_: Q) => R,\n    rs: (_: R) => S\n  ): S\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never,\n    M = never,\n    N = never,\n    O = never,\n    P = never,\n    Q = never,\n    R = never,\n    S = never,\n    T = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L,\n    lm: (_: L) => M,\n    mn: (_: M) => N,\n    no: (_: N) => O,\n    op: (_: O) => P,\n    pq: (_: P) => Q,\n    qr: (_: Q) => R,\n    rs: (_: R) => S,\n    st: (_: S) => T\n  ): T\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never,\n    M = never,\n    N = never,\n    O = never,\n    P = never,\n    Q = never,\n    R = never,\n    S = never,\n    T = never,\n    U = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L,\n    lm: (_: L) => M,\n    mn: (_: M) => N,\n    no: (_: N) => O,\n    op: (_: O) => P,\n    pq: (_: P) => Q,\n    qr: (_: Q) => R,\n    rs: (_: R) => S,\n    st: (_: S) => T,\n    tu: (_: T) => U\n  ): U\n  pipe<\n    A,\n    B = never,\n    C = never,\n    D = never,\n    E = never,\n    F = never,\n    G = never,\n    H = never,\n    I = never,\n    J = never,\n    K = never,\n    L = never,\n    M = never,\n    N = never,\n    O = never,\n    P = never,\n    Q = never,\n    R = never,\n    S = never,\n    T = never,\n    U = never\n  >(\n    this: A,\n    ab: (_: A) => B,\n    bc: (_: B) => C,\n    cd: (_: C) => D,\n    de: (_: D) => E,\n    ef: (_: E) => F,\n    fg: (_: F) => G,\n    gh: (_: G) => H,\n    hi: (_: H) => I,\n    ij: (_: I) => J,\n    jk: (_: J) => K,\n    kl: (_: K) => L,\n    lm: (_: L) => M,\n    mn: (_: M) => N,\n    no: (_: N) => O,\n    op: (_: O) => P,\n    pq: (_: P) => Q,\n    qr: (_: Q) => R,\n    rs: (_: R) => S,\n    st: (_: S) => T,\n    tu: (_: T) => U\n  ): U\n}\n\n/**\n * @since 2.0.0\n */\nexport const pipeArguments = <A>(self: A, args: IArguments): unknown => {\n  switch (args.length) {\n    case 0:\n      return self\n    case 1:\n      return args[0](self)\n    case 2:\n      return args[1](args[0](self))\n    case 3:\n      return args[2](args[1](args[0](self)))\n    case 4:\n      return args[3](args[2](args[1](args[0](self))))\n    case 5:\n      return args[4](args[3](args[2](args[1](args[0](self)))))\n    case 6:\n      return args[5](args[4](args[3](args[2](args[1](args[0](self))))))\n    case 7:\n      return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))\n    case 8:\n      return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))\n    case 9:\n      return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))))\n    default: {\n      let ret = self\n      for (let i = 0, len = args.length; i < len; i++) {\n        ret = args[i](ret)\n      }\n      return ret\n    }\n  }\n}\n\n/**\n * @since 3.15.0\n * @category Models\n */\nexport interface PipeableConstructor {\n  new(...args: Array<any>): Pipeable\n}\n\n/**\n * @since 3.15.0\n * @category Prototypes\n */\nexport const Prototype: Pipeable = {\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst Base: PipeableConstructor = (function() {\n  function PipeableBase() {}\n  PipeableBase.prototype = Prototype\n  return PipeableBase as any\n})()\n\n/**\n * @since 3.15.0\n * @category Constructors\n */\nexport const Class: {\n  (): PipeableConstructor\n  <TBase extends Ctor>(klass: TBase): TBase & PipeableConstructor\n} = (klass?: Ctor) =>\n  klass ?\n    class extends klass {\n      pipe() {\n        return pipeArguments(this, arguments)\n      }\n    }\n    : Base\n"
  },
  {
    "path": "packages/effect/src/Pool.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/pool.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const PoolTypeId: unique symbol = internal.PoolTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type PoolTypeId = typeof PoolTypeId\n\n/**\n * A `Pool<A, E>` is a pool of items of type `A`, each of which may be\n * associated with the acquisition and release of resources. An attempt to get\n * an item `A` from a pool may fail with an error of type `E`.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Pool<in out A, out E = never> extends Pool.Variance<A, E>, Effect.Effect<A, E, Scope.Scope>, Pipeable {\n  /**\n   * Retrieves an item from the pool in a scoped effect. Note that if\n   * acquisition fails, then the returned effect will fail for that same reason.\n   * Retrying a failed acquisition attempt will repeat the acquisition attempt.\n   */\n  readonly get: Effect.Effect<A, E, Scope.Scope>\n\n  /**\n   * Invalidates the specified item. This will cause the pool to eventually\n   * reallocate the item, although this reallocation may occur lazily rather\n   * than eagerly.\n   */\n  invalidate(item: A): Effect.Effect<void>\n\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: PoolUnify<this>\n  readonly [Unify.ignoreSymbol]?: PoolUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.9.0\n */\nexport interface PoolUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  Pool?: () => Extract<A[Unify.typeSymbol], Pool<any, any>> extends Pool<infer A0, infer _E0> | infer _ ?\n    A0 extends any ? Extract<A[Unify.typeSymbol], Pool<A0, any>> extends Pool<A0, infer E1> ? Pool<A0, E1>\n      : never\n    : never :\n    never\n}\n\n/**\n * @category models\n * @since 3.9.0\n */\nexport interface PoolUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Pool {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A, out E> {\n    readonly [PoolTypeId]: {\n      readonly _A: Types.Invariant<A>\n      readonly _E: Types.Covariant<E>\n    }\n  }\n}\n\n/**\n * Returns `true` if the specified value is a `Pool`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isPool: (u: unknown) => u is Pool<unknown, unknown> = internal.isPool\n\n/**\n * Makes a new pool of the specified fixed size. The pool is returned in a\n * `Scope`, which governs the lifetime of the pool. When the pool is shutdown\n * because the `Scope` is closed, the individual items allocated by the pool\n * will be released in some unspecified order.\n *\n * By setting the `concurrency` parameter, you can control the level of concurrent\n * access per pool item. By default, the number of permits is set to `1`.\n *\n * `targetUtilization` determines when to create new pool items. It is a value\n * between 0 and 1, where 1 means only create new pool items when all the existing\n * items are fully utilized.\n *\n * A `targetUtilization` of 0.5 will create new pool items when the existing items are\n * 50% utilized.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A, E, R>(\n  options: {\n    readonly acquire: Effect.Effect<A, E, R>\n    readonly size: number\n    readonly concurrency?: number | undefined\n    readonly targetUtilization?: number | undefined\n  }\n) => Effect.Effect<Pool<A, E>, never, Scope.Scope | R> = internal.make\n\n/**\n * Makes a new pool with the specified minimum and maximum sizes and time to\n * live before a pool whose excess items are not being used will be shrunk\n * down to the minimum size. The pool is returned in a `Scope`, which governs\n * the lifetime of the pool. When the pool is shutdown because the `Scope` is\n * used, the individual items allocated by the pool will be released in some\n * unspecified order.\n *\n * By setting the `concurrency` parameter, you can control the level of concurrent\n * access per pool item. By default, the number of permits is set to `1`.\n *\n * `targetUtilization` determines when to create new pool items. It is a value\n * between 0 and 1, where 1 means only create new pool items when all the existing\n * items are fully utilized.\n *\n * A `targetUtilization` of 0.5 will create new pool items when the existing items are\n * 50% utilized.\n *\n * The `timeToLiveStrategy` determines how items are invalidated. If set to\n * \"creation\", then items are invalidated based on their creation time. If set\n * to \"usage\", then items are invalidated based on pool usage.\n *\n * By default, the `timeToLiveStrategy` is set to \"usage\".\n *\n * ```ts skip-type-checking\n * import { createConnection } from \"mysql2\";\n * import { Duration, Effect, Pool } from \"effect\"\n *\n * const acquireDBConnection = Effect.acquireRelease(\n *   Effect.sync(() => createConnection('mysql://...')),\n *   (connection) => Effect.sync(() => connection.end(() => {})),\n * )\n *\n * const connectionPool = Effect.flatMap(\n *  Pool.makeWithTTL({\n *     acquire: acquireDBConnection,\n *     min: 10,\n *     max: 20,\n *     timeToLive: Duration.seconds(60)\n *   }),\n *   (pool) => pool.get\n * )\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeWithTTL: <A, E, R>(\n  options: {\n    readonly acquire: Effect.Effect<A, E, R>\n    readonly min: number\n    readonly max: number\n    readonly concurrency?: number | undefined\n    readonly targetUtilization?: number | undefined\n    readonly timeToLive: Duration.DurationInput\n    readonly timeToLiveStrategy?: \"creation\" | \"usage\" | undefined\n  }\n) => Effect.Effect<Pool<A, E>, never, Scope.Scope | R> = internal.makeWithTTL\n\n/**\n * Retrieves an item from the pool in a scoped effect. Note that if\n * acquisition fails, then the returned effect will fail for that same reason.\n * Retrying a failed acquisition attempt will repeat the acquisition attempt.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const get: <A, E>(self: Pool<A, E>) => Effect.Effect<A, E, Scope.Scope> = internal.get\n\n/**\n * Invalidates the specified item. This will cause the pool to eventually\n * reallocate the item, although this reallocation may occur lazily rather\n * than eagerly.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const invalidate: {\n  <A>(value: A): <E>(self: Pool<A, E>) => Effect.Effect<void, never, Scope.Scope>\n  <A, E>(self: Pool<A, E>, value: A): Effect.Effect<void, never, Scope.Scope>\n} = internal.invalidate\n"
  },
  {
    "path": "packages/effect/src/Predicate.ts",
    "content": "/**\n * This module provides a collection of functions for working with predicates and refinements.\n *\n * A `Predicate<A>` is a function that takes a value of type `A` and returns a boolean.\n * It is used to check if a value satisfies a certain condition.\n *\n * A `Refinement<A, B>` is a special type of predicate that not only checks a condition\n * but also provides a type guard, allowing TypeScript to narrow the type of the input\n * value from `A` to a more specific type `B` within a conditional block.\n *\n * The module includes:\n * - Basic predicates and refinements for common types (e.g., `isString`, `isNumber`).\n * - Combinators to create new predicates from existing ones (e.g., `and`, `or`, `not`).\n * - Advanced combinators for working with data structures (e.g., `tuple`, `struct`).\n * - Type-level utilities for inspecting predicate and refinement types.\n *\n * @since 2.0.0\n */\nimport { dual, isFunction as isFunction_ } from \"./Function.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport type { TupleOf, TupleOfAtLeast } from \"./Types.js\"\n\n/**\n * Represents a function that takes a value of type `A` and returns `true` if the value\n * satisfies some condition, `false` otherwise.\n *\n * @example\n * ```ts\n * import { Predicate } from \"effect\"\n * import * as assert from \"node:assert\"\n *\n * const isEven: Predicate.Predicate<number> = (n) => n % 2 === 0\n *\n * assert.strictEqual(isEven(2), true)\n * assert.strictEqual(isEven(3), false)\n * ```\n *\n * @category models\n * @since 2.0.0\n */\nexport interface Predicate<in A> {\n  (a: A): boolean\n}\n\n/**\n * A `TypeLambda` for `Predicate`. This is used to support higher-kinded types\n * and allows `Predicate` to be used in generic contexts within the `effect` ecosystem.\n *\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface PredicateTypeLambda extends TypeLambda {\n  readonly type: Predicate<this[\"Target\"]>\n}\n\n/**\n * Represents a function that serves as a type guard.\n *\n * A `Refinement<A, B>` is a function that takes a value of type `A` and returns a\n * type predicate `a is B`, where `B` is a subtype of `A`. If the function returns\n * `true`, TypeScript will narrow the type of the input variable to `B`.\n *\n * @example\n * ```ts\n * import { Predicate } from \"effect\"\n * import * as assert from \"node:assert\"\n *\n * const isString: Predicate.Refinement<unknown, string> = (u): u is string => typeof u === \"string\"\n *\n * const value: unknown = \"hello\"\n *\n * if (isString(value)) {\n *   // value is now known to be a string\n *   assert.strictEqual(value.toUpperCase(), \"HELLO\")\n * }\n * ```\n *\n * @category models\n * @since 2.0.0\n */\nexport interface Refinement<in A, out B extends A> {\n  (a: A): a is B\n}\n\n/**\n * A namespace for type-level utilities for `Predicate`.\n *\n * @since 3.6.0\n * @category type-level\n */\nexport declare namespace Predicate {\n  /**\n   * Extracts the input type `A` from a `Predicate<A>`.\n   *\n   * @example\n   * ```ts\n   * import { type Predicate } from \"effect\"\n   *\n   * type T = Predicate.Predicate.In<Predicate.Predicate<string>> // T is string\n   * ```\n   *\n   * @since 3.6.0\n   * @category type-level\n   */\n  export type In<T extends Any> = [T] extends [Predicate<infer _A>] ? _A : never\n  /**\n   * A type representing any `Predicate`.\n   *\n   * @since 3.6.0\n   * @category type-level\n   */\n  export type Any = Predicate<never>\n}\n\n/**\n * A namespace for type-level utilities for `Refinement`.\n *\n * @since 3.6.0\n * @category type-level\n */\nexport declare namespace Refinement {\n  /**\n   * Extracts the input type `A` from a `Refinement<A, B>`.\n   *\n   * @example\n   * ```ts\n   * import { type Predicate } from \"effect\"\n   *\n   * type IsString = Predicate.Refinement<unknown, string>\n   * type T = Predicate.Refinement.In<IsString> // T is unknown\n   * ```\n   *\n   * @since 3.6.0\n   * @category type-level\n   */\n  export type In<T extends Any> = [T] extends [Refinement<infer _A, infer _>] ? _A : never\n  /**\n   * Extracts the output (refined) type `B` from a `Refinement<A, B>`.\n   *\n   * @example\n   * ```ts\n   * import { type Predicate } from \"effect\"\n   *\n   * type IsString = Predicate.Refinement<unknown, string>\n   * type T = Predicate.Refinement.Out<IsString> // T is string\n   * ```\n   *\n   * @since 3.6.0\n   * @category type-level\n   */\n  export type Out<T extends Any> = [T] extends [Refinement<infer _, infer _B>] ? _B : never\n  /**\n   * A type representing any `Refinement`.\n   *\n   * @since 3.6.0\n   * @category type-level\n   */\n  export type Any = Refinement<any, any>\n}\n\n/**\n * Transforms a `Predicate<A>` into a `Predicate<B>` by applying a function `(b: B) => A`\n * to the input before passing it to the predicate. This is also known as \"contramap\" or\n * \"pre-composition\".\n *\n * @example\n * ```ts\n * import { Predicate, Number } from \"effect\"\n * import * as assert from \"node:assert\"\n *\n * // A predicate on numbers\n * const isPositive: Predicate.Predicate<number> = Number.greaterThan(0)\n *\n * // A function from `string` to `number`\n * const stringLength = (s: string): number => s.length\n *\n * // Create a new predicate on strings by mapping the input\n * const hasPositiveLength = Predicate.mapInput(isPositive, stringLength)\n *\n * assert.strictEqual(hasPositiveLength(\"hello\"), true)\n * assert.strictEqual(hasPositiveLength(\"\"), false)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const mapInput: {\n  <B, A>(f: (b: B) => A): (self: Predicate<A>) => Predicate<B>\n  <A, B>(self: Predicate<A>, f: (b: B) => A): Predicate<B>\n} = dual(2, <A, B>(self: Predicate<A>, f: (b: B) => A): Predicate<B> => (b) => self(f(b)))\n\n/**\n * A refinement that checks if a `ReadonlyArray<T>` is a tuple with exactly `N` elements.\n * If the check is successful, the type is narrowed to `TupleOf<N, T>`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isTupleOf } from \"effect/Predicate\"\n *\n * const isTupleOf3 = isTupleOf(3)\n *\n * assert.strictEqual(isTupleOf3([1, 2, 3]), true);\n * assert.strictEqual(isTupleOf3([1, 2]), false);\n *\n * const arr: number[] = [1, 2, 3];\n * if (isTupleOf(arr, 3)) {\n *   // The type of arr is now [number, number, number]\n *   const [a, b, c] = arr;\n *   assert.deepStrictEqual([a, b, c], [1, 2, 3])\n * }\n * ```\n *\n * @category guards\n * @since 3.3.0\n */\nexport const isTupleOf: {\n  <N extends number>(n: N): <T>(self: ReadonlyArray<T>) => self is TupleOf<N, T>\n  <T, N extends number>(self: ReadonlyArray<T>, n: N): self is TupleOf<N, T>\n} = dual(2, <T, N extends number>(self: ReadonlyArray<T>, n: N): self is TupleOf<N, T> => self.length === n)\n\n/**\n * A refinement that checks if a `ReadonlyArray<T>` is a tuple with at least `N` elements.\n * If the check is successful, the type is narrowed to `TupleOfAtLeast<N, T>`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isTupleOfAtLeast } from \"effect/Predicate\"\n *\n * const isTupleOfAtLeast3 = isTupleOfAtLeast(3)\n *\n * assert.strictEqual(isTupleOfAtLeast3([1, 2, 3]), true);\n * assert.strictEqual(isTupleOfAtLeast3([1, 2, 3, 4]), true);\n * assert.strictEqual(isTupleOfAtLeast3([1, 2]), false);\n *\n * const arr: number[] = [1, 2, 3, 4];\n * if (isTupleOfAtLeast(arr, 3)) {\n *   // The type of arr is now [number, number, number, ...number[]]\n *   const [a, b, c] = arr;\n *   assert.deepStrictEqual([a, b, c], [1, 2, 3])\n * }\n * ```\n *\n * @category guards\n * @since 3.3.0\n */\nexport const isTupleOfAtLeast: {\n  <N extends number>(n: N): <T>(self: ReadonlyArray<T>) => self is TupleOfAtLeast<N, T>\n  <T, N extends number>(self: ReadonlyArray<T>, n: N): self is TupleOfAtLeast<N, T>\n} = dual(2, <T, N extends number>(self: ReadonlyArray<T>, n: N): self is TupleOfAtLeast<N, T> => self.length >= n)\n\n/**\n * A predicate that checks if a value is \"truthy\" in JavaScript.\n * Fails for `false`, `0`, `-0`, `0n`, `\"\"`, `null`, `undefined`, and `NaN`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isTruthy } from \"effect/Predicate\"\n *\n * assert.strictEqual(isTruthy(1), true)\n * assert.strictEqual(isTruthy(\"hello\"), true)\n * assert.strictEqual(isTruthy({}), true)\n *\n * assert.strictEqual(isTruthy(0), false)\n * assert.strictEqual(isTruthy(\"\"), false)\n * assert.strictEqual(isTruthy(null), false)\n * assert.strictEqual(isTruthy(undefined), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isTruthy = (input: unknown) => !!input\n\n/**\n * A refinement that checks if a value is a `Set`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isSet } from \"effect/Predicate\"\n *\n * assert.strictEqual(isSet(new Set([1, 2])), true)\n * assert.strictEqual(isSet(new Set()), true)\n *\n * assert.strictEqual(isSet({}), false)\n * assert.strictEqual(isSet([1, 2]), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isSet = (input: unknown): input is Set<unknown> => input instanceof Set\n\n/**\n * A refinement that checks if a value is a `Map`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isMap } from \"effect/Predicate\"\n *\n * assert.strictEqual(isMap(new Map()), true)\n *\n * assert.strictEqual(isMap({}), false)\n * assert.strictEqual(isMap(new Set()), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isMap = (input: unknown): input is Map<unknown, unknown> => input instanceof Map\n\n/**\n * A refinement that checks if a value is a `string`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isString } from \"effect/Predicate\"\n *\n * assert.strictEqual(isString(\"hello\"), true)\n * assert.strictEqual(isString(\"\"), true)\n *\n * assert.strictEqual(isString(123), false)\n * assert.strictEqual(isString(null), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isString = (input: unknown): input is string => typeof input === \"string\"\n\n/**\n * A refinement that checks if a value is a `number`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isNumber } from \"effect/Predicate\"\n *\n * assert.strictEqual(isNumber(123), true)\n * assert.strictEqual(isNumber(0), true)\n * assert.strictEqual(isNumber(-1.5), true)\n * assert.strictEqual(isNumber(NaN), true)\n *\n * assert.strictEqual(isNumber(\"123\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isNumber = (input: unknown): input is number => typeof input === \"number\"\n\n/**\n * A refinement that checks if a value is a `boolean`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isBoolean } from \"effect/Predicate\"\n *\n * assert.strictEqual(isBoolean(true), true)\n * assert.strictEqual(isBoolean(false), true)\n *\n * assert.strictEqual(isBoolean(\"true\"), false)\n * assert.strictEqual(isBoolean(0), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isBoolean = (input: unknown): input is boolean => typeof input === \"boolean\"\n\n/**\n * A refinement that checks if a value is a `bigint`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isBigInt } from \"effect/Predicate\"\n *\n * assert.strictEqual(isBigInt(1n), true)\n *\n * assert.strictEqual(isBigInt(1), false)\n * assert.strictEqual(isBigInt(\"1\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isBigInt = (input: unknown): input is bigint => typeof input === \"bigint\"\n\n/**\n * A refinement that checks if a value is a `symbol`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isSymbol } from \"effect/Predicate\"\n *\n * assert.strictEqual(isSymbol(Symbol.for(\"a\")), true)\n *\n * assert.strictEqual(isSymbol(\"a\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isSymbol = (input: unknown): input is symbol => typeof input === \"symbol\"\n\n// TODO: make public\n/**\n * A refinement that checks if a value is a valid `PropertyKey` (a `string`, `number`, or `symbol`).\n * @internal\n */\nexport const isPropertyKey = (u: unknown): u is PropertyKey => isString(u) || isNumber(u) || isSymbol(u)\n\n/**\n * A refinement that checks if a value is a `Function`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isFunction } from \"effect/Predicate\"\n *\n * assert.strictEqual(isFunction(() => {}), true)\n * assert.strictEqual(isFunction(isFunction), true)\n *\n * assert.strictEqual(isFunction(\"function\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isFunction: (input: unknown) => input is Function = isFunction_\n\n/**\n * A refinement that checks if a value is `undefined`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isUndefined } from \"effect/Predicate\"\n *\n * assert.strictEqual(isUndefined(undefined), true)\n *\n * assert.strictEqual(isUndefined(null), false)\n * assert.strictEqual(isUndefined(\"undefined\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isUndefined = (input: unknown): input is undefined => input === undefined\n\n/**\n * A refinement that checks if a value is not `undefined`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isNotUndefined } from \"effect/Predicate\"\n *\n * assert.strictEqual(isNotUndefined(null), true)\n * assert.strictEqual(isNotUndefined(\"value\"), true)\n *\n * assert.strictEqual(isNotUndefined(undefined), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isNotUndefined = <A>(input: A): input is Exclude<A, undefined> => input !== undefined\n\n/**\n * A refinement that checks if a value is `null`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isNull } from \"effect/Predicate\"\n *\n * assert.strictEqual(isNull(null), true)\n *\n * assert.strictEqual(isNull(undefined), false)\n * assert.strictEqual(isNull(\"null\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isNull = (input: unknown): input is null => input === null\n\n/**\n * A refinement that checks if a value is not `null`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isNotNull } from \"effect/Predicate\"\n *\n * assert.strictEqual(isNotNull(undefined), true)\n * assert.strictEqual(isNotNull(\"value\"), true)\n *\n * assert.strictEqual(isNotNull(null), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isNotNull = <A>(input: A): input is Exclude<A, null> => input !== null\n\n/**\n * A refinement that always returns `false`. The type is narrowed to `never`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isNever } from \"effect/Predicate\"\n *\n * assert.strictEqual(isNever(1), false)\n * assert.strictEqual(isNever(null), false)\n * assert.strictEqual(isNever({}), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isNever: (input: unknown) => input is never = (_: unknown): _ is never => false\n\n/**\n * A refinement that always returns `true`. The type is narrowed to `unknown`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isUnknown } from \"effect/Predicate\"\n *\n * assert.strictEqual(isUnknown(1), true)\n * assert.strictEqual(isUnknown(null), true)\n * assert.strictEqual(isUnknown({}), true)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isUnknown: (input: unknown) => input is unknown = (_): _ is unknown => true\n\n/**\n * Checks if the input is an object or an array.\n * @internal\n */\nexport const isRecordOrArray = (input: unknown): input is { [x: PropertyKey]: unknown } =>\n  typeof input === \"object\" && input !== null\n\n/**\n * A refinement that checks if a value is an `object`. Note that in JavaScript,\n * arrays and functions are also considered objects.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isObject } from \"effect/Predicate\"\n *\n * assert.strictEqual(isObject({}), true)\n * assert.strictEqual(isObject([]), true)\n * assert.strictEqual(isObject(() => {}), true)\n *\n * assert.strictEqual(isObject(null), false)\n * assert.strictEqual(isObject(\"hello\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n * @see isRecord to check for plain objects (excluding arrays and functions).\n */\nexport const isObject = (input: unknown): input is object => isRecordOrArray(input) || isFunction(input)\n\n/**\n * A refinement that checks if a value is an object-like value and has a specific property key.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { hasProperty } from \"effect/Predicate\"\n *\n * assert.strictEqual(hasProperty({ a: 1 }, \"a\"), true)\n * assert.strictEqual(hasProperty({ a: 1 }, \"b\"), false)\n *\n * const value: unknown = { name: \"Alice\" };\n * if (hasProperty(value, \"name\")) {\n *   // The type of `value` is narrowed to `{ name: unknown }`\n *   // and we can safely access `value.name`\n *   console.log(value.name)\n * }\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const hasProperty: {\n  <P extends PropertyKey>(property: P): (self: unknown) => self is { [K in P]: unknown }\n  <P extends PropertyKey>(self: unknown, property: P): self is { [K in P]: unknown }\n} = dual(\n  2,\n  <P extends PropertyKey>(self: unknown, property: P): self is { [K in P]: unknown } =>\n    isObject(self) && (property in self)\n)\n\n/**\n * A refinement that checks if a value is an object with a `_tag` property\n * that matches the given tag. This is a powerful tool for working with\n * discriminated union types.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isTagged } from \"effect/Predicate\"\n *\n * type Shape = { _tag: \"circle\"; radius: number } | { _tag: \"square\"; side: number }\n *\n * const isCircle = isTagged(\"circle\")\n *\n * const shape1: Shape = { _tag: \"circle\", radius: 10 }\n * const shape2: Shape = { _tag: \"square\", side: 5 }\n *\n * assert.strictEqual(isCircle(shape1), true)\n * assert.strictEqual(isCircle(shape2), false)\n *\n * if (isCircle(shape1)) {\n *   // shape1 is now narrowed to { _tag: \"circle\"; radius: number }\n *   assert.strictEqual(shape1.radius, 10)\n * }\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isTagged: {\n  <K extends string>(tag: K): (self: unknown) => self is { _tag: K }\n  <K extends string>(self: unknown, tag: K): self is { _tag: K }\n} = dual(\n  2,\n  <K extends string>(self: unknown, tag: K): self is { _tag: K } => hasProperty(self, \"_tag\") && self[\"_tag\"] === tag\n)\n\n/**\n * A refinement that checks if a value is either `null` or `undefined`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isNullable } from \"effect/Predicate\"\n *\n * assert.strictEqual(isNullable(null), true)\n * assert.strictEqual(isNullable(undefined), true)\n *\n * assert.strictEqual(isNullable(0), false)\n * assert.strictEqual(isNullable(\"\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n * @see isNotNullable\n */\nexport const isNullable = <A>(input: A): input is Extract<A, null | undefined> => input === null || input === undefined\n\n/**\n * A refinement that checks if a value is neither `null` nor `undefined`.\n * The type is narrowed to `NonNullable<A>`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isNotNullable } from \"effect/Predicate\"\n *\n * assert.strictEqual(isNotNullable(0), true)\n * assert.strictEqual(isNotNullable(\"hello\"), true)\n *\n * assert.strictEqual(isNotNullable(null), false)\n * assert.strictEqual(isNotNullable(undefined), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n * @see isNullable\n */\nexport const isNotNullable = <A>(input: A): input is NonNullable<A> => input !== null && input !== undefined\n\n/**\n * A refinement that checks if a value is an instance of `Error`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isError } from \"effect/Predicate\"\n *\n * assert.strictEqual(isError(new Error(\"boom\")), true)\n * assert.strictEqual(isError(new TypeError(\"boom\")), true)\n *\n * assert.strictEqual(isError({ message: \"boom\" }), false)\n * assert.strictEqual(isError(\"boom\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isError = (input: unknown): input is Error => input instanceof Error\n\n/**\n * A refinement that checks if a value is a `Uint8Array`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isUint8Array } from \"effect/Predicate\"\n *\n * assert.strictEqual(isUint8Array(new Uint8Array()), true)\n *\n * assert.strictEqual(isUint8Array(new Uint16Array()), false)\n * assert.strictEqual(isUint8Array([1, 2, 3]), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isUint8Array = (input: unknown): input is Uint8Array => input instanceof Uint8Array\n\n/**\n * A refinement that checks if a value is a `Date` object.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isDate } from \"effect/Predicate\"\n *\n * assert.strictEqual(isDate(new Date()), true)\n *\n * assert.strictEqual(isDate(Date.now()), false) // `Date.now()` returns a number\n * assert.strictEqual(isDate(\"2023-01-01\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isDate = (input: unknown): input is Date => input instanceof Date\n\n/**\n * A refinement that checks if a value is an `Iterable`.\n * Many built-in types are iterable, such as `Array`, `string`, `Map`, and `Set`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isIterable } from \"effect/Predicate\"\n *\n * assert.strictEqual(isIterable([]), true)\n * assert.strictEqual(isIterable(\"hello\"), true)\n * assert.strictEqual(isIterable(new Set()), true)\n *\n * assert.strictEqual(isIterable({}), false)\n * assert.strictEqual(isIterable(123), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isIterable = (input: unknown): input is Iterable<unknown> =>\n  typeof input === \"string\" || hasProperty(input, Symbol.iterator)\n\n/**\n * A refinement that checks if a value is a record (i.e., a plain object).\n * This check returns `false` for arrays, `null`, and functions.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isRecord } from \"effect/Predicate\"\n *\n * assert.strictEqual(isRecord({}), true)\n * assert.strictEqual(isRecord({ a: 1 }), true)\n *\n * assert.strictEqual(isRecord([]), false)\n * assert.strictEqual(isRecord(new Date()), false)\n * assert.strictEqual(isRecord(null), false)\n * assert.strictEqual(isRecord(() => null), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n * @see isObject\n */\nexport const isRecord = (input: unknown): input is { [x: string | symbol]: unknown } =>\n  isRecordOrArray(input) && !Array.isArray(input)\n\n/**\n * A refinement that checks if a value is a readonly record (i.e., a plain object).\n * This check returns `false` for arrays, `null`, and functions.\n *\n * This is an alias for `isRecord`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isReadonlyRecord } from \"effect/Predicate\"\n *\n * assert.strictEqual(isReadonlyRecord({}), true)\n * assert.strictEqual(isReadonlyRecord({ a: 1 }), true)\n *\n * assert.strictEqual(isReadonlyRecord([]), false)\n * assert.strictEqual(isReadonlyRecord(null), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isReadonlyRecord: (\n  input: unknown\n) => input is { readonly [x: string | symbol]: unknown } = isRecord\n\n/**\n * A refinement that checks if a value is a `Promise`. It performs a duck-typing check\n * for `.then` and `.catch` methods.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isPromise } from \"effect/Predicate\"\n *\n * assert.strictEqual(isPromise(Promise.resolve(1)), true)\n * assert.strictEqual(isPromise(new Promise(() => {})), true)\n *\n * assert.strictEqual(isPromise({ then() {} }), false) // Missing .catch\n * assert.strictEqual(isPromise({}), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n * @see isPromiseLike\n */\nexport const isPromise = (\n  input: unknown\n): input is Promise<unknown> =>\n  hasProperty(input, \"then\") && \"catch\" in input && isFunction(input.then) && isFunction(input.catch)\n\n/**\n * A refinement that checks if a value is `PromiseLike`. It performs a duck-typing\n * check for a `.then` method.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isPromiseLike } from \"effect/Predicate\"\n *\n * assert.strictEqual(isPromiseLike(Promise.resolve(1)), true)\n * assert.strictEqual(isPromiseLike({ then: () => {} }), true)\n *\n * assert.strictEqual(isPromiseLike({}), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n * @see isPromise\n */\nexport const isPromiseLike = (\n  input: unknown\n): input is PromiseLike<unknown> => hasProperty(input, \"then\") && isFunction(input.then)\n\n/**\n * A refinement that checks if a value is a `RegExp`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * assert.strictEqual(Predicate.isRegExp(/a/), true)\n * assert.strictEqual(Predicate.isRegExp(new RegExp(\"a\")), true)\n *\n * assert.strictEqual(Predicate.isRegExp(\"/a/\"), false)\n * ```\n *\n * @category guards\n * @since 3.9.0\n */\nexport const isRegExp = (input: unknown): input is RegExp => input instanceof RegExp\n\n/**\n * Composes a `Refinement` with another `Refinement` or `Predicate`.\n *\n * This can be used to chain checks. The first refinement is applied, and if it\n * passes, the second check is applied to the same value, potentially refining\n * the type further.\n *\n * @example\n * ```ts\n * import { Predicate } from \"effect\"\n * import * as assert from \"node:assert\"\n *\n * const isString = (u: unknown): u is string => typeof u === \"string\"\n * const minLength = (n: number) => (s: string): boolean => s.length >= n\n *\n * // Create a refinement that checks for a string with a minimum length of 3\n * const isLongString = Predicate.compose(isString, minLength(3))\n *\n * let value: unknown = \"hello\"\n *\n * assert.strictEqual(isLongString(value), true)\n * if (isLongString(value)) {\n *   // value is narrowed to string\n *   assert.strictEqual(value.toUpperCase(), \"HELLO\")\n * }\n * assert.strictEqual(isLongString(\"hi\"), false)\n * ```\n *\n * @since 2.0.0\n */\nexport const compose: {\n  <A, B extends A, C extends B, D extends C>(bc: Refinement<C, D>): (ab: Refinement<A, B>) => Refinement<A, D>\n  <A, B extends A>(bc: Predicate<NoInfer<B>>): (ab: Refinement<A, B>) => Refinement<A, B>\n  <A, B extends A, C extends B, D extends C>(ab: Refinement<A, B>, bc: Refinement<C, D>): Refinement<A, D>\n  <A, B extends A>(ab: Refinement<A, B>, bc: Predicate<NoInfer<B>>): Refinement<A, B>\n} = dual(\n  2,\n  <A, B extends A, C extends B, D extends C>(ab: Refinement<A, B>, bc: Refinement<C, D>): Refinement<A, D> =>\n  (a): a is D => ab(a) && bc(a as C)\n)\n\n/**\n * Combines two predicates to test a tuple of two values. The first predicate tests the\n * first element of the tuple, and the second predicate tests the second element.\n *\n * @category combining\n * @since 2.0.0\n */\nexport const product =\n  <A, B>(self: Predicate<A>, that: Predicate<B>): Predicate<readonly [A, B]> /* readonly because contravariant */ =>\n  ([a, b]) => self(a) && that(b)\n\n/**\n * Takes an iterable of predicates and returns a new predicate that tests an array of values.\n * The new predicate returns `true` if each predicate at a given index is satisfied by the\n * value at the same index in the array. The check stops at the length of the shorter of\n * the two iterables (predicates or values).\n *\n * @category combining\n * @since 2.0.0\n * @see tuple for a more powerful, variadic version.\n */\nexport const all = <A>(\n  collection: Iterable<Predicate<A>>\n): Predicate<ReadonlyArray<A>> => {\n  return (as) => {\n    let collectionIndex = 0\n    for (const p of collection) {\n      if (collectionIndex >= as.length) {\n        break\n      }\n      if (p(as[collectionIndex]) === false) {\n        return false\n      }\n      collectionIndex++\n    }\n    return true\n  }\n}\n\n/**\n * Combines a predicate for a single value and an iterable of predicates for the rest of an array.\n * Useful for checking the head and tail of an array separately.\n *\n * @category combining\n * @since 2.0.0\n */\nexport const productMany = <A>(\n  self: Predicate<A>,\n  collection: Iterable<Predicate<A>>\n): Predicate<readonly [A, ...Array<A>]> /* readonly because contravariant */ => {\n  const rest = all(collection)\n  return ([head, ...tail]) => self(head) === false ? false : rest(tail)\n}\n\n/**\n * Combines an array of predicates into a single predicate that tests an array of values.\n * This function is highly type-aware and will produce a `Refinement` if any of the provided\n * predicates are `Refinement`s, allowing for powerful type-narrowing of tuples.\n *\n * - If all predicates are `Predicate<T>`, the result is `Predicate<[T, T, ...]>`.\n * - If any predicate is a `Refinement<A, B>`, the result is a `Refinement` that narrows\n *   the input tuple type to a more specific tuple type.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * const isString = (u: unknown): u is string => typeof u === \"string\"\n * const isNumber = (u: unknown): u is number => typeof u === \"number\"\n *\n * // Create a refinement for a [string, number] tuple\n * const isStringNumberTuple = Predicate.tuple(isString, isNumber)\n *\n * const value: [unknown, unknown] = [\"hello\", 123]\n * if (isStringNumberTuple(value)) {\n *   // value is narrowed to [string, number]\n *   const [s, n] = value\n *   assert.strictEqual(s.toUpperCase(), \"HELLO\")\n *   assert.strictEqual(n.toFixed(2), \"123.00\")\n * }\n * assert.strictEqual(isStringNumberTuple([\"hello\", \"123\"]), false)\n * ```\n *\n * @since 2.0.0\n */\nexport const tuple: {\n  <T extends ReadonlyArray<Predicate.Any>>(\n    ...elements: T\n  ): [Extract<T[number], Refinement.Any>] extends [never] ? Predicate<{ readonly [I in keyof T]: Predicate.In<T[I]> }>\n    : Refinement<\n      { readonly [I in keyof T]: T[I] extends Refinement.Any ? Refinement.In<T[I]> : Predicate.In<T[I]> },\n      { readonly [I in keyof T]: T[I] extends Refinement.Any ? Refinement.Out<T[I]> : Predicate.In<T[I]> }\n    >\n} = (...elements: ReadonlyArray<Predicate.Any>) => all(elements) as any\n\n/**\n * Combines a record of predicates into a single predicate that tests a record of values.\n * This function is highly type-aware and will produce a `Refinement` if any of the provided\n * predicates are `Refinement`s, allowing for powerful type-narrowing of structs.\n *\n * - If all predicates are `Predicate<T>`, the result is `Predicate<{ k: T, ... }>`.\n * - If any predicate is a `Refinement<A, B>`, the result is a `Refinement` that narrows\n *   the input record type to a more specific record type.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * const isString = (u: unknown): u is string => typeof u === \"string\"\n * const isNumber = (u: unknown): u is number => typeof u === \"number\"\n *\n * const personPredicate = Predicate.struct({\n *   name: isString,\n *   age: isNumber\n * })\n *\n * const value: { name: unknown; age: unknown } = { name: \"Alice\", age: 30 }\n * if (personPredicate(value)) {\n *   // value is narrowed to { name: string; age: number }\n *   assert.strictEqual(value.name.toUpperCase(), \"ALICE\")\n *   assert.strictEqual(value.age.toFixed(0), \"30\")\n * }\n * assert.strictEqual(personPredicate({ name: \"Bob\", age: \"40\" }), false)\n * ```\n *\n * @since 2.0.0\n */\nexport const struct: {\n  <R extends Record<string, Predicate.Any>>(\n    fields: R\n  ): [Extract<R[keyof R], Refinement.Any>] extends [never] ?\n    Predicate<{ readonly [K in keyof R]: Predicate.In<R[K]> }> :\n    Refinement<\n      { readonly [K in keyof R]: R[K] extends Refinement.Any ? Refinement.In<R[K]> : Predicate.In<R[K]> },\n      { readonly [K in keyof R]: R[K] extends Refinement.Any ? Refinement.Out<R[K]> : Predicate.In<R[K]> }\n    >\n} = (<R extends Record<string, Predicate.Any>>(fields: R) => {\n  const keys = Object.keys(fields)\n  return (a: Record<string, unknown>) => {\n    for (const key of keys) {\n      if (!fields[key](a[key] as never)) {\n        return false\n      }\n    }\n    return true\n  }\n}) as any\n\n/**\n * Returns a new predicate that is the logical negation of the given predicate.\n *\n * **Note**: If the input is a `Refinement`, the resulting predicate will be a\n * simple `Predicate`, as TypeScript cannot infer the negative type.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate, Number } from \"effect\"\n *\n * const isNonPositive = Predicate.not(Number.greaterThan(0))\n *\n * assert.strictEqual(isNonPositive(-1), true)\n * assert.strictEqual(isNonPositive(0), true)\n * assert.strictEqual(isNonPositive(1), false)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const not = <A>(self: Predicate<A>): Predicate<A> => (a) => !self(a)\n\n/**\n * Combines two predicates with a logical \"OR\". The resulting predicate returns `true`\n * if at least one of the predicates returns `true`.\n *\n * If both predicates are `Refinement`s, the resulting predicate is a `Refinement` to the\n * union of their target types (`B | C`).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * const isString = (u: unknown): u is string => typeof u === \"string\"\n * const isNumber = (u: unknown): u is number => typeof u === \"number\"\n *\n * const isStringOrNumber = Predicate.or(isString, isNumber)\n *\n * assert.strictEqual(isStringOrNumber(\"hello\"), true)\n * assert.strictEqual(isStringOrNumber(123), true)\n * assert.strictEqual(isStringOrNumber(null), false)\n *\n * const value: unknown = \"world\"\n * if (isStringOrNumber(value)) {\n *   // value is narrowed to string | number\n *   console.log(value)\n * }\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const or: {\n  <A, C extends A>(that: Refinement<A, C>): <B extends A>(self: Refinement<A, B>) => Refinement<A, B | C>\n  <A, B extends A, C extends A>(self: Refinement<A, B>, that: Refinement<A, C>): Refinement<A, B | C>\n  <A>(that: Predicate<A>): (self: Predicate<A>) => Predicate<A>\n  <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A>\n} = dual(2, <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A> => (a) => self(a) || that(a))\n\n/**\n * Combines two predicates with a logical \"AND\". The resulting predicate returns `true`\n * only if both of the predicates return `true`.\n *\n * If both predicates are `Refinement`s, the resulting predicate is a `Refinement` to the\n * intersection of their target types (`B & C`).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * type Person = { name: string }\n * type Employee = { id: number }\n *\n * const hasName = (u: unknown): u is Person => Predicate.hasProperty(u, \"name\") && typeof (u as any).name === \"string\"\n * const hasId = (u: unknown): u is Employee => Predicate.hasProperty(u, \"id\") && typeof (u as any).id === \"number\"\n *\n * const isPersonAndEmployee = Predicate.and(hasName, hasId)\n *\n * const val: unknown = { name: \"Alice\", id: 123 }\n * if (isPersonAndEmployee(val)) {\n *   // val is narrowed to Person & Employee\n *   assert.strictEqual(val.name, \"Alice\")\n *   assert.strictEqual(val.id, 123)\n * }\n *\n * assert.strictEqual(isPersonAndEmployee({ name: \"Bob\" }), false) // Missing id\n * assert.strictEqual(isPersonAndEmployee({ id: 456 }), false) // Missing name\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const and: {\n  <A, C extends A>(that: Refinement<A, C>): <B extends A>(self: Refinement<A, B>) => Refinement<A, B & C>\n  <A, B extends A, C extends A>(self: Refinement<A, B>, that: Refinement<A, C>): Refinement<A, B & C>\n  <A>(that: Predicate<A>): (self: Predicate<A>) => Predicate<A>\n  <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A>\n} = dual(2, <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A> => (a) => self(a) && that(a))\n\n/**\n * Combines two predicates with a logical \"XOR\" (exclusive OR). The resulting predicate\n * returns `true` if one of the predicates returns `true`, but not both.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * const isPositive = (n: number) => n > 0\n * const isEven = (n: number) => n % 2 === 0\n *\n * const isPositiveXorEven = Predicate.xor(isPositive, isEven)\n *\n * assert.strictEqual(isPositiveXorEven(4), false)  // both true -> false\n * assert.strictEqual(isPositiveXorEven(3), true)   // one true -> true\n * assert.strictEqual(isPositiveXorEven(-2), true)  // one true -> true\n * assert.strictEqual(isPositiveXorEven(-1), false) // both false -> false\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const xor: {\n  <A>(that: Predicate<A>): (self: Predicate<A>) => Predicate<A>\n  <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A>\n} = dual(2, <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A> => (a) => self(a) !== that(a))\n\n/**\n * Combines two predicates with a logical \"EQV\" (equivalence). The resulting predicate\n * returns `true` if both predicates return the same boolean value (both `true` or both `false`).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * const isPositive = (n: number) => n > 0\n * const isEven = (n: number) => n % 2 === 0\n *\n * const isPositiveEqvEven = Predicate.eqv(isPositive, isEven)\n *\n * assert.strictEqual(isPositiveEqvEven(4), true)   // both true -> true\n * assert.strictEqual(isPositiveEqvEven(3), false)  // different -> false\n * assert.strictEqual(isPositiveEqvEven(-2), false) // different -> false\n * assert.strictEqual(isPositiveEqvEven(-1), true)  // both false -> true\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const eqv: {\n  <A>(that: Predicate<A>): (self: Predicate<A>) => Predicate<A>\n  <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A>\n} = dual(2, <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A> => (a) => self(a) === that(a))\n\n/**\n * Creates a predicate that represents a logical \"if-then\" rule.\n *\n * Think of it as a conditional promise: **\"If `antecedent` holds true, then I promise `consequent` will also be true.\"**\n *\n * This function is invaluable for defining complex validation logic where one condition dictates another.\n *\n * ### How It Works\n *\n * The rule only fails (returns `false`) when the \"if\" part is `true`, but the \"then\" part is `false`.\n * In all other cases, the promise is considered kept, and the result is `true`.\n *\n * This includes the concept of **\"vacuous truth\"**: if the \"if\" part is `false`, the rule doesn't apply,\n * so the promise isn't broken, and the result is `true`. (e.g., \"If it rains, I'll bring an umbrella.\"\n * If it doesn't rain, you haven't broken your promise, no matter what).\n *\n * ### Key Details\n *\n * - **Logical Equivalence**: `implies(p, q)` is the same as `not(p).or(q)`, or simply `!p || q`\n *   in plain JavaScript. This can be a helpful way to reason about its behavior.\n *\n * - **Type-Safety Warning**: This function always returns a `Predicate`, never a type-narrowing\n *   `Refinement`. A `true` result doesn't guarantee the `consequent` passed (it could be `true`\n *   simply because the `antecedent` was `false`), so it cannot be used to safely narrow a type.\n *\n * @example\n * ```ts\n * // Rule: A user can only be an admin if they also belong to the \"staff\" group.\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * type User = {\n *   isStaff: boolean\n *   isAdmin: boolean\n * }\n *\n * const isValidUserPermission = Predicate.implies(\n *   // antecedent: \"if\" the user is an admin...\n *   (user: User) => user.isAdmin,\n *   // consequent: \"then\" they must be staff.\n *   (user: User) => user.isStaff\n * )\n *\n * // A non-admin who is not staff. Rule doesn't apply (antecedent is false).\n * assert.strictEqual(isValidUserPermission({ isStaff: false, isAdmin: false }), true)\n *\n * // A staff member who is not an admin. Rule doesn't apply (antecedent is false).\n * assert.strictEqual(isValidUserPermission({ isStaff: true, isAdmin: false }), true)\n *\n * // An admin who is also staff. The rule was followed.\n * assert.strictEqual(isValidUserPermission({ isStaff: true, isAdmin: true }), true)\n *\n * // An admin who is NOT staff. The rule was broken!\n * assert.strictEqual(isValidUserPermission({ isStaff: false, isAdmin: true }), false)\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const implies: {\n  <A>(consequent: Predicate<A>): (antecedent: Predicate<A>) => Predicate<A>\n  <A>(antecedent: Predicate<A>, consequent: Predicate<A>): Predicate<A>\n} = dual(\n  2,\n  <A>(antecedent: Predicate<A>, consequent: Predicate<A>): Predicate<A> => (a) => antecedent(a) ? consequent(a) : true\n)\n\n/**\n * Combines two predicates with a logical \"NOR\" (negated OR). The resulting predicate\n * returns `true` only if both predicates return `false`.\n * This is equivalent to `not(or(p, q))`.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const nor: {\n  <A>(that: Predicate<A>): (self: Predicate<A>) => Predicate<A>\n  <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A>\n} = dual(\n  2,\n  <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A> => (a) => !(self(a) || that(a))\n)\n\n/**\n * Combines two predicates with a logical \"NAND\" (negated AND). The resulting predicate\n * returns `true` if at least one of the predicates returns `false`.\n * This is equivalent to `not(and(p, q))`.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const nand: {\n  <A>(that: Predicate<A>): (self: Predicate<A>) => Predicate<A>\n  <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A>\n} = dual(\n  2,\n  <A>(self: Predicate<A>, that: Predicate<A>): Predicate<A> => (a) => !(self(a) && that(a))\n)\n\n/**\n * Takes an iterable of predicates and returns a new predicate. The new predicate\n * returns `true` if all predicates in the collection return `true` for a given value.\n *\n * This is like `Array.prototype.every` but for a collection of predicates.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * const isPositive = (n: number) => n > 0\n * const isEven = (n: number) => n % 2 === 0\n *\n * const isPositiveAndEven = Predicate.every([isPositive, isEven])\n *\n * assert.strictEqual(isPositiveAndEven(4), true)\n * assert.strictEqual(isPositiveAndEven(3), false)\n * assert.strictEqual(isPositiveAndEven(-2), false)\n * ```\n *\n * @category elements\n * @since 2.0.0\n * @see some\n */\nexport const every = <A>(collection: Iterable<Predicate<A>>): Predicate<A> => (a: A) => {\n  for (const p of collection) {\n    if (!p(a)) {\n      return false\n    }\n  }\n  return true\n}\n\n/**\n * Takes an iterable of predicates and returns a new predicate. The new predicate\n * returns `true` if at least one predicate in the collection returns `true` for a given value.\n *\n * This is like `Array.prototype.some` but for a collection of predicates.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * const isNegative = (n: number) => n < 0\n * const isOdd = (n: number) => n % 2 !== 0\n *\n * const isNegativeOrOdd = Predicate.some([isNegative, isOdd])\n *\n * assert.strictEqual(isNegativeOrOdd(-2), true) // isNegative is true\n * assert.strictEqual(isNegativeOrOdd(3), true)  // isOdd is true\n * assert.strictEqual(isNegativeOrOdd(4), false) // both are false\n * ```\n *\n * @category elements\n * @since 2.0.0\n * @see every\n */\nexport const some = <A>(collection: Iterable<Predicate<A>>): Predicate<A> => (a) => {\n  for (const p of collection) {\n    if (p(a)) {\n      return true\n    }\n  }\n  return false\n}\n"
  },
  {
    "path": "packages/effect/src/Pretty.ts",
    "content": "/**\n * @since 3.10.0\n */\nimport * as Arr from \"./Array.js\"\nimport * as Inspectable from \"./Inspectable.js\"\nimport * as errors_ from \"./internal/schema/errors.js\"\nimport * as util_ from \"./internal/schema/util.js\"\nimport * as Option from \"./Option.js\"\nimport * as ParseResult from \"./ParseResult.js\"\nimport type * as Schema from \"./Schema.js\"\nimport * as AST from \"./SchemaAST.js\"\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface Pretty<To> {\n  (a: To): string\n}\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type PrettyAnnotation<A, TypeParameters extends ReadonlyArray<any> = readonly []> = (\n  ...pretties: { readonly [K in keyof TypeParameters]: Pretty<TypeParameters[K]> }\n) => Pretty<A>\n\n/**\n * @category prettify\n * @since 3.10.0\n */\nexport const make = <A, I, R>(schema: Schema.Schema<A, I, R>): (a: A) => string => compile(schema.ast, [])\n\nconst getPrettyAnnotation = AST.getAnnotation<PrettyAnnotation<any, any>>(AST.PrettyAnnotationId)\n\nconst getMatcher = (defaultPretty: Pretty<any>) => (ast: AST.AST): Pretty<any> =>\n  Option.match(getPrettyAnnotation(ast), {\n    onNone: () => defaultPretty,\n    onSome: (handler) => handler()\n  })\n\nconst toString = getMatcher((a) => String(a))\n\nconst stringify = getMatcher((a) => JSON.stringify(a))\n\nconst formatUnknown = getMatcher(Inspectable.formatUnknown)\n\n/**\n * @since 3.10.0\n */\nexport const match: AST.Match<Pretty<any>> = {\n  \"Declaration\": (ast, go, path) => {\n    const annotation = getPrettyAnnotation(ast)\n    if (Option.isSome(annotation)) {\n      return annotation.value(...ast.typeParameters.map((tp) => go(tp, path)))\n    }\n    throw new Error(errors_.getPrettyMissingAnnotationErrorMessage(path, ast))\n  },\n  \"VoidKeyword\": getMatcher(() => \"void(0)\"),\n  \"NeverKeyword\": getMatcher(() => {\n    throw new Error(errors_.getPrettyNeverErrorMessage)\n  }),\n  \"Literal\": getMatcher((literal: AST.LiteralValue): string =>\n    typeof literal === \"bigint\" ?\n      `${String(literal)}n` :\n      JSON.stringify(literal)\n  ),\n  \"SymbolKeyword\": toString,\n  \"UniqueSymbol\": toString,\n  \"TemplateLiteral\": stringify,\n  \"UndefinedKeyword\": toString,\n  \"UnknownKeyword\": formatUnknown,\n  \"AnyKeyword\": formatUnknown,\n  \"ObjectKeyword\": formatUnknown,\n  \"StringKeyword\": stringify,\n  \"NumberKeyword\": toString,\n  \"BooleanKeyword\": toString,\n  \"BigIntKeyword\": getMatcher((a) => `${String(a)}n`),\n  \"Enums\": stringify,\n  \"TupleType\": (ast, go, path) => {\n    const hook = getPrettyAnnotation(ast)\n    if (Option.isSome(hook)) {\n      return hook.value()\n    }\n    const elements = ast.elements.map((e, i) => go(e.type, path.concat(i)))\n    const rest = ast.rest.map((annotatedAST) => go(annotatedAST.type, path))\n    return (input: ReadonlyArray<unknown>) => {\n      const output: Array<string> = []\n      let i = 0\n      // ---------------------------------------------\n      // handle elements\n      // ---------------------------------------------\n      for (; i < elements.length; i++) {\n        if (input.length < i + 1) {\n          if (ast.elements[i].isOptional) {\n            continue\n          }\n        } else {\n          output.push(elements[i](input[i]))\n        }\n      }\n      // ---------------------------------------------\n      // handle rest element\n      // ---------------------------------------------\n      if (Arr.isNonEmptyReadonlyArray(rest)) {\n        const [head, ...tail] = rest\n        for (; i < input.length - tail.length; i++) {\n          output.push(head(input[i]))\n        }\n        // ---------------------------------------------\n        // handle post rest elements\n        // ---------------------------------------------\n        for (let j = 0; j < tail.length; j++) {\n          i += j\n          output.push(tail[j](input[i]))\n        }\n      }\n\n      return \"[\" + output.join(\", \") + \"]\"\n    }\n  },\n  \"TypeLiteral\": (ast, go, path) => {\n    const hook = getPrettyAnnotation(ast)\n    if (Option.isSome(hook)) {\n      return hook.value()\n    }\n    const propertySignaturesTypes = ast.propertySignatures.map((ps) => go(ps.type, path.concat(ps.name)))\n    const indexSignatureTypes = ast.indexSignatures.map((is) => go(is.type, path))\n    const expectedKeys: any = {}\n    for (let i = 0; i < propertySignaturesTypes.length; i++) {\n      expectedKeys[ast.propertySignatures[i].name] = null\n    }\n    return (input: { readonly [x: PropertyKey]: unknown }) => {\n      const output: Array<string> = []\n      // ---------------------------------------------\n      // handle property signatures\n      // ---------------------------------------------\n      for (let i = 0; i < propertySignaturesTypes.length; i++) {\n        const ps = ast.propertySignatures[i]\n        const name = ps.name\n        if (ps.isOptional && !Object.prototype.hasOwnProperty.call(input, name)) {\n          continue\n        }\n        output.push(\n          `${Inspectable.formatPropertyKey(name)}: ${propertySignaturesTypes[i](input[name])}`\n        )\n      }\n      // ---------------------------------------------\n      // handle index signatures\n      // ---------------------------------------------\n      if (indexSignatureTypes.length > 0) {\n        for (let i = 0; i < indexSignatureTypes.length; i++) {\n          const type = indexSignatureTypes[i]\n          const keys = util_.getKeysForIndexSignature(input, ast.indexSignatures[i].parameter)\n          for (const key of keys) {\n            if (Object.prototype.hasOwnProperty.call(expectedKeys, key)) {\n              continue\n            }\n            output.push(`${Inspectable.formatPropertyKey(key)}: ${type(input[key])}`)\n          }\n        }\n      }\n\n      return Arr.isNonEmptyReadonlyArray(output) ? \"{ \" + output.join(\", \") + \" }\" : \"{}\"\n    }\n  },\n  \"Union\": (ast, go, path) => {\n    const hook = getPrettyAnnotation(ast)\n    if (Option.isSome(hook)) {\n      return hook.value()\n    }\n    const types = ast.types.map((ast) => [ParseResult.is({ ast } as any), go(ast, path)] as const)\n    return (a) => {\n      const index = types.findIndex(([is]) => is(a))\n      if (index === -1) {\n        throw new Error(errors_.getPrettyNoMatchingSchemaErrorMessage(a, path, ast))\n      }\n      return types[index][1](a)\n    }\n  },\n  \"Suspend\": (ast, go, path) => {\n    return Option.match(getPrettyAnnotation(ast), {\n      onNone: () => {\n        const get = util_.memoizeThunk(() => go(ast.f(), path))\n        return (a) => get()(a)\n      },\n      onSome: (handler) => handler()\n    })\n  },\n  \"Refinement\": (ast, go, path) => {\n    return Option.match(getPrettyAnnotation(ast), {\n      onNone: () => go(ast.from, path),\n      onSome: (handler) => handler()\n    })\n  },\n  \"Transformation\": (ast, go, path) => {\n    return Option.match(getPrettyAnnotation(ast), {\n      onNone: () => go(ast.to, path),\n      onSome: (handler) => handler()\n    })\n  }\n}\n\nconst compile = AST.getCompiler(match)\n"
  },
  {
    "path": "packages/effect/src/PrimaryKey.ts",
    "content": "/**\n * @since 2.0.0\n */\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const symbol: unique symbol = Symbol.for(\"effect/PrimaryKey\")\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface PrimaryKey {\n  [symbol](): string\n}\n\n/**\n * @since 2.0.0\n * @category accessors\n */\nexport const value = (self: PrimaryKey): string => self[symbol]()\n"
  },
  {
    "path": "packages/effect/src/PubSub.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/pubsub.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Queue from \"./Queue.js\"\nimport type * as Scope from \"./Scope.js\"\n\n/**\n * A `PubSub<A>` is an asynchronous message hub into which publishers can publish\n * messages of type `A` and subscribers can subscribe to take messages of type\n * `A`.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface PubSub<in out A> extends Queue.Enqueue<A>, Pipeable {\n  /**\n   * Publishes a message to the `PubSub`, returning whether the message was published\n   * to the `PubSub`.\n   */\n  publish(value: A): Effect.Effect<boolean>\n\n  /**\n   * Publishes all of the specified messages to the `PubSub`, returning whether they\n   * were published to the `PubSub`.\n   */\n  publishAll(elements: Iterable<A>): Effect.Effect<boolean>\n\n  /**\n   * Subscribes to receive messages from the `PubSub`. The resulting subscription can\n   * be evaluated multiple times within the scope to take a message from the `PubSub`\n   * each time.\n   */\n  readonly subscribe: Effect.Effect<Queue.Dequeue<A>, never, Scope.Scope>\n}\n\n/**\n * Creates a bounded `PubSub` with the back pressure strategy. The `PubSub` will retain\n * messages until they have been taken by all subscribers, applying back\n * pressure to publishers if the `PubSub` is at capacity.\n *\n * For best performance use capacities that are powers of two.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const bounded: <A>(\n  capacity: number | { readonly capacity: number; readonly replay?: number | undefined }\n) => Effect.Effect<PubSub<A>> = internal.bounded\n\n/**\n * Creates a bounded `PubSub` with the dropping strategy. The `PubSub` will drop new\n * messages if the `PubSub` is at capacity.\n *\n * For best performance use capacities that are powers of two.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dropping: <A>(\n  capacity: number | { readonly capacity: number; readonly replay?: number | undefined }\n) => Effect.Effect<PubSub<A>> = internal.dropping\n\n/**\n * Creates a bounded `PubSub` with the sliding strategy. The `PubSub` will add new\n * messages and drop old messages if the `PubSub` is at capacity.\n *\n * For best performance use capacities that are powers of two.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sliding: <A>(\n  capacity: number | { readonly capacity: number; readonly replay?: number | undefined }\n) => Effect.Effect<PubSub<A>> = internal.sliding\n\n/**\n * Creates an unbounded `PubSub`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unbounded: <A>(options?: { readonly replay?: number | undefined }) => Effect.Effect<PubSub<A>> =\n  internal.unbounded\n\n/**\n *  Returns the number of elements the queue can hold.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const capacity: <A>(self: PubSub<A>) => number = internal.capacity\n\n/**\n * Retrieves the size of the queue, which is equal to the number of elements\n * in the queue. This may be negative if fibers are suspended waiting for\n * elements to be added to the queue.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <A>(self: PubSub<A>) => Effect.Effect<number> = internal.size\n\n/**\n * Returns `true` if the `Queue` contains at least one element, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isFull: <A>(self: PubSub<A>) => Effect.Effect<boolean> = internal.isFull\n\n/**\n * Returns `true` if the `Queue` contains zero elements, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isEmpty: <A>(self: PubSub<A>) => Effect.Effect<boolean> = internal.isEmpty\n\n/**\n * Interrupts any fibers that are suspended on `offer` or `take`. Future calls\n * to `offer*` and `take*` will be interrupted immediately.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const shutdown: <A>(self: PubSub<A>) => Effect.Effect<void> = internal.shutdown\n\n/**\n * Returns `true` if `shutdown` has been called, otherwise returns `false`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isShutdown: <A>(self: PubSub<A>) => Effect.Effect<boolean> = internal.isShutdown\n\n/**\n * Waits until the queue is shutdown. The `Effect` returned by this method will\n * not resume until the queue has been shutdown. If the queue is already\n * shutdown, the `Effect` will resume right away.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const awaitShutdown: <A>(self: PubSub<A>) => Effect.Effect<void> = internal.awaitShutdown\n\n/**\n * Publishes a message to the `PubSub`, returning whether the message was published\n * to the `PubSub`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const publish: {\n  <A>(value: A): (self: PubSub<A>) => Effect.Effect<boolean>\n  <A>(self: PubSub<A>, value: A): Effect.Effect<boolean>\n} = internal.publish\n\n/**\n * Publishes all of the specified messages to the `PubSub`, returning whether they\n * were published to the `PubSub`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const publishAll: {\n  <A>(elements: Iterable<A>): (self: PubSub<A>) => Effect.Effect<boolean>\n  <A>(self: PubSub<A>, elements: Iterable<A>): Effect.Effect<boolean>\n} = internal.publishAll\n\n/**\n * Subscribes to receive messages from the `PubSub`. The resulting subscription can\n * be evaluated multiple times within the scope to take a message from the `PubSub`\n * each time.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const subscribe: <A>(self: PubSub<A>) => Effect.Effect<Queue.Dequeue<A>, never, Scope.Scope> = internal.subscribe\n"
  },
  {
    "path": "packages/effect/src/Queue.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Deferred from \"./Deferred.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/queue.js\"\nimport type * as MutableQueue from \"./MutableQueue.js\"\nimport type * as MutableRef from \"./MutableRef.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const EnqueueTypeId: unique symbol = internal.EnqueueTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type EnqueueTypeId = typeof EnqueueTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const DequeueTypeId: unique symbol = internal.DequeueTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type DequeueTypeId = typeof DequeueTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const QueueStrategyTypeId: unique symbol = internal.QueueStrategyTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type QueueStrategyTypeId = typeof QueueStrategyTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const BackingQueueTypeId: unique symbol = internal.BackingQueueTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type BackingQueueTypeId = typeof BackingQueueTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Queue<in out A> extends Enqueue<A>, Dequeue<A> {\n  /** @internal */\n  readonly queue: BackingQueue<A>\n  /** @internal */\n  readonly takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n  /** @internal */\n  readonly shutdownHook: Deferred.Deferred<void>\n  /** @internal */\n  readonly shutdownFlag: MutableRef.MutableRef<boolean>\n  /** @internal */\n  readonly strategy: Strategy<A>\n\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: QueueUnify<this>\n  readonly [Unify.ignoreSymbol]?: QueueUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface QueueUnify<A extends { [Unify.typeSymbol]?: any }> extends DequeueUnify<A> {\n  Queue?: () => Extract<A[Unify.typeSymbol], Queue<any>>\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface QueueUnifyIgnore extends DequeueUnifyIgnore {\n  Dequeue?: true\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Enqueue<in A> extends Queue.EnqueueVariance<A>, BaseQueue, Pipeable {\n  /**\n   * Places one value in the queue.\n   */\n  offer(value: A): Effect.Effect<boolean>\n\n  /**\n   * Places one value in the queue when possible without needing the fiber runtime.\n   */\n  unsafeOffer(value: A): boolean\n\n  /**\n   * For Bounded Queue: uses the `BackPressure` Strategy, places the values in\n   * the queue and always returns true. If the queue has reached capacity, then\n   * the fiber performing the `offerAll` will be suspended until there is room\n   * in the queue.\n   *\n   * For Unbounded Queue: Places all values in the queue and returns true.\n   *\n   * For Sliding Queue: uses `Sliding` Strategy If there is room in the queue,\n   * it places the values otherwise it removes the old elements and enqueues the\n   * new ones. Always returns true.\n   *\n   * For Dropping Queue: uses `Dropping` Strategy, It places the values in the\n   * queue but if there is no room it will not enqueue them and return false.\n   */\n  offerAll(iterable: Iterable<A>): Effect.Effect<boolean>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Dequeue<out A> extends Effect.Effect<A>, Queue.DequeueVariance<A>, BaseQueue {\n  /**\n   * Takes the oldest value in the queue. If the queue is empty, this will return\n   * a computation that resumes when an item has been added to the queue.\n   */\n  readonly take: Effect.Effect<A>\n\n  /**\n   * Takes all the values in the queue and returns the values. If the queue is\n   * empty returns an empty collection.\n   */\n  readonly takeAll: Effect.Effect<Chunk.Chunk<A>>\n\n  /**\n   * Takes up to max number of values from the queue.\n   */\n  takeUpTo(max: number): Effect.Effect<Chunk.Chunk<A>>\n\n  /**\n   * Takes a number of elements from the queue between the specified minimum and\n   * maximum. If there are fewer than the minimum number of elements available,\n   * suspends until at least the minimum number of elements have been collected.\n   */\n  takeBetween(min: number, max: number): Effect.Effect<Chunk.Chunk<A>>\n\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: DequeueUnify<this>\n  readonly [Unify.ignoreSymbol]?: DequeueUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface DequeueUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  Dequeue?: () => A[Unify.typeSymbol] extends Dequeue<infer A0> | infer _ ? Dequeue<A0> : never\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface DequeueUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * The base interface that all `Queue`s must implement.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface BaseQueue {\n  /**\n   * Returns the number of elements the queue can hold.\n   */\n  capacity(): number\n\n  /**\n   * Returns false if shutdown has been called.\n   */\n  isActive(): boolean\n\n  /**\n   * Retrieves the size of the queue, which is equal to the number of elements\n   * in the queue. This may be negative if fibers are suspended waiting for\n   * elements to be added to the queue.\n   */\n  readonly size: Effect.Effect<number>\n\n  /**\n   * Retrieves the size of the queue, which is equal to the number of elements\n   * in the queue. This may be negative if fibers are suspended waiting for\n   * elements to be added to the queue. Returns None if shutdown has been called\n   */\n  unsafeSize(): Option.Option<number>\n\n  /**\n   * Returns `true` if the `Queue` contains at least one element, `false`\n   * otherwise.\n   */\n  readonly isFull: Effect.Effect<boolean>\n\n  /**\n   * Returns `true` if the `Queue` contains zero elements, `false` otherwise.\n   */\n  readonly isEmpty: Effect.Effect<boolean>\n\n  /**\n   * Interrupts any fibers that are suspended on `offer` or `take`. Future calls\n   * to `offer*` and `take*` will be interrupted immediately.\n   */\n  readonly shutdown: Effect.Effect<void>\n\n  /**\n   * Returns `true` if `shutdown` has been called, otherwise returns `false`.\n   */\n  readonly isShutdown: Effect.Effect<boolean>\n\n  /**\n   * Waits until the queue is shutdown. The `Effect` returned by this method will\n   * not resume until the queue has been shutdown. If the queue is already\n   * shutdown, the `Effect` will resume right away.\n   */\n  readonly awaitShutdown: Effect.Effect<void>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Strategy<in out A> extends Queue.StrategyVariance<A> {\n  /**\n   * Returns the number of surplus values that were unable to be added to the\n   * `Queue`\n   */\n  surplusSize(): number\n\n  /**\n   * Determines how the `Queue.Strategy` should shut down when the `Queue` is\n   * shut down.\n   */\n  readonly shutdown: Effect.Effect<void>\n\n  /**\n   * Determines the behavior of the `Queue.Strategy` when there are surplus\n   * values that could not be added to the `Queue` following an `offer`\n   * operation.\n   */\n  handleSurplus(\n    iterable: Iterable<A>,\n    queue: BackingQueue<A>,\n    takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>,\n    isShutdown: MutableRef.MutableRef<boolean>\n  ): Effect.Effect<boolean>\n\n  /**\n   * It is called when the backing queue is empty but there are some\n   * takers that can be completed\n   */\n  onCompleteTakersWithEmptyQueue(\n    takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n  ): void\n\n  /**\n   * Determines the behavior of the `Queue.Strategy` when the `Queue` has empty\n   * slots following a `take` operation.\n   */\n  unsafeOnQueueEmptySpace(\n    queue: BackingQueue<A>,\n    takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n  ): void\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface BackingQueue<in out A> extends Queue.BackingQueueVariance<A> {\n  /**\n   * Dequeues an element from the queue.\n   * Returns either an element from the queue, or the `def` param.\n   */\n  poll<Def>(def: Def): A | Def\n  /**\n   * Dequeues up to `limit` elements from the queue.\n   */\n  pollUpTo(limit: number): Chunk.Chunk<A>\n  /**\n   * Enqueues a collection of values into the queue.\n   *\n   * Returns a `Chunk` of the values that were **not** able to be enqueued.\n   */\n  offerAll(elements: Iterable<A>): Chunk.Chunk<A>\n  /**\n   * Offers an element to the queue.\n   *\n   * Returns whether the enqueue was successful or not.\n   */\n  offer(element: A): boolean\n  /**\n   * The **maximum** number of elements that a queue can hold.\n   *\n   * **Note**: unbounded queues can still implement this interface with\n   * `capacity = Infinity`.\n   */\n  capacity(): number\n  /**\n   * Returns the number of elements currently in the queue\n   */\n  length(): number\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Queue {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface EnqueueVariance<in A> {\n    readonly [EnqueueTypeId]: {\n      readonly _In: Types.Contravariant<A>\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface DequeueVariance<out A> {\n    readonly [DequeueTypeId]: {\n      readonly _Out: Types.Covariant<A>\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface StrategyVariance<in out A> {\n    readonly [QueueStrategyTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface BackingQueueVariance<in out A> {\n    readonly [BackingQueueTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * Returns `true` if the specified value is a `Queue`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isQueue: (u: unknown) => u is Queue<unknown> = internal.isQueue\n\n/**\n * Returns `true` if the specified value is a `Dequeue`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isDequeue: (u: unknown) => u is Dequeue<unknown> = internal.isDequeue\n\n/**\n * Returns `true` if the specified value is a `Enqueue`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isEnqueue: (u: unknown) => u is Enqueue<unknown> = internal.isEnqueue\n\n/**\n * @since 2.0.0\n * @category strategies\n */\nexport const backPressureStrategy: <A>() => Strategy<A> = internal.backPressureStrategy\n\n/**\n * @since 2.0.0\n * @category strategies\n */\nexport const droppingStrategy: <A>() => Strategy<A> = internal.droppingStrategy\n\n/**\n * @since 2.0.0\n * @category strategies\n */\nexport const slidingStrategy: <A>() => Strategy<A> = internal.slidingStrategy\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A>(queue: BackingQueue<A>, strategy: Strategy<A>) => Effect.Effect<Queue<A>> = internal.make\n\n/**\n * Makes a new bounded `Queue`. When the capacity of the queue is reached, any\n * additional calls to `offer` will be suspended until there is more room in\n * the queue.\n *\n * **Note**: When possible use only power of 2 capacities; this will provide\n * better performance by utilising an optimised version of the underlying\n * `RingBuffer`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const bounded: <A>(requestedCapacity: number) => Effect.Effect<Queue<A>> = internal.bounded\n\n/**\n * Makes a new bounded `Queue` with the dropping strategy.\n *\n * When the capacity of the queue is reached, new elements will be dropped and the\n * old elements will remain.\n *\n * **Note**: When possible use only power of 2 capacities; this will provide\n * better performance by utilising an optimised version of the underlying\n * `RingBuffer`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dropping: <A>(requestedCapacity: number) => Effect.Effect<Queue<A>> = internal.dropping\n\n/**\n * Makes a new bounded `Queue` with the sliding strategy.\n *\n * When the capacity of the queue is reached, new elements will be added and the\n * old elements will be dropped.\n *\n * **Note**: When possible use only power of 2 capacities; this will provide\n * better performance by utilising an optimised version of the underlying\n * `RingBuffer`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sliding: <A>(requestedCapacity: number) => Effect.Effect<Queue<A>> = internal.sliding\n\n/**\n * Creates a new unbounded `Queue`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unbounded: <A>() => Effect.Effect<Queue<A>> = internal.unbounded\n\n/**\n * Returns the number of elements the queue can hold.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const capacity: <A>(self: Dequeue<A> | Enqueue<A>) => number = internal.capacity\n\n/**\n * Retrieves the size of the queue, which is equal to the number of elements\n * in the queue. This may be negative if fibers are suspended waiting for\n * elements to be added to the queue.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <A>(self: Dequeue<A> | Enqueue<A>) => Effect.Effect<number> = internal.size\n\n/**\n * Returns `true` if the `Queue` contains zero elements, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isEmpty: <A>(self: Dequeue<A> | Enqueue<A>) => Effect.Effect<boolean> = internal.isEmpty\n\n/**\n * Returns `true` if the `Queue` contains at least one element, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isFull: <A>(self: Dequeue<A> | Enqueue<A>) => Effect.Effect<boolean> = internal.isFull\n\n/**\n * Returns `true` if `shutdown` has been called, otherwise returns `false`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isShutdown: <A>(self: Dequeue<A> | Enqueue<A>) => Effect.Effect<boolean> = internal.isShutdown\n\n/**\n * Waits until the queue is shutdown. The `Effect` returned by this method will\n * not resume until the queue has been shutdown. If the queue is already\n * shutdown, the `Effect` will resume right away.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const awaitShutdown: <A>(self: Dequeue<A> | Enqueue<A>) => Effect.Effect<void> = internal.awaitShutdown\n\n/**\n * Interrupts any fibers that are suspended on `offer` or `take`. Future calls\n * to `offer*` and `take*` will be interrupted immediately.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const shutdown: <A>(self: Dequeue<A> | Enqueue<A>) => Effect.Effect<void> = internal.shutdown\n\n/**\n * Places one value in the queue.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const offer: {\n  <A>(value: A): (self: Enqueue<A>) => Effect.Effect<boolean>\n  <A>(self: Enqueue<A>, value: A): Effect.Effect<boolean>\n} = internal.offer\n\n/**\n * Places one value in the queue.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const unsafeOffer: {\n  <A>(value: A): (self: Enqueue<A>) => boolean\n  <A>(self: Enqueue<A>, value: A): boolean\n} = internal.unsafeOffer\n\n/**\n * For Bounded Queue: uses the `BackPressure` Strategy, places the values in\n * the queue and always returns true. If the queue has reached capacity, then\n * the fiber performing the `offerAll` will be suspended until there is room\n * in the queue.\n *\n * For Unbounded Queue: Places all values in the queue and returns true.\n *\n * For Sliding Queue: uses `Sliding` Strategy If there is room in the queue,\n * it places the values otherwise it removes the old elements and enqueues the\n * new ones. Always returns true.\n *\n * For Dropping Queue: uses `Dropping` Strategy, It places the values in the\n * queue but if there is no room it will not enqueue them and return false.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const offerAll: {\n  <A>(iterable: Iterable<A>): (self: Enqueue<A>) => Effect.Effect<boolean>\n  <A>(self: Enqueue<A>, iterable: Iterable<A>): Effect.Effect<boolean>\n} = internal.offerAll\n\n/**\n * Returns the first value in the `Queue` as a `Some<A>`, or `None` if the queue\n * is empty.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const poll: <A>(self: Dequeue<A>) => Effect.Effect<Option.Option<A>> = internal.poll\n\n/**\n * Takes the oldest value in the queue. If the queue is empty, this will return\n * a computation that resumes when an item has been added to the queue.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const take: <A>(self: Dequeue<A>) => Effect.Effect<A> = internal.take\n\n/**\n * Takes all the values in the queue and returns the values. If the queue is\n * empty returns an empty collection.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const takeAll: <A>(self: Dequeue<A>) => Effect.Effect<Chunk.Chunk<A>> = internal.takeAll\n\n/**\n * Takes up to max number of values from the queue.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const takeUpTo: {\n  (max: number): <A>(self: Dequeue<A>) => Effect.Effect<Chunk.Chunk<A>>\n  <A>(self: Dequeue<A>, max: number): Effect.Effect<Chunk.Chunk<A>>\n} = internal.takeUpTo\n\n/**\n * Takes a number of elements from the queue between the specified minimum and\n * maximum. If there are fewer than the minimum number of elements available,\n * suspends until at least the minimum number of elements have been collected.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const takeBetween: {\n  (min: number, max: number): <A>(self: Dequeue<A>) => Effect.Effect<Chunk.Chunk<A>>\n  <A>(self: Dequeue<A>, min: number, max: number): Effect.Effect<Chunk.Chunk<A>>\n} = internal.takeBetween\n\n/**\n * Takes the specified number of elements from the queue. If there are fewer\n * than the specified number of elements available, it suspends until they\n * become available.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const takeN: {\n  (n: number): <A>(self: Dequeue<A>) => Effect.Effect<Chunk.Chunk<A>>\n  <A>(self: Dequeue<A>, n: number): Effect.Effect<Chunk.Chunk<A>>\n} = internal.takeN\n"
  },
  {
    "path": "packages/effect/src/Random.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Array from \"./Array.js\"\nimport type * as Cause from \"./Cause.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as defaultServices from \"./internal/defaultServices.js\"\nimport * as internal from \"./internal/random.js\"\nimport type * as NonEmptyIterable from \"./NonEmptyIterable.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const RandomTypeId: unique symbol = internal.RandomTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type RandomTypeId = typeof RandomTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Random {\n  readonly [RandomTypeId]: RandomTypeId\n  /**\n   * Returns the next numeric value from the pseudo-random number generator.\n   */\n  readonly next: Effect.Effect<number>\n  /**\n   * Returns the next boolean value from the pseudo-random number generator.\n   */\n  readonly nextBoolean: Effect.Effect<boolean>\n  /**\n   * Returns the next integer value from the pseudo-random number generator.\n   */\n  readonly nextInt: Effect.Effect<number>\n  /**\n   * Returns the next numeric value in the specified range from the\n   * pseudo-random number generator.\n   */\n  nextRange(min: number, max: number): Effect.Effect<number>\n  /**\n   * Returns the next integer value in the specified range from the\n   * pseudo-random number generator.\n   */\n  nextIntBetween(min: number, max: number): Effect.Effect<number>\n  /**\n   * Uses the pseudo-random number generator to shuffle the specified iterable.\n   */\n  shuffle<A>(elements: Iterable<A>): Effect.Effect<Chunk.Chunk<A>>\n}\n\n/**\n * Returns the next numeric value from the pseudo-random number generator.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const next: Effect.Effect<number> = defaultServices.next\n\n/**\n * Returns the next integer value from the pseudo-random number generator.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const nextInt: Effect.Effect<number> = defaultServices.nextInt\n\n/**\n * Returns the next boolean value from the pseudo-random number generator.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const nextBoolean: Effect.Effect<boolean> = defaultServices.nextBoolean\n\n/**\n * Returns the next numeric value in the specified range from the\n * pseudo-random number generator.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const nextRange: (min: number, max: number) => Effect.Effect<number> = defaultServices.nextRange\n\n/**\n * Returns the next integer value in the specified range from the\n * pseudo-random number generator.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const nextIntBetween: (min: number, max: number) => Effect.Effect<number> = defaultServices.nextIntBetween\n\n/**\n * Uses the pseudo-random number generator to shuffle the specified iterable.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const shuffle: <A>(elements: Iterable<A>) => Effect.Effect<Chunk.Chunk<A>> = defaultServices.shuffle\n\n/**\n * Get a random element from an iterable.\n *\n * @example\n * ```ts\n * import { Effect, Random } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const randomItem = yield* Random.choice([1, 2, 3])\n *   console.log(randomItem)\n * })\n * ```\n *\n * @since 3.6.0\n * @category constructors\n */\nexport const choice: <Self extends Iterable<unknown>>(\n  elements: Self\n) => Self extends NonEmptyIterable.NonEmptyIterable<infer A> ? Effect.Effect<A>\n  : Self extends Array.NonEmptyReadonlyArray<infer A> ? Effect.Effect<A>\n  : Self extends Iterable<infer A> ? Effect.Effect<A, Cause.NoSuchElementException>\n  : never = defaultServices.choice\n\n/**\n * Retreives the `Random` service from the context and uses it to run the\n * specified workflow.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const randomWith: <A, E, R>(f: (random: Random) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> =\n  defaultServices.randomWith\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const Random: Context.Tag<Random, Random> = internal.randomTag\n\n/**\n * Constructs the `Random` service, seeding the pseudo-random number generator\n * with an hash of the specified seed.\n * This constructor is useful for generating predictable sequences of random values for specific use cases.\n *\n * Example uses:\n * - Generating random UI data for visual tests.\n * - Creating data that needs to change daily but remain the same throughout a single day, such as using a date as the seed.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Effect, Random } from \"effect\"\n *\n * const random1 = Random.make(\"myseed\")\n * const random2 = Random.make(\"myseed\")\n *\n * assert.equal(Effect.runSync(random1.next), Effect.runSync(random2.next))\n * ```\n *\n * @since 3.5.0\n * @category constructors\n */\nexport const make: <A>(seed: A) => Random = internal.make\n\n/**\n * Constructs the `Random` service from an array of literal values.\n * The service will cycle through the provided values in order when generating random values.\n * This constructor is useful for creating deterministic sequences for testing or when specific values need to be returned.\n *\n * @example\n * ```ts\n * import { Effect, Random } from \"effect\"\n *\n * Effect.gen(function* () {\n *   console.log(yield* Random.next) // 0.2\n *   console.log(yield* Random.next) // 0.5\n *   console.log(yield* Random.next) // 0.8\n *   console.log(yield* Random.next) // 0.2 (cycles back)\n * }).pipe(Effect.withRandom(Random.fixed([0.2, 0.5, 0.8])))\n * ```\n *\n * @example\n * ```ts\n * import { Effect, Random } from \"effect\"\n *\n * Effect.gen(function* () {\n *   console.log(yield* Random.nextBoolean) // true\n *   console.log(yield* Random.nextBoolean) // false\n *   console.log(yield* Random.nextBoolean) // true\n * }).pipe(Effect.withRandom(Random.fixed([true, false, true])))\n * ```\n *\n * @since 3.11.0\n * @category constructors\n */\nexport const fixed: <const T extends Array.NonEmptyArray<any>>(values: T) => Random = internal.fixed\n"
  },
  {
    "path": "packages/effect/src/RateLimiter.ts",
    "content": "/**\n * Limits the number of calls to a resource to a maximum amount in some interval.\n *\n * @since 2.0.0\n */\nimport type { DurationInput } from \"./Duration.js\"\nimport type { Effect } from \"./Effect.js\"\nimport * as internal from \"./internal/rateLimiter.js\"\nimport type { Scope } from \"./Scope.js\"\n\n/**\n * Limits the number of calls to a resource to a maximum amount in some interval.\n *\n * Note that only the moment of starting the effect is rate limited: the number\n * of concurrent executions is not bounded.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface RateLimiter {\n  <A, E, R>(task: Effect<A, E, R>): Effect<A, E, R>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace RateLimiter {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Options {\n    /**\n     * The maximum number of requests that should be allowed.\n     */\n    readonly limit: number\n    /**\n     * The interval to utilize for rate-limiting requests. The semantics of the\n     * specified `interval` vary depending on the chosen `algorithm`:\n     *\n     * `token-bucket`: The maximum number of requests will be spread out over\n     * the provided interval if no tokens are available.\n     *\n     * For example, for a `RateLimiter` using the `token-bucket` algorithm with\n     * a `limit` of `10` and an `interval` of `1 seconds`, `1` request can be\n     * made every `100 millis`.\n     *\n     * `fixed-window`: The maximum number of requests will be reset during each\n     * interval. For example, for a `RateLimiter` using the `fixed-window`\n     * algorithm with a `limit` of `10` and an `interval` of `1 seconds`, a\n     * maximum of `10` requests can be made each second.\n     */\n    readonly interval: DurationInput\n    /**\n     * The algorithm to utilize for rate-limiting requests.\n     *\n     * Defaults to `token-bucket`.\n     */\n    readonly algorithm?: \"fixed-window\" | \"token-bucket\"\n  }\n}\n\n/**\n * Constructs a new `RateLimiter` which will utilize the specified algorithm\n * to limit requests (defaults to `token-bucket`).\n *\n * Notes\n * - Only the moment of starting the effect is rate limited. The number of concurrent executions is not bounded.\n * - Instances of `RateLimiter` can be composed.\n * - The \"cost\" per effect can be changed. See {@link withCost}\n *\n * @example\n * ```ts\n * import { Effect, RateLimiter } from \"effect\";\n * import { compose } from \"effect/Function\"\n *\n * const program = Effect.scoped(\n *   Effect.gen(function* ($) {\n *     const perMinuteRL = yield* $(RateLimiter.make({ limit: 30, interval: \"1 minutes\" }))\n *     const perSecondRL = yield* $(RateLimiter.make({ limit: 2, interval: \"1 seconds\" }))\n *\n *     // This rate limiter respects both the 30 calls per minute\n *     // and the 2 calls per second constraints.\n *      const rateLimit = compose(perMinuteRL, perSecondRL)\n *\n *     // simulate repeated calls\n *     for (let n = 0; n < 100; n++) {\n *       // wrap the effect we want to limit with rateLimit\n *       yield* $(rateLimit(Effect.log(\"Calling RateLimited Effect\")));\n *     }\n *   })\n * );\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (options: RateLimiter.Options) => Effect<RateLimiter, never, Scope> = internal.make\n\n/**\n * Alters the per-effect cost of the rate-limiter.\n *\n * This can be used for \"credit\" based rate-limiting where different API endpoints\n * cost a different number of credits within a time window.\n * Eg: 1000 credits / hour, where a query costs 1 credit and a mutation costs 5 credits.\n *\n * @example\n * ```ts\n * import { Effect, RateLimiter } from \"effect\";\n * import { compose } from \"effect/Function\";\n *\n * const program = Effect.scoped(\n *   Effect.gen(function* ($) {\n *     // Create a rate limiter that has an hourly limit of 1000 credits\n *     const rateLimiter = yield* $(RateLimiter.make({ limit: 1000, interval: \"1 hours\" }));\n *     // Query API costs 1 credit per call ( 1 is the default cost )\n *     const queryAPIRL = compose(rateLimiter, RateLimiter.withCost(1));\n *     // Mutation API costs 5 credits per call\n *     const mutationAPIRL = compose(rateLimiter, RateLimiter.withCost(5));\n\n *     // Use the pre-defined rate limiters\n *     yield* $(queryAPIRL(Effect.log(\"Sample Query\")));\n *     yield* $(mutationAPIRL(Effect.log(\"Sample Mutation\")));\n *\n *     // Or set a cost on-the-fly\n *     yield* $(\n *       rateLimiter(Effect.log(\"Another query with a different cost\")).pipe(\n *         RateLimiter.withCost(3)\n *       )\n *     );\n *   })\n * );\n * ```\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const withCost: (cost: number) => <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R> = internal.withCost\n"
  },
  {
    "path": "packages/effect/src/RcMap.ts",
    "content": "/**\n * @since 3.5.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/rcMap.js\"\nimport { type Pipeable } from \"./Pipeable.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 3.5.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 3.5.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 3.5.0\n * @category models\n */\nexport interface RcMap<in K, out A, out E = never> extends Pipeable {\n  readonly [TypeId]: RcMap.Variance<K, A, E>\n}\n\n/**\n * @since 3.5.0\n * @category models\n */\nexport declare namespace RcMap {\n  /**\n   * @since 3.5.0\n   * @category models\n   */\n  export interface Variance<K, A, E> {\n    readonly _K: Types.Contravariant<K>\n    readonly _A: Types.Covariant<A>\n    readonly _E: Types.Covariant<E>\n  }\n}\n\n/**\n * An `RcMap` can contain multiple reference counted resources that can be indexed\n * by a key. The resources are lazily acquired on the first call to `get` and\n * released when the last reference is released.\n *\n * Complex keys can extend `Equal` and `Hash` to allow lookups by value.\n *\n * **Options**\n *\n * - `capacity`: The maximum number of resources that can be held in the map.\n * - `idleTimeToLive`: When the reference count reaches zero, the resource will be released after this duration.\n *   Can be a static duration or a function that returns a duration based on the key.\n *\n * @since 3.5.0\n * @category models\n * @example\n * ```ts\n * import { Effect, RcMap } from \"effect\"\n *\n * Effect.gen(function*() {\n *   const map = yield* RcMap.make({\n *     lookup: (key: string) =>\n *       Effect.acquireRelease(\n *         Effect.succeed(`acquired ${key}`),\n *         () => Effect.log(`releasing ${key}`)\n *       )\n *   })\n *\n *   // Get \"foo\" from the map twice, which will only acquire it once.\n *   // It will then be released once the scope closes.\n *   yield* RcMap.get(map, \"foo\").pipe(\n *     Effect.andThen(RcMap.get(map, \"foo\")),\n *     Effect.scoped\n *   )\n * })\n * ```\n */\nexport const make: {\n  <K, A, E, R>(\n    options: {\n      readonly lookup: (key: K) => Effect.Effect<A, E, R>\n      readonly idleTimeToLive?: Duration.DurationInput | ((key: K) => Duration.DurationInput) | undefined\n      readonly capacity?: undefined\n    }\n  ): Effect.Effect<RcMap<K, A, E>, never, Scope.Scope | R>\n  <K, A, E, R>(\n    options: {\n      readonly lookup: (key: K) => Effect.Effect<A, E, R>\n      readonly idleTimeToLive?: Duration.DurationInput | ((key: K) => Duration.DurationInput) | undefined\n      readonly capacity: number\n    }\n  ): Effect.Effect<RcMap<K, A, E | Cause.ExceededCapacityException>, never, Scope.Scope | R>\n} = internal.make\n\n/**\n * @since 3.5.0\n * @category combinators\n */\nexport const get: {\n  <K>(key: K): <A, E>(self: RcMap<K, A, E>) => Effect.Effect<A, E, Scope.Scope>\n  <K, A, E>(self: RcMap<K, A, E>, key: K): Effect.Effect<A, E, Scope.Scope>\n} = internal.get\n\n/**\n * @since 3.17.7\n * @category combinators\n */\nexport const has: {\n  <K>(key: K): <A, E>(self: RcMap<K, A, E>) => Effect.Effect<boolean>\n  <K, A, E>(self: RcMap<K, A, E>, key: K): Effect.Effect<boolean>\n} = internal.has\n\n/**\n * @since 3.8.0\n * @category combinators\n */\nexport const keys: <K, A, E>(self: RcMap<K, A, E>) => Effect.Effect<Array<K>> = internal.keys\n\n/**\n * @since 3.13.0\n * @category combinators\n */\nexport const invalidate: {\n  <K>(key: K): <A, E>(self: RcMap<K, A, E>) => Effect.Effect<void>\n  <K, A, E>(self: RcMap<K, A, E>, key: K): Effect.Effect<void>\n} = internal.invalidate\n\n/**\n * @since 3.13.0\n * @category combinators\n */\nexport const touch: {\n  <K>(key: K): <A, E>(self: RcMap<K, A, E>) => Effect.Effect<void>\n  <K, A, E>(self: RcMap<K, A, E>, key: K): Effect.Effect<void>\n} = internal.touch\n"
  },
  {
    "path": "packages/effect/src/RcRef.ts",
    "content": "/**\n * @since 3.5.0\n */\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/rcRef.js\"\nimport type * as Readable from \"./Readable.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 3.5.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 3.5.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 3.5.0\n * @category models\n */\nexport interface RcRef<out A, out E = never>\n  extends Effect.Effect<A, E, Scope.Scope>, Readable.Readable<A, E, Scope.Scope>\n{\n  readonly [TypeId]: RcRef.Variance<A, E>\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: RcRefUnify<this>\n  readonly [Unify.ignoreSymbol]?: RcRefUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface RcRefUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  RcRef?: () => A[Unify.typeSymbol] extends RcRef<infer A0, infer E0> | infer _ ? RcRef<A0, E0>\n    : never\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface RcRefUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n/**\n * @since 3.5.0\n * @category models\n */\nexport declare namespace RcRef {\n  /**\n   * @since 3.5.0\n   * @category models\n   */\n  export interface Variance<A, E> {\n    readonly _A: Types.Covariant<A>\n    readonly _E: Types.Covariant<E>\n  }\n}\n\n/**\n * Create an `RcRef` from an acquire `Effect`.\n *\n * An RcRef wraps a reference counted resource that can be acquired and released\n * multiple times.\n *\n * The resource is lazily acquired on the first call to `get` and released when\n * the last reference is released.\n *\n * @since 3.5.0\n * @category constructors\n * @example\n * ```ts\n * import { Effect, RcRef } from \"effect\"\n *\n * Effect.gen(function*() {\n *   const ref = yield* RcRef.make({\n *     acquire: Effect.acquireRelease(\n *       Effect.succeed(\"foo\"),\n *       () => Effect.log(\"release foo\")\n *     )\n *   })\n *\n *   // will only acquire the resource once, and release it\n *   // when the scope is closed\n *   yield* RcRef.get(ref).pipe(\n *     Effect.andThen(RcRef.get(ref)),\n *     Effect.scoped\n *   )\n * })\n * ```\n */\nexport const make: <A, E, R>(\n  options: {\n    readonly acquire: Effect.Effect<A, E, R>\n    /**\n     * When the reference count reaches zero, the resource will be released\n     * after this duration.\n     */\n    readonly idleTimeToLive?: Duration.DurationInput | undefined\n  }\n) => Effect.Effect<RcRef<A, E>, never, R | Scope.Scope> = internal.make\n\n/**\n * @since 3.5.0\n * @category combinators\n */\nexport const get: <A, E>(self: RcRef<A, E>) => Effect.Effect<A, E, Scope.Scope> = internal.get\n\n/**\n * @since 3.19.6\n * @category combinators\n * @experimental\n */\nexport const invalidate: <A, E>(self: RcRef<A, E>) => Effect.Effect<void> = internal.invalidate\n"
  },
  {
    "path": "packages/effect/src/Readable.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { Effect } from \"./Effect.js\"\nimport { dual } from \"./Function.js\"\nimport * as core from \"./internal/core.js\"\nimport { type Pipeable, pipeArguments } from \"./Pipeable.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport type { NoInfer } from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/Readable\")\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Readable<A, E = never, R = never> extends Pipeable {\n  readonly [TypeId]: TypeId\n  readonly get: Effect<A, E, R>\n}\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isReadable = (u: unknown): u is Readable<unknown, unknown, unknown> => hasProperty(u, TypeId)\n\nconst Proto: Omit<Readable<any>, \"get\"> = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make = <A, E, R>(get: Effect<A, E, R>): Readable<A, E, R> => {\n  const self = Object.create(Proto)\n  self.get = get\n  return self\n}\n\n/**\n * @since 2.0.0\n * @category combinators\n */\nexport const map: {\n  <A, B>(f: (a: NoInfer<A>) => B): <E, R>(fa: Readable<A, E, R>) => Readable<B, E, R>\n  <A, E, R, B>(self: Readable<A, E, R>, f: (a: NoInfer<A>) => B): Readable<B, E, R>\n} = dual(\n  2,\n  <A, E, R, B>(self: Readable<A, E, R>, f: (a: NoInfer<A>) => B): Readable<B, E, R> => make(core.map(self.get, f))\n)\n\n/**\n * @since 2.0.0\n * @category combinators\n */\nexport const mapEffect: {\n  <A, B, E2, R2>(\n    f: (a: NoInfer<A>) => Effect<B, E2, R2>\n  ): <E, R>(fa: Readable<A, E, R>) => Readable<B, E | E2, R | R2>\n  <A, E, R, B, E2, R2>(\n    self: Readable<A, E, R>,\n    f: (a: NoInfer<A>) => Effect<B, E2, R2>\n  ): Readable<B, E | E2, R | R2>\n} = dual(2, <A, E, R, B, E2, R2>(\n  self: Readable<A, E, R>,\n  f: (a: NoInfer<A>) => Effect<B, E2, R2>\n): Readable<B, E | E2, R | R2> => make(core.flatMap(self.get, f)))\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const unwrap = <A, E, R, E1, R1>(\n  effect: Effect<Readable<A, E, R>, E1, R1>\n): Readable<A, E | E1, R | R1> =>\n  make(\n    core.flatMap(effect, (s) => s.get)\n  )\n"
  },
  {
    "path": "packages/effect/src/Record.ts",
    "content": "/**\n * This module provides utility functions for working with records in TypeScript.\n *\n * @since 2.0.0\n */\n\nimport type { Either } from \"./Either.js\"\nimport * as E from \"./Either.js\"\nimport * as Equal from \"./Equal.js\"\nimport type { Equivalence } from \"./Equivalence.js\"\nimport { dual, identity } from \"./Function.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport * as Option from \"./Option.js\"\nimport type { NoInfer } from \"./Types.js\"\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport type ReadonlyRecord<in out K extends string | symbol, out A> = {\n  readonly [P in K]: A\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace ReadonlyRecord {\n  type IsFiniteString<T extends string> = T extends \"\" ? true :\n    [T] extends [`${infer Head}${infer Rest}`]\n      ? string extends Head ? false : `${number}` extends Head ? false : Rest extends \"\" ? true : IsFiniteString<Rest>\n    : false\n\n  /**\n   * @since 2.0.0\n   */\n  export type NonLiteralKey<K extends string | symbol> = K extends string ? IsFiniteString<K> extends true ? string : K\n    : symbol\n\n  /**\n   * @since 2.0.0\n   */\n  export type IntersectKeys<K1 extends string, K2 extends string> = [string] extends [K1 | K2] ?\n    NonLiteralKey<K1> & NonLiteralKey<K2>\n    : K1 & K2\n}\n\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface ReadonlyRecordTypeLambda<K extends string = string> extends TypeLambda {\n  readonly type: ReadonlyRecord<K, this[\"Target\"]>\n}\n\n/**\n * Creates a new, empty record.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = <K extends string | symbol = never, V = never>(): Record<\n  ReadonlyRecord.NonLiteralKey<K>,\n  V\n> => ({} as any)\n\n/**\n * Determine if a record is empty.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isEmptyRecord } from \"effect/Record\"\n *\n * assert.deepStrictEqual(isEmptyRecord({}), true);\n * assert.deepStrictEqual(isEmptyRecord({ a: 3 }), false);\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEmptyRecord = <K extends string, A>(self: Record<K, A>): self is Record<K, never> =>\n  keys(self).length === 0\n\n/**\n * Determine if a record is empty.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { isEmptyReadonlyRecord } from \"effect/Record\"\n *\n * assert.deepStrictEqual(isEmptyReadonlyRecord({}), true);\n * assert.deepStrictEqual(isEmptyReadonlyRecord({ a: 3 }), false);\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isEmptyReadonlyRecord: <K extends string, A>(\n  self: ReadonlyRecord<K, A>\n) => self is ReadonlyRecord<K, never> = isEmptyRecord\n\n/**\n * Takes an iterable and a projection function and returns a record.\n * The projection function maps each value of the iterable to a tuple of a key and a value, which is then added to the resulting record.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { fromIterableWith } from \"effect/Record\"\n *\n * const input = [1, 2, 3, 4]\n *\n * assert.deepStrictEqual(\n *   fromIterableWith(input, a => [String(a), a * 2]),\n *   { '1': 2, '2': 4, '3': 6, '4': 8 }\n * )\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterableWith: {\n  <A, K extends string | symbol, B>(\n    f: (a: A) => readonly [K, B]\n  ): (self: Iterable<A>) => Record<ReadonlyRecord.NonLiteralKey<K>, B>\n  <A, K extends string | symbol, B>(\n    self: Iterable<A>,\n    f: (a: A) => readonly [K, B]\n  ): Record<ReadonlyRecord.NonLiteralKey<K>, B>\n} = dual(\n  2,\n  <A, K extends string, B>(\n    self: Iterable<A>,\n    f: (a: A) => readonly [K, B]\n  ): Record<ReadonlyRecord.NonLiteralKey<K>, B> => {\n    const out: Record<string, B> = empty()\n    for (const a of self) {\n      const [k, b] = f(a)\n      out[k] = b\n    }\n    return out\n  }\n)\n\n/**\n * Creates a new record from an iterable, utilizing the provided function to determine the key for each element.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { fromIterableBy } from \"effect/Record\"\n *\n * const users = [\n *   { id: \"2\", name: \"name2\" },\n *   { id: \"1\", name: \"name1\" }\n * ]\n *\n * assert.deepStrictEqual(\n *   fromIterableBy(users, user => user.id),\n *   {\n *     \"2\": { id: \"2\", name: \"name2\" },\n *     \"1\": { id: \"1\", name: \"name1\" }\n *   }\n * )\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterableBy = <A, K extends string | symbol>(\n  items: Iterable<A>,\n  f: (a: A) => K\n): Record<ReadonlyRecord.NonLiteralKey<K>, A> => fromIterableWith(items, (a) => [f(a), a])\n\n/**\n * Builds a record from an iterable of key-value pairs.\n *\n * If there are conflicting keys when using `fromEntries`, the last occurrence of the key/value pair will overwrite the\n * previous ones. So the resulting record will only have the value of the last occurrence of each key.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { fromEntries } from \"effect/Record\"\n *\n * const input: Array<[string, number]> = [[\"a\", 1], [\"b\", 2]]\n *\n * assert.deepStrictEqual(fromEntries(input), { a: 1, b: 2 })\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEntries: <Entry extends readonly [string | symbol, any]>(\n  entries: Iterable<Entry>\n) => Record<ReadonlyRecord.NonLiteralKey<Entry[0]>, Entry[1]> = Object.fromEntries\n\n/**\n * Transforms the values of a record into an `Array` with a custom mapping function.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { collect } from \"effect/Record\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * assert.deepStrictEqual(collect(x, (key, n) => [key, n]), [[\"a\", 1], [\"b\", 2], [\"c\", 3]])\n * ```\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const collect: {\n  <K extends string, A, B>(f: (key: K, a: A) => B): (self: ReadonlyRecord<K, A>) => Array<B>\n  <K extends string, A, B>(self: ReadonlyRecord<K, A>, f: (key: K, a: A) => B): Array<B>\n} = dual(\n  2,\n  <K extends string, A, B>(self: ReadonlyRecord<K, A>, f: (key: K, a: A) => B): Array<B> => {\n    const out: Array<B> = []\n    for (const key of keys(self)) {\n      out.push(f(key, self[key]))\n    }\n    return out\n  }\n)\n\n/**\n * Takes a record and returns an array of tuples containing its keys and values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { toEntries } from \"effect/Record\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * assert.deepStrictEqual(toEntries(x), [[\"a\", 1], [\"b\", 2], [\"c\", 3]])\n * ```\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const toEntries: <K extends string, A>(self: ReadonlyRecord<K, A>) => Array<[K, A]> = collect((\n  key,\n  value\n) => [key, value])\n\n/**\n * Returns the number of key/value pairs in a record.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { size } from \"effect/Record\";\n *\n * assert.deepStrictEqual(size({ a: \"a\", b: 1, c: true }), 3);\n * ```\n *\n * @since 2.0.0\n */\nexport const size = <K extends string, A>(self: ReadonlyRecord<K, A>): number => keys(self).length\n\n/**\n * Check if a given `key` exists in a record.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { empty, has } from \"effect/Record\"\n *\n * assert.deepStrictEqual(has({ a: 1, b: 2 }, \"a\"), true);\n * assert.deepStrictEqual(has(empty<string>(), \"c\"), false);\n * ```\n *\n * @since 2.0.0\n */\nexport const has: {\n  <K extends string | symbol>(\n    key: NoInfer<K>\n  ): <A>(self: ReadonlyRecord<K, A>) => boolean\n  <K extends string | symbol, A>(\n    self: ReadonlyRecord<K, A>,\n    key: NoInfer<K>\n  ): boolean\n} = dual(\n  2,\n  <K extends string | symbol, A>(\n    self: ReadonlyRecord<K, A>,\n    key: NoInfer<K>\n  ): boolean => Object.prototype.hasOwnProperty.call(self, key)\n)\n\n/**\n * Retrieve a value at a particular key from a record, returning it wrapped in an `Option`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record as R, Option } from \"effect\"\n *\n * const person: Record<string, unknown> = { name: \"John Doe\", age: 35 }\n *\n * assert.deepStrictEqual(R.get(person, \"name\"), Option.some(\"John Doe\"))\n * assert.deepStrictEqual(R.get(person, \"email\"), Option.none())\n * ```\n *\n * @since 2.0.0\n */\nexport const get: {\n  <K extends string | symbol>(key: NoInfer<K>): <A>(self: ReadonlyRecord<K, A>) => Option.Option<A>\n  <K extends string | symbol, A>(self: ReadonlyRecord<K, A>, key: NoInfer<K>): Option.Option<A>\n} = dual(\n  2,\n  <K extends string | symbol, A>(self: ReadonlyRecord<K, A>, key: NoInfer<K>): Option.Option<A> =>\n    has(self, key) ? Option.some(self[key]) : Option.none()\n)\n\n/**\n * Apply a function to the element at the specified key, creating a new record.\n * If the key does not exist, the record is returned unchanged.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record as R } from \"effect\"\n *\n * const f = (x: number) => x * 2\n *\n * assert.deepStrictEqual(\n *  R.modify({ a: 3 }, 'a', f),\n *  { a: 6 }\n * )\n * assert.deepStrictEqual(\n *  R.modify({ a: 3 } as Record<string, number>, 'b', f),\n *  { a: 3 }\n * )\n * ```\n *\n * @since 2.0.0\n */\nexport const modify: {\n  <K extends string | symbol, A, B>(\n    key: NoInfer<K>,\n    f: (a: A) => B\n  ): (self: ReadonlyRecord<K, A>) => Record<K, A | B>\n  <K extends string | symbol, A, B>(self: ReadonlyRecord<K, A>, key: NoInfer<K>, f: (a: A) => B): Record<K, A | B>\n} = dual(\n  3,\n  <K extends string | symbol, A, B>(self: ReadonlyRecord<K, A>, key: NoInfer<K>, f: (a: A) => B): Record<K, A | B> => {\n    if (!has(self, key)) {\n      return { ...self }\n    }\n    return { ...self, [key]: f(self[key]) }\n  }\n)\n\n/**\n * Apply a function to the element at the specified key, creating a new record,\n * or return `None` if the key doesn't exist.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record as R, Option } from \"effect\"\n *\n * const f = (x: number) => x * 2\n *\n * assert.deepStrictEqual(\n *  R.modifyOption({ a: 3 }, 'a', f),\n *  Option.some({ a: 6 })\n * )\n * assert.deepStrictEqual(\n *  R.modifyOption({ a: 3 } as Record<string, number>, 'b', f),\n *  Option.none()\n * )\n * ```\n *\n * @since 2.0.0\n */\nexport const modifyOption: {\n  <K extends string | symbol, A, B>(\n    key: NoInfer<K>,\n    f: (a: A) => B\n  ): (self: ReadonlyRecord<K, A>) => Option.Option<Record<K, A | B>>\n  <K extends string | symbol, A, B>(\n    self: ReadonlyRecord<K, A>,\n    key: NoInfer<K>,\n    f: (a: A) => B\n  ): Option.Option<Record<K, A | B>>\n} = dual(\n  3,\n  <K extends string | symbol, A, B>(\n    self: ReadonlyRecord<K, A>,\n    key: NoInfer<K>,\n    f: (a: A) => B\n  ): Option.Option<Record<K, A | B>> => {\n    if (!has(self, key)) {\n      return Option.none()\n    }\n    return Option.some({ ...self, [key]: f(self[key]) })\n  }\n)\n\n/**\n * Replaces a value in the record with the new value passed as parameter.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record, Option } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Record.replaceOption({ a: 1, b: 2, c: 3 }, 'a', 10),\n *   Option.some({ a: 10, b: 2, c: 3 })\n * )\n * assert.deepStrictEqual(Record.replaceOption(Record.empty<string>(), 'a', 10), Option.none())\n * ```\n *\n * @since 2.0.0\n */\nexport const replaceOption: {\n  <K extends string | symbol, B>(\n    key: NoInfer<K>,\n    b: B\n  ): <A>(self: ReadonlyRecord<K, A>) => Option.Option<Record<K, A | B>>\n  <K extends string | symbol, A, B>(\n    self: ReadonlyRecord<K, A>,\n    key: NoInfer<K>,\n    b: B\n  ): Option.Option<Record<K, A | B>>\n} = dual(\n  3,\n  <K extends string | symbol, A, B>(\n    self: ReadonlyRecord<K, A>,\n    key: NoInfer<K>,\n    b: B\n  ): Option.Option<Record<K, A | B>> => modifyOption(self, key, () => b)\n)\n\n/**\n * If the given key exists in the record, returns a new record with the key removed,\n * otherwise returns a copy of the original record.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { remove } from \"effect/Record\"\n *\n * assert.deepStrictEqual(remove({ a: 1, b: 2 }, \"a\"), { b: 2 })\n * ```\n *\n * @since 2.0.0\n */\nexport const remove: {\n  <K extends string | symbol, X extends K>(key: X): <A>(self: ReadonlyRecord<K, A>) => Record<Exclude<K, X>, A>\n  <K extends string | symbol, A, X extends K>(self: ReadonlyRecord<K, A>, key: X): Record<Exclude<K, X>, A>\n} = dual(\n  2,\n  <K extends string | symbol, A, X extends K>(self: ReadonlyRecord<K, A>, key: X): Record<Exclude<K, X>, A> => {\n    if (!has(self, key)) {\n      return { ...self }\n    }\n    const out = { ...self }\n    delete out[key]\n    return out\n  }\n)\n\n/**\n * Retrieves the value of the property with the given `key` from a record and returns an `Option`\n * of a tuple with the value and the record with the removed property.\n * If the key is not present, returns `O.none`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record as R, Option } from \"effect\"\n *\n * assert.deepStrictEqual(R.pop({ a: 1, b: 2 }, \"a\"), Option.some([1, { b: 2 }]))\n * assert.deepStrictEqual(R.pop({ a: 1, b: 2 } as Record<string, number>, \"c\"), Option.none())\n * ```\n *\n * @category record\n * @since 2.0.0\n */\nexport const pop: {\n  <K extends string | symbol, X extends K>(\n    key: X\n  ): <A>(self: ReadonlyRecord<K, A>) => Option.Option<[A, Record<Exclude<K, X>, A>]>\n  <K extends string | symbol, A, X extends K>(\n    self: ReadonlyRecord<K, A>,\n    key: X\n  ): Option.Option<[A, Record<Exclude<K, X>, A>]>\n} = dual(2, <K extends string | symbol, A, X extends K>(\n  self: ReadonlyRecord<K, A>,\n  key: X\n): Option.Option<[A, Record<Exclude<K, X>, A>]> =>\n  has(self, key) ? Option.some([self[key], remove(self, key)]) : Option.none())\n\n/**\n * Maps a record into another record by applying a transformation function to each of its values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { map } from \"effect/Record\"\n *\n * const f = (n: number) => `-${n}`\n *\n * assert.deepStrictEqual(map({ a: 3, b: 5 }, f), { a: \"-3\", b: \"-5\" })\n *\n * const g = (n: number, key: string) => `${key.toUpperCase()}-${n}`\n *\n * assert.deepStrictEqual(map({ a: 3, b: 5 }, g), { a: \"A-3\", b: \"B-5\" })\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const map: {\n  <K extends string, A, B>(f: (a: A, key: NoInfer<K>) => B): (self: ReadonlyRecord<K, A>) => Record<K, B>\n  <K extends string, A, B>(self: ReadonlyRecord<K, A>, f: (a: A, key: NoInfer<K>) => B): Record<K, B>\n} = dual(\n  2,\n  <K extends string, A, B>(self: ReadonlyRecord<K, A>, f: (a: A, key: NoInfer<K>) => B): Record<K, B> => {\n    const out: Record<K, B> = { ...self } as any\n    for (const key of keys(self)) {\n      out[key] = f(self[key], key)\n    }\n    return out\n  }\n)\n\n/**\n * Maps the keys of a `ReadonlyRecord` while preserving the corresponding values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { mapKeys } from \"effect/Record\"\n *\n * assert.deepStrictEqual(mapKeys({ a: 3, b: 5 }, (key) => key.toUpperCase()), { A: 3, B: 5 })\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapKeys: {\n  <K extends string, A, K2 extends string>(\n    f: (key: K, a: A) => K2\n  ): (self: ReadonlyRecord<K, A>) => Record<K2, A>\n  <K extends string, A, K2 extends string>(\n    self: ReadonlyRecord<K, A>,\n    f: (key: K, a: A) => K2\n  ): Record<K2, A>\n} = dual(\n  2,\n  <K extends string, A, K2 extends string>(\n    self: ReadonlyRecord<K, A>,\n    f: (key: K, a: A) => K2\n  ): Record<K2, A> => {\n    const out: Record<K2, A> = {} as any\n    for (const key of keys(self)) {\n      const a = self[key]\n      out[f(key, a)] = a\n    }\n    return out\n  }\n)\n\n/**\n * Maps entries of a `ReadonlyRecord` using the provided function, allowing modification of both keys and corresponding values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { mapEntries } from \"effect/Record\"\n *\n * assert.deepStrictEqual(mapEntries({ a: 3, b: 5 }, (a, key) => [key.toUpperCase(), a + 1]), { A: 4, B: 6 })\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapEntries: {\n  <K extends string, A, K2 extends string, B>(\n    f: (a: A, key: K) => readonly [K2, B]\n  ): (self: ReadonlyRecord<K, A>) => Record<K2, B>\n  <K extends string, A, K2 extends string, B>(\n    self: ReadonlyRecord<K, A>,\n    f: (a: A, key: K) => [K2, B]\n  ): Record<K2, B>\n} = dual(\n  2,\n  <K extends string, A, K2 extends string, B>(\n    self: ReadonlyRecord<K, A>,\n    f: (a: A, key: K) => [K2, B]\n  ): Record<K2, B> => {\n    const out = <Record<K2, B>> {}\n    for (const key of keys(self)) {\n      const [k, b] = f(self[key], key)\n      out[k] = b\n    }\n    return out\n  }\n)\n\n/**\n * Transforms a record into a record by applying the function `f` to each key and value in the original record.\n * If the function returns `Some`, the key-value pair is included in the output record.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record, Option } from \"effect\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * const f = (a: number, key: string) => a > 2 ? Option.some(a * 2) : Option.none()\n * assert.deepStrictEqual(Record.filterMap(x, f), { c: 6 })\n * ```\n *\n * @since 2.0.0\n */\nexport const filterMap: {\n  <K extends string, A, B>(\n    f: (a: A, key: K) => Option.Option<B>\n  ): (self: ReadonlyRecord<K, A>) => Record<ReadonlyRecord.NonLiteralKey<K>, B>\n  <K extends string, A, B>(\n    self: ReadonlyRecord<K, A>,\n    f: (a: A, key: K) => Option.Option<B>\n  ): Record<ReadonlyRecord.NonLiteralKey<K>, B>\n} = dual(\n  2,\n  <K extends string, A, B>(\n    self: ReadonlyRecord<K, A>,\n    f: (a: A, key: K) => Option.Option<B>\n  ): Record<ReadonlyRecord.NonLiteralKey<K>, B> => {\n    const out: Record<string, B> = empty()\n    for (const key of keys(self)) {\n      const o = f(self[key], key)\n      if (Option.isSome(o)) {\n        out[key] = o.value\n      }\n    }\n    return out\n  }\n)\n\n/**\n * Selects properties from a record whose values match the given predicate.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { filter } from \"effect/Record\"\n *\n * const x = { a: 1, b: 2, c: 3, d: 4 }\n * assert.deepStrictEqual(filter(x, (n) => n > 2), { c: 3, d: 4 })\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const filter: {\n  <K extends string, A, B extends A>(\n    refinement: (a: NoInfer<A>, key: K) => a is B\n  ): (self: ReadonlyRecord<K, A>) => Record<ReadonlyRecord.NonLiteralKey<K>, B>\n  <K extends string, A>(\n    predicate: (A: NoInfer<A>, key: K) => boolean\n  ): (self: ReadonlyRecord<K, A>) => Record<ReadonlyRecord.NonLiteralKey<K>, A>\n  <K extends string, A, B extends A>(\n    self: ReadonlyRecord<K, A>,\n    refinement: (a: A, key: K) => a is B\n  ): Record<ReadonlyRecord.NonLiteralKey<K>, B>\n  <K extends string, A>(\n    self: ReadonlyRecord<K, A>,\n    predicate: (a: A, key: K) => boolean\n  ): Record<ReadonlyRecord.NonLiteralKey<K>, A>\n} = dual(\n  2,\n  <K extends string, A>(\n    self: ReadonlyRecord<K, A>,\n    predicate: (a: A, key: K) => boolean\n  ): Record<ReadonlyRecord.NonLiteralKey<K>, A> => {\n    const out: Record<string, A> = empty()\n    for (const key of keys(self)) {\n      if (predicate(self[key], key)) {\n        out[key] = self[key]\n      }\n    }\n    return out\n  }\n)\n\n/**\n * Given a record with `Option` values, returns a new record containing only the `Some` values, preserving the original keys.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record, Option } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Record.getSomes({ a: Option.some(1), b: Option.none(), c: Option.some(2) }),\n *   { a: 1, c: 2 }\n * )\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getSomes: <K extends string, A>(\n  self: ReadonlyRecord<K, Option.Option<A>>\n) => Record<ReadonlyRecord.NonLiteralKey<K>, A> = filterMap(\n  identity\n)\n\n/**\n * Given a record with `Either` values, returns a new record containing only the `Left` values, preserving the original keys.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record, Either } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Record.getLefts({ a: Either.right(1), b: Either.left(\"err\"), c: Either.right(2) }),\n *   { b: \"err\" }\n * )\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getLefts = <K extends string, R, L>(\n  self: ReadonlyRecord<K, Either<R, L>>\n): Record<ReadonlyRecord.NonLiteralKey<K>, L> => {\n  const out: Record<string, L> = empty()\n  for (const key of keys(self)) {\n    const value = self[key]\n    if (E.isLeft(value)) {\n      out[key] = value.left\n    }\n  }\n\n  return out\n}\n\n/**\n * Given a record with `Either` values, returns a new record containing only the `Right` values, preserving the original keys.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record, Either } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Record.getRights({ a: Either.right(1), b: Either.left(\"err\"), c: Either.right(2) }),\n *   { a: 1, c: 2 }\n * )\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const getRights = <K extends string, R, L>(\n  self: ReadonlyRecord<K, Either<R, L>>\n): Record<string, R> => {\n  const out: Record<string, R> = empty()\n  for (const key of keys(self)) {\n    const value = self[key]\n    if (E.isRight(value)) {\n      out[key] = value.right\n    }\n  }\n\n  return out\n}\n\n/**\n * Partitions the elements of a record into two groups: those that match a predicate, and those that don't.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record, Either } from \"effect\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * const f = (n: number) => (n % 2 === 0 ? Either.right(n) : Either.left(n))\n * assert.deepStrictEqual(Record.partitionMap(x, f), [{ a: 1, c: 3 }, { b: 2}])\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partitionMap: {\n  <K extends string, A, B, C>(\n    f: (a: A, key: K) => Either<C, B>\n  ): (\n    self: ReadonlyRecord<K, A>\n  ) => [left: Record<ReadonlyRecord.NonLiteralKey<K>, B>, right: Record<ReadonlyRecord.NonLiteralKey<K>, C>]\n  <K extends string, A, B, C>(\n    self: ReadonlyRecord<K, A>,\n    f: (a: A, key: K) => Either<C, B>\n  ): [left: Record<ReadonlyRecord.NonLiteralKey<K>, B>, right: Record<ReadonlyRecord.NonLiteralKey<K>, C>]\n} = dual(\n  2,\n  <K extends string, A, B, C>(\n    self: ReadonlyRecord<K, A>,\n    f: (a: A, key: K) => Either<C, B>\n  ): [left: Record<ReadonlyRecord.NonLiteralKey<K>, B>, right: Record<ReadonlyRecord.NonLiteralKey<K>, C>] => {\n    const left: Record<string, B> = empty()\n    const right: Record<string, C> = empty()\n    for (const key of keys(self)) {\n      const e = f(self[key], key)\n      if (E.isLeft(e)) {\n        left[key] = e.left\n      } else {\n        right[key] = e.right\n      }\n    }\n    return [left, right]\n  }\n)\n\n/**\n * Partitions a record of `Either` values into two separate records,\n * one with the `Left` values and one with the `Right` values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record, Either } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   Record.separate({ a: Either.left(\"e\"), b: Either.right(1) }),\n *   [{ a: \"e\" }, { b: 1 }]\n * )\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const separate: <K extends string, A, B>(\n  self: ReadonlyRecord<K, Either<B, A>>\n) => [Record<ReadonlyRecord.NonLiteralKey<K>, A>, Record<ReadonlyRecord.NonLiteralKey<K>, B>] = partitionMap(identity)\n\n/**\n * Partitions a record into two separate records based on the result of a predicate function.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { partition } from \"effect/Record\"\n *\n * assert.deepStrictEqual(\n *   partition({ a: 1, b: 3 }, (n) => n > 2),\n *   [{ a: 1 }, { b: 3 }]\n * )\n * ```\n *\n * @category filtering\n * @since 2.0.0\n */\nexport const partition: {\n  <K extends string, A, B extends A>(refinement: (a: NoInfer<A>, key: K) => a is B): (\n    self: ReadonlyRecord<K, A>\n  ) => [\n    excluded: Record<ReadonlyRecord.NonLiteralKey<K>, Exclude<A, B>>,\n    satisfying: Record<ReadonlyRecord.NonLiteralKey<K>, B>\n  ]\n  <K extends string, A>(\n    predicate: (a: NoInfer<A>, key: K) => boolean\n  ): (\n    self: ReadonlyRecord<K, A>\n  ) => [excluded: Record<ReadonlyRecord.NonLiteralKey<K>, A>, satisfying: Record<ReadonlyRecord.NonLiteralKey<K>, A>]\n  <K extends string, A, B extends A>(\n    self: ReadonlyRecord<K, A>,\n    refinement: (a: A, key: K) => a is B\n  ): [\n    excluded: Record<ReadonlyRecord.NonLiteralKey<K>, Exclude<A, B>>,\n    satisfying: Record<ReadonlyRecord.NonLiteralKey<K>, B>\n  ]\n  <K extends string, A>(\n    self: ReadonlyRecord<K, A>,\n    predicate: (a: A, key: K) => boolean\n  ): [excluded: Record<ReadonlyRecord.NonLiteralKey<K>, A>, satisfying: Record<ReadonlyRecord.NonLiteralKey<K>, A>]\n} = dual(\n  2,\n  <K extends string, A>(\n    self: ReadonlyRecord<K, A>,\n    predicate: (a: A, key: K) => boolean\n  ): [excluded: Record<ReadonlyRecord.NonLiteralKey<K>, A>, satisfying: Record<ReadonlyRecord.NonLiteralKey<K>, A>] => {\n    const left: Record<string, A> = empty()\n    const right: Record<string, A> = empty()\n    for (const key of keys(self)) {\n      if (predicate(self[key], key)) {\n        right[key] = self[key]\n      } else {\n        left[key] = self[key]\n      }\n    }\n    return [left, right]\n  }\n)\n\n/**\n * Retrieve the keys of a given record as an array.\n *\n * @since 2.0.0\n */\nexport const keys = <K extends string | symbol, A>(self: ReadonlyRecord<K, A>): Array<K & string> =>\n  Object.keys(self) as Array<K & string>\n\n/**\n * Retrieve the values of a given record as an array.\n *\n * @since 2.0.0\n */\nexport const values = <K extends string, A>(self: ReadonlyRecord<K, A>): Array<A> => collect(self, (_, a) => a)\n\n/**\n * Add a new key-value pair or update an existing key's value in a record.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { set } from \"effect/Record\"\n *\n * assert.deepStrictEqual(set(\"a\", 5)({ a: 1, b: 2 }), { a: 5, b: 2 });\n * assert.deepStrictEqual(set(\"c\", 5)({ a: 1, b: 2 }), { a: 1, b: 2, c: 5 });\n * ```\n *\n * @since 2.0.0\n */\nexport const set: {\n  <K extends string | symbol, K1 extends K | ((string | symbol) & {}), B>(\n    key: K1,\n    value: B\n  ): <A>(self: ReadonlyRecord<K, A>) => Record<K | K1, A | B>\n  <K extends string | symbol, A, K1 extends K | ((string | symbol) & {}), B>(\n    self: ReadonlyRecord<K, A>,\n    key: K1,\n    value: B\n  ): Record<K | K1, A | B>\n} = dual(\n  3,\n  <K extends string | symbol, A, K1 extends K | ((string | symbol) & {}), B>(\n    self: ReadonlyRecord<K, A>,\n    key: K1,\n    value: B\n  ): Record<K | K1, A | B> => {\n    return { ...self, [key]: value } as any\n  }\n)\n\n/**\n * Replace a key's value in a record and return the updated record.\n * If the key does not exist in the record, a copy of the original record is returned.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Record } from \"effect\"\n *\n * assert.deepStrictEqual(Record.replace(\"a\", 3)({ a: 1, b: 2 }), { a: 3, b: 2 });\n * assert.deepStrictEqual(Record.replace(\"c\", 3)({ a: 1, b: 2 }), { a: 1, b: 2 });\n * ```\n *\n * @since 2.0.0\n */\nexport const replace: {\n  <K extends string | symbol, B>(key: NoInfer<K>, value: B): <A>(self: ReadonlyRecord<K, A>) => Record<K, A | B>\n  <K extends string | symbol, A, B>(self: ReadonlyRecord<K, A>, key: NoInfer<K>, value: B): Record<K, A | B>\n} = dual(\n  3,\n  <K extends string | symbol, A, B>(self: ReadonlyRecord<K, A>, key: NoInfer<K>, value: B): Record<K, A | B> => {\n    if (has(self, key)) {\n      return { ...self, [key]: value }\n    }\n    return { ...self }\n  }\n)\n\n/**\n * Check if all the keys and values in one record are also found in another record.\n *\n * @since 2.0.0\n */\nexport const isSubrecordBy = <A>(equivalence: Equivalence<A>): {\n  <K extends string>(that: ReadonlyRecord<K, A>): (self: ReadonlyRecord<K, A>) => boolean\n  <K extends string>(self: ReadonlyRecord<K, A>, that: ReadonlyRecord<K, A>): boolean\n} =>\n  dual(2, <K extends string>(self: ReadonlyRecord<K, A>, that: ReadonlyRecord<K, A>): boolean => {\n    for (const key of keys(self)) {\n      if (!has(that, key) || !equivalence(self[key], that[key])) {\n        return false\n      }\n    }\n    return true\n  })\n\n/**\n * Check if one record is a subrecord of another, meaning it contains all the keys and values found in the second record.\n * This comparison uses default equality checks (`Equal.equivalence()`).\n *\n * @since 2.0.0\n */\nexport const isSubrecord: {\n  <K extends string, A>(that: ReadonlyRecord<K, A>): (self: ReadonlyRecord<K, A>) => boolean\n  <K extends string, A>(self: ReadonlyRecord<K, A>, that: ReadonlyRecord<K, A>): boolean\n} = isSubrecordBy(Equal.equivalence())\n\n/**\n * Reduce a record to a single value by combining its entries with a specified function.\n *\n * @category folding\n * @since 2.0.0\n */\nexport const reduce: {\n  <Z, V, K extends string>(\n    zero: Z,\n    f: (accumulator: Z, value: V, key: K) => Z\n  ): (self: ReadonlyRecord<K, V>) => Z\n  <K extends string, V, Z>(self: ReadonlyRecord<K, V>, zero: Z, f: (accumulator: Z, value: V, key: K) => Z): Z\n} = dual(\n  3,\n  <K extends string, V, Z>(\n    self: ReadonlyRecord<K, V>,\n    zero: Z,\n    f: (accumulator: Z, value: V, key: K) => Z\n  ): Z => {\n    let out: Z = zero\n    for (const key of keys(self)) {\n      out = f(out, self[key], key)\n    }\n    return out\n  }\n)\n\n/**\n * Check if all entries in a record meet a specific condition.\n *\n * @since 2.0.0\n */\nexport const every: {\n  <A, K extends string, B extends A>(\n    refinement: (value: A, key: K) => value is B\n  ): (self: ReadonlyRecord<K, A>) => self is ReadonlyRecord<K, B>\n  <A, K extends string>(predicate: (value: A, key: K) => boolean): (self: ReadonlyRecord<K, A>) => boolean\n  <A, K extends string, B extends A>(\n    self: ReadonlyRecord<K, A>,\n    refinement: (value: A, key: K) => value is B\n  ): self is ReadonlyRecord<K, B>\n  <K extends string, A>(self: ReadonlyRecord<K, A>, predicate: (value: A, key: K) => boolean): boolean\n} = dual(\n  2,\n  <A, K extends string, B extends A>(\n    self: ReadonlyRecord<K, A>,\n    refinement: (value: A, key: K) => value is B\n  ): self is ReadonlyRecord<K, B> => {\n    for (const key of keys(self)) {\n      if (!refinement(self[key], key)) {\n        return false\n      }\n    }\n    return true\n  }\n)\n\n/**\n * Check if any entry in a record meets a specific condition.\n *\n * @since 2.0.0\n */\nexport const some: {\n  <A, K extends string>(predicate: (value: A, key: K) => boolean): (self: ReadonlyRecord<K, A>) => boolean\n  <K extends string, A>(self: ReadonlyRecord<K, A>, predicate: (value: A, key: K) => boolean): boolean\n} = dual(\n  2,\n  <K extends string, A>(self: ReadonlyRecord<K, A>, predicate: (value: A, key: K) => boolean): boolean => {\n    for (const key of keys(self)) {\n      if (predicate(self[key], key)) {\n        return true\n      }\n    }\n    return false\n  }\n)\n\n/**\n * Merge two records, preserving entries that exist in either of the records.\n *\n * @since 2.0.0\n */\nexport const union: {\n  <K1 extends string, A, B, C>(\n    that: ReadonlyRecord<K1, B>,\n    combine: (selfValue: A, thatValue: B) => C\n  ): <K0 extends string>(self: ReadonlyRecord<K0, A>) => Record<K0 | K1, A | B | C>\n  <K0 extends string, A, K1 extends string, B, C>(\n    self: ReadonlyRecord<K0, A>,\n    that: ReadonlyRecord<K1, B>,\n    combine: (selfValue: A, thatValue: B) => C\n  ): Record<K0 | K1, A | B | C>\n} = dual(\n  3,\n  <K0 extends string, A, K1 extends string, B, C>(\n    self: ReadonlyRecord<K0, A>,\n    that: ReadonlyRecord<K1, B>,\n    combine: (selfValue: A, thatValue: B) => C\n  ): Record<K0 | K1, A | B | C> => {\n    if (isEmptyRecord(self)) {\n      return { ...that } as any\n    }\n    if (isEmptyRecord(that)) {\n      return { ...self } as any\n    }\n    const out: Record<string, A | B | C> = empty()\n    for (const key of keys(self)) {\n      if (has(that, key as any)) {\n        out[key] = combine(self[key], that[key as unknown as K1])\n      } else {\n        out[key] = self[key]\n      }\n    }\n    for (const key of keys(that)) {\n      if (!has(out, key)) {\n        out[key] = that[key]\n      }\n    }\n    return out\n  }\n)\n\n/**\n * Merge two records, retaining only the entries that exist in both records.\n *\n * @since 2.0.0\n */\nexport const intersection: {\n  <K1 extends string, A, B, C>(\n    that: ReadonlyRecord<K1, B>,\n    combine: (selfValue: A, thatValue: B) => C\n  ): <K0 extends string>(self: ReadonlyRecord<K0, A>) => Record<ReadonlyRecord.IntersectKeys<K0, K1>, C>\n  <K0 extends string, A, K1 extends string, B, C>(\n    self: ReadonlyRecord<K0, A>,\n    that: ReadonlyRecord<K1, B>,\n    combine: (selfValue: A, thatValue: B) => C\n  ): Record<ReadonlyRecord.IntersectKeys<K0, K1>, C>\n} = dual(\n  3,\n  <K0 extends string, A, K1 extends string, B, C>(\n    self: ReadonlyRecord<K0, A>,\n    that: ReadonlyRecord<K1, B>,\n    combine: (selfValue: A, thatValue: B) => C\n  ): Record<ReadonlyRecord.IntersectKeys<K0, K1>, C> => {\n    const out: Record<string, C> = empty()\n    if (isEmptyRecord(self) || isEmptyRecord(that)) {\n      return out\n    }\n    for (const key of keys(self)) {\n      if (has(that, key as any)) {\n        out[key] = combine(self[key], that[key as unknown as K1])\n      }\n    }\n    return out\n  }\n)\n\n/**\n * Merge two records, preserving only the entries that are unique to each record.\n *\n * @since 2.0.0\n */\nexport const difference: {\n  <K1 extends string, B>(\n    that: ReadonlyRecord<K1, B>\n  ): <K0 extends string, A>(self: ReadonlyRecord<K0, A>) => Record<K0 | K1, A | B>\n  <K0 extends string, A, K1 extends string, B>(\n    self: ReadonlyRecord<K0, A>,\n    that: ReadonlyRecord<K1, B>\n  ): Record<K0 | K1, A | B>\n} = dual(2, <K0 extends string, A, K1 extends string, B>(\n  self: ReadonlyRecord<K0, A>,\n  that: ReadonlyRecord<K1, B>\n): Record<K0 | K1, A | B> => {\n  if (isEmptyRecord(self)) {\n    return { ...that } as any\n  }\n  if (isEmptyRecord(that)) {\n    return { ...self } as any\n  }\n  const out = <Record<K0 | K1, A | B>> {}\n  for (const key of keys(self)) {\n    if (!has(that, key as any)) {\n      out[key] = self[key]\n    }\n  }\n  for (const key of keys(that)) {\n    if (!has(self, key as any)) {\n      out[key] = that[key]\n    }\n  }\n  return out\n})\n\n/**\n * Create an `Equivalence` for records using the provided `Equivalence` for values.\n *\n * @category instances\n * @since 2.0.0\n */\nexport const getEquivalence = <K extends string, A>(\n  equivalence: Equivalence<A>\n): Equivalence<ReadonlyRecord<K, A>> => {\n  const is = isSubrecordBy(equivalence)\n  return (self, that) => is(self, that) && is(that, self)\n}\n\n/**\n * Create a non-empty record from a single element.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const singleton = <K extends string | symbol, A>(key: K, value: A): Record<K, A> => ({\n  [key]: value\n} as any)\n\n/**\n * Returns the first entry that satisfies the specified\n * predicate, or `None` if no such entry exists.\n *\n * @example\n * ```ts\n * import { Record, Option } from \"effect\"\n *\n * const record = { a: 1, b: 2, c: 3 }\n * const result = Record.findFirst(record, (value, key) => value > 1 && key !== \"b\")\n * console.log(result) // Option.Some([\"c\", 3])\n * ```\n *\n * @category elements\n * @since 3.14.0\n */\nexport const findFirst: {\n  <K extends string | symbol, V, V2 extends V>(\n    refinement: (value: NoInfer<V>, key: NoInfer<K>) => value is V2\n  ): (self: ReadonlyRecord<K, V>) => Option.Option<[K, V2]>\n  <K extends string | symbol, V>(\n    predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean\n  ): (self: ReadonlyRecord<K, V>) => Option.Option<[K, V]>\n  <K extends string | symbol, V, V2 extends V>(\n    self: ReadonlyRecord<K, V>,\n    refinement: (value: NoInfer<V>, key: NoInfer<K>) => value is V2\n  ): Option.Option<[K, V2]>\n  <K extends string | symbol, V>(\n    self: ReadonlyRecord<K, V>,\n    predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean\n  ): Option.Option<[K, V]>\n} = dual(\n  2,\n  <K extends string | symbol, V>(self: ReadonlyRecord<K, V>, f: (value: V, key: K) => boolean) => {\n    const k = keys(self)\n    for (let i = 0; i < k.length; i++) {\n      const key = k[i]\n      if (f(self[key], key)) {\n        return Option.some([key, self[key]])\n      }\n    }\n    return Option.none()\n  }\n)\n"
  },
  {
    "path": "packages/effect/src/RedBlackTree.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { Chunk } from \"./Chunk.js\"\nimport type { Equal } from \"./Equal.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as RBT from \"./internal/redBlackTree.js\"\nimport * as RBTI from \"./internal/redBlackTree/iterator.js\"\nimport type { Option } from \"./Option.js\"\nimport type { Order } from \"./Order.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\n\nconst TypeId: unique symbol = RBT.RedBlackTreeTypeId as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category constants\n */\nexport const Direction = RBTI.Direction\n\n/**\n * A Red-Black Tree.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface RedBlackTree<in out Key, out Value> extends Iterable<[Key, Value]>, Equal, Pipeable, Inspectable {\n  readonly [TypeId]: {\n    readonly _Key: Types.Invariant<Key>\n    readonly _Value: Types.Covariant<Value>\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace RedBlackTree {\n  /**\n   * @since 2.0.0\n   */\n  export type Direction = number & {\n    readonly Direction: unique symbol\n  }\n}\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isRedBlackTree: {\n  <K, V>(u: Iterable<readonly [K, V]>): u is RedBlackTree<K, V>\n  (u: unknown): u is RedBlackTree<unknown, unknown>\n} = RBT.isRedBlackTree\n\n/**\n * Creates an empty `RedBlackTree`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: <K, V = never>(ord: Order<K>) => RedBlackTree<K, V> = RBT.empty\n\n/**\n * Creates a new `RedBlackTree` from an iterable collection of key/value pairs.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: {\n  <B>(ord: Order<B>): <K extends B, V>(entries: Iterable<readonly [K, V]>) => RedBlackTree<K, V>\n  <K extends B, V, B>(entries: Iterable<readonly [K, V]>, ord: Order<B>): RedBlackTree<K, V>\n} = RBT.fromIterable\n\n/**\n * Constructs a new `RedBlackTree` from the specified entries.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <K>(\n  ord: Order<K>\n) => <Entries extends Array<readonly [K, any]>>(\n  ...entries: Entries\n) => RedBlackTree<K, Entries[number] extends readonly [any, infer V] ? V : never> = RBT.make\n\n/**\n * Returns an iterator that points to the element at the specified index of the\n * tree.\n *\n * **Note**: The iterator will run through elements in order.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const at: {\n  (index: number): <K, V>(self: RedBlackTree<K, V>) => Iterable<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, index: number): Iterable<[K, V]>\n} = RBT.atForwards\n\n/**\n * Returns an iterator that points to the element at the specified index of the\n * tree.\n *\n * **Note**: The iterator will run through elements in reverse order.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const atReversed: {\n  (index: number): <K, V>(self: RedBlackTree<K, V>) => Iterable<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, index: number): Iterable<[K, V]>\n} = RBT.atBackwards\n\n/**\n * Finds all values in the tree associated with the specified key.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findAll: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => Chunk<V>\n  <K, V>(self: RedBlackTree<K, V>, key: K): Chunk<V>\n} = RBT.findAll\n\n/**\n * Finds the first value in the tree associated with the specified key, if it exists.\n *\n * @category elements\n * @since 2.0.0\n */\nexport const findFirst: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => Option<V>\n  <K, V>(self: RedBlackTree<K, V>, key: K): Option<V>\n} = RBT.findFirst\n\n/**\n * Returns the first entry in the tree, if it exists.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const first: <K, V>(self: RedBlackTree<K, V>) => Option<[K, V]> = RBT.first\n\n/**\n * Returns the element at the specified index within the tree or `None` if the\n * specified index does not exist.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const getAt: {\n  (index: number): <K, V>(self: RedBlackTree<K, V>) => Option<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, index: number): Option<[K, V]>\n} = RBT.getAt\n\n/**\n * Gets the `Order<K>` that the `RedBlackTree<K, V>` is using.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const getOrder: <K, V>(self: RedBlackTree<K, V>) => Order<K> = RBT.getOrder\n\n/**\n * Returns an iterator that traverse entries in order with keys greater than the\n * specified key.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const greaterThan: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => Iterable<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, key: K): Iterable<[K, V]>\n} = RBT.greaterThanForwards\n\n/**\n * Returns an iterator that traverse entries in reverse order with keys greater\n * than the specified key.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const greaterThanReversed: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => Iterable<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, key: K): Iterable<[K, V]>\n} = RBT.greaterThanBackwards\n\n/**\n * Returns an iterator that traverse entries in order with keys greater than or\n * equal to the specified key.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const greaterThanEqual: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => Iterable<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, key: K): Iterable<[K, V]>\n} = RBT.greaterThanEqualForwards\n\n/**\n * Returns an iterator that traverse entries in reverse order with keys greater\n * than or equal to the specified key.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const greaterThanEqualReversed: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => Iterable<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, key: K): Iterable<[K, V]>\n} = RBT.greaterThanEqualBackwards\n\n/**\n * Finds the item with key, if it exists.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const has: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => boolean\n  <K, V>(self: RedBlackTree<K, V>, key: K): boolean\n} = RBT.has\n\n/**\n * Insert a new item into the tree.\n *\n * @since 2.0.0\n */\nexport const insert: {\n  <K, V>(key: K, value: V): (self: RedBlackTree<K, V>) => RedBlackTree<K, V>\n  <K, V>(self: RedBlackTree<K, V>, key: K, value: V): RedBlackTree<K, V>\n} = RBT.insert\n\n/**\n * Get all the keys present in the tree in order.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const keys: <K, V>(self: RedBlackTree<K, V>) => IterableIterator<K> = RBT.keysForward\n\n/**\n * Get all the keys present in the tree in reverse order.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const keysReversed: <K, V>(self: RedBlackTree<K, V>) => IterableIterator<K> = RBT.keysBackward\n\n/**\n * Returns the last entry in the tree, if it exists.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const last: <K, V>(self: RedBlackTree<K, V>) => Option<[K, V]> = RBT.last\n\n/**\n * Returns an iterator that traverse entries in order with keys less than the\n * specified key.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const lessThan: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => Iterable<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, key: K): Iterable<[K, V]>\n} = RBT.lessThanForwards\n\n/**\n * Returns an iterator that traverse entries in reverse order with keys less\n * than the specified key.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const lessThanReversed: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => Iterable<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, key: K): Iterable<[K, V]>\n} = RBT.lessThanBackwards\n\n/**\n * Returns an iterator that traverse entries in order with keys less than or\n * equal to the specified key.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const lessThanEqual: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => Iterable<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, key: K): Iterable<[K, V]>\n} = RBT.lessThanEqualForwards\n\n/**\n * Returns an iterator that traverse entries in reverse order with keys less\n * than or equal to the specified key.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const lessThanEqualReversed: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => Iterable<[K, V]>\n  <K, V>(self: RedBlackTree<K, V>, key: K): Iterable<[K, V]>\n} = RBT.lessThanEqualBackwards\n\n/**\n * Execute the specified function for each node of the tree, in order.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const forEach: {\n  <K, V>(f: (key: K, value: V) => void): (self: RedBlackTree<K, V>) => void\n  <K, V>(self: RedBlackTree<K, V>, f: (key: K, value: V) => void): void\n} = RBT.forEach\n\n/**\n * Visit each node of the tree in order with key greater then or equal to max.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const forEachGreaterThanEqual: {\n  <K, V>(min: K, f: (key: K, value: V) => void): (self: RedBlackTree<K, V>) => void\n  <K, V>(self: RedBlackTree<K, V>, min: K, f: (key: K, value: V) => void): void\n} = RBT.forEachGreaterThanEqual\n\n/**\n * Visit each node of the tree in order with key lower then max.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const forEachLessThan: {\n  <K, V>(max: K, f: (key: K, value: V) => void): (self: RedBlackTree<K, V>) => void\n  <K, V>(self: RedBlackTree<K, V>, max: K, f: (key: K, value: V) => void): void\n} = RBT.forEachLessThan\n\n/**\n * Visit each node of the tree in order with key lower than max and greater\n * than or equal to min.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const forEachBetween: {\n  <K, V>(\n    options: {\n      readonly min: K\n      readonly max: K\n      readonly body: (key: K, value: V) => void\n    }\n  ): (self: RedBlackTree<K, V>) => void\n  <K, V>(\n    self: RedBlackTree<K, V>,\n    options: {\n      readonly min: K\n      readonly max: K\n      readonly body: (key: K, value: V) => void\n    }\n  ): void\n} = RBT.forEachBetween\n\n/**\n * Reduce a state over the entries of the tree.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const reduce: {\n  <Z, V, K>(zero: Z, f: (accumulator: Z, value: V, key: K) => Z): (self: RedBlackTree<K, V>) => Z\n  <Z, V, K>(self: RedBlackTree<K, V>, zero: Z, f: (accumulator: Z, value: V, key: K) => Z): Z\n} = RBT.reduce\n\n/**\n * Removes the entry with the specified key, if it exists.\n *\n * @since 2.0.0\n */\nexport const removeFirst: {\n  <K>(key: K): <V>(self: RedBlackTree<K, V>) => RedBlackTree<K, V>\n  <K, V>(self: RedBlackTree<K, V>, key: K): RedBlackTree<K, V>\n} = RBT.removeFirst\n\n/**\n * Traverse the tree in reverse order.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const reversed: <K, V>(self: RedBlackTree<K, V>) => Iterable<[K, V]> = RBT.reversed\n\n/**\n * Returns the size of the tree.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <K, V>(self: RedBlackTree<K, V>) => number = RBT.size\n\n/**\n * Get all values present in the tree in order.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const values: <K, V>(self: RedBlackTree<K, V>) => IterableIterator<V> = RBT.valuesForward\n\n/**\n * Get all values present in the tree in reverse order.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const valuesReversed: <K, V>(self: RedBlackTree<K, V>) => IterableIterator<V> = RBT.valuesBackward\n"
  },
  {
    "path": "packages/effect/src/Redacted.ts",
    "content": "/**\n * The Redacted module provides functionality for handling sensitive information\n * securely within your application. By using the `Redacted` data type, you can\n * ensure that sensitive values are not accidentally exposed in logs or error\n * messages.\n *\n * @since 3.3.0\n */\nimport type * as Equal from \"./Equal.js\"\nimport * as Equivalence from \"./Equivalence.js\"\nimport * as redacted_ from \"./internal/redacted.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Covariant } from \"./Types.js\"\n\n/**\n * @since 3.3.0\n * @category symbols\n */\nexport const RedactedTypeId: unique symbol = redacted_.RedactedTypeId\n\n/**\n * @since 3.3.0\n * @category symbols\n */\nexport type RedactedTypeId = typeof RedactedTypeId\n\n/**\n * @since 3.3.0\n * @category models\n */\nexport interface Redacted<out A = string> extends Redacted.Variance<A>, Equal.Equal, Pipeable {\n}\n\n/**\n * @since 3.3.0\n */\nexport declare namespace Redacted {\n  /**\n   * @since 3.3.0\n   * @category models\n   */\n  export interface Variance<out A> {\n    readonly [RedactedTypeId]: {\n      readonly _A: Covariant<A>\n    }\n  }\n\n  /**\n   * @since 3.3.0\n   * @category type-level\n   */\n  export type Value<T extends Redacted<any>> = [T] extends [Redacted<infer _A>] ? _A : never\n}\n\n/**\n * @since 3.3.0\n * @category refinements\n */\nexport const isRedacted: (u: unknown) => u is Redacted<unknown> = redacted_.isRedacted\n\n/**\n * This function creates a `Redacted<A>` instance from a given value `A`,\n * securely hiding its content.\n *\n * @example\n * ```ts\n * import { Redacted } from \"effect\"\n *\n * const API_KEY = Redacted.make(\"1234567890\")\n * ```\n *\n * @since 3.3.0\n * @category constructors\n */\nexport const make: <A>(value: A) => Redacted<A> = redacted_.make\n\n/**\n * Retrieves the original value from a `Redacted` instance. Use this function\n * with caution, as it exposes the sensitive data.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Redacted } from \"effect\"\n *\n * const API_KEY = Redacted.make(\"1234567890\")\n *\n * assert.equal(Redacted.value(API_KEY), \"1234567890\")\n * ```\n *\n * @since 3.3.0\n * @category getters\n */\nexport const value: <A>(self: Redacted<A>) => A = redacted_.value\n\n/**\n * Erases the underlying value of a `Redacted` instance, rendering it unusable.\n * This function is intended to ensure that sensitive data does not remain in\n * memory longer than necessary.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Redacted } from \"effect\"\n *\n * const API_KEY = Redacted.make(\"1234567890\")\n *\n * assert.equal(Redacted.value(API_KEY), \"1234567890\")\n *\n * Redacted.unsafeWipe(API_KEY)\n *\n * assert.throws(() => Redacted.value(API_KEY), new Error(\"Unable to get redacted value\"))\n * ```\n *\n * @since 3.3.0\n * @category unsafe\n */\nexport const unsafeWipe: <A>(self: Redacted<A>) => boolean = redacted_.unsafeWipe\n\n/**\n * Generates an equivalence relation for `Redacted<A>` values based on an\n * equivalence relation for the underlying values `A`. This function is useful\n * for comparing `Redacted` instances without exposing their contents.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Redacted, Equivalence } from \"effect\"\n *\n * const API_KEY1 = Redacted.make(\"1234567890\")\n * const API_KEY2 = Redacted.make(\"1-34567890\")\n * const API_KEY3 = Redacted.make(\"1234567890\")\n *\n * const equivalence = Redacted.getEquivalence(Equivalence.string)\n *\n * assert.equal(equivalence(API_KEY1, API_KEY2), false)\n * assert.equal(equivalence(API_KEY1, API_KEY3), true)\n * ```\n *\n * @category equivalence\n * @since 3.3.0\n */\nexport const getEquivalence = <A>(isEquivalent: Equivalence.Equivalence<A>): Equivalence.Equivalence<Redacted<A>> =>\n  Equivalence.make((x, y) => isEquivalent(value(x), value(y)))\n"
  },
  {
    "path": "packages/effect/src/Ref.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/ref.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Readable from \"./Readable.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const RefTypeId: unique symbol = internal.RefTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type RefTypeId = typeof RefTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Ref<in out A> extends Ref.Variance<A>, Effect.Effect<A>, Readable.Readable<A> {\n  modify<B>(f: (a: A) => readonly [B, A]): Effect.Effect<B>\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: RefUnify<this>\n  readonly [Unify.ignoreSymbol]?: RefUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface RefUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  Ref?: () => Extract<A[Unify.typeSymbol], Ref<any>>\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface RefUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport declare namespace Ref {\n  /**\n   * @since 2.0.0\n   */\n  export interface Variance<in out A> {\n    readonly [RefTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A>(value: A) => Effect.Effect<Ref<A>> = internal.make\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const get: <A>(self: Ref<A>) => Effect.Effect<A> = internal.get\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndSet: {\n  <A>(value: A): (self: Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref<A>, value: A): Effect.Effect<A>\n} = internal.getAndSet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdate: {\n  <A>(f: (a: A) => A): (self: Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref<A>, f: (a: A) => A): Effect.Effect<A>\n} = internal.getAndUpdate\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdateSome: {\n  <A>(pf: (a: A) => Option.Option<A>): (self: Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<A>\n} = internal.getAndUpdateSome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modify: {\n  <A, B>(f: (a: A) => readonly [B, A]): (self: Ref<A>) => Effect.Effect<B>\n  <A, B>(self: Ref<A>, f: (a: A) => readonly [B, A]): Effect.Effect<B>\n} = internal.modify\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modifySome: {\n  <B, A>(fallback: B, pf: (a: A) => Option.Option<readonly [B, A]>): (self: Ref<A>) => Effect.Effect<B>\n  <A, B>(self: Ref<A>, fallback: B, pf: (a: A) => Option.Option<readonly [B, A]>): Effect.Effect<B>\n} = internal.modifySome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const set: {\n  <A>(value: A): (self: Ref<A>) => Effect.Effect<void>\n  <A>(self: Ref<A>, value: A): Effect.Effect<void>\n} = internal.set\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const setAndGet: {\n  <A>(value: A): (self: Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref<A>, value: A): Effect.Effect<A>\n} = internal.setAndGet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const update: {\n  <A>(f: (a: A) => A): (self: Ref<A>) => Effect.Effect<void>\n  <A>(self: Ref<A>, f: (a: A) => A): Effect.Effect<void>\n} = internal.update\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateAndGet: {\n  <A>(f: (a: A) => A): (self: Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref<A>, f: (a: A) => A): Effect.Effect<A>\n} = internal.updateAndGet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSome: {\n  <A>(f: (a: A) => Option.Option<A>): (self: Ref<A>) => Effect.Effect<void>\n  <A>(self: Ref<A>, f: (a: A) => Option.Option<A>): Effect.Effect<void>\n} = internal.updateSome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSomeAndGet: {\n  <A>(pf: (a: A) => Option.Option<A>): (self: Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<A>\n} = internal.updateSomeAndGet\n\n/**\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeMake: <A>(value: A) => Ref<A> = internal.unsafeMake\n"
  },
  {
    "path": "packages/effect/src/RegExp.ts",
    "content": "/**\n * This module provides utility functions for working with RegExp in TypeScript.\n *\n * @since 2.0.0\n */\nimport * as predicate from \"./Predicate.js\"\n\n/**\n * Tests if a value is a `RegExp`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { RegExp } from \"effect\"\n *\n * assert.deepStrictEqual(RegExp.isRegExp(/a/), true)\n * assert.deepStrictEqual(RegExp.isRegExp(\"a\"), false)\n * ```\n *\n * @category guards\n * @since 3.9.0\n */\nexport const isRegExp: (input: unknown) => input is RegExp = predicate.isRegExp\n\n/**\n * Escapes special characters in a regular expression pattern.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { RegExp } from \"effect\"\n *\n * assert.deepStrictEqual(RegExp.escape(\"a*b\"), \"a\\\\*b\")\n * ```\n *\n * @since 2.0.0\n */\nexport const escape = (string: string): string => string.replace(/[/\\\\^$*+?.()|[\\]{}]/g, \"\\\\$&\")\n"
  },
  {
    "path": "packages/effect/src/Reloadable.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/reloadable.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type * as Schedule from \"./Schedule.js\"\nimport type * as ScopedRef from \"./ScopedRef.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ReloadableTypeId: unique symbol = internal.ReloadableTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ReloadableTypeId = typeof ReloadableTypeId\n\n/**\n * A `Reloadable` is an implementation of some service that can be dynamically\n * reloaded, or swapped out for another implementation on-the-fly.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Reloadable<in out A> extends Reloadable.Variance<A> {\n  /**\n   * @internal\n   */\n  readonly scopedRef: ScopedRef.ScopedRef<A>\n  /**\n   * @internal\n   */\n  readonly reload: Effect.Effect<void, unknown>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Reloadable {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A> {\n    readonly [ReloadableTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * Makes a new reloadable service from a layer that describes the construction\n * of a static service. The service is automatically reloaded according to the\n * provided schedule.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const auto: <I, S, E, In, R>(\n  tag: Context.Tag<I, S>,\n  options: { readonly layer: Layer.Layer<I, E, In>; readonly schedule: Schedule.Schedule<unknown, unknown, R> }\n) => Layer.Layer<Reloadable<I>, E, R | In> = internal.auto\n\n/**\n * Makes a new reloadable service from a layer that describes the construction\n * of a static service. The service is automatically reloaded according to a\n * schedule, which is extracted from the input to the layer.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const autoFromConfig: <I, S, E, In, R>(\n  tag: Context.Tag<I, S>,\n  options: {\n    readonly layer: Layer.Layer<I, E, In>\n    readonly scheduleFromConfig: (context: Context.Context<In>) => Schedule.Schedule<unknown, unknown, R>\n  }\n) => Layer.Layer<Reloadable<I>, E, R | In> = internal.autoFromConfig\n\n/**\n * Retrieves the current version of the reloadable service.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const get: <I, S>(tag: Context.Tag<I, S>) => Effect.Effect<S, never, Reloadable<I>> = internal.get\n\n/**\n * Makes a new reloadable service from a layer that describes the construction\n * of a static service.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const manual: <I, S, In, E>(\n  tag: Context.Tag<I, S>,\n  options: { readonly layer: Layer.Layer<I, E, In> }\n) => Layer.Layer<Reloadable<I>, E, In> = internal.manual\n\n/**\n * Reloads the specified service.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const reload: <I, S>(tag: Context.Tag<I, S>) => Effect.Effect<void, unknown, Reloadable<I>> = internal.reload\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const tag: <I, S>(tag: Context.Tag<I, S>) => Context.Tag<Reloadable<I>, Reloadable<S>> = internal.reloadableTag\n\n/**\n * Forks the reload of the service in the background, ignoring any errors.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const reloadFork: <I, S>(tag: Context.Tag<I, S>) => Effect.Effect<void, unknown, Reloadable<I>> =\n  internal.reloadFork\n"
  },
  {
    "path": "packages/effect/src/Request.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as _Cache from \"./Cache.js\"\nimport type { Cause } from \"./Cause.js\"\nimport type { Deferred } from \"./Deferred.js\"\nimport type { DurationInput } from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type { FiberId } from \"./FiberId.js\"\nimport * as RequestBlock_ from \"./internal/blockedRequests.js\"\nimport * as cache from \"./internal/cache.js\"\nimport * as core from \"./internal/core.js\"\nimport * as fiberRuntime from \"./internal/fiberRuntime.js\"\nimport * as internal from \"./internal/request.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const RequestTypeId: unique symbol = internal.RequestTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type RequestTypeId = typeof RequestTypeId\n\n/**\n * A `Request<A, E>` is a request from a data source for a value of type `A`\n * that may fail with an `E`.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Request<out A, out E = never> extends Request.Variance<A, E> {}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Request {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out A, out E> {\n    readonly [RequestTypeId]: {\n      readonly _A: Types.Covariant<A>\n      readonly _E: Types.Covariant<E>\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Constructor<R extends Request<any, any>, T extends keyof R = never> {\n    (args: Omit<R, T | keyof (Request.Variance<Request.Success<R>, Request.Error<R>>)>): R\n  }\n\n  /**\n   * A utility type to extract the error type from a `Request`.\n   *\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type Error<T extends Request<any, any>> = [T] extends [Request<infer _A, infer _E>] ? _E : never\n\n  /**\n   * A utility type to extract the value type from a `Request`.\n   *\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type Success<T extends Request<any, any>> = [T] extends [Request<infer _A, infer _E>] ? _A : never\n\n  /**\n   * A utility type to extract the result type from a `Request`.\n   *\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type Result<T extends Request<any, any>> = T extends Request<infer A, infer E> ? Exit.Exit<A, E> : never\n\n  /**\n   * A utility type to extract the optional result type from a `Request`.\n   *\n   * @since 2.0.0\n   * @category type-level\n   */\n  export type OptionalResult<T extends Request<any, any>> = T extends Request<infer A, infer E>\n    ? Exit.Exit<Option.Option<A>, E>\n    : never\n}\n\n/**\n * Returns `true` if the specified value is a `Request`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isRequest: (u: unknown) => u is Request<unknown, unknown> = internal.isRequest\n\n/**\n * Constructs a new `Request`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const of: <R extends Request<any, any>>() => Request.Constructor<R> = internal.of\n\n/**\n * Constructs a new `Request`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const tagged: <R extends Request<any, any> & { _tag: string }>(\n  tag: R[\"_tag\"]\n) => Request.Constructor<R, \"_tag\"> = internal.tagged\n\n/**\n * Provides a constructor for a Request Class.\n *\n * @example\n * ```ts\n * import { Request } from \"effect\"\n *\n * type Success = string\n * type Error = never\n *\n * class MyRequest extends Request.Class<Success, Error, {\n *   readonly id: string\n * }> {}\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const Class: new<Success, Error, A extends Record<string, any>>(\n  args: Types.Equals<Omit<A, keyof Request<unknown, unknown>>, {}> extends true ? void\n    : { readonly [P in keyof A as P extends keyof Request<unknown, unknown> ? never : P]: A[P] }\n) => Request<Success, Error> & Readonly<A> = internal.Class as any\n\n/**\n * Provides a Tagged constructor for a Request Class.\n *\n * @example\n * ```ts\n * import { Request } from \"effect\"\n *\n * type Success = string\n * type Error = never\n *\n * class MyRequest extends Request.TaggedClass(\"MyRequest\")<Success, Error, {\n *   readonly name: string\n * }> {}\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const TaggedClass: <Tag extends string>(\n  tag: Tag\n) => new<Success, Error, A extends Record<string, any>>(\n  args: Types.Equals<Omit<A, keyof Request<unknown, unknown>>, {}> extends true ? void\n    : { readonly [P in keyof A as P extends \"_tag\" | keyof Request<unknown, unknown> ? never : P]: A[P] }\n) => Request<Success, Error> & Readonly<A> & { readonly _tag: Tag } = internal.TaggedClass as any\n\n/**\n * Complete a `Request` with the specified result.\n *\n * @since 2.0.0\n * @category request completion\n */\nexport const complete: {\n  <A extends Request<any, any>>(result: Request.Result<A>): (self: A) => Effect.Effect<void>\n  <A extends Request<any, any>>(self: A, result: Request.Result<A>): Effect.Effect<void>\n} = internal.complete\n\n/**\n * Interrupts the child effect when requests are no longer needed\n *\n * @since 2.0.0\n * @category request completion\n */\nexport const interruptWhenPossible: {\n  (all: Iterable<Request<any, any>>): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<void, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, all: Iterable<Request<any, any>>): Effect.Effect<void, E, R>\n} = fiberRuntime.interruptWhenPossible\n\n/**\n * Complete a `Request` with the specified effectful computation, failing the\n * request with the error from the effect workflow if it fails, and completing\n * the request with the value of the effect workflow if it succeeds.\n *\n * @since 2.0.0\n * @category request completion\n */\nexport const completeEffect: {\n  <A extends Request<any, any>, R>(\n    effect: Effect.Effect<Request.Success<A>, Request.Error<A>, R>\n  ): (self: A) => Effect.Effect<void, never, R>\n  <A extends Request<any, any>, R>(\n    self: A,\n    effect: Effect.Effect<Request.Success<A>, Request.Error<A>, R>\n  ): Effect.Effect<void, never, R>\n} = internal.completeEffect\n\n/**\n * Complete a `Request` with the specified error.\n *\n * @since 2.0.0\n * @category request completion\n */\nexport const fail: {\n  <A extends Request<any, any>>(error: Request.Error<A>): (self: A) => Effect.Effect<void>\n  <A extends Request<any, any>>(self: A, error: Request.Error<A>): Effect.Effect<void>\n} = internal.fail\n\n/**\n * Complete a `Request` with the specified cause.\n *\n * @since 2.0.0\n * @category request completion\n */\nexport const failCause: {\n  <A extends Request<any, any>>(cause: Cause<Request.Error<A>>): (self: A) => Effect.Effect<void>\n  <A extends Request<any, any>>(self: A, cause: Cause<Request.Error<A>>): Effect.Effect<void>\n} = internal.failCause\n\n/**\n * Complete a `Request` with the specified value.\n *\n * @since 2.0.0\n * @category request completion\n */\nexport const succeed: {\n  <A extends Request<any, any>>(value: Request.Success<A>): (self: A) => Effect.Effect<void>\n  <A extends Request<any, any>>(self: A, value: Request.Success<A>): Effect.Effect<void>\n} = internal.succeed\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface Listeners {\n  readonly count: number\n  readonly observers: Set<(count: number) => void>\n  interrupted: boolean\n  addObserver(f: (count: number) => void): void\n  removeObserver(f: (count: number) => void): void\n  increment(): void\n  decrement(): void\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface Cache extends\n  _Cache.ConsumerCache<Request<any, any>, {\n    listeners: Listeners\n    handle: Deferred<unknown, unknown>\n  }>\n{}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport const makeCache = (\n  options: {\n    readonly capacity: number\n    readonly timeToLive: DurationInput\n  }\n): Effect.Effect<Cache> =>\n  cache.make({\n    ...options,\n    lookup: () =>\n      core.map(core.deferredMake<unknown, unknown>(), (handle) => ({ listeners: new internal.Listeners(), handle }))\n  })\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const EntryTypeId: unique symbol = Symbol.for(\"effect/RequestBlock.Entry\")\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type EntryTypeId = typeof EntryTypeId\n\n/**\n * A `Entry<A>` keeps track of a request of type `A` along with a\n * `Ref` containing the result of the request, existentially hiding the result\n * type. This is used internally by the library to support data sources that\n * return different result types for different requests while guaranteeing that\n * results will be of the type requested.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Entry<out R> extends Entry.Variance<R> {\n  readonly request: R\n  readonly result: Deferred<\n    [R] extends [Request<infer _A, infer _E>] ? _A : never,\n    [R] extends [Request<infer _A, infer _E>] ? _E : never\n  >\n  readonly listeners: Listeners\n  readonly ownerId: FiberId\n  readonly state: {\n    completed: boolean\n  }\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport declare namespace Entry {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out R> {\n    readonly [EntryTypeId]: {\n      readonly _R: Types.Covariant<R>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category guards\n */\nexport const isEntry = RequestBlock_.isEntry\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const makeEntry = RequestBlock_.makeEntry\n"
  },
  {
    "path": "packages/effect/src/RequestBlock.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as RequestBlock_ from \"./internal/blockedRequests.js\"\nimport type * as Request from \"./Request.js\"\nimport type * as RequestResolver from \"./RequestResolver.js\"\n\n/**\n * `RequestBlock` captures a collection of blocked requests as a data\n * structure. By doing this the library is able to preserve information about\n * which requests must be performed sequentially and which can be performed in\n * parallel, allowing for maximum possible batching and pipelining while\n * preserving ordering guarantees.\n *\n * @since 2.0.0\n * @category models\n */\nexport type RequestBlock = Empty | Par | Seq | Single\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport declare namespace RequestBlock {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Reducer<in out Z> {\n    emptyCase(): Z\n    parCase(left: Z, right: Z): Z\n    singleCase(\n      dataSource: RequestResolver.RequestResolver<unknown>,\n      blockedRequest: Request.Entry<unknown>\n    ): Z\n    seqCase(left: Z, right: Z): Z\n  }\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Empty {\n  readonly _tag: \"Empty\"\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Par {\n  readonly _tag: \"Par\"\n  readonly left: RequestBlock\n  readonly right: RequestBlock\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Seq {\n  readonly _tag: \"Seq\"\n  readonly left: RequestBlock\n  readonly right: RequestBlock\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Single {\n  readonly _tag: \"Single\"\n  readonly dataSource: RequestResolver.RequestResolver<unknown>\n  readonly blockedRequest: Request.Entry<unknown>\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const single: <A>(\n  dataSource: RequestResolver.RequestResolver<A>,\n  blockedRequest: Request.Entry<A>\n) => RequestBlock = RequestBlock_.single\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: RequestBlock = RequestBlock_.empty\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const mapRequestResolvers: <A>(\n  self: RequestBlock,\n  f: (dataSource: RequestResolver.RequestResolver<A>) => RequestResolver.RequestResolver<A>\n) => RequestBlock = RequestBlock_.mapRequestResolvers\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const parallel: (self: RequestBlock, that: RequestBlock) => RequestBlock = RequestBlock_.par\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const reduce: <Z>(self: RequestBlock, reducer: RequestBlock.Reducer<Z>) => Z = RequestBlock_.reduce\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const sequential: (self: RequestBlock, that: RequestBlock) => RequestBlock = RequestBlock_.seq\n"
  },
  {
    "path": "packages/effect/src/RequestResolver.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport type { NonEmptyArray } from \"./Array.js\"\nimport * as Context from \"./Context.js\"\nimport * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type * as Equal from \"./Equal.js\"\nimport type { FiberRef } from \"./FiberRef.js\"\nimport * as core from \"./internal/core.js\"\nimport * as internal from \"./internal/dataSource.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Request from \"./Request.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const RequestResolverTypeId: unique symbol = core.RequestResolverTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type RequestResolverTypeId = typeof RequestResolverTypeId\n\n/**\n * The `RequestResolver<A, R>` interface requires an environment `R` and handles\n * the execution of requests of type `A`.\n *\n * Implementations must provide a `runAll` method, which processes a collection\n * of requests and produces an effect that fulfills these requests. Requests are\n * organized into a `Array<Array<A>>`, where the outer `Array` groups requests\n * into batches that are executed sequentially, and each inner `Array` contains\n * requests that can be executed in parallel. This structure allows\n * implementations to analyze all incoming requests collectively and optimize\n * query execution accordingly.\n *\n * Implementations are typically specialized for a subtype of `Request<A, E>`.\n * However, they are not strictly limited to these subtypes as long as they can\n * map any given request type to `Request<A, E>`. Implementations should inspect\n * the collection of requests to identify the needed information and execute the\n * corresponding queries. It is imperative that implementations resolve all the\n * requests they receive. Failing to do so will lead to a `QueryFailure` error\n * during query execution.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface RequestResolver<in A, out R = never> extends RequestResolver.Variance<A, R>, Equal.Equal, Pipeable {\n  /**\n   * Execute a collection of requests. The outer `Array` represents batches\n   * of requests that must be performed sequentially. The inner `Array`\n   * represents a batch of requests that can be performed in parallel.\n   */\n  runAll(requests: Array<Array<Request.Entry<A>>>): Effect.Effect<void, never, R>\n\n  /**\n   * Identify the data source using the specific identifier\n   */\n  identified(...identifiers: Array<unknown>): RequestResolver<A, R>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace RequestResolver {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in A, out R> {\n    readonly [RequestResolverTypeId]: {\n      readonly _A: Types.Contravariant<A>\n      readonly _R: Types.Covariant<R>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const contextFromEffect = <R, A extends Request.Request<any, any>>(self: RequestResolver<A, R>) =>\n  Effect.contextWith((_: Context.Context<R>) => provideContext(self, _))\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const contextFromServices =\n  <Services extends Array<Context.Tag<any, any>>>(...services: Services) =>\n  <R, A extends Request.Request<any, any>>(\n    self: RequestResolver<A, R>\n  ): Effect.Effect<\n    RequestResolver<A, Exclude<R, { [k in keyof Services]: Effect.Effect.Context<Services[k]> }[number]>>,\n    never,\n    { [k in keyof Services]: Effect.Effect.Context<Services[k]> }[number]\n  > => Effect.contextWith((_) => provideContext(self as any, Context.pick(...services)(_ as any)))\n\n/**\n * Returns `true` if the specified value is a `RequestResolver`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isRequestResolver: (u: unknown) => u is RequestResolver<unknown, unknown> = core.isRequestResolver\n\n/**\n * Constructs a data source with the specified identifier and method to run\n * requests.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A, R>(\n  runAll: (requests: Array<Array<A>>) => Effect.Effect<void, never, R>\n) => RequestResolver<A, R> = internal.make\n\n/**\n * Constructs a data source with the specified identifier and method to run\n * requests.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeWithEntry: <A, R>(\n  runAll: (requests: Array<Array<Request.Entry<A>>>) => Effect.Effect<void, never, R>\n) => RequestResolver<A, R> = internal.makeWithEntry\n\n/**\n * Constructs a data source from a function taking a collection of requests.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeBatched: <A extends Request.Request<any, any>, R>(\n  run: (requests: NonEmptyArray<A>) => Effect.Effect<void, never, R>\n) => RequestResolver<A, R> = internal.makeBatched\n\n/**\n * A data source aspect that executes requests between two effects, `before`\n * and `after`, where the result of `before` can be used by `after`.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const around: {\n  <A2, R2, X, R3>(\n    before: Effect.Effect<A2, never, R2>,\n    after: (a: A2) => Effect.Effect<X, never, R3>\n  ): <A, R>(self: RequestResolver<A, R>) => RequestResolver<A, R2 | R3 | R>\n  <A, R, A2, R2, X, R3>(\n    self: RequestResolver<A, R>,\n    before: Effect.Effect<A2, never, R2>,\n    after: (a: A2) => Effect.Effect<X, never, R3>\n  ): RequestResolver<A, R | R2 | R3>\n} = internal.around\n\n/**\n * A data source aspect that executes requests between two effects, `before`\n * and `after`, where the result of `before` can be used by `after`.\n *\n * The `before` and `after` effects are provided with the requests being executed.\n *\n * @since 2.0.0\n * @category combinators\n * @example\n * ```ts\n * import { Effect, Request, RequestResolver } from \"effect\"\n *\n * interface GetUserById extends Request.Request<unknown> {\n *   readonly id: number\n * }\n *\n * const resolver = RequestResolver.fromFunction(\n *   (request: GetUserById) => ({ id: request.id, name: \"John\" })\n * )\n *\n * RequestResolver.aroundRequests(\n *   resolver,\n *   (requests) => Effect.log(`got ${requests.length} requests`),\n *   (requests, _) => Effect.log(`finised running ${requests.length} requests`)\n * )\n * ```\n */\nexport const aroundRequests: {\n  <A, A2, R2, X, R3>(\n    before: (requests: ReadonlyArray<Types.NoInfer<A>>) => Effect.Effect<A2, never, R2>,\n    after: (requests: ReadonlyArray<Types.NoInfer<A>>, _: A2) => Effect.Effect<X, never, R3>\n  ): <R>(self: RequestResolver<A, R>) => RequestResolver<A, R2 | R3 | R>\n  <A, R, A2, R2, X, R3>(\n    self: RequestResolver<A, R>,\n    before: (requests: ReadonlyArray<Types.NoInfer<A>>) => Effect.Effect<A2, never, R2>,\n    after: (requests: ReadonlyArray<Types.NoInfer<A>>, _: A2) => Effect.Effect<X, never, R3>\n  ): RequestResolver<A, R | R2 | R3>\n} = internal.aroundRequests\n\n/**\n * Returns a data source that executes at most `n` requests in parallel.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const batchN: {\n  (n: number): <A, R>(self: RequestResolver<A, R>) => RequestResolver<A, R>\n  <A, R>(self: RequestResolver<A, R>, n: number): RequestResolver<A, R>\n} = internal.batchN\n\n/**\n * Provides this data source with part of its required context.\n *\n * @since 2.0.0\n * @category context\n */\nexport const mapInputContext: {\n  <R0, R>(\n    f: (context: Context.Context<R0>) => Context.Context<R>\n  ): <A extends Request.Request<any, any>>(self: RequestResolver<A, R>) => RequestResolver<A, R0>\n  <R, A extends Request.Request<any, any>, R0>(\n    self: RequestResolver<A, R>,\n    f: (context: Context.Context<R0>) => Context.Context<R>\n  ): RequestResolver<A, R0>\n} = internal.mapInputContext\n\n/**\n * Returns a new data source that executes requests of type `C` using the\n * specified function to transform `C` requests into requests that either this\n * data source or that data source can execute.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const eitherWith: {\n  <A extends Request.Request<any, any>, R2, B extends Request.Request<any, any>, C extends Request.Request<any, any>>(\n    that: RequestResolver<B, R2>,\n    f: (_: Request.Entry<C>) => Either.Either<Request.Entry<B>, Request.Entry<A>>\n  ): <R>(self: RequestResolver<A, R>) => RequestResolver<C, R2 | R>\n  <\n    R,\n    A extends Request.Request<any, any>,\n    R2,\n    B extends Request.Request<any, any>,\n    C extends Request.Request<any, any>\n  >(\n    self: RequestResolver<A, R>,\n    that: RequestResolver<B, R2>,\n    f: (_: Request.Entry<C>) => Either.Either<Request.Entry<B>, Request.Entry<A>>\n  ): RequestResolver<C, R | R2>\n} = internal.eitherWith\n\n/**\n * Constructs a data source from a pure function.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromFunction: <A extends Request.Request<any>>(\n  f: (request: A) => Request.Request.Success<A>\n) => RequestResolver<A> = internal.fromFunction\n\n/**\n * Constructs a data source from a pure function that takes a list of requests\n * and returns a list of results of the same size. Each item in the result\n * list must correspond to the item at the same index in the request list.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromFunctionBatched: <A extends Request.Request<any>>(\n  f: (chunk: NonEmptyArray<A>) => Iterable<Request.Request.Success<A>>\n) => RequestResolver<A> = internal.fromFunctionBatched\n\n/**\n * Constructs a data source from an effectual function.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEffect: <R, A extends Request.Request<any, any>>(\n  f: (a: A) => Effect.Effect<Request.Request.Success<A>, Request.Request.Error<A>, R>\n) => RequestResolver<A, R> = internal.fromEffect\n\n/**\n * Constructs a data source from a list of tags paired to functions, that takes\n * a list of requests and returns a list of results of the same size. Each item\n * in the result list must correspond to the item at the same index in the\n * request list.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEffectTagged: <A extends Request.Request<any, any> & { readonly _tag: string }>() => <\n  Fns extends {\n    readonly [Tag in A[\"_tag\"]]: [Extract<A, { readonly _tag: Tag }>] extends [infer Req]\n      ? Req extends Request.Request<infer ReqA, infer ReqE>\n        ? (requests: Array<Req>) => Effect.Effect<Iterable<ReqA>, ReqE, any>\n      : never\n      : never\n  }\n>(\n  fns: Fns\n) => RequestResolver<A, ReturnType<Fns[keyof Fns]> extends Effect.Effect<infer _A, infer _E, infer R> ? R : never> =\n  internal.fromEffectTagged\n\n/**\n * A data source that never executes requests.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const never: RequestResolver<never> = internal.never\n\n/**\n * Provides this data source with its required context.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideContext: {\n  <R>(\n    context: Context.Context<R>\n  ): <A extends Request.Request<any, any>>(self: RequestResolver<A, R>) => RequestResolver<A>\n  <R, A extends Request.Request<any, any>>(\n    self: RequestResolver<A, R>,\n    context: Context.Context<R>\n  ): RequestResolver<A>\n} = internal.provideContext\n\n/**\n * Returns a new data source that executes requests by sending them to this\n * data source and that data source, returning the results from the first data\n * source to complete and safely interrupting the loser.\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const race: {\n  <A2 extends Request.Request<any, any>, R2>(\n    that: RequestResolver<A2, R2>\n  ): <A extends Request.Request<any, any>, R>(self: RequestResolver<A, R>) => RequestResolver<A2 | A, R2 | R>\n  <A extends Request.Request<any, any>, R, A2 extends Request.Request<any, any>, R2>(\n    self: RequestResolver<A, R>,\n    that: RequestResolver<A2, R2>\n  ): RequestResolver<A | A2, R | R2>\n} = internal.race\n\n/**\n * Returns a new data source with a localized FiberRef\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const locally: {\n  <A>(\n    self: FiberRef<A>,\n    value: A\n  ): <R, B extends Request.Request<any, any>>(use: RequestResolver<B, R>) => RequestResolver<B, R>\n  <R, B extends Request.Request<any, any>, A>(\n    use: RequestResolver<B, R>,\n    self: FiberRef<A>,\n    value: A\n  ): RequestResolver<B, R>\n} = core.resolverLocally\n"
  },
  {
    "path": "packages/effect/src/Resource.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport * as internal from \"./internal/resource.js\"\nimport type * as Schedule from \"./Schedule.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as ScopedRef from \"./ScopedRef.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ResourceTypeId: unique symbol = internal.ResourceTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ResourceTypeId = typeof ResourceTypeId\n\n/**\n * A `Resource` is a possibly resourceful value that is loaded into memory, and\n * which can be refreshed either manually or automatically.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Resource<in out A, in out E = never> extends Effect.Effect<A, E>, Resource.Variance<A, E> {\n  /** @internal */\n  readonly scopedRef: ScopedRef.ScopedRef<Exit.Exit<A, E>>\n  /** @internal */\n  readonly acquire: Effect.Effect<A, E, Scope.Scope>\n\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: ResourceUnify<this>\n  readonly [Unify.ignoreSymbol]?: ResourceUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.9.0\n */\nexport interface ResourceUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  Resource?: () => Extract<A[Unify.typeSymbol], Resource<any, any>>\n}\n\n/**\n * @category models\n * @since 3.9.0\n */\nexport interface ResourceUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Resource {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A, in out E> {\n    readonly [ResourceTypeId]: {\n      _A: Types.Invariant<A>\n      _E: Types.Invariant<E>\n    }\n  }\n}\n\n/**\n * Creates a new `Resource` value that is automatically refreshed according to\n * the specified policy. Note that error retrying is not performed\n * automatically, so if you want to retry on errors, you should first apply\n * retry policies to the acquisition effect before passing it to this\n * constructor.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const auto: <A, E, R, Out, R2>(\n  acquire: Effect.Effect<A, E, R>,\n  policy: Schedule.Schedule<Out, unknown, R2>\n) => Effect.Effect<Resource<A, E>, never, R | R2 | Scope.Scope> = internal.auto\n\n/**\n * Retrieves the current value stored in the cache.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const get: <A, E>(self: Resource<A, E>) => Effect.Effect<A, E> = internal.get\n\n/**\n * Creates a new `Resource` value that must be manually refreshed by calling\n * the refresh method. Note that error retrying is not performed\n * automatically, so if you want to retry on errors, you should first apply\n * retry policies to the acquisition effect before passing it to this\n * constructor.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const manual: <A, E, R>(\n  acquire: Effect.Effect<A, E, R>\n) => Effect.Effect<Resource<A, E>, never, Scope.Scope | R> = internal.manual\n\n/**\n * Refreshes the cache. This method will not return until either the refresh\n * is successful, or the refresh operation fails.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const refresh: <A, E>(self: Resource<A, E>) => Effect.Effect<void, E> = internal.refresh\n"
  },
  {
    "path": "packages/effect/src/Runtime.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type { Cause } from \"./Cause.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport type * as FiberRef from \"./FiberRef.js\"\nimport type * as FiberRefs from \"./FiberRefs.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as internal from \"./internal/runtime.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as RuntimeFlags from \"./RuntimeFlags.js\"\nimport type { Scheduler } from \"./Scheduler.js\"\nimport type { Scope } from \"./Scope.js\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface AsyncFiberException<out A, out E = never> {\n  readonly _tag: \"AsyncFiberException\"\n  readonly fiber: Fiber.RuntimeFiber<A, E>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Cancel<out A, out E = never> {\n  (fiberId?: FiberId.FiberId, options?: RunCallbackOptions<A, E> | undefined): void\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Runtime<in R> extends Pipeable {\n  /**\n   * The context used as initial for forks\n   */\n  readonly context: Context.Context<R>\n  /**\n   * The runtime flags used as initial for forks\n   */\n  readonly runtimeFlags: RuntimeFlags.RuntimeFlags\n  /**\n   * The fiber references used as initial for forks\n   */\n  readonly fiberRefs: FiberRefs.FiberRefs\n}\n\n/**\n * @since 3.12.0\n */\nexport declare namespace Runtime {\n  /**\n   * @since 3.12.0\n   * @category Type Extractors\n   */\n  export type Context<T extends Runtime<never>> = [T] extends [Runtime<infer R>] ? R : never\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface RunForkOptions {\n  readonly scheduler?: Scheduler | undefined\n  readonly updateRefs?: ((refs: FiberRefs.FiberRefs, fiberId: FiberId.Runtime) => FiberRefs.FiberRefs) | undefined\n  readonly immediate?: boolean\n  readonly scope?: Scope\n}\n\n/**\n * Executes the effect using the provided Scheduler or using the global\n * Scheduler if not provided\n *\n * @since 2.0.0\n * @category execution\n */\nexport const runFork: {\n  <R>(\n    runtime: Runtime<R>\n  ): <A, E>(effect: Effect.Effect<A, E, R>, options?: RunForkOptions | undefined) => Fiber.RuntimeFiber<A, E>\n  <R, A, E>(\n    runtime: Runtime<R>,\n    effect: Effect.Effect<A, E, R>,\n    options?: RunForkOptions | undefined\n  ): Fiber.RuntimeFiber<A, E>\n} = internal.unsafeFork\n\n/**\n * Executes the effect synchronously returning the exit.\n *\n * This method is effectful and should only be invoked at the edges of your\n * program.\n *\n * @since 2.0.0\n * @category execution\n */\nexport const runSyncExit: {\n  <A, E, R>(runtime: Runtime<R>, effect: Effect.Effect<A, E, R>): Exit.Exit<A, E>\n  <R>(runtime: Runtime<R>): <A, E>(effect: Effect.Effect<A, E, R>) => Exit.Exit<A, E>\n} = internal.unsafeRunSyncExit\n\n/**\n * Executes the effect synchronously throwing in case of errors or async boundaries.\n *\n * This method is effectful and should only be invoked at the edges of your\n * program.\n *\n * @since 2.0.0\n * @category execution\n */\nexport const runSync: {\n  <A, E, R>(runtime: Runtime<R>, effect: Effect.Effect<A, E, R>): A\n  <R>(runtime: Runtime<R>): <A, E>(effect: Effect.Effect<A, E, R>) => A\n} = internal.unsafeRunSync\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface RunCallbackOptions<in A, in E = never> extends RunForkOptions {\n  readonly onExit?: ((exit: Exit.Exit<A, E>) => void) | undefined\n}\n\n/**\n * Executes the effect asynchronously, eventually passing the exit value to\n * the specified callback.\n *\n * This method is effectful and should only be invoked at the edges of your\n * program.\n *\n * @since 2.0.0\n * @category execution\n */\nexport const runCallback: {\n  <R>(\n    runtime: Runtime<R>\n  ): <A, E>(\n    effect: Effect.Effect<A, E, R>,\n    options?: RunCallbackOptions<A, E> | undefined\n  ) => (fiberId?: FiberId.FiberId, options?: RunCallbackOptions<A, E> | undefined) => void\n  <R, A, E>(\n    runtime: Runtime<R>,\n    effect: Effect.Effect<A, E, R>,\n    options?: RunCallbackOptions<A, E> | undefined\n  ): (fiberId?: FiberId.FiberId, options?: RunCallbackOptions<A, E> | undefined) => void\n} = internal.unsafeRunCallback\n\n/**\n * Runs the `Effect`, returning a JavaScript `Promise` that will be resolved\n * with the value of the effect once the effect has been executed, or will be\n * rejected with the first error or exception throw by the effect.\n *\n * This method is effectful and should only be used at the edges of your\n * program.\n *\n * @since 2.0.0\n * @category execution\n */\nexport const runPromise: {\n  <R>(\n    runtime: Runtime<R>\n  ): <A, E>(effect: Effect.Effect<A, E, R>, options?: { readonly signal?: AbortSignal } | undefined) => Promise<A>\n  <R, A, E>(\n    runtime: Runtime<R>,\n    effect: Effect.Effect<A, E, R>,\n    options?: { readonly signal?: AbortSignal } | undefined\n  ): Promise<A>\n} = internal.unsafeRunPromise\n\n/**\n * Runs the `Effect`, returning a JavaScript `Promise` that will be resolved\n * with the `Exit` state of the effect once the effect has been executed.\n *\n * This method is effectful and should only be used at the edges of your\n * program.\n *\n * @since 2.0.0\n * @category execution\n */\nexport const runPromiseExit: {\n  <R>(\n    runtime: Runtime<R>\n  ): <A, E>(\n    effect: Effect.Effect<A, E, R>,\n    options?: { readonly signal?: AbortSignal } | undefined\n  ) => Promise<Exit.Exit<A, E>>\n  <R, A, E>(\n    runtime: Runtime<R>,\n    effect: Effect.Effect<A, E, R>,\n    options?: { readonly signal?: AbortSignal } | undefined\n  ): Promise<Exit.Exit<A, E>>\n} = internal.unsafeRunPromiseExit\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const defaultRuntime: Runtime<never> = internal.defaultRuntime\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const defaultRuntimeFlags: RuntimeFlags.RuntimeFlags = internal.defaultRuntimeFlags\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <R>(\n  options: {\n    readonly context: Context.Context<R>\n    readonly runtimeFlags: RuntimeFlags.RuntimeFlags\n    readonly fiberRefs: FiberRefs.FiberRefs\n  }\n) => Runtime<R> = internal.make\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const FiberFailureId = Symbol.for(\"effect/Runtime/FiberFailure\")\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type FiberFailureId = typeof FiberFailureId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const FiberFailureCauseId: unique symbol = internal.FiberFailureCauseId\n\n/**\n * @since 2.0.0\n * @category exports\n */\nexport type FiberFailureCauseId = typeof FiberFailureCauseId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface FiberFailure extends Error, Inspectable {\n  readonly [FiberFailureId]: FiberFailureId\n  readonly [FiberFailureCauseId]: Cause<unknown>\n}\n\n/**\n * @since 2.0.0\n * @category guards\n */\nexport const isAsyncFiberException: (u: unknown) => u is AsyncFiberException<unknown, unknown> =\n  internal.isAsyncFiberException\n\n/**\n * @since 2.0.0\n * @category guards\n */\nexport const isFiberFailure: (u: unknown) => u is FiberFailure = internal.isFiberFailure\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const makeFiberFailure: <E>(cause: Cause<E>) => FiberFailure = internal.fiberFailure\n\n/**\n * @since 2.0.0\n * @category runtime flags\n */\nexport const updateRuntimeFlags: {\n  (f: (flags: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags): <R>(self: Runtime<R>) => Runtime<R>\n  <R>(self: Runtime<R>, f: (flags: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags): Runtime<R>\n} = internal.updateRuntimeFlags\n\n/**\n * @since 2.0.0\n * @category runtime flags\n */\nexport const enableRuntimeFlag: {\n  (flag: RuntimeFlags.RuntimeFlag): <R>(self: Runtime<R>) => Runtime<R>\n  <R>(self: Runtime<R>, flag: RuntimeFlags.RuntimeFlag): Runtime<R>\n} = internal.enableRuntimeFlag\n\n/**\n * @since 2.0.0\n * @category runtime flags\n */\nexport const disableRuntimeFlag: {\n  (flag: RuntimeFlags.RuntimeFlag): <R>(self: Runtime<R>) => Runtime<R>\n  <R>(self: Runtime<R>, flag: RuntimeFlags.RuntimeFlag): Runtime<R>\n} = internal.disableRuntimeFlag\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const updateContext: {\n  <R, R2>(f: (context: Context.Context<R>) => Context.Context<R2>): (self: Runtime<R>) => Runtime<R2>\n  <R, R2>(self: Runtime<R>, f: (context: Context.Context<R>) => Context.Context<R2>): Runtime<R2>\n} = internal.updateContext\n\n/**\n * @since 2.0.0\n * @category context\n * @example\n * ```ts\n * import { Context, Runtime } from \"effect\"\n *\n * class Name extends Context.Tag(\"Name\")<Name, string>() {}\n *\n * const runtime: Runtime.Runtime<Name> = Runtime.defaultRuntime.pipe(\n *   Runtime.provideService(Name, \"John\")\n * )\n * ```\n */\nexport const provideService: {\n  <I, S>(tag: Context.Tag<I, S>, service: S): <R>(self: Runtime<R>) => Runtime<I | R>\n  <R, I, S>(self: Runtime<R>, tag: Context.Tag<I, S>, service: S): Runtime<R | I>\n} = internal.provideService\n\n/**\n * @since 2.0.0\n * @category fiber refs\n */\nexport const updateFiberRefs: {\n  (f: (fiberRefs: FiberRefs.FiberRefs) => FiberRefs.FiberRefs): <R>(self: Runtime<R>) => Runtime<R>\n  <R>(self: Runtime<R>, f: (fiberRefs: FiberRefs.FiberRefs) => FiberRefs.FiberRefs): Runtime<R>\n} = internal.updateFiberRefs\n\n/**\n * @since 2.0.0\n * @category fiber refs\n * @example\n * ```ts\n * import { Effect, FiberRef, Runtime } from \"effect\"\n *\n * const ref = FiberRef.unsafeMake(0)\n *\n * const updatedRuntime = Runtime.defaultRuntime.pipe(\n *   Runtime.setFiberRef(ref, 1)\n * )\n *\n * // returns 1\n * const result = Runtime.runSync(updatedRuntime)(FiberRef.get(ref))\n * ```\n */\nexport const setFiberRef: {\n  <A>(fiberRef: FiberRef.FiberRef<A>, value: A): <R>(self: Runtime<R>) => Runtime<R>\n  <R, A>(self: Runtime<R>, fiberRef: FiberRef.FiberRef<A>, value: A): Runtime<R>\n} = internal.setFiberRef\n\n/**\n * @since 2.0.0\n * @category fiber refs\n * @example\n * ```ts\n * import { Effect, FiberRef, Runtime } from \"effect\"\n *\n * const ref = FiberRef.unsafeMake(0)\n *\n * const updatedRuntime = Runtime.defaultRuntime.pipe(\n *   Runtime.setFiberRef(ref, 1),\n *   Runtime.deleteFiberRef(ref)\n * )\n *\n * // returns 0\n * const result = Runtime.runSync(updatedRuntime)(FiberRef.get(ref))\n * ```\n */\nexport const deleteFiberRef: {\n  <A>(fiberRef: FiberRef.FiberRef<A>): <R>(self: Runtime<R>) => Runtime<R>\n  <R, A>(self: Runtime<R>, fiberRef: FiberRef.FiberRef<A>): Runtime<R>\n} = internal.deleteFiberRef\n"
  },
  {
    "path": "packages/effect/src/RuntimeFlags.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport type * as Differ from \"./Differ.js\"\nimport * as circular from \"./internal/layer/circular.js\"\nimport * as internal from \"./internal/runtimeFlags.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type * as RuntimeFlagsPatch from \"./RuntimeFlagsPatch.js\"\n\n/**\n * Represents a set of `RuntimeFlag`s. `RuntimeFlag`s affect the operation of\n * the Effect runtime system. They are exposed to application-level code because\n * they affect the behavior and performance of application code.\n *\n * @since 2.0.0\n * @category models\n */\nexport type RuntimeFlags = number & {\n  readonly RuntimeFlags: unique symbol\n}\n\n/**\n * Represents a flag that can be set to enable or disable a particular feature\n * of the Effect runtime.\n *\n * @since 2.0.0\n * @category models\n */\nexport type RuntimeFlag = number & {\n  readonly RuntimeFlag: unique symbol\n}\n\n/**\n * No runtime flags.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const None: RuntimeFlag = internal.None\n\n/**\n * The interruption flag determines whether or not the Effect runtime system will\n * interrupt a fiber.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const Interruption: RuntimeFlag = internal.Interruption\n\n/**\n * The op supervision flag determines whether or not the Effect runtime system\n * will supervise all operations of the Effect runtime. Use of this flag will\n * negatively impact performance, but is required for some operations, such as\n * profiling.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const OpSupervision: RuntimeFlag = internal.OpSupervision\n\n/**\n * The runtime metrics flag determines whether or not the Effect runtime system\n * will collect metrics about the Effect runtime. Use of this flag will have a\n * very small negative impact on performance, but generates very helpful\n * operational insight into running Effect applications that can be exported to\n * Prometheus or other tools via Effect Metrics.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const RuntimeMetrics: RuntimeFlag = internal.RuntimeMetrics\n\n/**\n * The wind down flag determines whether the Effect runtime system will execute\n * effects in wind-down mode. In wind-down mode, even if interruption is\n * enabled and a fiber has been interrupted, the fiber will continue its\n * execution uninterrupted.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const WindDown: RuntimeFlag = internal.WindDown\n\n/**\n * The cooperative yielding flag determines whether the Effect runtime will\n * yield to another fiber.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const CooperativeYielding: RuntimeFlag = internal.CooperativeYielding\n\n/**\n * Returns `true` if the `CooperativeYielding` `RuntimeFlag` is enabled, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const cooperativeYielding: (self: RuntimeFlags) => boolean = internal.cooperativeYielding\n\n/**\n * Creates a `RuntimeFlagsPatch` which describes the difference between `self`\n * and `that`.\n *\n * @since 2.0.0\n * @category diffing\n */\nexport const diff: {\n  (that: RuntimeFlags): (self: RuntimeFlags) => RuntimeFlagsPatch.RuntimeFlagsPatch\n  (self: RuntimeFlags, that: RuntimeFlags): RuntimeFlagsPatch.RuntimeFlagsPatch\n} = internal.diff\n\n/**\n * Constructs a differ that knows how to diff `RuntimeFlags` values.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const differ: Differ.Differ<RuntimeFlags, RuntimeFlagsPatch.RuntimeFlagsPatch> = internal.differ\n\n/**\n * Disables the specified `RuntimeFlag`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const disable: {\n  (flag: RuntimeFlag): (self: RuntimeFlags) => RuntimeFlags\n  (self: RuntimeFlags, flag: RuntimeFlag): RuntimeFlags\n} = internal.disable\n\n/**\n * Disables all of the `RuntimeFlag`s in the specified set of `RuntimeFlags`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const disableAll: {\n  (flags: RuntimeFlags): (self: RuntimeFlags) => RuntimeFlags\n  (self: RuntimeFlags, flags: RuntimeFlags): RuntimeFlags\n} = internal.disableAll\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const disableCooperativeYielding: Layer.Layer<never> = circular.disableCooperativeYielding\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const disableInterruption: Layer.Layer<never> = circular.disableInterruption\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const disableOpSupervision: Layer.Layer<never> = circular.disableOpSupervision\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const disableRuntimeMetrics: Layer.Layer<never> = circular.disableRuntimeMetrics\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const disableWindDown: Layer.Layer<never> = circular.disableWindDown\n\n/**\n * Enables the specified `RuntimeFlag`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const enable: {\n  (flag: RuntimeFlag): (self: RuntimeFlags) => RuntimeFlags\n  (self: RuntimeFlags, flag: RuntimeFlag): RuntimeFlags\n} = internal.enable\n\n/**\n * Enables all of the `RuntimeFlag`s in the specified set of `RuntimeFlags`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const enableAll: {\n  (flags: RuntimeFlags): (self: RuntimeFlags) => RuntimeFlags\n  (self: RuntimeFlags, flags: RuntimeFlags): RuntimeFlags\n} = internal.enableAll\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const enableCooperativeYielding: Layer.Layer<never> = circular.enableCooperativeYielding\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const enableInterruption: Layer.Layer<never> = circular.enableInterruption\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const enableOpSupervision: Layer.Layer<never> = circular.enableOpSupervision\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const enableRuntimeMetrics: Layer.Layer<never> = circular.enableRuntimeMetrics\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const enableWindDown: Layer.Layer<never> = circular.enableWindDown\n\n/**\n * Returns true only if the `Interruption` flag is **enabled** and the\n * `WindDown` flag is **disabled**.\n *\n * A fiber is said to be interruptible if interruption is enabled and the fiber\n * is not in its wind-down phase, in which it takes care of cleanup activities\n * related to fiber shutdown.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const interruptible: (self: RuntimeFlags) => boolean = internal.interruptible\n\n/**\n * Returns `true` if the `Interruption` `RuntimeFlag` is enabled, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const interruption: (self: RuntimeFlags) => boolean = internal.interruption\n\n/**\n * Returns `true` if the specified `RuntimeFlag` is enabled, `false` otherwise.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const isEnabled: {\n  (flag: RuntimeFlag): (self: RuntimeFlags) => boolean\n  (self: RuntimeFlags, flag: RuntimeFlag): boolean\n} = internal.isEnabled\n\n/**\n * Returns `true` if the specified `RuntimeFlag` is disabled, `false` otherwise.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const isDisabled: {\n  (flag: RuntimeFlag): (self: RuntimeFlags) => boolean\n  (self: RuntimeFlags, flag: RuntimeFlag): boolean\n} = internal.isDisabled\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (...flags: ReadonlyArray<RuntimeFlag>) => RuntimeFlags = internal.make\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const none: RuntimeFlags = internal.none\n\n/**\n * Returns `true` if the `OpSupervision` `RuntimeFlag` is enabled, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const opSupervision: (self: RuntimeFlags) => boolean = internal.opSupervision\n\n/**\n * Patches a set of `RuntimeFlag`s with a `RuntimeFlagsPatch`, returning the\n * patched set of `RuntimeFlag`s.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const patch: {\n  (patch: RuntimeFlagsPatch.RuntimeFlagsPatch): (self: RuntimeFlags) => RuntimeFlags\n  (self: RuntimeFlags, patch: RuntimeFlagsPatch.RuntimeFlagsPatch): RuntimeFlags\n} = internal.patch\n\n/**\n * Converts the provided `RuntimeFlags` into a `string`.\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const render: (self: RuntimeFlags) => string = internal.render\n\n/**\n * Returns `true` if the `RuntimeMetrics` `RuntimeFlag` is enabled, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const runtimeMetrics: (self: RuntimeFlags) => boolean = internal.runtimeMetrics\n\n/**\n * Converts the provided `RuntimeFlags` into a `ReadonlySet<number>`.\n *\n * @category conversions\n * @since 2.0.0\n */\nexport const toSet: (self: RuntimeFlags) => ReadonlySet<RuntimeFlag> = internal.toSet\n\n/**\n * Returns `true` if the `WindDown` `RuntimeFlag` is enabled, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const windDown: (self: RuntimeFlags) => boolean = internal.windDown\n"
  },
  {
    "path": "packages/effect/src/RuntimeFlagsPatch.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as runtimeFlags from \"./internal/runtimeFlags.js\"\nimport * as internal from \"./internal/runtimeFlagsPatch.js\"\nimport type * as RuntimeFlags from \"./RuntimeFlags.js\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type RuntimeFlagsPatch = number & {\n  readonly RuntimeFlagsPatch: unique symbol\n}\n\n/**\n * The empty `RuntimeFlagsPatch`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: RuntimeFlagsPatch = internal.empty\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (active: number, enabled: number) => RuntimeFlagsPatch = internal.make\n\n/**\n * Creates a `RuntimeFlagsPatch` describing enabling the provided `RuntimeFlag`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const enable: (flag: RuntimeFlags.RuntimeFlag) => RuntimeFlagsPatch = internal.enable\n\n/**\n * Creates a `RuntimeFlagsPatch` describing disabling the provided `RuntimeFlag`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const disable: (flag: RuntimeFlags.RuntimeFlag) => RuntimeFlagsPatch = internal.disable\n\n/**\n * Returns `true` if the specified `RuntimeFlagsPatch` is empty.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isEmpty: (patch: RuntimeFlagsPatch) => boolean = internal.isEmpty\n\n/**\n * Returns `true` if the `RuntimeFlagsPatch` describes the specified\n * `RuntimeFlag` as active.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const isActive: {\n  (flag: RuntimeFlagsPatch): (self: RuntimeFlagsPatch) => boolean\n  (self: RuntimeFlagsPatch, flag: RuntimeFlagsPatch): boolean\n} = internal.isActive\n\n/**\n * Returns `true` if the `RuntimeFlagsPatch` describes the specified\n * `RuntimeFlag` as enabled.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const isEnabled: {\n  (flag: RuntimeFlags.RuntimeFlag): (self: RuntimeFlagsPatch) => boolean\n  (self: RuntimeFlagsPatch, flag: RuntimeFlags.RuntimeFlag): boolean\n} = internal.isEnabled\n\n/**\n * Returns `true` if the `RuntimeFlagsPatch` describes the specified\n * `RuntimeFlag` as disabled.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const isDisabled: {\n  (flag: RuntimeFlags.RuntimeFlag): (self: RuntimeFlagsPatch) => boolean\n  (self: RuntimeFlagsPatch, flag: RuntimeFlags.RuntimeFlag): boolean\n} = internal.isDisabled\n\n/**\n * Returns `true` if the `RuntimeFlagsPatch` includes the specified\n * `RuntimeFlag`, `false` otherwise.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const includes: {\n  (flag: RuntimeFlagsPatch): (self: RuntimeFlagsPatch) => boolean\n  (self: RuntimeFlagsPatch, flag: RuntimeFlagsPatch): boolean\n} = internal.isActive\n\n/**\n * Creates a `RuntimeFlagsPatch` describing the application of the `self` patch,\n * followed by `that` patch.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const andThen: {\n  (that: RuntimeFlagsPatch): (self: RuntimeFlagsPatch) => RuntimeFlagsPatch\n  (self: RuntimeFlagsPatch, that: RuntimeFlagsPatch): RuntimeFlagsPatch\n} = internal.andThen\n\n/**\n * Creates a `RuntimeFlagsPatch` describing application of both the `self` patch\n * and `that` patch.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const both: {\n  (that: RuntimeFlagsPatch): (self: RuntimeFlagsPatch) => RuntimeFlagsPatch\n  (self: RuntimeFlagsPatch, that: RuntimeFlagsPatch): RuntimeFlagsPatch\n} = internal.both\n\n/**\n * Creates a `RuntimeFlagsPatch` describing application of either the `self`\n * patch or `that` patch.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const either: {\n  (that: RuntimeFlagsPatch): (self: RuntimeFlagsPatch) => RuntimeFlagsPatch\n  (self: RuntimeFlagsPatch, that: RuntimeFlagsPatch): RuntimeFlagsPatch\n} = internal.either\n\n/**\n * Creates a `RuntimeFlagsPatch` which describes exclusion of the specified\n * `RuntimeFlag` from the set of `RuntimeFlags`.\n *\n * @category utils\n * @since 2.0.0\n */\nexport const exclude: {\n  (flag: RuntimeFlags.RuntimeFlag): (self: RuntimeFlagsPatch) => RuntimeFlagsPatch\n  (self: RuntimeFlagsPatch, flag: RuntimeFlags.RuntimeFlag): RuntimeFlagsPatch\n} = internal.exclude\n\n/**\n * Creates a `RuntimeFlagsPatch` which describes the inverse of the patch\n * specified by the provided `RuntimeFlagsPatch`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const inverse: (patch: RuntimeFlagsPatch) => RuntimeFlagsPatch = internal.inverse\n\n/**\n * Returns a `ReadonlySet<number>` containing the `RuntimeFlags` described as\n * enabled by the specified `RuntimeFlagsPatch`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const enabledSet: (self: RuntimeFlagsPatch) => ReadonlySet<RuntimeFlags.RuntimeFlag> = runtimeFlags.enabledSet\n\n/**\n * Returns a `ReadonlySet<number>` containing the `RuntimeFlags` described as\n * disabled by the specified `RuntimeFlagsPatch`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const disabledSet: (self: RuntimeFlagsPatch) => ReadonlySet<RuntimeFlags.RuntimeFlag> = runtimeFlags.disabledSet\n\n/**\n * Renders the provided `RuntimeFlagsPatch` to a string.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const render: (self: RuntimeFlagsPatch) => string = runtimeFlags.renderPatch\n"
  },
  {
    "path": "packages/effect/src/STM.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Cause from \"./Cause.js\"\nimport * as Chunk from \"./Chunk.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport * as core from \"./internal/stm/core.js\"\nimport * as stm from \"./internal/stm/stm.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport type { Covariant, MergeRecord, NoExcessProperties, NoInfer } from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\nimport type { YieldWrap } from \"./Utils.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const STMTypeId: unique symbol = core.STMTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type STMTypeId = typeof STMTypeId\n\n/**\n * `STM<A, E, R>` represents an effect that can be performed transactionally,\n *  resulting in a failure `E` or a value `A` that may require an environment\n *  `R` to execute.\n *\n * Software Transactional Memory is a technique which allows composition of\n * arbitrary atomic operations.  It is the software analog of transactions in\n * database systems.\n *\n * The API is lifted directly from the Haskell package Control.Concurrent.STM\n * although the implementation does not resemble the Haskell one at all.\n *\n * See http://hackage.haskell.org/package/stm-2.5.0.0/docs/Control-Concurrent-STM.html\n *\n * STM in Haskell was introduced in:\n *\n * Composable memory transactions, by Tim Harris, Simon Marlow, Simon Peyton\n * Jones, and Maurice Herlihy, in ACM Conference on Principles and Practice of\n * Parallel Programming 2005.\n *\n * See https://www.microsoft.com/en-us/research/publication/composable-memory-transactions/\n *\n * See also:\n *  Lock Free Data Structures using STMs in Haskell, by Anthony Discolo, Tim\n *  Harris, Simon Marlow, Simon Peyton Jones, Satnam Singh) FLOPS 2006: Eighth\n *  International Symposium on Functional and Logic Programming, Fuji Susono,\n *  JAPAN, April 2006\n *\n *  https://www.microsoft.com/en-us/research/publication/lock-free-data-structures-using-stms-in-haskell/\n *\n * The implemtation is based on the ZIO STM module, while JS environments have\n * no race conditions from multiple threads STM provides greater benefits for\n * synchronization of Fibers and transactional data-types can be quite useful.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface STM<out A, out E = never, out R = never>\n  extends Effect.Effect<A, E, R>, STM.Variance<A, E, R>, Pipeable\n{\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: STMUnify<this>\n  [Unify.ignoreSymbol]?: STMUnifyIgnore\n  [Symbol.iterator](): Effect.EffectGenerator<STM<A, E, R>>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface STMUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  STM?: () => A[Unify.typeSymbol] extends STM<infer A0, infer E0, infer R0> | infer _ ? STM<A0, E0, R0> : never\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface STMUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface STMTypeLambda extends TypeLambda {\n  readonly type: STM<this[\"Target\"], this[\"Out1\"], this[\"Out2\"]>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\ndeclare module \"./Context.js\" {\n  interface Tag<Id, Value> extends STM<Value, never, Id> {}\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  interface Reference<Id, Value> extends STM<Value> {}\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\ndeclare module \"./Either.js\" {\n  interface Left<E, A> extends STM<A, E> {\n    readonly _tag: \"Left\"\n  }\n  interface Right<E, A> extends STM<A, E> {\n    readonly _tag: \"Right\"\n  }\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\ndeclare module \"./Option.js\" {\n  interface None<A> extends STM<A, Cause.NoSuchElementException> {\n    readonly _tag: \"None\"\n  }\n  interface Some<A> extends STM<A, Cause.NoSuchElementException> {\n    readonly _tag: \"Some\"\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace STM {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out A, out E, out R> {\n    readonly [STMTypeId]: {\n      readonly _A: Covariant<A>\n      readonly _E: Covariant<E>\n      readonly _R: Covariant<R>\n    }\n  }\n}\n\n/**\n * Returns `true` if the provided value is an `STM`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isSTM: (u: unknown) => u is STM<unknown, unknown, unknown> = core.isSTM\n\n/**\n * Treats the specified `acquire` transaction as the acquisition of a\n * resource. The `acquire` transaction will be executed interruptibly. If it\n * is a success and is committed the specified `release` workflow will be\n * executed uninterruptibly as soon as the `use` workflow completes execution.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const acquireUseRelease: {\n  <A, A2, E2, R2, A3, E3, R3>(\n    use: (resource: A) => STM<A2, E2, R2>,\n    release: (resource: A) => STM<A3, E3, R3>\n  ): <E, R>(acquire: STM<A, E, R>) => Effect.Effect<A2, E2 | E3 | E, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    acquire: STM<A, E, R>,\n    use: (resource: A) => STM<A2, E2, R2>,\n    release: (resource: A) => STM<A3, E3, R3>\n  ): Effect.Effect<A2, E | E2 | E3, R | R2 | R3>\n} = stm.acquireUseRelease\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport declare namespace All {\n  type STMAny = STM<any, any, any>\n\n  type ReturnTuple<T extends ReadonlyArray<STM<any, any, any>>, Discard extends boolean> = STM<\n    Discard extends true ? void\n      : T[number] extends never ? []\n      : { -readonly [K in keyof T]: [T[K]] extends [STM<infer A, infer _E, infer _R>] ? A : never },\n    T[number] extends never ? never\n      : [T[number]] extends [{ [STMTypeId]: { _E: (_: never) => infer E } }] ? E\n      : never,\n    T[number] extends never ? never\n      : [T[number]] extends [{ [STMTypeId]: { _R: (_: never) => infer R } }] ? R\n      : never\n  > extends infer X ? X : never\n\n  type ReturnIterable<T extends Iterable<STMAny>, Discard extends boolean> = [T] extends\n    [Iterable<STM.Variance<infer A, infer E, infer R>>] ? STM<Discard extends true ? void : Array<A>, E, R> : never\n\n  type ReturnObject<T extends Record<string, STMAny>, Discard extends boolean> = STM<\n    Discard extends true ? void\n      : { -readonly [K in keyof T]: [T[K]] extends [STM.Variance<infer A, infer _E, infer _R>] ? A : never },\n    keyof T extends never ? never\n      : [T[keyof T]] extends [{ [STMTypeId]: { _E: (_: never) => infer E } }] ? E\n      : never,\n    keyof T extends never ? never\n      : [T[keyof T]] extends [{ [STMTypeId]: { _R: (_: never) => infer R } }] ? R\n      : never\n  >\n\n  /**\n   * @since 2.0.0\n   * @category utils\n   */\n  export type Options = {\n    readonly discard?: boolean | undefined\n  }\n  type IsDiscard<A> = [Extract<A, { readonly discard: true }>] extends [never] ? false : true\n  type Narrow<A> = (A extends [] ? [] : never) | A\n\n  /**\n   * @since 2.0.0\n   * @category utils\n   */\n  export interface Signature {\n    <\n      Arg extends ReadonlyArray<STMAny> | Iterable<STMAny> | Record<string, STMAny>,\n      O extends NoExcessProperties<Options, O>\n    >(\n      arg: Narrow<Arg>,\n      options?: O\n    ): [Arg] extends [ReadonlyArray<STMAny>] ? ReturnTuple<Arg, IsDiscard<O>>\n      : [Arg] extends [Iterable<STMAny>] ? ReturnIterable<Arg, IsDiscard<O>>\n      : [Arg] extends [Record<string, STMAny>] ? ReturnObject<Arg, IsDiscard<O>>\n      : never\n  }\n}\n\n/**\n * Runs all the provided transactional effects in sequence respecting the\n * structure provided in input.\n *\n * Supports multiple arguments, a single argument tuple / array or record /\n * struct.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const all: All.Signature = stm.all\n\n/**\n * Maps the success value of this effect to the specified constant value.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const as: {\n  <A2>(value: A2): <A, E, R>(self: STM<A, E, R>) => STM<A2, E, R>\n  <A, E, R, A2>(self: STM<A, E, R>, value: A2): STM<A2, E, R>\n} = stm.as\n\n/**\n * Maps the success value of this effect to an optional value.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const asSome: <A, E, R>(self: STM<A, E, R>) => STM<Option.Option<A>, E, R> = stm.asSome\n\n/**\n * Maps the error value of this effect to an optional value.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const asSomeError: <A, E, R>(self: STM<A, E, R>) => STM<A, Option.Option<E>, R> = stm.asSomeError\n\n/**\n * This function maps the success value of an `STM` to `void`. If the original\n * `STM` succeeds, the returned `STM` will also succeed. If the original `STM`\n * fails, the returned `STM` will fail with the same error.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const asVoid: <A, E, R>(self: STM<A, E, R>) => STM<void, E, R> = stm.asVoid\n\n/**\n * Creates an `STM` value from a partial (but pure) function.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const attempt: <A>(evaluate: LazyArg<A>) => STM<A, unknown> = stm.attempt\n\n/**\n * Recovers from all errors.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchAll: {\n  <E, B, E1, R1>(f: (e: E) => STM<B, E1, R1>): <A, R>(self: STM<A, E, R>) => STM<B | A, E1, R1 | R>\n  <A, E, R, B, E1, R1>(self: STM<A, E, R>, f: (e: E) => STM<B, E1, R1>): STM<A | B, E1, R | R1>\n} = core.catchAll\n\n/**\n * Recovers from some or all of the error cases.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchSome: {\n  <E, A2, E2, R2>(\n    pf: (error: E) => Option.Option<STM<A2, E2, R2>>\n  ): <A, R>(self: STM<A, E, R>) => STM<A2 | A, E | E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: STM<A, E, R>,\n    pf: (error: E) => Option.Option<STM<A2, E2, R2>>\n  ): STM<A | A2, E | E2, R | R2>\n} = stm.catchSome\n\n/**\n * Recovers from the specified tagged error.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchTag: {\n  <K extends E[\"_tag\"] & string, E extends { _tag: string }, A1, E1, R1>(\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => STM<A1, E1, R1>\n  ): <A, R>(self: STM<A, E, R>) => STM<A1 | A, E1 | Exclude<E, { _tag: K }>, R1 | R>\n  <A, E extends { _tag: string }, R, K extends E[\"_tag\"] & string, A1, E1, R1>(\n    self: STM<A, E, R>,\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => STM<A1, E1, R1>\n  ): STM<A | A1, E1 | Exclude<E, { _tag: K }>, R | R1>\n} = stm.catchTag\n\n/**\n * Recovers from multiple tagged errors.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchTags: {\n  <\n    E extends { _tag: string },\n    Cases extends { [K in E[\"_tag\"]]+?: ((error: Extract<E, { _tag: K }>) => STM<any, any, any>) }\n  >(\n    cases: Cases\n  ): <A, R>(\n    self: STM<A, E, R>\n  ) => STM<\n    | A\n    | { [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => STM<infer A, any, any> ? A : never }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | { [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => STM<any, infer E, any> ? E : never }[keyof Cases],\n    | R\n    | { [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => STM<any, any, infer R> ? R : never }[keyof Cases]\n  >\n  <\n    R,\n    E extends { _tag: string },\n    A,\n    Cases extends { [K in E[\"_tag\"]]+?: ((error: Extract<E, { _tag: K }>) => STM<any, any, any>) }\n  >(\n    self: STM<A, E, R>,\n    cases: Cases\n  ): STM<\n    | A\n    | { [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => STM<infer A, any, any> ? A : never }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | { [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => STM<any, infer E, any> ? E : never }[keyof Cases],\n    | R\n    | { [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => STM<any, any, infer R> ? R : never }[keyof Cases]\n  >\n} = stm.catchTags\n\n/**\n * Checks the condition, and if it's true, returns unit, otherwise, retries.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const check: (predicate: LazyArg<boolean>) => STM<void> = stm.check\n\n/**\n * Simultaneously filters and maps the value produced by this effect.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const collect: {\n  <A, A2>(pf: (a: A) => Option.Option<A2>): <E, R>(self: STM<A, E, R>) => STM<A2, E, R>\n  <A, E, R, A2>(self: STM<A, E, R>, pf: (a: A) => Option.Option<A2>): STM<A2, E, R>\n} = stm.collect\n\n/**\n * Simultaneously filters and maps the value produced by this effect.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const collectSTM: {\n  <A, A2, E2, R2>(pf: (a: A) => Option.Option<STM<A2, E2, R2>>): <E, R>(self: STM<A, E, R>) => STM<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: STM<A, E, R>, pf: (a: A) => Option.Option<STM<A2, E2, R2>>): STM<A2, E | E2, R | R2>\n} = stm.collectSTM\n\n/**\n * Commits this transaction atomically.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const commit: <A, E, R>(self: STM<A, E, R>) => Effect.Effect<A, E, R> = core.commit\n\n/**\n * Commits this transaction atomically, regardless of whether the transaction\n * is a success or a failure.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const commitEither: <A, E, R>(self: STM<A, E, R>) => Effect.Effect<A, E, R> = stm.commitEither\n\n/**\n * Similar to Either.cond, evaluate the predicate, return the given A as\n * success if predicate returns true, and the given E as error otherwise\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const cond: <A, E>(predicate: LazyArg<boolean>, error: LazyArg<E>, result: LazyArg<A>) => STM<A, E> = stm.cond\n\n/**\n * Retrieves the environment inside an stm.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const context: <R>() => STM<Context.Context<R>, never, R> = core.context\n\n/**\n * Accesses the environment of the transaction to perform a transaction.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const contextWith: <R0, R>(f: (environment: Context.Context<R0>) => R) => STM<R, never, R0> = core.contextWith\n\n/**\n * Accesses the environment of the transaction to perform a transaction.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const contextWithSTM: <R0, A, E, R>(\n  f: (environment: Context.Context<R0>) => STM<A, E, R>\n) => STM<A, E, R0 | R> = core.contextWithSTM\n\n/**\n * Transforms the environment being provided to this effect with the specified\n * function.\n *\n * @since 2.0.0\n * @category context\n */\nexport const mapInputContext: {\n  <R0, R>(f: (context: Context.Context<R0>) => Context.Context<R>): <A, E>(self: STM<A, E, R>) => STM<A, E, R0>\n  <A, E, R0, R>(self: STM<A, E, R>, f: (context: Context.Context<R0>) => Context.Context<R>): STM<A, E, R0>\n} = core.mapInputContext\n\n/**\n * Fails the transactional effect with the specified defect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const die: (defect: unknown) => STM<never> = core.die\n\n/**\n * Kills the fiber running the effect with a `Cause.RuntimeException` that\n * contains the specified message.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dieMessage: (message: string) => STM<never> = core.dieMessage\n\n/**\n * Fails the transactional effect with the specified lazily evaluated defect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dieSync: (evaluate: LazyArg<unknown>) => STM<never> = core.dieSync\n\n/**\n * Converts the failure channel into an `Either`.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const either: <A, E, R>(self: STM<A, E, R>) => STM<Either.Either<A, E>, never, R> = stm.either\n\n/**\n * Executes the specified finalization transaction whether or not this effect\n * succeeds. Note that as with all STM transactions, if the full transaction\n * fails, everything will be rolled back.\n *\n * @since 2.0.0\n * @category finalization\n */\nexport const ensuring: {\n  <R1, B>(finalizer: STM<B, never, R1>): <A, E, R>(self: STM<A, E, R>) => STM<A, E, R1 | R>\n  <A, E, R, R1, B>(self: STM<A, E, R>, finalizer: STM<B, never, R1>): STM<A, E, R | R1>\n} = core.ensuring\n\n/**\n * Returns an effect that ignores errors and runs repeatedly until it\n * eventually succeeds.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const eventually: <A, E, R>(self: STM<A, E, R>) => STM<A, E, R> = stm.eventually\n\n/**\n * Determines whether all elements of the `Iterable<A>` satisfy the effectual\n * predicate.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const every: {\n  <A, R, E>(predicate: (a: NoInfer<A>) => STM<boolean, E, R>): (iterable: Iterable<A>) => STM<boolean, E, R>\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM<boolean, E, R>): STM<boolean, E, R>\n} = stm.every\n\n/**\n * Determines whether any element of the `Iterable[A]` satisfies the effectual\n * predicate `f`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const exists: {\n  <A, R, E>(predicate: (a: NoInfer<A>) => STM<boolean, E, R>): (iterable: Iterable<A>) => STM<boolean, E, R>\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM<boolean, E, R>): STM<boolean, E, R>\n} = stm.exists\n\n/**\n * Fails the transactional effect with the specified error.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fail: <E>(error: E) => STM<never, E> = core.fail\n\n/**\n * Fails the transactional effect with the specified lazily evaluated error.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failSync: <E>(evaluate: LazyArg<E>) => STM<never, E> = core.failSync\n\n/**\n * Returns the fiber id of the fiber committing the transaction.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fiberId: STM<FiberId.FiberId> = stm.fiberId\n\n/**\n * Filters the collection using the specified effectual predicate.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const filter: {\n  <A, R, E>(predicate: (a: NoInfer<A>) => STM<boolean, E, R>): (iterable: Iterable<A>) => STM<Array<A>, E, R>\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM<boolean, E, R>): STM<Array<A>, E, R>\n} = stm.filter\n\n/**\n * Filters the collection using the specified effectual predicate, removing\n * all elements that satisfy the predicate.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const filterNot: {\n  <A, R, E>(predicate: (a: NoInfer<A>) => STM<boolean, E, R>): (iterable: Iterable<A>) => STM<Array<A>, E, R>\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM<boolean, E, R>): STM<Array<A>, E, R>\n} = stm.filterNot\n\n/**\n * Dies with specified defect if the predicate fails.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterOrDie: {\n  <A, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>,\n    defect: LazyArg<unknown>\n  ): <E, R>(self: STM<A, E, R>) => STM<B, E, R>\n  <A>(predicate: Predicate<NoInfer<A>>, defect: LazyArg<unknown>): <E, R>(self: STM<A, E, R>) => STM<A, E, R>\n  <A, E, R, B extends A>(self: STM<A, E, R>, refinement: Refinement<A, B>, defect: LazyArg<unknown>): STM<B, E, R>\n  <A, E, R>(self: STM<A, E, R>, predicate: Predicate<A>, defect: LazyArg<unknown>): STM<A, E, R>\n} = stm.filterOrDie\n\n/**\n * Dies with a `Cause.RuntimeException` having the specified  message if the\n * predicate fails.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterOrDieMessage: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>, message: string): <E, R>(self: STM<A, E, R>) => STM<B, E, R>\n  <A>(predicate: Predicate<NoInfer<A>>, message: string): <E, R>(self: STM<A, E, R>) => STM<A, E, R>\n  <A, E, R, B extends A>(self: STM<A, E, R>, refinement: Refinement<A, B>, message: string): STM<B, E, R>\n  <A, E, R>(self: STM<A, E, R>, predicate: Predicate<A>, message: string): STM<A, E, R>\n} = stm.filterOrDieMessage\n\n/**\n * Supplies `orElse` if the predicate fails.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterOrElse: {\n  <A, B extends A, C, E2, R2>(\n    refinement: Refinement<NoInfer<A>, B>,\n    orElse: (a: NoInfer<A>) => STM<C, E2, R2>\n  ): <E, R>(self: STM<A, E, R>) => STM<B | C, E2 | E, R2 | R>\n  <A, B, E2, R2>(\n    predicate: Predicate<NoInfer<A>>,\n    orElse: (a: NoInfer<A>) => STM<B, E2, R2>\n  ): <E, R>(self: STM<A, E, R>) => STM<A | B, E2 | E, R2 | R>\n  <A, E, R, B extends A, C, E2, R2>(\n    self: STM<A, E, R>,\n    refinement: Refinement<A, B>,\n    orElse: (a: A) => STM<C, E2, R2>\n  ): STM<B | C, E | E2, R | R2>\n  <A, E, R, B, E2, R2>(\n    self: STM<A, E, R>,\n    predicate: Predicate<A>,\n    orElse: (a: A) => STM<B, E2, R2>\n  ): STM<A | B, E | E2, R | R2>\n} = stm.filterOrElse\n\n/**\n * Fails with the specified error if the predicate fails.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterOrFail: {\n  <A, B extends A, E2>(\n    refinement: Refinement<NoInfer<A>, B>,\n    orFailWith: (a: NoInfer<A>) => E2\n  ): <E, R>(self: STM<A, E, R>) => STM<B, E2 | E, R>\n  <A, E2>(\n    predicate: Predicate<NoInfer<A>>,\n    orFailWith: (a: NoInfer<A>) => E2\n  ): <E, R>(self: STM<A, E, R>) => STM<A, E2 | E, R>\n  <A, E, R, B extends A, E2>(\n    self: STM<A, E, R>,\n    refinement: Refinement<A, B>,\n    orFailWith: (a: A) => E2\n  ): STM<B, E | E2, R>\n  <A, E, R, E2>(self: STM<A, E, R>, predicate: Predicate<A>, orFailWith: (a: A) => E2): STM<A, E | E2, R>\n} = stm.filterOrFail\n\n/**\n * Feeds the value produced by this effect to the specified function, and then\n * runs the returned effect as well to produce its results.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMap: {\n  <A, A2, E1, R1>(f: (a: A) => STM<A2, E1, R1>): <E, R>(self: STM<A, E, R>) => STM<A2, E1 | E, R1 | R>\n  <A, E, R, A2, E1, R1>(self: STM<A, E, R>, f: (a: A) => STM<A2, E1, R1>): STM<A2, E | E1, R | R1>\n} = core.flatMap\n\n/**\n * Flattens out a nested `STM` effect.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatten: <A, E2, R2, E, R>(self: STM<STM<A, E2, R2>, E, R>) => STM<A, E2 | E, R2 | R> = stm.flatten\n\n/**\n * Flips the success and failure channels of this transactional effect. This\n * allows you to use all methods on the error channel, possibly before\n * flipping back.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const flip: <A, E, R>(self: STM<A, E, R>) => STM<E, A, R> = stm.flip\n\n/**\n * Swaps the error/value parameters, applies the function `f` and flips the\n * parameters back\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const flipWith: {\n  <E, A, R, E2, A2, R2>(f: (stm: STM<E, A, R>) => STM<E2, A2, R2>): (self: STM<A, E, R>) => STM<A | A2, E | E2, R | R2>\n  <A, E, R, E2, A2, R2>(self: STM<A, E, R>, f: (stm: STM<E, A, R>) => STM<E2, A2, R2>): STM<A | A2, E | E2, R | R2>\n} = stm.flipWith\n\n/**\n * Folds over the `STM` effect, handling both failure and success, but not\n * retry.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <E, A2, A, A3>(\n    options: { readonly onFailure: (error: E) => A2; readonly onSuccess: (value: A) => A3 }\n  ): <R>(self: STM<A, E, R>) => STM<A2 | A3, never, R>\n  <A, E, R, A2, A3>(\n    self: STM<A, E, R>,\n    options: { readonly onFailure: (error: E) => A2; readonly onSuccess: (value: A) => A3 }\n  ): STM<A2 | A3, never, R>\n} = stm.match\n\n/**\n * Effectfully folds over the `STM` effect, handling both failure and success.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const matchSTM: {\n  <E, A1, E1, R1, A, A2, E2, R2>(\n    options: { readonly onFailure: (e: E) => STM<A1, E1, R1>; readonly onSuccess: (a: A) => STM<A2, E2, R2> }\n  ): <R>(self: STM<A, E, R>) => STM<A1 | A2, E1 | E2, R1 | R2 | R>\n  <A, E, R, A1, E1, R1, A2, E2, R2>(\n    self: STM<A, E, R>,\n    options: { readonly onFailure: (e: E) => STM<A1, E1, R1>; readonly onSuccess: (a: A) => STM<A2, E2, R2> }\n  ): STM<A1 | A2, E1 | E2, R | R1 | R2>\n} = core.matchSTM\n\n/**\n * Applies the function `f` to each element of the `Iterable<A>` and returns\n * a transactional effect that produces a new `Chunk<A2>`.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const forEach: {\n  <A, A2, E, R>(\n    f: (a: A) => STM<A2, E, R>,\n    options?: { readonly discard?: false | undefined } | undefined\n  ): (elements: Iterable<A>) => STM<Array<A2>, E, R>\n  <A, A2, E, R>(\n    f: (a: A) => STM<A2, E, R>,\n    options: { readonly discard: true }\n  ): (elements: Iterable<A>) => STM<void, E, R>\n  <A, A2, E, R>(\n    elements: Iterable<A>,\n    f: (a: A) => STM<A2, E, R>,\n    options?: { readonly discard?: false | undefined } | undefined\n  ): STM<Array<A2>, E, R>\n  <A, A2, E, R>(elements: Iterable<A>, f: (a: A) => STM<A2, E, R>, options: { readonly discard: true }): STM<void, E, R>\n} = stm.forEach\n\n/**\n * Lifts an `Either` into a `STM`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEither: <A, E>(either: Either.Either<A, E>) => STM<A, E> = stm.fromEither\n\n/**\n * Lifts an `Option` into a `STM`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromOption: <A>(option: Option.Option<A>) => STM<A, Option.Option<never>> = stm.fromOption\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Adapter {\n  <A, E, R>(self: STM<A, E, R>): STM<A, E, R>\n  <A, _R, _E, _A>(a: A, ab: (a: A) => STM<_A, _E, _R>): STM<_A, _E, _R>\n  <A, B, _R, _E, _A>(a: A, ab: (a: A) => B, bc: (b: B) => STM<_A, _E, _R>): STM<_A, _E, _R>\n  <A, B, C, _R, _E, _A>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => STM<_A, _E, _R>): STM<_A, _E, _R>\n  <A, B, C, D, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: F) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (g: H) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => R,\n    rs: (r: R) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => R,\n    rs: (r: R) => S,\n    st: (s: S) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, _R, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => R,\n    rs: (r: R) => S,\n    st: (s: S) => T,\n    tu: (s: T) => STM<_A, _E, _R>\n  ): STM<_A, _E, _R>\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const gen: <Self, Eff extends YieldWrap<STM<any, any, any>>, AEff>(\n  ...args:\n    | [\n      self: Self,\n      body: (this: Self, resume: Adapter) => Generator<Eff, AEff, never>\n    ]\n    | [body: (resume: Adapter) => Generator<Eff, AEff, never>]\n) => STM<\n  AEff,\n  [Eff] extends [never] ? never : [Eff] extends [YieldWrap<STM<infer _A, infer E, infer _R>>] ? E : never,\n  [Eff] extends [never] ? never : [Eff] extends [YieldWrap<STM<infer _A, infer _E, infer R>>] ? R : never\n> = stm.gen\n\n/**\n * Returns a successful effect with the head of the list if the list is\n * non-empty or fails with the error `None` if the list is empty.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const head: <A, E, R>(self: STM<Iterable<A>, E, R>) => STM<A, Option.Option<E>, R> = stm.head\n\nconst if_: {\n  <A, E1, R1, A2, E2, R2>(options: {\n    readonly onTrue: STM<A, E1, R1>\n    readonly onFalse: STM<A2, E2, R2> /**\n     * Flattens out a nested `STM` effect.\n     *\n     * @since 2.0.0\n     * @category sequencing\n     */\n  }): <E = never, R = never>(self: boolean | STM<boolean, E, R>) => STM<A | A2, E1 | E2 | E, R1 | R2 | R>\n  <A, E1, R1, A2, E2, R2, E = never, R = never>(\n    self: boolean,\n    options: { readonly onTrue: STM<A, E1, R1>; readonly onFalse: STM<A2, E2, R2> }\n  ): STM<A | A2, E1 | E2 | E, R1 | R2 | R>\n  <E, R, A, E1, R1, A2, E2, R2>(\n    self: STM<boolean, E, R>,\n    options: { readonly onTrue: STM<A, E1, R1>; readonly onFalse: STM<A2, E2, R2> }\n  ): STM<A | A2, E | E1 | E2, R | R1 | R2>\n} = stm.if_\n\nexport {\n  /**\n   * Runs `onTrue` if the result of `b` is `true` and `onFalse` otherwise.\n   *\n   * @since 2.0.0\n   * @category mutations\n   */\n  if_ as if\n}\n\n/**\n * Returns a new effect that ignores the success or failure of this effect.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const ignore: <A, E, R>(self: STM<A, E, R>) => STM<void, never, R> = stm.ignore\n\n/**\n * Interrupts the fiber running the effect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const interrupt: STM<never> = core.interrupt\n\n/**\n * Interrupts the fiber running the effect with the specified `FiberId`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const interruptAs: (fiberId: FiberId.FiberId) => STM<never> = core.interruptAs\n\n/**\n * Returns whether this transactional effect is a failure.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isFailure: <A, E, R>(self: STM<A, E, R>) => STM<boolean, never, R> = stm.isFailure\n\n/**\n * Returns whether this transactional effect is a success.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isSuccess: <A, E, R>(self: STM<A, E, R>) => STM<boolean, never, R> = stm.isSuccess\n\n/**\n * Iterates with the specified transactional function. The moral equivalent\n * of:\n *\n * ```ts skip-type-checking\n * const s = initial\n *\n * while (cont(s)) {\n *   s = body(s)\n * }\n *\n * return s\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const iterate: <Z, E, R>(\n  initial: Z,\n  options: {\n    readonly while: Predicate<Z>\n    readonly body: (z: Z) => STM<Z, E, R>\n  }\n) => STM<Z, E, R> = stm.iterate\n\n/**\n * Loops with the specified transactional function, collecting the results\n * into a list. The moral equivalent of:\n *\n * ```ts skip-type-checking\n * const as = []\n * let s  = initial\n *\n * while (cont(s)) {\n *   as.push(body(s))\n *   s  = inc(s)\n * }\n *\n * return as\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const loop: {\n  <Z, A, E, R>(\n    initial: Z,\n    options: {\n      readonly while: (z: Z) => boolean\n      readonly step: (z: Z) => Z\n      readonly body: (z: Z) => STM<A, E, R>\n      readonly discard?: false | undefined\n    }\n  ): STM<Array<A>, E, R>\n  <Z, A, E, R>(\n    initial: Z,\n    options: {\n      readonly while: (z: Z) => boolean\n      readonly step: (z: Z) => Z\n      readonly body: (z: Z) => STM<A, E, R>\n      readonly discard: true\n    }\n  ): STM<void, E, R>\n} = stm.loop\n\n/**\n * Maps the value produced by the effect.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): <E, R>(self: STM<A, E, R>) => STM<B, E, R>\n  <A, E, R, B>(self: STM<A, E, R>, f: (a: A) => B): STM<B, E, R>\n} = core.map\n\n/**\n * Maps the value produced by the effect with the specified function that may\n * throw exceptions but is otherwise pure, translating any thrown exceptions\n * into typed failed effects.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapAttempt: {\n  <A, B>(f: (a: A) => B): <E, R>(self: STM<A, E, R>) => STM<B, unknown, R>\n  <A, E, R, B>(self: STM<A, E, R>, f: (a: A) => B): STM<B, unknown, R>\n} = stm.mapAttempt\n\n/**\n * Returns an `STM` effect whose failure and success channels have been mapped\n * by the specified pair of functions, `f` and `g`.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapBoth: {\n  <E, E2, A, A2>(\n    options: { readonly onFailure: (error: E) => E2; readonly onSuccess: (value: A) => A2 }\n  ): <R>(self: STM<A, E, R>) => STM<A2, E2, R>\n  <A, E, R, E2, A2>(\n    self: STM<A, E, R>,\n    options: { readonly onFailure: (error: E) => E2; readonly onSuccess: (value: A) => A2 }\n  ): STM<A2, E2, R>\n} = stm.mapBoth\n\n/**\n * Maps from one error type to another.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapError: {\n  <E, E2>(f: (error: E) => E2): <A, R>(self: STM<A, E, R>) => STM<A, E2, R>\n  <A, E, R, E2>(self: STM<A, E, R>, f: (error: E) => E2): STM<A, E2, R>\n} = stm.mapError\n\n/**\n * Returns a new effect where the error channel has been merged into the\n * success channel to their common combined type.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const merge: <A, E, R>(self: STM<A, E, R>) => STM<E | A, never, R> = stm.merge\n\n/**\n * Merges an `Iterable<STM>` to a single `STM`, working sequentially.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const mergeAll: {\n  <A2, A>(zero: A2, f: (a2: A2, a: A) => A2): <E, R>(iterable: Iterable<STM<A, E, R>>) => STM<A2, E, R>\n  <A, E, R, A2>(iterable: Iterable<STM<A, E, R>>, zero: A2, f: (a2: A2, a: A) => A2): STM<A2, E, R>\n} = stm.mergeAll\n\n/**\n * Returns a new effect where boolean value of this effect is negated.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const negate: <E, R>(self: STM<boolean, E, R>) => STM<boolean, E, R> = stm.negate\n\n/**\n * Requires the option produced by this value to be `None`.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const none: <A, E, R>(self: STM<Option.Option<A>, E, R>) => STM<void, Option.Option<E>, R> = stm.none\n\n/**\n * Converts the failure channel into an `Option`.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const option: <A, E, R>(self: STM<A, E, R>) => STM<Option.Option<A>, never, R> = stm.option\n\n/**\n * Translates `STM` effect failure into death of the fiber, making all\n * failures unchecked and not a part of the type of the effect.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orDie: <A, E, R>(self: STM<A, E, R>) => STM<A, never, R> = stm.orDie\n\n/**\n * Keeps none of the errors, and terminates the fiber running the `STM` effect\n * with them, using the specified function to convert the `E` into a defect.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orDieWith: {\n  <E>(f: (error: E) => unknown): <A, R>(self: STM<A, E, R>) => STM<A, never, R>\n  <A, E, R>(self: STM<A, E, R>, f: (error: E) => unknown): STM<A, never, R>\n} = stm.orDieWith\n\n/**\n * Tries this effect first, and if it fails or retries, tries the other\n * effect.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElse: {\n  <A2, E2, R2>(that: LazyArg<STM<A2, E2, R2>>): <A, E, R>(self: STM<A, E, R>) => STM<A2 | A, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(self: STM<A, E, R>, that: LazyArg<STM<A2, E2, R2>>): STM<A | A2, E2, R | R2>\n} = stm.orElse\n\n/**\n * Returns a transactional effect that will produce the value of this effect\n * in left side, unless it fails or retries, in which case, it will produce\n * the value of the specified effect in right side.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElseEither: {\n  <A2, E2, R2>(that: LazyArg<STM<A2, E2, R2>>): <A, E, R>(self: STM<A, E, R>) => STM<Either.Either<A2, A>, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(self: STM<A, E, R>, that: LazyArg<STM<A2, E2, R2>>): STM<Either.Either<A2, A>, E2, R | R2>\n} = stm.orElseEither\n\n/**\n * Tries this effect first, and if it fails or retries, fails with the\n * specified error.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElseFail: {\n  <E2>(error: LazyArg<E2>): <A, E, R>(self: STM<A, E, R>) => STM<A, E2, R>\n  <A, E, R, E2>(self: STM<A, E, R>, error: LazyArg<E2>): STM<A, E2, R>\n} = stm.orElseFail\n\n/**\n * Returns an effect that will produce the value of this effect, unless it\n * fails with the `None` value, in which case it will produce the value of the\n * specified effect.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElseOptional: {\n  <A2, E2, R2>(\n    that: LazyArg<STM<A2, Option.Option<E2>, R2>>\n  ): <A, E, R>(self: STM<A, Option.Option<E>, R>) => STM<A2 | A, Option.Option<E2 | E>, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: STM<A, Option.Option<E>, R>,\n    that: LazyArg<STM<A2, Option.Option<E2>, R2>>\n  ): STM<A | A2, Option.Option<E | E2>, R | R2>\n} = stm.orElseOptional\n\n/**\n * Tries this effect first, and if it fails or retries, succeeds with the\n * specified value.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElseSucceed: {\n  <A2>(value: LazyArg<A2>): <A, E, R>(self: STM<A, E, R>) => STM<A2 | A, never, R>\n  <A, E, R, A2>(self: STM<A, E, R>, value: LazyArg<A2>): STM<A | A2, never, R>\n} = stm.orElseSucceed\n\n/**\n * Tries this effect first, and if it enters retry, then it tries the other\n * effect. This is an equivalent of Haskell's orElse.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orTry: {\n  <A1, E1, R1>(that: LazyArg<STM<A1, E1, R1>>): <A, E, R>(self: STM<A, E, R>) => STM<A1 | A, E1 | E, R1 | R>\n  <A, E, R, A1, E1, R1>(self: STM<A, E, R>, that: LazyArg<STM<A1, E1, R1>>): STM<A | A1, E | E1, R | R1>\n} = core.orTry\n\n/**\n * Feeds elements of type `A` to a function `f` that returns an effect.\n * Collects all successes and failures in a tupled fashion.\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const partition: {\n  <A, A2, E, R>(\n    f: (a: A) => STM<A2, E, R>\n  ): (elements: Iterable<A>) => STM<[excluded: Array<E>, satisfying: Array<A2>], never, R>\n  <A, A2, E, R>(\n    elements: Iterable<A>,\n    f: (a: A) => STM<A2, E, R>\n  ): STM<[excluded: Array<E>, satisfying: Array<A2>], never, R>\n} = stm.partition\n\n/**\n * Provides the transaction its required environment, which eliminates its\n * dependency on `R`.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideContext: {\n  <R>(env: Context.Context<R>): <A, E>(self: STM<A, E, R>) => STM<A, E>\n  <A, E, R>(self: STM<A, E, R>, env: Context.Context<R>): STM<A, E>\n} = stm.provideContext\n\n/**\n * Splits the context into two parts, providing one part using the\n * specified layer and leaving the remainder `R0`.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideSomeContext: {\n  <R>(context: Context.Context<R>): <R1, E, A>(self: STM<A, E, R1>) => STM<A, E, Exclude<R1, R>>\n  <R, R1, E, A>(self: STM<A, E, R1>, context: Context.Context<R>): STM<A, E, Exclude<R1, R>>\n} = stm.provideSomeContext\n\n/**\n * Provides the effect with the single service it requires. If the transactional\n * effect requires more than one service use `provideEnvironment` instead.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideService: {\n  <I, S>(tag: Context.Tag<I, S>, resource: NoInfer<S>): <A, E, R>(self: STM<A, E, R>) => STM<A, E, Exclude<R, I>>\n  <A, E, R, I, S>(self: STM<A, E, R>, tag: Context.Tag<I, S>, resource: NoInfer<S>): STM<A, E, Exclude<R, I>>\n} = stm.provideService\n\n/**\n * Provides the effect with the single service it requires. If the transactional\n * effect requires more than one service use `provideEnvironment` instead.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideServiceSTM: {\n  <I, S, E1, R1>(\n    tag: Context.Tag<I, S>,\n    stm: STM<NoInfer<S>, E1, R1>\n  ): <A, E, R>(self: STM<A, E, R>) => STM<A, E1 | E, R1 | Exclude<R, I>>\n  <A, E, R, I, S, E1, R1>(\n    self: STM<A, E, R>,\n    tag: Context.Tag<I, S>,\n    stm: STM<NoInfer<S>, E1, R1>\n  ): STM<A, E1 | E, R1 | Exclude<R, I>>\n} = stm.provideServiceSTM\n\n/**\n * Folds an `Iterable<A>` using an effectual function f, working sequentially\n * from left to right.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const reduce: {\n  <S, A, E, R>(zero: S, f: (s: S, a: A) => STM<S, E, R>): (iterable: Iterable<A>) => STM<S, E, R>\n  <S, A, E, R>(iterable: Iterable<A>, zero: S, f: (s: S, a: A) => STM<S, E, R>): STM<S, E, R>\n} = stm.reduce\n\n/**\n * Reduces an `Iterable<STM>` to a single `STM`, working sequentially.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const reduceAll: {\n  <A, E2, R2>(\n    initial: STM<A, E2, R2>,\n    f: (x: A, y: A) => A\n  ): <E, R>(iterable: Iterable<STM<A, E, R>>) => STM<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(\n    iterable: Iterable<STM<A, E, R>>,\n    initial: STM<A, E2, R2>,\n    f: (x: A, y: A) => A\n  ): STM<A, E | E2, R | R2>\n} = stm.reduceAll\n\n/**\n * Folds an `Iterable<A>` using an effectual function f, working sequentially\n * from right to left.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const reduceRight: {\n  <S, A, R, E>(zero: S, f: (s: S, a: A) => STM<S, E, R>): (iterable: Iterable<A>) => STM<S, E, R>\n  <S, A, R, E>(iterable: Iterable<A>, zero: S, f: (s: S, a: A) => STM<S, E, R>): STM<S, E, R>\n} = stm.reduceRight\n\n/**\n * Keeps some of the errors, and terminates the fiber with the rest.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const refineOrDie: {\n  <E, E2>(pf: (error: E) => Option.Option<E2>): <A, R>(self: STM<A, E, R>) => STM<A, E2, R>\n  <A, E, R, E2>(self: STM<A, E, R>, pf: (error: E) => Option.Option<E2>): STM<A, E2, R>\n} = stm.refineOrDie\n\n/**\n * Keeps some of the errors, and terminates the fiber with the rest, using the\n * specified function to convert the `E` into a `Throwable`.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const refineOrDieWith: {\n  <E, E2>(pf: (error: E) => Option.Option<E2>, f: (error: E) => unknown): <A, R>(self: STM<A, E, R>) => STM<A, E2, R>\n  <A, E, R, E2>(self: STM<A, E, R>, pf: (error: E) => Option.Option<E2>, f: (error: E) => unknown): STM<A, E2, R>\n} = stm.refineOrDieWith\n\n/**\n * Fail with the returned value if the `PartialFunction` matches, otherwise\n * continue with our held value.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const reject: {\n  <A, E2>(pf: (a: A) => Option.Option<E2>): <E, R>(self: STM<A, E, R>) => STM<A, E2 | E, R>\n  <A, E, R, E2>(self: STM<A, E, R>, pf: (a: A) => Option.Option<E2>): STM<A, E | E2, R>\n} = stm.reject\n\n/**\n * Continue with the returned computation if the specified partial function\n * matches, translating the successful match into a failure, otherwise continue\n * with our held value.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const rejectSTM: {\n  <A, E2, R2>(pf: (a: A) => Option.Option<STM<E2, E2, R2>>): <E, R>(self: STM<A, E, R>) => STM<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(self: STM<A, E, R>, pf: (a: A) => Option.Option<STM<E2, E2, R2>>): STM<A, E | E2, R | R2>\n} = stm.rejectSTM\n\n/**\n * Repeats this `STM` effect until its result satisfies the specified\n * predicate.\n *\n * **WARNING**: `repeatUntil` uses a busy loop to repeat the effect and will\n * consume a thread until it completes (it cannot yield). This is because STM\n * describes a single atomic transaction which must either complete, retry or\n * fail a transaction before yielding back to the Effect runtime.\n *   - Use `retryUntil` instead if you don't need to maintain transaction\n *     state for repeats.\n *   - Ensure repeating the STM effect will eventually satisfy the predicate.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const repeatUntil: {\n  <A>(predicate: Predicate<A>): <E, R>(self: STM<A, E, R>) => STM<A, E, R>\n  <A, E, R>(self: STM<A, E, R>, predicate: Predicate<A>): STM<A, E, R>\n} = stm.repeatUntil\n\n/**\n * Repeats this `STM` effect while its result satisfies the specified\n * predicate.\n *\n * **WARNING**: `repeatWhile` uses a busy loop to repeat the effect and will\n * consume a thread until it completes (it cannot yield). This is because STM\n * describes a single atomic transaction which must either complete, retry or\n * fail a transaction before yielding back to the Effect runtime.\n *   - Use `retryWhile` instead if you don't need to maintain transaction\n *     state for repeats.\n *   - Ensure repeating the STM effect will eventually not satisfy the\n *     predicate.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const repeatWhile: {\n  <A>(predicate: Predicate<A>): <E, R>(self: STM<A, E, R>) => STM<A, E, R>\n  <A, E, R>(self: STM<A, E, R>, predicate: Predicate<A>): STM<A, E, R>\n} = stm.repeatWhile\n\n/**\n * Replicates the given effect n times. If 0 or negative numbers are given, an\n * empty `Chunk` will be returned.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const replicate: {\n  (n: number): <A, E, R>(self: STM<A, E, R>) => Array<STM<A, E, R>>\n  <A, E, R>(self: STM<A, E, R>, n: number): Array<STM<A, E, R>>\n} = stm.replicate\n\n/**\n * Performs this transaction the specified number of times and collects the\n * results.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const replicateSTM: {\n  (n: number): <A, E, R>(self: STM<A, E, R>) => STM<Array<A>, E, R>\n  <A, E, R>(self: STM<A, E, R>, n: number): STM<Array<A>, E, R>\n} = stm.replicateSTM\n\n/**\n * Performs this transaction the specified number of times, discarding the\n * results.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const replicateSTMDiscard: {\n  (n: number): <A, E, R>(self: STM<A, E, R>) => STM<void, E, R>\n  <A, E, R>(self: STM<A, E, R>, n: number): STM<void, E, R>\n} = stm.replicateSTMDiscard\n\n/**\n * Abort and retry the whole transaction when any of the underlying\n * transactional variables have changed.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const retry: STM<never> = core.retry\n\n/**\n * Filters the value produced by this effect, retrying the transaction until\n * the predicate returns `true` for the value.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const retryUntil: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): <E, R>(self: STM<A, E, R>) => STM<B, E, R>\n  <A>(predicate: Predicate<A>): <E, R>(self: STM<A, E, R>) => STM<A, E, R>\n  <A, E, R, B extends A>(self: STM<A, E, R>, refinement: Refinement<A, B>): STM<B, E, R>\n  <A, E, R>(self: STM<A, E, R>, predicate: Predicate<A>): STM<A, E, R>\n} = stm.retryUntil\n\n/**\n * Filters the value produced by this effect, retrying the transaction while\n * the predicate returns `true` for the value.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const retryWhile: {\n  <A>(predicate: Predicate<A>): <E, R>(self: STM<A, E, R>) => STM<A, E, R>\n  <A, E, R>(self: STM<A, E, R>, predicate: Predicate<A>): STM<A, E, R>\n} = stm.retryWhile\n\n/**\n * Converts an option on values into an option on errors.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const some: <A, E, R>(self: STM<Option.Option<A>, E, R>) => STM<A, Option.Option<E>, R> = stm.some\n\n/**\n * Returns an `STM` effect that succeeds with the specified value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeed: <A>(value: A) => STM<A> = core.succeed\n\n/**\n * Returns an effect with the empty value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeedNone: STM<Option.Option<never>> = stm.succeedNone\n\n/**\n * Returns an effect with the optional value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeedSome: <A>(value: A) => STM<Option.Option<A>> = stm.succeedSome\n\n/**\n * Summarizes a `STM` effect by computing a provided value before and after\n * execution, and then combining the values to produce a summary, together\n * with the result of execution.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const summarized: {\n  <A2, E2, R2, A3>(\n    summary: STM<A2, E2, R2>,\n    f: (before: A2, after: A2) => A3\n  ): <A, E, R>(self: STM<A, E, R>) => STM<[A3, A], E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2, A3>(\n    self: STM<A, E, R>,\n    summary: STM<A2, E2, R2>,\n    f: (before: A2, after: A2) => A3\n  ): STM<[A3, A], E | E2, R | R2>\n} = stm.summarized\n\n/**\n * Suspends creation of the specified transaction lazily.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const suspend: <A, E, R>(evaluate: LazyArg<STM<A, E, R>>) => STM<A, E, R> = stm.suspend\n\n/**\n * Returns an `STM` effect that succeeds with the specified lazily evaluated\n * value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sync: <A>(evaluate: () => A) => STM<A> = core.sync\n\n/**\n * \"Peeks\" at the success of transactional effect.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tap: {\n  <A, X, E2, R2>(f: (a: A) => STM<X, E2, R2>): <E, R>(self: STM<A, E, R>) => STM<A, E2 | E, R2 | R>\n  <A, E, R, X, E2, R2>(self: STM<A, E, R>, f: (a: A) => STM<X, E2, R2>): STM<A, E | E2, R | R2>\n} = stm.tap\n\n/**\n * \"Peeks\" at both sides of an transactional effect.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tapBoth: {\n  <XE extends E, A2, E2, R2, XA extends A, A3, E3, R3, A, E>(\n    options: { readonly onFailure: (error: XE) => STM<A2, E2, R2>; readonly onSuccess: (value: XA) => STM<A3, E3, R3> }\n  ): <R>(self: STM<A, E, R>) => STM<A, E | E2 | E3, R2 | R3 | R>\n  <A, E, R, XE extends E, A2, E2, R2, XA extends A, A3, E3, R3>(\n    self: STM<A, E, R>,\n    options: { readonly onFailure: (error: XE) => STM<A2, E2, R2>; readonly onSuccess: (value: XA) => STM<A3, E3, R3> }\n  ): STM<A, E | E2 | E3, R | R2 | R3>\n} = stm.tapBoth\n\n/**\n * \"Peeks\" at the error of the transactional effect.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tapError: {\n  <E, X, E2, R2>(f: (error: NoInfer<E>) => STM<X, E2, R2>): <A, R>(self: STM<A, E, R>) => STM<A, E | E2, R2 | R>\n  <A, E, R, X, E2, R2>(self: STM<A, E, R>, f: (error: E) => STM<X, E2, R2>): STM<A, E | E2, R | R2>\n} = stm.tapError\n\nconst try_: {\n  <A, E>(options: {\n    readonly try: LazyArg<A>\n    readonly catch: (u: unknown) => E\n  }): STM<A, E>\n  <A>(try_: LazyArg<A>): STM<A, unknown>\n} = stm.try_\n\nexport {\n  /**\n   * Imports a synchronous side-effect into a pure value, translating any thrown\n   * exceptions into typed failed effects.\n   *\n   * @since 2.0.0\n   * @category constructors\n   */\n  try_ as try\n}\n\n/**\n * The moral equivalent of `if (!p) exp`\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const unless: {\n  (predicate: LazyArg<boolean>): <A, E, R>(self: STM<A, E, R>) => STM<Option.Option<A>, E, R>\n  <A, E, R>(self: STM<A, E, R>, predicate: LazyArg<boolean>): STM<Option.Option<A>, E, R>\n} = stm.unless\n\n/**\n * The moral equivalent of `if (!p) exp` when `p` has side-effects\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const unlessSTM: {\n  <E2, R2>(predicate: STM<boolean, E2, R2>): <A, E, R>(self: STM<A, E, R>) => STM<Option.Option<A>, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(self: STM<A, E, R>, predicate: STM<boolean, E2, R2>): STM<Option.Option<A>, E | E2, R | R2>\n} = stm.unlessSTM\n\n/**\n * Converts an option on errors into an option on values.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const unsome: <A, E, R>(self: STM<A, Option.Option<E>, R>) => STM<Option.Option<A>, E, R> = stm.unsome\n\nconst void_: STM<void> = stm.void\nexport {\n  /**\n   * Returns an `STM` effect that succeeds with `void`.\n   *\n   * @since 2.0.0\n   * @category constructors\n   */\n  void_ as void\n}\n\n/**\n * Feeds elements of type `A` to `f` and accumulates all errors in error\n * channel or successes in success channel.\n *\n * This combinator is lossy meaning that if there are errors all successes\n * will be lost. To retain all information please use `STM.partition`.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const validateAll: {\n  <A, B, E, R>(f: (a: A) => STM<B, E, R>): (elements: Iterable<A>) => STM<Array<B>, [E, ...Array<E>], R>\n  <A, B, E, R>(elements: Iterable<A>, f: (a: A) => STM<B, E, R>): STM<Array<B>, [E, ...Array<E>], R>\n} = stm.validateAll\n\n/**\n * Feeds elements of type `A` to `f` until it succeeds. Returns first success\n * or the accumulation of all errors.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const validateFirst: {\n  <A, B, E, R>(f: (a: A) => STM<B, E, R>): (elements: Iterable<A>) => STM<B, Array<E>, R>\n  <A, B, E, R>(elements: Iterable<A>, f: (a: A) => STM<B, E, R>): STM<B, Array<E>, R>\n} = stm.validateFirst\n\n/**\n * The moral equivalent of `if (p) exp`.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const when: {\n  (predicate: LazyArg<boolean>): <A, E, R>(self: STM<A, E, R>) => STM<Option.Option<A>, E, R>\n  <A, E, R>(self: STM<A, E, R>, predicate: LazyArg<boolean>): STM<Option.Option<A>, E, R>\n} = stm.when\n\n/**\n * The moral equivalent of `if (p) exp` when `p` has side-effects.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const whenSTM: {\n  <E2, R2>(predicate: STM<boolean, E2, R2>): <A, E, R>(self: STM<A, E, R>) => STM<Option.Option<A>, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(self: STM<A, E, R>, predicate: STM<boolean, E2, R2>): STM<Option.Option<A>, E | E2, R | R2>\n} = stm.whenSTM\n\n/**\n * Sequentially zips this value with the specified one.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zip: {\n  <A1, E1, R1>(that: STM<A1, E1, R1>): <A, E, R>(self: STM<A, E, R>) => STM<[A, A1], E1 | E, R1 | R>\n  <A, E, R, A1, E1, R1>(self: STM<A, E, R>, that: STM<A1, E1, R1>): STM<[A, A1], E | E1, R | R1>\n} = core.zip\n\n/**\n * Sequentially zips this value with the specified one, discarding the second\n * element of the tuple.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipLeft: {\n  <A1, E1, R1>(that: STM<A1, E1, R1>): <A, E, R>(self: STM<A, E, R>) => STM<A, E1 | E, R1 | R>\n  <A, E, R, A1, E1, R1>(self: STM<A, E, R>, that: STM<A1, E1, R1>): STM<A, E | E1, R | R1>\n} = core.zipLeft\n\n/**\n * Sequentially zips this value with the specified one, discarding the first\n * element of the tuple.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipRight: {\n  <A1, E1, R1>(that: STM<A1, E1, R1>): <A, E, R>(self: STM<A, E, R>) => STM<A1, E1 | E, R1 | R>\n  <A, E, R, A1, E1, R1>(self: STM<A, E, R>, that: STM<A1, E1, R1>): STM<A1, E | E1, R | R1>\n} = core.zipRight\n\n/**\n * Sequentially zips this value with the specified one, combining the values\n * using the specified combiner function.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWith: {\n  <A1, E1, R1, A, A2>(\n    that: STM<A1, E1, R1>,\n    f: (a: A, b: A1) => A2\n  ): <E, R>(self: STM<A, E, R>) => STM<A2, E1 | E, R1 | R>\n  <A, E, R, A1, E1, R1, A2>(self: STM<A, E, R>, that: STM<A1, E1, R1>, f: (a: A, b: A1) => A2): STM<A2, E | E1, R | R1>\n} = core.zipWith\n\n/**\n * This function takes an iterable of `STM` values and returns a new\n * `STM` value that represents the first `STM` value in the iterable\n * that succeeds. If all of the `Effect` values in the iterable fail, then\n * the resulting `STM` value will fail as well.\n *\n * This function is sequential, meaning that the `STM` values in the\n * iterable will be executed in sequence, and the first one that succeeds\n * will determine the outcome of the resulting `STM` value.\n *\n * Returns a new `STM` value that represents the first successful\n * `STM` value in the iterable, or a failed `STM` value if all of the\n * `STM` values in the iterable fail.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const firstSuccessOf = <A, E, R>(effects: Iterable<STM<A, E, R>>): STM<A, E, R> =>\n  suspend<A, E, R>(() => {\n    const list = Chunk.fromIterable(effects)\n    if (!Chunk.isNonEmpty(list)) {\n      return dieSync(() => new Cause.IllegalArgumentException(`Received an empty collection of effects`))\n    }\n    return Chunk.reduce(\n      Chunk.tailNonEmpty(list),\n      Chunk.headNonEmpty(list),\n      (left, right) => orElse(left, () => right)\n    )\n  })\n\n/**\n * @category do notation\n * @since 2.0.0\n */\nexport const Do: STM<{}> = succeed({})\n\n/**\n * @category do notation\n * @since 2.0.0\n */\nexport const bind: {\n  <N extends string, K, A, E2, R2>(\n    tag: Exclude<N, keyof K>,\n    f: (_: NoInfer<K>) => STM<A, E2, R2>\n  ): <E, R>(self: STM<K, E, R>) => STM<MergeRecord<K, { [k in N]: A }>, E2 | E, R2 | R>\n  <K, E, R, N extends string, A, E2, R2>(\n    self: STM<K, E, R>,\n    tag: Exclude<N, keyof K>,\n    f: (_: NoInfer<K>) => STM<A, E2, R2>\n  ): STM<MergeRecord<K, { [k in N]: A }>, E | E2, R | R2>\n} = stm.bind\n\nconst let_: {\n  <N extends string, K, A>(\n    tag: Exclude<N, keyof K>,\n    f: (_: NoInfer<K>) => A\n  ): <E, R>(self: STM<K, E, R>) => STM<MergeRecord<K, { [k in N]: A }>, E, R>\n  <K, E, R, N extends string, A>(\n    self: STM<K, E, R>,\n    tag: Exclude<N, keyof K>,\n    f: (_: NoInfer<K>) => A\n  ): STM<MergeRecord<K, { [k in N]: A }>, E, R>\n} = stm.let_\n\nexport {\n  /**\n   * @category do notation\n   * @since 2.0.0\n   */\n  let_ as let\n}\n\n/**\n * @category do notation\n * @since 2.0.0\n */\nexport const bindTo: {\n  <N extends string>(tag: N): <A, E, R>(self: STM<A, E, R>) => STM<Record<N, A>, E, R>\n  <A, E, R, N extends string>(self: STM<A, E, R>, tag: N): STM<Record<N, A>, E, R>\n} = stm.bindTo\n"
  },
  {
    "path": "packages/effect/src/Schedule.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as Cron from \"./Cron.js\"\nimport type * as DateTime from \"./DateTime.js\"\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport * as internal from \"./internal/schedule.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate } from \"./Predicate.js\"\nimport type * as Ref from \"./Ref.js\"\nimport type * as ScheduleDecision from \"./ScheduleDecision.js\"\nimport type * as Intervals from \"./ScheduleIntervals.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport const ScheduleTypeId: unique symbol = internal.ScheduleTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type ScheduleTypeId = typeof ScheduleTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport const ScheduleDriverTypeId: unique symbol = internal.ScheduleDriverTypeId\n\n/**\n * @since 2.0.0\n * @category Symbols\n */\nexport type ScheduleDriverTypeId = typeof ScheduleDriverTypeId\n\n/**\n * A `Schedule<Out, In, R>` defines a recurring schedule, which consumes values\n * of type `In`, and which returns values of type `Out`.\n *\n * The `Schedule` type is structured as follows:\n *\n * ```ts skip-type-checking\n * //        ┌─── The type of output produced by the schedule\n * //        │   ┌─── The type of input consumed by the schedule\n * //        │   │     ┌─── Additional requirements for the schedule\n * //        ▼   ▼     ▼\n * Schedule<Out, In, Requirements>\n * ```\n *\n * A schedule operates by consuming values of type `In` (such as errors in the\n * case of `Effect.retry`, or values in the case of `Effect.repeat`) and\n * producing values of type `Out`. It determines when to halt or continue the\n * execution based on input values and its internal state.\n *\n * The inclusion of a `Requirements` parameter allows the schedule to leverage\n * additional services or resources as needed.\n *\n * Schedules are defined as a possibly infinite set of intervals spread out over\n * time. Each interval defines a window in which recurrence is possible.\n *\n * When schedules are used to repeat or retry effects, the starting boundary of\n * each interval produced by a schedule is used as the moment when the effect\n * will be executed again.\n *\n * Schedules can be composed in different ways:\n *\n * - Union: Combines two schedules and recurs if either schedule wants to\n *   continue, using the shorter delay.\n * - Intersection: Combines two schedules and recurs only if both schedules want\n *   to continue, using the longer delay.\n * - Sequencing: Combines two schedules by running the first one fully, then\n *   switching to the second.\n *\n * In addition, schedule inputs and outputs can be transformed, filtered (to\n * terminate a schedule early in response to some input or output), and so\n * forth.\n *\n * A variety of other operators exist for transforming and combining schedules,\n * and the companion object for `Schedule` contains all common types of\n * schedules, both for performing retrying, as well as performing repetition.\n *\n * @category Model\n * @since 2.0.0\n */\nexport interface Schedule<out Out, in In = unknown, out R = never> extends Schedule.Variance<Out, In, R>, Pipeable {\n  /**\n   * Initial State\n   */\n  readonly initial: any\n  /**\n   * Schedule Step\n   */\n  step(\n    now: number,\n    input: In,\n    state: any\n  ): Effect.Effect<readonly [any, Out, ScheduleDecision.ScheduleDecision], never, R>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Schedule {\n  /**\n   * @since 2.0.0\n   * @category Models\n   */\n  export interface Variance<out Out, in In, out R> {\n    readonly [ScheduleTypeId]: {\n      readonly _Out: Types.Covariant<Out>\n      readonly _In: Types.Contravariant<In>\n      readonly _R: Types.Covariant<R>\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  export interface DriverVariance<out Out, in In, out R> {\n    readonly [ScheduleDriverTypeId]: {\n      readonly _Out: Types.Covariant<Out>\n      readonly _In: Types.Contravariant<In>\n      readonly _R: Types.Covariant<R>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category Models\n */\nexport interface ScheduleDriver<out Out, in In = unknown, out R = never> extends Schedule.DriverVariance<Out, In, R> {\n  readonly state: Effect.Effect<unknown>\n  readonly iterationMeta: Ref.Ref<IterationMetadata>\n  readonly last: Effect.Effect<Out, Cause.NoSuchElementException>\n  readonly reset: Effect.Effect<void>\n  next(input: In): Effect.Effect<Out, Option.Option<never>, R>\n}\n\n/**\n * Creates a new schedule with a custom state and step function.\n *\n * **Details**\n *\n * This function constructs a `Schedule` by defining its initial state and a\n * step function, which determines how the schedule progresses over time. The\n * step function is called on each iteration with the current time, an input\n * value, and the schedule's current state. It returns the next state, an output\n * value, and a decision on whether the schedule should continue or stop.\n *\n * This function is useful for creating custom scheduling logic that goes beyond\n * predefined schedules like fixed intervals or exponential backoff. It allows\n * full control over how the schedule behaves at each step.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const makeWithState: <S, In, Out, R = never>(\n  initial: S,\n  step: (\n    now: number,\n    input: In,\n    state: S\n  ) => Effect.Effect<readonly [S, Out, ScheduleDecision.ScheduleDecision], never, R>\n) => Schedule<Out, In, R> = internal.makeWithState\n\n/**\n * Checks whether a given value is a `Schedule`.\n *\n * @since 2.0.0\n * @category Guards\n */\nexport const isSchedule: (u: unknown) => u is Schedule<unknown, never, unknown> = internal.isSchedule\n\n/**\n * Adds a delay to every interval in a schedule.\n *\n * **Details**\n *\n * This function modifies a given schedule by applying an additional delay to\n * every interval it defines. The delay is determined by the provided function,\n * which takes the schedule's output and returns a delay duration.\n *\n * @see {@link addDelayEffect} If you need to compute the delay using an effectful function.\n *\n * @since 2.0.0\n * @category Timing & Delay\n */\nexport const addDelay: {\n  <Out>(f: (out: Out) => Duration.DurationInput): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(self: Schedule<Out, In, R>, f: (out: Out) => Duration.DurationInput): Schedule<Out, In, R>\n} = internal.addDelay\n\n/**\n * Adds an effectfully computed delay to every interval in a schedule.\n *\n * **Details**\n *\n * This function modifies a given schedule by applying an additional delay to\n * each interval, where the delay is determined by an effectful function. The\n * function takes the schedule’s output and returns an effect that produces a\n * delay duration.\n *\n * @see {@link addDelay} If you need to compute the delay using a pure function.\n *\n * @since 2.0.0\n * @category Timing & Delay\n */\nexport const addDelayEffect: {\n  <Out, R2>(\n    f: (out: Out) => Effect.Effect<Duration.DurationInput, never, R2>\n  ): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R2 | R>\n  <Out, In, R, R2>(\n    self: Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<Duration.DurationInput, never, R2>\n  ): Schedule<Out, In, R | R2>\n} = internal.addDelayEffect\n\n/**\n * Runs two schedules sequentially, merging their outputs.\n *\n * **Details**\n *\n * This function executes two schedules one after the other. The first schedule\n * runs to completion, and then the second schedule begins execution. Unlike\n * {@link andThenEither}, this function merges the outputs instead of wrapping\n * them in `Either`, allowing both schedules to contribute their results\n * directly.\n *\n * This is useful when a workflow consists of two phases where the second phase\n * should start only after the first one has fully completed.\n *\n * @see {@link andThenEither} If you need to keep track of which schedule\n * produced each result.\n *\n * @since 2.0.0\n * @category Sequential Composition\n */\nexport const andThen: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out2 | Out, In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>\n  ): Schedule<Out | Out2, In & In2, R | R2>\n} = internal.andThen\n\n/**\n * Runs two schedules sequentially, collecting results in an `Either`.\n *\n * **Details**\n *\n * This function combines two schedules in sequence. The first schedule runs to\n * completion, and then the second schedule starts and runs to completion as\n * well. The outputs of both schedules are collected into an `Either` structure:\n * - `Either.Left` contains the output of the second schedule.\n * - `Either.Right` contains the output of the first schedule.\n *\n * This is useful when you need to switch from one schedule to another after the\n * first one finishes, while still keeping track of which schedule produced each\n * result.\n *\n * @see {@link andThen} If you need to merge the outputs of both schedules.\n *\n * @since 2.0.0\n * @category Sequential Composition\n */\nexport const andThenEither: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Either.Either<Out2, Out>, In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>\n  ): Schedule<Either.Either<Out2, Out>, In & In2, R | R2>\n} = internal.andThenEither\n\n/**\n * Transforms a schedule to always produce a constant output.\n *\n * **Details**\n *\n * This function modifies a given schedule so that instead of returning its\n * computed outputs, it always returns a constant value.\n *\n * This is useful when you need a schedule for timing but don’t care about its\n * actual output, or when you want to standardize results across different\n * scheduling strategies.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const as: {\n  <Out2>(out: Out2): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out2, In, R>\n  <Out, In, R, Out2>(self: Schedule<Out, In, R>, out: Out2): Schedule<Out2, In, R>\n} = internal.as\n\n/**\n * Transforms a schedule to always return `void` instead of its output.\n *\n * **Details**\n *\n * This function modifies a given schedule so that it no longer returns\n * meaningful output—each execution produces `void`. This is useful when the\n * schedule is used only for timing purposes and the actual output of the\n * schedule is irrelevant.\n *\n * The schedule still determines when executions should occur, but the results\n * are discarded.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const asVoid: <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<void, In, R> = internal.asVoid\n\n// TODO(4.0): rename to `zip`?\n/**\n * Combines two schedules, preserving both their inputs and outputs.\n *\n * **Details**\n *\n * This function merges two schedules so that both their input types and output\n * types are retained. When executed, the resulting schedule will take inputs\n * from both original schedules and produce a tuple containing both outputs.\n *\n * It recurs if either schedule wants to continue, using the shorter delay.\n *\n * This is useful when you want to track multiple schedules simultaneously,\n * ensuring that both receive the same inputs and produce combined results.\n *\n * @since 2.0.0\n * @category Zipping\n */\nexport const bothInOut: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<[Out, Out2], readonly [In, In2], R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>\n  ): Schedule<[Out, Out2], readonly [In, In2], R | R2>\n} = internal.bothInOut\n\n/**\n * Filters schedule executions based on a custom condition.\n *\n * **Details**\n *\n * This function modifies a schedule by applying a custom test function to each\n * input-output pair. The test function determines whether the schedule should\n * continue or stop. If the function returns `true`, the schedule proceeds as\n * usual; if it returns `false`, the schedule terminates.\n *\n * This is useful for conditional retries, custom stop conditions, or\n * dynamically controlling execution based on observed inputs and outputs.\n *\n * @see {@link checkEffect} If you need to use an effectful test function.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const check: {\n  <In, Out>(test: (input: In, output: Out) => boolean): <R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(self: Schedule<Out, In, R>, test: (input: In, output: Out) => boolean): Schedule<Out, In, R>\n} = internal.check\n\n/**\n * Conditionally filters schedule executions using an effectful function.\n *\n * **Details**\n *\n * This function modifies a schedule by applying a custom effectful test\n * function to each input-output pair. The test function determines whether the\n * schedule should continue (`true`) or stop (`false`).\n *\n * This is useful when the decision to continue depends on external factors such\n * as database lookups, API calls, or other asynchronous computations.\n *\n * @see {@link check} If you need to use a pure test function.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const checkEffect: {\n  <In, Out, R2>(\n    test: (input: In, output: Out) => Effect.Effect<boolean, never, R2>\n  ): <R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R2 | R>\n  <Out, In, R, R2>(\n    self: Schedule<Out, In, R>,\n    test: (input: In, output: Out) => Effect.Effect<boolean, never, R2>\n  ): Schedule<Out, In, R | R2>\n} = internal.checkEffect\n\n/**\n * A schedule that collects all inputs into a `Chunk`.\n *\n * **Details**\n *\n * This function creates a schedule that never terminates and continuously\n * collects every input it receives into a `Chunk`. Each time the schedule runs,\n * it appends the new input to the collected list.\n *\n * This is useful when you need to track all received inputs over time, such as\n * logging user actions, recording retry attempts, or accumulating data for\n * later processing.\n *\n * @see {@link collectAllOutputs} If you need to collect outputs instead of\n * inputs.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const collectAllInputs: <A>() => Schedule<Chunk.Chunk<A>, A> = internal.collectAllInputs\n\n/**\n * Collects all outputs of a schedule into a `Chunk`.\n *\n * **Details**\n *\n * This function modifies a given schedule so that instead of returning\n * individual outputs, it accumulates them into a `Chunk`. The schedule\n * continues to run, appending each output to the collected list.\n *\n * This is useful when you need to track all results over time, such as logging\n * outputs, aggregating data, or keeping a history of previous values.\n *\n * @see {@link collectAllInputs} If you need to collect inputs instead of\n * outputs.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const collectAllOutputs: <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Chunk.Chunk<Out>, In, R> =\n  internal.collectAllOutputs\n\n/**\n * Collects all inputs into a `Chunk` until a condition fails.\n *\n * **Details**\n *\n * This function creates a schedule that continuously collects inputs into a\n * `Chunk` until the given predicate function `f` evaluates to `false`. Once the\n * condition fails, the schedule stops.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const collectUntil: <A>(f: Predicate<A>) => Schedule<Chunk.Chunk<A>, A> = internal.collectUntil\n\n/**\n * Collects all inputs into a `Chunk` until an effectful condition fails.\n *\n * **Details**\n *\n * This function creates a schedule that continuously collects inputs into a\n * `Chunk` until the given effectful predicate `f` returns `false`. The\n * predicate runs as an effect, meaning it can involve asynchronous computations\n * like API calls, database lookups, or randomness.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const collectUntilEffect: <A, R>(\n  f: (a: A) => Effect.Effect<boolean, never, R>\n) => Schedule<Chunk.Chunk<A>, A, R> = internal.collectUntilEffect\n\n/**\n * Collects all inputs into a `Chunk` while a condition holds.\n *\n * **Details**\n *\n * This function creates a schedule that continuously collects inputs into a\n * `Chunk` while the given predicate function `f` evaluates to `true`. As soon\n * as the condition fails, the schedule stops.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const collectWhile: <A>(f: Predicate<A>) => Schedule<Chunk.Chunk<A>, A> = internal.collectWhile\n\n/**\n * Collects all inputs into a `Chunk` while an effectful condition holds.\n *\n * **Details**\n *\n * This function creates a schedule that continuously collects inputs into a\n * `Chunk` while the given effectful predicate `f` returns `true`. The predicate\n * returns an effect, meaning it can depend on external state, such as database\n * queries, API responses, or real-time user conditions.\n *\n * As soon as the effectful condition returns `false`, the schedule stops. This\n * is useful for dynamically controlled data collection, where stopping depends\n * on an external or asynchronous factor.\n *\n * @since 2.0.0\n * @category Collecting\n */\nexport const collectWhileEffect: <A, R>(\n  f: (a: A) => Effect.Effect<boolean, never, R>\n) => Schedule<Chunk.Chunk<A>, A, R> = internal.collectWhileEffect\n\n/**\n * Chains two schedules, passing the output of the first as the input to the\n * second, while selecting the shorter delay between them.\n *\n * **Details**\n *\n * This function composes two schedules so that the output of the first schedule\n * becomes the input of the second schedule. The first schedule executes first,\n * and once it produces a result, the second schedule receives that result and\n * continues execution based on it.\n *\n * This is useful for building complex scheduling workflows where one schedule's\n * behavior determines how the next schedule behaves.\n *\n * @since 2.0.0\n * @category Composition\n */\nexport const compose: {\n  <Out2, Out, R2>(that: Schedule<Out2, Out, R2>): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out2, In, R2 | R>\n  <Out, In, R, Out2, R2>(self: Schedule<Out, In, R>, that: Schedule<Out2, Out, R2>): Schedule<Out2, In, R | R2>\n} = internal.compose\n\n/**\n * Transforms the input type of a schedule.\n *\n * **Details**\n *\n * This function modifies a given schedule by applying a transformation function\n * to its inputs. Instead of directly receiving values of type `In`, the\n * schedule will now accept values of type `In2`, which are converted to `In`\n * using the provided mapping function `f`.\n *\n * This is useful when you have a schedule that expects a specific input type\n * but you need to adapt it to work with a different type.\n *\n * @see {@link mapInputEffect} If you need to use an effectful transformation function.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const mapInput: {\n  <In, In2>(f: (in2: In2) => In): <Out, R>(self: Schedule<Out, In, R>) => Schedule<Out, In2, R>\n  <Out, In, R, In2>(self: Schedule<Out, In, R>, f: (in2: In2) => In): Schedule<Out, In2, R>\n} = internal.mapInput\n\n/**\n * Transforms the input type of a schedule using an effectful function.\n *\n * **Details**\n *\n * This function modifies a schedule by applying an effectful transformation to\n * its inputs. Instead of directly receiving values of type `In`, the schedule\n * will now accept values of type `In2`, which are converted to `In` via an\n * effectful function `f`.\n *\n * This is useful when the input transformation involves external dependencies,\n * such as API calls, database lookups, or other asynchronous computations.\n *\n * @see {@link mapInput} If you need to use a pure transformation function.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const mapInputEffect: {\n  <In2, In, R2>(\n    f: (in2: In2) => Effect.Effect<In, never, R2>\n  ): <Out, R>(self: Schedule<Out, In, R>) => Schedule<Out, In2, R2 | R>\n  <Out, In, R, In2, R2>(\n    self: Schedule<Out, In, R>,\n    f: (in2: In2) => Effect.Effect<In, never, R2>\n  ): Schedule<Out, In2, R | R2>\n} = internal.mapInputEffect\n\n/**\n * Transforms the required context of a schedule.\n *\n * **Details**\n *\n * This function modifies a schedule by mapping its required context (`R`) into\n * a new context (`R0`) using the provided function `f`.\n *\n * This is useful when you need to adapt a schedule to work with a different\n * dependency environment without changing its core logic.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const mapInputContext: {\n  <R0, R>(\n    f: (env0: Context.Context<R0>) => Context.Context<R>\n  ): <Out, In>(self: Schedule<Out, In, R>) => Schedule<Out, In, R0>\n  <Out, In, R, R0>(\n    self: Schedule<Out, In, R>,\n    f: (env0: Context.Context<R0>) => Context.Context<R>\n  ): Schedule<Out, In, R0>\n} = internal.mapInputContext\n\n/**\n * A schedule that recurs indefinitely, counting the number of recurrences.\n *\n * **Details**\n *\n * This schedule never stops and simply counts how many times it has executed.\n * Each recurrence increases the count, starting from `0`.\n *\n * This is useful when tracking the number of attempts in retry policies,\n * measuring execution loops, or implementing infinite polling scenarios.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const count: Schedule<number> = internal.count\n\n/**\n * Creates a schedule that recurs based on a cron expression.\n *\n * **Details**\n *\n * This schedule automatically executes at intervals defined by a cron\n * expression. It triggers at the beginning of each matched interval and\n * produces timestamps representing the start and end of the cron window.\n *\n * The cron `expression` is validated lazily, meaning errors may only be\n * detected when the schedule is executed.\n *\n * @since 2.0.0\n * @category Cron\n */\nexport const cron: {\n  (cron: Cron.Cron): Schedule<[number, number]>\n  (expression: string, tz?: DateTime.TimeZone | string): Schedule<[number, number]>\n} = internal.cron\n\n/**\n * Cron-like schedule that recurs at a specific second of each minute.\n *\n * **Details**\n *\n * This schedule triggers at the specified `second` of each minute,\n * starting at zero nanoseconds. It produces a count of executions\n * (0, 1, 2, ...). The `second` parameter is validated lazily, meaning\n * invalid values will only be caught at runtime.\n *\n * @since 2.0.0\n * @category Cron\n */\nexport const secondOfMinute: (second: number) => Schedule<number> = internal.secondOfMinute\n\n/**\n * Creates a schedule that recurs every specified minute of each hour.\n *\n * **Details**\n *\n * This schedule triggers once per hour at the specified `minute`, starting\n * exactly at `minute:00` (zero seconds). The schedule produces a count of\n * executions (`0, 1, 2, ...`), representing how many times it has run.\n *\n * The `minute` parameter must be between `0` and `59`. It is validated lazily,\n * meaning an invalid value will cause errors only when the schedule is\n * executed.\n *\n * @since 2.0.0\n * @category Cron\n */\nexport const minuteOfHour: (minute: number) => Schedule<number> = internal.minuteOfHour\n\n/**\n * Creates a schedule that recurs at a specific hour of each day.\n *\n * **Details**\n *\n * This schedule triggers once per day at the specified `hour`, starting at zero\n * minutes of that hour. The schedule produces a count of executions (`0, 1, 2,\n * ...`), indicating how many times it has been triggered.\n *\n * The `hour` parameter must be between `0` (midnight) and `23` (11 PM). It is\n * validated lazily, meaning an invalid value will cause errors only when the\n * schedule is executed.\n *\n * This is useful for scheduling daily recurring tasks at a fixed time, such as\n * running batch jobs or refreshing data.\n *\n * @since 2.0.0\n * @category Cron\n */\nexport const hourOfDay: (hour: number) => Schedule<number> = internal.hourOfDay\n\n/**\n * Creates a schedule that recurs on a specific day of the month.\n *\n * **Details**\n *\n * This schedule triggers at midnight on the specified day of each month. It\n * will not execute in months that have fewer days than the given day. For\n * example, if the schedule is set to run on the 31st, it will not execute in\n * months with only 30 days.\n *\n * The schedule produces a count of executions, starting at 0 and incrementing\n * with each recurrence.\n *\n * The `day` parameter is validated lazily, meaning errors may only be detected\n * when the schedule is executed.\n *\n * @since 2.0.0\n * @category Cron\n */\nexport const dayOfMonth: (day: number) => Schedule<number> = internal.dayOfMonth\n\n/**\n * Creates a schedule that recurs on a specific day of the week.\n *\n * **Details**\n *\n * This schedule triggers at midnight on the specified day of the week. The\n * `day` parameter follows the standard convention where `Monday = 1` and\n * `Sunday = 7`. The schedule produces a count of executions, starting at 0 and\n * incrementing with each recurrence.\n *\n * The `day` parameter is validated lazily, meaning errors may only be detected\n * when the schedule is executed.\n *\n * @since 2.0.0\n * @category Cron\n */\nexport const dayOfWeek: (day: number) => Schedule<number> = internal.dayOfWeek\n\n/**\n * Modifies a schedule by adding a computed delay before each execution.\n *\n * **Details**\n *\n * This function adjusts an existing schedule by applying a transformation to\n * its delays. Instead of using the default interval, each delay is modified\n * using the provided function `f`, which takes the current delay and returns a\n * new delay.\n *\n * This is useful for dynamically adjusting wait times between executions, such\n * as introducing jitter, exponential backoff, or custom delay logic.\n *\n * @see {@link delayedEffect} If you need to compute the delay using an effectful function.\n *\n * @since 2.0.0\n * @category Timing & Delay\n */\nexport const delayed: {\n  (\n    f: (duration: Duration.Duration) => Duration.DurationInput\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(\n    self: Schedule<Out, In, R>,\n    f: (duration: Duration.Duration) => Duration.DurationInput\n  ): Schedule<Out, In, R>\n} = internal.delayed\n\n/**\n * Modifies a schedule by adding an effectfully computed delay before each\n * execution.\n *\n * **Details**\n *\n * This function adjusts an existing schedule by introducing a delay that is\n * computed via an effect. Instead of using a fixed delay, each interval is\n * dynamically adjusted based on an effectful function `f`, which takes the\n * current delay and returns a new delay wrapped in an `Effect`.\n *\n * This is useful for adaptive scheduling where delays depend on external\n * factors, such as API calls, database queries, or dynamic system conditions.\n *\n * @see {@link delayed} If you need to compute the delay using a pure function.\n *\n * @since 2.0.0\n * @category Timing & Delay\n */\nexport const delayedEffect: {\n  <R2>(\n    f: (duration: Duration.Duration) => Effect.Effect<Duration.DurationInput, never, R2>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R2 | R>\n  <Out, In, R, R2>(\n    self: Schedule<Out, In, R>,\n    f: (duration: Duration.Duration) => Effect.Effect<Duration.DurationInput, never, R2>\n  ): Schedule<Out, In, R | R2>\n} = internal.delayedEffect\n\n/**\n * Uses the delays produced by a schedule to further delay its intervals.\n *\n * **Details**\n *\n * This function modifies a schedule by using its own output delays to control\n * its execution timing. Instead of executing immediately at each interval, the\n * schedule will be delayed by the duration it produces.\n *\n * @since 2.0.0\n * @category Timing & Delay\n */\nexport const delayedSchedule: <In, R>(\n  schedule: Schedule<Duration.Duration, In, R>\n) => Schedule<Duration.Duration, In, R> = internal.delayedSchedule\n\n/**\n * Transforms a schedule to output the delay between each occurrence.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that instead of producing its\n * original output, it now returns the delay between each scheduled execution.\n *\n * @since 2.0.0\n * @category Monitoring\n */\nexport const delays: <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Duration.Duration, In, R> = internal.delays\n\n/**\n * Transforms both the input and output of a schedule.\n *\n * **Details**\n *\n * This function modifies an existing schedule by applying a transformation to\n * both its input values and its output values. The provided transformation\n * functions `onInput` and `onOutput` allow you to map the schedule to work with\n * a different input type while modifying its outputs as well.\n *\n * @see {@link mapBothEffect} If you need to use effectful transformation functions.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const mapBoth: {\n  <In2, In, Out, Out2>(\n    options: { readonly onInput: (in2: In2) => In; readonly onOutput: (out: Out) => Out2 }\n  ): <R>(self: Schedule<Out, In, R>) => Schedule<Out2, In2, R>\n  <Out, In, R, In2, Out2>(\n    self: Schedule<Out, In, R>,\n    options: { readonly onInput: (in2: In2) => In; readonly onOutput: (out: Out) => Out2 }\n  ): Schedule<Out2, In2, R>\n} = internal.mapBoth\n\n/**\n * Transforms both the input and output of a schedule using effectful\n * computations.\n *\n * **Details**\n *\n * This function modifies an existing schedule by applying effectful\n * transformations to both its input values and its output values. The provided\n * effectful functions `onInput` and `onOutput` allow you to transform inputs\n * and outputs using computations that may involve additional logic, resource\n * access, or side effects.\n *\n * @see {@link mapBoth} If you need to use pure transformation functions.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const mapBothEffect: {\n  <In2, In, R2, Out, R3, Out2>(\n    options: {\n      readonly onInput: (input: In2) => Effect.Effect<In, never, R2>\n      readonly onOutput: (out: Out) => Effect.Effect<Out2, never, R3>\n    }\n  ): <R>(self: Schedule<Out, In, R>) => Schedule<Out2, In2, R2 | R3 | R>\n  <Out, In, R, In2, R2, Out2, R3>(\n    self: Schedule<Out, In, R>,\n    options: {\n      readonly onInput: (input: In2) => Effect.Effect<In, never, R2>\n      readonly onOutput: (out: Out) => Effect.Effect<Out2, never, R3>\n    }\n  ): Schedule<Out2, In2, R | R2 | R3>\n} = internal.mapBothEffect\n\n/**\n * Creates a driver to manually control the execution of a schedule.\n *\n * **Details**\n *\n * This function returns a `ScheduleDriver`, which allows stepping through a\n * schedule manually while handling delays and sleeping appropriately. A driver\n * is useful when you need fine-grained control over how a schedule progresses,\n * rather than relying on automatic execution.\n *\n * The returned driver exposes methods for retrieving the current state,\n * executing the next step, and resetting the schedule when needed.\n *\n * @since 2.0.0\n * @category getter\n */\nexport const driver: <Out, In, R>(\n  self: Schedule<Out, In, R>\n) => Effect.Effect<ScheduleDriver<Out, In, R>> = internal.driver\n\n// TODO(4.0): remove?\n/**\n * Alias of {@link fromDelay}.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const duration: (duration: Duration.DurationInput) => Schedule<Duration.Duration> = internal.duration\n\n// TODO(4.0): remove?\n/**\n * Alias of {@link union}.\n *\n * @since 2.0.0\n * @category Alternatives\n */\nexport const either: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<[Out, Out2], In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>\n  ): Schedule<[Out, Out2], In & In2, R | R2>\n} = internal.either\n\n// TODO(4.0): remove?\n/**\n * Alias of {@link unionWith}.\n *\n * @since 2.0.0\n * @category Alternatives\n */\nexport const eitherWith: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<[Out, Out2], In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ): Schedule<[Out, Out2], In & In2, R | R2>\n} = internal.eitherWith\n\n/**\n * Creates a schedule that tracks the total elapsed duration since it started.\n *\n * **Details**\n *\n * This schedule executes continuously and returns the total time that has\n * passed since the first execution. The duration keeps increasing with each\n * step, providing a way to measure elapsed time.\n *\n * This is useful for tracking execution time, monitoring delays, or\n * implementing logic based on how long a process has been running.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const elapsed: Schedule<Duration.Duration> = internal.elapsed\n\n/**\n * Attaches a finalizer to a schedule that runs when the schedule completes.\n *\n * **Details**\n *\n * This function returns a new schedule that executes a given finalizer when the\n * schedule reaches completion. Unlike `Effect.ensuring`, this method does not\n * guarantee the finalizer will run in all cases. If the schedule never\n * initializes or is not driven to completion, the finalizer may not execute.\n * However, if the schedule decides not to continue, the finalizer will be\n * invoked.\n *\n * This is useful for cleaning up resources, logging, or executing other side\n * effects when a schedule completes.\n *\n * @since 2.0.0\n * @category Finalization\n */\nexport const ensuring: {\n  <X>(finalizer: Effect.Effect<X, never, never>): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R, X>(self: Schedule<Out, In, R>, finalizer: Effect.Effect<X, never, never>): Schedule<Out, In, R>\n} = internal.ensuring\n\n/**\n * Creates a schedule that recurs indefinitely with exponentially increasing\n * delays.\n *\n * **Details**\n *\n * This schedule starts with an initial delay of `base` and increases the delay\n * exponentially on each repetition using the formula `base * factor^n`, where\n * `n` is the number of times the schedule has executed so far. If no `factor`\n * is provided, it defaults to `2`, causing the delay to double after each\n * execution.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const exponential: (\n  base: Duration.DurationInput,\n  factor?: number\n) => Schedule<Duration.Duration> = internal.exponential\n\n/**\n * Creates a schedule that recurs indefinitely with Fibonacci-based increasing\n * delays.\n *\n * **Details**\n *\n * This schedule starts with an initial delay of `one` and increases subsequent\n * delays by summing the two previous delays, following the Fibonacci sequence.\n * The delay pattern follows: `one, one, one + one, (one + one) + one, ...`,\n * resulting in `1s, 1s, 2s, 3s, 5s, 8s, 13s, ...` if `one = 1s`.\n *\n * This is useful for progressive backoff strategies, where delays grow\n * naturally over time without increasing as aggressively as an exponential\n * schedule.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const fibonacci: (one: Duration.DurationInput) => Schedule<Duration.Duration> = internal.fibonacci\n\n/**\n * Creates a schedule that recurs at a fixed interval.\n *\n * **Details**\n *\n * This schedule executes at regular, evenly spaced intervals, returning the\n * number of times it has run so far. If the action being executed takes longer\n * than the interval, the next execution will happen immediately to prevent\n * \"pile-ups,\" ensuring that the schedule remains consistent without overlapping\n * executions.\n *\n * ```text\n * |-----interval-----|-----interval-----|-----interval-----|\n * |---------action--------||action|-----|action|-----------|\n * ```\n *\n * @see {@link spaced} If you need to run from the end of the last execution.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const fixed: (interval: Duration.DurationInput) => Schedule<number> = internal.fixed\n\n/**\n * Creates a schedule that recurs indefinitely, producing a count of\n * repetitions.\n *\n * **Details**\n *\n * This schedule runs indefinitely, returning an increasing count of executions\n * (`0, 1, 2, 3, ...`). Each step increments the count by one, allowing tracking\n * of how many times it has executed.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const forever: Schedule<number> = internal.forever\n\n/**\n * Creates a schedule that recurs once after a specified duration.\n *\n * **Details**\n *\n * This schedule executes a single time after waiting for the given duration.\n * Once it has executed, it does not repeat.\n *\n * @see {@link fromDelays} If you need to create a schedule with multiple delays.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const fromDelay: (delay: Duration.DurationInput) => Schedule<Duration.Duration> = internal.fromDelay\n\n/**\n * Creates a schedule that recurs once for each specified duration, applying the\n * given delays sequentially.\n *\n * **Details**\n *\n * This schedule executes multiple times, each time waiting for the\n * corresponding duration from the provided list of delays. The first execution\n * waits for `delay`, the next for the second value in `delays`, and so on. Once\n * all delays have been used, the schedule stops executing.\n *\n * This is useful for defining a custom delay sequence that does not follow a\n * fixed pattern like exponential or Fibonacci backoff.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const fromDelays: (\n  delay: Duration.DurationInput,\n  ...delays: Array<Duration.DurationInput>\n) => Schedule<Duration.Duration> = internal.fromDelays\n\n/**\n * Creates a schedule that always recurs, transforming input values using the\n * specified function.\n *\n * **Details**\n *\n * This schedule continuously executes and applies the given function `f` to\n * each input value, producing a transformed output. The schedule itself does\n * not control delays or stopping conditions; it simply transforms the input\n * values as they are processed.\n *\n * This is useful when defining schedules that map inputs to outputs, allowing\n * dynamic transformations of incoming data.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const fromFunction: <A, B>(f: (a: A) => B) => Schedule<B, A> = internal.fromFunction\n\n/**\n * Creates a schedule that always recurs, passing inputs directly as outputs.\n *\n * **Details**\n *\n * This schedule runs indefinitely, returning each input value as its output\n * without modification. It effectively acts as a pass-through that simply\n * echoes its input values at each step.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const identity: <A>() => Schedule<A, A> = internal.identity\n\n/**\n * Transforms a schedule to pass through its inputs as outputs.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that it returns its input\n * values instead of its original output values. The schedule's timing remains\n * unchanged, but its outputs are replaced with whatever inputs it receives.\n *\n * @since 2.0.0\n */\nexport const passthrough: <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<In, In, R> = internal.passthrough\n\n/**\n * Combines two schedules, continuing only if both schedules want to continue,\n * using the longer delay.\n *\n * **Details**\n *\n * This function takes two schedules and creates a new schedule that only\n * continues execution if both schedules allow it. The interval between\n * recurrences is determined by the longer delay between the two schedules.\n *\n * The output of the resulting schedule is a tuple containing the outputs of\n * both schedules. The input type is the intersection of both schedules' input\n * types.\n *\n * This is useful when coordinating multiple scheduling conditions where\n * execution should proceed only when both schedules permit it.\n *\n * @see {@link intersectWith} If you need to use a custom merge function.\n *\n * @since 2.0.0\n * @category Composition\n */\nexport const intersect: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<[Out, Out2], In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>\n  ): Schedule<[Out, Out2], In & In2, R | R2>\n} = internal.intersect\n\n/**\n * Combines two schedules, continuing only if both want to continue, merging\n * intervals using a custom function.\n *\n * **Details**\n *\n * This function takes two schedules and creates a new schedule that only\n * continues execution if both schedules allow it. Instead of automatically\n * using the longer delay (like {@link intersect}), this function applies a\n * user-provided merge function `f` to determine the next interval between\n * executions.\n *\n * The output of the resulting schedule is a tuple containing the outputs of\n * both schedules, and the input type is the intersection of both schedules'\n * input types.\n *\n * @since 2.0.0\n * @category Composition\n */\nexport const intersectWith: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<[Out, Out2], In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ): Schedule<[Out, Out2], In & In2, R | R2>\n} = internal.intersectWith\n\n/**\n * Returns a new schedule that randomly adjusts the interval size within a\n * range.\n *\n * **Details**\n *\n * This function modifies a schedule so that its delay between executions is\n * randomly varied within a range. By default, the delay is adjusted between\n * `80%` (`0.8 * interval`) and `120%` (`1.2 * interval`) of the original\n * interval size.\n *\n * This is useful for adding randomness to repeated executions, reducing\n * contention in distributed systems, and avoiding synchronized execution\n * patterns that can cause bottlenecks.\n *\n * @see {@link jitteredWith} If you need to specify custom min/max values.\n *\n * @since 2.0.0\n * @category Timing & Delay\n */\nexport const jittered: <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R> = internal.jittered\n\n/**\n * Returns a new schedule that randomly adjusts the interval size within a\n * user-defined range.\n *\n * **Details**\n *\n * This function modifies a schedule so that its delay between executions is\n * randomly varied within a specified range. Instead of using the default `0.8 -\n * 1.2` range like {@link jittered}, this function allows customizing the `min`\n * and `max` multipliers.\n *\n * The delay for each step will be adjusted within `min * original_interval` and\n * `max * original_interval`. If `min` and `max` are not provided, the defaults\n * are `0.8` and `1.2`, respectively.\n *\n * This is useful for introducing randomness into scheduling behavior while\n * having precise control over the jitter range.\n *\n * @since 2.0.0\n * @category Timing & Delay\n */\nexport const jitteredWith: {\n  (\n    options: { min?: number | undefined; max?: number | undefined }\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(\n    self: Schedule<Out, In, R>,\n    options: { min?: number | undefined; max?: number | undefined }\n  ): Schedule<Out, In, R>\n} = internal.jitteredWith\n\n/**\n * Creates a schedule that recurs indefinitely, increasing the delay linearly.\n *\n * **Details**\n *\n * This schedule starts with an initial delay of `base` and increases the delay\n * on each recurrence in a linear fashion, following the formula:\n *\n * `delay = base * n`\n *\n * where `n` is the number of times the schedule has executed so far. This\n * results in increasing intervals between executions.\n *\n * This is useful for implementing linear backoff strategies where the wait time\n * between retries increases at a steady rate.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const linear: (base: Duration.DurationInput) => Schedule<Duration.Duration> = internal.linear\n\n/**\n * Returns a new schedule that transforms its output using the specified\n * function.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that its outputs are\n * transformed by the provided function `f`. The timing and recurrence behavior\n * of the schedule remain unchanged, but the values it produces are mapped to\n * new values.\n *\n * This is useful when composing schedules where you need to adjust the output\n * format or apply additional processing.\n *\n * @see {@link mapEffect} If you need to use an effectful transformation\n * function.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const map: {\n  <Out, Out2>(f: (out: Out) => Out2): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out2, In, R>\n  <Out, In, R, Out2>(self: Schedule<Out, In, R>, f: (out: Out) => Out2): Schedule<Out2, In, R>\n} = internal.map\n\n/**\n * Returns a new schedule that applies an effectful transformation to its\n * output.\n *\n * **Details**\n *\n * This function modifies an existing schedule by applying an effectful function\n * `f` to its output values. The timing and recurrence behavior of the schedule\n * remain unchanged, but each output is mapped to a new value within an\n * `Effect`.\n *\n * This is useful when you need to perform side effects or asynchronous\n * transformations before passing the output forward.\n *\n * @see {@link map} If you need to use a pure transformation function.\n *\n * @since 2.0.0\n * @category Mapping\n */\nexport const mapEffect: {\n  <Out, Out2, R2>(\n    f: (out: Out) => Effect.Effect<Out2, never, R2>\n  ): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out2, In, R2 | R>\n  <Out, In, R, Out2, R2>(\n    self: Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<Out2, never, R2>\n  ): Schedule<Out2, In, R | R2>\n} = internal.mapEffect\n\n/**\n * Returns a new schedule that modifies the delay between executions using a\n * custom function.\n *\n * **Details**\n *\n * This function transforms an existing schedule by applying `f` to modify the\n * delay before each execution. The function receives both the schedule's output\n * (`out`) and the originally computed delay (`duration`), and returns a new\n * adjusted delay.\n *\n * @see {@link modifyDelayEffect} If you need to use an effectful function.\n *\n * @since 2.0.0\n * @category Timing & Delay\n */\nexport const modifyDelay: {\n  <Out>(\n    f: (out: Out, duration: Duration.Duration) => Duration.DurationInput\n  ): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(\n    self: Schedule<Out, In, R>,\n    f: (out: Out, duration: Duration.Duration) => Duration.DurationInput\n  ): Schedule<Out, In, R>\n} = internal.modifyDelay\n\n/**\n * Returns a new schedule that modifies the delay before execution using an\n * effectful function.\n *\n * **Details**\n *\n * This function takes an existing schedule and applies an effectful function\n * `f` to dynamically adjust the delay before each execution. The function\n * receives both the schedule's output (`out`) and the originally computed delay\n * (`duration`), returning a new adjusted delay wrapped in an `Effect`.\n *\n * @see {@link modifyDelay} If you need to use a pure function.\n *\n * @since 2.0.0\n * @category Timing & Delay\n */\nexport const modifyDelayEffect: {\n  <Out, R2>(\n    f: (out: Out, duration: Duration.Duration) => Effect.Effect<Duration.DurationInput, never, R2>\n  ): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R2 | R>\n  <Out, In, R, R2>(\n    self: Schedule<Out, In, R>,\n    f: (out: Out, duration: Duration.Duration) => Effect.Effect<Duration.DurationInput, never, R2>\n  ): Schedule<Out, In, R | R2>\n} = internal.modifyDelayEffect\n\n/**\n * Returns a new schedule that executes an effect every time the schedule makes\n * a decision.\n *\n * **Details**\n *\n * This function enhances an existing schedule by running an effectful function\n * `f` whenever a scheduling decision is made. The function receives the current\n * schedule output (`out`) and the decision (`ScheduleDecision`), allowing\n * additional logic to be executed, such as logging, monitoring, or side\n * effects.\n *\n * @since 2.0.0\n */\nexport const onDecision: {\n  <Out, X, R2>(\n    f: (out: Out, decision: ScheduleDecision.ScheduleDecision) => Effect.Effect<X, never, R2>\n  ): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R2 | R>\n  <Out, In, R, X, R2>(\n    self: Schedule<Out, In, R>,\n    f: (out: Out, decision: ScheduleDecision.ScheduleDecision) => Effect.Effect<X, never, R2>\n  ): Schedule<Out, In, R | R2>\n} = internal.onDecision\n\n/**\n * A schedule that executes only once and then stops.\n *\n * **Details**\n *\n * This schedule triggers a single execution and then terminates. It does not\n * repeat or apply any additional logic.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const once: Schedule<void> = internal.once\n\n/**\n * Returns a new schedule with a provided context, eliminating the need for\n * external dependencies.\n *\n * **Details**\n *\n * This function supplies a required `context` to a schedule, allowing it to run\n * without requiring external dependencies. After calling this function, the\n * schedule can be used freely without needing to pass a context at execution\n * time.\n *\n * This is useful when working with schedules that rely on contextual\n * information, such as logging services, database connections, or configuration\n * settings.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const provideContext: {\n  <R>(context: Context.Context<R>): <Out, In>(self: Schedule<Out, In, R>) => Schedule<Out, In, never>\n  <Out, In, R>(self: Schedule<Out, In, R>, context: Context.Context<R>): Schedule<Out, In, never>\n} = internal.provideContext\n\n/**\n * Returns a new schedule with a single required service provided, eliminating\n * the need for external dependencies.\n *\n * **Details**\n *\n * This function supplies a single service dependency to a schedule, allowing it\n * to run without requiring that service externally. If a schedule depends on\n * multiple services, consider using `provideContext` instead.\n *\n * This is useful when working with schedules that require a specific service,\n * such as logging, metrics, or configuration retrieval.\n *\n * @since 2.0.0\n * @category Context\n */\nexport const provideService: {\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, Exclude<R, I>>\n  <Out, In, R, I, S>(\n    self: Schedule<Out, In, R>,\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ): Schedule<Out, In, Exclude<R, I>>\n} = internal.provideService\n\n/**\n * A schedule that recurs until the given predicate evaluates to true.\n *\n * **Details**\n *\n * This schedule will continue executing as long as the provided predicate `f`\n * returns `false` for the input value. Once `f` evaluates to `true`, the\n * schedule stops recurring.\n *\n * This is useful for defining schedules that should stop when a certain\n * condition is met, such as detecting a success state, reaching a threshold, or\n * avoiding unnecessary retries.\n *\n * @see {@link recurUntilEffect} If you need to use an effectful predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const recurUntil: <A>(f: Predicate<A>) => Schedule<A, A> = internal.recurUntil\n\n/**\n * A schedule that recurs until the given effectful predicate evaluates to true.\n *\n * **Details**\n *\n * This schedule continues executing as long as the provided effectful predicate\n * `f` returns `false`. Once `f` evaluates to `true`, the schedule stops\n * recurring. Unlike {@link recurUntil}, this function allows the stopping\n * condition to be computed asynchronously or based on external dependencies.\n *\n * This is useful when the stopping condition depends on an effectful\n * computation, such as checking a database, making an API call, or retrieving\n * system state dynamically.\n *\n * @see {@link recurUntil} If you need to use a pure predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const recurUntilEffect: <A, R>(f: (a: A) => Effect.Effect<boolean, never, R>) => Schedule<A, A, R> =\n  internal.recurUntilEffect\n\n/**\n * A schedule that recurs until the input value matches a partial function, then\n * maps the value.\n *\n * **Details**\n *\n * This schedule continues executing until the provided partial function `pf`\n * returns `Some(value)`. At that point, it stops and maps the resulting value\n * to an `Option<B>`. If `pf` returns `None`, the schedule continues.\n *\n * This is useful when defining schedules that should stop once a certain\n * condition is met and transform the final value before completion.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const recurUntilOption: <A, B>(pf: (a: A) => Option.Option<B>) => Schedule<Option.Option<B>, A> =\n  internal.recurUntilOption\n\n/**\n * A schedule that recurs until the specified duration has elapsed.\n *\n * **Details**\n *\n * This schedule continues executing for the given `duration`, after which it\n * stops. The schedule outputs the elapsed time on each recurrence.\n *\n * This is useful for limiting the duration of retries, enforcing time-based\n * constraints, or ensuring that an operation does not run indefinitely.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const recurUpTo: (duration: Duration.DurationInput) => Schedule<Duration.Duration> = internal.recurUpTo\n\n/**\n * A schedule that recurs as long as the given predicate evaluates to true.\n *\n * **Details*\n *\n * This schedule continues executing as long as the provided predicate `f`\n * returns `true` for the input value. Once `f` evaluates to `false`, the\n * schedule stops recurring.\n *\n * @see {@link recurWhileEffect} If you need to use an effectful predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const recurWhile: <A>(f: Predicate<A>) => Schedule<A, A> = internal.recurWhile\n\n/**\n * A schedule that recurs as long as the given effectful predicate evaluates to\n * true.\n *\n * **Details**\n *\n * This schedule continues executing as long as the provided effectful predicate\n * `f` returns `true`. Once `f` evaluates to `false`, the schedule stops\n * recurring. Unlike {@link recurWhile}, this function allows the condition to\n * be computed dynamically using an effectful computation.\n *\n * @see {@link recurWhile} If you need to use a pure predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const recurWhileEffect: <A, R>(f: (a: A) => Effect.Effect<boolean, never, R>) => Schedule<A, A, R> =\n  internal.recurWhileEffect\n\n/**\n * A schedule that recurs a fixed number of times before terminating.\n *\n * **Details**\n *\n * This schedule will continue executing until it has been stepped `n` times,\n * after which it will stop. The output of the schedule is the current count of\n * recurrences.\n *\n * @category Constructors\n * @since 2.0.0\n */\nexport const recurs: (n: number) => Schedule<number> = internal.recurs\n\n/**\n * Returns a new schedule that folds over the outputs of this one.\n *\n * **Details**\n *\n * This schedule transforms the output by accumulating values over time using a\n * reducer function `f`. It starts with an initial value `zero` and updates it\n * each time the schedule produces an output.\n *\n * This is useful for tracking statistics, aggregating results, or summarizing\n * data across multiple executions.\n *\n * @see {@link reduceEffect} If you need to use an effectful reducer function.\n *\n * @since 2.0.0\n * @category Reducing\n */\nexport const reduce: {\n  <Out, Z>(zero: Z, f: (z: Z, out: Out) => Z): <In, R>(self: Schedule<Out, In, R>) => Schedule<Z, In, R>\n  <Out, In, R, Z>(self: Schedule<Out, In, R>, zero: Z, f: (z: Z, out: Out) => Z): Schedule<Z, In, R>\n} = internal.reduce\n\n/**\n * Returns a new schedule that effectfully folds over the outputs of this one.\n *\n * **Details**\n *\n * This schedule accumulates outputs over time using an effectful reducer\n * function `f`. It starts with an initial value `zero` and updates it\n * asynchronously or based on external dependencies.\n *\n * This is useful for asynchronous state tracking, logging, external metrics\n * aggregation, or any scenario where accumulation needs to involve an effectful\n * computation.\n *\n * @see {@link reduce} If you need to use a pure reducer function.\n *\n * @since 2.0.0\n * @category Reducing\n */\nexport const reduceEffect: {\n  <Z, Out, R2>(\n    zero: Z,\n    f: (z: Z, out: Out) => Effect.Effect<Z, never, R2>\n  ): <In, R>(self: Schedule<Out, In, R>) => Schedule<Z, In, R2 | R>\n  <Out, In, R, Z, R2>(\n    self: Schedule<Out, In, R>,\n    zero: Z,\n    f: (z: Z, out: Out) => Effect.Effect<Z, never, R2>\n  ): Schedule<Z, In, R | R2>\n} = internal.reduceEffect\n\n// TODO(4.0): remove?\n/**\n * Alias of {@link forever}.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const repeatForever: Schedule<number> = internal.forever\n\n/**\n * Returns a new schedule that outputs the number of repetitions of this one.\n *\n * **Details**\n *\n * This schedule tracks how many times the given schedule has executed and\n * outputs the count instead of the original values. The first execution starts\n * at `0`, and the count increases with each recurrence.\n *\n * @since 2.0.0\n * @category Monitoring\n */\nexport const repetitions: <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<number, In, R> = internal.repetitions\n\n/**\n * Returns a new schedule that automatically resets to its initial state after a\n * period of inactivity defined by `duration`.\n *\n * **Details**\n *\n * This function modifies a schedule so that if no inputs are received for the\n * specified `duration`, the schedule resets as if it were new.\n *\n * @see {@link resetWhen} If you need to reset based on output values.\n *\n * @since 2.0.0\n * @category State Management\n */\nexport const resetAfter: {\n  (duration: Duration.DurationInput): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(self: Schedule<Out, In, R>, duration: Duration.DurationInput): Schedule<Out, In, R>\n} = internal.resetAfter\n\n/**\n * Resets the schedule when the specified predicate on the schedule output\n * evaluates to `true`.\n *\n * **Details**\n *\n * This function modifies a schedule so that it resets to its initial state\n * whenever the provided predicate `f` returns `true` for an output value.\n *\n * @see {@link resetAfter} If you need to reset based on inactivity.\n *\n * @since 2.0.0\n * @category State Management\n */\nexport const resetWhen: {\n  <Out>(f: Predicate<Out>): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(self: Schedule<Out, In, R>, f: Predicate<Out>): Schedule<Out, In, R>\n} = internal.resetWhen\n\n/**\n * Runs a schedule using the provided inputs and collects all outputs.\n *\n * **Details**\n *\n * This function executes a given schedule with a sequence of input values and\n * accumulates all outputs into a `Chunk`. The schedule starts execution at the\n * specified `now` timestamp and proceeds according to its defined behavior.\n *\n * This is useful for batch processing, simulating execution, or testing\n * schedules with predefined input sequences.\n *\n * @since 2.0.0\n * @category Execution\n */\nexport const run: {\n  <In>(\n    now: number,\n    input: Iterable<In>\n  ): <Out, R>(self: Schedule<Out, In, R>) => Effect.Effect<Chunk.Chunk<Out>, never, R>\n  <Out, In, R>(self: Schedule<Out, In, R>, now: number, input: Iterable<In>): Effect.Effect<Chunk.Chunk<Out>, never, R>\n} = internal.run\n\n/**\n * Returns a schedule that recurs continuously, with each repetition\n * spaced by the specified `duration` from the last run.\n *\n * **Details**\n *\n * This schedule ensures that executions occur at a fixed interval,\n * maintaining a consistent delay between repetitions. The delay starts\n * from the end of the last execution, not from the schedule start time.\n *\n * @see {@link fixed} If you need to run at a fixed interval from the start.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const spaced: (duration: Duration.DurationInput) => Schedule<number> = internal.spaced\n\n/**\n * A schedule that does not recur and stops immediately.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const stop: Schedule<void> = internal.stop\n\n/**\n * Returns a schedule that recurs indefinitely, always producing the specified\n * constant value.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const succeed: <A>(value: A) => Schedule<A> = internal.succeed\n\n/**\n * Returns a schedule that recurs indefinitely, evaluating the given function to\n * produce a constant value.\n *\n * @category Constructors\n * @since 2.0.0\n */\nexport const sync: <A>(evaluate: LazyArg<A>) => Schedule<A> = internal.sync\n\n/**\n * Returns a new schedule that runs the given effectful function for each input\n * before continuing execution.\n *\n * **Details**\n *\n * This function allows side effects to be performed on each input processed by\n * the schedule. It does not modify the schedule’s behavior but ensures that the\n * provided function `f` runs before each step.\n *\n * @since 2.0.0\n * @category Tapping\n */\nexport const tapInput: {\n  <In2, X, R2>(\n    f: (input: In2) => Effect.Effect<X, never, R2>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In & In2, R2 | R>\n  <Out, In, R, In2, X, R2>(\n    self: Schedule<Out, In, R>,\n    f: (input: In2) => Effect.Effect<X, never, R2>\n  ): Schedule<Out, In & In2, R | R2>\n} = internal.tapInput\n\n/**\n * Returns a new schedule that runs the given effectful function for each output\n * before continuing execution.\n *\n * **Details**\n *\n * This function allows side effects to be performed on each output produced by\n * the schedule. It does not modify the schedule’s behavior but ensures that the\n * provided function `f` runs after each step.\n *\n * @since 2.0.0\n * @category Tapping\n */\nexport const tapOutput: {\n  <X, R2, Out>(\n    f: (out: Types.NoInfer<Out>) => Effect.Effect<X, never, R2>\n  ): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R2 | R>\n  <Out, In, R, X, R2>(\n    self: Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<X, never, R2>\n  ): Schedule<Out, In, R | R2>\n} = internal.tapOutput\n\n/**\n * Creates a schedule that repeatedly applies a function to transform a state\n * value, producing a sequence of values.\n *\n * **Details**\n *\n * This function starts with an `initial` value and applies `f` recursively to\n * generate the next state at each step. The schedule continues indefinitely,\n * producing a stream of values by unfolding the state over time.\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const unfold: <A>(initial: A, f: (a: A) => A) => Schedule<A> = internal.unfold\n\n/**\n * Combines two schedules, continuing execution as long as at least one of them\n * allows it, using the shorter delay.\n *\n * **Details**\n *\n * This function combines two schedules into a single schedule that executes in\n * parallel. If either schedule allows continuation, the merged schedule\n * continues. When both schedules produce delays, the schedule selects the\n * shorter delay to determine the next step.\n *\n * The output of the new schedule is a tuple containing the outputs of both\n * schedules. The input type is the intersection of both schedules' input types.\n *\n * This is useful for scenarios where multiple scheduling conditions should be\n * considered, ensuring execution proceeds if at least one schedule permits it.\n *\n * @see {@link unionWith} If you need to use a custom merge function.\n *\n * @since 2.0.0\n * @category Composition\n */\nexport const union: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<[Out, Out2], In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>\n  ): Schedule<[Out, Out2], In & In2, R | R2>\n} = internal.union\n\n/**\n * Combines two schedules, continuing execution as long as at least one of them\n * wants to continue, merging their intervals using a custom merge function.\n *\n * **Details**\n *\n * This function allows you to combine two schedules while defining how their\n * intervals should be merged. Unlike {@link union}, which simply selects the\n * shorter delay, this function lets you specify a custom merging strategy for\n * the schedules’ intervals.\n *\n * The merged schedule continues execution as long as at least one of the input\n * schedules allows it. The next interval is determined by applying the provided\n * merge function to the intervals of both schedules.\n *\n * The output of the resulting schedule is a tuple containing the outputs of\n * both schedules. The input type is the intersection of both schedules' input\n * types.\n *\n * @see {@link union} If you need to use the shorter delay.\n *\n * @since 2.0.0\n * @category Composition\n */\nexport const unionWith: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<[Out, Out2], In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ): Schedule<[Out, Out2], In & In2, R | R2>\n} = internal.unionWith\n\n/**\n * Returns a new schedule that stops execution when the given predicate on the\n * input evaluates to `true`.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that it continues executing\n * only while the provided predicate returns `false` for incoming inputs. Once\n * an input satisfies the condition, the schedule terminates immediately.\n *\n * @see {@link untilInputEffect} If you need to use an effectful predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const untilInput: {\n  <In>(f: Predicate<In>): <Out, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(self: Schedule<Out, In, R>, f: Predicate<In>): Schedule<Out, In, R>\n} = internal.untilInput\n\n/**\n * Returns a new schedule that stops execution when the given effectful\n * predicate on the input evaluates to `true`.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that it continues executing\n * only while the provided effectful predicate returns `false` for incoming\n * inputs. The predicate is an `Effect`, meaning it can involve asynchronous\n * computations or dependency-based logic.\n *\n * @see {@link untilInput} If you need to use a pure predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const untilInputEffect: {\n  <In, R2>(\n    f: (input: In) => Effect.Effect<boolean, never, R2>\n  ): <Out, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R2 | R>\n  <Out, In, R, R2>(\n    self: Schedule<Out, In, R>,\n    f: (input: In) => Effect.Effect<boolean, never, R2>\n  ): Schedule<Out, In, R | R2>\n} = internal.untilInputEffect\n\n/**\n * Returns a new schedule that stops execution when the given predicate on the\n * output evaluates to `true`.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that it only continues\n * executing while the given predicate returns false for its output values. Once\n * the predicate evaluates to `true`, execution stops.\n *\n * The output of the resulting schedule remains the same, but its duration is\n * now constrained by a stopping condition based on its own output.\n *\n * @see {@link untilOutputEffect} If you need to use an effectful predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const untilOutput: {\n  <Out>(f: Predicate<Out>): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(self: Schedule<Out, In, R>, f: Predicate<Out>): Schedule<Out, In, R>\n} = internal.untilOutput\n\n/**\n * Returns a new schedule that stops execution when the given effectful\n * predicate on the output evaluates to `true`.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that it only continues\n * executing while the provided effectful predicate returns `false` for its\n * output values. Once the predicate returns `true`, execution stops.\n *\n * @see {@link untilOutput} If you need to use a pure predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const untilOutputEffect: {\n  <Out, R2>(\n    f: (out: Out) => Effect.Effect<boolean, never, R2>\n  ): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R2 | R>\n  <Out, In, R, R2>(\n    self: Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<boolean, never, R2>\n  ): Schedule<Out, In, R | R2>\n} = internal.untilOutputEffect\n\n/**\n * Returns a new schedule that limits execution to a fixed duration.\n *\n * **Details**\n *\n * This function modifies an existing schedule to stop execution after a\n * specified duration has passed. The schedule continues as normal until the\n * duration is reached, at which point it stops automatically.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const upTo: {\n  (duration: Duration.DurationInput): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(self: Schedule<Out, In, R>, duration: Duration.DurationInput): Schedule<Out, In, R>\n} = internal.upTo\n\n/**\n * Returns a new schedule that continues execution as long as the given\n * predicate on the input is true.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that it only continues\n * execution while a specified predicate holds true for its input. If the\n * predicate evaluates to `false` at any step, the schedule stops.\n *\n * @see {@link whileInputEffect} If you need to use an effectful predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const whileInput: {\n  <In>(f: Predicate<In>): <Out, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(self: Schedule<Out, In, R>, f: Predicate<In>): Schedule<Out, In, R>\n} = internal.whileInput\n\n/**\n * Returns a new schedule that continues execution for as long as the given\n * effectful predicate on the input evaluates to `true`.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that it only continues\n * execution while an effectful predicate holds true for its input. If the\n * predicate evaluates to `false` at any step, the schedule stops.\n *\n * @see {@link whileInput} If you need to use a pure predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const whileInputEffect: {\n  <In, R2>(\n    f: (input: In) => Effect.Effect<boolean, never, R2>\n  ): <Out, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R2 | R>\n  <Out, In, R, R2>(\n    self: Schedule<Out, In, R>,\n    f: (input: In) => Effect.Effect<boolean, never, R2>\n  ): Schedule<Out, In, R | R2>\n} = internal.whileInputEffect\n\n/**\n * Returns a new schedule that continues execution for as long as the given\n * predicate on the output evaluates to `true`.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that it only continues\n * execution while a provided condition holds true for its output. If the\n * predicate returns `false`, the schedule stops.\n *\n * @see {@link whileOutputEffect} If you need to use an effectful predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const whileOutput: {\n  <Out>(f: Predicate<Out>): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R>\n  <Out, In, R>(self: Schedule<Out, In, R>, f: Predicate<Out>): Schedule<Out, In, R>\n} = internal.whileOutput\n\n/**\n * Returns a new schedule that continues execution for as long as the given\n * effectful predicate on the output evaluates to `true`.\n *\n * **Details**\n *\n * This function modifies an existing schedule so that it only continues\n * execution while an effectful condition holds true for its output. If the\n * effectful predicate returns `false`, the schedule stops.\n *\n * @see {@link whileOutput} If you need to use a pure predicate.\n *\n * @since 2.0.0\n * @category Recurrence Conditions\n */\nexport const whileOutputEffect: {\n  <Out, R2>(\n    f: (out: Out) => Effect.Effect<boolean, never, R2>\n  ): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In, R2 | R>\n  <Out, In, R, R2>(\n    self: Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<boolean, never, R2>\n  ): Schedule<Out, In, R | R2>\n} = internal.whileOutputEffect\n\n/**\n * Creates a schedule that divides time into fixed `interval`-long windows,\n * triggering execution at the start of each new window.\n *\n * **Details**\n *\n * This function produces a schedule that waits until the next time window\n * boundary before executing. Each window spans a fixed duration specified by\n * `interval`. If an action completes midway through a window, the schedule\n * waits until the next full window starts before proceeding.\n *\n * For example, `windowed(Duration.seconds(10))` would produce a schedule as\n * follows:\n *\n * ```text\n *      10s        10s        10s       10s\n * |----------|----------|----------|----------|\n * |action------|sleep---|act|-sleep|action----|\n * ```\n *\n * @since 2.0.0\n * @category Constructors\n */\nexport const windowed: (interval: Duration.DurationInput) => Schedule<number> = internal.windowed\n\n/**\n * The same as {@link intersect} but ignores the right output.\n *\n * @since 2.0.0\n * @category Composition\n */\nexport const zipLeft: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out, In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>\n  ): Schedule<Out, In & In2, R | R2>\n} = internal.zipLeft\n\n/**\n * The same as {@link intersect} but ignores the left output.\n *\n * @since 2.0.0\n * @category Composition\n */\nexport const zipRight: {\n  <Out2, In2, R2>(\n    that: Schedule<Out2, In2, R2>\n  ): <Out, In, R>(self: Schedule<Out, In, R>) => Schedule<Out2, In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>\n  ): Schedule<Out2, In & In2, R | R2>\n} = internal.zipRight\n\n/**\n * Equivalent to {@link intersect} followed by {@link map}.\n *\n * @since 2.0.0\n * @category Composition\n */\nexport const zipWith: {\n  <Out2, In2, R2, Out, Out3>(\n    that: Schedule<Out2, In2, R2>,\n    f: (out: Out, out2: Out2) => Out3\n  ): <In, R>(self: Schedule<Out, In, R>) => Schedule<Out3, In & In2, R2 | R>\n  <Out, In, R, Out2, In2, R2, Out3>(\n    self: Schedule<Out, In, R>,\n    that: Schedule<Out2, In2, R2>,\n    f: (out: Out, out2: Out2) => Out3\n  ): Schedule<Out3, In & In2, R | R2>\n} = internal.zipWith\n\n/**\n * @since 3.15.0\n * @category models\n */\nexport interface CurrentIterationMetadata {\n  readonly _: unique symbol\n}\n\n/**\n * @since 3.15.0\n * @category models\n */\nexport interface IterationMetadata {\n  readonly input: unknown\n  readonly output: unknown\n  readonly recurrence: number\n  readonly start: number\n  readonly now: number\n  readonly elapsed: Duration.Duration\n  readonly elapsedSincePrevious: Duration.Duration\n}\n\n/**\n * @since 3.15.0\n * @category models\n */\nexport const CurrentIterationMetadata: Context.Reference<\n  CurrentIterationMetadata,\n  IterationMetadata\n> = internal.CurrentIterationMetadata\n"
  },
  {
    "path": "packages/effect/src/ScheduleDecision.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/schedule/decision.js\"\nimport type * as Interval from \"./ScheduleInterval.js\"\nimport type * as Intervals from \"./ScheduleIntervals.js\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type ScheduleDecision = Continue | Done\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Continue {\n  readonly _tag: \"Continue\"\n  readonly intervals: Intervals.Intervals\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Done {\n  readonly _tag: \"Done\"\n}\n\nconst _continue = internal._continue\nexport {\n  /**\n   * @since 2.0.0\n   * @category constructors\n   */\n  _continue as continue\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const continueWith: (interval: Interval.Interval) => ScheduleDecision = internal.continueWith\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const done: ScheduleDecision = internal.done\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isContinue: (self: ScheduleDecision) => self is Continue = internal.isContinue\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isDone: (self: ScheduleDecision) => self is Done = internal.isDone\n"
  },
  {
    "path": "packages/effect/src/ScheduleInterval.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Duration from \"./Duration.js\"\nimport * as internal from \"./internal/schedule/interval.js\"\nimport type * as Option from \"./Option.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const IntervalTypeId: unique symbol = internal.IntervalTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type IntervalTypeId = typeof IntervalTypeId\n\n/**\n * An `Interval` represents an interval of time. Intervals can encompass all\n * time, or no time at all.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Interval {\n  readonly [IntervalTypeId]: IntervalTypeId\n  readonly startMillis: number\n  readonly endMillis: number\n}\n\n/**\n * Constructs a new interval from the two specified endpoints. If the start\n * endpoint greater than the end endpoint, then a zero size interval will be\n * returned.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (startMillis: number, endMillis: number) => Interval = internal.make\n\n/**\n * An `Interval` of zero-width.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: Interval = internal.empty\n\n/**\n * Returns `true` if this `Interval` is less than `that` interval, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category ordering\n */\nexport const lessThan: {\n  (that: Interval): (self: Interval) => boolean\n  (self: Interval, that: Interval): boolean\n} = internal.lessThan\n\n/**\n * Returns the minimum of two `Interval`s.\n *\n * @since 2.0.0\n * @category ordering\n */\nexport const min: {\n  (that: Interval): (self: Interval) => Interval\n  (self: Interval, that: Interval): Interval\n} = internal.min\n\n/**\n * Returns the maximum of two `Interval`s.\n *\n * @since 2.0.0\n * @category ordering\n */\nexport const max: {\n  (that: Interval): (self: Interval) => Interval\n  (self: Interval, that: Interval): Interval\n} = internal.max\n\n/**\n * Returns `true` if the specified `Interval` is empty, `false` otherwise.\n *\n * @since 2.0.0\n * @category ordering\n */\nexport const isEmpty: (self: Interval) => boolean = internal.isEmpty\n\n/**\n * Returns `true` if the specified `Interval` is non-empty, `false` otherwise.\n *\n * @since 2.0.0\n * @category ordering\n */\nexport const isNonEmpty: (self: Interval) => boolean = internal.isNonEmpty\n\n/**\n * Computes a new `Interval` which is the intersection of this `Interval` and\n * that `Interval`.\n *\n * @since 2.0.0\n * @category ordering\n */\nexport const intersect: {\n  (that: Interval): (self: Interval) => Interval\n  (self: Interval, that: Interval): Interval\n} = internal.intersect\n\n/**\n * Calculates the size of the `Interval` as the `Duration` from the start of the\n * interval to the end of the interval.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: (self: Interval) => Duration.Duration = internal.size\n\n/**\n * Computes a new `Interval` which is the union of this `Interval` and that\n * `Interval` as a `Some`, otherwise returns `None` if the two intervals cannot\n * form a union.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const union: {\n  (that: Interval): (self: Interval) => Option.Option<Interval>\n  (self: Interval, that: Interval): Option.Option<Interval>\n} = internal.union\n\n/**\n * Construct an `Interval` that includes all time equal to and after the\n * specified start time.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const after: (startMilliseconds: number) => Interval = internal.after\n\n/**\n * Construct an `Interval` that includes all time equal to and before the\n * specified end time.\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const before: (endMilliseconds: number) => Interval = internal.before\n"
  },
  {
    "path": "packages/effect/src/ScheduleIntervals.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Check from \"./Chunk.js\"\nimport * as internal from \"./internal/schedule/intervals.js\"\nimport type * as Interval from \"./ScheduleInterval.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const IntervalsTypeId: unique symbol = internal.IntervalsTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type IntervalsTypeId = typeof IntervalsTypeId\n\n/**\n * An `Intervals` represents a list of several `Interval`s.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Intervals {\n  readonly [IntervalsTypeId]: IntervalsTypeId\n  readonly intervals: Check.Chunk<Interval.Interval>\n}\n\n/**\n * Creates a new `Intervals` from a `List` of `Interval`s.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (intervals: Check.Chunk<Interval.Interval>) => Intervals = internal.make\n\n/**\n * Constructs an empty list of `Interval`s.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: Intervals = internal.empty\n\n/**\n * Creates `Intervals` from the specified `Iterable<Interval>`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: (intervals: Iterable<Interval.Interval>) => Intervals = internal.fromIterable\n\n/**\n * Computes the union of this `Intervals` and  that `Intervals`\n *\n * @since 2.0.0\n * @category utils\n */\nexport const union: {\n  (that: Intervals): (self: Intervals) => Intervals\n  (self: Intervals, that: Intervals): Intervals\n} = internal.union\n\n/**\n * Produces the intersection of this `Intervals` and that `Intervals`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const intersect: {\n  (that: Intervals): (self: Intervals) => Intervals\n  (self: Intervals, that: Intervals): Intervals\n} = internal.intersect\n\n/**\n * The start of the earliest interval in the specified `Intervals`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const start: (self: Intervals) => number = internal.start\n\n/**\n * The end of the latest interval in the specified `Intervals`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const end: (self: Intervals) => number = internal.end\n\n/**\n * Returns `true` if the start of this `Intervals` is before the start of that\n * `Intervals`, `false` otherwise.\n *\n * @since 2.0.0\n * @category ordering\n */\nexport const lessThan: {\n  (that: Intervals): (self: Intervals) => boolean\n  (self: Intervals, that: Intervals): boolean\n} = internal.lessThan\n\n/**\n * Returns `true` if this `Intervals` is non-empty, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isNonEmpty: (self: Intervals) => boolean = internal.isNonEmpty\n\n/**\n * Returns the maximum of the two `Intervals` (i.e. which has the latest start).\n *\n * @since 2.0.0\n * @category ordering\n */\nexport const max: {\n  (that: Intervals): (self: Intervals) => Intervals\n  (self: Intervals, that: Intervals): Intervals\n} = internal.max\n"
  },
  {
    "path": "packages/effect/src/Scheduler.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport type { Effect } from \"./Effect.js\"\nimport type { RuntimeFiber } from \"./Fiber.js\"\nimport type { FiberRef } from \"./FiberRef.js\"\nimport { dual } from \"./Function.js\"\nimport { globalValue } from \"./GlobalValue.js\"\nimport * as core from \"./internal/core.js\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type Task = () => void\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Scheduler {\n  shouldYield(fiber: RuntimeFiber<unknown, unknown>): number | false\n  scheduleTask(task: Task, priority: number, fiber?: RuntimeFiber<unknown, unknown>): void\n}\n\n/**\n * @since 3.20.0\n * @category models\n */\nexport class SchedulerRunner {\n  running = false\n  tasks = new PriorityBuckets()\n\n  constructor(\n    readonly scheduleDrain: (depth: number, drain: (depth: number) => void) => void\n  ) {}\n\n  private starveInternal = (depth: number) => {\n    const tasks = this.tasks.buckets\n    this.tasks.buckets = []\n    for (const [_, toRun] of tasks) {\n      for (let i = 0; i < toRun.length; i++) {\n        toRun[i]()\n      }\n    }\n    if (this.tasks.buckets.length === 0) {\n      this.running = false\n    } else {\n      this.starve(depth)\n    }\n  }\n\n  private starve(depth = 0) {\n    this.scheduleDrain(depth, this.starveInternal)\n  }\n\n  scheduleTask(task: Task, priority: number) {\n    this.tasks.scheduleTask(task, priority)\n    if (!this.running) {\n      this.running = true\n      this.starve()\n    }\n  }\n  /**\n   * @since 3.20.0\n   * @category constructors\n   */\n  static cached(\n    scheduleDrain: (depth: number, drain: (depth: number) => void) => void\n  ) {\n    const fallback = new SchedulerRunner(scheduleDrain)\n    const runners = new WeakMap<RuntimeFiber<unknown, unknown>, SchedulerRunner>()\n\n    return (fiber?: RuntimeFiber<unknown, unknown>) => {\n      if (fiber === undefined) {\n        return fallback\n      }\n      let runner = runners.get(fiber)\n      if (runner === undefined) {\n        runner = new SchedulerRunner(scheduleDrain)\n        runners.set(fiber, runner)\n      }\n      return runner\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport class PriorityBuckets<in out T = Task> {\n  /**\n   * @since 2.0.0\n   */\n  public buckets: Array<[number, Array<T>]> = []\n  /**\n   * @since 2.0.0\n   */\n  scheduleTask(task: T, priority: number) {\n    const length = this.buckets.length\n    let bucket: [number, Array<T>] | undefined = undefined\n    let index = 0\n    for (; index < length; index++) {\n      if (this.buckets[index][0] <= priority) {\n        bucket = this.buckets[index]\n      } else {\n        break\n      }\n    }\n    if (bucket && bucket[0] === priority) {\n      bucket[1].push(task)\n    } else if (index === length) {\n      this.buckets.push([priority, [task]])\n    } else {\n      this.buckets.splice(index, 0, [priority, [task]])\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport class MixedScheduler implements Scheduler {\n  private readonly getRunner = SchedulerRunner.cached((depth, drain) => {\n    if (depth >= this.maxNextTickBeforeTimer) {\n      setTimeout(() => drain(0), 0)\n    } else {\n      Promise.resolve(void 0).then(() => drain(depth + 1))\n    }\n  })\n\n  constructor(\n    /**\n     * @since 2.0.0\n     */\n    readonly maxNextTickBeforeTimer: number\n  ) {}\n\n  /**\n   * @since 2.0.0\n   */\n  shouldYield(fiber: RuntimeFiber<unknown, unknown>): number | false {\n    return fiber.currentOpCount > fiber.getFiberRef(core.currentMaxOpsBeforeYield)\n      ? fiber.getFiberRef(core.currentSchedulingPriority)\n      : false\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  scheduleTask(task: Task, priority: number, fiber?: RuntimeFiber<unknown, unknown>) {\n    this.getRunner(fiber).scheduleTask(task, priority)\n  }\n}\n\n/**\n * @since 2.0.0\n * @category schedulers\n */\nexport const defaultScheduler: Scheduler = globalValue(\n  Symbol.for(\"effect/Scheduler/defaultScheduler\"),\n  () => new MixedScheduler(2048)\n)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport class SyncScheduler implements Scheduler {\n  /**\n   * @since 2.0.0\n   */\n  tasks = new PriorityBuckets()\n\n  /**\n   * @since 2.0.0\n   */\n  deferred = false\n\n  /**\n   * @since 2.0.0\n   */\n  scheduleTask(task: Task, priority: number, fiber?: RuntimeFiber<unknown, unknown>) {\n    if (this.deferred) {\n      defaultScheduler.scheduleTask(task, priority, fiber)\n    } else {\n      this.tasks.scheduleTask(task, priority)\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  shouldYield(fiber: RuntimeFiber<unknown, unknown>): number | false {\n    return fiber.currentOpCount > fiber.getFiberRef(core.currentMaxOpsBeforeYield)\n      ? fiber.getFiberRef(core.currentSchedulingPriority)\n      : false\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  flush() {\n    while (this.tasks.buckets.length > 0) {\n      const tasks = this.tasks.buckets\n      this.tasks.buckets = []\n      for (const [_, toRun] of tasks) {\n        for (let i = 0; i < toRun.length; i++) {\n          toRun[i]()\n        }\n      }\n    }\n    this.deferred = true\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport class ControlledScheduler implements Scheduler {\n  /**\n   * @since 2.0.0\n   */\n  tasks = new PriorityBuckets()\n\n  /**\n   * @since 2.0.0\n   */\n  deferred = false\n\n  /**\n   * @since 2.0.0\n   */\n  scheduleTask(task: Task, priority: number, fiber?: RuntimeFiber<unknown, unknown>) {\n    if (this.deferred) {\n      defaultScheduler.scheduleTask(task, priority, fiber)\n    } else {\n      this.tasks.scheduleTask(task, priority)\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  shouldYield(fiber: RuntimeFiber<unknown, unknown>): number | false {\n    return fiber.currentOpCount > fiber.getFiberRef(core.currentMaxOpsBeforeYield)\n      ? fiber.getFiberRef(core.currentSchedulingPriority)\n      : false\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  step() {\n    const tasks = this.tasks.buckets\n    this.tasks.buckets = []\n    for (const [_, toRun] of tasks) {\n      for (let i = 0; i < toRun.length; i++) {\n        toRun[i]()\n      }\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const makeMatrix = (...record: Array<[number, Scheduler]>): Scheduler => {\n  const index = record.sort(([p0], [p1]) => p0 < p1 ? -1 : p0 > p1 ? 1 : 0)\n  return {\n    shouldYield(fiber) {\n      for (const scheduler of record) {\n        const priority = scheduler[1].shouldYield(fiber)\n        if (priority !== false) {\n          return priority\n        }\n      }\n      return false\n    },\n    scheduleTask(task, priority, fiber) {\n      let scheduler: Scheduler | undefined = undefined\n      for (const i of index) {\n        if (priority >= i[0]) {\n          scheduler = i[1]\n        } else {\n          return (scheduler ?? defaultScheduler).scheduleTask(task, priority, fiber)\n        }\n      }\n      return (scheduler ?? defaultScheduler).scheduleTask(task, priority, fiber)\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category utilities\n */\nexport const defaultShouldYield: Scheduler[\"shouldYield\"] = (fiber) => {\n  return fiber.currentOpCount > fiber.getFiberRef(core.currentMaxOpsBeforeYield)\n    ? fiber.getFiberRef(core.currentSchedulingPriority)\n    : false\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make = (\n  scheduleTask: Scheduler[\"scheduleTask\"],\n  shouldYield: Scheduler[\"shouldYield\"] = defaultShouldYield\n): Scheduler => ({\n  scheduleTask,\n  shouldYield\n})\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const makeBatched = (\n  callback: (runBatch: () => void) => void,\n  shouldYield: Scheduler[\"shouldYield\"] = defaultShouldYield\n) => {\n  const getRunner = SchedulerRunner.cached((_, drain) => {\n    callback(() => drain(0))\n  })\n\n  return make((task, priority, fiber) => {\n    getRunner(fiber).scheduleTask(task, priority)\n  }, shouldYield)\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const timer = (ms: number, shouldYield: Scheduler[\"shouldYield\"] = defaultShouldYield) =>\n  make((task) => setTimeout(task, ms), shouldYield)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const timerBatched = (ms: number, shouldYield: Scheduler[\"shouldYield\"] = defaultShouldYield) =>\n  makeBatched((task) => setTimeout(task, ms), shouldYield)\n\n/** @internal */\nexport const currentScheduler: FiberRef<Scheduler> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentScheduler\"),\n  () => core.fiberRefUnsafeMake(defaultScheduler)\n)\n\n/** @internal */\nexport const withScheduler = dual<\n  (scheduler: Scheduler) => <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>,\n  <A, E, R>(self: Effect<A, E, R>, scheduler: Scheduler) => Effect<A, E, R>\n>(2, (self, scheduler) => core.fiberRefLocally(self, currentScheduler, scheduler))\n"
  },
  {
    "path": "packages/effect/src/Schema.ts",
    "content": "/**\n * @since 3.10.0\n */\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\nimport type { ArbitraryAnnotation, ArbitraryGenerationContext, LazyArbitrary } from \"./Arbitrary.js\"\nimport * as array_ from \"./Array.js\"\nimport * as bigDecimal_ from \"./BigDecimal.js\"\nimport * as bigInt_ from \"./BigInt.js\"\nimport * as boolean_ from \"./Boolean.js\"\nimport type { Brand } from \"./Brand.js\"\nimport * as cause_ from \"./Cause.js\"\nimport * as chunk_ from \"./Chunk.js\"\nimport * as config_ from \"./Config.js\"\nimport * as configError_ from \"./ConfigError.js\"\nimport * as data_ from \"./Data.js\"\nimport * as dateTime from \"./DateTime.js\"\nimport * as duration_ from \"./Duration.js\"\nimport * as Effect from \"./Effect.js\"\nimport * as either_ from \"./Either.js\"\nimport * as Encoding from \"./Encoding.js\"\nimport * as Equal from \"./Equal.js\"\nimport * as Equivalence from \"./Equivalence.js\"\nimport * as exit_ from \"./Exit.js\"\nimport * as fastCheck_ from \"./FastCheck.js\"\nimport * as fiberId_ from \"./FiberId.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport { dual, identity } from \"./Function.js\"\nimport { globalValue } from \"./GlobalValue.js\"\nimport * as hashMap_ from \"./HashMap.js\"\nimport * as hashSet_ from \"./HashSet.js\"\nimport * as Inspectable from \"./Inspectable.js\"\nimport * as internalCause_ from \"./internal/cause.js\"\nimport * as errors_ from \"./internal/schema/errors.js\"\nimport * as schemaId_ from \"./internal/schema/schemaId.js\"\nimport * as util_ from \"./internal/schema/util.js\"\nimport * as list_ from \"./List.js\"\nimport * as number_ from \"./Number.js\"\nimport * as option_ from \"./Option.js\"\nimport type * as Order from \"./Order.js\"\nimport * as ParseResult from \"./ParseResult.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport type * as pretty_ from \"./Pretty.js\"\nimport * as redacted_ from \"./Redacted.js\"\nimport * as Request from \"./Request.js\"\nimport * as scheduler_ from \"./Scheduler.js\"\nimport type { ParseOptions } from \"./SchemaAST.js\"\nimport * as AST from \"./SchemaAST.js\"\nimport * as sortedSet_ from \"./SortedSet.js\"\nimport * as string_ from \"./String.js\"\nimport * as struct_ from \"./Struct.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 3.10.0\n */\nexport type Simplify<A> = { [K in keyof A]: A[K] } & {}\n\n/**\n * @since 3.10.0\n */\nexport type SimplifyMutable<A> = {\n  -readonly [K in keyof A]: A[K]\n} extends infer B ? B : never\n\n/**\n * @since 3.10.0\n * @category symbol\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/Schema\")\n\n/**\n * @since 3.10.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface Schema<in out A, in out I = A, out R = never> extends Schema.Variance<A, I, R>, Pipeable {\n  readonly Type: A\n  readonly Encoded: I\n  readonly Context: R\n  readonly ast: AST.AST\n  /**\n   * Merges a set of new annotations with existing ones, potentially overwriting\n   * any duplicates.\n   */\n  annotations(annotations: Annotations.GenericSchema<A>): Schema<A, I, R>\n}\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport interface Annotable<Self extends Schema<A, I, R>, A, I = A, R = never> extends Schema<A, I, R> {\n  annotations(annotations: Annotations.GenericSchema<A>): Self\n}\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport interface AnnotableClass<Self extends Schema<A, I, R>, A, I = A, R = never> extends Annotable<Self, A, I, R> {\n  new(_: never): Schema.Variance<A, I, R>\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface SchemaClass<A, I = A, R = never> extends AnnotableClass<SchemaClass<A, I, R>, A, I, R> {}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport function make<A, I = A, R = never>(ast: AST.AST): SchemaClass<A, I, R> {\n  return class SchemaClass {\n    [TypeId] = variance\n    static ast = ast\n    static annotations(annotations: Annotations.GenericSchema<A>) {\n      return make<A, I, R>(mergeSchemaAnnotations(this.ast, annotations))\n    }\n    static pipe() {\n      return pipeArguments(this, arguments)\n    }\n    static toString() {\n      return String(ast)\n    }\n    static Type: A\n    static Encoded: I\n    static Context: R\n    static [TypeId] = variance\n  }\n}\n\nconst variance = {\n  /* c8 ignore next */\n  _A: (_: any) => _,\n  /* c8 ignore next */\n  _I: (_: any) => _,\n  /* c8 ignore next */\n  _R: (_: never) => _\n}\n\nconst makeStandardResult = <A>(exit: exit_.Exit<StandardSchemaV1.Result<A>>): StandardSchemaV1.Result<A> =>\n  exit_.isSuccess(exit) ? exit.value : makeStandardFailureResult(cause_.pretty(exit.cause))\n\nconst makeStandardFailureResult = (message: string): StandardSchemaV1.FailureResult => ({\n  issues: [{ message }]\n})\n\nconst makeStandardFailureFromParseIssue = (\n  issue: ParseResult.ParseIssue\n): Effect.Effect<StandardSchemaV1.FailureResult> =>\n  Effect.map(ParseResult.ArrayFormatter.formatIssue(issue), (issues) => ({\n    issues: issues.map((issue) => ({\n      path: issue.path,\n      message: issue.message\n    }))\n  }))\n\n/**\n * Returns a \"Standard Schema\" object conforming to the [Standard Schema\n * v1](https://standardschema.dev/) specification.\n *\n * This function creates a schema whose `validate` method attempts to decode and\n * validate the provided input synchronously. If the underlying `Schema`\n * includes any asynchronous components (e.g., asynchronous message resolutions\n * or checks), then validation will necessarily return a `Promise` instead.\n *\n * Any detected defects will be reported via a single issue containing no\n * `path`.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n *\n * const schema = Schema.Struct({\n *   name: Schema.String\n * })\n *\n * //      ┌─── StandardSchemaV1<{ readonly name: string; }>\n * //      ▼\n * const standardSchema = Schema.standardSchemaV1(schema)\n * ```\n *\n * @category Standard Schema\n * @since 3.13.0\n */\nexport const standardSchemaV1 = <A, I>(\n  schema: Schema<A, I, never>,\n  overrideOptions?: AST.ParseOptions\n): StandardSchemaV1<I, A> & SchemaClass<A, I, never> => {\n  const decodeUnknown = ParseResult.decodeUnknown(schema, { errors: \"all\" })\n  return class StandardSchemaV1Class extends make<A, I, never>(schema.ast) {\n    static \"~standard\" = {\n      version: 1,\n      vendor: \"effect\",\n      validate(value) {\n        const scheduler = new scheduler_.SyncScheduler()\n        const fiber = Effect.runFork(\n          Effect.matchEffect(decodeUnknown(value, overrideOptions), {\n            onFailure: makeStandardFailureFromParseIssue,\n            onSuccess: (value) => Effect.succeed({ value })\n          }),\n          { scheduler }\n        )\n        scheduler.flush()\n        const exit = fiber.unsafePoll()\n        if (exit) {\n          return makeStandardResult(exit)\n        }\n        return new Promise((resolve) => {\n          fiber.addObserver((exit) => {\n            resolve(makeStandardResult(exit))\n          })\n        })\n      }\n    }\n  }\n}\n\ninterface AllAnnotations<A, TypeParameters extends ReadonlyArray<any>>\n  extends Annotations.Schema<A, TypeParameters>, PropertySignature.Annotations<A>\n{}\n\nconst builtInAnnotations = {\n  typeConstructor: AST.TypeConstructorAnnotationId,\n  schemaId: AST.SchemaIdAnnotationId,\n  message: AST.MessageAnnotationId,\n  missingMessage: AST.MissingMessageAnnotationId,\n  identifier: AST.IdentifierAnnotationId,\n  title: AST.TitleAnnotationId,\n  description: AST.DescriptionAnnotationId,\n  examples: AST.ExamplesAnnotationId,\n  default: AST.DefaultAnnotationId,\n  documentation: AST.DocumentationAnnotationId,\n  jsonSchema: AST.JSONSchemaAnnotationId,\n  arbitrary: AST.ArbitraryAnnotationId,\n  pretty: AST.PrettyAnnotationId,\n  equivalence: AST.EquivalenceAnnotationId,\n  concurrency: AST.ConcurrencyAnnotationId,\n  batching: AST.BatchingAnnotationId,\n  parseIssueTitle: AST.ParseIssueTitleAnnotationId,\n  parseOptions: AST.ParseOptionsAnnotationId,\n  decodingFallback: AST.DecodingFallbackAnnotationId\n}\n\nconst toASTAnnotations = <A, TypeParameters extends ReadonlyArray<any>>(\n  annotations?: AllAnnotations<A, TypeParameters>\n): AST.Annotations => {\n  if (!annotations) {\n    return {}\n  }\n  const out: Types.Mutable<AST.Annotations> = { ...annotations }\n\n  for (const key in builtInAnnotations) {\n    if (key in annotations) {\n      const id = builtInAnnotations[key as keyof typeof builtInAnnotations]\n      out[id] = annotations[key as keyof typeof annotations]\n      delete out[key]\n    }\n  }\n\n  return out\n}\n\nconst mergeSchemaAnnotations = <A>(ast: AST.AST, annotations: Annotations.Schema<A>): AST.AST =>\n  AST.annotations(ast, toASTAnnotations(annotations))\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport declare namespace Annotable {\n  /**\n   * @since 3.10.0\n   */\n  export type Self<S extends All> = ReturnType<S[\"annotations\"]>\n\n  /**\n   * @since 3.10.0\n   */\n  export type Any = Annotable<any, any, any, unknown>\n\n  /**\n   * @since 3.10.0\n   */\n  export type All =\n    | Any\n    | Annotable<any, any, never, unknown>\n    | Annotable<any, never, any, unknown>\n    | Annotable<any, never, never, unknown>\n}\n\n/**\n * @since 3.10.0\n */\nexport function asSchema<S extends Schema.All>(\n  schema: S\n): Schema<Schema.Type<S>, Schema.Encoded<S>, Schema.Context<S>> {\n  return schema as any\n}\n\n/**\n * @category formatting\n * @since 3.10.0\n */\nexport const format = <S extends Schema.All>(schema: S): string => String(schema.ast)\n\n/**\n * @since 3.10.0\n */\nexport declare namespace Schema {\n  /**\n   * @since 3.10.0\n   */\n  export interface Variance<A, I, R> {\n    readonly [TypeId]: {\n      readonly _A: Types.Invariant<A>\n      readonly _I: Types.Invariant<I>\n      readonly _R: Types.Covariant<R>\n    }\n  }\n\n  /**\n   * @since 3.10.0\n   */\n  export type Type<S> = S extends Schema.Variance<infer A, infer _I, infer _R> ? A : never\n\n  /**\n   * @since 3.10.0\n   */\n  export type Encoded<S> = S extends Schema.Variance<infer _A, infer I, infer _R> ? I : never\n\n  /**\n   * @since 3.10.0\n   */\n  export type Context<S> = S extends Schema.Variance<infer _A, infer _I, infer R> ? R : never\n\n  /**\n   * @since 3.10.0\n   */\n  export type ToAsserts<S extends AnyNoContext> = (\n    input: unknown,\n    options?: AST.ParseOptions\n  ) => asserts input is Schema.Type<S>\n\n  /**\n   * Any schema, except for `never`.\n   *\n   * @since 3.10.0\n   */\n  export type Any = Schema<any, any, unknown>\n\n  /**\n   * Any schema with `Context = never`, except for `never`.\n   *\n   * @since 3.10.0\n   */\n  export type AnyNoContext = Schema<any, any, never>\n\n  /**\n   * Any schema, including `never`.\n   *\n   * @since 3.10.0\n   */\n  export type All =\n    | Any\n    | Schema<any, never, unknown>\n    | Schema<never, any, unknown>\n    | Schema<never, never, unknown>\n\n  /**\n   * Type-level counterpart of `Schema.asSchema` function.\n   *\n   * @since 3.10.0\n   */\n  export type AsSchema<S extends All> = Schema<Type<S>, Encoded<S>, Context<S>>\n}\n\n/**\n * The `encodedSchema` function allows you to extract the `Encoded` portion of a\n * schema, creating a new schema that conforms to the properties defined in the\n * original schema without retaining any refinements or transformations that\n * were applied previously.\n *\n * @since 3.10.0\n */\nexport const encodedSchema = <A, I, R>(schema: Schema<A, I, R>): SchemaClass<I> => make(AST.encodedAST(schema.ast))\n\n/**\n * The `encodedBoundSchema` function is similar to `encodedSchema` but preserves\n * the refinements up to the first transformation point in the original schema.\n *\n * @since 3.10.0\n */\nexport const encodedBoundSchema = <A, I, R>(schema: Schema<A, I, R>): SchemaClass<I> =>\n  make(AST.encodedBoundAST(schema.ast))\n\n/**\n * The `typeSchema` function allows you to extract the `Type` portion of a\n * schema, creating a new schema that conforms to the properties defined in the\n * original schema without considering the initial encoding or transformation\n * processes.\n *\n * @since 3.10.0\n */\nexport const typeSchema = <A, I, R>(schema: Schema<A, I, R>): SchemaClass<A> => make(AST.typeAST(schema.ast))\n\n/* c8 ignore start */\nexport {\n  /**\n   * By default the option `exact` is set to `true`.\n   *\n   * @throws `ParseError`\n   * @category validation\n   * @since 3.10.0\n   */\n  asserts,\n  /**\n   * @category decoding\n   * @since 3.10.0\n   */\n  decodeOption,\n  /**\n   * @throws `ParseError`\n   * @category decoding\n   * @since 3.10.0\n   */\n  decodeSync,\n  /**\n   * @category decoding\n   * @since 3.10.0\n   */\n  decodeUnknownOption,\n  /**\n   * @throws `ParseError`\n   * @category decoding\n   * @since 3.10.0\n   */\n  decodeUnknownSync,\n  /**\n   * @category encoding\n   * @since 3.10.0\n   */\n  encodeOption,\n  /**\n   * @throws `ParseError`\n   * @category encoding\n   * @since 3.10.0\n   */\n  encodeSync,\n  /**\n   * @category encoding\n   * @since 3.10.0\n   */\n  encodeUnknownOption,\n  /**\n   * @throws `ParseError`\n   * @category encoding\n   * @since 3.10.0\n   */\n  encodeUnknownSync,\n  /**\n   * By default the option `exact` is set to `true`.\n   *\n   * @category validation\n   * @since 3.10.0\n   */\n  is,\n  /**\n   * @category validation\n   * @since 3.10.0\n   */\n  validateOption,\n  /**\n   * @throws `ParseError`\n   * @category validation\n   * @since 3.10.0\n   */\n  validateSync\n} from \"./ParseResult.js\"\n/* c8 ignore end */\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeUnknown = <A, I, R>(\n  schema: Schema<A, I, R>,\n  options?: ParseOptions\n) => {\n  const encodeUnknown = ParseResult.encodeUnknown(schema, options)\n  return (u: unknown, overrideOptions?: ParseOptions): Effect.Effect<I, ParseResult.ParseError, R> =>\n    ParseResult.mapError(encodeUnknown(u, overrideOptions), ParseResult.parseError)\n}\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeUnknownEither = <A, I>(\n  schema: Schema<A, I, never>,\n  options?: ParseOptions\n) => {\n  const encodeUnknownEither = ParseResult.encodeUnknownEither(schema, options)\n  return (u: unknown, overrideOptions?: ParseOptions): either_.Either<I, ParseResult.ParseError> =>\n    either_.mapLeft(encodeUnknownEither(u, overrideOptions), ParseResult.parseError)\n}\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeUnknownPromise = <A, I>(\n  schema: Schema<A, I, never>,\n  options?: ParseOptions\n) => {\n  const parser = encodeUnknown(schema, options)\n  return (u: unknown, overrideOptions?: ParseOptions): Promise<I> => Effect.runPromise(parser(u, overrideOptions))\n}\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encode: <A, I, R>(\n  schema: Schema<A, I, R>,\n  options?: ParseOptions\n) => (a: A, overrideOptions?: ParseOptions) => Effect.Effect<I, ParseResult.ParseError, R> = encodeUnknown\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodeEither: <A, I>(\n  schema: Schema<A, I, never>,\n  options?: ParseOptions\n) => (a: A, overrideOptions?: ParseOptions) => either_.Either<I, ParseResult.ParseError> = encodeUnknownEither\n\n/**\n * @category encoding\n * @since 3.10.0\n */\nexport const encodePromise: <A, I>(\n  schema: Schema<A, I, never>,\n  options?: ParseOptions\n) => (a: A, overrideOptions?: ParseOptions) => Promise<I> = encodeUnknownPromise\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeUnknown = <A, I, R>(\n  schema: Schema<A, I, R>,\n  options?: ParseOptions\n) => {\n  const decodeUnknown = ParseResult.decodeUnknown(schema, options)\n  return (u: unknown, overrideOptions?: ParseOptions): Effect.Effect<A, ParseResult.ParseError, R> =>\n    ParseResult.mapError(decodeUnknown(u, overrideOptions), ParseResult.parseError)\n}\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeUnknownEither = <A, I>(\n  schema: Schema<A, I, never>,\n  options?: ParseOptions\n) => {\n  const decodeUnknownEither = ParseResult.decodeUnknownEither(schema, options)\n  return (u: unknown, overrideOptions?: ParseOptions): either_.Either<A, ParseResult.ParseError> =>\n    either_.mapLeft(decodeUnknownEither(u, overrideOptions), ParseResult.parseError)\n}\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeUnknownPromise = <A, I>(\n  schema: Schema<A, I, never>,\n  options?: ParseOptions\n) => {\n  const parser = decodeUnknown(schema, options)\n  return (u: unknown, overrideOptions?: ParseOptions): Promise<A> => Effect.runPromise(parser(u, overrideOptions))\n}\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decode: <A, I, R>(\n  schema: Schema<A, I, R>,\n  options?: ParseOptions\n) => (i: I, overrideOptions?: ParseOptions) => Effect.Effect<A, ParseResult.ParseError, R> = decodeUnknown\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodeEither: <A, I>(\n  schema: Schema<A, I, never>,\n  options?: ParseOptions\n) => (i: I, overrideOptions?: ParseOptions) => either_.Either<A, ParseResult.ParseError> = decodeUnknownEither\n\n/**\n * @category decoding\n * @since 3.10.0\n */\nexport const decodePromise: <A, I>(\n  schema: Schema<A, I, never>,\n  options?: ParseOptions\n) => (i: I, overrideOptions?: ParseOptions) => Promise<A> = decodeUnknownPromise\n\n/**\n * @category validation\n * @since 3.10.0\n */\nexport const validate = <A, I, R>(\n  schema: Schema<A, I, R>,\n  options?: ParseOptions\n) => {\n  const validate = ParseResult.validate(schema, options)\n  return (u: unknown, overrideOptions?: ParseOptions): Effect.Effect<A, ParseResult.ParseError, R> =>\n    ParseResult.mapError(validate(u, overrideOptions), ParseResult.parseError)\n}\n\n/**\n * @category validation\n * @since 3.10.0\n */\nexport const validateEither = <A, I, R>(\n  schema: Schema<A, I, R>,\n  options?: ParseOptions\n) => {\n  const validateEither = ParseResult.validateEither(schema, options)\n  return (u: unknown, overrideOptions?: ParseOptions): either_.Either<A, ParseResult.ParseError> =>\n    either_.mapLeft(validateEither(u, overrideOptions), ParseResult.parseError)\n}\n\n/**\n * @category validation\n * @since 3.10.0\n */\nexport const validatePromise = <A, I>(\n  schema: Schema<A, I, never>,\n  options?: ParseOptions\n) => {\n  const parser = validate(schema, options)\n  return (u: unknown, overrideOptions?: ParseOptions): Promise<A> => Effect.runPromise(parser(u, overrideOptions))\n}\n\n/**\n * Tests if a value is a `Schema`.\n *\n * @category guards\n * @since 3.10.0\n */\nexport const isSchema = (u: unknown): u is Schema.Any =>\n  Predicate.hasProperty(u, TypeId) && Predicate.isObject(u[TypeId])\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Literal<Literals extends array_.NonEmptyReadonlyArray<AST.LiteralValue>>\n  extends AnnotableClass<Literal<Literals>, Literals[number]>\n{\n  readonly literals: Readonly<Literals>\n}\n\nfunction getDefaultLiteralAST<Literals extends array_.NonEmptyReadonlyArray<AST.LiteralValue>>(\n  literals: Literals\n): AST.AST {\n  return AST.isMembers(literals)\n    ? AST.Union.make(AST.mapMembers(literals, (literal) => new AST.Literal(literal)))\n    : new AST.Literal(literals[0])\n}\n\nfunction makeLiteralClass<Literals extends array_.NonEmptyReadonlyArray<AST.LiteralValue>>(\n  literals: Literals,\n  ast: AST.AST = getDefaultLiteralAST(literals)\n): Literal<Literals> {\n  return class LiteralClass extends make<Literals[number]>(ast) {\n    static override annotations(annotations: Annotations.Schema<Literals[number]>): Literal<Literals> {\n      return makeLiteralClass(this.literals, mergeSchemaAnnotations(this.ast, annotations))\n    }\n    static literals = [...literals] as Literals\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport function Literal<Literals extends array_.NonEmptyReadonlyArray<AST.LiteralValue>>(\n  ...literals: Literals\n): Literal<Literals>\nexport function Literal(): Never\nexport function Literal<Literals extends ReadonlyArray<AST.LiteralValue>>(\n  ...literals: Literals\n): SchemaClass<Literals[number]>\nexport function Literal<Literals extends ReadonlyArray<AST.LiteralValue>>(\n  ...literals: Literals\n): SchemaClass<Literals[number]> | Never {\n  return array_.isNonEmptyReadonlyArray(literals) ? makeLiteralClass(literals) : Never\n}\n\n/**\n * Creates a new `Schema` from a literal schema.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Either, Schema } from \"effect\"\n *\n * const schema = Schema.Literal(\"a\", \"b\", \"c\").pipe(Schema.pickLiteral(\"a\", \"b\"))\n *\n * assert.deepStrictEqual(Schema.decodeSync(schema)(\"a\"), \"a\")\n * assert.deepStrictEqual(Schema.decodeSync(schema)(\"b\"), \"b\")\n * assert.strictEqual(Either.isLeft(Schema.decodeUnknownEither(schema)(\"c\")), true)\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const pickLiteral =\n  <A extends AST.LiteralValue, L extends array_.NonEmptyReadonlyArray<A>>(...literals: L) =>\n  <I, R>(_schema: Schema<A, I, R>): Literal<[...L]> => Literal(...literals)\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const UniqueSymbolFromSelf = <S extends symbol>(symbol: S): SchemaClass<S> => make(new AST.UniqueSymbol(symbol))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Enums<A extends EnumsDefinition> extends AnnotableClass<Enums<A>, A[keyof A]> {\n  readonly enums: A\n}\n\n/**\n * @since 3.10.0\n */\nexport type EnumsDefinition = { [x: string]: string | number }\n\nconst getDefaultEnumsAST = <A extends EnumsDefinition>(enums: A) =>\n  new AST.Enums(\n    Object.keys(enums).filter(\n      (key) => typeof enums[enums[key]] !== \"number\"\n    ).map((key) => [key, enums[key]])\n  )\n\nconst makeEnumsClass = <A extends EnumsDefinition>(\n  enums: A,\n  ast: AST.AST = getDefaultEnumsAST(enums)\n): Enums<A> => (class EnumsClass extends make<A[keyof A]>(ast) {\n  static override annotations(annotations: Annotations.Schema<A[keyof A]>) {\n    return makeEnumsClass(this.enums, mergeSchemaAnnotations(this.ast, annotations))\n  }\n\n  static enums = { ...enums }\n})\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const Enums = <A extends EnumsDefinition>(enums: A): Enums<A> => makeEnumsClass(enums)\n\ntype AppendType<\n  Template extends string,\n  Next\n> = Next extends AST.LiteralValue ? `${Template}${Next}`\n  : Next extends Schema<infer A extends AST.LiteralValue, infer _I, infer _R> ? `${Template}${A}`\n  : never\n\ntype GetTemplateLiteralType<Params> = Params extends [...infer Init, infer Last] ?\n  AppendType<GetTemplateLiteralType<Init>, Last>\n  : ``\n\n/**\n * @category API interface\n * @since 3.10.0\n */\nexport interface TemplateLiteral<A> extends SchemaClass<A> {}\n\ntype TemplateLiteralParameter = Schema.AnyNoContext | AST.LiteralValue\n\n/**\n * @category template literal\n * @since 3.10.0\n */\nexport const TemplateLiteral = <Params extends array_.NonEmptyReadonlyArray<TemplateLiteralParameter>>(\n  ...[head, ...tail]: Params\n): TemplateLiteral<GetTemplateLiteralType<Params>> => {\n  const spans: Array<AST.TemplateLiteralSpan> = []\n  let h = \"\"\n  let ts = tail\n\n  if (isSchema(head)) {\n    if (AST.isLiteral(head.ast)) {\n      h = String(head.ast.literal)\n    } else {\n      ts = [head, ...ts]\n    }\n  } else {\n    h = String(head)\n  }\n\n  for (let i = 0; i < ts.length; i++) {\n    const item = ts[i]\n    if (isSchema(item)) {\n      if (i < ts.length - 1) {\n        const next = ts[i + 1]\n        if (isSchema(next)) {\n          if (AST.isLiteral(next.ast)) {\n            spans.push(new AST.TemplateLiteralSpan(item.ast, String(next.ast.literal)))\n            i++\n            continue\n          }\n        } else {\n          spans.push(new AST.TemplateLiteralSpan(item.ast, String(next)))\n          i++\n          continue\n        }\n      }\n      spans.push(new AST.TemplateLiteralSpan(item.ast, \"\"))\n    } else {\n      spans.push(new AST.TemplateLiteralSpan(new AST.Literal(item), \"\"))\n    }\n  }\n\n  if (array_.isNonEmptyArray(spans)) {\n    return make(new AST.TemplateLiteral(h, spans))\n  } else {\n    return make(new AST.TemplateLiteral(\"\", [new AST.TemplateLiteralSpan(new AST.Literal(h), \"\")]))\n  }\n}\n\ntype TemplateLiteralParserParameters = Schema.Any | AST.LiteralValue\n\ntype GetTemplateLiteralParserType<Params> = Params extends [infer Head, ...infer Tail] ? readonly [\n    Head extends Schema<infer A, infer _I, infer _R> ? A : Head,\n    ...GetTemplateLiteralParserType<Tail>\n  ]\n  : []\n\ntype AppendEncoded<\n  Template extends string,\n  Next\n> = Next extends AST.LiteralValue ? `${Template}${Next}`\n  : Next extends Schema<infer _A, infer I extends AST.LiteralValue, infer _R> ? `${Template}${I}`\n  : never\n\ntype GetTemplateLiteralParserEncoded<Params> = Params extends [...infer Init, infer Last] ?\n  AppendEncoded<GetTemplateLiteralParserEncoded<Init>, Last>\n  : ``\n\n/**\n * @category API interface\n * @since 3.10.0\n */\nexport interface TemplateLiteralParser<Params extends array_.NonEmptyReadonlyArray<TemplateLiteralParserParameters>>\n  extends\n    Schema<\n      GetTemplateLiteralParserType<Params>,\n      GetTemplateLiteralParserEncoded<Params>,\n      Schema.Context<Params[number]>\n    >\n{\n  readonly params: Params\n}\n\nfunction getTemplateLiteralParserCoercedElement(encoded: Schema.Any, schema: Schema.Any): Schema.Any | undefined {\n  const ast = encoded.ast\n  switch (ast._tag) {\n    case \"Literal\": {\n      const literal = ast.literal\n      if (!Predicate.isString(literal)) {\n        const s = String(literal)\n        return transform(Literal(s), schema, {\n          strict: true,\n          decode: () => literal,\n          encode: () => s\n        })\n      }\n      break\n    }\n    case \"NumberKeyword\":\n      return compose(NumberFromString, schema)\n    case \"Union\": {\n      const members: Array<Schema.Any> = []\n      let hasCoercions = false\n      for (const member of ast.types) {\n        const schema = make(member)\n        const encoded = encodedSchema(schema)\n        const coerced = getTemplateLiteralParserCoercedElement(encoded, schema)\n        if (coerced) {\n          hasCoercions = true\n        }\n        members.push(coerced ?? schema)\n      }\n      return hasCoercions ? compose(Union(...members), schema) : schema\n    }\n  }\n}\n\n/**\n * @category template literal\n * @since 3.10.0\n */\nexport const TemplateLiteralParser = <Params extends array_.NonEmptyReadonlyArray<TemplateLiteralParserParameters>>(\n  ...params: Params\n): TemplateLiteralParser<Params> => {\n  const encodedSchemas: Array<Schema.Any> = []\n  const elements: Array<Schema.Any> = []\n  const schemas: Array<Schema.Any> = []\n  let coerced = false\n  for (let i = 0; i < params.length; i++) {\n    const param = params[i]\n    const schema = isSchema(param) ? param : Literal(param)\n    schemas.push(schema)\n    const encoded = encodedSchema(schema)\n    encodedSchemas.push(encoded)\n    const element = getTemplateLiteralParserCoercedElement(encoded, schema)\n    if (element) {\n      elements.push(element)\n      coerced = true\n    } else {\n      elements.push(schema)\n    }\n  }\n  const from = TemplateLiteral(...encodedSchemas as any)\n  const re = AST.getTemplateLiteralCapturingRegExp(from.ast as AST.TemplateLiteral)\n  let to = Tuple(...elements)\n  if (coerced) {\n    to = to.annotations({ [AST.AutoTitleAnnotationId]: format(Tuple(...schemas)) })\n  }\n  return class TemplateLiteralParserClass extends transformOrFail(from, to, {\n    strict: false,\n    decode: (i, _, ast) => {\n      const match = re.exec(i)\n      return match\n        ? ParseResult.succeed(match.slice(1, params.length + 1))\n        : ParseResult.fail(new ParseResult.Type(ast, i, `${re.source}: no match for ${JSON.stringify(i)}`))\n    },\n    encode: (tuple) => ParseResult.succeed(tuple.join(\"\"))\n  }) {\n    static params = params.slice()\n  } as any\n}\n\nconst declareConstructor = <\n  const TypeParameters extends ReadonlyArray<Schema.Any>,\n  I,\n  A\n>(\n  typeParameters: TypeParameters,\n  options: {\n    readonly decode: (\n      ...typeParameters: {\n        readonly [K in keyof TypeParameters]: Schema<\n          Schema.Type<TypeParameters[K]>,\n          Schema.Encoded<TypeParameters[K]>,\n          never\n        >\n      }\n    ) => (\n      input: unknown,\n      options: ParseOptions,\n      ast: AST.Declaration\n    ) => Effect.Effect<A, ParseResult.ParseIssue, never>\n    readonly encode: (\n      ...typeParameters: {\n        readonly [K in keyof TypeParameters]: Schema<\n          Schema.Type<TypeParameters[K]>,\n          Schema.Encoded<TypeParameters[K]>,\n          never\n        >\n      }\n    ) => (\n      input: unknown,\n      options: ParseOptions,\n      ast: AST.Declaration\n    ) => Effect.Effect<I, ParseResult.ParseIssue, never>\n  },\n  annotations?: Annotations.Schema<A, TypeParameters>\n): SchemaClass<A, I, Schema.Context<TypeParameters[number]>> =>\n  makeDeclareClass(\n    typeParameters,\n    new AST.Declaration(\n      typeParameters.map((tp) => tp.ast),\n      (...typeParameters) => options.decode(...typeParameters.map(make) as any),\n      (...typeParameters) => options.encode(...typeParameters.map(make) as any),\n      toASTAnnotations(annotations)\n    )\n  )\n\nconst declarePrimitive = <A>(\n  is: (input: unknown) => input is A,\n  annotations?: Annotations.Schema<A>\n): SchemaClass<A> => {\n  const decodeUnknown = () => (input: unknown, _: ParseOptions, ast: AST.Declaration) =>\n    is(input) ? ParseResult.succeed(input) : ParseResult.fail(new ParseResult.Type(ast, input))\n  const encodeUnknown = decodeUnknown\n  return makeDeclareClass([], new AST.Declaration([], decodeUnknown, encodeUnknown, toASTAnnotations(annotations)))\n}\n\n/**\n * @category api interface\n * @since 3.13.3\n */\nexport interface declare<\n  A,\n  I = A,\n  P extends ReadonlyArray<Schema.All> = readonly [],\n  R = Schema.Context<P[number]>\n> extends AnnotableClass<declare<A, I, P, R>, A, I, R> {\n  readonly typeParameters: Readonly<P>\n}\n\n/**\n * @category api interface\n * @since 3.13.3\n */\nexport interface AnnotableDeclare<\n  Self extends declare<A, I, P, R>,\n  A,\n  I = A,\n  P extends ReadonlyArray<Schema.All> = readonly [],\n  R = Schema.Context<P[number]>\n> extends declare<A, I, P, R> {\n  annotations(annotations: Annotations.Schema<A>): Self\n}\n\nfunction makeDeclareClass<P extends ReadonlyArray<Schema.All>, A, I, R>(\n  typeParameters: P,\n  ast: AST.AST\n): declare<A, I, P, R> {\n  return class DeclareClass extends make<A, I, R>(ast) {\n    static override annotations(annotations: Annotations.Schema<A>): declare<A, I, P, R> {\n      return makeDeclareClass(this.typeParameters, mergeSchemaAnnotations(this.ast, annotations))\n    }\n    static typeParameters = [...typeParameters] as any as P\n  }\n}\n\n/**\n * The constraint `R extends Schema.Context<P[number]>` enforces dependencies solely from `typeParameters`.\n * This ensures that when you call `Schema.to` or `Schema.from`, you receive a schema with a `never` context.\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const declare: {\n  <A>(\n    is: (input: unknown) => input is A,\n    annotations?: Annotations.Schema<A>\n  ): declare<A>\n  <A, I, const P extends ReadonlyArray<Schema.All>>(\n    typeParameters: P,\n    options: {\n      readonly decode: (\n        ...typeParameters: { readonly [K in keyof P]: Schema<Schema.Type<P[K]>, Schema.Encoded<P[K]>, never> }\n      ) => (\n        input: unknown,\n        options: ParseOptions,\n        ast: AST.Declaration\n      ) => Effect.Effect<A, ParseResult.ParseIssue, never>\n      readonly encode: (\n        ...typeParameters: { readonly [K in keyof P]: Schema<Schema.Type<P[K]>, Schema.Encoded<P[K]>, never> }\n      ) => (\n        input: unknown,\n        options: ParseOptions,\n        ast: AST.Declaration\n      ) => Effect.Effect<I, ParseResult.ParseIssue, never>\n    },\n    annotations?: Annotations.Schema<A, { readonly [K in keyof P]: Schema.Type<P[K]> }>\n  ): declare<A, I, P>\n} = function() {\n  if (Array.isArray(arguments[0])) {\n    const typeParameters = arguments[0]\n    const options = arguments[1]\n    const annotations = arguments[2]\n    return declareConstructor(typeParameters, options, annotations)\n  }\n  const is = arguments[0]\n  const annotations = arguments[1]\n  return declarePrimitive(is, annotations)\n} as any\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const BrandSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/Brand\")\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const fromBrand = <C extends Brand<string | symbol>, A extends Brand.Unbranded<C>>(\n  constructor: Brand.Constructor<C>,\n  annotations?: Annotations.Filter<C, A>\n) =>\n<I, R>(self: Schema<A, I, R>): BrandSchema<A & C, I, R> => {\n  const out = makeBrandClass(\n    self,\n    new AST.Refinement(\n      self.ast,\n      function predicate(a: A, _: ParseOptions, ast: AST.AST): option_.Option<ParseResult.ParseIssue> {\n        const either = constructor.either(a)\n        return either_.isLeft(either) ?\n          option_.some(new ParseResult.Type(ast, a, either.left.map((v) => v.message).join(\", \"))) :\n          option_.none()\n      },\n      toASTAnnotations({\n        schemaId: BrandSchemaId,\n        [BrandSchemaId]: { constructor },\n        ...annotations\n      })\n    )\n  )\n  return out as any\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const InstanceOfSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/InstanceOf\")\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface instanceOf<A> extends AnnotableDeclare<instanceOf<A>, A> {}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const instanceOf = <A extends abstract new(...args: any) => any>(\n  constructor: A,\n  annotations?: Annotations.Schema<InstanceType<A>>\n): instanceOf<InstanceType<A>> =>\n  declare(\n    (u): u is InstanceType<A> => u instanceof constructor,\n    {\n      title: constructor.name,\n      description: `an instance of ${constructor.name}`,\n      pretty: (): pretty_.Pretty<InstanceType<A>> => String,\n      schemaId: InstanceOfSchemaId,\n      [InstanceOfSchemaId]: { constructor },\n      ...annotations\n    }\n  )\n\n/**\n * @category primitives\n * @since 3.10.0\n */\nexport class Undefined extends make<undefined>(AST.undefinedKeyword) {}\n\n/**\n * @category primitives\n * @since 3.10.0\n */\nexport class Void extends make<void>(AST.voidKeyword) {}\n\n/**\n * @category primitives\n * @since 3.10.0\n */\nexport class Null extends make<null>(AST.null) {}\n\n/**\n * @category primitives\n * @since 3.10.0\n */\nexport class Never extends make<never>(AST.neverKeyword) {}\n\n/**\n * @category primitives\n * @since 3.10.0\n */\nexport class Unknown extends make<unknown>(AST.unknownKeyword) {}\n\n/**\n * @category primitives\n * @since 3.10.0\n */\nexport class Any extends make<any>(AST.anyKeyword) {}\n\n/**\n * @category primitives\n * @since 3.10.0\n */\nexport class BigIntFromSelf extends make<bigint>(AST.bigIntKeyword) {}\n\n/**\n * @category primitives\n * @since 3.10.0\n */\nexport class SymbolFromSelf extends make<symbol>(AST.symbolKeyword) {}\n\n/** @ignore */\nclass String$ extends make<string>(AST.stringKeyword) {}\n\n/** @ignore */\nclass Number$ extends make<number>(AST.numberKeyword) {}\n\n/** @ignore */\nclass Boolean$ extends make<boolean>(AST.booleanKeyword) {}\n\n/** @ignore */\nclass Object$ extends make<object>(AST.objectKeyword) {}\n\nexport {\n  /**\n   * @category primitives\n   * @since 3.10.0\n   */\n  Boolean$ as Boolean,\n  /**\n   * @category primitives\n   * @since 3.10.0\n   */\n  Number$ as Number,\n  /**\n   * @category primitives\n   * @since 3.10.0\n   */\n  Object$ as Object,\n  /**\n   * @category primitives\n   * @since 3.10.0\n   */\n  String$ as String\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Union<Members extends ReadonlyArray<Schema.All>> extends\n  AnnotableClass<\n    Union<Members>,\n    Schema.Type<Members[number]>,\n    Schema.Encoded<Members[number]>,\n    Schema.Context<Members[number]>\n  >\n{\n  readonly members: Readonly<Members>\n}\n\nconst getDefaultUnionAST = <Members extends AST.Members<Schema.All>>(members: Members): AST.AST =>\n  AST.Union.make(members.map((m) => m.ast))\n\nfunction makeUnionClass<Members extends AST.Members<Schema.All>>(\n  members: Members,\n  ast: AST.AST = getDefaultUnionAST(members)\n): Union<Members> {\n  return class UnionClass extends make<\n    Schema.Type<Members[number]>,\n    Schema.Encoded<Members[number]>,\n    Schema.Context<Members[number]>\n  >(ast) {\n    static override annotations(annotations: Annotations.Schema<Schema.Type<Members[number]>>): Union<Members> {\n      return makeUnionClass(this.members, mergeSchemaAnnotations(this.ast, annotations))\n    }\n\n    static members = [...members]\n  }\n}\n\n/**\n * @category combinators\n * @since 3.10.0\n */\nexport function Union<Members extends AST.Members<Schema.All>>(...members: Members): Union<Members>\nexport function Union<Member extends Schema.All>(member: Member): Member\nexport function Union(): typeof Never\nexport function Union<Members extends ReadonlyArray<Schema.All>>(\n  ...members: Members\n): Schema<Schema.Type<Members[number]>, Schema.Encoded<Members[number]>, Schema.Context<Members[number]>>\nexport function Union<Members extends ReadonlyArray<Schema.All>>(\n  ...members: Members\n) {\n  return AST.isMembers(members)\n    ? makeUnionClass(members)\n    : array_.isNonEmptyReadonlyArray(members)\n    ? members[0]\n    : Never\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface NullOr<S extends Schema.All> extends Union<[S, typeof Null]> {\n  annotations(annotations: Annotations.Schema<Schema.Type<S> | null>): NullOr<S>\n}\n\n/**\n * @category combinators\n * @since 3.10.0\n */\nexport const NullOr = <S extends Schema.All>(self: S): NullOr<S> => Union(self, Null)\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface UndefinedOr<S extends Schema.All> extends Union<[S, typeof Undefined]> {\n  annotations(annotations: Annotations.Schema<Schema.Type<S> | undefined>): UndefinedOr<S>\n}\n\n/**\n * @category combinators\n * @since 3.10.0\n */\nexport const UndefinedOr = <S extends Schema.All>(self: S): UndefinedOr<S> => Union(self, Undefined)\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface NullishOr<S extends Schema.All> extends Union<[S, typeof Null, typeof Undefined]> {\n  annotations(annotations: Annotations.Schema<Schema.Type<S> | null | undefined>): NullishOr<S>\n}\n\n/**\n * @category combinators\n * @since 3.10.0\n */\nexport const NullishOr = <S extends Schema.All>(self: S): NullishOr<S> => Union(self, Null, Undefined)\n\n/**\n * @category combinators\n * @since 3.10.0\n */\nexport const keyof = <A, I, R>(self: Schema<A, I, R>): SchemaClass<keyof A> => make<keyof A>(AST.keyof(self.ast))\n\n/**\n * @since 3.10.0\n */\nexport declare namespace Element {\n  /**\n   * @since 3.10.0\n   */\n  export interface Annotations<A> extends Annotations.Doc<A> {\n    readonly missingMessage?: AST.MissingMessageAnnotation\n  }\n\n  /**\n   * @since 3.10.0\n   */\n  export type Token = \"\" | \"?\"\n}\n\n/**\n * @category API interface\n * @since 3.10.0\n */\nexport interface Element<S extends Schema.Any, Token extends Element.Token>\n  extends Schema.Variance<Schema.Type<S>, Schema.Encoded<S>, Schema.Context<S>>\n{\n  readonly _Token: Token\n  readonly ast: AST.OptionalType\n  readonly from: S\n  annotations(annotations: Element.Annotations<Schema.Type<S>>): Element<S, Token>\n}\n\n/**\n * @since 3.10.0\n */\nexport const element = <S extends Schema.Any>(self: S): Element<S, \"\"> =>\n  new ElementImpl(new AST.OptionalType(self.ast, false), self)\n\n/**\n * @since 3.10.0\n */\nexport const optionalElement = <S extends Schema.Any>(self: S): Element<S, \"?\"> =>\n  new ElementImpl(new AST.OptionalType(self.ast, true), self)\n\nclass ElementImpl<S extends Schema.Any, Token extends Element.Token> implements Element<S, Token> {\n  readonly [TypeId]!: Schema.Variance<Schema.Type<S>, Schema.Encoded<S>, Schema.Context<S>>[TypeId]\n  readonly _Token!: Token\n  constructor(\n    readonly ast: AST.OptionalType,\n    readonly from: S\n  ) {}\n  annotations(\n    annotations: Annotations.Schema<Schema.Type<S>>\n  ): ElementImpl<S, Token> {\n    return new ElementImpl(\n      new AST.OptionalType(\n        this.ast.type,\n        this.ast.isOptional,\n        { ...this.ast.annotations, ...toASTAnnotations(annotations) }\n      ),\n      this.from\n    )\n  }\n  toString() {\n    return `${this.ast.type}${this.ast.isOptional ? \"?\" : \"\"}`\n  }\n}\n\n/**\n * @since 3.10.0\n */\nexport declare namespace TupleType {\n  type ElementsType<\n    Elements,\n    Out extends ReadonlyArray<any> = readonly []\n  > = Elements extends readonly [infer Head, ...infer Tail] ?\n    Head extends Element<infer T, \"?\"> ? ElementsType<Tail, readonly [...Out, Schema.Type<T>?]>\n    : ElementsType<Tail, readonly [...Out, Schema.Type<Head>]>\n    : Out\n\n  type ElementsEncoded<\n    Elements,\n    Out extends ReadonlyArray<any> = readonly []\n  > = Elements extends readonly [infer Head, ...infer Tail] ?\n    Head extends Element<infer T, \"?\"> ? ElementsEncoded<Tail, readonly [...Out, Schema.Encoded<T>?]>\n    : ElementsEncoded<Tail, readonly [...Out, Schema.Encoded<Head>]>\n    : Out\n\n  /**\n   * @since 3.10.0\n   */\n  export type Elements = ReadonlyArray<Schema.Any | Element<Schema.Any, Element.Token>>\n\n  /**\n   * @since 3.10.0\n   */\n  export type Rest = ReadonlyArray<Schema.Any | Element<Schema.Any, \"\">>\n\n  /**\n   * @since 3.10.0\n   */\n  export type Type<Elements extends TupleType.Elements, Rest extends TupleType.Rest> = Rest extends\n    [infer Head, ...infer Tail] ? Readonly<[\n      ...ElementsType<Elements>,\n      ...ReadonlyArray<Schema.Type<Head>>,\n      ...{ readonly [K in keyof Tail]: Schema.Type<Tail[K]> }\n    ]> :\n    ElementsType<Elements>\n\n  /**\n   * @since 3.10.0\n   */\n  export type Encoded<Elements extends TupleType.Elements, Rest extends TupleType.Rest> = Rest extends\n    [infer Head, ...infer Tail] ? Readonly<[\n      ...ElementsEncoded<Elements>,\n      ...ReadonlyArray<Schema.Encoded<Head>>,\n      ...{ readonly [K in keyof Tail]: Schema.Encoded<Tail[K]> }\n    ]> :\n    ElementsEncoded<Elements>\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface TupleType<Elements extends TupleType.Elements, Rest extends TupleType.Rest> extends\n  AnnotableClass<\n    TupleType<Elements, Rest>,\n    TupleType.Type<Elements, Rest>,\n    TupleType.Encoded<Elements, Rest>,\n    Schema.Context<Elements[number]> | Schema.Context<Rest[number]>\n  >\n{\n  readonly elements: Readonly<Elements>\n  readonly rest: Readonly<Rest>\n}\n\nconst getDefaultTupleTypeAST = <Elements extends TupleType.Elements, Rest extends TupleType.Rest>(\n  elements: Elements,\n  rest: Rest\n) =>\n  new AST.TupleType(\n    elements.map((el) => isSchema(el) ? new AST.OptionalType(el.ast, false) : el.ast),\n    rest.map((el) => isSchema(el) ? new AST.Type(el.ast) : el.ast),\n    true\n  )\n\nfunction makeTupleTypeClass<Elements extends TupleType.Elements, Rest extends TupleType.Rest>(\n  elements: Elements,\n  rest: Rest,\n  ast: AST.AST = getDefaultTupleTypeAST(elements, rest)\n) {\n  return class TupleTypeClass extends make<\n    TupleType.Type<Elements, Rest>,\n    TupleType.Encoded<Elements, Rest>,\n    Schema.Context<Elements[number]> | Schema.Context<Rest[number]>\n  >(ast) {\n    static override annotations(\n      annotations: Annotations.Schema<TupleType.Type<Elements, Rest>>\n    ): TupleType<Elements, Rest> {\n      return makeTupleTypeClass(this.elements, this.rest, mergeSchemaAnnotations(this.ast, annotations))\n    }\n\n    static elements = [...elements] as any as Elements\n\n    static rest = [...rest] as any as Rest\n  }\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Tuple<Elements extends TupleType.Elements> extends TupleType<Elements, []> {\n  annotations(annotations: Annotations.Schema<TupleType.Type<Elements, []>>): Tuple<Elements>\n}\n\n/**\n * @category api interface\n * @since 3.13.3\n */\nexport interface Tuple2<Fst extends Schema.Any, Snd extends Schema.Any> extends\n  AnnotableClass<\n    Tuple2<Fst, Snd>,\n    readonly [Schema.Type<Fst>, Schema.Type<Snd>],\n    readonly [Schema.Encoded<Fst>, Schema.Encoded<Snd>],\n    Schema.Context<Fst> | Schema.Context<Snd>\n  >\n{\n  readonly elements: readonly [Fst, Snd]\n  readonly rest: readonly []\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport function Tuple<\n  const Elements extends TupleType.Elements,\n  Rest extends array_.NonEmptyReadonlyArray<TupleType.Rest[number]>\n>(elements: Elements, ...rest: Rest): TupleType<Elements, Rest>\nexport function Tuple<Fst extends Schema.Any, Snd extends Schema.Any>(fst: Fst, snd: Snd): Tuple2<Fst, Snd>\nexport function Tuple<Elements extends TupleType.Elements>(...elements: Elements): Tuple<Elements>\nexport function Tuple(...args: ReadonlyArray<any>): any {\n  return Array.isArray(args[0])\n    ? makeTupleTypeClass(args[0], args.slice(1))\n    : makeTupleTypeClass(args, [])\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Array$<Value extends Schema.Any> extends TupleType<[], [Value]> {\n  readonly value: Value\n  annotations(annotations: Annotations.Schema<TupleType.Type<[], [Value]>>): Array$<Value>\n}\n\nfunction makeArrayClass<Value extends Schema.Any>(\n  value: Value,\n  ast?: AST.AST\n): Array$<Value> {\n  return class ArrayClass extends makeTupleTypeClass<[], [Value]>([], [value], ast) {\n    static override annotations(annotations: Annotations.Schema<TupleType.Type<[], [Value]>>) {\n      return makeArrayClass(this.value, mergeSchemaAnnotations(this.ast, annotations))\n    }\n\n    static value = value\n  }\n}\n\nconst Array$ = <Value extends Schema.Any>(value: Value): Array$<Value> => makeArrayClass(value)\n\nexport {\n  /**\n   * @category constructors\n   * @since 3.10.0\n   */\n  Array$ as Array\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface NonEmptyArray<Value extends Schema.Any> extends\n  AnnotableClass<\n    NonEmptyArray<Value>,\n    array_.NonEmptyReadonlyArray<Schema.Type<Value>>,\n    array_.NonEmptyReadonlyArray<Schema.Encoded<Value>>,\n    Schema.Context<Value>\n  >\n{\n  readonly elements: readonly [Value]\n  readonly rest: readonly [Value]\n  readonly value: Value\n}\n\nfunction makeNonEmptyArrayClass<Value extends Schema.Any>(\n  value: Value,\n  ast?: AST.AST\n) {\n  return class NonEmptyArrayClass extends makeTupleTypeClass<[Value], [Value]>([value], [value], ast) {\n    static override annotations(annotations: Annotations.Schema<TupleType.Type<[Value], [Value]>>) {\n      return makeNonEmptyArrayClass(this.value, mergeSchemaAnnotations(this.ast, annotations))\n    }\n\n    static value = value\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const NonEmptyArray = <Value extends Schema.Any>(value: Value): NonEmptyArray<Value> =>\n  makeNonEmptyArrayClass(value) as any\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface ArrayEnsure<Value extends Schema.Any>\n  extends transform<Union<[Value, Array$<Value>]>, Array$<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport function ArrayEnsure<Value extends Schema.Any>(value: Value): ArrayEnsure<Value> {\n  return transform(Union(value, Array$(value)), Array$(typeSchema(asSchema(value))), {\n    strict: true,\n    decode: (i) => array_.ensure(i),\n    encode: (a) => a.length === 1 ? a[0] : a\n  })\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface NonEmptyArrayEnsure<Value extends Schema.Any>\n  extends transform<Union<[Value, NonEmptyArray<Value>]>, NonEmptyArray<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport function NonEmptyArrayEnsure<Value extends Schema.Any>(value: Value): NonEmptyArrayEnsure<Value> {\n  return transform(Union(value, NonEmptyArray(value)), NonEmptyArray(typeSchema(asSchema(value))), {\n    strict: true,\n    decode: (i) => array_.isNonEmptyReadonlyArray(i) ? i : array_.of(i),\n    encode: (a) => a.length === 1 ? a[0] : a\n  })\n}\n\n/**\n * @since 3.10.0\n */\nexport declare namespace PropertySignature {\n  /**\n   * @since 3.10.0\n   */\n  export type Token = \"?:\" | \":\"\n\n  /**\n   * @since 3.10.0\n   */\n  export type Any<Key extends PropertyKey = PropertyKey> = PropertySignature<\n    Token,\n    any,\n    Key,\n    Token,\n    any,\n    boolean,\n    unknown\n  >\n\n  /**\n   * @since 3.10.0\n   */\n  export type All<Key extends PropertyKey = PropertyKey> =\n    | Any<Key>\n    | PropertySignature<Token, never, Key, Token, any, boolean, unknown>\n    | PropertySignature<Token, any, Key, Token, never, boolean, unknown>\n    | PropertySignature<Token, never, Key, Token, never, boolean, unknown>\n\n  /**\n   * @since 3.10.0\n   */\n  export type AST =\n    | PropertySignatureDeclaration\n    | PropertySignatureTransformation\n\n  /**\n   * @since 3.10.0\n   */\n  export interface Annotations<A> extends Annotations.Doc<A> {\n    readonly missingMessage?: AST.MissingMessageAnnotation\n  }\n}\n\nconst formatPropertySignatureToken = (isOptional: boolean): string => isOptional ? \"\\\"?:\\\"\" : \"\\\":\\\"\"\n\n/**\n * @category PropertySignature\n * @since 3.10.0\n */\nexport class PropertySignatureDeclaration extends AST.OptionalType {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"PropertySignatureDeclaration\"\n  constructor(\n    type: AST.AST,\n    isOptional: boolean,\n    readonly isReadonly: boolean,\n    annotations: AST.Annotations,\n    readonly defaultValue: (() => unknown) | undefined\n  ) {\n    super(type, isOptional, annotations)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    const token = formatPropertySignatureToken(this.isOptional)\n    const type = String(this.type)\n    return `PropertySignature<${token}, ${type}, never, ${token}, ${type}>`\n  }\n}\n\n/**\n * @category PropertySignature\n * @since 3.10.0\n */\nexport class FromPropertySignature extends AST.OptionalType {\n  constructor(\n    type: AST.AST,\n    isOptional: boolean,\n    readonly isReadonly: boolean,\n    annotations: AST.Annotations,\n    readonly fromKey?: PropertyKey | undefined\n  ) {\n    super(type, isOptional, annotations)\n  }\n}\n\n/**\n * @category PropertySignature\n * @since 3.10.0\n */\nexport class ToPropertySignature extends AST.OptionalType {\n  constructor(\n    type: AST.AST,\n    isOptional: boolean,\n    readonly isReadonly: boolean,\n    annotations: AST.Annotations,\n    readonly defaultValue: (() => unknown) | undefined\n  ) {\n    super(type, isOptional, annotations)\n  }\n}\n\nconst formatPropertyKey = (p: PropertyKey | undefined): string => {\n  if (p === undefined) {\n    return \"never\"\n  }\n  if (Predicate.isString(p)) {\n    return JSON.stringify(p)\n  }\n  return String(p)\n}\n\n/**\n * @category PropertySignature\n * @since 3.10.0\n */\nexport class PropertySignatureTransformation {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"PropertySignatureTransformation\"\n  constructor(\n    readonly from: FromPropertySignature,\n    readonly to: ToPropertySignature,\n    readonly decode: AST.PropertySignatureTransformation[\"decode\"],\n    readonly encode: AST.PropertySignatureTransformation[\"encode\"]\n  ) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return `PropertySignature<${formatPropertySignatureToken(this.to.isOptional)}, ${this.to.type}, ${\n      formatPropertyKey(this.from.fromKey)\n    }, ${formatPropertySignatureToken(this.from.isOptional)}, ${this.from.type}>`\n  }\n}\n\nconst mergeSignatureAnnotations = (\n  ast: PropertySignature.AST,\n  annotations: AST.Annotations\n): PropertySignature.AST => {\n  switch (ast._tag) {\n    case \"PropertySignatureDeclaration\": {\n      return new PropertySignatureDeclaration(\n        ast.type,\n        ast.isOptional,\n        ast.isReadonly,\n        { ...ast.annotations, ...annotations },\n        ast.defaultValue\n      )\n    }\n    case \"PropertySignatureTransformation\": {\n      return new PropertySignatureTransformation(\n        ast.from,\n        new ToPropertySignature(ast.to.type, ast.to.isOptional, ast.to.isReadonly, {\n          ...ast.to.annotations,\n          ...annotations\n        }, ast.to.defaultValue),\n        ast.decode,\n        ast.encode\n      )\n    }\n  }\n}\n\n/**\n * @since 3.10.0\n * @category symbol\n */\nexport const PropertySignatureTypeId: unique symbol = Symbol.for(\"effect/PropertySignature\")\n\n/**\n * @since 3.10.0\n * @category symbol\n */\nexport type PropertySignatureTypeId = typeof PropertySignatureTypeId\n\n/**\n * @since 3.10.0\n * @category guards\n */\nexport const isPropertySignature = (u: unknown): u is PropertySignature.All =>\n  Predicate.hasProperty(u, PropertySignatureTypeId)\n\n/**\n * @category PropertySignature\n * @since 3.10.0\n */\nexport interface PropertySignature<\n  TypeToken extends PropertySignature.Token,\n  Type,\n  Key extends PropertyKey,\n  EncodedToken extends PropertySignature.Token,\n  Encoded,\n  HasDefault extends boolean = false,\n  R = never\n> extends Schema.Variance<Type, Encoded, R>, Pipeable {\n  readonly [PropertySignatureTypeId]: null\n  readonly _TypeToken: TypeToken\n  readonly _EncodedToken: EncodedToken\n  readonly _HasDefault: HasDefault\n  readonly _Key: Key\n  readonly ast: PropertySignature.AST\n\n  annotations(\n    annotations: PropertySignature.Annotations<Type>\n  ): PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, HasDefault, R>\n}\n\nclass PropertySignatureImpl<\n  TypeToken extends PropertySignature.Token,\n  Type,\n  Key extends PropertyKey,\n  EncodedToken extends PropertySignature.Token,\n  Encoded,\n  HasDefault extends boolean = false,\n  R = never\n> implements PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, HasDefault, R> {\n  readonly [TypeId]!: Schema.Variance<Type, Encoded, R>[TypeId]\n  readonly [PropertySignatureTypeId] = null\n  readonly _TypeToken!: TypeToken\n  readonly _Key!: Key\n  readonly _EncodedToken!: EncodedToken\n  readonly _HasDefault!: HasDefault\n\n  constructor(\n    readonly ast: PropertySignature.AST\n  ) {}\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n\n  annotations(\n    annotations: PropertySignature.Annotations<Type>\n  ): PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, HasDefault, R> {\n    return new PropertySignatureImpl(mergeSignatureAnnotations(this.ast, toASTAnnotations(annotations)))\n  }\n\n  toString() {\n    return String(this.ast)\n  }\n}\n\n/**\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const makePropertySignature = <\n  TypeToken extends PropertySignature.Token,\n  Type,\n  Key extends PropertyKey,\n  EncodedToken extends PropertySignature.Token,\n  Encoded,\n  HasDefault extends boolean = false,\n  R = never\n>(ast: PropertySignature.AST) =>\n  new PropertySignatureImpl<TypeToken, Type, Key, EncodedToken, Encoded, HasDefault, R>(ast)\n\nclass PropertySignatureWithFromImpl<\n  From extends Schema.All,\n  TypeToken extends PropertySignature.Token,\n  Type,\n  Key extends PropertyKey,\n  EncodedToken extends PropertySignature.Token,\n  Encoded,\n  HasDefault extends boolean = false,\n  R = never\n> extends PropertySignatureImpl<TypeToken, Type, Key, EncodedToken, Encoded, HasDefault, R> {\n  constructor(ast: PropertySignature.AST, readonly from: From) {\n    super(ast)\n  }\n  annotations(\n    annotations: PropertySignature.Annotations<Type>\n  ): PropertySignatureWithFromImpl<From, TypeToken, Type, Key, EncodedToken, Encoded, HasDefault, R> {\n    return new PropertySignatureWithFromImpl(\n      mergeSignatureAnnotations(this.ast, toASTAnnotations(annotations)),\n      this.from\n    )\n  }\n}\n\n/**\n * @category API interface\n * @since 1.0.0\n */\nexport interface propertySignature<S extends Schema.All>\n  extends PropertySignature<\":\", Schema.Type<S>, never, \":\", Schema.Encoded<S>, false, Schema.Context<S>>\n{\n  readonly from: S\n  annotations(annotations: PropertySignature.Annotations<Schema.Type<S>>): propertySignature<S>\n}\n\n/**\n * Lifts a `Schema` into a `PropertySignature`.\n *\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const propertySignature = <S extends Schema.All>(\n  self: S\n): propertySignature<S> =>\n  new PropertySignatureWithFromImpl(\n    new PropertySignatureDeclaration(self.ast, false, true, {}, undefined),\n    self\n  )\n\n/**\n * Enhances a property signature with a default constructor value.\n *\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const withConstructorDefault: {\n  <Type>(defaultValue: () => Types.NoInfer<Type>): <\n    TypeToken extends PropertySignature.Token,\n    Key extends PropertyKey,\n    EncodedToken extends PropertySignature.Token,\n    Encoded,\n    R\n  >(\n    self: PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, boolean, R>\n  ) => PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, true, R>\n  <\n    TypeToken extends PropertySignature.Token,\n    Type,\n    Key extends PropertyKey,\n    EncodedToken extends PropertySignature.Token,\n    Encoded,\n    R\n  >(\n    self: PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, boolean, R>,\n    defaultValue: () => Types.NoInfer<Type>\n  ): PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, true, R>\n} = dual(2, <\n  TypeToken extends PropertySignature.Token,\n  Type,\n  Key extends PropertyKey,\n  EncodedToken extends PropertySignature.Token,\n  Encoded,\n  R\n>(\n  self: PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, boolean, R>,\n  defaultValue: () => Types.NoInfer<Type>\n): PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, true, R> => {\n  const ast = self.ast\n  switch (ast._tag) {\n    case \"PropertySignatureDeclaration\":\n      return makePropertySignature(\n        new PropertySignatureDeclaration(ast.type, ast.isOptional, ast.isReadonly, ast.annotations, defaultValue)\n      )\n    case \"PropertySignatureTransformation\":\n      return makePropertySignature(\n        new PropertySignatureTransformation(\n          ast.from,\n          new ToPropertySignature(ast.to.type, ast.to.isOptional, ast.to.isReadonly, ast.to.annotations, defaultValue),\n          ast.decode,\n          ast.encode\n        )\n      )\n  }\n})\n\nconst applyDefaultValue = <A>(o: option_.Option<A>, defaultValue: () => A) =>\n  option_.match(o, {\n    onNone: () => option_.some(defaultValue()),\n    onSome: (value) => option_.some(value === undefined ? defaultValue() : value)\n  })\n\nconst pruneUndefined = (ast: AST.AST): AST.AST | undefined =>\n  AST.pruneUndefined(ast, pruneUndefined, (ast) => {\n    const pruned = pruneUndefined(ast.to)\n    if (pruned) {\n      return new AST.Transformation(ast.from, pruned, ast.transformation)\n    }\n  })\n\n/**\n * Enhances a property signature with a default decoding value.\n *\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const withDecodingDefault: {\n  <Type>(defaultValue: () => Types.NoInfer<Exclude<Type, undefined>>): <\n    Key extends PropertyKey,\n    Encoded,\n    R\n  >(\n    self: PropertySignature<\"?:\", Type, Key, \"?:\", Encoded, false, R>\n  ) => PropertySignature<\":\", Exclude<Type, undefined>, Key, \"?:\", Encoded, false, R>\n  <\n    Type,\n    Key extends PropertyKey,\n    Encoded,\n    R\n  >(\n    self: PropertySignature<\"?:\", Type, Key, \"?:\", Encoded, false, R>,\n    defaultValue: () => Types.NoInfer<Exclude<Type, undefined>>\n  ): PropertySignature<\":\", Exclude<Type, undefined>, Key, \"?:\", Encoded, false, R>\n} = dual(2, <\n  Type,\n  Key extends PropertyKey,\n  Encoded,\n  R\n>(\n  self: PropertySignature<\"?:\", Type, Key, \"?:\", Encoded, false, R>,\n  defaultValue: () => Types.NoInfer<Exclude<Type, undefined>>\n): PropertySignature<\":\", Exclude<Type, undefined>, Key, \"?:\", Encoded, false, R> => {\n  const ast = self.ast\n  switch (ast._tag) {\n    case \"PropertySignatureDeclaration\": {\n      const to = AST.typeAST(ast.type)\n      return makePropertySignature(\n        new PropertySignatureTransformation(\n          new FromPropertySignature(ast.type, ast.isOptional, ast.isReadonly, ast.annotations),\n          new ToPropertySignature(pruneUndefined(to) ?? to, false, true, {}, ast.defaultValue),\n          (o) => applyDefaultValue(o, defaultValue),\n          identity\n        )\n      )\n    }\n    case \"PropertySignatureTransformation\": {\n      const to = ast.to.type\n      return makePropertySignature(\n        new PropertySignatureTransformation(\n          ast.from,\n          new ToPropertySignature(\n            pruneUndefined(to) ?? to,\n            false,\n            ast.to.isReadonly,\n            ast.to.annotations,\n            ast.to.defaultValue\n          ),\n          (o) => applyDefaultValue(ast.decode(o), defaultValue),\n          ast.encode\n        )\n      )\n    }\n  }\n})\n\n/**\n * Enhances a property signature with a default decoding value and a default constructor value.\n *\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const withDefaults: {\n  <Type>(defaults: {\n    constructor: () => Types.NoInfer<Exclude<Type, undefined>>\n    decoding: () => Types.NoInfer<Exclude<Type, undefined>>\n  }): <\n    Key extends PropertyKey,\n    Encoded,\n    R\n  >(\n    self: PropertySignature<\"?:\", Type, Key, \"?:\", Encoded, boolean, R>\n  ) => PropertySignature<\":\", Exclude<Type, undefined>, Key, \"?:\", Encoded, true, R>\n  <\n    Type,\n    Key extends PropertyKey,\n    Encoded,\n    R\n  >(\n    self: PropertySignature<\"?:\", Type, Key, \"?:\", Encoded, boolean, R>,\n    defaults: {\n      constructor: () => Types.NoInfer<Exclude<Type, undefined>>\n      decoding: () => Types.NoInfer<Exclude<Type, undefined>>\n    }\n  ): PropertySignature<\":\", Exclude<Type, undefined>, Key, \"?:\", Encoded, true, R>\n} = dual(2, <\n  Type,\n  Key extends PropertyKey,\n  Encoded,\n  R\n>(\n  self: PropertySignature<\"?:\", Type, Key, \"?:\", Encoded, false, R>,\n  defaults: {\n    constructor: () => Types.NoInfer<Exclude<Type, undefined>>\n    decoding: () => Types.NoInfer<Exclude<Type, undefined>>\n  }\n): PropertySignature<\":\", Exclude<Type, undefined>, Key, \"?:\", Encoded, true, R> =>\n  self.pipe(withDecodingDefault(defaults.decoding), withConstructorDefault(defaults.constructor)))\n\n/**\n * Enhances a property signature by specifying a different key for it in the Encoded type.\n *\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const fromKey: {\n  <Key extends PropertyKey>(key: Key): <\n    TypeToken extends PropertySignature.Token,\n    Type,\n    EncodedToken extends PropertySignature.Token,\n    Encoded,\n    HasDefault extends boolean,\n    R\n  >(\n    self: PropertySignature<TypeToken, Type, PropertyKey, EncodedToken, Encoded, HasDefault, R>\n  ) => PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, HasDefault, R>\n  <\n    Type,\n    TypeToken extends PropertySignature.Token,\n    Encoded,\n    EncodedToken extends PropertySignature.Token,\n    HasDefault extends boolean,\n    R,\n    Key extends PropertyKey\n  >(\n    self: PropertySignature<TypeToken, Type, PropertyKey, EncodedToken, Encoded, HasDefault, R>,\n    key: Key\n  ): PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, HasDefault, R>\n} = dual(2, <\n  Type,\n  TypeToken extends PropertySignature.Token,\n  Encoded,\n  EncodedToken extends PropertySignature.Token,\n  HasDefault extends boolean,\n  R,\n  Key extends PropertyKey\n>(\n  self: PropertySignature<TypeToken, Type, PropertyKey, EncodedToken, Encoded, HasDefault, R>,\n  key: Key\n): PropertySignature<TypeToken, Type, Key, EncodedToken, Encoded, HasDefault, R> => {\n  const ast = self.ast\n  switch (ast._tag) {\n    case \"PropertySignatureDeclaration\": {\n      return makePropertySignature(\n        new PropertySignatureTransformation(\n          new FromPropertySignature(\n            ast.type,\n            ast.isOptional,\n            ast.isReadonly,\n            ast.annotations,\n            key\n          ),\n          new ToPropertySignature(AST.typeAST(ast.type), ast.isOptional, ast.isReadonly, {}, ast.defaultValue),\n          identity,\n          identity\n        )\n      )\n    }\n    case \"PropertySignatureTransformation\":\n      return makePropertySignature(\n        new PropertySignatureTransformation(\n          new FromPropertySignature(\n            ast.from.type,\n            ast.from.isOptional,\n            ast.from.isReadonly,\n            ast.from.annotations,\n            key\n          ),\n          ast.to,\n          ast.decode,\n          ast.encode\n        )\n      )\n  }\n})\n\n/**\n * Converts an optional property to a required one through a transformation `Option -> Type`.\n *\n * - `decode`: `none` as argument means the value is missing in the input.\n * - `encode`: `none` as return value means the value will be missing in the output.\n *\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const optionalToRequired = <FA, FI, FR, TA, TI, TR>(\n  from: Schema<FA, FI, FR>,\n  to: Schema<TA, TI, TR>,\n  options: {\n    readonly decode: (o: option_.Option<FA>) => TI\n    readonly encode: (ti: TI) => option_.Option<FA>\n  }\n): PropertySignature<\":\", TA, never, \"?:\", FI, false, FR | TR> =>\n  makePropertySignature(\n    new PropertySignatureTransformation(\n      new FromPropertySignature(from.ast, true, true, {}, undefined),\n      new ToPropertySignature(to.ast, false, true, {}, undefined),\n      (o) => option_.some(options.decode(o)),\n      option_.flatMap(options.encode)\n    )\n  )\n\n/**\n * Converts an optional property to a required one through a transformation `Type -> Option`.\n *\n * - `decode`: `none` as return value means the value will be missing in the output.\n * - `encode`: `none` as argument means the value is missing in the input.\n *\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const requiredToOptional = <FA, FI, FR, TA, TI, TR>(\n  from: Schema<FA, FI, FR>,\n  to: Schema<TA, TI, TR>,\n  options: {\n    readonly decode: (fa: FA) => option_.Option<TI>\n    readonly encode: (o: option_.Option<TI>) => FA\n  }\n): PropertySignature<\"?:\", TA, never, \":\", FI, false, FR | TR> =>\n  makePropertySignature(\n    new PropertySignatureTransformation(\n      new FromPropertySignature(from.ast, false, true, {}, undefined),\n      new ToPropertySignature(to.ast, true, true, {}, undefined),\n      option_.flatMap(options.decode),\n      (o) => option_.some(options.encode(o))\n    )\n  )\n\n/**\n * Converts an optional property to another optional property through a transformation `Option -> Option`.\n *\n * - `decode`:\n *   - `none` as argument means the value is missing in the input.\n *   - `none` as return value means the value will be missing in the output.\n * - `encode`:\n *   - `none` as argument means the value is missing in the input.\n *   - `none` as return value means the value will be missing in the output.\n *\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const optionalToOptional = <FA, FI, FR, TA, TI, TR>(\n  from: Schema<FA, FI, FR>,\n  to: Schema<TA, TI, TR>,\n  options: {\n    readonly decode: (o: option_.Option<FA>) => option_.Option<TI>\n    readonly encode: (o: option_.Option<TI>) => option_.Option<FA>\n  }\n): PropertySignature<\"?:\", TA, never, \"?:\", FI, false, FR | TR> =>\n  makePropertySignature(\n    new PropertySignatureTransformation(\n      new FromPropertySignature(from.ast, true, true, {}, undefined),\n      new ToPropertySignature(to.ast, true, true, {}, undefined),\n      options.decode,\n      options.encode\n    )\n  )\n\n/**\n * @since 3.10.0\n */\nexport type OptionalOptions<A> = {\n  readonly default?: never\n  readonly as?: never\n  readonly exact?: true\n  readonly nullable?: true\n} | {\n  readonly default: LazyArg<A>\n  readonly as?: never\n  readonly exact?: true\n  readonly nullable?: true\n} | {\n  readonly as: \"Option\"\n  readonly default?: never\n  readonly exact?: never\n  readonly nullable?: never\n  readonly onNoneEncoding?: LazyArg<option_.Option<undefined>>\n} | {\n  readonly as: \"Option\"\n  readonly default?: never\n  readonly exact?: never\n  readonly nullable: true\n  readonly onNoneEncoding?: LazyArg<option_.Option<null | undefined>>\n} | {\n  readonly as: \"Option\"\n  readonly default?: never\n  readonly exact: true\n  readonly nullable?: never\n  readonly onNoneEncoding?: never\n} | {\n  readonly as: \"Option\"\n  readonly default?: never\n  readonly exact: true\n  readonly nullable: true\n  readonly onNoneEncoding?: LazyArg<option_.Option<null>>\n} | undefined\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface optional<S extends Schema.All> extends\n  PropertySignature<\n    \"?:\",\n    Schema.Type<S> | undefined,\n    never,\n    \"?:\",\n    Schema.Encoded<S> | undefined,\n    false,\n    Schema.Context<S>\n  >\n{\n  readonly from: S\n  annotations(annotations: PropertySignature.Annotations<Schema.Type<S> | undefined>): optional<S>\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface optionalWith<S extends Schema.All, Options> extends\n  PropertySignature<\n    Types.Has<Options, \"as\" | \"default\"> extends true ? \":\" : \"?:\",\n    | (Types.Has<Options, \"as\"> extends true ? option_.Option<Schema.Type<S>> : Schema.Type<S>)\n    | (Types.Has<Options, \"as\" | \"default\" | \"exact\"> extends true ? never : undefined),\n    never,\n    \"?:\",\n    | Schema.Encoded<S>\n    | (Types.Has<Options, \"nullable\"> extends true ? null : never)\n    | (Types.Has<Options, \"exact\"> extends true ? never : undefined),\n    Types.Has<Options, \"default\">,\n    Schema.Context<S>\n  >\n{\n  readonly from: S\n  annotations(\n    annotations: PropertySignature.Annotations<\n      | (Types.Has<Options, \"as\"> extends true ? option_.Option<Schema.Type<S>> : Schema.Type<S>)\n      | (Types.Has<Options, \"as\" | \"default\" | \"exact\"> extends true ? never : undefined)\n    >\n  ): optionalWith<S, Options>\n}\n\nconst optionalPropertySignatureAST = <A, I, R>(\n  self: Schema<A, I, R>,\n  options?: {\n    readonly exact?: true\n    readonly default?: () => A\n    readonly nullable?: true\n    readonly as?: \"Option\"\n    readonly onNoneEncoding?: () => option_.Option<never>\n  }\n): PropertySignature.AST => {\n  const isExact = options?.exact\n  const defaultValue = options?.default\n  const isNullable = options?.nullable\n  const asOption = options?.as == \"Option\"\n  const asOptionEncode = options?.onNoneEncoding ? option_.orElse(options.onNoneEncoding) : identity\n\n  if (isExact) {\n    if (defaultValue) {\n      if (isNullable) {\n        return withConstructorDefault(\n          optionalToRequired(\n            NullOr(self),\n            typeSchema(self),\n            {\n              decode: option_.match({ onNone: defaultValue, onSome: (a) => a === null ? defaultValue() : a }),\n              encode: option_.some\n            }\n          ),\n          defaultValue\n        ).ast\n      } else {\n        return withConstructorDefault(\n          optionalToRequired(\n            self,\n            typeSchema(self),\n            { decode: option_.match({ onNone: defaultValue, onSome: identity }), encode: option_.some }\n          ),\n          defaultValue\n        ).ast\n      }\n    } else if (asOption) {\n      const to = OptionFromSelf_(typeSchema(self))\n      if (isNullable) {\n        return optionalToRequired(\n          NullOr(self),\n          to,\n          {\n            decode: option_.filter(Predicate.isNotNull<A | null>),\n            encode: asOptionEncode\n          }\n        ).ast\n      } else {\n        return optionalToRequired(\n          self,\n          to,\n          { decode: identity, encode: identity }\n        ).ast\n      }\n    } else {\n      if (isNullable) {\n        return optionalToOptional(\n          NullOr(self),\n          typeSchema(self),\n          { decode: option_.filter(Predicate.isNotNull<A | null>), encode: identity }\n        ).ast\n      } else {\n        return new PropertySignatureDeclaration(self.ast, true, true, {}, undefined)\n      }\n    }\n  } else {\n    if (defaultValue) {\n      if (isNullable) {\n        return withConstructorDefault(\n          optionalToRequired(\n            NullishOr(self),\n            typeSchema(self),\n            {\n              decode: option_.match({ onNone: defaultValue, onSome: (a) => (a == null ? defaultValue() : a) }),\n              encode: option_.some\n            }\n          ),\n          defaultValue\n        ).ast\n      } else {\n        return withConstructorDefault(\n          optionalToRequired(\n            UndefinedOr(self),\n            typeSchema(self),\n            {\n              decode: option_.match({ onNone: defaultValue, onSome: (a) => (a === undefined ? defaultValue() : a) }),\n              encode: option_.some\n            }\n          ),\n          defaultValue\n        ).ast\n      }\n    } else if (asOption) {\n      const to = OptionFromSelf_(typeSchema(self))\n      if (isNullable) {\n        return optionalToRequired(\n          NullishOr(self),\n          to,\n          {\n            decode: option_.filter<A | null | undefined, A>((a): a is A => a != null),\n            encode: asOptionEncode\n          }\n        ).ast\n      } else {\n        return optionalToRequired(\n          UndefinedOr(self),\n          to,\n          {\n            decode: option_.filter(Predicate.isNotUndefined<A | undefined>),\n            encode: asOptionEncode\n          }\n        ).ast\n      }\n    } else {\n      if (isNullable) {\n        return optionalToOptional(\n          NullishOr(self),\n          UndefinedOr(typeSchema(self)),\n          { decode: option_.filter(Predicate.isNotNull<A | null | undefined>), encode: identity }\n        ).ast\n      } else {\n        return new PropertySignatureDeclaration(UndefinedOr(self).ast, true, true, {}, undefined)\n      }\n    }\n  }\n}\n\n/**\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const optional = <S extends Schema.All>(self: S): optional<S> => {\n  const ast = self.ast === AST.undefinedKeyword || self.ast === AST.neverKeyword\n    ? AST.undefinedKeyword\n    : UndefinedOr(self).ast\n  return new PropertySignatureWithFromImpl(new PropertySignatureDeclaration(ast, true, true, {}, undefined), self)\n}\n\n/**\n * @category PropertySignature\n * @since 3.10.0\n */\nexport const optionalWith: {\n  <S extends Schema.All, Options extends OptionalOptions<Schema.Type<S>>>(\n    options: Options\n  ): (self: S) => optionalWith<S, Options>\n  <S extends Schema.All, Options extends OptionalOptions<Schema.Type<S>>>(\n    self: S,\n    options: Options\n  ): optionalWith<S, Options>\n} = dual((args) => isSchema(args[0]), (self, options) => {\n  return new PropertySignatureWithFromImpl(optionalPropertySignatureAST(self, options), self)\n})\n\n/**\n * @since 3.10.0\n */\nexport declare namespace Struct {\n  /**\n   * Useful for creating a type that can be used to add custom constraints to the fields of a struct.\n   *\n   * ```ts\n   * import { Schema } from \"effect\"\n   *\n   * const f = <Fields extends Record<\"a\" | \"b\", Schema.Struct.Field>>(\n   *   schema: Schema.Struct<Fields>\n   * ) => {\n   *   return schema.omit(\"a\")\n   * }\n   *\n   * //      ┌─── Schema.Struct<{ b: typeof Schema.Number; }>\n   * //      ▼\n   * const result = f(Schema.Struct({ a: Schema.String, b: Schema.Number }))\n   * ```\n   * @since 3.13.11\n   */\n  export type Field =\n    | Schema.All\n    | PropertySignature.All\n\n  /**\n   * @since 3.10.0\n   */\n  export type Fields = { readonly [x: PropertyKey]: Field }\n\n  type OptionalEncodedPropertySignature =\n    | PropertySignature<PropertySignature.Token, any, PropertyKey, \"?:\", any, boolean, unknown>\n    | PropertySignature<PropertySignature.Token, any, PropertyKey, \"?:\", never, boolean, unknown>\n    | PropertySignature<PropertySignature.Token, never, PropertyKey, \"?:\", any, boolean, unknown>\n    | PropertySignature<PropertySignature.Token, never, PropertyKey, \"?:\", never, boolean, unknown>\n\n  type EncodedOptionalKeys<Fields extends Struct.Fields> = {\n    [K in keyof Fields]: Fields[K] extends OptionalEncodedPropertySignature ? K\n      : never\n  }[keyof Fields]\n\n  type OptionalTypePropertySignature =\n    | PropertySignature<\"?:\", any, PropertyKey, PropertySignature.Token, any, boolean, unknown>\n    | PropertySignature<\"?:\", any, PropertyKey, PropertySignature.Token, never, boolean, unknown>\n    | PropertySignature<\"?:\", never, PropertyKey, PropertySignature.Token, any, boolean, unknown>\n    | PropertySignature<\"?:\", never, PropertyKey, PropertySignature.Token, never, boolean, unknown>\n\n  // type TypeOptionalKeys<Fields extends Struct.Fields> = {\n  //   [K in keyof Fields]: Fields[K] extends OptionalTypePropertySignature ? K : never\n  // }[keyof Fields]\n\n  /**\n   * @since 3.10.0\n   */\n  export type Type<F extends Fields> = Types.UnionToIntersection<\n    {\n      [K in keyof F]: F[K] extends OptionalTypePropertySignature ? { readonly [H in K]?: Schema.Type<F[H]> } :\n        { readonly [h in K]: Schema.Type<F[h]> }\n    }[keyof F]\n  > extends infer Q ? Q : never\n\n  type Key<F extends Fields, K extends keyof F> = [K] extends [never] ? never :\n    F[K] extends PropertySignature.All<infer Key> ? [Key] extends [never] ? K : Key :\n    K\n\n  /**\n   * @since 3.10.0\n   */\n  export type Encoded<F extends Fields> =\n    & { readonly [K in Exclude<keyof F, EncodedOptionalKeys<F>> as Key<F, K>]: Schema.Encoded<F[K]> }\n    & { readonly [K in EncodedOptionalKeys<F> as Key<F, K>]?: Schema.Encoded<F[K]> }\n\n  /**\n   * @since 3.10.0\n   */\n  export type Context<F extends Fields> = Schema.Context<F[keyof F]>\n\n  type PropertySignatureWithDefault =\n    | PropertySignature<PropertySignature.Token, any, PropertyKey, PropertySignature.Token, any, true, unknown>\n    | PropertySignature<PropertySignature.Token, any, PropertyKey, PropertySignature.Token, never, true, unknown>\n    | PropertySignature<PropertySignature.Token, never, PropertyKey, PropertySignature.Token, any, true, unknown>\n    | PropertySignature<PropertySignature.Token, never, PropertyKey, PropertySignature.Token, never, true, unknown>\n\n  /**\n   * @since 3.10.0\n   */\n  export type Constructor<F extends Fields> = Types.UnionToIntersection<\n    {\n      [K in keyof F]: F[K] extends OptionalTypePropertySignature ? { readonly [H in K]?: Schema.Type<F[H]> } :\n        F[K] extends PropertySignatureWithDefault ? { readonly [H in K]?: Schema.Type<F[H]> } :\n        { readonly [h in K]: Schema.Type<F[h]> }\n    }[keyof F]\n  > extends infer Q ? Q : never\n}\n\n/**\n * @since 3.10.0\n */\nexport declare namespace IndexSignature {\n  /**\n   * @since 3.10.0\n   */\n  export type Record = { readonly key: Schema.All; readonly value: Schema.All }\n\n  /**\n   * @since 3.10.0\n   */\n  export type Records = ReadonlyArray<Record>\n\n  /**\n   * @since 3.10.0\n   */\n  export type NonEmptyRecords = array_.NonEmptyReadonlyArray<Record>\n\n  type MergeTuple<T extends ReadonlyArray<unknown>> = T extends readonly [infer Head, ...infer Tail] ?\n    Head & MergeTuple<Tail>\n    : {}\n\n  /**\n   * @since 3.10.0\n   */\n  export type Type<Records extends IndexSignature.Records> = MergeTuple<\n    {\n      readonly [K in keyof Records]: {\n        readonly [P in Schema.Type<Records[K][\"key\"]>]: Schema.Type<Records[K][\"value\"]>\n      }\n    }\n  >\n\n  /**\n   * @since 3.10.0\n   */\n  export type Encoded<Records extends IndexSignature.Records> = MergeTuple<\n    {\n      readonly [K in keyof Records]: {\n        readonly [P in Schema.Encoded<Records[K][\"key\"]>]: Schema.Encoded<Records[K][\"value\"]>\n      }\n    }\n  >\n\n  /**\n   * @since 3.10.0\n   */\n  export type Context<Records extends IndexSignature.Records> = {\n    [K in keyof Records]: Schema.Context<Records[K][\"key\"]> | Schema.Context<Records[K][\"value\"]>\n  }[number]\n}\n\n/**\n * @since 3.10.0\n */\nexport declare namespace TypeLiteral {\n  /**\n   * @since 3.10.0\n   */\n  export type Type<Fields extends Struct.Fields, Records extends IndexSignature.Records> =\n    & Struct.Type<Fields>\n    & IndexSignature.Type<Records>\n\n  /**\n   * @since 3.10.0\n   */\n  export type Encoded<Fields extends Struct.Fields, Records extends IndexSignature.Records> =\n    & Struct.Encoded<Fields>\n    & IndexSignature.Encoded<Records>\n\n  /**\n   * @since 3.10.0\n   */\n  export type Constructor<Fields extends Struct.Fields, Records extends IndexSignature.Records> =\n    & Struct.Constructor<Fields>\n    & IndexSignature.Type<Records>\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface TypeLiteral<\n  Fields extends Struct.Fields,\n  Records extends IndexSignature.Records\n> extends\n  AnnotableClass<\n    TypeLiteral<Fields, Records>,\n    Simplify<TypeLiteral.Type<Fields, Records>>,\n    Simplify<TypeLiteral.Encoded<Fields, Records>>,\n    | Struct.Context<Fields>\n    | IndexSignature.Context<Records>\n  >\n{\n  readonly fields: Readonly<Fields>\n  readonly records: Readonly<Records>\n  annotations(\n    annotations: Annotations.Schema<Simplify<TypeLiteral.Type<Fields, Records>>>\n  ): TypeLiteral<Fields, Records>\n  make(\n    props: RequiredKeys<TypeLiteral.Constructor<Fields, Records>> extends never\n      ? void | Simplify<TypeLiteral.Constructor<Fields, Records>>\n      : Simplify<TypeLiteral.Constructor<Fields, Records>>,\n    options?: MakeOptions\n  ): Simplify<TypeLiteral.Type<Fields, Records>>\n}\n\nconst preserveMissingMessageAnnotation = AST.pickAnnotations([AST.MissingMessageAnnotationId])\n\nconst getDefaultTypeLiteralAST = <\n  Fields extends Struct.Fields,\n  const Records extends IndexSignature.Records\n>(fields: Fields, records: Records) => {\n  const ownKeys = Reflect.ownKeys(fields)\n  const pss: Array<AST.PropertySignature> = []\n  if (ownKeys.length > 0) {\n    const from: Array<AST.PropertySignature> = []\n    const to: Array<AST.PropertySignature> = []\n    const transformations: Array<AST.PropertySignatureTransformation> = []\n    for (let i = 0; i < ownKeys.length; i++) {\n      const key = ownKeys[i]\n      const field = fields[key]\n      if (isPropertySignature(field)) {\n        const ast: PropertySignature.AST = field.ast\n        switch (ast._tag) {\n          case \"PropertySignatureDeclaration\": {\n            const type = ast.type\n            const isOptional = ast.isOptional\n            const toAnnotations = ast.annotations\n            from.push(new AST.PropertySignature(key, type, isOptional, true, preserveMissingMessageAnnotation(ast)))\n            to.push(new AST.PropertySignature(key, AST.typeAST(type), isOptional, true, toAnnotations))\n            pss.push(\n              new AST.PropertySignature(key, type, isOptional, true, toAnnotations)\n            )\n            break\n          }\n          case \"PropertySignatureTransformation\": {\n            const fromKey = ast.from.fromKey ?? key\n            from.push(\n              new AST.PropertySignature(fromKey, ast.from.type, ast.from.isOptional, true, ast.from.annotations)\n            )\n            to.push(\n              new AST.PropertySignature(key, ast.to.type, ast.to.isOptional, true, ast.to.annotations)\n            )\n            transformations.push(new AST.PropertySignatureTransformation(fromKey, key, ast.decode, ast.encode))\n            break\n          }\n        }\n      } else {\n        from.push(new AST.PropertySignature(key, field.ast, false, true))\n        to.push(new AST.PropertySignature(key, AST.typeAST(field.ast), false, true))\n        pss.push(new AST.PropertySignature(key, field.ast, false, true))\n      }\n    }\n    if (array_.isNonEmptyReadonlyArray(transformations)) {\n      const issFrom: Array<AST.IndexSignature> = []\n      const issTo: Array<AST.IndexSignature> = []\n      for (const r of records) {\n        const { indexSignatures, propertySignatures } = AST.record(r.key.ast, r.value.ast)\n        propertySignatures.forEach((ps) => {\n          from.push(ps)\n          to.push(\n            new AST.PropertySignature(ps.name, AST.typeAST(ps.type), ps.isOptional, ps.isReadonly, ps.annotations)\n          )\n        })\n        indexSignatures.forEach((is) => {\n          issFrom.push(is)\n          issTo.push(new AST.IndexSignature(is.parameter, AST.typeAST(is.type), is.isReadonly))\n        })\n      }\n      return new AST.Transformation(\n        new AST.TypeLiteral(from, issFrom, { [AST.AutoTitleAnnotationId]: \"Struct (Encoded side)\" }),\n        new AST.TypeLiteral(to, issTo, { [AST.AutoTitleAnnotationId]: \"Struct (Type side)\" }),\n        new AST.TypeLiteralTransformation(transformations)\n      )\n    }\n  }\n  const iss: Array<AST.IndexSignature> = []\n  for (const r of records) {\n    const { indexSignatures, propertySignatures } = AST.record(r.key.ast, r.value.ast)\n    propertySignatures.forEach((ps) => pss.push(ps))\n    indexSignatures.forEach((is) => iss.push(is))\n  }\n  return new AST.TypeLiteral(pss, iss)\n}\n\nconst lazilyMergeDefaults = (\n  fields: Struct.Fields,\n  out: Record<PropertyKey, unknown>\n): { [x: string | symbol]: unknown } => {\n  const ownKeys = Reflect.ownKeys(fields)\n  for (const key of ownKeys) {\n    const field = fields[key]\n    if (out[key] === undefined && isPropertySignature(field)) {\n      const ast = field.ast\n      const defaultValue = ast._tag === \"PropertySignatureDeclaration\" ? ast.defaultValue : ast.to.defaultValue\n      if (defaultValue !== undefined) {\n        out[key] = defaultValue()\n      }\n    }\n  }\n  return out\n}\n\nfunction makeTypeLiteralClass<Fields extends Struct.Fields, const Records extends IndexSignature.Records>(\n  fields: Fields,\n  records: Records,\n  ast: AST.AST = getDefaultTypeLiteralAST(fields, records)\n): TypeLiteral<Fields, Records> {\n  return class TypeLiteralClass extends make<\n    Simplify<TypeLiteral.Type<Fields, Records>>,\n    Simplify<TypeLiteral.Encoded<Fields, Records>>,\n    | Struct.Context<Fields>\n    | IndexSignature.Context<Records>\n  >(ast) {\n    static override annotations(\n      annotations: Annotations.Schema<Simplify<TypeLiteral.Type<Fields, Records>>>\n    ): TypeLiteral<Fields, Records> {\n      return makeTypeLiteralClass(this.fields, this.records, mergeSchemaAnnotations(this.ast, annotations))\n    }\n\n    static fields = { ...fields }\n\n    static records = [...records] as Records\n\n    static make = (\n      props: Simplify<TypeLiteral.Constructor<Fields, Records>>,\n      options?: MakeOptions\n    ): Simplify<TypeLiteral.Type<Fields, Records>> => {\n      const propsWithDefaults: any = lazilyMergeDefaults(fields, { ...props as any })\n      return getDisableValidationMakeOption(options)\n        ? propsWithDefaults\n        : ParseResult.validateSync(this)(propsWithDefaults)\n    }\n\n    static pick(...keys: Array<keyof Fields>): Struct<Simplify<Pick<Fields, typeof keys[number]>>> {\n      return Struct(struct_.pick(fields, ...keys) as any)\n    }\n\n    static omit(...keys: Array<keyof Fields>): Struct<Simplify<Omit<Fields, typeof keys[number]>>> {\n      return Struct(struct_.omit(fields, ...keys) as any)\n    }\n  }\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Struct<Fields extends Struct.Fields> extends\n  AnnotableClass<\n    Struct<Fields>,\n    Simplify<Struct.Type<Fields>>,\n    Simplify<Struct.Encoded<Fields>>,\n    Struct.Context<Fields>\n  >\n{\n  readonly fields: Readonly<Fields>\n  readonly records: readonly []\n  make(\n    props: RequiredKeys<Struct.Constructor<Fields>> extends never ? void | Simplify<Struct.Constructor<Fields>>\n      : Simplify<Struct.Constructor<Fields>>,\n    options?: MakeOptions\n  ): Simplify<Struct.Type<Fields>>\n\n  annotations(annotations: Annotations.Schema<Simplify<Struct.Type<Fields>>>): Struct<Fields>\n  pick<Keys extends ReadonlyArray<keyof Fields>>(...keys: Keys): Struct<Simplify<Pick<Fields, Keys[number]>>>\n  omit<Keys extends ReadonlyArray<keyof Fields>>(...keys: Keys): Struct<Simplify<Omit<Fields, Keys[number]>>>\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport function Struct<Fields extends Struct.Fields, const Records extends IndexSignature.NonEmptyRecords>(\n  fields: Fields,\n  ...records: Records\n): TypeLiteral<Fields, Records>\nexport function Struct<Fields extends Struct.Fields>(fields: Fields): Struct<Fields>\nexport function Struct<Fields extends Struct.Fields, const Records extends IndexSignature.Records>(\n  fields: Fields,\n  ...records: Records\n): TypeLiteral<Fields, Records> {\n  return makeTypeLiteralClass(fields, records)\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface tag<Tag extends AST.LiteralValue> extends PropertySignature<\":\", Tag, never, \":\", Tag, true, never> {}\n\n/**\n * Returns a property signature that represents a tag.\n * A tag is a literal value that is used to distinguish between different types of objects.\n * The tag is optional when using the `make` method.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Schema } from \"effect\"\n *\n * const User = Schema.Struct({\n *   _tag: Schema.tag(\"User\"),\n *   name: Schema.String,\n *   age: Schema.Number\n * })\n *\n * assert.deepStrictEqual(User.make({ name: \"John\", age: 44 }), { _tag: \"User\", name: \"John\", age: 44 })\n * ```\n *\n * @see {@link TaggedStruct}\n *\n * @since 3.10.0\n */\nexport const tag = <Tag extends AST.LiteralValue>(tag: Tag): tag<Tag> =>\n  Literal(tag).pipe(propertySignature, withConstructorDefault(() => tag))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport type TaggedStruct<Tag extends AST.LiteralValue, Fields extends Struct.Fields> = Struct<\n  { _tag: tag<Tag> } & Fields\n>\n\n/**\n * A tagged struct is a struct that has a tag property that is used to distinguish between different types of objects.\n *\n * The tag is optional when using the `make` method.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Schema } from \"effect\"\n *\n * const User = Schema.TaggedStruct(\"User\", {\n *   name: Schema.String,\n *   age: Schema.Number\n * })\n *\n * assert.deepStrictEqual(User.make({ name: \"John\", age: 44 }), { _tag: \"User\", name: \"John\", age: 44 })\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport const TaggedStruct = <Tag extends AST.LiteralValue, Fields extends Struct.Fields>(\n  value: Tag,\n  fields: Fields\n): TaggedStruct<Tag, Fields> => Struct({ _tag: tag(value), ...fields })\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Record$<K extends Schema.All, V extends Schema.All> extends\n  AnnotableClass<\n    Record$<K, V>,\n    { readonly [P in Schema.Type<K>]: Schema.Type<V> },\n    { readonly [P in Schema.Encoded<K>]: Schema.Encoded<V> },\n    | Schema.Context<K>\n    | Schema.Context<V>\n  >\n{\n  readonly fields: {}\n  readonly records: readonly [{ readonly key: K; readonly value: V }]\n  readonly key: K\n  readonly value: V\n  make(\n    props: void | { readonly [P in Schema.Type<K>]: Schema.Type<V> },\n    options?: MakeOptions\n  ): { readonly [P in Schema.Type<K>]: Schema.Type<V> }\n  annotations(annotations: Annotations.Schema<{ readonly [P in Schema.Type<K>]: Schema.Type<V> }>): Record$<K, V>\n}\n\nfunction makeRecordClass<K extends Schema.All, V extends Schema.All>(\n  key: K,\n  value: V,\n  ast?: AST.AST\n): Record$<K, V> {\n  return class RecordClass extends makeTypeLiteralClass({}, [{ key, value }], ast) {\n    static override annotations(\n      annotations: Annotations.Schema<{ readonly [P in Schema.Type<K>]: Schema.Type<V> }>\n    ): Record$<K, V> {\n      return makeRecordClass(key, value, mergeSchemaAnnotations(this.ast, annotations))\n    }\n\n    static key = key\n\n    static value = value\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const Record = <K extends Schema.All, V extends Schema.All>(\n  options: { readonly key: K; readonly value: V }\n): Record$<K, V> => makeRecordClass(options.key, options.value)\n\n/**\n * @category struct transformations\n * @since 3.10.0\n */\nexport const pick = <A, I, Keys extends ReadonlyArray<keyof A & keyof I>>(...keys: Keys) =>\n<R>(\n  self: Schema<A, I, R>\n): SchemaClass<Simplify<Pick<A, Keys[number]>>, Simplify<Pick<I, Keys[number]>>, R> => make(AST.pick(self.ast, keys))\n\n/**\n * @category struct transformations\n * @since 3.10.0\n */\nexport const omit = <A, I, Keys extends ReadonlyArray<keyof A & keyof I>>(...keys: Keys) =>\n<R>(\n  self: Schema<A, I, R>\n): SchemaClass<Simplify<Omit<A, Keys[number]>>, Simplify<Omit<I, Keys[number]>>, R> => make(AST.omit(self.ast, keys))\n\n/**\n * Given a schema `Schema<A, I, R>` and a key `key: K`, this function extracts a specific field from the `A` type,\n * producing a new schema that represents a transformation from the `{ readonly [key]: I[K] }` type to `A[K]`.\n *\n * @example\n * ```ts\n * import * as Schema from \"effect/Schema\"\n *\n * // ---------------------------------------------\n * // use case: pull out a single field from a\n * // struct through a transformation\n * // ---------------------------------------------\n *\n * const mytable = Schema.Struct({\n *   column1: Schema.NumberFromString,\n *   column2: Schema.Number\n * })\n *\n * // const pullOutColumn: S.Schema<number, {\n * //     readonly column1: string;\n * // }, never>\n * const pullOutColumn = mytable.pipe(Schema.pluck(\"column1\"))\n *\n * console.log(Schema.decodeUnknownEither(Schema.Array(pullOutColumn))([{ column1: \"1\", column2: 100 }, { column1: \"2\", column2: 300 }]))\n * // Output: { _id: 'Either', _tag: 'Right', right: [ 1, 2 ] }\n * ```\n *\n * @category struct transformations\n * @since 3.10.0\n */\nexport const pluck: {\n  <A, I, K extends keyof A & keyof I>(\n    key: K\n  ): <R>(schema: Schema<A, I, R>) => SchemaClass<A[K], Simplify<Pick<I, K>>, R>\n  <A, I, R, K extends keyof A & keyof I>(\n    schema: Schema<A, I, R>,\n    key: K\n  ): SchemaClass<A[K], Simplify<Pick<I, K>>, R>\n} = dual(\n  2,\n  <A, I, R, K extends keyof A & keyof I>(\n    schema: Schema<A, I, R>,\n    key: K\n  ): Schema<A[K], Pick<I, K>, R> => {\n    const ps = AST.getPropertyKeyIndexedAccess(AST.typeAST(schema.ast), key)\n    const value = make<A[K], A[K], R>(ps.isOptional ? AST.orUndefined(ps.type) : ps.type)\n    const out = transform(\n      schema.pipe(pick(key)),\n      value,\n      {\n        strict: true,\n        decode: (i) => i[key],\n        encode: (a) => ps.isOptional && a === undefined ? {} : { [key]: a } as any\n      }\n    )\n    return out\n  }\n)\n\n/**\n * @category branding\n * @since 3.10.0\n */\nexport interface BrandSchema<A extends Brand<any>, I = A, R = never>\n  extends AnnotableClass<BrandSchema<A, I, R>, A, I, R>\n{\n  make(a: Brand.Unbranded<A>, options?: MakeOptions): A\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface brand<S extends Schema.Any, B extends string | symbol>\n  extends BrandSchema<Schema.Type<S> & Brand<B>, Schema.Encoded<S>, Schema.Context<S>>\n{\n  readonly from: S\n  annotations(annotations: Annotations.Schema<Schema.Type<S> & Brand<B>>): brand<S, B>\n}\n\nfunction makeBrandClass<S extends Schema.Any, B extends string | symbol>(\n  from: S,\n  ast: AST.AST\n): brand<S, B> {\n  return class BrandClass extends make<Schema.Type<S> & Brand<B>, Schema.Encoded<S>, Schema.Context<S>>(ast) {\n    static override annotations(annotations: Annotations.Schema<Schema.Type<S> & Brand<B>>): brand<S, B> {\n      return makeBrandClass(this.from, mergeSchemaAnnotations(this.ast, annotations))\n    }\n\n    static make = (a: Brand.Unbranded<Schema.Type<S> & Brand<B>>, options?: MakeOptions): Schema.Type<S> & Brand<B> => {\n      return getDisableValidationMakeOption(options) ? a : ParseResult.validateSync(this)(a)\n    }\n\n    static from = from\n  }\n}\n\n/**\n * Returns a nominal branded schema by applying a brand to a given schema.\n *\n * ```\n * Schema<A> + B -> Schema<A & Brand<B>>\n * ```\n *\n * @example\n * ```ts\n * import * as Schema from \"effect/Schema\"\n *\n * const Int = Schema.Number.pipe(Schema.int(), Schema.brand(\"Int\"))\n * type Int = Schema.Schema.Type<typeof Int> // number & Brand<\"Int\">\n * ```\n *\n * @category branding\n * @since 3.10.0\n */\nexport const brand = <S extends Schema.Any, B extends string | symbol>(\n  brand: B,\n  annotations?: Annotations.Schema<Schema.Type<S> & Brand<B>>\n) =>\n(self: S): brand<S, B> => {\n  const annotation: AST.BrandAnnotation = option_.match(AST.getBrandAnnotation(self.ast), {\n    onNone: () => [brand],\n    onSome: (brands) => [...brands, brand]\n  })\n  const ast = AST.annotations(\n    self.ast,\n    toASTAnnotations({\n      [AST.BrandAnnotationId]: annotation,\n      ...annotations\n    })\n  )\n  return makeBrandClass(self, ast)\n}\n\n/**\n * @category combinators\n * @since 3.10.0\n */\nexport const partial = <A, I, R>(\n  self: Schema<A, I, R>\n): SchemaClass<{ [K in keyof A]?: A[K] | undefined }, { [K in keyof I]?: I[K] | undefined }, R> =>\n  make(AST.partial(self.ast))\n\n/**\n * @category combinators\n * @since 3.10.0\n */\nexport const partialWith: {\n  <const Options extends { readonly exact: true }>(options: Options): <A, I, R>(\n    self: Schema<A, I, R>\n  ) => SchemaClass<{ [K in keyof A]?: A[K] }, { [K in keyof I]?: I[K] }, R>\n  <A, I, R, const Options extends { readonly exact: true } | undefined>(\n    self: Schema<A, I, R>,\n    options: Options\n  ): SchemaClass<{ [K in keyof A]?: A[K] }, { [K in keyof I]?: I[K] }, R>\n} = dual((args) => isSchema(args[0]), <A, I, R>(\n  self: Schema<A, I, R>,\n  options: { readonly exact: true }\n): SchemaClass<Partial<A>, Partial<I>, R> => make(AST.partial(self.ast, options)))\n\n/**\n * @category combinators\n * @since 3.10.0\n */\nexport const required = <A, I, R>(\n  self: Schema<A, I, R>\n): SchemaClass<{ [K in keyof A]-?: A[K] }, { [K in keyof I]-?: I[K] }, R> => make(AST.required(self.ast))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface mutable<S extends Schema.Any> extends\n  AnnotableClass<\n    mutable<S>,\n    SimplifyMutable<Schema.Type<S>>,\n    SimplifyMutable<Schema.Encoded<S>>,\n    Schema.Context<S>\n  >\n{}\n\n/**\n * Creates a new schema with shallow mutability applied to its properties.\n *\n * @category combinators\n * @since 3.10.0\n */\nexport const mutable = <S extends Schema.Any>(schema: S): mutable<S> => make(AST.mutable(schema.ast))\n\nconst intersectTypeLiterals = (\n  x: AST.AST,\n  y: AST.AST,\n  path: ReadonlyArray<PropertyKey>\n): AST.TypeLiteral => {\n  if (AST.isTypeLiteral(x) && AST.isTypeLiteral(y)) {\n    const propertySignatures = [...x.propertySignatures]\n    for (const ps of y.propertySignatures) {\n      const name = ps.name\n      const i = propertySignatures.findIndex((ps) => ps.name === name)\n      if (i === -1) {\n        propertySignatures.push(ps)\n      } else {\n        const { isOptional, type } = propertySignatures[i]\n        propertySignatures[i] = new AST.PropertySignature(\n          name,\n          extendAST(type, ps.type, path.concat(name)),\n          isOptional,\n          true\n        )\n      }\n    }\n    return new AST.TypeLiteral(\n      propertySignatures,\n      x.indexSignatures.concat(y.indexSignatures)\n    )\n  }\n  throw new Error(errors_.getSchemaExtendErrorMessage(x, y, path))\n}\n\nconst preserveRefinementAnnotations = AST.omitAnnotations([AST.IdentifierAnnotationId])\n\nconst addRefinementToMembers = (refinement: AST.Refinement, asts: ReadonlyArray<AST.AST>): Array<AST.Refinement> =>\n  asts.map((ast) => new AST.Refinement(ast, refinement.filter, preserveRefinementAnnotations(refinement)))\n\nconst extendAST = (x: AST.AST, y: AST.AST, path: ReadonlyArray<PropertyKey>): AST.AST =>\n  AST.Union.make(intersectUnionMembers([x], [y], path))\n\nconst getTypes = (ast: AST.AST): ReadonlyArray<AST.AST> => AST.isUnion(ast) ? ast.types : [ast]\n\nconst intersectUnionMembers = (\n  xs: ReadonlyArray<AST.AST>,\n  ys: ReadonlyArray<AST.AST>,\n  path: ReadonlyArray<PropertyKey>\n): Array<AST.AST> =>\n  array_.flatMap(xs, (x) =>\n    array_.flatMap(ys, (y) => {\n      switch (y._tag) {\n        case \"Literal\": {\n          if (\n            (Predicate.isString(y.literal) && AST.isStringKeyword(x) ||\n              (Predicate.isNumber(y.literal) && AST.isNumberKeyword(x)) ||\n              (Predicate.isBoolean(y.literal) && AST.isBooleanKeyword(x)))\n          ) {\n            return [y]\n          }\n          break\n        }\n        case \"StringKeyword\": {\n          if (y === AST.stringKeyword) {\n            if (AST.isStringKeyword(x) || (AST.isLiteral(x) && Predicate.isString(x.literal))) {\n              return [x]\n            } else if (AST.isRefinement(x)) {\n              return addRefinementToMembers(x, intersectUnionMembers(getTypes(x.from), [y], path))\n            }\n          } else if (x === AST.stringKeyword) {\n            return [y]\n          }\n          break\n        }\n        case \"NumberKeyword\": {\n          if (y === AST.numberKeyword) {\n            if (AST.isNumberKeyword(x) || (AST.isLiteral(x) && Predicate.isNumber(x.literal))) {\n              return [x]\n            } else if (AST.isRefinement(x)) {\n              return addRefinementToMembers(x, intersectUnionMembers(getTypes(x.from), [y], path))\n            }\n          } else if (x === AST.numberKeyword) {\n            return [y]\n          }\n          break\n        }\n        case \"BooleanKeyword\": {\n          if (y === AST.booleanKeyword) {\n            if (AST.isBooleanKeyword(x) || (AST.isLiteral(x) && Predicate.isBoolean(x.literal))) {\n              return [x]\n            } else if (AST.isRefinement(x)) {\n              return addRefinementToMembers(x, intersectUnionMembers(getTypes(x.from), [y], path))\n            }\n          } else if (x === AST.booleanKeyword) {\n            return [y]\n          }\n          break\n        }\n        case \"Union\":\n          return intersectUnionMembers(getTypes(x), y.types, path)\n        case \"Suspend\":\n          return [new AST.Suspend(() => extendAST(x, y.f(), path))]\n        case \"Refinement\":\n          return addRefinementToMembers(y, intersectUnionMembers(getTypes(x), getTypes(y.from), path))\n        case \"TypeLiteral\": {\n          switch (x._tag) {\n            case \"Union\":\n              return intersectUnionMembers(x.types, [y], path)\n            case \"Suspend\":\n              return [new AST.Suspend(() => extendAST(x.f(), y, path))]\n            case \"Refinement\":\n              return addRefinementToMembers(x, intersectUnionMembers(getTypes(x.from), [y], path))\n            case \"TypeLiteral\":\n              return [intersectTypeLiterals(x, y, path)]\n            case \"Transformation\": {\n              const transformation = x.transformation\n              const from = intersectTypeLiterals(x.from, y, path)\n              const to = intersectTypeLiterals(x.to, AST.typeAST(y), path)\n              switch (transformation._tag) {\n                case \"TypeLiteralTransformation\":\n                  return [\n                    new AST.Transformation(\n                      from,\n                      to,\n                      new AST.TypeLiteralTransformation(transformation.propertySignatureTransformations)\n                    )\n                  ]\n                case \"ComposeTransformation\":\n                  return [new AST.Transformation(from, to, AST.composeTransformation)]\n                case \"FinalTransformation\":\n                  return [\n                    new AST.Transformation(\n                      from,\n                      to,\n                      new AST.FinalTransformation(\n                        (fromA, options, ast, fromI) =>\n                          ParseResult.map(\n                            transformation.decode(fromA, options, ast, fromI),\n                            (partial) => ({ ...fromA, ...partial })\n                          ),\n                        (toI, options, ast, toA) =>\n                          ParseResult.map(\n                            transformation.encode(toI, options, ast, toA),\n                            (partial) => ({ ...toI, ...partial })\n                          )\n                      )\n                    )\n                  ]\n              }\n            }\n          }\n          break\n        }\n        case \"Transformation\": {\n          if (AST.isTransformation(x)) {\n            if (\n              AST.isTypeLiteralTransformation(y.transformation) && AST.isTypeLiteralTransformation(x.transformation)\n            ) {\n              return [\n                new AST.Transformation(\n                  intersectTypeLiterals(x.from, y.from, path),\n                  intersectTypeLiterals(x.to, y.to, path),\n                  new AST.TypeLiteralTransformation(\n                    y.transformation.propertySignatureTransformations.concat(\n                      x.transformation.propertySignatureTransformations\n                    )\n                  )\n                )\n              ]\n            }\n          } else {\n            return intersectUnionMembers([y], [x], path)\n          }\n          break\n        }\n      }\n      throw new Error(errors_.getSchemaExtendErrorMessage(x, y, path))\n    }))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface extend<Self extends Schema.Any, That extends Schema.Any> extends\n  AnnotableClass<\n    extend<Self, That>,\n    Schema.Type<Self> & Schema.Type<That>,\n    Schema.Encoded<Self> & Schema.Encoded<That>,\n    Schema.Context<Self> | Schema.Context<That>\n  >\n{}\n\n/**\n * Extends a schema with another schema.\n *\n * Not all extensions are supported, and their support depends on the nature of\n * the involved schemas.\n *\n * Possible extensions include:\n * - `Schema.String` with another `Schema.String` refinement or a string literal\n * - `Schema.Number` with another `Schema.Number` refinement or a number literal\n * - `Schema.Boolean` with another `Schema.Boolean` refinement or a boolean\n *   literal\n * - A struct with another struct where overlapping fields support extension\n * - A struct with in index signature\n * - A struct with a union of supported schemas\n * - A refinement of a struct with a supported schema\n * - A suspend of a struct with a supported schema\n * - A transformation between structs where the “from” and “to” sides have no\n *   overlapping fields with the target struct\n *\n * @example\n * ```ts\n * import * as Schema from \"effect/Schema\"\n *\n * const schema = Schema.Struct({\n *   a: Schema.String,\n *   b: Schema.String\n * })\n *\n * // const extended: Schema<\n * //   {\n * //     readonly a: string\n * //     readonly b: string\n * //   } & {\n * //     readonly c: string\n * //   } & {\n * //     readonly [x: string]: string\n * //   }\n * // >\n * const extended = Schema.asSchema(schema.pipe(\n *   Schema.extend(Schema.Struct({ c: Schema.String })), // <= you can add more fields\n *   Schema.extend(Schema.Record({ key: Schema.String, value: Schema.String })) // <= you can add index signatures\n * ))\n * ```\n *\n * @category combinators\n * @since 3.10.0\n */\nexport const extend: {\n  <That extends Schema.Any>(that: That): <Self extends Schema.Any>(self: Self) => extend<Self, That>\n  <Self extends Schema.Any, That extends Schema.Any>(self: Self, that: That): extend<Self, That>\n} = dual(\n  2,\n  <Self extends Schema.Any, That extends Schema.Any>(self: Self, that: That) => make(extendAST(self.ast, that.ast, []))\n)\n\n/**\n * @category combinators\n * @since 3.10.0\n */\nexport const compose: {\n  <To extends Schema.Any, From extends Schema.Any, C extends Schema.Type<From>>(\n    to: To & Schema<Schema.Type<To>, C, Schema.Context<To>>\n  ): (from: From) => transform<From, To>\n  <To extends Schema.Any>(\n    to: To\n  ): <From extends Schema.Any, B extends Schema.Encoded<To>>(\n    from: From & Schema<B, Schema.Encoded<From>, Schema.Context<From>>\n  ) => transform<From, To>\n  <To extends Schema.Any>(\n    to: To,\n    options?: { readonly strict: true }\n  ): <From extends Schema.Any>(\n    from: From & Schema<Schema.Encoded<To>, Schema.Encoded<From>, Schema.Context<From>>\n  ) => transform<From, To>\n  <To extends Schema.Any>(\n    to: To,\n    options: { readonly strict: false }\n  ): <From extends Schema.Any>(from: From) => transform<From, To>\n\n  <From extends Schema.Any, To extends Schema.Any, C extends Schema.Type<From>>(\n    from: From,\n    to: To & Schema<Schema.Type<To>, C, Schema.Context<To>>\n  ): transform<From, To>\n  <From extends Schema.Any, B extends Schema.Encoded<To>, To extends Schema.Any>(\n    from: From & Schema<B, Schema.Encoded<From>, Schema.Context<From>>,\n    to: To\n  ): transform<From, To>\n  <From extends Schema.Any, To extends Schema.Any>(\n    from: From & Schema<Schema.Encoded<To>, Schema.Encoded<From>, Schema.Context<From>>,\n    to: To,\n    options?: { readonly strict: true }\n  ): transform<From, To>\n  <From extends Schema.Any, To extends Schema.Any>(\n    from: From,\n    to: To,\n    options: { readonly strict: false }\n  ): transform<From, To>\n} = dual(\n  (args) => isSchema(args[1]),\n  <B, A, R1, D, C, R2>(from: Schema<B, A, R1>, to: Schema<D, C, R2>): SchemaClass<D, A, R1 | R2> =>\n    makeTransformationClass(from, to, AST.compose(from.ast, to.ast))\n)\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface suspend<A, I, R> extends AnnotableClass<suspend<A, I, R>, A, I, R> {}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const suspend = <A, I, R>(f: () => Schema<A, I, R>): suspend<A, I, R> => make(new AST.Suspend(() => f().ast))\n\n/**\n * @since 3.10.0\n * @category symbol\n */\nexport const RefineSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/Refine\")\n\n/**\n * @since 3.10.0\n * @category symbol\n */\nexport type RefineSchemaId = typeof RefineSchemaId\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface refine<A, From extends Schema.Any>\n  extends AnnotableClass<refine<A, From>, A, Schema.Encoded<From>, Schema.Context<From>>\n{\n  /** The following is required for {@link HasFields} to work */\n  readonly [RefineSchemaId]: From\n  readonly from: From\n  readonly filter: (\n    a: Schema.Type<From>,\n    options: ParseOptions,\n    self: AST.Refinement\n  ) => option_.Option<ParseResult.ParseIssue>\n  make(a: Schema.Type<From>, options?: MakeOptions): A\n}\n\nfunction makeRefineClass<From extends Schema.Any, A>(\n  from: From,\n  filter: (a: Schema.Type<From>, options: ParseOptions, self: AST.Refinement) => option_.Option<ParseResult.ParseIssue>,\n  ast: AST.AST\n): refine<A, From> {\n  return class RefineClass extends make<A, Schema.Encoded<From>, Schema.Context<From>>(ast) {\n    static override annotations(annotations: Annotations.Schema<A>): refine<A, From> {\n      return makeRefineClass(this.from, this.filter, mergeSchemaAnnotations(this.ast, annotations))\n    }\n\n    static [RefineSchemaId] = from\n\n    static from = from\n\n    static filter = filter\n\n    static make = (a: Schema.Type<From>, options?: MakeOptions): A => {\n      return getDisableValidationMakeOption(options) ? a : ParseResult.validateSync(this)(a)\n    }\n  }\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface filter<From extends Schema.Any> extends refine<Schema.Type<From>, From> {}\n\nconst fromFilterPredicateReturnTypeItem = (\n  item: FilterOutput,\n  ast: AST.Refinement | AST.Transformation,\n  input: unknown\n): option_.Option<ParseResult.ParseIssue> => {\n  if (Predicate.isBoolean(item)) {\n    return item\n      ? option_.none()\n      : option_.some(new ParseResult.Type(ast, input))\n  }\n  if (Predicate.isString(item)) {\n    return option_.some(new ParseResult.Type(ast, input, item))\n  }\n  if (item !== undefined) {\n    if (\"_tag\" in item) {\n      return option_.some(item)\n    }\n    const issue = new ParseResult.Type(ast, input, item.message)\n    return option_.some(\n      array_.isNonEmptyReadonlyArray(item.path) ? new ParseResult.Pointer(item.path, input, issue) : issue\n    )\n  }\n  return option_.none()\n}\n\nconst toFilterParseIssue = (\n  out: FilterReturnType,\n  ast: AST.Refinement | AST.Transformation,\n  input: unknown\n): option_.Option<ParseResult.ParseIssue> => {\n  if (util_.isSingle(out)) {\n    return fromFilterPredicateReturnTypeItem(out, ast, input)\n  }\n  if (array_.isNonEmptyReadonlyArray(out)) {\n    const issues = array_.filterMap(out, (issue) => fromFilterPredicateReturnTypeItem(issue, ast, input))\n    if (array_.isNonEmptyReadonlyArray(issues)) {\n      return option_.some(issues.length === 1 ? issues[0] : new ParseResult.Composite(ast, input, issues))\n    }\n  }\n  return option_.none()\n}\n\n/**\n * @category filtering\n * @since 3.10.0\n */\nexport interface FilterIssue {\n  readonly path: ReadonlyArray<PropertyKey>\n  readonly message: string\n}\n\n/**\n * @category filtering\n * @since 3.10.0\n */\nexport type FilterOutput = undefined | boolean | string | ParseResult.ParseIssue | FilterIssue\n\ntype FilterReturnType = FilterOutput | ReadonlyArray<FilterOutput>\n\n/**\n * @category filtering\n * @since 3.10.0\n */\nexport function filter<C extends A, B extends A, A = C>(\n  refinement: (a: A, options: ParseOptions, self: AST.Refinement) => a is B,\n  annotations?: Annotations.Filter<C & B, C>\n): <I, R>(self: Schema<C, I, R>) => refine<C & B, Schema<A, I, R>>\nexport function filter<A, B extends A>(\n  refinement: (a: A, options: ParseOptions, self: AST.Refinement) => a is B,\n  annotations?: Annotations.Filter<B, A>\n): <I, R>(self: Schema<A, I, R>) => refine<B, Schema<A, I, R>>\nexport function filter<S extends Schema.Any>(\n  predicate: (\n    a: Types.NoInfer<Schema.Type<S>>,\n    options: ParseOptions,\n    self: AST.Refinement\n  ) => FilterReturnType,\n  annotations?: Annotations.Filter<Types.NoInfer<Schema.Type<S>>>\n): (self: S) => filter<S>\nexport function filter<A>(\n  predicate: (\n    a: A,\n    options: ParseOptions,\n    self: AST.Refinement\n  ) => FilterReturnType,\n  annotations?: Annotations.Filter<A>\n): <I, R>(self: Schema<A, I, R>) => refine<A, Schema<A, I, R>> {\n  return <I, R>(self: Schema<A, I, R>) => {\n    function filter(input: A, options: AST.ParseOptions, ast: AST.Refinement) {\n      return toFilterParseIssue(predicate(input, options, ast), ast, input)\n    }\n    const ast = new AST.Refinement(\n      self.ast,\n      filter,\n      toASTAnnotations(annotations)\n    )\n    return makeRefineClass(self, filter, ast)\n  }\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface filterEffect<S extends Schema.Any, FD = never>\n  extends transformOrFail<S, SchemaClass<Schema.Type<S>>, FD>\n{}\n\n/**\n * @category transformations\n * @since 3.10.0\n */\nexport const filterEffect: {\n  <S extends Schema.Any, FD>(\n    f: (\n      a: Types.NoInfer<Schema.Type<S>>,\n      options: ParseOptions,\n      self: AST.Transformation\n    ) => Effect.Effect<FilterReturnType, never, FD>\n  ): (self: S) => filterEffect<S, FD>\n  <S extends Schema.Any, RD>(\n    self: S,\n    f: (\n      a: Types.NoInfer<Schema.Type<S>>,\n      options: ParseOptions,\n      self: AST.Transformation\n    ) => Effect.Effect<FilterReturnType, never, RD>\n  ): filterEffect<S, RD>\n} = dual(2, <S extends Schema.Any, FD>(\n  self: S,\n  f: (\n    a: Types.NoInfer<Schema.Type<S>>,\n    options: ParseOptions,\n    self: AST.Transformation\n  ) => Effect.Effect<FilterReturnType, never, FD>\n): filterEffect<S, FD> =>\n  transformOrFail(\n    self,\n    typeSchema(self),\n    {\n      strict: true,\n      decode: (i, options, ast) =>\n        ParseResult.flatMap(\n          f(i, options, ast),\n          (filterReturnType) =>\n            option_.match(toFilterParseIssue(filterReturnType, ast, i), {\n              onNone: () => ParseResult.succeed(i),\n              onSome: ParseResult.fail\n            })\n        ),\n      encode: (a) => ParseResult.succeed(a)\n    }\n  ))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface transformOrFail<From extends Schema.All, To extends Schema.All, R = never> extends\n  AnnotableClass<\n    transformOrFail<From, To, R>,\n    Schema.Type<To>,\n    Schema.Encoded<From>,\n    Schema.Context<From> | Schema.Context<To> | R\n  >\n{\n  readonly from: From\n  readonly to: To\n}\n\nfunction makeTransformationClass<From extends Schema.Any, To extends Schema.Any, R>(\n  from: From,\n  to: To,\n  ast: AST.AST\n): transformOrFail<From, To, R> {\n  return class TransformationClass\n    extends make<Schema.Type<To>, Schema.Encoded<From>, Schema.Context<From> | Schema.Context<To> | R>(ast)\n  {\n    static override annotations(annotations: Annotations.Schema<Schema.Type<To>>) {\n      return makeTransformationClass<From, To, R>(\n        this.from,\n        this.to,\n        mergeSchemaAnnotations(this.ast, annotations)\n      )\n    }\n\n    static from = from\n\n    static to = to\n  }\n}\n\n/**\n * Create a new `Schema` by transforming the input and output of an existing `Schema`\n * using the provided decoding functions.\n *\n * @category transformations\n * @since 3.10.0\n */\nexport const transformOrFail: {\n  <To extends Schema.Any, From extends Schema.Any, RD, RE>(\n    to: To,\n    options: {\n      readonly decode: (\n        fromA: Schema.Type<From>,\n        options: ParseOptions,\n        ast: AST.Transformation,\n        fromI: Schema.Encoded<From>\n      ) => Effect.Effect<Schema.Encoded<To>, ParseResult.ParseIssue, RD>\n      readonly encode: (\n        toI: Schema.Encoded<To>,\n        options: ParseOptions,\n        ast: AST.Transformation,\n        toA: Schema.Type<To>\n      ) => Effect.Effect<Schema.Type<From>, ParseResult.ParseIssue, RE>\n      readonly strict?: true\n    } | {\n      readonly decode: (\n        fromA: Schema.Type<From>,\n        options: ParseOptions,\n        ast: AST.Transformation,\n        fromI: Schema.Encoded<From>\n      ) => Effect.Effect<unknown, ParseResult.ParseIssue, RD>\n      readonly encode: (\n        toI: Schema.Encoded<To>,\n        options: ParseOptions,\n        ast: AST.Transformation,\n        toA: Schema.Type<To>\n      ) => Effect.Effect<unknown, ParseResult.ParseIssue, RE>\n      readonly strict: false\n    }\n  ): (from: From) => transformOrFail<From, To, RD | RE>\n  <To extends Schema.Any, From extends Schema.Any, RD, RE>(\n    from: From,\n    to: To,\n    options: {\n      readonly decode: (\n        fromA: Schema.Type<From>,\n        options: ParseOptions,\n        ast: AST.Transformation,\n        fromI: Schema.Encoded<From>\n      ) => Effect.Effect<Schema.Encoded<To>, ParseResult.ParseIssue, RD>\n      readonly encode: (\n        toI: Schema.Encoded<To>,\n        options: ParseOptions,\n        ast: AST.Transformation,\n        toA: Schema.Type<To>\n      ) => Effect.Effect<Schema.Type<From>, ParseResult.ParseIssue, RE>\n      readonly strict?: true\n    } | {\n      readonly decode: (\n        fromA: Schema.Type<From>,\n        options: ParseOptions,\n        ast: AST.Transformation,\n        fromI: Schema.Encoded<From>\n      ) => Effect.Effect<unknown, ParseResult.ParseIssue, RD>\n      readonly encode: (\n        toI: Schema.Encoded<To>,\n        options: ParseOptions,\n        ast: AST.Transformation,\n        toA: Schema.Type<To>\n      ) => Effect.Effect<unknown, ParseResult.ParseIssue, RE>\n      readonly strict: false\n    }\n  ): transformOrFail<From, To, RD | RE>\n} = dual((args) => isSchema(args[0]) && isSchema(args[1]), <FromA, FromI, FromR, ToA, ToI, ToR, RD, RE>(\n  from: Schema<FromA, FromI, FromR>,\n  to: Schema<ToA, ToI, ToR>,\n  options: {\n    readonly decode: (\n      fromA: FromA,\n      options: ParseOptions,\n      ast: AST.Transformation,\n      fromI: FromI\n    ) => Effect.Effect<ToI, ParseResult.ParseIssue, RD>\n    readonly encode: (\n      toI: ToI,\n      options: ParseOptions,\n      ast: AST.Transformation,\n      toA: ToA\n    ) => Effect.Effect<FromA, ParseResult.ParseIssue, RE>\n  }\n): Schema<ToA, FromI, FromR | ToR | RD | RE> =>\n  makeTransformationClass(\n    from,\n    to,\n    new AST.Transformation(\n      from.ast,\n      to.ast,\n      new AST.FinalTransformation(options.decode, options.encode)\n    )\n  ))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface transform<From extends Schema.All, To extends Schema.All> extends transformOrFail<From, To> {\n  annotations(annotations: Annotations.Schema<Schema.Type<To>>): transform<From, To>\n}\n\n/**\n * Create a new `Schema` by transforming the input and output of an existing `Schema`\n * using the provided mapping functions.\n *\n * @category transformations\n * @since 3.10.0\n */\nexport const transform: {\n  <To extends Schema.Any, From extends Schema.Any>(\n    to: To,\n    options: {\n      readonly decode: (fromA: Schema.Type<From>, fromI: Schema.Encoded<From>) => Schema.Encoded<To>\n      readonly encode: (toI: Schema.Encoded<To>, toA: Schema.Type<To>) => Schema.Type<From>\n      readonly strict?: true\n    } | {\n      readonly decode: (fromA: Schema.Type<From>, fromI: Schema.Encoded<From>) => unknown\n      readonly encode: (toI: Schema.Encoded<To>, toA: Schema.Type<To>) => unknown\n      readonly strict: false\n    }\n  ): (from: From) => transform<From, To>\n  <To extends Schema.Any, From extends Schema.Any>(\n    from: From,\n    to: To,\n    options: {\n      readonly decode: (fromA: Schema.Type<From>, fromI: Schema.Encoded<From>) => Schema.Encoded<To>\n      readonly encode: (toI: Schema.Encoded<To>, toA: Schema.Type<To>) => Schema.Type<From>\n      readonly strict?: true\n    } | {\n      readonly decode: (fromA: Schema.Type<From>, fromI: Schema.Encoded<From>) => unknown\n      readonly encode: (toI: Schema.Encoded<To>, toA: Schema.Type<To>) => unknown\n      readonly strict: false\n    }\n  ): transform<From, To>\n} = dual(\n  (args) => isSchema(args[0]) && isSchema(args[1]),\n  <FromA, FromI, FromR, ToA, ToI, ToR>(\n    from: Schema<FromA, FromI, FromR>,\n    to: Schema<ToA, ToI, ToR>,\n    options: {\n      readonly decode: (fromA: FromA, fromI: FromI) => ToI\n      readonly encode: (toI: ToI, toA: ToA) => FromA\n    }\n  ): Schema<ToA, FromI, FromR | ToR> =>\n    transformOrFail(\n      from,\n      to,\n      {\n        strict: true,\n        decode: (fromA, _options, _ast, toA) => ParseResult.succeed(options.decode(fromA, toA)),\n        encode: (toI, _options, _ast, toA) => ParseResult.succeed(options.encode(toI, toA))\n      }\n    )\n)\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface transformLiteral<Type extends AST.LiteralValue, Encoded extends AST.LiteralValue>\n  extends transform<Literal<[Encoded]>, Literal<[Type]>>\n{\n  annotations(annotations: Annotations.Schema<Type>): transformLiteral<Type, Encoded>\n}\n\n/**\n * Creates a new `Schema` which transforms literal values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import * as S from \"effect/Schema\"\n *\n * const schema = S.transformLiteral(0, \"a\")\n *\n * assert.deepStrictEqual(S.decodeSync(schema)(0), \"a\")\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function transformLiteral<Encoded extends AST.LiteralValue, Type extends AST.LiteralValue>(\n  from: Encoded,\n  to: Type\n): transformLiteral<Type, Encoded> {\n  return transform(Literal(from), Literal(to), {\n    strict: true,\n    decode: () => to,\n    encode: () => from\n  })\n}\n\n/**\n * Creates a new `Schema` which maps between corresponding literal values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import * as S from \"effect/Schema\"\n *\n * const Animal = S.transformLiterals(\n *   [0, \"cat\"],\n *   [1, \"dog\"],\n *   [2, \"cow\"]\n * )\n *\n * assert.deepStrictEqual(S.decodeSync(Animal)(1), \"dog\")\n * ```\n *\n * @category constructors\n * @since 3.10.0\n */\nexport function transformLiterals<const A extends AST.Members<readonly [from: AST.LiteralValue, to: AST.LiteralValue]>>(\n  ...pairs: A\n): Union<{ -readonly [I in keyof A]: transformLiteral<A[I][1], A[I][0]> }>\nexport function transformLiterals<Encoded extends AST.LiteralValue, Type extends AST.LiteralValue>(\n  pairs: [Encoded, Type]\n): transformLiteral<Type, Encoded>\nexport function transformLiterals<\n  const A extends ReadonlyArray<readonly [from: AST.LiteralValue, to: AST.LiteralValue]>\n>(...pairs: A): Schema<A[number][1], A[number][0]>\nexport function transformLiterals<\n  const A extends ReadonlyArray<readonly [from: AST.LiteralValue, to: AST.LiteralValue]>\n>(...pairs: A): Schema<A[number][1], A[number][0]> {\n  return Union(...pairs.map(([from, to]) => transformLiteral(from, to)))\n}\n\n/**\n * Attaches a property signature with the specified key and value to the schema.\n * This API is useful when you want to add a property to your schema which doesn't describe the shape of the input,\n * but rather maps to another schema, for example when you want to add a discriminant to a simple union.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import * as S from \"effect/Schema\"\n * import { pipe } from \"effect/Function\"\n *\n * const Circle = S.Struct({ radius: S.Number })\n * const Square = S.Struct({ sideLength: S.Number })\n * const Shape = S.Union(\n *   Circle.pipe(S.attachPropertySignature(\"kind\", \"circle\")),\n *   Square.pipe(S.attachPropertySignature(\"kind\", \"square\"))\n * )\n *\n * assert.deepStrictEqual(S.decodeSync(Shape)({ radius: 10 }), {\n *   kind: \"circle\",\n *   radius: 10\n * })\n * ```\n *\n * @category combinators\n * @since 3.10.0\n */\nexport const attachPropertySignature: {\n  <K extends PropertyKey, V extends AST.LiteralValue | symbol, A>(\n    key: K,\n    value: V,\n    annotations?: Annotations.Schema<A & { readonly [k in K]: V }>\n  ): <I, R>(\n    schema: Schema<A, I, R>\n  ) => SchemaClass<A & { readonly [k in K]: V }, I, R>\n  <A, I, R, K extends PropertyKey, V extends AST.LiteralValue | symbol>(\n    schema: Schema<A, I, R>,\n    key: K,\n    value: V,\n    annotations?: Annotations.Schema<A & { readonly [k in K]: V }>\n  ): SchemaClass<A & { readonly [k in K]: V }, I, R>\n} = dual(\n  (args) => isSchema(args[0]),\n  <A, I, R, K extends PropertyKey, V extends AST.LiteralValue | symbol>(\n    schema: Schema<A, I, R>,\n    key: K,\n    value: V,\n    annotations?: Annotations.Schema<A & { readonly [k in K]: V }>\n  ): SchemaClass<A & { readonly [k in K]: V }, I, R> => {\n    const ast = extend(\n      typeSchema(schema),\n      Struct({ [key]: Predicate.isSymbol(value) ? UniqueSymbolFromSelf(value) : Literal(value) })\n    ).ast\n    return make(\n      new AST.Transformation(\n        schema.ast,\n        annotations ? mergeSchemaAnnotations(ast, annotations) : ast,\n        new AST.TypeLiteralTransformation(\n          [\n            new AST.PropertySignatureTransformation(\n              key,\n              key,\n              () => option_.some(value),\n              () => option_.none()\n            )\n          ]\n        )\n      )\n    )\n  }\n)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport declare namespace Annotations {\n  /**\n   * @category annotations\n   * @since 3.10.0\n   */\n  export interface Doc<A> extends AST.Annotations {\n    readonly title?: AST.TitleAnnotation\n    readonly description?: AST.DescriptionAnnotation\n    readonly documentation?: AST.DocumentationAnnotation\n    readonly examples?: AST.ExamplesAnnotation<A>\n    readonly default?: AST.DefaultAnnotation<A>\n  }\n\n  /**\n   * @since 3.10.0\n   */\n  export interface Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []> extends Doc<A> {\n    readonly typeConstructor?: AST.TypeConstructorAnnotation\n    readonly identifier?: AST.IdentifierAnnotation\n    readonly message?: AST.MessageAnnotation\n    readonly schemaId?: AST.SchemaIdAnnotation\n    readonly jsonSchema?: AST.JSONSchemaAnnotation\n    readonly arbitrary?: ArbitraryAnnotation<A, TypeParameters>\n    readonly pretty?: pretty_.PrettyAnnotation<A, TypeParameters>\n    readonly equivalence?: AST.EquivalenceAnnotation<A, TypeParameters>\n    readonly concurrency?: AST.ConcurrencyAnnotation\n    readonly batching?: AST.BatchingAnnotation\n    readonly parseIssueTitle?: AST.ParseIssueTitleAnnotation\n    readonly parseOptions?: AST.ParseOptions\n    readonly decodingFallback?: AST.DecodingFallbackAnnotation<A>\n  }\n\n  /**\n   * @since 3.11.6\n   */\n  export interface GenericSchema<A> extends Schema<A> {\n    readonly arbitrary?: (..._: any) => LazyArbitrary<A>\n    readonly pretty?: (..._: any) => pretty_.Pretty<A>\n    readonly equivalence?: (..._: any) => Equivalence.Equivalence<A>\n  }\n\n  // TODO(4.0): replace `readonly [P]` with `readonly []`\n  /**\n   * @since 3.10.0\n   */\n  export interface Filter<A, P = A> extends Schema<A, readonly [P]> {}\n}\n\n/**\n * Merges a set of new annotations with existing ones, potentially overwriting\n * any duplicates.\n *\n * @category annotations\n * @since 3.10.0\n */\nexport const annotations: {\n  <S extends Annotable.All>(annotations: Annotations.GenericSchema<Schema.Type<S>>): (self: S) => Annotable.Self<S>\n  <S extends Annotable.All>(self: S, annotations: Annotations.GenericSchema<Schema.Type<S>>): Annotable.Self<S>\n} = dual(\n  2,\n  <A, I, R>(self: Schema<A, I, R>, annotations: Annotations.GenericSchema<A>): Schema<A, I, R> =>\n    self.annotations(annotations)\n)\n\ntype Rename<A, M> = {\n  [\n    K in keyof A as K extends keyof M ? M[K] extends PropertyKey ? M[K]\n      : never\n      : K\n  ]: A[K]\n}\n\n/**\n * @category renaming\n * @since 3.10.0\n */\nexport const rename: {\n  <\n    A,\n    const M extends\n      & { readonly [K in keyof A]?: PropertyKey }\n      & { readonly [K in Exclude<keyof M, keyof A>]: never }\n  >(\n    mapping: M\n  ): <I, R>(self: Schema<A, I, R>) => SchemaClass<Simplify<Rename<A, M>>, I, R>\n  <\n    A,\n    I,\n    R,\n    const M extends\n      & { readonly [K in keyof A]?: PropertyKey }\n      & { readonly [K in Exclude<keyof M, keyof A>]: never }\n  >(\n    self: Schema<A, I, R>,\n    mapping: M\n  ): SchemaClass<Simplify<Rename<A, M>>, I, R>\n} = dual(\n  2,\n  <\n    A,\n    I,\n    R,\n    const M extends\n      & { readonly [K in keyof A]?: PropertyKey }\n      & { readonly [K in Exclude<keyof M, keyof A>]: never }\n  >(\n    self: Schema<A, I, R>,\n    mapping: M\n  ): SchemaClass<Simplify<Rename<A, M>>, I, R> => make(AST.rename(self.ast, mapping))\n)\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const TrimmedSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/Trimmed\")\n\n/**\n * Verifies that a string contains no leading or trailing whitespaces.\n *\n * Note. This combinator does not make any transformations, it only validates.\n * If what you were looking for was a combinator to trim strings, then check out the `trim` combinator.\n *\n * @category string filters\n * @since 3.10.0\n */\nexport const trimmed = <S extends Schema.Any>(\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => a === a.trim(), {\n      schemaId: TrimmedSchemaId,\n      title: \"trimmed\",\n      description: \"a string with no leading or trailing whitespace\",\n      jsonSchema: { pattern: \"^\\\\S[\\\\s\\\\S]*\\\\S$|^\\\\S$|^$\" },\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const MaxLengthSchemaId: unique symbol = schemaId_.MaxLengthSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type MaxLengthSchemaId = typeof MaxLengthSchemaId\n\n/**\n * @category string filters\n * @since 3.10.0\n */\nexport const maxLength =\n  <S extends Schema.Any>(maxLength: number, annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter(\n        (a) => a.length <= maxLength,\n        {\n          schemaId: MaxLengthSchemaId,\n          title: `maxLength(${maxLength})`,\n          description: `a string at most ${maxLength} character(s) long`,\n          jsonSchema: { maxLength },\n          ...annotations\n        }\n      )\n    )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const MinLengthSchemaId: unique symbol = schemaId_.MinLengthSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type MinLengthSchemaId = typeof MinLengthSchemaId\n\n/**\n * @category string filters\n * @since 3.10.0\n */\nexport const minLength = <S extends Schema.Any>(\n  minLength: number,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter(\n      (a) => a.length >= minLength,\n      {\n        schemaId: MinLengthSchemaId,\n        title: `minLength(${minLength})`,\n        description: `a string at least ${minLength} character(s) long`,\n        jsonSchema: { minLength },\n        ...annotations\n      }\n    )\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LengthSchemaId: unique symbol = schemaId_.LengthSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type LengthSchemaId = typeof LengthSchemaId\n\n/**\n * @category string filters\n * @since 3.10.0\n */\nexport const length = <S extends Schema.Any>(\n  length: number | { readonly min: number; readonly max: number },\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n  const minLength = Predicate.isObject(length) ? Math.max(0, Math.floor(length.min)) : Math.max(0, Math.floor(length))\n  const maxLength = Predicate.isObject(length) ? Math.max(minLength, Math.floor(length.max)) : minLength\n  if (minLength !== maxLength) {\n    return self.pipe(\n      filter((a) => a.length >= minLength && a.length <= maxLength, {\n        schemaId: LengthSchemaId,\n        title: `length({ min: ${minLength}, max: ${maxLength})`,\n        description: `a string at least ${minLength} character(s) and at most ${maxLength} character(s) long`,\n        jsonSchema: { minLength, maxLength },\n        ...annotations\n      })\n    )\n  }\n  return self.pipe(\n    filter((a) => a.length === minLength, {\n      schemaId: LengthSchemaId,\n      title: `length(${minLength})`,\n      description: minLength === 1 ? `a single character` : `a string ${minLength} character(s) long`,\n      jsonSchema: { minLength, maxLength: minLength },\n      ...annotations\n    })\n  )\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const PatternSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/Pattern\")\n\n/**\n * @category string filters\n * @since 3.10.0\n */\nexport const pattern = <S extends Schema.Any>(\n  regex: RegExp,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n  const source = regex.source\n  return self.pipe(\n    filter(\n      (a) => {\n        // The following line ensures that `lastIndex` is reset to `0` in case the user has specified the `g` flag\n        regex.lastIndex = 0\n        return regex.test(a)\n      },\n      {\n        schemaId: PatternSchemaId,\n        [PatternSchemaId]: { regex },\n        // title: `pattern(/${source}/)`, // avoiding this because it can be very long\n        description: `a string matching the pattern ${source}`,\n        jsonSchema: { pattern: source },\n        ...annotations\n      }\n    )\n  )\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const StartsWithSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/StartsWith\")\n\n/**\n * @category string filters\n * @since 3.10.0\n */\nexport const startsWith = <S extends Schema.Any>(\n  startsWith: string,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n  const formatted = JSON.stringify(startsWith)\n  return self.pipe(\n    filter(\n      (a) => a.startsWith(startsWith),\n      {\n        schemaId: StartsWithSchemaId,\n        [StartsWithSchemaId]: { startsWith },\n        title: `startsWith(${formatted})`,\n        description: `a string starting with ${formatted}`,\n        jsonSchema: { pattern: `^${startsWith}` },\n        ...annotations\n      }\n    )\n  )\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const EndsWithSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/EndsWith\")\n\n/**\n * @category string filters\n * @since 3.10.0\n */\nexport const endsWith = <S extends Schema.Any>(\n  endsWith: string,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n  const formatted = JSON.stringify(endsWith)\n  return self.pipe(\n    filter(\n      (a) => a.endsWith(endsWith),\n      {\n        schemaId: EndsWithSchemaId,\n        [EndsWithSchemaId]: { endsWith },\n        title: `endsWith(${formatted})`,\n        description: `a string ending with ${formatted}`,\n        jsonSchema: { pattern: `^.*${endsWith}$` },\n        ...annotations\n      }\n    )\n  )\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const IncludesSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/Includes\")\n\n/**\n * @category string filters\n * @since 3.10.0\n */\nexport const includes = <S extends Schema.Any>(\n  searchString: string,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n  const formatted = JSON.stringify(searchString)\n  return self.pipe(\n    filter(\n      (a) => a.includes(searchString),\n      {\n        schemaId: IncludesSchemaId,\n        [IncludesSchemaId]: { includes: searchString },\n        title: `includes(${formatted})`,\n        description: `a string including ${formatted}`,\n        jsonSchema: { pattern: `.*${searchString}.*` },\n        ...annotations\n      }\n    )\n  )\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LowercasedSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/Lowercased\")\n\n/**\n * Verifies that a string is lowercased.\n *\n * @category string filters\n * @since 3.10.0\n */\nexport const lowercased =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => a === a.toLowerCase(), {\n        schemaId: LowercasedSchemaId,\n        title: \"lowercased\",\n        description: \"a lowercase string\",\n        jsonSchema: { pattern: \"^[^A-Z]*$\" },\n        ...annotations\n      })\n    )\n\n/**\n * @category string constructors\n * @since 3.10.0\n */\nexport class Lowercased extends String$.pipe(\n  lowercased({ identifier: \"Lowercased\" })\n) {}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const UppercasedSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/Uppercased\")\n\n/**\n * Verifies that a string is uppercased.\n *\n * @category string filters\n * @since 3.10.0\n */\nexport const uppercased =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => a === a.toUpperCase(), {\n        schemaId: UppercasedSchemaId,\n        title: \"uppercased\",\n        description: \"an uppercase string\",\n        jsonSchema: { pattern: \"^[^a-z]*$\" },\n        ...annotations\n      })\n    )\n\n/**\n * @category string constructors\n * @since 3.10.0\n */\nexport class Uppercased extends String$.pipe(\n  uppercased({ identifier: \"Uppercased\" })\n) {}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const CapitalizedSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/Capitalized\")\n\n/**\n * Verifies that a string is capitalized.\n *\n * @category string filters\n * @since 3.10.0\n */\nexport const capitalized =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => a[0]?.toUpperCase() === a[0], {\n        schemaId: CapitalizedSchemaId,\n        title: \"capitalized\",\n        description: \"a capitalized string\",\n        jsonSchema: { pattern: \"^[^a-z]?.*$\" },\n        ...annotations\n      })\n    )\n\n/**\n * @category string constructors\n * @since 3.10.0\n */\nexport class Capitalized extends String$.pipe(\n  capitalized({ identifier: \"Capitalized\" })\n) {}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const UncapitalizedSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/Uncapitalized\")\n\n/**\n * Verifies that a string is uncapitalized.\n *\n * @category string filters\n * @since 3.10.0\n */\nexport const uncapitalized =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => a[0]?.toLowerCase() === a[0], {\n        schemaId: UncapitalizedSchemaId,\n        title: \"uncapitalized\",\n        description: \"a uncapitalized string\",\n        jsonSchema: { pattern: \"^[^A-Z]?.*$\" },\n        ...annotations\n      })\n    )\n\n/**\n * @category string constructors\n * @since 3.10.0\n */\nexport class Uncapitalized extends String$.pipe(\n  uncapitalized({ identifier: \"Uncapitalized\" })\n) {}\n\n/**\n * A schema representing a single character.\n *\n * @category string constructors\n * @since 3.10.0\n */\nexport class Char extends String$.pipe(length(1, { identifier: \"Char\" })) {}\n\n/**\n * @category string filters\n * @since 3.10.0\n */\nexport const nonEmptyString = <S extends Schema.Any>(\n  annotations?: Annotations.Filter<Schema.Type<S>>\n): <A extends string>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>) => filter<S> =>\n  minLength(1, {\n    title: \"nonEmptyString\",\n    description: \"a non empty string\",\n    ...annotations\n  })\n\n/**\n * This schema converts a string to lowercase.\n *\n * @category string transformations\n * @since 3.10.0\n */\nexport class Lowercase extends transform(\n  String$.annotations({ description: \"a string that will be converted to lowercase\" }),\n  Lowercased,\n  {\n    strict: true,\n    decode: (i) => i.toLowerCase(),\n    encode: identity\n  }\n).annotations({ identifier: \"Lowercase\" }) {}\n\n/**\n * This schema converts a string to uppercase.\n *\n * @category string transformations\n * @since 3.10.0\n */\nexport class Uppercase extends transform(\n  String$.annotations({ description: \"a string that will be converted to uppercase\" }),\n  Uppercased,\n  {\n    strict: true,\n    decode: (i) => i.toUpperCase(),\n    encode: identity\n  }\n).annotations({ identifier: \"Uppercase\" }) {}\n\n/**\n * This schema converts a string to capitalized one.\n *\n * @category string transformations\n * @since 3.10.0\n */\nexport class Capitalize extends transform(\n  String$.annotations({ description: \"a string that will be converted to a capitalized format\" }),\n  Capitalized,\n  {\n    strict: true,\n    decode: (i) => string_.capitalize(i),\n    encode: identity\n  }\n).annotations({ identifier: \"Capitalize\" }) {}\n\n/**\n * This schema converts a string to uncapitalized one.\n *\n * @category string transformations\n * @since 3.10.0\n */\nexport class Uncapitalize extends transform(\n  String$.annotations({ description: \"a string that will be converted to an uncapitalized format\" }),\n  Uncapitalized,\n  {\n    strict: true,\n    decode: (i) => string_.uncapitalize(i),\n    encode: identity\n  }\n).annotations({ identifier: \"Uncapitalize\" }) {}\n\n/**\n * @category string constructors\n * @since 3.10.0\n */\nexport class Trimmed extends String$.pipe(\n  trimmed({ identifier: \"Trimmed\" })\n) {}\n\n/**\n * Useful for validating strings that must contain meaningful characters without\n * leading or trailing whitespace.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n *\n * console.log(Schema.decodeOption(Schema.NonEmptyTrimmedString)(\"\")) // Option.none()\n * console.log(Schema.decodeOption(Schema.NonEmptyTrimmedString)(\" a \")) // Option.none()\n * console.log(Schema.decodeOption(Schema.NonEmptyTrimmedString)(\"a\")) // Option.some(\"a\")\n * ```\n *\n * @category string constructors\n * @since 3.10.0\n */\nexport class NonEmptyTrimmedString extends Trimmed.pipe(\n  nonEmptyString({ identifier: \"NonEmptyTrimmedString\" })\n) {}\n\n/**\n * This schema allows removing whitespaces from the beginning and end of a string.\n *\n * @category string transformations\n * @since 3.10.0\n */\nexport class Trim extends transform(\n  String$.annotations({ description: \"a string that will be trimmed\" }),\n  Trimmed,\n  {\n    strict: true,\n    decode: (i) => i.trim(),\n    encode: identity\n  }\n).annotations({ identifier: \"Trim\" }) {}\n\n/**\n * Returns a schema that allows splitting a string into an array of strings.\n *\n * @category string transformations\n * @since 3.10.0\n */\nexport const split = (separator: string): transform<SchemaClass<string>, Array$<typeof String$>> =>\n  transform(\n    String$.annotations({ description: \"a string that will be split\" }),\n    Array$(String$),\n    {\n      strict: true,\n      decode: (i) => i.split(separator),\n      encode: (a) => a.join(separator)\n    }\n  )\n\n/**\n * @since 3.10.0\n */\nexport type ParseJsonOptions = {\n  readonly reviver?: Parameters<typeof JSON.parse>[1]\n  readonly replacer?: Parameters<typeof JSON.stringify>[1]\n  readonly space?: Parameters<typeof JSON.stringify>[2]\n}\n\nconst getErrorMessage = (e: unknown): string => e instanceof Error ? e.message : String(e)\n\nconst getParseJsonTransformation = (options?: ParseJsonOptions): SchemaClass<unknown, string> =>\n  transformOrFail(\n    String$.annotations({ description: \"a string to be decoded into JSON\" }),\n    Unknown,\n    {\n      strict: true,\n      decode: (i, _, ast) =>\n        ParseResult.try({\n          try: () => JSON.parse(i, options?.reviver),\n          catch: (e) => new ParseResult.Type(ast, i, getErrorMessage(e))\n        }),\n      encode: (a, _, ast) =>\n        ParseResult.try({\n          try: () => JSON.stringify(a, options?.replacer, options?.space),\n          catch: (e) => new ParseResult.Type(ast, a, getErrorMessage(e))\n        })\n    }\n  ).annotations({\n    title: \"parseJson\",\n    schemaId: AST.ParseJsonSchemaId\n  })\n\n/**\n * The `ParseJson` combinator provides a method to convert JSON strings into the `unknown` type using the underlying\n * functionality of `JSON.parse`. It also utilizes `JSON.stringify` for encoding.\n *\n * You can optionally provide a `ParseJsonOptions` to configure both `JSON.parse` and `JSON.stringify` executions.\n *\n * Optionally, you can pass a schema `Schema<A, I, R>` to obtain an `A` type instead of `unknown`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import * as Schema from \"effect/Schema\"\n *\n * assert.deepStrictEqual(Schema.decodeUnknownSync(Schema.parseJson())(`{\"a\":\"1\"}`), { a: \"1\" })\n * assert.deepStrictEqual(Schema.decodeUnknownSync(Schema.parseJson(Schema.Struct({ a: Schema.NumberFromString })))(`{\"a\":\"1\"}`), { a: 1 })\n * ```\n *\n * @category string transformations\n * @since 3.10.0\n */\nexport const parseJson: {\n  <S extends Schema.Any>(schema: S, options?: ParseJsonOptions): transform<SchemaClass<unknown, string>, S>\n  (options?: ParseJsonOptions): SchemaClass<unknown, string>\n} = <A, I, R>(schemaOrOptions?: Schema<A, I, R> | ParseJsonOptions, o?: ParseJsonOptions) =>\n  isSchema(schemaOrOptions)\n    ? compose(parseJson(o), schemaOrOptions) as any\n    : getParseJsonTransformation(schemaOrOptions as ParseJsonOptions | undefined)\n\n/**\n * @category string constructors\n * @since 3.10.0\n */\nexport class NonEmptyString extends String$.pipe(\n  nonEmptyString({ identifier: \"NonEmptyString\" })\n) {}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const UUIDSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/UUID\")\n\nconst uuidRegexp = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i\n\n/**\n * Represents a Universally Unique Identifier (UUID).\n *\n * This schema ensures that the provided string adheres to the standard UUID format.\n *\n * @category string constructors\n * @since 3.10.0\n */\nexport class UUID extends String$.pipe(\n  pattern(uuidRegexp, {\n    schemaId: UUIDSchemaId,\n    identifier: \"UUID\",\n    jsonSchema: {\n      format: \"uuid\",\n      pattern: uuidRegexp.source\n    },\n    description: \"a Universally Unique Identifier\",\n    arbitrary: (): LazyArbitrary<string> => (fc) => fc.uuid()\n  })\n) {}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const ULIDSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/ULID\")\n\nconst ulidRegexp = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i\n\n/**\n * Represents a Universally Unique Lexicographically Sortable Identifier (ULID).\n *\n * ULIDs are designed to be compact, URL-safe, and ordered, making them suitable for use as identifiers.\n * This schema ensures that the provided string adheres to the standard ULID format.\n *\n * @category string constructors\n * @since 3.10.0\n */\nexport class ULID extends String$.pipe(\n  pattern(ulidRegexp, {\n    schemaId: ULIDSchemaId,\n    identifier: \"ULID\",\n    description: \"a Universally Unique Lexicographically Sortable Identifier\",\n    arbitrary: (): LazyArbitrary<string> => (fc) => fc.ulid()\n  })\n) {}\n\n/**\n * Defines a schema that represents a `URL` object.\n *\n * @category URL constructors\n * @since 3.11.0\n */\nexport class URLFromSelf extends instanceOf(URL, {\n  typeConstructor: { _tag: \"URL\" },\n  identifier: \"URLFromSelf\",\n  arbitrary: (): LazyArbitrary<URL> => (fc) => fc.webUrl().map((s) => new URL(s)),\n  pretty: () => (url) => url.toString()\n}) {}\n\n/** @ignore */\nclass URL$ extends transformOrFail(\n  String$.annotations({ description: \"a string to be decoded into a URL\" }),\n  URLFromSelf,\n  {\n    strict: true,\n    decode: (i, _, ast) =>\n      ParseResult.try({\n        try: () => new URL(i),\n        catch: (e) =>\n          new ParseResult.Type(\n            ast,\n            i,\n            `Unable to decode ${JSON.stringify(i)} into a URL. ${getErrorMessage(e)}`\n          )\n      }),\n    encode: (a) => ParseResult.succeed(a.toString())\n  }\n).annotations({\n  identifier: \"URL\",\n  pretty: () => (url) => url.toString()\n}) {}\n\nexport {\n  /**\n   * Defines a schema that attempts to convert a `string` to a `URL` object using\n   * the `new URL` constructor.\n   *\n   * @category URL transformations\n   * @since 3.11.0\n   */\n  URL$ as URL\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const FiniteSchemaId: unique symbol = schemaId_.FiniteSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type FiniteSchemaId = typeof FiniteSchemaId\n\n/**\n * Ensures that the provided value is a finite number (excluding NaN, +Infinity, and -Infinity).\n *\n * @category number filters\n * @since 3.10.0\n */\nexport const finite =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter(Number.isFinite, {\n        schemaId: FiniteSchemaId,\n        title: \"finite\",\n        description: \"a finite number\",\n        jsonSchema: {},\n        ...annotations\n      })\n    )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const GreaterThanSchemaId: unique symbol = schemaId_.GreaterThanSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type GreaterThanSchemaId = typeof GreaterThanSchemaId\n\n/**\n * This filter checks whether the provided number is greater than the specified minimum.\n *\n * @category number filters\n * @since 3.10.0\n */\nexport const greaterThan = <S extends Schema.Any>(\n  exclusiveMinimum: number,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => a > exclusiveMinimum, {\n      schemaId: GreaterThanSchemaId,\n      title: `greaterThan(${exclusiveMinimum})`,\n      description: exclusiveMinimum === 0 ? \"a positive number\" : `a number greater than ${exclusiveMinimum}`,\n      jsonSchema: { exclusiveMinimum },\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const GreaterThanOrEqualToSchemaId: unique symbol = schemaId_.GreaterThanOrEqualToSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type GreaterThanOrEqualToSchemaId = typeof GreaterThanOrEqualToSchemaId\n\n/**\n * This filter checks whether the provided number is greater than or equal to the specified minimum.\n *\n * @category number filters\n * @since 3.10.0\n */\nexport const greaterThanOrEqualTo = <S extends Schema.Any>(\n  minimum: number,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => a >= minimum, {\n      schemaId: GreaterThanOrEqualToSchemaId,\n      title: `greaterThanOrEqualTo(${minimum})`,\n      description: minimum === 0 ? \"a non-negative number\" : `a number greater than or equal to ${minimum}`,\n      jsonSchema: { minimum },\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const MultipleOfSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/MultipleOf\")\n\n/**\n * @category number filters\n * @since 3.10.0\n */\nexport const multipleOf = <S extends Schema.Any>(\n  divisor: number,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n  const positiveDivisor = Math.abs(divisor) // spec requires positive divisor\n  return self.pipe(\n    filter((a) => number_.remainder(a, divisor) === 0, {\n      schemaId: MultipleOfSchemaId,\n      title: `multipleOf(${positiveDivisor})`,\n      description: `a number divisible by ${positiveDivisor}`,\n      jsonSchema: { multipleOf: positiveDivisor },\n      ...annotations\n    })\n  )\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const IntSchemaId: unique symbol = schemaId_.IntSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type IntSchemaId = typeof IntSchemaId\n\n/**\n * Ensures that the provided value is an integer number (excluding NaN, +Infinity, and -Infinity).\n *\n * @category number filters\n * @since 3.10.0\n */\nexport const int =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => Number.isSafeInteger(a), {\n        schemaId: IntSchemaId,\n        title: \"int\",\n        description: \"an integer\",\n        jsonSchema: { type: \"integer\" },\n        ...annotations\n      })\n    )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LessThanSchemaId: unique symbol = schemaId_.LessThanSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type LessThanSchemaId = typeof LessThanSchemaId\n\n/**\n * This filter checks whether the provided number is less than the specified maximum.\n *\n * @category number filters\n * @since 3.10.0\n */\nexport const lessThan =\n  <S extends Schema.Any>(exclusiveMaximum: number, annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => a < exclusiveMaximum, {\n        schemaId: LessThanSchemaId,\n        title: `lessThan(${exclusiveMaximum})`,\n        description: exclusiveMaximum === 0 ? \"a negative number\" : `a number less than ${exclusiveMaximum}`,\n        jsonSchema: { exclusiveMaximum },\n        ...annotations\n      })\n    )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LessThanOrEqualToSchemaId: unique symbol = schemaId_.LessThanOrEqualToSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type LessThanOrEqualToSchemaId = typeof LessThanOrEqualToSchemaId\n\n/**\n * This schema checks whether the provided number is less than or equal to the specified maximum.\n *\n * @category number filters\n * @since 3.10.0\n */\nexport const lessThanOrEqualTo = <S extends Schema.Any>(\n  maximum: number,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => a <= maximum, {\n      schemaId: LessThanOrEqualToSchemaId,\n      title: `lessThanOrEqualTo(${maximum})`,\n      description: maximum === 0 ? \"a non-positive number\" : `a number less than or equal to ${maximum}`,\n      jsonSchema: { maximum },\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const BetweenSchemaId: unique symbol = schemaId_.BetweenSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type BetweenSchemaId = typeof BetweenSchemaId\n\n/**\n * This filter checks whether the provided number falls within the specified minimum and maximum values.\n *\n * @category number filters\n * @since 3.10.0\n */\nexport const between = <S extends Schema.Any>(\n  minimum: number,\n  maximum: number,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => a >= minimum && a <= maximum, {\n      schemaId: BetweenSchemaId,\n      title: `between(${minimum}, ${maximum})`,\n      description: `a number between ${minimum} and ${maximum}`,\n      jsonSchema: { minimum, maximum },\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const NonNaNSchemaId: unique symbol = schemaId_.NonNaNSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type NonNaNSchemaId = typeof NonNaNSchemaId\n\n/**\n * @category number filters\n * @since 3.10.0\n */\nexport const nonNaN =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => !Number.isNaN(a), {\n        schemaId: NonNaNSchemaId,\n        title: \"nonNaN\",\n        description: \"a number excluding NaN\",\n        ...annotations\n      })\n    )\n\n/**\n * @category number filters\n * @since 3.10.0\n */\nexport const positive = <S extends Schema.Any>(\n  annotations?: Annotations.Filter<Schema.Type<S>>\n): <A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>) => filter<S> =>\n  greaterThan(0, { title: \"positive\", ...annotations })\n\n/**\n * @category number filters\n * @since 3.10.0\n */\nexport const negative = <S extends Schema.Any>(\n  annotations?: Annotations.Filter<Schema.Type<S>>\n): <A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>) => filter<S> =>\n  lessThan(0, { title: \"negative\", ...annotations })\n\n/**\n * @category number filters\n * @since 3.10.0\n */\nexport const nonPositive = <S extends Schema.Any>(\n  annotations?: Annotations.Filter<Schema.Type<S>>\n): <A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>) => filter<S> =>\n  lessThanOrEqualTo(0, { title: \"nonPositive\", ...annotations })\n\n/**\n * @category number filters\n * @since 3.10.0\n */\nexport const nonNegative = <S extends Schema.Any>(\n  annotations?: Annotations.Filter<Schema.Type<S>>\n): <A extends number>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>) => filter<S> =>\n  greaterThanOrEqualTo(0, { title: \"nonNegative\", ...annotations })\n\n/**\n * Clamps a number between a minimum and a maximum value.\n *\n * @category number transformations\n * @since 3.10.0\n */\nexport const clamp = (minimum: number, maximum: number) =>\n<S extends Schema.Any, A extends number>(\n  self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>\n): transform<S, filter<SchemaClass<A>>> => {\n  return transform(\n    self,\n    typeSchema(self).pipe(between(minimum, maximum)),\n    {\n      strict: false,\n      decode: (i) => number_.clamp(i, { minimum, maximum }),\n      encode: identity\n    }\n  )\n}\n\n/**\n * Transforms a `string` into a `number` by parsing the string using the `parse`\n * function of the `effect/Number` module.\n *\n * It returns an error if the value can't be converted (for example when\n * non-numeric characters are provided).\n *\n * The following special string values are supported: \"NaN\", \"Infinity\",\n * \"-Infinity\".\n *\n * @category number transformations\n * @since 3.10.0\n */\nexport function parseNumber<S extends Schema.Any, A extends string>(\n  self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>\n): transformOrFail<S, typeof Number$> {\n  return transformOrFail(\n    self,\n    Number$,\n    {\n      strict: false,\n      decode: (i, _, ast) =>\n        ParseResult.fromOption(\n          number_.parse(i),\n          () => new ParseResult.Type(ast, i, `Unable to decode ${JSON.stringify(i)} into a number`)\n        ),\n      encode: (a) => ParseResult.succeed(String(a))\n    }\n  )\n}\n\n/**\n * This schema transforms a `string` into a `number` by parsing the string using the `parse` function of the `effect/Number` module.\n *\n * It returns an error if the value can't be converted (for example when non-numeric characters are provided).\n *\n * The following special string values are supported: \"NaN\", \"Infinity\", \"-Infinity\".\n *\n * @category number transformations\n * @since 3.10.0\n */\nexport class NumberFromString extends parseNumber(String$.annotations({\n  description: \"a string to be decoded into a number\"\n})).annotations({ identifier: \"NumberFromString\" }) {}\n\n/**\n * @category number constructors\n * @since 3.10.0\n */\nexport class Finite extends Number$.pipe(finite({ identifier: \"Finite\" })) {}\n\n/**\n * @category number constructors\n * @since 3.10.0\n */\nexport class Int extends Number$.pipe(int({ identifier: \"Int\" })) {}\n\n/**\n * @category number constructors\n * @since 3.10.0\n */\nexport class NonNaN extends Number$.pipe(nonNaN({ identifier: \"NonNaN\" })) {}\n\n/**\n * @category number constructors\n * @since 3.10.0\n */\nexport class Positive extends Number$.pipe(\n  positive({ identifier: \"Positive\" })\n) {}\n\n/**\n * @category number constructors\n * @since 3.10.0\n */\nexport class Negative extends Number$.pipe(\n  negative({ identifier: \"Negative\" })\n) {}\n\n/**\n * @category number constructors\n * @since 3.10.0\n */\nexport class NonPositive extends Number$.pipe(\n  nonPositive({ identifier: \"NonPositive\" })\n) {}\n\n/**\n * @category number constructors\n * @since 3.10.0\n */\nexport class NonNegative extends Number$.pipe(\n  nonNegative({ identifier: \"NonNegative\" })\n) {}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const JsonNumberSchemaId: unique symbol = schemaId_.JsonNumberSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type JsonNumberSchemaId = typeof JsonNumberSchemaId\n\n/**\n * The `JsonNumber` is a schema for representing JSON numbers. It ensures that the provided value is a valid\n * number by filtering out `NaN` and `(+/-) Infinity`. This is useful when you want to validate and represent numbers in JSON\n * format.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import * as Schema from \"effect/Schema\"\n *\n * const is = Schema.is(Schema.JsonNumber)\n *\n * assert.deepStrictEqual(is(42), true)\n * assert.deepStrictEqual(is(Number.NaN), false)\n * assert.deepStrictEqual(is(Number.POSITIVE_INFINITY), false)\n * assert.deepStrictEqual(is(Number.NEGATIVE_INFINITY), false)\n * ```\n *\n * @category number constructors\n * @since 3.10.0\n */\nexport class JsonNumber extends Number$.pipe(\n  finite({\n    schemaId: JsonNumberSchemaId,\n    identifier: \"JsonNumber\"\n  })\n) {}\n\n/**\n * @category boolean transformations\n * @since 3.10.0\n */\nexport class Not extends transform(Boolean$.annotations({ description: \"a boolean that will be negated\" }), Boolean$, {\n  strict: true,\n  decode: (i) => boolean_.not(i),\n  encode: (a) => boolean_.not(a)\n}) {}\n\nconst encodeSymbol = (sym: symbol, ast: AST.AST) => {\n  const key = Symbol.keyFor(sym)\n  return key === undefined\n    ? ParseResult.fail(\n      new ParseResult.Type(ast, sym, `Unable to encode a unique symbol ${String(sym)} into a string`)\n    )\n    : ParseResult.succeed(key)\n}\n\nconst decodeSymbol = (s: string) => ParseResult.succeed(Symbol.for(s))\n\n/** @ignore */\nclass Symbol$ extends transformOrFail(\n  String$.annotations({ description: \"a string to be decoded into a globally shared symbol\" }),\n  SymbolFromSelf,\n  {\n    strict: false,\n    decode: (i) => decodeSymbol(i),\n    encode: (a, _, ast) => encodeSymbol(a, ast)\n  }\n).annotations({ identifier: \"Symbol\" }) {}\n\nexport {\n  /**\n   * Converts a string key into a globally shared symbol.\n   *\n   * @category symbol transformations\n   * @since 3.10.0\n   */\n  Symbol$ as Symbol\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const GreaterThanBigIntSchemaId: unique symbol = schemaId_.GreaterThanBigintSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type GreaterThanBigIntSchemaId = typeof GreaterThanBigIntSchemaId\n\n/**\n * @category bigint filters\n * @since 3.10.0\n */\nexport const greaterThanBigInt = <S extends Schema.Any>(\n  min: bigint,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends bigint>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => a > min, {\n      schemaId: GreaterThanBigIntSchemaId,\n      [GreaterThanBigIntSchemaId]: { min },\n      title: `greaterThanBigInt(${min})`,\n      description: min === 0n ? \"a positive bigint\" : `a bigint greater than ${min}n`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const GreaterThanOrEqualToBigIntSchemaId: unique symbol = schemaId_.GreaterThanOrEqualToBigIntSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type GreaterThanOrEqualToBigIntSchemaId = typeof GreaterThanOrEqualToBigIntSchemaId\n\n/**\n * @category bigint filters\n * @since 3.10.0\n */\nexport const greaterThanOrEqualToBigInt = <S extends Schema.Any>(\n  min: bigint,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends bigint>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => a >= min, {\n      schemaId: GreaterThanOrEqualToBigIntSchemaId,\n      [GreaterThanOrEqualToBigIntSchemaId]: { min },\n      title: `greaterThanOrEqualToBigInt(${min})`,\n      description: min === 0n\n        ? \"a non-negative bigint\"\n        : `a bigint greater than or equal to ${min}n`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LessThanBigIntSchemaId: unique symbol = schemaId_.LessThanBigIntSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type LessThanBigIntSchemaId = typeof LessThanBigIntSchemaId\n\n/**\n * @category bigint filters\n * @since 3.10.0\n */\nexport const lessThanBigInt = <S extends Schema.Any>(\n  max: bigint,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends bigint>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => a < max, {\n      schemaId: LessThanBigIntSchemaId,\n      [LessThanBigIntSchemaId]: { max },\n      title: `lessThanBigInt(${max})`,\n      description: max === 0n ? \"a negative bigint\" : `a bigint less than ${max}n`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LessThanOrEqualToBigIntSchemaId: unique symbol = schemaId_.LessThanOrEqualToBigIntSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type LessThanOrEqualToBigIntSchemaId = typeof LessThanOrEqualToBigIntSchemaId\n\n/**\n * @category bigint filters\n * @since 3.10.0\n */\nexport const lessThanOrEqualToBigInt = <S extends Schema.Any>(\n  max: bigint,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends bigint>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => a <= max, {\n      schemaId: LessThanOrEqualToBigIntSchemaId,\n      [LessThanOrEqualToBigIntSchemaId]: { max },\n      title: `lessThanOrEqualToBigInt(${max})`,\n      description: max === 0n ? \"a non-positive bigint\" : `a bigint less than or equal to ${max}n`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const BetweenBigIntSchemaId: unique symbol = schemaId_.BetweenBigintSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type BetweenBigIntSchemaId = typeof BetweenBigIntSchemaId\n\n/**\n * @category bigint filters\n * @since 3.10.0\n */\nexport const betweenBigInt = <S extends Schema.Any>(\n  min: bigint,\n  max: bigint,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends bigint>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => a >= min && a <= max, {\n      schemaId: BetweenBigIntSchemaId,\n      [BetweenBigIntSchemaId]: { min, max },\n      title: `betweenBigInt(${min}, ${max})`,\n      description: `a bigint between ${min}n and ${max}n`,\n      ...annotations\n    })\n  )\n\n/**\n * @category bigint filters\n * @since 3.10.0\n */\nexport const positiveBigInt = <S extends Schema.Any>(\n  annotations?: Annotations.Filter<Schema.Type<S>>\n): <A extends bigint>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>) => filter<S> =>\n  greaterThanBigInt(0n, { title: \"positiveBigInt\", ...annotations })\n\n/**\n * @category bigint filters\n * @since 3.10.0\n */\nexport const negativeBigInt = <S extends Schema.Any>(\n  annotations?: Annotations.Filter<Schema.Type<S>>\n): <A extends bigint>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>) => filter<S> =>\n  lessThanBigInt(0n, { title: \"negativeBigInt\", ...annotations })\n\n/**\n * @category bigint filters\n * @since 3.10.0\n */\nexport const nonNegativeBigInt = <S extends Schema.Any>(\n  annotations?: Annotations.Filter<Schema.Type<S>>\n): <A extends bigint>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>) => filter<S> =>\n  greaterThanOrEqualToBigInt(0n, { title: \"nonNegativeBigInt\", ...annotations })\n\n/**\n * @category bigint filters\n * @since 3.10.0\n */\nexport const nonPositiveBigInt = <S extends Schema.Any>(\n  annotations?: Annotations.Filter<Schema.Type<S>>\n): <A extends bigint>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>) => filter<S> =>\n  lessThanOrEqualToBigInt(0n, { title: \"nonPositiveBigInt\", ...annotations })\n\n/**\n * Clamps a bigint between a minimum and a maximum value.\n *\n * @category bigint transformations\n * @since 3.10.0\n */\nexport const clampBigInt = (minimum: bigint, maximum: bigint) =>\n<S extends Schema.Any, A extends bigint>(\n  self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>\n): transform<S, filter<SchemaClass<A>>> =>\n  transform(\n    self,\n    self.pipe(typeSchema, betweenBigInt(minimum, maximum)),\n    {\n      strict: false,\n      decode: (i) => bigInt_.clamp(i, { minimum, maximum }),\n      encode: identity\n    }\n  )\n\n/** @ignore */\nclass BigInt$ extends transformOrFail(\n  String$.annotations({ description: \"a string to be decoded into a bigint\" }),\n  BigIntFromSelf,\n  {\n    strict: true,\n    decode: (i, _, ast) =>\n      ParseResult.fromOption(\n        bigInt_.fromString(i),\n        () => new ParseResult.Type(ast, i, `Unable to decode ${JSON.stringify(i)} into a bigint`)\n      ),\n    encode: (a) => ParseResult.succeed(String(a))\n  }\n).annotations({ identifier: \"BigInt\" }) {}\n\nexport {\n  /**\n   * This schema transforms a `string` into a `bigint` by parsing the string using the `BigInt` function.\n   *\n   * It returns an error if the value can't be converted (for example when non-numeric characters are provided).\n   *\n   * @category bigint transformations\n   * @since 3.10.0\n   */\n  BigInt$ as BigInt\n}\n\n/**\n * @category bigint constructors\n * @since 3.10.0\n */\nexport const PositiveBigIntFromSelf: filter<Schema<bigint>> = BigIntFromSelf.pipe(\n  positiveBigInt({ identifier: \"PositiveBigintFromSelf\" })\n)\n\n/**\n * @category bigint constructors\n * @since 3.10.0\n */\nexport const PositiveBigInt: filter<Schema<bigint, string>> = BigInt$.pipe(\n  positiveBigInt({ identifier: \"PositiveBigint\" })\n)\n\n/**\n * @category bigint constructors\n * @since 3.10.0\n */\nexport const NegativeBigIntFromSelf: filter<Schema<bigint>> = BigIntFromSelf.pipe(\n  negativeBigInt({ identifier: \"NegativeBigintFromSelf\" })\n)\n\n/**\n * @category bigint constructors\n * @since 3.10.0\n */\nexport const NegativeBigInt: filter<Schema<bigint, string>> = BigInt$.pipe(\n  negativeBigInt({ identifier: \"NegativeBigint\" })\n)\n\n/**\n * @category bigint constructors\n * @since 3.10.0\n */\nexport const NonPositiveBigIntFromSelf: filter<Schema<bigint>> = BigIntFromSelf.pipe(\n  nonPositiveBigInt({ identifier: \"NonPositiveBigintFromSelf\" })\n)\n\n/**\n * @category bigint constructors\n * @since 3.10.0\n */\nexport const NonPositiveBigInt: filter<Schema<bigint, string>> = BigInt$.pipe(\n  nonPositiveBigInt({ identifier: \"NonPositiveBigint\" })\n)\n\n/**\n * @category bigint constructors\n * @since 3.10.0\n */\nexport const NonNegativeBigIntFromSelf: filter<Schema<bigint>> = BigIntFromSelf.pipe(\n  nonNegativeBigInt({ identifier: \"NonNegativeBigintFromSelf\" })\n)\n\n/**\n * @category bigint constructors\n * @since 3.10.0\n */\nexport const NonNegativeBigInt: filter<Schema<bigint, string>> = BigInt$.pipe(\n  nonNegativeBigInt({ identifier: \"NonNegativeBigint\" })\n)\n\n/**\n * This schema transforms a `number` into a `bigint` by parsing the number using the `BigInt` function.\n *\n * It returns an error if the value can't be safely encoded as a `number` due to being out of range.\n *\n * @category bigint transformations\n * @since 3.10.0\n */\nexport class BigIntFromNumber extends transformOrFail(\n  Number$.annotations({ description: \"a number to be decoded into a bigint\" }),\n  BigIntFromSelf.pipe(betweenBigInt(BigInt(Number.MIN_SAFE_INTEGER), BigInt(Number.MAX_SAFE_INTEGER))),\n  {\n    strict: true,\n    decode: (i, _, ast) =>\n      ParseResult.fromOption(\n        bigInt_.fromNumber(i),\n        () => new ParseResult.Type(ast, i, `Unable to decode ${i} into a bigint`)\n      ),\n    encode: (a, _, ast) =>\n      ParseResult.fromOption(\n        bigInt_.toNumber(a),\n        () => new ParseResult.Type(ast, a, `Unable to encode ${a}n into a number`)\n      )\n  }\n).annotations({ identifier: \"BigIntFromNumber\" }) {}\n\nconst redactedArbitrary = <A>(value: LazyArbitrary<A>): LazyArbitrary<redacted_.Redacted<A>> => (fc) =>\n  value(fc).map(redacted_.make)\n\nconst toComposite = <A, R, B>(\n  eff: Effect.Effect<A, ParseResult.ParseIssue, R>,\n  onSuccess: (a: A) => B,\n  ast: AST.AST,\n  actual: unknown\n): Effect.Effect<B, ParseResult.Composite, R> =>\n  ParseResult.mapBoth(eff, {\n    onFailure: (e) => new ParseResult.Composite(ast, actual, e),\n    onSuccess\n  })\n\nconst redactedParse = <A, R>(\n  decodeUnknown: ParseResult.DecodeUnknown<A, R>\n): ParseResult.DeclarationDecodeUnknown<redacted_.Redacted<A>, R> =>\n(u, options, ast) =>\n  redacted_.isRedacted(u) ?\n    toComposite(decodeUnknown(redacted_.value(u), options), redacted_.make, ast, u) :\n    ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface RedactedFromSelf<Value extends Schema.Any> extends\n  AnnotableDeclare<\n    RedactedFromSelf<Value>,\n    redacted_.Redacted<Schema.Type<Value>>,\n    redacted_.Redacted<Schema.Encoded<Value>>,\n    [Value]\n  >\n{}\n\n/**\n * @category Redacted constructors\n * @since 3.10.0\n */\nexport const RedactedFromSelf = <Value extends Schema.Any>(value: Value): RedactedFromSelf<Value> =>\n  declare(\n    [value],\n    {\n      decode: (value) => redactedParse(ParseResult.decodeUnknown(value)),\n      encode: (value) => redactedParse(ParseResult.encodeUnknown(value))\n    },\n    {\n      typeConstructor: { _tag: \"effect/Redacted\" },\n      description: \"Redacted(<redacted>)\",\n      pretty: () => () => \"Redacted(<redacted>)\",\n      arbitrary: redactedArbitrary,\n      equivalence: redacted_.getEquivalence\n    }\n  )\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Redacted<Value extends Schema.Any>\n  extends transform<Value, RedactedFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * A transformation that transform a `Schema<A, I, R>` into a\n * `RedactedFromSelf<A>`.\n *\n * @category Redacted transformations\n * @since 3.10.0\n */\nexport function Redacted<Value extends Schema.Any>(value: Value): Redacted<Value> {\n  return transform(\n    value,\n    RedactedFromSelf(typeSchema(asSchema(value))),\n    {\n      strict: true,\n      decode: (i) => redacted_.make(i),\n      encode: (a) => redacted_.value(a)\n    }\n  )\n}\n\n/**\n * @category Duration constructors\n * @since 3.10.0\n */\nexport class DurationFromSelf extends declare(\n  duration_.isDuration,\n  {\n    typeConstructor: { _tag: \"effect/Duration\" },\n    identifier: \"DurationFromSelf\",\n    pretty: (): pretty_.Pretty<duration_.Duration> => String,\n    arbitrary: (): LazyArbitrary<duration_.Duration> => (fc) =>\n      fc.oneof(\n        fc.constant(duration_.infinity),\n        fc.bigInt({ min: 0n }).map((_) => duration_.nanos(_)),\n        fc.maxSafeNat().map((_) => duration_.millis(_))\n      ),\n    equivalence: (): Equivalence.Equivalence<duration_.Duration> => duration_.Equivalence\n  }\n) {}\n\n/**\n * A schema that transforms a non negative `bigint` into a `Duration`. Treats\n * the value as the number of nanoseconds.\n *\n * @category Duration transformations\n * @since 3.10.0\n */\nexport class DurationFromNanos extends transformOrFail(\n  NonNegativeBigIntFromSelf.annotations({ description: \"a bigint to be decoded into a Duration\" }),\n  DurationFromSelf.pipe(filter((duration) => duration_.isFinite(duration), { description: \"a finite duration\" })),\n  {\n    strict: true,\n    decode: (i) => ParseResult.succeed(duration_.nanos(i)),\n    encode: (a, _, ast) =>\n      option_.match(duration_.toNanos(a), {\n        onNone: () => ParseResult.fail(new ParseResult.Type(ast, a, `Unable to encode ${a} into a bigint`)),\n        onSome: (nanos) => ParseResult.succeed(nanos)\n      })\n  }\n).annotations({ identifier: \"DurationFromNanos\" }) {}\n\n/**\n * A non-negative integer. +Infinity is excluded.\n *\n * @category number constructors\n * @since 3.11.10\n */\nexport const NonNegativeInt = NonNegative.pipe(int()).annotations({ identifier: \"NonNegativeInt\" })\n\n/**\n * A schema that transforms a (possibly Infinite) non negative number into a\n * `Duration`. Treats the value as the number of milliseconds.\n *\n * @category Duration transformations\n * @since 3.10.0\n */\nexport class DurationFromMillis extends transform(\n  NonNegative.annotations({\n    description: \"a non-negative number to be decoded into a Duration\"\n  }),\n  DurationFromSelf,\n  {\n    strict: true,\n    decode: (i) => duration_.millis(i),\n    encode: (a) => duration_.toMillis(a)\n  }\n).annotations({ identifier: \"DurationFromMillis\" }) {}\n\nconst DurationValueMillis = TaggedStruct(\"Millis\", { millis: NonNegativeInt })\nconst DurationValueNanos = TaggedStruct(\"Nanos\", { nanos: BigInt$ })\nconst DurationValueInfinity = TaggedStruct(\"Infinity\", {})\nconst durationValueInfinity = DurationValueInfinity.make({})\n\n/**\n * @category Duration utils\n * @since 3.12.8\n */\nexport type DurationEncoded =\n  | {\n    readonly _tag: \"Millis\"\n    readonly millis: number\n  }\n  | {\n    readonly _tag: \"Nanos\"\n    readonly nanos: string\n  }\n  | {\n    readonly _tag: \"Infinity\"\n  }\n\nconst DurationValue: Schema<duration_.DurationValue, DurationEncoded> = Union(\n  DurationValueMillis,\n  DurationValueNanos,\n  DurationValueInfinity\n).annotations({\n  identifier: \"DurationValue\",\n  description: \"an JSON-compatible tagged union to be decoded into a Duration\"\n})\n\nconst FiniteHRTime = Tuple(\n  element(NonNegativeInt).annotations({ title: \"seconds\" }),\n  element(NonNegativeInt).annotations({ title: \"nanos\" })\n).annotations({ identifier: \"FiniteHRTime\" })\n\nconst InfiniteHRTime = Tuple(Literal(-1), Literal(0)).annotations({ identifier: \"InfiniteHRTime\" })\n\nconst HRTime: Schema<readonly [seconds: number, nanos: number]> = Union(FiniteHRTime, InfiniteHRTime).annotations({\n  identifier: \"HRTime\",\n  description: \"a tuple of seconds and nanos to be decoded into a Duration\"\n})\n\nconst isDurationValue = (u: duration_.DurationValue | typeof HRTime.Type): u is duration_.DurationValue =>\n  typeof u === \"object\"\n\n// TODO(4.0): remove HRTime union member\n/**\n * A schema that converts a JSON-compatible tagged union into a `Duration`.\n *\n * @category Duration transformations\n * @since 3.10.0\n */\nexport class Duration extends transform(\n  Union(DurationValue, HRTime),\n  DurationFromSelf,\n  {\n    strict: true,\n    decode: (i) => {\n      if (isDurationValue(i)) {\n        switch (i._tag) {\n          case \"Millis\":\n            return duration_.millis(i.millis)\n          case \"Nanos\":\n            return duration_.nanos(i.nanos)\n          case \"Infinity\":\n            return duration_.infinity\n        }\n      }\n      const [seconds, nanos] = i\n      return seconds === -1 ? duration_.infinity : duration_.nanos(BigInt(seconds) * BigInt(1e9) + BigInt(nanos))\n    },\n    encode: (a) => {\n      switch (a.value._tag) {\n        case \"Millis\":\n          return DurationValueMillis.make({ millis: a.value.millis })\n        case \"Nanos\":\n          return DurationValueNanos.make({ nanos: a.value.nanos })\n        case \"Infinity\":\n          return durationValueInfinity\n      }\n    }\n  }\n).annotations({ identifier: \"Duration\" }) {}\n\n/**\n * Clamps a `Duration` between a minimum and a maximum value.\n *\n * @category Duration transformations\n * @since 3.10.0\n */\nexport const clampDuration =\n  (minimum: duration_.DurationInput, maximum: duration_.DurationInput) =>\n  <S extends Schema.Any, A extends duration_.Duration>(\n    self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>\n  ): transform<S, filter<SchemaClass<A>>> =>\n    transform(\n      self,\n      self.pipe(typeSchema, betweenDuration(minimum, maximum)),\n      {\n        strict: false,\n        decode: (i) => duration_.clamp(i, { minimum, maximum }),\n        encode: identity\n      }\n    )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LessThanDurationSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/LessThanDuration\")\n\n/**\n * @category Duration filters\n * @since 3.10.0\n */\nexport const lessThanDuration = <S extends Schema.Any>(\n  max: duration_.DurationInput,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends duration_.Duration>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => duration_.lessThan(a, max), {\n      schemaId: LessThanDurationSchemaId,\n      [LessThanDurationSchemaId]: { max },\n      title: `lessThanDuration(${max})`,\n      description: `a Duration less than ${duration_.decode(max)}`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LessThanOrEqualToDurationSchemaId: unique symbol = Symbol.for(\n  \"effect/schema/LessThanOrEqualToDuration\"\n)\n\n/**\n * @category Duration filters\n * @since 3.10.0\n */\nexport const lessThanOrEqualToDuration = <S extends Schema.Any>(\n  max: duration_.DurationInput,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends duration_.Duration>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => duration_.lessThanOrEqualTo(a, max), {\n      schemaId: LessThanDurationSchemaId,\n      [LessThanDurationSchemaId]: { max },\n      title: `lessThanOrEqualToDuration(${max})`,\n      description: `a Duration less than or equal to ${duration_.decode(max)}`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const GreaterThanDurationSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/GreaterThanDuration\")\n\n/**\n * @category Duration filters\n * @since 3.10.0\n */\nexport const greaterThanDuration = <S extends Schema.Any>(\n  min: duration_.DurationInput,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends duration_.Duration>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => duration_.greaterThan(a, min), {\n      schemaId: GreaterThanDurationSchemaId,\n      [GreaterThanDurationSchemaId]: { min },\n      title: `greaterThanDuration(${min})`,\n      description: `a Duration greater than ${duration_.decode(min)}`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const GreaterThanOrEqualToDurationSchemaId: unique symbol = Symbol.for(\n  \"effect/schema/GreaterThanOrEqualToDuration\"\n)\n\n/**\n * @category Duration filters\n * @since 3.10.0\n */\nexport const greaterThanOrEqualToDuration = <S extends Schema.Any>(\n  min: duration_.DurationInput,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends duration_.Duration>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => duration_.greaterThanOrEqualTo(a, min), {\n      schemaId: GreaterThanOrEqualToDurationSchemaId,\n      [GreaterThanOrEqualToDurationSchemaId]: { min },\n      title: `greaterThanOrEqualToDuration(${min})`,\n      description: `a Duration greater than or equal to ${duration_.decode(min)}`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const BetweenDurationSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/BetweenDuration\")\n\n/**\n * @category Duration filters\n * @since 3.10.0\n */\nexport const betweenDuration = <S extends Schema.Any>(\n  minimum: duration_.DurationInput,\n  maximum: duration_.DurationInput,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends duration_.Duration>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a) => duration_.between(a, { minimum, maximum }), {\n      schemaId: BetweenDurationSchemaId,\n      [BetweenDurationSchemaId]: { maximum, minimum },\n      title: `betweenDuration(${minimum}, ${maximum})`,\n      description: `a Duration between ${duration_.decode(minimum)} and ${duration_.decode(maximum)}`,\n      ...annotations\n    })\n  )\n\n/**\n * @category Uint8Array constructors\n * @since 3.10.0\n */\nexport class Uint8ArrayFromSelf extends declare(\n  Predicate.isUint8Array,\n  {\n    typeConstructor: { _tag: \"Uint8Array\" },\n    identifier: \"Uint8ArrayFromSelf\",\n    pretty: (): pretty_.Pretty<Uint8Array> => (u8arr) => `new Uint8Array(${JSON.stringify(Array.from(u8arr))})`,\n    arbitrary: (): LazyArbitrary<Uint8Array> => (fc) => fc.uint8Array(),\n    equivalence: (): Equivalence.Equivalence<Uint8Array> => array_.getEquivalence(Equal.equals) as any\n  }\n) {}\n\n/**\n * @category number constructors\n * @since 3.11.10\n */\nexport class Uint8 extends Number$.pipe(\n  between(0, 255, {\n    identifier: \"Uint8\",\n    description: \"a 8-bit unsigned integer\"\n  })\n) {}\n\n/** @ignore */\nclass Uint8Array$ extends transform(\n  Array$(Uint8).annotations({\n    description: \"an array of 8-bit unsigned integers to be decoded into a Uint8Array\"\n  }),\n  Uint8ArrayFromSelf,\n  {\n    strict: true,\n    decode: (i) => Uint8Array.from(i),\n    encode: (a) => Array.from(a)\n  }\n).annotations({ identifier: \"Uint8Array\" }) {}\n\nexport {\n  /**\n   * A schema that transforms an array of numbers into a `Uint8Array`.\n   *\n   * @category Uint8Array transformations\n   * @since 3.10.0\n   */\n  Uint8Array$ as Uint8Array\n}\n\nconst makeUint8ArrayTransformation = (\n  id: string,\n  decode: (s: string) => either_.Either<Uint8Array, Encoding.DecodeException>,\n  encode: (u: Uint8Array) => string\n) =>\n  transformOrFail(\n    String$.annotations({ description: \"a string to be decoded into a Uint8Array\" }),\n    Uint8ArrayFromSelf,\n    {\n      strict: true,\n      decode: (i, _, ast) =>\n        either_.mapLeft(\n          decode(i),\n          (decodeException) => new ParseResult.Type(ast, i, decodeException.message)\n        ),\n      encode: (a) => ParseResult.succeed(encode(a))\n    }\n  ).annotations({ identifier: id })\n\n/**\n * Decodes a base64 (RFC4648) encoded string into a `Uint8Array`.\n *\n * @category Uint8Array transformations\n * @since 3.10.0\n */\nexport const Uint8ArrayFromBase64: Schema<Uint8Array, string> = makeUint8ArrayTransformation(\n  \"Uint8ArrayFromBase64\",\n  Encoding.decodeBase64,\n  Encoding.encodeBase64\n)\n\n/**\n * Decodes a base64 (URL) encoded string into a `Uint8Array`.\n *\n * @category Uint8Array transformations\n * @since 3.10.0\n */\nexport const Uint8ArrayFromBase64Url: Schema<Uint8Array, string> = makeUint8ArrayTransformation(\n  \"Uint8ArrayFromBase64Url\",\n  Encoding.decodeBase64Url,\n  Encoding.encodeBase64Url\n)\n\n/**\n * Decodes a hex encoded string into a `Uint8Array`.\n *\n * @category Uint8Array transformations\n * @since 3.10.0\n */\nexport const Uint8ArrayFromHex: Schema<Uint8Array, string> = makeUint8ArrayTransformation(\n  \"Uint8ArrayFromHex\",\n  Encoding.decodeHex,\n  Encoding.encodeHex\n)\n\nconst makeEncodingTransformation = (\n  id: string,\n  decode: (s: string) => either_.Either<string, Encoding.DecodeException>,\n  encode: (u: string) => string\n) =>\n  transformOrFail(\n    String$.annotations({\n      description: `A string that is interpreted as being ${id}-encoded and will be decoded into a UTF-8 string`\n    }),\n    String$,\n    {\n      strict: true,\n      decode: (i, _, ast) =>\n        either_.mapLeft(\n          decode(i),\n          (decodeException) => new ParseResult.Type(ast, i, decodeException.message)\n        ),\n      encode: (a) => ParseResult.succeed(encode(a))\n    }\n  ).annotations({ identifier: `StringFrom${id}` })\n\n/**\n * Decodes a base64 (RFC4648) encoded string into a UTF-8 string.\n *\n * @category string transformations\n * @since 3.10.0\n */\nexport const StringFromBase64: Schema<string> = makeEncodingTransformation(\n  \"Base64\",\n  Encoding.decodeBase64String,\n  Encoding.encodeBase64\n)\n\n/**\n * Decodes a base64 (URL) encoded string into a UTF-8 string.\n *\n * @category string transformations\n * @since 3.10.0\n */\nexport const StringFromBase64Url: Schema<string> = makeEncodingTransformation(\n  \"Base64Url\",\n  Encoding.decodeBase64UrlString,\n  Encoding.encodeBase64Url\n)\n\n/**\n * Decodes a hex encoded string into a UTF-8 string.\n *\n * @category string transformations\n * @since 3.10.0\n */\nexport const StringFromHex: Schema<string> = makeEncodingTransformation(\n  \"Hex\",\n  Encoding.decodeHexString,\n  Encoding.encodeHex\n)\n\n/**\n * Decodes a URI component encoded string into a UTF-8 string.\n * Can be used to store data in a URL.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n *\n * const PaginationSchema = Schema.Struct({\n *   maxItemPerPage: Schema.Number,\n *   page: Schema.Number\n * })\n *\n * const UrlSchema = Schema.compose(Schema.StringFromUriComponent, Schema.parseJson(PaginationSchema))\n *\n * console.log(Schema.encodeSync(UrlSchema)({ maxItemPerPage: 10, page: 1 }))\n * // Output: %7B%22maxItemPerPage%22%3A10%2C%22page%22%3A1%7D\n * ```\n *\n * @category string transformations\n * @since 3.12.0\n */\nexport const StringFromUriComponent = transformOrFail(\n  String$.annotations({\n    description: `A string that is interpreted as being UriComponent-encoded and will be decoded into a UTF-8 string`\n  }),\n  String$,\n  {\n    strict: true,\n    decode: (i, _, ast) =>\n      either_.mapLeft(\n        Encoding.decodeUriComponent(i),\n        (decodeException) => new ParseResult.Type(ast, i, decodeException.message)\n      ),\n    encode: (a, _, ast) =>\n      either_.mapLeft(\n        Encoding.encodeUriComponent(a),\n        (encodeException) => new ParseResult.Type(ast, a, encodeException.message)\n      )\n  }\n).annotations({ identifier: `StringFromUriComponent` })\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const MinItemsSchemaId: unique symbol = schemaId_.MinItemsSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type MinItemsSchemaId = typeof MinItemsSchemaId\n\n/**\n * @category ReadonlyArray filters\n * @since 3.10.0\n */\nexport const minItems = <S extends Schema.Any>(\n  n: number,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends ReadonlyArray<any>>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n  const minItems = Math.floor(n)\n  if (minItems < 1) {\n    throw new Error(\n      errors_.getInvalidArgumentErrorMessage(`Expected an integer greater than or equal to 1, actual ${n}`)\n    )\n  }\n  return self.pipe(\n    filter(\n      (a) => a.length >= minItems,\n      {\n        schemaId: MinItemsSchemaId,\n        title: `minItems(${minItems})`,\n        description: `an array of at least ${minItems} item(s)`,\n        jsonSchema: { minItems },\n        [AST.StableFilterAnnotationId]: true,\n        ...annotations\n      }\n    )\n  )\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const MaxItemsSchemaId: unique symbol = schemaId_.MaxItemsSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type MaxItemsSchemaId = typeof MaxItemsSchemaId\n\n/**\n * @category ReadonlyArray filters\n * @since 3.10.0\n */\nexport const maxItems = <S extends Schema.Any>(\n  n: number,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends ReadonlyArray<any>>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n  const maxItems = Math.floor(n)\n  if (maxItems < 1) {\n    throw new Error(\n      errors_.getInvalidArgumentErrorMessage(`Expected an integer greater than or equal to 1, actual ${n}`)\n    )\n  }\n  return self.pipe(\n    filter((a) => a.length <= maxItems, {\n      schemaId: MaxItemsSchemaId,\n      title: `maxItems(${maxItems})`,\n      description: `an array of at most ${maxItems} item(s)`,\n      jsonSchema: { maxItems },\n      [AST.StableFilterAnnotationId]: true,\n      ...annotations\n    })\n  )\n}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const ItemsCountSchemaId: unique symbol = schemaId_.ItemsCountSchemaId\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport type ItemsCountSchemaId = typeof ItemsCountSchemaId\n\n/**\n * @category ReadonlyArray filters\n * @since 3.10.0\n */\nexport const itemsCount = <S extends Schema.Any>(\n  n: number,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends ReadonlyArray<any>>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n  const itemsCount = Math.floor(n)\n  if (itemsCount < 0) {\n    throw new Error(\n      errors_.getInvalidArgumentErrorMessage(`Expected an integer greater than or equal to 0, actual ${n}`)\n    )\n  }\n  return self.pipe(\n    filter((a) => a.length === itemsCount, {\n      schemaId: ItemsCountSchemaId,\n      title: `itemsCount(${itemsCount})`,\n      description: `an array of exactly ${itemsCount} item(s)`,\n      jsonSchema: { minItems: itemsCount, maxItems: itemsCount },\n      [AST.StableFilterAnnotationId]: true,\n      ...annotations\n    })\n  )\n}\n\n/**\n * @category ReadonlyArray transformations\n * @since 3.10.0\n */\nexport const getNumberIndexedAccess = <A extends ReadonlyArray<any>, I extends ReadonlyArray<any>, R>(\n  self: Schema<A, I, R>\n): SchemaClass<A[number], I[number], R> => make(AST.getNumberIndexedAccess(self.ast))\n\n/**\n * Get the first element of a `ReadonlyArray`, or `None` if the array is empty.\n *\n * @category ReadonlyArray transformations\n * @since 3.10.0\n */\nexport function head<S extends Schema.Any, A extends ReadonlyArray<unknown>>(\n  self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>\n): transform<S, OptionFromSelf<SchemaClass<A[number]>>> {\n  return transform(\n    self,\n    OptionFromSelf(getNumberIndexedAccess(typeSchema(self))),\n    {\n      strict: false,\n      decode: (i) => array_.head(i),\n      encode: (a) =>\n        option_.match(a, {\n          onNone: () => [],\n          onSome: array_.of\n        })\n    }\n  )\n}\n\n/**\n * Get the first element of a `NonEmptyReadonlyArray`.\n *\n * @category NonEmptyReadonlyArray transformations\n * @since 3.12.0\n */\nexport function headNonEmpty<S extends Schema.Any, A extends array_.NonEmptyReadonlyArray<unknown>>(\n  self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>\n): transform<S, SchemaClass<A[number]>> {\n  return transform(\n    self,\n    getNumberIndexedAccess(typeSchema(self)),\n    {\n      strict: false,\n      decode: (i) => array_.headNonEmpty(i),\n      encode: (a) => array_.of(a)\n    }\n  )\n}\n\n/**\n * Retrieves the first element of a `ReadonlyArray`.\n *\n * If the array is empty, it returns the `fallback` argument if provided; otherwise, it fails.\n *\n * @category ReadonlyArray transformations\n * @since 3.10.0\n */\nexport const headOrElse: {\n  <S extends Schema.Any, A extends ReadonlyArray<unknown>>(\n    fallback?: LazyArg<A[number]>\n  ): (\n    self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>\n  ) => transform<S, SchemaClass<A[number]>>\n  <S extends Schema.Any, A extends ReadonlyArray<unknown>>(\n    self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>,\n    fallback?: LazyArg<A[number]>\n  ): transform<S, SchemaClass<A[number]>>\n} = dual(\n  (args) => isSchema(args[0]),\n  <A, I, R>(\n    self: Schema<ReadonlyArray<A>, I, R>,\n    fallback?: LazyArg<A>\n  ): transform<Schema<ReadonlyArray<A>, I, R>, SchemaClass<A>> =>\n    transformOrFail(\n      self,\n      getNumberIndexedAccess(typeSchema(self)),\n      {\n        strict: true,\n        decode: (i, _, ast) =>\n          i.length > 0\n            ? ParseResult.succeed(i[0])\n            : fallback\n            ? ParseResult.succeed(fallback())\n            : ParseResult.fail(new ParseResult.Type(ast, i, \"Unable to retrieve the first element of an empty array\")),\n        encode: (a) => ParseResult.succeed(array_.of(a))\n      }\n    )\n)\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const ValidDateSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/ValidDate\")\n\n/**\n * Defines a filter that specifically rejects invalid dates, such as `new\n * Date(\"Invalid Date\")`. This filter ensures that only properly formatted and\n * valid date objects are accepted, enhancing data integrity by preventing\n * erroneous date values from being processed.\n *\n * @category Date filters\n * @since 3.10.0\n */\nexport const validDate =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends Date>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => !Number.isNaN(a.getTime()), {\n        schemaId: ValidDateSchemaId,\n        [ValidDateSchemaId]: { noInvalidDate: true },\n        title: \"validDate\",\n        description: \"a valid Date\",\n        ...annotations\n      })\n    )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LessThanDateSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/LessThanDate\")\n\n/**\n * @category Date filters\n * @since 3.10.0\n */\nexport const lessThanDate = <S extends Schema.Any>(\n  max: Date,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends Date>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a: Date) => a < max, {\n      schemaId: LessThanDateSchemaId,\n      [LessThanDateSchemaId]: { max },\n      title: `lessThanDate(${Inspectable.formatDate(max)})`,\n      description: `a date before ${Inspectable.formatDate(max)}`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LessThanOrEqualToDateSchemaId: unique symbol = Symbol.for(\n  \"effect/schema/LessThanOrEqualToDate\"\n)\n\n/**\n * @category Date filters\n * @since 3.10.0\n */\nexport const lessThanOrEqualToDate = <S extends Schema.Any>(\n  max: Date,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends Date>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a: Date) => a <= max, {\n      schemaId: LessThanOrEqualToDateSchemaId,\n      [LessThanOrEqualToDateSchemaId]: { max },\n      title: `lessThanOrEqualToDate(${Inspectable.formatDate(max)})`,\n      description: `a date before or equal to ${Inspectable.formatDate(max)}`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const GreaterThanDateSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/GreaterThanDate\")\n\n/**\n * @category Date filters\n * @since 3.10.0\n */\nexport const greaterThanDate = <S extends Schema.Any>(\n  min: Date,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends Date>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a: Date) => a > min, {\n      schemaId: GreaterThanDateSchemaId,\n      [GreaterThanDateSchemaId]: { min },\n      title: `greaterThanDate(${Inspectable.formatDate(min)})`,\n      description: `a date after ${Inspectable.formatDate(min)}`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const GreaterThanOrEqualToDateSchemaId: unique symbol = Symbol.for(\n  \"effect/schema/GreaterThanOrEqualToDate\"\n)\n\n/**\n * @category Date filters\n * @since 3.10.0\n */\nexport const greaterThanOrEqualToDate = <S extends Schema.Any>(\n  min: Date,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends Date>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a: Date) => a >= min, {\n      schemaId: GreaterThanOrEqualToDateSchemaId,\n      [GreaterThanOrEqualToDateSchemaId]: { min },\n      title: `greaterThanOrEqualToDate(${Inspectable.formatDate(min)})`,\n      description: `a date after or equal to ${Inspectable.formatDate(min)}`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const BetweenDateSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/BetweenDate\")\n\n/**\n * @category Date filters\n * @since 3.10.0\n */\nexport const betweenDate = <S extends Schema.Any>(\n  min: Date,\n  max: Date,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends Date>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n  self.pipe(\n    filter((a: Date) => a <= max && a >= min, {\n      schemaId: BetweenDateSchemaId,\n      [BetweenDateSchemaId]: { max, min },\n      title: `betweenDate(${Inspectable.formatDate(min)}, ${Inspectable.formatDate(max)})`,\n      description: `a date between ${Inspectable.formatDate(min)} and ${Inspectable.formatDate(max)}`,\n      ...annotations\n    })\n  )\n\n/**\n * @category schema id\n * @since 3.11.8\n */\nexport const DateFromSelfSchemaId: unique symbol = schemaId_.DateFromSelfSchemaId\n\n/**\n * @category schema id\n * @since 3.11.8\n */\nexport type DateFromSelfSchemaId = typeof DateFromSelfSchemaId\n\n/**\n * Describes a schema that accommodates potentially invalid `Date` instances,\n * such as `new Date(\"Invalid Date\")`, without rejection.\n *\n * @category Date constructors\n * @since 3.10.0\n */\nexport class DateFromSelf extends declare(\n  Predicate.isDate,\n  {\n    typeConstructor: { _tag: \"Date\" },\n    identifier: \"DateFromSelf\",\n    schemaId: DateFromSelfSchemaId,\n    [DateFromSelfSchemaId]: { noInvalidDate: false },\n    description: \"a potentially invalid Date instance\",\n    pretty: () => (date) => `new Date(${JSON.stringify(date)})`,\n    arbitrary: () => (fc) => fc.date({ noInvalidDate: false }),\n    equivalence: () => Equivalence.Date\n  }\n) {}\n\n/**\n * Defines a schema that ensures only valid dates are accepted. This schema\n * rejects values like `new Date(\"Invalid Date\")`, which, despite being a `Date`\n * instance, represents an invalid date. Such stringent validation ensures that\n * all date objects processed through this schema are properly formed and\n * represent real dates.\n *\n * @category Date constructors\n * @since 3.10.0\n */\nexport class ValidDateFromSelf extends DateFromSelf.pipe(\n  validDate({\n    identifier: \"ValidDateFromSelf\",\n    description: \"a valid Date instance\"\n  })\n) {}\n\n/**\n * Defines a schema that attempts to convert a `string` to a `Date` object using\n * the `new Date` constructor. This conversion is lenient, meaning it does not\n * reject strings that do not form valid dates (e.g., using `new Date(\"Invalid\n * Date\")` results in a `Date` object, despite being invalid).\n *\n * @category Date transformations\n * @since 3.10.0\n */\nexport class DateFromString extends transform(\n  String$.annotations({ description: \"a string to be decoded into a Date\" }),\n  DateFromSelf,\n  {\n    strict: true,\n    decode: (i) => new Date(i),\n    encode: (a) => Inspectable.formatDate(a)\n  }\n).annotations({ identifier: \"DateFromString\" }) {}\n\n/** @ignore */\nclass Date$ extends DateFromString.pipe(\n  validDate({ identifier: \"Date\" })\n) {}\n\nexport {\n  /**\n   * This schema converts a `string` into a `Date` object using the `new Date`\n   * constructor. It ensures that only valid date strings are accepted,\n   * rejecting any strings that would result in an invalid date, such as `new\n   * Date(\"Invalid Date\")`.\n   *\n   * @category Date transformations\n   * @since 3.10.0\n   */\n  Date$ as Date\n}\n\n/**\n * Defines a schema that converts a `number` into a `Date` object using the `new\n * Date` constructor. This schema does not validate the numerical input,\n * allowing potentially invalid values such as `NaN`, `Infinity`, and\n * `-Infinity` to be converted into `Date` objects. During the encoding process,\n * any invalid `Date` object will be encoded to `NaN`.\n *\n * @category Date transformations\n * @since 3.10.0\n */\nexport class DateFromNumber extends transform(\n  Number$.annotations({ description: \"a number to be decoded into a Date\" }),\n  DateFromSelf,\n  {\n    strict: true,\n    decode: (i) => new Date(i),\n    encode: (a) => a.getTime()\n  }\n).annotations({ identifier: \"DateFromNumber\" }) {}\n\n/**\n * Describes a schema that represents a `DateTime.Utc` instance.\n *\n * @category DateTime.Utc constructors\n * @since 3.10.0\n */\nexport class DateTimeUtcFromSelf extends declare(\n  (u) => dateTime.isDateTime(u) && dateTime.isUtc(u),\n  {\n    typeConstructor: { _tag: \"effect/DateTime.Utc\" },\n    identifier: \"DateTimeUtcFromSelf\",\n    description: \"a DateTime.Utc instance\",\n    pretty: (): pretty_.Pretty<dateTime.Utc> => (dateTime) => dateTime.toString(),\n    arbitrary: (): LazyArbitrary<dateTime.Utc> => (fc) =>\n      fc.date({ noInvalidDate: true }).map((date) => dateTime.unsafeFromDate(date)),\n    equivalence: () => dateTime.Equivalence\n  }\n) {}\n\nconst decodeDateTimeUtc = <A extends dateTime.DateTime.Input>(input: A, ast: AST.AST) =>\n  ParseResult.try({\n    try: () => dateTime.unsafeMake(input),\n    catch: () =>\n      new ParseResult.Type(ast, input, `Unable to decode ${Inspectable.formatUnknown(input)} into a DateTime.Utc`)\n  })\n\n/**\n * Defines a schema that attempts to convert a `number` to a `DateTime.Utc` instance using the `DateTime.unsafeMake` constructor.\n *\n * @category DateTime.Utc transformations\n * @since 3.10.0\n */\nexport class DateTimeUtcFromNumber extends transformOrFail(\n  Number$.annotations({ description: \"a number to be decoded into a DateTime.Utc\" }),\n  DateTimeUtcFromSelf,\n  {\n    strict: true,\n    decode: (i, _, ast) => decodeDateTimeUtc(i, ast),\n    encode: (a) => ParseResult.succeed(dateTime.toEpochMillis(a))\n  }\n).annotations({ identifier: \"DateTimeUtcFromNumber\" }) {}\n\n/**\n * Defines a schema that attempts to convert a `Date` to a `DateTime.Utc` instance using the `DateTime.unsafeMake` constructor.\n *\n * @category DateTime.Utc transformations\n * @since 3.12.0\n */\nexport class DateTimeUtcFromDate extends transformOrFail(\n  DateFromSelf.annotations({ description: \"a Date to be decoded into a DateTime.Utc\" }),\n  DateTimeUtcFromSelf,\n  {\n    strict: true,\n    decode: (i, _, ast) => decodeDateTimeUtc(i, ast),\n    encode: (a) => ParseResult.succeed(dateTime.toDateUtc(a))\n  }\n).annotations({ identifier: \"DateTimeUtcFromDate\" }) {}\n\n/**\n * Defines a schema that attempts to convert a `string` to a `DateTime.Utc` instance using the `DateTime.unsafeMake` constructor.\n *\n * @category DateTime.Utc transformations\n * @since 3.10.0\n */\nexport class DateTimeUtc extends transformOrFail(\n  String$.annotations({ description: \"a string to be decoded into a DateTime.Utc\" }),\n  DateTimeUtcFromSelf,\n  {\n    strict: true,\n    decode: (i, _, ast) => decodeDateTimeUtc(i, ast),\n    encode: (a) => ParseResult.succeed(dateTime.formatIso(a))\n  }\n).annotations({ identifier: \"DateTimeUtc\" }) {}\n\nconst timeZoneOffsetArbitrary = (): LazyArbitrary<dateTime.TimeZone.Offset> => (fc) =>\n  fc.integer({ min: -12 * 60 * 60 * 1000, max: 14 * 60 * 60 * 1000 }).map(dateTime.zoneMakeOffset)\n\n/**\n * Describes a schema that represents a `TimeZone.Offset` instance.\n *\n * @category TimeZone constructors\n * @since 3.10.0\n */\nexport class TimeZoneOffsetFromSelf extends declare(\n  dateTime.isTimeZoneOffset,\n  {\n    typeConstructor: { _tag: \"effect/DateTime.TimeZone.Offset\" },\n    identifier: \"TimeZoneOffsetFromSelf\",\n    description: \"a TimeZone.Offset instance\",\n    pretty: (): pretty_.Pretty<dateTime.TimeZone.Offset> => (zone) => zone.toString(),\n    arbitrary: timeZoneOffsetArbitrary\n  }\n) {}\n\n/**\n * Defines a schema that converts a `number` to a `TimeZone.Offset` instance using the `DateTime.zoneMakeOffset` constructor.\n *\n * @category TimeZone transformations\n * @since 3.10.0\n */\nexport class TimeZoneOffset extends transform(\n  Number$.annotations({ description: \"a number to be decoded into a TimeZone.Offset\" }),\n  TimeZoneOffsetFromSelf,\n  {\n    strict: true,\n    decode: (i) => dateTime.zoneMakeOffset(i),\n    encode: (a) => a.offset\n  }\n).annotations({ identifier: \"TimeZoneOffset\" }) {}\n\nconst timeZoneNamedArbitrary = (): LazyArbitrary<dateTime.TimeZone.Named> => (fc) =>\n  fc.constantFrom(...Intl.supportedValuesOf(\"timeZone\")).map(dateTime.zoneUnsafeMakeNamed)\n\n/**\n * Describes a schema that represents a `TimeZone.Named` instance.\n *\n * @category TimeZone constructors\n * @since 3.10.0\n */\nexport class TimeZoneNamedFromSelf extends declare(\n  dateTime.isTimeZoneNamed,\n  {\n    typeConstructor: { _tag: \"effect/DateTime.TimeZone.Named\" },\n    identifier: \"TimeZoneNamedFromSelf\",\n    description: \"a TimeZone.Named instance\",\n    pretty: (): pretty_.Pretty<dateTime.TimeZone.Named> => (zone) => zone.toString(),\n    arbitrary: timeZoneNamedArbitrary\n  }\n) {}\n\n/**\n * Defines a schema that attempts to convert a `string` to a `TimeZone.Named` instance using the `DateTime.zoneUnsafeMakeNamed` constructor.\n *\n * @category TimeZone transformations\n * @since 3.10.0\n */\nexport class TimeZoneNamed extends transformOrFail(\n  String$.annotations({ description: \"a string to be decoded into a TimeZone.Named\" }),\n  TimeZoneNamedFromSelf,\n  {\n    strict: true,\n    decode: (i, _, ast) =>\n      ParseResult.try({\n        try: () => dateTime.zoneUnsafeMakeNamed(i),\n        catch: () => new ParseResult.Type(ast, i, `Unable to decode ${JSON.stringify(i)} into a TimeZone.Named`)\n      }),\n    encode: (a) => ParseResult.succeed(a.id)\n  }\n).annotations({ identifier: \"TimeZoneNamed\" }) {}\n\n/**\n * @category TimeZone constructors\n * @since 3.10.0\n */\nexport class TimeZoneFromSelf extends Union(TimeZoneOffsetFromSelf, TimeZoneNamedFromSelf) {}\n\n/**\n * Defines a schema that attempts to convert a `string` to a `TimeZone` using the `DateTime.zoneFromString` constructor.\n *\n * @category TimeZone transformations\n * @since 3.10.0\n */\nexport class TimeZone extends transformOrFail(\n  String$.annotations({ description: \"a string to be decoded into a TimeZone\" }),\n  TimeZoneFromSelf,\n  {\n    strict: true,\n    decode: (i, _, ast) =>\n      option_.match(dateTime.zoneFromString(i), {\n        onNone: () =>\n          ParseResult.fail(new ParseResult.Type(ast, i, `Unable to decode ${JSON.stringify(i)} into a TimeZone`)),\n        onSome: ParseResult.succeed\n      }),\n    encode: (a) => ParseResult.succeed(dateTime.zoneToString(a))\n  }\n).annotations({ identifier: \"TimeZone\" }) {}\n\nconst timeZoneArbitrary: LazyArbitrary<dateTime.TimeZone> = (fc) =>\n  fc.oneof(\n    timeZoneOffsetArbitrary()(fc),\n    timeZoneNamedArbitrary()(fc)\n  )\n\n/**\n * Describes a schema that represents a `DateTime.Zoned` instance.\n *\n * @category DateTime.Zoned constructors\n * @since 3.10.0\n */\nexport class DateTimeZonedFromSelf extends declare(\n  (u) => dateTime.isDateTime(u) && dateTime.isZoned(u),\n  {\n    typeConstructor: { _tag: \"effect/DateTime.Zoned\" },\n    identifier: \"DateTimeZonedFromSelf\",\n    description: \"a DateTime.Zoned instance\",\n    pretty: (): pretty_.Pretty<dateTime.Zoned> => (dateTime) => dateTime.toString(),\n    arbitrary: (): LazyArbitrary<dateTime.Zoned> => (fc) =>\n      fc.tuple(\n        fc.integer({\n          // time zone db supports +/- 1000 years or so\n          min: -31536000000000,\n          max: 31536000000000\n        }),\n        timeZoneArbitrary(fc)\n      ).map(([millis, timeZone]) => dateTime.unsafeMakeZoned(millis, { timeZone })),\n    equivalence: () => dateTime.Equivalence\n  }\n) {}\n\n/**\n * Defines a schema that attempts to convert a `string` to a `DateTime.Zoned` instance.\n *\n * @category DateTime.Zoned transformations\n * @since 3.10.0\n */\nexport class DateTimeZoned extends transformOrFail(\n  String$.annotations({ description: \"a string to be decoded into a DateTime.Zoned\" }),\n  DateTimeZonedFromSelf,\n  {\n    strict: true,\n    decode: (i, _, ast) =>\n      option_.match(dateTime.makeZonedFromString(i), {\n        onNone: () =>\n          ParseResult.fail(new ParseResult.Type(ast, i, `Unable to decode ${JSON.stringify(i)} into a DateTime.Zoned`)),\n        onSome: ParseResult.succeed\n      }),\n    encode: (a) => ParseResult.succeed(dateTime.formatIsoZoned(a))\n  }\n).annotations({ identifier: \"DateTimeZoned\" }) {}\n\n/**\n * @category Option utils\n * @since 3.10.0\n */\nexport type OptionEncoded<I> =\n  | {\n    readonly _tag: \"None\"\n  }\n  | {\n    readonly _tag: \"Some\"\n    readonly value: I\n  }\n\nconst OptionNoneEncoded = Struct({\n  _tag: Literal(\"None\")\n}).annotations({ description: \"NoneEncoded\" })\n\nconst optionSomeEncoded = <Value extends Schema.Any>(value: Value) =>\n  Struct({\n    _tag: Literal(\"Some\"),\n    value\n  }).annotations({ description: `SomeEncoded<${format(value)}>` })\n\nconst optionEncoded = <Value extends Schema.Any>(value: Value) =>\n  Union(\n    OptionNoneEncoded,\n    optionSomeEncoded(value)\n  ).annotations({\n    description: `OptionEncoded<${format(value)}>`\n  })\n\nconst optionDecode = <A>(input: OptionEncoded<A>): option_.Option<A> =>\n  input._tag === \"None\" ? option_.none() : option_.some(input.value)\n\nconst optionArbitrary =\n  <A>(value: LazyArbitrary<A>, ctx: ArbitraryGenerationContext): LazyArbitrary<option_.Option<A>> => (fc) =>\n    fc.oneof(\n      ctx,\n      fc.record({ _tag: fc.constant(\"None\" as const) }),\n      fc.record({ _tag: fc.constant(\"Some\" as const), value: value(fc) })\n    ).map(optionDecode)\n\nconst optionPretty = <A>(value: pretty_.Pretty<A>): pretty_.Pretty<option_.Option<A>> =>\n  option_.match({\n    onNone: () => \"none()\",\n    onSome: (a) => `some(${value(a)})`\n  })\n\nconst optionParse =\n  <A, R>(decodeUnknown: ParseResult.DecodeUnknown<A, R>): ParseResult.DeclarationDecodeUnknown<option_.Option<A>, R> =>\n  (u, options, ast) =>\n    option_.isOption(u) ?\n      option_.isNone(u) ?\n        ParseResult.succeed(option_.none())\n        : toComposite(decodeUnknown(u.value, options), option_.some, ast, u)\n      : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface OptionFromSelf<Value extends Schema.Any> extends\n  AnnotableDeclare<\n    OptionFromSelf<Value>,\n    option_.Option<Schema.Type<Value>>,\n    option_.Option<Schema.Encoded<Value>>,\n    [Value]\n  >\n{}\n\nconst OptionFromSelf_ = <Value extends Schema.Any>(value: Value): OptionFromSelf<Value> => {\n  return declare(\n    [value],\n    {\n      decode: (value) => optionParse(ParseResult.decodeUnknown(value)),\n      encode: (value) => optionParse(ParseResult.encodeUnknown(value))\n    },\n    {\n      typeConstructor: { _tag: \"effect/Option\" },\n      pretty: optionPretty,\n      arbitrary: optionArbitrary,\n      equivalence: option_.getEquivalence\n    }\n  )\n}\n\n/**\n * @category Option transformations\n * @since 3.10.0\n */\nexport const OptionFromSelf = <Value extends Schema.Any>(value: Value): OptionFromSelf<Value> => {\n  return OptionFromSelf_(value).annotations({ description: `Option<${format(value)}>` })\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Option<Value extends Schema.Any> extends\n  transform<\n    Union<[\n      Struct<{ _tag: Literal<[\"None\"]> }>,\n      Struct<{ _tag: Literal<[\"Some\"]>; value: Value }>\n    ]>,\n    OptionFromSelf<SchemaClass<Schema.Type<Value>>>\n  >\n{}\n\nconst makeNoneEncoded = {\n  _tag: \"None\"\n} as const\n\nconst makeSomeEncoded = <A>(value: A) => ({\n  _tag: \"Some\",\n  value\n} as const)\n\n/**\n * @category Option transformations\n * @since 3.10.0\n */\nexport function Option<Value extends Schema.Any>(value: Value): Option<Value> {\n  const value_ = asSchema(value)\n  const out = transform(\n    optionEncoded(value_),\n    OptionFromSelf(typeSchema(value_)),\n    {\n      strict: true,\n      decode: (i) => optionDecode(i),\n      encode: (a) =>\n        option_.match(a, {\n          onNone: () => makeNoneEncoded,\n          onSome: makeSomeEncoded\n        })\n    }\n  )\n  return out as any\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface OptionFromNullOr<Value extends Schema.Any>\n  extends transform<NullOr<Value>, OptionFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category Option transformations\n * @since 3.10.0\n */\nexport function OptionFromNullOr<Value extends Schema.Any>(value: Value): OptionFromNullOr<Value> {\n  return transform(NullOr(value), OptionFromSelf(typeSchema(asSchema(value))), {\n    strict: true,\n    decode: (i) => option_.fromNullable(i),\n    encode: (a) => option_.getOrNull(a)\n  })\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface OptionFromNullishOr<Value extends Schema.Any>\n  extends transform<NullishOr<Value>, OptionFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category Option transformations\n * @since 3.10.0\n */\nexport function OptionFromNullishOr<Value extends Schema.Any>(\n  value: Value,\n  onNoneEncoding: null | undefined\n): OptionFromNullishOr<Value> {\n  return transform(\n    NullishOr(value),\n    OptionFromSelf(typeSchema(asSchema(value))),\n    {\n      strict: true,\n      decode: (i) => option_.fromNullable(i),\n      encode: onNoneEncoding === null ?\n        (a) => option_.getOrNull(a) :\n        (a) => option_.getOrUndefined(a)\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface OptionFromUndefinedOr<Value extends Schema.Any>\n  extends transform<UndefinedOr<Value>, OptionFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category Option transformations\n * @since 3.10.0\n */\nexport function OptionFromUndefinedOr<Value extends Schema.Any>(value: Value): OptionFromUndefinedOr<Value> {\n  return transform(UndefinedOr(value), OptionFromSelf(typeSchema(asSchema(value))), {\n    strict: true,\n    decode: (i) => option_.fromNullable(i),\n    encode: (a) => option_.getOrUndefined(a)\n  })\n}\n\n/**\n * Transforms strings into an Option type, effectively filtering out empty or\n * whitespace-only strings by trimming them and checking their length. Returns\n * `none` for invalid inputs and `some` for valid non-empty strings.\n *\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n *\n * console.log(Schema.decodeSync(Schema.OptionFromNonEmptyTrimmedString)(\"\")) // Option.none()\n * console.log(Schema.decodeSync(Schema.OptionFromNonEmptyTrimmedString)(\" a \")) // Option.some(\"a\")\n * console.log(Schema.decodeSync(Schema.OptionFromNonEmptyTrimmedString)(\"a\")) // Option.some(\"a\")\n * ```\n *\n * @category Option transformations\n * @since 3.10.0\n */\nexport class OptionFromNonEmptyTrimmedString extends transform(String$, OptionFromSelf(NonEmptyTrimmedString), {\n  strict: true,\n  decode: (i) => option_.filter(option_.some(i.trim()), string_.isNonEmpty),\n  encode: (a) => option_.getOrElse(a, () => \"\")\n}) {}\n\n/**\n * @category Either utils\n * @since 3.10.0\n */\nexport type RightEncoded<IA> = {\n  readonly _tag: \"Right\"\n  readonly right: IA\n}\n\n/**\n * @category Either utils\n * @since 3.10.0\n */\nexport type LeftEncoded<IE> = {\n  readonly _tag: \"Left\"\n  readonly left: IE\n}\n\n/**\n * @category Either utils\n * @since 3.10.0\n */\nexport type EitherEncoded<IR, IL> = RightEncoded<IR> | LeftEncoded<IL>\n\nconst rightEncoded = <Right extends Schema.All>(right: Right) =>\n  Struct({\n    _tag: Literal(\"Right\"),\n    right\n  }).annotations({ description: `RightEncoded<${format(right)}>` })\n\nconst leftEncoded = <Left extends Schema.All>(left: Left) =>\n  Struct({\n    _tag: Literal(\"Left\"),\n    left\n  }).annotations({ description: `LeftEncoded<${format(left)}>` })\n\nconst eitherEncoded = <Right extends Schema.All, Left extends Schema.All>(\n  right: Right,\n  left: Left\n) =>\n  Union(rightEncoded(right), leftEncoded(left)).annotations({\n    description: `EitherEncoded<${format(left)}, ${format(right)}>`\n  })\n\nconst eitherDecode = <R, L>(input: EitherEncoded<R, L>): either_.Either<R, L> =>\n  input._tag === \"Left\" ? either_.left(input.left) : either_.right(input.right)\n\nconst eitherArbitrary = <R, L>(\n  right: LazyArbitrary<R>,\n  left: LazyArbitrary<L>\n): LazyArbitrary<either_.Either<R, L>> =>\n(fc) =>\n  fc.oneof(\n    fc.record({ _tag: fc.constant(\"Left\" as const), left: left(fc) }),\n    fc.record({ _tag: fc.constant(\"Right\" as const), right: right(fc) })\n  ).map(eitherDecode)\n\nconst eitherPretty = <R, L>(\n  right: pretty_.Pretty<R>,\n  left: pretty_.Pretty<L>\n): pretty_.Pretty<either_.Either<R, L>> =>\n  either_.match({\n    onLeft: (e) => `left(${left(e)})`,\n    onRight: (a) => `right(${right(a)})`\n  })\n\nconst eitherParse = <RR, R, LR, L>(\n  parseRight: ParseResult.DecodeUnknown<R, RR>,\n  decodeUnknownLeft: ParseResult.DecodeUnknown<L, LR>\n): ParseResult.DeclarationDecodeUnknown<either_.Either<R, L>, LR | RR> =>\n(u, options, ast) =>\n  either_.isEither(u) ?\n    either_.match(u, {\n      onLeft: (left) => toComposite(decodeUnknownLeft(left, options), either_.left, ast, u),\n      onRight: (right) => toComposite(parseRight(right, options), either_.right, ast, u)\n    })\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface EitherFromSelf<R extends Schema.All, L extends Schema.All> extends\n  AnnotableDeclare<\n    EitherFromSelf<R, L>,\n    either_.Either<Schema.Type<R>, Schema.Type<L>>,\n    either_.Either<Schema.Encoded<R>, Schema.Encoded<L>>,\n    [R, L]\n  >\n{}\n\n/**\n * @category Either transformations\n * @since 3.10.0\n */\nexport const EitherFromSelf = <R extends Schema.All, L extends Schema.All>({ left, right }: {\n  readonly left: L\n  readonly right: R\n}): EitherFromSelf<R, L> => {\n  return declare(\n    [right, left],\n    {\n      decode: (right, left) => eitherParse(ParseResult.decodeUnknown(right), ParseResult.decodeUnknown(left)),\n      encode: (right, left) => eitherParse(ParseResult.encodeUnknown(right), ParseResult.encodeUnknown(left))\n    },\n    {\n      typeConstructor: { _tag: \"effect/Either\" },\n      description: `Either<${format(right)}, ${format(left)}>`,\n      pretty: eitherPretty,\n      arbitrary: eitherArbitrary,\n      equivalence: (right, left) => either_.getEquivalence({ left, right })\n    }\n  )\n}\n\nconst makeLeftEncoded = <E>(left: E) => (({\n  _tag: \"Left\",\n  left\n}) as const)\nconst makeRightEncoded = <A>(right: A) => (({\n  _tag: \"Right\",\n  right\n}) as const)\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Either<Right extends Schema.All, Left extends Schema.All> extends\n  transform<\n    Union<[\n      Struct<{\n        _tag: Literal<[\"Right\"]>\n        right: Right\n      }>,\n      Struct<{\n        _tag: Literal<[\"Left\"]>\n        left: Left\n      }>\n    ]>,\n    EitherFromSelf<SchemaClass<Schema.Type<Right>>, SchemaClass<Schema.Type<Left>>>\n  >\n{}\n\n/**\n * @category Either transformations\n * @since 3.10.0\n */\nexport const Either = <R extends Schema.All, L extends Schema.All>({ left, right }: {\n  readonly left: L\n  readonly right: R\n}): Either<R, L> => {\n  const right_ = asSchema(right)\n  const left_ = asSchema(left)\n  const out = transform(\n    eitherEncoded(right_, left_),\n    EitherFromSelf({ left: typeSchema(left_), right: typeSchema(right_) }),\n    {\n      strict: true,\n      decode: (i) => eitherDecode(i),\n      encode: (a) =>\n        either_.match(a, {\n          onLeft: makeLeftEncoded,\n          onRight: makeRightEncoded\n        })\n    }\n  )\n  return out as any\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface EitherFromUnion<Right extends Schema.All, Left extends Schema.All> extends\n  transform<\n    Union<[\n      transform<Right, Struct<{ _tag: Literal<[\"Right\"]>; right: SchemaClass<Schema.Type<Right>> }>>,\n      transform<Left, Struct<{ _tag: Literal<[\"Left\"]>; right: SchemaClass<Schema.Type<Left>> }>>\n    ]>,\n    EitherFromSelf<SchemaClass<Schema.Type<Right>>, SchemaClass<Schema.Type<Left>>>\n  >\n{}\n\n/**\n * @example\n * ```ts\n * import * as Schema from \"effect/Schema\"\n *\n * // Schema<string | number, Either<string, number>>\n * Schema.EitherFromUnion({ left: Schema.String, right: Schema.Number })\n * ```\n *\n * @category Either transformations\n * @since 3.10.0\n */\nexport const EitherFromUnion = <Right extends Schema.All, Left extends Schema.All>({ left, right }: {\n  readonly left: Left\n  readonly right: Right\n}): EitherFromUnion<Right, Left> => {\n  const right_ = asSchema(right)\n  const left_ = asSchema(left)\n  const toright = typeSchema(right_)\n  const toleft = typeSchema(left_)\n  const fromRight = transform(right_, rightEncoded(toright), {\n    strict: true,\n    decode: (i) => makeRightEncoded(i),\n    encode: (a) => a.right\n  })\n  const fromLeft = transform(left_, leftEncoded(toleft), {\n    strict: true,\n    decode: (i) => makeLeftEncoded(i),\n    encode: (a) => a.left\n  })\n  const out = transform(\n    Union(fromRight, fromLeft),\n    EitherFromSelf({ left: toleft, right: toright }),\n    {\n      strict: true,\n      decode: (i) => i._tag === \"Left\" ? either_.left(i.left) : either_.right(i.right),\n      encode: (a) =>\n        either_.match(a, {\n          onLeft: makeLeftEncoded,\n          onRight: makeRightEncoded\n        })\n    }\n  )\n  return out as any\n}\n\nconst mapArbitrary = <K, V>(\n  key: LazyArbitrary<K>,\n  value: LazyArbitrary<V>,\n  ctx: ArbitraryGenerationContext\n): LazyArbitrary<Map<K, V>> => {\n  return (fc) => {\n    const items = fc.array(fc.tuple(key(fc), value(fc)))\n    return (ctx.depthIdentifier !== undefined ? fc.oneof(ctx, fc.constant([]), items) : items).map((as) => new Map(as))\n  }\n}\n\nconst readonlyMapPretty = <K, V>(\n  key: pretty_.Pretty<K>,\n  value: pretty_.Pretty<V>\n): pretty_.Pretty<ReadonlyMap<K, V>> =>\n(map) =>\n  `new Map([${\n    Array.from(map.entries())\n      .map(([k, v]) => `[${key(k)}, ${value(v)}]`)\n      .join(\", \")\n  }])`\n\nconst readonlyMapEquivalence = <K, V>(\n  key: Equivalence.Equivalence<K>,\n  value: Equivalence.Equivalence<V>\n): Equivalence.Equivalence<ReadonlyMap<K, V>> => {\n  const arrayEquivalence = array_.getEquivalence(\n    Equivalence.make<[K, V]>(([ka, va], [kb, vb]) => key(ka, kb) && value(va, vb))\n  )\n  return Equivalence.make((a, b) => arrayEquivalence(Array.from(a.entries()), Array.from(b.entries())))\n}\n\nconst readonlyMapParse = <R, K, V>(\n  decodeUnknown: ParseResult.DecodeUnknown<ReadonlyArray<readonly [K, V]>, R>\n): ParseResult.DeclarationDecodeUnknown<ReadonlyMap<K, V>, R> =>\n(u, options, ast) =>\n  Predicate.isMap(u) ?\n    toComposite(decodeUnknown(Array.from(u.entries()), options), (as) => new Map(as), ast, u)\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface ReadonlyMapFromSelf<K extends Schema.Any, V extends Schema.Any> extends\n  AnnotableDeclare<\n    ReadonlyMapFromSelf<K, V>,\n    ReadonlyMap<Schema.Type<K>, Schema.Type<V>>,\n    ReadonlyMap<Schema.Encoded<K>, Schema.Encoded<V>>,\n    [K, V]\n  >\n{}\n\nconst mapFromSelf_ = <K extends Schema.Any, V extends Schema.Any>(\n  key: K,\n  value: V,\n  description: string\n): ReadonlyMapFromSelf<K, V> =>\n  declare(\n    [key, value],\n    {\n      decode: (Key, Value) => readonlyMapParse(ParseResult.decodeUnknown(Array$(Tuple(Key, Value)))),\n      encode: (Key, Value) => readonlyMapParse(ParseResult.encodeUnknown(Array$(Tuple(Key, Value))))\n    },\n    {\n      typeConstructor: { _tag: \"ReadonlyMap\" },\n      description,\n      pretty: readonlyMapPretty,\n      arbitrary: mapArbitrary,\n      equivalence: readonlyMapEquivalence\n    }\n  )\n\n/**\n * @category ReadonlyMap\n * @since 3.10.0\n */\nexport const ReadonlyMapFromSelf = <K extends Schema.Any, V extends Schema.Any>({ key, value }: {\n  readonly key: K\n  readonly value: V\n}): ReadonlyMapFromSelf<K, V> => mapFromSelf_(key, value, `ReadonlyMap<${format(key)}, ${format(value)}>`)\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface MapFromSelf<K extends Schema.Any, V extends Schema.Any> extends\n  AnnotableDeclare<\n    MapFromSelf<K, V>,\n    Map<Schema.Type<K>, Schema.Type<V>>,\n    ReadonlyMap<Schema.Encoded<K>, Schema.Encoded<V>>,\n    [K, V]\n  >\n{}\n\n/**\n * @category Map\n * @since 3.10.0\n */\nexport const MapFromSelf = <K extends Schema.Any, V extends Schema.Any>({ key, value }: {\n  readonly key: K\n  readonly value: V\n}): MapFromSelf<K, V> => mapFromSelf_(key, value, `Map<${format(key)}, ${format(value)}>`) as any\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface ReadonlyMap$<K extends Schema.Any, V extends Schema.Any>\n  extends transform<Array$<Tuple2<K, V>>, ReadonlyMapFromSelf<SchemaClass<Schema.Type<K>>, SchemaClass<Schema.Type<V>>>>\n{}\n\n/**\n * @category ReadonlyMap transformations\n * @since 3.10.0\n */\nexport function ReadonlyMap<K extends Schema.Any, V extends Schema.Any>({ key, value }: {\n  readonly key: K\n  readonly value: V\n}): ReadonlyMap$<K, V> {\n  return transform(\n    Array$(Tuple(key, value)),\n    ReadonlyMapFromSelf({ key: typeSchema(asSchema(key)), value: typeSchema(asSchema(value)) }),\n    {\n      strict: true,\n      decode: (i) => new Map(i),\n      encode: (a) => Array.from(a.entries())\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Map$<K extends Schema.Any, V extends Schema.Any>\n  extends transform<Array$<Tuple2<K, V>>, MapFromSelf<SchemaClass<Schema.Type<K>>, SchemaClass<Schema.Type<V>>>>\n{}\n\n/** @ignore */\nfunction map<K extends Schema.Any, V extends Schema.Any>({ key, value }: {\n  readonly key: K\n  readonly value: V\n}): Map$<K, V> {\n  return transform(\n    Array$(Tuple(key, value)),\n    MapFromSelf({ key: typeSchema(asSchema(key)), value: typeSchema(asSchema(value)) }),\n    {\n      strict: true,\n      decode: (i) => new Map(i),\n      encode: (a) => Array.from(a.entries())\n    }\n  )\n}\n\nexport {\n  /**\n   * @category Map transformations\n   * @since 3.10.0\n   */\n  map as Map\n}\n\n/**\n * @category ReadonlyMap transformations\n * @since 3.10.0\n */\nexport const ReadonlyMapFromRecord = <KA, KR, VA, VI, VR>({ key, value }: {\n  key: Schema<KA, string, KR>\n  value: Schema<VA, VI, VR>\n}): SchemaClass<ReadonlyMap<KA, VA>, { readonly [x: string]: VI }, KR | VR> =>\n  transform(\n    Record({ key: encodedBoundSchema(key), value }).annotations({\n      description: \"a record to be decoded into a ReadonlyMap\"\n    }),\n    ReadonlyMapFromSelf({ key, value: typeSchema(value) }),\n    {\n      strict: true,\n      decode: (i) => new Map(Object.entries(i)),\n      encode: (a) => Object.fromEntries(a)\n    }\n  )\n\n/**\n * @category Map transformations\n * @since 3.10.0\n */\nexport const MapFromRecord = <KA, KR, VA, VI, VR>({ key, value }: {\n  key: Schema<KA, string, KR>\n  value: Schema<VA, VI, VR>\n}): SchemaClass<Map<KA, VA>, { readonly [x: string]: VI }, KR | VR> =>\n  transform(\n    Record({ key: encodedBoundSchema(key), value }).annotations({\n      description: \"a record to be decoded into a Map\"\n    }),\n    MapFromSelf({ key, value: typeSchema(value) }),\n    {\n      strict: true,\n      decode: (i) => new Map(Object.entries(i)),\n      encode: (a) => Object.fromEntries(a)\n    }\n  )\n\nconst setArbitrary =\n  <A>(item: LazyArbitrary<A>, ctx: ArbitraryGenerationContext): LazyArbitrary<ReadonlySet<A>> => (fc) => {\n    const items = fc.array(item(fc))\n    return (ctx.depthIdentifier !== undefined ? fc.oneof(ctx, fc.constant([]), items) : items).map((as) => new Set(as))\n  }\n\nconst readonlySetPretty = <A>(item: pretty_.Pretty<A>): pretty_.Pretty<ReadonlySet<A>> => (set) =>\n  `new Set([${Array.from(set.values()).map((a) => item(a)).join(\", \")}])`\n\nconst readonlySetEquivalence = <A>(\n  item: Equivalence.Equivalence<A>\n): Equivalence.Equivalence<ReadonlySet<A>> => {\n  const arrayEquivalence = array_.getEquivalence(item)\n  return Equivalence.make((a, b) => arrayEquivalence(Array.from(a.values()), Array.from(b.values())))\n}\n\nconst readonlySetParse = <A, R>(\n  decodeUnknown: ParseResult.DecodeUnknown<ReadonlyArray<A>, R>\n): ParseResult.DeclarationDecodeUnknown<ReadonlySet<A>, R> =>\n(u, options, ast) =>\n  Predicate.isSet(u) ?\n    toComposite(decodeUnknown(Array.from(u.values()), options), (as) => new Set(as), ast, u)\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface ReadonlySetFromSelf<Value extends Schema.Any> extends\n  AnnotableDeclare<\n    ReadonlySetFromSelf<Value>,\n    ReadonlySet<Schema.Type<Value>>,\n    ReadonlySet<Schema.Encoded<Value>>,\n    [Value]\n  >\n{}\n\nconst setFromSelf_ = <Value extends Schema.Any>(value: Value, description: string): ReadonlySetFromSelf<Value> =>\n  declare(\n    [value],\n    {\n      decode: (item) => readonlySetParse(ParseResult.decodeUnknown(Array$(item))),\n      encode: (item) => readonlySetParse(ParseResult.encodeUnknown(Array$(item)))\n    },\n    {\n      typeConstructor: { _tag: \"ReadonlySet\" },\n      description,\n      pretty: readonlySetPretty,\n      arbitrary: setArbitrary,\n      equivalence: readonlySetEquivalence\n    }\n  )\n\n/**\n * @category ReadonlySet\n * @since 3.10.0\n */\nexport const ReadonlySetFromSelf = <Value extends Schema.Any>(value: Value): ReadonlySetFromSelf<Value> =>\n  setFromSelf_(value, `ReadonlySet<${format(value)}>`)\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface SetFromSelf<Value extends Schema.Any> extends\n  AnnotableDeclare<\n    SetFromSelf<Value>,\n    Set<Schema.Type<Value>>,\n    ReadonlySet<Schema.Encoded<Value>>,\n    [Value]\n  >\n{}\n\n/**\n * @category Set\n * @since 3.10.0\n */\nexport const SetFromSelf = <Value extends Schema.Any>(value: Value): SetFromSelf<Value> =>\n  setFromSelf_(value, `Set<${format(value)}>`) as any\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface ReadonlySet$<Value extends Schema.Any>\n  extends transform<Array$<Value>, ReadonlySetFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category ReadonlySet transformations\n * @since 3.10.0\n */\nexport function ReadonlySet<Value extends Schema.Any>(value: Value): ReadonlySet$<Value> {\n  return transform(\n    Array$(value),\n    ReadonlySetFromSelf(typeSchema(asSchema(value))),\n    {\n      strict: true,\n      decode: (i) => new Set(i),\n      encode: (a) => Array.from(a)\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Set$<Value extends Schema.Any>\n  extends transform<Array$<Value>, SetFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/** @ignore */\nfunction set<Value extends Schema.Any>(value: Value): Set$<Value> {\n  return transform(\n    Array$(value),\n    SetFromSelf(typeSchema(asSchema(value))),\n    {\n      strict: true,\n      decode: (i) => new Set(i),\n      encode: (a) => Array.from(a)\n    }\n  )\n}\n\nexport {\n  /**\n   * @category Set transformations\n   * @since 3.10.0\n   */\n  set as Set\n}\n\nconst bigDecimalPretty = (): pretty_.Pretty<bigDecimal_.BigDecimal> => (val) =>\n  `BigDecimal(${bigDecimal_.format(bigDecimal_.normalize(val))})`\n\nconst bigDecimalArbitrary = (): LazyArbitrary<bigDecimal_.BigDecimal> => (fc) =>\n  fc.tuple(fc.bigInt(), fc.integer({ min: -18, max: 18 }))\n    .map(([value, scale]) => bigDecimal_.make(value, scale))\n\n/**\n * @category BigDecimal constructors\n * @since 3.10.0\n */\nexport class BigDecimalFromSelf extends declare(\n  bigDecimal_.isBigDecimal,\n  {\n    typeConstructor: { _tag: \"effect/BigDecimal\" },\n    identifier: \"BigDecimalFromSelf\",\n    pretty: bigDecimalPretty,\n    arbitrary: bigDecimalArbitrary,\n    equivalence: () => bigDecimal_.Equivalence\n  }\n) {}\n\n/**\n * @category BigDecimal transformations\n * @since 3.10.0\n */\nexport class BigDecimal extends transformOrFail(\n  String$.annotations({ description: \"a string to be decoded into a BigDecimal\" }),\n  BigDecimalFromSelf,\n  {\n    strict: true,\n    decode: (i, _, ast) =>\n      bigDecimal_.fromString(i).pipe(option_.match({\n        onNone: () =>\n          ParseResult.fail(new ParseResult.Type(ast, i, `Unable to decode ${JSON.stringify(i)} into a BigDecimal`)),\n        onSome: (val) => ParseResult.succeed(bigDecimal_.normalize(val))\n      })),\n    encode: (a) => ParseResult.succeed(bigDecimal_.format(bigDecimal_.normalize(a)))\n  }\n).annotations({ identifier: \"BigDecimal\" }) {}\n\n/**\n * A schema that transforms a `number` into a `BigDecimal`.\n * When encoding, this Schema will produce incorrect results if the BigDecimal exceeds the 64-bit range of a number.\n *\n * @category BigDecimal transformations\n * @since 3.10.0\n */\nexport class BigDecimalFromNumber extends transform(\n  Number$.annotations({ description: \"a number to be decoded into a BigDecimal\" }),\n  BigDecimalFromSelf,\n  {\n    strict: true,\n    decode: (i) => bigDecimal_.unsafeFromNumber(i),\n    encode: (a) => bigDecimal_.unsafeToNumber(a)\n  }\n).annotations({ identifier: \"BigDecimalFromNumber\" }) {}\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const GreaterThanBigDecimalSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/GreaterThanBigDecimal\")\n\n/**\n * @category BigDecimal filters\n * @since 3.10.0\n */\nexport const greaterThanBigDecimal =\n  <S extends Schema.Any>(min: bigDecimal_.BigDecimal, annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends bigDecimal_.BigDecimal>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n    const formatted = bigDecimal_.format(min)\n    return self.pipe(\n      filter((a) => bigDecimal_.greaterThan(a, min), {\n        schemaId: GreaterThanBigDecimalSchemaId,\n        [GreaterThanBigDecimalSchemaId]: { min },\n        title: `greaterThanBigDecimal(${formatted})`,\n        description: `a BigDecimal greater than ${formatted}`,\n        ...annotations\n      })\n    )\n  }\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const GreaterThanOrEqualToBigDecimalSchemaId: unique symbol = Symbol.for(\n  \"effect/schema/GreaterThanOrEqualToBigDecimal\"\n)\n\n/**\n * @category BigDecimal filters\n * @since 3.10.0\n */\nexport const greaterThanOrEqualToBigDecimal =\n  <S extends Schema.Any>(min: bigDecimal_.BigDecimal, annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends bigDecimal_.BigDecimal>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n    const formatted = bigDecimal_.format(min)\n    return self.pipe(\n      filter((a) => bigDecimal_.greaterThanOrEqualTo(a, min), {\n        schemaId: GreaterThanOrEqualToBigDecimalSchemaId,\n        [GreaterThanOrEqualToBigDecimalSchemaId]: { min },\n        title: `greaterThanOrEqualToBigDecimal(${formatted})`,\n        description: `a BigDecimal greater than or equal to ${formatted}`,\n        ...annotations\n      })\n    )\n  }\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LessThanBigDecimalSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/LessThanBigDecimal\")\n\n/**\n * @category BigDecimal filters\n * @since 3.10.0\n */\nexport const lessThanBigDecimal =\n  <S extends Schema.Any>(max: bigDecimal_.BigDecimal, annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends bigDecimal_.BigDecimal>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n    const formatted = bigDecimal_.format(max)\n    return self.pipe(\n      filter((a) => bigDecimal_.lessThan(a, max), {\n        schemaId: LessThanBigDecimalSchemaId,\n        [LessThanBigDecimalSchemaId]: { max },\n        title: `lessThanBigDecimal(${formatted})`,\n        description: `a BigDecimal less than ${formatted}`,\n        ...annotations\n      })\n    )\n  }\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const LessThanOrEqualToBigDecimalSchemaId: unique symbol = Symbol.for(\n  \"effect/schema/LessThanOrEqualToBigDecimal\"\n)\n\n/**\n * @category BigDecimal filters\n * @since 3.10.0\n */\nexport const lessThanOrEqualToBigDecimal =\n  <S extends Schema.Any>(max: bigDecimal_.BigDecimal, annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends bigDecimal_.BigDecimal>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n    const formatted = bigDecimal_.format(max)\n    return self.pipe(\n      filter((a) => bigDecimal_.lessThanOrEqualTo(a, max), {\n        schemaId: LessThanOrEqualToBigDecimalSchemaId,\n        [LessThanOrEqualToBigDecimalSchemaId]: { max },\n        title: `lessThanOrEqualToBigDecimal(${formatted})`,\n        description: `a BigDecimal less than or equal to ${formatted}`,\n        ...annotations\n      })\n    )\n  }\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const PositiveBigDecimalSchemaId: unique symbol = Symbol.for(\n  \"effect/schema/PositiveBigDecimal\"\n)\n\n/**\n * @category BigDecimal filters\n * @since 3.10.0\n */\nexport const positiveBigDecimal =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends bigDecimal_.BigDecimal>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => bigDecimal_.isPositive(a), {\n        schemaId: PositiveBigDecimalSchemaId,\n        title: \"positiveBigDecimal\",\n        description: `a positive BigDecimal`,\n        ...annotations\n      })\n    )\n\n/**\n * @category BigDecimal constructors\n * @since 3.10.0\n */\nexport const PositiveBigDecimalFromSelf: filter<Schema<bigDecimal_.BigDecimal>> = BigDecimalFromSelf.pipe(\n  positiveBigDecimal({ identifier: \"PositiveBigDecimalFromSelf\" })\n)\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const NonNegativeBigDecimalSchemaId: unique symbol = Symbol.for(\n  \"effect/schema/NonNegativeBigDecimal\"\n)\n\n/**\n * @category BigDecimal filters\n * @since 3.10.0\n */\nexport const nonNegativeBigDecimal =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends bigDecimal_.BigDecimal>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => a.value >= 0n, {\n        schemaId: NonNegativeBigDecimalSchemaId,\n        title: \"nonNegativeBigDecimal\",\n        description: `a non-negative BigDecimal`,\n        ...annotations\n      })\n    )\n\n/**\n * @category BigDecimal constructors\n * @since 3.10.0\n */\nexport const NonNegativeBigDecimalFromSelf: filter<Schema<bigDecimal_.BigDecimal>> = BigDecimalFromSelf.pipe(\n  nonNegativeBigDecimal({ identifier: \"NonNegativeBigDecimalFromSelf\" })\n)\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const NegativeBigDecimalSchemaId: unique symbol = Symbol.for(\n  \"effect/schema/NegativeBigDecimal\"\n)\n\n/**\n * @category BigDecimal filters\n * @since 3.10.0\n */\nexport const negativeBigDecimal =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends bigDecimal_.BigDecimal>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => bigDecimal_.isNegative(a), {\n        schemaId: NegativeBigDecimalSchemaId,\n        title: \"negativeBigDecimal\",\n        description: `a negative BigDecimal`,\n        ...annotations\n      })\n    )\n\n/**\n * @category BigDecimal constructors\n * @since 3.10.0\n */\nexport const NegativeBigDecimalFromSelf: filter<Schema<bigDecimal_.BigDecimal>> = BigDecimalFromSelf.pipe(\n  negativeBigDecimal({ identifier: \"NegativeBigDecimalFromSelf\" })\n)\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const NonPositiveBigDecimalSchemaId: unique symbol = Symbol.for(\n  \"effect/schema/NonPositiveBigDecimal\"\n)\n\n/**\n * @category BigDecimal filters\n * @since 3.10.0\n */\nexport const nonPositiveBigDecimal =\n  <S extends Schema.Any>(annotations?: Annotations.Filter<Schema.Type<S>>) =>\n  <A extends bigDecimal_.BigDecimal>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> =>\n    self.pipe(\n      filter((a) => a.value <= 0n, {\n        schemaId: NonPositiveBigDecimalSchemaId,\n        title: \"nonPositiveBigDecimal\",\n        description: `a non-positive BigDecimal`,\n        ...annotations\n      })\n    )\n\n/**\n * @category BigDecimal constructors\n * @since 3.10.0\n */\nexport const NonPositiveBigDecimalFromSelf: filter<Schema<bigDecimal_.BigDecimal>> = BigDecimalFromSelf.pipe(\n  nonPositiveBigDecimal({ identifier: \"NonPositiveBigDecimalFromSelf\" })\n)\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const BetweenBigDecimalSchemaId: unique symbol = Symbol.for(\"effect/SchemaId/BetweenBigDecimal\")\n\n/**\n * @category BigDecimal filters\n * @since 3.10.0\n */\nexport const betweenBigDecimal = <S extends Schema.Any>(\n  minimum: bigDecimal_.BigDecimal,\n  maximum: bigDecimal_.BigDecimal,\n  annotations?: Annotations.Filter<Schema.Type<S>>\n) =>\n<A extends bigDecimal_.BigDecimal>(self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>): filter<S> => {\n  const formattedMinimum = bigDecimal_.format(minimum)\n  const formattedMaximum = bigDecimal_.format(maximum)\n  return self.pipe(\n    filter((a) => bigDecimal_.between(a, { minimum, maximum }), {\n      schemaId: BetweenBigDecimalSchemaId,\n      [BetweenBigDecimalSchemaId]: { maximum, minimum },\n      title: `betweenBigDecimal(${formattedMinimum}, ${formattedMaximum})`,\n      description: `a BigDecimal between ${formattedMinimum} and ${formattedMaximum}`,\n      ...annotations\n    })\n  )\n}\n\n/**\n * Clamps a `BigDecimal` between a minimum and a maximum value.\n *\n * @category BigDecimal transformations\n * @since 3.10.0\n */\nexport const clampBigDecimal =\n  (minimum: bigDecimal_.BigDecimal, maximum: bigDecimal_.BigDecimal) =>\n  <S extends Schema.Any, A extends bigDecimal_.BigDecimal>(\n    self: S & Schema<A, Schema.Encoded<S>, Schema.Context<S>>\n  ): transform<S, filter<SchemaClass<A>>> =>\n    transform(\n      self,\n      self.pipe(typeSchema, betweenBigDecimal(minimum, maximum)),\n      {\n        strict: false,\n        decode: (i) => bigDecimal_.clamp(i, { minimum, maximum }),\n        encode: identity\n      }\n    )\n\nconst chunkArbitrary =\n  <A>(item: LazyArbitrary<A>, ctx: ArbitraryGenerationContext): LazyArbitrary<chunk_.Chunk<A>> => (fc) => {\n    const items = fc.array(item(fc))\n    return (ctx.depthIdentifier !== undefined ? fc.oneof(ctx, fc.constant([]), items) : items).map(chunk_.fromIterable)\n  }\n\nconst chunkPretty = <A>(item: pretty_.Pretty<A>): pretty_.Pretty<chunk_.Chunk<A>> => (c) =>\n  `Chunk(${chunk_.toReadonlyArray(c).map(item).join(\", \")})`\n\nconst chunkParse = <A, R>(\n  decodeUnknown: ParseResult.DecodeUnknown<ReadonlyArray<A>, R>\n): ParseResult.DeclarationDecodeUnknown<chunk_.Chunk<A>, R> =>\n(u, options, ast) =>\n  chunk_.isChunk(u) ?\n    chunk_.isEmpty(u) ?\n      ParseResult.succeed(chunk_.empty())\n      : toComposite(decodeUnknown(chunk_.toReadonlyArray(u), options), chunk_.fromIterable, ast, u)\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface ChunkFromSelf<Value extends Schema.Any> extends\n  AnnotableDeclare<\n    ChunkFromSelf<Value>,\n    chunk_.Chunk<Schema.Type<Value>>,\n    chunk_.Chunk<Schema.Encoded<Value>>,\n    [Value]\n  >\n{}\n\n/**\n * @category Chunk\n * @since 3.10.0\n */\nexport const ChunkFromSelf = <Value extends Schema.Any>(value: Value): ChunkFromSelf<Value> => {\n  return declare(\n    [value],\n    {\n      decode: (item) => chunkParse(ParseResult.decodeUnknown(Array$(item))),\n      encode: (item) => chunkParse(ParseResult.encodeUnknown(Array$(item)))\n    },\n    {\n      typeConstructor: { _tag: \"effect/Chunk\" },\n      description: `Chunk<${format(value)}>`,\n      pretty: chunkPretty,\n      arbitrary: chunkArbitrary,\n      equivalence: chunk_.getEquivalence\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Chunk<Value extends Schema.Any>\n  extends transform<Array$<Value>, ChunkFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category Chunk transformations\n * @since 3.10.0\n */\nexport function Chunk<Value extends Schema.Any>(value: Value): Chunk<Value> {\n  return transform(\n    Array$(value),\n    ChunkFromSelf(typeSchema(asSchema(value))),\n    {\n      strict: true,\n      decode: (i) => i.length === 0 ? chunk_.empty() : chunk_.fromIterable(i),\n      encode: (a) => chunk_.toReadonlyArray(a)\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface NonEmptyChunkFromSelf<Value extends Schema.Any> extends\n  AnnotableDeclare<\n    NonEmptyChunkFromSelf<Value>,\n    chunk_.NonEmptyChunk<Schema.Type<Value>>,\n    chunk_.NonEmptyChunk<Schema.Encoded<Value>>,\n    [Value]\n  >\n{}\n\nconst nonEmptyChunkArbitrary = <A>(item: LazyArbitrary<A>): LazyArbitrary<chunk_.NonEmptyChunk<A>> => (fc) =>\n  fastCheck_.array(item(fc), { minLength: 1 }).map((as) => chunk_.unsafeFromNonEmptyArray(as as any))\n\nconst nonEmptyChunkPretty = <A>(item: pretty_.Pretty<A>): pretty_.Pretty<chunk_.NonEmptyChunk<A>> => (c) =>\n  `NonEmptyChunk(${chunk_.toReadonlyArray(c).map(item).join(\", \")})`\n\nconst nonEmptyChunkParse = <A, R>(\n  decodeUnknown: ParseResult.DecodeUnknown<array_.NonEmptyReadonlyArray<A>, R>\n): ParseResult.DeclarationDecodeUnknown<chunk_.NonEmptyChunk<A>, R> =>\n(u, options, ast) =>\n  chunk_.isChunk(u) && chunk_.isNonEmpty(u)\n    ? toComposite(decodeUnknown(chunk_.toReadonlyArray(u), options), chunk_.unsafeFromNonEmptyArray, ast, u)\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category Chunk\n * @since 3.10.0\n */\nexport const NonEmptyChunkFromSelf = <Value extends Schema.Any>(value: Value): NonEmptyChunkFromSelf<Value> => {\n  return declare(\n    [value],\n    {\n      decode: (item) => nonEmptyChunkParse(ParseResult.decodeUnknown(NonEmptyArray(item))),\n      encode: (item) => nonEmptyChunkParse(ParseResult.encodeUnknown(NonEmptyArray(item)))\n    },\n    {\n      typeConstructor: { _tag: \"effect/Chunk.NonEmptyChunk\" },\n      description: `NonEmptyChunk<${format(value)}>`,\n      pretty: nonEmptyChunkPretty,\n      arbitrary: nonEmptyChunkArbitrary,\n      equivalence: chunk_.getEquivalence\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface NonEmptyChunk<Value extends Schema.Any>\n  extends transform<NonEmptyArray<Value>, NonEmptyChunkFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category Chunk transformations\n * @since 3.10.0\n */\nexport function NonEmptyChunk<Value extends Schema.Any>(value: Value): NonEmptyChunk<Value> {\n  return transform(\n    NonEmptyArray(value),\n    NonEmptyChunkFromSelf(typeSchema(asSchema(value))),\n    {\n      strict: true,\n      decode: (i) => chunk_.unsafeFromNonEmptyArray(i),\n      encode: (a) => chunk_.toReadonlyArray(a)\n    }\n  )\n}\n\nconst decodeData = <A extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>>(a: A): A =>\n  Array.isArray(a) ? data_.array(a) : data_.struct(a)\n\nconst dataArbitrary = <A extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>>(\n  item: LazyArbitrary<A>\n): LazyArbitrary<A> =>\n(fc) => item(fc).map(decodeData)\n\nconst dataPretty = <A extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>>(\n  item: pretty_.Pretty<A>\n): pretty_.Pretty<A> =>\n(d) => `Data(${item(d)})`\n\nconst dataParse = <R, A extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>>(\n  decodeUnknown: ParseResult.DecodeUnknown<A, R>\n): ParseResult.DeclarationDecodeUnknown<A, R> =>\n(u, options, ast) =>\n  Equal.isEqual(u) ?\n    toComposite(decodeUnknown(u, options), decodeData, ast, u)\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.13.3\n */\nexport interface DataFromSelf<Value extends Schema.Any> extends\n  AnnotableDeclare<\n    DataFromSelf<Value>,\n    Schema.Type<Value>,\n    Schema.Encoded<Value>,\n    [Value]\n  >\n{}\n\n/**\n * Type and Encoded must extend `Readonly<Record<string, any>> |\n * ReadonlyArray<any>` to be compatible with this API.\n *\n * @category Data transformations\n * @since 3.10.0\n */\nexport const DataFromSelf = <\n  S extends Schema.Any,\n  A extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>,\n  I extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>\n>(value: S & Schema<A & Schema.Type<S>, I & Schema.Encoded<S>, Schema.Context<S>>): DataFromSelf<S> => {\n  return declare(\n    [value],\n    {\n      decode: (item) => dataParse(ParseResult.decodeUnknown(item)),\n      encode: (item) => dataParse(ParseResult.encodeUnknown(item))\n    },\n    {\n      description: `Data<${format(value)}>`,\n      pretty: dataPretty,\n      arbitrary: dataArbitrary\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.13.3\n */\nexport interface Data<Value extends Schema.Any>\n  extends transform<Value, DataFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * Type and Encoded must extend `Readonly<Record<string, any>> |\n * ReadonlyArray<any>` to be compatible with this API.\n *\n * @category Data transformations\n * @since 3.10.0\n */\nexport const Data = <\n  S extends Schema.Any,\n  A extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>,\n  I extends Readonly<Record<string, unknown>> | ReadonlyArray<unknown>\n>(value: S & Schema<A & Schema.Type<S>, I & Schema.Encoded<S>, Schema.Context<S>>): Data<S> => {\n  return transform(\n    value,\n    DataFromSelf(typeSchema(value)),\n    {\n      strict: false,\n      decode: (i) => decodeData(i),\n      encode: (a) => Array.isArray(a) ? Array.from(a) : Object.assign({}, a)\n    }\n  )\n}\n\ntype MissingSelfGeneric<Usage extends string, Params extends string = \"\"> =\n  `Missing \\`Self\\` generic - use \\`class Self extends ${Usage}<Self>()(${Params}{ ... })\\``\n\ntype RequiredKeys<T> = {\n  [K in keyof T]-?: {} extends Pick<T, K> ? never : K\n}[keyof T]\n\ntype ClassAnnotations<Self, A> =\n  | Annotations.Schema<Self>\n  | readonly [\n    // Annotations for the \"to\" schema\n    Annotations.Schema<Self> | undefined,\n    // Annotations for the \"transformation schema\n    (Annotations.Schema<Self> | undefined)?,\n    // Annotations for the \"from\" schema\n    Annotations.Schema<A>?\n  ]\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Class<Self, Fields extends Struct.Fields, I, R, C, Inherited, Proto>\n  extends Schema<Self, Simplify<I>, R>\n{\n  new(\n    props: RequiredKeys<C> extends never ? void | Simplify<C> : Simplify<C>,\n    options?: MakeOptions\n  ): Struct.Type<Fields> & Inherited & Proto\n\n  /** @since 3.10.0 */\n  readonly ast: AST.Transformation\n\n  make<C extends new(...args: Array<any>) => any>(this: C, ...args: ConstructorParameters<C>): InstanceType<C>\n\n  annotations(annotations: Annotations.Schema<Self>): SchemaClass<Self, Simplify<I>, R>\n\n  readonly fields: { readonly [K in keyof Fields]: Fields[K] }\n\n  readonly identifier: string\n\n  /**\n   * @example\n   * ```ts\n   * import { Schema } from \"effect\"\n   *\n   * class MyClass extends Schema.Class<MyClass>(\"MyClass\")({\n   *  myField: Schema.String\n   * }) {\n   *  myMethod() {\n   *    return this.myField + \"my\"\n   *  }\n   * }\n   *\n   * class NextClass extends MyClass.extend<NextClass>(\"NextClass\")({\n   *  nextField: Schema.Number\n   * }) {\n   *  nextMethod() {\n   *    return this.myMethod() + this.myField + this.nextField\n   *  }\n   * }\n   * ```\n   */\n  extend<Extended = never>(identifier: string): <NewFields extends Struct.Fields>(\n    fields: NewFields | HasFields<NewFields>,\n    annotations?: ClassAnnotations<Extended, Simplify<Struct.Type<Fields & NewFields>>>\n  ) => [Extended] extends [never] ? MissingSelfGeneric<\"Base.extend\">\n    : Class<\n      Extended,\n      Fields & NewFields,\n      I & Struct.Encoded<NewFields>,\n      R | Struct.Context<NewFields>,\n      C & Struct.Constructor<NewFields>,\n      Self,\n      Proto\n    >\n\n  /**\n   * @example\n   * ```ts\n   * import { Effect, Schema } from \"effect\"\n   *\n   * class MyClass extends Schema.Class<MyClass>(\"MyClass\")({\n   *   myField: Schema.String\n   * }) {\n   *   myMethod() {\n   *     return this.myField + \"my\"\n   *   }\n   * }\n   *\n   * class NextClass extends MyClass.transformOrFail<NextClass>(\"NextClass\")({\n   *   nextField: Schema.Number\n   * }, {\n   *   decode: (i) =>\n   *     Effect.succeed({\n   *       myField: i.myField,\n   *       nextField: i.myField.length\n   *     }),\n   *   encode: (a) => Effect.succeed({ myField: a.myField })\n   * }) {\n   *   nextMethod() {\n   *     return this.myMethod() + this.myField + this.nextField\n   *   }\n   * }\n   * ```\n   */\n  transformOrFail<Transformed = never>(identifier: string): <\n    NewFields extends Struct.Fields,\n    R2,\n    R3\n  >(\n    fields: NewFields,\n    options: {\n      readonly decode: (\n        input: Simplify<Struct.Type<Fields>>,\n        options: ParseOptions,\n        ast: AST.Transformation\n      ) => Effect.Effect<Simplify<Struct.Type<Fields & NewFields>>, ParseResult.ParseIssue, R2>\n      readonly encode: (\n        input: Simplify<Struct.Type<Fields & NewFields>>,\n        options: ParseOptions,\n        ast: AST.Transformation\n      ) => Effect.Effect<Struct.Type<Fields>, ParseResult.ParseIssue, R3>\n    },\n    annotations?: ClassAnnotations<Transformed, Simplify<Struct.Type<Fields & NewFields>>>\n  ) => [Transformed] extends [never] ? MissingSelfGeneric<\"Base.transformOrFail\">\n    : Class<\n      Transformed,\n      Fields & NewFields,\n      I,\n      R | Struct.Context<NewFields> | R2 | R3,\n      C & Struct.Constructor<NewFields>,\n      Self,\n      Proto\n    >\n\n  /**\n   * @example\n   * ```ts\n   * import { Effect, Schema } from \"effect\"\n   *\n   * class MyClass extends Schema.Class<MyClass>(\"MyClass\")({\n   *   myField: Schema.String\n   * }) {\n   *   myMethod() {\n   *     return this.myField + \"my\"\n   *   }\n   * }\n   *\n   * class NextClass extends MyClass.transformOrFailFrom<NextClass>(\"NextClass\")({\n   *   nextField: Schema.Number\n   * }, {\n   *   decode: (i) =>\n   *     Effect.succeed({\n   *       myField: i.myField,\n   *       nextField: i.myField.length\n   *     }),\n   *   encode: (a) => Effect.succeed({ myField: a.myField })\n   * }) {\n   *   nextMethod() {\n   *     return this.myMethod() + this.myField + this.nextField\n   *   }\n   * }\n   * ```\n   */\n  transformOrFailFrom<Transformed = never>(identifier: string): <\n    NewFields extends Struct.Fields,\n    R2,\n    R3\n  >(\n    fields: NewFields,\n    options: {\n      readonly decode: (\n        input: Simplify<I>,\n        options: ParseOptions,\n        ast: AST.Transformation\n      ) => Effect.Effect<Simplify<I & Struct.Encoded<NewFields>>, ParseResult.ParseIssue, R2>\n      readonly encode: (\n        input: Simplify<I & Struct.Encoded<NewFields>>,\n        options: ParseOptions,\n        ast: AST.Transformation\n      ) => Effect.Effect<I, ParseResult.ParseIssue, R3>\n    },\n    annotations?: ClassAnnotations<Transformed, Simplify<Struct.Type<Fields & NewFields>>>\n  ) => [Transformed] extends [never] ? MissingSelfGeneric<\"Base.transformOrFailFrom\">\n    : Class<\n      Transformed,\n      Fields & NewFields,\n      I,\n      R | Struct.Context<NewFields> | R2 | R3,\n      C & Struct.Constructor<NewFields>,\n      Self,\n      Proto\n    >\n}\n\ntype HasFields<Fields extends Struct.Fields> = Struct<Fields> | {\n  readonly [RefineSchemaId]: HasFields<Fields>\n}\n\nconst isField = (u: unknown) => isSchema(u) || isPropertySignature(u)\n\nconst isFields = <Fields extends Struct.Fields>(fields: object): fields is Fields =>\n  Reflect.ownKeys(fields).every((key) => isField((fields as any)[key]))\n\nconst getFields = <Fields extends Struct.Fields>(hasFields: HasFields<Fields>): Fields =>\n  \"fields\" in hasFields ? hasFields.fields : getFields(hasFields[RefineSchemaId])\n\nconst getSchemaFromFieldsOr = <Fields extends Struct.Fields>(fieldsOr: Fields | HasFields<Fields>): Schema.Any =>\n  isFields(fieldsOr) ? Struct(fieldsOr) : isSchema(fieldsOr) ? fieldsOr : Struct(getFields(fieldsOr))\n\nconst getFieldsFromFieldsOr = <Fields extends Struct.Fields>(fieldsOr: Fields | HasFields<Fields>): Fields =>\n  isFields(fieldsOr) ? fieldsOr : getFields(fieldsOr)\n\n/**\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n *\n * class MyClass extends Schema.Class<MyClass>(\"MyClass\")({\n *  someField: Schema.String\n * }) {\n *  someMethod() {\n *    return this.someField + \"bar\"\n *  }\n * }\n * ```\n *\n * @category classes\n * @since 3.10.0\n */\nexport const Class = <Self = never>(identifier: string) =>\n<Fields extends Struct.Fields>(\n  fieldsOr: Fields | HasFields<Fields>,\n  annotations?: ClassAnnotations<Self, Simplify<Struct.Type<Fields>>>\n): [Self] extends [never] ? MissingSelfGeneric<\"Class\">\n  : Class<\n    Self,\n    Fields,\n    Struct.Encoded<Fields>,\n    Struct.Context<Fields>,\n    Struct.Constructor<Fields>,\n    {},\n    {}\n  > =>\n  makeClass({\n    kind: \"Class\",\n    identifier,\n    schema: getSchemaFromFieldsOr(fieldsOr),\n    fields: getFieldsFromFieldsOr(fieldsOr),\n    Base: data_.Class,\n    annotations\n  })\n\n/** @internal */\nexport const getClassTag = <Tag extends string>(tag: Tag) =>\n  withConstructorDefault(propertySignature(Literal(tag)), () => tag)\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface TaggedClass<Self, Tag extends string, Fields extends Struct.Fields> extends\n  Class<\n    Self,\n    Fields,\n    Struct.Encoded<Fields>,\n    Struct.Context<Fields>,\n    Struct.Constructor<Omit<Fields, \"_tag\">>,\n    {},\n    {}\n  >\n{\n  readonly _tag: Tag\n}\n\n/**\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n *\n * class MyClass extends Schema.TaggedClass<MyClass>(\"MyClass\")(\"MyClass\", {\n *  a: Schema.String\n * }) {}\n * ```\n *\n * @category classes\n * @since 3.10.0\n */\nexport const TaggedClass = <Self = never>(identifier?: string) =>\n<Tag extends string, Fields extends Struct.Fields>(\n  tag: Tag,\n  fieldsOr: Fields | HasFields<Fields>,\n  annotations?: ClassAnnotations<Self, Simplify<Struct.Type<{ readonly _tag: tag<Tag> } & Fields>>>\n): [Self] extends [never] ? MissingSelfGeneric<\"TaggedClass\", `\"Tag\", `>\n  : TaggedClass<Self, Tag, { readonly _tag: tag<Tag> } & Fields> =>\n{\n  const fields = getFieldsFromFieldsOr(fieldsOr)\n  const schema = getSchemaFromFieldsOr(fieldsOr)\n  const newFields = { _tag: getClassTag(tag) }\n  const taggedFields = extendFields(newFields, fields)\n  return class TaggedClass extends makeClass({\n    kind: \"TaggedClass\",\n    identifier: identifier ?? tag,\n    schema: extend(schema, Struct(newFields)),\n    fields: taggedFields,\n    Base: data_.Class,\n    annotations\n  }) {\n    static _tag = tag\n  } as any\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface TaggedErrorClass<Self, Tag extends string, Fields extends Struct.Fields> extends\n  Class<\n    Self,\n    Fields,\n    Struct.Encoded<Fields>,\n    Struct.Context<Fields>,\n    Struct.Constructor<Omit<Fields, \"_tag\">>,\n    {},\n    cause_.YieldableError\n  >\n{\n  readonly _tag: Tag\n}\n\n/**\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n *\n * class MyError extends Schema.TaggedError<MyError>(\"MyError\")(\n *   \"MyError\",\n *   {\n *     module: Schema.String,\n *     method: Schema.String,\n *     description: Schema.String\n *   }\n * ) {\n *   get message(): string {\n *     return `${this.module}.${this.method}: ${this.description}`\n *   }\n * }\n * ```\n * @category classes\n * @since 3.10.0\n */\nexport const TaggedError = <Self = never>(identifier?: string) =>\n<Tag extends string, Fields extends Struct.Fields>(\n  tag: Tag,\n  fieldsOr: Fields | HasFields<Fields>,\n  annotations?: ClassAnnotations<Self, Simplify<Struct.Type<{ readonly _tag: tag<Tag> } & Fields>>>\n): [Self] extends [never] ? MissingSelfGeneric<\"TaggedError\", `\"Tag\", `>\n  : TaggedErrorClass<\n    Self,\n    Tag,\n    { readonly _tag: tag<Tag> } & Fields\n  > =>\n{\n  class Base extends data_.Error {}\n  ;(Base.prototype as any).name = tag\n  const fields = getFieldsFromFieldsOr(fieldsOr)\n  const schema = getSchemaFromFieldsOr(fieldsOr)\n  const newFields = { _tag: getClassTag(tag) }\n  const taggedFields = extendFields(newFields, fields)\n  const hasMessageField = \"message\" in taggedFields\n  class TaggedErrorClass extends makeClass({\n    kind: \"TaggedError\",\n    identifier: identifier ?? tag,\n    schema: extend(schema, Struct(newFields)),\n    fields: taggedFields,\n    Base,\n    annotations,\n    disableToString: true\n  }) {\n    static _tag = tag\n  }\n\n  if (!hasMessageField) {\n    Object.defineProperty(TaggedErrorClass.prototype, \"message\", {\n      get() {\n        return `{ ${\n          Reflect.ownKeys(fields)\n            .map((p: any) => `${Inspectable.formatPropertyKey(p)}: ${Inspectable.formatUnknown((this)[p])}`)\n            .join(\", \")\n        } }`\n      },\n      enumerable: false, // mirrors the built-in Error.prototype.message, whose descriptor is also non-enumerable\n      configurable: true\n    })\n  }\n\n  return TaggedErrorClass as any\n}\n\nconst extendFields = (a: Struct.Fields, b: Struct.Fields): Struct.Fields => {\n  const out = { ...a }\n  for (const key of Reflect.ownKeys(b)) {\n    if (key in a) {\n      throw new Error(errors_.getASTDuplicatePropertySignatureErrorMessage(key))\n    }\n    out[key] = b[key]\n  }\n  return out\n}\n\n/**\n * @category Constructor utils\n * @since 3.13.4\n */\nexport type MakeOptions = boolean | {\n  readonly disableValidation?: boolean | undefined\n}\n\nfunction getDisableValidationMakeOption(options: MakeOptions | undefined): boolean {\n  return Predicate.isBoolean(options) ? options : options?.disableValidation ?? false\n}\n\nconst astCache = globalValue(\"effect/Schema/astCache\", () => new WeakMap<any, AST.AST>())\n\nconst getClassAnnotations = <Self, A>(\n  annotations: ClassAnnotations<Self, A> | undefined\n): [Annotations.Schema<Self>?, Annotations.Schema<Self>?, Annotations.Schema<A>?] => {\n  if (annotations === undefined) {\n    return []\n  } else if (Array.isArray(annotations)) {\n    return annotations as any\n  } else {\n    return [annotations] as any\n  }\n}\n\nconst makeClass = <Fields extends Struct.Fields>(\n  { Base, annotations, disableToString, fields, identifier, kind, schema }: {\n    kind: \"Class\" | \"TaggedClass\" | \"TaggedError\" | \"TaggedRequest\"\n    identifier: string\n    schema: Schema.Any\n    fields: Fields\n    Base: new(...args: ReadonlyArray<any>) => any\n    annotations?: ClassAnnotations<any, any> | undefined\n    disableToString?: boolean | undefined\n  }\n): any => {\n  const classSymbol = Symbol.for(`effect/Schema/${kind}/${identifier}`)\n\n  const [typeAnnotations, transformationAnnotations, encodedAnnotations] = getClassAnnotations(annotations)\n\n  const typeSchema_ = typeSchema(schema)\n\n  const declarationSurrogate = typeSchema_.annotations({\n    identifier,\n    ...typeAnnotations\n  })\n\n  const typeSide = typeSchema_.annotations({\n    [AST.AutoTitleAnnotationId]: `${identifier} (Type side)`,\n    ...typeAnnotations\n  })\n\n  const constructorSchema = schema.annotations({\n    [AST.AutoTitleAnnotationId]: `${identifier} (Constructor)`,\n    ...typeAnnotations\n  })\n\n  const encodedSide = schema.annotations({\n    [AST.AutoTitleAnnotationId]: `${identifier} (Encoded side)`,\n    ...encodedAnnotations\n  })\n\n  const transformationSurrogate = schema.annotations({\n    ...encodedAnnotations,\n    ...typeAnnotations,\n    ...transformationAnnotations\n  })\n\n  const fallbackInstanceOf = (u: unknown) => Predicate.hasProperty(u, classSymbol) && ParseResult.is(typeSide)(u)\n\n  const klass = class extends Base {\n    constructor(\n      props: { [x: string | symbol]: unknown } = {},\n      options: MakeOptions = false\n    ) {\n      props = { ...props }\n      if (kind !== \"Class\") {\n        delete props[\"_tag\"]\n      }\n      props = lazilyMergeDefaults(fields, props)\n      if (!getDisableValidationMakeOption(options)) {\n        props = ParseResult.validateSync(constructorSchema)(props)\n      }\n      super(props, true)\n    }\n\n    // ----------------\n    // Schema interface\n    // ----------------\n\n    static [TypeId] = variance\n\n    static get ast(): AST.AST {\n      let out = astCache.get(this)\n      if (out) {\n        return out\n      }\n\n      const declaration: Schema.Any = declare(\n        [schema],\n        {\n          decode: () => (input, _, ast) =>\n            input instanceof this || fallbackInstanceOf(input)\n              ? ParseResult.succeed(input)\n              : ParseResult.fail(new ParseResult.Type(ast, input)),\n          encode: () => (input, options) =>\n            input instanceof this\n              ? ParseResult.succeed(input)\n              : ParseResult.map(\n                ParseResult.encodeUnknown(typeSide)(input, options),\n                (props) => new this(props, true)\n              )\n        },\n        {\n          identifier,\n          pretty: (pretty) => (self: any) => `${identifier}(${pretty(self)})`,\n          // @ts-expect-error\n          arbitrary: (arb) => (fc) => arb(fc).map((props) => new this(props)),\n          equivalence: identity,\n          [AST.SurrogateAnnotationId]: declarationSurrogate.ast,\n          ...typeAnnotations\n        }\n      )\n\n      out = transform(\n        encodedSide,\n        declaration,\n        {\n          strict: true,\n          decode: (i) => new this(i, true),\n          encode: identity\n        }\n      ).annotations({\n        [AST.SurrogateAnnotationId]: transformationSurrogate.ast,\n        ...transformationAnnotations\n      }).ast\n\n      astCache.set(this, out)\n\n      return out\n    }\n\n    static pipe() {\n      return pipeArguments(this, arguments)\n    }\n\n    static annotations(annotations: Annotations.Schema<any>) {\n      return make(this.ast).annotations(annotations)\n    }\n\n    static toString() {\n      return `(${String(encodedSide)} <-> ${identifier})`\n    }\n\n    // ----------------\n    // Class interface\n    // ----------------\n\n    static make(...args: Array<any>) {\n      return new this(...args)\n    }\n\n    static fields = { ...fields }\n\n    static identifier = identifier\n\n    static extend<Extended, NewFields extends Struct.Fields>(identifier: string) {\n      return (\n        newFieldsOr: NewFields | HasFields<NewFields>,\n        annotations?: ClassAnnotations<Extended, Simplify<Struct.Type<Fields & NewFields>>>\n      ) => {\n        const newFields = getFieldsFromFieldsOr(newFieldsOr)\n        const newSchema = getSchemaFromFieldsOr(newFieldsOr)\n        const extendedFields = extendFields(fields, newFields)\n        return makeClass({\n          kind,\n          identifier,\n          schema: extend(schema, newSchema),\n          fields: extendedFields,\n          Base: this,\n          annotations\n        })\n      }\n    }\n\n    static transformOrFail<Transformed, NewFields extends Struct.Fields>(identifier: string) {\n      return (\n        newFieldsOr: NewFields,\n        options: any,\n        annotations?: ClassAnnotations<Transformed, Simplify<Struct.Type<Fields & NewFields>>>\n      ) => {\n        const transformedFields: Struct.Fields = extendFields(fields, newFieldsOr)\n        return makeClass({\n          kind,\n          identifier,\n          schema: transformOrFail(\n            schema,\n            typeSchema(Struct(transformedFields)),\n            options\n          ),\n          fields: transformedFields,\n          Base: this,\n          annotations\n        })\n      }\n    }\n\n    static transformOrFailFrom<Transformed, NewFields extends Struct.Fields>(identifier: string) {\n      return (\n        newFields: NewFields,\n        options: any,\n        annotations?: ClassAnnotations<Transformed, Simplify<Struct.Type<Fields & NewFields>>>\n      ) => {\n        const transformedFields: Struct.Fields = extendFields(fields, newFields)\n        return makeClass({\n          kind,\n          identifier,\n          schema: transformOrFail(\n            encodedSchema(schema),\n            Struct(transformedFields),\n            options\n          ),\n          fields: transformedFields,\n          Base: this,\n          annotations\n        })\n      }\n    }\n\n    // ----------------\n    // other\n    // ----------------\n\n    get [classSymbol]() {\n      return classSymbol\n    }\n  }\n  if (disableToString !== true) {\n    Object.defineProperty(klass.prototype, \"toString\", {\n      value() {\n        return `${identifier}({ ${\n          Reflect.ownKeys(fields).map((p: any) =>\n            `${Inspectable.formatPropertyKey(p)}: ${Inspectable.formatUnknown(this[p])}`\n          )\n            .join(\", \")\n        } })`\n      },\n      configurable: true,\n      writable: true\n    })\n  }\n  return klass\n}\n\n/**\n * @category FiberId\n * @since 3.10.0\n */\nexport type FiberIdEncoded =\n  | {\n    readonly _tag: \"Composite\"\n    readonly left: FiberIdEncoded\n    readonly right: FiberIdEncoded\n  }\n  | {\n    readonly _tag: \"None\"\n  }\n  | {\n    readonly _tag: \"Runtime\"\n    readonly id: number\n    readonly startTimeMillis: number\n  }\n\nconst FiberIdNoneEncoded = Struct({\n  _tag: Literal(\"None\")\n}).annotations({ identifier: \"FiberIdNoneEncoded\" })\n\nconst FiberIdRuntimeEncoded = Struct({\n  _tag: Literal(\"Runtime\"),\n  id: Int,\n  startTimeMillis: Int\n}).annotations({ identifier: \"FiberIdRuntimeEncoded\" })\n\nconst FiberIdCompositeEncoded = Struct({\n  _tag: Literal(\"Composite\"),\n  left: suspend(() => FiberIdEncoded),\n  right: suspend(() => FiberIdEncoded)\n}).annotations({ identifier: \"FiberIdCompositeEncoded\" })\n\nconst FiberIdEncoded: Schema<FiberIdEncoded> = Union(\n  FiberIdNoneEncoded,\n  FiberIdRuntimeEncoded,\n  FiberIdCompositeEncoded\n).annotations({ identifier: \"FiberIdEncoded\" })\n\nconst fiberIdArbitrary: LazyArbitrary<fiberId_.FiberId> = (fc) =>\n  fc.letrec((tie) => ({\n    None: fc.record({ _tag: fc.constant(\"None\" as const) }),\n    Runtime: fc.record({ _tag: fc.constant(\"Runtime\" as const), id: fc.integer(), startTimeMillis: fc.integer() }),\n    Composite: fc.record({ _tag: fc.constant(\"Composite\" as const), left: tie(\"FiberId\"), right: tie(\"FiberId\") }),\n    FiberId: fc.oneof(tie(\"None\"), tie(\"Runtime\"), tie(\"Composite\")) as any as fastCheck_.Arbitrary<fiberId_.FiberId>\n  })).FiberId.map(fiberIdDecode)\n\nconst fiberIdPretty: pretty_.Pretty<fiberId_.FiberId> = (fiberId) => {\n  switch (fiberId._tag) {\n    case \"None\":\n      return \"FiberId.none\"\n    case \"Runtime\":\n      return `FiberId.runtime(${fiberId.id}, ${fiberId.startTimeMillis})`\n    case \"Composite\":\n      return `FiberId.composite(${fiberIdPretty(fiberId.right)}, ${fiberIdPretty(fiberId.left)})`\n  }\n}\n\n/**\n * @category FiberId constructors\n * @since 3.10.0\n */\nexport class FiberIdFromSelf extends declare(\n  fiberId_.isFiberId,\n  {\n    typeConstructor: { _tag: \"effect/FiberId\" },\n    identifier: \"FiberIdFromSelf\",\n    pretty: () => fiberIdPretty,\n    arbitrary: () => fiberIdArbitrary\n  }\n) {}\n\nconst fiberIdDecode = (input: FiberIdEncoded): fiberId_.FiberId => {\n  switch (input._tag) {\n    case \"None\":\n      return fiberId_.none\n    case \"Runtime\":\n      return fiberId_.runtime(input.id, input.startTimeMillis)\n    case \"Composite\":\n      return fiberId_.composite(fiberIdDecode(input.left), fiberIdDecode(input.right))\n  }\n}\n\nconst fiberIdEncode = (input: fiberId_.FiberId): FiberIdEncoded => {\n  switch (input._tag) {\n    case \"None\":\n      return { _tag: \"None\" }\n    case \"Runtime\":\n      return { _tag: \"Runtime\", id: input.id, startTimeMillis: input.startTimeMillis }\n    case \"Composite\":\n      return {\n        _tag: \"Composite\",\n        left: fiberIdEncode(input.left),\n        right: fiberIdEncode(input.right)\n      }\n  }\n}\n\n/**\n * @category FiberId transformations\n * @since 3.10.0\n */\nexport class FiberId extends transform(\n  FiberIdEncoded,\n  FiberIdFromSelf,\n  {\n    strict: true,\n    decode: (i) => fiberIdDecode(i),\n    encode: (a) => fiberIdEncode(a)\n  }\n).annotations({ identifier: \"FiberId\" }) {}\n\n/**\n * @category Cause utils\n * @since 3.10.0\n */\nexport type CauseEncoded<E, D> =\n  | {\n    readonly _tag: \"Empty\"\n  }\n  | {\n    readonly _tag: \"Fail\"\n    readonly error: E\n  }\n  | {\n    readonly _tag: \"Die\"\n    readonly defect: D\n  }\n  | {\n    readonly _tag: \"Interrupt\"\n    readonly fiberId: FiberIdEncoded\n  }\n  | {\n    readonly _tag: \"Sequential\"\n    readonly left: CauseEncoded<E, D>\n    readonly right: CauseEncoded<E, D>\n  }\n  | {\n    readonly _tag: \"Parallel\"\n    readonly left: CauseEncoded<E, D>\n    readonly right: CauseEncoded<E, D>\n  }\n\nconst causeDieEncoded = <Defect extends Schema.Any>(defect: Defect) =>\n  Struct({\n    _tag: Literal(\"Die\"),\n    defect\n  })\n\nconst CauseEmptyEncoded = Struct({\n  _tag: Literal(\"Empty\")\n})\n\nconst causeFailEncoded = <E extends Schema.Any>(error: E) =>\n  Struct({\n    _tag: Literal(\"Fail\"),\n    error\n  })\n\nconst CauseInterruptEncoded = Struct({\n  _tag: Literal(\"Interrupt\"),\n  fiberId: FiberIdEncoded\n})\n\nlet causeEncodedId = 0\n\nconst causeEncoded = <E extends Schema.All, D extends Schema.All>(\n  error: E,\n  defect: D\n): SchemaClass<\n  CauseEncoded<Schema.Type<E>, Schema.Type<D>>,\n  CauseEncoded<Schema.Encoded<E>, Schema.Encoded<D>>,\n  Schema.Context<E> | Schema.Context<D>\n> => {\n  const error_ = asSchema(error)\n  const defect_ = asSchema(defect)\n  const suspended = suspend((): Schema<\n    CauseEncoded<Schema.Type<E>, Schema.Type<D>>,\n    CauseEncoded<Schema.Encoded<E>, Schema.Encoded<D>>,\n    Schema.Context<E> | Schema.Context<D>\n  > => out)\n  const out = Union(\n    CauseEmptyEncoded,\n    causeFailEncoded(error_),\n    causeDieEncoded(defect_),\n    CauseInterruptEncoded,\n    Struct({\n      _tag: Literal(\"Sequential\"),\n      left: suspended,\n      right: suspended\n    }),\n    Struct({\n      _tag: Literal(\"Parallel\"),\n      left: suspended,\n      right: suspended\n    })\n  ).annotations({\n    title: `CauseEncoded<${format(error)}>`,\n    [AST.JSONIdentifierAnnotationId]: `CauseEncoded${causeEncodedId++}`\n  })\n  return out\n}\n\nconst causeArbitrary = <E>(\n  error: LazyArbitrary<E>,\n  defect: LazyArbitrary<unknown>\n): LazyArbitrary<cause_.Cause<E>> =>\n(fc) =>\n  fc.letrec((tie) => ({\n    Empty: fc.record({ _tag: fc.constant(\"Empty\" as const) }),\n    Fail: fc.record({ _tag: fc.constant(\"Fail\" as const), error: error(fc) }),\n    Die: fc.record({ _tag: fc.constant(\"Die\" as const), defect: defect(fc) }),\n    Interrupt: fc.record({ _tag: fc.constant(\"Interrupt\" as const), fiberId: fiberIdArbitrary(fc) }),\n    Sequential: fc.record({ _tag: fc.constant(\"Sequential\" as const), left: tie(\"Cause\"), right: tie(\"Cause\") }),\n    Parallel: fc.record({ _tag: fc.constant(\"Parallel\" as const), left: tie(\"Cause\"), right: tie(\"Cause\") }),\n    Cause: fc.oneof(\n      tie(\"Empty\"),\n      tie(\"Fail\"),\n      tie(\"Die\"),\n      tie(\"Interrupt\"),\n      tie(\"Sequential\"),\n      tie(\"Parallel\")\n    ) as any as fastCheck_.Arbitrary<cause_.Cause<E>>\n  })).Cause.map(causeDecode)\n\nconst causePretty = <E>(error: pretty_.Pretty<E>): pretty_.Pretty<cause_.Cause<E>> => (cause) => {\n  const f = (cause: cause_.Cause<E>): string => {\n    switch (cause._tag) {\n      case \"Empty\":\n        return \"Cause.empty\"\n      case \"Fail\":\n        return `Cause.fail(${error(cause.error)})`\n      case \"Die\":\n        return `Cause.die(${cause_.pretty(cause)})`\n      case \"Interrupt\":\n        return `Cause.interrupt(${fiberIdPretty(cause.fiberId)})`\n      case \"Sequential\":\n        return `Cause.sequential(${f(cause.left)}, ${f(cause.right)})`\n      case \"Parallel\":\n        return `Cause.parallel(${f(cause.left)}, ${f(cause.right)})`\n    }\n  }\n  return f(cause)\n}\n\nconst causeParse = <A, D, R>(\n  decodeUnknown: ParseResult.DecodeUnknown<CauseEncoded<A, D>, R>\n): ParseResult.DeclarationDecodeUnknown<cause_.Cause<A>, R> =>\n(u, options, ast) =>\n  cause_.isCause(u) ?\n    toComposite(decodeUnknown(causeEncode(u), options), causeDecode, ast, u)\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface CauseFromSelf<E extends Schema.All, D extends Schema.All> extends\n  AnnotableDeclare<\n    CauseFromSelf<E, D>,\n    cause_.Cause<Schema.Type<E>>,\n    cause_.Cause<Schema.Encoded<E>>,\n    [E, D]\n  >\n{}\n\n/**\n * @category Cause transformations\n * @since 3.10.0\n */\nexport const CauseFromSelf = <E extends Schema.All, D extends Schema.All>({ defect, error }: {\n  readonly error: E\n  readonly defect: D\n}): CauseFromSelf<E, D> => {\n  return declare(\n    [error, defect],\n    {\n      decode: (error, defect) => causeParse(ParseResult.decodeUnknown(causeEncoded(error, defect))),\n      encode: (error, defect) => causeParse(ParseResult.encodeUnknown(causeEncoded(error, defect)))\n    },\n    {\n      typeConstructor: { _tag: \"effect/Cause\" },\n      title: `Cause<${error.ast}>`,\n      pretty: causePretty,\n      arbitrary: causeArbitrary\n    }\n  )\n}\n\nfunction causeDecode<E>(cause: CauseEncoded<E, unknown>): cause_.Cause<E> {\n  switch (cause._tag) {\n    case \"Empty\":\n      return cause_.empty\n    case \"Fail\":\n      return cause_.fail(cause.error)\n    case \"Die\":\n      return cause_.die(cause.defect)\n    case \"Interrupt\":\n      return cause_.interrupt(fiberIdDecode(cause.fiberId))\n    case \"Sequential\":\n      return cause_.sequential(causeDecode(cause.left), causeDecode(cause.right))\n    case \"Parallel\":\n      return cause_.parallel(causeDecode(cause.left), causeDecode(cause.right))\n  }\n}\n\nfunction causeEncode<E>(cause: cause_.Cause<E>): CauseEncoded<E, unknown> {\n  switch (cause._tag) {\n    case \"Empty\":\n      return { _tag: \"Empty\" }\n    case \"Fail\":\n      return { _tag: \"Fail\", error: cause.error }\n    case \"Die\":\n      return { _tag: \"Die\", defect: cause.defect }\n    case \"Interrupt\":\n      return { _tag: \"Interrupt\", fiberId: cause.fiberId }\n    case \"Sequential\":\n      return {\n        _tag: \"Sequential\",\n        left: causeEncode(cause.left),\n        right: causeEncode(cause.right)\n      }\n    case \"Parallel\":\n      return {\n        _tag: \"Parallel\",\n        left: causeEncode(cause.left),\n        right: causeEncode(cause.right)\n      }\n  }\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Cause<E extends Schema.All, D extends Schema.All> extends\n  transform<\n    SchemaClass<\n      CauseEncoded<Schema.Type<E>, Schema.Type<Defect>>,\n      CauseEncoded<Schema.Encoded<E>, Schema.Encoded<Defect>>,\n      Schema.Context<E> | Schema.Context<D>\n    >,\n    CauseFromSelf<SchemaClass<Schema.Type<E>>, SchemaClass<Schema.Type<D>>>\n  >\n{}\n\n/**\n * @category Cause transformations\n * @since 3.10.0\n */\nexport const Cause = <E extends Schema.All, D extends Schema.All>({ defect, error }: {\n  readonly error: E\n  readonly defect: D\n}): Cause<E, D> => {\n  const error_ = asSchema(error)\n  const defect_ = asSchema(defect)\n  const out = transform(\n    causeEncoded(error_, defect_),\n    CauseFromSelf({ error: typeSchema(error_), defect: typeSchema(defect_) }),\n    {\n      strict: false,\n      decode: (i) => causeDecode(i),\n      encode: (a) => causeEncode(a)\n    }\n  )\n  return out as any\n}\n\n/**\n * Defines a schema for handling JavaScript errors (`Error` instances) and other types of defects.\n * It decodes objects into Error instances if they match the expected structure (i.e., have a `message` and optionally a `name` and `stack`),\n * or converts other values to their string representations.\n *\n * When encoding, it converts `Error` instances back into plain objects containing only the error's name and message,\n * or other values into their string forms.\n *\n * This is useful for serializing and deserializing errors across network boundaries where error objects do not natively serialize.\n *\n * @category defect\n * @since 3.10.0\n */\nexport class Defect extends transform(\n  Unknown,\n  Unknown,\n  {\n    strict: true,\n    decode: (i) => {\n      if (Predicate.isObject(i) && \"message\" in i && typeof i.message === \"string\") {\n        const err = new Error(i.message, { cause: i })\n        if (\"name\" in i && typeof i.name === \"string\") {\n          err.name = i.name\n        }\n        err.stack = \"stack\" in i && typeof i.stack === \"string\" ? i.stack : \"\"\n        return err\n      }\n      return internalCause_.prettyErrorMessage(i)\n    },\n    encode: (a) => {\n      if (a instanceof Error) {\n        return {\n          name: a.name,\n          message: a.message\n          // no stack because of security reasons\n        }\n      }\n      return internalCause_.prettyErrorMessage(a)\n    }\n  }\n).annotations({ identifier: \"Defect\" }) {}\n\n/**\n * @category Exit utils\n * @since 3.10.0\n */\nexport type ExitEncoded<A, E, D> =\n  | {\n    readonly _tag: \"Failure\"\n    readonly cause: CauseEncoded<E, D>\n  }\n  | {\n    readonly _tag: \"Success\"\n    readonly value: A\n  }\n\nconst exitFailureEncoded = <E extends Schema.All, D extends Schema.All>(\n  error: E,\n  defect: D\n) =>\n  Struct({\n    _tag: Literal(\"Failure\"),\n    cause: causeEncoded(error, defect)\n  })\n\nconst exitSuccessEncoded = <A extends Schema.All>(\n  value: A\n) =>\n  Struct({\n    _tag: Literal(\"Success\"),\n    value\n  })\n\nconst exitEncoded = <A extends Schema.All, E extends Schema.All, D extends Schema.Any>(\n  value: A,\n  error: E,\n  defect: D\n) => {\n  return Union(\n    exitFailureEncoded(error, defect),\n    exitSuccessEncoded(value)\n  ).annotations({\n    title: `ExitEncoded<${format(value)}, ${format(error)}, ${format(defect)}>`\n  })\n}\n\nconst exitDecode = <A, E>(input: ExitEncoded<A, E, unknown>): exit_.Exit<A, E> => {\n  switch (input._tag) {\n    case \"Failure\":\n      return exit_.failCause(causeDecode(input.cause))\n    case \"Success\":\n      return exit_.succeed(input.value)\n  }\n}\n\nconst exitArbitrary = <A, E>(\n  value: LazyArbitrary<A>,\n  error: LazyArbitrary<E>,\n  defect: LazyArbitrary<unknown>\n): LazyArbitrary<exit_.Exit<A, E>> =>\n(fc) =>\n  fc.oneof(\n    fc.record({ _tag: fc.constant(\"Failure\" as const), cause: causeArbitrary(error, defect)(fc) }),\n    fc.record({ _tag: fc.constant(\"Success\" as const), value: value(fc) })\n  ).map(exitDecode)\n\nconst exitPretty =\n  <A, E>(value: pretty_.Pretty<A>, error: pretty_.Pretty<E>): pretty_.Pretty<exit_.Exit<A, E>> => (exit) =>\n    exit._tag === \"Failure\"\n      ? `Exit.failCause(${causePretty(error)(exit.cause)})`\n      : `Exit.succeed(${value(exit.value)})`\n\nconst exitParse = <A, R, E, ER>(\n  decodeUnknownValue: ParseResult.DecodeUnknown<A, R>,\n  decodeUnknownCause: ParseResult.DecodeUnknown<cause_.Cause<E>, ER>\n): ParseResult.DeclarationDecodeUnknown<exit_.Exit<A, E>, ER | R> =>\n(u, options, ast) =>\n  exit_.isExit(u) ?\n    exit_.match(u, {\n      onFailure: (cause) => toComposite(decodeUnknownCause(cause, options), exit_.failCause, ast, u),\n      onSuccess: (value) => toComposite(decodeUnknownValue(value, options), exit_.succeed, ast, u)\n    })\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface ExitFromSelf<A extends Schema.All, E extends Schema.All, D extends Schema.All>\n  extends\n    AnnotableDeclare<\n      ExitFromSelf<A, E, D>,\n      exit_.Exit<Schema.Type<A>, Schema.Type<E>>,\n      exit_.Exit<Schema.Encoded<A>, Schema.Encoded<E>>,\n      [A, E, D]\n    >\n{}\n\n/**\n * @category Exit transformations\n * @since 3.10.0\n */\nexport const ExitFromSelf = <A extends Schema.All, E extends Schema.All, D extends Schema.All>(\n  { defect, failure, success }: {\n    readonly failure: E\n    readonly success: A\n    readonly defect: D\n  }\n): ExitFromSelf<A, E, D> =>\n  declare(\n    [success, failure, defect],\n    {\n      decode: (success, failure, defect) =>\n        exitParse(\n          ParseResult.decodeUnknown(success),\n          ParseResult.decodeUnknown(CauseFromSelf({ error: failure, defect }))\n        ),\n      encode: (success, failure, defect) =>\n        exitParse(\n          ParseResult.encodeUnknown(success),\n          ParseResult.encodeUnknown(CauseFromSelf({ error: failure, defect }))\n        )\n    },\n    {\n      typeConstructor: { _tag: \"effect/Exit\" },\n      title: `Exit<${success.ast}, ${failure.ast}>`,\n      pretty: exitPretty,\n      arbitrary: exitArbitrary\n    }\n  )\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface Exit<A extends Schema.All, E extends Schema.All, D extends Schema.All> extends\n  transform<\n    Union<[\n      Struct<{\n        _tag: Literal<[\"Failure\"]>\n        cause: SchemaClass<\n          CauseEncoded<Schema.Type<E>, Schema.Type<D>>,\n          CauseEncoded<Schema.Encoded<E>, Schema.Encoded<D>>,\n          Schema.Context<E> | Schema.Context<D>\n        >\n      }>,\n      Struct<{\n        _tag: Literal<[\"Success\"]>\n        value: A\n      }>\n    ]>,\n    ExitFromSelf<SchemaClass<Schema.Type<A>>, SchemaClass<Schema.Type<E>>, SchemaClass<Schema.Type<D>>>\n  >\n{}\n\n/**\n * @category Exit transformations\n * @since 3.10.0\n */\nexport const Exit = <A extends Schema.All, E extends Schema.All, D extends Schema.All>(\n  { defect, failure, success }: {\n    readonly failure: E\n    readonly success: A\n    readonly defect: D\n  }\n): Exit<A, E, D> => {\n  const success_ = asSchema(success)\n  const failure_ = asSchema(failure)\n  const defect_ = asSchema(defect)\n  const out = transform(\n    exitEncoded(success_, failure_, defect_),\n    ExitFromSelf({ failure: typeSchema(failure_), success: typeSchema(success_), defect: typeSchema(defect_) }),\n    {\n      strict: false,\n      decode: (i) => exitDecode(i),\n      encode: (a) =>\n        a._tag === \"Failure\"\n          ? { _tag: \"Failure\", cause: a.cause } as const\n          : { _tag: \"Success\", value: a.value } as const\n    }\n  )\n  return out as any\n}\n\nconst hashSetArbitrary =\n  <A>(item: LazyArbitrary<A>, ctx: ArbitraryGenerationContext): LazyArbitrary<hashSet_.HashSet<A>> => (fc) => {\n    const items = fc.array(item(fc))\n    return (ctx.depthIdentifier !== undefined ? fc.oneof(ctx, fc.constant([]), items) : items).map(\n      hashSet_.fromIterable\n    )\n  }\n\nconst hashSetPretty = <A>(item: pretty_.Pretty<A>): pretty_.Pretty<hashSet_.HashSet<A>> => (set) =>\n  `HashSet(${Array.from(set).map((a) => item(a)).join(\", \")})`\n\nconst hashSetEquivalence = <A>(\n  item: Equivalence.Equivalence<A>\n): Equivalence.Equivalence<hashSet_.HashSet<A>> => {\n  const arrayEquivalence = array_.getEquivalence(item)\n  return Equivalence.make((a, b) => arrayEquivalence(Array.from(a), Array.from(b)))\n}\n\nconst hashSetParse = <A, R>(\n  decodeUnknown: ParseResult.DecodeUnknown<ReadonlyArray<A>, R>\n): ParseResult.DeclarationDecodeUnknown<hashSet_.HashSet<A>, R> =>\n(u, options, ast) =>\n  hashSet_.isHashSet(u) ?\n    toComposite(decodeUnknown(Array.from(u), options), hashSet_.fromIterable, ast, u)\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface HashSetFromSelf<Value extends Schema.Any> extends\n  AnnotableDeclare<\n    HashSetFromSelf<Value>,\n    hashSet_.HashSet<Schema.Type<Value>>,\n    hashSet_.HashSet<Schema.Encoded<Value>>,\n    [Value]\n  >\n{}\n\n/**\n * @category HashSet transformations\n * @since 3.10.0\n */\nexport const HashSetFromSelf = <Value extends Schema.Any>(\n  value: Value\n): HashSetFromSelf<Value> => {\n  return declare(\n    [value],\n    {\n      decode: (item) => hashSetParse(ParseResult.decodeUnknown(Array$(item))),\n      encode: (item) => hashSetParse(ParseResult.encodeUnknown(Array$(item)))\n    },\n    {\n      typeConstructor: { _tag: \"effect/HashSet\" },\n      description: `HashSet<${format(value)}>`,\n      pretty: hashSetPretty,\n      arbitrary: hashSetArbitrary,\n      equivalence: hashSetEquivalence\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface HashSet<Value extends Schema.Any>\n  extends transform<Array$<Value>, HashSetFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category HashSet transformations\n * @since 3.10.0\n */\nexport function HashSet<Value extends Schema.Any>(value: Value): HashSet<Value> {\n  return transform(\n    Array$(value),\n    HashSetFromSelf(typeSchema(asSchema(value))),\n    {\n      strict: true,\n      decode: (i) => hashSet_.fromIterable(i),\n      encode: (a) => Array.from(a)\n    }\n  )\n}\n\nconst hashMapArbitrary = <K, V>(\n  key: LazyArbitrary<K>,\n  value: LazyArbitrary<V>,\n  ctx: ArbitraryGenerationContext\n): LazyArbitrary<hashMap_.HashMap<K, V>> =>\n(fc) => {\n  const items = fc.array(fc.tuple(key(fc), value(fc)))\n  return (ctx.depthIdentifier !== undefined ? fc.oneof(ctx, fc.constant([]), items) : items).map(hashMap_.fromIterable)\n}\n\nconst hashMapPretty = <K, V>(\n  key: pretty_.Pretty<K>,\n  value: pretty_.Pretty<V>\n): pretty_.Pretty<hashMap_.HashMap<K, V>> =>\n(map) =>\n  `HashMap([${\n    Array.from(map)\n      .map(([k, v]) => `[${key(k)}, ${value(v)}]`)\n      .join(\", \")\n  }])`\n\nconst hashMapEquivalence = <K, V>(\n  key: Equivalence.Equivalence<K>,\n  value: Equivalence.Equivalence<V>\n): Equivalence.Equivalence<hashMap_.HashMap<K, V>> => {\n  const arrayEquivalence = array_.getEquivalence(\n    Equivalence.make<[K, V]>(([ka, va], [kb, vb]) => key(ka, kb) && value(va, vb))\n  )\n  return Equivalence.make((a, b) => arrayEquivalence(Array.from(a), Array.from(b)))\n}\n\nconst hashMapParse = <R, K, V>(\n  decodeUnknown: ParseResult.DecodeUnknown<ReadonlyArray<readonly [K, V]>, R>\n): ParseResult.DeclarationDecodeUnknown<hashMap_.HashMap<K, V>, R> =>\n(u, options, ast) =>\n  hashMap_.isHashMap(u) ?\n    toComposite(decodeUnknown(Array.from(u), options), hashMap_.fromIterable, ast, u)\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface HashMapFromSelf<K extends Schema.Any, V extends Schema.Any> extends\n  AnnotableDeclare<\n    HashMapFromSelf<K, V>,\n    hashMap_.HashMap<Schema.Type<K>, Schema.Type<V>>,\n    hashMap_.HashMap<Schema.Encoded<K>, Schema.Encoded<V>>,\n    [K, V]\n  >\n{}\n\n/**\n * @category HashMap transformations\n * @since 3.10.0\n */\nexport const HashMapFromSelf = <K extends Schema.Any, V extends Schema.Any>({ key, value }: {\n  readonly key: K\n  readonly value: V\n}): HashMapFromSelf<K, V> => {\n  return declare(\n    [key, value],\n    {\n      decode: (key, value) => hashMapParse(ParseResult.decodeUnknown(Array$(Tuple(key, value)))),\n      encode: (key, value) => hashMapParse(ParseResult.encodeUnknown(Array$(Tuple(key, value))))\n    },\n    {\n      typeConstructor: { _tag: \"effect/HashMap\" },\n      description: `HashMap<${format(key)}, ${format(value)}>`,\n      pretty: hashMapPretty,\n      arbitrary: hashMapArbitrary,\n      equivalence: hashMapEquivalence\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface HashMap<K extends Schema.Any, V extends Schema.Any>\n  extends transform<Array$<Tuple2<K, V>>, HashMapFromSelf<SchemaClass<Schema.Type<K>>, SchemaClass<Schema.Type<V>>>>\n{}\n\n/**\n * @category HashMap transformations\n * @since 3.10.0\n */\nexport const HashMap = <K extends Schema.Any, V extends Schema.Any>({ key, value }: {\n  readonly key: K\n  readonly value: V\n}): HashMap<K, V> => {\n  return transform(\n    Array$(Tuple(key, value)),\n    HashMapFromSelf({ key: typeSchema(asSchema(key)), value: typeSchema(asSchema(value)) }),\n    {\n      strict: true,\n      decode: (i) => hashMap_.fromIterable(i),\n      encode: (a) => Array.from(a)\n    }\n  )\n}\n\nconst listArbitrary =\n  <A>(item: LazyArbitrary<A>, ctx: ArbitraryGenerationContext): LazyArbitrary<list_.List<A>> => (fc) => {\n    const items = fc.array(item(fc))\n    return (ctx.depthIdentifier !== undefined ? fc.oneof(ctx, fc.constant([]), items) : items).map(list_.fromIterable)\n  }\n\nconst listPretty = <A>(item: pretty_.Pretty<A>): pretty_.Pretty<list_.List<A>> => (set) =>\n  `List(${Array.from(set).map((a) => item(a)).join(\", \")})`\n\nconst listEquivalence = <A>(\n  item: Equivalence.Equivalence<A>\n): Equivalence.Equivalence<list_.List<A>> => {\n  const arrayEquivalence = array_.getEquivalence(item)\n  return Equivalence.make((a, b) => arrayEquivalence(Array.from(a), Array.from(b)))\n}\n\nconst listParse = <A, R>(\n  decodeUnknown: ParseResult.DecodeUnknown<ReadonlyArray<A>, R>\n): ParseResult.DeclarationDecodeUnknown<list_.List<A>, R> =>\n(u, options, ast) =>\n  list_.isList(u) ?\n    toComposite(decodeUnknown(Array.from(u), options), list_.fromIterable, ast, u)\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface ListFromSelf<Value extends Schema.Any> extends\n  AnnotableDeclare<\n    ListFromSelf<Value>,\n    list_.List<Schema.Type<Value>>,\n    list_.List<Schema.Encoded<Value>>,\n    [Value]\n  >\n{}\n\n/**\n * @category List transformations\n * @since 3.10.0\n */\nexport const ListFromSelf = <Value extends Schema.Any>(\n  value: Value\n): ListFromSelf<Value> => {\n  return declare(\n    [value],\n    {\n      decode: (item) => listParse(ParseResult.decodeUnknown(Array$(item))),\n      encode: (item) => listParse(ParseResult.encodeUnknown(Array$(item)))\n    },\n    {\n      typeConstructor: { _tag: \"effect/List\" },\n      description: `List<${format(value)}>`,\n      pretty: listPretty,\n      arbitrary: listArbitrary,\n      equivalence: listEquivalence\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface List<Value extends Schema.Any>\n  extends transform<Array$<Value>, ListFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category List transformations\n * @since 3.10.0\n */\nexport function List<Value extends Schema.Any>(value: Value): List<Value> {\n  return transform(\n    Array$(value),\n    ListFromSelf(typeSchema(asSchema(value))),\n    {\n      strict: true,\n      decode: (i) => list_.fromIterable(i),\n      encode: (a) => Array.from(a)\n    }\n  )\n}\n\nconst sortedSetArbitrary = <A>(\n  item: LazyArbitrary<A>,\n  ord: Order.Order<A>,\n  ctx: ArbitraryGenerationContext\n): LazyArbitrary<sortedSet_.SortedSet<A>> =>\n(fc) => {\n  const items = fc.array(item(fc))\n  return (ctx.depthIdentifier !== undefined ? fc.oneof(ctx, fc.constant([]), items) : items).map((as) =>\n    sortedSet_.fromIterable(as, ord)\n  )\n}\n\nconst sortedSetPretty = <A>(item: pretty_.Pretty<A>): pretty_.Pretty<sortedSet_.SortedSet<A>> => (set) =>\n  `new SortedSet([${Array.from(sortedSet_.values(set)).map((a) => item(a)).join(\", \")}])`\n\nconst sortedSetParse = <A, R>(\n  decodeUnknown: ParseResult.DecodeUnknown<ReadonlyArray<A>, R>,\n  ord: Order.Order<A>\n): ParseResult.DeclarationDecodeUnknown<sortedSet_.SortedSet<A>, R> =>\n(u, options, ast) =>\n  sortedSet_.isSortedSet(u) ?\n    toComposite(\n      decodeUnknown(Array.from(sortedSet_.values(u)), options),\n      (as): sortedSet_.SortedSet<A> => sortedSet_.fromIterable(as, ord),\n      ast,\n      u\n    )\n    : ParseResult.fail(new ParseResult.Type(ast, u))\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface SortedSetFromSelf<Value extends Schema.Any> extends\n  AnnotableDeclare<\n    SortedSetFromSelf<Value>,\n    sortedSet_.SortedSet<Schema.Type<Value>>,\n    sortedSet_.SortedSet<Schema.Encoded<Value>>,\n    [Value]\n  >\n{}\n\n/**\n * @category SortedSet transformations\n * @since 3.10.0\n */\nexport const SortedSetFromSelf = <Value extends Schema.Any>(\n  value: Value,\n  ordA: Order.Order<Schema.Type<Value>>,\n  ordI: Order.Order<Schema.Encoded<Value>>\n): SortedSetFromSelf<Value> => {\n  return declare(\n    [value],\n    {\n      decode: (item) => sortedSetParse(ParseResult.decodeUnknown(Array$(item)), ordA),\n      encode: (item) => sortedSetParse(ParseResult.encodeUnknown(Array$(item)), ordI)\n    },\n    {\n      typeConstructor: { _tag: \"effect/SortedSet\" },\n      description: `SortedSet<${format(value)}>`,\n      pretty: sortedSetPretty,\n      arbitrary: (arb, ctx) => sortedSetArbitrary(arb, ordA, ctx),\n      equivalence: () => sortedSet_.getEquivalence<Schema.Type<Value>>()\n    }\n  )\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface SortedSet<Value extends Schema.Any>\n  extends transform<Array$<Value>, SortedSetFromSelf<SchemaClass<Schema.Type<Value>>>>\n{}\n\n/**\n * @category SortedSet transformations\n * @since 3.10.0\n */\nexport function SortedSet<Value extends Schema.Any>(\n  value: Value,\n  ordA: Order.Order<Schema.Type<Value>>\n): SortedSet<Value> {\n  const to = typeSchema(asSchema(value))\n  return transform(\n    Array$(value),\n    SortedSetFromSelf<typeof to>(to, ordA, ordA),\n    {\n      strict: true,\n      decode: (i) => sortedSet_.fromIterable(i, ordA),\n      encode: (a) => Array.from(sortedSet_.values(a))\n    }\n  )\n}\n\n/**\n * Converts an arbitrary value to a `boolean` by testing whether it is truthy.\n * Uses `!!val` to coerce the value to a `boolean`.\n *\n * @see https://developer.mozilla.org/docs/Glossary/Truthy\n *\n * @category boolean constructors\n * @since 3.10.0\n */\nexport class BooleanFromUnknown extends transform(\n  Unknown,\n  Boolean$,\n  {\n    strict: true,\n    decode: (i) => Predicate.isTruthy(i),\n    encode: identity\n  }\n).annotations({ identifier: \"BooleanFromUnknown\" }) {}\n\n/**\n * Converts an `string` value into its corresponding `boolean`\n * (\"true\" as `true` and \"false\" as `false`).\n *\n * @category boolean transformations\n * @since 3.11.0\n */\nexport class BooleanFromString extends transform(\n  Literal(\"true\", \"false\").annotations({ description: \"a string to be decoded into a boolean\" }),\n  Boolean$,\n  {\n    strict: true,\n    decode: (i) => i === \"true\",\n    encode: (a) => a ? \"true\" : \"false\"\n  }\n).annotations({ identifier: \"BooleanFromString\" }) {}\n\n/**\n * @category Config validations\n * @since 3.10.0\n */\nexport const Config = <A, I extends string>(name: string, schema: Schema<A, I>): config_.Config<A> => {\n  const decodeUnknownEither = ParseResult.decodeUnknownEither(schema)\n  return config_.string(name).pipe(\n    config_.mapOrFail((s) =>\n      decodeUnknownEither(s).pipe(\n        either_.mapLeft((error) => configError_.InvalidData([], ParseResult.TreeFormatter.formatIssueSync(error)))\n      )\n    )\n  )\n}\n\n// ---------------------------------------------\n// Serializable\n// ---------------------------------------------\n\n/**\n * @since 3.10.0\n * @category symbol\n */\nexport const symbolSerializable: unique symbol = Symbol.for(\n  \"effect/Schema/Serializable/symbol\"\n)\n\n/**\n * The `Serializable` trait allows objects to define their own schema for\n * serialization.\n *\n * @since 3.10.0\n * @category model\n */\nexport interface Serializable<A, I, R> {\n  readonly [symbolSerializable]: Schema<A, I, R>\n}\n\n/**\n * @since 3.10.0\n * @category model\n */\nexport declare namespace Serializable {\n  /**\n   * @since 3.10.0\n   */\n  export type Type<T> = T extends Serializable<infer A, infer _I, infer _R> ? A : never\n  /**\n   * @since 3.10.0\n   */\n  export type Encoded<T> = T extends Serializable<infer _A, infer I, infer _R> ? I : never\n  /**\n   * @since 3.10.0\n   */\n  export type Context<T> = T extends Serializable<infer _A, infer _I, infer R> ? R : never\n  /**\n   * @since 3.10.0\n   */\n  export type Any = Serializable<any, any, unknown>\n  /**\n   * @since 3.10.0\n   */\n  export type All =\n    | Any\n    | Serializable<any, never, unknown>\n    | Serializable<never, any, unknown>\n    | Serializable<never, never, unknown>\n}\n\n/**\n * @since 3.10.0\n */\nexport const asSerializable = <S extends Serializable.All>(\n  serializable: S\n): Serializable<Serializable.Type<S>, Serializable.Encoded<S>, Serializable.Context<S>> => serializable as any\n\n/**\n * @since 3.10.0\n * @category accessor\n */\nexport const serializableSchema = <A, I, R>(self: Serializable<A, I, R>): Schema<A, I, R> => self[symbolSerializable]\n\n/**\n * @since 3.10.0\n * @category encoding\n */\nexport const serialize = <A, I, R>(self: Serializable<A, I, R>): Effect.Effect<I, ParseResult.ParseError, R> =>\n  encodeUnknown(self[symbolSerializable])(self)\n\n/**\n * @since 3.10.0\n * @category decoding\n */\nexport const deserialize: {\n  (value: unknown): <A, I, R>(self: Serializable<A, I, R>) => Effect.Effect<A, ParseResult.ParseError, R>\n  <A, I, R>(self: Serializable<A, I, R>, value: unknown): Effect.Effect<A, ParseResult.ParseError, R>\n} = dual(\n  2,\n  <A, I, R>(self: Serializable<A, I, R>, value: unknown): Effect.Effect<A, ParseResult.ParseError, R> =>\n    decodeUnknown(self[symbolSerializable])(value)\n)\n\n/**\n * @since 3.10.0\n * @category symbol\n */\nexport const symbolWithResult: unique symbol = Symbol.for(\n  \"effect/Schema/Serializable/symbolResult\"\n)\n\n/**\n * The `WithResult` trait is designed to encapsulate the outcome of an\n * operation, distinguishing between success and failure cases. Each case is\n * associated with a schema that defines the structure and types of the success\n * or failure data.\n *\n * @since 3.10.0\n * @category model\n */\nexport interface WithResult<Success, SuccessEncoded, Failure, FailureEncoded, ResultR> {\n  readonly [symbolWithResult]: {\n    readonly success: Schema<Success, SuccessEncoded, ResultR>\n    readonly failure: Schema<Failure, FailureEncoded, ResultR>\n  }\n}\n\n/**\n * @since 3.10.0\n * @category model\n */\nexport declare namespace WithResult {\n  /**\n   * @since 3.10.0\n   */\n  export type Success<T> = T extends WithResult<infer _A, infer _I, infer _E, infer _EI, infer _R> ? _A : never\n  /**\n   * @since 3.10.0\n   */\n  export type SuccessEncoded<T> = T extends WithResult<infer _A, infer _I, infer _E, infer _EI, infer _R> ? _I : never\n  /**\n   * @since 3.10.0\n   */\n  export type Failure<T> = T extends WithResult<infer _A, infer _I, infer _E, infer _EI, infer _R> ? _E : never\n  /**\n   * @since 3.10.0\n   */\n  export type FailureEncoded<T> = T extends WithResult<infer _A, infer _I, infer _E, infer _EI, infer _R> ? _EI : never\n\n  /**\n   * @since 3.10.0\n   */\n  export type Context<T> = T extends WithResult<infer _SA, infer _SI, infer _FA, infer _FI, infer R> ? R : never\n  /**\n   * @since 3.10.0\n   */\n  export type Any = WithResult<any, any, any, any, unknown>\n  /**\n   * @since 3.10.0\n   */\n  export type All =\n    | Any\n    | WithResult<any, any, never, never, unknown>\n}\n\n/**\n * @since 3.10.0\n */\nexport const asWithResult = <WR extends WithResult.All>(\n  withExit: WR\n): WithResult<\n  WithResult.Success<WR>,\n  WithResult.SuccessEncoded<WR>,\n  WithResult.Failure<WR>,\n  WithResult.FailureEncoded<WR>,\n  WithResult.Context<WR>\n> => withExit as any\n\n/**\n * @since 3.10.0\n * @category accessor\n */\nexport const failureSchema = <SA, SI, FA, FI, R>(self: WithResult<SA, SI, FA, FI, R>): Schema<FA, FI, R> =>\n  self[symbolWithResult].failure\n\n/**\n * @since 3.10.0\n * @category accessor\n */\nexport const successSchema = <SA, SI, FA, FI, R>(self: WithResult<SA, SI, FA, FI, R>): Schema<SA, SI, R> =>\n  self[symbolWithResult].success\n\nconst exitSchemaCache = globalValue(\n  \"effect/Schema/Serializable/exitSchemaCache\",\n  () => new WeakMap<object, Schema<any, any, any>>()\n)\n\n/**\n * @since 3.10.0\n * @category accessor\n */\nexport const exitSchema = <SA, SI, FA, FI, R>(self: WithResult<SA, SI, FA, FI, R>): Schema<\n  exit_.Exit<SA, FA>,\n  ExitEncoded<SI, FI, unknown>,\n  R\n> => {\n  const proto = Object.getPrototypeOf(self)\n  if (!(symbolWithResult in proto)) {\n    return Exit({\n      failure: failureSchema(self),\n      success: successSchema(self),\n      defect: Defect\n    })\n  }\n  let schema = exitSchemaCache.get(proto)\n  if (schema === undefined) {\n    schema = Exit({\n      failure: failureSchema(self),\n      success: successSchema(self),\n      defect: Defect\n    })\n    exitSchemaCache.set(proto, schema)\n  }\n  return schema\n}\n\n/**\n * @since 3.10.0\n * @category encoding\n */\nexport const serializeFailure: {\n  <FA>(value: FA): <SA, SI, FI, R>(\n    self: WithResult<SA, SI, FA, FI, R>\n  ) => Effect.Effect<FI, ParseResult.ParseError, R>\n  <SA, SI, FA, FI, R>(self: WithResult<SA, SI, FA, FI, R>, value: FA): Effect.Effect<FI, ParseResult.ParseError, R>\n} = dual(\n  2,\n  <SA, SI, FA, FI, R>(self: WithResult<SA, SI, FA, FI, R>, value: FA): Effect.Effect<FI, ParseResult.ParseError, R> =>\n    encode(self[symbolWithResult].failure)(value)\n)\n\n/**\n * @since 3.10.0\n * @category decoding\n */\nexport const deserializeFailure: {\n  (\n    value: unknown\n  ): <SA, SI, FA, FI, R>(self: WithResult<SA, SI, FA, FI, R>) => Effect.Effect<FA, ParseResult.ParseError, R>\n  <SA, SI, FA, FI, R>(self: WithResult<SA, SI, FA, FI, R>, value: unknown): Effect.Effect<FA, ParseResult.ParseError, R>\n} = dual(\n  2,\n  <SA, SI, FA, FI, R>(\n    self: WithResult<SA, SI, FA, FI, R>,\n    value: unknown\n  ): Effect.Effect<FA, ParseResult.ParseError, R> => decodeUnknown(self[symbolWithResult].failure)(value)\n)\n\n/**\n * @since 3.10.0\n * @category encoding\n */\nexport const serializeSuccess: {\n  <SA>(value: SA): <SI, FA, FI, R>(\n    self: WithResult<SA, SI, FA, FI, R>\n  ) => Effect.Effect<SI, ParseResult.ParseError, R>\n  <SA, SI, FA, FI, R>(self: WithResult<SA, SI, FA, FI, R>, value: SA): Effect.Effect<SI, ParseResult.ParseError, R>\n} = dual(\n  2,\n  <SA, SI, FA, FI, R>(self: WithResult<SA, SI, FA, FI, R>, value: SA): Effect.Effect<SI, ParseResult.ParseError, R> =>\n    encode(self[symbolWithResult].success)(value)\n)\n\n/**\n * @since 3.10.0\n * @category decoding\n */\nexport const deserializeSuccess: {\n  (value: unknown): <SA, SI, FA, FI, R>(\n    self: WithResult<SA, SI, FA, FI, R>\n  ) => Effect.Effect<SA, ParseResult.ParseError, R>\n  <SA, SI, FA, FI, R>(self: WithResult<SA, SI, FA, FI, R>, value: unknown): Effect.Effect<SA, ParseResult.ParseError, R>\n} = dual(\n  2,\n  <SA, SI, FA, FI, R>(\n    self: WithResult<SA, SI, FA, FI, R>,\n    value: unknown\n  ): Effect.Effect<SA, ParseResult.ParseError, R> => decodeUnknown(self[symbolWithResult].success)(value)\n)\n\n/**\n * @since 3.10.0\n * @category encoding\n */\nexport const serializeExit: {\n  <SA, FA>(value: exit_.Exit<SA, FA>): <SI, FI, R>(\n    self: WithResult<SA, SI, FA, FI, R>\n  ) => Effect.Effect<ExitEncoded<SI, FI, unknown>, ParseResult.ParseError, R>\n  <SA, SI, FA, FI, R>(\n    self: WithResult<SA, SI, FA, FI, R>,\n    value: exit_.Exit<SA, FA>\n  ): Effect.Effect<ExitEncoded<SI, FI, unknown>, ParseResult.ParseError, R>\n} = dual(2, <SA, SI, FA, FI, R>(\n  self: WithResult<SA, SI, FA, FI, R>,\n  value: exit_.Exit<SA, FA>\n): Effect.Effect<ExitEncoded<SI, FI, unknown>, ParseResult.ParseError, R> => encode(exitSchema(self))(value))\n\n/**\n * @since 3.10.0\n * @category decoding\n */\nexport const deserializeExit: {\n  (value: unknown): <SA, SI, FA, FI, R>(\n    self: WithResult<SA, SI, FA, FI, R>\n  ) => Effect.Effect<exit_.Exit<SA, FA>, ParseResult.ParseError, R>\n  <SA, SI, FA, FI, R>(\n    self: WithResult<SA, SI, FA, FI, R>,\n    value: unknown\n  ): Effect.Effect<exit_.Exit<SA, FA>, ParseResult.ParseError, R>\n} = dual(2, <SA, SI, FA, FI, R>(\n  self: WithResult<SA, SI, FA, FI, R>,\n  value: unknown\n): Effect.Effect<exit_.Exit<SA, FA>, ParseResult.ParseError, R> => decodeUnknown(exitSchema(self))(value))\n\n// ---------------------------------------------\n// SerializableWithResult\n// ---------------------------------------------\n\n/**\n * The `SerializableWithResult` trait is specifically designed to model remote\n * procedures that require serialization of their input and output, managing\n * both successful and failed outcomes.\n *\n * This trait combines functionality from both the `Serializable` and `WithResult`\n * traits to handle data serialization and the bifurcation of operation results\n * into success or failure categories.\n *\n * @since 3.10.0\n * @category model\n */\nexport interface SerializableWithResult<\n  A,\n  I,\n  R,\n  Success,\n  SuccessEncoded,\n  Failure,\n  FailureEncoded,\n  ResultR\n> extends Serializable<A, I, R>, WithResult<Success, SuccessEncoded, Failure, FailureEncoded, ResultR> {}\n\n/**\n * @since 3.10.0\n * @category model\n */\nexport declare namespace SerializableWithResult {\n  /**\n   * @since 3.10.0\n   */\n  export type Context<P> = P extends\n    SerializableWithResult<infer _S, infer _SI, infer SR, infer _A, infer _AI, infer _E, infer _EI, infer RR> ? SR | RR\n    : never\n  /**\n   * @since 3.10.0\n   */\n  export type Any = SerializableWithResult<any, any, any, any, any, any, any, unknown>\n  /**\n   * @since 3.10.0\n   */\n  export type All =\n    | Any\n    | SerializableWithResult<any, any, any, any, any, never, never, unknown>\n}\n\n/**\n * @since 3.10.0\n */\nexport const asSerializableWithResult = <SWR extends SerializableWithResult.All>(\n  procedure: SWR\n): SerializableWithResult<\n  Serializable.Type<SWR>,\n  Serializable.Encoded<SWR>,\n  Serializable.Context<SWR>,\n  WithResult.Success<SWR>,\n  WithResult.SuccessEncoded<SWR>,\n  WithResult.Failure<SWR>,\n  WithResult.FailureEncoded<SWR>,\n  WithResult.Context<SWR>\n> => procedure as any\n\n/**\n * @since 3.10.0\n */\nexport interface TaggedRequest<\n  Tag extends string,\n  A,\n  I,\n  R,\n  SuccessType,\n  SuccessEncoded,\n  FailureType,\n  FailureEncoded,\n  ResultR\n> extends\n  Request.Request<SuccessType, FailureType>,\n  SerializableWithResult<\n    A,\n    I,\n    R,\n    SuccessType,\n    SuccessEncoded,\n    FailureType,\n    FailureEncoded,\n    ResultR\n  >\n{\n  readonly _tag: Tag\n}\n\n/**\n * @since 3.10.0\n */\nexport declare namespace TaggedRequest {\n  /**\n   * @since 3.10.0\n   */\n  export type Any = TaggedRequest<string, any, any, any, any, any, any, any, unknown>\n  /**\n   * @since 3.10.0\n   */\n  export type All =\n    | Any\n    | TaggedRequest<string, any, any, any, any, any, never, never, unknown>\n}\n\n/**\n * @category api interface\n * @since 3.10.0\n */\nexport interface TaggedRequestClass<\n  Self,\n  Tag extends string,\n  Payload extends Struct.Fields,\n  Success extends Schema.All,\n  Failure extends Schema.All\n> extends\n  Class<\n    Self,\n    Payload,\n    Struct.Encoded<Payload>,\n    Struct.Context<Payload>,\n    Struct.Constructor<Omit<Payload, \"_tag\">>,\n    TaggedRequest<\n      Tag,\n      Self,\n      Struct.Encoded<Payload>,\n      Struct.Context<Payload>,\n      Schema.Type<Success>,\n      Schema.Encoded<Success>,\n      Schema.Type<Failure>,\n      Schema.Encoded<Failure>,\n      Schema.Context<Success> | Schema.Context<Failure>\n    >,\n    {}\n  >\n{\n  readonly _tag: Tag\n  readonly success: Success\n  readonly failure: Failure\n}\n\n/**\n * @example\n * ```ts\n * import { Schema } from \"effect\"\n *\n * class MyRequest extends Schema.TaggedRequest<MyRequest>(\"MyRequest\")(\"MyRequest\", {\n *  failure: Schema.String,\n *  success: Schema.Number,\n *  payload: { id: Schema.String }\n * }) {}\n * ```\n *\n * @category classes\n * @since 3.10.0\n */\nexport const TaggedRequest =\n  <Self = never>(identifier?: string) =>\n  <Tag extends string, Payload extends Struct.Fields, Success extends Schema.All, Failure extends Schema.All>(\n    tag: Tag,\n    options: {\n      failure: Failure\n      success: Success\n      payload: Payload\n    },\n    annotations?: ClassAnnotations<Self, Simplify<Struct.Type<{ readonly _tag: tag<Tag> } & Payload>>>\n  ): [Self] extends [never] ? MissingSelfGeneric<\"TaggedRequest\", `\"Tag\", SuccessSchema, FailureSchema, `>\n    : TaggedRequestClass<\n      Self,\n      Tag,\n      { readonly _tag: tag<Tag> } & Payload,\n      Success,\n      Failure\n    > =>\n  {\n    const taggedFields = extendFields({ _tag: getClassTag(tag) }, options.payload)\n    return class TaggedRequestClass extends makeClass({\n      kind: \"TaggedRequest\",\n      identifier: identifier ?? tag,\n      schema: Struct(taggedFields),\n      fields: taggedFields,\n      Base: Request.Class<any, any, { readonly _tag: string }>,\n      annotations\n    }) {\n      static _tag = tag\n      static success = options.success\n      static failure = options.failure\n      get [symbolSerializable]() {\n        return this.constructor\n      }\n      get [symbolWithResult]() {\n        return {\n          failure: options.failure,\n          success: options.success\n        }\n      }\n    } as any\n  }\n\n// -------------------------------------------------------------------------------------------------\n// Equivalence compiler\n// -------------------------------------------------------------------------------------------------\n\n/**\n * Given a schema `Schema<A, I, R>`, returns an `Equivalence` instance for `A`.\n *\n * @category Equivalence\n * @since 3.10.0\n */\nexport const equivalence = <A, I, R>(schema: Schema<A, I, R>): Equivalence.Equivalence<A> => go(schema.ast, [])\n\nconst getEquivalenceAnnotation = AST.getAnnotation<AST.EquivalenceAnnotation<any, any>>(AST.EquivalenceAnnotationId)\n\nconst go = (ast: AST.AST, path: ReadonlyArray<PropertyKey>): Equivalence.Equivalence<any> => {\n  const hook = getEquivalenceAnnotation(ast)\n  if (option_.isSome(hook)) {\n    switch (ast._tag) {\n      case \"Declaration\":\n        return hook.value(...ast.typeParameters.map((tp) => go(tp, path)))\n      case \"Refinement\":\n        return hook.value(go(ast.from, path))\n      default:\n        return hook.value()\n    }\n  }\n  switch (ast._tag) {\n    case \"NeverKeyword\":\n      throw new Error(errors_.getEquivalenceUnsupportedErrorMessage(ast, path))\n    case \"Transformation\":\n      return go(ast.to, path)\n    case \"Declaration\":\n    case \"Literal\":\n    case \"StringKeyword\":\n    case \"TemplateLiteral\":\n    case \"UniqueSymbol\":\n    case \"SymbolKeyword\":\n    case \"UnknownKeyword\":\n    case \"AnyKeyword\":\n    case \"NumberKeyword\":\n    case \"BooleanKeyword\":\n    case \"BigIntKeyword\":\n    case \"UndefinedKeyword\":\n    case \"VoidKeyword\":\n    case \"Enums\":\n    case \"ObjectKeyword\":\n      return Equal.equals\n    case \"Refinement\":\n      return go(ast.from, path)\n    case \"Suspend\": {\n      const get = util_.memoizeThunk(() => go(ast.f(), path))\n      return (a, b) => get()(a, b)\n    }\n    case \"TupleType\": {\n      const elements = ast.elements.map((element, i) => go(element.type, path.concat(i)))\n      const rest = ast.rest.map((annotatedAST) => go(annotatedAST.type, path))\n      return Equivalence.make((a, b) => {\n        if (!Array.isArray(a) || !Array.isArray(b)) {\n          return false\n        }\n        const len = a.length\n        if (len !== b.length) {\n          return false\n        }\n        // ---------------------------------------------\n        // handle elements\n        // ---------------------------------------------\n        let i = 0\n        for (; i < Math.min(len, ast.elements.length); i++) {\n          if (!elements[i](a[i], b[i])) {\n            return false\n          }\n        }\n        // ---------------------------------------------\n        // handle rest element\n        // ---------------------------------------------\n        if (array_.isNonEmptyReadonlyArray(rest)) {\n          const [head, ...tail] = rest\n          for (; i < len - tail.length; i++) {\n            if (!head(a[i], b[i])) {\n              return false\n            }\n          }\n          // ---------------------------------------------\n          // handle post rest elements\n          // ---------------------------------------------\n          for (let j = 0; j < tail.length; j++) {\n            i += j\n            if (!tail[j](a[i], b[i])) {\n              return false\n            }\n          }\n        }\n        return true\n      })\n    }\n    case \"TypeLiteral\": {\n      if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) {\n        return Equal.equals\n      }\n      const propertySignatures = ast.propertySignatures.map((ps) => go(ps.type, path.concat(ps.name)))\n      const indexSignatures = ast.indexSignatures.map((is) => go(is.type, path))\n      return Equivalence.make((a, b) => {\n        if (!Predicate.isRecord(a) || !Predicate.isRecord(b)) {\n          return false\n        }\n        const aStringKeys = Object.keys(a)\n        const aSymbolKeys = Object.getOwnPropertySymbols(a)\n        // ---------------------------------------------\n        // handle property signatures\n        // ---------------------------------------------\n        for (let i = 0; i < propertySignatures.length; i++) {\n          const ps = ast.propertySignatures[i]\n          const name = ps.name\n          const aHas = Object.prototype.hasOwnProperty.call(a, name)\n          const bHas = Object.prototype.hasOwnProperty.call(b, name)\n          if (ps.isOptional) {\n            if (aHas !== bHas) {\n              return false\n            }\n          }\n          if (aHas && bHas && !propertySignatures[i](a[name], b[name])) {\n            return false\n          }\n        }\n        // ---------------------------------------------\n        // handle index signatures\n        // ---------------------------------------------\n        let bSymbolKeys: Array<symbol> | undefined\n        let bStringKeys: Array<string> | undefined\n        for (let i = 0; i < indexSignatures.length; i++) {\n          const is = ast.indexSignatures[i]\n          const encodedParameter = AST.getEncodedParameter(is.parameter)\n          const isSymbol = AST.isSymbolKeyword(encodedParameter)\n          if (isSymbol) {\n            bSymbolKeys = bSymbolKeys || Object.getOwnPropertySymbols(b)\n            if (aSymbolKeys.length !== bSymbolKeys.length) {\n              return false\n            }\n          } else {\n            bStringKeys = bStringKeys || Object.keys(b)\n            if (aStringKeys.length !== bStringKeys.length) {\n              return false\n            }\n          }\n          const aKeys = isSymbol ? aSymbolKeys : aStringKeys\n          for (let j = 0; j < aKeys.length; j++) {\n            const key = aKeys[j]\n            if (\n              !Object.prototype.hasOwnProperty.call(b, key) || !indexSignatures[i](a[key], b[key])\n            ) {\n              return false\n            }\n          }\n        }\n        return true\n      })\n    }\n    case \"Union\": {\n      const searchTree = ParseResult.getSearchTree(ast.types, true)\n      const ownKeys = Reflect.ownKeys(searchTree.keys)\n      const len = ownKeys.length\n      return Equivalence.make((a, b) => {\n        let candidates: Array<AST.AST> = []\n        if (len > 0 && Predicate.isRecordOrArray(a)) {\n          for (let i = 0; i < len; i++) {\n            const name = ownKeys[i]\n            const buckets = searchTree.keys[name].buckets\n            if (Object.prototype.hasOwnProperty.call(a, name)) {\n              const literal = String(a[name])\n              if (Object.prototype.hasOwnProperty.call(buckets, literal)) {\n                candidates = candidates.concat(buckets[literal])\n              }\n            }\n          }\n        }\n        if (searchTree.otherwise.length > 0) {\n          candidates = candidates.concat(searchTree.otherwise)\n        }\n        const tuples = candidates.map((ast) => [go(ast, path), ParseResult.is({ ast } as any)] as const)\n        for (let i = 0; i < tuples.length; i++) {\n          const [equivalence, is] = tuples[i]\n          if (is(a) && is(b)) {\n            if (equivalence(a, b)) {\n              return true\n            }\n          }\n        }\n        return false\n      })\n    }\n  }\n}\n\nconst SymbolStruct = TaggedStruct(\"symbol\", {\n  key: String$\n}).annotations({ description: \"an object to be decoded into a globally shared symbol\" })\n\nconst SymbolFromStruct = transformOrFail(\n  SymbolStruct,\n  SymbolFromSelf,\n  {\n    strict: true,\n    decode: (i) => decodeSymbol(i.key),\n    encode: (a, _, ast) => ParseResult.map(encodeSymbol(a, ast), (key) => SymbolStruct.make({ key }))\n  }\n)\n\n/** @ignore */\nclass PropertyKey$ extends Union(String$, Number$, SymbolFromStruct).annotations({ identifier: \"PropertyKey\" }) {}\n\nexport {\n  /**\n   * @since 3.12.5\n   */\n  PropertyKey$ as PropertyKey\n}\n\n/**\n * @category ArrayFormatter\n * @since 3.12.5\n */\nexport class ArrayFormatterIssue extends Struct({\n  _tag: propertySignature(Literal(\n    \"Pointer\",\n    \"Unexpected\",\n    \"Missing\",\n    \"Composite\",\n    \"Refinement\",\n    \"Transformation\",\n    \"Type\",\n    \"Forbidden\"\n  )).annotations({ description: \"The tag identifying the type of parse issue\" }),\n  path: propertySignature(Array$(PropertyKey$)).annotations({\n    description: \"The path to the property where the issue occurred\"\n  }),\n  message: propertySignature(String$).annotations({ description: \"A descriptive message explaining the issue\" })\n}).annotations({\n  identifier: \"ArrayFormatterIssue\",\n  description: \"Represents an issue returned by the ArrayFormatter formatter\"\n}) {}\n"
  },
  {
    "path": "packages/effect/src/SchemaAST.ts",
    "content": "/**\n * @since 3.10.0\n */\n\nimport * as Arr from \"./Array.js\"\nimport type { Effect } from \"./Effect.js\"\nimport type { Equivalence } from \"./Equivalence.js\"\nimport { dual, identity } from \"./Function.js\"\nimport { globalValue } from \"./GlobalValue.js\"\nimport * as Inspectable from \"./Inspectable.js\"\nimport * as errors_ from \"./internal/schema/errors.js\"\nimport * as util_ from \"./internal/schema/util.js\"\nimport * as Number from \"./Number.js\"\nimport * as Option from \"./Option.js\"\nimport * as Order from \"./Order.js\"\nimport type { ParseIssue } from \"./ParseResult.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport * as regexp from \"./RegExp.js\"\nimport type { Concurrency } from \"./Types.js\"\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport type AST =\n  | Declaration\n  | Literal\n  | UniqueSymbol\n  | UndefinedKeyword\n  | VoidKeyword\n  | NeverKeyword\n  | UnknownKeyword\n  | AnyKeyword\n  | StringKeyword\n  | NumberKeyword\n  | BooleanKeyword\n  | BigIntKeyword\n  | SymbolKeyword\n  | ObjectKeyword\n  | Enums\n  | TemplateLiteral\n  // possible transformations\n  | Refinement\n  | TupleType\n  | TypeLiteral\n  | Union\n  | Suspend\n  // transformations\n  | Transformation\n\n// -------------------------------------------------------------------------------------\n// annotations\n// -------------------------------------------------------------------------------------\n\n/**\n * @category annotations\n * @since 3.19.0\n * @experimental\n */\nexport type TypeConstructorAnnotation = {\n  readonly _tag: string\n  [key: PropertyKey]: unknown\n}\n\n/**\n * @category annotations\n * @since 3.19.0\n * @experimental\n */\nexport const TypeConstructorAnnotationId: unique symbol = Symbol.for(\"effect/annotation/TypeConstructor\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type BrandAnnotation = Arr.NonEmptyReadonlyArray<string | symbol>\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const BrandAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Brand\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type SchemaIdAnnotation = string | symbol\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const SchemaIdAnnotationId: unique symbol = Symbol.for(\"effect/annotation/SchemaId\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type MessageAnnotation = (issue: ParseIssue) => string | Effect<string> | {\n  readonly message: string | Effect<string>\n  readonly override: boolean\n}\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const MessageAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Message\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type MissingMessageAnnotation = () => string | Effect<string>\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const MissingMessageAnnotationId: unique symbol = Symbol.for(\"effect/annotation/MissingMessage\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type IdentifierAnnotation = string\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const IdentifierAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Identifier\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type TitleAnnotation = string\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const TitleAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Title\")\n\n/** @internal */\nexport const AutoTitleAnnotationId: unique symbol = Symbol.for(\"effect/annotation/AutoTitle\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type DescriptionAnnotation = string\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const DescriptionAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Description\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type ExamplesAnnotation<A> = Arr.NonEmptyReadonlyArray<A>\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const ExamplesAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Examples\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type DefaultAnnotation<A> = A\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const DefaultAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Default\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type JSONSchemaAnnotation = object\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const JSONSchemaAnnotationId: unique symbol = Symbol.for(\"effect/annotation/JSONSchema\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const ArbitraryAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Arbitrary\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const PrettyAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Pretty\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type EquivalenceAnnotation<A, TypeParameters extends ReadonlyArray<any> = readonly []> = (\n  ...equivalences: { readonly [K in keyof TypeParameters]: Equivalence<TypeParameters[K]> }\n) => Equivalence<A>\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const EquivalenceAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Equivalence\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type DocumentationAnnotation = string\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const DocumentationAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Documentation\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type ConcurrencyAnnotation = Concurrency | undefined\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const ConcurrencyAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Concurrency\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type BatchingAnnotation = boolean | \"inherit\" | undefined\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const BatchingAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Batching\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type ParseIssueTitleAnnotation = (issue: ParseIssue) => string | undefined\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const ParseIssueTitleAnnotationId: unique symbol = Symbol.for(\"effect/annotation/ParseIssueTitle\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const ParseOptionsAnnotationId: unique symbol = Symbol.for(\"effect/annotation/ParseOptions\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type DecodingFallbackAnnotation<A> = (issue: ParseIssue) => Effect<A, ParseIssue>\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const DecodingFallbackAnnotationId: unique symbol = Symbol.for(\"effect/annotation/DecodingFallback\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const SurrogateAnnotationId: unique symbol = Symbol.for(\"effect/annotation/Surrogate\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport type SurrogateAnnotation = AST\n\n/** @internal */\nexport const StableFilterAnnotationId: unique symbol = Symbol.for(\"effect/annotation/StableFilter\")\n\n/**\n * A stable filter consistently applies fixed validation rules, such as\n * 'minItems', 'maxItems', and 'itemsCount', to ensure array length complies\n * with set criteria regardless of the input data's content.\n *\n * @internal\n */\nexport type StableFilterAnnotation = boolean\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport interface Annotations {\n  readonly [_: string]: unknown\n  readonly [_: symbol]: unknown\n}\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport interface Annotated {\n  readonly annotations: Annotations\n}\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getAnnotation: {\n  <A>(key: symbol): (annotated: Annotated) => Option.Option<A>\n  <A>(annotated: Annotated, key: symbol): Option.Option<A>\n} = dual(\n  2,\n  <A>(annotated: Annotated, key: symbol): Option.Option<A> =>\n    Object.prototype.hasOwnProperty.call(annotated.annotations, key) ?\n      Option.some(annotated.annotations[key] as any) :\n      Option.none()\n)\n\n/**\n * @category annotations\n * @since 3.19.0\n * @experimental\n */\nexport const getTypeConstructorAnnotation = getAnnotation<TypeConstructorAnnotation>(TypeConstructorAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getBrandAnnotation = getAnnotation<BrandAnnotation>(BrandAnnotationId)\n\n/**\n * @category annotations\n * @since 3.14.2\n */\nexport const getSchemaIdAnnotation = getAnnotation<SchemaIdAnnotation>(SchemaIdAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getMessageAnnotation = getAnnotation<MessageAnnotation>(MessageAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getMissingMessageAnnotation = getAnnotation<MissingMessageAnnotation>(MissingMessageAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getTitleAnnotation = getAnnotation<TitleAnnotation>(TitleAnnotationId)\n\n/** @internal */\nexport const getAutoTitleAnnotation = getAnnotation<TitleAnnotation>(AutoTitleAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getIdentifierAnnotation = getAnnotation<IdentifierAnnotation>(IdentifierAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getDescriptionAnnotation = getAnnotation<DescriptionAnnotation>(DescriptionAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getExamplesAnnotation = getAnnotation<ExamplesAnnotation<unknown>>(ExamplesAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getDefaultAnnotation = getAnnotation<DefaultAnnotation<unknown>>(DefaultAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getJSONSchemaAnnotation = getAnnotation<JSONSchemaAnnotation>(JSONSchemaAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getDocumentationAnnotation = getAnnotation<DocumentationAnnotation>(DocumentationAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getConcurrencyAnnotation = getAnnotation<ConcurrencyAnnotation>(ConcurrencyAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getBatchingAnnotation = getAnnotation<BatchingAnnotation>(BatchingAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getParseIssueTitleAnnotation = getAnnotation<ParseIssueTitleAnnotation>(ParseIssueTitleAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getParseOptionsAnnotation = getAnnotation<ParseOptions>(ParseOptionsAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getDecodingFallbackAnnotation = getAnnotation<DecodingFallbackAnnotation<unknown>>(\n  DecodingFallbackAnnotationId\n)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getSurrogateAnnotation = getAnnotation<SurrogateAnnotation>(SurrogateAnnotationId)\n\nconst getStableFilterAnnotation = getAnnotation<StableFilterAnnotation>(StableFilterAnnotationId)\n\n/** @internal */\nexport const hasStableFilter = (annotated: Annotated) =>\n  Option.exists(getStableFilterAnnotation(annotated), (b) => b === true)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const JSONIdentifierAnnotationId: unique symbol = Symbol.for(\"effect/annotation/JSONIdentifier\")\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getJSONIdentifierAnnotation = getAnnotation<IdentifierAnnotation>(JSONIdentifierAnnotationId)\n\n/**\n * @category annotations\n * @since 3.10.0\n */\nexport const getJSONIdentifier = (annotated: Annotated) =>\n  Option.orElse(getJSONIdentifierAnnotation(annotated), () => getIdentifierAnnotation(annotated))\n\n// -------------------------------------------------------------------------------------\n// schema ids\n// -------------------------------------------------------------------------------------\n\n/**\n * @category schema id\n * @since 3.10.0\n */\nexport const ParseJsonSchemaId: unique symbol = Symbol.for(\"effect/schema/ParseJson\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class Declaration implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Declaration\"\n  constructor(\n    readonly typeParameters: ReadonlyArray<AST>,\n    readonly decodeUnknown: (\n      ...typeParameters: ReadonlyArray<AST>\n    ) => (input: unknown, options: ParseOptions, self: Declaration) => Effect<any, ParseIssue, any>,\n    readonly encodeUnknown: (\n      ...typeParameters: ReadonlyArray<AST>\n    ) => (input: unknown, options: ParseOptions, self: Declaration) => Effect<any, ParseIssue, any>,\n    readonly annotations: Annotations = {}\n  ) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return Option.getOrElse(getExpected(this), () => \"<declaration schema>\")\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      typeParameters: this.typeParameters.map((ast) => ast.toJSON()),\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\nconst createASTGuard = <T extends AST[\"_tag\"]>(tag: T) => (ast: AST): ast is Extract<AST, { _tag: T }> =>\n  ast._tag === tag\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isDeclaration: (ast: AST) => ast is Declaration = createASTGuard(\"Declaration\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport type LiteralValue = string | number | boolean | null | bigint\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class Literal implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Literal\"\n  constructor(readonly literal: LiteralValue, readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return Option.getOrElse(getExpected(this), () => Inspectable.formatUnknown(this.literal))\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      literal: Predicate.isBigInt(this.literal) ? String(this.literal) : this.literal,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isLiteral: (ast: AST) => ast is Literal = createASTGuard(\"Literal\")\n\nconst $null = new Literal(null)\n\nexport {\n  /**\n   * @category constructors\n   * @since 3.10.0\n   */\n  $null as null\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class UniqueSymbol implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"UniqueSymbol\"\n  constructor(readonly symbol: symbol, readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return Option.getOrElse(getExpected(this), () => Inspectable.formatUnknown(this.symbol))\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      symbol: String(this.symbol),\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isUniqueSymbol: (ast: AST) => ast is UniqueSymbol = createASTGuard(\"UniqueSymbol\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class UndefinedKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"UndefinedKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const undefinedKeyword: UndefinedKeyword = new UndefinedKeyword({\n  [TitleAnnotationId]: \"undefined\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isUndefinedKeyword: (ast: AST) => ast is UndefinedKeyword = createASTGuard(\"UndefinedKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class VoidKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"VoidKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const voidKeyword: VoidKeyword = new VoidKeyword({\n  [TitleAnnotationId]: \"void\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isVoidKeyword: (ast: AST) => ast is VoidKeyword = createASTGuard(\"VoidKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class NeverKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"NeverKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const neverKeyword: NeverKeyword = new NeverKeyword({\n  [TitleAnnotationId]: \"never\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isNeverKeyword: (ast: AST) => ast is NeverKeyword = createASTGuard(\"NeverKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class UnknownKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"UnknownKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const unknownKeyword: UnknownKeyword = new UnknownKeyword({\n  [TitleAnnotationId]: \"unknown\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isUnknownKeyword: (ast: AST) => ast is UnknownKeyword = createASTGuard(\"UnknownKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class AnyKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"AnyKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const anyKeyword: AnyKeyword = new AnyKeyword({\n  [TitleAnnotationId]: \"any\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isAnyKeyword: (ast: AST) => ast is AnyKeyword = createASTGuard(\"AnyKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class StringKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"StringKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const stringKeyword: StringKeyword = new StringKeyword({\n  [TitleAnnotationId]: \"string\",\n  [DescriptionAnnotationId]: \"a string\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isStringKeyword: (ast: AST) => ast is StringKeyword = createASTGuard(\"StringKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class NumberKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"NumberKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const numberKeyword: NumberKeyword = new NumberKeyword({\n  [TitleAnnotationId]: \"number\",\n  [DescriptionAnnotationId]: \"a number\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isNumberKeyword: (ast: AST) => ast is NumberKeyword = createASTGuard(\"NumberKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class BooleanKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"BooleanKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const booleanKeyword: BooleanKeyword = new BooleanKeyword({\n  [TitleAnnotationId]: \"boolean\",\n  [DescriptionAnnotationId]: \"a boolean\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isBooleanKeyword: (ast: AST) => ast is BooleanKeyword = createASTGuard(\"BooleanKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class BigIntKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"BigIntKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const bigIntKeyword: BigIntKeyword = new BigIntKeyword({\n  [TitleAnnotationId]: \"bigint\",\n  [DescriptionAnnotationId]: \"a bigint\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isBigIntKeyword: (ast: AST) => ast is BigIntKeyword = createASTGuard(\"BigIntKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class SymbolKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"SymbolKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const symbolKeyword: SymbolKeyword = new SymbolKeyword({\n  [TitleAnnotationId]: \"symbol\",\n  [DescriptionAnnotationId]: \"a symbol\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isSymbolKeyword: (ast: AST) => ast is SymbolKeyword = createASTGuard(\"SymbolKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class ObjectKeyword implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"ObjectKeyword\"\n  constructor(readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return formatKeyword(this)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const objectKeyword: ObjectKeyword = new ObjectKeyword({\n  [TitleAnnotationId]: \"object\",\n  [DescriptionAnnotationId]: \"an object in the TypeScript meaning, i.e. the `object` type\"\n})\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isObjectKeyword: (ast: AST) => ast is ObjectKeyword = createASTGuard(\"ObjectKeyword\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class Enums implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Enums\"\n  constructor(\n    readonly enums: ReadonlyArray<readonly [string, string | number]>,\n    readonly annotations: Annotations = {}\n  ) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return Option.getOrElse(\n      getExpected(this),\n      () => `<enum ${this.enums.length} value(s): ${this.enums.map(([_, value]) => JSON.stringify(value)).join(\" | \")}>`\n    )\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      enums: this.enums,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isEnums: (ast: AST) => ast is Enums = createASTGuard(\"Enums\")\n\ntype TemplateLiteralSpanBaseType = StringKeyword | NumberKeyword | Literal | TemplateLiteral\n\ntype TemplateLiteralSpanType = TemplateLiteralSpanBaseType | Union<TemplateLiteralSpanType>\n\nconst isTemplateLiteralSpanType = (ast: AST): ast is TemplateLiteralSpanType => {\n  switch (ast._tag) {\n    case \"Literal\":\n    case \"NumberKeyword\":\n    case \"StringKeyword\":\n    case \"TemplateLiteral\":\n      return true\n    case \"Union\":\n      return ast.types.every(isTemplateLiteralSpanType)\n  }\n  return false\n}\n\nconst templateLiteralSpanUnionTypeToString = (type: TemplateLiteralSpanType): string => {\n  switch (type._tag) {\n    case \"Literal\":\n      return JSON.stringify(String(type.literal))\n    case \"StringKeyword\":\n      return \"string\"\n    case \"NumberKeyword\":\n      return \"number\"\n    case \"TemplateLiteral\":\n      return String(type)\n    case \"Union\":\n      return type.types.map(templateLiteralSpanUnionTypeToString).join(\" | \")\n  }\n}\n\nconst templateLiteralSpanTypeToString = (type: TemplateLiteralSpanType): string => {\n  switch (type._tag) {\n    case \"Literal\":\n      return String(type.literal)\n    case \"StringKeyword\":\n      return \"${string}\"\n    case \"NumberKeyword\":\n      return \"${number}\"\n    case \"TemplateLiteral\":\n      return \"${\" + String(type) + \"}\"\n    case \"Union\":\n      return \"${\" + type.types.map(templateLiteralSpanUnionTypeToString).join(\" | \") + \"}\"\n  }\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class TemplateLiteralSpan {\n  /**\n   * @since 3.10.0\n   */\n  readonly type: TemplateLiteralSpanType\n  constructor(type: AST, readonly literal: string) {\n    if (isTemplateLiteralSpanType(type)) {\n      this.type = type\n    } else {\n      throw new Error(errors_.getSchemaUnsupportedLiteralSpanErrorMessage(type))\n    }\n  }\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return templateLiteralSpanTypeToString(this.type) + this.literal\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      type: this.type.toJSON(),\n      literal: this.literal\n    }\n  }\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class TemplateLiteral implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"TemplateLiteral\"\n  constructor(\n    readonly head: string,\n    readonly spans: Arr.NonEmptyReadonlyArray<TemplateLiteralSpan>,\n    readonly annotations: Annotations = {}\n  ) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return Option.getOrElse(getExpected(this), () => formatTemplateLiteral(this))\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      head: this.head,\n      spans: this.spans.map((span) => span.toJSON()),\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\nconst formatTemplateLiteral = (ast: TemplateLiteral): string =>\n  \"`\" + ast.head + ast.spans.map(String).join(\"\") +\n  \"`\"\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isTemplateLiteral: (ast: AST) => ast is TemplateLiteral = createASTGuard(\"TemplateLiteral\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class Type implements Annotated {\n  constructor(\n    readonly type: AST,\n    readonly annotations: Annotations = {}\n  ) {}\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      type: this.type.toJSON(),\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return String(this.type)\n  }\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class OptionalType extends Type {\n  constructor(\n    type: AST,\n    readonly isOptional: boolean,\n    annotations: Annotations = {}\n  ) {\n    super(type, annotations)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      type: this.type.toJSON(),\n      isOptional: this.isOptional,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return String(this.type) + (this.isOptional ? \"?\" : \"\")\n  }\n}\n\nconst getRestASTs = (rest: ReadonlyArray<Type>): ReadonlyArray<AST> => rest.map((annotatedAST) => annotatedAST.type)\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class TupleType implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"TupleType\"\n  constructor(\n    readonly elements: ReadonlyArray<OptionalType>,\n    readonly rest: ReadonlyArray<Type>,\n    readonly isReadonly: boolean,\n    readonly annotations: Annotations = {}\n  ) {\n    let hasOptionalElement = false\n    let hasIllegalRequiredElement = false\n    for (const e of elements) {\n      if (e.isOptional) {\n        hasOptionalElement = true\n      } else if (hasOptionalElement) {\n        hasIllegalRequiredElement = true\n        break\n      }\n    }\n    if (hasIllegalRequiredElement || (hasOptionalElement && rest.length > 1)) {\n      throw new Error(errors_.getASTRequiredElementFollowinAnOptionalElementErrorMessage)\n    }\n  }\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return Option.getOrElse(getExpected(this), () => formatTuple(this))\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      elements: this.elements.map((e) => e.toJSON()),\n      rest: this.rest.map((ast) => ast.toJSON()),\n      isReadonly: this.isReadonly,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\nconst formatTuple = (ast: TupleType): string => {\n  const formattedElements = ast.elements.map(String)\n    .join(\", \")\n  return Arr.matchLeft(ast.rest, {\n    onEmpty: () => `readonly [${formattedElements}]`,\n    onNonEmpty: (head, tail) => {\n      const formattedHead = String(head)\n      const wrappedHead = formattedHead.includes(\" | \") ? `(${formattedHead})` : formattedHead\n\n      if (tail.length > 0) {\n        const formattedTail = tail.map(String).join(\", \")\n        if (ast.elements.length > 0) {\n          return `readonly [${formattedElements}, ...${wrappedHead}[], ${formattedTail}]`\n        } else {\n          return `readonly [...${wrappedHead}[], ${formattedTail}]`\n        }\n      } else {\n        if (ast.elements.length > 0) {\n          return `readonly [${formattedElements}, ...${wrappedHead}[]]`\n        } else {\n          return `ReadonlyArray<${formattedHead}>`\n        }\n      }\n    }\n  })\n}\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isTupleType: (ast: AST) => ast is TupleType = createASTGuard(\"TupleType\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class PropertySignature extends OptionalType {\n  constructor(\n    readonly name: PropertyKey,\n    type: AST,\n    isOptional: boolean,\n    readonly isReadonly: boolean,\n    annotations?: Annotations\n  ) {\n    super(type, isOptional, annotations)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toString(): string {\n    return (this.isReadonly ? \"readonly \" : \"\") + String(this.name) + (this.isOptional ? \"?\" : \"\") + \": \" +\n      this.type\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      name: String(this.name),\n      type: this.type.toJSON(),\n      isOptional: this.isOptional,\n      isReadonly: this.isReadonly,\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @since 3.10.0\n */\nexport type Parameter = StringKeyword | SymbolKeyword | TemplateLiteral | Refinement<Parameter>\n\n/**\n * @since 3.10.0\n */\nexport const isParameter = (ast: AST): ast is Parameter => {\n  switch (ast._tag) {\n    case \"StringKeyword\":\n    case \"SymbolKeyword\":\n    case \"TemplateLiteral\":\n      return true\n    case \"Refinement\":\n      return isParameter(ast.from)\n  }\n  return false\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class IndexSignature {\n  /**\n   * @since 3.10.0\n   */\n  readonly parameter: Parameter\n  constructor(\n    parameter: AST,\n    readonly type: AST,\n    readonly isReadonly: boolean\n  ) {\n    if (isParameter(parameter)) {\n      this.parameter = parameter\n    } else {\n      throw new Error(errors_.getASTIndexSignatureParameterErrorMessage)\n    }\n  }\n  /**\n   * @since 3.10.0\n   */\n  toString(): string {\n    return (this.isReadonly ? \"readonly \" : \"\") + `[x: ${this.parameter}]: ${this.type}`\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      parameter: this.parameter.toJSON(),\n      type: this.type.toJSON(),\n      isReadonly: this.isReadonly\n    }\n  }\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class TypeLiteral implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"TypeLiteral\"\n  /**\n   * @since 3.10.0\n   */\n  readonly propertySignatures: ReadonlyArray<PropertySignature>\n  /**\n   * @since 3.10.0\n   */\n  readonly indexSignatures: ReadonlyArray<IndexSignature>\n  constructor(\n    propertySignatures: ReadonlyArray<PropertySignature>,\n    indexSignatures: ReadonlyArray<IndexSignature>,\n    readonly annotations: Annotations = {}\n  ) {\n    // check for duplicate property signatures\n    const keys: Record<PropertyKey, null> = {}\n    for (let i = 0; i < propertySignatures.length; i++) {\n      const name = propertySignatures[i].name\n      if (Object.prototype.hasOwnProperty.call(keys, name)) {\n        throw new Error(errors_.getASTDuplicatePropertySignatureErrorMessage(name))\n      }\n      keys[name] = null\n    }\n    // check for duplicate index signatures\n    const parameters = {\n      string: false,\n      symbol: false\n    }\n    for (let i = 0; i < indexSignatures.length; i++) {\n      const encodedParameter = getEncodedParameter(indexSignatures[i].parameter)\n      if (isStringKeyword(encodedParameter)) {\n        if (parameters.string) {\n          throw new Error(errors_.getASTDuplicateIndexSignatureErrorMessage(\"string\"))\n        }\n        parameters.string = true\n      } else if (isSymbolKeyword(encodedParameter)) {\n        if (parameters.symbol) {\n          throw new Error(errors_.getASTDuplicateIndexSignatureErrorMessage(\"symbol\"))\n        }\n        parameters.symbol = true\n      }\n    }\n\n    this.propertySignatures = propertySignatures\n    this.indexSignatures = indexSignatures\n  }\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return Option.getOrElse(getExpected(this), () => formatTypeLiteral(this))\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      propertySignatures: this.propertySignatures.map((ps) => ps.toJSON()),\n      indexSignatures: this.indexSignatures.map((ps) => ps.toJSON()),\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\nconst formatIndexSignatures = (iss: ReadonlyArray<IndexSignature>): string => iss.map(String).join(\"; \")\n\nconst formatTypeLiteral = (ast: TypeLiteral): string => {\n  if (ast.propertySignatures.length > 0) {\n    const pss = ast.propertySignatures.map(String).join(\"; \")\n    if (ast.indexSignatures.length > 0) {\n      return `{ ${pss}; ${formatIndexSignatures(ast.indexSignatures)} }`\n    } else {\n      return `{ ${pss} }`\n    }\n  } else {\n    if (ast.indexSignatures.length > 0) {\n      return `{ ${formatIndexSignatures(ast.indexSignatures)} }`\n    } else {\n      return \"{}\"\n    }\n  }\n}\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isTypeLiteral: (ast: AST) => ast is TypeLiteral = createASTGuard(\"TypeLiteral\")\n\n/**\n * @since 3.10.0\n */\nexport type Members<A> = readonly [A, A, ...Array<A>]\n\nconst sortCandidates = Arr.sort(\n  Order.mapInput(Number.Order, (ast: AST) => {\n    switch (ast._tag) {\n      case \"AnyKeyword\":\n        return 0\n      case \"UnknownKeyword\":\n        return 1\n      case \"ObjectKeyword\":\n        return 2\n      case \"StringKeyword\":\n      case \"NumberKeyword\":\n      case \"BooleanKeyword\":\n      case \"BigIntKeyword\":\n      case \"SymbolKeyword\":\n        return 3\n    }\n    return 4\n  })\n)\n\nconst literalMap = {\n  string: \"StringKeyword\",\n  number: \"NumberKeyword\",\n  boolean: \"BooleanKeyword\",\n  bigint: \"BigIntKeyword\"\n} as const\n\n/** @internal */\nexport const flatten = (candidates: ReadonlyArray<AST>): Array<AST> =>\n  Arr.flatMap(candidates, (ast) => isUnion(ast) ? flatten(ast.types) : [ast])\n\n/** @internal */\nexport const unify = (candidates: ReadonlyArray<AST>): Array<AST> => {\n  const cs = sortCandidates(candidates)\n  const out: Array<AST> = []\n  const uniques: { [K in AST[\"_tag\"] | \"{}\"]?: AST } = {}\n  const literals: Array<LiteralValue | symbol> = []\n  for (const ast of cs) {\n    switch (ast._tag) {\n      case \"NeverKeyword\":\n        break\n      case \"AnyKeyword\":\n        return [anyKeyword]\n      case \"UnknownKeyword\":\n        return [unknownKeyword]\n      // uniques\n      case \"ObjectKeyword\":\n      case \"UndefinedKeyword\":\n      case \"VoidKeyword\":\n      case \"StringKeyword\":\n      case \"NumberKeyword\":\n      case \"BooleanKeyword\":\n      case \"BigIntKeyword\":\n      case \"SymbolKeyword\": {\n        if (!uniques[ast._tag]) {\n          uniques[ast._tag] = ast\n          out.push(ast)\n        }\n        break\n      }\n      case \"Literal\": {\n        const type = typeof ast.literal\n        switch (type) {\n          case \"string\":\n          case \"number\":\n          case \"bigint\":\n          case \"boolean\": {\n            const _tag = literalMap[type]\n            if (!uniques[_tag] && !literals.includes(ast.literal)) {\n              literals.push(ast.literal)\n              out.push(ast)\n            }\n            break\n          }\n          // null\n          case \"object\": {\n            if (!literals.includes(ast.literal)) {\n              literals.push(ast.literal)\n              out.push(ast)\n            }\n            break\n          }\n        }\n        break\n      }\n      case \"UniqueSymbol\": {\n        if (!uniques[\"SymbolKeyword\"] && !literals.includes(ast.symbol)) {\n          literals.push(ast.symbol)\n          out.push(ast)\n        }\n        break\n      }\n      case \"TupleType\": {\n        if (!uniques[\"ObjectKeyword\"]) {\n          out.push(ast)\n        }\n        break\n      }\n      case \"TypeLiteral\": {\n        if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) {\n          if (!uniques[\"{}\"]) {\n            uniques[\"{}\"] = ast\n            out.push(ast)\n          }\n        } else if (!uniques[\"ObjectKeyword\"]) {\n          out.push(ast)\n        }\n        break\n      }\n      default:\n        out.push(ast)\n    }\n  }\n  return out\n}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class Union<M extends AST = AST> implements Annotated {\n  static make = (types: ReadonlyArray<AST>, annotations?: Annotations): AST => {\n    return isMembers(types) ? new Union(types, annotations) : types.length === 1 ? types[0] : neverKeyword\n  }\n  /** @internal */\n  static unify = (candidates: ReadonlyArray<AST>, annotations?: Annotations): AST => {\n    return Union.make(unify(flatten(candidates)), annotations)\n  }\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Union\"\n  private constructor(readonly types: Members<M>, readonly annotations: Annotations = {}) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return Option.getOrElse(getExpected(this), () => this.types.map(String).join(\" | \"))\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      types: this.types.map((ast) => ast.toJSON()),\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/** @internal */\nexport const mapMembers = <A, B>(members: Members<A>, f: (a: A) => B): Members<B> => members.map(f) as any\n\n/** @internal */\nexport const isMembers = <A>(as: ReadonlyArray<A>): as is Members<A> => as.length > 1\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isUnion: (ast: AST) => ast is Union = createASTGuard(\"Union\")\n\nconst toJSONMemoMap = globalValue(\n  Symbol.for(\"effect/Schema/AST/toJSONMemoMap\"),\n  () => new WeakMap<AST, object>()\n)\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class Suspend implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Suspend\"\n  constructor(readonly f: () => AST, readonly annotations: Annotations = {}) {\n    this.f = util_.memoizeThunk(f)\n  }\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return getExpected(this).pipe(\n      Option.orElse(() =>\n        Option.flatMap(\n          Option.liftThrowable(this.f)(),\n          (ast) => getExpected(ast)\n        )\n      ),\n      Option.getOrElse(() => \"<suspended schema>\")\n    )\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    const ast = this.f()\n    let out = toJSONMemoMap.get(ast)\n    if (out) {\n      return out\n    }\n    toJSONMemoMap.set(ast, { _tag: this._tag })\n    out = {\n      _tag: this._tag,\n      ast: ast.toJSON(),\n      annotations: toJSONAnnotations(this.annotations)\n    }\n    toJSONMemoMap.set(ast, out)\n    return out\n  }\n}\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isSuspend: (ast: AST) => ast is Suspend = createASTGuard(\"Suspend\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class Refinement<From extends AST = AST> implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Refinement\"\n  constructor(\n    readonly from: From,\n    readonly filter: (\n      input: any,\n      options: ParseOptions,\n      self: Refinement\n    ) => Option.Option<ParseIssue>,\n    readonly annotations: Annotations = {}\n  ) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return getIdentifierAnnotation(this).pipe(Option.getOrElse(() =>\n      Option.match(getOrElseExpected(this), {\n        onNone: () => `{ ${this.from} | filter }`,\n        onSome: (expected) => isRefinement(this.from) ? String(this.from) + \" & \" + expected : expected\n      })\n    ))\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      from: this.from.toJSON(),\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isRefinement: (ast: AST) => ast is Refinement<AST> = createASTGuard(\"Refinement\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport interface ParseOptions {\n  /**\n   * The `errors` option allows you to receive all parsing errors when\n   * attempting to parse a value using a schema. By default only the first error\n   * is returned, but by setting the `errors` option to `\"all\"`, you can receive\n   * all errors that occurred during the parsing process. This can be useful for\n   * debugging or for providing more comprehensive error messages to the user.\n   *\n   * default: \"first\"\n   *\n   * @since 3.10.0\n   */\n  readonly errors?: \"first\" | \"all\" | undefined\n  /**\n   * When using a `Schema` to parse a value, by default any properties that are\n   * not specified in the `Schema` will be stripped out from the output. This is\n   * because the `Schema` is expecting a specific shape for the parsed value,\n   * and any excess properties do not conform to that shape.\n   *\n   * However, you can use the `onExcessProperty` option (default value:\n   * `\"ignore\"`) to trigger a parsing error. This can be particularly useful in\n   * cases where you need to detect and handle potential errors or unexpected\n   * values.\n   *\n   * If you want to allow excess properties to remain, you can use\n   * `onExcessProperty` set to `\"preserve\"`.\n   *\n   * default: \"ignore\"\n   *\n   * @since 3.10.0\n   */\n  readonly onExcessProperty?: \"ignore\" | \"error\" | \"preserve\" | undefined\n  /**\n   * The `propertyOrder` option provides control over the order of object fields\n   * in the output. This feature is particularly useful when the sequence of\n   * keys is important for the consuming processes or when maintaining the input\n   * order enhances readability and usability.\n   *\n   * By default, the `propertyOrder` option is set to `\"none\"`. This means that\n   * the internal system decides the order of keys to optimize parsing speed.\n   * The order of keys in this mode should not be considered stable, and it's\n   * recommended not to rely on key ordering as it may change in future updates\n   * without notice.\n   *\n   * Setting `propertyOrder` to `\"original\"` ensures that the keys are ordered\n   * as they appear in the input during the decoding/encoding process.\n   *\n   * default: \"none\"\n   *\n   * @since 3.10.0\n   */\n  readonly propertyOrder?: \"none\" | \"original\" | undefined\n  /**\n   * Handles missing properties in data structures. By default, missing\n   * properties are treated as if present with an `undefined` value. To treat\n   * missing properties as errors, set the `exact` option to `true`. This\n   * setting is already enabled by default for `is` and `asserts` functions,\n   * treating absent properties strictly unless overridden.\n   *\n   * default: false\n   *\n   * @since 3.10.0\n   */\n  readonly exact?: boolean | undefined\n}\n\n/**\n * @since 3.10.0\n */\nexport const defaultParseOption: ParseOptions = {}\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class Transformation implements Annotated {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"Transformation\"\n  constructor(\n    readonly from: AST,\n    readonly to: AST,\n    readonly transformation: TransformationKind,\n    readonly annotations: Annotations = {}\n  ) {}\n  /**\n   * @since 3.10.0\n   */\n  toString() {\n    return Option.getOrElse(\n      getExpected(this),\n      () => `(${String(this.from)} <-> ${String(this.to)})`\n    )\n  }\n  /**\n   * @since 3.10.0\n   */\n  toJSON(): object {\n    return {\n      _tag: this._tag,\n      from: this.from.toJSON(),\n      to: this.to.toJSON(),\n      annotations: toJSONAnnotations(this.annotations)\n    }\n  }\n}\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isTransformation: (ast: AST) => ast is Transformation = createASTGuard(\"Transformation\")\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport type TransformationKind =\n  | FinalTransformation\n  | ComposeTransformation\n  | TypeLiteralTransformation\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class FinalTransformation {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"FinalTransformation\"\n  constructor(\n    readonly decode: (\n      fromA: any,\n      options: ParseOptions,\n      self: Transformation,\n      fromI: any\n    ) => Effect<any, ParseIssue, any>,\n    readonly encode: (toI: any, options: ParseOptions, self: Transformation, toA: any) => Effect<any, ParseIssue, any>\n  ) {}\n}\n\nconst createTransformationGuard =\n  <T extends TransformationKind[\"_tag\"]>(tag: T) =>\n  (ast: TransformationKind): ast is Extract<TransformationKind, { _tag: T }> => ast._tag === tag\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isFinalTransformation: (ast: TransformationKind) => ast is FinalTransformation = createTransformationGuard(\n  \"FinalTransformation\"\n)\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class ComposeTransformation {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"ComposeTransformation\"\n}\n\n/**\n * @category constructors\n * @since 3.10.0\n */\nexport const composeTransformation: ComposeTransformation = new ComposeTransformation()\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isComposeTransformation: (ast: TransformationKind) => ast is ComposeTransformation =\n  createTransformationGuard(\n    \"ComposeTransformation\"\n  )\n\n/**\n * Represents a `PropertySignature -> PropertySignature` transformation\n *\n * The semantic of `decode` is:\n * - `none()` represents the absence of the key/value pair\n * - `some(value)` represents the presence of the key/value pair\n *\n * The semantic of `encode` is:\n * - `none()` you don't want to output the key/value pair\n * - `some(value)` you want to output the key/value pair\n *\n * @category model\n * @since 3.10.0\n */\nexport class PropertySignatureTransformation {\n  constructor(\n    readonly from: PropertyKey,\n    readonly to: PropertyKey,\n    readonly decode: (o: Option.Option<any>) => Option.Option<any>,\n    readonly encode: (o: Option.Option<any>) => Option.Option<any>\n  ) {}\n}\n\nconst isRenamingPropertySignatureTransformation = (t: PropertySignatureTransformation) =>\n  t.decode === identity && t.encode === identity\n\n/**\n * @category model\n * @since 3.10.0\n */\nexport class TypeLiteralTransformation {\n  /**\n   * @since 3.10.0\n   */\n  readonly _tag = \"TypeLiteralTransformation\"\n  constructor(\n    readonly propertySignatureTransformations: ReadonlyArray<\n      PropertySignatureTransformation\n    >\n  ) {\n    // check for duplicate property signature transformations\n    const fromKeys: Record<PropertyKey, true> = {}\n    const toKeys: Record<PropertyKey, true> = {}\n    for (const pst of propertySignatureTransformations) {\n      const from = pst.from\n      if (fromKeys[from]) {\n        throw new Error(errors_.getASTDuplicatePropertySignatureTransformationErrorMessage(from))\n      }\n      fromKeys[from] = true\n      const to = pst.to\n      if (toKeys[to]) {\n        throw new Error(errors_.getASTDuplicatePropertySignatureTransformationErrorMessage(to))\n      }\n      toKeys[to] = true\n    }\n  }\n}\n\n/**\n * @category guards\n * @since 3.10.0\n */\nexport const isTypeLiteralTransformation: (ast: TransformationKind) => ast is TypeLiteralTransformation =\n  createTransformationGuard(\"TypeLiteralTransformation\")\n\n// -------------------------------------------------------------------------------------\n// API\n// -------------------------------------------------------------------------------------\n\n/**\n * Merges a set of new annotations with existing ones, potentially overwriting\n * any duplicates.\n *\n * Any previously existing identifier annotations are deleted.\n *\n * @since 3.10.0\n */\nexport const annotations = (ast: AST, overrides: Annotations): AST => {\n  const d = Object.getOwnPropertyDescriptors(ast)\n  const base: any = { ...ast.annotations }\n  delete base[IdentifierAnnotationId]\n  const value = { ...base, ...overrides }\n  const surrogate = getSurrogateAnnotation(ast)\n  if (Option.isSome(surrogate)) {\n    value[SurrogateAnnotationId] = annotations(surrogate.value, overrides)\n  }\n  d.annotations.value = value\n  return Object.create(Object.getPrototypeOf(ast), d)\n}\n\n/**\n * Equivalent at runtime to the TypeScript type-level `keyof` operator.\n *\n * @since 3.10.0\n */\nexport const keyof = (ast: AST): AST => Union.unify(_keyof(ast))\n\nconst STRING_KEYWORD_PATTERN = \"[\\\\s\\\\S]*?\" // any string, including newlines\nconst NUMBER_KEYWORD_PATTERN = \"[+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?\"\n\nconst getTemplateLiteralSpanTypePattern = (type: TemplateLiteralSpanType, capture: boolean): string => {\n  switch (type._tag) {\n    case \"Literal\":\n      return regexp.escape(String(type.literal))\n    case \"StringKeyword\":\n      return STRING_KEYWORD_PATTERN\n    case \"NumberKeyword\":\n      return NUMBER_KEYWORD_PATTERN\n    case \"TemplateLiteral\":\n      return getTemplateLiteralPattern(type, capture, false)\n    case \"Union\":\n      return type.types.map((type) => getTemplateLiteralSpanTypePattern(type, capture)).join(\"|\")\n  }\n}\n\nconst handleTemplateLiteralSpanTypeParens = (\n  type: TemplateLiteralSpanType,\n  s: string,\n  capture: boolean,\n  top: boolean\n) => {\n  if (isUnion(type)) {\n    if (capture && !top) {\n      return `(?:${s})`\n    }\n  } else if (!capture || !top) {\n    return s\n  }\n  return `(${s})`\n}\n\nconst getTemplateLiteralPattern = (ast: TemplateLiteral, capture: boolean, top: boolean): string => {\n  let pattern = ``\n  if (ast.head !== \"\") {\n    const head = regexp.escape(ast.head)\n    pattern += capture && top ? `(${head})` : head\n  }\n\n  for (const span of ast.spans) {\n    const spanPattern = getTemplateLiteralSpanTypePattern(span.type, capture)\n    pattern += handleTemplateLiteralSpanTypeParens(span.type, spanPattern, capture, top)\n    if (span.literal !== \"\") {\n      const literal = regexp.escape(span.literal)\n      pattern += capture && top ? `(${literal})` : literal\n    }\n  }\n\n  return pattern\n}\n\n/**\n * Generates a regular expression from a `TemplateLiteral` AST node.\n *\n * @see {@link getTemplateLiteralCapturingRegExp} for a variant that captures the pattern.\n *\n * @since 3.10.0\n */\nexport const getTemplateLiteralRegExp = (ast: TemplateLiteral): RegExp =>\n  new RegExp(`^${getTemplateLiteralPattern(ast, false, true)}$`)\n\n/**\n * Generates a regular expression that captures the pattern defined by the given `TemplateLiteral` AST.\n *\n * @see {@link getTemplateLiteralRegExp} for a variant that does not capture the pattern.\n *\n * @since 3.10.0\n */\nexport const getTemplateLiteralCapturingRegExp = (ast: TemplateLiteral): RegExp =>\n  new RegExp(`^${getTemplateLiteralPattern(ast, true, true)}$`)\n\n/**\n * @since 3.10.0\n */\nexport const getPropertySignatures = (ast: AST): Array<PropertySignature> => {\n  const annotation = getSurrogateAnnotation(ast)\n  if (Option.isSome(annotation)) {\n    return getPropertySignatures(annotation.value)\n  }\n  switch (ast._tag) {\n    case \"TypeLiteral\":\n      return ast.propertySignatures.slice()\n    case \"Suspend\":\n      return getPropertySignatures(ast.f())\n    case \"Refinement\":\n      return getPropertySignatures(ast.from)\n  }\n  return getPropertyKeys(ast).map((name) => getPropertyKeyIndexedAccess(ast, name))\n}\n\nconst getIndexSignatures = (ast: AST): Array<IndexSignature> => {\n  const annotation = getSurrogateAnnotation(ast)\n  if (Option.isSome(annotation)) {\n    return getIndexSignatures(annotation.value)\n  }\n  switch (ast._tag) {\n    case \"TypeLiteral\":\n      return ast.indexSignatures.slice()\n    case \"Suspend\":\n      return getIndexSignatures(ast.f())\n    case \"Refinement\":\n      return getIndexSignatures(ast.from)\n    case \"Transformation\":\n      return getIndexSignatures(ast.to)\n  }\n  return []\n}\n\n/** @internal */\nexport const getNumberIndexedAccess = (ast: AST): AST => {\n  switch (ast._tag) {\n    case \"TupleType\": {\n      let hasOptional = false\n      let out: Array<AST> = []\n      for (const e of ast.elements) {\n        if (e.isOptional) {\n          hasOptional = true\n        }\n        out.push(e.type)\n      }\n      if (hasOptional) {\n        out.push(undefinedKeyword)\n      }\n      out = out.concat(getRestASTs(ast.rest))\n      return Union.make(out)\n    }\n    case \"Refinement\":\n      return getNumberIndexedAccess(ast.from)\n    case \"Union\":\n      return Union.make(ast.types.map(getNumberIndexedAccess))\n    case \"Suspend\":\n      return getNumberIndexedAccess(ast.f())\n  }\n  throw new Error(errors_.getASTUnsupportedSchemaErrorMessage(ast))\n}\n\nconst getTypeLiteralPropertySignature = (ast: TypeLiteral, name: PropertyKey): PropertySignature | undefined => {\n  // from property signatures...\n  const ops = Arr.findFirst(ast.propertySignatures, (ps) => ps.name === name)\n  if (Option.isSome(ops)) {\n    return ops.value\n  }\n\n  // from index signatures...\n  if (Predicate.isString(name)) {\n    let out: PropertySignature | undefined = undefined\n    for (const is of ast.indexSignatures) {\n      const encodedParameter = getEncodedParameter(is.parameter)\n      switch (encodedParameter._tag) {\n        case \"TemplateLiteral\": {\n          const regex = getTemplateLiteralRegExp(encodedParameter)\n          if (regex.test(name)) {\n            return new PropertySignature(name, is.type, false, true)\n          }\n          break\n        }\n        case \"StringKeyword\": {\n          if (out === undefined) {\n            out = new PropertySignature(name, is.type, false, true)\n          }\n        }\n      }\n    }\n    if (out) {\n      return out\n    }\n  } else if (Predicate.isSymbol(name)) {\n    for (const is of ast.indexSignatures) {\n      const encodedParameter = getEncodedParameter(is.parameter)\n      if (isSymbolKeyword(encodedParameter)) {\n        return new PropertySignature(name, is.type, false, true)\n      }\n    }\n  }\n}\n\n/** @internal */\nexport const getPropertyKeyIndexedAccess = (ast: AST, name: PropertyKey): PropertySignature => {\n  const annotation = getSurrogateAnnotation(ast)\n  if (Option.isSome(annotation)) {\n    return getPropertyKeyIndexedAccess(annotation.value, name)\n  }\n  switch (ast._tag) {\n    case \"TypeLiteral\": {\n      const ps = getTypeLiteralPropertySignature(ast, name)\n      if (ps) {\n        return ps\n      }\n      break\n    }\n    case \"Union\":\n      return new PropertySignature(\n        name,\n        Union.make(ast.types.map((ast) => getPropertyKeyIndexedAccess(ast, name).type)),\n        false,\n        true\n      )\n    case \"Suspend\":\n      return getPropertyKeyIndexedAccess(ast.f(), name)\n    case \"Refinement\":\n      return getPropertyKeyIndexedAccess(ast.from, name)\n    case \"Transformation\":\n      return getPropertyKeyIndexedAccess(ast.to, name)\n  }\n  throw new Error(errors_.getASTUnsupportedSchemaErrorMessage(ast))\n}\n\nconst getPropertyKeys = (ast: AST): Array<PropertyKey> => {\n  const annotation = getSurrogateAnnotation(ast)\n  if (Option.isSome(annotation)) {\n    return getPropertyKeys(annotation.value)\n  }\n  switch (ast._tag) {\n    case \"TypeLiteral\":\n      return ast.propertySignatures.map((ps) => ps.name)\n    case \"Union\":\n      return ast.types.slice(1).reduce(\n        (out: Array<PropertyKey>, ast) => Arr.intersection(out, getPropertyKeys(ast)),\n        getPropertyKeys(ast.types[0])\n      )\n    case \"Suspend\":\n      return getPropertyKeys(ast.f())\n    case \"Refinement\":\n      return getPropertyKeys(ast.from)\n    case \"Transformation\":\n      return getPropertyKeys(ast.to)\n  }\n  return []\n}\n\n/** @internal */\nexport const record = (key: AST, value: AST): {\n  propertySignatures: Array<PropertySignature>\n  indexSignatures: Array<IndexSignature>\n} => {\n  const propertySignatures: Array<PropertySignature> = []\n  const indexSignatures: Array<IndexSignature> = []\n  const go = (key: AST): void => {\n    switch (key._tag) {\n      case \"NeverKeyword\":\n        break\n      case \"StringKeyword\":\n      case \"SymbolKeyword\":\n      case \"TemplateLiteral\":\n      case \"Refinement\":\n        indexSignatures.push(new IndexSignature(key, value, true))\n        break\n      case \"Literal\":\n        if (Predicate.isString(key.literal) || Predicate.isNumber(key.literal)) {\n          propertySignatures.push(new PropertySignature(key.literal, value, false, true))\n        } else {\n          throw new Error(errors_.getASTUnsupportedLiteralErrorMessage(key.literal))\n        }\n        break\n      case \"Enums\": {\n        for (const [_, name] of key.enums) {\n          propertySignatures.push(new PropertySignature(name, value, false, true))\n        }\n        break\n      }\n      case \"UniqueSymbol\":\n        propertySignatures.push(new PropertySignature(key.symbol, value, false, true))\n        break\n      case \"Union\":\n        key.types.forEach(go)\n        break\n      default:\n        throw new Error(errors_.getASTUnsupportedKeySchemaErrorMessage(key))\n    }\n  }\n  go(key)\n  return { propertySignatures, indexSignatures }\n}\n\n/**\n * Equivalent at runtime to the built-in TypeScript utility type `Pick`.\n *\n * @since 3.10.0\n */\nexport const pick = (ast: AST, keys: ReadonlyArray<PropertyKey>): TypeLiteral | Transformation => {\n  const annotation = getSurrogateAnnotation(ast)\n  if (Option.isSome(annotation)) {\n    return pick(annotation.value, keys)\n  }\n  switch (ast._tag) {\n    case \"TypeLiteral\": {\n      const pss: Array<PropertySignature> = []\n      const names: Record<PropertyKey, null> = {}\n      for (const ps of ast.propertySignatures) {\n        names[ps.name] = null\n        if (keys.includes(ps.name)) {\n          pss.push(ps)\n        }\n      }\n      for (const key of keys) {\n        if (!(key in names)) {\n          const ps = getTypeLiteralPropertySignature(ast, key)\n          if (ps) {\n            pss.push(ps)\n          }\n        }\n      }\n      return new TypeLiteral(pss, [])\n    }\n    case \"Union\":\n      return new TypeLiteral(keys.map((name) => getPropertyKeyIndexedAccess(ast, name)), [])\n    case \"Suspend\":\n      return pick(ast.f(), keys)\n    case \"Refinement\":\n      return pick(ast.from, keys)\n    case \"Transformation\": {\n      switch (ast.transformation._tag) {\n        case \"ComposeTransformation\":\n          return new Transformation(\n            pick(ast.from, keys),\n            pick(ast.to, keys),\n            composeTransformation\n          )\n        case \"TypeLiteralTransformation\": {\n          const ts: Array<PropertySignatureTransformation> = []\n          const fromKeys: Array<PropertyKey> = []\n          for (const k of keys) {\n            const t = ast.transformation.propertySignatureTransformations.find((t) => t.to === k)\n            if (t) {\n              ts.push(t)\n              fromKeys.push(t.from)\n            } else {\n              fromKeys.push(k)\n            }\n          }\n          return Arr.isNonEmptyReadonlyArray(ts) ?\n            new Transformation(\n              pick(ast.from, fromKeys),\n              pick(ast.to, keys),\n              new TypeLiteralTransformation(ts)\n            ) :\n            pick(ast.from, fromKeys)\n        }\n      }\n    }\n  }\n  throw new Error(errors_.getASTUnsupportedSchemaErrorMessage(ast))\n}\n\n/**\n * Equivalent at runtime to the built-in TypeScript utility type `Omit`.\n *\n * @since 3.10.0\n */\nexport const omit = (ast: AST, keys: ReadonlyArray<PropertyKey>): TypeLiteral | Transformation => {\n  let indexSignatures = getIndexSignatures(ast)\n  if (indexSignatures.length > 0) {\n    if (indexSignatures.some((is) => isStringKeyword(getEncodedParameter(is.parameter)))) {\n      indexSignatures = indexSignatures.filter((is) => !isTemplateLiteral(getEncodedParameter(is.parameter)))\n    }\n    return new TypeLiteral([], indexSignatures)\n  }\n  return pick(ast, getPropertyKeys(ast).filter((name) => !keys.includes(name)))\n}\n\n/** @internal */\nexport const orUndefined = (ast: AST): AST => Union.make([ast, undefinedKeyword])\n\n/**\n * Equivalent at runtime to the built-in TypeScript utility type `Partial`.\n *\n * @since 3.10.0\n */\nexport const partial = (ast: AST, options?: { readonly exact: true }): AST => {\n  const exact = options?.exact === true\n  switch (ast._tag) {\n    case \"TupleType\":\n      return new TupleType(\n        ast.elements.map((e) => new OptionalType(exact ? e.type : orUndefined(e.type), true)),\n        Arr.match(ast.rest, {\n          onEmpty: () => ast.rest,\n          onNonEmpty: (rest) => [new Type(Union.make([...getRestASTs(rest), undefinedKeyword]))]\n        }),\n        ast.isReadonly\n      )\n    case \"TypeLiteral\":\n      return new TypeLiteral(\n        ast.propertySignatures.map((ps) =>\n          new PropertySignature(ps.name, exact ? ps.type : orUndefined(ps.type), true, ps.isReadonly, ps.annotations)\n        ),\n        ast.indexSignatures.map((is) => new IndexSignature(is.parameter, orUndefined(is.type), is.isReadonly))\n      )\n    case \"Union\":\n      return Union.make(ast.types.map((member) => partial(member, options)))\n    case \"Suspend\":\n      return new Suspend(() => partial(ast.f(), options))\n    case \"Declaration\":\n    case \"Refinement\":\n      throw new Error(errors_.getASTUnsupportedSchemaErrorMessage(ast))\n    case \"Transformation\": {\n      if (\n        isTypeLiteralTransformation(ast.transformation) &&\n        ast.transformation.propertySignatureTransformations.every(isRenamingPropertySignatureTransformation)\n      ) {\n        return new Transformation(partial(ast.from, options), partial(ast.to, options), ast.transformation)\n      }\n      throw new Error(errors_.getASTUnsupportedSchemaErrorMessage(ast))\n    }\n  }\n  return ast\n}\n\n/**\n * Equivalent at runtime to the built-in TypeScript utility type `Required`.\n *\n * @since 3.10.0\n */\nexport const required = (ast: AST): AST => {\n  switch (ast._tag) {\n    case \"TupleType\":\n      return new TupleType(\n        ast.elements.map((e) => new OptionalType(e.type, false)),\n        ast.rest,\n        ast.isReadonly\n      )\n    case \"TypeLiteral\":\n      return new TypeLiteral(\n        ast.propertySignatures.map((f) => new PropertySignature(f.name, f.type, false, f.isReadonly, f.annotations)),\n        ast.indexSignatures\n      )\n    case \"Union\":\n      return Union.make(ast.types.map((member) => required(member)))\n    case \"Suspend\":\n      return new Suspend(() => required(ast.f()))\n    case \"Declaration\":\n    case \"Refinement\":\n      throw new Error(errors_.getASTUnsupportedSchemaErrorMessage(ast))\n    case \"Transformation\": {\n      if (\n        isTypeLiteralTransformation(ast.transformation) &&\n        ast.transformation.propertySignatureTransformations.every(isRenamingPropertySignatureTransformation)\n      ) {\n        return new Transformation(required(ast.from), required(ast.to), ast.transformation)\n      }\n      throw new Error(errors_.getASTUnsupportedSchemaErrorMessage(ast))\n    }\n  }\n  return ast\n}\n\n/**\n * Creates a new AST with shallow mutability applied to its properties.\n *\n * @since 3.10.0\n */\nexport const mutable = (ast: AST): AST => {\n  switch (ast._tag) {\n    case \"TupleType\":\n      return ast.isReadonly === false ? ast : new TupleType(ast.elements, ast.rest, false, ast.annotations)\n    case \"TypeLiteral\": {\n      const propertySignatures = changeMap(\n        ast.propertySignatures,\n        (ps) =>\n          ps.isReadonly === false ? ps : new PropertySignature(ps.name, ps.type, ps.isOptional, false, ps.annotations)\n      )\n      const indexSignatures = changeMap(\n        ast.indexSignatures,\n        (is) => is.isReadonly === false ? is : new IndexSignature(is.parameter, is.type, false)\n      )\n      return propertySignatures === ast.propertySignatures && indexSignatures === ast.indexSignatures ?\n        ast :\n        new TypeLiteral(propertySignatures, indexSignatures, ast.annotations)\n    }\n    case \"Union\": {\n      const types = changeMap(ast.types, mutable)\n      return types === ast.types ? ast : Union.make(types, ast.annotations)\n    }\n    case \"Suspend\":\n      return new Suspend(() => mutable(ast.f()), ast.annotations)\n    case \"Refinement\": {\n      const from = mutable(ast.from)\n      return from === ast.from ? ast : new Refinement(from, ast.filter, ast.annotations)\n    }\n    case \"Transformation\": {\n      const from = mutable(ast.from)\n      const to = mutable(ast.to)\n      return from === ast.from && to === ast.to ?\n        ast :\n        new Transformation(from, to, ast.transformation, ast.annotations)\n    }\n  }\n  return ast\n}\n\n// -------------------------------------------------------------------------------------\n// compiler harness\n// -------------------------------------------------------------------------------------\n\n/**\n * @since 3.10.0\n */\nexport type Compiler<A> = (ast: AST, path: ReadonlyArray<PropertyKey>) => A\n\n/**\n * @since 3.10.0\n */\nexport type Match<A> = {\n  [K in AST[\"_tag\"]]: (ast: Extract<AST, { _tag: K }>, compile: Compiler<A>, path: ReadonlyArray<PropertyKey>) => A\n}\n\n/**\n * @since 3.10.0\n */\nexport const getCompiler = <A>(match: Match<A>): Compiler<A> => {\n  const compile = (ast: AST, path: ReadonlyArray<PropertyKey>): A => match[ast._tag](ast as any, compile, path)\n  return compile\n}\n\n/** @internal */\nexport const pickAnnotations =\n  (annotationIds: ReadonlyArray<symbol>) => (annotated: Annotated): Annotations | undefined => {\n    let out: { [_: symbol]: unknown } | undefined = undefined\n    for (const id of annotationIds) {\n      if (Object.prototype.hasOwnProperty.call(annotated.annotations, id)) {\n        if (out === undefined) {\n          out = {}\n        }\n        out[id] = annotated.annotations[id]\n      }\n    }\n    return out\n  }\n\n/** @internal */\nexport const omitAnnotations =\n  (annotationIds: ReadonlyArray<symbol>) => (annotated: Annotated): Annotations | undefined => {\n    const out = { ...annotated.annotations }\n    for (const id of annotationIds) {\n      delete out[id]\n    }\n    return out\n  }\n\nconst preserveTransformationAnnotations = pickAnnotations([\n  ExamplesAnnotationId,\n  DefaultAnnotationId,\n  JSONSchemaAnnotationId,\n  ArbitraryAnnotationId,\n  PrettyAnnotationId,\n  EquivalenceAnnotationId\n])\n\n/**\n * @since 3.10.0\n */\nexport const typeAST = (ast: AST): AST => {\n  switch (ast._tag) {\n    case \"Declaration\": {\n      const typeParameters = changeMap(ast.typeParameters, typeAST)\n      return typeParameters === ast.typeParameters ?\n        ast :\n        new Declaration(typeParameters, ast.decodeUnknown, ast.encodeUnknown, ast.annotations)\n    }\n    case \"TupleType\": {\n      const elements = changeMap(ast.elements, (e) => {\n        const type = typeAST(e.type)\n        return type === e.type ? e : new OptionalType(type, e.isOptional)\n      })\n      const restASTs = getRestASTs(ast.rest)\n      const rest = changeMap(restASTs, typeAST)\n      return elements === ast.elements && rest === restASTs ?\n        ast :\n        new TupleType(elements, rest.map((type) => new Type(type)), ast.isReadonly, ast.annotations)\n    }\n    case \"TypeLiteral\": {\n      const propertySignatures = changeMap(ast.propertySignatures, (p) => {\n        const type = typeAST(p.type)\n        return type === p.type ? p : new PropertySignature(p.name, type, p.isOptional, p.isReadonly)\n      })\n      const indexSignatures = changeMap(ast.indexSignatures, (is) => {\n        const type = typeAST(is.type)\n        return type === is.type ? is : new IndexSignature(is.parameter, type, is.isReadonly)\n      })\n      return propertySignatures === ast.propertySignatures && indexSignatures === ast.indexSignatures ?\n        ast :\n        new TypeLiteral(propertySignatures, indexSignatures, ast.annotations)\n    }\n    case \"Union\": {\n      const types = changeMap(ast.types, typeAST)\n      return types === ast.types ? ast : Union.make(types, ast.annotations)\n    }\n    case \"Suspend\":\n      return new Suspend(() => typeAST(ast.f()), ast.annotations)\n    case \"Refinement\": {\n      const from = typeAST(ast.from)\n      return from === ast.from ?\n        ast :\n        new Refinement(from, ast.filter, ast.annotations)\n    }\n    case \"Transformation\": {\n      const preserve = preserveTransformationAnnotations(ast)\n      return typeAST(\n        preserve !== undefined ?\n          annotations(ast.to, preserve) :\n          ast.to\n      )\n    }\n  }\n  return ast\n}\n\nfunction changeMap<A>(\n  as: Arr.NonEmptyReadonlyArray<A>,\n  f: (a: A) => A\n): Arr.NonEmptyReadonlyArray<A>\nfunction changeMap<A>(as: ReadonlyArray<A>, f: (a: A) => A): ReadonlyArray<A>\nfunction changeMap<A>(as: ReadonlyArray<A>, f: (a: A) => A): ReadonlyArray<A> {\n  let changed = false\n  const out = Arr.allocate(as.length) as Array<A>\n  for (let i = 0; i < as.length; i++) {\n    const a = as[i]\n    const fa = f(a)\n    if (fa !== a) {\n      changed = true\n    }\n    out[i] = fa\n  }\n  return changed ? out : as\n}\n\n/**\n * Returns the from part of a transformation if it exists\n *\n * @internal\n */\nexport const getTransformationFrom = (ast: AST): AST | undefined => {\n  switch (ast._tag) {\n    case \"Transformation\":\n      return ast.from\n    case \"Refinement\":\n      return getTransformationFrom(ast.from)\n    case \"Suspend\":\n      return getTransformationFrom(ast.f())\n  }\n}\n\nconst encodedAST_ = (ast: AST, isBound: boolean): AST => {\n  switch (ast._tag) {\n    case \"Declaration\": {\n      const typeParameters = changeMap(ast.typeParameters, (ast) => encodedAST_(ast, isBound))\n      return typeParameters === ast.typeParameters ?\n        ast :\n        new Declaration(typeParameters, ast.decodeUnknown, ast.encodeUnknown)\n    }\n    case \"TupleType\": {\n      const elements = changeMap(ast.elements, (e) => {\n        const type = encodedAST_(e.type, isBound)\n        return type === e.type ? e : new OptionalType(type, e.isOptional)\n      })\n      const restASTs = getRestASTs(ast.rest)\n      const rest = changeMap(restASTs, (ast) => encodedAST_(ast, isBound))\n      return elements === ast.elements && rest === restASTs ?\n        ast :\n        new TupleType(elements, rest.map((ast) => new Type(ast)), ast.isReadonly)\n    }\n    case \"TypeLiteral\": {\n      const propertySignatures = changeMap(ast.propertySignatures, (ps) => {\n        const type = encodedAST_(ps.type, isBound)\n        return type === ps.type\n          ? ps\n          : new PropertySignature(ps.name, type, ps.isOptional, ps.isReadonly)\n      })\n      const indexSignatures = changeMap(ast.indexSignatures, (is) => {\n        const type = encodedAST_(is.type, isBound)\n        return type === is.type ? is : new IndexSignature(is.parameter, type, is.isReadonly)\n      })\n      return propertySignatures === ast.propertySignatures && indexSignatures === ast.indexSignatures ?\n        ast :\n        new TypeLiteral(propertySignatures, indexSignatures)\n    }\n    case \"Union\": {\n      const types = changeMap(ast.types, (ast) => encodedAST_(ast, isBound))\n      return types === ast.types ? ast : Union.make(types)\n    }\n    case \"Suspend\": {\n      let borrowedAnnotations = undefined\n      const identifier = getJSONIdentifier(ast)\n      if (Option.isSome(identifier)) {\n        const suffix = isBound ? \"Bound\" : \"\"\n        borrowedAnnotations = { [JSONIdentifierAnnotationId]: `${identifier.value}Encoded${suffix}` }\n      }\n      return new Suspend(() => encodedAST_(ast.f(), isBound), borrowedAnnotations)\n    }\n    case \"Refinement\": {\n      const from = encodedAST_(ast.from, isBound)\n      if (isBound) {\n        if (from === ast.from) return ast\n        if (getTransformationFrom(ast.from) === undefined && hasStableFilter(ast)) {\n          return new Refinement(from, ast.filter, ast.annotations)\n        }\n        return from\n      } else {\n        return from\n      }\n    }\n    case \"Transformation\":\n      return encodedAST_(ast.from, isBound)\n  }\n  return ast\n}\n\n/**\n * @since 3.10.0\n */\nexport const encodedAST = (ast: AST): AST => encodedAST_(ast, false)\n\n/**\n * @since 3.10.0\n */\nexport const encodedBoundAST = (ast: AST): AST => encodedAST_(ast, true)\n\nconst toJSONAnnotations = (annotations: Annotations): object => {\n  const out: Record<string, unknown> = {}\n  for (const k of Object.getOwnPropertySymbols(annotations)) {\n    out[String(k)] = annotations[k]\n  }\n  return out\n}\n\n/** @internal */\nexport const getEncodedParameter = (\n  ast: Parameter\n): StringKeyword | SymbolKeyword | TemplateLiteral => {\n  switch (ast._tag) {\n    case \"StringKeyword\":\n    case \"SymbolKeyword\":\n    case \"TemplateLiteral\":\n      return ast\n    case \"Refinement\":\n      return getEncodedParameter(ast.from)\n  }\n}\n\n/** @internal  */\nexport const equals = (self: AST, that: AST): boolean => {\n  switch (self._tag) {\n    case \"Literal\":\n      return isLiteral(that) && that.literal === self.literal\n    case \"UniqueSymbol\":\n      return isUniqueSymbol(that) && that.symbol === self.symbol\n    case \"UndefinedKeyword\":\n    case \"VoidKeyword\":\n    case \"NeverKeyword\":\n    case \"UnknownKeyword\":\n    case \"AnyKeyword\":\n    case \"StringKeyword\":\n    case \"NumberKeyword\":\n    case \"BooleanKeyword\":\n    case \"BigIntKeyword\":\n    case \"SymbolKeyword\":\n    case \"ObjectKeyword\":\n      return that._tag === self._tag\n    case \"TemplateLiteral\":\n      return isTemplateLiteral(that) && that.head === self.head && equalsTemplateLiteralSpan(that.spans, self.spans)\n    case \"Enums\":\n      return isEnums(that) && equalsEnums(that.enums, self.enums)\n    case \"Union\":\n      return isUnion(that) && equalsUnion(self.types, that.types)\n    case \"Refinement\":\n    case \"TupleType\":\n    case \"TypeLiteral\":\n    case \"Suspend\":\n    case \"Transformation\":\n    case \"Declaration\":\n      return self === that\n  }\n}\n\nconst equalsTemplateLiteralSpan = Arr.getEquivalence<TemplateLiteralSpan>((self, that): boolean => {\n  return self.literal === that.literal && equals(self.type, that.type)\n})\n\nconst equalsEnums = Arr.getEquivalence<readonly [string, string | number]>((self, that) =>\n  that[0] === self[0] && that[1] === self[1]\n)\n\nconst equalsUnion = Arr.getEquivalence<AST>(equals)\n\nconst intersection = Arr.intersectionWith(equals)\n\nconst _keyof = (ast: AST): Array<AST> => {\n  switch (ast._tag) {\n    case \"Declaration\": {\n      const annotation = getSurrogateAnnotation(ast)\n      if (Option.isSome(annotation)) {\n        return _keyof(annotation.value)\n      }\n      break\n    }\n    case \"TypeLiteral\":\n      return ast.propertySignatures.map((p): AST =>\n        Predicate.isSymbol(p.name) ? new UniqueSymbol(p.name) : new Literal(p.name)\n      ).concat(ast.indexSignatures.map((is) => getEncodedParameter(is.parameter)))\n    case \"Suspend\":\n      return _keyof(ast.f())\n    case \"Union\":\n      return ast.types.slice(1).reduce(\n        (out: Array<AST>, ast) => intersection(out, _keyof(ast)),\n        _keyof(ast.types[0])\n      )\n    case \"Transformation\":\n      return _keyof(ast.to)\n  }\n  throw new Error(errors_.getASTUnsupportedSchemaErrorMessage(ast))\n}\n\n/** @internal */\nexport const compose = (ab: AST, cd: AST): AST => new Transformation(ab, cd, composeTransformation)\n\n/** @internal */\nexport const rename = (ast: AST, mapping: { readonly [K in PropertyKey]?: PropertyKey }): AST => {\n  switch (ast._tag) {\n    case \"TypeLiteral\": {\n      const propertySignatureTransformations: Array<PropertySignatureTransformation> = []\n      for (const key of Reflect.ownKeys(mapping)) {\n        const name = mapping[key]\n        if (name !== undefined) {\n          propertySignatureTransformations.push(\n            new PropertySignatureTransformation(\n              key,\n              name,\n              identity,\n              identity\n            )\n          )\n        }\n      }\n      if (propertySignatureTransformations.length === 0) {\n        return ast\n      }\n      return new Transformation(\n        ast,\n        new TypeLiteral(\n          ast.propertySignatures.map((ps) => {\n            const name = mapping[ps.name]\n            return new PropertySignature(\n              name === undefined ? ps.name : name,\n              typeAST(ps.type),\n              ps.isOptional,\n              ps.isReadonly,\n              ps.annotations\n            )\n          }),\n          ast.indexSignatures\n        ),\n        new TypeLiteralTransformation(propertySignatureTransformations)\n      )\n    }\n    case \"Union\":\n      return Union.make(ast.types.map((ast) => rename(ast, mapping)))\n    case \"Suspend\":\n      return new Suspend(() => rename(ast.f(), mapping))\n    case \"Transformation\":\n      return compose(ast, rename(typeAST(ast), mapping))\n  }\n  throw new Error(errors_.getASTUnsupportedRenameSchemaErrorMessage(ast))\n}\n\nconst formatKeyword = (ast: AST): string => Option.getOrElse(getExpected(ast), () => ast._tag)\n\nfunction getBrands(ast: Annotated): string {\n  return Option.match(getBrandAnnotation(ast), {\n    onNone: () => \"\",\n    onSome: (brands) => brands.map((brand) => ` & Brand<${Inspectable.formatUnknown(brand)}>`).join(\"\")\n  })\n}\n\nconst getOrElseExpected = (ast: Annotated): Option.Option<string> =>\n  getTitleAnnotation(ast).pipe(\n    Option.orElse(() => getDescriptionAnnotation(ast)),\n    Option.orElse(() => getAutoTitleAnnotation(ast)),\n    Option.map((s) => s + getBrands(ast))\n  )\n\nconst getExpected = (ast: Annotated): Option.Option<string> =>\n  Option.orElse(getIdentifierAnnotation(ast), () => getOrElseExpected(ast))\n\n/** @internal */\nexport const pruneUndefined = (\n  ast: AST,\n  self: (ast: AST) => AST | undefined,\n  onTransformation: (ast: Transformation) => AST | undefined\n): AST | undefined => {\n  switch (ast._tag) {\n    case \"UndefinedKeyword\":\n      return neverKeyword\n    case \"Union\": {\n      const types: Array<AST> = []\n      let hasUndefined = false\n      for (const type of ast.types) {\n        const pruned = self(type)\n        if (pruned) {\n          hasUndefined = true\n          if (!isNeverKeyword(pruned)) {\n            types.push(pruned)\n          }\n        } else {\n          types.push(type)\n        }\n      }\n      if (hasUndefined) {\n        return Union.make(types)\n      }\n      break\n    }\n    case \"Suspend\":\n      return self(ast.f())\n    case \"Transformation\":\n      return onTransformation(ast)\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/Scope.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport type * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as ExecutionStrategy from \"./ExecutionStrategy.js\"\nimport type * as Exit from \"./Exit.js\"\nimport * as core from \"./internal/core.js\"\nimport * as fiberRuntime from \"./internal/fiberRuntime.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\n\n/**\n * A unique identifier for the `Scope` type.\n *\n * @since 2.0.0\n * @category symbols\n */\nexport const ScopeTypeId: unique symbol = core.ScopeTypeId\n\n/**\n * The type of the unique identifier for `Scope`.\n *\n * @since 2.0.0\n * @category symbols\n */\nexport type ScopeTypeId = typeof ScopeTypeId\n\n/**\n * A unique identifier for the `CloseableScope` type.\n *\n * @since 2.0.0\n * @category symbols\n */\nexport const CloseableScopeTypeId: unique symbol = core.CloseableScopeTypeId\n\n/**\n * The type of the unique identifier for `CloseableScope`.\n *\n * @since 2.0.0\n * @category symbols\n */\nexport type CloseableScopeTypeId = typeof CloseableScopeTypeId\n\n/**\n * Represents a scope that manages finalizers and can fork child scopes.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Scope extends Pipeable {\n  readonly [ScopeTypeId]: ScopeTypeId\n  /**\n   * The execution strategy for running finalizers in this scope.\n   */\n  readonly strategy: ExecutionStrategy.ExecutionStrategy\n  /**\n   * Forks a new child scope with the specified execution strategy. The child scope\n   * will automatically be closed when this scope is closed.\n   *\n   * @internal\n   */\n  fork(strategy: ExecutionStrategy.ExecutionStrategy): Effect.Effect<Scope.Closeable>\n  /**\n   * Adds a finalizer to this scope. The finalizer will be run when the scope is closed.\n   *\n   * @internal\n   */\n  addFinalizer(finalizer: Scope.Finalizer): Effect.Effect<void>\n}\n\n/**\n * A scope that can be explicitly closed with a specified exit value.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface CloseableScope extends Scope, Pipeable {\n  readonly [CloseableScopeTypeId]: CloseableScopeTypeId\n\n  /**\n   * Closes this scope with the given exit value, running all finalizers.\n   *\n   * @internal\n   */\n  close(exit: Exit.Exit<unknown, unknown>): Effect.Effect<void>\n}\n\n/**\n * A tag representing the current `Scope` in the environment.\n *\n * @since 2.0.0\n * @category context\n */\nexport const Scope: Context.Tag<Scope, Scope> = fiberRuntime.scopeTag\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Scope {\n  /**\n   * A finalizer function that takes an `Exit` value and returns an `Effect`.\n   *\n   * @since 2.0.0\n   * @category model\n   */\n  export type Finalizer = (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>\n  /**\n   * A closeable scope that can be explicitly closed.\n   *\n   * @since 2.0.0\n   * @category model\n   */\n  export type Closeable = CloseableScope\n}\n\n/**\n * Adds a finalizer to this scope. The finalizer is guaranteed to be run when\n * the scope is closed. Use this when the finalizer does not need to know the\n * `Exit` value that the scope is closed with.\n *\n * @see {@link addFinalizerExit}\n *\n * @since 2.0.0\n * @category utils\n */\nexport const addFinalizer: (\n  self: Scope,\n  finalizer: Effect.Effect<unknown>\n) => Effect.Effect<void> = core.scopeAddFinalizer\n\n/**\n * Adds a finalizer to this scope. The finalizer receives the `Exit` value\n * when the scope is closed, allowing it to perform different actions based\n * on the exit status.\n *\n * @see {@link addFinalizer}\n *\n * @since 2.0.0\n * @category utils\n */\nexport const addFinalizerExit: (self: Scope, finalizer: Scope.Finalizer) => Effect.Effect<void> =\n  core.scopeAddFinalizerExit\n\n/**\n * Closes this scope with the specified exit value, running all finalizers that\n * have been added to the scope.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const close: (self: CloseableScope, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void> = core.scopeClose\n\n/**\n * Extends the scope of an `Effect` that requires a scope into this scope.\n * It provides this scope to the effect but does not close the scope when the\n * effect completes execution. This allows extending a scoped value into a\n * larger scope.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const extend: {\n  (scope: Scope): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Scope>>\n  <A, E, R>(effect: Effect.Effect<A, E, R>, scope: Scope): Effect.Effect<A, E, Exclude<R, Scope>>\n} = fiberRuntime.scopeExtend\n\n/**\n * Forks a new child scope with the specified execution strategy. The child scope\n * will automatically be closed when this scope is closed.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const fork: (\n  self: Scope,\n  strategy: ExecutionStrategy.ExecutionStrategy\n) => Effect.Effect<CloseableScope> = core.scopeFork\n\n/**\n * Provides this closeable scope to an `Effect` that requires a scope,\n * guaranteeing that the scope is closed with the result of that effect as\n * soon as the effect completes execution, whether by success, failure, or\n * interruption.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const use: {\n  (scope: CloseableScope): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Scope>>\n  <A, E, R>(effect: Effect.Effect<A, E, R>, scope: CloseableScope): Effect.Effect<A, E, Exclude<R, Scope>>\n} = fiberRuntime.scopeUse\n\n/**\n * Creates a new closeable scope where finalizers will run according to the\n * specified `ExecutionStrategy`. If no execution strategy is provided, `sequential`\n * will be used by default.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (\n  executionStrategy?: ExecutionStrategy.ExecutionStrategy\n) => Effect.Effect<CloseableScope> = fiberRuntime.scopeMake\n"
  },
  {
    "path": "packages/effect/src/ScopedCache.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cache from \"./Cache.js\"\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport * as internal from \"./internal/scopedCache.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ScopedCacheTypeId: unique symbol = internal.ScopedCacheTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ScopedCacheTypeId = typeof ScopedCacheTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface ScopedCache<in Key, out Value, out Error = never>\n  extends ScopedCache.Variance<Key, Value, Error>, Pipeable\n{\n  /**\n   * Retrieves the value associated with the specified key if it exists.\n   * Otherwise returns `Option.none`.\n   */\n  getOption(key: Key): Effect.Effect<Option.Option<Value>, Error, Scope.Scope>\n\n  /**\n   * Retrieves the value associated with the specified key if it exists and the\n   * lookup function has completed. Otherwise returns `Option.none`.\n   */\n  getOptionComplete(key: Key): Effect.Effect<Option.Option<Value>, never, Scope.Scope>\n\n  /**\n   * Returns statistics for this cache.\n   */\n  readonly cacheStats: Effect.Effect<Cache.CacheStats>\n\n  /**\n   * Return whether a resource associated with the specified key exists in the\n   * cache. Sometime `contains` can return true if the resource is currently\n   * being created but not yet totally created.\n   */\n  contains(key: Key): Effect.Effect<boolean>\n\n  /**\n   * Return statistics for the specified entry.\n   */\n  entryStats(key: Key): Effect.Effect<Option.Option<Cache.EntryStats>>\n\n  /**\n   * Gets the value from the cache if it exists or otherwise computes it, the\n   * release action signals to the cache that the value is no longer being used\n   * and can potentially be finalized subject to the policies of the cache.\n   */\n  get(key: Key): Effect.Effect<Value, Error, Scope.Scope>\n\n  /**\n   * Invalidates the resource associated with the specified key.\n   */\n  invalidate(key: Key): Effect.Effect<void>\n\n  /**\n   * Invalidates all values in the cache.\n   */\n  readonly invalidateAll: Effect.Effect<void>\n\n  /**\n   * Force the reuse of the lookup function to compute the returned scoped\n   * effect associated with the specified key immediately. Once the new resource\n   * is recomputed, the old resource associated to the key is cleaned (once all\n   * fiber using it are done with it). During the time the new resource is\n   * computed, concurrent call the .get will use the old resource if this one is\n   * not expired.\n   */\n  refresh(key: Key): Effect.Effect<void, Error>\n\n  /**\n   * Returns the approximate number of values in the cache.\n   */\n  readonly size: Effect.Effect<number>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace ScopedCache {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in Key, out Value, out Error> {\n    readonly [ScopedCacheTypeId]: {\n      _Key: Types.Contravariant<Key>\n      _Error: Types.Covariant<Error>\n      _Value: Types.Covariant<Value>\n    }\n  }\n}\n\n/**\n * Constructs a new cache with the specified capacity, time to live, and\n * lookup function.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Key, Value, Error = never, Environment = never>(\n  options: {\n    readonly lookup: Lookup<Key, Value, Error, Environment>\n    readonly capacity: number\n    readonly timeToLive: Duration.DurationInput\n  }\n) => Effect.Effect<ScopedCache<Key, Value, Error>, never, Scope.Scope | Environment> = internal.make\n\n/**\n * Constructs a new cache with the specified capacity, time to live, and\n * lookup function, where the time to live can depend on the `Exit` value\n * returned by the lookup function.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const makeWith: <Key, Value, Error = never, Environment = never>(\n  options: {\n    readonly capacity: number\n    readonly lookup: Lookup<Key, Value, Error, Environment>\n    readonly timeToLive: (exit: Exit.Exit<Value, Error>) => Duration.DurationInput\n  }\n) => Effect.Effect<ScopedCache<Key, Value, Error>, never, Scope.Scope | Environment> = internal.makeWith\n\n/**\n * Similar to `Cache.Lookup`, but executes the lookup function within a `Scope`.\n *\n * @since 2.0.0\n * @category models\n */\nexport type Lookup<Key, Value, Error = never, Environment = never> = (\n  key: Key\n) => Effect.Effect<Value, Error, Environment | Scope.Scope>\n"
  },
  {
    "path": "packages/effect/src/ScopedRef.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport * as internal from \"./internal/scopedRef.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Synchronized from \"./SynchronizedRef.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const ScopedRefTypeId: unique symbol = internal.ScopedRefTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type ScopedRefTypeId = typeof ScopedRefTypeId\n\n/**\n * A `ScopedRef` is a reference whose value is associated with resources,\n * which must be released properly. You can both get the current value of any\n * `ScopedRef`, as well as set it to a new value (which may require new\n * resources). The reference itself takes care of properly releasing resources\n * for the old value whenever a new value is obtained.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface ScopedRef<in out A> extends Effect.Effect<A>, ScopedRef.Variance<A>, Pipeable {\n  /** @internal */\n  readonly ref: Synchronized.SynchronizedRef<readonly [Scope.Scope.Closeable, A]>\n\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: ScopedRefUnify<this>\n  readonly [Unify.ignoreSymbol]?: ScopedRefUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.9.0\n */\nexport interface ScopedRefUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  ScopedRef?: () => Extract<A[Unify.typeSymbol], ScopedRef<any>>\n}\n\n/**\n * @category models\n * @since 3.9.0\n */\nexport interface ScopedRefUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace ScopedRef {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A> {\n    readonly [ScopedRefTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * Creates a new `ScopedRef` from an effect that resourcefully produces a\n * value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromAcquire: <A, E, R>(\n  acquire: Effect.Effect<A, E, R>\n) => Effect.Effect<ScopedRef<A>, E, Scope.Scope | R> = internal.fromAcquire\n\n/**\n * Retrieves the current value of the scoped reference.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const get: <A>(self: ScopedRef<A>) => Effect.Effect<A> = internal.get\n\n/**\n * Creates a new `ScopedRef` from the specified value. This method should\n * not be used for values whose creation require the acquisition of resources.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A>(evaluate: LazyArg<A>) => Effect.Effect<ScopedRef<A>, never, Scope.Scope> = internal.make\n\n/**\n * Sets the value of this reference to the specified resourcefully-created\n * value. Any resources associated with the old value will be released.\n *\n * This method will not return until either the reference is successfully\n * changed to the new value, with old resources released, or until the attempt\n * to acquire a new value fails.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const set: {\n  <A, R, E>(acquire: Effect.Effect<A, E, R>): (self: ScopedRef<A>) => Effect.Effect<void, E, Exclude<R, Scope.Scope>>\n  <A, R, E>(self: ScopedRef<A>, acquire: Effect.Effect<A, E, R>): Effect.Effect<void, E, Exclude<R, Scope.Scope>>\n} = internal.set\n"
  },
  {
    "path": "packages/effect/src/Secret.ts",
    "content": "/**\n * @since 2.0.0\n * @deprecated\n */\nimport type * as Equal from \"./Equal.js\"\nimport * as InternalSecret from \"./internal/secret.js\"\nimport type * as Redacted from \"./Redacted.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n * @deprecated\n */\nexport const SecretTypeId: unique symbol = InternalSecret.SecretTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n * @deprecated\n */\nexport type SecretTypeId = typeof SecretTypeId\n\n/**\n * @since 2.0.0\n * @category models\n * @deprecated\n */\nexport interface Secret extends Redacted.Redacted, Secret.Proto, Equal.Equal {\n  /** @internal */\n  readonly raw: Array<number>\n}\n\n/**\n * @since 2.0.0\n * @deprecated\n */\nexport declare namespace Secret {\n  /**\n   * @since 2.0.0\n   * @category models\n   * @deprecated\n   */\n  export interface Proto {\n    readonly [SecretTypeId]: SecretTypeId\n  }\n}\n\n/**\n * @since 2.0.0\n * @category refinements\n * @deprecated\n */\nexport const isSecret: (u: unknown) => u is Secret = InternalSecret.isSecret\n\n/**\n * @since 2.0.0\n * @category constructors\n * @deprecated\n */\nexport const make: (bytes: Array<number>) => Secret = InternalSecret.make\n\n/**\n * @since 2.0.0\n * @category constructors\n * @deprecated\n */\nexport const fromIterable: (iterable: Iterable<string>) => Secret = InternalSecret.fromIterable\n\n/**\n * @since 2.0.0\n * @category constructors\n * @deprecated\n */\nexport const fromString: (text: string) => Secret = InternalSecret.fromString\n\n/**\n * @since 2.0.0\n * @category getters\n * @deprecated\n */\nexport const value: (self: Secret) => string = InternalSecret.value\n\n/**\n * @since 2.0.0\n * @category unsafe\n * @deprecated\n */\nexport const unsafeWipe: (self: Secret) => void = InternalSecret.unsafeWipe\n"
  },
  {
    "path": "packages/effect/src/SingleProducerAsyncInput.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type * as Exit from \"./Exit.js\"\nimport * as internal from \"./internal/channel/singleProducerAsyncInput.js\"\n\n/**\n * An MVar-like abstraction for sending data to channels asynchronously which is\n * designed for one producer and multiple consumers.\n *\n * Features the following semantics:\n *   - Buffer of size 1.\n *   - When emitting, the producer waits for a consumer to pick up the value to\n *     prevent \"reading ahead\" too much.\n *   - Once an emitted element is read by a consumer, it is cleared from the\n *     buffer, so that at most one consumer sees every emitted element.\n *   - When sending a done or error signal, the producer does not wait for a\n *     consumer to pick up the signal. The signal stays in the buffer after\n *     being read by a consumer, so it can be propagated to multiple consumers.\n *   - Trying to publish another emit/error/done after an error/done have\n *     already been published results in an interruption.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface SingleProducerAsyncInput<in out Err, in out Elem, in out Done>\n  extends AsyncInputProducer<Err, Elem, Done>, AsyncInputConsumer<Err, Elem, Done>\n{\n  readonly close: Effect.Effect<unknown>\n  readonly take: Effect.Effect<Exit.Exit<Elem, Either.Either<Done, Err>>>\n}\n\n/**\n * Producer-side view of `SingleProducerAsyncInput` for variance purposes.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface AsyncInputProducer<in Err, in Elem, in Done> {\n  awaitRead(): Effect.Effect<unknown>\n  done(value: Done): Effect.Effect<unknown>\n  emit(element: Elem): Effect.Effect<unknown>\n  error(cause: Cause.Cause<Err>): Effect.Effect<unknown>\n}\n\n/**\n * Consumer-side view of `SingleProducerAsyncInput` for variance purposes.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface AsyncInputConsumer<out Err, out Elem, out Done> {\n  takeWith<A>(\n    onError: (cause: Cause.Cause<Err>) => A,\n    onElement: (element: Elem) => A,\n    onDone: (value: Done) => A\n  ): Effect.Effect<A>\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Err, Elem, Done>() => Effect.Effect<SingleProducerAsyncInput<Err, Elem, Done>> = internal.make\n"
  },
  {
    "path": "packages/effect/src/Sink.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Channel from \"./Channel.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport type * as HashMap from \"./HashMap.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport * as internal from \"./internal/sink.js\"\nimport type * as MergeDecision from \"./MergeDecision.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport type * as PubSub from \"./PubSub.js\"\nimport type * as Queue from \"./Queue.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const SinkTypeId: unique symbol = internal.SinkTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type SinkTypeId = typeof SinkTypeId\n\n/**\n * A `Sink<A, In, L, E, R>` is used to consume elements produced by a `Stream`.\n * You can think of a sink as a function that will consume a variable amount of\n * `In` elements (could be 0, 1, or many), might fail with an error of type `E`,\n * and will eventually yield a value of type `A` together with a remainder of\n * type `L` (i.e. any leftovers).\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Sink<out A, in In = unknown, out L = never, out E = never, out R = never>\n  extends Sink.Variance<A, In, L, E, R>, Pipeable\n{}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface SinkUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  Sink?: () => A[Unify.typeSymbol] extends\n    | Sink<\n      infer A,\n      infer In,\n      infer L,\n      infer E,\n      infer R\n    >\n    | infer _ ? Sink<A, In, L, E, R>\n    : never\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface SinkUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Sink?: true\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\ndeclare module \"./Effect.js\" {\n  interface Effect<A, E, R> extends Sink<A, unknown, never, E, R> {}\n  interface EffectUnifyIgnore {\n    Sink?: true\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Sink {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out A, in In, out L, out E, out R> {\n    readonly [SinkTypeId]: VarianceStruct<A, In, L, E, R>\n  }\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface VarianceStruct<out A, in In, out L, out E, out R> {\n    _A: Types.Covariant<A>\n    _In: Types.Contravariant<In>\n    _L: Types.Covariant<L>\n    _E: Types.Covariant<E>\n    _R: Types.Covariant<R>\n  }\n}\n\n/**\n * Replaces this sink's result with the provided value.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const as: {\n  <A2>(a: A2): <A, In, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A2, In, L, E, R>\n  <A, In, L, E, R, A2>(self: Sink<A, In, L, E, R>, a: A2): Sink<A2, In, L, E, R>\n} = internal.as\n\n/**\n * A sink that collects all elements into a `Chunk`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAll: <In>() => Sink<Chunk.Chunk<In>, In> = internal.collectAll\n\n/**\n * A sink that collects first `n` elements into a chunk.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAllN: <In>(n: number) => Sink<Chunk.Chunk<In>, In, In> = internal.collectAllN\n\n/**\n * Repeatedly runs the sink and accumulates its results into a `Chunk`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const collectAllFrom: <A, In, L extends In, E, R>(\n  self: Sink<A, In, L, E, R>\n) => Sink<Chunk.Chunk<A>, In, L, E, R> = internal.collectAllFrom\n\n/**\n * A sink that collects all of its inputs into a map. The keys are extracted\n * from inputs using the keying function `key`; if multiple inputs use the\n * same key, they are merged using the `merge` function.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAllToMap: <In, K>(\n  key: (input: In) => K,\n  merge: (x: In, y: In) => In\n) => Sink<HashMap.HashMap<K, In>, In> = internal.collectAllToMap\n\n/**\n * A sink that collects first `n` keys into a map. The keys are calculated\n * from inputs using the keying function `key`; if multiple inputs use the the\n * same key, they are merged using the `merge` function.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAllToMapN: <In, K>(\n  n: number,\n  key: (input: In) => K,\n  merge: (x: In, y: In) => In\n) => Sink<HashMap.HashMap<K, In>, In, In> = internal.collectAllToMapN\n\n/**\n * A sink that collects all of its inputs into a set.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAllToSet: <In>() => Sink<HashSet.HashSet<In>, In> = internal.collectAllToSet\n\n/**\n * A sink that collects first `n` distinct inputs into a set.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAllToSetN: <In>(n: number) => Sink<HashSet.HashSet<In>, In, In> = internal.collectAllToSetN\n\n/**\n * Accumulates incoming elements into a chunk until predicate `p` is\n * satisfied.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAllUntil: <In>(p: Predicate<In>) => Sink<Chunk.Chunk<In>, In, In> = internal.collectAllUntil\n\n/**\n * Accumulates incoming elements into a chunk until effectful predicate `p` is\n * satisfied.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAllUntilEffect: <In, E, R>(\n  p: (input: In) => Effect.Effect<boolean, E, R>\n) => Sink<Chunk.Chunk<In>, In, In, E, R> = internal.collectAllUntilEffect\n\n/**\n * Accumulates incoming elements into a chunk as long as they verify predicate\n * `p`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAllWhile: {\n  <In, Out extends In>(refinement: Refinement<In, Out>): Sink<Chunk.Chunk<Out>, In, In>\n  <In>(predicate: Predicate<In>): Sink<Chunk.Chunk<In>, In, In>\n} = internal.collectAllWhile\n\n/**\n * Accumulates incoming elements into a chunk as long as they verify effectful\n * predicate `p`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const collectAllWhileEffect: <In, E, R>(\n  predicate: (input: In) => Effect.Effect<boolean, E, R>\n) => Sink<Chunk.Chunk<In>, In, In, E, R> = internal.collectAllWhileEffect\n\n/**\n * Repeatedly runs the sink for as long as its results satisfy the predicate\n * `p`. The sink's results will be accumulated using the stepping function `f`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const collectAllWhileWith: {\n  <A, S>(\n    options: { readonly initial: S; readonly while: Predicate<A>; readonly body: (s: S, a: A) => S }\n  ): <In, L extends In, E, R>(self: Sink<A, In, L, E, R>) => Sink<S, In, L, E, R>\n  <A, In, L extends In, E, R, S>(\n    self: Sink<A, In, L, E, R>,\n    options: { readonly initial: S; readonly while: Predicate<A>; readonly body: (s: S, a: A) => S }\n  ): Sink<S, In, L, E, R>\n} = internal.collectAllWhileWith as any\n\n/**\n * Collects the leftovers from the stream when the sink succeeds and returns\n * them as part of the sink's result.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const collectLeftover: <A, In, L, E, R>(\n  self: Sink<A, In, L, E, R>\n) => Sink<[A, Chunk.Chunk<L>], In, never, E, R> = internal.collectLeftover\n\n/**\n * Transforms this sink's input elements.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapInput: {\n  <In0, In>(f: (input: In0) => In): <A, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In0, L, E, R>\n  <A, In, L, E, R, In0>(self: Sink<A, In, L, E, R>, f: (input: In0) => In): Sink<A, In0, L, E, R>\n} = internal.mapInput\n\n/**\n * Effectfully transforms this sink's input elements.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapInputEffect: {\n  <In0, In, E2, R2>(\n    f: (input: In0) => Effect.Effect<In, E2, R2>\n  ): <A, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In0, L, E2 | E, R2 | R>\n  <A, In, L, E, R, In0, E2, R2>(\n    self: Sink<A, In, L, E, R>,\n    f: (input: In0) => Effect.Effect<In, E2, R2>\n  ): Sink<A, In0, L, E | E2, R | R2>\n} = internal.mapInputEffect\n\n/**\n * Transforms this sink's input chunks. `f` must preserve chunking-invariance.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapInputChunks: {\n  <In0, In>(\n    f: (chunk: Chunk.Chunk<In0>) => Chunk.Chunk<In>\n  ): <A, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In0, L, E, R>\n  <A, In, L, E, R, In0>(\n    self: Sink<A, In, L, E, R>,\n    f: (chunk: Chunk.Chunk<In0>) => Chunk.Chunk<In>\n  ): Sink<A, In0, L, E, R>\n} = internal.mapInputChunks\n\n/**\n * Effectfully transforms this sink's input chunks. `f` must preserve\n * chunking-invariance.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapInputChunksEffect: {\n  <In0, In, E2, R2>(\n    f: (chunk: Chunk.Chunk<In0>) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n  ): <A, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In0, L, E2 | E, R2 | R>\n  <A, In, L, E, R, In0, E2, R2>(\n    self: Sink<A, In, L, E, R>,\n    f: (chunk: Chunk.Chunk<In0>) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n  ): Sink<A, In0, L, E | E2, R | R2>\n} = internal.mapInputChunksEffect\n\n/**\n * A sink that counts the number of elements fed to it.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const count: Sink<number, unknown> = internal.count\n\n/**\n * Creates a sink halting with the specified defect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const die: (defect: unknown) => Sink<never, unknown> = internal.die\n\n/**\n * Creates a sink halting with the specified message, wrapped in a\n * `RuntimeException`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dieMessage: (message: string) => Sink<never, unknown> = internal.dieMessage\n\n/**\n * Creates a sink halting with the specified defect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dieSync: (evaluate: LazyArg<unknown>) => Sink<never, unknown> = internal.dieSync\n\n/**\n * Transforms both inputs and result of this sink using the provided\n * functions.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const dimap: {\n  <In0, In, A, A2>(\n    options: { readonly onInput: (input: In0) => In; readonly onDone: (a: A) => A2 }\n  ): <L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A2, In0, L, E, R>\n  <A, In, L, E, R, In0, A2>(\n    self: Sink<A, In, L, E, R>,\n    options: { readonly onInput: (input: In0) => In; readonly onDone: (a: A) => A2 }\n  ): Sink<A2, In0, L, E, R>\n} = internal.dimap\n\n/**\n * Effectfully transforms both inputs and result of this sink using the\n * provided functions.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const dimapEffect: {\n  <In0, In, E2, R2, A, A2, E3, R3>(\n    options: {\n      readonly onInput: (input: In0) => Effect.Effect<In, E2, R2>\n      readonly onDone: (a: A) => Effect.Effect<A2, E3, R3>\n    }\n  ): <L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A2, In0, L, E2 | E3 | E, R2 | R3 | R>\n  <A, In, L, E, R, In0, E2, R2, A2, E3, R3>(\n    self: Sink<A, In, L, E, R>,\n    options: {\n      readonly onInput: (input: In0) => Effect.Effect<In, E2, R2>\n      readonly onDone: (a: A) => Effect.Effect<A2, E3, R3>\n    }\n  ): Sink<A2, In0, L, E | E2 | E3, R | R2 | R3>\n} = internal.dimapEffect\n\n/**\n * Transforms both input chunks and result of this sink using the provided\n * functions.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const dimapChunks: {\n  <In0, In, A, A2>(\n    options: { readonly onInput: (chunk: Chunk.Chunk<In0>) => Chunk.Chunk<In>; readonly onDone: (a: A) => A2 }\n  ): <L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A2, In0, L, E, R>\n  <A, In, L, E, R, In0, A2>(\n    self: Sink<A, In, L, E, R>,\n    options: { readonly onInput: (chunk: Chunk.Chunk<In0>) => Chunk.Chunk<In>; readonly onDone: (a: A) => A2 }\n  ): Sink<A2, In0, L, E, R>\n} = internal.dimapChunks\n\n/**\n * Effectfully transforms both input chunks and result of this sink using the\n * provided functions. `f` and `g` must preserve chunking-invariance.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const dimapChunksEffect: {\n  <In0, In, E2, R2, A, A2, E3, R3>(\n    options: {\n      readonly onInput: (chunk: Chunk.Chunk<In0>) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n      readonly onDone: (a: A) => Effect.Effect<A2, E3, R3>\n    }\n  ): <L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A2, In0, L, E2 | E3 | E, R2 | R3 | R>\n  <A, In, L, E, R, In0, E2, R2, A2, E3, R3>(\n    self: Sink<A, In, L, E, R>,\n    options: {\n      readonly onInput: (chunk: Chunk.Chunk<In0>) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n      readonly onDone: (a: A) => Effect.Effect<A2, E3, R3>\n    }\n  ): Sink<A2, In0, L, E | E2 | E3, R | R2 | R3>\n} = internal.dimapChunksEffect\n\n/**\n * A sink that ignores its inputs.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const drain: Sink<void, unknown> = internal.drain\n\n/**\n * Creates a sink that drops `n` elements.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const drop: <In>(n: number) => Sink<unknown, In, In> = internal.drop\n\n/**\n * Drops incoming elements until the predicate is satisfied.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dropUntil: <In>(predicate: Predicate<In>) => Sink<unknown, In, In> = internal.dropUntil\n\n/**\n * Drops incoming elements until the effectful predicate is satisfied.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dropUntilEffect: <In, E, R>(\n  predicate: (input: In) => Effect.Effect<boolean, E, R>\n) => Sink<unknown, In, In, E, R> = internal.dropUntilEffect\n\n/**\n * Drops incoming elements as long as the predicate is satisfied.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dropWhile: <In>(predicate: Predicate<In>) => Sink<unknown, In, In> = internal.dropWhile\n\n/**\n * Drops incoming elements as long as the effectful predicate is satisfied.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dropWhileEffect: <In, E, R>(\n  predicate: (input: In) => Effect.Effect<boolean, E, R>\n) => Sink<unknown, In, In, E, R> = internal.dropWhileEffect\n\n/**\n * Returns a new sink with an attached finalizer. The finalizer is guaranteed\n * to be executed so long as the sink begins execution (and regardless of\n * whether or not it completes).\n *\n * @since 2.0.0\n * @category finalization\n */\nexport const ensuring: {\n  <X, R2>(\n    finalizer: Effect.Effect<X, never, R2>\n  ): <A, In, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In, L, E, R2 | R>\n  <A, In, L, E, R, X, R2>(self: Sink<A, In, L, E, R>, finalizer: Effect.Effect<X, never, R2>): Sink<A, In, L, E, R | R2>\n} = internal.ensuring\n\n/**\n * Returns a new sink with an attached finalizer. The finalizer is guaranteed\n * to be executed so long as the sink begins execution (and regardless of\n * whether or not it completes).\n *\n * @since 2.0.0\n * @category finalization\n */\nexport const ensuringWith: {\n  <A, E, X, R2>(\n    finalizer: (exit: Exit.Exit<A, E>) => Effect.Effect<X, never, R2>\n  ): <In, L, R>(self: Sink<A, In, L, E, R>) => Sink<A, In, L, E, R2 | R>\n  <A, In, L, E, R, X, R2>(\n    self: Sink<A, In, L, E, R>,\n    finalizer: (exit: Exit.Exit<A, E>) => Effect.Effect<X, never, R2>\n  ): Sink<A, In, L, E, R | R2>\n} = internal.ensuringWith\n\n/**\n * Accesses the whole context of the sink.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const context: <R>() => Sink<Context.Context<R>, unknown, never, never, R> = internal.context\n\n/**\n * Accesses the context of the sink.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const contextWith: <R, Z>(f: (context: Context.Context<R>) => Z) => Sink<Z, unknown, never, never, R> =\n  internal.contextWith\n\n/**\n * Accesses the context of the sink in the context of an effect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const contextWithEffect: <R0, A, E, R>(\n  f: (context: Context.Context<R0>) => Effect.Effect<A, E, R>\n) => Sink<A, unknown, never, E, R0 | R> = internal.contextWithEffect\n\n/**\n * Accesses the context of the sink in the context of a sink.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const contextWithSink: <R0, A, In, L, E, R>(\n  f: (context: Context.Context<R0>) => Sink<A, In, L, E, R>\n) => Sink<A, In, L, E, R0 | R> = internal.contextWithSink\n\n/**\n * A sink that returns whether all elements satisfy the specified predicate.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const every: <In>(predicate: Predicate<In>) => Sink<boolean, In, In> = internal.every\n\n/**\n * A sink that always fails with the specified error.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fail: <E>(e: E) => Sink<never, unknown, never, E> = internal.fail\n\n/**\n * A sink that always fails with the specified lazily evaluated error.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failSync: <E>(evaluate: LazyArg<E>) => Sink<never, unknown, never, E> = internal.failSync\n\n/**\n * Creates a sink halting with a specified `Cause`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCause: <E>(cause: Cause.Cause<E>) => Sink<never, unknown, never, E> = internal.failCause\n\n/**\n * Creates a sink halting with a specified lazily evaluated `Cause`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCauseSync: <E>(evaluate: LazyArg<Cause.Cause<E>>) => Sink<never, unknown, never, E> =\n  internal.failCauseSync\n\n/**\n * Filters the sink's input with the given predicate.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterInput: {\n  <In, In1 extends In, In2 extends In1>(\n    f: Refinement<In1, In2>\n  ): <A, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In2, L, E, R>\n  <In, In1 extends In>(f: Predicate<In1>): <A, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In1, L, E, R>\n} = internal.filterInput\n\n/**\n * Effectfully filter the input of this sink using the specified predicate.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterInputEffect: {\n  <In, In1 extends In, E2, R2>(\n    f: (input: In1) => Effect.Effect<boolean, E2, R2>\n  ): <A, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In1, L, E2 | E, R2 | R>\n  <A, In, L, E, R, In1 extends In, E2, R2>(\n    self: Sink<A, In, L, E, R>,\n    f: (input: In1) => Effect.Effect<boolean, E2, R2>\n  ): Sink<A, In1, L, E | E2, R | R2>\n} = internal.filterInputEffect\n\n/**\n * Creates a sink that produces values until one verifies the predicate `f`.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findEffect: {\n  <A, E2, R2>(\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): <In, L extends In, E, R>(self: Sink<A, In, L, E, R>) => Sink<Option.Option<A>, In, L, E2 | E, R2 | R>\n  <A, In, L extends In, E, R, E2, R2>(\n    self: Sink<A, In, L, E, R>,\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): Sink<Option.Option<A>, In, L, E | E2, R | R2>\n} = internal.findEffect as any\n\n/**\n * A sink that folds its inputs with the provided function, termination\n * predicate and initial state.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const fold: <S, In>(s: S, contFn: Predicate<S>, f: (s: S, input: In) => S) => Sink<S, In, In> = internal.fold\n\n/**\n * Folds over the result of the sink\n *\n * @since 2.0.0\n * @category folding\n */\nexport const foldSink: {\n  <E, A1, In, In1 extends In, L1, E1, R1, A, A2, In2 extends In, L2, E2, R2>(\n    options: {\n      readonly onFailure: (err: E) => Sink<A1, In1, L1, E1, R1>\n      readonly onSuccess: (a: A) => Sink<A2, In2, L2, E2, R2>\n    }\n  ): <L, R>(self: Sink<A, In, L, E, R>) => Sink<A1 | A2, In1 & In2, L1 | L2, E1 | E2, R1 | R2 | R>\n  <A, In, L, E, R, A1, In1 extends In, L1, E1, R1, A2, In2 extends In, L2, E2, R2>(\n    self: Sink<A, In, L, E, R>,\n    options: {\n      readonly onFailure: (err: E) => Sink<A1, In1, L1, E1, R1>\n      readonly onSuccess: (a: A) => Sink<A2, In2, L2, E2, R2>\n    }\n  ): Sink<A1 | A2, In1 & In2, L1 | L2, E1 | E2, R | R1 | R2>\n} = internal.foldSink\n\n/**\n * A sink that folds its input chunks with the provided function, termination\n * predicate and initial state. `contFn` condition is checked only for the\n * initial value and at the end of processing of each chunk. `f` and `contFn`\n * must preserve chunking-invariance.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldChunks: <S, In>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (s: S, chunk: Chunk.Chunk<In>) => S\n) => Sink<S, In> = internal.foldChunks\n\n/**\n * A sink that effectfully folds its input chunks with the provided function,\n * termination predicate and initial state. `contFn` condition is checked only\n * for the initial value and at the end of processing of each chunk. `f` and\n * `contFn` must preserve chunking-invariance.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldChunksEffect: <S, In, E, R>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (s: S, chunk: Chunk.Chunk<In>) => Effect.Effect<S, E, R>\n) => Sink<S, In, In, E, R> = internal.foldChunksEffect\n\n/**\n * A sink that effectfully folds its inputs with the provided function,\n * termination predicate and initial state.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldEffect: <S, In, E, R>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (s: S, input: In) => Effect.Effect<S, E, R>\n) => Sink<S, In, In, E, R> = internal.foldEffect\n\n/**\n * A sink that folds its inputs with the provided function and initial state.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldLeft: <S, In>(s: S, f: (s: S, input: In) => S) => Sink<S, In> = internal.foldLeft\n\n/**\n * A sink that folds its input chunks with the provided function and initial\n * state. `f` must preserve chunking-invariance.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldLeftChunks: <S, In>(s: S, f: (s: S, chunk: Chunk.Chunk<In>) => S) => Sink<S, In> =\n  internal.foldLeftChunks\n\n/**\n * A sink that effectfully folds its input chunks with the provided function\n * and initial state. `f` must preserve chunking-invariance.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldLeftChunksEffect: <S, In, E, R>(\n  s: S,\n  f: (s: S, chunk: Chunk.Chunk<In>) => Effect.Effect<S, E, R>\n) => Sink<S, In, never, E, R> = internal.foldLeftChunksEffect\n\n/**\n * A sink that effectfully folds its inputs with the provided function and\n * initial state.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldLeftEffect: <S, In, E, R>(\n  s: S,\n  f: (s: S, input: In) => Effect.Effect<S, E, R>\n) => Sink<S, In, In, E, R> = internal.foldLeftEffect\n\n/**\n * Creates a sink that folds elements of type `In` into a structure of type\n * `S` until `max` elements have been folded.\n *\n * Like `Sink.foldWeighted`, but with a constant cost function of `1`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldUntil: <In, S>(s: S, max: number, f: (s: S, input: In) => S) => Sink<S, In, In> = internal.foldUntil\n\n/**\n * Creates a sink that effectfully folds elements of type `In` into a\n * structure of type `S` until `max` elements have been folded.\n *\n * Like `Sink.foldWeightedEffect` but with a constant cost function of `1`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldUntilEffect: <S, In, E, R>(\n  s: S,\n  max: number,\n  f: (s: S, input: In) => Effect.Effect<S, E, R>\n) => Sink<S, In, In, E, R> = internal.foldUntilEffect\n\n/**\n * Creates a sink that folds elements of type `In` into a structure of type `S`,\n * until `max` worth of elements (determined by the `costFn`) have been folded.\n *\n * **Note**\n *\n * Elements that have an individual cost larger than `max` will force the sink\n * to cross the `max` cost. See `Sink.foldWeightedDecompose` for a variant\n * that can handle these cases.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldWeighted: <S, In>(\n  options: {\n    readonly initial: S\n    readonly maxCost: number\n    readonly cost: (s: S, input: In) => number\n    readonly body: (s: S, input: In) => S\n  }\n) => Sink<S, In, In> = internal.foldWeighted\n\n/**\n * Creates a sink that folds elements of type `In` into a structure of type\n * `S`, until `max` worth of elements (determined by the `costFn`) have been\n * folded.\n *\n * The `decompose` function will be used for decomposing elements that cause\n * an `S` aggregate to cross `max` into smaller elements. For example:\n *\n * ```ts skip-type-checking\n * pipe(\n *   Stream.make(1, 5, 1),\n *   Stream.transduce(\n *     Sink.foldWeightedDecompose(\n *       Chunk.empty<number>(),\n *       4,\n *       (n: number) => n,\n *       (n: number) => Chunk.make(n - 1, 1),\n *       (acc, el) => pipe(acc, Chunk.append(el))\n *     )\n *   ),\n *   Stream.runCollect\n * )\n * ```\n *\n * The stream would emit the elements `Chunk(1), Chunk(4), Chunk(1, 1)`.\n *\n * Be vigilant with this function, it has to generate \"simpler\" values or the\n * fold may never end. A value is considered indivisible if `decompose` yields\n * the empty chunk or a single-valued chunk. In these cases, there is no other\n * choice than to yield a value that will cross the threshold.\n *\n * `Sink.foldWeightedDecomposeEffect` allows the decompose function to return an\n * effect value, and consequently it allows the sink to fail.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldWeightedDecompose: <S, In>(\n  options: {\n    readonly initial: S\n    readonly maxCost: number\n    readonly cost: (s: S, input: In) => number\n    readonly decompose: (input: In) => Chunk.Chunk<In>\n    readonly body: (s: S, input: In) => S\n  }\n) => Sink<S, In, In> = internal.foldWeightedDecompose\n\n/**\n * Creates a sink that effectfully folds elements of type `In` into a\n * structure of type `S`, until `max` worth of elements (determined by the\n * `costFn`) have been folded.\n *\n * The `decompose` function will be used for decomposing elements that cause\n * an `S` aggregate to cross `max` into smaller elements. Be vigilant with\n * this function, it has to generate \"simpler\" values or the fold may never\n * end. A value is considered indivisible if `decompose` yields the empty\n * chunk or a single-valued chunk. In these cases, there is no other choice\n * than to yield a value that will cross the threshold.\n *\n * See `Sink.foldWeightedDecompose` for an example.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldWeightedDecomposeEffect: <S, In, E, R, E2, R2, E3, R3>(\n  options: {\n    readonly initial: S\n    readonly maxCost: number\n    readonly cost: (s: S, input: In) => Effect.Effect<number, E, R>\n    readonly decompose: (input: In) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n    readonly body: (s: S, input: In) => Effect.Effect<S, E3, R3>\n  }\n) => Sink<S, In, In, E | E2 | E3, R | R2 | R3> = internal.foldWeightedDecomposeEffect\n\n/**\n * Creates a sink that effectfully folds elements of type `In` into a\n * structure of type `S`, until `max` worth of elements (determined by the\n * `costFn`) have been folded.\n *\n * @note\n *   Elements that have an individual cost larger than `max` will force the\n *   sink to cross the `max` cost. See `Sink.foldWeightedDecomposeEffect` for\n *   a variant that can handle these cases.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const foldWeightedEffect: <S, In, E, R, E2, R2>(\n  options: {\n    readonly initial: S\n    readonly maxCost: number\n    readonly cost: (s: S, input: In) => Effect.Effect<number, E, R>\n    readonly body: (s: S, input: In) => Effect.Effect<S, E2, R2>\n  }\n) => Sink<S, In, In, E | E2, R | R2> = internal.foldWeightedEffect\n\n/**\n * A sink that executes the provided effectful function for every element fed\n * to it.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const forEach: <In, X, E, R>(f: (input: In) => Effect.Effect<X, E, R>) => Sink<void, In, never, E, R> =\n  internal.forEach\n\n/**\n * A sink that executes the provided effectful function for every chunk fed to\n * it.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const forEachChunk: <In, X, E, R>(\n  f: (input: Chunk.Chunk<In>) => Effect.Effect<X, E, R>\n) => Sink<void, In, never, E, R> = internal.forEachChunk\n\n/**\n * A sink that executes the provided effectful function for every chunk fed to\n * it until `f` evaluates to `false`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const forEachChunkWhile: <In, E, R>(\n  f: (input: Chunk.Chunk<In>) => Effect.Effect<boolean, E, R>\n) => Sink<void, In, In, E, R> = internal.forEachChunkWhile\n\n/**\n * A sink that executes the provided effectful function for every element fed\n * to it until `f` evaluates to `false`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const forEachWhile: <In, E, R>(f: (input: In) => Effect.Effect<boolean, E, R>) => Sink<void, In, In, E, R> =\n  internal.forEachWhile\n\n/**\n * Runs this sink until it yields a result, then uses that result to create\n * another sink from the provided function which will continue to run until it\n * yields a result.\n *\n * This function essentially runs sinks in sequence.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMap: {\n  <A, A1, In, In1 extends In, L1, E1, R1>(\n    f: (a: A) => Sink<A1, In1, L1, E1, R1>\n  ): <L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A1, In & In1, L1 | L, E1 | E, R1 | R>\n  <A, In, L, E, R, A1, In1 extends In, L1, E1, R1>(\n    self: Sink<A, In, L, E, R>,\n    f: (a: A) => Sink<A1, In1, L1, E1, R1>\n  ): Sink<A1, In & In1, L | L1, E | E1, R | R1>\n} = internal.flatMap\n\n/**\n * Creates a sink from a `Channel`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromChannel: <L, In, E, A, R>(\n  channel: Channel.Channel<Chunk.Chunk<L>, Chunk.Chunk<In>, E, never, A, unknown, R>\n) => Sink<A, In, L, E, R> = internal.fromChannel\n\n/**\n * Creates a `Channel` from a Sink.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const toChannel: <A, In, L, E, R>(\n  self: Sink<A, In, L, E, R>\n) => Channel.Channel<Chunk.Chunk<L>, Chunk.Chunk<In>, E, never, A, unknown, R> = internal.toChannel\n\n/**\n * Creates a single-value sink produced from an effect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEffect: <A, E, R>(effect: Effect.Effect<A, E, R>) => Sink<A, unknown, never, E, R> =\n  internal.fromEffect\n\n/**\n * Create a sink which publishes each element to the specified `PubSub`.\n *\n * If the `shutdown` parameter is `true`, the `PubSub` will be shutdown after\n * the sink is evaluated (defaults to `false`).\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromPubSub: <In>(\n  pubsub: PubSub.PubSub<In>,\n  options?: {\n    readonly shutdown?: boolean | undefined\n  }\n) => Sink<void, In> = internal.fromPubSub\n\n/**\n * Creates a sink from a chunk processing function.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromPush: <In, L0, R0, L, R>(\n  push: Effect.Effect<\n    (_: Option.Option<Chunk.Chunk<In>>) => Effect.Effect<void, readonly [Either.Either<R0, L0>, Chunk.Chunk<L>], R>,\n    never,\n    R\n  >\n) => Sink<R0, In, L, L0, Exclude<R, Scope.Scope>> = internal.fromPush\n\n/**\n * Create a sink which enqueues each element into the specified queue.\n *\n * If the `shutdown` parameter is `true`, the queue will be shutdown after the\n * sink is evaluated (defaults to `false`).\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromQueue: <In>(\n  queue: Queue.Enqueue<In>,\n  options?: {\n    readonly shutdown?: boolean | undefined\n  }\n) => Sink<void, In> = internal.fromQueue\n\n/**\n * Creates a sink containing the first value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const head: <In>() => Sink<Option.Option<In>, In, In> = internal.head\n\n/**\n * Drains the remaining elements from the stream after the sink finishes\n *\n * @since 2.0.0\n * @category utils\n */\nexport const ignoreLeftover: <A, In, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In, never, E, R> =\n  internal.ignoreLeftover\n\n/**\n * Creates a sink containing the last value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const last: <In>() => Sink<Option.Option<In>, In, In> = internal.last\n\n/**\n * Creates a sink that does not consume any input but provides the given chunk\n * as its leftovers\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const leftover: <L>(chunk: Chunk.Chunk<L>) => Sink<void, unknown, L> = internal.leftover\n\n/**\n * Transforms this sink's result.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <A, A2>(f: (a: A) => A2): <In, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A2, In, L, E, R>\n  <A, In, L, E, R, A2>(self: Sink<A, In, L, E, R>, f: (a: A) => A2): Sink<A2, In, L, E, R>\n} = internal.map\n\n/**\n * Effectfully transforms this sink's result.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapEffect: {\n  <A, A2, E2, R2>(\n    f: (a: A) => Effect.Effect<A2, E2, R2>\n  ): <In, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A2, In, L, E2 | E, R2 | R>\n  <A, In, L, E, R, A2, E2, R2>(\n    self: Sink<A, In, L, E, R>,\n    f: (a: A) => Effect.Effect<A2, E2, R2>\n  ): Sink<A2, In, L, E | E2, R | R2>\n} = internal.mapEffect\n\n/**\n * Transforms the errors emitted by this sink using `f`.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapError: {\n  <E, E2>(f: (error: E) => E2): <A, In, L, R>(self: Sink<A, In, L, E, R>) => Sink<A, In, L, E2, R>\n  <A, In, L, E, R, E2>(self: Sink<A, In, L, E, R>, f: (error: E) => E2): Sink<A, In, L, E2, R>\n} = internal.mapError\n\n/**\n * Transforms the leftovers emitted by this sink using `f`.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapLeftover: {\n  <L, L2>(f: (leftover: L) => L2): <A, In, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In, L2, E, R>\n  <A, In, L, E, R, L2>(self: Sink<A, In, L, E, R>, f: (leftover: L) => L2): Sink<A, In, L2, E, R>\n} = internal.mapLeftover\n\n/**\n * Creates a sink which transforms it's inputs into a string.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const mkString: Sink<string, unknown> = internal.mkString\n\n/**\n * Creates a sink which never terminates.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const never: Sink<never, unknown> = internal.never\n\n/**\n * Switch to another sink in case of failure\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElse: {\n  <A2, In2, L2, E2, R2>(\n    that: LazyArg<Sink<A2, In2, L2, E2, R2>>\n  ): <A, In, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A2 | A, In & In2, L2 | L, E2 | E, R2 | R>\n  <A, In, L, E, R, A2, In2, L2, E2, R2>(\n    self: Sink<A, In, L, E, R>,\n    that: LazyArg<Sink<A2, In2, L2, E2, R2>>\n  ): Sink<A | A2, In & In2, L | L2, E | E2, R | R2>\n} = internal.orElse\n\n/**\n * Provides the sink with its required context, which eliminates its\n * dependency on `R`.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideContext: {\n  <R>(context: Context.Context<R>): <A, In, L, E>(self: Sink<A, In, L, E, R>) => Sink<A, In, L, E, never>\n  <A, In, L, E, R>(self: Sink<A, In, L, E, R>, context: Context.Context<R>): Sink<A, In, L, E, never>\n} = internal.provideContext\n\n/**\n * Runs both sinks in parallel on the input, , returning the result or the\n * error from the one that finishes first.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const race: {\n  <R1, E1, In1, L1, A1>(\n    that: Sink<A1, In1, L1, E1, R1>\n  ): <A, In, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A1 | A, In & In1, L1 | L, E1 | E, R1 | R>\n  <A, In, L, E, R, A1, In1, L1, E1, R1>(\n    self: Sink<A, In, L, E, R>,\n    that: Sink<A1, In1, L1, E1, R1>\n  ): Sink<A | A1, In & In1, L | L1, E | E1, R | R1>\n} = internal.race\n\n/**\n * Runs both sinks in parallel on the input, returning the result or the error\n * from the one that finishes first.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const raceBoth: {\n  <A1, In1, L1, E1, R1>(\n    that: Sink<A1, In1, L1, E1, R1>,\n    options?: { readonly capacity?: number | undefined } | undefined\n  ): <A, In, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<Either.Either<A1, A>, In & In1, L1 | L, E1 | E, R1 | R>\n  <A, In, L, E, R, A1, In1, L1, E1, R1>(\n    self: Sink<A, In, L, E, R>,\n    that: Sink<A1, In1, L1, E1, R1>,\n    options?: { readonly capacity?: number | undefined } | undefined\n  ): Sink<Either.Either<A1, A>, In & In1, L | L1, E | E1, R | R1>\n} = internal.raceBoth\n\n/**\n * Runs both sinks in parallel on the input, using the specified merge\n * function as soon as one result or the other has been computed.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const raceWith: {\n  <A2, In2, L2, E2, R2, A, E, A3, A4>(\n    options: {\n      readonly other: Sink<A2, In2, L2, E2, R2>\n      readonly onSelfDone: (exit: Exit.Exit<A, E>) => MergeDecision.MergeDecision<R2, E2, A2, E2 | E, A3>\n      readonly onOtherDone: (exit: Exit.Exit<A2, E2>) => MergeDecision.MergeDecision<R2, E, A, E2 | E, A4>\n      readonly capacity?: number | undefined\n    }\n  ): <In, L, R>(self: Sink<A, In, L, E, R>) => Sink<A3 | A4, In & In2, L2 | L, E2 | E, R2 | R>\n  <A, In, L, E, R, A2, In2, L2, E2, R2, A3, A4>(\n    self: Sink<A, In, L, E, R>,\n    options: {\n      readonly other: Sink<A2, In2, L2, E2, R2>\n      readonly onSelfDone: (exit: Exit.Exit<A, E>) => MergeDecision.MergeDecision<R2, E2, A2, E | E2, A3>\n      readonly onOtherDone: (exit: Exit.Exit<A2, E2>) => MergeDecision.MergeDecision<R2, E, A, E | E2, A4>\n      readonly capacity?: number | undefined\n    }\n  ): Sink<A3 | A4, In & In2, L | L2, E | E2, R | R2>\n} = internal.raceWith\n\n/**\n * @since 2.0.0\n * @category error handling\n */\nexport const refineOrDie: {\n  <E, E2>(pf: (error: E) => Option.Option<E2>): <A, In, L, R>(self: Sink<A, In, L, E, R>) => Sink<A, In, L, E2, R>\n  <A, In, L, E, R, E2>(self: Sink<A, In, L, E, R>, pf: (error: E) => Option.Option<E2>): Sink<A, In, L, E2, R>\n} = internal.refineOrDie\n\n/**\n * @since 2.0.0\n * @category error handling\n */\nexport const refineOrDieWith: {\n  <E, E2>(\n    pf: (error: E) => Option.Option<E2>,\n    f: (error: E) => unknown\n  ): <A, In, L, R>(self: Sink<A, In, L, E, R>) => Sink<A, In, L, E2, R>\n  <A, In, L, E, R, E2>(\n    self: Sink<A, In, L, E, R>,\n    pf: (error: E) => Option.Option<E2>,\n    f: (error: E) => unknown\n  ): Sink<A, In, L, E2, R>\n} = internal.refineOrDieWith\n\n/**\n * A sink that returns whether an element satisfies the specified predicate.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const some: <In>(predicate: Predicate<In>) => Sink<boolean, In, In> = internal.some\n\n/**\n * Splits the sink on the specified predicate, returning a new sink that\n * consumes elements until an element after the first satisfies the specified\n * predicate.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const splitWhere: {\n  <In>(f: Predicate<In>): <A, L extends In, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In, In, E, R>\n  <A, In, L extends In, E, R>(self: Sink<A, In, L, E, R>, f: Predicate<In>): Sink<A, In, In, E, R>\n} = internal.splitWhere\n\n/**\n * A sink that immediately ends with the specified value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeed: <A>(a: A) => Sink<A, unknown> = internal.succeed\n\n/**\n * A sink that sums incoming numeric values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sum: Sink<number, number> = internal.sum\n\n/**\n * Summarize a sink by running an effect when the sink starts and again when\n * it completes.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const summarized: {\n  <A2, E2, R2, A3>(\n    summary: Effect.Effect<A2, E2, R2>,\n    f: (start: A2, end: A2) => A3\n  ): <A, In, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<[A, A3], In, L, E2 | E, R2 | R>\n  <A, In, L, E, R, A2, E2, R2, A3>(\n    self: Sink<A, In, L, E, R>,\n    summary: Effect.Effect<A2, E2, R2>,\n    f: (start: A2, end: A2) => A3\n  ): Sink<[A, A3], In, L, E | E2, R | R2>\n} = internal.summarized\n\n/**\n * Returns a lazily constructed sink that may require effects for its\n * creation.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const suspend: <A, In, L, E, R>(evaluate: LazyArg<Sink<A, In, L, E, R>>) => Sink<A, In, L, E, R> =\n  internal.suspend\n\n/**\n * A sink that immediately ends with the specified lazy value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sync: <A>(evaluate: LazyArg<A>) => Sink<A, unknown> = internal.sync\n\n/**\n * A sink that takes the specified number of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const take: <In>(n: number) => Sink<Chunk.Chunk<In>, In, In> = internal.take\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const timed: Sink<Duration.Duration, unknown> = internal.timed\n\n/**\n * Creates a sink produced from an effect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unwrap: <A, In, L, E2, R2, E, R>(\n  effect: Effect.Effect<Sink<A, In, L, E2, R2>, E, R>\n) => Sink<A, In, L, E2 | E, R2 | R> = internal.unwrap\n\n/**\n * Creates a sink produced from a scoped effect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unwrapScoped: <A, In, L, E, R>(\n  effect: Effect.Effect<Sink<A, In, L, E, R>, E, R>\n) => Sink<A, In, L, E, Exclude<R, Scope.Scope>> = internal.unwrapScoped\n\n/**\n * Constructs a `Sink` from a function which receives a `Scope` and returns\n * an effect that will result in a `Sink` if successful.\n *\n * @since 3.11.0\n * @category constructors\n */\nexport const unwrapScopedWith: <A, In, L, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<Sink<A, In, L, E, R>, E, R>\n) => Sink<A, In, L, E, R> = internal.unwrapScopedWith\n\n/**\n * Returns the sink that executes this one and times its execution.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const withDuration: <A, In, L, E, R>(\n  self: Sink<A, In, L, E, R>\n) => Sink<[A, Duration.Duration], In, L, E, R> = internal.withDuration\n\n/**\n * Feeds inputs to this sink until it yields a result, then switches over to\n * the provided sink until it yields a result, finally combining the two\n * results into a tuple.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zip: {\n  <A2, In, In2 extends In, L2, E2, R2>(\n    that: Sink<A2, In2, L2, E2, R2>,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): <A, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<[A, A2], In & In2, L2 | L, E2 | E, R2 | R>\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2>(\n    self: Sink<A, In, L, E, R>,\n    that: Sink<A2, In2, L2, E2, R2>,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): Sink<[A, A2], In & In2, L | L2, E | E2, R | R2>\n} = internal.zip\n\n/**\n * Like `Sink.zip` but keeps only the result from this sink.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipLeft: {\n  <A2, In, In2 extends In, L2, E2, R2>(\n    that: Sink<A2, In2, L2, E2, R2>,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): <A, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A, In & In2, L2 | L, E2 | E, R2 | R>\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2>(\n    self: Sink<A, In, L, E, R>,\n    that: Sink<A2, In2, L2, E2, R2>,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): Sink<A, In & In2, L | L2, E | E2, R | R2>\n} = internal.zipLeft\n\n/**\n * Like `Sink.zip` but keeps only the result from `that` sink.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipRight: {\n  <A2, In, In2 extends In, L2, E2, R2>(\n    that: Sink<A2, In2, L2, E2, R2>,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): <A, L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A2, In & In2, L2 | L, E2 | E, R2 | R>\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2>(\n    self: Sink<A, In, L, E, R>,\n    that: Sink<A2, In2, L2, E2, R2>,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): Sink<A2, In & In2, L | L2, E | E2, R | R2>\n} = internal.zipRight\n\n/**\n * Feeds inputs to this sink until it yields a result, then switches over to\n * the provided sink until it yields a result, finally combining the two\n * results with `f`.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWith: {\n  <A2, In, In2 extends In, L2, E2, R2, A, A3>(\n    that: Sink<A2, In2, L2, E2, R2>,\n    f: (a: A, a2: A2) => A3,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): <L, E, R>(self: Sink<A, In, L, E, R>) => Sink<A3, In & In2, L2 | L, E2 | E, R2 | R>\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2, A3>(\n    self: Sink<A, In, L, E, R>,\n    that: Sink<A2, In2, L2, E2, R2>,\n    f: (a: A, a2: A2) => A3,\n    options?: { readonly concurrent?: boolean | undefined } | undefined\n  ): Sink<A3, In & In2, L | L2, E | E2, R | R2>\n} = internal.zipWith\n"
  },
  {
    "path": "packages/effect/src/SortedMap.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\"\nimport * as Dual from \"./Function.js\"\nimport { pipe } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport { format, type Inspectable, NodeInspectSymbol, toJSON } from \"./Inspectable.js\"\nimport * as Option from \"./Option.js\"\nimport type { Order } from \"./Order.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport * as RBT from \"./RedBlackTree.js\"\nimport type * as Types from \"./Types.js\"\n\nconst TypeId: unique symbol = Symbol.for(\"effect/SortedMap\")\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface SortedMap<in out K, out V> extends Iterable<[K, V]>, Equal.Equal, Pipeable, Inspectable {\n  readonly [TypeId]: {\n    readonly _K: Types.Invariant<K>\n    readonly _V: Types.Covariant<V>\n  }\n  /** @internal */\n  readonly tree: RBT.RedBlackTree<K, V>\n}\n\nconst SortedMapProto: Omit<SortedMap<unknown, unknown>, \"tree\"> = {\n  [TypeId]: {\n    _K: (_: any) => _,\n    _V: (_: never) => _\n  },\n  [Hash.symbol]<K, V>(this: SortedMap<K, V>): number {\n    return pipe(\n      Hash.hash(this.tree),\n      Hash.combine(Hash.hash(\"effect/SortedMap\")),\n      Hash.cached(this)\n    )\n  },\n  [Equal.symbol]<K, V>(this: SortedMap<K, V>, that: unknown): boolean {\n    return isSortedMap(that) && Equal.equals(this.tree, that.tree)\n  },\n  [Symbol.iterator]<K, V>(this: SortedMap<K, V>): Iterator<[K, V]> {\n    return this.tree[Symbol.iterator]()\n  },\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"SortedMap\",\n      values: Array.from(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makeImpl = <K, V>(tree: RBT.RedBlackTree<K, V>): SortedMap<K, V> => {\n  const self = Object.create(SortedMapProto)\n  self.tree = tree\n  return self\n}\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isSortedMap: {\n  <K, V>(u: Iterable<readonly [K, V]>): u is SortedMap<K, V>\n  (u: unknown): u is SortedMap<unknown, unknown>\n} = (u: unknown): u is SortedMap<unknown, unknown> => hasProperty(u, TypeId)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const empty = <K, V = never>(ord: Order<K>): SortedMap<K, V> => makeImpl<K, V>(RBT.empty<K, V>(ord))\n\n/**\n * Creates a new `SortedMap` from an iterable collection of key/value pairs.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: {\n  <B>(ord: Order<B>): <K extends B, V>(iterable: Iterable<readonly [K, V]>) => SortedMap<K, V>\n  <K extends B, V, B>(iterable: Iterable<readonly [K, V]>, ord: Order<B>): SortedMap<K, V>\n} = Dual.dual(\n  2,\n  <K extends B, V, B>(iterable: Iterable<readonly [K, V]>, ord: Order<B>): SortedMap<K, V> =>\n    makeImpl(RBT.fromIterable(iterable, ord))\n)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make =\n  <K>(ord: Order<K>) =>\n  <Entries extends ReadonlyArray<readonly [K, any]>>(...entries: Entries): SortedMap<\n    K,\n    Entries[number] extends (readonly [any, infer V]) ? V : never\n  > => fromIterable(ord)(entries)\n\n/**\n * @since 2.0.0\n * @category predicates\n */\nexport const isEmpty = <K, V>(self: SortedMap<K, V>): boolean => size(self) === 0\n\n/**\n * @since 2.0.0\n * @category predicates\n */\nexport const isNonEmpty = <K, V>(self: SortedMap<K, V>): boolean => size(self) > 0\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const get: {\n  <K>(key: K): <V>(self: SortedMap<K, V>) => Option.Option<V>\n  <K, V>(self: SortedMap<K, V>, key: K): Option.Option<V>\n} = Dual.dual<\n  <K>(key: K) => <V>(self: SortedMap<K, V>) => Option.Option<V>,\n  <K, V>(self: SortedMap<K, V>, key: K) => Option.Option<V>\n>(2, (self, key) => RBT.findFirst(self.tree, key))\n\n/**\n * Gets the `Order<K>` that the `SortedMap<K, V>` is using.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const getOrder = <K, V>(self: SortedMap<K, V>): Order<K> => RBT.getOrder(self.tree)\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const has: {\n  <K>(key: K): <V>(self: SortedMap<K, V>) => boolean\n  <K, V>(self: SortedMap<K, V>, key: K): boolean\n} = Dual.dual<\n  <K>(key: K) => <V>(self: SortedMap<K, V>) => boolean,\n  <K, V>(self: SortedMap<K, V>, key: K) => boolean\n>(2, (self, key) => Option.isSome(get(self, key)))\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const headOption = <K, V>(self: SortedMap<K, V>): Option.Option<[K, V]> => RBT.first(self.tree)\n\n/**\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <A, K, B>(f: (a: A, k: K) => B): (self: SortedMap<K, A>) => SortedMap<K, B>\n  <K, A, B>(self: SortedMap<K, A>, f: (a: A, k: K) => B): SortedMap<K, B>\n} = Dual.dual<\n  <A, K, B>(f: (a: A, k: K) => B) => (self: SortedMap<K, A>) => SortedMap<K, B>,\n  <K, A, B>(self: SortedMap<K, A>, f: (a: A, k: K) => B) => SortedMap<K, B>\n>(2, <K, A, B>(self: SortedMap<K, A>, f: (a: A, k: K) => B) =>\n  reduce(\n    self,\n    empty<K, B>(RBT.getOrder(self.tree)),\n    (acc, v, k) => set(acc, k, f(v, k))\n  ))\n\n/**\n * @since 2.0.0\n * @category folding\n */\nexport const reduce: {\n  <B, A, K>(zero: B, f: (acc: B, value: A, key: K) => B): (self: SortedMap<K, A>) => B\n  <K, A, B>(self: SortedMap<K, A>, zero: B, f: (acc: B, value: A, key: K) => B): B\n} = Dual.dual<\n  <B, A, K>(zero: B, f: (acc: B, value: A, key: K) => B) => (self: SortedMap<K, A>) => B,\n  <K, A, B>(self: SortedMap<K, A>, zero: B, f: (acc: B, value: A, key: K) => B) => B\n>(3, (self, zero, f) => RBT.reduce(self.tree, zero, f))\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const remove: {\n  <K>(key: K): <V>(self: SortedMap<K, V>) => SortedMap<K, V>\n  <K, V>(self: SortedMap<K, V>, key: K): SortedMap<K, V>\n} = Dual.dual<\n  <K>(key: K) => <V>(self: SortedMap<K, V>) => SortedMap<K, V>,\n  <K, V>(self: SortedMap<K, V>, key: K) => SortedMap<K, V>\n>(2, (self, key) => makeImpl(RBT.removeFirst(self.tree, key)))\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const set: {\n  <K, V>(key: K, value: V): (self: SortedMap<K, V>) => SortedMap<K, V>\n  <K, V>(self: SortedMap<K, V>, key: K, value: V): SortedMap<K, V>\n} = Dual.dual<\n  <K, V>(key: K, value: V) => (self: SortedMap<K, V>) => SortedMap<K, V>,\n  <K, V>(self: SortedMap<K, V>, key: K, value: V) => SortedMap<K, V>\n>(3, (self, key, value) =>\n  RBT.has(self.tree, key)\n    ? makeImpl(RBT.insert(RBT.removeFirst(self.tree, key), key, value))\n    : makeImpl(RBT.insert(self.tree, key, value)))\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const size = <K, V>(self: SortedMap<K, V>): number => RBT.size(self.tree)\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const keys = <K, V>(self: SortedMap<K, V>): IterableIterator<K> => RBT.keys(self.tree)\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const values = <K, V>(self: SortedMap<K, V>): IterableIterator<V> => RBT.values(self.tree)\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const entries = <K, V>(self: SortedMap<K, V>): IterableIterator<[K, V]> => {\n  const iterator: any = self.tree[Symbol.iterator]()\n  iterator[Symbol.iterator] = () => entries(self)\n  return iterator\n}\n\n/**\n * @since 3.1.0\n * @category elements\n */\nexport const lastOption = <K, V>(self: SortedMap<K, V>): Option.Option<[K, V]> => RBT.last(self.tree)\n\n/**\n * @since 3.1.0\n * @category filtering\n */\nexport const partition: {\n  <K, V>(\n    predicate: (a: Types.NoInfer<K>) => boolean\n  ): (self: SortedMap<K, V>) => [excluded: SortedMap<K, V>, satisfying: SortedMap<K, V>]\n  <K, V>(self: SortedMap<K, V>, predicate: (a: K) => boolean): [excluded: SortedMap<K, V>, satisfying: SortedMap<K, V>]\n} = Dual.dual(\n  2,\n  <K, V>(\n    self: SortedMap<K, V>,\n    predicate: (a: K) => boolean\n  ): [excluded: SortedMap<K, V>, satisfying: SortedMap<K, V>] => {\n    const ord = RBT.getOrder(self.tree)\n    let right = empty<K, V>(ord)\n    let left = empty<K, V>(ord)\n    for (const value of self) {\n      if (predicate(value[0])) {\n        right = set(right, value[0], value[1])\n      } else {\n        left = set(left, value[0], value[1])\n      }\n    }\n    return [left, right]\n  }\n)\n"
  },
  {
    "path": "packages/effect/src/SortedSet.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\"\nimport type * as Equivalence from \"./Equivalence.js\"\nimport * as Dual from \"./Function.js\"\nimport { pipe } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"./Inspectable.js\"\nimport type { Order } from \"./Order.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\nimport type { Predicate } from \"./Predicate.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport * as RBT from \"./RedBlackTree.js\"\nimport type { Invariant, NoInfer } from \"./Types.js\"\n\nconst TypeId: unique symbol = Symbol.for(\"effect/SortedSet\")\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface SortedSet<in out A> extends Iterable<A>, Equal.Equal, Pipeable, Inspectable {\n  readonly [TypeId]: {\n    readonly _A: Invariant<A>\n  }\n  /** @internal */\n  readonly keyTree: RBT.RedBlackTree<A, boolean>\n}\n\nconst SortedSetProto: Omit<SortedSet<unknown>, \"keyTree\"> = {\n  [TypeId]: {\n    _A: (_: any) => _\n  },\n  [Hash.symbol]<A>(this: SortedSet<A>): number {\n    return pipe(\n      Hash.hash(this.keyTree),\n      Hash.combine(Hash.hash(TypeId)),\n      Hash.cached(this)\n    )\n  },\n  [Equal.symbol]<A>(this: SortedSet<A>, that: unknown): boolean {\n    return isSortedSet(that) && Equal.equals(this.keyTree, that.keyTree)\n  },\n  [Symbol.iterator]<A>(this: SortedSet<A>): Iterator<A> {\n    return RBT.keys(this.keyTree)\n  },\n  toString<A>(this: SortedSet<A>) {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"SortedSet\",\n      values: Array.from(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst fromTree = <A>(keyTree: RBT.RedBlackTree<A, boolean>): SortedSet<A> => {\n  const a = Object.create(SortedSetProto)\n  a.keyTree = keyTree\n  return a\n}\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isSortedSet: {\n  <A>(u: Iterable<A>): u is SortedSet<A>\n  (u: unknown): u is SortedSet<unknown>\n} = (u: unknown): u is SortedSet<unknown> => hasProperty(u, TypeId)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const empty = <A>(O: Order<A>): SortedSet<A> => fromTree(RBT.empty(O))\n\n/**\n * Creates a new `SortedSet` from an iterable collection of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: {\n  <B>(ord: Order<B>): <A extends B>(iterable: Iterable<A>) => SortedSet<A>\n  <A extends B, B>(iterable: Iterable<A>, ord: Order<B>): SortedSet<A>\n} = Dual.dual(\n  2,\n  <A extends B, B>(iterable: Iterable<A>, ord: Order<B>): SortedSet<A> =>\n    fromTree(RBT.fromIterable(Array.from(iterable).map((k) => [k, true]), ord))\n)\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make =\n  <K>(ord: Order<K>) => <Entries extends ReadonlyArray<K>>(...entries: Entries): SortedSet<Entries[number]> =>\n    fromIterable(entries, ord)\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const add: {\n  <A>(value: A): (self: SortedSet<A>) => SortedSet<A>\n  <A>(self: SortedSet<A>, value: A): SortedSet<A>\n} = Dual.dual<\n  <A>(value: A) => (self: SortedSet<A>) => SortedSet<A>,\n  <A>(self: SortedSet<A>, value: A) => SortedSet<A>\n>(2, (self, value) =>\n  RBT.has(self.keyTree, value)\n    ? self\n    : fromTree(RBT.insert(self.keyTree, value, true)))\n\n/**\n * @since 2.0.0\n */\nexport const difference: {\n  <A, B extends A>(that: Iterable<B>): (self: SortedSet<A>) => SortedSet<A>\n  <A, B extends A>(self: SortedSet<A>, that: Iterable<B>): SortedSet<A>\n} = Dual.dual<\n  <A, B extends A>(that: Iterable<B>) => (self: SortedSet<A>) => SortedSet<A>,\n  <A, B extends A>(self: SortedSet<A>, that: Iterable<B>) => SortedSet<A>\n>(2, <A, B extends A>(self: SortedSet<A>, that: Iterable<B>) => {\n  let out = self\n  for (const value of that) {\n    out = remove<A | B>(out, value)\n  }\n  return out\n})\n\n/**\n * Check if a predicate holds true for every `SortedSet` element.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const every: {\n  <A>(predicate: Predicate<A>): (self: SortedSet<A>) => boolean\n  <A>(self: SortedSet<A>, predicate: Predicate<A>): boolean\n} = Dual.dual(2, <A>(self: SortedSet<A>, predicate: Predicate<A>): boolean => {\n  for (const value of self) {\n    if (!predicate(value)) {\n      return false\n    }\n  }\n  return true\n})\n\n/**\n * @since 2.0.0\n * @category filtering\n */\nexport const filter: {\n  <A, B extends A>(predicate: Predicate<B>): (self: SortedSet<A>) => SortedSet<A>\n  <A>(self: SortedSet<A>, predicate: Predicate<A>): SortedSet<A>\n} = Dual.dual(2, <A>(self: SortedSet<A>, predicate: Predicate<A>): SortedSet<A> => {\n  const ord = RBT.getOrder(self.keyTree)\n  let out = empty<A>(ord)\n  for (const value of self) {\n    if (predicate(value)) {\n      out = add(out, value)\n    }\n  }\n  return out\n})\n\n/**\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMap: {\n  <B, A>(O: Order<B>, f: (a: A) => Iterable<B>): (self: SortedSet<A>) => SortedSet<B>\n  <A, B>(self: SortedSet<A>, O: Order<B>, f: (a: A) => Iterable<B>): SortedSet<B>\n} = Dual.dual<\n  <B, A>(O: Order<B>, f: (a: A) => Iterable<B>) => (self: SortedSet<A>) => SortedSet<B>,\n  <A, B>(self: SortedSet<A>, O: Order<B>, f: (a: A) => Iterable<B>) => SortedSet<B>\n>(3, (self, O, f) => {\n  let out = empty(O)\n  forEach(self, (a) => {\n    for (const b of f(a)) {\n      out = add(out, b)\n    }\n  })\n  return out\n})\n\n/**\n * @since 2.0.0\n * @category traversing\n */\nexport const forEach: {\n  <A>(f: (a: A) => void): (self: SortedSet<A>) => void\n  <A>(self: SortedSet<A>, f: (a: A) => void): void\n} = Dual.dual<\n  <A>(f: (a: A) => void) => (self: SortedSet<A>) => void,\n  <A>(self: SortedSet<A>, f: (a: A) => void) => void\n>(2, (self, f) => RBT.forEach(self.keyTree, f))\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const has: {\n  <A>(value: A): (self: SortedSet<A>) => boolean\n  <A>(self: SortedSet<A>, value: A): boolean\n} = Dual.dual<\n  <A>(value: A) => (self: SortedSet<A>) => boolean,\n  <A>(self: SortedSet<A>, value: A) => boolean\n>(2, (self, value) => RBT.has(self.keyTree, value))\n\n/**\n * @since 2.0.0\n */\nexport const intersection: {\n  <A>(that: Iterable<A>): (self: SortedSet<A>) => SortedSet<A>\n  <A>(self: SortedSet<A>, that: Iterable<A>): SortedSet<A>\n} = Dual.dual<\n  <A>(that: Iterable<A>) => (self: SortedSet<A>) => SortedSet<A>,\n  <A>(self: SortedSet<A>, that: Iterable<A>) => SortedSet<A>\n>(2, (self, that) => {\n  const ord = RBT.getOrder(self.keyTree)\n  let out = empty(ord)\n  for (const value of that) {\n    if (has(self, value)) {\n      out = add(out, value)\n    }\n  }\n  return out\n})\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const isSubset: {\n  <A>(that: SortedSet<A>): (self: SortedSet<A>) => boolean\n  <A>(self: SortedSet<A>, that: SortedSet<A>): boolean\n} = Dual.dual<\n  <A>(that: SortedSet<A>) => (self: SortedSet<A>) => boolean,\n  <A>(self: SortedSet<A>, that: SortedSet<A>) => boolean\n>(2, (self, that) => every(self, (a) => has(that, a)))\n\n/**\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <B, A>(O: Order<B>, f: (a: A) => B): (self: SortedSet<A>) => SortedSet<B>\n  <B, A>(self: SortedSet<A>, O: Order<B>, f: (a: A) => B): SortedSet<B>\n} = Dual.dual<\n  <B, A>(O: Order<B>, f: (a: A) => B) => (self: SortedSet<A>) => SortedSet<B>,\n  <B, A>(self: SortedSet<A>, O: Order<B>, f: (a: A) => B) => SortedSet<B>\n>(3, (self, O, f) => {\n  let out = empty(O)\n  forEach(self, (a) => {\n    const b = f(a)\n    if (!has(out, b)) {\n      out = add(out, b)\n    }\n  })\n  return out\n})\n\n/**\n * @since 2.0.0\n * @category filtering\n */\nexport const partition: {\n  <A>(\n    predicate: (a: NoInfer<A>) => boolean\n  ): (self: SortedSet<A>) => [excluded: SortedSet<A>, satisfying: SortedSet<A>]\n  <A>(self: SortedSet<A>, predicate: (a: A) => boolean): [excluded: SortedSet<A>, satisfying: SortedSet<A>]\n} = Dual.dual(\n  2,\n  <A>(self: SortedSet<A>, predicate: (a: A) => boolean): [excluded: SortedSet<A>, satisfying: SortedSet<A>] => {\n    const ord = RBT.getOrder(self.keyTree)\n    let right = empty(ord)\n    let left = empty(ord)\n    for (const value of self) {\n      if (predicate(value)) {\n        right = add(right, value)\n      } else {\n        left = add(left, value)\n      }\n    }\n    return [left, right]\n  }\n)\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const remove: {\n  <A>(value: A): (self: SortedSet<A>) => SortedSet<A>\n  <A>(self: SortedSet<A>, value: A): SortedSet<A>\n} = Dual.dual<\n  <A>(value: A) => (self: SortedSet<A>) => SortedSet<A>,\n  <A>(self: SortedSet<A>, value: A) => SortedSet<A>\n>(2, (self, value) => fromTree(RBT.removeFirst(self.keyTree, value)))\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const size = <A>(self: SortedSet<A>): number => RBT.size(self.keyTree)\n\n/**\n * Check if a predicate holds true for some `SortedSet` element.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const some: {\n  <A>(predicate: Predicate<A>): (self: SortedSet<A>) => boolean\n  <A>(self: SortedSet<A>, predicate: Predicate<A>): boolean\n} = Dual.dual<\n  <A>(predicate: Predicate<A>) => (self: SortedSet<A>) => boolean,\n  <A>(self: SortedSet<A>, predicate: Predicate<A>) => boolean\n>(2, (self, predicate) => {\n  for (const value of self) {\n    if (predicate(value)) {\n      return true\n    }\n  }\n  return false\n})\n\n/**\n * @since 2.0.0\n * @category elements\n */\nexport const toggle: {\n  <A>(value: A): (self: SortedSet<A>) => SortedSet<A>\n  <A>(self: SortedSet<A>, value: A): SortedSet<A>\n} = Dual.dual<\n  <A>(value: A) => (self: SortedSet<A>) => SortedSet<A>,\n  <A>(self: SortedSet<A>, value: A) => SortedSet<A>\n>(2, (self, value) => has(self, value) ? remove(self, value) : add(self, value))\n\n/**\n * @since 2.0.0\n */\nexport const union: {\n  <A>(that: Iterable<A>): (self: SortedSet<A>) => SortedSet<A>\n  <A>(self: SortedSet<A>, that: Iterable<A>): SortedSet<A>\n} = Dual.dual<\n  <A>(that: Iterable<A>) => (self: SortedSet<A>) => SortedSet<A>,\n  <A>(self: SortedSet<A>, that: Iterable<A>) => SortedSet<A>\n>(2, <A>(self: SortedSet<A>, that: Iterable<A>) => {\n  const ord = RBT.getOrder(self.keyTree)\n  let out = empty<A>(ord)\n  for (const value of self) {\n    out = add(value)(out)\n  }\n  for (const value of that) {\n    out = add(value)(out)\n  }\n  return out\n})\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const values = <A>(self: SortedSet<A>): IterableIterator<A> => RBT.keys(self.keyTree)\n\n/**\n * @since 2.0.0\n * @category equivalence\n */\nexport const getEquivalence = <A>(): Equivalence.Equivalence<SortedSet<A>> => (a, b) => isSubset(a, b) && isSubset(b, a)\n"
  },
  {
    "path": "packages/effect/src/Stream.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Channel from \"./Channel.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Context from \"./Context.js\"\nimport type * as Deferred from \"./Deferred.js\"\nimport type * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Either from \"./Either.js\"\nimport type { ExecutionPlan } from \"./ExecutionPlan.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport type * as GroupBy from \"./GroupBy.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport * as groupBy_ from \"./internal/groupBy.js\"\nimport * as internal from \"./internal/stream.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Order from \"./Order.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Predicate, Refinement } from \"./Predicate.js\"\nimport type * as PubSub from \"./PubSub.js\"\nimport type * as Queue from \"./Queue.js\"\nimport type { Runtime } from \"./Runtime.js\"\nimport type * as Schedule from \"./Schedule.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as Sink from \"./Sink.js\"\nimport type * as Emit from \"./StreamEmit.js\"\nimport type * as HaltStrategy from \"./StreamHaltStrategy.js\"\nimport type * as Take from \"./Take.js\"\nimport type { TPubSub } from \"./TPubSub.js\"\nimport type { TDequeue } from \"./TQueue.js\"\nimport type * as Tracer from \"./Tracer.js\"\nimport type { Covariant, NoInfer, TupleOf } from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const StreamTypeId: unique symbol = internal.StreamTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type StreamTypeId = typeof StreamTypeId\n\n/**\n * A `Stream<A, E, R>` is a description of a program that, when evaluated, may\n * emit zero or more values of type `A`, may fail with errors of type `E`, and\n * uses an context of type `R`. One way to think of `Stream` is as a\n * `Effect` program that could emit multiple values.\n *\n * `Stream` is a purely functional *pull* based stream. Pull based streams offer\n * inherent laziness and backpressure, relieving users of the need to manage\n * buffers between operators. As an optimization, `Stream` does not emit\n * single values, but rather an array of values. This allows the cost of effect\n * evaluation to be amortized.\n *\n * `Stream` forms a monad on its `A` type parameter, and has error management\n * facilities for its `E` type parameter, modeled similarly to `Effect` (with\n * some adjustments for the multiple-valued nature of `Stream`). These aspects\n * allow for rich and expressive composition of streams.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Stream<out A, out E = never, out R = never> extends Stream.Variance<A, E, R>, Pipeable {\n  [Unify.typeSymbol]?: unknown\n  [Unify.unifySymbol]?: StreamUnify<this>\n  [Unify.ignoreSymbol]?: StreamUnifyIgnore\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface StreamUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> {\n  Stream?: () => A[Unify.typeSymbol] extends Stream<infer A0, infer E0, infer R0> | infer _ ? Stream<A0, E0, R0> : never\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface StreamUnifyIgnore extends Effect.EffectUnifyIgnore {\n  Effect?: true\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\ndeclare module \"./Effect.js\" {\n  interface Effect<A, E, R> extends Stream<A, E, R> {}\n}\n\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface StreamTypeLambda extends TypeLambda {\n  readonly type: Stream<this[\"Target\"], this[\"Out1\"], this[\"Out2\"]>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Stream {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out A, out E, out R> {\n    readonly [StreamTypeId]: VarianceStruct<A, E, R>\n  }\n\n  /**\n   * @since 3.4.0\n   * @category models\n   */\n  export interface VarianceStruct<out A, out E, out R> {\n    readonly _A: Covariant<A>\n    readonly _E: Covariant<E>\n    readonly _R: Covariant<R>\n  }\n\n  /**\n   * @since 3.4.0\n   * @category type-level\n   */\n  export type Success<T extends Stream<any, any, any>> = [T] extends [Stream<infer _A, infer _E, infer _R>] ? _A : never\n\n  /**\n   * @since 3.4.0\n   * @category type-level\n   */\n  export type Error<T extends Stream<any, any, any>> = [T] extends [Stream<infer _A, infer _E, infer _R>] ? _E : never\n\n  /**\n   * @since 3.4.0\n   * @category type-level\n   */\n  export type Context<T extends Stream<any, any, any>> = [T] extends [Stream<infer _A, infer _E, infer _R>] ? _R : never\n\n  /**\n   * @since 2.0.0\n   * @category models\n   * @deprecated use Types.TupleOf instead\n   */\n  export type DynamicTuple<T, N extends number> = N extends N ? number extends N ? Array<T> : DynamicTupleOf<T, N, []>\n    : never\n\n  /**\n   * @since 2.0.0\n   * @category models\n   * @deprecated use Types.TupleOf instead\n   */\n  export type DynamicTupleOf<T, N extends number, R extends Array<unknown>> = R[\"length\"] extends N ? R\n    : DynamicTupleOf<T, N, [T, ...R]>\n}\n\n/**\n * The default chunk size used by the various combinators and constructors of\n * `Stream`.\n *\n * @since 2.0.0\n * @category constants\n */\nexport const DefaultChunkSize: number = internal.DefaultChunkSize\n\n/**\n * Collects each underlying Chunk of the stream into a new chunk, and emits it\n * on each pull.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const accumulate: <A, E, R>(self: Stream<A, E, R>) => Stream<Chunk.Chunk<A>, E, R> = internal.accumulate\n\n/**\n * Re-chunks the elements of the stream by accumulating each underlying chunk.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const accumulateChunks: <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R> = internal.accumulateChunks\n\n/**\n * Creates a stream from a single value that will get cleaned up after the\n * stream is consumed.\n *\n * @example\n * ```ts\n * import { Console, Effect, Stream } from \"effect\"\n *\n * // Simulating File operations\n * const open = (filename: string) =>\n *   Effect.gen(function*() {\n *     yield* Console.log(`Opening ${filename}`)\n *     return {\n *       getLines: Effect.succeed([\"Line 1\", \"Line 2\", \"Line 3\"]),\n *       close: Console.log(`Closing ${filename}`)\n *     }\n *   })\n *\n * const stream = Stream.acquireRelease(\n *   open(\"file.txt\"),\n *   (file) => file.close\n * ).pipe(Stream.flatMap((file) => file.getLines))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // Opening file.txt\n * // Closing file.txt\n * // { _id: 'Chunk', values: [ [ 'Line 1', 'Line 2', 'Line 3' ] ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const acquireRelease: <A, E, R, R2, X>(\n  acquire: Effect.Effect<A, E, R>,\n  release: (resource: A, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<X, never, R2>\n) => Stream<A, E, R | R2> = internal.acquireRelease\n\n/**\n * Aggregates elements of this stream using the provided sink for as long as\n * the downstream operators on the stream are busy.\n *\n * This operator divides the stream into two asynchronous \"islands\". Operators\n * upstream of this operator run on one fiber, while downstream operators run\n * on another. Whenever the downstream fiber is busy processing elements, the\n * upstream fiber will feed elements into the sink until it signals\n * completion.\n *\n * Any sink can be used here, but see `Sink.foldWeightedEffect` and\n * `Sink.foldUntilEffect` for sinks that cover the common usecases.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const aggregate: {\n  <B, A, A2, E2, R2>(sink: Sink.Sink<B, A | A2, A2, E2, R2>): <E, R>(self: Stream<A, E, R>) => Stream<B, E2 | E, R2 | R>\n  <A, E, R, B, A2, E2, R2>(self: Stream<A, E, R>, sink: Sink.Sink<B, A | A2, A2, E2, R2>): Stream<B, E | E2, R | R2>\n} = internal.aggregate\n\n/**\n * Like {@link aggregateWithinEither}, but only returns the `Right` results.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const aggregateWithin: {\n  <B, A, A2, E2, R2, C, R3>(\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>,\n    schedule: Schedule.Schedule<C, Option.Option<B>, R3>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<B, E2 | E, R2 | R3 | R>\n  <A, E, R, B, A2, E2, R2, C, R3>(\n    self: Stream<A, E, R>,\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>,\n    schedule: Schedule.Schedule<C, Option.Option<B>, R3>\n  ): Stream<B, E | E2, R | R2 | R3>\n} = internal.aggregateWithin\n\n/**\n * Aggregates elements using the provided sink until it completes, or until\n * the delay signalled by the schedule has passed.\n *\n * This operator divides the stream into two asynchronous islands. Operators\n * upstream of this operator run on one fiber, while downstream operators run\n * on another. Elements will be aggregated by the sink until the downstream\n * fiber pulls the aggregated value, or until the schedule's delay has passed.\n *\n * Aggregated elements will be fed into the schedule to determine the delays\n * between pulls.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const aggregateWithinEither: {\n  <B, A, A2, E2, R2, C, R3>(\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>,\n    schedule: Schedule.Schedule<C, Option.Option<B>, R3>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<Either.Either<B, C>, E2 | E, R2 | R3 | R>\n  <A, E, R, B, A2, E2, R2, C, R3>(\n    self: Stream<A, E, R>,\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>,\n    schedule: Schedule.Schedule<C, Option.Option<B>, R3>\n  ): Stream<Either.Either<B, C>, E | E2, R | R2 | R3>\n} = internal.aggregateWithinEither\n\n/**\n * Maps the success values of this stream to the specified constant value.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(1, 5).pipe(Stream.as(null))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ null, null, null, null, null ] }\n * ```\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const as: {\n  <B>(value: B): <A, E, R>(self: Stream<A, E, R>) => Stream<B, E, R>\n  <A, E, R, B>(self: Stream<A, E, R>, value: B): Stream<B, E, R>\n} = internal.as\n\nconst _async: <A, E = never, R = never>(\n  register: (emit: Emit.Emit<R, E, A, void>) => Effect.Effect<void, never, R> | void,\n  bufferSize?: number | \"unbounded\" | {\n    readonly bufferSize?: number | undefined\n    readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n  } | undefined\n) => Stream<A, E, R> = internal._async\n\nexport {\n  /**\n   * Creates a stream from an asynchronous callback that can be called multiple\n   * times. The optionality of the error type `E` in `Emit` can be used to\n   * signal the end of the stream by setting it to `None`.\n   *\n   * The registration function can optionally return an `Effect`, which will be\n   * executed if the `Fiber` executing this Effect is interrupted.\n   *\n   * @example\n   * ```ts\n   * import type { StreamEmit } from \"effect\"\n   * import { Chunk, Effect, Option, Stream } from \"effect\"\n   *\n   * const events = [1, 2, 3, 4]\n   *\n   * const stream = Stream.async(\n   *   (emit: StreamEmit.Emit<never, never, number, void>) => {\n   *     events.forEach((n) => {\n   *       setTimeout(() => {\n   *         if (n === 3) {\n   *           emit(Effect.fail(Option.none())) // Terminate the stream\n   *         } else {\n   *           emit(Effect.succeed(Chunk.of(n))) // Add the current item to the stream\n   *         }\n   *       }, 100 * n)\n   *     })\n   *   }\n   * )\n   *\n   * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n   * // { _id: 'Chunk', values: [ 1, 2 ] }\n   *\n   * ```\n   * @since 2.0.0\n   * @category constructors\n   */\n  _async as async\n}\n\n/**\n * Creates a stream from an asynchronous callback that can be called multiple\n * times The registration of the callback itself returns an effect. The\n * optionality of the error type `E` can be used to signal the end of the\n * stream, by setting it to `None`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const asyncEffect: <A, E = never, R = never>(\n  register: (emit: Emit.Emit<R, E, A, void>) => Effect.Effect<unknown, E, R>,\n  bufferSize?: number | \"unbounded\" | {\n    readonly bufferSize?: number | undefined\n    readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n  } | undefined\n) => Stream<A, E, R> = internal.asyncEffect\n\n/**\n * Creates a stream from an external push-based resource.\n *\n * You can use the `emit` helper to emit values to the stream. The `emit` helper\n * returns a boolean indicating whether the value was emitted or not.\n *\n * You can also use the `emit` helper to signal the end of the stream by\n * using apis such as `emit.end` or `emit.fail`.\n *\n * By default it uses an \"unbounded\" buffer size.\n * You can customize the buffer size and strategy by passing an object as the\n * second argument with the `bufferSize` and `strategy` fields.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * Stream.asyncPush<string>((emit) =>\n *   Effect.acquireRelease(\n *     Effect.gen(function*() {\n *       yield* Effect.log(\"subscribing\")\n *       return setInterval(() => emit.single(\"tick\"), 1000)\n *     }),\n *     (handle) =>\n *       Effect.gen(function*() {\n *         yield* Effect.log(\"unsubscribing\")\n *         clearInterval(handle)\n *       })\n *   ), { bufferSize: 16, strategy: \"dropping\" })\n * ```\n *\n * @since 3.6.0\n * @category constructors\n */\nexport const asyncPush: <A, E = never, R = never>(\n  register: (emit: Emit.EmitOpsPush<E, A>) => Effect.Effect<unknown, E, R | Scope.Scope>,\n  options?: { readonly bufferSize: \"unbounded\" } | {\n    readonly bufferSize?: number | undefined\n    readonly strategy?: \"dropping\" | \"sliding\" | undefined\n  } | undefined\n) => Stream<A, E, Exclude<R, Scope.Scope>> = internal.asyncPush\n\n/**\n * Creates a stream from an asynchronous callback that can be called multiple\n * times. The registration of the callback itself returns an a scoped\n * resource. The optionality of the error type `E` can be used to signal the\n * end of the stream, by setting it to `None`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const asyncScoped: <A, E = never, R = never>(\n  register: (emit: Emit.Emit<R, E, A, void>) => Effect.Effect<unknown, E, R | Scope.Scope>,\n  bufferSize?: number | \"unbounded\" | {\n    readonly bufferSize?: number | undefined\n    readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n  } | undefined\n) => Stream<A, E, Exclude<R, Scope.Scope>> = internal.asyncScoped\n\n/**\n * Returns a `Stream` that first collects `n` elements from the input `Stream`,\n * and then creates a new `Stream` using the specified function, and sends all\n * the following elements through that.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const branchAfter: {\n  <A, A2, E2, R2>(\n    n: number,\n    f: (input: Chunk.Chunk<A>) => Stream<A2, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    n: number,\n    f: (input: Chunk.Chunk<A>) => Stream<A2, E2, R2>\n  ): Stream<A2, E | E2, R | R2>\n} = internal.branchAfter\n\n/**\n * Fan out the stream, producing a list of streams that have the same elements\n * as this stream. The driver stream will only ever advance the `maximumLag`\n * chunks before the slowest downstream stream.\n *\n * @example\n * ```ts\n * import { Console, Effect, Fiber, Schedule, Stream } from \"effect\"\n *\n * const numbers = Effect.scoped(\n *   Stream.range(1, 20).pipe(\n *     Stream.tap((n) => Console.log(`Emit ${n} element before broadcasting`)),\n *     Stream.broadcast(2, 5),\n *     Stream.flatMap(([first, second]) =>\n *       Effect.gen(function*() {\n *         const fiber1 = yield* Stream.runFold(first, 0, (acc, e) => Math.max(acc, e)).pipe(\n *           Effect.andThen((max) => Console.log(`Maximum: ${max}`)),\n *           Effect.fork\n *         )\n *         const fiber2 = yield* second.pipe(\n *           Stream.schedule(Schedule.spaced(\"1 second\")),\n *           Stream.runForEach((n) => Console.log(`Logging to the Console: ${n}`)),\n *           Effect.fork\n *         )\n *         yield* Fiber.join(fiber1).pipe(\n *           Effect.zip(Fiber.join(fiber2), { concurrent: true })\n *         )\n *       })\n *     ),\n *     Stream.runCollect\n *   )\n * )\n *\n * Effect.runPromise(numbers).then(console.log)\n * // Emit 1 element before broadcasting\n * // Emit 2 element before broadcasting\n * // Emit 3 element before broadcasting\n * // Emit 4 element before broadcasting\n * // Emit 5 element before broadcasting\n * // Emit 6 element before broadcasting\n * // Emit 7 element before broadcasting\n * // Emit 8 element before broadcasting\n * // Emit 9 element before broadcasting\n * // Emit 10 element before broadcasting\n * // Emit 11 element before broadcasting\n * // Logging to the Console: 1\n * // Logging to the Console: 2\n * // Logging to the Console: 3\n * // Logging to the Console: 4\n * // Logging to the Console: 5\n * // Emit 12 element before broadcasting\n * // Emit 13 element before broadcasting\n * // Emit 14 element before broadcasting\n * // Emit 15 element before broadcasting\n * // Emit 16 element before broadcasting\n * // Logging to the Console: 6\n * // Logging to the Console: 7\n * // Logging to the Console: 8\n * // Logging to the Console: 9\n * // Logging to the Console: 10\n * // Emit 17 element before broadcasting\n * // Emit 18 element before broadcasting\n * // Emit 19 element before broadcasting\n * // Emit 20 element before broadcasting\n * // Logging to the Console: 11\n * // Logging to the Console: 12\n * // Logging to the Console: 13\n * // Logging to the Console: 14\n * // Logging to the Console: 15\n * // Maximum: 20\n * // Logging to the Console: 16\n * // Logging to the Console: 17\n * // Logging to the Console: 18\n * // Logging to the Console: 19\n * // Logging to the Console: 20\n * // { _id: 'Chunk', values: [ undefined ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const broadcast: {\n  <N extends number>(\n    n: N,\n    maximumLag: number | { readonly capacity: \"unbounded\"; readonly replay?: number | undefined } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ): <A, E, R>(self: Stream<A, E, R>) => Effect.Effect<TupleOf<N, Stream<A, E>>, never, Scope.Scope | R>\n  <A, E, R, N extends number>(\n    self: Stream<A, E, R>,\n    n: N,\n    maximumLag: number | { readonly capacity: \"unbounded\"; readonly replay?: number | undefined } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ): Effect.Effect<TupleOf<N, Stream<A, E>>, never, Scope.Scope | R>\n} = internal.broadcast\n\n/**\n * Returns a new Stream that multicasts the original Stream, subscribing to it as soon as the first consumer subscribes.\n * As long as there is at least one consumer, the upstream will continue running and emitting data.\n * When all consumers have exited, the upstream will be finalized.\n *\n * @since 3.8.0\n * @category utils\n */\nexport const share: {\n  <A, E>(\n    config: {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n    }\n  ): <R>(self: Stream<A, E, R>) => Effect.Effect<Stream<A, E>, never, R | Scope.Scope>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    config: {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n    }\n  ): Effect.Effect<Stream<A, E>, never, R | Scope.Scope>\n} = internal.share\n\n/**\n * Fan out the stream, producing a dynamic number of streams that have the\n * same elements as this stream. The driver stream will only ever advance the\n * `maximumLag` chunks before the slowest downstream stream.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const broadcastDynamic: {\n  (\n    maximumLag: number | { readonly capacity: \"unbounded\"; readonly replay?: number | undefined } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ): <A, E, R>(self: Stream<A, E, R>) => Effect.Effect<Stream<A, E>, never, Scope.Scope | R>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    maximumLag: number | { readonly capacity: \"unbounded\"; readonly replay?: number | undefined } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ): Effect.Effect<Stream<A, E>, never, Scope.Scope | R>\n} = internal.broadcastDynamic\n\n/**\n * Converts the stream to a scoped list of queues. Every value will be\n * replicated to every queue with the slowest queue being allowed to buffer\n * `maximumLag` chunks before the driver is back pressured.\n *\n * Queues can unsubscribe from upstream by shutting down.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const broadcastedQueues: {\n  <N extends number>(\n    n: N,\n    maximumLag: number | { readonly capacity: \"unbounded\"; readonly replay?: number | undefined } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ): <A, E, R>(\n    self: Stream<A, E, R>\n  ) => Effect.Effect<TupleOf<N, Queue.Dequeue<Take.Take<A, E>>>, never, Scope.Scope | R>\n  <A, E, R, N extends number>(\n    self: Stream<A, E, R>,\n    n: N,\n    maximumLag: number | { readonly capacity: \"unbounded\"; readonly replay?: number | undefined } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ): Effect.Effect<TupleOf<N, Queue.Dequeue<Take.Take<A, E>>>, never, Scope.Scope | R>\n} = internal.broadcastedQueues\n\n/**\n * Converts the stream to a scoped dynamic amount of queues. Every chunk will\n * be replicated to every queue with the slowest queue being allowed to buffer\n * `maximumLag` chunks before the driver is back pressured.\n *\n * Queues can unsubscribe from upstream by shutting down.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const broadcastedQueuesDynamic: {\n  (\n    maximumLag: number | { readonly capacity: \"unbounded\"; readonly replay?: number | undefined } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ): <A, E, R>(\n    self: Stream<A, E, R>\n  ) => Effect.Effect<Effect.Effect<Queue.Dequeue<Take.Take<A, E>>, never, Scope.Scope>, never, Scope.Scope | R>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    maximumLag: number | { readonly capacity: \"unbounded\"; readonly replay?: number | undefined } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ): Effect.Effect<Effect.Effect<Queue.Dequeue<Take.Take<A, E>>, never, Scope.Scope>, never, Scope.Scope | R>\n} = internal.broadcastedQueuesDynamic\n\n/**\n * Allows a faster producer to progress independently of a slower consumer by\n * buffering up to `capacity` elements in a queue.\n *\n * Note: This combinator destroys the chunking structure. It's recommended to\n *       use rechunk afterwards. Additionally, prefer capacities that are powers\n *       of 2 for better performance.\n *\n * @example\n * ```ts\n * import { Console, Effect, Schedule, Stream } from \"effect\"\n *\n * const stream = Stream.range(1, 10).pipe(\n *   Stream.tap((n) => Console.log(`before buffering: ${n}`)),\n *   Stream.buffer({ capacity: 4 }),\n *   Stream.tap((n) => Console.log(`after buffering: ${n}`)),\n *   Stream.schedule(Schedule.spaced(\"5 seconds\"))\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // before buffering: 1\n * // before buffering: 2\n * // before buffering: 3\n * // before buffering: 4\n * // before buffering: 5\n * // before buffering: 6\n * // after buffering: 1\n * // after buffering: 2\n * // before buffering: 7\n * // after buffering: 3\n * // before buffering: 8\n * // after buffering: 4\n * // before buffering: 9\n * // after buffering: 5\n * // before buffering: 10\n * // ...\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const buffer: {\n  (\n    options: { readonly capacity: \"unbounded\" } | {\n      readonly capacity: number\n      readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n    }\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    options: { readonly capacity: \"unbounded\" } | {\n      readonly capacity: number\n      readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n    }\n  ): Stream<A, E, R>\n} = internal.buffer\n\n/**\n * Allows a faster producer to progress independently of a slower consumer by\n * buffering up to `capacity` chunks in a queue.\n *\n * @note Prefer capacities that are powers of 2 for better performance.\n * @since 2.0.0\n * @category utils\n */\nexport const bufferChunks: {\n  (\n    options: { readonly capacity: number; readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined }\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    options: { readonly capacity: number; readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined }\n  ): Stream<A, E, R>\n} = internal.bufferChunks\n\n/**\n * Switches over to the stream produced by the provided function in case this\n * one fails with a typed error.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchAll: {\n  <E, A2, E2, R2>(f: (error: E) => Stream<A2, E2, R2>): <A, R>(self: Stream<A, E, R>) => Stream<A2 | A, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, f: (error: E) => Stream<A2, E2, R2>): Stream<A | A2, E2, R | R2>\n} = internal.catchAll\n\n/**\n * Switches over to the stream produced by the provided function in case this\n * one fails. Allows recovery from all causes of failure, including\n * interruption if the stream is uninterruptible.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchAllCause: {\n  <E, A2, E2, R2>(\n    f: (cause: Cause.Cause<E>) => Stream<A2, E2, R2>\n  ): <A, R>(self: Stream<A, E, R>) => Stream<A2 | A, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (cause: Cause.Cause<E>) => Stream<A2, E2, R2>\n  ): Stream<A | A2, E2, R | R2>\n} = internal.catchAllCause\n\n/**\n * Switches over to the stream produced by the provided function in case this\n * one fails with some typed error.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchSome: {\n  <E, A2, E2, R2>(\n    pf: (error: E) => Option.Option<Stream<A2, E2, R2>>\n  ): <A, R>(self: Stream<A, E, R>) => Stream<A2 | A, E | E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    pf: (error: E) => Option.Option<Stream<A2, E2, R2>>\n  ): Stream<A | A2, E | E2, R | R2>\n} = internal.catchSome\n\n/**\n * Switches over to the stream produced by the provided function in case this\n * one fails with an error matching the given `_tag`.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchTag: {\n  <K extends E[\"_tag\"] & string, E extends { _tag: string }, A1, E1, R1>(\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Stream<A1, E1, R1>\n  ): <A, R>(self: Stream<A, E, R>) => Stream<A1 | A, E1 | Exclude<E, { _tag: K }>, R1 | R>\n  <A, E extends { _tag: string }, R, K extends E[\"_tag\"] & string, A1, E1, R1>(\n    self: Stream<A, E, R>,\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Stream<A1, E1, R1>\n  ): Stream<A | A1, E1 | Exclude<E, { _tag: K }>, R | R1>\n} = internal.catchTag\n\n/**\n * Switches over to the stream produced by one of the provided functions, in\n * case this one fails with an error matching one of the given `_tag`'s.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchTags: {\n  <\n    E extends { _tag: string },\n    Cases extends { [K in E[\"_tag\"]]+?: (error: Extract<E, { _tag: K }>) => Stream<any, any, any> }\n  >(\n    cases: Cases\n  ): <A, R>(\n    self: Stream<A, E, R>\n  ) => Stream<\n    | A\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Stream.Variance<infer A, infer _E, infer _R> ? A\n        : never\n    }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Stream.Variance<infer _A, infer E, infer _R> ? E\n        : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Stream.Variance<infer _A, infer _E, infer R> ? R\n        : never\n    }[keyof Cases]\n  >\n  <\n    A,\n    E extends { _tag: string },\n    R,\n    Cases extends { [K in E[\"_tag\"]]+?: (error: Extract<E, { _tag: K }>) => Stream<any, any, any> }\n  >(\n    self: Stream<A, E, R>,\n    cases: Cases\n  ): Stream<\n    | A\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Stream.Variance<infer _R, infer _E, infer A> ? A\n        : never\n    }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Stream.Variance<infer _R, infer E, infer _A> ? E\n        : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Stream.Variance<infer R, infer _E, infer _A> ? R\n        : never\n    }[keyof Cases]\n  >\n} = internal.catchTags\n\n/**\n * Switches over to the stream produced by the provided function in case this\n * one fails with some errors. Allows recovery from all causes of failure,\n * including interruption if the stream is uninterruptible.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const catchSomeCause: {\n  <E, A2, E2, R2>(\n    pf: (cause: Cause.Cause<E>) => Option.Option<Stream<A2, E2, R2>>\n  ): <A, R>(self: Stream<A, E, R>) => Stream<A2 | A, E | E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    pf: (cause: Cause.Cause<E>) => Option.Option<Stream<A2, E2, R2>>\n  ): Stream<A | A2, E | E2, R | R2>\n} = internal.catchSomeCause\n\n/**\n * Returns a new stream that only emits elements that are not equal to the\n * previous element emitted, using natural equality to determine whether two\n * elements are equal.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 1, 1, 2, 2, 3, 4).pipe(Stream.changes)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2, 3, 4 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const changes: <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R> = internal.changes\n\n/**\n * Returns a new stream that only emits elements that are not equal to the\n * previous element emitted, using the specified function to determine whether\n * two elements are equal.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const changesWith: {\n  <A>(f: (x: A, y: A) => boolean): <E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, f: (x: A, y: A) => boolean): Stream<A, E, R>\n} = internal.changesWith\n\n/**\n * Returns a new stream that only emits elements that are not equal to the\n * previous element emitted, using the specified effectual function to\n * determine whether two elements are equal.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const changesWithEffect: {\n  <A, E2, R2>(\n    f: (x: A, y: A) => Effect.Effect<boolean, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(self: Stream<A, E, R>, f: (x: A, y: A) => Effect.Effect<boolean, E2, R2>): Stream<A, E | E2, R | R2>\n} = internal.changesWithEffect\n\n/**\n * Exposes the underlying chunks of the stream as a stream of chunks of\n * elements.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const chunks: <A, E, R>(self: Stream<A, E, R>) => Stream<Chunk.Chunk<A>, E, R> = internal.chunks\n\n/**\n * Performs the specified stream transformation with the chunk structure of\n * the stream exposed.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const chunksWith: {\n  <A, E, R, A2, E2, R2>(\n    f: (stream: Stream<Chunk.Chunk<A>, E, R>) => Stream<Chunk.Chunk<A2>, E2, R2>\n  ): (self: Stream<A, E, R>) => Stream<A2, E | E2, R | R2>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (stream: Stream<Chunk.Chunk<A>, E, R>) => Stream<Chunk.Chunk<A2>, E2, R2>\n  ): Stream<A2, E | E2, R | R2>\n} = internal.chunksWith\n\n/**\n * Combines the elements from this stream and the specified stream by\n * repeatedly applying the function `f` to extract an element using both sides\n * and conceptually \"offer\" it to the destination stream. `f` can maintain\n * some internal state to control the combining process, with the initial\n * state being specified by `s`.\n *\n * Where possible, prefer `Stream.combineChunks` for a more efficient\n * implementation.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const combine: {\n  <A2, E2, R2, S, R3, E, A, R4, R5, A3>(\n    that: Stream<A2, E2, R2>,\n    s: S,\n    f: (\n      s: S,\n      pullLeft: Effect.Effect<A, Option.Option<E>, R3>,\n      pullRight: Effect.Effect<A2, Option.Option<E2>, R4>\n    ) => Effect.Effect<Exit.Exit<readonly [A3, S], Option.Option<E2 | E>>, never, R5>\n  ): <R>(self: Stream<A, E, R>) => Stream<A3, E2 | E, R2 | R3 | R4 | R5 | R>\n  <R, A2, E2, R2, S, R3, E, A, R4, R5, A3>(\n    self: Stream<A, E, R>,\n    that: Stream<A2, E2, R2>,\n    s: S,\n    f: (\n      s: S,\n      pullLeft: Effect.Effect<A, Option.Option<E>, R3>,\n      pullRight: Effect.Effect<A2, Option.Option<E2>, R4>\n    ) => Effect.Effect<Exit.Exit<readonly [A3, S], Option.Option<E2 | E>>, never, R5>\n  ): Stream<A3, E2 | E, R | R2 | R3 | R4 | R5>\n} = internal.combine\n\n/**\n * Combines the chunks from this stream and the specified stream by repeatedly\n * applying the function `f` to extract a chunk using both sides and\n * conceptually \"offer\" it to the destination stream. `f` can maintain some\n * internal state to control the combining process, with the initial state\n * being specified by `s`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const combineChunks: {\n  <A2, E2, R2, S, R3, E, A, R4, R5, A3>(\n    that: Stream<A2, E2, R2>,\n    s: S,\n    f: (\n      s: S,\n      pullLeft: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R3>,\n      pullRight: Effect.Effect<Chunk.Chunk<A2>, Option.Option<E2>, R4>\n    ) => Effect.Effect<Exit.Exit<readonly [Chunk.Chunk<A3>, S], Option.Option<E2 | E>>, never, R5>\n  ): <R>(self: Stream<A, E, R>) => Stream<A3, E2 | E, R2 | R3 | R4 | R5 | R>\n  <R, A2, E2, R2, S, R3, E, A, R4, R5, A3>(\n    self: Stream<A, E, R>,\n    that: Stream<A2, E2, R2>,\n    s: S,\n    f: (\n      s: S,\n      pullLeft: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R3>,\n      pullRight: Effect.Effect<Chunk.Chunk<A2>, Option.Option<E2>, R4>\n    ) => Effect.Effect<Exit.Exit<readonly [Chunk.Chunk<A3>, S], Option.Option<E2 | E>>, never, R5>\n  ): Stream<A3, E2 | E, R | R2 | R3 | R4 | R5>\n} = internal.combineChunks\n\n/**\n * Concatenates the specified stream with this stream, resulting in a stream\n * that emits the elements from this stream and then the elements from the\n * specified stream.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const s1 = Stream.make(1, 2, 3)\n * const s2 = Stream.make(4, 5)\n *\n * const stream = Stream.concat(s1, s2)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const concat: {\n  <A2, E2, R2>(that: Stream<A2, E2, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, that: Stream<A2, E2, R2>): Stream<A | A2, E | E2, R | R2>\n} = internal.concat\n\n/**\n * Concatenates all of the streams in the chunk to one stream.\n *\n * @example\n * ```ts\n * import { Chunk, Effect, Stream } from \"effect\"\n *\n * const s1 = Stream.make(1, 2, 3)\n * const s2 = Stream.make(4, 5)\n * const s3 = Stream.make(6, 7, 8)\n *\n * const stream = Stream.concatAll(Chunk.make(s1, s2, s3))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // {\n * //   _id: 'Chunk',\n * //   values: [\n * //     1, 2, 3, 4,\n * //     5, 6, 7, 8\n * //   ]\n * // }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const concatAll: <A, E, R>(streams: Chunk.Chunk<Stream<A, E, R>>) => Stream<A, E, R> = internal.concatAll\n\n/**\n * Composes this stream with the specified stream to create a cartesian\n * product of elements. The `right` stream would be run multiple times, for\n * every element in the `left` stream.\n *\n * See also `Stream.zip` for the more common point-wise variant.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const s1 = Stream.make(1, 2, 3)\n * const s2 = Stream.make(\"a\", \"b\")\n *\n * const product = Stream.cross(s1, s2)\n *\n * Effect.runPromise(Stream.runCollect(product)).then(console.log)\n * // {\n * //   _id: \"Chunk\",\n * //   values: [\n * //     [ 1, \"a\" ], [ 1, \"b\" ], [ 2, \"a\" ], [ 2, \"b\" ], [ 3, \"a\" ], [ 3, \"b\" ]\n * //   ]\n * // }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const cross: {\n  <AR, ER, RR>(right: Stream<AR, ER, RR>): <AL, EL, RL>(left: Stream<AL, EL, RL>) => Stream<[AL, AR], EL | ER, RL | RR>\n  <AL, ER, RR, AR, EL, RL>(left: Stream<AL, ER, RR>, right: Stream<AR, EL, RL>): Stream<[AL, AR], EL | ER, RL | RR>\n} = internal.cross\n\n/**\n * Composes this stream with the specified stream to create a cartesian\n * product of elements, but keeps only elements from `left` stream. The `right`\n * stream would be run multiple times, for every element in the `left` stream.\n *\n * See also `Stream.zipLeft` for the more common point-wise variant.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const crossLeft: {\n  <AR, ER, RR>(right: Stream<AR, ER, RR>): <AL, EL, RL>(left: Stream<AL, EL, RL>) => Stream<AL, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR>(left: Stream<AL, EL, RL>, right: Stream<AR, ER, RR>): Stream<AL, EL | ER, RL | RR>\n} = internal.crossLeft\n\n/**\n * Composes this stream with the specified stream to create a cartesian\n * product of elements, but keeps only elements from the `right` stream. The\n * `left` stream would be run multiple times, for every element in the `right`\n * stream.\n *\n * See also `Stream.zipRight` for the more common point-wise variant.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const crossRight: {\n  <AR, ER, RR>(right: Stream<AR, ER, RR>): <AL, EL, RL>(left: Stream<AL, EL, RL>) => Stream<AR, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR>(left: Stream<AL, EL, RL>, right: Stream<AR, ER, RR>): Stream<AR, EL | ER, RL | RR>\n} = internal.crossRight\n\n/**\n * Composes this stream with the specified stream to create a cartesian\n * product of elements with a specified function. The `right` stream would be\n * run multiple times, for every element in the `left` stream.\n *\n * See also `Stream.zipWith` for the more common point-wise variant.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const crossWith: {\n  <AR, ER, RR, AL, A>(\n    right: Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): <EL, RL>(left: Stream<AL, EL, RL>) => Stream<A, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR, A>(\n    left: Stream<AL, EL, RL>,\n    right: Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): Stream<A, EL | ER, RL | RR>\n} = internal.crossWith\n\n/**\n * Delays the emission of values by holding new values for a set duration. If\n * no new values arrive during that time the value is emitted, however if a\n * new value is received during the holding period the previous value is\n * discarded and the process is repeated with the new value.\n *\n * This operator is useful if you have a stream of \"bursty\" events which\n * eventually settle down and you only need the final event of the burst. For\n * example, a search engine may only want to initiate a search after a user\n * has paused typing so as to not prematurely recommend results.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * let last = Date.now()\n * const log = (message: string) =>\n *   Effect.sync(() => {\n *     const end = Date.now()\n *     console.log(`${message} after ${end - last}ms`)\n *     last = end\n *   })\n *\n * const stream = Stream.make(1, 2, 3).pipe(\n *   Stream.concat(\n *     Stream.fromEffect(Effect.sleep(\"200 millis\").pipe(Effect.as(4))) // Emit 4 after 200 ms\n *   ),\n *   Stream.concat(Stream.make(5, 6)), // Continue with more rapid values\n *   Stream.concat(\n *     Stream.fromEffect(Effect.sleep(\"150 millis\").pipe(Effect.as(7))) // Emit 7 after 150 ms\n *   ),\n *   Stream.concat(Stream.make(8)),\n *   Stream.tap((n) => log(`Received ${n}`)),\n *   Stream.debounce(\"100 millis\"), // Only emit values after a pause of at least 100 milliseconds,\n *   Stream.tap((n) => log(`> Emitted ${n}`))\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // Received 1 after 5ms\n * // Received 2 after 2ms\n * // Received 3 after 0ms\n * // > Emitted 3 after 104ms\n * // Received 4 after 99ms\n * // Received 5 after 1ms\n * // Received 6 after 0ms\n * // > Emitted 6 after 101ms\n * // Received 7 after 50ms\n * // Received 8 after 1ms\n * // > Emitted 8 after 101ms\n * // { _id: 'Chunk', values: [ 3, 6, 8 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const debounce: {\n  (duration: Duration.DurationInput): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, duration: Duration.DurationInput): Stream<A, E, R>\n} = internal.debounce\n\n/**\n * The stream that dies with the specified defect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const die: (defect: unknown) => Stream<never> = internal.die\n\n/**\n * The stream that dies with the specified lazily evaluated defect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dieSync: (evaluate: LazyArg<unknown>) => Stream<never> = internal.dieSync\n\n/**\n * The stream that dies with an exception described by `message`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dieMessage: (message: string) => Stream<never> = internal.dieMessage\n\n/**\n * More powerful version of `Stream.broadcast`. Allows to provide a function\n * that determines what queues should receive which elements. The decide\n * function will receive the indices of the queues in the resulting list.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const distributedWith: {\n  <N extends number, A>(\n    options: {\n      readonly size: N\n      readonly maximumLag: number\n      readonly decide: (a: A) => Effect.Effect<Predicate<number>>\n    }\n  ): <E, R>(\n    self: Stream<A, E, R>\n  ) => Effect.Effect<TupleOf<N, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>>, never, Scope.Scope | R>\n  <A, E, R, N extends number>(\n    self: Stream<A, E, R>,\n    options: {\n      readonly size: N\n      readonly maximumLag: number\n      readonly decide: (a: A) => Effect.Effect<Predicate<number>>\n    }\n  ): Effect.Effect<TupleOf<N, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>>, never, Scope.Scope | R>\n} = internal.distributedWith\n\n/**\n * More powerful version of `Stream.distributedWith`. This returns a function\n * that will produce new queues and corresponding indices. You can also\n * provide a function that will be executed after the final events are\n * enqueued in all queues. Shutdown of the queues is handled by the driver.\n * Downstream users can also shutdown queues manually. In this case the driver\n * will continue but no longer backpressure on them.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const distributedWithDynamic: {\n  <A>(\n    options: { readonly maximumLag: number; readonly decide: (a: A) => Effect.Effect<Predicate<number>, never, never> }\n  ): <E, R>(\n    self: Stream<A, E, R>\n  ) => Effect.Effect<\n    Effect.Effect<[number, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>], never, never>,\n    never,\n    Scope.Scope | R\n  >\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    options: { readonly maximumLag: number; readonly decide: (a: A) => Effect.Effect<Predicate<number>, never, never> }\n  ): Effect.Effect<\n    Effect.Effect<[number, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>], never, never>,\n    never,\n    Scope.Scope | R\n  >\n} = internal.distributedWithDynamic\n\n/**\n * Converts this stream to a stream that executes its effects but emits no\n * elements. Useful for sequencing effects using streams:\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * // We create a stream and immediately drain it.\n * const stream = Stream.range(1, 6).pipe(Stream.drain)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const drain: <A, E, R>(self: Stream<A, E, R>) => Stream<never, E, R> = internal.drain\n\n/**\n * Drains the provided stream in the background for as long as this stream is\n * running. If this stream ends before `other`, `other` will be interrupted.\n * If `other` fails, this stream will fail with that error.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const drainFork: {\n  <A2, E2, R2>(that: Stream<A2, E2, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, that: Stream<A2, E2, R2>): Stream<A, E | E2, R | R2>\n} = internal.drainFork\n\n/**\n * Drops the specified number of elements from this stream.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const drop: {\n  (n: number): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, n: number): Stream<A, E, R>\n} = internal.drop\n\n/**\n * Drops the last specified number of elements from this stream.\n *\n * @note This combinator keeps `n` elements in memory. Be careful with big\n *       numbers.\n * @since 2.0.0\n * @category utils\n */\nexport const dropRight: {\n  (n: number): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, n: number): Stream<A, E, R>\n} = internal.dropRight\n\n/**\n * Drops all elements of the stream until the specified predicate evaluates to\n * `true`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const dropUntil: {\n  <A>(predicate: Predicate<NoInfer<A>>): <E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, predicate: Predicate<A>): Stream<A, E, R>\n} = internal.dropUntil\n\n/**\n * Drops all elements of the stream until the specified effectful predicate\n * evaluates to `true`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const dropUntilEffect: {\n  <A, E2, R2>(\n    predicate: (a: NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(\n    self: Stream<A, E, R>,\n    predicate: (a: NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): Stream<A, E | E2, R | R2>\n} = internal.dropUntilEffect\n\n/**\n * Drops all elements of the stream for as long as the specified predicate\n * evaluates to `true`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const dropWhile: {\n  <A>(predicate: Predicate<NoInfer<A>>): <E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, predicate: Predicate<A>): Stream<A, E, R>\n} = internal.dropWhile\n\n/**\n * Drops all elements of the stream for as long as the specified predicate\n * produces an effect that evalutates to `true`\n *\n * @since 2.0.0\n * @category utils\n */\nexport const dropWhileEffect: {\n  <A, E2, R2>(\n    predicate: (a: NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(\n    self: Stream<A, E, R>,\n    predicate: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): Stream<A, E | E2, R | R2>\n} = internal.dropWhileEffect\n\n/**\n * Returns a stream whose failures and successes have been lifted into an\n * `Either`. The resulting stream cannot fail, because the failures have been\n * exposed as part of the `Either` success case.\n *\n * @note The stream will end as soon as the first error occurs.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const either: <A, E, R>(self: Stream<A, E, R>) => Stream<Either.Either<A, E>, never, R> = internal.either\n\n/**\n * The empty stream.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.empty\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: Stream<never> = internal.empty\n\n/**\n * Executes the provided finalizer after this stream's finalizers run.\n *\n * @example\n * ```ts\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const program = Stream.fromEffect(Console.log(\"Application Logic.\")).pipe(\n *   Stream.concat(Stream.finalizer(Console.log(\"Finalizing the stream\"))),\n *   Stream.ensuring(\n *     Console.log(\"Doing some other works after stream's finalization\")\n *   )\n * )\n *\n * Effect.runPromise(Stream.runCollect(program)).then(console.log)\n * // Application Logic.\n * // Finalizing the stream\n * // Doing some other works after stream's finalization\n * // { _id: 'Chunk', values: [ undefined, undefined ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const ensuring: {\n  <X, R2>(finalizer: Effect.Effect<X, never, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R2 | R>\n  <A, E, R, X, R2>(self: Stream<A, E, R>, finalizer: Effect.Effect<X, never, R2>): Stream<A, E, R | R2>\n} = internal.ensuring\n\n/**\n * Executes the provided finalizer after this stream's finalizers run.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const ensuringWith: {\n  <E, R2>(\n    finalizer: (exit: Exit.Exit<unknown, E>) => Effect.Effect<unknown, never, R2>\n  ): <A, R>(self: Stream<A, E, R>) => Stream<A, E, R2 | R>\n  <A, E, R, R2>(\n    self: Stream<A, E, R>,\n    finalizer: (exit: Exit.Exit<unknown, E>) => Effect.Effect<unknown, never, R2>\n  ): Stream<A, E, R | R2>\n} = internal.ensuringWith\n\n/**\n * Accesses the whole context of the stream.\n *\n * @since 2.0.0\n * @category context\n */\nexport const context: <R>() => Stream<Context.Context<R>, never, R> = internal.context\n\n/**\n * Accesses the context of the stream.\n *\n * @since 2.0.0\n * @category context\n */\nexport const contextWith: <R, A>(f: (env: Context.Context<R>) => A) => Stream<A, never, R> = internal.contextWith\n\n/**\n * Accesses the context of the stream in the context of an effect.\n *\n * @since 2.0.0\n * @category context\n */\nexport const contextWithEffect: <R0, A, E, R>(\n  f: (env: Context.Context<R0>) => Effect.Effect<A, E, R>\n) => Stream<A, E, R0 | R> = internal.contextWithEffect\n\n/**\n * Accesses the context of the stream in the context of a stream.\n *\n * @since 2.0.0\n * @category context\n */\nexport const contextWithStream: <R0, A, E, R>(\n  f: (env: Context.Context<R0>) => Stream<A, E, R>\n) => Stream<A, E, R0 | R> = internal.contextWithStream\n\n/**\n * Creates a stream that executes the specified effect but emits no elements.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const execute: <X, E, R>(effect: Effect.Effect<X, E, R>) => Stream<never, E, R> = internal.execute\n\n/**\n * Terminates with the specified error.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.fail(\"Uh oh!\")\n *\n * Effect.runPromiseExit(Stream.runCollect(stream)).then(console.log)\n * // {\n * //   _id: 'Exit',\n * //   _tag: 'Failure',\n * //   cause: { _id: 'Cause', _tag: 'Fail', failure: 'Uh oh!' }\n * // }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fail: <E>(error: E) => Stream<never, E> = internal.fail\n\n/**\n * Terminates with the specified lazily evaluated error.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failSync: <E>(evaluate: LazyArg<E>) => Stream<never, E> = internal.failSync\n\n/**\n * The stream that always fails with the specified `Cause`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCause: <E>(cause: Cause.Cause<E>) => Stream<never, E> = internal.failCause\n\n/**\n * The stream that always fails with the specified lazily evaluated `Cause`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCauseSync: <E>(evaluate: LazyArg<Cause.Cause<E>>) => Stream<never, E> = internal.failCauseSync\n\n/**\n * Filters the elements emitted by this stream using the provided function.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(1, 11).pipe(Stream.filter((n) => n % 2 === 0))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 2, 4, 6, 8, 10 ] }\n * ```\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filter: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): <E, R>(self: Stream<A, E, R>) => Stream<B, E, R>\n  <A, B extends A>(predicate: Predicate<B>): <E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R, B extends A>(self: Stream<A, E, R>, refinement: Refinement<A, B>): Stream<B, E, R>\n  <A, E, R>(self: Stream<A, E, R>, predicate: Predicate<A>): Stream<A, E, R>\n} = internal.filter\n\n/**\n * Effectfully filters the elements emitted by this stream.\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterEffect: {\n  <A, E2, R2>(\n    f: (a: NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(self: Stream<A, E, R>, f: (a: A) => Effect.Effect<boolean, E2, R2>): Stream<A, E | E2, R | R2>\n} = internal.filterEffect\n\n/**\n * Performs a filter and map in a single step.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const filterMap: {\n  <A, B>(pf: (a: A) => Option.Option<B>): <E, R>(self: Stream<A, E, R>) => Stream<B, E, R>\n  <A, E, R, B>(self: Stream<A, E, R>, pf: (a: A) => Option.Option<B>): Stream<B, E, R>\n} = internal.filterMap\n\n/**\n * Performs an effectful filter and map in a single step.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const filterMapEffect: {\n  <A, A2, E2, R2>(\n    pf: (a: A) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    pf: (a: A) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ): Stream<A2, E | E2, R | R2>\n} = internal.filterMapEffect\n\n/**\n * Transforms all elements of the stream for as long as the specified partial\n * function is defined.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const filterMapWhile: {\n  <A, A2>(pf: (a: A) => Option.Option<A2>): <E, R>(self: Stream<A, E, R>) => Stream<A2, E, R>\n  <A, E, R, A2>(self: Stream<A, E, R>, pf: (a: A) => Option.Option<A2>): Stream<A2, E, R>\n} = internal.filterMapWhile\n\n/**\n * Effectfully transforms all elements of the stream for as long as the\n * specified partial function is defined.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const filterMapWhileEffect: {\n  <A, A2, E2, R2>(\n    pf: (a: A) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    pf: (a: A) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ): Stream<A2, E | E2, R | R2>\n} = internal.filterMapWhileEffect\n\n/**\n * Creates a one-element stream that never fails and executes the finalizer\n * when it ends.\n *\n * @example\n * ```ts\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const application = Stream.fromEffect(Console.log(\"Application Logic.\"))\n *\n * const deleteDir = (dir: string) => Console.log(`Deleting dir: ${dir}`)\n *\n * const program = application.pipe(\n *   Stream.concat(\n *     Stream.finalizer(\n *       deleteDir(\"tmp\").pipe(\n *         Effect.andThen(Console.log(\"Temporary directory was deleted.\"))\n *       )\n *     )\n *   )\n * )\n *\n * Effect.runPromise(Stream.runCollect(program)).then(console.log)\n * // Application Logic.\n * // Deleting dir: tmp\n * // Temporary directory was deleted.\n * // { _id: 'Chunk', values: [ undefined, undefined ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const finalizer: <R, X>(finalizer: Effect.Effect<X, never, R>) => Stream<void, never, R> = internal.finalizer\n\n/**\n * Finds the first element emitted by this stream that satisfies the provided\n * predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const find: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): <E, R>(self: Stream<A, E, R>) => Stream<B, E, R>\n  <A>(predicate: Predicate<NoInfer<A>>): <E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R, B extends A>(self: Stream<A, E, R>, refinement: Refinement<A, B>): Stream<B, E, R>\n  <A, E, R>(self: Stream<A, E, R>, predicate: Predicate<A>): Stream<A, E, R>\n} = internal.find\n\n/**\n * Finds the first element emitted by this stream that satisfies the provided\n * effectful predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findEffect: {\n  <A, E2, R2>(\n    predicate: (a: NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(\n    self: Stream<A, E, R>,\n    predicate: (a: NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): Stream<A, E | E2, R | R2>\n} = internal.findEffect\n\n/**\n * Returns a stream made of the concatenation in strict order of all the\n * streams produced by passing each element of this stream to `f0`\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatMap: {\n  <A, A2, E2, R2>(\n    f: (a: A) => Stream<A2, E2, R2>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly bufferSize?: number | undefined\n      readonly switch?: boolean | undefined\n    } | undefined\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: A) => Stream<A2, E2, R2>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly bufferSize?: number | undefined\n      readonly switch?: boolean | undefined\n    } | undefined\n  ): Stream<A2, E | E2, R | R2>\n} = internal.flatMap\n\n/**\n * Flattens this stream-of-streams into a stream made of the concatenation in\n * strict order of all the streams.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flatten: {\n  (\n    options?:\n      | { readonly concurrency?: number | \"unbounded\" | undefined; readonly bufferSize?: number | undefined }\n      | undefined\n  ): <A, E2, R2, E, R>(self: Stream<Stream<A, E2, R2>, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E2, R2, E, R>(\n    self: Stream<Stream<A, E2, R2>, E, R>,\n    options?:\n      | { readonly concurrency?: number | \"unbounded\" | undefined; readonly bufferSize?: number | undefined }\n      | undefined\n  ): Stream<A, E2 | E, R2 | R>\n} = internal.flatten\n\n/**\n * Submerges the chunks carried by this stream into the stream's structure,\n * while still preserving them.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flattenChunks: <A, E, R>(self: Stream<Chunk.Chunk<A>, E, R>) => Stream<A, E, R> = internal.flattenChunks\n\n/**\n * Flattens `Effect` values into the stream's structure, preserving all\n * information about the effect.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flattenEffect: {\n  (\n    options?:\n      | { readonly concurrency?: number | \"unbounded\" | undefined; readonly unordered?: boolean | undefined }\n      | undefined\n  ): <A, E2, R2, E, R>(self: Stream<Effect.Effect<A, E2, R2>, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E2, R2, E, R>(\n    self: Stream<Effect.Effect<A, E2, R2>, E, R>,\n    options?:\n      | { readonly concurrency?: number | \"unbounded\" | undefined; readonly unordered?: boolean | undefined }\n      | undefined\n  ): Stream<A, E2 | E, R2 | R>\n} = internal.flattenEffect\n\n/**\n * Unwraps `Exit` values that also signify end-of-stream by failing with `None`.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flattenExitOption: <A, E2, E, R>(\n  self: Stream<Exit.Exit<A, Option.Option<E2>>, E, R>\n) => Stream<A, E | E2, R> = internal.flattenExitOption\n\n/**\n * Submerges the iterables carried by this stream into the stream's structure,\n * while still preserving them.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flattenIterables: <A, E, R>(self: Stream<Iterable<A>, E, R>) => Stream<A, E, R> = internal.flattenIterables\n\n/**\n * Unwraps `Exit` values and flatten chunks that also signify end-of-stream\n * by failing with `None`.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const flattenTake: <A, E2, E, R>(self: Stream<Take.Take<A, E2>, E, R>) => Stream<A, E | E2, R> =\n  internal.flattenTake\n\n/**\n * Repeats this stream forever.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const forever: <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R> = internal.forever\n\n/**\n * Creates a stream from an `AsyncIterable`.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const myAsyncIterable = async function*() {\n *   yield 1\n *   yield 2\n * }\n *\n * const stream = Stream.fromAsyncIterable(\n *   myAsyncIterable(),\n *   (e) => new Error(String(e)) // Error Handling\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromAsyncIterable: <A, E>(iterable: AsyncIterable<A>, onError: (e: unknown) => E) => Stream<A, E> =\n  internal.fromAsyncIterable\n\n/**\n * Creates a stream from a `Channel`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromChannel: <A, E, R>(\n  channel: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, unknown, unknown, R>\n) => Stream<A, E, R> = internal.fromChannel\n\n/**\n * Creates a channel from a `Stream`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const toChannel: <A, E, R>(\n  stream: Stream<A, E, R>\n) => Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, unknown, unknown, R> = internal.toChannel\n\n/**\n * Creates a stream from a `Chunk` of values.\n *\n * @example\n * ```ts\n * import { Chunk, Effect, Stream } from \"effect\"\n *\n * // Creating a stream with values from a single Chunk\n * const stream = Stream.fromChunk(Chunk.make(1, 2, 3))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2, 3 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromChunk: <A>(chunk: Chunk.Chunk<A>) => Stream<A> = internal.fromChunk\n\n/**\n * Creates a stream from a subscription to a `PubSub`.\n *\n * **Options**\n *\n * - `shutdown`: If `true`, the `PubSub` will be shutdown after the stream is evaluated (defaults to `false`)\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromChunkPubSub: {\n  <A>(\n    pubsub: PubSub.PubSub<Chunk.Chunk<A>>,\n    options: { readonly scoped: true; readonly shutdown?: boolean | undefined }\n  ): Effect.Effect<Stream<A>, never, Scope.Scope>\n  <A>(\n    pubsub: PubSub.PubSub<Chunk.Chunk<A>>,\n    options?: { readonly scoped?: false | undefined; readonly shutdown?: boolean | undefined } | undefined\n  ): Stream<A>\n} = internal.fromChunkPubSub\n\n/**\n * Creates a stream from a `Queue` of values.\n *\n * **Options**\n *\n * - `shutdown`: If `true`, the queue will be shutdown after the stream is evaluated (defaults to `false`)\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromChunkQueue: <A>(\n  queue: Queue.Dequeue<Chunk.Chunk<A>>,\n  options?: {\n    readonly shutdown?: boolean | undefined\n  }\n) => Stream<A> = internal.fromChunkQueue\n\n/**\n * Creates a stream from an arbitrary number of chunks.\n *\n * @example\n * ```ts\n * import { Chunk, Effect, Stream } from \"effect\"\n *\n * // Creating a stream with values from multiple Chunks\n * const stream = Stream.fromChunks(Chunk.make(1, 2, 3), Chunk.make(4, 5, 6))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromChunks: <A>(...chunks: Array<Chunk.Chunk<A>>) => Stream<A> = internal.fromChunks\n\n/**\n * Either emits the success value of this effect or terminates the stream\n * with the failure value of this effect.\n *\n * @example\n * ```ts\n * import { Effect, Random, Stream } from \"effect\"\n *\n * const stream = Stream.fromEffect(Random.nextInt)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // Example Output: { _id: 'Chunk', values: [ 922694024 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEffect: <A, E, R>(effect: Effect.Effect<A, E, R>) => Stream<A, E, R> = internal.fromEffect\n\n/**\n * Creates a stream from an effect producing a value of type `A` or an empty\n * `Stream`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEffectOption: <A, E, R>(effect: Effect.Effect<A, Option.Option<E>, R>) => Stream<A, E, R> =\n  internal.fromEffectOption\n\n/**\n * Creates a stream from a subscription to a `PubSub`.\n *\n * **Options**\n *\n * - `shutdown`: If `true`, the `PubSub` will be shutdown after the stream is evaluated (defaults to `false`)\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromPubSub: {\n  <A>(\n    pubsub: PubSub.PubSub<A>,\n    options: {\n      readonly scoped: true\n      readonly maxChunkSize?: number | undefined\n      readonly shutdown?: boolean | undefined\n    }\n  ): Effect.Effect<Stream<A>, never, Scope.Scope>\n  <A>(\n    pubsub: PubSub.PubSub<A>,\n    options?: {\n      readonly scoped?: false | undefined\n      readonly maxChunkSize?: number | undefined\n      readonly shutdown?: boolean | undefined\n    } | undefined\n  ): Stream<A>\n} = internal.fromPubSub\n\n/**\n * Creates a stream from a subscription to a `TPubSub`.\n *\n * @since 3.10.0\n * @category constructors\n */\nexport const fromTPubSub: <A>(pubsub: TPubSub<A>) => Stream<A> = internal.fromTPubSub\n\n/**\n * Creates a new `Stream` from an iterable collection of values.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n *\n * const stream = Stream.fromIterable(numbers)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2, 3 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: <A>(iterable: Iterable<A>) => Stream<A> = internal.fromIterable\n\n/**\n * Creates a stream from an effect producing a value of type `Iterable<A>`.\n *\n * @example\n * ```ts\n * import { Context, Effect, Stream } from \"effect\"\n *\n * class Database extends Context.Tag(\"Database\")<\n *   Database,\n *   { readonly getUsers: Effect.Effect<Array<string>> }\n * >() {}\n *\n * const getUsers = Database.pipe(Effect.andThen((_) => _.getUsers))\n *\n * const stream = Stream.fromIterableEffect(getUsers)\n *\n * Effect.runPromise(\n *   Stream.runCollect(stream.pipe(Stream.provideService(Database, { getUsers: Effect.succeed([\"user1\", \"user2\"]) })))\n * ).then(console.log)\n * // { _id: 'Chunk', values: [ 'user1', 'user2' ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterableEffect: <A, E, R>(effect: Effect.Effect<Iterable<A>, E, R>) => Stream<A, E, R> =\n  internal.fromIterableEffect\n\n/**\n * Creates a stream from an iterator\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIteratorSucceed: <A>(iterator: IterableIterator<A>, maxChunkSize?: number) => Stream<A> =\n  internal.fromIteratorSucceed\n\n/**\n * Creates a stream from an effect that pulls elements from another stream.\n *\n * See `Stream.toPull` for reference.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromPull: <R, R2, E, A>(\n  effect: Effect.Effect<Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R2>, never, Scope.Scope | R>\n) => Stream<A, E, R2 | Exclude<R, Scope.Scope>> = internal.fromPull\n\n/**\n * Creates a stream from a queue of values\n *\n * **Options**\n *\n * - `maxChunkSize`: The maximum number of queued elements to put in one chunk in the stream\n * - `shutdown`: If `true`, the queue will be shutdown after the stream is evaluated (defaults to `false`)\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromQueue: <A>(\n  queue: Queue.Dequeue<A>,\n  options?: {\n    readonly maxChunkSize?: number | undefined\n    readonly shutdown?: boolean | undefined\n  }\n) => Stream<A> = internal.fromQueue\n\n/**\n * Creates a stream from a TQueue of values\n *\n * @since 3.10.0\n * @category constructors\n */\nexport const fromTQueue: <A>(queue: TDequeue<A>) => Stream<A> = internal.fromTQueue\n\n/**\n * Creates a stream from a `ReadableStream`.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromReadableStream: {\n  <A, E>(\n    options: {\n      readonly evaluate: LazyArg<ReadableStream<A>>\n      readonly onError: (error: unknown) => E\n      readonly releaseLockOnEnd?: boolean | undefined\n    }\n  ): Stream<A, E>\n  <A, E>(evaluate: LazyArg<ReadableStream<A>>, onError: (error: unknown) => E): Stream<A, E>\n} = internal.fromReadableStream\n\n/**\n * Creates a stream from a `ReadableStreamBYOBReader`.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromReadableStreamByob: {\n  <E>(\n    options: {\n      readonly evaluate: LazyArg<ReadableStream<Uint8Array>>\n      readonly onError: (error: unknown) => E\n      readonly bufferSize?: number | undefined\n      readonly releaseLockOnEnd?: boolean | undefined\n    }\n  ): Stream<Uint8Array, E>\n  <E>(\n    evaluate: LazyArg<ReadableStream<Uint8Array>>,\n    onError: (error: unknown) => E,\n    /** Controls the size of the underlying `ArrayBuffer` (defaults to `4096`) */\n    allocSize?: number\n  ): Stream<Uint8Array, E>\n} = internal.fromReadableStreamByob\n\n/**\n * Creates a stream from a `Schedule` that does not require any further\n * input. The stream will emit an element for each value output from the\n * schedule, continuing for as long as the schedule continues.\n *\n * @example\n * ```ts\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * // Emits values every 1 second for a total of 5 emissions\n * const schedule = Schedule.spaced(\"1 second\").pipe(\n *   Schedule.compose(Schedule.recurs(5))\n * )\n *\n * const stream = Stream.fromSchedule(schedule)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromSchedule: <A, R>(schedule: Schedule.Schedule<A, unknown, R>) => Stream<A, never, R> =\n  internal.fromSchedule\n\n/**\n * Creates a pipeline that groups on adjacent keys, calculated by the\n * specified function.\n *\n * @since 2.0.0\n * @category grouping\n */\nexport const groupAdjacentBy: {\n  <A, K>(f: (a: A) => K): <E, R>(self: Stream<A, E, R>) => Stream<[K, Chunk.NonEmptyChunk<A>], E, R>\n  <A, E, R, K>(self: Stream<A, E, R>, f: (a: A) => K): Stream<[K, Chunk.NonEmptyChunk<A>], E, R>\n} = internal.groupAdjacentBy\n\n/**\n * More powerful version of `Stream.groupByKey`.\n *\n * @example\n * ```ts\n * import { Chunk, Effect, GroupBy, Stream } from \"effect\"\n *\n * const groupByKeyResult = Stream.fromIterable([\n *   \"Mary\",\n *   \"James\",\n *   \"Robert\",\n *   \"Patricia\",\n *   \"John\",\n *   \"Jennifer\",\n *   \"Rebecca\",\n *   \"Peter\"\n * ]).pipe(\n *   Stream.groupBy((name) => Effect.succeed([name.substring(0, 1), name]))\n * )\n *\n * const stream = GroupBy.evaluate(groupByKeyResult, (key, stream) =>\n *   Stream.fromEffect(\n *     Stream.runCollect(stream).pipe(\n *       Effect.andThen((chunk) => [key, Chunk.size(chunk)] as const)\n *     )\n *   ))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // {\n * //   _id: 'Chunk',\n * //   values: [ [ 'M', 1 ], [ 'J', 3 ], [ 'R', 2 ], [ 'P', 2 ] ]\n * // }\n * ```\n *\n * @since 2.0.0\n * @category grouping\n */\nexport const groupBy: {\n  <A, K, V, E2, R2>(\n    f: (a: A) => Effect.Effect<readonly [K, V], E2, R2>,\n    options?: { readonly bufferSize?: number | undefined } | undefined\n  ): <E, R>(self: Stream<A, E, R>) => GroupBy.GroupBy<K, V, E2 | E, R2 | R>\n  <A, E, R, K, V, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<readonly [K, V], E2, R2>,\n    options?: { readonly bufferSize?: number | undefined } | undefined\n  ): GroupBy.GroupBy<K, V, E | E2, R | R2>\n} = groupBy_.groupBy\n\n/**\n * Partition a stream using a function and process each stream individually.\n * This returns a data structure that can be used to further filter down which\n * groups shall be processed.\n *\n * After calling apply on the GroupBy object, the remaining groups will be\n * processed in parallel and the resulting streams merged in a\n * nondeterministic fashion.\n *\n * Up to `buffer` elements may be buffered in any group stream before the\n * producer is backpressured. Take care to consume from all streams in order\n * to prevent deadlocks.\n *\n * For example, to collect the first 2 words for every starting letter from a\n * stream of words:\n *\n * ```ts\n * import { pipe, GroupBy, Stream } from \"effect\"\n *\n * pipe(\n *   Stream.fromIterable([\"hello\", \"world\", \"hi\", \"holla\"]),\n *   Stream.groupByKey((word) => word[0]),\n *   GroupBy.evaluate((key, stream) =>\n *     pipe(\n *       stream,\n *       Stream.take(2),\n *       Stream.map((words) => [key, words] as const)\n *     )\n *   )\n * )\n * ```\n *\n * @since 2.0.0\n * @category grouping\n */\nexport const groupByKey: {\n  <A, K>(\n    f: (a: A) => K,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ): <E, R>(self: Stream<A, E, R>) => GroupBy.GroupBy<K, A, E, R>\n  <A, E, R, K>(\n    self: Stream<A, E, R>,\n    f: (a: A) => K,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ): GroupBy.GroupBy<K, A, E, R>\n} = groupBy_.groupByKey\n\n/**\n * Partitions the stream with specified `chunkSize`.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(0, 8).pipe(Stream.grouped(3))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then((chunks) => console.log(\"%o\", chunks))\n * // {\n * //   _id: 'Chunk',\n * //   values: [\n * //     { _id: 'Chunk', values: [ 0, 1, 2, [length]: 3 ] },\n * //     { _id: 'Chunk', values: [ 3, 4, 5, [length]: 3 ] },\n * //     { _id: 'Chunk', values: [ 6, 7, 8, [length]: 3 ] },\n * //     [length]: 3\n * //   ]\n * // }\n * ```\n *\n * @since 2.0.0\n * @category grouping\n */\nexport const grouped: {\n  (chunkSize: number): <A, E, R>(self: Stream<A, E, R>) => Stream<Chunk.Chunk<A>, E, R>\n  <A, E, R>(self: Stream<A, E, R>, chunkSize: number): Stream<Chunk.Chunk<A>, E, R>\n} = internal.grouped\n\n/**\n * Partitions the stream with the specified `chunkSize` or until the specified\n * `duration` has passed, whichever is satisfied first.\n *\n * @example\n * ```ts\n * import { Chunk, Effect, Schedule, Stream } from \"effect\"\n *\n * const stream = Stream.range(0, 9).pipe(\n *   Stream.repeat(Schedule.spaced(\"1 second\")),\n *   Stream.groupedWithin(18, \"1.5 seconds\"),\n *   Stream.take(3)\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then((chunks) => console.log(Chunk.toArray(chunks)))\n * // [\n * //   {\n * //     _id: 'Chunk',\n * //     values: [\n * //       0, 1, 2, 3, 4, 5, 6,\n * //       7, 8, 9, 0, 1, 2, 3,\n * //       4, 5, 6, 7\n * //     ]\n * //   },\n * //   {\n * //     _id: 'Chunk',\n * //     values: [\n * //       8, 9, 0, 1, 2,\n * //       3, 4, 5, 6, 7,\n * //       8, 9\n * //     ]\n * //   },\n * //   {\n * //     _id: 'Chunk',\n * //     values: [\n * //       0, 1, 2, 3, 4, 5, 6,\n * //       7, 8, 9, 0, 1, 2, 3,\n * //       4, 5, 6, 7\n * //     ]\n * //   }\n * // ]\n * ```\n *\n * @since 2.0.0\n * @category grouping\n */\nexport const groupedWithin: {\n  (\n    chunkSize: number,\n    duration: Duration.DurationInput\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<Chunk.Chunk<A>, E, R>\n  <A, E, R>(self: Stream<A, E, R>, chunkSize: number, duration: Duration.DurationInput): Stream<Chunk.Chunk<A>, E, R>\n} = internal.groupedWithin\n\n/**\n * Specialized version of haltWhen which halts the evaluation of this stream\n * after the given duration.\n *\n * An element in the process of being pulled will not be interrupted when the\n * given duration completes. See `interruptAfter` for this behavior.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const haltAfter: {\n  (duration: Duration.DurationInput): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, duration: Duration.DurationInput): Stream<A, E, R>\n} = internal.haltAfter\n\n/**\n * Halts the evaluation of this stream when the provided effect completes. The\n * given effect will be forked as part of the returned stream, and its success\n * will be discarded.\n *\n * An element in the process of being pulled will not be interrupted when the\n * effect completes. See `interruptWhen` for this behavior.\n *\n * If the effect completes with a failure, the stream will emit that failure.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const haltWhen: {\n  <X, E2, R2>(effect: Effect.Effect<X, E2, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, X, E2, R2>(self: Stream<A, E, R>, effect: Effect.Effect<X, E2, R2>): Stream<A, E | E2, R | R2>\n} = internal.haltWhen\n\n/**\n * Halts the evaluation of this stream when the provided promise resolves.\n *\n * If the promise completes with a failure, the stream will emit that failure.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const haltWhenDeferred: {\n  <X, E2>(deferred: Deferred.Deferred<X, E2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R>\n  <A, E, R, X, E2>(self: Stream<A, E, R>, deferred: Deferred.Deferred<X, E2>): Stream<A, E | E2, R>\n} = internal.haltWhenDeferred\n\n/**\n * The identity pipeline, which does not modify streams in any way.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const identity: <A, E = never, R = never>() => Stream<A, E, R> = internal.identityStream\n\n/**\n * Interleaves this stream and the specified stream deterministically by\n * alternating pulling values from this stream and the specified stream. When\n * one stream is exhausted all remaining values in the other stream will be\n * pulled.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const s1 = Stream.make(1, 2, 3)\n * const s2 = Stream.make(4, 5, 6)\n *\n * const stream = Stream.interleave(s1, s2)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 4, 2, 5, 3, 6 ] }\n * ```\n * @since 2.0.0\n * @category utils\n */\nexport const interleave: {\n  <A2, E2, R2>(that: Stream<A2, E2, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, that: Stream<A2, E2, R2>): Stream<A | A2, E | E2, R | R2>\n} = internal.interleave\n\n/**\n * Combines this stream and the specified stream deterministically using the\n * stream of boolean values `pull` to control which stream to pull from next.\n * A value of `true` indicates to pull from this stream and a value of `false`\n * indicates to pull from the specified stream. Only consumes as many elements\n * as requested by the `pull` stream. If either this stream or the specified\n * stream are exhausted further requests for values from that stream will be\n * ignored.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const s1 = Stream.make(1, 3, 5, 7, 9)\n * const s2 = Stream.make(2, 4, 6, 8, 10)\n *\n * const booleanStream = Stream.make(true, false, false).pipe(Stream.forever)\n *\n * const stream = Stream.interleaveWith(s1, s2, booleanStream)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // {\n * //   _id: 'Chunk',\n * //   values: [\n * //     1, 2,  4, 3, 6,\n * //     8, 5, 10, 7, 9\n * //   ]\n * // }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const interleaveWith: {\n  <A2, E2, R2, E3, R3>(\n    that: Stream<A2, E2, R2>,\n    decider: Stream<boolean, E3, R3>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E2 | E3 | E, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, E3, R3>(\n    self: Stream<A, E, R>,\n    that: Stream<A2, E2, R2>,\n    decider: Stream<boolean, E3, R3>\n  ): Stream<A | A2, E | E2 | E3, R | R2 | R3>\n} = internal.interleaveWith\n\n/**\n * Intersperse stream with provided `element`.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5).pipe(Stream.intersperse(0))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // {\n * //   _id: 'Chunk',\n * //   values: [\n * //     1, 0, 2, 0, 3,\n * //     0, 4, 0, 5\n * //   ]\n * // }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const intersperse: {\n  <A2>(element: A2): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E, R>\n  <A, E, R, A2>(self: Stream<A, E, R>, element: A2): Stream<A | A2, E, R>\n} = internal.intersperse\n\n/**\n * Intersperse the specified element, also adding a prefix and a suffix.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3, 4, 5).pipe(\n *   Stream.intersperseAffixes({\n *     start: \"[\",\n *     middle: \"-\",\n *     end: \"]\"\n *   })\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // {\n * //   _id: 'Chunk',\n * //   values: [\n * //     '[', 1,   '-', 2,   '-',\n * //     3,   '-', 4,   '-', 5,\n * //     ']'\n * //   ]\n * // }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const intersperseAffixes: {\n  <A2, A3, A4>(\n    options: { readonly start: A2; readonly middle: A3; readonly end: A4 }\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A3 | A4 | A, E, R>\n  <A, E, R, A2, A3, A4>(\n    self: Stream<A, E, R>,\n    options: { readonly start: A2; readonly middle: A3; readonly end: A4 }\n  ): Stream<A | A2 | A3 | A4, E, R>\n} = internal.intersperseAffixes\n\n/**\n * Specialized version of `Stream.interruptWhen` which interrupts the\n * evaluation of this stream after the given `Duration`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const interruptAfter: {\n  (duration: Duration.DurationInput): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, duration: Duration.DurationInput): Stream<A, E, R>\n} = internal.interruptAfter\n\n/**\n * Interrupts the evaluation of this stream when the provided effect\n * completes. The given effect will be forked as part of this stream, and its\n * success will be discarded. This combinator will also interrupt any\n * in-progress element being pulled from upstream.\n *\n * If the effect completes with a failure before the stream completes, the\n * returned stream will emit that failure.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const interruptWhen: {\n  <X, E2, R2>(effect: Effect.Effect<X, E2, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, X, E2, R2>(self: Stream<A, E, R>, effect: Effect.Effect<X, E2, R2>): Stream<A, E | E2, R | R2>\n} = internal.interruptWhen\n\n/**\n * Interrupts the evaluation of this stream when the provided promise\n * resolves. This combinator will also interrupt any in-progress element being\n * pulled from upstream.\n *\n * If the promise completes with a failure, the stream will emit that failure.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const interruptWhenDeferred: {\n  <X, E2>(deferred: Deferred.Deferred<X, E2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R>\n  <A, E, R, X, E2>(self: Stream<A, E, R>, deferred: Deferred.Deferred<X, E2>): Stream<A, E | E2, R>\n} = internal.interruptWhenDeferred\n\n/**\n * The infinite stream of iterative function application: a, f(a), f(f(a)),\n * f(f(f(a))), ...\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * // An infinite Stream of numbers starting from 1 and incrementing\n * const stream = Stream.iterate(1, (n) => n + 1)\n *\n * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(10)))).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const iterate: <A>(value: A, next: (value: A) => A) => Stream<A> = internal.iterate\n\n/**\n * Creates a stream from an sequence of values.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2, 3 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <As extends Array<any>>(...as: As) => Stream<As[number]> = internal.make\n\n/**\n * Transforms the elements of this stream using the supplied function.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3).pipe(Stream.map((n) => n + 1))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 2, 3, 4 ] }\n * ```\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): <E, R>(self: Stream<A, E, R>) => Stream<B, E, R>\n  <A, E, R, B>(self: Stream<A, E, R>, f: (a: A) => B): Stream<B, E, R>\n} = internal.map\n\n/**\n * Statefully maps over the elements of this stream to produce new elements.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const runningTotal = (stream: Stream.Stream<number>): Stream.Stream<number> =>\n *   stream.pipe(Stream.mapAccum(0, (s, a) => [s + a, s + a]))\n *\n * // input:  0, 1, 2, 3, 4, 5, 6\n * Effect.runPromise(Stream.runCollect(runningTotal(Stream.range(0, 6)))).then(\n *   console.log\n * )\n * // { _id: \"Chunk\", values: [ 0, 1, 3, 6, 10, 15, 21 ] }\n * ```\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapAccum: {\n  <S, A, A2>(s: S, f: (s: S, a: A) => readonly [S, A2]): <E, R>(self: Stream<A, E, R>) => Stream<A2, E, R>\n  <A, E, R, S, A2>(self: Stream<A, E, R>, s: S, f: (s: S, a: A) => readonly [S, A2]): Stream<A2, E, R>\n} = internal.mapAccum\n\n/**\n * Statefully and effectfully maps over the elements of this stream to produce\n * new elements.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapAccumEffect: {\n  <S, A, A2, E2, R2>(\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<readonly [S, A2], E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, S, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<readonly [S, A2], E2, R2>\n  ): Stream<A2, E | E2, R | R2>\n} = internal.mapAccumEffect\n\n/**\n * Returns a stream whose failure and success channels have been mapped by the\n * specified `onFailure` and `onSuccess` functions.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mapBoth: {\n  <E, E2, A, A2>(\n    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n  ): <R>(self: Stream<A, E, R>) => Stream<A2, E2, R>\n  <A, E, R, E2, A2>(\n    self: Stream<A, E, R>,\n    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n  ): Stream<A2, E2, R>\n} = internal.mapBoth\n\n/**\n * Transforms the chunks emitted by this stream.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapChunks: {\n  <A, B>(f: (chunk: Chunk.Chunk<A>) => Chunk.Chunk<B>): <E, R>(self: Stream<A, E, R>) => Stream<B, E, R>\n  <A, E, R, B>(self: Stream<A, E, R>, f: (chunk: Chunk.Chunk<A>) => Chunk.Chunk<B>): Stream<B, E, R>\n} = internal.mapChunks\n\n/**\n * Effectfully transforms the chunks emitted by this stream.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapChunksEffect: {\n  <A, B, E2, R2>(\n    f: (chunk: Chunk.Chunk<A>) => Effect.Effect<Chunk.Chunk<B>, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<B, E2 | E, R2 | R>\n  <A, E, R, B, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (chunk: Chunk.Chunk<A>) => Effect.Effect<Chunk.Chunk<B>, E2, R2>\n  ): Stream<B, E | E2, R | R2>\n} = internal.mapChunksEffect\n\n/**\n * Maps each element to an iterable, and flattens the iterables into the\n * output of this stream.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const numbers = Stream.make(\"1-2-3\", \"4-5\", \"6\").pipe(\n *   Stream.mapConcat((s) => s.split(\"-\")),\n *   Stream.map((s) => parseInt(s))\n * )\n *\n * Effect.runPromise(Stream.runCollect(numbers)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5, 6 ] }\n * ```\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapConcat: {\n  <A, A2>(f: (a: A) => Iterable<A2>): <E, R>(self: Stream<A, E, R>) => Stream<A2, E, R>\n  <A, E, R, A2>(self: Stream<A, E, R>, f: (a: A) => Iterable<A2>): Stream<A2, E, R>\n} = internal.mapConcat\n\n/**\n * Maps each element to a chunk, and flattens the chunks into the output of\n * this stream.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapConcatChunk: {\n  <A, A2>(f: (a: A) => Chunk.Chunk<A2>): <E, R>(self: Stream<A, E, R>) => Stream<A2, E, R>\n  <A, E, R, A2>(self: Stream<A, E, R>, f: (a: A) => Chunk.Chunk<A2>): Stream<A2, E, R>\n} = internal.mapConcatChunk\n\n/**\n * Effectfully maps each element to a chunk, and flattens the chunks into the\n * output of this stream.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapConcatChunkEffect: {\n  <A, A2, E2, R2>(\n    f: (a: A) => Effect.Effect<Chunk.Chunk<A2>, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<Chunk.Chunk<A2>, E2, R2>\n  ): Stream<A2, E | E2, R | R2>\n} = internal.mapConcatChunkEffect\n\n/**\n * Effectfully maps each element to an iterable, and flattens the iterables\n * into the output of this stream.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapConcatEffect: {\n  <A, A2, E2, R2>(\n    f: (a: A) => Effect.Effect<Iterable<A2>, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<Iterable<A2>, E2, R2>\n  ): Stream<A2, E | E2, R | R2>\n} = internal.mapConcatEffect\n\n/**\n * Maps over elements of the stream with the specified effectful function.\n *\n * @example\n * ```ts\n * import { Effect, Random, Stream } from \"effect\"\n *\n * const stream = Stream.make(10, 20, 30).pipe(\n *   Stream.mapEffect((n) => Random.nextIntBetween(0, n))\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // Example Output: { _id: 'Chunk', values: [ 7, 19, 8 ] }\n * ```\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapEffect: {\n  <A, A2, E2, R2>(\n    f: (a: A) => Effect.Effect<A2, E2, R2>,\n    options?:\n      | { readonly concurrency?: number | \"unbounded\" | undefined; readonly unordered?: boolean | undefined }\n      | undefined\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, A2, E2, R2, K>(\n    f: (a: A) => Effect.Effect<A2, E2, R2>,\n    options: { readonly key: (a: A) => K; readonly bufferSize?: number | undefined }\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<A2, E2, R2>,\n    options?:\n      | { readonly concurrency?: number | \"unbounded\" | undefined; readonly unordered?: boolean | undefined }\n      | undefined\n  ): Stream<A2, E | E2, R | R2>\n  <A, E, R, A2, E2, R2, K>(\n    self: Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<A2, E2, R2>,\n    options: { readonly key: (a: A) => K; readonly bufferSize?: number | undefined }\n  ): Stream<A2, E | E2, R | R2>\n} = groupBy_.mapEffectOptions\n\n/**\n * Transforms the errors emitted by this stream using `f`.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapError: {\n  <E, E2>(f: (error: E) => E2): <A, R>(self: Stream<A, E, R>) => Stream<A, E2, R>\n  <A, E, R, E2>(self: Stream<A, E, R>, f: (error: E) => E2): Stream<A, E2, R>\n} = internal.mapError\n\n/**\n * Transforms the full causes of failures emitted by this stream.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const mapErrorCause: {\n  <E, E2>(f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): <A, R>(self: Stream<A, E, R>) => Stream<A, E2, R>\n  <A, E, R, E2>(self: Stream<A, E, R>, f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): Stream<A, E2, R>\n} = internal.mapErrorCause\n\n/**\n * Merges this stream and the specified stream together.\n *\n * New produced stream will terminate when both specified stream terminate if\n * no termination strategy is specified.\n *\n * @example\n * ```ts\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const s1 = Stream.make(1, 2, 3).pipe(\n *   Stream.schedule(Schedule.spaced(\"100 millis\"))\n * )\n * const s2 = Stream.make(4, 5, 6).pipe(\n *   Stream.schedule(Schedule.spaced(\"200 millis\"))\n * )\n *\n * const stream = Stream.merge(s1, s2)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 4, 2, 3, 5, 6 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const merge: {\n  <A2, E2, R2>(\n    that: Stream<A2, E2, R2>,\n    options?: { readonly haltStrategy?: HaltStrategy.HaltStrategyInput | undefined } | undefined\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    that: Stream<A2, E2, R2>,\n    options?: { readonly haltStrategy?: HaltStrategy.HaltStrategyInput | undefined } | undefined\n  ): Stream<A | A2, E | E2, R | R2>\n} = internal.merge\n\n/**\n * Merges a variable list of streams in a non-deterministic fashion. Up to `n`\n * streams may be consumed in parallel and up to `outputBuffer` chunks may be\n * buffered by this operator.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mergeAll: {\n  (\n    options: {\n      readonly concurrency: number | \"unbounded\"\n      readonly bufferSize?: number | undefined\n    }\n  ): <A, E, R>(streams: Iterable<Stream<A, E, R>>) => Stream<A, E, R>\n  <A, E, R>(\n    streams: Iterable<Stream<A, E, R>>,\n    options: {\n      readonly concurrency: number | \"unbounded\"\n      readonly bufferSize?: number | undefined\n    }\n  ): Stream<A, E, R>\n} = internal.mergeAll\n\n/**\n * Merges a struct of streams into a single stream of tagged values.\n * @category combinators\n * @since 3.8.5\n *\n * @example\n * ```ts\n * import { Stream } from \"effect\"\n * // Stream.Stream<{ _tag: \"a\"; value: number; } | { _tag: \"b\"; value: string; }>\n * const res = Stream.mergeWithTag({\n *    a: Stream.make(0),\n *    b: Stream.make(\"\")\n * }, { concurrency: \"unbounded\" })\n * ```\n */\nexport const mergeWithTag: {\n  <S extends { [k in string]: Stream<any, any, any> }>(\n    streams: S,\n    options: {\n      readonly concurrency: number | \"unbounded\"\n      readonly bufferSize?: number | undefined\n    }\n  ): Stream<\n    { [K in keyof S]: { _tag: K; value: Stream.Success<S[K]> } }[keyof S],\n    Stream.Error<S[keyof S]>,\n    Stream.Context<S[keyof S]>\n  >\n  (options: {\n    readonly concurrency: number | \"unbounded\"\n    readonly bufferSize?: number | undefined\n  }): <S extends { [k in string]: Stream<any, any, any> }>(streams: S) => Stream<\n    { [K in keyof S]: { _tag: K; value: Stream.Success<S[K]> } }[keyof S],\n    Stream.Error<S[keyof S]>,\n    Stream.Context<S[keyof S]>\n  >\n} = internal.mergeWithTag\n\n/**\n * Merges this stream and the specified stream together to a common element\n * type with the specified mapping functions.\n *\n * New produced stream will terminate when both specified stream terminate if\n * no termination strategy is specified.\n *\n * @example\n * ```ts\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const s1 = Stream.make(\"1\", \"2\", \"3\").pipe(\n *   Stream.schedule(Schedule.spaced(\"100 millis\"))\n * )\n * const s2 = Stream.make(4.1, 5.3, 6.2).pipe(\n *   Stream.schedule(Schedule.spaced(\"200 millis\"))\n * )\n *\n * const stream = Stream.mergeWith(s1, s2, {\n *   onSelf: (s) => parseInt(s),\n *   onOther: (n) => Math.floor(n)\n * })\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 4, 2, 3, 5, 6 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mergeWith: {\n  <A2, E2, R2, A, A3, A4>(\n    other: Stream<A2, E2, R2>,\n    options: {\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A4\n      readonly haltStrategy?: HaltStrategy.HaltStrategyInput | undefined\n    }\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A3 | A4, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2, A3, A4>(\n    self: Stream<A, E, R>,\n    other: Stream<A2, E2, R2>,\n    options: {\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A4\n      readonly haltStrategy?: HaltStrategy.HaltStrategyInput | undefined\n    }\n  ): Stream<A3 | A4, E | E2, R | R2>\n} = internal.mergeWith\n\n/**\n * Merges this stream and the specified stream together to produce a stream of\n * eithers.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mergeEither: {\n  <A2, E2, R2>(\n    that: Stream<A2, E2, R2>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<Either.Either<A2, A>, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, that: Stream<A2, E2, R2>): Stream<Either.Either<A2, A>, E | E2, R | R2>\n} = internal.mergeEither\n\n/**\n * Merges this stream and the specified stream together, discarding the values\n * from the right stream.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mergeLeft: {\n  <AR, ER, RR>(right: Stream<AR, ER, RR>): <AL, EL, RL>(left: Stream<AL, EL, RL>) => Stream<AL, ER | EL, RR | RL>\n  <AL, EL, RL, AR, ER, RR>(left: Stream<AL, EL, RL>, right: Stream<AR, ER, RR>): Stream<AL, EL | ER, RL | RR>\n} = internal.mergeLeft\n\n/**\n * Merges this stream and the specified stream together, discarding the values\n * from the left stream.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mergeRight: {\n  <AR, ER, RR>(right: Stream<AR, ER, RR>): <AL, EL, RL>(left: Stream<AL, EL, RL>) => Stream<AR, ER | EL, RR | RL>\n  <AL, EL, RL, AR, ER, RR>(left: Stream<AL, EL, RL>, right: Stream<AR, ER, RR>): Stream<AR, EL | ER, RL | RR>\n} = internal.mergeRight\n\n/**\n * Returns a combined string resulting from concatenating each of the values\n * from the stream.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const mkString: <E, R>(self: Stream<string, E, R>) => Effect.Effect<string, E, R> = internal.mkString\n\n/**\n * The stream that never produces any value or fails with any error.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const never: Stream<never> = internal.never\n\n/**\n * Adds an effect to be executed at the end of the stream.\n *\n * @example\n * ```ts\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3).pipe(\n *   Stream.map((n) => n * 2),\n *   Stream.tap((n) => Console.log(`after mapping: ${n}`)),\n *   Stream.onEnd(Console.log(\"Stream ended\"))\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // after mapping: 2\n * // after mapping: 4\n * // after mapping: 6\n * // Stream ended\n * // { _id: 'Chunk', values: [ 2, 4, 6 ] }\n * ```\n *\n * @since 3.6.0\n * @category sequencing\n */\nexport const onEnd: {\n  <_, E2, R2>(\n    effect: Effect.Effect<_, E2, R2>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, _, E2, R2>(\n    self: Stream<A, E, R>,\n    effect: Effect.Effect<_, E2, R2>\n  ): Stream<A, E | E2, R | R2>\n} = internal.onEnd\n\n/**\n * Runs the specified effect if this stream fails, providing the error to the\n * effect if it exists.\n *\n * Note: Unlike `Effect.onError` there is no guarantee that the provided\n * effect will not be interrupted.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const onError: {\n  <E, X, R2>(\n    cleanup: (cause: Cause.Cause<E>) => Effect.Effect<X, never, R2>\n  ): <A, R>(self: Stream<A, E, R>) => Stream<A, E, R2 | R>\n  <A, E, R, X, R2>(\n    self: Stream<A, E, R>,\n    cleanup: (cause: Cause.Cause<E>) => Effect.Effect<X, never, R2>\n  ): Stream<A, E, R | R2>\n} = internal.onError\n\n/**\n * Runs the specified effect if this stream ends.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const onDone: {\n  <X, R2>(cleanup: () => Effect.Effect<X, never, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R2 | R>\n  <A, E, R, X, R2>(self: Stream<A, E, R>, cleanup: () => Effect.Effect<X, never, R2>): Stream<A, E, R | R2>\n} = internal.onDone\n\n/**\n * Adds an effect to be executed at the start of the stream.\n *\n * @example\n * ```ts\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3).pipe(\n *   Stream.onStart(Console.log(\"Stream started\")),\n *   Stream.map((n) => n * 2),\n *   Stream.tap((n) => Console.log(`after mapping: ${n}`))\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // Stream started\n * // after mapping: 2\n * // after mapping: 4\n * // after mapping: 6\n * // { _id: 'Chunk', values: [ 2, 4, 6 ] }\n * ```\n *\n * @since 3.6.0\n * @category sequencing\n */\nexport const onStart: {\n  <_, E2, R2>(\n    effect: Effect.Effect<_, E2, R2>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, _, E2, R2>(\n    self: Stream<A, E, R>,\n    effect: Effect.Effect<_, E2, R2>\n  ): Stream<A, E | E2, R | R2>\n} = internal.onStart\n\n/**\n * Translates any failure into a stream termination, making the stream\n * infallible and all failures unchecked.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orDie: <A, E, R>(self: Stream<A, E, R>) => Stream<A, never, R> = internal.orDie\n\n/**\n * Keeps none of the errors, and terminates the stream with them, using the\n * specified function to convert the `E` into a defect.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orDieWith: {\n  <E>(f: (e: E) => unknown): <A, R>(self: Stream<A, E, R>) => Stream<A, never, R>\n  <A, E, R>(self: Stream<A, E, R>, f: (e: E) => unknown): Stream<A, never, R>\n} = internal.orDieWith\n\n/**\n * Switches to the provided stream in case this one fails with a typed error.\n *\n * See also `Stream.catchAll`.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElse: {\n  <A2, E2, R2>(that: LazyArg<Stream<A2, E2, R2>>): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, that: LazyArg<Stream<A2, E2, R2>>): Stream<A | A2, E2, R | R2>\n} = internal.orElse\n\n/**\n * Switches to the provided stream in case this one fails with a typed error.\n *\n * See also `Stream.catchAll`.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElseEither: {\n  <A2, E2, R2>(\n    that: LazyArg<Stream<A2, E2, R2>>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<Either.Either<A2, A>, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    that: LazyArg<Stream<A2, E2, R2>>\n  ): Stream<Either.Either<A2, A>, E2, R | R2>\n} = internal.orElseEither\n\n/**\n * Fails with given error in case this one fails with a typed error.\n *\n * See also `Stream.catchAll`.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElseFail: {\n  <E2>(error: LazyArg<E2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2, R>\n  <A, E, R, E2>(self: Stream<A, E, R>, error: LazyArg<E2>): Stream<A, E2, R>\n} = internal.orElseFail\n\n/**\n * Produces the specified element if this stream is empty.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElseIfEmpty: {\n  <A2>(element: LazyArg<A2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E, R>\n  <A, E, R, A2>(self: Stream<A, E, R>, element: LazyArg<A2>): Stream<A | A2, E, R>\n} = internal.orElseIfEmpty\n\n/**\n * Produces the specified chunk if this stream is empty.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElseIfEmptyChunk: {\n  <A2>(chunk: LazyArg<Chunk.Chunk<A2>>): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E, R>\n  <A, E, R, A2>(self: Stream<A, E, R>, chunk: LazyArg<Chunk.Chunk<A2>>): Stream<A | A2, E, R>\n} = internal.orElseIfEmptyChunk\n\n/**\n * Switches to the provided stream in case this one is empty.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElseIfEmptyStream: {\n  <A2, E2, R2>(stream: LazyArg<Stream<A2, E2, R2>>): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, stream: LazyArg<Stream<A2, E2, R2>>): Stream<A | A2, E | E2, R | R2>\n} = internal.orElseIfEmptyStream\n\n/**\n * Succeeds with the specified value if this one fails with a typed error.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const orElseSucceed: {\n  <A2>(value: LazyArg<A2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, never, R>\n  <A, E, R, A2>(self: Stream<A, E, R>, value: LazyArg<A2>): Stream<A | A2, never, R>\n} = internal.orElseSucceed\n\n/**\n * Like `Stream.unfold`, but allows the emission of values to end one step further\n * than the unfolding of the state. This is useful for embedding paginated\n * APIs, hence the name.\n *\n * @example\n * ```ts\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const stream = Stream.paginate(0, (n) => [\n *   n,\n *   n < 3 ? Option.some(n + 1) : Option.none()\n * ])\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 0, 1, 2, 3 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const paginate: <S, A>(s: S, f: (s: S) => readonly [A, Option.Option<S>]) => Stream<A> = internal.paginate\n\n/**\n * Like `Stream.unfoldChunk`, but allows the emission of values to end one step\n * further than the unfolding of the state. This is useful for embedding\n * paginated APIs, hence the name.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const paginateChunk: <S, A>(\n  s: S,\n  f: (s: S) => readonly [Chunk.Chunk<A>, Option.Option<S>]\n) => Stream<A> = internal.paginateChunk\n\n/**\n * Like `Stream.unfoldChunkEffect`, but allows the emission of values to end one step\n * further than the unfolding of the state. This is useful for embedding\n * paginated APIs, hence the name.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const paginateChunkEffect: <S, A, E, R>(\n  s: S,\n  f: (s: S) => Effect.Effect<readonly [Chunk.Chunk<A>, Option.Option<S>], E, R>\n) => Stream<A, E, R> = internal.paginateChunkEffect\n\n/**\n * Like `Stream.unfoldEffect` but allows the emission of values to end one step\n * further than the unfolding of the state. This is useful for embedding\n * paginated APIs, hence the name.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const paginateEffect: <S, A, E, R>(\n  s: S,\n  f: (s: S) => Effect.Effect<readonly [A, Option.Option<S>], E, R>\n) => Stream<A, E, R> = internal.paginateEffect\n\n/**\n * Splits a stream into two substreams based on a predicate.\n *\n * **Details**\n *\n * The `Stream.partition` function splits a stream into two parts: one for\n * elements that satisfy the predicate (evaluated to `true`) and another for\n * those that do not (evaluated to `false`).\n *\n * The faster stream may advance up to `bufferSize` elements ahead of the slower\n * one.\n *\n * **Example** (Partitioning a Stream into Even and Odd Numbers)\n *\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const partition = Stream.range(1, 9).pipe(\n *   Stream.partition((n) => n % 2 === 0, { bufferSize: 5 })\n * )\n *\n * const program = Effect.scoped(\n *   Effect.gen(function*() {\n *     const [odds, evens] = yield* partition\n *     console.log(yield* Stream.runCollect(odds))\n *     console.log(yield* Stream.runCollect(evens))\n *   })\n * )\n *\n * Effect.runPromise(program)\n * // { _id: 'Chunk', values: [ 1, 3, 5, 7, 9 ] }\n * // { _id: 'Chunk', values: [ 2, 4, 6, 8 ] }\n * ```\n *\n * @see {@link partitionEither} for partitioning a stream based on effectful\n * conditions.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const partition: {\n  <C extends A, B extends A, A = C>(\n    refinement: Refinement<NoInfer<A>, B>,\n    options?: { bufferSize?: number | undefined } | undefined\n  ): <E, R>(\n    self: Stream<C, E, R>\n  ) => Effect.Effect<[excluded: Stream<Exclude<C, B>, E, never>, satisfying: Stream<B, E, never>], E, R | Scope.Scope>\n  <A>(\n    predicate: Predicate<A>,\n    options?: { bufferSize?: number | undefined } | undefined\n  ): <E, R>(\n    self: Stream<A, E, R>\n  ) => Effect.Effect<[excluded: Stream<A, E, never>, satisfying: Stream<A, E, never>], E, Scope.Scope | R>\n  <C extends A, E, R, B extends A, A = C>(\n    self: Stream<C, E, R>,\n    refinement: Refinement<A, B>,\n    options?: { bufferSize?: number | undefined } | undefined\n  ): Effect.Effect<[excluded: Stream<Exclude<C, B>, E, never>, satisfying: Stream<B, E, never>], E, R | Scope.Scope>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    predicate: Predicate<A>,\n    options?: { bufferSize?: number | undefined } | undefined\n  ): Effect.Effect<[excluded: Stream<A, E, never>, satisfying: Stream<A, E, never>], E, R | Scope.Scope>\n} = internal.partition\n\n/**\n * Splits a stream into two substreams based on an effectful condition.\n *\n * **Details**\n *\n * The `Stream.partitionEither` function is used to divide a stream into two\n * parts: one for elements that satisfy a condition producing `Either.left`\n * values, and another for those that produce `Either.right` values. This\n * function applies an effectful predicate to each element in the stream to\n * determine which substream it belongs to.\n *\n * The faster stream may advance up to `bufferSize` elements ahead of the slower\n * one.\n *\n * **Example** (Partitioning a Stream with an Effectful Predicate)\n *\n * ```ts\n * import { Effect, Either, Stream } from \"effect\"\n *\n * const partition = Stream.range(1, 9).pipe(\n *   Stream.partitionEither(\n *     (n) => Effect.succeed(n % 2 === 0 ? Either.right(n) : Either.left(n)),\n *     { bufferSize: 5 }\n *   )\n * )\n *\n * const program = Effect.scoped(\n *   Effect.gen(function*() {\n *     const [evens, odds] = yield* partition\n *     console.log(yield* Stream.runCollect(evens))\n *     console.log(yield* Stream.runCollect(odds))\n *   })\n * )\n *\n * Effect.runPromise(program)\n * // { _id: 'Chunk', values: [ 1, 3, 5, 7, 9 ] }\n * // { _id: 'Chunk', values: [ 2, 4, 6, 8 ] }\n * ```\n *\n * @see {@link partition} for partitioning a stream based on simple conditions.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const partitionEither: {\n  <A, A3, A2, E2, R2>(\n    predicate: (a: NoInfer<A>) => Effect.Effect<Either.Either<A3, A2>, E2, R2>,\n    options?: { readonly bufferSize?: number | undefined } | undefined\n  ): <E, R>(\n    self: Stream<A, E, R>\n  ) => Effect.Effect<[left: Stream<A2, E2 | E, never>, right: Stream<A3, E2 | E, never>], E2 | E, Scope.Scope | R2 | R>\n  <A, E, R, A3, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    predicate: (a: A) => Effect.Effect<Either.Either<A3, A2>, E2, R2>,\n    options?: { readonly bufferSize?: number | undefined } | undefined\n  ): Effect.Effect<[left: Stream<A2, E | E2, never>, right: Stream<A3, E | E2, never>], E | E2, Scope.Scope | R | R2>\n} = internal.partitionEither\n\n/**\n * Peels off enough material from the stream to construct a `Z` using the\n * provided `Sink` and then returns both the `Z` and the rest of the\n * `Stream` in a scope. Like all scoped values, the provided stream is\n * valid only within the scope.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const peel: {\n  <A2, A, E2, R2>(\n    sink: Sink.Sink<A2, A, A, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<[A2, Stream<A, E, never>], E2 | E, Scope.Scope | R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    sink: Sink.Sink<A2, A, A, E2, R2>\n  ): Effect.Effect<[A2, Stream<A, E, never>], E | E2, Scope.Scope | R | R2>\n} = internal.peel\n\n/**\n * Pipes all of the values from this stream through the provided sink.\n *\n * See also `Stream.transduce`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const pipeThrough: {\n  <A2, A, L, E2, R2>(sink: Sink.Sink<A2, A, L, E2, R2>): <E, R>(self: Stream<A, E, R>) => Stream<L, E2 | E, R2 | R>\n  <A, E, R, A2, L, E2, R2>(self: Stream<A, E, R>, sink: Sink.Sink<A2, A, L, E2, R2>): Stream<L, E | E2, R | R2>\n} = internal.pipeThrough\n\n/**\n * Pipes all the values from this stream through the provided channel.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const pipeThroughChannel: {\n  <R2, E, E2, A, A2>(\n    channel: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, E, unknown, unknown, R2>\n  ): <R>(self: Stream<A, E, R>) => Stream<A2, E2, R2 | R>\n  <R, R2, E, E2, A, A2>(\n    self: Stream<A, E, R>,\n    channel: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, E, unknown, unknown, R2>\n  ): Stream<A2, E2, R | R2>\n} = internal.pipeThroughChannel\n\n/**\n * Pipes all values from this stream through the provided channel, passing\n * through any error emitted by this stream unchanged.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const pipeThroughChannelOrFail: {\n  <R2, E, E2, A, A2>(\n    chan: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, E, unknown, unknown, R2>\n  ): <R>(self: Stream<A, E, R>) => Stream<A2, E | E2, R2 | R>\n  <R, R2, E, E2, A, A2>(\n    self: Stream<A, E, R>,\n    chan: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, E, unknown, unknown, R2>\n  ): Stream<A2, E | E2, R | R2>\n} = internal.pipeThroughChannelOrFail\n\n/**\n * Emits the provided chunk before emitting any other value.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const prepend: {\n  <B>(values: Chunk.Chunk<B>): <A, E, R>(self: Stream<A, E, R>) => Stream<B | A, E, R>\n  <A, E, R, B>(self: Stream<A, E, R>, values: Chunk.Chunk<B>): Stream<A | B, E, R>\n} = internal.prepend\n\n/**\n * Provides the stream with its required context, which eliminates its\n * dependency on `R`.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideContext: {\n  <R>(context: Context.Context<R>): <A, E>(self: Stream<A, E, R>) => Stream<A, E>\n  <A, E, R>(self: Stream<A, E, R>, context: Context.Context<R>): Stream<A, E>\n} = internal.provideContext\n\n/**\n * Provides the stream with some of its required context, which eliminates its\n * dependency on `R`.\n *\n * @since 3.16.9\n * @category context\n */\nexport const provideSomeContext: {\n  <R2>(context: Context.Context<R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, Exclude<R, R2>>\n  <A, E, R, R2>(self: Stream<A, E, R>, context: Context.Context<R2>): Stream<A, E, Exclude<R, R2>>\n} = internal.provideSomeContext\n\n/**\n * Provides a `Layer` to the stream, which translates it to another level.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideLayer: {\n  <RIn, E2, ROut>(layer: Layer.Layer<ROut, E2, RIn>): <A, E>(self: Stream<A, E, ROut>) => Stream<A, E2 | E, RIn>\n  <A, E, RIn, E2, ROut>(self: Stream<A, E, ROut>, layer: Layer.Layer<ROut, E2, RIn>): Stream<A, E | E2, RIn>\n} = internal.provideLayer\n\n/**\n * Provides the stream with the single service it requires. If the stream\n * requires more than one service use `Stream.provideContext` instead.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideService: {\n  <I, S>(tag: Context.Tag<I, S>, resource: NoInfer<S>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, Exclude<R, I>>\n  <A, E, R, I, S>(self: Stream<A, E, R>, tag: Context.Tag<I, S>, resource: NoInfer<S>): Stream<A, E, Exclude<R, I>>\n} = internal.provideService\n\n/**\n * Provides the stream with the single service it requires. If the stream\n * requires more than one service use `Stream.provideContext` instead.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideServiceEffect: {\n  <I, S, E2, R2>(\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<NoInfer<S>, E2, R2>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | Exclude<R, I>>\n  <A, E, R, I, S, E2, R2>(\n    self: Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<NoInfer<S>, E2, R2>\n  ): Stream<A, E2 | E, R2 | Exclude<R, I>>\n} = internal.provideServiceEffect\n\n/**\n * Provides the stream with the single service it requires. If the stream\n * requires more than one service use `Stream.provideContext` instead.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideServiceStream: {\n  <I, S, E2, R2>(\n    tag: Context.Tag<I, S>,\n    stream: Stream<NoInfer<S>, E2, R2>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | Exclude<R, I>>\n  <A, E, R, I, S, E2, R2>(\n    self: Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    stream: Stream<NoInfer<S>, E2, R2>\n  ): Stream<A, E2 | E, R2 | Exclude<R, I>>\n} = internal.provideServiceStream\n\n/**\n * Transforms the context being provided to the stream with the specified\n * function.\n *\n * @since 2.0.0\n * @category context\n */\nexport const mapInputContext: {\n  <R0, R>(f: (env: Context.Context<R0>) => Context.Context<R>): <A, E>(self: Stream<A, E, R>) => Stream<A, E, R0>\n  <A, E, R0, R>(self: Stream<A, E, R>, f: (env: Context.Context<R0>) => Context.Context<R>): Stream<A, E, R0>\n} = internal.mapInputContext\n\n/**\n * Splits the context into two parts, providing one part using the\n * specified layer and leaving the remainder `R0`.\n *\n * @since 2.0.0\n * @category context\n */\nexport const provideSomeLayer: {\n  <RIn, E2, ROut>(\n    layer: Layer.Layer<ROut, E2, RIn>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, RIn | Exclude<R, ROut>>\n  <A, E, R, RIn, E2, ROut>(\n    self: Stream<A, E, R>,\n    layer: Layer.Layer<ROut, E2, RIn>\n  ): Stream<A, E | E2, RIn | Exclude<R, ROut>>\n} = internal.provideSomeLayer\n\n/**\n * Returns a stream that mirrors the first upstream to emit an item.\n * As soon as one of the upstream emits a first value, the other is interrupted.\n * The resulting stream will forward all items from the \"winning\" source stream.\n * Any upstream failures will cause the returned stream to fail.\n *\n * @example\n * ```ts\n * import { Stream, Schedule, Console, Effect } from \"effect\"\n *\n * const stream = Stream.fromSchedule(Schedule.spaced('2 millis')).pipe(\n *   Stream.race(Stream.fromSchedule(Schedule.spaced('1 millis'))),\n *   Stream.take(6),\n *   Stream.tap(Console.log)\n * )\n *\n * Effect.runPromise(Stream.runDrain(stream))\n * // Output each millisecond from the first stream, the rest streams are interrupted\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * // 5\n * ```\n * @since 3.7.0\n * @category racing\n */\nexport const race: {\n  <AR, ER, RR>(\n    right: Stream<AR, ER, RR>\n  ): <AL, EL, RL>(left: Stream<AL, EL, RL>) => Stream<AL | AR, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream<AL, EL, RL>,\n    right: Stream<AR, ER, RR>\n  ): Stream<AL | AR, EL | ER, RL | RR>\n} = internal.race\n\n/**\n * Returns a stream that mirrors the first upstream to emit an item.\n * As soon as one of the upstream emits a first value, all the others are interrupted.\n * The resulting stream will forward all items from the \"winning\" source stream.\n * Any upstream failures will cause the returned stream to fail.\n *\n * @example\n * ```ts\n * import { Stream, Schedule, Console, Effect } from \"effect\"\n *\n * const stream = Stream.raceAll(\n *   Stream.fromSchedule(Schedule.spaced('1 millis')),\n *   Stream.fromSchedule(Schedule.spaced('2 millis')),\n *   Stream.fromSchedule(Schedule.spaced('4 millis')),\n * ).pipe(Stream.take(6), Stream.tap(Console.log))\n *\n * Effect.runPromise(Stream.runDrain(stream))\n * // Output each millisecond from the first stream, the rest streams are interrupted\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * // 5\n * ```\n * @since 3.5.0\n * @category racing\n */\nexport const raceAll: <S extends ReadonlyArray<Stream<any, any, any>>>(\n  ...streams: S\n) => Stream<\n  Stream.Success<S[number]>,\n  Stream.Error<S[number]>,\n  Stream.Context<S[number]>\n> = internal.raceAll\n\n/**\n * Constructs a stream from a range of integers, including both endpoints.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * // A Stream with a range of numbers from 1 to 5\n * const stream = Stream.range(1, 5)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const range: (min: number, max: number, chunkSize?: number) => Stream<number> = internal.range\n\n/**\n * Re-chunks the elements of the stream into chunks of `n` elements each. The\n * last chunk might contain less than `n` elements.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const rechunk: {\n  (n: number): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, n: number): Stream<A, E, R>\n} = internal.rechunk\n\n/**\n * Keeps some of the errors, and terminates the fiber with the rest\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const refineOrDie: {\n  <E, E2>(pf: (error: E) => Option.Option<E2>): <A, R>(self: Stream<A, E, R>) => Stream<A, E2, R>\n  <A, E, R, E2>(self: Stream<A, E, R>, pf: (error: E) => Option.Option<E2>): Stream<A, E2, R>\n} = internal.refineOrDie\n\n/**\n * Keeps some of the errors, and terminates the fiber with the rest, using the\n * specified function to convert the `E` into a defect.\n *\n * @since 2.0.0\n * @category error handling\n */\nexport const refineOrDieWith: {\n  <E, E2>(\n    pf: (error: E) => Option.Option<E2>,\n    f: (error: E) => unknown\n  ): <A, R>(self: Stream<A, E, R>) => Stream<A, E2, R>\n  <A, E, R, E2>(self: Stream<A, E, R>, pf: (error: E) => Option.Option<E2>, f: (error: E) => unknown): Stream<A, E2, R>\n} = internal.refineOrDieWith\n\n/**\n * Repeats the entire stream using the specified schedule. The stream will\n * execute normally, and then repeat again according to the provided schedule.\n *\n * @example\n * ```ts\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const stream = Stream.repeat(Stream.succeed(1), Schedule.forever)\n *\n * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 1, 1, 1, 1 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const repeat: {\n  <B, R2>(schedule: Schedule.Schedule<B, unknown, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R2 | R>\n  <A, E, R, B, R2>(self: Stream<A, E, R>, schedule: Schedule.Schedule<B, unknown, R2>): Stream<A, E, R | R2>\n} = internal.repeat\n\n/**\n * Creates a stream from an effect producing a value of type `A` which repeats\n * forever.\n *\n * @example\n * ```ts\n * import { Effect, Random, Stream } from \"effect\"\n *\n * const stream = Stream.repeatEffect(Random.nextInt)\n *\n * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)\n * // Example Output: { _id: 'Chunk', values: [ 3891571149, 4239494205, 2352981603, 2339111046, 1488052210 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const repeatEffect: <A, E, R>(effect: Effect.Effect<A, E, R>) => Stream<A, E, R> = internal.repeatEffect\n\n/**\n * Creates a stream from an effect producing chunks of `A` values which\n * repeats forever.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const repeatEffectChunk: <A, E, R>(effect: Effect.Effect<Chunk.Chunk<A>, E, R>) => Stream<A, E, R> =\n  internal.repeatEffectChunk\n\n/**\n * Creates a stream from an effect producing chunks of `A` values until it\n * fails with `None`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const repeatEffectChunkOption: <A, E, R>(\n  effect: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R>\n) => Stream<A, E, R> = internal.repeatEffectChunkOption\n\n/**\n * Creates a stream from an effect producing values of type `A` until it fails\n * with `None`.\n *\n * @example\n * ```ts\n * // In this example, we're draining an Iterator to create a stream from it\n * import { Stream, Effect, Option } from \"effect\"\n *\n * const drainIterator = <A>(it: Iterator<A>): Stream.Stream<A> =>\n *   Stream.repeatEffectOption(\n *     Effect.sync(() => it.next()).pipe(\n *       Effect.andThen((res) => {\n *         if (res.done) {\n *           return Effect.fail(Option.none())\n *         }\n *         return Effect.succeed(res.value)\n *       })\n *     )\n *   )\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const repeatEffectOption: <A, E, R>(effect: Effect.Effect<A, Option.Option<E>, R>) => Stream<A, E, R> =\n  internal.repeatEffectOption\n\n/**\n * Creates a stream from an effect producing a value of type `A`, which is\n * repeated using the specified schedule.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const repeatEffectWithSchedule: <A, E, R, X, A0 extends A, R2>(\n  effect: Effect.Effect<A, E, R>,\n  schedule: Schedule.Schedule<X, A0, R2>\n) => Stream<A, E, R | R2> = internal.repeatEffectWithSchedule\n\n/**\n * Repeats the entire stream using the specified schedule. The stream will\n * execute normally, and then repeat again according to the provided schedule.\n * The schedule output will be emitted at the end of each repetition.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const repeatEither: {\n  <B, R2>(\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<Either.Either<A, B>, E, R2 | R>\n  <A, E, R, B, R2>(\n    self: Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ): Stream<Either.Either<A, B>, E, R | R2>\n} = internal.repeatEither\n\n/**\n * Repeats each element of the stream using the provided schedule. Repetitions\n * are done in addition to the first execution, which means using\n * `Schedule.recurs(1)` actually results in the original effect, plus an\n * additional recurrence, for a total of two repetitions of each value in the\n * stream.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const repeatElements: {\n  <B, R2>(schedule: Schedule.Schedule<B, unknown, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R2 | R>\n  <A, E, R, B, R2>(self: Stream<A, E, R>, schedule: Schedule.Schedule<B, unknown, R2>): Stream<A, E, R | R2>\n} = internal.repeatElements\n\n/**\n * Repeats each element of the stream using the provided schedule. When the\n * schedule is finished, then the output of the schedule will be emitted into\n * the stream. Repetitions are done in addition to the first execution, which\n * means using `Schedule.recurs(1)` actually results in the original effect,\n * plus an additional recurrence, for a total of two repetitions of each value\n * in the stream.\n *\n * This function accepts two conversion functions, which allow the output of\n * this stream and the output of the provided schedule to be unified into a\n * single type. For example, `Either` or similar data type.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const repeatElementsWith: {\n  <B, R2, A, C>(\n    schedule: Schedule.Schedule<B, unknown, R2>,\n    options: { readonly onElement: (a: A) => C; readonly onSchedule: (b: B) => C }\n  ): <E, R>(self: Stream<A, E, R>) => Stream<C, E, R2 | R>\n  <A, E, R, B, R2, C>(\n    self: Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>,\n    options: { readonly onElement: (a: A) => C; readonly onSchedule: (b: B) => C }\n  ): Stream<C, E, R | R2>\n} = internal.repeatElementsWith\n\n/**\n * Repeats the provided value infinitely.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.repeatValue(0)\n *\n * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)\n * // { _id: 'Chunk', values: [ 0, 0, 0, 0, 0 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const repeatValue: <A>(value: A) => Stream<A> = internal.repeatValue\n\n/**\n * Repeats the entire stream using the specified schedule. The stream will\n * execute normally, and then repeat again according to the provided schedule.\n * The schedule output will be emitted at the end of each repetition and can\n * be unified with the stream elements using the provided functions.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const repeatWith: {\n  <B, R2, A, C>(\n    schedule: Schedule.Schedule<B, unknown, R2>,\n    options: { readonly onElement: (a: A) => C; readonly onSchedule: (b: B) => C }\n  ): <E, R>(self: Stream<A, E, R>) => Stream<C, E, R2 | R>\n  <A, E, R, B, R2, C>(\n    self: Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>,\n    options: { readonly onElement: (a: A) => C; readonly onSchedule: (b: B) => C }\n  ): Stream<C, E, R | R2>\n} = internal.repeatWith\n\n/**\n * When the stream fails, retry it according to the given schedule\n *\n * This retries the entire stream, so will re-execute all of the stream's\n * acquire operations.\n *\n * The schedule is reset as soon as the first element passes through the\n * stream again.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const retry: {\n  <E, R2, X>(policy: Schedule.Schedule<X, NoInfer<E>, R2>): <A, R>(self: Stream<A, E, R>) => Stream<A, E, R2 | R>\n  <A, E, R, X, R2>(self: Stream<A, E, R>, policy: Schedule.Schedule<X, NoInfer<E>, R2>): Stream<A, E, R2 | R>\n} = internal.retry\n\n/**\n * Apply an `ExecutionPlan` to the stream, which allows you to fallback to\n * different resources in case of failure.\n *\n * If you have a stream that could fail with partial results, you can use\n * the `preventFallbackOnPartialStream` option to prevent contamination of\n * the final stream with partial results.\n *\n * @since 3.16.0\n * @category Error handling\n * @experimental\n */\nexport const withExecutionPlan: {\n  <Input, R2, Provides, PolicyE>(\n    policy: ExecutionPlan<{ provides: Provides; input: Input; error: PolicyE; requirements: R2 }>,\n    options?: { readonly preventFallbackOnPartialStream?: boolean | undefined }\n  ): <A, E extends Input, R>(self: Stream<A, E, R>) => Stream<A, E | PolicyE, R2 | Exclude<R, Provides>>\n  <A, E extends Input, R, R2, Input, Provides, PolicyE>(\n    self: Stream<A, E, R>,\n    policy: ExecutionPlan<{ provides: Provides; input: Input; error: PolicyE; requirements: R2 }>,\n    options?: { readonly preventFallbackOnPartialStream?: boolean | undefined }\n  ): Stream<A, E | PolicyE, R2 | Exclude<R, Provides>>\n} = internal.withExecutionPlan\n\n/**\n * Runs the sink on the stream to produce either the sink's result or an error.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const run: {\n  <A2, A, E2, R2>(\n    sink: Sink.Sink<A2, A, unknown, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<A2, E2 | E, Exclude<R | R2, Scope.Scope>>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    sink: Sink.Sink<A2, A, unknown, E2, R2>\n  ): Effect.Effect<A2, E | E2, Exclude<R | R2, Scope.Scope>>\n} = internal.run\n\n/**\n * Runs the stream and collects all of its elements to a chunk.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runCollect: <A, E, R>(self: Stream<A, E, R>) => Effect.Effect<Chunk.Chunk<A>, E, R> = internal.runCollect\n\n/**\n * Runs the stream and emits the number of elements processed\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runCount: <A, E, R>(self: Stream<A, E, R>) => Effect.Effect<number, E, R> = internal.runCount\n\n/**\n * Runs the stream only for its effects. The emitted elements are discarded.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runDrain: <A, E, R>(self: Stream<A, E, R>) => Effect.Effect<void, E, R> = internal.runDrain\n\n/**\n * Executes a pure fold over the stream of values - reduces all elements in\n * the stream to a value of type `S`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runFold: {\n  <S, A>(s: S, f: (s: S, a: A) => S): <E, R>(self: Stream<A, E, R>) => Effect.Effect<S, E, R>\n  <A, E, R, S>(self: Stream<A, E, R>, s: S, f: (s: S, a: A) => S): Effect.Effect<S, E, R>\n} = internal.runFold\n\n/**\n * Executes an effectful fold over the stream of values.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runFoldEffect: {\n  <S, A, E2, R2>(\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<S, E2 | E, Exclude<R | R2, Scope.Scope>>\n  <A, E, R, S, E2, R2>(\n    self: Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): Effect.Effect<S, E | E2, Exclude<R | R2, Scope.Scope>>\n} = internal.runFoldEffect\n\n/**\n * Executes a pure fold over the stream of values. Returns a scoped value that\n * represents the scope of the stream.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runFoldScoped: {\n  <S, A>(s: S, f: (s: S, a: A) => S): <E, R>(self: Stream<A, E, R>) => Effect.Effect<S, E, Scope.Scope | R>\n  <A, E, R, S>(self: Stream<A, E, R>, s: S, f: (s: S, a: A) => S): Effect.Effect<S, E, Scope.Scope | R>\n} = internal.runFoldScoped\n\n/**\n * Executes an effectful fold over the stream of values. Returns a scoped\n * value that represents the scope of the stream.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runFoldScopedEffect: {\n  <S, A, E2, R2>(\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<S, E2 | E, Scope.Scope | R2 | R>\n  <A, E, R, S, E2, R2>(\n    self: Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): Effect.Effect<S, E | E2, Scope.Scope | R | R2>\n} = internal.runFoldScopedEffect\n\n/**\n * Reduces the elements in the stream to a value of type `S`. Stops the fold\n * early when the condition is not fulfilled. Example:\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runFoldWhile: {\n  <S, A>(s: S, cont: Predicate<S>, f: (s: S, a: A) => S): <E, R>(self: Stream<A, E, R>) => Effect.Effect<S, E, R>\n  <A, E, R, S>(self: Stream<A, E, R>, s: S, cont: Predicate<S>, f: (s: S, a: A) => S): Effect.Effect<S, E, R>\n} = internal.runFoldWhile\n\n/**\n * Executes an effectful fold over the stream of values. Stops the fold early\n * when the condition is not fulfilled.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runFoldWhileEffect: {\n  <S, A, E2, R2>(\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<S, E2 | E, Exclude<R | R2, Scope.Scope>>\n  <A, E, R, S, E2, R2>(\n    self: Stream<A, E, R>,\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): Effect.Effect<S, E | E2, Exclude<R | R2, Scope.Scope>>\n} = internal.runFoldWhileEffect\n\n/**\n * Executes a pure fold over the stream of values. Returns a scoped value that\n * represents the scope of the stream. Stops the fold early when the condition\n * is not fulfilled.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runFoldWhileScoped: {\n  <S, A>(\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => S\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<S, E, Scope.Scope | R>\n  <A, E, R, S>(\n    self: Stream<A, E, R>,\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => S\n  ): Effect.Effect<S, E, Scope.Scope | R>\n} = internal.runFoldWhileScoped\n\n/**\n * Executes an effectful fold over the stream of values. Returns a scoped\n * value that represents the scope of the stream. Stops the fold early when\n * the condition is not fulfilled.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runFoldWhileScopedEffect: {\n  <S, A, E2, R2>(\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<S, E2 | E, R2 | R | Scope.Scope>\n  <A, E, R, S, E2, R2>(\n    self: Stream<A, E, R>,\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): Effect.Effect<S, E | E2, Scope.Scope | R | R2>\n} = internal.runFoldWhileScopedEffect\n\n/**\n * Consumes all elements of the stream, passing them to the specified\n * callback.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runForEach: {\n  <A, X, E2, R2>(\n    f: (a: A) => Effect.Effect<X, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<void, E2 | E, R2 | R>\n  <A, E, R, X, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<X, E2, R2>\n  ): Effect.Effect<void, E | E2, R | R2>\n} = internal.runForEach\n\n/**\n * Consumes all elements of the stream, passing them to the specified\n * callback.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runForEachChunk: {\n  <A, X, E2, R2>(\n    f: (a: Chunk.Chunk<A>) => Effect.Effect<X, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<void, E2 | E, R2 | R>\n  <A, E, R, X, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: Chunk.Chunk<A>) => Effect.Effect<X, E2, R2>\n  ): Effect.Effect<void, E | E2, R | R2>\n} = internal.runForEachChunk\n\n/**\n * Like `Stream.runForEachChunk`, but returns a scoped effect so the\n * finalization order can be controlled.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runForEachChunkScoped: {\n  <A, X, E2, R2>(\n    f: (a: Chunk.Chunk<A>) => Effect.Effect<X, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<void, E2 | E, Scope.Scope | R2 | R>\n  <A, E, R, X, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: Chunk.Chunk<A>) => Effect.Effect<X, E2, R2>\n  ): Effect.Effect<void, E | E2, Scope.Scope | R | R2>\n} = internal.runForEachChunkScoped\n\n/**\n * Like `Stream.forEach`, but returns a scoped effect so the finalization\n * order can be controlled.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runForEachScoped: {\n  <A, X, E2, R2>(\n    f: (a: A) => Effect.Effect<X, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<void, E2 | E, Scope.Scope | R2 | R>\n  <A, E, R, X, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<X, E2, R2>\n  ): Effect.Effect<void, E | E2, Scope.Scope | R | R2>\n} = internal.runForEachScoped\n\n/**\n * Consumes elements of the stream, passing them to the specified callback,\n * and terminating consumption when the callback returns `false`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runForEachWhile: {\n  <A, E2, R2>(\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<void, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): Effect.Effect<void, E | E2, R | R2>\n} = internal.runForEachWhile\n\n/**\n * Like `Stream.runForEachWhile`, but returns a scoped effect so the\n * finalization order can be controlled.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runForEachWhileScoped: {\n  <A, E2, R2>(\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<void, E2 | E, Scope.Scope | R2 | R>\n  <A, E, R, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): Effect.Effect<void, E | E2, Scope.Scope | R | R2>\n} = internal.runForEachWhileScoped\n\n/**\n * Runs the stream to completion and yields the first value emitted by it,\n * discarding the rest of the elements.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runHead: <A, E, R>(self: Stream<A, E, R>) => Effect.Effect<Option.Option<A>, E, R> = internal.runHead\n\n/**\n * Publishes elements of this stream to a `PubSub`. Stream failure and ending will\n * also be signalled.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runIntoPubSub: {\n  <A, E>(pubsub: PubSub.PubSub<Take.Take<A, E>>): <R>(self: Stream<A, E, R>) => Effect.Effect<void, never, R>\n  <A, E, R>(self: Stream<A, E, R>, pubsub: PubSub.PubSub<Take.Take<A, E>>): Effect.Effect<void, never, R>\n} = internal.runIntoPubSub\n\n/**\n * Like `Stream.runIntoPubSub`, but provides the result as a scoped effect to\n * allow for scope composition.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runIntoPubSubScoped: {\n  <A, E>(\n    pubsub: PubSub.PubSub<Take.Take<A, E>>\n  ): <R>(self: Stream<A, E, R>) => Effect.Effect<void, never, Scope.Scope | R>\n  <A, E, R>(self: Stream<A, E, R>, pubsub: PubSub.PubSub<Take.Take<A, E>>): Effect.Effect<void, never, Scope.Scope | R>\n} = internal.runIntoPubSubScoped\n\n/**\n * Enqueues elements of this stream into a queue. Stream failure and ending\n * will also be signalled.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runIntoQueue: {\n  <A, E>(queue: Queue.Enqueue<Take.Take<A, E>>): <R>(self: Stream<A, E, R>) => Effect.Effect<void, never, R>\n  <A, E, R>(self: Stream<A, E, R>, queue: Queue.Enqueue<Take.Take<A, E>>): Effect.Effect<void, never, R>\n} = internal.runIntoQueue\n\n/**\n * Like `Stream.runIntoQueue`, but provides the result as a scoped Effect\n * to allow for scope composition.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runIntoQueueElementsScoped: {\n  <A, E>(\n    queue: Queue.Enqueue<Exit.Exit<A, Option.Option<E>>>\n  ): <R>(self: Stream<A, E, R>) => Effect.Effect<void, never, Scope.Scope | R>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    queue: Queue.Enqueue<Exit.Exit<A, Option.Option<E>>>\n  ): Effect.Effect<void, never, Scope.Scope | R>\n} = internal.runIntoQueueElementsScoped\n\n/**\n * Like `Stream.runIntoQueue`, but provides the result as a scoped effect\n * to allow for scope composition.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runIntoQueueScoped: {\n  <A, E>(\n    queue: Queue.Enqueue<Take.Take<A, E>>\n  ): <R>(self: Stream<A, E, R>) => Effect.Effect<void, never, Scope.Scope | R>\n  <A, E, R>(self: Stream<A, E, R>, queue: Queue.Enqueue<Take.Take<A, E>>): Effect.Effect<void, never, Scope.Scope | R>\n} = internal.runIntoQueueScoped\n\n/**\n * Runs the stream to completion and yields the last value emitted by it,\n * discarding the rest of the elements.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runLast: <A, E, R>(self: Stream<A, E, R>) => Effect.Effect<Option.Option<A>, E, R> = internal.runLast\n\n/**\n * @since 2.0.0\n * @category destructors\n */\nexport const runScoped: {\n  <A2, A, E2, R2>(\n    sink: Sink.Sink<A2, A, unknown, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<A2, E2 | E, Scope.Scope | R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    sink: Sink.Sink<A2, A, unknown, E2, R2>\n  ): Effect.Effect<A2, E | E2, Scope.Scope | R | R2>\n} = internal.runScoped\n\n/**\n * Runs the stream to a sink which sums elements, provided they are Numeric.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const runSum: <E, R>(self: Stream<number, E, R>) => Effect.Effect<number, E, R> = internal.runSum\n\n/**\n * Statefully maps over the elements of this stream to produce all\n * intermediate results of type `S` given an initial S.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.range(1, 6).pipe(Stream.scan(0, (a, b) => a + b))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 0,  1,  3, 6, 10, 15, 21 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const scan: {\n  <S, A>(s: S, f: (s: S, a: A) => S): <E, R>(self: Stream<A, E, R>) => Stream<S, E, R>\n  <A, E, R, S>(self: Stream<A, E, R>, s: S, f: (s: S, a: A) => S): Stream<S, E, R>\n} = internal.scan\n\n/**\n * Statefully and effectfully maps over the elements of this stream to produce\n * all intermediate results of type `S` given an initial S.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const scanEffect: {\n  <S, A, E2, R2>(\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<S, E2 | E, R2 | R>\n  <A, E, R, S, E2, R2>(\n    self: Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): Stream<S, E | E2, R | R2>\n} = internal.scanEffect\n\n/**\n * Statefully maps over the elements of this stream to produce all\n * intermediate results.\n *\n * See also `Stream.scan`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const scanReduce: {\n  <A2, A>(f: (a2: A2 | A, a: A) => A2): <E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E, R>\n  <A, E, R, A2>(self: Stream<A, E, R>, f: (a2: A | A2, a: A) => A2): Stream<A | A2, E, R>\n} = internal.scanReduce\n\n/**\n * Statefully and effectfully maps over the elements of this stream to produce\n * all intermediate results.\n *\n * See also `Stream.scanEffect`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const scanReduceEffect: {\n  <A2, A, E2, R2>(\n    f: (a2: A2 | A, a: A) => Effect.Effect<A2 | A, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (a2: A | A2, a: A) => Effect.Effect<A | A2, E2, R2>\n  ): Stream<A | A2, E | E2, R | R2>\n} = internal.scanReduceEffect\n\n/**\n * Schedules the output of the stream using the provided `schedule`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const schedule: {\n  <X, A0 extends A, R2, A>(\n    schedule: Schedule.Schedule<X, A0, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A, E, R2 | R>\n  <A, E, R, X, A0 extends A, R2>(self: Stream<A, E, R>, schedule: Schedule.Schedule<X, A0, R2>): Stream<A, E, R | R2>\n} = internal.schedule\n\n/**\n * Schedules the output of the stream using the provided `schedule` and emits\n * its output at the end (if `schedule` is finite). Uses the provided function\n * to align the stream and schedule outputs on the same type.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const scheduleWith: {\n  <B, A0 extends A, R2, A, C>(\n    schedule: Schedule.Schedule<B, A0, R2>,\n    options: { readonly onElement: (a: A) => C; readonly onSchedule: (b: B) => C }\n  ): <E, R>(self: Stream<A, E, R>) => Stream<C, E, R2 | R>\n  <A, E, R, B, A0 extends A, R2, C>(\n    self: Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, A0, R2>,\n    options: { readonly onElement: (a: A) => C; readonly onSchedule: (b: B) => C }\n  ): Stream<C, E, R | R2>\n} = internal.scheduleWith\n\n/**\n * Creates a single-valued stream from a scoped resource.\n *\n * @example\n * ```ts\n * import { Console, Effect, Stream } from \"effect\"\n *\n * // Creating a single-valued stream from a scoped resource\n * const stream = Stream.scoped(\n *  Effect.acquireRelease(\n *    Console.log(\"acquire\"),\n *    () => Console.log(\"release\")\n *  )\n * ).pipe(\n *  Stream.flatMap(() => Console.log(\"use\"))\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // acquire\n * // use\n * // release\n * // { _id: 'Chunk', values: [ undefined ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const scoped: <A, E, R>(effect: Effect.Effect<A, E, R>) => Stream<A, E, Exclude<R, Scope.Scope>> =\n  internal.scoped\n\n/**\n * Use a function that receives a scope and returns an effect to emit an output\n * element. The output element will be the result of the returned effect, if\n * successful.\n *\n * @since 3.11.0\n * @category constructors\n */\nexport const scopedWith: <A, E, R>(f: (scope: Scope.Scope) => Effect.Effect<A, E, R>) => Stream<A, E, R> =\n  internal.scopedWith\n\n/**\n * Emits a sliding window of `n` elements.\n *\n * ```ts\n * import { pipe, Stream } from \"effect\"\n *\n * pipe(\n *   Stream.make(1, 2, 3, 4),\n *   Stream.sliding(2),\n *   Stream.runCollect\n * )\n * // => Chunk(Chunk(1, 2), Chunk(2, 3), Chunk(3, 4))\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const sliding: {\n  (chunkSize: number): <A, E, R>(self: Stream<A, E, R>) => Stream<Chunk.Chunk<A>, E, R>\n  <A, E, R>(self: Stream<A, E, R>, chunkSize: number): Stream<Chunk.Chunk<A>, E, R>\n} = internal.sliding\n\n/**\n * Like `sliding`, but with a configurable `stepSize` parameter.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const slidingSize: {\n  (chunkSize: number, stepSize: number): <A, E, R>(self: Stream<A, E, R>) => Stream<Chunk.Chunk<A>, E, R>\n  <A, E, R>(self: Stream<A, E, R>, chunkSize: number, stepSize: number): Stream<Chunk.Chunk<A>, E, R>\n} = internal.slidingSize\n\n/**\n * Converts an option on values into an option on errors.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const some: <A, E, R>(self: Stream<Option.Option<A>, E, R>) => Stream<A, Option.Option<E>, R> = internal.some\n\n/**\n * Extracts the optional value, or returns the given 'default'.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const someOrElse: {\n  <A2>(fallback: LazyArg<A2>): <A, E, R>(self: Stream<Option.Option<A>, E, R>) => Stream<A2 | A, E, R>\n  <A, E, R, A2>(self: Stream<Option.Option<A>, E, R>, fallback: LazyArg<A2>): Stream<A | A2, E, R>\n} = internal.someOrElse\n\n/**\n * Extracts the optional value, or fails with the given error 'e'.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const someOrFail: {\n  <E2>(error: LazyArg<E2>): <A, E, R>(self: Stream<Option.Option<A>, E, R>) => Stream<A, E2 | E, R>\n  <A, E, R, E2>(self: Stream<Option.Option<A>, E, R>, error: LazyArg<E2>): Stream<A, E | E2, R>\n} = internal.someOrFail\n\n/**\n * Splits elements based on a predicate or refinement.\n *\n * ```ts\n * import { pipe, Stream } from \"effect\"\n *\n * pipe(\n *   Stream.range(1, 10),\n *   Stream.split((n) => n % 4 === 0),\n *   Stream.runCollect\n * )\n * // => Chunk(Chunk(1, 2, 3), Chunk(5, 6, 7), Chunk(9))\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const split: {\n  <A, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<Chunk.Chunk<Exclude<A, B>>, E, R>\n  <A>(predicate: Predicate<NoInfer<A>>): <E, R>(self: Stream<A, E, R>) => Stream<Chunk.Chunk<A>, E, R>\n  <A, E, R, B extends A>(self: Stream<A, E, R>, refinement: Refinement<A, B>): Stream<Chunk.Chunk<Exclude<A, B>>, E, R>\n  <A, E, R>(self: Stream<A, E, R>, predicate: Predicate<A>): Stream<Chunk.Chunk<A>, E, R>\n} = internal.split\n\n/**\n * Splits elements on a delimiter and transforms the splits into desired output.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const splitOnChunk: {\n  <A>(delimiter: Chunk.Chunk<A>): <E, R>(self: Stream<A, E, R>) => Stream<Chunk.Chunk<A>, E, R>\n  <A, E, R>(self: Stream<A, E, R>, delimiter: Chunk.Chunk<A>): Stream<Chunk.Chunk<A>, E, R>\n} = internal.splitOnChunk\n\n/**\n * Splits strings on newlines. Handles both Windows newlines (`\\r\\n`) and UNIX\n * newlines (`\\n`).\n *\n * @since 2.0.0\n * @category combinators\n */\nexport const splitLines: <E, R>(self: Stream<string, E, R>) => Stream<string, E, R> = internal.splitLines\n\n/**\n * Creates a single-valued pure stream.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * // A Stream with a single number\n * const stream = Stream.succeed(3)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 3 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const succeed: <A>(value: A) => Stream<A> = internal.succeed\n\n/**\n * Creates a single-valued pure stream.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sync: <A>(evaluate: LazyArg<A>) => Stream<A> = internal.sync\n\n/**\n * Returns a lazily constructed stream.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const suspend: <A, E, R>(stream: LazyArg<Stream<A, E, R>>) => Stream<A, E, R> = internal.suspend\n\n/**\n * Takes the specified number of elements from this stream.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.take(Stream.iterate(0, (n) => n + 1), 5)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const take: {\n  (n: number): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, n: number): Stream<A, E, R>\n} = internal.take\n\n/**\n * Takes the last specified number of elements from this stream.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.takeRight(Stream.make(1, 2, 3, 4, 5, 6), 3)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 4, 5, 6 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const takeRight: {\n  (n: number): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, n: number): Stream<A, E, R>\n} = internal.takeRight\n\n/**\n * Takes all elements of the stream until the specified predicate evaluates to\n * `true`.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.takeUntil(Stream.iterate(0, (n) => n + 1), (n) => n === 4)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const takeUntil: {\n  <A>(predicate: Predicate<NoInfer<A>>): <E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, predicate: Predicate<A>): Stream<A, E, R>\n} = internal.takeUntil\n\n/**\n * Takes all elements of the stream until the specified effectual predicate\n * evaluates to `true`.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const takeUntilEffect: {\n  <A, E2, R2>(\n    predicate: (a: NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(\n    self: Stream<A, E, R>,\n    predicate: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): Stream<A, E | E2, R | R2>\n} = internal.takeUntilEffect\n\n/**\n * Takes all elements of the stream for as long as the specified predicate\n * evaluates to `true`.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.takeWhile(Stream.iterate(0, (n) => n + 1), (n) => n < 5)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ 0, 1, 2, 3, 4 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const takeWhile: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): <E, R>(self: Stream<A, E, R>) => Stream<B, E, R>\n  <A>(predicate: Predicate<NoInfer<A>>): <E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R, B extends A>(self: Stream<A, E, R>, refinement: Refinement<A, B>): Stream<B, E, R>\n  <A, E, R>(self: Stream<A, E, R>, predicate: Predicate<A>): Stream<A, E, R>\n} = internal.takeWhile\n\n/**\n * Adds an effect to consumption of every element of the stream.\n *\n * @example\n * ```ts\n * import { Console, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(1, 2, 3).pipe(\n *   Stream.tap((n) => Console.log(`before mapping: ${n}`)),\n *   Stream.map((n) => n * 2),\n *   Stream.tap((n) => Console.log(`after mapping: ${n}`))\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // before mapping: 1\n * // after mapping: 2\n * // before mapping: 2\n * // after mapping: 4\n * // before mapping: 3\n * // after mapping: 6\n * // { _id: 'Chunk', values: [ 2, 4, 6 ] }\n * ```\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tap: {\n  <A, X, E2, R2>(\n    f: (a: NoInfer<A>) => Effect.Effect<X, E2, R2>\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, X, E2, R2>(self: Stream<A, E, R>, f: (a: NoInfer<A>) => Effect.Effect<X, E2, R2>): Stream<A, E | E2, R | R2>\n} = internal.tap\n\n/**\n * Returns a stream that effectfully \"peeks\" at the failure or success of\n * the stream.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tapBoth: {\n  <E, X1, E2, R2, A, X2, E3, R3>(\n    options: {\n      readonly onFailure: (e: NoInfer<E>) => Effect.Effect<X1, E2, R2>\n      readonly onSuccess: (a: NoInfer<A>) => Effect.Effect<X2, E3, R3>\n    }\n  ): <R>(self: Stream<A, E, R>) => Stream<A, E | E2 | E3, R2 | R3 | R>\n  <A, E, R, X1, E2, R2, X2, E3, R3>(\n    self: Stream<A, E, R>,\n    options: {\n      readonly onFailure: (e: NoInfer<E>) => Effect.Effect<X1, E2, R2>\n      readonly onSuccess: (a: NoInfer<A>) => Effect.Effect<X2, E3, R3>\n    }\n  ): Stream<A, E | E2 | E3, R | R2 | R3>\n} = internal.tapBoth\n\n/**\n * Returns a stream that effectfully \"peeks\" at the failure of the stream.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tapError: {\n  <E, X, E2, R2>(\n    f: (error: NoInfer<E>) => Effect.Effect<X, E2, R2>\n  ): <A, R>(self: Stream<A, E, R>) => Stream<A, E | E2, R2 | R>\n  <A, E, R, X, E2, R2>(self: Stream<A, E, R>, f: (error: E) => Effect.Effect<X, E2, R2>): Stream<A, E | E2, R | R2>\n} = internal.tapError\n\n/**\n * Returns a stream that effectfully \"peeks\" at the cause of failure of the\n * stream.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const tapErrorCause: {\n  <E, X, E2, R2>(\n    f: (cause: Cause.Cause<NoInfer<E>>) => Effect.Effect<X, E2, R2>\n  ): <A, R>(self: Stream<A, E, R>) => Stream<A, E | E2, R2 | R>\n  <A, E, R, X, E2, R2>(\n    self: Stream<A, E, R>,\n    f: (cause: Cause.Cause<E>) => Effect.Effect<X, E2, R2>\n  ): Stream<A, E | E2, R | R2>\n} = internal.tapErrorCause\n\n/**\n * Sends all elements emitted by this stream to the specified sink in addition\n * to emitting them.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tapSink: {\n  <A, E2, R2>(sink: Sink.Sink<unknown, A, unknown, E2, R2>): <E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(self: Stream<A, E, R>, sink: Sink.Sink<unknown, A, unknown, E2, R2>): Stream<A, E | E2, R | R2>\n} = internal.tapSink\n\n/**\n * Delays the chunks of this stream according to the given bandwidth\n * parameters using the token bucket algorithm. Allows for burst in the\n * processing of elements by allowing the token bucket to accumulate tokens up\n * to a `units + burst` threshold. The weight of each chunk is determined by\n * the `cost` function.\n *\n * If using the \"enforce\" strategy, chunks that do not meet the bandwidth\n * constraints are dropped. If using the \"shape\" strategy, chunks are delayed\n * until they can be emitted without exceeding the bandwidth constraints.\n *\n * Defaults to the \"shape\" strategy.\n *\n * @example\n * ```ts\n * import { Chunk, Effect, Schedule, Stream } from \"effect\"\n *\n * let last = Date.now()\n * const log = (message: string) =>\n *   Effect.sync(() => {\n *     const end = Date.now()\n *     console.log(`${message} after ${end - last}ms`)\n *     last = end\n *   })\n *\n * const stream = Stream.fromSchedule(Schedule.spaced(\"50 millis\")).pipe(\n *   Stream.take(6),\n *   Stream.tap((n) => log(`Received ${n}`)),\n *   Stream.throttle({\n *     cost: Chunk.size,\n *     duration: \"100 millis\",\n *     units: 1\n *   }),\n *   Stream.tap((n) => log(`> Emitted ${n}`))\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // Received 0 after 56ms\n * // > Emitted 0 after 0ms\n * // Received 1 after 52ms\n * // > Emitted 1 after 48ms\n * // Received 2 after 52ms\n * // > Emitted 2 after 49ms\n * // Received 3 after 52ms\n * // > Emitted 3 after 48ms\n * // Received 4 after 52ms\n * // > Emitted 4 after 47ms\n * // Received 5 after 52ms\n * // > Emitted 5 after 49ms\n * // { _id: 'Chunk', values: [ 0, 1, 2, 3, 4, 5 ] }\n * ```\n *\n * @since 2.0.0\n * @category utils\n */\nexport const throttle: {\n  <A>(\n    options: {\n      readonly cost: (chunk: Chunk.Chunk<A>) => number\n      readonly units: number\n      readonly duration: Duration.DurationInput\n      readonly burst?: number | undefined\n      readonly strategy?: \"enforce\" | \"shape\" | undefined\n    }\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    options: {\n      readonly cost: (chunk: Chunk.Chunk<A>) => number\n      readonly units: number\n      readonly duration: Duration.DurationInput\n      readonly burst?: number | undefined\n      readonly strategy?: \"enforce\" | \"shape\" | undefined\n    }\n  ): Stream<A, E, R>\n} = internal.throttle\n\n/**\n * Delays the chunks of this stream according to the given bandwidth\n * parameters using the token bucket algorithm. Allows for burst in the\n * processing of elements by allowing the token bucket to accumulate tokens up\n * to a `units + burst` threshold. The weight of each chunk is determined by\n * the effectful `costFn` function.\n *\n * If using the \"enforce\" strategy, chunks that do not meet the bandwidth\n * constraints are dropped. If using the \"shape\" strategy, chunks are delayed\n * until they can be emitted without exceeding the bandwidth constraints.\n *\n * Defaults to the \"shape\" strategy.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const throttleEffect: {\n  <A, E2, R2>(\n    options: {\n      readonly cost: (chunk: Chunk.Chunk<A>) => Effect.Effect<number, E2, R2>\n      readonly units: number\n      readonly duration: Duration.DurationInput\n      readonly burst?: number | undefined\n      readonly strategy?: \"enforce\" | \"shape\" | undefined\n    }\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(\n    self: Stream<A, E, R>,\n    options: {\n      readonly cost: (chunk: Chunk.Chunk<A>) => Effect.Effect<number, E2, R2>\n      readonly units: number\n      readonly duration: Duration.DurationInput\n      readonly burst?: number | undefined\n      readonly strategy?: \"enforce\" | \"shape\" | undefined\n    }\n  ): Stream<A, E | E2, R | R2>\n} = internal.throttleEffect\n\n/**\n * A stream that emits void values spaced by the specified duration.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * let last = Date.now()\n * const log = (message: string) =>\n *   Effect.sync(() => {\n *     const end = Date.now()\n *     console.log(`${message} after ${end - last}ms`)\n *     last = end\n *   })\n *\n * const stream = Stream.tick(\"1 seconds\").pipe(Stream.tap(() => log(\"tick\")))\n *\n * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)\n * // tick after 4ms\n * // tick after 1003ms\n * // tick after 1001ms\n * // tick after 1002ms\n * // tick after 1002ms\n * // { _id: 'Chunk', values: [ undefined, undefined, undefined, undefined, undefined ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const tick: (interval: Duration.DurationInput) => Stream<void> = internal.tick\n\n/**\n * Ends the stream if it does not produce a value after the specified duration.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const timeout: {\n  (duration: Duration.DurationInput): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, duration: Duration.DurationInput): Stream<A, E, R>\n} = internal.timeout\n\n/**\n * Fails the stream with given error if it does not produce a value after d\n * duration.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const timeoutFail: {\n  <E2>(error: LazyArg<E2>, duration: Duration.DurationInput): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R>\n  <A, E, R, E2>(self: Stream<A, E, R>, error: LazyArg<E2>, duration: Duration.DurationInput): Stream<A, E | E2, R>\n} = internal.timeoutFail\n\n/**\n * Fails the stream with given cause if it does not produce a value after d\n * duration.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const timeoutFailCause: {\n  <E2>(\n    cause: LazyArg<Cause.Cause<E2>>,\n    duration: Duration.DurationInput\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R>\n  <A, E, R, E2>(\n    self: Stream<A, E, R>,\n    cause: LazyArg<Cause.Cause<E2>>,\n    duration: Duration.DurationInput\n  ): Stream<A, E | E2, R>\n} = internal.timeoutFailCause\n\n/**\n * Switches the stream if it does not produce a value after the specified\n * duration.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const timeoutTo: {\n  <A2, E2, R2>(\n    duration: Duration.DurationInput,\n    that: Stream<A2, E2, R2>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A2 | A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    duration: Duration.DurationInput,\n    that: Stream<A2, E2, R2>\n  ): Stream<A | A2, E | E2, R | R2>\n} = internal.timeoutTo\n\n/**\n * Converts the stream to a scoped `PubSub` of chunks. After the scope is closed,\n * the `PubSub` will never again produce values and should be discarded.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toPubSub: {\n  (\n    capacity: number | { readonly capacity: \"unbounded\"; readonly replay?: number | undefined } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ): <A, E, R>(self: Stream<A, E, R>) => Effect.Effect<PubSub.PubSub<Take.Take<A, E>>, never, Scope.Scope | R>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    capacity: number | { readonly capacity: \"unbounded\"; readonly replay?: number | undefined } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ): Effect.Effect<PubSub.PubSub<Take.Take<A, E>>, never, Scope.Scope | R>\n} = internal.toPubSub\n\n/**\n * Returns in a scope an Effect that can be used to repeatedly pull chunks\n * from the stream. The pull effect fails with None when the stream is\n * finished, or with Some error if it fails, otherwise it returns a chunk of\n * the stream's output.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * // Simulate a chunked stream\n * const stream = Stream.fromIterable([1, 2, 3, 4, 5]).pipe(Stream.rechunk(2))\n *\n * const program = Effect.gen(function*() {\n *   // Create an effect to get data chunks from the stream\n *   const getChunk = yield* Stream.toPull(stream)\n *\n *   // Continuously fetch and process chunks\n *   while (true) {\n *     const chunk = yield* getChunk\n *     console.log(chunk)\n *   }\n * })\n *\n * Effect.runPromise(Effect.scoped(program)).then(console.log, console.error)\n * // { _id: 'Chunk', values: [ 1, 2 ] }\n * // { _id: 'Chunk', values: [ 3, 4 ] }\n * // { _id: 'Chunk', values: [ 5 ] }\n * // (FiberFailure) Error: {\n * //   \"_id\": \"Option\",\n * //   \"_tag\": \"None\"\n * // }\n * ```\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toPull: <A, E, R>(\n  self: Stream<A, E, R>\n) => Effect.Effect<Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R>, never, Scope.Scope | R> = internal.toPull\n\n/**\n * Converts the stream to a scoped queue of chunks. After the scope is closed,\n * the queue will never again produce values and should be discarded.\n *\n * Defaults to the \"suspend\" back pressure strategy with a capacity of 2.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toQueue: {\n  (\n    options?:\n      | { readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined; readonly capacity?: number | undefined }\n      | { readonly strategy: \"unbounded\" }\n      | undefined\n  ): <A, E, R>(self: Stream<A, E, R>) => Effect.Effect<Queue.Dequeue<Take.Take<A, E>>, never, Scope.Scope | R>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    options?:\n      | { readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined; readonly capacity?: number | undefined }\n      | { readonly strategy: \"unbounded\" }\n      | undefined\n  ): Effect.Effect<Queue.Dequeue<Take.Take<A, E>>, never, Scope.Scope | R>\n} = internal.toQueue\n\n/**\n * Converts the stream to a scoped queue of elements. After the scope is\n * closed, the queue will never again produce values and should be discarded.\n *\n * Defaults to a capacity of 2.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toQueueOfElements: {\n  (\n    options?: { readonly capacity?: number | undefined } | undefined\n  ): <A, E, R>(\n    self: Stream<A, E, R>\n  ) => Effect.Effect<Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>, never, Scope.Scope | R>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    options?: { readonly capacity?: number | undefined } | undefined\n  ): Effect.Effect<Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>, never, Scope.Scope | R>\n} = internal.toQueueOfElements\n\n/**\n * Converts the stream to a `ReadableStream`.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toReadableStream: {\n  <A>(\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ): <E>(\n    self: Stream<A, E>\n  ) => ReadableStream<A>\n  <A, E>(\n    self: Stream<A, E>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ): ReadableStream<A>\n} = internal.toReadableStream\n\n/**\n * Converts the stream to a `Effect<ReadableStream>`.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toReadableStreamEffect: {\n  <A>(\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ): <E, R>(\n    self: Stream<A, E, R>\n  ) => Effect.Effect<ReadableStream<A>, never, R>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ): Effect.Effect<ReadableStream<A>, never, R>\n} = internal.toReadableStreamEffect\n\n/**\n * Converts the stream to a `ReadableStream` using the provided runtime.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toReadableStreamRuntime: {\n  <A, XR>(\n    runtime: Runtime<XR>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ): <E, R extends XR>(self: Stream<A, E, R>) => ReadableStream<A>\n  <A, E, XR, R extends XR>(\n    self: Stream<A, E, R>,\n    runtime: Runtime<XR>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ): ReadableStream<A>\n} = internal.toReadableStreamRuntime\n\n/**\n * Converts the stream to a `AsyncIterable` using the provided runtime.\n *\n * @since 3.15.0\n * @category destructors\n */\nexport const toAsyncIterableRuntime: {\n  <A, XR>(runtime: Runtime<XR>): <E, R extends XR>(self: Stream<A, E, R>) => AsyncIterable<A>\n  <A, E, XR, R extends XR>(self: Stream<A, E, R>, runtime: Runtime<XR>): AsyncIterable<A>\n} = internal.toAsyncIterableRuntime\n\n/**\n * Converts the stream to a `AsyncIterable` capturing the required dependencies.\n *\n * @since 3.15.0\n * @category destructors\n */\nexport const toAsyncIterableEffect: <A, E, R>(self: Stream<A, E, R>) => Effect.Effect<AsyncIterable<A>, never, R> =\n  internal.toAsyncIterableEffect\n\n/**\n * Converts the stream to a `AsyncIterable`.\n *\n * @since 3.15.0\n * @category destructors\n */\nexport const toAsyncIterable: <A, E>(self: Stream<A, E>) => AsyncIterable<A> = internal.toAsyncIterable\n\n/**\n * Applies the transducer to the stream and emits its outputs.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const transduce: {\n  <A2, A, E2, R2>(sink: Sink.Sink<A2, A, A, E2, R2>): <E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, sink: Sink.Sink<A2, A, A, E2, R2>): Stream<A2, E | E2, R | R2>\n} = internal.transduce\n\n/**\n * Creates a stream by peeling off the \"layers\" of a value of type `S`.\n *\n * @example\n * ```ts\n * import { Effect, Option, Stream } from \"effect\"\n *\n * const stream = Stream.unfold(1, (n) => Option.some([n, n + 1]))\n *\n * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)\n * // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unfold: <S, A>(s: S, f: (s: S) => Option.Option<readonly [A, S]>) => Stream<A> = internal.unfold\n\n/**\n * Creates a stream by peeling off the \"layers\" of a value of type `S`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unfoldChunk: <S, A>(\n  s: S,\n  f: (s: S) => Option.Option<readonly [Chunk.Chunk<A>, S]>\n) => Stream<A> = internal.unfoldChunk\n\n/**\n * Creates a stream by effectfully peeling off the \"layers\" of a value of type\n * `S`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unfoldChunkEffect: <S, A, E, R>(\n  s: S,\n  f: (s: S) => Effect.Effect<Option.Option<readonly [Chunk.Chunk<A>, S]>, E, R>\n) => Stream<A, E, R> = internal.unfoldChunkEffect\n\n/**\n * Creates a stream by effectfully peeling off the \"layers\" of a value of type\n * `S`.\n *\n * @example\n * ```ts\n * import { Effect, Option, Random, Stream } from \"effect\"\n *\n * const stream = Stream.unfoldEffect(1, (n) =>\n *   Random.nextBoolean.pipe(\n *     Effect.map((b) => (b ? Option.some([n, -n]) : Option.some([n, n])))\n *   ))\n *\n * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log)\n * // { _id: 'Chunk', values: [ 1, -1, -1, -1, -1 ] }\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unfoldEffect: <S, A, E, R>(\n  s: S,\n  f: (s: S) => Effect.Effect<Option.Option<readonly [A, S]>, E, R>\n) => Stream<A, E, R> = internal.unfoldEffect\n\nconst void_: Stream<void> = internal.void\nexport {\n  /**\n   * A stream that contains a single `void` value.\n   *\n   * @example\n   * ```ts\n   * import { Effect, Stream } from \"effect\"\n   *\n   * const stream = Stream.void\n   *\n   * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n   * // { _id: 'Chunk', values: [ undefined ] }\n   *\n   * ```\n   * @since 2.0.0\n   * @category constructors\n   */\n  void_ as void\n}\n\n/**\n * Creates a stream produced from an `Effect`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unwrap: <A, E2, R2, E, R>(effect: Effect.Effect<Stream<A, E2, R2>, E, R>) => Stream<A, E | E2, R | R2> =\n  internal.unwrap\n\n/**\n * Creates a stream produced from a scoped `Effect`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unwrapScoped: <A, E2, R2, E, R>(\n  effect: Effect.Effect<Stream<A, E2, R2>, E, R>\n) => Stream<A, E | E2, R2 | Exclude<R, Scope.Scope>> = internal.unwrapScoped\n\n/**\n * Creates a stream produced from a function which receives a `Scope` and\n * returns an `Effect`. The resulting stream will emit a single element, which\n * will be the result of the returned effect, if successful.\n *\n * @since 3.11.0\n * @category constructors\n */\nexport const unwrapScopedWith: <A, E2, R2, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<Stream<A, E2, R2>, E, R>\n) => Stream<A, E | E2, R | R2> = internal.unwrapScopedWith\n\n/**\n * Updates the specified service within the context of the `Stream`.\n *\n * @since 2.0.0\n * @category context\n */\nexport const updateService: {\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    f: (service: NoInfer<S>) => NoInfer<S>\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, I | R>\n  <A, E, R, I, S>(\n    self: Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    f: (service: NoInfer<S>) => NoInfer<S>\n  ): Stream<A, E, I | R>\n} = internal.updateService\n\n/**\n * Returns the specified stream if the given condition is satisfied, otherwise\n * returns an empty stream.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const when: {\n  (test: LazyArg<boolean>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, R>\n  <A, E, R>(self: Stream<A, E, R>, test: LazyArg<boolean>): Stream<A, E, R>\n} = internal.when\n\n/**\n * Returns the resulting stream when the given `PartialFunction` is defined\n * for the given value, otherwise returns an empty stream.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const whenCase: <A, A2, E, R>(\n  evaluate: LazyArg<A>,\n  pf: (a: A) => Option.Option<Stream<A2, E, R>>\n) => Stream<A2, E, R> = internal.whenCase\n\n/**\n * Returns the stream when the given partial function is defined for the given\n * effectful value, otherwise returns an empty stream.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const whenCaseEffect: {\n  <A, A2, E2, R2>(\n    pf: (a: A) => Option.Option<Stream<A2, E2, R2>>\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    pf: (a: A) => Option.Option<Stream<A2, E2, R2>>\n  ): Stream<A2, E | E2, R | R2>\n} = internal.whenCaseEffect\n\n/**\n * Returns the stream if the given effectful condition is satisfied, otherwise\n * returns an empty stream.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const whenEffect: {\n  <E2, R2>(effect: Effect.Effect<boolean, E2, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(self: Stream<A, E, R>, effect: Effect.Effect<boolean, E2, R2>): Stream<A, E | E2, R | R2>\n} = internal.whenEffect\n\n/**\n * Wraps the stream with a new span for tracing.\n *\n * @since 2.0.0\n * @category tracing\n */\nexport const withSpan: {\n  (\n    name: string,\n    options?: Tracer.SpanOptions | undefined\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A, E, Exclude<R, Tracer.ParentSpan>>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    name: string,\n    options?: Tracer.SpanOptions | undefined\n  ): Stream<A, E, Exclude<R, Tracer.ParentSpan>>\n} = internal.withSpan\n\n/**\n * Zips this stream with another point-wise and emits tuples of elements from\n * both streams.\n *\n * The new stream will end when one of the sides ends.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * // We create two streams and zip them together.\n * const stream = Stream.zip(\n *   Stream.make(1, 2, 3, 4, 5, 6),\n *   Stream.make(\"a\", \"b\", \"c\")\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ [ 1, 'a' ], [ 2, 'b' ], [ 3, 'c' ] ] }\n * ```\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zip: {\n  <A2, E2, R2>(that: Stream<A2, E2, R2>): <A, E, R>(self: Stream<A, E, R>) => Stream<[A, A2], E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, that: Stream<A2, E2, R2>): Stream<[A, A2], E | E2, R | R2>\n} = internal.zip\n\n/**\n * Zips this stream with another point-wise and emits tuples of elements from\n * both streams.\n *\n * The new stream will end when one of the sides ends.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipFlatten: {\n  <A2, E2, R2>(\n    that: Stream<A2, E2, R2>\n  ): <A extends ReadonlyArray<any>, E, R>(self: Stream<A, E, R>) => Stream<[...A, A2], E2 | E, R2 | R>\n  <A extends ReadonlyArray<any>, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    that: Stream<A2, E2, R2>\n  ): Stream<[...A, A2], E | E2, R | R2>\n} = internal.zipFlatten\n\n/**\n * Zips this stream with another point-wise, creating a new stream of pairs of\n * elements from both sides.\n *\n * The defaults `defaultLeft` and `defaultRight` will be used if the streams\n * have different lengths and one of the streams has ended before the other.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.zipAll(Stream.make(1, 2, 3, 4, 5, 6), {\n *   other: Stream.make(\"a\", \"b\", \"c\"),\n *   defaultSelf: 0,\n *   defaultOther: \"x\"\n * })\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: \"Chunk\", values: [ [ 1, \"a\" ], [ 2, \"b\" ], [ 3, \"c\" ], [ 4, \"x\" ], [ 5, \"x\" ], [ 6, \"x\" ] ] }\n * ```\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipAll: {\n  <A2, E2, R2, A>(\n    options: { readonly other: Stream<A2, E2, R2>; readonly defaultSelf: A; readonly defaultOther: A2 }\n  ): <E, R>(self: Stream<A, E, R>) => Stream<[A, A2], E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Stream<A, E, R>,\n    options: { readonly other: Stream<A2, E2, R2>; readonly defaultSelf: A; readonly defaultOther: A2 }\n  ): Stream<[A, A2], E | E2, R | R2>\n} = internal.zipAll\n\n/**\n * Zips this stream with another point-wise, and keeps only elements from this\n * stream.\n *\n * The provided default value will be used if the other stream ends before\n * this one.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipAllLeft: {\n  <A2, E2, R2, A>(that: Stream<A2, E2, R2>, defaultLeft: A): <E, R>(self: Stream<A, E, R>) => Stream<A, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, that: Stream<A2, E2, R2>, defaultLeft: A): Stream<A, E | E2, R | R2>\n} = internal.zipAllLeft\n\n/**\n * Zips this stream with another point-wise, and keeps only elements from the\n * other stream.\n *\n * The provided default value will be used if this stream ends before the\n * other one.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipAllRight: {\n  <A2, E2, R2>(\n    that: Stream<A2, E2, R2>,\n    defaultRight: A2\n  ): <A, E, R>(self: Stream<A, E, R>) => Stream<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(self: Stream<A, E, R>, that: Stream<A2, E2, R2>, defaultRight: A2): Stream<A2, E | E2, R | R2>\n} = internal.zipAllRight\n\n/**\n * Zips this stream that is sorted by distinct keys and the specified stream\n * that is sorted by distinct keys to produce a new stream that is sorted by\n * distinct keys. Combines values associated with each key into a tuple,\n * using the specified values `defaultLeft` and `defaultRight` to fill in\n * missing values.\n *\n * This allows zipping potentially unbounded streams of data by key in\n * constant space but the caller is responsible for ensuring that the\n * streams are sorted by distinct keys.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipAllSortedByKey: {\n  <A2, E2, R2, A, K>(\n    options: {\n      readonly other: Stream<readonly [K, A2], E2, R2>\n      readonly defaultSelf: A\n      readonly defaultOther: A2\n      readonly order: Order.Order<K>\n    }\n  ): <E, R>(self: Stream<readonly [K, A], E, R>) => Stream<[K, [A, A2]], E2 | E, R2 | R>\n  <K, A, E, R, A2, E2, R2>(\n    self: Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream<readonly [K, A2], E2, R2>\n      readonly defaultSelf: A\n      readonly defaultOther: A2\n      readonly order: Order.Order<K>\n    }\n  ): Stream<[K, [A, A2]], E | E2, R | R2>\n} = internal.zipAllSortedByKey\n\n/**\n * Zips this stream that is sorted by distinct keys and the specified stream\n * that is sorted by distinct keys to produce a new stream that is sorted by\n * distinct keys. Keeps only values from this stream, using the specified\n * value `default` to fill in missing values.\n *\n * This allows zipping potentially unbounded streams of data by key in\n * constant space but the caller is responsible for ensuring that the\n * streams are sorted by distinct keys.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipAllSortedByKeyLeft: {\n  <A2, E2, R2, A, K>(\n    options: {\n      readonly other: Stream<readonly [K, A2], E2, R2>\n      readonly defaultSelf: A\n      readonly order: Order.Order<K>\n    }\n  ): <E, R>(self: Stream<readonly [K, A], E, R>) => Stream<[K, A], E2 | E, R2 | R>\n  <K, A, E, R, A2, E2, R2>(\n    self: Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream<readonly [K, A2], E2, R2>\n      readonly defaultSelf: A\n      readonly order: Order.Order<K>\n    }\n  ): Stream<[K, A], E | E2, R | R2>\n} = internal.zipAllSortedByKeyLeft\n\n/**\n * Zips this stream that is sorted by distinct keys and the specified stream\n * that is sorted by distinct keys to produce a new stream that is sorted by\n * distinct keys. Keeps only values from that stream, using the specified\n * value `default` to fill in missing values.\n *\n * This allows zipping potentially unbounded streams of data by key in\n * constant space but the caller is responsible for ensuring that the\n * streams are sorted by distinct keys.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipAllSortedByKeyRight: {\n  <K, A2, E2, R2>(\n    options: {\n      readonly other: Stream<readonly [K, A2], E2, R2>\n      readonly defaultOther: A2\n      readonly order: Order.Order<K>\n    }\n  ): <A, E, R>(self: Stream<readonly [K, A], E, R>) => Stream<[K, A2], E2 | E, R2 | R>\n  <A, E, R, K, A2, E2, R2>(\n    self: Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream<readonly [K, A2], E2, R2>\n      readonly defaultOther: A2\n      readonly order: Order.Order<K>\n    }\n  ): Stream<[K, A2], E | E2, R | R2>\n} = internal.zipAllSortedByKeyRight\n\n/**\n * Zips this stream that is sorted by distinct keys and the specified stream\n * that is sorted by distinct keys to produce a new stream that is sorted by\n * distinct keys. Uses the functions `left`, `right`, and `both` to handle\n * the cases where a key and value exist in this stream, that stream, or\n * both streams.\n *\n * This allows zipping potentially unbounded streams of data by key in\n * constant space but the caller is responsible for ensuring that the\n * streams are sorted by distinct keys.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipAllSortedByKeyWith: {\n  <K, A2, E2, R2, A, A3>(\n    options: {\n      readonly other: Stream<readonly [K, A2], E2, R2>\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A3\n      readonly onBoth: (a: A, a2: A2) => A3\n      readonly order: Order.Order<K>\n    }\n  ): <E, R>(self: Stream<readonly [K, A], E, R>) => Stream<[K, A3], E2 | E, R2 | R>\n  <K, A, E, R, A2, E2, R2, A3>(\n    self: Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream<readonly [K, A2], E2, R2>\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A3\n      readonly onBoth: (a: A, a2: A2) => A3\n      readonly order: Order.Order<K>\n    }\n  ): Stream<[K, A3], E | E2, R | R2>\n} = internal.zipAllSortedByKeyWith\n\n/**\n * Zips this stream with another point-wise. The provided functions will be\n * used to create elements for the composed stream.\n *\n * The functions `left` and `right` will be used if the streams have different\n * lengths and one of the streams has ended before the other.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.zipAllWith(Stream.make(1, 2, 3, 4, 5, 6), {\n *   other: Stream.make(\"a\", \"b\", \"c\"),\n *   onSelf: (n) => [n, \"x\"],\n *   onOther: (s) => [0, s],\n *   onBoth: (n, s) => [n - s.length, s]\n * })\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: \"Chunk\", values: [ [ 0, \"a\" ], [ 1, \"b\" ], [ 2, \"c\" ], [ 4, \"x\" ], [ 5, \"x\" ], [ 6, \"x\" ] ] }\n * ```\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipAllWith: {\n  <A2, E2, R2, A, A3>(\n    options: {\n      readonly other: Stream<A2, E2, R2>\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A3\n      readonly onBoth: (a: A, a2: A2) => A3\n    }\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A3, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2, A3>(\n    self: Stream<A, E, R>,\n    options: {\n      readonly other: Stream<A2, E2, R2>\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A3\n      readonly onBoth: (a: A, a2: A2) => A3\n    }\n  ): Stream<A3, E | E2, R | R2>\n} = internal.zipAllWith\n\n/**\n * Zips the two streams so that when a value is emitted by either of the two\n * streams, it is combined with the latest value from the other stream to\n * produce a result.\n *\n * Note: tracking the latest value is done on a per-chunk basis. That means\n * that emitted elements that are not the last value in chunks will never be\n * used for zipping.\n *\n * @example\n * ```ts\n * import { Effect, Schedule, Stream } from \"effect\"\n *\n * const s1 = Stream.make(1, 2, 3).pipe(\n *   Stream.schedule(Schedule.spaced(\"1 second\"))\n * )\n *\n * const s2 = Stream.make(\"a\", \"b\", \"c\", \"d\").pipe(\n *   Stream.schedule(Schedule.spaced(\"500 millis\"))\n * )\n *\n * const stream = Stream.zipLatest(s1, s2)\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: \"Chunk\", values: [ [ 1, \"a\" ], [ 1, \"b\" ], [ 2, \"b\" ], [ 2, \"c\" ], [ 2, \"d\" ], [ 3, \"d\" ] ] }\n * ```\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipLatest: {\n  <AR, ER, RR>(right: Stream<AR, ER, RR>): <AL, EL, RL>(left: Stream<AL, EL, RL>) => Stream<[AL, AR], EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR>(left: Stream<AL, EL, RL>, right: Stream<AR, ER, RR>): Stream<[AL, AR], EL | ER, RL | RR>\n} = internal.zipLatest\n\n/**\n * Zips multiple streams so that when a value is emitted by any of the streams,\n * it is combined with the latest values from the other streams to produce a result.\n *\n * Note: tracking the latest value is done on a per-chunk basis. That means\n * that emitted elements that are not the last value in chunks will never be\n * used for zipping.\n *\n * @example\n * ```ts\n * import { Stream, Schedule, Console, Effect } from \"effect\"\n *\n * const stream = Stream.zipLatestAll(\n *     Stream.fromSchedule(Schedule.spaced('1 millis')),\n *     Stream.fromSchedule(Schedule.spaced('2 millis')),\n *     Stream.fromSchedule(Schedule.spaced('4 millis')),\n * ).pipe(Stream.take(6), Stream.tap(Console.log))\n *\n * Effect.runPromise(Stream.runDrain(stream))\n * // Output:\n * // [ 0, 0, 0 ]\n * // [ 1, 0, 0 ]\n * // [ 1, 1, 0 ]\n * // [ 2, 1, 0 ]\n * // [ 3, 1, 0 ]\n * // [ 3, 1, 1 ]\n * // .....\n * ```\n *\n * @since 3.3.0\n * @category zipping\n */\nexport const zipLatestAll: <T extends ReadonlyArray<Stream<any, any, any>>>(\n  ...streams: T\n) => Stream<\n  [T[number]] extends [never] ? never\n    : { [K in keyof T]: T[K] extends Stream<infer A, infer _E, infer _R> ? A : never },\n  [T[number]] extends [never] ? never : T[number] extends Stream<infer _A, infer _E, infer _R> ? _E : never,\n  [T[number]] extends [never] ? never : T[number] extends Stream<infer _A, infer _E, infer _R> ? _R : never\n> = internal.zipLatestAll\n\n/**\n * Zips the two streams so that when a value is emitted by either of the two\n * streams, it is combined with the latest value from the other stream to\n * produce a result.\n *\n * Note: tracking the latest value is done on a per-chunk basis. That means\n * that emitted elements that are not the last value in chunks will never be\n * used for zipping.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipLatestWith: {\n  <AR, ER, RR, AL, A>(\n    right: Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): <EL, RL>(left: Stream<AL, EL, RL>) => Stream<A, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR, A>(\n    left: Stream<AL, EL, RL>,\n    right: Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): Stream<A, EL | ER, RL | RR>\n} = internal.zipLatestWith\n\n/**\n * Zips this stream with another point-wise, but keeps only the outputs of\n * `left` stream.\n *\n * The new stream will end when one of the sides ends.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipLeft: {\n  <AR, ER, RR>(right: Stream<AR, ER, RR>): <AL, EL, RL>(left: Stream<AL, EL, RL>) => Stream<AL, ER | EL, RR | RL>\n  <AL, EL, RL, AR, ER, RR>(left: Stream<AL, EL, RL>, right: Stream<AR, ER, RR>): Stream<AL, EL | ER, RL | RR>\n} = internal.zipLeft\n\n/**\n * Zips this stream with another point-wise, but keeps only the outputs of the\n * `right` stream.\n *\n * The new stream will end when one of the sides ends.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipRight: {\n  <AR, ER, RR>(right: Stream<AR, ER, RR>): <AL, EL, RL>(left: Stream<AL, EL, RL>) => Stream<AR, ER | EL, RR | RL>\n  <AL, EL, RL, AR, ER, RR>(left: Stream<AL, EL, RL>, right: Stream<AR, ER, RR>): Stream<AR, EL | ER, RL | RR>\n} = internal.zipRight\n\n/**\n * Zips this stream with another point-wise and applies the function to the\n * paired elements.\n *\n * The new stream will end when one of the sides ends.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * // We create two streams and zip them with custom logic.\n * const stream = Stream.zipWith(\n *   Stream.make(1, 2, 3, 4, 5, 6),\n *   Stream.make(\"a\", \"b\", \"c\"),\n *   (n, s) => [n - s.length, s]\n * )\n *\n * Effect.runPromise(Stream.runCollect(stream)).then(console.log)\n * // { _id: 'Chunk', values: [ [ 0, 'a' ], [ 1, 'b' ], [ 2, 'c' ] ] }\n * ```\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWith: {\n  <AR, ER, RR, AL, A>(\n    right: Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): <EL, RL>(left: Stream<AL, EL, RL>) => Stream<A, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR, A>(\n    left: Stream<AL, EL, RL>,\n    right: Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): Stream<A, EL | ER, RL | RR>\n} = internal.zipWith\n\n/**\n * Zips this stream with another point-wise and applies the function to the\n * paired elements.\n *\n * The new stream will end when one of the sides ends.\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWithChunks: {\n  <A2, E2, R2, A, A3>(\n    that: Stream<A2, E2, R2>,\n    f: (\n      left: Chunk.Chunk<A>,\n      right: Chunk.Chunk<A2>\n    ) => readonly [Chunk.Chunk<A3>, Either.Either<Chunk.Chunk<A2>, Chunk.Chunk<A>>]\n  ): <E, R>(self: Stream<A, E, R>) => Stream<A3, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2, A3>(\n    self: Stream<A, E, R>,\n    that: Stream<A2, E2, R2>,\n    f: (\n      left: Chunk.Chunk<A>,\n      right: Chunk.Chunk<A2>\n    ) => readonly [Chunk.Chunk<A3>, Either.Either<Chunk.Chunk<A2>, Chunk.Chunk<A>>]\n  ): Stream<A3, E | E2, R | R2>\n} = internal.zipWithChunks\n\n/**\n * Zips each element with the next element if present.\n *\n * @example\n * ```ts\n * import { Chunk, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.zipWithNext(Stream.make(1, 2, 3, 4))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then((chunk) => console.log(Chunk.toArray(chunk)))\n * // [\n * //   [ 1, { _id: 'Option', _tag: 'Some', value: 2 } ],\n * //   [ 2, { _id: 'Option', _tag: 'Some', value: 3 } ],\n * //   [ 3, { _id: 'Option', _tag: 'Some', value: 4 } ],\n * //   [ 4, { _id: 'Option', _tag: 'None' } ]\n * // ]\n * ```\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWithNext: <A, E, R>(self: Stream<A, E, R>) => Stream<[A, Option.Option<A>], E, R> = internal.zipWithNext\n\n/**\n * Zips each element with the previous element. Initially accompanied by\n * `None`.\n *\n * @example\n * ```ts\n * import { Chunk, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.zipWithPrevious(Stream.make(1, 2, 3, 4))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then((chunk) => console.log(Chunk.toArray(chunk)))\n * // [\n * //   [ { _id: 'Option', _tag: 'None' }, 1 ],\n * //   [ { _id: 'Option', _tag: 'Some', value: 1 }, 2 ],\n * //   [ { _id: 'Option', _tag: 'Some', value: 2 }, 3 ],\n * //   [ { _id: 'Option', _tag: 'Some', value: 3 }, 4 ]\n * // ]\n * ```\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWithPrevious: <A, E, R>(self: Stream<A, E, R>) => Stream<[Option.Option<A>, A], E, R> =\n  internal.zipWithPrevious\n\n/**\n * Zips each element with both the previous and next element.\n *\n * @example\n * ```ts\n * import { Chunk, Effect, Stream } from \"effect\"\n *\n * const stream = Stream.zipWithPreviousAndNext(Stream.make(1, 2, 3, 4))\n *\n * Effect.runPromise(Stream.runCollect(stream)).then((chunk) => console.log(Chunk.toArray(chunk)))\n * // [\n * //   [\n * //     { _id: 'Option', _tag: 'None' },\n * //     1,\n * //     { _id: 'Option', _tag: 'Some', value: 2 }\n * //   ],\n * //   [\n * //     { _id: 'Option', _tag: 'Some', value: 1 },\n * //     2,\n * //     { _id: 'Option', _tag: 'Some', value: 3 }\n * //   ],\n * //   [\n * //     { _id: 'Option', _tag: 'Some', value: 2 },\n * //     3,\n * //     { _id: 'Option', _tag: 'Some', value: 4 }\n * //   ],\n * //   [\n * //     { _id: 'Option', _tag: 'Some', value: 3 },\n * //     4,\n * //     { _id: 'Option', _tag: 'None' }\n * //   ]\n * // ]\n * ```\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWithPreviousAndNext: <A, E, R>(\n  self: Stream<A, E, R>\n) => Stream<[Option.Option<A>, A, Option.Option<A>], E, R> = internal.zipWithPreviousAndNext\n\n/**\n * Zips this stream together with the index of elements.\n *\n * @example\n * ```ts\n * import { Effect, Stream } from \"effect\"\n *\n * const stream = Stream.make(\"Mary\", \"James\", \"Robert\", \"Patricia\")\n *\n * const indexedStream = Stream.zipWithIndex(stream)\n *\n * Effect.runPromise(Stream.runCollect(indexedStream)).then(console.log)\n * // {\n * //   _id: 'Chunk',\n * //   values: [ [ 'Mary', 0 ], [ 'James', 1 ], [ 'Robert', 2 ], [ 'Patricia', 3 ] ]\n * // }\n * ```\n *\n * @since 2.0.0\n * @category zipping\n */\nexport const zipWithIndex: <A, E, R>(self: Stream<A, E, R>) => Stream<[A, number], E, R> = internal.zipWithIndex\n\n// -------------------------------------------------------------------------------------\n// do notation\n// -------------------------------------------------------------------------------------\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Stream` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Chunk, Effect, pipe, Stream } from \"effect\"\n *\n * const result = pipe(\n *   Stream.Do,\n *   Stream.bind(\"x\", () => Stream.succeed(2)),\n *   Stream.bind(\"y\", () => Stream.succeed(3)),\n *   Stream.let(\"sum\", ({ x, y }) => x + y)\n * )\n * assert.deepStrictEqual(Effect.runSync(Stream.runCollect(result)), Chunk.of({ x: 2, y: 3, sum: 5 }))\n * ```\n *\n * @see {@link bindTo}\n * @see {@link bind}\n * @see {@link bindEffect}\n * @see {@link let_ let}\n *\n * @category do notation\n * @since 2.0.0\n */\nexport const Do: Stream<{}> = internal.Do\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Stream` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Chunk, Effect, pipe, Stream } from \"effect\"\n *\n * const result = pipe(\n *   Stream.Do,\n *   Stream.bind(\"x\", () => Stream.succeed(2)),\n *   Stream.bind(\"y\", () => Stream.succeed(3)),\n *   Stream.let(\"sum\", ({ x, y }) => x + y)\n * )\n * assert.deepStrictEqual(Effect.runSync(Stream.runCollect(result)), Chunk.of({ x: 2, y: 3, sum: 5 }))\n * ```\n *\n * @see {@link Do}\n * @see {@link bindTo}\n * @see {@link bindEffect}\n * @see {@link let_ let}\n *\n * @category do notation\n * @since 2.0.0\n */\nexport const bind: {\n  <N extends string, A, B, E2, R2>(\n    tag: Exclude<N, keyof A>,\n    f: (_: NoInfer<A>) => Stream<B, E2, R2>,\n    options?:\n      | { readonly concurrency?: number | \"unbounded\" | undefined; readonly bufferSize?: number | undefined }\n      | undefined\n  ): <E, R>(self: Stream<A, E, R>) => Stream<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E2 | E, R2 | R>\n  <A, E, R, N extends string, B, E2, R2>(\n    self: Stream<A, E, R>,\n    tag: Exclude<N, keyof A>,\n    f: (_: NoInfer<A>) => Stream<B, E2, R2>,\n    options?:\n      | { readonly concurrency?: number | \"unbounded\" | undefined; readonly bufferSize?: number | undefined }\n      | undefined\n  ): Stream<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E | E2, R | R2>\n} = internal.bind\n\n/**\n * Binds an effectful value in a `do` scope\n *\n * @see {@link Do}\n * @see {@link bindTo}\n * @see {@link bind}\n * @see {@link let_ let}\n *\n * @since 2.0.0\n * @category do notation\n */\nexport const bindEffect: {\n  <N extends string, A, B, E2, R2>(\n    tag: Exclude<N, keyof A>,\n    f: (_: NoInfer<A>) => Effect.Effect<B, E2, R2>,\n    options?: { readonly concurrency?: number | \"unbounded\" | undefined; readonly bufferSize?: number | undefined }\n  ): <E, R>(self: Stream<A, E, R>) => Stream<{ [K in keyof A | N]: K extends keyof A ? A[K] : B }, E | E2, R | R2>\n  <A, E, R, N extends string, B, E2, R2>(\n    self: Stream<A, E, R>,\n    tag: Exclude<N, keyof A>,\n    f: (_: NoInfer<A>) => Effect.Effect<B, E2, R2>,\n    options?: { readonly concurrency?: number | \"unbounded\" | undefined; readonly unordered?: boolean | undefined }\n  ): Stream<{ [K in keyof A | N]: K extends keyof A ? A[K] : B }, E | E2, R | R2>\n} = groupBy_.bindEffect\n\n/**\n * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n *\n * Here's how the do simulation works:\n *\n * 1. Start the do simulation using the `Do` value\n * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Stream` values\n * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Chunk, Effect, pipe, Stream } from \"effect\"\n *\n * const result = pipe(\n *   Stream.Do,\n *   Stream.bind(\"x\", () => Stream.succeed(2)),\n *   Stream.bind(\"y\", () => Stream.succeed(3)),\n *   Stream.let(\"sum\", ({ x, y }) => x + y)\n * )\n * assert.deepStrictEqual(Effect.runSync(Stream.runCollect(result)), Chunk.of({ x: 2, y: 3, sum: 5 }))\n * ```\n *\n * @see {@link Do}\n * @see {@link bind}\n * @see {@link bindEffect}\n * @see {@link let_ let}\n *\n * @category do notation\n * @since 2.0.0\n */\nexport const bindTo: {\n  <N extends string>(name: N): <A, E, R>(self: Stream<A, E, R>) => Stream<{ [K in N]: A }, E, R>\n  <A, E, R, N extends string>(self: Stream<A, E, R>, name: N): Stream<{ [K in N]: A }, E, R>\n} = internal.bindTo\n\nconst let_: {\n  <N extends string, A extends object, B>(\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): <E, R>(self: Stream<A, E, R>) => Stream<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E, R>\n  <A extends object, E, R, N extends string, B>(\n    self: Stream<A, E, R>,\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): Stream<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E, R>\n} = internal.let_\n\nexport {\n  /**\n   * The \"do simulation\" in Effect allows you to write code in a more declarative style, similar to the \"do notation\" in other programming languages. It provides a way to define variables and perform operations on them using functions like `bind` and `let`.\n   *\n   * Here's how the do simulation works:\n   *\n   * 1. Start the do simulation using the `Do` value\n   * 2. Within the do simulation scope, you can use the `bind` function to define variables and bind them to `Stream` values\n   * 3. You can accumulate multiple `bind` statements to define multiple variables within the scope\n   * 4. Inside the do simulation scope, you can also use the `let` function to define variables and bind them to simple values\n   *\n   * @example\n   * ```ts\n   * import * as assert from \"node:assert\"\n   * import { Chunk, Effect, pipe, Stream } from \"effect\"\n   *\n   * const result = pipe(\n   *   Stream.Do,\n   *   Stream.bind(\"x\", () => Stream.succeed(2)),\n   *   Stream.bind(\"y\", () => Stream.succeed(3)),\n   *   Stream.let(\"sum\", ({ x, y }) => x + y)\n   * )\n   * assert.deepStrictEqual(Effect.runSync(Stream.runCollect(result)), Chunk.of({ x: 2, y: 3, sum: 5 }))\n   * ```\n   *\n   * @see {@link Do}\n   * @see {@link bindTo}\n   * @see {@link bind}\n   * @see {@link bindEffect}\n   *\n   * @category do notation\n   * @since 2.0.0\n   */\n  let_ as let\n}\n\n// -------------------------------------------------------------------------------------\n// encoding\n// -------------------------------------------------------------------------------------\n\n/**\n * Decode Uint8Array chunks into a stream of strings using the specified encoding.\n *\n * @since 2.0.0\n * @category encoding\n */\nexport const decodeText: {\n  (encoding?: string | undefined): <E, R>(self: Stream<Uint8Array, E, R>) => Stream<string, E, R>\n  <E, R>(self: Stream<Uint8Array, E, R>, encoding?: string | undefined): Stream<string, E, R>\n} = internal.decodeText\n\n/**\n * Encode a stream of strings into a stream of Uint8Array chunks using the specified encoding.\n *\n * @since 2.0.0\n * @category encoding\n */\nexport const encodeText: <E, R>(self: Stream<string, E, R>) => Stream<Uint8Array, E, R> = internal.encodeText\n\n/**\n * @since 3.4.0\n * @category models\n */\nexport interface EventListener<A> {\n  addEventListener(\n    event: string,\n    f: (event: A) => void,\n    options?: {\n      readonly capture?: boolean\n      readonly passive?: boolean\n      readonly once?: boolean\n      readonly signal?: AbortSignal\n    } | boolean\n  ): void\n  removeEventListener(\n    event: string,\n    f: (event: A) => void,\n    options?: {\n      readonly capture?: boolean\n    } | boolean\n  ): void\n}\n\n/**\n * Creates a `Stream` using addEventListener.\n * @since 3.1.0\n */\nexport const fromEventListener: <A = unknown>(\n  target: EventListener<A>,\n  type: string,\n  options?: boolean | {\n    readonly capture?: boolean\n    readonly passive?: boolean\n    readonly once?: boolean\n    readonly bufferSize?: number | \"unbounded\" | undefined\n  } | undefined\n) => Stream<A> = internal.fromEventListener\n"
  },
  {
    "path": "packages/effect/src/StreamEmit.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type * as Option from \"./Option.js\"\n\n/**\n * An `Emit<R, E, A, B>` represents an asynchronous callback that can be\n * called multiple times. The callback can be called with a value of type\n * `Effect<Chunk<A>, Option<E>, R>`, where succeeding with a `Chunk<A>`\n * indicates to emit those elements, failing with `Some<E>` indicates to\n * terminate with that error, and failing with `None` indicates to terminate\n * with an end of stream signal.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Emit<in R, in E, in A, out B> extends EmitOps<R, E, A, B> {\n  (f: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R>): Promise<B>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface EmitOps<in R, in E, in A, out B> {\n  /**\n   * Emits a chunk containing the specified values.\n   */\n  chunk(chunk: Chunk.Chunk<A>): Promise<B>\n\n  /**\n   * Terminates with a cause that dies with the specified defect.\n   */\n  die<Err>(defect: Err): Promise<B>\n\n  /**\n   * Terminates with a cause that dies with a `Throwable` with the specified\n   * message.\n   */\n  dieMessage(message: string): Promise<B>\n\n  /**\n   * Either emits the specified value if this `Exit` is a `Success` or else\n   * terminates with the specified cause if this `Exit` is a `Failure`.\n   */\n  done(exit: Exit.Exit<A, E>): Promise<B>\n\n  /**\n   * Terminates with an end of stream signal.\n   */\n  end(): Promise<B>\n\n  /**\n   * Terminates with the specified error.\n   */\n  fail(error: E): Promise<B>\n\n  /**\n   * Either emits the success value of this effect or terminates the stream\n   * with the failure value of this effect.\n   */\n  fromEffect(effect: Effect.Effect<A, E, R>): Promise<B>\n\n  /**\n   * Either emits the success value of this effect or terminates the stream\n   * with the failure value of this effect.\n   */\n  fromEffectChunk(effect: Effect.Effect<Chunk.Chunk<A>, E, R>): Promise<B>\n\n  /**\n   * Terminates the stream with the specified cause.\n   */\n  halt(cause: Cause.Cause<E>): Promise<B>\n\n  /**\n   * Emits a chunk containing the specified value.\n   */\n  single(value: A): Promise<B>\n}\n\n/**\n * @since 3.6.0\n * @category models\n */\nexport interface EmitOpsPush<in E, in A> {\n  /**\n   * Emits a chunk containing the specified values.\n   */\n  chunk(chunk: Chunk.Chunk<A>): boolean\n\n  /**\n   * Emits a chunk containing the specified values.\n   */\n  array(chunk: ReadonlyArray<A>): boolean\n\n  /**\n   * Terminates with a cause that dies with the specified defect.\n   */\n  die<Err>(defect: Err): void\n\n  /**\n   * Terminates with a cause that dies with a `Throwable` with the specified\n   * message.\n   */\n  dieMessage(message: string): void\n\n  /**\n   * Either emits the specified value if this `Exit` is a `Success` or else\n   * terminates with the specified cause if this `Exit` is a `Failure`.\n   */\n  done(exit: Exit.Exit<A, E>): void\n\n  /**\n   * Terminates with an end of stream signal.\n   */\n  end(): void\n\n  /**\n   * Terminates with the specified error.\n   */\n  fail(error: E): void\n\n  /**\n   * Terminates the stream with the specified cause.\n   */\n  halt(cause: Cause.Cause<E>): void\n\n  /**\n   * Emits a chunk containing the specified value.\n   */\n  single(value: A): boolean\n}\n"
  },
  {
    "path": "packages/effect/src/StreamHaltStrategy.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/stream/haltStrategy.js\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type HaltStrategy = Left | Right | Both | Either\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type HaltStrategyInput = HaltStrategy | \"left\" | \"right\" | \"both\" | \"either\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Left {\n  readonly _tag: \"Left\"\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Right {\n  readonly _tag: \"Right\"\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Both {\n  readonly _tag: \"Both\"\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Either {\n  readonly _tag: \"Either\"\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Left: HaltStrategy = internal.Left\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Right: HaltStrategy = internal.Right\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Both: HaltStrategy = internal.Both\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Either: HaltStrategy = internal.Either\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const fromInput: (input: HaltStrategyInput) => HaltStrategy = internal.fromInput\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isLeft: (self: HaltStrategy) => self is Left = internal.isLeft\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isRight: (self: HaltStrategy) => self is Right = internal.isRight\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isBoth: (self: HaltStrategy) => self is Both = internal.isBoth\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isEither: (self: HaltStrategy) => self is Either = internal.isEither\n\n/**\n * Folds over the specified `HaltStrategy` using the provided case functions.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <Z>(options: {\n    readonly onLeft: () => Z\n    readonly onRight: () => Z\n    readonly onBoth: () => Z\n    readonly onEither: () => Z\n  }): (self: HaltStrategy) => Z\n  <Z>(self: HaltStrategy, options: {\n    readonly onLeft: () => Z\n    readonly onRight: () => Z\n    readonly onBoth: () => Z\n    readonly onEither: () => Z\n  }): Z\n} = internal.match\n"
  },
  {
    "path": "packages/effect/src/Streamable.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport { pipeArguments } from \"./Pipeable.js\"\nimport * as Stream from \"./Stream.js\"\n\nconst streamVariance = {\n  /* c8 ignore next */\n  _R: (_: never) => _,\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _A: (_: never) => _\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport abstract class Class<A, E = never, R = never> implements Stream.Stream<A, E, R> {\n  /**\n   * @since 2.0.0\n   */\n  readonly [Stream.StreamTypeId] = streamVariance\n\n  /**\n   * @since 2.0.0\n   */\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  abstract toStream(): Stream.Stream<A, E, R>\n\n  /**\n   * @internal\n   */\n  get channel() {\n    return Stream.toChannel(this.toStream())\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/String.ts",
    "content": "/**\n * This module provides utility functions and type class instances for working with the `string` type in TypeScript.\n * It includes functions for basic string manipulation, as well as type class instances for\n * `Equivalence` and `Order`.\n *\n * @since 2.0.0\n */\n\nimport type { NonEmptyArray } from \"./Array.js\"\nimport * as equivalence from \"./Equivalence.js\"\nimport { dual } from \"./Function.js\"\nimport * as readonlyArray from \"./internal/array.js\"\nimport * as number from \"./Number.js\"\nimport * as Option from \"./Option.js\"\nimport * as order from \"./Order.js\"\nimport type * as Ordering from \"./Ordering.js\"\nimport type { Refinement } from \"./Predicate.js\"\nimport * as predicate from \"./Predicate.js\"\n\n/**\n * Tests if a value is a `string`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { String } from \"effect\"\n *\n * assert.deepStrictEqual(String.isString(\"a\"), true)\n * assert.deepStrictEqual(String.isString(1), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isString: Refinement<unknown, string> = predicate.isString\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence: equivalence.Equivalence<string> = equivalence.string\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Order: order.Order<string> = order.string\n\n/**\n * The empty string `\"\"`.\n *\n * @since 2.0.0\n */\nexport const empty: \"\" = \"\" as const\n\n/**\n * Concatenates two strings at the type level.\n *\n * @since 2.0.0\n */\nexport type Concat<A extends string, B extends string> = `${A}${B}`\n\n/**\n * Concatenates two strings at runtime.\n *\n * @since 2.0.0\n */\nexport const concat: {\n  <B extends string>(that: B): <A extends string>(self: A) => Concat<A, B>\n  <A extends string, B extends string>(self: A, that: B): Concat<A, B>\n} = dual(2, (self: string, that: string): string => self + that)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe('a', String.toUpperCase), 'A')\n * ```\n *\n * @since 2.0.0\n */\nexport const toUpperCase = <S extends string>(self: S): Uppercase<S> => self.toUpperCase() as Uppercase<S>\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe('A', String.toLowerCase), 'a')\n * ```\n *\n * @since 2.0.0\n */\nexport const toLowerCase = <T extends string>(self: T): Lowercase<T> => self.toLowerCase() as Lowercase<T>\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe('abc', String.capitalize), 'Abc')\n * ```\n *\n * @since 2.0.0\n */\nexport const capitalize = <T extends string>(self: T): Capitalize<T> => {\n  if (self.length === 0) return self as Capitalize<T>\n\n  return (toUpperCase(self[0]) + self.slice(1)) as Capitalize<T>\n}\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe('ABC', String.uncapitalize), 'aBC')\n * ```\n *\n * @since 2.0.0\n */\nexport const uncapitalize = <T extends string>(self: T): Uncapitalize<T> => {\n  if (self.length === 0) return self as Uncapitalize<T>\n\n  return (toLowerCase(self[0]) + self.slice(1)) as Uncapitalize<T>\n}\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe('abc', String.replace('b', 'd')), 'adc')\n * ```\n *\n * @since 2.0.0\n */\nexport const replace = (searchValue: string | RegExp, replaceValue: string) => (self: string): string =>\n  self.replace(searchValue, replaceValue)\n\n/**\n * @since 2.0.0\n */\nexport type Trim<A extends string> = TrimEnd<TrimStart<A>>\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { String } from \"effect\"\n *\n * assert.deepStrictEqual(String.trim(' a '), 'a')\n * ```\n *\n * @since 2.0.0\n */\nexport const trim = <A extends string>(self: A): Trim<A> => self.trim() as Trim<A>\n\n/**\n * @since 2.0.0\n */\nexport type TrimStart<A extends string> = A extends `${\" \" | \"\\n\" | \"\\t\" | \"\\r\"}${infer B}` ? TrimStart<B> : A\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { String } from \"effect\"\n *\n * assert.deepStrictEqual(String.trimStart(' a '), 'a ')\n * ```\n *\n * @since 2.0.0\n */\nexport const trimStart = <A extends string>(self: A): TrimStart<A> => self.trimStart() as TrimStart<A>\n\n/**\n * @since 2.0.0\n */\nexport type TrimEnd<A extends string> = A extends `${infer B}${\" \" | \"\\n\" | \"\\t\" | \"\\r\"}` ? TrimEnd<B> : A\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { String } from \"effect\"\n *\n * assert.deepStrictEqual(String.trimEnd(' a '), ' a')\n * ```\n *\n * @since 2.0.0\n */\nexport const trimEnd = <A extends string>(self: A): TrimEnd<A> => self.trimEnd() as TrimEnd<A>\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe('abcd', String.slice(1, 3)), 'bc')\n * ```\n *\n * @since 2.0.0\n */\nexport const slice = (start?: number, end?: number) => (self: string): string => self.slice(start, end)\n\n/**\n * Test whether a `string` is empty.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { String } from \"effect\"\n *\n * assert.deepStrictEqual(String.isEmpty(''), true)\n * assert.deepStrictEqual(String.isEmpty('a'), false)\n * ```\n *\n * @since 2.0.0\n */\nexport const isEmpty = (self: string): self is \"\" => self.length === 0\n\n/**\n * Test whether a `string` is non empty.\n *\n * @since 2.0.0\n */\nexport const isNonEmpty = (self: string): boolean => self.length > 0\n\n/**\n * Calculate the number of characters in a `string`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { String } from \"effect\"\n *\n * assert.deepStrictEqual(String.length('abc'), 3)\n * ```\n *\n * @since 2.0.0\n */\nexport const length = (self: string): number => self.length\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe('abc', String.split('')), ['a', 'b', 'c'])\n * assert.deepStrictEqual(pipe('', String.split('')), [''])\n * ```\n *\n * @since 2.0.0\n */\nexport const split: {\n  (separator: string | RegExp): (self: string) => NonEmptyArray<string>\n  (self: string, separator: string | RegExp): NonEmptyArray<string>\n} = dual(2, (self: string, separator: string | RegExp): NonEmptyArray<string> => {\n  const out = self.split(separator)\n  return readonlyArray.isNonEmptyArray(out) ? out : [self]\n})\n\n/**\n * Returns `true` if `searchString` appears as a substring of `self`, at one or more positions that are\n * greater than or equal to `position`; otherwise, returns `false`.\n *\n * @since 2.0.0\n */\nexport const includes = (searchString: string, position?: number) => (self: string): boolean =>\n  self.includes(searchString, position)\n\n/**\n * @since 2.0.0\n */\nexport const startsWith = (searchString: string, position?: number) => (self: string): boolean =>\n  self.startsWith(searchString, position)\n\n/**\n * @since 2.0.0\n */\nexport const endsWith = (searchString: string, position?: number) => (self: string): boolean =>\n  self.endsWith(searchString, position)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String, Option } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"abc\", String.charCodeAt(1)), Option.some(98))\n * assert.deepStrictEqual(pipe(\"abc\", String.charCodeAt(4)), Option.none())\n * ```\n *\n * @since 2.0.0\n */\nexport const charCodeAt: {\n  (index: number): (self: string) => Option.Option<number>\n  (self: string, index: number): Option.Option<number>\n} = dual(\n  2,\n  (self: string, index: number): Option.Option<number> =>\n    Option.filter(Option.some(self.charCodeAt(index)), (charCode) => !isNaN(charCode))\n)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String, Option } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"abcd\", String.substring(1)), \"bcd\")\n * assert.deepStrictEqual(pipe(\"abcd\", String.substring(1, 3)), \"bc\")\n * ```\n *\n * @since 2.0.0\n */\nexport const substring = (start: number, end?: number) => (self: string): string => self.substring(start, end)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String, Option } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"abc\", String.at(1)), Option.some(\"b\"))\n * assert.deepStrictEqual(pipe(\"abc\", String.at(4)), Option.none())\n * ```\n *\n * @since 2.0.0\n */\nexport const at: {\n  (index: number): (self: string) => Option.Option<string>\n  (self: string, index: number): Option.Option<string>\n} = dual(2, (self: string, index: number): Option.Option<string> => Option.fromNullable(self.at(index)))\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String, Option } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"abc\", String.charAt(1)), Option.some(\"b\"))\n * assert.deepStrictEqual(pipe(\"abc\", String.charAt(4)), Option.none())\n * ```\n *\n * @since 2.0.0\n */\nexport const charAt: {\n  (index: number): (self: string) => Option.Option<string>\n  (self: string, index: number): Option.Option<string>\n} = dual(\n  2,\n  (self: string, index: number): Option.Option<string> => Option.filter(Option.some(self.charAt(index)), isNonEmpty)\n)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String, Option } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"abc\", String.codePointAt(1)), Option.some(98))\n * ```\n *\n * @since 2.0.0\n */\nexport const codePointAt: {\n  (index: number): (self: string) => Option.Option<number>\n  (self: string, index: number): Option.Option<number>\n} = dual(2, (self: string, index: number): Option.Option<number> => Option.fromNullable(self.codePointAt(index)))\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String, Option } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"abbbc\", String.indexOf(\"b\")), Option.some(1))\n * ```\n *\n * @since 2.0.0\n */\nexport const indexOf = (searchString: string) => (self: string): Option.Option<number> =>\n  Option.filter(Option.some(self.indexOf(searchString)), number.greaterThanOrEqualTo(0))\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String, Option } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"abbbc\", String.lastIndexOf(\"b\")), Option.some(3))\n * assert.deepStrictEqual(pipe(\"abbbc\", String.lastIndexOf(\"d\")), Option.none())\n * ```\n *\n * @since 2.0.0\n */\nexport const lastIndexOf = (searchString: string) => (self: string): Option.Option<number> =>\n  Option.filter(Option.some(self.lastIndexOf(searchString)), number.greaterThanOrEqualTo(0))\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"a\", String.localeCompare(\"b\")), -1)\n * assert.deepStrictEqual(pipe(\"b\", String.localeCompare(\"a\")), 1)\n * assert.deepStrictEqual(pipe(\"a\", String.localeCompare(\"a\")), 0)\n * ```\n *\n * @since 2.0.0\n */\nexport const localeCompare =\n  (that: string, locales?: Intl.LocalesArgument, options?: Intl.CollatorOptions) => (self: string): Ordering.Ordering =>\n    number.sign(self.localeCompare(that, locales, options))\n\n/**\n * It is the `pipe`-able version of the native `match` method.\n *\n * @since 2.0.0\n */\nexport const match = (regexp: RegExp | string) => (self: string): Option.Option<RegExpMatchArray> =>\n  Option.fromNullable(self.match(regexp))\n\n/**\n * It is the `pipe`-able version of the native `matchAll` method.\n *\n * @since 2.0.0\n */\nexport const matchAll = (regexp: RegExp) => (self: string): IterableIterator<RegExpMatchArray> => self.matchAll(regexp)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * const str = \"\\u1E9B\\u0323\";\n * assert.deepStrictEqual(pipe(str, String.normalize()), \"\\u1E9B\\u0323\")\n * assert.deepStrictEqual(pipe(str, String.normalize(\"NFC\")), \"\\u1E9B\\u0323\")\n * assert.deepStrictEqual(pipe(str, String.normalize(\"NFD\")), \"\\u017F\\u0323\\u0307\")\n * assert.deepStrictEqual(pipe(str, String.normalize(\"NFKC\")), \"\\u1E69\")\n * assert.deepStrictEqual(pipe(str, String.normalize(\"NFKD\")), \"\\u0073\\u0323\\u0307\")\n * ```\n *\n * @since 2.0.0\n */\nexport const normalize = (form?: \"NFC\" | \"NFD\" | \"NFKC\" | \"NFKD\") => (self: string): string => self.normalize(form)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"a\", String.padEnd(5)), \"a    \")\n * assert.deepStrictEqual(pipe(\"a\", String.padEnd(5, \"_\")), \"a____\")\n * ```\n *\n * @since 2.0.0\n */\nexport const padEnd = (maxLength: number, fillString?: string) => (self: string): string =>\n  self.padEnd(maxLength, fillString)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"a\", String.padStart(5)), \"    a\")\n * assert.deepStrictEqual(pipe(\"a\", String.padStart(5, \"_\")), \"____a\")\n * ```\n *\n * @since 2.0.0\n */\nexport const padStart = (maxLength: number, fillString?: string) => (self: string): string =>\n  self.padStart(maxLength, fillString)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"a\", String.repeat(5)), \"aaaaa\")\n * ```\n *\n * @since 2.0.0\n */\nexport const repeat = (count: number) => (self: string): string => self.repeat(count)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"ababb\", String.replaceAll(\"b\", \"c\")), \"acacc\")\n * assert.deepStrictEqual(pipe(\"ababb\", String.replaceAll(/ba/g, \"cc\")), \"accbb\")\n * ```\n *\n * @since 2.0.0\n */\nexport const replaceAll = (searchValue: string | RegExp, replaceValue: string) => (self: string): string =>\n  self.replaceAll(searchValue, replaceValue)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String, Option } from \"effect\"\n *\n * assert.deepStrictEqual(pipe(\"ababb\", String.search(\"b\")), Option.some(1))\n * assert.deepStrictEqual(pipe(\"ababb\", String.search(/abb/)), Option.some(2))\n * assert.deepStrictEqual(pipe(\"ababb\", String.search(\"d\")), Option.none())\n * ```\n *\n * @since 2.0.0\n */\nexport const search: {\n  (regexp: RegExp | string): (self: string) => Option.Option<number>\n  (self: string, regexp: RegExp | string): Option.Option<number>\n} = dual(\n  2,\n  (self: string, regexp: RegExp | string): Option.Option<number> =>\n    Option.filter(Option.some(self.search(regexp)), number.greaterThanOrEqualTo(0))\n)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * const str = \"\\u0130\"\n * assert.deepStrictEqual(pipe(str, String.toLocaleLowerCase(\"tr\")), \"i\")\n * ```\n *\n * @since 2.0.0\n */\nexport const toLocaleLowerCase = (locale?: Intl.LocalesArgument) => (self: string): string =>\n  self.toLocaleLowerCase(locale)\n\n/**\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, String } from \"effect\"\n *\n * const str = \"i\\u0307\"\n * assert.deepStrictEqual(pipe(str, String.toLocaleUpperCase(\"lt-LT\")), \"I\")\n * ```\n *\n * @since 2.0.0\n */\nexport const toLocaleUpperCase = (locale?: Intl.LocalesArgument) => (self: string): string =>\n  self.toLocaleUpperCase(locale)\n\n/**\n * Keep the specified number of characters from the start of a string.\n *\n * If `n` is larger than the available number of characters, the string will\n * be returned whole.\n *\n * If `n` is not a positive number, an empty string will be returned.\n *\n * If `n` is a float, it will be rounded down to the nearest integer.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { String } from \"effect\"\n *\n * assert.deepStrictEqual(String.takeLeft(\"Hello World\", 5), \"Hello\")\n * ```\n *\n * @since 2.0.0\n */\nexport const takeLeft: {\n  (n: number): (self: string) => string\n  (self: string, n: number): string\n} = dual(2, (self: string, n: number): string => self.slice(0, Math.max(n, 0)))\n\n/**\n * Keep the specified number of characters from the end of a string.\n *\n * If `n` is larger than the available number of characters, the string will\n * be returned whole.\n *\n * If `n` is not a positive number, an empty string will be returned.\n *\n * If `n` is a float, it will be rounded down to the nearest integer.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { String } from \"effect\"\n *\n * assert.deepStrictEqual(String.takeRight(\"Hello World\", 5), \"World\")\n * ```\n *\n * @since 2.0.0\n */\nexport const takeRight: {\n  (n: number): (self: string) => string\n  (self: string, n: number): string\n} = dual(\n  2,\n  (self: string, n: number): string => self.slice(Math.max(0, self.length - Math.floor(n)), Infinity)\n)\n\nconst CR = 0x0d\nconst LF = 0x0a\n\n/**\n * Returns an `IterableIterator` which yields each line contained within the\n * string, trimming off the trailing newline character.\n *\n * @since 2.0.0\n */\nexport const linesIterator = (self: string): LinesIterator => linesSeparated(self, true)\n\n/**\n * Returns an `IterableIterator` which yields each line contained within the\n * string as well as the trailing newline character.\n *\n * @since 2.0.0\n */\nexport const linesWithSeparators = (s: string): LinesIterator => linesSeparated(s, false)\n\n/**\n * For every line in this string, strip a leading prefix consisting of blanks\n * or control characters followed by the character specified by `marginChar`\n * from the line.\n *\n * @since 2.0.0\n */\nexport const stripMarginWith: {\n  (marginChar: string): (self: string) => string\n  (self: string, marginChar: string): string\n} = dual(2, (self: string, marginChar: string): string => {\n  let out = \"\"\n\n  for (const line of linesWithSeparators(self)) {\n    let index = 0\n\n    while (index < line.length && line.charAt(index) <= \" \") {\n      index = index + 1\n    }\n\n    const stripped = index < line.length && line.charAt(index) === marginChar\n      ? line.substring(index + 1)\n      : line\n\n    out = out + stripped\n  }\n\n  return out\n})\n\n/**\n * For every line in this string, strip a leading prefix consisting of blanks\n * or control characters followed by the `\"|\"` character from the line.\n *\n * @since 2.0.0\n */\nexport const stripMargin = (self: string): string => stripMarginWith(self, \"|\")\n\n/**\n * @since 2.0.0\n */\nexport const snakeToCamel = (self: string): string => {\n  let str = self[0]\n  for (let i = 1; i < self.length; i++) {\n    str += self[i] === \"_\" ? self[++i].toUpperCase() : self[i]\n  }\n  return str\n}\n\n/**\n * @since 2.0.0\n */\nexport const snakeToPascal = (self: string): string => {\n  let str = self[0].toUpperCase()\n  for (let i = 1; i < self.length; i++) {\n    str += self[i] === \"_\" ? self[++i].toUpperCase() : self[i]\n  }\n  return str\n}\n\n/**\n * @since 2.0.0\n */\nexport const snakeToKebab = (self: string): string => self.replace(/_/g, \"-\")\n\n/**\n * @since 2.0.0\n */\nexport const camelToSnake = (self: string): string => self.replace(/([A-Z])/g, \"_$1\").toLowerCase()\n\n/**\n * @since 2.0.0\n */\nexport const pascalToSnake = (self: string): string =>\n  (self.slice(0, 1) + self.slice(1).replace(/([A-Z])/g, \"_$1\")).toLowerCase()\n\n/**\n * @since 2.0.0\n */\nexport const kebabToSnake = (self: string): string => self.replace(/-/g, \"_\")\n\nclass LinesIterator implements IterableIterator<string> {\n  private index: number\n  private readonly length: number\n\n  constructor(readonly s: string, readonly stripped: boolean = false) {\n    this.index = 0\n    this.length = s.length\n  }\n\n  next(): IteratorResult<string> {\n    if (this.done) {\n      return { done: true, value: undefined }\n    }\n    const start = this.index\n    while (!this.done && !isLineBreak(this.s[this.index]!)) {\n      this.index = this.index + 1\n    }\n    let end = this.index\n    if (!this.done) {\n      const char = this.s[this.index]!\n      this.index = this.index + 1\n      if (!this.done && isLineBreak2(char, this.s[this.index]!)) {\n        this.index = this.index + 1\n      }\n      if (!this.stripped) {\n        end = this.index\n      }\n    }\n    return { done: false, value: this.s.substring(start, end) }\n  }\n\n  [Symbol.iterator](): IterableIterator<string> {\n    return new LinesIterator(this.s, this.stripped)\n  }\n\n  private get done(): boolean {\n    return this.index >= this.length\n  }\n}\n\n/**\n * Test if the provided character is a line break character (i.e. either `\"\\r\"`\n * or `\"\\n\"`).\n */\nconst isLineBreak = (char: string): boolean => {\n  const code = char.charCodeAt(0)\n  return code === CR || code === LF\n}\n\n/**\n * Test if the provided characters combine to form a carriage return/line-feed\n * (i.e. `\"\\r\\n\"`).\n */\nconst isLineBreak2 = (char0: string, char1: string): boolean => char0.charCodeAt(0) === CR && char1.charCodeAt(0) === LF\n\nconst linesSeparated = (self: string, stripped: boolean): LinesIterator => new LinesIterator(self, stripped)\n"
  },
  {
    "path": "packages/effect/src/Struct.ts",
    "content": "/**\n * This module provides utility functions for working with structs in TypeScript.\n *\n * @since 2.0.0\n */\n\nimport * as Equivalence from \"./Equivalence.js\"\nimport { dual } from \"./Function.js\"\nimport * as order from \"./Order.js\"\nimport * as Predicate from \"./Predicate.js\"\nimport type { MatchRecord, Simplify } from \"./Types.js\"\n\n/**\n * Create a new object by picking properties of an existing object.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, Struct } from \"effect\"\n *\n * assert.deepStrictEqual(pipe({ a: \"a\", b: 1, c: true }, Struct.pick(\"a\", \"b\")), { a: \"a\", b: 1 })\n * assert.deepStrictEqual(Struct.pick({ a: \"a\", b: 1, c: true }, \"a\", \"b\"), { a: \"a\", b: 1 })\n * ```\n *\n * @since 2.0.0\n */\nexport const pick: {\n  <Keys extends Array<PropertyKey>>(\n    ...keys: Keys\n  ): <S extends { [K in Keys[number]]?: any }>(\n    s: S\n  ) => MatchRecord<S, { [K in Keys[number]]?: S[K] }, Simplify<Pick<S, Keys[number]>>>\n  <S extends object, Keys extends Array<keyof S>>(\n    s: S,\n    ...keys: Keys\n  ): MatchRecord<S, { [K in Keys[number]]?: S[K] }, Simplify<Pick<S, Keys[number]>>>\n} = dual(\n  (args) => Predicate.isObject(args[0]),\n  <S extends object, Keys extends Array<keyof S>>(s: S, ...keys: Keys) => {\n    const out: any = {}\n    for (const k of keys) {\n      if (k in s) {\n        out[k] = (s as any)[k]\n      }\n    }\n    return out\n  }\n)\n\n/**\n * Create a new object by omitting properties of an existing object.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, Struct } from \"effect\"\n *\n * assert.deepStrictEqual(pipe({ a: \"a\", b: 1, c: true }, Struct.omit(\"c\")), { a: \"a\", b: 1 })\n * assert.deepStrictEqual(Struct.omit({ a: \"a\", b: 1, c: true }, \"c\"), { a: \"a\", b: 1 })\n * ```\n *\n * @since 2.0.0\n */\nexport const omit: {\n  <Keys extends Array<PropertyKey>>(\n    ...keys: Keys\n  ): <S extends { [K in Keys[number]]?: any }>(s: S) => Simplify<Omit<S, Keys[number]>>\n  <S extends object, Keys extends Array<keyof S>>(\n    s: S,\n    ...keys: Keys\n  ): Simplify<Omit<S, Keys[number]>>\n} = dual(\n  (args) => Predicate.isObject(args[0]),\n  <S extends object, Keys extends Array<keyof S>>(s: S, ...keys: Keys) => {\n    const out: any = { ...s }\n    for (const k of keys) {\n      delete out[k]\n    }\n    return out\n  }\n)\n\n/**\n * Given a struct of `Equivalence`s returns a new `Equivalence` that compares values of a struct\n * by applying each `Equivalence` to the corresponding property of the struct.\n *\n * Alias of {@link Equivalence.struct}.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Struct, String, Number } from \"effect\"\n *\n * const PersonEquivalence = Struct.getEquivalence({\n *   name: String.Equivalence,\n *   age: Number.Equivalence\n * })\n *\n * assert.deepStrictEqual(\n *   PersonEquivalence({ name: \"John\", age: 25 }, { name: \"John\", age: 25 }),\n *   true\n * )\n * assert.deepStrictEqual(\n *   PersonEquivalence({ name: \"John\", age: 25 }, { name: \"John\", age: 40 }),\n *   false\n * )\n * ```\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const getEquivalence: <R extends Record<string, Equivalence.Equivalence<any>>>(\n  isEquivalents: R\n) => Equivalence.Equivalence<\n  { readonly [K in keyof R]: [R[K]] extends [Equivalence.Equivalence<infer A>] ? A : never }\n> = Equivalence.struct\n\n/**\n * This function creates and returns a new `Order` for a struct of values based on the given `Order`s\n * for each property in the struct.\n *\n * Alias of {@link order.struct}.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const getOrder: <R extends { readonly [x: string]: order.Order<any> }>(\n  fields: R\n) => order.Order<{ [K in keyof R]: [R[K]] extends [order.Order<infer A>] ? A : never }> = order.struct\n\ntype Transformed<O, T> =\n  & unknown\n  & {\n    [K in keyof O]: K extends keyof T ? (T[K] extends (...a: any) => any ? ReturnType<T[K]> : O[K]) : O[K]\n  }\ntype PartialTransform<O, T> = {\n  [K in keyof T]: T[K] extends (a: O[K & keyof O]) => any ? T[K] : (a: O[K & keyof O]) => unknown\n}\n/**\n * Transforms the values of a Struct provided a transformation function for each key.\n * If no transformation function is provided for a key, it will return the original value for that key.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, Struct } from \"effect\"\n *\n * assert.deepStrictEqual(\n *   pipe(\n *     { a: 'a', b: 1, c: 3 },\n *     Struct.evolve({\n *       a: (a) => a.length,\n *       b: (b) => b * 2\n *     })\n *   ),\n *   { a: 1, b: 2, c: 3 }\n * )\n * ```\n *\n * @since 2.0.0\n */\nexport const evolve: {\n  <O, T>(t: PartialTransform<O, T>): (obj: O) => Transformed<O, T>\n  <O, T>(obj: O, t: PartialTransform<O, T>): Transformed<O, T>\n} = dual(\n  2,\n  <O, T>(obj: O, t: PartialTransform<O, T>): Transformed<O, T> => {\n    const out = { ...obj }\n    for (const k in t) {\n      if (Object.prototype.hasOwnProperty.call(obj, k)) {\n        // @ts-expect-error\n        out[k] = t[k](obj[k])\n      }\n    }\n    return out as any\n  }\n)\n\n/**\n * Retrieves the value associated with the specified key from a struct.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, Struct } from \"effect\"\n *\n * const value = pipe({ a: 1, b: 2 }, Struct.get(\"a\"))\n *\n * assert.deepStrictEqual(value, 1)\n * ```\n *\n * @since 2.0.0\n */\nexport const get =\n  <K extends PropertyKey>(key: K) => <S extends { [P in K]?: any }>(s: S): MatchRecord<S, S[K] | undefined, S[K]> =>\n    s[key]\n\n/**\n * Retrieves the object keys that are strings in a typed manner\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Struct } from \"effect\"\n *\n * const symbol: unique symbol = Symbol()\n *\n * const value = {\n *   a: 1,\n *   b: 2,\n *   [symbol]: 3\n * }\n *\n * const keys: Array<\"a\" | \"b\"> = Struct.keys(value)\n *\n * assert.deepStrictEqual(keys, [\"a\", \"b\"])\n * ```\n *\n * @since 3.6.0\n */\nexport const keys = <T extends {}>(o: T): Array<(keyof T) & string> => Object.keys(o) as Array<(keyof T) & string>\n\n/**\n * Retrieves the entries (key-value pairs) of an object, where keys are strings,\n * in a type-safe manner. Symbol keys are excluded from the result.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Struct } from \"effect\"\n *\n * const c = Symbol(\"c\")\n * const value = { a: \"foo\", b: 1, [c]: true }\n *\n * const entries: Array<[\"a\" | \"b\", string | number]> = Struct.entries(value)\n *\n * assert.deepStrictEqual(entries, [[\"a\", \"foo\"], [\"b\", 1]])\n * ```\n *\n * @since 3.17.0\n */\nexport const entries = <const R>(obj: R): Array<[keyof R & string, R[keyof R & string]]> =>\n  Object.entries(obj as any) as any\n"
  },
  {
    "path": "packages/effect/src/Subscribable.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Effect from \"./Effect.js\"\nimport { dual } from \"./Function.js\"\nimport { pipeArguments } from \"./Pipeable.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport * as Readable from \"./Readable.js\"\nimport * as Stream from \"./Stream.js\"\nimport type { NoInfer } from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"effect/Subscribable\")\n\n/**\n * @since 2.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Subscribable<A, E = never, R = never> extends Readable.Readable<A, E, R> {\n  readonly [TypeId]: TypeId\n  readonly changes: Stream.Stream<A, E, R>\n}\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isSubscribable = (u: unknown): u is Subscribable<unknown, unknown, unknown> => hasProperty(u, TypeId)\n\nconst Proto: Omit<Subscribable<any>, \"get\" | \"changes\"> = {\n  [Readable.TypeId]: Readable.TypeId,\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make = <A, E, R>(options: {\n  readonly get: Effect.Effect<A, E, R>\n  readonly changes: Stream.Stream<A, E, R>\n}): Subscribable<A, E, R> => Object.assign(Object.create(Proto), options)\n\n/**\n * @since 2.0.0\n * @category combinators\n */\nexport const map: {\n  <A, B>(f: (a: NoInfer<A>) => B): <E, R>(fa: Subscribable<A, E, R>) => Subscribable<B, E, R>\n  <A, E, R, B>(self: Subscribable<A, E, R>, f: (a: NoInfer<A>) => B): Subscribable<B, E, R>\n} = dual(2, <A, E, R, B>(self: Subscribable<A, E, R>, f: (a: NoInfer<A>) => B): Subscribable<B, E, R> =>\n  make({\n    get: Effect.map(self.get, f),\n    changes: Stream.map(self.changes, f)\n  }))\n\n/**\n * @since 2.0.0\n * @category combinators\n */\nexport const mapEffect: {\n  <A, B, E2, R2>(\n    f: (a: NoInfer<A>) => Effect.Effect<B, E2, R2>\n  ): <E, R>(fa: Subscribable<A, E, R>) => Subscribable<B, E | E2, R | R2>\n  <A, E, R, B, E2, R2>(\n    self: Subscribable<A, E, R>,\n    f: (a: NoInfer<A>) => Effect.Effect<B, E2, R2>\n  ): Subscribable<B, E | E2, R | R2>\n} = dual(2, <A, E, R, B, E2, R2>(\n  self: Subscribable<A, E, R>,\n  f: (a: NoInfer<A>) => Effect.Effect<B, E2, R2>\n): Subscribable<B, E | E2, R | R2> =>\n  make({\n    get: Effect.flatMap(self.get, f),\n    changes: Stream.mapEffect(self.changes, f)\n  }))\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const unwrap = <A, E, R, E1, R1>(\n  effect: Effect.Effect<Subscribable<A, E, R>, E1, R1>\n): Subscribable<A, E | E1, R | R1> =>\n  make({\n    get: Effect.flatMap(effect, (s) => s.get),\n    changes: Stream.unwrap(Effect.map(effect, (s) => s.changes))\n  })\n"
  },
  {
    "path": "packages/effect/src/SubscriptionRef.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/subscriptionRef.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as PubSub from \"./PubSub.js\"\nimport * as Ref from \"./Ref.js\"\nimport type * as Stream from \"./Stream.js\"\nimport type { Subscribable } from \"./Subscribable.js\"\nimport * as Synchronized from \"./SynchronizedRef.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const SubscriptionRefTypeId: unique symbol = internal.SubscriptionRefTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type SubscriptionRefTypeId = typeof SubscriptionRefTypeId\n\n/**\n * A `SubscriptionRef<A>` is a `Ref` that can be subscribed to in order to\n * receive the current value as well as all changes to the value.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface SubscriptionRef<in out A>\n  extends SubscriptionRef.Variance<A>, Synchronized.SynchronizedRef<A>, Subscribable<A>\n{\n  /** @internal */\n  readonly ref: Ref.Ref<A>\n  /** @internal */\n  readonly pubsub: PubSub.PubSub<A>\n  /** @internal */\n  readonly semaphore: Effect.Semaphore\n  /**\n   * A stream containing the current value of the `Ref` as well as all changes\n   * to that value.\n   */\n  readonly changes: Stream.Stream<A>\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: SubscriptionRefUnify<this>\n  readonly [Unify.ignoreSymbol]?: SubscriptionRefUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface SubscriptionRefUnify<A extends { [Unify.typeSymbol]?: any }>\n  extends Synchronized.SynchronizedRefUnify<A>\n{\n  SubscriptionRef?: () => Extract<A[Unify.typeSymbol], SubscriptionRef<any>>\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface SubscriptionRefUnifyIgnore extends Synchronized.SynchronizedRefUnifyIgnore {\n  SynchronizedRef?: true\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace SubscriptionRef {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A> {\n    readonly [SubscriptionRefTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const get: <A>(self: SubscriptionRef<A>) => Effect.Effect<A> = internal.get\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndSet: {\n  <A>(value: A): (self: SubscriptionRef<A>) => Effect.Effect<A>\n  <A>(self: SubscriptionRef<A>, value: A): Effect.Effect<A>\n} = Ref.getAndSet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdate: {\n  <A>(f: (a: A) => A): (self: SubscriptionRef<A>) => Effect.Effect<A>\n  <A>(self: SubscriptionRef<A>, f: (a: A) => A): Effect.Effect<A>\n} = Ref.getAndUpdate\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdateEffect: {\n  <A, R, E>(f: (a: A) => Effect.Effect<A, E, R>): (self: SubscriptionRef<A>) => Effect.Effect<A, E, R>\n  <A, R, E>(self: SubscriptionRef<A>, f: (a: A) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R>\n} = Synchronized.getAndUpdateEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdateSome: {\n  <A>(pf: (a: A) => Option.Option<A>): (self: SubscriptionRef<A>) => Effect.Effect<A>\n  <A>(self: SubscriptionRef<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<A>\n} = Ref.getAndUpdateSome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdateSomeEffect: {\n  <A, R, E>(\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ): (self: SubscriptionRef<A>) => Effect.Effect<A, E, R>\n  <A, R, E>(\n    self: SubscriptionRef<A>,\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ): Effect.Effect<A, E, R>\n} = Synchronized.getAndUpdateSomeEffect\n\n/**\n * Creates a new `SubscriptionRef` with the specified value.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A>(value: A) => Effect.Effect<SubscriptionRef<A>> = internal.make\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modify: {\n  <A, B>(f: (a: A) => readonly [B, A]): (self: SubscriptionRef<A>) => Effect.Effect<B>\n  <A, B>(self: SubscriptionRef<A>, f: (a: A) => readonly [B, A]): Effect.Effect<B>\n} = internal.modify\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modifyEffect: {\n  <B, A, E, R>(f: (a: A) => Effect.Effect<readonly [B, A], E, R>): (self: SubscriptionRef<A>) => Effect.Effect<B, E, R>\n  <A, B, E, R>(self: SubscriptionRef<A>, f: (a: A) => Effect.Effect<readonly [B, A], E, R>): Effect.Effect<B, E, R>\n} = internal.modifyEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modifySome: {\n  <B, A>(\n    fallback: B,\n    pf: (a: A) => Option.Option<readonly [B, A]>\n  ): (self: SubscriptionRef<A>) => Effect.Effect<B>\n  <A, B>(\n    self: SubscriptionRef<A>,\n    fallback: B,\n    pf: (a: A) => Option.Option<readonly [B, A]>\n  ): Effect.Effect<B>\n} = Ref.modifySome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modifySomeEffect: {\n  <A, B, R, E>(\n    fallback: B,\n    pf: (a: A) => Option.Option<Effect.Effect<readonly [B, A], E, R>>\n  ): (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<B, E, R>\n  <A, B, R, E>(\n    self: Synchronized.SynchronizedRef<A>,\n    fallback: B,\n    pf: (a: A) => Option.Option<Effect.Effect<readonly [B, A], E, R>>\n  ): Effect.Effect<B, E, R>\n} = Synchronized.modifySomeEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const set: {\n  <A>(value: A): (self: SubscriptionRef<A>) => Effect.Effect<void>\n  <A>(self: SubscriptionRef<A>, value: A): Effect.Effect<void>\n} = internal.set\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const setAndGet: {\n  <A>(value: A): (self: SubscriptionRef<A>) => Effect.Effect<A>\n  <A>(self: SubscriptionRef<A>, value: A): Effect.Effect<A>\n} = Ref.setAndGet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const update: {\n  <A>(f: (a: A) => A): (self: SubscriptionRef<A>) => Effect.Effect<void>\n  <A>(self: SubscriptionRef<A>, f: (a: A) => A): Effect.Effect<void>\n} = Ref.update\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateEffect: {\n  <A, R, E>(f: (a: A) => Effect.Effect<A, E, R>): (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<void, E, R>\n  <A, R, E>(self: Synchronized.SynchronizedRef<A>, f: (a: A) => Effect.Effect<A, E, R>): Effect.Effect<void, E, R>\n} = Synchronized.updateEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateAndGet: {\n  <A>(f: (a: A) => A): (self: SubscriptionRef<A>) => Effect.Effect<A>\n  <A>(self: SubscriptionRef<A>, f: (a: A) => A): Effect.Effect<A>\n} = Ref.updateAndGet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateAndGetEffect: {\n  <A, R, E>(f: (a: A) => Effect.Effect<A, E, R>): (self: SubscriptionRef<A>) => Effect.Effect<A, E, R>\n  <A, R, E>(self: SubscriptionRef<A>, f: (a: A) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R>\n} = Synchronized.updateAndGetEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSome: {\n  <A>(f: (a: A) => Option.Option<A>): (self: SubscriptionRef<A>) => Effect.Effect<void>\n  <A>(self: SubscriptionRef<A>, f: (a: A) => Option.Option<A>): Effect.Effect<void>\n} = Ref.updateSome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSomeEffect: {\n  <A, R, E>(\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ): (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<void, E, R>\n  <A, R, E>(\n    self: Synchronized.SynchronizedRef<A>,\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ): Effect.Effect<void, E, R>\n} = Synchronized.updateSomeEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSomeAndGet: {\n  <A>(pf: (a: A) => Option.Option<A>): (self: SubscriptionRef<A>) => Effect.Effect<A>\n  <A>(self: SubscriptionRef<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<A>\n} = Ref.updateSomeAndGet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSomeAndGetEffect: {\n  <A, R, E>(\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ): (self: SubscriptionRef<A>) => Effect.Effect<A, E, R>\n  <A, R, E>(\n    self: SubscriptionRef<A>,\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ): Effect.Effect<A, E, R>\n} = Synchronized.updateSomeAndGetEffect\n"
  },
  {
    "path": "packages/effect/src/Supervisor.ts",
    "content": "/**\n * A `Supervisor<T>` is allowed to supervise the launching and termination of\n * fibers, producing some visible value of type `T` from the supervision.\n *\n * @since 2.0.0\n */\nimport type * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport * as core from \"./internal/core.js\"\nimport * as circular from \"./internal/layer/circular.js\"\nimport * as internal from \"./internal/supervisor.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type * as MutableRef from \"./MutableRef.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as SortedSet from \"./SortedSet.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const SupervisorTypeId: unique symbol = internal.SupervisorTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type SupervisorTypeId = typeof SupervisorTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Supervisor<out T> extends Supervisor.Variance<T> {\n  /**\n   * Returns an `Effect` that succeeds with the value produced by this\n   * supervisor. This value may change over time, reflecting what the supervisor\n   * produces as it supervises fibers.\n   */\n  readonly value: Effect.Effect<T>\n\n  /**\n   * Supervises the start of a `Fiber`.\n   */\n  onStart<A, E, R>(\n    context: Context.Context<R>,\n    effect: Effect.Effect<A, E, R>,\n    parent: Option.Option<Fiber.RuntimeFiber<any, any>>,\n    fiber: Fiber.RuntimeFiber<A, E>\n  ): void\n\n  /**\n   * Supervises the end of a `Fiber`.\n   */\n  onEnd<A, E>(value: Exit.Exit<A, E>, fiber: Fiber.RuntimeFiber<A, E>): void\n\n  /**\n   * Supervises the execution of an `Effect` by a `Fiber`.\n   */\n  onEffect<A, E>(fiber: Fiber.RuntimeFiber<A, E>, effect: Effect.Effect<any, any, any>): void\n\n  /**\n   * Supervises the suspension of a computation running within a `Fiber`.\n   */\n  onSuspend<A, E>(fiber: Fiber.RuntimeFiber<A, E>): void\n\n  /**\n   * Supervises the resumption of a computation running within a `Fiber`.\n   */\n  onResume<A, E>(fiber: Fiber.RuntimeFiber<A, E>): void\n\n  /**\n   * Maps this supervisor to another one, which has the same effect, but whose\n   * value has been transformed by the specified function.\n   */\n  map<B>(f: (a: T) => B): Supervisor<B>\n\n  /**\n   * Returns a new supervisor that performs the function of this supervisor, and\n   * the function of the specified supervisor, producing a tuple of the outputs\n   * produced by both supervisors.\n   */\n  zip<A>(right: Supervisor<A>): Supervisor<[T, A]>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Supervisor {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out T> {\n    readonly [SupervisorTypeId]: {\n      readonly _T: Types.Covariant<T>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category context\n */\nexport const addSupervisor: <A>(supervisor: Supervisor<A>) => Layer.Layer<never> = circular.addSupervisor\n\n/**\n * Creates a new supervisor that tracks children in a set.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fibersIn: (\n  ref: MutableRef.MutableRef<SortedSet.SortedSet<Fiber.RuntimeFiber<any, any>>>\n) => Effect.Effect<Supervisor<SortedSet.SortedSet<Fiber.RuntimeFiber<any, any>>>> = internal.fibersIn\n\n/**\n * Creates a new supervisor that constantly yields effect when polled\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEffect: <A>(effect: Effect.Effect<A>) => Supervisor<A> = internal.fromEffect\n\n/**\n * A supervisor that doesn't do anything in response to supervision events.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const none: Supervisor<void> = internal.none\n\n/**\n * Creates a new supervisor that tracks children in a set.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const track: Effect.Effect<Supervisor<Array<Fiber.RuntimeFiber<any, any>>>> = internal.track\n\n/**\n * Unsafely creates a new supervisor that tracks children in a set.\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeTrack: () => Supervisor<Array<Fiber.RuntimeFiber<any, any>>> = internal.unsafeTrack\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport abstract class AbstractSupervisor<T> implements Supervisor<T> {\n  /**\n   * @since 2.0.0\n   */\n  abstract value: Effect.Effect<T>\n\n  /**\n   * @since 2.0.0\n   */\n  onStart<A, E, R>(\n    _context: Context.Context<R>,\n    _effect: Effect.Effect<A, E, R>,\n    _parent: Option.Option<Fiber.RuntimeFiber<any, any>>,\n    _fiber: Fiber.RuntimeFiber<A, E>\n  ): void {\n    //\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  onEnd<A, E>(\n    _value: Exit.Exit<A, E>,\n    _fiber: Fiber.RuntimeFiber<A, E>\n  ): void {\n    //\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  onEffect<A, E>(\n    _fiber: Fiber.RuntimeFiber<A, E>,\n    _effect: Effect.Effect<any, any, any>\n  ): void {\n    //\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  onSuspend<A, E>(\n    _fiber: Fiber.RuntimeFiber<A, E>\n  ): void {\n    //\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  onResume<A, E>(\n    _fiber: Fiber.RuntimeFiber<A, E>\n  ): void {\n    //\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  map<B>(f: (a: T) => B): Supervisor<B> {\n    return new internal.ProxySupervisor(this, core.map(this.value, f))\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  zip<A>(\n    right: Supervisor<A>\n  ): Supervisor<[T, A]> {\n    return new internal.Zip(this, right)\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  onRun<E, A, X>(execution: () => X, _fiber: Fiber.RuntimeFiber<A, E>): X {\n    return execution()\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  readonly [SupervisorTypeId]: {\n    _T: (_: never) => never\n  } = internal.supervisorVariance\n}\n"
  },
  {
    "path": "packages/effect/src/Symbol.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport * as equivalence from \"./Equivalence.js\"\nimport * as predicate from \"./Predicate.js\"\n\n/**\n * Tests if a value is a `symbol`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Predicate } from \"effect\"\n *\n * assert.deepStrictEqual(Predicate.isSymbol(Symbol.for(\"a\")), true)\n * assert.deepStrictEqual(Predicate.isSymbol(\"a\"), false)\n * ```\n *\n * @category guards\n * @since 2.0.0\n */\nexport const isSymbol: (u: unknown) => u is symbol = predicate.isSymbol\n\n/**\n * @category instances\n * @since 2.0.0\n */\nexport const Equivalence: equivalence.Equivalence<symbol> = equivalence.symbol\n"
  },
  {
    "path": "packages/effect/src/SynchronizedRef.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport * as circular from \"./internal/effect/circular.js\"\nimport * as ref from \"./internal/ref.js\"\nimport * as internal from \"./internal/synchronizedRef.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Ref from \"./Ref.js\"\nimport type * as Types from \"./Types.js\"\nimport type * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const SynchronizedRefTypeId: unique symbol = circular.SynchronizedTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type SynchronizedRefTypeId = typeof SynchronizedRefTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface SynchronizedRef<in out A> extends SynchronizedRef.Variance<A>, Ref.Ref<A> {\n  modifyEffect<B, E, R>(f: (a: A) => Effect.Effect<readonly [B, A], E, R>): Effect.Effect<B, E, R>\n  readonly [Unify.typeSymbol]?: unknown\n  readonly [Unify.unifySymbol]?: SynchronizedRefUnify<this>\n  readonly [Unify.ignoreSymbol]?: SynchronizedRefUnifyIgnore\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface SynchronizedRefUnify<A extends { [Unify.typeSymbol]?: any }> extends Ref.RefUnify<A> {\n  SynchronizedRef?: () => Extract<A[Unify.typeSymbol], SynchronizedRef<any>>\n}\n\n/**\n * @category models\n * @since 3.8.0\n */\nexport interface SynchronizedRefUnifyIgnore extends Ref.RefUnifyIgnore {\n  Ref?: true\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace SynchronizedRef {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A> {\n    readonly [SynchronizedRefTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A>(value: A) => Effect.Effect<SynchronizedRef<A>> = circular.makeSynchronized\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const get: <A>(self: SynchronizedRef<A>) => Effect.Effect<A> = ref.get\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndSet: {\n  <A>(value: A): (self: Ref.Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref.Ref<A>, value: A): Effect.Effect<A>\n} = ref.getAndSet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdate: {\n  <A>(f: (a: A) => A): (self: Ref.Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref.Ref<A>, f: (a: A) => A): Effect.Effect<A>\n} = ref.getAndUpdate\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdateEffect: {\n  <A, R, E>(f: (a: A) => Effect.Effect<A, E, R>): (self: SynchronizedRef<A>) => Effect.Effect<A, E, R>\n  <A, R, E>(self: SynchronizedRef<A>, f: (a: A) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R>\n} = internal.getAndUpdateEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdateSome: {\n  <A>(pf: (a: A) => Option.Option<A>): (self: Ref.Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref.Ref<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<A>\n} = ref.getAndUpdateSome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const getAndUpdateSomeEffect: {\n  <A, R, E>(pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>): (self: SynchronizedRef<A>) => Effect.Effect<A, E, R>\n  <A, R, E>(self: SynchronizedRef<A>, pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>): Effect.Effect<A, E, R>\n} = internal.getAndUpdateSomeEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modify: {\n  <A, B>(f: (a: A) => readonly [B, A]): (self: SynchronizedRef<A>) => Effect.Effect<B>\n  <A, B>(self: SynchronizedRef<A>, f: (a: A) => readonly [B, A]): Effect.Effect<B>\n} = internal.modify\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modifyEffect: {\n  <A, B, E, R>(f: (a: A) => Effect.Effect<readonly [B, A], E, R>): (self: SynchronizedRef<A>) => Effect.Effect<B, E, R>\n  <A, B, E, R>(self: SynchronizedRef<A>, f: (a: A) => Effect.Effect<readonly [B, A], E, R>): Effect.Effect<B, E, R>\n} = internal.modifyEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modifySome: {\n  <B, A>(\n    fallback: B,\n    pf: (a: A) => Option.Option<readonly [B, A]>\n  ): (self: Ref.Ref<A>) => Effect.Effect<B>\n  <A, B>(\n    self: Ref.Ref<A>,\n    fallback: B,\n    pf: (a: A) => Option.Option<readonly [B, A]>\n  ): Effect.Effect<B>\n} = ref.modifySome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const modifySomeEffect: {\n  <A, B, R, E>(\n    fallback: B,\n    pf: (a: A) => Option.Option<Effect.Effect<readonly [B, A], E, R>>\n  ): (self: SynchronizedRef<A>) => Effect.Effect<B, E, R>\n  <A, B, R, E>(\n    self: SynchronizedRef<A>,\n    fallback: B,\n    pf: (a: A) => Option.Option<Effect.Effect<readonly [B, A], E, R>>\n  ): Effect.Effect<B, E, R>\n} = internal.modifySomeEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const set: {\n  <A>(value: A): (self: Ref.Ref<A>) => Effect.Effect<void>\n  <A>(self: Ref.Ref<A>, value: A): Effect.Effect<void>\n} = ref.set\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const setAndGet: {\n  <A>(value: A): (self: Ref.Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref.Ref<A>, value: A): Effect.Effect<A>\n} = ref.setAndGet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const update: {\n  <A>(f: (a: A) => A): (self: Ref.Ref<A>) => Effect.Effect<void>\n  <A>(self: Ref.Ref<A>, f: (a: A) => A): Effect.Effect<void>\n} = ref.update\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateEffect: {\n  <A, R, E>(f: (a: A) => Effect.Effect<A, E, R>): (self: SynchronizedRef<A>) => Effect.Effect<void, E, R>\n  <A, R, E>(self: SynchronizedRef<A>, f: (a: A) => Effect.Effect<A, E, R>): Effect.Effect<void, E, R>\n} = internal.updateEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateAndGet: {\n  <A>(f: (a: A) => A): (self: Ref.Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref.Ref<A>, f: (a: A) => A): Effect.Effect<A>\n} = ref.updateAndGet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateAndGetEffect: {\n  <A, R, E>(f: (a: A) => Effect.Effect<A, E, R>): (self: SynchronizedRef<A>) => Effect.Effect<A, E, R>\n  <A, R, E>(self: SynchronizedRef<A>, f: (a: A) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R>\n} = internal.updateAndGetEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSome: {\n  <A>(f: (a: A) => Option.Option<A>): (self: Ref.Ref<A>) => Effect.Effect<void>\n  <A>(self: Ref.Ref<A>, f: (a: A) => Option.Option<A>): Effect.Effect<void>\n} = ref.updateSome\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSomeEffect: {\n  <A, R, E>(\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ): (self: SynchronizedRef<A>) => Effect.Effect<void, E, R>\n  <A, R, E>(self: SynchronizedRef<A>, pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>): Effect.Effect<void, E, R>\n} = internal.updateSomeEffect\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSomeAndGet: {\n  <A>(pf: (a: A) => Option.Option<A>): (self: Ref.Ref<A>) => Effect.Effect<A>\n  <A>(self: Ref.Ref<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<A>\n} = ref.updateSomeAndGet\n\n/**\n * @since 2.0.0\n * @category utils\n */\nexport const updateSomeAndGetEffect: {\n  <A, R, E>(pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>): (self: SynchronizedRef<A>) => Effect.Effect<A, E, R>\n  <A, R, E>(self: SynchronizedRef<A>, pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>): Effect.Effect<A, E, R>\n} = circular.updateSomeAndGetEffectSynchronized\n\n/**\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeMake: <A>(value: A) => SynchronizedRef<A> = circular.unsafeMakeSynchronized\n"
  },
  {
    "path": "packages/effect/src/TArray.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/stm/tArray.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Order from \"./Order.js\"\nimport type { Predicate } from \"./Predicate.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as TRef from \"./TRef.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TArrayTypeId: unique symbol = internal.TArrayTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TArrayTypeId = typeof TArrayTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface TArray<in out A> extends TArray.Variance<A> {}\n/**\n * @internal\n * @since 2.0.0\n */\nexport interface TArray<in out A> {\n  /** @internal */\n  readonly chunk: Array<TRef.TRef<A>>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace TArray {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A> {\n    readonly [TArrayTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * Finds the result of applying a partial function to the first value in its\n * domain.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const collectFirst: {\n  <A, B>(pf: (a: A) => Option.Option<B>): (self: TArray<A>) => STM.STM<Option.Option<B>>\n  <A, B>(self: TArray<A>, pf: (a: A) => Option.Option<B>): STM.STM<Option.Option<B>>\n} = internal.collectFirst\n\n/**\n * Finds the result of applying an transactional partial function to the first\n * value in its domain.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const collectFirstSTM: {\n  <A, B, E, R>(pf: (a: A) => Option.Option<STM.STM<B, E, R>>): (self: TArray<A>) => STM.STM<Option.Option<B>, E, R>\n  <A, B, E, R>(self: TArray<A>, pf: (a: A) => Option.Option<STM.STM<B, E, R>>): STM.STM<Option.Option<B>, E, R>\n} = internal.collectFirstSTM\n\n/**\n * Determine if the array contains a specified value.\n *\n * @macro trace\n * @since 2.0.0\n * @category elements\n */\nexport const contains: {\n  <A>(value: A): (self: TArray<A>) => STM.STM<boolean>\n  <A>(self: TArray<A>, value: A): STM.STM<boolean>\n} = internal.contains\n\n/**\n * Count the values in the array matching a predicate.\n *\n * @macro trace\n * @since 2.0.0\n * @category folding\n */\nexport const count: {\n  <A>(predicate: Predicate<A>): (self: TArray<A>) => STM.STM<number>\n  <A>(self: TArray<A>, predicate: Predicate<A>): STM.STM<number>\n} = internal.count\n\n/**\n * Count the values in the array matching a transactional predicate.\n *\n * @macro trace\n * @since 2.0.0\n * @category folding\n */\nexport const countSTM: {\n  <A, R, E>(predicate: (value: A) => STM.STM<boolean, E, R>): (self: TArray<A>) => STM.STM<number, E, R>\n  <A, R, E>(self: TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>): STM.STM<number, E, R>\n} = internal.countSTM\n\n/**\n * Makes an empty `TArray`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: <A>() => STM.STM<TArray<A>> = internal.empty\n\n/**\n * Atomically evaluate the conjunction of a predicate across the members of\n * the array.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const every: {\n  <A>(predicate: Predicate<A>): (self: TArray<A>) => STM.STM<boolean>\n  <A>(self: TArray<A>, predicate: Predicate<A>): STM.STM<boolean>\n} = internal.every\n\n/**\n * Atomically evaluate the conjunction of a transactional predicate across the\n * members of the array.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const everySTM: {\n  <A, R, E>(predicate: (value: A) => STM.STM<boolean, E, R>): (self: TArray<A>) => STM.STM<boolean, E, R>\n  <A, R, E>(self: TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>): STM.STM<boolean, E, R>\n} = internal.everySTM\n\n/**\n * Find the first element in the array matching the specified predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findFirst: {\n  <A>(predicate: Predicate<A>): (self: TArray<A>) => STM.STM<Option.Option<A>>\n  <A>(self: TArray<A>, predicate: Predicate<A>): STM.STM<Option.Option<A>>\n} = internal.findFirst\n\n/**\n * Get the first index of a specific value in the array.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findFirstIndex: {\n  <A>(value: A): (self: TArray<A>) => STM.STM<Option.Option<number>>\n  <A>(self: TArray<A>, value: A): STM.STM<Option.Option<number>>\n} = internal.findFirstIndex\n\n/**\n * Get the first index of a specific value in the array starting from the\n * specified index.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findFirstIndexFrom: {\n  <A>(value: A, from: number): (self: TArray<A>) => STM.STM<Option.Option<number>>\n  <A>(self: TArray<A>, value: A, from: number): STM.STM<Option.Option<number>>\n} = internal.findFirstIndexFrom\n\n/**\n * Get the index of the first entry in the array matching a predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findFirstIndexWhere: {\n  <A>(predicate: Predicate<A>): (self: TArray<A>) => STM.STM<Option.Option<number>>\n  <A>(self: TArray<A>, predicate: Predicate<A>): STM.STM<Option.Option<number>>\n} = internal.findFirstIndexWhere\n\n/**\n * Get the index of the first entry in the array starting from the specified\n * index, matching a predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findFirstIndexWhereFrom: {\n  <A>(predicate: Predicate<A>, from: number): (self: TArray<A>) => STM.STM<Option.Option<number>>\n  <A>(self: TArray<A>, predicate: Predicate<A>, from: number): STM.STM<Option.Option<number>>\n} = internal.findFirstIndexWhereFrom\n\n/**\n * Get the index of the next entry that matches a transactional predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findFirstIndexWhereSTM: {\n  <A, R, E>(predicate: (value: A) => STM.STM<boolean, E, R>): (self: TArray<A>) => STM.STM<Option.Option<number>, E, R>\n  <A, R, E>(self: TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>): STM.STM<Option.Option<number>, E, R>\n} = internal.findFirstIndexWhereSTM\n\n/**\n * Starting at specified index, get the index of the next entry that matches a\n * transactional predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findFirstIndexWhereFromSTM: {\n  <A, R, E>(\n    predicate: (value: A) => STM.STM<boolean, E, R>,\n    from: number\n  ): (self: TArray<A>) => STM.STM<Option.Option<number>, E, R>\n  <A, R, E>(\n    self: TArray<A>,\n    predicate: (value: A) => STM.STM<boolean, E, R>,\n    from: number\n  ): STM.STM<Option.Option<number>, E, R>\n} = internal.findFirstIndexWhereFromSTM\n\n/**\n * Find the first element in the array matching a transactional predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findFirstSTM: {\n  <A, R, E>(predicate: (value: A) => STM.STM<boolean, E, R>): (self: TArray<A>) => STM.STM<Option.Option<A>, E, R>\n  <A, R, E>(self: TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>): STM.STM<Option.Option<A>, E, R>\n} = internal.findFirstSTM\n\n/**\n * Find the last element in the array matching a predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findLast: {\n  <A>(predicate: Predicate<A>): (self: TArray<A>) => STM.STM<Option.Option<A>>\n  <A>(self: TArray<A>, predicate: Predicate<A>): STM.STM<Option.Option<A>>\n} = internal.findLast\n\n/**\n * Get the last index of a specific value in the array bounded above by a\n * specific index.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findLastIndex: {\n  <A>(value: A): (self: TArray<A>) => STM.STM<Option.Option<number>>\n  <A>(self: TArray<A>, value: A): STM.STM<Option.Option<number>>\n} = internal.findLastIndex\n\n/**\n * Get the last index of a specific value in the array bounded above by a\n * specific index.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findLastIndexFrom: {\n  <A>(value: A, end: number): (self: TArray<A>) => STM.STM<Option.Option<number>>\n  <A>(self: TArray<A>, value: A, end: number): STM.STM<Option.Option<number>>\n} = internal.findLastIndexFrom\n\n/**\n * Find the last element in the array matching a transactional predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findLastSTM: {\n  <A, R, E>(predicate: (value: A) => STM.STM<boolean, E, R>): (self: TArray<A>) => STM.STM<Option.Option<A>, E, R>\n  <A, R, E>(self: TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>): STM.STM<Option.Option<A>, E, R>\n} = internal.findLastSTM\n\n/**\n * Atomically performs transactional effect for each item in array.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const forEach: {\n  <A, R, E>(f: (value: A) => STM.STM<void, E, R>): (self: TArray<A>) => STM.STM<void, E, R>\n  <A, R, E>(self: TArray<A>, f: (value: A) => STM.STM<void, E, R>): STM.STM<void, E, R>\n} = internal.forEach\n\n/**\n * Creates a new `TArray` from an iterable collection of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: <A>(iterable: Iterable<A>) => STM.STM<TArray<A>> = internal.fromIterable\n\n/**\n * Extracts value from ref in array.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const get: {\n  (index: number): <A>(self: TArray<A>) => STM.STM<A>\n  <A>(self: TArray<A>, index: number): STM.STM<A>\n} = internal.get\n\n/**\n * The first entry of the array, if it exists.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const headOption: <A>(self: TArray<A>) => STM.STM<Option.Option<A>> = internal.headOption\n\n/**\n * The last entry in the array, if it exists.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const lastOption: <A>(self: TArray<A>) => STM.STM<Option.Option<A>> = internal.lastOption\n\n/**\n * Makes a new `TArray` that is initialized with specified values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Elements extends [any, ...Array<any>]>(\n  ...elements: Elements\n) => STM.STM<TArray<Elements[number]>> = internal.make\n\n/**\n * Atomically compute the greatest element in the array, if it exists.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const maxOption: {\n  <A>(order: Order.Order<A>): (self: TArray<A>) => STM.STM<Option.Option<A>>\n  <A>(self: TArray<A>, order: Order.Order<A>): STM.STM<Option.Option<A>>\n} = internal.maxOption\n\n/**\n * Atomically compute the least element in the array, if it exists.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const minOption: {\n  <A>(order: Order.Order<A>): (self: TArray<A>) => STM.STM<Option.Option<A>>\n  <A>(self: TArray<A>, order: Order.Order<A>): STM.STM<Option.Option<A>>\n} = internal.minOption\n\n/**\n * Atomically folds using a pure function.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const reduce: {\n  <Z, A>(zero: Z, f: (accumulator: Z, current: A) => Z): (self: TArray<A>) => STM.STM<Z>\n  <Z, A>(self: TArray<A>, zero: Z, f: (accumulator: Z, current: A) => Z): STM.STM<Z>\n} = internal.reduce\n\n/**\n * Atomically reduce the array, if non-empty, by a binary operator.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const reduceOption: {\n  <A>(f: (x: A, y: A) => A): (self: TArray<A>) => STM.STM<Option.Option<A>>\n  <A>(self: TArray<A>, f: (x: A, y: A) => A): STM.STM<Option.Option<A>>\n} = internal.reduceOption\n\n/**\n * Atomically reduce the non-empty array using a transactional binary\n * operator.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const reduceOptionSTM: {\n  <A, R, E>(f: (x: A, y: A) => STM.STM<A, E, R>): (self: TArray<A>) => STM.STM<Option.Option<A>, E, R>\n  <A, R, E>(self: TArray<A>, f: (x: A, y: A) => STM.STM<A, E, R>): STM.STM<Option.Option<A>, E, R>\n} = internal.reduceOptionSTM\n\n/**\n * Atomically folds using a transactional function.\n *\n * @macro trace\n * @since 2.0.0\n * @category folding\n */\nexport const reduceSTM: {\n  <Z, A, R, E>(zero: Z, f: (accumulator: Z, current: A) => STM.STM<Z, E, R>): (self: TArray<A>) => STM.STM<Z, E, R>\n  <Z, A, R, E>(self: TArray<A>, zero: Z, f: (accumulator: Z, current: A) => STM.STM<Z, E, R>): STM.STM<Z, E, R>\n} = internal.reduceSTM\n\n/**\n * Returns the size of the `TArray`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <A>(self: TArray<A>) => number = internal.size\n\n/**\n * Determine if the array contains a value satisfying a predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const some: {\n  <A>(predicate: Predicate<A>): (self: TArray<A>) => STM.STM<boolean>\n  <A>(self: TArray<A>, predicate: Predicate<A>): STM.STM<boolean>\n} = internal.some\n\n/**\n * Determine if the array contains a value satisfying a transactional\n * predicate.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const someSTM: {\n  <A, R, E>(predicate: (value: A) => STM.STM<boolean, E, R>): (self: TArray<A>) => STM.STM<boolean, E, R>\n  <A, R, E>(self: TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>): STM.STM<boolean, E, R>\n} = internal.someSTM\n\n/**\n * Collects all elements into a chunk.\n *\n * @since 2.0.0\n * @since 2.0.0\n * @category destructors\n */\nexport const toArray: <A>(self: TArray<A>) => STM.STM<Array<A>> = internal.toArray\n\n/**\n * Atomically updates all elements using a pure function.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const transform: {\n  <A>(f: (value: A) => A): (self: TArray<A>) => STM.STM<void>\n  <A>(self: TArray<A>, f: (value: A) => A): STM.STM<void>\n} = internal.transform\n\n/**\n * Atomically updates all elements using a transactional effect.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const transformSTM: {\n  <A, R, E>(f: (value: A) => STM.STM<A, E, R>): (self: TArray<A>) => STM.STM<void, E, R>\n  <A, R, E>(self: TArray<A>, f: (value: A) => STM.STM<A, E, R>): STM.STM<void, E, R>\n} = internal.transformSTM\n\n/**\n * Updates element in the array with given function.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const update: {\n  <A>(index: number, f: (value: A) => A): (self: TArray<A>) => STM.STM<void>\n  <A>(self: TArray<A>, index: number, f: (value: A) => A): STM.STM<void>\n} = internal.update\n\n/**\n * Atomically updates element in the array with given transactional effect.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const updateSTM: {\n  <A, R, E>(index: number, f: (value: A) => STM.STM<A, E, R>): (self: TArray<A>) => STM.STM<void, E, R>\n  <A, R, E>(self: TArray<A>, index: number, f: (value: A) => STM.STM<A, E, R>): STM.STM<void, E, R>\n} = internal.updateSTM\n"
  },
  {
    "path": "packages/effect/src/TDeferred.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Either from \"./Either.js\"\nimport * as internal from \"./internal/stm/tDeferred.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as TRef from \"./TRef.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TDeferredTypeId: unique symbol = internal.TDeferredTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TDeferredTypeId = typeof TDeferredTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface TDeferred<in out A, in out E = never> extends TDeferred.Variance<A, E> {}\n/**\n * @internal\n * @since 2.0.0\n */\nexport interface TDeferred<in out A, in out E> {\n  /** @internal */\n  readonly ref: TRef.TRef<Option.Option<Either.Either<A, E>>>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace TDeferred {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A, in out E> {\n    readonly [TDeferredTypeId]: {\n      readonly _A: Types.Invariant<A>\n      readonly _E: Types.Invariant<E>\n    }\n  }\n}\n\nconst _await: <A, E>(self: TDeferred<A, E>) => STM.STM<A, E> = internal._await\n\nexport {\n  /**\n   * @since 2.0.0\n   * @category getters\n   */\n  _await as await\n}\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const done: {\n  <A, E>(either: Either.Either<A, E>): (self: TDeferred<A, E>) => STM.STM<boolean>\n  <A, E>(self: TDeferred<A, E>, either: Either.Either<A, E>): STM.STM<boolean>\n} = internal.done\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const fail: {\n  <E>(error: E): <A>(self: TDeferred<A, E>) => STM.STM<boolean>\n  <A, E>(self: TDeferred<A, E>, error: E): STM.STM<boolean>\n} = internal.fail\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A, E = never>() => STM.STM<TDeferred<A, E>> = internal.make\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const poll: <A, E>(self: TDeferred<A, E>) => STM.STM<Option.Option<Either.Either<A, E>>> = internal.poll\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const succeed: {\n  <A>(value: A): <E>(self: TDeferred<A, E>) => STM.STM<boolean>\n  <A, E>(self: TDeferred<A, E>, value: A): STM.STM<boolean>\n} = internal.succeed\n"
  },
  {
    "path": "packages/effect/src/TMap.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Chunk from \"./Chunk.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport type * as HashMap from \"./HashMap.js\"\nimport * as internal from \"./internal/stm/tMap.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as TArray from \"./TArray.js\"\nimport type * as TRef from \"./TRef.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TMapTypeId: unique symbol = internal.TMapTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TMapTypeId = typeof TMapTypeId\n\n/**\n * Transactional map implemented on top of `TRef` and `TArray`. Resolves\n * conflicts via chaining.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface TMap<in out K, in out V> extends TMap.Variance<K, V> {}\n/**\n * @internal\n * @since 2.0.0\n */\nexport interface TMap<in out K, in out V> {\n  /** @internal */\n  readonly tBuckets: TRef.TRef<TArray.TArray<Chunk.Chunk<readonly [K, V]>>>\n  /** @internal */\n  readonly tSize: TRef.TRef<number>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace TMap {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out K, in out V> {\n    readonly [TMapTypeId]: {\n      readonly _K: Types.Invariant<K>\n      readonly _V: Types.Invariant<V>\n    }\n  }\n}\n\n/**\n * Makes an empty `TMap`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: <K, V>() => STM.STM<TMap<K, V>> = internal.empty\n\n/**\n * Finds the key/value pair matching the specified predicate, and uses the\n * provided function to extract a value out of it.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const find: {\n  <K, V, A>(pf: (key: K, value: V) => Option.Option<A>): (self: TMap<K, V>) => STM.STM<Option.Option<A>>\n  <K, V, A>(self: TMap<K, V>, pf: (key: K, value: V) => Option.Option<A>): STM.STM<Option.Option<A>>\n} = internal.find\n\n/**\n * Finds the key/value pair matching the specified predicate, and uses the\n * provided effectful function to extract a value out of it.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findSTM: {\n  <K, V, A, E, R>(\n    f: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ): (self: TMap<K, V>) => STM.STM<Option.Option<A>, E, R>\n  <K, V, A, E, R>(\n    self: TMap<K, V>,\n    f: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ): STM.STM<Option.Option<A>, E, R>\n} = internal.findSTM\n\n/**\n * Finds all the key/value pairs matching the specified predicate, and uses\n * the provided function to extract values out them.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findAll: {\n  <K, V, A>(pf: (key: K, value: V) => Option.Option<A>): (self: TMap<K, V>) => STM.STM<Array<A>>\n  <K, V, A>(self: TMap<K, V>, pf: (key: K, value: V) => Option.Option<A>): STM.STM<Array<A>>\n} = internal.findAll\n\n/**\n * Finds all the key/value pairs matching the specified predicate, and uses\n * the provided effectful function to extract values out of them..\n *\n * @since 2.0.0\n * @category elements\n */\nexport const findAllSTM: {\n  <K, V, A, E, R>(\n    pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ): (self: TMap<K, V>) => STM.STM<Array<A>, E, R>\n  <K, V, A, E, R>(self: TMap<K, V>, pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>): STM.STM<Array<A>, E, R>\n} = internal.findAllSTM\n\n/**\n * Atomically performs transactional-effect for each binding present in map.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const forEach: {\n  <K, V, X, E, R>(f: (key: K, value: V) => STM.STM<X, E, R>): (self: TMap<K, V>) => STM.STM<void, E, R>\n  <K, V, X, E, R>(self: TMap<K, V>, f: (key: K, value: V) => STM.STM<X, E, R>): STM.STM<void, E, R>\n} = internal.forEach\n\n/**\n * Creates a new `TMap` from an iterable collection of key/value pairs.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: <K, V>(\n  iterable: Iterable<readonly [K, V]>\n) => STM.STM<TMap<K, V>> = internal.fromIterable\n\n/**\n * Retrieves value associated with given key.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const get: {\n  <K>(key: K): <V>(self: TMap<K, V>) => STM.STM<Option.Option<V>>\n  <K, V>(self: TMap<K, V>, key: K): STM.STM<Option.Option<V>>\n} = internal.get\n\n/**\n * Retrieves value associated with given key or default value, in case the key\n * isn't present.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const getOrElse: {\n  <K, V>(key: K, fallback: LazyArg<V>): (self: TMap<K, V>) => STM.STM<V>\n  <K, V>(self: TMap<K, V>, key: K, fallback: LazyArg<V>): STM.STM<V>\n} = internal.getOrElse\n\n/**\n * Tests whether or not map contains a key.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const has: {\n  <K>(key: K): <V>(self: TMap<K, V>) => STM.STM<boolean>\n  <K, V>(self: TMap<K, V>, key: K): STM.STM<boolean>\n} = internal.has\n\n/**\n * Tests if the map is empty or not.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isEmpty: <K, V>(self: TMap<K, V>) => STM.STM<boolean> = internal.isEmpty\n\n/**\n * Collects all keys stored in map.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const keys: <K, V>(self: TMap<K, V>) => STM.STM<Array<K>> = internal.keys\n\n/**\n * Makes a new `TMap` that is initialized with specified values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <K, V>(...entries: Array<readonly [K, V]>) => STM.STM<TMap<K, V>> = internal.make\n\n/**\n * If the key is not already associated with a value, stores the provided value,\n * otherwise merge the existing value with the new one using function `f` and\n * store the result.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const merge: {\n  <K, V>(key: K, value: V, f: (x: V, y: V) => V): (self: TMap<K, V>) => STM.STM<V>\n  <K, V>(self: TMap<K, V>, key: K, value: V, f: (x: V, y: V) => V): STM.STM<V>\n} = internal.merge\n\n/**\n * Atomically folds using a pure function.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const reduce: {\n  <Z, K, V>(zero: Z, f: (acc: Z, value: V, key: K) => Z): (self: TMap<K, V>) => STM.STM<Z>\n  <K, V, Z>(self: TMap<K, V>, zero: Z, f: (acc: Z, value: V, key: K) => Z): STM.STM<Z>\n} = internal.reduce\n\n/**\n * Atomically folds using a transactional function.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const reduceSTM: {\n  <Z, V, K, R, E>(zero: Z, f: (acc: Z, value: V, key: K) => STM.STM<Z, E, R>): (self: TMap<K, V>) => STM.STM<Z, E, R>\n  <Z, V, K, R, E>(self: TMap<K, V>, zero: Z, f: (acc: Z, value: V, key: K) => STM.STM<Z, E, R>): STM.STM<Z, E, R>\n} = internal.reduceSTM\n\n/**\n * Removes binding for given key.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const remove: {\n  <K>(key: K): <V>(self: TMap<K, V>) => STM.STM<void>\n  <K, V>(self: TMap<K, V>, key: K): STM.STM<void>\n} = internal.remove\n\n/**\n * Deletes all entries associated with the specified keys.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const removeAll: {\n  <K>(keys: Iterable<K>): <V>(self: TMap<K, V>) => STM.STM<void>\n  <K, V>(self: TMap<K, V>, keys: Iterable<K>): STM.STM<void>\n} = internal.removeAll\n\n/**\n * Removes entries from a `TMap` that satisfy the specified predicate and returns the removed entries\n * (or `void` if `discard = true`).\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const removeIf: {\n  <K, V>(\n    predicate: (key: K, value: V) => boolean,\n    options: {\n      readonly discard: true\n    }\n  ): (self: TMap<K, V>) => STM.STM<void>\n  <K, V>(\n    predicate: (key: K, value: V) => boolean,\n    options?: {\n      readonly discard: false\n    }\n  ): (self: TMap<K, V>) => STM.STM<Array<[K, V]>>\n  <K, V>(\n    self: TMap<K, V>,\n    predicate: (key: K, value: V) => boolean,\n    options: {\n      readonly discard: true\n    }\n  ): STM.STM<void>\n  <K, V>(\n    self: TMap<K, V>,\n    predicate: (key: K, value: V) => boolean,\n    options?: {\n      readonly discard: false\n    }\n  ): STM.STM<Array<[K, V]>>\n} = internal.removeIf\n\n/**\n * Retains entries in a `TMap` that satisfy the specified predicate and returns the removed entries\n * (or `void` if `discard = true`).\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const retainIf: {\n  <K, V>(\n    predicate: (key: K, value: V) => boolean,\n    options: {\n      readonly discard: true\n    }\n  ): (self: TMap<K, V>) => STM.STM<void>\n  <K, V>(\n    predicate: (key: K, value: V) => boolean,\n    options?: {\n      readonly discard: false\n    }\n  ): (self: TMap<K, V>) => STM.STM<Array<[K, V]>>\n  <K, V>(\n    self: TMap<K, V>,\n    predicate: (key: K, value: V) => boolean,\n    options: {\n      readonly discard: true\n    }\n  ): STM.STM<void>\n  <K, V>(\n    self: TMap<K, V>,\n    predicate: (key: K, value: V) => boolean,\n    options?: {\n      readonly discard: false\n    }\n  ): STM.STM<Array<[K, V]>>\n} = internal.retainIf\n\n/**\n * Stores new binding into the map.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const set: {\n  <K, V>(key: K, value: V): (self: TMap<K, V>) => STM.STM<void>\n  <K, V>(self: TMap<K, V>, key: K, value: V): STM.STM<void>\n} = internal.set\n\n/**\n * Stores new binding in the map if it does not already exist.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const setIfAbsent: {\n  <K, V>(key: K, value: V): (self: TMap<K, V>) => STM.STM<void>\n  <K, V>(self: TMap<K, V>, key: K, value: V): STM.STM<void>\n} = internal.setIfAbsent\n\n/**\n * Returns the number of bindings.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <K, V>(self: TMap<K, V>) => STM.STM<number> = internal.size\n\n/**\n * Takes the first matching value, or retries until there is one.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeFirst: {\n  <K, V, A>(pf: (key: K, value: V) => Option.Option<A>): (self: TMap<K, V>) => STM.STM<A>\n  <K, V, A>(self: TMap<K, V>, pf: (key: K, value: V) => Option.Option<A>): STM.STM<A>\n} = internal.takeFirst\n\n/**\n * Takes the first matching value, or retries until there is one.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeFirstSTM: {\n  <K, V, A, E, R>(pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>): (self: TMap<K, V>) => STM.STM<A, E, R>\n  <K, V, A, E, R>(self: TMap<K, V>, pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>): STM.STM<A, E, R>\n} = internal.takeFirstSTM\n\n/**\n * Takes all matching values, or retries until there is at least one.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeSome: {\n  <K, V, A>(pf: (key: K, value: V) => Option.Option<A>): (self: TMap<K, V>) => STM.STM<[A, ...Array<A>]>\n  <K, V, A>(self: TMap<K, V>, pf: (key: K, value: V) => Option.Option<A>): STM.STM<[A, ...Array<A>]>\n} = internal.takeSome\n\n/**\n * Takes all matching values, or retries until there is at least one.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeSomeSTM: {\n  <K, V, A, E, R>(\n    pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ): (self: TMap<K, V>) => STM.STM<[A, ...Array<A>], E, R>\n  <K, V, A, E, R>(\n    self: TMap<K, V>,\n    pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ): STM.STM<[A, ...Array<A>], E, R>\n} = internal.takeSomeSTM\n\n/**\n * Collects all bindings into a `Chunk`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toChunk: <K, V>(self: TMap<K, V>) => STM.STM<Chunk.Chunk<[K, V]>> = internal.toChunk\n\n/**\n * Collects all bindings into a `HashMap`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toHashMap: <K, V>(self: TMap<K, V>) => STM.STM<HashMap.HashMap<K, V>> = internal.toHashMap\n\n/**\n * Collects all bindings into an `Array`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toArray: <K, V>(self: TMap<K, V>) => STM.STM<Array<[K, V]>> = internal.toArray\n\n/**\n * Collects all bindings into a `Map`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toMap: <K, V>(self: TMap<K, V>) => STM.STM<ReadonlyMap<K, V>> = internal.toMap\n\n/**\n * Atomically updates all bindings using a pure function.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const transform: {\n  <K, V>(f: (key: K, value: V) => readonly [K, V]): (self: TMap<K, V>) => STM.STM<void>\n  <K, V>(self: TMap<K, V>, f: (key: K, value: V) => readonly [K, V]): STM.STM<void>\n} = internal.transform\n\n/**\n * Atomically updates all bindings using a transactional function.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const transformSTM: {\n  <K, V, R, E>(f: (key: K, value: V) => STM.STM<readonly [K, V], E, R>): (self: TMap<K, V>) => STM.STM<void, E, R>\n  <K, V, R, E>(self: TMap<K, V>, f: (key: K, value: V) => STM.STM<readonly [K, V], E, R>): STM.STM<void, E, R>\n} = internal.transformSTM\n\n/**\n * Atomically updates all values using a pure function.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const transformValues: {\n  <V>(f: (value: V) => V): <K>(self: TMap<K, V>) => STM.STM<void>\n  <K, V>(self: TMap<K, V>, f: (value: V) => V): STM.STM<void>\n} = internal.transformValues\n\n/**\n * Atomically updates all values using a transactional function.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const transformValuesSTM: {\n  <V, R, E>(f: (value: V) => STM.STM<V, E, R>): <K>(self: TMap<K, V>) => STM.STM<void, E, R>\n  <K, V, R, E>(self: TMap<K, V>, f: (value: V) => STM.STM<V, E, R>): STM.STM<void, E, R>\n} = internal.transformValuesSTM\n\n/**\n * Updates the mapping for the specified key with the specified function,\n * which takes the current value of the key as an input, if it exists, and\n * either returns `Some` with a new value to indicate to update the value in\n * the map or `None` to remove the value from the map. Returns `Some` with the\n * updated value or `None` if the value was removed from the map.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const updateWith: {\n  <K, V>(\n    key: K,\n    f: (value: Option.Option<V>) => Option.Option<V>\n  ): (self: TMap<K, V>) => STM.STM<Option.Option<V>>\n  <K, V>(\n    self: TMap<K, V>,\n    key: K,\n    f: (value: Option.Option<V>) => Option.Option<V>\n  ): STM.STM<Option.Option<V>>\n} = internal.updateWith\n\n/**\n * Collects all values stored in map.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const values: <K, V>(self: TMap<K, V>) => STM.STM<Array<V>> = internal.values\n"
  },
  {
    "path": "packages/effect/src/TPriorityQueue.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Chunk from \"./Chunk.js\"\nimport * as internal from \"./internal/stm/tPriorityQueue.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Order from \"./Order.js\"\nimport type { Predicate } from \"./Predicate.js\"\nimport type * as SortedMap from \"./SortedMap.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as TRef from \"./TRef.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TPriorityQueueTypeId: unique symbol = internal.TPriorityQueueTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TPriorityQueueTypeId = typeof TPriorityQueueTypeId\n\n/**\n * A `TPriorityQueue` contains values of type `A` that an `Order` is defined\n * on. Unlike a `TQueue`, `take` returns the highest priority value (the value\n * that is first in the specified ordering) as opposed to the first value\n * offered to the queue. The ordering that elements with the same priority will\n * be taken from the queue is not guaranteed.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface TPriorityQueue<in out A> extends TPriorityQueue.Variance<A> {}\n/**\n * @internal\n * @since 2.0.0\n */\nexport interface TPriorityQueue<in out A> {\n  /** @internal */\n  readonly ref: TRef.TRef<SortedMap.SortedMap<A, [A, ...Array<A>]>>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace TPriorityQueue {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A> {\n    readonly [TPriorityQueueTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * Constructs a new empty `TPriorityQueue` with the specified `Order`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: <A>(order: Order.Order<A>) => STM.STM<TPriorityQueue<A>> = internal.empty\n\n/**\n * Creates a new `TPriorityQueue` from an iterable collection of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: <A>(\n  order: Order.Order<A>\n) => (iterable: Iterable<A>) => STM.STM<TPriorityQueue<A>> = internal.fromIterable\n\n/**\n * Checks whether the queue is empty.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isEmpty: <A>(self: TPriorityQueue<A>) => STM.STM<boolean> = internal.isEmpty\n\n/**\n * Checks whether the queue is not empty.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isNonEmpty: <A>(self: TPriorityQueue<A>) => STM.STM<boolean> = internal.isNonEmpty\n\n/**\n * Makes a new `TPriorityQueue` that is initialized with specified values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A>(order: Order.Order<A>) => (...elements: Array<A>) => STM.STM<TPriorityQueue<A>> = internal.make\n\n/**\n * Offers the specified value to the queue.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const offer: {\n  <A>(value: A): (self: TPriorityQueue<A>) => STM.STM<void>\n  <A>(self: TPriorityQueue<A>, value: A): STM.STM<void>\n} = internal.offer\n\n/**\n * Offers all of the elements in the specified collection to the queue.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const offerAll: {\n  <A>(values: Iterable<A>): (self: TPriorityQueue<A>) => STM.STM<void>\n  <A>(self: TPriorityQueue<A>, values: Iterable<A>): STM.STM<void>\n} = internal.offerAll\n\n/**\n * Peeks at the first value in the queue without removing it, retrying until a\n * value is in the queue.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const peek: <A>(self: TPriorityQueue<A>) => STM.STM<A> = internal.peek\n\n/**\n * Peeks at the first value in the queue without removing it, returning `None`\n * if there is not a value in the queue.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const peekOption: <A>(self: TPriorityQueue<A>) => STM.STM<Option.Option<A>> = internal.peekOption\n\n/**\n * Removes all elements from the queue matching the specified predicate.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const removeIf: {\n  <A>(predicate: Predicate<A>): (self: TPriorityQueue<A>) => STM.STM<void>\n  <A>(self: TPriorityQueue<A>, predicate: Predicate<A>): STM.STM<void>\n} = internal.removeIf\n\n/**\n * Retains only elements from the queue matching the specified predicate.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const retainIf: {\n  <A>(predicate: Predicate<A>): (self: TPriorityQueue<A>) => STM.STM<void>\n  <A>(self: TPriorityQueue<A>, predicate: Predicate<A>): STM.STM<void>\n} = internal.retainIf\n\n/**\n * Returns the size of the queue.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <A>(self: TPriorityQueue<A>) => STM.STM<number> = internal.size\n\n/**\n * Takes a value from the queue, retrying until a value is in the queue.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const take: <A>(self: TPriorityQueue<A>) => STM.STM<A> = internal.take\n\n/**\n * Takes all values from the queue.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeAll: <A>(self: TPriorityQueue<A>) => STM.STM<Array<A>> = internal.takeAll\n\n/**\n * Takes a value from the queue, returning `None` if there is not a value in\n * the queue.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeOption: <A>(self: TPriorityQueue<A>) => STM.STM<Option.Option<A>> = internal.takeOption\n\n/**\n * Takes up to the specified maximum number of elements from the queue.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeUpTo: {\n  (n: number): <A>(self: TPriorityQueue<A>) => STM.STM<Array<A>>\n  <A>(self: TPriorityQueue<A>, n: number): STM.STM<Array<A>>\n} = internal.takeUpTo\n\n/**\n * Collects all values into a `Chunk`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toChunk: <A>(self: TPriorityQueue<A>) => STM.STM<Chunk.Chunk<A>> = internal.toChunk\n\n/**\n * Collects all values into an array.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toArray: <A>(self: TPriorityQueue<A>) => STM.STM<Array<A>> = internal.toArray\n"
  },
  {
    "path": "packages/effect/src/TPubSub.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport * as internal from \"./internal/stm/tPubSub.js\"\nimport type * as tQueue from \"./internal/stm/tQueue.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as TQueue from \"./TQueue.js\"\nimport type * as TRef from \"./TRef.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TPubSubTypeId: unique symbol = internal.TPubSubTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TPubSubTypeId = typeof TPubSubTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface TPubSub<in out A> extends TQueue.TEnqueue<A> {\n  readonly [TPubSubTypeId]: {\n    readonly _A: Types.Invariant<A>\n  }\n}\n/**\n * @internal\n * @since 2.0.0\n */\nexport interface TPubSub<in out A> {\n  /** @internal */\n  readonly pubsubSize: TRef.TRef<number>\n  /** @internal */\n  readonly publisherHead: TRef.TRef<TRef.TRef<internal.Node<A> | undefined>>\n  /** @internal */\n  readonly publisherTail: TRef.TRef<TRef.TRef<internal.Node<A> | undefined> | undefined>\n  /** @internal */\n  readonly requestedCapacity: number\n  /** @internal */\n  readonly strategy: tQueue.TQueueStrategy\n  /** @internal */\n  readonly subscriberCount: TRef.TRef<number>\n  /** @internal */\n  readonly subscribers: TRef.TRef<HashSet.HashSet<TRef.TRef<TRef.TRef<internal.Node<A>> | undefined>>>\n}\n\n/**\n * Waits until the `TPubSub` is shutdown. The `STM` returned by this method will\n * not resume until the queue has been shutdown. If the `TPubSub` is already\n * shutdown, the `STM` will resume right away.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const awaitShutdown: <A>(self: TPubSub<A>) => STM.STM<void> = internal.awaitShutdown\n\n/**\n * Creates a bounded `TPubSub` with the back pressure strategy. The `TPubSub` will retain\n * messages until they have been taken by all subscribers, applying back\n * pressure to publishers if the `TPubSub` is at capacity.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const bounded: <A>(requestedCapacity: number) => STM.STM<TPubSub<A>> = internal.bounded\n\n/**\n * Returns the number of elements the `TPubSub` can hold.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const capacity: <A>(self: TPubSub<A>) => number = internal.capacity\n\n/**\n * Creates a bounded `TPubSub` with the dropping strategy. The `TPubSub` will drop new\n * messages if the `TPubSub` is at capacity.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dropping: <A>(requestedCapacity: number) => STM.STM<TPubSub<A>> = internal.dropping\n\n/**\n * Returns `true` if the `TPubSub` contains zero elements, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isEmpty: <A>(self: TPubSub<A>) => STM.STM<boolean> = internal.isEmpty\n\n/**\n * Returns `true` if the `TPubSub` contains at least one element, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isFull: <A>(self: TPubSub<A>) => STM.STM<boolean> = internal.isFull\n\n/**\n * Interrupts any fibers that are suspended on `offer` or `take`. Future calls\n * to `offer*` and `take*` will be interrupted immediately.\n *\n * @since 2.0.0\n * @category utils\n */\nexport const shutdown: <A>(self: TPubSub<A>) => STM.STM<void> = internal.shutdown\n\n/**\n * Returns `true` if `shutdown` has been called, otherwise returns `false`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isShutdown: <A>(self: TPubSub<A>) => STM.STM<boolean> = internal.isShutdown\n\n/**\n * Publishes a message to the `TPubSub`, returning whether the message was published\n * to the `TPubSub`.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const publish: {\n  <A>(value: A): (self: TPubSub<A>) => STM.STM<boolean>\n  <A>(self: TPubSub<A>, value: A): STM.STM<boolean>\n} = internal.publish\n\n/**\n * Publishes all of the specified messages to the `TPubSub`, returning whether they\n * were published to the `TPubSub`.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const publishAll: {\n  <A>(iterable: Iterable<A>): (self: TPubSub<A>) => STM.STM<boolean>\n  <A>(self: TPubSub<A>, iterable: Iterable<A>): STM.STM<boolean>\n} = internal.publishAll\n\n/**\n * Retrieves the size of the `TPubSub`, which is equal to the number of elements\n * in the `TPubSub`. This may be negative if fibers are suspended waiting for\n * elements to be added to the `TPubSub`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <A>(self: TPubSub<A>) => STM.STM<number> = internal.size\n\n/**\n * Creates a bounded `TPubSub` with the sliding strategy. The `TPubSub` will add new\n * messages and drop old messages if the `TPubSub` is at capacity.\n *\n * For best performance use capacities that are powers of two.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sliding: <A>(requestedCapacity: number) => STM.STM<TPubSub<A>> = internal.sliding\n\n/**\n * Subscribes to receive messages from the `TPubSub`. The resulting subscription can\n * be evaluated multiple times to take a message from the `TPubSub` each time. The\n * caller is responsible for unsubscribing from the `TPubSub` by shutting down the\n * queue.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const subscribe: <A>(self: TPubSub<A>) => STM.STM<TQueue.TDequeue<A>> = internal.subscribe\n\n/**\n * Subscribes to receive messages from the `TPubSub`. The resulting subscription can\n * be evaluated multiple times within the scope to take a message from the `TPubSub`\n * each time.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const subscribeScoped: <A>(self: TPubSub<A>) => Effect.Effect<TQueue.TDequeue<A>, never, Scope.Scope> =\n  internal.subscribeScoped\n\n/**\n * Creates an unbounded `TPubSub`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unbounded: <A>() => STM.STM<TPubSub<A>> = internal.unbounded\n"
  },
  {
    "path": "packages/effect/src/TQueue.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/stm/tQueue.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Predicate } from \"./Predicate.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TDequeueTypeId: unique symbol = internal.TDequeueTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TDequeueTypeId = typeof TDequeueTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TEnqueueTypeId: unique symbol = internal.TEnqueueTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TEnqueueTypeId = typeof TEnqueueTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface TQueue<in out A> extends TEnqueue<A>, TDequeue<A> {}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface TEnqueue<in A> extends TQueue.TEnqueueVariance<A>, BaseTQueue {\n  /**\n   * Places one value in the queue.\n   */\n  offer(value: A): STM.STM<boolean>\n\n  /**\n   * For Bounded TQueue: uses the `BackPressure` Strategy, places the values in\n   * the queue and always returns true. If the queue has reached capacity, then\n   * the fiber performing the `offerAll` will be suspended until there is room\n   * in the queue.\n   *\n   * For Unbounded TQueue: Places all values in the queue and returns true.\n   *\n   * For Sliding TQueue: uses `Sliding` Strategy If there is room in the queue,\n   * it places the values otherwise it removes the old elements and enqueues the\n   * new ones. Always returns true.\n   *\n   * For Dropping TQueue: uses `Dropping` Strategy, It places the values in the\n   * queue but if there is no room it will not enqueue them and return false.\n   */\n  offerAll(iterable: Iterable<A>): STM.STM<boolean>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface TDequeue<out A> extends TQueue.TDequeueVariance<A>, BaseTQueue {\n  /**\n   * Views the next element in the queue without removing it, retrying if the\n   * queue is empty.\n   */\n  readonly peek: STM.STM<A>\n\n  /**\n   * Views the next element in the queue without removing it, returning `None`\n   * if the queue is empty.\n   */\n  readonly peekOption: STM.STM<Option.Option<A>>\n\n  /**\n   * Takes the oldest value in the queue. If the queue is empty, this will return\n   * a computation that resumes when an item has been added to the queue.\n   */\n  readonly take: STM.STM<A>\n\n  /**\n   * Takes all the values in the queue and returns the values. If the queue is\n   * empty returns an empty collection.\n   */\n  readonly takeAll: STM.STM<Array<A>>\n\n  /**\n   * Takes up to max number of values from the queue.\n   */\n  takeUpTo(max: number): STM.STM<Array<A>>\n}\n\n/**\n * The base interface that all `TQueue`s must implement.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface BaseTQueue {\n  /**\n   * Returns the number of elements the queue can hold.\n   */\n  capacity(): number\n\n  /**\n   * Retrieves the size of the queue, which is equal to the number of elements\n   * in the queue. This may be negative if fibers are suspended waiting for\n   * elements to be added to the queue.\n   */\n  readonly size: STM.STM<number>\n\n  /**\n   * Returns `true` if the `TQueue` contains at least one element, `false`\n   * otherwise.\n   */\n  readonly isFull: STM.STM<boolean>\n\n  /**\n   * Returns `true` if the `TQueue` contains zero elements, `false` otherwise.\n   */\n  readonly isEmpty: STM.STM<boolean>\n\n  /**\n   * Interrupts any fibers that are suspended on `offer` or `take`. Future calls\n   * to `offer*` and `take*` will be interrupted immediately.\n   */\n  readonly shutdown: STM.STM<void>\n\n  /**\n   * Returns `true` if `shutdown` has been called, otherwise returns `false`.\n   */\n  readonly isShutdown: STM.STM<boolean>\n\n  /**\n   * Waits until the queue is shutdown. The `STM` returned by this method will\n   * not resume until the queue has been shutdown. If the queue is already\n   * shutdown, the `STM` will resume right away.\n   */\n  readonly awaitShutdown: STM.STM<void>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace TQueue {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface TEnqueueVariance<in A> {\n    readonly [TEnqueueTypeId]: {\n      readonly _In: Types.Contravariant<A>\n    }\n  }\n\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface TDequeueVariance<out A> {\n    readonly [TDequeueTypeId]: {\n      readonly _Out: Types.Covariant<A>\n    }\n  }\n}\n\n/**\n * Returns `true` if the specified value is a `TQueue`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isTQueue: (u: unknown) => u is TQueue<unknown> = internal.isTQueue\n\n/**\n * Returns `true` if the specified value is a `TDequeue`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isTDequeue: (u: unknown) => u is TDequeue<unknown> = internal.isTDequeue\n\n/**\n * Returns `true` if the specified value is a `TEnqueue`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isTEnqueue: (u: unknown) => u is TEnqueue<unknown> = internal.isTEnqueue\n\n/**\n * Waits until the queue is shutdown. The `STM` returned by this method will\n * not resume until the queue has been shutdown. If the queue is already\n * shutdown, the `STM` will resume right away.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const awaitShutdown: <A>(self: TDequeue<A> | TEnqueue<A>) => STM.STM<void> = internal.awaitShutdown\n\n/**\n * Creates a bounded queue with the back pressure strategy. The queue will\n * retain values until they have been taken, applying back pressure to\n * offerors if the queue is at capacity.\n *\n * For best performance use capacities that are powers of two.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const bounded: <A>(requestedCapacity: number) => STM.STM<TQueue<A>> = internal.bounded\n\n/**\n * Returns the number of elements the queue can hold.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const capacity: <A>(self: TDequeue<A> | TEnqueue<A>) => number = internal.capacity\n\n/**\n * Creates a bounded queue with the dropping strategy. The queue will drop new\n * values if the queue is at capacity.\n *\n * For best performance use capacities that are powers of two.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dropping: <A>(requestedCapacity: number) => STM.STM<TQueue<A>> = internal.dropping\n\n/**\n * Returns `true` if the `TQueue` contains zero elements, `false` otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isEmpty: <A>(self: TDequeue<A> | TEnqueue<A>) => STM.STM<boolean> = internal.isEmpty\n\n/**\n * Returns `true` if the `TQueue` contains at least one element, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isFull: <A>(self: TDequeue<A> | TEnqueue<A>) => STM.STM<boolean> = internal.isFull\n\n/**\n * Returns `true` if `shutdown` has been called, otherwise returns `false`.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isShutdown: <A>(self: TDequeue<A> | TEnqueue<A>) => STM.STM<boolean> = internal.isShutdown\n\n/**\n * Places one value in the queue.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const offer: {\n  <A>(value: A): (self: TEnqueue<A>) => STM.STM<void>\n  <A>(self: TEnqueue<A>, value: A): STM.STM<void>\n} = internal.offer\n\n/**\n * For Bounded TQueue: uses the `BackPressure` Strategy, places the values in\n * the queue and always returns true. If the queue has reached capacity, then\n * the fiber performing the `offerAll` will be suspended until there is room\n * in the queue.\n *\n * For Unbounded TQueue: Places all values in the queue and returns true.\n *\n * For Sliding TQueue: uses `Sliding` Strategy If there is room in the queue,\n * it places the values otherwise it removes the old elements and enqueues the\n * new ones. Always returns true.\n *\n * For Dropping TQueue: uses `Dropping` Strategy, It places the values in the\n * queue but if there is no room it will not enqueue them and return false.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const offerAll: {\n  <A>(iterable: Iterable<A>): (self: TEnqueue<A>) => STM.STM<boolean>\n  <A>(self: TEnqueue<A>, iterable: Iterable<A>): STM.STM<boolean>\n} = internal.offerAll\n\n/**\n * Views the next element in the queue without removing it, retrying if the\n * queue is empty.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const peek: <A>(self: TDequeue<A>) => STM.STM<A> = internal.peek\n\n/**\n * Views the next element in the queue without removing it, returning `None`\n * if the queue is empty.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const peekOption: <A>(self: TDequeue<A>) => STM.STM<Option.Option<A>> = internal.peekOption\n\n/**\n * Takes a single element from the queue, returning `None` if the queue is\n * empty.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const poll: <A>(self: TDequeue<A>) => STM.STM<Option.Option<A>> = internal.poll\n\n/**\n * Drops elements from the queue while they do not satisfy the predicate,\n * taking and returning the first element that does satisfy the predicate.\n * Retries if no elements satisfy the predicate.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const seek: {\n  <A>(predicate: Predicate<A>): (self: TDequeue<A>) => STM.STM<A>\n  <A>(self: TDequeue<A>, predicate: Predicate<A>): STM.STM<A>\n} = internal.seek\n\n/**\n * Interrupts any fibers that are suspended on `offer` or `take`. Future calls\n * to `offer*` and `take*` will be interrupted immediately.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const shutdown: <A>(self: TDequeue<A> | TEnqueue<A>) => STM.STM<void> = internal.shutdown\n\n/**\n * Retrieves the size of the queue, which is equal to the number of elements\n * in the queue. This may be negative if fibers are suspended waiting for\n * elements to be added to the queue.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <A>(self: TDequeue<A> | TEnqueue<A>) => STM.STM<number> = internal.size\n\n/**\n * Creates a bounded queue with the sliding strategy. The queue will add new\n * values and drop old values if the queue is at capacity.\n *\n * For best performance use capacities that are powers of two.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const sliding: <A>(requestedCapacity: number) => STM.STM<TQueue<A>> = internal.sliding\n\n/**\n * Takes the oldest value in the queue. If the queue is empty, this will return\n * a computation that resumes when an item has been added to the queue.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const take: <A>(self: TDequeue<A>) => STM.STM<A> = internal.take\n\n/**\n * Takes all the values in the queue and returns the values. If the queue is\n * empty returns an empty collection.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeAll: <A>(self: TDequeue<A>) => STM.STM<Array<A>> = internal.takeAll\n\n/**\n * Takes a number of elements from the queue between the specified minimum and\n * maximum. If there are fewer than the minimum number of elements available,\n * retries until at least the minimum number of elements have been collected.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeBetween: {\n  (min: number, max: number): <A>(self: TDequeue<A>) => STM.STM<Array<A>>\n  <A>(self: TDequeue<A>, min: number, max: number): STM.STM<Array<A>>\n} = internal.takeBetween\n\n/**\n * Takes the specified number of elements from the queue. If there are fewer\n * than the specified number of elements available, it retries until they\n * become available.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeN: {\n  (n: number): <A>(self: TDequeue<A>) => STM.STM<Array<A>>\n  <A>(self: TDequeue<A>, n: number): STM.STM<Array<A>>\n} = internal.takeN\n\n/**\n * Takes up to max number of values from the queue.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeUpTo: {\n  (max: number): <A>(self: TDequeue<A>) => STM.STM<Array<A>>\n  <A>(self: TDequeue<A>, max: number): STM.STM<Array<A>>\n} = internal.takeUpTo\n\n/**\n * Creates an unbounded queue.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const unbounded: <A>() => STM.STM<TQueue<A>> = internal.unbounded\n"
  },
  {
    "path": "packages/effect/src/TRandom.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Context from \"./Context.js\"\nimport * as internal from \"./internal/stm/tRandom.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as TRef from \"./TRef.js\"\nimport type * as Random from \"./Utils.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TRandomTypeId: unique symbol = internal.TRandomTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TRandomTypeId = typeof TRandomTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface TRandom {\n  readonly [TRandomTypeId]: TRandomTypeId\n  /**\n   * Returns the next numeric value from the pseudo-random number generator.\n   */\n  readonly next: STM.STM<number>\n  /**\n   * Returns the next boolean value from the pseudo-random number generator.\n   */\n  readonly nextBoolean: STM.STM<boolean>\n  /**\n   * Returns the next integer value from the pseudo-random number generator.\n   */\n  readonly nextInt: STM.STM<number>\n  /**\n   * Returns the next numeric value in the specified range from the\n   * pseudo-random number generator.\n   */\n  nextRange(min: number, max: number): STM.STM<number>\n  /**\n   * Returns the next integer value in the specified range from the\n   * pseudo-random number generator.\n   */\n  nextIntBetween(min: number, max: number): STM.STM<number>\n  /**\n   * Uses the pseudo-random number generator to shuffle the specified iterable.\n   */\n  shuffle<A>(elements: Iterable<A>): STM.STM<Array<A>>\n}\n/**\n * @internal\n * @since 2.0.0\n */\nexport interface TRandom {\n  /** @internal */\n  readonly state: TRef.TRef<Random.PCGRandomState>\n}\n\n/**\n * The service tag used to access `TRandom` in the environment of an effect.\n *\n * @since 2.0.0\n * @category context\n */\nexport const Tag: Context.Tag<TRandom, TRandom> = internal.Tag\n\n/**\n * The \"live\" `TRandom` service wrapped into a `Layer`.\n *\n * @since 2.0.0\n * @category context\n */\nexport const live: Layer.Layer<TRandom> = internal.live\n\n/**\n * Returns the next number from the pseudo-random number generator.\n *\n * @since 2.0.0\n * @category random\n */\nexport const next: STM.STM<number, never, TRandom> = internal.next\n\n/**\n * Returns the next boolean value from the pseudo-random number generator.\n *\n * @since 2.0.0\n * @category random\n */\nexport const nextBoolean: STM.STM<boolean, never, TRandom> = internal.nextBoolean\n\n/**\n * Returns the next integer from the pseudo-random number generator.\n *\n * @since 2.0.0\n * @category random\n */\nexport const nextInt: STM.STM<number, never, TRandom> = internal.nextInt\n\n/**\n * Returns the next integer in the specified range from the pseudo-random number\n * generator.\n *\n * @since 2.0.0\n * @category random\n */\nexport const nextIntBetween: (low: number, high: number) => STM.STM<number, never, TRandom> = internal.nextIntBetween\n\n/**\n * Returns the next number in the specified range from the pseudo-random number\n * generator.\n *\n * @since 2.0.0\n * @category random\n */\nexport const nextRange: (min: number, max: number) => STM.STM<number, never, TRandom> = internal.nextRange\n\n/**\n * Uses the pseudo-random number generator to shuffle the specified iterable.\n *\n * @since 2.0.0\n * @category random\n */\nexport const shuffle: <A>(elements: Iterable<A>) => STM.STM<Array<A>, never, TRandom> = internal.shuffle\n"
  },
  {
    "path": "packages/effect/src/TReentrantLock.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/stm/tReentrantLock.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as TRef from \"./TRef.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TReentrantLockTypeId: unique symbol = internal.TReentrantLockTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TReentrantLockTypeId = typeof TReentrantLockTypeId\n\n/**\n * A `TReentrantLock` is a reentrant read/write lock. Multiple readers may all\n * concurrently acquire read locks. Only one writer is allowed to acquire a\n * write lock at any given time. Read locks may be upgraded into write locks. A\n * fiber that has a write lock may acquire other write locks or read locks.\n *\n * The two primary methods of this structure are `readLock`, which acquires a\n * read lock in a scoped context, and `writeLock`, which acquires a write lock\n * in a scoped context.\n *\n * Although located in the STM package, there is no need for locks within STM\n * transactions. However, this lock can be quite useful in effectful code, to\n * provide consistent read/write access to mutable state; and being in STM\n * allows this structure to be composed into more complicated concurrent\n * structures that are consumed from effectful code.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface TReentrantLock extends TReentrantLock.Proto {}\n/**\n * @internal\n * @since 2.0.0\n */\nexport interface TReentrantLock {\n  /** @internal */\n  readonly state: TRef.TRef<internal.LockState>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace TReentrantLock {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Proto {\n    readonly [TReentrantLockTypeId]: TReentrantLockTypeId\n  }\n}\n\n/**\n * Acquires a read lock. The transaction will suspend until no other fiber is\n * holding a write lock. Succeeds with the number of read locks held by this\n * fiber.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const acquireRead: (self: TReentrantLock) => STM.STM<number> = internal.acquireRead\n\n/**\n * Acquires a write lock. The transaction will suspend until no other fibers\n * are holding read or write locks. Succeeds with the number of write locks\n * held by this fiber.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const acquireWrite: (self: TReentrantLock) => STM.STM<number> = internal.acquireWrite\n\n/**\n * Retrieves the number of acquired read locks for this fiber.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const fiberReadLocks: (self: TReentrantLock) => STM.STM<number> = internal.fiberReadLocks\n\n/**\n * Retrieves the number of acquired write locks for this fiber.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const fiberWriteLocks: (self: TReentrantLock) => STM.STM<number> = internal.fiberWriteLocks\n\n/**\n * Just a convenience method for applications that only need reentrant locks,\n * without needing a distinction between readers / writers.\n *\n * See `TReentrantLock.writeLock`.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const lock: (self: TReentrantLock) => Effect.Effect<number, never, Scope.Scope> = internal.lock\n\n/**\n * Determines if any fiber has a read or write lock.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const locked: (self: TReentrantLock) => STM.STM<boolean> = internal.locked\n\n/**\n * Makes a new reentrant read/write lock.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: STM.STM<TReentrantLock> = internal.make\n\n/**\n * Obtains a read lock in a scoped context.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const readLock: (self: TReentrantLock) => Effect.Effect<number, never, Scope.Scope> = internal.readLock\n\n/**\n * Retrieves the total number of acquired read locks.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const readLocks: (self: TReentrantLock) => STM.STM<number> = internal.readLocks\n\n/**\n * Determines if any fiber has a read lock.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const readLocked: (self: TReentrantLock) => STM.STM<boolean> = internal.readLocked\n\n/**\n * Releases a read lock held by this fiber. Succeeds with the outstanding\n * number of read locks held by this fiber.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const releaseRead: (self: TReentrantLock) => STM.STM<number> = internal.releaseRead\n\n/**\n * Releases a write lock held by this fiber. Succeeds with the outstanding\n * number of write locks held by this fiber.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const releaseWrite: (self: TReentrantLock) => STM.STM<number> = internal.releaseWrite\n\n/**\n * Runs the specified workflow with a lock.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const withLock: {\n  (self: TReentrantLock): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(effect: Effect.Effect<A, E, R>, self: TReentrantLock): Effect.Effect<A, E, R>\n} = internal.withLock\n\n/**\n * Runs the specified workflow with a read lock.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const withReadLock: {\n  (self: TReentrantLock): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(effect: Effect.Effect<A, E, R>, self: TReentrantLock): Effect.Effect<A, E, R>\n} = internal.withReadLock\n\n/**\n * Runs the specified workflow with a write lock.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const withWriteLock: {\n  (self: TReentrantLock): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(effect: Effect.Effect<A, E, R>, self: TReentrantLock): Effect.Effect<A, E, R>\n} = internal.withWriteLock\n\n/**\n * Obtains a write lock in a scoped context.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const writeLock: (self: TReentrantLock) => Effect.Effect<number, never, Scope.Scope> = internal.writeLock\n\n/**\n * Determines if a write lock is held by some fiber.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const writeLocked: (self: TReentrantLock) => STM.STM<boolean> = internal.writeLocked\n\n/**\n * Computes the number of write locks held by fibers.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const writeLocks: (self: TReentrantLock) => STM.STM<number> = internal.writeLocks\n"
  },
  {
    "path": "packages/effect/src/TRef.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport type * as Journal from \"./internal/stm/journal.js\"\nimport * as internal from \"./internal/stm/tRef.js\"\nimport type * as TxnId from \"./internal/stm/txnId.js\"\nimport type * as Versioned from \"./internal/stm/versioned.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TRefTypeId: unique symbol = internal.TRefTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TRefTypeId = typeof TRefTypeId\n\n/**\n * A `TRef<A>` is a purely functional description of a mutable reference that can\n * be modified as part of a transactional effect. The fundamental operations of\n * a `TRef` are `set` and `get`. `set` transactionally sets the reference to a\n * new value. `get` gets the current value of the reference.\n *\n * NOTE: While `TRef<A>` provides the transactional equivalent of a mutable\n * reference, the value inside the `TRef` should be immutable.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface TRef<in out A> extends TRef.Variance<A>, Pipeable {\n  /**\n   * Note: the method is unbound, exposed only for potential extensions.\n   */\n  modify<B>(f: (a: A) => readonly [B, A]): STM.STM<B>\n}\n/**\n * @internal\n * @since 2.0.0\n */\nexport interface TRef<in out A> {\n  /** @internal */\n  todos: Map<TxnId.TxnId, Journal.Todo>\n  /** @internal */\n  versioned: Versioned.Versioned<A>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace TRef {\n  /**\n   * @since 2.0.0\n   */\n  export interface Variance<in out A> {\n    readonly [TRefTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const get: <A>(self: TRef<A>) => STM.STM<A> = internal.get\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const getAndSet: {\n  <A>(value: A): (self: TRef<A>) => STM.STM<A>\n  <A>(self: TRef<A>, value: A): STM.STM<A>\n} = internal.getAndSet\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const getAndUpdate: {\n  <A>(f: (a: A) => A): (self: TRef<A>) => STM.STM<A>\n  <A>(self: TRef<A>, f: (a: A) => A): STM.STM<A>\n} = internal.getAndUpdate\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const getAndUpdateSome: {\n  <A>(f: (a: A) => Option.Option<A>): (self: TRef<A>) => STM.STM<A>\n  <A>(self: TRef<A>, f: (a: A) => Option.Option<A>): STM.STM<A>\n} = internal.getAndUpdateSome\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A>(value: A) => STM.STM<TRef<A>> = internal.make\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const modify: {\n  <A, B>(f: (a: A) => readonly [B, A]): (self: TRef<A>) => STM.STM<B>\n  <A, B>(self: TRef<A>, f: (a: A) => readonly [B, A]): STM.STM<B>\n} = internal.modify\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const modifySome: {\n  <A, B>(fallback: B, f: (a: A) => Option.Option<readonly [B, A]>): (self: TRef<A>) => STM.STM<B>\n  <A, B>(self: TRef<A>, fallback: B, f: (a: A) => Option.Option<readonly [B, A]>): STM.STM<B>\n} = internal.modifySome\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const set: {\n  <A>(value: A): (self: TRef<A>) => STM.STM<void>\n  <A>(self: TRef<A>, value: A): STM.STM<void>\n} = internal.set\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const setAndGet: {\n  <A>(value: A): (self: TRef<A>) => STM.STM<A>\n  <A>(self: TRef<A>, value: A): STM.STM<A>\n} = internal.setAndGet\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const update: {\n  <A>(f: (a: A) => A): (self: TRef<A>) => STM.STM<void>\n  <A>(self: TRef<A>, f: (a: A) => A): STM.STM<void>\n} = internal.update\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const updateAndGet: {\n  <A>(f: (a: A) => A): (self: TRef<A>) => STM.STM<A>\n  <A>(self: TRef<A>, f: (a: A) => A): STM.STM<A>\n} = internal.updateAndGet\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const updateSome: {\n  <A>(f: (a: A) => Option.Option<A>): (self: TRef<A>) => STM.STM<void>\n  <A>(self: TRef<A>, f: (a: A) => Option.Option<A>): STM.STM<void>\n} = internal.updateSome\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const updateSomeAndGet: {\n  <A>(f: (a: A) => Option.Option<A>): (self: TRef<A>) => STM.STM<A>\n  <A>(self: TRef<A>, f: (a: A) => Option.Option<A>): STM.STM<A>\n} = internal.updateSomeAndGet\n"
  },
  {
    "path": "packages/effect/src/TSemaphore.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/stm/tSemaphore.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as TRef from \"./TRef.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TSemaphoreTypeId: unique symbol = internal.TSemaphoreTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TSemaphoreTypeId = typeof TSemaphoreTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface TSemaphore extends TSemaphore.Proto {}\n/**\n * @internal\n * @since 2.0.0\n */\nexport interface TSemaphore {\n  /** @internal */\n  readonly permits: TRef.TRef<number>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace TSemaphore {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Proto {\n    readonly [TSemaphoreTypeId]: TSemaphoreTypeId\n  }\n}\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const acquire: (self: TSemaphore) => STM.STM<void> = internal.acquire\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const acquireN: {\n  (n: number): (self: TSemaphore) => STM.STM<void>\n  (self: TSemaphore, n: number): STM.STM<void>\n} = internal.acquireN\n\n/**\n * @since 2.0.0\n * @category getters\n */\nexport const available: (self: TSemaphore) => STM.STM<number> = internal.available\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (permits: number) => STM.STM<TSemaphore> = internal.make\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const release: (self: TSemaphore) => STM.STM<void> = internal.release\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const releaseN: {\n  (n: number): (self: TSemaphore) => STM.STM<void>\n  (self: TSemaphore, n: number): STM.STM<void>\n} = internal.releaseN\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const withPermit: {\n  (semaphore: TSemaphore): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, semaphore: TSemaphore): Effect.Effect<A, E, R>\n} = internal.withPermit\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const withPermits: {\n  (semaphore: TSemaphore, permits: number): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, semaphore: TSemaphore, permits: number): Effect.Effect<A, E, R>\n} = internal.withPermits\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const withPermitScoped: (self: TSemaphore) => Effect.Effect<void, never, Scope.Scope> = internal.withPermitScoped\n\n/**\n * @since 2.0.0\n * @category mutations\n */\nexport const withPermitsScoped: {\n  (permits: number): (self: TSemaphore) => Effect.Effect<void, never, Scope.Scope>\n  (self: TSemaphore, permits: number): Effect.Effect<void, never, Scope.Scope>\n} = internal.withPermitsScoped\n\n/**\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeMake: (permits: number) => TSemaphore = internal.unsafeMakeSemaphore\n"
  },
  {
    "path": "packages/effect/src/TSet.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as HashSet from \"./HashSet.js\"\nimport * as internal from \"./internal/stm/tSet.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Predicate } from \"./Predicate.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as TMap from \"./TMap.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TSetTypeId: unique symbol = internal.TSetTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TSetTypeId = typeof TSetTypeId\n\n/**\n * Transactional set implemented on top of `TMap`.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface TSet<in out A> extends TSet.Variance<A> {}\n/**\n * @internal\n * @since 2.0.0\n */\nexport interface TSet<in out A> {\n  /** @internal */\n  readonly tMap: TMap.TMap<A, void>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace TSet {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<in out A> {\n    readonly [TSetTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * Stores new element in the set.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const add: {\n  <A>(value: A): (self: TSet<A>) => STM.STM<void>\n  <A>(self: TSet<A>, value: A): STM.STM<void>\n} = internal.add\n\n/**\n * Atomically transforms the set into the difference of itself and the\n * provided set.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const difference: {\n  <A>(other: TSet<A>): (self: TSet<A>) => STM.STM<void>\n  <A>(self: TSet<A>, other: TSet<A>): STM.STM<void>\n} = internal.difference\n\n/**\n * Makes an empty `TSet`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: <A>() => STM.STM<TSet<A>> = internal.empty\n\n/**\n * Atomically performs transactional-effect for each element in set.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const forEach: {\n  <A, R, E>(f: (value: A) => STM.STM<void, E, R>): (self: TSet<A>) => STM.STM<void, E, R>\n  <A, R, E>(self: TSet<A>, f: (value: A) => STM.STM<void, E, R>): STM.STM<void, E, R>\n} = internal.forEach\n\n/**\n * Creates a new `TSet` from an iterable collection of values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: <A>(iterable: Iterable<A>) => STM.STM<TSet<A>> = internal.fromIterable\n\n/**\n * Tests whether or not set contains an element.\n *\n * @since 2.0.0\n * @category elements\n */\nexport const has: {\n  <A>(value: A): (self: TSet<A>) => STM.STM<boolean>\n  <A>(self: TSet<A>, value: A): STM.STM<boolean>\n} = internal.has\n\n/**\n * Atomically transforms the set into the intersection of itself and the\n * provided set.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const intersection: {\n  <A>(other: TSet<A>): (self: TSet<A>) => STM.STM<void>\n  <A>(self: TSet<A>, other: TSet<A>): STM.STM<void>\n} = internal.intersection\n\n/**\n * Tests if the set is empty or not\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isEmpty: <A>(self: TSet<A>) => STM.STM<boolean> = internal.isEmpty\n\n/**\n * Makes a new `TSet` that is initialized with specified values.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Elements extends Array<any>>(\n  ...elements: Elements\n) => STM.STM<TSet<Elements[number]>> = internal.make\n\n/**\n * Atomically folds using a pure function.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const reduce: {\n  <Z, A>(zero: Z, f: (accumulator: Z, value: A) => Z): (self: TSet<A>) => STM.STM<Z>\n  <Z, A>(self: TSet<A>, zero: Z, f: (accumulator: Z, value: A) => Z): STM.STM<Z>\n} = internal.reduce\n\n/**\n * Atomically folds using a transactional function.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const reduceSTM: {\n  <Z, A, R, E>(zero: Z, f: (accumulator: Z, value: A) => STM.STM<Z, E, R>): (self: TSet<A>) => STM.STM<Z, E, R>\n  <Z, A, R, E>(self: TSet<A>, zero: Z, f: (accumulator: Z, value: A) => STM.STM<Z, E, R>): STM.STM<Z, E, R>\n} = internal.reduceSTM\n\n/**\n * Removes a single element from the set.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const remove: {\n  <A>(value: A): (self: TSet<A>) => STM.STM<void>\n  <A>(self: TSet<A>, value: A): STM.STM<void>\n} = internal.remove\n\n/**\n * Removes elements from the set.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const removeAll: {\n  <A>(iterable: Iterable<A>): (self: TSet<A>) => STM.STM<void>\n  <A>(self: TSet<A>, iterable: Iterable<A>): STM.STM<void>\n} = internal.removeAll\n\n/**\n * Removes entries from a `TSet` that satisfy the specified predicate and returns the removed entries\n * (or `void` if `discard = true`).\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const removeIf: {\n  <A>(predicate: Predicate<A>, options: {\n    readonly discard: true\n  }): (self: TSet<A>) => STM.STM<void>\n  <A>(\n    predicate: Predicate<A>,\n    options?: {\n      readonly discard: false\n    }\n  ): (self: TSet<A>) => STM.STM<Array<A>>\n  <A>(self: TSet<A>, predicate: Predicate<A>, options: {\n    readonly discard: true\n  }): STM.STM<void>\n  <A>(\n    self: TSet<A>,\n    predicate: Predicate<A>,\n    options?: {\n      readonly discard: false\n    }\n  ): STM.STM<Array<A>>\n} = internal.removeIf\n\n/**\n * Retains entries in a `TSet` that satisfy the specified predicate and returns the removed entries\n * (or `void` if `discard = true`).\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const retainIf: {\n  <A>(predicate: Predicate<A>, options: {\n    readonly discard: true\n  }): (self: TSet<A>) => STM.STM<void>\n  <A>(\n    predicate: Predicate<A>,\n    options?: {\n      readonly discard: false\n    }\n  ): (self: TSet<A>) => STM.STM<Array<A>>\n  <A>(self: TSet<A>, predicate: Predicate<A>, options: {\n    readonly discard: true\n  }): STM.STM<void>\n  <A>(\n    self: TSet<A>,\n    predicate: Predicate<A>,\n    options?: {\n      readonly discard: false\n    }\n  ): STM.STM<Array<A>>\n} = internal.retainIf\n\n/**\n * Returns the set's cardinality.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <A>(self: TSet<A>) => STM.STM<number> = internal.size\n\n/**\n * Takes the first matching value, or retries until there is one.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeFirst: {\n  <A, B>(pf: (a: A) => Option.Option<B>): (self: TSet<A>) => STM.STM<B>\n  <A, B>(self: TSet<A>, pf: (a: A) => Option.Option<B>): STM.STM<B>\n} = internal.takeFirst\n\n/**\n * Takes the first matching value, or retries until there is one.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeFirstSTM: {\n  <A, B, E, R>(pf: (a: A) => STM.STM<B, Option.Option<E>, R>): (self: TSet<A>) => STM.STM<B, E, R>\n  <A, B, E, R>(self: TSet<A>, pf: (a: A) => STM.STM<B, Option.Option<E>, R>): STM.STM<B, E, R>\n} = internal.takeFirstSTM\n\n/**\n * Takes all matching values, or retries until there is at least one.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeSome: {\n  <A, B>(pf: (a: A) => Option.Option<B>): (self: TSet<A>) => STM.STM<[B, ...Array<B>]>\n  <A, B>(self: TSet<A>, pf: (a: A) => Option.Option<B>): STM.STM<[B, ...Array<B>]>\n} = internal.takeSome\n\n/**\n * Takes all matching values, or retries until there is at least one.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const takeSomeSTM: {\n  <A, B, E, R>(pf: (a: A) => STM.STM<B, Option.Option<E>, R>): (self: TSet<A>) => STM.STM<[B, ...Array<B>], E, R>\n  <A, B, E, R>(self: TSet<A>, pf: (a: A) => STM.STM<B, Option.Option<E>, R>): STM.STM<[B, ...Array<B>], E, R>\n} = internal.takeSomeSTM\n\n/**\n * Collects all elements into a `Chunk`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toChunk: <A>(self: TSet<A>) => STM.STM<Chunk.Chunk<A>> = internal.toChunk\n\n/**\n * Collects all elements into a `HashSet`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toHashSet: <A>(self: TSet<A>) => STM.STM<HashSet.HashSet<A>> = internal.toHashSet\n\n/**\n * Collects all elements into a `Array`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toArray: <A>(self: TSet<A>) => STM.STM<Array<A>> = internal.toArray\n\n/**\n * Collects all elements into a `ReadonlySet`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const toReadonlySet: <A>(self: TSet<A>) => STM.STM<ReadonlySet<A>> = internal.toReadonlySet\n\n/**\n * Atomically updates all elements using a pure function.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const transform: {\n  <A>(f: (a: A) => A): (self: TSet<A>) => STM.STM<void>\n  <A>(self: TSet<A>, f: (a: A) => A): STM.STM<void>\n} = internal.transform\n\n/**\n * Atomically updates all elements using a transactional function.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const transformSTM: {\n  <A, R, E>(f: (a: A) => STM.STM<A, E, R>): (self: TSet<A>) => STM.STM<void, E, R>\n  <A, R, E>(self: TSet<A>, f: (a: A) => STM.STM<A, E, R>): STM.STM<void, E, R>\n} = internal.transformSTM\n\n/**\n * Atomically transforms the set into the union of itself and the provided\n * set.\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const union: {\n  <A>(other: TSet<A>): (self: TSet<A>) => STM.STM<void>\n  <A>(self: TSet<A>, other: TSet<A>): STM.STM<void>\n} = internal.union\n"
  },
  {
    "path": "packages/effect/src/TSubscriptionRef.ts",
    "content": "/**\n * @since 3.10.0\n */\nimport type * as Effect from \"./Effect.js\"\nimport * as internal from \"./internal/stm/tSubscriptionRef.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as STM from \"./STM.js\"\nimport type * as Stream from \"./Stream.js\"\nimport type * as TPubSub from \"./TPubSub.js\"\nimport type * as TQueue from \"./TQueue.js\"\nimport type * as TRef from \"./TRef.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 3.10.0\n * @category symbols\n */\nexport const TSubscriptionRefTypeId: unique symbol = internal.TSubscriptionRefTypeId\n\n/**\n * @since 3.10.0\n * @category symbols\n */\nexport type TSubscriptionRefTypeId = typeof TSubscriptionRefTypeId\n\n/**\n * A `TSubscriptionRef<A>` is a `TRef` that can be subscribed to in order to\n * receive a `TDequeue<A>` of the current value and all committed changes to the value.\n *\n * @since 3.10.0\n * @category models\n */\nexport interface TSubscriptionRef<in out A> extends TSubscriptionRef.Variance<A>, TRef.TRef<A> {\n  /** @internal */\n  readonly ref: TRef.TRef<A>\n  /** @internal */\n  readonly pubsub: TPubSub.TPubSub<A>\n  /** @internal */\n  modify<B>(f: (a: A) => readonly [B, A]): STM.STM<B>\n\n  /**\n   * A TDequeue containing the current value of the `Ref` as well as all changes\n   * to that value.\n   */\n  readonly changes: STM.STM<TQueue.TDequeue<A>>\n}\n\n/**\n * @since 3.10.0\n */\nexport declare namespace TSubscriptionRef {\n  /**\n   * @since 3.10.0\n   * @category models\n   */\n  export interface Variance<in out A> {\n    readonly [TSubscriptionRefTypeId]: {\n      readonly _A: Types.Invariant<A>\n    }\n  }\n}\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const get: <A>(self: TSubscriptionRef<A>) => STM.STM<A> = internal.get\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const getAndSet: {\n  <A>(value: A): (self: TSubscriptionRef<A>) => STM.STM<A>\n  <A>(self: TSubscriptionRef<A>, value: A): STM.STM<A>\n} = internal.getAndSet\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const getAndUpdate: {\n  <A>(f: (a: A) => A): (self: TSubscriptionRef<A>) => STM.STM<A>\n  <A>(self: TSubscriptionRef<A>, f: (a: A) => A): STM.STM<A>\n} = internal.getAndUpdate\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const getAndUpdateSome: {\n  <A>(f: (a: A) => Option.Option<A>): (self: TSubscriptionRef<A>) => STM.STM<A>\n  <A>(self: TSubscriptionRef<A>, f: (a: A) => Option.Option<A>): STM.STM<A>\n} = internal.getAndUpdateSome\n\n/**\n * @since 3.10.0\n * @category constructors\n */\nexport const make: <A>(value: A) => STM.STM<TSubscriptionRef<A>> = internal.make\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const modify: {\n  <A, B>(f: (a: A) => readonly [B, A]): (self: TSubscriptionRef<A>) => STM.STM<B>\n  <A, B>(self: TSubscriptionRef<A>, f: (a: A) => readonly [B, A]): STM.STM<B>\n} = internal.modify\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const modifySome: {\n  <A, B>(fallback: B, f: (a: A) => Option.Option<readonly [B, A]>): (self: TSubscriptionRef<A>) => STM.STM<B>\n  <A, B>(self: TSubscriptionRef<A>, fallback: B, f: (a: A) => Option.Option<readonly [B, A]>): STM.STM<B>\n} = internal.modifySome\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const set: {\n  <A>(value: A): (self: TSubscriptionRef<A>) => STM.STM<void>\n  <A>(self: TSubscriptionRef<A>, value: A): STM.STM<void>\n} = internal.set\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const setAndGet: {\n  <A>(value: A): (self: TSubscriptionRef<A>) => STM.STM<A>\n  <A>(self: TSubscriptionRef<A>, value: A): STM.STM<A>\n} = internal.setAndGet\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const update: {\n  <A>(f: (a: A) => A): (self: TSubscriptionRef<A>) => STM.STM<void>\n  <A>(self: TSubscriptionRef<A>, f: (a: A) => A): STM.STM<void>\n} = internal.update\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const updateAndGet: {\n  <A>(f: (a: A) => A): (self: TSubscriptionRef<A>) => STM.STM<A>\n  <A>(self: TSubscriptionRef<A>, f: (a: A) => A): STM.STM<A>\n} = internal.updateAndGet\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const updateSome: {\n  <A>(f: (a: A) => Option.Option<A>): (self: TSubscriptionRef<A>) => STM.STM<void>\n  <A>(self: TSubscriptionRef<A>, f: (a: A) => Option.Option<A>): STM.STM<void>\n} = internal.updateSome\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const updateSomeAndGet: {\n  <A>(f: (a: A) => Option.Option<A>): (self: TSubscriptionRef<A>) => STM.STM<A>\n  <A>(self: TSubscriptionRef<A>, f: (a: A) => Option.Option<A>): STM.STM<A>\n} = internal.updateSomeAndGet\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const changesScoped: <A>(self: TSubscriptionRef<A>) => Effect.Effect<TQueue.TDequeue<A>, never, Scope.Scope> =\n  internal.changesScoped\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const changesStream: <A>(self: TSubscriptionRef<A>) => Stream.Stream<A> = internal.changesStream\n\n/**\n * @since 3.10.0\n * @category mutations\n */\nexport const changes: <A>(self: TSubscriptionRef<A>) => STM.STM<TQueue.TDequeue<A>> = (self) => self.changes\n"
  },
  {
    "path": "packages/effect/src/Take.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Cause from \"./Cause.js\"\nimport type * as Chunk from \"./Chunk.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport * as internal from \"./internal/take.js\"\nimport type * as Option from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const TakeTypeId: unique symbol = internal.TakeTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type TakeTypeId = typeof TakeTypeId\n\n/**\n * A `Take<A, E>` represents a single `take` from a queue modeling a stream of\n * values. A `Take` may be a failure cause `Cause<E>`, a chunk value `Chunk<A>`,\n * or an end-of-stream marker.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface Take<out A, out E = never> extends Take.Variance<A, E>, Pipeable {\n  /** @internal */\n  readonly exit: Exit.Exit<Chunk.Chunk<A>, Option.Option<E>>\n}\n\n/**\n * @since 2.0.0\n */\nexport declare namespace Take {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out A, out E> {\n    readonly [TakeTypeId]: {\n      readonly _A: Types.Covariant<A>\n      readonly _E: Types.Covariant<E>\n    }\n  }\n}\n\n/**\n * Creates a `Take` with the specified chunk.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const chunk: <A>(chunk: Chunk.Chunk<A>) => Take<A> = internal.chunk\n\n/**\n * Creates a failing `Take` with the specified defect.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const die: (defect: unknown) => Take<never> = internal.die\n\n/**\n * Creates a failing `Take` with the specified error message.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const dieMessage: (message: string) => Take<never> = internal.dieMessage\n\n/**\n * Transforms a `Take<A, E>` to an `Effect<A, E>`.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const done: <A, E>(self: Take<A, E>) => Effect.Effect<Chunk.Chunk<A>, Option.Option<E>> = internal.done\n\n/**\n * Represents the end-of-stream marker.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const end: Take<never> = internal.end\n\n/**\n * Creates a failing `Take` with the specified error.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fail: <E>(error: E) => Take<never, E> = internal.fail\n\n/**\n * Creates a failing `Take` with the specified cause.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const failCause: <E>(cause: Cause.Cause<E>) => Take<never, E> = internal.failCause\n\n/**\n * Creates an effect from `Effect<A, E, R>` that does not fail, but succeeds with\n * the `Take<A, E>`. Error from stream when pulling is converted to\n * `Take.failCause`. Creates a single value chunk.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromEffect: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<Take<A, E>, never, R> =\n  internal.fromEffect\n\n/**\n * Creates a `Take` from an `Exit`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromExit: <A, E>(exit: Exit.Exit<A, E>) => Take<A, E> = internal.fromExit\n\n/**\n * Creates effect from `Effect<Chunk<A>, Option<E>, R>` that does not fail, but\n * succeeds with the `Take<A, E>`. Errors from stream when pulling are converted\n * to `Take.failCause`, and the end-of-stream is converted to `Take.end`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromPull: <A, E, R>(\n  pull: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R>\n) => Effect.Effect<Take<A, E>, never, R> = internal.fromPull\n\n/**\n * Checks if this `take` is done (`Take.end`).\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isDone: <A, E>(self: Take<A, E>) => boolean = internal.isDone\n\n/**\n * Checks if this `take` is a failure.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isFailure: <A, E>(self: Take<A, E>) => boolean = internal.isFailure\n\n/**\n * Checks if this `take` is a success.\n *\n * @since 2.0.0\n * @category getters\n */\nexport const isSuccess: <A, E>(self: Take<A, E>) => boolean = internal.isSuccess\n\n/**\n * Constructs a `Take`.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <A, E>(exit: Exit.Exit<Chunk.Chunk<A>, Option.Option<E>>) => Take<A, E> = internal.make\n\n/**\n * Transforms `Take<A, E>` to `Take<B, A>` by applying function `f`.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map: {\n  <A, B>(f: (a: A) => B): <E>(self: Take<A, E>) => Take<B, E>\n  <A, E, B>(self: Take<A, E>, f: (a: A) => B): Take<B, E>\n} = internal.map\n\n/**\n * Folds over the failure cause, success value and end-of-stream marker to\n * yield a value.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const match: {\n  <Z, E, Z2, A, Z3>(\n    options: {\n      readonly onEnd: () => Z\n      readonly onFailure: (cause: Cause.Cause<E>) => Z2\n      readonly onSuccess: (chunk: Chunk.Chunk<A>) => Z3\n    }\n  ): (self: Take<A, E>) => Z | Z2 | Z3\n  <A, E, Z, Z2, Z3>(\n    self: Take<A, E>,\n    options: {\n      readonly onEnd: () => Z\n      readonly onFailure: (cause: Cause.Cause<E>) => Z2\n      readonly onSuccess: (chunk: Chunk.Chunk<A>) => Z3\n    }\n  ): Z | Z2 | Z3\n} = internal.match\n\n/**\n * Effectful version of `Take.fold`.\n *\n * Folds over the failure cause, success value and end-of-stream marker to\n * yield an effect.\n *\n * @since 2.0.0\n * @category destructors\n */\nexport const matchEffect: {\n  <Z, E2, R, E, Z2, R2, A, Z3, E3, R3>(\n    options: {\n      readonly onEnd: Effect.Effect<Z, E2, R>\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<Z2, E2, R2>\n      readonly onSuccess: (chunk: Chunk.Chunk<A>) => Effect.Effect<Z3, E3, R3>\n    }\n  ): (self: Take<A, E>) => Effect.Effect<Z | Z2 | Z3, E2 | E | E3, R | R2 | R3>\n  <A, E, Z, E2, R, Z2, R2, Z3, E3, R3>(\n    self: Take<A, E>,\n    options: {\n      readonly onEnd: Effect.Effect<Z, E2, R>\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<Z2, E2, R2>\n      readonly onSuccess: (chunk: Chunk.Chunk<A>) => Effect.Effect<Z3, E3, R3>\n    }\n  ): Effect.Effect<Z | Z2 | Z3, E | E2 | E3, R | R2 | R3>\n} = internal.matchEffect\n\n/**\n * Creates a `Take` with a single value chunk.\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const of: <A>(value: A) => Take<A> = internal.of\n\n/**\n * Returns an effect that effectfully \"peeks\" at the success of this take.\n *\n * @since 2.0.0\n * @category sequencing\n */\nexport const tap: {\n  <A, X, E2, R>(\n    f: (chunk: Chunk.Chunk<A>) => Effect.Effect<X, E2, R>\n  ): <E>(self: Take<A, E>) => Effect.Effect<void, E2 | E, R>\n  <A, E, X, E2, R>(\n    self: Take<A, E>,\n    f: (chunk: Chunk.Chunk<A>) => Effect.Effect<X, E2, R>\n  ): Effect.Effect<void, E | E2, R>\n} = internal.tap\n"
  },
  {
    "path": "packages/effect/src/TestAnnotation.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Chunk from \"./Chunk.js\"\nimport * as Either from \"./Either.js\"\nimport * as Equal from \"./Equal.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport { pipe } from \"./Function.js\"\nimport * as Hash from \"./Hash.js\"\nimport * as HashSet from \"./HashSet.js\"\nimport { getBugErrorMessage } from \"./internal/errors.js\"\nimport type * as MutableRef from \"./MutableRef.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport type * as SortedSet from \"./SortedSet.js\"\nimport type * as Types from \"./Types.js\"\n\n/** @internal */\nconst TestAnnotationSymbolKey = \"effect/TestAnnotation\"\n\n/**\n * @since 2.0.0\n */\nexport const TestAnnotationTypeId: unique symbol = Symbol.for(TestAnnotationSymbolKey)\n\n/**\n * @since 2.0.0\n */\nexport type TestAnnotationTypeId = typeof TestAnnotationTypeId\n\n/**\n * @since 2.0.0\n */\nexport interface TestAnnotation<in out A> extends Equal.Equal {\n  readonly [TestAnnotationTypeId]: {\n    readonly _A: Types.Invariant<A>\n  }\n  readonly identifier: string\n  readonly initial: A\n  combine(a: A, b: A): A\n}\n\n/** @internal */\nclass TestAnnotationImpl<A> implements Equal.Equal {\n  readonly [TestAnnotationTypeId] = {\n    _A: (_: any) => _\n  }\n  constructor(\n    readonly identifier: string,\n    readonly initial: A,\n    readonly combine: (a: A, b: A) => A\n  ) {}\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(TestAnnotationSymbolKey),\n      Hash.combine(Hash.hash(this.identifier)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isTestAnnotation(that) &&\n      this.identifier === that.identifier\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport const isTestAnnotation = (u: unknown): u is TestAnnotation<unknown> => hasProperty(u, TestAnnotationTypeId)\n\n/**\n * @since 2.0.0\n */\nexport const make = <A>(\n  identifier: string,\n  initial: A,\n  combine: (a: A, b: A) => A\n): TestAnnotation<A> => {\n  return new TestAnnotationImpl<A>(identifier, initial, combine)\n}\n\n/**\n * @since 2.0.0\n */\nexport const compose = <A>(\n  left: Either.Either<Chunk.Chunk<A>, number>,\n  right: Either.Either<Chunk.Chunk<A>, number>\n): Either.Either<Chunk.Chunk<A>, number> => {\n  if (Either.isLeft(left) && Either.isLeft(right)) {\n    return Either.left(left.left + right.left)\n  }\n  if (Either.isRight(left) && Either.isRight(right)) {\n    return Either.right(pipe(left.right, Chunk.appendAll(right.right)))\n  }\n  if (Either.isRight(left) && Either.isLeft(right)) {\n    return right\n  }\n  if (Either.isLeft(left) && Either.isRight(right)) {\n    return right\n  }\n  throw new Error(getBugErrorMessage(\"TestAnnotation.compose\"))\n}\n\n/**\n * @since 2.0.0\n */\nexport const fibers: TestAnnotation<\n  Either.Either<Chunk.Chunk<MutableRef.MutableRef<SortedSet.SortedSet<Fiber.RuntimeFiber<unknown, unknown>>>>, number>\n> = make<\n  Either.Either<Chunk.Chunk<MutableRef.MutableRef<SortedSet.SortedSet<Fiber.RuntimeFiber<unknown, unknown>>>>, number>\n>(\n  \"fibers\",\n  Either.left(0),\n  compose\n)\n\n/**\n * An annotation which counts ignored tests.\n *\n * @since 2.0.0\n */\nexport const ignored: TestAnnotation<number> = make(\n  \"ignored\",\n  0,\n  (a, b) => a + b\n)\n\n/**\n * An annotation which counts repeated tests.\n *\n * @since 2.0.0\n */\nexport const repeated: TestAnnotation<number> = make(\n  \"repeated\",\n  0,\n  (a, b) => a + b\n)\n\n/**\n * An annotation which counts retried tests.\n *\n * @since 2.0.0\n */\nexport const retried: TestAnnotation<number> = make(\n  \"retried\",\n  0,\n  (a, b) => a + b\n)\n\n/**\n * An annotation which tags tests with strings.\n *\n * @since 2.0.0\n */\nexport const tagged: TestAnnotation<HashSet.HashSet<string>> = make(\n  \"tagged\",\n  HashSet.empty(),\n  (a, b) => pipe(a, HashSet.union(b))\n)\n"
  },
  {
    "path": "packages/effect/src/TestAnnotationMap.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport { dual } from \"./Function.js\"\nimport * as HashMap from \"./HashMap.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport type * as TestAnnotation from \"./TestAnnotation.js\"\n\n/**\n * @since 2.0.0\n */\nexport const TestAnnotationMapTypeId: unique symbol = Symbol.for(\"effect/TestAnnotationMap\")\n\n/**\n * @since 2.0.0\n */\nexport type TestAnnotationMapTypeId = typeof TestAnnotationMapTypeId\n\n/**\n * An annotation map keeps track of annotations of different types.\n *\n * @since 2.0.0\n */\nexport interface TestAnnotationMap {\n  readonly [TestAnnotationMapTypeId]: TestAnnotationMapTypeId\n  /** @internal */\n  readonly map: HashMap.HashMap<TestAnnotation.TestAnnotation<any>, any>\n}\n\n/** @internal */\nclass TestAnnotationMapImpl implements TestAnnotationMap {\n  readonly [TestAnnotationMapTypeId]: TestAnnotationMapTypeId = TestAnnotationMapTypeId\n  constructor(readonly map: HashMap.HashMap<TestAnnotation.TestAnnotation<any>, any>) {\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport const isTestAnnotationMap = (u: unknown): u is TestAnnotationMap => hasProperty(u, TestAnnotationMapTypeId)\n\n/**\n * @since 2.0.0\n */\nexport const empty: (_: void) => TestAnnotationMap = () => new TestAnnotationMapImpl(HashMap.empty())\n\n/**\n * @since 2.0.0\n */\nexport const make = (map: HashMap.HashMap<TestAnnotation.TestAnnotation<any>, any>): TestAnnotationMap => {\n  return new TestAnnotationMapImpl(map)\n}\n\n/**\n * @since 2.0.0\n */\nexport const overwrite = dual<\n  <A>(key: TestAnnotation.TestAnnotation<A>, value: A) => (self: TestAnnotationMap) => TestAnnotationMap,\n  <A>(self: TestAnnotationMap, key: TestAnnotation.TestAnnotation<A>, value: A) => TestAnnotationMap\n>(3, (self, key, value) => make(HashMap.set(self.map, key, value)))\n\n/**\n * @since 2.0.0\n */\nexport const update = dual<\n  <A>(key: TestAnnotation.TestAnnotation<A>, f: (value: A) => A) => (self: TestAnnotationMap) => TestAnnotationMap,\n  <A>(self: TestAnnotationMap, key: TestAnnotation.TestAnnotation<A>, f: (value: A) => A) => TestAnnotationMap\n>(3, <A>(self: TestAnnotationMap, key: TestAnnotation.TestAnnotation<A>, f: (value: A) => A) => {\n  let value = key.initial\n  if (HashMap.has(self.map, key)) {\n    value = HashMap.unsafeGet(self.map, key) as A\n  }\n  return overwrite(self, key, f(value))\n})\n\n/**\n * Retrieves the annotation of the specified type, or its default value if\n * there is none.\n *\n * @since 2.0.0\n */\nexport const get = dual<\n  <A>(key: TestAnnotation.TestAnnotation<A>) => (self: TestAnnotationMap) => A,\n  <A>(self: TestAnnotationMap, key: TestAnnotation.TestAnnotation<A>) => A\n>(2, <A>(self: TestAnnotationMap, key: TestAnnotation.TestAnnotation<A>) => {\n  if (HashMap.has(self.map, key)) {\n    return HashMap.unsafeGet(self.map, key) as A\n  }\n  return key.initial\n})\n\n/**\n * Appends the specified annotation to the annotation map.\n *\n * @since 2.0.0\n */\nexport const annotate = dual<\n  <A>(key: TestAnnotation.TestAnnotation<A>, value: A) => (self: TestAnnotationMap) => TestAnnotationMap,\n  <A>(self: TestAnnotationMap, key: TestAnnotation.TestAnnotation<A>, value: A) => TestAnnotationMap\n>(3, (self, key, value) => update(self, key, (_) => key.combine(_, value)))\n\n/**\n * @since 2.0.0\n */\nexport const combine = dual<\n  (that: TestAnnotationMap) => (self: TestAnnotationMap) => TestAnnotationMap,\n  (self: TestAnnotationMap, that: TestAnnotationMap) => TestAnnotationMap\n>(2, (self, that) => {\n  let result = self.map\n  for (const entry of that.map) {\n    if (HashMap.has(result, entry[0])) {\n      const value = HashMap.get(result, entry[0])!\n      result = HashMap.set(result, entry[0], entry[0].combine(value, entry[1]))\n    } else {\n      result = HashMap.set(result, entry[0], entry[1])\n    }\n  }\n  return make(result)\n})\n"
  },
  {
    "path": "packages/effect/src/TestAnnotations.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as RA from \"./Array.js\"\nimport * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as Equal from \"./Equal.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport { pipe } from \"./Function.js\"\nimport * as effect from \"./internal/core-effect.js\"\nimport * as core from \"./internal/core.js\"\nimport * as fiber from \"./internal/fiber.js\"\nimport * as MutableRef from \"./MutableRef.js\"\nimport { hasProperty } from \"./Predicate.js\"\nimport * as Ref from \"./Ref.js\"\nimport * as SortedSet from \"./SortedSet.js\"\nimport * as TestAnnotation from \"./TestAnnotation.js\"\nimport * as TestAnnotationMap from \"./TestAnnotationMap.js\"\n\n/**\n * @since 2.0.0\n */\nexport const TestAnnotationsTypeId: unique symbol = Symbol.for(\"effect/TestAnnotations\")\n\n/**\n * @since 2.0.0\n */\nexport type TestAnnotationsTypeId = typeof TestAnnotationsTypeId\n\n/**\n * The `Annotations` trait provides access to an annotation map that tests can\n * add arbitrary annotations to. Each annotation consists of a string\n * identifier, an initial value, and a function for combining two values.\n * Annotations form monoids and you can think of `Annotations` as a more\n * structured logging service or as a super polymorphic version of the writer\n * monad effect.\n *\n * @since 2.0.0\n */\nexport interface TestAnnotations {\n  readonly [TestAnnotationsTypeId]: TestAnnotationsTypeId\n\n  /**\n   * A ref containing the bacnking map for all annotations\n   */\n  readonly ref: Ref.Ref<TestAnnotationMap.TestAnnotationMap>\n\n  /**\n   * Accesses an `Annotations` instance in the context and retrieves the\n   * annotation of the specified type, or its default value if there is none.\n   */\n  get<A>(key: TestAnnotation.TestAnnotation<A>): Effect.Effect<A>\n\n  /**\n   * Accesses an `Annotations` instance in the context and appends the\n   * specified annotation to the annotation map.\n   */\n  annotate<A>(key: TestAnnotation.TestAnnotation<A>, value: A): Effect.Effect<void>\n\n  /**\n   * Returns the set of all fibers in this test.\n   */\n  readonly supervisedFibers: Effect.Effect<\n    SortedSet.SortedSet<Fiber.RuntimeFiber<unknown, unknown>>\n  >\n}\n\n/** @internal */\nclass AnnotationsImpl implements TestAnnotations {\n  readonly [TestAnnotationsTypeId]: TestAnnotationsTypeId = TestAnnotationsTypeId\n  constructor(readonly ref: Ref.Ref<TestAnnotationMap.TestAnnotationMap>) {\n  }\n  get<A>(key: TestAnnotation.TestAnnotation<A>): Effect.Effect<A> {\n    return core.map(Ref.get(this.ref), TestAnnotationMap.get(key))\n  }\n  annotate<A>(key: TestAnnotation.TestAnnotation<A>, value: A): Effect.Effect<void> {\n    return Ref.update(this.ref, TestAnnotationMap.annotate(key, value))\n  }\n  get supervisedFibers(): Effect.Effect<SortedSet.SortedSet<Fiber.RuntimeFiber<unknown, unknown>>> {\n    return effect.descriptorWith((descriptor) =>\n      core.flatMap(this.get(TestAnnotation.fibers), (either) => {\n        switch (either._tag) {\n          case \"Left\": {\n            return core.succeed(SortedSet.empty(fiber.Order))\n          }\n          case \"Right\": {\n            return pipe(\n              either.right,\n              core.forEachSequential((ref) => core.sync(() => MutableRef.get(ref))),\n              core.map(RA.reduce(SortedSet.empty(fiber.Order), (a, b) => SortedSet.union(a, b))),\n              core.map(SortedSet.filter((fiber) => !Equal.equals(fiber.id(), descriptor.id)))\n            )\n          }\n        }\n      })\n    )\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport const TestAnnotations: Context.Tag<TestAnnotations, TestAnnotations> = Context.GenericTag<TestAnnotations>(\n  \"effect/Annotations\"\n)\n\n/**\n * @since 2.0.0\n */\nexport const isTestAnnotations = (u: unknown): u is TestAnnotations => hasProperty(u, TestAnnotationsTypeId)\n\n/**\n * @since 2.0.0\n */\nexport const make = (\n  ref: Ref.Ref<TestAnnotationMap.TestAnnotationMap>\n): TestAnnotations => new AnnotationsImpl(ref)\n"
  },
  {
    "path": "packages/effect/src/TestClock.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Chunk from \"./Chunk.js\"\nimport type * as Clock from \"./Clock.js\"\nimport * as Context from \"./Context.js\"\nimport * as DateTime from \"./DateTime.js\"\nimport type * as Deferred from \"./Deferred.js\"\nimport * as Duration from \"./Duration.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as Equal from \"./Equal.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport type * as FiberId from \"./FiberId.js\"\nimport * as FiberStatus from \"./FiberStatus.js\"\nimport { constVoid, dual, identity, pipe } from \"./Function.js\"\nimport * as HashMap from \"./HashMap.js\"\nimport * as clock from \"./internal/clock.js\"\nimport * as effect from \"./internal/core-effect.js\"\nimport * as core from \"./internal/core.js\"\nimport * as defaultServices from \"./internal/defaultServices.js\"\nimport * as circular from \"./internal/effect/circular.js\"\nimport * as fiberRuntime from \"./internal/fiberRuntime.js\"\nimport * as layer from \"./internal/layer.js\"\nimport * as ref from \"./internal/ref.js\"\nimport * as synchronized from \"./internal/synchronizedRef.js\"\nimport * as SuspendedWarningData from \"./internal/testing/suspendedWarningData.js\"\nimport * as WarningData from \"./internal/testing/warningData.js\"\nimport type * as Layer from \"./Layer.js\"\nimport * as number from \"./Number.js\"\nimport * as Option from \"./Option.js\"\nimport * as Order from \"./Order.js\"\nimport type * as Ref from \"./Ref.js\"\nimport type * as SortedSet from \"./SortedSet.js\"\nimport type * as Synchronized from \"./SynchronizedRef.js\"\nimport * as Annotations from \"./TestAnnotations.js\"\nimport * as Live from \"./TestLive.js\"\n\n/**\n * A `TestClock` makes it easy to deterministically and efficiently test effects\n * involving the passage of time.\n *\n * Instead of waiting for actual time to pass, `sleep` and methods implemented\n * in terms of it schedule effects to take place at a given clock time. Users\n * can adjust the clock time using the `adjust` and `setTime` methods, and all\n * effects scheduled to take place on or before that time will automatically be\n * run in order.\n *\n * For example, here is how we can test `Effect.timeout` using `TestClock`:\n *\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Duration, Effect, Fiber, TestClock, Option, pipe } from \"effect\"\n *\n * Effect.gen(function*() {\n *   const fiber = yield* pipe(\n *     Effect.sleep(Duration.minutes(5)),\n *     Effect.timeout(Duration.minutes(1)),\n *     Effect.fork\n *   )\n *   yield* TestClock.adjust(Duration.minutes(1))\n *   const result = yield* Fiber.join(fiber)\n *   assert.deepStrictEqual(result, Option.none())\n * })\n * ```\n *\n * Note how we forked the fiber that `sleep` was invoked on. Calls to `sleep`\n * and methods derived from it will semantically block until the time is set to\n * on or after the time they are scheduled to run. If we didn't fork the fiber\n * on which we called sleep we would never get to set the time on the line\n * below. Thus, a useful pattern when using `TestClock` is to fork the effect\n * being tested, then adjust the clock time, and finally verify that the\n * expected effects have been performed.\n *\n * @since 2.0.0\n */\nexport interface TestClock extends Clock.Clock {\n  adjust(duration: Duration.DurationInput): Effect.Effect<void>\n  adjustWith(duration: Duration.DurationInput): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  readonly save: Effect.Effect<Effect.Effect<void>>\n  setTime(time: number): Effect.Effect<void>\n  readonly sleeps: Effect.Effect<Chunk.Chunk<number>>\n}\n\n/**\n * `Data` represents the state of the `TestClock`, including the clock time.\n *\n * @since 2.0.1\n */\nexport interface Data {\n  readonly instant: number\n  readonly sleeps: Chunk.Chunk<readonly [number, Deferred.Deferred<void>]>\n}\n\n/**\n * @since 2.0.0\n */\nexport const makeData = (\n  instant: number,\n  sleeps: Chunk.Chunk<readonly [number, Deferred.Deferred<void>]>\n): Data => ({\n  instant,\n  sleeps\n})\n\n/**\n * @since 2.0.0\n */\nexport const TestClock: Context.Tag<TestClock, TestClock> = Context.GenericTag<TestClock>(\"effect/TestClock\")\n\n/**\n * The warning message that will be displayed if a test is using time but is\n * not advancing the `TestClock`.\n *\n * @internal\n */\nconst warning = \"Warning: A test is using time, but is not advancing \" +\n  \"the test clock, which may result in the test hanging. Use TestClock.adjust to \" +\n  \"manually advance the time.\"\n\n/**\n * The warning message that will be displayed if a test is advancing the clock\n * but a fiber is still running.\n *\n * @internal\n */\nconst suspendedWarning = \"Warning: A test is advancing the test clock, \" +\n  \"but a fiber is not suspending, which may result in the test hanging. Use \" +\n  \"TestAspect.diagnose to identity the fiber that is not suspending.\"\n\n/** @internal */\nexport class TestClockImpl implements TestClock {\n  [clock.ClockTypeId]: Clock.ClockTypeId = clock.ClockTypeId\n  constructor(\n    readonly clockState: Ref.Ref<Data>,\n    readonly live: Live.TestLive,\n    readonly annotations: Annotations.TestAnnotations,\n    readonly warningState: Synchronized.SynchronizedRef<WarningData.WarningData>,\n    readonly suspendedWarningState: Synchronized.SynchronizedRef<SuspendedWarningData.SuspendedWarningData>\n  ) {\n    this.currentTimeMillis = core.map(\n      ref.get(this.clockState),\n      (data) => data.instant\n    )\n    this.currentTimeNanos = core.map(\n      ref.get(this.clockState),\n      (data) => BigInt(data.instant * 1000000)\n    )\n  }\n\n  /**\n   * Unsafely returns the current time in milliseconds.\n   */\n  unsafeCurrentTimeMillis(): number {\n    return ref.unsafeGet(this.clockState).instant\n  }\n\n  /**\n   * Unsafely returns the current time in nanoseconds.\n   */\n  unsafeCurrentTimeNanos(): bigint {\n    return BigInt(ref.unsafeGet(this.clockState).instant * 1000000)\n  }\n\n  /**\n   * Returns the current clock time in milliseconds.\n   */\n  currentTimeMillis: Effect.Effect<number>\n\n  /**\n   * Returns the current clock time in nanoseconds.\n   */\n  currentTimeNanos: Effect.Effect<bigint>\n\n  /**\n   * Saves the `TestClock`'s current state in an effect which, when run, will\n   * restore the `TestClock` state to the saved state.\n   */\n  get save(): Effect.Effect<Effect.Effect<void>> {\n    return core.map(ref.get(this.clockState), (data) => ref.set(this.clockState, data))\n  }\n  /**\n   * Sets the current clock time to the specified instant. Any effects that\n   * were scheduled to occur on or before the new time will be run in order.\n   */\n  setTime(instant: number): Effect.Effect<void> {\n    return core.zipRight(this.warningDone(), this.run(() => instant))\n  }\n  /**\n   * Semantically blocks the current fiber until the clock time is equal to or\n   * greater than the specified duration. Once the clock time is adjusted to\n   * on or after the duration, the fiber will automatically be resumed.\n   */\n  sleep(durationInput: Duration.DurationInput): Effect.Effect<void> {\n    const duration = Duration.decode(durationInput)\n    return core.flatMap(core.deferredMake<void>(), (deferred) =>\n      pipe(\n        ref.modify(this.clockState, (data) => {\n          const end = data.instant + Duration.toMillis(duration)\n          if (end > data.instant) {\n            return [\n              true,\n              makeData(data.instant, pipe(data.sleeps, Chunk.prepend([end, deferred] as const)))\n            ] as const\n          }\n          return [false, data] as const\n        }),\n        core.flatMap((shouldAwait) =>\n          shouldAwait ?\n            pipe(this.warningStart(), core.zipRight(core.deferredAwait(deferred))) :\n            pipe(core.deferredSucceed(deferred, void 0), core.asVoid)\n        )\n      ))\n  }\n  /**\n   * Returns a list of the times at which all queued effects are scheduled to\n   * resume.\n   */\n  get sleeps(): Effect.Effect<Chunk.Chunk<number>> {\n    return core.map(\n      ref.get(this.clockState),\n      (data) => Chunk.map(data.sleeps, (_) => _[0])\n    )\n  }\n  /**\n   * Increments the current clock time by the specified duration. Any effects\n   * that were scheduled to occur on or before the new time will be run in\n   * order.\n   */\n  adjust(durationInput: Duration.DurationInput): Effect.Effect<void> {\n    const duration = Duration.decode(durationInput)\n    return core.zipRight(this.warningDone(), this.run((n) => n + Duration.toMillis(duration)))\n  }\n  /**\n   * Increments the current clock time by the specified duration. Any effects\n   * that were scheduled to occur on or before the new time will be run in\n   * order.\n   */\n  adjustWith(durationInput: Duration.DurationInput) {\n    const duration = Duration.decode(durationInput)\n    return <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n      fiberRuntime.zipLeftOptions(effect, this.adjust(duration), { concurrent: true })\n  }\n  /**\n   * Returns a set of all fibers in this test.\n   */\n  supervisedFibers(): Effect.Effect<SortedSet.SortedSet<Fiber.RuntimeFiber<unknown, unknown>>> {\n    return this.annotations.supervisedFibers\n  }\n  /**\n   * Captures a \"snapshot\" of the identifier and status of all fibers in this\n   * test other than the current fiber. Fails with the `void` value if any of\n   * these fibers are not done or suspended. Note that because we cannot\n   * synchronize on the status of multiple fibers at the same time this\n   * snapshot may not be fully consistent.\n   */\n  freeze(): Effect.Effect<HashMap.HashMap<FiberId.FiberId, FiberStatus.FiberStatus>, void> {\n    return core.flatMap(this.supervisedFibers(), (fibers) =>\n      pipe(\n        fibers,\n        effect.reduce(HashMap.empty<FiberId.FiberId, FiberStatus.FiberStatus>(), (map, fiber) =>\n          pipe(\n            fiber.status,\n            core.flatMap((status) => {\n              if (FiberStatus.isDone(status)) {\n                return core.succeed(HashMap.set(map, fiber.id() as FiberId.FiberId, status as FiberStatus.FiberStatus))\n              }\n              if (FiberStatus.isSuspended(status)) {\n                return core.succeed(HashMap.set(map, fiber.id() as FiberId.FiberId, status as FiberStatus.FiberStatus))\n              }\n              return core.fail(void 0)\n            })\n          ))\n      ))\n  }\n  /**\n   * Forks a fiber that will display a warning message if a test is using time\n   * but is not advancing the `TestClock`.\n   */\n  warningStart(): Effect.Effect<void> {\n    return synchronized.updateSomeEffect(this.warningState, (data) =>\n      WarningData.isStart(data) ?\n        Option.some(\n          pipe(\n            this.live.provide(\n              pipe(effect.logWarning(warning), effect.delay(Duration.seconds(5)))\n            ),\n            core.interruptible,\n            fiberRuntime.fork,\n            core.map((fiber) => WarningData.pending(fiber))\n          )\n        ) :\n        Option.none())\n  }\n  /**\n   * Cancels the warning message that is displayed if a test is using time but\n   * is not advancing the `TestClock`.\n   */\n  warningDone(): Effect.Effect<void> {\n    return synchronized.updateSomeEffect(this.warningState, (warningData) => {\n      if (WarningData.isStart(warningData)) {\n        return Option.some(core.succeed(WarningData.done))\n      }\n      if (WarningData.isPending(warningData)) {\n        return Option.some(pipe(core.interruptFiber(warningData.fiber), core.as(WarningData.done)))\n      }\n      return Option.none()\n    })\n  }\n\n  private yieldTimer = core.async<void>((resume) => {\n    const timer = setTimeout(() => {\n      resume(core.void)\n    }, 0)\n    return core.sync(() => clearTimeout(timer))\n  })\n\n  /**\n   * Returns whether all descendants of this fiber are done or suspended.\n   */\n  suspended(): Effect.Effect<HashMap.HashMap<FiberId.FiberId, FiberStatus.FiberStatus>, void> {\n    return pipe(\n      this.freeze(),\n      core.zip(pipe(this.yieldTimer, core.zipRight(this.freeze()))),\n      core.flatMap(([first, last]) =>\n        Equal.equals(first, last) ?\n          core.succeed(first) :\n          core.fail(void 0)\n      )\n    )\n  }\n  /**\n   * Polls until all descendants of this fiber are done or suspended.\n   */\n  awaitSuspended(): Effect.Effect<void> {\n    return pipe(\n      this.suspendedWarningStart(),\n      core.zipRight(\n        pipe(\n          this.suspended(),\n          core.zipWith(\n            pipe(this.yieldTimer, core.zipRight(this.suspended())),\n            Equal.equals\n          ),\n          effect.filterOrFail(identity, constVoid),\n          effect.eventually\n        )\n      ),\n      core.zipRight(this.suspendedWarningDone())\n    )\n  }\n  /**\n   * Forks a fiber that will display a warning message if a test is advancing\n   * the `TestClock` but a fiber is not suspending.\n   */\n  suspendedWarningStart(): Effect.Effect<void> {\n    return synchronized.updateSomeEffect(this.suspendedWarningState, (suspendedWarningData) => {\n      if (SuspendedWarningData.isStart(suspendedWarningData)) {\n        return Option.some(\n          pipe(\n            this.live.provide(\n              pipe(\n                effect.logWarning(suspendedWarning),\n                core.zipRight(ref.set(this.suspendedWarningState, SuspendedWarningData.done)),\n                effect.delay(Duration.seconds(5))\n              )\n            ),\n            core.interruptible,\n            fiberRuntime.fork,\n            core.map((fiber) => SuspendedWarningData.pending(fiber))\n          )\n        )\n      }\n      return Option.none()\n    })\n  }\n  /**\n   * Cancels the warning message that is displayed if a test is advancing the\n   * `TestClock` but a fiber is not suspending.\n   */\n  suspendedWarningDone(): Effect.Effect<void> {\n    return synchronized.updateSomeEffect(this.suspendedWarningState, (suspendedWarningData) => {\n      if (SuspendedWarningData.isPending(suspendedWarningData)) {\n        return Option.some(pipe(core.interruptFiber(suspendedWarningData.fiber), core.as(SuspendedWarningData.start)))\n      }\n      return Option.none()\n    })\n  }\n  /**\n   * Runs all effects scheduled to occur on or before the specified instant,\n   * which may depend on the current time, in order.\n   */\n  run(f: (instant: number) => number): Effect.Effect<void> {\n    return pipe(\n      this.awaitSuspended(),\n      core.zipRight(pipe(\n        ref.modify(this.clockState, (data) => {\n          const end = f(data.instant)\n          const sorted = pipe(\n            data.sleeps,\n            Chunk.sort<readonly [number, Deferred.Deferred<void>]>(\n              pipe(number.Order, Order.mapInput((_) => _[0]))\n            )\n          )\n          if (Chunk.isNonEmpty(sorted)) {\n            const [instant, deferred] = Chunk.headNonEmpty(sorted)\n            if (instant <= end) {\n              return [\n                Option.some([end, deferred] as const),\n                makeData(instant, Chunk.tailNonEmpty(sorted))\n              ] as const\n            }\n          }\n          return [Option.none(), makeData(end, data.sleeps)] as const\n        }),\n        core.flatMap((option) => {\n          switch (option._tag) {\n            case \"None\": {\n              return core.void\n            }\n            case \"Some\": {\n              const [end, deferred] = option.value\n              return pipe(\n                core.deferredSucceed(deferred, void 0),\n                core.zipRight(core.yieldNow()),\n                core.zipRight(this.run(() => end))\n              )\n            }\n          }\n        })\n      ))\n    )\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport const live = (data: Data): Layer.Layer<TestClock, never, Annotations.TestAnnotations | Live.TestLive> =>\n  layer.scoped(\n    TestClock,\n    core.gen(function*() {\n      const live = yield* Live.TestLive\n      const annotations = yield* Annotations.TestAnnotations\n      const clockState = yield* core.sync(() => ref.unsafeMake(data))\n      const warningState = yield* circular.makeSynchronized(WarningData.start)\n      const suspendedWarningState = yield* circular.makeSynchronized(SuspendedWarningData.start)\n      const testClock = new TestClockImpl(clockState, live, annotations, warningState, suspendedWarningState)\n      yield* fiberRuntime.withClockScoped(testClock)\n      yield* fiberRuntime.addFinalizer(\n        () => core.zipRight(testClock.warningDone(), testClock.suspendedWarningDone())\n      )\n      return testClock\n    })\n  )\n\n/**\n * @since 2.0.0\n */\nexport const defaultTestClock: Layer.Layer<TestClock, never, Annotations.TestAnnotations | Live.TestLive> = live(\n  makeData(new Date(0).getTime(), Chunk.empty())\n)\n\n/**\n * Accesses a `TestClock` instance in the context and increments the time\n * by the specified duration, running any actions scheduled for on or before\n * the new time in order.\n *\n * @since 2.0.0\n */\nexport const adjust = (durationInput: Duration.DurationInput): Effect.Effect<void> => {\n  const duration = Duration.decode(durationInput)\n  return testClockWith((testClock) => testClock.adjust(duration))\n}\n\n/**\n * @since 2.0.0\n */\nexport const adjustWith = dual<\n  (duration: Duration.DurationInput) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, duration: Duration.DurationInput) => Effect.Effect<A, E, R>\n>(2, (effect, durationInput) => {\n  const duration = Duration.decode(durationInput)\n  return testClockWith((testClock) => testClock.adjustWith(duration)(effect))\n})\n\n/**\n * Accesses a `TestClock` instance in the context and saves the clock\n * state in an effect which, when run, will restore the `TestClock` to the\n * saved state.\n *\n * @since 2.0.0\n */\nexport const save = (): Effect.Effect<Effect.Effect<void>> => testClockWith((testClock) => testClock.save)\n\n/**\n * Accesses a `TestClock` instance in the context and sets the clock time\n * to the specified `Instant` or `Date`, running any actions scheduled for on or before\n * the new time in order.\n *\n * @since 2.0.0\n */\nexport const setTime = (input: DateTime.DateTime.Input): Effect.Effect<void> =>\n  testClockWith((testClock) =>\n    testClock.setTime(\n      typeof input === \"number\"\n        ? input\n        : DateTime.unsafeMake(input).epochMillis\n    )\n  )\n\n/**\n * Semantically blocks the current fiber until the clock time is equal to or\n * greater than the specified duration. Once the clock time is adjusted to\n * on or after the duration, the fiber will automatically be resumed.\n *\n * @since 2.0.0\n */\nexport const sleep = (durationInput: Duration.DurationInput): Effect.Effect<void> => {\n  const duration = Duration.decode(durationInput)\n  return testClockWith((testClock) => testClock.sleep(duration))\n}\n\n/**\n * Accesses a `TestClock` instance in the context and returns a list of\n * times that effects are scheduled to run.\n *\n * @since 2.0.0\n */\nexport const sleeps = (): Effect.Effect<Chunk.Chunk<number>> => testClockWith((testClock) => testClock.sleeps)\n\n/**\n * Retrieves the `TestClock` service for this test.\n *\n * @since 2.0.0\n */\nexport const testClock = (): Effect.Effect<TestClock> => testClockWith(core.succeed)\n\n/**\n * Retrieves the `TestClock` service for this test and uses it to run the\n * specified workflow.\n *\n * @since 2.0.0\n */\nexport const testClockWith = <A, E, R>(f: (testClock: TestClock) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  core.fiberRefGetWith(\n    defaultServices.currentServices,\n    (services) => f(pipe(services, Context.get(clock.clockTag)) as TestClock)\n  )\n\n/**\n * Accesses the current time of a `TestClock` instance in the context in\n * milliseconds.\n *\n * @since 2.0.0\n */\nexport const currentTimeMillis: Effect.Effect<number> = testClockWith((testClock) => testClock.currentTimeMillis)\n"
  },
  {
    "path": "packages/effect/src/TestConfig.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Context from \"./Context.js\"\n\n/**\n * The `TestConfig` service provides access to default configuration settings\n * used by tests, including the number of times to repeat tests to ensure\n * they are stable, the number of times to retry flaky tests, the sufficient\n * number of samples to check from a random variable, and the maximum number of\n * shrinkings to minimize large failures.\n *\n * @since 2.0.0\n */\nexport interface TestConfig {\n  /**\n   * The number of times to repeat tests to ensure they are stable.\n   */\n  readonly repeats: number\n  /**\n   * The number of times to retry flaky tests.\n   */\n  readonly retries: number\n  /**\n   * The number of sufficient samples to check for a random variable.\n   */\n  readonly samples: number\n  /**\n   * The maximum number of shrinkings to minimize large failures\n   */\n  readonly shrinks: number\n}\n\n/**\n * @since 2.0.0\n */\nexport const TestConfig: Context.Tag<TestConfig, TestConfig> = Context.GenericTag<TestConfig>(\"effect/TestConfig\")\n\n/**\n * @since 2.0.0\n */\nexport const make = (params: {\n  readonly repeats: number\n  readonly retries: number\n  readonly samples: number\n  readonly shrinks: number\n}): TestConfig => params\n"
  },
  {
    "path": "packages/effect/src/TestContext.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as DefaultServices from \"./DefaultServices.js\"\nimport { pipe } from \"./Function.js\"\nimport * as defaultServices from \"./internal/defaultServices.js\"\nimport * as layer from \"./internal/layer.js\"\nimport type * as Layer from \"./Layer.js\"\nimport * as TestClock from \"./TestClock.js\"\nimport * as TestServices from \"./TestServices.js\"\n\n/** @internal */\nexport const live: Layer.Layer<TestServices.TestServices, never, DefaultServices.DefaultServices> = pipe(\n  TestServices.annotationsLayer(),\n  layer.merge(TestServices.liveLayer()),\n  layer.merge(TestServices.sizedLayer(100)),\n  layer.merge(pipe(\n    TestClock.defaultTestClock,\n    layer.provideMerge(\n      layer.merge(TestServices.liveLayer(), TestServices.annotationsLayer())\n    )\n  )),\n  layer.merge(TestServices.testConfigLayer({ repeats: 100, retries: 100, samples: 200, shrinks: 1000 }))\n)\n\n/**\n * @since 2.0.0\n */\nexport const LiveContext: Layer.Layer<DefaultServices.DefaultServices> = layer.syncContext(() =>\n  defaultServices.liveServices\n)\n\n/**\n * @since 2.0.0\n */\nexport const TestContext: Layer.Layer<TestServices.TestServices> = layer.provideMerge(live, LiveContext)\n"
  },
  {
    "path": "packages/effect/src/TestLive.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Context from \"./Context.js\"\nimport type * as DefaultServices from \"./DefaultServices.js\"\nimport type * as Effect from \"./Effect.js\"\nimport * as core from \"./internal/core.js\"\nimport * as defaultServices from \"./internal/defaultServices.js\"\n\n/**\n * @since 2.0.0\n */\nexport const TestLiveTypeId: unique symbol = Symbol.for(\"effect/TestLive\")\n\n/**\n * @since 2.0.0\n */\nexport type TestLiveTypeId = typeof TestLiveTypeId\n\n/**\n * The `Live` trait provides access to the \"live\" default Effect services from\n * within tests for workflows such as printing test results to the console or\n * timing out tests where it is necessary to access the real implementations of\n * these services.\n *\n * @since 2.0.0\n */\nexport interface TestLive {\n  readonly [TestLiveTypeId]: TestLiveTypeId\n  provide<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R>\n}\n\n/**\n * @since 2.0.0\n */\nexport const TestLive: Context.Tag<TestLive, TestLive> = Context.GenericTag<TestLive>(\"effect/TestLive\")\n\n/** @internal */\nclass LiveImpl implements TestLive {\n  readonly [TestLiveTypeId]: TestLiveTypeId = TestLiveTypeId\n  constructor(readonly services: Context.Context<DefaultServices.DefaultServices>) {}\n  provide<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> {\n    return core.fiberRefLocallyWith(\n      defaultServices.currentServices,\n      Context.merge(this.services)\n    )(effect)\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport const make = (services: Context.Context<DefaultServices.DefaultServices>): TestLive => new LiveImpl(services)\n"
  },
  {
    "path": "packages/effect/src/TestServices.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Context from \"./Context.js\"\nimport type * as DefaultServices from \"./DefaultServices.js\"\nimport * as Effect from \"./Effect.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport type * as FiberRef from \"./FiberRef.js\"\nimport { dual, pipe } from \"./Function.js\"\nimport * as core from \"./internal/core.js\"\nimport * as defaultServices from \"./internal/defaultServices.js\"\nimport * as fiberRuntime from \"./internal/fiberRuntime.js\"\nimport * as layer from \"./internal/layer.js\"\nimport * as ref from \"./internal/ref.js\"\nimport type * as Layer from \"./Layer.js\"\nimport type * as Scope from \"./Scope.js\"\nimport type * as SortedSet from \"./SortedSet.js\"\nimport type * as TestAnnotation from \"./TestAnnotation.js\"\nimport * as TestAnnotationMap from \"./TestAnnotationMap.js\"\nimport * as Annotations from \"./TestAnnotations.js\"\nimport * as TestConfig from \"./TestConfig.js\"\nimport * as Live from \"./TestLive.js\"\nimport * as Sized from \"./TestSized.js\"\n\n/**\n * @since 2.0.0\n */\nexport type TestServices =\n  | Annotations.TestAnnotations\n  | Live.TestLive\n  | Sized.TestSized\n  | TestConfig.TestConfig\n\n/**\n * The default Effect test services.\n *\n * @since 2.0.0\n */\nexport const liveServices: Context.Context<TestServices> = pipe(\n  Context.make(Annotations.TestAnnotations, Annotations.make(ref.unsafeMake(TestAnnotationMap.empty()))),\n  Context.add(Live.TestLive, Live.make(defaultServices.liveServices)),\n  Context.add(Sized.TestSized, Sized.make(100)),\n  Context.add(TestConfig.TestConfig, TestConfig.make({ repeats: 100, retries: 100, samples: 200, shrinks: 1000 }))\n)\n\n/**\n * @since 2.0.0\n */\nexport const currentServices: FiberRef.FiberRef<Context.Context<TestServices>> = core.fiberRefUnsafeMakeContext(\n  liveServices\n)\n\n/**\n * Retrieves the `Annotations` service for this test.\n *\n * @since 2.0.0\n */\nexport const annotations = (): Effect.Effect<Annotations.TestAnnotations> => annotationsWith(core.succeed)\n\n/**\n * Retrieves the `Annotations` service for this test and uses it to run the\n * specified workflow.\n *\n * @since 2.0.0\n */\nexport const annotationsWith = <A, E, R>(\n  f: (annotations: Annotations.TestAnnotations) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> =>\n  core.fiberRefGetWith(\n    currentServices,\n    (services) => f(Context.get(services, Annotations.TestAnnotations))\n  )\n\n/**\n * Executes the specified workflow with the specified implementation of the\n * annotations service.\n *\n * @since 2.0.0\n */\nexport const withAnnotations = dual<\n  (annotations: Annotations.TestAnnotations) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, annotations: Annotations.TestAnnotations) => Effect.Effect<A, E, R>\n>(2, (effect, annotations) =>\n  core.fiberRefLocallyWith(\n    currentServices,\n    Context.add(Annotations.TestAnnotations, annotations)\n  )(effect))\n\n/**\n * Sets the implementation of the annotations service to the specified value\n * and restores it to its original value when the scope is closed.\n *\n * @since 2.0.0\n */\nexport const withAnnotationsScoped = (\n  annotations: Annotations.TestAnnotations\n): Effect.Effect<void, never, Scope.Scope> =>\n  fiberRuntime.fiberRefLocallyScopedWith(\n    currentServices,\n    Context.add(Annotations.TestAnnotations, annotations)\n  )\n\n/**\n * Constructs a new `Annotations` service wrapped in a layer.\n *\n * @since 2.0.0\n */\nexport const annotationsLayer = (): Layer.Layer<Annotations.TestAnnotations> =>\n  layer.scoped(\n    Annotations.TestAnnotations,\n    pipe(\n      core.sync(() => ref.unsafeMake(TestAnnotationMap.empty())),\n      core.map(Annotations.make),\n      core.tap(withAnnotationsScoped)\n    )\n  )\n\n/**\n * Accesses an `Annotations` instance in the context and retrieves the\n * annotation of the specified type, or its default value if there is none.\n *\n * @since 2.0.0\n */\nexport const get = <A>(key: TestAnnotation.TestAnnotation<A>): Effect.Effect<A> =>\n  annotationsWith((annotations) => annotations.get(key))\n\n/**\n * Accesses an `Annotations` instance in the context and appends the\n * specified annotation to the annotation map.\n *\n * @since 2.0.0\n */\nexport const annotate = <A>(key: TestAnnotation.TestAnnotation<A>, value: A): Effect.Effect<void> =>\n  annotationsWith((annotations) => annotations.annotate(key, value))\n\n/**\n * Returns the set of all fibers in this test.\n *\n * @since 2.0.0\n */\nexport const supervisedFibers = (): Effect.Effect<\n  SortedSet.SortedSet<Fiber.RuntimeFiber<unknown, unknown>>\n> => annotationsWith((annotations) => annotations.supervisedFibers)\n\n/**\n * Retrieves the `Live` service for this test and uses it to run the specified\n * workflow.\n *\n * @since 2.0.0\n */\nexport const liveWith = <A, E, R>(f: (live: Live.TestLive) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  core.fiberRefGetWith(currentServices, (services) => f(Context.get(services, Live.TestLive)))\n\n/**\n * Retrieves the `Live` service for this test.\n *\n * @since 2.0.0\n */\nexport const live: Effect.Effect<Live.TestLive> = liveWith(core.succeed)\n\n/**\n * Executes the specified workflow with the specified implementation of the\n * live service.\n *\n * @since 2.0.0\n */\nexport const withLive = dual<\n  (live: Live.TestLive) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, live: Live.TestLive) => Effect.Effect<A, E, R>\n>(2, (effect, live) =>\n  core.fiberRefLocallyWith(\n    currentServices,\n    Context.add(Live.TestLive, live)\n  )(effect))\n\n/**\n * Sets the implementation of the live service to the specified value and\n * restores it to its original value when the scope is closed.\n *\n * @since 2.0.0\n */\nexport const withLiveScoped = (live: Live.TestLive): Effect.Effect<void, never, Scope.Scope> =>\n  fiberRuntime.fiberRefLocallyScopedWith(currentServices, Context.add(Live.TestLive, live))\n\n/**\n * Constructs a new `Live` service wrapped in a layer.\n *\n * @since 2.0.0\n */\nexport const liveLayer = (): Layer.Layer<Live.TestLive, never, DefaultServices.DefaultServices> =>\n  layer.scoped(\n    Live.TestLive,\n    pipe(\n      core.context<DefaultServices.DefaultServices>(),\n      core.map(Live.make),\n      core.tap(withLiveScoped)\n    )\n  )\n\n/**\n * Provides a workflow with the \"live\" default Effect services.\n *\n * @since 2.0.0\n */\nexport const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  liveWith((live) => live.provide(effect))\n\n/**\n * Runs a transformation function with the live default Effect services while\n * ensuring that the workflow itself is run with the test services.\n *\n * @since 2.0.0\n */\nexport const provideWithLive = dual<\n  <A, E, R, A2, E2, R2>(\n    f: (effect: Effect.Effect<A, E, R>) => Effect.Effect<A2, E2, R2>\n  ) => (self: Effect.Effect<A, E, R>) => Effect.Effect<A2, E | E2, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (effect: Effect.Effect<A, E, R>) => Effect.Effect<A2, E2, R2>\n  ) => Effect.Effect<A2, E | E2, R | R2>\n>(2, (self, f) =>\n  core.fiberRefGetWith(\n    defaultServices.currentServices,\n    (services) => provideLive(f(core.fiberRefLocally(defaultServices.currentServices, services)(self)))\n  ))\n\n/**\n * Retrieves the `Sized` service for this test and uses it to run the\n * specified workflow.\n *\n * @since 2.0.0\n */\nexport const sizedWith = <A, E, R>(f: (sized: Sized.TestSized) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  core.fiberRefGetWith(\n    currentServices,\n    (services) => f(Context.get(services, Sized.TestSized))\n  )\n\n/**\n * Retrieves the `Sized` service for this test.\n *\n * @since 2.0.0\n */\nexport const sized: Effect.Effect<Sized.TestSized> = sizedWith(core.succeed)\n\n/**\n * Executes the specified workflow with the specified implementation of the\n * sized service.\n *\n * @since 2.0.0\n */\nexport const withSized = dual<\n  (sized: Sized.TestSized) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, sized: Sized.TestSized) => Effect.Effect<A, E, R>\n>(2, (effect, sized) =>\n  core.fiberRefLocallyWith(\n    currentServices,\n    Context.add(Sized.TestSized, sized)\n  )(effect))\n\n/**\n * Sets the implementation of the sized service to the specified value and\n * restores it to its original value when the scope is closed.\n *\n * @since 2.0.0\n */\nexport const withSizedScoped = (sized: Sized.TestSized): Effect.Effect<void, never, Scope.Scope> =>\n  fiberRuntime.fiberRefLocallyScopedWith(currentServices, Context.add(Sized.TestSized, sized))\n\n/**\n * @since 2.0.0\n */\nexport const sizedLayer = (size: number): Layer.Layer<Sized.TestSized> =>\n  layer.scoped(\n    Sized.TestSized,\n    pipe(\n      fiberRuntime.fiberRefMake(size),\n      core.map(Sized.fromFiberRef),\n      core.tap(withSizedScoped)\n    )\n  )\n\n/**\n * @since 2.0.0\n */\nexport const size: Effect.Effect<number> = sizedWith((sized) => sized.size)\n\n/**\n * @since 2.0.0\n */\nexport const withSize = dual<\n  (size: number) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, size: number) => Effect.Effect<A, E, R>\n>(2, (effect, size) => sizedWith((sized) => sized.withSize(size)(effect)))\n\n/**\n * Retrieves the `TestConfig` service for this test and uses it to run the\n * specified workflow.\n *\n * @since 2.0.0\n */\nexport const testConfigWith = <A, E, R>(\n  f: (config: TestConfig.TestConfig) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> =>\n  core.fiberRefGetWith(\n    currentServices,\n    (services) => f(Context.get(services, TestConfig.TestConfig))\n  )\n\n/**\n * Retrieves the `TestConfig` service for this test.\n *\n * @since 2.0.0\n */\nexport const testConfig: Effect.Effect<TestConfig.TestConfig> = testConfigWith(core.succeed)\n\n/**\n * Executes the specified workflow with the specified implementation of the\n * config service.\n *\n * @since 2.0.0\n */\nexport const withTestConfig = dual<\n  (config: TestConfig.TestConfig) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, config: TestConfig.TestConfig) => Effect.Effect<A, E, R>\n>(2, (effect, config) =>\n  core.fiberRefLocallyWith(\n    currentServices,\n    Context.add(TestConfig.TestConfig, config)\n  )(effect))\n\n/**\n * Sets the implementation of the config service to the specified value and\n * restores it to its original value when the scope is closed.\n *\n * @since 2.0.0\n */\nexport const withTestConfigScoped = (config: TestConfig.TestConfig): Effect.Effect<void, never, Scope.Scope> =>\n  fiberRuntime.fiberRefLocallyScopedWith(currentServices, Context.add(TestConfig.TestConfig, config))\n\n/**\n * Constructs a new `TestConfig` service with the specified settings.\n *\n * @since 2.0.0\n */\nexport const testConfigLayer = (params: {\n  readonly repeats: number\n  readonly retries: number\n  readonly samples: number\n  readonly shrinks: number\n}): Layer.Layer<TestConfig.TestConfig> =>\n  layer.scoped(\n    TestConfig.TestConfig,\n    Effect.suspend(() => {\n      const testConfig = TestConfig.make(params)\n      return pipe(\n        withTestConfigScoped(testConfig),\n        core.as(testConfig)\n      )\n    })\n  )\n\n/**\n * The number of times to repeat tests to ensure they are stable.\n *\n * @since 2.0.0\n */\nexport const repeats: Effect.Effect<number> = testConfigWith((config) => core.succeed(config.repeats))\n\n/**\n * The number of times to retry flaky tests.\n *\n * @since 2.0.0\n */\nexport const retries: Effect.Effect<number> = testConfigWith((config) => core.succeed(config.retries))\n\n/**\n * The number of sufficient samples to check for a random variable.\n *\n * @since 2.0.0\n */\nexport const samples: Effect.Effect<number> = testConfigWith((config) => core.succeed(config.samples))\n\n/**\n * The maximum number of shrinkings to minimize large failures.\n *\n * @since 2.0.0\n */\nexport const shrinks: Effect.Effect<number> = testConfigWith((config) => core.succeed(config.shrinks))\n"
  },
  {
    "path": "packages/effect/src/TestSized.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as FiberRef from \"./FiberRef.js\"\nimport * as core from \"./internal/core.js\"\n\n/**\n * @since 2.0.0\n */\nexport const TestSizedTypeId: unique symbol = Symbol.for(\"effect/TestSized\")\n\n/**\n * @since 2.0.0\n */\nexport type TestSizedTypeId = typeof TestSizedTypeId\n\n/**\n * @since 2.0.0\n */\nexport interface TestSized {\n  readonly [TestSizedTypeId]: TestSizedTypeId\n  readonly fiberRef: FiberRef.FiberRef<number>\n  readonly size: Effect.Effect<number>\n  withSize(size: number): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n}\n\n/**\n * @since 2.0.0\n */\nexport const TestSized: Context.Tag<TestSized, TestSized> = Context.GenericTag(\"effect/TestSized\")\n\n/** @internal */\nclass SizedImpl implements TestSized {\n  readonly [TestSizedTypeId]: TestSizedTypeId = TestSizedTypeId\n  constructor(readonly fiberRef: FiberRef.FiberRef<number>) {}\n  get size(): Effect.Effect<number> {\n    return core.fiberRefGet(this.fiberRef)\n  }\n  withSize(size: number) {\n    return <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n      core.fiberRefLocally(this.fiberRef, size)(effect)\n  }\n}\n\n/**\n * @since 2.0.0\n */\nexport const make = (size: number): TestSized => new SizedImpl(core.fiberRefUnsafeMake(size))\n\n/**\n * @since 2.0.0\n */\nexport const fromFiberRef = (fiberRef: FiberRef.FiberRef<number>): TestSized => new SizedImpl(fiberRef)\n"
  },
  {
    "path": "packages/effect/src/Tracer.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport type * as Context from \"./Context.js\"\nimport type * as Effect from \"./Effect.js\"\nimport type * as Exit from \"./Exit.js\"\nimport type * as Fiber from \"./Fiber.js\"\nimport type { LazyArg } from \"./Function.js\"\nimport * as defaultServices from \"./internal/defaultServices.js\"\nimport * as internal from \"./internal/tracer.js\"\nimport type * as Option from \"./Option.js\"\n\n/**\n * @since 2.0.0\n */\nexport const TracerTypeId: unique symbol = internal.TracerTypeId\n\n/**\n * @since 2.0.0\n */\nexport type TracerTypeId = typeof TracerTypeId\n\n/**\n * @since 2.0.0\n */\nexport interface Tracer {\n  readonly [TracerTypeId]: TracerTypeId\n  span(\n    name: string,\n    parent: Option.Option<AnySpan>,\n    context: Context.Context<never>,\n    links: ReadonlyArray<SpanLink>,\n    startTime: bigint,\n    kind: SpanKind,\n    options?: SpanOptions\n  ): Span\n  context<X>(f: () => X, fiber: Fiber.RuntimeFiber<any, any>): X\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type SpanStatus = {\n  _tag: \"Started\"\n  startTime: bigint\n} | {\n  _tag: \"Ended\"\n  startTime: bigint\n  endTime: bigint\n  exit: Exit.Exit<unknown, unknown>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type AnySpan = Span | ExternalSpan\n\n/**\n * @since 2.0.0\n * @category tags\n */\nexport interface ParentSpan {\n  readonly _: unique symbol\n}\n\n/**\n * @since 2.0.0\n * @category tags\n */\nexport const ParentSpan: Context.Tag<ParentSpan, AnySpan> = internal.spanTag\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface ExternalSpan {\n  readonly _tag: \"ExternalSpan\"\n  readonly spanId: string\n  readonly traceId: string\n  readonly sampled: boolean\n  readonly context: Context.Context<never>\n}\n\n/**\n * @since 3.1.0\n * @category models\n */\nexport interface SpanOptions {\n  readonly attributes?: Record<string, unknown> | undefined\n  readonly links?: ReadonlyArray<SpanLink> | undefined\n  readonly parent?: AnySpan | undefined\n  readonly root?: boolean | undefined\n  readonly context?: Context.Context<never> | undefined\n  readonly kind?: SpanKind | undefined\n  readonly captureStackTrace?: boolean | LazyArg<string | undefined> | undefined\n}\n\n/**\n * @since 3.1.0\n * @category models\n */\nexport type SpanKind = \"internal\" | \"server\" | \"client\" | \"producer\" | \"consumer\"\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Span {\n  readonly _tag: \"Span\"\n  readonly name: string\n  readonly spanId: string\n  readonly traceId: string\n  readonly parent: Option.Option<AnySpan>\n  readonly context: Context.Context<never>\n  readonly status: SpanStatus\n  readonly attributes: ReadonlyMap<string, unknown>\n  readonly links: ReadonlyArray<SpanLink>\n  readonly sampled: boolean\n  readonly kind: SpanKind\n  end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void\n  attribute(key: string, value: unknown): void\n  event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void\n  addLinks(links: ReadonlyArray<SpanLink>): void\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface SpanLink {\n  readonly _tag: \"SpanLink\"\n  readonly span: AnySpan\n  readonly attributes: Readonly<Record<string, unknown>>\n}\n\n/**\n * @since 2.0.0\n * @category tags\n */\nexport const Tracer: Context.Tag<Tracer, Tracer> = internal.tracerTag\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const make: (options: Omit<Tracer, typeof TracerTypeId>) => Tracer = internal.make\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const externalSpan: (\n  options: {\n    readonly spanId: string\n    readonly traceId: string\n    readonly sampled?: boolean | undefined\n    readonly context?: Context.Context<never> | undefined\n  }\n) => ExternalSpan = internal.externalSpan\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const tracerWith: <A, E, R>(f: (tracer: Tracer) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> =\n  defaultServices.tracerWith\n\n/**\n * @since 3.12.0\n * @category annotations\n */\nexport interface DisablePropagation {\n  readonly _: unique symbol\n}\n\n/**\n * @since 3.12.0\n * @category annotations\n */\nexport const DisablePropagation: Context.Reference<DisablePropagation, boolean> = internal.DisablePropagation\n"
  },
  {
    "path": "packages/effect/src/Trie.ts",
    "content": "/**\n * A `Trie` is used for locating specific `string` keys from within a set.\n *\n * It works similar to `HashMap`, but with keys required to be `string`.\n * This constraint unlocks some performance optimizations and new methods to get string prefixes (e.g. `keysWithPrefix`, `longestPrefixOf`).\n *\n * Prefix search is also the main feature that makes a `Trie` more suited than `HashMap` for certain usecases.\n *\n * A `Trie` is often used to store a dictionary (list of words) that can be searched\n * in a manner that allows for efficient generation of completion lists\n * (e.g. predict the rest of a word a user is typing).\n *\n * A `Trie` has O(n) lookup time where `n` is the size of the key,\n * or even less than `n` on search misses.\n *\n * @since 2.0.0\n */\nimport type { Equal } from \"./Equal.js\"\nimport type { Inspectable } from \"./Inspectable.js\"\nimport * as TR from \"./internal/trie.js\"\nimport type { Option } from \"./Option.js\"\nimport type { Pipeable } from \"./Pipeable.js\"\nimport type { Covariant, NoInfer } from \"./Types.js\"\n\nconst TypeId: unique symbol = TR.TrieTypeId as TypeId\n\n/**\n * @since 2.0.0\n * @category symbol\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Trie<out Value> extends Iterable<[string, Value]>, Equal, Pipeable, Inspectable {\n  readonly [TypeId]: {\n    readonly _Value: Covariant<Value>\n  }\n}\n\n/**\n * Creates an empty `Trie`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Equal } from \"effect\"\n *\n * const trie = Trie.empty<string>()\n *\n * assert.equal(Trie.size(trie), 0)\n * assert.deepStrictEqual(Array.from(trie), [])\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const empty: <V = never>() => Trie<V> = TR.empty\n\n/**\n * Creates a new `Trie` from an iterable collection of key/value pairs (e.g. `Array<[string, V]>`).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Equal } from \"effect\"\n *\n * const iterable: Array<readonly [string, number]> = [[\"call\", 0], [\"me\", 1], [\"mind\", 2], [\"mid\", 3]]\n * const trie = Trie.fromIterable(iterable)\n *\n * // The entries in the `Trie` are extracted in alphabetical order, regardless of the insertion order\n * assert.deepStrictEqual(Array.from(trie), [[\"call\", 0], [\"me\", 1], [\"mid\", 3], [\"mind\", 2]])\n * assert.equal(Equal.equals(Trie.make([\"call\", 0], [\"me\", 1], [\"mind\", 2], [\"mid\", 3]), trie), true)\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const fromIterable: <V>(entries: Iterable<readonly [string, V]>) => Trie<V> = TR.fromIterable\n\n/**\n * Constructs a new `Trie` from the specified entries (`[string, V]`).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Equal } from \"effect\"\n *\n * const trie = Trie.make([\"ca\", 0], [\"me\", 1])\n *\n * assert.deepStrictEqual(Array.from(trie), [[\"ca\", 0], [\"me\", 1]])\n * assert.equal(Equal.equals(Trie.fromIterable([[\"ca\", 0], [\"me\", 1]]), trie), true)\n * ```\n *\n * @since 2.0.0\n * @category constructors\n */\nexport const make: <Entries extends Array<readonly [string, any]>>(\n  ...entries: Entries\n) => Trie<Entries[number] extends readonly [any, infer V] ? V : never> = TR.make\n\n/**\n * Insert a new entry in the `Trie`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie1 = Trie.empty<number>().pipe(\n *   Trie.insert(\"call\", 0)\n * )\n * const trie2 = trie1.pipe(Trie.insert(\"me\", 1))\n * const trie3 = trie2.pipe(Trie.insert(\"mind\", 2))\n * const trie4 = trie3.pipe(Trie.insert(\"mid\", 3))\n *\n * assert.deepStrictEqual(Array.from(trie1), [[\"call\", 0]])\n * assert.deepStrictEqual(Array.from(trie2), [[\"call\", 0], [\"me\", 1]])\n * assert.deepStrictEqual(Array.from(trie3), [[\"call\", 0], [\"me\", 1], [\"mind\", 2]])\n * assert.deepStrictEqual(Array.from(trie4), [[\"call\", 0], [\"me\", 1], [\"mid\", 3], [\"mind\", 2]])\n * ```\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const insert: {\n  <V1>(key: string, value: V1): <V>(self: Trie<V>) => Trie<V | V1>\n  <V1, V>(self: Trie<V>, key: string, value: V1): Trie<V | V1>\n} = TR.insert\n\n/**\n * Returns an `IterableIterator` of the keys within the `Trie`.\n *\n * The keys are returned in alphabetical order, regardless of insertion order.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"cab\", 0),\n *   Trie.insert(\"abc\", 1),\n *   Trie.insert(\"bca\", 2)\n * )\n *\n * const result = Array.from(Trie.keys(trie))\n * assert.deepStrictEqual(result, [\"abc\", \"bca\", \"cab\"])\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const keys: <V>(self: Trie<V>) => IterableIterator<string> = TR.keys\n\n/**\n * Returns an `IterableIterator` of the values within the `Trie`.\n *\n * Values are ordered based on their key in alphabetical order, regardless of insertion order.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"call\", 0),\n *   Trie.insert(\"me\", 1),\n *   Trie.insert(\"and\", 2)\n * )\n *\n * const result = Array.from(Trie.values(trie))\n * assert.deepStrictEqual(result, [2, 0, 1])\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const values: <V>(self: Trie<V>) => IterableIterator<V> = TR.values\n\n/**\n * Returns an `IterableIterator` of the entries within the `Trie`.\n *\n * The entries are returned by keys in alphabetical order, regardless of insertion order.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"call\", 0),\n *   Trie.insert(\"me\", 1)\n * )\n *\n * const result = Array.from(Trie.entries(trie))\n * assert.deepStrictEqual(result, [[\"call\", 0], [\"me\", 1]])\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const entries: <V>(self: Trie<V>) => IterableIterator<[string, V]> = TR.entries\n\n/**\n * Returns an `Array<[K, V]>` of the entries within the `Trie`.\n *\n * Equivalent to `Array.from(Trie.entries(trie))`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"call\", 0),\n *   Trie.insert(\"me\", 1)\n * )\n * const result = Trie.toEntries(trie)\n *\n * assert.deepStrictEqual(result, [[\"call\", 0], [\"me\", 1]])\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const toEntries = <V>(self: Trie<V>): Array<[string, V]> => Array.from(entries(self))\n\n/**\n * Returns an `IterableIterator` of the keys within the `Trie`\n * that have `prefix` as prefix (`prefix` included if it exists).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"she\", 0),\n *   Trie.insert(\"shells\", 1),\n *   Trie.insert(\"sea\", 2),\n *   Trie.insert(\"shore\", 3)\n * )\n *\n * const result = Array.from(Trie.keysWithPrefix(trie, \"she\"))\n * assert.deepStrictEqual(result, [\"she\", \"shells\"])\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const keysWithPrefix: {\n  (prefix: string): <V>(self: Trie<V>) => IterableIterator<string>\n  <V>(self: Trie<V>, prefix: string): IterableIterator<string>\n} = TR.keysWithPrefix\n\n/**\n * Returns an `IterableIterator` of the values within the `Trie`\n * that have `prefix` as prefix (`prefix` included if it exists).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"she\", 0),\n *   Trie.insert(\"shells\", 1),\n *   Trie.insert(\"sea\", 2),\n *   Trie.insert(\"shore\", 3)\n * )\n *\n * const result = Array.from(Trie.valuesWithPrefix(trie, \"she\"))\n *\n * // 0: \"she\", 1: \"shells\"\n * assert.deepStrictEqual(result, [0, 1])\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const valuesWithPrefix: {\n  (prefix: string): <V>(self: Trie<V>) => IterableIterator<V>\n  <V>(self: Trie<V>, prefix: string): IterableIterator<V>\n} = TR.valuesWithPrefix\n\n/**\n * Returns an `IterableIterator` of the entries within the `Trie`\n * that have `prefix` as prefix (`prefix` included if it exists).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"she\", 0),\n *   Trie.insert(\"shells\", 1),\n *   Trie.insert(\"sea\", 2),\n *   Trie.insert(\"shore\", 3)\n * )\n *\n * const result = Array.from(Trie.entriesWithPrefix(trie, \"she\"))\n * assert.deepStrictEqual(result, [[\"she\", 0], [\"shells\", 1]])\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const entriesWithPrefix: {\n  (prefix: string): <V>(self: Trie<V>) => IterableIterator<[string, V]>\n  <V>(self: Trie<V>, prefix: string): IterableIterator<[string, V]>\n} = TR.entriesWithPrefix\n\n/**\n * Returns `Array<[K, V]>` of the entries within the `Trie`\n * that have `prefix` as prefix (`prefix` included if it exists).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1),\n *   Trie.insert(\"sea\", 2),\n *   Trie.insert(\"she\", 3)\n * )\n *\n * const result = Trie.toEntriesWithPrefix(trie, \"she\")\n * assert.deepStrictEqual(result, [[\"she\", 3], [\"shells\", 0]])\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const toEntriesWithPrefix: {\n  (prefix: string): <V>(self: Trie<V>) => Array<[string, V]>\n  <V>(self: Trie<V>, prefix: string): Array<[string, V]>\n} = TR.toEntriesWithPrefix\n\n/**\n * Returns the longest key/value in the `Trie`\n * that is a prefix of that `key` if it exists, `None` otherwise.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Option } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1),\n *   Trie.insert(\"she\", 2)\n * )\n *\n * assert.deepStrictEqual(Trie.longestPrefixOf(trie, \"sell\"), Option.none())\n * assert.deepStrictEqual(Trie.longestPrefixOf(trie, \"sells\"), Option.some([\"sells\", 1]))\n * assert.deepStrictEqual(Trie.longestPrefixOf(trie, \"shell\"), Option.some([\"she\", 2]))\n * assert.deepStrictEqual(Trie.longestPrefixOf(trie, \"shellsort\"), Option.some([\"shells\", 0]))\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const longestPrefixOf: {\n  (key: string): <V>(self: Trie<V>) => Option<[string, V]>\n  <V>(self: Trie<V>, key: string): Option<[string, V]>\n} = TR.longestPrefixOf\n\n/**\n * Returns the size of the `Trie` (number of entries in the `Trie`).\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"a\", 0),\n *   Trie.insert(\"b\", 1)\n * )\n *\n * assert.equal(Trie.size(trie), 2)\n * ```\n *\n * @since 2.0.0\n * @category getters\n */\nexport const size: <V>(self: Trie<V>) => number = TR.size\n\n/**\n * Safely lookup the value for the specified key in the `Trie`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Option } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"call\", 0),\n *   Trie.insert(\"me\", 1),\n *   Trie.insert(\"mind\", 2),\n *   Trie.insert(\"mid\", 3)\n * )\n *\n * assert.deepStrictEqual(Trie.get(trie, \"call\"), Option.some(0))\n * assert.deepStrictEqual(Trie.get(trie, \"me\"), Option.some(1))\n * assert.deepStrictEqual(Trie.get(trie, \"mind\"), Option.some(2))\n * assert.deepStrictEqual(Trie.get(trie, \"mid\"), Option.some(3))\n * assert.deepStrictEqual(Trie.get(trie, \"cale\"), Option.none())\n * assert.deepStrictEqual(Trie.get(trie, \"ma\"), Option.none())\n * assert.deepStrictEqual(Trie.get(trie, \"midn\"), Option.none())\n * assert.deepStrictEqual(Trie.get(trie, \"mea\"), Option.none())\n * ```\n *\n * @since 2.0.0\n * @category elements\n */\nexport const get: {\n  (key: string): <V>(self: Trie<V>) => Option<V>\n  <V>(self: Trie<V>, key: string): Option<V>\n} = TR.get\n\n/**\n * Check if the given key exists in the `Trie`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"call\", 0),\n *   Trie.insert(\"me\", 1),\n *   Trie.insert(\"mind\", 2),\n *   Trie.insert(\"mid\", 3)\n * )\n *\n * assert.equal(Trie.has(trie, \"call\"), true)\n * assert.equal(Trie.has(trie, \"me\"), true)\n * assert.equal(Trie.has(trie, \"mind\"), true)\n * assert.equal(Trie.has(trie, \"mid\"), true)\n * assert.equal(Trie.has(trie, \"cale\"), false)\n * assert.equal(Trie.has(trie, \"ma\"), false)\n * assert.equal(Trie.has(trie, \"midn\"), false)\n * assert.equal(Trie.has(trie, \"mea\"), false)\n * ```\n *\n * @since 2.0.0\n * @category elements\n */\nexport const has: {\n  (key: string): <V>(self: Trie<V>) => boolean\n  <V>(self: Trie<V>, key: string): boolean\n} = TR.has\n\n/**\n * Checks if the `Trie` contains any entries.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>()\n * const trie1 = trie.pipe(Trie.insert(\"ma\", 0))\n *\n * assert.equal(Trie.isEmpty(trie), true)\n * assert.equal(Trie.isEmpty(trie1), false)\n * ```\n *\n * @since 2.0.0\n * @category elements\n */\nexport const isEmpty: <V>(self: Trie<V>) => boolean = TR.isEmpty\n\n/**\n * Unsafely lookup the value for the specified key in the `Trie`.\n *\n * `unsafeGet` will throw if the key is not found. Use `get` instead to safely\n * get a value from the `Trie`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"call\", 0),\n *   Trie.insert(\"me\", 1)\n * )\n *\n * assert.throws(() => Trie.unsafeGet(trie, \"mae\"))\n * ```\n *\n * @since 2.0.0\n * @category unsafe\n */\nexport const unsafeGet: {\n  (key: string): <V>(self: Trie<V>) => V\n  <V>(self: Trie<V>, key: string): V\n} = TR.unsafeGet\n\n/**\n * Remove the entry for the specified key in the `Trie`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Option } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"call\", 0),\n *   Trie.insert(\"me\", 1),\n *   Trie.insert(\"mind\", 2),\n *   Trie.insert(\"mid\", 3)\n * )\n *\n * const trie1 = trie.pipe(Trie.remove(\"call\"))\n * const trie2 = trie1.pipe(Trie.remove(\"mea\"))\n *\n * assert.deepStrictEqual(Trie.get(trie, \"call\"), Option.some(0))\n * assert.deepStrictEqual(Trie.get(trie1, \"call\"), Option.none())\n * assert.deepStrictEqual(Trie.get(trie2, \"call\"), Option.none())\n * ```\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const remove: {\n  (key: string): <V>(self: Trie<V>) => Trie<V>\n  <V>(self: Trie<V>, key: string): Trie<V>\n} = TR.remove\n\n/**\n * Reduce a state over the entries of the `Trie`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1),\n *   Trie.insert(\"she\", 2)\n * )\n *\n * assert.equal(\n *   trie.pipe(\n *     Trie.reduce(0, (acc, n) => acc + n)\n *   ),\n *   3\n * )\n * assert.equal(\n *   trie.pipe(\n *     Trie.reduce(10, (acc, n) => acc + n)\n *   ),\n *   13\n * )\n * assert.equal(\n *   trie.pipe(\n *     Trie.reduce(\"\", (acc, _, key) => acc + key)\n *   ),\n *   \"sellssheshells\"\n * )\n * ```\n *\n * @since 2.0.0\n * @category folding\n */\nexport const reduce: {\n  <Z, V>(zero: Z, f: (accumulator: Z, value: V, key: string) => Z): (self: Trie<V>) => Z\n  <Z, V>(self: Trie<V>, zero: Z, f: (accumulator: Z, value: V, key: string) => Z): Z\n} = TR.reduce\n\n/**\n * Maps over the entries of the `Trie` using the specified function.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Equal } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1),\n *   Trie.insert(\"she\", 2)\n * )\n *\n * const trieMapV = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 1),\n *   Trie.insert(\"sells\", 2),\n *   Trie.insert(\"she\", 3)\n * )\n *\n * const trieMapK = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 6),\n *   Trie.insert(\"sells\", 5),\n *   Trie.insert(\"she\", 3)\n * )\n *\n * assert.equal(Equal.equals(Trie.map(trie, (v) => v + 1), trieMapV), true)\n * assert.equal(Equal.equals(Trie.map(trie, (_, k) => k.length), trieMapK), true)\n * ```\n *\n * @since 2.0.0\n * @category folding\n */\nexport const map: {\n  <A, V>(f: (value: V, key: string) => A): (self: Trie<V>) => Trie<A>\n  <V, A>(self: Trie<V>, f: (value: V, key: string) => A): Trie<A>\n} = TR.map\n\n/**\n * Filters entries out of a `Trie` using the specified predicate.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Equal } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1),\n *   Trie.insert(\"she\", 2)\n * )\n *\n * const trieMapV = Trie.empty<number>().pipe(\n *   Trie.insert(\"she\", 2)\n * )\n *\n * const trieMapK = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1)\n * )\n *\n * assert.equal(Equal.equals(Trie.filter(trie, (v) => v > 1), trieMapV), true)\n * assert.equal(Equal.equals(Trie.filter(trie, (_, k) => k.length > 3), trieMapK), true)\n * ```\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filter: {\n  <A, B extends A>(f: (a: NoInfer<A>, k: string) => a is B): (self: Trie<A>) => Trie<B>\n  <A>(f: (a: NoInfer<A>, k: string) => boolean): (self: Trie<A>) => Trie<A>\n  <A, B extends A>(self: Trie<A>, f: (a: A, k: string) => a is B): Trie<B>\n  <A>(self: Trie<A>, f: (a: A, k: string) => boolean): Trie<A>\n} = TR.filter\n\n/**\n * Maps over the entries of the `Trie` using the specified partial function\n * and filters out `None` values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Equal, Option } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1),\n *   Trie.insert(\"she\", 2)\n * )\n *\n * const trieMapV = Trie.empty<number>().pipe(\n *   Trie.insert(\"she\", 2)\n * )\n *\n * const trieMapK = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1)\n * )\n *\n * assert.equal(Equal.equals(Trie.filterMap(trie, (v) => v > 1 ? Option.some(v) : Option.none()), trieMapV), true)\n * assert.equal(\n *   Equal.equals(Trie.filterMap(trie, (v, k) => k.length > 3 ? Option.some(v) : Option.none()), trieMapK),\n *   true\n * )\n * ```\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const filterMap: {\n  <A, B>(f: (value: A, key: string) => Option<B>): (self: Trie<A>) => Trie<B>\n  <A, B>(self: Trie<A>, f: (value: A, key: string) => Option<B>): Trie<B>\n} = TR.filterMap\n\n/**\n * Filters out `None` values from a `Trie` of `Options`s.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Equal, Option } from \"effect\"\n *\n * const trie = Trie.empty<Option.Option<number>>().pipe(\n *   Trie.insert(\"shells\", Option.some(0)),\n *   Trie.insert(\"sells\", Option.none()),\n *   Trie.insert(\"she\", Option.some(2))\n * )\n *\n * const trieMapV = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"she\", 2)\n * )\n *\n * assert.equal(Equal.equals(Trie.compact(trie), trieMapV), true)\n * ```\n *\n * @since 2.0.0\n * @category filtering\n */\nexport const compact: <A>(self: Trie<Option<A>>) => Trie<A> = TR.compact\n\n/**\n * Applies the specified function to the entries of the `Trie`.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie } from \"effect\"\n *\n * let value = 0\n *\n * Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1),\n *   Trie.insert(\"she\", 2),\n *   Trie.forEach((n, key) => {\n *     value += n + key.length\n *   })\n * )\n *\n * assert.equal(value, 17)\n * ```\n *\n * @since 2.0.0\n * @category traversing\n */\nexport const forEach: {\n  <V>(f: (value: V, key: string) => void): (self: Trie<V>) => void\n  <V>(self: Trie<V>, f: (value: V, key: string) => void): void\n} = TR.forEach\n\n/**\n * Updates the value of the specified key within the `Trie` if it exists.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Equal, Option } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1),\n *   Trie.insert(\"she\", 2)\n * )\n *\n * assert.deepStrictEqual(trie.pipe(Trie.modify(\"she\", (v) => v + 10), Trie.get(\"she\")), Option.some(12))\n *\n * assert.equal(Equal.equals(trie.pipe(Trie.modify(\"me\", (v) => v)), trie), true)\n * ```\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const modify: {\n  <V1, V>(key: string, f: (v: V) => V1): (self: Trie<V>) => Trie<V1 | V>\n  <V1, V>(self: Trie<V>, key: string, f: (v: V) => V1): Trie<V | V1>\n} = TR.modify\n\n/**\n * Removes all entries in the `Trie` which have the specified keys.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Equal } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1),\n *   Trie.insert(\"she\", 2)\n * )\n *\n * assert.equal(\n *   Equal.equals(trie.pipe(Trie.removeMany([\"she\", \"sells\"])), Trie.empty<number>().pipe(Trie.insert(\"shells\", 0))),\n *   true\n * )\n * ```\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const removeMany: {\n  (keys: Iterable<string>): <V>(self: Trie<V>) => Trie<V>\n  <V>(self: Trie<V>, keys: Iterable<string>): Trie<V>\n} = TR.removeMany\n\n/**\n * Insert multiple entries in the `Trie` at once.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Trie, Equal } from \"effect\"\n *\n * const trie = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insert(\"sells\", 1),\n *   Trie.insert(\"she\", 2)\n * )\n *\n * const trieInsert = Trie.empty<number>().pipe(\n *   Trie.insert(\"shells\", 0),\n *   Trie.insertMany(\n *     [[\"sells\", 1], [\"she\", 2]]\n *   )\n * )\n *\n * assert.equal(\n *   Equal.equals(trie, trieInsert),\n *   true\n * )\n * ```\n *\n * @since 2.0.0\n * @category mutations\n */\nexport const insertMany: {\n  <V1>(iter: Iterable<[string, V1]>): <V>(self: Trie<V>) => Trie<V | V1>\n  <V1, V>(self: Trie<V>, iter: Iterable<[string, V1]>): Trie<V | V1>\n} = TR.insertMany\n"
  },
  {
    "path": "packages/effect/src/Tuple.ts",
    "content": "/**\n * This module provides utility functions for working with tuples in TypeScript.\n *\n * @since 2.0.0\n */\nimport * as Equivalence from \"./Equivalence.js\"\nimport { dual } from \"./Function.js\"\nimport type { TypeLambda } from \"./HKT.js\"\nimport * as order from \"./Order.js\"\nimport type { TupleOf } from \"./Types.js\"\n\n/**\n * @category type lambdas\n * @since 2.0.0\n */\nexport interface TupleTypeLambda extends TypeLambda {\n  readonly type: [this[\"Out1\"], this[\"Target\"]]\n}\n\n/**\n * Constructs a new tuple from the provided values.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { make } from \"effect/Tuple\"\n *\n * assert.deepStrictEqual(make(1, 'hello', true), [1, 'hello', true])\n * ```\n *\n * @category constructors\n * @since 2.0.0\n */\nexport const make = <A extends ReadonlyArray<any>>(...elements: A): A => elements\n\n/**\n * Return the first element from a tuple with two elements.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { getFirst } from \"effect/Tuple\"\n *\n * assert.deepStrictEqual(getFirst([\"hello\", 42]), \"hello\")\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getFirst = <L, R>(self: readonly [L, R]): L => self[0]\n\n/**\n * Return the second element from a tuple with two elements.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { getSecond } from \"effect/Tuple\"\n *\n * assert.deepStrictEqual(getSecond([\"hello\", 42]), 42)\n * ```\n *\n * @category getters\n * @since 2.0.0\n */\nexport const getSecond = <L, R>(self: readonly [L, R]): R => self[1]\n\n/**\n * Transforms each element of tuple using the given function, treating tuple homomorphically\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { pipe, Tuple } from \"effect\"\n *\n * const result = pipe(\n *   [\"a\", 1, false] as const,\n *   Tuple.map((el) => el.toString().toUpperCase())\n * )\n * assert.deepStrictEqual(result, ['A', '1', 'FALSE'])\n * ```\n *\n * @category mapping\n * @since 3.9.0\n */\nexport const map: {\n  <T extends ReadonlyArray<any> | [], B>(\n    fn: (element: T[number]) => B\n  ): (self: T) => TupleOf<T[\"length\"], B>\n  <B, T extends ReadonlyArray<any> | []>(\n    self: T,\n    fn: (element: T[number]) => B\n  ): TupleOf<T[\"length\"], B>\n} = dual(\n  2,\n  <N extends number, A, B>(\n    self: TupleOf<N, A>,\n    fn: (element: A) => B\n  ): TupleOf<N, B> => self.map((element) => fn(element)) as TupleOf<N, B>\n)\n\n/**\n * Transforms both elements of a tuple with two elements using the given functions.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { mapBoth } from \"effect/Tuple\"\n *\n * assert.deepStrictEqual(\n *   mapBoth([\"hello\", 42], { onFirst: s => s.toUpperCase(), onSecond: n => n.toString() }),\n *   [\"HELLO\", \"42\"]\n * )\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapBoth: {\n  <L1, L2, R1, R2>(options: {\n    readonly onFirst: (e: L1) => L2\n    readonly onSecond: (a: R1) => R2\n  }): (self: readonly [L1, R1]) => [L2, R2]\n  <L1, R1, L2, R2>(self: readonly [L1, R1], options: {\n    readonly onFirst: (e: L1) => L2\n    readonly onSecond: (a: R1) => R2\n  }): [L2, R2]\n} = dual(\n  2,\n  <L1, R1, L2, R2>(\n    self: readonly [L1, R1],\n    { onFirst, onSecond }: {\n      readonly onFirst: (e: L1) => L2\n      readonly onSecond: (a: R1) => R2\n    }\n  ): [L2, R2] => [onFirst(self[0]), onSecond(self[1])]\n)\n\n/**\n * Transforms the first component of a tuple with two elements using a given function.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { mapFirst } from \"effect/Tuple\"\n *\n * assert.deepStrictEqual(\n *   mapFirst([\"hello\", 42], s => s.toUpperCase()),\n *   [\"HELLO\", 42]\n * )\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapFirst: {\n  <L1, L2>(f: (left: L1) => L2): <R>(self: readonly [L1, R]) => [L2, R]\n  <L1, R, L2>(self: readonly [L1, R], f: (left: L1) => L2): [L2, R]\n} = dual(2, <L1, R, L2>(self: readonly [L1, R], f: (left: L1) => L2): [L2, R] => [f(self[0]), self[1]])\n\n/**\n * Transforms the second component of a tuple with two elements using a given function.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { mapSecond } from \"effect/Tuple\"\n *\n * assert.deepStrictEqual(\n *   mapSecond([\"hello\", 42], n => n.toString()),\n *   [\"hello\", \"42\"]\n * )\n * ```\n *\n * @category mapping\n * @since 2.0.0\n */\nexport const mapSecond: {\n  <R1, R2>(f: (right: R1) => R2): <L>(self: readonly [L, R1]) => [L, R2]\n  <L, R1, R2>(self: readonly [L, R1], f: (right: R1) => R2): [L, R2]\n} = dual(2, <L, R1, R2>(self: readonly [L, R1], f: (right: R1) => R2): [L, R2] => [self[0], f(self[1])])\n\n/**\n * Swaps the elements of a tuple with two elements.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { swap } from \"effect/Tuple\"\n *\n * assert.deepStrictEqual(swap([\"hello\", 42]), [42, \"hello\"])\n * ```\n *\n * @since 2.0.0\n */\nexport const swap = <L, R>(self: readonly [L, R]): [R, L] => [self[1], self[0]]\n\n/**\n * Given a tuple of `Equivalence`s returns a new `Equivalence` that compares values of a tuple\n * by applying each `Equivalence` to the corresponding element of the tuple.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const getEquivalence: <T extends ReadonlyArray<Equivalence.Equivalence<any>>>(\n  ...isEquivalents: T\n) => Equivalence.Equivalence<\n  Readonly<{ [I in keyof T]: [T[I]] extends [Equivalence.Equivalence<infer A>] ? A : never }>\n> = Equivalence.tuple\n\n/**\n * This function creates and returns a new `Order` for a tuple of values based on the given `Order`s for each element in the tuple.\n * The returned `Order` compares two tuples of the same type by applying the corresponding `Order` to each element in the tuple.\n * It is useful when you need to compare two tuples of the same type and you have a specific way of comparing each element\n * of the tuple.\n *\n * @category combinators\n * @since 2.0.0\n */\nexport const getOrder: <T extends ReadonlyArray<order.Order<any>>>(\n  ...elements: T\n) => order.Order<{ [I in keyof T]: [T[I]] extends [order.Order<infer A>] ? A : never }> = order.tuple\n\n/**\n * Appends an element to the end of a tuple.\n *\n * @category concatenating\n * @since 2.0.0\n */\nexport const appendElement: {\n  <B>(that: B): <A extends ReadonlyArray<unknown>>(self: A) => [...A, B]\n  <A extends ReadonlyArray<unknown>, B>(self: A, that: B): [...A, B]\n} = dual(2, <A extends ReadonlyArray<unknown>, B>(self: A, that: B): [...A, B] => [...self, that])\n\n/**\n * Retrieves the element at a specified index from a tuple.\n *\n * @example\n * ```ts\n * import * as assert from \"node:assert\"\n * import { Tuple } from \"effect\"\n *\n * assert.deepStrictEqual(Tuple.at([1, 'hello', true], 1), 'hello')\n * ```\n *\n * @category getters\n * @since 3.4.0\n */\nexport const at: {\n  <N extends number>(index: N): <A extends ReadonlyArray<unknown>>(self: A) => A[N]\n  <A extends ReadonlyArray<unknown>, N extends number>(self: A, index: N): A[N]\n} = dual(2, <A extends ReadonlyArray<unknown>, N extends number>(self: A, index: N): A[N] => self[index])\n\nexport {\n  /**\n   * Determine if an `Array` is a tuple with exactly `N` elements, narrowing down the type to `TupleOf`.\n   *\n   * An `Array` is considered to be a `TupleOf` if its length is exactly `N`.\n   *\n   * @example\n   * ```ts\n   * import * as assert from \"node:assert\"\n   * import { isTupleOf } from \"effect/Tuple\"\n   *\n   * assert.deepStrictEqual(isTupleOf([1, 2, 3], 3), true);\n   * assert.deepStrictEqual(isTupleOf([1, 2, 3], 2), false);\n   * assert.deepStrictEqual(isTupleOf([1, 2, 3], 4), false);\n   *\n   * const arr: number[] = [1, 2, 3];\n   * if (isTupleOf(arr, 3)) {\n   *   console.log(arr);\n   *   // ^? [number, number, number]\n   * }\n   *\n   * ```\n   * @category guards\n   * @since 3.3.0\n   */\n  isTupleOf,\n  /**\n   * Determine if an `Array` is a tuple with at least `N` elements, narrowing down the type to `TupleOfAtLeast`.\n   *\n   * An `Array` is considered to be a `TupleOfAtLeast` if its length is at least `N`.\n   *\n   * @example\n   * ```ts\n   * import * as assert from \"node:assert\"\n   * import { isTupleOfAtLeast } from \"effect/Tuple\"\n   *\n   * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 3), true);\n   * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 2), true);\n   * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 4), false);\n   *\n   * const arr: number[] = [1, 2, 3, 4];\n   * if (isTupleOfAtLeast(arr, 3)) {\n   *   console.log(arr);\n   *   // ^? [number, number, number, ...number[]]\n   * }\n   *\n   * ```\n   * @category guards\n   * @since 3.3.0\n   */\n  isTupleOfAtLeast\n} from \"./Predicate.js\"\n"
  },
  {
    "path": "packages/effect/src/Types.ts",
    "content": "/**\n * A collection of types that are commonly used types.\n *\n * @since 2.0.0\n */\n\ntype _TupleOf<T, N extends number, R extends Array<unknown>> = `${N}` extends `-${number}` ? never\n  : R[\"length\"] extends N ? R\n  : _TupleOf<T, N, [T, ...R]>\n\n/**\n * Represents a tuple with a fixed number of elements of type `T`.\n *\n * This type constructs a tuple that has exactly `N` elements of type `T`.\n *\n * @typeParam N - The number of elements in the tuple.\n * @typeParam T - The type of elements in the tuple.\n *\n * @example\n * ```ts\n * import { TupleOf } from \"effect/Types\"\n *\n * // A tuple with exactly 3 numbers\n * const example1: TupleOf<3, number> = [1, 2, 3]; // valid\n * // @ts-expect-error\n * const example2: TupleOf<3, number> = [1, 2]; // invalid\n * // @ts-expect-error\n * const example3: TupleOf<3, number> = [1, 2, 3, 4]; // invalid\n * ```\n *\n * @category tuples\n * @since 3.3.0\n */\nexport type TupleOf<N extends number, T> = N extends N ? number extends N ? Array<T> : _TupleOf<T, N, []> : never\n\n/**\n * Represents a tuple with at least `N` elements of type `T`.\n *\n * This type constructs a tuple that has a fixed number of elements `N` of type `T` at the start,\n * followed by any number (including zero) of additional elements of the same type `T`.\n *\n * @typeParam N - The minimum number of elements in the tuple.\n * @typeParam T - The type of elements in the tuple.\n *\n * @example\n * ```ts\n * import { TupleOfAtLeast } from \"effect/Types\"\n *\n * // A tuple with at least 3 numbers\n * const example1: TupleOfAtLeast<3, number> = [1, 2, 3]; // valid\n * const example2: TupleOfAtLeast<3, number> = [1, 2, 3, 4, 5]; // valid\n * // @ts-expect-error\n * const example3: TupleOfAtLeast<3, number> = [1, 2]; // invalid\n * ```\n *\n * @category tuples\n * @since 3.3.0\n */\nexport type TupleOfAtLeast<N extends number, T> = [...TupleOf<N, T>, ...Array<T>]\n\n/**\n * Returns the tags in a type.\n * @example\n * ```ts\n * import type { Types } from \"effect\"\n *\n * type Res = Types.Tags<string | { _tag: \"a\" } | { _tag: \"b\" } > // \"a\" | \"b\"\n * ```\n *\n * @category types\n * @since 2.0.0\n */\nexport type Tags<E> = E extends { _tag: string } ? E[\"_tag\"] : never\n\n/**\n * Excludes the tagged object from the type.\n * @example\n * ```ts\n * import type { Types } from \"effect\"\n *\n * type Res = Types.ExcludeTag<string | { _tag: \"a\" } | { _tag: \"b\" }, \"a\"> // string | { _tag: \"b\" }\n * ```\n *\n * @category types\n * @since 2.0.0\n */\nexport type ExcludeTag<E, K extends Tags<E>> = Exclude<E, { _tag: K }>\n\n/**\n * Extracts the type of the given tag.\n *\n * @example\n * ```ts\n * import type { Types } from \"effect\"\n *\n * type Res = Types.ExtractTag<{ _tag: \"a\", a: number } | { _tag: \"b\", b: number }, \"b\"> // { _tag: \"b\", b: number }\n * ```\n *\n * @category types\n * @since 2.0.0\n */\nexport type ExtractTag<E, K extends Tags<E>> = Extract<E, { _tag: K }>\n\n/**\n * A utility type that transforms a union type `T` into an intersection type.\n *\n * @since 2.0.0\n * @category types\n */\nexport type UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (x: infer R) => any ? R\n  : never\n\n/**\n * Simplifies the type signature of a type.\n *\n * @example\n * ```ts\n * import type { Types } from \"effect\"\n *\n * type Res = Types.Simplify<{ a: number } & { b: number }> // { a: number; b: number; }\n * ```\n *\n * @since 2.0.0\n * @category types\n */\nexport type Simplify<A> = {\n  [K in keyof A]: A[K]\n} extends infer B ? B : never\n\n/**\n * Determines if two types are equal.\n *\n * @example\n * ```ts\n * import type { Types } from \"effect\"\n *\n * type Res1 = Types.Equals<{ a: number }, { a: number }> // true\n * type Res2 = Types.Equals<{ a: number }, { b: number }> // false\n * ```\n *\n * @since 2.0.0\n * @category models\n */\nexport type Equals<X, Y> = (<T>() => T extends X ? 1 : 2) extends <\n  T\n>() => T extends Y ? 1 : 2 ? true\n  : false\n\n/**\n * Determines if two types are equal, allowing to specify the return types.\n *\n * @since 3.15.0\n * @category models\n */\nexport type EqualsWith<A, B, Y, N> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? Y : N\n\n/**\n * Determines if a record contains any of the given keys.\n *\n * @example\n * ```ts\n * import type { Types } from \"effect\"\n *\n * type Res1 = Types.Has<{ a: number }, \"a\" | \"b\"> // true\n * type Res2 = Types.Has<{ c: number }, \"a\" | \"b\"> // false\n * ```\n *\n * @since 2.0.0\n * @category models\n */\nexport type Has<A, Key extends string> = (Key extends infer K ? K extends keyof A ? true : never : never) extends never\n  ? false\n  : true\n\n/**\n * Merges two object where the keys of the left object take precedence in the case of a conflict.\n *\n * @example\n * ```ts\n * import type { Types } from \"effect\"\n * type MergeLeft = Types.MergeLeft<{ a: number, b: number; }, { a: string }> // { a: number; b: number; }\n * ```\n *\n * @since 2.0.0\n * @category models\n */\nexport type MergeLeft<Source, Target> = MergeRight<Target, Source>\n\n/**\n * Merges two object where the keys of the right object take precedence in the case of a conflict.\n *\n * @example\n * ```ts\n * import type { Types } from \"effect\"\n * type MergeRight = Types.MergeRight<{ a: number, b: number; }, { a: string }> // { a: string; b: number; }\n * ```\n *\n * @since 2.0.0\n * @category models\n */\nexport type MergeRight<Target, Source> = Simplify<\n  & Source\n  & {\n    [Key in keyof Target as Key extends keyof Source ? never : Key]: Target[Key]\n  }\n>\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type MergeRecord<Source, Target> = MergeLeft<Source, Target>\n\n/**\n * Describes the concurrency to use when executing multiple Effect's.\n *\n * @since 2.0.0\n * @category models\n */\nexport type Concurrency = number | \"unbounded\" | \"inherit\"\n\n/**\n * Make all properties in `T` mutable. Supports arrays, tuples, and records as well.\n *\n * @example\n * ```ts\n * import type { Types } from \"effect\"\n *\n * type MutableStruct = Types.Mutable<{ readonly a: string; readonly b: number }> // { a: string; b: number; }\n *\n * type MutableArray = Types.Mutable<ReadonlyArray<string>> // string[]\n *\n * type MutableTuple = Types.Mutable<readonly [string, number]> // [string, number]\n *\n * type MutableRecord = Types.Mutable<{ readonly [_: string]: number }> // { [x: string]: number; }\n * ```\n *\n * @since 2.0.0\n * @category types\n */\nexport type Mutable<T> = {\n  -readonly [P in keyof T]: T[P]\n}\n\n/**\n * Like `Types.Mutable`, but works recursively.\n *\n * @example\n * ```ts\n * import type { Types } from \"effect\"\n *\n * type DeepMutableStruct = Types.DeepMutable<{\n *   readonly a: string;\n *   readonly b: readonly string[]\n * }>\n * // { a: string; b: string[] }\n * ```\n *\n * @since 3.1.0\n * @category types\n */\nexport type DeepMutable<T> = T extends ReadonlyMap<infer K, infer V> ? Map<DeepMutable<K>, DeepMutable<V>>\n  : T extends ReadonlySet<infer V> ? Set<DeepMutable<V>>\n  : T extends string | number | boolean | bigint | symbol | Function ? T\n  : { -readonly [K in keyof T]: DeepMutable<T[K]> }\n\n/**\n * Avoid inference on a specific parameter\n *\n * @since 2.0.0\n * @category models\n */\nexport type NoInfer<A> = [A][A extends any ? 0 : never]\n\n/**\n * Invariant helper.\n *\n * @since 2.0.0\n * @category models\n */\nexport type Invariant<A> = (_: A) => A\n\n/**\n * @since 3.9.0\n * @category models\n */\nexport declare namespace Invariant {\n  /**\n   * @since 3.9.0\n   * @category models\n   */\n  export type Type<A> = A extends Invariant<infer U> ? U : never\n}\n\n/**\n * Covariant helper.\n *\n * @since 2.0.0\n * @category models\n */\nexport type Covariant<A> = (_: never) => A\n\n/**\n * @since 3.9.0\n * @category models\n */\nexport declare namespace Covariant {\n  /**\n   * @since 3.9.0\n   * @category models\n   */\n  export type Type<A> = A extends Covariant<infer U> ? U : never\n}\n\n/**\n * Contravariant helper.\n *\n * @since 2.0.0\n * @category models\n */\nexport type Contravariant<A> = (_: A) => void\n\n/**\n * @since 3.9.0\n * @category models\n */\nexport declare namespace Contravariant {\n  /**\n   * @since 3.9.0\n   * @category models\n   */\n  export type Type<A> = A extends Contravariant<infer U> ? U : never\n}\n\n/**\n * @since 2.0.0\n */\nexport type MatchRecord<S, onTrue, onFalse> = {} extends S ? onTrue : onFalse\n\n/**\n * @since 2.0.0\n */\nexport type NotFunction<T> = T extends Function ? never : T\n\n/**\n * @since 3.9.0\n */\nexport type NoExcessProperties<T, U> = T & { readonly [K in Exclude<keyof U, keyof T>]: never }\n\n/**\n * @since 3.15.0\n */\nexport type Ctor<T = {}> = new(...args: Array<any>) => T\n\n/**\n * Conditional type that returns `void` if `S` is an empty object type,\n * otherwise returns `S`.\n *\n * @since 3.19.20\n */\nexport type VoidIfEmpty<S> = keyof S extends never ? void : S\n"
  },
  {
    "path": "packages/effect/src/Unify.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport { identity } from \"./Function.js\"\n\n/**\n * @since 2.0.0\n */\nexport declare const unifySymbol: unique symbol\n\n/**\n * @since 2.0.0\n */\nexport type unifySymbol = typeof unifySymbol\n\n/**\n * @since 2.0.0\n */\nexport declare const typeSymbol: unique symbol\n\n/**\n * @since 2.0.0\n */\nexport type typeSymbol = typeof typeSymbol\n\n/**\n * @since 2.0.0\n */\nexport declare const ignoreSymbol: unique symbol\n\n/**\n * @since 2.0.0\n */\nexport type ignoreSymbol = typeof ignoreSymbol\n\ntype MaybeReturn<F> = F extends () => infer R ? R : NonNullable<F>\n\ntype Values<X extends [any, any]> = X extends [infer A, infer Ignore]\n  ? Exclude<keyof A, Ignore> extends infer k ? k extends keyof A ? MaybeReturn<A[k]> : never : never\n  : never\n\ntype Ignore<X> = X extends { [ignoreSymbol]?: infer Obj } ? keyof NonNullable<Obj>\n  : never\n\ntype ExtractTypes<\n  X\n> = X extends {\n  [typeSymbol]?: infer _Type\n  [unifySymbol]?: infer _Unify\n} ? [NonNullable<_Unify>, Ignore<X>]\n  : never\n\ntype FilterIn<A> = A extends any ? typeSymbol extends keyof A ? A : never : never\n\ntype FilterOut<A> = A extends any ? typeSymbol extends keyof A ? never : A : never\n\n/**\n * @since 2.0.0\n */\nexport type Unify<A> = Values<\n  ExtractTypes<\n    (\n      & FilterIn<A>\n      & { [typeSymbol]: A }\n    )\n  >\n> extends infer Z ? Z | Exclude<A, Z> | FilterOut<A> : never\n\n/**\n * @since 2.0.0\n */\nexport const unify: {\n  <\n    Args extends Array<any>,\n    Args2 extends Array<any>,\n    Args3 extends Array<any>,\n    Args4 extends Array<any>,\n    Args5 extends Array<any>,\n    T\n  >(\n    x: (...args: Args) => (...args: Args2) => (...args: Args3) => (...args: Args4) => (...args: Args5) => T\n  ): (...args: Args) => (...args: Args2) => (...args: Args3) => (...args: Args4) => (...args: Args5) => Unify<T>\n  <\n    Args extends Array<any>,\n    Args2 extends Array<any>,\n    Args3 extends Array<any>,\n    Args4 extends Array<any>,\n    T\n  >(\n    x: (...args: Args) => (...args: Args2) => (...args: Args3) => (...args: Args4) => T\n  ): (...args: Args) => (...args: Args2) => (...args: Args3) => (...args: Args4) => Unify<T>\n  <\n    Args extends Array<any>,\n    Args2 extends Array<any>,\n    Args3 extends Array<any>,\n    T\n  >(\n    x: (...args: Args) => (...args: Args2) => (...args: Args3) => T\n  ): (...args: Args) => (...args: Args2) => (...args: Args3) => Unify<T>\n  <\n    Args extends Array<any>,\n    Args2 extends Array<any>,\n    T\n  >(\n    x: (...args: Args) => (...args: Args2) => T\n  ): (...args: Args) => (...args: Args2) => Unify<T>\n  <\n    Args extends Array<any>,\n    T\n  >(x: (...args: Args) => T): (...args: Args) => Unify<T>\n  <T>(x: T): Unify<T>\n} = identity as any\n"
  },
  {
    "path": "packages/effect/src/UpstreamPullRequest.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/channel/upstreamPullRequest.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const UpstreamPullRequestTypeId: unique symbol = internal.UpstreamPullRequestTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type UpstreamPullRequestTypeId = typeof UpstreamPullRequestTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type UpstreamPullRequest<A> = Pulled<A> | NoUpstream\n\n/**\n * @since 2.0.0\n */\nexport declare namespace UpstreamPullRequest {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out A> {\n    readonly [UpstreamPullRequestTypeId]: {\n      readonly _A: Types.Covariant<A>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface Pulled<out A> extends UpstreamPullRequest.Variance<A> {\n  readonly _tag: \"Pulled\"\n  readonly value: A\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface NoUpstream extends UpstreamPullRequest.Variance<never> {\n  readonly _tag: \"NoUpstream\"\n  readonly activeDownstreamCount: number\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const Pulled: <A>(value: A) => UpstreamPullRequest<A> = internal.Pulled\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const NoUpstream: (activeDownstreamCount: number) => UpstreamPullRequest<never> = internal.NoUpstream\n\n/**\n * Returns `true` if the specified value is an `UpstreamPullRequest`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isUpstreamPullRequest: (u: unknown) => u is UpstreamPullRequest<unknown> = internal.isUpstreamPullRequest\n\n/**\n * Returns `true` if the specified `UpstreamPullRequest` is a `Pulled`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isPulled: <A>(self: UpstreamPullRequest<A>) => self is Pulled<A> = internal.isPulled\n\n/**\n * Returns `true` if the specified `UpstreamPullRequest` is a `NoUpstream`,\n * `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isNoUpstream: <A>(self: UpstreamPullRequest<A>) => self is NoUpstream = internal.isNoUpstream\n\n/**\n * Folds an `UpstreamPullRequest<A>` into a value of type `Z`.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <A, Z>(\n    options: {\n      readonly onPulled: (value: A) => Z\n      readonly onNoUpstream: (activeDownstreamCount: number) => Z\n    }\n  ): (self: UpstreamPullRequest<A>) => Z\n  <A, Z>(\n    self: UpstreamPullRequest<A>,\n    options: {\n      readonly onPulled: (value: A) => Z\n      readonly onNoUpstream: (activeDownstreamCount: number) => Z\n    }\n  ): Z\n} = internal.match\n"
  },
  {
    "path": "packages/effect/src/UpstreamPullStrategy.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as internal from \"./internal/channel/upstreamPullStrategy.js\"\nimport type * as Option from \"./Option.js\"\nimport type * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport const UpstreamPullStrategyTypeId: unique symbol = internal.UpstreamPullStrategyTypeId\n\n/**\n * @since 2.0.0\n * @category symbols\n */\nexport type UpstreamPullStrategyTypeId = typeof UpstreamPullStrategyTypeId\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport type UpstreamPullStrategy<A> = PullAfterNext<A> | PullAfterAllEnqueued<A>\n\n/**\n * @since 2.0.0\n */\nexport declare namespace UpstreamPullStrategy {\n  /**\n   * @since 2.0.0\n   * @category models\n   */\n  export interface Variance<out A> {\n    readonly [UpstreamPullStrategyTypeId]: {\n      readonly _A: Types.Covariant<A>\n    }\n  }\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface PullAfterNext<out A> extends UpstreamPullStrategy.Variance<A> {\n  readonly _tag: \"PullAfterNext\"\n  readonly emitSeparator: Option.Option<A>\n}\n\n/**\n * @since 2.0.0\n * @category models\n */\nexport interface PullAfterAllEnqueued<out A> extends UpstreamPullStrategy.Variance<A> {\n  readonly _tag: \"PullAfterAllEnqueued\"\n  readonly emitSeparator: Option.Option<A>\n}\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const PullAfterNext: <A>(emitSeparator: Option.Option<A>) => UpstreamPullStrategy<A> = internal.PullAfterNext\n\n/**\n * @since 2.0.0\n * @category constructors\n */\nexport const PullAfterAllEnqueued: <A>(emitSeparator: Option.Option<A>) => UpstreamPullStrategy<A> =\n  internal.PullAfterAllEnqueued\n\n/**\n * Returns `true` if the specified value is an `UpstreamPullStrategy`, `false`\n * otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isUpstreamPullStrategy: (u: unknown) => u is UpstreamPullStrategy<unknown> =\n  internal.isUpstreamPullStrategy\n\n/**\n * Returns `true` if the specified `UpstreamPullStrategy` is a `PullAfterNext`,\n * `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isPullAfterNext: <A>(self: UpstreamPullStrategy<A>) => self is PullAfterNext<A> = internal.isPullAfterNext\n\n/**\n * Returns `true` if the specified `UpstreamPullStrategy` is a\n * `PullAfterAllEnqueued`, `false` otherwise.\n *\n * @since 2.0.0\n * @category refinements\n */\nexport const isPullAfterAllEnqueued: <A>(self: UpstreamPullStrategy<A>) => self is PullAfterAllEnqueued<A> =\n  internal.isPullAfterAllEnqueued\n\n/**\n * Folds an `UpstreamPullStrategy<A>` into a value of type `Z`.\n *\n * @since 2.0.0\n * @category folding\n */\nexport const match: {\n  <A, Z>(\n    options: {\n      readonly onNext: (emitSeparator: Option.Option<A>) => Z\n      readonly onAllEnqueued: (emitSeparator: Option.Option<A>) => Z\n    }\n  ): (self: UpstreamPullStrategy<A>) => Z\n  <A, Z>(\n    self: UpstreamPullStrategy<A>,\n    options: {\n      readonly onNext: (emitSeparator: Option.Option<A>) => Z\n      readonly onAllEnqueued: (emitSeparator: Option.Option<A>) => Z\n    }\n  ): Z\n} = internal.match\n"
  },
  {
    "path": "packages/effect/src/Utils.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport { identity } from \"./Function.js\"\nimport { globalValue } from \"./GlobalValue.js\"\nimport type { Kind, TypeLambda } from \"./HKT.js\"\nimport { getBugErrorMessage } from \"./internal/errors.js\"\nimport { isNullable, isObject } from \"./Predicate.js\"\nimport type * as Types from \"./Types.js\"\n\n/*\n * Copyright 2014 Thom Chiovoloni, released under the MIT license.\n *\n * A random number generator based on the basic implementation of the PCG algorithm,\n * as described here: http://www.pcg-random.org/\n *\n * Adapted for TypeScript from Thom's original code at https://github.com/thomcc/pcg-random\n *\n * forked from https://github.com/frptools\n *\n * @since 2.0.0\n */\n\n/**\n * @category symbols\n * @since 2.0.0\n */\nexport const GenKindTypeId: unique symbol = Symbol.for(\"effect/Gen/GenKind\")\n\n/**\n * @category symbols\n * @since 2.0.0\n */\nexport type GenKindTypeId = typeof GenKindTypeId\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface GenKind<F extends TypeLambda, R, O, E, A> extends Variance<F, R, O, E> {\n  readonly value: Kind<F, R, O, E, A>\n\n  [Symbol.iterator](): IterableIterator<GenKind<F, R, O, E, A>, A>\n}\n\n/**\n * @category predicates\n * @since 3.0.6\n */\nexport const isGenKind = (u: unknown): u is GenKind<any, any, any, any, any> => isObject(u) && GenKindTypeId in u\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport class GenKindImpl<F extends TypeLambda, R, O, E, A> implements GenKind<F, R, O, E, A> {\n  constructor(\n    /**\n     * @since 2.0.0\n     */\n    readonly value: Kind<F, R, O, E, A>\n  ) {}\n\n  /**\n   * @since 2.0.0\n   */\n  get _F() {\n    return identity\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  get _R() {\n    return (_: R) => _\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  get _O() {\n    return (_: never): O => _\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  get _E() {\n    return (_: never): E => _\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  readonly [GenKindTypeId]: typeof GenKindTypeId = GenKindTypeId;\n\n  /**\n   * @since 2.0.0\n   */\n  [Symbol.iterator](): IterableIterator<GenKind<F, R, O, E, A>, A> {\n    return new SingleShotGen<GenKind<F, R, O, E, A>, A>(this as any)\n  }\n}\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport class SingleShotGen<T, A> implements IterableIterator<T, A> {\n  private called = false\n\n  constructor(readonly self: T) {}\n\n  /**\n   * @since 2.0.0\n   */\n  next(a: A): IteratorResult<T, A> {\n    return this.called ?\n      ({\n        value: a,\n        done: true\n      }) :\n      (this.called = true,\n        ({\n          value: this.self,\n          done: false\n        }))\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  return(a: A): IteratorResult<T, A> {\n    return ({\n      value: a,\n      done: true\n    })\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  throw(e: unknown): IteratorResult<T, A> {\n    throw e\n  }\n\n  /**\n   * @since 2.0.0\n   */\n  [Symbol.iterator](): IterableIterator<T, A> {\n    return new SingleShotGen<T, A>(this.self)\n  }\n}\n\n/**\n * @category constructors\n * @since 2.0.0\n */\nexport const makeGenKind = <F extends TypeLambda, R, O, E, A>(\n  kind: Kind<F, R, O, E, A>\n): GenKind<F, R, O, E, A> => new GenKindImpl(kind)\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface Variance<in out F extends TypeLambda, in R, out O, out E> {\n  readonly [GenKindTypeId]: GenKindTypeId\n  readonly _F: Types.Invariant<F>\n  readonly _R: Types.Contravariant<R>\n  readonly _O: Types.Covariant<O>\n  readonly _E: Types.Covariant<E>\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface Gen<F extends TypeLambda, Z> {\n  <Self, K extends Variance<F, any, any, any> | YieldWrap<Kind<F, any, any, any, any>>, A>(\n    ...args:\n      | [\n        self: Self,\n        body: (this: Self, resume: Z) => Generator<K, A, never>\n      ]\n      | [\n        body: (resume: Z) => Generator<K, A, never>\n      ]\n  ): Kind<\n    F,\n    [K] extends [Variance<F, infer R, any, any>] ? R\n      : [K] extends [YieldWrap<Kind<F, infer R, any, any, any>>] ? R\n      : never,\n    [K] extends [Variance<F, any, infer O, any>] ? O\n      : [K] extends [YieldWrap<Kind<F, any, infer O, any, any>>] ? O\n      : never,\n    [K] extends [Variance<F, any, any, infer E>] ? E\n      : [K] extends [YieldWrap<Kind<F, any, any, infer E, any>>] ? E\n      : never,\n    A\n  >\n}\n\n/**\n * @category models\n * @since 2.0.0\n */\nexport interface Adapter<Z extends TypeLambda> {\n  <_R, _O, _E, _A>(\n    self: Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, _R, _O, _E, _A>(a: A, ab: (a: A) => Kind<Z, _R, _O, _E, _A>): GenKind<Z, _R, _O, _E, _A>\n  <A, B, _R, _O, _E, _A>(a: A, ab: (a: A) => B, bc: (b: B) => Kind<Z, _R, _O, _E, _A>): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: F) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (g: H) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, K, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, K, L, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => R,\n    rs: (r: R) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => R,\n    rs: (r: R) => S,\n    st: (s: S) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, _R, _O, _E, _A>(\n    a: A,\n    ab: (a: A) => B,\n    bc: (b: B) => C,\n    cd: (c: C) => D,\n    de: (d: D) => E,\n    ef: (e: E) => F,\n    fg: (f: F) => G,\n    gh: (g: G) => H,\n    hi: (h: H) => I,\n    ij: (i: I) => J,\n    jk: (j: J) => K,\n    kl: (k: K) => L,\n    lm: (l: L) => M,\n    mn: (m: M) => N,\n    no: (n: N) => O,\n    op: (o: O) => P,\n    pq: (p: P) => Q,\n    qr: (q: Q) => R,\n    rs: (r: R) => S,\n    st: (s: S) => T,\n    tu: (s: T) => Kind<Z, _R, _O, _E, _A>\n  ): GenKind<Z, _R, _O, _E, _A>\n}\n\n/**\n * @category adapters\n * @since 2.0.0\n */\nexport const adapter: <F extends TypeLambda>() => Adapter<F> = () => (function() {\n  let x = arguments[0]\n  for (let i = 1; i < arguments.length; i++) {\n    x = arguments[i](x)\n  }\n  return new GenKindImpl(x) as any\n})\n\nconst defaultIncHi = 0x14057b7e\nconst defaultIncLo = 0xf767814f\nconst MUL_HI = 0x5851f42d >>> 0\nconst MUL_LO = 0x4c957f2d >>> 0\nconst BIT_53 = 9007199254740992.0\nconst BIT_27 = 134217728.0\n\n/**\n * @category model\n * @since 2.0.0\n */\nexport type PCGRandomState = [number, number, number, number]\n\n/**\n * @category model\n * @since 2.0.0\n */\nexport type OptionalNumber = number | null | undefined\n\n/**\n * PCG is a family of simple fast space-efficient statistically good algorithms\n * for random number generation. Unlike many general-purpose RNGs, they are also\n * hard to predict.\n *\n * @category model\n * @since 2.0.0\n */\nexport class PCGRandom {\n  private _state!: Int32Array\n\n  /**\n   * Creates an instance of PCGRandom.\n   *\n   * - `seed` - The low 32 bits of the seed (0 is used for high 32 bits).\n   *\n   * @memberOf PCGRandom\n   */\n  constructor(seed?: OptionalNumber)\n  /**\n   * Creates an instance of PCGRandom.\n   *\n   * - `seedHi` - The high 32 bits of the seed.\n   * - `seedLo` - The low 32 bits of the seed.\n   * - `inc` - The low 32 bits of the incrementer (0 is used for high 32 bits).\n   *\n   * @memberOf PCGRandom\n   */\n  constructor(seedHi: OptionalNumber, seedLo: OptionalNumber, inc?: OptionalNumber)\n  /**\n   * Creates an instance of PCGRandom.\n   *\n   * - `seedHi` - The high 32 bits of the seed.\n   * - `seedLo` - The low 32 bits of the seed.\n   * - `incHi` - The high 32 bits of the incrementer.\n   * - `incLo` - The low 32 bits of the incrementer.\n   *\n   * @memberOf PCGRandom\n   */\n  constructor(\n    seedHi: OptionalNumber,\n    seedLo: OptionalNumber,\n    incHi: OptionalNumber,\n    incLo: OptionalNumber\n  )\n  constructor(\n    seedHi?: OptionalNumber,\n    seedLo?: OptionalNumber,\n    incHi?: OptionalNumber,\n    incLo?: OptionalNumber\n  ) {\n    if (isNullable(seedLo) && isNullable(seedHi)) {\n      seedLo = (Math.random() * 0xffffffff) >>> 0\n      seedHi = 0\n    } else if (isNullable(seedLo)) {\n      seedLo = seedHi\n      seedHi = 0\n    }\n    if (isNullable(incLo) && isNullable(incHi)) {\n      incLo = this._state ? this._state[3] : defaultIncLo\n      incHi = this._state ? this._state[2] : defaultIncHi\n    } else if (isNullable(incLo)) {\n      incLo = <number> incHi\n      incHi = 0\n    }\n\n    this._state = new Int32Array([0, 0, (<number> incHi) >>> 0, ((incLo || 0) | 1) >>> 0])\n    this._next()\n    add64(\n      this._state,\n      this._state[0]!,\n      this._state[1]!,\n      (<number> seedHi) >>> 0,\n      (<number> seedLo) >>> 0\n    )\n    this._next()\n    return this\n  }\n\n  /**\n   * Returns a copy of the internal state of this random number generator as a\n   * JavaScript Array.\n   *\n   * @category getters\n   * @since 2.0.0\n   */\n  getState(): PCGRandomState {\n    return [this._state[0]!, this._state[1]!, this._state[2]!, this._state[3]!]\n  }\n\n  /**\n   * Restore state previously retrieved using `getState()`.\n   *\n   * @since 2.0.0\n   */\n  setState(state: PCGRandomState) {\n    this._state[0] = state[0]\n    this._state[1] = state[1]\n    this._state[2] = state[2]\n    this._state[3] = state[3] | 1\n  }\n\n  /**\n   * Get a uniformly distributed 32 bit integer between [0, max).\n   *\n   * @category getter\n   * @since 2.0.0\n   */\n  integer(max: number) {\n    return Math.round(this.number() * Number.MAX_SAFE_INTEGER) % max\n  }\n\n  /**\n   * Get a uniformly distributed IEEE-754 double between 0.0 and 1.0, with\n   * 53 bits of precision (every bit of the mantissa is randomized).\n   *\n   * @category getters\n   * @since 2.0.0\n   */\n  number() {\n    const hi = (this._next() & 0x03ffffff) * 1.0\n    const lo = (this._next() & 0x07ffffff) * 1.0\n    return (hi * BIT_27 + lo) / BIT_53\n  }\n\n  /** @internal */\n  private _next() {\n    // save current state (what we'll use for this number)\n    const oldHi = this._state[0]! >>> 0\n    const oldLo = this._state[1]! >>> 0\n\n    // churn LCG.\n    mul64(this._state, oldHi, oldLo, MUL_HI, MUL_LO)\n    add64(this._state, this._state[0]!, this._state[1]!, this._state[2]!, this._state[3]!)\n\n    // get least sig. 32 bits of ((oldstate >> 18) ^ oldstate) >> 27\n    let xsHi = oldHi >>> 18\n    let xsLo = ((oldLo >>> 18) | (oldHi << 14)) >>> 0\n    xsHi = (xsHi ^ oldHi) >>> 0\n    xsLo = (xsLo ^ oldLo) >>> 0\n    const xorshifted = ((xsLo >>> 27) | (xsHi << 5)) >>> 0\n    // rotate xorshifted right a random amount, based on the most sig. 5 bits\n    // bits of the old state.\n    const rot = oldHi >>> 27\n    const rot2 = ((-rot >>> 0) & 31) >>> 0\n    return ((xorshifted >>> rot) | (xorshifted << rot2)) >>> 0\n  }\n}\n\nfunction mul64(\n  out: Int32Array,\n  aHi: number,\n  aLo: number,\n  bHi: number,\n  bLo: number\n): void {\n  let c1 = ((aLo >>> 16) * (bLo & 0xffff)) >>> 0\n  let c0 = ((aLo & 0xffff) * (bLo >>> 16)) >>> 0\n\n  let lo = ((aLo & 0xffff) * (bLo & 0xffff)) >>> 0\n  let hi = ((aLo >>> 16) * (bLo >>> 16) + ((c0 >>> 16) + (c1 >>> 16))) >>> 0\n\n  c0 = (c0 << 16) >>> 0\n  lo = (lo + c0) >>> 0\n  if ((lo >>> 0) < (c0 >>> 0)) {\n    hi = (hi + 1) >>> 0\n  }\n\n  c1 = (c1 << 16) >>> 0\n  lo = (lo + c1) >>> 0\n  if ((lo >>> 0) < (c1 >>> 0)) {\n    hi = (hi + 1) >>> 0\n  }\n\n  hi = (hi + Math.imul(aLo, bHi)) >>> 0\n  hi = (hi + Math.imul(aHi, bLo)) >>> 0\n\n  out[0] = hi\n  out[1] = lo\n}\n\n// add two 64 bit numbers (given in parts), and store the result in `out`.\nfunction add64(\n  out: Int32Array,\n  aHi: number,\n  aLo: number,\n  bHi: number,\n  bLo: number\n): void {\n  let hi = (aHi + bHi) >>> 0\n  const lo = (aLo + bLo) >>> 0\n  if ((lo >>> 0) < (aLo >>> 0)) {\n    hi = (hi + 1) | 0\n  }\n  out[0] = hi\n  out[1] = lo\n}\n\n/**\n * @since 3.0.6\n */\nexport const YieldWrapTypeId: unique symbol = Symbol.for(\"effect/Utils/YieldWrap\")\n\n/**\n * @since 3.0.6\n */\nexport class YieldWrap<T> {\n  /**\n   * @since 3.0.6\n   */\n  readonly #value: T\n  constructor(value: T) {\n    this.#value = value\n  }\n  /**\n   * @since 3.0.6\n   */\n  [YieldWrapTypeId](): T {\n    return this.#value\n  }\n}\n\n/**\n * @since 3.0.6\n */\nexport function yieldWrapGet<T>(self: YieldWrap<T>): T {\n  if (typeof self === \"object\" && self !== null && YieldWrapTypeId in self) {\n    return self[YieldWrapTypeId]()\n  }\n  throw new Error(getBugErrorMessage(\"yieldWrapGet\"))\n}\n\n/**\n * Note: this is an experimental feature made available to allow custom matchers in tests, not to be directly used yet in user code\n *\n * @since 3.1.1\n * @status experimental\n * @category modifiers\n */\nexport const structuralRegionState = globalValue(\n  \"effect/Utils/isStructuralRegion\",\n  (): { enabled: boolean; tester: ((a: unknown, b: unknown) => boolean) | undefined } => ({\n    enabled: false,\n    tester: undefined\n  })\n)\n\n/**\n * Note: this is an experimental feature made available to allow custom matchers in tests, not to be directly used yet in user code\n *\n * @since 3.1.1\n * @status experimental\n * @category modifiers\n */\nexport const structuralRegion = <A>(body: () => A, tester?: (a: unknown, b: unknown) => boolean): A => {\n  const current = structuralRegionState.enabled\n  const currentTester = structuralRegionState.tester\n  structuralRegionState.enabled = true\n  if (tester) {\n    structuralRegionState.tester = tester\n  }\n  try {\n    return body()\n  } finally {\n    structuralRegionState.enabled = current\n    structuralRegionState.tester = currentTester\n  }\n}\n\nconst standard = {\n  effect_internal_function: <A>(body: () => A) => {\n    return body()\n  }\n}\n\nconst forced = {\n  effect_internal_function: <A>(body: () => A) => {\n    try {\n      return body()\n    } finally {\n      //\n    }\n  }\n}\n\nconst isNotOptimizedAway =\n  standard.effect_internal_function(() => new Error().stack)?.includes(\"effect_internal_function\") === true\n\n/**\n * @since 3.2.2\n * @status experimental\n * @category tracing\n */\nexport const internalCall = isNotOptimizedAway ? standard.effect_internal_function : forced.effect_internal_function\n\nconst genConstructor = (function*() {}).constructor\n\n/**\n * @since 3.11.0\n */\nexport const isGeneratorFunction = (u: unknown): u is (...args: Array<any>) => Generator<any, any, any> =>\n  isObject(u) && u.constructor === genConstructor\n"
  },
  {
    "path": "packages/effect/src/index.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nexport {\n  /**\n   * @since 2.0.0\n   */\n  absurd,\n  /**\n   * @since 2.0.0\n   */\n  flow,\n  /**\n   * @since 2.0.0\n   */\n  hole,\n  /**\n   * @since 2.0.0\n   */\n  identity,\n  /**\n   * @since 2.0.0\n   */\n  pipe,\n  /**\n   * @since 2.0.0\n   */\n  unsafeCoerce\n} from \"./Function.js\"\n\n/**\n * @since 3.10.0\n */\nexport * as Arbitrary from \"./Arbitrary.js\"\n\n/**\n * This module provides utility functions for working with arrays in TypeScript.\n *\n * @since 2.0.0\n */\nexport * as Array from \"./Array.js\"\n\n/**\n * This module provides utility functions and type class instances for working with the `BigDecimal` type in TypeScript.\n * It includes functions for basic arithmetic operations, as well as type class instances for `Equivalence` and `Order`.\n *\n * A `BigDecimal` allows storing any real number to arbitrary precision; which avoids common floating point errors\n * (such as 0.1 + 0.2 ≠ 0.3) at the cost of complexity.\n *\n * Internally, `BigDecimal` uses a `BigInt` object, paired with a 64-bit integer which determines the position of the\n * decimal point. Therefore, the precision *is not* actually arbitrary, but limited to 2<sup>63</sup> decimal places.\n *\n * It is not recommended to convert a floating point number to a decimal directly, as the floating point representation\n * may be unexpected.\n *\n * @module BigDecimal\n * @since 2.0.0\n * @see {@link module:BigInt} for more similar operations on `bigint` types\n * @see {@link module:Number} for more similar operations on `number` types\n */\nexport * as BigDecimal from \"./BigDecimal.js\"\n\n/**\n * This module provides utility functions and type class instances for working with the `bigint` type in TypeScript.\n * It includes functions for basic arithmetic operations, as well as type class instances for\n * `Equivalence` and `Order`.\n *\n * @module BigInt\n * @since 2.0.0\n * @see {@link module:BigDecimal} for more similar operations on `BigDecimal` types\n * @see {@link module:Number} for more similar operations on `number` types\n */\nexport * as BigInt from \"./BigInt.js\"\n\n/**\n * This module provides utility functions and type class instances for working with the `boolean` type in TypeScript.\n * It includes functions for basic boolean operations, as well as type class instances for\n * `Equivalence` and `Order`.\n *\n * @since 2.0.0\n */\nexport * as Boolean from \"./Boolean.js\"\n\n/**\n * This module provides types and utility functions to create and work with branded types,\n * which are TypeScript types with an added type tag to prevent accidental usage of a value in the wrong context.\n *\n * The `refined` and `nominal` functions are both used to create branded types in TypeScript.\n * The main difference between them is that `refined` allows for validation of the data, while `nominal` does not.\n *\n * The `nominal` function is used to create a new branded type that has the same underlying type as the input, but with a different name.\n * This is useful when you want to distinguish between two values of the same type that have different meanings.\n * The `nominal` function does not perform any validation of the input data.\n *\n * On the other hand, the `refined` function is used to create a new branded type that has the same underlying type as the input,\n * but with a different name, and it also allows for validation of the input data.\n * The `refined` function takes a predicate that is used to validate the input data.\n * If the input data fails the validation, a `BrandErrors` is returned, which provides information about the specific validation failure.\n *\n * @since 2.0.0\n */\nexport * as Brand from \"./Brand.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Cache from \"./Cache.js\"\n\n/**\n * The `Effect<A, E, R>` type is polymorphic in values of type `E` and we can\n * work with any error type that we want. However, there is a lot of information\n * that is not inside an arbitrary `E` value. So as a result, an `Effect` needs\n * somewhere to store things like unexpected errors or defects, stack and\n * execution traces, causes of fiber interruptions, and so forth.\n *\n * Effect-TS is very strict about preserving the full information related to a\n * failure. It captures all type of errors into the `Cause` data type. `Effect`\n * uses the `Cause<E>` data type to store the full story of failure. So its\n * error model is lossless. It doesn't throw information related to the failure\n * result. So we can figure out exactly what happened during the operation of\n * our effects.\n *\n * It is important to note that `Cause` is an underlying data type representing\n * errors occuring within an `Effect` workflow. Thus, we don't usually deal with\n * `Cause`s directly. Even though it is not a data type that we deal with very\n * often, the `Cause` of a failing `Effect` workflow can be accessed at any\n * time, which gives us total access to all parallel and sequential errors in\n * occurring within our codebase.\n *\n * @since 2.0.0\n */\nexport * as Cause from \"./Cause.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Channel from \"./Channel.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ChildExecutorDecision from \"./ChildExecutorDecision.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Chunk from \"./Chunk.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Clock from \"./Clock.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Config from \"./Config.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ConfigError from \"./ConfigError.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ConfigProvider from \"./ConfigProvider.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ConfigProviderPathPatch from \"./ConfigProviderPathPatch.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Console from \"./Console.js\"\n\n/**\n * This module provides a data structure called `Context` that can be used for dependency injection in effectful\n * programs. It is essentially a table mapping `Tag`s to their implementations (called `Service`s), and can be used to\n * manage dependencies in a type-safe way. The `Context` data structure is essentially a way of providing access to a set\n * of related services that can be passed around as a single unit. This module provides functions to create, modify, and\n * query the contents of a `Context`, as well as a number of utility types for working with tags and services.\n *\n * @since 2.0.0\n */\nexport * as Context from \"./Context.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Cron from \"./Cron.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Data from \"./Data.js\"\n\n/**\n * @since 3.6.0\n */\nexport * as DateTime from \"./DateTime.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as DefaultServices from \"./DefaultServices.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Deferred from \"./Deferred.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Differ from \"./Differ.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Duration from \"./Duration.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Effect from \"./Effect.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Effectable from \"./Effectable.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Either from \"./Either.js\"\n\n/**\n * This module provides encoding & decoding functionality for:\n *\n * - base64 (RFC4648)\n * - base64 (URL)\n * - hex\n *\n * @since 2.0.0\n */\nexport * as Encoding from \"./Encoding.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Equal from \"./Equal.js\"\n\n/**\n * This module provides an implementation of the `Equivalence` type class, which defines a binary relation\n * that is reflexive, symmetric, and transitive. In other words, it defines a notion of equivalence between values of a certain type.\n * These properties are also known in mathematics as an \"equivalence relation\".\n *\n * @since 2.0.0\n */\nexport * as Equivalence from \"./Equivalence.js\"\n\n/**\n * @since 3.16.0\n * @experimental\n */\nexport * as ExecutionPlan from \"./ExecutionPlan.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ExecutionStrategy from \"./ExecutionStrategy.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Exit from \"./Exit.js\"\n\n/**\n * @since 3.10.0\n */\nexport * as FastCheck from \"./FastCheck.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Fiber from \"./Fiber.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as FiberHandle from \"./FiberHandle.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as FiberId from \"./FiberId.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as FiberMap from \"./FiberMap.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as FiberRef from \"./FiberRef.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as FiberRefs from \"./FiberRefs.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as FiberRefsPatch from \"./FiberRefsPatch.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as FiberSet from \"./FiberSet.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as FiberStatus from \"./FiberStatus.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Function from \"./Function.js\"\n\n/**\n * The `GlobalValue` module ensures that a single instance of a value is created globally,\n * even when modules are imported multiple times (e.g., due to mixing CommonJS and ESM builds)\n * or during hot-reloading in development environments like Next.js or Remix.\n *\n * It achieves this by using a versioned global store, identified by a unique `Symbol` tied to\n * the current version of the `effect` library. The store holds values that are keyed by an identifier,\n * allowing the reuse of previously computed instances across imports or reloads.\n *\n * This pattern is particularly useful in scenarios where frequent reloading can cause services or\n * single-instance objects to be recreated unnecessarily, such as in development environments with hot-reloading.\n *\n * @since 2.0.0\n */\nexport * as GlobalValue from \"./GlobalValue.js\"\n\n/**\n * @experimental\n * @since 3.18.0\n */\nexport * as Graph from \"./Graph.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as GroupBy from \"./GroupBy.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as HKT from \"./HKT.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Hash from \"./Hash.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as HashMap from \"./HashMap.js\"\n\n/**\n * @since 3.19.0\n * @experimental\n */\nexport * as HashRing from \"./HashRing.js\"\n\n/**\n * # HashSet\n *\n * An immutable `HashSet` provides a collection of unique values with efficient\n * lookup, insertion and removal. Once created, a `HashSet` cannot be modified;\n * any operation that would alter the set instead returns a new `HashSet` with\n * the changes. This immutability offers benefits like predictable state\n * management and easier reasoning about your code.\n *\n * ## What Problem Does It Solve?\n *\n * `HashSet` solves the problem of maintaining an unsorted collection where each\n * value appears exactly once, with fast operations for checking membership and\n * adding/removing values.\n *\n * ## When to Use\n *\n * Use `HashSet` when you need:\n *\n * - A collection with no duplicate values\n * - Efficient membership testing (**`O(1)`** average complexity)\n * - Set operations like union, intersection, and difference\n * - An immutable data structure that preserves functional programming patterns\n *\n * ## Advanced Features\n *\n * HashSet provides operations for:\n *\n * - Transforming sets with map and flatMap\n * - Filtering elements with filter\n * - Combining sets with union, intersection and difference\n * - Performance optimizations via mutable operations in controlled contexts\n *\n * ## Performance Characteristics\n *\n * - **Lookup** operations ({@link module:HashSet.has}): **`O(1)`** average time\n *   complexity\n * - **Insertion** operations ({@link module:HashSet.add}): **`O(1)`** average time\n *   complexity\n * - **Removal** operations ({@link module:HashSet.remove}): **`O(1)`** average\n *   time complexity\n * - **Set** operations ({@link module:HashSet.union},\n *   {@link module:HashSet.intersection}): **`O(n)`** where n is the size of the\n *   smaller set\n * - **Iteration**: **`O(n)`** where n is the size of the set\n *\n * The HashSet data structure implements the following traits:\n *\n * - {@link Iterable}: allows iterating over the values in the set\n * - {@link Equal}: allows comparing two sets for value-based equality\n * - {@link Pipeable}: allows chaining operations with the pipe operator\n * - {@link Inspectable}: allows inspecting the contents of the set\n *\n * ## Operations Reference\n *\n * | Category     | Operation                           | Description                                 | Complexity |\n * | ------------ | ----------------------------------- | ------------------------------------------- | ---------- |\n * | constructors | {@link module:HashSet.empty}        | Creates an empty HashSet                    | O(1)       |\n * | constructors | {@link module:HashSet.fromIterable} | Creates a HashSet from an iterable          | O(n)       |\n * | constructors | {@link module:HashSet.make}         | Creates a HashSet from multiple values      | O(n)       |\n * |              |                                     |                                             |            |\n * | elements     | {@link module:HashSet.has}          | Checks if a value exists in the set         | O(1) avg   |\n * | elements     | {@link module:HashSet.some}         | Checks if any element satisfies a predicate | O(n)       |\n * | elements     | {@link module:HashSet.every}        | Checks if all elements satisfy a predicate  | O(n)       |\n * | elements     | {@link module:HashSet.isSubset}     | Checks if a set is a subset of another      | O(n)       |\n * |              |                                     |                                             |            |\n * | getters      | {@link module:HashSet.values}       | Gets an iterator of all values              | O(1)       |\n * | getters      | {@link module:HashSet.toValues}     | Gets an array of all values                 | O(n)       |\n * | getters      | {@link module:HashSet.size}         | Gets the number of elements                 | O(1)       |\n * |              |                                     |                                             |            |\n * | mutations    | {@link module:HashSet.add}          | Adds a value to the set                     | O(1) avg   |\n * | mutations    | {@link module:HashSet.remove}       | Removes a value from the set                | O(1) avg   |\n * | mutations    | {@link module:HashSet.toggle}       | Toggles a value's presence                  | O(1) avg   |\n * |              |                                     |                                             |            |\n * | operations   | {@link module:HashSet.difference}   | Computes set difference (A - B)             | O(n)       |\n * | operations   | {@link module:HashSet.intersection} | Computes set intersection (A ∩ B)           | O(n)       |\n * | operations   | {@link module:HashSet.union}        | Computes set union (A ∪ B)                  | O(n)       |\n * |              |                                     |                                             |            |\n * | mapping      | {@link module:HashSet.map}          | Transforms each element                     | O(n)       |\n * |              |                                     |                                             |            |\n * | sequencing   | {@link module:HashSet.flatMap}      | Transforms and flattens elements            | O(n)       |\n * |              |                                     |                                             |            |\n * | traversing   | {@link module:HashSet.forEach}      | Applies a function to each element          | O(n)       |\n * |              |                                     |                                             |            |\n * | folding      | {@link module:HashSet.reduce}       | Reduces the set to a single value           | O(n)       |\n * |              |                                     |                                             |            |\n * | filtering    | {@link module:HashSet.filter}       | Keeps elements that satisfy a predicate     | O(n)       |\n * |              |                                     |                                             |            |\n * | partitioning | {@link module:HashSet.partition}    | Splits into two sets by a predicate         | O(n)       |\n *\n * ## Notes\n *\n * ### Composability with the Effect Ecosystem:\n *\n * This `HashSet` is designed to work seamlessly within the Effect ecosystem. It\n * implements the {@link Iterable}, {@link Equal}, {@link Pipeable}, and\n * {@link Inspectable} traits from Effect. This ensures compatibility with other\n * Effect data structures and functionalities. For example, you can easily use\n * Effect's `pipe` method to chain operations on the `HashSet`.\n *\n * **Equality of Elements with Effect's {@link Equal `Equal`} Trait:**\n *\n * This `HashSet` relies on Effect's {@link Equal} trait to determine the\n * uniqueness of elements within the set. The way equality is checked depends on\n * the type of the elements:\n *\n * - **Primitive Values:** For primitive JavaScript values like strings, numbers,\n *   booleans, `null`, and `undefined`, equality is determined by their value\n *   (similar to the `===` operator).\n * - **Objects and Custom Types:** For objects and other custom types, equality is\n *   determined by whether those types implement the {@link Equal} interface\n *   themselves. If an element type implements `Equal`, the `HashSet` will\n *   delegate to that implementation to perform the equality check. This allows\n *   you to define custom logic for determining when two instances of your\n *   objects should be considered equal based on their properties, rather than\n *   just their object identity.\n *\n * ```ts\n * import { Equal, Hash, HashSet } from \"effect\"\n *\n * class Person implements Equal.Equal {\n *   constructor(\n *     readonly id: number, // Unique identifier\n *     readonly name: string,\n *     readonly age: number\n *   ) {}\n *\n *   // Define equality based on id, name, and age\n *   [Equal.symbol](that: Equal.Equal): boolean {\n *     if (that instanceof Person) {\n *       return (\n *         Equal.equals(this.id, that.id) &&\n *         Equal.equals(this.name, that.name) &&\n *         Equal.equals(this.age, that.age)\n *       )\n *     }\n *     return false\n *   }\n *\n *   // Generate a hash code based on the unique id\n *   [Hash.symbol](): number {\n *     return Hash.hash(this.id)\n *   }\n * }\n *\n * // Creating a HashSet with objects that implement the Equal interface\n * const set = HashSet.empty().pipe(\n *   HashSet.add(new Person(1, \"Alice\", 30)),\n *   HashSet.add(new Person(1, \"Alice\", 30))\n * )\n *\n * // HashSet recognizes them as equal, so only one element is stored\n * console.log(HashSet.size(set))\n * // Output: 1\n * ```\n *\n * **Simplifying Equality and Hashing with `Data` and `Schema`:**\n *\n * Effect's {@link Data} and {@link Schema `Schema.Data`} modules offer powerful\n * ways to automatically handle the implementation of both the {@link Equal} and\n * {@link Hash} traits for your custom data structures.\n *\n * - **`Data` Module:** By using constructors like `Data.struct`, `Data.tuple`,\n *   `Data.array`, or `Data.case` to define your data types, Effect\n *   automatically generates the necessary implementations for value-based\n *   equality and consistent hashing. This significantly reduces boilerplate and\n *   ensures correctness.\n *\n * ```ts\n * import { HashSet, Data, Equal } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * // Data.* implements the `Equal` traits for us\n * const person1 = Data.struct({ id: 1, name: \"Alice\", age: 30 })\n * const person2 = Data.struct({ id: 1, name: \"Alice\", age: 30 })\n *\n * assert(Equal.equals(person1, person2))\n *\n * const set = HashSet.empty().pipe(\n *   HashSet.add(person1),\n *   HashSet.add(person2)\n * )\n *\n * // HashSet recognizes them as equal, so only one element is stored\n * console.log(HashSet.size(set)) // Output: 1\n * ```\n *\n * - **`Schema` Module:** When defining data schemas using the {@link Schema}\n *   module, you can use `Schema.Data` to automatically include the `Equal` and\n *   `Hash` traits in the decoded objects. This is particularly important when\n *   working with `HashSet`. **For decoded objects to be correctly recognized as\n *   equal within a `HashSet`, ensure that the schema for those objects is\n *   defined using `Schema.Data`.**\n *\n * ```ts\n * import { Equal, HashSet, Schema } from \"effect\"\n * import assert from \"node:assert/strict\"\n *\n * // Schema.Data implements the `Equal` traits for us\n * const PersonSchema = Schema.Data(\n *   Schema.Struct({\n *     id: Schema.Number,\n *     name: Schema.String,\n *     age: Schema.Number\n *   })\n * )\n *\n * const Person = Schema.decode(PersonSchema)\n *\n * const person1 = Person({ id: 1, name: \"Alice\", age: 30 })\n * const person2 = Person({ id: 1, name: \"Alice\", age: 30 })\n *\n * assert(Equal.equals(person1, person2)) // Output: true\n *\n * const set = HashSet.empty().pipe(\n *   HashSet.add(person1),\n *   HashSet.add(person2)\n * )\n *\n * // HashSet thanks to Schema.Data implementation of the `Equal` trait, recognizes the two Person as equal, so only one element is stored\n * console.log(HashSet.size(set)) // Output: 1\n * ```\n *\n * ### Interoperability with the JavaScript Runtime:\n *\n * To interoperate with the regular JavaScript runtime, Effect's `HashSet`\n * provides methods to access its elements in formats readily usable by\n * JavaScript APIs: {@link values `HashSet.values`},\n * {@link toValues `HashSet.toValues`}\n *\n * ```ts\n * import { HashSet } from \"effect\"\n *\n * const hashSet: HashSet.HashSet<number> = HashSet.make(1, 2, 3)\n *\n * // Using HashSet.values to convert HashSet.HashSet<A> to IterableIterator<A>\n * const iterable: IterableIterator<number> = HashSet.values(hashSet)\n *\n * console.log(...iterable) // Logs:  1 2 3\n *\n * // Using HashSet.toValues to convert HashSet.HashSet<A> to Array<A>\n * const array: Array<number> = HashSet.toValues(hashSet)\n *\n * console.log(array) // Logs: [ 1, 2, 3 ]\n * ```\n *\n * Be mindful of performance implications (both time and space complexity) when\n * frequently converting between Effect's immutable HashSet and mutable\n * JavaScript data structures, especially for large collections.\n *\n * @module HashSet\n * @since 2.0.0\n */\nexport * as HashSet from \"./HashSet.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Inspectable from \"./Inspectable.js\"\n\n/**\n * This module provides utility functions for working with Iterables in TypeScript.\n *\n * @since 2.0.0\n */\nexport * as Iterable from \"./Iterable.js\"\n\n/**\n * @since 3.10.0\n */\nexport * as JSONSchema from \"./JSONSchema.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as KeyedPool from \"./KeyedPool.js\"\n\n/**\n * A `Layer<ROut, E, RIn>` describes how to build one or more services in your\n * application. Services can be injected into effects via\n * `Effect.provideService`. Effects can require services via `Effect.service`.\n *\n * Layer can be thought of as recipes for producing bundles of services, given\n * their dependencies (other services).\n *\n * Construction of services can be effectful and utilize resources that must be\n * acquired and safely released when the services are done being utilized.\n *\n * By default layers are shared, meaning that if the same layer is used twice\n * the layer will only be allocated a single time.\n *\n * Because of their excellent composition properties, layers are the idiomatic\n * way in Effect-TS to create services that depend on other services.\n *\n * @since 2.0.0\n */\nexport * as Layer from \"./Layer.js\"\n\n/**\n * @since 3.14.0\n * @experimental\n */\nexport * as LayerMap from \"./LayerMap.js\"\n\n/**\n * A data type for immutable linked lists representing ordered collections of elements of type `A`.\n *\n * This data type is optimal for last-in-first-out (LIFO), stack-like access patterns. If you need another access pattern, for example, random access or FIFO, consider using a collection more suited to this than `List`.\n *\n * **Performance**\n *\n * - Time: `List` has `O(1)` prepend and head/tail access. Most other operations are `O(n)` on the number of elements in the list. This includes the index-based lookup of elements, `length`, `append` and `reverse`.\n * - Space: `List` implements structural sharing of the tail list. This means that many operations are either zero- or constant-memory cost.\n *\n * @since 2.0.0\n */\nexport * as List from \"./List.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as LogLevel from \"./LogLevel.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as LogSpan from \"./LogSpan.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Logger from \"./Logger.js\"\n\n/**\n * @since 3.8.0\n * @experimental\n */\nexport * as Mailbox from \"./Mailbox.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ManagedRuntime from \"./ManagedRuntime.js\"\n\n/**\n * The `effect/match` module provides a type-safe pattern matching system for\n * TypeScript. Inspired by functional programming, it simplifies conditional\n * logic by replacing verbose if/else or switch statements with a structured and\n * expressive API.\n *\n * This module supports matching against types, values, and discriminated unions\n * while enforcing exhaustiveness checking to ensure all cases are handled.\n *\n * Although pattern matching is not yet a native JavaScript feature,\n * `effect/match` offers a reliable implementation that is available today.\n *\n * **How Pattern Matching Works**\n *\n * Pattern matching follows a structured process:\n *\n * - **Creating a matcher**: Define a `Matcher` that operates on either a\n *   specific `Match.type` or `Match.value`.\n *\n * - **Defining patterns**: Use combinators such as `Match.when`, `Match.not`,\n *   and `Match.tag` to specify matching conditions.\n *\n * - **Completing the match**: Apply a finalizer such as `Match.exhaustive`,\n *   `Match.orElse`, or `Match.option` to determine how unmatched cases should\n *   be handled.\n *\n * @since 1.0.0\n */\nexport * as Match from \"./Match.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MergeDecision from \"./MergeDecision.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MergeState from \"./MergeState.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MergeStrategy from \"./MergeStrategy.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Metric from \"./Metric.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MetricBoundaries from \"./MetricBoundaries.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MetricHook from \"./MetricHook.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MetricKey from \"./MetricKey.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MetricKeyType from \"./MetricKeyType.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MetricLabel from \"./MetricLabel.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MetricPair from \"./MetricPair.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MetricPolling from \"./MetricPolling.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MetricRegistry from \"./MetricRegistry.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MetricState from \"./MetricState.js\"\n\n/**\n * A lightweight alternative to the `Effect` data type, with a subset of the functionality.\n *\n * @since 3.4.0\n * @experimental\n */\nexport * as Micro from \"./Micro.js\"\n\n/**\n * @since 2.0.0\n *\n * Enables low level framework authors to run on their own isolated effect version\n */\nexport * as ModuleVersion from \"./ModuleVersion.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MutableHashMap from \"./MutableHashMap.js\"\n\n/**\n * # MutableHashSet\n *\n * A mutable `MutableHashSet` provides a collection of unique values with\n * efficient lookup, insertion and removal. Unlike its immutable sibling\n * {@link module:HashSet}, a `MutableHashSet` can be modified in-place;\n * operations like add, remove, and clear directly modify the original set\n * rather than creating a new one. This mutability offers benefits like improved\n * performance in scenarios where you need to build or modify a set\n * incrementally.\n *\n * ## What Problem Does It Solve?\n *\n * `MutableHashSet` solves the problem of maintaining an unsorted collection\n * where each value appears exactly once, with fast operations for checking\n * membership and adding/removing values, in contexts where mutability is\n * preferred for performance or implementation simplicity.\n *\n * ## When to Use\n *\n * Use `MutableHashSet` when you need:\n *\n * - A collection with no duplicate values\n * - Efficient membership testing (**`O(1)`** average complexity)\n * - In-place modifications for better performance\n * - A set that will be built or modified incrementally\n * - Local mutability in otherwise immutable code\n *\n * ## Advanced Features\n *\n * MutableHashSet provides operations for:\n *\n * - Adding and removing elements with direct mutation\n * - Checking for element existence\n * - Clearing all elements at once\n * - Converting to/from other collection types\n *\n * ## Performance Characteristics\n *\n * - **Lookup** operations ({@link module:MutableHashSet.has}): **`O(1)`** average\n *   time complexity\n * - **Insertion** operations ({@link module:MutableHashSet.add}): **`O(1)`**\n *   average time complexity\n * - **Removal** operations ({@link module:MutableHashSet.remove}): **`O(1)`**\n *   average time complexity\n * - **Iteration**: **`O(n)`** where n is the size of the set\n *\n * The MutableHashSet data structure implements the following traits:\n *\n * - {@link Iterable}: allows iterating over the values in the set\n * - {@link Pipeable}: allows chaining operations with the pipe operator\n * - {@link Inspectable}: allows inspecting the contents of the set\n *\n * ## Operations Reference\n *\n * | Category     | Operation                                  | Description                         | Complexity |\n * | ------------ | ------------------------------------------ | ----------------------------------- | ---------- |\n * | constructors | {@link module:MutableHashSet.empty}        | Creates an empty MutableHashSet     | O(1)       |\n * | constructors | {@link module:MutableHashSet.fromIterable} | Creates a set from an iterable      | O(n)       |\n * | constructors | {@link module:MutableHashSet.make}         | Creates a set from multiple values  | O(n)       |\n * |              |                                            |                                     |            |\n * | elements     | {@link module:MutableHashSet.has}          | Checks if a value exists in the set | O(1) avg   |\n * | elements     | {@link module:MutableHashSet.add}          | Adds a value to the set             | O(1) avg   |\n * | elements     | {@link module:MutableHashSet.remove}       | Removes a value from the set        | O(1) avg   |\n * | elements     | {@link module:MutableHashSet.size}         | Gets the number of elements         | O(1)       |\n * | elements     | {@link module:MutableHashSet.clear}        | Removes all values from the set     | O(1)       |\n *\n * ## Notes\n *\n * ### Mutability Considerations:\n *\n * Unlike most data structures in the Effect ecosystem, `MutableHashSet` is\n * mutable. This means that operations like `add`, `remove`, and `clear` modify\n * the original set rather than creating a new one. This can lead to more\n * efficient code in some scenarios, but requires careful handling to avoid\n * unexpected side effects.\n *\n * ### When to Choose `MutableHashSet` vs {@link module:HashSet}:\n *\n * - Use `MutableHashSet` when you need to build or modify a set incrementally and\n *   performance is a priority\n * - Use `HashSet` when you want immutability guarantees and functional\n *   programming patterns\n * - Consider using {@link module:HashSet}'s bounded mutation context (via\n *   {@link module:HashSet.beginMutation}, {@link module:HashSet.endMutation}, and\n *   {@link module:HashSet.mutate} methods) when you need temporary mutability\n *   within an otherwise immutable context - this approach might be sufficient\n *   for many use cases without requiring a separate `MutableHashSet`\n * - `MutableHashSet` is often useful for local operations where the mutability is\n *   contained and doesn't leak into the broader application\n *\n * @module MutableHashSet\n * @since 2.0.0\n */\nexport * as MutableHashSet from \"./MutableHashSet.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MutableList from \"./MutableList.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MutableQueue from \"./MutableQueue.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as MutableRef from \"./MutableRef.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as NonEmptyIterable from \"./NonEmptyIterable.js\"\n\n/**\n * # Number\n *\n * This module provides utility functions and type class instances for working\n * with the `number` type in TypeScript. It includes functions for basic\n * arithmetic operations, as well as type class instances for `Equivalence` and\n * `Order`.\n *\n * ## Operations Reference\n *\n * | Category     | Operation                                  | Description                                             | Domain                         | Co-domain             |\n * | ------------ | ------------------------------------------ | ------------------------------------------------------- | ------------------------------ | --------------------- |\n * | constructors | {@link module:Number.parse}                | Safely parses a string to a number                      | `string`                       | `Option<number>`      |\n * |              |                                            |                                                         |                                |                       |\n * | math         | {@link module:Number.sum}                  | Adds two numbers                                        | `number`, `number`             | `number`              |\n * | math         | {@link module:Number.sumAll}               | Sums all numbers in a collection                        | `Iterable<number>`             | `number`              |\n * | math         | {@link module:Number.subtract}             | Subtracts one number from another                       | `number`, `number`             | `number`              |\n * | math         | {@link module:Number.multiply}             | Multiplies two numbers                                  | `number`, `number`             | `number`              |\n * | math         | {@link module:Number.multiplyAll}          | Multiplies all numbers in a collection                  | `Iterable<number>`             | `number`              |\n * | math         | {@link module:Number.divide}               | Safely divides handling division by zero                | `number`, `number`             | `Option<number>`      |\n * | math         | {@link module:Number.unsafeDivide}         | Divides but misbehaves for division by zero             | `number`, `number`             | `number`              |\n * | math         | {@link module:Number.remainder}            | Calculates remainder of division                        | `number`, `number`             | `number`              |\n * | math         | {@link module:Number.increment}            | Adds 1 to a number                                      | `number`                       | `number`              |\n * | math         | {@link module:Number.decrement}            | Subtracts 1 from a number                               | `number`                       | `number`              |\n * | math         | {@link module:Number.sign}                 | Determines the sign of a number                         | `number`                       | `Ordering`            |\n * | math         | {@link module:Number.nextPow2}             | Finds the next power of 2                               | `number`                       | `number`              |\n * | math         | {@link module:Number.round}                | Rounds a number with specified precision                | `number`, `number`             | `number`              |\n * |              |                                            |                                                         |                                |                       |\n * | predicates   | {@link module:Number.between}              | Checks if a number is in a range                        | `number`, `{minimum, maximum}` | `boolean`             |\n * | predicates   | {@link module:Number.lessThan}             | Checks if one number is less than another               | `number`, `number`             | `boolean`             |\n * | predicates   | {@link module:Number.lessThanOrEqualTo}    | Checks if one number is less than or equal              | `number`, `number`             | `boolean`             |\n * | predicates   | {@link module:Number.greaterThan}          | Checks if one number is greater than another            | `number`, `number`             | `boolean`             |\n * | predicates   | {@link module:Number.greaterThanOrEqualTo} | Checks if one number is greater or equal                | `number`, `number`             | `boolean`             |\n * |              |                                            |                                                         |                                |                       |\n * | guards       | {@link module:Number.isNumber}             | Type guard for JavaScript numbers                       | `unknown`                      | `boolean`             |\n * |              |                                            |                                                         |                                |                       |\n * | comparison   | {@link module:Number.min}                  | Returns the minimum of two numbers                      | `number`, `number`             | `number`              |\n * | comparison   | {@link module:Number.max}                  | Returns the maximum of two numbers                      | `number`, `number`             | `number`              |\n * | comparison   | {@link module:Number.clamp}                | Restricts a number to a range                           | `number`, `{minimum, maximum}` | `number`              |\n * |              |                                            |                                                         |                                |                       |\n * | instances    | {@link module:Number.Equivalence}          | Equivalence instance for numbers                        |                                | `Equivalence<number>` |\n * | instances    | {@link module:Number.Order}                | Order instance for numbers                              |                                | `Order<number>`       |\n * |              |                                            |                                                         |                                |                       |\n * | errors       | {@link module:Number.DivisionByZeroError}  | Error thrown by unsafeDivide                            |                                |                       |\n *\n * ## Composition Patterns and Type Safety\n *\n * When building function pipelines, understanding how types flow through\n * operations is critical:\n *\n * ### Composing with type-preserving operations\n *\n * Most operations in this module are type-preserving (`number → number`),\n * making them easily composable in pipelines:\n *\n * ```ts\n * import { pipe } from \"effect\"\n * import * as Number from \"effect/Number\"\n *\n * const result = pipe(\n *   10,\n *   Number.increment, // number → number\n *   Number.multiply(2), // number → number\n *   Number.round(1) // number → number\n * ) // Result: number (21)\n * ```\n *\n * ### Working with Option results\n *\n * Operations that might fail (like division by zero) return Option types and\n * require Option combinators:\n *\n * ```ts\n * import { pipe, Option } from \"effect\"\n * import * as Number from \"effect/Number\"\n *\n * const result = pipe(\n *   10,\n *   Number.divide(0), // number → Option<number>\n *   Option.getOrElse(() => 0) // Option<number> → number\n * ) // Result: number (0)\n * ```\n *\n * ### Composition best practices\n *\n * - Chain type-preserving operations for maximum composability\n * - Use Option combinators when working with potentially failing operations\n * - Consider using Effect for operations that might fail with specific errors\n * - Remember that all operations maintain JavaScript's floating-point precision\n *   limitations\n *\n * @module Number\n * @since 2.0.0\n * @see {@link module:BigInt} for more similar operations on `bigint` types\n * @see {@link module:BigDecimal} for more similar operations on `BigDecimal` types\n */\nexport * as Number from \"./Number.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Option from \"./Option.js\"\n\n/**\n * This module provides an implementation of the `Order` type class which is used to define a total ordering on some type `A`.\n * An order is defined by a relation `<=`, which obeys the following laws:\n *\n * - either `x <= y` or `y <= x` (totality)\n * - if `x <= y` and `y <= x`, then `x == y` (antisymmetry)\n * - if `x <= y` and `y <= z`, then `x <= z` (transitivity)\n *\n * The truth table for compare is defined as follows:\n *\n * | `x <= y` | `x >= y` | Ordering |                       |\n * | -------- | -------- | -------- | --------------------- |\n * | `true`   | `true`   | `0`      | corresponds to x == y |\n * | `true`   | `false`  | `< 0`    | corresponds to x < y  |\n * | `false`  | `true`   | `> 0`    | corresponds to x > y  |\n *\n * @since 2.0.0\n */\nexport * as Order from \"./Order.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Ordering from \"./Ordering.js\"\n\n/**\n * @since 3.10.0\n */\nexport * as ParseResult from \"./ParseResult.js\"\n\n/**\n * @since 3.19.4\n * @experimental\n */\nexport * as PartitionedSemaphore from \"./PartitionedSemaphore.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Pipeable from \"./Pipeable.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Pool from \"./Pool.js\"\n\n/**\n * This module provides a collection of functions for working with predicates and refinements.\n *\n * A `Predicate<A>` is a function that takes a value of type `A` and returns a boolean.\n * It is used to check if a value satisfies a certain condition.\n *\n * A `Refinement<A, B>` is a special type of predicate that not only checks a condition\n * but also provides a type guard, allowing TypeScript to narrow the type of the input\n * value from `A` to a more specific type `B` within a conditional block.\n *\n * The module includes:\n * - Basic predicates and refinements for common types (e.g., `isString`, `isNumber`).\n * - Combinators to create new predicates from existing ones (e.g., `and`, `or`, `not`).\n * - Advanced combinators for working with data structures (e.g., `tuple`, `struct`).\n * - Type-level utilities for inspecting predicate and refinement types.\n *\n * @since 2.0.0\n */\nexport * as Predicate from \"./Predicate.js\"\n\n/**\n * @since 3.10.0\n */\nexport * as Pretty from \"./Pretty.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as PrimaryKey from \"./PrimaryKey.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as PubSub from \"./PubSub.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Queue from \"./Queue.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Random from \"./Random.js\"\n\n/**\n * Limits the number of calls to a resource to a maximum amount in some interval.\n *\n * @since 2.0.0\n */\nexport * as RateLimiter from \"./RateLimiter.js\"\n\n/**\n * @since 3.5.0\n */\nexport * as RcMap from \"./RcMap.js\"\n\n/**\n * @since 3.5.0\n */\nexport * as RcRef from \"./RcRef.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Readable from \"./Readable.js\"\n\n/**\n * This module provides utility functions for working with records in TypeScript.\n *\n * @since 2.0.0\n */\nexport * as Record from \"./Record.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as RedBlackTree from \"./RedBlackTree.js\"\n\n/**\n * The Redacted module provides functionality for handling sensitive information\n * securely within your application. By using the `Redacted` data type, you can\n * ensure that sensitive values are not accidentally exposed in logs or error\n * messages.\n *\n * @since 3.3.0\n */\nexport * as Redacted from \"./Redacted.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Ref from \"./Ref.js\"\n\n/**\n * This module provides utility functions for working with RegExp in TypeScript.\n *\n * @since 2.0.0\n */\nexport * as RegExp from \"./RegExp.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Reloadable from \"./Reloadable.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Request from \"./Request.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as RequestBlock from \"./RequestBlock.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as RequestResolver from \"./RequestResolver.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Resource from \"./Resource.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Runtime from \"./Runtime.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as RuntimeFlags from \"./RuntimeFlags.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as RuntimeFlagsPatch from \"./RuntimeFlagsPatch.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as STM from \"./STM.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Schedule from \"./Schedule.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ScheduleDecision from \"./ScheduleDecision.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ScheduleInterval from \"./ScheduleInterval.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ScheduleIntervals from \"./ScheduleIntervals.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Scheduler from \"./Scheduler.js\"\n\n/**\n * @since 3.10.0\n */\nexport * as Schema from \"./Schema.js\"\n\n/**\n * @since 3.10.0\n */\nexport * as SchemaAST from \"./SchemaAST.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Scope from \"./Scope.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ScopedCache from \"./ScopedCache.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as ScopedRef from \"./ScopedRef.js\"\n\n/**\n * @since 2.0.0\n * @deprecated\n */\nexport * as Secret from \"./Secret.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as SingleProducerAsyncInput from \"./SingleProducerAsyncInput.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Sink from \"./Sink.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as SortedMap from \"./SortedMap.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as SortedSet from \"./SortedSet.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Stream from \"./Stream.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as StreamEmit from \"./StreamEmit.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as StreamHaltStrategy from \"./StreamHaltStrategy.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Streamable from \"./Streamable.js\"\n\n/**\n * This module provides utility functions and type class instances for working with the `string` type in TypeScript.\n * It includes functions for basic string manipulation, as well as type class instances for\n * `Equivalence` and `Order`.\n *\n * @since 2.0.0\n */\nexport * as String from \"./String.js\"\n\n/**\n * This module provides utility functions for working with structs in TypeScript.\n *\n * @since 2.0.0\n */\nexport * as Struct from \"./Struct.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Subscribable from \"./Subscribable.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as SubscriptionRef from \"./SubscriptionRef.js\"\n\n/**\n * A `Supervisor<T>` is allowed to supervise the launching and termination of\n * fibers, producing some visible value of type `T` from the supervision.\n *\n * @since 2.0.0\n */\nexport * as Supervisor from \"./Supervisor.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Symbol from \"./Symbol.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as SynchronizedRef from \"./SynchronizedRef.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TArray from \"./TArray.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TDeferred from \"./TDeferred.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TMap from \"./TMap.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TPriorityQueue from \"./TPriorityQueue.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TPubSub from \"./TPubSub.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TQueue from \"./TQueue.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TRandom from \"./TRandom.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TReentrantLock from \"./TReentrantLock.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TRef from \"./TRef.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TSemaphore from \"./TSemaphore.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TSet from \"./TSet.js\"\n\n/**\n * @since 3.10.0\n */\nexport * as TSubscriptionRef from \"./TSubscriptionRef.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Take from \"./Take.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TestAnnotation from \"./TestAnnotation.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TestAnnotationMap from \"./TestAnnotationMap.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TestAnnotations from \"./TestAnnotations.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TestClock from \"./TestClock.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TestConfig from \"./TestConfig.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TestContext from \"./TestContext.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TestLive from \"./TestLive.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TestServices from \"./TestServices.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as TestSized from \"./TestSized.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Tracer from \"./Tracer.js\"\n\n/**\n * A `Trie` is used for locating specific `string` keys from within a set.\n *\n * It works similar to `HashMap`, but with keys required to be `string`.\n * This constraint unlocks some performance optimizations and new methods to get string prefixes (e.g. `keysWithPrefix`, `longestPrefixOf`).\n *\n * Prefix search is also the main feature that makes a `Trie` more suited than `HashMap` for certain usecases.\n *\n * A `Trie` is often used to store a dictionary (list of words) that can be searched\n * in a manner that allows for efficient generation of completion lists\n * (e.g. predict the rest of a word a user is typing).\n *\n * A `Trie` has O(n) lookup time where `n` is the size of the key,\n * or even less than `n` on search misses.\n *\n * @since 2.0.0\n */\nexport * as Trie from \"./Trie.js\"\n\n/**\n * This module provides utility functions for working with tuples in TypeScript.\n *\n * @since 2.0.0\n */\nexport * as Tuple from \"./Tuple.js\"\n\n/**\n * A collection of types that are commonly used types.\n *\n * @since 2.0.0\n */\nexport * as Types from \"./Types.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Unify from \"./Unify.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as UpstreamPullRequest from \"./UpstreamPullRequest.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as UpstreamPullStrategy from \"./UpstreamPullStrategy.js\"\n\n/**\n * @since 2.0.0\n */\nexport * as Utils from \"./Utils.js\"\n"
  },
  {
    "path": "packages/effect/src/internal/array.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport type { NonEmptyArray } from \"../Array.js\"\n\n/** @internal */\nexport const isNonEmptyArray = <A>(self: ReadonlyArray<A>): self is NonEmptyArray<A> => self.length > 0\n"
  },
  {
    "path": "packages/effect/src/internal/blockedRequests.ts",
    "content": "import * as Chunk from \"../Chunk.js\"\nimport type * as Deferred from \"../Deferred.js\"\nimport * as Either from \"../Either.js\"\nimport * as Equal from \"../Equal.js\"\nimport type { FiberId } from \"../FiberId.js\"\nimport * as HashMap from \"../HashMap.js\"\nimport * as List from \"../List.js\"\nimport * as Option from \"../Option.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as Request from \"../Request.js\"\nimport type * as RequestBlock from \"../RequestBlock.js\"\nimport type * as RequestResolver from \"../RequestResolver.js\"\n\n/** @internal */\nexport const empty: RequestBlock.RequestBlock = {\n  _tag: \"Empty\"\n}\n\n/**\n * Combines this collection of blocked requests with the specified collection\n * of blocked requests, in parallel.\n *\n * @internal\n */\nexport const par = (\n  self: RequestBlock.RequestBlock,\n  that: RequestBlock.RequestBlock\n): RequestBlock.RequestBlock => ({\n  _tag: \"Par\",\n  left: self,\n  right: that\n})\n\n/**\n * Combines this collection of blocked requests with the specified collection\n * of blocked requests, in sequence.\n *\n * @internal\n */\nexport const seq = (\n  self: RequestBlock.RequestBlock,\n  that: RequestBlock.RequestBlock\n): RequestBlock.RequestBlock => ({\n  _tag: \"Seq\",\n  left: self,\n  right: that\n})\n\n/**\n * Constructs a collection of blocked requests from the specified blocked\n * request and data source.\n *\n * @internal\n */\nexport const single = <A>(\n  dataSource: RequestResolver.RequestResolver<A>,\n  blockedRequest: Request.Entry<A>\n): RequestBlock.RequestBlock => ({\n  _tag: \"Single\",\n  dataSource: dataSource as any,\n  blockedRequest\n})\n\n/** @internal */\nexport const MapRequestResolversReducer = <A>(\n  f: (dataSource: RequestResolver.RequestResolver<A>) => RequestResolver.RequestResolver<A>\n): RequestBlock.RequestBlock.Reducer<RequestBlock.RequestBlock> => ({\n  emptyCase: () => empty,\n  parCase: (left, right) => par(left, right),\n  seqCase: (left, right) => seq(left, right),\n  singleCase: (dataSource, blockedRequest) => single(f(dataSource), blockedRequest as any)\n})\n\ntype BlockedRequestsCase = ParCase | SeqCase\n\ninterface ParCase {\n  readonly _tag: \"ParCase\"\n}\n\ninterface SeqCase {\n  readonly _tag: \"SeqCase\"\n}\n\n/**\n * Transforms all data sources with the specified data source aspect, which\n * can change the environment type of data sources but must preserve the\n * request type of each data source.\n *\n * @internal\n */\nexport const mapRequestResolvers = <A>(\n  self: RequestBlock.RequestBlock,\n  f: (dataSource: RequestResolver.RequestResolver<A>) => RequestResolver.RequestResolver<A>\n): RequestBlock.RequestBlock => reduce(self, MapRequestResolversReducer(f))\n\n/**\n * Folds over the cases of this collection of blocked requests with the\n * specified functions.\n *\n * @internal\n */\nexport const reduce = <Z>(\n  self: RequestBlock.RequestBlock,\n  reducer: RequestBlock.RequestBlock.Reducer<Z>\n): Z => {\n  let input: List.List<RequestBlock.RequestBlock> = List.of(self)\n  let output = List.empty<Either.Either<Z, BlockedRequestsCase>>()\n  while (List.isCons(input)) {\n    const current: RequestBlock.RequestBlock = input.head\n    switch (current._tag) {\n      case \"Empty\": {\n        output = List.cons(Either.right(reducer.emptyCase()), output)\n        input = input.tail\n        break\n      }\n      case \"Par\": {\n        output = List.cons(Either.left({ _tag: \"ParCase\" }), output)\n        input = List.cons(current.left, List.cons(current.right, input.tail))\n        break\n      }\n      case \"Seq\": {\n        output = List.cons(Either.left({ _tag: \"SeqCase\" }), output)\n        input = List.cons(current.left, List.cons(current.right, input.tail))\n        break\n      }\n      case \"Single\": {\n        const result = reducer.singleCase(current.dataSource, current.blockedRequest)\n        output = List.cons(Either.right(result), output)\n        input = input.tail\n        break\n      }\n    }\n  }\n  const result = List.reduce(output, List.empty<Z>(), (acc, current) => {\n    switch (current._tag) {\n      case \"Left\": {\n        const left = List.unsafeHead(acc)\n        const right = List.unsafeHead(List.unsafeTail(acc))\n        const tail = List.unsafeTail(List.unsafeTail(acc))\n        switch (current.left._tag) {\n          case \"ParCase\": {\n            return List.cons(reducer.parCase(left, right), tail)\n          }\n          case \"SeqCase\": {\n            return List.cons(reducer.seqCase(left, right), tail)\n          }\n        }\n      }\n      case \"Right\": {\n        return List.cons(current.right, acc)\n      }\n    }\n  })\n  if (List.isNil(result)) {\n    throw new Error(\n      \"BUG: BlockedRequests.reduce - please report an issue at https://github.com/Effect-TS/effect/issues\"\n    )\n  }\n  return result.head\n}\n\n/**\n * Flattens a collection of blocked requests into a collection of pipelined\n * and batched requests that can be submitted for execution.\n *\n * @internal\n */\nexport const flatten = (\n  self: RequestBlock.RequestBlock\n): List.List<SequentialCollection> => {\n  let current = List.of(self)\n  let updated = List.empty<SequentialCollection>()\n  // eslint-disable-next-line no-constant-condition\n  while (1) {\n    const [parallel, sequential] = List.reduce(\n      current,\n      [parallelCollectionEmpty(), List.empty<RequestBlock.RequestBlock>()] as const,\n      ([parallel, sequential], blockedRequest) => {\n        const [par, seq] = step(blockedRequest)\n        return [\n          parallelCollectionCombine(parallel, par),\n          List.appendAll(sequential, seq)\n        ]\n      }\n    )\n    updated = merge(updated, parallel)\n    if (List.isNil(sequential)) {\n      return List.reverse(updated)\n    }\n    current = sequential\n  }\n  throw new Error(\n    \"BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues\"\n  )\n}\n\n/**\n * Takes one step in evaluating a collection of blocked requests, returning a\n * collection of blocked requests that can be performed in parallel and a list\n * of blocked requests that must be performed sequentially after those\n * requests.\n */\nconst step = (\n  requests: RequestBlock.RequestBlock\n): [ParallelCollection, List.List<RequestBlock.RequestBlock>] => {\n  let current: RequestBlock.RequestBlock = requests\n  let parallel = parallelCollectionEmpty()\n  let stack = List.empty<RequestBlock.RequestBlock>()\n  let sequential = List.empty<RequestBlock.RequestBlock>()\n  // eslint-disable-next-line no-constant-condition\n  while (1) {\n    switch (current._tag) {\n      case \"Empty\": {\n        if (List.isNil(stack)) {\n          return [parallel, sequential]\n        }\n        current = stack.head\n        stack = stack.tail\n        break\n      }\n      case \"Par\": {\n        stack = List.cons(current.right, stack)\n        current = current.left\n        break\n      }\n      case \"Seq\": {\n        const left = current.left\n        const right = current.right\n        switch (left._tag) {\n          case \"Empty\": {\n            current = right\n            break\n          }\n          case \"Par\": {\n            const l = left.left\n            const r = left.right\n            current = par(seq(l, right), seq(r, right))\n            break\n          }\n          case \"Seq\": {\n            const l = left.left\n            const r = left.right\n            current = seq(l, seq(r, right))\n            break\n          }\n          case \"Single\": {\n            current = left\n            sequential = List.cons(right, sequential)\n            break\n          }\n        }\n        break\n      }\n      case \"Single\": {\n        parallel = parallelCollectionAdd(\n          parallel,\n          current\n        )\n        if (List.isNil(stack)) {\n          return [parallel, sequential]\n        }\n        current = stack.head\n        stack = stack.tail\n        break\n      }\n    }\n  }\n  throw new Error(\n    \"BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues\"\n  )\n}\n\n/**\n * Merges a collection of requests that must be executed sequentially with a\n * collection of requests that can be executed in parallel. If the collections\n * are both from the same single data source then the requests can be\n * pipelined while preserving ordering guarantees.\n */\nconst merge = (\n  sequential: List.List<SequentialCollection>,\n  parallel: ParallelCollection\n): List.List<SequentialCollection> => {\n  if (List.isNil(sequential)) {\n    return List.of(parallelCollectionToSequentialCollection(parallel))\n  }\n  if (parallelCollectionIsEmpty(parallel)) {\n    return sequential\n  }\n  const seqHeadKeys = sequentialCollectionKeys(sequential.head)\n  const parKeys = parallelCollectionKeys(parallel)\n  if (\n    seqHeadKeys.length === 1 &&\n    parKeys.length === 1 &&\n    Equal.equals(seqHeadKeys[0], parKeys[0])\n  ) {\n    return List.cons(\n      sequentialCollectionCombine(\n        sequential.head,\n        parallelCollectionToSequentialCollection(parallel)\n      ),\n      sequential.tail\n    )\n  }\n  return List.cons(parallelCollectionToSequentialCollection(parallel), sequential)\n}\n\n//\n// circular\n//\n\n/** @internal */\nexport const EntryTypeId: Request.EntryTypeId = Symbol.for(\n  \"effect/RequestBlock/Entry\"\n) as Request.EntryTypeId\n\n/** @internal */\nclass EntryImpl<A extends Request.Request<any, any>> implements Request.Entry<A> {\n  readonly [EntryTypeId] = blockedRequestVariance\n  constructor(\n    readonly request: A,\n    readonly result: Deferred.Deferred<Request.Request.Success<A>, Request.Request.Error<A>>,\n    readonly listeners: Request.Listeners,\n    readonly ownerId: FiberId,\n    readonly state: {\n      completed: boolean\n    }\n  ) {}\n}\n\nconst blockedRequestVariance = {\n  /* c8 ignore next */\n  _R: (_: never) => _\n}\n\n/** @internal */\nexport const isEntry = (u: unknown): u is Request.Entry<unknown> => hasProperty(u, EntryTypeId)\n\n/** @internal */\nexport const makeEntry = <A extends Request.Request<any, any>>(\n  options: {\n    readonly request: A\n    readonly result: Deferred.Deferred<Request.Request.Success<A>, Request.Request.Error<A>>\n    readonly listeners: Request.Listeners\n    readonly ownerId: FiberId\n    readonly state: { completed: boolean }\n  }\n): Request.Entry<A> => new EntryImpl(options.request, options.result, options.listeners, options.ownerId, options.state)\n\n/** @internal */\nexport const RequestBlockParallelTypeId = Symbol.for(\n  \"effect/RequestBlock/RequestBlockParallel\"\n)\n\nconst parallelVariance = {\n  /* c8 ignore next */\n  _R: (_: never) => _\n}\n\nclass ParallelImpl implements ParallelCollection {\n  readonly [RequestBlockParallelTypeId] = parallelVariance\n  constructor(\n    readonly map: HashMap.HashMap<\n      RequestResolver.RequestResolver<unknown, unknown>,\n      Chunk.Chunk<Request.Entry<unknown>>\n    >\n  ) {}\n}\n\n/** @internal */\nexport const parallelCollectionEmpty = (): ParallelCollection => new ParallelImpl(HashMap.empty())\n\n/** @internal */\nexport const parallelCollectionMake = <A>(\n  dataSource: RequestResolver.RequestResolver<A>,\n  blockedRequest: Request.Entry<A>\n): ParallelCollection => new ParallelImpl(HashMap.make([dataSource, Chunk.of(blockedRequest)]) as any)\n\n/** @internal */\nexport const parallelCollectionAdd = (\n  self: ParallelCollection,\n  blockedRequest: RequestBlock.Single\n): ParallelCollection =>\n  new ParallelImpl(HashMap.modifyAt(\n    self.map,\n    blockedRequest.dataSource,\n    (_) =>\n      Option.orElseSome(\n        Option.map(_, Chunk.append(blockedRequest.blockedRequest)),\n        () => Chunk.of(blockedRequest.blockedRequest)\n      )\n  ))\n\n/** @internal */\nexport const parallelCollectionCombine = (\n  self: ParallelCollection,\n  that: ParallelCollection\n): ParallelCollection =>\n  new ParallelImpl(HashMap.reduce(self.map, that.map, (map, value, key) =>\n    HashMap.set(\n      map,\n      key,\n      Option.match(HashMap.get(map, key), {\n        onNone: () => value,\n        onSome: (other) => Chunk.appendAll(value, other)\n      })\n    )))\n\n/** @internal */\nexport const parallelCollectionIsEmpty = (self: ParallelCollection): boolean => HashMap.isEmpty(self.map)\n\n/** @internal */\nexport const parallelCollectionKeys = (\n  self: ParallelCollection\n): Array<RequestResolver.RequestResolver<unknown>> => Array.from(HashMap.keys(self.map)) as any\n\n/** @internal */\nexport const parallelCollectionToSequentialCollection = (\n  self: ParallelCollection\n): SequentialCollection => sequentialCollectionMake(HashMap.map(self.map, (x) => Chunk.of(x)) as any)\n\n// TODO\n// /** @internal */\n// export const parallelCollectionToChunk = <R>(\n//   self: ParallelCollection<R>\n// ): Array<[RequestResolver.RequestResolver<unknown, R>, Array<Request.Entry<unknown>>]> => Array.from(self.map) as any\n\n/** @internal */\nexport const SequentialCollectionTypeId = Symbol.for(\n  \"effect/RequestBlock/RequestBlockSequential\"\n)\n\nconst sequentialVariance = {\n  /* c8 ignore next */\n  _R: (_: never) => _\n}\n\nclass SequentialImpl implements SequentialCollection {\n  readonly [SequentialCollectionTypeId] = sequentialVariance\n  constructor(\n    readonly map: HashMap.HashMap<\n      RequestResolver.RequestResolver<unknown, unknown>,\n      Chunk.Chunk<Chunk.Chunk<Request.Entry<unknown>>>\n    >\n  ) {}\n}\n\n/** @internal */\nexport const sequentialCollectionMake = <A, R>(\n  map: HashMap.HashMap<\n    RequestResolver.RequestResolver<A, R>,\n    Chunk.Chunk<Chunk.Chunk<Request.Entry<A>>>\n  >\n): SequentialCollection => new SequentialImpl(map as any)\n\n/** @internal */\nexport const sequentialCollectionCombine = (\n  self: SequentialCollection,\n  that: SequentialCollection\n): SequentialCollection =>\n  new SequentialImpl(HashMap.reduce(that.map, self.map, (map, value, key) =>\n    HashMap.set(\n      map,\n      key,\n      Option.match(HashMap.get(map, key), {\n        onNone: () => Chunk.empty(),\n        onSome: (a) => Chunk.appendAll(a, value)\n      })\n    )))\n\n/** @internal */\nexport const sequentialCollectionIsEmpty = (self: SequentialCollection): boolean => HashMap.isEmpty(self.map)\n\n/** @internal */\nexport const sequentialCollectionKeys = (\n  self: SequentialCollection\n): Array<RequestResolver.RequestResolver<unknown>> => Array.from(HashMap.keys(self.map)) as any\n\n/** @internal */\nexport const sequentialCollectionToChunk = (\n  self: SequentialCollection\n): Array<[RequestResolver.RequestResolver<unknown>, Chunk.Chunk<Chunk.Chunk<Request.Entry<unknown>>>]> =>\n  Array.from(self.map) as any\n\n/** @internal */\nexport type RequestBlockParallelTypeId = typeof RequestBlockParallelTypeId\n\n/** @internal */\nexport interface ParallelCollection extends ParallelCollection.Variance {\n  readonly map: HashMap.HashMap<\n    RequestResolver.RequestResolver<unknown, unknown>,\n    Chunk.Chunk<Request.Entry<unknown>>\n  >\n}\n\n/** @internal */\nexport declare namespace ParallelCollection {\n  /** @internal */\n  export interface Variance {\n    readonly [RequestBlockParallelTypeId]: {}\n  }\n}\n\n/** @internal */\nexport type SequentialCollectionTypeId = typeof SequentialCollectionTypeId\n\n/** @internal */\nexport interface SequentialCollection extends SequentialCollection.Variance {\n  readonly map: HashMap.HashMap<\n    RequestResolver.RequestResolver<unknown, unknown>,\n    Chunk.Chunk<Chunk.Chunk<Request.Entry<unknown>>>\n  >\n}\n\n/** @internal */\nexport declare namespace SequentialCollection {\n  /** @internal */\n  export interface Variance {\n    readonly [SequentialCollectionTypeId]: {}\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/cache.ts",
    "content": "import type * as Cache from \"../Cache.js\"\nimport type * as Clock from \"../Clock.js\"\nimport * as Context from \"../Context.js\"\nimport * as Deferred from \"../Deferred.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport * as Equal from \"../Equal.js\"\nimport * as Exit from \"../Exit.js\"\nimport type * as FiberId from \"../FiberId.js\"\nimport { pipe } from \"../Function.js\"\nimport * as Hash from \"../Hash.js\"\nimport * as MutableHashMap from \"../MutableHashMap.js\"\nimport * as MutableQueue from \"../MutableQueue.js\"\nimport * as MutableRef from \"../MutableRef.js\"\nimport * as Option from \"../Option.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport * as effect from \"./core-effect.js\"\nimport * as core from \"./core.js\"\nimport * as Data from \"./data.js\"\nimport { none } from \"./fiberId.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\n\n/**\n * A `MapValue` represents a value in the cache. A value may either be\n * `Pending` with a `Promise` that will contain the result of computing the\n * lookup function, when it is available, or `Complete` with an `Exit` value\n * that contains the result of computing the lookup function.\n *\n * @internal\n */\nexport type MapValue<Key, Value, Error> =\n  | Complete<Key, Value, Error>\n  | Pending<Key, Value, Error>\n  | Refreshing<Key, Value, Error>\n\n/** @internal */\nexport interface Complete<out Key, out Value, out Error> {\n  readonly _tag: \"Complete\"\n  readonly key: MapKey<Key>\n  readonly exit: Exit.Exit<Value, Error>\n  readonly entryStats: Cache.EntryStats\n  readonly timeToLiveMillis: number\n}\n\n/** @internal */\nexport interface Pending<out Key, in out Value, in out Error> {\n  readonly _tag: \"Pending\"\n  readonly key: MapKey<Key>\n  readonly deferred: Deferred.Deferred<Value, Error>\n}\n\n/** @internal */\nexport interface Refreshing<out Key, in out Value, in out Error> {\n  readonly _tag: \"Refreshing\"\n  readonly deferred: Deferred.Deferred<Value, Error>\n  readonly complete: Complete<Key, Value, Error>\n}\n\n/** @internal */\nexport const complete = <Key, Value, Error>(\n  key: MapKey<Key>,\n  exit: Exit.Exit<Value, Error>,\n  entryStats: Cache.EntryStats,\n  timeToLiveMillis: number\n): MapValue<Key, Value, Error> =>\n  Data.struct({\n    _tag: \"Complete\" as const,\n    key,\n    exit,\n    entryStats,\n    timeToLiveMillis\n  })\n\n/** @internal */\nexport const pending = <Key, Value, Error>(\n  key: MapKey<Key>,\n  deferred: Deferred.Deferred<Value, Error>\n): MapValue<Key, Value, Error> =>\n  Data.struct({\n    _tag: \"Pending\" as const,\n    key,\n    deferred\n  })\n\n/** @internal */\nexport const refreshing = <Key, Value, Error>(\n  deferred: Deferred.Deferred<Value, Error>,\n  complete: Complete<Key, Value, Error>\n): MapValue<Key, Value, Error> =>\n  Data.struct({\n    _tag: \"Refreshing\" as const,\n    deferred,\n    complete\n  })\n\n/** @internal */\nexport const MapKeyTypeId = Symbol.for(\"effect/Cache/MapKey\")\n\n/** @internal */\nexport type MapKeyTypeId = typeof MapKeyTypeId\n\n/**\n * A `MapKey` represents a key in the cache. It contains mutable references\n * to the previous key and next key in the `KeySet` to support an efficient\n * implementation of a sorted set of keys.\n *\n * @internal\n */\nexport interface MapKey<out K> extends Equal.Equal {\n  readonly [MapKeyTypeId]: MapKeyTypeId\n  readonly current: K\n  previous: MapKey<K> | undefined // mutable by design\n  next: MapKey<K> | undefined // mutable by design\n}\n\nclass MapKeyImpl<out K> implements MapKey<K> {\n  readonly [MapKeyTypeId]: MapKeyTypeId = MapKeyTypeId\n  previous: MapKey<K> | undefined = undefined\n  next: MapKey<K> | undefined = undefined\n  constructor(readonly current: K) {}\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(this.current),\n      Hash.combine(Hash.hash(this.previous)),\n      Hash.combine(Hash.hash(this.next)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](that: unknown): boolean {\n    if (this === that) {\n      return true\n    }\n    return isMapKey(that) &&\n      Equal.equals(this.current, that.current) &&\n      Equal.equals(this.previous, that.previous) &&\n      Equal.equals(this.next, that.next)\n  }\n}\n\n/** @internal */\nexport const makeMapKey = <K>(current: K): MapKey<K> => new MapKeyImpl(current)\n\n/** @internal */\nexport const isMapKey = (u: unknown): u is MapKey<unknown> => hasProperty(u, MapKeyTypeId)\n\n/**\n * A `KeySet` is a sorted set of keys in the cache ordered by last access.\n * For efficiency, the set is implemented in terms of a doubly linked list\n * and is not safe for concurrent access.\n *\n * @internal\n */\nexport interface KeySet<in out K> {\n  head: MapKey<K> | undefined // mutable by design\n  tail: MapKey<K> | undefined // mutable by design\n  /**\n   * Adds the specified key to the set.\n   */\n  add(key: MapKey<K>): void\n  /**\n   * Removes the lowest priority key from the set.\n   */\n  remove(): MapKey<K> | undefined\n}\n\nclass KeySetImpl<in out K> implements KeySet<K> {\n  head: MapKey<K> | undefined = undefined\n  tail: MapKey<K> | undefined = undefined\n  add(key: MapKey<K>): void {\n    if (key !== this.tail) {\n      if (this.tail === undefined) {\n        this.head = key\n        this.tail = key\n      } else {\n        const previous = key.previous\n        const next = key.next\n        if (next !== undefined) {\n          key.next = undefined\n          if (previous !== undefined) {\n            previous.next = next\n            next.previous = previous\n          } else {\n            this.head = next\n            this.head.previous = undefined\n          }\n        }\n        this.tail.next = key\n        key.previous = this.tail\n        this.tail = key\n      }\n    }\n  }\n  remove(): MapKey<K> | undefined {\n    const key = this.head\n    if (key !== undefined) {\n      const next = key.next\n      if (next !== undefined) {\n        key.next = undefined\n        this.head = next\n        this.head.previous = undefined\n      } else {\n        this.head = undefined\n        this.tail = undefined\n      }\n    }\n    return key\n  }\n}\n\n/** @internal */\nexport const makeKeySet = <K>(): KeySet<K> => new KeySetImpl<K>()\n\n/**\n * The `CacheState` represents the mutable state underlying the cache.\n *\n * @internal\n */\nexport interface CacheState<in out Key, in out Value, in out Error> {\n  map: MutableHashMap.MutableHashMap<Key, MapValue<Key, Value, Error>> // mutable by design\n  keys: KeySet<Key> // mutable by design\n  accesses: MutableQueue.MutableQueue<MapKey<Key>> // mutable by design\n  updating: MutableRef.MutableRef<boolean> // mutable by design\n  hits: number // mutable by design\n  misses: number // mutable by design\n}\n\n/**\n * Constructs a new `CacheState` from the specified values.\n *\n * @internal\n */\nexport const makeCacheState = <Key, Value, Error>(\n  map: MutableHashMap.MutableHashMap<Key, MapValue<Key, Value, Error>>,\n  keys: KeySet<Key>,\n  accesses: MutableQueue.MutableQueue<MapKey<Key>>,\n  updating: MutableRef.MutableRef<boolean>,\n  hits: number,\n  misses: number\n): CacheState<Key, Value, Error> => ({\n  map,\n  keys,\n  accesses,\n  updating,\n  hits,\n  misses\n})\n\n/**\n * Constructs an initial cache state.\n *\n * @internal\n */\nexport const initialCacheState = <Key, Value, Error>(): CacheState<Key, Value, Error> =>\n  makeCacheState(\n    MutableHashMap.empty(),\n    makeKeySet(),\n    MutableQueue.unbounded(),\n    MutableRef.make(false),\n    0,\n    0\n  )\n\n/** @internal */\nconst CacheSymbolKey = \"effect/Cache\"\n\n/** @internal */\nexport const CacheTypeId: Cache.CacheTypeId = Symbol.for(\n  CacheSymbolKey\n) as Cache.CacheTypeId\n\nconst cacheVariance = {\n  /* c8 ignore next */\n  _Key: (_: any) => _,\n  /* c8 ignore next */\n  _Error: (_: never) => _,\n  /* c8 ignore next */\n  _Value: (_: any) => _\n}\n\n/** @internal */\nconst ConsumerCacheSymbolKey = \"effect/ConsumerCache\"\n\n/** @internal */\nexport const ConsumerCacheTypeId: Cache.ConsumerCacheTypeId = Symbol.for(\n  ConsumerCacheSymbolKey\n) as Cache.ConsumerCacheTypeId\n\nconst consumerCacheVariance = {\n  /* c8 ignore next */\n  _Key: (_: any) => _,\n  /* c8 ignore next */\n  _Error: (_: never) => _,\n  /* c8 ignore next */\n  _Value: (_: never) => _\n}\n\n/** @internal */\nexport const makeCacheStats = (\n  options: {\n    readonly hits: number\n    readonly misses: number\n    readonly size: number\n  }\n): Cache.CacheStats => options\n\n/** @internal */\nexport const makeEntryStats = (loadedMillis: number): Cache.EntryStats => ({\n  loadedMillis\n})\n\nclass CacheImpl<in out Key, in out Value, in out Error> implements Cache.Cache<Key, Value, Error> {\n  readonly [CacheTypeId] = cacheVariance\n  readonly [ConsumerCacheTypeId] = consumerCacheVariance\n  readonly cacheState: CacheState<Key, Value, Error>\n  constructor(\n    readonly capacity: number,\n    readonly context: Context.Context<any>,\n    readonly fiberId: FiberId.FiberId,\n    readonly lookup: Cache.Lookup<Key, Value, Error, any>,\n    readonly timeToLive: (exit: Exit.Exit<Value, Error>) => Duration.DurationInput\n  ) {\n    this.cacheState = initialCacheState()\n  }\n\n  get(key: Key): Effect.Effect<Value, Error> {\n    return core.map(this.getEither(key), Either.merge)\n  }\n\n  get cacheStats(): Effect.Effect<Cache.CacheStats> {\n    return core.sync(() =>\n      makeCacheStats({\n        hits: this.cacheState.hits,\n        misses: this.cacheState.misses,\n        size: MutableHashMap.size(this.cacheState.map)\n      })\n    )\n  }\n\n  getOption(key: Key): Effect.Effect<Option.Option<Value>, Error> {\n    return core.suspend(() =>\n      Option.match(MutableHashMap.get(this.cacheState.map, key), {\n        onNone: () => {\n          const mapKey = makeMapKey(key)\n          this.trackAccess(mapKey)\n          this.trackMiss()\n          return core.succeed(Option.none<Value>())\n        },\n        onSome: (value) => this.resolveMapValue(value)\n      })\n    )\n  }\n\n  getOptionComplete(key: Key): Effect.Effect<Option.Option<Value>> {\n    return core.suspend(() =>\n      Option.match(MutableHashMap.get(this.cacheState.map, key), {\n        onNone: () => {\n          const mapKey = makeMapKey(key)\n          this.trackAccess(mapKey)\n          this.trackMiss()\n          return core.succeed(Option.none<Value>())\n        },\n        onSome: (value) => this.resolveMapValue(value, true) as Effect.Effect<Option.Option<Value>>\n      })\n    )\n  }\n\n  contains(key: Key): Effect.Effect<boolean> {\n    return core.sync(() => MutableHashMap.has(this.cacheState.map, key))\n  }\n\n  entryStats(key: Key): Effect.Effect<Option.Option<Cache.EntryStats>> {\n    return core.sync(() => {\n      const option = MutableHashMap.get(this.cacheState.map, key)\n      if (Option.isSome(option)) {\n        switch (option.value._tag) {\n          case \"Complete\": {\n            const loaded = option.value.entryStats.loadedMillis\n            return Option.some(makeEntryStats(loaded))\n          }\n          case \"Pending\": {\n            return Option.none()\n          }\n          case \"Refreshing\": {\n            const loaded = option.value.complete.entryStats.loadedMillis\n            return Option.some(makeEntryStats(loaded))\n          }\n        }\n      }\n      return Option.none()\n    })\n  }\n\n  getEither(key: Key): Effect.Effect<Either.Either<Value, Value>, Error> {\n    return core.suspend((): Effect.Effect<Either.Either<Value, Value>, Error> => {\n      const k = key\n      let mapKey: MapKey<Key> | undefined = undefined\n      let deferred: Deferred.Deferred<Value, Error> | undefined = undefined\n      let value = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, k))\n      if (value === undefined) {\n        deferred = Deferred.unsafeMake<Value, Error>(this.fiberId)\n        mapKey = makeMapKey(k)\n        if (MutableHashMap.has(this.cacheState.map, k)) {\n          value = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, k))\n        } else {\n          MutableHashMap.set(this.cacheState.map, k, pending(mapKey, deferred))\n        }\n      }\n      if (value === undefined) {\n        this.trackAccess(mapKey!)\n        this.trackMiss()\n        return core.map(this.lookupValueOf(key, deferred!), Either.right)\n      } else {\n        return core.flatMap(\n          this.resolveMapValue(value),\n          Option.match({\n            onNone: () => this.getEither(key),\n            onSome: (value) => core.succeed(Either.left(value))\n          })\n        )\n      }\n    })\n  }\n\n  invalidate(key: Key): Effect.Effect<void> {\n    return core.sync(() => {\n      MutableHashMap.remove(this.cacheState.map, key)\n    })\n  }\n\n  invalidateWhen(key: Key, when: (value: Value) => boolean): Effect.Effect<void> {\n    return core.sync(() => {\n      const value = MutableHashMap.get(this.cacheState.map, key)\n      if (Option.isSome(value) && value.value._tag === \"Complete\") {\n        if (value.value.exit._tag === \"Success\") {\n          if (when(value.value.exit.value)) {\n            MutableHashMap.remove(this.cacheState.map, key)\n          }\n        }\n      }\n    })\n  }\n\n  get invalidateAll(): Effect.Effect<void> {\n    return core.sync(() => {\n      this.cacheState.map = MutableHashMap.empty()\n    })\n  }\n\n  refresh(key: Key): Effect.Effect<void, Error> {\n    return effect.clockWith((clock) =>\n      core.suspend(() => {\n        const k = key\n        const deferred: Deferred.Deferred<Value, Error> = Deferred.unsafeMake(this.fiberId)\n        let value = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, k))\n        if (value === undefined) {\n          if (MutableHashMap.has(this.cacheState.map, k)) {\n            value = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, k))\n          } else {\n            MutableHashMap.set(this.cacheState.map, k, pending(makeMapKey(k), deferred))\n          }\n        }\n        if (value === undefined) {\n          return core.asVoid(this.lookupValueOf(key, deferred))\n        } else {\n          switch (value._tag) {\n            case \"Complete\": {\n              if (this.hasExpired(clock, value.timeToLiveMillis)) {\n                const found = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, k))\n                if (Equal.equals(found, value)) {\n                  MutableHashMap.remove(this.cacheState.map, k)\n                }\n                return core.asVoid(this.get(key))\n              }\n              // Only trigger the lookup if we're still the current value, `completedResult`\n              return pipe(\n                this.lookupValueOf(key, deferred),\n                effect.when(() => {\n                  const current = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, k))\n                  if (Equal.equals(current, value)) {\n                    const mapValue = refreshing(deferred, value as Complete<Key, Value, Error>)\n                    MutableHashMap.set(this.cacheState.map, k, mapValue)\n                    return true\n                  }\n                  return false\n                }),\n                core.asVoid\n              )\n            }\n            case \"Pending\": {\n              return Deferred.await(value.deferred)\n            }\n            case \"Refreshing\": {\n              return Deferred.await(value.deferred)\n            }\n          }\n        }\n      })\n    )\n  }\n\n  set(key: Key, value: Value): Effect.Effect<void> {\n    return effect.clockWith((clock) =>\n      core.sync(() => {\n        const now = clock.unsafeCurrentTimeMillis()\n        const k = key\n        const lookupResult = Exit.succeed(value)\n        const mapValue = complete(\n          makeMapKey(k),\n          lookupResult,\n          makeEntryStats(now),\n          now + Duration.toMillis(Duration.decode(this.timeToLive(lookupResult)))\n        )\n        MutableHashMap.set(\n          this.cacheState.map,\n          k,\n          mapValue as Complete<Key, Value, Error>\n        )\n      })\n    )\n  }\n\n  get size(): Effect.Effect<number> {\n    return core.sync(() => {\n      return MutableHashMap.size(this.cacheState.map)\n    })\n  }\n\n  get values(): Effect.Effect<Array<Value>> {\n    return core.sync(() => {\n      const values: Array<Value> = []\n      for (const entry of this.cacheState.map) {\n        if (entry[1]._tag === \"Complete\" && entry[1].exit._tag === \"Success\") {\n          values.push(entry[1].exit.value)\n        }\n      }\n      return values\n    })\n  }\n\n  get entries(): Effect.Effect<Array<[Key, Value]>> {\n    return core.sync(() => {\n      const values: Array<[Key, Value]> = []\n      for (const entry of this.cacheState.map) {\n        if (entry[1]._tag === \"Complete\" && entry[1].exit._tag === \"Success\") {\n          values.push([entry[0], entry[1].exit.value])\n        }\n      }\n      return values\n    })\n  }\n\n  get keys(): Effect.Effect<Array<Key>> {\n    return core.sync(() => {\n      const keys: Array<Key> = []\n      for (const entry of this.cacheState.map) {\n        if (entry[1]._tag === \"Complete\" && entry[1].exit._tag === \"Success\") {\n          keys.push(entry[0])\n        }\n      }\n      return keys\n    })\n  }\n\n  resolveMapValue(\n    value: MapValue<Key, Value, Error>,\n    ignorePending = false\n  ): Effect.Effect<Option.Option<Value>, Error> {\n    return effect.clockWith((clock) => {\n      switch (value._tag) {\n        case \"Complete\": {\n          this.trackAccess(value.key)\n          if (this.hasExpired(clock, value.timeToLiveMillis)) {\n            MutableHashMap.remove(this.cacheState.map, value.key.current)\n            return core.succeed(Option.none<Value>())\n          }\n          this.trackHit()\n          return core.map(value.exit, Option.some)\n        }\n        case \"Pending\": {\n          this.trackAccess(value.key)\n          this.trackHit()\n          if (ignorePending) {\n            return core.succeed(Option.none<Value>())\n          }\n          return core.map(Deferred.await(value.deferred), Option.some)\n        }\n        case \"Refreshing\": {\n          this.trackAccess(value.complete.key)\n          this.trackHit()\n          if (this.hasExpired(clock, value.complete.timeToLiveMillis)) {\n            if (ignorePending) {\n              return core.succeed(Option.none<Value>())\n            }\n            return core.map(Deferred.await(value.deferred), Option.some)\n          }\n          return core.map(value.complete.exit, Option.some)\n        }\n      }\n    })\n  }\n\n  trackHit(): void {\n    this.cacheState.hits = this.cacheState.hits + 1\n  }\n\n  trackMiss(): void {\n    this.cacheState.misses = this.cacheState.misses + 1\n  }\n\n  trackAccess(key: MapKey<Key>): void {\n    MutableQueue.offer(this.cacheState.accesses, key)\n    if (MutableRef.compareAndSet(this.cacheState.updating, false, true)) {\n      let loop = true\n      while (loop) {\n        const key = MutableQueue.poll(this.cacheState.accesses, MutableQueue.EmptyMutableQueue)\n        if (key === MutableQueue.EmptyMutableQueue) {\n          loop = false\n        } else {\n          this.cacheState.keys.add(key)\n        }\n      }\n      let size = MutableHashMap.size(this.cacheState.map)\n      loop = size > this.capacity\n      while (loop) {\n        const key = this.cacheState.keys.remove()\n        if (key !== undefined) {\n          if (MutableHashMap.has(this.cacheState.map, key.current)) {\n            MutableHashMap.remove(this.cacheState.map, key.current)\n            size = size - 1\n            loop = size > this.capacity\n          }\n        } else {\n          loop = false\n        }\n      }\n      MutableRef.set(this.cacheState.updating, false)\n    }\n  }\n\n  hasExpired(clock: Clock.Clock, timeToLiveMillis: number): boolean {\n    return clock.unsafeCurrentTimeMillis() > timeToLiveMillis\n  }\n\n  lookupValueOf(\n    input: Key,\n    deferred: Deferred.Deferred<Value, Error>\n  ): Effect.Effect<Value, Error> {\n    return effect.clockWith((clock) =>\n      core.suspend(() => {\n        const key = input\n        return pipe(\n          this.lookup(input),\n          core.provideContext(this.context),\n          core.exit,\n          core.flatMap((exit) => {\n            const now = clock.unsafeCurrentTimeMillis()\n            const stats = makeEntryStats(now)\n            const value = complete(\n              makeMapKey(key),\n              exit,\n              stats,\n              now + Duration.toMillis(Duration.decode(this.timeToLive(exit)))\n            )\n            MutableHashMap.set(this.cacheState.map, key, value)\n            return core.zipRight(\n              Deferred.done(deferred, exit),\n              exit\n            )\n          }),\n          core.onInterrupt(() =>\n            core.zipRight(\n              Deferred.interrupt(deferred),\n              core.sync(() => {\n                MutableHashMap.remove(this.cacheState.map, key)\n              })\n            )\n          )\n        )\n      })\n    )\n  }\n}\n\n/** @internal */\nexport const make = <Key, Value, Error = never, Environment = never>(\n  options: {\n    readonly capacity: number\n    readonly timeToLive: Duration.DurationInput\n    readonly lookup: Cache.Lookup<Key, Value, Error, Environment>\n  }\n): Effect.Effect<Cache.Cache<Key, Value, Error>, never, Environment> => {\n  const timeToLive = Duration.decode(options.timeToLive)\n  return makeWith({\n    capacity: options.capacity,\n    lookup: options.lookup,\n    timeToLive: () => timeToLive\n  })\n}\n\n/** @internal */\nexport const makeWith = <Key, Value, Error = never, Environment = never>(\n  options: {\n    readonly capacity: number\n    readonly lookup: Cache.Lookup<Key, Value, Error, Environment>\n    readonly timeToLive: (exit: Exit.Exit<Value, Error>) => Duration.DurationInput\n  }\n): Effect.Effect<Cache.Cache<Key, Value, Error>, never, Environment> =>\n  core.map(\n    fiberRuntime.all([core.context<Environment>(), core.fiberId]),\n    ([context, fiberId]) =>\n      new CacheImpl(\n        options.capacity,\n        context,\n        fiberId,\n        options.lookup,\n        (exit) => Duration.decode(options.timeToLive(exit))\n      )\n  )\n\n/** @internal */\nexport const unsafeMakeWith = <Key, Value, Error = never>(\n  capacity: number,\n  lookup: Cache.Lookup<Key, Value, Error>,\n  timeToLive: (exit: Exit.Exit<Value, Error>) => Duration.DurationInput\n): Cache.Cache<Key, Value, Error> =>\n  new CacheImpl<Key, Value, Error>(\n    capacity,\n    Context.empty() as Context.Context<any>,\n    none,\n    lookup,\n    (exit) => Duration.decode(timeToLive(exit))\n  )\n"
  },
  {
    "path": "packages/effect/src/internal/cause.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport type * as Cause from \"../Cause.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport * as Either from \"../Either.js\"\nimport * as Equal from \"../Equal.js\"\nimport type * as FiberId from \"../FiberId.js\"\nimport { constFalse, constTrue, dual, identity, pipe } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport * as Hash from \"../Hash.js\"\nimport * as HashSet from \"../HashSet.js\"\nimport { NodeInspectSymbol, stringifyCircular, toJSON } from \"../Inspectable.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport type { Predicate, Refinement } from \"../Predicate.js\"\nimport { hasProperty, isFunction } from \"../Predicate.js\"\nimport type { AnySpan, Span } from \"../Tracer.js\"\nimport type * as Types from \"../Types.js\"\nimport { getBugErrorMessage } from \"./errors.js\"\nimport * as OpCodes from \"./opCodes/cause.js\"\n\n// -----------------------------------------------------------------------------\n// Models\n// -----------------------------------------------------------------------------\n\n/** @internal */\nconst CauseSymbolKey = \"effect/Cause\"\n\n/** @internal */\nexport const CauseTypeId: Cause.CauseTypeId = Symbol.for(\n  CauseSymbolKey\n) as Cause.CauseTypeId\n\nconst variance = {\n  /* c8 ignore next */\n  _E: (_: never) => _\n}\n\n/** @internal */\nconst proto = {\n  [CauseTypeId]: variance,\n  [Hash.symbol](this: Cause.Cause<any>): number {\n    return pipe(\n      Hash.hash(CauseSymbolKey),\n      Hash.combine(Hash.hash(flattenCause(this))),\n      Hash.cached(this)\n    )\n  },\n  [Equal.symbol](this: Cause.Cause<any>, that: unknown): boolean {\n    return isCause(that) && causeEquals(this, that)\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  toJSON<E>(this: Cause.Cause<E>) {\n    switch (this._tag) {\n      case \"Empty\":\n        return { _id: \"Cause\", _tag: this._tag }\n      case \"Die\":\n        return { _id: \"Cause\", _tag: this._tag, defect: toJSON(this.defect) }\n      case \"Interrupt\":\n        return { _id: \"Cause\", _tag: this._tag, fiberId: this.fiberId.toJSON() }\n      case \"Fail\":\n        return { _id: \"Cause\", _tag: this._tag, failure: toJSON(this.error) }\n      case \"Sequential\":\n      case \"Parallel\":\n        return { _id: \"Cause\", _tag: this._tag, left: toJSON(this.left), right: toJSON(this.right) }\n    }\n  },\n  toString<E>(this: Cause.Cause<E>) {\n    return pretty(this)\n  },\n  [NodeInspectSymbol]<E>(this: Cause.Cause<E>) {\n    return this.toJSON()\n  }\n}\n\n// -----------------------------------------------------------------------------\n// Constructors\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const empty: Cause.Cause<never> = (() => {\n  const o = Object.create(proto)\n  o._tag = OpCodes.OP_EMPTY\n  return o\n})()\n\n/** @internal */\nexport const fail = <E>(error: E): Cause.Cause<E> => {\n  const o = Object.create(proto)\n  o._tag = OpCodes.OP_FAIL\n  o.error = error\n  return o\n}\n\n/** @internal */\nexport const die = (defect: unknown): Cause.Cause<never> => {\n  const o = Object.create(proto)\n  o._tag = OpCodes.OP_DIE\n  o.defect = defect\n  return o\n}\n\n/** @internal */\nexport const interrupt = (fiberId: FiberId.FiberId): Cause.Cause<never> => {\n  const o = Object.create(proto)\n  o._tag = OpCodes.OP_INTERRUPT\n  o.fiberId = fiberId\n  return o\n}\n\n/** @internal */\nexport const parallel = <E, E2>(left: Cause.Cause<E>, right: Cause.Cause<E2>): Cause.Cause<E | E2> => {\n  const o = Object.create(proto)\n  o._tag = OpCodes.OP_PARALLEL\n  o.left = left\n  o.right = right\n  return o\n}\n\n/** @internal */\nexport const sequential = <E, E2>(left: Cause.Cause<E>, right: Cause.Cause<E2>): Cause.Cause<E | E2> => {\n  const o = Object.create(proto)\n  o._tag = OpCodes.OP_SEQUENTIAL\n  o.left = left\n  o.right = right\n  return o\n}\n\n// -----------------------------------------------------------------------------\n// Refinements\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const isCause = (u: unknown): u is Cause.Cause<unknown> => hasProperty(u, CauseTypeId)\n\n/** @internal */\nexport const isEmptyType = <E>(self: Cause.Cause<E>): self is Cause.Empty => self._tag === OpCodes.OP_EMPTY\n\n/** @internal */\nexport const isFailType = <E>(self: Cause.Cause<E>): self is Cause.Fail<E> => self._tag === OpCodes.OP_FAIL\n\n/** @internal */\nexport const isDieType = <E>(self: Cause.Cause<E>): self is Cause.Die => self._tag === OpCodes.OP_DIE\n\n/** @internal */\nexport const isInterruptType = <E>(self: Cause.Cause<E>): self is Cause.Interrupt => self._tag === OpCodes.OP_INTERRUPT\n\n/** @internal */\nexport const isSequentialType = <E>(self: Cause.Cause<E>): self is Cause.Sequential<E> =>\n  self._tag === OpCodes.OP_SEQUENTIAL\n\n/** @internal */\nexport const isParallelType = <E>(self: Cause.Cause<E>): self is Cause.Parallel<E> => self._tag === OpCodes.OP_PARALLEL\n\n// -----------------------------------------------------------------------------\n// Getters\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const size = <E>(self: Cause.Cause<E>): number => reduceWithContext(self, void 0, SizeCauseReducer)\n\n/** @internal */\nexport const isEmpty = <E>(self: Cause.Cause<E>): boolean => {\n  if (self._tag === OpCodes.OP_EMPTY) {\n    return true\n  }\n  return reduce(self, true, (acc, cause) => {\n    switch (cause._tag) {\n      case OpCodes.OP_EMPTY: {\n        return Option.some(acc)\n      }\n      case OpCodes.OP_DIE:\n      case OpCodes.OP_FAIL:\n      case OpCodes.OP_INTERRUPT: {\n        return Option.some(false)\n      }\n      default: {\n        return Option.none()\n      }\n    }\n  })\n}\n\n/** @internal */\nexport const isFailure = <E>(self: Cause.Cause<E>): boolean => Option.isSome(failureOption(self))\n\n/** @internal */\nexport const isDie = <E>(self: Cause.Cause<E>): boolean => Option.isSome(dieOption(self))\n\n/** @internal */\nexport const isInterrupted = <E>(self: Cause.Cause<E>): boolean => Option.isSome(interruptOption(self))\n\n/** @internal */\nexport const isInterruptedOnly = <E>(self: Cause.Cause<E>): boolean =>\n  reduceWithContext(undefined, IsInterruptedOnlyCauseReducer)(self)\n\n/** @internal */\nexport const failures = <E>(self: Cause.Cause<E>): Chunk.Chunk<E> =>\n  Chunk.reverse(\n    reduce<Chunk.Chunk<E>, E>(\n      self,\n      Chunk.empty<E>(),\n      (list, cause) =>\n        cause._tag === OpCodes.OP_FAIL ?\n          Option.some(pipe(list, Chunk.prepend(cause.error))) :\n          Option.none()\n    )\n  )\n\n/** @internal */\nexport const defects = <E>(self: Cause.Cause<E>): Chunk.Chunk<unknown> =>\n  Chunk.reverse(\n    reduce<Chunk.Chunk<unknown>, E>(\n      self,\n      Chunk.empty<unknown>(),\n      (list, cause) =>\n        cause._tag === OpCodes.OP_DIE ?\n          Option.some(pipe(list, Chunk.prepend(cause.defect))) :\n          Option.none()\n    )\n  )\n\n/** @internal */\nexport const interruptors = <E>(self: Cause.Cause<E>): HashSet.HashSet<FiberId.FiberId> =>\n  reduce(self, HashSet.empty<FiberId.FiberId>(), (set, cause) =>\n    cause._tag === OpCodes.OP_INTERRUPT ?\n      Option.some(pipe(set, HashSet.add(cause.fiberId))) :\n      Option.none())\n\n/** @internal */\nexport const failureOption = <E>(self: Cause.Cause<E>): Option.Option<E> =>\n  find<E, E>(self, (cause) =>\n    cause._tag === OpCodes.OP_FAIL ?\n      Option.some(cause.error) :\n      Option.none())\n\n/** @internal */\nexport const failureOrCause = <E>(self: Cause.Cause<E>): Either.Either<Cause.Cause<never>, E> => {\n  const option = failureOption(self)\n  switch (option._tag) {\n    case \"None\": {\n      // no `E` inside this `Cause`, so it can be safely cast to `never`\n      return Either.right(self as Cause.Cause<never>)\n    }\n    case \"Some\": {\n      return Either.left(option.value)\n    }\n  }\n}\n\n/** @internal */\nexport const dieOption = <E>(self: Cause.Cause<E>): Option.Option<unknown> =>\n  find(self, (cause) =>\n    cause._tag === OpCodes.OP_DIE ?\n      Option.some(cause.defect) :\n      Option.none())\n\n/** @internal */\nexport const flipCauseOption = <E>(self: Cause.Cause<Option.Option<E>>): Option.Option<Cause.Cause<E>> =>\n  match(self, {\n    onEmpty: Option.some<Cause.Cause<E>>(empty),\n    onFail: Option.map(fail),\n    onDie: (defect) => Option.some(die(defect)),\n    onInterrupt: (fiberId) => Option.some(interrupt(fiberId)),\n    onSequential: Option.mergeWith(sequential),\n    onParallel: Option.mergeWith(parallel)\n  })\n\n/** @internal */\nexport const interruptOption = <E>(self: Cause.Cause<E>): Option.Option<FiberId.FiberId> =>\n  find(self, (cause) =>\n    cause._tag === OpCodes.OP_INTERRUPT ?\n      Option.some(cause.fiberId) :\n      Option.none())\n\n/** @internal */\nexport const keepDefects = <E>(self: Cause.Cause<E>): Option.Option<Cause.Cause<never>> =>\n  match(self, {\n    onEmpty: Option.none(),\n    onFail: () => Option.none(),\n    onDie: (defect) => Option.some(die(defect)),\n    onInterrupt: () => Option.none(),\n    onSequential: Option.mergeWith(sequential),\n    onParallel: Option.mergeWith(parallel)\n  })\n\n/** @internal */\nexport const keepDefectsAndElectFailures = <E>(self: Cause.Cause<E>): Option.Option<Cause.Cause<never>> =>\n  match(self, {\n    onEmpty: Option.none(),\n    onFail: (failure) => Option.some(die(failure)),\n    onDie: (defect) => Option.some(die(defect)),\n    onInterrupt: () => Option.none(),\n    onSequential: Option.mergeWith(sequential),\n    onParallel: Option.mergeWith(parallel)\n  })\n\n/** @internal */\nexport const linearize = <E>(self: Cause.Cause<E>): HashSet.HashSet<Cause.Cause<E>> =>\n  match(self, {\n    onEmpty: HashSet.empty(),\n    onFail: (error) => HashSet.make(fail(error)),\n    onDie: (defect) => HashSet.make(die(defect)),\n    onInterrupt: (fiberId) => HashSet.make(interrupt(fiberId)),\n    onSequential: (leftSet, rightSet) =>\n      HashSet.flatMap(leftSet, (leftCause) => HashSet.map(rightSet, (rightCause) => sequential(leftCause, rightCause))),\n    onParallel: (leftSet, rightSet) =>\n      HashSet.flatMap(leftSet, (leftCause) => HashSet.map(rightSet, (rightCause) => parallel(leftCause, rightCause)))\n  })\n\n/** @internal */\nexport const stripFailures = <E>(self: Cause.Cause<E>): Cause.Cause<never> =>\n  match(self, {\n    onEmpty: empty,\n    onFail: () => empty,\n    onDie: die,\n    onInterrupt: interrupt,\n    onSequential: sequential,\n    onParallel: parallel\n  })\n\n/** @internal */\nexport const electFailures = <E>(self: Cause.Cause<E>): Cause.Cause<never> =>\n  match(self, {\n    onEmpty: empty,\n    onFail: die,\n    onDie: die,\n    onInterrupt: interrupt,\n    onSequential: sequential,\n    onParallel: parallel\n  })\n\n/** @internal */\nexport const stripSomeDefects = dual<\n  (pf: (defect: unknown) => Option.Option<unknown>) => <E>(self: Cause.Cause<E>) => Option.Option<Cause.Cause<E>>,\n  <E>(self: Cause.Cause<E>, pf: (defect: unknown) => Option.Option<unknown>) => Option.Option<Cause.Cause<E>>\n>(\n  2,\n  <E>(self: Cause.Cause<E>, pf: (defect: unknown) => Option.Option<unknown>): Option.Option<Cause.Cause<E>> =>\n    match(self, {\n      onEmpty: Option.some<Cause.Cause<E>>(empty),\n      onFail: (error) => Option.some(fail(error)),\n      onDie: (defect) => {\n        const option = pf(defect)\n        return Option.isSome(option) ? Option.none() : Option.some(die(defect))\n      },\n      onInterrupt: (fiberId) => Option.some(interrupt(fiberId)),\n      onSequential: Option.mergeWith(sequential),\n      onParallel: Option.mergeWith(parallel)\n    })\n)\n\n// -----------------------------------------------------------------------------\n// Mapping\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const as = dual<\n  <E2>(error: E2) => <E>(self: Cause.Cause<E>) => Cause.Cause<E2>,\n  <E, E2>(self: Cause.Cause<E>, error: E2) => Cause.Cause<E2>\n>(2, (self, error) => map(self, () => error))\n\n/** @internal */\nexport const map = dual<\n  <E, E2>(f: (e: E) => E2) => (self: Cause.Cause<E>) => Cause.Cause<E2>,\n  <E, E2>(self: Cause.Cause<E>, f: (e: E) => E2) => Cause.Cause<E2>\n>(2, (self, f) => flatMap(self, (e) => fail(f(e))))\n\n// -----------------------------------------------------------------------------\n// Sequencing\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const flatMap = dual<\n  <E, E2>(f: (e: E) => Cause.Cause<E2>) => (self: Cause.Cause<E>) => Cause.Cause<E2>,\n  <E, E2>(self: Cause.Cause<E>, f: (e: E) => Cause.Cause<E2>) => Cause.Cause<E2>\n>(2, (self, f) =>\n  match(self, {\n    onEmpty: empty,\n    onFail: (error) => f(error),\n    onDie: (defect) => die(defect),\n    onInterrupt: (fiberId) => interrupt(fiberId),\n    onSequential: (left, right) => sequential(left, right),\n    onParallel: (left, right) => parallel(left, right)\n  }))\n\n/** @internal */\nexport const flatten = <E>(self: Cause.Cause<Cause.Cause<E>>): Cause.Cause<E> => flatMap(self, identity)\n\n/** @internal */\nexport const andThen: {\n  <E, E2>(f: (e: E) => Cause.Cause<E2>): (self: Cause.Cause<E>) => Cause.Cause<E2>\n  <E2>(f: Cause.Cause<E2>): <E>(self: Cause.Cause<E>) => Cause.Cause<E2>\n  <E, E2>(self: Cause.Cause<E>, f: (e: E) => Cause.Cause<E2>): Cause.Cause<E2>\n  <E, E2>(self: Cause.Cause<E>, f: Cause.Cause<E2>): Cause.Cause<E2>\n} = dual(\n  2,\n  <E, E2>(self: Cause.Cause<E>, f: ((e: E) => Cause.Cause<E2>) | Cause.Cause<E2>): Cause.Cause<E2> =>\n    isFunction(f) ? flatMap(self, f) : flatMap(self, () => f)\n)\n\n// -----------------------------------------------------------------------------\n// Equality\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const contains = dual<\n  <E2>(that: Cause.Cause<E2>) => <E>(self: Cause.Cause<E>) => boolean,\n  <E, E2>(self: Cause.Cause<E>, that: Cause.Cause<E2>) => boolean\n>(2, (self, that) => {\n  if (that._tag === OpCodes.OP_EMPTY || self === that) {\n    return true\n  }\n  return reduce(self, false, (accumulator, cause) => {\n    return Option.some(accumulator || causeEquals(cause, that))\n  })\n})\n\n/** @internal */\nconst causeEquals = (left: Cause.Cause<unknown>, right: Cause.Cause<unknown>): boolean => {\n  let leftStack: Chunk.Chunk<Cause.Cause<unknown>> = Chunk.of(left)\n  let rightStack: Chunk.Chunk<Cause.Cause<unknown>> = Chunk.of(right)\n  while (Chunk.isNonEmpty(leftStack) && Chunk.isNonEmpty(rightStack)) {\n    const [leftParallel, leftSequential] = pipe(\n      Chunk.headNonEmpty(leftStack),\n      reduce(\n        [HashSet.empty<unknown>(), Chunk.empty<Cause.Cause<unknown>>()] as const,\n        ([parallel, sequential], cause) => {\n          const [par, seq] = evaluateCause(cause)\n          return Option.some(\n            [\n              pipe(parallel, HashSet.union(par)),\n              pipe(sequential, Chunk.appendAll(seq))\n            ] as const\n          )\n        }\n      )\n    )\n    const [rightParallel, rightSequential] = pipe(\n      Chunk.headNonEmpty(rightStack),\n      reduce(\n        [HashSet.empty<unknown>(), Chunk.empty<Cause.Cause<unknown>>()] as const,\n        ([parallel, sequential], cause) => {\n          const [par, seq] = evaluateCause(cause)\n          return Option.some(\n            [\n              pipe(parallel, HashSet.union(par)),\n              pipe(sequential, Chunk.appendAll(seq))\n            ] as const\n          )\n        }\n      )\n    )\n    if (!Equal.equals(leftParallel, rightParallel)) {\n      return false\n    }\n    leftStack = leftSequential\n    rightStack = rightSequential\n  }\n  return true\n}\n\n// -----------------------------------------------------------------------------\n// Flattening\n// -----------------------------------------------------------------------------\n\n/**\n * Flattens a cause to a sequence of sets of causes, where each set represents\n * causes that fail in parallel and sequential sets represent causes that fail\n * after each other.\n *\n * @internal\n */\nconst flattenCause = (cause: Cause.Cause<unknown>): Chunk.Chunk<HashSet.HashSet<unknown>> => {\n  return flattenCauseLoop(Chunk.of(cause), Chunk.empty())\n}\n\n/** @internal */\nconst flattenCauseLoop = (\n  causes: Chunk.Chunk<Cause.Cause<unknown>>,\n  flattened: Chunk.Chunk<HashSet.HashSet<unknown>>\n): Chunk.Chunk<HashSet.HashSet<unknown>> => {\n  // eslint-disable-next-line no-constant-condition\n  while (1) {\n    const [parallel, sequential] = pipe(\n      causes,\n      Arr.reduce(\n        [HashSet.empty<unknown>(), Chunk.empty<Cause.Cause<unknown>>()] as const,\n        ([parallel, sequential], cause) => {\n          const [par, seq] = evaluateCause(cause)\n          return [\n            pipe(parallel, HashSet.union(par)),\n            pipe(sequential, Chunk.appendAll(seq))\n          ]\n        }\n      )\n    )\n    const updated = HashSet.size(parallel) > 0 ?\n      pipe(flattened, Chunk.prepend(parallel)) :\n      flattened\n    if (Chunk.isEmpty(sequential)) {\n      return Chunk.reverse(updated)\n    }\n    causes = sequential\n    flattened = updated\n  }\n  throw new Error(getBugErrorMessage(\"Cause.flattenCauseLoop\"))\n}\n\n// -----------------------------------------------------------------------------\n// Finding\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const find = dual<\n  <E, Z>(pf: (cause: Cause.Cause<E>) => Option.Option<Z>) => (self: Cause.Cause<E>) => Option.Option<Z>,\n  <E, Z>(self: Cause.Cause<E>, pf: (cause: Cause.Cause<E>) => Option.Option<Z>) => Option.Option<Z>\n>(2, <E, Z>(self: Cause.Cause<E>, pf: (cause: Cause.Cause<E>) => Option.Option<Z>) => {\n  const stack: Array<Cause.Cause<E>> = [self]\n  while (stack.length > 0) {\n    const item = stack.pop()!\n    const option = pf(item)\n    switch (option._tag) {\n      case \"None\": {\n        switch (item._tag) {\n          case OpCodes.OP_SEQUENTIAL:\n          case OpCodes.OP_PARALLEL: {\n            stack.push(item.right)\n            stack.push(item.left)\n            break\n          }\n        }\n        break\n      }\n      case \"Some\": {\n        return option\n      }\n    }\n  }\n  return Option.none()\n})\n\n// -----------------------------------------------------------------------------\n// Filtering\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const filter: {\n  <E, EB extends E>(\n    refinement: Refinement<Cause.Cause<NoInfer<E>>, Cause.Cause<EB>>\n  ): (self: Cause.Cause<E>) => Cause.Cause<EB>\n  <E>(predicate: Predicate<Cause.Cause<NoInfer<E>>>): (self: Cause.Cause<E>) => Cause.Cause<E>\n  <E, EB extends E>(self: Cause.Cause<E>, refinement: Refinement<Cause.Cause<E>, Cause.Cause<EB>>): Cause.Cause<EB>\n  <E>(self: Cause.Cause<E>, predicate: Predicate<Cause.Cause<E>>): Cause.Cause<E>\n} = dual(\n  2,\n  <E>(self: Cause.Cause<E>, predicate: Predicate<Cause.Cause<E>>): Cause.Cause<E> =>\n    reduceWithContext(self, void 0, FilterCauseReducer(predicate))\n)\n\n// -----------------------------------------------------------------------------\n// Evaluation\n// -----------------------------------------------------------------------------\n\n/**\n * Takes one step in evaluating a cause, returning a set of causes that fail\n * in parallel and a list of causes that fail sequentially after those causes.\n *\n * @internal\n */\nconst evaluateCause = (\n  self: Cause.Cause<unknown>\n): [HashSet.HashSet<unknown>, Chunk.Chunk<Cause.Cause<unknown>>] => {\n  let cause: Cause.Cause<unknown> | undefined = self\n  const stack: Array<Cause.Cause<unknown>> = []\n  let _parallel = HashSet.empty<unknown>()\n  let _sequential = Chunk.empty<Cause.Cause<unknown>>()\n  while (cause !== undefined) {\n    switch (cause._tag) {\n      case OpCodes.OP_EMPTY: {\n        if (stack.length === 0) {\n          return [_parallel, _sequential]\n        }\n        cause = stack.pop()\n        break\n      }\n      case OpCodes.OP_FAIL: {\n        _parallel = HashSet.add(_parallel, Chunk.make(cause._tag, cause.error))\n        if (stack.length === 0) {\n          return [_parallel, _sequential]\n        }\n        cause = stack.pop()\n        break\n      }\n      case OpCodes.OP_DIE: {\n        _parallel = HashSet.add(_parallel, Chunk.make(cause._tag, cause.defect))\n        if (stack.length === 0) {\n          return [_parallel, _sequential]\n        }\n        cause = stack.pop()\n        break\n      }\n      case OpCodes.OP_INTERRUPT: {\n        _parallel = HashSet.add(_parallel, Chunk.make(cause._tag, cause.fiberId as unknown))\n        if (stack.length === 0) {\n          return [_parallel, _sequential]\n        }\n        cause = stack.pop()\n        break\n      }\n      case OpCodes.OP_SEQUENTIAL: {\n        switch (cause.left._tag) {\n          case OpCodes.OP_EMPTY: {\n            cause = cause.right\n            break\n          }\n          case OpCodes.OP_SEQUENTIAL: {\n            cause = sequential(cause.left.left, sequential(cause.left.right, cause.right))\n            break\n          }\n          case OpCodes.OP_PARALLEL: {\n            cause = parallel(\n              sequential(cause.left.left, cause.right),\n              sequential(cause.left.right, cause.right)\n            )\n            break\n          }\n          default: {\n            _sequential = Chunk.prepend(_sequential, cause.right)\n            cause = cause.left\n            break\n          }\n        }\n        break\n      }\n      case OpCodes.OP_PARALLEL: {\n        stack.push(cause.right)\n        cause = cause.left\n        break\n      }\n    }\n  }\n  throw new Error(getBugErrorMessage(\"Cause.evaluateCauseLoop\"))\n}\n\n// -----------------------------------------------------------------------------\n// Reducing\n// -----------------------------------------------------------------------------\n\n/** @internal */\nconst SizeCauseReducer: Cause.CauseReducer<unknown, unknown, number> = {\n  emptyCase: () => 0,\n  failCase: () => 1,\n  dieCase: () => 1,\n  interruptCase: () => 1,\n  sequentialCase: (_, left, right) => left + right,\n  parallelCase: (_, left, right) => left + right\n}\n\n/** @internal */\nconst IsInterruptedOnlyCauseReducer: Cause.CauseReducer<unknown, unknown, boolean> = {\n  emptyCase: constTrue,\n  failCase: constFalse,\n  dieCase: constFalse,\n  interruptCase: constTrue,\n  sequentialCase: (_, left, right) => left && right,\n  parallelCase: (_, left, right) => left && right\n}\n\n/** @internal */\nconst FilterCauseReducer = <E>(\n  predicate: Predicate<Cause.Cause<E>>\n): Cause.CauseReducer<unknown, E, Cause.Cause<E>> => ({\n  emptyCase: () => empty,\n  failCase: (_, error) => fail(error),\n  dieCase: (_, defect) => die(defect),\n  interruptCase: (_, fiberId) => interrupt(fiberId),\n  sequentialCase: (_, left, right) => {\n    if (predicate(left)) {\n      if (predicate(right)) {\n        return sequential(left, right)\n      }\n      return left\n    }\n    if (predicate(right)) {\n      return right\n    }\n    return empty\n  },\n  parallelCase: (_, left, right) => {\n    if (predicate(left)) {\n      if (predicate(right)) {\n        return parallel(left, right)\n      }\n      return left\n    }\n    if (predicate(right)) {\n      return right\n    }\n    return empty\n  }\n})\n\n/** @internal */\ntype CauseCase = SequentialCase | ParallelCase\n\nconst OP_SEQUENTIAL_CASE = \"SequentialCase\"\n\nconst OP_PARALLEL_CASE = \"ParallelCase\"\n\n/** @internal */\ninterface SequentialCase {\n  readonly _tag: typeof OP_SEQUENTIAL_CASE\n}\n\n/** @internal */\ninterface ParallelCase {\n  readonly _tag: typeof OP_PARALLEL_CASE\n}\n\n/** @internal */\nexport const match = dual<\n  <Z, E>(\n    options: {\n      readonly onEmpty: Z\n      readonly onFail: (error: E) => Z\n      readonly onDie: (defect: unknown) => Z\n      readonly onInterrupt: (fiberId: FiberId.FiberId) => Z\n      readonly onSequential: (left: Z, right: Z) => Z\n      readonly onParallel: (left: Z, right: Z) => Z\n    }\n  ) => (self: Cause.Cause<E>) => Z,\n  <Z, E>(\n    self: Cause.Cause<E>,\n    options: {\n      readonly onEmpty: Z\n      readonly onFail: (error: E) => Z\n      readonly onDie: (defect: unknown) => Z\n      readonly onInterrupt: (fiberId: FiberId.FiberId) => Z\n      readonly onSequential: (left: Z, right: Z) => Z\n      readonly onParallel: (left: Z, right: Z) => Z\n    }\n  ) => Z\n>(2, (self, { onDie, onEmpty, onFail, onInterrupt, onParallel, onSequential }) => {\n  return reduceWithContext(self, void 0, {\n    emptyCase: () => onEmpty,\n    failCase: (_, error) => onFail(error),\n    dieCase: (_, defect) => onDie(defect),\n    interruptCase: (_, fiberId) => onInterrupt(fiberId),\n    sequentialCase: (_, left, right) => onSequential(left, right),\n    parallelCase: (_, left, right) => onParallel(left, right)\n  })\n})\n\n/** @internal */\nexport const reduce = dual<\n  <Z, E>(zero: Z, pf: (accumulator: Z, cause: Cause.Cause<E>) => Option.Option<Z>) => (self: Cause.Cause<E>) => Z,\n  <Z, E>(self: Cause.Cause<E>, zero: Z, pf: (accumulator: Z, cause: Cause.Cause<E>) => Option.Option<Z>) => Z\n>(3, <Z, E>(self: Cause.Cause<E>, zero: Z, pf: (accumulator: Z, cause: Cause.Cause<E>) => Option.Option<Z>) => {\n  let accumulator: Z = zero\n  let cause: Cause.Cause<E> | undefined = self\n  const causes: Array<Cause.Cause<E>> = []\n  while (cause !== undefined) {\n    const option = pf(accumulator, cause)\n    accumulator = Option.isSome(option) ? option.value : accumulator\n    switch (cause._tag) {\n      case OpCodes.OP_SEQUENTIAL: {\n        causes.push(cause.right)\n        cause = cause.left\n        break\n      }\n      case OpCodes.OP_PARALLEL: {\n        causes.push(cause.right)\n        cause = cause.left\n        break\n      }\n      default: {\n        cause = undefined\n        break\n      }\n    }\n    if (cause === undefined && causes.length > 0) {\n      cause = causes.pop()!\n    }\n  }\n  return accumulator\n})\n\n/** @internal */\nexport const reduceWithContext = dual<\n  <C, E, Z>(context: C, reducer: Cause.CauseReducer<C, E, Z>) => (self: Cause.Cause<E>) => Z,\n  <C, E, Z>(self: Cause.Cause<E>, context: C, reducer: Cause.CauseReducer<C, E, Z>) => Z\n>(3, <C, E, Z>(self: Cause.Cause<E>, context: C, reducer: Cause.CauseReducer<C, E, Z>) => {\n  const input: Array<Cause.Cause<E>> = [self]\n  const output: Array<Either.Either<Z, CauseCase>> = []\n  while (input.length > 0) {\n    const cause = input.pop()!\n    switch (cause._tag) {\n      case OpCodes.OP_EMPTY: {\n        output.push(Either.right(reducer.emptyCase(context)))\n        break\n      }\n      case OpCodes.OP_FAIL: {\n        output.push(Either.right(reducer.failCase(context, cause.error)))\n        break\n      }\n      case OpCodes.OP_DIE: {\n        output.push(Either.right(reducer.dieCase(context, cause.defect)))\n        break\n      }\n      case OpCodes.OP_INTERRUPT: {\n        output.push(Either.right(reducer.interruptCase(context, cause.fiberId)))\n        break\n      }\n      case OpCodes.OP_SEQUENTIAL: {\n        input.push(cause.right)\n        input.push(cause.left)\n        output.push(Either.left({ _tag: OP_SEQUENTIAL_CASE }))\n        break\n      }\n      case OpCodes.OP_PARALLEL: {\n        input.push(cause.right)\n        input.push(cause.left)\n        output.push(Either.left({ _tag: OP_PARALLEL_CASE }))\n        break\n      }\n    }\n  }\n  const accumulator: Array<Z> = []\n  while (output.length > 0) {\n    const either = output.pop()!\n    switch (either._tag) {\n      case \"Left\": {\n        switch (either.left._tag) {\n          case OP_SEQUENTIAL_CASE: {\n            const left = accumulator.pop()!\n            const right = accumulator.pop()!\n            const value = reducer.sequentialCase(context, left, right)\n            accumulator.push(value)\n            break\n          }\n          case OP_PARALLEL_CASE: {\n            const left = accumulator.pop()!\n            const right = accumulator.pop()!\n            const value = reducer.parallelCase(context, left, right)\n            accumulator.push(value)\n            break\n          }\n        }\n        break\n      }\n      case \"Right\": {\n        accumulator.push(either.right)\n        break\n      }\n    }\n  }\n  if (accumulator.length === 0) {\n    throw new Error(\n      \"BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues\"\n    )\n  }\n  return accumulator.pop()!\n})\n\n// -----------------------------------------------------------------------------\n// Pretty Printing\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const pretty = <E>(cause: Cause.Cause<E>, options?: {\n  readonly renderErrorCause?: boolean | undefined\n}): string => {\n  if (isInterruptedOnly(cause)) {\n    return \"All fibers interrupted without errors.\"\n  }\n  return prettyErrors<E>(cause).map(function(e) {\n    if (options?.renderErrorCause !== true || e.cause === undefined) {\n      return e.stack\n    }\n    return `${e.stack} {\\n${renderErrorCause(e.cause as Cause.PrettyError, \"  \")}\\n}`\n  }).join(\"\\n\")\n}\n\nconst renderErrorCause = (cause: Cause.PrettyError, prefix: string) => {\n  const lines = cause.stack!.split(\"\\n\")\n  let stack = `${prefix}[cause]: ${lines[0]}`\n  for (let i = 1, len = lines.length; i < len; i++) {\n    stack += `\\n${prefix}${lines[i]}`\n  }\n  if (cause.cause) {\n    stack += ` {\\n${renderErrorCause(cause.cause as Cause.PrettyError, `${prefix}  `)}\\n${prefix}}`\n  }\n  return stack\n}\n\n/** @internal */\nexport const makePrettyError = (originalError: unknown): Cause.PrettyError => {\n  const originalErrorIsObject = typeof originalError === \"object\" && originalError !== null\n  const prevLimit = Error.stackTraceLimit\n  Error.stackTraceLimit = 1\n  const error = new Error(\n    prettyErrorMessage(originalError),\n    originalErrorIsObject && \"cause\" in originalError && typeof originalError.cause !== \"undefined\"\n      ? { cause: makePrettyError(originalError.cause) }\n      : undefined\n  ) as Types.Mutable<Cause.PrettyError>\n  Error.stackTraceLimit = prevLimit\n  if (error.message === \"\") {\n    error.message = \"An error has occurred\"\n  }\n  Error.stackTraceLimit = prevLimit\n  error.name = originalError instanceof Error ? originalError.name : \"Error\"\n  if (originalErrorIsObject) {\n    if (spanSymbol in originalError) {\n      error.span = originalError[spanSymbol] as Span\n    }\n    Object.keys(originalError).forEach((key) => {\n      if (!(key in error)) {\n        // @ts-expect-error\n        error[key] = originalError[key]\n      }\n    })\n  }\n  error.stack = prettyErrorStack(\n    `${error.name}: ${error.message}`,\n    originalError instanceof Error && originalError.stack\n      ? originalError.stack\n      : \"\",\n    error.span\n  )\n  return error\n}\n\n/**\n * A utility function for generating human-readable error messages from a generic error of type `unknown`.\n *\n * Rules:\n *\n * 1) If the input `u` is already a string, it's considered a message.\n * 2) If `u` is an Error instance with a message defined, it uses the message.\n * 3) If `u` has a user-defined `toString()` method, it uses that method.\n * 4) Otherwise, it uses `Inspectable.stringifyCircular` to produce a string representation and uses it as the error message,\n *   with \"Error\" added as a prefix.\n *\n * @internal\n */\nexport const prettyErrorMessage = (u: unknown): string => {\n  // 1)\n  if (typeof u === \"string\") {\n    return u\n  }\n  // 2)\n  if (typeof u === \"object\" && u !== null && u instanceof Error) {\n    return u.message\n  }\n  // 3)\n  try {\n    if (\n      hasProperty(u, \"toString\") &&\n      isFunction(u[\"toString\"]) &&\n      u[\"toString\"] !== Object.prototype.toString &&\n      u[\"toString\"] !== globalThis.Array.prototype.toString\n    ) {\n      return u[\"toString\"]()\n    }\n  } catch {\n    // something's off, rollback to json\n  }\n  // 4)\n  return stringifyCircular(u)\n}\n\nconst locationRegex = /\\((.*)\\)/g\n\n/** @internal */\nexport const spanToTrace = globalValue(\"effect/Tracer/spanToTrace\", () => new WeakMap())\n\nconst prettyErrorStack = (message: string, stack: string, span?: Span | undefined): string => {\n  const out: Array<string> = [message]\n  const lines = stack.startsWith(message) ? stack.slice(message.length).split(\"\\n\") : stack.split(\"\\n\")\n\n  for (let i = 1; i < lines.length; i++) {\n    if (lines[i].includes(\" at new BaseEffectError\") || lines[i].includes(\" at new YieldableError\")) {\n      i++\n      continue\n    }\n    if (lines[i].includes(\"Generator.next\")) {\n      break\n    }\n    if (lines[i].includes(\"effect_internal_function\")) {\n      break\n    }\n    out.push(\n      lines[i]\n        .replace(/at .*effect_instruction_i.*\\((.*)\\)/, \"at $1\")\n        .replace(/EffectPrimitive\\.\\w+/, \"<anonymous>\")\n    )\n  }\n\n  if (span) {\n    let current: Span | AnySpan | undefined = span\n    let i = 0\n    while (current && current._tag === \"Span\" && i < 10) {\n      const stackFn = spanToTrace.get(current)\n      if (typeof stackFn === \"function\") {\n        const stack = stackFn()\n        if (typeof stack === \"string\") {\n          const locationMatchAll = stack.matchAll(locationRegex)\n          let match = false\n          for (const [, location] of locationMatchAll) {\n            match = true\n            out.push(`    at ${current.name} (${location})`)\n          }\n          if (!match) {\n            out.push(`    at ${current.name} (${stack.replace(/^at /, \"\")})`)\n          }\n        } else {\n          out.push(`    at ${current.name}`)\n        }\n      } else {\n        out.push(`    at ${current.name}`)\n      }\n      current = Option.getOrUndefined(current.parent)\n      i++\n    }\n  }\n\n  return out.join(\"\\n\")\n}\n\n/** @internal */\nexport const spanSymbol = Symbol.for(\"effect/SpanAnnotation\")\n\n/** @internal */\nexport const prettyErrors = <E>(cause: Cause.Cause<E>): Array<Cause.PrettyError> =>\n  reduceWithContext(cause, void 0, {\n    emptyCase: (): Array<Cause.PrettyError> => [],\n    dieCase: (_, unknownError) => {\n      return [makePrettyError(unknownError)]\n    },\n    failCase: (_, error) => {\n      return [makePrettyError(error)]\n    },\n    interruptCase: () => [],\n    parallelCase: (_, l, r) => [...l, ...r],\n    sequentialCase: (_, l, r) => [...l, ...r]\n  })\n"
  },
  {
    "path": "packages/effect/src/internal/channel/channelExecutor.ts",
    "content": "import * as Cause from \"../../Cause.js\"\nimport type * as Channel from \"../../Channel.js\"\nimport type * as ChildExecutorDecision from \"../../ChildExecutorDecision.js\"\nimport type * as Context from \"../../Context.js\"\nimport * as Deferred from \"../../Deferred.js\"\nimport * as Effect from \"../../Effect.js\"\nimport * as ExecutionStrategy from \"../../ExecutionStrategy.js\"\nimport * as Exit from \"../../Exit.js\"\nimport * as Fiber from \"../../Fiber.js\"\nimport * as FiberId from \"../../FiberId.js\"\nimport { dual, identity, pipe } from \"../../Function.js\"\nimport * as HashSet from \"../../HashSet.js\"\nimport * as Option from \"../../Option.js\"\nimport * as Scope from \"../../Scope.js\"\nimport type * as UpstreamPullStrategy from \"../../UpstreamPullStrategy.js\"\nimport * as core from \"../core-stream.js\"\nimport * as ChannelOpCodes from \"../opCodes/channel.js\"\nimport * as ChildExecutorDecisionOpCodes from \"../opCodes/channelChildExecutorDecision.js\"\nimport * as ChannelStateOpCodes from \"../opCodes/channelState.js\"\nimport * as UpstreamPullStrategyOpCodes from \"../opCodes/channelUpstreamPullStrategy.js\"\nimport * as ContinuationOpCodes from \"../opCodes/continuation.js\"\nimport * as ChannelState from \"./channelState.js\"\nimport * as Continuation from \"./continuation.js\"\nimport * as Subexecutor from \"./subexecutor.js\"\nimport * as upstreamPullRequest from \"./upstreamPullRequest.js\"\n\nexport type ErasedChannel<R> = Channel.Channel<unknown, unknown, unknown, unknown, unknown, unknown, R>\n\n/** @internal */\nexport type ErasedExecutor<R> = ChannelExecutor<unknown, unknown, unknown, unknown, unknown, unknown, R>\n\n/** @internal */\nexport type ErasedContinuation<R> = Continuation.Continuation<\n  R,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown\n>\n\n/** @internal */\nexport type ErasedFinalizer<R> = (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<unknown, never, R>\n\n/** @internal */\nexport class ChannelExecutor<\n  out OutElem,\n  in InElem = unknown,\n  out OutErr = never,\n  in InErr = unknown,\n  out OutDone = void,\n  in InDone = unknown,\n  in out Env = never\n> {\n  private _activeSubexecutor: Subexecutor.Subexecutor<Env> | undefined = undefined\n\n  private _cancelled: Exit.Exit<OutErr, OutDone> | undefined = undefined\n\n  private _closeLastSubstream: Effect.Effect<unknown, never, Env> | undefined = undefined\n\n  private _currentChannel: core.Primitive | undefined\n\n  private _done: Exit.Exit<unknown, unknown> | undefined = undefined\n\n  private _doneStack: Array<ErasedContinuation<Env>> = []\n\n  private _emitted: unknown | undefined = undefined\n\n  private _executeCloseLastSubstream: (\n    effect: Effect.Effect<unknown, never, Env>\n  ) => Effect.Effect<unknown, never, Env>\n\n  private _input: ErasedExecutor<Env> | undefined = undefined\n\n  private _inProgressFinalizer: Effect.Effect<unknown, never, Env> | undefined = undefined\n\n  private _providedEnv: Context.Context<unknown> | undefined\n\n  constructor(\n    initialChannel: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    providedEnv: Context.Context<unknown> | undefined,\n    executeCloseLastSubstream: (effect: Effect.Effect<unknown, never, Env>) => Effect.Effect<unknown, never, Env>\n  ) {\n    this._currentChannel = initialChannel as core.Primitive\n    this._executeCloseLastSubstream = executeCloseLastSubstream\n    this._providedEnv = providedEnv\n  }\n\n  run(): ChannelState.ChannelState<unknown, Env> {\n    let result: ChannelState.ChannelState<unknown, Env> | undefined = undefined\n    while (result === undefined) {\n      if (this._cancelled !== undefined) {\n        result = this.processCancellation()\n      } else if (this._activeSubexecutor !== undefined) {\n        result = this.runSubexecutor()\n      } else {\n        try {\n          if (this._currentChannel === undefined) {\n            result = ChannelState.Done()\n          } else {\n            if (Effect.isEffect(this._currentChannel)) {\n              this._currentChannel = core.fromEffect(this._currentChannel) as core.Primitive\n            }\n            switch (this._currentChannel._tag) {\n              case ChannelOpCodes.OP_BRACKET_OUT: {\n                result = this.runBracketOut(this._currentChannel)\n                break\n              }\n\n              case ChannelOpCodes.OP_BRIDGE: {\n                const bridgeInput = this._currentChannel.input\n\n                // PipeTo(left, Bridge(queue, channel))\n                // In a fiber: repeatedly run left and push its outputs to the queue\n                // Add a finalizer to interrupt the fiber and close the executor\n                this._currentChannel = this._currentChannel.channel as core.Primitive\n\n                if (this._input !== undefined) {\n                  const inputExecutor = this._input\n                  this._input = undefined\n\n                  const drainer = (): Effect.Effect<unknown, never, Env> =>\n                    Effect.flatMap(bridgeInput.awaitRead(), () =>\n                      Effect.suspend(() => {\n                        const state = inputExecutor.run() as ChannelState.Primitive\n                        switch (state._tag) {\n                          case ChannelStateOpCodes.OP_DONE: {\n                            return Exit.match(inputExecutor.getDone(), {\n                              onFailure: (cause) => bridgeInput.error(cause),\n                              onSuccess: (value) => bridgeInput.done(value)\n                            })\n                          }\n                          case ChannelStateOpCodes.OP_EMIT: {\n                            return Effect.flatMap(\n                              bridgeInput.emit(inputExecutor.getEmit()),\n                              () => drainer()\n                            )\n                          }\n                          case ChannelStateOpCodes.OP_FROM_EFFECT: {\n                            return Effect.matchCauseEffect(state.effect, {\n                              onFailure: (cause) => bridgeInput.error(cause),\n                              onSuccess: () => drainer()\n                            })\n                          }\n                          case ChannelStateOpCodes.OP_READ: {\n                            return readUpstream(\n                              state,\n                              () => drainer(),\n                              (cause) => bridgeInput.error(cause)\n                            )\n                          }\n                        }\n                      })) as Effect.Effect<unknown, never, Env>\n\n                  result = ChannelState.fromEffect(\n                    Effect.flatMap(\n                      Effect.forkDaemon(Effect.interruptible(drainer())),\n                      (fiber) =>\n                        Effect.sync(() =>\n                          this.addFinalizer((exit) =>\n                            Effect.flatMap(Fiber.interrupt(fiber), () =>\n                              Effect.suspend(() => {\n                                const effect = this.restorePipe(exit, inputExecutor)\n                                return effect !== undefined ? effect : Effect.void\n                              }))\n                          )\n                        )\n                    )\n                  )\n                }\n\n                break\n              }\n\n              case ChannelOpCodes.OP_CONCAT_ALL: {\n                const executor: ErasedExecutor<Env> = new ChannelExecutor(\n                  this._currentChannel.value() as Channel.Channel<\n                    never,\n                    unknown,\n                    never,\n                    unknown,\n                    never,\n                    unknown,\n                    Env\n                  >,\n                  this._providedEnv,\n                  (effect) =>\n                    Effect.sync(() => {\n                      const prevLastClose = this._closeLastSubstream === undefined\n                        ? Effect.void\n                        : this._closeLastSubstream\n                      this._closeLastSubstream = pipe(prevLastClose, Effect.zipRight(effect))\n                    })\n                )\n                executor._input = this._input\n\n                const channel = this._currentChannel\n                this._activeSubexecutor = new Subexecutor.PullFromUpstream(\n                  executor,\n                  (value) => channel.k(value),\n                  undefined,\n                  [],\n                  (x, y) => channel.combineInners(x, y),\n                  (x, y) => channel.combineAll(x, y),\n                  (request) => channel.onPull(request),\n                  (value) => channel.onEmit(value)\n                )\n\n                this._closeLastSubstream = undefined\n                this._currentChannel = undefined\n\n                break\n              }\n\n              case ChannelOpCodes.OP_EMIT: {\n                this._emitted = this._currentChannel.out\n                this._currentChannel = (this._activeSubexecutor !== undefined ?\n                  undefined :\n                  core.void) as core.Primitive | undefined\n                result = ChannelState.Emit()\n                break\n              }\n\n              case ChannelOpCodes.OP_ENSURING: {\n                this.runEnsuring(this._currentChannel)\n                break\n              }\n\n              case ChannelOpCodes.OP_FAIL: {\n                result = this.doneHalt(this._currentChannel.error())\n                break\n              }\n\n              case ChannelOpCodes.OP_FOLD: {\n                this._doneStack.push(this._currentChannel.k as ErasedContinuation<Env>)\n                this._currentChannel = this._currentChannel.channel as core.Primitive\n                break\n              }\n\n              case ChannelOpCodes.OP_FROM_EFFECT: {\n                const effect = this._providedEnv === undefined ?\n                  this._currentChannel.effect() :\n                  pipe(\n                    this._currentChannel.effect(),\n                    Effect.provide(this._providedEnv)\n                  )\n\n                result = ChannelState.fromEffect(\n                  Effect.matchCauseEffect(effect, {\n                    onFailure: (cause) => {\n                      const state = this.doneHalt(cause)\n                      return state !== undefined && ChannelState.isFromEffect(state) ?\n                        state.effect :\n                        Effect.void\n                    },\n                    onSuccess: (value) => {\n                      const state = this.doneSucceed(value)\n                      return state !== undefined && ChannelState.isFromEffect(state) ?\n                        state.effect :\n                        Effect.void\n                    }\n                  })\n                ) as ChannelState.ChannelState<unknown, Env> | undefined\n\n                break\n              }\n\n              case ChannelOpCodes.OP_PIPE_TO: {\n                const previousInput = this._input\n\n                const leftExec: ErasedExecutor<Env> = new ChannelExecutor(\n                  this._currentChannel.left() as Channel.Channel<never, unknown, never, unknown, never, unknown, Env>,\n                  this._providedEnv,\n                  (effect) => this._executeCloseLastSubstream(effect)\n                )\n                leftExec._input = previousInput\n                this._input = leftExec\n\n                this.addFinalizer((exit) => {\n                  const effect = this.restorePipe(exit, previousInput)\n                  return effect !== undefined ? effect : Effect.void\n                })\n\n                this._currentChannel = this._currentChannel.right() as core.Primitive\n\n                break\n              }\n\n              case ChannelOpCodes.OP_PROVIDE: {\n                const previousEnv = this._providedEnv\n                this._providedEnv = this._currentChannel.context()\n                this._currentChannel = this._currentChannel.inner as core.Primitive\n                this.addFinalizer(() =>\n                  Effect.sync(() => {\n                    this._providedEnv = previousEnv\n                  })\n                )\n                break\n              }\n\n              case ChannelOpCodes.OP_READ: {\n                const read = this._currentChannel\n                result = ChannelState.Read(\n                  this._input!,\n                  identity,\n                  (emitted) => {\n                    try {\n                      this._currentChannel = read.more(emitted) as core.Primitive\n                    } catch (error) {\n                      this._currentChannel = read.done.onExit(Exit.die(error)) as core.Primitive\n                    }\n                    return undefined\n                  },\n                  (exit) => {\n                    const onExit = (exit: Exit.Exit<unknown, unknown>): core.Primitive => {\n                      return read.done.onExit(exit) as core.Primitive\n                    }\n                    this._currentChannel = onExit(exit)\n                    return undefined\n                  }\n                )\n                break\n              }\n\n              case ChannelOpCodes.OP_SUCCEED: {\n                result = this.doneSucceed(this._currentChannel.evaluate())\n                break\n              }\n\n              case ChannelOpCodes.OP_SUCCEED_NOW: {\n                result = this.doneSucceed(this._currentChannel.terminal)\n                break\n              }\n\n              case ChannelOpCodes.OP_SUSPEND: {\n                this._currentChannel = this._currentChannel.channel() as core.Primitive\n                break\n              }\n            }\n          }\n        } catch (error) {\n          this._currentChannel = core.failCause(Cause.die(error)) as core.Primitive\n        }\n      }\n    }\n    return result\n  }\n\n  getDone(): Exit.Exit<OutDone, OutErr> {\n    return this._done as Exit.Exit<OutDone, OutErr>\n  }\n\n  getEmit(): OutElem {\n    return this._emitted as OutElem\n  }\n\n  cancelWith(exit: Exit.Exit<OutErr, OutDone>): void {\n    this._cancelled = exit\n  }\n\n  clearInProgressFinalizer(): void {\n    this._inProgressFinalizer = undefined\n  }\n\n  storeInProgressFinalizer(finalizer: Effect.Effect<unknown, never, Env> | undefined): void {\n    this._inProgressFinalizer = finalizer\n  }\n\n  popAllFinalizers(exit: Exit.Exit<unknown, unknown>): Effect.Effect<unknown, never, Env> {\n    const finalizers: Array<ErasedFinalizer<Env>> = []\n    let next = this._doneStack.pop() as Continuation.Primitive | undefined\n    while (next) {\n      if (next._tag === \"ContinuationFinalizer\") {\n        finalizers.push(next.finalizer as ErasedFinalizer<Env>)\n      }\n      next = this._doneStack.pop() as Continuation.Primitive | undefined\n    }\n    const effect = (finalizers.length === 0 ? Effect.void : runFinalizers(finalizers, exit)) as Effect.Effect<\n      unknown,\n      never,\n      Env\n    >\n    this.storeInProgressFinalizer(effect)\n    return effect\n  }\n\n  popNextFinalizers(): Array<Continuation.ContinuationFinalizer<Env, unknown, unknown>> {\n    const builder: Array<Continuation.ContinuationFinalizer<Env, unknown, unknown>> = []\n    while (this._doneStack.length !== 0) {\n      const cont = this._doneStack[this._doneStack.length - 1] as Continuation.Primitive\n      if (cont._tag === ContinuationOpCodes.OP_CONTINUATION_K) {\n        return builder\n      }\n      builder.push(cont as Continuation.ContinuationFinalizer<Env, unknown, unknown>)\n      this._doneStack.pop()\n    }\n    return builder\n  }\n\n  restorePipe(\n    exit: Exit.Exit<unknown, unknown>,\n    prev: ErasedExecutor<Env> | undefined\n  ): Effect.Effect<unknown, never, Env> | undefined {\n    const currInput = this._input\n    this._input = prev\n    if (currInput !== undefined) {\n      const effect = currInput.close(exit)\n      return effect\n    }\n    return Effect.void\n  }\n\n  close(exit: Exit.Exit<unknown, unknown>): Effect.Effect<unknown, never, Env> | undefined {\n    let runInProgressFinalizers: Effect.Effect<unknown, never, Env> | undefined = undefined\n    const finalizer = this._inProgressFinalizer\n    if (finalizer !== undefined) {\n      runInProgressFinalizers = pipe(\n        finalizer,\n        Effect.ensuring(Effect.sync(() => this.clearInProgressFinalizer()))\n      )\n    }\n\n    let closeSelf: Effect.Effect<unknown, never, Env> | undefined = undefined\n    const selfFinalizers = this.popAllFinalizers(exit)\n    if (selfFinalizers !== undefined) {\n      closeSelf = pipe(\n        selfFinalizers,\n        Effect.ensuring(Effect.sync(() => this.clearInProgressFinalizer()))\n      )\n    }\n\n    const closeSubexecutors = this._activeSubexecutor === undefined ?\n      undefined :\n      this._activeSubexecutor.close(exit)\n\n    if (\n      closeSubexecutors === undefined &&\n      runInProgressFinalizers === undefined &&\n      closeSelf === undefined\n    ) {\n      return undefined\n    }\n\n    return pipe(\n      Effect.exit(ifNotNull(closeSubexecutors)),\n      Effect.zip(Effect.exit(ifNotNull(runInProgressFinalizers))),\n      Effect.zip(Effect.exit(ifNotNull(closeSelf))),\n      Effect.map(([[exit1, exit2], exit3]) => pipe(exit1, Exit.zipRight(exit2), Exit.zipRight(exit3))),\n      Effect.uninterruptible,\n      // TODO: remove\n      Effect.flatMap((exit) => Effect.suspend(() => exit))\n    )\n  }\n\n  doneSucceed(value: unknown): ChannelState.ChannelState<unknown, Env> | undefined {\n    if (this._doneStack.length === 0) {\n      this._done = Exit.succeed(value)\n      this._currentChannel = undefined\n      return ChannelState.Done()\n    }\n\n    const head = this._doneStack[this._doneStack.length - 1] as Continuation.Primitive\n    if (head._tag === ContinuationOpCodes.OP_CONTINUATION_K) {\n      this._doneStack.pop()\n      this._currentChannel = head.onSuccess(value) as core.Primitive\n      return undefined\n    }\n\n    const finalizers = this.popNextFinalizers()\n    if (this._doneStack.length === 0) {\n      this._doneStack = finalizers.reverse()\n      this._done = Exit.succeed(value)\n      this._currentChannel = undefined\n      return ChannelState.Done()\n    }\n\n    const finalizerEffect = runFinalizers(finalizers.map((f) => f.finalizer), Exit.succeed(value))!\n    this.storeInProgressFinalizer(finalizerEffect)\n\n    const effect = pipe(\n      finalizerEffect,\n      Effect.ensuring(Effect.sync(() => this.clearInProgressFinalizer())),\n      Effect.uninterruptible,\n      Effect.flatMap(() => Effect.sync(() => this.doneSucceed(value)))\n    )\n\n    return ChannelState.fromEffect(effect)\n  }\n\n  doneHalt(cause: Cause.Cause<unknown>): ChannelState.ChannelState<unknown, Env> | undefined {\n    if (this._doneStack.length === 0) {\n      this._done = Exit.failCause(cause)\n      this._currentChannel = undefined\n      return ChannelState.Done()\n    }\n\n    const head = this._doneStack[this._doneStack.length - 1] as Continuation.Primitive\n    if (head._tag === ContinuationOpCodes.OP_CONTINUATION_K) {\n      this._doneStack.pop()\n      try {\n        this._currentChannel = head.onHalt(cause) as core.Primitive\n      } catch (error) {\n        this._currentChannel = core.failCause(Cause.die(error)) as core.Primitive\n      }\n      return undefined\n    }\n\n    const finalizers = this.popNextFinalizers()\n    if (this._doneStack.length === 0) {\n      this._doneStack = finalizers.reverse()\n      this._done = Exit.failCause(cause)\n      this._currentChannel = undefined\n      return ChannelState.Done()\n    }\n\n    const finalizerEffect = runFinalizers(finalizers.map((f) => f.finalizer), Exit.failCause(cause))!\n    this.storeInProgressFinalizer(finalizerEffect)\n\n    const effect = pipe(\n      finalizerEffect,\n      Effect.ensuring(Effect.sync(() => this.clearInProgressFinalizer())),\n      Effect.uninterruptible,\n      Effect.flatMap(() => Effect.sync(() => this.doneHalt(cause)))\n    )\n\n    return ChannelState.fromEffect(effect)\n  }\n\n  processCancellation(): ChannelState.ChannelState<unknown, Env> {\n    this._currentChannel = undefined\n    this._done = this._cancelled\n    this._cancelled = undefined\n    return ChannelState.Done()\n  }\n\n  runBracketOut(bracketOut: core.BracketOut): ChannelState.ChannelState<unknown, Env> {\n    const effect = Effect.uninterruptible(\n      Effect.matchCauseEffect(this.provide(bracketOut.acquire() as Effect.Effect<OutDone, OutErr, Env>), {\n        onFailure: (cause) =>\n          Effect.sync(() => {\n            this._currentChannel = core.failCause(cause) as core.Primitive\n          }),\n        onSuccess: (out) =>\n          Effect.sync(() => {\n            this.addFinalizer((exit) =>\n              this.provide(bracketOut.finalizer(out, exit)) as Effect.Effect<unknown, never, Env>\n            )\n            this._currentChannel = core.write(out) as core.Primitive\n          })\n      })\n    )\n    return ChannelState.fromEffect(effect) as ChannelState.ChannelState<unknown, Env>\n  }\n\n  provide(effect: Effect.Effect<unknown, unknown, unknown>): Effect.Effect<unknown, unknown, unknown> {\n    if (this._providedEnv === undefined) {\n      return effect\n    }\n    return pipe(effect, Effect.provide(this._providedEnv))\n  }\n\n  runEnsuring(ensuring: core.Ensuring): void {\n    this.addFinalizer(ensuring.finalizer as ErasedFinalizer<Env>)\n    this._currentChannel = ensuring.channel as core.Primitive\n  }\n\n  addFinalizer(f: ErasedFinalizer<Env>): void {\n    this._doneStack.push(new Continuation.ContinuationFinalizerImpl(f))\n  }\n\n  runSubexecutor(): ChannelState.ChannelState<unknown, Env> | undefined {\n    const subexecutor = this._activeSubexecutor as Subexecutor.Primitive<Env>\n    switch (subexecutor._tag) {\n      case Subexecutor.OP_PULL_FROM_CHILD: {\n        return this.pullFromChild(\n          subexecutor.childExecutor,\n          subexecutor.parentSubexecutor,\n          subexecutor.onEmit,\n          subexecutor\n        )\n      }\n      case Subexecutor.OP_PULL_FROM_UPSTREAM: {\n        return this.pullFromUpstream(subexecutor)\n      }\n      case Subexecutor.OP_DRAIN_CHILD_EXECUTORS: {\n        return this.drainChildExecutors(subexecutor)\n      }\n      case Subexecutor.OP_EMIT: {\n        this._emitted = subexecutor.value\n        this._activeSubexecutor = subexecutor.next\n        return ChannelState.Emit()\n      }\n    }\n  }\n\n  replaceSubexecutor(nextSubExec: Subexecutor.Subexecutor<Env>): void {\n    this._currentChannel = undefined\n    this._activeSubexecutor = nextSubExec\n  }\n\n  finishWithExit(exit: Exit.Exit<unknown, unknown>): Effect.Effect<unknown, unknown, Env> {\n    const state = Exit.match(exit, {\n      onFailure: (cause) => this.doneHalt(cause),\n      onSuccess: (value) => this.doneSucceed(value)\n    })\n    this._activeSubexecutor = undefined\n    return state === undefined ?\n      Effect.void :\n      ChannelState.effect(state)\n  }\n\n  finishSubexecutorWithCloseEffect(\n    subexecutorDone: Exit.Exit<unknown, unknown>,\n    ...closeFuncs: Array<(exit: Exit.Exit<unknown, unknown>) => Effect.Effect<unknown, never, Env> | undefined>\n  ): ChannelState.ChannelState<unknown, Env> | undefined {\n    this.addFinalizer(() =>\n      pipe(\n        closeFuncs,\n        Effect.forEach((closeFunc) =>\n          pipe(\n            Effect.sync(() => closeFunc(subexecutorDone)),\n            Effect.flatMap((closeEffect) => closeEffect !== undefined ? closeEffect : Effect.void)\n          ), { discard: true })\n      )\n    )\n    const state = pipe(\n      subexecutorDone,\n      Exit.match({\n        onFailure: (cause) => this.doneHalt(cause),\n        onSuccess: (value) => this.doneSucceed(value)\n      })\n    )\n    this._activeSubexecutor = undefined\n    return state\n  }\n\n  applyUpstreamPullStrategy(\n    upstreamFinished: boolean,\n    queue: ReadonlyArray<Subexecutor.PullFromChild<Env> | undefined>,\n    strategy: UpstreamPullStrategy.UpstreamPullStrategy<unknown>\n  ): [Option.Option<unknown>, ReadonlyArray<Subexecutor.PullFromChild<Env> | undefined>] {\n    switch (strategy._tag) {\n      case UpstreamPullStrategyOpCodes.OP_PULL_AFTER_NEXT: {\n        const shouldPrepend = !upstreamFinished || queue.some((subexecutor) => subexecutor !== undefined)\n        return [strategy.emitSeparator, shouldPrepend ? [undefined, ...queue] : queue]\n      }\n      case UpstreamPullStrategyOpCodes.OP_PULL_AFTER_ALL_ENQUEUED: {\n        const shouldEnqueue = !upstreamFinished || queue.some((subexecutor) => subexecutor !== undefined)\n        return [strategy.emitSeparator, shouldEnqueue ? [...queue, undefined] : queue]\n      }\n    }\n  }\n\n  pullFromChild(\n    childExecutor: ErasedExecutor<Env>,\n    parentSubexecutor: Subexecutor.Subexecutor<Env>,\n    onEmitted: (emitted: unknown) => ChildExecutorDecision.ChildExecutorDecision,\n    subexecutor: Subexecutor.PullFromChild<Env>\n  ): ChannelState.ChannelState<unknown, Env> | undefined {\n    return ChannelState.Read(\n      childExecutor,\n      identity,\n      (emitted) => {\n        const childExecutorDecision = onEmitted(emitted)\n        switch (childExecutorDecision._tag) {\n          case ChildExecutorDecisionOpCodes.OP_CONTINUE: {\n            break\n          }\n          case ChildExecutorDecisionOpCodes.OP_CLOSE: {\n            this.finishWithDoneValue(childExecutor, parentSubexecutor, childExecutorDecision.value)\n            break\n          }\n          case ChildExecutorDecisionOpCodes.OP_YIELD: {\n            const modifiedParent = parentSubexecutor.enqueuePullFromChild(subexecutor)\n            this.replaceSubexecutor(modifiedParent)\n            break\n          }\n        }\n        this._activeSubexecutor = new Subexecutor.Emit(emitted, this._activeSubexecutor!)\n        return undefined\n      },\n      Exit.match({\n        onFailure: (cause) => {\n          const state = this.handleSubexecutorFailure(childExecutor, parentSubexecutor, cause)\n          return state === undefined ?\n            undefined :\n            ChannelState.effectOrUndefinedIgnored(state) as Effect.Effect<void, never, Env>\n        },\n        onSuccess: (doneValue) => {\n          this.finishWithDoneValue(childExecutor, parentSubexecutor, doneValue)\n          return undefined\n        }\n      })\n    )\n  }\n\n  finishWithDoneValue(\n    childExecutor: ErasedExecutor<Env>,\n    parentSubexecutor: Subexecutor.Subexecutor<Env>,\n    doneValue: unknown\n  ): void {\n    const subexecutor = parentSubexecutor as Subexecutor.Primitive<Env>\n    switch (subexecutor._tag) {\n      case Subexecutor.OP_PULL_FROM_UPSTREAM: {\n        const modifiedParent = new Subexecutor.PullFromUpstream(\n          subexecutor.upstreamExecutor,\n          subexecutor.createChild,\n          subexecutor.lastDone !== undefined\n            ? subexecutor.combineChildResults(\n              subexecutor.lastDone,\n              doneValue\n            )\n            : doneValue,\n          subexecutor.activeChildExecutors,\n          subexecutor.combineChildResults,\n          subexecutor.combineWithChildResult,\n          subexecutor.onPull,\n          subexecutor.onEmit\n        )\n        this._closeLastSubstream = childExecutor.close(Exit.succeed(doneValue))\n        this.replaceSubexecutor(modifiedParent)\n        break\n      }\n      case Subexecutor.OP_DRAIN_CHILD_EXECUTORS: {\n        const modifiedParent = new Subexecutor.DrainChildExecutors(\n          subexecutor.upstreamExecutor,\n          subexecutor.lastDone !== undefined\n            ? subexecutor.combineChildResults(\n              subexecutor.lastDone,\n              doneValue\n            )\n            : doneValue,\n          subexecutor.activeChildExecutors,\n          subexecutor.upstreamDone,\n          subexecutor.combineChildResults,\n          subexecutor.combineWithChildResult,\n          subexecutor.onPull\n        )\n        this._closeLastSubstream = childExecutor.close(Exit.succeed(doneValue))\n        this.replaceSubexecutor(modifiedParent)\n        break\n      }\n      default: {\n        break\n      }\n    }\n  }\n\n  handleSubexecutorFailure(\n    childExecutor: ErasedExecutor<Env>,\n    parentSubexecutor: Subexecutor.Subexecutor<Env>,\n    cause: Cause.Cause<unknown>\n  ): ChannelState.ChannelState<unknown, Env> | undefined {\n    return this.finishSubexecutorWithCloseEffect(\n      Exit.failCause(cause),\n      (exit) => parentSubexecutor.close(exit),\n      (exit) => childExecutor.close(exit)\n    )\n  }\n\n  pullFromUpstream(\n    subexecutor: Subexecutor.PullFromUpstream<Env>\n  ): ChannelState.ChannelState<unknown, Env> | undefined {\n    if (subexecutor.activeChildExecutors.length === 0) {\n      return this.performPullFromUpstream(subexecutor)\n    }\n\n    const activeChild = subexecutor.activeChildExecutors[0]\n\n    const parentSubexecutor = new Subexecutor.PullFromUpstream(\n      subexecutor.upstreamExecutor,\n      subexecutor.createChild,\n      subexecutor.lastDone,\n      subexecutor.activeChildExecutors.slice(1),\n      subexecutor.combineChildResults,\n      subexecutor.combineWithChildResult,\n      subexecutor.onPull,\n      subexecutor.onEmit\n    )\n\n    if (activeChild === undefined) {\n      return this.performPullFromUpstream(parentSubexecutor)\n    }\n\n    this.replaceSubexecutor(\n      new Subexecutor.PullFromChild(\n        activeChild.childExecutor,\n        parentSubexecutor,\n        activeChild.onEmit\n      )\n    )\n\n    return undefined\n  }\n\n  performPullFromUpstream(\n    subexecutor: Subexecutor.PullFromUpstream<Env>\n  ): ChannelState.ChannelState<unknown, Env> | undefined {\n    return ChannelState.Read(\n      subexecutor.upstreamExecutor,\n      (effect) => {\n        const closeLastSubstream = this._closeLastSubstream === undefined ? Effect.void : this._closeLastSubstream\n        this._closeLastSubstream = undefined\n        return pipe(\n          this._executeCloseLastSubstream(closeLastSubstream),\n          Effect.zipRight(effect)\n        )\n      },\n      (emitted) => {\n        if (this._closeLastSubstream !== undefined) {\n          const closeLastSubstream = this._closeLastSubstream\n          this._closeLastSubstream = undefined\n          return pipe(\n            this._executeCloseLastSubstream(closeLastSubstream),\n            Effect.map(() => {\n              const childExecutor: ErasedExecutor<Env> = new ChannelExecutor(\n                subexecutor.createChild(emitted),\n                this._providedEnv,\n                this._executeCloseLastSubstream\n              )\n\n              childExecutor._input = this._input\n\n              const [emitSeparator, updatedChildExecutors] = this.applyUpstreamPullStrategy(\n                false,\n                subexecutor.activeChildExecutors,\n                subexecutor.onPull(upstreamPullRequest.Pulled(emitted))\n              )\n\n              this._activeSubexecutor = new Subexecutor.PullFromChild(\n                childExecutor,\n                new Subexecutor.PullFromUpstream(\n                  subexecutor.upstreamExecutor,\n                  subexecutor.createChild,\n                  subexecutor.lastDone,\n                  updatedChildExecutors,\n                  subexecutor.combineChildResults,\n                  subexecutor.combineWithChildResult,\n                  subexecutor.onPull,\n                  subexecutor.onEmit\n                ),\n                subexecutor.onEmit\n              )\n\n              if (Option.isSome(emitSeparator)) {\n                this._activeSubexecutor = new Subexecutor.Emit(emitSeparator.value, this._activeSubexecutor)\n              }\n\n              return undefined\n            })\n          )\n        }\n\n        const childExecutor: ErasedExecutor<Env> = new ChannelExecutor(\n          subexecutor.createChild(emitted),\n          this._providedEnv,\n          this._executeCloseLastSubstream\n        )\n\n        childExecutor._input = this._input\n\n        const [emitSeparator, updatedChildExecutors] = this.applyUpstreamPullStrategy(\n          false,\n          subexecutor.activeChildExecutors,\n          subexecutor.onPull(upstreamPullRequest.Pulled(emitted))\n        )\n\n        this._activeSubexecutor = new Subexecutor.PullFromChild(\n          childExecutor,\n          new Subexecutor.PullFromUpstream(\n            subexecutor.upstreamExecutor,\n            subexecutor.createChild,\n            subexecutor.lastDone,\n            updatedChildExecutors,\n            subexecutor.combineChildResults,\n            subexecutor.combineWithChildResult,\n            subexecutor.onPull,\n            subexecutor.onEmit\n          ),\n          subexecutor.onEmit\n        )\n\n        if (Option.isSome(emitSeparator)) {\n          this._activeSubexecutor = new Subexecutor.Emit(emitSeparator.value, this._activeSubexecutor)\n        }\n\n        return undefined\n      },\n      (exit) => {\n        if (subexecutor.activeChildExecutors.some((subexecutor) => subexecutor !== undefined)) {\n          const drain = new Subexecutor.DrainChildExecutors(\n            subexecutor.upstreamExecutor,\n            subexecutor.lastDone,\n            [undefined, ...subexecutor.activeChildExecutors],\n            subexecutor.upstreamExecutor.getDone(),\n            subexecutor.combineChildResults,\n            subexecutor.combineWithChildResult,\n            subexecutor.onPull\n          )\n\n          if (this._closeLastSubstream !== undefined) {\n            const closeLastSubstream = this._closeLastSubstream\n            this._closeLastSubstream = undefined\n            return pipe(\n              this._executeCloseLastSubstream(closeLastSubstream),\n              Effect.map(() => this.replaceSubexecutor(drain))\n            )\n          }\n\n          this.replaceSubexecutor(drain)\n\n          return undefined\n        }\n\n        const closeLastSubstream = this._closeLastSubstream\n        const state = this.finishSubexecutorWithCloseEffect(\n          pipe(exit, Exit.map((a) => subexecutor.combineWithChildResult(subexecutor.lastDone, a))),\n          () => closeLastSubstream,\n          (exit) => subexecutor.upstreamExecutor.close(exit)\n        )\n        return state === undefined ?\n          undefined :\n          // NOTE: assuming finalizers cannot fail\n          ChannelState.effectOrUndefinedIgnored(state as ChannelState.ChannelState<never, Env>)\n      }\n    )\n  }\n\n  drainChildExecutors(\n    subexecutor: Subexecutor.DrainChildExecutors<Env>\n  ): ChannelState.ChannelState<unknown, Env> | undefined {\n    if (subexecutor.activeChildExecutors.length === 0) {\n      const lastClose = this._closeLastSubstream\n      if (lastClose !== undefined) {\n        this.addFinalizer(() => Effect.succeed(lastClose))\n      }\n      return this.finishSubexecutorWithCloseEffect(\n        subexecutor.upstreamDone,\n        () => lastClose,\n        (exit) => subexecutor.upstreamExecutor.close(exit)\n      )\n    }\n\n    const activeChild = subexecutor.activeChildExecutors[0]\n    const rest = subexecutor.activeChildExecutors.slice(1)\n\n    if (activeChild === undefined) {\n      const [emitSeparator, remainingExecutors] = this.applyUpstreamPullStrategy(\n        true,\n        rest,\n        subexecutor.onPull(\n          upstreamPullRequest.NoUpstream(rest.reduce((n, curr) => curr !== undefined ? n + 1 : n, 0))\n        )\n      )\n\n      this.replaceSubexecutor(\n        new Subexecutor.DrainChildExecutors(\n          subexecutor.upstreamExecutor,\n          subexecutor.lastDone,\n          remainingExecutors,\n          subexecutor.upstreamDone,\n          subexecutor.combineChildResults,\n          subexecutor.combineWithChildResult,\n          subexecutor.onPull\n        )\n      )\n\n      if (Option.isSome(emitSeparator)) {\n        this._emitted = emitSeparator.value\n        return ChannelState.Emit()\n      }\n\n      return undefined\n    }\n\n    const parentSubexecutor = new Subexecutor.DrainChildExecutors(\n      subexecutor.upstreamExecutor,\n      subexecutor.lastDone,\n      rest,\n      subexecutor.upstreamDone,\n      subexecutor.combineChildResults,\n      subexecutor.combineWithChildResult,\n      subexecutor.onPull\n    )\n\n    this.replaceSubexecutor(\n      new Subexecutor.PullFromChild(\n        activeChild.childExecutor,\n        parentSubexecutor,\n        activeChild.onEmit\n      )\n    )\n\n    return undefined\n  }\n}\n\nconst ifNotNull = <Env>(effect: Effect.Effect<unknown, never, Env> | undefined): Effect.Effect<unknown, never, Env> =>\n  effect !== undefined ? effect : Effect.void\n\nconst runFinalizers = <Env>(\n  finalizers: Array<ErasedFinalizer<Env>>,\n  exit: Exit.Exit<unknown, unknown>\n): Effect.Effect<unknown, never, Env> => {\n  return pipe(\n    Effect.forEach(finalizers, (fin) => Effect.exit(fin(exit))),\n    Effect.map((exits) => pipe(Exit.all(exits), Option.getOrElse(() => Exit.void))),\n    Effect.flatMap((exit) => Effect.suspend(() => exit as Exit.Exit<unknown>))\n  )\n}\n\n/**\n * @internal\n */\nexport const readUpstream = <A, E2, R, E>(\n  r: ChannelState.Read,\n  onSuccess: () => Effect.Effect<A, E2, R>,\n  onFailure: (cause: Cause.Cause<E>) => Effect.Effect<A, E2, R>\n): Effect.Effect<A, E2, R> => {\n  const readStack = [r as ChannelState.Read]\n  const read = (): Effect.Effect<A, E2, R> => {\n    const current = readStack.pop()\n    if (current === undefined || current.upstream === undefined) {\n      return Effect.dieMessage(\"Unexpected end of input for channel execution\")\n    }\n    const state = current.upstream.run() as ChannelState.Primitive\n    switch (state._tag) {\n      case ChannelStateOpCodes.OP_EMIT: {\n        const emitEffect = current.onEmit(current.upstream.getEmit())\n        if (readStack.length === 0) {\n          if (emitEffect === undefined) {\n            return Effect.suspend(onSuccess)\n          }\n          return pipe(\n            emitEffect as Effect.Effect<void>,\n            Effect.matchCauseEffect({ onFailure, onSuccess })\n          )\n        }\n        if (emitEffect === undefined) {\n          return Effect.suspend(() => read())\n        }\n        return pipe(\n          emitEffect as Effect.Effect<void>,\n          Effect.matchCauseEffect({ onFailure, onSuccess: () => read() })\n        )\n      }\n\n      case ChannelStateOpCodes.OP_DONE: {\n        const doneEffect = current.onDone(current.upstream.getDone())\n        if (readStack.length === 0) {\n          if (doneEffect === undefined) {\n            return Effect.suspend(onSuccess)\n          }\n          return pipe(\n            doneEffect as Effect.Effect<void>,\n            Effect.matchCauseEffect({ onFailure, onSuccess })\n          )\n        }\n        if (doneEffect === undefined) {\n          return Effect.suspend(() => read())\n        }\n        return pipe(\n          doneEffect as Effect.Effect<void>,\n          Effect.matchCauseEffect({ onFailure, onSuccess: () => read() })\n        )\n      }\n\n      case ChannelStateOpCodes.OP_FROM_EFFECT: {\n        readStack.push(current)\n        return pipe(\n          current.onEffect(state.effect as Effect.Effect<void>) as Effect.Effect<void>,\n          Effect.catchAllCause((cause) =>\n            Effect.suspend(() => {\n              const doneEffect = current.onDone(Exit.failCause(cause)) as Effect.Effect<void>\n              return doneEffect === undefined ? Effect.void : doneEffect\n            })\n          ),\n          Effect.matchCauseEffect({ onFailure, onSuccess: () => read() })\n        )\n      }\n\n      case ChannelStateOpCodes.OP_READ: {\n        readStack.push(current)\n        readStack.push(state)\n        return Effect.suspend(() => read())\n      }\n    }\n  }\n  return read()\n}\n\n/** @internal */\nexport const runIn = dual<\n  (scope: Scope.Scope) => <Env, InErr, InDone, OutErr, OutDone>(\n    self: Channel.Channel<never, unknown, OutErr, InErr, OutDone, InDone, Env>\n  ) => Effect.Effect<OutDone, OutErr, Env>,\n  <Env, InErr, InDone, OutErr, OutDone>(\n    self: Channel.Channel<never, unknown, OutErr, InErr, OutDone, InDone, Env>,\n    scope: Scope.Scope\n  ) => Effect.Effect<OutDone, OutErr, Env>\n>(2, <Env, InErr, InDone, OutErr, OutDone>(\n  self: Channel.Channel<never, unknown, OutErr, InErr, OutDone, InDone, Env>,\n  scope: Scope.Scope\n) => {\n  const run = (\n    channelDeferred: Deferred.Deferred<OutDone, OutErr>,\n    scopeDeferred: Deferred.Deferred<void>,\n    scope: Scope.Scope\n  ) =>\n    Effect.acquireUseRelease(\n      Effect.sync(() => new ChannelExecutor(self, void 0, identity)),\n      (exec) =>\n        Effect.suspend(() =>\n          runScopedInterpret(exec.run() as ChannelState.ChannelState<OutErr, Env>, exec).pipe(\n            Effect.intoDeferred(channelDeferred),\n            Effect.zipRight(Deferred.await(channelDeferred)),\n            Effect.zipLeft(Deferred.await(scopeDeferred))\n          )\n        ),\n      (exec, exit) => {\n        const finalize = exec.close(exit)\n        if (finalize === undefined) {\n          return Effect.void\n        }\n        return Effect.tapErrorCause(\n          finalize,\n          (cause) => Scope.addFinalizer(scope, Effect.failCause(cause))\n        )\n      }\n    )\n  return Effect.uninterruptibleMask((restore) =>\n    Effect.all([\n      Scope.fork(scope, ExecutionStrategy.sequential),\n      Deferred.make<OutDone, OutErr>(),\n      Deferred.make<void>()\n    ]).pipe(Effect.flatMap(([child, channelDeferred, scopeDeferred]) =>\n      restore(run(channelDeferred, scopeDeferred, child)).pipe(\n        Effect.forkIn(scope),\n        Effect.flatMap((fiber) =>\n          scope.addFinalizer((exit) => {\n            const interruptors = Exit.isFailure(exit) ? Cause.interruptors(exit.cause) : undefined\n            return Deferred.isDone(channelDeferred).pipe(\n              Effect.flatMap((isDone) =>\n                isDone\n                  ? Deferred.succeed(scopeDeferred, void 0).pipe(\n                    Effect.zipRight(Fiber.await(fiber)),\n                    Effect.zipRight(Fiber.inheritAll(fiber))\n                  )\n                  : Deferred.succeed(scopeDeferred, void 0).pipe(\n                    Effect.zipRight(\n                      interruptors && HashSet.size(interruptors) > 0\n                        ? Fiber.interruptAs(fiber, FiberId.combineAll(interruptors))\n                        : Fiber.interrupt(fiber)\n                    ),\n                    Effect.zipRight(Fiber.inheritAll(fiber))\n                  )\n              )\n            )\n          }).pipe(Effect.zipRight(restore(Deferred.await(channelDeferred))))\n        )\n      )\n    ))\n  )\n})\n\n/** @internal */\nconst runScopedInterpret = <Env, InErr, InDone, OutErr, OutDone>(\n  channelState: ChannelState.ChannelState<OutErr, Env>,\n  exec: ChannelExecutor<never, unknown, OutErr, InErr, OutDone, InDone, Env>\n): Effect.Effect<OutDone, OutErr, Env> => {\n  const op = channelState as ChannelState.Primitive\n  switch (op._tag) {\n    case ChannelStateOpCodes.OP_FROM_EFFECT: {\n      return pipe(\n        op.effect as Effect.Effect<OutDone, OutErr, Env>,\n        Effect.flatMap(() => runScopedInterpret(exec.run() as ChannelState.ChannelState<OutErr, Env>, exec))\n      )\n    }\n    case ChannelStateOpCodes.OP_EMIT: {\n      // Can't really happen because Out <:< Nothing. So just skip ahead.\n      return runScopedInterpret<Env, InErr, InDone, OutErr, OutDone>(\n        exec.run() as ChannelState.ChannelState<OutErr, Env>,\n        exec\n      )\n    }\n    case ChannelStateOpCodes.OP_DONE: {\n      return Effect.suspend(() => exec.getDone())\n    }\n    case ChannelStateOpCodes.OP_READ: {\n      return readUpstream(\n        op,\n        () => runScopedInterpret(exec.run() as ChannelState.ChannelState<OutErr, Env>, exec),\n        Effect.failCause\n      ) as Effect.Effect<OutDone, OutErr, Env>\n    }\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/channel/channelState.ts",
    "content": "import * as Effect from \"../../Effect.js\"\nimport type * as Exit from \"../../Exit.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport type * as Types from \"../../Types.js\"\nimport * as OpCodes from \"../opCodes/channelState.js\"\nimport type { ErasedExecutor } from \"./channelExecutor.js\"\n\n/** @internal */\nexport const ChannelStateTypeId = Symbol.for(\"effect/ChannelState\")\n\n/** @internal */\nexport type ChannelStateTypeId = typeof ChannelStateTypeId\n\n/** @internal */\nexport interface ChannelState<out E, out R> extends ChannelState.Variance<E, R> {}\n\n/** @internal */\nexport declare namespace ChannelState {\n  export interface Variance<out E, out R> {\n    readonly [ChannelStateTypeId]: {\n      readonly _E: Types.Covariant<E>\n      readonly _R: Types.Covariant<R>\n    }\n  }\n}\n\nconst channelStateVariance = {\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _R: (_: never) => _\n}\n\n/** @internal */\nconst proto = {\n  [ChannelStateTypeId]: channelStateVariance\n}\n\n/** @internal */\nexport type Primitive =\n  | Done\n  | Emit\n  | FromEffect\n  | Read\n\n/** @internal */\nexport type Op<Tag extends string, Body = {}> = ChannelState<never, never> & Body & {\n  readonly _tag: Tag\n}\n\n/** @internal */\nexport interface Done extends Op<OpCodes.OP_DONE, {}> {}\n\n/** @internal */\nexport interface Emit extends Op<OpCodes.OP_EMIT, {}> {}\n\n/** @internal */\nexport interface FromEffect extends\n  Op<OpCodes.OP_FROM_EFFECT, {\n    readonly effect: Effect.Effect<unknown, unknown, unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Read extends\n  Op<OpCodes.OP_READ, {\n    readonly upstream: ErasedExecutor<unknown>\n    onEffect(effect: Effect.Effect<void, never, unknown>): Effect.Effect<void, never, unknown>\n    onEmit(value: unknown): Effect.Effect<void, never, unknown>\n    onDone(exit: Exit.Exit<unknown, unknown>): Effect.Effect<void, never, unknown>\n  }>\n{}\n\n/** @internal */\nexport const Done = (): ChannelState<never, never> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_DONE\n  return op\n}\n\n/** @internal */\nexport const Emit = (): ChannelState<never, never> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_EMIT\n  return op\n}\n\n/** @internal */\nexport const fromEffect = <X, E, R>(effect: Effect.Effect<X, E, R>): ChannelState<E, R> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_FROM_EFFECT\n  op.effect = effect\n  return op\n}\n\n/** @internal */\nexport const Read = <R>(\n  upstream: ErasedExecutor<R>,\n  onEffect: (effect: Effect.Effect<void, never, R>) => Effect.Effect<void, never, R>,\n  onEmit: (value: unknown) => Effect.Effect<void, never, R> | undefined,\n  onDone: (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void, never, R> | undefined\n): ChannelState<never, R> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_READ\n  op.upstream = upstream\n  op.onEffect = onEffect\n  op.onEmit = onEmit\n  op.onDone = onDone\n  return op\n}\n\n/** @internal */\nexport const isChannelState = (u: unknown): u is ChannelState<unknown, unknown> => hasProperty(u, ChannelStateTypeId)\n\n/** @internal */\nexport const isDone = <E, R>(self: ChannelState<E, R>): self is Done => (self as Primitive)._tag === OpCodes.OP_DONE\n\n/** @internal */\nexport const isEmit = <E, R>(self: ChannelState<E, R>): self is Emit => (self as Primitive)._tag === OpCodes.OP_EMIT\n\n/** @internal */\nexport const isFromEffect = <E, R>(self: ChannelState<E, R>): self is FromEffect =>\n  (self as Primitive)._tag === OpCodes.OP_FROM_EFFECT\n\n/** @internal */\nexport const isRead = <E, R>(self: ChannelState<E, R>): self is Read => (self as Primitive)._tag === OpCodes.OP_READ\n\n/** @internal */\nexport const effect = <E, R>(self: ChannelState<E, R>): Effect.Effect<void, E, R> =>\n  isFromEffect(self) ? self.effect as Effect.Effect<void, E, R> : Effect.void\n\n/** @internal */\nexport const effectOrUndefinedIgnored = <E, R>(self: ChannelState<E, R>): Effect.Effect<void, E, R> | undefined =>\n  isFromEffect(self) ? Effect.ignore(self.effect as Effect.Effect<void, E, R>) : undefined\n"
  },
  {
    "path": "packages/effect/src/internal/channel/childExecutorDecision.ts",
    "content": "import type * as ChildExecutorDecision from \"../../ChildExecutorDecision.js\"\nimport { dual } from \"../../Function.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport * as OpCodes from \"../opCodes/channelChildExecutorDecision.js\"\n\n/** @internal */\nconst ChildExecutorDecisionSymbolKey = \"effect/ChannelChildExecutorDecision\"\n\n/** @internal */\nexport const ChildExecutorDecisionTypeId: ChildExecutorDecision.ChildExecutorDecisionTypeId = Symbol.for(\n  ChildExecutorDecisionSymbolKey\n) as ChildExecutorDecision.ChildExecutorDecisionTypeId\n\n/** @internal */\nconst proto = {\n  [ChildExecutorDecisionTypeId]: ChildExecutorDecisionTypeId\n}\n\n/** @internal */\nexport const Continue = (_: void): ChildExecutorDecision.ChildExecutorDecision => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_CONTINUE\n  return op\n}\n\n/** @internal */\nexport const Close = (value: unknown): ChildExecutorDecision.ChildExecutorDecision => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_CLOSE\n  op.value = value\n  return op\n}\n\n/** @internal */\nexport const Yield = (_: void): ChildExecutorDecision.ChildExecutorDecision => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_YIELD\n  return op\n}\n\n/** @internal */\nexport const isChildExecutorDecision = (u: unknown): u is ChildExecutorDecision.ChildExecutorDecision =>\n  hasProperty(u, ChildExecutorDecisionTypeId)\n\n/** @internal */\nexport const isContinue = (\n  self: ChildExecutorDecision.ChildExecutorDecision\n): self is ChildExecutorDecision.Continue => self._tag === OpCodes.OP_CONTINUE\n\n/** @internal */\nexport const isClose = (\n  self: ChildExecutorDecision.ChildExecutorDecision\n): self is ChildExecutorDecision.Close => self._tag === OpCodes.OP_CLOSE\n\n/** @internal */\nexport const isYield = (\n  self: ChildExecutorDecision.ChildExecutorDecision\n): self is ChildExecutorDecision.Yield => self._tag === OpCodes.OP_YIELD\n\n/** @internal */\nexport const match = dual<\n  <A>(\n    options: {\n      readonly onContinue: () => A\n      readonly onClose: (value: unknown) => A\n      readonly onYield: () => A\n    }\n  ) => (self: ChildExecutorDecision.ChildExecutorDecision) => A,\n  <A>(\n    self: ChildExecutorDecision.ChildExecutorDecision,\n    options: {\n      readonly onContinue: () => A\n      readonly onClose: (value: unknown) => A\n      readonly onYield: () => A\n    }\n  ) => A\n>(2, <A>(\n  self: ChildExecutorDecision.ChildExecutorDecision,\n  { onClose, onContinue, onYield }: {\n    readonly onContinue: () => A\n    readonly onClose: (value: unknown) => A\n    readonly onYield: () => A\n  }\n): A => {\n  switch (self._tag) {\n    case OpCodes.OP_CONTINUE: {\n      return onContinue()\n    }\n    case OpCodes.OP_CLOSE: {\n      return onClose(self.value)\n    }\n    case OpCodes.OP_YIELD: {\n      return onYield()\n    }\n  }\n})\n"
  },
  {
    "path": "packages/effect/src/internal/channel/continuation.ts",
    "content": "import type * as Cause from \"../../Cause.js\"\nimport type * as Channel from \"../../Channel.js\"\nimport type * as Effect from \"../../Effect.js\"\nimport * as Exit from \"../../Exit.js\"\nimport type * as Types from \"../../Types.js\"\nimport * as OpCodes from \"../opCodes/continuation.js\"\n\n/** @internal */\nexport const ContinuationTypeId = Symbol.for(\"effect/ChannelContinuation\")\n\n/** @internal */\nexport type ContinuationTypeId = typeof ContinuationTypeId\n\n/** @internal */\nexport interface Continuation<\n  out Env,\n  in InErr,\n  in InElem,\n  in InDone,\n  out OutErr,\n  out OutErr2,\n  out OutElem,\n  out OutDone,\n  out OutDone2\n> extends Continuation.Variance<Env, InErr, InElem, InDone, OutErr, OutErr2, OutElem, OutDone, OutDone2> {}\n\n/** @internal */\nexport declare namespace Continuation {\n  /** @internal */\n  export interface Variance<\n    out Env,\n    in InErr,\n    in InElem,\n    in InDone,\n    out OutErr,\n    out OutErr2,\n    out OutElem,\n    out OutDone,\n    out OutDone2\n  > {\n    readonly [ContinuationTypeId]: {\n      readonly _Env: Types.Covariant<Env>\n      readonly _InErr: Types.Contravariant<InErr>\n      readonly _InElem: Types.Contravariant<InElem>\n      readonly _InDone: Types.Contravariant<InDone>\n      readonly _OutErr: Types.Covariant<OutErr>\n      readonly _OutDone: Types.Covariant<OutDone>\n      readonly _OutErr2: Types.Covariant<OutErr2>\n      readonly _OutElem: Types.Covariant<OutElem>\n      readonly _OutDone2: Types.Covariant<OutDone2>\n    }\n  }\n}\n\n/** @internal */\nexport type Primitive = ErasedContinuationK | ErasedContinuationFinalizer\n\n/** @internal */\nexport type ErasedContinuationK = ContinuationK<\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown\n>\n\n/** @internal */\nexport type ErasedContinuationFinalizer = ContinuationFinalizer<unknown, unknown, unknown>\n\n/** @internal */\nexport interface ContinuationK<\n  out Env,\n  in InErr,\n  in InElem,\n  in InDone,\n  out OutErr,\n  out OutErr2,\n  out OutElem,\n  out OutDone,\n  out OutDone2\n> extends\n  Continuation<\n    Env,\n    InErr,\n    InElem,\n    InDone,\n    OutErr,\n    OutErr2,\n    OutElem,\n    OutDone,\n    OutDone2\n  >\n{\n  readonly _tag: OpCodes.OP_CONTINUATION_K\n  onSuccess(\n    o: OutDone\n  ): Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone2, InDone, Env>\n  onHalt(\n    c: Cause.Cause<OutErr>\n  ): Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone2, InDone, Env>\n  onExit(\n    exit: Exit.Exit<OutDone, OutErr>\n  ): Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone2, InDone, Env>\n}\n\n/** @internal */\nexport interface ContinuationFinalizer<out Env, out OutErr, out OutDone> extends\n  Continuation<\n    Env,\n    unknown,\n    unknown,\n    unknown,\n    OutErr,\n    never,\n    never,\n    OutDone,\n    never\n  >\n{\n  readonly _tag: OpCodes.OP_CONTINUATION_FINALIZER\n  finalizer(exit: Exit.Exit<OutErr, OutDone>): Effect.Effect<unknown, never, Env>\n}\n\nconst continuationVariance = {\n  /* c8 ignore next */\n  _Env: (_: never) => _,\n  /* c8 ignore next */\n  _InErr: (_: unknown) => _,\n  /* c8 ignore next */\n  _InElem: (_: unknown) => _,\n  /* c8 ignore next */\n  _InDone: (_: unknown) => _,\n  /* c8 ignore next */\n  _OutErr: (_: never) => _,\n  /* c8 ignore next */\n  _OutDone: (_: never) => _,\n  /* c8 ignore next */\n  _OutErr2: (_: never) => _,\n  /* c8 ignore next */\n  _OutElem: (_: never) => _,\n  /* c8 ignore next */\n  _OutDone2: (_: never) => _\n}\n\n/** @internal */\nexport class ContinuationKImpl<\n  out Env,\n  out Env2,\n  in InErr,\n  in InElem,\n  in InDone,\n  in out OutErr,\n  out OutErr2,\n  out OutElem,\n  in out OutDone,\n  out OutDone2\n> implements\n  ContinuationK<\n    Env | Env2,\n    InErr,\n    InElem,\n    InDone,\n    OutErr,\n    OutErr2,\n    OutElem,\n    OutDone,\n    OutDone2\n  >\n{\n  readonly _tag = OpCodes.OP_CONTINUATION_K\n  readonly [ContinuationTypeId] = continuationVariance\n  constructor(\n    readonly onSuccess: (\n      o: OutDone\n    ) => Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone2, InDone, Env>,\n    readonly onHalt: (\n      c: Cause.Cause<OutErr>\n    ) => Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone2, InDone, Env2>\n  ) {\n  }\n  onExit(\n    exit: Exit.Exit<OutDone, OutErr>\n  ): Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone2, InDone, Env | Env2> {\n    return Exit.isFailure(exit) ? this.onHalt(exit.cause) : this.onSuccess(exit.value)\n  }\n}\n\n/** @internal */\nexport class ContinuationFinalizerImpl<out Env, in out OutErr, in out OutDone>\n  implements ContinuationFinalizer<Env, OutErr, OutDone>\n{\n  readonly _tag = OpCodes.OP_CONTINUATION_FINALIZER\n  readonly [ContinuationTypeId] = continuationVariance\n  constructor(readonly finalizer: (exit: Exit.Exit<OutErr, OutDone>) => Effect.Effect<unknown, never, Env>) {\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/channel/mergeDecision.ts",
    "content": "import type * as Effect from \"../../Effect.js\"\nimport type * as Exit from \"../../Exit.js\"\nimport { dual } from \"../../Function.js\"\nimport type * as MergeDecision from \"../../MergeDecision.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport * as OpCodes from \"../opCodes/channelMergeDecision.js\"\n\n/** @internal */\nconst MergeDecisionSymbolKey = \"effect/ChannelMergeDecision\"\n\n/** @internal */\nexport const MergeDecisionTypeId: MergeDecision.MergeDecisionTypeId = Symbol.for(\n  MergeDecisionSymbolKey\n) as MergeDecision.MergeDecisionTypeId\n\n/** @internal */\nconst proto = {\n  [MergeDecisionTypeId]: {\n    _R: (_: never) => _,\n    _E0: (_: unknown) => _,\n    _Z0: (_: unknown) => _,\n    _E: (_: never) => _,\n    _Z: (_: never) => _\n  }\n}\n\n/** @internal */\nexport type Primitive =\n  | Done\n  | Await\n\n/** @internal */\nexport type Op<Tag extends string, Body = {}> =\n  & MergeDecision.MergeDecision<never, unknown, unknown, never, never>\n  & Body\n  & {\n    readonly _tag: Tag\n  }\n\n/** @internal */\nexport interface Done extends\n  Op<OpCodes.OP_DONE, {\n    readonly effect: Effect.Effect<never>\n  }>\n{}\n\n/** @internal */\nexport interface Await extends\n  Op<OpCodes.OP_AWAIT, {\n    f(exit: Exit.Exit<unknown, unknown>): Effect.Effect<never>\n  }>\n{}\n\n/** @internal */\nexport const Done = <Z, E, R>(\n  effect: Effect.Effect<Z, E, R>\n): MergeDecision.MergeDecision<R, unknown, unknown, E, Z> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_DONE\n  op.effect = effect\n  return op\n}\n\n/** @internal */\nexport const Await = <R, E0, Z0, E, Z>(\n  f: (exit: Exit.Exit<Z0, E0>) => Effect.Effect<Z, E, R>\n): MergeDecision.MergeDecision<R, E0, Z0, E, Z> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_AWAIT\n  op.f = f\n  return op\n}\n\n/** @internal */\nexport const AwaitConst = <Z, E, R>(\n  effect: Effect.Effect<Z, E, R>\n): MergeDecision.MergeDecision<R, unknown, unknown, E, Z> => Await(() => effect)\n\n/** @internal */\nexport const isMergeDecision = (\n  u: unknown\n): u is MergeDecision.MergeDecision<unknown, unknown, unknown, unknown, unknown> => hasProperty(u, MergeDecisionTypeId)\n\n/** @internal */\nexport const match = dual<\n  <R, E0, Z0, E, Z, Z2>(\n    options: {\n      readonly onDone: (effect: Effect.Effect<Z, E, R>) => Z2\n      readonly onAwait: (f: (exit: Exit.Exit<Z0, E0>) => Effect.Effect<Z, E, R>) => Z2\n    }\n  ) => (self: MergeDecision.MergeDecision<R, E0, Z0, E, Z>) => Z2,\n  <R, E0, Z0, E, Z, Z2>(\n    self: MergeDecision.MergeDecision<R, E0, Z0, E, Z>,\n    options: {\n      readonly onDone: (effect: Effect.Effect<Z, E, R>) => Z2\n      readonly onAwait: (f: (exit: Exit.Exit<Z0, E0>) => Effect.Effect<Z, E, R>) => Z2\n    }\n  ) => Z2\n>(2, <R, E0, Z0, E, Z, Z2>(\n  self: MergeDecision.MergeDecision<R, E0, Z0, E, Z>,\n  { onAwait, onDone }: {\n    readonly onDone: (effect: Effect.Effect<Z, E, R>) => Z2\n    readonly onAwait: (f: (exit: Exit.Exit<Z0, E0>) => Effect.Effect<Z, E, R>) => Z2\n  }\n): Z2 => {\n  const op = self as Primitive\n  switch (op._tag) {\n    case OpCodes.OP_DONE:\n      return onDone(op.effect)\n    case OpCodes.OP_AWAIT:\n      return onAwait(op.f)\n  }\n})\n"
  },
  {
    "path": "packages/effect/src/internal/channel/mergeState.ts",
    "content": "import type * as Effect from \"../../Effect.js\"\nimport type * as Either from \"../../Either.js\"\nimport type * as Exit from \"../../Exit.js\"\nimport type * as Fiber from \"../../Fiber.js\"\nimport { dual } from \"../../Function.js\"\nimport type * as MergeState from \"../../MergeState.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport * as OpCodes from \"../opCodes/channelMergeState.js\"\n\n/** @internal */\nconst MergeStateSymbolKey = \"effect/ChannelMergeState\"\n\n/** @internal */\nexport const MergeStateTypeId: MergeState.MergeStateTypeId = Symbol.for(\n  MergeStateSymbolKey\n) as MergeState.MergeStateTypeId\n\n/** @internal */\nconst proto = {\n  [MergeStateTypeId]: MergeStateTypeId\n}\n\n/** @internal */\nexport const BothRunning = <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  left: Fiber.Fiber<Either.Either<Elem, Done>, Err>,\n  right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1>\n): MergeState.MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_BOTH_RUNNING\n  op.left = left\n  op.right = right\n  return op\n}\n\n/** @internal */\nexport const LeftDone = <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  f: (exit: Exit.Exit<Done1, Err1>) => Effect.Effect<Done2, Err2, Env>\n): MergeState.MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_LEFT_DONE\n  op.f = f\n  return op\n}\n\n/** @internal */\nexport const RightDone = <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  f: (exit: Exit.Exit<Done, Err>) => Effect.Effect<Done2, Err2, Env>\n): MergeState.MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_RIGHT_DONE\n  op.f = f\n  return op\n}\n\n/** @internal */\nexport const isMergeState = (\n  u: unknown\n): u is MergeState.MergeState<unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown> =>\n  hasProperty(u, MergeStateTypeId)\n\n/** @internal */\nexport const isBothRunning = <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  self: MergeState.MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>\n): self is MergeState.BothRunning<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> => {\n  return self._tag === OpCodes.OP_BOTH_RUNNING\n}\n\n/** @internal */\nexport const isLeftDone = <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  self: MergeState.MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>\n): self is MergeState.LeftDone<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> => {\n  return self._tag === OpCodes.OP_LEFT_DONE\n}\n\n/** @internal */\nexport const isRightDone = <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>(\n  self: MergeState.MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>\n): self is MergeState.RightDone<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> => {\n  return self._tag === OpCodes.OP_RIGHT_DONE\n}\n\n/** @internal */\nexport const match = dual<\n  <Env, Err, Err1, Err2, Elem, Done, Done1, Done2, Z>(\n    options: {\n      readonly onBothRunning: (\n        left: Fiber.Fiber<Either.Either<Elem, Done>, Err>,\n        right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1>\n      ) => Z\n      readonly onLeftDone: (f: (exit: Exit.Exit<Done1, Err1>) => Effect.Effect<Done2, Err2, Env>) => Z\n      readonly onRightDone: (f: (exit: Exit.Exit<Done, Err>) => Effect.Effect<Done2, Err2, Env>) => Z\n    }\n  ) => (self: MergeState.MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>) => Z,\n  <Env, Err, Err1, Err2, Elem, Done, Done1, Done2, Z>(\n    self: MergeState.MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>,\n    options: {\n      readonly onBothRunning: (\n        left: Fiber.Fiber<Either.Either<Elem, Done>, Err>,\n        right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1>\n      ) => Z\n      readonly onLeftDone: (f: (exit: Exit.Exit<Done1, Err1>) => Effect.Effect<Done2, Err2, Env>) => Z\n      readonly onRightDone: (f: (exit: Exit.Exit<Done, Err>) => Effect.Effect<Done2, Err2, Env>) => Z\n    }\n  ) => Z\n>(2, (\n  self,\n  { onBothRunning, onLeftDone, onRightDone }\n) => {\n  switch (self._tag) {\n    case OpCodes.OP_BOTH_RUNNING: {\n      return onBothRunning(self.left, self.right)\n    }\n    case OpCodes.OP_LEFT_DONE: {\n      return onLeftDone(self.f)\n    }\n    case OpCodes.OP_RIGHT_DONE: {\n      return onRightDone(self.f)\n    }\n  }\n})\n"
  },
  {
    "path": "packages/effect/src/internal/channel/mergeStrategy.ts",
    "content": "import { dual } from \"../../Function.js\"\nimport type * as MergeStrategy from \"../../MergeStrategy.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport * as OpCodes from \"../opCodes/channelMergeStrategy.js\"\n\n/** @internal */\nconst MergeStrategySymbolKey = \"effect/ChannelMergeStrategy\"\n\n/** @internal */\nexport const MergeStrategyTypeId: MergeStrategy.MergeStrategyTypeId = Symbol.for(\n  MergeStrategySymbolKey\n) as MergeStrategy.MergeStrategyTypeId\n\n/** @internal */\nconst proto = {\n  [MergeStrategyTypeId]: MergeStrategyTypeId\n}\n\n/** @internal */\nexport const BackPressure = (_: void): MergeStrategy.MergeStrategy => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_BACK_PRESSURE\n  return op\n}\n\n/** @internal */\nexport const BufferSliding = (_: void): MergeStrategy.MergeStrategy => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_BUFFER_SLIDING\n  return op\n}\n\n/** @internal */\nexport const isMergeStrategy = (u: unknown): u is MergeStrategy.MergeStrategy => hasProperty(u, MergeStrategyTypeId)\n\n/** @internal */\nexport const isBackPressure = (self: MergeStrategy.MergeStrategy): self is MergeStrategy.BackPressure =>\n  self._tag === OpCodes.OP_BACK_PRESSURE\n\n/** @internal */\nexport const isBufferSliding = (self: MergeStrategy.MergeStrategy): self is MergeStrategy.BufferSliding =>\n  self._tag === OpCodes.OP_BUFFER_SLIDING\n\n/** @internal */\nexport const match = dual<\n  <A>(options: {\n    readonly onBackPressure: () => A\n    readonly onBufferSliding: () => A\n  }) => (self: MergeStrategy.MergeStrategy) => A,\n  <A>(\n    self: MergeStrategy.MergeStrategy,\n    options: {\n      readonly onBackPressure: () => A\n      readonly onBufferSliding: () => A\n    }\n  ) => A\n>(2, <A>(\n  self: MergeStrategy.MergeStrategy,\n  { onBackPressure, onBufferSliding }: {\n    readonly onBackPressure: () => A\n    readonly onBufferSliding: () => A\n  }\n): A => {\n  switch (self._tag) {\n    case OpCodes.OP_BACK_PRESSURE: {\n      return onBackPressure()\n    }\n    case OpCodes.OP_BUFFER_SLIDING: {\n      return onBufferSliding()\n    }\n  }\n})\n"
  },
  {
    "path": "packages/effect/src/internal/channel/singleProducerAsyncInput.ts",
    "content": "import * as Cause from \"../../Cause.js\"\nimport * as Deferred from \"../../Deferred.js\"\nimport * as Effect from \"../../Effect.js\"\nimport * as Either from \"../../Either.js\"\nimport * as Exit from \"../../Exit.js\"\nimport { pipe } from \"../../Function.js\"\nimport * as Ref from \"../../Ref.js\"\nimport type * as SingleProducerAsyncInput from \"../../SingleProducerAsyncInput.js\"\n\n/** @internal */\ntype State<Err, Elem, _Done> =\n  | Empty\n  | Emit<Err, Elem, _Done>\n  | Error<Err>\n  | Done<_Done>\n\n/** @internal */\nconst OP_STATE_EMPTY = \"Empty\" as const\n\n/** @internal */\ntype OP_STATE_EMPTY = typeof OP_STATE_EMPTY\n\n/** @internal */\nconst OP_STATE_EMIT = \"Emit\" as const\n\n/** @internal */\ntype OP_STATE_EMIT = typeof OP_STATE_EMIT\n\n/** @internal */\nconst OP_STATE_ERROR = \"Error\" as const\n\n/** @internal */\ntype OP_STATE_ERROR = typeof OP_STATE_ERROR\n\n/** @internal */\nconst OP_STATE_DONE = \"Done\" as const\n\n/** @internal */\ntype OP_STATE_DONE = typeof OP_STATE_DONE\n\n/** @internal */\ninterface Empty {\n  readonly _tag: OP_STATE_EMPTY\n  readonly notifyProducer: Deferred.Deferred<void>\n}\n\n/** @internal */\ninterface Emit<Err, Elem, Done> {\n  readonly _tag: OP_STATE_EMIT\n  readonly notifyConsumers: ReadonlyArray<Deferred.Deferred<Either.Either<Elem, Done>, Err>>\n}\n\n/** @internal */\ninterface Error<Err> {\n  readonly _tag: OP_STATE_ERROR\n  readonly cause: Cause.Cause<Err>\n}\n\n/** @internal */\ninterface Done<_Done> {\n  readonly _tag: OP_STATE_DONE\n  readonly done: _Done\n}\n\n/** @internal */\nconst stateEmpty = (notifyProducer: Deferred.Deferred<void>): State<never, never, never> => ({\n  _tag: OP_STATE_EMPTY,\n  notifyProducer\n})\n\n/** @internal */\nconst stateEmit = <Err, Elem, Done>(\n  notifyConsumers: ReadonlyArray<Deferred.Deferred<Either.Either<Elem, Done>, Err>>\n): State<Err, Elem, Done> => ({\n  _tag: OP_STATE_EMIT,\n  notifyConsumers\n})\n\n/** @internal */\nconst stateError = <Err>(cause: Cause.Cause<Err>): State<Err, never, never> => ({\n  _tag: OP_STATE_ERROR,\n  cause\n})\n\n/** @internal */\nconst stateDone = <Done>(done: Done): State<never, never, Done> => ({\n  _tag: OP_STATE_DONE,\n  done\n})\n\n/** @internal */\nclass SingleProducerAsyncInputImpl<in out Err, in out Elem, in out Done>\n  implements SingleProducerAsyncInput.SingleProducerAsyncInput<Err, Elem, Done>\n{\n  constructor(readonly ref: Ref.Ref<State<Err, Elem, Done>>) {\n  }\n\n  awaitRead(): Effect.Effect<unknown> {\n    return Effect.flatten(\n      Ref.modify(this.ref, (state) =>\n        state._tag === OP_STATE_EMPTY ?\n          [Deferred.await(state.notifyProducer), state as State<Err, Elem, Done>] :\n          [Effect.void, state])\n    )\n  }\n\n  get close(): Effect.Effect<unknown> {\n    return Effect.fiberIdWith((fiberId) => this.error(Cause.interrupt(fiberId)))\n  }\n\n  done(value: Done): Effect.Effect<unknown> {\n    return Effect.flatten(\n      Ref.modify(this.ref, (state) => {\n        switch (state._tag) {\n          case OP_STATE_EMPTY: {\n            return [Deferred.await(state.notifyProducer), state]\n          }\n          case OP_STATE_EMIT: {\n            return [\n              Effect.forEach(\n                state.notifyConsumers,\n                (deferred) => Deferred.succeed(deferred, Either.left(value)),\n                { discard: true }\n              ),\n              stateDone(value) as State<Err, Elem, Done>\n            ]\n          }\n          case OP_STATE_ERROR: {\n            return [Effect.interrupt, state]\n          }\n          case OP_STATE_DONE: {\n            return [Effect.interrupt, state]\n          }\n        }\n      })\n    )\n  }\n\n  emit(element: Elem): Effect.Effect<unknown> {\n    return Effect.flatMap(Deferred.make<void>(), (deferred) =>\n      Effect.flatten(\n        Ref.modify(this.ref, (state) => {\n          switch (state._tag) {\n            case OP_STATE_EMPTY: {\n              return [Deferred.await(state.notifyProducer), state]\n            }\n            case OP_STATE_EMIT: {\n              const notifyConsumer = state.notifyConsumers[0]\n              const notifyConsumers = state.notifyConsumers.slice(1)\n              if (notifyConsumer !== undefined) {\n                return [\n                  Deferred.succeed(notifyConsumer, Either.right(element)),\n                  (notifyConsumers.length === 0 ?\n                    stateEmpty(deferred) :\n                    stateEmit(notifyConsumers)) as State<Err, Elem, Done>\n                ]\n              }\n              throw new Error(\n                \"Bug: Channel.SingleProducerAsyncInput.emit - Queue was empty! please report an issue at https://github.com/Effect-TS/effect/issues\"\n              )\n            }\n            case OP_STATE_ERROR: {\n              return [Effect.interrupt, state]\n            }\n            case OP_STATE_DONE: {\n              return [Effect.interrupt, state]\n            }\n          }\n        })\n      ))\n  }\n\n  error(cause: Cause.Cause<Err>): Effect.Effect<unknown> {\n    return Effect.flatten(\n      Ref.modify(this.ref, (state) => {\n        switch (state._tag) {\n          case OP_STATE_EMPTY: {\n            return [Deferred.await(state.notifyProducer), state]\n          }\n          case OP_STATE_EMIT: {\n            return [\n              Effect.forEach(\n                state.notifyConsumers,\n                (deferred) => Deferred.failCause(deferred, cause),\n                { discard: true }\n              ),\n              stateError(cause) as State<Err, Elem, Done>\n            ]\n          }\n          case OP_STATE_ERROR: {\n            return [Effect.interrupt, state]\n          }\n          case OP_STATE_DONE: {\n            return [Effect.interrupt, state]\n          }\n        }\n      })\n    )\n  }\n\n  get take(): Effect.Effect<Exit.Exit<Elem, Either.Either<Done, Err>>> {\n    return this.takeWith(\n      (cause) => Exit.failCause(Cause.map(cause, Either.left)),\n      (elem) => Exit.succeed(elem) as Exit.Exit<Elem, Either.Either<Done, Err>>,\n      (done) => Exit.fail(Either.right(done))\n    )\n  }\n\n  takeWith<A>(\n    onError: (cause: Cause.Cause<Err>) => A,\n    onElement: (element: Elem) => A,\n    onDone: (value: Done) => A\n  ): Effect.Effect<A> {\n    return Effect.flatMap(Deferred.make<Either.Either<Elem, Done>, Err>(), (deferred) =>\n      Effect.flatten(\n        Ref.modify(this.ref, (state) => {\n          switch (state._tag) {\n            case OP_STATE_EMPTY: {\n              return [\n                Effect.zipRight(\n                  Deferred.succeed(state.notifyProducer, void 0),\n                  Effect.matchCause(Deferred.await(deferred), {\n                    onFailure: onError,\n                    onSuccess: Either.match({ onLeft: onDone, onRight: onElement })\n                  })\n                ),\n                stateEmit([deferred])\n              ]\n            }\n            case OP_STATE_EMIT: {\n              return [\n                Effect.matchCause(Deferred.await(deferred), {\n                  onFailure: onError,\n                  onSuccess: Either.match({ onLeft: onDone, onRight: onElement })\n                }),\n                stateEmit([...state.notifyConsumers, deferred])\n              ]\n            }\n            case OP_STATE_ERROR: {\n              return [Effect.succeed(onError(state.cause)), state]\n            }\n            case OP_STATE_DONE: {\n              return [Effect.succeed(onDone(state.done)), state]\n            }\n          }\n        })\n      ))\n  }\n}\n\n/** @internal */\nexport const make = <Err, Elem, Done>(): Effect.Effect<\n  SingleProducerAsyncInput.SingleProducerAsyncInput<Err, Elem, Done>\n> =>\n  pipe(\n    Deferred.make<void>(),\n    Effect.flatMap((deferred) => Ref.make(stateEmpty(deferred) as State<Err, Elem, Done>)),\n    Effect.map((ref) => new SingleProducerAsyncInputImpl(ref))\n  )\n"
  },
  {
    "path": "packages/effect/src/internal/channel/subexecutor.ts",
    "content": "import type * as ChildExecutorDecision from \"../../ChildExecutorDecision.js\"\nimport * as Effect from \"../../Effect.js\"\nimport * as Exit from \"../../Exit.js\"\nimport { pipe } from \"../../Function.js\"\nimport type * as UpstreamPullRequest from \"../../UpstreamPullRequest.js\"\nimport type * as UpstreamPullStrategy from \"../../UpstreamPullStrategy.js\"\nimport type { ErasedChannel, ErasedExecutor } from \"./channelExecutor.js\"\n\n/** @internal */\nexport interface Subexecutor<in out R> {\n  close(exit: Exit.Exit<unknown, unknown>): Effect.Effect<unknown, never, R> | undefined\n  enqueuePullFromChild(child: PullFromChild<R>): Subexecutor<R>\n}\n\n/** @internal */\nexport type Primitive<Env> = PullFromChild<Env> | PullFromUpstream<Env> | DrainChildExecutors<Env> | Emit<Env>\n\n/** @internal */\nexport const OP_PULL_FROM_CHILD = \"PullFromChild\" as const\n\n/** @internal */\nexport type OP_PULL_FROM_CHILD = typeof OP_PULL_FROM_CHILD\n\n/** @internal */\nexport const OP_PULL_FROM_UPSTREAM = \"PullFromUpstream\" as const\n\n/** @internal */\nexport type OP_PULL_FROM_UPSTREAM = typeof OP_PULL_FROM_UPSTREAM\n\n/** @internal */\nexport const OP_DRAIN_CHILD_EXECUTORS = \"DrainChildExecutors\" as const\n\n/** @internal */\nexport type OP_DRAIN_CHILD_EXECUTORS = typeof OP_DRAIN_CHILD_EXECUTORS\n\n/** @internal */\nexport const OP_EMIT = \"Emit\" as const\n\n/** @internal */\nexport type OP_EMIT = typeof OP_EMIT\n\n/**\n * Execute the `childExecutor` and on each emitted value, decide what to do by\n * `onEmit`.\n *\n * @internal\n */\nexport class PullFromChild<in out R> implements Subexecutor<R> {\n  readonly _tag: OP_PULL_FROM_CHILD = OP_PULL_FROM_CHILD\n\n  constructor(\n    readonly childExecutor: ErasedExecutor<R>,\n    readonly parentSubexecutor: Subexecutor<R>,\n    readonly onEmit: (value: unknown) => ChildExecutorDecision.ChildExecutorDecision\n  ) {\n  }\n\n  close(exit: Exit.Exit<unknown, unknown>): Effect.Effect<unknown, never, R> | undefined {\n    const fin1 = this.childExecutor.close(exit)\n    const fin2 = this.parentSubexecutor.close(exit)\n    if (fin1 !== undefined && fin2 !== undefined) {\n      return Effect.zipWith(\n        Effect.exit(fin1),\n        Effect.exit(fin2),\n        (exit1, exit2) => pipe(exit1, Exit.zipRight(exit2))\n      )\n    } else if (fin1 !== undefined) {\n      return fin1\n    } else if (fin2 !== undefined) {\n      return fin2\n    } else {\n      return undefined\n    }\n  }\n\n  enqueuePullFromChild(_child: PullFromChild<R>): Subexecutor<R> {\n    return this\n  }\n}\n\n/**\n * Execute `upstreamExecutor` and for each emitted element, spawn a child\n * channel and continue with processing it by `PullFromChild`.\n *\n * @internal\n */\nexport class PullFromUpstream<in out R> implements Subexecutor<R> {\n  readonly _tag: OP_PULL_FROM_UPSTREAM = OP_PULL_FROM_UPSTREAM\n\n  constructor(\n    readonly upstreamExecutor: ErasedExecutor<R>,\n    readonly createChild: (value: unknown) => ErasedChannel<R>,\n    readonly lastDone: unknown,\n    readonly activeChildExecutors: ReadonlyArray<PullFromChild<R> | undefined>,\n    readonly combineChildResults: (x: unknown, y: unknown) => unknown,\n    readonly combineWithChildResult: (x: unknown, y: unknown) => unknown,\n    readonly onPull: (\n      request: UpstreamPullRequest.UpstreamPullRequest<unknown>\n    ) => UpstreamPullStrategy.UpstreamPullStrategy<unknown>,\n    readonly onEmit: (value: unknown) => ChildExecutorDecision.ChildExecutorDecision\n  ) {\n  }\n\n  close(exit: Exit.Exit<unknown, unknown>): Effect.Effect<unknown, never, R> | undefined {\n    const fin1 = this.upstreamExecutor.close(exit)\n    const fins = [\n      ...this.activeChildExecutors.map((child) =>\n        child !== undefined ?\n          child.childExecutor.close(exit) :\n          undefined\n      ),\n      fin1\n    ]\n    const result = fins.reduce(\n      (acc: Effect.Effect<Exit.Exit<unknown, unknown>, never, R> | undefined, next) => {\n        if (acc !== undefined && next !== undefined) {\n          return Effect.zipWith(\n            acc,\n            Effect.exit(next),\n            (exit1, exit2) => Exit.zipRight(exit1, exit2)\n          )\n        } else if (acc !== undefined) {\n          return acc\n        } else if (next !== undefined) {\n          return Effect.exit(next)\n        } else {\n          return undefined\n        }\n      },\n      undefined\n    )\n    return result === undefined ? result : result\n  }\n\n  enqueuePullFromChild(child: PullFromChild<R>): Subexecutor<R> {\n    return new PullFromUpstream(\n      this.upstreamExecutor,\n      this.createChild,\n      this.lastDone,\n      [...this.activeChildExecutors, child],\n      this.combineChildResults,\n      this.combineWithChildResult,\n      this.onPull,\n      this.onEmit\n    )\n  }\n}\n\n/**\n * Transformed from `PullFromUpstream` when upstream has finished but there\n * are still active child executors.\n *\n * @internal\n */\nexport class DrainChildExecutors<in out R> implements Subexecutor<R> {\n  readonly _tag: OP_DRAIN_CHILD_EXECUTORS = OP_DRAIN_CHILD_EXECUTORS\n\n  constructor(\n    readonly upstreamExecutor: ErasedExecutor<R>,\n    readonly lastDone: unknown,\n    readonly activeChildExecutors: ReadonlyArray<PullFromChild<R> | undefined>,\n    readonly upstreamDone: Exit.Exit<unknown, unknown>,\n    readonly combineChildResults: (x: unknown, y: unknown) => unknown,\n    readonly combineWithChildResult: (x: unknown, y: unknown) => unknown,\n    readonly onPull: (\n      request: UpstreamPullRequest.UpstreamPullRequest<unknown>\n    ) => UpstreamPullStrategy.UpstreamPullStrategy<unknown>\n  ) {\n  }\n\n  close(exit: Exit.Exit<unknown, unknown>): Effect.Effect<unknown, never, R> | undefined {\n    const fin1 = this.upstreamExecutor.close(exit)\n    const fins = [\n      ...this.activeChildExecutors.map((child) => (child !== undefined ?\n        child.childExecutor.close(exit) :\n        undefined)\n      ),\n      fin1\n    ]\n    const result = fins.reduce(\n      (acc: Effect.Effect<Exit.Exit<unknown, unknown>, never, R> | undefined, next) => {\n        if (acc !== undefined && next !== undefined) {\n          return Effect.zipWith(\n            acc,\n            Effect.exit(next),\n            (exit1, exit2) => Exit.zipRight(exit1, exit2)\n          )\n        } else if (acc !== undefined) {\n          return acc\n        } else if (next !== undefined) {\n          return Effect.exit(next)\n        } else {\n          return undefined\n        }\n      },\n      undefined\n    )\n    return result === undefined ? result : result\n  }\n\n  enqueuePullFromChild(child: PullFromChild<R>): Subexecutor<R> {\n    return new DrainChildExecutors(\n      this.upstreamExecutor,\n      this.lastDone,\n      [...this.activeChildExecutors, child],\n      this.upstreamDone,\n      this.combineChildResults,\n      this.combineWithChildResult,\n      this.onPull\n    )\n  }\n}\n\n/** @internal */\nexport class Emit<in out R> implements Subexecutor<R> {\n  readonly _tag: OP_EMIT = OP_EMIT\n\n  constructor(readonly value: unknown, readonly next: Subexecutor<R>) {\n  }\n\n  close(exit: Exit.Exit<unknown, unknown>): Effect.Effect<unknown, never, R> | undefined {\n    const result = this.next.close(exit)\n    return result === undefined ? result : result\n  }\n\n  enqueuePullFromChild(_child: PullFromChild<R>): Subexecutor<R> {\n    return this\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/channel/upstreamPullRequest.ts",
    "content": "import { dual } from \"../../Function.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport type * as UpstreamPullRequest from \"../../UpstreamPullRequest.js\"\nimport * as OpCodes from \"../opCodes/channelUpstreamPullRequest.js\"\n\n/** @internal */\nconst UpstreamPullRequestSymbolKey = \"effect/ChannelUpstreamPullRequest\"\n\n/** @internal */\nexport const UpstreamPullRequestTypeId: UpstreamPullRequest.UpstreamPullRequestTypeId = Symbol.for(\n  UpstreamPullRequestSymbolKey\n) as UpstreamPullRequest.UpstreamPullRequestTypeId\n\nconst upstreamPullRequestVariance = {\n  /* c8 ignore next */\n  _A: (_: never) => _\n}\n\n/** @internal */\nconst proto = {\n  [UpstreamPullRequestTypeId]: upstreamPullRequestVariance\n}\n\n/** @internal */\nexport const Pulled = <A>(value: A): UpstreamPullRequest.UpstreamPullRequest<A> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_PULLED\n  op.value = value\n  return op\n}\n\n/** @internal */\nexport const NoUpstream = (activeDownstreamCount: number): UpstreamPullRequest.UpstreamPullRequest<never> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_NO_UPSTREAM\n  op.activeDownstreamCount = activeDownstreamCount\n  return op\n}\n\n/** @internal */\nexport const isUpstreamPullRequest = (u: unknown): u is UpstreamPullRequest.UpstreamPullRequest<unknown> =>\n  hasProperty(u, UpstreamPullRequestTypeId)\n\n/** @internal */\nexport const isPulled = <A>(\n  self: UpstreamPullRequest.UpstreamPullRequest<A>\n): self is UpstreamPullRequest.Pulled<A> => self._tag === OpCodes.OP_PULLED\n\n/** @internal */\nexport const isNoUpstream = <A>(\n  self: UpstreamPullRequest.UpstreamPullRequest<A>\n): self is UpstreamPullRequest.NoUpstream => self._tag === OpCodes.OP_NO_UPSTREAM\n\n/** @internal */\nexport const match = dual<\n  <A, Z>(\n    options: {\n      readonly onPulled: (value: A) => Z\n      readonly onNoUpstream: (activeDownstreamCount: number) => Z\n    }\n  ) => (self: UpstreamPullRequest.UpstreamPullRequest<A>) => Z,\n  <A, Z>(\n    self: UpstreamPullRequest.UpstreamPullRequest<A>,\n    options: {\n      readonly onPulled: (value: A) => Z\n      readonly onNoUpstream: (activeDownstreamCount: number) => Z\n    }\n  ) => Z\n>(2, <A, Z>(\n  self: UpstreamPullRequest.UpstreamPullRequest<A>,\n  { onNoUpstream, onPulled }: {\n    readonly onPulled: (value: A) => Z\n    readonly onNoUpstream: (activeDownstreamCount: number) => Z\n  }\n): Z => {\n  switch (self._tag) {\n    case OpCodes.OP_PULLED: {\n      return onPulled(self.value)\n    }\n    case OpCodes.OP_NO_UPSTREAM: {\n      return onNoUpstream(self.activeDownstreamCount)\n    }\n  }\n})\n"
  },
  {
    "path": "packages/effect/src/internal/channel/upstreamPullStrategy.ts",
    "content": "import { dual } from \"../../Function.js\"\nimport type * as Option from \"../../Option.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport type * as UpstreamPullStrategy from \"../../UpstreamPullStrategy.js\"\nimport * as OpCodes from \"../opCodes/channelUpstreamPullStrategy.js\"\n\n/** @internal */\nconst UpstreamPullStrategySymbolKey = \"effect/ChannelUpstreamPullStrategy\"\n\n/** @internal */\nexport const UpstreamPullStrategyTypeId: UpstreamPullStrategy.UpstreamPullStrategyTypeId = Symbol.for(\n  UpstreamPullStrategySymbolKey\n) as UpstreamPullStrategy.UpstreamPullStrategyTypeId\n\nconst upstreamPullStrategyVariance = {\n  /* c8 ignore next */\n  _A: (_: never) => _\n}\n\n/** @internal */\nconst proto = {\n  [UpstreamPullStrategyTypeId]: upstreamPullStrategyVariance\n}\n\n/** @internal */\nexport const PullAfterNext = <A>(emitSeparator: Option.Option<A>): UpstreamPullStrategy.UpstreamPullStrategy<A> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_PULL_AFTER_NEXT\n  op.emitSeparator = emitSeparator\n  return op\n}\n\n/** @internal */\nexport const PullAfterAllEnqueued = <A>(\n  emitSeparator: Option.Option<A>\n): UpstreamPullStrategy.UpstreamPullStrategy<A> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_PULL_AFTER_ALL_ENQUEUED\n  op.emitSeparator = emitSeparator\n  return op\n}\n\n/** @internal */\nexport const isUpstreamPullStrategy = (u: unknown): u is UpstreamPullStrategy.UpstreamPullStrategy<unknown> =>\n  hasProperty(u, UpstreamPullStrategyTypeId)\n\n/** @internal */\nexport const isPullAfterNext = <A>(\n  self: UpstreamPullStrategy.UpstreamPullStrategy<A>\n): self is UpstreamPullStrategy.PullAfterNext<A> => self._tag === OpCodes.OP_PULL_AFTER_NEXT\n\n/** @internal */\nexport const isPullAfterAllEnqueued = <A>(\n  self: UpstreamPullStrategy.UpstreamPullStrategy<A>\n): self is UpstreamPullStrategy.PullAfterAllEnqueued<A> => self._tag === OpCodes.OP_PULL_AFTER_ALL_ENQUEUED\n\n/** @internal */\nexport const match = dual<\n  <A, Z>(\n    options: {\n      readonly onNext: (emitSeparator: Option.Option<A>) => Z\n      readonly onAllEnqueued: (emitSeparator: Option.Option<A>) => Z\n    }\n  ) => (self: UpstreamPullStrategy.UpstreamPullStrategy<A>) => Z,\n  <A, Z>(\n    self: UpstreamPullStrategy.UpstreamPullStrategy<A>,\n    options: {\n      readonly onNext: (emitSeparator: Option.Option<A>) => Z\n      readonly onAllEnqueued: (emitSeparator: Option.Option<A>) => Z\n    }\n  ) => Z\n>(2, <A, Z>(\n  self: UpstreamPullStrategy.UpstreamPullStrategy<A>,\n  { onAllEnqueued, onNext }: {\n    readonly onNext: (emitSeparator: Option.Option<A>) => Z\n    readonly onAllEnqueued: (emitSeparator: Option.Option<A>) => Z\n  }\n): Z => {\n  switch (self._tag) {\n    case OpCodes.OP_PULL_AFTER_NEXT: {\n      return onNext(self.emitSeparator)\n    }\n    case OpCodes.OP_PULL_AFTER_ALL_ENQUEUED: {\n      return onAllEnqueued(self.emitSeparator)\n    }\n  }\n})\n"
  },
  {
    "path": "packages/effect/src/internal/channel.ts",
    "content": "import * as Cause from \"../Cause.js\"\nimport type * as Channel from \"../Channel.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport * as Context from \"../Context.js\"\nimport * as Deferred from \"../Deferred.js\"\nimport * as Effect from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport * as Equal from \"../Equal.js\"\nimport * as Exit from \"../Exit.js\"\nimport * as Fiber from \"../Fiber.js\"\nimport * as FiberRef from \"../FiberRef.js\"\nimport { constVoid, dual, identity, pipe } from \"../Function.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport * as Layer from \"../Layer.js\"\nimport type * as MergeDecision from \"../MergeDecision.js\"\nimport type * as MergeState from \"../MergeState.js\"\nimport type * as MergeStrategy from \"../MergeStrategy.js\"\nimport * as Option from \"../Option.js\"\nimport { hasProperty, type Predicate } from \"../Predicate.js\"\nimport * as PubSub from \"../PubSub.js\"\nimport * as Queue from \"../Queue.js\"\nimport * as Ref from \"../Ref.js\"\nimport * as Scope from \"../Scope.js\"\nimport type * as SingleProducerAsyncInput from \"../SingleProducerAsyncInput.js\"\nimport type * as Tracer from \"../Tracer.js\"\nimport type * as Types from \"../Types.js\"\nimport * as executor from \"./channel/channelExecutor.js\"\nimport type * as ChannelState from \"./channel/channelState.js\"\nimport * as mergeDecision from \"./channel/mergeDecision.js\"\nimport * as mergeState from \"./channel/mergeState.js\"\nimport * as mergeStrategy_ from \"./channel/mergeStrategy.js\"\nimport * as singleProducerAsyncInput from \"./channel/singleProducerAsyncInput.js\"\nimport * as coreEffect from \"./core-effect.js\"\nimport * as core from \"./core-stream.js\"\nimport * as MergeDecisionOpCodes from \"./opCodes/channelMergeDecision.js\"\nimport * as MergeStateOpCodes from \"./opCodes/channelMergeState.js\"\nimport * as ChannelStateOpCodes from \"./opCodes/channelState.js\"\nimport * as tracer from \"./tracer.js\"\n\n/** @internal */\nexport const acquireUseRelease = <Acquired, OutErr, Env, OutElem1, InElem, InErr, OutDone, InDone>(\n  acquire: Effect.Effect<Acquired, OutErr, Env>,\n  use: (a: Acquired) => Channel.Channel<OutElem1, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  release: (a: Acquired, exit: Exit.Exit<OutDone, OutErr>) => Effect.Effect<any, never, Env>\n): Channel.Channel<OutElem1, InElem, OutErr, InErr, OutDone, InDone, Env> =>\n  core.flatMap(\n    core.fromEffect(\n      Ref.make<\n        (exit: Exit.Exit<OutDone, OutErr>) => Effect.Effect<any, never, Env>\n      >(() => Effect.void)\n    ),\n    (ref) =>\n      pipe(\n        core.fromEffect(\n          Effect.uninterruptible(\n            Effect.tap(\n              acquire,\n              (a) => Ref.set(ref, (exit) => release(a, exit))\n            )\n          )\n        ),\n        core.flatMap(use),\n        core.ensuringWith((exit) => Effect.flatMap(Ref.get(ref), (f) => f(exit)))\n      )\n  )\n\n/** @internal */\nexport const as = dual<\n  <OutDone2>(\n    value: OutDone2\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    value: OutDone2\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone2>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  value: OutDone2\n): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env> => map(self, () => value))\n\n/** @internal */\nexport const asVoid = <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n): Channel.Channel<OutElem, InElem, OutErr, InErr, void, InDone, Env> => map(self, constVoid)\n\n/** @internal */\nexport const buffer = <InElem, InErr, InDone>(\n  options: {\n    readonly empty: InElem\n    readonly isEmpty: Predicate<InElem>\n    readonly ref: Ref.Ref<InElem>\n  }\n): Channel.Channel<InElem, InElem, InErr, InErr, InDone, InDone> =>\n  core.suspend(() => {\n    const doBuffer = <InErr, InElem, InDone>(\n      empty: InElem,\n      isEmpty: Predicate<InElem>,\n      ref: Ref.Ref<InElem>\n    ): Channel.Channel<InElem, InElem, InErr, InErr, InDone, InDone> =>\n      unwrap(\n        Ref.modify(ref, (inElem) =>\n          isEmpty(inElem) ?\n            [\n              core.readWith({\n                onInput: (input: InElem) =>\n                  core.flatMap(\n                    core.write(input),\n                    () => doBuffer<InErr, InElem, InDone>(empty, isEmpty, ref)\n                  ),\n                onFailure: (error: InErr) => core.fail(error),\n                onDone: (done: InDone) => core.succeedNow(done)\n              }),\n              inElem\n            ] as const :\n            [\n              core.flatMap(\n                core.write(inElem),\n                () => doBuffer<InErr, InElem, InDone>(empty, isEmpty, ref)\n              ),\n              empty\n            ] as const)\n      )\n    return doBuffer(options.empty, options.isEmpty, options.ref)\n  })\n\n/** @internal */\nexport const bufferChunk = <InElem, InErr, InDone>(\n  ref: Ref.Ref<Chunk.Chunk<InElem>>\n): Channel.Channel<Chunk.Chunk<InElem>, Chunk.Chunk<InElem>, InErr, InErr, InDone, InDone> =>\n  buffer({\n    empty: Chunk.empty(),\n    isEmpty: Chunk.isEmpty,\n    ref\n  })\n\n/** @internal */\nexport const catchAll = dual<\n  <OutErr, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    f: (error: OutErr) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n  ) => <OutElem, InElem, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone1 | OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (error: OutErr) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone1 | OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >\n>(\n  2,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (error: OutErr) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n  ): Channel.Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone | OutDone1,\n    InDone & InDone1,\n    Env | Env1\n  > =>\n    core.catchAllCause(self, (cause) =>\n      Either.match(Cause.failureOrCause(cause), {\n        onLeft: f,\n        onRight: core.failCause\n      }))\n)\n\n/** @internal */\nexport const concatMap = dual<\n  <OutElem, OutElem2, InElem2, OutErr2, InErr2, X, InDone2, Env2>(\n    f: (o: OutElem) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, X, InDone2, Env2>\n  ) => <Env, InErr, InElem, InDone, OutErr, OutDone>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem2,\n    InElem & InElem2,\n    OutErr2 | OutErr,\n    InErr & InErr2,\n    unknown,\n    InDone & InDone2,\n    Env2 | Env\n  >,\n  <Env, InErr, InElem, InDone, OutErr, OutDone, OutElem, OutElem2, Env2, InErr2, InElem2, InDone2, OutErr2, X>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (o: OutElem) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, X, InDone2, Env2>\n  ) => Channel.Channel<\n    OutElem2,\n    InElem & InElem2,\n    OutErr2 | OutErr,\n    InErr & InErr2,\n    unknown,\n    InDone & InDone2,\n    Env2 | Env\n  >\n>(2, <Env, InErr, InElem, InDone, OutErr, OutDone, OutElem, OutElem2, Env2, InErr2, InElem2, InDone2, OutErr2, X>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (o: OutElem) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, X, InDone2, Env2>\n): Channel.Channel<\n  OutElem2,\n  InElem & InElem2,\n  OutErr | OutErr2,\n  InErr & InErr2,\n  unknown,\n  InDone & InDone2,\n  Env | Env2\n> => core.concatMapWith(self, f, () => void 0, () => void 0))\n\n/** @internal */\nexport const collect = dual<\n  <OutElem, OutElem2>(\n    pf: (o: OutElem) => Option.Option<OutElem2>\n  ) => <InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem>\n  ) => Channel.Channel<OutElem2, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    pf: (o: OutElem) => Option.Option<OutElem2>\n  ) => Channel.Channel<OutElem2, InElem, OutErr, InErr, OutDone, InDone, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  pf: (o: OutElem) => Option.Option<OutElem2>\n): Channel.Channel<OutElem2, InElem, OutErr, InErr, OutDone, InDone, Env> => {\n  const collector: Channel.Channel<OutElem2, OutElem, OutErr, OutErr, OutDone, OutDone, Env> = core\n    .readWith({\n      onInput: (out) =>\n        Option.match(pf(out), {\n          onNone: () => collector,\n          onSome: (out2) => core.flatMap(core.write(out2), () => collector)\n        }),\n      onFailure: core.fail,\n      onDone: core.succeedNow\n    })\n  return core.pipeTo(self, collector)\n})\n\n/** @internal */\nexport const concatOut = <OutElem, InElem, OutErr, InErr, InDone, Env, OutDone>(\n  self: Channel.Channel<\n    Channel.Channel<OutElem, InElem, OutErr, InErr, unknown, InDone, Env>,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env\n  >\n): Channel.Channel<OutElem, InElem, OutErr, InErr, unknown, InDone, Env> => core.concatAll(self)\n\n/** @internal */\nexport const mapInput = dual<\n  <InDone0, InDone>(\n    f: (a: InDone0) => InDone\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone0, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InDone0>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (a: InDone0) => InDone\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone0, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InDone0>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (a: InDone0) => InDone\n): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone0, Env> => {\n  const reader: Channel.Channel<InElem, InElem, InErr, InErr, InDone, InDone0> = core.readWith({\n    onInput: (inElem: InElem) => core.flatMap(core.write(inElem), () => reader),\n    onFailure: core.fail,\n    onDone: (done: InDone0) => core.succeedNow(f(done))\n  })\n  return core.pipeTo(reader, self)\n})\n\n/** @internal */\nexport const mapInputEffect = dual<\n  <InDone0, InDone, InErr, Env1>(\n    f: (i: InDone0) => Effect.Effect<InDone, InErr, Env1>\n  ) => <OutElem, InElem, OutErr, OutDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone0, Env1 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InDone0, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (i: InDone0) => Effect.Effect<InDone, InErr, Env1>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone0, Env1 | Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InDone0, Env1>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (i: InDone0) => Effect.Effect<InDone, InErr, Env1>\n): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone0, Env | Env1> => {\n  const reader: Channel.Channel<InElem, InElem, InErr, InErr, InDone, InDone0, Env1> = core.readWith({\n    onInput: (inElem) => core.flatMap(core.write(inElem), () => reader),\n    onFailure: core.fail,\n    onDone: (done) => core.fromEffect(f(done))\n  })\n  return core.pipeTo(reader, self)\n})\n\n/** @internal */\nexport const mapInputError = dual<\n  <InErr0, InErr>(\n    f: (a: InErr0) => InErr\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr0, OutDone, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InErr0>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (a: InErr0) => InErr\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr0, OutDone, InDone, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InErr0>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (a: InErr0) => InErr\n): Channel.Channel<OutElem, InElem, OutErr, InErr0, OutDone, InDone, Env> => {\n  const reader: Channel.Channel<InElem, InElem, InErr, InErr0, InDone, InDone> = core.readWith({\n    onInput: (inElem: InElem) => core.flatMap(core.write(inElem), () => reader),\n    onFailure: (error) => core.fail(f(error)),\n    onDone: core.succeedNow\n  })\n  return core.pipeTo(reader, self)\n})\n\n/** @internal */\nexport const mapInputErrorEffect = dual<\n  <InErr0, InDone, InErr, Env1>(\n    f: (error: InErr0) => Effect.Effect<InDone, InErr, Env1>\n  ) => <OutElem, InElem, OutErr, OutDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr0, OutDone, InDone, Env1 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InErr0, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (error: InErr0) => Effect.Effect<InDone, InErr, Env1>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr0, OutDone, InDone, Env1 | Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InErr0, Env1>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (error: InErr0) => Effect.Effect<InDone, InErr, Env1>\n): Channel.Channel<OutElem, InElem, OutErr, InErr0, OutDone, InDone, Env | Env1> => {\n  const reader: Channel.Channel<InElem, InElem, InErr, InErr0, InDone, InDone, Env1> = core.readWith({\n    onInput: (inElem) => core.flatMap(core.write(inElem), () => reader),\n    onFailure: (error) => core.fromEffect(f(error)),\n    onDone: core.succeedNow\n  })\n  return core.pipeTo(reader, self)\n})\n\n/** @internal */\nexport const mapInputIn = dual<\n  <InElem0, InElem>(\n    f: (a: InElem0) => InElem\n  ) => <OutElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem0, OutErr, InErr, OutDone, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InElem0>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (a: InElem0) => InElem\n  ) => Channel.Channel<OutElem, InElem0, OutErr, InErr, OutDone, InDone, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InElem0>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (a: InElem0) => InElem\n): Channel.Channel<OutElem, InElem0, OutErr, InErr, OutDone, InDone, Env> => {\n  const reader: Channel.Channel<InElem, InElem0, InErr, InErr, InDone, InDone> = core.readWith({\n    onInput: (inElem) => core.flatMap(core.write(f(inElem)), () => reader),\n    onFailure: core.fail,\n    onDone: core.succeedNow\n  })\n  return core.pipeTo(reader, self)\n})\n\n/** @internal */\nexport const mapInputInEffect = dual<\n  <InElem0, InElem, InErr, Env1>(\n    f: (a: InElem0) => Effect.Effect<InElem, InErr, Env1>\n  ) => <OutElem, OutErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem0, OutErr, InErr, OutDone, InDone, Env1 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InElem0, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (a: InElem0) => Effect.Effect<InElem, InErr, Env1>\n  ) => Channel.Channel<OutElem, InElem0, OutErr, InErr, OutDone, InDone, Env1 | Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, InElem0, Env1>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (a: InElem0) => Effect.Effect<InElem, InErr, Env1>\n): Channel.Channel<OutElem, InElem0, OutErr, InErr, OutDone, InDone, Env | Env1> => {\n  const reader: Channel.Channel<InElem, InElem0, InErr, InErr, InDone, InDone, Env1> = core.readWith({\n    onInput: (inElem) => core.flatMap(core.flatMap(core.fromEffect(f(inElem)), core.write), () => reader),\n    onFailure: core.fail,\n    onDone: core.succeedNow\n  })\n  return core.pipeTo(reader, self)\n})\n\n/** @internal */\nexport const doneCollect = <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n): Channel.Channel<never, InElem, OutErr, InErr, [Chunk.Chunk<OutElem>, OutDone], InDone, Env> =>\n  core.suspend(() => {\n    const builder: Array<OutElem> = []\n    return pipe(\n      core.pipeTo(self, doneCollectReader<Env, OutErr, OutElem, OutDone>(builder)),\n      core.flatMap((outDone) => core.succeed([Chunk.unsafeFromArray(builder), outDone]))\n    )\n  })\n\n/** @internal */\nconst doneCollectReader = <Env, OutErr, OutElem, OutDone>(\n  builder: Array<OutElem>\n): Channel.Channel<never, OutElem, OutErr, OutErr, OutDone, OutDone, Env> => {\n  return core.readWith({\n    onInput: (outElem) =>\n      core.flatMap(\n        core.sync(() => {\n          builder.push(outElem)\n        }),\n        () => doneCollectReader<Env, OutErr, OutElem, OutDone>(builder)\n      ),\n    onFailure: core.fail,\n    onDone: core.succeed\n  })\n}\n\n/** @internal */\nexport const drain = <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n): Channel.Channel<never, InElem, OutErr, InErr, OutDone, InDone, Env> => {\n  const drainer: Channel.Channel<never, OutElem, OutErr, OutErr, OutDone, OutDone, Env> = core\n    .readWithCause({\n      onInput: () => drainer,\n      onFailure: core.failCause,\n      onDone: core.succeed\n    })\n  return core.pipeTo(self, drainer)\n}\n\n/** @internal */\nexport const emitCollect = <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n): Channel.Channel<[Chunk.Chunk<OutElem>, OutDone], InElem, OutErr, InErr, void, InDone, Env> =>\n  core.flatMap(doneCollect(self), core.write)\n\n/** @internal */\nexport const ensuring = dual<\n  <Z, Env1>(\n    finalizer: Effect.Effect<Z, never, Env1>\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env1 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, Z, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    finalizer: Effect.Effect<Z, never, Env1>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env1 | Env>\n>(2, <Env, InErr, InElem, InDone, OutErr, OutElem, OutDone, Env1, Z>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  finalizer: Effect.Effect<Z, never, Env1>\n): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env | Env1> =>\n  core.ensuringWith(self, () => finalizer))\n\n/** @internal */\nexport const context = <Env>(): Channel.Channel<never, unknown, never, unknown, Context.Context<Env>, unknown, Env> =>\n  core.fromEffect(Effect.context<Env>())\n\n/** @internal */\nexport const contextWith = <Env, OutDone>(\n  f: (env: Context.Context<Env>) => OutDone\n): Channel.Channel<never, unknown, never, unknown, OutDone, unknown, Env> => map(context<Env>(), f)\n\n/** @internal */\nexport const contextWithChannel = <\n  Env,\n  OutElem,\n  InElem,\n  OutErr,\n  InErr,\n  OutDone,\n  InDone,\n  Env1\n>(\n  f: (env: Context.Context<Env>) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env1>\n): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env | Env1> => core.flatMap(context<Env>(), f)\n\n/** @internal */\nexport const contextWithEffect = <Env, OutDone, OutErr, Env1>(\n  f: (env: Context.Context<Env>) => Effect.Effect<OutDone, OutErr, Env1>\n): Channel.Channel<never, unknown, OutErr, unknown, OutDone, unknown, Env | Env1> => mapEffect(context<Env>(), f)\n\n/** @internal */\nexport const flatten = <\n  OutElem,\n  InElem,\n  OutErr,\n  InErr,\n  OutElem1,\n  InElem1,\n  OutErr1,\n  InErr1,\n  OutDone2,\n  InDone1,\n  Env1,\n  InDone,\n  Env\n>(\n  self: Channel.Channel<\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>,\n    InDone,\n    Env\n  >\n): Channel.Channel<\n  OutElem | OutElem1,\n  InElem & InElem1,\n  OutErr | OutErr1,\n  InErr & InErr1,\n  OutDone2,\n  InDone & InDone1,\n  Env | Env1\n> => core.flatMap(self, identity)\n\n/** @internal */\nexport const foldChannel = dual<\n  <\n    OutErr,\n    OutElem1,\n    InElem1,\n    OutErr1,\n    InErr1,\n    OutDone1,\n    InDone1,\n    Env1,\n    OutDone,\n    OutElem2,\n    InElem2,\n    OutErr2,\n    InErr2,\n    OutDone2,\n    InDone2,\n    Env2\n  >(\n    options: {\n      readonly onFailure: (\n        error: OutErr\n      ) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n      readonly onSuccess: (\n        done: OutDone\n      ) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone2, InDone2, Env2>\n    }\n  ) => <Env, InErr, InElem, InDone, OutElem>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1 | OutElem2 | OutElem,\n    InElem & InElem1 & InElem2,\n    OutErr1 | OutErr2,\n    InErr & InErr1 & InErr2,\n    OutDone1 | OutDone2,\n    InDone & InDone1 & InDone2,\n    Env1 | Env2 | Env\n  >,\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env,\n    OutElem1,\n    InElem1,\n    OutErr1,\n    InErr1,\n    OutDone1,\n    InDone1,\n    Env1,\n    OutElem2,\n    InElem2,\n    OutErr2,\n    InErr2,\n    OutDone2,\n    InDone2,\n    Env2\n  >(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    options: {\n      readonly onFailure: (\n        error: OutErr\n      ) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n      readonly onSuccess: (\n        done: OutDone\n      ) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone2, InDone2, Env2>\n    }\n  ) => Channel.Channel<\n    OutElem1 | OutElem2 | OutElem,\n    InElem & InElem1 & InElem2,\n    OutErr1 | OutErr2,\n    InErr & InErr1 & InErr2,\n    OutDone1 | OutDone2,\n    InDone & InDone1 & InDone2,\n    Env1 | Env2 | Env\n  >\n>(2, <\n  OutElem,\n  InElem,\n  OutErr,\n  InErr,\n  OutDone,\n  InDone,\n  Env,\n  OutElem1,\n  InElem1,\n  OutErr1,\n  InErr1,\n  OutDone1,\n  InDone1,\n  Env1,\n  OutElem2,\n  InElem2,\n  OutErr2,\n  InErr2,\n  OutDone2,\n  InDone2,\n  Env2\n>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  options: {\n    readonly onFailure: (error: OutErr) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n    readonly onSuccess: (done: OutDone) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone2, InDone2, Env2>\n  }\n): Channel.Channel<\n  OutElem | OutElem2 | OutElem1,\n  InElem & InElem1 & InElem2,\n  OutErr2 | OutErr1,\n  InErr & InErr1 & InErr2,\n  OutDone2 | OutDone1,\n  InDone & InDone1 & InDone2,\n  Env | Env1 | Env2\n> =>\n  core.foldCauseChannel(self, {\n    onFailure: (cause) => {\n      const either = Cause.failureOrCause(cause)\n      switch (either._tag) {\n        case \"Left\": {\n          return options.onFailure(either.left)\n        }\n        case \"Right\": {\n          return core.failCause(either.right)\n        }\n      }\n    },\n    onSuccess: options.onSuccess\n  }))\n\n/** @internal */\nexport const fromEither = <R, L>(\n  either: Either.Either<R, L>\n): Channel.Channel<never, unknown, L, unknown, R, unknown> =>\n  core.suspend(() => Either.match(either, { onLeft: core.fail, onRight: core.succeed }))\n\n/** @internal */\nexport const fromInput = <Err, Elem, Done>(\n  input: SingleProducerAsyncInput.AsyncInputConsumer<Err, Elem, Done>\n): Channel.Channel<Elem, unknown, Err, unknown, Done, unknown> =>\n  unwrap(\n    input.takeWith(\n      core.failCause,\n      (elem) => core.flatMap(core.write(elem), () => fromInput(input)),\n      core.succeed\n    )\n  )\n\n/** @internal */\nexport const fromPubSub = <Done, Err, Elem>(\n  pubsub: PubSub.PubSub<Either.Either<Elem, Exit.Exit<Done, Err>>>\n): Channel.Channel<Elem, unknown, Err, unknown, Done, unknown> =>\n  unwrapScoped(Effect.map(PubSub.subscribe(pubsub), fromQueue))\n\n/** @internal */\nexport const fromPubSubScoped = <Done, Err, Elem>(\n  pubsub: PubSub.PubSub<Either.Either<Elem, Exit.Exit<Done, Err>>>\n): Effect.Effect<Channel.Channel<Elem, unknown, Err, unknown, Done, unknown>, never, Scope.Scope> =>\n  Effect.map(PubSub.subscribe(pubsub), fromQueue)\n\n/** @internal */\nexport const fromOption = <A>(\n  option: Option.Option<A>\n): Channel.Channel<never, unknown, Option.Option<never>, unknown, A, unknown> =>\n  core.suspend(() =>\n    Option.match(option, {\n      onNone: () => core.fail(Option.none()),\n      onSome: core.succeed\n    })\n  )\n\n/** @internal */\nexport const fromQueue = <Done, Err, Elem>(\n  queue: Queue.Dequeue<Either.Either<Elem, Exit.Exit<Done, Err>>>\n): Channel.Channel<Elem, unknown, Err, unknown, Done, unknown> => core.suspend(() => fromQueueInternal(queue))\n\n/** @internal */\nconst fromQueueInternal = <Done, Err, Elem>(\n  queue: Queue.Dequeue<Either.Either<Elem, Exit.Exit<Done, Err>>>\n): Channel.Channel<Elem, unknown, Err, unknown, Done, unknown> =>\n  pipe(\n    core.fromEffect(Queue.take(queue)),\n    core.flatMap(Either.match({\n      onLeft: Exit.match({\n        onFailure: core.failCause,\n        onSuccess: core.succeedNow\n      }),\n      onRight: (elem) =>\n        core.flatMap(\n          core.write(elem),\n          () => fromQueueInternal(queue)\n        )\n    }))\n  )\n\n/** @internal */\nexport const identityChannel = <Elem, Err, Done>(): Channel.Channel<Elem, Elem, Err, Err, Done, Done> =>\n  core.readWith({\n    onInput: (input: Elem) => core.flatMap(core.write(input), () => identityChannel()),\n    onFailure: core.fail,\n    onDone: core.succeedNow\n  })\n\n/** @internal */\nexport const interruptWhen = dual<\n  <OutDone1, OutErr1, Env1>(\n    effect: Effect.Effect<OutDone1, OutErr1, Env1>\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr1 | OutErr, InErr, OutDone1 | OutDone, InDone, Env1 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone1, OutErr1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    effect: Effect.Effect<OutDone1, OutErr1, Env1>\n  ) => Channel.Channel<OutElem, InElem, OutErr1 | OutErr, InErr, OutDone1 | OutDone, InDone, Env1 | Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone1, OutErr1, Env1>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  effect: Effect.Effect<OutDone1, OutErr1, Env1>\n): Channel.Channel<OutElem, InElem, OutErr | OutErr1, InErr, OutDone | OutDone1, InDone, Env1 | Env> =>\n  mergeWith(self, {\n    other: core.fromEffect(effect),\n    onSelfDone: (selfDone) => mergeDecision.Done(Effect.suspend(() => selfDone)),\n    onOtherDone: (effectDone) => mergeDecision.Done(Effect.suspend(() => effectDone))\n  }))\n\n/** @internal */\nexport const interruptWhenDeferred = dual<\n  <OutDone1, OutErr1>(\n    deferred: Deferred.Deferred<OutDone1, OutErr1>\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr1 | OutErr, InErr, OutDone1 | OutDone, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone1, OutErr1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    deferred: Deferred.Deferred<OutDone1, OutErr1>\n  ) => Channel.Channel<OutElem, InElem, OutErr1 | OutErr, InErr, OutDone1 | OutDone, InDone, Env>\n>(2, <Env, InErr, InElem, InDone, OutErr, OutElem, OutDone, OutErr1, OutDone1>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  deferred: Deferred.Deferred<OutDone1, OutErr1>\n): Channel.Channel<OutElem, InElem, OutErr | OutErr1, InErr, OutDone | OutDone1, InDone, Env> =>\n  interruptWhen(self, Deferred.await(deferred)))\n\n/** @internal */\nexport const map = dual<\n  <OutDone, OutDone2>(\n    f: (out: OutDone) => OutDone2\n  ) => <OutElem, InElem, OutErr, InErr, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (out: OutDone) => OutDone2\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>\n>(2, <Env, InErr, InElem, InDone, OutErr, OutElem, OutDone, OutDone2>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (out: OutDone) => OutDone2\n): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env> =>\n  core.flatMap(self, (a) => core.sync(() => f(a))))\n\n/** @internal */\nexport const mapEffect = dual<\n  <OutDone, OutDone1, OutErr1, Env1>(\n    f: (o: OutDone) => Effect.Effect<OutDone1, OutErr1, Env1>\n  ) => <OutElem, InElem, OutErr, InErr, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr1 | OutErr, InErr, OutDone1, InDone, Env1 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone1, OutErr1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (o: OutDone) => Effect.Effect<OutDone1, OutErr1, Env1>\n  ) => Channel.Channel<OutElem, InElem, OutErr1 | OutErr, InErr, OutDone1, InDone, Env1 | Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutDone1, OutErr1, Env1>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (o: OutDone) => Effect.Effect<OutDone1, OutErr1, Env1>\n): Channel.Channel<OutElem, InElem, OutErr | OutErr1, InErr, OutDone1, InDone, Env | Env1> =>\n  core.flatMap(self, (z) => core.fromEffect(f(z))))\n\n/** @internal */\nexport const mapError = dual<\n  <OutErr, OutErr2>(\n    f: (err: OutErr) => OutErr2\n  ) => <OutElem, InElem, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutErr2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (err: OutErr) => OutErr2\n  ) => Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone, InDone, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutErr2>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (err: OutErr) => OutErr2\n): Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone, InDone, Env> => mapErrorCause(self, Cause.map(f)))\n\n/** @internal */\nexport const mapErrorCause = dual<\n  <OutErr, OutErr2>(\n    f: (cause: Cause.Cause<OutErr>) => Cause.Cause<OutErr2>\n  ) => <OutElem, InElem, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutErr2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (cause: Cause.Cause<OutErr>) => Cause.Cause<OutErr2>\n  ) => Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone, InDone, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutErr2>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (cause: Cause.Cause<OutErr>) => Cause.Cause<OutErr2>\n): Channel.Channel<OutElem, InElem, OutErr2, InErr, OutDone, InDone, Env> =>\n  core.catchAllCause(self, (cause) => core.failCause(f(cause))))\n\n/** @internal */\nexport const mapOut = dual<\n  <OutElem, OutElem2>(\n    f: (o: OutElem) => OutElem2\n  ) => <InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem2, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (o: OutElem) => OutElem2\n  ) => Channel.Channel<OutElem2, InElem, OutErr, InErr, OutDone, InDone, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (o: OutElem) => OutElem2\n): Channel.Channel<OutElem2, InElem, OutErr, InErr, OutDone, InDone, Env> => {\n  const reader: Channel.Channel<OutElem2, OutElem, OutErr, OutErr, OutDone, OutDone, Env> = core\n    .readWith({\n      onInput: (outElem) => core.flatMap(core.write(f(outElem)), () => reader),\n      onFailure: core.fail,\n      onDone: core.succeedNow\n    })\n  return core.pipeTo(self, reader)\n})\n\n/** @internal */\nexport const mapOutEffect = dual<\n  <OutElem, OutElem1, OutErr1, Env1>(\n    f: (o: OutElem) => Effect.Effect<OutElem1, OutErr1, Env1>\n  ) => <InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem1, InElem, OutErr1 | OutErr, InErr, OutDone, InDone, Env1 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, OutErr1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (o: OutElem) => Effect.Effect<OutElem1, OutErr1, Env1>\n  ) => Channel.Channel<OutElem1, InElem, OutErr1 | OutErr, InErr, OutDone, InDone, Env1 | Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, OutErr1, Env1>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (o: OutElem) => Effect.Effect<OutElem1, OutErr1, Env1>\n): Channel.Channel<OutElem1, InElem, OutErr | OutErr1, InErr, OutDone, InDone, Env | Env1> => {\n  const reader: Channel.Channel<OutElem1, OutElem, OutErr | OutErr1, OutErr, OutDone, OutDone, Env | Env1> = core\n    .readWithCause({\n      onInput: (outElem) =>\n        pipe(\n          core.fromEffect(f(outElem)),\n          core.flatMap(core.write),\n          core.flatMap(() => reader)\n        ),\n      onFailure: core.failCause,\n      onDone: core.succeedNow\n    })\n  return core.pipeTo(self, reader)\n})\n\n/** @internal */\nexport const mapOutEffectPar = dual<\n  <OutElem, OutElem1, OutErr1, Env1>(\n    f: (o: OutElem) => Effect.Effect<OutElem1, OutErr1, Env1>,\n    n: number\n  ) => <InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem1, InElem, OutErr1 | OutErr, InErr, OutDone, InDone, Env1 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, OutErr1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (o: OutElem) => Effect.Effect<OutElem1, OutErr1, Env1>,\n    n: number\n  ) => Channel.Channel<OutElem1, InElem, OutErr1 | OutErr, InErr, OutDone, InDone, Env1 | Env>\n>(3, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, OutErr1, Env1>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (o: OutElem) => Effect.Effect<OutElem1, OutErr1, Env1>,\n  n: number\n): Channel.Channel<OutElem1, InElem, OutErr | OutErr1, InErr, OutDone, InDone, Env | Env1> =>\n  unwrapScopedWith(\n    (scope) =>\n      Effect.gen(function*() {\n        const input = yield* singleProducerAsyncInput.make<InErr, InElem, InDone>()\n        const queueReader = fromInput(input)\n        const queue = yield* Queue.bounded<Effect.Effect<Either.Either<OutElem1, OutDone>, OutErr | OutErr1, Env1>>(n)\n        yield* Scope.addFinalizer(scope, Queue.shutdown(queue))\n        const errorSignal = yield* Deferred.make<never, OutErr1>()\n        const withPermits = n === Number.POSITIVE_INFINITY ?\n          ((_: number) => identity) :\n          (yield* Effect.makeSemaphore(n)).withPermits\n        const pull = yield* queueReader.pipe(core.pipeTo(self), toPullIn(scope))\n        yield* pull.pipe(\n          Effect.matchCauseEffect({\n            onFailure: (cause) => Queue.offer(queue, Effect.failCause(cause)),\n            onSuccess: Either.match({\n              onLeft: (outDone) =>\n                Effect.zipRight(\n                  Effect.interruptible(withPermits(n)(Effect.void)),\n                  Effect.asVoid(Queue.offer(queue, Effect.succeed(Either.left(outDone))))\n                ),\n              onRight: (outElem) =>\n                Effect.gen(function*() {\n                  const deferred = yield* Deferred.make<OutElem1, OutErr1>()\n                  const latch = yield* Deferred.make<void>()\n                  yield* Queue.offer(queue, Effect.map(Deferred.await(deferred), Either.right))\n                  yield* Deferred.succeed(latch, void 0).pipe(\n                    Effect.zipRight(\n                      Effect.uninterruptibleMask((restore) =>\n                        Effect.exit(restore(Deferred.await(errorSignal))).pipe(\n                          Effect.raceFirst(Effect.exit(restore(f(outElem)))),\n                          Effect.flatMap(identity)\n                        )\n                      ).pipe(\n                        Effect.tapErrorCause((cause) => Deferred.failCause(errorSignal, cause)),\n                        Effect.intoDeferred(deferred)\n                      )\n                    ),\n                    withPermits(1),\n                    Effect.forkIn(scope)\n                  )\n                  yield* Deferred.await(latch)\n                })\n            })\n          }),\n          Effect.forever,\n          Effect.interruptible,\n          Effect.forkIn(scope)\n        )\n        const consumer: Channel.Channel<OutElem1, unknown, OutErr | OutErr1, unknown, OutDone, unknown, Env1> = unwrap(\n          Effect.matchCause(Effect.flatten(Queue.take(queue)), {\n            onFailure: core.failCause,\n            onSuccess: Either.match({\n              onLeft: core.succeedNow,\n              onRight: (outElem) => core.flatMap(core.write(outElem), () => consumer)\n            })\n          })\n        )\n        return core.embedInput(consumer, input)\n      })\n  ))\n\n/** @internal */\nexport const mergeAll = (\n  options: {\n    readonly concurrency: number | \"unbounded\"\n    readonly bufferSize?: number | undefined\n    readonly mergeStrategy?: MergeStrategy.MergeStrategy | undefined\n  }\n) => {\n  return <\n    OutElem,\n    InElem1,\n    OutErr1,\n    InErr1,\n    InDone1,\n    Env1,\n    InElem,\n    OutErr,\n    InErr,\n    InDone,\n    Env\n  >(\n    channels: Channel.Channel<\n      Channel.Channel<OutElem, InElem1, OutErr1, InErr1, unknown, InDone1, Env1>,\n      InElem,\n      OutErr,\n      InErr,\n      unknown,\n      InDone,\n      Env\n    >\n  ): Channel.Channel<\n    OutElem,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    unknown,\n    InDone & InDone1,\n    Env | Env1\n  > => mergeAllWith(options)(channels, constVoid)\n}\n\n/** @internal */\nexport const mergeAllUnbounded = <\n  OutElem,\n  InElem1,\n  OutErr1,\n  InErr1,\n  InDone1,\n  Env1,\n  InElem,\n  OutErr,\n  InErr,\n  InDone,\n  Env\n>(\n  channels: Channel.Channel<\n    Channel.Channel<OutElem, InElem1, OutErr1, InErr1, unknown, InDone1, Env1>,\n    InElem,\n    OutErr,\n    InErr,\n    unknown,\n    InDone,\n    Env\n  >\n): Channel.Channel<\n  OutElem,\n  InElem & InElem1,\n  OutErr | OutErr1,\n  InErr & InErr1,\n  unknown,\n  InDone & InDone1,\n  Env | Env1\n> => mergeAllWith({ concurrency: \"unbounded\" })(channels, constVoid)\n\n/** @internal */\nexport const mergeAllUnboundedWith = <\n  OutElem,\n  InElem1,\n  OutErr1,\n  InErr1,\n  OutDone,\n  InDone1,\n  Env1,\n  InElem,\n  OutErr,\n  InErr,\n  InDone,\n  Env\n>(\n  channels: Channel.Channel<\n    Channel.Channel<OutElem, InElem1, OutErr1, InErr1, OutDone, InDone1, Env1>,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env\n  >,\n  f: (o1: OutDone, o2: OutDone) => OutDone\n): Channel.Channel<\n  OutElem,\n  InElem & InElem1,\n  OutErr | OutErr1,\n  InErr & InErr1,\n  OutDone,\n  InDone & InDone1,\n  Env | Env1\n> => mergeAllWith({ concurrency: \"unbounded\" })(channels, f)\n\n/** @internal */\nexport const mergeAllWith = (\n  {\n    bufferSize = 16,\n    concurrency,\n    mergeStrategy = mergeStrategy_.BackPressure()\n  }: {\n    readonly concurrency: number | \"unbounded\"\n    readonly bufferSize?: number | undefined\n    readonly mergeStrategy?: MergeStrategy.MergeStrategy | undefined\n  }\n) =>\n<OutElem, InElem1, OutErr1, InErr1, OutDone, InDone1, Env1, InElem, OutErr, InErr, InDone, Env>(\n  channels: Channel.Channel<\n    Channel.Channel<OutElem, InElem1, OutErr1, InErr1, OutDone, InDone1, Env1>,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env\n  >,\n  f: (o1: OutDone, o2: OutDone) => OutDone\n): Channel.Channel<\n  OutElem,\n  InElem & InElem1,\n  OutErr | OutErr1,\n  InErr & InErr1,\n  OutDone,\n  InDone & InDone1,\n  Env | Env1\n> =>\n  unwrapScopedWith(\n    (scope) =>\n      Effect.gen(function*() {\n        const concurrencyN = concurrency === \"unbounded\" ? Number.MAX_SAFE_INTEGER : concurrency\n        const input = yield* singleProducerAsyncInput.make<\n          InErr & InErr1,\n          InElem & InElem1,\n          InDone & InDone1\n        >()\n        const queueReader = fromInput(input)\n        const queue = yield* Queue.bounded<Effect.Effect<Either.Either<OutElem, OutDone>, OutErr | OutErr1, Env>>(\n          bufferSize\n        )\n        yield* Scope.addFinalizer(scope, Queue.shutdown(queue))\n        const cancelers = yield* Queue.unbounded<Deferred.Deferred<void>>()\n        yield* Scope.addFinalizer(scope, Queue.shutdown(cancelers))\n        const lastDone = yield* Ref.make<Option.Option<OutDone>>(Option.none())\n        const errorSignal = yield* Deferred.make<void>()\n        const withPermits = (yield* Effect.makeSemaphore(concurrencyN)).withPermits\n        const pull = yield* toPullIn(core.pipeTo(queueReader, channels), scope)\n\n        function evaluatePull(\n          pull: Effect.Effect<\n            Either.Either<OutElem, OutDone>,\n            OutErr | OutErr1,\n            Env | Env1\n          >\n        ) {\n          return pull.pipe(\n            Effect.flatMap(Either.match({\n              onLeft: (done) => Effect.succeed(Option.some(done)),\n              onRight: (outElem) =>\n                Effect.as(\n                  Queue.offer(queue, Effect.succeed(Either.right(outElem))),\n                  Option.none()\n                )\n            })),\n            Effect.repeat({ until: (_): _ is Option.Some<OutDone> => Option.isSome(_) }),\n            Effect.flatMap((outDone) =>\n              Ref.update(\n                lastDone,\n                Option.match({\n                  onNone: () => Option.some(outDone.value),\n                  onSome: (lastDone) => Option.some(f(lastDone, outDone.value))\n                })\n              )\n            ),\n            Effect.catchAllCause((cause) =>\n              Cause.isInterrupted(cause)\n                ? Effect.failCause(cause)\n                : Queue.offer(queue, Effect.failCause(cause)).pipe(\n                  Effect.zipRight(Deferred.succeed(errorSignal, void 0)),\n                  Effect.asVoid\n                )\n            )\n          )\n        }\n\n        yield* pull.pipe(\n          Effect.matchCauseEffect({\n            onFailure: (cause) =>\n              Queue.offer(queue, Effect.failCause(cause)).pipe(\n                Effect.zipRight(Effect.succeed(false))\n              ),\n            onSuccess: Either.match({\n              onLeft: (outDone) =>\n                Effect.raceWith(\n                  Effect.interruptible(Deferred.await(errorSignal)),\n                  Effect.interruptible(withPermits(concurrencyN)(Effect.void)),\n                  {\n                    onSelfDone: (_, permitAcquisition) => Effect.as(Fiber.interrupt(permitAcquisition), false),\n                    onOtherDone: (_, failureAwait) =>\n                      Effect.zipRight(\n                        Fiber.interrupt(failureAwait),\n                        Ref.get(lastDone).pipe(\n                          Effect.flatMap(Option.match({\n                            onNone: () => Queue.offer(queue, Effect.succeed(Either.left(outDone))),\n                            onSome: (lastDone) => Queue.offer(queue, Effect.succeed(Either.left(f(lastDone, outDone))))\n                          })),\n                          Effect.as(false)\n                        )\n                      )\n                  }\n                ),\n              onRight: (channel) =>\n                mergeStrategy_.match(mergeStrategy, {\n                  onBackPressure: () =>\n                    Effect.gen(function*() {\n                      const latch = yield* Deferred.make<void>()\n                      const raceEffects = Effect.scopedWith((scope) =>\n                        toPullIn(core.pipeTo(queueReader, channel), scope).pipe(\n                          Effect.flatMap((pull) =>\n                            Effect.race(\n                              Effect.exit(evaluatePull(pull)),\n                              Effect.exit(Effect.interruptible(Deferred.await(errorSignal)))\n                            )\n                          ),\n                          Effect.flatMap(identity)\n                        )\n                      )\n                      yield* Deferred.succeed(latch, void 0).pipe(\n                        Effect.zipRight(raceEffects),\n                        withPermits(1),\n                        Effect.forkIn(scope)\n                      )\n                      yield* Deferred.await(latch)\n                      const errored = yield* Deferred.isDone(errorSignal)\n                      return !errored\n                    }),\n                  onBufferSliding: () =>\n                    Effect.gen(function*() {\n                      const canceler = yield* Deferred.make<void>()\n                      const latch = yield* Deferred.make<void>()\n                      const size = yield* Queue.size(cancelers)\n                      yield* Queue.take(cancelers).pipe(\n                        Effect.flatMap((canceler) => Deferred.succeed(canceler, void 0)),\n                        Effect.when(() => size >= concurrencyN)\n                      )\n                      yield* Queue.offer(cancelers, canceler)\n                      const raceEffects = Effect.scopedWith((scope) =>\n                        toPullIn(core.pipeTo(queueReader, channel), scope).pipe(\n                          Effect.flatMap((pull) =>\n                            Effect.exit(evaluatePull(pull)).pipe(\n                              Effect.race(Effect.exit(Effect.interruptible(Deferred.await(errorSignal)))),\n                              Effect.race(Effect.exit(Effect.interruptible(Deferred.await(canceler))))\n                            )\n                          ),\n                          Effect.flatMap(identity)\n                        )\n                      )\n                      yield* Deferred.succeed(latch, void 0).pipe(\n                        Effect.zipRight(raceEffects),\n                        withPermits(1),\n                        Effect.forkIn(scope)\n                      )\n                      yield* Deferred.await(latch)\n                      const errored = yield* Deferred.isDone(errorSignal)\n                      return !errored\n                    })\n                })\n            })\n          }),\n          Effect.repeat({ while: (_) => _ }),\n          Effect.forkIn(scope)\n        )\n\n        const consumer: Channel.Channel<OutElem, unknown, OutErr | OutErr1, unknown, OutDone, unknown, Env | Env1> =\n          pipe(\n            Queue.take(queue),\n            Effect.flatten,\n            Effect.matchCause({\n              onFailure: core.failCause,\n              onSuccess: Either.match({\n                onLeft: core.succeedNow,\n                onRight: (outElem) => core.flatMap(core.write(outElem), () => consumer)\n              })\n            }),\n            unwrap\n          )\n\n        return core.embedInput(consumer, input)\n      })\n  )\n\n/** @internal */\nexport const mergeMap = dual<\n  <OutElem, OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>(\n    f: (outElem: OutElem) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>,\n    options: {\n      readonly concurrency: number | \"unbounded\"\n      readonly bufferSize?: number | undefined\n      readonly mergeStrategy?: MergeStrategy.MergeStrategy | undefined\n    }\n  ) => <InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    unknown,\n    InDone & InDone1,\n    Env1 | Env\n  >,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (outElem: OutElem) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>,\n    options: {\n      readonly concurrency: number | \"unbounded\"\n      readonly bufferSize?: number | undefined\n      readonly mergeStrategy?: MergeStrategy.MergeStrategy | undefined\n    }\n  ) => Channel.Channel<\n    OutElem1,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    unknown,\n    InDone & InDone1,\n    Env1 | Env\n  >\n>(3, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (outElem: OutElem) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>,\n  options: {\n    readonly concurrency: number | \"unbounded\"\n    readonly bufferSize?: number | undefined\n    readonly mergeStrategy?: MergeStrategy.MergeStrategy | undefined\n  }\n): Channel.Channel<\n  OutElem1,\n  InElem & InElem1,\n  OutErr | OutErr1,\n  InErr & InErr1,\n  unknown,\n  InDone & InDone1,\n  Env | Env1\n> => mergeAll(options)(mapOut(self, f)))\n\n/** @internal */\nexport const mergeOut = dual<\n  (\n    n: number\n  ) => <OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<\n      Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>,\n      InElem,\n      OutErr,\n      InErr,\n      OutDone,\n      InDone,\n      Env\n    >\n  ) => Channel.Channel<\n    OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    unknown,\n    InDone & InDone1,\n    Env | Env1\n  >,\n  <OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<\n      Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>,\n      InElem,\n      OutErr,\n      InErr,\n      OutDone,\n      InDone,\n      Env\n    >,\n    n: number\n  ) => Channel.Channel<\n    OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    unknown,\n    InDone & InDone1,\n    Env | Env1\n  >\n>(2, <OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<\n    Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, Z, InDone1, Env1>,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env\n  >,\n  n: number\n): Channel.Channel<\n  OutElem1,\n  InElem & InElem1,\n  OutErr | OutErr1,\n  InErr & InErr1,\n  unknown,\n  InDone & InDone1,\n  Env | Env1\n> => mergeAll({ concurrency: n })(mapOut(self, identity)))\n\n/** @internal */\nexport const mergeOutWith = dual<\n  <OutDone1>(\n    n: number,\n    f: (o1: OutDone1, o2: OutDone1) => OutDone1\n  ) => <OutElem1, InElem1, OutErr1, InErr1, InDone1, Env1, InElem, OutErr, InErr, InDone, Env>(\n    self: Channel.Channel<\n      Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n      InElem,\n      OutErr,\n      InErr,\n      OutDone1,\n      InDone,\n      Env\n    >\n  ) => Channel.Channel<\n    OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    OutDone1,\n    InDone & InDone1,\n    Env | Env1\n  >,\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1, InElem, OutErr, InErr, InDone, Env>(\n    self: Channel.Channel<\n      Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n      InElem,\n      OutErr,\n      InErr,\n      OutDone1,\n      InDone,\n      Env\n    >,\n    n: number,\n    f: (o1: OutDone1, o2: OutDone1) => OutDone1\n  ) => Channel.Channel<\n    OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    OutDone1,\n    InDone & InDone1,\n    Env | Env1\n  >\n>(3, <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1, InElem, OutErr, InErr, InDone, Env>(\n  self: Channel.Channel<\n    Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone1,\n    InDone,\n    Env\n  >,\n  n: number,\n  f: (o1: OutDone1, o2: OutDone1) => OutDone1\n): Channel.Channel<\n  OutElem1,\n  InElem & InElem1,\n  OutErr | OutErr1,\n  InErr & InErr1,\n  OutDone1,\n  InDone & InDone1,\n  Env | Env1\n> => mergeAllWith({ concurrency: n })(mapOut(self, identity), f))\n\n/** @internal */\nexport const mergeWith = dual<\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1, OutDone, OutErr, OutErr2, OutDone2, OutErr3, OutDone3>(\n    options: {\n      readonly other: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n      readonly onSelfDone: (\n        exit: Exit.Exit<OutDone, OutErr>\n      ) => MergeDecision.MergeDecision<Env1, OutErr1, OutDone1, OutErr2, OutDone2>\n      readonly onOtherDone: (\n        ex: Exit.Exit<OutDone1, OutErr1>\n      ) => MergeDecision.MergeDecision<Env1, OutErr, OutDone, OutErr3, OutDone3>\n    }\n  ) => <Env, InErr, InElem, InDone, OutElem>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr2 | OutErr3,\n    InErr & InErr1,\n    OutDone2 | OutDone3,\n    InDone & InDone1,\n    Env1 | Env\n  >,\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env,\n    OutElem1,\n    InElem1,\n    OutErr1,\n    InErr1,\n    OutDone1,\n    InDone1,\n    Env1,\n    OutErr2,\n    OutDone2,\n    OutErr3,\n    OutDone3\n  >(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    options: {\n      readonly other: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n      readonly onSelfDone: (\n        exit: Exit.Exit<OutDone, OutErr>\n      ) => MergeDecision.MergeDecision<Env1, OutErr1, OutDone1, OutErr2, OutDone2>\n      readonly onOtherDone: (\n        ex: Exit.Exit<OutDone1, OutErr1>\n      ) => MergeDecision.MergeDecision<Env1, OutErr, OutDone, OutErr3, OutDone3>\n    }\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr2 | OutErr3,\n    InErr & InErr1,\n    OutDone2 | OutDone3,\n    InDone & InDone1,\n    Env1 | Env\n  >\n>(2, <\n  OutElem,\n  InElem,\n  OutErr,\n  InErr,\n  OutDone,\n  InDone,\n  Env,\n  OutElem1,\n  InElem1,\n  OutErr1,\n  InErr1,\n  OutDone1,\n  InDone1,\n  Env1,\n  OutErr2,\n  OutDone2,\n  OutErr3,\n  OutDone3\n>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  options: {\n    readonly other: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n    readonly onSelfDone: (\n      exit: Exit.Exit<OutDone, OutErr>\n    ) => MergeDecision.MergeDecision<Env1, OutErr1, OutDone1, OutErr2, OutDone2>\n    readonly onOtherDone: (\n      ex: Exit.Exit<OutDone1, OutErr1>\n    ) => MergeDecision.MergeDecision<Env1, OutErr, OutDone, OutErr3, OutDone3>\n  }\n): Channel.Channel<\n  OutElem | OutElem1,\n  InElem & InElem1,\n  OutErr2 | OutErr3,\n  InErr & InErr1,\n  OutDone2 | OutDone3,\n  InDone & InDone1,\n  Env1 | Env\n> => {\n  function merge(scope: Scope.Scope) {\n    return Effect.gen(function*() {\n      type State = MergeState.MergeState<\n        Env | Env1,\n        OutErr,\n        OutErr1,\n        OutErr2 | OutErr3,\n        OutElem | OutElem1,\n        OutDone,\n        OutDone1,\n        OutDone2 | OutDone3\n      >\n\n      const input = yield* singleProducerAsyncInput.make<\n        InErr & InErr1,\n        InElem & InElem1,\n        InDone & InDone1\n      >()\n      const queueReader = fromInput(input)\n      const pullL = yield* toPullIn(core.pipeTo(queueReader, self), scope)\n      const pullR = yield* toPullIn(core.pipeTo(queueReader, options.other), scope)\n\n      function handleSide<Err, Done, Err2, Done2>(\n        exit: Exit.Exit<Either.Either<OutElem | OutElem1, Done>, Err>,\n        fiber: Fiber.Fiber<Either.Either<OutElem | OutElem1, Done2>, Err2>,\n        pull: Effect.Effect<Either.Either<OutElem | OutElem1, Done>, Err, Env | Env1>\n      ) {\n        return (\n          done: (\n            ex: Exit.Exit<Done, Err>\n          ) => MergeDecision.MergeDecision<\n            Env | Env1,\n            Err2,\n            Done2,\n            OutErr2 | OutErr3,\n            OutDone2 | OutDone3\n          >,\n          both: (\n            f1: Fiber.Fiber<Either.Either<OutElem | OutElem1, Done>, Err>,\n            f2: Fiber.Fiber<Either.Either<OutElem | OutElem1, Done2>, Err2>\n          ) => State,\n          single: (\n            f: (\n              ex: Exit.Exit<Done2, Err2>\n            ) => Effect.Effect<OutDone2 | OutDone3, OutErr2 | OutErr3, Env | Env1>\n          ) => State\n        ): Effect.Effect<\n          Channel.Channel<\n            OutElem | OutElem1,\n            unknown,\n            OutErr2 | OutErr3,\n            unknown,\n            OutDone2 | OutDone3,\n            unknown,\n            Env | Env1\n          >,\n          never,\n          Env | Env1\n        > => {\n          function onDecision(\n            decision: MergeDecision.MergeDecision<\n              Env | Env1,\n              Err2,\n              Done2,\n              OutErr2 | OutErr3,\n              OutDone2 | OutDone3\n            >\n          ): Effect.Effect<\n            Channel.Channel<\n              OutElem | OutElem1,\n              unknown,\n              OutErr2 | OutErr3,\n              unknown,\n              OutDone2 | OutDone3,\n              unknown,\n              Env | Env1\n            >\n          > {\n            const op = decision as mergeDecision.Primitive\n            if (op._tag === MergeDecisionOpCodes.OP_DONE) {\n              return Effect.succeed(\n                core.fromEffect(\n                  Effect.zipRight(\n                    Fiber.interrupt(fiber),\n                    op.effect\n                  )\n                )\n              )\n            }\n            return Effect.map(\n              Fiber.await(fiber),\n              Exit.match({\n                onFailure: (cause) => core.fromEffect(op.f(Exit.failCause(cause))),\n                onSuccess: Either.match({\n                  onLeft: (done) => core.fromEffect(op.f(Exit.succeed(done))),\n                  onRight: (elem) => zipRight(core.write(elem), go(single(op.f)))\n                })\n              })\n            )\n          }\n\n          return Exit.match(exit, {\n            onFailure: (cause) => onDecision(done(Exit.failCause(cause))),\n            onSuccess: Either.match({\n              onLeft: (z) => onDecision(done(Exit.succeed(z))),\n              onRight: (elem) =>\n                Effect.succeed(\n                  core.flatMap(core.write(elem), () =>\n                    core.flatMap(\n                      core.fromEffect(Effect.forkIn(Effect.interruptible(pull), scope)),\n                      (leftFiber) => go(both(leftFiber, fiber))\n                    ))\n                )\n            })\n          })\n        }\n      }\n\n      function go(\n        state: State\n      ): Channel.Channel<\n        OutElem | OutElem1,\n        unknown,\n        OutErr2 | OutErr3,\n        unknown,\n        OutDone2 | OutDone3,\n        unknown,\n        Env | Env1\n      > {\n        switch (state._tag) {\n          case MergeStateOpCodes.OP_BOTH_RUNNING: {\n            const leftJoin = Effect.interruptible(Fiber.join(state.left))\n            const rightJoin = Effect.interruptible(Fiber.join(state.right))\n            return unwrap(\n              Effect.raceWith(leftJoin, rightJoin, {\n                onSelfDone: (leftExit, rf) =>\n                  Effect.zipRight(\n                    Fiber.interrupt(rf),\n                    handleSide(leftExit, state.right, pullL)(\n                      options.onSelfDone,\n                      mergeState.BothRunning,\n                      (f) => mergeState.LeftDone(f)\n                    )\n                  ),\n                onOtherDone: (rightExit, lf) =>\n                  Effect.zipRight(\n                    Fiber.interrupt(lf),\n                    handleSide(rightExit, state.left, pullR)(\n                      options.onOtherDone as (\n                        ex: Exit.Exit<OutDone1, InErr1 | OutErr1>\n                      ) => MergeDecision.MergeDecision<\n                        Env1 | Env,\n                        OutErr,\n                        OutDone,\n                        OutErr2 | OutErr3,\n                        OutDone2 | OutDone3\n                      >,\n                      (left, right) => mergeState.BothRunning(right, left),\n                      (f) => mergeState.RightDone(f)\n                    )\n                  )\n              })\n            )\n          }\n          case MergeStateOpCodes.OP_LEFT_DONE: {\n            return unwrap(\n              Effect.map(\n                Effect.exit(pullR),\n                Exit.match({\n                  onFailure: (cause) => core.fromEffect(state.f(Exit.failCause(cause))),\n                  onSuccess: Either.match({\n                    onLeft: (done) => core.fromEffect(state.f(Exit.succeed(done))),\n                    onRight: (elem) =>\n                      core.flatMap(\n                        core.write(elem),\n                        () => go(mergeState.LeftDone(state.f))\n                      )\n                  })\n                })\n              )\n            )\n          }\n          case MergeStateOpCodes.OP_RIGHT_DONE: {\n            return unwrap(\n              Effect.map(\n                Effect.exit(pullL),\n                Exit.match({\n                  onFailure: (cause) => core.fromEffect(state.f(Exit.failCause(cause))),\n                  onSuccess: Either.match({\n                    onLeft: (done) => core.fromEffect(state.f(Exit.succeed(done))),\n                    onRight: (elem) =>\n                      core.flatMap(\n                        core.write(elem),\n                        () => go(mergeState.RightDone(state.f))\n                      )\n                  })\n                })\n              )\n            )\n          }\n        }\n      }\n\n      return core.fromEffect(\n        Effect.withFiberRuntime<\n          MergeState.MergeState<\n            Env | Env1,\n            OutErr,\n            OutErr1,\n            OutErr2 | OutErr3,\n            OutElem | OutElem1,\n            OutDone,\n            OutDone1,\n            OutDone2 | OutDone3\n          >,\n          never,\n          Env | Env1\n        >((parent) => {\n          const inherit = Effect.withFiberRuntime<void, never, never>((state) => {\n            ;(state as any).transferChildren((parent as any).scope())\n            return Effect.void\n          })\n          const leftFiber = Effect.interruptible(pullL).pipe(\n            Effect.ensuring(inherit),\n            Effect.forkIn(scope)\n          )\n          const rightFiber = Effect.interruptible(pullR).pipe(\n            Effect.ensuring(inherit),\n            Effect.forkIn(scope)\n          )\n          return Effect.zipWith(\n            leftFiber,\n            rightFiber,\n            (left, right): State =>\n              mergeState.BothRunning<\n                Env | Env1,\n                OutErr,\n                OutErr1,\n                OutErr2 | OutErr3,\n                OutElem | OutElem1,\n                OutDone,\n                OutDone1,\n                OutDone2 | OutDone3\n              >(left, right)\n          )\n        })\n      ).pipe(\n        core.flatMap(go),\n        core.embedInput(input)\n      )\n    })\n  }\n  return unwrapScopedWith(merge)\n})\n\n/** @internal */\nexport const never: Channel.Channel<never, unknown, never, unknown, never, unknown> = core.fromEffect(\n  Effect.never\n)\n\n/** @internal */\nexport const orDie = dual<\n  <E>(\n    error: LazyArg<E>\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, never, InErr, OutDone, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, E>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    error: LazyArg<E>\n  ) => Channel.Channel<OutElem, InElem, never, InErr, OutDone, InDone, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, E>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  error: LazyArg<E>\n): Channel.Channel<OutElem, InElem, never, InErr, OutDone, InDone, Env> => orDieWith(self, error))\n\n/** @internal */\nexport const orDieWith = dual<\n  <OutErr>(\n    f: (e: OutErr) => unknown\n  ) => <OutElem, InElem, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, never, InErr, OutDone, InDone, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (e: OutErr) => unknown\n  ) => Channel.Channel<OutElem, InElem, never, InErr, OutDone, InDone, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (e: OutErr) => unknown\n): Channel.Channel<OutElem, InElem, never, InErr, OutDone, InDone, Env> =>\n  catchAll(self, (e) => core.failCauseSync(() => Cause.die(f(e)))) as Channel.Channel<\n    OutElem,\n    InElem,\n    never,\n    InErr,\n    OutDone,\n    InDone,\n    Env\n  >)\n\n/** @internal */\nexport const orElse = dual<\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    that: LazyArg<Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>>\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone1 | OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: LazyArg<Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone1 | OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >\n>(\n  2,\n  <Env, InErr, InElem, InDone, OutErr, OutElem, OutDone, Env1, InErr1, InElem1, InDone1, OutErr1, OutElem1, OutDone1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: LazyArg<Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>>\n  ): Channel.Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone | OutDone1,\n    InDone & InDone1,\n    Env | Env1\n  > => catchAll(self, that)\n)\n\n/** @internal */\nexport const pipeToOrFail = dual<\n  <OutElem2, OutElem, OutErr2, OutDone2, OutDone, Env2>(\n    that: Channel.Channel<OutElem2, OutElem, OutErr2, never, OutDone2, OutDone, Env2>\n  ) => <InElem, OutErr, InErr, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem2, InElem, OutErr2 | OutErr, InErr, OutDone2, InDone, Env2 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2, OutErr2, OutDone2, Env2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel.Channel<OutElem2, OutElem, OutErr2, never, OutDone2, OutDone, Env2>\n  ) => Channel.Channel<OutElem2, InElem, OutErr2 | OutErr, InErr, OutDone2, InDone, Env2 | Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2, OutErr2, OutDone2, Env2>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  that: Channel.Channel<OutElem2, OutElem, OutErr2, never, OutDone2, OutDone, Env2>\n): Channel.Channel<OutElem2, InElem, OutErr | OutErr2, InErr, OutDone2, InDone, Env | Env2> =>\n  core.suspend(() => {\n    let channelException: Channel.ChannelException<OutErr | OutErr2> | undefined = undefined\n\n    const reader: Channel.Channel<OutElem, OutElem, never, OutErr, OutDone, OutDone, Env> = core\n      .readWith({\n        onInput: (outElem) => core.flatMap(core.write(outElem), () => reader),\n        onFailure: (outErr) => {\n          channelException = ChannelException(outErr)\n          return core.failCause(Cause.die(channelException))\n        },\n        onDone: core.succeedNow\n      })\n\n    const writer: Channel.Channel<\n      OutElem2,\n      OutElem2,\n      OutErr2,\n      OutErr2,\n      OutDone2,\n      OutDone2,\n      Env2\n    > = core.readWithCause({\n      onInput: (outElem) => pipe(core.write(outElem), core.flatMap(() => writer)),\n      onFailure: (cause) =>\n        Cause.isDieType(cause) &&\n          isChannelException(cause.defect) &&\n          Equal.equals(cause.defect, channelException)\n          ? core.fail(cause.defect.error as OutErr2)\n          : core.failCause(cause),\n      onDone: core.succeedNow\n    })\n\n    return core.pipeTo(core.pipeTo(core.pipeTo(self, reader), that), writer)\n  }))\n\n/** @internal */\nexport const provideService = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<Env, I>>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, I, S>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<Env, I>>\n>(3, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, I, S>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  tag: Context.Tag<I, S>,\n  service: Types.NoInfer<S>\n): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<Env, I>> => {\n  return core.flatMap(\n    context<any>(),\n    (context) => core.provideContext(self, Context.add(context, tag, service))\n  )\n})\n\n/** @internal */\nexport const provideLayer = dual<\n  <Env, OutErr2, Env0>(\n    layer: Layer.Layer<Env, OutErr2, Env0>\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr2 | OutErr, InErr, OutDone, InDone, Env0>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutErr2, Env0>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    layer: Layer.Layer<Env, OutErr2, Env0>\n  ) => Channel.Channel<OutElem, InElem, OutErr2 | OutErr, InErr, OutDone, InDone, Env0>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutErr2, Env0>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  layer: Layer.Layer<Env, OutErr2, Env0>\n): Channel.Channel<OutElem, InElem, OutErr | OutErr2, InErr, OutDone, InDone, Env0> =>\n  unwrapScopedWith((scope) =>\n    Effect.map(Layer.buildWithScope(layer, scope), (context) => core.provideContext(self, context))\n  ))\n\n/** @internal */\nexport const mapInputContext = dual<\n  <Env0, Env>(\n    f: (env: Context.Context<Env0>) => Context.Context<Env>\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env0>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, Env0>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (env: Context.Context<Env0>) => Context.Context<Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env0>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, Env0>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  f: (env: Context.Context<Env0>) => Context.Context<Env>\n): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env0> =>\n  contextWithChannel((context: Context.Context<Env0>) => core.provideContext(self, f(context))))\n\n/** @internal */\nexport const provideSomeLayer = dual<\n  <R2, OutErr2, Env0>(\n    layer: Layer.Layer<R2, OutErr2, Env0>\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, R>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, R>\n  ) => Channel.Channel<OutElem, InElem, OutErr2 | OutErr, InErr, OutDone, InDone, Env0 | Exclude<R, R2>>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, R, R2, OutErr2, Env0>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, R>,\n    layer: Layer.Layer<R2, OutErr2, Env0>\n  ) => Channel.Channel<OutElem, InElem, OutErr2 | OutErr, InErr, OutDone, InDone, Env0 | Exclude<R, R2>>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, R, R2, OutErr2, Env0>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, R>,\n  layer: Layer.Layer<R2, OutErr2, Env0>\n): Channel.Channel<OutElem, InElem, OutErr | OutErr2, InErr, OutDone, InDone, Env0 | Exclude<R, R2>> =>\n  // @ts-expect-error\n  provideLayer(self, Layer.merge(Layer.context<Exclude<R, R2>>(), layer)))\n\n/** @internal */\nexport const read = <In>(): Channel.Channel<never, In, Option.Option<never>, unknown, In, unknown> =>\n  core.readOrFail<Option.Option<never>, In>(Option.none())\n\n/** @internal */\nexport const repeated = <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env> => core.flatMap(self, () => repeated(self))\n\n/** @internal */\nexport const run = <OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<never, unknown, OutErr, InErr, OutDone, InDone, Env>\n): Effect.Effect<OutDone, OutErr, Env> => Effect.scopedWith((scope) => executor.runIn(self, scope))\n\n/** @internal */\nexport const runCollect = <OutElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, Env>\n): Effect.Effect<[Chunk.Chunk<OutElem>, OutDone], OutErr, Env> => run(core.collectElements(self))\n\n/** @internal */\nexport const runDrain = <OutElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, Env>\n): Effect.Effect<OutDone, OutErr, Env> => run(drain(self))\n\n/** @internal */\nexport const runScoped = <OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<never, unknown, OutErr, InErr, OutDone, InDone, Env>\n): Effect.Effect<OutDone, OutErr, Env | Scope.Scope> => Effect.scopeWith((scope) => executor.runIn(self, scope))\n\n/** @internal */\nexport const scoped = <A, E, R>(\n  effect: Effect.Effect<A, E, R>\n): Channel.Channel<A, unknown, E, unknown, unknown, unknown, Exclude<R, Scope.Scope>> =>\n  unwrap(\n    Effect.uninterruptibleMask((restore) =>\n      Effect.map(Scope.make(), (scope) =>\n        core.acquireReleaseOut(\n          Effect.tapErrorCause(\n            restore(Scope.extend(effect, scope)),\n            (cause) => Scope.close(scope, Exit.failCause(cause))\n          ),\n          (_, exit) => Scope.close(scope, exit)\n        ))\n    )\n  )\n\n/** @internal */\nexport const scopedWith = <A, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<A, E, R>\n): Channel.Channel<A, unknown, E, unknown, unknown, unknown, R> =>\n  unwrapScoped(Effect.map(Effect.scope, (scope) => core.flatMap(core.fromEffect(f(scope)), core.write)))\n\n/** @internal */\nexport const service = <I, S>(\n  tag: Context.Tag<I, S>\n): Channel.Channel<never, unknown, never, unknown, S, unknown, I> => core.fromEffect(tag)\n\n/** @internal */\nexport const serviceWith = <I, S>(tag: Context.Tag<I, S>) =>\n<OutDone>(\n  f: (resource: Types.NoInfer<S>) => OutDone\n): Channel.Channel<never, unknown, never, unknown, OutDone, unknown, I> => map(service(tag), f)\n\n/** @internal */\nexport const serviceWithChannel =\n  <I, S>(tag: Context.Tag<I, S>) =>\n  <Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>(\n    f: (resource: Types.NoInfer<S>) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env | I> => core.flatMap(service(tag), f)\n\n/** @internal */\nexport const serviceWithEffect = <I, S>(tag: Context.Tag<I, S>) =>\n<Env, OutErr, OutDone>(\n  f: (resource: Types.NoInfer<S>) => Effect.Effect<OutDone, OutErr, Env>\n): Channel.Channel<never, unknown, OutErr, unknown, OutDone, unknown, Env | I> => mapEffect(service(tag), f)\n\n/** @internal */\nexport const splitLines = <Err, Done>(): Channel.Channel<\n  Chunk.Chunk<string>,\n  Chunk.Chunk<string>,\n  Err,\n  Err,\n  Done,\n  Done,\n  never\n> =>\n  core.suspend(() => {\n    let stringBuilder = \"\"\n    let midCRLF = false\n    const splitLinesChunk = (chunk: Chunk.Chunk<string>): Chunk.Chunk<string> => {\n      const chunkBuilder: Array<string> = []\n      Chunk.map(chunk, (str) => {\n        if (str.length !== 0) {\n          let from = 0\n          let indexOfCR = str.indexOf(\"\\r\")\n          let indexOfLF = str.indexOf(\"\\n\")\n          if (midCRLF) {\n            if (indexOfLF === 0) {\n              chunkBuilder.push(stringBuilder)\n              stringBuilder = \"\"\n              from = 1\n              indexOfLF = str.indexOf(\"\\n\", from)\n            } else {\n              stringBuilder = stringBuilder + \"\\r\"\n            }\n            midCRLF = false\n          }\n          while (indexOfCR !== -1 || indexOfLF !== -1) {\n            if (indexOfCR === -1 || (indexOfLF !== -1 && indexOfLF < indexOfCR)) {\n              if (stringBuilder.length === 0) {\n                chunkBuilder.push(str.substring(from, indexOfLF))\n              } else {\n                chunkBuilder.push(stringBuilder + str.substring(from, indexOfLF))\n                stringBuilder = \"\"\n              }\n              from = indexOfLF + 1\n              indexOfLF = str.indexOf(\"\\n\", from)\n            } else {\n              if (str.length === indexOfCR + 1) {\n                midCRLF = true\n                indexOfCR = -1\n              } else {\n                if (indexOfLF === indexOfCR + 1) {\n                  if (stringBuilder.length === 0) {\n                    chunkBuilder.push(str.substring(from, indexOfCR))\n                  } else {\n                    stringBuilder = stringBuilder + str.substring(from, indexOfCR)\n                    chunkBuilder.push(stringBuilder)\n                    stringBuilder = \"\"\n                  }\n                  from = indexOfCR + 2\n                  indexOfCR = str.indexOf(\"\\r\", from)\n                  indexOfLF = str.indexOf(\"\\n\", from)\n                } else {\n                  indexOfCR = str.indexOf(\"\\r\", indexOfCR + 1)\n                }\n              }\n            }\n          }\n          if (midCRLF) {\n            stringBuilder = stringBuilder + str.substring(from, str.length - 1)\n          } else {\n            stringBuilder = stringBuilder + str.substring(from, str.length)\n          }\n        }\n      })\n      return Chunk.unsafeFromArray(chunkBuilder)\n    }\n    const loop: Channel.Channel<Chunk.Chunk<string>, Chunk.Chunk<string>, Err, Err, Done, Done, never> = core\n      .readWithCause({\n        onInput: (input: Chunk.Chunk<string>) => {\n          const out = splitLinesChunk(input)\n          return Chunk.isEmpty(out)\n            ? loop\n            : core.flatMap(core.write(out), () => loop)\n        },\n        onFailure: (cause) =>\n          stringBuilder.length === 0\n            ? core.failCause(cause)\n            : core.flatMap(core.write(Chunk.of(stringBuilder)), () => core.failCause(cause)),\n        onDone: (done) =>\n          stringBuilder.length === 0\n            ? core.succeed(done)\n            : core.flatMap(core.write(Chunk.of(stringBuilder)), () => core.succeed(done))\n      })\n    return loop\n  })\n\n/** @internal */\nexport const toPubSub = <Done, Err, Elem>(\n  pubsub: PubSub.PubSub<Either.Either<Elem, Exit.Exit<Done, Err>>>\n): Channel.Channel<never, Elem, never, Err, unknown, Done> => toQueue(pubsub)\n\n/** @internal */\nexport const toPull = <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n): Effect.Effect<Effect.Effect<Either.Either<OutElem, OutDone>, OutErr, Env>, never, Env | Scope.Scope> =>\n  Effect.flatMap(Effect.scope, (scope) => toPullIn(self, scope))\n\n/** @internal */\nexport const toPullIn = dual<\n  (scope: Scope.Scope) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Effect.Effect<Effect.Effect<Either.Either<OutElem, OutDone>, OutErr, Env>, never, Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    scope: Scope.Scope\n  ) => Effect.Effect<Effect.Effect<Either.Either<OutElem, OutDone>, OutErr, Env>, never, Env>\n>(2, <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  scope: Scope.Scope\n) =>\n  Effect.zip(\n    Effect.sync(() => new executor.ChannelExecutor(self, void 0, identity)),\n    Effect.runtime<Env>()\n  ).pipe(\n    Effect.tap(([executor, runtime]) =>\n      Scope.addFinalizerExit(scope, (exit) => {\n        const finalizer = executor.close(exit)\n        return finalizer !== undefined\n          ? Effect.provide(finalizer, runtime)\n          : Effect.void\n      })\n    ),\n    Effect.uninterruptible,\n    Effect.map(([executor]) =>\n      Effect.suspend(() =>\n        interpretToPull(\n          executor.run() as ChannelState.ChannelState<OutErr, Env>,\n          executor\n        )\n      )\n    )\n  ))\n\n/** @internal */\nconst interpretToPull = <Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>(\n  channelState: ChannelState.ChannelState<OutErr, Env>,\n  exec: executor.ChannelExecutor<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n): Effect.Effect<Either.Either<OutElem, OutDone>, OutErr, Env> => {\n  const state = channelState as ChannelState.Primitive\n  switch (state._tag) {\n    case ChannelStateOpCodes.OP_DONE: {\n      return Exit.match(exec.getDone(), {\n        onFailure: Effect.failCause,\n        onSuccess: (done): Effect.Effect<Either.Either<OutElem, OutDone>, OutErr, Env> =>\n          Effect.succeed(Either.left(done))\n      })\n    }\n    case ChannelStateOpCodes.OP_EMIT: {\n      return Effect.succeed(Either.right(exec.getEmit()))\n    }\n    case ChannelStateOpCodes.OP_FROM_EFFECT: {\n      return pipe(\n        state.effect as Effect.Effect<Either.Either<OutElem, OutDone>, OutErr, Env>,\n        Effect.flatMap(() => interpretToPull(exec.run() as ChannelState.ChannelState<OutErr, Env>, exec))\n      )\n    }\n    case ChannelStateOpCodes.OP_READ: {\n      return executor.readUpstream(\n        state,\n        () => interpretToPull(exec.run() as ChannelState.ChannelState<OutErr, Env>, exec),\n        (cause) => Effect.failCause(cause) as Effect.Effect<Either.Either<OutElem, OutDone>, OutErr, Env>\n      )\n    }\n  }\n}\n\n/** @internal */\nexport const toQueue = <Done, Err, Elem>(\n  queue: Queue.Enqueue<Either.Either<Elem, Exit.Exit<Done, Err>>>\n): Channel.Channel<never, Elem, never, Err, unknown, Done> => core.suspend(() => toQueueInternal(queue))\n\n/** @internal */\nconst toQueueInternal = <Err, Done, Elem>(\n  queue: Queue.Enqueue<Either.Either<Elem, Exit.Exit<Done, Err>>>\n): Channel.Channel<never, Elem, never, Err, unknown, Done> => {\n  return core.readWithCause({\n    onInput: (elem) =>\n      core.flatMap(\n        core.fromEffect(Queue.offer(queue, Either.right(elem))),\n        () => toQueueInternal(queue)\n      ),\n    onFailure: (cause) => core.fromEffect(Queue.offer(queue, Either.left(Exit.failCause(cause)))),\n    onDone: (done) => core.fromEffect(Queue.offer(queue, Either.left(Exit.succeed(done))))\n  })\n}\n\n/** @internal */\nexport const unwrap = <OutElem, InElem, OutErr, InErr, OutDone, InDone, R2, E, R>(\n  channel: Effect.Effect<Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, R2>, E, R>\n): Channel.Channel<OutElem, InElem, E | OutErr, InErr, OutDone, InDone, R | R2> => flatten(core.fromEffect(channel))\n\n/** @internal */\nexport const unwrapScoped = <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, E, R>(\n  self: Effect.Effect<Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>, E, R>\n): Channel.Channel<OutElem, InElem, E | OutErr, InErr, OutDone, InDone, Env | Exclude<R, Scope.Scope>> =>\n  core.concatAllWith(\n    scoped(self),\n    (d, _) => d,\n    (d, _) => d\n  )\n\n/** @internal */\nexport const unwrapScopedWith = <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>, E, R>\n): Channel.Channel<OutElem, InElem, E | OutErr, InErr, OutDone, InDone, R | Env> =>\n  core.concatAllWith(\n    scopedWith(f),\n    (d, _) => d,\n    (d, _) => d\n  )\n\n/** @internal */\nexport const updateService = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    f: (resource: Types.NoInfer<S>) => Types.NoInfer<S>\n  ) => <OutElem, OutErr, InErr, OutDone, InDone, R>(\n    self: Channel.Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, R>\n  ) => Channel.Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, I | R>,\n  <OutElem, OutErr, InErr, OutDone, InDone, R, I, S>(\n    self: Channel.Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, R>,\n    tag: Context.Tag<I, S>,\n    f: (resource: Types.NoInfer<S>) => Types.NoInfer<S>\n  ) => Channel.Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, I | R>\n>(3, <OutElem, OutErr, InErr, OutDone, InDone, R, I, S>(\n  self: Channel.Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, R>,\n  tag: Context.Tag<I, S>,\n  f: (resource: Types.NoInfer<S>) => Types.NoInfer<S>\n): Channel.Channel<OutElem, unknown, OutErr, InErr, OutDone, InDone, R | I> =>\n  mapInputContext(self, (context: Context.Context<R>) =>\n    Context.merge(\n      context,\n      Context.make(tag, f(Context.unsafeGet(context, tag)))\n    )))\n\n/** @internal */\nexport const withSpan: {\n  (\n    name: string,\n    options?: Tracer.SpanOptions\n  ): <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<Env, Tracer.ParentSpan>>\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    name: string,\n    options?: Tracer.SpanOptions\n  ): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Exclude<Env, Tracer.ParentSpan>>\n} = function() {\n  const dataFirst = typeof arguments[0] !== \"string\"\n  const name = dataFirst ? arguments[1] : arguments[0]\n  const options = tracer.addSpanStackTrace(dataFirst ? arguments[2] : arguments[1])\n  const acquire = Effect.all([\n    Effect.makeSpan(name, options),\n    Effect.context(),\n    Effect.clock,\n    FiberRef.get(FiberRef.currentTracerTimingEnabled)\n  ])\n  if (dataFirst) {\n    const self = arguments[0]\n    return acquireUseRelease(\n      acquire,\n      ([span, context]) => core.provideContext(self, Context.add(context, tracer.spanTag, span)),\n      ([span, , clock, timingEnabled], exit) => coreEffect.endSpan(span, exit, clock, timingEnabled)\n    )\n  }\n  return (self: Channel.Channel<any>) =>\n    acquireUseRelease(\n      acquire,\n      ([span, context]) => core.provideContext(self, Context.add(context, tracer.spanTag, span)),\n      ([span, , clock, timingEnabled], exit) => coreEffect.endSpan(span, exit, clock, timingEnabled)\n    )\n} as any\n\n/** @internal */\nexport const writeAll = <OutElem>(\n  ...outs: Array<OutElem>\n): Channel.Channel<OutElem> => writeChunk(Chunk.fromIterable(outs))\n\n/** @internal */\nexport const writeChunk = <OutElem>(\n  outs: Chunk.Chunk<OutElem>\n): Channel.Channel<OutElem> => writeChunkWriter(0, outs.length, outs)\n\n/** @internal */\nconst writeChunkWriter = <OutElem>(\n  idx: number,\n  len: number,\n  chunk: Chunk.Chunk<OutElem>\n): Channel.Channel<OutElem> => {\n  return idx === len\n    ? core.void\n    : pipe(\n      core.write(pipe(chunk, Chunk.unsafeGet(idx))),\n      core.flatMap(() => writeChunkWriter(idx + 1, len, chunk))\n    )\n}\n\n/** @internal */\nexport const zip = dual<\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    that: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    readonly [OutDone, OutDone1],\n    InDone & InDone1,\n    Env1 | Env\n  >,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    readonly [OutDone, OutDone1],\n    InDone & InDone1,\n    Env1 | Env\n  >\n>(\n  (args) => core.isChannel(args[1]),\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ): Channel.Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    readonly [OutDone, OutDone1],\n    InDone & InDone1,\n    Env | Env1\n  > =>\n    options?.concurrent ?\n      mergeWith(self, {\n        other: that,\n        onSelfDone: (exit1) => mergeDecision.Await((exit2) => Effect.suspend(() => Exit.zip(exit1, exit2))),\n        onOtherDone: (exit2) => mergeDecision.Await((exit1) => Effect.suspend(() => Exit.zip(exit1, exit2)))\n      }) :\n      core.flatMap(self, (a) => map(that, (b) => [a, b] as const))\n)\n\n/** @internal */\nexport const zipLeft = dual<\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    that: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >\n>(\n  (args) => core.isChannel(args[1]),\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ): Channel.Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    OutDone,\n    InDone & InDone1,\n    Env | Env1\n  > =>\n    options?.concurrent ?\n      map(zip(self, that, { concurrent: true }), (tuple) => tuple[0]) :\n      core.flatMap(self, (z) => as(that, z))\n)\n\n/** @internal */\nexport const zipRight = dual<\n  <OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    that: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    OutDone1,\n    InDone & InDone1,\n    Env1 | Env\n  >,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    OutDone1,\n    InDone & InDone1,\n    Env1 | Env\n  >\n>(\n  (args) => core.isChannel(args[1]),\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ): Channel.Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    OutDone1,\n    InDone & InDone1,\n    Env | Env1\n  > =>\n    options?.concurrent ?\n      map(zip(self, that, { concurrent: true }), (tuple) => tuple[1]) :\n      core.flatMap(self, () => that)\n)\n\n/** @internal */\nexport const ChannelExceptionTypeId: Channel.ChannelExceptionTypeId = Symbol.for(\n  \"effect/Channel/ChannelException\"\n) as Channel.ChannelExceptionTypeId\n\n/** @internal */\nexport const ChannelException = <E>(error: E): Channel.ChannelException<E> => ({\n  _tag: \"ChannelException\",\n  [ChannelExceptionTypeId]: ChannelExceptionTypeId,\n  error\n})\n\n/** @internal */\nexport const isChannelException = (u: unknown): u is Channel.ChannelException<unknown> =>\n  hasProperty(u, ChannelExceptionTypeId)\n"
  },
  {
    "path": "packages/effect/src/internal/clock.ts",
    "content": "import type * as Clock from \"../Clock.js\"\nimport * as Context from \"../Context.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport { constFalse } from \"../Function.js\"\nimport * as core from \"./core.js\"\n\n/** @internal */\nconst ClockSymbolKey = \"effect/Clock\"\n\n/** @internal */\nexport const ClockTypeId: Clock.ClockTypeId = Symbol.for(ClockSymbolKey) as Clock.ClockTypeId\n\n/** @internal */\nexport const clockTag: Context.Tag<Clock.Clock, Clock.Clock> = Context.GenericTag(\"effect/Clock\")\n\n/** @internal */\nexport const MAX_TIMER_MILLIS = 2 ** 31 - 1\n\n/** @internal */\nexport const globalClockScheduler: Clock.ClockScheduler = {\n  unsafeSchedule(task: Clock.Task, duration: Duration.Duration): Clock.CancelToken {\n    const millis = Duration.toMillis(duration)\n    // If the duration is greater than the value allowable by the JS timer\n    // functions, treat the value as an infinite duration\n    if (millis > MAX_TIMER_MILLIS) {\n      return constFalse\n    }\n    let completed = false\n    const handle = setTimeout(() => {\n      completed = true\n      task()\n    }, millis)\n    return () => {\n      clearTimeout(handle)\n      return !completed\n    }\n  }\n}\n\nconst performanceNowNanos = (function() {\n  const bigint1e6 = BigInt(1_000_000)\n  if (typeof performance === \"undefined\" || typeof performance.now !== \"function\") {\n    return () => BigInt(Date.now()) * bigint1e6\n  }\n  let origin: bigint\n  return () => {\n    if (origin === undefined) {\n      origin = (BigInt(Date.now()) * bigint1e6) - BigInt(Math.round(performance.now() * 1_000_000))\n    }\n    return origin + BigInt(Math.round(performance.now() * 1000000))\n  }\n})()\nconst processOrPerformanceNow = (function() {\n  const processHrtime =\n    typeof process === \"object\" && \"hrtime\" in process && typeof process.hrtime.bigint === \"function\" ?\n      process.hrtime :\n      undefined\n  if (!processHrtime) {\n    return performanceNowNanos\n  }\n  const origin = performanceNowNanos() - processHrtime.bigint()\n  return () => origin + processHrtime.bigint()\n})()\n\n/** @internal */\nclass ClockImpl implements Clock.Clock {\n  readonly [ClockTypeId]: Clock.ClockTypeId = ClockTypeId\n\n  unsafeCurrentTimeMillis(): number {\n    return Date.now()\n  }\n\n  unsafeCurrentTimeNanos(): bigint {\n    return processOrPerformanceNow()\n  }\n\n  currentTimeMillis: Effect.Effect<number> = core.sync(() => this.unsafeCurrentTimeMillis())\n\n  currentTimeNanos: Effect.Effect<bigint> = core.sync(() => this.unsafeCurrentTimeNanos())\n\n  scheduler(): Effect.Effect<Clock.ClockScheduler> {\n    return core.succeed(globalClockScheduler)\n  }\n\n  sleep(duration: Duration.Duration): Effect.Effect<void> {\n    return core.async<void>((resume) => {\n      const canceler = globalClockScheduler.unsafeSchedule(() => resume(core.void), duration)\n      return core.asVoid(core.sync(canceler))\n    })\n  }\n}\n\n/** @internal */\nexport const make = (): Clock.Clock => new ClockImpl()\n"
  },
  {
    "path": "packages/effect/src/internal/completedRequestMap.ts",
    "content": "import { globalValue } from \"../GlobalValue.js\"\nimport type * as Request from \"../Request.js\"\nimport { fiberRefUnsafeMake } from \"./core.js\"\n\n/** @internal */\nexport const currentRequestMap = globalValue(\n  Symbol.for(\"effect/FiberRef/currentRequestMap\"),\n  () => fiberRefUnsafeMake(new Map<any, Request.Entry<any>>())\n)\n"
  },
  {
    "path": "packages/effect/src/internal/concurrency.ts",
    "content": "import type { Effect } from \"../Effect.js\"\nimport type { Concurrency } from \"../Types.js\"\nimport * as core from \"./core.js\"\n\n/** @internal */\nexport const match = <A, E, R>(\n  concurrency: Concurrency | undefined,\n  sequential: () => Effect<A, E, R>,\n  unbounded: () => Effect<A, E, R>,\n  bounded: (limit: number) => Effect<A, E, R>\n): Effect<A, E, R> => {\n  switch (concurrency) {\n    case undefined:\n      return sequential()\n    case \"unbounded\":\n      return unbounded()\n    case \"inherit\":\n      return core.fiberRefGetWith(\n        core.currentConcurrency,\n        (concurrency) =>\n          concurrency === \"unbounded\" ?\n            unbounded() :\n            concurrency > 1 ?\n            bounded(concurrency) :\n            sequential()\n      )\n    default:\n      return concurrency > 1 ? bounded(concurrency) : sequential()\n  }\n}\n\n/** @internal */\nexport const matchSimple = <A, E, R>(\n  concurrency: Concurrency | undefined,\n  sequential: () => Effect<A, E, R>,\n  concurrent: () => Effect<A, E, R>\n): Effect<A, E, R> => {\n  switch (concurrency) {\n    case undefined:\n      return sequential()\n    case \"unbounded\":\n      return concurrent()\n    case \"inherit\":\n      return core.fiberRefGetWith(\n        core.currentConcurrency,\n        (concurrency) =>\n          concurrency === \"unbounded\" || concurrency > 1 ?\n            concurrent() :\n            sequential()\n      )\n    default:\n      return concurrency > 1 ? concurrent() : sequential()\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/config.ts",
    "content": "import type * as Brand from \"../Brand.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport type * as Config from \"../Config.js\"\nimport * as ConfigError from \"../ConfigError.js\"\nimport * as Duration from \"../Duration.js\"\nimport * as Either from \"../Either.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { constTrue, dual, pipe } from \"../Function.js\"\nimport type * as HashMap from \"../HashMap.js\"\nimport * as HashSet from \"../HashSet.js\"\nimport { formatUnknown } from \"../Inspectable.js\"\nimport type * as LogLevel from \"../LogLevel.js\"\nimport * as Option from \"../Option.js\"\nimport { hasProperty, type Predicate, type Refinement } from \"../Predicate.js\"\nimport type * as Redacted from \"../Redacted.js\"\nimport type * as Secret from \"../Secret.js\"\nimport * as configError from \"./configError.js\"\nimport * as core from \"./core.js\"\nimport * as defaultServices from \"./defaultServices.js\"\nimport * as effectable from \"./effectable.js\"\nimport * as OpCodes from \"./opCodes/config.js\"\nimport * as redacted_ from \"./redacted.js\"\nimport * as InternalSecret from \"./secret.js\"\n\nconst ConfigSymbolKey = \"effect/Config\"\n\n/** @internal */\nexport const ConfigTypeId: Config.ConfigTypeId = Symbol.for(\n  ConfigSymbolKey\n) as Config.ConfigTypeId\n\n/** @internal */\nexport type ConfigPrimitive =\n  | Constant\n  | Described\n  | Fallback\n  | Fail\n  | Lazy\n  | MapOrFail\n  | Nested\n  | Primitive\n  | Sequence\n  | Table\n  | Zipped\n\nconst configVariance = {\n  /* c8 ignore next */\n  _A: (_: never) => _\n}\n\nconst proto = {\n  ...effectable.CommitPrototype,\n  [ConfigTypeId]: configVariance,\n  commit(this: Config.Config<unknown>) {\n    return defaultServices.config(this)\n  }\n}\n\n/** @internal */\nexport type Op<Tag extends string, Body = {}> = Config.Config<never> & Body & {\n  readonly _tag: Tag\n}\n\n/** @internal */\nexport interface Constant extends\n  Op<OpCodes.OP_CONSTANT, {\n    readonly value: unknown\n    parse(text: string): Either.Either<unknown, ConfigError.ConfigError>\n  }>\n{}\n\n/** @internal */\nexport interface Described extends\n  Op<OpCodes.OP_DESCRIBED, {\n    readonly config: Config.Config<unknown>\n    readonly description: string\n  }>\n{}\n\n/** @internal */\nexport interface Fallback extends\n  Op<OpCodes.OP_FALLBACK, {\n    readonly first: Config.Config<unknown>\n    readonly second: Config.Config<unknown>\n    readonly condition: Predicate<ConfigError.ConfigError>\n  }>\n{}\n\n/** @internal */\nexport interface Fail extends\n  Op<OpCodes.OP_FAIL, {\n    readonly message: string\n    parse(text: string): Either.Either<unknown, ConfigError.ConfigError>\n  }>\n{}\n\n/** @internal */\nexport interface Lazy extends\n  Op<OpCodes.OP_LAZY, {\n    config(): Config.Config<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface MapOrFail extends\n  Op<OpCodes.OP_MAP_OR_FAIL, {\n    readonly original: Config.Config<unknown>\n    mapOrFail(value: unknown): Either.Either<unknown, ConfigError.ConfigError>\n  }>\n{}\n\n/** @internal */\nexport interface Nested extends\n  Op<OpCodes.OP_NESTED, {\n    readonly name: string\n    readonly config: Config.Config<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Primitive extends\n  Op<OpCodes.OP_PRIMITIVE, {\n    readonly description: string\n    parse(text: string): Either.Either<unknown, ConfigError.ConfigError>\n  }>\n{}\n\n/** @internal */\nexport interface Sequence extends\n  Op<OpCodes.OP_SEQUENCE, {\n    readonly config: Config.Config<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Table extends\n  Op<OpCodes.OP_HASHMAP, {\n    readonly op: OpCodes.OP_HASHMAP\n    readonly valueConfig: Config.Config<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Zipped extends\n  Op<OpCodes.OP_ZIP_WITH, {\n    readonly op: OpCodes.OP_ZIP_WITH\n    readonly left: Config.Config<unknown>\n    readonly right: Config.Config<unknown>\n    zip(a: unknown, b: unknown): unknown\n  }>\n{}\n\n/** @internal */\nexport const boolean = (name?: string): Config.Config<boolean> => {\n  const config = primitive(\n    \"a boolean property\",\n    (text) => {\n      switch (text) {\n        case \"true\":\n        case \"yes\":\n        case \"on\":\n        case \"1\": {\n          return Either.right(true)\n        }\n        case \"false\":\n        case \"no\":\n        case \"off\":\n        case \"0\": {\n          return Either.right(false)\n        }\n        default: {\n          const error = configError.InvalidData(\n            [],\n            `Expected a boolean value but received ${formatUnknown(text)}`\n          )\n          return Either.left(error)\n        }\n      }\n    }\n  )\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const url = (name?: string): Config.Config<URL> => {\n  const config = primitive(\n    \"an URL property\",\n    (text) =>\n      Either.try({\n        try: () => new URL(text),\n        catch: (_) => configError.InvalidData([], `Expected an URL value but received ${formatUnknown(text)}`)\n      })\n  )\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const port = (name?: string): Config.Config<number> => {\n  const config = primitive(\n    \"a network port property\",\n    (text) => {\n      const result = Number(text)\n\n      if (\n        Number.isNaN(result) ||\n        result.toString() !== text.toString() ||\n        !Number.isInteger(result) ||\n        result < 1 ||\n        result > 65535\n      ) {\n        return Either.left(\n          configError.InvalidData(\n            [],\n            `Expected a network port value but received ${formatUnknown(text)}`\n          )\n        )\n      }\n      return Either.right(result)\n    }\n  )\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const array = <A>(config: Config.Config<A>, name?: string): Config.Config<Array<A>> => {\n  return pipe(chunk(config, name), map(Chunk.toArray))\n}\n\n/** @internal */\nexport const chunk = <A>(config: Config.Config<A>, name?: string): Config.Config<Chunk.Chunk<A>> => {\n  return map(name === undefined ? repeat(config) : nested(repeat(config), name), Chunk.unsafeFromArray)\n}\n\n/** @internal */\nexport const date = (name?: string): Config.Config<Date> => {\n  const config = primitive(\n    \"a date property\",\n    (text) => {\n      const result = Date.parse(text)\n      if (Number.isNaN(result)) {\n        return Either.left(\n          configError.InvalidData(\n            [],\n            `Expected a Date value but received ${formatUnknown(text)}`\n          )\n        )\n      }\n      return Either.right(new Date(result))\n    }\n  )\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const fail = (message: string): Config.Config<never> => {\n  const fail = Object.create(proto)\n  fail._tag = OpCodes.OP_FAIL\n  fail.message = message\n  fail.parse = () => Either.left(configError.Unsupported([], message))\n  return fail\n}\n\n/** @internal */\nexport const number = (name?: string): Config.Config<number> => {\n  const config = primitive(\n    \"a number property\",\n    (text) => {\n      const result = Number(text)\n      if (Number.isNaN(result)) {\n        return Either.left(\n          configError.InvalidData(\n            [],\n            `Expected a number value but received ${formatUnknown(text)}`\n          )\n        )\n      }\n      return Either.right(result)\n    }\n  )\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const integer = (name?: string): Config.Config<number> => {\n  const config = primitive(\n    \"an integer property\",\n    (text) => {\n      const result = Number(text)\n      if (!Number.isInteger(result)) {\n        return Either.left(\n          configError.InvalidData(\n            [],\n            `Expected an integer value but received ${formatUnknown(text)}`\n          )\n        )\n      }\n      return Either.right(result)\n    }\n  )\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const literal = <Literals extends ReadonlyArray<Config.LiteralValue>>(...literals: Literals) =>\n(\n  name?: string\n): Config.Config<Literals[number]> => {\n  const valuesString = literals.map(String).join(\", \")\n  const config = primitive(`one of (${valuesString})`, (text) => {\n    const found = literals.find((value) => String(value) === text)\n    if (found === undefined) {\n      return Either.left(\n        configError.InvalidData(\n          [],\n          `Expected one of (${valuesString}) but received ${formatUnknown(text)}`\n        )\n      )\n    }\n    return Either.right(found)\n  })\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const logLevel = (name?: string): Config.Config<LogLevel.LogLevel> => {\n  const config = mapOrFail(string(), (value) => {\n    const label = value.toUpperCase()\n    const level = core.allLogLevels.find((level) => level.label === label)\n    return level === undefined\n      ? Either.left(\n        configError.InvalidData([], `Expected a log level but received ${formatUnknown(value)}`)\n      )\n      : Either.right(level)\n  })\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const duration = (name?: string): Config.Config<Duration.Duration> => {\n  const config = mapOrFail(string(), (value) => {\n    const duration = Duration.decodeUnknown(value)\n    return Either.fromOption(\n      duration,\n      () => configError.InvalidData([], `Expected a duration but received ${formatUnknown(value)}`)\n    )\n  })\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const map = dual<\n  <A, B>(f: (a: A) => B) => (self: Config.Config<A>) => Config.Config<B>,\n  <A, B>(self: Config.Config<A>, f: (a: A) => B) => Config.Config<B>\n>(2, (self, f) => mapOrFail(self, (a) => Either.right(f(a))))\n\n/** @internal */\nexport const mapAttempt = dual<\n  <A, B>(f: (a: A) => B) => (self: Config.Config<A>) => Config.Config<B>,\n  <A, B>(self: Config.Config<A>, f: (a: A) => B) => Config.Config<B>\n>(2, (self, f) =>\n  mapOrFail(self, (a) => {\n    try {\n      return Either.right(f(a))\n    } catch (error) {\n      return Either.left(\n        configError.InvalidData(\n          [],\n          error instanceof Error ? error.message : `${error}`\n        )\n      )\n    }\n  }))\n\n/** @internal */\nexport const mapOrFail = dual<\n  <A, B>(f: (a: A) => Either.Either<B, ConfigError.ConfigError>) => (self: Config.Config<A>) => Config.Config<B>,\n  <A, B>(self: Config.Config<A>, f: (a: A) => Either.Either<B, ConfigError.ConfigError>) => Config.Config<B>\n>(2, (self, f) => {\n  const mapOrFail = Object.create(proto)\n  mapOrFail._tag = OpCodes.OP_MAP_OR_FAIL\n  mapOrFail.original = self\n  mapOrFail.mapOrFail = f\n  return mapOrFail\n})\n\n/** @internal */\nexport const nested = dual<\n  (name: string) => <A>(self: Config.Config<A>) => Config.Config<A>,\n  <A>(self: Config.Config<A>, name: string) => Config.Config<A>\n>(2, (self, name) => {\n  const nested = Object.create(proto)\n  nested._tag = OpCodes.OP_NESTED\n  nested.name = name\n  nested.config = self\n  return nested\n})\n\n/** @internal */\nexport const orElse = dual<\n  <A2>(that: LazyArg<Config.Config<A2>>) => <A>(self: Config.Config<A>) => Config.Config<A | A2>,\n  <A, A2>(self: Config.Config<A>, that: LazyArg<Config.Config<A2>>) => Config.Config<A | A2>\n>(2, (self, that) => {\n  const fallback = Object.create(proto)\n  fallback._tag = OpCodes.OP_FALLBACK\n  fallback.first = self\n  fallback.second = suspend(that)\n  fallback.condition = constTrue\n  return fallback\n})\n\n/** @internal */\nexport const orElseIf = dual<\n  <A2>(\n    options: {\n      readonly if: Predicate<ConfigError.ConfigError>\n      readonly orElse: LazyArg<Config.Config<A2>>\n    }\n  ) => <A>(self: Config.Config<A>) => Config.Config<A | A2>,\n  <A, A2>(\n    self: Config.Config<A>,\n    options: {\n      readonly if: Predicate<ConfigError.ConfigError>\n      readonly orElse: LazyArg<Config.Config<A2>>\n    }\n  ) => Config.Config<A | A2>\n>(2, (self, options) => {\n  const fallback = Object.create(proto)\n  fallback._tag = OpCodes.OP_FALLBACK\n  fallback.first = self\n  fallback.second = suspend(options.orElse)\n  fallback.condition = options.if\n  return fallback\n})\n\n/** @internal */\nexport const option = <A>(self: Config.Config<A>): Config.Config<Option.Option<A>> => {\n  return pipe(\n    self,\n    map(Option.some),\n    orElseIf({ orElse: () => succeed(Option.none()), if: ConfigError.isMissingDataOnly })\n  )\n}\n\n/** @internal */\nexport const primitive = <A>(\n  description: string,\n  parse: (text: string) => Either.Either<A, ConfigError.ConfigError>\n): Config.Config<A> => {\n  const primitive = Object.create(proto)\n  primitive._tag = OpCodes.OP_PRIMITIVE\n  primitive.description = description\n  primitive.parse = parse\n  return primitive\n}\n\n/** @internal */\nexport const repeat = <A>(self: Config.Config<A>): Config.Config<Array<A>> => {\n  const repeat = Object.create(proto)\n  repeat._tag = OpCodes.OP_SEQUENCE\n  repeat.config = self\n  return repeat\n}\n\n/** @internal */\nexport const secret = (name?: string): Config.Config<Secret.Secret> => {\n  const config = primitive(\n    \"a secret property\",\n    (text) => Either.right(InternalSecret.fromString(text))\n  )\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const redacted = <A>(\n  nameOrConfig?: string | Config.Config<A>\n): Config.Config<Redacted.Redacted<A | string>> => {\n  const config: Config.Config<A | string> = isConfig(nameOrConfig) ? nameOrConfig : string(nameOrConfig)\n  return map(config, redacted_.make)\n}\n\n/** @internal */\nexport const branded: {\n  <A, B extends Brand.Branded<A, any>>(\n    constructor: Brand.Brand.Constructor<B>\n  ): (config: Config.Config<A>) => Config.Config<B>\n  <B extends Brand.Branded<string, any>>(\n    name: string | undefined,\n    constructor: Brand.Brand.Constructor<B>\n  ): Config.Config<B>\n  <A, B extends Brand.Branded<A, any>>(\n    config: Config.Config<A>,\n    constructor: Brand.Brand.Constructor<B>\n  ): Config.Config<B>\n} = dual(2, <A, B extends Brand.Brand.Constructor<any>>(\n  nameOrConfig: Config.Config<NoInfer<A>> | string | undefined,\n  constructor: B\n) => {\n  const config: Config.Config<string | A> = isConfig(nameOrConfig) ? nameOrConfig : string(nameOrConfig)\n\n  return mapOrFail(config, (a) =>\n    constructor.either(a).pipe(\n      Either.mapLeft((brandErrors) =>\n        configError.InvalidData([], brandErrors.map((brandError) => brandError.message).join(\"\\n\"))\n      )\n    ))\n})\n\n/** @internal */\nexport const hashSet = <A>(config: Config.Config<A>, name?: string): Config.Config<HashSet.HashSet<A>> => {\n  const newConfig = map(chunk(config), HashSet.fromIterable)\n  return name === undefined ? newConfig : nested(newConfig, name)\n}\n\n/** @internal */\nexport const string = (name?: string): Config.Config<string> => {\n  const config = primitive(\n    \"a text property\",\n    Either.right\n  )\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const nonEmptyString = (name?: string): Config.Config<string> => {\n  const config = primitive(\n    \"a non-empty text property\",\n    Either.liftPredicate((text) => text.length > 0, () => configError.MissingData([], \"Expected a non-empty string\"))\n  )\n\n  return name === undefined ? config : nested(config, name)\n}\n\n/** @internal */\nexport const all = <const Arg extends Iterable<Config.Config<any>> | Record<string, Config.Config<any>>>(\n  arg: Arg\n): Config.Config<\n  [Arg] extends [ReadonlyArray<Config.Config<any>>] ? {\n      -readonly [K in keyof Arg]: [Arg[K]] extends [Config.Config<infer A>] ? A : never\n    }\n    : [Arg] extends [Iterable<Config.Config<infer A>>] ? Array<A>\n    : [Arg] extends [Record<string, Config.Config<any>>] ? {\n        -readonly [K in keyof Arg]: [Arg[K]] extends [Config.Config<infer A>] ? A : never\n      }\n    : never\n> => {\n  if (Array.isArray(arg)) {\n    return tuple(arg) as any\n  } else if (Symbol.iterator in arg) {\n    return tuple([...(arg as Iterable<Config.Config<any>>)]) as any\n  }\n  return struct(arg) as any\n}\n\nconst struct = <NER extends Record<string, Config.Config<any>>>(r: NER): Config.Config<\n  {\n    [K in keyof NER]: [NER[K]] extends [{ [ConfigTypeId]: { _A: (_: never) => infer A } }] ? A : never\n  }\n> => {\n  const entries = Object.entries(r)\n  let result = pipe(entries[0][1], map((value) => ({ [entries[0][0]]: value })))\n  if (entries.length === 1) {\n    return result as any\n  }\n  const rest = entries.slice(1)\n  for (const [key, config] of rest) {\n    result = pipe(\n      result,\n      zipWith(config, (record, value) => ({ ...record, [key]: value }))\n    )\n  }\n  return result as any\n}\n\n/** @internal */\nexport const succeed = <A>(value: A): Config.Config<A> => {\n  const constant = Object.create(proto)\n  constant._tag = OpCodes.OP_CONSTANT\n  constant.value = value\n  constant.parse = () => Either.right(value)\n  return constant\n}\n\n/** @internal */\nexport const suspend = <A>(config: LazyArg<Config.Config<A>>): Config.Config<A> => {\n  const lazy = Object.create(proto)\n  lazy._tag = OpCodes.OP_LAZY\n  lazy.config = config\n  return lazy\n}\n\n/** @internal */\nexport const sync = <A>(value: LazyArg<A>): Config.Config<A> => {\n  return suspend(() => succeed(value()))\n}\n\n/** @internal */\nexport const hashMap = <A>(config: Config.Config<A>, name?: string): Config.Config<HashMap.HashMap<string, A>> => {\n  const table = Object.create(proto)\n  table._tag = OpCodes.OP_HASHMAP\n  table.valueConfig = config\n  return name === undefined ? table : nested(table, name)\n}\n\n/** @internal */\nexport const isConfig = (u: unknown): u is Config.Config<unknown> => hasProperty(u, ConfigTypeId)\n\n/** @internal */\nconst tuple = <T extends ArrayLike<Config.Config<any>>>(tuple: T): Config.Config<\n  {\n    [K in keyof T]: [T[K]] extends [Config.Config<infer A>] ? A : never\n  }\n> => {\n  if (tuple.length === 0) {\n    return succeed([]) as any\n  }\n  if (tuple.length === 1) {\n    return map(tuple[0], (x) => [x]) as any\n  }\n  let result = map(tuple[0], (x) => [x])\n  for (let i = 1; i < tuple.length; i++) {\n    const config = tuple[i]\n    result = pipe(\n      result,\n      zipWith(config, (tuple, value) => [...tuple, value])\n    ) as any\n  }\n  return result as any\n}\n\n/**\n * @internal\n */\nexport const unwrap = <A>(wrapped: Config.Config.Wrap<A>): Config.Config<A> => {\n  if (isConfig(wrapped)) {\n    return wrapped\n  }\n  return struct(\n    Object.fromEntries(\n      Object.entries(wrapped).map(([k, a]) => [k, unwrap(a as any)])\n    )\n  ) as any\n}\n\n/** @internal */\nexport const validate = dual<\n  {\n    <A, B extends A>(options: {\n      readonly message: string\n      readonly validation: Refinement<A, B>\n    }): (self: Config.Config<A>) => Config.Config<B>\n    <A>(options: {\n      readonly message: string\n      readonly validation: Predicate<A>\n    }): (self: Config.Config<A>) => Config.Config<A>\n  },\n  {\n    <A, B extends A>(self: Config.Config<A>, options: {\n      readonly message: string\n      readonly validation: Refinement<A, B>\n    }): Config.Config<B>\n    <A>(self: Config.Config<A>, options: {\n      readonly message: string\n      readonly validation: Predicate<A>\n    }): Config.Config<A>\n  }\n>(2, <A>(self: Config.Config<A>, { message, validation }: {\n  readonly message: string\n  readonly validation: Predicate<A>\n}) =>\n  mapOrFail(self, (a) => {\n    if (validation(a)) {\n      return Either.right(a)\n    }\n    return Either.left(configError.InvalidData([], message))\n  }))\n\n/** @internal */\nexport const withDefault = dual<\n  <const A2>(def: A2) => <A>(self: Config.Config<A>) => Config.Config<A | A2>,\n  <A, const A2>(self: Config.Config<A>, def: A2) => Config.Config<A | A2>\n>(2, (self, def) =>\n  orElseIf(self, {\n    orElse: () => succeed(def),\n    if: ConfigError.isMissingDataOnly\n  }))\n\n/** @internal */\nexport const withDescription = dual<\n  (description: string) => <A>(self: Config.Config<A>) => Config.Config<A>,\n  <A>(self: Config.Config<A>, description: string) => Config.Config<A>\n>(2, (self, description) => {\n  const described = Object.create(proto)\n  described._tag = OpCodes.OP_DESCRIBED\n  described.config = self\n  described.description = description\n  return described\n})\n\n/** @internal */\nexport const zip = dual<\n  <B>(that: Config.Config<B>) => <A>(self: Config.Config<A>) => Config.Config<[A, B]>,\n  <A, B>(self: Config.Config<A>, that: Config.Config<B>) => Config.Config<[A, B]>\n>(2, (self, that) => zipWith(self, that, (a, b) => [a, b]))\n\n/** @internal */\nexport const zipWith = dual<\n  <B, A, C>(that: Config.Config<B>, f: (a: A, b: B) => C) => (self: Config.Config<A>) => Config.Config<C>,\n  <A, B, C>(self: Config.Config<A>, that: Config.Config<B>, f: (a: A, b: B) => C) => Config.Config<C>\n>(3, (self, that, f) => {\n  const zipWith = Object.create(proto)\n  zipWith._tag = OpCodes.OP_ZIP_WITH\n  zipWith.left = self\n  zipWith.right = that\n  zipWith.zip = f\n  return zipWith\n})\n"
  },
  {
    "path": "packages/effect/src/internal/configError.ts",
    "content": "import * as RA from \"../Array.js\"\nimport type * as Cause from \"../Cause.js\"\nimport type * as ConfigError from \"../ConfigError.js\"\nimport * as Either from \"../Either.js\"\nimport { constFalse, constTrue, dual, pipe } from \"../Function.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport * as OpCodes from \"./opCodes/configError.js\"\n\n/** @internal */\nconst ConfigErrorSymbolKey = \"effect/ConfigError\"\n\n/** @internal */\nexport const ConfigErrorTypeId: ConfigError.ConfigErrorTypeId = Symbol.for(\n  ConfigErrorSymbolKey\n) as ConfigError.ConfigErrorTypeId\n\n/** @internal */\nexport const proto = {\n  _tag: \"ConfigError\",\n  [ConfigErrorTypeId]: ConfigErrorTypeId\n}\n\n/** @internal */\nexport const And = (self: ConfigError.ConfigError, that: ConfigError.ConfigError): ConfigError.ConfigError => {\n  const error = Object.create(proto)\n  error._op = OpCodes.OP_AND\n  error.left = self\n  error.right = that\n  Object.defineProperty(error, \"toString\", {\n    enumerable: false,\n    value(this: ConfigError.And) {\n      return `${this.left} and ${this.right}`\n    }\n  })\n  Object.defineProperty(error, \"message\", {\n    enumerable: false,\n    get(this: ConfigError.And) {\n      return this.toString()\n    }\n  })\n  return error\n}\n\n/** @internal */\nexport const Or = (self: ConfigError.ConfigError, that: ConfigError.ConfigError): ConfigError.ConfigError => {\n  const error = Object.create(proto)\n  error._op = OpCodes.OP_OR\n  error.left = self\n  error.right = that\n  Object.defineProperty(error, \"toString\", {\n    enumerable: false,\n    value(this: ConfigError.Or) {\n      return `${this.left} or ${this.right}`\n    }\n  })\n  Object.defineProperty(error, \"message\", {\n    enumerable: false,\n    get(this: ConfigError.Or) {\n      return this.toString()\n    }\n  })\n  return error\n}\n\n/** @internal */\nexport const InvalidData = (\n  path: ReadonlyArray<string>,\n  message: string,\n  options: ConfigError.Options = { pathDelim: \".\" }\n): ConfigError.ConfigError => {\n  const error = Object.create(proto)\n  error._op = OpCodes.OP_INVALID_DATA\n  error.path = path\n  error.message = message\n  Object.defineProperty(error, \"toString\", {\n    enumerable: false,\n    value(this: ConfigError.InvalidData) {\n      const path = pipe(this.path, RA.join(options.pathDelim))\n      return `(Invalid data at ${path}: \"${this.message}\")`\n    }\n  })\n  return error\n}\n\n/** @internal */\nexport const MissingData = (\n  path: ReadonlyArray<string>,\n  message: string,\n  options: ConfigError.Options = { pathDelim: \".\" }\n): ConfigError.ConfigError => {\n  const error = Object.create(proto)\n  error._op = OpCodes.OP_MISSING_DATA\n  error.path = path\n  error.message = message\n  Object.defineProperty(error, \"toString\", {\n    enumerable: false,\n    value(this: ConfigError.MissingData) {\n      const path = pipe(this.path, RA.join(options.pathDelim))\n      return `(Missing data at ${path}: \"${this.message}\")`\n    }\n  })\n  return error\n}\n\n/** @internal */\nexport const SourceUnavailable = (\n  path: ReadonlyArray<string>,\n  message: string,\n  cause: Cause.Cause<unknown>,\n  options: ConfigError.Options = { pathDelim: \".\" }\n): ConfigError.ConfigError => {\n  const error = Object.create(proto)\n  error._op = OpCodes.OP_SOURCE_UNAVAILABLE\n  error.path = path\n  error.message = message\n  error.cause = cause\n  Object.defineProperty(error, \"toString\", {\n    enumerable: false,\n    value(this: ConfigError.SourceUnavailable) {\n      const path = pipe(this.path, RA.join(options.pathDelim))\n      return `(Source unavailable at ${path}: \"${this.message}\")`\n    }\n  })\n  return error\n}\n\n/** @internal */\nexport const Unsupported = (\n  path: ReadonlyArray<string>,\n  message: string,\n  options: ConfigError.Options = { pathDelim: \".\" }\n): ConfigError.ConfigError => {\n  const error = Object.create(proto)\n  error._op = OpCodes.OP_UNSUPPORTED\n  error.path = path\n  error.message = message\n  Object.defineProperty(error, \"toString\", {\n    enumerable: false,\n    value(this: ConfigError.Unsupported) {\n      const path = pipe(this.path, RA.join(options.pathDelim))\n      return `(Unsupported operation at ${path}: \"${this.message}\")`\n    }\n  })\n  return error\n}\n\n/** @internal */\nexport const isConfigError = (u: unknown): u is ConfigError.ConfigError => hasProperty(u, ConfigErrorTypeId)\n\n/** @internal */\nexport const isAnd = (self: ConfigError.ConfigError): self is ConfigError.And => self._op === OpCodes.OP_AND\n\n/** @internal */\nexport const isOr = (self: ConfigError.ConfigError): self is ConfigError.Or => self._op === OpCodes.OP_OR\n\n/** @internal */\nexport const isInvalidData = (self: ConfigError.ConfigError): self is ConfigError.InvalidData =>\n  self._op === OpCodes.OP_INVALID_DATA\n\n/** @internal */\nexport const isMissingData = (self: ConfigError.ConfigError): self is ConfigError.MissingData =>\n  self._op === OpCodes.OP_MISSING_DATA\n\n/** @internal */\nexport const isSourceUnavailable = (self: ConfigError.ConfigError): self is ConfigError.SourceUnavailable =>\n  self._op === OpCodes.OP_SOURCE_UNAVAILABLE\n\n/** @internal */\nexport const isUnsupported = (self: ConfigError.ConfigError): self is ConfigError.Unsupported =>\n  self._op === OpCodes.OP_UNSUPPORTED\n\n/** @internal */\nexport const prefixed: {\n  (prefix: ReadonlyArray<string>): (self: ConfigError.ConfigError) => ConfigError.ConfigError\n  (self: ConfigError.ConfigError, prefix: ReadonlyArray<string>): ConfigError.ConfigError\n} = dual<\n  (prefix: ReadonlyArray<string>) => (self: ConfigError.ConfigError) => ConfigError.ConfigError,\n  (self: ConfigError.ConfigError, prefix: ReadonlyArray<string>) => ConfigError.ConfigError\n>(2, (self, prefix) => {\n  switch (self._op) {\n    case OpCodes.OP_AND: {\n      return And(prefixed(self.left, prefix), prefixed(self.right, prefix))\n    }\n    case OpCodes.OP_OR: {\n      return Or(prefixed(self.left, prefix), prefixed(self.right, prefix))\n    }\n    case OpCodes.OP_INVALID_DATA: {\n      return InvalidData([...prefix, ...self.path], self.message)\n    }\n    case OpCodes.OP_MISSING_DATA: {\n      return MissingData([...prefix, ...self.path], self.message)\n    }\n    case OpCodes.OP_SOURCE_UNAVAILABLE: {\n      return SourceUnavailable([...prefix, ...self.path], self.message, self.cause)\n    }\n    case OpCodes.OP_UNSUPPORTED: {\n      return Unsupported([...prefix, ...self.path], self.message)\n    }\n  }\n})\n\n/** @internal */\nconst IsMissingDataOnlyReducer: ConfigError.ConfigErrorReducer<unknown, boolean> = {\n  andCase: (_, left, right) => left && right,\n  orCase: (_, left, right) => left && right,\n  invalidDataCase: constFalse,\n  missingDataCase: constTrue,\n  sourceUnavailableCase: constFalse,\n  unsupportedCase: constFalse\n}\n\n/** @internal */\ntype ConfigErrorCase = AndCase | OrCase\n\n/** @internal */\ninterface AndCase {\n  readonly _op: \"AndCase\"\n}\n\n/** @internal */\ninterface OrCase {\n  readonly _op: \"OrCase\"\n}\n\n/** @internal */\nexport const reduceWithContext = dual<\n  <C, Z>(context: C, reducer: ConfigError.ConfigErrorReducer<C, Z>) => (self: ConfigError.ConfigError) => Z,\n  <C, Z>(self: ConfigError.ConfigError, context: C, reducer: ConfigError.ConfigErrorReducer<C, Z>) => Z\n>(3, <C, Z>(self: ConfigError.ConfigError, context: C, reducer: ConfigError.ConfigErrorReducer<C, Z>) => {\n  const input: Array<ConfigError.ConfigError> = [self]\n  const output: Array<Either.Either<Z, ConfigErrorCase>> = []\n  while (input.length > 0) {\n    const error = input.pop()!\n    switch (error._op) {\n      case OpCodes.OP_AND: {\n        input.push(error.right)\n        input.push(error.left)\n        output.push(Either.left({ _op: \"AndCase\" }))\n        break\n      }\n      case OpCodes.OP_OR: {\n        input.push(error.right)\n        input.push(error.left)\n        output.push(Either.left({ _op: \"OrCase\" }))\n        break\n      }\n      case OpCodes.OP_INVALID_DATA: {\n        output.push(Either.right(reducer.invalidDataCase(context, error.path, error.message)))\n        break\n      }\n      case OpCodes.OP_MISSING_DATA: {\n        output.push(Either.right(reducer.missingDataCase(context, error.path, error.message)))\n        break\n      }\n      case OpCodes.OP_SOURCE_UNAVAILABLE: {\n        output.push(Either.right(reducer.sourceUnavailableCase(context, error.path, error.message, error.cause)))\n        break\n      }\n      case OpCodes.OP_UNSUPPORTED: {\n        output.push(Either.right(reducer.unsupportedCase(context, error.path, error.message)))\n        break\n      }\n    }\n  }\n  const accumulator: Array<Z> = []\n  while (output.length > 0) {\n    const either = output.pop()!\n    switch (either._op) {\n      case \"Left\": {\n        switch (either.left._op) {\n          case \"AndCase\": {\n            const left = accumulator.pop()!\n            const right = accumulator.pop()!\n            const value = reducer.andCase(context, left, right)\n            accumulator.push(value)\n            break\n          }\n          case \"OrCase\": {\n            const left = accumulator.pop()!\n            const right = accumulator.pop()!\n            const value = reducer.orCase(context, left, right)\n            accumulator.push(value)\n            break\n          }\n        }\n        break\n      }\n      case \"Right\": {\n        accumulator.push(either.right)\n        break\n      }\n    }\n  }\n  if (accumulator.length === 0) {\n    throw new Error(\n      \"BUG: ConfigError.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues\"\n    )\n  }\n  return accumulator.pop()!\n})\n\n/** @internal */\nexport const isMissingDataOnly = (self: ConfigError.ConfigError): boolean =>\n  reduceWithContext(self, void 0, IsMissingDataOnlyReducer)\n"
  },
  {
    "path": "packages/effect/src/internal/configProvider/pathPatch.ts",
    "content": "import * as RA from \"../../Array.js\"\nimport type * as ConfigError from \"../../ConfigError.js\"\nimport type * as PathPatch from \"../../ConfigProviderPathPatch.js\"\nimport * as Either from \"../../Either.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as List from \"../../List.js\"\nimport * as Option from \"../../Option.js\"\nimport * as configError from \"../configError.js\"\n\n/** @internal */\nexport const empty: PathPatch.PathPatch = {\n  _tag: \"Empty\"\n}\n\n/** @internal */\nexport const andThen = dual<\n  (that: PathPatch.PathPatch) => (self: PathPatch.PathPatch) => PathPatch.PathPatch,\n  (self: PathPatch.PathPatch, that: PathPatch.PathPatch) => PathPatch.PathPatch\n>(2, (self, that) => ({\n  _tag: \"AndThen\",\n  first: self,\n  second: that\n}))\n\n/** @internal */\nexport const mapName = dual<\n  (f: (string: string) => string) => (self: PathPatch.PathPatch) => PathPatch.PathPatch,\n  (self: PathPatch.PathPatch, f: (string: string) => string) => PathPatch.PathPatch\n>(2, (self, f) => andThen(self, { _tag: \"MapName\", f }))\n\n/** @internal */\nexport const nested = dual<\n  (name: string) => (self: PathPatch.PathPatch) => PathPatch.PathPatch,\n  (self: PathPatch.PathPatch, name: string) => PathPatch.PathPatch\n>(2, (self, name) => andThen(self, { _tag: \"Nested\", name }))\n\n/** @internal */\nexport const unnested = dual<\n  (name: string) => (self: PathPatch.PathPatch) => PathPatch.PathPatch,\n  (self: PathPatch.PathPatch, name: string) => PathPatch.PathPatch\n>(2, (self, name) => andThen(self, { _tag: \"Unnested\", name }))\n\n/** @internal */\nexport const patch = dual<\n  (\n    patch: PathPatch.PathPatch\n  ) => (\n    path: ReadonlyArray<string>\n  ) => Either.Either<ReadonlyArray<string>, ConfigError.ConfigError>,\n  (\n    path: ReadonlyArray<string>,\n    patch: PathPatch.PathPatch\n  ) => Either.Either<ReadonlyArray<string>, ConfigError.ConfigError>\n>(2, (path, patch) => {\n  let input: List.List<PathPatch.PathPatch> = List.of(patch)\n  let output: ReadonlyArray<string> = path\n  while (List.isCons(input)) {\n    const patch: PathPatch.PathPatch = input.head\n    switch (patch._tag) {\n      case \"Empty\": {\n        input = input.tail\n        break\n      }\n      case \"AndThen\": {\n        input = List.cons(patch.first, List.cons(patch.second, input.tail))\n        break\n      }\n      case \"MapName\": {\n        output = RA.map(output, patch.f)\n        input = input.tail\n        break\n      }\n      case \"Nested\": {\n        output = RA.prepend(output, patch.name)\n        input = input.tail\n        break\n      }\n      case \"Unnested\": {\n        const containsName = pipe(\n          RA.head(output),\n          Option.contains(patch.name)\n        )\n        if (containsName) {\n          output = RA.tailNonEmpty(output as RA.NonEmptyArray<string>)\n          input = input.tail\n        } else {\n          return Either.left(configError.MissingData(\n            output,\n            `Expected ${patch.name} to be in path in ConfigProvider#unnested`\n          ))\n        }\n        break\n      }\n    }\n  }\n  return Either.right(output)\n})\n"
  },
  {
    "path": "packages/effect/src/internal/configProvider.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport type * as Config from \"../Config.js\"\nimport type * as ConfigError from \"../ConfigError.js\"\nimport type * as ConfigProvider from \"../ConfigProvider.js\"\nimport type * as PathPatch from \"../ConfigProviderPathPatch.js\"\nimport * as Context from \"../Context.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport * as HashMap from \"../HashMap.js\"\nimport * as HashSet from \"../HashSet.js\"\nimport * as number from \"../Number.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport * as Predicate from \"../Predicate.js\"\nimport * as regexp from \"../RegExp.js\"\nimport type * as _config from \"./config.js\"\nimport * as configError from \"./configError.js\"\nimport * as pathPatch from \"./configProvider/pathPatch.js\"\nimport * as core from \"./core.js\"\nimport * as OpCodes from \"./opCodes/config.js\"\nimport * as StringUtils from \"./string-utils.js\"\n\ntype KeyComponent = ConfigProvider.ConfigProvider.KeyComponent\n\nconst concat = <A, B>(l: ReadonlyArray<A>, r: ReadonlyArray<B>): ReadonlyArray<A | B> => [...l, ...r]\n\n/** @internal */\nconst ConfigProviderSymbolKey = \"effect/ConfigProvider\"\n\n/** @internal */\nexport const ConfigProviderTypeId: ConfigProvider.ConfigProviderTypeId = Symbol.for(\n  ConfigProviderSymbolKey\n) as ConfigProvider.ConfigProviderTypeId\n\n/** @internal */\nexport const configProviderTag: Context.Tag<ConfigProvider.ConfigProvider, ConfigProvider.ConfigProvider> = Context\n  .GenericTag(\n    \"effect/ConfigProvider\"\n  )\n\n/** @internal */\nconst FlatConfigProviderSymbolKey = \"effect/ConfigProviderFlat\"\n\n/** @internal */\nexport const FlatConfigProviderTypeId: ConfigProvider.FlatConfigProviderTypeId = Symbol.for(\n  FlatConfigProviderSymbolKey\n) as ConfigProvider.FlatConfigProviderTypeId\n\n/** @internal */\nexport const make = (\n  options: {\n    readonly load: <A>(config: Config.Config<A>) => Effect.Effect<A, ConfigError.ConfigError>\n    readonly flattened: ConfigProvider.ConfigProvider.Flat\n  }\n): ConfigProvider.ConfigProvider => ({\n  [ConfigProviderTypeId]: ConfigProviderTypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  ...options\n})\n\n/** @internal */\nexport const makeFlat = (\n  options: {\n    readonly load: <A>(\n      path: ReadonlyArray<string>,\n      config: Config.Config.Primitive<A>,\n      split: boolean\n    ) => Effect.Effect<Array<A>, ConfigError.ConfigError>\n    readonly enumerateChildren: (\n      path: ReadonlyArray<string>\n    ) => Effect.Effect<HashSet.HashSet<string>, ConfigError.ConfigError>\n    readonly patch: PathPatch.PathPatch\n  }\n): ConfigProvider.ConfigProvider.Flat => ({\n  [FlatConfigProviderTypeId]: FlatConfigProviderTypeId,\n  patch: options.patch,\n  load: (path, config, split = true) => options.load(path, config, split),\n  enumerateChildren: options.enumerateChildren\n})\n\n/** @internal */\nexport const fromFlat = (flat: ConfigProvider.ConfigProvider.Flat): ConfigProvider.ConfigProvider =>\n  make({\n    load: (config) =>\n      core.flatMap(fromFlatLoop(flat, Arr.empty(), config, false), (chunk) =>\n        Option.match(Arr.head(chunk), {\n          onNone: () =>\n            core.fail(\n              configError.MissingData(\n                Arr.empty(),\n                `Expected a single value having structure: ${config}`\n              )\n            ),\n          onSome: core.succeed\n        })),\n    flattened: flat\n  })\n\n/** @internal */\nexport const fromEnv = (\n  options?: Partial<ConfigProvider.ConfigProvider.FromEnvConfig>\n): ConfigProvider.ConfigProvider => {\n  const { pathDelim, seqDelim } = Object.assign({}, { pathDelim: \"_\", seqDelim: \",\" }, options)\n  const makePathString = (path: ReadonlyArray<string>): string => pipe(path, Arr.join(pathDelim))\n  const unmakePathString = (pathString: string): ReadonlyArray<string> => pathString.split(pathDelim)\n\n  const getEnv = () =>\n    typeof process !== \"undefined\" && \"env\" in process && typeof process.env === \"object\" ? process.env : {}\n\n  const load = <A>(\n    path: ReadonlyArray<string>,\n    primitive: Config.Config.Primitive<A>,\n    split = true\n  ): Effect.Effect<Array<A>, ConfigError.ConfigError> => {\n    const pathString = makePathString(path)\n    const current = getEnv()\n    const valueOpt = pathString in current ? Option.some(current[pathString]!) : Option.none()\n    return pipe(\n      valueOpt,\n      core.mapError(() => configError.MissingData(path, `Expected ${pathString} to exist in the process context`)),\n      core.flatMap((value) => parsePrimitive(value, path, primitive, seqDelim, split))\n    )\n  }\n\n  const enumerateChildren = (\n    path: ReadonlyArray<string>\n  ): Effect.Effect<HashSet.HashSet<string>, ConfigError.ConfigError> =>\n    core.sync(() => {\n      const current = getEnv()\n      const keys = Object.keys(current)\n      const keyPaths = keys.map((value) => unmakePathString(value.toUpperCase()))\n      const filteredKeyPaths = keyPaths.filter((keyPath) => {\n        for (let i = 0; i < path.length; i++) {\n          const pathComponent = pipe(path, Arr.unsafeGet(i))\n          const currentElement = keyPath[i]\n          if (currentElement === undefined || pathComponent !== currentElement) {\n            return false\n          }\n        }\n        return true\n      }).flatMap((keyPath) => keyPath.slice(path.length, path.length + 1))\n      return HashSet.fromIterable(filteredKeyPaths)\n    })\n\n  return fromFlat(makeFlat({ load, enumerateChildren, patch: pathPatch.empty }))\n}\n\n/** @internal */\nexport const fromMap = (\n  map: Map<string, string>,\n  config?: Partial<ConfigProvider.ConfigProvider.FromMapConfig>\n): ConfigProvider.ConfigProvider => {\n  const { pathDelim, seqDelim } = Object.assign({ seqDelim: \",\", pathDelim: \".\" }, config)\n  const makePathString = (path: ReadonlyArray<string>): string => pipe(path, Arr.join(pathDelim))\n  const unmakePathString = (pathString: string): ReadonlyArray<string> => pathString.split(pathDelim)\n  const mapWithIndexSplit = splitIndexInKeys(\n    map,\n    (str) => unmakePathString(str),\n    makePathString\n  )\n  const load = <A>(\n    path: ReadonlyArray<string>,\n    primitive: Config.Config.Primitive<A>,\n    split = true\n  ): Effect.Effect<Array<A>, ConfigError.ConfigError> => {\n    const pathString = makePathString(path)\n    const valueOpt = mapWithIndexSplit.has(pathString) ?\n      Option.some(mapWithIndexSplit.get(pathString)!) :\n      Option.none()\n    return pipe(\n      valueOpt,\n      core.mapError(() => configError.MissingData(path, `Expected ${pathString} to exist in the provided map`)),\n      core.flatMap((value) => parsePrimitive(value, path, primitive, seqDelim, split))\n    )\n  }\n  const enumerateChildren = (\n    path: ReadonlyArray<string>\n  ): Effect.Effect<HashSet.HashSet<string>, ConfigError.ConfigError> =>\n    core.sync(() => {\n      const keyPaths = Arr.fromIterable(mapWithIndexSplit.keys()).map(unmakePathString)\n      const filteredKeyPaths = keyPaths.filter((keyPath) => {\n        for (let i = 0; i < path.length; i++) {\n          const pathComponent = pipe(path, Arr.unsafeGet(i))\n          const currentElement = keyPath[i]\n          if (currentElement === undefined || pathComponent !== currentElement) {\n            return false\n          }\n        }\n        return true\n      }).flatMap((keyPath) => keyPath.slice(path.length, path.length + 1))\n      return HashSet.fromIterable(filteredKeyPaths)\n    })\n\n  return fromFlat(makeFlat({ load, enumerateChildren, patch: pathPatch.empty }))\n}\n\nconst extend = <A, B>(\n  leftDef: (n: number) => A,\n  rightDef: (n: number) => B,\n  left: ReadonlyArray<A>,\n  right: ReadonlyArray<B>\n): [ReadonlyArray<A>, ReadonlyArray<B>] => {\n  const leftPad = Arr.unfold(\n    left.length,\n    (index) =>\n      index >= right.length ?\n        Option.none() :\n        Option.some([leftDef(index), index + 1])\n  )\n  const rightPad = Arr.unfold(\n    right.length,\n    (index) =>\n      index >= left.length ?\n        Option.none() :\n        Option.some([rightDef(index), index + 1])\n  )\n  const leftExtension = concat(left, leftPad)\n  const rightExtension = concat(right, rightPad)\n  return [leftExtension, rightExtension]\n}\n\nconst appendConfigPath = (path: ReadonlyArray<string>, config: Config.Config<unknown>): ReadonlyArray<string> => {\n  let op = config as _config.ConfigPrimitive\n  if (op._tag === \"Nested\") {\n    const out = path.slice()\n    while (op._tag === \"Nested\") {\n      out.push(op.name)\n      op = op.config as _config.ConfigPrimitive\n    }\n    return out\n  }\n  return path\n}\n\nconst fromFlatLoop = <A>(\n  flat: ConfigProvider.ConfigProvider.Flat,\n  prefix: ReadonlyArray<string>,\n  config: Config.Config<A>,\n  split: boolean\n): Effect.Effect<Array<A>, ConfigError.ConfigError> => {\n  const op = config as _config.ConfigPrimitive\n  switch (op._tag) {\n    case OpCodes.OP_CONSTANT: {\n      return core.succeed(Arr.of(op.value)) as Effect.Effect<Array<A>, ConfigError.ConfigError>\n    }\n    case OpCodes.OP_DESCRIBED: {\n      return core.suspend(\n        () => fromFlatLoop(flat, prefix, op.config, split)\n      ) as unknown as Effect.Effect<Array<A>, ConfigError.ConfigError>\n    }\n    case OpCodes.OP_FAIL: {\n      return core.fail(configError.MissingData(prefix, op.message)) as Effect.Effect<\n        Array<A>,\n        ConfigError.ConfigError\n      >\n    }\n    case OpCodes.OP_FALLBACK: {\n      return pipe(\n        core.suspend(() => fromFlatLoop(flat, prefix, op.first, split)),\n        core.catchAll((error1) => {\n          if (op.condition(error1)) {\n            return pipe(\n              fromFlatLoop(flat, prefix, op.second, split),\n              core.catchAll((error2) => core.fail(configError.Or(error1, error2)))\n            )\n          }\n          return core.fail(error1)\n        })\n      ) as unknown as Effect.Effect<Array<A>, ConfigError.ConfigError>\n    }\n    case OpCodes.OP_LAZY: {\n      return core.suspend(() => fromFlatLoop(flat, prefix, op.config(), split)) as Effect.Effect<\n        Array<A>,\n        ConfigError.ConfigError\n      >\n    }\n    case OpCodes.OP_MAP_OR_FAIL: {\n      return core.suspend(() =>\n        pipe(\n          fromFlatLoop(flat, prefix, op.original, split),\n          core.flatMap(\n            core.forEachSequential((a) =>\n              pipe(\n                op.mapOrFail(a),\n                core.mapError(configError.prefixed(appendConfigPath(prefix, op.original)))\n              )\n            )\n          )\n        )\n      ) as unknown as Effect.Effect<Array<A>, ConfigError.ConfigError>\n    }\n    case OpCodes.OP_NESTED: {\n      return core.suspend(() =>\n        fromFlatLoop(\n          flat,\n          concat(prefix, Arr.of(op.name)),\n          op.config,\n          split\n        )\n      ) as unknown as Effect.Effect<Array<A>, ConfigError.ConfigError>\n    }\n    case OpCodes.OP_PRIMITIVE: {\n      return pipe(\n        pathPatch.patch(prefix, flat.patch),\n        core.flatMap((prefix) =>\n          pipe(\n            flat.load(prefix, op, split),\n            core.flatMap((values) => {\n              if (values.length === 0) {\n                const name = pipe(Arr.last(prefix), Option.getOrElse(() => \"<n/a>\"))\n                return core.fail(configError.MissingData([], `Expected ${op.description} with name ${name}`))\n              }\n              return core.succeed(values)\n            })\n          )\n        )\n      ) as unknown as Effect.Effect<Array<A>, ConfigError.ConfigError>\n    }\n    case OpCodes.OP_SEQUENCE: {\n      return pipe(\n        pathPatch.patch(prefix, flat.patch),\n        core.flatMap((patchedPrefix) =>\n          pipe(\n            flat.enumerateChildren(patchedPrefix),\n            core.flatMap(indicesFrom),\n            core.flatMap((indices) => {\n              if (indices.length === 0) {\n                return core.suspend(() =>\n                  core.map(fromFlatLoop(flat, prefix, op.config, true), Arr.of)\n                ) as unknown as Effect.Effect<Array<A>, ConfigError.ConfigError>\n              }\n              return pipe(\n                core.forEachSequential(\n                  indices,\n                  (index) => fromFlatLoop(flat, Arr.append(prefix, `[${index}]`), op.config, true)\n                ),\n                core.map((chunkChunk) => {\n                  const flattened = Arr.flatten(chunkChunk)\n                  if (flattened.length === 0) {\n                    return Arr.of(Arr.empty<A>())\n                  }\n                  return Arr.of(flattened)\n                })\n              ) as unknown as Effect.Effect<Array<A>, ConfigError.ConfigError>\n            })\n          )\n        )\n      )\n    }\n    case OpCodes.OP_HASHMAP: {\n      return core.suspend(() =>\n        pipe(\n          pathPatch.patch(prefix, flat.patch),\n          core.flatMap((prefix) =>\n            pipe(\n              flat.enumerateChildren(prefix),\n              core.flatMap((keys) => {\n                return pipe(\n                  keys,\n                  core.forEachSequential((key) =>\n                    fromFlatLoop(\n                      flat,\n                      concat(prefix, Arr.of(key)),\n                      op.valueConfig,\n                      split\n                    )\n                  ),\n                  core.map((matrix) => {\n                    if (matrix.length === 0) {\n                      return Arr.of(HashMap.empty())\n                    }\n                    return pipe(\n                      transpose(matrix),\n                      Arr.map((values) => HashMap.fromIterable(Arr.zip(Arr.fromIterable(keys), values)))\n                    )\n                  })\n                )\n              })\n            )\n          )\n        )\n      ) as unknown as Effect.Effect<Array<A>, ConfigError.ConfigError>\n    }\n    case OpCodes.OP_ZIP_WITH: {\n      return core.suspend(() =>\n        pipe(\n          fromFlatLoop(flat, prefix, op.left, split),\n          core.either,\n          core.flatMap((left) =>\n            pipe(\n              fromFlatLoop(flat, prefix, op.right, split),\n              core.either,\n              core.flatMap((right) => {\n                if (Either.isLeft(left) && Either.isLeft(right)) {\n                  return core.fail(configError.And(left.left, right.left))\n                }\n                if (Either.isLeft(left) && Either.isRight(right)) {\n                  return core.fail(left.left)\n                }\n                if (Either.isRight(left) && Either.isLeft(right)) {\n                  return core.fail(right.left)\n                }\n                if (Either.isRight(left) && Either.isRight(right)) {\n                  const path = pipe(prefix, Arr.join(\".\"))\n                  const fail = fromFlatLoopFail(prefix, path)\n                  const [lefts, rights] = extend(\n                    fail,\n                    fail,\n                    pipe(left.right, Arr.map(Either.right)),\n                    pipe(right.right, Arr.map(Either.right))\n                  )\n                  return pipe(\n                    lefts,\n                    Arr.zip(rights),\n                    core.forEachSequential(([left, right]) =>\n                      pipe(\n                        core.zip(left, right),\n                        core.map(([left, right]) => op.zip(left, right))\n                      )\n                    )\n                  )\n                }\n                throw new Error(\n                  \"BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues\"\n                )\n              })\n            )\n          )\n        )\n      ) as unknown as Effect.Effect<Array<A>, ConfigError.ConfigError>\n    }\n  }\n}\n\nconst fromFlatLoopFail =\n  (prefix: ReadonlyArray<string>, path: string) => (index: number): Either.Either<unknown, ConfigError.ConfigError> =>\n    Either.left(\n      configError.MissingData(\n        prefix,\n        `The element at index ${index} in a sequence at path \"${path}\" was missing`\n      )\n    )\n\n/** @internal */\nexport const mapInputPath = dual<\n  (f: (path: string) => string) => (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider,\n  (self: ConfigProvider.ConfigProvider, f: (path: string) => string) => ConfigProvider.ConfigProvider\n>(2, (self, f) => fromFlat(mapInputPathFlat(self.flattened, f)))\n\nconst mapInputPathFlat = (\n  self: ConfigProvider.ConfigProvider.Flat,\n  f: (path: string) => string\n): ConfigProvider.ConfigProvider.Flat =>\n  makeFlat({\n    load: (path, config, split = true) => self.load(path, config, split),\n    enumerateChildren: (path) => self.enumerateChildren(path),\n    patch: pathPatch.mapName(self.patch, f)\n  })\n\n/** @internal */\nexport const nested = dual<\n  (name: string) => (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider,\n  (self: ConfigProvider.ConfigProvider, name: string) => ConfigProvider.ConfigProvider\n>(2, (self, name) =>\n  fromFlat(makeFlat({\n    load: (path, config) => self.flattened.load(path, config, true),\n    enumerateChildren: (path) => self.flattened.enumerateChildren(path),\n    patch: pathPatch.nested(self.flattened.patch, name)\n  })))\n\n/** @internal */\nexport const unnested = dual<\n  (name: string) => (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider,\n  (self: ConfigProvider.ConfigProvider, name: string) => ConfigProvider.ConfigProvider\n>(2, (self, name) =>\n  fromFlat(makeFlat({\n    load: (path, config) => self.flattened.load(path, config, true),\n    enumerateChildren: (path) => self.flattened.enumerateChildren(path),\n    patch: pathPatch.unnested(self.flattened.patch, name)\n  })))\n\n/** @internal */\nexport const orElse = dual<\n  (\n    that: LazyArg<ConfigProvider.ConfigProvider>\n  ) => (\n    self: ConfigProvider.ConfigProvider\n  ) => ConfigProvider.ConfigProvider,\n  (\n    self: ConfigProvider.ConfigProvider,\n    that: LazyArg<ConfigProvider.ConfigProvider>\n  ) => ConfigProvider.ConfigProvider\n>(2, (self, that) => fromFlat(orElseFlat(self.flattened, () => that().flattened)))\n\nconst orElseFlat = (\n  self: ConfigProvider.ConfigProvider.Flat,\n  that: LazyArg<ConfigProvider.ConfigProvider.Flat>\n): ConfigProvider.ConfigProvider.Flat =>\n  makeFlat({\n    load: (path, config, split) =>\n      pipe(\n        pathPatch.patch(path, self.patch),\n        core.flatMap((patch) => self.load(patch, config, split)),\n        core.catchAll((error1) =>\n          pipe(\n            core.sync(that),\n            core.flatMap((that) =>\n              pipe(\n                pathPatch.patch(path, that.patch),\n                core.flatMap((patch) => that.load(patch, config, split)),\n                core.catchAll((error2) => core.fail(configError.Or(error1, error2)))\n              )\n            )\n          )\n        )\n      ),\n    enumerateChildren: (path) =>\n      pipe(\n        pathPatch.patch(path, self.patch),\n        core.flatMap((patch) => self.enumerateChildren(patch)),\n        core.either,\n        core.flatMap((left) =>\n          pipe(\n            core.sync(that),\n            core.flatMap((that) =>\n              pipe(\n                pathPatch.patch(path, that.patch),\n                core.flatMap((patch) => that.enumerateChildren(patch)),\n                core.either,\n                core.flatMap((right) => {\n                  if (Either.isLeft(left) && Either.isLeft(right)) {\n                    return core.fail(configError.And(left.left, right.left))\n                  }\n                  if (Either.isLeft(left) && Either.isRight(right)) {\n                    return core.succeed(right.right)\n                  }\n                  if (Either.isRight(left) && Either.isLeft(right)) {\n                    return core.succeed(left.right)\n                  }\n                  if (Either.isRight(left) && Either.isRight(right)) {\n                    return core.succeed(pipe(left.right, HashSet.union(right.right)))\n                  }\n                  throw new Error(\n                    \"BUG: ConfigProvider.orElseFlat - please report an issue at https://github.com/Effect-TS/effect/issues\"\n                  )\n                })\n              )\n            )\n          )\n        )\n      ),\n    patch: pathPatch.empty\n  })\n\n/** @internal */\nexport const constantCase = (self: ConfigProvider.ConfigProvider): ConfigProvider.ConfigProvider =>\n  mapInputPath(self, StringUtils.constantCase)\n\n/** @internal */\nexport const kebabCase = (self: ConfigProvider.ConfigProvider): ConfigProvider.ConfigProvider =>\n  mapInputPath(self, StringUtils.kebabCase)\n\n/** @internal */\nexport const lowerCase = (self: ConfigProvider.ConfigProvider): ConfigProvider.ConfigProvider =>\n  mapInputPath(self, StringUtils.lowerCase)\n\n/** @internal */\nexport const snakeCase = (self: ConfigProvider.ConfigProvider): ConfigProvider.ConfigProvider =>\n  mapInputPath(self, StringUtils.snakeCase)\n\n/** @internal */\nexport const upperCase = (self: ConfigProvider.ConfigProvider): ConfigProvider.ConfigProvider =>\n  mapInputPath(self, StringUtils.upperCase)\n\n/** @internal */\nexport const within = dual<\n  (\n    path: ReadonlyArray<string>,\n    f: (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider\n  ) => (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider,\n  (\n    self: ConfigProvider.ConfigProvider,\n    path: ReadonlyArray<string>,\n    f: (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider\n  ) => ConfigProvider.ConfigProvider\n>(3, (self, path, f) => {\n  const unnest = Arr.reduce(path, self, (provider, name) => unnested(provider, name))\n  const nest = Arr.reduceRight(path, f(unnest), (provider, name) => nested(provider, name))\n  return orElse(nest, () => self)\n})\n\nconst splitPathString = (text: string, delim: string): Array<string> => {\n  const split = text.split(new RegExp(`\\\\s*${regexp.escape(delim)}\\\\s*`))\n  return split\n}\n\nconst parsePrimitive = <A>(\n  text: string,\n  path: ReadonlyArray<string>,\n  primitive: Config.Config.Primitive<A>,\n  delimiter: string,\n  split: boolean\n): Effect.Effect<Array<A>, ConfigError.ConfigError> => {\n  if (!split) {\n    return pipe(\n      primitive.parse(text),\n      core.mapBoth({\n        onFailure: configError.prefixed(path),\n        onSuccess: Arr.of\n      })\n    )\n  }\n  return pipe(\n    splitPathString(text, delimiter),\n    core.forEachSequential((char) => primitive.parse(char.trim())),\n    core.mapError(configError.prefixed(path))\n  )\n}\n\nconst transpose = <A>(array: ReadonlyArray<ReadonlyArray<A>>): Array<Array<A>> => {\n  return Object.keys(array[0]).map((column) => array.map((row) => row[column as any]))\n}\n\nconst indicesFrom = (quotedIndices: HashSet.HashSet<string>): Effect.Effect<Array<number>> =>\n  pipe(\n    core.forEachSequential(quotedIndices, parseQuotedIndex),\n    core.mapBoth({\n      onFailure: () => Arr.empty<number>(),\n      onSuccess: Arr.sort(number.Order)\n    }),\n    core.either,\n    core.map(Either.merge)\n  )\n\nconst STR_INDEX_REGEX = /(^.+)(\\[(\\d+)\\])$/\nconst QUOTED_INDEX_REGEX = /^(\\[(\\d+)\\])$/\n\nconst parseQuotedIndex = (str: string): Option.Option<number> => {\n  const match = str.match(QUOTED_INDEX_REGEX)\n  if (match !== null) {\n    const matchedIndex = match[2]\n    return pipe(\n      matchedIndex !== undefined && matchedIndex.length > 0 ?\n        Option.some(matchedIndex) :\n        Option.none(),\n      Option.flatMap(parseInteger)\n    )\n  }\n  return Option.none()\n}\n\nconst splitIndexInKeys = (\n  map: Map<string, string>,\n  unmakePathString: (str: string) => ReadonlyArray<string>,\n  makePathString: (chunk: ReadonlyArray<string>) => string\n): Map<string, string> => {\n  const newMap: Map<string, string> = new Map()\n  for (const [pathString, value] of map) {\n    const keyWithIndex = pipe(\n      unmakePathString(pathString),\n      Arr.flatMap((key) =>\n        Option.match(splitIndexFrom(key), {\n          onNone: () => Arr.of(key),\n          onSome: ([key, index]) => Arr.make(key, `[${index}]`)\n        })\n      )\n    )\n    newMap.set(makePathString(keyWithIndex), value)\n  }\n  return newMap\n}\n\nconst splitIndexFrom = (key: string): Option.Option<[string, number]> => {\n  const match = key.match(STR_INDEX_REGEX)\n  if (match !== null) {\n    const matchedString = match[1]\n    const matchedIndex = match[3]\n    const optionalString = matchedString !== undefined && matchedString.length > 0 ?\n      Option.some(matchedString) :\n      Option.none()\n    const optionalIndex = pipe(\n      matchedIndex !== undefined && matchedIndex.length > 0 ?\n        Option.some(matchedIndex) :\n        Option.none(),\n      Option.flatMap(parseInteger)\n    )\n    return Option.all([optionalString, optionalIndex])\n  }\n  return Option.none()\n}\n\nconst parseInteger = (str: string): Option.Option<number> => {\n  const parsedIndex = Number.parseInt(str)\n  return Number.isNaN(parsedIndex) ?\n    Option.none() :\n    Option.some(parsedIndex)\n}\n\nconst keyName = (name: string): KeyComponent => ({\n  _tag: \"KeyName\",\n  name\n})\n\nconst keyIndex = (index: number): KeyComponent => ({\n  _tag: \"KeyIndex\",\n  index\n})\n\ninterface JsonMap {\n  [member: string]: string | number | boolean | null | JsonArray | JsonMap\n}\ninterface JsonArray extends Array<string | number | boolean | null | JsonArray | JsonMap> {}\n\n/** @internal */\nexport const fromJson = (json: unknown): ConfigProvider.ConfigProvider => {\n  const hiddenDelimiter = \"\\ufeff\"\n  const indexedEntries = Arr.map(\n    getIndexedEntries(json as JsonMap),\n    ([key, value]): [string, string] => [configPathToString(key).join(hiddenDelimiter), value]\n  )\n  return fromMap(new Map(indexedEntries), {\n    pathDelim: hiddenDelimiter,\n    seqDelim: hiddenDelimiter\n  })\n}\n\nconst configPathToString = (path: ReadonlyArray<KeyComponent>): ReadonlyArray<string> => {\n  const output: Array<string> = []\n  let i = 0\n  while (i < path.length) {\n    const component = path[i]\n    if (component._tag === \"KeyName\") {\n      if (i + 1 < path.length) {\n        const nextComponent = path[i + 1]\n        if (nextComponent._tag === \"KeyIndex\") {\n          output.push(`${component.name}[${nextComponent.index}]`)\n          i += 2\n        } else {\n          output.push(component.name)\n          i += 1\n        }\n      } else {\n        output.push(component.name)\n        i += 1\n      }\n    }\n  }\n  return output\n}\n\nconst getIndexedEntries = (\n  config: JsonMap\n): ReadonlyArray<[path: ReadonlyArray<KeyComponent>, value: string]> => {\n  const loopAny = (\n    path: ReadonlyArray<KeyComponent>,\n    value: string | number | boolean | JsonMap | JsonArray | null\n  ): ReadonlyArray<[path: ReadonlyArray<KeyComponent>, value: string]> => {\n    if (typeof value === \"string\") {\n      return Arr.make([path, value] as [ReadonlyArray<KeyComponent>, string])\n    }\n    if (typeof value === \"number\" || typeof value === \"boolean\") {\n      return Arr.make([path, String(value)] as [ReadonlyArray<KeyComponent>, string])\n    }\n    if (Arr.isArray(value)) {\n      return loopArray(path, value)\n    }\n    if (typeof value === \"object\" && value !== null) {\n      return loopObject(path, value)\n    }\n    return Arr.empty<[ReadonlyArray<KeyComponent>, string]>()\n  }\n  const loopArray = (\n    path: ReadonlyArray<KeyComponent>,\n    values: JsonArray\n  ): ReadonlyArray<[path: ReadonlyArray<KeyComponent>, value: string]> =>\n    Arr.match(values, {\n      onEmpty: () => Arr.make([path, \"<nil>\"] as [ReadonlyArray<KeyComponent>, string]),\n      onNonEmpty: Arr.flatMap((value, index) => loopAny(Arr.append(path, keyIndex(index)), value))\n    })\n  const loopObject = (\n    path: ReadonlyArray<KeyComponent>,\n    value: JsonMap\n  ): ReadonlyArray<[path: ReadonlyArray<KeyComponent>, value: string]> =>\n    Object.entries(value)\n      .filter(([, value]) => Predicate.isNotNullable(value))\n      .flatMap(([key, value]) => {\n        const newPath = Arr.append(path, keyName(key))\n        const result = loopAny(newPath, value)\n        if (Arr.isEmptyReadonlyArray(result)) {\n          return Arr.make([newPath, \"\"] as [ReadonlyArray<KeyComponent>, string])\n        }\n        return result\n      })\n  return loopObject(Arr.empty(), config)\n}\n"
  },
  {
    "path": "packages/effect/src/internal/console.ts",
    "content": "import type * as Console from \"../Console.js\"\nimport * as Context from \"../Context.js\"\nimport type * as Effect from \"../Effect.js\"\nimport { dual } from \"../Function.js\"\nimport type * as Layer from \"../Layer.js\"\nimport type * as Scope from \"../Scope.js\"\nimport * as core from \"./core.js\"\nimport * as defaultServices from \"./defaultServices.js\"\nimport * as defaultConsole from \"./defaultServices/console.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\nimport * as layer from \"./layer.js\"\n\n/** @internal */\nexport const console: Effect.Effect<Console.Console> = core.map(\n  core.fiberRefGet(defaultServices.currentServices),\n  Context.get(defaultConsole.consoleTag)\n)\n\n/** @internal */\nexport const consoleWith = <A, E, R>(f: (console: Console.Console) => Effect.Effect<A, E, R>) =>\n  core.fiberRefGetWith(\n    defaultServices.currentServices,\n    (services) => f(Context.get(services, defaultConsole.consoleTag))\n  )\n\n/** @internal */\nexport const withConsole = dual<\n  <C extends Console.Console>(console: C) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R, C extends Console.Console>(effect: Effect.Effect<A, E, R>, console: C) => Effect.Effect<A, E, R>\n>(2, (effect, value) =>\n  core.fiberRefLocallyWith(\n    effect,\n    defaultServices.currentServices,\n    Context.add(defaultConsole.consoleTag, value)\n  ))\n\n/** @internal */\nexport const withConsoleScoped = <A extends Console.Console>(console: A): Effect.Effect<void, never, Scope.Scope> =>\n  fiberRuntime.fiberRefLocallyScopedWith(\n    defaultServices.currentServices,\n    Context.add(defaultConsole.consoleTag, console)\n  )\n\n/** @internal */\nexport const setConsole = <A extends Console.Console>(console: A): Layer.Layer<never> =>\n  layer.scopedDiscard(\n    fiberRuntime.fiberRefLocallyScopedWith(\n      defaultServices.currentServices,\n      Context.add(defaultConsole.consoleTag, console)\n    )\n  )\n\n/** @internal */\nexport const assert = (condition: boolean, ...args: ReadonlyArray<any>) =>\n  consoleWith((_) => _.assert(condition, ...args))\n\n/** @internal */\nexport const clear = consoleWith((_) => _.clear)\n\n/** @internal */\nexport const count = (label?: string) => consoleWith((_) => _.count(label))\n\n/** @internal */\nexport const countReset = (label?: string) => consoleWith((_) => _.countReset(label))\n\n/** @internal */\nexport const debug = (...args: ReadonlyArray<any>) => consoleWith((_) => _.debug(...args))\n\n/** @internal */\nexport const dir = (item: any, options?: any) => consoleWith((_) => _.dir(item, options))\n\n/** @internal */\nexport const dirxml = (...args: ReadonlyArray<any>) => consoleWith((_) => _.dirxml(...args))\n\n/** @internal */\nexport const error = (...args: ReadonlyArray<any>) => consoleWith((_) => _.error(...args))\n\n/** @internal */\nexport const group = (options?: {\n  label?: string | undefined\n  collapsed?: boolean | undefined\n}) =>\n  consoleWith((_) =>\n    fiberRuntime.acquireRelease(\n      _.group(options),\n      () => _.groupEnd\n    )\n  )\n\n/** @internal */\nexport const info = (...args: ReadonlyArray<any>) => consoleWith((_) => _.info(...args))\n\n/** @internal */\nexport const log = (...args: ReadonlyArray<any>) => consoleWith((_) => _.log(...args))\n\n/** @internal */\nexport const table = (tabularData: any, properties?: ReadonlyArray<string>) =>\n  consoleWith((_) => _.table(tabularData, properties))\n\n/** @internal */\nexport const time = (label?: string) =>\n  consoleWith((_) =>\n    fiberRuntime.acquireRelease(\n      _.time(label),\n      () => _.timeEnd(label)\n    )\n  )\n\n/** @internal */\nexport const timeLog = (label?: string, ...args: ReadonlyArray<any>) => consoleWith((_) => _.timeLog(label, ...args))\n\n/** @internal */\nexport const trace = (...args: ReadonlyArray<any>) => consoleWith((_) => _.trace(...args))\n\n/** @internal */\nexport const warn = (...args: ReadonlyArray<any>) => consoleWith((_) => _.warn(...args))\n\n/** @internal */\nexport const withGroup = dual<\n  (\n    options?: {\n      readonly label?: string | undefined\n      readonly collapsed?: boolean | undefined\n    }\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    options?: {\n      readonly label?: string | undefined\n      readonly collapsed?: boolean | undefined\n    }\n  ) => Effect.Effect<A, E, R>\n>((args) => core.isEffect(args[0]), (self, options) =>\n  consoleWith((_) =>\n    core.acquireUseRelease(\n      _.group(options),\n      () => self,\n      () => _.groupEnd\n    )\n  ))\n\n/** @internal */\nexport const withTime = dual<\n  (label?: string) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, label?: string) => Effect.Effect<A, E, R>\n>((args) => core.isEffect(args[0]), (self, label) =>\n  consoleWith((_) =>\n    core.acquireUseRelease(\n      _.time(label),\n      () => self,\n      () => _.timeEnd(label)\n    )\n  ))\n"
  },
  {
    "path": "packages/effect/src/internal/context.ts",
    "content": "import type * as C from \"../Context.js\"\nimport * as Equal from \"../Equal.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { dual } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport * as Hash from \"../Hash.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"../Inspectable.js\"\nimport type * as O from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as STM from \"../STM.js\"\nimport type { NoInfer } from \"../Types.js\"\nimport { EffectPrototype, effectVariance } from \"./effectable.js\"\nimport * as option from \"./option.js\"\n\n/** @internal */\nexport const TagTypeId: C.TagTypeId = Symbol.for(\"effect/Context/Tag\") as C.TagTypeId\n\n/** @internal */\nexport const ReferenceTypeId: C.ReferenceTypeId = Symbol.for(\"effect/Context/Reference\") as C.ReferenceTypeId\n\n/** @internal */\nconst STMSymbolKey = \"effect/STM\"\n\n/** @internal */\nexport const STMTypeId: STM.STMTypeId = Symbol.for(\n  STMSymbolKey\n) as STM.STMTypeId\n\n/** @internal */\nexport const TagProto: any = {\n  ...EffectPrototype,\n  _op: \"Tag\",\n  [STMTypeId]: effectVariance,\n  [TagTypeId]: {\n    _Service: (_: unknown) => _,\n    _Identifier: (_: unknown) => _\n  },\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON<I, A>(this: C.Tag<I, A>) {\n    return {\n      _id: \"Tag\",\n      key: this.key,\n      stack: this.stack\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  of<Service>(self: Service): Service {\n    return self\n  },\n  context<Identifier, Service>(\n    this: C.Tag<Identifier, Service>,\n    self: Service\n  ): C.Context<Identifier> {\n    return make(this, self)\n  }\n}\n\nexport const ReferenceProto: any = {\n  ...TagProto,\n  [ReferenceTypeId]: ReferenceTypeId\n}\n\n/** @internal */\nexport const makeGenericTag = <Identifier, Service = Identifier>(key: string): C.Tag<Identifier, Service> => {\n  const limit = Error.stackTraceLimit\n  Error.stackTraceLimit = 2\n  const creationError = new Error()\n  Error.stackTraceLimit = limit\n  const tag = Object.create(TagProto)\n  Object.defineProperty(tag, \"stack\", {\n    get() {\n      return creationError.stack\n    }\n  })\n  tag.key = key\n  return tag\n}\n\n/** @internal */\nexport const Tag = <const Id extends string>(id: Id) => <Self, Shape>(): C.TagClass<Self, Id, Shape> => {\n  const limit = Error.stackTraceLimit\n  Error.stackTraceLimit = 2\n  const creationError = new Error()\n  Error.stackTraceLimit = limit\n\n  function TagClass() {}\n  Object.setPrototypeOf(TagClass, TagProto)\n  TagClass.key = id\n  Object.defineProperty(TagClass, \"stack\", {\n    get() {\n      return creationError.stack\n    }\n  })\n  return TagClass as any\n}\n\n/** @internal */\nexport const Reference = <Self>() =>\n<const Id extends string, Service>(id: Id, options: {\n  readonly defaultValue: () => Service\n}): C.ReferenceClass<Self, Id, Service> => {\n  const limit = Error.stackTraceLimit\n  Error.stackTraceLimit = 2\n  const creationError = new Error()\n  Error.stackTraceLimit = limit\n\n  function ReferenceClass() {}\n  Object.setPrototypeOf(ReferenceClass, ReferenceProto)\n  ReferenceClass.key = id\n  ReferenceClass.defaultValue = options.defaultValue\n  Object.defineProperty(ReferenceClass, \"stack\", {\n    get() {\n      return creationError.stack\n    }\n  })\n  return ReferenceClass as any\n}\n\n/** @internal */\nexport const TypeId: C.TypeId = Symbol.for(\"effect/Context\") as C.TypeId\n\n/** @internal */\nexport const ContextProto: Omit<C.Context<unknown>, \"unsafeMap\"> = {\n  [TypeId]: {\n    _Services: (_: unknown) => _\n  },\n  [Equal.symbol]<A>(this: C.Context<A>, that: unknown): boolean {\n    if (isContext(that)) {\n      if (this.unsafeMap.size === that.unsafeMap.size) {\n        for (const k of this.unsafeMap.keys()) {\n          if (!that.unsafeMap.has(k) || !Equal.equals(this.unsafeMap.get(k), that.unsafeMap.get(k))) {\n            return false\n          }\n        }\n        return true\n      }\n    }\n    return false\n  },\n  [Hash.symbol]<A>(this: C.Context<A>): number {\n    return Hash.cached(this, Hash.number(this.unsafeMap.size))\n  },\n  pipe<A>(this: C.Context<A>) {\n    return pipeArguments(this, arguments)\n  },\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON<A>(this: C.Context<A>) {\n    return {\n      _id: \"Context\",\n      services: Array.from(this.unsafeMap).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return (this as any).toJSON()\n  }\n}\n\n/** @internal */\nexport const makeContext = <Services>(unsafeMap: Map<string, any>): C.Context<Services> => {\n  const context = Object.create(ContextProto)\n  context.unsafeMap = unsafeMap\n  return context\n}\n\nconst serviceNotFoundError = (tag: C.Tag<any, any>) => {\n  const error = new Error(`Service not found${tag.key ? `: ${String(tag.key)}` : \"\"}`)\n  if (tag.stack) {\n    const lines = tag.stack.split(\"\\n\")\n    if (lines.length > 2) {\n      const afterAt = lines[2].match(/at (.*)/)\n      if (afterAt) {\n        error.message = error.message + ` (defined at ${afterAt[1]})`\n      }\n    }\n  }\n  if (error.stack) {\n    const lines = error.stack.split(\"\\n\")\n    lines.splice(1, 3)\n    error.stack = lines.join(\"\\n\")\n  }\n  return error\n}\n\n/** @internal */\nexport const isContext = (u: unknown): u is C.Context<never> => hasProperty(u, TypeId)\n\n/** @internal */\nexport const isTag = (u: unknown): u is C.Tag<any, any> => hasProperty(u, TagTypeId)\n\n/** @internal */\nexport const isReference = (u: unknown): u is C.Reference<any, any> => hasProperty(u, ReferenceTypeId)\n\nconst _empty = makeContext(new Map())\n\n/** @internal */\nexport const empty = (): C.Context<never> => _empty\n\n/** @internal */\nexport const make = <I, S>(tag: C.Tag<I, S>, service: NoInfer<S>): C.Context<I> =>\n  makeContext(new Map([[tag.key, service]]))\n\n/** @internal */\nexport const add = dual<\n  <I, S>(\n    tag: C.Tag<I, S>,\n    service: NoInfer<S>\n  ) => <Services>(\n    self: C.Context<Services>\n  ) => C.Context<Services | I>,\n  <Services, I, S>(\n    self: C.Context<Services>,\n    tag: C.Tag<I, S>,\n    service: NoInfer<S>\n  ) => C.Context<Services | I>\n>(3, (self, tag, service) => {\n  const map = new Map(self.unsafeMap)\n  map.set(tag.key, service)\n  return makeContext(map)\n})\n\nconst defaultValueCache = globalValue(\"effect/Context/defaultValueCache\", () => new Map<string, any>())\nconst getDefaultValue = (tag: C.Reference<any, any>) => {\n  if (defaultValueCache.has(tag.key)) {\n    return defaultValueCache.get(tag.key)\n  }\n  const value = tag.defaultValue()\n  defaultValueCache.set(tag.key, value)\n  return value\n}\n\n/** @internal */\nexport const unsafeGetReference = <Services, I, S>(self: C.Context<Services>, tag: C.Reference<I, S>): S => {\n  return self.unsafeMap.has(tag.key) ? self.unsafeMap.get(tag.key) : getDefaultValue(tag)\n}\n\n/** @internal */\nexport const unsafeGet = dual<\n  <S, I>(tag: C.Tag<I, S>) => <Services>(self: C.Context<Services>) => S,\n  <Services, S, I>(self: C.Context<Services>, tag: C.Tag<I, S>) => S\n>(2, (self, tag) => {\n  if (!self.unsafeMap.has(tag.key)) {\n    if (ReferenceTypeId in tag) return getDefaultValue(tag as any)\n    throw serviceNotFoundError(tag)\n  }\n  return self.unsafeMap.get(tag.key)! as any\n})\n\n/** @internal */\nexport const get: {\n  <I, S>(tag: C.Reference<I, S>): <Services>(self: C.Context<Services>) => S\n  <Services, I extends Services, S>(tag: C.Tag<I, S>): (self: C.Context<Services>) => S\n  <Services, I, S>(self: C.Context<Services>, tag: C.Reference<I, S>): S\n  <Services, I extends Services, S>(self: C.Context<Services>, tag: C.Tag<I, S>): S\n} = unsafeGet as any\n\n/** @internal */\nexport const getOrElse = dual<\n  <S, I, B>(tag: C.Tag<I, S>, orElse: LazyArg<B>) => <Services>(self: C.Context<Services>) => S | B,\n  <Services, S, I, B>(self: C.Context<Services>, tag: C.Tag<I, S>, orElse: LazyArg<B>) => S | B\n>(3, (self, tag, orElse) => {\n  if (!self.unsafeMap.has(tag.key)) {\n    return isReference(tag) ? getDefaultValue(tag) : orElse()\n  }\n  return self.unsafeMap.get(tag.key)! as any\n})\n\n/** @internal */\nexport const getOption = dual<\n  <S, I>(tag: C.Tag<I, S>) => <Services>(self: C.Context<Services>) => O.Option<S>,\n  <Services, S, I>(self: C.Context<Services>, tag: C.Tag<I, S>) => O.Option<S>\n>(2, (self, tag) => {\n  if (!self.unsafeMap.has(tag.key)) {\n    return isReference(tag) ? option.some(getDefaultValue(tag)) : option.none\n  }\n  return option.some(self.unsafeMap.get(tag.key)! as any)\n})\n\n/** @internal */\nexport const merge = dual<\n  <R1>(that: C.Context<R1>) => <Services>(self: C.Context<Services>) => C.Context<Services | R1>,\n  <Services, R1>(self: C.Context<Services>, that: C.Context<R1>) => C.Context<Services | R1>\n>(2, (self, that) => {\n  const map = new Map(self.unsafeMap)\n  for (const [tag, s] of that.unsafeMap) {\n    map.set(tag, s)\n  }\n  return makeContext(map)\n})\n\n/** @internal */\nexport const mergeAll = <T extends Array<unknown>>(\n  ...ctxs: [...{ [K in keyof T]: C.Context<T[K]> }]\n): C.Context<T[number]> => {\n  const map = new Map()\n  for (let i = 0; i < ctxs.length; i++) {\n    ctxs[i].unsafeMap.forEach((value, key) => {\n      map.set(key, value)\n    })\n  }\n  return makeContext(map)\n}\n\n/** @internal */\nexport const pick =\n  <Tags extends ReadonlyArray<C.Tag<any, any>>>(...tags: Tags) =>\n  <Services>(self: C.Context<Services>): C.Context<\n    Services & C.Tag.Identifier<Tags[number]>\n  > => {\n    const tagSet = new Set<string>(tags.map((_) => _.key))\n    const newEnv = new Map()\n    for (const [tag, s] of self.unsafeMap.entries()) {\n      if (tagSet.has(tag)) {\n        newEnv.set(tag, s)\n      }\n    }\n    return makeContext(newEnv)\n  }\n\n/** @internal */\nexport const omit =\n  <Tags extends ReadonlyArray<C.Tag<any, any>>>(...tags: Tags) =>\n  <Services>(self: C.Context<Services>): C.Context<\n    Exclude<Services, C.Tag.Identifier<Tags[number]>>\n  > => {\n    const newEnv = new Map(self.unsafeMap)\n    for (const tag of tags) {\n      newEnv.delete(tag.key)\n    }\n    return makeContext(newEnv)\n  }\n"
  },
  {
    "path": "packages/effect/src/internal/core-effect.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport type * as Cause from \"../Cause.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport * as Clock from \"../Clock.js\"\nimport * as Context from \"../Context.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport type { Exit } from \"../Exit.js\"\nimport type * as Fiber from \"../Fiber.js\"\nimport type * as FiberId from \"../FiberId.js\"\nimport type * as FiberRef from \"../FiberRef.js\"\nimport * as FiberRefs from \"../FiberRefs.js\"\nimport type * as FiberRefsPatch from \"../FiberRefsPatch.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { constFalse, constTrue, constVoid, dual, identity, pipe } from \"../Function.js\"\nimport * as HashMap from \"../HashMap.js\"\nimport * as HashSet from \"../HashSet.js\"\nimport * as List from \"../List.js\"\nimport * as LogLevel from \"../LogLevel.js\"\nimport * as LogSpan from \"../LogSpan.js\"\nimport type * as Metric from \"../Metric.js\"\nimport type * as MetricLabel from \"../MetricLabel.js\"\nimport * as Option from \"../Option.js\"\nimport * as Predicate from \"../Predicate.js\"\nimport type * as Random from \"../Random.js\"\nimport * as Ref from \"../Ref.js\"\nimport type * as runtimeFlagsPatch from \"../RuntimeFlagsPatch.js\"\nimport * as Tracer from \"../Tracer.js\"\nimport type * as Types from \"../Types.js\"\nimport type { Unify } from \"../Unify.js\"\nimport { internalCall } from \"../Utils.js\"\nimport * as internalCause from \"./cause.js\"\nimport { clockTag } from \"./clock.js\"\nimport * as core from \"./core.js\"\nimport * as defaultServices from \"./defaultServices.js\"\nimport * as doNotation from \"./doNotation.js\"\nimport * as fiberRefsPatch from \"./fiberRefs/patch.js\"\nimport type { FiberRuntime } from \"./fiberRuntime.js\"\nimport * as metricLabel from \"./metric/label.js\"\nimport * as runtimeFlags from \"./runtimeFlags.js\"\nimport * as internalTracer from \"./tracer.js\"\n\n/* @internal */\nexport const annotateLogs = dual<\n  {\n    (key: string, value: unknown): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n    (\n      values: Record<string, unknown>\n    ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  },\n  {\n    <A, E, R>(effect: Effect.Effect<A, E, R>, key: string, value: unknown): Effect.Effect<A, E, R>\n    <A, E, R>(effect: Effect.Effect<A, E, R>, values: Record<string, unknown>): Effect.Effect<A, E, R>\n  }\n>(\n  (args) => core.isEffect(args[0]),\n  function<A, E, R>() {\n    const args = arguments\n    return core.fiberRefLocallyWith(\n      args[0] as Effect.Effect<A, E, R>,\n      core.currentLogAnnotations,\n      typeof args[1] === \"string\"\n        ? HashMap.set(args[1], args[2])\n        : (annotations) =>\n          Object.entries(args[1] as Record<string, unknown>).reduce(\n            (acc, [key, value]) => HashMap.set(acc, key, value),\n            annotations\n          )\n    )\n  }\n)\n\n/* @internal */\nexport const asSome = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<Option.Option<A>, E, R> =>\n  core.map(self, Option.some)\n\n/* @internal */\nexport const asSomeError = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, Option.Option<E>, R> =>\n  core.mapError(self, Option.some)\n\n/* @internal */\nexport const try_: {\n  <A, E>(options: {\n    readonly try: LazyArg<A>\n    readonly catch: (error: unknown) => E\n  }): Effect.Effect<A, E>\n  <A>(thunk: LazyArg<A>): Effect.Effect<A, Cause.UnknownException>\n} = <A, E>(\n  arg: LazyArg<A> | {\n    readonly try: LazyArg<A>\n    readonly catch: (error: unknown) => E\n  }\n) => {\n  let evaluate: LazyArg<A>\n  let onFailure: ((error: unknown) => E) | undefined = undefined\n  if (typeof arg === \"function\") {\n    evaluate = arg\n  } else {\n    evaluate = arg.try\n    onFailure = arg.catch\n  }\n  return core.suspend(() => {\n    try {\n      return core.succeed(internalCall(evaluate))\n    } catch (error) {\n      return core.fail(\n        onFailure\n          ? internalCall(() => onFailure(error))\n          : new core.UnknownException(error, \"An unknown error occurred in Effect.try\")\n      )\n    }\n  })\n}\n\n/* @internal */\nexport const _catch: {\n  <N extends keyof E, K extends E[N] & string, E, A1, E1, R1>(\n    discriminator: N,\n    options: {\n      readonly failure: K\n      readonly onFailure: (error: Extract<E, { [n in N]: K }>) => Effect.Effect<A1, E1, R1>\n    }\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<\n    A | A1,\n    Exclude<E, { [n in N]: K }> | E1,\n    R | R1\n  >\n  <A, E, R, N extends keyof E, K extends E[N] & string, A1, E1, R1>(\n    self: Effect.Effect<A, E, R>,\n    discriminator: N,\n    options: {\n      readonly failure: K\n      readonly onFailure: (error: Extract<E, { [n in N]: K }>) => Effect.Effect<A1, E1, R1>\n    }\n  ): Effect.Effect<A | A1, Exclude<E, { [n in N]: K }> | E1, R | R1>\n} = dual(\n  3,\n  (self, tag, options) =>\n    core.catchAll(self, (e) => {\n      if (Predicate.hasProperty(e, tag) && e[tag] === options.failure) {\n        return options.onFailure(e)\n      }\n      return core.fail(e)\n    })\n)\n\n/* @internal */\nexport const catchAllDefect = dual<\n  <A2, E2, R2>(\n    f: (defect: unknown) => Effect.Effect<A2, E2, R2>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A | A2, E | E2, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (defect: unknown) => Effect.Effect<A2, E2, R2>\n  ) => Effect.Effect<A | A2, E | E2, R | R2>\n>(2, <A, E, R, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  f: (defect: unknown) => Effect.Effect<A2, E2, R2>\n): Effect.Effect<A | A2, E | E2, R | R2> =>\n  core.catchAllCause(\n    self,\n    (cause): Effect.Effect<A | A2, E | E2, R | R2> => {\n      const option = internalCause.find(cause, (_) => internalCause.isDieType(_) ? Option.some(_) : Option.none())\n      switch (option._tag) {\n        case \"None\": {\n          return core.failCause(cause)\n        }\n        case \"Some\": {\n          return f(option.value.defect)\n        }\n      }\n    }\n  ))\n\n/* @internal */\nexport const catchSomeCause: {\n  <E, A2, E2, R2>(\n    f: (cause: Cause.Cause<Types.NoInfer<E>>) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A, E | E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (cause: Cause.Cause<Types.NoInfer<E>>) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ): Effect.Effect<A2 | A, E | E2, R2 | R>\n} = dual(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (cause: Cause.Cause<Types.NoInfer<E>>) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ): Effect.Effect<A2 | A, E | E2, R2 | R> =>\n    core.matchCauseEffect(self, {\n      onFailure: (cause): Effect.Effect<A2, E | E2, R2> => {\n        const option = f(cause)\n        switch (option._tag) {\n          case \"None\": {\n            return core.failCause(cause)\n          }\n          case \"Some\": {\n            return option.value\n          }\n        }\n      },\n      onSuccess: core.succeed\n    })\n)\n\n/* @internal */\nexport const catchSomeDefect = dual<\n  <A2, E2, R2>(\n    pf: (defect: unknown) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A | A2, E | E2, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    pf: (defect: unknown) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ) => Effect.Effect<A | A2, E | E2, R | R2>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    pf: (defect: unknown) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ): Effect.Effect<A | A2, E | E2, R | R2> =>\n    core.catchAllCause(\n      self,\n      (cause): Effect.Effect<A | A2, E | E2, R | R2> => {\n        const option = internalCause.find(cause, (_) => internalCause.isDieType(_) ? Option.some(_) : Option.none())\n        switch (option._tag) {\n          case \"None\": {\n            return core.failCause(cause)\n          }\n          case \"Some\": {\n            const optionEffect = pf(option.value.defect)\n            return optionEffect._tag === \"Some\" ? optionEffect.value : core.failCause(cause)\n          }\n        }\n      }\n    )\n)\n\n/* @internal */\nexport const catchTag: {\n  <\n    E,\n    const K extends Arr.NonEmptyReadonlyArray<E extends { _tag: string } ? E[\"_tag\"] : never>,\n    A1,\n    E1,\n    R1\n  >(\n    ...args: [\n      ...tags: K,\n      f: (e: Extract<Types.NoInfer<E>, { _tag: K[number] }>) => Effect.Effect<A1, E1, R1>\n    ]\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A | A1, Exclude<E, { _tag: K[number] }> | E1, R | R1>\n  <\n    A,\n    E,\n    R,\n    const K extends Arr.NonEmptyReadonlyArray<E extends { _tag: string } ? E[\"_tag\"] : never>,\n    A1,\n    E1,\n    R1\n  >(\n    self: Effect.Effect<A, E, R>,\n    ...args: [\n      ...tags: K,\n      f: (e: Extract<Types.NoInfer<E>, { _tag: K[number] }>) => Effect.Effect<A1, E1, R1>\n    ]\n  ): Effect.Effect<A | A1, Exclude<E, { _tag: K[number] }> | E1, R | R1>\n} = dual(\n  (args: any) => core.isEffect(args[0]),\n  <A, E, R, const K extends Arr.NonEmptyReadonlyArray<E extends { _tag: string } ? E[\"_tag\"] : never>, R1, E1, A1>(\n    self: Effect.Effect<A, E, R>,\n    ...args: [\n      ...tags: K & { [I in keyof K]: E extends { _tag: string } ? E[\"_tag\"] : never },\n      f: (e: Extract<Types.NoInfer<E>, { _tag: K[number] }>) => Effect.Effect<A1, E1, R1>\n    ]\n  ): Effect.Effect<A | A1, Exclude<E, { _tag: K[number] }> | E1, R | R1> => {\n    const f = args[args.length - 1] as any\n    let predicate: Predicate.Predicate<E>\n    if (args.length === 2) {\n      predicate = Predicate.isTagged(args[0] as string)\n    } else {\n      predicate = (e) => {\n        const tag = Predicate.hasProperty(e, \"_tag\") ? e[\"_tag\"] : undefined\n        if (!tag) return false\n        for (let i = 0; i < args.length - 1; i++) {\n          if (args[i] === tag) return true\n        }\n        return false\n      }\n    }\n    return core.catchIf(self, predicate as Predicate.Refinement<E, Extract<E, { _tag: K[number] }>>, f) as any\n  }\n) as any\n\n/** @internal */\nexport const catchTags: {\n  <\n    E,\n    Cases extends (E extends { _tag: string } ? {\n        [K in E[\"_tag\"]]+?: (error: Extract<E, { _tag: K }>) => Effect.Effect<any, any, any>\n      } :\n      {})\n  >(\n    cases: Cases\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<\n    | A\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => Effect.Effect<infer A, any, any>) ? A : never\n    }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => Effect.Effect<any, infer E, any>) ? E : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => Effect.Effect<any, any, infer R>) ? R : never\n    }[keyof Cases]\n  >\n  <\n    R,\n    E,\n    A,\n    Cases extends (E extends { _tag: string } ? {\n        [K in E[\"_tag\"]]+?: (error: Extract<E, { _tag: K }>) => Effect.Effect<any, any, any>\n      } :\n      {})\n  >(\n    self: Effect.Effect<A, E, R>,\n    cases: Cases\n  ): Effect.Effect<\n    | A\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => Effect.Effect<infer A, any, any>) ? A : never\n    }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => Effect.Effect<any, infer E, any>) ? E : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => Effect.Effect<any, any, infer R>) ? R : never\n    }[keyof Cases]\n  >\n} = dual(2, (self, cases) => {\n  let keys: Array<string>\n  return core.catchIf(\n    self,\n    (e): e is { readonly _tag: string } => {\n      keys ??= Object.keys(cases)\n      return Predicate.hasProperty(e, \"_tag\") && Predicate.isString(e[\"_tag\"]) && keys.includes(e[\"_tag\"])\n    },\n    (e) => cases[e[\"_tag\"]](e)\n  )\n})\n\n/* @internal */\nexport const cause = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<Cause.Cause<E>, never, R> =>\n  core.matchCause(self, { onFailure: identity, onSuccess: () => internalCause.empty })\n\n/* @internal */\nexport const clockWith: <A, E, R>(f: (clock: Clock.Clock) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> =\n  Clock.clockWith\n\n/* @internal */\nexport const clock: Effect.Effect<Clock.Clock> = clockWith(core.succeed)\n\n/* @internal */\nexport const delay = dual<\n  (duration: Duration.DurationInput) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, duration: Duration.DurationInput) => Effect.Effect<A, E, R>\n>(2, (self, duration) => core.zipRight(Clock.sleep(duration), self))\n\n/* @internal */\nexport const descriptorWith = <A, E, R>(\n  f: (descriptor: Fiber.Fiber.Descriptor) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> =>\n  core.withFiberRuntime((state, status) =>\n    f({\n      id: state.id(),\n      status,\n      interruptors: internalCause.interruptors(state.getFiberRef(core.currentInterruptedCause))\n    })\n  ) as Effect.Effect<A, E, R>\n\n/* @internal */\nexport const allowInterrupt: Effect.Effect<void> = descriptorWith(\n  (descriptor) =>\n    HashSet.size(descriptor.interruptors) > 0\n      ? core.interrupt\n      : core.void\n)\n\n/* @internal */\nexport const descriptor: Effect.Effect<Fiber.Fiber.Descriptor> = descriptorWith(core.succeed)\n\n/* @internal */\nexport const diffFiberRefs = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Effect.Effect<[FiberRefsPatch.FiberRefsPatch, A], E, R> => summarized(self, fiberRefs, fiberRefsPatch.diff)\n\n/* @internal */\nexport const diffFiberRefsAndRuntimeFlags = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Effect.Effect<[[FiberRefsPatch.FiberRefsPatch, runtimeFlagsPatch.RuntimeFlagsPatch], A], E, R> =>\n  summarized(\n    self,\n    core.zip(fiberRefs, core.runtimeFlags),\n    ([refs, flags], [refsNew, flagsNew]) => [fiberRefsPatch.diff(refs, refsNew), runtimeFlags.diff(flags, flagsNew)]\n  )\n\n/* @internal */\nexport const Do: Effect.Effect<{}> = core.succeed({})\n\n/* @internal */\nexport const bind: {\n  <N extends string, A extends object, B, E2, R2>(\n    name: Exclude<N, keyof A>,\n    f: (a: Types.NoInfer<A>) => Effect.Effect<B, E2, R2>\n  ): <E1, R1>(\n    self: Effect.Effect<A, E1, R1>\n  ) => Effect.Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E2 | E1, R2 | R1>\n  <A extends object, N extends string, E1, R1, B, E2, R2>(\n    self: Effect.Effect<A, E1, R1>,\n    name: Exclude<N, keyof A>,\n    f: (a: Types.NoInfer<A>) => Effect.Effect<B, E2, R2>\n  ): Effect.Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E1 | E2, R1 | R2>\n} = doNotation.bind<Effect.EffectTypeLambda>(core.map, core.flatMap)\n\n/* @internal */\nexport const bindTo: {\n  <N extends string>(name: N): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<{ [K in N]: A }, E, R>\n  <A, E, R, N extends string>(self: Effect.Effect<A, E, R>, name: N): Effect.Effect<{ [K in N]: A }, E, R>\n} = doNotation.bindTo<Effect.EffectTypeLambda>(core.map)\n\n/* @internal */\nexport const let_: {\n  <N extends string, A extends object, B>(\n    name: Exclude<N, keyof A>,\n    f: (a: Types.NoInfer<A>) => B\n  ): <E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E, R>\n  <A extends object, N extends string, E, R, B>(\n    self: Effect.Effect<A, E, R>,\n    name: Exclude<N, keyof A>,\n    f: (a: Types.NoInfer<A>) => B\n  ): Effect.Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E, R>\n} = doNotation.let_<Effect.EffectTypeLambda>(core.map)\n\n/* @internal */\nexport const dropUntil: {\n  <A, E, R>(\n    predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>\n  ): (elements: Iterable<A>) => Effect.Effect<Array<A>, E, R>\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: A, i: number) => Effect.Effect<boolean, E, R>\n  ): Effect.Effect<Array<A>, E, R>\n} = dual(\n  2,\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: A, i: number) => Effect.Effect<boolean, E, R>\n  ): Effect.Effect<Array<A>, E, R> =>\n    core.suspend(() => {\n      const iterator = elements[Symbol.iterator]()\n      const builder: Array<A> = []\n      let next: IteratorResult<A, any>\n      let dropping: Effect.Effect<boolean, E, R> = core.succeed(false)\n      let i = 0\n      while ((next = iterator.next()) && !next.done) {\n        const a = next.value\n        const index = i++\n        dropping = core.flatMap(dropping, (bool) => {\n          if (bool) {\n            builder.push(a)\n            return core.succeed(true)\n          }\n          return predicate(a, index)\n        })\n      }\n      return core.map(dropping, () => builder)\n    })\n)\n\n/* @internal */\nexport const dropWhile: {\n  <A, E, R>(\n    predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>\n  ): (elements: Iterable<A>) => Effect.Effect<Array<A>, E, R>\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: A, i: number) => Effect.Effect<boolean, E, R>\n  ): Effect.Effect<Array<A>, E, R>\n} = dual(\n  2,\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: A, i: number) => Effect.Effect<boolean, E, R>\n  ): Effect.Effect<Array<A>, E, R> =>\n    core.suspend(() => {\n      const iterator = elements[Symbol.iterator]()\n      const builder: Array<A> = []\n      let next\n      let dropping: Effect.Effect<boolean, E, R> = core.succeed(true)\n      let i = 0\n      while ((next = iterator.next()) && !next.done) {\n        const a = next.value\n        const index = i++\n        dropping = core.flatMap(dropping, (d) =>\n          core.map(d ? predicate(a, index) : core.succeed(false), (b) => {\n            if (!b) {\n              builder.push(a)\n            }\n            return b\n          }))\n      }\n      return core.map(dropping, () => builder)\n    })\n)\n\n/* @internal */\nexport const contextWith = <R, A>(f: (context: Context.Context<R>) => A): Effect.Effect<A, never, R> =>\n  core.map(core.context<R>(), f)\n\n/* @internal */\nexport const eventually = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, never, R> =>\n  core.orElse(self, () => core.flatMap(core.yieldNow(), () => eventually(self)))\n\n/* @internal */\nexport const filterMap = dual<\n  <Eff extends Effect.Effect<any, any, any>, B>(\n    pf: (a: Effect.Effect.Success<Eff>) => Option.Option<B>\n  ) => (elements: Iterable<Eff>) => Effect.Effect<Array<B>, Effect.Effect.Error<Eff>, Effect.Effect.Context<Eff>>,\n  <Eff extends Effect.Effect<any, any, any>, B>(\n    elements: Iterable<Eff>,\n    pf: (a: Effect.Effect.Success<Eff>) => Option.Option<B>\n  ) => Effect.Effect<Array<B>, Effect.Effect.Error<Eff>, Effect.Effect.Context<Eff>>\n>(2, (elements, pf) =>\n  core.map(\n    core.forEachSequential(elements, identity),\n    Arr.filterMap(pf)\n  ))\n\n/* @internal */\nexport const filterOrDie: {\n  <A, B extends A>(\n    refinement: Predicate.Refinement<Types.NoInfer<A>, B>,\n    orDieWith: (a: Types.EqualsWith<A, B, A, Exclude<A, B>>) => unknown\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E, R>\n  <A>(\n    predicate: Predicate.Predicate<Types.NoInfer<A>>,\n    orDieWith: (a: Types.NoInfer<A>) => unknown\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R, B extends A>(\n    self: Effect.Effect<A, E, R>,\n    refinement: Predicate.Refinement<A, B>,\n    orDieWith: (a: Types.EqualsWith<A, B, A, Exclude<A, B>>) => unknown\n  ): Effect.Effect<B, E, R>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    predicate: Predicate.Predicate<A>,\n    orDieWith: (a: A) => unknown\n  ): Effect.Effect<A, E, R>\n} = dual(\n  3,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    predicate: Predicate.Predicate<A>,\n    orDieWith: (a: A) => unknown\n  ): Effect.Effect<A, E, R> => filterOrElse(self, predicate, (a) => core.dieSync(() => orDieWith(a)))\n)\n\n/* @internal */\nexport const filterOrDieMessage: {\n  <A, B extends A>(\n    refinement: Predicate.Refinement<Types.NoInfer<A>, B>,\n    message: string\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E, R>\n  <A>(\n    predicate: Predicate.Predicate<Types.NoInfer<A>>,\n    message: string\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R, B extends A>(\n    self: Effect.Effect<A, E, R>,\n    refinement: Predicate.Refinement<A, B>,\n    message: string\n  ): Effect.Effect<B, E, R>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    predicate: Predicate.Predicate<A>,\n    message: string\n  ): Effect.Effect<A, E, R>\n} = dual(\n  3,\n  <A, E, R>(self: Effect.Effect<A, E, R>, predicate: Predicate.Predicate<A>, message: string): Effect.Effect<A, E, R> =>\n    filterOrElse(self, predicate, () => core.dieMessage(message))\n)\n\n/* @internal */\nexport const filterOrElse: {\n  <A, C, E2, R2, B extends A>(\n    refinement: Predicate.Refinement<Types.NoInfer<A>, B>,\n    orElse: (a: Types.EqualsWith<A, B, Types.NoInfer<A>, Exclude<Types.NoInfer<A>, B>>) => Effect.Effect<C, E2, R2>\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B | C, E2 | E, R2 | R>\n  <A, C, E2, R2>(\n    predicate: Predicate.Predicate<Types.NoInfer<A>>,\n    orElse: (a: Types.NoInfer<A>) => Effect.Effect<C, E2, R2>\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A | C, E2 | E, R2 | R>\n  <A, E, R, C, E2, R2, B extends A>(\n    self: Effect.Effect<A, E, R>,\n    refinement: Predicate.Refinement<A, B>,\n    orElse: (a: Types.EqualsWith<A, B, A, Exclude<A, B>>) => Effect.Effect<C, E2, R2>\n  ): Effect.Effect<B | C, E | E2, R | R2>\n  <A, E, R, C, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    predicate: Predicate.Predicate<A>,\n    orElse: (a: A) => Effect.Effect<C, E2, R2>\n  ): Effect.Effect<A | C, E | E2, R | R2>\n} = dual(3, <A, E, R, B, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  predicate: Predicate.Predicate<A>,\n  orElse: (a: A) => Effect.Effect<B, E2, R2>\n): Effect.Effect<A | B, E | E2, R | R2> =>\n  core.flatMap(\n    self,\n    (a) => predicate(a) ? core.succeed<A | B>(a) : orElse(a)\n  ))\n\n/** @internal */\nexport const liftPredicate = dual<\n  <T extends A, E, B extends T = T, A = T>(\n    predicate: Predicate.Refinement<T, B> | Predicate.Predicate<T>,\n    orFailWith: (a: Types.EqualsWith<T, B, A, Exclude<A, B>>) => E\n  ) => (a: A) => Effect.Effect<Types.EqualsWith<T, B, A, B>, E>,\n  <A, E, B extends A = A>(\n    self: A,\n    predicate: Predicate.Refinement<A, B> | Predicate.Predicate<A>,\n    orFailWith: (a: Types.EqualsWith<A, B, A, Exclude<A, B>>) => E\n  ) => Effect.Effect<B, E>\n>(\n  3,\n  <A, E, B extends A = A>(\n    self: A,\n    predicate: Predicate.Refinement<A, B> | Predicate.Predicate<A>,\n    orFailWith: (a: Types.EqualsWith<A, B, A, Exclude<A, B>>) => E\n  ): Effect.Effect<B, E> =>\n    core.suspend(() => predicate(self) ? core.succeed(self as B) : core.fail(orFailWith(self as any)))\n)\n\n/* @internal */\nexport const filterOrFail: {\n  <A, E2, B extends A>(\n    refinement: Predicate.Refinement<Types.NoInfer<A>, B>,\n    orFailWith: (a: Types.EqualsWith<A, B, Types.NoInfer<A>, Exclude<Types.NoInfer<A>, B>>) => E2\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Types.NoInfer<B>, E2 | E, R>\n  <A, E2>(\n    predicate: Predicate.Predicate<Types.NoInfer<A>>,\n    orFailWith: (a: Types.NoInfer<A>) => E2\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E2 | E, R>\n  <A, E, R, E2, B extends A>(\n    self: Effect.Effect<A, E, R>,\n    refinement: Predicate.Refinement<A, B>,\n    orFailWith: (a: Types.EqualsWith<A, B, A, Exclude<A, B>>) => E2\n  ): Effect.Effect<Types.NoInfer<B>, E2 | E, R>\n  <A, E, R, E2>(\n    self: Effect.Effect<A, E, R>,\n    predicate: Predicate.Predicate<A>,\n    orFailWith: (a: A) => E2\n  ): Effect.Effect<A, E2 | E, R>\n  <A, B extends A>(\n    refinement: Predicate.Refinement<Types.NoInfer<A>, B>\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Types.NoInfer<B>, Cause.NoSuchElementException | E, R>\n  <A>(\n    predicate: Predicate.Predicate<Types.NoInfer<A>>\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, Cause.NoSuchElementException | E, R>\n  <A, E, R, B extends A>(\n    self: Effect.Effect<A, E, R>,\n    refinement: Predicate.Refinement<A, B>\n  ): Effect.Effect<Types.NoInfer<B>, E | Cause.NoSuchElementException, R>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    predicate: Predicate.Predicate<A>\n  ): Effect.Effect<A, E | Cause.NoSuchElementException, R>\n} = dual((args) => core.isEffect(args[0]), <A, E, R, E2>(\n  self: Effect.Effect<A, E, R>,\n  predicate: Predicate.Predicate<A>,\n  orFailWith?: (a: A) => E2\n): Effect.Effect<A, E | E2 | Cause.NoSuchElementException, R> =>\n  filterOrElse(\n    self,\n    predicate,\n    (a): Effect.Effect<never, E2 | Cause.NoSuchElementException, never> =>\n      orFailWith === undefined ? core.fail(new core.NoSuchElementException()) : core.failSync(() => orFailWith(a))\n  ))\n\n/* @internal */\nexport const findFirst: {\n  <A, E, R>(\n    predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>\n  ): (elements: Iterable<A>) => Effect.Effect<Option.Option<A>, E, R>\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>\n  ): Effect.Effect<Option.Option<A>, E, R>\n} = dual(\n  2,\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>\n  ): Effect.Effect<Option.Option<A>, E, R> =>\n    core.suspend(() => {\n      const iterator = elements[Symbol.iterator]()\n      const next = iterator.next()\n      if (!next.done) {\n        return findLoop(iterator, 0, predicate, next.value)\n      }\n      return core.succeed(Option.none())\n    })\n)\n\nconst findLoop = <A, E, R>(\n  iterator: Iterator<A>,\n  index: number,\n  f: (a: A, i: number) => Effect.Effect<boolean, E, R>,\n  value: A\n): Effect.Effect<Option.Option<A>, E, R> =>\n  core.flatMap(f(value, index), (result) => {\n    if (result) {\n      return core.succeed(Option.some(value))\n    }\n    const next = iterator.next()\n    if (!next.done) {\n      return findLoop(iterator, index + 1, f, next.value)\n    }\n    return core.succeed(Option.none())\n  })\n\n/* @internal */\nexport const firstSuccessOf = <Eff extends Effect.Effect<any, any, any>>(\n  effects: Iterable<Eff>\n): Effect.Effect<Effect.Effect.Success<Eff>, Effect.Effect.Error<Eff>, Effect.Effect.Context<Eff>> =>\n  core.suspend(() => {\n    const list = Chunk.fromIterable(effects)\n    if (!Chunk.isNonEmpty(list)) {\n      return core.dieSync(() => new core.IllegalArgumentException(`Received an empty collection of effects`))\n    }\n    return pipe(\n      Chunk.tailNonEmpty(list),\n      Arr.reduce(Chunk.headNonEmpty(list), (left, right) => core.orElse(left, () => right) as Eff)\n    )\n  })\n\n/* @internal */\nexport const flipWith: {\n  <E, A, R, E2, A2, R2>(\n    f: (effect: Effect.Effect<E, A, R>) => Effect.Effect<E2, A2, R2>\n  ): (self: Effect.Effect<A, E, R>) => Effect.Effect<A2, E2, R2>\n  <A, E, R, E2, A2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (effect: Effect.Effect<E, A, R>) => Effect.Effect<E2, A2, R2>\n  ): Effect.Effect<A2, E2, R2>\n} = dual(2, <A, E, R, E2, A2, R2>(\n  self: Effect.Effect<A, E, R>,\n  f: (effect: Effect.Effect<E, A, R>) => Effect.Effect<E2, A2, R2>\n): Effect.Effect<A2, E2, R2> => core.flip(f(core.flip(self))))\n\n/* @internal */\nexport const match: {\n  <E, A2, A, A3>(\n    options: {\n      readonly onFailure: (error: E) => A2\n      readonly onSuccess: (value: A) => A3\n    }\n  ): <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A3, never, R>\n  <A, E, R, A2, A3>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly onFailure: (error: E) => A2\n      readonly onSuccess: (value: A) => A3\n    }\n  ): Effect.Effect<A2 | A3, never, R>\n} = dual(2, <A, E, R, A2, A3>(\n  self: Effect.Effect<A, E, R>,\n  options: {\n    readonly onFailure: (error: E) => A2\n    readonly onSuccess: (value: A) => A3\n  }\n): Effect.Effect<A2 | A3, never, R> =>\n  core.matchEffect(self, {\n    onFailure: (e) => core.succeed(options.onFailure(e)),\n    onSuccess: (a) => core.succeed(options.onSuccess(a))\n  }))\n\n/* @internal */\nexport const every: {\n  <A, E, R>(\n    predicate: (a: A, i: number) => Effect.Effect<boolean, E, R>\n  ): (elements: Iterable<A>) => Effect.Effect<boolean, E, R>\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: A, i: number) => Effect.Effect<boolean, E, R>\n  ): Effect.Effect<boolean, E, R>\n} = dual(\n  2,\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: A, i: number) => Effect.Effect<boolean, E, R>\n  ): Effect.Effect<boolean, E, R> => core.suspend(() => forAllLoop(elements[Symbol.iterator](), 0, predicate))\n)\n\nconst forAllLoop = <A, E, R>(\n  iterator: Iterator<A>,\n  index: number,\n  f: (a: A, i: number) => Effect.Effect<boolean, E, R>\n): Effect.Effect<boolean, E, R> => {\n  const next = iterator.next()\n  return next.done\n    ? core.succeed(true)\n    : core.flatMap(\n      f(next.value, index),\n      (b) => b ? forAllLoop(iterator, index + 1, f) : core.succeed(b)\n    )\n}\n\n/* @internal */\nexport const forever = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<never, E, R> => {\n  const loop: Effect.Effect<never, E, R> = core.flatMap(core.flatMap(self, () => core.yieldNow()), () => loop)\n  return loop\n}\n\n/* @internal */\nexport const fiberRefs: Effect.Effect<FiberRefs.FiberRefs> = core.withFiberRuntime((state) =>\n  core.succeed(state.getFiberRefs())\n)\n\n/* @internal */\nexport const head = <A, E, R>(\n  self: Effect.Effect<Iterable<A>, E, R>\n): Effect.Effect<A, E | Cause.NoSuchElementException, R> =>\n  core.flatMap(self, (as) => {\n    const iterator = as[Symbol.iterator]()\n    const next = iterator.next()\n    if (next.done) {\n      return core.fail(new core.NoSuchElementException())\n    }\n    return core.succeed(next.value)\n  })\n\n/* @internal */\nexport const ignore = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<void, never, R> =>\n  match(self, { onFailure: constVoid, onSuccess: constVoid })\n\n/* @internal */\nexport const ignoreLogged = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<void, never, R> =>\n  core.matchCauseEffect(self, {\n    onFailure: (cause) => logDebug(cause, \"An error was silently ignored because it is not anticipated to be useful\"),\n    onSuccess: () => core.void\n  })\n\n/* @internal */\nexport const inheritFiberRefs = (childFiberRefs: FiberRefs.FiberRefs) =>\n  updateFiberRefs((parentFiberId, parentFiberRefs) => FiberRefs.joinAs(parentFiberRefs, parentFiberId, childFiberRefs))\n\n/* @internal */\nexport const isFailure = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<boolean, never, R> =>\n  match(self, { onFailure: constTrue, onSuccess: constFalse })\n\n/* @internal */\nexport const isSuccess = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<boolean, never, R> =>\n  match(self, { onFailure: constFalse, onSuccess: constTrue })\n\n/* @internal */\nexport const iterate: {\n  <A, B extends A, R, E>(\n    initial: A,\n    options: {\n      readonly while: Predicate.Refinement<A, B>\n      readonly body: (b: B) => Effect.Effect<A, E, R>\n    }\n  ): Effect.Effect<A, E, R>\n  <A, R, E>(\n    initial: A,\n    options: {\n      readonly while: Predicate.Predicate<A>\n      readonly body: (a: A) => Effect.Effect<A, E, R>\n    }\n  ): Effect.Effect<A, E, R>\n} = <A, E, R>(\n  initial: A,\n  options: {\n    readonly while: Predicate.Predicate<A>\n    readonly body: (z: A) => Effect.Effect<A, E, R>\n  }\n): Effect.Effect<A, E, R> =>\n  core.suspend<A, E, R>(() => {\n    if (options.while(initial)) {\n      return core.flatMap(options.body(initial), (z2) => iterate(z2, options))\n    }\n    return core.succeed(initial)\n  })\n\n/** @internal */\nexport const logWithLevel = (level?: LogLevel.LogLevel) =>\n(\n  ...message: ReadonlyArray<any>\n): Effect.Effect<void> => {\n  const levelOption = Option.fromNullable(level)\n  let cause: Cause.Cause<unknown> | undefined = undefined\n  for (let i = 0, len = message.length; i < len; i++) {\n    const msg = message[i]\n    if (internalCause.isCause(msg)) {\n      if (cause !== undefined) {\n        cause = internalCause.sequential(cause, msg)\n      } else {\n        cause = msg\n      }\n      message = [...message.slice(0, i), ...message.slice(i + 1)]\n      i--\n    }\n  }\n  if (cause === undefined) {\n    cause = internalCause.empty\n  }\n  return core.withFiberRuntime((fiberState) => {\n    fiberState.log(message, cause, levelOption)\n    return core.void\n  })\n}\n\n/** @internal */\nexport const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never> = logWithLevel()\n\n/** @internal */\nexport const logTrace: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never> = logWithLevel(\n  LogLevel.Trace\n)\n\n/** @internal */\nexport const logDebug: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never> = logWithLevel(\n  LogLevel.Debug\n)\n\n/** @internal */\nexport const logInfo: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never> = logWithLevel(\n  LogLevel.Info\n)\n\n/** @internal */\nexport const logWarning: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never> = logWithLevel(\n  LogLevel.Warning\n)\n\n/** @internal */\nexport const logError: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never> = logWithLevel(\n  LogLevel.Error\n)\n\n/** @internal */\nexport const logFatal: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never> = logWithLevel(\n  LogLevel.Fatal\n)\n\n/* @internal */\nexport const withLogSpan = dual<\n  (label: string) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, label: string) => Effect.Effect<A, E, R>\n>(2, (effect, label) =>\n  core.flatMap(Clock.currentTimeMillis, (now) =>\n    core.fiberRefLocallyWith(\n      effect,\n      core.currentLogSpan,\n      List.prepend(LogSpan.make(label, now))\n    )))\n\n/* @internal */\nexport const logAnnotations: Effect.Effect<HashMap.HashMap<string, unknown>> = core\n  .fiberRefGet(\n    core.currentLogAnnotations\n  )\n\n/* @internal */\nexport const loop: {\n  <A, B extends A, C, E, R>(\n    initial: A,\n    options: {\n      readonly while: Predicate.Refinement<A, B>\n      readonly step: (b: B) => A\n      readonly body: (b: B) => Effect.Effect<C, E, R>\n      readonly discard?: false | undefined\n    }\n  ): Effect.Effect<Array<C>, E, R>\n  <A, C, E, R>(\n    initial: A,\n    options: {\n      readonly while: (a: A) => boolean\n      readonly step: (a: A) => A\n      readonly body: (a: A) => Effect.Effect<C, E, R>\n      readonly discard?: false | undefined\n    }\n  ): Effect.Effect<Array<C>, E, R>\n  <A, B extends A, C, E, R>(\n    initial: A,\n    options: {\n      readonly while: Predicate.Refinement<A, B>\n      readonly step: (b: B) => A\n      readonly body: (b: B) => Effect.Effect<R, E, C>\n      readonly discard: true\n    }\n  ): Effect.Effect<void, E, R>\n  <A, C, E, R>(\n    initial: A,\n    options: {\n      readonly while: (a: A) => boolean\n      readonly step: (a: A) => A\n      readonly body: (a: A) => Effect.Effect<C, E, R>\n      readonly discard: true\n    }\n  ): Effect.Effect<void, E, R>\n} = <A, C, E, R>(\n  initial: A,\n  options: {\n    readonly while: Predicate.Predicate<A>\n    readonly step: (a: A) => A\n    readonly body: (a: A) => Effect.Effect<C, E, R>\n    readonly discard?: boolean | undefined\n  }\n): any =>\n  options.discard\n    ? loopDiscard(initial, options.while, options.step, options.body)\n    : core.map(loopInternal(initial, options.while, options.step, options.body), Arr.fromIterable)\n\nconst loopInternal = <Z, A, E, R>(\n  initial: Z,\n  cont: Predicate.Predicate<Z>,\n  inc: (z: Z) => Z,\n  body: (z: Z) => Effect.Effect<A, E, R>\n): Effect.Effect<List.List<A>, E, R> =>\n  core.suspend(() =>\n    cont(initial)\n      ? core.flatMap(body(initial), (a) =>\n        core.map(\n          loopInternal(inc(initial), cont, inc, body),\n          List.prepend(a)\n        ))\n      : core.sync(() => List.empty())\n  )\n\nconst loopDiscard = <S, X, E, R>(\n  initial: S,\n  cont: Predicate.Predicate<S>,\n  inc: (s: S) => S,\n  body: (s: S) => Effect.Effect<X, E, R>\n): Effect.Effect<void, E, R> =>\n  core.suspend(() =>\n    cont(initial)\n      ? core.flatMap(\n        body(initial),\n        () => loopDiscard(inc(initial), cont, inc, body)\n      )\n      : core.void\n  )\n\n/* @internal */\nexport const mapAccum: {\n  <S, A, B, E, R, I extends Iterable<A> = Iterable<A>>(\n    initial: S,\n    f: (state: S, a: A, i: number) => Effect.Effect<readonly [S, B], E, R>\n  ): (elements: I) => Effect.Effect<[S, Arr.ReadonlyArray.With<I, B>], E, R>\n  <A, S, B, E, R, I extends Iterable<A> = Iterable<A>>(\n    elements: I,\n    initial: S,\n    f: (state: S, a: A, i: number) => Effect.Effect<readonly [S, B], E, R>\n  ): Effect.Effect<[S, Arr.ReadonlyArray.With<I, B>], E, R>\n} = dual(3, <A, S, B, E, R, I extends Iterable<A> = Iterable<A>>(\n  elements: I,\n  initial: S,\n  f: (state: S, a: A, i: number) => Effect.Effect<readonly [S, B], E, R>\n): Effect.Effect<[S, Array<B>], E, R> =>\n  core.suspend(() => {\n    const iterator = elements[Symbol.iterator]()\n    const builder: Array<B> = []\n    let result: Effect.Effect<S, E, R> = core.succeed(initial)\n    let next: IteratorResult<A, any>\n    let i = 0\n    while (!(next = iterator.next()).done) {\n      const index = i++\n      const value = next.value\n      result = core.flatMap(result, (state) =>\n        core.map(f(state, value, index), ([z, b]) => {\n          builder.push(b)\n          return z\n        }))\n    }\n    return core.map(result, (z) => [z, builder])\n  }))\n\n/* @internal */\nexport const mapErrorCause: {\n  <E, E2>(\n    f: (cause: Cause.Cause<E>) => Cause.Cause<E2>\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E2, R>\n  <A, E, R, E2>(self: Effect.Effect<A, E, R>, f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): Effect.Effect<A, E2, R>\n} = dual(\n  2,\n  <A, E, R, E2>(self: Effect.Effect<A, E, R>, f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): Effect.Effect<A, E2, R> =>\n    core.matchCauseEffect(self, {\n      onFailure: (c) => core.failCauseSync(() => f(c)),\n      onSuccess: core.succeed\n    })\n)\n\n/* @internal */\nexport const memoize = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Effect.Effect<Effect.Effect<A, E, R>> =>\n  pipe(\n    core.deferredMake<[[FiberRefsPatch.FiberRefsPatch, runtimeFlagsPatch.RuntimeFlagsPatch], A], E>(),\n    core.flatMap((deferred) =>\n      pipe(\n        diffFiberRefsAndRuntimeFlags(self),\n        core.intoDeferred(deferred),\n        once,\n        core.map((complete) =>\n          core.zipRight(\n            complete,\n            pipe(\n              core.deferredAwait(deferred),\n              core.flatMap(([patch, a]) =>\n                core.as(core.zip(patchFiberRefs(patch[0]), core.updateRuntimeFlags(patch[1])), a)\n              )\n            )\n          )\n        )\n      )\n    )\n  )\n\n/* @internal */\nexport const merge = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<E | A, never, R> =>\n  core.matchEffect(self, {\n    onFailure: (e) => core.succeed(e),\n    onSuccess: core.succeed\n  })\n\n/* @internal */\nexport const negate = <E, R>(self: Effect.Effect<boolean, E, R>): Effect.Effect<boolean, E, R> =>\n  core.map(self, (b) => !b)\n\n/* @internal */\nexport const none = <A, E, R>(\n  self: Effect.Effect<Option.Option<A>, E, R>\n): Effect.Effect<void, E | Cause.NoSuchElementException, R> =>\n  core.flatMap(self, (option) => {\n    switch (option._tag) {\n      case \"None\":\n        return core.void\n      case \"Some\":\n        return core.fail(new core.NoSuchElementException())\n    }\n  })\n\n/* @internal */\nexport const once = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Effect.Effect<Effect.Effect<void, E, R>> =>\n  core.map(\n    Ref.make(true),\n    (ref) => core.asVoid(core.whenEffect(self, Ref.getAndSet(ref, false)))\n  )\n\n/* @internal */\nexport const option = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<Option.Option<A>, never, R> =>\n  core.matchEffect(self, {\n    onFailure: () => core.succeed(Option.none()),\n    onSuccess: (a) => core.succeed(Option.some(a))\n  })\n\n/* @internal */\nexport const orElseFail = dual<\n  <E2>(evaluate: LazyArg<E2>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E2, R>,\n  <A, E, R, E2>(self: Effect.Effect<A, E, R>, evaluate: LazyArg<E2>) => Effect.Effect<A, E2, R>\n>(2, (self, evaluate) => core.orElse(self, () => core.failSync(evaluate)))\n\n/* @internal */\nexport const orElseSucceed = dual<\n  <A2>(evaluate: LazyArg<A2>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A | A2, never, R>,\n  <A, E, R, A2>(self: Effect.Effect<A, E, R>, evaluate: LazyArg<A2>) => Effect.Effect<A | A2, never, R>\n>(2, (self, evaluate) => core.orElse(self, () => core.sync(evaluate)))\n\n/* @internal */\nexport const parallelErrors = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, Array<E>, R> =>\n  core.matchCauseEffect(self, {\n    onFailure: (cause) => {\n      const errors = Arr.fromIterable(internalCause.failures(cause))\n      return errors.length === 0\n        ? core.failCause(cause as Cause.Cause<never>)\n        : core.fail(errors)\n    },\n    onSuccess: core.succeed\n  })\n\n/* @internal */\nexport const patchFiberRefs = (patch: FiberRefsPatch.FiberRefsPatch): Effect.Effect<void> =>\n  updateFiberRefs((fiberId, fiberRefs) => pipe(patch, fiberRefsPatch.patch(fiberId, fiberRefs)))\n\n/* @internal */\nexport const promise = <A>(evaluate: (signal: AbortSignal) => PromiseLike<A>): Effect.Effect<A> =>\n  evaluate.length >= 1\n    ? core.async((resolve, signal) => {\n      try {\n        evaluate(signal)\n          .then((a) => resolve(core.succeed(a)), (e) => resolve(core.die(e)))\n      } catch (e) {\n        resolve(core.die(e))\n      }\n    })\n    : core.async((resolve) => {\n      try {\n        ;(evaluate as LazyArg<PromiseLike<A>>)()\n          .then((a) => resolve(core.succeed(a)), (e) => resolve(core.die(e)))\n      } catch (e) {\n        resolve(core.die(e))\n      }\n    })\n\n/* @internal */\nexport const provideService = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, I>>,\n  <A, E, R, I, S>(\n    self: Effect.Effect<A, E, R>,\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ) => Effect.Effect<A, E, Exclude<R, I>>\n>(\n  3,\n  <A, E, R, I, S>(\n    self: Effect.Effect<A, E, R>,\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ): Effect.Effect<A, E, Exclude<R, I>> =>\n    core.contextWithEffect((env) =>\n      core.provideContext(\n        self as Effect.Effect<A, E, I | Exclude<R, I>>,\n        Context.add(env, tag, service)\n      )\n    )\n)\n\n/* @internal */\nexport const provideServiceEffect = dual<\n  <I, S, E1, R1>(\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<Types.NoInfer<S>, E1, R1>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E1, R1 | Exclude<R, I>>,\n  <A, E, R, I, S, E1, R1>(\n    self: Effect.Effect<A, E, R>,\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<Types.NoInfer<S>, E1, R1>\n  ) => Effect.Effect<A, E | E1, R1 | Exclude<R, I>>\n>(3, <A, E, R, I, S, E1, R1>(\n  self: Effect.Effect<A, E, R>,\n  tag: Context.Tag<I, S>,\n  effect: Effect.Effect<Types.NoInfer<S>, E1, R1>\n) =>\n  core.contextWithEffect((env: Context.Context<R1 | Exclude<R, I>>) =>\n    core.flatMap(\n      effect,\n      (service) => core.provideContext(self, pipe(env, Context.add(tag, service)) as Context.Context<R | R1>)\n    )\n  ))\n\n/* @internal */\nexport const random: Effect.Effect<Random.Random> = defaultServices.randomWith(core.succeed)\n\n/* @internal */\nexport const reduce = dual<\n  <Z, A, E, R>(\n    zero: Z,\n    f: (z: Z, a: A, i: number) => Effect.Effect<Z, E, R>\n  ) => (elements: Iterable<A>) => Effect.Effect<Z, E, R>,\n  <A, Z, E, R>(\n    elements: Iterable<A>,\n    zero: Z,\n    f: (z: Z, a: A, i: number) => Effect.Effect<Z, E, R>\n  ) => Effect.Effect<Z, E, R>\n>(\n  3,\n  <A, Z, E, R>(\n    elements: Iterable<A>,\n    zero: Z,\n    f: (z: Z, a: A, i: number) => Effect.Effect<Z, E, R>\n  ) =>\n    Arr.fromIterable(elements).reduce(\n      (acc, el, i) => core.flatMap(acc, (a) => f(a, el, i)),\n      core.succeed(zero) as Effect.Effect<Z, E, R>\n    )\n)\n\n/* @internal */\nexport const reduceRight = dual<\n  <A, Z, R, E>(\n    zero: Z,\n    f: (a: A, z: Z, i: number) => Effect.Effect<Z, E, R>\n  ) => (elements: Iterable<A>) => Effect.Effect<Z, E, R>,\n  <A, Z, R, E>(\n    elements: Iterable<A>,\n    zero: Z,\n    f: (a: A, z: Z, i: number) => Effect.Effect<Z, E, R>\n  ) => Effect.Effect<Z, E, R>\n>(\n  3,\n  <A, Z, R, E>(elements: Iterable<A>, zero: Z, f: (a: A, z: Z, i: number) => Effect.Effect<Z, E, R>) =>\n    Arr.fromIterable(elements).reduceRight(\n      (acc, el, i) => core.flatMap(acc, (a) => f(el, a, i)),\n      core.succeed(zero) as Effect.Effect<Z, E, R>\n    )\n)\n\n/* @internal */\nexport const reduceWhile = dual<\n  <Z, A, E, R>(\n    zero: Z,\n    options: {\n      readonly while: Predicate.Predicate<Z>\n      readonly body: (s: Z, a: A, i: number) => Effect.Effect<Z, E, R>\n    }\n  ) => (elements: Iterable<A>) => Effect.Effect<Z, E, R>,\n  <A, Z, E, R>(\n    elements: Iterable<A>,\n    zero: Z,\n    options: {\n      readonly while: Predicate.Predicate<Z>\n      readonly body: (s: Z, a: A, i: number) => Effect.Effect<Z, E, R>\n    }\n  ) => Effect.Effect<Z, E, R>\n>(3, <A, Z, E, R>(\n  elements: Iterable<A>,\n  zero: Z,\n  options: {\n    readonly while: Predicate.Predicate<Z>\n    readonly body: (s: Z, a: A, i: number) => Effect.Effect<Z, E, R>\n  }\n) =>\n  core.flatMap(\n    core.sync(() => elements[Symbol.iterator]()),\n    (iterator) => reduceWhileLoop(iterator, 0, zero, options.while, options.body)\n  ))\n\nconst reduceWhileLoop = <A, R, E, Z>(\n  iterator: Iterator<A>,\n  index: number,\n  state: Z,\n  predicate: Predicate.Predicate<Z>,\n  f: (s: Z, a: A, i: number) => Effect.Effect<Z, E, R>\n): Effect.Effect<Z, E, R> => {\n  const next = iterator.next()\n  if (!next.done && predicate(state)) {\n    return core.flatMap(\n      f(state, next.value, index),\n      (nextState) => reduceWhileLoop(iterator, index + 1, nextState, predicate, f)\n    )\n  }\n  return core.succeed(state)\n}\n\n/* @internal */\nexport const repeatN = dual<\n  (n: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, n: number) => Effect.Effect<A, E, R>\n>(2, (self, n) => core.suspend(() => repeatNLoop(self, n)))\n\n/* @internal */\nconst repeatNLoop = <A, E, R>(self: Effect.Effect<A, E, R>, n: number): Effect.Effect<A, E, R> =>\n  core.flatMap(self, (a) =>\n    n <= 0\n      ? core.succeed(a)\n      : core.zipRight(core.yieldNow(), repeatNLoop(self, n - 1)))\n\n/* @internal */\nexport const sandbox = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, Cause.Cause<E>, R> =>\n  core.matchCauseEffect(self, {\n    onFailure: core.fail,\n    onSuccess: core.succeed\n  })\n\n/* @internal */\nexport const setFiberRefs = (fiberRefs: FiberRefs.FiberRefs): Effect.Effect<void> =>\n  core.suspend(() => FiberRefs.setAll(fiberRefs))\n\n/* @internal */\nexport const sleep: (duration: Duration.DurationInput) => Effect.Effect<void> = Clock.sleep\n\n/* @internal */\nexport const succeedNone: Effect.Effect<Option.Option<never>> = core.succeed(Option.none())\n\n/* @internal */\nexport const succeedSome = <A>(value: A): Effect.Effect<Option.Option<A>> => core.succeed(Option.some(value))\n\n/* @internal */\nexport const summarized: {\n  <B, E2, R2, C>(\n    summary: Effect.Effect<B, E2, R2>,\n    f: (start: B, end: B) => C\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<[C, A], E2 | E, R2 | R>\n  <A, E, R, B, E2, R2, C>(\n    self: Effect.Effect<A, E, R>,\n    summary: Effect.Effect<B, E2, R2>,\n    f: (start: B, end: B) => C\n  ): Effect.Effect<[C, A], E2 | E, R2 | R>\n} = dual(\n  3,\n  <A, E, R, B, E2, R2, C>(\n    self: Effect.Effect<A, E, R>,\n    summary: Effect.Effect<B, E2, R2>,\n    f: (start: B, end: B) => C\n  ): Effect.Effect<[C, A], E2 | E, R2 | R> =>\n    core.flatMap(\n      summary,\n      (start) => core.flatMap(self, (value) => core.map(summary, (end) => [f(start, end), value]))\n    )\n)\n\n/* @internal */\nexport const tagMetrics = dual<\n  {\n    (key: string, value: string): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n    (\n      values: Record<string, string>\n    ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  },\n  {\n    <A, E, R>(effect: Effect.Effect<A, E, R>, key: string, value: string): Effect.Effect<A, E, R>\n    <A, E, R>(effect: Effect.Effect<A, E, R>, values: Record<string, string>): Effect.Effect<A, E, R>\n  }\n>((args) => core.isEffect(args[0]), function() {\n  return labelMetrics(\n    arguments[0],\n    typeof arguments[1] === \"string\"\n      ? [metricLabel.make(arguments[1], arguments[2])]\n      : Object.entries<string>(arguments[1]).map(([k, v]) => metricLabel.make(k, v))\n  )\n})\n\n/* @internal */\nexport const labelMetrics = dual<\n  (labels: Iterable<MetricLabel.MetricLabel>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, labels: Iterable<MetricLabel.MetricLabel>) => Effect.Effect<A, E, R>\n>(\n  2,\n  (self, labels) => core.fiberRefLocallyWith(self, core.currentMetricLabels, (old) => Arr.union(old, labels))\n)\n\n/* @internal */\nexport const takeUntil: {\n  <A, R, E>(\n    predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>\n  ): (elements: Iterable<A>) => Effect.Effect<Array<A>, E, R>\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>\n  ): Effect.Effect<Array<A>, E, R>\n} = dual(\n  2,\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>\n  ): Effect.Effect<Array<A>, E, R> =>\n    core.suspend(() => {\n      const iterator = elements[Symbol.iterator]()\n      const builder: Array<A> = []\n      let next: IteratorResult<A, any>\n      let effect: Effect.Effect<boolean, E, R> = core.succeed(false)\n      let i = 0\n      while ((next = iterator.next()) && !next.done) {\n        const a = next.value\n        const index = i++\n        effect = core.flatMap(effect, (bool) => {\n          if (bool) {\n            return core.succeed(true)\n          }\n          builder.push(a)\n          return predicate(a, index)\n        })\n      }\n      return core.map(effect, () => builder)\n    })\n)\n\n/* @internal */\nexport const takeWhile = dual<\n  <A, E, R>(\n    predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>\n  ) => (elements: Iterable<A>) => Effect.Effect<Array<A>, E, R>,\n  <A, E, R>(\n    elements: Iterable<A>,\n    predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>\n  ) => Effect.Effect<Array<A>, E, R>\n>(\n  2,\n  <A, E, R>(elements: Iterable<A>, predicate: (a: Types.NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>) =>\n    core.suspend(() => {\n      const iterator = elements[Symbol.iterator]()\n      const builder: Array<A> = []\n      let next: IteratorResult<A, any>\n      let taking: Effect.Effect<boolean, E, R> = core.succeed(true)\n      let i = 0\n      while ((next = iterator.next()) && !next.done) {\n        const a = next.value\n        const index = i++\n        taking = core.flatMap(taking, (taking) =>\n          pipe(\n            taking ? predicate(a, index) : core.succeed(false),\n            core.map((bool) => {\n              if (bool) {\n                builder.push(a)\n              }\n              return bool\n            })\n          ))\n      }\n      return core.map(taking, () => builder)\n    })\n)\n\n/* @internal */\nexport const tapBoth = dual<\n  <E, X, E2, R2, A, X1, E3, R3>(\n    options: {\n      readonly onFailure: (e: Types.NoInfer<E>) => Effect.Effect<X, E2, R2>\n      readonly onSuccess: (a: Types.NoInfer<A>) => Effect.Effect<X1, E3, R3>\n    }\n  ) => <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E2 | E3, R | R2 | R3>,\n  <A, E, R, X, E2, R2, X1, E3, R3>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly onFailure: (e: E) => Effect.Effect<X, E2, R2>\n      readonly onSuccess: (a: A) => Effect.Effect<X1, E3, R3>\n    }\n  ) => Effect.Effect<A, E | E2 | E3, R | R2 | R3>\n>(2, (self, { onFailure, onSuccess }) =>\n  core.matchCauseEffect(self, {\n    onFailure: (cause) => {\n      const either = internalCause.failureOrCause(cause)\n      switch (either._tag) {\n        case \"Left\": {\n          return core.zipRight(onFailure(either.left as any), core.failCause(cause))\n        }\n        case \"Right\": {\n          return core.failCause(cause)\n        }\n      }\n    },\n    onSuccess: (a) => core.as(onSuccess(a as any), a)\n  }))\n\n/* @internal */\nexport const tapDefect = dual<\n  <X, E2, R2>(\n    f: (cause: Cause.Cause<never>) => Effect.Effect<X, E2, R2>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E2, R | R2>,\n  <A, E, R, X, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (cause: Cause.Cause<never>) => Effect.Effect<X, E2, R2>\n  ) => Effect.Effect<A, E | E2, R | R2>\n>(2, (self, f) =>\n  core.catchAllCause(self, (cause) =>\n    Option.match(internalCause.keepDefects(cause), {\n      onNone: () => core.failCause(cause),\n      onSome: (a) => core.zipRight(f(a), core.failCause(cause))\n    })))\n\n/* @internal */\nexport const tapError = dual<\n  <E, X, E2, R2>(\n    f: (e: Types.NoInfer<E>) => Effect.Effect<X, E2, R2>\n  ) => <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E2, R | R2>,\n  <A, E, R, X, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (e: E) => Effect.Effect<X, E2, R2>\n  ) => Effect.Effect<A, E | E2, R | R2>\n>(2, (self, f) =>\n  core.matchCauseEffect(self, {\n    onFailure: (cause) => {\n      const either = internalCause.failureOrCause(cause)\n      switch (either._tag) {\n        case \"Left\":\n          return core.zipRight(f(either.left as any), core.failCause(cause))\n        case \"Right\":\n          return core.failCause(cause)\n      }\n    },\n    onSuccess: core.succeed\n  }))\n\n/* @internal */\nexport const tapErrorTag = dual<\n  <K extends (E extends { _tag: string } ? E[\"_tag\"] : never), E, A1, E1, R1>(\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Effect.Effect<A1, E1, R1>\n  ) => <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E1, R | R1>,\n  <A, E, R, K extends (E extends { _tag: string } ? E[\"_tag\"] : never), A1, E1, R1>(\n    self: Effect.Effect<A, E, R>,\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Effect.Effect<A1, E1, R1>\n  ) => Effect.Effect<A, E | E1, R | R1>\n>(3, (self, k, f) =>\n  tapError(self, (e) => {\n    if (Predicate.isTagged(e, k)) {\n      return f(e as any)\n    }\n    return core.void as any\n  }))\n\n/* @internal */\nexport const tapErrorCause = dual<\n  <E, X, E2, R2>(\n    f: (cause: Cause.Cause<Types.NoInfer<E>>) => Effect.Effect<X, E2, R2>\n  ) => <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E2, R | R2>,\n  <A, E, R, X, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (cause: Cause.Cause<E>) => Effect.Effect<X, E2, R2>\n  ) => Effect.Effect<A, E | E2, R | R2>\n>(2, (self, f) =>\n  core.matchCauseEffect(self, {\n    onFailure: (cause) => core.zipRight(f(cause), core.failCause(cause)),\n    onSuccess: core.succeed\n  }))\n\n/* @internal */\nexport const timed = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Effect.Effect<[duration: Duration.Duration, result: A], E, R> => timedWith(self, Clock.currentTimeNanos)\n\n/* @internal */\nexport const timedWith = dual<\n  <E1, R1>(\n    nanoseconds: Effect.Effect<bigint, E1, R1>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<[Duration.Duration, A], E | E1, R | R1>,\n  <A, E, R, E1, R1>(\n    self: Effect.Effect<A, E, R>,\n    nanoseconds: Effect.Effect<bigint, E1, R1>\n  ) => Effect.Effect<[Duration.Duration, A], E | E1, R | R1>\n>(\n  2,\n  (self, nanos) => summarized(self, nanos, (start, end) => Duration.nanos(end - start))\n)\n\n/* @internal */\nexport const tracerWith: <A, E, R>(f: (tracer: Tracer.Tracer) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> =\n  Tracer.tracerWith\n\n/** @internal */\nexport const tracer: Effect.Effect<Tracer.Tracer> = tracerWith(core.succeed)\n\n/* @internal */\nexport const tryPromise: {\n  <A, E>(\n    options: {\n      readonly try: (signal: AbortSignal) => PromiseLike<A>\n      readonly catch: (error: unknown) => E\n    }\n  ): Effect.Effect<A, E>\n  <A>(evaluate: (signal: AbortSignal) => PromiseLike<A>): Effect.Effect<A, Cause.UnknownException>\n} = <A, E>(\n  arg: ((signal: AbortSignal) => PromiseLike<A>) | {\n    readonly try: (signal: AbortSignal) => PromiseLike<A>\n    readonly catch: (error: unknown) => E\n  }\n): Effect.Effect<A, E | Cause.UnknownException> => {\n  let evaluate: (signal?: AbortSignal) => PromiseLike<A>\n  let catcher: ((error: unknown) => E) | undefined = undefined\n  if (typeof arg === \"function\") {\n    evaluate = arg as (signal?: AbortSignal) => PromiseLike<A>\n  } else {\n    evaluate = arg.try as (signal?: AbortSignal) => PromiseLike<A>\n    catcher = arg.catch\n  }\n  const fail = (e: unknown) =>\n    catcher\n      ? core.failSync(() => catcher(e))\n      : core.fail(new core.UnknownException(e, \"An unknown error occurred in Effect.tryPromise\"))\n\n  if (evaluate.length >= 1) {\n    return core.async((resolve, signal) => {\n      try {\n        evaluate(signal).then(\n          (a) => resolve(core.succeed(a)),\n          (e) => resolve(fail(e))\n        )\n      } catch (e) {\n        resolve(fail(e))\n      }\n    })\n  }\n\n  return core.async((resolve) => {\n    try {\n      evaluate()\n        .then(\n          (a) => resolve(core.succeed(a)),\n          (e) => resolve(fail(e))\n        )\n    } catch (e) {\n      resolve(fail(e))\n    }\n  })\n}\n\n/* @internal */\nexport const tryMap = dual<\n  <A, B, E1>(\n    options: {\n      readonly try: (a: A) => B\n      readonly catch: (error: unknown) => E1\n    }\n  ) => <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E | E1, R>,\n  <A, E, R, B, E1>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly try: (a: A) => B\n      readonly catch: (error: unknown) => E1\n    }\n  ) => Effect.Effect<B, E | E1, R>\n>(2, (self, options) =>\n  core.flatMap(self, (a) =>\n    try_({\n      try: () => options.try(a),\n      catch: options.catch\n    })))\n\n/* @internal */\nexport const tryMapPromise = dual<\n  <A, B, E1>(\n    options: {\n      readonly try: (a: A, signal: AbortSignal) => PromiseLike<B>\n      readonly catch: (error: unknown) => E1\n    }\n  ) => <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E | E1, R>,\n  <A, E, R, B, E1>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly try: (a: A, signal: AbortSignal) => PromiseLike<B>\n      readonly catch: (error: unknown) => E1\n    }\n  ) => Effect.Effect<B, E | E1, R>\n>(2, <A, E, R, B, E1>(\n  self: Effect.Effect<A, E, R>,\n  options: {\n    readonly try: (a: A, signal: AbortSignal) => PromiseLike<B>\n    readonly catch: (error: unknown) => E1\n  }\n) =>\n  core.flatMap(self, (a) =>\n    tryPromise({\n      try: options.try.length >= 1\n        ? (signal) => options.try(a, signal)\n        : () => (options.try as (a: A) => PromiseLike<B>)(a),\n      catch: options.catch\n    })))\n\n/* @internal */\nexport const unless = dual<\n  (condition: LazyArg<boolean>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Option.Option<A>, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, condition: LazyArg<boolean>) => Effect.Effect<Option.Option<A>, E, R>\n>(2, (self, condition) =>\n  core.suspend(() =>\n    condition()\n      ? succeedNone\n      : asSome(self)\n  ))\n\n/* @internal */\nexport const unlessEffect = dual<\n  <E2, R2>(\n    condition: Effect.Effect<boolean, E2, R2>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Option.Option<A>, E | E2, R | R2>,\n  <A, E, R, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    condition: Effect.Effect<boolean, E2, R2>\n  ) => Effect.Effect<Option.Option<A>, E | E2, R | R2>\n>(2, (self, condition) => core.flatMap(condition, (b) => (b ? succeedNone : asSome(self))))\n\n/* @internal */\nexport const unsandbox = <A, E, R>(self: Effect.Effect<A, Cause.Cause<E>, R>) =>\n  mapErrorCause(self, internalCause.flatten)\n\n/* @internal */\nexport const updateFiberRefs = (\n  f: (fiberId: FiberId.Runtime, fiberRefs: FiberRefs.FiberRefs) => FiberRefs.FiberRefs\n): Effect.Effect<void> =>\n  core.withFiberRuntime((state) => {\n    state.setFiberRefs(f(state.id(), state.getFiberRefs()))\n    return core.void\n  })\n\n/* @internal */\nexport const updateService = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    f: (service: Types.NoInfer<S>) => Types.NoInfer<S>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R | I>,\n  <A, E, R, I, S>(\n    self: Effect.Effect<A, E, R>,\n    tag: Context.Tag<I, S>,\n    f: (service: Types.NoInfer<S>) => Types.NoInfer<S>\n  ) => Effect.Effect<A, E, R | I>\n>(3, <A, E, R, I, S>(\n  self: Effect.Effect<A, E, R>,\n  tag: Context.Tag<I, S>,\n  f: (service: Types.NoInfer<S>) => Types.NoInfer<S>\n) =>\n  core.mapInputContext(self, (context) =>\n    Context.add(\n      context,\n      tag,\n      f(Context.unsafeGet(context, tag))\n    )) as Effect.Effect<A, E, R | I>)\n\n/* @internal */\nexport const when = dual<\n  (condition: LazyArg<boolean>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Option.Option<A>, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, condition: LazyArg<boolean>) => Effect.Effect<Option.Option<A>, E, R>\n>(2, (self, condition) =>\n  core.suspend(() =>\n    condition()\n      ? core.map(self, Option.some)\n      : core.succeed(Option.none())\n  ))\n\n/* @internal */\nexport const whenFiberRef = dual<\n  <S>(\n    fiberRef: FiberRef.FiberRef<S>,\n    predicate: Predicate.Predicate<S>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<[S, Option.Option<A>], E, R>,\n  <A, E, R, S>(\n    self: Effect.Effect<A, E, R>,\n    fiberRef: FiberRef.FiberRef<S>,\n    predicate: Predicate.Predicate<S>\n  ) => Effect.Effect<[S, Option.Option<A>], E, R>\n>(\n  3,\n  <A, E, R, S>(\n    self: Effect.Effect<A, E, R>,\n    fiberRef: FiberRef.FiberRef<S>,\n    predicate: Predicate.Predicate<S>\n  ) =>\n    core.flatMap(core.fiberRefGet(fiberRef), (s) =>\n      predicate(s)\n        ? core.map(self, (a) => [s, Option.some(a)])\n        : core.succeed<[S, Option.Option<A>]>([s, Option.none()]))\n)\n\n/* @internal */\nexport const whenRef = dual<\n  <S>(\n    ref: Ref.Ref<S>,\n    predicate: Predicate.Predicate<S>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<[S, Option.Option<A>], E, R>,\n  <A, E, R, S>(\n    self: Effect.Effect<A, E, R>,\n    ref: Ref.Ref<S>,\n    predicate: Predicate.Predicate<S>\n  ) => Effect.Effect<[S, Option.Option<A>], E, R>\n>(\n  3,\n  <A, E, R, S>(self: Effect.Effect<A, E, R>, ref: Ref.Ref<S>, predicate: Predicate.Predicate<S>) =>\n    core.flatMap(Ref.get(ref), (s) =>\n      predicate(s)\n        ? core.map(self, (a) => [s, Option.some(a)])\n        : core.succeed<[S, Option.Option<A>]>([s, Option.none()]))\n)\n\n/* @internal */\nexport const withMetric = dual<\n  <Type, In, Out>(\n    metric: Metric.Metric<Type, In, Out>\n  ) => <A extends In, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A extends In, E, R, Type, In, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric.Metric<Type, In, Out>\n  ) => Effect.Effect<A, E, R>\n>(2, (self, metric) => metric(self))\n\n/** @internal */\nexport const serviceFunctionEffect = <T extends Effect.Effect<any, any, any>, Args extends Array<any>, A, E, R>(\n  getService: T,\n  f: (_: Effect.Effect.Success<T>) => (...args: Args) => Effect.Effect<A, E, R>\n) =>\n(...args: Args): Effect.Effect<A, E | Effect.Effect.Error<T>, R | Effect.Effect.Context<T>> =>\n  core.flatMap(getService, (a) => f(a)(...args))\n\n/** @internal */\nexport const serviceFunction = <T extends Effect.Effect<any, any, any>, Args extends Array<any>, A>(\n  getService: T,\n  f: (_: Effect.Effect.Success<T>) => (...args: Args) => A\n) =>\n(...args: Args): Effect.Effect<A, Effect.Effect.Error<T>, Effect.Effect.Context<T>> =>\n  core.map(getService, (a) => f(a)(...args))\n\n/** @internal */\nexport const serviceFunctions = <S, SE, SR>(\n  getService: Effect.Effect<S, SE, SR>\n): {\n  [k in keyof S as S[k] extends (...args: Array<any>) => Effect.Effect<any, any, any> ? k : never]: S[k] extends\n    (...args: infer Args) => Effect.Effect<infer A, infer E, infer R>\n    ? (...args: Args) => Effect.Effect<A, E | SE, R | SR>\n    : never\n} =>\n  new Proxy({} as any, {\n    get(_target: any, prop: any, _receiver) {\n      return (...args: Array<any>) => core.flatMap(getService, (s: any) => s[prop](...args))\n    }\n  })\n\n/** @internal */\nexport const serviceConstants = <S, SE, SR>(\n  getService: Effect.Effect<S, SE, SR>\n): {\n  [k in { [k in keyof S]: k }[keyof S]]: S[k] extends Effect.Effect<infer A, infer E, infer R> ?\n    Effect.Effect<A, E | SE, R | SR> :\n    Effect.Effect<S[k], SE, SR>\n} =>\n  new Proxy({} as any, {\n    get(_target: any, prop: any, _receiver) {\n      return core.flatMap(getService, (s: any) => core.isEffect(s[prop]) ? s[prop] : core.succeed(s[prop]))\n    }\n  })\n\n/** @internal */\nexport const serviceMembers = <S, SE, SR>(getService: Effect.Effect<S, SE, SR>): {\n  functions: {\n    [k in keyof S as S[k] extends (...args: Array<any>) => Effect.Effect<any, any, any> ? k : never]: S[k] extends\n      (...args: infer Args) => Effect.Effect<infer A, infer E, infer R>\n      ? (...args: Args) => Effect.Effect<A, E | SE, R | SR>\n      : never\n  }\n  constants: {\n    [k in { [k in keyof S]: k }[keyof S]]: S[k] extends Effect.Effect<infer A, infer E, infer R> ?\n      Effect.Effect<A, E | SE, R | SR> :\n      Effect.Effect<S[k], SE, SR>\n  }\n} => ({\n  functions: serviceFunctions(getService) as any,\n  constants: serviceConstants(getService)\n})\n\n/** @internal */\nexport const serviceOption = <I, S>(tag: Context.Tag<I, S>) => core.map(core.context<never>(), Context.getOption(tag))\n\n/** @internal */\nexport const serviceOptional = <I, S>(tag: Context.Tag<I, S>) =>\n  core.flatMap(core.context<never>(), Context.getOption(tag))\n\n// -----------------------------------------------------------------------------\n// tracing\n// -----------------------------------------------------------------------------\n\n/* @internal */\nexport const annotateCurrentSpan: {\n  (key: string, value: unknown): Effect.Effect<void>\n  (values: Record<string, unknown>): Effect.Effect<void>\n} = function(): Effect.Effect<void> {\n  const args = arguments\n  return ignore(core.flatMap(\n    currentPropagatedSpan,\n    (span) =>\n      core.sync(() => {\n        if (typeof args[0] === \"string\") {\n          span.attribute(args[0], args[1])\n        } else {\n          for (const key in args[0]) {\n            span.attribute(key, args[0][key])\n          }\n        }\n      })\n  ))\n}\n\n/* @internal */\nexport const linkSpanCurrent: {\n  (span: Tracer.AnySpan, attributes?: Readonly<Record<string, unknown>> | undefined): Effect.Effect<void>\n  (links: ReadonlyArray<Tracer.SpanLink>): Effect.Effect<void>\n} = function(): Effect.Effect<void> {\n  const args = arguments\n  const links: ReadonlyArray<Tracer.SpanLink> = Array.isArray(args[0])\n    ? args[0]\n    : [{ _tag: \"SpanLink\", span: args[0], attributes: args[1] ?? {} }]\n  return ignore(core.flatMap(\n    currentSpan,\n    (span) => core.sync(() => span.addLinks(links))\n  ))\n}\n\n/* @internal */\nexport const annotateSpans = dual<\n  {\n    (key: string, value: unknown): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n    (\n      values: Record<string, unknown>\n    ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  },\n  {\n    <A, E, R>(effect: Effect.Effect<A, E, R>, key: string, value: unknown): Effect.Effect<A, E, R>\n    <A, E, R>(effect: Effect.Effect<A, E, R>, values: Record<string, unknown>): Effect.Effect<A, E, R>\n  }\n>(\n  (args) => core.isEffect(args[0]),\n  function<A, E, R>() {\n    const args = arguments\n    return core.fiberRefLocallyWith(\n      args[0] as Effect.Effect<A, E, R>,\n      core.currentTracerSpanAnnotations,\n      typeof args[1] === \"string\"\n        ? HashMap.set(args[1], args[2])\n        : (annotations) =>\n          Object.entries(args[1] as Record<string, unknown>).reduce(\n            (acc, [key, value]) => HashMap.set(acc, key, value),\n            annotations\n          )\n    )\n  }\n)\n\n/** @internal */\nexport const currentParentSpan: Effect.Effect<Tracer.AnySpan, Cause.NoSuchElementException> = serviceOptional(\n  internalTracer.spanTag\n)\n\n/** @internal */\nexport const currentSpan: Effect.Effect<Tracer.Span, Cause.NoSuchElementException> = core.flatMap(\n  core.context<never>(),\n  (context) => {\n    const span = context.unsafeMap.get(internalTracer.spanTag.key) as Tracer.AnySpan | undefined\n    return span !== undefined && span._tag === \"Span\"\n      ? core.succeed(span)\n      : core.fail(new core.NoSuchElementException())\n  }\n)\n\nexport const currentPropagatedSpan: Effect.Effect<Tracer.Span, Cause.NoSuchElementException> = core.flatMap(\n  core.context<never>(),\n  (context) => {\n    const span = filterDisablePropagation(Context.getOption(context, internalTracer.spanTag))\n    return span._tag === \"Some\" && span.value._tag === \"Span\"\n      ? core.succeed(span.value)\n      : core.fail(new core.NoSuchElementException())\n  }\n)\n\n/* @internal */\nexport const linkSpans = dual<\n  (\n    span: Tracer.AnySpan,\n    attributes?: Record<string, unknown>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    span: Tracer.AnySpan,\n    attributes?: Record<string, unknown>\n  ) => Effect.Effect<A, E, R>\n>(\n  (args) => core.isEffect(args[0]),\n  (self, span, attributes) =>\n    core.fiberRefLocallyWith(\n      self,\n      core.currentTracerSpanLinks,\n      Chunk.append(\n        {\n          _tag: \"SpanLink\",\n          span,\n          attributes: attributes ?? {}\n        } as const\n      )\n    )\n)\n\nconst bigint0 = BigInt(0)\n\nexport const filterDisablePropagation: (self: Option.Option<Tracer.AnySpan>) => Option.Option<Tracer.AnySpan> = Option\n  .flatMap(\n    (span) =>\n      Context.get(span.context, internalTracer.DisablePropagation)\n        ? span._tag === \"Span\" ? filterDisablePropagation(span.parent) : Option.none()\n        : Option.some(span)\n  )\n\n/** @internal */\nexport const unsafeMakeSpan = <XA, XE>(\n  fiber: FiberRuntime<XA, XE>,\n  name: string,\n  options: Tracer.SpanOptions\n) => {\n  const disablePropagation = !fiber.getFiberRef(core.currentTracerEnabled) ||\n    (options.context && Context.get(options.context, internalTracer.DisablePropagation))\n  const context = fiber.getFiberRef(core.currentContext)\n  const parent = options.parent\n    ? Option.some(options.parent)\n    : options.root\n    ? Option.none()\n    : filterDisablePropagation(Context.getOption(context, internalTracer.spanTag))\n\n  let span: Tracer.Span\n\n  if (disablePropagation) {\n    span = core.noopSpan({\n      name,\n      parent,\n      context: Context.add(options.context ?? Context.empty(), internalTracer.DisablePropagation, true)\n    })\n  } else {\n    const services = fiber.getFiberRef(defaultServices.currentServices)\n\n    const tracer = Context.get(services, internalTracer.tracerTag)\n    const clock = Context.get(services, Clock.Clock)\n    const timingEnabled = fiber.getFiberRef(core.currentTracerTimingEnabled)\n\n    const fiberRefs = fiber.getFiberRefs()\n    const annotationsFromEnv = FiberRefs.get(fiberRefs, core.currentTracerSpanAnnotations)\n    const linksFromEnv = FiberRefs.get(fiberRefs, core.currentTracerSpanLinks)\n\n    const links = linksFromEnv._tag === \"Some\" ?\n      options.links !== undefined ?\n        [\n          ...Chunk.toReadonlyArray(linksFromEnv.value),\n          ...(options.links ?? [])\n        ] :\n        Chunk.toReadonlyArray(linksFromEnv.value) :\n      options.links ?? Arr.empty()\n\n    span = tracer.span(\n      name,\n      parent,\n      options.context ?? Context.empty(),\n      links,\n      timingEnabled ? clock.unsafeCurrentTimeNanos() : bigint0,\n      options.kind ?? \"internal\",\n      options\n    )\n\n    if (annotationsFromEnv._tag === \"Some\") {\n      HashMap.forEach(annotationsFromEnv.value, (value, key) => span.attribute(key, value))\n    }\n    if (options.attributes !== undefined) {\n      Object.entries(options.attributes).forEach(([k, v]) => span.attribute(k, v))\n    }\n  }\n\n  if (typeof options.captureStackTrace === \"function\") {\n    internalCause.spanToTrace.set(span, options.captureStackTrace)\n  }\n\n  return span\n}\n\n/** @internal */\nexport const makeSpan = (\n  name: string,\n  options?: Tracer.SpanOptions\n): Effect.Effect<Tracer.Span> => {\n  options = internalTracer.addSpanStackTrace(options)\n  return core.withFiberRuntime((fiber) => core.succeed(unsafeMakeSpan(fiber, name, options)))\n}\n\n/* @internal */\nexport const spanAnnotations: Effect.Effect<HashMap.HashMap<string, unknown>> = core\n  .fiberRefGet(core.currentTracerSpanAnnotations)\n\n/* @internal */\nexport const spanLinks: Effect.Effect<Chunk.Chunk<Tracer.SpanLink>> = core\n  .fiberRefGet(core.currentTracerSpanLinks)\n\n/** @internal */\nexport const endSpan = <A, E>(span: Tracer.Span, exit: Exit<A, E>, clock: Clock.Clock, timingEnabled: boolean) =>\n  core.sync(() => {\n    if (span.status._tag === \"Ended\") {\n      return\n    }\n    if (core.exitIsFailure(exit) && internalCause.spanToTrace.has(span)) {\n      // https://opentelemetry.io/docs/specs/semconv/registry/attributes/code/#code-stacktrace\n      span.attribute(\"code.stacktrace\", internalCause.spanToTrace.get(span)!())\n    }\n    span.end(timingEnabled ? clock.unsafeCurrentTimeNanos() : bigint0, exit)\n  })\n\n/** @internal */\nexport const useSpan: {\n  <A, E, R>(name: string, evaluate: (span: Tracer.Span) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R>\n  <A, E, R>(\n    name: string,\n    options: Tracer.SpanOptions,\n    evaluate: (span: Tracer.Span) => Effect.Effect<A, E, R>\n  ): Effect.Effect<A, E, R>\n} = <A, E, R>(\n  name: string,\n  ...args: [evaluate: (span: Tracer.Span) => Effect.Effect<A, E, R>] | [\n    options: any,\n    evaluate: (span: Tracer.Span) => Effect.Effect<A, E, R>\n  ]\n) => {\n  const options = internalTracer.addSpanStackTrace(args.length === 1 ? undefined : args[0])\n  const evaluate: (span: Tracer.Span) => Effect.Effect<A, E, R> = args[args.length - 1]\n\n  return core.withFiberRuntime<A, E, R>((fiber) => {\n    const span = unsafeMakeSpan(fiber, name, options)\n    const timingEnabled = fiber.getFiberRef(core.currentTracerTimingEnabled)\n    const clock = Context.get(fiber.getFiberRef(defaultServices.currentServices), clockTag)\n    return core.onExit(evaluate(span), (exit) => endSpan(span, exit, clock, timingEnabled))\n  })\n}\n\n/** @internal */\nexport const withParentSpan = dual<\n  (\n    span: Tracer.AnySpan\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, span: Tracer.AnySpan) => Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>>\n>(2, (self, span) => provideService(self, internalTracer.spanTag, span))\n\n/** @internal */\nexport const withSpan: {\n  (\n    name: string,\n    options?: Tracer.SpanOptions | undefined\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    name: string,\n    options?: Tracer.SpanOptions | undefined\n  ): Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>>\n} = function() {\n  const dataFirst = typeof arguments[0] !== \"string\"\n  const name = dataFirst ? arguments[1] : arguments[0]\n  const options = internalTracer.addSpanStackTrace(dataFirst ? arguments[2] : arguments[1])\n  if (dataFirst) {\n    const self = arguments[0]\n    return useSpan(name, options, (span) => withParentSpan(self, span))\n  }\n  return (self: Effect.Effect<any, any, any>) => useSpan(name, options, (span) => withParentSpan(self, span))\n} as any\n\nexport const functionWithSpan = <Args extends Array<any>, Ret extends Effect.Effect<any, any, any>>(\n  options: {\n    readonly body: (...args: Args) => Ret\n    readonly options: Effect.FunctionWithSpanOptions | ((...args: Args) => Effect.FunctionWithSpanOptions)\n    readonly captureStackTrace?: boolean | undefined\n  }\n): (...args: Args) => Unify<Ret> =>\n  (function(this: any) {\n    let captureStackTrace: LazyArg<string | undefined> | boolean = options.captureStackTrace ?? false\n    if (options.captureStackTrace !== false) {\n      const limit = Error.stackTraceLimit\n      Error.stackTraceLimit = 2\n      const error = new Error()\n      Error.stackTraceLimit = limit\n      let cache: false | string = false\n      captureStackTrace = () => {\n        if (cache !== false) {\n          return cache\n        }\n        if (error.stack) {\n          const stack = error.stack.trim().split(\"\\n\")\n          cache = stack.slice(2).join(\"\\n\").trim()\n          return cache\n        }\n      }\n    }\n    return core.suspend(() => {\n      const opts = typeof options.options === \"function\"\n        ? options.options.apply(null, arguments as any)\n        : options.options\n      return withSpan(\n        core.suspend(() => internalCall(() => options.body.apply(this, arguments as any))),\n        opts.name,\n        {\n          ...opts,\n          captureStackTrace\n        }\n      )\n    })\n  }) as any\n\n// -------------------------------------------------------------------------------------\n// optionality\n// -------------------------------------------------------------------------------------\n\n/* @internal */\nexport const fromNullable = <A>(value: A): Effect.Effect<NonNullable<A>, Cause.NoSuchElementException> =>\n  value == null ? core.fail(new core.NoSuchElementException()) : core.succeed(value as NonNullable<A>)\n\n/* @internal */\nexport const optionFromOptional = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Effect.Effect<Option.Option<A>, Exclude<E, Cause.NoSuchElementException>, R> =>\n  core.catchAll(\n    core.map(self, Option.some),\n    (error) =>\n      core.isNoSuchElementException(error) ?\n        succeedNone :\n        core.fail(error as Exclude<E, Cause.NoSuchElementException>)\n  )\n"
  },
  {
    "path": "packages/effect/src/internal/core-stream.ts",
    "content": "import * as Cause from \"../Cause.js\"\nimport type * as Channel from \"../Channel.js\"\nimport type * as ChildExecutorDecision from \"../ChildExecutorDecision.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport type * as Context from \"../Context.js\"\nimport * as Effect from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport type * as Exit from \"../Exit.js\"\nimport { constVoid, dual, identity } from \"../Function.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as SingleProducerAsyncInput from \"../SingleProducerAsyncInput.js\"\nimport type * as UpstreamPullRequest from \"../UpstreamPullRequest.js\"\nimport type * as UpstreamPullStrategy from \"../UpstreamPullStrategy.js\"\nimport * as childExecutorDecision from \"./channel/childExecutorDecision.js\"\nimport type { ErasedContinuationK } from \"./channel/continuation.js\"\nimport { ContinuationKImpl } from \"./channel/continuation.js\"\nimport * as upstreamPullStrategy from \"./channel/upstreamPullStrategy.js\"\nimport * as OpCodes from \"./opCodes/channel.js\"\n\n/** @internal */\nconst ChannelSymbolKey = \"effect/Channel\"\n\n/** @internal */\nexport const ChannelTypeId: Channel.ChannelTypeId = Symbol.for(\n  ChannelSymbolKey\n) as Channel.ChannelTypeId\n\nconst channelVariance = {\n  /* c8 ignore next */\n  _Env: (_: never) => _,\n  /* c8 ignore next */\n  _InErr: (_: unknown) => _,\n  /* c8 ignore next */\n  _InElem: (_: unknown) => _,\n  /* c8 ignore next */\n  _InDone: (_: unknown) => _,\n  /* c8 ignore next */\n  _OutErr: (_: never) => _,\n  /* c8 ignore next */\n  _OutElem: (_: never) => _,\n  /* c8 ignore next */\n  _OutDone: (_: never) => _\n}\n\n/** @internal */\nconst proto = {\n  [ChannelTypeId]: channelVariance,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\ntype ErasedChannel = Channel.Channel<never, unknown, never, unknown, never, unknown>\n\n/** @internal */\nexport type Op<Tag extends string, Body = {}> =\n  & ErasedChannel\n  & Body\n  & { readonly _tag: Tag }\n\nexport type Primitive =\n  | BracketOut\n  | Bridge\n  | ConcatAll\n  | Emit\n  | Ensuring\n  | Fail\n  | Fold\n  | FromEffect\n  | PipeTo\n  | Provide\n  | Read\n  | Succeed\n  | SucceedNow\n  | Suspend\n\n/** @internal */\nexport interface BracketOut extends\n  Op<OpCodes.OP_BRACKET_OUT, {\n    acquire(): Effect.Effect<unknown, unknown, unknown>\n    finalizer(resource: unknown, exit: Exit.Exit<unknown, unknown>): Effect.Effect<unknown, unknown, unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Bridge extends\n  Op<OpCodes.OP_BRIDGE, {\n    readonly input: SingleProducerAsyncInput.AsyncInputProducer<unknown, unknown, unknown>\n    readonly channel: ErasedChannel\n  }>\n{}\n\n/** @internal */\nexport interface ConcatAll extends\n  Op<OpCodes.OP_CONCAT_ALL, {\n    combineInners(outDone: unknown, outDone2: unknown): unknown\n    combineAll(outDone: unknown, outDone2: unknown): unknown\n    onPull(\n      request: UpstreamPullRequest.UpstreamPullRequest<unknown>\n    ): UpstreamPullStrategy.UpstreamPullStrategy<unknown>\n    onEmit(outElem: unknown): ChildExecutorDecision.ChildExecutorDecision\n    value(): ErasedChannel\n    k(outElem: unknown): ErasedChannel\n  }>\n{}\n\n/** @internal */\nexport interface Emit extends\n  Op<OpCodes.OP_EMIT, {\n    readonly out: unknown\n  }>\n{}\n\n/** @internal */\nexport interface Ensuring extends\n  Op<OpCodes.OP_ENSURING, {\n    readonly channel: ErasedChannel\n    finalizer(exit: Exit.Exit<unknown, unknown>): Effect.Effect<unknown, unknown, unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Fail extends\n  Op<OpCodes.OP_FAIL, {\n    error(): Cause.Cause<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Fold extends\n  Op<OpCodes.OP_FOLD, {\n    readonly channel: ErasedChannel\n    readonly k: ErasedContinuationK\n  }>\n{}\n\n/** @internal */\nexport interface FromEffect extends\n  Op<OpCodes.OP_FROM_EFFECT, {\n    effect(): Effect.Effect<unknown, unknown, unknown>\n  }>\n{}\n\n/** @internal */\nexport interface PipeTo extends\n  Op<OpCodes.OP_PIPE_TO, {\n    left(): ErasedChannel\n    right(): ErasedChannel\n  }>\n{}\n\n/** @internal */\nexport interface Provide extends\n  Op<OpCodes.OP_PROVIDE, {\n    context(): Context.Context<unknown>\n    readonly inner: ErasedChannel\n  }>\n{}\n\n/** @internal */\nexport interface Read extends\n  Op<OpCodes.OP_READ, {\n    more(input: unknown): ErasedChannel\n    readonly done: ErasedContinuationK\n  }>\n{}\n\n/** @internal */\nexport interface Succeed extends\n  Op<OpCodes.OP_SUCCEED, {\n    evaluate(): unknown\n  }>\n{}\n\n/** @internal */\nexport interface SucceedNow extends\n  Op<OpCodes.OP_SUCCEED_NOW, {\n    readonly terminal: unknown\n  }>\n{}\n\n/** @internal */\nexport interface Suspend extends\n  Op<OpCodes.OP_SUSPEND, {\n    channel(): ErasedChannel\n  }>\n{}\n\n/** @internal */\nexport const isChannel = (u: unknown): u is Channel.Channel<\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown,\n  unknown\n> => hasProperty(u, ChannelTypeId) || Effect.isEffect(u)\n\n/** @internal */\nexport const acquireReleaseOut = dual<\n  <Z, R2>(\n    release: (z: Z, e: Exit.Exit<unknown, unknown>) => Effect.Effect<unknown, never, R2>\n  ) => <E, R>(self: Effect.Effect<Z, E, R>) => Channel.Channel<Z, unknown, E, unknown, void, unknown, R | R2>,\n  <Z, E, R, R2>(\n    self: Effect.Effect<Z, E, R>,\n    release: (z: Z, e: Exit.Exit<unknown, unknown>) => Effect.Effect<unknown, never, R2>\n  ) => Channel.Channel<Z, unknown, E, unknown, void, unknown, R | R2>\n>(2, (self, release) => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_BRACKET_OUT\n  op.acquire = () => self\n  op.finalizer = release\n  return op\n})\n\n/** @internal */\nexport const catchAllCause = dual<\n  <OutErr, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    f: (cause: Cause.Cause<OutErr>) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n  ) => <OutElem, InElem, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone1 | OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (cause: Cause.Cause<OutErr>) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone1 | OutDone,\n    InDone & InDone1,\n    Env1 | Env\n  >\n>(\n  2,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (cause: Cause.Cause<OutErr>) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone1, InDone1, Env1>\n  ): Channel.Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr1,\n    InErr & InErr1,\n    OutDone | OutDone1,\n    InDone & InDone1,\n    Env | Env1\n  > => {\n    const op = Object.create(proto)\n    op._tag = OpCodes.OP_FOLD\n    op.channel = self\n    op.k = new ContinuationKImpl(succeed, f)\n    return op\n  }\n)\n\n/** @internal */\nexport const collectElements = <Env, InErr, InElem, InDone, OutErr, OutElem, OutDone>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n): Channel.Channel<never, InElem, OutErr, InErr, [Chunk.Chunk<OutElem>, OutDone], InDone, Env> => {\n  return suspend(() => {\n    const builder: Array<OutElem> = []\n    return flatMap(\n      pipeTo(self, collectElementsReader(builder)),\n      (value) => sync(() => [Chunk.fromIterable(builder), value])\n    )\n  })\n}\n\n/** @internal */\nconst collectElementsReader = <OutErr, OutElem, OutDone>(\n  builder: Array<OutElem>\n): Channel.Channel<never, OutElem, OutErr, OutErr, OutDone, OutDone> =>\n  readWith({\n    onInput: (outElem) =>\n      flatMap(\n        sync(() => {\n          builder.push(outElem)\n        }),\n        () => collectElementsReader<OutErr, OutElem, OutDone>(builder)\n      ),\n    onFailure: fail,\n    onDone: succeedNow\n  })\n\n/** @internal */\nexport const concatAll = <OutElem, InElem, OutErr, InErr, InDone, Env>(\n  channels: Channel.Channel<\n    Channel.Channel<OutElem, InElem, OutErr, InErr, any, InDone, Env>,\n    InElem,\n    OutErr,\n    InErr,\n    any,\n    InDone,\n    Env\n  >\n): Channel.Channel<OutElem, InElem, OutErr, InErr, any, InDone, Env> => concatAllWith(channels, constVoid, constVoid)\n\n/** @internal */\nexport const concatAllWith = <\n  OutElem,\n  InElem2,\n  OutErr2,\n  InErr2,\n  OutDone,\n  InDone2,\n  Env2,\n  InElem,\n  OutErr,\n  InErr,\n  OutDone2,\n  InDone,\n  Env,\n  OutDone3\n>(\n  channels: Channel.Channel<\n    Channel.Channel<OutElem, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone2,\n    InDone,\n    Env\n  >,\n  f: (o: OutDone, o1: OutDone) => OutDone,\n  g: (o: OutDone, o2: OutDone2) => OutDone3\n): Channel.Channel<\n  OutElem,\n  InElem & InElem2,\n  OutErr | OutErr2,\n  InErr & InErr2,\n  OutDone3,\n  InDone & InDone2,\n  Env | Env2\n> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_CONCAT_ALL\n  op.combineInners = f\n  op.combineAll = g\n  op.onPull = () => upstreamPullStrategy.PullAfterNext(Option.none())\n  op.onEmit = () => childExecutorDecision.Continue\n  op.value = () => channels\n  op.k = identity\n  return op\n}\n\n/** @internal */\nexport const concatMapWith = dual<\n  <OutElem, OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2, OutDone2, OutDone3>(\n    f: (o: OutElem) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n    g: (o: OutDone, o1: OutDone) => OutDone,\n    h: (o: OutDone, o2: OutDone2) => OutDone3\n  ) => <Env, InErr, InElem, InDone, OutErr>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>\n  ) => Channel.Channel<\n    OutElem2,\n    InElem & InElem2,\n    OutErr2 | OutErr,\n    InErr & InErr2,\n    OutDone3,\n    InDone & InDone2,\n    Env2 | Env\n  >,\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone2,\n    InDone,\n    Env,\n    OutElem2,\n    InElem2,\n    OutErr2,\n    InErr2,\n    OutDone,\n    InDone2,\n    Env2,\n    OutDone3\n  >(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>,\n    f: (o: OutElem) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n    g: (o: OutDone, o1: OutDone) => OutDone,\n    h: (o: OutDone, o2: OutDone2) => OutDone3\n  ) => Channel.Channel<\n    OutElem2,\n    InElem & InElem2,\n    OutErr2 | OutErr,\n    InErr & InErr2,\n    OutDone3,\n    InDone & InDone2,\n    Env2 | Env\n  >\n>(4, <\n  Env,\n  InErr,\n  InElem,\n  InDone,\n  OutErr,\n  OutElem,\n  OutElem2,\n  OutDone,\n  OutDone2,\n  OutDone3,\n  Env2,\n  InErr2,\n  InElem2,\n  InDone2,\n  OutErr2\n>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>,\n  f: (\n    o: OutElem\n  ) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n  g: (o: OutDone, o1: OutDone) => OutDone,\n  h: (o: OutDone, o2: OutDone2) => OutDone3\n): Channel.Channel<\n  OutElem2,\n  InElem & InElem2,\n  OutErr | OutErr2,\n  InErr & InErr2,\n  OutDone3,\n  InDone & InDone2,\n  Env | Env2\n> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_CONCAT_ALL\n  op.combineInners = g\n  op.combineAll = h\n  op.onPull = () => upstreamPullStrategy.PullAfterNext(Option.none())\n  op.onEmit = () => childExecutorDecision.Continue\n  op.value = () => self\n  op.k = f\n  return op\n})\n\n/** @internal */\nexport const concatMapWithCustom = dual<\n  <OutElem, OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2, OutDone2, OutDone3>(\n    f: (o: OutElem) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n    g: (o: OutDone, o1: OutDone) => OutDone,\n    h: (o: OutDone, o2: OutDone2) => OutDone3,\n    onPull: (\n      upstreamPullRequest: UpstreamPullRequest.UpstreamPullRequest<OutElem>\n    ) => UpstreamPullStrategy.UpstreamPullStrategy<OutElem2>,\n    onEmit: (elem: OutElem2) => ChildExecutorDecision.ChildExecutorDecision\n  ) => <Env, InErr, InElem, InDone, OutErr>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>\n  ) => Channel.Channel<\n    OutElem2,\n    InElem & InElem2,\n    OutErr2 | OutErr,\n    InErr & InErr2,\n    OutDone3,\n    InDone & InDone2,\n    Env2 | Env\n  >,\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone2,\n    InDone,\n    Env,\n    OutElem2,\n    InElem2,\n    OutErr2,\n    InErr2,\n    OutDone,\n    InDone2,\n    Env2,\n    OutDone3\n  >(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>,\n    f: (o: OutElem) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n    g: (o: OutDone, o1: OutDone) => OutDone,\n    h: (o: OutDone, o2: OutDone2) => OutDone3,\n    onPull: (\n      upstreamPullRequest: UpstreamPullRequest.UpstreamPullRequest<OutElem>\n    ) => UpstreamPullStrategy.UpstreamPullStrategy<OutElem2>,\n    onEmit: (elem: OutElem2) => ChildExecutorDecision.ChildExecutorDecision\n  ) => Channel.Channel<\n    OutElem2,\n    InElem & InElem2,\n    OutErr2 | OutErr,\n    InErr & InErr2,\n    OutDone3,\n    InDone & InDone2,\n    Env2 | Env\n  >\n>(6, <\n  Env,\n  InErr,\n  InElem,\n  InDone,\n  OutErr,\n  OutElem,\n  OutElem2,\n  OutDone,\n  OutDone2,\n  OutDone3,\n  Env2,\n  InErr2,\n  InElem2,\n  InDone2,\n  OutErr2\n>(\n  self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone2, InDone, Env>,\n  f: (\n    o: OutElem\n  ) => Channel.Channel<OutElem2, InElem2, OutErr2, InErr2, OutDone, InDone2, Env2>,\n  g: (o: OutDone, o1: OutDone) => OutDone,\n  h: (o: OutDone, o2: OutDone2) => OutDone3,\n  onPull: (\n    upstreamPullRequest: UpstreamPullRequest.UpstreamPullRequest<OutElem>\n  ) => UpstreamPullStrategy.UpstreamPullStrategy<OutElem2>,\n  onEmit: (elem: OutElem2) => ChildExecutorDecision.ChildExecutorDecision\n): Channel.Channel<\n  OutElem2,\n  InElem & InElem2,\n  OutErr | OutErr2,\n  InErr & InErr2,\n  OutDone3,\n  InDone & InDone2,\n  Env | Env2\n> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_CONCAT_ALL\n  op.combineInners = g\n  op.combineAll = h\n  op.onPull = onPull\n  op.onEmit = onEmit\n  op.value = () => self\n  op.k = f\n  return op\n})\n\n/** @internal */\nexport const embedInput = dual<\n  <InErr, InElem, InDone>(\n    input: SingleProducerAsyncInput.AsyncInputProducer<InErr, InElem, InDone>\n  ) => <OutElem, OutErr, OutDone, Env>(\n    self: Channel.Channel<OutElem, unknown, OutErr, unknown, OutDone, unknown, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n  <OutElem, OutErr, OutDone, Env, InErr, InElem, InDone>(\n    self: Channel.Channel<OutElem, unknown, OutErr, unknown, OutDone, unknown, Env>,\n    input: SingleProducerAsyncInput.AsyncInputProducer<InErr, InElem, InDone>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n>(\n  2,\n  <OutElem, OutErr, OutDone, Env, InErr, InElem, InDone>(\n    self: Channel.Channel<OutElem, unknown, OutErr, unknown, OutDone, unknown, Env>,\n    input: SingleProducerAsyncInput.AsyncInputProducer<InErr, InElem, InDone>\n  ): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env> => {\n    const op = Object.create(proto)\n    op._tag = OpCodes.OP_BRIDGE\n    op.input = input\n    op.channel = self\n    return op\n  }\n)\n\n/** @internal */\nexport const ensuringWith = dual<\n  <OutDone, OutErr, Env2>(\n    finalizer: (e: Exit.Exit<OutDone, OutErr>) => Effect.Effect<unknown, never, Env2>\n  ) => <OutElem, InElem, InErr, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env2 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, Env2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    finalizer: (e: Exit.Exit<OutDone, OutErr>) => Effect.Effect<unknown, never, Env2>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env2 | Env>\n>(\n  2,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, Env2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    finalizer: (e: Exit.Exit<OutDone, OutErr>) => Effect.Effect<unknown, never, Env2>\n  ): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env | Env2> => {\n    const op = Object.create(proto)\n    op._tag = OpCodes.OP_ENSURING\n    op.channel = self\n    op.finalizer = finalizer\n    return op\n  }\n)\n\n/** @internal */\nexport const fail = <E>(error: E): Channel.Channel<never, unknown, E, unknown, never, unknown> =>\n  failCause(Cause.fail(error))\n\n/** @internal */\nexport const failSync = <E>(\n  evaluate: LazyArg<E>\n): Channel.Channel<never, unknown, E, unknown, never, unknown> => failCauseSync(() => Cause.fail(evaluate()))\n\n/** @internal */\nexport const failCause = <E>(\n  cause: Cause.Cause<E>\n): Channel.Channel<never, unknown, E, unknown, never, unknown> => failCauseSync(() => cause)\n\n/** @internal */\nexport const failCauseSync = <E>(\n  evaluate: LazyArg<Cause.Cause<E>>\n): Channel.Channel<never, unknown, E, unknown, never, unknown> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_FAIL\n  op.error = evaluate\n  return op\n}\n\n/** @internal */\nexport const flatMap = dual<\n  <OutDone, OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>(\n    f: (d: OutDone) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>\n  ) => <OutElem, InElem, OutErr, InErr, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    OutDone2,\n    InDone & InDone1,\n    Env1 | Env\n  >,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (d: OutDone) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>\n  ) => Channel.Channel<\n    OutElem1 | OutElem,\n    InElem & InElem1,\n    OutErr1 | OutErr,\n    InErr & InErr1,\n    OutDone2,\n    InDone & InDone1,\n    Env1 | Env\n  >\n>(\n  2,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    f: (d: OutDone) => Channel.Channel<OutElem1, InElem1, OutErr1, InErr1, OutDone2, InDone1, Env1>\n  ): Channel.Channel<\n    OutElem | OutElem1,\n    InElem & InElem1,\n    OutErr | OutErr1,\n    InErr & InErr1,\n    OutDone2,\n    InDone & InDone1,\n    Env | Env1\n  > => {\n    const op = Object.create(proto)\n    op._tag = OpCodes.OP_FOLD\n    op.channel = self\n    op.k = new ContinuationKImpl(f, failCause)\n    return op\n  }\n)\n\n/** @internal */\nexport const foldCauseChannel = dual<\n  <\n    OutErr,\n    OutElem1,\n    InElem1,\n    OutErr2,\n    InErr1,\n    OutDone2,\n    InDone1,\n    Env1,\n    OutDone,\n    OutElem2,\n    InElem2,\n    OutErr3,\n    InErr2,\n    OutDone3,\n    InDone2,\n    Env2\n  >(\n    options: {\n      readonly onFailure: (\n        c: Cause.Cause<OutErr>\n      ) => Channel.Channel<OutElem1, InElem1, OutErr2, InErr1, OutDone2, InDone1, Env1>\n      readonly onSuccess: (o: OutDone) => Channel.Channel<OutElem2, InElem2, OutErr3, InErr2, OutDone3, InDone2, Env2>\n    }\n  ) => <Env, InErr, InElem, InDone, OutElem>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<\n    OutElem1 | OutElem2 | OutElem,\n    InElem & InElem1 & InElem2,\n    OutErr2 | OutErr3,\n    InErr & InErr1 & InErr2,\n    OutDone2 | OutDone3,\n    InDone & InDone1 & InDone2,\n    Env1 | Env2 | Env\n  >,\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env,\n    OutElem1,\n    InElem1,\n    OutErr2,\n    InErr1,\n    OutDone2,\n    InDone1,\n    Env1,\n    OutElem2,\n    InElem2,\n    OutErr3,\n    InErr2,\n    OutDone3,\n    InDone2,\n    Env2\n  >(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    options: {\n      readonly onFailure: (\n        c: Cause.Cause<OutErr>\n      ) => Channel.Channel<OutElem1, InElem1, OutErr2, InErr1, OutDone2, InDone1, Env1>\n      readonly onSuccess: (o: OutDone) => Channel.Channel<OutElem2, InElem2, OutErr3, InErr2, OutDone3, InDone2, Env2>\n    }\n  ) => Channel.Channel<\n    OutElem1 | OutElem2 | OutElem,\n    InElem & InElem1 & InElem2,\n    OutErr2 | OutErr3,\n    InErr & InErr1 & InErr2,\n    OutDone2 | OutDone3,\n    InDone & InDone1 & InDone2,\n    Env1 | Env2 | Env\n  >\n>(\n  2,\n  <\n    OutElem,\n    InElem,\n    OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    Env,\n    OutElem1,\n    InElem1,\n    OutErr2,\n    InErr1,\n    OutDone2,\n    InDone1,\n    Env1,\n    OutElem2,\n    InElem2,\n    OutErr3,\n    InErr2,\n    OutDone3,\n    InDone2,\n    Env2\n  >(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    options: {\n      readonly onFailure: (\n        c: Cause.Cause<OutErr>\n      ) => Channel.Channel<OutElem1, InElem1, OutErr2, InErr1, OutDone2, InDone1, Env1>\n      readonly onSuccess: (o: OutDone) => Channel.Channel<OutElem2, InElem2, OutErr3, InErr2, OutDone3, InDone2, Env2>\n    }\n  ): Channel.Channel<\n    OutElem | OutElem1 | OutElem2,\n    InElem & InElem1 & InElem2,\n    OutErr2 | OutErr3,\n    InErr & InErr1 & InErr2,\n    OutDone2 | OutDone3,\n    InDone & InDone1 & InDone2,\n    Env | Env1 | Env2\n  > => {\n    const op = Object.create(proto)\n    op._tag = OpCodes.OP_FOLD\n    op.channel = self\n    op.k = new ContinuationKImpl(options.onSuccess, options.onFailure as any)\n    return op\n  }\n)\n\n/** @internal */\nexport const fromEffect = <A, E, R>(\n  effect: Effect.Effect<A, E, R>\n): Channel.Channel<never, unknown, E, unknown, A, unknown, R> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_FROM_EFFECT\n  op.effect = () => effect\n  return op\n}\n\n/** @internal */\nexport const pipeTo = dual<\n  <OutElem2, OutElem, OutErr2, OutErr, OutDone2, OutDone, Env2>(\n    that: Channel.Channel<OutElem2, OutElem, OutErr2, OutErr, OutDone2, OutDone, Env2>\n  ) => <InElem, InErr, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem2, InElem, OutErr2, InErr, OutDone2, InDone, Env2 | Env>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2, OutErr2, OutDone2, Env2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel.Channel<OutElem2, OutElem, OutErr2, OutErr, OutDone2, OutDone, Env2>\n  ) => Channel.Channel<OutElem2, InElem, OutErr2, InErr, OutDone2, InDone, Env2 | Env>\n>(\n  2,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env, OutElem2, OutErr2, OutDone2, Env2>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    that: Channel.Channel<OutElem2, OutElem, OutErr2, OutErr, OutDone2, OutDone, Env2>\n  ): Channel.Channel<OutElem2, InElem, OutErr2, InErr, OutDone2, InDone, Env | Env2> => {\n    const op = Object.create(proto)\n    op._tag = OpCodes.OP_PIPE_TO\n    op.left = () => self\n    op.right = () => that\n    return op\n  }\n)\n\n/** @internal */\nexport const provideContext = dual<\n  <Env>(\n    env: Context.Context<Env>\n  ) => <OutElem, InElem, OutErr, InErr, OutDone, InDone>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone>,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    env: Context.Context<Env>\n  ) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone>\n>(\n  2,\n  <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n    self: Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>,\n    env: Context.Context<Env>\n  ): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone> => {\n    const op = Object.create(proto)\n    op._tag = OpCodes.OP_PROVIDE\n    op.context = () => env\n    op.inner = self\n    return op\n  }\n)\n\n/** @internal */\nexport const readOrFail = <E, In = unknown>(\n  error: E\n): Channel.Channel<never, In, E, unknown, In, unknown> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_READ\n  op.more = succeed\n  op.done = new ContinuationKImpl(() => fail(error), () => fail(error))\n  return op\n}\n\n/** @internal */\nexport const readWith = <\n  InElem,\n  OutElem,\n  OutErr,\n  InErr,\n  OutDone,\n  InDone,\n  Env,\n  OutElem2,\n  OutErr2,\n  OutDone2,\n  Env2,\n  OutElem3,\n  OutErr3,\n  OutDone3,\n  Env3\n>(\n  options: {\n    readonly onInput: (input: InElem) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n    readonly onFailure: (error: InErr) => Channel.Channel<OutElem2, InElem, OutErr2, InErr, OutDone2, InDone, Env2>\n    readonly onDone: (done: InDone) => Channel.Channel<OutElem3, InElem, OutErr3, InErr, OutDone3, InDone, Env3>\n  }\n): Channel.Channel<\n  OutElem | OutElem2 | OutElem3,\n  InElem,\n  OutErr | OutErr2 | OutErr3,\n  InErr,\n  OutDone | OutDone2 | OutDone3,\n  InDone,\n  Env | Env2 | Env3\n> =>\n  readWithCause({\n    onInput: options.onInput,\n    onFailure: (cause) => Either.match(Cause.failureOrCause(cause), { onLeft: options.onFailure, onRight: failCause }),\n    onDone: options.onDone\n  })\n\n/** @internal */\nexport const readWithCause = <\n  InElem,\n  OutElem,\n  OutErr,\n  InErr,\n  OutDone,\n  InDone,\n  Env,\n  OutElem2,\n  OutErr2,\n  OutDone2,\n  Env2,\n  OutElem3,\n  OutErr3,\n  OutDone3,\n  Env3\n>(\n  options: {\n    readonly onInput: (input: InElem) => Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>\n    readonly onFailure: (\n      cause: Cause.Cause<InErr>\n    ) => Channel.Channel<OutElem2, InElem, OutErr2, InErr, OutDone2, InDone, Env2>\n    readonly onDone: (done: InDone) => Channel.Channel<OutElem3, InElem, OutErr3, InErr, OutDone3, InDone, Env3>\n  }\n): Channel.Channel<\n  OutElem | OutElem2 | OutElem3,\n  InElem,\n  OutErr | OutErr2 | OutErr3,\n  InErr,\n  OutDone | OutDone2 | OutDone3,\n  InDone,\n  Env | Env2 | Env3\n> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_READ\n  op.more = options.onInput\n  op.done = new ContinuationKImpl(options.onDone, options.onFailure as any)\n  return op\n}\n\n/** @internal */\nexport const succeed = <A>(\n  value: A\n): Channel.Channel<never, unknown, never, unknown, A, unknown> => sync(() => value)\n\n/** @internal */\nexport const succeedNow = <OutDone>(\n  result: OutDone\n): Channel.Channel<never, unknown, never, unknown, OutDone, unknown> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_SUCCEED_NOW\n  op.terminal = result\n  return op\n}\n\n/** @internal */\nexport const suspend = <OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>(\n  evaluate: LazyArg<Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env>>\n): Channel.Channel<OutElem, InElem, OutErr, InErr, OutDone, InDone, Env> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_SUSPEND\n  op.channel = evaluate\n  return op\n}\n\nexport const sync = <OutDone>(\n  evaluate: LazyArg<OutDone>\n): Channel.Channel<never, unknown, never, unknown, OutDone, unknown> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_SUCCEED\n  op.evaluate = evaluate\n  return op\n}\n\nconst void_: Channel.Channel<never> = succeedNow(void 0)\nexport {\n  /** @internal */\n  void_ as void\n}\n\n/** @internal */\nexport const write = <OutElem>(\n  out: OutElem\n): Channel.Channel<OutElem, unknown, never, unknown, void, unknown> => {\n  const op = Object.create(proto)\n  op._tag = OpCodes.OP_EMIT\n  op.out = out\n  return op\n}\n"
  },
  {
    "path": "packages/effect/src/internal/core.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport type * as Cause from \"../Cause.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport * as Context from \"../Context.js\"\nimport type * as Deferred from \"../Deferred.js\"\nimport type * as Differ from \"../Differ.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport * as Equal from \"../Equal.js\"\nimport type * as ExecutionStrategy from \"../ExecutionStrategy.js\"\nimport type * as Exit from \"../Exit.js\"\nimport type * as Fiber from \"../Fiber.js\"\nimport * as FiberId from \"../FiberId.js\"\nimport type * as FiberRef from \"../FiberRef.js\"\nimport type * as FiberStatus from \"../FiberStatus.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { dual, identity, pipe } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport * as Hash from \"../Hash.js\"\nimport * as HashMap from \"../HashMap.js\"\nimport type * as HashSet from \"../HashSet.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"../Inspectable.js\"\nimport * as List from \"../List.js\"\nimport type * as LogLevel from \"../LogLevel.js\"\nimport type * as LogSpan from \"../LogSpan.js\"\nimport type * as MetricLabel from \"../MetricLabel.js\"\nimport * as MutableRef from \"../MutableRef.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty, isObject, isPromiseLike, type Predicate, type Refinement } from \"../Predicate.js\"\nimport type * as Request from \"../Request.js\"\nimport type * as BlockedRequests from \"../RequestBlock.js\"\nimport type * as RequestResolver from \"../RequestResolver.js\"\nimport type * as RuntimeFlags from \"../RuntimeFlags.js\"\nimport * as RuntimeFlagsPatch from \"../RuntimeFlagsPatch.js\"\nimport type * as Scope from \"../Scope.js\"\nimport type * as Tracer from \"../Tracer.js\"\nimport type { NoInfer, NotFunction } from \"../Types.js\"\nimport { internalCall, YieldWrap } from \"../Utils.js\"\nimport * as blockedRequests_ from \"./blockedRequests.js\"\nimport * as internalCause from \"./cause.js\"\nimport * as deferred from \"./deferred.js\"\nimport * as internalDiffer from \"./differ.js\"\nimport { CommitPrototype, effectVariance, StructuralCommitPrototype } from \"./effectable.js\"\nimport { getBugErrorMessage } from \"./errors.js\"\nimport type * as FiberRuntime from \"./fiberRuntime.js\"\nimport type * as fiberScope from \"./fiberScope.js\"\nimport * as DeferredOpCodes from \"./opCodes/deferred.js\"\nimport * as OpCodes from \"./opCodes/effect.js\"\nimport * as runtimeFlags_ from \"./runtimeFlags.js\"\nimport { SingleShotGen } from \"./singleShotGen.js\"\n\n// -----------------------------------------------------------------------------\n// Effect\n// -----------------------------------------------------------------------------\n\n/**\n * @internal\n */\nexport const blocked = <A, E>(\n  blockedRequests: BlockedRequests.RequestBlock,\n  _continue: Effect.Effect<A, E>\n): Effect.Blocked<A, E> => {\n  const effect = new EffectPrimitive(\"Blocked\") as any\n  effect.effect_instruction_i0 = blockedRequests\n  effect.effect_instruction_i1 = _continue\n  return effect\n}\n\n/**\n * @internal\n */\nexport const runRequestBlock = (\n  blockedRequests: BlockedRequests.RequestBlock\n): Effect.Effect<void> => {\n  const effect = new EffectPrimitive(\"RunBlocked\") as any\n  effect.effect_instruction_i0 = blockedRequests\n  return effect\n}\n\n/** @internal */\nexport const EffectTypeId: Effect.EffectTypeId = Symbol.for(\"effect/Effect\") as Effect.EffectTypeId\n\n/** @internal */\nexport type Primitive =\n  | Async\n  | Commit\n  | Failure\n  | OnFailure\n  | OnSuccess\n  | OnStep\n  | OnSuccessAndFailure\n  | Success\n  | Sync\n  | UpdateRuntimeFlags\n  | While\n  | FromIterator\n  | WithRuntime\n  | Yield\n  | OpTag\n  | Blocked\n  | RunBlocked\n  | Either.Either<any, any>\n  | Option.Option<any>\n\n/** @internal */\nexport type Continuation =\n  | OnSuccess\n  | OnStep\n  | OnSuccessAndFailure\n  | OnFailure\n  | While\n  | FromIterator\n  | RevertFlags\n\n/** @internal */\nexport class RevertFlags {\n  readonly _op = OpCodes.OP_REVERT_FLAGS\n  constructor(\n    readonly patch: RuntimeFlagsPatch.RuntimeFlagsPatch,\n    readonly op: Primitive & { _op: OpCodes.OP_UPDATE_RUNTIME_FLAGS }\n  ) {\n  }\n}\n\nclass EffectPrimitive {\n  public effect_instruction_i0 = undefined\n  public effect_instruction_i1 = undefined\n  public effect_instruction_i2 = undefined\n  public trace = undefined;\n  [EffectTypeId] = effectVariance\n  constructor(readonly _op: Primitive[\"_op\"]) {}\n  [Equal.symbol](this: {}, that: unknown) {\n    return this === that\n  }\n  [Hash.symbol](this: {}) {\n    return Hash.cached(this, Hash.random(this))\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n  toJSON() {\n    return {\n      _id: \"Effect\",\n      _op: this._op,\n      effect_instruction_i0: toJSON(this.effect_instruction_i0),\n      effect_instruction_i1: toJSON(this.effect_instruction_i1),\n      effect_instruction_i2: toJSON(this.effect_instruction_i2)\n    }\n  }\n  toString() {\n    return format(this.toJSON())\n  }\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  }\n  [Symbol.iterator]() {\n    return new SingleShotGen(new YieldWrap(this))\n  }\n}\n\n/** @internal */\nclass EffectPrimitiveFailure {\n  public effect_instruction_i0 = undefined\n  public effect_instruction_i1 = undefined\n  public effect_instruction_i2 = undefined\n  public trace = undefined;\n  [EffectTypeId] = effectVariance\n  constructor(readonly _op: Primitive[\"_op\"]) {\n    // @ts-expect-error\n    this._tag = _op\n  }\n  [Equal.symbol](this: {}, that: unknown) {\n    return exitIsExit(that) && that._op === \"Failure\" &&\n      // @ts-expect-error\n      Equal.equals(this.effect_instruction_i0, that.effect_instruction_i0)\n  }\n  [Hash.symbol](this: {}) {\n    return pipe(\n      // @ts-expect-error\n      Hash.string(this._tag),\n      // @ts-expect-error\n      Hash.combine(Hash.hash(this.effect_instruction_i0)),\n      Hash.cached(this)\n    )\n  }\n  get cause() {\n    return this.effect_instruction_i0\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n  toJSON() {\n    return {\n      _id: \"Exit\",\n      _tag: this._op,\n      cause: (this.cause as any).toJSON()\n    }\n  }\n  toString() {\n    return format(this.toJSON())\n  }\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  }\n  [Symbol.iterator]() {\n    return new SingleShotGen(new YieldWrap(this))\n  }\n}\n\n/** @internal */\nclass EffectPrimitiveSuccess {\n  public effect_instruction_i0 = undefined\n  public effect_instruction_i1 = undefined\n  public effect_instruction_i2 = undefined\n  public trace = undefined;\n  [EffectTypeId] = effectVariance\n  constructor(readonly _op: Primitive[\"_op\"]) {\n    // @ts-expect-error\n    this._tag = _op\n  }\n  [Equal.symbol](this: {}, that: unknown) {\n    return exitIsExit(that) && that._op === \"Success\" &&\n      // @ts-expect-error\n      Equal.equals(this.effect_instruction_i0, that.effect_instruction_i0)\n  }\n  [Hash.symbol](this: {}) {\n    return pipe(\n      // @ts-expect-error\n      Hash.string(this._tag),\n      // @ts-expect-error\n      Hash.combine(Hash.hash(this.effect_instruction_i0)),\n      Hash.cached(this)\n    )\n  }\n  get value() {\n    return this.effect_instruction_i0\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n  toJSON() {\n    return {\n      _id: \"Exit\",\n      _tag: this._op,\n      value: toJSON(this.value)\n    }\n  }\n  toString() {\n    return format(this.toJSON())\n  }\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  }\n  [Symbol.iterator]() {\n    return new SingleShotGen(new YieldWrap(this))\n  }\n}\n\n/** @internal */\nexport type Op<Tag extends string, Body = {}> = Effect.Effect<never> & Body & {\n  readonly _op: Tag\n}\n\n/** @internal */\nexport interface Async extends\n  Op<OpCodes.OP_ASYNC, {\n    effect_instruction_i0(resume: (effect: Primitive) => void): void\n    readonly effect_instruction_i1: FiberId.FiberId\n  }>\n{}\n\n/** @internal */\nexport interface Blocked<out E = any, out A = any> extends\n  Op<\"Blocked\", {\n    readonly effect_instruction_i0: BlockedRequests.RequestBlock\n    readonly effect_instruction_i1: Effect.Effect<A, E>\n  }>\n{}\n\n/** @internal */\nexport interface RunBlocked extends\n  Op<\"RunBlocked\", {\n    readonly effect_instruction_i0: BlockedRequests.RequestBlock\n  }>\n{}\n\n/** @internal */\nexport interface Failure extends\n  Op<OpCodes.OP_FAILURE, {\n    readonly effect_instruction_i0: Cause.Cause<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface OpTag extends Op<OpCodes.OP_TAG, {}> {}\n\n/** @internal */\nexport interface Commit extends\n  Op<OpCodes.OP_COMMIT, {\n    commit(): Effect.Effect<unknown, unknown, unknown>\n  }>\n{}\n\n/** @internal */\nexport interface OnFailure extends\n  Op<OpCodes.OP_ON_FAILURE, {\n    readonly effect_instruction_i0: Primitive\n    effect_instruction_i1(a: Cause.Cause<unknown>): Primitive\n  }>\n{}\n\n/** @internal */\nexport interface OnSuccess extends\n  Op<OpCodes.OP_ON_SUCCESS, {\n    readonly effect_instruction_i0: Primitive\n    effect_instruction_i1(a: unknown): Primitive\n  }>\n{}\n\n/** @internal */\nexport interface OnStep extends Op<\"OnStep\", { readonly effect_instruction_i0: Primitive }> {}\n\n/** @internal */\nexport interface OnSuccessAndFailure extends\n  Op<OpCodes.OP_ON_SUCCESS_AND_FAILURE, {\n    readonly effect_instruction_i0: Primitive\n    effect_instruction_i1(a: Cause.Cause<unknown>): Primitive\n    effect_instruction_i2(a: unknown): Primitive\n  }>\n{}\n\n/** @internal */\nexport interface Success extends\n  Op<OpCodes.OP_SUCCESS, {\n    readonly effect_instruction_i0: unknown\n  }>\n{}\n\n/** @internal */\nexport interface Sync extends\n  Op<OpCodes.OP_SYNC, {\n    effect_instruction_i0(): unknown\n  }>\n{}\n\n/** @internal */\nexport interface UpdateRuntimeFlags extends\n  Op<OpCodes.OP_UPDATE_RUNTIME_FLAGS, {\n    readonly effect_instruction_i0: RuntimeFlagsPatch.RuntimeFlagsPatch\n    readonly effect_instruction_i1?: (oldRuntimeFlags: RuntimeFlags.RuntimeFlags) => Primitive\n  }>\n{}\n\n/** @internal */\nexport interface While extends\n  Op<OpCodes.OP_WHILE, {\n    effect_instruction_i0(): boolean\n    effect_instruction_i1(): Primitive\n    effect_instruction_i2(a: unknown): void\n  }>\n{}\n\n/** @internal */\nexport interface FromIterator extends\n  Op<OpCodes.OP_ITERATOR, {\n    effect_instruction_i0: Iterator<YieldWrap<Primitive>, any>\n  }>\n{}\n\n/** @internal */\nexport interface WithRuntime extends\n  Op<OpCodes.OP_WITH_RUNTIME, {\n    effect_instruction_i0(fiber: FiberRuntime.FiberRuntime<unknown, unknown>, status: FiberStatus.Running): Primitive\n  }>\n{}\n\n/** @internal */\nexport interface Yield extends Op<OpCodes.OP_YIELD> {}\n\n/** @internal */\nexport const isEffect = (u: unknown): u is Effect.Effect<unknown, unknown, unknown> => hasProperty(u, EffectTypeId)\n\n/* @internal */\nexport const withFiberRuntime = <A, E = never, R = never>(\n  withRuntime: (fiber: FiberRuntime.FiberRuntime<A, E>, status: FiberStatus.Running) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => {\n  const effect = new EffectPrimitive(OpCodes.OP_WITH_RUNTIME) as any\n  effect.effect_instruction_i0 = withRuntime\n  return effect\n}\n\n/* @internal */\nexport const acquireUseRelease: {\n  <A2, E2, R2, A, X, R3>(\n    use: (a: A) => Effect.Effect<A2, E2, R2>,\n    release: (a: A, exit: Exit.Exit<A2, E2>) => Effect.Effect<X, never, R3>\n  ): <E, R>(acquire: Effect.Effect<A, E, R>) => Effect.Effect<A2, E2 | E, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, X, R3>(\n    acquire: Effect.Effect<A, E, R>,\n    use: (a: A) => Effect.Effect<A2, E2, R2>,\n    release: (a: A, exit: Exit.Exit<A2, E2>) => Effect.Effect<X, never, R3>\n  ): Effect.Effect<A2, E | E2, R | R2 | R3>\n} = dual(3, <A, E, R, A2, E2, R2, X, R3>(\n  acquire: Effect.Effect<A, E, R>,\n  use: (a: A) => Effect.Effect<A2, E2, R2>,\n  release: (a: A, exit: Exit.Exit<A2, E2>) => Effect.Effect<X, never, R3>\n): Effect.Effect<A2, E | E2, R | R2 | R3> =>\n  uninterruptibleMask((restore) =>\n    flatMap(\n      acquire,\n      (a) =>\n        flatMap(exit(suspend(() => restore(use(a)))), (exit): Effect.Effect<A2, E | E2, R | R2 | R3> => {\n          return suspend(() => release(a, exit)).pipe(\n            matchCauseEffect({\n              onFailure: (cause) => {\n                switch (exit._tag) {\n                  case OpCodes.OP_FAILURE:\n                    return failCause(internalCause.sequential(exit.effect_instruction_i0, cause))\n                  case OpCodes.OP_SUCCESS:\n                    return failCause(cause)\n                }\n              },\n              onSuccess: () => exit\n            })\n          )\n        })\n    )\n  ))\n\n/* @internal */\nexport const as: {\n  <B>(value: B): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E, R>\n  <A, E, R, B>(self: Effect.Effect<A, E, R>, value: B): Effect.Effect<B, E, R>\n} = dual(\n  2,\n  <A, E, R, B>(self: Effect.Effect<A, E, R>, value: B): Effect.Effect<B, E, R> => flatMap(self, () => succeed(value))\n)\n\n/* @internal */\nexport const asVoid = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> => as(self, void 0)\n\n/* @internal */\nexport const custom: {\n  <X, A, E, R>(i0: X, body: (this: { effect_instruction_i0: X }) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R>\n  <X, Y, A, E, R>(\n    i0: X,\n    i1: Y,\n    body: (this: { effect_instruction_i0: X; effect_instruction_i1: Y }) => Effect.Effect<A, E, R>\n  ): Effect.Effect<A, E, R>\n  <X, Y, Z, A, E, R>(\n    i0: X,\n    i1: Y,\n    i2: Z,\n    body: (\n      this: { effect_instruction_i0: X; effect_instruction_i1: Y; effect_instruction_i2: Z }\n    ) => Effect.Effect<A, E, R>\n  ): Effect.Effect<A, E, R>\n} = function() {\n  const wrapper = new EffectPrimitive(OpCodes.OP_COMMIT) as any\n  switch (arguments.length) {\n    case 2: {\n      wrapper.effect_instruction_i0 = arguments[0]\n      wrapper.commit = arguments[1]\n      break\n    }\n    case 3: {\n      wrapper.effect_instruction_i0 = arguments[0]\n      wrapper.effect_instruction_i1 = arguments[1]\n      wrapper.commit = arguments[2]\n      break\n    }\n    case 4: {\n      wrapper.effect_instruction_i0 = arguments[0]\n      wrapper.effect_instruction_i1 = arguments[1]\n      wrapper.effect_instruction_i2 = arguments[2]\n      wrapper.commit = arguments[3]\n      break\n    }\n    default: {\n      throw new Error(getBugErrorMessage(\"you're not supposed to end up here\"))\n    }\n  }\n  return wrapper\n}\n\n/* @internal */\nexport const unsafeAsync = <A, E = never, R = never>(\n  register: (\n    callback: (_: Effect.Effect<A, E, R>) => void\n  ) => void | Effect.Effect<void, never, R>,\n  blockingOn: FiberId.FiberId = FiberId.none\n): Effect.Effect<A, E, R> => {\n  const effect = new EffectPrimitive(OpCodes.OP_ASYNC) as any\n  let cancelerRef: Effect.Effect<void, never, R> | void = undefined\n  effect.effect_instruction_i0 = (resume: (_: Effect.Effect<A, E, R>) => void) => {\n    cancelerRef = register(resume)\n  }\n  effect.effect_instruction_i1 = blockingOn\n  return onInterrupt(effect, (_) => isEffect(cancelerRef) ? cancelerRef : void_)\n}\n\n/* @internal */\nexport const asyncInterrupt = <A, E = never, R = never>(\n  register: (\n    callback: (_: Effect.Effect<A, E, R>) => void\n  ) => void | Effect.Effect<void, never, R>,\n  blockingOn: FiberId.FiberId = FiberId.none\n): Effect.Effect<A, E, R> => suspend(() => unsafeAsync(register, blockingOn))\n\nconst async_ = <A, E = never, R = never>(\n  resume: (\n    callback: (_: Effect.Effect<A, E, R>) => void,\n    signal: AbortSignal\n  ) => void | Effect.Effect<void, never, R>,\n  blockingOn: FiberId.FiberId = FiberId.none\n): Effect.Effect<A, E, R> => {\n  return custom(resume, function() {\n    let backingResume: ((_: Effect.Effect<A, E, R>) => void) | undefined = undefined\n    let pendingEffect: Effect.Effect<A, E, R> | undefined = undefined\n    function proxyResume(effect: Effect.Effect<A, E, R>) {\n      if (backingResume) {\n        backingResume(effect)\n      } else if (pendingEffect === undefined) {\n        pendingEffect = effect\n      }\n    }\n    const effect = new EffectPrimitive(OpCodes.OP_ASYNC) as any\n    effect.effect_instruction_i0 = (resume: (_: Effect.Effect<A, E, R>) => void) => {\n      backingResume = resume\n      if (pendingEffect) {\n        resume(pendingEffect)\n      }\n    }\n    effect.effect_instruction_i1 = blockingOn\n    let cancelerRef: Effect.Effect<void, never, R> | void = undefined\n    let controllerRef: AbortController | void = undefined\n    if (this.effect_instruction_i0.length !== 1) {\n      controllerRef = new AbortController()\n      cancelerRef = internalCall(() => this.effect_instruction_i0(proxyResume, controllerRef!.signal))\n    } else {\n      cancelerRef = internalCall(() => (this.effect_instruction_i0 as any)(proxyResume))\n    }\n    return (cancelerRef || controllerRef) ?\n      onInterrupt(effect, (_) => {\n        if (controllerRef) {\n          controllerRef.abort()\n        }\n        return cancelerRef ?? void_\n      }) :\n      effect\n  })\n}\nexport {\n  /** @internal */\n  async_ as async\n}\n\n/* @internal */\nexport const catchAllCause = dual<\n  <E, A2, E2, R2>(\n    f: (cause: Cause.Cause<E>) => Effect.Effect<A2, E2, R2>\n  ) => <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A, E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (cause: Cause.Cause<E>) => Effect.Effect<A2, E2, R2>\n  ) => Effect.Effect<A2 | A, E2, R2 | R>\n>(2, (self, f) => {\n  const effect = new EffectPrimitive(OpCodes.OP_ON_FAILURE) as any\n  effect.effect_instruction_i0 = self\n  effect.effect_instruction_i1 = f\n  return effect\n})\n\n/* @internal */\nexport const catchAll: {\n  <E, A2, E2, R2>(\n    f: (e: E) => Effect.Effect<A2, E2, R2>\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (e: E) => Effect.Effect<A2, E2, R2>\n  ): Effect.Effect<A2 | A, E2, R2 | R>\n} = dual(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (e: E) => Effect.Effect<A2, E2, R2>\n  ): Effect.Effect<A2 | A, E2, R2 | R> => matchEffect(self, { onFailure: f, onSuccess: succeed })\n)\n\n/* @internal */\nexport const catchIf: {\n  <E, EB extends E, A2, E2, R2>(\n    refinement: Refinement<NoInfer<E>, EB>,\n    f: (e: EB) => Effect.Effect<A2, E2, R2>\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A, E2 | Exclude<E, EB>, R2 | R>\n  <E, A2, E2, R2>(\n    predicate: Predicate<NoInfer<E>>,\n    f: (e: NoInfer<E>) => Effect.Effect<A2, E2, R2>\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A, E | E2, R2 | R>\n  <A, E, R, EB extends E, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    refinement: Refinement<E, EB>,\n    f: (e: EB) => Effect.Effect<A2, E2, R2>\n  ): Effect.Effect<A2 | A, E2 | Exclude<E, EB>, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    predicate: Predicate<E>,\n    f: (e: E) => Effect.Effect<A2, E2, R2>\n  ): Effect.Effect<A | A2, E | E2, R | R2>\n} = dual(3, <A, E, R, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  predicate: Predicate<E>,\n  f: (e: E) => Effect.Effect<A2, E2, R2>\n): Effect.Effect<A | A2, E | E2, R | R2> =>\n  catchAllCause(self, (cause): Effect.Effect<A | A2, E | E2, R | R2> => {\n    const either = internalCause.failureOrCause(cause)\n    switch (either._tag) {\n      case \"Left\":\n        return predicate(either.left) ? f(either.left) : failCause(cause)\n      case \"Right\":\n        return failCause(either.right)\n    }\n  }))\n\n/* @internal */\nexport const catchSome = dual<\n  <E, A2, E2, R2>(\n    pf: (e: NoInfer<E>) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ) => <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A, E | E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    pf: (e: NoInfer<E>) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ) => Effect.Effect<A2 | A, E | E2, R2 | R>\n>(2, <A, E, R, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  pf: (e: NoInfer<E>) => Option.Option<Effect.Effect<A2, E2, R2>>\n) =>\n  catchAllCause(self, (cause): Effect.Effect<A2 | A, E | E2, R2 | R> => {\n    const either = internalCause.failureOrCause(cause)\n    switch (either._tag) {\n      case \"Left\":\n        return pipe(pf(either.left), Option.getOrElse(() => failCause(cause)))\n      case \"Right\":\n        return failCause(either.right)\n    }\n  }))\n\n/* @internal */\nexport const checkInterruptible = <A, E, R>(\n  f: (isInterruptible: boolean) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => withFiberRuntime((_, status) => f(runtimeFlags_.interruption(status.runtimeFlags)))\n\nconst originalSymbol = Symbol.for(\"effect/OriginalAnnotation\")\n\n/* @internal */\nexport const originalInstance = <E>(obj: E): E => {\n  if (hasProperty(obj, originalSymbol)) {\n    // @ts-expect-error\n    return obj[originalSymbol]\n  }\n  return obj\n}\n\n/* @internal */\nexport const capture = <E>(obj: E & object, span: Option.Option<Tracer.Span>): E => {\n  if (Option.isSome(span)) {\n    return new Proxy(obj, {\n      has(target, p) {\n        return p === internalCause.spanSymbol || p === originalSymbol || p in target\n      },\n      get(target, p) {\n        if (p === internalCause.spanSymbol) {\n          return span.value\n        }\n        if (p === originalSymbol) {\n          return obj\n        }\n        // @ts-expect-error\n        return target[p]\n      }\n    })\n  }\n  return obj\n}\n\n/* @internal */\nexport const die = (defect: unknown): Effect.Effect<never> =>\n  isObject(defect) && !(internalCause.spanSymbol in defect) ?\n    withFiberRuntime((fiber) => failCause(internalCause.die(capture(defect, currentSpanFromFiber(fiber)))))\n    : failCause(internalCause.die(defect))\n\n/* @internal */\nexport const dieMessage = (message: string): Effect.Effect<never> =>\n  failCauseSync(() => internalCause.die(new RuntimeException(message)))\n\n/* @internal */\nexport const dieSync = (evaluate: LazyArg<unknown>): Effect.Effect<never> => flatMap(sync(evaluate), die)\n\n/* @internal */\nexport const either = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<Either.Either<A, E>, never, R> =>\n  matchEffect(self, {\n    onFailure: (e) => succeed(Either.left(e)),\n    onSuccess: (a) => succeed(Either.right(a))\n  })\n\n/* @internal */\nexport const exit = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<Exit.Exit<A, E>, never, R> =>\n  matchCause(self, {\n    onFailure: exitFailCause,\n    onSuccess: exitSucceed\n  })\n\n/* @internal */\nexport const fail = <E>(error: E): Effect.Effect<never, E> =>\n  isObject(error) && !(internalCause.spanSymbol in error) ?\n    withFiberRuntime((fiber) => failCause(internalCause.fail(capture(error, currentSpanFromFiber(fiber)))))\n    : failCause(internalCause.fail(error))\n\n/* @internal */\nexport const failSync = <E>(evaluate: LazyArg<E>): Effect.Effect<never, E> => flatMap(sync(evaluate), fail)\n\n/* @internal */\nexport const failCause = <E>(cause: Cause.Cause<E>): Effect.Effect<never, E> => {\n  const effect = new EffectPrimitiveFailure(OpCodes.OP_FAILURE) as any\n  effect.effect_instruction_i0 = cause\n  return effect\n}\n\n/* @internal */\nexport const failCauseSync = <E>(\n  evaluate: LazyArg<Cause.Cause<E>>\n): Effect.Effect<never, E> => flatMap(sync(evaluate), failCause)\n\n/* @internal */\nexport const fiberId: Effect.Effect<FiberId.FiberId> = withFiberRuntime((state) => succeed(state.id()))\n\n/* @internal */\nexport const fiberIdWith = <A, E, R>(\n  f: (descriptor: FiberId.Runtime) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => withFiberRuntime((state) => f(state.id()))\n\n/* @internal */\nexport const flatMap = dual<\n  <A, B, E1, R1>(\n    f: (a: A) => Effect.Effect<B, E1, R1>\n  ) => <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E1 | E, R1 | R>,\n  <A, E, R, B, E1, R1>(\n    self: Effect.Effect<A, E, R>,\n    f: (a: A) => Effect.Effect<B, E1, R1>\n  ) => Effect.Effect<B, E | E1, R | R1>\n>(\n  2,\n  (self, f) => {\n    const effect = new EffectPrimitive(OpCodes.OP_ON_SUCCESS) as any\n    effect.effect_instruction_i0 = self\n    effect.effect_instruction_i1 = f\n    return effect\n  }\n)\n\n/* @internal */\nexport const andThen: {\n  <A, X>(\n    f: (a: NoInfer<A>) => X\n  ): <E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => [X] extends [Effect.Effect<infer A1, infer E1, infer R1>] ? Effect.Effect<A1, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer A1>] ? Effect.Effect<A1, E | Cause.UnknownException, R>\n    : Effect.Effect<X, E, R>\n  <X>(\n    f: NotFunction<X>\n  ): <A, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => [X] extends [Effect.Effect<infer A1, infer E1, infer R1>] ? Effect.Effect<A1, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer A1>] ? Effect.Effect<A1, E | Cause.UnknownException, R>\n    : Effect.Effect<X, E, R>\n  <A, E, R, X>(\n    self: Effect.Effect<A, E, R>,\n    f: (a: NoInfer<A>) => X\n  ): [X] extends [Effect.Effect<infer A1, infer E1, infer R1>] ? Effect.Effect<A1, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer A1>] ? Effect.Effect<A1, E | Cause.UnknownException, R>\n    : Effect.Effect<X, E, R>\n  <A, E, R, X>(\n    self: Effect.Effect<A, E, R>,\n    f: NotFunction<X>\n  ): [X] extends [Effect.Effect<infer A1, infer E1, infer R1>] ? Effect.Effect<A1, E | E1, R | R1>\n    : [X] extends [PromiseLike<infer A1>] ? Effect.Effect<A1, E | Cause.UnknownException, R>\n    : Effect.Effect<X, E, R>\n} = dual(2, (self, f) =>\n  flatMap(self, (a) => {\n    const b = typeof f === \"function\" ? (f as any)(a) : f\n    if (isEffect(b)) {\n      return b\n    } else if (isPromiseLike(b)) {\n      return unsafeAsync<any, Cause.UnknownException>((resume) => {\n        b.then((a) => resume(succeed(a)), (e) =>\n          resume(fail(new UnknownException(e, \"An unknown error occurred in Effect.andThen\"))))\n      })\n    }\n    return succeed(b)\n  }))\n\n/* @internal */\nexport const step = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Effect.Effect<Exit.Exit<A, E> | Effect.Blocked<A, E>, never, R> => {\n  const effect = new EffectPrimitive(\"OnStep\") as any\n  effect.effect_instruction_i0 = self\n  return effect\n}\n\n/* @internal */\nexport const flatten = <A, E1, R1, E, R>(\n  self: Effect.Effect<Effect.Effect<A, E1, R1>, E, R>\n): Effect.Effect<A, E | E1, R | R1> => flatMap(self, identity)\n\n/* @internal */\nexport const flip = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<E, A, R> =>\n  matchEffect(self, { onFailure: succeed, onSuccess: fail })\n\n/* @internal */\nexport const matchCause: {\n  <E, A2, A, A3>(\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => A2\n      readonly onSuccess: (a: A) => A3\n    }\n  ): <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A3, never, R>\n  <A, E, R, A2, A3>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => A2\n      readonly onSuccess: (a: A) => A3\n    }\n  ): Effect.Effect<A2 | A3, never, R>\n} = dual(2, <A, E, R, A2, A3>(\n  self: Effect.Effect<A, E, R>,\n  options: {\n    readonly onFailure: (cause: Cause.Cause<E>) => A2\n    readonly onSuccess: (a: A) => A3\n  }\n): Effect.Effect<A2 | A3, never, R> =>\n  matchCauseEffect(self, {\n    onFailure: (cause) => succeed(options.onFailure(cause)),\n    onSuccess: (a) => succeed(options.onSuccess(a))\n  }))\n\n/* @internal */\nexport const matchCauseEffect: {\n  <E, A2, E2, R2, A, A3, E3, R3>(\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<A2, E2, R2>\n      readonly onSuccess: (a: A) => Effect.Effect<A3, E3, R3>\n    }\n  ): <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A3, E2 | E3, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<A2, E2, R2>\n      readonly onSuccess: (a: A) => Effect.Effect<A3, E3, R3>\n    }\n  ): Effect.Effect<A2 | A3, E2 | E3, R2 | R3 | R>\n} = dual(2, <A, E, R, A2, E2, R2, A3, E3, R3>(\n  self: Effect.Effect<A, E, R>,\n  options: {\n    readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<A2, E2, R2>\n    readonly onSuccess: (a: A) => Effect.Effect<A3, E3, R3>\n  }\n): Effect.Effect<A2 | A3, E2 | E3, R2 | R3 | R> => {\n  const effect = new EffectPrimitive(OpCodes.OP_ON_SUCCESS_AND_FAILURE) as any\n  effect.effect_instruction_i0 = self\n  effect.effect_instruction_i1 = options.onFailure\n  effect.effect_instruction_i2 = options.onSuccess\n  return effect\n})\n\n/* @internal */\nexport const matchEffect: {\n  <E, A2, E2, R2, A, A3, E3, R3>(\n    options: {\n      readonly onFailure: (e: E) => Effect.Effect<A2, E2, R2>\n      readonly onSuccess: (a: A) => Effect.Effect<A3, E3, R3>\n    }\n  ): <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A3, E2 | E3, R2 | R3 | R>\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly onFailure: (e: E) => Effect.Effect<A2, E2, R2>\n      readonly onSuccess: (a: A) => Effect.Effect<A3, E3, R3>\n    }\n  ): Effect.Effect<A2 | A3, E2 | E3, R2 | R3 | R>\n} = dual(2, <A, E, R, A2, E2, R2, A3, E3, R3>(\n  self: Effect.Effect<A, E, R>,\n  options: {\n    readonly onFailure: (e: E) => Effect.Effect<A2, E2, R2>\n    readonly onSuccess: (a: A) => Effect.Effect<A3, E3, R3>\n  }\n): Effect.Effect<A2 | A3, E2 | E3, R2 | R3 | R> =>\n  matchCauseEffect(self, {\n    onFailure: (cause) => {\n      const defects = internalCause.defects(cause)\n      if (defects.length > 0) {\n        return failCause(internalCause.electFailures(cause))\n      }\n      const failures = internalCause.failures(cause)\n      if (failures.length > 0) {\n        return options.onFailure(Chunk.unsafeHead(failures))\n      }\n      return failCause(cause as Cause.Cause<never>)\n    },\n    onSuccess: options.onSuccess\n  }))\n\n/* @internal */\nexport const forEachSequential: {\n  <A, B, E, R>(f: (a: A, i: number) => Effect.Effect<B, E, R>): (self: Iterable<A>) => Effect.Effect<Array<B>, E, R>\n  <A, B, E, R>(self: Iterable<A>, f: (a: A, i: number) => Effect.Effect<B, E, R>): Effect.Effect<Array<B>, E, R>\n} = dual(\n  2,\n  <A, B, E, R>(self: Iterable<A>, f: (a: A, i: number) => Effect.Effect<B, E, R>): Effect.Effect<Array<B>, E, R> =>\n    suspend(() => {\n      const arr = Arr.fromIterable(self)\n      const ret = Arr.allocate<B>(arr.length)\n      let i = 0\n      return as(\n        whileLoop({\n          while: () => i < arr.length,\n          body: () => f(arr[i], i),\n          step: (b) => {\n            ret[i++] = b\n          }\n        }),\n        ret as Array<B>\n      )\n    })\n)\n\n/* @internal */\nexport const forEachSequentialDiscard: {\n  <A, B, E, R>(f: (a: A, i: number) => Effect.Effect<B, E, R>): (self: Iterable<A>) => Effect.Effect<void, E, R>\n  <A, B, E, R>(self: Iterable<A>, f: (a: A, i: number) => Effect.Effect<B, E, R>): Effect.Effect<void, E, R>\n} = dual(\n  2,\n  <A, B, E, R>(self: Iterable<A>, f: (a: A, i: number) => Effect.Effect<B, E, R>): Effect.Effect<void, E, R> =>\n    suspend(() => {\n      const arr = Arr.fromIterable(self)\n      let i = 0\n      return whileLoop({\n        while: () => i < arr.length,\n        body: () => f(arr[i], i),\n        step: () => {\n          i++\n        }\n      })\n    })\n)\n\n/* @internal */\nexport const if_ = dual<\n  <A1, E1, R1, A2, E2, R2>(\n    options: {\n      readonly onTrue: LazyArg<Effect.Effect<A1, E1, R1>>\n      readonly onFalse: LazyArg<Effect.Effect<A2, E2, R2>>\n    }\n  ) => <E = never, R = never>(\n    self: Effect.Effect<boolean, E, R> | boolean\n  ) => Effect.Effect<A1 | A2, E | E1 | E2, R | R1 | R2>,\n  <A1, E1, R1, A2, E2, R2, E = never, R = never>(\n    self: Effect.Effect<boolean, E, R> | boolean,\n    options: {\n      readonly onTrue: LazyArg<Effect.Effect<A1, E1, R1>>\n      readonly onFalse: LazyArg<Effect.Effect<A2, E2, R2>>\n    }\n  ) => Effect.Effect<A1 | A2, E1 | E2 | E, R1 | R2 | R>\n>(\n  (args) => typeof args[0] === \"boolean\" || isEffect(args[0]),\n  <A1, E1, R1, A2, E2, R2, E = never, R = never>(\n    self: Effect.Effect<boolean, E, R> | boolean,\n    options: {\n      readonly onTrue: LazyArg<Effect.Effect<A1, E1, R1>>\n      readonly onFalse: LazyArg<Effect.Effect<A2, E2, R2>>\n    }\n  ): Effect.Effect<A1 | A2, E1 | E2 | E, R1 | R2 | R> =>\n    isEffect(self)\n      ? flatMap(self, (b): Effect.Effect<A1 | A2, E1 | E2, R1 | R2> => (b ? options.onTrue() : options.onFalse()))\n      : self\n      ? options.onTrue()\n      : options.onFalse()\n)\n\n/* @internal */\nexport const interrupt: Effect.Effect<never> = flatMap(fiberId, (fiberId) => interruptWith(fiberId))\n\n/* @internal */\nexport const interruptWith = (fiberId: FiberId.FiberId): Effect.Effect<never> =>\n  failCause(internalCause.interrupt(fiberId))\n\n/* @internal */\nexport const interruptible = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => {\n  const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS) as any\n  effect.effect_instruction_i0 = RuntimeFlagsPatch.enable(runtimeFlags_.Interruption)\n  effect.effect_instruction_i1 = () => self\n  return effect\n}\n\n/* @internal */\nexport const interruptibleMask = <A, E, R>(\n  f: (restore: <AX, EX, RX>(effect: Effect.Effect<AX, EX, RX>) => Effect.Effect<AX, EX, RX>) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> =>\n  custom(f, function() {\n    const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS) as any\n    effect.effect_instruction_i0 = RuntimeFlagsPatch.enable(runtimeFlags_.Interruption)\n    effect.effect_instruction_i1 = (oldFlags: RuntimeFlags.RuntimeFlags) =>\n      runtimeFlags_.interruption(oldFlags)\n        ? internalCall(() => this.effect_instruction_i0(interruptible))\n        : internalCall(() => this.effect_instruction_i0(uninterruptible))\n    return effect\n  })\n\n/* @internal */\nexport const intoDeferred: {\n  <A, E>(deferred: Deferred.Deferred<A, E>): <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<boolean, never, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, deferred: Deferred.Deferred<A, E>): Effect.Effect<boolean, never, R>\n} = dual(\n  2,\n  <A, E, R>(self: Effect.Effect<A, E, R>, deferred: Deferred.Deferred<A, E>): Effect.Effect<boolean, never, R> =>\n    uninterruptibleMask((restore) =>\n      flatMap(\n        exit(restore(self)),\n        (exit) => deferredDone(deferred, exit)\n      )\n    )\n)\n\n/* @internal */\nexport const map: {\n  <A, B>(f: (a: A) => B): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E, R>\n  <A, E, R, B>(self: Effect.Effect<A, E, R>, f: (a: A) => B): Effect.Effect<B, E, R>\n} = dual(\n  2,\n  <A, E, R, B>(self: Effect.Effect<A, E, R>, f: (a: A) => B): Effect.Effect<B, E, R> =>\n    flatMap(self, (a) => sync(() => f(a)))\n)\n\n/* @internal */\nexport const mapBoth: {\n  <E, E2, A, A2>(\n    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n  ): <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2, E2, R>\n  <A, E, R, E2, A2>(\n    self: Effect.Effect<A, E, R>,\n    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n  ): Effect.Effect<A2, E2, R>\n} = dual(2, <A, E, R, E2, A2>(\n  self: Effect.Effect<A, E, R>,\n  options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }\n): Effect.Effect<A2, E2, R> =>\n  matchEffect(self, {\n    onFailure: (e) => failSync(() => options.onFailure(e)),\n    onSuccess: (a) => sync(() => options.onSuccess(a))\n  }))\n\n/* @internal */\nexport const mapError: {\n  <E, E2>(f: (e: E) => E2): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E2, R>\n  <A, E, R, E2>(self: Effect.Effect<A, E, R>, f: (e: E) => E2): Effect.Effect<A, E2, R>\n} = dual(\n  2,\n  <A, E, R, E2>(self: Effect.Effect<A, E, R>, f: (e: E) => E2): Effect.Effect<A, E2, R> =>\n    matchCauseEffect(self, {\n      onFailure: (cause) => {\n        const either = internalCause.failureOrCause(cause)\n        switch (either._tag) {\n          case \"Left\": {\n            return failSync(() => f(either.left))\n          }\n          case \"Right\": {\n            return failCause(either.right)\n          }\n        }\n      },\n      onSuccess: succeed\n    })\n)\n\n/* @internal */\nexport const onError: {\n  <E, X, R2>(\n    cleanup: (cause: Cause.Cause<E>) => Effect.Effect<X, never, R2>\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R2 | R>\n  <A, E, R, X, R2>(\n    self: Effect.Effect<A, E, R>,\n    cleanup: (cause: Cause.Cause<E>) => Effect.Effect<X, never, R2>\n  ): Effect.Effect<A, E, R2 | R>\n} = dual(2, <A, E, R, X, R2>(\n  self: Effect.Effect<A, E, R>,\n  cleanup: (cause: Cause.Cause<E>) => Effect.Effect<X, never, R2>\n): Effect.Effect<A, E, R2 | R> =>\n  onExit(self, (exit) => exitIsSuccess(exit) ? void_ : cleanup(exit.effect_instruction_i0)))\n\n/* @internal */\nexport const onExit: {\n  <A, E, X, R2>(\n    cleanup: (exit: Exit.Exit<A, E>) => Effect.Effect<X, never, R2>\n  ): <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R2 | R>\n  <A, E, R, X, R2>(\n    self: Effect.Effect<A, E, R>,\n    cleanup: (exit: Exit.Exit<A, E>) => Effect.Effect<X, never, R2>\n  ): Effect.Effect<A, E, R2 | R>\n} = dual(2, <A, E, R, X, R2>(\n  self: Effect.Effect<A, E, R>,\n  cleanup: (exit: Exit.Exit<A, E>) => Effect.Effect<X, never, R2>\n): Effect.Effect<A, E, R2 | R> =>\n  uninterruptibleMask((restore) =>\n    matchCauseEffect(restore(self), {\n      onFailure: (cause1) => {\n        const result = exitFailCause(cause1)\n        return matchCauseEffect(cleanup(result), {\n          onFailure: (cause2) => exitFailCause(internalCause.sequential(cause1, cause2)),\n          onSuccess: () => result\n        })\n      },\n      onSuccess: (success) => {\n        const result = exitSucceed(success)\n        return zipRight(cleanup(result), result)\n      }\n    })\n  ))\n\n/* @internal */\nexport const onInterrupt: {\n  <X, R2>(\n    cleanup: (interruptors: HashSet.HashSet<FiberId.FiberId>) => Effect.Effect<X, never, R2>\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R2 | R>\n  <A, E, R, X, R2>(\n    self: Effect.Effect<A, E, R>,\n    cleanup: (interruptors: HashSet.HashSet<FiberId.FiberId>) => Effect.Effect<X, never, R2>\n  ): Effect.Effect<A, E, R2 | R>\n} = dual(2, <A, E, R, X, R2>(\n  self: Effect.Effect<A, E, R>,\n  cleanup: (interruptors: HashSet.HashSet<FiberId.FiberId>) => Effect.Effect<X, never, R2>\n): Effect.Effect<A, E, R2 | R> =>\n  onExit(\n    self,\n    exitMatch({\n      onFailure: (cause) =>\n        internalCause.isInterruptedOnly(cause)\n          ? asVoid(cleanup(internalCause.interruptors(cause)))\n          : void_,\n      onSuccess: () => void_\n    })\n  ))\n\n/* @internal */\nexport const orElse: {\n  <A2, E2, R2>(\n    that: LazyArg<Effect.Effect<A2, E2, R2>>\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A, E2, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: LazyArg<Effect.Effect<A2, E2, R2>>\n  ): Effect.Effect<A2 | A, E2, R2 | R>\n} = dual(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: LazyArg<Effect.Effect<A2, E2, R2>>\n  ): Effect.Effect<A2 | A, E2, R2 | R> => attemptOrElse(self, that, succeed)\n)\n\n/* @internal */\nexport const orDie = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, never, R> => orDieWith(self, identity)\n\n/* @internal */\nexport const orDieWith: {\n  <E>(f: (error: E) => unknown): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, never, R>\n  <A, E, R>(self: Effect.Effect<A, E, R>, f: (error: E) => unknown): Effect.Effect<A, never, R>\n} = dual(\n  2,\n  <A, E, R>(self: Effect.Effect<A, E, R>, f: (error: E) => unknown): Effect.Effect<A, never, R> =>\n    matchEffect(self, {\n      onFailure: (e) => die(f(e)),\n      onSuccess: succeed\n    })\n)\n\n/* @internal */\nexport const partitionMap: <A, A1, A2>(\n  elements: Iterable<A>,\n  f: (a: A) => Either.Either<A2, A1>\n) => [left: Array<A1>, right: Array<A2>] = Arr.partitionMap\n/* @internal */\nexport const runtimeFlags: Effect.Effect<RuntimeFlags.RuntimeFlags> = withFiberRuntime((_, status) =>\n  succeed(status.runtimeFlags)\n)\n\n/* @internal */\nexport const succeed = <A>(value: A): Effect.Effect<A> => {\n  const effect = new EffectPrimitiveSuccess(OpCodes.OP_SUCCESS) as any\n  effect.effect_instruction_i0 = value\n  return effect\n}\n\n/* @internal */\nexport const suspend = <A, E, R>(evaluate: LazyArg<Effect.Effect<A, E, R>>): Effect.Effect<A, E, R> => {\n  const effect = new EffectPrimitive(OpCodes.OP_COMMIT) as any\n  effect.commit = evaluate\n  return effect\n}\n\n/* @internal */\nexport const sync = <A>(thunk: LazyArg<A>): Effect.Effect<A> => {\n  const effect = new EffectPrimitive(OpCodes.OP_SYNC) as any\n  effect.effect_instruction_i0 = thunk\n  return effect\n}\n\n/* @internal */\nexport const tap = dual<\n  {\n    <A, X>(\n      f: (a: NoInfer<A>) => X\n    ): <E, R>(\n      self: Effect.Effect<A, E, R>\n    ) => [X] extends [Effect.Effect<infer _A1, infer E1, infer R1>] ? Effect.Effect<A, E | E1, R | R1>\n      : [X] extends [PromiseLike<infer _A1>] ? Effect.Effect<A, E | Cause.UnknownException, R>\n      : Effect.Effect<A, E, R>\n    <A, X, E1, R1>(\n      f: (a: NoInfer<A>) => Effect.Effect<X, E1, R1>,\n      options: { onlyEffect: true }\n    ): <E, R>(\n      self: Effect.Effect<A, E, R>\n    ) => Effect.Effect<A, E | E1, R | R1>\n    <X>(\n      f: NotFunction<X>\n    ): <A, E, R>(\n      self: Effect.Effect<A, E, R>\n    ) => [X] extends [Effect.Effect<infer _A1, infer E1, infer R1>] ? Effect.Effect<A, E | E1, R | R1>\n      : [X] extends [PromiseLike<infer _A1>] ? Effect.Effect<A, E | Cause.UnknownException, R>\n      : Effect.Effect<A, E, R>\n    <X, E1, R1>(\n      f: Effect.Effect<X, E1, R1>,\n      options: { onlyEffect: true }\n    ): <A, E, R>(\n      self: Effect.Effect<A, E, R>\n    ) => Effect.Effect<A, E | E1, R | R1>\n  },\n  {\n    <A, E, R, X>(\n      self: Effect.Effect<A, E, R>,\n      f: (a: NoInfer<A>) => X\n    ): [X] extends [Effect.Effect<infer _A1, infer E1, infer R1>] ? Effect.Effect<A, E | E1, R | R1>\n      : [X] extends [PromiseLike<infer _A1>] ? Effect.Effect<A, E | Cause.UnknownException, R>\n      : Effect.Effect<A, E, R>\n    <A, E, R, X, E1, R1>(\n      self: Effect.Effect<A, E, R>,\n      f: (a: NoInfer<A>) => Effect.Effect<X, E1, R1>,\n      options: { onlyEffect: true }\n    ): Effect.Effect<A, E | E1, R | R1>\n    <A, E, R, X>(\n      self: Effect.Effect<A, E, R>,\n      f: NotFunction<X>\n    ): [X] extends [Effect.Effect<infer _A1, infer E1, infer R1>] ? Effect.Effect<A, E | E1, R | R1>\n      : [X] extends [PromiseLike<infer _A1>] ? Effect.Effect<A, E | Cause.UnknownException, R>\n      : Effect.Effect<A, E, R>\n    <A, E, R, X, E1, R1>(\n      self: Effect.Effect<A, E, R>,\n      f: Effect.Effect<X, E1, R1>,\n      options: { onlyEffect: true }\n    ): Effect.Effect<A, E | E1, R | R1>\n  }\n>(\n  (args) => args.length === 3 || args.length === 2 && !(isObject(args[1]) && \"onlyEffect\" in args[1]),\n  <A, E, R, X>(self: Effect.Effect<A, E, R>, f: X) =>\n    flatMap(self, (a) => {\n      const b = typeof f === \"function\" ? (f as any)(a) : f\n      if (isEffect(b)) {\n        return as(b, a)\n      } else if (isPromiseLike(b)) {\n        return unsafeAsync<any, Cause.UnknownException>((resume) => {\n          b.then((_) => resume(succeed(a)), (e) =>\n            resume(fail(new UnknownException(e, \"An unknown error occurred in Effect.tap\"))))\n        })\n      }\n      return succeed(a)\n    })\n)\n\n/* @internal */\nexport const transplant = <A, E, R>(\n  f: (grafter: <A2, E2, R2>(effect: Effect.Effect<A2, E2, R2>) => Effect.Effect<A2, E2, R2>) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> =>\n  withFiberRuntime<A, E, R>((state) => {\n    const scopeOverride = state.getFiberRef(currentForkScopeOverride)\n    const scope = pipe(scopeOverride, Option.getOrElse(() => state.scope()))\n    return f(fiberRefLocally(currentForkScopeOverride, Option.some(scope)))\n  })\n\n/* @internal */\nexport const attemptOrElse: {\n  <A2, E2, R2, A, A3, E3, R3>(\n    that: LazyArg<Effect.Effect<A2, E2, R2>>,\n    onSuccess: (a: A) => Effect.Effect<A3, E3, R3>\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A3, E2 | E3, R | R2 | R3>\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Effect.Effect<A, E, R>,\n    that: LazyArg<Effect.Effect<A2, E2, R2>>,\n    onSuccess: (a: A) => Effect.Effect<A3, E3, R3>\n  ): Effect.Effect<A2 | A3, E2 | E3, R | R2 | R3>\n} = dual(3, <A, E, R, A2, E2, R2, A3, E3, R3>(\n  self: Effect.Effect<A, E, R>,\n  that: LazyArg<Effect.Effect<A2, E2, R2>>,\n  onSuccess: (a: A) => Effect.Effect<A3, E3, R3>\n): Effect.Effect<A2 | A3, E2 | E3, R | R2 | R3> =>\n  matchCauseEffect(self, {\n    onFailure: (cause) => {\n      const defects = internalCause.defects(cause)\n      if (defects.length > 0) {\n        return failCause(Option.getOrThrow(internalCause.keepDefectsAndElectFailures(cause)))\n      }\n      return that()\n    },\n    onSuccess\n  }))\n\n/* @internal */\nexport const uninterruptible: <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => {\n  const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS) as any\n  effect.effect_instruction_i0 = RuntimeFlagsPatch.disable(runtimeFlags_.Interruption)\n  effect.effect_instruction_i1 = () => self\n  return effect\n}\n\n/* @internal */\nexport const uninterruptibleMask = <A, E, R>(\n  f: (restore: <AX, EX, RX>(effect: Effect.Effect<AX, EX, RX>) => Effect.Effect<AX, EX, RX>) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> =>\n  custom(f, function() {\n    const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS) as any\n    effect.effect_instruction_i0 = RuntimeFlagsPatch.disable(runtimeFlags_.Interruption)\n    effect.effect_instruction_i1 = (oldFlags: RuntimeFlags.RuntimeFlags) =>\n      runtimeFlags_.interruption(oldFlags)\n        ? internalCall(() => this.effect_instruction_i0(interruptible))\n        : internalCall(() => this.effect_instruction_i0(uninterruptible))\n    return effect\n  })\n\nconst void_: Effect.Effect<void> = succeed(void 0)\nexport {\n  /* @internal */\n  void_ as void\n}\n\n/* @internal */\nexport const updateRuntimeFlags = (patch: RuntimeFlagsPatch.RuntimeFlagsPatch): Effect.Effect<void> => {\n  const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS) as any\n  effect.effect_instruction_i0 = patch\n  effect.effect_instruction_i1 = void 0\n  return effect\n}\n\n/* @internal */\nexport const whenEffect: {\n  <E, R>(\n    condition: Effect.Effect<boolean, E, R>\n  ): <A, E2, R2>(\n    effect: Effect.Effect<A, E2, R2>\n  ) => Effect.Effect<Option.Option<A>, E | E2, R | R2>\n  <A, E2, R2, E, R>(\n    self: Effect.Effect<A, E2, R2>,\n    condition: Effect.Effect<boolean, E, R>\n  ): Effect.Effect<Option.Option<A>, E | E2, R | R2>\n} = dual(2, <A, E2, R2, E, R>(\n  self: Effect.Effect<A, E2, R2>,\n  condition: Effect.Effect<boolean, E, R>\n): Effect.Effect<Option.Option<A>, E | E2, R | R2> =>\n  flatMap(condition, (b) => {\n    if (b) {\n      return pipe(self, map(Option.some))\n    }\n    return succeed(Option.none())\n  }))\n\n/* @internal */\nexport const whileLoop = <A, E, R>(\n  options: {\n    readonly while: LazyArg<boolean>\n    readonly body: LazyArg<Effect.Effect<A, E, R>>\n    readonly step: (a: A) => void\n  }\n): Effect.Effect<void, E, R> => {\n  const effect = new EffectPrimitive(OpCodes.OP_WHILE) as any\n  effect.effect_instruction_i0 = options.while\n  effect.effect_instruction_i1 = options.body\n  effect.effect_instruction_i2 = options.step\n  return effect\n}\n\n/* @internal */\nexport const fromIterator = <Eff extends YieldWrap<Effect.Effect<any, any, any>>, AEff>(\n  iterator: LazyArg<Iterator<Eff, AEff, never>>\n): Effect.Effect<\n  AEff,\n  [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect.Effect<infer _A, infer E, infer _R>>] ? E : never,\n  [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect.Effect<infer _A, infer _E, infer R>>] ? R : never\n> =>\n  suspend(() => {\n    const effect = new EffectPrimitive(OpCodes.OP_ITERATOR) as any\n    effect.effect_instruction_i0 = iterator()\n    return effect\n  })\n\n/* @internal */\nexport const gen: typeof Effect.gen = function() {\n  const f = arguments.length === 1 ? arguments[0] : arguments[1].bind(arguments[0])\n  return fromIterator(() => f(pipe))\n}\n\n/** @internal */\nexport const fnUntraced: Effect.fn.Untraced = (body: Function, ...pipeables: Array<any>) =>\n  Object.defineProperty(\n    pipeables.length === 0\n      ? function(this: any, ...args: Array<any>) {\n        return fromIterator(() => body.apply(this, args))\n      }\n      : function(this: any, ...args: Array<any>) {\n        let effect = fromIterator(() => body.apply(this, args))\n        for (const x of pipeables) {\n          effect = x(effect, ...args)\n        }\n        return effect\n      },\n    \"length\",\n    { value: body.length, configurable: true }\n  )\n\n/* @internal */\nexport const withConcurrency = dual<\n  (concurrency: number | \"unbounded\") => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, concurrency: number | \"unbounded\") => Effect.Effect<A, E, R>\n>(2, (self, concurrency) => fiberRefLocally(self, currentConcurrency, concurrency))\n\n/* @internal */\nexport const withRequestBatching = dual<\n  (requestBatching: boolean) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, requestBatching: boolean) => Effect.Effect<A, E, R>\n>(2, (self, requestBatching) => fiberRefLocally(self, currentRequestBatching, requestBatching))\n\n/* @internal */\nexport const withRuntimeFlags = dual<\n  (update: RuntimeFlagsPatch.RuntimeFlagsPatch) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, update: RuntimeFlagsPatch.RuntimeFlagsPatch) => Effect.Effect<A, E, R>\n>(2, (self, update) => {\n  const effect = new EffectPrimitive(OpCodes.OP_UPDATE_RUNTIME_FLAGS) as any\n  effect.effect_instruction_i0 = update\n  effect.effect_instruction_i1 = () => self\n  return effect\n})\n\n/** @internal */\nexport const withTracerEnabled = dual<\n  (enabled: boolean) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, enabled: boolean) => Effect.Effect<A, E, R>\n>(2, (effect, enabled) =>\n  fiberRefLocally(\n    effect,\n    currentTracerEnabled,\n    enabled\n  ))\n\n/** @internal */\nexport const withTracerTiming = dual<\n  (enabled: boolean) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, enabled: boolean) => Effect.Effect<A, E, R>\n>(2, (effect, enabled) =>\n  fiberRefLocally(\n    effect,\n    currentTracerTimingEnabled,\n    enabled\n  ))\n\n/* @internal */\nexport const yieldNow = (options?: {\n  readonly priority?: number | undefined\n}): Effect.Effect<void> => {\n  const effect = new EffectPrimitive(OpCodes.OP_YIELD) as any\n  return typeof options?.priority !== \"undefined\" ?\n    withSchedulingPriority(effect, options.priority) :\n    effect\n}\n\n/* @internal */\nexport const zip = dual<\n  <A2, E2, R2>(\n    that: Effect.Effect<A2, E2, R2>\n  ) => <A, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<[A, A2], E | E2, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>\n  ) => Effect.Effect<[A, A2], E | E2, R | R2>\n>(2, <A, E, R, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  that: Effect.Effect<A2, E2, R2>\n): Effect.Effect<[A, A2], E | E2, R | R2> => flatMap(self, (a) => map(that, (b) => [a, b])))\n\n/* @internal */\nexport const zipFlatten: {\n  <A2, E2, R2>(\n    that: Effect.Effect<A2, E2, R2>\n  ): <A extends ReadonlyArray<any>, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<[...A, A2], E | E2, R | R2>\n  <A extends ReadonlyArray<any>, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>\n  ): Effect.Effect<[...A, A2], E | E2, R | R2>\n} = dual(2, <A extends ReadonlyArray<any>, E, R, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  that: Effect.Effect<A2, E2, R2>\n): Effect.Effect<[...A, A2], E | E2, R | R2> => flatMap(self, (a) => map(that, (b) => [...a, b])))\n\n/* @internal */\nexport const zipLeft: {\n  <A2, E2, R2>(\n    that: Effect.Effect<A2, E2, R2>\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E2, R | R2>\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>\n  ): Effect.Effect<A, E | E2, R | R2>\n} = dual(2, <A, E, R, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  that: Effect.Effect<A2, E2, R2>\n): Effect.Effect<A, E | E2, R | R2> => flatMap(self, (a) => as(that, a)))\n\n/* @internal */\nexport const zipRight: {\n  <A2, E2, R2>(\n    that: Effect.Effect<A2, E2, R2>\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2, E | E2, R | R2>\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>\n  ): Effect.Effect<A2, E | E2, R | R2>\n} = dual(2, <A, E, R, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  that: Effect.Effect<A2, E2, R2>\n): Effect.Effect<A2, E | E2, R | R2> => flatMap(self, () => that))\n\n/* @internal */\nexport const zipWith: {\n  <A2, E2, R2, A, B>(\n    that: Effect.Effect<A2, E2, R2>,\n    f: (a: A, b: A2) => B\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E | E2, R | R2>\n  <A, E, R, A2, E2, R2, B>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>,\n    f: (a: A, b: A2) => B\n  ): Effect.Effect<B, E | E2, R | R2>\n} = dual(3, <A, E, R, A2, E2, R2, B>(\n  self: Effect.Effect<A, E, R>,\n  that: Effect.Effect<A2, E2, R2>,\n  f: (a: A, b: A2) => B\n): Effect.Effect<B, E | E2, R | R2> => flatMap(self, (a) => map(that, (b) => f(a, b))))\n\n/* @internal */\nexport const never: Effect.Effect<never> = asyncInterrupt<never>(() => {\n  const interval = setInterval(() => {\n    //\n  }, 2 ** 31 - 1)\n  return sync(() => clearInterval(interval))\n})\n\n// -----------------------------------------------------------------------------\n// Fiber\n// -----------------------------------------------------------------------------\n\n/* @internal */\nexport const interruptFiber = <A, E>(self: Fiber.Fiber<A, E>): Effect.Effect<Exit.Exit<A, E>> =>\n  flatMap(fiberId, (fiberId) => pipe(self, interruptAsFiber(fiberId)))\n\n/* @internal */\nexport const interruptAsFiber = dual<\n  (fiberId: FiberId.FiberId) => <A, E>(self: Fiber.Fiber<A, E>) => Effect.Effect<Exit.Exit<A, E>>,\n  <A, E>(self: Fiber.Fiber<A, E>, fiberId: FiberId.FiberId) => Effect.Effect<Exit.Exit<A, E>>\n>(2, (self, fiberId) => flatMap(self.interruptAsFork(fiberId), () => self.await))\n\n// -----------------------------------------------------------------------------\n// LogLevel\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const logLevelAll: LogLevel.LogLevel = {\n  _tag: \"All\",\n  syslog: 0,\n  label: \"ALL\",\n  ordinal: Number.MIN_SAFE_INTEGER,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const logLevelFatal: LogLevel.LogLevel = {\n  _tag: \"Fatal\",\n  syslog: 2,\n  label: \"FATAL\",\n  ordinal: 50000,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const logLevelError: LogLevel.LogLevel = {\n  _tag: \"Error\",\n  syslog: 3,\n  label: \"ERROR\",\n  ordinal: 40000,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const logLevelWarning: LogLevel.LogLevel = {\n  _tag: \"Warning\",\n  syslog: 4,\n  label: \"WARN\",\n  ordinal: 30000,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const logLevelInfo: LogLevel.LogLevel = {\n  _tag: \"Info\",\n  syslog: 6,\n  label: \"INFO\",\n  ordinal: 20000,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const logLevelDebug: LogLevel.LogLevel = {\n  _tag: \"Debug\",\n  syslog: 7,\n  label: \"DEBUG\",\n  ordinal: 10000,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const logLevelTrace: LogLevel.LogLevel = {\n  _tag: \"Trace\",\n  syslog: 7,\n  label: \"TRACE\",\n  ordinal: 0,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const logLevelNone: LogLevel.LogLevel = {\n  _tag: \"None\",\n  syslog: 7,\n  label: \"OFF\",\n  ordinal: Number.MAX_SAFE_INTEGER,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const allLogLevels: ReadonlyArray<LogLevel.LogLevel> = [\n  logLevelAll,\n  logLevelTrace,\n  logLevelDebug,\n  logLevelInfo,\n  logLevelWarning,\n  logLevelError,\n  logLevelFatal,\n  logLevelNone\n]\n\n// -----------------------------------------------------------------------------\n// FiberRef\n// -----------------------------------------------------------------------------\n\n/** @internal */\nconst FiberRefSymbolKey = \"effect/FiberRef\"\n\n/** @internal */\nexport const FiberRefTypeId: FiberRef.FiberRefTypeId = Symbol.for(\n  FiberRefSymbolKey\n) as FiberRef.FiberRefTypeId\n\nconst fiberRefVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/* @internal */\nexport const fiberRefGet = <A>(self: FiberRef.FiberRef<A>): Effect.Effect<A> =>\n  withFiberRuntime((fiber) => exitSucceed(fiber.getFiberRef(self)))\n\n/* @internal */\nexport const fiberRefGetAndSet = dual<\n  <A>(value: A) => (self: FiberRef.FiberRef<A>) => Effect.Effect<A>,\n  <A>(self: FiberRef.FiberRef<A>, value: A) => Effect.Effect<A>\n>(2, (self, value) => fiberRefModify(self, (v) => [v, value] as const))\n\n/* @internal */\nexport const fiberRefGetAndUpdate = dual<\n  <A>(f: (a: A) => A) => (self: FiberRef.FiberRef<A>) => Effect.Effect<A>,\n  <A>(self: FiberRef.FiberRef<A>, f: (a: A) => A) => Effect.Effect<A>\n>(2, (self, f) => fiberRefModify(self, (v) => [v, f(v)] as const))\n\n/* @internal */\nexport const fiberRefGetAndUpdateSome = dual<\n  <A>(\n    pf: (a: A) => Option.Option<A>\n  ) => (self: FiberRef.FiberRef<A>) => Effect.Effect<A>,\n  <A>(\n    self: FiberRef.FiberRef<A>,\n    pf: (a: A) => Option.Option<A>\n  ) => Effect.Effect<A>\n>(2, (self, pf) => fiberRefModify(self, (v) => [v, Option.getOrElse(pf(v), () => v)] as const))\n\n/* @internal */\nexport const fiberRefGetWith = dual<\n  <B, E, R, A>(f: (a: A) => Effect.Effect<B, E, R>) => (self: FiberRef.FiberRef<A>) => Effect.Effect<B, E, R>,\n  <A, B, E, R>(self: FiberRef.FiberRef<A>, f: (a: A) => Effect.Effect<B, E, R>) => Effect.Effect<B, E, R>\n>(2, (self, f) => flatMap(fiberRefGet(self), f))\n\n/* @internal */\nexport const fiberRefSet = dual<\n  <A>(value: A) => (self: FiberRef.FiberRef<A>) => Effect.Effect<void>,\n  <A>(self: FiberRef.FiberRef<A>, value: A) => Effect.Effect<void>\n>(2, (self, value) => fiberRefModify(self, () => [void 0, value] as const))\n\n/* @internal */\nexport const fiberRefDelete = <A>(self: FiberRef.FiberRef<A>): Effect.Effect<void> =>\n  withFiberRuntime((state) => {\n    state.unsafeDeleteFiberRef(self)\n    return void_\n  })\n\n/* @internal */\nexport const fiberRefReset = <A>(self: FiberRef.FiberRef<A>): Effect.Effect<void> => fiberRefSet(self, self.initial)\n\n/* @internal */\nexport const fiberRefModify = dual<\n  <A, B>(f: (a: A) => readonly [B, A]) => (self: FiberRef.FiberRef<A>) => Effect.Effect<B>,\n  <A, B>(self: FiberRef.FiberRef<A>, f: (a: A) => readonly [B, A]) => Effect.Effect<B>\n>(2, <A, B>(\n  self: FiberRef.FiberRef<A>,\n  f: (a: A) => readonly [B, A]\n): Effect.Effect<B> =>\n  withFiberRuntime((state) => {\n    const [b, a] = f(state.getFiberRef(self) as A)\n    state.setFiberRef(self, a)\n    return succeed(b)\n  }))\n\n/* @internal */\nexport const fiberRefModifySome = <A, B>(\n  self: FiberRef.FiberRef<A>,\n  def: B,\n  f: (a: A) => Option.Option<readonly [B, A]>\n): Effect.Effect<B> => fiberRefModify(self, (v) => Option.getOrElse(f(v), () => [def, v] as const))\n\n/* @internal */\nexport const fiberRefUpdate = dual<\n  <A>(f: (a: A) => A) => (self: FiberRef.FiberRef<A>) => Effect.Effect<void>,\n  <A>(self: FiberRef.FiberRef<A>, f: (a: A) => A) => Effect.Effect<void>\n>(2, (self, f) => fiberRefModify(self, (v) => [void 0, f(v)] as const))\n\n/* @internal */\nexport const fiberRefUpdateSome = dual<\n  <A>(pf: (a: A) => Option.Option<A>) => (self: FiberRef.FiberRef<A>) => Effect.Effect<void>,\n  <A>(self: FiberRef.FiberRef<A>, pf: (a: A) => Option.Option<A>) => Effect.Effect<void>\n>(2, (self, pf) => fiberRefModify(self, (v) => [void 0, Option.getOrElse(pf(v), () => v)] as const))\n\n/* @internal */\nexport const fiberRefUpdateAndGet = dual<\n  <A>(f: (a: A) => A) => (self: FiberRef.FiberRef<A>) => Effect.Effect<A>,\n  <A>(self: FiberRef.FiberRef<A>, f: (a: A) => A) => Effect.Effect<A>\n>(2, (self, f) =>\n  fiberRefModify(self, (v) => {\n    const result = f(v)\n    return [result, result] as const\n  }))\n\n/* @internal */\nexport const fiberRefUpdateSomeAndGet = dual<\n  <A>(pf: (a: A) => Option.Option<A>) => (self: FiberRef.FiberRef<A>) => Effect.Effect<A>,\n  <A>(self: FiberRef.FiberRef<A>, pf: (a: A) => Option.Option<A>) => Effect.Effect<A>\n>(2, (self, pf) =>\n  fiberRefModify(self, (v) => {\n    const result = Option.getOrElse(pf(v), () => v)\n    return [result, result] as const\n  }))\n\n// circular\n/** @internal */\nconst RequestResolverSymbolKey = \"effect/RequestResolver\"\n\n/** @internal */\nexport const RequestResolverTypeId: RequestResolver.RequestResolverTypeId = Symbol.for(\n  RequestResolverSymbolKey\n) as RequestResolver.RequestResolverTypeId\n\nconst requestResolverVariance = {\n  /* c8 ignore next */\n  _A: (_: unknown) => _,\n  /* c8 ignore next */\n  _R: (_: never) => _\n}\n\n/** @internal */\nexport class RequestResolverImpl<in A, out R> implements RequestResolver.RequestResolver<A, R> {\n  readonly [RequestResolverTypeId] = requestResolverVariance\n  constructor(\n    readonly runAll: (\n      requests: Array<Array<Request.Entry<A>>>\n    ) => Effect.Effect<void, never, R>,\n    readonly target?: unknown\n  ) {\n  }\n  [Hash.symbol](): number {\n    return Hash.cached(this, this.target ? Hash.hash(this.target) : Hash.random(this))\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return this.target ?\n      isRequestResolver(that) && Equal.equals(this.target, (that as RequestResolverImpl<any, any>).target) :\n      this === that\n  }\n  identified(...ids: Array<unknown>): RequestResolver.RequestResolver<A, R> {\n    return new RequestResolverImpl(this.runAll, Chunk.fromIterable(ids))\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const isRequestResolver = (u: unknown): u is RequestResolver.RequestResolver<unknown, unknown> =>\n  hasProperty(u, RequestResolverTypeId)\n\n// end\n\n/** @internal */\nexport const resolverLocally = dual<\n  <A>(\n    self: FiberRef.FiberRef<A>,\n    value: A\n  ) => <R, B extends Request.Request<any, any>>(\n    use: RequestResolver.RequestResolver<B, R>\n  ) => RequestResolver.RequestResolver<B, R>,\n  <R, B extends Request.Request<any, any>, A>(\n    use: RequestResolver.RequestResolver<B, R>,\n    self: FiberRef.FiberRef<A>,\n    value: A\n  ) => RequestResolver.RequestResolver<B, R>\n>(3, <R, B extends Request.Request<any, any>, A>(\n  use: RequestResolver.RequestResolver<B, R>,\n  self: FiberRef.FiberRef<A>,\n  value: A\n): RequestResolver.RequestResolver<B, R> =>\n  new RequestResolverImpl<B, R>(\n    (requests) =>\n      fiberRefLocally(\n        use.runAll(requests),\n        self,\n        value\n      ),\n    Chunk.make(\"Locally\", use, self, value)\n  ))\n\n/** @internal */\nexport const requestBlockLocally = <A>(\n  self: BlockedRequests.RequestBlock,\n  ref: FiberRef.FiberRef<A>,\n  value: A\n): BlockedRequests.RequestBlock => blockedRequests_.reduce(self, LocallyReducer(ref, value))\n\nconst LocallyReducer = <A>(\n  ref: FiberRef.FiberRef<A>,\n  value: A\n): BlockedRequests.RequestBlock.Reducer<BlockedRequests.RequestBlock> => ({\n  emptyCase: () => blockedRequests_.empty,\n  parCase: (left, right) => blockedRequests_.par(left, right),\n  seqCase: (left, right) => blockedRequests_.seq(left, right),\n  singleCase: (dataSource, blockedRequest) =>\n    blockedRequests_.single(\n      resolverLocally(dataSource, ref, value),\n      blockedRequest as any\n    )\n})\n\n/* @internal */\nexport const fiberRefLocally: {\n  <A>(self: FiberRef.FiberRef<A>, value: A): <B, E, R>(use: Effect.Effect<B, E, R>) => Effect.Effect<B, E, R>\n  <B, E, R, A>(use: Effect.Effect<B, E, R>, self: FiberRef.FiberRef<A>, value: A): Effect.Effect<B, E, R>\n} = dual(\n  3,\n  <B, E, R, A>(use: Effect.Effect<B, E, R>, self: FiberRef.FiberRef<A>, value: A): Effect.Effect<B, E, R> =>\n    acquireUseRelease(\n      zipLeft(fiberRefGet(self), fiberRefSet(self, value)),\n      () => use,\n      (oldValue) => fiberRefSet(self, oldValue)\n    )\n)\n\n/* @internal */\nexport const fiberRefLocallyWith = dual<\n  <A>(self: FiberRef.FiberRef<A>, f: (a: A) => A) => <B, E, R>(use: Effect.Effect<B, E, R>) => Effect.Effect<B, E, R>,\n  <B, E, R, A>(use: Effect.Effect<B, E, R>, self: FiberRef.FiberRef<A>, f: (a: A) => A) => Effect.Effect<B, E, R>\n>(3, (use, self, f) => fiberRefGetWith(self, (a) => fiberRefLocally(use, self, f(a))))\n\n/** @internal */\nexport const fiberRefUnsafeMake = <Value>(\n  initial: Value,\n  options?: {\n    readonly fork?: ((a: Value) => Value) | undefined\n    readonly join?: ((left: Value, right: Value) => Value) | undefined\n  }\n): FiberRef.FiberRef<Value> =>\n  fiberRefUnsafeMakePatch(initial, {\n    differ: internalDiffer.update(),\n    fork: options?.fork ?? identity,\n    join: options?.join\n  })\n\n/** @internal */\nexport const fiberRefUnsafeMakeHashSet = <A>(\n  initial: HashSet.HashSet<A>\n): FiberRef.FiberRef<HashSet.HashSet<A>> => {\n  const differ = internalDiffer.hashSet<A>()\n  return fiberRefUnsafeMakePatch(initial, {\n    differ,\n    fork: differ.empty\n  })\n}\n\n/** @internal */\nexport const fiberRefUnsafeMakeReadonlyArray = <A>(\n  initial: ReadonlyArray<A>\n): FiberRef.FiberRef<ReadonlyArray<A>> => {\n  const differ = internalDiffer.readonlyArray(internalDiffer.update<A>())\n  return fiberRefUnsafeMakePatch(initial, {\n    differ,\n    fork: differ.empty\n  })\n}\n\n/** @internal */\nexport const fiberRefUnsafeMakeContext = <A>(\n  initial: Context.Context<A>\n): FiberRef.FiberRef<Context.Context<A>> => {\n  const differ = internalDiffer.environment<A>()\n  return fiberRefUnsafeMakePatch(initial, {\n    differ,\n    fork: differ.empty\n  })\n}\n\n/** @internal */\nexport const fiberRefUnsafeMakePatch = <Value, Patch>(\n  initial: Value,\n  options: {\n    readonly differ: Differ.Differ<Value, Patch>\n    readonly fork: Patch\n    readonly join?: ((oldV: Value, newV: Value) => Value) | undefined\n  }\n): FiberRef.FiberRef<Value> => {\n  const _fiberRef = {\n    ...CommitPrototype,\n    [FiberRefTypeId]: fiberRefVariance,\n    initial,\n    commit() {\n      return fiberRefGet(this)\n    },\n    diff: (oldValue: Value, newValue: Value) => options.differ.diff(oldValue, newValue),\n    combine: (first: Patch, second: Patch) => options.differ.combine(first, second),\n    patch: (patch: Patch) => (oldValue: Value) => options.differ.patch(patch, oldValue),\n    fork: options.fork,\n    join: options.join ?? ((_, n) => n)\n  }\n  return _fiberRef\n}\n\n/** @internal */\nexport const fiberRefUnsafeMakeRuntimeFlags = (\n  initial: RuntimeFlags.RuntimeFlags\n): FiberRef.FiberRef<RuntimeFlags.RuntimeFlags> =>\n  fiberRefUnsafeMakePatch(initial, {\n    differ: runtimeFlags_.differ,\n    fork: runtimeFlags_.differ.empty\n  })\n\n/** @internal */\nexport const currentContext: FiberRef.FiberRef<Context.Context<never>> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentContext\"),\n  () => fiberRefUnsafeMakeContext(Context.empty())\n)\n\n/** @internal */\nexport const currentSchedulingPriority: FiberRef.FiberRef<number> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentSchedulingPriority\"),\n  () => fiberRefUnsafeMake(0)\n)\n\n/** @internal */\nexport const currentMaxOpsBeforeYield: FiberRef.FiberRef<number> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentMaxOpsBeforeYield\"),\n  () => fiberRefUnsafeMake(2048)\n)\n\n/** @internal */\nexport const currentLogAnnotations: FiberRef.FiberRef<HashMap.HashMap<string, unknown>> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentLogAnnotation\"),\n  () => fiberRefUnsafeMake(HashMap.empty())\n)\n\n/** @internal */\nexport const currentLogLevel: FiberRef.FiberRef<LogLevel.LogLevel> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentLogLevel\"),\n  () => fiberRefUnsafeMake<LogLevel.LogLevel>(logLevelInfo)\n)\n\n/** @internal */\nexport const currentLogSpan: FiberRef.FiberRef<List.List<LogSpan.LogSpan>> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentLogSpan\"),\n  () => fiberRefUnsafeMake(List.empty<LogSpan.LogSpan>())\n)\n\n/** @internal */\nexport const withSchedulingPriority = dual<\n  (priority: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, priority: number) => Effect.Effect<A, E, R>\n>(2, (self, scheduler) => fiberRefLocally(self, currentSchedulingPriority, scheduler))\n\n/** @internal */\nexport const withMaxOpsBeforeYield = dual<\n  (priority: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, priority: number) => Effect.Effect<A, E, R>\n>(2, (self, scheduler) => fiberRefLocally(self, currentMaxOpsBeforeYield, scheduler))\n\n/** @internal */\nexport const currentConcurrency: FiberRef.FiberRef<\"unbounded\" | number> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentConcurrency\"),\n  () => fiberRefUnsafeMake<\"unbounded\" | number>(\"unbounded\")\n)\n\n/**\n * @internal\n */\nexport const currentRequestBatching = globalValue(\n  Symbol.for(\"effect/FiberRef/currentRequestBatching\"),\n  () => fiberRefUnsafeMake(true)\n)\n\n/** @internal */\nexport const currentUnhandledErrorLogLevel: FiberRef.FiberRef<Option.Option<LogLevel.LogLevel>> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentUnhandledErrorLogLevel\"),\n  () => fiberRefUnsafeMake(Option.some<LogLevel.LogLevel>(logLevelDebug))\n)\n\n/** @internal */\nexport const currentVersionMismatchErrorLogLevel: FiberRef.FiberRef<Option.Option<LogLevel.LogLevel>> = globalValue(\n  Symbol.for(\"effect/FiberRef/versionMismatchErrorLogLevel\"),\n  () => fiberRefUnsafeMake(Option.some<LogLevel.LogLevel>(logLevelWarning))\n)\n\n/** @internal */\nexport const withUnhandledErrorLogLevel = dual<\n  (level: Option.Option<LogLevel.LogLevel>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, level: Option.Option<LogLevel.LogLevel>) => Effect.Effect<A, E, R>\n>(2, (self, level) => fiberRefLocally(self, currentUnhandledErrorLogLevel, level))\n\n/** @internal */\nexport const currentMetricLabels: FiberRef.FiberRef<ReadonlyArray<MetricLabel.MetricLabel>> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentMetricLabels\"),\n  () => fiberRefUnsafeMakeReadonlyArray(Arr.empty())\n)\n\n/* @internal */\nexport const metricLabels: Effect.Effect<ReadonlyArray<MetricLabel.MetricLabel>> = fiberRefGet(\n  currentMetricLabels\n)\n\n/** @internal */\nexport const currentForkScopeOverride: FiberRef.FiberRef<Option.Option<fiberScope.FiberScope>> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentForkScopeOverride\"),\n  () =>\n    fiberRefUnsafeMake(Option.none(), {\n      fork: () => Option.none() as Option.Option<fiberScope.FiberScope>,\n      join: (parent, _) => parent\n    })\n)\n\n/** @internal */\nexport const currentInterruptedCause: FiberRef.FiberRef<Cause.Cause<never>> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentInterruptedCause\"),\n  () =>\n    fiberRefUnsafeMake(internalCause.empty, {\n      fork: () => internalCause.empty,\n      join: (parent, _) => parent\n    })\n)\n\n/** @internal */\nexport const currentTracerEnabled: FiberRef.FiberRef<boolean> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentTracerEnabled\"),\n  () => fiberRefUnsafeMake(true)\n)\n\n/** @internal */\nexport const currentTracerTimingEnabled: FiberRef.FiberRef<boolean> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentTracerTiming\"),\n  () => fiberRefUnsafeMake(true)\n)\n\n/** @internal */\nexport const currentTracerSpanAnnotations: FiberRef.FiberRef<HashMap.HashMap<string, unknown>> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentTracerSpanAnnotations\"),\n  () => fiberRefUnsafeMake(HashMap.empty())\n)\n\n/** @internal */\nexport const currentTracerSpanLinks: FiberRef.FiberRef<Chunk.Chunk<Tracer.SpanLink>> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentTracerSpanLinks\"),\n  () => fiberRefUnsafeMake(Chunk.empty())\n)\n\n// -----------------------------------------------------------------------------\n// Scope\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const ScopeTypeId: Scope.ScopeTypeId = Symbol.for(\"effect/Scope\") as Scope.ScopeTypeId\n\n/** @internal */\nexport const CloseableScopeTypeId: Scope.CloseableScopeTypeId = Symbol.for(\n  \"effect/CloseableScope\"\n) as Scope.CloseableScopeTypeId\n\n/* @internal */\nexport const scopeAddFinalizer = (\n  self: Scope.Scope,\n  finalizer: Effect.Effect<unknown>\n): Effect.Effect<void> => self.addFinalizer(() => asVoid(finalizer))\n\n/* @internal */\nexport const scopeAddFinalizerExit = (\n  self: Scope.Scope,\n  finalizer: Scope.Scope.Finalizer\n): Effect.Effect<void> => self.addFinalizer(finalizer)\n\n/* @internal */\nexport const scopeClose = (\n  self: Scope.Scope.Closeable,\n  exit: Exit.Exit<unknown, unknown>\n): Effect.Effect<void> => self.close(exit)\n\n/* @internal */\nexport const scopeFork = (\n  self: Scope.Scope,\n  strategy: ExecutionStrategy.ExecutionStrategy\n): Effect.Effect<Scope.Scope.Closeable> => self.fork(strategy)\n\n// -----------------------------------------------------------------------------\n// Cause\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const causeSquash = <E>(self: Cause.Cause<E>): unknown => {\n  return causeSquashWith(identity)(self)\n}\n\n/** @internal */\nexport const causeSquashWith = dual<\n  <E>(f: (error: E) => unknown) => (self: Cause.Cause<E>) => unknown,\n  <E>(self: Cause.Cause<E>, f: (error: E) => unknown) => unknown\n>(2, (self, f) => {\n  const option = pipe(self, internalCause.failureOption, Option.map(f))\n  switch (option._tag) {\n    case \"None\": {\n      return pipe(\n        internalCause.defects(self),\n        Chunk.head,\n        Option.match({\n          onNone: () => {\n            const interrupts = Arr.fromIterable(internalCause.interruptors(self)).flatMap((fiberId) =>\n              Arr.fromIterable(FiberId.ids(fiberId)).map((id) => `#${id}`)\n            )\n            return new InterruptedException(interrupts ? `Interrupted by fibers: ${interrupts.join(\", \")}` : void 0)\n          },\n          onSome: identity\n        })\n      )\n    }\n    case \"Some\": {\n      return option.value\n    }\n  }\n})\n\n// -----------------------------------------------------------------------------\n// Errors\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const YieldableError: new(message?: string, options?: ErrorOptions) => Cause.YieldableError = (function() {\n  class YieldableError extends globalThis.Error {\n    commit() {\n      return fail(this)\n    }\n    toJSON() {\n      const obj = { ...this }\n      if (this.message) obj.message = this.message\n      if (this.cause) obj.cause = this.cause\n      return obj\n    }\n    [NodeInspectSymbol]() {\n      if (this.toString !== globalThis.Error.prototype.toString) {\n        return this.stack ? `${this.toString()}\\n${this.stack.split(\"\\n\").slice(1).join(\"\\n\")}` : this.toString()\n      } else if (\"Bun\" in globalThis) {\n        return internalCause.pretty(internalCause.fail(this), { renderErrorCause: true })\n      }\n      return this\n    }\n  }\n  // @effect-diagnostics-next-line floatingEffect:off\n  Object.assign(YieldableError.prototype, StructuralCommitPrototype)\n  return YieldableError as any\n})()\n\nconst makeException = <T extends { _tag: string; message?: string }>(\n  proto: Omit<T, keyof Cause.YieldableError | \"_tag\">,\n  tag: T[\"_tag\"]\n): new(message?: string | undefined) => T => {\n  class Base extends YieldableError {\n    readonly _tag = tag\n  }\n  Object.assign(Base.prototype, proto)\n  ;(Base.prototype as any).name = tag\n  return Base as any\n}\n\n/** @internal */\nexport const RuntimeExceptionTypeId: Cause.RuntimeExceptionTypeId = Symbol.for(\n  \"effect/Cause/errors/RuntimeException\"\n) as Cause.RuntimeExceptionTypeId\n\n/** @internal */\nexport const RuntimeException = makeException<Cause.RuntimeException>({\n  [RuntimeExceptionTypeId]: RuntimeExceptionTypeId\n}, \"RuntimeException\")\n\n/** @internal */\nexport const isRuntimeException = (u: unknown): u is Cause.RuntimeException => hasProperty(u, RuntimeExceptionTypeId)\n\n/** @internal */\nexport const InterruptedExceptionTypeId: Cause.InterruptedExceptionTypeId = Symbol.for(\n  \"effect/Cause/errors/InterruptedException\"\n) as Cause.InterruptedExceptionTypeId\n\n/** @internal */\nexport const InterruptedException = makeException<Cause.InterruptedException>({\n  [InterruptedExceptionTypeId]: InterruptedExceptionTypeId\n}, \"InterruptedException\")\n\n/** @internal */\nexport const isInterruptedException = (u: unknown): u is Cause.InterruptedException =>\n  hasProperty(u, InterruptedExceptionTypeId)\n\n/** @internal */\nexport const IllegalArgumentExceptionTypeId: Cause.IllegalArgumentExceptionTypeId = Symbol.for(\n  \"effect/Cause/errors/IllegalArgument\"\n) as Cause.IllegalArgumentExceptionTypeId\n\n/** @internal */\nexport const IllegalArgumentException = makeException<Cause.IllegalArgumentException>({\n  [IllegalArgumentExceptionTypeId]: IllegalArgumentExceptionTypeId\n}, \"IllegalArgumentException\")\n\n/** @internal */\nexport const isIllegalArgumentException = (u: unknown): u is Cause.IllegalArgumentException =>\n  hasProperty(u, IllegalArgumentExceptionTypeId)\n\n/** @internal */\nexport const NoSuchElementExceptionTypeId: Cause.NoSuchElementExceptionTypeId = Symbol.for(\n  \"effect/Cause/errors/NoSuchElement\"\n) as Cause.NoSuchElementExceptionTypeId\n\n/** @internal */\nexport const NoSuchElementException = makeException<Cause.NoSuchElementException>({\n  [NoSuchElementExceptionTypeId]: NoSuchElementExceptionTypeId\n}, \"NoSuchElementException\")\n\n/** @internal */\nexport const isNoSuchElementException = (u: unknown): u is Cause.NoSuchElementException =>\n  hasProperty(u, NoSuchElementExceptionTypeId)\n\n/** @internal */\nexport const InvalidPubSubCapacityExceptionTypeId: Cause.InvalidPubSubCapacityExceptionTypeId = Symbol.for(\n  \"effect/Cause/errors/InvalidPubSubCapacityException\"\n) as Cause.InvalidPubSubCapacityExceptionTypeId\n\n/** @internal */\nexport const InvalidPubSubCapacityException = makeException<Cause.InvalidPubSubCapacityException>({\n  [InvalidPubSubCapacityExceptionTypeId]: InvalidPubSubCapacityExceptionTypeId\n}, \"InvalidPubSubCapacityException\")\n\n/** @internal */\nexport const ExceededCapacityExceptionTypeId: Cause.ExceededCapacityExceptionTypeId = Symbol.for(\n  \"effect/Cause/errors/ExceededCapacityException\"\n) as Cause.ExceededCapacityExceptionTypeId\n\n/** @internal */\nexport const ExceededCapacityException = makeException<Cause.ExceededCapacityException>({\n  [ExceededCapacityExceptionTypeId]: ExceededCapacityExceptionTypeId\n}, \"ExceededCapacityException\")\n\n/** @internal */\nexport const isExceededCapacityException = (u: unknown): u is Cause.ExceededCapacityException =>\n  hasProperty(u, ExceededCapacityExceptionTypeId)\n\n/** @internal */\nexport const isInvalidCapacityError = (u: unknown): u is Cause.InvalidPubSubCapacityException =>\n  hasProperty(u, InvalidPubSubCapacityExceptionTypeId)\n\n/** @internal */\nexport const TimeoutExceptionTypeId: Cause.TimeoutExceptionTypeId = Symbol.for(\n  \"effect/Cause/errors/Timeout\"\n) as Cause.TimeoutExceptionTypeId\n\n/** @internal */\nexport const TimeoutException = makeException<Cause.TimeoutException>({\n  [TimeoutExceptionTypeId]: TimeoutExceptionTypeId\n}, \"TimeoutException\")\n\n/** @internal */\nexport const timeoutExceptionFromDuration = (duration: Duration.DurationInput): Cause.TimeoutException =>\n  new TimeoutException(`Operation timed out after '${Duration.format(duration)}'`)\n\n/** @internal */\nexport const isTimeoutException = (u: unknown): u is Cause.TimeoutException => hasProperty(u, TimeoutExceptionTypeId)\n\n/** @internal */\nexport const UnknownExceptionTypeId: Cause.UnknownExceptionTypeId = Symbol.for(\n  \"effect/Cause/errors/UnknownException\"\n) as Cause.UnknownExceptionTypeId\n\n/** @internal */\nexport const UnknownException: new(cause: unknown, message?: string | undefined) => Cause.UnknownException =\n  (function() {\n    class UnknownException extends YieldableError {\n      readonly _tag = \"UnknownException\"\n      readonly error: unknown\n      constructor(cause: unknown, message?: string) {\n        super(message ?? \"An unknown error occurred\", { cause })\n        this.error = cause\n      }\n    }\n    Object.assign(UnknownException.prototype, {\n      [UnknownExceptionTypeId]: UnknownExceptionTypeId,\n      name: \"UnknownException\"\n    })\n    return UnknownException as any\n  })()\n\n/** @internal */\nexport const isUnknownException = (u: unknown): u is Cause.UnknownException => hasProperty(u, UnknownExceptionTypeId)\n\n// -----------------------------------------------------------------------------\n// Exit\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const exitIsExit = (u: unknown): u is Exit.Exit<unknown, unknown> =>\n  isEffect(u) && \"_tag\" in u && (u._tag === \"Success\" || u._tag === \"Failure\")\n\n/** @internal */\nexport const exitIsFailure = <A, E>(self: Exit.Exit<A, E>): self is Exit.Failure<A, E> => self._tag === \"Failure\"\n\n/** @internal */\nexport const exitIsSuccess = <A, E>(self: Exit.Exit<A, E>): self is Exit.Success<A, E> => self._tag === \"Success\"\n\n/** @internal */\nexport const exitIsInterrupted = <A, E>(self: Exit.Exit<A, E>): boolean => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE:\n      return internalCause.isInterrupted(self.effect_instruction_i0)\n    case OpCodes.OP_SUCCESS:\n      return false\n  }\n}\n\n/** @internal */\nexport const exitAs = dual<\n  <A2>(value: A2) => <A, E>(self: Exit.Exit<A, E>) => Exit.Exit<A2, E>,\n  <A, E, A2>(self: Exit.Exit<A, E>, value: A2) => Exit.Exit<A2, E>\n>(2, <A, E, A2>(self: Exit.Exit<A, E>, value: A2): Exit.Exit<A2, E> => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE: {\n      return exitFailCause(self.effect_instruction_i0)\n    }\n    case OpCodes.OP_SUCCESS: {\n      return exitSucceed(value) as Exit.Exit<A2, E>\n    }\n  }\n})\n\n/** @internal */\nexport const exitAsVoid = <A, E>(self: Exit.Exit<A, E>): Exit.Exit<void, E> => exitAs(self, void 0)\n\n/** @internal */\nexport const exitCauseOption = <A, E>(self: Exit.Exit<A, E>): Option.Option<Cause.Cause<E>> => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE:\n      return Option.some(self.effect_instruction_i0)\n    case OpCodes.OP_SUCCESS:\n      return Option.none()\n  }\n}\n\n/** @internal */\nexport const exitCollectAll = <A, E>(\n  exits: Iterable<Exit.Exit<A, E>>,\n  options?: {\n    readonly parallel?: boolean | undefined\n  }\n): Option.Option<Exit.Exit<Array<A>, E>> =>\n  exitCollectAllInternal(exits, options?.parallel ? internalCause.parallel : internalCause.sequential)\n\n/** @internal */\nexport const exitDie = (defect: unknown): Exit.Exit<never> =>\n  exitFailCause(internalCause.die(defect)) as Exit.Exit<never>\n\n/** @internal */\nexport const exitExists: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): <E>(self: Exit.Exit<A, E>) => self is Exit.Exit<B>\n  <A>(predicate: Predicate<NoInfer<A>>): <E>(self: Exit.Exit<A, E>) => boolean\n  <A, E, B extends A>(self: Exit.Exit<A, E>, refinement: Refinement<A, B>): self is Exit.Exit<B>\n  <A, E>(self: Exit.Exit<A, E>, predicate: Predicate<A>): boolean\n} = dual(2, <A, E, B extends A>(self: Exit.Exit<A, E>, refinement: Refinement<A, B>): self is Exit.Exit<B> => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE:\n      return false\n    case OpCodes.OP_SUCCESS:\n      return refinement(self.effect_instruction_i0)\n  }\n})\n\n/** @internal */\nexport const exitFail = <E>(error: E): Exit.Exit<never, E> =>\n  exitFailCause(internalCause.fail(error)) as Exit.Exit<never, E>\n\n/** @internal */\nexport const exitFailCause = <E>(cause: Cause.Cause<E>): Exit.Exit<never, E> => {\n  const effect = new EffectPrimitiveFailure(OpCodes.OP_FAILURE) as any\n  effect.effect_instruction_i0 = cause\n  return effect\n}\n\n/** @internal */\nexport const exitFlatMap = dual<\n  <A, A2, E2>(f: (a: A) => Exit.Exit<A2, E2>) => <E>(self: Exit.Exit<A, E>) => Exit.Exit<A2, E | E2>,\n  <A, E, E2, A2>(self: Exit.Exit<A, E>, f: (a: A) => Exit.Exit<A2, E2>) => Exit.Exit<A2, E | E2>\n>(2, <A, E, E2, A2>(self: Exit.Exit<A, E>, f: (a: A) => Exit.Exit<A2, E2>): Exit.Exit<A2, E | E2> => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE: {\n      return exitFailCause(self.effect_instruction_i0)\n    }\n    case OpCodes.OP_SUCCESS: {\n      return f(self.effect_instruction_i0)\n    }\n  }\n})\n\n/** @internal */\nexport const exitFlatMapEffect: {\n  <A, E, A2, E2, R>(\n    f: (a: A) => Effect.Effect<Exit.Exit<A2, E>, E2, R>\n  ): (self: Exit.Exit<A, E>) => Effect.Effect<Exit.Exit<A2, E>, E2, R>\n  <A, E, A2, E2, R>(\n    self: Exit.Exit<A, E>,\n    f: (a: A) => Effect.Effect<Exit.Exit<A2, E>, E2, R>\n  ): Effect.Effect<Exit.Exit<A2, E>, E2, R>\n} = dual(2, <A, E, A2, E2, R>(\n  self: Exit.Exit<A, E>,\n  f: (a: A) => Effect.Effect<Exit.Exit<A2, E>, E2, R>\n): Effect.Effect<Exit.Exit<A2, E>, E2, R> => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE: {\n      return succeed(exitFailCause(self.effect_instruction_i0))\n    }\n    case OpCodes.OP_SUCCESS: {\n      return f(self.effect_instruction_i0)\n    }\n  }\n})\n\n/** @internal */\nexport const exitFlatten = <A, E, E2>(\n  self: Exit.Exit<Exit.Exit<A, E>, E2>\n): Exit.Exit<A, E | E2> => pipe(self, exitFlatMap(identity))\n\n/** @internal */\nexport const exitForEachEffect: {\n  <A, B, E2, R>(\n    f: (a: A) => Effect.Effect<B, E2, R>\n  ): <E>(self: Exit.Exit<A, E>) => Effect.Effect<Exit.Exit<B, E | E2>, never, R>\n  <A, E, B, E2, R>(\n    self: Exit.Exit<A, E>,\n    f: (a: A) => Effect.Effect<B, E2, R>\n  ): Effect.Effect<Exit.Exit<B, E | E2>, never, R>\n} = dual(2, <A, E, B, E2, R>(\n  self: Exit.Exit<A, E>,\n  f: (a: A) => Effect.Effect<B, E2, R>\n): Effect.Effect<Exit.Exit<B, E | E2>, never, R> => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE: {\n      return succeed(exitFailCause(self.effect_instruction_i0))\n    }\n    case OpCodes.OP_SUCCESS: {\n      return exit(f(self.effect_instruction_i0))\n    }\n  }\n})\n\n/** @internal */\nexport const exitFromEither = <R, L>(either: Either.Either<R, L>): Exit.Exit<R, L> => {\n  switch (either._tag) {\n    case \"Left\":\n      return exitFail(either.left)\n    case \"Right\":\n      return exitSucceed(either.right)\n  }\n}\n\n/** @internal */\nexport const exitFromOption = <A>(option: Option.Option<A>): Exit.Exit<A, void> => {\n  switch (option._tag) {\n    case \"None\":\n      return exitFail(void 0)\n    case \"Some\":\n      return exitSucceed(option.value)\n  }\n}\n\n/** @internal */\nexport const exitGetOrElse = dual<\n  <E, A2>(orElse: (cause: Cause.Cause<E>) => A2) => <A>(self: Exit.Exit<A, E>) => A | A2,\n  <A, E, A2>(self: Exit.Exit<A, E>, orElse: (cause: Cause.Cause<E>) => A2) => A | A2\n>(2, (self, orElse) => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE:\n      return orElse(self.effect_instruction_i0)\n    case OpCodes.OP_SUCCESS:\n      return self.effect_instruction_i0\n  }\n})\n\n/** @internal */\nexport const exitInterrupt = (fiberId: FiberId.FiberId): Exit.Exit<never> =>\n  exitFailCause(internalCause.interrupt(fiberId))\n\n/** @internal */\nexport const exitMap = dual<\n  <A, B>(f: (a: A) => B) => <E>(self: Exit.Exit<A, E>) => Exit.Exit<B, E>,\n  <A, E, B>(self: Exit.Exit<A, E>, f: (a: A) => B) => Exit.Exit<B, E>\n>(2, (self, f) => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE:\n      return exitFailCause(self.effect_instruction_i0)\n    case OpCodes.OP_SUCCESS:\n      return exitSucceed(f(self.effect_instruction_i0))\n  }\n})\n\n/** @internal */\nexport const exitMapBoth = dual<\n  <E, A, E2, A2>(\n    options: {\n      readonly onFailure: (e: E) => E2\n      readonly onSuccess: (a: A) => A2\n    }\n  ) => (self: Exit.Exit<A, E>) => Exit.Exit<A2, E2>,\n  <A, E, E2, A2>(\n    self: Exit.Exit<A, E>,\n    options: {\n      readonly onFailure: (e: E) => E2\n      readonly onSuccess: (a: A) => A2\n    }\n  ) => Exit.Exit<A2, E2>\n>(2, (self, { onFailure, onSuccess }) => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE:\n      return exitFailCause(pipe(self.effect_instruction_i0, internalCause.map(onFailure)))\n    case OpCodes.OP_SUCCESS:\n      return exitSucceed(onSuccess(self.effect_instruction_i0))\n  }\n})\n\n/** @internal */\nexport const exitMapError = dual<\n  <E, E2>(f: (e: E) => E2) => <A>(self: Exit.Exit<A, E>) => Exit.Exit<A, E2>,\n  <A, E, E2>(self: Exit.Exit<A, E>, f: (e: E) => E2) => Exit.Exit<A, E2>\n>(2, (self, f) => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE:\n      return exitFailCause(pipe(self.effect_instruction_i0, internalCause.map(f)))\n    case OpCodes.OP_SUCCESS:\n      return exitSucceed(self.effect_instruction_i0)\n  }\n})\n\n/** @internal */\nexport const exitMapErrorCause = dual<\n  <E, E2>(f: (cause: Cause.Cause<E>) => Cause.Cause<E2>) => <A>(self: Exit.Exit<A, E>) => Exit.Exit<A, E2>,\n  <E, A, E2>(self: Exit.Exit<A, E>, f: (cause: Cause.Cause<E>) => Cause.Cause<E2>) => Exit.Exit<A, E2>\n>(2, (self, f) => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE:\n      return exitFailCause(f(self.effect_instruction_i0))\n    case OpCodes.OP_SUCCESS:\n      return exitSucceed(self.effect_instruction_i0)\n  }\n})\n\n/** @internal */\nexport const exitMatch = dual<\n  <E, A, Z1, Z2>(options: {\n    readonly onFailure: (cause: Cause.Cause<E>) => Z1\n    readonly onSuccess: (a: A) => Z2\n  }) => (self: Exit.Exit<A, E>) => Z1 | Z2,\n  <A, E, Z1, Z2>(self: Exit.Exit<A, E>, options: {\n    readonly onFailure: (cause: Cause.Cause<E>) => Z1\n    readonly onSuccess: (a: A) => Z2\n  }) => Z1 | Z2\n>(2, (self, { onFailure, onSuccess }) => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE:\n      return onFailure(self.effect_instruction_i0)\n    case OpCodes.OP_SUCCESS:\n      return onSuccess(self.effect_instruction_i0)\n  }\n})\n\n/** @internal */\nexport const exitMatchEffect = dual<\n  <E, A2, E2, R, A, A3, E3, R2>(\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<A2, E2, R>\n      readonly onSuccess: (a: A) => Effect.Effect<A3, E3, R2>\n    }\n  ) => (self: Exit.Exit<A, E>) => Effect.Effect<A2 | A3, E2 | E3, R | R2>,\n  <A, E, A2, E2, R, A3, E3, R2>(\n    self: Exit.Exit<A, E>,\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<A2, E2, R>\n      readonly onSuccess: (a: A) => Effect.Effect<A3, E3, R2>\n    }\n  ) => Effect.Effect<A2 | A3, E2 | E3, R | R2>\n>(2, (self, { onFailure, onSuccess }) => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE:\n      return onFailure(self.effect_instruction_i0)\n    case OpCodes.OP_SUCCESS:\n      return onSuccess(self.effect_instruction_i0)\n  }\n})\n\n/** @internal */\nexport const exitSucceed = <A>(value: A): Exit.Exit<A> => {\n  const effect = new EffectPrimitiveSuccess(OpCodes.OP_SUCCESS) as any\n  effect.effect_instruction_i0 = value\n  return effect\n}\n\n/** @internal */\nexport const exitVoid: Exit.Exit<void> = exitSucceed(void 0)\n\n/** @internal */\nexport const exitZip = dual<\n  <A2, E2>(that: Exit.Exit<A2, E2>) => <A, E>(self: Exit.Exit<A, E>) => Exit.Exit<[A, A2], E | E2>,\n  <A, E, A2, E2>(self: Exit.Exit<A, E>, that: Exit.Exit<A2, E2>) => Exit.Exit<[A, A2], E | E2>\n>(2, (self, that) =>\n  exitZipWith(self, that, {\n    onSuccess: (a, a2) => [a, a2],\n    onFailure: internalCause.sequential\n  }))\n\n/** @internal */\nexport const exitZipLeft = dual<\n  <A2, E2>(that: Exit.Exit<A2, E2>) => <A, E>(self: Exit.Exit<A, E>) => Exit.Exit<A, E | E2>,\n  <A, E, A2, E2>(self: Exit.Exit<A, E>, that: Exit.Exit<A2, E2>) => Exit.Exit<A, E | E2>\n>(2, (self, that) =>\n  exitZipWith(self, that, {\n    onSuccess: (a, _) => a,\n    onFailure: internalCause.sequential\n  }))\n\n/** @internal */\nexport const exitZipRight = dual<\n  <A2, E2>(that: Exit.Exit<A2, E2>) => <A, E>(self: Exit.Exit<A, E>) => Exit.Exit<A2, E | E2>,\n  <A, E, A2, E2>(self: Exit.Exit<A, E>, that: Exit.Exit<A2, E2>) => Exit.Exit<A2, E | E2>\n>(2, (self, that) =>\n  exitZipWith(self, that, {\n    onSuccess: (_, a2) => a2,\n    onFailure: internalCause.sequential\n  }))\n\n/** @internal */\nexport const exitZipPar = dual<\n  <A2, E2>(that: Exit.Exit<A2, E2>) => <A, E>(self: Exit.Exit<A, E>) => Exit.Exit<[A, A2], E | E2>,\n  <A, E, A2, E2>(self: Exit.Exit<A, E>, that: Exit.Exit<A2, E2>) => Exit.Exit<[A, A2], E | E2>\n>(2, (self, that) =>\n  exitZipWith(self, that, {\n    onSuccess: (a, a2) => [a, a2],\n    onFailure: internalCause.parallel\n  }))\n\n/** @internal */\nexport const exitZipParLeft = dual<\n  <A2, E2>(that: Exit.Exit<A2, E2>) => <A, E>(self: Exit.Exit<A, E>) => Exit.Exit<A, E | E2>,\n  <A, E, A2, E2>(self: Exit.Exit<A, E>, that: Exit.Exit<A2, E2>) => Exit.Exit<A, E | E2>\n>(2, (self, that) =>\n  exitZipWith(self, that, {\n    onSuccess: (a, _) => a,\n    onFailure: internalCause.parallel\n  }))\n\n/** @internal */\nexport const exitZipParRight = dual<\n  <A2, E2>(that: Exit.Exit<A2, E2>) => <A, E>(self: Exit.Exit<A, E>) => Exit.Exit<A2, E | E2>,\n  <A, E, A2, E2>(self: Exit.Exit<A, E>, that: Exit.Exit<A2, E2>) => Exit.Exit<A2, E | E2>\n>(2, (self, that) =>\n  exitZipWith(self, that, {\n    onSuccess: (_, a2) => a2,\n    onFailure: internalCause.parallel\n  }))\n\n/** @internal */\nexport const exitZipWith = dual<\n  <B, E2, A, C, E>(\n    that: Exit.Exit<B, E2>,\n    options: {\n      readonly onSuccess: (a: A, b: B) => C\n      readonly onFailure: (cause: Cause.Cause<E>, cause2: Cause.Cause<E2>) => Cause.Cause<E | E2>\n    }\n  ) => (self: Exit.Exit<A, E>) => Exit.Exit<C, E | E2>,\n  <A, E, B, E2, C>(\n    self: Exit.Exit<A, E>,\n    that: Exit.Exit<B, E2>,\n    options: {\n      readonly onSuccess: (a: A, b: B) => C\n      readonly onFailure: (cause: Cause.Cause<E>, cause2: Cause.Cause<E2>) => Cause.Cause<E | E2>\n    }\n  ) => Exit.Exit<C, E | E2>\n>(3, (\n  self,\n  that,\n  { onFailure, onSuccess }\n) => {\n  switch (self._tag) {\n    case OpCodes.OP_FAILURE: {\n      switch (that._tag) {\n        case OpCodes.OP_SUCCESS:\n          return exitFailCause(self.effect_instruction_i0)\n        case OpCodes.OP_FAILURE: {\n          return exitFailCause(onFailure(self.effect_instruction_i0, that.effect_instruction_i0))\n        }\n      }\n    }\n    case OpCodes.OP_SUCCESS: {\n      switch (that._tag) {\n        case OpCodes.OP_SUCCESS:\n          return exitSucceed(onSuccess(self.effect_instruction_i0, that.effect_instruction_i0))\n        case OpCodes.OP_FAILURE:\n          return exitFailCause(that.effect_instruction_i0)\n      }\n    }\n  }\n})\n\nconst exitCollectAllInternal = <A, E>(\n  exits: Iterable<Exit.Exit<A, E>>,\n  combineCauses: (causeA: Cause.Cause<E>, causeB: Cause.Cause<E>) => Cause.Cause<E>\n): Option.Option<Exit.Exit<Array<A>, E>> => {\n  const list = Chunk.fromIterable(exits)\n  if (!Chunk.isNonEmpty(list)) {\n    return Option.none()\n  }\n  return pipe(\n    Chunk.tailNonEmpty(list),\n    Arr.reduce(\n      pipe(Chunk.headNonEmpty(list), exitMap<A, Chunk.Chunk<A>>(Chunk.of)),\n      (accumulator, current) =>\n        pipe(\n          accumulator,\n          exitZipWith(current, {\n            onSuccess: (list, value) => pipe(list, Chunk.prepend(value)),\n            onFailure: combineCauses\n          })\n        )\n    ),\n    exitMap(Chunk.reverse),\n    exitMap((chunk) => Chunk.toReadonlyArray(chunk) as Array<A>),\n    Option.some\n  )\n}\n\n// -----------------------------------------------------------------------------\n// Deferred\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const deferredUnsafeMake = <A, E = never>(fiberId: FiberId.FiberId): Deferred.Deferred<A, E> => {\n  const _deferred = {\n    ...CommitPrototype,\n    [deferred.DeferredTypeId]: deferred.deferredVariance,\n    state: MutableRef.make(deferred.pending<A, E>([])),\n    commit() {\n      return deferredAwait(this)\n    },\n    blockingOn: fiberId\n  }\n  return _deferred\n}\n\n/* @internal */\nexport const deferredMake = <A, E = never>(): Effect.Effect<Deferred.Deferred<A, E>> =>\n  flatMap(fiberId, (id) => deferredMakeAs<A, E>(id))\n\n/* @internal */\nexport const deferredMakeAs = <A, E = never>(fiberId: FiberId.FiberId): Effect.Effect<Deferred.Deferred<A, E>> =>\n  sync(() => deferredUnsafeMake<A, E>(fiberId))\n\n/* @internal */\nexport const deferredAwait = <A, E>(self: Deferred.Deferred<A, E>): Effect.Effect<A, E> =>\n  asyncInterrupt<A, E>((resume) => {\n    const state = MutableRef.get(self.state)\n    switch (state._tag) {\n      case DeferredOpCodes.OP_STATE_DONE: {\n        return resume(state.effect)\n      }\n      case DeferredOpCodes.OP_STATE_PENDING: {\n        // we can push here as the internal state is mutable\n        state.joiners.push(resume)\n        return deferredInterruptJoiner(self, resume)\n      }\n    }\n  }, self.blockingOn)\n\n/* @internal */\nexport const deferredComplete: {\n  <A, E>(effect: Effect.Effect<A, E>): (self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>\n  <A, E>(self: Deferred.Deferred<A, E>, effect: Effect.Effect<A, E>): Effect.Effect<boolean>\n} = dual(\n  2,\n  <A, E>(self: Deferred.Deferred<A, E>, effect: Effect.Effect<A, E>): Effect.Effect<boolean> =>\n    intoDeferred(effect, self)\n)\n\n/* @internal */\nexport const deferredCompleteWith = dual<\n  <A, E>(effect: Effect.Effect<A, E>) => (self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, effect: Effect.Effect<A, E>) => Effect.Effect<boolean>\n>(2, (self, effect) =>\n  sync(() => {\n    const state = MutableRef.get(self.state)\n    switch (state._tag) {\n      case DeferredOpCodes.OP_STATE_DONE: {\n        return false\n      }\n      case DeferredOpCodes.OP_STATE_PENDING: {\n        MutableRef.set(self.state, deferred.done(effect))\n        for (let i = 0, len = state.joiners.length; i < len; i++) {\n          state.joiners[i](effect)\n        }\n        return true\n      }\n    }\n  }))\n\n/* @internal */\nexport const deferredDone = dual<\n  <A, E>(exit: Exit.Exit<A, E>) => (self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) => Effect.Effect<boolean>\n>(2, (self, exit) => deferredCompleteWith(self, exit))\n\n/* @internal */\nexport const deferredFail = dual<\n  <E>(error: E) => <A>(self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, error: E) => Effect.Effect<boolean>\n>(2, (self, error) => deferredCompleteWith(self, fail(error)))\n\n/* @internal */\nexport const deferredFailSync = dual<\n  <E>(evaluate: LazyArg<E>) => <A>(self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, evaluate: LazyArg<E>) => Effect.Effect<boolean>\n>(2, (self, evaluate) => deferredCompleteWith(self, failSync(evaluate)))\n\n/* @internal */\nexport const deferredFailCause = dual<\n  <E>(cause: Cause.Cause<E>) => <A>(self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, cause: Cause.Cause<E>) => Effect.Effect<boolean>\n>(2, (self, cause) => deferredCompleteWith(self, failCause(cause)))\n\n/* @internal */\nexport const deferredFailCauseSync = dual<\n  <E>(evaluate: LazyArg<Cause.Cause<E>>) => <A>(self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, evaluate: LazyArg<Cause.Cause<E>>) => Effect.Effect<boolean>\n>(2, (self, evaluate) => deferredCompleteWith(self, failCauseSync(evaluate)))\n\n/* @internal */\nexport const deferredDie = dual<\n  (defect: unknown) => <A, E>(self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, defect: unknown) => Effect.Effect<boolean>\n>(2, (self, defect) => deferredCompleteWith(self, die(defect)))\n\n/* @internal */\nexport const deferredDieSync = dual<\n  (evaluate: LazyArg<unknown>) => <A, E>(self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, evaluate: LazyArg<unknown>) => Effect.Effect<boolean>\n>(2, (self, evaluate) => deferredCompleteWith(self, dieSync(evaluate)))\n\n/* @internal */\nexport const deferredInterrupt = <A, E>(self: Deferred.Deferred<A, E>): Effect.Effect<boolean> =>\n  flatMap(fiberId, (fiberId) => deferredCompleteWith(self, interruptWith(fiberId)))\n\n/* @internal */\nexport const deferredInterruptWith = dual<\n  (fiberId: FiberId.FiberId) => <A, E>(self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, fiberId: FiberId.FiberId) => Effect.Effect<boolean>\n>(2, (self, fiberId) => deferredCompleteWith(self, interruptWith(fiberId)))\n\n/* @internal */\nexport const deferredIsDone = <A, E>(self: Deferred.Deferred<A, E>): Effect.Effect<boolean> =>\n  sync(() => MutableRef.get(self.state)._tag === DeferredOpCodes.OP_STATE_DONE)\n\n/* @internal */\nexport const deferredPoll = <A, E>(\n  self: Deferred.Deferred<A, E>\n): Effect.Effect<Option.Option<Effect.Effect<A, E>>> =>\n  sync(() => {\n    const state = MutableRef.get(self.state)\n    switch (state._tag) {\n      case DeferredOpCodes.OP_STATE_DONE: {\n        return Option.some(state.effect)\n      }\n      case DeferredOpCodes.OP_STATE_PENDING: {\n        return Option.none()\n      }\n    }\n  })\n\n/* @internal */\nexport const deferredSucceed = dual<\n  <A>(value: A) => <E>(self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, value: A) => Effect.Effect<boolean>\n>(2, (self, value) => deferredCompleteWith(self, succeed(value)))\n\n/* @internal */\nexport const deferredSync = dual<\n  <A>(evaluate: LazyArg<A>) => <E>(self: Deferred.Deferred<A, E>) => Effect.Effect<boolean>,\n  <A, E>(self: Deferred.Deferred<A, E>, evaluate: LazyArg<A>) => Effect.Effect<boolean>\n>(2, (self, evaluate) => deferredCompleteWith(self, sync(evaluate)))\n\n/** @internal */\nexport const deferredUnsafeDone = <A, E>(self: Deferred.Deferred<A, E>, effect: Effect.Effect<A, E>): void => {\n  const state = MutableRef.get(self.state)\n  if (state._tag === DeferredOpCodes.OP_STATE_PENDING) {\n    MutableRef.set(self.state, deferred.done(effect))\n    for (let i = 0, len = state.joiners.length; i < len; i++) {\n      state.joiners[i](effect)\n    }\n  }\n}\n\nconst deferredInterruptJoiner = <A, E>(\n  self: Deferred.Deferred<A, E>,\n  joiner: (effect: Effect.Effect<A, E>) => void\n): Effect.Effect<void> =>\n  sync(() => {\n    const state = MutableRef.get(self.state)\n    if (state._tag === DeferredOpCodes.OP_STATE_PENDING) {\n      const index = state.joiners.indexOf(joiner)\n      if (index >= 0) {\n        // we can splice here as the internal state is mutable\n        state.joiners.splice(index, 1)\n      }\n    }\n  })\n\n// -----------------------------------------------------------------------------\n// Context\n// -----------------------------------------------------------------------------\n\nconst constContext = withFiberRuntime((fiber) => exitSucceed(fiber.currentContext))\n\n/* @internal */\nexport const context = <R>(): Effect.Effect<Context.Context<R>, never, R> => constContext as any\n\n/* @internal */\nexport const contextWith = <R0, A>(\n  f: (context: Context.Context<R0>) => A\n): Effect.Effect<A, never, R0> => map(context<R0>(), f)\n\n/* @internal */\nexport const contextWithEffect = <R2, A, E, R>(\n  f: (context: Context.Context<R2>) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R | R2> => flatMap(context<R2>(), f)\n\n/* @internal */\nexport const provideContext = dual<\n  <R>(context: Context.Context<R>) => <A, E>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, context: Context.Context<R>) => Effect.Effect<A, E>\n>(2, <A, E, R>(self: Effect.Effect<A, E, R>, context: Context.Context<R>) =>\n  fiberRefLocally(\n    currentContext,\n    context\n  )(self as Effect.Effect<A, E>))\n\n/* @internal */\nexport const provideSomeContext = dual<\n  <R>(context: Context.Context<R>) => <A, E, R1>(self: Effect.Effect<A, E, R1>) => Effect.Effect<A, E, Exclude<R1, R>>,\n  <A, E, R1, R>(self: Effect.Effect<A, E, R1>, context: Context.Context<R>) => Effect.Effect<A, E, Exclude<R1, R>>\n>(2, <A, E, R1, R>(self: Effect.Effect<A, E, R1>, context: Context.Context<R>) =>\n  fiberRefLocallyWith(\n    currentContext,\n    (parent) => Context.merge(parent, context)\n  )(self as Effect.Effect<A, E>))\n\n/* @internal */\nexport const mapInputContext = dual<\n  <R2, R>(\n    f: (context: Context.Context<R2>) => Context.Context<R>\n  ) => <A, E>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R2>,\n  <A, E, R, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (context: Context.Context<R2>) => Context.Context<R>\n  ) => Effect.Effect<A, E, R2>\n>(2, <A, E, R, R2>(\n  self: Effect.Effect<A, E, R>,\n  f: (context: Context.Context<R2>) => Context.Context<R>\n) => contextWithEffect((context: Context.Context<R2>) => provideContext(self, f(context))))\n\n// -----------------------------------------------------------------------------\n// Filtering\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const filterEffectOrElse: {\n  <A, E2, R2, A2, E3, R3>(\n    options: {\n      readonly predicate: (a: NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n      readonly orElse: (a: NoInfer<A>) => Effect.Effect<A2, E3, R3>\n    }\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A | A2, E | E2 | E3, R | R2 | R3>\n  <A, E, R, E2, R2, A2, E3, R3>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly predicate: (a: A) => Effect.Effect<boolean, E2, R2>\n      readonly orElse: (a: A) => Effect.Effect<A2, E3, R3>\n    }\n  ): Effect.Effect<A | A2, E | E2 | E3, R | R2 | R3>\n} = dual(2, <A, E, R, E2, R2, A2, E3, R3>(\n  self: Effect.Effect<A, E, R>,\n  options: {\n    readonly predicate: (a: A) => Effect.Effect<boolean, E2, R2>\n    readonly orElse: (a: A) => Effect.Effect<A2, E3, R3>\n  }\n): Effect.Effect<A | A2, E | E2 | E3, R | R2 | R3> =>\n  flatMap(\n    self,\n    (a) =>\n      flatMap(\n        options.predicate(a),\n        (pass): Effect.Effect<A | A2, E3, R3> => pass ? succeed(a) : options.orElse(a)\n      )\n  ))\n\n/** @internal */\nexport const filterEffectOrFail: {\n  <A, E2, R2, E3>(\n    options: {\n      readonly predicate: (a: NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n      readonly orFailWith: (a: NoInfer<A>) => E3\n    }\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E2 | E3, R | R2>\n  <A, E, R, E2, R2, E3>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly predicate: (a: A) => Effect.Effect<boolean, E2, R2>\n      readonly orFailWith: (a: A) => E3\n    }\n  ): Effect.Effect<A, E | E2 | E3, R | R2>\n} = dual(2, <A, E, R, E2, R2, E3>(\n  self: Effect.Effect<A, E, R>,\n  options: {\n    readonly predicate: (a: A) => Effect.Effect<boolean, E2, R2>\n    readonly orFailWith: (a: A) => E3\n  }\n): Effect.Effect<A, E | E2 | E3, R | R2> =>\n  filterEffectOrElse(self, {\n    predicate: options.predicate,\n    orElse: (a) => fail(options.orFailWith(a))\n  }))\n\n// -----------------------------------------------------------------------------\n// Tracing\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const currentSpanFromFiber = <A, E>(fiber: Fiber.RuntimeFiber<A, E>): Option.Option<Tracer.Span> => {\n  const span = fiber.currentSpan\n  return span !== undefined && span._tag === \"Span\" ? Option.some(span) : Option.none()\n}\n\nconst NoopSpanProto: Omit<Tracer.Span, \"parent\" | \"name\" | \"context\"> = {\n  _tag: \"Span\",\n  spanId: \"noop\",\n  traceId: \"noop\",\n  sampled: false,\n  status: {\n    _tag: \"Ended\",\n    startTime: BigInt(0),\n    endTime: BigInt(0),\n    exit: exitVoid\n  },\n  attributes: new Map(),\n  links: [],\n  kind: \"internal\",\n  attribute() {},\n  event() {},\n  end() {},\n  addLinks() {}\n}\n\n/** @internal */\nexport const noopSpan = (options: {\n  readonly name: string\n  readonly parent: Option.Option<Tracer.AnySpan>\n  readonly context: Context.Context<never>\n}): Tracer.Span => Object.assign(Object.create(NoopSpanProto), options)\n"
  },
  {
    "path": "packages/effect/src/internal/data.ts",
    "content": "import * as Equal from \"../Equal.js\"\nimport * as Hash from \"../Hash.js\"\nimport type * as Types from \"../Types.js\"\nimport { StructuralPrototype } from \"./effectable.js\"\n\n/** @internal */\nexport const ArrayProto: Equal.Equal = Object.assign(Object.create(Array.prototype), {\n  [Hash.symbol](this: Array<any>) {\n    return Hash.cached(this, Hash.array(this))\n  },\n  [Equal.symbol](this: Array<any>, that: Equal.Equal) {\n    if (Array.isArray(that) && this.length === that.length) {\n      return this.every((v, i) => Equal.equals(v, (that as Array<any>)[i]))\n    } else {\n      return false\n    }\n  }\n})\n\n/** @internal */\nexport const Structural: new<A>(\n  args: Types.Equals<Omit<A, keyof Equal.Equal>, {}> extends true ? void\n    : { readonly [P in keyof A as P extends keyof Equal.Equal ? never : P]: A[P] }\n) => {} = (function() {\n  function Structural(this: any, args: any) {\n    if (args) {\n      Object.assign(this, args)\n    }\n  }\n  Structural.prototype = StructuralPrototype\n  return Structural as any\n})()\n\n/** @internal */\nexport const struct = <As extends Readonly<Record<string, any>>>(as: As): As =>\n  Object.assign(Object.create(StructuralPrototype), as)\n"
  },
  {
    "path": "packages/effect/src/internal/dataSource.ts",
    "content": "import * as RA from \"../Array.js\"\nimport * as Cause from \"../Cause.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport type * as Context from \"../Context.js\"\nimport * as Effect from \"../Effect.js\"\nimport type * as Either from \"../Either.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport type * as Request from \"../Request.js\"\nimport type * as RequestResolver from \"../RequestResolver.js\"\nimport type { NoInfer } from \"../Types.js\"\nimport * as core from \"./core.js\"\nimport { invokeWithInterrupt, zipWithOptions } from \"./fiberRuntime.js\"\nimport { complete } from \"./request.js\"\n\n/** @internal */\nexport const make = <A, R>(\n  runAll: (requests: Array<Array<A>>) => Effect.Effect<void, never, R>\n): RequestResolver.RequestResolver<A, R> =>\n  new core.RequestResolverImpl((requests) => runAll(requests.map((_) => _.map((_) => _.request))))\n\n/** @internal */\nexport const makeWithEntry = <A, R>(\n  runAll: (requests: Array<Array<Request.Entry<A>>>) => Effect.Effect<void, never, R>\n): RequestResolver.RequestResolver<A, R> => new core.RequestResolverImpl((requests) => runAll(requests))\n\n/** @internal */\nexport const makeBatched = <A extends Request.Request<any, any>, R>(\n  run: (requests: RA.NonEmptyArray<A>) => Effect.Effect<void, never, R>\n): RequestResolver.RequestResolver<A, R> =>\n  new core.RequestResolverImpl<A, R>(\n    (requests) => {\n      if (requests.length > 1) {\n        return core.forEachSequentialDiscard(requests, (block) => {\n          const filtered = block.filter((_) => !_.state.completed).map((_) => _.request)\n          if (!RA.isNonEmptyArray(filtered)) {\n            return core.void\n          }\n          return invokeWithInterrupt(run(filtered), block)\n        })\n      } else if (requests.length === 1) {\n        const filtered = requests[0].filter((_) => !_.state.completed).map((_) => _.request)\n        if (!RA.isNonEmptyArray(filtered)) {\n          return core.void\n        }\n        return run(filtered)\n      }\n      return core.void\n    }\n  )\n\n/** @internal */\nexport const around = dual<\n  <A2, R2, X, R3>(\n    before: Effect.Effect<A2, never, R2>,\n    after: (a: A2) => Effect.Effect<X, never, R3>\n  ) => <A, R>(\n    self: RequestResolver.RequestResolver<A, R>\n  ) => RequestResolver.RequestResolver<A, R | R2 | R3>,\n  <A, R, A2, R2, X, R3>(\n    self: RequestResolver.RequestResolver<A, R>,\n    before: Effect.Effect<A2, never, R2>,\n    after: (a: A2) => Effect.Effect<X, never, R3>\n  ) => RequestResolver.RequestResolver<A, R | R2 | R3>\n>(3, (self, before, after) =>\n  new core.RequestResolverImpl(\n    (requests) =>\n      core.acquireUseRelease(\n        before,\n        () => self.runAll(requests),\n        after\n      ),\n    Chunk.make(\"Around\", self, before, after)\n  ))\n\n/** @internal */\nexport const aroundRequests = dual<\n  <A, A2, R2, X, R3>(\n    before: (requests: ReadonlyArray<NoInfer<A>>) => Effect.Effect<A2, never, R2>,\n    after: (requests: ReadonlyArray<NoInfer<A>>, _: A2) => Effect.Effect<X, never, R3>\n  ) => <R>(\n    self: RequestResolver.RequestResolver<A, R>\n  ) => RequestResolver.RequestResolver<A, R | R2 | R3>,\n  <A, R, A2, R2, X, R3>(\n    self: RequestResolver.RequestResolver<A, R>,\n    before: (requests: ReadonlyArray<NoInfer<A>>) => Effect.Effect<A2, never, R2>,\n    after: (requests: ReadonlyArray<NoInfer<A>>, _: A2) => Effect.Effect<X, never, R3>\n  ) => RequestResolver.RequestResolver<A, R | R2 | R3>\n>(3, (self, before, after) =>\n  new core.RequestResolverImpl(\n    (requests) => {\n      const flatRequests = requests.flatMap((chunk) => chunk.map((entry) => entry.request))\n      return core.acquireUseRelease(\n        before(flatRequests),\n        () => self.runAll(requests),\n        (a2) => after(flatRequests, a2)\n      )\n    },\n    Chunk.make(\"AroundRequests\", self, before, after)\n  ))\n\n/** @internal */\nexport const batchN = dual<\n  (n: number) => <A, R>(\n    self: RequestResolver.RequestResolver<A, R>\n  ) => RequestResolver.RequestResolver<A, R>,\n  <A, R>(\n    self: RequestResolver.RequestResolver<A, R>,\n    n: number\n  ) => RequestResolver.RequestResolver<A, R>\n>(2, <A, R>(\n  self: RequestResolver.RequestResolver<A, R>,\n  n: number\n): RequestResolver.RequestResolver<A, R> =>\n  new core.RequestResolverImpl(\n    (requests) => {\n      return n < 1\n        ? core.die(new Cause.IllegalArgumentException(\"RequestResolver.batchN: n must be at least 1\"))\n        : self.runAll(\n          Array.from(Chunk.map(\n            RA.reduce(\n              requests,\n              Chunk.empty<Chunk.Chunk<Request.Entry<A>>>(),\n              (acc, chunk) => Chunk.appendAll(acc, Chunk.chunksOf(Chunk.unsafeFromArray(chunk), n))\n            ),\n            (chunk) => Array.from(chunk)\n          ))\n        )\n    },\n    Chunk.make(\"BatchN\", self, n)\n  ))\n\n/** @internal */\nexport const mapInputContext = dual<\n  <R0, R>(\n    f: (context: Context.Context<R0>) => Context.Context<R>\n  ) => <A extends Request.Request<any, any>>(\n    self: RequestResolver.RequestResolver<A, R>\n  ) => RequestResolver.RequestResolver<A, R0>,\n  <R, A extends Request.Request<any, any>, R0>(\n    self: RequestResolver.RequestResolver<A, R>,\n    f: (context: Context.Context<R0>) => Context.Context<R>\n  ) => RequestResolver.RequestResolver<A, R0>\n>(2, <R, A extends Request.Request<any, any>, R0>(\n  self: RequestResolver.RequestResolver<A, R>,\n  f: (context: Context.Context<R0>) => Context.Context<R>\n) =>\n  new core.RequestResolverImpl<A, R0>(\n    (requests) =>\n      core.mapInputContext(\n        self.runAll(requests),\n        (context: Context.Context<R0>) => f(context)\n      ),\n    Chunk.make(\"MapInputContext\", self, f)\n  ))\n\n/** @internal */\nexport const eitherWith = dual<\n  <\n    A extends Request.Request<any, any>,\n    R2,\n    B extends Request.Request<any, any>,\n    C extends Request.Request<any, any>\n  >(\n    that: RequestResolver.RequestResolver<B, R2>,\n    f: (_: Request.Entry<C>) => Either.Either<Request.Entry<B>, Request.Entry<A>>\n  ) => <R>(\n    self: RequestResolver.RequestResolver<A, R>\n  ) => RequestResolver.RequestResolver<C, R | R2>,\n  <\n    R,\n    A extends Request.Request<any, any>,\n    R2,\n    B extends Request.Request<any, any>,\n    C extends Request.Request<any, any>\n  >(\n    self: RequestResolver.RequestResolver<A, R>,\n    that: RequestResolver.RequestResolver<B, R2>,\n    f: (_: Request.Entry<C>) => Either.Either<Request.Entry<B>, Request.Entry<A>>\n  ) => RequestResolver.RequestResolver<C, R | R2>\n>(3, <\n  R,\n  A extends Request.Request<any, any>,\n  R2,\n  B extends Request.Request<any, any>,\n  C extends Request.Request<any, any>\n>(\n  self: RequestResolver.RequestResolver<A, R>,\n  that: RequestResolver.RequestResolver<B, R2>,\n  f: (_: Request.Entry<C>) => Either.Either<Request.Entry<B>, Request.Entry<A>>\n) =>\n  new core.RequestResolverImpl<C, R | R2>(\n    (batch) =>\n      core.forEachSequential(batch, (requests) => {\n        const [as, bs] = pipe(\n          requests,\n          RA.partitionMap(f)\n        )\n        return zipWithOptions(\n          self.runAll(Array.of(as)),\n          that.runAll(Array.of(bs)),\n          () => void 0,\n          { concurrent: true }\n        )\n      }),\n    Chunk.make(\"EitherWith\", self, that, f)\n  ))\n\n/** @internal */\nexport const fromFunction = <A extends Request.Request<any>>(\n  f: (request: A) => Request.Request.Success<A>\n): RequestResolver.RequestResolver<A> =>\n  makeBatched((requests: RA.NonEmptyArray<A>) =>\n    core.forEachSequentialDiscard(\n      requests,\n      (request) => complete(request, core.exitSucceed(f(request)) as any)\n    )\n  ).identified(\"FromFunction\", f)\n\n/** @internal */\nexport const fromFunctionBatched = <A extends Request.Request<any>>(\n  f: (chunk: RA.NonEmptyArray<A>) => Iterable<Request.Request.Success<A>>\n): RequestResolver.RequestResolver<A> =>\n  makeBatched((as: RA.NonEmptyArray<A>) =>\n    Effect.forEach(\n      f(as),\n      (res, i) => complete(as[i], core.exitSucceed(res) as any),\n      { discard: true }\n    )\n  ).identified(\"FromFunctionBatched\", f)\n\n/** @internal */\nexport const fromEffect = <R, A extends Request.Request<any, any>>(\n  f: (a: A) => Effect.Effect<Request.Request.Success<A>, Request.Request.Error<A>, R>\n): RequestResolver.RequestResolver<A, R> =>\n  makeBatched((requests: RA.NonEmptyArray<A>) =>\n    Effect.forEach(\n      requests,\n      (a) => Effect.flatMap(Effect.exit(f(a)), (e) => complete(a, e as any)),\n      { concurrency: \"unbounded\", discard: true }\n    )\n  ).identified(\"FromEffect\", f)\n\n/** @internal */\nexport const fromEffectTagged = <\n  A extends Request.Request<any, any> & {\n    readonly _tag: string\n  }\n>() =>\n<\n  Fns extends {\n    readonly [Tag in A[\"_tag\"]]: [Extract<A, { readonly _tag: Tag }>] extends [infer Req] ?\n      Req extends Request.Request<infer ReqA, infer ReqE> ?\n        (requests: Array<Req>) => Effect.Effect<Iterable<ReqA>, ReqE, any>\n      : never\n      : never\n  }\n>(\n  fns: Fns\n): RequestResolver.RequestResolver<\n  A,\n  ReturnType<Fns[keyof Fns]> extends Effect.Effect<infer _A, infer _E, infer R> ? R : never\n> =>\n  makeBatched<A, any>((requests: RA.NonEmptyArray<A>) => {\n    const grouped: Record<string, Array<A>> = {}\n    const tags: Array<A[\"_tag\"]> = []\n    for (let i = 0, len = requests.length; i < len; i++) {\n      if (tags.includes(requests[i]._tag)) {\n        grouped[requests[i]._tag].push(requests[i])\n      } else {\n        grouped[requests[i]._tag] = [requests[i]]\n        tags.push(requests[i]._tag)\n      }\n    }\n    return Effect.forEach(\n      tags,\n      (tag) =>\n        Effect.matchCauseEffect((fns[tag] as any)(grouped[tag]) as Effect.Effect<Array<any>, unknown, unknown>, {\n          onFailure: (cause) =>\n            Effect.forEach(grouped[tag], (req) => complete(req, core.exitFail(cause) as any), { discard: true }),\n          onSuccess: (res) =>\n            Effect.forEach(grouped[tag], (req, i) => complete(req, core.exitSucceed(res[i]) as any), { discard: true })\n        }),\n      { concurrency: \"unbounded\", discard: true }\n    )\n  }).identified(\"FromEffectTagged\", fns)\n\n/** @internal */\nexport const never: RequestResolver.RequestResolver<never> = make(() => Effect.never).identified(\"Never\")\n\n/** @internal */\nexport const provideContext = dual<\n  <R>(\n    context: Context.Context<R>\n  ) => <A extends Request.Request<any, any>>(\n    self: RequestResolver.RequestResolver<A, R>\n  ) => RequestResolver.RequestResolver<A>,\n  <R, A extends Request.Request<any, any>>(\n    self: RequestResolver.RequestResolver<A, R>,\n    context: Context.Context<R>\n  ) => RequestResolver.RequestResolver<A>\n>(2, (self, context) =>\n  mapInputContext(\n    self,\n    (_: Context.Context<never>) => context\n  ).identified(\"ProvideContext\", self, context))\n\n/** @internal */\nexport const race = dual<\n  <A2 extends Request.Request<any, any>, R2>(\n    that: RequestResolver.RequestResolver<A2, R2>\n  ) => <A extends Request.Request<any, any>, R>(\n    self: RequestResolver.RequestResolver<A, R>\n  ) => RequestResolver.RequestResolver<A | A2, R | R2>,\n  <A extends Request.Request<any, any>, R, A2 extends Request.Request<any, any>, R2>(\n    self: RequestResolver.RequestResolver<A, R>,\n    that: RequestResolver.RequestResolver<A2, R2>\n  ) => RequestResolver.RequestResolver<A | A2, R | R2>\n>(2, <A, R, A2, R2>(\n  self: RequestResolver.RequestResolver<A, R>,\n  that: RequestResolver.RequestResolver<A2, R2>\n) =>\n  new core.RequestResolverImpl((requests) =>\n    Effect.race(\n      self.runAll(requests as Array<Array<Request.Entry<A>>>),\n      that.runAll(requests as Array<Array<Request.Entry<A2>>>)\n    )\n  ).identified(\"Race\", self, that))\n"
  },
  {
    "path": "packages/effect/src/internal/dateTime.ts",
    "content": "import { IllegalArgumentException } from \"../Cause.js\"\nimport * as Clock from \"../Clock.js\"\nimport type * as DateTime from \"../DateTime.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport * as Equal from \"../Equal.js\"\nimport * as equivalence from \"../Equivalence.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport * as Hash from \"../Hash.js\"\nimport * as Inspectable from \"../Inspectable.js\"\nimport * as Option from \"../Option.js\"\nimport * as order from \"../Order.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport * as Predicate from \"../Predicate.js\"\nimport type { Mutable } from \"../Types.js\"\nimport * as internalEffect from \"./core-effect.js\"\nimport * as core from \"./core.js\"\n\n/** @internal */\nexport const TypeId: DateTime.TypeId = Symbol.for(\"effect/DateTime\") as DateTime.TypeId\n\n/** @internal */\nexport const TimeZoneTypeId: DateTime.TimeZoneTypeId = Symbol.for(\"effect/DateTime/TimeZone\") as DateTime.TimeZoneTypeId\n\nconst Proto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  [Inspectable.NodeInspectSymbol](this: DateTime.DateTime) {\n    return this.toString()\n  },\n  toJSON(this: DateTime.DateTime) {\n    return toDateUtc(this).toJSON()\n  }\n}\n\nconst ProtoUtc = {\n  ...Proto,\n  _tag: \"Utc\",\n  [Hash.symbol](this: DateTime.Utc) {\n    return Hash.cached(this, Hash.number(this.epochMillis))\n  },\n  [Equal.symbol](this: DateTime.Utc, that: unknown) {\n    return isDateTime(that) && that._tag === \"Utc\" && this.epochMillis === that.epochMillis\n  },\n  toString(this: DateTime.Utc) {\n    return `DateTime.Utc(${toDateUtc(this).toJSON()})`\n  }\n}\n\nconst ProtoZoned = {\n  ...Proto,\n  _tag: \"Zoned\",\n  [Hash.symbol](this: DateTime.Zoned) {\n    return pipe(\n      Hash.number(this.epochMillis),\n      Hash.combine(Hash.hash(this.zone)),\n      Hash.cached(this)\n    )\n  },\n  [Equal.symbol](this: DateTime.Zoned, that: unknown) {\n    return isDateTime(that) && that._tag === \"Zoned\" && this.epochMillis === that.epochMillis &&\n      Equal.equals(this.zone, that.zone)\n  },\n  toString(this: DateTime.Zoned) {\n    return `DateTime.Zoned(${formatIsoZoned(this)})`\n  }\n}\n\nconst ProtoTimeZone = {\n  [TimeZoneTypeId]: TimeZoneTypeId,\n  [Inspectable.NodeInspectSymbol](this: DateTime.TimeZone) {\n    return this.toString()\n  }\n}\n\nconst ProtoTimeZoneNamed = {\n  ...ProtoTimeZone,\n  _tag: \"Named\",\n  [Hash.symbol](this: DateTime.TimeZone.Named) {\n    return Hash.cached(this, Hash.string(`Named:${this.id}`))\n  },\n  [Equal.symbol](this: DateTime.TimeZone.Named, that: unknown) {\n    return isTimeZone(that) && that._tag === \"Named\" && this.id === that.id\n  },\n  toString(this: DateTime.TimeZone.Named) {\n    return `TimeZone.Named(${this.id})`\n  },\n  toJSON(this: DateTime.TimeZone.Named) {\n    return {\n      _id: \"TimeZone\",\n      _tag: \"Named\",\n      id: this.id\n    }\n  }\n}\n\nconst ProtoTimeZoneOffset = {\n  ...ProtoTimeZone,\n  _tag: \"Offset\",\n  [Hash.symbol](this: DateTime.TimeZone.Offset) {\n    return Hash.cached(this, Hash.string(`Offset:${this.offset}`))\n  },\n  [Equal.symbol](this: DateTime.TimeZone.Offset, that: unknown) {\n    return isTimeZone(that) && that._tag === \"Offset\" && this.offset === that.offset\n  },\n  toString(this: DateTime.TimeZone.Offset) {\n    return `TimeZone.Offset(${offsetToString(this.offset)})`\n  },\n  toJSON(this: DateTime.TimeZone.Offset) {\n    return {\n      _id: \"TimeZone\",\n      _tag: \"Offset\",\n      offset: this.offset\n    }\n  }\n}\n\n/** @internal */\nexport const makeZonedProto = (\n  epochMillis: number,\n  zone: DateTime.TimeZone,\n  partsUtc?: DateTime.DateTime.PartsWithWeekday\n): DateTime.Zoned => {\n  const self = Object.create(ProtoZoned)\n  self.epochMillis = epochMillis\n  self.zone = zone\n  Object.defineProperty(self, \"partsUtc\", {\n    value: partsUtc,\n    enumerable: false,\n    writable: true\n  })\n  Object.defineProperty(self, \"adjustedEpochMillis\", {\n    value: undefined,\n    enumerable: false,\n    writable: true\n  })\n  Object.defineProperty(self, \"partsAdjusted\", {\n    value: undefined,\n    enumerable: false,\n    writable: true\n  })\n  return self\n}\n\n// =============================================================================\n// guards\n// =============================================================================\n\n/** @internal */\nexport const isDateTime = (u: unknown): u is DateTime.DateTime => Predicate.hasProperty(u, TypeId)\n\nconst isDateTimeArgs = (args: IArguments) => isDateTime(args[0])\n\n/** @internal */\nexport const isTimeZone = (u: unknown): u is DateTime.TimeZone => Predicate.hasProperty(u, TimeZoneTypeId)\n\n/** @internal */\nexport const isTimeZoneOffset = (u: unknown): u is DateTime.TimeZone.Offset => isTimeZone(u) && u._tag === \"Offset\"\n\n/** @internal */\nexport const isTimeZoneNamed = (u: unknown): u is DateTime.TimeZone.Named => isTimeZone(u) && u._tag === \"Named\"\n\n/** @internal */\nexport const isUtc = (self: DateTime.DateTime): self is DateTime.Utc => self._tag === \"Utc\"\n\n/** @internal */\nexport const isZoned = (self: DateTime.DateTime): self is DateTime.Zoned => self._tag === \"Zoned\"\n\n// =============================================================================\n// instances\n// =============================================================================\n\n/** @internal */\nexport const Equivalence: equivalence.Equivalence<DateTime.DateTime> = equivalence.make((a, b) =>\n  a.epochMillis === b.epochMillis\n)\n\n/** @internal */\nexport const Order: order.Order<DateTime.DateTime> = order.make((self, that) =>\n  self.epochMillis < that.epochMillis ? -1 : self.epochMillis > that.epochMillis ? 1 : 0\n)\n\n/** @internal */\nexport const clamp: {\n  <Min extends DateTime.DateTime, Max extends DateTime.DateTime>(\n    options: { readonly minimum: Min; readonly maximum: Max }\n  ): <A extends DateTime.DateTime>(self: A) => A | Min | Max\n  <A extends DateTime.DateTime, Min extends DateTime.DateTime, Max extends DateTime.DateTime>(\n    self: A,\n    options: { readonly minimum: Min; readonly maximum: Max }\n  ): A | Min | Max\n} = order.clamp(Order)\n\n// =============================================================================\n// constructors\n// =============================================================================\n\nconst makeUtc = (epochMillis: number): DateTime.Utc => {\n  const self = Object.create(ProtoUtc)\n  self.epochMillis = epochMillis\n  Object.defineProperty(self, \"partsUtc\", {\n    value: undefined,\n    enumerable: false,\n    writable: true\n  })\n  return self\n}\n\n/** @internal */\nexport const unsafeFromDate = (date: Date): DateTime.Utc => {\n  const epochMillis = date.getTime()\n  if (Number.isNaN(epochMillis)) {\n    throw new IllegalArgumentException(\"Invalid date\")\n  }\n  return makeUtc(epochMillis)\n}\n\n/** @internal */\nexport const unsafeMake = <A extends DateTime.DateTime.Input>(input: A): DateTime.DateTime.PreserveZone<A> => {\n  if (isDateTime(input)) {\n    return input as DateTime.DateTime.PreserveZone<A>\n  } else if (input instanceof Date) {\n    return unsafeFromDate(input) as DateTime.DateTime.PreserveZone<A>\n  } else if (typeof input === \"object\") {\n    const date = new Date(0)\n    setPartsDate(date, input)\n    return unsafeFromDate(date) as DateTime.DateTime.PreserveZone<A>\n  } else if (typeof input === \"string\" && !hasZone(input)) {\n    return unsafeFromDate(new Date(input + \"Z\")) as DateTime.DateTime.PreserveZone<A>\n  }\n  return unsafeFromDate(new Date(input)) as DateTime.DateTime.PreserveZone<A>\n}\n\nconst hasZone = (input: string): boolean => /Z|[+-]\\d{2}$|[+-]\\d{2}:?\\d{2}$|\\]$/.test(input)\n\nconst minEpochMillis = -8640000000000000 + (12 * 60 * 60 * 1000)\nconst maxEpochMillis = 8640000000000000 - (14 * 60 * 60 * 1000)\n\n/** @internal */\nexport const unsafeMakeZoned = (input: DateTime.DateTime.Input, options?: {\n  readonly timeZone?: number | string | DateTime.TimeZone | undefined\n  readonly adjustForTimeZone?: boolean | undefined\n  readonly disambiguation?: DateTime.Disambiguation | undefined\n}): DateTime.Zoned => {\n  if (options?.timeZone === undefined && isDateTime(input) && isZoned(input)) {\n    return input\n  }\n  const self = unsafeMake(input)\n  if (self.epochMillis < minEpochMillis || self.epochMillis > maxEpochMillis) {\n    throw new RangeError(`Epoch millis out of range: ${self.epochMillis}`)\n  }\n  let zone: DateTime.TimeZone\n  if (options?.timeZone === undefined) {\n    const offset = new Date(self.epochMillis).getTimezoneOffset() * -60 * 1000\n    zone = zoneMakeOffset(offset)\n  } else if (isTimeZone(options?.timeZone)) {\n    zone = options.timeZone\n  } else if (typeof options?.timeZone === \"number\") {\n    zone = zoneMakeOffset(options.timeZone)\n  } else {\n    const parsedZone = zoneFromString(options.timeZone)\n    if (Option.isNone(parsedZone)) {\n      throw new IllegalArgumentException(`Invalid time zone: ${options.timeZone}`)\n    }\n    zone = parsedZone.value\n  }\n  if (options?.adjustForTimeZone !== true) {\n    return makeZonedProto(self.epochMillis, zone, self.partsUtc)\n  }\n  return makeZonedFromAdjusted(self.epochMillis, zone, options?.disambiguation ?? \"compatible\")\n}\n\n/** @internal */\nexport const makeZoned: (\n  input: DateTime.DateTime.Input,\n  options?: {\n    readonly timeZone?: number | string | DateTime.TimeZone | undefined\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }\n) => Option.Option<DateTime.Zoned> = Option.liftThrowable(unsafeMakeZoned)\n\n/** @internal */\nexport const make: <A extends DateTime.DateTime.Input>(input: A) => Option.Option<DateTime.DateTime.PreserveZone<A>> =\n  Option.liftThrowable(unsafeMake)\n\nconst zonedStringRegex = /^(.{17,35})\\[(.+)\\]$/\n\n/** @internal */\nexport const makeZonedFromString = (input: string): Option.Option<DateTime.Zoned> => {\n  const match = zonedStringRegex.exec(input)\n  if (match === null) {\n    const offset = parseOffset(input)\n    return offset !== null ? makeZoned(input, { timeZone: offset }) : Option.none()\n  }\n  const [, isoString, timeZone] = match\n  return makeZoned(isoString, { timeZone })\n}\n\n/** @internal */\nexport const now: Effect.Effect<DateTime.Utc> = core.map(Clock.currentTimeMillis, makeUtc)\n\n/** @internal */\nexport const nowAsDate: Effect.Effect<Date> = core.map(Clock.currentTimeMillis, (millis) => new Date(millis))\n\n/** @internal */\nexport const unsafeNow: LazyArg<DateTime.Utc> = () => makeUtc(Date.now())\n\n// =============================================================================\n// time zones\n// =============================================================================\n\n/** @internal */\nexport const toUtc = (self: DateTime.DateTime): DateTime.Utc => makeUtc(self.epochMillis)\n\n/** @internal */\nexport const setZone: {\n  (zone: DateTime.TimeZone, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): (self: DateTime.DateTime) => DateTime.Zoned\n  (self: DateTime.DateTime, zone: DateTime.TimeZone, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): DateTime.Zoned\n} = dual(isDateTimeArgs, (self: DateTime.DateTime, zone: DateTime.TimeZone, options?: {\n  readonly adjustForTimeZone?: boolean | undefined\n  readonly disambiguation?: DateTime.Disambiguation | undefined\n}): DateTime.Zoned =>\n  options?.adjustForTimeZone === true\n    ? makeZonedFromAdjusted(self.epochMillis, zone, options?.disambiguation ?? \"compatible\")\n    : makeZonedProto(self.epochMillis, zone, self.partsUtc))\n\n/** @internal */\nexport const setZoneOffset: {\n  (offset: number, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): (self: DateTime.DateTime) => DateTime.Zoned\n  (self: DateTime.DateTime, offset: number, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): DateTime.Zoned\n} = dual(isDateTimeArgs, (self: DateTime.DateTime, offset: number, options?: {\n  readonly adjustForTimeZone?: boolean | undefined\n  readonly disambiguation?: DateTime.Disambiguation | undefined\n}): DateTime.Zoned => setZone(self, zoneMakeOffset(offset), options))\n\nconst validZoneCache = globalValue(\"effect/DateTime/validZoneCache\", () => new Map<string, DateTime.TimeZone.Named>())\n\nconst formatOptions: Intl.DateTimeFormatOptions = {\n  day: \"numeric\",\n  month: \"numeric\",\n  year: \"numeric\",\n  hour: \"numeric\",\n  minute: \"numeric\",\n  second: \"numeric\",\n  timeZoneName: \"longOffset\",\n  fractionalSecondDigits: 3,\n  hourCycle: \"h23\"\n}\n\nconst zoneMakeIntl = (format: Intl.DateTimeFormat): DateTime.TimeZone.Named => {\n  const zoneId = format.resolvedOptions().timeZone\n  if (validZoneCache.has(zoneId)) {\n    return validZoneCache.get(zoneId)!\n  }\n  const zone = Object.create(ProtoTimeZoneNamed)\n  zone.id = zoneId\n  zone.format = format\n  validZoneCache.set(zoneId, zone)\n  return zone\n}\n\n/** @internal */\nexport const zoneUnsafeMakeNamed = (zoneId: string): DateTime.TimeZone.Named => {\n  if (validZoneCache.has(zoneId)) {\n    return validZoneCache.get(zoneId)!\n  }\n  try {\n    return zoneMakeIntl(\n      new Intl.DateTimeFormat(\"en-US\", {\n        ...formatOptions,\n        timeZone: zoneId\n      })\n    )\n  } catch {\n    throw new IllegalArgumentException(`Invalid time zone: ${zoneId}`)\n  }\n}\n\n/** @internal */\nexport const zoneMakeOffset = (offset: number): DateTime.TimeZone.Offset => {\n  const zone = Object.create(ProtoTimeZoneOffset)\n  zone.offset = offset\n  return zone\n}\n\n/** @internal */\nexport const zoneMakeNamed: (zoneId: string) => Option.Option<DateTime.TimeZone.Named> = Option.liftThrowable(\n  zoneUnsafeMakeNamed\n)\n\n/** @internal */\nexport const zoneMakeNamedEffect = (zoneId: string): Effect.Effect<DateTime.TimeZone.Named, IllegalArgumentException> =>\n  internalEffect.try_({\n    try: () => zoneUnsafeMakeNamed(zoneId),\n    catch: (e) => e as IllegalArgumentException\n  })\n\n/** @internal */\nexport const zoneMakeLocal = (): DateTime.TimeZone.Named =>\n  zoneMakeIntl(new Intl.DateTimeFormat(\"en-US\", formatOptions))\n\nconst offsetZoneRegex = /^(?:GMT|[+-])/\n\n/** @internal */\nexport const zoneFromString = (zone: string): Option.Option<DateTime.TimeZone> => {\n  if (offsetZoneRegex.test(zone)) {\n    const offset = parseOffset(zone)\n    return offset === null ? Option.none() : Option.some(zoneMakeOffset(offset))\n  }\n  return zoneMakeNamed(zone)\n}\n\n/** @internal */\nexport const zoneToString = (self: DateTime.TimeZone): string => {\n  if (self._tag === \"Offset\") {\n    return offsetToString(self.offset)\n  }\n  return self.id\n}\n\n/** @internal */\nexport const setZoneNamed: {\n  (zoneId: string, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): (self: DateTime.DateTime) => Option.Option<DateTime.Zoned>\n  (self: DateTime.DateTime, zoneId: string, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): Option.Option<DateTime.Zoned>\n} = dual(\n  isDateTimeArgs,\n  (self: DateTime.DateTime, zoneId: string, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): Option.Option<DateTime.Zoned> => Option.map(zoneMakeNamed(zoneId), (zone) => setZone(self, zone, options))\n)\n\n/** @internal */\nexport const unsafeSetZoneNamed: {\n  (zoneId: string, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): (self: DateTime.DateTime) => DateTime.Zoned\n  (self: DateTime.DateTime, zoneId: string, options?: {\n    readonly adjustForTimeZone?: boolean | undefined\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): DateTime.Zoned\n} = dual(isDateTimeArgs, (self: DateTime.DateTime, zoneId: string, options?: {\n  readonly adjustForTimeZone?: boolean | undefined\n  readonly disambiguation?: DateTime.Disambiguation | undefined\n}): DateTime.Zoned => setZone(self, zoneUnsafeMakeNamed(zoneId), options))\n\n// =============================================================================\n// comparisons\n// =============================================================================\n\n/** @internal */\nexport const distance: {\n  (other: DateTime.DateTime): (self: DateTime.DateTime) => number\n  (self: DateTime.DateTime, other: DateTime.DateTime): number\n} = dual(2, (self: DateTime.DateTime, other: DateTime.DateTime): number => toEpochMillis(other) - toEpochMillis(self))\n\n/** @internal */\nexport const distanceDurationEither: {\n  (other: DateTime.DateTime): (self: DateTime.DateTime) => Either.Either<Duration.Duration, Duration.Duration>\n  (self: DateTime.DateTime, other: DateTime.DateTime): Either.Either<Duration.Duration, Duration.Duration>\n} = dual(\n  2,\n  (self: DateTime.DateTime, other: DateTime.DateTime): Either.Either<Duration.Duration, Duration.Duration> => {\n    const diffMillis = distance(self, other)\n    return diffMillis > 0\n      ? Either.right(Duration.millis(diffMillis))\n      : Either.left(Duration.millis(-diffMillis))\n  }\n)\n\n/** @internal */\nexport const distanceDuration: {\n  (other: DateTime.DateTime): (self: DateTime.DateTime) => Duration.Duration\n  (self: DateTime.DateTime, other: DateTime.DateTime): Duration.Duration\n} = dual(\n  2,\n  (self: DateTime.DateTime, other: DateTime.DateTime): Duration.Duration =>\n    Duration.millis(Math.abs(distance(self, other)))\n)\n\n/** @internal */\nexport const min: {\n  <That extends DateTime.DateTime>(that: That): <Self extends DateTime.DateTime>(self: Self) => Self | That\n  <Self extends DateTime.DateTime, That extends DateTime.DateTime>(self: Self, that: That): Self | That\n} = order.min(Order)\n\n/** @internal */\nexport const max: {\n  <That extends DateTime.DateTime>(that: That): <Self extends DateTime.DateTime>(self: Self) => Self | That\n  <Self extends DateTime.DateTime, That extends DateTime.DateTime>(self: Self, that: That): Self | That\n} = order.max(Order)\n\n/** @internal */\nexport const greaterThan: {\n  (that: DateTime.DateTime): (self: DateTime.DateTime) => boolean\n  (self: DateTime.DateTime, that: DateTime.DateTime): boolean\n} = order.greaterThan(Order)\n\n/** @internal */\nexport const greaterThanOrEqualTo: {\n  (that: DateTime.DateTime): (self: DateTime.DateTime) => boolean\n  (self: DateTime.DateTime, that: DateTime.DateTime): boolean\n} = order.greaterThanOrEqualTo(Order)\n\n/** @internal */\nexport const lessThan: {\n  (that: DateTime.DateTime): (self: DateTime.DateTime) => boolean\n  (self: DateTime.DateTime, that: DateTime.DateTime): boolean\n} = order.lessThan(Order)\n\n/** @internal */\nexport const lessThanOrEqualTo: {\n  (that: DateTime.DateTime): (self: DateTime.DateTime) => boolean\n  (self: DateTime.DateTime, that: DateTime.DateTime): boolean\n} = order.lessThanOrEqualTo(Order)\n\n/** @internal */\nexport const between: {\n  (options: { minimum: DateTime.DateTime; maximum: DateTime.DateTime }): (self: DateTime.DateTime) => boolean\n  (self: DateTime.DateTime, options: { minimum: DateTime.DateTime; maximum: DateTime.DateTime }): boolean\n} = order.between(Order)\n\n/** @internal */\nexport const isFuture = (self: DateTime.DateTime): Effect.Effect<boolean> => core.map(now, lessThan(self))\n\n/** @internal */\nexport const unsafeIsFuture = (self: DateTime.DateTime): boolean => lessThan(unsafeNow(), self)\n\n/** @internal */\nexport const isPast = (self: DateTime.DateTime): Effect.Effect<boolean> => core.map(now, greaterThan(self))\n\n/** @internal */\nexport const unsafeIsPast = (self: DateTime.DateTime): boolean => greaterThan(unsafeNow(), self)\n\n// =============================================================================\n// conversions\n// =============================================================================\n\n/** @internal */\nexport const toDateUtc = (self: DateTime.DateTime): Date => new Date(self.epochMillis)\n\n/** @internal */\nexport const toDate = (self: DateTime.DateTime): Date => {\n  if (self._tag === \"Utc\") {\n    return new Date(self.epochMillis)\n  } else if (self.zone._tag === \"Offset\") {\n    return new Date(self.epochMillis + self.zone.offset)\n  } else if (self.adjustedEpochMillis !== undefined) {\n    return new Date(self.adjustedEpochMillis)\n  }\n  const parts = self.zone.format.formatToParts(self.epochMillis).filter((_) => _.type !== \"literal\")\n  const date = new Date(0)\n  date.setUTCFullYear(\n    Number(parts[2].value),\n    Number(parts[0].value) - 1,\n    Number(parts[1].value)\n  )\n  date.setUTCHours(\n    Number(parts[3].value),\n    Number(parts[4].value),\n    Number(parts[5].value),\n    Number(parts[6].value)\n  )\n  self.adjustedEpochMillis = date.getTime()\n  return date\n}\n\n/** @internal */\nexport const zonedOffset = (self: DateTime.Zoned): number => {\n  const date = toDate(self)\n  return date.getTime() - toEpochMillis(self)\n}\n\nconst offsetToString = (offset: number): string => {\n  const abs = Math.abs(offset)\n  let hours = Math.floor(abs / (60 * 60 * 1000))\n  let minutes = Math.round((abs % (60 * 60 * 1000)) / (60 * 1000))\n  if (minutes === 60) {\n    hours += 1\n    minutes = 0\n  }\n  return `${offset < 0 ? \"-\" : \"+\"}${String(hours).padStart(2, \"0\")}:${String(minutes).padStart(2, \"0\")}`\n}\n\n/** @internal */\nexport const zonedOffsetIso = (self: DateTime.Zoned): string => offsetToString(zonedOffset(self))\n\n/** @internal */\nexport const toEpochMillis = (self: DateTime.DateTime): number => self.epochMillis\n\n/** @internal */\nexport const removeTime = (self: DateTime.DateTime): DateTime.Utc =>\n  withDate(self, (date) => {\n    date.setUTCHours(0, 0, 0, 0)\n    return makeUtc(date.getTime())\n  })\n\n// =============================================================================\n// parts\n// =============================================================================\n\nconst dateToParts = (date: Date): DateTime.DateTime.PartsWithWeekday => ({\n  millis: date.getUTCMilliseconds(),\n  seconds: date.getUTCSeconds(),\n  minutes: date.getUTCMinutes(),\n  hours: date.getUTCHours(),\n  day: date.getUTCDate(),\n  weekDay: date.getUTCDay(),\n  month: date.getUTCMonth() + 1,\n  year: date.getUTCFullYear()\n})\n\n/** @internal */\nexport const toParts = (self: DateTime.DateTime): DateTime.DateTime.PartsWithWeekday => {\n  if (self._tag === \"Utc\") {\n    return toPartsUtc(self)\n  } else if (self.partsAdjusted !== undefined) {\n    return self.partsAdjusted\n  }\n  self.partsAdjusted = withDate(self, dateToParts)\n  return self.partsAdjusted\n}\n\n/** @internal */\nexport const toPartsUtc = (self: DateTime.DateTime): DateTime.DateTime.PartsWithWeekday => {\n  if (self.partsUtc !== undefined) {\n    return self.partsUtc\n  }\n  self.partsUtc = withDateUtc(self, dateToParts)\n  return self.partsUtc\n}\n\n/** @internal */\nexport const getPartUtc: {\n  (part: keyof DateTime.DateTime.PartsWithWeekday): (self: DateTime.DateTime) => number\n  (self: DateTime.DateTime, part: keyof DateTime.DateTime.PartsWithWeekday): number\n} = dual(2, (self: DateTime.DateTime, part: keyof DateTime.DateTime.PartsWithWeekday): number => toPartsUtc(self)[part])\n\n/** @internal */\nexport const getPart: {\n  (part: keyof DateTime.DateTime.PartsWithWeekday): (self: DateTime.DateTime) => number\n  (self: DateTime.DateTime, part: keyof DateTime.DateTime.PartsWithWeekday): number\n} = dual(2, (self: DateTime.DateTime, part: keyof DateTime.DateTime.PartsWithWeekday): number => toParts(self)[part])\n\nconst setPartsDate = (date: Date, parts: Partial<DateTime.DateTime.PartsWithWeekday>): void => {\n  if (parts.year !== undefined) {\n    date.setUTCFullYear(parts.year)\n  }\n  if (parts.month !== undefined) {\n    date.setUTCMonth(parts.month - 1)\n  }\n  if (parts.day !== undefined) {\n    date.setUTCDate(parts.day)\n  }\n  if (parts.weekDay !== undefined) {\n    const diff = parts.weekDay - date.getUTCDay()\n    date.setUTCDate(date.getUTCDate() + diff)\n  }\n  if (parts.hours !== undefined) {\n    date.setUTCHours(parts.hours)\n  }\n  if (parts.minutes !== undefined) {\n    date.setUTCMinutes(parts.minutes)\n  }\n  if (parts.seconds !== undefined) {\n    date.setUTCSeconds(parts.seconds)\n  }\n  if (parts.millis !== undefined) {\n    date.setUTCMilliseconds(parts.millis)\n  }\n}\n\n/** @internal */\nexport const setParts: {\n  (\n    parts: Partial<DateTime.DateTime.PartsWithWeekday>\n  ): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(\n    self: A,\n    parts: Partial<DateTime.DateTime.PartsWithWeekday>\n  ): A\n} = dual(\n  2,\n  (self: DateTime.DateTime, parts: Partial<DateTime.DateTime.PartsWithWeekday>): DateTime.DateTime =>\n    mutate(self, (date) => setPartsDate(date, parts))\n)\n\n/** @internal */\nexport const setPartsUtc: {\n  (\n    parts: Partial<DateTime.DateTime.PartsWithWeekday>\n  ): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(\n    self: A,\n    parts: Partial<DateTime.DateTime.PartsWithWeekday>\n  ): A\n} = dual(\n  2,\n  (self: DateTime.DateTime, parts: Partial<DateTime.DateTime.PartsWithWeekday>): DateTime.DateTime =>\n    mutateUtc(self, (date) => setPartsDate(date, parts))\n)\n\n// =============================================================================\n// mapping\n// =============================================================================\n\nconst constDayMillis = 24 * 60 * 60 * 1000\n\nconst makeZonedFromAdjusted = (\n  adjustedMillis: number,\n  zone: DateTime.TimeZone,\n  disambiguation: DateTime.Disambiguation\n): DateTime.Zoned => {\n  if (zone._tag === \"Offset\") {\n    return makeZonedProto(adjustedMillis - zone.offset, zone)\n  }\n  const beforeOffset = calculateNamedOffset(\n    adjustedMillis - constDayMillis,\n    adjustedMillis,\n    zone\n  )\n  const afterOffset = calculateNamedOffset(\n    adjustedMillis + constDayMillis,\n    adjustedMillis,\n    zone\n  )\n  // If there is no transition, we can return early\n  if (beforeOffset === afterOffset) {\n    return makeZonedProto(adjustedMillis - beforeOffset, zone)\n  }\n  const isForwards = beforeOffset < afterOffset\n  const transitionMillis = beforeOffset - afterOffset\n  // If the transition is forwards, we only need to check if we should move the\n  // local wall clock time forward if it is inside the gap\n  if (isForwards) {\n    const currentAfterOffset = calculateNamedOffset(\n      adjustedMillis - afterOffset,\n      adjustedMillis,\n      zone\n    )\n    if (currentAfterOffset === afterOffset) {\n      return makeZonedProto(adjustedMillis - afterOffset, zone)\n    }\n    const before = makeZonedProto(adjustedMillis - beforeOffset, zone)\n    const beforeAdjustedMillis = toDate(before).getTime()\n    // If the wall clock time has changed, we are inside the gap\n    if (adjustedMillis !== beforeAdjustedMillis) {\n      switch (disambiguation) {\n        case \"reject\": {\n          const formatted = new Date(adjustedMillis).toISOString()\n          throw new RangeError(`Gap time: ${formatted} does not exist in time zone ${zone.id}`)\n        }\n        case \"earlier\":\n          return makeZonedProto(adjustedMillis - afterOffset, zone)\n\n        case \"compatible\":\n        case \"later\":\n          return before\n      }\n    }\n    // The wall clock time is in the earlier offset, so we use that\n    return before\n  }\n\n  const currentBeforeOffset = calculateNamedOffset(\n    adjustedMillis - beforeOffset,\n    adjustedMillis,\n    zone\n  )\n  // The wall clock time is in the earlier offset, so we use that\n  if (currentBeforeOffset === beforeOffset) {\n    if (disambiguation === \"earlier\" || disambiguation === \"compatible\") {\n      return makeZonedProto(adjustedMillis - beforeOffset, zone)\n    }\n    const laterOffset = calculateNamedOffset(\n      adjustedMillis - beforeOffset + transitionMillis,\n      adjustedMillis + transitionMillis,\n      zone\n    )\n    if (laterOffset === beforeOffset) {\n      return makeZonedProto(adjustedMillis - beforeOffset, zone)\n    }\n    // If the offset changed in this period, then we are inside the period where\n    // the wall clock time occurs twice, once in the earlier offset and once in\n    // the later offset.\n    if (disambiguation === \"reject\") {\n      const formatted = new Date(adjustedMillis).toISOString()\n      throw new RangeError(`Ambiguous time: ${formatted} occurs twice in time zone ${zone.id}`)\n    }\n    // If the disambiguation is \"later\", we return the later offset below\n  }\n  return makeZonedProto(adjustedMillis - afterOffset, zone)\n}\n\nconst offsetRegex = /([+-])(\\d{2}):(\\d{2})$/\nconst parseOffset = (offset: string): number | null => {\n  const match = offsetRegex.exec(offset)\n  if (match === null) {\n    return null\n  }\n  const [, sign, hours, minutes] = match\n  return (sign === \"+\" ? 1 : -1) * (Number(hours) * 60 + Number(minutes)) * 60 * 1000\n}\n\nconst calculateNamedOffset = (\n  utcMillis: number,\n  adjustedMillis: number,\n  zone: DateTime.TimeZone.Named\n): number => {\n  const offset = zone.format.formatToParts(utcMillis).find((_) => _.type === \"timeZoneName\")?.value ?? \"\"\n  if (offset === \"GMT\") {\n    return 0\n  }\n  const result = parseOffset(offset)\n  if (result === null) {\n    // fallback to using the adjusted date\n    return zonedOffset(makeZonedProto(adjustedMillis, zone))\n  }\n  return result\n}\n\n/** @internal */\nexport const mutate: {\n  (f: (date: Date) => void, options?: {\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(self: A, f: (date: Date) => void, options?: {\n    readonly disambiguation?: DateTime.Disambiguation | undefined\n  }): A\n} = dual(isDateTimeArgs, (self: DateTime.DateTime, f: (date: Date) => void, options?: {\n  readonly disambiguation?: DateTime.Disambiguation | undefined\n}): DateTime.DateTime => {\n  if (self._tag === \"Utc\") {\n    const date = toDateUtc(self)\n    f(date)\n    return makeUtc(date.getTime())\n  }\n  const adjustedDate = toDate(self)\n  const newAdjustedDate = new Date(adjustedDate.getTime())\n  f(newAdjustedDate)\n  return makeZonedFromAdjusted(newAdjustedDate.getTime(), self.zone, options?.disambiguation ?? \"compatible\")\n})\n\n/** @internal */\nexport const mutateUtc: {\n  (f: (date: Date) => void): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(self: A, f: (date: Date) => void): A\n} = dual(2, (self: DateTime.DateTime, f: (date: Date) => void): DateTime.DateTime =>\n  mapEpochMillis(self, (millis) => {\n    const date = new Date(millis)\n    f(date)\n    return date.getTime()\n  }))\n\n/** @internal */\nexport const mapEpochMillis: {\n  (f: (millis: number) => number): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(self: A, f: (millis: number) => number): A\n} = dual(2, (self: DateTime.DateTime, f: (millis: number) => number): DateTime.DateTime => {\n  const millis = f(toEpochMillis(self))\n  return self._tag === \"Utc\" ? makeUtc(millis) : makeZonedProto(millis, self.zone)\n})\n\n/** @internal */\nexport const withDate: {\n  <A>(f: (date: Date) => A): (self: DateTime.DateTime) => A\n  <A>(self: DateTime.DateTime, f: (date: Date) => A): A\n} = dual(2, <A>(self: DateTime.DateTime, f: (date: Date) => A): A => f(toDate(self)))\n\n/** @internal */\nexport const withDateUtc: {\n  <A>(f: (date: Date) => A): (self: DateTime.DateTime) => A\n  <A>(self: DateTime.DateTime, f: (date: Date) => A): A\n} = dual(2, <A>(self: DateTime.DateTime, f: (date: Date) => A): A => f(toDateUtc(self)))\n\n/** @internal */\nexport const match: {\n  <A, B>(options: {\n    readonly onUtc: (_: DateTime.Utc) => A\n    readonly onZoned: (_: DateTime.Zoned) => B\n  }): (self: DateTime.DateTime) => A | B\n  <A, B>(self: DateTime.DateTime, options: {\n    readonly onUtc: (_: DateTime.Utc) => A\n    readonly onZoned: (_: DateTime.Zoned) => B\n  }): A | B\n} = dual(2, <A, B>(self: DateTime.DateTime, options: {\n  readonly onUtc: (_: DateTime.Utc) => A\n  readonly onZoned: (_: DateTime.Zoned) => B\n}): A | B => self._tag === \"Utc\" ? options.onUtc(self) : options.onZoned(self))\n\n// =============================================================================\n// math\n// =============================================================================\n\n/** @internal */\nexport const addDuration: {\n  (duration: Duration.DurationInput): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(self: A, duration: Duration.DurationInput): A\n} = dual(\n  2,\n  (self: DateTime.DateTime, duration: Duration.DurationInput): DateTime.DateTime =>\n    mapEpochMillis(self, (millis) => millis + Duration.toMillis(duration))\n)\n\n/** @internal */\nexport const subtractDuration: {\n  (duration: Duration.DurationInput): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(self: A, duration: Duration.DurationInput): A\n} = dual(\n  2,\n  (self: DateTime.DateTime, duration: Duration.DurationInput): DateTime.DateTime =>\n    mapEpochMillis(self, (millis) => millis - Duration.toMillis(duration))\n)\n\nconst addMillis = (date: Date, amount: number): void => {\n  date.setTime(date.getTime() + amount)\n}\n\n/** @internal */\nexport const add: {\n  (\n    parts: Partial<DateTime.DateTime.PartsForMath>\n  ): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(\n    self: A,\n    parts: Partial<DateTime.DateTime.PartsForMath>\n  ): A\n} = dual(\n  2,\n  (self: DateTime.DateTime, parts: Partial<DateTime.DateTime.PartsForMath>): DateTime.DateTime =>\n    mutate(self, (date) => {\n      if (parts.millis) {\n        addMillis(date, parts.millis)\n      }\n      if (parts.seconds) {\n        addMillis(date, parts.seconds * 1000)\n      }\n      if (parts.minutes) {\n        addMillis(date, parts.minutes * 60 * 1000)\n      }\n      if (parts.hours) {\n        addMillis(date, parts.hours * 60 * 60 * 1000)\n      }\n      if (parts.days) {\n        date.setUTCDate(date.getUTCDate() + parts.days)\n      }\n      if (parts.weeks) {\n        date.setUTCDate(date.getUTCDate() + parts.weeks * 7)\n      }\n      if (parts.months) {\n        const day = date.getUTCDate()\n        date.setUTCMonth(date.getUTCMonth() + parts.months + 1, 0)\n        if (day < date.getUTCDate()) {\n          date.setUTCDate(day)\n        }\n      }\n      if (parts.years) {\n        const day = date.getUTCDate()\n        const month = date.getUTCMonth()\n        date.setUTCFullYear(\n          date.getUTCFullYear() + parts.years,\n          month + 1,\n          0\n        )\n        if (day < date.getUTCDate()) {\n          date.setUTCDate(day)\n        }\n      }\n    })\n)\n\n/** @internal */\nexport const subtract: {\n  (\n    parts: Partial<DateTime.DateTime.PartsForMath>\n  ): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(\n    self: A,\n    parts: Partial<DateTime.DateTime.PartsForMath>\n  ): A\n} = dual(2, (self: DateTime.DateTime, parts: Partial<DateTime.DateTime.PartsForMath>): DateTime.DateTime => {\n  const newParts = {} as Partial<Mutable<DateTime.DateTime.PartsForMath>>\n  for (const key in parts) {\n    newParts[key as keyof DateTime.DateTime.PartsForMath] = -1 * parts[key as keyof DateTime.DateTime.PartsForMath]!\n  }\n  return add(self, newParts)\n})\n\nconst startOfDate = (date: Date, part: DateTime.DateTime.UnitSingular, options?: {\n  readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n}) => {\n  switch (part) {\n    case \"second\": {\n      date.setUTCMilliseconds(0)\n      break\n    }\n    case \"minute\": {\n      date.setUTCSeconds(0, 0)\n      break\n    }\n    case \"hour\": {\n      date.setUTCMinutes(0, 0, 0)\n      break\n    }\n    case \"day\": {\n      date.setUTCHours(0, 0, 0, 0)\n      break\n    }\n    case \"week\": {\n      const weekStartsOn = options?.weekStartsOn ?? 0\n      const day = date.getUTCDay()\n      const diff = (day - weekStartsOn + 7) % 7\n      date.setUTCDate(date.getUTCDate() - diff)\n      date.setUTCHours(0, 0, 0, 0)\n      break\n    }\n    case \"month\": {\n      date.setUTCDate(1)\n      date.setUTCHours(0, 0, 0, 0)\n      break\n    }\n    case \"year\": {\n      date.setUTCMonth(0, 1)\n      date.setUTCHours(0, 0, 0, 0)\n      break\n    }\n  }\n}\n\n/** @internal */\nexport const startOf: {\n  (part: DateTime.DateTime.UnitSingular, options?: {\n    readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n  }): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(self: A, part: DateTime.DateTime.UnitSingular, options?: {\n    readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n  }): A\n} = dual(isDateTimeArgs, (self: DateTime.DateTime, part: DateTime.DateTime.UnitSingular, options?: {\n  readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n}): DateTime.DateTime => mutate(self, (date) => startOfDate(date, part, options)))\n\nconst endOfDate = (date: Date, part: DateTime.DateTime.UnitSingular, options?: {\n  readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n}) => {\n  switch (part) {\n    case \"second\": {\n      date.setUTCMilliseconds(999)\n      break\n    }\n    case \"minute\": {\n      date.setUTCSeconds(59, 999)\n      break\n    }\n    case \"hour\": {\n      date.setUTCMinutes(59, 59, 999)\n      break\n    }\n    case \"day\": {\n      date.setUTCHours(23, 59, 59, 999)\n      break\n    }\n    case \"week\": {\n      const weekStartsOn = options?.weekStartsOn ?? 0\n      const day = date.getUTCDay()\n      const diff = (day - weekStartsOn + 7) % 7\n      date.setUTCDate(date.getUTCDate() - diff + 6)\n      date.setUTCHours(23, 59, 59, 999)\n      break\n    }\n    case \"month\": {\n      date.setUTCMonth(date.getUTCMonth() + 1, 0)\n      date.setUTCHours(23, 59, 59, 999)\n      break\n    }\n    case \"year\": {\n      date.setUTCMonth(11, 31)\n      date.setUTCHours(23, 59, 59, 999)\n      break\n    }\n  }\n}\n\n/** @internal */\nexport const endOf: {\n  (part: DateTime.DateTime.UnitSingular, options?: {\n    readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n  }): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(self: A, part: DateTime.DateTime.UnitSingular, options?: {\n    readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n  }): A\n} = dual(isDateTimeArgs, (self: DateTime.DateTime, part: DateTime.DateTime.UnitSingular, options?: {\n  readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n}): DateTime.DateTime => mutate(self, (date) => endOfDate(date, part, options)))\n\n/** @internal */\nexport const nearest: {\n  (part: DateTime.DateTime.UnitSingular, options?: {\n    readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n  }): <A extends DateTime.DateTime>(self: A) => A\n  <A extends DateTime.DateTime>(self: A, part: DateTime.DateTime.UnitSingular, options?: {\n    readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n  }): A\n} = dual(isDateTimeArgs, (self: DateTime.DateTime, part: DateTime.DateTime.UnitSingular, options?: {\n  readonly weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | undefined\n}): DateTime.DateTime =>\n  mutate(self, (date) => {\n    if (part === \"milli\") return\n    const millis = date.getTime()\n    const start = new Date(millis)\n    startOfDate(start, part, options)\n    const startMillis = start.getTime()\n    const end = new Date(millis)\n    endOfDate(end, part, options)\n    const endMillis = end.getTime() + 1\n    const diffStart = millis - startMillis\n    const diffEnd = endMillis - millis\n    if (diffStart < diffEnd) {\n      date.setTime(startMillis)\n    } else {\n      date.setTime(endMillis)\n    }\n  }))\n\n// =============================================================================\n// formatting\n// =============================================================================\n\nconst intlTimeZone = (self: DateTime.TimeZone): string => {\n  if (self._tag === \"Named\") {\n    return self.id\n  }\n  return offsetToString(self.offset)\n}\n\n/** @internal */\nexport const format: {\n  (\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): (self: DateTime.DateTime) => string\n  (\n    self: DateTime.DateTime,\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): string\n} = dual(isDateTimeArgs, (\n  self: DateTime.DateTime,\n  options?:\n    | Intl.DateTimeFormatOptions & {\n      readonly locale?: Intl.LocalesArgument\n    }\n    | undefined\n): string => {\n  try {\n    return new Intl.DateTimeFormat(options?.locale, {\n      timeZone: self._tag === \"Utc\" ? \"UTC\" : intlTimeZone(self.zone),\n      ...options\n    }).format(self.epochMillis)\n  } catch {\n    return new Intl.DateTimeFormat(options?.locale, {\n      timeZone: \"UTC\",\n      ...options\n    }).format(toDate(self))\n  }\n})\n\n/** @internal */\nexport const formatLocal: {\n  (\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): (self: DateTime.DateTime) => string\n  (\n    self: DateTime.DateTime,\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): string\n} = dual(isDateTimeArgs, (\n  self: DateTime.DateTime,\n  options?:\n    | Intl.DateTimeFormatOptions & {\n      readonly locale?: Intl.LocalesArgument\n    }\n    | undefined\n): string => new Intl.DateTimeFormat(options?.locale, options).format(self.epochMillis))\n\n/** @internal */\nexport const formatUtc: {\n  (\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): (self: DateTime.DateTime) => string\n  (\n    self: DateTime.DateTime,\n    options?:\n      | Intl.DateTimeFormatOptions & {\n        readonly locale?: Intl.LocalesArgument\n      }\n      | undefined\n  ): string\n} = dual(isDateTimeArgs, (\n  self: DateTime.DateTime,\n  options?:\n    | Intl.DateTimeFormatOptions & {\n      readonly locale?: Intl.LocalesArgument\n    }\n    | undefined\n): string =>\n  new Intl.DateTimeFormat(options?.locale, {\n    ...options,\n    timeZone: \"UTC\"\n  }).format(self.epochMillis))\n\n/** @internal */\nexport const formatIntl: {\n  (format: Intl.DateTimeFormat): (self: DateTime.DateTime) => string\n  (self: DateTime.DateTime, format: Intl.DateTimeFormat): string\n} = dual(2, (self: DateTime.DateTime, format: Intl.DateTimeFormat): string => format.format(self.epochMillis))\n\n/** @internal */\nexport const formatIso = (self: DateTime.DateTime): string => toDateUtc(self).toISOString()\n\n/** @internal */\nexport const formatIsoDate = (self: DateTime.DateTime): string => toDate(self).toISOString().slice(0, 10)\n\n/** @internal */\nexport const formatIsoDateUtc = (self: DateTime.DateTime): string => toDateUtc(self).toISOString().slice(0, 10)\n\n/** @internal */\nexport const formatIsoOffset = (self: DateTime.DateTime): string => {\n  const date = toDate(self)\n  return self._tag === \"Utc\" ? date.toISOString() : `${date.toISOString().slice(0, -1)}${zonedOffsetIso(self)}`\n}\n\n/** @internal */\nexport const formatIsoZoned = (self: DateTime.Zoned): string =>\n  self.zone._tag === \"Offset\" ? formatIsoOffset(self) : `${formatIsoOffset(self)}[${self.zone.id}]`\n"
  },
  {
    "path": "packages/effect/src/internal/defaultServices/console.ts",
    "content": "/* eslint-disable no-console */\nimport type * as Console from \"../../Console.js\"\nimport * as Context from \"../../Context.js\"\nimport * as core from \"../core.js\"\n\n/** @internal */\nexport const TypeId: Console.TypeId = Symbol.for(\"effect/Console\") as Console.TypeId\n\n/** @internal */\nexport const consoleTag: Context.Tag<Console.Console, Console.Console> = Context.GenericTag<Console.Console>(\n  \"effect/Console\"\n)\n\n/** @internal */\nexport const defaultConsole: Console.Console = {\n  [TypeId]: TypeId,\n  assert(condition, ...args) {\n    return core.sync(() => {\n      console.assert(condition, ...args)\n    })\n  },\n  clear: core.sync(() => {\n    console.clear()\n  }),\n  count(label) {\n    return core.sync(() => {\n      console.count(label)\n    })\n  },\n  countReset(label) {\n    return core.sync(() => {\n      console.countReset(label)\n    })\n  },\n  debug(...args) {\n    return core.sync(() => {\n      console.debug(...args)\n    })\n  },\n  dir(item, options) {\n    return core.sync(() => {\n      console.dir(item, options)\n    })\n  },\n  dirxml(...args) {\n    return core.sync(() => {\n      console.dirxml(...args)\n    })\n  },\n  error(...args) {\n    return core.sync(() => {\n      console.error(...args)\n    })\n  },\n  group(options) {\n    return options?.collapsed ?\n      core.sync(() => console.groupCollapsed(options?.label)) :\n      core.sync(() => console.group(options?.label))\n  },\n  groupEnd: core.sync(() => {\n    console.groupEnd()\n  }),\n  info(...args) {\n    return core.sync(() => {\n      console.info(...args)\n    })\n  },\n  log(...args) {\n    return core.sync(() => {\n      console.log(...args)\n    })\n  },\n  table(tabularData, properties) {\n    return core.sync(() => {\n      console.table(tabularData, properties)\n    })\n  },\n  time(label) {\n    return core.sync(() => console.time(label))\n  },\n  timeEnd(label) {\n    return core.sync(() => console.timeEnd(label))\n  },\n  timeLog(label, ...args) {\n    return core.sync(() => {\n      console.timeLog(label, ...args)\n    })\n  },\n  trace(...args) {\n    return core.sync(() => {\n      console.trace(...args)\n    })\n  },\n  warn(...args) {\n    return core.sync(() => {\n      console.warn(...args)\n    })\n  },\n  unsafe: console\n}\n"
  },
  {
    "path": "packages/effect/src/internal/defaultServices.ts",
    "content": "import * as Array from \"../Array.js\"\nimport type * as Chunk from \"../Chunk.js\"\nimport type * as Clock from \"../Clock.js\"\nimport type * as Config from \"../Config.js\"\nimport type * as ConfigProvider from \"../ConfigProvider.js\"\nimport * as Context from \"../Context.js\"\nimport type * as DefaultServices from \"../DefaultServices.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport type * as Random from \"../Random.js\"\nimport type * as Tracer from \"../Tracer.js\"\nimport * as clock from \"./clock.js\"\nimport * as configProvider from \"./configProvider.js\"\nimport * as core from \"./core.js\"\nimport * as console_ from \"./defaultServices/console.js\"\nimport * as random from \"./random.js\"\nimport * as tracer from \"./tracer.js\"\n\n/** @internal */\nexport const liveServices: Context.Context<DefaultServices.DefaultServices> = pipe(\n  Context.empty(),\n  Context.add(clock.clockTag, clock.make()),\n  Context.add(console_.consoleTag, console_.defaultConsole),\n  Context.add(random.randomTag, random.make(Math.random())),\n  Context.add(configProvider.configProviderTag, configProvider.fromEnv()),\n  Context.add(tracer.tracerTag, tracer.nativeTracer)\n)\n\n/**\n * The `FiberRef` holding the default `Effect` services.\n *\n * @since 2.0.0\n * @category fiberRefs\n */\nexport const currentServices = globalValue(\n  Symbol.for(\"effect/DefaultServices/currentServices\"),\n  () => core.fiberRefUnsafeMakeContext(liveServices)\n)\n\n// circular with Clock\n\n/** @internal */\nexport const sleep = (duration: Duration.DurationInput): Effect.Effect<void> => {\n  const decodedDuration = Duration.decode(duration)\n  return clockWith((clock) => clock.sleep(decodedDuration))\n}\n\n/** @internal */\nexport const defaultServicesWith = <A, E, R>(\n  f: (services: Context.Context<DefaultServices.DefaultServices>) => Effect.Effect<A, E, R>\n) => core.withFiberRuntime<A, E, R>((fiber) => f(fiber.currentDefaultServices))\n\n/** @internal */\nexport const clockWith = <A, E, R>(f: (clock: Clock.Clock) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  defaultServicesWith((services) => f(services.unsafeMap.get(clock.clockTag.key)))\n\n/** @internal */\nexport const currentTimeMillis: Effect.Effect<number> = clockWith((clock) => clock.currentTimeMillis)\n\n/** @internal */\nexport const currentTimeNanos: Effect.Effect<bigint> = clockWith((clock) => clock.currentTimeNanos)\n\n/** @internal */\nexport const withClock = dual<\n  <C extends Clock.Clock>(clock: C) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <C extends Clock.Clock, A, E, R>(effect: Effect.Effect<A, E, R>, clock: C) => Effect.Effect<A, E, R>\n>(2, (effect, c) =>\n  core.fiberRefLocallyWith(\n    currentServices,\n    Context.add(clock.clockTag, c)\n  )(effect))\n\n// circular with ConfigProvider\n\n/** @internal */\nexport const withConfigProvider = dual<\n  (provider: ConfigProvider.ConfigProvider) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, provider: ConfigProvider.ConfigProvider) => Effect.Effect<A, E, R>\n>(2, (self, provider) =>\n  core.fiberRefLocallyWith(\n    currentServices,\n    Context.add(configProvider.configProviderTag, provider)\n  )(self))\n\n/** @internal */\nexport const configProviderWith = <A, E, R>(\n  f: (provider: ConfigProvider.ConfigProvider) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> =>\n  defaultServicesWith((services) => f(services.unsafeMap.get(configProvider.configProviderTag.key)))\n\n/** @internal */\nexport const config = <A>(config: Config.Config<A>) => configProviderWith((_) => _.load(config))\n\n/** @internal */\nexport const configOrDie = <A>(config: Config.Config<A>) => core.orDie(configProviderWith((_) => _.load(config)))\n\n// circular with Random\n\n/** @internal */\nexport const randomWith = <A, E, R>(f: (random: Random.Random) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  defaultServicesWith((services) => f(services.unsafeMap.get(random.randomTag.key)))\n\n/** @internal */\nexport const withRandom = dual<\n  <X extends Random.Random>(value: X) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <X extends Random.Random, A, E, R>(effect: Effect.Effect<A, E, R>, value: X) => Effect.Effect<A, E, R>\n>(2, (effect, value) =>\n  core.fiberRefLocallyWith(\n    currentServices,\n    Context.add(random.randomTag, value)\n  )(effect))\n\n/** @internal */\nexport const next: Effect.Effect<number> = randomWith((random) => random.next)\n\n/** @internal */\nexport const nextInt: Effect.Effect<number> = randomWith((random) => random.nextInt)\n\n/** @internal */\nexport const nextBoolean: Effect.Effect<boolean> = randomWith((random) => random.nextBoolean)\n\n/** @internal */\nexport const nextRange = (min: number, max: number): Effect.Effect<number> =>\n  randomWith((random) => random.nextRange(min, max))\n\n/** @internal */\nexport const nextIntBetween = (min: number, max: number): Effect.Effect<number> =>\n  randomWith((random) => random.nextIntBetween(min, max))\n\n/** @internal */\nexport const shuffle = <A>(elements: Iterable<A>): Effect.Effect<Chunk.Chunk<A>> =>\n  randomWith((random) => random.shuffle(elements))\n\n/** @internal */\nexport const choice = <Self extends Iterable<unknown>>(\n  elements: Self\n) => {\n  const array = Array.fromIterable(elements)\n  return core.map(\n    array.length === 0\n      ? core.fail(new core.NoSuchElementException(\"Cannot select a random element from an empty array\"))\n      : randomWith((random) => random.nextIntBetween(0, array.length)),\n    (i) => array[i]\n  ) as any\n}\n\n// circular with Tracer\n\n/** @internal */\nexport const tracerWith = <A, E, R>(f: (tracer: Tracer.Tracer) => Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  defaultServicesWith((services) => f(services.unsafeMap.get(tracer.tracerTag.key)))\n\n/** @internal */\nexport const withTracer = dual<\n  (value: Tracer.Tracer) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, value: Tracer.Tracer) => Effect.Effect<A, E, R>\n>(2, (effect, value) =>\n  core.fiberRefLocallyWith(\n    currentServices,\n    Context.add(tracer.tracerTag, value)\n  )(effect))\n"
  },
  {
    "path": "packages/effect/src/internal/deferred.ts",
    "content": "import type * as Deferred from \"../Deferred.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as OpCodes from \"./opCodes/deferred.js\"\n\n/** @internal */\nconst DeferredSymbolKey = \"effect/Deferred\"\n\n/** @internal */\nexport const DeferredTypeId: Deferred.DeferredTypeId = Symbol.for(\n  DeferredSymbolKey\n) as Deferred.DeferredTypeId\n\n/** @internal */\nexport const deferredVariance = {\n  /* c8 ignore next */\n  _E: (_: any) => _,\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nexport type State</* in out */ A, /* in out */ E> = Pending<A, E> | Done<A, E>\n\n/** @internal */\nexport interface Pending<in A, in E> {\n  readonly _tag: \"Pending\"\n  readonly joiners: Array<(effect: Effect.Effect<A, E>) => void>\n}\n\n/** @internal */\nexport interface Done<out A, out E> {\n  readonly _tag: \"Done\"\n  readonly effect: Effect.Effect<A, E>\n}\n\n/** @internal */\nexport const pending = <A, E>(\n  joiners: Array<(effect: Effect.Effect<A, E>) => void>\n): State<A, E> => {\n  return { _tag: OpCodes.OP_STATE_PENDING, joiners }\n}\n\n/** @internal */\nexport const done = <A, E>(effect: Effect.Effect<A, E>): State<A, E> => {\n  return { _tag: OpCodes.OP_STATE_DONE, effect }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/differ/chunkPatch.ts",
    "content": "import * as Chunk from \"../../Chunk.js\"\nimport type * as Differ from \"../../Differ.js\"\nimport * as Equal from \"../../Equal.js\"\nimport * as Dual from \"../../Function.js\"\nimport { pipe } from \"../../Function.js\"\nimport * as Data from \"../data.js\"\n\n/** @internal */\nexport const ChunkPatchTypeId: Differ.Differ.Chunk.TypeId = Symbol.for(\n  \"effect/DifferChunkPatch\"\n) as Differ.Differ.Chunk.TypeId\n\nfunction variance<A, B>(a: A): B {\n  return a as unknown as B\n}\n\nconst PatchProto = {\n  ...Data.Structural.prototype,\n  [ChunkPatchTypeId]: {\n    _Value: variance,\n    _Patch: variance\n  }\n}\n\ninterface Empty<Value, Patch> extends Differ.Differ.Chunk.Patch<Value, Patch> {\n  readonly _tag: \"Empty\"\n}\n\nconst EmptyProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Empty\"\n})\n\nconst _empty = Object.create(EmptyProto)\n\n/**\n * @internal\n */\nexport const empty = <Value, Patch>(): Differ.Differ.Chunk.Patch<Value, Patch> => _empty\n\ninterface AndThen<Value, Patch> extends Differ.Differ.Chunk.Patch<Value, Patch> {\n  readonly _tag: \"AndThen\"\n  readonly first: Differ.Differ.Chunk.Patch<Value, Patch>\n  readonly second: Differ.Differ.Chunk.Patch<Value, Patch>\n}\n\nconst AndThenProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"AndThen\"\n})\n\nconst makeAndThen = <Value, Patch>(\n  first: Differ.Differ.Chunk.Patch<Value, Patch>,\n  second: Differ.Differ.Chunk.Patch<Value, Patch>\n): Differ.Differ.Chunk.Patch<Value, Patch> => {\n  const o = Object.create(AndThenProto)\n  o.first = first\n  o.second = second\n  return o\n}\n\ninterface Append<Value, Patch> extends Differ.Differ.Chunk.Patch<Value, Patch> {\n  readonly _tag: \"Append\"\n  readonly values: Chunk.Chunk<Value>\n}\n\nconst AppendProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Append\"\n})\n\nconst makeAppend = <Value, Patch>(values: Chunk.Chunk<Value>): Differ.Differ.Chunk.Patch<Value, Patch> => {\n  const o = Object.create(AppendProto)\n  o.values = values\n  return o\n}\n\ninterface Slice<Value, Patch> extends Differ.Differ.Chunk.Patch<Value, Patch> {\n  readonly _tag: \"Slice\"\n  readonly from: number\n  readonly until: number\n}\n\nconst SliceProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Slice\"\n})\n\nconst makeSlice = <Value, Patch>(from: number, until: number): Differ.Differ.Chunk.Patch<Value, Patch> => {\n  const o = Object.create(SliceProto)\n  o.from = from\n  o.until = until\n  return o\n}\n\ninterface Update<Value, Patch> extends Differ.Differ.Chunk.Patch<Value, Patch> {\n  readonly _tag: \"Update\"\n  readonly index: number\n  readonly patch: Patch\n}\n\nconst UpdateProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Update\"\n})\n\nconst makeUpdate = <Value, Patch>(index: number, patch: Patch): Differ.Differ.Chunk.Patch<Value, Patch> => {\n  const o = Object.create(UpdateProto)\n  o.index = index\n  o.patch = patch\n  return o\n}\n\ntype Instruction =\n  | Empty<any, any>\n  | AndThen<any, any>\n  | Append<any, any>\n  | Slice<any, any>\n  | Update<any, any>\n\n/** @internal */\nexport const diff = <Value, Patch>(\n  options: {\n    readonly oldValue: Chunk.Chunk<Value>\n    readonly newValue: Chunk.Chunk<Value>\n    readonly differ: Differ.Differ<Value, Patch>\n  }\n): Differ.Differ.Chunk.Patch<Value, Patch> => {\n  let i = 0\n  let patch = empty<Value, Patch>()\n  while (i < options.oldValue.length && i < options.newValue.length) {\n    const oldElement = Chunk.unsafeGet(i)(options.oldValue)\n    const newElement = Chunk.unsafeGet(i)(options.newValue)\n    const valuePatch = options.differ.diff(oldElement, newElement)\n    if (!Equal.equals(valuePatch, options.differ.empty)) {\n      patch = pipe(patch, combine(makeUpdate(i, valuePatch)))\n    }\n    i = i + 1\n  }\n  if (i < options.oldValue.length) {\n    patch = pipe(patch, combine(makeSlice(0, i)))\n  }\n  if (i < options.newValue.length) {\n    patch = pipe(patch, combine(makeAppend(Chunk.drop(i)(options.newValue))))\n  }\n  return patch\n}\n\n/** @internal */\nexport const combine = Dual.dual<\n  <Value, Patch>(\n    that: Differ.Differ.Chunk.Patch<Value, Patch>\n  ) => (\n    self: Differ.Differ.Chunk.Patch<Value, Patch>\n  ) => Differ.Differ.Chunk.Patch<Value, Patch>,\n  <Value, Patch>(\n    self: Differ.Differ.Chunk.Patch<Value, Patch>,\n    that: Differ.Differ.Chunk.Patch<Value, Patch>\n  ) => Differ.Differ.Chunk.Patch<Value, Patch>\n>(2, (self, that) => makeAndThen(self, that))\n\n/** @internal */\nexport const patch = Dual.dual<\n  <Value, Patch>(\n    oldValue: Chunk.Chunk<Value>,\n    differ: Differ.Differ<Value, Patch>\n  ) => (self: Differ.Differ.Chunk.Patch<Value, Patch>) => Chunk.Chunk<Value>,\n  <Value, Patch>(\n    self: Differ.Differ.Chunk.Patch<Value, Patch>,\n    oldValue: Chunk.Chunk<Value>,\n    differ: Differ.Differ<Value, Patch>\n  ) => Chunk.Chunk<Value>\n>(3, <Value, Patch>(\n  self: Differ.Differ.Chunk.Patch<Value, Patch>,\n  oldValue: Chunk.Chunk<Value>,\n  differ: Differ.Differ<Value, Patch>\n) => {\n  if ((self as Instruction)._tag === \"Empty\") {\n    return oldValue\n  }\n  let chunk = oldValue\n  let patches: Chunk.Chunk<Differ.Differ.Chunk.Patch<Value, Patch>> = Chunk.of(self)\n  while (Chunk.isNonEmpty(patches)) {\n    const head: Instruction = Chunk.headNonEmpty(patches) as Instruction\n    const tail = Chunk.tailNonEmpty(patches)\n    switch (head._tag) {\n      case \"Empty\": {\n        patches = tail\n        break\n      }\n      case \"AndThen\": {\n        patches = Chunk.prepend(head.first)(Chunk.prepend(head.second)(tail))\n        break\n      }\n      case \"Append\": {\n        chunk = Chunk.appendAll(head.values)(chunk)\n        patches = tail\n        break\n      }\n      case \"Slice\": {\n        const array = Chunk.toReadonlyArray(chunk)\n        chunk = Chunk.unsafeFromArray(array.slice(head.from, head.until))\n        patches = tail\n        break\n      }\n      case \"Update\": {\n        const array = Chunk.toReadonlyArray(chunk) as Array<Value>\n        array[head.index] = differ.patch(head.patch, array[head.index]!)\n        chunk = Chunk.unsafeFromArray(array)\n        patches = tail\n        break\n      }\n    }\n  }\n  return chunk\n})\n"
  },
  {
    "path": "packages/effect/src/internal/differ/contextPatch.ts",
    "content": "import * as Chunk from \"../../Chunk.js\"\nimport type { Context } from \"../../Context.js\"\nimport type { Differ } from \"../../Differ.js\"\nimport * as Equal from \"../../Equal.js\"\nimport * as Dual from \"../../Function.js\"\nimport { makeContext } from \"../context.js\"\nimport { Structural } from \"../data.js\"\n\n/** @internal */\nexport const ContextPatchTypeId: Differ.Context.TypeId = Symbol.for(\n  \"effect/DifferContextPatch\"\n) as Differ.Context.TypeId\n\nfunction variance<A, B>(a: A): B {\n  return a as unknown as B\n}\n\n/** @internal */\nconst PatchProto = {\n  ...Structural.prototype,\n  [ContextPatchTypeId]: {\n    _Value: variance,\n    _Patch: variance\n  }\n}\n\ninterface Empty<Input, Output> extends Differ.Context.Patch<Input, Output> {\n  readonly _tag: \"Empty\"\n}\n\nconst EmptyProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Empty\"\n})\n\nconst _empty = Object.create(EmptyProto)\n\n/**\n * @internal\n */\nexport const empty = <Input, Output>(): Differ.Context.Patch<Input, Output> => _empty\n\n/** @internal */\nexport interface AndThen<in out Input, in out Output, in out Output2> extends Differ.Context.Patch<Input, Output2> {\n  readonly _tag: \"AndThen\"\n  readonly first: Differ.Context.Patch<Input, Output>\n  readonly second: Differ.Context.Patch<Output, Output2>\n}\n\nconst AndThenProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"AndThen\"\n})\n\nconst makeAndThen = <Input, Output, Output2>(\n  first: Differ.Context.Patch<Input, Output>,\n  second: Differ.Context.Patch<Output, Output2>\n): Differ.Context.Patch<Input, Output2> => {\n  const o = Object.create(AndThenProto)\n  o.first = first\n  o.second = second\n  return o\n}\n\n/** @internal */\nexport interface AddService<in out Env, in out T, in out I> extends Differ.Context.Patch<Env, Env | I> {\n  readonly _tag: \"AddService\"\n  readonly key: string\n  readonly service: T\n}\n\nconst AddServiceProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"AddService\"\n})\n\nconst makeAddService = <Env, I, T>(\n  key: string,\n  service: T\n): Differ.Context.Patch<Env, Env | I> => {\n  const o = Object.create(AddServiceProto)\n  o.key = key\n  o.service = service\n  return o\n}\n\n/** @internal */\nexport interface RemoveService<in out Env, in out I> extends Differ.Context.Patch<Env, Exclude<Env, I>> {\n  readonly _tag: \"RemoveService\"\n  readonly key: string\n}\n\nconst RemoveServiceProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"RemoveService\"\n})\n\nconst makeRemoveService = <Env, I>(\n  key: string\n): Differ.Context.Patch<Env, Exclude<Env, I>> => {\n  const o = Object.create(RemoveServiceProto)\n  o.key = key\n  return o\n}\n\n/** @internal */\nexport interface UpdateService<in out Env, in out T, in out I> extends Differ.Context.Patch<Env | I, Env | I> {\n  readonly _tag: \"UpdateService\"\n  readonly key: string\n  update(service: T): T\n}\n\nconst UpdateServiceProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"UpdateService\"\n})\n\nconst makeUpdateService = <Env, I, T>(\n  key: string,\n  update: (service: T) => T\n): Differ.Context.Patch<Env | I, Env | I> => {\n  const o = Object.create(UpdateServiceProto)\n  o.key = key\n  o.update = update\n  return o\n}\n\ntype Instruction =\n  | Empty<any, any>\n  | AndThen<any, any, any>\n  | AddService<any, any, any>\n  | RemoveService<any, any>\n  | UpdateService<any, any, any>\n\n/** @internal */\nexport const diff = <Input, Output>(\n  oldValue: Context<Input>,\n  newValue: Context<Output>\n): Differ.Context.Patch<Input, Output> => {\n  const missingServices = new Map(oldValue.unsafeMap)\n  let patch = empty<any, any>()\n  for (const [tag, newService] of newValue.unsafeMap.entries()) {\n    if (missingServices.has(tag)) {\n      const old = missingServices.get(tag)!\n      missingServices.delete(tag)\n      if (!Equal.equals(old, newService)) {\n        patch = combine(makeUpdateService(tag, () => newService))(patch)\n      }\n    } else {\n      missingServices.delete(tag)\n      patch = combine(makeAddService(tag, newService))(patch)\n    }\n  }\n  for (const [tag] of missingServices.entries()) {\n    patch = combine(makeRemoveService(tag))(patch)\n  }\n  return patch\n}\n\n/** @internal */\nexport const combine = Dual.dual<\n  <Output, Output2>(\n    that: Differ.Context.Patch<Output, Output2>\n  ) => <Input>(\n    self: Differ.Context.Patch<Input, Output>\n  ) => Differ.Context.Patch<Input, Output2>,\n  <Input, Output, Output2>(\n    self: Differ.Context.Patch<Input, Output>,\n    that: Differ.Context.Patch<Output, Output2>\n  ) => Differ.Context.Patch<Input, Output2>\n>(2, (self, that) => makeAndThen(self, that))\n\n/** @internal */\nexport const patch = Dual.dual<\n  <Input>(\n    context: Context<Input>\n  ) => <Output>(\n    self: Differ.Context.Patch<Input, Output>\n  ) => Context<Output>,\n  <Input, Output>(\n    self: Differ.Context.Patch<Input, Output>,\n    context: Context<Input>\n  ) => Context<Output>\n>(2, <Input, Output>(self: Differ.Context.Patch<Input, Output>, context: Context<Input>) => {\n  if ((self as Instruction)._tag === \"Empty\") {\n    return context as any\n  }\n  let wasServiceUpdated = false\n  let patches: Chunk.Chunk<Differ.Context.Patch<unknown, unknown>> = Chunk.of(\n    self as Differ.Context.Patch<unknown, unknown>\n  )\n  const updatedContext: Map<string, unknown> = new Map(context.unsafeMap)\n  while (Chunk.isNonEmpty(patches)) {\n    const head: Instruction = Chunk.headNonEmpty(patches) as Instruction\n    const tail = Chunk.tailNonEmpty(patches)\n    switch (head._tag) {\n      case \"Empty\": {\n        patches = tail\n        break\n      }\n      case \"AddService\": {\n        updatedContext.set(head.key, head.service)\n        patches = tail\n        break\n      }\n      case \"AndThen\": {\n        patches = Chunk.prepend(Chunk.prepend(tail, head.second), head.first)\n        break\n      }\n      case \"RemoveService\": {\n        updatedContext.delete(head.key)\n        patches = tail\n        break\n      }\n      case \"UpdateService\": {\n        updatedContext.set(head.key, head.update(updatedContext.get(head.key)))\n        wasServiceUpdated = true\n        patches = tail\n        break\n      }\n    }\n  }\n  if (!wasServiceUpdated) {\n    return makeContext(updatedContext) as Context<Output>\n  }\n  const map = new Map()\n  for (const [tag] of context.unsafeMap) {\n    if (updatedContext.has(tag)) {\n      map.set(tag, updatedContext.get(tag))\n      updatedContext.delete(tag)\n    }\n  }\n  for (const [tag, s] of updatedContext) {\n    map.set(tag, s)\n  }\n  return makeContext(map) as Context<Output>\n})\n"
  },
  {
    "path": "packages/effect/src/internal/differ/hashMapPatch.ts",
    "content": "import * as Chunk from \"../../Chunk.js\"\nimport type * as Differ from \"../../Differ.js\"\nimport * as Equal from \"../../Equal.js\"\nimport * as Dual from \"../../Function.js\"\nimport * as HashMap from \"../../HashMap.js\"\nimport { Structural } from \"../data.js\"\n\n/** @internal */\nexport const HashMapPatchTypeId: Differ.Differ.HashMap.TypeId = Symbol.for(\n  \"effect/DifferHashMapPatch\"\n) as Differ.Differ.HashMap.TypeId\n\nfunction variance<A, B>(a: A): B {\n  return a as unknown as B\n}\n\n/** @internal */\nconst PatchProto = {\n  ...Structural.prototype,\n  [HashMapPatchTypeId]: {\n    _Value: variance,\n    _Key: variance,\n    _Patch: variance\n  }\n}\n\ninterface Empty<Key, Value, Patch> extends Differ.Differ.HashMap.Patch<Key, Value, Patch> {\n  readonly _tag: \"Empty\"\n}\n\nconst EmptyProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Empty\"\n})\n\nconst _empty = Object.create(EmptyProto)\n\n/** @internal */\nexport const empty = <Key, Value, Patch>(): Differ.Differ.HashMap.Patch<Key, Value, Patch> => _empty\n\ninterface AndThen<Key, Value, Patch> extends Differ.Differ.HashMap.Patch<Key, Value, Patch> {\n  readonly _tag: \"AndThen\"\n  readonly first: Differ.Differ.HashMap.Patch<Key, Value, Patch>\n  readonly second: Differ.Differ.HashMap.Patch<Key, Value, Patch>\n}\n\nconst AndThenProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"AndThen\"\n})\n\nconst makeAndThen = <Key, Value, Patch>(\n  first: Differ.Differ.HashMap.Patch<Key, Value, Patch>,\n  second: Differ.Differ.HashMap.Patch<Key, Value, Patch>\n): Differ.Differ.HashMap.Patch<Key, Value, Patch> => {\n  const o = Object.create(AndThenProto)\n  o.first = first\n  o.second = second\n  return o\n}\n\ninterface Add<Key, Value, Patch> extends Differ.Differ.HashMap.Patch<Key, Value, Patch> {\n  readonly _tag: \"Add\"\n  readonly key: Key\n  readonly value: Value\n}\n\nconst AddProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Add\"\n})\n\nconst makeAdd = <Key, Value, Patch>(key: Key, value: Value): Differ.Differ.HashMap.Patch<Key, Value, Patch> => {\n  const o = Object.create(AddProto)\n  o.key = key\n  o.value = value\n  return o\n}\n\ninterface Remove<Key, Value, Patch> extends Differ.Differ.HashMap.Patch<Key, Value, Patch> {\n  readonly _tag: \"Remove\"\n  readonly key: Key\n}\n\nconst RemoveProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Remove\"\n})\n\nconst makeRemove = <Key, Value, Patch>(key: Key): Differ.Differ.HashMap.Patch<Key, Value, Patch> => {\n  const o = Object.create(RemoveProto)\n  o.key = key\n  return o\n}\n\ninterface Update<Key, Value, Patch> extends Differ.Differ.HashMap.Patch<Key, Value, Patch> {\n  readonly _tag: \"Update\"\n  readonly key: Key\n  readonly patch: Patch\n}\n\nconst UpdateProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Update\"\n})\n\nconst makeUpdate = <Key, Value, Patch>(key: Key, patch: Patch): Differ.Differ.HashMap.Patch<Key, Value, Patch> => {\n  const o = Object.create(UpdateProto)\n  o.key = key\n  o.patch = patch\n  return o\n}\n\ntype Instruction =\n  | Add<any, any, any>\n  | Remove<any, any, any>\n  | Update<any, any, any>\n  | Empty<any, any, any>\n  | AndThen<any, any, any>\n\n/** @internal */\nexport const diff = <Key, Value, Patch>(\n  options: {\n    readonly oldValue: HashMap.HashMap<Key, Value>\n    readonly newValue: HashMap.HashMap<Key, Value>\n    readonly differ: Differ.Differ<Value, Patch>\n  }\n): Differ.Differ.HashMap.Patch<Key, Value, Patch> => {\n  const [removed, patch] = HashMap.reduce(\n    [options.oldValue, empty<Key, Value, Patch>()] as const,\n    ([map, patch], newValue: Value, key: Key) => {\n      const option = HashMap.get(key)(map)\n      switch (option._tag) {\n        case \"Some\": {\n          const valuePatch = options.differ.diff(option.value, newValue)\n          if (Equal.equals(valuePatch, options.differ.empty)) {\n            return [HashMap.remove(key)(map), patch] as const\n          }\n          return [\n            HashMap.remove(key)(map),\n            combine<Key, Value, Patch>(makeUpdate(key, valuePatch))(patch)\n          ] as const\n        }\n        case \"None\": {\n          return [map, combine<Key, Value, Patch>(makeAdd(key, newValue))(patch)] as const\n        }\n      }\n    }\n  )(options.newValue)\n  return HashMap.reduce(\n    patch,\n    (patch, _, key: Key) => combine<Key, Value, Patch>(makeRemove(key))(patch)\n  )(removed)\n}\n\n/** @internal */\nexport const combine = Dual.dual<\n  <Key, Value, Patch>(\n    that: Differ.Differ.HashMap.Patch<Key, Value, Patch>\n  ) => (\n    self: Differ.Differ.HashMap.Patch<Key, Value, Patch>\n  ) => Differ.Differ.HashMap.Patch<Key, Value, Patch>,\n  <Key, Value, Patch>(\n    self: Differ.Differ.HashMap.Patch<Key, Value, Patch>,\n    that: Differ.Differ.HashMap.Patch<Key, Value, Patch>\n  ) => Differ.Differ.HashMap.Patch<Key, Value, Patch>\n>(2, (self, that) => makeAndThen(self, that))\n\n/** @internal */\nexport const patch = Dual.dual<\n  <Key, Value, Patch>(\n    oldValue: HashMap.HashMap<Key, Value>,\n    differ: Differ.Differ<Value, Patch>\n  ) => (\n    self: Differ.Differ.HashMap.Patch<Key, Value, Patch>\n  ) => HashMap.HashMap<Key, Value>,\n  <Key, Value, Patch>(\n    self: Differ.Differ.HashMap.Patch<Key, Value, Patch>,\n    oldValue: HashMap.HashMap<Key, Value>,\n    differ: Differ.Differ<Value, Patch>\n  ) => HashMap.HashMap<Key, Value>\n>(3, <Key, Value, Patch>(\n  self: Differ.Differ.HashMap.Patch<Key, Value, Patch>,\n  oldValue: HashMap.HashMap<Key, Value>,\n  differ: Differ.Differ<Value, Patch>\n) => {\n  if ((self as Instruction)._tag === \"Empty\") {\n    return oldValue\n  }\n  let map = oldValue\n  let patches: Chunk.Chunk<Differ.Differ.HashMap.Patch<Key, Value, Patch>> = Chunk.of(self)\n  while (Chunk.isNonEmpty(patches)) {\n    const head: Instruction = Chunk.headNonEmpty(patches) as Instruction\n    const tail = Chunk.tailNonEmpty(patches)\n    switch (head._tag) {\n      case \"Empty\": {\n        patches = tail\n        break\n      }\n      case \"AndThen\": {\n        patches = Chunk.prepend(head.first)(Chunk.prepend(head.second)(tail))\n        break\n      }\n      case \"Add\": {\n        map = HashMap.set(head.key, head.value)(map)\n        patches = tail\n        break\n      }\n      case \"Remove\": {\n        map = HashMap.remove(head.key)(map)\n        patches = tail\n        break\n      }\n      case \"Update\": {\n        const option = HashMap.get(head.key)(map)\n        if (option._tag === \"Some\") {\n          map = HashMap.set(head.key, differ.patch(head.patch, option.value))(map)\n        }\n        patches = tail\n        break\n      }\n    }\n  }\n  return map\n})\n"
  },
  {
    "path": "packages/effect/src/internal/differ/hashSetPatch.ts",
    "content": "import * as Chunk from \"../../Chunk.js\"\nimport type { Differ } from \"../../Differ.js\"\nimport * as Dual from \"../../Function.js\"\nimport * as HashSet from \"../../HashSet.js\"\nimport { Structural } from \"../data.js\"\n\n/** @internal */\nexport const HashSetPatchTypeId: Differ.HashSet.TypeId = Symbol.for(\n  \"effect/DifferHashSetPatch\"\n) as Differ.HashSet.TypeId\n\nfunction variance<A, B>(a: A): B {\n  return a as unknown as B\n}\n\n/** @internal */\nconst PatchProto = {\n  ...Structural.prototype,\n  [HashSetPatchTypeId]: {\n    _Value: variance,\n    _Key: variance,\n    _Patch: variance\n  }\n}\n\ninterface Empty<Value> extends Differ.HashSet.Patch<Value> {\n  readonly _tag: \"Empty\"\n}\n\nconst EmptyProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Empty\"\n})\n\nconst _empty = Object.create(EmptyProto)\n\n/** @internal */\nexport const empty = <Value>(): Differ.HashSet.Patch<Value> => _empty\n\ninterface AndThen<Value> extends Differ.HashSet.Patch<Value> {\n  readonly _tag: \"AndThen\"\n  readonly first: Differ.HashSet.Patch<Value>\n  readonly second: Differ.HashSet.Patch<Value>\n}\n\nconst AndThenProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"AndThen\"\n})\n\n/** @internal */\nexport const makeAndThen = <Value>(\n  first: Differ.HashSet.Patch<Value>,\n  second: Differ.HashSet.Patch<Value>\n): Differ.HashSet.Patch<Value> => {\n  const o = Object.create(AndThenProto)\n  o.first = first\n  o.second = second\n  return o\n}\n\ninterface Add<Value> extends Differ.HashSet.Patch<Value> {\n  readonly _tag: \"Add\"\n  readonly value: Value\n}\n\nconst AddProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Add\"\n})\n\n/** @internal */\nexport const makeAdd = <Value>(\n  value: Value\n): Differ.HashSet.Patch<Value> => {\n  const o = Object.create(AddProto)\n  o.value = value\n  return o\n}\n\ninterface Remove<Value> extends Differ.HashSet.Patch<Value> {\n  readonly _tag: \"Remove\"\n  readonly value: Value\n}\n\nconst RemoveProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Remove\"\n})\n\n/** @internal */\nexport const makeRemove = <Value>(\n  value: Value\n): Differ.HashSet.Patch<Value> => {\n  const o = Object.create(RemoveProto)\n  o.value = value\n  return o\n}\n\ntype Instruction =\n  | Add<any>\n  | AndThen<any>\n  | Empty<any>\n  | Remove<any>\n\n/** @internal */\nexport const diff = <Value>(\n  oldValue: HashSet.HashSet<Value>,\n  newValue: HashSet.HashSet<Value>\n): Differ.HashSet.Patch<Value> => {\n  const [removed, patch] = HashSet.reduce(\n    [oldValue, empty<Value>()] as const,\n    ([set, patch], value: Value) => {\n      if (HashSet.has(value)(set)) {\n        return [HashSet.remove(value)(set), patch] as const\n      }\n      return [set, combine(makeAdd(value))(patch)] as const\n    }\n  )(newValue)\n  return HashSet.reduce(patch, (patch, value: Value) => combine(makeRemove(value))(patch))(removed)\n}\n\n/** @internal */\nexport const combine = Dual.dual<\n  <Value>(\n    that: Differ.HashSet.Patch<Value>\n  ) => (\n    self: Differ.HashSet.Patch<Value>\n  ) => Differ.HashSet.Patch<Value>,\n  <Value>(\n    self: Differ.HashSet.Patch<Value>,\n    that: Differ.HashSet.Patch<Value>\n  ) => Differ.HashSet.Patch<Value>\n>(2, (self, that) => makeAndThen(self, that))\n\n/** @internal */\nexport const patch = Dual.dual<\n  <Value>(\n    oldValue: HashSet.HashSet<Value>\n  ) => (\n    self: Differ.HashSet.Patch<Value>\n  ) => HashSet.HashSet<Value>,\n  <Value>(\n    self: Differ.HashSet.Patch<Value>,\n    oldValue: HashSet.HashSet<Value>\n  ) => HashSet.HashSet<Value>\n>(2, <Value>(\n  self: Differ.HashSet.Patch<Value>,\n  oldValue: HashSet.HashSet<Value>\n) => {\n  if ((self as Instruction)._tag === \"Empty\") {\n    return oldValue\n  }\n  let set = oldValue\n  let patches: Chunk.Chunk<Differ.HashSet.Patch<Value>> = Chunk.of(self)\n  while (Chunk.isNonEmpty(patches)) {\n    const head: Instruction = Chunk.headNonEmpty(patches) as Instruction\n    const tail = Chunk.tailNonEmpty(patches)\n    switch (head._tag) {\n      case \"Empty\": {\n        patches = tail\n        break\n      }\n      case \"AndThen\": {\n        patches = Chunk.prepend(head.first)(Chunk.prepend(head.second)(tail))\n        break\n      }\n      case \"Add\": {\n        set = HashSet.add(head.value)(set)\n        patches = tail\n        break\n      }\n      case \"Remove\": {\n        set = HashSet.remove(head.value)(set)\n        patches = tail\n      }\n    }\n  }\n  return set\n})\n"
  },
  {
    "path": "packages/effect/src/internal/differ/orPatch.ts",
    "content": "import * as Chunk from \"../../Chunk.js\"\nimport type { Differ } from \"../../Differ.js\"\nimport type { Either } from \"../../Either.js\"\nimport * as E from \"../../Either.js\"\nimport * as Equal from \"../../Equal.js\"\nimport * as Dual from \"../../Function.js\"\nimport { Structural } from \"../data.js\"\n\n/** @internal */\nexport const OrPatchTypeId: Differ.Or.TypeId = Symbol.for(\"effect/DifferOrPatch\") as Differ.Or.TypeId\n\nfunction variance<A, B>(a: A): B {\n  return a as unknown as B\n}\n\n/** @internal */\nconst PatchProto = {\n  ...Structural.prototype,\n  [OrPatchTypeId]: {\n    _Value: variance,\n    _Key: variance,\n    _Patch: variance\n  }\n}\n\n/** @internal */\nexport interface Empty<in out Value, in out Value2, in out Patch, in out Patch2>\n  extends Differ.Or.Patch<Value, Value2, Patch, Patch2>\n{\n  readonly _tag: \"Empty\"\n}\n\nconst EmptyProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Empty\"\n})\n\nconst _empty = Object.create(EmptyProto)\n\n/** @internal */\nexport const empty = <Value, Value2, Patch, Patch2>(): Differ.Or.Patch<\n  Value,\n  Value2,\n  Patch,\n  Patch2\n> => _empty\n\n/** @internal */\nexport interface AndThen<in out Value, in out Value2, in out Patch, Patch2>\n  extends Differ.Or.Patch<Value, Value2, Patch, Patch2>\n{\n  readonly _tag: \"AndThen\"\n  readonly first: Differ.Or.Patch<Value, Value2, Patch, Patch2>\n  readonly second: Differ.Or.Patch<Value, Value2, Patch, Patch2>\n}\n\nconst AndThenProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"AndThen\"\n})\n\n/** @internal */\nexport const makeAndThen = <Value, Value2, Patch, Patch2>(\n  first: Differ.Or.Patch<Value, Value2, Patch, Patch2>,\n  second: Differ.Or.Patch<Value, Value2, Patch, Patch2>\n): Differ.Or.Patch<\n  Value,\n  Value2,\n  Patch,\n  Patch2\n> => {\n  const o = Object.create(AndThenProto)\n  o.first = first\n  o.second = second\n  return o\n}\n\n/** @internal */\nexport interface SetLeft<in out Value, in out Value2, in out Patch, Patch2>\n  extends Differ.Or.Patch<Value, Value2, Patch, Patch2>\n{\n  readonly _tag: \"SetLeft\"\n  readonly value: Value\n}\n\nconst SetLeftProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"SetLeft\"\n})\n\n/** @internal */\nexport const makeSetLeft = <Value, Value2, Patch, Patch2>(\n  value: Value\n): Differ.Or.Patch<\n  Value,\n  Value2,\n  Patch,\n  Patch2\n> => {\n  const o = Object.create(SetLeftProto)\n  o.value = value\n  return o\n}\n\n/** @internal */\nexport interface SetRight<in out Value, in out Value2, in out Patch, in out Patch2>\n  extends Differ.Or.Patch<Value, Value2, Patch, Patch2>\n{\n  readonly _tag: \"SetRight\"\n  readonly value: Value2\n}\n\nconst SetRightProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"SetRight\"\n})\n\n/** @internal */\nexport const makeSetRight = <Value, Value2, Patch, Patch2>(\n  value: Value2\n): Differ.Or.Patch<\n  Value,\n  Value2,\n  Patch,\n  Patch2\n> => {\n  const o = Object.create(SetRightProto)\n  o.value = value\n  return o\n}\n\n/** @internal */\nexport interface UpdateLeft<in out Value, in out Value2, in out Patch, in out Patch2>\n  extends Differ.Or.Patch<Value, Value2, Patch, Patch2>\n{\n  readonly _tag: \"UpdateLeft\"\n  readonly patch: Patch\n}\n\nconst UpdateLeftProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"UpdateLeft\"\n})\n\n/** @internal */\nexport const makeUpdateLeft = <Value, Value2, Patch, Patch2>(\n  patch: Patch\n): Differ.Or.Patch<\n  Value,\n  Value2,\n  Patch,\n  Patch2\n> => {\n  const o = Object.create(UpdateLeftProto)\n  o.patch = patch\n  return o\n}\n\n/** @internal */\nexport interface UpdateRight<in out Value, in out Value2, in out Patch, in out Patch2>\n  extends Differ.Or.Patch<Value, Value2, Patch, Patch2>\n{\n  readonly _tag: \"UpdateRight\"\n  readonly patch: Patch2\n}\n\nconst UpdateRightProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"UpdateRight\"\n})\n\n/** @internal */\nexport const makeUpdateRight = <Value, Value2, Patch, Patch2>(\n  patch: Patch2\n): Differ.Or.Patch<\n  Value,\n  Value2,\n  Patch,\n  Patch2\n> => {\n  const o = Object.create(UpdateRightProto)\n  o.patch = patch\n  return o\n}\n\ntype Instruction =\n  | AndThen<any, any, any, any>\n  | Empty<any, any, any, any>\n  | SetLeft<any, any, any, any>\n  | SetRight<any, any, any, any>\n  | UpdateLeft<any, any, any, any>\n  | UpdateRight<any, any, any, any>\n\n/** @internal */\nexport const diff = <Value, Value2, Patch, Patch2>(\n  options: {\n    readonly oldValue: Either<Value2, Value>\n    readonly newValue: Either<Value2, Value>\n    readonly left: Differ<Value, Patch>\n    readonly right: Differ<Value2, Patch2>\n  }\n): Differ.Or.Patch<Value, Value2, Patch, Patch2> => {\n  switch (options.oldValue._tag) {\n    case \"Left\": {\n      switch (options.newValue._tag) {\n        case \"Left\": {\n          const valuePatch = options.left.diff(options.oldValue.left, options.newValue.left)\n          if (Equal.equals(valuePatch, options.left.empty)) {\n            return empty()\n          }\n          return makeUpdateLeft(valuePatch)\n        }\n        case \"Right\": {\n          return makeSetRight(options.newValue.right)\n        }\n      }\n    }\n    case \"Right\": {\n      switch (options.newValue._tag) {\n        case \"Left\": {\n          return makeSetLeft(options.newValue.left)\n        }\n        case \"Right\": {\n          const valuePatch = options.right.diff(options.oldValue.right, options.newValue.right)\n          if (Equal.equals(valuePatch, options.right.empty)) {\n            return empty()\n          }\n          return makeUpdateRight(valuePatch)\n        }\n      }\n    }\n  }\n}\n\n/** @internal */\nexport const combine = Dual.dual<\n  <Value, Value2, Patch, Patch2>(\n    that: Differ.Or.Patch<Value, Value2, Patch, Patch2>\n  ) => (\n    self: Differ.Or.Patch<Value, Value2, Patch, Patch2>\n  ) => Differ.Or.Patch<Value, Value2, Patch, Patch2>,\n  <Value, Value2, Patch, Patch2>(\n    self: Differ.Or.Patch<Value, Value2, Patch, Patch2>,\n    that: Differ.Or.Patch<Value, Value2, Patch, Patch2>\n  ) => Differ.Or.Patch<Value, Value2, Patch, Patch2>\n>(2, (self, that) => makeAndThen(self, that))\n\n/** @internal */\nexport const patch = Dual.dual<\n  <Value, Value2, Patch, Patch2>(\n    options: {\n      readonly oldValue: Either<Value2, Value>\n      readonly left: Differ<Value, Patch>\n      readonly right: Differ<Value2, Patch2>\n    }\n  ) => (self: Differ.Or.Patch<Value, Value2, Patch, Patch2>) => Either<Value2, Value>,\n  <Value, Value2, Patch, Patch2>(\n    self: Differ.Or.Patch<Value, Value2, Patch, Patch2>,\n    options: {\n      readonly oldValue: Either<Value2, Value>\n      readonly left: Differ<Value, Patch>\n      readonly right: Differ<Value2, Patch2>\n    }\n  ) => Either<Value2, Value>\n>(2, <Value, Value2, Patch, Patch2>(\n  self: Differ.Or.Patch<Value, Value2, Patch, Patch2>,\n  { left, oldValue, right }: {\n    oldValue: Either<Value2, Value>\n    left: Differ<Value, Patch>\n    right: Differ<Value2, Patch2>\n  }\n) => {\n  if ((self as Instruction)._tag === \"Empty\") {\n    return oldValue\n  }\n  let patches: Chunk.Chunk<Differ.Or.Patch<Value, Value2, Patch, Patch2>> = Chunk.of(self)\n  let result = oldValue\n  while (Chunk.isNonEmpty(patches)) {\n    const head: Instruction = Chunk.headNonEmpty(patches) as Instruction\n    const tail = Chunk.tailNonEmpty(patches)\n    switch (head._tag) {\n      case \"Empty\": {\n        patches = tail\n        break\n      }\n      case \"AndThen\": {\n        patches = Chunk.prepend(head.first)(Chunk.prepend(head.second)(tail))\n        break\n      }\n      case \"UpdateLeft\": {\n        if (result._tag === \"Left\") {\n          result = E.left(left.patch(head.patch, result.left))\n        }\n        patches = tail\n        break\n      }\n      case \"UpdateRight\": {\n        if (result._tag === \"Right\") {\n          result = E.right(right.patch(head.patch, result.right))\n        }\n        patches = tail\n        break\n      }\n      case \"SetLeft\": {\n        result = E.left(head.value)\n        patches = tail\n        break\n      }\n      case \"SetRight\": {\n        result = E.right(head.value)\n        patches = tail\n        break\n      }\n    }\n  }\n  return result\n})\n"
  },
  {
    "path": "packages/effect/src/internal/differ/readonlyArrayPatch.ts",
    "content": "import * as Arr from \"../../Array.js\"\nimport type * as Differ from \"../../Differ.js\"\nimport * as Equal from \"../../Equal.js\"\nimport * as Dual from \"../../Function.js\"\nimport * as Data from \"../data.js\"\n\n/** @internal */\nexport const ReadonlyArrayPatchTypeId: Differ.Differ.ReadonlyArray.TypeId = Symbol.for(\n  \"effect/DifferReadonlyArrayPatch\"\n) as Differ.Differ.ReadonlyArray.TypeId\n\nfunction variance<A, B>(a: A): B {\n  return a as unknown as B\n}\n\nconst PatchProto = {\n  ...Data.Structural.prototype,\n  [ReadonlyArrayPatchTypeId]: {\n    _Value: variance,\n    _Patch: variance\n  }\n}\n\ninterface Empty<Value, Patch> extends Differ.Differ.ReadonlyArray.Patch<Value, Patch> {\n  readonly _tag: \"Empty\"\n}\n\nconst EmptyProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Empty\"\n})\n\nconst _empty = Object.create(EmptyProto)\n\n/**\n * @internal\n */\nexport const empty = <Value, Patch>(): Differ.Differ.ReadonlyArray.Patch<Value, Patch> => _empty\n\ninterface AndThen<Value, Patch> extends Differ.Differ.ReadonlyArray.Patch<Value, Patch> {\n  readonly _tag: \"AndThen\"\n  readonly first: Differ.Differ.ReadonlyArray.Patch<Value, Patch>\n  readonly second: Differ.Differ.ReadonlyArray.Patch<Value, Patch>\n}\n\nconst AndThenProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"AndThen\"\n})\n\nconst makeAndThen = <Value, Patch>(\n  first: Differ.Differ.ReadonlyArray.Patch<Value, Patch>,\n  second: Differ.Differ.ReadonlyArray.Patch<Value, Patch>\n): Differ.Differ.ReadonlyArray.Patch<Value, Patch> => {\n  const o = Object.create(AndThenProto)\n  o.first = first\n  o.second = second\n  return o\n}\n\ninterface Append<Value, Patch> extends Differ.Differ.ReadonlyArray.Patch<Value, Patch> {\n  readonly _tag: \"Append\"\n  readonly values: ReadonlyArray<Value>\n}\n\nconst AppendProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Append\"\n})\n\nconst makeAppend = <Value, Patch>(values: ReadonlyArray<Value>): Differ.Differ.ReadonlyArray.Patch<Value, Patch> => {\n  const o = Object.create(AppendProto)\n  o.values = values\n  return o\n}\n\ninterface Slice<Value, Patch> extends Differ.Differ.ReadonlyArray.Patch<Value, Patch> {\n  readonly _tag: \"Slice\"\n  readonly from: number\n  readonly until: number\n}\n\nconst SliceProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Slice\"\n})\n\nconst makeSlice = <Value, Patch>(from: number, until: number): Differ.Differ.ReadonlyArray.Patch<Value, Patch> => {\n  const o = Object.create(SliceProto)\n  o.from = from\n  o.until = until\n  return o\n}\n\ninterface Update<Value, Patch> extends Differ.Differ.ReadonlyArray.Patch<Value, Patch> {\n  readonly _tag: \"Update\"\n  readonly index: number\n  readonly patch: Patch\n}\n\nconst UpdateProto = Object.assign(Object.create(PatchProto), {\n  _tag: \"Update\"\n})\n\nconst makeUpdate = <Value, Patch>(index: number, patch: Patch): Differ.Differ.ReadonlyArray.Patch<Value, Patch> => {\n  const o = Object.create(UpdateProto)\n  o.index = index\n  o.patch = patch\n  return o\n}\n\ntype Instruction =\n  | Empty<any, any>\n  | AndThen<any, any>\n  | Append<any, any>\n  | Slice<any, any>\n  | Update<any, any>\n\n/** @internal */\nexport const diff = <Value, Patch>(\n  options: {\n    readonly oldValue: ReadonlyArray<Value>\n    readonly newValue: ReadonlyArray<Value>\n    readonly differ: Differ.Differ<Value, Patch>\n  }\n): Differ.Differ.ReadonlyArray.Patch<Value, Patch> => {\n  let i = 0\n  let patch = empty<Value, Patch>()\n  while (i < options.oldValue.length && i < options.newValue.length) {\n    const oldElement = options.oldValue[i]!\n    const newElement = options.newValue[i]!\n    const valuePatch = options.differ.diff(oldElement, newElement)\n    if (!Equal.equals(valuePatch, options.differ.empty)) {\n      patch = combine(patch, makeUpdate(i, valuePatch))\n    }\n    i = i + 1\n  }\n  if (i < options.oldValue.length) {\n    patch = combine(patch, makeSlice(0, i))\n  }\n  if (i < options.newValue.length) {\n    patch = combine(patch, makeAppend(Arr.drop(i)(options.newValue)))\n  }\n  return patch\n}\n\n/** @internal */\nexport const combine = Dual.dual<\n  <Value, Patch>(\n    that: Differ.Differ.ReadonlyArray.Patch<Value, Patch>\n  ) => (\n    self: Differ.Differ.ReadonlyArray.Patch<Value, Patch>\n  ) => Differ.Differ.ReadonlyArray.Patch<Value, Patch>,\n  <Value, Patch>(\n    self: Differ.Differ.ReadonlyArray.Patch<Value, Patch>,\n    that: Differ.Differ.ReadonlyArray.Patch<Value, Patch>\n  ) => Differ.Differ.ReadonlyArray.Patch<Value, Patch>\n>(2, (self, that) => makeAndThen(self, that))\n\n/** @internal */\nexport const patch = Dual.dual<\n  <Value, Patch>(\n    oldValue: ReadonlyArray<Value>,\n    differ: Differ.Differ<Value, Patch>\n  ) => (self: Differ.Differ.ReadonlyArray.Patch<Value, Patch>) => ReadonlyArray<Value>,\n  <Value, Patch>(\n    self: Differ.Differ.ReadonlyArray.Patch<Value, Patch>,\n    oldValue: ReadonlyArray<Value>,\n    differ: Differ.Differ<Value, Patch>\n  ) => ReadonlyArray<Value>\n>(3, <Value, Patch>(\n  self: Differ.Differ.ReadonlyArray.Patch<Value, Patch>,\n  oldValue: ReadonlyArray<Value>,\n  differ: Differ.Differ<Value, Patch>\n) => {\n  if ((self as Instruction)._tag === \"Empty\") {\n    return oldValue\n  }\n  let readonlyArray = oldValue.slice()\n  let patches: Array<Differ.Differ.ReadonlyArray.Patch<Value, Patch>> = Arr.of(self)\n  while (Arr.isNonEmptyArray(patches)) {\n    const head: Instruction = Arr.headNonEmpty(patches) as Instruction\n    const tail = Arr.tailNonEmpty(patches)\n    switch (head._tag) {\n      case \"Empty\": {\n        patches = tail\n        break\n      }\n      case \"AndThen\": {\n        tail.unshift(head.first, head.second)\n        patches = tail\n        break\n      }\n      case \"Append\": {\n        for (const value of head.values) {\n          readonlyArray.push(value)\n        }\n        patches = tail\n        break\n      }\n      case \"Slice\": {\n        readonlyArray = readonlyArray.slice(head.from, head.until)\n        patches = tail\n        break\n      }\n      case \"Update\": {\n        readonlyArray[head.index] = differ.patch(head.patch, readonlyArray[head.index]!)\n        patches = tail\n        break\n      }\n    }\n  }\n  return readonlyArray\n})\n"
  },
  {
    "path": "packages/effect/src/internal/differ.ts",
    "content": "import type { Chunk } from \"../Chunk.js\"\nimport type { Context } from \"../Context.js\"\nimport type * as Differ from \"../Differ.js\"\nimport type { Either } from \"../Either.js\"\nimport * as Equal from \"../Equal.js\"\nimport * as Dual from \"../Function.js\"\nimport { constant, identity } from \"../Function.js\"\nimport type { HashMap } from \"../HashMap.js\"\nimport type { HashSet } from \"../HashSet.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport * as ChunkPatch from \"./differ/chunkPatch.js\"\nimport * as ContextPatch from \"./differ/contextPatch.js\"\nimport * as HashMapPatch from \"./differ/hashMapPatch.js\"\nimport * as HashSetPatch from \"./differ/hashSetPatch.js\"\nimport * as OrPatch from \"./differ/orPatch.js\"\nimport * as ReadonlyArrayPatch from \"./differ/readonlyArrayPatch.js\"\n\n/** @internal */\nexport const DifferTypeId: Differ.TypeId = Symbol.for(\"effect/Differ\") as Differ.TypeId\n\n/** @internal */\nexport const DifferProto = {\n  [DifferTypeId]: {\n    _P: identity,\n    _V: identity\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const make = <Value, Patch>(\n  params: {\n    readonly empty: Patch\n    readonly diff: (oldValue: Value, newValue: Value) => Patch\n    readonly combine: (first: Patch, second: Patch) => Patch\n    readonly patch: (patch: Patch, oldValue: Value) => Value\n  }\n): Differ.Differ<Value, Patch> => {\n  const differ = Object.create(DifferProto)\n  differ.empty = params.empty\n  differ.diff = params.diff\n  differ.combine = params.combine\n  differ.patch = params.patch\n  return differ\n}\n\n/** @internal */\nexport const environment = <A>(): Differ.Differ<Context<A>, Differ.Differ.Context.Patch<A, A>> =>\n  make({\n    empty: ContextPatch.empty(),\n    combine: (first, second) => ContextPatch.combine(second)(first),\n    diff: (oldValue, newValue) => ContextPatch.diff(oldValue, newValue),\n    patch: (patch, oldValue) => ContextPatch.patch(oldValue)(patch)\n  })\n\n/** @internal */\nexport const chunk = <Value, Patch>(\n  differ: Differ.Differ<Value, Patch>\n): Differ.Differ<Chunk<Value>, Differ.Differ.Chunk.Patch<Value, Patch>> =>\n  make({\n    empty: ChunkPatch.empty(),\n    combine: (first, second) => ChunkPatch.combine(second)(first),\n    diff: (oldValue, newValue) => ChunkPatch.diff({ oldValue, newValue, differ }),\n    patch: (patch, oldValue) => ChunkPatch.patch(oldValue, differ)(patch)\n  })\n\n/** @internal */\nexport const hashMap = <Key, Value, Patch>(\n  differ: Differ.Differ<Value, Patch>\n): Differ.Differ<HashMap<Key, Value>, Differ.Differ.HashMap.Patch<Key, Value, Patch>> =>\n  make({\n    empty: HashMapPatch.empty(),\n    combine: (first, second) => HashMapPatch.combine(second)(first),\n    diff: (oldValue, newValue) => HashMapPatch.diff({ oldValue, newValue, differ }),\n    patch: (patch, oldValue) => HashMapPatch.patch(oldValue, differ)(patch)\n  })\n\n/** @internal */\nexport const hashSet = <Value>(): Differ.Differ<HashSet<Value>, Differ.Differ.HashSet.Patch<Value>> =>\n  make({\n    empty: HashSetPatch.empty(),\n    combine: (first, second) => HashSetPatch.combine(second)(first),\n    diff: (oldValue, newValue) => HashSetPatch.diff(oldValue, newValue),\n    patch: (patch, oldValue) => HashSetPatch.patch(oldValue)(patch)\n  })\n\n/** @internal */\nexport const orElseEither = Dual.dual<\n  <Value2, Patch2>(that: Differ.Differ<Value2, Patch2>) => <Value, Patch>(\n    self: Differ.Differ<Value, Patch>\n  ) => Differ.Differ<Either<Value2, Value>, Differ.Differ.Or.Patch<Value, Value2, Patch, Patch2>>,\n  <Value, Patch, Value2, Patch2>(\n    self: Differ.Differ<Value, Patch>,\n    that: Differ.Differ<Value2, Patch2>\n  ) => Differ.Differ<Either<Value2, Value>, Differ.Differ.Or.Patch<Value, Value2, Patch, Patch2>>\n>(2, (self, that) =>\n  make({\n    empty: OrPatch.empty(),\n    combine: (first, second) => OrPatch.combine(first, second),\n    diff: (oldValue, newValue) =>\n      OrPatch.diff({\n        oldValue,\n        newValue,\n        left: self,\n        right: that\n      }),\n    patch: (patch, oldValue) =>\n      OrPatch.patch(patch, {\n        oldValue,\n        left: self,\n        right: that\n      })\n  }))\n\n/** @internal */\nexport const readonlyArray = <Value, Patch>(\n  differ: Differ.Differ<Value, Patch>\n): Differ.Differ<ReadonlyArray<Value>, Differ.Differ.ReadonlyArray.Patch<Value, Patch>> =>\n  make({\n    empty: ReadonlyArrayPatch.empty(),\n    combine: (first, second) => ReadonlyArrayPatch.combine(first, second),\n    diff: (oldValue, newValue) => ReadonlyArrayPatch.diff({ oldValue, newValue, differ }),\n    patch: (patch, oldValue) => ReadonlyArrayPatch.patch(patch, oldValue, differ)\n  })\n\n/** @internal */\nexport const transform = Dual.dual<\n  <Value, Value2>(\n    options: {\n      readonly toNew: (value: Value) => Value2\n      readonly toOld: (value: Value2) => Value\n    }\n  ) => <Patch>(self: Differ.Differ<Value, Patch>) => Differ.Differ<Value2, Patch>,\n  <Value, Patch, Value2>(\n    self: Differ.Differ<Value, Patch>,\n    options: {\n      readonly toNew: (value: Value) => Value2\n      readonly toOld: (value: Value2) => Value\n    }\n  ) => Differ.Differ<Value2, Patch>\n>(2, (self, { toNew, toOld }) =>\n  make({\n    empty: self.empty,\n    combine: (first, second) => self.combine(first, second),\n    diff: (oldValue, newValue) => self.diff(toOld(oldValue), toOld(newValue)),\n    patch: (patch, oldValue) => toNew(self.patch(patch, toOld(oldValue)))\n  }))\n\n/** @internal */\nexport const update = <A>(): Differ.Differ<A, (a: A) => A> => updateWith((_, a) => a)\n\n/** @internal */\nexport const updateWith = <A>(f: (x: A, y: A) => A): Differ.Differ<A, (a: A) => A> =>\n  make({\n    empty: identity,\n    combine: (first, second) => {\n      if (first === identity) {\n        return second\n      }\n      if (second === identity) {\n        return first\n      }\n      return (a) => second(first(a))\n    },\n    diff: (oldValue, newValue) => {\n      if (Equal.equals(oldValue, newValue)) {\n        return identity\n      }\n      return constant(newValue)\n    },\n    patch: (patch, oldValue) => f(oldValue, patch(oldValue))\n  })\n\n/** @internal */\nexport const zip = Dual.dual<\n  <Value2, Patch2>(that: Differ.Differ<Value2, Patch2>) => <Value, Patch>(\n    self: Differ.Differ<Value, Patch>\n  ) => Differ.Differ<readonly [Value, Value2], readonly [Patch, Patch2]>,\n  <Value, Patch, Value2, Patch2>(\n    self: Differ.Differ<Value, Patch>,\n    that: Differ.Differ<Value2, Patch2>\n  ) => Differ.Differ<readonly [Value, Value2], readonly [Patch, Patch2]>\n>(2, (self, that) =>\n  make({\n    empty: [self.empty, that.empty] as const,\n    combine: (first, second) => [\n      self.combine(first[0], second[0]),\n      that.combine(first[1], second[1])\n    ],\n    diff: (oldValue, newValue) => [\n      self.diff(oldValue[0], newValue[0]),\n      that.diff(oldValue[1], newValue[1])\n    ],\n    patch: (patch, oldValue) => [\n      self.patch(patch[0], oldValue[0]),\n      that.patch(patch[1], oldValue[1])\n    ]\n  }))\n"
  },
  {
    "path": "packages/effect/src/internal/doNotation.ts",
    "content": "import { dual } from \"../Function.js\"\nimport type { Kind, TypeLambda } from \"../HKT.js\"\nimport type { NoInfer } from \"../Types.js\"\n\ntype Map<F extends TypeLambda> = {\n  <A, B>(f: (a: A) => B): <R, O, E>(self: Kind<F, R, O, E, A>) => Kind<F, R, O, E, B>\n  <R, O, E, A, B>(self: Kind<F, R, O, E, A>, f: (a: A) => B): Kind<F, R, O, E, B>\n}\n\ntype FlatMap<F extends TypeLambda> = {\n  <A, R2, O2, E2, B>(\n    f: (a: A) => Kind<F, R2, O2, E2, B>\n  ): <R1, O1, E1>(self: Kind<F, R1, O1, E1, A>) => Kind<F, R1 & R2, O1 | O2, E1 | E2, B>\n  <R1, O1, E1, A, R2, O2, E2, B>(\n    self: Kind<F, R1, O1, E1, A>,\n    f: (a: A) => Kind<F, R2, O2, E2, B>\n  ): Kind<F, R1 & R2, O1 | O2, E1 | E2, B>\n}\n\n/** @internal */\nexport const let_ = <F extends TypeLambda>(\n  map: Map<F>\n): {\n  <N extends string, A extends object, B>(\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): <R, O, E>(\n    self: Kind<F, R, O, E, A>\n  ) => Kind<F, R, O, E, { [K in keyof A | N]: K extends keyof A ? A[K] : B }>\n  <R, O, E, A extends object, N extends string, B>(\n    self: Kind<F, R, O, E, A>,\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): Kind<F, R, O, E, { [K in keyof A | N]: K extends keyof A ? A[K] : B }>\n} =>\n  dual(3, <R, O, E, A extends object, N extends string, B>(\n    self: Kind<F, R, O, E, A>,\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => B\n  ): Kind<F, R, O, E, { [K in keyof A | N]: K extends keyof A ? A[K] : B }> =>\n    map(self, (a) => ({ ...a, [name]: f(a) }) as any))\n\n/** @internal */\nexport const bindTo = <F extends TypeLambda>(map: Map<F>): {\n  <N extends string>(\n    name: N\n  ): <R, O, E, A>(self: Kind<F, R, O, E, A>) => Kind<F, R, O, E, { [K in N]: A }>\n  <R, O, E, A, N extends string>(\n    self: Kind<F, R, O, E, A>,\n    name: N\n  ): Kind<F, R, O, E, { [K in N]: A }>\n} =>\n  dual(2, <R, O, E, A, N extends string>(\n    self: Kind<F, R, O, E, A>,\n    name: N\n  ): Kind<F, R, O, E, { [K in N]: A }> => map(self, (a) => ({ [name]: a } as { [K in N]: A })))\n\n/** @internal */\nexport const bind = <F extends TypeLambda>(map: Map<F>, flatMap: FlatMap<F>): {\n  <N extends string, A extends object, R2, O2, E2, B>(\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => Kind<F, R2, O2, E2, B>\n  ): <R1, O1, E1>(\n    self: Kind<F, R1, O1, E1, A>\n  ) => Kind<F, R1 & R2, O1 | O2, E1 | E2, { [K in keyof A | N]: K extends keyof A ? A[K] : B }>\n  <R1, O1, E1, A extends object, N extends string, R2, O2, E2, B>(\n    self: Kind<F, R1, O1, E1, A>,\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => Kind<F, R2, O2, E2, B>\n  ): Kind<F, R1 & R2, O1 | O2, E1 | E2, { [K in keyof A | N]: K extends keyof A ? A[K] : B }>\n} =>\n  dual(3, <R1, O1, E1, A, N extends string, R2, O2, E2, B>(\n    self: Kind<F, R1, O1, E1, A>,\n    name: Exclude<N, keyof A>,\n    f: (a: NoInfer<A>) => Kind<F, R2, O2, E2, B>\n  ): Kind<F, R1 & R2, O1 | O2, E1 | E2, { [K in keyof A | N]: K extends keyof A ? A[K] : B }> =>\n    flatMap(\n      self,\n      (a) => map(f(a), (b) => ({ ...a, [name]: b }) as { [K in keyof A | N]: K extends keyof A ? A[K] : B })\n    ))\n"
  },
  {
    "path": "packages/effect/src/internal/effect/circular.ts",
    "content": "import type * as Cause from \"../../Cause.js\"\nimport type * as Deferred from \"../../Deferred.js\"\nimport * as Duration from \"../../Duration.js\"\nimport type * as Effect from \"../../Effect.js\"\nimport * as Effectable from \"../../Effectable.js\"\nimport * as Equal from \"../../Equal.js\"\nimport type { Equivalence } from \"../../Equivalence.js\"\nimport * as Exit from \"../../Exit.js\"\nimport type * as Fiber from \"../../Fiber.js\"\nimport * as FiberId from \"../../FiberId.js\"\nimport type * as FiberRefsPatch from \"../../FiberRefsPatch.js\"\nimport type { LazyArg } from \"../../Function.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as Hash from \"../../Hash.js\"\nimport * as MutableHashMap from \"../../MutableHashMap.js\"\nimport * as Option from \"../../Option.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport * as Predicate from \"../../Predicate.js\"\nimport * as Readable from \"../../Readable.js\"\nimport type * as Ref from \"../../Ref.js\"\nimport { currentScheduler } from \"../../Scheduler.js\"\nimport type * as Scope from \"../../Scope.js\"\nimport type * as Supervisor from \"../../Supervisor.js\"\nimport type * as Synchronized from \"../../SynchronizedRef.js\"\nimport type * as Types from \"../../Types.js\"\nimport * as internalCause from \"../cause.js\"\nimport * as effect from \"../core-effect.js\"\nimport * as core from \"../core.js\"\nimport * as internalFiber from \"../fiber.js\"\nimport * as fiberRuntime from \"../fiberRuntime.js\"\nimport { globalScope } from \"../fiberScope.js\"\nimport * as internalRef from \"../ref.js\"\nimport * as supervisor from \"../supervisor.js\"\n\n/** @internal */\nclass Semaphore {\n  public waiters = new Set<() => void>()\n  public taken = 0\n\n  constructor(public permits: number) {}\n\n  get free() {\n    return this.permits - this.taken\n  }\n\n  readonly take = (n: number): Effect.Effect<number> =>\n    core.asyncInterrupt<number>((resume) => {\n      if (this.free < n) {\n        const observer = () => {\n          if (this.free < n) return\n          this.waiters.delete(observer)\n          resume(core.suspend(() => {\n            if (this.free < n) return this.take(n)\n            this.taken += n\n            return core.succeed(n)\n          }))\n        }\n        this.waiters.add(observer)\n        return core.sync(() => {\n          this.waiters.delete(observer)\n        })\n      }\n      resume(core.suspend(() => {\n        if (this.free < n) return this.take(n)\n        this.taken += n\n        return core.succeed(n)\n      }))\n    })\n\n  updateTakenUnsafe(fiber: Fiber.RuntimeFiber<any, any>, f: (n: number) => number): Effect.Effect<number> {\n    this.taken = f(this.taken)\n    if (this.waiters.size > 0) {\n      fiber.getFiberRef(currentScheduler).scheduleTask(\n        () => {\n          const iter = this.waiters.values()\n          let item = iter.next()\n          while (item.done === false && this.free > 0) {\n            item.value()\n            item = iter.next()\n          }\n        },\n        fiber.getFiberRef(core.currentSchedulingPriority),\n        fiber\n      )\n    }\n    return core.succeed(this.free)\n  }\n\n  updateTaken(f: (n: number) => number): Effect.Effect<number> {\n    return core.withFiberRuntime((fiber) => this.updateTakenUnsafe(fiber, f))\n  }\n\n  readonly resize = (permits: number) =>\n    core.asVoid(\n      core.withFiberRuntime((fiber) => {\n        this.permits = permits\n        if (this.free < 0) {\n          return core.void\n        }\n        return this.updateTakenUnsafe(fiber, (taken) => taken)\n      })\n    )\n\n  readonly release = (n: number): Effect.Effect<number> => this.updateTaken((taken) => taken - n)\n\n  readonly releaseAll: Effect.Effect<number> = this.updateTaken((_) => 0)\n\n  readonly withPermits = (n: number) => <A, E, R>(self: Effect.Effect<A, E, R>) =>\n    core.uninterruptibleMask((restore) =>\n      core.flatMap(\n        restore(this.take(n)),\n        (permits) => fiberRuntime.ensuring(restore(self), this.release(permits))\n      )\n    )\n\n  readonly withPermitsIfAvailable = (n: number) => <A, E, R>(self: Effect.Effect<A, E, R>) =>\n    core.uninterruptibleMask((restore) =>\n      core.suspend(() => {\n        if (this.free < n) {\n          return effect.succeedNone\n        }\n        this.taken += n\n        return fiberRuntime.ensuring(restore(effect.asSome(self)), this.release(n))\n      })\n    )\n}\n\n/** @internal */\nexport const unsafeMakeSemaphore = (permits: number): Effect.Semaphore => new Semaphore(permits)\n\n/** @internal */\nexport const makeSemaphore = (permits: number) => core.sync(() => unsafeMakeSemaphore(permits))\n\nclass Latch extends Effectable.Class<void> implements Effect.Latch {\n  waiters: Array<(_: Effect.Effect<void>) => void> = []\n  scheduled = false\n  constructor(private isOpen: boolean) {\n    super()\n  }\n\n  commit() {\n    return this.await\n  }\n\n  private unsafeSchedule(fiber: Fiber.RuntimeFiber<void>) {\n    if (this.scheduled || this.waiters.length === 0) {\n      return core.void\n    }\n    this.scheduled = true\n    fiber.currentScheduler.scheduleTask(this.flushWaiters, fiber.getFiberRef(core.currentSchedulingPriority), fiber)\n    return core.void\n  }\n  private flushWaiters = () => {\n    this.scheduled = false\n    const waiters = this.waiters\n    this.waiters = []\n    for (let i = 0; i < waiters.length; i++) {\n      waiters[i](core.exitVoid)\n    }\n  }\n\n  open = core.withFiberRuntime<void>((fiber) => {\n    if (this.isOpen) {\n      return core.void\n    }\n    this.isOpen = true\n    return this.unsafeSchedule(fiber)\n  })\n  unsafeOpen() {\n    if (this.isOpen) return\n    this.isOpen = true\n    this.flushWaiters()\n  }\n  release = core.withFiberRuntime<void>((fiber) => {\n    if (this.isOpen) {\n      return core.void\n    }\n    return this.unsafeSchedule(fiber)\n  })\n  await = core.asyncInterrupt<void>((resume) => {\n    if (this.isOpen) {\n      return resume(core.void)\n    }\n    this.waiters.push(resume)\n    return core.sync(() => {\n      const index = this.waiters.indexOf(resume)\n      if (index !== -1) {\n        this.waiters.splice(index, 1)\n      }\n    })\n  })\n  unsafeClose() {\n    this.isOpen = false\n  }\n  close = core.sync(() => {\n    this.isOpen = false\n  })\n  whenOpen = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => {\n    return core.zipRight(this.await, self)\n  }\n}\n\n/** @internal */\nexport const unsafeMakeLatch = (open?: boolean | undefined): Effect.Latch => new Latch(open ?? false)\n\n/** @internal */\nexport const makeLatch = (open?: boolean | undefined) => core.sync(() => unsafeMakeLatch(open))\n\n/** @internal */\nexport const awaitAllChildren = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  ensuringChildren(self, fiberRuntime.fiberAwaitAll)\n\n/** @internal */\nexport const cached: {\n  (\n    timeToLive: Duration.DurationInput\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Effect.Effect<A, E>, never, R>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    timeToLive: Duration.DurationInput\n  ): Effect.Effect<Effect.Effect<A, E>, never, R>\n} = dual(\n  2,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    timeToLive: Duration.DurationInput\n  ): Effect.Effect<Effect.Effect<A, E>, never, R> =>\n    core.map(cachedInvalidateWithTTL(self, timeToLive), (tuple) => tuple[0])\n)\n\n/** @internal */\nexport const cachedInvalidateWithTTL: {\n  (timeToLive: Duration.DurationInput): <A, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<[Effect.Effect<A, E>, Effect.Effect<void>], never, R>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    timeToLive: Duration.DurationInput\n  ): Effect.Effect<[Effect.Effect<A, E>, Effect.Effect<void>], never, R>\n} = dual(\n  2,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    timeToLive: Duration.DurationInput\n  ): Effect.Effect<[Effect.Effect<A, E>, Effect.Effect<void>], never, R> => {\n    const duration = Duration.decode(timeToLive)\n    return core.flatMap(\n      core.context<R>(),\n      (env) =>\n        core.map(\n          makeSynchronized<Option.Option<readonly [number, Deferred.Deferred<A, E>]>>(Option.none()),\n          (cache) =>\n            [\n              core.provideContext(getCachedValue(self, duration, cache), env),\n              invalidateCache(cache)\n            ] as [Effect.Effect<A, E>, Effect.Effect<void>]\n        )\n    )\n  }\n)\n\n/** @internal */\nconst computeCachedValue = <A, E, R>(\n  self: Effect.Effect<A, E, R>,\n  timeToLive: Duration.DurationInput,\n  start: number\n): Effect.Effect<Option.Option<[number, Deferred.Deferred<A, E>]>, never, R> => {\n  const timeToLiveMillis = Duration.toMillis(Duration.decode(timeToLive))\n  return pipe(\n    core.deferredMake<A, E>(),\n    core.tap((deferred) => core.intoDeferred(self, deferred)),\n    core.map((deferred) => Option.some([start + timeToLiveMillis, deferred]))\n  )\n}\n\n/** @internal */\nconst getCachedValue = <A, E, R>(\n  self: Effect.Effect<A, E, R>,\n  timeToLive: Duration.DurationInput,\n  cache: Synchronized.SynchronizedRef<Option.Option<readonly [number, Deferred.Deferred<A, E>]>>\n): Effect.Effect<A, E, R> =>\n  core.uninterruptibleMask((restore) =>\n    pipe(\n      effect.clockWith((clock) => clock.currentTimeMillis),\n      core.flatMap((time) =>\n        updateSomeAndGetEffectSynchronized(cache, (option) => {\n          switch (option._tag) {\n            case \"None\": {\n              return Option.some(computeCachedValue(self, timeToLive, time))\n            }\n            case \"Some\": {\n              const [end] = option.value\n              return end - time <= 0\n                ? Option.some(computeCachedValue(self, timeToLive, time))\n                : Option.none()\n            }\n          }\n        })\n      ),\n      core.flatMap((option) =>\n        Option.isNone(option) ?\n          core.dieMessage(\n            \"BUG: Effect.cachedInvalidate - please report an issue at https://github.com/Effect-TS/effect/issues\"\n          ) :\n          restore(core.deferredAwait(option.value[1]))\n      )\n    )\n  )\n\n/** @internal */\nconst invalidateCache = <A, E>(\n  cache: Synchronized.SynchronizedRef<Option.Option<readonly [number, Deferred.Deferred<A, E>]>>\n): Effect.Effect<void> => internalRef.set(cache, Option.none())\n\n/** @internal */\nexport const ensuringChild = dual<\n  <X, R2>(\n    f: (fiber: Fiber.Fiber<ReadonlyArray<unknown>, any>) => Effect.Effect<X, never, R2>\n  ) => <A, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<A, E, R | R2>,\n  <A, E, R, X, R2>(\n    self: Effect.Effect<A, E, R>,\n    f: (fiber: Fiber.Fiber<ReadonlyArray<unknown>, any>) => Effect.Effect<X, never, R2>\n  ) => Effect.Effect<A, E, R | R2>\n>(2, (self, f) => ensuringChildren(self, (children) => f(fiberRuntime.fiberAll(children))))\n\n/** @internal */\nexport const ensuringChildren = dual<\n  <X, R2>(\n    children: (fibers: ReadonlyArray<Fiber.RuntimeFiber<any, any>>) => Effect.Effect<X, never, R2>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R | R2>,\n  <A, E, R, X, R2>(\n    self: Effect.Effect<A, E, R>,\n    children: (fibers: ReadonlyArray<Fiber.RuntimeFiber<any, any>>) => Effect.Effect<X, never, R2>\n  ) => Effect.Effect<A, E, R | R2>\n>(2, (self, children) =>\n  core.flatMap(supervisor.track, (supervisor) =>\n    pipe(\n      supervised(self, supervisor),\n      fiberRuntime.ensuring(core.flatMap(supervisor.value, children))\n    )))\n\n/** @internal */\nexport const forkAll: {\n  (\n    options?: {\n      readonly discard?: false | undefined\n    }\n  ): <Eff extends Effect.Effect<any, any, any>>(\n    effects: Iterable<Eff>\n  ) => Effect.Effect<\n    Fiber.Fiber<Array<Effect.Effect.Success<Eff>>, Effect.Effect.Error<Eff>>,\n    never,\n    Effect.Effect.Context<Eff>\n  >\n  (options: {\n    readonly discard: true\n  }): <Eff extends Effect.Effect<any, any, any>>(\n    effects: Iterable<Eff>\n  ) => Effect.Effect<void, never, Effect.Effect.Context<Eff>>\n  <Eff extends Effect.Effect<any, any, any>>(\n    effects: Iterable<Eff>,\n    options?: {\n      readonly discard?: false | undefined\n    }\n  ): Effect.Effect<\n    Fiber.Fiber<Array<Effect.Effect.Success<Eff>>, Effect.Effect.Error<Eff>>,\n    never,\n    Effect.Effect.Context<Eff>\n  >\n  <Eff extends Effect.Effect<any, any, any>>(effects: Iterable<Eff>, options: {\n    readonly discard: true\n  }): Effect.Effect<void, never, Effect.Effect.Context<Eff>>\n} = dual((args) => Predicate.isIterable(args[0]), <A, E, R>(effects: Iterable<Effect.Effect<A, E, R>>, options: {\n  readonly discard: true\n}): Effect.Effect<void, never, R> =>\n  options?.discard ?\n    core.forEachSequentialDiscard(effects, fiberRuntime.fork) :\n    core.map(core.forEachSequential(effects, fiberRuntime.fork), fiberRuntime.fiberAll))\n\n/** @internal */\nexport const forkIn = dual<\n  (scope: Scope.Scope) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, scope: Scope.Scope) => Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R>\n>(\n  2,\n  (self, scope) =>\n    core.withFiberRuntime((parent, parentStatus) => {\n      const scopeImpl = scope as fiberRuntime.ScopeImpl\n      const fiber = fiberRuntime.unsafeFork(self, parent, parentStatus.runtimeFlags, globalScope)\n      if (scopeImpl.state._tag === \"Open\") {\n        const finalizer = () =>\n          core.fiberIdWith((fiberId) =>\n            Equal.equals(fiberId, fiber.id()) ?\n              core.void :\n              core.asVoid(core.interruptFiber(fiber))\n          )\n        const key = {}\n        scopeImpl.state.finalizers.set(key, finalizer)\n        fiber.addObserver(() => {\n          if (scopeImpl.state._tag === \"Closed\") return\n          scopeImpl.state.finalizers.delete(key)\n        })\n      } else {\n        fiber.unsafeInterruptAsFork(parent.id())\n      }\n      return core.succeed(fiber)\n    })\n)\n\n/** @internal */\nexport const forkScoped = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R | Scope.Scope> =>\n  fiberRuntime.scopeWith((scope) => forkIn(self, scope))\n\n/** @internal */\nexport const fromFiber = <A, E>(fiber: Fiber.Fiber<A, E>): Effect.Effect<A, E> => internalFiber.join(fiber)\n\n/** @internal */\nexport const fromFiberEffect = <A, E, R>(fiber: Effect.Effect<Fiber.Fiber<A, E>, E, R>): Effect.Effect<A, E, R> =>\n  core.suspend(() => core.flatMap(fiber, internalFiber.join))\n\nconst memoKeySymbol = Symbol.for(\"effect/Effect/memoizeFunction.key\")\n\nclass Key<in out A> implements Equal.Equal {\n  [memoKeySymbol] = memoKeySymbol\n  constructor(readonly a: A, readonly eq?: Equivalence<A>) {}\n  [Equal.symbol](that: Equal.Equal) {\n    if (Predicate.hasProperty(that, memoKeySymbol)) {\n      if (this.eq) {\n        return this.eq(this.a, (that as unknown as Key<A>).a)\n      } else {\n        return Equal.equals(this.a, (that as unknown as Key<A>).a)\n      }\n    }\n    return false\n  }\n  [Hash.symbol]() {\n    return this.eq ? 0 : Hash.cached(this, Hash.hash(this.a))\n  }\n}\n\n/** @internal */\nexport const cachedFunction = <A, B, E, R>(\n  f: (a: A) => Effect.Effect<B, E, R>,\n  eq?: Equivalence<A>\n): Effect.Effect<(a: A) => Effect.Effect<B, E, R>> => {\n  return pipe(\n    core.sync(() => MutableHashMap.empty<Key<A>, Deferred.Deferred<readonly [FiberRefsPatch.FiberRefsPatch, B], E>>()),\n    core.flatMap(makeSynchronized),\n    core.map((ref) => (a: A) =>\n      pipe(\n        ref.modifyEffect((map) => {\n          const result = pipe(map, MutableHashMap.get(new Key(a, eq)))\n          if (Option.isNone(result)) {\n            return pipe(\n              core.deferredMake<readonly [FiberRefsPatch.FiberRefsPatch, B], E>(),\n              core.tap((deferred) =>\n                pipe(\n                  effect.diffFiberRefs(f(a)),\n                  core.intoDeferred(deferred),\n                  fiberRuntime.fork\n                )\n              ),\n              core.map((deferred) => [deferred, pipe(map, MutableHashMap.set(new Key(a, eq), deferred))] as const)\n            )\n          }\n          return core.succeed([result.value, map] as const)\n        }),\n        core.flatMap(core.deferredAwait),\n        core.flatMap(([patch, b]) => pipe(effect.patchFiberRefs(patch), core.as(b)))\n      )\n    )\n  )\n}\n\n/** @internal */\nexport const raceFirst = dual<\n  <A2, E2, R2>(\n    that: Effect.Effect<A2, E2, R2>\n  ) => <A, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<A2 | A, E2 | E, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>\n  ) => Effect.Effect<A2 | A, E2 | E, R | R2>\n>(2, <A, E, R, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  that: Effect.Effect<A2, E2, R2>\n) =>\n  pipe(\n    core.exit(self),\n    fiberRuntime.race(core.exit(that)),\n    (effect: Effect.Effect<Exit.Exit<A | A2, E | E2>, never, R | R2>) => core.flatten(effect)\n  ))\n\n/** @internal */\nexport const supervised = dual<\n  <X>(supervisor: Supervisor.Supervisor<X>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R, X>(self: Effect.Effect<A, E, R>, supervisor: Supervisor.Supervisor<X>) => Effect.Effect<A, E, R>\n>(2, (self, supervisor) => {\n  const supervise = core.fiberRefLocallyWith(fiberRuntime.currentSupervisor, (s) => s.zip(supervisor))\n  return supervise(self)\n})\n\n/** @internal */\nexport const timeout = dual<\n  (\n    duration: Duration.DurationInput\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | Cause.TimeoutException, R>,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    duration: Duration.DurationInput\n  ) => Effect.Effect<A, E | Cause.TimeoutException, R>\n>(2, (self, duration) =>\n  timeoutFail(self, {\n    onTimeout: () => core.timeoutExceptionFromDuration(duration),\n    duration\n  }))\n\n/** @internal */\nexport const timeoutFail = dual<\n  <E1>(\n    options: {\n      readonly onTimeout: LazyArg<E1>\n      readonly duration: Duration.DurationInput\n    }\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E1, R>,\n  <A, E, R, E1>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly onTimeout: LazyArg<E1>\n      readonly duration: Duration.DurationInput\n    }\n  ) => Effect.Effect<A, E | E1, R>\n>(2, (self, { duration, onTimeout }) =>\n  core.flatten(timeoutTo(self, {\n    onTimeout: () => core.failSync(onTimeout),\n    onSuccess: core.succeed,\n    duration\n  })))\n\n/** @internal */\nexport const timeoutFailCause = dual<\n  <E1>(\n    options: {\n      readonly onTimeout: LazyArg<Cause.Cause<E1>>\n      readonly duration: Duration.DurationInput\n    }\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E1, R>,\n  <A, E, R, E1>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly onTimeout: LazyArg<Cause.Cause<E1>>\n      readonly duration: Duration.DurationInput\n    }\n  ) => Effect.Effect<A, E | E1, R>\n>(2, (self, { duration, onTimeout }) =>\n  core.flatten(timeoutTo(self, {\n    onTimeout: () => core.failCauseSync(onTimeout),\n    onSuccess: core.succeed,\n    duration\n  })))\n\n/** @internal */\nexport const timeoutOption = dual<\n  (\n    duration: Duration.DurationInput\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Option.Option<A>, E, R>,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    duration: Duration.DurationInput\n  ) => Effect.Effect<Option.Option<A>, E, R>\n>(2, (self, duration) =>\n  timeoutTo(self, {\n    duration,\n    onSuccess: Option.some,\n    onTimeout: Option.none\n  }))\n\n/** @internal */\nexport const timeoutTo = dual<\n  <A, B, B1>(\n    options: {\n      readonly onTimeout: LazyArg<B1>\n      readonly onSuccess: (a: A) => B\n      readonly duration: Duration.DurationInput\n    }\n  ) => <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B | B1, E, R>,\n  <A, E, R, B1, B>(\n    self: Effect.Effect<A, E, R>,\n    options: {\n      readonly onTimeout: LazyArg<B1>\n      readonly onSuccess: (a: A) => B\n      readonly duration: Duration.DurationInput\n    }\n  ) => Effect.Effect<B | B1, E, R>\n>(\n  2,\n  (self, { duration, onSuccess, onTimeout }) =>\n    core.fiberIdWith((parentFiberId) =>\n      core.uninterruptibleMask((restore) =>\n        fiberRuntime.raceFibersWith(\n          restore(self),\n          core.interruptible(effect.sleep(duration)),\n          {\n            onSelfWin: (winner, loser) =>\n              core.flatMap(\n                winner.await,\n                (exit) => {\n                  if (exit._tag === \"Success\") {\n                    return core.flatMap(\n                      winner.inheritAll,\n                      () =>\n                        core.as(\n                          core.interruptAsFiber(loser, parentFiberId),\n                          onSuccess(exit.value)\n                        )\n                    )\n                  } else {\n                    return core.flatMap(\n                      core.interruptAsFiber(loser, parentFiberId),\n                      () => core.exitFailCause(exit.cause)\n                    )\n                  }\n                }\n              ),\n            onOtherWin: (winner, loser) =>\n              core.flatMap(\n                winner.await,\n                (exit) => {\n                  if (exit._tag === \"Success\") {\n                    return core.flatMap(\n                      winner.inheritAll,\n                      () =>\n                        core.as(\n                          core.interruptAsFiber(loser, parentFiberId),\n                          onTimeout()\n                        )\n                    )\n                  } else {\n                    return core.flatMap(\n                      core.interruptAsFiber(loser, parentFiberId),\n                      () => core.exitFailCause(exit.cause)\n                    )\n                  }\n                }\n              ),\n            otherScope: globalScope\n          }\n        )\n      )\n    )\n)\n\n// circular with Synchronized\n\n/** @internal */\nconst SynchronizedSymbolKey = \"effect/Ref/SynchronizedRef\"\n\n/** @internal */\nexport const SynchronizedTypeId: Synchronized.SynchronizedRefTypeId = Symbol.for(\n  SynchronizedSymbolKey\n) as Synchronized.SynchronizedRefTypeId\n\n/** @internal */\nexport const synchronizedVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nclass SynchronizedImpl<in out A> extends Effectable.Class<A> implements Synchronized.SynchronizedRef<A> {\n  readonly [SynchronizedTypeId] = synchronizedVariance\n  readonly [internalRef.RefTypeId] = internalRef.refVariance\n  readonly [Readable.TypeId]: Readable.TypeId = Readable.TypeId\n  constructor(\n    readonly ref: Ref.Ref<A>,\n    readonly withLock: <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  ) {\n    super()\n    this.get = internalRef.get(this.ref)\n  }\n  readonly get: Effect.Effect<A>\n  commit() {\n    return this.get\n  }\n  modify<B>(f: (a: A) => readonly [B, A]): Effect.Effect<B> {\n    return this.modifyEffect((a) => core.succeed(f(a)))\n  }\n  modifyEffect<B, E, R>(f: (a: A) => Effect.Effect<readonly [B, A], E, R>): Effect.Effect<B, E, R> {\n    return this.withLock(\n      pipe(\n        core.flatMap(internalRef.get(this.ref), f),\n        core.flatMap(([b, a]) => core.as(internalRef.set(this.ref, a), b))\n      )\n    )\n  }\n}\n\n/** @internal */\nexport const makeSynchronized = <A>(value: A): Effect.Effect<Synchronized.SynchronizedRef<A>> =>\n  core.sync(() => unsafeMakeSynchronized(value))\n\n/** @internal */\nexport const unsafeMakeSynchronized = <A>(value: A): Synchronized.SynchronizedRef<A> => {\n  const ref = internalRef.unsafeMake(value)\n  const sem = unsafeMakeSemaphore(1)\n  return new SynchronizedImpl(ref, sem.withPermits(1))\n}\n\n/** @internal */\nexport const updateSomeAndGetEffectSynchronized = dual<\n  <A, R, E>(\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ) => (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<A, E, R>,\n  <A, R, E>(\n    self: Synchronized.SynchronizedRef<A>,\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ) => Effect.Effect<A, E, R>\n>(2, (self, pf) =>\n  self.modifyEffect((value) => {\n    const result = pf(value)\n    switch (result._tag) {\n      case \"None\": {\n        return core.succeed([value, value] as const)\n      }\n      case \"Some\": {\n        return core.map(result.value, (a) => [a, a] as const)\n      }\n    }\n  }))\n\n// circular with Fiber\n\n/** @internal */\nexport const zipFiber = dual<\n  <A2, E2>(that: Fiber.Fiber<A2, E2>) => <A, E>(self: Fiber.Fiber<A, E>) => Fiber.Fiber<[A, A2], E | E2>,\n  <A, E, A2, E2>(self: Fiber.Fiber<A, E>, that: Fiber.Fiber<A2, E2>) => Fiber.Fiber<[A, A2], E | E2>\n>(2, (self, that) => zipWithFiber(self, that, (a, b) => [a, b]))\n\n/** @internal */\nexport const zipLeftFiber = dual<\n  <A2, E2>(that: Fiber.Fiber<A2, E2>) => <A, E>(self: Fiber.Fiber<A, E>) => Fiber.Fiber<A, E | E2>,\n  <A, E, A2, E2>(self: Fiber.Fiber<A, E>, that: Fiber.Fiber<A2, E2>) => Fiber.Fiber<A, E | E2>\n>(2, (self, that) => zipWithFiber(self, that, (a, _) => a))\n\n/** @internal */\nexport const zipRightFiber = dual<\n  <A2, E2>(that: Fiber.Fiber<A2, E2>) => <A, E>(self: Fiber.Fiber<A, E>) => Fiber.Fiber<A2, E | E2>,\n  <A, E, A2, E2>(self: Fiber.Fiber<A, E>, that: Fiber.Fiber<A2, E2>) => Fiber.Fiber<A2, E | E2>\n>(2, (self, that) => zipWithFiber(self, that, (_, b) => b))\n\n/** @internal */\nexport const zipWithFiber = dual<\n  <B, E2, A, C>(\n    that: Fiber.Fiber<B, E2>,\n    f: (a: A, b: B) => C\n  ) => <E>(self: Fiber.Fiber<A, E>) => Fiber.Fiber<C, E | E2>,\n  <A, E, B, E2, C>(\n    self: Fiber.Fiber<A, E>,\n    that: Fiber.Fiber<B, E2>,\n    f: (a: A, b: B) => C\n  ) => Fiber.Fiber<C, E | E2>\n>(3, (self, that, f) => ({\n  ...Effectable.CommitPrototype,\n  commit() {\n    return internalFiber.join(this)\n  },\n  [internalFiber.FiberTypeId]: internalFiber.fiberVariance,\n  id: () => pipe(self.id(), FiberId.getOrElse(that.id())),\n  await: pipe(\n    self.await,\n    core.flatten,\n    fiberRuntime.zipWithOptions(core.flatten(that.await), f, { concurrent: true }),\n    core.exit\n  ),\n  children: self.children,\n  inheritAll: core.zipRight(\n    that.inheritAll,\n    self.inheritAll\n  ),\n  poll: core.zipWith(\n    self.poll,\n    that.poll,\n    (optionA, optionB) =>\n      pipe(\n        optionA,\n        Option.flatMap((exitA) =>\n          pipe(\n            optionB,\n            Option.map((exitB) =>\n              Exit.zipWith(exitA, exitB, {\n                onSuccess: f,\n                onFailure: internalCause.parallel\n              })\n            )\n          )\n        )\n      )\n  ),\n  interruptAsFork: (id) =>\n    core.zipRight(\n      self.interruptAsFork(id),\n      that.interruptAsFork(id)\n    ),\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}))\n\n/* @internal */\nexport const bindAll: {\n  <\n    A extends object,\n    X extends Record<string, Effect.Effect<any, any, any>>,\n    O extends Types.NoExcessProperties<{\n      readonly concurrency?: Types.Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }, O>\n  >(\n    f: (a: A) => [Extract<keyof X, keyof A>] extends [never] ? X : `Duplicate keys`,\n    options?: undefined | O\n  ): <E1, R1>(\n    self: Effect.Effect<A, E1, R1>\n  ) => [Effect.All.ReturnObject<X, false, Effect.All.ExtractMode<O>>] extends\n    [Effect.Effect<infer Success, infer Error, infer Context>] ? Effect.Effect<\n      {\n        [K in keyof A | keyof Success]: K extends keyof A ? A[K]\n          : K extends keyof Success ? Success[K]\n          : never\n      },\n      | E1\n      | Error,\n      R1 | Context\n    >\n    : never\n\n  <\n    A extends object,\n    X extends Record<string, Effect.Effect<any, any, any>>,\n    O extends Types.NoExcessProperties<{\n      readonly concurrency?: Types.Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }, O>,\n    E1,\n    R1\n  >(\n    self: Effect.Effect<A, E1, R1>,\n    f: (a: A) => [Extract<keyof X, keyof A>] extends [never] ? X : `Duplicate keys`,\n    options?: undefined | {\n      readonly concurrency?: Types.Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): [Effect.All.ReturnObject<X, false, Effect.All.ExtractMode<O>>] extends\n    [Effect.Effect<infer Success, infer Error, infer Context>] ? Effect.Effect<\n      {\n        [K in keyof A | keyof Success]: K extends keyof A ? A[K]\n          : K extends keyof Success ? Success[K]\n          : never\n      },\n      | E1\n      | Error,\n      R1 | Context\n    >\n    : never\n} = dual((args) => core.isEffect(args[0]), <\n  A extends object,\n  X extends Record<string, Effect.Effect<any, any, any>>,\n  O extends Types.NoExcessProperties<{\n    readonly concurrency?: Types.Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }, O>,\n  E1,\n  R1\n>(\n  self: Effect.Effect<A, E1, R1>,\n  f: (a: A) => X,\n  options?: undefined | O\n) =>\n  core.flatMap(\n    self,\n    (a) =>\n      (fiberRuntime.all(f(a), options) as Effect.All.ReturnObject<\n        X,\n        Effect.All.IsDiscard<O>,\n        Effect.All.ExtractMode<O>\n      >)\n        .pipe(\n          core.map((record) => Object.assign({}, a, record))\n        )\n  ))\n"
  },
  {
    "path": "packages/effect/src/internal/effectable.ts",
    "content": "import type * as Channel from \"../Channel.js\"\nimport type * as Effect from \"../Effect.js\"\nimport type * as Effectable from \"../Effectable.js\"\nimport * as Equal from \"../Equal.js\"\nimport * as Hash from \"../Hash.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport type * as Sink from \"../Sink.js\"\nimport type * as Stream from \"../Stream.js\"\nimport { SingleShotGen, YieldWrap } from \"../Utils.js\"\nimport * as OpCodes from \"./opCodes/effect.js\"\nimport * as version from \"./version.js\"\n\n/** @internal */\nexport const EffectTypeId: Effect.EffectTypeId = Symbol.for(\"effect/Effect\") as Effect.EffectTypeId\n\n/** @internal */\nexport const StreamTypeId: Stream.StreamTypeId = Symbol.for(\"effect/Stream\") as Stream.StreamTypeId\n\n/** @internal */\nexport const SinkTypeId: Sink.SinkTypeId = Symbol.for(\"effect/Sink\") as Sink.SinkTypeId\n\n/** @internal */\nexport const ChannelTypeId: Channel.ChannelTypeId = Symbol.for(\"effect/Channel\") as Channel.ChannelTypeId\n\n/** @internal */\nexport const effectVariance = {\n  /* c8 ignore next */\n  _R: (_: never) => _,\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _A: (_: never) => _,\n\n  _V: version.getCurrentVersion()\n}\n\nconst sinkVariance = {\n  /* c8 ignore next */\n  _A: (_: never) => _,\n  /* c8 ignore next */\n  _In: (_: unknown) => _,\n  /* c8 ignore next */\n  _L: (_: never) => _,\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _R: (_: never) => _\n}\n\nconst channelVariance = {\n  /* c8 ignore next */\n  _Env: (_: never) => _,\n  /* c8 ignore next */\n  _InErr: (_: unknown) => _,\n  /* c8 ignore next */\n  _InElem: (_: unknown) => _,\n  /* c8 ignore next */\n  _InDone: (_: unknown) => _,\n  /* c8 ignore next */\n  _OutErr: (_: never) => _,\n  /* c8 ignore next */\n  _OutElem: (_: never) => _,\n  /* c8 ignore next */\n  _OutDone: (_: never) => _\n}\n\n/** @internal */\nexport const EffectPrototype: Effect.Effect<never> & Equal.Equal = {\n  [EffectTypeId]: effectVariance,\n  [StreamTypeId]: effectVariance,\n  [SinkTypeId]: sinkVariance,\n  [ChannelTypeId]: channelVariance,\n  [Equal.symbol](that: any) {\n    return this === that\n  },\n  [Hash.symbol]() {\n    return Hash.cached(this, Hash.random(this))\n  },\n  [Symbol.iterator]() {\n    return new SingleShotGen(new YieldWrap(this)) as any\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const StructuralPrototype: Equal.Equal = {\n  [Hash.symbol]() {\n    return Hash.cached(this, Hash.structure(this))\n  },\n  [Equal.symbol](this: Equal.Equal, that: Equal.Equal) {\n    const selfKeys = Object.keys(this)\n    const thatKeys = Object.keys(that as object)\n    if (selfKeys.length !== thatKeys.length) {\n      return false\n    }\n    for (const key of selfKeys) {\n      if (!(key in (that as object) && Equal.equals((this as any)[key], (that as any)[key]))) {\n        return false\n      }\n    }\n    return true\n  }\n}\n\n/** @internal */\nexport const CommitPrototype: Effect.Effect<never> = {\n  ...EffectPrototype,\n  _op: OpCodes.OP_COMMIT\n} as any\n\n/** @internal */\nexport const StructuralCommitPrototype: Effect.Effect<never> = {\n  ...CommitPrototype,\n  ...StructuralPrototype\n} as any\n\n/** @internal */\nexport const Base: Effectable.CommitPrimitive = (function() {\n  function Base() {}\n  Base.prototype = CommitPrototype\n  return Base as any\n})()\n\n/** @internal */\nexport const StructuralBase: Effectable.CommitPrimitive = (function() {\n  function Base() {}\n  Base.prototype = StructuralCommitPrototype\n  return Base as any\n})()\n"
  },
  {
    "path": "packages/effect/src/internal/either.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport type * as Either from \"../Either.js\"\nimport * as Equal from \"../Equal.js\"\nimport { dual } from \"../Function.js\"\nimport * as Hash from \"../Hash.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"../Inspectable.js\"\nimport type { Option } from \"../Option.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport { EffectPrototype } from \"./effectable.js\"\nimport * as option from \"./option.js\"\n\n/**\n * @internal\n */\nexport const TypeId: Either.TypeId = Symbol.for(\"effect/Either\") as Either.TypeId\n\nconst CommonProto = {\n  ...EffectPrototype,\n  [TypeId]: {\n    _R: (_: never) => _\n  },\n  [NodeInspectSymbol]<L, R>(this: Either.Either<R, L>) {\n    return this.toJSON()\n  },\n  toString<L, R>(this: Either.Left<L, R>) {\n    return format(this.toJSON())\n  }\n}\n\nconst RightProto = Object.assign(Object.create(CommonProto), {\n  _tag: \"Right\",\n  _op: \"Right\",\n  [Equal.symbol]<L, R>(this: Either.Right<L, R>, that: unknown): boolean {\n    return isEither(that) && isRight(that) && Equal.equals(this.right, that.right)\n  },\n  [Hash.symbol]<L, R>(this: Either.Right<L, R>) {\n    return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.right))\n  },\n  toJSON<L, R>(this: Either.Right<L, R>) {\n    return {\n      _id: \"Either\",\n      _tag: this._tag,\n      right: toJSON(this.right)\n    }\n  }\n})\n\nconst LeftProto = Object.assign(Object.create(CommonProto), {\n  _tag: \"Left\",\n  _op: \"Left\",\n  [Equal.symbol]<L, R>(this: Either.Left<L, R>, that: unknown): boolean {\n    return isEither(that) && isLeft(that) && Equal.equals(this.left, that.left)\n  },\n  [Hash.symbol]<L, R>(this: Either.Left<L, R>) {\n    return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.left))\n  },\n  toJSON<E, A>(this: Either.Left<E, A>) {\n    return {\n      _id: \"Either\",\n      _tag: this._tag,\n      left: toJSON(this.left)\n    }\n  }\n})\n\n/** @internal */\nexport const isEither = (input: unknown): input is Either.Either<unknown, unknown> => hasProperty(input, TypeId)\n\n/** @internal */\nexport const isLeft = <R, L>(ma: Either.Either<R, L>): ma is Either.Left<L, R> => ma._tag === \"Left\"\n\n/** @internal */\nexport const isRight = <R, L>(ma: Either.Either<R, L>): ma is Either.Right<L, R> => ma._tag === \"Right\"\n\n/** @internal */\nexport const left = <L>(left: L): Either.Either<never, L> => {\n  const a = Object.create(LeftProto)\n  a.left = left\n  return a\n}\n\n/** @internal */\nexport const right = <R>(right: R): Either.Either<R> => {\n  const a = Object.create(RightProto)\n  a.right = right\n  return a\n}\n\n/** @internal */\nexport const getLeft = <R, L>(\n  self: Either.Either<R, L>\n): Option<L> => (isRight(self) ? option.none : option.some(self.left))\n\n/** @internal */\nexport const getRight = <R, L>(\n  self: Either.Either<R, L>\n): Option<R> => (isLeft(self) ? option.none : option.some(self.right))\n\n/** @internal */\nexport const fromOption: {\n  <L>(onNone: () => L): <R>(self: Option<R>) => Either.Either<R, L>\n  <R, L>(self: Option<R>, onNone: () => L): Either.Either<R, L>\n} = dual(\n  2,\n  <R, L>(self: Option<R>, onNone: () => L): Either.Either<R, L> =>\n    option.isNone(self) ? left(onNone()) : right(self.value)\n)\n"
  },
  {
    "path": "packages/effect/src/internal/encoding/base64.ts",
    "content": "import * as Either from \"../../Either.js\"\nimport type * as Encoding from \"../../Encoding.js\"\nimport { DecodeException } from \"./common.js\"\n\n/** @internal */\nexport const encode = (bytes: Uint8Array) => {\n  const length = bytes.length\n\n  let result = \"\"\n  let i: number\n\n  for (i = 2; i < length; i += 3) {\n    result += base64abc[bytes[i - 2] >> 2]\n    result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]\n    result += base64abc[((bytes[i - 1] & 0x0f) << 2) | (bytes[i] >> 6)]\n    result += base64abc[bytes[i] & 0x3f]\n  }\n\n  if (i === length + 1) {\n    // 1 octet yet to write\n    result += base64abc[bytes[i - 2] >> 2]\n    result += base64abc[(bytes[i - 2] & 0x03) << 4]\n    result += \"==\"\n  }\n\n  if (i === length) {\n    // 2 octets yet to write\n    result += base64abc[bytes[i - 2] >> 2]\n    result += base64abc[((bytes[i - 2] & 0x03) << 4) | (bytes[i - 1] >> 4)]\n    result += base64abc[(bytes[i - 1] & 0x0f) << 2]\n    result += \"=\"\n  }\n\n  return result\n}\n\n/** @internal */\nexport const decode = (str: string): Either.Either<Uint8Array, Encoding.DecodeException> => {\n  const stripped = stripCrlf(str)\n  const length = stripped.length\n  if (length % 4 !== 0) {\n    return Either.left(\n      DecodeException(stripped, `Length must be a multiple of 4, but is ${length}`)\n    )\n  }\n\n  const index = stripped.indexOf(\"=\")\n  if (index !== -1 && ((index < length - 2) || (index === length - 2 && stripped[length - 1] !== \"=\"))) {\n    return Either.left(\n      DecodeException(stripped, \"Found a '=' character, but it is not at the end\")\n    )\n  }\n\n  try {\n    const missingOctets = stripped.endsWith(\"==\") ? 2 : stripped.endsWith(\"=\") ? 1 : 0\n    const result = new Uint8Array(3 * (length / 4) - missingOctets)\n    for (let i = 0, j = 0; i < length; i += 4, j += 3) {\n      const buffer = getBase64Code(stripped.charCodeAt(i)) << 18 |\n        getBase64Code(stripped.charCodeAt(i + 1)) << 12 |\n        getBase64Code(stripped.charCodeAt(i + 2)) << 6 |\n        getBase64Code(stripped.charCodeAt(i + 3))\n\n      result[j] = buffer >> 16\n      result[j + 1] = (buffer >> 8) & 0xff\n      result[j + 2] = buffer & 0xff\n    }\n\n    return Either.right(result)\n  } catch (e) {\n    return Either.left(\n      DecodeException(stripped, e instanceof Error ? e.message : \"Invalid input\")\n    )\n  }\n}\n\n/** @internal */\nexport const stripCrlf = (str: string) => str.replace(/[\\n\\r]/g, \"\")\n\n/** @internal */\nfunction getBase64Code(charCode: number) {\n  if (charCode >= base64codes.length) {\n    throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`)\n  }\n\n  const code = base64codes[charCode]\n  if (code === 255) {\n    throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`)\n  }\n\n  return code\n}\n\n/** @internal */\nconst base64abc = [\n  \"A\",\n  \"B\",\n  \"C\",\n  \"D\",\n  \"E\",\n  \"F\",\n  \"G\",\n  \"H\",\n  \"I\",\n  \"J\",\n  \"K\",\n  \"L\",\n  \"M\",\n  \"N\",\n  \"O\",\n  \"P\",\n  \"Q\",\n  \"R\",\n  \"S\",\n  \"T\",\n  \"U\",\n  \"V\",\n  \"W\",\n  \"X\",\n  \"Y\",\n  \"Z\",\n  \"a\",\n  \"b\",\n  \"c\",\n  \"d\",\n  \"e\",\n  \"f\",\n  \"g\",\n  \"h\",\n  \"i\",\n  \"j\",\n  \"k\",\n  \"l\",\n  \"m\",\n  \"n\",\n  \"o\",\n  \"p\",\n  \"q\",\n  \"r\",\n  \"s\",\n  \"t\",\n  \"u\",\n  \"v\",\n  \"w\",\n  \"x\",\n  \"y\",\n  \"z\",\n  \"0\",\n  \"1\",\n  \"2\",\n  \"3\",\n  \"4\",\n  \"5\",\n  \"6\",\n  \"7\",\n  \"8\",\n  \"9\",\n  \"+\",\n  \"/\"\n]\n\n/** @internal */\nconst base64codes = [\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  62,\n  255,\n  255,\n  255,\n  63,\n  52,\n  53,\n  54,\n  55,\n  56,\n  57,\n  58,\n  59,\n  60,\n  61,\n  255,\n  255,\n  255,\n  0,\n  255,\n  255,\n  255,\n  0,\n  1,\n  2,\n  3,\n  4,\n  5,\n  6,\n  7,\n  8,\n  9,\n  10,\n  11,\n  12,\n  13,\n  14,\n  15,\n  16,\n  17,\n  18,\n  19,\n  20,\n  21,\n  22,\n  23,\n  24,\n  25,\n  255,\n  255,\n  255,\n  255,\n  255,\n  255,\n  26,\n  27,\n  28,\n  29,\n  30,\n  31,\n  32,\n  33,\n  34,\n  35,\n  36,\n  37,\n  38,\n  39,\n  40,\n  41,\n  42,\n  43,\n  44,\n  45,\n  46,\n  47,\n  48,\n  49,\n  50,\n  51\n]\n"
  },
  {
    "path": "packages/effect/src/internal/encoding/base64Url.ts",
    "content": "import * as Either from \"../../Either.js\"\nimport type * as Encoding from \"../../Encoding.js\"\nimport * as Base64 from \"./base64.js\"\nimport { DecodeException } from \"./common.js\"\n\n/** @internal */\nexport const encode = (data: Uint8Array) =>\n  Base64.encode(data).replace(/=/g, \"\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\")\n\n/** @internal */\nexport const decode = (str: string): Either.Either<Uint8Array, Encoding.DecodeException> => {\n  const stripped = Base64.stripCrlf(str)\n  const length = stripped.length\n  if (length % 4 === 1) {\n    return Either.left(\n      DecodeException(stripped, `Length should be a multiple of 4, but is ${length}`)\n    )\n  }\n\n  if (!/^[-_A-Z0-9]*?={0,2}$/i.test(stripped)) {\n    return Either.left(DecodeException(stripped, \"Invalid input\"))\n  }\n\n  // Some variants allow or require omitting the padding '=' signs\n  let sanitized = length % 4 === 2 ? `${stripped}==` : length % 4 === 3 ? `${stripped}=` : stripped\n  sanitized = sanitized.replace(/-/g, \"+\").replace(/_/g, \"/\")\n\n  return Base64.decode(sanitized)\n}\n"
  },
  {
    "path": "packages/effect/src/internal/encoding/common.ts",
    "content": "import type * as Encoding from \"../../Encoding.js\"\nimport { hasProperty, isString } from \"../../Predicate.js\"\nimport type { Mutable } from \"../../Types.js\"\n\n/** @internal */\nexport const DecodeExceptionTypeId: Encoding.DecodeExceptionTypeId = Symbol.for(\n  \"effect/Encoding/errors/Decode\"\n) as Encoding.DecodeExceptionTypeId\n\n/** @internal */\nexport const DecodeException = (input: string, message?: string): Encoding.DecodeException => {\n  const out: Mutable<Encoding.DecodeException> = {\n    _tag: \"DecodeException\",\n    [DecodeExceptionTypeId]: DecodeExceptionTypeId,\n    input\n  }\n  if (isString(message)) {\n    out.message = message\n  }\n  return out\n}\n\n/** @internal */\nexport const isDecodeException = (u: unknown): u is Encoding.DecodeException => hasProperty(u, DecodeExceptionTypeId)\n\n/** @internal */\nexport const EncodeExceptionTypeId: Encoding.EncodeExceptionTypeId = Symbol.for(\n  \"effect/Encoding/errors/Encode\"\n) as Encoding.EncodeExceptionTypeId\n\n/** @internal */\nexport const EncodeException = (input: string, message?: string): Encoding.EncodeException => {\n  const out: Mutable<Encoding.EncodeException> = {\n    _tag: \"EncodeException\",\n    [EncodeExceptionTypeId]: EncodeExceptionTypeId,\n    input\n  }\n  if (isString(message)) {\n    out.message = message\n  }\n  return out\n}\n\n/** @internal */\nexport const isEncodeException = (u: unknown): u is Encoding.EncodeException => hasProperty(u, EncodeExceptionTypeId)\n\n/** @interal */\nexport const encoder = new TextEncoder()\n\n/** @interal */\nexport const decoder = new TextDecoder()\n"
  },
  {
    "path": "packages/effect/src/internal/encoding/hex.ts",
    "content": "import * as Either from \"../../Either.js\"\nimport type * as Encoding from \"../../Encoding.js\"\nimport { DecodeException } from \"./common.js\"\n\n/** @internal */\nexport const encode = (bytes: Uint8Array) => {\n  let result = \"\"\n  for (let i = 0; i < bytes.length; ++i) {\n    result += bytesToHex[bytes[i]]\n  }\n\n  return result\n}\n\n/** @internal */\nexport const decode = (str: string): Either.Either<Uint8Array, Encoding.DecodeException> => {\n  const bytes = new TextEncoder().encode(str)\n  if (bytes.length % 2 !== 0) {\n    return Either.left(DecodeException(str, `Length must be a multiple of 2, but is ${bytes.length}`))\n  }\n\n  try {\n    const length = bytes.length / 2\n    const result = new Uint8Array(length)\n    for (let i = 0; i < length; i++) {\n      const a = fromHexChar(bytes[i * 2])\n      const b = fromHexChar(bytes[i * 2 + 1])\n      result[i] = (a << 4) | b\n    }\n\n    return Either.right(result)\n  } catch (e) {\n    return Either.left(DecodeException(str, e instanceof Error ? e.message : \"Invalid input\"))\n  }\n}\n\n/** @internal */\nconst bytesToHex = [\n  \"00\",\n  \"01\",\n  \"02\",\n  \"03\",\n  \"04\",\n  \"05\",\n  \"06\",\n  \"07\",\n  \"08\",\n  \"09\",\n  \"0a\",\n  \"0b\",\n  \"0c\",\n  \"0d\",\n  \"0e\",\n  \"0f\",\n  \"10\",\n  \"11\",\n  \"12\",\n  \"13\",\n  \"14\",\n  \"15\",\n  \"16\",\n  \"17\",\n  \"18\",\n  \"19\",\n  \"1a\",\n  \"1b\",\n  \"1c\",\n  \"1d\",\n  \"1e\",\n  \"1f\",\n  \"20\",\n  \"21\",\n  \"22\",\n  \"23\",\n  \"24\",\n  \"25\",\n  \"26\",\n  \"27\",\n  \"28\",\n  \"29\",\n  \"2a\",\n  \"2b\",\n  \"2c\",\n  \"2d\",\n  \"2e\",\n  \"2f\",\n  \"30\",\n  \"31\",\n  \"32\",\n  \"33\",\n  \"34\",\n  \"35\",\n  \"36\",\n  \"37\",\n  \"38\",\n  \"39\",\n  \"3a\",\n  \"3b\",\n  \"3c\",\n  \"3d\",\n  \"3e\",\n  \"3f\",\n  \"40\",\n  \"41\",\n  \"42\",\n  \"43\",\n  \"44\",\n  \"45\",\n  \"46\",\n  \"47\",\n  \"48\",\n  \"49\",\n  \"4a\",\n  \"4b\",\n  \"4c\",\n  \"4d\",\n  \"4e\",\n  \"4f\",\n  \"50\",\n  \"51\",\n  \"52\",\n  \"53\",\n  \"54\",\n  \"55\",\n  \"56\",\n  \"57\",\n  \"58\",\n  \"59\",\n  \"5a\",\n  \"5b\",\n  \"5c\",\n  \"5d\",\n  \"5e\",\n  \"5f\",\n  \"60\",\n  \"61\",\n  \"62\",\n  \"63\",\n  \"64\",\n  \"65\",\n  \"66\",\n  \"67\",\n  \"68\",\n  \"69\",\n  \"6a\",\n  \"6b\",\n  \"6c\",\n  \"6d\",\n  \"6e\",\n  \"6f\",\n  \"70\",\n  \"71\",\n  \"72\",\n  \"73\",\n  \"74\",\n  \"75\",\n  \"76\",\n  \"77\",\n  \"78\",\n  \"79\",\n  \"7a\",\n  \"7b\",\n  \"7c\",\n  \"7d\",\n  \"7e\",\n  \"7f\",\n  \"80\",\n  \"81\",\n  \"82\",\n  \"83\",\n  \"84\",\n  \"85\",\n  \"86\",\n  \"87\",\n  \"88\",\n  \"89\",\n  \"8a\",\n  \"8b\",\n  \"8c\",\n  \"8d\",\n  \"8e\",\n  \"8f\",\n  \"90\",\n  \"91\",\n  \"92\",\n  \"93\",\n  \"94\",\n  \"95\",\n  \"96\",\n  \"97\",\n  \"98\",\n  \"99\",\n  \"9a\",\n  \"9b\",\n  \"9c\",\n  \"9d\",\n  \"9e\",\n  \"9f\",\n  \"a0\",\n  \"a1\",\n  \"a2\",\n  \"a3\",\n  \"a4\",\n  \"a5\",\n  \"a6\",\n  \"a7\",\n  \"a8\",\n  \"a9\",\n  \"aa\",\n  \"ab\",\n  \"ac\",\n  \"ad\",\n  \"ae\",\n  \"af\",\n  \"b0\",\n  \"b1\",\n  \"b2\",\n  \"b3\",\n  \"b4\",\n  \"b5\",\n  \"b6\",\n  \"b7\",\n  \"b8\",\n  \"b9\",\n  \"ba\",\n  \"bb\",\n  \"bc\",\n  \"bd\",\n  \"be\",\n  \"bf\",\n  \"c0\",\n  \"c1\",\n  \"c2\",\n  \"c3\",\n  \"c4\",\n  \"c5\",\n  \"c6\",\n  \"c7\",\n  \"c8\",\n  \"c9\",\n  \"ca\",\n  \"cb\",\n  \"cc\",\n  \"cd\",\n  \"ce\",\n  \"cf\",\n  \"d0\",\n  \"d1\",\n  \"d2\",\n  \"d3\",\n  \"d4\",\n  \"d5\",\n  \"d6\",\n  \"d7\",\n  \"d8\",\n  \"d9\",\n  \"da\",\n  \"db\",\n  \"dc\",\n  \"dd\",\n  \"de\",\n  \"df\",\n  \"e0\",\n  \"e1\",\n  \"e2\",\n  \"e3\",\n  \"e4\",\n  \"e5\",\n  \"e6\",\n  \"e7\",\n  \"e8\",\n  \"e9\",\n  \"ea\",\n  \"eb\",\n  \"ec\",\n  \"ed\",\n  \"ee\",\n  \"ef\",\n  \"f0\",\n  \"f1\",\n  \"f2\",\n  \"f3\",\n  \"f4\",\n  \"f5\",\n  \"f6\",\n  \"f7\",\n  \"f8\",\n  \"f9\",\n  \"fa\",\n  \"fb\",\n  \"fc\",\n  \"fd\",\n  \"fe\",\n  \"ff\"\n]\n\n/** @internal */\nconst fromHexChar = (byte: number) => {\n  // '0' <= byte && byte <= '9'\n  if (48 <= byte && byte <= 57) {\n    return byte - 48\n  }\n\n  // 'a' <= byte && byte <= 'f'\n  if (97 <= byte && byte <= 102) {\n    return byte - 97 + 10\n  }\n\n  // 'A' <= byte && byte <= 'F'\n  if (65 <= byte && byte <= 70) {\n    return byte - 65 + 10\n  }\n\n  throw new TypeError(\"Invalid input\")\n}\n"
  },
  {
    "path": "packages/effect/src/internal/errors.ts",
    "content": "/**\n * @since 2.0.0\n */\n\n/** @internal */\nexport const getBugErrorMessage = (message: string) =>\n  `BUG: ${message} - please report an issue at https://github.com/Effect-TS/effect/issues`\n"
  },
  {
    "path": "packages/effect/src/internal/executionPlan.ts",
    "content": "import type { Effect } from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport type * as Api from \"../ExecutionPlan.js\"\nimport { dual } from \"../Function.js\"\nimport * as Predicate from \"../Predicate.js\"\nimport * as core from \"./core.js\"\nimport * as layer from \"./layer.js\"\nimport * as InternalSchedule from \"./schedule.js\"\n\n/** @internal */\nexport const TypeId: Api.TypeId = Symbol.for(\"effect/ExecutionPlan\") as Api.TypeId\n\n/** @internal */\nexport const isExecutionPlan = (u: unknown): u is Api.ExecutionPlan<any> => Predicate.hasProperty(u, TypeId)\n\n/** @internal */\nexport const withExecutionPlan: {\n  <Input, Provides, PlanE, PlanR>(\n    plan: Api.ExecutionPlan<{\n      provides: Provides\n      input: Input\n      error: PlanE\n      requirements: PlanR\n    }>\n  ): <A, E extends Input, R>(effect: Effect<A, E, R>) => Effect<\n    A,\n    E | PlanE,\n    Exclude<R, Provides> | PlanR\n  >\n  <A, E extends Input, R, Provides, Input, PlanE, PlanR>(\n    effect: Effect<A, E, R>,\n    plan: Api.ExecutionPlan<{\n      provides: Provides\n      input: Input\n      error: PlanE\n      requirements: PlanR\n    }>\n  ): Effect<\n    A,\n    E | PlanE,\n    Exclude<R, Provides> | PlanR\n  >\n} = dual(2, <A, E extends Input, R, Provides, Input, PlanE, PlanR>(\n  effect: Effect<A, E, R>,\n  plan: Api.ExecutionPlan<{\n    provides: Provides\n    input: Input\n    error: PlanE\n    requirements: PlanR\n  }>\n) =>\n  core.suspend(() => {\n    let i = 0\n    let result: Either.Either<A, any> | undefined\n    return core.flatMap(\n      core.whileLoop({\n        while: () => i < plan.steps.length && (result === undefined || Either.isLeft(result)),\n        body: () => {\n          const step = plan.steps[i]\n          let nextEffect: Effect<A, any, any> = layer.effect_provide(effect, step.provide as any)\n          if (result) {\n            let attempted = false\n            const wrapped = nextEffect\n            // ensure the schedule is applied at least once\n            nextEffect = core.suspend(() => {\n              if (attempted) return wrapped\n              attempted = true\n              return result!\n            })\n            nextEffect = InternalSchedule.scheduleDefectRefail(\n              InternalSchedule.retry_Effect(nextEffect, scheduleFromStep(step, false)!)\n            )\n          } else {\n            const schedule = scheduleFromStep(step, true)\n            nextEffect = schedule\n              ? InternalSchedule.scheduleDefectRefail(InternalSchedule.retry_Effect(nextEffect, schedule))\n              : nextEffect\n          }\n          return core.either(nextEffect)\n        },\n        step: (either) => {\n          result = either\n          i++\n        }\n      }),\n      () => result!\n    )\n  }))\n\n/** @internal */\nexport const scheduleFromStep = <Provides, In, PlanE, PlanR>(\n  step: Api.ExecutionPlan<{\n    provides: Provides\n    input: In\n    error: PlanE\n    requirements: PlanR\n  }>[\"steps\"][number],\n  first: boolean\n) => {\n  if (!first) {\n    return InternalSchedule.fromRetryOptions({\n      schedule: step.schedule ? step.schedule : step.attempts ? undefined : InternalSchedule.once,\n      times: step.attempts,\n      while: step.while\n    })\n  } else if (step.attempts === 1 || !(step.schedule || step.attempts)) {\n    return undefined\n  }\n  return InternalSchedule.fromRetryOptions({\n    schedule: step.schedule,\n    while: step.while,\n    times: step.attempts ? step.attempts - 1 : undefined\n  })\n}\n"
  },
  {
    "path": "packages/effect/src/internal/executionStrategy.ts",
    "content": "import type * as ExecutionStrategy from \"../ExecutionStrategy.js\"\nimport { dual } from \"../Function.js\"\nimport type { LazyArg } from \"../Function.js\"\n\n/** @internal */\nexport const OP_SEQUENTIAL = \"Sequential\" as const\n\n/** @internal */\nexport type OP_SEQUENTIAL = typeof OP_SEQUENTIAL\n\n/** @internal */\nexport const OP_PARALLEL = \"Parallel\" as const\n\n/** @internal */\nexport type OP_PARALLEL = typeof OP_PARALLEL\n\n/** @internal */\nexport const OP_PARALLEL_N = \"ParallelN\" as const\n\n/** @internal */\nexport type OP_PARALLEL_N = typeof OP_PARALLEL_N\n\n/** @internal */\nexport const sequential: ExecutionStrategy.ExecutionStrategy = { _tag: OP_SEQUENTIAL }\n\n/** @internal */\nexport const parallel: ExecutionStrategy.ExecutionStrategy = { _tag: OP_PARALLEL }\n\n/** @internal */\nexport const parallelN = (parallelism: number): ExecutionStrategy.ExecutionStrategy => ({\n  _tag: OP_PARALLEL_N,\n  parallelism\n})\n\n/** @internal */\nexport const isSequential = (self: ExecutionStrategy.ExecutionStrategy): self is ExecutionStrategy.Sequential =>\n  self._tag === OP_SEQUENTIAL\n\n/** @internal */\nexport const isParallel = (self: ExecutionStrategy.ExecutionStrategy): self is ExecutionStrategy.Parallel =>\n  self._tag === OP_PARALLEL\n\n/** @internal */\nexport const isParallelN = (self: ExecutionStrategy.ExecutionStrategy): self is ExecutionStrategy.ParallelN =>\n  self._tag === OP_PARALLEL_N\n\n/** @internal */\nexport const match = dual<\n  <A>(options: {\n    readonly onSequential: LazyArg<A>\n    readonly onParallel: LazyArg<A>\n    readonly onParallelN: (n: number) => A\n  }) => (self: ExecutionStrategy.ExecutionStrategy) => A,\n  <A>(\n    self: ExecutionStrategy.ExecutionStrategy,\n    options: {\n      readonly onSequential: LazyArg<A>\n      readonly onParallel: LazyArg<A>\n      readonly onParallelN: (n: number) => A\n    }\n  ) => A\n>(2, (self, options) => {\n  switch (self._tag) {\n    case OP_SEQUENTIAL: {\n      return options.onSequential()\n    }\n    case OP_PARALLEL: {\n      return options.onParallel()\n    }\n    case OP_PARALLEL_N: {\n      return options.onParallelN(self.parallelism)\n    }\n  }\n})\n"
  },
  {
    "path": "packages/effect/src/internal/fiber.ts",
    "content": "import type * as Cause from \"../Cause.js\"\nimport * as Clock from \"../Clock.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport * as Exit from \"../Exit.js\"\nimport type * as Fiber from \"../Fiber.js\"\nimport * as FiberId from \"../FiberId.js\"\nimport * as FiberStatus from \"../FiberStatus.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport * as HashSet from \"../HashSet.js\"\nimport * as number from \"../Number.js\"\nimport * as Option from \"../Option.js\"\nimport * as order from \"../Order.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport * as core from \"./core.js\"\nimport * as effectable from \"./effectable.js\"\nimport * as fiberScope from \"./fiberScope.js\"\nimport * as runtimeFlags from \"./runtimeFlags.js\"\n\n/** @internal */\nconst FiberSymbolKey = \"effect/Fiber\"\n\n/** @internal */\nexport const FiberTypeId: Fiber.FiberTypeId = Symbol.for(\n  FiberSymbolKey\n) as Fiber.FiberTypeId\n\n/** @internal */\nexport const fiberVariance = {\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _A: (_: never) => _\n}\n\n/** @internal */\nconst fiberProto = {\n  [FiberTypeId]: fiberVariance,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nconst RuntimeFiberSymbolKey = \"effect/Fiber\"\n\n/** @internal */\nexport const RuntimeFiberTypeId: Fiber.RuntimeFiberTypeId = Symbol.for(\n  RuntimeFiberSymbolKey\n) as Fiber.RuntimeFiberTypeId\n\n/** @internal */\nexport const Order: order.Order<Fiber.RuntimeFiber<unknown, unknown>> = pipe(\n  order.tuple(number.Order, number.Order),\n  order.mapInput((fiber: Fiber.RuntimeFiber<unknown, unknown>) =>\n    [\n      (fiber.id() as FiberId.Runtime).startTimeMillis,\n      (fiber.id() as FiberId.Runtime).id\n    ] as const\n  )\n)\n\n/** @internal */\nexport const isFiber = (u: unknown): u is Fiber.Fiber<unknown, unknown> => hasProperty(u, FiberTypeId)\n\n/** @internal */\nexport const isRuntimeFiber = <A, E>(self: Fiber.Fiber<A, E>): self is Fiber.RuntimeFiber<A, E> =>\n  RuntimeFiberTypeId in self\n\n/** @internal */\nexport const _await = <A, E>(self: Fiber.Fiber<A, E>): Effect.Effect<Exit.Exit<A, E>> => self.await\n\n/** @internal */\nexport const children = <A, E>(\n  self: Fiber.Fiber<A, E>\n): Effect.Effect<Array<Fiber.RuntimeFiber<any, any>>> => self.children\n\n/** @internal */\nexport const done = <A, E>(exit: Exit.Exit<A, E>): Fiber.Fiber<A, E> => {\n  const _fiber = {\n    ...effectable.CommitPrototype,\n    commit() {\n      return join(this)\n    },\n    ...fiberProto,\n    id: () => FiberId.none,\n    await: core.succeed(exit),\n    children: core.succeed([]),\n    inheritAll: core.void,\n    poll: core.succeed(Option.some(exit)),\n    interruptAsFork: () => core.void\n  }\n\n  return _fiber\n}\n\n/** @internal */\nexport const dump = <A, E>(self: Fiber.RuntimeFiber<A, E>): Effect.Effect<Fiber.Fiber.Dump> =>\n  core.map(self.status, (status) => ({ id: self.id(), status }))\n\n/** @internal */\nexport const dumpAll = (\n  fibers: Iterable<Fiber.RuntimeFiber<unknown, unknown>>\n): Effect.Effect<Array<Fiber.Fiber.Dump>> => core.forEachSequential(fibers, dump)\n\n/** @internal */\nexport const fail = <E>(error: E): Fiber.Fiber<never, E> => done(Exit.fail(error))\n\n/** @internal */\nexport const failCause = <E>(cause: Cause.Cause<E>): Fiber.Fiber<never, E> => done(Exit.failCause(cause))\n\n/** @internal */\nexport const fromEffect = <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<Fiber.Fiber<A, E>> =>\n  core.map(core.exit(effect), done)\n\n/** @internal */\nexport const id = <A, E>(self: Fiber.Fiber<A, E>): FiberId.FiberId => self.id()\n\n/** @internal */\nexport const inheritAll = <A, E>(self: Fiber.Fiber<A, E>): Effect.Effect<void> => self.inheritAll\n\n/** @internal */\nexport const interrupted = (fiberId: FiberId.FiberId): Fiber.Fiber<never> => done(Exit.interrupt(fiberId))\n\n/** @internal */\nexport const interruptAll = (fibers: Iterable<Fiber.Fiber<any, any>>): Effect.Effect<void> =>\n  core.flatMap(core.fiberId, (fiberId) => pipe(fibers, interruptAllAs(fiberId)))\n\n/** @internal */\nexport const interruptAllAs = dual<\n  (fiberId: FiberId.FiberId) => (fibers: Iterable<Fiber.Fiber<any, any>>) => Effect.Effect<void>,\n  (fibers: Iterable<Fiber.Fiber<any, any>>, fiberId: FiberId.FiberId) => Effect.Effect<void>\n>(\n  2,\n  core.fnUntraced(function*(fibers, fiberId) {\n    for (const fiber of fibers) {\n      if (isRuntimeFiber(fiber)) {\n        fiber.unsafeInterruptAsFork(fiberId)\n        continue\n      }\n      yield* fiber.interruptAsFork(fiberId)\n    }\n    for (const fiber of fibers) {\n      if (isRuntimeFiber(fiber) && fiber.unsafePoll()) {\n        continue\n      }\n      yield* fiber.await\n    }\n  })\n)\n\n/** @internal */\nexport const interruptAsFork = dual<\n  (fiberId: FiberId.FiberId) => <A, E>(self: Fiber.Fiber<A, E>) => Effect.Effect<void>,\n  <A, E>(self: Fiber.Fiber<A, E>, fiberId: FiberId.FiberId) => Effect.Effect<void>\n>(2, (self, fiberId) => self.interruptAsFork(fiberId))\n\n/** @internal */\nexport const join = <A, E>(self: Fiber.Fiber<A, E>): Effect.Effect<A, E> =>\n  core.zipLeft(core.flatten(self.await), self.inheritAll)\n\n/** @internal */\nexport const map = dual<\n  <A, B>(f: (a: A) => B) => <E>(self: Fiber.Fiber<A, E>) => Fiber.Fiber<B, E>,\n  <A, E, B>(self: Fiber.Fiber<A, E>, f: (a: A) => B) => Fiber.Fiber<B, E>\n>(2, (self, f) => mapEffect(self, (a) => core.sync(() => f(a))))\n\n/** @internal */\nexport const mapEffect = dual<\n  <A, A2, E2>(f: (a: A) => Effect.Effect<A2, E2>) => <E>(self: Fiber.Fiber<A, E>) => Fiber.Fiber<A2, E | E2>,\n  <A, E, A2, E2>(self: Fiber.Fiber<A, E>, f: (a: A) => Effect.Effect<A2, E2>) => Fiber.Fiber<A2, E | E2>\n>(2, (self, f) => {\n  const _fiber = {\n    ...effectable.CommitPrototype,\n    commit() {\n      return join(this)\n    },\n    ...fiberProto,\n    id: () => self.id(),\n    await: core.flatMap(self.await, Exit.forEachEffect(f)),\n    children: self.children,\n    inheritAll: self.inheritAll,\n    poll: core.flatMap(self.poll, (result) => {\n      switch (result._tag) {\n        case \"None\":\n          return core.succeed(Option.none())\n        case \"Some\":\n          return pipe(\n            Exit.forEachEffect(result.value, f),\n            core.map(Option.some)\n          )\n      }\n    }),\n    interruptAsFork: (id: FiberId.FiberId) => self.interruptAsFork(id)\n  }\n  return _fiber\n})\n\n/** @internal */\nexport const mapFiber = dual<\n  <E, E2, A, B>(\n    f: (a: A) => Fiber.Fiber<B, E2>\n  ) => (self: Fiber.Fiber<A, E>) => Effect.Effect<Fiber.Fiber<B, E | E2>>,\n  <A, E, E2, B>(\n    self: Fiber.Fiber<A, E>,\n    f: (a: A) => Fiber.Fiber<B, E2>\n  ) => Effect.Effect<Fiber.Fiber<B, E | E2>>\n>(2, <A, E, E2, B>(\n  self: Fiber.Fiber<A, E>,\n  f: (a: A) => Fiber.Fiber<B, E2>\n) =>\n  core.map(\n    self.await,\n    Exit.match({\n      onFailure: (cause): Fiber.Fiber<B, E | E2> => failCause(cause),\n      onSuccess: (a) => f(a)\n    })\n  ))\n\n/** @internal */\nexport const match = dual<\n  <A, E, Z>(\n    options: {\n      readonly onFiber: (fiber: Fiber.Fiber<A, E>) => Z\n      readonly onRuntimeFiber: (fiber: Fiber.RuntimeFiber<A, E>) => Z\n    }\n  ) => (self: Fiber.Fiber<A, E>) => Z,\n  <A, E, Z>(\n    self: Fiber.Fiber<A, E>,\n    options: {\n      readonly onFiber: (fiber: Fiber.Fiber<A, E>) => Z\n      readonly onRuntimeFiber: (fiber: Fiber.RuntimeFiber<A, E>) => Z\n    }\n  ) => Z\n>(2, (self, { onFiber, onRuntimeFiber }) => {\n  if (isRuntimeFiber(self)) {\n    return onRuntimeFiber(self)\n  }\n  return onFiber(self)\n})\n\n/** @internal */\nconst _never = {\n  ...effectable.CommitPrototype,\n  commit() {\n    return join(this)\n  },\n  ...fiberProto,\n  id: () => FiberId.none,\n  await: core.never,\n  children: core.succeed([]),\n  inheritAll: core.never,\n  poll: core.succeed(Option.none()),\n  interruptAsFork: () => core.never\n}\n\n/** @internal */\nexport const never: Fiber.Fiber<never> = _never\n\n/** @internal */\nexport const orElse = dual<\n  <A2, E2>(that: Fiber.Fiber<A2, E2>) => <A, E>(self: Fiber.Fiber<A, E>) => Fiber.Fiber<A | A2, E | E2>,\n  <A, E, A2, E2>(self: Fiber.Fiber<A, E>, that: Fiber.Fiber<A2, E2>) => Fiber.Fiber<A | A2, E | E2>\n>(2, (self, that) => ({\n  ...effectable.CommitPrototype,\n  commit() {\n    return join(this)\n  },\n  ...fiberProto,\n  id: () => FiberId.getOrElse(self.id(), that.id()),\n  await: core.zipWith(\n    self.await,\n    that.await,\n    (exit1, exit2) => (Exit.isSuccess(exit1) ? exit1 : exit2)\n  ),\n  children: self.children,\n  inheritAll: core.zipRight(that.inheritAll, self.inheritAll),\n  poll: core.zipWith(\n    self.poll,\n    that.poll,\n    (option1, option2) => {\n      switch (option1._tag) {\n        case \"None\": {\n          return Option.none()\n        }\n        case \"Some\": {\n          return Exit.isSuccess(option1.value) ? option1 : option2\n        }\n      }\n    }\n  ),\n  interruptAsFork: (id) =>\n    pipe(\n      core.interruptAsFiber(self, id),\n      core.zipRight(pipe(that, core.interruptAsFiber(id))),\n      core.asVoid\n    )\n}))\n\n/** @internal */\nexport const orElseEither = dual<\n  <A2, E2>(that: Fiber.Fiber<A2, E2>) => <A, E>(self: Fiber.Fiber<A, E>) => Fiber.Fiber<Either.Either<A2, A>, E | E2>,\n  <A, E, A2, E2>(self: Fiber.Fiber<A, E>, that: Fiber.Fiber<A2, E2>) => Fiber.Fiber<Either.Either<A2, A>, E | E2>\n>(2, (self, that) => orElse(map(self, Either.left), map(that, Either.right)))\n\n/** @internal */\nexport const poll = <A, E>(self: Fiber.Fiber<A, E>): Effect.Effect<Option.Option<Exit.Exit<A, E>>> => self.poll\n\n// forked from https://github.com/sindresorhus/parse-ms/blob/4da2ffbdba02c6e288c08236695bdece0adca173/index.js\n// MIT License\n// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)\n/** @internal */\nconst parseMs = (milliseconds: number) => {\n  const roundTowardsZero = milliseconds > 0 ? Math.floor : Math.ceil\n  return {\n    days: roundTowardsZero(milliseconds / 86400000),\n    hours: roundTowardsZero(milliseconds / 3600000) % 24,\n    minutes: roundTowardsZero(milliseconds / 60000) % 60,\n    seconds: roundTowardsZero(milliseconds / 1000) % 60,\n    milliseconds: roundTowardsZero(milliseconds) % 1000,\n    microseconds: roundTowardsZero(milliseconds * 1000) % 1000,\n    nanoseconds: roundTowardsZero(milliseconds * 1e6) % 1000\n  }\n}\n\n/** @internal */\nconst renderStatus = (status: FiberStatus.FiberStatus): string => {\n  if (FiberStatus.isDone(status)) {\n    return \"Done\"\n  }\n  if (FiberStatus.isRunning(status)) {\n    return \"Running\"\n  }\n\n  const isInterruptible = runtimeFlags.interruptible(status.runtimeFlags) ?\n    \"interruptible\" :\n    \"uninterruptible\"\n  return `Suspended(${isInterruptible})`\n}\n\n/** @internal */\nexport const pretty = <A, E>(self: Fiber.RuntimeFiber<A, E>): Effect.Effect<string> =>\n  core.flatMap(Clock.currentTimeMillis, (now) =>\n    core.map(dump(self), (dump) => {\n      const time = now - dump.id.startTimeMillis\n      const { days, hours, milliseconds, minutes, seconds } = parseMs(time)\n      const lifeMsg = (days === 0 ? \"\" : `${days}d`) +\n        (days === 0 && hours === 0 ? \"\" : `${hours}h`) +\n        (days === 0 && hours === 0 && minutes === 0 ? \"\" : `${minutes}m`) +\n        (days === 0 && hours === 0 && minutes === 0 && seconds === 0 ? \"\" : `${seconds}s`) +\n        `${milliseconds}ms`\n      const waitMsg = FiberStatus.isSuspended(dump.status) ?\n        (() => {\n          const ids = FiberId.ids(dump.status.blockingOn)\n          return HashSet.size(ids) > 0\n            ? `waiting on ` + Array.from(ids).map((id) => `${id}`).join(\", \")\n            : \"\"\n        })() :\n        \"\"\n      const statusMsg = renderStatus(dump.status)\n      return `[Fiber](#${dump.id.id}) (${lifeMsg}) ${waitMsg}\\n   Status: ${statusMsg}`\n    }))\n\n/** @internal */\nexport const unsafeRoots = (): Array<Fiber.RuntimeFiber<any, any>> => Array.from(fiberScope.globalScope.roots)\n\n/** @internal */\nexport const roots: Effect.Effect<Array<Fiber.RuntimeFiber<any, any>>> = core.sync(unsafeRoots)\n\n/** @internal */\nexport const status = <A, E>(self: Fiber.RuntimeFiber<A, E>): Effect.Effect<FiberStatus.FiberStatus> => self.status\n\n/** @internal */\nexport const succeed = <A>(value: A): Fiber.Fiber<A> => done(Exit.succeed(value))\n\nconst void_: Fiber.Fiber<void> = succeed(void 0)\nexport {\n  /** @internal */\n  void_ as void\n}\n\n/** @internal */\nexport const currentFiberURI = \"effect/FiberCurrent\"\n\n/** @internal */\nexport const getCurrentFiber = (): Option.Option<Fiber.RuntimeFiber<any, any>> =>\n  Option.fromNullable((globalThis as any)[currentFiberURI])\n"
  },
  {
    "path": "packages/effect/src/internal/fiberId.ts",
    "content": "import * as Equal from \"../Equal.js\"\nimport type * as FiberId from \"../FiberId.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport * as Hash from \"../Hash.js\"\nimport * as HashSet from \"../HashSet.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"../Inspectable.js\"\nimport * as MutableRef from \"../MutableRef.js\"\nimport * as Option from \"../Option.js\"\nimport { hasProperty } from \"../Predicate.js\"\n\n/** @internal */\nconst FiberIdSymbolKey = \"effect/FiberId\"\n\n/** @internal */\nexport const FiberIdTypeId: FiberId.FiberIdTypeId = Symbol.for(\n  FiberIdSymbolKey\n) as FiberId.FiberIdTypeId\n\n/** @internal */\nconst OP_NONE = \"None\" as const\n\n/** @internal */\nexport type OP_NONE = typeof OP_NONE\n\n/** @internal */\nconst OP_RUNTIME = \"Runtime\" as const\n\n/** @internal */\nexport type OP_RUNTIME = typeof OP_RUNTIME\n\n/** @internal */\nconst OP_COMPOSITE = \"Composite\" as const\n\n/** @internal */\nexport type OP_COMPOSITE = typeof OP_COMPOSITE\n\nconst emptyHash = Hash.string(`${FiberIdSymbolKey}-${OP_NONE}`)\n\n/** @internal */\nclass None implements FiberId.None {\n  readonly [FiberIdTypeId]: FiberId.FiberIdTypeId = FiberIdTypeId\n  readonly _tag = OP_NONE\n  readonly id = -1\n  readonly startTimeMillis = -1;\n  [Hash.symbol](): number {\n    return emptyHash\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isFiberId(that) && that._tag === OP_NONE\n  }\n  toString() {\n    return format(this.toJSON())\n  }\n  toJSON() {\n    return {\n      _id: \"FiberId\",\n      _tag: this._tag\n    }\n  }\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  }\n}\n\n/** @internal */\nclass Runtime implements FiberId.Runtime {\n  readonly [FiberIdTypeId]: FiberId.FiberIdTypeId = FiberIdTypeId\n  readonly _tag = OP_RUNTIME\n  constructor(\n    readonly id: number,\n    readonly startTimeMillis: number\n  ) {}\n  [Hash.symbol](): number {\n    return Hash.cached(this, Hash.string(`${FiberIdSymbolKey}-${this._tag}-${this.id}-${this.startTimeMillis}`))\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isFiberId(that) &&\n      that._tag === OP_RUNTIME &&\n      this.id === that.id &&\n      this.startTimeMillis === that.startTimeMillis\n  }\n  toString() {\n    return format(this.toJSON())\n  }\n  toJSON() {\n    return {\n      _id: \"FiberId\",\n      _tag: this._tag,\n      id: this.id,\n      startTimeMillis: this.startTimeMillis\n    }\n  }\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  }\n}\n\n/** @internal */\nclass Composite implements FiberId.Composite {\n  readonly [FiberIdTypeId]: FiberId.FiberIdTypeId = FiberIdTypeId\n  readonly _tag = OP_COMPOSITE\n  constructor(\n    readonly left: FiberId.FiberId,\n    readonly right: FiberId.FiberId\n  ) {\n  }\n  _hash: number | undefined;\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.string(`${FiberIdSymbolKey}-${this._tag}`),\n      Hash.combine(Hash.hash(this.left)),\n      Hash.combine(Hash.hash(this.right)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isFiberId(that) &&\n      that._tag === OP_COMPOSITE &&\n      Equal.equals(this.left, that.left) &&\n      Equal.equals(this.right, that.right)\n  }\n  toString() {\n    return format(this.toJSON())\n  }\n  toJSON() {\n    return {\n      _id: \"FiberId\",\n      _tag: this._tag,\n      left: toJSON(this.left),\n      right: toJSON(this.right)\n    }\n  }\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  }\n}\n\n/** @internal */\nexport const none: FiberId.None = new None()\n\n/** @internal */\nexport const runtime = (id: number, startTimeMillis: number): FiberId.Runtime => {\n  return new Runtime(id, startTimeMillis)\n}\n\n/** @internal */\nexport const composite = (left: FiberId.FiberId, right: FiberId.FiberId): FiberId.Composite => {\n  return new Composite(left, right)\n}\n\n/** @internal */\nexport const isFiberId = (self: unknown): self is FiberId.FiberId => hasProperty(self, FiberIdTypeId)\n\n/** @internal */\nexport const isNone = (self: FiberId.FiberId): self is FiberId.None => {\n  return self._tag === OP_NONE || pipe(toSet(self), HashSet.every((id) => isNone(id)))\n}\n\n/** @internal */\nexport const isRuntime = (self: FiberId.FiberId): self is FiberId.Runtime => {\n  return self._tag === OP_RUNTIME\n}\n\n/** @internal */\nexport const isComposite = (self: FiberId.FiberId): self is FiberId.Composite => {\n  return self._tag === OP_COMPOSITE\n}\n\n/** @internal */\nexport const combine = dual<\n  (that: FiberId.FiberId) => (self: FiberId.FiberId) => FiberId.FiberId,\n  (self: FiberId.FiberId, that: FiberId.FiberId) => FiberId.FiberId\n>(2, (self, that) => {\n  if (self._tag === OP_NONE) {\n    return that\n  }\n  if (that._tag === OP_NONE) {\n    return self\n  }\n  return new Composite(self, that)\n})\n\n/** @internal */\nexport const combineAll = (fiberIds: HashSet.HashSet<FiberId.FiberId>): FiberId.FiberId => {\n  return pipe(fiberIds, HashSet.reduce(none as FiberId.FiberId, (a, b) => combine(b)(a)))\n}\n\n/** @internal */\nexport const getOrElse = dual<\n  (that: FiberId.FiberId) => (self: FiberId.FiberId) => FiberId.FiberId,\n  (self: FiberId.FiberId, that: FiberId.FiberId) => FiberId.FiberId\n>(2, (self, that) => isNone(self) ? that : self)\n\n/** @internal */\nexport const ids = (self: FiberId.FiberId): HashSet.HashSet<number> => {\n  switch (self._tag) {\n    case OP_NONE: {\n      return HashSet.empty()\n    }\n    case OP_RUNTIME: {\n      return HashSet.make(self.id)\n    }\n    case OP_COMPOSITE: {\n      return pipe(ids(self.left), HashSet.union(ids(self.right)))\n    }\n  }\n}\n\nconst _fiberCounter = globalValue(\n  Symbol.for(\"effect/Fiber/Id/_fiberCounter\"),\n  () => MutableRef.make(0)\n)\n\n/** @internal */\nexport const make = (id: number, startTimeSeconds: number): FiberId.FiberId => {\n  return new Runtime(id, startTimeSeconds)\n}\n\n/** @internal */\nexport const threadName = (self: FiberId.FiberId): string => {\n  const identifiers = Array.from(ids(self)).map((n) => `#${n}`).join(\",\")\n  return identifiers\n}\n\n/** @internal */\nexport const toOption = (self: FiberId.FiberId): Option.Option<FiberId.FiberId> => {\n  const fiberIds = toSet(self)\n  if (HashSet.size(fiberIds) === 0) {\n    return Option.none()\n  }\n  let first = true\n  let acc: FiberId.FiberId\n  for (const fiberId of fiberIds) {\n    if (first) {\n      acc = fiberId\n      first = false\n    } else {\n      // @ts-expect-error\n      acc = pipe(acc, combine(fiberId))\n    }\n  }\n  // @ts-expect-error\n  return Option.some(acc)\n}\n\n/** @internal */\nexport const toSet = (self: FiberId.FiberId): HashSet.HashSet<FiberId.Runtime> => {\n  switch (self._tag) {\n    case OP_NONE: {\n      return HashSet.empty()\n    }\n    case OP_RUNTIME: {\n      return HashSet.make(self)\n    }\n    case OP_COMPOSITE: {\n      return pipe(toSet(self.left), HashSet.union(toSet(self.right)))\n    }\n  }\n}\n\n/** @internal */\nexport const unsafeMake = (): FiberId.Runtime => {\n  const id = MutableRef.get(_fiberCounter)\n  pipe(_fiberCounter, MutableRef.set(id + 1))\n  return new Runtime(id, Date.now())\n}\n"
  },
  {
    "path": "packages/effect/src/internal/fiberMessage.ts",
    "content": "import type * as Cause from \"../Cause.js\"\nimport type * as Effect from \"../Effect.js\"\nimport type * as FiberStatus from \"../FiberStatus.js\"\nimport type * as FiberRuntime from \"./fiberRuntime.js\"\n\n/** @internal */\nexport type FiberMessage = InterruptSignal | Stateful | Resume | YieldNow\n\n/** @internal */\nexport const OP_INTERRUPT_SIGNAL = \"InterruptSignal\" as const\n\n/** @internal */\nexport type OP_INTERRUPT_SIGNAL = typeof OP_INTERRUPT_SIGNAL\n\n/** @internal */\nexport const OP_STATEFUL = \"Stateful\" as const\n\n/** @internal */\nexport type OP_STATEFUL = typeof OP_STATEFUL\n\n/** @internal */\nexport const OP_RESUME = \"Resume\" as const\n\n/** @internal */\nexport type OP_RESUME = typeof OP_RESUME\n\n/** @internal */\nexport const OP_YIELD_NOW = \"YieldNow\" as const\n\n/** @internal */\nexport type OP_YIELD_NOW = typeof OP_YIELD_NOW\n\n/** @internal */\nexport interface InterruptSignal {\n  readonly _tag: OP_INTERRUPT_SIGNAL\n  readonly cause: Cause.Cause<never>\n}\n\n/** @internal */\nexport interface Stateful {\n  readonly _tag: OP_STATEFUL\n  onFiber(fiber: FiberRuntime.FiberRuntime<any, any>, status: FiberStatus.FiberStatus): void\n}\n\n/** @internal */\nexport interface Resume {\n  readonly _tag: OP_RESUME\n  readonly effect: Effect.Effect<any, any, any>\n}\n\n/** @internal */\nexport interface YieldNow {\n  readonly _tag: OP_YIELD_NOW\n}\n\n/** @internal */\nexport const interruptSignal = (cause: Cause.Cause<never>): FiberMessage => ({\n  _tag: OP_INTERRUPT_SIGNAL,\n  cause\n})\n\n/** @internal */\nexport const stateful = (\n  onFiber: (\n    fiber: FiberRuntime.FiberRuntime<any, any>,\n    status: FiberStatus.FiberStatus\n  ) => void\n): FiberMessage => ({\n  _tag: OP_STATEFUL,\n  onFiber\n})\n\n/** @internal */\nexport const resume = (effect: Effect.Effect<any, any, any>): FiberMessage => ({\n  _tag: OP_RESUME,\n  effect\n})\n\n/** @internal */\nexport const yieldNow = (): FiberMessage => ({\n  _tag: OP_YIELD_NOW\n})\n"
  },
  {
    "path": "packages/effect/src/internal/fiberRefs/patch.ts",
    "content": "import * as Arr from \"../../Array.js\"\nimport { equals } from \"../../Equal.js\"\nimport type * as FiberId from \"../../FiberId.js\"\nimport type * as FiberRefs from \"../../FiberRefs.js\"\nimport type * as FiberRefsPatch from \"../../FiberRefsPatch.js\"\nimport { dual } from \"../../Function.js\"\nimport * as fiberRefs_ from \"../fiberRefs.js\"\n\n/** @internal */\nexport const OP_EMPTY = \"Empty\" as const\n\n/** @internal */\nexport type OP_EMPTY = typeof OP_EMPTY\n\n/** @internal */\nexport const OP_ADD = \"Add\" as const\n\n/** @internal */\nexport type OP_ADD = typeof OP_ADD\n\n/** @internal */\nexport const OP_REMOVE = \"Remove\" as const\n\n/** @internal */\nexport type OP_REMOVE = typeof OP_REMOVE\n\n/** @internal */\nexport const OP_UPDATE = \"Update\" as const\n\n/** @internal */\nexport type OP_UPDATE = typeof OP_UPDATE\n\n/** @internal */\nexport const OP_AND_THEN = \"AndThen\" as const\n\n/** @internal */\nexport type OP_AND_THEN = typeof OP_AND_THEN\n\n/** @internal */\nexport const empty: FiberRefsPatch.FiberRefsPatch = ({\n  _tag: OP_EMPTY\n}) as FiberRefsPatch.FiberRefsPatch\n\n/** @internal */\nexport const diff = (\n  oldValue: FiberRefs.FiberRefs,\n  newValue: FiberRefs.FiberRefs\n): FiberRefsPatch.FiberRefsPatch => {\n  const missingLocals = new Map(oldValue.locals)\n  let patch = empty\n  for (const [fiberRef, pairs] of newValue.locals.entries()) {\n    const newValue = Arr.headNonEmpty(pairs)[1]\n    const old = missingLocals.get(fiberRef)\n    if (old !== undefined) {\n      const oldValue = Arr.headNonEmpty(old)[1]\n      if (!equals(oldValue, newValue)) {\n        patch = combine({\n          _tag: OP_UPDATE,\n          fiberRef,\n          patch: fiberRef.diff(oldValue, newValue)\n        })(patch)\n      }\n    } else {\n      patch = combine({\n        _tag: OP_ADD,\n        fiberRef,\n        value: newValue\n      })(patch)\n    }\n    missingLocals.delete(fiberRef)\n  }\n  for (const [fiberRef] of missingLocals.entries()) {\n    patch = combine({\n      _tag: OP_REMOVE,\n      fiberRef\n    })(patch)\n  }\n  return patch\n}\n\n/** @internal */\nexport const combine = dual<\n  (that: FiberRefsPatch.FiberRefsPatch) => (self: FiberRefsPatch.FiberRefsPatch) => FiberRefsPatch.FiberRefsPatch,\n  (self: FiberRefsPatch.FiberRefsPatch, that: FiberRefsPatch.FiberRefsPatch) => FiberRefsPatch.FiberRefsPatch\n>(2, (self, that) => ({\n  _tag: OP_AND_THEN,\n  first: self,\n  second: that\n}))\n\n/** @internal */\nexport const patch = dual<\n  (\n    fiberId: FiberId.Runtime,\n    oldValue: FiberRefs.FiberRefs\n  ) => (self: FiberRefsPatch.FiberRefsPatch) => FiberRefs.FiberRefs,\n  (\n    self: FiberRefsPatch.FiberRefsPatch,\n    fiberId: FiberId.Runtime,\n    oldValue: FiberRefs.FiberRefs\n  ) => FiberRefs.FiberRefs\n>(3, (self, fiberId, oldValue) => {\n  let fiberRefs: FiberRefs.FiberRefs = oldValue\n  let patches: ReadonlyArray<FiberRefsPatch.FiberRefsPatch> = Arr.of(self)\n  while (Arr.isNonEmptyReadonlyArray(patches)) {\n    const head = Arr.headNonEmpty(patches)\n    const tail = Arr.tailNonEmpty(patches)\n    switch (head._tag) {\n      case OP_EMPTY: {\n        patches = tail\n        break\n      }\n      case OP_ADD: {\n        fiberRefs = fiberRefs_.updateAs(fiberRefs, {\n          fiberId,\n          fiberRef: head.fiberRef,\n          value: head.value\n        })\n        patches = tail\n        break\n      }\n      case OP_REMOVE: {\n        fiberRefs = fiberRefs_.delete_(fiberRefs, head.fiberRef)\n        patches = tail\n        break\n      }\n      case OP_UPDATE: {\n        const value = fiberRefs_.getOrDefault(fiberRefs, head.fiberRef)\n        fiberRefs = fiberRefs_.updateAs(fiberRefs, {\n          fiberId,\n          fiberRef: head.fiberRef,\n          value: head.fiberRef.patch(head.patch)(value)\n        })\n        patches = tail\n        break\n      }\n      case OP_AND_THEN: {\n        patches = Arr.prepend(head.first)(Arr.prepend(head.second)(tail))\n        break\n      }\n    }\n  }\n  return fiberRefs\n})\n"
  },
  {
    "path": "packages/effect/src/internal/fiberRefs.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Equal from \"../Equal.js\"\nimport type * as FiberId from \"../FiberId.js\"\nimport type * as FiberRef from \"../FiberRef.js\"\nimport type * as FiberRefs from \"../FiberRefs.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport * as HashSet from \"../HashSet.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport * as core from \"./core.js\"\n\n/** @internal */\nexport function unsafeMake(\n  fiberRefLocals: Map<FiberRef.FiberRef<any>, Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, any]>>\n): FiberRefs.FiberRefs {\n  return new FiberRefsImpl(fiberRefLocals)\n}\n\n/** @internal */\nexport function empty(): FiberRefs.FiberRefs {\n  return unsafeMake(new Map())\n}\n\n/** @internal */\nexport const FiberRefsSym: FiberRefs.FiberRefsSym = Symbol.for(\"effect/FiberRefs\") as FiberRefs.FiberRefsSym\n\n/** @internal */\nexport class FiberRefsImpl implements FiberRefs.FiberRefs {\n  readonly [FiberRefsSym]: FiberRefs.FiberRefsSym = FiberRefsSym\n  constructor(\n    readonly locals: Map<\n      FiberRef.FiberRef<any>,\n      Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, any]>\n    >\n  ) {}\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nconst findAncestor = (\n  _ref: FiberRef.FiberRef<any>,\n  _parentStack: ReadonlyArray<readonly [FiberId.Single, unknown]>,\n  _childStack: ReadonlyArray<readonly [FiberId.Single, unknown]>,\n  _childModified = false\n): readonly [unknown, boolean] => {\n  const ref = _ref\n  let parentStack = _parentStack\n  let childStack = _childStack\n  let childModified = _childModified\n  let ret: readonly [unknown, boolean] | undefined = undefined\n  while (ret === undefined) {\n    if (Arr.isNonEmptyReadonlyArray(parentStack) && Arr.isNonEmptyReadonlyArray(childStack)) {\n      const parentFiberId = Arr.headNonEmpty(parentStack)[0]\n      const parentAncestors = Arr.tailNonEmpty(parentStack)\n      const childFiberId = Arr.headNonEmpty(childStack)[0]\n      const childRefValue = Arr.headNonEmpty(childStack)[1]\n      const childAncestors = Arr.tailNonEmpty(childStack)\n      if (parentFiberId.startTimeMillis < childFiberId.startTimeMillis) {\n        childStack = childAncestors\n        childModified = true\n      } else if (parentFiberId.startTimeMillis > childFiberId.startTimeMillis) {\n        parentStack = parentAncestors\n      } else {\n        if (parentFiberId.id < childFiberId.id) {\n          childStack = childAncestors\n          childModified = true\n        } else if (parentFiberId.id > childFiberId.id) {\n          parentStack = parentAncestors\n        } else {\n          ret = [childRefValue, childModified] as const\n        }\n      }\n    } else {\n      ret = [ref.initial, true] as const\n    }\n  }\n  return ret\n}\n\n/** @internal */\nexport const joinAs = dual<\n  (fiberId: FiberId.Single, that: FiberRefs.FiberRefs) => (self: FiberRefs.FiberRefs) => FiberRefs.FiberRefs,\n  (self: FiberRefs.FiberRefs, fiberId: FiberId.Single, that: FiberRefs.FiberRefs) => FiberRefs.FiberRefs\n>(3, (self, fiberId, that) => {\n  const parentFiberRefs = new Map(self.locals)\n  that.locals.forEach((childStack, fiberRef) => {\n    const childValue = childStack[0][1]\n    if (!childStack[0][0][Equal.symbol](fiberId)) {\n      if (!parentFiberRefs.has(fiberRef)) {\n        if (Equal.equals(childValue, fiberRef.initial)) {\n          return\n        }\n        parentFiberRefs.set(\n          fiberRef,\n          [[fiberId, fiberRef.join(fiberRef.initial, childValue)]]\n        )\n        return\n      }\n      const parentStack = parentFiberRefs.get(fiberRef)!\n      const [ancestor, wasModified] = findAncestor(\n        fiberRef,\n        parentStack,\n        childStack\n      )\n      if (wasModified) {\n        const patch = fiberRef.diff(ancestor, childValue)\n        const oldValue = parentStack[0][1]\n        const newValue = fiberRef.join(oldValue, fiberRef.patch(patch)(oldValue))\n        if (!Equal.equals(oldValue, newValue)) {\n          let newStack: Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, unknown]>\n          const parentFiberId = parentStack[0][0]\n          if (parentFiberId[Equal.symbol](fiberId)) {\n            newStack = [[parentFiberId, newValue] as const, ...parentStack.slice(1)]\n          } else {\n            newStack = [[fiberId, newValue] as const, ...parentStack]\n          }\n          parentFiberRefs.set(fiberRef, newStack)\n        }\n      }\n    }\n  })\n  return new FiberRefsImpl(parentFiberRefs)\n})\n\n/** @internal */\nexport const forkAs = dual<\n  (childId: FiberId.Single) => (self: FiberRefs.FiberRefs) => FiberRefs.FiberRefs,\n  (self: FiberRefs.FiberRefs, childId: FiberId.Single) => FiberRefs.FiberRefs\n>(2, (self, childId) => {\n  const map = new Map<FiberRef.FiberRef<any>, Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, unknown]>>()\n  unsafeForkAs(self, map, childId)\n  return new FiberRefsImpl(map)\n})\n\nconst unsafeForkAs = (\n  self: FiberRefs.FiberRefs,\n  map: Map<FiberRef.FiberRef<any>, Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, any]>>,\n  fiberId: FiberId.Single\n) => {\n  self.locals.forEach((stack, fiberRef) => {\n    const oldValue = stack[0][1]\n    const newValue = fiberRef.patch(fiberRef.fork)(oldValue)\n    if (Equal.equals(oldValue, newValue)) {\n      map.set(fiberRef, stack)\n    } else {\n      map.set(fiberRef, [[fiberId, newValue] as const, ...stack])\n    }\n  })\n}\n\n/** @internal */\nexport const fiberRefs = (self: FiberRefs.FiberRefs) => HashSet.fromIterable(self.locals.keys())\n\n/** @internal */\nexport const setAll = (self: FiberRefs.FiberRefs): Effect.Effect<void> =>\n  core.forEachSequentialDiscard(\n    fiberRefs(self),\n    (fiberRef) => core.fiberRefSet(fiberRef, getOrDefault(self, fiberRef))\n  )\n\n/** @internal */\nexport const delete_ = dual<\n  <A>(fiberRef: FiberRef.FiberRef<A>) => (self: FiberRefs.FiberRefs) => FiberRefs.FiberRefs,\n  <A>(self: FiberRefs.FiberRefs, fiberRef: FiberRef.FiberRef<A>) => FiberRefs.FiberRefs\n>(2, (self, fiberRef) => {\n  const locals = new Map(self.locals)\n  locals.delete(fiberRef)\n  return new FiberRefsImpl(locals)\n})\n\n/** @internal */\nexport const get = dual<\n  <A>(fiberRef: FiberRef.FiberRef<A>) => (self: FiberRefs.FiberRefs) => Option.Option<A>,\n  <A>(self: FiberRefs.FiberRefs, fiberRef: FiberRef.FiberRef<A>) => Option.Option<A>\n>(2, (self, fiberRef) => {\n  if (!self.locals.has(fiberRef)) {\n    return Option.none()\n  }\n  return Option.some(Arr.headNonEmpty(self.locals.get(fiberRef)!)[1])\n})\n\n/** @internal */\nexport const getOrDefault = dual<\n  <A>(fiberRef: FiberRef.FiberRef<A>) => (self: FiberRefs.FiberRefs) => A,\n  <A>(self: FiberRefs.FiberRefs, fiberRef: FiberRef.FiberRef<A>) => A\n>(2, (self, fiberRef) => pipe(get(self, fiberRef), Option.getOrElse(() => fiberRef.initial)))\n\n/** @internal */\nexport const updateAs = dual<\n  <A>(\n    options: {\n      readonly fiberId: FiberId.Single\n      readonly fiberRef: FiberRef.FiberRef<A>\n      readonly value: A\n    }\n  ) => (self: FiberRefs.FiberRefs) => FiberRefs.FiberRefs,\n  <A>(\n    self: FiberRefs.FiberRefs,\n    options: {\n      readonly fiberId: FiberId.Single\n      readonly fiberRef: FiberRef.FiberRef<A>\n      readonly value: A\n    }\n  ) => FiberRefs.FiberRefs\n>(2, <A>(self: FiberRefs.FiberRefs, { fiberId, fiberRef, value }: {\n  readonly fiberId: FiberId.Single\n  readonly fiberRef: FiberRef.FiberRef<A>\n  readonly value: A\n}) => {\n  if (self.locals.size === 0) {\n    return new FiberRefsImpl(new Map([[fiberRef, [[fiberId, value] as const]]]))\n  }\n  const locals = new Map(self.locals)\n  unsafeUpdateAs(locals, fiberId, fiberRef, value)\n  return new FiberRefsImpl(locals)\n})\n\nconst unsafeUpdateAs = (\n  locals: Map<FiberRef.FiberRef<any>, Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, any]>>,\n  fiberId: FiberId.Single,\n  fiberRef: FiberRef.FiberRef<any>,\n  value: any\n) => {\n  const oldStack: ReadonlyArray<readonly [FiberId.Single, any]> = locals.get(fiberRef) ?? []\n  let newStack: Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, any]> | undefined\n\n  if (Arr.isNonEmptyReadonlyArray(oldStack)) {\n    const [currentId, currentValue] = Arr.headNonEmpty(oldStack)\n    if (currentId[Equal.symbol](fiberId)) {\n      if (Equal.equals(currentValue, value)) {\n        return\n      } else {\n        newStack = [\n          [fiberId, value] as const,\n          ...oldStack.slice(1)\n        ]\n      }\n    } else {\n      newStack = [\n        [fiberId, value] as const,\n        ...oldStack\n      ]\n    }\n  } else {\n    newStack = [[fiberId, value] as const]\n  }\n\n  locals.set(fiberRef, newStack)\n}\n\n/** @internal */\nexport const updateManyAs = dual<\n  (\n    options: {\n      readonly forkAs?: FiberId.Single | undefined\n      readonly entries: Arr.NonEmptyReadonlyArray<\n        readonly [FiberRef.FiberRef<any>, Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, any]>]\n      >\n    }\n  ) => (self: FiberRefs.FiberRefs) => FiberRefs.FiberRefs,\n  (\n    self: FiberRefs.FiberRefs,\n    options: {\n      readonly forkAs?: FiberId.Single | undefined\n      readonly entries: Arr.NonEmptyReadonlyArray<\n        readonly [FiberRef.FiberRef<any>, Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, any]>]\n      >\n    }\n  ) => FiberRefs.FiberRefs\n>(2, (self: FiberRefs.FiberRefs, { entries, forkAs }: {\n  readonly forkAs?: FiberId.Single | undefined\n  readonly entries: Arr.NonEmptyReadonlyArray<\n    readonly [FiberRef.FiberRef<any>, Arr.NonEmptyReadonlyArray<readonly [FiberId.Single, any]>]\n  >\n}) => {\n  if (self.locals.size === 0) {\n    return new FiberRefsImpl(new Map(entries))\n  }\n\n  const locals = new Map(self.locals)\n  if (forkAs !== undefined) {\n    unsafeForkAs(self, locals, forkAs)\n  }\n  entries.forEach(([fiberRef, values]) => {\n    if (values.length === 1) {\n      unsafeUpdateAs(locals, values[0][0], fiberRef, values[0][1])\n    } else {\n      values.forEach(([fiberId, value]) => {\n        unsafeUpdateAs(locals, fiberId, fiberRef, value)\n      })\n    }\n  })\n  return new FiberRefsImpl(locals)\n})\n"
  },
  {
    "path": "packages/effect/src/internal/fiberRuntime.ts",
    "content": "import * as RA from \"../Array.js\"\nimport * as Boolean from \"../Boolean.js\"\nimport type * as Cause from \"../Cause.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport type * as Clock from \"../Clock.js\"\nimport type { ConfigProvider } from \"../ConfigProvider.js\"\nimport * as Context from \"../Context.js\"\nimport type { DefaultServices } from \"../DefaultServices.js\"\nimport type * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Effectable from \"../Effectable.js\"\nimport type * as Either from \"../Either.js\"\nimport * as ExecutionStrategy from \"../ExecutionStrategy.js\"\nimport type * as Exit from \"../Exit.js\"\nimport type * as Fiber from \"../Fiber.js\"\nimport * as FiberId from \"../FiberId.js\"\nimport type * as FiberRef from \"../FiberRef.js\"\nimport * as FiberRefs from \"../FiberRefs.js\"\nimport * as FiberRefsPatch from \"../FiberRefsPatch.js\"\nimport * as FiberStatus from \"../FiberStatus.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { dual, identity, pipe } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport * as HashMap from \"../HashMap.js\"\nimport * as HashSet from \"../HashSet.js\"\nimport * as Inspectable from \"../Inspectable.js\"\nimport type { Logger } from \"../Logger.js\"\nimport * as LogLevel from \"../LogLevel.js\"\nimport type * as MetricLabel from \"../MetricLabel.js\"\nimport * as Micro from \"../Micro.js\"\nimport * as MRef from \"../MutableRef.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport * as Predicate from \"../Predicate.js\"\nimport type * as Random from \"../Random.js\"\nimport * as Ref from \"../Ref.js\"\nimport type { Entry, Request } from \"../Request.js\"\nimport type * as RequestBlock from \"../RequestBlock.js\"\nimport type * as RuntimeFlags from \"../RuntimeFlags.js\"\nimport * as RuntimeFlagsPatch from \"../RuntimeFlagsPatch.js\"\nimport { currentScheduler, type Scheduler } from \"../Scheduler.js\"\nimport type * as Scope from \"../Scope.js\"\nimport type * as Supervisor from \"../Supervisor.js\"\nimport type * as Tracer from \"../Tracer.js\"\nimport type { Concurrency, NoExcessProperties, NoInfer } from \"../Types.js\"\nimport { internalCall, yieldWrapGet } from \"../Utils.js\"\nimport * as RequestBlock_ from \"./blockedRequests.js\"\nimport * as internalCause from \"./cause.js\"\nimport * as clock from \"./clock.js\"\nimport { currentRequestMap } from \"./completedRequestMap.js\"\nimport * as concurrency from \"./concurrency.js\"\nimport { configProviderTag } from \"./configProvider.js\"\nimport * as internalEffect from \"./core-effect.js\"\nimport * as core from \"./core.js\"\nimport * as defaultServices from \"./defaultServices.js\"\nimport { consoleTag } from \"./defaultServices/console.js\"\nimport * as executionStrategy from \"./executionStrategy.js\"\nimport * as internalFiber from \"./fiber.js\"\nimport * as FiberMessage from \"./fiberMessage.js\"\nimport * as fiberRefs from \"./fiberRefs.js\"\nimport * as fiberScope from \"./fiberScope.js\"\nimport * as internalLogger from \"./logger.js\"\nimport * as metric from \"./metric.js\"\nimport * as metricBoundaries from \"./metric/boundaries.js\"\nimport * as metricLabel from \"./metric/label.js\"\nimport * as OpCodes from \"./opCodes/effect.js\"\nimport { randomTag } from \"./random.js\"\nimport { complete } from \"./request.js\"\nimport * as runtimeFlags_ from \"./runtimeFlags.js\"\nimport { OpSupervision } from \"./runtimeFlags.js\"\nimport * as supervisor from \"./supervisor.js\"\nimport * as SupervisorPatch from \"./supervisor/patch.js\"\nimport * as tracer from \"./tracer.js\"\nimport * as version from \"./version.js\"\n\n/** @internal */\nexport const fiberStarted = metric.counter(\"effect_fiber_started\", { incremental: true })\n/** @internal */\nexport const fiberActive = metric.counter(\"effect_fiber_active\")\n/** @internal */\nexport const fiberSuccesses = metric.counter(\"effect_fiber_successes\", { incremental: true })\n/** @internal */\nexport const fiberFailures = metric.counter(\"effect_fiber_failures\", { incremental: true })\n/** @internal */\nexport const fiberLifetimes = metric.tagged(\n  metric.histogram(\n    \"effect_fiber_lifetimes\",\n    metricBoundaries.exponential({\n      start: 0.5,\n      factor: 2,\n      count: 35\n    })\n  ),\n  \"time_unit\",\n  \"milliseconds\"\n)\n\n/** @internal */\ntype EvaluationSignal =\n  | EvaluationSignalContinue\n  | EvaluationSignalDone\n  | EvaluationSignalYieldNow\n\n/** @internal */\nconst EvaluationSignalContinue = \"Continue\" as const\n\n/** @internal */\ntype EvaluationSignalContinue = typeof EvaluationSignalContinue\n\n/** @internal */\nconst EvaluationSignalDone = \"Done\" as const\n\n/** @internal */\ntype EvaluationSignalDone = typeof EvaluationSignalDone\n\n/** @internal */\nconst EvaluationSignalYieldNow = \"Yield\" as const\n\n/** @internal */\ntype EvaluationSignalYieldNow = typeof EvaluationSignalYieldNow\n\nconst runtimeFiberVariance = {\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _A: (_: never) => _\n}\n\nconst absurd = (_: never): never => {\n  throw new Error(\n    `BUG: FiberRuntime - ${\n      Inspectable.toStringUnknown(_)\n    } - please report an issue at https://github.com/Effect-TS/effect/issues`\n  )\n}\n\nconst YieldedOp = Symbol.for(\"effect/internal/fiberRuntime/YieldedOp\")\ntype YieldedOp = typeof YieldedOp\nconst yieldedOpChannel: {\n  currentOp: core.Primitive | null\n} = globalValue(\"effect/internal/fiberRuntime/yieldedOpChannel\", () => ({\n  currentOp: null\n}))\n\nconst contOpSuccess = {\n  [OpCodes.OP_ON_SUCCESS]: (\n    _: FiberRuntime<any, any>,\n    cont: core.OnSuccess,\n    value: unknown\n  ) => {\n    return internalCall(() => cont.effect_instruction_i1(value))\n  },\n  [\"OnStep\"]: (\n    _: FiberRuntime<any, any>,\n    _cont: core.OnStep,\n    value: unknown\n  ) => {\n    return core.exitSucceed(core.exitSucceed(value))\n  },\n  [OpCodes.OP_ON_SUCCESS_AND_FAILURE]: (\n    _: FiberRuntime<any, any>,\n    cont: core.OnSuccessAndFailure,\n    value: unknown\n  ) => {\n    return internalCall(() => cont.effect_instruction_i2(value))\n  },\n  [OpCodes.OP_REVERT_FLAGS]: (\n    self: FiberRuntime<any, any>,\n    cont: core.RevertFlags,\n    value: unknown\n  ) => {\n    self.patchRuntimeFlags(self.currentRuntimeFlags, cont.patch)\n    if (runtimeFlags_.interruptible(self.currentRuntimeFlags) && self.isInterrupted()) {\n      return core.exitFailCause(self.getInterruptedCause())\n    } else {\n      return core.exitSucceed(value)\n    }\n  },\n  [OpCodes.OP_WHILE]: (\n    self: FiberRuntime<any, any>,\n    cont: core.While,\n    value: unknown\n  ) => {\n    internalCall(() => cont.effect_instruction_i2(value))\n    if (internalCall(() => cont.effect_instruction_i0())) {\n      self.pushStack(cont)\n      return internalCall(() => cont.effect_instruction_i1())\n    } else {\n      return core.void\n    }\n  },\n  [OpCodes.OP_ITERATOR]: (\n    self: FiberRuntime<any, any>,\n    cont: core.FromIterator,\n    value: unknown\n  ) => {\n    while (true) {\n      const state = internalCall(() => cont.effect_instruction_i0.next(value))\n      if (state.done) {\n        return core.exitSucceed(state.value)\n      }\n      const primitive = yieldWrapGet(state.value)\n      if (!core.exitIsExit(primitive)) {\n        self.pushStack(cont)\n        return primitive\n      } else if (primitive._tag === \"Failure\") {\n        return primitive\n      }\n      value = primitive.value\n    }\n  }\n}\n\nconst drainQueueWhileRunningTable = {\n  [FiberMessage.OP_INTERRUPT_SIGNAL]: (\n    self: FiberRuntime<any, any>,\n    runtimeFlags: RuntimeFlags.RuntimeFlags,\n    cur: Effect.Effect<any, any, any>,\n    message: FiberMessage.FiberMessage & { _tag: FiberMessage.OP_INTERRUPT_SIGNAL }\n  ) => {\n    self.processNewInterruptSignal(message.cause)\n    return runtimeFlags_.interruptible(runtimeFlags) ? core.exitFailCause(message.cause) : cur\n  },\n  [FiberMessage.OP_RESUME]: (\n    _self: FiberRuntime<any, any>,\n    _runtimeFlags: RuntimeFlags.RuntimeFlags,\n    _cur: Effect.Effect<any, any, any>,\n    _message: FiberMessage.FiberMessage\n  ) => {\n    throw new Error(\"It is illegal to have multiple concurrent run loops in a single fiber\")\n  },\n  [FiberMessage.OP_STATEFUL]: (\n    self: FiberRuntime<any, any>,\n    runtimeFlags: RuntimeFlags.RuntimeFlags,\n    cur: Effect.Effect<any, any, any>,\n    message: FiberMessage.FiberMessage & { _tag: FiberMessage.OP_STATEFUL }\n  ) => {\n    message.onFiber(self, FiberStatus.running(runtimeFlags))\n    return cur\n  },\n  [FiberMessage.OP_YIELD_NOW]: (\n    _self: FiberRuntime<any, any>,\n    _runtimeFlags: RuntimeFlags.RuntimeFlags,\n    cur: Effect.Effect<any, any, any>,\n    _message: FiberMessage.FiberMessage & { _tag: FiberMessage.OP_YIELD_NOW }\n  ) => {\n    return core.flatMap(core.yieldNow(), () => cur)\n  }\n}\n\n/**\n * Executes all requests, submitting requests to each data source in parallel.\n */\nconst runBlockedRequests = (self: RequestBlock.RequestBlock) =>\n  core.forEachSequentialDiscard(\n    RequestBlock_.flatten(self),\n    (requestsByRequestResolver) =>\n      forEachConcurrentDiscard(\n        RequestBlock_.sequentialCollectionToChunk(requestsByRequestResolver),\n        ([dataSource, sequential]) => {\n          const map = new Map<Request<any, any>, Entry<any>>()\n          const arr: Array<Array<Entry<any>>> = []\n          for (const block of sequential) {\n            arr.push(Chunk.toReadonlyArray(block) as any)\n            for (const entry of block) {\n              map.set(entry.request as Request<any, any>, entry)\n            }\n          }\n          const flat = arr.flat()\n          return core.fiberRefLocally(\n            invokeWithInterrupt(dataSource.runAll(arr), flat, () =>\n              flat.forEach((entry) => {\n                entry.listeners.interrupted = true\n              })),\n            currentRequestMap,\n            map\n          )\n        },\n        false,\n        false\n      )\n  )\n\n/** @internal */\nexport interface Snapshot {\n  refs: FiberRefs.FiberRefs\n  flags: RuntimeFlags.RuntimeFlags\n}\n\nconst _version = version.getCurrentVersion()\n\n/** @internal */\nexport class FiberRuntime<in out A, in out E = never> extends Effectable.Class<A, E>\n  implements Fiber.RuntimeFiber<A, E>\n{\n  readonly [internalFiber.FiberTypeId] = internalFiber.fiberVariance\n  readonly [internalFiber.RuntimeFiberTypeId] = runtimeFiberVariance\n  private _fiberRefs: FiberRefs.FiberRefs\n  private _fiberId: FiberId.Runtime\n  private _queue = new Array<FiberMessage.FiberMessage>()\n  private _children: Set<FiberRuntime<any, any>> | null = null\n  private _observers = new Array<(exit: Exit.Exit<A, E>) => void>()\n  private _running = false\n  private _stack: Array<core.Continuation> = []\n  private _asyncInterruptor: ((effect: Effect.Effect<any, any, any>) => any) | null = null\n  private _asyncBlockingOn: FiberId.FiberId | null = null\n  private _exitValue: Exit.Exit<A, E> | null = null\n  private _steps: Array<Snapshot> = []\n  private _isYielding = false\n\n  public currentRuntimeFlags: RuntimeFlags.RuntimeFlags\n  public currentOpCount: number = 0\n  public currentSupervisor!: Supervisor.Supervisor<any>\n  public currentScheduler!: Scheduler\n  public currentTracer!: Tracer.Tracer\n  public currentSpan!: Tracer.AnySpan | undefined\n  public currentContext!: Context.Context<never>\n  public currentDefaultServices!: Context.Context<DefaultServices>\n\n  constructor(\n    fiberId: FiberId.Runtime,\n    fiberRefs0: FiberRefs.FiberRefs,\n    runtimeFlags0: RuntimeFlags.RuntimeFlags\n  ) {\n    super()\n    this.currentRuntimeFlags = runtimeFlags0\n    this._fiberId = fiberId\n    this._fiberRefs = fiberRefs0\n    if (runtimeFlags_.runtimeMetrics(runtimeFlags0)) {\n      const tags = this.getFiberRef(core.currentMetricLabels)\n      fiberStarted.unsafeUpdate(1, tags)\n      fiberActive.unsafeUpdate(1, tags)\n    }\n    this.refreshRefCache()\n  }\n\n  commit(): Effect.Effect<A, E, never> {\n    return internalFiber.join(this)\n  }\n\n  /**\n   * The identity of the fiber.\n   */\n  id(): FiberId.Runtime {\n    return this._fiberId\n  }\n\n  /**\n   * Begins execution of the effect associated with this fiber on in the\n   * background. This can be called to \"kick off\" execution of a fiber after\n   * it has been created.\n   */\n  resume<A, E>(effect: Effect.Effect<A, E, any>): void {\n    this.tell(FiberMessage.resume(effect))\n  }\n\n  /**\n   * The status of the fiber.\n   */\n  get status(): Effect.Effect<FiberStatus.FiberStatus> {\n    return this.ask((_, status) => status)\n  }\n\n  /**\n   * Gets the fiber runtime flags.\n   */\n  get runtimeFlags(): Effect.Effect<RuntimeFlags.RuntimeFlags> {\n    return this.ask((state, status) => {\n      if (FiberStatus.isDone(status)) {\n        return state.currentRuntimeFlags\n      }\n      return status.runtimeFlags\n    })\n  }\n\n  /**\n   * Returns the current `FiberScope` for the fiber.\n   */\n  scope(): fiberScope.FiberScope {\n    return fiberScope.unsafeMake(this)\n  }\n\n  /**\n   * Retrieves the immediate children of the fiber.\n   */\n  get children(): Effect.Effect<Array<Fiber.RuntimeFiber<any, any>>> {\n    return this.ask((fiber) => Array.from(fiber.getChildren()))\n  }\n\n  /**\n   * Gets the fiber's set of children.\n   */\n  getChildren(): Set<FiberRuntime<any, any>> {\n    if (this._children === null) {\n      this._children = new Set()\n    }\n    return this._children\n  }\n\n  /**\n   * Retrieves the interrupted cause of the fiber, which will be `Cause.empty`\n   * if the fiber has not been interrupted.\n   *\n   * **NOTE**: This method is safe to invoke on any fiber, but if not invoked\n   * on this fiber, then values derived from the fiber's state (including the\n   * log annotations and log level) may not be up-to-date.\n   */\n  getInterruptedCause() {\n    return this.getFiberRef(core.currentInterruptedCause)\n  }\n\n  /**\n   * Retrieves the whole set of fiber refs.\n   */\n  fiberRefs(): Effect.Effect<FiberRefs.FiberRefs> {\n    return this.ask((fiber) => fiber.getFiberRefs())\n  }\n\n  /**\n   * Returns an effect that will contain information computed from the fiber\n   * state and status while running on the fiber.\n   *\n   * This allows the outside world to interact safely with mutable fiber state\n   * without locks or immutable data.\n   */\n  ask<Z>(\n    f: (runtime: FiberRuntime<any, any>, status: FiberStatus.FiberStatus) => Z\n  ): Effect.Effect<Z> {\n    return core.suspend(() => {\n      const deferred = core.deferredUnsafeMake<Z>(this._fiberId)\n      this.tell(\n        FiberMessage.stateful((fiber, status) => {\n          core.deferredUnsafeDone(deferred, core.sync(() => f(fiber, status)))\n        })\n      )\n      return core.deferredAwait(deferred)\n    })\n  }\n\n  /**\n   * Adds a message to be processed by the fiber on the fiber.\n   */\n  tell(message: FiberMessage.FiberMessage): void {\n    this._queue.push(message)\n    if (!this._running) {\n      this._running = true\n      this.drainQueueLaterOnExecutor()\n    }\n  }\n\n  get await(): Effect.Effect<Exit.Exit<A, E>> {\n    return core.async((resume) => {\n      const cb = (exit: Exit.Exit<A, E>) => resume(core.succeed(exit))\n      if (this._exitValue !== null) {\n        cb(this._exitValue!)\n        return\n      }\n      this.tell(\n        FiberMessage.stateful((fiber, _) => {\n          if (fiber._exitValue !== null) {\n            cb(this._exitValue!)\n          } else {\n            fiber.addObserver(cb)\n          }\n        })\n      )\n      return core.sync(() =>\n        this.tell(\n          FiberMessage.stateful((fiber, _) => {\n            fiber.removeObserver(cb)\n          })\n        )\n      )\n    }, this.id())\n  }\n\n  get inheritAll(): Effect.Effect<void> {\n    return core.withFiberRuntime((parentFiber, parentStatus) => {\n      const parentFiberId = parentFiber.id()\n      const parentFiberRefs = parentFiber.getFiberRefs()\n      const parentRuntimeFlags = parentStatus.runtimeFlags\n      const childFiberRefs = this.getFiberRefs()\n      const updatedFiberRefs = fiberRefs.joinAs(parentFiberRefs, parentFiberId, childFiberRefs)\n\n      parentFiber.setFiberRefs(updatedFiberRefs)\n\n      const updatedRuntimeFlags = parentFiber.getFiberRef(currentRuntimeFlags)\n\n      const patch = pipe(\n        runtimeFlags_.diff(parentRuntimeFlags, updatedRuntimeFlags),\n        // Do not inherit WindDown or Interruption!\n        RuntimeFlagsPatch.exclude(runtimeFlags_.Interruption),\n        RuntimeFlagsPatch.exclude(runtimeFlags_.WindDown)\n      )\n\n      return core.updateRuntimeFlags(patch)\n    })\n  }\n\n  /**\n   * Tentatively observes the fiber, but returns immediately if it is not\n   * already done.\n   */\n  get poll(): Effect.Effect<Option.Option<Exit.Exit<A, E>>> {\n    return core.sync(() => Option.fromNullable(this._exitValue))\n  }\n\n  /**\n   * Unsafely observes the fiber, but returns immediately if it is not\n   * already done.\n   */\n  unsafePoll(): Exit.Exit<A, E> | null {\n    return this._exitValue\n  }\n\n  /**\n   * In the background, interrupts the fiber as if interrupted from the specified fiber.\n   */\n  interruptAsFork(fiberId: FiberId.FiberId): Effect.Effect<void> {\n    return core.sync(() => this.tell(FiberMessage.interruptSignal(internalCause.interrupt(fiberId))))\n  }\n\n  /**\n   * In the background, interrupts the fiber as if interrupted from the specified fiber.\n   */\n  unsafeInterruptAsFork(fiberId: FiberId.FiberId) {\n    this.tell(FiberMessage.interruptSignal(internalCause.interrupt(fiberId)))\n  }\n\n  /**\n   * Adds an observer to the list of observers.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  addObserver(observer: (exit: Exit.Exit<A, E>) => void): void {\n    if (this._exitValue !== null) {\n      observer(this._exitValue!)\n    } else {\n      this._observers.push(observer)\n    }\n  }\n\n  /**\n   * Removes the specified observer from the list of observers that will be\n   * notified when the fiber exits.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  removeObserver(observer: (exit: Exit.Exit<A, E>) => void): void {\n    this._observers = this._observers.filter((o) => o !== observer)\n  }\n  /**\n   * Retrieves all fiber refs of the fiber.\n   *\n   * **NOTE**: This method is safe to invoke on any fiber, but if not invoked\n   * on this fiber, then values derived from the fiber's state (including the\n   * log annotations and log level) may not be up-to-date.\n   */\n  getFiberRefs(): FiberRefs.FiberRefs {\n    this.setFiberRef(currentRuntimeFlags, this.currentRuntimeFlags)\n    return this._fiberRefs\n  }\n\n  /**\n   * Deletes the specified fiber ref.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  unsafeDeleteFiberRef<X>(fiberRef: FiberRef.FiberRef<X>): void {\n    this._fiberRefs = fiberRefs.delete_(this._fiberRefs, fiberRef)\n  }\n\n  /**\n   * Retrieves the state of the fiber ref, or else its initial value.\n   *\n   * **NOTE**: This method is safe to invoke on any fiber, but if not invoked\n   * on this fiber, then values derived from the fiber's state (including the\n   * log annotations and log level) may not be up-to-date.\n   */\n  getFiberRef<X>(fiberRef: FiberRef.FiberRef<X>): X {\n    if (this._fiberRefs.locals.has(fiberRef)) {\n      return this._fiberRefs.locals.get(fiberRef)![0][1] as X\n    }\n    return fiberRef.initial\n  }\n\n  /**\n   * Sets the fiber ref to the specified value.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  setFiberRef<X>(fiberRef: FiberRef.FiberRef<X>, value: X): void {\n    this._fiberRefs = fiberRefs.updateAs(this._fiberRefs, {\n      fiberId: this._fiberId,\n      fiberRef,\n      value\n    })\n    this.refreshRefCache()\n  }\n\n  refreshRefCache() {\n    this.currentDefaultServices = this.getFiberRef(defaultServices.currentServices)\n    this.currentTracer = this.currentDefaultServices.unsafeMap.get(tracer.tracerTag.key)\n    this.currentSupervisor = this.getFiberRef(currentSupervisor)\n    this.currentScheduler = this.getFiberRef(currentScheduler)\n    this.currentContext = this.getFiberRef(core.currentContext)\n    this.currentSpan = this.currentContext.unsafeMap.get(tracer.spanTag.key)\n  }\n\n  /**\n   * Wholesale replaces all fiber refs of this fiber.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  setFiberRefs(fiberRefs: FiberRefs.FiberRefs): void {\n    this._fiberRefs = fiberRefs\n    this.refreshRefCache()\n  }\n\n  /**\n   * Adds a reference to the specified fiber inside the children set.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  addChild(child: FiberRuntime<any, any>) {\n    this.getChildren().add(child)\n  }\n\n  /**\n   * Removes a reference to the specified fiber inside the children set.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  removeChild(child: FiberRuntime<any, any>) {\n    this.getChildren().delete(child)\n  }\n\n  /**\n   * Transfers all children of this fiber that are currently running to the\n   * specified fiber scope.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself after it has\n   * evaluated the effects but prior to exiting.\n   */\n  transferChildren(scope: fiberScope.FiberScope) {\n    const children = this._children\n    // Clear the children of the current fiber\n    this._children = null\n    if (children !== null && children.size > 0) {\n      for (const child of children) {\n        // If the child is still running, add it to the scope\n        if (child._exitValue === null) {\n          scope.add(this.currentRuntimeFlags, child)\n        }\n      }\n    }\n  }\n\n  /**\n   * On the current thread, executes all messages in the fiber's inbox. This\n   * method may return before all work is done, in the event the fiber executes\n   * an asynchronous operation.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  drainQueueOnCurrentThread() {\n    let recurse = true\n    while (recurse) {\n      let evaluationSignal: EvaluationSignal = EvaluationSignalContinue\n      const prev = (globalThis as any)[internalFiber.currentFiberURI]\n      ;(globalThis as any)[internalFiber.currentFiberURI] = this\n      try {\n        while (evaluationSignal === EvaluationSignalContinue) {\n          evaluationSignal = this._queue.length === 0 ?\n            EvaluationSignalDone :\n            this.evaluateMessageWhileSuspended(this._queue.splice(0, 1)[0]!)\n        }\n      } finally {\n        this._running = false\n        ;(globalThis as any)[internalFiber.currentFiberURI] = prev\n      }\n      // Maybe someone added something to the queue between us checking, and us\n      // giving up the drain. If so, we need to restart the draining, but only\n      // if we beat everyone else to the restart:\n      if (this._queue.length > 0 && !this._running) {\n        this._running = true\n        if (evaluationSignal === EvaluationSignalYieldNow) {\n          this.drainQueueLaterOnExecutor()\n          recurse = false\n        } else {\n          recurse = true\n        }\n      } else {\n        recurse = false\n      }\n    }\n  }\n\n  /**\n   * Schedules the execution of all messages in the fiber's inbox.\n   *\n   * This method will return immediately after the scheduling\n   * operation is completed, but potentially before such messages have been\n   * executed.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  drainQueueLaterOnExecutor() {\n    this.currentScheduler.scheduleTask(\n      this.run,\n      this.getFiberRef(core.currentSchedulingPriority),\n      this\n    )\n  }\n\n  /**\n   * Drains the fiber's message queue while the fiber is actively running,\n   * returning the next effect to execute, which may be the input effect if no\n   * additional effect needs to be executed.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  drainQueueWhileRunning(\n    runtimeFlags: RuntimeFlags.RuntimeFlags,\n    cur0: Effect.Effect<any, any, any>\n  ) {\n    let cur = cur0\n    while (this._queue.length > 0) {\n      const message = this._queue.splice(0, 1)[0]\n      // @ts-expect-error\n      cur = drainQueueWhileRunningTable[message._tag](this, runtimeFlags, cur, message)\n    }\n    return cur\n  }\n\n  /**\n   * Determines if the fiber is interrupted.\n   *\n   * **NOTE**: This method is safe to invoke on any fiber, but if not invoked\n   * on this fiber, then values derived from the fiber's state (including the\n   * log annotations and log level) may not be up-to-date.\n   */\n  isInterrupted(): boolean {\n    return !internalCause.isEmpty(this.getFiberRef(core.currentInterruptedCause))\n  }\n\n  /**\n   * Adds an interruptor to the set of interruptors that are interrupting this\n   * fiber.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  addInterruptedCause(cause: Cause.Cause<never>) {\n    const oldSC = this.getFiberRef(core.currentInterruptedCause)\n    this.setFiberRef(core.currentInterruptedCause, internalCause.sequential(oldSC, cause))\n  }\n\n  /**\n   * Processes a new incoming interrupt signal.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  processNewInterruptSignal(cause: Cause.Cause<never>): void {\n    this.addInterruptedCause(cause)\n    this.sendInterruptSignalToAllChildren()\n  }\n\n  /**\n   * Interrupts all children of the current fiber, returning an effect that will\n   * await the exit of the children. This method will return null if the fiber\n   * has no children.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  sendInterruptSignalToAllChildren(): boolean {\n    if (this._children === null || this._children.size === 0) {\n      return false\n    }\n    let told = false\n    for (const child of this._children) {\n      child.tell(FiberMessage.interruptSignal(internalCause.interrupt(this.id())))\n      told = true\n    }\n    return told\n  }\n\n  /**\n   * Interrupts all children of the current fiber, returning an effect that will\n   * await the exit of the children. This method will return null if the fiber\n   * has no children.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  interruptAllChildren() {\n    if (this.sendInterruptSignalToAllChildren()) {\n      const it = this._children!.values()\n      this._children = null\n      let isDone = false\n      const body = () => {\n        const next = it.next()\n        if (!next.done) {\n          return core.asVoid(next.value.await)\n        } else {\n          return core.sync(() => {\n            isDone = true\n          })\n        }\n      }\n      return core.whileLoop({\n        while: () => !isDone,\n        body,\n        step: () => {\n          //\n        }\n      })\n    }\n    return null\n  }\n\n  reportExitValue(exit: Exit.Exit<A, E>) {\n    if (runtimeFlags_.runtimeMetrics(this.currentRuntimeFlags)) {\n      const tags = this.getFiberRef(core.currentMetricLabels)\n      const startTimeMillis = this.id().startTimeMillis\n      const endTimeMillis = Date.now()\n      fiberLifetimes.unsafeUpdate(endTimeMillis - startTimeMillis, tags)\n      fiberActive.unsafeUpdate(-1, tags)\n      switch (exit._tag) {\n        case OpCodes.OP_SUCCESS: {\n          fiberSuccesses.unsafeUpdate(1, tags)\n          break\n        }\n        case OpCodes.OP_FAILURE: {\n          fiberFailures.unsafeUpdate(1, tags)\n          break\n        }\n      }\n    }\n    if (exit._tag === \"Failure\") {\n      const level = this.getFiberRef(core.currentUnhandledErrorLogLevel)\n      if (!internalCause.isInterruptedOnly(exit.cause) && level._tag === \"Some\") {\n        this.log(\"Fiber terminated with an unhandled error\", exit.cause, level)\n      }\n    }\n  }\n\n  setExitValue(exit: Exit.Exit<A, E>) {\n    this._exitValue = exit\n    this.reportExitValue(exit)\n    for (let i = this._observers.length - 1; i >= 0; i--) {\n      this._observers[i](exit)\n    }\n    this._observers = []\n  }\n\n  getLoggers() {\n    return this.getFiberRef(currentLoggers)\n  }\n\n  log(\n    message: unknown,\n    cause: Cause.Cause<any>,\n    overrideLogLevel: Option.Option<LogLevel.LogLevel>\n  ): void {\n    const logLevel = Option.isSome(overrideLogLevel) ?\n      overrideLogLevel.value :\n      this.getFiberRef(core.currentLogLevel)\n    const minimumLogLevel = this.getFiberRef(currentMinimumLogLevel)\n    if (LogLevel.greaterThan(minimumLogLevel, logLevel)) {\n      return\n    }\n    const spans = this.getFiberRef(core.currentLogSpan)\n    const annotations = this.getFiberRef(core.currentLogAnnotations)\n    const loggers = this.getLoggers()\n    const contextMap = this.getFiberRefs()\n    if (HashSet.size(loggers) > 0) {\n      const clockService = Context.get(this.getFiberRef(defaultServices.currentServices), clock.clockTag)\n      const date = new Date(clockService.unsafeCurrentTimeMillis())\n      Inspectable.withRedactableContext(contextMap, () => {\n        for (const logger of loggers) {\n          logger.log({\n            fiberId: this.id(),\n            logLevel,\n            message,\n            cause,\n            context: contextMap,\n            spans,\n            annotations,\n            date\n          })\n        }\n      })\n    }\n  }\n\n  /**\n   * Evaluates a single message on the current thread, while the fiber is\n   * suspended. This method should only be called while evaluation of the\n   * fiber's effect is suspended due to an asynchronous operation.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  evaluateMessageWhileSuspended(message: FiberMessage.FiberMessage): EvaluationSignal {\n    switch (message._tag) {\n      case FiberMessage.OP_YIELD_NOW: {\n        return EvaluationSignalYieldNow\n      }\n      case FiberMessage.OP_INTERRUPT_SIGNAL: {\n        this.processNewInterruptSignal(message.cause)\n        if (this._asyncInterruptor !== null) {\n          this._asyncInterruptor(core.exitFailCause(message.cause))\n          this._asyncInterruptor = null\n        }\n        return EvaluationSignalContinue\n      }\n      case FiberMessage.OP_RESUME: {\n        this._asyncInterruptor = null\n        this._asyncBlockingOn = null\n        this.evaluateEffect(message.effect)\n        return EvaluationSignalContinue\n      }\n      case FiberMessage.OP_STATEFUL: {\n        message.onFiber(\n          this,\n          this._exitValue !== null ?\n            FiberStatus.done :\n            FiberStatus.suspended(this.currentRuntimeFlags, this._asyncBlockingOn!)\n        )\n        return EvaluationSignalContinue\n      }\n      default: {\n        return absurd(message)\n      }\n    }\n  }\n\n  /**\n   * Evaluates an effect until completion, potentially asynchronously.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  evaluateEffect(effect0: Effect.Effect<any, any, any>) {\n    this.currentSupervisor.onResume(this)\n    try {\n      let effect: Effect.Effect<any, any, any> | null =\n        runtimeFlags_.interruptible(this.currentRuntimeFlags) && this.isInterrupted() ?\n          core.exitFailCause(this.getInterruptedCause()) :\n          effect0\n      while (effect !== null) {\n        const eff: Effect.Effect<any, any, any> = effect\n        const exit = this.runLoop(eff)\n        if (exit === YieldedOp) {\n          const op = yieldedOpChannel.currentOp!\n          yieldedOpChannel.currentOp = null\n          if (op._op === OpCodes.OP_YIELD) {\n            if (runtimeFlags_.cooperativeYielding(this.currentRuntimeFlags)) {\n              this.tell(FiberMessage.yieldNow())\n              this.tell(FiberMessage.resume(core.exitVoid))\n              effect = null\n            } else {\n              effect = core.exitVoid\n            }\n          } else if (op._op === OpCodes.OP_ASYNC) {\n            // Terminate this evaluation, async resumption will continue evaluation:\n            effect = null\n          }\n        } else {\n          this.currentRuntimeFlags = pipe(this.currentRuntimeFlags, runtimeFlags_.enable(runtimeFlags_.WindDown))\n          const interruption = this.interruptAllChildren()\n          if (interruption !== null) {\n            effect = core.flatMap(interruption, () => exit)\n          } else {\n            if (this._queue.length === 0) {\n              // No more messages to process, so we will allow the fiber to end life:\n              this.setExitValue(exit)\n            } else {\n              // There are messages, possibly added by the final op executed by\n              // the fiber. To be safe, we should execute those now before we\n              // allow the fiber to end life:\n              this.tell(FiberMessage.resume(exit))\n            }\n            effect = null\n          }\n        }\n      }\n    } finally {\n      this.currentSupervisor.onSuspend(this)\n    }\n  }\n\n  /**\n   * Begins execution of the effect associated with this fiber on the current\n   * thread. This can be called to \"kick off\" execution of a fiber after it has\n   * been created, in hopes that the effect can be executed synchronously.\n   *\n   * This is not the normal way of starting a fiber, but it is useful when the\n   * express goal of executing the fiber is to synchronously produce its exit.\n   */\n  start<R>(effect: Effect.Effect<A, E, R>): void {\n    if (!this._running) {\n      this._running = true\n      const prev = (globalThis as any)[internalFiber.currentFiberURI]\n      ;(globalThis as any)[internalFiber.currentFiberURI] = this\n      try {\n        this.evaluateEffect(effect)\n      } finally {\n        this._running = false\n        ;(globalThis as any)[internalFiber.currentFiberURI] = prev\n        // Because we're special casing `start`, we have to be responsible\n        // for spinning up the fiber if there were new messages added to\n        // the queue between the completion of the effect and the transition\n        // to the not running state.\n        if (this._queue.length > 0) {\n          this.drainQueueLaterOnExecutor()\n        }\n      }\n    } else {\n      this.tell(FiberMessage.resume(effect))\n    }\n  }\n\n  /**\n   * Begins execution of the effect associated with this fiber on in the\n   * background, and on the correct thread pool. This can be called to \"kick\n   * off\" execution of a fiber after it has been created, in hopes that the\n   * effect can be executed synchronously.\n   */\n  startFork<R>(effect: Effect.Effect<A, E, R>): void {\n    this.tell(FiberMessage.resume(effect))\n  }\n\n  /**\n   * Takes the current runtime flags, patches them to return the new runtime\n   * flags, and then makes any changes necessary to fiber state based on the\n   * specified patch.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  patchRuntimeFlags(oldRuntimeFlags: RuntimeFlags.RuntimeFlags, patch: RuntimeFlagsPatch.RuntimeFlagsPatch) {\n    const newRuntimeFlags = runtimeFlags_.patch(oldRuntimeFlags, patch)\n    ;(globalThis as any)[internalFiber.currentFiberURI] = this\n    this.currentRuntimeFlags = newRuntimeFlags\n    return newRuntimeFlags\n  }\n\n  /**\n   * Initiates an asynchronous operation, by building a callback that will\n   * resume execution, and then feeding that callback to the registration\n   * function, handling error cases and repeated resumptions appropriately.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  initiateAsync(\n    runtimeFlags: RuntimeFlags.RuntimeFlags,\n    asyncRegister: (resume: (effect: Effect.Effect<any, any, any>) => void) => void\n  ) {\n    let alreadyCalled = false\n    const callback = (effect: Effect.Effect<any, any, any>) => {\n      if (!alreadyCalled) {\n        alreadyCalled = true\n        this.tell(FiberMessage.resume(effect))\n      }\n    }\n    if (runtimeFlags_.interruptible(runtimeFlags)) {\n      this._asyncInterruptor = callback\n    }\n    try {\n      asyncRegister(callback)\n    } catch (e) {\n      callback(core.failCause(internalCause.die(e)))\n    }\n  }\n\n  pushStack(cont: core.Continuation) {\n    this._stack.push(cont)\n    if (cont._op === \"OnStep\") {\n      this._steps.push({ refs: this.getFiberRefs(), flags: this.currentRuntimeFlags })\n    }\n  }\n\n  popStack() {\n    const item = this._stack.pop()\n    if (item) {\n      if (item._op === \"OnStep\") {\n        this._steps.pop()\n      }\n      return item\n    }\n    return\n  }\n\n  getNextSuccessCont() {\n    let frame = this.popStack()\n    while (frame) {\n      if (frame._op !== OpCodes.OP_ON_FAILURE) {\n        return frame\n      }\n      frame = this.popStack()\n    }\n  }\n\n  getNextFailCont() {\n    let frame = this.popStack()\n    while (frame) {\n      if (frame._op !== OpCodes.OP_ON_SUCCESS && frame._op !== OpCodes.OP_WHILE && frame._op !== OpCodes.OP_ITERATOR) {\n        return frame\n      }\n      frame = this.popStack()\n    }\n  }\n\n  [OpCodes.OP_TAG](op: core.Primitive & { _op: OpCodes.OP_SYNC }) {\n    return core.sync(() => Context.unsafeGet(this.currentContext, op as unknown as Context.Tag<any, any>))\n  }\n\n  [\"Left\"](op: core.Primitive & { _op: \"Left\" }) {\n    return core.fail(op.left)\n  }\n\n  [\"None\"](_: core.Primitive & { _op: \"None\" }) {\n    return core.fail(new core.NoSuchElementException())\n  }\n\n  [\"Right\"](op: core.Primitive & { _op: \"Right\" }) {\n    return core.exitSucceed(op.right)\n  }\n\n  [\"Some\"](op: core.Primitive & { _op: \"Some\" }) {\n    return core.exitSucceed(op.value)\n  }\n\n  [\"Micro\"](op: Micro.Micro<any, any, never> & { _op: \"Micro\" }) {\n    return core.unsafeAsync<any, any>((microResume) => {\n      let resume = microResume\n      const fiber = Micro.runFork(Micro.provideContext(op, this.currentContext))\n      fiber.addObserver((exit) => {\n        if (exit._tag === \"Success\") {\n          return resume(core.exitSucceed(exit.value))\n        }\n        switch (exit.cause._tag) {\n          case \"Interrupt\": {\n            return resume(core.exitFailCause(internalCause.interrupt(FiberId.none)))\n          }\n          case \"Fail\": {\n            return resume(core.fail(exit.cause.error))\n          }\n          case \"Die\": {\n            return resume(core.die(exit.cause.defect))\n          }\n        }\n      })\n      return core.unsafeAsync<void>((abortResume) => {\n        resume = (_: any) => {\n          abortResume(core.void)\n        }\n        fiber.unsafeInterrupt()\n      })\n    })\n  }\n\n  [OpCodes.OP_SYNC](op: core.Primitive & { _op: OpCodes.OP_SYNC }) {\n    const value = internalCall(() => op.effect_instruction_i0())\n    const cont = this.getNextSuccessCont()\n    if (cont !== undefined) {\n      if (!(cont._op in contOpSuccess)) {\n        // @ts-expect-error\n        absurd(cont)\n      }\n      // @ts-expect-error\n      return contOpSuccess[cont._op](this, cont, value)\n    } else {\n      yieldedOpChannel.currentOp = core.exitSucceed(value) as any\n      return YieldedOp\n    }\n  }\n\n  [OpCodes.OP_SUCCESS](op: core.Primitive & { _op: OpCodes.OP_SUCCESS }) {\n    const oldCur = op\n    const cont = this.getNextSuccessCont()\n    if (cont !== undefined) {\n      if (!(cont._op in contOpSuccess)) {\n        // @ts-expect-error\n        absurd(cont)\n      }\n      // @ts-expect-error\n      return contOpSuccess[cont._op](this, cont, oldCur.effect_instruction_i0)\n    } else {\n      yieldedOpChannel.currentOp = oldCur\n      return YieldedOp\n    }\n  }\n\n  [OpCodes.OP_FAILURE](op: core.Primitive & { _op: OpCodes.OP_FAILURE }) {\n    const cause = op.effect_instruction_i0\n    const cont = this.getNextFailCont()\n    if (cont !== undefined) {\n      switch (cont._op) {\n        case OpCodes.OP_ON_FAILURE:\n        case OpCodes.OP_ON_SUCCESS_AND_FAILURE: {\n          if (!(runtimeFlags_.interruptible(this.currentRuntimeFlags) && this.isInterrupted())) {\n            return internalCall(() => cont.effect_instruction_i1(cause))\n          } else {\n            return core.exitFailCause(internalCause.stripFailures(cause))\n          }\n        }\n        case \"OnStep\": {\n          if (!(runtimeFlags_.interruptible(this.currentRuntimeFlags) && this.isInterrupted())) {\n            return core.exitSucceed(core.exitFailCause(cause))\n          } else {\n            return core.exitFailCause(internalCause.stripFailures(cause))\n          }\n        }\n        case OpCodes.OP_REVERT_FLAGS: {\n          this.patchRuntimeFlags(this.currentRuntimeFlags, cont.patch)\n          if (runtimeFlags_.interruptible(this.currentRuntimeFlags) && this.isInterrupted()) {\n            return core.exitFailCause(internalCause.sequential(cause, this.getInterruptedCause()))\n          } else {\n            return core.exitFailCause(cause)\n          }\n        }\n        default: {\n          absurd(cont)\n        }\n      }\n    } else {\n      yieldedOpChannel.currentOp = core.exitFailCause(cause) as any\n      return YieldedOp\n    }\n  }\n\n  [OpCodes.OP_WITH_RUNTIME](op: core.Primitive & { _op: OpCodes.OP_WITH_RUNTIME }) {\n    return internalCall(() =>\n      op.effect_instruction_i0(\n        this as FiberRuntime<unknown, unknown>,\n        FiberStatus.running(this.currentRuntimeFlags) as FiberStatus.Running\n      )\n    )\n  }\n\n  [\"Blocked\"](op: core.Primitive & { _op: \"Blocked\" }) {\n    const refs = this.getFiberRefs()\n    const flags = this.currentRuntimeFlags\n    if (this._steps.length > 0) {\n      const frames: Array<core.Continuation> = []\n      const snap = this._steps[this._steps.length - 1]\n      let frame = this.popStack()\n      while (frame && frame._op !== \"OnStep\") {\n        frames.push(frame)\n        frame = this.popStack()\n      }\n      this.setFiberRefs(snap.refs)\n      this.currentRuntimeFlags = snap.flags\n      const patchRefs = FiberRefsPatch.diff(snap.refs, refs)\n      const patchFlags = runtimeFlags_.diff(snap.flags, flags)\n      return core.exitSucceed(core.blocked(\n        op.effect_instruction_i0,\n        core.withFiberRuntime<unknown, unknown>((newFiber) => {\n          while (frames.length > 0) {\n            newFiber.pushStack(frames.pop()!)\n          }\n          newFiber.setFiberRefs(\n            FiberRefsPatch.patch(newFiber.id(), newFiber.getFiberRefs())(patchRefs)\n          )\n          newFiber.currentRuntimeFlags = runtimeFlags_.patch(patchFlags)(newFiber.currentRuntimeFlags)\n          return op.effect_instruction_i1\n        })\n      ))\n    }\n    return core.uninterruptibleMask((restore) =>\n      core.flatMap(\n        forkDaemon(core.runRequestBlock(op.effect_instruction_i0)),\n        () => restore(op.effect_instruction_i1)\n      )\n    )\n  }\n\n  [\"RunBlocked\"](op: core.Primitive & { _op: \"RunBlocked\" }) {\n    return runBlockedRequests(op.effect_instruction_i0)\n  }\n\n  [OpCodes.OP_UPDATE_RUNTIME_FLAGS](op: core.Primitive & { _op: OpCodes.OP_UPDATE_RUNTIME_FLAGS }) {\n    const updateFlags = op.effect_instruction_i0\n    const oldRuntimeFlags = this.currentRuntimeFlags\n    const newRuntimeFlags = runtimeFlags_.patch(oldRuntimeFlags, updateFlags)\n    // One more chance to short circuit: if we're immediately going\n    // to interrupt. Interruption will cause immediate reversion of\n    // the flag, so as long as we \"peek ahead\", there's no need to\n    // set them to begin with.\n    if (runtimeFlags_.interruptible(newRuntimeFlags) && this.isInterrupted()) {\n      return core.exitFailCause(this.getInterruptedCause())\n    } else {\n      // Impossible to short circuit, so record the changes\n      this.patchRuntimeFlags(this.currentRuntimeFlags, updateFlags)\n      if (op.effect_instruction_i1) {\n        // Since we updated the flags, we need to revert them\n        const revertFlags = runtimeFlags_.diff(newRuntimeFlags, oldRuntimeFlags)\n        this.pushStack(new core.RevertFlags(revertFlags, op))\n        return internalCall(() => op.effect_instruction_i1!(oldRuntimeFlags))\n      } else {\n        return core.exitVoid\n      }\n    }\n  }\n\n  [OpCodes.OP_ON_SUCCESS](op: core.Primitive & { _op: OpCodes.OP_ON_SUCCESS }) {\n    this.pushStack(op)\n    return op.effect_instruction_i0\n  }\n\n  [\"OnStep\"](op: core.Primitive & { _op: \"OnStep\" }) {\n    this.pushStack(op)\n    return op.effect_instruction_i0\n  }\n\n  [OpCodes.OP_ON_FAILURE](op: core.Primitive & { _op: OpCodes.OP_ON_FAILURE }) {\n    this.pushStack(op)\n    return op.effect_instruction_i0\n  }\n\n  [OpCodes.OP_ON_SUCCESS_AND_FAILURE](op: core.Primitive & { _op: OpCodes.OP_ON_SUCCESS_AND_FAILURE }) {\n    this.pushStack(op)\n    return op.effect_instruction_i0\n  }\n\n  [OpCodes.OP_ASYNC](op: core.Primitive & { _op: OpCodes.OP_ASYNC }) {\n    this._asyncBlockingOn = op.effect_instruction_i1\n    this.initiateAsync(this.currentRuntimeFlags, op.effect_instruction_i0)\n    yieldedOpChannel.currentOp = op\n    return YieldedOp\n  }\n\n  [OpCodes.OP_YIELD](op: core.Primitive & { op: OpCodes.OP_YIELD }) {\n    this._isYielding = false\n    yieldedOpChannel.currentOp = op\n    return YieldedOp\n  }\n\n  [OpCodes.OP_WHILE](op: core.Primitive & { _op: OpCodes.OP_WHILE }) {\n    const check = op.effect_instruction_i0\n    const body = op.effect_instruction_i1\n    if (check()) {\n      this.pushStack(op)\n      return body()\n    } else {\n      return core.exitVoid\n    }\n  }\n\n  [OpCodes.OP_ITERATOR](op: core.Primitive & { _op: OpCodes.OP_ITERATOR }) {\n    return contOpSuccess[OpCodes.OP_ITERATOR](this, op, undefined)\n  }\n\n  [OpCodes.OP_COMMIT](op: core.Primitive & { _op: OpCodes.OP_COMMIT }) {\n    return internalCall(() => op.commit())\n  }\n\n  /**\n   * The main run-loop for evaluating effects.\n   *\n   * **NOTE**: This method must be invoked by the fiber itself.\n   */\n  runLoop(effect0: Effect.Effect<any, any, any>): Exit.Exit<any, any> | YieldedOp {\n    let cur: Effect.Effect<any, any, any> | YieldedOp = effect0\n    this.currentOpCount = 0\n\n    while (true) {\n      if ((this.currentRuntimeFlags & OpSupervision) !== 0) {\n        this.currentSupervisor.onEffect(this, cur)\n      }\n      if (this._queue.length > 0) {\n        cur = this.drainQueueWhileRunning(this.currentRuntimeFlags, cur)\n      }\n      if (!this._isYielding) {\n        this.currentOpCount += 1\n        const shouldYield = this.currentScheduler.shouldYield(this)\n        if (shouldYield !== false) {\n          this._isYielding = true\n          this.currentOpCount = 0\n          const oldCur = cur\n          cur = core.flatMap(core.yieldNow({ priority: shouldYield }), () => oldCur)\n        }\n      }\n      try {\n        // @ts-expect-error\n        cur = this.currentTracer.context(\n          () => {\n            if (_version !== (cur as core.Primitive)[core.EffectTypeId]._V) {\n              const level = this.getFiberRef(core.currentVersionMismatchErrorLogLevel)\n              if (level._tag === \"Some\") {\n                const effectVersion = (cur as core.Primitive)[core.EffectTypeId]._V\n                this.log(\n                  `Executing an Effect versioned ${effectVersion} with a Runtime of version ${version.getCurrentVersion()}, you may want to dedupe the effect dependencies, you can use the language service plugin to detect this at compile time: https://github.com/Effect-TS/language-service`,\n                  internalCause.empty,\n                  level\n                )\n              }\n            }\n            // @ts-expect-error\n            return this[(cur as core.Primitive)._op](cur as core.Primitive)\n          },\n          this\n        )\n\n        if (cur === YieldedOp) {\n          const op = yieldedOpChannel.currentOp!\n          if (\n            op._op === OpCodes.OP_YIELD ||\n            op._op === OpCodes.OP_ASYNC\n          ) {\n            return YieldedOp\n          }\n\n          yieldedOpChannel.currentOp = null\n          return (\n              op._op === OpCodes.OP_SUCCESS ||\n              op._op === OpCodes.OP_FAILURE\n            ) ?\n            op as unknown as Exit.Exit<A, E> :\n            core.exitFailCause(internalCause.die(op))\n        }\n      } catch (e) {\n        if (cur !== YieldedOp && !Predicate.hasProperty(cur, \"_op\") || !((cur as core.Primitive)._op in this)) {\n          cur = core.dieMessage(`Not a valid effect: ${Inspectable.toStringUnknown(cur)}`)\n        } else if (core.isInterruptedException(e)) {\n          cur = core.exitFailCause(\n            internalCause.sequential(internalCause.die(e), internalCause.interrupt(FiberId.none))\n          )\n        } else {\n          cur = core.die(e)\n        }\n      }\n    }\n  }\n\n  run = () => {\n    this.drainQueueOnCurrentThread()\n  }\n}\n\n// circular with Logger\n\n/** @internal */\nexport const currentMinimumLogLevel: FiberRef.FiberRef<LogLevel.LogLevel> = globalValue(\n  \"effect/FiberRef/currentMinimumLogLevel\",\n  () => core.fiberRefUnsafeMake<LogLevel.LogLevel>(LogLevel.fromLiteral(\"Info\"))\n)\n\n/** @internal */\nexport const loggerWithConsoleLog = <M, O>(self: Logger<M, O>): Logger<M, void> =>\n  internalLogger.makeLogger((opts) => {\n    const services = FiberRefs.getOrDefault(opts.context, defaultServices.currentServices)\n    Context.get(services, consoleTag).unsafe.log(self.log(opts))\n  })\n\n/** @internal */\nexport const loggerWithLeveledLog = <M, O>(self: Logger<M, O>): Logger<M, void> =>\n  internalLogger.makeLogger((opts) => {\n    const services = FiberRefs.getOrDefault(opts.context, defaultServices.currentServices)\n    const unsafeLogger = Context.get(services, consoleTag).unsafe\n    switch (opts.logLevel._tag) {\n      case \"Debug\":\n        return unsafeLogger.debug(self.log(opts))\n      case \"Info\":\n        return unsafeLogger.info(self.log(opts))\n      case \"Trace\":\n        return unsafeLogger.trace(self.log(opts))\n      case \"Warning\":\n        return unsafeLogger.warn(self.log(opts))\n      case \"Error\":\n      case \"Fatal\":\n        return unsafeLogger.error(self.log(opts))\n      default:\n        return unsafeLogger.log(self.log(opts))\n    }\n  })\n\n/** @internal */\nexport const loggerWithConsoleError = <M, O>(self: Logger<M, O>): Logger<M, void> =>\n  internalLogger.makeLogger((opts) => {\n    const services = FiberRefs.getOrDefault(opts.context, defaultServices.currentServices)\n    Context.get(services, consoleTag).unsafe.error(self.log(opts))\n  })\n\n/** @internal */\nexport const defaultLogger: Logger<unknown, void> = globalValue(\n  Symbol.for(\"effect/Logger/defaultLogger\"),\n  () => loggerWithConsoleLog(internalLogger.stringLogger)\n)\n\n/** @internal */\nexport const jsonLogger: Logger<unknown, void> = globalValue(\n  Symbol.for(\"effect/Logger/jsonLogger\"),\n  () => loggerWithConsoleLog(internalLogger.jsonLogger)\n)\n\n/** @internal */\nexport const logFmtLogger: Logger<unknown, void> = globalValue(\n  Symbol.for(\"effect/Logger/logFmtLogger\"),\n  () => loggerWithConsoleLog(internalLogger.logfmtLogger)\n)\n\n/** @internal */\nexport const prettyLogger: Logger<unknown, void> = globalValue(\n  Symbol.for(\"effect/Logger/prettyLogger\"),\n  () => internalLogger.prettyLoggerDefault\n)\n\n/** @internal */\nexport const structuredLogger: Logger<unknown, void> = globalValue(\n  Symbol.for(\"effect/Logger/structuredLogger\"),\n  () => loggerWithConsoleLog(internalLogger.structuredLogger)\n)\n\n/** @internal */\nexport const tracerLogger = globalValue(\n  Symbol.for(\"effect/Logger/tracerLogger\"),\n  () =>\n    internalLogger.makeLogger<unknown, void>(({\n      annotations,\n      cause,\n      context,\n      fiberId,\n      logLevel,\n      message\n    }) => {\n      const span = internalEffect.filterDisablePropagation(Context.getOption(\n        fiberRefs.getOrDefault(context, core.currentContext),\n        tracer.spanTag\n      ))\n\n      if (span._tag === \"None\" || span.value._tag === \"ExternalSpan\") {\n        return\n      }\n\n      const clockService = Context.unsafeGet(\n        fiberRefs.getOrDefault(context, defaultServices.currentServices),\n        clock.clockTag\n      )\n\n      const attributes: Record<string, unknown> = {}\n      for (const [key, value] of annotations) {\n        attributes[key] = value\n      }\n      attributes[\"effect.fiberId\"] = FiberId.threadName(fiberId)\n      attributes[\"effect.logLevel\"] = logLevel.label\n\n      if (cause !== null && cause._tag !== \"Empty\") {\n        attributes[\"effect.cause\"] = internalCause.pretty(cause, { renderErrorCause: true })\n      }\n\n      span.value.event(\n        Inspectable.toStringUnknown(Array.isArray(message) && message.length === 1 ? message[0] : message),\n        clockService.unsafeCurrentTimeNanos(),\n        attributes\n      )\n    })\n)\n\n/** @internal */\nexport const loggerWithSpanAnnotations = <Message, Output>(self: Logger<Message, Output>): Logger<Message, Output> =>\n  internalLogger.mapInputOptions(self, (options: Logger.Options<Message>) => {\n    const span = Option.flatMap(fiberRefs.get(options.context, core.currentContext), Context.getOption(tracer.spanTag))\n    if (span._tag === \"None\") {\n      return options\n    }\n    return {\n      ...options,\n      annotations: pipe(\n        options.annotations,\n        HashMap.set(\"effect.traceId\", span.value.traceId as unknown),\n        HashMap.set(\"effect.spanId\", span.value.spanId as unknown),\n        span.value._tag === \"Span\" ? HashMap.set(\"effect.spanName\", span.value.name as unknown) : identity\n      )\n    }\n  })\n\n/** @internal */\nexport const currentLoggers: FiberRef.FiberRef<\n  HashSet.HashSet<Logger<unknown, any>>\n> = globalValue(\n  Symbol.for(\"effect/FiberRef/currentLoggers\"),\n  () => core.fiberRefUnsafeMakeHashSet(HashSet.make(defaultLogger, tracerLogger))\n)\n\n/** @internal */\nexport const batchedLogger = dual<\n  <Output, R>(\n    window: Duration.DurationInput,\n    f: (messages: Array<NoInfer<Output>>) => Effect.Effect<void, never, R>\n  ) => <Message>(\n    self: Logger<Message, Output>\n  ) => Effect.Effect<Logger<Message, void>, never, Scope.Scope | R>,\n  <Message, Output, R>(\n    self: Logger<Message, Output>,\n    window: Duration.DurationInput,\n    f: (messages: Array<NoInfer<Output>>) => Effect.Effect<void, never, R>\n  ) => Effect.Effect<Logger<Message, void>, never, Scope.Scope | R>\n>(3, <Message, Output, R>(\n  self: Logger<Message, Output>,\n  window: Duration.DurationInput,\n  f: (messages: Array<NoInfer<Output>>) => Effect.Effect<void, never, R>\n): Effect.Effect<Logger<Message, void>, never, Scope.Scope | R> =>\n  core.flatMap(scope, (scope) => {\n    let buffer: Array<Output> = []\n    const flush = core.suspend(() => {\n      if (buffer.length === 0) {\n        return core.void\n      }\n      const arr = buffer\n      buffer = []\n      return f(arr)\n    })\n\n    return core.uninterruptibleMask((restore) =>\n      pipe(\n        internalEffect.sleep(window),\n        core.zipRight(flush),\n        internalEffect.forever,\n        restore,\n        forkDaemon,\n        core.flatMap((fiber) => core.scopeAddFinalizer(scope, core.interruptFiber(fiber))),\n        core.zipRight(addFinalizer(() => flush)),\n        core.as(\n          internalLogger.makeLogger((options) => {\n            buffer.push(self.log(options))\n          })\n        )\n      )\n    )\n  }))\n\nexport const annotateLogsScoped: {\n  (key: string, value: unknown): Effect.Effect<void, never, Scope.Scope>\n  (values: Record<string, unknown>): Effect.Effect<void, never, Scope.Scope>\n} = function() {\n  if (typeof arguments[0] === \"string\") {\n    return fiberRefLocallyScopedWith(\n      core.currentLogAnnotations,\n      HashMap.set(arguments[0], arguments[1])\n    )\n  }\n  const entries = Object.entries(arguments[0])\n  return fiberRefLocallyScopedWith(\n    core.currentLogAnnotations,\n    HashMap.mutate((annotations) => {\n      for (let i = 0; i < entries.length; i++) {\n        const [key, value] = entries[i]\n        HashMap.set(annotations, key, value)\n      }\n      return annotations\n    })\n  )\n}\n\n/** @internal */\nexport const whenLogLevel = dual<\n  (\n    level: LogLevel.LogLevel | LogLevel.Literal\n  ) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<Option.Option<A>, E, R>,\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    level: LogLevel.LogLevel | LogLevel.Literal\n  ) => Effect.Effect<Option.Option<A>, E, R>\n>(2, (effect, level) => {\n  const requiredLogLevel = typeof level === \"string\" ? LogLevel.fromLiteral(level) : level\n\n  return core.withFiberRuntime((fiberState) => {\n    const minimumLogLevel = fiberState.getFiberRef(currentMinimumLogLevel)\n\n    // Imitate the behaviour of `FiberRuntime.log`\n    if (LogLevel.greaterThan(minimumLogLevel, requiredLogLevel)) {\n      return core.succeed(Option.none())\n    }\n\n    return core.map(effect, Option.some)\n  })\n})\n\n// circular with Effect\n\n/* @internal */\nexport const acquireRelease: {\n  <A, X, R2>(\n    release: (a: A, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<X, never, R2>\n  ): <E, R>(acquire: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R2 | R | Scope.Scope>\n  <A, E, R, X, R2>(\n    acquire: Effect.Effect<A, E, R>,\n    release: (a: A, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<X, never, R2>\n  ): Effect.Effect<A, E, R2 | R | Scope.Scope>\n} = dual((args) => core.isEffect(args[0]), (acquire, release) =>\n  core.uninterruptible(\n    core.tap(acquire, (a) => addFinalizer((exit) => release(a, exit)))\n  ))\n\n/* @internal */\nexport const acquireReleaseInterruptible: {\n  <X, R2>(\n    release: (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<X, never, R2>\n  ): <A, E, R>(acquire: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Scope.Scope | R2 | R>\n  <A, E, R, X, R2>(\n    acquire: Effect.Effect<A, E, R>,\n    release: (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<X, never, R2>\n  ): Effect.Effect<A, E, Scope.Scope | R2 | R>\n} = dual((args) => core.isEffect(args[0]), (acquire, release) =>\n  ensuring(\n    acquire,\n    addFinalizer((exit) => release(exit))\n  ))\n\n/* @internal */\nexport const addFinalizer = <X, R>(\n  finalizer: (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<X, never, R>\n): Effect.Effect<void, never, R | Scope.Scope> =>\n  core.withFiberRuntime(\n    (runtime) => {\n      const acquireRefs = runtime.getFiberRefs()\n      const acquireFlags = runtimeFlags_.disable(runtime.currentRuntimeFlags, runtimeFlags_.Interruption)\n      return core.flatMap(scope, (scope) =>\n        core.scopeAddFinalizerExit(scope, (exit) =>\n          core.withFiberRuntime((runtimeFinalizer) => {\n            const preRefs = runtimeFinalizer.getFiberRefs()\n            const preFlags = runtimeFinalizer.currentRuntimeFlags\n            const patchRefs = FiberRefsPatch.diff(preRefs, acquireRefs)\n            const patchFlags = runtimeFlags_.diff(preFlags, acquireFlags)\n            const inverseRefs = FiberRefsPatch.diff(acquireRefs, preRefs)\n            runtimeFinalizer.setFiberRefs(\n              FiberRefsPatch.patch(patchRefs, runtimeFinalizer.id(), acquireRefs)\n            )\n\n            return ensuring(\n              core.withRuntimeFlags(finalizer(exit) as Effect.Effect<X>, patchFlags),\n              core.sync(() => {\n                runtimeFinalizer.setFiberRefs(\n                  FiberRefsPatch.patch(inverseRefs, runtimeFinalizer.id(), runtimeFinalizer.getFiberRefs())\n                )\n              })\n            )\n          })))\n    }\n  )\n\n/* @internal */\nexport const daemonChildren = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => {\n  const forkScope = core.fiberRefLocally(core.currentForkScopeOverride, Option.some(fiberScope.globalScope))\n  return forkScope(self)\n}\n\n/** @internal */\nconst _existsParFound = Symbol.for(\"effect/Effect/existsPar/found\")\n\n/* @internal */\nexport const exists: {\n  <A, E, R>(predicate: (a: A, i: number) => Effect.Effect<boolean, E, R>, options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }): (elements: Iterable<A>) => Effect.Effect<boolean, E, R>\n  <A, E, R>(elements: Iterable<A>, predicate: (a: A, i: number) => Effect.Effect<boolean, E, R>, options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }): Effect.Effect<boolean, E, R>\n} = dual(\n  (args) => Predicate.isIterable(args[0]) && !core.isEffect(args[0]),\n  <A, E, R>(elements: Iterable<A>, predicate: (a: A, i: number) => Effect.Effect<boolean, E, R>, options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n  }) =>\n    concurrency.matchSimple(\n      options?.concurrency,\n      () => core.suspend(() => existsLoop(elements[Symbol.iterator](), 0, predicate)),\n      () =>\n        core.matchEffect(\n          forEach(\n            elements,\n            (a, i) => core.if_(predicate(a, i), { onTrue: () => core.fail(_existsParFound), onFalse: () => core.void }),\n            options\n          ),\n          {\n            onFailure: (e) => e === _existsParFound ? core.succeed(true) : core.fail(e),\n            onSuccess: () => core.succeed(false)\n          }\n        )\n    )\n)\n\nconst existsLoop = <A, E, R>(\n  iterator: Iterator<A>,\n  index: number,\n  f: (a: A, i: number) => Effect.Effect<boolean, E, R>\n): Effect.Effect<boolean, E, R> => {\n  const next = iterator.next()\n  if (next.done) {\n    return core.succeed(false)\n  }\n  return core.flatMap(\n    f(next.value, index),\n    (b) => b ? core.succeed(b) : existsLoop(iterator, index + 1, f)\n  )\n}\n\n/* @internal */\nexport const filter = dual<\n  <A, E, R>(\n    predicate: (a: NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly negate?: boolean | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => (elements: Iterable<A>) => Effect.Effect<Array<A>, E, R>,\n  <A, E, R>(elements: Iterable<A>, predicate: (a: NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>, options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly negate?: boolean | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }) => Effect.Effect<Array<A>, E, R>\n>(\n  (args) => Predicate.isIterable(args[0]) && !core.isEffect(args[0]),\n  <A, E, R>(elements: Iterable<A>, predicate: (a: NoInfer<A>, i: number) => Effect.Effect<boolean, E, R>, options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly negate?: boolean | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }) => {\n    const predicate_ = options?.negate ? (a: A, i: number) => core.map(predicate(a, i), Boolean.not) : predicate\n    return concurrency.matchSimple(\n      options?.concurrency,\n      () =>\n        core.suspend(() =>\n          RA.fromIterable(elements).reduceRight(\n            (effect, a, i) =>\n              core.zipWith(\n                effect,\n                core.suspend(() => predicate_(a, i)),\n                (list, b) => b ? [a, ...list] : list\n              ),\n            core.sync(() => new Array<A>()) as Effect.Effect<Array<A>, E, R>\n          )\n        ),\n      () =>\n        core.map(\n          forEach(\n            elements,\n            (a, i) => core.map(predicate_(a, i), (b) => (b ? Option.some(a) : Option.none())),\n            options\n          ),\n          RA.getSomes\n        )\n    )\n  }\n)\n\n// === all\n\nconst allResolveInput = (\n  input: Iterable<Effect.Effect<any, any, any>> | Record<string, Effect.Effect<any, any, any>>\n): [Iterable<Effect.Effect<any, any, any>>, Option.Option<(as: ReadonlyArray<any>) => any>] => {\n  if (Array.isArray(input) || Predicate.isIterable(input)) {\n    return [input, Option.none()]\n  }\n  const keys = Object.keys(input)\n  const size = keys.length\n  return [\n    keys.map((k) => input[k]),\n    Option.some((values: ReadonlyArray<any>) => {\n      const res = {}\n      for (let i = 0; i < size; i++) {\n        ;(res as any)[keys[i]] = values[i]\n      }\n      return res\n    })\n  ]\n}\n\nconst allValidate = (\n  effects: Iterable<Effect.Effect<any, any, any>>,\n  reconcile: Option.Option<(as: ReadonlyArray<any>) => any>,\n  options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly discard?: boolean | undefined\n    readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }\n) => {\n  const eitherEffects: Array<Effect.Effect<Either.Either<unknown, unknown>, never, unknown>> = []\n  for (const effect of effects) {\n    eitherEffects.push(core.either(effect))\n  }\n  return core.flatMap(\n    forEach(eitherEffects, identity, {\n      concurrency: options?.concurrency,\n      batching: options?.batching,\n      concurrentFinalizers: options?.concurrentFinalizers\n    }),\n    (eithers) => {\n      const none = Option.none()\n      const size = eithers.length\n      const errors: Array<unknown> = new Array(size)\n      const successes: Array<unknown> = new Array(size)\n      let errored = false\n      for (let i = 0; i < size; i++) {\n        const either = eithers[i] as Either.Either<unknown, unknown>\n        if (either._tag === \"Left\") {\n          errors[i] = Option.some(either.left)\n          errored = true\n        } else {\n          successes[i] = either.right\n          errors[i] = none\n        }\n      }\n      if (errored) {\n        return reconcile._tag === \"Some\" ?\n          core.fail(reconcile.value(errors)) :\n          core.fail(errors)\n      } else if (options?.discard) {\n        return core.void\n      }\n      return reconcile._tag === \"Some\" ?\n        core.succeed(reconcile.value(successes)) :\n        core.succeed(successes)\n    }\n  )\n}\n\nconst allEither = (\n  effects: Iterable<Effect.Effect<any, any, any>>,\n  reconcile: Option.Option<(as: ReadonlyArray<any>) => any>,\n  options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly discard?: boolean | undefined\n    readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }\n) => {\n  const eitherEffects: Array<Effect.Effect<Either.Either<unknown, unknown>, never, unknown>> = []\n  for (const effect of effects) {\n    eitherEffects.push(core.either(effect))\n  }\n\n  if (options?.discard) {\n    return forEach(eitherEffects, identity, {\n      concurrency: options?.concurrency,\n      batching: options?.batching,\n      discard: true,\n      concurrentFinalizers: options?.concurrentFinalizers\n    })\n  }\n\n  return core.map(\n    forEach(eitherEffects, identity, {\n      concurrency: options?.concurrency,\n      batching: options?.batching,\n      concurrentFinalizers: options?.concurrentFinalizers\n    }),\n    (eithers) =>\n      reconcile._tag === \"Some\" ?\n        reconcile.value(eithers) :\n        eithers\n  )\n}\n\n/* @internal */\nexport const all = <\n  const Arg extends Iterable<Effect.Effect<any, any, any>> | Record<string, Effect.Effect<any, any, any>>,\n  O extends NoExcessProperties<{\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly discard?: boolean | undefined\n    readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }, O>\n>(\n  arg: Arg,\n  options?: O\n): Effect.All.Return<Arg, O> => {\n  const [effects, reconcile] = allResolveInput(arg)\n\n  if (options?.mode === \"validate\") {\n    return allValidate(effects, reconcile, options) as any\n  } else if (options?.mode === \"either\") {\n    return allEither(effects, reconcile, options) as any\n  }\n\n  return options?.discard !== true && reconcile._tag === \"Some\"\n    ? core.map(\n      forEach(effects, identity, options as any),\n      reconcile.value\n    ) as any\n    : forEach(effects, identity, options as any) as any\n}\n\n/* @internal */\nexport const allWith = <\n  O extends NoExcessProperties<{\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly discard?: boolean | undefined\n    readonly mode?: \"default\" | \"validate\" | \"either\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }, O>\n>(options?: O) =>\n<const Arg extends Iterable<Effect.Effect<any, any, any>> | Record<string, Effect.Effect<any, any, any>>>(\n  arg: Arg\n): Effect.All.Return<Arg, O> => all(arg, options)\n\n/* @internal */\nexport const allSuccesses = <Eff extends Effect.Effect<any, any, any>>(\n  elements: Iterable<Eff>,\n  options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }\n): Effect.Effect<Array<Effect.Effect.Success<Eff>>, never, Effect.Effect.Context<Eff>> =>\n  core.map(\n    all(RA.fromIterable(elements).map(core.exit), options),\n    RA.filterMap((exit) => core.exitIsSuccess(exit) ? Option.some(exit.effect_instruction_i0) : Option.none())\n  )\n\n/* @internal */\nexport const replicate = dual<\n  (n: number) => <A, E, R>(self: Effect.Effect<A, E, R>) => Array<Effect.Effect<A, E, R>>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, n: number) => Array<Effect.Effect<A, E, R>>\n>(2, (self, n) => Array.from({ length: n }, () => self))\n\n/* @internal */\nexport const replicateEffect: {\n  (\n    n: number,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Array<A>, E, R>\n  (\n    n: number,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard: true\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<void, E, R>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    n: number,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect.Effect<Array<A>, E, R>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    n: number,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard: true\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect.Effect<void, E, R>\n} = dual(\n  (args) => core.isEffect(args[0]),\n  (self, n, options) => all(replicate(self, n), options)\n)\n\n/* @internal */\nexport const forEach: {\n  <B, E, R, S extends Iterable<any>>(\n    f: (a: RA.ReadonlyArray.Infer<S>, i: number) => Effect.Effect<B, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    } | undefined\n  ): (\n    self: S\n  ) => Effect.Effect<RA.ReadonlyArray.With<S, B>, E, R>\n  <A, B, E, R>(\n    f: (a: A, i: number) => Effect.Effect<B, E, R>,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard: true\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): (self: Iterable<A>) => Effect.Effect<void, E, R>\n  <A, B, E, R>(\n    self: RA.NonEmptyReadonlyArray<A>,\n    f: (a: A, i: number) => Effect.Effect<B, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    } | undefined\n  ): Effect.Effect<RA.NonEmptyArray<B>, E, R>\n  <A, B, E, R>(\n    self: Iterable<A>,\n    f: (a: A, i: number) => Effect.Effect<B, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard?: false | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    } | undefined\n  ): Effect.Effect<Array<B>, E, R>\n  <A, B, E, R>(\n    self: Iterable<A>,\n    f: (a: A, i: number) => Effect.Effect<B, E, R>,\n    options: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly discard: true\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect.Effect<void, E, R>\n} = dual((args) => Predicate.isIterable(args[0]), <A, R, E, B>(\n  self: Iterable<A>,\n  f: (a: A, i: number) => Effect.Effect<B, E, R>,\n  options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly discard?: boolean | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }\n) =>\n  core.withFiberRuntime<A | void, E, R>((r) => {\n    const isRequestBatchingEnabled = options?.batching === true ||\n      (options?.batching === \"inherit\" && r.getFiberRef(core.currentRequestBatching))\n\n    if (options?.discard) {\n      return concurrency.match(\n        options.concurrency,\n        () =>\n          finalizersMaskInternal(ExecutionStrategy.sequential, options?.concurrentFinalizers)((restore) =>\n            isRequestBatchingEnabled\n              ? forEachConcurrentDiscard(self, (a, i) => restore(f(a, i)), true, false, 1)\n              : core.forEachSequentialDiscard(self, (a, i) => restore(f(a, i)))\n          ),\n        () =>\n          finalizersMaskInternal(ExecutionStrategy.parallel, options?.concurrentFinalizers)((restore) =>\n            forEachConcurrentDiscard(self, (a, i) => restore(f(a, i)), isRequestBatchingEnabled, false)\n          ),\n        (n) =>\n          finalizersMaskInternal(ExecutionStrategy.parallelN(n), options?.concurrentFinalizers)((restore) =>\n            forEachConcurrentDiscard(self, (a, i) => restore(f(a, i)), isRequestBatchingEnabled, false, n)\n          )\n      )\n    }\n\n    return concurrency.match(\n      options?.concurrency,\n      () =>\n        finalizersMaskInternal(ExecutionStrategy.sequential, options?.concurrentFinalizers)((restore) =>\n          isRequestBatchingEnabled\n            ? forEachParN(self, 1, (a, i) => restore(f(a, i)), true)\n            : core.forEachSequential(self, (a, i) => restore(f(a, i)))\n        ),\n      () =>\n        finalizersMaskInternal(ExecutionStrategy.parallel, options?.concurrentFinalizers)((restore) =>\n          forEachParUnbounded(self, (a, i) => restore(f(a, i)), isRequestBatchingEnabled)\n        ),\n      (n) =>\n        finalizersMaskInternal(ExecutionStrategy.parallelN(n), options?.concurrentFinalizers)((restore) =>\n          forEachParN(self, n, (a, i) => restore(f(a, i)), isRequestBatchingEnabled)\n        )\n    )\n  }))\n\n/* @internal */\nexport const forEachParUnbounded = <A, B, E, R>(\n  self: Iterable<A>,\n  f: (a: A, i: number) => Effect.Effect<B, E, R>,\n  batching: boolean\n): Effect.Effect<Array<B>, E, R> =>\n  core.suspend(() => {\n    const as = RA.fromIterable(self)\n    const array = new Array<B>(as.length)\n    const fn = (a: A, i: number) => core.flatMap(f(a, i), (b) => core.sync(() => array[i] = b))\n    return core.zipRight(forEachConcurrentDiscard(as, fn, batching, false), core.succeed(array))\n  })\n\n/** @internal */\nexport const forEachConcurrentDiscard = <A, X, E, R>(\n  self: Iterable<A>,\n  f: (a: A, i: number) => Effect.Effect<X, E, R>,\n  batching: boolean,\n  processAll: boolean,\n  n?: number\n): Effect.Effect<void, E, R> =>\n  core.uninterruptibleMask((restore) =>\n    core.transplant((graft) =>\n      core.withFiberRuntime<void, E, R>((parent) => {\n        let todos = Array.from(self).reverse()\n        let target = todos.length\n        if (target === 0) {\n          return core.void\n        }\n        let counter = 0\n        let interrupted = false\n        const fibersCount = n ? Math.min(todos.length, n) : todos.length\n        const fibers = new Set<FiberRuntime<Exit.Exit<X, E> | Effect.Blocked<X, E>>>()\n        const results = new Array()\n        const interruptAll = () =>\n          fibers.forEach((fiber) => {\n            fiber.currentScheduler.scheduleTask(\n              () => {\n                fiber.unsafeInterruptAsFork(parent.id())\n              },\n              0,\n              fiber\n            )\n          })\n        const startOrder = new Array<FiberRuntime<Exit.Exit<X, E> | Effect.Blocked<X, E>>>()\n        const joinOrder = new Array<FiberRuntime<Exit.Exit<X, E> | Effect.Blocked<X, E>>>()\n        const residual = new Array<core.Blocked>()\n        const collectExits = () => {\n          const exits: Array<Exit.Exit<any, E>> = results\n            .filter(({ exit }) => exit._tag === \"Failure\")\n            .sort((a, b) => a.index < b.index ? -1 : a.index === b.index ? 0 : 1)\n            .map(({ exit }) => exit)\n          if (exits.length === 0) {\n            exits.push(core.exitVoid)\n          }\n          return exits\n        }\n        const runFiber = <A, E, R>(eff: Effect.Effect<A, E, R>, interruptImmediately = false) => {\n          const runnable = core.uninterruptible(graft(eff))\n          const fiber = unsafeForkUnstarted(\n            runnable,\n            parent,\n            parent.currentRuntimeFlags,\n            fiberScope.globalScope\n          )\n          parent.currentScheduler.scheduleTask(\n            () => {\n              if (interruptImmediately) {\n                fiber.unsafeInterruptAsFork(parent.id())\n              }\n              fiber.resume(runnable)\n            },\n            0,\n            fiber\n          )\n          return fiber\n        }\n        const onInterruptSignal = () => {\n          if (!processAll) {\n            target -= todos.length\n            todos = []\n          }\n          interrupted = true\n          interruptAll()\n        }\n        const stepOrExit = batching ? core.step : core.exit\n        const processingFiber = runFiber(\n          core.async<any, any, any>((resume) => {\n            const pushResult = <X, E>(res: Exit.Exit<X, E> | Effect.Blocked<X, E>, index: number) => {\n              if (res._op === \"Blocked\") {\n                residual.push(res as core.Blocked)\n              } else {\n                results.push({ index, exit: res })\n                if (res._op === \"Failure\" && !interrupted) {\n                  onInterruptSignal()\n                }\n              }\n            }\n            const next = () => {\n              if (todos.length > 0) {\n                const a = todos.pop()!\n                let index = counter++\n                const returnNextElement = () => {\n                  const a = todos.pop()!\n                  index = counter++\n                  return core.flatMap(core.yieldNow(), () =>\n                    core.flatMap(\n                      stepOrExit(restore(f(a, index))),\n                      onRes\n                    ))\n                }\n                const onRes = (\n                  res: Exit.Exit<X, E> | Effect.Blocked<X, E>\n                ): Effect.Effect<Exit.Exit<X, E> | Effect.Blocked<X, E>, never, R> => {\n                  if (todos.length > 0) {\n                    pushResult(res, index)\n                    if (todos.length > 0) {\n                      return returnNextElement()\n                    }\n                  }\n                  return core.succeed(res)\n                }\n                const todo = core.flatMap(\n                  stepOrExit(restore(f(a, index))),\n                  onRes\n                )\n                const fiber = runFiber(todo)\n                startOrder.push(fiber)\n                fibers.add(fiber)\n                if (interrupted) {\n                  fiber.currentScheduler.scheduleTask(\n                    () => {\n                      fiber.unsafeInterruptAsFork(parent.id())\n                    },\n                    0,\n                    fiber\n                  )\n                }\n                fiber.addObserver((wrapped) => {\n                  let exit: Exit.Exit<any, any> | core.Blocked\n                  if (wrapped._op === \"Failure\") {\n                    exit = wrapped\n                  } else {\n                    exit = wrapped.effect_instruction_i0 as any\n                  }\n                  joinOrder.push(fiber)\n                  fibers.delete(fiber)\n                  pushResult(exit, index)\n                  if (results.length === target) {\n                    resume(core.succeed(Option.getOrElse(\n                      core.exitCollectAll(collectExits(), { parallel: true }),\n                      () => core.exitVoid\n                    )))\n                  } else if (residual.length + results.length === target) {\n                    const exits = collectExits()\n                    const requests = residual.map((blocked) => blocked.effect_instruction_i0).reduce(RequestBlock_.par)\n                    resume(core.succeed(core.blocked(\n                      requests,\n                      forEachConcurrentDiscard(\n                        [\n                          Option.getOrElse(\n                            core.exitCollectAll(exits, { parallel: true }),\n                            () => core.exitVoid\n                          ),\n                          ...residual.map((blocked) => blocked.effect_instruction_i1)\n                        ],\n                        (i) => i,\n                        batching,\n                        true,\n                        n\n                      )\n                    )))\n                  } else {\n                    next()\n                  }\n                })\n              }\n            }\n            for (let i = 0; i < fibersCount; i++) {\n              next()\n            }\n          })\n        )\n        return core.asVoid(\n          core.onExit(\n            core.flatten(restore(internalFiber.join(processingFiber))),\n            core.exitMatch({\n              onFailure: (cause) => {\n                onInterruptSignal()\n                const target = residual.length + 1\n                const concurrency = Math.min(typeof n === \"number\" ? n : residual.length, residual.length)\n                const toPop = Array.from(residual)\n                return core.async<any, any>((cb) => {\n                  const exits: Array<Exit.Exit<any, any>> = []\n                  let count = 0\n                  let index = 0\n                  const check = (index: number, hitNext: boolean) => (exit: Exit.Exit<any, any>) => {\n                    exits[index] = exit\n                    count++\n                    if (count === target) {\n                      cb(core.exitSucceed(core.exitFailCause(cause)))\n                    }\n                    if (toPop.length > 0 && hitNext) {\n                      next()\n                    }\n                  }\n                  const next = () => {\n                    runFiber(toPop.pop()!, true).addObserver(check(index, true))\n                    index++\n                  }\n                  processingFiber.addObserver(check(index, false))\n                  index++\n                  for (let i = 0; i < concurrency; i++) {\n                    next()\n                  }\n                }) as any\n              },\n              onSuccess: () => core.forEachSequential(joinOrder, (f) => f.inheritAll)\n            })\n          )\n        )\n      })\n    )\n  )\n\n/* @internal */\nexport const forEachParN = <A, B, E, R>(\n  self: Iterable<A>,\n  n: number,\n  f: (a: A, i: number) => Effect.Effect<B, E, R>,\n  batching: boolean\n): Effect.Effect<Array<B>, E, R> =>\n  core.suspend(() => {\n    const as = RA.fromIterable(self)\n    const array = new Array<B>(as.length)\n    const fn = (a: A, i: number) => core.map(f(a, i), (b) => array[i] = b)\n    return core.zipRight(forEachConcurrentDiscard(as, fn, batching, false, n), core.succeed(array))\n  })\n\n/* @internal */\nexport const fork = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R> =>\n  core.withFiberRuntime((state, status) => core.succeed(unsafeFork(self, state, status.runtimeFlags)))\n\n/* @internal */\nexport const forkDaemon = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R> =>\n  forkWithScopeOverride(self, fiberScope.globalScope)\n\n/* @internal */\nexport const forkWithErrorHandler = dual<\n  <E, X>(\n    handler: (e: E) => Effect.Effect<X>\n  ) => <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R>,\n  <A, E, R, X>(\n    self: Effect.Effect<A, E, R>,\n    handler: (e: E) => Effect.Effect<X>\n  ) => Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R>\n>(2, (self, handler) =>\n  fork(core.onError(self, (cause) => {\n    const either = internalCause.failureOrCause(cause)\n    switch (either._tag) {\n      case \"Left\":\n        return handler(either.left)\n      case \"Right\":\n        return core.failCause(either.right)\n    }\n  })))\n\n/** @internal */\nexport const unsafeFork = <A, E, R, E2, B>(\n  effect: Effect.Effect<A, E, R>,\n  parentFiber: FiberRuntime<B, E2>,\n  parentRuntimeFlags: RuntimeFlags.RuntimeFlags,\n  overrideScope: fiberScope.FiberScope | null = null\n): FiberRuntime<A, E> => {\n  const childFiber = unsafeMakeChildFiber(effect, parentFiber, parentRuntimeFlags, overrideScope)\n  childFiber.resume(effect)\n  return childFiber\n}\n\n/** @internal */\nexport const unsafeForkUnstarted = <A, E, R, E2, B>(\n  effect: Effect.Effect<A, E, R>,\n  parentFiber: FiberRuntime<B, E2>,\n  parentRuntimeFlags: RuntimeFlags.RuntimeFlags,\n  overrideScope: fiberScope.FiberScope | null = null\n): FiberRuntime<A, E> => {\n  const childFiber = unsafeMakeChildFiber(effect, parentFiber, parentRuntimeFlags, overrideScope)\n  return childFiber\n}\n\n/** @internal */\nexport const unsafeMakeChildFiber = <A, E, R, E2, B>(\n  effect: Effect.Effect<A, E, R>,\n  parentFiber: FiberRuntime<B, E2>,\n  parentRuntimeFlags: RuntimeFlags.RuntimeFlags,\n  overrideScope: fiberScope.FiberScope | null = null\n): FiberRuntime<A, E> => {\n  const childId = FiberId.unsafeMake()\n  const parentFiberRefs = parentFiber.getFiberRefs()\n  const childFiberRefs = fiberRefs.forkAs(parentFiberRefs, childId)\n  const childFiber = new FiberRuntime<A, E>(childId, childFiberRefs, parentRuntimeFlags)\n  const childContext = fiberRefs.getOrDefault(\n    childFiberRefs,\n    core.currentContext as unknown as FiberRef.FiberRef<Context.Context<R>>\n  )\n  const supervisor = childFiber.currentSupervisor\n\n  supervisor.onStart(\n    childContext,\n    effect,\n    Option.some(parentFiber),\n    childFiber\n  )\n\n  childFiber.addObserver((exit) => supervisor.onEnd(exit, childFiber))\n\n  const parentScope = overrideScope !== null ? overrideScope : pipe(\n    parentFiber.getFiberRef(core.currentForkScopeOverride),\n    Option.getOrElse(() => parentFiber.scope())\n  )\n\n  parentScope.add(parentRuntimeFlags, childFiber)\n\n  return childFiber\n}\n\n/* @internal */\nconst forkWithScopeOverride = <A, E, R>(\n  self: Effect.Effect<A, E, R>,\n  scopeOverride: fiberScope.FiberScope\n): Effect.Effect<Fiber.RuntimeFiber<A, E>, never, R> =>\n  core.withFiberRuntime((parentFiber, parentStatus) =>\n    core.succeed(unsafeFork(self, parentFiber, parentStatus.runtimeFlags, scopeOverride))\n  )\n\n/* @internal */\nexport const mergeAll = dual<\n  <Z, Eff extends Effect.Effect<any, any, any>>(\n    zero: Z,\n    f: (z: Z, a: Effect.Effect.Success<Eff>, i: number) => Z,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => (elements: Iterable<Eff>) => Effect.Effect<Z, Effect.Effect.Error<Eff>, Effect.Effect.Context<Eff>>,\n  <Eff extends Effect.Effect<any, any, any>, Z>(\n    elements: Iterable<Eff>,\n    zero: Z,\n    f: (z: Z, a: Effect.Effect.Success<Eff>, i: number) => Z,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => Effect.Effect<Z, Effect.Effect.Error<Eff>, Effect.Effect.Context<Eff>>\n>(\n  (args) => Predicate.isFunction(args[2]),\n  <A, E, R, Z>(elements: Iterable<Effect.Effect<A, E, R>>, zero: Z, f: (z: Z, a: A, i: number) => Z, options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }) =>\n    concurrency.matchSimple(\n      options?.concurrency,\n      () =>\n        RA.fromIterable(elements).reduce(\n          (acc, a, i) => core.zipWith(acc, a, (acc, a) => f(acc, a, i)),\n          core.succeed(zero) as Effect.Effect<Z, E, R>\n        ),\n      () =>\n        core.flatMap(Ref.make(zero), (acc) =>\n          core.flatMap(\n            forEach(\n              elements,\n              (effect, i) => core.flatMap(effect, (a) => Ref.update(acc, (b) => f(b, a, i))),\n              options\n            ),\n            () => Ref.get(acc)\n          ))\n    )\n)\n\n/* @internal */\nexport const partition = dual<\n  <A, B, E, R>(\n    f: (a: A, i: number) => Effect.Effect<B, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => (elements: Iterable<A>) => Effect.Effect<[excluded: Array<E>, satisfying: Array<B>], never, R>,\n  <A, B, E, R>(\n    elements: Iterable<A>,\n    f: (a: A, i: number) => Effect.Effect<B, E, R>,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => Effect.Effect<[excluded: Array<E>, satisfying: Array<B>], never, R>\n>((args) => Predicate.isIterable(args[0]), (elements, f, options) =>\n  pipe(\n    forEach(elements, (a, i) => core.either(f(a, i)), options),\n    core.map((chunk) => core.partitionMap(chunk, identity))\n  ))\n\n/* @internal */\nexport const validateAll = dual<\n  {\n    <A, B, E, R>(\n      f: (a: A, i: number) => Effect.Effect<B, E, R>,\n      options?: {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly discard?: false | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n    ): (elements: Iterable<A>) => Effect.Effect<Array<B>, RA.NonEmptyArray<E>, R>\n    <A, B, E, R>(\n      f: (a: A, i: number) => Effect.Effect<B, E, R>,\n      options: {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly discard: true\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n    ): (elements: Iterable<A>) => Effect.Effect<void, RA.NonEmptyArray<E>, R>\n  },\n  {\n    <A, B, E, R>(\n      elements: Iterable<A>,\n      f: (a: A, i: number) => Effect.Effect<B, E, R>,\n      options?: {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly discard?: false | undefined\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n    ): Effect.Effect<Array<B>, RA.NonEmptyArray<E>, R>\n    <A, B, E, R>(\n      elements: Iterable<A>,\n      f: (a: A, i: number) => Effect.Effect<B, E, R>,\n      options: {\n        readonly concurrency?: Concurrency | undefined\n        readonly batching?: boolean | \"inherit\" | undefined\n        readonly discard: true\n        readonly concurrentFinalizers?: boolean | undefined\n      }\n    ): Effect.Effect<void, RA.NonEmptyArray<E>, R>\n  }\n>(\n  (args) => Predicate.isIterable(args[0]),\n  <A, B, E, R>(elements: Iterable<A>, f: (a: A, i: number) => Effect.Effect<B, E, R>, options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly discard?: boolean | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }): Effect.Effect<any, RA.NonEmptyArray<E>, R> =>\n    core.flatMap(\n      partition(elements, f, {\n        concurrency: options?.concurrency,\n        batching: options?.batching,\n        concurrentFinalizers: options?.concurrentFinalizers\n      }),\n      ([es, bs]) =>\n        RA.isNonEmptyArray(es)\n          ? core.fail(es)\n          : options?.discard\n          ? core.void\n          : core.succeed(bs)\n    )\n)\n\n/* @internal */\nexport const raceAll: <Eff extends Effect.Effect<any, any, any>>(\n  all: Iterable<Eff>\n) => Effect.Effect<Effect.Effect.Success<Eff>, Effect.Effect.Error<Eff>, Effect.Effect.Context<Eff>> = <\n  A,\n  E,\n  R\n>(all: Iterable<Effect.Effect<A, E, R>>): Effect.Effect<A, E, R> =>\n  core.withFiberRuntime((state, status) =>\n    core.async<A, E, R>((resume) => {\n      const fibers = new Set<FiberRuntime<A, E>>()\n      let winner: FiberRuntime<A, E> | undefined\n      let failures: Cause.Cause<E> = internalCause.empty\n      const interruptAll = () => {\n        for (const fiber of fibers) {\n          fiber.unsafeInterruptAsFork(state.id())\n        }\n      }\n      let latch = false\n      let empty = true\n      for (const self of all) {\n        empty = false\n        const fiber = unsafeFork(\n          core.interruptible(self),\n          state,\n          status.runtimeFlags\n        )\n        fibers.add(fiber)\n        fiber.addObserver((exit) => {\n          fibers.delete(fiber)\n          if (!winner) {\n            if (exit._tag === \"Success\") {\n              latch = true\n              winner = fiber\n              failures = internalCause.empty\n              interruptAll()\n            } else {\n              failures = internalCause.parallel(exit.cause, failures)\n            }\n          }\n          if (latch && fibers.size === 0) {\n            resume(\n              winner ? core.zipRight(internalFiber.inheritAll(winner), winner.unsafePoll()!) : core.failCause(failures)\n            )\n          }\n        })\n        if (winner) break\n      }\n      if (empty) {\n        return resume(core.dieSync(() => new core.IllegalArgumentException(`Received an empty collection of effects`)))\n      }\n      latch = true\n      return internalFiber.interruptAllAs(fibers, state.id())\n    })\n  )\n\n/* @internal */\nexport const reduceEffect = dual<\n  <Z, E, R, Eff extends Effect.Effect<any, any, any>>(\n    zero: Effect.Effect<Z, E, R>,\n    f: (z: NoInfer<Z>, a: Effect.Effect.Success<Eff>, i: number) => Z,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => (elements: Iterable<Eff>) => Effect.Effect<Z, E | Effect.Effect.Error<Eff>, R | Effect.Effect.Context<Eff>>,\n  <Eff extends Effect.Effect<any, any, any>, Z, E, R>(\n    elements: Iterable<Eff>,\n    zero: Effect.Effect<Z, E, R>,\n    f: (z: NoInfer<Z>, a: Effect.Effect.Success<Eff>, i: number) => Z,\n    options?: {\n      readonly concurrency?: Concurrency | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => Effect.Effect<Z, E | Effect.Effect.Error<Eff>, R | Effect.Effect.Context<Eff>>\n>((args) => Predicate.isIterable(args[0]) && !core.isEffect(args[0]), <A, E, R, Z>(\n  elements: Iterable<Effect.Effect<A, E, R>>,\n  zero: Effect.Effect<Z, E, R>,\n  f: (z: NoInfer<Z>, a: NoInfer<A>, i: number) => Z,\n  options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }\n) =>\n  concurrency.matchSimple(\n    options?.concurrency,\n    () => RA.fromIterable(elements).reduce((acc, a, i) => core.zipWith(acc, a, (acc, a) => f(acc, a, i)), zero),\n    () =>\n      core.suspend(() =>\n        pipe(\n          mergeAll(\n            [zero, ...elements],\n            Option.none<Z>(),\n            (acc, elem, i) => {\n              switch (acc._tag) {\n                case \"None\": {\n                  return Option.some(elem as Z)\n                }\n                case \"Some\": {\n                  return Option.some(f(acc.value, elem as A, i))\n                }\n              }\n            },\n            options\n          ),\n          core.map((option) => {\n            switch (option._tag) {\n              case \"None\": {\n                throw new Error(\n                  \"BUG: Effect.reduceEffect - please report an issue at https://github.com/Effect-TS/effect/issues\"\n                )\n              }\n              case \"Some\": {\n                return option.value\n              }\n            }\n          })\n        )\n      )\n  ))\n\n/* @internal */\nexport const parallelFinalizers = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  core.contextWithEffect((context) =>\n    Option.match(Context.getOption(context, scopeTag), {\n      onNone: () => self,\n      onSome: (scope) => {\n        switch (scope.strategy._tag) {\n          case \"Parallel\":\n            return self\n          case \"Sequential\":\n          case \"ParallelN\":\n            return core.flatMap(\n              core.scopeFork(scope, ExecutionStrategy.parallel),\n              (inner) => scopeExtend(self, inner)\n            )\n        }\n      }\n    })\n  )\n\n/* @internal */\nexport const parallelNFinalizers =\n  (parallelism: number) => <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n    core.contextWithEffect((context) =>\n      Option.match(Context.getOption(context, scopeTag), {\n        onNone: () => self,\n        onSome: (scope) => {\n          if (scope.strategy._tag === \"ParallelN\" && scope.strategy.parallelism === parallelism) {\n            return self\n          }\n          return core.flatMap(\n            core.scopeFork(scope, ExecutionStrategy.parallelN(parallelism)),\n            (inner) => scopeExtend(self, inner)\n          )\n        }\n      })\n    )\n\n/* @internal */\nexport const finalizersMask = (strategy: ExecutionStrategy.ExecutionStrategy) =>\n<A, E, R>(\n  self: (\n    restore: <A1, E1, R1>(self: Effect.Effect<A1, E1, R1>) => Effect.Effect<A1, E1, R1>\n  ) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => finalizersMaskInternal(strategy, true)(self)\n\n/* @internal */\nexport const finalizersMaskInternal =\n  (strategy: ExecutionStrategy.ExecutionStrategy, concurrentFinalizers?: boolean | undefined) =>\n  <A, E, R>(\n    self: (\n      restore: <A1, E1, R1>(self: Effect.Effect<A1, E1, R1>) => Effect.Effect<A1, E1, R1>\n    ) => Effect.Effect<A, E, R>\n  ): Effect.Effect<A, E, R> =>\n    core.contextWithEffect((context) =>\n      Option.match(Context.getOption(context, scopeTag), {\n        onNone: () => self(identity),\n        onSome: (scope) => {\n          if (concurrentFinalizers === true) {\n            const patch = strategy._tag === \"Parallel\"\n              ? parallelFinalizers\n              : strategy._tag === \"Sequential\"\n              ? sequentialFinalizers\n              : parallelNFinalizers(strategy.parallelism)\n            switch (scope.strategy._tag) {\n              case \"Parallel\":\n                return patch(self(parallelFinalizers))\n              case \"Sequential\":\n                return patch(self(sequentialFinalizers))\n              case \"ParallelN\":\n                return patch(self(parallelNFinalizers(scope.strategy.parallelism)))\n            }\n          } else {\n            return self(identity)\n          }\n        }\n      })\n    )\n\n/* @internal */\nexport const scopeWith = <A, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R | Scope.Scope> => core.flatMap(scopeTag, f)\n\n/** @internal */\nexport const scopedWith = <A, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => core.flatMap(scopeMake(), (scope) => core.onExit(f(scope), (exit) => scope.close(exit)))\n\n/* @internal */\nexport const scopedEffect = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>\n  core.flatMap(scopeMake(), (scope) => scopeUse(effect, scope))\n\n/* @internal */\nexport const sequentialFinalizers = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  core.contextWithEffect((context) =>\n    Option.match(Context.getOption(context, scopeTag), {\n      onNone: () => self,\n      onSome: (scope) => {\n        switch (scope.strategy._tag) {\n          case \"Sequential\":\n            return self\n          case \"Parallel\":\n          case \"ParallelN\":\n            return core.flatMap(\n              core.scopeFork(scope, ExecutionStrategy.sequential),\n              (inner) => scopeExtend(self, inner)\n            )\n        }\n      }\n    })\n  )\n\n/* @internal */\nexport const tagMetricsScoped = (key: string, value: string): Effect.Effect<void, never, Scope.Scope> =>\n  labelMetricsScoped([metricLabel.make(key, value)])\n\n/* @internal */\nexport const labelMetricsScoped = (\n  labels: Iterable<MetricLabel.MetricLabel>\n): Effect.Effect<void, never, Scope.Scope> =>\n  fiberRefLocallyScopedWith(core.currentMetricLabels, (old) => RA.union(old, labels))\n\n/* @internal */\nexport const using = dual<\n  <A, A2, E2, R2>(\n    use: (a: A) => Effect.Effect<A2, E2, R2>\n  ) => <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2, E | E2, Exclude<R, Scope.Scope> | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    use: (a: A) => Effect.Effect<A2, E2, R2>\n  ) => Effect.Effect<A2, E | E2, Exclude<R, Scope.Scope> | R2>\n>(2, (self, use) => scopedWith((scope) => core.flatMap(scopeExtend(self, scope), use)))\n\n/** @internal */\nexport const validate = dual<\n  <B, E1, R1>(\n    that: Effect.Effect<B, E1, R1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<[A, B], E | E1, R | R1>,\n  <A, E, R, B, E1, R1>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<B, E1, R1>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => Effect.Effect<[A, B], E | E1, R | R1>\n>(\n  (args) => core.isEffect(args[1]),\n  (self, that, options) => validateWith(self, that, (a, b) => [a, b], options)\n)\n\n/** @internal */\nexport const validateWith = dual<\n  <B, E1, R1, A, C>(\n    that: Effect.Effect<B, E1, R1>,\n    f: (a: A, b: B) => C,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<C, E | E1, R | R1>,\n  <A, E, R, B, E1, R1, C>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<B, E1, R1>,\n    f: (a: A, b: B) => C,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => Effect.Effect<C, E | E1, R | R1>\n>((args) => core.isEffect(args[1]), (self, that, f, options) =>\n  core.flatten(zipWithOptions(\n    core.exit(self),\n    core.exit(that),\n    (ea, eb) =>\n      core.exitZipWith(ea, eb, {\n        onSuccess: f,\n        onFailure: (ca, cb) => options?.concurrent ? internalCause.parallel(ca, cb) : internalCause.sequential(ca, cb)\n      }),\n    options\n  )))\n\n/* @internal */\nexport const validateAllPar = dual<\n  <A, B, E, R>(\n    f: (a: A) => Effect.Effect<B, E, R>\n  ) => (elements: Iterable<A>) => Effect.Effect<Array<B>, Array<E>, R>,\n  <A, B, E, R>(\n    elements: Iterable<A>,\n    f: (a: A) => Effect.Effect<B, E, R>\n  ) => Effect.Effect<Array<B>, Array<E>, R>\n>(2, (elements, f) =>\n  core.flatMap(\n    partition(elements, f),\n    ([es, bs]) =>\n      es.length === 0\n        ? core.succeed(bs)\n        : core.fail(es)\n  ))\n\n/* @internal */\nexport const validateAllParDiscard = dual<\n  <A, B, E, R>(\n    f: (a: A) => Effect.Effect<B, E, R>\n  ) => (elements: Iterable<A>) => Effect.Effect<void, Array<E>, R>,\n  <A, B, E, R>(elements: Iterable<A>, f: (a: A) => Effect.Effect<B, E, R>) => Effect.Effect<void, Array<E>, R>\n>(2, (elements, f) =>\n  core.flatMap(\n    partition(elements, f),\n    ([es, _]) =>\n      es.length === 0\n        ? core.void\n        : core.fail(es)\n  ))\n\n/* @internal */\nexport const validateFirst = dual<\n  <A, B, E, R>(f: (a: A, i: number) => Effect.Effect<B, E, R>, options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }) => (elements: Iterable<A>) => Effect.Effect<B, Array<E>, R>,\n  <A, B, E, R>(elements: Iterable<A>, f: (a: A, i: number) => Effect.Effect<B, E, R>, options?: {\n    readonly concurrency?: Concurrency | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }) => Effect.Effect<B, Array<E>, R>\n>(\n  (args) => Predicate.isIterable(args[0]),\n  (elements, f, options) => core.flip(forEach(elements, (a, i) => core.flip(f(a, i)), options))\n)\n\n/* @internal */\nexport const withClockScoped = <C extends Clock.Clock>(c: C) =>\n  fiberRefLocallyScopedWith(defaultServices.currentServices, Context.add(clock.clockTag, c))\n\n/* @internal */\nexport const withRandomScoped = <A extends Random.Random>(value: A) =>\n  fiberRefLocallyScopedWith(defaultServices.currentServices, Context.add(randomTag, value))\n\n/* @internal */\nexport const withConfigProviderScoped = (provider: ConfigProvider) =>\n  fiberRefLocallyScopedWith(defaultServices.currentServices, Context.add(configProviderTag, provider))\n\n/* @internal */\nexport const withEarlyRelease = <A, E, R>(\n  self: Effect.Effect<A, E, R>\n): Effect.Effect<[Effect.Effect<void>, A], E, R | Scope.Scope> =>\n  scopeWith((parent) =>\n    core.flatMap(core.scopeFork(parent, executionStrategy.sequential), (child) =>\n      pipe(\n        self,\n        scopeExtend(child),\n        core.map((value) => [\n          core.fiberIdWith((fiberId) => core.scopeClose(child, core.exitInterrupt(fiberId))),\n          value\n        ])\n      ))\n  )\n\n/** @internal */\nexport const zipOptions = dual<\n  <A2, E2, R2>(\n    that: Effect.Effect<A2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => <A, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<[A, A2], E | E2, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => Effect.Effect<[A, A2], E | E2, R | R2>\n>((args) => core.isEffect(args[1]), (\n  self,\n  that,\n  options\n) => zipWithOptions(self, that, (a, b) => [a, b], options))\n\n/** @internal */\nexport const zipLeftOptions = dual<\n  <A2, E2, R2>(\n    that: Effect.Effect<A2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => <A, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<A, E | E2, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ) => Effect.Effect<A, E | E2, R | R2>\n>(\n  (args) => core.isEffect(args[1]),\n  (self, that, options) => {\n    if (options?.concurrent !== true && (options?.batching === undefined || options.batching === false)) {\n      return core.zipLeft(self, that)\n    }\n    return zipWithOptions(self, that, (a, _) => a, options)\n  }\n)\n\n/** @internal */\nexport const zipRightOptions: {\n  <A2, E2, R2>(\n    that: Effect.Effect<A2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect.Effect<A2, E2 | E, R2 | R>\n} = dual((args) => core.isEffect(args[1]), <A, E, R, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  that: Effect.Effect<A2, E2, R2>,\n  options?: {\n    readonly concurrent?: boolean | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }\n): Effect.Effect<A2, E2 | E, R2 | R> => {\n  if (options?.concurrent !== true && (options?.batching === undefined || options.batching === false)) {\n    return core.zipRight(self, that)\n  }\n  return zipWithOptions(self, that, (_, b) => b, options)\n})\n\n/** @internal */\nexport const zipWithOptions: {\n  <A2, E2, R2, A, B>(\n    that: Effect.Effect<A2, E2, R2>,\n    f: (a: A, b: A2) => B,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E2 | E, R2 | R>\n  <A, E, R, A2, E2, R2, B>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>,\n    f: (a: A, b: A2) => B,\n    options?: {\n      readonly concurrent?: boolean | undefined\n      readonly batching?: boolean | \"inherit\" | undefined\n      readonly concurrentFinalizers?: boolean | undefined\n    }\n  ): Effect.Effect<B, E2 | E, R2 | R>\n} = dual((args) => core.isEffect(args[1]), <A, E, R, A2, E2, R2, B>(\n  self: Effect.Effect<A, E, R>,\n  that: Effect.Effect<A2, E2, R2>,\n  f: (a: A, b: A2) => B,\n  options?: {\n    readonly concurrent?: boolean | undefined\n    readonly batching?: boolean | \"inherit\" | undefined\n    readonly concurrentFinalizers?: boolean | undefined\n  }\n): Effect.Effect<B, E2 | E, R2 | R> =>\n  core.map(\n    all([self, that], {\n      concurrency: options?.concurrent ? 2 : 1,\n      batching: options?.batching,\n      concurrentFinalizers: options?.concurrentFinalizers\n    }),\n    ([a, a2]) => f(a, a2)\n  ))\n\n/* @internal */\nexport const withRuntimeFlagsScoped = (\n  update: RuntimeFlagsPatch.RuntimeFlagsPatch\n): Effect.Effect<void, never, Scope.Scope> => {\n  if (update === RuntimeFlagsPatch.empty) {\n    return core.void\n  }\n  return pipe(\n    core.runtimeFlags,\n    core.flatMap((runtimeFlags) => {\n      const updatedRuntimeFlags = runtimeFlags_.patch(runtimeFlags, update)\n      const revertRuntimeFlags = runtimeFlags_.diff(updatedRuntimeFlags, runtimeFlags)\n      return pipe(\n        core.updateRuntimeFlags(update),\n        core.zipRight(addFinalizer(() => core.updateRuntimeFlags(revertRuntimeFlags))),\n        core.asVoid\n      )\n    }),\n    core.uninterruptible\n  )\n}\n\n// circular with Scope\n\n/** @internal */\nexport const scopeTag = Context.GenericTag<Scope.Scope>(\"effect/Scope\")\n\n/* @internal */\nexport const scope: Effect.Effect<Scope.Scope, never, Scope.Scope> = scopeTag\n\n/** @internal */\nexport interface ScopeImpl extends Scope.CloseableScope {\n  state: {\n    readonly _tag: \"Open\"\n    readonly finalizers: Map<{}, Scope.Scope.Finalizer>\n  } | {\n    readonly _tag: \"Closed\"\n    readonly exit: Exit.Exit<unknown, unknown>\n  }\n}\n\nconst scopeUnsafeAddFinalizer = (scope: ScopeImpl, fin: Scope.Scope.Finalizer): void => {\n  if (scope.state._tag === \"Open\") {\n    scope.state.finalizers.set({}, fin)\n  }\n}\n\nconst ScopeImplProto: Omit<ScopeImpl, \"strategy\" | \"state\"> = {\n  [core.ScopeTypeId]: core.ScopeTypeId,\n  [core.CloseableScopeTypeId]: core.CloseableScopeTypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  fork(this: ScopeImpl, strategy) {\n    return core.sync(() => {\n      const newScope = scopeUnsafeMake(strategy)\n      if (this.state._tag === \"Closed\") {\n        newScope.state = this.state\n        return newScope\n      }\n      const key = {}\n      const fin = (exit: Exit.Exit<unknown, unknown>) => newScope.close(exit)\n      this.state.finalizers.set(key, fin)\n      scopeUnsafeAddFinalizer(newScope, (_) =>\n        core.sync(() => {\n          if (this.state._tag === \"Open\") {\n            this.state.finalizers.delete(key)\n          }\n        }))\n      return newScope\n    })\n  },\n  close(this: ScopeImpl, exit) {\n    return core.suspend(() => {\n      if (this.state._tag === \"Closed\") {\n        return core.void\n      }\n      const finalizers = Array.from(this.state.finalizers.values()).reverse()\n      this.state = { _tag: \"Closed\", exit }\n      if (finalizers.length === 0) {\n        return core.void\n      }\n      return executionStrategy.isSequential(this.strategy) ?\n        pipe(\n          core.forEachSequential(finalizers, (fin) => core.exit(fin(exit))),\n          core.flatMap((results) =>\n            pipe(\n              core.exitCollectAll(results),\n              Option.map(core.exitAsVoid),\n              Option.getOrElse(() => core.exitVoid)\n            )\n          )\n        ) :\n        executionStrategy.isParallel(this.strategy) ?\n        pipe(\n          forEachParUnbounded(finalizers, (fin) => core.exit(fin(exit)), false),\n          core.flatMap((results) =>\n            pipe(\n              core.exitCollectAll(results, { parallel: true }),\n              Option.map(core.exitAsVoid),\n              Option.getOrElse(() => core.exitVoid)\n            )\n          )\n        ) :\n        pipe(\n          forEachParN(finalizers, this.strategy.parallelism, (fin) => core.exit(fin(exit)), false),\n          core.flatMap((results) =>\n            pipe(\n              core.exitCollectAll(results, { parallel: true }),\n              Option.map(core.exitAsVoid),\n              Option.getOrElse(() => core.exitVoid)\n            )\n          )\n        )\n    })\n  },\n  addFinalizer(this: ScopeImpl, fin) {\n    return core.suspend(() => {\n      if (this.state._tag === \"Closed\") {\n        return fin(this.state.exit)\n      }\n      this.state.finalizers.set({}, fin)\n      return core.void\n    })\n  }\n}\n\nconst scopeUnsafeMake = (\n  strategy: ExecutionStrategy.ExecutionStrategy = executionStrategy.sequential\n): ScopeImpl => {\n  const scope = Object.create(ScopeImplProto)\n  scope.strategy = strategy\n  scope.state = { _tag: \"Open\", finalizers: new Map() }\n  return scope\n}\n\n/* @internal */\nexport const scopeMake = (\n  strategy: ExecutionStrategy.ExecutionStrategy = executionStrategy.sequential\n): Effect.Effect<Scope.Scope.Closeable> => core.sync(() => scopeUnsafeMake(strategy))\n\n/* @internal */\nexport const scopeExtend = dual<\n  (scope: Scope.Scope) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Scope.Scope>>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, scope: Scope.Scope) => Effect.Effect<A, E, Exclude<R, Scope.Scope>>\n>(\n  2,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, scope: Scope.Scope) =>\n    core.mapInputContext<A, E, R, Exclude<R, Scope.Scope>>(\n      effect,\n      // @ts-expect-error\n      Context.merge(Context.make(scopeTag, scope))\n    )\n)\n\n/* @internal */\nexport const scopeUse = dual<\n  (\n    scope: Scope.Scope.Closeable\n  ) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Scope.Scope>>,\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    scope: Scope.Scope.Closeable\n  ) => Effect.Effect<A, E, Exclude<R, Scope.Scope>>\n>(2, (effect, scope) =>\n  pipe(\n    effect,\n    scopeExtend(scope),\n    core.onExit((exit) => scope.close(exit))\n  ))\n\n// circular with Supervisor\n\n/** @internal */\nexport const fiberRefUnsafeMakeSupervisor = (\n  initial: Supervisor.Supervisor<any>\n): FiberRef.FiberRef<Supervisor.Supervisor<any>> =>\n  core.fiberRefUnsafeMakePatch(initial, {\n    differ: SupervisorPatch.differ,\n    fork: SupervisorPatch.empty\n  })\n\n// circular with FiberRef\n\n/* @internal */\nexport const fiberRefLocallyScoped = dual<\n  <A>(value: A) => (self: FiberRef.FiberRef<A>) => Effect.Effect<void, never, Scope.Scope>,\n  <A>(self: FiberRef.FiberRef<A>, value: A) => Effect.Effect<void, never, Scope.Scope>\n>(2, (self, value) =>\n  core.asVoid(\n    acquireRelease(\n      core.flatMap(\n        core.fiberRefGet(self),\n        (oldValue) => core.as(core.fiberRefSet(self, value), oldValue)\n      ),\n      (oldValue) => core.fiberRefSet(self, oldValue)\n    )\n  ))\n\n/* @internal */\nexport const fiberRefLocallyScopedWith = dual<\n  <A>(f: (a: A) => A) => (self: FiberRef.FiberRef<A>) => Effect.Effect<void, never, Scope.Scope>,\n  <A>(self: FiberRef.FiberRef<A>, f: (a: A) => A) => Effect.Effect<void, never, Scope.Scope>\n>(2, (self, f) => core.fiberRefGetWith(self, (a) => fiberRefLocallyScoped(self, f(a))))\n\n/* @internal */\nexport const fiberRefMake = <A>(\n  initial: A,\n  options?: {\n    readonly fork?: ((a: A) => A) | undefined\n    readonly join?: ((left: A, right: A) => A) | undefined\n  }\n): Effect.Effect<FiberRef.FiberRef<A>, never, Scope.Scope> =>\n  fiberRefMakeWith(() => core.fiberRefUnsafeMake(initial, options))\n\n/* @internal */\nexport const fiberRefMakeWith = <Value>(\n  ref: LazyArg<FiberRef.FiberRef<Value>>\n): Effect.Effect<FiberRef.FiberRef<Value>, never, Scope.Scope> =>\n  acquireRelease(\n    core.tap(core.sync(ref), (ref) => core.fiberRefUpdate(ref, identity)),\n    (fiberRef) => core.fiberRefDelete(fiberRef)\n  )\n\n/* @internal */\nexport const fiberRefMakeContext = <A>(\n  initial: Context.Context<A>\n): Effect.Effect<FiberRef.FiberRef<Context.Context<A>>, never, Scope.Scope> =>\n  fiberRefMakeWith(() => core.fiberRefUnsafeMakeContext(initial))\n\n/* @internal */\nexport const fiberRefMakeRuntimeFlags = (\n  initial: RuntimeFlags.RuntimeFlags\n): Effect.Effect<FiberRef.FiberRef<RuntimeFlags.RuntimeFlags>, never, Scope.Scope> =>\n  fiberRefMakeWith(() => core.fiberRefUnsafeMakeRuntimeFlags(initial))\n\n/** @internal */\nexport const currentRuntimeFlags: FiberRef.FiberRef<RuntimeFlags.RuntimeFlags> = core.fiberRefUnsafeMakeRuntimeFlags(\n  runtimeFlags_.none\n)\n\n/** @internal */\nexport const currentSupervisor: FiberRef.FiberRef<Supervisor.Supervisor<any>> = fiberRefUnsafeMakeSupervisor(\n  supervisor.none\n)\n\n// circular with Fiber\n\n/* @internal */\nexport const fiberAwaitAll = <const T extends Iterable<Fiber.Fiber<any, any>>>(\n  fibers: T\n): Effect.Effect<\n  [T] extends [ReadonlyArray<infer U>]\n    ? number extends T[\"length\"] ? Array<U extends Fiber.Fiber<infer A, infer E> ? Exit.Exit<A, E> : never>\n    : { -readonly [K in keyof T]: T[K] extends Fiber.Fiber<infer A, infer E> ? Exit.Exit<A, E> : never }\n    : Array<T extends Iterable<infer U> ? U extends Fiber.Fiber<infer A, infer E> ? Exit.Exit<A, E> : never : never>\n> => forEach(fibers, internalFiber._await) as any\n\n/** @internal */\nexport const fiberAll = <A, E>(fibers: Iterable<Fiber.Fiber<A, E>>): Fiber.Fiber<Array<A>, E> => {\n  const _fiberAll = {\n    ...Effectable.CommitPrototype,\n    commit() {\n      return internalFiber.join(this)\n    },\n    [internalFiber.FiberTypeId]: internalFiber.fiberVariance,\n    id: () =>\n      RA.fromIterable(fibers).reduce((id, fiber) => FiberId.combine(id, fiber.id()), FiberId.none as FiberId.FiberId),\n    await: core.exit(forEachParUnbounded(fibers, (fiber) => core.flatten(fiber.await), false)),\n    children: core.map(forEachParUnbounded(fibers, (fiber) => fiber.children, false), RA.flatten),\n    inheritAll: core.forEachSequentialDiscard(fibers, (fiber) => fiber.inheritAll),\n    poll: core.map(\n      core.forEachSequential(fibers, (fiber) => fiber.poll),\n      RA.reduceRight(\n        Option.some<Exit.Exit<Array<A>, E>>(core.exitSucceed(new Array())),\n        (optionB, optionA) => {\n          switch (optionA._tag) {\n            case \"None\": {\n              return Option.none()\n            }\n            case \"Some\": {\n              switch (optionB._tag) {\n                case \"None\": {\n                  return Option.none()\n                }\n                case \"Some\": {\n                  return Option.some(\n                    core.exitZipWith(optionA.value, optionB.value, {\n                      onSuccess: (a, chunk) => [a, ...chunk],\n                      onFailure: internalCause.parallel\n                    })\n                  )\n                }\n              }\n            }\n          }\n        }\n      )\n    ),\n    interruptAsFork: (fiberId: FiberId.FiberId) =>\n      core.forEachSequentialDiscard(fibers, (fiber) => fiber.interruptAsFork(fiberId))\n  }\n  return _fiberAll\n}\n\n/* @internal */\nexport const fiberInterruptFork = <A, E>(self: Fiber.Fiber<A, E>): Effect.Effect<void> =>\n  core.asVoid(forkDaemon(core.interruptFiber(self)))\n\n/* @internal */\nexport const fiberJoinAll = <A, E>(fibers: Iterable<Fiber.Fiber<A, E>>): Effect.Effect<Array<A>, E> =>\n  internalFiber.join(fiberAll(fibers))\n\n/* @internal */\nexport const fiberScoped = <A, E>(self: Fiber.Fiber<A, E>): Effect.Effect<Fiber.Fiber<A, E>, never, Scope.Scope> =>\n  acquireRelease(core.succeed(self), core.interruptFiber)\n\n//\n// circular race\n//\n\n/** @internal */\nexport const raceWith = dual<\n  <A1, E1, R1, E, A, A2, E2, R2, A3, E3, R3>(\n    other: Effect.Effect<A1, E1, R1>,\n    options: {\n      readonly onSelfDone: (exit: Exit.Exit<A, E>, fiber: Fiber.Fiber<A1, E1>) => Effect.Effect<A2, E2, R2>\n      readonly onOtherDone: (exit: Exit.Exit<A1, E1>, fiber: Fiber.Fiber<A, E>) => Effect.Effect<A3, E3, R3>\n    }\n  ) => <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A3, E2 | E3, R | R1 | R2 | R3>,\n  <A, E, R, A1, E1, R1, A2, E2, R2, A3, E3, R3>(\n    self: Effect.Effect<A, E, R>,\n    other: Effect.Effect<A1, E1, R1>,\n    options: {\n      readonly onSelfDone: (exit: Exit.Exit<A, E>, fiber: Fiber.Fiber<A1, E1>) => Effect.Effect<A2, E2, R2>\n      readonly onOtherDone: (exit: Exit.Exit<A1, E1>, fiber: Fiber.Fiber<A, E>) => Effect.Effect<A3, E3, R3>\n    }\n  ) => Effect.Effect<A2 | A3, E2 | E3, R | R1 | R2 | R3>\n>(3, (self, other, options) =>\n  raceFibersWith(self, other, {\n    onSelfWin: (winner, loser) =>\n      core.flatMap(winner.await, (exit) => {\n        switch (exit._tag) {\n          case OpCodes.OP_SUCCESS: {\n            return core.flatMap(\n              winner.inheritAll,\n              () => options.onSelfDone(exit, loser)\n            )\n          }\n          case OpCodes.OP_FAILURE: {\n            return options.onSelfDone(exit, loser)\n          }\n        }\n      }),\n    onOtherWin: (winner, loser) =>\n      core.flatMap(winner.await, (exit) => {\n        switch (exit._tag) {\n          case OpCodes.OP_SUCCESS: {\n            return core.flatMap(\n              winner.inheritAll,\n              () => options.onOtherDone(exit, loser)\n            )\n          }\n          case OpCodes.OP_FAILURE: {\n            return options.onOtherDone(exit, loser)\n          }\n        }\n      })\n  }))\n\n/** @internal */\nexport const disconnect = <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n  core.uninterruptibleMask((restore) =>\n    core.fiberIdWith((fiberId) =>\n      core.flatMap(forkDaemon(restore(self)), (fiber) =>\n        pipe(\n          restore(internalFiber.join(fiber)),\n          core.onInterrupt(() => pipe(fiber, internalFiber.interruptAsFork(fiberId)))\n        ))\n    )\n  )\n\n/** @internal */\nexport const race = dual<\n  <A2, E2, R2>(\n    that: Effect.Effect<A2, E2, R2>\n  ) => <A, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<A | A2, E | E2, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    that: Effect.Effect<A2, E2, R2>\n  ) => Effect.Effect<A | A2, E | E2, R | R2>\n>(\n  2,\n  (self, that) =>\n    core.fiberIdWith((parentFiberId) =>\n      raceWith(self, that, {\n        onSelfDone: (exit, right) =>\n          core.exitMatchEffect(exit, {\n            onFailure: (cause) =>\n              pipe(\n                internalFiber.join(right),\n                internalEffect.mapErrorCause((cause2) => internalCause.parallel(cause, cause2))\n              ),\n            onSuccess: (value) =>\n              pipe(\n                right,\n                core.interruptAsFiber(parentFiberId),\n                core.as(value)\n              )\n          }),\n        onOtherDone: (exit, left) =>\n          core.exitMatchEffect(exit, {\n            onFailure: (cause) =>\n              pipe(\n                internalFiber.join(left),\n                internalEffect.mapErrorCause((cause2) => internalCause.parallel(cause2, cause))\n              ),\n            onSuccess: (value) =>\n              pipe(\n                left,\n                core.interruptAsFiber(parentFiberId),\n                core.as(value)\n              )\n          })\n      })\n    )\n)\n\n/** @internal */\nexport const raceFibersWith = dual<\n  <A1, E1, R1, E, A, A2, E2, R2, A3, E3, R3>(\n    other: Effect.Effect<A1, E1, R1>,\n    options: {\n      readonly onSelfWin: (\n        winner: Fiber.RuntimeFiber<A, E>,\n        loser: Fiber.RuntimeFiber<A1, E1>\n      ) => Effect.Effect<A2, E2, R2>\n      readonly onOtherWin: (\n        winner: Fiber.RuntimeFiber<A1, E1>,\n        loser: Fiber.RuntimeFiber<A, E>\n      ) => Effect.Effect<A3, E3, R3>\n      readonly selfScope?: fiberScope.FiberScope | undefined\n      readonly otherScope?: fiberScope.FiberScope | undefined\n    }\n  ) => <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A2 | A3, E2 | E3, R | R1 | R2 | R3>,\n  <A, E, R, A1, E1, R1, A2, E2, R2, A3, E3, R3>(\n    self: Effect.Effect<A, E, R>,\n    other: Effect.Effect<A1, E1, R1>,\n    options: {\n      readonly onSelfWin: (\n        winner: Fiber.RuntimeFiber<A, E>,\n        loser: Fiber.RuntimeFiber<A1, E1>\n      ) => Effect.Effect<A2, E2, R2>\n      readonly onOtherWin: (\n        winner: Fiber.RuntimeFiber<A1, E1>,\n        loser: Fiber.RuntimeFiber<A, E>\n      ) => Effect.Effect<A3, E3, R3>\n      readonly selfScope?: fiberScope.FiberScope | undefined\n      readonly otherScope?: fiberScope.FiberScope | undefined\n    }\n  ) => Effect.Effect<A2 | A3, E2 | E3, R | R1 | R2 | R3>\n>(3, <A, E, R, A1, E1, R1, A2, E2, R2, A3, E3, R3>(\n  self: Effect.Effect<A, E, R>,\n  other: Effect.Effect<A1, E1, R1>,\n  options: {\n    readonly onSelfWin: (\n      winner: Fiber.RuntimeFiber<A, E>,\n      loser: Fiber.RuntimeFiber<A1, E1>\n    ) => Effect.Effect<A2, E2, R2>\n    readonly onOtherWin: (\n      winner: Fiber.RuntimeFiber<A1, E1>,\n      loser: Fiber.RuntimeFiber<A, E>\n    ) => Effect.Effect<A3, E3, R3>\n    readonly selfScope?: fiberScope.FiberScope | undefined\n    readonly otherScope?: fiberScope.FiberScope | undefined\n  }\n) =>\n  core.withFiberRuntime((parentFiber, parentStatus) => {\n    const parentRuntimeFlags = parentStatus.runtimeFlags\n    const raceIndicator = MRef.make(true)\n    const leftFiber: FiberRuntime<A, E> = unsafeMakeChildFiber(\n      self,\n      parentFiber,\n      parentRuntimeFlags,\n      options.selfScope\n    )\n    const rightFiber: FiberRuntime<A1, E1> = unsafeMakeChildFiber(\n      other,\n      parentFiber,\n      parentRuntimeFlags,\n      options.otherScope\n    )\n    return core.async((cb) => {\n      leftFiber.addObserver(() => completeRace(leftFiber, rightFiber, options.onSelfWin, raceIndicator, cb))\n      rightFiber.addObserver(() => completeRace(rightFiber, leftFiber, options.onOtherWin, raceIndicator, cb))\n      leftFiber.startFork(self)\n      rightFiber.startFork(other)\n    }, FiberId.combine(leftFiber.id(), rightFiber.id()))\n  }))\n\nconst completeRace = <A2, A3, E2, E3, R, R1, R2, R3>(\n  winner: Fiber.RuntimeFiber<any, any>,\n  loser: Fiber.RuntimeFiber<any, any>,\n  cont: (winner: Fiber.RuntimeFiber<any, any>, loser: Fiber.RuntimeFiber<any, any>) => Effect.Effect<any, any, any>,\n  ab: MRef.MutableRef<boolean>,\n  cb: (_: Effect.Effect<A2 | A3, E2 | E3, R | R1 | R2 | R3>) => void\n): void => {\n  if (MRef.compareAndSet(true, false)(ab)) {\n    cb(cont(winner, loser))\n  }\n}\n\n/** @internal */\nexport const ensuring: {\n  <X, R1>(\n    finalizer: Effect.Effect<X, never, R1>\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R1 | R>\n  <A, E, R, X, R1>(self: Effect.Effect<A, E, R>, finalizer: Effect.Effect<X, never, R1>): Effect.Effect<A, E, R1 | R>\n} = dual(\n  2,\n  <A, E, R, X, R1>(self: Effect.Effect<A, E, R>, finalizer: Effect.Effect<X, never, R1>): Effect.Effect<A, E, R1 | R> =>\n    core.uninterruptibleMask((restore) =>\n      core.matchCauseEffect(restore(self), {\n        onFailure: (cause1) =>\n          core.matchCauseEffect(finalizer, {\n            onFailure: (cause2) => core.failCause(internalCause.sequential(cause1, cause2)),\n            onSuccess: () => core.failCause(cause1)\n          }),\n        onSuccess: (a) => core.as(finalizer, a)\n      })\n    )\n)\n\n/** @internal */\nexport const invokeWithInterrupt: <A, E, R>(\n  self: Effect.Effect<A, E, R>,\n  entries: ReadonlyArray<Entry<unknown>>,\n  onInterrupt?: () => void\n) => Effect.Effect<void, E, R> = <A, E, R>(\n  self: Effect.Effect<A, E, R>,\n  entries: ReadonlyArray<Entry<unknown>>,\n  onInterrupt?: () => void\n) =>\n  core.fiberIdWith((id) =>\n    core.flatMap(\n      core.flatMap(\n        forkDaemon(core.interruptible(self)),\n        (processing) =>\n          core.async<void, E>((cb) => {\n            const counts = entries.map((_) => _.listeners.count)\n            const checkDone = () => {\n              if (counts.every((count) => count === 0)) {\n                if (\n                  entries.every((_) => {\n                    if (_.result.state.current._tag === \"Pending\") {\n                      return true\n                    } else if (\n                      _.result.state.current._tag === \"Done\" &&\n                      core.exitIsExit(_.result.state.current.effect) &&\n                      _.result.state.current.effect._tag === \"Failure\" &&\n                      internalCause.isInterrupted(_.result.state.current.effect.cause)\n                    ) {\n                      return true\n                    } else {\n                      return false\n                    }\n                  })\n                ) {\n                  cleanup.forEach((f) => f())\n                  onInterrupt?.()\n                  cb(core.interruptFiber(processing))\n                }\n              }\n            }\n            processing.addObserver((exit) => {\n              cleanup.forEach((f) => f())\n              cb(exit)\n            })\n            const cleanup = entries.map((r, i) => {\n              const observer = (count: number) => {\n                counts[i] = count\n                checkDone()\n              }\n              r.listeners.addObserver(observer)\n              return () => r.listeners.removeObserver(observer)\n            })\n            checkDone()\n            return core.sync(() => {\n              cleanup.forEach((f) => f())\n            })\n          })\n      ),\n      () =>\n        core.suspend(() => {\n          const residual = entries.flatMap((entry) => {\n            if (!entry.state.completed) {\n              return [entry]\n            }\n            return []\n          })\n          return core.forEachSequentialDiscard(\n            residual,\n            (entry) => complete(entry.request as any, core.exitInterrupt(id))\n          )\n        })\n    )\n  )\n\n/** @internal */\nexport const interruptWhenPossible = dual<\n  (all: Iterable<Request<any, any>>) => <A, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<void, E, R>,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    all: Iterable<Request<any, any>>\n  ) => Effect.Effect<void, E, R>\n>(2, (self, all) =>\n  core.fiberRefGetWith(\n    currentRequestMap,\n    (map) =>\n      core.suspend(() => {\n        const entries = RA.fromIterable(all).flatMap((_) => map.has(_) ? [map.get(_)!] : [])\n        return invokeWithInterrupt(self, entries)\n      })\n  ))\n\n// circular Tracer\n\n/** @internal */\nexport const makeSpanScoped = (\n  name: string,\n  options?: Tracer.SpanOptions | undefined\n): Effect.Effect<Tracer.Span, never, Scope.Scope> => {\n  options = tracer.addSpanStackTrace(options)\n  return core.uninterruptible(\n    core.withFiberRuntime((fiber) => {\n      const scope = Context.unsafeGet(fiber.getFiberRef(core.currentContext), scopeTag)\n      const span = internalEffect.unsafeMakeSpan(fiber, name, options)\n      const timingEnabled = fiber.getFiberRef(core.currentTracerTimingEnabled)\n      const clock_ = Context.get(fiber.getFiberRef(defaultServices.currentServices), clock.clockTag)\n      return core.as(\n        core.scopeAddFinalizerExit(scope, (exit) => internalEffect.endSpan(span, exit, clock_, timingEnabled)),\n        span\n      )\n    })\n  )\n}\n\n/* @internal */\nexport const withTracerScoped = (value: Tracer.Tracer): Effect.Effect<void, never, Scope.Scope> =>\n  fiberRefLocallyScopedWith(defaultServices.currentServices, Context.add(tracer.tracerTag, value))\n\n/** @internal */\nexport const withSpanScoped: {\n  (\n    name: string,\n    options?: Tracer.SpanOptions\n  ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Scope.Scope | Exclude<R, Tracer.ParentSpan>>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    name: string,\n    options?: Tracer.SpanOptions\n  ): Effect.Effect<A, E, Scope.Scope | Exclude<R, Tracer.ParentSpan>>\n} = function() {\n  const dataFirst = typeof arguments[0] !== \"string\"\n  const name = dataFirst ? arguments[1] : arguments[0]\n  const options = tracer.addSpanStackTrace(dataFirst ? arguments[2] : arguments[1])\n  if (dataFirst) {\n    const self = arguments[0]\n    return core.flatMap(\n      makeSpanScoped(name, tracer.addSpanStackTrace(options)),\n      (span) => internalEffect.provideService(self, tracer.spanTag, span)\n    )\n  }\n  return (self: Effect.Effect<any, any, any>) =>\n    core.flatMap(\n      makeSpanScoped(name, tracer.addSpanStackTrace(options)),\n      (span) => internalEffect.provideService(self, tracer.spanTag, span)\n    )\n} as any\n"
  },
  {
    "path": "packages/effect/src/internal/fiberScope.ts",
    "content": "import * as FiberId from \"../FiberId.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport type * as RuntimeFlags from \"../RuntimeFlags.js\"\nimport * as FiberMessage from \"./fiberMessage.js\"\nimport type * as FiberRuntime from \"./fiberRuntime.js\"\n\n/** @internal */\nconst FiberScopeSymbolKey = \"effect/FiberScope\"\n\n/** @internal */\nexport const FiberScopeTypeId = Symbol.for(FiberScopeSymbolKey)\n\nexport type FiberScopeTypeId = typeof FiberScopeTypeId\n\n/**\n * A `FiberScope` represents the scope of a fiber lifetime. The scope of a\n * fiber can be retrieved using `Effect.descriptor`, and when forking fibers,\n * you can specify a custom scope to fork them on by using the `forkIn`.\n *\n * @since 2.0.0\n * @category models\n */\nexport interface FiberScope {\n  readonly [FiberScopeTypeId]: FiberScopeTypeId\n  get fiberId(): FiberId.FiberId\n  add(runtimeFlags: RuntimeFlags.RuntimeFlags, child: FiberRuntime.FiberRuntime<any, any>): void\n}\n\n/** @internal */\nclass Global implements FiberScope {\n  readonly [FiberScopeTypeId]: FiberScopeTypeId = FiberScopeTypeId\n  readonly fiberId = FiberId.none\n  readonly roots = new Set<FiberRuntime.FiberRuntime<any, any>>()\n  add(_runtimeFlags: RuntimeFlags.RuntimeFlags, child: FiberRuntime.FiberRuntime<any, any>): void {\n    this.roots.add(child)\n    child.addObserver(() => {\n      this.roots.delete(child)\n    })\n  }\n}\n\n/** @internal */\nclass Local implements FiberScope {\n  readonly [FiberScopeTypeId]: FiberScopeTypeId = FiberScopeTypeId\n  constructor(\n    readonly fiberId: FiberId.FiberId,\n    readonly parent: FiberRuntime.FiberRuntime<any, any>\n  ) {\n  }\n  add(_runtimeFlags: RuntimeFlags.RuntimeFlags, child: FiberRuntime.FiberRuntime<any, any>): void {\n    this.parent.tell(\n      FiberMessage.stateful((parentFiber) => {\n        parentFiber.addChild(child)\n        child.addObserver(() => {\n          parentFiber.removeChild(child)\n        })\n      })\n    )\n  }\n}\n\n/** @internal */\nexport const unsafeMake = (fiber: FiberRuntime.FiberRuntime<any, any>): FiberScope => {\n  return new Local(fiber.id(), fiber)\n}\n\n/** @internal */\nexport const globalScope = globalValue(\n  Symbol.for(\"effect/FiberScope/Global\"),\n  () => new Global()\n)\n"
  },
  {
    "path": "packages/effect/src/internal/fiberStatus.ts",
    "content": "import * as Equal from \"../Equal.js\"\nimport type { FiberId } from \"../FiberId.js\"\nimport type * as FiberStatus from \"../FiberStatus.js\"\nimport { pipe } from \"../Function.js\"\nimport * as Hash from \"../Hash.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type { RuntimeFlags } from \"../RuntimeFlags.js\"\n\nconst FiberStatusSymbolKey = \"effect/FiberStatus\"\n\n/** @internal */\nexport const FiberStatusTypeId: FiberStatus.FiberStatusTypeId = Symbol.for(\n  FiberStatusSymbolKey\n) as FiberStatus.FiberStatusTypeId\n\n/** @internal */\nexport const OP_DONE = \"Done\" as const\n\n/** @internal */\nexport type OP_DONE = typeof OP_DONE\n\n/** @internal */\nexport const OP_RUNNING = \"Running\" as const\n\n/** @internal */\nexport type OP_RUNNING = typeof OP_RUNNING\n\n/** @internal */\nexport const OP_SUSPENDED = \"Suspended\" as const\n\n/** @internal */\nexport type OP_SUSPENDED = typeof OP_SUSPENDED\n\nconst DoneHash = Hash.string(`${FiberStatusSymbolKey}-${OP_DONE}`)\n\n/** @internal */\nclass Done implements FiberStatus.Done {\n  readonly [FiberStatusTypeId]: FiberStatus.FiberStatusTypeId = FiberStatusTypeId\n  readonly _tag = OP_DONE;\n  [Hash.symbol](): number {\n    return DoneHash\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isFiberStatus(that) && that._tag === OP_DONE\n  }\n}\n\n/** @internal */\nclass Running implements FiberStatus.Running {\n  readonly [FiberStatusTypeId]: FiberStatus.FiberStatusTypeId = FiberStatusTypeId\n  readonly _tag = OP_RUNNING\n  constructor(readonly runtimeFlags: RuntimeFlags) {}\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(FiberStatusSymbolKey),\n      Hash.combine(Hash.hash(this._tag)),\n      Hash.combine(Hash.hash(this.runtimeFlags)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return (\n      isFiberStatus(that) &&\n      that._tag === OP_RUNNING &&\n      this.runtimeFlags === that.runtimeFlags\n    )\n  }\n}\n\n/** @internal */\nclass Suspended implements FiberStatus.Suspended {\n  readonly [FiberStatusTypeId]: FiberStatus.FiberStatusTypeId = FiberStatusTypeId\n  readonly _tag = OP_SUSPENDED\n  constructor(\n    readonly runtimeFlags: RuntimeFlags,\n    readonly blockingOn: FiberId\n  ) {}\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(FiberStatusSymbolKey),\n      Hash.combine(Hash.hash(this._tag)),\n      Hash.combine(Hash.hash(this.runtimeFlags)),\n      Hash.combine(Hash.hash(this.blockingOn)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return (\n      isFiberStatus(that) &&\n      that._tag === OP_SUSPENDED &&\n      this.runtimeFlags === that.runtimeFlags &&\n      Equal.equals(this.blockingOn, that.blockingOn)\n    )\n  }\n}\n\n/** @internal */\nexport const done: FiberStatus.FiberStatus = new Done()\n\n/** @internal */\nexport const running = (runtimeFlags: RuntimeFlags): FiberStatus.FiberStatus => new Running(runtimeFlags)\n\n/** @internal */\nexport const suspended = (\n  runtimeFlags: RuntimeFlags,\n  blockingOn: FiberId\n): FiberStatus.FiberStatus => new Suspended(runtimeFlags, blockingOn)\n\n/** @internal */\nexport const isFiberStatus = (u: unknown): u is FiberStatus.FiberStatus => hasProperty(u, FiberStatusTypeId)\n\n/** @internal */\nexport const isDone = (self: FiberStatus.FiberStatus): self is FiberStatus.Done => self._tag === OP_DONE\n\n/** @internal */\nexport const isRunning = (self: FiberStatus.FiberStatus): self is FiberStatus.Running => self._tag === OP_RUNNING\n\n/** @internal */\nexport const isSuspended = (self: FiberStatus.FiberStatus): self is FiberStatus.Suspended => self._tag === OP_SUSPENDED\n"
  },
  {
    "path": "packages/effect/src/internal/groupBy.ts",
    "content": "import * as Cause from \"../Cause.js\"\nimport type * as Channel from \"../Channel.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport * as Deferred from \"../Deferred.js\"\nimport * as Effect from \"../Effect.js\"\nimport * as Effectable from \"../Effectable.js\"\nimport * as Exit from \"../Exit.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport type * as GroupBy from \"../GroupBy.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty, type Predicate } from \"../Predicate.js\"\nimport * as Queue from \"../Queue.js\"\nimport * as Ref from \"../Ref.js\"\nimport * as Scope from \"../Scope.js\"\nimport type * as Stream from \"../Stream.js\"\nimport type * as Take from \"../Take.js\"\nimport type { NoInfer } from \"../Types.js\"\nimport * as channel from \"./channel.js\"\nimport * as channelExecutor from \"./channel/channelExecutor.js\"\nimport * as core from \"./core-stream.js\"\nimport * as stream from \"./stream.js\"\nimport * as take from \"./take.js\"\n\n/** @internal */\nconst GroupBySymbolKey = \"effect/GroupBy\"\n\n/** @internal */\nexport const GroupByTypeId: GroupBy.GroupByTypeId = Symbol.for(\n  GroupBySymbolKey\n) as GroupBy.GroupByTypeId\n\nconst groupByVariance = {\n  /* c8 ignore next */\n  _R: (_: never) => _,\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _K: (_: never) => _,\n  /* c8 ignore next */\n  _V: (_: never) => _\n}\n\n/** @internal */\nexport const isGroupBy = (u: unknown): u is GroupBy.GroupBy<unknown, unknown, unknown, unknown> =>\n  hasProperty(u, GroupByTypeId)\n\n/** @internal */\nexport const evaluate = dual<\n  <K, V, E, A, E2, R2>(\n    f: (key: K, stream: Stream.Stream<V, E>) => Stream.Stream<A, E2, R2>,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ) => <R>(self: GroupBy.GroupBy<K, V, E, R>) => Stream.Stream<A, E | E2, R2 | R>,\n  <K, V, E, R, A, E2, R2>(\n    self: GroupBy.GroupBy<K, V, E, R>,\n    f: (key: K, stream: Stream.Stream<V, E>) => Stream.Stream<A, E2, R2>,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ) => Stream.Stream<A, E | E2, R2 | R>\n>(\n  (args) => isGroupBy(args[0]),\n  <K, V, E, R, A, E2, R2>(\n    self: GroupBy.GroupBy<K, V, E, R>,\n    f: (key: K, stream: Stream.Stream<V, E>) => Stream.Stream<A, E2, R2>,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ): Stream.Stream<A, E | E2, R2 | R> =>\n    stream.flatMap(\n      self.grouped,\n      ([key, queue]) => f(key, stream.flattenTake(stream.fromQueue(queue, { shutdown: true }))),\n      { concurrency: \"unbounded\", bufferSize: options?.bufferSize ?? 16 }\n    )\n)\n\n/** @internal */\nexport const filter = dual<\n  <K>(predicate: Predicate<NoInfer<K>>) => <V, E, R>(self: GroupBy.GroupBy<K, V, E, R>) => GroupBy.GroupBy<K, V, E, R>,\n  <K, V, E, R>(self: GroupBy.GroupBy<K, V, E, R>, predicate: Predicate<K>) => GroupBy.GroupBy<K, V, E, R>\n>(2, <K, V, E, R>(self: GroupBy.GroupBy<K, V, E, R>, predicate: Predicate<K>): GroupBy.GroupBy<K, V, E, R> =>\n  make(\n    pipe(\n      self.grouped,\n      stream.filterEffect((tuple) => {\n        if (predicate(tuple[0])) {\n          return pipe(Effect.succeed(tuple), Effect.as(true))\n        }\n        return pipe(Queue.shutdown(tuple[1]), Effect.as(false))\n      })\n    )\n  ))\n\n/** @internal */\nexport const first = dual<\n  (n: number) => <K, V, E, R>(self: GroupBy.GroupBy<K, V, E, R>) => GroupBy.GroupBy<K, V, E, R>,\n  <K, V, E, R>(self: GroupBy.GroupBy<K, V, E, R>, n: number) => GroupBy.GroupBy<K, V, E, R>\n>(2, <K, V, E, R>(self: GroupBy.GroupBy<K, V, E, R>, n: number): GroupBy.GroupBy<K, V, E, R> =>\n  make(\n    pipe(\n      stream.zipWithIndex(self.grouped),\n      stream.filterEffect((tuple) => {\n        const index = tuple[1]\n        const queue = tuple[0][1]\n        if (index < n) {\n          return pipe(Effect.succeed(tuple), Effect.as(true))\n        }\n        return pipe(Queue.shutdown(queue), Effect.as(false))\n      }),\n      stream.map((tuple) => tuple[0])\n    )\n  ))\n\n/** @internal */\nexport const make = <K, V, E, R>(\n  grouped: Stream.Stream<readonly [K, Queue.Dequeue<Take.Take<V, E>>], E, R>\n): GroupBy.GroupBy<K, V, E, R> => ({\n  [GroupByTypeId]: groupByVariance,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  grouped\n})\n\n// Circular with Stream\n\n/** @internal */\nexport const groupBy = dual<\n  <A, K, V, E2, R2>(\n    f: (a: A) => Effect.Effect<readonly [K, V], E2, R2>,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => GroupBy.GroupBy<K, V, E2 | E, R2 | R>,\n  <A, E, R, K, V, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<readonly [K, V], E2, R2>,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ) => GroupBy.GroupBy<K, V, E2 | E, R2 | R>\n>(\n  (args) => stream.isStream(args[0]),\n  <A, E, R, K, V, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<readonly [K, V], E2, R2>,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ): GroupBy.GroupBy<K, V, E | E2, R | R2> =>\n    make(\n      stream.unwrapScoped(\n        Effect.gen(function*() {\n          const decider = yield* Deferred.make<(key: K, value: V) => Effect.Effect<Predicate<number>>>()\n          const output = yield* Effect.acquireRelease(\n            Queue.bounded<Exit.Exit<readonly [K, Queue.Dequeue<Take.Take<V, E | E2>>], Option.Option<E | E2>>>(\n              options?.bufferSize ?? 16\n            ),\n            (queue) => Queue.shutdown(queue)\n          )\n          const ref = yield* Ref.make<Map<K, number>>(new Map())\n          const add = yield* pipe(\n            stream.mapEffectSequential(self, f),\n            stream.distributedWithDynamicCallback(\n              options?.bufferSize ?? 16,\n              ([key, value]) => Effect.flatMap(Deferred.await(decider), (f) => f(key, value)),\n              (exit) => Queue.offer(output, exit)\n            )\n          )\n          yield* Deferred.succeed(decider, (key, _) =>\n            pipe(\n              Ref.get(ref),\n              Effect.map((map) => Option.fromNullable(map.get(key))),\n              Effect.flatMap(Option.match({\n                onNone: () =>\n                  Effect.flatMap(add, ([index, queue]) =>\n                    Effect.zipRight(\n                      Ref.update(ref, (map) => map.set(key, index)),\n                      pipe(\n                        Queue.offer(\n                          output,\n                          Exit.succeed(\n                            [\n                              key,\n                              mapDequeue(queue, (exit) =>\n                                new take.TakeImpl(pipe(\n                                  exit,\n                                  Exit.map((tuple) => Chunk.of(tuple[1]))\n                                )))\n                            ] as const\n                          )\n                        ),\n                        Effect.as<Predicate<number>>((n: number) => n === index)\n                      )\n                    )),\n                onSome: (index) => Effect.succeed<Predicate<number>>((n: number) => n === index)\n              }))\n            ))\n          return stream.flattenExitOption(stream.fromQueue(output, { shutdown: true }))\n        })\n      )\n    )\n)\n\n/** @internal */\nexport const mapEffectOptions = dual<\n  {\n    <A, A2, E2, R2>(\n      f: (a: A) => Effect.Effect<A2, E2, R2>,\n      options?: {\n        readonly concurrency?: number | \"unbounded\" | undefined\n        readonly unordered?: boolean | undefined\n      }\n    ): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>\n    <A, A2, E2, R2, K>(\n      f: (a: A) => Effect.Effect<A2, E2, R2>,\n      options: {\n        readonly key: (a: A) => K\n        readonly bufferSize?: number | undefined\n      }\n    ): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>\n  },\n  {\n    <A, E, R, A2, E2, R2>(\n      self: Stream.Stream<A, E, R>,\n      f: (a: A) => Effect.Effect<A2, E2, R2>,\n      options?: {\n        readonly concurrency?: number | \"unbounded\" | undefined\n        readonly unordered?: boolean | undefined\n      }\n    ): Stream.Stream<A2, E2 | E, R2 | R>\n    <A, E, R, A2, E2, R2, K>(\n      self: Stream.Stream<A, E, R>,\n      f: (a: A) => Effect.Effect<A2, E2, R2>,\n      options: {\n        readonly key: (a: A) => K\n        readonly bufferSize?: number | undefined\n      }\n    ): Stream.Stream<A2, E2 | E, R2 | R>\n  }\n>(\n  (args) => typeof args[0] !== \"function\",\n  (<A, E, R, A2, E2, R2, K>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<A2, E2, R2>,\n    options?: {\n      readonly key?: ((a: A) => K) | undefined\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly unordered?: boolean | undefined\n      readonly bufferSize?: number | undefined\n    }\n  ): Stream.Stream<A2, E2 | E, R2 | R> => {\n    if (options?.key) {\n      return evaluate(\n        groupByKey(self, options.key, { bufferSize: options.bufferSize }),\n        (_, s) => stream.mapEffectSequential(s, f)\n      )\n    }\n\n    return stream.matchConcurrency(\n      options?.concurrency,\n      () => stream.mapEffectSequential(self, f),\n      (n) =>\n        options?.unordered ?\n          stream.flatMap(self, (a) => stream.fromEffect(f(a)), { concurrency: n }) :\n          stream.mapEffectPar(self, n, f)\n    )\n  }) as any\n)\n\n/** @internal */\nexport const bindEffect = dual<\n  <N extends string, A, B, E2, R2>(\n    tag: Exclude<N, keyof A>,\n    f: (_: NoInfer<A>) => Effect.Effect<B, E2, R2>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly bufferSize?: number | undefined\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<\n    { [K in keyof A | N]: K extends keyof A ? A[K] : B },\n    E | E2,\n    R | R2\n  >,\n  <A, E, R, N extends string, B, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    tag: Exclude<N, keyof A>,\n    f: (_: NoInfer<A>) => Effect.Effect<B, E2, R2>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly unordered?: boolean | undefined\n    }\n  ) => Stream.Stream<\n    { [K in keyof A | N]: K extends keyof A ? A[K] : B },\n    E | E2,\n    R | R2\n  >\n>((args) => typeof args[0] !== \"string\", <A, E, R, N extends string, B, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  tag: Exclude<N, keyof A>,\n  f: (_: A) => Effect.Effect<B, E2, R2>,\n  options?: {\n    readonly concurrency?: number | \"unbounded\" | undefined\n    readonly unordered?: boolean | undefined\n  }\n) =>\n  mapEffectOptions(self, (k) =>\n    Effect.map(\n      f(k),\n      (a) => ({ ...k, [tag]: a } as { [K in keyof A | N]: K extends keyof A ? A[K] : B })\n    ), options))\n\nconst mapDequeue = <A, B>(dequeue: Queue.Dequeue<A>, f: (a: A) => B): Queue.Dequeue<B> => new MapDequeue(dequeue, f)\n\nclass MapDequeue<in out A, out B> extends Effectable.Class<B> implements Queue.Dequeue<B> {\n  readonly [Queue.DequeueTypeId] = {\n    _Out: (_: never) => _\n  }\n\n  constructor(\n    readonly dequeue: Queue.Dequeue<A>,\n    readonly f: (a: A) => B\n  ) {\n    super()\n  }\n\n  capacity(): number {\n    return Queue.capacity(this.dequeue)\n  }\n\n  get size(): Effect.Effect<number> {\n    return Queue.size(this.dequeue)\n  }\n\n  unsafeSize(): Option.Option<number> {\n    return this.dequeue.unsafeSize()\n  }\n\n  get awaitShutdown(): Effect.Effect<void> {\n    return Queue.awaitShutdown(this.dequeue)\n  }\n\n  isActive(): boolean {\n    return this.dequeue.isActive()\n  }\n\n  get isShutdown(): Effect.Effect<boolean> {\n    return Queue.isShutdown(this.dequeue)\n  }\n\n  get shutdown(): Effect.Effect<void> {\n    return Queue.shutdown(this.dequeue)\n  }\n\n  get isFull(): Effect.Effect<boolean> {\n    return Queue.isFull(this.dequeue)\n  }\n\n  get isEmpty(): Effect.Effect<boolean> {\n    return Queue.isEmpty(this.dequeue)\n  }\n\n  get take(): Effect.Effect<B> {\n    return pipe(Queue.take(this.dequeue), Effect.map((a) => this.f(a)))\n  }\n\n  get takeAll(): Effect.Effect<Chunk.Chunk<B>> {\n    return pipe(Queue.takeAll(this.dequeue), Effect.map(Chunk.map((a) => this.f(a))))\n  }\n\n  takeUpTo(max: number): Effect.Effect<Chunk.Chunk<B>> {\n    return pipe(Queue.takeUpTo(this.dequeue, max), Effect.map(Chunk.map((a) => this.f(a))))\n  }\n\n  takeBetween(min: number, max: number): Effect.Effect<Chunk.Chunk<B>> {\n    return pipe(Queue.takeBetween(this.dequeue, min, max), Effect.map(Chunk.map((a) => this.f(a))))\n  }\n\n  takeN(n: number): Effect.Effect<Chunk.Chunk<B>> {\n    return pipe(Queue.takeN(this.dequeue, n), Effect.map(Chunk.map((a) => this.f(a))))\n  }\n\n  poll(): Effect.Effect<Option.Option<B>> {\n    return pipe(Queue.poll(this.dequeue), Effect.map(Option.map((a) => this.f(a))))\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n\n  commit() {\n    return this.take\n  }\n}\n\n/** @internal */\nexport const groupByKey = dual<\n  <A, K>(\n    f: (a: A) => K,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => GroupBy.GroupBy<K, A, E, R>,\n  <A, E, R, K>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => K,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ) => GroupBy.GroupBy<K, A, E, R>\n>(\n  (args) => typeof args[0] !== \"function\",\n  <A, E, R, K>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => K,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ): GroupBy.GroupBy<K, A, E, R> => {\n    const loop = (\n      map: Map<K, Queue.Queue<Take.Take<A, E>>>,\n      outerQueue: Queue.Queue<Take.Take<readonly [K, Queue.Queue<Take.Take<A, E>>], E>>\n    ): Channel.Channel<never, Chunk.Chunk<A>, E, E, unknown, unknown, R> =>\n      core.readWithCause({\n        onInput: (input: Chunk.Chunk<A>) =>\n          core.flatMap(\n            core.fromEffect(\n              Effect.forEach(groupByIterable(input, f), ([key, values]) => {\n                const innerQueue = map.get(key)\n                if (innerQueue === undefined) {\n                  return pipe(\n                    Queue.bounded<Take.Take<A, E>>(options?.bufferSize ?? 16),\n                    Effect.flatMap((innerQueue) =>\n                      pipe(\n                        Effect.sync(() => {\n                          map.set(key, innerQueue)\n                        }),\n                        Effect.zipRight(\n                          Queue.offer(outerQueue, take.of([key, innerQueue] as const))\n                        ),\n                        Effect.zipRight(\n                          pipe(\n                            Queue.offer(innerQueue, take.chunk(values)),\n                            Effect.catchSomeCause((cause) =>\n                              Cause.isInterruptedOnly(cause) ?\n                                Option.some(Effect.void) :\n                                Option.none()\n                            )\n                          )\n                        )\n                      )\n                    )\n                  )\n                }\n                return Effect.catchSomeCause(\n                  Queue.offer(innerQueue, take.chunk(values)),\n                  (cause) =>\n                    Cause.isInterruptedOnly(cause) ?\n                      Option.some(Effect.void) :\n                      Option.none()\n                )\n              }, { discard: true })\n            ),\n            () => loop(map, outerQueue)\n          ),\n        onFailure: (cause) => core.fromEffect(Queue.offer(outerQueue, take.failCause(cause))),\n        onDone: () =>\n          core.fromEffect(\n            pipe(\n              Effect.forEach(map.entries(), ([_, innerQueue]) =>\n                pipe(\n                  Queue.offer(innerQueue, take.end),\n                  Effect.catchSomeCause((cause) =>\n                    Cause.isInterruptedOnly(cause) ?\n                      Option.some(Effect.void) :\n                      Option.none()\n                  )\n                ), { discard: true }),\n              Effect.zipRight(Queue.offer(outerQueue, take.end))\n            )\n          )\n      })\n    return make(stream.unwrapScopedWith((scope) =>\n      Effect.gen(function*() {\n        const map = new Map<K, Queue.Queue<Take.Take<A, E>>>()\n        const queue = yield* Queue.unbounded<Take.Take<readonly [K, Queue.Queue<Take.Take<A, E>>], E>>()\n        yield* Scope.addFinalizer(scope, Queue.shutdown(queue))\n        return yield* stream.toChannel(self).pipe(\n          core.pipeTo(loop(map, queue)),\n          channel.drain,\n          channelExecutor.runIn(scope),\n          Effect.forkIn(scope),\n          Effect.as(stream.flattenTake(stream.fromQueue(queue, { shutdown: true })))\n        )\n      })\n    ))\n  }\n)\n\n/**\n * A variant of `groupBy` that retains the insertion order of keys.\n *\n * @internal\n */\nconst groupByIterable = dual<\n  <V, K>(f: (value: V) => K) => (iterable: Iterable<V>) => Chunk.Chunk<[K, Chunk.Chunk<V>]>,\n  <V, K>(iterable: Iterable<V>, f: (value: V) => K) => Chunk.Chunk<[K, Chunk.Chunk<V>]>\n>(2, <V, K>(iterable: Iterable<V>, f: (value: V) => K): Chunk.Chunk<[K, Chunk.Chunk<V>]> => {\n  const builder: Array<[K, Array<V>]> = []\n  const iterator = iterable[Symbol.iterator]()\n  const map = new Map<K, Array<V>>()\n  let next: IteratorResult<V, any>\n  while ((next = iterator.next()) && !next.done) {\n    const value = next.value\n    const key = f(value)\n    if (map.has(key)) {\n      const innerBuilder = map.get(key)!\n      innerBuilder.push(value)\n    } else {\n      const innerBuilder: Array<V> = [value]\n      builder.push([key, innerBuilder])\n      map.set(key, innerBuilder)\n    }\n  }\n  return Chunk.unsafeFromArray(\n    builder.map((tuple) => [tuple[0], Chunk.unsafeFromArray(tuple[1])])\n  )\n})\n"
  },
  {
    "path": "packages/effect/src/internal/hashMap/array.ts",
    "content": "/** @internal */\nexport function arrayUpdate<A>(mutate: boolean, at: number, v: A, arr: Array<A>) {\n  let out = arr\n  if (!mutate) {\n    const len = arr.length\n    out = new Array(len)\n    for (let i = 0; i < len; ++i) out[i] = arr[i]!\n  }\n  out[at] = v\n  return out\n}\n\n/** @internal */\nexport function arraySpliceOut<A>(mutate: boolean, at: number, arr: Array<A>) {\n  const newLen = arr.length - 1\n  let i = 0\n  let g = 0\n  let out = arr\n  if (mutate) {\n    i = g = at\n  } else {\n    out = new Array(newLen)\n    while (i < at) out[g++] = arr[i++]!\n  }\n  ++i\n  while (i <= newLen) out[g++] = arr[i++]!\n  if (mutate) {\n    out.length = newLen\n  }\n  return out\n}\n\n/** @internal */\nexport function arraySpliceIn<A>(mutate: boolean, at: number, v: A, arr: Array<A>) {\n  const len = arr.length\n  if (mutate) {\n    let i = len\n    while (i >= at) arr[i--] = arr[i]!\n    arr[at] = v\n    return arr\n  }\n  let i = 0,\n    g = 0\n  const out = new Array<A>(len + 1)\n  while (i < at) out[g++] = arr[i++]!\n  out[at] = v\n  while (i < len) out[++g] = arr[i++]!\n  return out\n}\n"
  },
  {
    "path": "packages/effect/src/internal/hashMap/bitwise.ts",
    "content": "import { MASK } from \"./config.js\"\n\n/**\n * Hamming weight.\n *\n * Taken from: http://jsperf.com/hamming-weight\n *\n * @internal\n */\nexport function popcount(x: number) {\n  x -= (x >> 1) & 0x55555555\n  x = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n  x = (x + (x >> 4)) & 0x0f0f0f0f\n  x += x >> 8\n  x += x >> 16\n  return x & 0x7f\n}\n\n/** @internal */\nexport function hashFragment(shift: number, h: number) {\n  return (h >>> shift) & MASK\n}\n\n/** @internal */\nexport function toBitmap(x: number) {\n  return 1 << x\n}\n\n/** @internal */\nexport function fromBitmap(bitmap: number, bit: number) {\n  return popcount(bitmap & (bit - 1))\n}\n"
  },
  {
    "path": "packages/effect/src/internal/hashMap/config.ts",
    "content": "/** @internal */\nexport const SIZE = 5\n\n/** @internal */\nexport const BUCKET_SIZE = Math.pow(2, SIZE)\n\n/** @internal */\nexport const MASK = BUCKET_SIZE - 1\n\n/** @internal */\nexport const MAX_INDEX_NODE = BUCKET_SIZE / 2\n\n/** @internal */\nexport const MIN_ARRAY_NODE = BUCKET_SIZE / 4\n"
  },
  {
    "path": "packages/effect/src/internal/hashMap/keySet.ts",
    "content": "import type { HashMap } from \"../../HashMap.js\"\nimport type { HashSet } from \"../../HashSet.js\"\nimport { makeImpl } from \"../hashSet.js\"\n\n/** @internal */\nexport function keySet<K, V>(self: HashMap<K, V>): HashSet<K> {\n  return makeImpl(self)\n}\n"
  },
  {
    "path": "packages/effect/src/internal/hashMap/node.ts",
    "content": "import { equals } from \"../../Equal.js\"\nimport type { HashMap } from \"../../HashMap.js\"\nimport * as O from \"../../Option.js\"\nimport { isTagged } from \"../../Predicate.js\"\nimport * as Stack from \"../stack.js\"\nimport { arraySpliceIn, arraySpliceOut, arrayUpdate } from \"./array.js\"\nimport { fromBitmap, hashFragment, toBitmap } from \"./bitwise.js\"\nimport { MAX_INDEX_NODE, MIN_ARRAY_NODE, SIZE } from \"./config.js\"\n\n/** @internal */\nexport type Node<K, V> =\n  | EmptyNode<K, V>\n  | LeafNode<K, V>\n  | CollisionNode<K, V>\n  | IndexedNode<K, V>\n  | ArrayNode<K, V>\n\n/** @internal */\nexport interface SizeRef {\n  value: number // mutable by design\n}\n\n/** @internal */\nexport class EmptyNode<out K, out V> {\n  readonly _tag = \"EmptyNode\"\n\n  modify(\n    edit: number,\n    _shift: number,\n    f: HashMap.UpdateFn<V>,\n    hash: number,\n    key: K,\n    size: SizeRef\n  ): Node<K, V> {\n    const v = f(O.none())\n    if (O.isNone(v)) return new EmptyNode()\n    ++size.value\n    return new LeafNode(edit, hash, key, v)\n  }\n}\n\n/** @internal */\nexport function isEmptyNode(a: unknown): a is EmptyNode<unknown, unknown> {\n  return isTagged(a, \"EmptyNode\")\n}\n\n/** @internal */\nexport function isLeafNode<K, V>(\n  node: Node<K, V>\n): node is EmptyNode<K, V> | LeafNode<K, V> | CollisionNode<K, V> {\n  return isEmptyNode(node) || node._tag === \"LeafNode\" || node._tag === \"CollisionNode\"\n}\n\n/** @internal */\nexport function canEditNode<K, V>(node: Node<K, V>, edit: number): boolean {\n  return isEmptyNode(node) ? false : edit === node.edit\n}\n\n/** @internal */\nexport class LeafNode<out K, out V> {\n  readonly _tag = \"LeafNode\"\n\n  constructor(\n    readonly edit: number,\n    readonly hash: number,\n    readonly key: K,\n    public value: O.Option<V>\n  ) {}\n\n  modify(\n    edit: number,\n    shift: number,\n    f: HashMap.UpdateFn<V>,\n    hash: number,\n    key: K,\n    size: SizeRef\n  ): Node<K, V> {\n    if (equals(key, this.key)) {\n      const v = f(this.value)\n      if (v === this.value) return this\n      else if (O.isNone(v)) {\n        --size.value\n        return new EmptyNode()\n      }\n      if (canEditNode(this, edit)) {\n        this.value = v\n        return this\n      }\n      return new LeafNode(edit, hash, key, v)\n    }\n    const v = f(O.none())\n    if (O.isNone(v)) return this\n    ++size.value\n    return mergeLeaves(\n      edit,\n      shift,\n      this.hash,\n      this,\n      hash,\n      new LeafNode(edit, hash, key, v)\n    )\n  }\n}\n\n/** @internal */\nexport class CollisionNode<out K, out V> {\n  readonly _tag = \"CollisionNode\"\n\n  constructor(\n    readonly edit: number,\n    readonly hash: number,\n    readonly children: Array<Node<K, V>>\n  ) {}\n\n  modify(\n    edit: number,\n    shift: number,\n    f: HashMap.UpdateFn<V>,\n    hash: number,\n    key: K,\n    size: SizeRef\n  ): Node<K, V> {\n    if (hash === this.hash) {\n      const canEdit = canEditNode(this, edit)\n      const list = this.updateCollisionList(\n        canEdit,\n        edit,\n        this.hash,\n        this.children,\n        f,\n        key,\n        size\n      )\n      if (list === this.children) return this\n\n      return list.length > 1 ? new CollisionNode(edit, this.hash, list) : list[0]! // collapse single element collision list\n    }\n    const v = f(O.none())\n    if (O.isNone(v)) return this\n    ++size.value\n    return mergeLeaves(\n      edit,\n      shift,\n      this.hash,\n      this,\n      hash,\n      new LeafNode(edit, hash, key, v)\n    )\n  }\n\n  updateCollisionList(\n    mutate: boolean,\n    edit: number,\n    hash: number,\n    list: Array<Node<K, V>>,\n    f: HashMap.UpdateFn<V>,\n    key: K,\n    size: SizeRef\n  ) {\n    const len = list.length\n    for (let i = 0; i < len; ++i) {\n      const child = list[i]!\n      if (\"key\" in child && equals(key, child.key)) {\n        const value = child.value\n        const newValue = f(value)\n        if (newValue === value) return list\n        if (O.isNone(newValue)) {\n          --size.value\n          return arraySpliceOut(mutate, i, list)\n        }\n        return arrayUpdate(mutate, i, new LeafNode(edit, hash, key, newValue), list)\n      }\n    }\n\n    const newValue = f(O.none())\n    if (O.isNone(newValue)) return list\n    ++size.value\n    return arrayUpdate(mutate, len, new LeafNode(edit, hash, key, newValue), list)\n  }\n}\n\n/** @internal */\nexport class IndexedNode<out K, out V> {\n  readonly _tag = \"IndexedNode\"\n\n  constructor(\n    readonly edit: number,\n    public mask: number,\n    public children: Array<Node<K, V>>\n  ) {}\n\n  modify(\n    edit: number,\n    shift: number,\n    f: HashMap.UpdateFn<V>,\n    hash: number,\n    key: K,\n    size: SizeRef\n  ): Node<K, V> {\n    const mask = this.mask\n    const children = this.children\n    const frag = hashFragment(shift, hash)\n    const bit = toBitmap(frag)\n    const indx = fromBitmap(mask, bit)\n    const exists = mask & bit\n    const canEdit = canEditNode(this, edit)\n\n    if (!exists) {\n      const _newChild = new EmptyNode<K, V>().modify(edit, shift + SIZE, f, hash, key, size)\n      if (!_newChild) return this\n      return children.length >= MAX_INDEX_NODE ?\n        expand(edit, frag, _newChild, mask, children) :\n        new IndexedNode(edit, mask | bit, arraySpliceIn(canEdit, indx, _newChild, children))\n    }\n\n    const current = children[indx]!\n    const child = current.modify(edit, shift + SIZE, f, hash, key, size)\n\n    if (current === child) return this\n    let bitmap = mask\n    let newChildren\n    if (isEmptyNode(child)) {\n      // remove\n      bitmap &= ~bit\n      if (!bitmap) return new EmptyNode()\n      if (children.length <= 2 && isLeafNode(children[indx ^ 1]!)) {\n        return children[indx ^ 1]! // collapse\n      }\n\n      newChildren = arraySpliceOut(canEdit, indx, children)\n    } else {\n      // modify\n      newChildren = arrayUpdate(canEdit, indx, child, children)\n    }\n\n    if (canEdit) {\n      this.mask = bitmap\n      this.children = newChildren\n      return this\n    }\n\n    return new IndexedNode(edit, bitmap, newChildren)\n  }\n}\n\n/** @internal */\nexport class ArrayNode<out K, out V> {\n  readonly _tag = \"ArrayNode\"\n\n  constructor(\n    readonly edit: number,\n    public size: number,\n    public children: Array<Node<K, V>>\n  ) {}\n\n  modify(\n    edit: number,\n    shift: number,\n    f: HashMap.UpdateFn<V>,\n    hash: number,\n    key: K,\n    size: SizeRef\n  ): Node<K, V> {\n    let count = this.size\n    const children = this.children\n    const frag = hashFragment(shift, hash)\n    const child = children[frag]\n    const newChild = (child || new EmptyNode<K, V>()).modify(\n      edit,\n      shift + SIZE,\n      f,\n      hash,\n      key,\n      size\n    )\n\n    if (child === newChild) return this\n\n    const canEdit = canEditNode(this, edit)\n    let newChildren\n    if (isEmptyNode(child) && !isEmptyNode(newChild)) {\n      // add\n      ++count\n      newChildren = arrayUpdate(canEdit, frag, newChild, children)\n    } else if (!isEmptyNode(child) && isEmptyNode(newChild)) {\n      // remove\n      --count\n      if (count <= MIN_ARRAY_NODE) {\n        return pack(edit, count, frag, children)\n      }\n      newChildren = arrayUpdate(canEdit, frag, new EmptyNode<K, V>(), children)\n    } else {\n      // modify\n      newChildren = arrayUpdate(canEdit, frag, newChild, children)\n    }\n\n    if (canEdit) {\n      this.size = count\n      this.children = newChildren\n      return this\n    }\n    return new ArrayNode(edit, count, newChildren)\n  }\n}\n\nfunction pack<K, V>(\n  edit: number,\n  count: number,\n  removed: number,\n  elements: Array<Node<K, V>>\n) {\n  const children = new Array<Node<K, V>>(count - 1)\n  let g = 0\n  let bitmap = 0\n  for (let i = 0, len = elements.length; i < len; ++i) {\n    if (i !== removed) {\n      const elem = elements[i]\n      if (elem && !isEmptyNode(elem)) {\n        children[g++] = elem\n        bitmap |= 1 << i\n      }\n    }\n  }\n  return new IndexedNode(edit, bitmap, children)\n}\n\nfunction expand<K, V>(\n  edit: number,\n  frag: number,\n  child: Node<K, V>,\n  bitmap: number,\n  subNodes: Array<Node<K, V>>\n) {\n  const arr = []\n  let bit = bitmap\n  let count = 0\n  for (let i = 0; bit; ++i) {\n    if (bit & 1) arr[i] = subNodes[count++]!\n    bit >>>= 1\n  }\n  arr[frag] = child\n  return new ArrayNode(edit, count + 1, arr)\n}\n\nfunction mergeLeavesInner<K, V>(\n  edit: number,\n  shift: number,\n  h1: number,\n  n1: Node<K, V>,\n  h2: number,\n  n2: Node<K, V>\n): Node<K, V> | ((child: Node<K, V>) => Node<K, V>) {\n  if (h1 === h2) return new CollisionNode(edit, h1, [n2, n1])\n  const subH1 = hashFragment(shift, h1)\n  const subH2 = hashFragment(shift, h2)\n\n  if (subH1 === subH2) {\n    return (child) => new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), [child])\n  } else {\n    const children = subH1 < subH2 ? [n1, n2] : [n2, n1]\n    return new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), children)\n  }\n}\n\nfunction mergeLeaves<K, V>(\n  edit: number,\n  shift: number,\n  h1: number,\n  n1: Node<K, V>,\n  h2: number,\n  n2: Node<K, V>\n): Node<K, V> {\n  let stack: Stack.Stack<(node: Node<K, V>) => Node<K, V>> | undefined = undefined\n  let currentShift = shift\n\n  while (true) {\n    const res = mergeLeavesInner(edit, currentShift, h1, n1, h2, n2)\n\n    if (typeof res === \"function\") {\n      stack = Stack.make(res, stack)\n      currentShift = currentShift + SIZE\n    } else {\n      let final = res\n      while (stack != null) {\n        final = stack.value(final)\n        stack = stack.previous\n      }\n      return final\n    }\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/hashMap.ts",
    "content": "import * as Equal from \"../Equal.js\"\nimport * as Dual from \"../Function.js\"\nimport { identity, pipe } from \"../Function.js\"\nimport * as Hash from \"../Hash.js\"\nimport type * as HM from \"../HashMap.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"../Inspectable.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type { NoInfer } from \"../Types.js\"\nimport { fromBitmap, hashFragment, toBitmap } from \"./hashMap/bitwise.js\"\nimport { SIZE } from \"./hashMap/config.js\"\nimport * as Node from \"./hashMap/node.js\"\n\nconst HashMapSymbolKey = \"effect/HashMap\"\n\n/** @internal */\nexport const HashMapTypeId: HM.TypeId = Symbol.for(HashMapSymbolKey) as HM.TypeId\n\ntype TraversalFn<K, V, A> = (k: K, v: V) => A\n\ntype Cont<K, V, A> =\n  | [\n    len: number,\n    children: Array<Node.Node<K, V>>,\n    i: number,\n    f: TraversalFn<K, V, A>,\n    cont: Cont<K, V, A>\n  ]\n  | undefined\n\ninterface VisitResult<K, V, A> {\n  value: A\n  cont: Cont<K, V, A>\n}\n\n/** @internal */\nexport interface HashMapImpl<out K, out V> extends HM.HashMap<K, V> {\n  _editable: boolean // mutable by design\n  _edit: number // mutable by design\n  _root: Node.Node<K, V> // mutable by design\n  _size: number // mutable by design\n}\n\nconst HashMapProto: HM.HashMap<unknown, unknown> = {\n  [HashMapTypeId]: HashMapTypeId,\n  [Symbol.iterator]<K, V>(this: HashMapImpl<K, V>): Iterator<[K, V]> {\n    return new HashMapIterator(this, (k, v) => [k, v])\n  },\n  [Hash.symbol](this: HM.HashMap<unknown, unknown>): number {\n    let hash = Hash.hash(HashMapSymbolKey)\n    for (const item of this) {\n      hash ^= pipe(Hash.hash(item[0]), Hash.combine(Hash.hash(item[1])))\n    }\n    return Hash.cached(this, hash)\n  },\n  [Equal.symbol]<K, V>(this: HashMapImpl<K, V>, that: unknown): boolean {\n    if (isHashMap(that)) {\n      if ((that as HashMapImpl<K, V>)._size !== this._size) {\n        return false\n      }\n      for (const item of this) {\n        const elem = pipe(\n          that as HM.HashMap<K, V>,\n          getHash(item[0], Hash.hash(item[0]))\n        )\n        if (Option.isNone(elem)) {\n          return false\n        } else {\n          if (!Equal.equals(item[1], elem.value)) {\n            return false\n          }\n        }\n      }\n      return true\n    }\n    return false\n  },\n  toString<K, V>(this: HashMapImpl<K, V>) {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"HashMap\",\n      values: Array.from(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makeImpl = <K, V>(\n  editable: boolean,\n  edit: number,\n  root: Node.Node<K, V>,\n  size: number\n): HashMapImpl<K, V> => {\n  const map = Object.create(HashMapProto)\n  map._editable = editable\n  map._edit = edit\n  map._root = root\n  map._size = size\n  return map\n}\n\nclass HashMapIterator<in out K, in out V, out T> implements IterableIterator<T> {\n  v: Option.Option<VisitResult<K, V, T>>\n\n  constructor(readonly map: HashMapImpl<K, V>, readonly f: TraversalFn<K, V, T>) {\n    this.v = visitLazy(this.map._root, this.f, undefined)\n  }\n\n  next(): IteratorResult<T> {\n    if (Option.isNone(this.v)) {\n      return { done: true, value: undefined }\n    }\n    const v0 = this.v.value\n    this.v = applyCont(v0.cont)\n    return { done: false, value: v0.value }\n  }\n\n  [Symbol.iterator](): IterableIterator<T> {\n    return new HashMapIterator(this.map, this.f)\n  }\n}\n\nconst applyCont = <K, V, A>(cont: Cont<K, V, A>): Option.Option<VisitResult<K, V, A>> =>\n  cont\n    ? visitLazyChildren(cont[0], cont[1], cont[2], cont[3], cont[4])\n    : Option.none()\n\nconst visitLazy = <K, V, A>(\n  node: Node.Node<K, V>,\n  f: TraversalFn<K, V, A>,\n  cont: Cont<K, V, A> = undefined\n): Option.Option<VisitResult<K, V, A>> => {\n  switch (node._tag) {\n    case \"LeafNode\": {\n      if (Option.isSome(node.value)) {\n        return Option.some({\n          value: f(node.key, node.value.value),\n          cont\n        })\n      }\n      return applyCont(cont)\n    }\n    case \"CollisionNode\":\n    case \"ArrayNode\":\n    case \"IndexedNode\": {\n      const children = node.children\n      return visitLazyChildren(children.length, children, 0, f, cont)\n    }\n    default: {\n      return applyCont(cont)\n    }\n  }\n}\n\nconst visitLazyChildren = <K, V, A>(\n  len: number,\n  children: Array<Node.Node<K, V>>,\n  i: number,\n  f: TraversalFn<K, V, A>,\n  cont: Cont<K, V, A>\n): Option.Option<VisitResult<K, V, A>> => {\n  while (i < len) {\n    const child = children[i++]\n    if (child && !Node.isEmptyNode(child)) {\n      return visitLazy(child, f, [len, children, i, f, cont])\n    }\n  }\n  return applyCont(cont)\n}\n\nconst _empty = makeImpl<never, never>(false, 0, new Node.EmptyNode(), 0)\n\n/** @internal */\nexport const empty = <K = never, V = never>(): HM.HashMap<K, V> => _empty\n\n/** @internal */\nexport const make = <Entries extends ReadonlyArray<readonly [any, any]>>(\n  ...entries: Entries\n): HM.HashMap<\n  Entries[number] extends readonly [infer K, any] ? K : never,\n  Entries[number] extends readonly [any, infer V] ? V : never\n> => fromIterable(entries)\n\n/** @internal */\nexport const fromIterable = <K, V>(entries: Iterable<readonly [K, V]>): HM.HashMap<K, V> => {\n  const map = beginMutation(empty<K, V>())\n  for (const entry of entries) {\n    set(map, entry[0], entry[1])\n  }\n  return endMutation(map)\n}\n\n/** @internal */\nexport const isHashMap: {\n  <K, V>(u: Iterable<readonly [K, V]>): u is HM.HashMap<K, V>\n  (u: unknown): u is HM.HashMap<unknown, unknown>\n} = (u: unknown): u is HM.HashMap<unknown, unknown> => hasProperty(u, HashMapTypeId)\n\n/** @internal */\nexport const isEmpty = <K, V>(self: HM.HashMap<K, V>): boolean =>\n  self && Node.isEmptyNode((self as HashMapImpl<K, V>)._root)\n\n/** @internal */\nexport const get = Dual.dual<\n  <K1 extends K, K>(key: K1) => <V>(self: HM.HashMap<K, V>) => Option.Option<V>,\n  <K, V, K1 extends K>(self: HM.HashMap<K, V>, key: K1) => Option.Option<V>\n>(2, (self, key) => getHash(self, key, Hash.hash(key)))\n\n/** @internal */\nexport const getHash = Dual.dual<\n  <K1 extends K, K>(key: K1, hash: number) => <V>(self: HM.HashMap<K, V>) => Option.Option<V>,\n  <K, V, K1 extends K>(self: HM.HashMap<K, V>, key: K1, hash: number) => Option.Option<V>\n>(3, <K, V, K1 extends K>(self: HM.HashMap<K, V>, key: K1, hash: number) => {\n  let node = (self as HashMapImpl<K, V>)._root\n  let shift = 0\n\n  while (true) {\n    switch (node._tag) {\n      case \"LeafNode\": {\n        return Equal.equals(key, node.key) ? node.value : Option.none()\n      }\n      case \"CollisionNode\": {\n        if (hash === node.hash) {\n          const children = node.children\n          for (let i = 0, len = children.length; i < len; ++i) {\n            const child = children[i]!\n            if (\"key\" in child && Equal.equals(key, child.key)) {\n              return child.value\n            }\n          }\n        }\n        return Option.none()\n      }\n      case \"IndexedNode\": {\n        const frag = hashFragment(shift, hash)\n        const bit = toBitmap(frag)\n        if (node.mask & bit) {\n          node = node.children[fromBitmap(node.mask, bit)]!\n          shift += SIZE\n          break\n        }\n        return Option.none()\n      }\n      case \"ArrayNode\": {\n        node = node.children[hashFragment(shift, hash)]!\n        if (node) {\n          shift += SIZE\n          break\n        }\n        return Option.none()\n      }\n      default:\n        return Option.none()\n    }\n  }\n})\n\n/** @internal */\nexport const unsafeGet = Dual.dual<\n  <K1 extends K, K>(key: K1) => <V>(self: HM.HashMap<K, V>) => V,\n  <K, V, K1 extends K>(self: HM.HashMap<K, V>, key: K1) => V\n>(2, (self, key) => {\n  const element = getHash(self, key, Hash.hash(key))\n  if (Option.isNone(element)) {\n    throw new Error(\"Expected map to contain key\")\n  }\n  return element.value\n})\n\n/** @internal */\nexport const has = Dual.dual<\n  <K1 extends K, K>(key: K1) => <V>(self: HM.HashMap<K, V>) => boolean,\n  <K, V, K1 extends K>(self: HM.HashMap<K, V>, key: K1) => boolean\n>(2, (self, key) => Option.isSome(getHash(self, key, Hash.hash(key))))\n\n/** @internal */\nexport const hasHash = Dual.dual<\n  <K1 extends K, K>(key: K1, hash: number) => <V>(self: HM.HashMap<K, V>) => boolean,\n  <K, V, K1 extends K>(self: HM.HashMap<K, V>, key: K1, hash: number) => boolean\n>(3, (self, key, hash) => Option.isSome(getHash(self, key, hash)))\n\n/** @internal */\nexport const hasBy = Dual.dual<\n  <K, V>(predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean) => (self: HM.HashMap<K, V>) => boolean,\n  <K, V>(self: HM.HashMap<K, V>, predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean) => boolean\n>(2, (self, predicate) => Option.isSome(findFirst(self, predicate)))\n\n/** @internal */\nexport const set = Dual.dual<\n  <K, V>(key: K, value: V) => (self: HM.HashMap<K, V>) => HM.HashMap<K, V>,\n  <K, V>(self: HM.HashMap<K, V>, key: K, value: V) => HM.HashMap<K, V>\n>(3, (self, key, value) => modifyAt(self, key, () => Option.some(value)))\n\n/** @internal */\nexport const setTree = Dual.dual<\n  <K, V>(newRoot: Node.Node<K, V>, newSize: number) => (self: HM.HashMap<K, V>) => HM.HashMap<K, V>,\n  <K, V>(self: HM.HashMap<K, V>, newRoot: Node.Node<K, V>, newSize: number) => HM.HashMap<K, V>\n>(3, <K, V>(self: HM.HashMap<K, V>, newRoot: Node.Node<K, V>, newSize: number) => {\n  if ((self as HashMapImpl<K, V>)._editable) {\n    ;(self as HashMapImpl<K, V>)._root = newRoot\n    ;(self as HashMapImpl<K, V>)._size = newSize\n    return self\n  }\n  return newRoot === (self as HashMapImpl<K, V>)._root\n    ? self\n    : makeImpl(\n      (self as HashMapImpl<K, V>)._editable,\n      (self as HashMapImpl<K, V>)._edit,\n      newRoot,\n      newSize\n    )\n})\n\n/** @internal */\nexport const keys = <K, V>(self: HM.HashMap<K, V>): IterableIterator<K> =>\n  new HashMapIterator(self as HashMapImpl<K, V>, (key) => key)\n\n/** @internal */\nexport const values = <K, V>(self: HM.HashMap<K, V>): IterableIterator<V> =>\n  new HashMapIterator(self as HashMapImpl<K, V>, (_, value) => value)\n\n/** @internal */\nexport const entries = <K, V>(self: HM.HashMap<K, V>): IterableIterator<[K, V]> =>\n  new HashMapIterator(self as HashMapImpl<K, V>, (key, value) => [key, value])\n\n/** @internal */\nexport const size = <K, V>(self: HM.HashMap<K, V>): number => (self as HashMapImpl<K, V>)._size\n\n/** @internal */\nexport const countBy = Dual.dual<\n  <K, V>(predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean) => (self: HM.HashMap<K, V>) => number,\n  <K, V>(self: HM.HashMap<K, V>, predicate: (value: NoInfer<V>, key: NoInfer<K>) => boolean) => number\n>(2, (self, f) => {\n  let count = 0\n  for (const [k, a] of self) {\n    if (f(a, k)) {\n      count++\n    }\n  }\n  return count\n})\n\n/** @internal */\nexport const beginMutation = <K, V>(self: HM.HashMap<K, V>): HM.HashMap<K, V> =>\n  makeImpl(\n    true,\n    (self as HashMapImpl<K, V>)._edit + 1,\n    (self as HashMapImpl<K, V>)._root,\n    (self as HashMapImpl<K, V>)._size\n  )\n\n/** @internal */\nexport const endMutation = <K, V>(self: HM.HashMap<K, V>): HM.HashMap<K, V> => {\n  ;(self as HashMapImpl<K, V>)._editable = false\n  return self\n}\n\n/** @internal */\nexport const mutate = Dual.dual<\n  <K, V>(f: (self: HM.HashMap<K, V>) => void) => (self: HM.HashMap<K, V>) => HM.HashMap<K, V>,\n  <K, V>(self: HM.HashMap<K, V>, f: (self: HM.HashMap<K, V>) => void) => HM.HashMap<K, V>\n>(2, (self, f) => {\n  const transient = beginMutation(self)\n  f(transient)\n  return endMutation(transient)\n})\n\n/** @internal */\nexport const modifyAt = Dual.dual<\n  <K, V>(key: K, f: HM.HashMap.UpdateFn<V>) => (self: HM.HashMap<K, V>) => HM.HashMap<K, V>,\n  <K, V>(self: HM.HashMap<K, V>, key: K, f: HM.HashMap.UpdateFn<V>) => HM.HashMap<K, V>\n>(3, (self, key, f) => modifyHash(self, key, Hash.hash(key), f))\n\n/** @internal */\nexport const modifyHash = Dual.dual<\n  <K, V>(key: K, hash: number, f: HM.HashMap.UpdateFn<V>) => (self: HM.HashMap<K, V>) => HM.HashMap<K, V>,\n  <K, V>(self: HM.HashMap<K, V>, key: K, hash: number, f: HM.HashMap.UpdateFn<V>) => HM.HashMap<K, V>\n>(4, <K, V>(self: HM.HashMap<K, V>, key: K, hash: number, f: HM.HashMap.UpdateFn<V>) => {\n  const size = { value: (self as HashMapImpl<K, V>)._size }\n  const newRoot = (self as HashMapImpl<K, V>)._root.modify(\n    (self as HashMapImpl<K, V>)._editable ?\n      (self as HashMapImpl<K, V>)._edit :\n      NaN,\n    0,\n    f,\n    hash,\n    key,\n    size\n  )\n  return pipe(self, setTree(newRoot, size.value))\n})\n\n/** @internal */\nexport const modify = Dual.dual<\n  <K, V>(key: K, f: (v: V) => V) => (self: HM.HashMap<K, V>) => HM.HashMap<K, V>,\n  <K, V>(self: HM.HashMap<K, V>, key: K, f: (v: V) => V) => HM.HashMap<K, V>\n>(3, (self, key, f) => modifyAt(self, key, Option.map(f)))\n\n/** @internal */\nexport const union = Dual.dual<\n  <K1, V1>(\n    that: HM.HashMap<K1, V1>\n  ) => <K0, V0>(self: HM.HashMap<K0, V0>) => HM.HashMap<K0 | K1, V0 | V1>,\n  <K0, V0, K1, V1>(\n    self: HM.HashMap<K0, V0>,\n    that: HM.HashMap<K1, V1>\n  ) => HM.HashMap<K0 | K1, V0 | V1>\n>(2, <K0, V0, K1, V1>(self: HM.HashMap<K0, V0>, that: HM.HashMap<K1, V1>) => {\n  const result: HM.HashMap<K0 | K1, V0 | V1> = beginMutation(self)\n  forEach(that, (v, k) => set(result, k, v))\n  return endMutation(result)\n})\n\n/** @internal */\nexport const remove = Dual.dual<\n  <K>(key: K) => <V>(self: HM.HashMap<K, V>) => HM.HashMap<K, V>,\n  <K, V>(self: HM.HashMap<K, V>, key: K) => HM.HashMap<K, V>\n>(2, (self, key) => modifyAt(self, key, Option.none))\n\n/** @internal */\nexport const removeMany = Dual.dual<\n  <K>(keys: Iterable<K>) => <V>(self: HM.HashMap<K, V>) => HM.HashMap<K, V>,\n  <K, V>(self: HM.HashMap<K, V>, keys: Iterable<K>) => HM.HashMap<K, V>\n>(2, (self, keys) =>\n  mutate(self, (map) => {\n    for (const key of keys) {\n      remove(key)(map)\n    }\n  }))\n\n/**\n * Maps over the entries of the `HashMap` using the specified function.\n *\n * @since 2.0.0\n * @category mapping\n */\nexport const map = Dual.dual<\n  <A, V, K>(f: (value: V, key: K) => A) => (self: HM.HashMap<K, V>) => HM.HashMap<K, A>,\n  <K, V, A>(self: HM.HashMap<K, V>, f: (value: V, key: K) => A) => HM.HashMap<K, A>\n>(2, (self, f) =>\n  reduce(\n    self,\n    empty(),\n    (map, value, key) => set(map, key, f(value, key))\n  ))\n\n/** @internal */\nexport const flatMap = Dual.dual<\n  <A, K, B>(\n    f: (value: A, key: K) => HM.HashMap<K, B>\n  ) => (self: HM.HashMap<K, A>) => HM.HashMap<K, B>,\n  <K, A, B>(self: HM.HashMap<K, A>, f: (value: A, key: K) => HM.HashMap<K, B>) => HM.HashMap<K, B>\n>(\n  2,\n  (self, f) =>\n    reduce(self, empty(), (zero, value, key) =>\n      mutate(\n        zero,\n        (map) => forEach(f(value, key), (value, key) => set(map, key, value))\n      ))\n)\n\n/** @internal */\nexport const forEach = Dual.dual<\n  <V, K>(f: (value: V, key: K) => void) => (self: HM.HashMap<K, V>) => void,\n  <V, K>(self: HM.HashMap<K, V>, f: (value: V, key: K) => void) => void\n>(2, (self, f) => reduce(self, void 0 as void, (_, value, key) => f(value, key)))\n\n/** @internal */\nexport const reduce = Dual.dual<\n  <Z, V, K>(zero: Z, f: (accumulator: Z, value: V, key: K) => Z) => (self: HM.HashMap<K, V>) => Z,\n  <Z, V, K>(self: HM.HashMap<K, V>, zero: Z, f: (accumulator: Z, value: V, key: K) => Z) => Z\n>(3, <Z, V, K>(self: HM.HashMap<K, V>, zero: Z, f: (accumulator: Z, value: V, key: K) => Z) => {\n  const root = (self as HashMapImpl<K, V>)._root\n  if (root._tag === \"LeafNode\") {\n    return Option.isSome(root.value) ? f(zero, root.value.value, root.key) : zero\n  }\n  if (root._tag === \"EmptyNode\") {\n    return zero\n  }\n  const toVisit = [root.children]\n  let children\n  while ((children = toVisit.pop())) {\n    for (let i = 0, len = children.length; i < len;) {\n      const child = children[i++]\n      if (child && !Node.isEmptyNode(child)) {\n        if (child._tag === \"LeafNode\") {\n          if (Option.isSome(child.value)) {\n            zero = f(zero, child.value.value, child.key)\n          }\n        } else {\n          toVisit.push(child.children)\n        }\n      }\n    }\n  }\n  return zero\n})\n\n/** @internal */\nexport const filter: {\n  <K, A, B extends A>(f: (a: NoInfer<A>, k: K) => a is B): (self: HM.HashMap<K, A>) => HM.HashMap<K, B>\n  <K, A>(f: (a: NoInfer<A>, k: K) => boolean): (self: HM.HashMap<K, A>) => HM.HashMap<K, A>\n  <K, A, B extends A>(self: HM.HashMap<K, A>, f: (a: A, k: K) => a is B): HM.HashMap<K, B>\n  <K, A>(self: HM.HashMap<K, A>, f: (a: A, k: K) => boolean): HM.HashMap<K, A>\n} = Dual.dual(\n  2,\n  <K, A>(self: HM.HashMap<K, A>, f: (a: A, k: K) => boolean): HM.HashMap<K, A> =>\n    mutate(empty(), (map) => {\n      for (const [k, a] of self) {\n        if (f(a, k)) {\n          set(map, k, a)\n        }\n      }\n    })\n)\n\n/** @internal */\nexport const compact = <K, A>(self: HM.HashMap<K, Option.Option<A>>) => filterMap(self, identity)\n\n/** @internal */\nexport const filterMap = Dual.dual<\n  <A, K, B>(\n    f: (value: A, key: K) => Option.Option<B>\n  ) => (self: HM.HashMap<K, A>) => HM.HashMap<K, B>,\n  <K, A, B>(self: HM.HashMap<K, A>, f: (value: A, key: K) => Option.Option<B>) => HM.HashMap<K, B>\n>(2, (self, f) =>\n  mutate(empty(), (map) => {\n    for (const [k, a] of self) {\n      const option = f(a, k)\n      if (Option.isSome(option)) {\n        set(map, k, option.value)\n      }\n    }\n  }))\n\n/** @internal */\nexport const findFirst: {\n  <K, A, B extends A>(predicate: (a: NoInfer<A>, k: K) => a is B): (self: HM.HashMap<K, A>) => Option.Option<[K, B]>\n  <K, A>(predicate: (a: NoInfer<A>, k: K) => boolean): (self: HM.HashMap<K, A>) => Option.Option<[K, A]>\n  <K, A, B extends A>(self: HM.HashMap<K, A>, predicate: (a: A, k: K) => a is B): Option.Option<[K, B]>\n  <K, A>(self: HM.HashMap<K, A>, predicate: (a: A, k: K) => boolean): Option.Option<[K, A]>\n} = Dual.dual(\n  2,\n  <K, A>(self: HM.HashMap<K, A>, predicate: (a: A, k: K) => boolean): Option.Option<[K, A]> => {\n    for (const ka of self) {\n      if (predicate(ka[1], ka[0])) {\n        return Option.some(ka)\n      }\n    }\n    return Option.none()\n  }\n)\n\n/** @internal */\nexport const some: {\n  <K, A>(predicate: (a: NoInfer<A>, k: K) => boolean): (self: HM.HashMap<K, A>) => boolean\n  <K, A>(self: HM.HashMap<K, A>, predicate: (a: A, k: K) => boolean): boolean\n} = Dual.dual(\n  2,\n  <K, A>(self: HM.HashMap<K, A>, predicate: (a: A, k: K) => boolean): boolean => {\n    for (const ka of self) {\n      if (predicate(ka[1], ka[0])) {\n        return true\n      }\n    }\n    return false\n  }\n)\n\n/** @internal */\nexport const every: {\n  <K, A>(predicate: (a: NoInfer<A>, k: K) => boolean): (self: HM.HashMap<K, A>) => boolean\n  <K, A>(self: HM.HashMap<K, A>, predicate: (a: A, k: K) => boolean): boolean\n} = Dual.dual(\n  2,\n  <K, A>(self: HM.HashMap<K, A>, predicate: (a: A, k: K) => boolean): boolean => !some(self, (a, k) => !predicate(a, k))\n)\n"
  },
  {
    "path": "packages/effect/src/internal/hashSet.ts",
    "content": "import * as Equal from \"../Equal.js\"\nimport { dual } from \"../Function.js\"\nimport * as Hash from \"../Hash.js\"\nimport type { HashMap } from \"../HashMap.js\"\nimport type * as HS from \"../HashSet.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"../Inspectable.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport type { Predicate, Refinement } from \"../Predicate.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type { NoInfer } from \"../Types.js\"\nimport * as HM from \"./hashMap.js\"\n\nconst HashSetSymbolKey = \"effect/HashSet\"\n\n/** @internal */\nexport const HashSetTypeId: HS.TypeId = Symbol.for(HashSetSymbolKey) as HS.TypeId\n\n/** @internal */\nexport interface HashSetImpl<out A> extends HS.HashSet<A> {\n  readonly _keyMap: HashMap<A, unknown>\n}\n\nconst HashSetProto: Omit<HashSetImpl<unknown>, \"_keyMap\"> = {\n  [HashSetTypeId]: HashSetTypeId,\n  [Symbol.iterator]<A>(this: HashSetImpl<A>): Iterator<A> {\n    return HM.keys(this._keyMap)\n  },\n  [Hash.symbol]<A>(this: HashSetImpl<A>): number {\n    return Hash.cached(\n      this,\n      Hash.combine(Hash.hash(this._keyMap))(Hash.hash(HashSetSymbolKey))\n    )\n  },\n  [Equal.symbol]<A>(this: HashSetImpl<A>, that: unknown): boolean {\n    if (isHashSet(that)) {\n      return (\n        HM.size(this._keyMap) === HM.size((that as HashSetImpl<A>)._keyMap) &&\n        Equal.equals(this._keyMap, (that as HashSetImpl<A>)._keyMap)\n      )\n    }\n    return false\n  },\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"HashSet\",\n      values: Array.from(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const makeImpl = <A>(keyMap: HashMap<A, unknown>): HashSetImpl<A> => {\n  const set = Object.create(HashSetProto)\n  set._keyMap = keyMap\n  return set\n}\n\n/** @internal */\nexport const isHashSet: {\n  <A>(u: Iterable<A>): u is HS.HashSet<A>\n  (u: unknown): u is HS.HashSet<unknown>\n} = (u: unknown): u is HS.HashSet<unknown> => hasProperty(u, HashSetTypeId)\n\nconst _empty = makeImpl<never>(HM.empty())\n\n/** @internal */\nexport const empty = <A = never>(): HS.HashSet<A> => _empty\n\n/** @internal */\nexport const fromIterable = <A>(elements: Iterable<A>): HS.HashSet<A> => {\n  const set = beginMutation(empty<A>())\n  for (const value of elements) {\n    add(set, value)\n  }\n  return endMutation(set)\n}\n\n/** @internal */\nexport const make = <As extends ReadonlyArray<any>>(...elements: As): HS.HashSet<As[number]> => {\n  const set = beginMutation(empty<As[number]>())\n  for (const value of elements) {\n    add(set, value)\n  }\n  return endMutation(set)\n}\n\n/** @internal */\nexport const has = dual<\n  <A>(value: A) => (self: HS.HashSet<A>) => boolean,\n  <A>(self: HS.HashSet<A>, value: A) => boolean\n>(2, <A>(self: HS.HashSet<A>, value: A) => HM.has((self as HashSetImpl<A>)._keyMap, value))\n\n/** @internal */\nexport const some = dual<\n  <A>(f: Predicate<A>) => (self: HS.HashSet<A>) => boolean,\n  <A>(self: HS.HashSet<A>, f: Predicate<A>) => boolean\n>(2, (self, f) => {\n  let found = false\n  for (const value of self) {\n    found = f(value)\n    if (found) {\n      break\n    }\n  }\n  return found\n})\n\n/** @internal */\nexport const every: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: HS.HashSet<A>) => self is HS.HashSet<B>\n  <A>(predicate: Predicate<A>): (self: HS.HashSet<A>) => boolean\n  <A, B extends A>(self: HS.HashSet<A>, refinement: Refinement<A, B>): self is HS.HashSet<B>\n  <A>(self: HS.HashSet<A>, predicate: Predicate<A>): boolean\n} = dual(\n  2,\n  <A, B extends A>(self: HS.HashSet<A>, refinement: Refinement<A, B>): self is HS.HashSet<B> =>\n    !some(self, (a) => !refinement(a))\n)\n\n/** @internal */\nexport const isSubset = dual<\n  <A>(that: HS.HashSet<A>) => (self: HS.HashSet<A>) => boolean,\n  <A>(self: HS.HashSet<A>, that: HS.HashSet<A>) => boolean\n>(2, (self, that) => every(self, (value) => has(that, value)))\n\n/** @internal */\nexport const values = <A>(self: HS.HashSet<A>): IterableIterator<A> => HM.keys((self as HashSetImpl<A>)._keyMap)\n\n/** @internal */\nexport const size = <A>(self: HS.HashSet<A>): number => HM.size((self as HashSetImpl<A>)._keyMap)\n\n/** @internal */\nexport const beginMutation = <A>(self: HS.HashSet<A>): HS.HashSet<A> =>\n  makeImpl(HM.beginMutation((self as HashSetImpl<A>)._keyMap))\n\n/** @internal */\nexport const endMutation = <A>(self: HS.HashSet<A>): HS.HashSet<A> => {\n  ;((self as HashSetImpl<A>)._keyMap as HM.HashMapImpl<A, unknown>)._editable = false\n  return self\n}\n\n/** @internal */\nexport const mutate = dual<\n  <A>(f: (set: HS.HashSet<A>) => void) => (self: HS.HashSet<A>) => HS.HashSet<A>,\n  <A>(self: HS.HashSet<A>, f: (set: HS.HashSet<A>) => void) => HS.HashSet<A>\n>(2, (self, f) => {\n  const transient = beginMutation(self)\n  f(transient)\n  return endMutation(transient)\n})\n\n/** @internal */\nexport const add = dual<\n  <A>(value: A) => (self: HS.HashSet<A>) => HS.HashSet<A>,\n  <A>(self: HS.HashSet<A>, value: A) => HS.HashSet<A>\n>(\n  2,\n  <A>(self: HS.HashSet<A>, value: A) =>\n    ((self as HashSetImpl<A>)._keyMap as HM.HashMapImpl<A, unknown>)._editable\n      ? (HM.set(value as A, true as unknown)((self as HashSetImpl<A>)._keyMap), self)\n      : makeImpl(HM.set(value as A, true as unknown)((self as HashSetImpl<A>)._keyMap))\n)\n\n/** @internal */\nexport const remove = dual<\n  <A>(value: A) => (self: HS.HashSet<A>) => HS.HashSet<A>,\n  <A>(self: HS.HashSet<A>, value: A) => HS.HashSet<A>\n>(\n  2,\n  <A>(self: HS.HashSet<A>, value: A) =>\n    (((self as HashSetImpl<A>)._keyMap) as HM.HashMapImpl<A, unknown>)._editable\n      ? (HM.remove(value)((self as HashSetImpl<A>)._keyMap), self)\n      : makeImpl(HM.remove(value)((self as HashSetImpl<A>)._keyMap))\n)\n\n/** @internal */\nexport const difference = dual<\n  <A>(that: Iterable<A>) => (self: HS.HashSet<A>) => HS.HashSet<A>,\n  <A>(self: HS.HashSet<A>, that: Iterable<A>) => HS.HashSet<A>\n>(2, (self, that) =>\n  mutate(self, (set) => {\n    for (const value of that) {\n      remove(set, value)\n    }\n  }))\n\n/** @internal */\nexport const intersection = dual<\n  <A>(that: Iterable<A>) => (self: HS.HashSet<A>) => HS.HashSet<A>,\n  <A>(self: HS.HashSet<A>, that: Iterable<A>) => HS.HashSet<A>\n>(2, (self, that) =>\n  mutate(empty(), (set) => {\n    for (const value of that) {\n      if (has(value)(self)) {\n        add(value)(set)\n      }\n    }\n  }))\n\n/** @internal */\nexport const union = dual<\n  <A>(that: Iterable<A>) => (self: HS.HashSet<A>) => HS.HashSet<A>,\n  <A>(self: HS.HashSet<A>, that: Iterable<A>) => HS.HashSet<A>\n>(2, (self, that) =>\n  mutate(empty(), (set) => {\n    forEach(self, (value) => add(set, value))\n    for (const value of that) {\n      add(set, value)\n    }\n  }))\n\n/** @internal */\nexport const toggle = dual<\n  <A>(value: A) => (self: HS.HashSet<A>) => HS.HashSet<A>,\n  <A>(self: HS.HashSet<A>, value: A) => HS.HashSet<A>\n>(2, (self, value) => has(self, value) ? remove(self, value) : add(self, value))\n\n/** @internal */\nexport const map = dual<\n  <A, B>(f: (a: A) => B) => (self: HS.HashSet<A>) => HS.HashSet<B>,\n  <A, B>(self: HS.HashSet<A>, f: (a: A) => B) => HS.HashSet<B>\n>(2, (self, f) =>\n  mutate(empty(), (set) => {\n    forEach(self, (a) => {\n      const b = f(a)\n      if (!has(set, b)) {\n        add(set, b)\n      }\n    })\n  }))\n\n/** @internal */\nexport const flatMap = dual<\n  <A, B>(f: (a: A) => Iterable<B>) => (self: HS.HashSet<A>) => HS.HashSet<B>,\n  <A, B>(self: HS.HashSet<A>, f: (a: A) => Iterable<B>) => HS.HashSet<B>\n>(2, (self, f) =>\n  mutate(empty(), (set) => {\n    forEach(self, (a) => {\n      for (const b of f(a)) {\n        if (!has(set, b)) {\n          add(set, b)\n        }\n      }\n    })\n  }))\n\n/** @internal */\nexport const forEach = dual<\n  <A>(f: (value: A) => void) => (self: HS.HashSet<A>) => void,\n  <A>(self: HS.HashSet<A>, f: (value: A) => void) => void\n>(2, <A>(self: HS.HashSet<A>, f: (value: A) => void) =>\n  HM.forEach(\n    (self as HashSetImpl<A>)._keyMap,\n    (_, k) => f(k)\n  ))\n\n/** @internal */\nexport const reduce = dual<\n  <A, Z>(zero: Z, f: (accumulator: Z, value: A) => Z) => (self: HS.HashSet<A>) => Z,\n  <A, Z>(self: HS.HashSet<A>, zero: Z, f: (accumulator: Z, value: A) => Z) => Z\n>(3, <A, Z>(self: HS.HashSet<A>, zero: Z, f: (accumulator: Z, value: A) => Z) =>\n  HM.reduce(\n    (self as HashSetImpl<A>)._keyMap,\n    zero,\n    (z, _, a) => f(z, a)\n  ))\n\n/** @internal */\nexport const filter: {\n  <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: HS.HashSet<A>) => HS.HashSet<B>\n  <A>(predicate: Predicate<NoInfer<A>>): (self: HS.HashSet<A>) => HS.HashSet<A>\n  <A, B extends A>(self: HS.HashSet<A>, refinement: Refinement<A, B>): HS.HashSet<B>\n  <A>(self: HS.HashSet<A>, predicate: Predicate<A>): HS.HashSet<A>\n} = dual(2, <A>(self: HS.HashSet<A>, f: Predicate<A>) => {\n  return mutate(empty(), (set) => {\n    const iterator = values(self)\n    let next: IteratorResult<A, any>\n    while (!(next = iterator.next()).done) {\n      const value = next.value\n      if (f(value)) {\n        add(set, value)\n      }\n    }\n  })\n})\n\n/** @internal */\nexport const partition: {\n  <A, B extends A>(\n    refinement: Refinement<NoInfer<A>, B>\n  ): (self: HS.HashSet<A>) => [excluded: HS.HashSet<Exclude<A, B>>, satisfying: HS.HashSet<B>]\n  <A>(\n    predicate: Predicate<NoInfer<A>>\n  ): (self: HS.HashSet<A>) => [excluded: HS.HashSet<A>, satisfying: HS.HashSet<A>]\n  <A, B extends A>(\n    self: HS.HashSet<A>,\n    refinement: Refinement<A, B>\n  ): [excluded: HS.HashSet<Exclude<A, B>>, satisfying: HS.HashSet<B>]\n  <A>(self: HS.HashSet<A>, predicate: Predicate<A>): [excluded: HS.HashSet<A>, satisfying: HS.HashSet<A>]\n} = dual(2, <A>(self: HS.HashSet<A>, predicate: Predicate<A>): [excluded: HS.HashSet<A>, satisfying: HS.HashSet<A>] => {\n  const iterator = values(self)\n  let next: IteratorResult<A, any>\n  const right = beginMutation(empty<A>())\n  const left = beginMutation(empty<A>())\n  while (!(next = iterator.next()).done) {\n    const value = next.value\n    if (predicate(value)) {\n      add(right, value)\n    } else {\n      add(left, value)\n    }\n  }\n  return [endMutation(left), endMutation(right)]\n})\n"
  },
  {
    "path": "packages/effect/src/internal/keyedPool.ts",
    "content": "import type * as Deferred from \"../Deferred.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Equal from \"../Equal.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport * as Hash from \"../Hash.js\"\nimport * as HashMap from \"../HashMap.js\"\nimport type * as KeyedPool from \"../KeyedPool.js\"\nimport * as MutableRef from \"../MutableRef.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport type * as Pool from \"../Pool.js\"\nimport * as Predicate from \"../Predicate.js\"\nimport type * as Scope from \"../Scope.js\"\nimport * as core from \"./core.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\nimport * as pool from \"./pool.js\"\n\n/** @internal */\nconst KeyedPoolSymbolKey = \"effect/KeyedPool\"\n\n/** @internal */\nexport const KeyedPoolTypeId: KeyedPool.KeyedPoolTypeId = Symbol.for(\n  KeyedPoolSymbolKey\n) as KeyedPool.KeyedPoolTypeId\n\nconst KeyedPoolMapValueSymbol = Symbol.for(\"effect/KeyedPool/MapValue\")\ntype KeyedPoolMapValueSymbol = typeof KeyedPoolMapValueSymbol\n\nconst keyedPoolVariance = {\n  /* c8 ignore next */\n  _K: (_: unknown) => _,\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\nclass KeyedPoolImpl<in K, in out A, out E = never> implements KeyedPool.KeyedPool<K, A, E> {\n  readonly [KeyedPoolTypeId] = keyedPoolVariance\n  constructor(\n    readonly getOrCreatePool: (key: K) => Effect.Effect<Pool.Pool<A, E>>,\n    readonly activePools: Effect.Effect<Array<Pool.Pool<A, E>>>\n  ) {}\n  get(key: K): Effect.Effect<A, E, Scope.Scope> {\n    return core.flatMap(this.getOrCreatePool(key), pool.get)\n  }\n  invalidate(item: A): Effect.Effect<void> {\n    return core.flatMap(this.activePools, core.forEachSequentialDiscard((pool) => pool.invalidate(item)))\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\ntype MapValue<A, E> = Complete<A, E> | Pending<A, E>\n\nclass Complete<in out A, out E> implements Equal.Equal {\n  readonly _tag = \"Complete\"\n  readonly [KeyedPoolMapValueSymbol]: KeyedPoolMapValueSymbol = KeyedPoolMapValueSymbol\n  constructor(readonly pool: Pool.Pool<A, E>) {}\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.string(\"effect/KeyedPool/Complete\"),\n      Hash.combine(Hash.hash(this.pool)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](u: unknown): boolean {\n    return isComplete(u) && Equal.equals(this.pool, u.pool)\n  }\n}\n\nconst isComplete = (u: unknown): u is Complete<unknown, unknown> =>\n  Predicate.isTagged(u, \"Complete\") && KeyedPoolMapValueSymbol in u\n\nclass Pending<in out A, in out E> implements Equal.Equal {\n  readonly _tag = \"Pending\"\n  readonly [KeyedPoolMapValueSymbol]: KeyedPoolMapValueSymbol = KeyedPoolMapValueSymbol\n  constructor(readonly deferred: Deferred.Deferred<Pool.Pool<A, E>>) {}\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.string(\"effect/KeyedPool/Pending\"),\n      Hash.combine(Hash.hash(this.deferred)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](u: unknown): boolean {\n    return isPending(u) && Equal.equals(this.deferred, u.deferred)\n  }\n}\n\nconst isPending = (u: unknown): u is Pending<unknown, unknown> =>\n  Predicate.isTagged(u, \"Pending\") && KeyedPoolMapValueSymbol in u\n\nconst makeImpl = <K, A, E, R>(\n  get: (key: K) => Effect.Effect<A, E, R>,\n  min: (key: K) => number,\n  max: (key: K) => number,\n  timeToLive: (key: K) => Option.Option<Duration.Duration>\n): Effect.Effect<KeyedPool.KeyedPool<K, A, E>, never, R | Scope.Scope> =>\n  pipe(\n    fiberRuntime.all([\n      core.context<R>(),\n      core.fiberId,\n      core.sync(() => MutableRef.make(HashMap.empty<K, MapValue<A, E>>())),\n      fiberRuntime.scopeMake()\n    ]),\n    core.map(([context, fiberId, map, scope]) => {\n      const getOrCreatePool = (key: K): Effect.Effect<Pool.Pool<A, E>> =>\n        core.suspend(() => {\n          let value: MapValue<A, E> | undefined = Option.getOrUndefined(HashMap.get(MutableRef.get(map), key))\n          if (value === undefined) {\n            return core.uninterruptibleMask((restore) => {\n              const deferred = core.deferredUnsafeMake<Pool.Pool<A, E>>(fiberId)\n              value = new Pending(deferred)\n              let previous: MapValue<A, E> | undefined = undefined\n              if (HashMap.has(MutableRef.get(map), key)) {\n                previous = Option.getOrUndefined(HashMap.get(MutableRef.get(map), key))\n              } else {\n                MutableRef.update(map, HashMap.set(key, value as MapValue<A, E>))\n              }\n              if (previous === undefined) {\n                return pipe(\n                  restore(\n                    fiberRuntime.scopeExtend(\n                      pool.makeWithTTL({\n                        acquire: core.provideContext(get(key), context),\n                        min: min(key),\n                        max: max(key),\n                        timeToLive: Option.getOrElse(timeToLive(key), () => Duration.infinity)\n                      }),\n                      scope\n                    )\n                  ),\n                  core.matchCauseEffect({\n                    onFailure: (cause) => {\n                      const current = Option.getOrUndefined(HashMap.get(MutableRef.get(map), key))\n                      if (Equal.equals(current, value)) {\n                        MutableRef.update(map, HashMap.remove(key))\n                      }\n                      return core.zipRight(\n                        core.deferredFailCause(deferred, cause),\n                        core.failCause(cause)\n                      )\n                    },\n                    onSuccess: (pool) => {\n                      MutableRef.update(map, HashMap.set(key, new Complete(pool) as MapValue<A, E>))\n                      return core.as(\n                        core.deferredSucceed(deferred, pool),\n                        pool\n                      )\n                    }\n                  })\n                )\n              }\n              switch (previous._tag) {\n                case \"Complete\": {\n                  return core.succeed(previous.pool)\n                }\n                case \"Pending\": {\n                  return restore(core.deferredAwait(previous.deferred))\n                }\n              }\n            })\n          }\n          switch (value._tag) {\n            case \"Complete\": {\n              return core.succeed(value.pool)\n            }\n            case \"Pending\": {\n              return core.deferredAwait(value.deferred)\n            }\n          }\n        })\n      const activePools: Effect.Effect<Array<Pool.Pool<A, E>>> = core.suspend(() =>\n        core.forEachSequential(HashMap.toValues(MutableRef.get(map)), (value) => {\n          switch (value._tag) {\n            case \"Complete\": {\n              return core.succeed(value.pool)\n            }\n            case \"Pending\": {\n              return core.deferredAwait(value.deferred)\n            }\n          }\n        })\n      )\n      return new KeyedPoolImpl(getOrCreatePool, activePools)\n    })\n  )\n\n/** @internal */\nexport const make = <K, A, E, R>(\n  options: {\n    readonly acquire: (key: K) => Effect.Effect<A, E, R>\n    readonly size: number\n  }\n): Effect.Effect<KeyedPool.KeyedPool<K, A, E>, never, R | Scope.Scope> =>\n  makeImpl(options.acquire, () => options.size, () => options.size, () => Option.none())\n\n/** @internal */\nexport const makeWith = <K, A, E, R>(\n  options: {\n    readonly acquire: (key: K) => Effect.Effect<A, E, R>\n    readonly size: (key: K) => number\n  }\n): Effect.Effect<KeyedPool.KeyedPool<K, A, E>, never, R | Scope.Scope> =>\n  makeImpl(options.acquire, options.size, options.size, () => Option.none())\n\n/** @internal */\nexport const makeWithTTL = <K, A, E, R>(\n  options: {\n    readonly acquire: (key: K) => Effect.Effect<A, E, R>\n    readonly min: (key: K) => number\n    readonly max: (key: K) => number\n    readonly timeToLive: Duration.DurationInput\n  }\n): Effect.Effect<KeyedPool.KeyedPool<K, A, E>, never, R | Scope.Scope> => {\n  const timeToLive = Duration.decode(options.timeToLive)\n  return makeImpl(options.acquire, options.min, options.max, () => Option.some(timeToLive))\n}\n\n/** @internal */\nexport const makeWithTTLBy = <K, A, E, R>(\n  options: {\n    readonly acquire: (key: K) => Effect.Effect<A, E, R>\n    readonly min: (key: K) => number\n    readonly max: (key: K) => number\n    readonly timeToLive: (key: K) => Duration.DurationInput\n  }\n): Effect.Effect<KeyedPool.KeyedPool<K, A, E>, never, R | Scope.Scope> =>\n  makeImpl(options.acquire, options.min, options.max, (key) => Option.some(Duration.decode(options.timeToLive(key))))\n\n/** @internal */\nexport const get = dual<\n  <K>(key: K) => <A, E>(self: KeyedPool.KeyedPool<K, A, E>) => Effect.Effect<A, E, Scope.Scope>,\n  <K, A, E>(self: KeyedPool.KeyedPool<K, A, E>, key: K) => Effect.Effect<A, E, Scope.Scope>\n>(2, (self, key) => self.get(key))\n\n/** @internal */\nexport const invalidate = dual<\n  <A>(item: A) => <K, E>(self: KeyedPool.KeyedPool<K, A, E>) => Effect.Effect<void>,\n  <K, A, E>(self: KeyedPool.KeyedPool<K, A, E>, item: A) => Effect.Effect<void>\n>(2, (self, item) => self.invalidate(item))\n"
  },
  {
    "path": "packages/effect/src/internal/layer/circular.ts",
    "content": "import type * as ConfigProvider from \"../../ConfigProvider.js\"\nimport * as Context from \"../../Context.js\"\nimport type * as Effect from \"../../Effect.js\"\nimport type * as Exit from \"../../Exit.js\"\nimport { dual } from \"../../Function.js\"\nimport * as HashSet from \"../../HashSet.js\"\nimport type * as Layer from \"../../Layer.js\"\nimport type * as Logger from \"../../Logger.js\"\nimport type * as LogLevel from \"../../LogLevel.js\"\nimport type { Scope } from \"../../Scope.js\"\nimport type * as Supervisor from \"../../Supervisor.js\"\nimport type * as Tracer from \"../../Tracer.js\"\nimport * as core from \"../core.js\"\nimport * as fiberRuntime from \"../fiberRuntime.js\"\nimport * as layer from \"../layer.js\"\nimport * as runtimeFlags from \"../runtimeFlags.js\"\nimport * as runtimeFlagsPatch from \"../runtimeFlagsPatch.js\"\nimport * as supervisor_ from \"../supervisor.js\"\nimport * as tracer from \"../tracer.js\"\n\n// circular with Logger\n\n/** @internal */\nexport const minimumLogLevel = (level: LogLevel.LogLevel): Layer.Layer<never> =>\n  layer.scopedDiscard(\n    fiberRuntime.fiberRefLocallyScoped(\n      fiberRuntime.currentMinimumLogLevel,\n      level\n    )\n  )\n\n/** @internal */\nexport const withMinimumLogLevel = dual<\n  (level: LogLevel.LogLevel) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, level: LogLevel.LogLevel) => Effect.Effect<A, E, R>\n>(2, (self, level) =>\n  core.fiberRefLocally(\n    fiberRuntime.currentMinimumLogLevel,\n    level\n  )(self))\n\n/** @internal */\nexport const addLogger = <A>(logger: Logger.Logger<unknown, A>): Layer.Layer<never> =>\n  layer.scopedDiscard(\n    fiberRuntime.fiberRefLocallyScopedWith(\n      fiberRuntime.currentLoggers,\n      HashSet.add(logger)\n    )\n  )\n\n/** @internal */\nexport const addLoggerEffect = <A, E, R>(\n  effect: Effect.Effect<Logger.Logger<unknown, A>, E, R>\n): Layer.Layer<never, E, R> =>\n  layer.unwrapEffect(\n    core.map(effect, addLogger)\n  )\n\n/** @internal */\nexport const addLoggerScoped = <A, E, R>(\n  effect: Effect.Effect<Logger.Logger<unknown, A>, E, R>\n): Layer.Layer<never, E, Exclude<R, Scope>> =>\n  layer.unwrapScoped(\n    core.map(effect, addLogger)\n  )\n\n/** @internal */\nexport const removeLogger = <A>(logger: Logger.Logger<unknown, A>): Layer.Layer<never> =>\n  layer.scopedDiscard(\n    fiberRuntime.fiberRefLocallyScopedWith(\n      fiberRuntime.currentLoggers,\n      HashSet.remove(logger)\n    )\n  )\n\n/** @internal */\nexport const replaceLogger = dual<\n  <B>(that: Logger.Logger<unknown, B>) => <A>(self: Logger.Logger<unknown, A>) => Layer.Layer<never>,\n  <A, B>(self: Logger.Logger<unknown, A>, that: Logger.Logger<unknown, B>) => Layer.Layer<never>\n>(2, (self, that) => layer.flatMap(removeLogger(self), () => addLogger(that)))\n\n/** @internal */\nexport const replaceLoggerEffect = dual<\n  <B, E, R>(\n    that: Effect.Effect<Logger.Logger<unknown, B>, E, R>\n  ) => <A>(self: Logger.Logger<unknown, A>) => Layer.Layer<never, E, R>,\n  <A, B, E, R>(\n    self: Logger.Logger<unknown, A>,\n    that: Effect.Effect<Logger.Logger<unknown, B>, E, R>\n  ) => Layer.Layer<never, E, R>\n>(2, (self, that) => layer.flatMap(removeLogger(self), () => addLoggerEffect(that)))\n\n/** @internal */\nexport const replaceLoggerScoped = dual<\n  <B, E, R>(\n    that: Effect.Effect<Logger.Logger<unknown, B>, E, R>\n  ) => <A>(self: Logger.Logger<unknown, A>) => Layer.Layer<never, E, Exclude<R, Scope>>,\n  <A, B, E, R>(\n    self: Logger.Logger<unknown, A>,\n    that: Effect.Effect<Logger.Logger<unknown, B>, E, R>\n  ) => Layer.Layer<never, E, Exclude<R, Scope>>\n>(2, (self, that) => layer.flatMap(removeLogger(self), () => addLoggerScoped(that)))\n\n/** @internal */\nexport const addSupervisor = <A>(supervisor: Supervisor.Supervisor<A>): Layer.Layer<never> =>\n  layer.scopedDiscard(\n    fiberRuntime.fiberRefLocallyScopedWith(\n      fiberRuntime.currentSupervisor,\n      (current) => new supervisor_.Zip(current, supervisor)\n    )\n  )\n\n/** @internal */\nexport const enableCooperativeYielding: Layer.Layer<never> = layer.scopedDiscard(\n  fiberRuntime.withRuntimeFlagsScoped(\n    runtimeFlagsPatch.enable(runtimeFlags.CooperativeYielding)\n  )\n)\n\n/** @internal */\nexport const enableInterruption: Layer.Layer<never> = layer.scopedDiscard(\n  fiberRuntime.withRuntimeFlagsScoped(\n    runtimeFlagsPatch.enable(runtimeFlags.Interruption)\n  )\n)\n\n/** @internal */\nexport const enableOpSupervision: Layer.Layer<never> = layer.scopedDiscard(\n  fiberRuntime.withRuntimeFlagsScoped(\n    runtimeFlagsPatch.enable(runtimeFlags.OpSupervision)\n  )\n)\n\n/** @internal */\nexport const enableRuntimeMetrics: Layer.Layer<never> = layer.scopedDiscard(\n  fiberRuntime.withRuntimeFlagsScoped(\n    runtimeFlagsPatch.enable(runtimeFlags.RuntimeMetrics)\n  )\n)\n\n/** @internal */\nexport const enableWindDown: Layer.Layer<never> = layer.scopedDiscard(\n  fiberRuntime.withRuntimeFlagsScoped(\n    runtimeFlagsPatch.enable(runtimeFlags.WindDown)\n  )\n)\n\n/** @internal */\nexport const disableCooperativeYielding: Layer.Layer<never> = layer.scopedDiscard(\n  fiberRuntime.withRuntimeFlagsScoped(\n    runtimeFlagsPatch.disable(runtimeFlags.CooperativeYielding)\n  )\n)\n\n/** @internal */\nexport const disableInterruption: Layer.Layer<never> = layer.scopedDiscard(\n  fiberRuntime.withRuntimeFlagsScoped(\n    runtimeFlagsPatch.disable(runtimeFlags.Interruption)\n  )\n)\n\n/** @internal */\nexport const disableOpSupervision: Layer.Layer<never> = layer.scopedDiscard(\n  fiberRuntime.withRuntimeFlagsScoped(\n    runtimeFlagsPatch.disable(runtimeFlags.OpSupervision)\n  )\n)\n\n/** @internal */\nexport const disableRuntimeMetrics: Layer.Layer<never> = layer.scopedDiscard(\n  fiberRuntime.withRuntimeFlagsScoped(\n    runtimeFlagsPatch.disable(runtimeFlags.RuntimeMetrics)\n  )\n)\n\n/** @internal */\nexport const disableWindDown: Layer.Layer<never> = layer.scopedDiscard(\n  fiberRuntime.withRuntimeFlagsScoped(\n    runtimeFlagsPatch.disable(runtimeFlags.WindDown)\n  )\n)\n\n/** @internal */\nexport const setConfigProvider = (configProvider: ConfigProvider.ConfigProvider): Layer.Layer<never> =>\n  layer.scopedDiscard(fiberRuntime.withConfigProviderScoped(configProvider))\n\n/** @internal */\nexport const parentSpan = (span: Tracer.AnySpan): Layer.Layer<Tracer.ParentSpan> =>\n  layer.succeedContext(Context.make(tracer.spanTag, span))\n\n/** @internal */\nexport const span = (\n  name: string,\n  options?: Tracer.SpanOptions & {\n    readonly onEnd?:\n      | ((span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>)\n      | undefined\n  }\n): Layer.Layer<Tracer.ParentSpan> => {\n  options = tracer.addSpanStackTrace(options) as any\n  return layer.scoped(\n    tracer.spanTag,\n    options?.onEnd\n      ? core.tap(\n        fiberRuntime.makeSpanScoped(name, options),\n        (span) => fiberRuntime.addFinalizer((exit) => options.onEnd!(span, exit))\n      )\n      : fiberRuntime.makeSpanScoped(name, options)\n  )\n}\n\n/** @internal */\nexport const setTracer = (tracer: Tracer.Tracer): Layer.Layer<never> =>\n  layer.scopedDiscard(fiberRuntime.withTracerScoped(tracer))\n"
  },
  {
    "path": "packages/effect/src/internal/layer.ts",
    "content": "import type * as Arr from \"../Array.js\"\nimport * as Cause from \"../Cause.js\"\nimport * as Clock from \"../Clock.js\"\nimport * as Context from \"../Context.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport type * as Exit from \"../Exit.js\"\nimport type { FiberRef } from \"../FiberRef.js\"\nimport * as FiberRefsPatch from \"../FiberRefsPatch.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { constTrue, dual, pipe } from \"../Function.js\"\nimport * as HashMap from \"../HashMap.js\"\nimport type * as Layer from \"../Layer.js\"\nimport type * as ManagedRuntime from \"../ManagedRuntime.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as Runtime from \"../Runtime.js\"\nimport type * as Schedule from \"../Schedule.js\"\nimport * as ScheduleDecision from \"../ScheduleDecision.js\"\nimport * as Intervals from \"../ScheduleIntervals.js\"\nimport * as Scope from \"../Scope.js\"\nimport type * as Synchronized from \"../SynchronizedRef.js\"\nimport type * as Tracer from \"../Tracer.js\"\nimport type * as Types from \"../Types.js\"\nimport * as effect from \"./core-effect.js\"\nimport * as core from \"./core.js\"\nimport * as circular from \"./effect/circular.js\"\nimport * as ExecutionStrategy from \"./executionStrategy.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\nimport * as circularManagedRuntime from \"./managedRuntime/circular.js\"\nimport * as EffectOpCodes from \"./opCodes/effect.js\"\nimport * as OpCodes from \"./opCodes/layer.js\"\nimport * as ref from \"./ref.js\"\nimport * as runtime from \"./runtime.js\"\nimport * as runtimeFlags from \"./runtimeFlags.js\"\nimport * as synchronized from \"./synchronizedRef.js\"\nimport * as tracer from \"./tracer.js\"\n\n/** @internal */\nconst LayerSymbolKey = \"effect/Layer\"\n\n/** @internal */\nexport const LayerTypeId: Layer.LayerTypeId = Symbol.for(\n  LayerSymbolKey\n) as Layer.LayerTypeId\n\nconst layerVariance = {\n  /* c8 ignore next */\n  _RIn: (_: never) => _,\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _ROut: (_: unknown) => _\n}\n\n/** @internal */\nexport const proto = {\n  [LayerTypeId]: layerVariance,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nconst MemoMapTypeIdKey = \"effect/Layer/MemoMap\"\n\n/** @internal */\nexport const MemoMapTypeId: Layer.MemoMapTypeId = Symbol.for(\n  MemoMapTypeIdKey\n) as Layer.MemoMapTypeId\n\n/** @internal */\nexport const CurrentMemoMap = Context.Reference<Layer.CurrentMemoMap>()(\"effect/Layer/CurrentMemoMap\", {\n  defaultValue: () => unsafeMakeMemoMap()\n})\n\n/** @internal */\nexport type Primitive =\n  | ExtendScope\n  | Fold\n  | Fresh\n  | FromEffect\n  | Scoped\n  | Suspend\n  | Locally\n  | ProvideTo\n  | ZipWith\n  | ZipWithPar\n  | MergeAll\n\n/** @internal */\nexport type Op<Tag extends string, Body = {}> = Layer.Layer<unknown, unknown, unknown> & Body & {\n  readonly _op_layer: Tag\n}\n\n/** @internal */\nexport interface ExtendScope extends\n  Op<OpCodes.OP_EXTEND_SCOPE, {\n    readonly layer: Layer.Layer<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Fold extends\n  Op<OpCodes.OP_FOLD, {\n    readonly layer: Layer.Layer<unknown>\n    failureK(cause: Cause.Cause<unknown>): Layer.Layer<unknown>\n    successK(context: Context.Context<unknown>): Layer.Layer<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Fresh extends\n  Op<OpCodes.OP_FRESH, {\n    readonly layer: Layer.Layer<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface FromEffect extends\n  Op<OpCodes.OP_FROM_EFFECT, {\n    readonly effect: Effect.Effect<unknown, unknown, Context.Context<unknown>>\n  }>\n{}\n\n/** @internal */\nexport interface Scoped extends\n  Op<OpCodes.OP_SCOPED, {\n    readonly effect: Effect.Effect<unknown, unknown, Context.Context<unknown>>\n  }>\n{}\n\n/** @internal */\nexport interface Suspend extends\n  Op<OpCodes.OP_SUSPEND, {\n    evaluate(): Layer.Layer<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface Locally extends\n  Op<\"Locally\", {\n    readonly self: Layer.Layer<unknown>\n    f(_: Effect.Effect<any, any, any>): Effect.Effect<any, any, any>\n  }>\n{}\n\n/** @internal */\nexport interface ProvideTo extends\n  Op<OpCodes.OP_PROVIDE, {\n    readonly first: Layer.Layer<unknown>\n    readonly second: Layer.Layer<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface ZipWith extends\n  Op<OpCodes.OP_PROVIDE_MERGE, {\n    readonly first: Layer.Layer<unknown>\n    readonly second: Layer.Layer<unknown>\n    zipK(left: Context.Context<unknown>, right: Context.Context<unknown>): Context.Context<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface ZipWithPar extends\n  Op<OpCodes.OP_ZIP_WITH, {\n    readonly first: Layer.Layer<unknown>\n    readonly second: Layer.Layer<unknown>\n    zipK(left: Context.Context<unknown>, right: Context.Context<unknown>): Context.Context<unknown>\n  }>\n{}\n\n/** @internal */\nexport interface MergeAll extends\n  Op<OpCodes.OP_MERGE_ALL, {\n    readonly layers: Arr.NonEmptyReadonlyArray<Layer.Layer<unknown>>\n  }>\n{}\n\n/** @internal */\nexport const isLayer = (u: unknown): u is Layer.Layer<unknown, unknown, unknown> => hasProperty(u, LayerTypeId)\n\n/** @internal */\nexport const isFresh = <RIn, E, ROut>(self: Layer.Layer<ROut, E, RIn>): boolean => {\n  return (self as Primitive)._op_layer === OpCodes.OP_FRESH\n}\n\n// -----------------------------------------------------------------------------\n// MemoMap\n// -----------------------------------------------------------------------------\n\n/** @internal */\nclass MemoMapImpl implements Layer.MemoMap {\n  readonly [MemoMapTypeId]: Layer.MemoMapTypeId\n  constructor(\n    readonly ref: Synchronized.SynchronizedRef<\n      Map<\n        Layer.Layer<any, any, any>,\n        readonly [Effect.Effect<any, any>, Scope.Scope.Finalizer]\n      >\n    >\n  ) {\n    this[MemoMapTypeId] = MemoMapTypeId\n  }\n\n  /**\n   * Checks the memo map to see if a layer exists. If it is, immediately\n   * returns it. Otherwise, obtains the layer, stores it in the memo map,\n   * and adds a finalizer to the `Scope`.\n   */\n  getOrElseMemoize<RIn, E, ROut>(\n    layer: Layer.Layer<ROut, E, RIn>,\n    scope: Scope.Scope\n  ): Effect.Effect<Context.Context<ROut>, E, RIn> {\n    return pipe(\n      synchronized.modifyEffect(this.ref, (map) => {\n        const inMap = map.get(layer)\n        if (inMap !== undefined) {\n          const [acquire, release] = inMap\n          const cached: Effect.Effect<Context.Context<ROut>, E> = pipe(\n            acquire as Effect.Effect<readonly [FiberRefsPatch.FiberRefsPatch, Context.Context<ROut>], E>,\n            core.flatMap(([patch, b]) => pipe(effect.patchFiberRefs(patch), core.as(b))),\n            core.onExit(core.exitMatch({\n              onFailure: () => core.void,\n              onSuccess: () => core.scopeAddFinalizerExit(scope, release)\n            }))\n          )\n          return core.succeed([cached, map] as const)\n        }\n        return pipe(\n          ref.make(0),\n          core.flatMap((observers) =>\n            pipe(\n              core.deferredMake<readonly [FiberRefsPatch.FiberRefsPatch, Context.Context<ROut>], E>(),\n              core.flatMap((deferred) =>\n                pipe(\n                  ref.make<Scope.Scope.Finalizer>(() => core.void),\n                  core.map((finalizerRef) => {\n                    const resource = core.uninterruptibleMask((restore) =>\n                      pipe(\n                        fiberRuntime.scopeMake(),\n                        core.flatMap((innerScope) =>\n                          pipe(\n                            restore(core.flatMap(\n                              makeBuilder(layer, innerScope, true),\n                              (f) => effect.diffFiberRefs(f(this))\n                            )),\n                            core.exit,\n                            core.flatMap((exit) => {\n                              switch (exit._tag) {\n                                case EffectOpCodes.OP_FAILURE: {\n                                  return pipe(\n                                    core.deferredFailCause(deferred, exit.effect_instruction_i0),\n                                    core.zipRight(core.scopeClose(innerScope, exit)),\n                                    core.zipRight(core.failCause(exit.effect_instruction_i0))\n                                  )\n                                }\n                                case EffectOpCodes.OP_SUCCESS: {\n                                  return pipe(\n                                    ref.set(finalizerRef, (exit) =>\n                                      pipe(\n                                        core.scopeClose(innerScope, exit),\n                                        core.whenEffect(\n                                          ref.modify(observers, (n) => [n === 1, n - 1] as const)\n                                        ),\n                                        core.asVoid\n                                      )),\n                                    core.zipRight(ref.update(observers, (n) => n + 1)),\n                                    core.zipRight(\n                                      core.scopeAddFinalizerExit(scope, (exit) =>\n                                        pipe(\n                                          core.sync(() => map.delete(layer)),\n                                          core.zipRight(ref.get(finalizerRef)),\n                                          core.flatMap((finalizer) => finalizer(exit))\n                                        ))\n                                    ),\n                                    core.zipRight(core.deferredSucceed(deferred, exit.effect_instruction_i0)),\n                                    core.as(exit.effect_instruction_i0[1])\n                                  )\n                                }\n                              }\n                            })\n                          )\n                        )\n                      )\n                    )\n                    const memoized = [\n                      pipe(\n                        core.deferredAwait(deferred),\n                        core.onExit(core.exitMatchEffect({\n                          onFailure: () => core.void,\n                          onSuccess: () => ref.update(observers, (n) => n + 1)\n                        }))\n                      ),\n                      (exit: Exit.Exit<unknown, unknown>) =>\n                        pipe(\n                          ref.get(finalizerRef),\n                          core.flatMap((finalizer) => finalizer(exit))\n                        )\n                    ] as const\n                    return [\n                      resource,\n                      isFresh(layer) ? map : map.set(layer, memoized)\n                    ] as const\n                  })\n                )\n              )\n            )\n          )\n        )\n      }),\n      core.flatten\n    )\n  }\n}\n\n/** @internal */\nexport const makeMemoMap: Effect.Effect<Layer.MemoMap> = core.suspend(() =>\n  core.map(\n    circular.makeSynchronized<\n      Map<\n        Layer.Layer<any, any, any>,\n        readonly [\n          Effect.Effect<any, any>,\n          Scope.Scope.Finalizer\n        ]\n      >\n    >(new Map()),\n    (ref) => new MemoMapImpl(ref)\n  )\n)\n\n/** @internal */\nexport const unsafeMakeMemoMap = (): Layer.MemoMap => new MemoMapImpl(circular.unsafeMakeSynchronized(new Map()))\n\n/** @internal */\nexport const build = <RIn, E, ROut>(\n  self: Layer.Layer<ROut, E, RIn>\n): Effect.Effect<Context.Context<ROut>, E, RIn | Scope.Scope> =>\n  fiberRuntime.scopeWith((scope) => buildWithScope(self, scope))\n\n/** @internal */\nexport const buildWithScope = dual<\n  (\n    scope: Scope.Scope\n  ) => <RIn, E, ROut>(self: Layer.Layer<ROut, E, RIn>) => Effect.Effect<Context.Context<ROut>, E, RIn>,\n  <RIn, E, ROut>(\n    self: Layer.Layer<ROut, E, RIn>,\n    scope: Scope.Scope\n  ) => Effect.Effect<Context.Context<ROut>, E, RIn>\n>(2, (self, scope) =>\n  core.flatMap(\n    makeMemoMap,\n    (memoMap) => buildWithMemoMap(self, memoMap, scope)\n  ))\n\n/** @internal */\nexport const buildWithMemoMap = dual<\n  (\n    memoMap: Layer.MemoMap,\n    scope: Scope.Scope\n  ) => <RIn, E, ROut>(self: Layer.Layer<ROut, E, RIn>) => Effect.Effect<Context.Context<ROut>, E, RIn>,\n  <RIn, E, ROut>(\n    self: Layer.Layer<ROut, E, RIn>,\n    memoMap: Layer.MemoMap,\n    scope: Scope.Scope\n  ) => Effect.Effect<Context.Context<ROut>, E, RIn>\n>(\n  3,\n  (self, memoMap, scope) =>\n    core.flatMap(\n      makeBuilder(self, scope),\n      (run) => effect.provideService(run(memoMap), CurrentMemoMap, memoMap)\n    )\n)\n\nconst makeBuilder = <RIn, E, ROut>(\n  self: Layer.Layer<ROut, E, RIn>,\n  scope: Scope.Scope,\n  inMemoMap = false\n): Effect.Effect<(memoMap: Layer.MemoMap) => Effect.Effect<Context.Context<ROut>, E, RIn>> => {\n  const op = self as Primitive\n  switch (op._op_layer) {\n    case \"Locally\": {\n      return core.sync(() => (memoMap: Layer.MemoMap) => op.f(memoMap.getOrElseMemoize(op.self, scope)))\n    }\n    case \"ExtendScope\": {\n      return core.sync(() => (memoMap: Layer.MemoMap) =>\n        fiberRuntime.scopeWith(\n          (scope) => memoMap.getOrElseMemoize(op.layer, scope)\n        ) as unknown as Effect.Effect<Context.Context<ROut>, E, RIn>\n      )\n    }\n    case \"Fold\": {\n      return core.sync(() => (memoMap: Layer.MemoMap) =>\n        pipe(\n          memoMap.getOrElseMemoize(op.layer, scope),\n          core.matchCauseEffect({\n            onFailure: (cause) => memoMap.getOrElseMemoize(op.failureK(cause), scope),\n            onSuccess: (value) => memoMap.getOrElseMemoize(op.successK(value), scope)\n          })\n        )\n      )\n    }\n    case \"Fresh\": {\n      return core.sync(() => (_: Layer.MemoMap) => pipe(op.layer, buildWithScope(scope)))\n    }\n    case \"FromEffect\": {\n      return inMemoMap\n        ? core.sync(() => (_: Layer.MemoMap) => op.effect as Effect.Effect<Context.Context<ROut>, E, RIn>)\n        : core.sync(() => (memoMap: Layer.MemoMap) => memoMap.getOrElseMemoize(self, scope))\n    }\n    case \"Provide\": {\n      return core.sync(() => (memoMap: Layer.MemoMap) =>\n        pipe(\n          memoMap.getOrElseMemoize(op.first, scope),\n          core.flatMap((env) =>\n            pipe(\n              memoMap.getOrElseMemoize(op.second, scope),\n              core.provideContext(env)\n            )\n          )\n        )\n      )\n    }\n    case \"Scoped\": {\n      return inMemoMap\n        ? core.sync(() => (_: Layer.MemoMap) =>\n          fiberRuntime.scopeExtend(\n            op.effect as Effect.Effect<Context.Context<ROut>, E, RIn>,\n            scope\n          )\n        )\n        : core.sync(() => (memoMap: Layer.MemoMap) => memoMap.getOrElseMemoize(self, scope))\n    }\n    case \"Suspend\": {\n      return core.sync(() => (memoMap: Layer.MemoMap) =>\n        memoMap.getOrElseMemoize(\n          op.evaluate(),\n          scope\n        )\n      )\n    }\n    case \"ProvideMerge\": {\n      return core.sync(() => (memoMap: Layer.MemoMap) =>\n        pipe(\n          memoMap.getOrElseMemoize(op.first, scope),\n          core.zipWith(\n            memoMap.getOrElseMemoize(op.second, scope),\n            op.zipK\n          )\n        )\n      )\n    }\n    case \"ZipWith\": {\n      return core.gen(function*() {\n        const parallelScope = yield* core.scopeFork(scope, ExecutionStrategy.parallel)\n        const firstScope = yield* core.scopeFork(parallelScope, ExecutionStrategy.sequential)\n        const secondScope = yield* core.scopeFork(parallelScope, ExecutionStrategy.sequential)\n        return (memoMap: Layer.MemoMap) =>\n          pipe(\n            memoMap.getOrElseMemoize(op.first, firstScope),\n            fiberRuntime.zipWithOptions(\n              memoMap.getOrElseMemoize(op.second, secondScope),\n              op.zipK,\n              { concurrent: true }\n            )\n          )\n      })\n    }\n    case \"MergeAll\": {\n      const layers = op.layers\n      return core.map(\n        core.scopeFork(scope, ExecutionStrategy.parallel),\n        (parallelScope) => (memoMap: Layer.MemoMap) => {\n          const contexts = new Array<Context.Context<any>>(layers.length)\n          return core.map(\n            fiberRuntime.forEachConcurrentDiscard(\n              layers,\n              core.fnUntraced(function*(layer, i) {\n                const scope = yield* core.scopeFork(parallelScope, ExecutionStrategy.sequential)\n                const context = yield* memoMap.getOrElseMemoize(layer, scope)\n                contexts[i] = context\n              }),\n              false,\n              false\n            ),\n            () => Context.mergeAll(...contexts)\n          )\n        }\n      )\n    }\n  }\n}\n\n// -----------------------------------------------------------------------------\n// Layer\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const catchAll = dual<\n  <E, RIn2, E2, ROut2>(\n    onError: (error: E) => Layer.Layer<ROut2, E2, RIn2>\n  ) => <RIn, ROut>(self: Layer.Layer<ROut, E, RIn>) => Layer.Layer<ROut & ROut2, E2, RIn | RIn2>,\n  <RIn, E, ROut, RIn2, E2, ROut2>(\n    self: Layer.Layer<ROut, E, RIn>,\n    onError: (error: E) => Layer.Layer<ROut2, E2, RIn2>\n  ) => Layer.Layer<ROut & ROut2, E2, RIn | RIn2>\n>(2, (self, onFailure) => match(self, { onFailure, onSuccess: succeedContext }))\n\n/** @internal */\nexport const catchAllCause = dual<\n  <E, RIn2, E2, ROut2>(\n    onError: (cause: Cause.Cause<E>) => Layer.Layer<ROut2, E2, RIn2>\n  ) => <RIn, ROut>(self: Layer.Layer<ROut, E, RIn>) => Layer.Layer<ROut & ROut2, E2, RIn | RIn2>,\n  <RIn, E, ROut, RIn2, E2, ROut22>(\n    self: Layer.Layer<ROut, E, RIn>,\n    onError: (cause: Cause.Cause<E>) => Layer.Layer<ROut22, E2, RIn2>\n  ) => Layer.Layer<ROut & ROut22, E2, RIn | RIn2>\n>(2, (self, onFailure) => matchCause(self, { onFailure, onSuccess: succeedContext }))\n\n/** @internal */\nexport const die = (defect: unknown): Layer.Layer<unknown> => failCause(Cause.die(defect))\n\n/** @internal */\nexport const dieSync = (evaluate: LazyArg<unknown>): Layer.Layer<unknown> => failCauseSync(() => Cause.die(evaluate()))\n\n/** @internal */\nexport const discard = <RIn, E, ROut>(self: Layer.Layer<ROut, E, RIn>): Layer.Layer<never, E, RIn> =>\n  map(self, () => Context.empty())\n\n/** @internal */\nexport const context = <R>(): Layer.Layer<R, never, R> => fromEffectContext(core.context<R>())\n\n/** @internal */\nexport const extendScope = <RIn, E, ROut>(\n  self: Layer.Layer<ROut, E, RIn>\n): Layer.Layer<ROut, E, RIn | Scope.Scope> => {\n  const extendScope = Object.create(proto)\n  extendScope._op_layer = OpCodes.OP_EXTEND_SCOPE\n  extendScope.layer = self\n  return extendScope\n}\n\n/** @internal */\nexport const fail = <E>(error: E): Layer.Layer<unknown, E> => failCause(Cause.fail(error))\n\n/** @internal */\nexport const failSync = <E>(evaluate: LazyArg<E>): Layer.Layer<unknown, E> =>\n  failCauseSync(() => Cause.fail(evaluate()))\n\n/** @internal */\nexport const failCause = <E>(cause: Cause.Cause<E>): Layer.Layer<unknown, E> => fromEffectContext(core.failCause(cause))\n\n/** @internal */\nexport const failCauseSync = <E>(evaluate: LazyArg<Cause.Cause<E>>): Layer.Layer<unknown, E> =>\n  fromEffectContext(core.failCauseSync(evaluate))\n\n/** @internal */\nexport const flatMap = dual<\n  <A, A2, E2, R2>(\n    f: (context: Context.Context<A>) => Layer.Layer<A2, E2, R2>\n  ) => <E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A2, E | E2, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Layer.Layer<A, E, R>,\n    f: (context: Context.Context<A>) => Layer.Layer<A2, E2, R2>\n  ) => Layer.Layer<A2, E | E2, R | R2>\n>(2, (self, f) => match(self, { onFailure: fail, onSuccess: f }))\n\n/** @internal */\nexport const flatten = dual<\n  <I, A, E2, R2>(\n    tag: Context.Tag<I, Layer.Layer<A, E2, R2>>\n  ) => <E, R>(\n    self: Layer.Layer<I, E, R>\n  ) => Layer.Layer<A, E | E2, R | R2>,\n  <I, E, R, A, E2, R2>(\n    self: Layer.Layer<I, E, R>,\n    tag: Context.Tag<I, Layer.Layer<A, E2, R2>>\n  ) => Layer.Layer<A, E | E2, R | R2>\n>(2, (self, tag) => flatMap(self, Context.get(tag as any) as any))\n\n/** @internal */\nexport const fresh = <A, E, R>(self: Layer.Layer<A, E, R>): Layer.Layer<A, E, R> => {\n  const fresh = Object.create(proto)\n  fresh._op_layer = OpCodes.OP_FRESH\n  fresh.layer = self\n  return fresh\n}\n\n/** @internal */\nexport const fromEffect = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>\n  ) => <E, R>(\n    effect: Effect.Effect<Types.NoInfer<S>, E, R>\n  ) => Layer.Layer<I, E, R>,\n  <I, S, E, R>(\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<Types.NoInfer<S>, E, R>\n  ) => Layer.Layer<I, E, R>\n>(2, (a, b) => {\n  const tagFirst = Context.isTag(a)\n  const tag = (tagFirst ? a : b) as Context.Tag<unknown, unknown>\n  const effect = tagFirst ? b : a\n  return fromEffectContext(core.map(effect, (service) => Context.make(tag, service)))\n})\n\n/** @internal */\nexport const fromEffectDiscard = <X, E, R>(effect: Effect.Effect<X, E, R>) =>\n  fromEffectContext(core.map(effect, () => Context.empty()))\n\n/** @internal */\nexport function fromEffectContext<A, E, R>(\n  effect: Effect.Effect<Context.Context<A>, E, R>\n): Layer.Layer<A, E, R> {\n  const fromEffect = Object.create(proto)\n  fromEffect._op_layer = OpCodes.OP_FROM_EFFECT\n  fromEffect.effect = effect\n  return fromEffect\n}\n\n/** @internal */\nexport const fiberRefLocally = dual<\n  <X>(ref: FiberRef<X>, value: X) => <A, E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>,\n  <A, E, R, X>(self: Layer.Layer<A, E, R>, ref: FiberRef<X>, value: X) => Layer.Layer<A, E, R>\n>(3, (self, ref, value) => locallyEffect(self, core.fiberRefLocally(ref, value)))\n\n/** @internal */\nexport const locallyEffect = dual<\n  <RIn, E, ROut, RIn2, E2, ROut2>(\n    f: (_: Effect.Effect<RIn, E, Context.Context<ROut>>) => Effect.Effect<RIn2, E2, Context.Context<ROut2>>\n  ) => (self: Layer.Layer<ROut, E, RIn>) => Layer.Layer<ROut2, E2, RIn2>,\n  <RIn, E, ROut, RIn2, E2, ROut2>(\n    self: Layer.Layer<ROut, E, RIn>,\n    f: (_: Effect.Effect<RIn, E, Context.Context<ROut>>) => Effect.Effect<RIn2, E2, Context.Context<ROut2>>\n  ) => Layer.Layer<ROut2, E2, RIn2>\n>(2, (self, f) => {\n  const locally = Object.create(proto)\n  locally._op_layer = \"Locally\"\n  locally.self = self\n  locally.f = f\n  return locally\n})\n\n/** @internal */\nexport const fiberRefLocallyWith = dual<\n  <X>(ref: FiberRef<X>, value: (_: X) => X) => <A, E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>,\n  <A, E, R, X>(self: Layer.Layer<A, E, R>, ref: FiberRef<X>, value: (_: X) => X) => Layer.Layer<A, E, R>\n>(3, (self, ref, value) => locallyEffect(self, core.fiberRefLocallyWith(ref, value)))\n\n/** @internal */\nexport const fiberRefLocallyScoped = <A>(self: FiberRef<A>, value: A): Layer.Layer<never> =>\n  scopedDiscard(fiberRuntime.fiberRefLocallyScoped(self, value))\n\n/** @internal */\nexport const fiberRefLocallyScopedWith = <A>(self: FiberRef<A>, value: (_: A) => A): Layer.Layer<never> =>\n  scopedDiscard(fiberRuntime.fiberRefLocallyScopedWith(self, value))\n\n/** @internal */\nexport const fromFunction = <I1, S1, I2, S2>(\n  tagA: Context.Tag<I1, S1>,\n  tagB: Context.Tag<I2, S2>,\n  f: (a: Types.NoInfer<S1>) => Types.NoInfer<S2>\n): Layer.Layer<I2, never, I1> => fromEffectContext(core.map(tagA, (a) => Context.make(tagB, f(a))))\n\n/** @internal */\nexport const launch = <RIn, E, ROut>(self: Layer.Layer<ROut, E, RIn>): Effect.Effect<never, E, RIn> =>\n  fiberRuntime.scopedEffect(\n    core.zipRight(\n      fiberRuntime.scopeWith((scope) => pipe(self, buildWithScope(scope))),\n      core.never\n    )\n  )\n\n/** @internal */\nexport const mock: {\n  <I, S extends object>(tag: Context.Tag<I, S>): (service: Layer.PartialEffectful<S>) => Layer.Layer<I>\n  <I, S extends object>(tag: Context.Tag<I, S>, service: Layer.PartialEffectful<S>): Layer.Layer<I>\n} = function() {\n  if (arguments.length === 1) {\n    return (service: Layer.PartialEffectful<any>) => mockImpl(arguments[0], service)\n  }\n  return mockImpl(arguments[0], arguments[1])\n} as any\n\nconst mockImpl = <I, S extends object>(tag: Context.Tag<I, S>, service: Layer.PartialEffectful<S>): Layer.Layer<I> =>\n  succeed(\n    tag,\n    new Proxy({ ...service as object } as S, {\n      get(target, prop, _receiver) {\n        if (prop in target) {\n          return target[prop as keyof S]\n        }\n        const prevLimit = Error.stackTraceLimit\n        Error.stackTraceLimit = 2\n        const error = new Error(`${tag.key}: Unimplemented method \"${prop.toString()}\"`)\n        Error.stackTraceLimit = prevLimit\n        error.name = \"UnimplementedError\"\n        return makeUnimplemented(error)\n      },\n      has: constTrue\n    })\n  )\n\nconst makeUnimplemented = (error: Error) => {\n  const dead = core.die(error)\n  function unimplemented() {\n    return dead\n  }\n  // @effect-diagnostics-next-line floatingEffect:off\n  Object.assign(unimplemented, dead)\n  Object.setPrototypeOf(unimplemented, Object.getPrototypeOf(dead))\n  return unimplemented\n}\n\n/** @internal */\nexport const map = dual<\n  <A, B>(\n    f: (context: Context.Context<A>) => Context.Context<B>\n  ) => <E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<B, E, R>,\n  <A, E, R, B>(\n    self: Layer.Layer<A, E, R>,\n    f: (context: Context.Context<A>) => Context.Context<B>\n  ) => Layer.Layer<B, E, R>\n>(2, (self, f) => flatMap(self, (context) => succeedContext(f(context))))\n\n/** @internal */\nexport const mapError = dual<\n  <E, E2>(f: (error: E) => E2) => <A, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A, E2, R>,\n  <A, E, R, E2>(self: Layer.Layer<A, E, R>, f: (error: E) => E2) => Layer.Layer<A, E2, R>\n>(2, (self, f) => catchAll(self, (error) => failSync(() => f(error))))\n\n/** @internal */\nexport const matchCause = dual<\n  <E, A2, E2, R2, A, A3, E3, R3>(\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Layer.Layer<A2, E2, R2>\n      readonly onSuccess: (context: Context.Context<A>) => Layer.Layer<A3, E3, R3>\n    }\n  ) => <R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A2 & A3, E2 | E3, R | R2 | R3>,\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Layer.Layer<A, E, R>,\n    options: {\n      readonly onFailure: (cause: Cause.Cause<E>) => Layer.Layer<A2, E2, R2>\n      readonly onSuccess: (context: Context.Context<A>) => Layer.Layer<A3, E3, R3>\n    }\n  ) => Layer.Layer<A2 & A3, E2 | E3, R | R2 | R3>\n>(2, (self, { onFailure, onSuccess }) => {\n  const fold = Object.create(proto)\n  fold._op_layer = OpCodes.OP_FOLD\n  fold.layer = self\n  fold.failureK = onFailure\n  fold.successK = onSuccess\n  return fold\n})\n\n/** @internal */\nexport const match = dual<\n  <E, A2, E2, R2, A, A3, E3, R3>(\n    options: {\n      readonly onFailure: (error: E) => Layer.Layer<A2, E2, R2>\n      readonly onSuccess: (context: Context.Context<A>) => Layer.Layer<A3, E3, R3>\n    }\n  ) => <R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A2 & A3, E2 | E3, R | R2 | R3>,\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    self: Layer.Layer<A, E, R>,\n    options: {\n      readonly onFailure: (error: E) => Layer.Layer<A2, E2, R2>\n      readonly onSuccess: (context: Context.Context<A>) => Layer.Layer<A3, E3, R3>\n    }\n  ) => Layer.Layer<A2 & A3, E2 | E3, R | R2 | R3>\n>(2, (self, { onFailure, onSuccess }) =>\n  matchCause(self, {\n    onFailure: (cause) => {\n      const failureOrCause = Cause.failureOrCause(cause)\n      switch (failureOrCause._tag) {\n        case \"Left\": {\n          return onFailure(failureOrCause.left)\n        }\n        case \"Right\": {\n          return failCause(failureOrCause.right)\n        }\n      }\n    },\n    onSuccess\n  }))\n\n/** @internal */\nexport const memoize = <RIn, E, ROut>(\n  self: Layer.Layer<ROut, E, RIn>\n): Effect.Effect<Layer.Layer<ROut, E, RIn>, never, Scope.Scope> =>\n  fiberRuntime.scopeWith((scope) =>\n    core.map(\n      effect.memoize(buildWithScope(self, scope)),\n      fromEffectContext\n    )\n  )\n\n/** @internal */\nexport const merge = dual<\n  <RIn2, E2, ROut2>(\n    that: Layer.Layer<ROut2, E2, RIn2>\n  ) => <RIn, E1, ROut>(self: Layer.Layer<ROut, E1, RIn>) => Layer.Layer<\n    ROut | ROut2,\n    E1 | E2,\n    RIn | RIn2\n  >,\n  <RIn, E1, ROut, RIn2, E2, ROut2>(self: Layer.Layer<ROut, E1, RIn>, that: Layer.Layer<ROut2, E2, RIn2>) => Layer.Layer<\n    ROut | ROut2,\n    E1 | E2,\n    RIn | RIn2\n  >\n>(2, (self, that) => zipWith(self, that, (a, b) => Context.merge(a, b)))\n\n/** @internal */\nexport const mergeAll = <\n  Layers extends readonly [Layer.Layer<never, any, any>, ...Array<Layer.Layer<never, any, any>>]\n>(\n  ...layers: Layers\n): Layer.Layer<\n  { [k in keyof Layers]: Layer.Layer.Success<Layers[k]> }[number],\n  { [k in keyof Layers]: Layer.Layer.Error<Layers[k]> }[number],\n  { [k in keyof Layers]: Layer.Layer.Context<Layers[k]> }[number]\n> => {\n  const mergeAll = Object.create(proto)\n  mergeAll._op_layer = OpCodes.OP_MERGE_ALL\n  mergeAll.layers = layers\n  return mergeAll as any\n}\n\n/** @internal */\nexport const orDie = <A, E, R>(self: Layer.Layer<A, E, R>): Layer.Layer<A, never, R> =>\n  catchAll(self, (defect) => die(defect))\n\n/** @internal */\nexport const orElse = dual<\n  <A2, E2, R2>(\n    that: LazyArg<Layer.Layer<A2, E2, R2>>\n  ) => <A, E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A & A2, E | E2, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Layer.Layer<A, E, R>,\n    that: LazyArg<Layer.Layer<A2, E2, R2>>\n  ) => Layer.Layer<A & A2, E | E2, R | R2>\n>(2, (self, that) => catchAll(self, that))\n\n/** @internal */\nexport const passthrough = <RIn, E, ROut>(self: Layer.Layer<ROut, E, RIn>): Layer.Layer<RIn | ROut, E, RIn> =>\n  merge(context<RIn>(), self)\n\n/** @internal */\nexport const project = dual<\n  <I1, S1, I2, S2>(\n    tagA: Context.Tag<I1, S1>,\n    tagB: Context.Tag<I2, S2>,\n    f: (a: Types.NoInfer<S1>) => Types.NoInfer<S2>\n  ) => <RIn, E>(self: Layer.Layer<I1, E, RIn>) => Layer.Layer<I2, E, RIn>,\n  <RIn, E, I1, S1, I2, S2>(\n    self: Layer.Layer<I1, E, RIn>,\n    tagA: Context.Tag<I1, S1>,\n    tagB: Context.Tag<I2, S2>,\n    f: (a: Types.NoInfer<S1>) => Types.NoInfer<S2>\n  ) => Layer.Layer<I2, E, RIn>\n>(4, (self, tagA, tagB, f) => map(self, (context) => Context.make(tagB, f(Context.unsafeGet(context, tagA)))))\n\n/** @internal */\nexport const retry = dual<\n  <X, E, RIn2>(\n    schedule: Schedule.Schedule<X, E, RIn2>\n  ) => <ROut, RIn>(\n    self: Layer.Layer<ROut, E, RIn>\n  ) => Layer.Layer<ROut, E, RIn | RIn2>,\n  <ROut, E, RIn, X, RIn2>(\n    self: Layer.Layer<ROut, E, RIn>,\n    schedule: Schedule.Schedule<X, E, RIn2>\n  ) => Layer.Layer<ROut, E, RIn | RIn2>\n>(2, (self, schedule) =>\n  suspend(() => {\n    const stateTag = Context.GenericTag<{ state: unknown }>(\"effect/Layer/retry/{ state: unknown }\")\n    return pipe(\n      succeed(stateTag, { state: schedule.initial }),\n      flatMap((env: Context.Context<{ state: unknown }>) =>\n        retryLoop(self, schedule, stateTag, pipe(env, Context.get(stateTag)).state)\n      )\n    )\n  }))\n\nconst retryLoop = <ROut, E, RIn, X, RIn2>(\n  self: Layer.Layer<ROut, E, RIn>,\n  schedule: Schedule.Schedule<X, E, RIn2>,\n  stateTag: Context.Tag<{ state: unknown }, { state: unknown }>,\n  state: unknown\n): Layer.Layer<ROut, E, RIn | RIn2> => {\n  return pipe(\n    self,\n    catchAll((error) =>\n      pipe(\n        retryUpdate(schedule, stateTag, error, state),\n        flatMap((env) => fresh(retryLoop(self, schedule, stateTag, pipe(env, Context.get(stateTag)).state)))\n      )\n    )\n  )\n}\n\nconst retryUpdate = <X, E, RIn>(\n  schedule: Schedule.Schedule<X, E, RIn>,\n  stateTag: Context.Tag<{ state: unknown }, { state: unknown }>,\n  error: E,\n  state: unknown\n): Layer.Layer<{ state: unknown }, E, RIn> => {\n  return fromEffect(\n    stateTag,\n    pipe(\n      Clock.currentTimeMillis,\n      core.flatMap((now) =>\n        pipe(\n          schedule.step(now, error, state),\n          core.flatMap(([state, _, decision]) =>\n            ScheduleDecision.isDone(decision) ?\n              core.fail(error) :\n              pipe(\n                Clock.sleep(Duration.millis(Intervals.start(decision.intervals) - now)),\n                core.as({ state })\n              )\n          )\n        )\n      )\n    )\n  )\n}\n\n/** @internal */\nexport const scoped = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>\n  ) => <E, R>(\n    effect: Effect.Effect<Types.NoInfer<S>, E, R>\n  ) => Layer.Layer<I, E, Exclude<R, Scope.Scope>>,\n  <I, S, E, R>(\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<Types.NoInfer<S>, E, R>\n  ) => Layer.Layer<I, E, Exclude<R, Scope.Scope>>\n>(2, (a, b) => {\n  const tagFirst = Context.isTag(a)\n  const tag = (tagFirst ? a : b) as Context.Tag<unknown, unknown>\n  const effect = tagFirst ? b : a\n  return scopedContext(core.map(effect, (service) => Context.make(tag, service)))\n})\n\n/** @internal */\nexport const scopedDiscard = <X, E, R>(\n  effect: Effect.Effect<X, E, R>\n): Layer.Layer<never, E, Exclude<R, Scope.Scope>> => scopedContext(pipe(effect, core.as(Context.empty())))\n\n/** @internal */\nexport const scopedContext = <A, E, R>(\n  effect: Effect.Effect<Context.Context<A>, E, R>\n): Layer.Layer<A, E, Exclude<R, Scope.Scope>> => {\n  const scoped = Object.create(proto)\n  scoped._op_layer = OpCodes.OP_SCOPED\n  scoped.effect = effect\n  return scoped\n}\n\n/** @internal */\nexport const scope: Layer.Layer<Scope.Scope> = scopedContext(\n  core.map(\n    fiberRuntime.acquireRelease(\n      fiberRuntime.scopeMake(),\n      (scope, exit) => scope.close(exit)\n    ),\n    (scope) => Context.make(Scope.Scope, scope)\n  )\n)\n\n/** @internal */\nexport const service = <I, S>(\n  tag: Context.Tag<I, S>\n): Layer.Layer<I, never, I> => fromEffect(tag, tag)\n\n/** @internal */\nexport const succeed = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>\n  ) => (\n    resource: Types.NoInfer<S>\n  ) => Layer.Layer<I>,\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    resource: Types.NoInfer<S>\n  ) => Layer.Layer<I>\n>(2, (a, b) => {\n  const tagFirst = Context.isTag(a)\n  const tag = (tagFirst ? a : b) as Context.Tag<unknown, unknown>\n  const resource = tagFirst ? b : a\n  return fromEffectContext(core.succeed(Context.make(tag, resource)))\n})\n\n/** @internal */\nexport const succeedContext = <A>(\n  context: Context.Context<A>\n): Layer.Layer<A> => {\n  return fromEffectContext(core.succeed(context))\n}\n\n/** @internal */\nexport const empty = succeedContext(Context.empty())\n\n/** @internal */\nexport const suspend = <RIn, E, ROut>(\n  evaluate: LazyArg<Layer.Layer<ROut, E, RIn>>\n): Layer.Layer<ROut, E, RIn> => {\n  const suspend = Object.create(proto)\n  suspend._op_layer = OpCodes.OP_SUSPEND\n  suspend.evaluate = evaluate\n  return suspend\n}\n\n/** @internal */\nexport const sync = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>\n  ) => (\n    evaluate: LazyArg<Types.NoInfer<S>>\n  ) => Layer.Layer<I>,\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    evaluate: LazyArg<Types.NoInfer<S>>\n  ) => Layer.Layer<I>\n>(2, (a, b) => {\n  const tagFirst = Context.isTag(a)\n  const tag = (tagFirst ? a : b) as Context.Tag<unknown, unknown>\n  const evaluate = tagFirst ? b : a\n  return fromEffectContext(core.sync(() => Context.make(tag, evaluate())))\n})\n\n/** @internal */\nexport const syncContext = <A>(evaluate: LazyArg<Context.Context<A>>): Layer.Layer<A> => {\n  return fromEffectContext(core.sync(evaluate))\n}\n\n/** @internal */\nexport const tap = dual<\n  <ROut, XR extends ROut, RIn2, E2, X>(\n    f: (context: Context.Context<XR>) => Effect.Effect<X, E2, RIn2>\n  ) => <RIn, E>(self: Layer.Layer<ROut, E, RIn>) => Layer.Layer<ROut, E | E2, RIn | RIn2>,\n  <RIn, E, ROut, XR extends ROut, RIn2, E2, X>(\n    self: Layer.Layer<ROut, E, RIn>,\n    f: (context: Context.Context<XR>) => Effect.Effect<X, E2, RIn2>\n  ) => Layer.Layer<ROut, E | E2, RIn | RIn2>\n>(2, (self, f) => flatMap(self, (context) => fromEffectContext(core.as(f(context), context))))\n\n/** @internal */\nexport const tapError = dual<\n  <E, XE extends E, RIn2, E2, X>(\n    f: (e: XE) => Effect.Effect<X, E2, RIn2>\n  ) => <RIn, ROut>(self: Layer.Layer<ROut, E, RIn>) => Layer.Layer<ROut, E | E2, RIn | RIn2>,\n  <RIn, E, XE extends E, ROut, RIn2, E2, X>(\n    self: Layer.Layer<ROut, E, RIn>,\n    f: (e: XE) => Effect.Effect<X, E2, RIn2>\n  ) => Layer.Layer<ROut, E | E2, RIn | RIn2>\n>(2, (self, f) =>\n  catchAll(\n    self,\n    (e) => fromEffectContext(core.flatMap(f(e as any), () => core.fail(e)))\n  ))\n\n/** @internal */\nexport const tapErrorCause = dual<\n  <E, XE extends E, RIn2, E2, X>(\n    f: (cause: Cause.Cause<XE>) => Effect.Effect<X, E2, RIn2>\n  ) => <RIn, ROut>(self: Layer.Layer<ROut, E, RIn>) => Layer.Layer<ROut, E | E2, RIn | RIn2>,\n  <RIn, E, XE extends E, ROut, RIn2, E2, X>(\n    self: Layer.Layer<ROut, E, RIn>,\n    f: (cause: Cause.Cause<XE>) => Effect.Effect<X, E2, RIn2>\n  ) => Layer.Layer<ROut, E | E2, RIn | RIn2>\n>(2, (self, f) =>\n  catchAllCause(\n    self,\n    (cause) => fromEffectContext(core.flatMap(f(cause as any), () => core.failCause(cause)))\n  ))\n\n/** @internal */\nexport const toRuntime = <RIn, E, ROut>(\n  self: Layer.Layer<ROut, E, RIn>\n): Effect.Effect<Runtime.Runtime<ROut>, E, RIn | Scope.Scope> =>\n  pipe(\n    fiberRuntime.scopeWith((scope) => buildWithScope(self, scope)),\n    core.flatMap((context) =>\n      pipe(\n        runtime.runtime<ROut>(),\n        core.provideContext(context)\n      )\n    )\n  )\n\n/** @internal */\nexport const toRuntimeWithMemoMap = dual<\n  (\n    memoMap: Layer.MemoMap\n  ) => <RIn, E, ROut>(self: Layer.Layer<ROut, E, RIn>) => Effect.Effect<Runtime.Runtime<ROut>, E, RIn | Scope.Scope>,\n  <RIn, E, ROut>(\n    self: Layer.Layer<ROut, E, RIn>,\n    memoMap: Layer.MemoMap\n  ) => Effect.Effect<Runtime.Runtime<ROut>, E, RIn | Scope.Scope>\n>(2, (self, memoMap) =>\n  core.flatMap(\n    fiberRuntime.scopeWith((scope) => buildWithMemoMap(self, memoMap, scope)),\n    (context) =>\n      pipe(\n        runtime.runtime<any>(),\n        core.provideContext(context)\n      )\n  ))\n\n/** @internal */\nexport const provide = dual<\n  {\n    <RIn, E, ROut>(\n      that: Layer.Layer<ROut, E, RIn>\n    ): <RIn2, E2, ROut2>(\n      self: Layer.Layer<ROut2, E2, RIn2>\n    ) => Layer.Layer<ROut2, E | E2, RIn | Exclude<RIn2, ROut>>\n    <const Layers extends readonly [Layer.Layer.Any, ...Array<Layer.Layer.Any>]>(\n      that: Layers\n    ): <A, E, R>(\n      self: Layer.Layer<A, E, R>\n    ) => Layer.Layer<\n      A,\n      E | { [k in keyof Layers]: Layer.Layer.Error<Layers[k]> }[number],\n      | { [k in keyof Layers]: Layer.Layer.Context<Layers[k]> }[number]\n      | Exclude<R, { [k in keyof Layers]: Layer.Layer.Success<Layers[k]> }[number]>\n    >\n  },\n  {\n    <RIn2, E2, ROut2, RIn, E, ROut>(\n      self: Layer.Layer<ROut2, E2, RIn2>,\n      that: Layer.Layer<ROut, E, RIn>\n    ): Layer.Layer<ROut2, E | E2, RIn | Exclude<RIn2, ROut>>\n    <A, E, R, const Layers extends readonly [Layer.Layer.Any, ...Array<Layer.Layer.Any>]>(\n      self: Layer.Layer<A, E, R>,\n      that: Layers\n    ): Layer.Layer<\n      A,\n      E | { [k in keyof Layers]: Layer.Layer.Error<Layers[k]> }[number],\n      | { [k in keyof Layers]: Layer.Layer.Context<Layers[k]> }[number]\n      | Exclude<R, { [k in keyof Layers]: Layer.Layer.Success<Layers[k]> }[number]>\n    >\n  }\n>(2, (\n  self: Layer.Layer.Any,\n  that: Layer.Layer.Any | ReadonlyArray<Layer.Layer.Any>\n) =>\n  suspend(() => {\n    const provideTo = Object.create(proto)\n    provideTo._op_layer = OpCodes.OP_PROVIDE\n    provideTo.first = Object.create(proto, {\n      _op_layer: { value: OpCodes.OP_PROVIDE_MERGE, enumerable: true },\n      first: { value: context(), enumerable: true },\n      second: { value: Array.isArray(that) ? mergeAll(...that as any) : that },\n      zipK: { value: (a: Context.Context<any>, b: Context.Context<any>) => pipe(a, Context.merge(b)) }\n    })\n    provideTo.second = self\n    return provideTo\n  }))\n\n/** @internal */\nexport const provideMerge = dual<\n  <RIn, E, ROut>(\n    self: Layer.Layer<ROut, E, RIn>\n  ) => <RIn2, E2, ROut2>(\n    that: Layer.Layer<ROut2, E2, RIn2>\n  ) => Layer.Layer<ROut | ROut2, E2 | E, RIn | Exclude<RIn2, ROut>>,\n  <RIn2, E2, ROut2, RIn, E, ROut>(\n    that: Layer.Layer<ROut2, E2, RIn2>,\n    self: Layer.Layer<ROut, E, RIn>\n  ) => Layer.Layer<ROut | ROut2, E2 | E, RIn | Exclude<RIn2, ROut>>\n>(2, <RIn2, E2, ROut2, RIn, E, ROut>(that: Layer.Layer<ROut2, E2, RIn2>, self: Layer.Layer<ROut, E, RIn>) => {\n  const zipWith = Object.create(proto)\n  zipWith._op_layer = OpCodes.OP_PROVIDE_MERGE\n  zipWith.first = self\n  zipWith.second = provide(that, self)\n  zipWith.zipK = (a: Context.Context<ROut>, b: Context.Context<ROut2>): Context.Context<ROut | ROut2> => {\n    return pipe(a, Context.merge(b))\n  }\n  return zipWith\n})\n\n/** @internal */\nexport const zipWith = dual<\n  <B, E2, R2, A, C>(\n    that: Layer.Layer<B, E2, R2>,\n    f: (a: Context.Context<A>, b: Context.Context<B>) => Context.Context<C>\n  ) => <E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<C, E | E2, R | R2>,\n  <A, E, R, B, E2, R2, C>(\n    self: Layer.Layer<A, E, R>,\n    that: Layer.Layer<B, E2, R2>,\n    f: (a: Context.Context<A>, b: Context.Context<B>) => Context.Context<C>\n  ) => Layer.Layer<C, E | E2, R | R2>\n>(3, (self, that, f) =>\n  suspend(() => {\n    const zipWith = Object.create(proto)\n    zipWith._op_layer = OpCodes.OP_ZIP_WITH\n    zipWith.first = self\n    zipWith.second = that\n    zipWith.zipK = f\n    return zipWith\n  }))\n\n/** @internal */\nexport const unwrapEffect = <A, E1, R1, E, R>(\n  self: Effect.Effect<Layer.Layer<A, E1, R1>, E, R>\n): Layer.Layer<A, E | E1, R | R1> => {\n  const tag = Context.GenericTag<Layer.Layer<A, E1, R1>>(\"effect/Layer/unwrapEffect/Layer.Layer<R1, E1, A>\")\n  return flatMap(fromEffect(tag, self), (context) => Context.get(context, tag))\n}\n\n/** @internal */\nexport const unwrapScoped = <A, E1, R1, E, R>(\n  self: Effect.Effect<Layer.Layer<A, E1, R1>, E, R>\n): Layer.Layer<A, E | E1, R1 | Exclude<R, Scope.Scope>> => {\n  const tag = Context.GenericTag<Layer.Layer<A, E1, R1>>(\"effect/Layer/unwrapScoped/Layer.Layer<R1, E1, A>\")\n  return flatMap(scoped(tag, self), (context) => Context.get(context, tag))\n}\n\n// -----------------------------------------------------------------------------\n// logging\n// -----------------------------------------------------------------------------\n\nexport const annotateLogs = dual<\n  {\n    (key: string, value: unknown): <A, E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>\n    (\n      values: Record<string, unknown>\n    ): <A, E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>\n  },\n  {\n    <A, E, R>(self: Layer.Layer<A, E, R>, key: string, value: unknown): Layer.Layer<A, E, R>\n    <A, E, R>(self: Layer.Layer<A, E, R>, values: Record<string, unknown>): Layer.Layer<A, E, R>\n  }\n>(\n  (args) => isLayer(args[0]),\n  function<A, E, R>() {\n    const args = arguments\n    return fiberRefLocallyWith(\n      args[0] as Layer.Layer<A, E, R>,\n      core.currentLogAnnotations,\n      typeof args[1] === \"string\"\n        ? HashMap.set(args[1], args[2])\n        : (annotations) =>\n          Object.entries(args[1] as Record<string, unknown>).reduce(\n            (acc, [key, value]) => HashMap.set(acc, key, value),\n            annotations\n          )\n    )\n  }\n)\n\n// -----------------------------------------------------------------------------\n// tracing\n// -----------------------------------------------------------------------------\n\nexport const annotateSpans = dual<\n  {\n    (key: string, value: unknown): <A, E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>\n    (\n      values: Record<string, unknown>\n    ): <A, E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A, E, R>\n  },\n  {\n    <A, E, R>(self: Layer.Layer<A, E, R>, key: string, value: unknown): Layer.Layer<A, E, R>\n    <A, E, R>(self: Layer.Layer<A, E, R>, values: Record<string, unknown>): Layer.Layer<A, E, R>\n  }\n>(\n  (args) => isLayer(args[0]),\n  function<A, E, R>() {\n    const args = arguments\n    return fiberRefLocallyWith(\n      args[0] as Layer.Layer<A, E, R>,\n      core.currentTracerSpanAnnotations,\n      typeof args[1] === \"string\"\n        ? HashMap.set(args[1], args[2])\n        : (annotations) =>\n          Object.entries(args[1] as Record<string, unknown>).reduce(\n            (acc, [key, value]) => HashMap.set(acc, key, value),\n            annotations\n          )\n    )\n  }\n)\n\n/** @internal */\nexport const withSpan: {\n  (\n    name: string,\n    options?: Tracer.SpanOptions & {\n      readonly onEnd?:\n        | ((span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>)\n        | undefined\n    }\n  ): <A, E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A, E, Exclude<R, Tracer.ParentSpan>>\n  <A, E, R>(\n    self: Layer.Layer<A, E, R>,\n    name: string,\n    options?: Tracer.SpanOptions & {\n      readonly onEnd?:\n        | ((span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>)\n        | undefined\n    }\n  ): Layer.Layer<A, E, Exclude<R, Tracer.ParentSpan>>\n} = function() {\n  const dataFirst = typeof arguments[0] !== \"string\"\n  const name = dataFirst ? arguments[1] : arguments[0]\n  const options = tracer.addSpanStackTrace(dataFirst ? arguments[2] : arguments[1]) as Tracer.SpanOptions & {\n    readonly onEnd?:\n      | ((span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>)\n      | undefined\n  }\n  if (dataFirst) {\n    const self = arguments[0]\n    return unwrapScoped(\n      core.map(\n        options?.onEnd\n          ? core.tap(\n            fiberRuntime.makeSpanScoped(name, options),\n            (span) => fiberRuntime.addFinalizer((exit) => options.onEnd!(span, exit))\n          )\n          : fiberRuntime.makeSpanScoped(name, options),\n        (span) => withParentSpan(self, span)\n      )\n    )\n  }\n  return (self: Layer.Layer<any, any, any>) =>\n    unwrapScoped(\n      core.map(\n        options?.onEnd\n          ? core.tap(\n            fiberRuntime.makeSpanScoped(name, options),\n            (span) => fiberRuntime.addFinalizer((exit) => options.onEnd!(span, exit))\n          )\n          : fiberRuntime.makeSpanScoped(name, options),\n        (span) => withParentSpan(self, span)\n      )\n    )\n} as any\n\n/** @internal */\nexport const withParentSpan = dual<\n  (\n    span: Tracer.AnySpan\n  ) => <A, E, R>(self: Layer.Layer<A, E, R>) => Layer.Layer<A, E, Exclude<R, Tracer.ParentSpan>>,\n  <A, E, R>(self: Layer.Layer<A, E, R>, span: Tracer.AnySpan) => Layer.Layer<A, E, Exclude<R, Tracer.ParentSpan>>\n>(2, (self, span) => provide(self, succeedContext(Context.make(tracer.spanTag, span))))\n\n// circular with Effect\n\nconst provideSomeLayer = dual<\n  <A2, E2, R2>(\n    layer: Layer.Layer<A2, E2, R2>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E2, R2 | Exclude<R, A2>>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    layer: Layer.Layer<A2, E2, R2>\n  ) => Effect.Effect<A, E | E2, R2 | Exclude<R, A2>>\n>(2, (self, layer) =>\n  fiberRuntime.scopedWith((scope) =>\n    core.flatMap(\n      buildWithScope(layer, scope),\n      (context) => core.provideSomeContext(self, context)\n    )\n  ))\n\nconst provideSomeRuntime = dual<\n  <R>(context: Runtime.Runtime<R>) => <A, E, R1>(self: Effect.Effect<A, E, R1>) => Effect.Effect<A, E, Exclude<R1, R>>,\n  <A, E, R1, R>(self: Effect.Effect<A, E, R1>, context: Runtime.Runtime<R>) => Effect.Effect<A, E, Exclude<R1, R>>\n>(2, (self, rt) => {\n  const patchRefs = FiberRefsPatch.diff(runtime.defaultRuntime.fiberRefs, rt.fiberRefs)\n  const patchFlags = runtimeFlags.diff(runtime.defaultRuntime.runtimeFlags, rt.runtimeFlags)\n  return core.uninterruptibleMask((restore) =>\n    core.withFiberRuntime((fiber) => {\n      const oldContext = fiber.getFiberRef(core.currentContext)\n      const oldRefs = fiber.getFiberRefs()\n      const newRefs = FiberRefsPatch.patch(fiber.id(), oldRefs)(patchRefs)\n      const oldFlags = fiber.currentRuntimeFlags\n      const newFlags = runtimeFlags.patch(patchFlags)(oldFlags)\n      const rollbackRefs = FiberRefsPatch.diff(newRefs, oldRefs)\n      const rollbackFlags = runtimeFlags.diff(newFlags, oldFlags)\n      fiber.setFiberRefs(newRefs)\n      fiber.currentRuntimeFlags = newFlags\n      return fiberRuntime.ensuring(\n        core.provideSomeContext(restore(self), Context.merge(oldContext, rt.context)),\n        core.withFiberRuntime((fiber) => {\n          fiber.setFiberRefs(FiberRefsPatch.patch(fiber.id(), fiber.getFiberRefs())(rollbackRefs))\n          fiber.currentRuntimeFlags = runtimeFlags.patch(rollbackFlags)(fiber.currentRuntimeFlags)\n          return core.void\n        })\n      )\n    })\n  )\n})\n\n/** @internal */\nexport const effect_provide = dual<\n  {\n    <const Layers extends readonly [Layer.Layer.Any, ...Array<Layer.Layer.Any>]>(\n      layers: Layers\n    ): <A, E, R>(\n      self: Effect.Effect<A, E, R>\n    ) => Effect.Effect<\n      A,\n      E | { [k in keyof Layers]: Layer.Layer.Error<Layers[k]> }[number],\n      | { [k in keyof Layers]: Layer.Layer.Context<Layers[k]> }[number]\n      | Exclude<R, { [k in keyof Layers]: Layer.Layer.Success<Layers[k]> }[number]>\n    >\n    <ROut, E2, RIn>(\n      layer: Layer.Layer<ROut, E2, RIn>\n    ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E2, RIn | Exclude<R, ROut>>\n    <R2>(\n      context: Context.Context<R2>\n    ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, R2>>\n    <R2>(\n      runtime: Runtime.Runtime<R2>\n    ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, R2>>\n    <E2, R2>(\n      managedRuntime: ManagedRuntime.ManagedRuntime<R2, E2>\n    ): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E | E2, Exclude<R, R2>>\n  },\n  {\n    <A, E, R, const Layers extends readonly [Layer.Layer.Any, ...Array<Layer.Layer.Any>]>(\n      self: Effect.Effect<A, E, R>,\n      layers: Layers\n    ): Effect.Effect<\n      A,\n      E | { [k in keyof Layers]: Layer.Layer.Error<Layers[k]> }[number],\n      | { [k in keyof Layers]: Layer.Layer.Context<Layers[k]> }[number]\n      | Exclude<R, { [k in keyof Layers]: Layer.Layer.Success<Layers[k]> }[number]>\n    >\n    <A, E, R, ROut, E2, RIn>(\n      self: Effect.Effect<A, E, R>,\n      layer: Layer.Layer<ROut, E2, RIn>\n    ): Effect.Effect<A, E | E2, RIn | Exclude<R, ROut>>\n    <A, E, R, R2>(\n      self: Effect.Effect<A, E, R>,\n      context: Context.Context<R2>\n    ): Effect.Effect<A, E, Exclude<R, R2>>\n    <A, E, R, R2>(\n      self: Effect.Effect<A, E, R>,\n      runtime: Runtime.Runtime<R2>\n    ): Effect.Effect<A, E, Exclude<R, R2>>\n    <A, E, E2, R, R2>(\n      self: Effect.Effect<A, E, R>,\n      managedRuntime: ManagedRuntime.ManagedRuntime<R2, E2>\n    ): Effect.Effect<A, E | E2, Exclude<R, R2>>\n  }\n>(\n  2,\n  <A, E, R, ROut>(\n    self: Effect.Effect<A, E, R>,\n    source:\n      | Layer.Layer<ROut, any, any>\n      | Context.Context<ROut>\n      | Runtime.Runtime<ROut>\n      | ManagedRuntime.ManagedRuntime<ROut, any>\n      | Array<Layer.Layer.Any>\n  ): Effect.Effect<any, any, Exclude<R, ROut>> => {\n    if (Array.isArray(source)) {\n      // @ts-expect-error\n      return provideSomeLayer(self, mergeAll(...source))\n    } else if (isLayer(source)) {\n      return provideSomeLayer(self, source as Layer.Layer<ROut, any, any>)\n    } else if (Context.isContext(source)) {\n      return core.provideSomeContext(self, source)\n    } else if (circularManagedRuntime.TypeId in source) {\n      return core.flatMap(\n        (source as ManagedRuntime.ManagedRuntime<ROut, any>).runtimeEffect,\n        (rt) => provideSomeRuntime(self, rt)\n      )\n    } else {\n      return provideSomeRuntime(self, source as Runtime.Runtime<ROut>)\n    }\n  }\n)\n"
  },
  {
    "path": "packages/effect/src/internal/logSpan.ts",
    "content": "import type * as LogSpan from \"../LogSpan.js\"\n\n/** @internal */\nexport const make = (label: string, startTime: number): LogSpan.LogSpan => ({\n  label,\n  startTime\n})\n\n/**\n * Sanitize a given string by replacing spaces, equal signs, and double quotes with underscores.\n *\n * @internal\n */\nexport const formatLabel = (key: string) => key.replace(/[\\s=\"]/g, \"_\")\n\n/** @internal */\nexport const render = (now: number) => (self: LogSpan.LogSpan): string => {\n  const label = formatLabel(self.label)\n  return `${label}=${now - self.startTime}ms`\n}\n"
  },
  {
    "path": "packages/effect/src/internal/logger-circular.ts",
    "content": "import * as Cause from \"../Cause.js\"\nimport { dual } from \"../Function.js\"\nimport * as HashMap from \"../HashMap.js\"\nimport * as List from \"../List.js\"\nimport type * as Logger from \"../Logger.js\"\nimport * as core from \"./core.js\"\nimport * as fiberId_ from \"./fiberId.js\"\nimport * as fiberRefs from \"./fiberRefs.js\"\n\n/** @internal */\nexport const test = dual<\n  <Message>(input: Message) => <Output>(self: Logger.Logger<Message, Output>) => Output,\n  <Message, Output>(self: Logger.Logger<Message, Output>, input: Message) => Output\n>(2, (self, input) =>\n  self.log({\n    fiberId: fiberId_.none,\n    logLevel: core.logLevelInfo,\n    message: input,\n    cause: Cause.empty,\n    context: fiberRefs.empty(),\n    spans: List.empty(),\n    annotations: HashMap.empty(),\n    date: new Date()\n  }))\n"
  },
  {
    "path": "packages/effect/src/internal/logger.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport * as Context from \"../Context.js\"\nimport * as FiberRefs from \"../FiberRefs.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { constVoid, dual } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport * as HashMap from \"../HashMap.js\"\nimport * as Inspectable from \"../Inspectable.js\"\nimport * as List from \"../List.js\"\nimport type * as Logger from \"../Logger.js\"\nimport type * as LogLevel from \"../LogLevel.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport * as Cause from \"./cause.js\"\nimport * as defaultServices from \"./defaultServices.js\"\nimport { consoleTag } from \"./defaultServices/console.js\"\nimport * as fiberId_ from \"./fiberId.js\"\nimport * as logSpan_ from \"./logSpan.js\"\n\n/** @internal */\nconst LoggerSymbolKey = \"effect/Logger\"\n\n/** @internal */\nexport const LoggerTypeId: Logger.LoggerTypeId = Symbol.for(\n  LoggerSymbolKey\n) as Logger.LoggerTypeId\n\nconst loggerVariance = {\n  /* c8 ignore next */\n  _Message: (_: unknown) => _,\n  /* c8 ignore next */\n  _Output: (_: never) => _\n}\n\n/** @internal */\nexport const makeLogger = <Message, Output>(\n  log: (options: Logger.Logger.Options<Message>) => Output\n): Logger.Logger<Message, Output> => ({\n  [LoggerTypeId]: loggerVariance,\n  log,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n})\n\n/** @internal */\nexport const mapInput = dual<\n  <Message, Message2>(\n    f: (message: Message2) => Message\n  ) => <Output>(self: Logger.Logger<Message, Output>) => Logger.Logger<Message2, Output>,\n  <Output, Message, Message2>(\n    self: Logger.Logger<Message, Output>,\n    f: (message: Message2) => Message\n  ) => Logger.Logger<Message2, Output>\n>(2, (self, f) =>\n  makeLogger(\n    (options) => self.log({ ...options, message: f(options.message) })\n  ))\n\n/** @internal */\nexport const mapInputOptions = dual<\n  <Message, Message2>(\n    f: (options: Logger.Logger.Options<Message2>) => Logger.Logger.Options<Message>\n  ) => <Output>(self: Logger.Logger<Message, Output>) => Logger.Logger<Message2, Output>,\n  <Output, Message, Message2>(\n    self: Logger.Logger<Message, Output>,\n    f: (options: Logger.Logger.Options<Message2>) => Logger.Logger.Options<Message>\n  ) => Logger.Logger<Message2, Output>\n>(2, (self, f) => makeLogger((options) => self.log(f(options))))\n\n/** @internal */\nexport const filterLogLevel = dual<\n  (\n    f: (logLevel: LogLevel.LogLevel) => boolean\n  ) => <Message, Output>(self: Logger.Logger<Message, Output>) => Logger.Logger<Message, Option.Option<Output>>,\n  <Message, Output>(\n    self: Logger.Logger<Message, Output>,\n    f: (logLevel: LogLevel.LogLevel) => boolean\n  ) => Logger.Logger<Message, Option.Option<Output>>\n>(2, (self, f) =>\n  makeLogger((options) =>\n    f(options.logLevel)\n      ? Option.some(self.log(options))\n      : Option.none()\n  ))\n\n/** @internal */\nexport const map = dual<\n  <Output, Output2>(\n    f: (output: Output) => Output2\n  ) => <Message>(self: Logger.Logger<Message, Output>) => Logger.Logger<Message, Output2>,\n  <Message, Output, Output2>(\n    self: Logger.Logger<Message, Output>,\n    f: (output: Output) => Output2\n  ) => Logger.Logger<Message, Output2>\n>(2, (self, f) => makeLogger((options) => f(self.log(options))))\n\n/** @internal */\nexport const none: Logger.Logger<unknown, void> = {\n  [LoggerTypeId]: loggerVariance,\n  log: constVoid,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n} as Logger.Logger<unknown, void>\n\n/** @internal */\nexport const simple = <A, B>(log: (a: A) => B): Logger.Logger<A, B> => ({\n  [LoggerTypeId]: loggerVariance,\n  log: ({ message }) => log(message),\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n})\n\n/** @internal */\nexport const succeed = <A>(value: A): Logger.Logger<unknown, A> => {\n  return simple(() => value)\n}\n\n/** @internal */\nexport const sync = <A>(evaluate: LazyArg<A>): Logger.Logger<unknown, A> => {\n  return simple(evaluate)\n}\n\n/** @internal */\nexport const zip = dual<\n  <Message2, Output2>(\n    that: Logger.Logger<Message2, Output2>\n  ) => <Message, Output>(\n    self: Logger.Logger<Message, Output>\n  ) => Logger.Logger<Message & Message2, [Output, Output2]>,\n  <Message, Output, Message2, Output2>(\n    self: Logger.Logger<Message, Output>,\n    that: Logger.Logger<Message2, Output2>\n  ) => Logger.Logger<Message & Message2, [Output, Output2]>\n>(2, (self, that) => makeLogger((options) => [self.log(options), that.log(options)]))\n\n/** @internal */\nexport const zipLeft = dual<\n  <Message2, Output2>(\n    that: Logger.Logger<Message2, Output2>\n  ) => <Message, Output>(\n    self: Logger.Logger<Message, Output>\n  ) => Logger.Logger<Message & Message2, Output>,\n  <Message, Output, Message2, Output2>(\n    self: Logger.Logger<Message, Output>,\n    that: Logger.Logger<Message2, Output2>\n  ) => Logger.Logger<Message & Message2, Output>\n>(2, (self, that) => map(zip(self, that), (tuple) => tuple[0]))\n\n/** @internal */\nexport const zipRight = dual<\n  <Message2, Output2>(\n    that: Logger.Logger<Message2, Output2>\n  ) => <Message, Output>(\n    self: Logger.Logger<Message, Output>\n  ) => Logger.Logger<Message & Message2, Output2>,\n  <Message, Output, Message2, Output2>(\n    self: Logger.Logger<Message, Output>,\n    that: Logger.Logger<Message2, Output2>\n  ) => Logger.Logger<Message & Message2, Output2>\n>(2, (self, that) => map(zip(self, that), (tuple) => tuple[1]))\n\n/**\n * Match strings that do not contain any whitespace characters, double quotes,\n * or equal signs.\n *\n * @internal\n */\nconst textOnly = /^[^\\s\"=]*$/\n\n/**\n * Used by both {@link stringLogger} and {@link logfmtLogger} to render a log\n * message.\n *\n * @internal\n */\nconst format = (quoteValue: (s: string) => string, whitespace?: number | string | undefined) =>\n(\n  { annotations, cause, date, fiberId, logLevel, message, spans }: Logger.Logger.Options<unknown>\n): string => {\n  const formatValue = (value: string): string => value.match(textOnly) ? value : quoteValue(value)\n  const format = (label: string, value: string): string => `${logSpan_.formatLabel(label)}=${formatValue(value)}`\n  const append = (label: string, value: string): string => \" \" + format(label, value)\n\n  let out = format(\"timestamp\", date.toISOString())\n  out += append(\"level\", logLevel.label)\n  out += append(\"fiber\", fiberId_.threadName(fiberId))\n\n  const messages = Arr.ensure(message)\n  for (let i = 0; i < messages.length; i++) {\n    out += append(\"message\", Inspectable.toStringUnknown(messages[i], whitespace))\n  }\n\n  if (!Cause.isEmptyType(cause)) {\n    out += append(\"cause\", Cause.pretty(cause, { renderErrorCause: true }))\n  }\n\n  for (const span of spans) {\n    out += \" \" + logSpan_.render(date.getTime())(span)\n  }\n\n  for (const [label, value] of annotations) {\n    out += append(label, Inspectable.toStringUnknown(value, whitespace))\n  }\n\n  return out\n}\n\n/** @internal */\nconst escapeDoubleQuotes = (s: string) => `\"${s.replace(/\\\\([\\s\\S])|(\")/g, \"\\\\$1$2\")}\"`\n\n/** @internal */\nexport const stringLogger: Logger.Logger<unknown, string> = makeLogger(format(escapeDoubleQuotes))\n\n/** @internal */\nexport const logfmtLogger: Logger.Logger<unknown, string> = makeLogger(format(JSON.stringify, 0))\n\n/** @internal */\nexport const structuredLogger = makeLogger<unknown, {\n  readonly logLevel: string\n  readonly fiberId: string\n  readonly timestamp: string\n  readonly message: unknown\n  readonly cause: string | undefined\n  readonly annotations: Record<string, unknown>\n  readonly spans: Record<string, number>\n}>(\n  ({ annotations, cause, date, fiberId, logLevel, message, spans }) => {\n    const now = date.getTime()\n    const annotationsObj: Record<string, unknown> = {}\n    const spansObj: Record<string, number> = {}\n\n    if (HashMap.size(annotations) > 0) {\n      for (const [k, v] of annotations) {\n        annotationsObj[k] = structuredMessage(v)\n      }\n    }\n\n    if (List.isCons(spans)) {\n      for (const span of spans) {\n        spansObj[span.label] = now - span.startTime\n      }\n    }\n\n    const messageArr = Arr.ensure(message)\n    return {\n      message: messageArr.length === 1 ? structuredMessage(messageArr[0]) : messageArr.map(structuredMessage),\n      logLevel: logLevel.label,\n      timestamp: date.toISOString(),\n      cause: Cause.isEmpty(cause) ? undefined : Cause.pretty(cause, { renderErrorCause: true }),\n      annotations: annotationsObj,\n      spans: spansObj,\n      fiberId: fiberId_.threadName(fiberId)\n    }\n  }\n)\n\n/** @internal */\nexport const structuredMessage = (u: unknown): unknown => {\n  switch (typeof u) {\n    case \"bigint\":\n    case \"function\":\n    case \"symbol\": {\n      return String(u)\n    }\n    default: {\n      return Inspectable.toJSON(u)\n    }\n  }\n}\n\n/** @internal */\nexport const jsonLogger = map(structuredLogger, Inspectable.stringifyCircular)\n\n/** @internal */\nexport const isLogger = (u: unknown): u is Logger.Logger<unknown, unknown> => {\n  return typeof u === \"object\" && u != null && LoggerTypeId in u\n}\n\nconst withColor = (text: string, ...colors: ReadonlyArray<string>) => {\n  let out = \"\"\n  for (let i = 0; i < colors.length; i++) {\n    out += `\\x1b[${colors[i]}m`\n  }\n  return out + text + \"\\x1b[0m\"\n}\nconst withColorNoop = (text: string, ..._colors: ReadonlyArray<string>) => text\nconst colors = {\n  bold: \"1\",\n  red: \"31\",\n  green: \"32\",\n  yellow: \"33\",\n  blue: \"34\",\n  cyan: \"36\",\n  white: \"37\",\n  gray: \"90\",\n  black: \"30\",\n  bgBrightRed: \"101\"\n} as const\n\nconst logLevelColors: Record<LogLevel.LogLevel[\"_tag\"], ReadonlyArray<string>> = {\n  None: [],\n  All: [],\n  Trace: [colors.gray],\n  Debug: [colors.blue],\n  Info: [colors.green],\n  Warning: [colors.yellow],\n  Error: [colors.red],\n  Fatal: [colors.bgBrightRed, colors.black]\n}\nconst logLevelStyle: Record<LogLevel.LogLevel[\"_tag\"], string> = {\n  None: \"\",\n  All: \"\",\n  Trace: \"color:gray\",\n  Debug: \"color:blue\",\n  Info: \"color:green\",\n  Warning: \"color:orange\",\n  Error: \"color:red\",\n  Fatal: \"background-color:red;color:white\"\n}\n\nconst defaultDateFormat = (date: Date): string =>\n  `${date.getHours().toString().padStart(2, \"0\")}:${date.getMinutes().toString().padStart(2, \"0\")}:${\n    date.getSeconds().toString().padStart(2, \"0\")\n  }.${date.getMilliseconds().toString().padStart(3, \"0\")}`\n\nconst hasProcessStdout = typeof process === \"object\" &&\n  process !== null &&\n  typeof process.stdout === \"object\" &&\n  process.stdout !== null\nconst processStdoutIsTTY = hasProcessStdout &&\n  process.stdout.isTTY === true\nconst hasProcessStdoutOrDeno = hasProcessStdout || \"Deno\" in globalThis\n\n/** @internal */\nexport const prettyLogger = (options?: {\n  readonly colors?: \"auto\" | boolean | undefined\n  readonly stderr?: boolean | undefined\n  readonly formatDate?: ((date: Date) => string) | undefined\n  readonly mode?: \"browser\" | \"tty\" | \"auto\" | undefined\n}) => {\n  const mode_ = options?.mode ?? \"auto\"\n  const mode = mode_ === \"auto\" ? (hasProcessStdoutOrDeno ? \"tty\" : \"browser\") : mode_\n  const isBrowser = mode === \"browser\"\n  const showColors = typeof options?.colors === \"boolean\" ? options.colors : processStdoutIsTTY || isBrowser\n  const formatDate = options?.formatDate ?? defaultDateFormat\n  return isBrowser\n    ? prettyLoggerBrowser({ colors: showColors, formatDate })\n    : prettyLoggerTty({ colors: showColors, formatDate, stderr: options?.stderr === true })\n}\n\nconst prettyLoggerTty = (options: {\n  readonly colors: boolean\n  readonly stderr: boolean\n  readonly formatDate: (date: Date) => string\n}) => {\n  const color = options.colors ? withColor : withColorNoop\n  return makeLogger<unknown, void>(\n    ({ annotations, cause, context, date, fiberId, logLevel, message: message_, spans }) => {\n      const services = FiberRefs.getOrDefault(context, defaultServices.currentServices)\n      const console = Context.get(services, consoleTag).unsafe\n      const log = options.stderr === true ? console.error : console.log\n\n      const message = Arr.ensure(message_)\n\n      let firstLine = color(`[${options.formatDate(date)}]`, colors.white)\n        + ` ${color(logLevel.label, ...logLevelColors[logLevel._tag])}`\n        + ` (${fiberId_.threadName(fiberId)})`\n\n      if (List.isCons(spans)) {\n        const now = date.getTime()\n        const render = logSpan_.render(now)\n        for (const span of spans) {\n          firstLine += \" \" + render(span)\n        }\n      }\n\n      firstLine += \":\"\n      let messageIndex = 0\n      if (message.length > 0) {\n        const firstMaybeString = structuredMessage(message[0])\n        if (typeof firstMaybeString === \"string\") {\n          firstLine += \" \" + color(firstMaybeString, colors.bold, colors.cyan)\n          messageIndex++\n        }\n      }\n\n      log(firstLine)\n      console.group()\n\n      if (!Cause.isEmpty(cause)) {\n        log(Cause.pretty(cause, { renderErrorCause: true }))\n      }\n\n      if (messageIndex < message.length) {\n        for (; messageIndex < message.length; messageIndex++) {\n          log(Inspectable.redact(message[messageIndex]))\n        }\n      }\n\n      if (HashMap.size(annotations) > 0) {\n        for (const [key, value] of annotations) {\n          log(color(`${key}:`, colors.bold, colors.white), Inspectable.redact(value))\n        }\n      }\n\n      console.groupEnd()\n    }\n  )\n}\n\nconst prettyLoggerBrowser = (options: {\n  readonly colors: boolean\n  readonly formatDate: (date: Date) => string\n}) => {\n  const color = options.colors ? \"%c\" : \"\"\n  return makeLogger<unknown, void>(\n    ({ annotations, cause, context, date, fiberId, logLevel, message: message_, spans }) => {\n      const services = FiberRefs.getOrDefault(context, defaultServices.currentServices)\n      const console = Context.get(services, consoleTag).unsafe\n      const message = Arr.ensure(message_)\n\n      let firstLine = `${color}[${options.formatDate(date)}]`\n      const firstParams = []\n      if (options.colors) {\n        firstParams.push(\"color:gray\")\n      }\n      firstLine += ` ${color}${logLevel.label}${color} (${fiberId_.threadName(fiberId)})`\n      if (options.colors) {\n        firstParams.push(logLevelStyle[logLevel._tag], \"\")\n      }\n      if (List.isCons(spans)) {\n        const now = date.getTime()\n        const render = logSpan_.render(now)\n        for (const span of spans) {\n          firstLine += \" \" + render(span)\n        }\n      }\n\n      firstLine += \":\"\n\n      let messageIndex = 0\n      if (message.length > 0) {\n        const firstMaybeString = structuredMessage(message[0])\n        if (typeof firstMaybeString === \"string\") {\n          firstLine += ` ${color}${firstMaybeString}`\n          if (options.colors) {\n            firstParams.push(\"color:deepskyblue\")\n          }\n          messageIndex++\n        }\n      }\n\n      console.groupCollapsed(firstLine, ...firstParams)\n\n      if (!Cause.isEmpty(cause)) {\n        console.error(...Cause.prettyErrors(cause))\n      }\n\n      if (messageIndex < message.length) {\n        for (; messageIndex < message.length; messageIndex++) {\n          console.log(Inspectable.redact(message[messageIndex]))\n        }\n      }\n\n      if (HashMap.size(annotations) > 0) {\n        for (const [key, value] of annotations) {\n          const redacted = Inspectable.redact(value)\n          if (options.colors) {\n            console.log(`%c${key}:`, \"color:gray\", redacted)\n          } else {\n            console.log(`${key}:`, redacted)\n          }\n        }\n      }\n\n      console.groupEnd()\n    }\n  )\n}\n\n/** @internal */\nexport const prettyLoggerDefault = globalValue(\"effect/Logger/prettyLoggerDefault\", () => prettyLogger())\n"
  },
  {
    "path": "packages/effect/src/internal/mailbox.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport type { Cause } from \"../Cause.js\"\nimport { NoSuchElementException } from \"../Cause.js\"\nimport type { Channel } from \"../Channel.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport type { Effect } from \"../Effect.js\"\nimport * as Effectable from \"../Effectable.js\"\nimport type { Exit } from \"../Exit.js\"\nimport { dual } from \"../Function.js\"\nimport * as Inspectable from \"../Inspectable.js\"\nimport type * as Api from \"../Mailbox.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type { Scheduler } from \"../Scheduler.js\"\nimport type { Scope } from \"../Scope.js\"\nimport type { Stream } from \"../Stream.js\"\nimport * as channel from \"./channel.js\"\nimport * as channelExecutor from \"./channel/channelExecutor.js\"\nimport * as coreChannel from \"./core-stream.js\"\nimport * as core from \"./core.js\"\nimport * as circular from \"./effect/circular.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\nimport * as stream from \"./stream.js\"\n\n/** @internal */\nexport const TypeId: Api.TypeId = Symbol.for(\"effect/Mailbox\") as Api.TypeId\n\n/** @internal */\nexport const ReadonlyTypeId: Api.ReadonlyTypeId = Symbol.for(\"effect/Mailbox/ReadonlyMailbox\") as Api.ReadonlyTypeId\n\n/** @internal */\nexport const isMailbox = (u: unknown): u is Api.Mailbox<unknown, unknown> => hasProperty(u, TypeId)\n\n/** @internal */\nexport const isReadonlyMailbox = (u: unknown): u is Api.ReadonlyMailbox<unknown, unknown> =>\n  hasProperty(u, ReadonlyTypeId)\n\ntype MailboxState<A, E> = {\n  readonly _tag: \"Open\"\n  readonly takers: Set<(_: Effect<void, E>) => void>\n  readonly offers: Set<OfferEntry<A>>\n  readonly awaiters: Set<(_: Effect<void, E>) => void>\n} | {\n  readonly _tag: \"Closing\"\n  readonly takers: Set<(_: Effect<void, E>) => void>\n  readonly offers: Set<OfferEntry<A>>\n  readonly awaiters: Set<(_: Effect<void, E>) => void>\n  readonly exit: Exit<void, E>\n} | {\n  readonly _tag: \"Done\"\n  readonly exit: Exit<void, E>\n}\n\ntype OfferEntry<A> = {\n  readonly _tag: \"Array\"\n  readonly remaining: Array<A>\n  offset: number\n  readonly resume: (_: Effect<Chunk.Chunk<A>>) => void\n} | {\n  readonly _tag: \"Single\"\n  readonly message: A\n  readonly resume: (_: Effect<boolean>) => void\n}\n\nconst empty = Chunk.empty()\nconst exitEmpty = core.exitSucceed(empty)\nconst exitFalse = core.exitSucceed(false)\nconst exitTrue = core.exitSucceed(true)\nconst constDone = [empty, true] as const\n\nclass MailboxImpl<A, E> extends Effectable.Class<readonly [messages: Chunk.Chunk<A>, done: boolean], E>\n  implements Api.Mailbox<A, E>\n{\n  readonly [TypeId]: Api.TypeId = TypeId\n  readonly [ReadonlyTypeId]: Api.ReadonlyTypeId = ReadonlyTypeId\n  private state: MailboxState<A, E> = {\n    _tag: \"Open\",\n    takers: new Set(),\n    offers: new Set(),\n    awaiters: new Set()\n  }\n  private messages: Array<A> = []\n  private messagesChunk = Chunk.empty<A>()\n  constructor(\n    readonly scheduler: Scheduler,\n    private capacity: number,\n    readonly strategy: \"suspend\" | \"dropping\" | \"sliding\"\n  ) {\n    super()\n  }\n\n  offer(message: A): Effect<boolean> {\n    return core.suspend(() => {\n      if (this.state._tag !== \"Open\") {\n        return exitFalse\n      } else if (this.messages.length + this.messagesChunk.length >= this.capacity) {\n        switch (this.strategy) {\n          case \"dropping\":\n            return exitFalse\n          case \"suspend\":\n            if (this.capacity <= 0 && this.state.takers.size > 0) {\n              this.messages.push(message)\n              this.releaseTaker()\n              return exitTrue\n            }\n            return this.offerRemainingSingle(message)\n          case \"sliding\":\n            this.unsafeTake()\n            this.messages.push(message)\n            return exitTrue\n        }\n      }\n      this.messages.push(message)\n      this.scheduleReleaseTaker()\n      return exitTrue\n    })\n  }\n  unsafeOffer(message: A): boolean {\n    if (this.state._tag !== \"Open\") {\n      return false\n    } else if (this.messages.length + this.messagesChunk.length >= this.capacity) {\n      if (this.strategy === \"sliding\") {\n        this.unsafeTake()\n        this.messages.push(message)\n        return true\n      } else if (this.capacity <= 0 && this.state.takers.size > 0) {\n        this.messages.push(message)\n        this.releaseTaker()\n        return true\n      }\n      return false\n    }\n    this.messages.push(message)\n    this.scheduleReleaseTaker()\n    return true\n  }\n  offerAll(messages: Iterable<A>): Effect<Chunk.Chunk<A>> {\n    return core.suspend(() => {\n      if (this.state._tag !== \"Open\") {\n        return core.succeed(Chunk.fromIterable(messages))\n      }\n      const remaining = this.unsafeOfferAllArray(messages)\n      if (remaining.length === 0) {\n        return exitEmpty\n      } else if (this.strategy === \"dropping\") {\n        return core.succeed(Chunk.unsafeFromArray(remaining))\n      }\n      return this.offerRemainingArray(remaining)\n    })\n  }\n  unsafeOfferAll(messages: Iterable<A>): Chunk.Chunk<A> {\n    return Chunk.unsafeFromArray(this.unsafeOfferAllArray(messages))\n  }\n  unsafeOfferAllArray(messages: Iterable<A>): Array<A> {\n    if (this.state._tag !== \"Open\") {\n      return Arr.fromIterable(messages)\n    } else if (this.capacity === Number.POSITIVE_INFINITY || this.strategy === \"sliding\") {\n      if (this.messages.length > 0) {\n        this.messagesChunk = Chunk.appendAll(this.messagesChunk, Chunk.unsafeFromArray(this.messages))\n      }\n      if (this.strategy === \"sliding\") {\n        this.messagesChunk = this.messagesChunk.pipe(\n          Chunk.appendAll(Chunk.fromIterable(messages)),\n          Chunk.takeRight(this.capacity)\n        )\n      } else if (Chunk.isChunk(messages)) {\n        this.messagesChunk = Chunk.appendAll(this.messagesChunk, messages)\n      } else {\n        this.messages = Arr.fromIterable(messages)\n      }\n      this.scheduleReleaseTaker()\n      return []\n    }\n    const free = this.capacity <= 0\n      ? this.state.takers.size\n      : this.capacity - this.messages.length - this.messagesChunk.length\n    if (free === 0) {\n      return Arr.fromIterable(messages)\n    }\n    const remaining: Array<A> = []\n    let i = 0\n    for (const message of messages) {\n      if (i < free) {\n        this.messages.push(message)\n      } else {\n        remaining.push(message)\n      }\n      i++\n    }\n    this.scheduleReleaseTaker()\n    return remaining\n  }\n  fail(error: E) {\n    return this.done(core.exitFail(error))\n  }\n  failCause(cause: Cause<E>) {\n    return this.done(core.exitFailCause(cause))\n  }\n  unsafeDone(exit: Exit<void, E>): boolean {\n    if (this.state._tag !== \"Open\") {\n      return false\n    } else if (this.state.offers.size === 0 && this.messages.length === 0 && this.messagesChunk.length === 0) {\n      this.finalize(exit)\n      return true\n    }\n    this.state = { ...this.state, _tag: \"Closing\", exit }\n    return true\n  }\n  shutdown: Effect<boolean> = core.sync(() => {\n    if (this.state._tag === \"Done\") {\n      return true\n    }\n    this.messages = []\n    this.messagesChunk = empty\n    const offers = this.state.offers\n    this.finalize(this.state._tag === \"Open\" ? core.exitVoid : this.state.exit)\n    if (offers.size > 0) {\n      for (const entry of offers) {\n        if (entry._tag === \"Single\") {\n          entry.resume(exitFalse)\n        } else {\n          entry.resume(core.exitSucceed(Chunk.unsafeFromArray(entry.remaining.slice(entry.offset))))\n        }\n      }\n      offers.clear()\n    }\n    return true\n  })\n  done(exit: Exit<void, E>) {\n    return core.sync(() => this.unsafeDone(exit))\n  }\n  end = this.done(core.exitVoid)\n  clear: Effect<Chunk.Chunk<A>, E> = core.suspend(() => {\n    if (this.state._tag === \"Done\") {\n      return core.exitAs(this.state.exit, empty)\n    }\n    const messages = this.unsafeTakeAll()\n    this.releaseCapacity()\n    return core.succeed(messages)\n  })\n  takeAll: Effect<readonly [messages: Chunk.Chunk<A>, done: boolean], E> = core.suspend(() => {\n    if (this.state._tag === \"Done\") {\n      return core.exitAs(this.state.exit, constDone)\n    }\n    const messages = this.unsafeTakeAll()\n    if (messages.length === 0) {\n      return core.zipRight(this.awaitTake, this.takeAll)\n    }\n    return core.succeed([messages, this.releaseCapacity()])\n  })\n  takeN(n: number): Effect<readonly [messages: Chunk.Chunk<A>, done: boolean], E> {\n    return core.suspend(() => {\n      if (this.state._tag === \"Done\") {\n        return core.exitAs(this.state.exit, constDone)\n      } else if (n <= 0) {\n        return core.succeed([empty, false])\n      }\n      n = Math.min(n, this.capacity)\n      let messages: Chunk.Chunk<A>\n      if (n <= this.messagesChunk.length) {\n        messages = Chunk.take(this.messagesChunk, n)\n        this.messagesChunk = Chunk.drop(this.messagesChunk, n)\n      } else if (n <= this.messages.length + this.messagesChunk.length) {\n        this.messagesChunk = Chunk.appendAll(this.messagesChunk, Chunk.unsafeFromArray(this.messages))\n        this.messages = []\n        messages = Chunk.take(this.messagesChunk, n)\n        this.messagesChunk = Chunk.drop(this.messagesChunk, n)\n      } else {\n        return core.zipRight(this.awaitTake, this.takeN(n))\n      }\n      return core.succeed([messages, this.releaseCapacity()])\n    })\n  }\n  unsafeTake(): Exit<A, E | NoSuchElementException> | undefined {\n    if (this.state._tag === \"Done\") {\n      return core.exitZipRight(this.state.exit, core.exitFail(new NoSuchElementException()))\n    }\n    let message: A\n    if (this.messagesChunk.length > 0) {\n      message = Chunk.unsafeHead(this.messagesChunk)\n      this.messagesChunk = Chunk.drop(this.messagesChunk, 1)\n    } else if (this.messages.length > 0) {\n      message = this.messages[0]\n      this.messagesChunk = Chunk.drop(Chunk.unsafeFromArray(this.messages), 1)\n      this.messages = []\n    } else if (this.capacity <= 0 && this.state.offers.size > 0) {\n      this.capacity = 1\n      this.releaseCapacity()\n      this.capacity = 0\n      return this.messages.length > 0 ? core.exitSucceed(this.messages.pop()!) : undefined\n    } else {\n      return undefined\n    }\n    this.releaseCapacity()\n    return core.exitSucceed(message)\n  }\n  take: Effect<A, E | NoSuchElementException> = core.suspend(() =>\n    this.unsafeTake() ?? core.zipRight(this.awaitTake, this.take)\n  )\n  await: Effect<void, E> = core.asyncInterrupt<void, E>((resume) => {\n    if (this.state._tag === \"Done\") {\n      return resume(this.state.exit)\n    }\n    this.state.awaiters.add(resume)\n    return core.sync(() => {\n      if (this.state._tag !== \"Done\") {\n        this.state.awaiters.delete(resume)\n      }\n    })\n  })\n  unsafeSize(): Option.Option<number> {\n    const size = this.messages.length + this.messagesChunk.length\n    return this.state._tag === \"Done\" ? Option.none() : Option.some(size)\n  }\n  size = core.sync(() => this.unsafeSize())\n\n  commit() {\n    return this.takeAll\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n  toJSON() {\n    return {\n      _id: \"effect/Mailbox\",\n      state: this.state._tag,\n      size: this.unsafeSize().toJSON()\n    }\n  }\n  toString(): string {\n    return Inspectable.format(this)\n  }\n  [Inspectable.NodeInspectSymbol]() {\n    return Inspectable.format(this)\n  }\n\n  private offerRemainingSingle(message: A) {\n    return core.asyncInterrupt<boolean>((resume) => {\n      if (this.state._tag !== \"Open\") {\n        return resume(exitFalse)\n      }\n      const entry: OfferEntry<A> = { _tag: \"Single\", message, resume }\n      this.state.offers.add(entry)\n      return core.sync(() => {\n        if (this.state._tag === \"Open\") {\n          this.state.offers.delete(entry)\n        }\n      })\n    })\n  }\n  private offerRemainingArray(remaining: Array<A>) {\n    return core.asyncInterrupt<Chunk.Chunk<A>>((resume) => {\n      if (this.state._tag !== \"Open\") {\n        return resume(core.exitSucceed(Chunk.unsafeFromArray(remaining)))\n      }\n      const entry: OfferEntry<A> = { _tag: \"Array\", remaining, offset: 0, resume }\n      this.state.offers.add(entry)\n      return core.sync(() => {\n        if (this.state._tag === \"Open\") {\n          this.state.offers.delete(entry)\n        }\n      })\n    })\n  }\n  private releaseCapacity(): boolean {\n    if (this.state._tag === \"Done\") {\n      return this.state.exit._tag === \"Success\"\n    } else if (this.state.offers.size === 0) {\n      if (this.state._tag === \"Closing\" && this.messages.length === 0 && this.messagesChunk.length === 0) {\n        this.finalize(this.state.exit)\n        return this.state.exit._tag === \"Success\"\n      }\n      return false\n    }\n    let n = this.capacity - this.messages.length - this.messagesChunk.length\n    for (const entry of this.state.offers) {\n      if (n === 0) return false\n      else if (entry._tag === \"Single\") {\n        this.messages.push(entry.message)\n        n--\n        entry.resume(exitTrue)\n        this.state.offers.delete(entry)\n      } else {\n        for (; entry.offset < entry.remaining.length; entry.offset++) {\n          if (n === 0) return false\n          this.messages.push(entry.remaining[entry.offset])\n          n--\n        }\n        entry.resume(exitEmpty)\n        this.state.offers.delete(entry)\n      }\n    }\n    return false\n  }\n  private awaitTake = core.asyncInterrupt<void, E>((resume) => {\n    if (this.state._tag === \"Done\") {\n      return resume(this.state.exit)\n    }\n    this.state.takers.add(resume)\n    return core.sync(() => {\n      if (this.state._tag !== \"Done\") {\n        this.state.takers.delete(resume)\n      }\n    })\n  })\n\n  private scheduleRunning = false\n  private scheduleReleaseTaker() {\n    if (this.scheduleRunning) {\n      return\n    }\n    this.scheduleRunning = true\n    this.scheduler.scheduleTask(this.releaseTaker, 0)\n  }\n  private releaseTaker = () => {\n    this.scheduleRunning = false\n    if (this.state._tag === \"Done\") {\n      return\n    } else if (this.state.takers.size === 0) {\n      return\n    }\n    for (const taker of this.state.takers) {\n      this.state.takers.delete(taker)\n      taker(core.exitVoid)\n      if (this.messages.length + this.messagesChunk.length === 0) {\n        break\n      }\n    }\n  }\n\n  private unsafeTakeAll() {\n    if (this.messagesChunk.length > 0) {\n      const messages = this.messages.length > 0 ?\n        Chunk.appendAll(this.messagesChunk, Chunk.unsafeFromArray(this.messages)) :\n        this.messagesChunk\n      this.messagesChunk = empty\n      this.messages = []\n      return messages\n    } else if (this.messages.length > 0) {\n      const messages = Chunk.unsafeFromArray(this.messages)\n      this.messages = []\n      return messages\n    } else if (this.state._tag !== \"Done\" && this.state.offers.size > 0) {\n      this.capacity = 1\n      this.releaseCapacity()\n      this.capacity = 0\n      return Chunk.of(this.messages.pop()!)\n    }\n    return empty\n  }\n\n  private finalize(exit: Exit<void, E>) {\n    if (this.state._tag === \"Done\") {\n      return\n    }\n    const openState = this.state\n    this.state = { _tag: \"Done\", exit }\n    for (const taker of openState.takers) {\n      taker(exit)\n    }\n    openState.takers.clear()\n    for (const awaiter of openState.awaiters) {\n      awaiter(exit)\n    }\n    openState.awaiters.clear()\n  }\n}\n\n/** @internal */\nexport const make = <A, E = never>(\n  capacity?: number | {\n    readonly capacity?: number | undefined\n    readonly strategy?: \"suspend\" | \"dropping\" | \"sliding\" | undefined\n  } | undefined\n): Effect<Api.Mailbox<A, E>> =>\n  core.withFiberRuntime((fiber) =>\n    core.succeed(\n      new MailboxImpl<A, E>(\n        fiber.currentScheduler,\n        typeof capacity === \"number\" ? capacity : capacity?.capacity ?? Number.POSITIVE_INFINITY,\n        typeof capacity === \"number\" ? \"suspend\" : capacity?.strategy ?? \"suspend\"\n      )\n    )\n  )\n\n/** @internal */\nexport const into: {\n  <A, E>(\n    self: Api.Mailbox<A, E>\n  ): <AX, EX extends E, RX>(effect: Effect<AX, EX, RX>) => Effect<boolean, never, RX>\n  <AX, E, EX extends E, RX, A>(\n    effect: Effect<AX, EX, RX>,\n    self: Api.Mailbox<A, E>\n  ): Effect<boolean, never, RX>\n} = dual(\n  2,\n  <AX, E, EX extends E, RX, A>(\n    effect: Effect<AX, EX, RX>,\n    self: Api.Mailbox<A, E>\n  ): Effect<boolean, never, RX> =>\n    core.uninterruptibleMask((restore) =>\n      core.matchCauseEffect(restore(effect), {\n        onFailure: (cause) => self.failCause(cause),\n        onSuccess: (_) => self.end\n      })\n    )\n)\n\n/** @internal */\nexport const toChannel = <A, E>(self: Api.ReadonlyMailbox<A, E>): Channel<Chunk.Chunk<A>, unknown, E> => {\n  const loop: Channel<Chunk.Chunk<A>, unknown, E> = coreChannel.flatMap(self.takeAll, ([messages, done]) =>\n    done\n      ? messages.length === 0 ? coreChannel.void : coreChannel.write(messages)\n      : channel.zipRight(coreChannel.write(messages), loop))\n  return loop\n}\n\n/** @internal */\nexport const toStream = <A, E>(self: Api.ReadonlyMailbox<A, E>): Stream<A, E> => stream.fromChannel(toChannel(self))\n\n/** @internal */\nexport const fromStream: {\n  (options?: {\n    readonly capacity?: number | undefined\n    readonly strategy?: \"suspend\" | \"dropping\" | \"sliding\" | undefined\n  }): <A, E, R>(self: Stream<A, E, R>) => Effect<Api.ReadonlyMailbox<A, E>, never, R | Scope>\n  <A, E, R>(\n    self: Stream<A, E, R>,\n    options?: {\n      readonly capacity?: number | undefined\n      readonly strategy?: \"suspend\" | \"dropping\" | \"sliding\" | undefined\n    }\n  ): Effect<Api.ReadonlyMailbox<A, E>, never, R | Scope>\n} = dual((args) => stream.isStream(args[0]), <A, E, R>(\n  self: Stream<A, E, R>,\n  options?: {\n    readonly capacity?: number | undefined\n    readonly strategy?: \"suspend\" | \"dropping\" | \"sliding\" | undefined\n  }\n): Effect<Api.ReadonlyMailbox<A, E>, never, R | Scope> =>\n  core.tap(\n    fiberRuntime.acquireRelease(\n      make<A, E>(options),\n      (mailbox) => mailbox.shutdown\n    ),\n    (mailbox) => {\n      const writer: Channel<never, Chunk.Chunk<A>, never, E> = coreChannel.readWithCause({\n        onInput: (input: Chunk.Chunk<A>) => coreChannel.flatMap(mailbox.offerAll(input), () => writer),\n        onFailure: (cause: Cause<E>) => mailbox.failCause(cause),\n        onDone: () => mailbox.end\n      })\n      return fiberRuntime.scopeWith((scope) =>\n        stream.toChannel(self).pipe(\n          coreChannel.pipeTo(writer),\n          channelExecutor.runIn(scope),\n          circular.forkIn(scope)\n        )\n      )\n    }\n  ))\n"
  },
  {
    "path": "packages/effect/src/internal/managedRuntime/circular.ts",
    "content": "import type * as M from \"../../ManagedRuntime.js\"\n\n// circular with Layer\n\n/** @internal */\nexport const TypeId: M.TypeId = Symbol.for(\"effect/ManagedRuntime\") as M.TypeId\n"
  },
  {
    "path": "packages/effect/src/internal/managedRuntime.ts",
    "content": "import type * as Effect from \"../Effect.js\"\nimport * as Effectable from \"../Effectable.js\"\nimport type { Exit } from \"../Exit.js\"\nimport type * as Fiber from \"../Fiber.js\"\nimport type * as Layer from \"../Layer.js\"\nimport type * as M from \"../ManagedRuntime.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as Runtime from \"../Runtime.js\"\nimport * as Scheduler from \"../Scheduler.js\"\nimport * as Scope from \"../Scope.js\"\nimport type { Mutable } from \"../Types.js\"\nimport * as core from \"./core.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\nimport * as internalLayer from \"./layer.js\"\nimport * as circular from \"./managedRuntime/circular.js\"\nimport * as internalRuntime from \"./runtime.js\"\n\ninterface ManagedRuntimeImpl<R, E> extends M.ManagedRuntime<R, E> {\n  readonly scope: Scope.CloseableScope\n  cachedRuntime: Runtime.Runtime<R> | undefined\n}\n\n/** @internal */\nexport const isManagedRuntime = (u: unknown): u is M.ManagedRuntime<unknown, unknown> => hasProperty(u, circular.TypeId)\n\nfunction provide<R, ER, A, E>(\n  managed: ManagedRuntimeImpl<R, ER>,\n  effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E | ER> {\n  return core.flatMap(\n    managed.runtimeEffect,\n    (rt) =>\n      core.withFiberRuntime((fiber) => {\n        fiber.setFiberRefs(rt.fiberRefs)\n        fiber.currentRuntimeFlags = rt.runtimeFlags\n        return core.provideContext(effect, rt.context)\n      })\n  )\n}\n\nconst ManagedRuntimeProto = {\n  ...Effectable.CommitPrototype,\n  [circular.TypeId]: circular.TypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  commit(this: ManagedRuntimeImpl<unknown, unknown>) {\n    return this.runtimeEffect\n  }\n}\n\n/** @internal */\nexport const make = <R, ER>(\n  layer: Layer.Layer<R, ER, never>,\n  memoMap?: Layer.MemoMap\n): M.ManagedRuntime<R, ER> => {\n  memoMap = memoMap ?? internalLayer.unsafeMakeMemoMap()\n  const scope = internalRuntime.unsafeRunSyncEffect(fiberRuntime.scopeMake())\n  let buildFiber: Fiber.RuntimeFiber<Runtime.Runtime<R>, ER> | undefined\n  const runtimeEffect = core.suspend(() => {\n    if (!buildFiber) {\n      const scheduler = new Scheduler.SyncScheduler()\n      buildFiber = internalRuntime.unsafeForkEffect(\n        core.tap(\n          Scope.extend(\n            internalLayer.toRuntimeWithMemoMap(layer, memoMap),\n            scope\n          ),\n          (rt) => {\n            self.cachedRuntime = rt\n          }\n        ),\n        { scope, scheduler }\n      )\n      scheduler.flush()\n    }\n    return core.flatten(buildFiber.await)\n  })\n  const self: ManagedRuntimeImpl<R, ER> = Object.assign(Object.create(ManagedRuntimeProto), {\n    memoMap,\n    scope,\n    runtimeEffect,\n    cachedRuntime: undefined,\n    runtime() {\n      return self.cachedRuntime === undefined ?\n        internalRuntime.unsafeRunPromiseEffect(self.runtimeEffect) :\n        Promise.resolve(self.cachedRuntime)\n    },\n    dispose(): Promise<void> {\n      return internalRuntime.unsafeRunPromiseEffect(self.disposeEffect)\n    },\n    disposeEffect: core.suspend(() => {\n      ;(self as Mutable<ManagedRuntimeImpl<R, ER>>).runtimeEffect = core.die(\"ManagedRuntime disposed\")\n      self.cachedRuntime = undefined\n      return Scope.close(self.scope, core.exitVoid)\n    }),\n    runFork<A, E>(effect: Effect.Effect<A, E, R>, options?: Runtime.RunForkOptions): Fiber.RuntimeFiber<A, E | ER> {\n      return self.cachedRuntime === undefined ?\n        internalRuntime.unsafeForkEffect(provide(self, effect), options) :\n        internalRuntime.unsafeFork(self.cachedRuntime)(effect, options)\n    },\n    runSyncExit<A, E>(effect: Effect.Effect<A, E, R>): Exit<A, E | ER> {\n      return self.cachedRuntime === undefined ?\n        internalRuntime.unsafeRunSyncExitEffect(provide(self, effect)) :\n        internalRuntime.unsafeRunSyncExit(self.cachedRuntime)(effect)\n    },\n    runSync<A, E>(effect: Effect.Effect<A, E, R>): A {\n      return self.cachedRuntime === undefined ?\n        internalRuntime.unsafeRunSyncEffect(provide(self, effect)) :\n        internalRuntime.unsafeRunSync(self.cachedRuntime)(effect)\n    },\n    runPromiseExit<A, E>(effect: Effect.Effect<A, E, R>, options?: {\n      readonly signal?: AbortSignal | undefined\n    }): Promise<Exit<A, E | ER>> {\n      return self.cachedRuntime === undefined ?\n        internalRuntime.unsafeRunPromiseExitEffect(provide(self, effect), options) :\n        internalRuntime.unsafeRunPromiseExit(self.cachedRuntime)(effect, options)\n    },\n    runCallback<A, E>(\n      effect: Effect.Effect<A, E, R>,\n      options?: Runtime.RunCallbackOptions<A, E | ER> | undefined\n    ): Runtime.Cancel<A, E | ER> {\n      return self.cachedRuntime === undefined ?\n        internalRuntime.unsafeRunCallback(internalRuntime.defaultRuntime)(provide(self, effect), options) :\n        internalRuntime.unsafeRunCallback(self.cachedRuntime)(effect, options)\n    },\n    runPromise<A, E>(effect: Effect.Effect<A, E, R>, options?: {\n      readonly signal?: AbortSignal | undefined\n    }): Promise<A> {\n      return self.cachedRuntime === undefined ?\n        internalRuntime.unsafeRunPromiseEffect(provide(self, effect), options) :\n        internalRuntime.unsafeRunPromise(self.cachedRuntime)(effect, options)\n    }\n  })\n  return self\n}\n"
  },
  {
    "path": "packages/effect/src/internal/matcher.ts",
    "content": "import * as Either from \"../Either.js\"\nimport { dual, identity } from \"../Function.js\"\nimport type {\n  Case,\n  Matcher,\n  MatcherTypeId,\n  Not,\n  SafeRefinement,\n  TypeMatcher,\n  Types,\n  ValueMatcher,\n  When\n} from \"../Match.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport type * as Predicate from \"../Predicate.js\"\nimport type { Unify } from \"../Unify.js\"\n\n/** @internal */\nexport const TypeId: MatcherTypeId = Symbol.for(\n  \"@effect/matcher/Matcher\"\n) as MatcherTypeId\n\nconst TypeMatcherProto: Omit<TypeMatcher<any, any, any, any>, \"cases\"> = {\n  [TypeId]: {\n    _input: identity,\n    _filters: identity,\n    _remaining: identity,\n    _result: identity,\n    _return: identity\n  },\n  _tag: \"TypeMatcher\",\n  add<I, R, RA, A>(\n    this: TypeMatcher<any, any, any, any>,\n    _case: Case\n  ): TypeMatcher<I, R, RA, A> {\n    return makeTypeMatcher([...this.cases, _case])\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nfunction makeTypeMatcher<I, R, RA, A>(\n  cases: ReadonlyArray<Case>\n): TypeMatcher<I, R, RA, A> {\n  const matcher = Object.create(TypeMatcherProto)\n  matcher.cases = cases\n  return matcher\n}\n\nconst ValueMatcherProto: Omit<\n  ValueMatcher<any, any, any, any, any>,\n  \"provided\" | \"value\"\n> = {\n  [TypeId]: {\n    _input: identity,\n    _filters: identity,\n    _remaining: identity,\n    _result: identity,\n    _provided: identity,\n    _return: identity\n  },\n  _tag: \"ValueMatcher\",\n  add<I, R, RA, A, Pr>(\n    this: ValueMatcher<any, any, any, any, any>,\n    _case: Case\n  ): ValueMatcher<I, R, RA, A, Pr> {\n    if (this.value._tag === \"Right\") {\n      return this\n    }\n\n    if (_case._tag === \"When\" && _case.guard(this.provided) === true) {\n      return makeValueMatcher(\n        this.provided,\n        Either.right(_case.evaluate(this.provided))\n      )\n    } else if (_case._tag === \"Not\" && _case.guard(this.provided) === false) {\n      return makeValueMatcher(\n        this.provided,\n        Either.right(_case.evaluate(this.provided))\n      )\n    }\n\n    return this\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nfunction makeValueMatcher<I, R, RA, A, Pr>(\n  provided: Pr,\n  value: Either.Either<Pr, RA>\n): ValueMatcher<I, R, RA, A, Pr> {\n  const matcher = Object.create(ValueMatcherProto)\n  matcher.provided = provided\n  matcher.value = value\n  return matcher\n}\n\nconst makeWhen = (\n  guard: (u: unknown) => boolean,\n  evaluate: (input: unknown) => any\n): When => ({\n  _tag: \"When\",\n  guard,\n  evaluate\n})\n\nconst makeNot = (\n  guard: (u: unknown) => boolean,\n  evaluate: (input: unknown) => any\n): Not => ({\n  _tag: \"Not\",\n  guard,\n  evaluate\n})\n\nconst makePredicate = (pattern: unknown): Predicate.Predicate<unknown> => {\n  if (typeof pattern === \"function\") {\n    return pattern as Predicate.Predicate<unknown>\n  } else if (Array.isArray(pattern)) {\n    const predicates = pattern.map(makePredicate)\n    const len = predicates.length\n\n    return (u: unknown) => {\n      if (!Array.isArray(u)) {\n        return false\n      }\n\n      for (let i = 0; i < len; i++) {\n        if (predicates[i](u[i]) === false) {\n          return false\n        }\n      }\n\n      return true\n    }\n  } else if (pattern !== null && typeof pattern === \"object\") {\n    const keysAndPredicates = Object.entries(pattern).map(\n      ([k, p]) => [k, makePredicate(p)] as const\n    )\n    const len = keysAndPredicates.length\n\n    return (u: unknown) => {\n      if (typeof u !== \"object\" || u === null) {\n        return false\n      }\n\n      for (let i = 0; i < len; i++) {\n        const [key, predicate] = keysAndPredicates[i]\n        if (!(key in u) || predicate((u as any)[key]) === false) {\n          return false\n        }\n      }\n\n      return true\n    }\n  }\n\n  return (u: unknown) => u === pattern\n}\n\nconst makeOrPredicate = (\n  patterns: ReadonlyArray<unknown>\n): Predicate.Predicate<unknown> => {\n  const predicates = patterns.map(makePredicate)\n  const len = predicates.length\n\n  return (u: unknown) => {\n    for (let i = 0; i < len; i++) {\n      if (predicates[i](u) === true) {\n        return true\n      }\n    }\n\n    return false\n  }\n}\n\nconst makeAndPredicate = (\n  patterns: ReadonlyArray<unknown>\n): Predicate.Predicate<unknown> => {\n  const predicates = patterns.map(makePredicate)\n  const len = predicates.length\n\n  return (u: unknown) => {\n    for (let i = 0; i < len; i++) {\n      if (predicates[i](u) === false) {\n        return false\n      }\n    }\n\n    return true\n  }\n}\n\n/** @internal */\nexport const type = <I>(): Matcher<\n  I,\n  Types.Without<never>,\n  I,\n  never,\n  never\n> => makeTypeMatcher([])\n\n/** @internal */\nexport const value = <const I>(\n  i: I\n): Matcher<I, Types.Without<never>, I, never, I> => makeValueMatcher(i, Either.left(i))\n\n/** @internal */\nexport const valueTags: {\n  <\n    const I,\n    P extends\n      & { readonly [Tag in Types.Tags<\"_tag\", I> & string]: (_: Extract<I, { readonly _tag: Tag }>) => any }\n      & { readonly [Tag in Exclude<keyof P, Types.Tags<\"_tag\", I>>]: never }\n  >(fields: P): (input: I) => Unify<ReturnType<P[keyof P]>>\n  <\n    const I,\n    P extends\n      & { readonly [Tag in Types.Tags<\"_tag\", I> & string]: (_: Extract<I, { readonly _tag: Tag }>) => any }\n      & { readonly [Tag in Exclude<keyof P, Types.Tags<\"_tag\", I>>]: never }\n  >(input: I, fields: P): Unify<ReturnType<P[keyof P]>>\n} = dual(\n  2,\n  <\n    const I,\n    P extends\n      & { readonly [Tag in Types.Tags<\"_tag\", I> & string]: (_: Extract<I, { readonly _tag: Tag }>) => any }\n      & { readonly [Tag in Exclude<keyof P, Types.Tags<\"_tag\", I>>]: never }\n  >(input: I, fields: P): Unify<ReturnType<P[keyof P]>> => {\n    const match: any = tagsExhaustive(fields as any)(makeTypeMatcher([]))\n    return match(input)\n  }\n)\n\n/** @internal */\nexport const typeTags = <I>() =>\n<\n  P extends {\n    readonly [Tag in Types.Tags<\"_tag\", I> & string]: (\n      _: Extract<I, { readonly _tag: Tag }>\n    ) => any\n  }\n>(\n  fields: P\n) => {\n  const match: any = tagsExhaustive(fields as any)(makeTypeMatcher([]))\n  return (input: I): Unify<ReturnType<P[keyof P]>> => match(input)\n}\n\n/** @internal */\nexport const withReturnType = <Ret>() =>\n<I, F, R, A, Pr, _>(self: Matcher<I, F, R, A, Pr, _>): [Ret] extends [\n  [A] extends [never] ? any : A\n] ? Matcher<I, F, R, A, Pr, Ret>\n  : \"withReturnType constraint does not extend Result type\" => self as any\n\n/** @internal */\nexport const when = <\n  R,\n  const P extends Types.PatternPrimitive<R> | Types.PatternBase<R>,\n  Ret,\n  Fn extends (_: Types.WhenMatch<R, P>) => Ret\n>(\n  pattern: P,\n  f: Fn\n) =>\n<I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n): Matcher<\n  I,\n  Types.AddWithout<F, Types.PForExclude<P>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Types.PForExclude<P>>>,\n  A | ReturnType<Fn>,\n  Pr,\n  Ret\n> => (self as any).add(makeWhen(makePredicate(pattern), f as any))\n\n/** @internal */\nexport const whenOr = <\n  R,\n  const P extends ReadonlyArray<\n    Types.PatternPrimitive<R> | Types.PatternBase<R>\n  >,\n  Ret,\n  Fn extends (_: Types.WhenMatch<R, P[number]>) => Ret\n>(\n  ...args: [...patterns: P, f: Fn]\n) =>\n<I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n): Matcher<\n  I,\n  Types.AddWithout<F, Types.PForExclude<P[number]>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Types.PForExclude<P[number]>>>,\n  A | ReturnType<Fn>,\n  Pr,\n  Ret\n> => {\n  const onMatch = args[args.length - 1] as any\n  const patterns = args.slice(0, -1) as unknown as P\n  return (self as any).add(makeWhen(makeOrPredicate(patterns), onMatch))\n}\n\n/** @internal */\nexport const whenAnd = <\n  R,\n  const P extends ReadonlyArray<\n    Types.PatternPrimitive<R> | Types.PatternBase<R>\n  >,\n  Ret,\n  Fn extends (_: Types.WhenMatch<R, Types.ArrayToIntersection<P>>) => Ret\n>(\n  ...args: [...patterns: P, f: Fn]\n) =>\n<I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n): Matcher<\n  I,\n  Types.AddWithout<F, Types.PForExclude<Types.ArrayToIntersection<P>>>,\n  Types.ApplyFilters<\n    I,\n    Types.AddWithout<F, Types.PForExclude<Types.ArrayToIntersection<P>>>\n  >,\n  A | ReturnType<Fn>,\n  Pr\n> => {\n  const onMatch = args[args.length - 1] as any\n  const patterns = args.slice(0, -1) as unknown as P\n  return (self as any).add(makeWhen(makeAndPredicate(patterns), onMatch))\n}\n\n/** @internal */\nexport const discriminator = <D extends string>(field: D) =>\n<\n  R,\n  P extends Types.Tags<D, R> & string,\n  Ret,\n  Fn extends (_: Extract<R, Record<D, P>>) => Ret\n>(\n  ...pattern: [\n    first: P,\n    ...values: Array<P>,\n    f: Fn\n  ]\n) => {\n  const f = pattern[pattern.length - 1]\n  const values: Array<P> = pattern.slice(0, -1) as any\n  const pred = values.length === 1\n    ? (_: any) => _ != null && _[field] === values[0]\n    : (_: any) => _ != null && values.includes(_[field])\n\n  return <I, F, A, Pr>(\n    self: Matcher<I, F, R, A, Pr, Ret>\n  ): Matcher<\n    I,\n    Types.AddWithout<F, Extract<R, Record<D, P>>>,\n    Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<D, P>>>>,\n    A | ReturnType<Fn>,\n    Pr,\n    Ret\n  > => (self as any).add(makeWhen(pred, f as any)) as any\n}\n\n/** @internal */\nexport const discriminatorStartsWith = <D extends string>(field: D) =>\n<\n  R,\n  P extends string,\n  Ret,\n  Fn extends (_: Extract<R, Record<D, `${P}${string}`>>) => Ret\n>(\n  pattern: P,\n  f: Fn\n) => {\n  const pred = (_: any) => _ != null && typeof _[field] === \"string\" && _[field].startsWith(pattern)\n\n  return <I, F, A, Pr>(\n    self: Matcher<I, F, R, A, Pr, Ret>\n  ): Matcher<\n    I,\n    Types.AddWithout<F, Extract<R, Record<D, `${P}${string}`>>>,\n    Types.ApplyFilters<\n      I,\n      Types.AddWithout<F, Extract<R, Record<D, `${P}${string}`>>>\n    >,\n    A | ReturnType<Fn>,\n    Pr,\n    Ret\n  > => (self as any).add(makeWhen(pred, f as any)) as any\n}\n\n/** @internal */\nexport const discriminators = <D extends string>(field: D) =>\n<\n  R,\n  Ret,\n  P extends\n    & {\n      readonly [Tag in Types.Tags<D, R> & string]?:\n        | ((_: Extract<R, Record<D, Tag>>) => Ret)\n        | undefined\n    }\n    & { readonly [Tag in Exclude<keyof P, Types.Tags<D, R>>]: never }\n>(\n  fields: P\n) => {\n  const predicate = makeWhen(\n    (arg: any) => arg != null && arg[field] in fields,\n    (data: any) => (fields as any)[data[field]](data)\n  )\n\n  return <I, F, A, Pr>(\n    self: Matcher<I, F, R, A, Pr, Ret>\n  ): Matcher<\n    I,\n    Types.AddWithout<F, Extract<R, Record<D, keyof P>>>,\n    Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<D, keyof P>>>>,\n    A | ReturnType<P[keyof P] & {}>,\n    Pr,\n    Ret\n  > => (self as any).add(predicate)\n}\n\n/** @internal */\nexport const discriminatorsExhaustive: <D extends string>(\n  field: D\n) => <\n  R,\n  Ret,\n  P extends\n    & {\n      readonly [Tag in Types.Tags<D, R> & string]: (\n        _: Extract<R, Record<D, Tag>>\n      ) => Ret\n    }\n    & { readonly [Tag in Exclude<keyof P, Types.Tags<D, R>>]: never }\n>(\n  fields: P\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => [Pr] extends [never] ? (u: I) => Unify<A | ReturnType<P[keyof P]>>\n  : Unify<A | ReturnType<P[keyof P]>> = (field: string) => (fields: object) => {\n    const addCases = discriminators(field)(fields)\n    return (matcher: any) => exhaustive(addCases(matcher))\n  }\n\n/** @internal */\nexport const tag: <\n  R,\n  P extends Types.Tags<\"_tag\", R> & string,\n  Ret,\n  Fn extends (_: Extract<R, Record<\"_tag\", P>>) => Ret\n>(\n  ...pattern: [\n    first: P,\n    ...values: Array<P>,\n    f: Fn\n  ]\n) => <I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => Matcher<\n  I,\n  Types.AddWithout<F, Extract<R, Record<\"_tag\", P>>>,\n  Types.ApplyFilters<I, Types.AddWithout<F, Extract<R, Record<\"_tag\", P>>>>,\n  ReturnType<Fn> | A,\n  Pr,\n  Ret\n> = discriminator(\"_tag\")\n\n/** @internal */\nexport const tagStartsWith = discriminatorStartsWith(\"_tag\")\n\n/** @internal */\nexport const tags = discriminators(\"_tag\")\n\n/** @internal */\nexport const tagsExhaustive = discriminatorsExhaustive(\"_tag\")\n\n/** @internal */\nexport const not = <\n  R,\n  const P extends Types.PatternPrimitive<R> | Types.PatternBase<R>,\n  Ret,\n  Fn extends (_: Types.NotMatch<R, P>) => Ret\n>(\n  pattern: P,\n  f: Fn\n) =>\n<I, F, A, Pr>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n): Matcher<\n  I,\n  Types.AddOnly<F, Types.WhenMatch<R, P>>,\n  Types.ApplyFilters<I, Types.AddOnly<F, Types.WhenMatch<R, P>>>,\n  A | ReturnType<Fn>,\n  Pr,\n  Ret\n> => (self as any).add(makeNot(makePredicate(pattern), f as any))\n\n/** @internal */\nexport const nonEmptyString: SafeRefinement<string, never> =\n  ((u: unknown) => typeof u === \"string\" && u.length > 0) as any\n\n/** @internal */\nexport const is: <\n  Literals extends ReadonlyArray<string | number | boolean | null | bigint>\n>(\n  ...literals: Literals\n) => SafeRefinement<Literals[number]> = (...literals): any => {\n  const len = literals.length\n  return (u: unknown) => {\n    for (let i = 0; i < len; i++) {\n      if (u === literals[i]) {\n        return true\n      }\n    }\n    return false\n  }\n}\n\n/** @internal */\nexport const any: SafeRefinement<unknown, any> = (() => true) as any\n\n/** @internal */\nexport const defined = <A>(u: A): u is A & {} => (u !== undefined && u !== null) as any\n\n/** @internal */\nexport const instanceOf = <A extends abstract new(...args: any) => any>(\n  constructor: A\n): SafeRefinement<InstanceType<A>, never> => ((u: unknown) => u instanceof constructor) as any\n\n/** @internal */\nexport const instanceOfUnsafe: <A extends abstract new(...args: any) => any>(\n  constructor: A\n) => SafeRefinement<InstanceType<A>, InstanceType<A>> = instanceOf\n\n/** @internal */\nexport const orElse =\n  <RA, Ret, F extends (_: RA) => Ret>(f: F) =>\n  <I, R, A, Pr>(self: Matcher<I, R, RA, A, Pr, Ret>): [Pr] extends [never] ? (input: I) => Unify<ReturnType<F> | A>\n    : Unify<ReturnType<F> | A> =>\n  {\n    const result = either(self)\n\n    if (Either.isEither(result)) {\n      // @ts-expect-error\n      return result._tag === \"Right\" ? result.right : f(result.left)\n    }\n\n    // @ts-expect-error\n    return (input: I) => {\n      const a = result(input)\n      return a._tag === \"Right\" ? a.right : f(a.left)\n    }\n  }\n\n/** @internal */\nexport const orElseAbsurd = <I, R, RA, A, Pr, Ret>(\n  self: Matcher<I, R, RA, A, Pr, Ret>\n): [Pr] extends [never] ? (input: I) => Unify<A> : Unify<A> =>\n  orElse(() => {\n    throw new Error(\"effect/Match/orElseAbsurd: absurd\")\n  })(self)\n\n/** @internal */\nexport const either: <I, F, R, A, Pr, Ret>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => [Pr] extends [never] ? (input: I) => Either.Either<Unify<A>, R>\n  : Either.Either<Unify<A>, R> = (<I, R, RA, A>(self: Matcher<I, R, RA, A, I>) => {\n    if (self._tag === \"ValueMatcher\") {\n      return self.value\n    }\n\n    const len = self.cases.length\n    if (len === 1) {\n      const _case = self.cases[0]\n      return (input: I): Either.Either<A, RA> => {\n        if (_case._tag === \"When\" && _case.guard(input) === true) {\n          return Either.right(_case.evaluate(input))\n        } else if (_case._tag === \"Not\" && _case.guard(input) === false) {\n          return Either.right(_case.evaluate(input))\n        }\n        return Either.left(input as any)\n      }\n    }\n    return (input: I): Either.Either<A, RA> => {\n      for (let i = 0; i < len; i++) {\n        const _case = self.cases[i]\n        if (_case._tag === \"When\" && _case.guard(input) === true) {\n          return Either.right(_case.evaluate(input))\n        } else if (_case._tag === \"Not\" && _case.guard(input) === false) {\n          return Either.right(_case.evaluate(input))\n        }\n      }\n\n      return Either.left(input as any)\n    }\n  }) as any\n\n/** @internal */\nexport const option: <I, F, R, A, Pr, Ret>(\n  self: Matcher<I, F, R, A, Pr, Ret>\n) => [Pr] extends [never] ? (input: I) => Option.Option<Unify<A>>\n  : Option.Option<Unify<A>> = (<I, A>(self: Matcher<I, any, any, A, I>) => {\n    const toEither = either(self)\n    if (Either.isEither(toEither)) {\n      return Either.match(toEither, {\n        onLeft: () => Option.none(),\n        onRight: Option.some\n      })\n    }\n    return (input: I): Option.Option<A> =>\n      Either.match((toEither as any)(input), {\n        onLeft: () => Option.none(),\n        onRight: Option.some as any\n      })\n  }) as any\n\nconst getExhaustiveAbsurdErrorMessage = \"effect/Match/exhaustive: absurd\"\n\n/** @internal */\nexport const exhaustive: <I, F, A, Pr, Ret>(\n  self: Matcher<I, F, never, A, Pr, Ret>\n) => [Pr] extends [never] ? (u: I) => Unify<A> : Unify<A> = (<I, F, A>(\n  self: Matcher<I, F, never, A, I>\n) => {\n  const toEither = either(self as any)\n\n  if (Either.isEither(toEither)) {\n    if (toEither._tag === \"Right\") {\n      return toEither.right\n    }\n\n    throw new Error(getExhaustiveAbsurdErrorMessage)\n  }\n\n  return (u: I): A => {\n    // @ts-expect-error\n    const result = toEither(u)\n\n    if (result._tag === \"Right\") {\n      return result.right as any\n    }\n\n    throw new Error(getExhaustiveAbsurdErrorMessage)\n  }\n}) as any\n"
  },
  {
    "path": "packages/effect/src/internal/metric/boundaries.ts",
    "content": "import * as Arr from \"../../Array.js\"\nimport * as Chunk from \"../../Chunk.js\"\nimport * as Equal from \"../../Equal.js\"\nimport { pipe } from \"../../Function.js\"\nimport * as Hash from \"../../Hash.js\"\nimport type * as MetricBoundaries from \"../../MetricBoundaries.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport { hasProperty } from \"../../Predicate.js\"\n\n/** @internal */\nconst MetricBoundariesSymbolKey = \"effect/MetricBoundaries\"\n\n/** @internal */\nexport const MetricBoundariesTypeId: MetricBoundaries.MetricBoundariesTypeId = Symbol.for(\n  MetricBoundariesSymbolKey\n) as MetricBoundaries.MetricBoundariesTypeId\n\n/** @internal */\nclass MetricBoundariesImpl implements MetricBoundaries.MetricBoundaries {\n  readonly [MetricBoundariesTypeId]: MetricBoundaries.MetricBoundariesTypeId = MetricBoundariesTypeId\n  constructor(readonly values: ReadonlyArray<number>) {\n    this._hash = pipe(\n      Hash.string(MetricBoundariesSymbolKey),\n      Hash.combine(Hash.array(this.values))\n    )\n  }\n  readonly _hash: number;\n  [Hash.symbol](): number {\n    return this._hash\n  }\n  [Equal.symbol](u: unknown): boolean {\n    return isMetricBoundaries(u) && Equal.equals(this.values, u.values)\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const isMetricBoundaries = (u: unknown): u is MetricBoundaries.MetricBoundaries =>\n  hasProperty(u, MetricBoundariesTypeId)\n\n/** @internal */\nexport const fromIterable = (iterable: Iterable<number>): MetricBoundaries.MetricBoundaries => {\n  const values = pipe(\n    iterable,\n    Arr.appendAll(Chunk.of(Number.POSITIVE_INFINITY)),\n    Arr.dedupe\n  )\n  return new MetricBoundariesImpl(values)\n}\n\n/** @internal */\nexport const linear = (options: {\n  readonly start: number\n  readonly width: number\n  readonly count: number\n}): MetricBoundaries.MetricBoundaries =>\n  pipe(\n    Arr.makeBy(options.count - 1, (i) => options.start + i * options.width),\n    Chunk.unsafeFromArray,\n    fromIterable\n  )\n\n/** @internal */\nexport const exponential = (options: {\n  readonly start: number\n  readonly factor: number\n  readonly count: number\n}): MetricBoundaries.MetricBoundaries =>\n  pipe(\n    Arr.makeBy(options.count - 1, (i) => options.start * Math.pow(options.factor, i)),\n    Chunk.unsafeFromArray,\n    fromIterable\n  )\n"
  },
  {
    "path": "packages/effect/src/internal/metric/hook.ts",
    "content": "import * as Arr from \"../../Array.js\"\nimport * as Duration from \"../../Duration.js\"\nimport type { LazyArg } from \"../../Function.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport type * as MetricHook from \"../../MetricHook.js\"\nimport type * as MetricKey from \"../../MetricKey.js\"\nimport type * as MetricState from \"../../MetricState.js\"\nimport * as number from \"../../Number.js\"\nimport * as Option from \"../../Option.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport * as metricState from \"./state.js\"\n\n/** @internal */\nconst MetricHookSymbolKey = \"effect/MetricHook\"\n\n/** @internal */\nexport const MetricHookTypeId: MetricHook.MetricHookTypeId = Symbol.for(\n  MetricHookSymbolKey\n) as MetricHook.MetricHookTypeId\n\nconst metricHookVariance = {\n  /* c8 ignore next */\n  _In: (_: unknown) => _,\n  /* c8 ignore next */\n  _Out: (_: never) => _\n}\n\n/** @internal */\nexport const make = <In, Out>(\n  options: {\n    readonly get: LazyArg<Out>\n    readonly update: (input: In) => void\n    readonly modify: (input: In) => void\n  }\n): MetricHook.MetricHook<In, Out> => ({\n  [MetricHookTypeId]: metricHookVariance,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  ...options\n})\n\n/** @internal */\nexport const onModify = dual<\n  <In, Out>(f: (input: In) => void) => (self: MetricHook.MetricHook<In, Out>) => MetricHook.MetricHook<In, Out>,\n  <In, Out>(self: MetricHook.MetricHook<In, Out>, f: (input: In) => void) => MetricHook.MetricHook<In, Out>\n>(2, (self, f) => ({\n  [MetricHookTypeId]: metricHookVariance,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  get: self.get,\n  update: self.update,\n  modify: (input) => {\n    self.modify(input)\n    return f(input)\n  }\n}))\n\n/** @internal */\nexport const onUpdate = dual<\n  <In, Out>(f: (input: In) => void) => (self: MetricHook.MetricHook<In, Out>) => MetricHook.MetricHook<In, Out>,\n  <In, Out>(self: MetricHook.MetricHook<In, Out>, f: (input: In) => void) => MetricHook.MetricHook<In, Out>\n>(2, (self, f) => ({\n  [MetricHookTypeId]: metricHookVariance,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  get: self.get,\n  update: (input) => {\n    self.update(input)\n    return f(input)\n  },\n  modify: self.modify\n}))\n\nconst bigint0 = BigInt(0)\n\n/** @internal */\nexport const counter = <A extends (number | bigint)>(\n  key: MetricKey.MetricKey.Counter<A>\n): MetricHook.MetricHook.Counter<A> => {\n  let sum: A = key.keyType.bigint ? bigint0 as A : 0 as A\n  const canUpdate = key.keyType.incremental\n    ? key.keyType.bigint\n      ? (value: A) => value >= bigint0\n      : (value: A) => value >= 0\n    : (_value: A) => true\n  const update = (value: A) => {\n    if (canUpdate(value)) {\n      sum = (sum as any) + value\n    }\n  }\n  return make({\n    get: () => metricState.counter(sum as number) as unknown as MetricState.MetricState.Counter<A>,\n    update,\n    modify: update\n  })\n}\n\n/** @internal */\nexport const frequency = (key: MetricKey.MetricKey.Frequency): MetricHook.MetricHook.Frequency => {\n  const values = new Map<string, number>()\n  for (const word of key.keyType.preregisteredWords) {\n    values.set(word, 0)\n  }\n  const update = (word: string) => {\n    const slotCount = values.get(word) ?? 0\n    values.set(word, slotCount + 1)\n  }\n  return make({\n    get: () => metricState.frequency(values),\n    update,\n    modify: update\n  })\n}\n\n/** @internal */\nexport const gauge: {\n  (key: MetricKey.MetricKey.Gauge<number>, startAt: number): MetricHook.MetricHook.Gauge<number>\n  (key: MetricKey.MetricKey.Gauge<bigint>, startAt: bigint): MetricHook.MetricHook.Gauge<bigint>\n} = <A extends (number | bigint)>(\n  _key: MetricKey.MetricKey.Gauge<A>,\n  startAt: A\n): MetricHook.MetricHook.Gauge<A> => {\n  let value = startAt\n  return make({\n    get: () => metricState.gauge(value as number) as unknown as MetricState.MetricState.Gauge<A>,\n    update: (v) => {\n      value = v\n    },\n    modify: (v) => {\n      value = (value as any) + v\n    }\n  })\n}\n\n/** @internal */\nexport const histogram = (key: MetricKey.MetricKey.Histogram): MetricHook.MetricHook.Histogram => {\n  const bounds = key.keyType.boundaries.values\n  const size = bounds.length\n  const values = new Uint32Array(size + 1)\n  // NOTE: while 64-bit floating point precision shoule be enough for any\n  // practical histogram boundary values, there is still a small chance that\n  // precision will be lost with very large / very small numbers. If we find\n  // that is the case, a more complex approach storing the histogram boundary\n  // values as a tuple of `[original: string, numeric: number]` may be warranted\n  const boundaries = new Float64Array(size)\n  let count = 0\n  let sum = 0\n  let min = Number.MAX_VALUE\n  let max = Number.MIN_VALUE\n\n  pipe(\n    bounds,\n    Arr.sort(number.Order),\n    Arr.map((n, i) => {\n      boundaries[i] = n\n    })\n  )\n\n  // Insert the value into the right bucket with a binary search\n  const update = (value: number) => {\n    let from = 0\n    let to = size\n    while (from !== to) {\n      const mid = Math.floor(from + (to - from) / 2)\n      const boundary = boundaries[mid]\n      if (value <= boundary) {\n        to = mid\n      } else {\n        from = mid\n      }\n      // The special case when to / from have a distance of one\n      if (to === from + 1) {\n        if (value <= boundaries[from]) {\n          to = from\n        } else {\n          from = to\n        }\n      }\n    }\n    values[from] = values[from]! + 1\n    count = count + 1\n    sum = sum + value\n    if (value < min) {\n      min = value\n    }\n    if (value > max) {\n      max = value\n    }\n  }\n\n  const getBuckets = (): ReadonlyArray<readonly [number, number]> => {\n    const builder: Array<readonly [number, number]> = Arr.allocate(size) as any\n    let cumulated = 0\n    for (let i = 0; i < size; i++) {\n      const boundary = boundaries[i]\n      const value = values[i]\n      cumulated = cumulated + value\n      builder[i] = [boundary, cumulated]\n    }\n    return builder\n  }\n\n  return make({\n    get: () =>\n      metricState.histogram({\n        buckets: getBuckets(),\n        count,\n        min,\n        max,\n        sum\n      }),\n    update,\n    modify: update\n  })\n}\n\n/** @internal */\nexport const summary = (key: MetricKey.MetricKey.Summary): MetricHook.MetricHook.Summary => {\n  const { error, maxAge, maxSize, quantiles } = key.keyType\n  const sortedQuantiles = pipe(quantiles, Arr.sort(number.Order))\n  const values = Arr.allocate<readonly [number, number]>(maxSize)\n\n  let head = 0\n  let count = 0\n  let sum = 0\n  let min = 0\n  let max = 0\n\n  // Just before the snapshot we filter out all values older than maxAge\n  const snapshot = (now: number): ReadonlyArray<readonly [number, Option.Option<number>]> => {\n    const builder: Array<number> = []\n    // If the buffer is not full yet it contains valid items at the 0..last\n    // indices and null values at the rest of the positions.\n    //\n    // If the buffer is already full then all elements contains a valid\n    // measurement with timestamp.\n    //\n    // At any given point in time we can enumerate all the non-null elements in\n    // the buffer and filter them by timestamp to get a valid view of a time\n    // window.\n    //\n    // The order does not matter because it gets sorted before passing to\n    // `calculateQuantiles`.\n    let i = 0\n    while (i !== maxSize - 1) {\n      const item = values[i]\n      if (item != null) {\n        const [t, v] = item\n        const age = Duration.millis(now - t)\n        if (Duration.greaterThanOrEqualTo(age, Duration.zero) && Duration.lessThanOrEqualTo(age, maxAge)) {\n          builder.push(v)\n        }\n      }\n      i = i + 1\n    }\n    return calculateQuantiles(\n      error,\n      sortedQuantiles,\n      Arr.sort(builder, number.Order)\n    )\n  }\n\n  const observe = (value: number, timestamp: number) => {\n    if (maxSize > 0) {\n      head = head + 1\n      const target = head % maxSize\n      values[target] = [timestamp, value] as const\n    }\n\n    min = count === 0 ? value : Math.min(min, value)\n    max = count === 0 ? value : Math.max(max, value)\n\n    count = count + 1\n    sum = sum + value\n  }\n\n  return make({\n    get: () =>\n      metricState.summary({\n        error,\n        quantiles: snapshot(Date.now()),\n        count,\n        min,\n        max,\n        sum\n      }),\n    update: ([value, timestamp]) => observe(value, timestamp),\n    modify: ([value, timestamp]) => observe(value, timestamp)\n  })\n}\n\n/** @internal */\ninterface ResolvedQuantile {\n  /**\n   * The quantile that shall be resolved.\n   */\n  readonly quantile: number\n  /**\n   * `Some<number>` if a value for the quantile could be found, otherwise\n   * `None`.\n   */\n  readonly value: Option.Option<number>\n  /**\n   * How many samples have been consumed prior to this quantile.\n   */\n  readonly consumed: number\n  /**\n   * The rest of the samples after the quantile has been resolved.\n   */\n  readonly rest: ReadonlyArray<number>\n}\n\n/** @internal */\nconst calculateQuantiles = (\n  error: number,\n  sortedQuantiles: ReadonlyArray<number>,\n  sortedSamples: ReadonlyArray<number>\n): ReadonlyArray<readonly [number, Option.Option<number>]> => {\n  // The number of samples examined\n  const sampleCount = sortedSamples.length\n  if (!Arr.isNonEmptyReadonlyArray(sortedQuantiles)) {\n    return Arr.empty()\n  }\n  const head = sortedQuantiles[0]\n  const tail = sortedQuantiles.slice(1)\n  const resolvedHead = resolveQuantile(\n    error,\n    sampleCount,\n    Option.none(),\n    0,\n    head,\n    sortedSamples\n  )\n  const resolved = Arr.of(resolvedHead)\n  tail.forEach((quantile) => {\n    resolved.push(\n      resolveQuantile(\n        error,\n        sampleCount,\n        resolvedHead.value,\n        resolvedHead.consumed,\n        quantile,\n        resolvedHead.rest\n      )\n    )\n  })\n  return Arr.map(resolved, (rq) => [rq.quantile, rq.value] as const)\n}\n\n/** @internal */\nconst resolveQuantile = (\n  error: number,\n  sampleCount: number,\n  current: Option.Option<number>,\n  consumed: number,\n  quantile: number,\n  rest: ReadonlyArray<number>\n): ResolvedQuantile => {\n  let error_1 = error\n  let sampleCount_1 = sampleCount\n  let current_1 = current\n  let consumed_1 = consumed\n  let quantile_1 = quantile\n  let rest_1 = rest\n  let error_2 = error\n  let sampleCount_2 = sampleCount\n  let current_2 = current\n  let consumed_2 = consumed\n  let quantile_2 = quantile\n  let rest_2 = rest\n  // eslint-disable-next-line no-constant-condition\n  while (1) {\n    // If the remaining list of samples is empty, there is nothing more to resolve\n    if (!Arr.isNonEmptyReadonlyArray(rest_1)) {\n      return {\n        quantile: quantile_1,\n        value: Option.none(),\n        consumed: consumed_1,\n        rest: []\n      }\n    }\n    // If the quantile is the 100% quantile, we can take the maximum of all the\n    // remaining values as the result\n    if (quantile_1 === 1) {\n      return {\n        quantile: quantile_1,\n        value: Option.some(Arr.lastNonEmpty(rest_1)),\n        consumed: consumed_1 + rest_1.length,\n        rest: []\n      }\n    }\n    // Split into two chunks - the first chunk contains all elements of the same\n    // value as the chunk head\n    const headValue = Arr.headNonEmpty(rest_1) // Get head value since rest_1 is non-empty\n    const sameHead = Arr.span(rest_1, (n) => n === headValue)\n    // How many elements do we want to accept for this quantile\n    const desired = quantile_1 * sampleCount_1\n    // The error margin\n    const allowedError = (error_1 / 2) * desired\n    // Taking into account the elements consumed from the samples so far and the\n    // number of same elements at the beginning of the chunk, calculate the number\n    // of elements we would have if we selected the current head as result\n    const candConsumed = consumed_1 + sameHead[0].length\n    const candError = Math.abs(candConsumed - desired)\n    // If we haven't got enough elements yet, recurse\n    if (candConsumed < desired - allowedError) {\n      error_2 = error_1\n      sampleCount_2 = sampleCount_1\n      current_2 = Arr.head(rest_1)\n      consumed_2 = candConsumed\n      quantile_2 = quantile_1\n      rest_2 = sameHead[1]\n      error_1 = error_2\n      sampleCount_1 = sampleCount_2\n      current_1 = current_2\n      consumed_1 = consumed_2\n      quantile_1 = quantile_2\n      rest_1 = rest_2\n      continue\n    }\n    // If consuming this chunk leads to too many elements (rank is too high)\n    if (candConsumed > desired + allowedError) {\n      const valueToReturn = Option.isNone(current_1)\n        ? Option.some(headValue)\n        : current_1\n      return {\n        quantile: quantile_1,\n        value: valueToReturn,\n        consumed: consumed_1,\n        rest: rest_1\n      }\n    }\n    // If we are in the target interval, select the current head and hand back the leftover after dropping all elements\n    // from the sample chunk that are equal to the current head\n    switch (current_1._tag) {\n      case \"None\": {\n        error_2 = error_1\n        sampleCount_2 = sampleCount_1\n        current_2 = Arr.head(rest_1)\n        consumed_2 = candConsumed\n        quantile_2 = quantile_1\n        rest_2 = sameHead[1]\n        error_1 = error_2\n        sampleCount_1 = sampleCount_2\n        current_1 = current_2\n        consumed_1 = consumed_2\n        quantile_1 = quantile_2\n        rest_1 = rest_2\n        continue\n      }\n      case \"Some\": {\n        const prevError = Math.abs(desired - current_1.value)\n        if (candError < prevError) {\n          error_2 = error_1\n          sampleCount_2 = sampleCount_1\n          current_2 = Arr.head(rest_1)\n          consumed_2 = candConsumed\n          quantile_2 = quantile_1\n          rest_2 = sameHead[1]\n          error_1 = error_2\n          sampleCount_1 = sampleCount_2\n          current_1 = current_2\n          consumed_1 = consumed_2\n          quantile_1 = quantile_2\n          rest_1 = rest_2\n          continue\n        }\n        return {\n          quantile: quantile_1,\n          value: Option.some(current_1.value),\n          consumed: consumed_1,\n          rest: rest_1\n        }\n      }\n    }\n  }\n  throw new Error(\n    \"BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues\"\n  )\n}\n"
  },
  {
    "path": "packages/effect/src/internal/metric/key.ts",
    "content": "import * as Arr from \"../../Array.js\"\nimport type * as Duration from \"../../Duration.js\"\nimport * as Equal from \"../../Equal.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as Hash from \"../../Hash.js\"\nimport type * as MetricBoundaries from \"../../MetricBoundaries.js\"\nimport type * as MetricKey from \"../../MetricKey.js\"\nimport type * as MetricKeyType from \"../../MetricKeyType.js\"\nimport type * as MetricLabel from \"../../MetricLabel.js\"\nimport * as Option from \"../../Option.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport * as metricKeyType from \"./keyType.js\"\nimport * as metricLabel from \"./label.js\"\n\n/** @internal */\nconst MetricKeySymbolKey = \"effect/MetricKey\"\n\n/** @internal */\nexport const MetricKeyTypeId: MetricKey.MetricKeyTypeId = Symbol.for(\n  MetricKeySymbolKey\n) as MetricKey.MetricKeyTypeId\n\nconst metricKeyVariance = {\n  /* c8 ignore next */\n  _Type: (_: never) => _\n}\n\nconst arrayEquivilence = Arr.getEquivalence(Equal.equals)\n\n/** @internal */\nclass MetricKeyImpl<out Type extends MetricKeyType.MetricKeyType<any, any>> implements MetricKey.MetricKey<Type> {\n  readonly [MetricKeyTypeId] = metricKeyVariance\n  constructor(\n    readonly name: string,\n    readonly keyType: Type,\n    readonly description: Option.Option<string>,\n    readonly tags: ReadonlyArray<MetricLabel.MetricLabel> = []\n  ) {\n    this._hash = pipe(\n      Hash.string(this.name + this.description),\n      Hash.combine(Hash.hash(this.keyType)),\n      Hash.combine(Hash.array(this.tags))\n    )\n  }\n  readonly _hash: number;\n  [Hash.symbol](): number {\n    return this._hash\n  }\n  [Equal.symbol](u: unknown): boolean {\n    return isMetricKey(u) &&\n      this.name === u.name &&\n      Equal.equals(this.keyType, u.keyType) &&\n      Equal.equals(this.description, u.description) &&\n      arrayEquivilence(this.tags, u.tags)\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const isMetricKey = (u: unknown): u is MetricKey.MetricKey<MetricKeyType.MetricKeyType<unknown, unknown>> =>\n  hasProperty(u, MetricKeyTypeId)\n\n/** @internal */\nexport const counter: {\n  (name: string, options?: {\n    readonly description?: string | undefined\n    readonly bigint?: false | undefined\n    readonly incremental?: boolean | undefined\n  }): MetricKey.MetricKey.Counter<number>\n  (name: string, options: {\n    readonly description?: string | undefined\n    readonly bigint: true\n    readonly incremental?: boolean | undefined\n  }): MetricKey.MetricKey.Counter<bigint>\n} = (name: string, options) =>\n  new MetricKeyImpl(\n    name,\n    metricKeyType.counter(options as any),\n    Option.fromNullable(options?.description)\n  )\n\n/** @internal */\nexport const frequency = (name: string, options?: {\n  readonly description?: string | undefined\n  readonly preregisteredWords?: ReadonlyArray<string> | undefined\n}): MetricKey.MetricKey.Frequency =>\n  new MetricKeyImpl(name, metricKeyType.frequency(options), Option.fromNullable(options?.description))\n\n/** @internal */\nexport const gauge: {\n  (name: string, options?: {\n    readonly description?: string | undefined\n    readonly bigint?: false | undefined\n  }): MetricKey.MetricKey.Gauge<number>\n  (name: string, options: {\n    readonly description?: string | undefined\n    readonly bigint: true\n  }): MetricKey.MetricKey.Gauge<bigint>\n} = (name, options) =>\n  new MetricKeyImpl(\n    name,\n    metricKeyType.gauge(options as any),\n    Option.fromNullable(options?.description)\n  )\n\n/** @internal */\nexport const histogram = (\n  name: string,\n  boundaries: MetricBoundaries.MetricBoundaries,\n  description?: string\n): MetricKey.MetricKey.Histogram =>\n  new MetricKeyImpl(\n    name,\n    metricKeyType.histogram(boundaries),\n    Option.fromNullable(description)\n  )\n\n/** @internal */\nexport const summary = (\n  options: {\n    readonly name: string\n    readonly maxAge: Duration.DurationInput\n    readonly maxSize: number\n    readonly error: number\n    readonly quantiles: ReadonlyArray<number>\n    readonly description?: string | undefined\n  }\n): MetricKey.MetricKey.Summary =>\n  new MetricKeyImpl(\n    options.name,\n    metricKeyType.summary(options),\n    Option.fromNullable(options.description)\n  )\n\n/** @internal */\nexport const tagged = dual<\n  (\n    key: string,\n    value: string\n  ) => <Type extends MetricKeyType.MetricKeyType<any, any>>(\n    self: MetricKey.MetricKey<Type>\n  ) => MetricKey.MetricKey<Type>,\n  <Type extends MetricKeyType.MetricKeyType<any, any>>(\n    self: MetricKey.MetricKey<Type>,\n    key: string,\n    value: string\n  ) => MetricKey.MetricKey<Type>\n>(3, (self, key, value) => taggedWithLabels(self, [metricLabel.make(key, value)]))\n\n/** @internal */\nexport const taggedWithLabels = dual<\n  (\n    extraTags: ReadonlyArray<MetricLabel.MetricLabel>\n  ) => <Type extends MetricKeyType.MetricKeyType<any, any>>(\n    self: MetricKey.MetricKey<Type>\n  ) => MetricKey.MetricKey<Type>,\n  <Type extends MetricKeyType.MetricKeyType<any, any>>(\n    self: MetricKey.MetricKey<Type>,\n    extraTags: ReadonlyArray<MetricLabel.MetricLabel>\n  ) => MetricKey.MetricKey<Type>\n>(2, (self, extraTags) =>\n  extraTags.length === 0\n    ? self\n    : new MetricKeyImpl(self.name, self.keyType, self.description, Arr.union(self.tags, extraTags)))\n"
  },
  {
    "path": "packages/effect/src/internal/metric/keyType.ts",
    "content": "import * as Duration from \"../../Duration.js\"\nimport * as Equal from \"../../Equal.js\"\nimport { pipe } from \"../../Function.js\"\nimport * as Hash from \"../../Hash.js\"\nimport type * as MetricBoundaries from \"../../MetricBoundaries.js\"\nimport type * as MetricKeyType from \"../../MetricKeyType.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport { hasProperty } from \"../../Predicate.js\"\n\n/** @internal */\nconst MetricKeyTypeSymbolKey = \"effect/MetricKeyType\"\n\n/** @internal */\nexport const MetricKeyTypeTypeId: MetricKeyType.MetricKeyTypeTypeId = Symbol.for(\n  MetricKeyTypeSymbolKey\n) as MetricKeyType.MetricKeyTypeTypeId\n\n/** @internal */\nconst CounterKeyTypeSymbolKey = \"effect/MetricKeyType/Counter\"\n\n/** @internal */\nexport const CounterKeyTypeTypeId: MetricKeyType.CounterKeyTypeTypeId = Symbol.for(\n  CounterKeyTypeSymbolKey\n) as MetricKeyType.CounterKeyTypeTypeId\n\n/** @internal */\nconst FrequencyKeyTypeSymbolKey = \"effect/MetricKeyType/Frequency\"\n\n/** @internal */\nexport const FrequencyKeyTypeTypeId: MetricKeyType.FrequencyKeyTypeTypeId = Symbol.for(\n  FrequencyKeyTypeSymbolKey\n) as MetricKeyType.FrequencyKeyTypeTypeId\n\n/** @internal */\nconst GaugeKeyTypeSymbolKey = \"effect/MetricKeyType/Gauge\"\n\n/** @internal */\nexport const GaugeKeyTypeTypeId: MetricKeyType.GaugeKeyTypeTypeId = Symbol.for(\n  GaugeKeyTypeSymbolKey\n) as MetricKeyType.GaugeKeyTypeTypeId\n\n/** @internal */\nconst HistogramKeyTypeSymbolKey = \"effect/MetricKeyType/Histogram\"\n\n/** @internal */\nexport const HistogramKeyTypeTypeId: MetricKeyType.HistogramKeyTypeTypeId = Symbol.for(\n  HistogramKeyTypeSymbolKey\n) as MetricKeyType.HistogramKeyTypeTypeId\n\n/** @internal */\nconst SummaryKeyTypeSymbolKey = \"effect/MetricKeyType/Summary\"\n\n/** @internal */\nexport const SummaryKeyTypeTypeId: MetricKeyType.SummaryKeyTypeTypeId = Symbol.for(\n  SummaryKeyTypeSymbolKey\n) as MetricKeyType.SummaryKeyTypeTypeId\n\nconst metricKeyTypeVariance = {\n  /* c8 ignore next */\n  _In: (_: unknown) => _,\n  /* c8 ignore next */\n  _Out: (_: never) => _\n}\n\n/** @internal */\nclass CounterKeyType<A extends (number | bigint)> implements MetricKeyType.MetricKeyType.Counter<A> {\n  readonly [MetricKeyTypeTypeId] = metricKeyTypeVariance\n  readonly [CounterKeyTypeTypeId]: MetricKeyType.CounterKeyTypeTypeId = CounterKeyTypeTypeId\n  constructor(readonly incremental: boolean, readonly bigint: boolean) {\n    this._hash = Hash.string(CounterKeyTypeSymbolKey)\n  }\n  readonly _hash: number;\n  [Hash.symbol](): number {\n    return this._hash\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isCounterKey(that)\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst FrequencyKeyTypeHash = Hash.string(FrequencyKeyTypeSymbolKey)\n\n/** @internal */\nclass FrequencyKeyType implements MetricKeyType.MetricKeyType.Frequency {\n  readonly [MetricKeyTypeTypeId] = metricKeyTypeVariance\n  readonly [FrequencyKeyTypeTypeId]: MetricKeyType.FrequencyKeyTypeTypeId = FrequencyKeyTypeTypeId\n  constructor(readonly preregisteredWords: ReadonlyArray<string>) {}\n  [Hash.symbol](): number {\n    return FrequencyKeyTypeHash\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isFrequencyKey(that)\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst GaugeKeyTypeHash = Hash.string(GaugeKeyTypeSymbolKey)\n\n/** @internal */\nclass GaugeKeyType<A extends (number | bigint)> implements MetricKeyType.MetricKeyType.Gauge<A> {\n  readonly [MetricKeyTypeTypeId] = metricKeyTypeVariance\n  readonly [GaugeKeyTypeTypeId]: MetricKeyType.GaugeKeyTypeTypeId = GaugeKeyTypeTypeId\n  constructor(readonly bigint: boolean) {}\n  [Hash.symbol](): number {\n    return GaugeKeyTypeHash\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isGaugeKey(that)\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport class HistogramKeyType implements MetricKeyType.MetricKeyType.Histogram {\n  readonly [MetricKeyTypeTypeId] = metricKeyTypeVariance\n  readonly [HistogramKeyTypeTypeId]: MetricKeyType.HistogramKeyTypeTypeId = HistogramKeyTypeTypeId\n  constructor(readonly boundaries: MetricBoundaries.MetricBoundaries) {\n    this._hash = pipe(\n      Hash.string(HistogramKeyTypeSymbolKey),\n      Hash.combine(Hash.hash(this.boundaries))\n    )\n  }\n  readonly _hash: number;\n  [Hash.symbol](): number {\n    return this._hash\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isHistogramKey(that) && Equal.equals(this.boundaries, that.boundaries)\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nclass SummaryKeyType implements MetricKeyType.MetricKeyType.Summary {\n  readonly [MetricKeyTypeTypeId] = metricKeyTypeVariance\n  readonly [SummaryKeyTypeTypeId]: MetricKeyType.SummaryKeyTypeTypeId = SummaryKeyTypeTypeId\n  constructor(\n    readonly maxAge: Duration.Duration,\n    readonly maxSize: number,\n    readonly error: number,\n    readonly quantiles: ReadonlyArray<number>\n  ) {\n    this._hash = pipe(\n      Hash.string(SummaryKeyTypeSymbolKey),\n      Hash.combine(Hash.hash(this.maxAge)),\n      Hash.combine(Hash.hash(this.maxSize)),\n      Hash.combine(Hash.hash(this.error)),\n      Hash.combine(Hash.array(this.quantiles))\n    )\n  }\n  readonly _hash: number;\n  [Hash.symbol](): number {\n    return this._hash\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isSummaryKey(that) &&\n      Equal.equals(this.maxAge, that.maxAge) &&\n      this.maxSize === that.maxSize &&\n      this.error === that.error &&\n      Equal.equals(this.quantiles, that.quantiles)\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const counter: <A extends number | bigint>(options?: {\n  readonly bigint: boolean\n  readonly incremental: boolean\n}) => CounterKeyType<A> = (options) =>\n  new CounterKeyType(\n    options?.incremental ?? false,\n    options?.bigint ?? false\n  )\n\n/** @internal */\nexport const frequency = (options?: {\n  readonly preregisteredWords?: ReadonlyArray<string> | undefined\n}): MetricKeyType.MetricKeyType.Frequency => new FrequencyKeyType(options?.preregisteredWords ?? [])\n\n/** @internal */\nexport const gauge: <A extends number | bigint>(options?: {\n  readonly bigint: boolean\n}) => GaugeKeyType<A> = (options) =>\n  new GaugeKeyType(\n    options?.bigint ?? false\n  )\n\n/** @internal */\nexport const histogram = (boundaries: MetricBoundaries.MetricBoundaries): MetricKeyType.MetricKeyType.Histogram => {\n  return new HistogramKeyType(boundaries)\n}\n\n/** @internal */\nexport const summary = (\n  options: {\n    readonly maxAge: Duration.DurationInput\n    readonly maxSize: number\n    readonly error: number\n    readonly quantiles: ReadonlyArray<number>\n  }\n): MetricKeyType.MetricKeyType.Summary => {\n  return new SummaryKeyType(Duration.decode(options.maxAge), options.maxSize, options.error, options.quantiles)\n}\n\n/** @internal */\nexport const isMetricKeyType = (u: unknown): u is MetricKeyType.MetricKeyType<unknown, unknown> =>\n  hasProperty(u, MetricKeyTypeTypeId)\n\n/** @internal */\nexport const isCounterKey = (u: unknown): u is MetricKeyType.MetricKeyType.Counter<number | bigint> =>\n  hasProperty(u, CounterKeyTypeTypeId)\n\n/** @internal */\nexport const isFrequencyKey = (u: unknown): u is MetricKeyType.MetricKeyType.Frequency =>\n  hasProperty(u, FrequencyKeyTypeTypeId)\n\n/** @internal */\nexport const isGaugeKey = (u: unknown): u is MetricKeyType.MetricKeyType.Gauge<number | bigint> =>\n  hasProperty(u, GaugeKeyTypeTypeId)\n\n/** @internal */\nexport const isHistogramKey = (u: unknown): u is MetricKeyType.MetricKeyType.Histogram =>\n  hasProperty(u, HistogramKeyTypeTypeId)\n\n/** @internal */\nexport const isSummaryKey = (u: unknown): u is MetricKeyType.MetricKeyType.Summary =>\n  hasProperty(u, SummaryKeyTypeTypeId)\n"
  },
  {
    "path": "packages/effect/src/internal/metric/label.ts",
    "content": "import * as Equal from \"../../Equal.js\"\nimport * as Hash from \"../../Hash.js\"\nimport type * as MetricLabel from \"../../MetricLabel.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport { hasProperty } from \"../../Predicate.js\"\n\n/** @internal */\nconst MetricLabelSymbolKey = \"effect/MetricLabel\"\n\n/** @internal */\nexport const MetricLabelTypeId: MetricLabel.MetricLabelTypeId = Symbol.for(\n  MetricLabelSymbolKey\n) as MetricLabel.MetricLabelTypeId\n\n/** @internal */\nclass MetricLabelImpl implements MetricLabel.MetricLabel {\n  readonly [MetricLabelTypeId]: MetricLabel.MetricLabelTypeId = MetricLabelTypeId\n  readonly _hash: number\n  constructor(readonly key: string, readonly value: string) {\n    this._hash = Hash.string(MetricLabelSymbolKey + this.key + this.value)\n  }\n  [Hash.symbol](): number {\n    return this._hash\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isMetricLabel(that) &&\n      this.key === that.key &&\n      this.value === that.value\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const make = (key: string, value: string): MetricLabel.MetricLabel => {\n  return new MetricLabelImpl(key, value)\n}\n\n/** @internal */\nexport const isMetricLabel = (u: unknown): u is MetricLabel.MetricLabel => hasProperty(u, MetricLabelTypeId)\n"
  },
  {
    "path": "packages/effect/src/internal/metric/pair.ts",
    "content": "import type * as MetricKey from \"../../MetricKey.js\"\nimport type * as MetricKeyType from \"../../MetricKeyType.js\"\nimport type * as MetricPair from \"../../MetricPair.js\"\nimport type * as MetricState from \"../../MetricState.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\n\n/** @internal */\nconst MetricPairSymbolKey = \"effect/MetricPair\"\n\n/** @internal */\nexport const MetricPairTypeId: MetricPair.MetricPairTypeId = Symbol.for(\n  MetricPairSymbolKey\n) as MetricPair.MetricPairTypeId\n\nconst metricPairVariance = {\n  /* c8 ignore next */\n  _Type: (_: never) => _\n}\n\n/** @internal */\nexport const make = <Type extends MetricKeyType.MetricKeyType<any, any>>(\n  metricKey: MetricKey.MetricKey<Type>,\n  metricState: MetricState.MetricState<MetricKeyType.MetricKeyType.OutType<Type>>\n): MetricPair.MetricPair.Untyped => {\n  return {\n    [MetricPairTypeId]: metricPairVariance,\n    metricKey,\n    metricState,\n    pipe() {\n      return pipeArguments(this, arguments)\n    }\n  }\n}\n\n/** @internal */\nexport const unsafeMake = <Type extends MetricKeyType.MetricKeyType<any, any>>(\n  metricKey: MetricKey.MetricKey<Type>,\n  metricState: MetricState.MetricState.Untyped\n): MetricPair.MetricPair.Untyped => {\n  return {\n    [MetricPairTypeId]: metricPairVariance,\n    metricKey,\n    metricState,\n    pipe() {\n      return pipeArguments(this, arguments)\n    }\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/metric/polling.ts",
    "content": "import type * as Effect from \"../../Effect.js\"\nimport type * as Fiber from \"../../Fiber.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport type * as Metric from \"../../Metric.js\"\nimport type * as MetricPolling from \"../../MetricPolling.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport type * as Schedule from \"../../Schedule.js\"\nimport type * as Scope from \"../../Scope.js\"\nimport * as core from \"../core.js\"\nimport * as metric from \"../metric.js\"\nimport * as schedule_ from \"../schedule.js\"\n\n/** @internal */\nconst MetricPollingSymbolKey = \"effect/MetricPolling\"\n\n/** @internal */\nexport const MetricPollingTypeId: MetricPolling.MetricPollingTypeId = Symbol.for(\n  MetricPollingSymbolKey\n) as MetricPolling.MetricPollingTypeId\n\n/** @internal */\nexport const make = <Type, In, Out, R, E>(\n  metric: Metric.Metric<Type, In, Out>,\n  poll: Effect.Effect<In, E, R>\n): MetricPolling.MetricPolling<Type, In, R, E, Out> => {\n  return {\n    [MetricPollingTypeId]: MetricPollingTypeId,\n    pipe() {\n      return pipeArguments(this, arguments)\n    },\n    metric,\n    poll\n  }\n}\n\n/** @internal */\nexport const collectAll = <R, E, Out>(\n  iterable: Iterable<MetricPolling.MetricPolling<any, any, R, E, Out>>\n): MetricPolling.MetricPolling<Array<any>, Array<any>, R, E, Array<Out>> => {\n  const metrics = Array.from(iterable)\n  return {\n    [MetricPollingTypeId]: MetricPollingTypeId,\n    pipe() {\n      return pipeArguments(this, arguments)\n    },\n    metric: metric.make(\n      Array.of<any>(void 0) as Array<any>,\n      (inputs: Array<any>, extraTags) => {\n        for (let i = 0; i < inputs.length; i++) {\n          const pollingMetric = metrics[i]!\n          const input = pipe(inputs, (x) => x[i])\n          pollingMetric.metric.unsafeUpdate(input, extraTags)\n        }\n      },\n      (extraTags) =>\n        Array.from(\n          metrics.map((pollingMetric) => pollingMetric.metric.unsafeValue(extraTags))\n        ),\n      (inputs: Array<any>, extraTags) => {\n        for (let i = 0; i < inputs.length; i++) {\n          const pollingMetric = metrics[i]!\n          const input = pipe(inputs, (x) => x[i])\n          pollingMetric.metric.unsafeModify(input, extraTags)\n        }\n      }\n    ),\n    poll: core.forEachSequential(metrics, (metric) => metric.poll)\n  }\n}\n\n/** @internal */\nexport const launch = dual<\n  <A2, R2>(\n    schedule: Schedule.Schedule<A2, unknown, R2>\n  ) => <Type, In, R, E, Out>(\n    self: MetricPolling.MetricPolling<Type, In, R, E, Out>\n  ) => Effect.Effect<Fiber.Fiber<A2, E>, never, R | R2 | Scope.Scope>,\n  <Type, In, R, E, Out, A2, R2>(\n    self: MetricPolling.MetricPolling<Type, In, R, E, Out>,\n    schedule: Schedule.Schedule<A2, unknown, R2>\n  ) => Effect.Effect<Fiber.Fiber<A2, E>, never, R | R2 | Scope.Scope>\n>(2, (self, schedule) =>\n  pipe(\n    pollAndUpdate(self),\n    core.zipRight(metric.value(self.metric)),\n    schedule_.scheduleForked(schedule)\n  ))\n\n/** @internal */\nexport const poll = <Type, In, R, E, Out>(\n  self: MetricPolling.MetricPolling<Type, In, R, E, Out>\n): Effect.Effect<In, E, R> => self.poll\n\n/** @internal */\nexport const pollAndUpdate = <Type, In, R, E, Out>(\n  self: MetricPolling.MetricPolling<Type, In, R, E, Out>\n): Effect.Effect<void, E, R> => core.flatMap(self.poll, (value) => metric.update(self.metric, value))\n\n/** @internal */\nexport const retry = dual<\n  <X, E, R2>(\n    policy: Schedule.Schedule<X, E, R2>\n  ) => <Type, In, R, Out>(\n    self: MetricPolling.MetricPolling<Type, In, R, E, Out>\n  ) => MetricPolling.MetricPolling<Type, In, R | R2, E, Out>,\n  <Type, In, R, E, Out, X, R2>(\n    self: MetricPolling.MetricPolling<Type, In, R, E, Out>,\n    policy: Schedule.Schedule<X, E, R2>\n  ) => MetricPolling.MetricPolling<Type, In, R | R2, E, Out>\n>(2, (self, policy) => ({\n  [MetricPollingTypeId]: MetricPollingTypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  metric: self.metric,\n  poll: schedule_.retry_Effect(self.poll, policy)\n}))\n\n/** @internal */\nexport const zip = dual<\n  <Type2, In2, R2, E2, Out2>(\n    that: MetricPolling.MetricPolling<Type2, In2, R2, E2, Out2>\n  ) => <Type, In, R, E, Out>(\n    self: MetricPolling.MetricPolling<Type, In, R, E, Out>\n  ) => MetricPolling.MetricPolling<\n    readonly [Type, Type2],\n    readonly [In, In2],\n    R | R2,\n    E | E2,\n    [Out, Out2]\n  >,\n  <Type, In, R, E, Out, Type2, In2, R2, E2, Out2>(\n    self: MetricPolling.MetricPolling<Type, In, R, E, Out>,\n    that: MetricPolling.MetricPolling<Type2, In2, R2, E2, Out2>\n  ) => MetricPolling.MetricPolling<\n    readonly [Type, Type2],\n    readonly [In, In2],\n    R | R2,\n    E | E2,\n    [Out, Out2]\n  >\n>(2, (self, that) => ({\n  [MetricPollingTypeId]: MetricPollingTypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  metric: pipe(self.metric, metric.zip(that.metric)),\n  poll: core.zip(self.poll, that.poll)\n}))\n"
  },
  {
    "path": "packages/effect/src/internal/metric/registry.ts",
    "content": "import { pipe } from \"../../Function.js\"\nimport type * as MetricHook from \"../../MetricHook.js\"\nimport type * as MetricKey from \"../../MetricKey.js\"\nimport type * as MetricKeyType from \"../../MetricKeyType.js\"\nimport type * as MetricPair from \"../../MetricPair.js\"\nimport type * as MetricRegistry from \"../../MetricRegistry.js\"\nimport * as MutableHashMap from \"../../MutableHashMap.js\"\nimport * as Option from \"../../Option.js\"\nimport * as metricHook from \"./hook.js\"\nimport * as metricKeyType from \"./keyType.js\"\nimport * as metricPair from \"./pair.js\"\n\n/** @internal */\nconst MetricRegistrySymbolKey = \"effect/MetricRegistry\"\n\n/** @internal */\nexport const MetricRegistryTypeId: MetricRegistry.MetricRegistryTypeId = Symbol.for(\n  MetricRegistrySymbolKey\n) as MetricRegistry.MetricRegistryTypeId\n\n/** @internal */\nclass MetricRegistryImpl implements MetricRegistry.MetricRegistry {\n  readonly [MetricRegistryTypeId]: MetricRegistry.MetricRegistryTypeId = MetricRegistryTypeId\n\n  private map = MutableHashMap.empty<\n    MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>,\n    MetricHook.MetricHook.Root\n  >()\n\n  snapshot(): Array<MetricPair.MetricPair.Untyped> {\n    const result: Array<MetricPair.MetricPair.Untyped> = []\n    for (const [key, hook] of this.map) {\n      result.push(metricPair.unsafeMake(key, hook.get()))\n    }\n    return result\n  }\n\n  get<Type extends MetricKeyType.MetricKeyType<any, any>>(\n    key: MetricKey.MetricKey<Type>\n  ): MetricHook.MetricHook<\n    MetricKeyType.MetricKeyType.InType<typeof key[\"keyType\"]>,\n    MetricKeyType.MetricKeyType.OutType<typeof key[\"keyType\"]>\n  > {\n    const hook = pipe(\n      this.map,\n      MutableHashMap.get(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>),\n      Option.getOrUndefined\n    )\n    if (hook == null) {\n      if (metricKeyType.isCounterKey(key.keyType)) {\n        return this.getCounter(key as unknown as MetricKey.MetricKey.Counter<any>) as any\n      }\n      if (metricKeyType.isGaugeKey(key.keyType)) {\n        return this.getGauge(key as unknown as MetricKey.MetricKey.Gauge<any>) as any\n      }\n      if (metricKeyType.isFrequencyKey(key.keyType)) {\n        return this.getFrequency(key as unknown as MetricKey.MetricKey.Frequency) as any\n      }\n      if (metricKeyType.isHistogramKey(key.keyType)) {\n        return this.getHistogram(key as unknown as MetricKey.MetricKey.Histogram) as any\n      }\n      if (metricKeyType.isSummaryKey(key.keyType)) {\n        return this.getSummary(key as unknown as MetricKey.MetricKey.Summary) as any\n      }\n      throw new Error(\n        \"BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/effect/issues\"\n      )\n    } else {\n      return hook as any\n    }\n  }\n\n  getCounter<A extends (number | bigint)>(key: MetricKey.MetricKey.Counter<A>): MetricHook.MetricHook.Counter<A> {\n    let value = pipe(\n      this.map,\n      MutableHashMap.get(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>),\n      Option.getOrUndefined\n    )\n    if (value == null) {\n      const counter = metricHook.counter(key)\n      if (!pipe(this.map, MutableHashMap.has(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>))) {\n        pipe(\n          this.map,\n          MutableHashMap.set(\n            key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>,\n            counter as MetricHook.MetricHook.Root\n          )\n        )\n      }\n      value = counter\n    }\n    return value as MetricHook.MetricHook.Counter<A>\n  }\n\n  getFrequency(key: MetricKey.MetricKey.Frequency): MetricHook.MetricHook.Frequency {\n    let value = pipe(\n      this.map,\n      MutableHashMap.get(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>),\n      Option.getOrUndefined\n    )\n    if (value == null) {\n      const frequency = metricHook.frequency(key)\n      if (!pipe(this.map, MutableHashMap.has(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>))) {\n        pipe(\n          this.map,\n          MutableHashMap.set(\n            key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>,\n            frequency as MetricHook.MetricHook.Root\n          )\n        )\n      }\n      value = frequency\n    }\n    return value as MetricHook.MetricHook.Frequency\n  }\n\n  getGauge<A extends (number | bigint)>(key: MetricKey.MetricKey.Gauge<A>): MetricHook.MetricHook.Gauge<A> {\n    let value = pipe(\n      this.map,\n      MutableHashMap.get(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>),\n      Option.getOrUndefined\n    )\n    if (value == null) {\n      const gauge = metricHook.gauge(key as any, key.keyType.bigint ? BigInt(0) as any : 0)\n      if (!pipe(this.map, MutableHashMap.has(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>))) {\n        pipe(\n          this.map,\n          MutableHashMap.set(\n            key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>,\n            gauge as MetricHook.MetricHook.Root\n          )\n        )\n      }\n      value = gauge\n    }\n    return value as MetricHook.MetricHook.Gauge<A>\n  }\n\n  getHistogram(key: MetricKey.MetricKey.Histogram): MetricHook.MetricHook.Histogram {\n    let value = pipe(\n      this.map,\n      MutableHashMap.get(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>),\n      Option.getOrUndefined\n    )\n    if (value == null) {\n      const histogram = metricHook.histogram(key)\n      if (!pipe(this.map, MutableHashMap.has(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>))) {\n        pipe(\n          this.map,\n          MutableHashMap.set(\n            key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>,\n            histogram as MetricHook.MetricHook.Root\n          )\n        )\n      }\n      value = histogram\n    }\n    return value as MetricHook.MetricHook.Histogram\n  }\n\n  getSummary(key: MetricKey.MetricKey.Summary): MetricHook.MetricHook.Summary {\n    let value = pipe(\n      this.map,\n      MutableHashMap.get(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>),\n      Option.getOrUndefined\n    )\n    if (value == null) {\n      const summary = metricHook.summary(key)\n      if (!pipe(this.map, MutableHashMap.has(key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>))) {\n        pipe(\n          this.map,\n          MutableHashMap.set(\n            key as MetricKey.MetricKey<MetricKeyType.MetricKeyType.Untyped>,\n            summary as MetricHook.MetricHook.Root\n          )\n        )\n      }\n      value = summary\n    }\n    return value as MetricHook.MetricHook.Summary\n  }\n}\n\n/** @internal */\nexport const make = (): MetricRegistry.MetricRegistry => {\n  return new MetricRegistryImpl()\n}\n"
  },
  {
    "path": "packages/effect/src/internal/metric/state.ts",
    "content": "import * as Arr from \"../../Array.js\"\nimport * as Equal from \"../../Equal.js\"\nimport { pipe } from \"../../Function.js\"\nimport * as Hash from \"../../Hash.js\"\nimport type * as MetricState from \"../../MetricState.js\"\nimport type * as Option from \"../../Option.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport { hasProperty } from \"../../Predicate.js\"\n\n/** @internal */\nconst MetricStateSymbolKey = \"effect/MetricState\"\n\n/** @internal */\nexport const MetricStateTypeId: MetricState.MetricStateTypeId = Symbol.for(\n  MetricStateSymbolKey\n) as MetricState.MetricStateTypeId\n\n/** @internal */\nconst CounterStateSymbolKey = \"effect/MetricState/Counter\"\n\n/** @internal */\nexport const CounterStateTypeId: MetricState.CounterStateTypeId = Symbol.for(\n  CounterStateSymbolKey\n) as MetricState.CounterStateTypeId\n\n/** @internal */\nconst FrequencyStateSymbolKey = \"effect/MetricState/Frequency\"\n\n/** @internal */\nexport const FrequencyStateTypeId: MetricState.FrequencyStateTypeId = Symbol.for(\n  FrequencyStateSymbolKey\n) as MetricState.FrequencyStateTypeId\n\n/** @internal */\nconst GaugeStateSymbolKey = \"effect/MetricState/Gauge\"\n\n/** @internal */\nexport const GaugeStateTypeId: MetricState.GaugeStateTypeId = Symbol.for(\n  GaugeStateSymbolKey\n) as MetricState.GaugeStateTypeId\n\n/** @internal */\nconst HistogramStateSymbolKey = \"effect/MetricState/Histogram\"\n\n/** @internal */\nexport const HistogramStateTypeId: MetricState.HistogramStateTypeId = Symbol.for(\n  HistogramStateSymbolKey\n) as MetricState.HistogramStateTypeId\n\n/** @internal */\nconst SummaryStateSymbolKey = \"effect/MetricState/Summary\"\n\n/** @internal */\nexport const SummaryStateTypeId: MetricState.SummaryStateTypeId = Symbol.for(\n  SummaryStateSymbolKey\n) as MetricState.SummaryStateTypeId\n\nconst metricStateVariance = {\n  /* c8 ignore next */\n  _A: (_: unknown) => _\n}\n\n/** @internal */\nclass CounterState<A extends (number | bigint)> implements MetricState.MetricState.Counter<A> {\n  readonly [MetricStateTypeId] = metricStateVariance\n  readonly [CounterStateTypeId]: MetricState.CounterStateTypeId = CounterStateTypeId\n  constructor(readonly count: A) {}\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(CounterStateSymbolKey),\n      Hash.combine(Hash.hash(this.count)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isCounterState(that) && this.count === that.count\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst arrayEquals = Arr.getEquivalence(Equal.equals)\n\n/** @internal */\nclass FrequencyState implements MetricState.MetricState.Frequency {\n  readonly [MetricStateTypeId] = metricStateVariance\n  readonly [FrequencyStateTypeId]: MetricState.FrequencyStateTypeId = FrequencyStateTypeId\n  constructor(readonly occurrences: ReadonlyMap<string, number>) {}\n  _hash: number | undefined;\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.string(FrequencyStateSymbolKey),\n      Hash.combine(Hash.array(Arr.fromIterable(this.occurrences.entries()))),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isFrequencyState(that) && arrayEquals(\n      Arr.fromIterable(this.occurrences.entries()),\n      Arr.fromIterable(that.occurrences.entries())\n    )\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nclass GaugeState<A extends (number | bigint)> implements MetricState.MetricState.Gauge<A> {\n  readonly [MetricStateTypeId] = metricStateVariance\n  readonly [GaugeStateTypeId]: MetricState.GaugeStateTypeId = GaugeStateTypeId\n  constructor(readonly value: A) {}\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(GaugeStateSymbolKey),\n      Hash.combine(Hash.hash(this.value)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](u: unknown): boolean {\n    return isGaugeState(u) && this.value === u.value\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport class HistogramState implements MetricState.MetricState.Histogram {\n  readonly [MetricStateTypeId] = metricStateVariance\n  readonly [HistogramStateTypeId]: MetricState.HistogramStateTypeId = HistogramStateTypeId\n  constructor(\n    readonly buckets: ReadonlyArray<readonly [number, number]>,\n    readonly count: number,\n    readonly min: number,\n    readonly max: number,\n    readonly sum: number\n  ) {}\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(HistogramStateSymbolKey),\n      Hash.combine(Hash.hash(this.buckets)),\n      Hash.combine(Hash.hash(this.count)),\n      Hash.combine(Hash.hash(this.min)),\n      Hash.combine(Hash.hash(this.max)),\n      Hash.combine(Hash.hash(this.sum)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isHistogramState(that) &&\n      Equal.equals(this.buckets, that.buckets) &&\n      this.count === that.count &&\n      this.min === that.min &&\n      this.max === that.max &&\n      this.sum === that.sum\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport class SummaryState implements MetricState.MetricState.Summary {\n  readonly [MetricStateTypeId] = metricStateVariance\n  readonly [SummaryStateTypeId]: MetricState.SummaryStateTypeId = SummaryStateTypeId\n  constructor(\n    readonly error: number,\n    readonly quantiles: ReadonlyArray<readonly [number, Option.Option<number>]>,\n    readonly count: number,\n    readonly min: number,\n    readonly max: number,\n    readonly sum: number\n  ) {}\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(SummaryStateSymbolKey),\n      Hash.combine(Hash.hash(this.error)),\n      Hash.combine(Hash.hash(this.quantiles)),\n      Hash.combine(Hash.hash(this.count)),\n      Hash.combine(Hash.hash(this.min)),\n      Hash.combine(Hash.hash(this.max)),\n      Hash.combine(Hash.hash(this.sum)),\n      Hash.cached(this)\n    )\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return isSummaryState(that) &&\n      this.error === that.error &&\n      Equal.equals(this.quantiles, that.quantiles) &&\n      this.count === that.count &&\n      this.min === that.min &&\n      this.max === that.max &&\n      this.sum === that.sum\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const counter: {\n  (count: number): MetricState.MetricState.Counter<number>\n  (count: bigint): MetricState.MetricState.Counter<bigint>\n} = (count) => new CounterState(count) as any\n\n/** @internal */\nexport const frequency = (occurrences: ReadonlyMap<string, number>): MetricState.MetricState.Frequency => {\n  return new FrequencyState(occurrences)\n}\n\n/** @internal */\nexport const gauge: {\n  (count: number): MetricState.MetricState.Gauge<number>\n  (count: bigint): MetricState.MetricState.Gauge<bigint>\n} = (count) => new GaugeState(count) as any\n\n/** @internal */\nexport const histogram = (\n  options: {\n    readonly buckets: ReadonlyArray<readonly [number, number]>\n    readonly count: number\n    readonly min: number\n    readonly max: number\n    readonly sum: number\n  }\n): MetricState.MetricState.Histogram =>\n  new HistogramState(\n    options.buckets,\n    options.count,\n    options.min,\n    options.max,\n    options.sum\n  )\n\n/** @internal */\nexport const summary = (\n  options: {\n    readonly error: number\n    readonly quantiles: ReadonlyArray<readonly [number, Option.Option<number>]>\n    readonly count: number\n    readonly min: number\n    readonly max: number\n    readonly sum: number\n  }\n): MetricState.MetricState.Summary =>\n  new SummaryState(\n    options.error,\n    options.quantiles,\n    options.count,\n    options.min,\n    options.max,\n    options.sum\n  )\n\n/** @internal */\nexport const isMetricState = (u: unknown): u is MetricState.MetricState.Counter<number | bigint> =>\n  hasProperty(u, MetricStateTypeId)\n\n/** @internal */\nexport const isCounterState = (u: unknown): u is MetricState.MetricState.Counter<number | bigint> =>\n  hasProperty(u, CounterStateTypeId)\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isFrequencyState = (u: unknown): u is MetricState.MetricState.Frequency =>\n  hasProperty(u, FrequencyStateTypeId)\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isGaugeState = (u: unknown): u is MetricState.MetricState.Gauge<number | bigint> =>\n  hasProperty(u, GaugeStateTypeId)\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isHistogramState = (u: unknown): u is MetricState.MetricState.Histogram =>\n  hasProperty(u, HistogramStateTypeId)\n\n/**\n * @since 2.0.0\n * @category refinements\n */\nexport const isSummaryState = (u: unknown): u is MetricState.MetricState.Summary => hasProperty(u, SummaryStateTypeId)\n"
  },
  {
    "path": "packages/effect/src/internal/metric.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport * as Clock from \"../Clock.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { constVoid, dual, identity, pipe } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport type * as Metric from \"../Metric.js\"\nimport type * as MetricBoundaries from \"../MetricBoundaries.js\"\nimport type * as MetricHook from \"../MetricHook.js\"\nimport type * as MetricKey from \"../MetricKey.js\"\nimport type * as MetricKeyType from \"../MetricKeyType.js\"\nimport type * as MetricLabel from \"../MetricLabel.js\"\nimport type * as MetricPair from \"../MetricPair.js\"\nimport type * as MetricRegistry from \"../MetricRegistry.js\"\nimport type * as MetricState from \"../MetricState.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport * as Cause from \"./cause.js\"\nimport * as effect_ from \"./core-effect.js\"\nimport * as core from \"./core.js\"\nimport * as metricBoundaries from \"./metric/boundaries.js\"\nimport * as metricKey from \"./metric/key.js\"\nimport * as metricKeyType from \"./metric/keyType.js\"\nimport * as metricLabel from \"./metric/label.js\"\nimport * as metricRegistry from \"./metric/registry.js\"\n\n/** @internal */\nconst MetricSymbolKey = \"effect/Metric\"\n\n/** @internal */\nexport const MetricTypeId: Metric.MetricTypeId = Symbol.for(\n  MetricSymbolKey\n) as Metric.MetricTypeId\n\nconst metricVariance = {\n  /* c8 ignore next */\n  _Type: (_: any) => _,\n  /* c8 ignore next */\n  _In: (_: unknown) => _,\n  /* c8 ignore next */\n  _Out: (_: never) => _\n}\n\n/** @internal */\nexport const globalMetricRegistry: MetricRegistry.MetricRegistry = globalValue(\n  Symbol.for(\"effect/Metric/globalMetricRegistry\"),\n  () => metricRegistry.make()\n)\n\n/** @internal */\nexport const make: Metric.MetricApply = function<Type, In, Out>(\n  keyType: Type,\n  unsafeUpdate: (input: In, extraTags: ReadonlyArray<MetricLabel.MetricLabel>) => void,\n  unsafeValue: (extraTags: ReadonlyArray<MetricLabel.MetricLabel>) => Out,\n  unsafeModify: (input: In, extraTags: ReadonlyArray<MetricLabel.MetricLabel>) => void\n): Metric.Metric<Type, In, Out> {\n  const metric: Metric.Metric<Type, In, Out> = Object.assign(\n    <A extends In, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n      core.tap(effect, (a) => update(metric, a)),\n    {\n      [MetricTypeId]: metricVariance,\n      keyType,\n      unsafeUpdate,\n      unsafeValue,\n      unsafeModify,\n      register() {\n        this.unsafeValue([])\n        return this as any\n      },\n      pipe() {\n        return pipeArguments(this, arguments)\n      }\n    } as const\n  )\n  return metric\n}\n\n/** @internal */\nexport const mapInput = dual<\n  <In, In2>(f: (input: In2) => In) => <Type, Out>(self: Metric.Metric<Type, In, Out>) => Metric.Metric<Type, In2, Out>,\n  <Type, In, Out, In2>(self: Metric.Metric<Type, In, Out>, f: (input: In2) => In) => Metric.Metric<Type, In2, Out>\n>(2, (self, f) =>\n  make(\n    self.keyType,\n    (input, extraTags) => self.unsafeUpdate(f(input), extraTags),\n    self.unsafeValue,\n    (input, extraTags) => self.unsafeModify(f(input), extraTags)\n  ))\n\n/** @internal */\nexport const counter: {\n  (name: string, options?: {\n    readonly description?: string | undefined\n    readonly bigint?: false | undefined\n    readonly incremental?: boolean | undefined\n  }): Metric.Metric.Counter<number>\n  (name: string, options: {\n    readonly description?: string | undefined\n    readonly bigint: true\n    readonly incremental?: boolean | undefined\n  }): Metric.Metric.Counter<bigint>\n} = (name, options) => fromMetricKey(metricKey.counter(name, options as any)) as any\n\n/** @internal */\nexport const frequency = (name: string, options?: {\n  readonly description?: string | undefined\n  readonly preregisteredWords?: ReadonlyArray<string> | undefined\n}): Metric.Metric.Frequency<string> => fromMetricKey(metricKey.frequency(name, options))\n\n/** @internal */\nexport const withConstantInput = dual<\n  <In>(input: In) => <Type, Out>(self: Metric.Metric<Type, In, Out>) => Metric.Metric<Type, unknown, Out>,\n  <Type, In, Out>(self: Metric.Metric<Type, In, Out>, input: In) => Metric.Metric<Type, unknown, Out>\n>(2, (self, input) => mapInput(self, () => input))\n\n/** @internal */\nexport const fromMetricKey = <Type extends MetricKeyType.MetricKeyType<any, any>>(\n  key: MetricKey.MetricKey<Type>\n): Metric.Metric<\n  Type,\n  MetricKeyType.MetricKeyType.InType<Type>,\n  MetricKeyType.MetricKeyType.OutType<Type>\n> => {\n  let untaggedHook:\n    | MetricHook.MetricHook<\n      MetricKeyType.MetricKeyType.InType<Type>,\n      MetricKeyType.MetricKeyType.OutType<Type>\n    >\n    | undefined\n  const hookCache = new WeakMap<ReadonlyArray<MetricLabel.MetricLabel>, MetricHook.MetricHook<any, any>>()\n\n  const hook = (extraTags: ReadonlyArray<MetricLabel.MetricLabel>): MetricHook.MetricHook<\n    MetricKeyType.MetricKeyType.InType<Type>,\n    MetricKeyType.MetricKeyType.OutType<Type>\n  > => {\n    if (extraTags.length === 0) {\n      if (untaggedHook !== undefined) {\n        return untaggedHook\n      }\n      untaggedHook = globalMetricRegistry.get(key)\n      return untaggedHook\n    }\n\n    let hook = hookCache.get(extraTags)\n    if (hook !== undefined) {\n      return hook\n    }\n    hook = globalMetricRegistry.get(metricKey.taggedWithLabels(key, extraTags))\n    hookCache.set(extraTags, hook)\n    return hook\n  }\n\n  return make(\n    key.keyType,\n    (input, extraTags) => hook(extraTags).update(input),\n    (extraTags) => hook(extraTags).get(),\n    (input, extraTags) => hook(extraTags).modify(input)\n  )\n}\n\n/** @internal */\nexport const gauge: {\n  (name: string, options?: {\n    readonly description?: string | undefined\n    readonly bigint?: false | undefined\n  }): Metric.Metric.Gauge<number>\n  (name: string, options: {\n    readonly description?: string | undefined\n    readonly bigint: true\n  }): Metric.Metric.Gauge<bigint>\n} = (name, options) => fromMetricKey(metricKey.gauge(name, options as any)) as any\n\n/** @internal */\nexport const histogram = (name: string, boundaries: MetricBoundaries.MetricBoundaries, description?: string) =>\n  fromMetricKey(metricKey.histogram(name, boundaries, description))\n\n/* @internal */\nexport const increment = (\n  self:\n    | Metric.Metric.Counter<number>\n    | Metric.Metric.Counter<bigint>\n    | Metric.Metric.Gauge<number>\n    | Metric.Metric.Gauge<bigint>\n): Effect.Effect<void> =>\n  metricKeyType.isCounterKey(self.keyType)\n    ? update(self as Metric.Metric.Counter<number>, self.keyType.bigint ? BigInt(1) as any : 1)\n    : modify(self as Metric.Metric.Gauge<number>, self.keyType.bigint ? BigInt(1) as any : 1)\n\n/* @internal */\nexport const incrementBy = dual<\n  {\n    (amount: number): (self: Metric.Metric.Counter<number> | Metric.Metric.Counter<number>) => Effect.Effect<void>\n    (amount: bigint): (self: Metric.Metric.Counter<bigint> | Metric.Metric.Gauge<bigint>) => Effect.Effect<void>\n  },\n  {\n    (self: Metric.Metric.Counter<number> | Metric.Metric.Gauge<number>, amount: number): Effect.Effect<void>\n    (self: Metric.Metric.Counter<bigint> | Metric.Metric.Gauge<bigint>, amount: bigint): Effect.Effect<void>\n  }\n>(2, (self, amount) =>\n  metricKeyType.isCounterKey(self.keyType)\n    ? update(self as any, amount)\n    : modify(self as any, amount))\n\n/** @internal */\nexport const map = dual<\n  <Out, Out2>(f: (out: Out) => Out2) => <Type, In>(self: Metric.Metric<Type, In, Out>) => Metric.Metric<Type, In, Out2>,\n  <Type, In, Out, Out2>(self: Metric.Metric<Type, In, Out>, f: (out: Out) => Out2) => Metric.Metric<Type, In, Out2>\n>(2, (self, f) =>\n  make(\n    self.keyType,\n    self.unsafeUpdate,\n    (extraTags) => f(self.unsafeValue(extraTags)),\n    self.unsafeModify\n  ))\n\n/** @internal */\nexport const mapType = dual<\n  <Type, Type2>(\n    f: (type: Type) => Type2\n  ) => <In, Out>(\n    self: Metric.Metric<Type, In, Out>\n  ) => Metric.Metric<Type2, In, Out>,\n  <Type, In, Out, Type2>(\n    self: Metric.Metric<Type, In, Out>,\n    f: (type: Type) => Type2\n  ) => Metric.Metric<Type2, In, Out>\n>(2, (self, f) =>\n  make(\n    f(self.keyType),\n    self.unsafeUpdate,\n    self.unsafeValue,\n    self.unsafeModify\n  ))\n\n/** @internal */\nexport const modify = dual<\n  <In>(input: In) => <Type, Out>(self: Metric.Metric<Type, In, Out>) => Effect.Effect<void>,\n  <Type, In, Out>(self: Metric.Metric<Type, In, Out>, input: In) => Effect.Effect<void>\n>(2, (self, input) =>\n  core.fiberRefGetWith(\n    core.currentMetricLabels,\n    (tags) => core.sync(() => self.unsafeModify(input, tags))\n  ))\n\n/* @internal */\nexport const set = dual<\n  {\n    (value: number): (self: Metric.Metric.Gauge<number>) => Effect.Effect<void>\n    (value: bigint): (self: Metric.Metric.Gauge<bigint>) => Effect.Effect<void>\n  },\n  {\n    (self: Metric.Metric.Gauge<number>, value: number): Effect.Effect<void>\n    (self: Metric.Metric.Gauge<bigint>, value: bigint): Effect.Effect<void>\n  }\n>(2, (self, value) => update(self as any, value))\n\n/** @internal */\nexport const succeed = <Out>(out: Out): Metric.Metric<void, unknown, Out> =>\n  make(void 0 as void, constVoid, () => out, constVoid)\n\n/** @internal */\nexport const sync = <Out>(evaluate: LazyArg<Out>): Metric.Metric<void, unknown, Out> =>\n  make(void 0 as void, constVoid, evaluate, constVoid)\n\n/** @internal */\nexport const summary = (\n  options: {\n    readonly name: string\n    readonly maxAge: Duration.DurationInput\n    readonly maxSize: number\n    readonly error: number\n    readonly quantiles: ReadonlyArray<number>\n    readonly description?: string | undefined\n  }\n): Metric.Metric.Summary<number> => withNow(summaryTimestamp(options))\n\n/** @internal */\nexport const summaryTimestamp = (\n  options: {\n    readonly name: string\n    readonly maxAge: Duration.DurationInput\n    readonly maxSize: number\n    readonly error: number\n    readonly quantiles: ReadonlyArray<number>\n    readonly description?: string | undefined\n  }\n): Metric.Metric.Summary<readonly [value: number, timestamp: number]> => fromMetricKey(metricKey.summary(options))\n\n/** @internal */\nexport const tagged = dual<\n  <Type, In, Out>(key: string, value: string) => (self: Metric.Metric<Type, In, Out>) => Metric.Metric<Type, In, Out>,\n  <Type, In, Out>(self: Metric.Metric<Type, In, Out>, key: string, value: string) => Metric.Metric<Type, In, Out>\n>(3, (self, key, value) => taggedWithLabels(self, [metricLabel.make(key, value)]))\n\n/** @internal */\nexport const taggedWithLabelsInput = dual<\n  <In>(\n    f: (input: In) => Iterable<MetricLabel.MetricLabel>\n  ) => <Type, Out>(self: Metric.Metric<Type, In, Out>) => Metric.Metric<Type, In, void>,\n  <Type, In, Out>(\n    self: Metric.Metric<Type, In, Out>,\n    f: (input: In) => Iterable<MetricLabel.MetricLabel>\n  ) => Metric.Metric<Type, In, void>\n>(2, (self, f) =>\n  map(\n    make(\n      self.keyType,\n      (input, extraTags) =>\n        self.unsafeUpdate(\n          input,\n          Arr.union(f(input), extraTags)\n        ),\n      self.unsafeValue,\n      (input, extraTags) =>\n        self.unsafeModify(\n          input,\n          Arr.union(f(input), extraTags)\n        )\n    ),\n    constVoid\n  ))\n\n/** @internal */\nexport const taggedWithLabels = dual<\n  <Type, In, Out>(\n    extraTags: Iterable<MetricLabel.MetricLabel>\n  ) => (self: Metric.Metric<Type, In, Out>) => Metric.Metric<Type, In, Out>,\n  <Type, In, Out>(\n    self: Metric.Metric<Type, In, Out>,\n    extraTags: Iterable<MetricLabel.MetricLabel>\n  ) => Metric.Metric<Type, In, Out>\n>(2, (self, extraTags) => {\n  return make(\n    self.keyType,\n    (input, extraTags1) => self.unsafeUpdate(input, Arr.union(extraTags, extraTags1)),\n    (extraTags1) => self.unsafeValue(Arr.union(extraTags, extraTags1)),\n    (input, extraTags1) => self.unsafeModify(input, Arr.union(extraTags, extraTags1))\n  )\n})\n\n/** @internal */\nexport const timer = (name: string, description?: string): Metric.Metric<\n  MetricKeyType.MetricKeyType.Histogram,\n  Duration.Duration,\n  MetricState.MetricState.Histogram\n> => {\n  const boundaries = metricBoundaries.exponential({\n    start: 0.5,\n    factor: 2,\n    count: 35\n  })\n  const base = pipe(histogram(name, boundaries, description), tagged(\"time_unit\", \"milliseconds\"))\n  return mapInput(base, Duration.toMillis)\n}\n\n/** @internal */\nexport const timerWithBoundaries = (\n  name: string,\n  boundaries: ReadonlyArray<number>,\n  description?: string\n): Metric.Metric<\n  MetricKeyType.MetricKeyType.Histogram,\n  Duration.Duration,\n  MetricState.MetricState.Histogram\n> => {\n  const base = pipe(\n    histogram(name, metricBoundaries.fromIterable(boundaries), description),\n    tagged(\"time_unit\", \"milliseconds\")\n  )\n  return mapInput(base, Duration.toMillis)\n}\n\n/* @internal */\nexport const trackAll = dual<\n  <In>(\n    input: In\n  ) => <Type, Out>(\n    self: Metric.Metric<Type, In, Out>\n  ) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <Type, In, Out>(\n    self: Metric.Metric<Type, In, Out>,\n    input: In\n  ) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n>(2, (self, input) => (effect) =>\n  core.matchCauseEffect(effect, {\n    onFailure: (cause) => core.zipRight(update(self, input), core.failCause(cause)),\n    onSuccess: (value) => core.zipRight(update(self, input), core.succeed(value))\n  }))\n\n/* @internal */\nexport const trackDefect = dual<\n  <Type, Out>(\n    metric: Metric.Metric<Type, unknown, Out>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R, Type, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric.Metric<Type, unknown, Out>\n  ) => Effect.Effect<A, E, R>\n>(2, (self, metric) => trackDefectWith(self, metric, identity))\n\n/* @internal */\nexport const trackDefectWith = dual<\n  <Type, In, Out>(\n    metric: Metric.Metric<Type, In, Out>,\n    f: (defect: unknown) => In\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R, Type, In, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric.Metric<Type, In, Out>,\n    f: (defect: unknown) => In\n  ) => Effect.Effect<A, E, R>\n>(3, (self, metric, f) => {\n  const updater = (defect: unknown) => update(metric, f(defect))\n  return effect_.tapDefect(self, (cause) => core.forEachSequentialDiscard(Cause.defects(cause), updater))\n})\n\n/* @internal */\nexport const trackDuration = dual<\n  <Type, Out>(\n    metric: Metric.Metric<Type, Duration.Duration, Out>\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R, Type, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric.Metric<Type, Duration.Duration, Out>\n  ) => Effect.Effect<A, E, R>\n>(2, (self, metric) => trackDurationWith(self, metric, identity))\n\n/* @internal */\nexport const trackDurationWith = dual<\n  <Type, In, Out>(\n    metric: Metric.Metric<Type, In, Out>,\n    f: (duration: Duration.Duration) => In\n  ) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R, Type, In, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric.Metric<Type, In, Out>,\n    f: (duration: Duration.Duration) => In\n  ) => Effect.Effect<A, E, R>\n>(3, (self, metric, f) =>\n  Clock.clockWith((clock) => {\n    const startTime = clock.unsafeCurrentTimeNanos()\n    return core.tap(self, (_) => {\n      const endTime = clock.unsafeCurrentTimeNanos()\n      const duration = Duration.nanos(endTime - startTime)\n      return update(metric, f(duration))\n    })\n  }))\n\n/* @internal */\nexport const trackError = dual<\n  <Type, In, Out>(\n    metric: Metric.Metric<Type, In, Out>\n  ) => <A, E extends In, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E extends In, R, Type, In, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric.Metric<Type, In, Out>\n  ) => Effect.Effect<A, E, R>\n>(2, <A, E extends In, R, Type, In, Out>(\n  self: Effect.Effect<A, E, R>,\n  metric: Metric.Metric<Type, In, Out>\n) => trackErrorWith(self, metric, (a: In) => a))\n\n/* @internal */\nexport const trackErrorWith = dual<\n  <Type, In, Out, In2>(\n    metric: Metric.Metric<Type, In, Out>,\n    f: (error: In2) => In\n  ) => <A, E extends In2, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E extends In2, R, Type, In, Out, In2>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric.Metric<Type, In, Out>,\n    f: (error: In2) => In\n  ) => Effect.Effect<A, E, R>\n>(3, <A, E extends In2, R, Type, In, Out, In2>(\n  self: Effect.Effect<A, E, R>,\n  metric: Metric.Metric<Type, In, Out>,\n  f: (error: In2) => In\n) => {\n  const updater = (error: E): Effect.Effect<void> => update(metric, f(error))\n  return effect_.tapError(self, updater)\n})\n\n/* @internal */\nexport const trackSuccess = dual<\n  <Type, In, Out>(\n    metric: Metric.Metric<Type, In, Out>\n  ) => <A extends In, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A extends In, E, R, Type, In, Out>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric.Metric<Type, In, Out>\n  ) => Effect.Effect<A, E, R>\n>(2, <A extends In, E, R, Type, In, Out>(\n  self: Effect.Effect<A, E, R>,\n  metric: Metric.Metric<Type, In, Out>\n) => trackSuccessWith(self, metric, (a: In) => a))\n\n/* @internal */\nexport const trackSuccessWith = dual<\n  <Type, In, Out, In2>(\n    metric: Metric.Metric<Type, In, Out>,\n    f: (value: In2) => In\n  ) => <A extends In2, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A extends In2, E, R, Type, In, Out, In2>(\n    self: Effect.Effect<A, E, R>,\n    metric: Metric.Metric<Type, In, Out>,\n    f: (value: In2) => In\n  ) => Effect.Effect<A, E, R>\n>(3, <A extends In2, E, R, Type, In, Out, In2>(\n  self: Effect.Effect<A, E, R>,\n  metric: Metric.Metric<Type, In, Out>,\n  f: (value: In2) => In\n) => {\n  const updater = (value: A): Effect.Effect<void> => update(metric, f(value))\n  return core.tap(self, updater)\n})\n\n/* @internal */\nexport const update = dual<\n  <In>(input: In) => <Type, Out>(self: Metric.Metric<Type, In, Out>) => Effect.Effect<void>,\n  <Type, In, Out>(self: Metric.Metric<Type, In, Out>, input: In) => Effect.Effect<void>\n>(2, (self, input) =>\n  core.fiberRefGetWith(\n    core.currentMetricLabels,\n    (tags) => core.sync(() => self.unsafeUpdate(input, tags))\n  ))\n\n/* @internal */\nexport const value = <Type, In, Out>(\n  self: Metric.Metric<Type, In, Out>\n): Effect.Effect<Out> =>\n  core.fiberRefGetWith(\n    core.currentMetricLabels,\n    (tags) => core.sync(() => self.unsafeValue(tags))\n  )\n\n/** @internal */\nexport const withNow = <Type, In, Out>(\n  self: Metric.Metric<Type, readonly [In, number], Out>\n): Metric.Metric<Type, In, Out> => mapInput(self, (input: In) => [input, Date.now()] as const)\n\n/** @internal */\nexport const zip = dual<\n  <Type2, In2, Out2>(\n    that: Metric.Metric<Type2, In2, Out2>\n  ) => <Type, In, Out>(\n    self: Metric.Metric<Type, In, Out>\n  ) => Metric.Metric<readonly [Type, Type2], readonly [In, In2], [Out, Out2]>,\n  <Type, In, Out, Type2, In2, Out2>(\n    self: Metric.Metric<Type, In, Out>,\n    that: Metric.Metric<Type2, In2, Out2>\n  ) => Metric.Metric<readonly [Type, Type2], readonly [In, In2], [Out, Out2]>\n>(\n  2,\n  <Type, In, Out, Type2, In2, Out2>(self: Metric.Metric<Type, In, Out>, that: Metric.Metric<Type2, In2, Out2>) =>\n    make(\n      [self.keyType, that.keyType] as const,\n      (input: readonly [In, In2], extraTags) => {\n        const [l, r] = input\n        self.unsafeUpdate(l, extraTags)\n        that.unsafeUpdate(r, extraTags)\n      },\n      (extraTags) => [self.unsafeValue(extraTags), that.unsafeValue(extraTags)],\n      (input: readonly [In, In2], extraTags) => {\n        const [l, r] = input\n        self.unsafeModify(l, extraTags)\n        that.unsafeModify(r, extraTags)\n      }\n    )\n)\n\n/** @internal */\nexport const unsafeSnapshot = (): Array<MetricPair.MetricPair.Untyped> => globalMetricRegistry.snapshot()\n\n/** @internal */\nexport const snapshot: Effect.Effect<Array<MetricPair.MetricPair.Untyped>> = core.sync(\n  unsafeSnapshot\n)\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/cause.ts",
    "content": "/** @internal */\nexport const OP_DIE = \"Die\" as const\n\n/** @internal */\nexport type OP_DIE = typeof OP_DIE\n\n/** @internal */\nexport const OP_EMPTY = \"Empty\" as const\n\n/** @internal */\nexport type OP_EMPTY = typeof OP_EMPTY\n\n/** @internal */\nexport const OP_FAIL = \"Fail\" as const\n\n/** @internal */\nexport type OP_FAIL = typeof OP_FAIL\n\n/** @internal */\nexport const OP_INTERRUPT = \"Interrupt\" as const\n\n/** @internal */\nexport type OP_INTERRUPT = typeof OP_INTERRUPT\n\n/** @internal */\nexport const OP_PARALLEL = \"Parallel\" as const\n\n/** @internal */\nexport type OP_PARALLEL = typeof OP_PARALLEL\n\n/** @internal */\nexport const OP_SEQUENTIAL = \"Sequential\" as const\n\n/** @internal */\nexport type OP_SEQUENTIAL = typeof OP_SEQUENTIAL\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/channel.ts",
    "content": "/** @internal */\nexport const OP_BRACKET_OUT = \"BracketOut\" as const\n\n/** @internal */\nexport type OP_BRACKET_OUT = typeof OP_BRACKET_OUT\n\n/** @internal */\nexport const OP_BRIDGE = \"Bridge\" as const\n\n/** @internal */\nexport type OP_BRIDGE = typeof OP_BRIDGE\n\n/** @internal */\nexport const OP_CONCAT_ALL = \"ConcatAll\" as const\n\n/** @internal */\nexport type OP_CONCAT_ALL = typeof OP_CONCAT_ALL\n\n/** @internal */\nexport const OP_EMIT = \"Emit\" as const\n\n/** @internal */\nexport type OP_EMIT = typeof OP_EMIT\n\n/** @internal */\nexport const OP_ENSURING = \"Ensuring\" as const\n\n/** @internal */\nexport type OP_ENSURING = typeof OP_ENSURING\n\n/** @internal */\nexport const OP_FAIL = \"Fail\" as const\n\n/** @internal */\nexport type OP_FAIL = typeof OP_FAIL\n\n/** @internal */\nexport const OP_FOLD = \"Fold\" as const\n\n/** @internal */\nexport type OP_FOLD = typeof OP_FOLD\n\n/** @internal */\nexport const OP_FROM_EFFECT = \"FromEffect\" as const\n\n/** @internal */\nexport type OP_FROM_EFFECT = typeof OP_FROM_EFFECT\n\n/** @internal */\nexport const OP_PIPE_TO = \"PipeTo\" as const\n\n/** @internal */\nexport type OP_PIPE_TO = typeof OP_PIPE_TO\n\n/** @internal */\nexport const OP_PROVIDE = \"Provide\" as const\n\n/** @internal */\nexport type OP_PROVIDE = typeof OP_PROVIDE\n\n/** @internal */\nexport const OP_READ = \"Read\" as const\n\n/** @internal */\nexport type OP_READ = typeof OP_READ\n\n/** @internal */\nexport const OP_SUCCEED = \"Succeed\" as const\n\n/** @internal */\nexport type OP_SUCCEED = typeof OP_SUCCEED\n\n/** @internal */\nexport const OP_SUCCEED_NOW = \"SucceedNow\" as const\n\n/** @internal */\nexport type OP_SUCCEED_NOW = typeof OP_SUCCEED_NOW\n\n/** @internal */\nexport const OP_SUSPEND = \"Suspend\" as const\n\n/** @internal */\nexport type OP_SUSPEND = typeof OP_SUSPEND\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/channelChildExecutorDecision.ts",
    "content": "/** @internal */\nexport const OP_CONTINUE = \"Continue\" as const\n\n/** @internal */\nexport type OP_CONTINUE = typeof OP_CONTINUE\n\n/** @internal */\nexport const OP_CLOSE = \"Close\" as const\n\n/** @internal */\nexport type OP_CLOSE = typeof OP_CLOSE\n\n/** @internal */\nexport const OP_YIELD = \"Yield\" as const\n\n/** @internal */\nexport type OP_YIELD = typeof OP_YIELD\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/channelMergeDecision.ts",
    "content": "/** @internal */\nexport const OP_DONE = \"Done\" as const\n\n/** @internal */\nexport type OP_DONE = typeof OP_DONE\n\n/** @internal */\nexport const OP_AWAIT = \"Await\" as const\n\n/** @internal */\nexport type OP_AWAIT = typeof OP_AWAIT\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/channelMergeState.ts",
    "content": "/** @internal */\nexport const OP_BOTH_RUNNING = \"BothRunning\" as const\n\n/** @internal */\nexport type OP_BOTH_RUNNING = typeof OP_BOTH_RUNNING\n\n/** @internal */\nexport const OP_LEFT_DONE = \"LeftDone\" as const\n\n/** @internal */\nexport type OP_LEFT_DONE = typeof OP_LEFT_DONE\n\n/** @internal */\nexport const OP_RIGHT_DONE = \"RightDone\" as const\n\n/** @internal */\nexport type OP_RIGHT_DONE = typeof OP_RIGHT_DONE\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/channelMergeStrategy.ts",
    "content": "/** @internal */\nexport const OP_BACK_PRESSURE = \"BackPressure\" as const\n\n/** @internal */\nexport type OP_BACK_PRESSURE = typeof OP_BACK_PRESSURE\n\n/** @internal */\nexport const OP_BUFFER_SLIDING = \"BufferSliding\" as const\n\n/** @internal */\nexport type OP_BUFFER_SLIDING = typeof OP_BUFFER_SLIDING\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/channelState.ts",
    "content": "/** @internal */\nexport const OP_DONE = \"Done\" as const\n\n/** @internal */\nexport type OP_DONE = typeof OP_DONE\n\n/** @internal */\nexport const OP_EMIT = \"Emit\" as const\n\n/** @internal */\nexport type OP_EMIT = typeof OP_EMIT\n\n/** @internal */\nexport const OP_FROM_EFFECT = \"FromEffect\" as const\n\n/** @internal */\nexport type OP_FROM_EFFECT = typeof OP_FROM_EFFECT\n\n/** @internal */\nexport const OP_READ = \"Read\" as const\n\n/** @internal */\nexport type OP_READ = typeof OP_READ\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/channelUpstreamPullRequest.ts",
    "content": "/** @internal */\nexport const OP_PULLED = \"Pulled\" as const\n\n/** @internal */\nexport type OP_PULLED = typeof OP_PULLED\n\n/** @internal */\nexport const OP_NO_UPSTREAM = \"NoUpstream\" as const\n\n/** @internal */\nexport type OP_NO_UPSTREAM = typeof OP_NO_UPSTREAM\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/channelUpstreamPullStrategy.ts",
    "content": "/** @internal */\nexport const OP_PULL_AFTER_NEXT = \"PullAfterNext\" as const\n\n/** @internal */\nexport type OP_PULL_AFTER_NEXT = typeof OP_PULL_AFTER_NEXT\n\n/** @internal */\nexport const OP_PULL_AFTER_ALL_ENQUEUED = \"PullAfterAllEnqueued\" as const\n\n/** @internal */\nexport type OP_PULL_AFTER_ALL_ENQUEUED = typeof OP_PULL_AFTER_ALL_ENQUEUED\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/config.ts",
    "content": "/** @internal */\nexport type OP_CONSTANT = typeof OP_CONSTANT\n\n/** @internal */\nexport const OP_CONSTANT = \"Constant\" as const\n\n/** @internal */\nexport type OP_FAIL = typeof OP_FAIL\n\n/** @internal */\nexport const OP_FAIL = \"Fail\" as const\n\n/** @internal */\nexport type OP_FALLBACK = typeof OP_FALLBACK\n\n/** @internal */\nexport const OP_FALLBACK = \"Fallback\" as const\n\n/** @internal */\nexport type OP_DESCRIBED = typeof OP_DESCRIBED\n\n/** @internal */\nexport const OP_DESCRIBED = \"Described\" as const\n\n/** @internal */\nexport type OP_LAZY = typeof OP_LAZY\n\n/** @internal */\nexport const OP_LAZY = \"Lazy\" as const\n\n/** @internal */\nexport type OP_MAP_OR_FAIL = typeof OP_MAP_OR_FAIL\n\n/** @internal */\nexport const OP_MAP_OR_FAIL = \"MapOrFail\" as const\n\n/** @internal */\nexport type OP_NESTED = typeof OP_NESTED\n\n/** @internal */\nexport const OP_NESTED = \"Nested\" as const\n\n/** @internal */\nexport type OP_PRIMITIVE = typeof OP_PRIMITIVE\n\n/** @internal */\nexport const OP_PRIMITIVE = \"Primitive\" as const\n\n/** @internal */\nexport type OP_SEQUENCE = typeof OP_SEQUENCE\n\n/** @internal */\nexport const OP_SEQUENCE = \"Sequence\" as const\n\n/** @internal */\nexport type OP_HASHMAP = typeof OP_HASHMAP\n\n/** @internal */\nexport const OP_HASHMAP = \"HashMap\" as const\n\n/** @internal */\nexport type OP_ZIP_WITH = typeof OP_ZIP_WITH\n\n/** @internal */\nexport const OP_ZIP_WITH = \"ZipWith\" as const\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/configError.ts",
    "content": "/** @internal */\nexport type OP_AND = typeof OP_AND\n\n/** @internal */\nexport const OP_AND = \"And\" as const\n\n/** @internal */\nexport type OP_OR = typeof OP_OR\n\n/** @internal */\nexport const OP_OR = \"Or\" as const\n\n/** @internal */\nexport type OP_INVALID_DATA = typeof OP_INVALID_DATA\n\n/** @internal */\nexport const OP_INVALID_DATA = \"InvalidData\" as const\n\n/** @internal */\nexport type OP_MISSING_DATA = typeof OP_MISSING_DATA\n\n/** @internal */\nexport const OP_MISSING_DATA = \"MissingData\" as const\n\n/** @internal */\nexport type OP_SOURCE_UNAVAILABLE = typeof OP_SOURCE_UNAVAILABLE\n\n/** @internal */\nexport const OP_SOURCE_UNAVAILABLE = \"SourceUnavailable\" as const\n\n/** @internal */\nexport type OP_UNSUPPORTED = typeof OP_UNSUPPORTED\n\n/** @internal */\nexport const OP_UNSUPPORTED = \"Unsupported\" as const\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/continuation.ts",
    "content": "/** @internal */\nexport const OP_CONTINUATION_K = \"ContinuationK\" as const\n\n/** @internal */\nexport type OP_CONTINUATION_K = typeof OP_CONTINUATION_K\n\n/** @internal */\nexport const OP_CONTINUATION_FINALIZER = \"ContinuationFinalizer\" as const\n\n/** @internal */\nexport type OP_CONTINUATION_FINALIZER = typeof OP_CONTINUATION_FINALIZER\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/deferred.ts",
    "content": "/** @internal */\nexport const OP_STATE_PENDING = \"Pending\" as const\n\n/** @internal */\nexport type OP_STATE_PENDING = typeof OP_STATE_PENDING\n\n/** @internal */\nexport const OP_STATE_DONE = \"Done\" as const\n\n/** @internal */\nexport type OP_STATE_DONE = typeof OP_STATE_DONE\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/effect.ts",
    "content": "/** @internal */\nexport type OP_ASYNC = typeof OP_ASYNC\n\n/** @internal */\nexport const OP_ASYNC = \"Async\" as const\n\n/** @internal */\nexport type OP_COMMIT = typeof OP_COMMIT\n\n/** @internal */\nexport const OP_COMMIT = \"Commit\" as const\n\n/** @internal */\nexport type OP_FAILURE = typeof OP_FAILURE\n\n/** @internal */\nexport const OP_FAILURE = \"Failure\" as const\n\n/** @internal */\nexport type OP_ON_FAILURE = typeof OP_ON_FAILURE\n\n/** @internal */\nexport const OP_ON_FAILURE = \"OnFailure\" as const\n\n/** @internal */\nexport type OP_ON_SUCCESS = typeof OP_ON_SUCCESS\n\n/** @internal */\nexport const OP_ON_SUCCESS = \"OnSuccess\" as const\n\n/** @internal */\nexport type OP_ON_SUCCESS_AND_FAILURE = typeof OP_ON_SUCCESS_AND_FAILURE\n\n/** @internal */\nexport const OP_ON_SUCCESS_AND_FAILURE = \"OnSuccessAndFailure\" as const\n\n/** @internal */\nexport type OP_SUCCESS = typeof OP_SUCCESS\n\n/** @internal */\nexport const OP_SUCCESS = \"Success\" as const\n\n/** @internal */\nexport type OP_SYNC = typeof OP_SYNC\n\n/** @internal */\nexport const OP_SYNC = \"Sync\" as const\n\n/** @internal */\nexport const OP_TAG = \"Tag\" as const\n\n/** @internal */\nexport type OP_TAG = typeof OP_TAG\n\n/** @internal */\nexport type OP_UPDATE_RUNTIME_FLAGS = typeof OP_UPDATE_RUNTIME_FLAGS\n\n/** @internal */\nexport const OP_UPDATE_RUNTIME_FLAGS = \"UpdateRuntimeFlags\" as const\n\n/** @internal */\nexport type OP_WHILE = typeof OP_WHILE\n\n/** @internal */\nexport const OP_WHILE = \"While\" as const\n\n/** @internal */\nexport type OP_ITERATOR = typeof OP_ITERATOR\n\n/** @internal */\nexport const OP_ITERATOR = \"Iterator\" as const\n\n/** @internal */\nexport type OP_WITH_RUNTIME = typeof OP_WITH_RUNTIME\n\n/** @internal */\nexport const OP_WITH_RUNTIME = \"WithRuntime\" as const\n\n/** @internal */\nexport type OP_YIELD = typeof OP_YIELD\n\n/** @internal */\nexport const OP_YIELD = \"Yield\" as const\n\n/** @internal */\nexport type OP_REVERT_FLAGS = typeof OP_REVERT_FLAGS\n\n/** @internal */\nexport const OP_REVERT_FLAGS = \"RevertFlags\" as const\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/layer.ts",
    "content": "/** @internal */\nexport const OP_EXTEND_SCOPE = \"ExtendScope\" as const\n\n/** @internal */\nexport type OP_EXTEND_SCOPE = typeof OP_EXTEND_SCOPE\n\n/** @internal */\nexport const OP_FOLD = \"Fold\" as const\n\n/** @internal */\nexport type OP_FOLD = typeof OP_FOLD\n\n/** @internal */\nexport const OP_FRESH = \"Fresh\" as const\n\n/** @internal */\nexport type OP_FRESH = typeof OP_FRESH\n\n/** @internal */\nexport const OP_FROM_EFFECT = \"FromEffect\" as const\n\n/** @internal */\nexport type OP_FROM_EFFECT = typeof OP_FROM_EFFECT\n\n/** @internal */\nexport const OP_SCOPED = \"Scoped\" as const\n\n/** @internal */\nexport type OP_SCOPED = typeof OP_SCOPED\n\n/** @internal */\nexport const OP_SUSPEND = \"Suspend\" as const\n\n/** @internal */\nexport type OP_SUSPEND = typeof OP_SUSPEND\n\n/** @internal */\nexport const OP_PROVIDE = \"Provide\" as const\n\n/** @internal */\nexport type OP_PROVIDE = typeof OP_PROVIDE\n\n/** @internal */\nexport const OP_PROVIDE_MERGE = \"ProvideMerge\" as const\n\n/** @internal */\nexport type OP_PROVIDE_MERGE = typeof OP_PROVIDE_MERGE\n\n/** @internal */\nexport const OP_MERGE_ALL = \"MergeAll\" as const\n\n/** @internal */\nexport type OP_MERGE_ALL = typeof OP_MERGE_ALL\n\n/** @internal */\nexport const OP_ZIP_WITH = \"ZipWith\" as const\n\n/** @internal */\nexport type OP_ZIP_WITH = typeof OP_ZIP_WITH\n"
  },
  {
    "path": "packages/effect/src/internal/opCodes/streamHaltStrategy.ts",
    "content": "/** @internal */\nexport const OP_LEFT = \"Left\" as const\n\n/** @internal */\nexport type OP_LEFT = typeof OP_LEFT\n\n/** @internal */\nexport const OP_RIGHT = \"Right\" as const\n\n/** @internal */\nexport type OP_RIGHT = typeof OP_RIGHT\n\n/** @internal */\nexport const OP_BOTH = \"Both\" as const\n\n/** @internal */\nexport type OP_BOTH = typeof OP_BOTH\n\n/** @internal */\nexport const OP_EITHER = \"Either\" as const\n\n/** @internal */\nexport type OP_EITHER = typeof OP_EITHER\n"
  },
  {
    "path": "packages/effect/src/internal/option.ts",
    "content": "/**\n * @since 2.0.0\n */\n\nimport * as Equal from \"../Equal.js\"\nimport * as Hash from \"../Hash.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"../Inspectable.js\"\nimport type * as Option from \"../Option.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport { EffectPrototype } from \"./effectable.js\"\n\nconst TypeId: Option.TypeId = Symbol.for(\"effect/Option\") as Option.TypeId\n\nconst CommonProto = {\n  ...EffectPrototype,\n  [TypeId]: {\n    _A: (_: never) => _\n  },\n  [NodeInspectSymbol]<A>(this: Option.Option<A>) {\n    return this.toJSON()\n  },\n  toString<A>(this: Option.Option<A>) {\n    return format(this.toJSON())\n  }\n}\n\nconst SomeProto = Object.assign(Object.create(CommonProto), {\n  _tag: \"Some\",\n  _op: \"Some\",\n  [Equal.symbol]<A>(this: Option.Some<A>, that: unknown): boolean {\n    return isOption(that) && isSome(that) && Equal.equals(this.value, that.value)\n  },\n  [Hash.symbol]<A>(this: Option.Some<A>) {\n    return Hash.cached(this, Hash.combine(Hash.hash(this._tag))(Hash.hash(this.value)))\n  },\n  toJSON<A>(this: Option.Some<A>) {\n    return {\n      _id: \"Option\",\n      _tag: this._tag,\n      value: toJSON(this.value)\n    }\n  }\n})\n\nconst NoneHash = Hash.hash(\"None\")\nconst NoneProto = Object.assign(Object.create(CommonProto), {\n  _tag: \"None\",\n  _op: \"None\",\n  [Equal.symbol]<A>(this: Option.None<A>, that: unknown): boolean {\n    return isOption(that) && isNone(that)\n  },\n  [Hash.symbol]<A>(this: Option.None<A>) {\n    return NoneHash\n  },\n  toJSON<A>(this: Option.None<A>) {\n    return {\n      _id: \"Option\",\n      _tag: this._tag\n    }\n  }\n})\n\n/** @internal */\nexport const isOption = (input: unknown): input is Option.Option<unknown> => hasProperty(input, TypeId)\n\n/** @internal */\nexport const isNone = <A>(fa: Option.Option<A>): fa is Option.None<A> => fa._tag === \"None\"\n\n/** @internal */\nexport const isSome = <A>(fa: Option.Option<A>): fa is Option.Some<A> => fa._tag === \"Some\"\n\n/** @internal */\nexport const none: Option.Option<never> = Object.create(NoneProto)\n\n/** @internal */\nexport const some = <A>(value: A): Option.Option<A> => {\n  const a = Object.create(SomeProto)\n  a.value = value\n  return a\n}\n"
  },
  {
    "path": "packages/effect/src/internal/pool.ts",
    "content": "import type { Cause } from \"../Cause.js\"\nimport * as Context from \"../Context.js\"\nimport * as Duration from \"../Duration.js\"\nimport type { Effect, Semaphore } from \"../Effect.js\"\nimport * as Effectable from \"../Effectable.js\"\nimport type { Exit } from \"../Exit.js\"\nimport { dual, identity } from \"../Function.js\"\nimport * as Iterable from \"../Iterable.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport type { Pool, PoolTypeId as PoolTypeId_ } from \"../Pool.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type { Scope } from \"../Scope.js\"\nimport * as coreEffect from \"./core-effect.js\"\nimport * as core from \"./core.js\"\nimport * as defaultServices from \"./defaultServices.js\"\nimport * as circular from \"./effect/circular.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\nimport * as internalQueue from \"./queue.js\"\n\n/** @internal */\nexport const PoolTypeId: PoolTypeId_ = Symbol.for(\"effect/Pool\") as PoolTypeId_\n\nconst poolVariance = {\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nexport const isPool = (u: unknown): u is Pool<unknown, unknown> => hasProperty(u, PoolTypeId)\n\n/** @internal */\nexport const makeWith = <A, E, R>(options: {\n  readonly acquire: Effect<A, E, R>\n  readonly min: number\n  readonly max: number\n  readonly concurrency?: number | undefined\n  readonly targetUtilization?: number | undefined\n  readonly strategy: Strategy<A, E>\n}): Effect<Pool<A, E>, never, Scope | R> =>\n  core.uninterruptibleMask((restore) =>\n    core.flatMap(core.context<R | Scope>(), (context) => {\n      const scope = Context.get(context, fiberRuntime.scopeTag)\n      const acquire = core.mapInputContext(\n        options.acquire,\n        (input) => Context.merge(context, input)\n      ) as Effect<\n        A,\n        E,\n        Scope\n      >\n      const pool = new PoolImpl<A, E>(\n        scope,\n        acquire,\n        options.concurrency ?? 1,\n        options.min,\n        options.max,\n        options.strategy,\n        Math.min(Math.max(options.targetUtilization ?? 1, 0.1), 1)\n      )\n      const initialize = core.tap(fiberRuntime.forkDaemon(restore(pool.resize)), (fiber) =>\n        scope.addFinalizer(() => core.interruptFiber(fiber)))\n      const runStrategy = core.tap(fiberRuntime.forkDaemon(restore(options.strategy.run(pool))), (fiber) =>\n        scope.addFinalizer(() =>\n          core.interruptFiber(fiber)\n        ))\n      return core.succeed(pool).pipe(\n        core.zipLeft(scope.addFinalizer(() =>\n          pool.shutdown\n        )),\n        core.zipLeft(initialize),\n        core.zipLeft(runStrategy)\n      )\n    })\n  )\n\n/** @internal */\nexport const make = <A, E, R>(options: {\n  readonly acquire: Effect<A, E, R>\n  readonly size: number\n  readonly concurrency?: number | undefined\n  readonly targetUtilization?: number | undefined\n}): Effect<Pool<A, E>, never, R | Scope> =>\n  makeWith({ ...options, min: options.size, max: options.size, strategy: strategyNoop() })\n\n/** @internal */\nexport const makeWithTTL = <A, E, R>(options: {\n  readonly acquire: Effect<A, E, R>\n  readonly min: number\n  readonly max: number\n  readonly concurrency?: number | undefined\n  readonly targetUtilization?: number | undefined\n  readonly timeToLive: Duration.DurationInput\n  readonly timeToLiveStrategy?: \"creation\" | \"usage\" | undefined\n}): Effect<Pool<A, E>, never, R | Scope> =>\n  core.flatMap(\n    options.timeToLiveStrategy === \"creation\" ?\n      strategyCreationTTL<A, E>(options.timeToLive) :\n      strategyUsageTTL<A, E>(options.timeToLive),\n    (strategy) => makeWith({ ...options, strategy })\n  )\n\n/** @internal */\nexport const get = <A, E>(self: Pool<A, E>): Effect<A, E, Scope> => self.get\n\n/** @internal */\nexport const invalidate: {\n  <A>(item: A): <E>(self: Pool<A, E>) => Effect<void>\n  <A, E>(self: Pool<A, E>, item: A): Effect<void>\n} = dual(2, <A, E>(self: Pool<A, E>, item: A): Effect<void> => self.invalidate(item))\n\ninterface PoolItem<A, E> {\n  readonly exit: Exit<A, E>\n  finalizer: Effect<void>\n  refCount: number\n  disableReclaim: boolean\n}\n\ninterface Strategy<A, E> {\n  readonly run: (pool: PoolImpl<A, E>) => Effect<void>\n  readonly onAcquire: (item: PoolItem<A, E>) => Effect<void>\n  readonly reclaim: (pool: PoolImpl<A, E>) => Effect<Option.Option<PoolItem<A, E>>>\n}\n\nclass PoolImpl<A, E> extends Effectable.Class<A, E, Scope> implements Pool<A, E> {\n  readonly [PoolTypeId]: Pool.Variance<A, E>[PoolTypeId_]\n\n  isShuttingDown = false\n  readonly semaphore: Semaphore\n  readonly items = new Set<PoolItem<A, E>>()\n  readonly available = new Set<PoolItem<A, E>>()\n  readonly availableLatch = circular.unsafeMakeLatch(false)\n  readonly invalidated = new Set<PoolItem<A, E>>()\n  waiters = 0\n\n  constructor(\n    readonly scope: Scope,\n    readonly acquire: Effect<A, E, Scope>,\n    readonly concurrency: number,\n    readonly minSize: number,\n    readonly maxSize: number,\n    readonly strategy: Strategy<A, E>,\n    readonly targetUtilization: number\n  ) {\n    super()\n    this[PoolTypeId] = poolVariance\n    this.semaphore = circular.unsafeMakeSemaphore(concurrency * maxSize)\n  }\n\n  readonly allocate: Effect<PoolItem<A, E>> = core.acquireUseRelease(\n    fiberRuntime.scopeMake(),\n    (scope) =>\n      this.acquire.pipe(\n        fiberRuntime.scopeExtend(scope),\n        core.exit,\n        core.flatMap((exit) => {\n          const item: PoolItem<A, E> = {\n            exit,\n            finalizer: core.catchAllCause(scope.close(exit), reportUnhandledError),\n            refCount: 0,\n            disableReclaim: false\n          }\n          this.items.add(item)\n          this.available.add(item)\n          return core.as(\n            exit._tag === \"Success\"\n              ? this.strategy.onAcquire(item)\n              : core.zipRight(item.finalizer, this.strategy.onAcquire(item)),\n            item\n          )\n        })\n      ),\n    (scope, exit) => exit._tag === \"Failure\" ? scope.close(exit) : core.void\n  )\n\n  get currentUsage() {\n    let count = this.waiters\n    for (const item of this.items) {\n      count += item.refCount\n    }\n    return count\n  }\n\n  get targetSize() {\n    if (this.isShuttingDown) return 0\n    const utilization = this.currentUsage / this.targetUtilization\n    const target = Math.ceil(utilization / this.concurrency)\n    return Math.min(Math.max(this.minSize, target), this.maxSize)\n  }\n\n  get activeSize() {\n    return this.items.size - this.invalidated.size\n  }\n\n  readonly resizeLoop: Effect<void> = core.suspend(() => {\n    if (this.activeSize >= this.targetSize) {\n      return core.void\n    }\n    const toAcquire = this.targetSize - this.activeSize\n    return this.strategy.reclaim(this).pipe(\n      core.flatMap(Option.match({\n        onNone: () => this.allocate,\n        onSome: core.succeed\n      })),\n      fiberRuntime.replicateEffect(toAcquire, { concurrency: toAcquire }),\n      core.zipLeft(this.availableLatch.open),\n      core.flatMap((items) => items.some((_) => _.exit._tag === \"Failure\") ? core.void : this.resizeLoop)\n    )\n  })\n  readonly resizeSemaphore = circular.unsafeMakeSemaphore(1)\n  readonly resize = this.resizeSemaphore.withPermits(1)(this.resizeLoop)\n\n  readonly getPoolItem: Effect<PoolItem<A, E>, never, Scope> = core.uninterruptibleMask((restore) =>\n    restore(this.semaphore.take(1)).pipe(\n      core.zipRight(fiberRuntime.scopeTag),\n      core.flatMap((scope) =>\n        core.suspend(() => {\n          this.waiters++\n          if (this.isShuttingDown) {\n            return core.interrupt\n          } else if (this.targetSize > this.activeSize) {\n            // eslint-disable-next-line @typescript-eslint/no-this-alias\n            const self = this\n            return core.flatMap(\n              this.resizeSemaphore.withPermitsIfAvailable(1)(\n                circular.forkIn(core.interruptible(this.resize), this.scope)\n              ),\n              function loop(): Effect<PoolItem<A, E>> {\n                if (self.isShuttingDown) {\n                  return core.interrupt\n                } else if (self.available.size > 0) {\n                  return core.succeed(Iterable.unsafeHead(self.available))\n                }\n                self.availableLatch.unsafeClose()\n                return core.flatMap(self.availableLatch.await, loop)\n              }\n            )\n          }\n          return core.succeed(Iterable.unsafeHead(this.available))\n        }).pipe(\n          fiberRuntime.ensuring(core.sync(() => this.waiters--)),\n          core.tap((item) => {\n            if (item.exit._tag === \"Failure\") {\n              this.items.delete(item)\n              this.invalidated.delete(item)\n              this.available.delete(item)\n              return this.semaphore.release(1)\n            }\n            item.refCount++\n            this.available.delete(item)\n            if (item.refCount < this.concurrency) {\n              this.available.add(item)\n            }\n            return scope.addFinalizer(() =>\n              core.zipRight(\n                core.suspend(() => {\n                  item.refCount--\n                  if (this.invalidated.has(item)) {\n                    return this.invalidatePoolItem(item)\n                  }\n                  this.available.add(item)\n                  return core.exitVoid\n                }),\n                this.semaphore.release(1)\n              )\n            )\n          }),\n          core.onInterrupt(() => this.semaphore.release(1))\n        )\n      )\n    )\n  )\n\n  commit() {\n    return this.get\n  }\n\n  readonly get: Effect<A, E, Scope> = core.flatMap(\n    core.suspend(() => this.isShuttingDown ? core.interrupt : this.getPoolItem),\n    (_) => _.exit\n  )\n\n  invalidate(item: A): Effect<void> {\n    return core.suspend(() => {\n      if (this.isShuttingDown) return core.void\n      for (const poolItem of this.items) {\n        if (poolItem.exit._tag === \"Success\" && poolItem.exit.value === item) {\n          poolItem.disableReclaim = true\n          return core.uninterruptible(this.invalidatePoolItem(poolItem))\n        }\n      }\n      return core.void\n    })\n  }\n\n  invalidatePoolItem(poolItem: PoolItem<A, E>): Effect<void> {\n    return core.suspend(() => {\n      if (!this.items.has(poolItem)) {\n        return core.void\n      } else if (poolItem.refCount === 0) {\n        this.items.delete(poolItem)\n        this.available.delete(poolItem)\n        this.invalidated.delete(poolItem)\n        return core.zipRight(\n          poolItem.finalizer,\n          circular.forkIn(core.interruptible(this.resize), this.scope)\n        )\n      }\n      this.invalidated.add(poolItem)\n      this.available.delete(poolItem)\n      return core.void\n    })\n  }\n\n  get shutdown(): Effect<void> {\n    return core.suspend(() => {\n      if (this.isShuttingDown) return core.void\n      this.isShuttingDown = true\n      const size = this.items.size\n      const semaphore = circular.unsafeMakeSemaphore(size)\n      return core.forEachSequentialDiscard(this.items, (item) => {\n        if (item.refCount > 0) {\n          item.finalizer = core.zipLeft(item.finalizer, semaphore.release(1))\n          this.invalidated.add(item)\n          return semaphore.take(1)\n        }\n        this.items.delete(item)\n        this.available.delete(item)\n        this.invalidated.delete(item)\n        return item.finalizer\n      }).pipe(\n        core.zipRight(this.semaphore.releaseAll),\n        core.zipRight(this.availableLatch.open),\n        core.zipRight(semaphore.take(size))\n      )\n    })\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst strategyNoop = <A, E>(): Strategy<A, E> => ({\n  run: (_) => core.void,\n  onAcquire: (_) => core.void,\n  reclaim: (_) => coreEffect.succeedNone\n})\n\nconst strategyCreationTTL = <A, E>(ttl: Duration.DurationInput) =>\n  defaultServices.clockWith((clock) =>\n    core.map(internalQueue.unbounded<PoolItem<A, E>>(), (queue) => {\n      const ttlMillis = Duration.toMillis(ttl)\n      const creationTimes = new WeakMap<PoolItem<A, E>, number>()\n      return identity<Strategy<A, E>>({\n        run: (pool) => {\n          const process = (item: PoolItem<A, E>): Effect<void> =>\n            core.suspend(() => {\n              if (!pool.items.has(item) || pool.invalidated.has(item)) {\n                return core.void\n              }\n              const now = clock.unsafeCurrentTimeMillis()\n              const created = creationTimes.get(item)!\n              const remaining = ttlMillis - (now - created)\n              return remaining > 0\n                ? coreEffect.delay(process(item), remaining)\n                : pool.invalidatePoolItem(item)\n            })\n          return queue.take.pipe(\n            core.tap(process),\n            coreEffect.forever\n          )\n        },\n        onAcquire: (item) =>\n          core.suspend(() => {\n            creationTimes.set(item, clock.unsafeCurrentTimeMillis())\n            return queue.offer(item)\n          }),\n        reclaim: (_) => coreEffect.succeedNone\n      })\n    })\n  )\n\nconst strategyUsageTTL = <A, E>(ttl: Duration.DurationInput) =>\n  core.map(internalQueue.unbounded<PoolItem<A, E>>(), (queue) => {\n    return identity<Strategy<A, E>>({\n      run: (pool) => {\n        const process: Effect<void> = core.suspend(() => {\n          const excess = pool.activeSize - pool.targetSize\n          if (excess <= 0) return core.void\n          return queue.take.pipe(\n            core.tap((item) => pool.invalidatePoolItem(item)),\n            core.zipRight(process)\n          )\n        })\n        return process.pipe(\n          coreEffect.delay(ttl),\n          coreEffect.forever\n        )\n      },\n      onAcquire: (item) => queue.offer(item),\n      reclaim(pool) {\n        return core.suspend((): Effect<Option.Option<PoolItem<A, E>>> => {\n          if (pool.invalidated.size === 0) {\n            return coreEffect.succeedNone\n          }\n          const item = Iterable.head(\n            Iterable.filter(pool.invalidated, (item) => !item.disableReclaim)\n          )\n          if (item._tag === \"None\") {\n            return coreEffect.succeedNone\n          }\n          pool.invalidated.delete(item.value)\n          if (item.value.refCount < pool.concurrency) {\n            pool.available.add(item.value)\n          }\n          return core.as(queue.offer(item.value), item)\n        })\n      }\n    })\n  })\n\nconst reportUnhandledError = <E>(cause: Cause<E>) =>\n  core.withFiberRuntime<void>((fiber) => {\n    const unhandledLogLevel = fiber.getFiberRef(core.currentUnhandledErrorLogLevel)\n    if (unhandledLogLevel._tag === \"Some\") {\n      fiber.log(\"Unhandled error in pool finalizer\", cause, unhandledLogLevel)\n    }\n    return core.void\n  })\n"
  },
  {
    "path": "packages/effect/src/internal/pubsub.ts",
    "content": "import * as Chunk from \"../Chunk.js\"\nimport type * as Deferred from \"../Deferred.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Effectable from \"../Effectable.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport * as MutableQueue from \"../MutableQueue.js\"\nimport * as MutableRef from \"../MutableRef.js\"\nimport { nextPow2 } from \"../Number.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport type * as PubSub from \"../PubSub.js\"\nimport type * as Queue from \"../Queue.js\"\nimport type * as Scope from \"../Scope.js\"\nimport * as core from \"./core.js\"\nimport * as executionStrategy from \"./executionStrategy.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\nimport * as queue from \"./queue.js\"\n\nconst AbsentValue = Symbol.for(\"effect/PubSub/AbsentValue\")\ntype AbsentValue = typeof AbsentValue\n\n/** @internal */\nexport interface AtomicPubSub<in out A> {\n  readonly capacity: number\n  isEmpty(): boolean\n  isFull(): boolean\n  size(): number\n  publish(value: A): boolean\n  publishAll(elements: Iterable<A>): Chunk.Chunk<A>\n  slide(): void\n  subscribe(): Subscription<A>\n  replayWindow(): ReplayWindow<A>\n}\n\n/** @internal */\ninterface Subscription<out A> {\n  isEmpty(): boolean\n  size(): number\n  poll<D>(default_: D): A | D\n  pollUpTo(n: number): Chunk.Chunk<A>\n  unsubscribe(): void\n}\n\n/** @internal */\ntype Subscribers<A> = Map<\n  Subscription<A>,\n  Set<MutableQueue.MutableQueue<Deferred.Deferred<A>>>\n>\n\nconst addSubscribers = <A>(\n  subscription: Subscription<A>,\n  pollers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n) =>\n(subscribers: Subscribers<A>) => {\n  if (!subscribers.has(subscription)) {\n    subscribers.set(subscription, new Set())\n  }\n  const set = subscribers.get(subscription)!\n  set.add(pollers)\n}\n\nconst removeSubscribers = <A>(\n  subscription: Subscription<A>,\n  pollers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n) =>\n(subscribers: Subscribers<A>) => {\n  if (!subscribers.has(subscription)) {\n    return\n  }\n  const set = subscribers.get(subscription)!\n  set.delete(pollers)\n  if (set.size === 0) {\n    subscribers.delete(subscription)\n  }\n}\n\n/** @internal */\nexport const bounded = <A>(\n  capacity: number | {\n    readonly capacity: number\n    readonly replay?: number | undefined\n  }\n): Effect.Effect<PubSub.PubSub<A>> =>\n  core.suspend(() => {\n    const pubsub = makeBoundedPubSub<A>(capacity)\n    return makePubSub(pubsub, new BackPressureStrategy())\n  })\n\n/** @internal */\nexport const dropping = <A>(\n  capacity: number | {\n    readonly capacity: number\n    readonly replay?: number | undefined\n  }\n): Effect.Effect<PubSub.PubSub<A>> =>\n  core.suspend(() => {\n    const pubsub = makeBoundedPubSub<A>(capacity)\n    return makePubSub(pubsub, new DroppingStrategy())\n  })\n\n/** @internal */\nexport const sliding = <A>(\n  capacity: number | {\n    readonly capacity: number\n    readonly replay?: number | undefined\n  }\n): Effect.Effect<PubSub.PubSub<A>> =>\n  core.suspend(() => {\n    const pubsub = makeBoundedPubSub<A>(capacity)\n    return makePubSub(pubsub, new SlidingStrategy())\n  })\n\n/** @internal */\nexport const unbounded = <A>(options?: {\n  readonly replay?: number | undefined\n}): Effect.Effect<PubSub.PubSub<A>> =>\n  core.suspend(() => {\n    const pubsub = makeUnboundedPubSub<A>(options)\n    return makePubSub(pubsub, new DroppingStrategy())\n  })\n\n/** @internal */\nexport const capacity = <A>(self: PubSub.PubSub<A>): number => self.capacity()\n\n/** @internal */\nexport const size = <A>(self: PubSub.PubSub<A>): Effect.Effect<number> => self.size\n\n/** @internal */\nexport const isFull = <A>(self: PubSub.PubSub<A>): Effect.Effect<boolean> => self.isFull\n\n/** @internal */\nexport const isEmpty = <A>(self: PubSub.PubSub<A>): Effect.Effect<boolean> => self.isEmpty\n\n/** @internal */\nexport const shutdown = <A>(self: PubSub.PubSub<A>): Effect.Effect<void> => self.shutdown\n\n/** @internal */\nexport const isShutdown = <A>(self: PubSub.PubSub<A>): Effect.Effect<boolean> => self.isShutdown\n\n/** @internal */\nexport const awaitShutdown = <A>(self: PubSub.PubSub<A>): Effect.Effect<void> => self.awaitShutdown\n\n/** @internal */\nexport const publish = dual<\n  <A>(value: A) => (self: PubSub.PubSub<A>) => Effect.Effect<boolean>,\n  <A>(self: PubSub.PubSub<A>, value: A) => Effect.Effect<boolean>\n>(2, (self, value) => self.publish(value))\n\n/** @internal */\nexport const publishAll = dual<\n  <A>(elements: Iterable<A>) => (self: PubSub.PubSub<A>) => Effect.Effect<boolean>,\n  <A>(self: PubSub.PubSub<A>, elements: Iterable<A>) => Effect.Effect<boolean>\n>(2, (self, elements) => self.publishAll(elements))\n\n/** @internal */\nexport const subscribe = <A>(self: PubSub.PubSub<A>): Effect.Effect<Queue.Dequeue<A>, never, Scope.Scope> =>\n  self.subscribe\n\n/** @internal */\nconst makeBoundedPubSub = <A>(\n  capacity: number | {\n    readonly capacity: number\n    readonly replay?: number | undefined\n  }\n): AtomicPubSub<A> => {\n  const options = typeof capacity === \"number\" ? { capacity } : capacity\n  ensureCapacity(options.capacity)\n  const replayBuffer = options.replay && options.replay > 0 ? new ReplayBuffer<A>(Math.ceil(options.replay)) : undefined\n  if (options.capacity === 1) {\n    return new BoundedPubSubSingle(replayBuffer)\n  } else if (nextPow2(options.capacity) === options.capacity) {\n    return new BoundedPubSubPow2(options.capacity, replayBuffer)\n  } else {\n    return new BoundedPubSubArb(options.capacity, replayBuffer)\n  }\n}\n\n/** @internal */\nconst makeUnboundedPubSub = <A>(options?: {\n  readonly replay?: number | undefined\n}): AtomicPubSub<A> => new UnboundedPubSub(options?.replay ? new ReplayBuffer(options.replay) : undefined)\n\n/** @internal */\nconst makeSubscription = <A>(\n  pubsub: AtomicPubSub<A>,\n  subscribers: Subscribers<A>,\n  strategy: PubSubStrategy<A>\n): Effect.Effect<Queue.Dequeue<A>> =>\n  core.map(core.deferredMake<void>(), (deferred) =>\n    unsafeMakeSubscription(\n      pubsub,\n      subscribers,\n      pubsub.subscribe(),\n      MutableQueue.unbounded<Deferred.Deferred<A>>(),\n      deferred,\n      MutableRef.make(false),\n      strategy\n    ))\n\n/** @internal */\nexport const unsafeMakeSubscription = <A>(\n  pubsub: AtomicPubSub<A>,\n  subscribers: Subscribers<A>,\n  subscription: Subscription<A>,\n  pollers: MutableQueue.MutableQueue<Deferred.Deferred<A>>,\n  shutdownHook: Deferred.Deferred<void>,\n  shutdownFlag: MutableRef.MutableRef<boolean>,\n  strategy: PubSubStrategy<A>\n): Queue.Dequeue<A> =>\n  new SubscriptionImpl(\n    pubsub,\n    subscribers,\n    subscription,\n    pollers,\n    shutdownHook,\n    shutdownFlag,\n    strategy,\n    pubsub.replayWindow()\n  )\n\n/** @internal */\nclass BoundedPubSubArb<in out A> implements AtomicPubSub<A> {\n  array: Array<A>\n  publisherIndex = 0\n  subscribers: Array<number>\n  subscriberCount = 0\n  subscribersIndex = 0\n\n  constructor(readonly capacity: number, readonly replayBuffer: ReplayBuffer<A> | undefined) {\n    this.array = Array.from({ length: capacity })\n    this.subscribers = Array.from({ length: capacity })\n  }\n\n  replayWindow(): ReplayWindow<A> {\n    return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow\n  }\n\n  isEmpty(): boolean {\n    return this.publisherIndex === this.subscribersIndex\n  }\n\n  isFull(): boolean {\n    return this.publisherIndex === this.subscribersIndex + this.capacity\n  }\n\n  size(): number {\n    return this.publisherIndex - this.subscribersIndex\n  }\n\n  publish(value: A): boolean {\n    if (this.isFull()) {\n      return false\n    }\n    if (this.subscriberCount !== 0) {\n      const index = this.publisherIndex % this.capacity\n      this.array[index] = value\n      this.subscribers[index] = this.subscriberCount\n      this.publisherIndex += 1\n    }\n    if (this.replayBuffer) {\n      this.replayBuffer.offer(value)\n    }\n    return true\n  }\n\n  publishAll(elements: Iterable<A>): Chunk.Chunk<A> {\n    if (this.subscriberCount === 0) {\n      if (this.replayBuffer) {\n        this.replayBuffer.offerAll(elements)\n      }\n      return Chunk.empty()\n    }\n    const chunk = Chunk.fromIterable(elements)\n    const n = chunk.length\n    const size = this.publisherIndex - this.subscribersIndex\n    const available = this.capacity - size\n    const forPubSub = Math.min(n, available)\n    if (forPubSub === 0) {\n      return chunk\n    }\n    let iteratorIndex = 0\n    const publishAllIndex = this.publisherIndex + forPubSub\n    while (this.publisherIndex !== publishAllIndex) {\n      const a = Chunk.unsafeGet(chunk, iteratorIndex++)\n      const index = this.publisherIndex % this.capacity\n      this.array[index] = a\n      this.subscribers[index] = this.subscriberCount\n      this.publisherIndex += 1\n      if (this.replayBuffer) {\n        this.replayBuffer.offer(a)\n      }\n    }\n    return Chunk.drop(chunk, iteratorIndex)\n  }\n\n  slide(): void {\n    if (this.subscribersIndex !== this.publisherIndex) {\n      const index = this.subscribersIndex % this.capacity\n      this.array[index] = AbsentValue as unknown as A\n      this.subscribers[index] = 0\n      this.subscribersIndex += 1\n    }\n    if (this.replayBuffer) {\n      this.replayBuffer.slide()\n    }\n  }\n\n  subscribe(): Subscription<A> {\n    this.subscriberCount += 1\n    return new BoundedPubSubArbSubscription(this, this.publisherIndex, false)\n  }\n}\n\nclass BoundedPubSubArbSubscription<in out A> implements Subscription<A> {\n  constructor(\n    private self: BoundedPubSubArb<A>,\n    private subscriberIndex: number,\n    private unsubscribed: boolean\n  ) {\n  }\n\n  isEmpty(): boolean {\n    return (\n      this.unsubscribed ||\n      this.self.publisherIndex === this.subscriberIndex ||\n      this.self.publisherIndex === this.self.subscribersIndex\n    )\n  }\n\n  size() {\n    if (this.unsubscribed) {\n      return 0\n    }\n    return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex)\n  }\n\n  poll<D>(default_: D): A | D {\n    if (this.unsubscribed) {\n      return default_\n    }\n    this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)\n    if (this.subscriberIndex !== this.self.publisherIndex) {\n      const index = this.subscriberIndex % this.self.capacity\n      const elem = this.self.array[index]!\n      this.self.subscribers[index] -= 1\n      if (this.self.subscribers[index] === 0) {\n        this.self.array[index] = AbsentValue as unknown as A\n        this.self.subscribersIndex += 1\n      }\n      this.subscriberIndex += 1\n      return elem\n    }\n    return default_\n  }\n\n  pollUpTo(n: number): Chunk.Chunk<A> {\n    if (this.unsubscribed) {\n      return Chunk.empty()\n    }\n    this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)\n    const size = this.self.publisherIndex - this.subscriberIndex\n    const toPoll = Math.min(n, size)\n    if (toPoll <= 0) {\n      return Chunk.empty()\n    }\n    const builder: Array<A> = []\n    const pollUpToIndex = this.subscriberIndex + toPoll\n    while (this.subscriberIndex !== pollUpToIndex) {\n      const index = this.subscriberIndex % this.self.capacity\n      const a = this.self.array[index] as A\n      this.self.subscribers[index] -= 1\n      if (this.self.subscribers[index] === 0) {\n        this.self.array[index] = AbsentValue as unknown as A\n        this.self.subscribersIndex += 1\n      }\n      builder.push(a)\n      this.subscriberIndex += 1\n    }\n\n    return Chunk.fromIterable(builder)\n  }\n\n  unsubscribe(): void {\n    if (!this.unsubscribed) {\n      this.unsubscribed = true\n      this.self.subscriberCount -= 1\n      this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)\n      while (this.subscriberIndex !== this.self.publisherIndex) {\n        const index = this.subscriberIndex % this.self.capacity\n        this.self.subscribers[index] -= 1\n        if (this.self.subscribers[index] === 0) {\n          this.self.array[index] = AbsentValue as unknown as A\n          this.self.subscribersIndex += 1\n        }\n        this.subscriberIndex += 1\n      }\n    }\n  }\n}\n\n/** @internal */\nclass BoundedPubSubPow2<in out A> implements AtomicPubSub<A> {\n  array: Array<A>\n  mask: number\n  publisherIndex = 0\n  subscribers: Array<number>\n  subscriberCount = 0\n  subscribersIndex = 0\n\n  constructor(readonly capacity: number, readonly replayBuffer: ReplayBuffer<A> | undefined) {\n    this.array = Array.from({ length: capacity })\n    this.mask = capacity - 1\n    this.subscribers = Array.from({ length: capacity })\n  }\n\n  replayWindow(): ReplayWindow<A> {\n    return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow\n  }\n\n  isEmpty(): boolean {\n    return this.publisherIndex === this.subscribersIndex\n  }\n\n  isFull(): boolean {\n    return this.publisherIndex === this.subscribersIndex + this.capacity\n  }\n\n  size(): number {\n    return this.publisherIndex - this.subscribersIndex\n  }\n\n  publish(value: A): boolean {\n    if (this.isFull()) {\n      return false\n    }\n    if (this.subscriberCount !== 0) {\n      const index = this.publisherIndex & this.mask\n      this.array[index] = value\n      this.subscribers[index] = this.subscriberCount\n      this.publisherIndex += 1\n    }\n    if (this.replayBuffer) {\n      this.replayBuffer.offer(value)\n    }\n    return true\n  }\n\n  publishAll(elements: Iterable<A>): Chunk.Chunk<A> {\n    if (this.subscriberCount === 0) {\n      if (this.replayBuffer) {\n        this.replayBuffer.offerAll(elements)\n      }\n      return Chunk.empty()\n    }\n    const chunk = Chunk.fromIterable(elements)\n    const n = chunk.length\n    const size = this.publisherIndex - this.subscribersIndex\n    const available = this.capacity - size\n    const forPubSub = Math.min(n, available)\n    if (forPubSub === 0) {\n      return chunk\n    }\n    let iteratorIndex = 0\n    const publishAllIndex = this.publisherIndex + forPubSub\n    while (this.publisherIndex !== publishAllIndex) {\n      const elem = Chunk.unsafeGet(chunk, iteratorIndex++)\n      const index = this.publisherIndex & this.mask\n      this.array[index] = elem\n      this.subscribers[index] = this.subscriberCount\n      this.publisherIndex += 1\n      if (this.replayBuffer) {\n        this.replayBuffer.offer(elem)\n      }\n    }\n    return Chunk.drop(chunk, iteratorIndex)\n  }\n\n  slide(): void {\n    if (this.subscribersIndex !== this.publisherIndex) {\n      const index = this.subscribersIndex & this.mask\n      this.array[index] = AbsentValue as unknown as A\n      this.subscribers[index] = 0\n      this.subscribersIndex += 1\n    }\n    if (this.replayBuffer) {\n      this.replayBuffer.slide()\n    }\n  }\n\n  subscribe(): Subscription<A> {\n    this.subscriberCount += 1\n    return new BoundedPubSubPow2Subscription(this, this.publisherIndex, false)\n  }\n}\n\n/** @internal */\nclass BoundedPubSubPow2Subscription<in out A> implements Subscription<A> {\n  constructor(\n    private self: BoundedPubSubPow2<A>,\n    private subscriberIndex: number,\n    private unsubscribed: boolean\n  ) {\n  }\n\n  isEmpty(): boolean {\n    return (\n      this.unsubscribed ||\n      this.self.publisherIndex === this.subscriberIndex ||\n      this.self.publisherIndex === this.self.subscribersIndex\n    )\n  }\n\n  size() {\n    if (this.unsubscribed) {\n      return 0\n    }\n    return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex)\n  }\n\n  poll<D>(default_: D): A | D {\n    if (this.unsubscribed) {\n      return default_\n    }\n    this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)\n    if (this.subscriberIndex !== this.self.publisherIndex) {\n      const index = this.subscriberIndex & this.self.mask\n      const elem = this.self.array[index]!\n      this.self.subscribers[index] -= 1\n      if (this.self.subscribers[index] === 0) {\n        this.self.array[index] = AbsentValue as unknown as A\n        this.self.subscribersIndex += 1\n      }\n      this.subscriberIndex += 1\n      return elem\n    }\n    return default_\n  }\n\n  pollUpTo(n: number): Chunk.Chunk<A> {\n    if (this.unsubscribed) {\n      return Chunk.empty()\n    }\n    this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)\n    const size = this.self.publisherIndex - this.subscriberIndex\n    const toPoll = Math.min(n, size)\n    if (toPoll <= 0) {\n      return Chunk.empty()\n    }\n    const builder: Array<A> = []\n    const pollUpToIndex = this.subscriberIndex + toPoll\n    while (this.subscriberIndex !== pollUpToIndex) {\n      const index = this.subscriberIndex & this.self.mask\n      const elem = this.self.array[index] as A\n      this.self.subscribers[index] -= 1\n      if (this.self.subscribers[index] === 0) {\n        this.self.array[index] = AbsentValue as unknown as A\n        this.self.subscribersIndex += 1\n      }\n      builder.push(elem)\n      this.subscriberIndex += 1\n    }\n    return Chunk.fromIterable(builder)\n  }\n\n  unsubscribe(): void {\n    if (!this.unsubscribed) {\n      this.unsubscribed = true\n      this.self.subscriberCount -= 1\n      this.subscriberIndex = Math.max(this.subscriberIndex, this.self.subscribersIndex)\n      while (this.subscriberIndex !== this.self.publisherIndex) {\n        const index = this.subscriberIndex & this.self.mask\n        this.self.subscribers[index] -= 1\n        if (this.self.subscribers[index] === 0) {\n          this.self.array[index] = AbsentValue as unknown as A\n          this.self.subscribersIndex += 1\n        }\n        this.subscriberIndex += 1\n      }\n    }\n  }\n}\n\n/** @internal */\nclass BoundedPubSubSingle<in out A> implements AtomicPubSub<A> {\n  publisherIndex = 0\n  subscriberCount = 0\n  subscribers = 0\n  value: A = AbsentValue as unknown as A\n\n  readonly capacity = 1\n  constructor(readonly replayBuffer: ReplayBuffer<A> | undefined) {}\n\n  replayWindow(): ReplayWindow<A> {\n    return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n\n  isEmpty(): boolean {\n    return this.subscribers === 0\n  }\n\n  isFull(): boolean {\n    return !this.isEmpty()\n  }\n\n  size(): number {\n    return this.isEmpty() ? 0 : 1\n  }\n\n  publish(value: A): boolean {\n    if (this.isFull()) {\n      return false\n    }\n    if (this.subscriberCount !== 0) {\n      this.value = value\n      this.subscribers = this.subscriberCount\n      this.publisherIndex += 1\n    }\n    if (this.replayBuffer) {\n      this.replayBuffer.offer(value)\n    }\n    return true\n  }\n\n  publishAll(elements: Iterable<A>): Chunk.Chunk<A> {\n    if (this.subscriberCount === 0) {\n      if (this.replayBuffer) {\n        this.replayBuffer.offerAll(elements)\n      }\n      return Chunk.empty()\n    }\n    const chunk = Chunk.fromIterable(elements)\n    if (Chunk.isEmpty(chunk)) {\n      return chunk\n    }\n    if (this.publish(Chunk.unsafeHead(chunk))) {\n      return Chunk.drop(chunk, 1)\n    } else {\n      return chunk\n    }\n  }\n\n  slide(): void {\n    if (this.isFull()) {\n      this.subscribers = 0\n      this.value = AbsentValue as unknown as A\n    }\n    if (this.replayBuffer) {\n      this.replayBuffer.slide()\n    }\n  }\n\n  subscribe(): Subscription<A> {\n    this.subscriberCount += 1\n    return new BoundedPubSubSingleSubscription(this, this.publisherIndex, false)\n  }\n}\n\n/** @internal */\nclass BoundedPubSubSingleSubscription<in out A> implements Subscription<A> {\n  constructor(\n    private self: BoundedPubSubSingle<A>,\n    private subscriberIndex: number,\n    private unsubscribed: boolean\n  ) {\n  }\n\n  isEmpty(): boolean {\n    return (\n      this.unsubscribed ||\n      this.self.subscribers === 0 ||\n      this.subscriberIndex === this.self.publisherIndex\n    )\n  }\n\n  size() {\n    return this.isEmpty() ? 0 : 1\n  }\n\n  poll<D>(default_: D): A | D {\n    if (this.isEmpty()) {\n      return default_\n    }\n    const elem = this.self.value\n    this.self.subscribers -= 1\n    if (this.self.subscribers === 0) {\n      this.self.value = AbsentValue as unknown as A\n    }\n    this.subscriberIndex += 1\n    return elem\n  }\n\n  pollUpTo(n: number): Chunk.Chunk<A> {\n    if (this.isEmpty() || n < 1) {\n      return Chunk.empty()\n    }\n    const a = this.self.value\n    this.self.subscribers -= 1\n    if (this.self.subscribers === 0) {\n      this.self.value = AbsentValue as unknown as A\n    }\n    this.subscriberIndex += 1\n    return Chunk.of(a)\n  }\n\n  unsubscribe(): void {\n    if (!this.unsubscribed) {\n      this.unsubscribed = true\n      this.self.subscriberCount -= 1\n      if (this.subscriberIndex !== this.self.publisherIndex) {\n        this.self.subscribers -= 1\n        if (this.self.subscribers === 0) {\n          this.self.value = AbsentValue as unknown as A\n        }\n      }\n    }\n  }\n}\n\n/** @internal */\ninterface Node<out A> {\n  value: A | AbsentValue\n  subscribers: number\n  next: Node<A> | null\n}\n\n/** @internal */\nclass UnboundedPubSub<in out A> implements AtomicPubSub<A> {\n  publisherHead: Node<A> = {\n    value: AbsentValue,\n    subscribers: 0,\n    next: null\n  }\n  publisherTail = this.publisherHead\n  publisherIndex = 0\n  subscribersIndex = 0\n\n  readonly capacity = Number.MAX_SAFE_INTEGER\n  constructor(readonly replayBuffer: ReplayBuffer<A> | undefined) {}\n\n  replayWindow(): ReplayWindow<A> {\n    return this.replayBuffer ? new ReplayWindowImpl(this.replayBuffer) : emptyReplayWindow\n  }\n\n  isEmpty(): boolean {\n    return this.publisherHead === this.publisherTail\n  }\n\n  isFull(): boolean {\n    return false\n  }\n\n  size(): number {\n    return this.publisherIndex - this.subscribersIndex\n  }\n\n  publish(value: A): boolean {\n    const subscribers = this.publisherTail.subscribers\n    if (subscribers !== 0) {\n      this.publisherTail.next = {\n        value,\n        subscribers,\n        next: null\n      }\n      this.publisherTail = this.publisherTail.next\n      this.publisherIndex += 1\n    }\n    if (this.replayBuffer) {\n      this.replayBuffer.offer(value)\n    }\n    return true\n  }\n\n  publishAll(elements: Iterable<A>): Chunk.Chunk<A> {\n    if (this.publisherTail.subscribers !== 0) {\n      for (const a of elements) {\n        this.publish(a)\n      }\n    } else if (this.replayBuffer) {\n      this.replayBuffer.offerAll(elements)\n    }\n    return Chunk.empty()\n  }\n\n  slide(): void {\n    if (this.publisherHead !== this.publisherTail) {\n      this.publisherHead = this.publisherHead.next!\n      this.publisherHead.value = AbsentValue\n      this.subscribersIndex += 1\n    }\n    if (this.replayBuffer) {\n      this.replayBuffer.slide()\n    }\n  }\n\n  subscribe(): Subscription<A> {\n    this.publisherTail.subscribers += 1\n    return new UnboundedPubSubSubscription(\n      this,\n      this.publisherTail,\n      this.publisherIndex,\n      false\n    )\n  }\n}\n\n/** @internal */\nclass UnboundedPubSubSubscription<in out A> implements Subscription<A> {\n  constructor(\n    private self: UnboundedPubSub<A>,\n    private subscriberHead: Node<A>,\n    private subscriberIndex: number,\n    private unsubscribed: boolean\n  ) {\n  }\n\n  isEmpty(): boolean {\n    if (this.unsubscribed) {\n      return true\n    }\n    let empty = true\n    let loop = true\n    while (loop) {\n      if (this.subscriberHead === this.self.publisherTail) {\n        loop = false\n      } else {\n        if (this.subscriberHead.next!.value !== AbsentValue) {\n          empty = false\n          loop = false\n        } else {\n          this.subscriberHead = this.subscriberHead.next!\n          this.subscriberIndex += 1\n        }\n      }\n    }\n    return empty\n  }\n\n  size() {\n    if (this.unsubscribed) {\n      return 0\n    }\n    return this.self.publisherIndex - Math.max(this.subscriberIndex, this.self.subscribersIndex)\n  }\n\n  poll<D>(default_: D): A | D {\n    if (this.unsubscribed) {\n      return default_\n    }\n    let loop = true\n    let polled: A | D = default_\n    while (loop) {\n      if (this.subscriberHead === this.self.publisherTail) {\n        loop = false\n      } else {\n        const elem = this.subscriberHead.next!.value\n        if (elem !== AbsentValue) {\n          polled = elem\n          this.subscriberHead.subscribers -= 1\n          if (this.subscriberHead.subscribers === 0) {\n            this.self.publisherHead = this.self.publisherHead.next!\n            this.self.publisherHead.value = AbsentValue\n            this.self.subscribersIndex += 1\n          }\n          loop = false\n        }\n        this.subscriberHead = this.subscriberHead.next!\n        this.subscriberIndex += 1\n      }\n    }\n    return polled\n  }\n\n  pollUpTo(n: number): Chunk.Chunk<A> {\n    const builder: Array<A> = []\n    const default_ = AbsentValue\n    let i = 0\n    while (i !== n) {\n      const a = this.poll(default_ as unknown as A)\n      if (a === default_) {\n        i = n\n      } else {\n        builder.push(a)\n        i += 1\n      }\n    }\n    return Chunk.fromIterable(builder)\n  }\n\n  unsubscribe(): void {\n    if (!this.unsubscribed) {\n      this.unsubscribed = true\n      this.self.publisherTail.subscribers -= 1\n      while (this.subscriberHead !== this.self.publisherTail) {\n        if (this.subscriberHead.next!.value !== AbsentValue) {\n          this.subscriberHead.subscribers -= 1\n          if (this.subscriberHead.subscribers === 0) {\n            this.self.publisherHead = this.self.publisherHead.next!\n            this.self.publisherHead.value = AbsentValue\n            this.self.subscribersIndex += 1\n          }\n        }\n        this.subscriberHead = this.subscriberHead.next!\n      }\n    }\n  }\n}\n\n/** @internal */\nclass SubscriptionImpl<in out A> extends Effectable.Class<A> implements Queue.Dequeue<A> {\n  [queue.DequeueTypeId] = queue.dequeueVariance\n\n  constructor(\n    readonly pubsub: AtomicPubSub<A>,\n    readonly subscribers: Subscribers<A>,\n    readonly subscription: Subscription<A>,\n    readonly pollers: MutableQueue.MutableQueue<Deferred.Deferred<A>>,\n    readonly shutdownHook: Deferred.Deferred<void>,\n    readonly shutdownFlag: MutableRef.MutableRef<boolean>,\n    readonly strategy: PubSubStrategy<A>,\n    readonly replayWindow: ReplayWindow<A>\n  ) {\n    super()\n  }\n\n  commit() {\n    return this.take\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n\n  capacity(): number {\n    return this.pubsub.capacity\n  }\n\n  isActive(): boolean {\n    return !MutableRef.get(this.shutdownFlag)\n  }\n\n  get size(): Effect.Effect<number> {\n    return core.suspend(() =>\n      MutableRef.get(this.shutdownFlag)\n        ? core.interrupt\n        : core.succeed(this.subscription.size() + this.replayWindow.remaining)\n    )\n  }\n\n  unsafeSize(): Option.Option<number> {\n    if (MutableRef.get(this.shutdownFlag)) {\n      return Option.none()\n    }\n    return Option.some(this.subscription.size() + this.replayWindow.remaining)\n  }\n\n  get isFull(): Effect.Effect<boolean> {\n    return core.suspend(() =>\n      MutableRef.get(this.shutdownFlag)\n        ? core.interrupt\n        : core.succeed(this.subscription.size() === this.capacity())\n    )\n  }\n\n  get isEmpty(): Effect.Effect<boolean> {\n    return core.map(this.size, (size) => size === 0)\n  }\n\n  get shutdown(): Effect.Effect<void> {\n    return core.uninterruptible(\n      core.withFiberRuntime<void>((state) => {\n        MutableRef.set(this.shutdownFlag, true)\n        return pipe(\n          fiberRuntime.forEachParUnbounded(\n            unsafePollAllQueue(this.pollers),\n            (d) => core.deferredInterruptWith(d, state.id()),\n            false\n          ),\n          core.zipRight(core.sync(() => {\n            this.subscribers.delete(this.subscription)\n            this.subscription.unsubscribe()\n            this.strategy.unsafeOnPubSubEmptySpace(this.pubsub, this.subscribers)\n          })),\n          core.whenEffect(core.deferredSucceed(this.shutdownHook, void 0)),\n          core.asVoid\n        )\n      })\n    )\n  }\n\n  get isShutdown(): Effect.Effect<boolean> {\n    return core.sync(() => MutableRef.get(this.shutdownFlag))\n  }\n\n  get awaitShutdown(): Effect.Effect<void> {\n    return core.deferredAwait(this.shutdownHook)\n  }\n\n  get take(): Effect.Effect<A> {\n    return core.withFiberRuntime((state) => {\n      if (MutableRef.get(this.shutdownFlag)) {\n        return core.interrupt\n      }\n      if (this.replayWindow.remaining > 0) {\n        const message = this.replayWindow.take()!\n        return core.succeed(message)\n      }\n      const message = MutableQueue.isEmpty(this.pollers)\n        ? this.subscription.poll(MutableQueue.EmptyMutableQueue)\n        : MutableQueue.EmptyMutableQueue\n      if (message === MutableQueue.EmptyMutableQueue) {\n        const deferred = core.deferredUnsafeMake<A>(state.id())\n        return pipe(\n          core.suspend(() => {\n            pipe(this.pollers, MutableQueue.offer(deferred))\n            pipe(this.subscribers, addSubscribers(this.subscription, this.pollers))\n            this.strategy.unsafeCompletePollers(\n              this.pubsub,\n              this.subscribers,\n              this.subscription,\n              this.pollers\n            )\n            return MutableRef.get(this.shutdownFlag) ? core.interrupt : core.deferredAwait(deferred)\n          }),\n          core.onInterrupt(() => core.sync(() => unsafeRemove(this.pollers, deferred)))\n        )\n      } else {\n        this.strategy.unsafeOnPubSubEmptySpace(this.pubsub, this.subscribers)\n        return core.succeed(message)\n      }\n    })\n  }\n\n  get takeAll(): Effect.Effect<Chunk.Chunk<A>> {\n    return core.suspend(() => {\n      if (MutableRef.get(this.shutdownFlag)) {\n        return core.interrupt\n      }\n      const as = MutableQueue.isEmpty(this.pollers)\n        ? unsafePollAllSubscription(this.subscription)\n        : Chunk.empty()\n      this.strategy.unsafeOnPubSubEmptySpace(this.pubsub, this.subscribers)\n      if (this.replayWindow.remaining > 0) {\n        return core.succeed(Chunk.appendAll(this.replayWindow.takeAll(), as))\n      }\n      return core.succeed(as)\n    })\n  }\n\n  takeUpTo(this: this, max: number): Effect.Effect<Chunk.Chunk<A>> {\n    return core.suspend(() => {\n      if (MutableRef.get(this.shutdownFlag)) {\n        return core.interrupt\n      }\n      let replay: Chunk.Chunk<A> | undefined = undefined\n      if (this.replayWindow.remaining >= max) {\n        const as = this.replayWindow.takeN(max)\n        return core.succeed(as)\n      } else if (this.replayWindow.remaining > 0) {\n        replay = this.replayWindow.takeAll()\n        max = max - replay.length\n      }\n      const as = MutableQueue.isEmpty(this.pollers)\n        ? unsafePollN(this.subscription, max)\n        : Chunk.empty()\n      this.strategy.unsafeOnPubSubEmptySpace(this.pubsub, this.subscribers)\n      return replay ? core.succeed(Chunk.appendAll(replay, as)) : core.succeed(as)\n    })\n  }\n\n  takeBetween(min: number, max: number): Effect.Effect<Chunk.Chunk<A>> {\n    return core.suspend(() => takeRemainderLoop(this, min, max, Chunk.empty()))\n  }\n}\n\n/** @internal */\nconst takeRemainderLoop = <A>(\n  self: Queue.Dequeue<A>,\n  min: number,\n  max: number,\n  acc: Chunk.Chunk<A>\n): Effect.Effect<Chunk.Chunk<A>> => {\n  if (max < min) {\n    return core.succeed(acc)\n  }\n  return pipe(\n    self.takeUpTo(max),\n    core.flatMap((bs) => {\n      const remaining = min - bs.length\n      if (remaining === 1) {\n        return pipe(self.take, core.map((b) => pipe(acc, Chunk.appendAll(bs), Chunk.append(b))))\n      }\n      if (remaining > 1) {\n        return pipe(\n          self.take,\n          core.flatMap((b) =>\n            takeRemainderLoop(\n              self,\n              remaining - 1,\n              max - bs.length - 1,\n              pipe(acc, Chunk.appendAll(bs), Chunk.append(b))\n            )\n          )\n        )\n      }\n      return core.succeed(pipe(acc, Chunk.appendAll(bs)))\n    })\n  )\n}\n\n/** @internal */\nclass PubSubImpl<in out A> implements PubSub.PubSub<A> {\n  readonly [queue.EnqueueTypeId] = queue.enqueueVariance\n  readonly [queue.DequeueTypeId] = queue.dequeueVariance\n\n  constructor(\n    readonly pubsub: AtomicPubSub<A>,\n    readonly subscribers: Subscribers<A>,\n    readonly scope: Scope.Scope.Closeable,\n    readonly shutdownHook: Deferred.Deferred<void>,\n    readonly shutdownFlag: MutableRef.MutableRef<boolean>,\n    readonly strategy: PubSubStrategy<A>\n  ) {}\n\n  capacity(): number {\n    return this.pubsub.capacity\n  }\n\n  get size(): Effect.Effect<number> {\n    return core.suspend(() =>\n      MutableRef.get(this.shutdownFlag) ?\n        core.interrupt :\n        core.sync(() => this.pubsub.size())\n    )\n  }\n\n  unsafeSize(): Option.Option<number> {\n    if (MutableRef.get(this.shutdownFlag)) {\n      return Option.none()\n    }\n    return Option.some(this.pubsub.size())\n  }\n\n  get isFull(): Effect.Effect<boolean> {\n    return core.map(this.size, (size) => size === this.capacity())\n  }\n\n  get isEmpty(): Effect.Effect<boolean> {\n    return core.map(this.size, (size) => size === 0)\n  }\n\n  get awaitShutdown(): Effect.Effect<void> {\n    return core.deferredAwait(this.shutdownHook)\n  }\n\n  get isShutdown(): Effect.Effect<boolean> {\n    return core.sync(() => MutableRef.get(this.shutdownFlag))\n  }\n\n  get shutdown(): Effect.Effect<void> {\n    return core.uninterruptible(core.withFiberRuntime((state) => {\n      pipe(this.shutdownFlag, MutableRef.set(true))\n      return pipe(\n        this.scope.close(core.exitInterrupt(state.id())),\n        core.zipRight(this.strategy.shutdown),\n        core.whenEffect(core.deferredSucceed(this.shutdownHook, void 0)),\n        core.asVoid\n      )\n    }))\n  }\n\n  publish(value: A): Effect.Effect<boolean> {\n    return core.suspend(() => {\n      if (MutableRef.get(this.shutdownFlag)) {\n        return core.interrupt\n      }\n\n      if (this.pubsub.publish(value)) {\n        this.strategy.unsafeCompleteSubscribers(this.pubsub, this.subscribers)\n        return core.succeed(true)\n      }\n\n      return this.strategy.handleSurplus(\n        this.pubsub,\n        this.subscribers,\n        Chunk.of(value),\n        this.shutdownFlag\n      )\n    })\n  }\n\n  isActive(): boolean {\n    return !MutableRef.get(this.shutdownFlag)\n  }\n\n  unsafeOffer(value: A): boolean {\n    if (MutableRef.get(this.shutdownFlag)) {\n      return false\n    }\n\n    if ((this.pubsub as AtomicPubSub<unknown>).publish(value)) {\n      this.strategy.unsafeCompleteSubscribers(this.pubsub, this.subscribers)\n      return true\n    }\n\n    return false\n  }\n\n  publishAll(elements: Iterable<A>): Effect.Effect<boolean> {\n    return core.suspend(() => {\n      if (MutableRef.get(this.shutdownFlag)) {\n        return core.interrupt\n      }\n      const surplus = unsafePublishAll(this.pubsub, elements)\n      this.strategy.unsafeCompleteSubscribers(this.pubsub, this.subscribers)\n      if (Chunk.isEmpty(surplus)) {\n        return core.succeed(true)\n      }\n      return this.strategy.handleSurplus(\n        this.pubsub,\n        this.subscribers,\n        surplus,\n        this.shutdownFlag\n      )\n    })\n  }\n\n  get subscribe(): Effect.Effect<Queue.Dequeue<A>, never, Scope.Scope> {\n    const acquire = core.tap(\n      fiberRuntime.all([\n        this.scope.fork(executionStrategy.sequential),\n        makeSubscription(this.pubsub, this.subscribers, this.strategy)\n      ]),\n      (tuple) => tuple[0].addFinalizer(() => tuple[1].shutdown)\n    )\n    return core.map(\n      fiberRuntime.acquireRelease(acquire, (tuple, exit) => tuple[0].close(exit)),\n      (tuple) => tuple[1]\n    )\n  }\n\n  offer(value: A): Effect.Effect<boolean> {\n    return this.publish(value)\n  }\n\n  offerAll(elements: Iterable<A>): Effect.Effect<boolean> {\n    return this.publishAll(elements)\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const makePubSub = <A>(\n  pubsub: AtomicPubSub<A>,\n  strategy: PubSubStrategy<A>\n): Effect.Effect<PubSub.PubSub<A>> =>\n  core.flatMap(\n    fiberRuntime.scopeMake(),\n    (scope) =>\n      core.map(core.deferredMake<void>(), (deferred) =>\n        unsafeMakePubSub(\n          pubsub,\n          new Map(),\n          scope,\n          deferred,\n          MutableRef.make(false),\n          strategy\n        ))\n  )\n\n/** @internal */\nexport const unsafeMakePubSub = <A>(\n  pubsub: AtomicPubSub<A>,\n  subscribers: Subscribers<A>,\n  scope: Scope.Scope.Closeable,\n  shutdownHook: Deferred.Deferred<void>,\n  shutdownFlag: MutableRef.MutableRef<boolean>,\n  strategy: PubSubStrategy<A>\n): PubSub.PubSub<A> => new PubSubImpl(pubsub, subscribers, scope, shutdownHook, shutdownFlag, strategy)\n\n/** @internal */\nconst ensureCapacity = (capacity: number): void => {\n  if (capacity <= 0) {\n    throw new core.InvalidPubSubCapacityException(`Cannot construct PubSub with capacity of ${capacity}`)\n  }\n}\n\n/** @internal */\nconst unsafeCompleteDeferred = <A>(deferred: Deferred.Deferred<A>, a: A): void => {\n  core.deferredUnsafeDone(deferred, core.succeed(a))\n}\n\n/** @internal */\nconst unsafeOfferAll = <A>(queue: MutableQueue.MutableQueue<A>, as: Iterable<A>): Chunk.Chunk<A> => {\n  return pipe(queue, MutableQueue.offerAll(as))\n}\n\n/** @internal */\nconst unsafePollAllQueue = <A>(queue: MutableQueue.MutableQueue<A>): Chunk.Chunk<A> => {\n  return pipe(queue, MutableQueue.pollUpTo(Number.POSITIVE_INFINITY))\n}\n\n/** @internal */\nconst unsafePollAllSubscription = <A>(subscription: Subscription<A>): Chunk.Chunk<A> => {\n  return subscription.pollUpTo(Number.POSITIVE_INFINITY)\n}\n\n/** @internal */\nconst unsafePollN = <A>(subscription: Subscription<A>, max: number): Chunk.Chunk<A> => {\n  return subscription.pollUpTo(max)\n}\n\n/** @internal */\nconst unsafePublishAll = <A>(pubsub: AtomicPubSub<A>, as: Iterable<A>): Chunk.Chunk<A> => {\n  return pubsub.publishAll(as)\n}\n\n/** @internal */\nconst unsafeRemove = <A>(queue: MutableQueue.MutableQueue<A>, value: A): void => {\n  unsafeOfferAll(\n    queue,\n    pipe(unsafePollAllQueue(queue), Chunk.filter((elem) => elem !== value))\n  )\n}\n\n// -----------------------------------------------------------------------------\n// PubSub.Strategy\n// -----------------------------------------------------------------------------\n\n/**\n * A `PubSubStrategy<A>` describes the protocol for how publishers and subscribers\n * will communicate with each other through the `PubSub`.\n *\n * @internal\n */\nexport interface PubSubStrategy<in out A> {\n  /**\n   * Describes any finalization logic associated with this strategy.\n   */\n  readonly shutdown: Effect.Effect<void>\n\n  /**\n   * Describes how publishers should signal to subscribers that they are\n   * waiting for space to become available in the `PubSub`.\n   */\n  handleSurplus(\n    pubsub: AtomicPubSub<A>,\n    subscribers: Subscribers<A>,\n    elements: Iterable<A>,\n    isShutdown: MutableRef.MutableRef<boolean>\n  ): Effect.Effect<boolean>\n\n  /**\n   * Describes how subscribers should signal to publishers waiting for space\n   * to become available in the `PubSub` that space may be available.\n   */\n  unsafeOnPubSubEmptySpace(\n    pubsub: AtomicPubSub<A>,\n    subscribers: Subscribers<A>\n  ): void\n\n  /**\n   * Describes how subscribers waiting for additional values from the `PubSub`\n   * should take those values and signal to publishers that they are no\n   * longer waiting for additional values.\n   */\n  unsafeCompletePollers(\n    pubsub: AtomicPubSub<A>,\n    subscribers: Subscribers<A>,\n    subscription: Subscription<A>,\n    pollers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n  ): void\n\n  /**\n   * Describes how publishers should signal to subscribers waiting for\n   * additional values from the `PubSub` that new values are available.\n   */\n  unsafeCompleteSubscribers(\n    pubsub: AtomicPubSub<A>,\n    subscribers: Subscribers<A>\n  ): void\n}\n\n/**\n * A strategy that applies back pressure to publishers when the `PubSub` is at\n * capacity. This guarantees that all subscribers will receive all messages\n * published to the `PubSub` while they are subscribed. However, it creates the\n * risk that a slow subscriber will slow down the rate at which messages\n * are published and received by other subscribers.\n *\n * @internal\n */\nclass BackPressureStrategy<in out A> implements PubSubStrategy<A> {\n  publishers: MutableQueue.MutableQueue<\n    readonly [A, Deferred.Deferred<boolean>, boolean]\n  > = MutableQueue.unbounded()\n\n  get shutdown(): Effect.Effect<void> {\n    return core.flatMap(core.fiberId, (fiberId) =>\n      core.flatMap(\n        core.sync(() => unsafePollAllQueue(this.publishers)),\n        (publishers) =>\n          fiberRuntime.forEachConcurrentDiscard(\n            publishers,\n            ([_, deferred, last]) =>\n              last ?\n                pipe(core.deferredInterruptWith(deferred, fiberId), core.asVoid) :\n                core.void,\n            false,\n            false\n          )\n      ))\n  }\n\n  handleSurplus(\n    pubsub: AtomicPubSub<A>,\n    subscribers: Subscribers<A>,\n    elements: Iterable<A>,\n    isShutdown: MutableRef.MutableRef<boolean>\n  ): Effect.Effect<boolean> {\n    return core.withFiberRuntime((state) => {\n      const deferred = core.deferredUnsafeMake<boolean>(state.id())\n      return pipe(\n        core.suspend(() => {\n          this.unsafeOffer(elements, deferred)\n          this.unsafeOnPubSubEmptySpace(pubsub, subscribers)\n          this.unsafeCompleteSubscribers(pubsub, subscribers)\n          return MutableRef.get(isShutdown) ?\n            core.interrupt :\n            core.deferredAwait(deferred)\n        }),\n        core.onInterrupt(() => core.sync(() => this.unsafeRemove(deferred)))\n      )\n    })\n  }\n\n  unsafeOnPubSubEmptySpace(\n    pubsub: AtomicPubSub<A>,\n    subscribers: Subscribers<A>\n  ): void {\n    let keepPolling = true\n    while (keepPolling && !pubsub.isFull()) {\n      const publisher = pipe(this.publishers, MutableQueue.poll(MutableQueue.EmptyMutableQueue))\n      if (publisher === MutableQueue.EmptyMutableQueue) {\n        keepPolling = false\n      } else {\n        const published = pubsub.publish(publisher[0])\n        if (published && publisher[2]) {\n          unsafeCompleteDeferred(publisher[1], true)\n        } else if (!published) {\n          unsafeOfferAll(\n            this.publishers,\n            pipe(unsafePollAllQueue(this.publishers), Chunk.prepend(publisher))\n          )\n        }\n        this.unsafeCompleteSubscribers(pubsub, subscribers)\n      }\n    }\n  }\n\n  unsafeCompletePollers(\n    pubsub: AtomicPubSub<A>,\n    subscribers: Subscribers<A>,\n    subscription: Subscription<A>,\n    pollers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n  ): void {\n    return unsafeStrategyCompletePollers(this, pubsub, subscribers, subscription, pollers)\n  }\n\n  unsafeCompleteSubscribers(pubsub: AtomicPubSub<A>, subscribers: Subscribers<A>): void {\n    return unsafeStrategyCompleteSubscribers(this, pubsub, subscribers)\n  }\n\n  private unsafeOffer(elements: Iterable<A>, deferred: Deferred.Deferred<boolean>): void {\n    const iterator = elements[Symbol.iterator]()\n    let next: IteratorResult<A> = iterator.next()\n    if (!next.done) {\n      // eslint-disable-next-line no-constant-condition\n      while (1) {\n        const value = next.value\n        next = iterator.next()\n        if (next.done) {\n          pipe(\n            this.publishers,\n            MutableQueue.offer([value, deferred, true as boolean] as const)\n          )\n          break\n        }\n        pipe(\n          this.publishers,\n          MutableQueue.offer([value, deferred, false as boolean] as const)\n        )\n      }\n    }\n  }\n\n  unsafeRemove(deferred: Deferred.Deferred<boolean>): void {\n    unsafeOfferAll(\n      this.publishers,\n      pipe(unsafePollAllQueue(this.publishers), Chunk.filter(([_, a]) => a !== deferred))\n    )\n  }\n}\n\n/**\n * A strategy that drops new messages when the `PubSub` is at capacity. This\n * guarantees that a slow subscriber will not slow down the rate at which\n * messages are published. However, it creates the risk that a slow\n * subscriber will slow down the rate at which messages are received by\n * other subscribers and that subscribers may not receive all messages\n * published to the `PubSub` while they are subscribed.\n *\n * @internal\n */\nexport class DroppingStrategy<in out A> implements PubSubStrategy<A> {\n  get shutdown(): Effect.Effect<void> {\n    return core.void\n  }\n\n  handleSurplus(\n    _pubsub: AtomicPubSub<A>,\n    _subscribers: Subscribers<A>,\n    _elements: Iterable<A>,\n    _isShutdown: MutableRef.MutableRef<boolean>\n  ): Effect.Effect<boolean> {\n    return core.succeed(false)\n  }\n\n  unsafeOnPubSubEmptySpace(\n    _pubsub: AtomicPubSub<A>,\n    _subscribers: Subscribers<A>\n  ): void {\n    //\n  }\n\n  unsafeCompletePollers(\n    pubsub: AtomicPubSub<A>,\n    subscribers: Subscribers<A>,\n    subscription: Subscription<A>,\n    pollers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n  ): void {\n    return unsafeStrategyCompletePollers(this, pubsub, subscribers, subscription, pollers)\n  }\n\n  unsafeCompleteSubscribers(pubsub: AtomicPubSub<A>, subscribers: Subscribers<A>): void {\n    return unsafeStrategyCompleteSubscribers(this, pubsub, subscribers)\n  }\n}\n\n/**\n * A strategy that adds new messages and drops old messages when the `PubSub` is\n * at capacity. This guarantees that a slow subscriber will not slow down\n * the rate at which messages are published and received by other\n * subscribers. However, it creates the risk that a slow subscriber will\n * not receive some messages published to the `PubSub` while it is subscribed.\n *\n * @internal\n */\nexport class SlidingStrategy<in out A> implements PubSubStrategy<A> {\n  get shutdown(): Effect.Effect<void> {\n    return core.void\n  }\n\n  handleSurplus(\n    pubsub: AtomicPubSub<A>,\n    subscribers: Subscribers<A>,\n    elements: Iterable<A>,\n    _isShutdown: MutableRef.MutableRef<boolean>\n  ): Effect.Effect<boolean> {\n    return core.sync(() => {\n      this.unsafeSlidingPublish(pubsub, elements)\n      this.unsafeCompleteSubscribers(pubsub, subscribers)\n      return true\n    })\n  }\n\n  unsafeOnPubSubEmptySpace(\n    _pubsub: AtomicPubSub<A>,\n    _subscribers: Subscribers<A>\n  ): void {\n    //\n  }\n\n  unsafeCompletePollers(\n    pubsub: AtomicPubSub<A>,\n    subscribers: Subscribers<A>,\n    subscription: Subscription<A>,\n    pollers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n  ): void {\n    return unsafeStrategyCompletePollers(this, pubsub, subscribers, subscription, pollers)\n  }\n\n  unsafeCompleteSubscribers(pubsub: AtomicPubSub<A>, subscribers: Subscribers<A>): void {\n    return unsafeStrategyCompleteSubscribers(this, pubsub, subscribers)\n  }\n\n  unsafeSlidingPublish(pubsub: AtomicPubSub<A>, elements: Iterable<A>): void {\n    const it = elements[Symbol.iterator]()\n    let next = it.next()\n    if (!next.done && pubsub.capacity > 0) {\n      let a = next.value\n      let loop = true\n      while (loop) {\n        pubsub.slide()\n        const pub = pubsub.publish(a)\n        if (pub && (next = it.next()) && !next.done) {\n          a = next.value\n        } else if (pub) {\n          loop = false\n        }\n      }\n    }\n  }\n}\n\n/** @internal */\nconst unsafeStrategyCompletePollers = <A>(\n  strategy: PubSubStrategy<A>,\n  pubsub: AtomicPubSub<A>,\n  subscribers: Subscribers<A>,\n  subscription: Subscription<A>,\n  pollers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n): void => {\n  let keepPolling = true\n  while (keepPolling && !subscription.isEmpty()) {\n    const poller = pipe(pollers, MutableQueue.poll(MutableQueue.EmptyMutableQueue))\n    if (poller === MutableQueue.EmptyMutableQueue) {\n      pipe(subscribers, removeSubscribers(subscription, pollers))\n      if (MutableQueue.isEmpty(pollers)) {\n        keepPolling = false\n      } else {\n        pipe(subscribers, addSubscribers(subscription, pollers))\n      }\n    } else {\n      const pollResult = subscription.poll(MutableQueue.EmptyMutableQueue)\n      if (pollResult === MutableQueue.EmptyMutableQueue) {\n        unsafeOfferAll(pollers, pipe(unsafePollAllQueue(pollers), Chunk.prepend(poller)))\n      } else {\n        unsafeCompleteDeferred(poller, pollResult)\n        strategy.unsafeOnPubSubEmptySpace(pubsub, subscribers)\n      }\n    }\n  }\n}\n\n/** @internal */\nconst unsafeStrategyCompleteSubscribers = <A>(\n  strategy: PubSubStrategy<A>,\n  pubsub: AtomicPubSub<A>,\n  subscribers: Subscribers<A>\n): void => {\n  for (\n    const [subscription, pollersSet] of subscribers\n  ) {\n    for (const pollers of pollersSet) {\n      strategy.unsafeCompletePollers(pubsub, subscribers, subscription, pollers)\n    }\n  }\n}\n\ninterface ReplayNode<A> {\n  value: A | AbsentValue\n  next: ReplayNode<A> | null\n}\n\nclass ReplayBuffer<A> {\n  constructor(readonly capacity: number) {}\n\n  head: ReplayNode<A> = { value: AbsentValue, next: null }\n  tail: ReplayNode<A> = this.head\n  size = 0\n  index = 0\n\n  slide() {\n    this.index++\n  }\n  offer(a: A): void {\n    this.tail.value = a\n    this.tail.next = {\n      value: AbsentValue,\n      next: null\n    }\n    this.tail = this.tail.next\n    if (this.size === this.capacity) {\n      this.head = this.head.next!\n    } else {\n      this.size += 1\n    }\n  }\n  offerAll(as: Iterable<A>): void {\n    for (const a of as) {\n      this.offer(a)\n    }\n  }\n}\n\ninterface ReplayWindow<A> {\n  take(): A | undefined\n  takeN(n: number): Chunk.Chunk<A>\n  takeAll(): Chunk.Chunk<A>\n  readonly remaining: number\n}\n\nclass ReplayWindowImpl<A> implements ReplayWindow<A> {\n  head: ReplayNode<A>\n  index: number\n  remaining: number\n  constructor(readonly buffer: ReplayBuffer<A>) {\n    this.index = buffer.index\n    this.remaining = buffer.size\n    this.head = buffer.head\n  }\n  fastForward() {\n    while (this.index < this.buffer.index) {\n      this.head = this.head.next!\n      this.index++\n    }\n  }\n  take(): A | undefined {\n    if (this.remaining === 0) {\n      return undefined\n    } else if (this.index < this.buffer.index) {\n      this.fastForward()\n    }\n    this.remaining--\n    const value = this.head.value\n    this.head = this.head.next!\n    return value as A\n  }\n  takeN(n: number): Chunk.Chunk<A> {\n    if (this.remaining === 0) {\n      return Chunk.empty()\n    } else if (this.index < this.buffer.index) {\n      this.fastForward()\n    }\n    const len = Math.min(n, this.remaining)\n    const items = new Array(len)\n    for (let i = 0; i < len; i++) {\n      const value = this.head.value as A\n      this.head = this.head.next!\n      items[i] = value\n    }\n    this.remaining -= len\n    return Chunk.unsafeFromArray(items)\n  }\n  takeAll(): Chunk.Chunk<A> {\n    return this.takeN(this.remaining)\n  }\n}\n\nconst emptyReplayWindow: ReplayWindow<never> = {\n  remaining: 0,\n  take: () => undefined,\n  takeN: () => Chunk.empty(),\n  takeAll: () => Chunk.empty()\n}\n"
  },
  {
    "path": "packages/effect/src/internal/query.ts",
    "content": "import type * as Cache from \"../Cache.js\"\nimport type { Deferred } from \"../Deferred.js\"\nimport { seconds } from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport { dual } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport type * as Request from \"../Request.js\"\nimport type * as RequestResolver from \"../RequestResolver.js\"\nimport * as BlockedRequests from \"./blockedRequests.js\"\nimport { unsafeMakeWith } from \"./cache.js\"\nimport * as core from \"./core.js\"\nimport { ensuring } from \"./fiberRuntime.js\"\nimport { Listeners } from \"./request.js\"\n\ntype RequestCache = Cache.Cache<Request.Request<any, any>, {\n  listeners: Request.Listeners\n  handle: Deferred<any, any>\n}>\n\n/** @internal */\nexport const currentCache = globalValue(\n  Symbol.for(\"effect/FiberRef/currentCache\"),\n  () =>\n    core.fiberRefUnsafeMake<RequestCache>(unsafeMakeWith<Request.Request<any, any>, {\n      listeners: Request.Listeners\n      handle: Deferred<any, any>\n    }>(\n      65536,\n      () => core.map(core.deferredMake<any, any>(), (handle) => ({ listeners: new Listeners(), handle })),\n      () => seconds(60)\n    ))\n)\n\n/** @internal */\nexport const currentCacheEnabled = globalValue(\n  Symbol.for(\"effect/FiberRef/currentCacheEnabled\"),\n  () => core.fiberRefUnsafeMake(false)\n)\n\n/** @internal */\nexport const fromRequest = <\n  A extends Request.Request<any, any>,\n  Ds extends\n    | RequestResolver.RequestResolver<A>\n    | Effect.Effect<RequestResolver.RequestResolver<A>, any, any>\n>(\n  request: A,\n  dataSource: Ds\n): Effect.Effect<\n  Request.Request.Success<A>,\n  Request.Request.Error<A>,\n  [Ds] extends [Effect.Effect<any, any, any>] ? Effect.Effect.Context<Ds> : never\n> =>\n  core.flatMap(\n    (core.isEffect(dataSource) ? dataSource : core.succeed(dataSource)) as Effect.Effect<\n      RequestResolver.RequestResolver<A>\n    >,\n    (ds) =>\n      core.fiberIdWith((id) => {\n        const proxy = new Proxy(request, {})\n        return core.fiberRefGetWith(currentCacheEnabled, (cacheEnabled) => {\n          if (cacheEnabled) {\n            const cached: Effect.Effect<any, any> = core.fiberRefGetWith(currentCache, (cache) =>\n              core.flatMap(cache.getEither(proxy), (orNew) => {\n                switch (orNew._tag) {\n                  case \"Left\": {\n                    if (orNew.left.listeners.interrupted) {\n                      return core.flatMap(\n                        cache.invalidateWhen(proxy, (entry) => entry.handle === orNew.left.handle),\n                        () => cached\n                      )\n                    }\n                    orNew.left.listeners.increment()\n                    return core.uninterruptibleMask((restore) =>\n                      core.flatMap(\n                        core.exit(core.blocked(\n                          BlockedRequests.empty,\n                          restore(core.deferredAwait(orNew.left.handle))\n                        )),\n                        (exit) => {\n                          orNew.left.listeners.decrement()\n                          return exit\n                        }\n                      )\n                    )\n                  }\n                  case \"Right\": {\n                    orNew.right.listeners.increment()\n                    return core.uninterruptibleMask((restore) =>\n                      core.flatMap(\n                        core.exit(\n                          core.blocked(\n                            BlockedRequests.single(\n                              ds as RequestResolver.RequestResolver<A>,\n                              BlockedRequests.makeEntry({\n                                request: proxy,\n                                result: orNew.right.handle,\n                                listeners: orNew.right.listeners,\n                                ownerId: id,\n                                state: { completed: false }\n                              })\n                            ),\n                            restore(core.deferredAwait(orNew.right.handle))\n                          )\n                        ),\n                        () => {\n                          orNew.right.listeners.decrement()\n                          return core.deferredAwait(orNew.right.handle)\n                        }\n                      )\n                    )\n                  }\n                }\n              }))\n            return cached\n          }\n          const listeners = new Listeners()\n          listeners.increment()\n          return core.flatMap(\n            core.deferredMake<Request.Request.Success<A>, Request.Request.Error<A>>(),\n            (ref) =>\n              ensuring(\n                core.blocked(\n                  BlockedRequests.single(\n                    ds as RequestResolver.RequestResolver<A>,\n                    BlockedRequests.makeEntry({\n                      request: proxy,\n                      result: ref,\n                      listeners,\n                      ownerId: id,\n                      state: { completed: false }\n                    })\n                  ),\n                  core.deferredAwait(ref)\n                ),\n                core.sync(() =>\n                  listeners.decrement()\n                )\n              )\n          )\n        })\n      })\n  )\n\n/** @internal */\nexport const cacheRequest = <A extends Request.Request<any, any>>(\n  request: A,\n  result: Request.Request.Result<A>\n): Effect.Effect<void> => {\n  return core.fiberRefGetWith(currentCacheEnabled, (cacheEnabled) => {\n    if (cacheEnabled) {\n      return core.fiberRefGetWith(currentCache, (cache) =>\n        core.flatMap(cache.getEither(request), (orNew) => {\n          switch (orNew._tag) {\n            case \"Left\": {\n              return core.void\n            }\n            case \"Right\": {\n              return core.deferredComplete(orNew.right.handle, result)\n            }\n          }\n        }))\n    }\n    return core.void\n  })\n}\n\n/** @internal */\nexport const withRequestCaching: {\n  (strategy: boolean): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    strategy: boolean\n  ): Effect.Effect<A, E, R>\n} = dual<\n  (\n    strategy: boolean\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    strategy: boolean\n  ) => Effect.Effect<A, E, R>\n>(2, (self, strategy) => core.fiberRefLocally(self, currentCacheEnabled, strategy))\n\n/** @internal */\nexport const withRequestCache: {\n  (cache: Request.Cache): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    cache: Request.Cache\n  ): Effect.Effect<A, E, R>\n} = dual<\n  (\n    cache: Request.Cache\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    cache: Request.Cache\n  ) => Effect.Effect<A, E, R>\n>(\n  2,\n  // @ts-expect-error\n  (self, cache) => core.fiberRefLocally(self, currentCache, cache)\n)\n"
  },
  {
    "path": "packages/effect/src/internal/queue.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport type * as Deferred from \"../Deferred.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Effectable from \"../Effectable.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport * as MutableQueue from \"../MutableQueue.js\"\nimport * as MutableRef from \"../MutableRef.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as Queue from \"../Queue.js\"\nimport * as core from \"./core.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\n\n/** @internal */\nconst EnqueueSymbolKey = \"effect/QueueEnqueue\"\n\n/** @internal */\nexport const EnqueueTypeId: Queue.EnqueueTypeId = Symbol.for(EnqueueSymbolKey) as Queue.EnqueueTypeId\n\n/** @internal */\nconst DequeueSymbolKey = \"effect/QueueDequeue\"\n\n/** @internal */\nexport const DequeueTypeId: Queue.DequeueTypeId = Symbol.for(DequeueSymbolKey) as Queue.DequeueTypeId\n\n/** @internal */\nconst QueueStrategySymbolKey = \"effect/QueueStrategy\"\n\n/** @internal */\nexport const QueueStrategyTypeId: Queue.QueueStrategyTypeId = Symbol.for(\n  QueueStrategySymbolKey\n) as Queue.QueueStrategyTypeId\n\n/** @internal */\nconst BackingQueueSymbolKey = \"effect/BackingQueue\"\n\n/** @internal */\nexport const BackingQueueTypeId: Queue.BackingQueueTypeId = Symbol.for(\n  BackingQueueSymbolKey\n) as Queue.BackingQueueTypeId\n\nconst queueStrategyVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\nconst backingQueueVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nexport const enqueueVariance = {\n  /* c8 ignore next */\n  _In: (_: unknown) => _\n}\n\n/** @internal */\nexport const dequeueVariance = {\n  /* c8 ignore next */\n  _Out: (_: never) => _\n}\n\n/** @internal */\nclass QueueImpl<in out A> extends Effectable.Class<A> implements Queue.Queue<A> {\n  readonly [EnqueueTypeId] = enqueueVariance\n  readonly [DequeueTypeId] = dequeueVariance\n\n  constructor(\n    /** @internal */\n    readonly queue: Queue.BackingQueue<A>,\n    /** @internal */\n    readonly takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>,\n    /** @internal */\n    readonly shutdownHook: Deferred.Deferred<void>,\n    /** @internal */\n    readonly shutdownFlag: MutableRef.MutableRef<boolean>,\n    /** @internal */\n    readonly strategy: Queue.Strategy<A>\n  ) {\n    super()\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n\n  commit() {\n    return this.take\n  }\n\n  capacity(): number {\n    return this.queue.capacity()\n  }\n\n  get size(): Effect.Effect<number> {\n    return core.suspend(() => core.catchAll(this.unsafeSize(), () => core.interrupt))\n  }\n\n  unsafeSize() {\n    if (MutableRef.get(this.shutdownFlag)) {\n      return Option.none<number>()\n    }\n    return Option.some(\n      this.queue.length() -\n        MutableQueue.length(this.takers) +\n        this.strategy.surplusSize()\n    )\n  }\n\n  get isEmpty(): Effect.Effect<boolean> {\n    return core.map(this.size, (size) => size <= 0)\n  }\n\n  get isFull(): Effect.Effect<boolean> {\n    return core.map(this.size, (size) => size >= this.capacity())\n  }\n\n  get shutdown(): Effect.Effect<void> {\n    return core.uninterruptible(\n      core.withFiberRuntime((state) => {\n        pipe(this.shutdownFlag, MutableRef.set(true))\n        return pipe(\n          fiberRuntime.forEachConcurrentDiscard(\n            unsafePollAll(this.takers),\n            (d) => core.deferredInterruptWith(d, state.id()),\n            false,\n            false\n          ),\n          core.zipRight(this.strategy.shutdown),\n          core.whenEffect(core.deferredSucceed(this.shutdownHook, void 0)),\n          core.asVoid\n        )\n      })\n    )\n  }\n\n  get isShutdown(): Effect.Effect<boolean> {\n    return core.sync(() => MutableRef.get(this.shutdownFlag))\n  }\n\n  get awaitShutdown(): Effect.Effect<void> {\n    return core.deferredAwait(this.shutdownHook)\n  }\n\n  isActive() {\n    return !MutableRef.get(this.shutdownFlag)\n  }\n\n  unsafeOffer(value: A): boolean {\n    if (MutableRef.get(this.shutdownFlag)) {\n      return false\n    }\n    let noRemaining: boolean\n    if (this.queue.length() === 0) {\n      const taker = pipe(\n        this.takers,\n        MutableQueue.poll(MutableQueue.EmptyMutableQueue)\n      )\n      if (taker !== MutableQueue.EmptyMutableQueue) {\n        unsafeCompleteDeferred(taker, value)\n        noRemaining = true\n      } else {\n        noRemaining = false\n      }\n    } else {\n      noRemaining = false\n    }\n    if (noRemaining) {\n      return true\n    }\n    // Not enough takers, offer to the queue\n    const succeeded = this.queue.offer(value)\n    unsafeCompleteTakers(this.strategy, this.queue, this.takers)\n    return succeeded\n  }\n\n  offer(value: A): Effect.Effect<boolean> {\n    return core.suspend(() => {\n      if (MutableRef.get(this.shutdownFlag)) {\n        return core.interrupt\n      }\n      let noRemaining: boolean\n      if (this.queue.length() === 0) {\n        const taker = pipe(\n          this.takers,\n          MutableQueue.poll(MutableQueue.EmptyMutableQueue)\n        )\n        if (taker !== MutableQueue.EmptyMutableQueue) {\n          unsafeCompleteDeferred(taker, value)\n          noRemaining = true\n        } else {\n          noRemaining = false\n        }\n      } else {\n        noRemaining = false\n      }\n      if (noRemaining) {\n        return core.succeed(true)\n      }\n      // Not enough takers, offer to the queue\n      const succeeded = this.queue.offer(value)\n      unsafeCompleteTakers(this.strategy, this.queue, this.takers)\n      return succeeded\n        ? core.succeed(true)\n        : this.strategy.handleSurplus([value], this.queue, this.takers, this.shutdownFlag)\n    })\n  }\n\n  offerAll(iterable: Iterable<A>): Effect.Effect<boolean> {\n    return core.suspend(() => {\n      if (MutableRef.get(this.shutdownFlag)) {\n        return core.interrupt\n      }\n      const values = Arr.fromIterable(iterable)\n      const pTakers = this.queue.length() === 0\n        ? Arr.fromIterable(unsafePollN(this.takers, values.length))\n        : Arr.empty\n      const [forTakers, remaining] = pipe(values, Arr.splitAt(pTakers.length))\n      for (let i = 0; i < pTakers.length; i++) {\n        const taker = (pTakers as any)[i]\n        const item = forTakers[i]\n        unsafeCompleteDeferred(taker, item)\n      }\n      if (remaining.length === 0) {\n        return core.succeed(true)\n      }\n      // Not enough takers, offer to the queue\n      const surplus = this.queue.offerAll(remaining)\n      unsafeCompleteTakers(this.strategy, this.queue, this.takers)\n      return Chunk.isEmpty(surplus)\n        ? core.succeed(true)\n        : this.strategy.handleSurplus(surplus, this.queue, this.takers, this.shutdownFlag)\n    })\n  }\n\n  get take(): Effect.Effect<A> {\n    return core.withFiberRuntime((state) => {\n      if (MutableRef.get(this.shutdownFlag)) {\n        return core.interrupt\n      }\n      const item = this.queue.poll(MutableQueue.EmptyMutableQueue)\n      if (item !== MutableQueue.EmptyMutableQueue) {\n        this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers)\n        return core.succeed(item)\n      } else {\n        // Add the deferred to takers, then:\n        // - Try to take again in case a value was added since\n        // - Wait for the deferred to be completed\n        // - Clean up resources in case of interruption\n        const deferred = core.deferredUnsafeMake<A>(state.id())\n        return pipe(\n          core.suspend(() => {\n            pipe(this.takers, MutableQueue.offer(deferred))\n            unsafeCompleteTakers(this.strategy, this.queue, this.takers)\n            return MutableRef.get(this.shutdownFlag) ?\n              core.interrupt :\n              core.deferredAwait(deferred)\n          }),\n          core.onInterrupt(() => {\n            return core.sync(() => unsafeRemove(this.takers, deferred))\n          })\n        )\n      }\n    })\n  }\n\n  get takeAll(): Effect.Effect<Chunk.Chunk<A>> {\n    return core.suspend(() => {\n      return MutableRef.get(this.shutdownFlag)\n        ? core.interrupt\n        : core.sync(() => {\n          const values = this.queue.pollUpTo(Number.POSITIVE_INFINITY)\n          this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers)\n          return Chunk.fromIterable(values)\n        })\n    })\n  }\n\n  takeUpTo(max: number): Effect.Effect<Chunk.Chunk<A>> {\n    return core.suspend(() =>\n      MutableRef.get(this.shutdownFlag)\n        ? core.interrupt\n        : core.sync(() => {\n          const values = this.queue.pollUpTo(max)\n          this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers)\n          return Chunk.fromIterable(values)\n        })\n    )\n  }\n\n  takeBetween(min: number, max: number): Effect.Effect<Chunk.Chunk<A>> {\n    return core.suspend(() =>\n      takeRemainderLoop(\n        this,\n        min,\n        max,\n        Chunk.empty()\n      )\n    )\n  }\n}\n\n/** @internal */\nconst takeRemainderLoop = <A>(\n  self: Queue.Dequeue<A>,\n  min: number,\n  max: number,\n  acc: Chunk.Chunk<A>\n): Effect.Effect<Chunk.Chunk<A>> => {\n  if (max < min) {\n    return core.succeed(acc)\n  }\n  return pipe(\n    takeUpTo(self, max),\n    core.flatMap((bs) => {\n      const remaining = min - bs.length\n      if (remaining === 1) {\n        return pipe(\n          take(self),\n          core.map((b) => pipe(acc, Chunk.appendAll(bs), Chunk.append(b)))\n        )\n      }\n      if (remaining > 1) {\n        return pipe(\n          take(self),\n          core.flatMap((b) =>\n            takeRemainderLoop(\n              self,\n              remaining - 1,\n              max - bs.length - 1,\n              pipe(acc, Chunk.appendAll(bs), Chunk.append(b))\n            )\n          )\n        )\n      }\n      return core.succeed(pipe(acc, Chunk.appendAll(bs)))\n    })\n  )\n}\n\n/** @internal */\nexport const isQueue = (u: unknown): u is Queue.Queue<unknown> => isEnqueue(u) && isDequeue(u)\n\n/** @internal */\nexport const isEnqueue = (u: unknown): u is Queue.Enqueue<unknown> => hasProperty(u, EnqueueTypeId)\n\n/** @internal */\nexport const isDequeue = (u: unknown): u is Queue.Dequeue<unknown> => hasProperty(u, DequeueTypeId)\n\n/** @internal */\nexport const bounded = <A>(requestedCapacity: number): Effect.Effect<Queue.Queue<A>> =>\n  pipe(\n    core.sync(() => MutableQueue.bounded<A>(requestedCapacity)),\n    core.flatMap((queue) => make(backingQueueFromMutableQueue(queue), backPressureStrategy()))\n  )\n\n/** @internal */\nexport const dropping = <A>(requestedCapacity: number): Effect.Effect<Queue.Queue<A>> =>\n  pipe(\n    core.sync(() => MutableQueue.bounded<A>(requestedCapacity)),\n    core.flatMap((queue) => make(backingQueueFromMutableQueue(queue), droppingStrategy()))\n  )\n\n/** @internal */\nexport const sliding = <A>(requestedCapacity: number): Effect.Effect<Queue.Queue<A>> =>\n  pipe(\n    core.sync(() => MutableQueue.bounded<A>(requestedCapacity)),\n    core.flatMap((queue) => make(backingQueueFromMutableQueue(queue), slidingStrategy()))\n  )\n\n/** @internal */\nexport const unbounded = <A>(): Effect.Effect<Queue.Queue<A>> =>\n  pipe(\n    core.sync(() => MutableQueue.unbounded<A>()),\n    core.flatMap((queue) => make(backingQueueFromMutableQueue(queue), droppingStrategy()))\n  )\n\n/** @internal */\nconst unsafeMake = <A>(\n  queue: Queue.BackingQueue<A>,\n  takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>,\n  shutdownHook: Deferred.Deferred<void>,\n  shutdownFlag: MutableRef.MutableRef<boolean>,\n  strategy: Queue.Strategy<A>\n): Queue.Queue<A> => {\n  return new QueueImpl(queue, takers, shutdownHook, shutdownFlag, strategy)\n}\n\n/** @internal */\nexport const make = <A>(\n  queue: Queue.BackingQueue<A>,\n  strategy: Queue.Strategy<A>\n): Effect.Effect<Queue.Queue<A>> =>\n  pipe(\n    core.deferredMake<void>(),\n    core.map((deferred) =>\n      unsafeMake(\n        queue,\n        MutableQueue.unbounded(),\n        deferred,\n        MutableRef.make(false),\n        strategy\n      )\n    )\n  )\n\n/** @internal */\nexport class BackingQueueFromMutableQueue<in out A> implements Queue.BackingQueue<A> {\n  readonly [BackingQueueTypeId] = backingQueueVariance\n  constructor(readonly mutable: MutableQueue.MutableQueue<A>) {}\n  poll<Def>(def: Def): A | Def {\n    return MutableQueue.poll(this.mutable, def)\n  }\n  pollUpTo(limit: number): Chunk.Chunk<A> {\n    return MutableQueue.pollUpTo(this.mutable, limit)\n  }\n  offerAll(elements: Iterable<A>): Chunk.Chunk<A> {\n    return MutableQueue.offerAll(this.mutable, elements)\n  }\n  offer(element: A): boolean {\n    return MutableQueue.offer(this.mutable, element)\n  }\n  capacity(): number {\n    return MutableQueue.capacity(this.mutable)\n  }\n  length(): number {\n    return MutableQueue.length(this.mutable)\n  }\n}\n\n/** @internal */\nexport const backingQueueFromMutableQueue = <A>(mutable: MutableQueue.MutableQueue<A>): Queue.BackingQueue<A> =>\n  new BackingQueueFromMutableQueue(mutable)\n\n/** @internal */\nexport const capacity = <A>(self: Queue.Dequeue<A> | Queue.Enqueue<A>): number => self.capacity()\n\n/** @internal */\nexport const size = <A>(self: Queue.Dequeue<A> | Queue.Enqueue<A>): Effect.Effect<number> => self.size\n\n/** @internal */\nexport const isFull = <A>(self: Queue.Dequeue<A> | Queue.Enqueue<A>): Effect.Effect<boolean> => self.isFull\n\n/** @internal */\nexport const isEmpty = <A>(self: Queue.Dequeue<A> | Queue.Enqueue<A>): Effect.Effect<boolean> => self.isEmpty\n\n/** @internal */\nexport const isShutdown = <A>(self: Queue.Dequeue<A> | Queue.Enqueue<A>): Effect.Effect<boolean> => self.isShutdown\n\n/** @internal */\nexport const awaitShutdown = <A>(self: Queue.Dequeue<A> | Queue.Enqueue<A>): Effect.Effect<void> => self.awaitShutdown\n\n/** @internal */\nexport const shutdown = <A>(self: Queue.Dequeue<A> | Queue.Enqueue<A>): Effect.Effect<void> => self.shutdown\n\n/** @internal */\nexport const offer = dual<\n  <A>(value: A) => (self: Queue.Enqueue<A>) => Effect.Effect<boolean>,\n  <A>(self: Queue.Enqueue<A>, value: A) => Effect.Effect<boolean>\n>(2, (self, value) => self.offer(value))\n\n/** @internal */\nexport const unsafeOffer = dual<\n  <A>(value: A) => (self: Queue.Enqueue<A>) => boolean,\n  <A>(self: Queue.Enqueue<A>, value: A) => boolean\n>(2, (self, value) => self.unsafeOffer(value))\n\n/** @internal */\nexport const offerAll = dual<\n  <A>(\n    iterable: Iterable<A>\n  ) => (self: Queue.Enqueue<A>) => Effect.Effect<boolean>,\n  <A>(\n    self: Queue.Enqueue<A>,\n    iterable: Iterable<A>\n  ) => Effect.Effect<boolean>\n>(2, (self, iterable) => self.offerAll(iterable))\n\n/** @internal */\nexport const poll = <A>(self: Queue.Dequeue<A>): Effect.Effect<Option.Option<A>> =>\n  core.map(self.takeUpTo(1), Chunk.head)\n\n/** @internal */\nexport const take = <A>(self: Queue.Dequeue<A>): Effect.Effect<A> => self.take\n\n/** @internal */\nexport const takeAll = <A>(self: Queue.Dequeue<A>): Effect.Effect<Chunk.Chunk<A>> => self.takeAll\n\n/** @internal */\nexport const takeUpTo = dual<\n  (max: number) => <A>(self: Queue.Dequeue<A>) => Effect.Effect<Chunk.Chunk<A>>,\n  <A>(self: Queue.Dequeue<A>, max: number) => Effect.Effect<Chunk.Chunk<A>>\n>(2, (self, max) => self.takeUpTo(max))\n\n/** @internal */\nexport const takeBetween = dual<\n  (min: number, max: number) => <A>(self: Queue.Dequeue<A>) => Effect.Effect<Chunk.Chunk<A>>,\n  <A>(self: Queue.Dequeue<A>, min: number, max: number) => Effect.Effect<Chunk.Chunk<A>>\n>(3, (self, min, max) => self.takeBetween(min, max))\n\n/** @internal */\nexport const takeN = dual<\n  (n: number) => <A>(self: Queue.Dequeue<A>) => Effect.Effect<Chunk.Chunk<A>>,\n  <A>(self: Queue.Dequeue<A>, n: number) => Effect.Effect<Chunk.Chunk<A>>\n>(2, (self, n) => self.takeBetween(n, n))\n\n// -----------------------------------------------------------------------------\n// Strategy\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const backPressureStrategy = <A>(): Queue.Strategy<A> => new BackPressureStrategy()\n\n/** @internal */\nexport const droppingStrategy = <A>(): Queue.Strategy<A> => new DroppingStrategy()\n\n/** @internal */\nexport const slidingStrategy = <A>(): Queue.Strategy<A> => new SlidingStrategy()\n\n/** @internal */\nclass BackPressureStrategy<in out A> implements Queue.Strategy<A> {\n  readonly [QueueStrategyTypeId] = queueStrategyVariance\n\n  readonly putters = MutableQueue.unbounded<readonly [A, Deferred.Deferred<boolean>, boolean]>()\n\n  surplusSize(): number {\n    return MutableQueue.length(this.putters)\n  }\n\n  onCompleteTakersWithEmptyQueue(takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>): void {\n    while (!MutableQueue.isEmpty(this.putters) && !MutableQueue.isEmpty(takers)) {\n      const taker = MutableQueue.poll(takers, void 0)!\n      const putter = MutableQueue.poll(this.putters, void 0)!\n      if (putter[2]) {\n        unsafeCompleteDeferred(putter[1], true)\n      }\n      unsafeCompleteDeferred(taker, putter[0])\n    }\n  }\n\n  get shutdown(): Effect.Effect<void> {\n    return pipe(\n      core.fiberId,\n      core.flatMap((fiberId) =>\n        pipe(\n          core.sync(() => unsafePollAll(this.putters)),\n          core.flatMap((putters) =>\n            fiberRuntime.forEachConcurrentDiscard(\n              putters,\n              ([_, deferred, isLastItem]) =>\n                isLastItem ?\n                  pipe(\n                    core.deferredInterruptWith(deferred, fiberId),\n                    core.asVoid\n                  ) :\n                  core.void,\n              false,\n              false\n            )\n          )\n        )\n      )\n    )\n  }\n\n  handleSurplus(\n    iterable: Iterable<A>,\n    queue: Queue.BackingQueue<A>,\n    takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>,\n    isShutdown: MutableRef.MutableRef<boolean>\n  ): Effect.Effect<boolean> {\n    return core.withFiberRuntime((state) => {\n      const deferred = core.deferredUnsafeMake<boolean>(state.id())\n      return pipe(\n        core.suspend(() => {\n          this.unsafeOffer(iterable, deferred)\n          this.unsafeOnQueueEmptySpace(queue, takers)\n          unsafeCompleteTakers(this, queue, takers)\n          return MutableRef.get(isShutdown) ? core.interrupt : core.deferredAwait(deferred)\n        }),\n        core.onInterrupt(() => core.sync(() => this.unsafeRemove(deferred)))\n      )\n    })\n  }\n\n  unsafeOnQueueEmptySpace(\n    queue: Queue.BackingQueue<A>,\n    takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n  ): void {\n    let keepPolling = true\n    while (keepPolling && (queue.capacity() === Number.POSITIVE_INFINITY || queue.length() < queue.capacity())) {\n      const putter = pipe(this.putters, MutableQueue.poll(MutableQueue.EmptyMutableQueue))\n      if (putter === MutableQueue.EmptyMutableQueue) {\n        keepPolling = false\n      } else {\n        const offered = queue.offer(putter[0])\n        if (offered && putter[2]) {\n          unsafeCompleteDeferred(putter[1], true)\n        } else if (!offered) {\n          unsafeOfferAll(this.putters, pipe(unsafePollAll(this.putters), Chunk.prepend(putter)))\n        }\n        unsafeCompleteTakers(this, queue, takers)\n      }\n    }\n  }\n\n  unsafeOffer(iterable: Iterable<A>, deferred: Deferred.Deferred<boolean>): void {\n    const stuff = Arr.fromIterable(iterable)\n    for (let i = 0; i < stuff.length; i++) {\n      const value = stuff[i]\n      if (i === stuff.length - 1) {\n        pipe(this.putters, MutableQueue.offer([value, deferred, true as boolean] as const))\n      } else {\n        pipe(this.putters, MutableQueue.offer([value, deferred, false as boolean] as const))\n      }\n    }\n  }\n\n  unsafeRemove(deferred: Deferred.Deferred<boolean>): void {\n    unsafeOfferAll(\n      this.putters,\n      pipe(unsafePollAll(this.putters), Chunk.filter(([, _]) => _ !== deferred))\n    )\n  }\n}\n\n/** @internal */\nclass DroppingStrategy<in out A> implements Queue.Strategy<A> {\n  readonly [QueueStrategyTypeId] = queueStrategyVariance\n\n  surplusSize(): number {\n    return 0\n  }\n\n  get shutdown(): Effect.Effect<void> {\n    return core.void\n  }\n\n  onCompleteTakersWithEmptyQueue(): void {\n  }\n\n  handleSurplus(\n    _iterable: Iterable<A>,\n    _queue: Queue.BackingQueue<A>,\n    _takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>,\n    _isShutdown: MutableRef.MutableRef<boolean>\n  ): Effect.Effect<boolean> {\n    return core.succeed(false)\n  }\n\n  unsafeOnQueueEmptySpace(\n    _queue: Queue.BackingQueue<A>,\n    _takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n  ): void {\n    //\n  }\n}\n\n/** @internal */\nclass SlidingStrategy<in out A> implements Queue.Strategy<A> {\n  readonly [QueueStrategyTypeId] = queueStrategyVariance\n\n  surplusSize(): number {\n    return 0\n  }\n\n  get shutdown(): Effect.Effect<void> {\n    return core.void\n  }\n\n  onCompleteTakersWithEmptyQueue(): void {\n  }\n\n  handleSurplus(\n    iterable: Iterable<A>,\n    queue: Queue.BackingQueue<A>,\n    takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>,\n    _isShutdown: MutableRef.MutableRef<boolean>\n  ): Effect.Effect<boolean> {\n    return core.sync(() => {\n      this.unsafeOffer(queue, iterable)\n      unsafeCompleteTakers(this, queue, takers)\n      return true\n    })\n  }\n\n  unsafeOnQueueEmptySpace(\n    _queue: Queue.BackingQueue<A>,\n    _takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n  ): void {\n    //\n  }\n\n  unsafeOffer(queue: Queue.BackingQueue<A>, iterable: Iterable<A>): void {\n    const iterator = iterable[Symbol.iterator]()\n    let next: IteratorResult<A>\n    let offering = true\n    while (!(next = iterator.next()).done && offering) {\n      if (queue.capacity() === 0) {\n        return\n      }\n      // Poll 1 and retry\n      queue.poll(MutableQueue.EmptyMutableQueue)\n      offering = queue.offer(next.value)\n    }\n  }\n}\n\n/** @internal */\nconst unsafeCompleteDeferred = <A>(deferred: Deferred.Deferred<A>, a: A): void => {\n  return core.deferredUnsafeDone(deferred, core.succeed(a))\n}\n\n/** @internal */\nconst unsafeOfferAll = <A>(queue: MutableQueue.MutableQueue<A>, as: Iterable<A>): Chunk.Chunk<A> => {\n  return pipe(queue, MutableQueue.offerAll(as))\n}\n\n/** @internal */\nconst unsafePollAll = <A>(queue: MutableQueue.MutableQueue<A>): Chunk.Chunk<A> => {\n  return pipe(queue, MutableQueue.pollUpTo(Number.POSITIVE_INFINITY))\n}\n\n/** @internal */\nconst unsafePollN = <A>(queue: MutableQueue.MutableQueue<A>, max: number): Chunk.Chunk<A> => {\n  return pipe(queue, MutableQueue.pollUpTo(max))\n}\n\n/** @internal */\nexport const unsafeRemove = <A>(queue: MutableQueue.MutableQueue<A>, a: A): void => {\n  unsafeOfferAll(\n    queue,\n    pipe(unsafePollAll(queue), Chunk.filter((b) => a !== b))\n  )\n}\n\n/** @internal */\nexport const unsafeCompleteTakers = <A>(\n  strategy: Queue.Strategy<A>,\n  queue: Queue.BackingQueue<A>,\n  takers: MutableQueue.MutableQueue<Deferred.Deferred<A>>\n): void => {\n  // Check both a taker and an item are in the queue, starting with the taker\n  let keepPolling = true\n  while (keepPolling && queue.length() !== 0) {\n    const taker = pipe(takers, MutableQueue.poll(MutableQueue.EmptyMutableQueue))\n    if (taker !== MutableQueue.EmptyMutableQueue) {\n      const element = queue.poll(MutableQueue.EmptyMutableQueue)\n      if (element !== MutableQueue.EmptyMutableQueue) {\n        unsafeCompleteDeferred(taker, element)\n        strategy.unsafeOnQueueEmptySpace(queue, takers)\n      } else {\n        unsafeOfferAll(takers, pipe(unsafePollAll(takers), Chunk.prepend(taker)))\n      }\n      keepPolling = true\n    } else {\n      keepPolling = false\n    }\n  }\n  if (keepPolling && queue.length() === 0 && !MutableQueue.isEmpty(takers)) {\n    strategy.onCompleteTakersWithEmptyQueue(takers)\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/random.ts",
    "content": "import type * as Arr from \"../Array.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport * as Context from \"../Context.js\"\nimport type * as Effect from \"../Effect.js\"\nimport { pipe } from \"../Function.js\"\nimport * as Hash from \"../Hash.js\"\nimport type * as Random from \"../Random.js\"\nimport * as PCGRandom from \"../Utils.js\"\nimport * as core from \"./core.js\"\n\n/** @internal */\nconst RandomSymbolKey = \"effect/Random\"\n\n/** @internal */\nexport const RandomTypeId: Random.RandomTypeId = Symbol.for(\n  RandomSymbolKey\n) as Random.RandomTypeId\n\n/** @internal */\nexport const randomTag: Context.Tag<Random.Random, Random.Random> = Context.GenericTag(\"effect/Random\")\n/** @internal */\nclass RandomImpl implements Random.Random {\n  readonly [RandomTypeId]: Random.RandomTypeId = RandomTypeId\n\n  readonly PRNG: PCGRandom.PCGRandom\n\n  constructor(readonly seed: number) {\n    this.PRNG = new PCGRandom.PCGRandom(seed)\n  }\n\n  get next(): Effect.Effect<number> {\n    return core.sync(() => this.PRNG.number())\n  }\n\n  get nextBoolean(): Effect.Effect<boolean> {\n    return core.map(this.next, (n) => n > 0.5)\n  }\n\n  get nextInt(): Effect.Effect<number> {\n    return core.sync(() => this.PRNG.integer(Number.MAX_SAFE_INTEGER))\n  }\n\n  nextRange(min: number, max: number): Effect.Effect<number> {\n    return core.map(this.next, (n) => (max - min) * n + min)\n  }\n\n  nextIntBetween(min: number, max: number): Effect.Effect<number> {\n    return core.sync(() => this.PRNG.integer(max - min) + min)\n  }\n\n  shuffle<A>(elements: Iterable<A>): Effect.Effect<Chunk.Chunk<A>> {\n    return shuffleWith(elements, (n) => this.nextIntBetween(0, n))\n  }\n}\n\nconst shuffleWith = <A>(\n  elements: Iterable<A>,\n  nextIntBounded: (n: number) => Effect.Effect<number>\n): Effect.Effect<Chunk.Chunk<A>> => {\n  return core.suspend(() =>\n    pipe(\n      core.sync(() => Array.from(elements)),\n      core.flatMap((buffer) => {\n        const numbers: Array<number> = []\n        for (let i = buffer.length; i >= 2; i = i - 1) {\n          numbers.push(i)\n        }\n        return pipe(\n          numbers,\n          core.forEachSequentialDiscard((n) =>\n            pipe(\n              nextIntBounded(n),\n              core.map((k) => swap(buffer, n - 1, k))\n            )\n          ),\n          core.as(Chunk.fromIterable(buffer))\n        )\n      })\n    )\n  )\n}\n\nconst swap = <A>(buffer: Array<A>, index1: number, index2: number): Array<A> => {\n  const tmp = buffer[index1]!\n  buffer[index1] = buffer[index2]!\n  buffer[index2] = tmp\n  return buffer\n}\n\nexport const make = <A>(seed: A): Random.Random => new RandomImpl(Hash.hash(seed))\n\n/** @internal */\nclass FixedRandomImpl implements Random.Random {\n  readonly [RandomTypeId]: Random.RandomTypeId = RandomTypeId\n\n  private index = 0\n\n  constructor(readonly values: Arr.NonEmptyArray<any>) {\n    if (values.length === 0) {\n      throw new Error(\"Requires at least one value\")\n    }\n  }\n\n  private getNextValue(): any {\n    const value = this.values[this.index]\n    this.index = (this.index + 1) % this.values.length\n    return value\n  }\n\n  get next(): Effect.Effect<number> {\n    return core.sync(() => {\n      const value = this.getNextValue()\n      if (typeof value === \"number\") {\n        return Math.max(0, Math.min(1, value))\n      }\n      return Hash.hash(value) / 2147483647\n    })\n  }\n\n  get nextBoolean(): Effect.Effect<boolean> {\n    return core.sync(() => {\n      const value = this.getNextValue()\n      if (typeof value === \"boolean\") {\n        return value\n      }\n      return Hash.hash(value) % 2 === 0\n    })\n  }\n\n  get nextInt(): Effect.Effect<number> {\n    return core.sync(() => {\n      const value = this.getNextValue()\n      if (typeof value === \"number\" && Number.isFinite(value)) {\n        return Math.round(value)\n      }\n      return Math.abs(Hash.hash(value))\n    })\n  }\n\n  nextRange(min: number, max: number): Effect.Effect<number> {\n    return core.map(this.next, (n) => (max - min) * n + min)\n  }\n\n  nextIntBetween(min: number, max: number): Effect.Effect<number> {\n    return core.sync(() => {\n      const value = this.getNextValue()\n      if (typeof value === \"number\" && Number.isFinite(value)) {\n        return Math.max(min, Math.min(max - 1, Math.round(value)))\n      }\n      const hash = Math.abs(Hash.hash(value))\n      return min + (hash % (max - min))\n    })\n  }\n\n  shuffle<A>(elements: Iterable<A>): Effect.Effect<Chunk.Chunk<A>> {\n    return shuffleWith(elements, (n) => this.nextIntBetween(0, n))\n  }\n}\n\n/** @internal */\nexport const fixed = <T extends Arr.NonEmptyArray<any>>(values: T): Random.Random => new FixedRandomImpl(values)\n"
  },
  {
    "path": "packages/effect/src/internal/rateLimiter.ts",
    "content": "import type { DurationInput } from \"../Duration.js\"\nimport * as Duration from \"../Duration.js\"\nimport * as Effect from \"../Effect.js\"\nimport * as FiberRef from \"../FiberRef.js\"\nimport { pipe } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport type * as RateLimiter from \"../RateLimiter.js\"\nimport type * as Scope from \"../Scope.js\"\n\n/** @internal */\nexport const make = ({\n  algorithm = \"token-bucket\",\n  interval,\n  limit\n}: RateLimiter.RateLimiter.Options): Effect.Effect<\n  RateLimiter.RateLimiter,\n  never,\n  Scope.Scope\n> => {\n  switch (algorithm) {\n    case \"fixed-window\": {\n      return fixedWindow(limit, interval)\n    }\n    case \"token-bucket\": {\n      return tokenBucket(limit, interval)\n    }\n  }\n}\n\nconst tokenBucket = (limit: number, window: DurationInput): Effect.Effect<\n  RateLimiter.RateLimiter,\n  never,\n  Scope.Scope\n> =>\n  Effect.gen(function*() {\n    const millisPerToken = Math.ceil(Duration.toMillis(window) / limit)\n    const semaphore = yield* Effect.makeSemaphore(limit)\n    const latch = yield* Effect.makeSemaphore(0)\n    const refill: Effect.Effect<void> = Effect.sleep(millisPerToken).pipe(\n      Effect.zipRight(latch.releaseAll),\n      Effect.zipRight(semaphore.release(1)),\n      Effect.flatMap((free) => free === limit ? Effect.void : refill)\n    )\n    yield* pipe(\n      latch.take(1),\n      Effect.zipRight(refill),\n      Effect.forever,\n      Effect.forkScoped,\n      Effect.interruptible\n    )\n    const take = Effect.uninterruptibleMask((restore) =>\n      Effect.flatMap(\n        FiberRef.get(currentCost),\n        (cost) => Effect.zipRight(restore(semaphore.take(cost)), latch.release(1))\n      )\n    )\n    return (effect) => Effect.zipRight(take, effect)\n  })\n\nconst fixedWindow = (limit: number, window: DurationInput): Effect.Effect<\n  RateLimiter.RateLimiter,\n  never,\n  Scope.Scope\n> =>\n  Effect.gen(function*() {\n    const semaphore = yield* Effect.makeSemaphore(limit)\n    const latch = yield* Effect.makeSemaphore(0)\n    yield* pipe(\n      latch.take(1),\n      Effect.zipRight(Effect.sleep(window)),\n      Effect.zipRight(latch.releaseAll),\n      Effect.zipRight(semaphore.releaseAll),\n      Effect.forever,\n      Effect.forkScoped,\n      Effect.interruptible\n    )\n    const take = Effect.uninterruptibleMask((restore) =>\n      Effect.flatMap(\n        FiberRef.get(currentCost),\n        (cost) => Effect.zipRight(restore(semaphore.take(cost)), latch.release(1))\n      )\n    )\n    return (effect) => Effect.zipRight(take, effect)\n  })\n\n/** @internal */\nconst currentCost = globalValue(\n  Symbol.for(\"effect/RateLimiter/currentCost\"),\n  () => FiberRef.unsafeMake(1)\n)\n\n/** @internal */\nexport const withCost = (cost: number) => Effect.locally(currentCost, cost)\n"
  },
  {
    "path": "packages/effect/src/internal/rcMap.ts",
    "content": "import type * as Cause from \"../Cause.js\"\nimport * as Context from \"../Context.js\"\nimport type * as Deferred from \"../Deferred.js\"\nimport * as Duration from \"../Duration.js\"\nimport type { Effect } from \"../Effect.js\"\nimport type { RuntimeFiber } from \"../Fiber.js\"\nimport { constant, dual, flow, identity } from \"../Function.js\"\nimport * as MutableHashMap from \"../MutableHashMap.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport type * as RcMap from \"../RcMap.js\"\nimport type * as Scope from \"../Scope.js\"\nimport * as coreEffect from \"./core-effect.js\"\nimport * as core from \"./core.js\"\nimport * as circular from \"./effect/circular.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\n\n/** @internal */\nexport const TypeId: RcMap.TypeId = Symbol.for(\"effect/RcMap\") as RcMap.TypeId\n\ntype State<K, A, E> = State.Open<K, A, E> | State.Closed\n\ndeclare namespace State {\n  interface Open<K, A, E> {\n    readonly _tag: \"Open\"\n    readonly map: MutableHashMap.MutableHashMap<K, Entry<A, E>>\n  }\n\n  interface Closed {\n    readonly _tag: \"Closed\"\n  }\n\n  interface Entry<A, E> {\n    readonly deferred: Deferred.Deferred<A, E>\n    readonly scope: Scope.CloseableScope\n    readonly finalizer: Effect<void>\n    readonly idleTimeToLive: Duration.Duration\n    fiber: RuntimeFiber<void, never> | undefined\n    expiresAt: number\n    refCount: number\n  }\n}\n\nconst variance: RcMap.RcMap.Variance<any, any, any> = {\n  _K: identity,\n  _A: identity,\n  _E: identity\n}\n\nclass RcMapImpl<K, A, E> implements RcMap.RcMap<K, A, E> {\n  readonly [TypeId]: RcMap.RcMap.Variance<K, A, E>\n\n  state: State<K, A, E> = {\n    _tag: \"Open\",\n    map: MutableHashMap.empty()\n  }\n  readonly semaphore = circular.unsafeMakeSemaphore(1)\n\n  constructor(\n    readonly lookup: (key: K) => Effect<A, E, Scope.Scope>,\n    readonly context: Context.Context<never>,\n    readonly scope: Scope.Scope,\n    readonly idleTimeToLive: ((key: K) => Duration.Duration) | undefined,\n    readonly capacity: number\n  ) {\n    this[TypeId] = variance\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const make: {\n  <K, A, E, R>(options: {\n    readonly lookup: (key: K) => Effect<A, E, R>\n    readonly idleTimeToLive?: Duration.DurationInput | ((key: K) => Duration.DurationInput) | undefined\n    readonly capacity?: undefined\n  }): Effect<RcMap.RcMap<K, A, E>, never, Scope.Scope | R>\n  <K, A, E, R>(options: {\n    readonly lookup: (key: K) => Effect<A, E, R>\n    readonly idleTimeToLive?: Duration.DurationInput | ((key: K) => Duration.DurationInput) | undefined\n    readonly capacity: number\n  }): Effect<RcMap.RcMap<K, A, E | Cause.ExceededCapacityException>, never, Scope.Scope | R>\n} = <K, A, E, R>(options: {\n  readonly lookup: (key: K) => Effect<A, E, R>\n  readonly idleTimeToLive?: Duration.DurationInput | ((key: K) => Duration.DurationInput) | undefined\n  readonly capacity?: number | undefined\n}) =>\n  core.withFiberRuntime<RcMap.RcMap<K, A, E>, never, R | Scope.Scope>((fiber) => {\n    const context = fiber.getFiberRef(core.currentContext) as Context.Context<R | Scope.Scope>\n    const scope = Context.get(context, fiberRuntime.scopeTag)\n    const idleTimeToLive = options.idleTimeToLive === undefined\n      ? undefined\n      : typeof options.idleTimeToLive === \"function\"\n      ? flow(options.idleTimeToLive, Duration.decode)\n      : constant(Duration.decode(options.idleTimeToLive))\n    const self = new RcMapImpl<K, A, E>(\n      options.lookup as any,\n      context,\n      scope,\n      idleTimeToLive,\n      Math.max(options.capacity ?? Number.POSITIVE_INFINITY, 0)\n    )\n    return core.as(\n      scope.addFinalizer(() =>\n        core.suspend(() => {\n          if (self.state._tag === \"Closed\") {\n            return core.void\n          }\n          const map = self.state.map\n          self.state = { _tag: \"Closed\" }\n          return core.forEachSequentialDiscard(\n            map,\n            ([, entry]) => core.scopeClose(entry.scope, core.exitVoid)\n          ).pipe(\n            core.tap(() => {\n              MutableHashMap.clear(map)\n            }),\n            self.semaphore.withPermits(1)\n          )\n        })\n      ),\n      self\n    )\n  })\n\n/** @internal */\nexport const get: {\n  <K>(key: K): <A, E>(self: RcMap.RcMap<K, A, E>) => Effect<A, E, Scope.Scope>\n  <K, A, E>(self: RcMap.RcMap<K, A, E>, key: K): Effect<A, E, Scope.Scope>\n} = dual(2, <K, A, E>(self_: RcMap.RcMap<K, A, E>, key: K): Effect<A, E, Scope.Scope> => {\n  const self = self_ as RcMapImpl<K, A, E>\n  return core.uninterruptibleMask((restore) => getImpl(self, key, restore as any))\n})\n\nconst getImpl = core.fnUntraced(function*<K, A, E>(self: RcMapImpl<K, A, E>, key: K, restore: <A>(a: A) => A) {\n  if (self.state._tag === \"Closed\") {\n    return yield* core.interrupt\n  }\n  const state = self.state\n  const o = MutableHashMap.get(state.map, key)\n  let entry: State.Entry<A, E>\n  if (o._tag === \"Some\") {\n    entry = o.value\n    entry.refCount++\n  } else if (Number.isFinite(self.capacity) && MutableHashMap.size(self.state.map) >= self.capacity) {\n    return yield* core.fail(\n      new core.ExceededCapacityException(`RcMap attempted to exceed capacity of ${self.capacity}`)\n    ) as Effect<never>\n  } else {\n    entry = yield* self.semaphore.withPermits(1)(acquire(self, key, restore))\n  }\n  const scope = yield* fiberRuntime.scopeTag\n  yield* scope.addFinalizer(() => entry.finalizer)\n  return yield* restore(core.deferredAwait(entry.deferred))\n})\n\nconst acquire = core.fnUntraced(function*<K, A, E>(self: RcMapImpl<K, A, E>, key: K, restore: <A>(a: A) => A) {\n  const scope = yield* fiberRuntime.scopeMake()\n  const deferred = yield* core.deferredMake<A, E>()\n  const acquire = self.lookup(key)\n  const contextMap = new Map(self.context.unsafeMap)\n  yield* restore(core.mapInputContext(\n    acquire as Effect<A, E>,\n    (inputContext: Context.Context<never>) => {\n      inputContext.unsafeMap.forEach((value, key) => {\n        contextMap.set(key, value)\n      })\n      contextMap.set(fiberRuntime.scopeTag.key, scope)\n      return Context.unsafeMake(contextMap)\n    }\n  )).pipe(\n    core.exit,\n    core.flatMap((exit) => core.deferredDone(deferred, exit)),\n    circular.forkIn(scope)\n  )\n  const idleTimeToLive = self.idleTimeToLive ? self.idleTimeToLive(key) : Duration.zero\n  const entry: State.Entry<A, E> = {\n    deferred,\n    scope,\n    finalizer: undefined as any,\n    idleTimeToLive,\n    fiber: undefined,\n    expiresAt: 0,\n    refCount: 1\n  }\n  ;(entry as any).finalizer = release(self, key, entry)\n  if (self.state._tag === \"Open\") {\n    MutableHashMap.set(self.state.map, key, entry)\n  }\n  return entry\n})\n\nconst release = <K, A, E>(self: RcMapImpl<K, A, E>, key: K, entry: State.Entry<A, E>) =>\n  coreEffect.clockWith((clock) => {\n    entry.refCount--\n    if (entry.refCount > 0) {\n      return core.void\n    } else if (\n      self.state._tag === \"Closed\"\n      || !MutableHashMap.has(self.state.map, key)\n      || Duration.isZero(entry.idleTimeToLive)\n    ) {\n      if (self.state._tag === \"Open\") {\n        MutableHashMap.remove(self.state.map, key)\n      }\n      return core.scopeClose(entry.scope, core.exitVoid)\n    }\n\n    if (!Duration.isFinite(entry.idleTimeToLive)) {\n      return core.void\n    }\n\n    entry.expiresAt = clock.unsafeCurrentTimeMillis() + Duration.toMillis(entry.idleTimeToLive)\n    if (entry.fiber) return core.void\n\n    return core.interruptibleMask(function loop(restore): Effect<void> {\n      const now = clock.unsafeCurrentTimeMillis()\n      const remaining = entry.expiresAt - now\n      if (remaining <= 0) {\n        if (self.state._tag === \"Closed\" || entry.refCount > 0) return core.void\n        MutableHashMap.remove(self.state.map, key)\n        return restore(core.scopeClose(entry.scope, core.exitVoid))\n      }\n      return core.flatMap(clock.sleep(Duration.millis(remaining)), () => loop(restore))\n    }).pipe(\n      fiberRuntime.ensuring(core.sync(() => {\n        entry.fiber = undefined\n      })),\n      circular.forkIn(self.scope),\n      core.tap((fiber) => {\n        entry.fiber = fiber\n      }),\n      self.semaphore.withPermits(1)\n    )\n  })\n\n/** @internal */\nexport const keys = <K, A, E>(self: RcMap.RcMap<K, A, E>): Effect<Array<K>> => {\n  const impl = self as RcMapImpl<K, A, E>\n  return core.suspend(() =>\n    impl.state._tag === \"Closed\" ? core.interrupt : core.succeed(MutableHashMap.keys(impl.state.map))\n  )\n}\n\n/** @internal */\nexport const invalidate: {\n  <K>(key: K): <A, E>(self: RcMap.RcMap<K, A, E>) => Effect<void>\n  <K, A, E>(self: RcMap.RcMap<K, A, E>, key: K): Effect<void>\n} = dual(\n  2,\n  core.fnUntraced(function*<K, A, E>(self_: RcMap.RcMap<K, A, E>, key: K) {\n    const self = self_ as RcMapImpl<K, A, E>\n    if (self.state._tag === \"Closed\") return\n    const o = MutableHashMap.get(self.state.map, key)\n    if (o._tag === \"None\") return\n    const entry = o.value\n    MutableHashMap.remove(self.state.map, key)\n    if (entry.refCount > 0) return\n    yield* core.scopeClose(entry.scope, core.exitVoid)\n    if (entry.fiber) yield* core.interruptFiber(entry.fiber)\n  })\n)\n\n/** @internal */\nexport const has: {\n  <K>(key: K): <A, E>(self: RcMap.RcMap<K, A, E>) => Effect<boolean>\n  <K, A, E>(self: RcMap.RcMap<K, A, E>, key: K): Effect<boolean>\n} = dual(2, <K, A, E>(self_: RcMap.RcMap<K, A, E>, key: K): Effect<boolean> => {\n  const self = self_ as RcMapImpl<K, A, E>\n  return core.sync(() => {\n    if (self.state._tag === \"Closed\") return false\n    return MutableHashMap.has(self.state.map, key)\n  })\n})\n\n/** @internal */\nexport const touch: {\n  <K>(key: K): <A, E>(self: RcMap.RcMap<K, A, E>) => Effect<void>\n  <K, A, E>(self: RcMap.RcMap<K, A, E>, key: K): Effect<void>\n} = dual(\n  2,\n  <K, A, E>(self_: RcMap.RcMap<K, A, E>, key: K) =>\n    coreEffect.clockWith((clock) => {\n      const self = self_ as RcMapImpl<K, A, E>\n      if (self.state._tag === \"Closed\") return core.void\n      const o = MutableHashMap.get(self.state.map, key)\n      if (o._tag === \"None\") return core.void\n      const entry = o.value\n      if (Duration.isZero(entry.idleTimeToLive)) return core.void\n      entry.expiresAt = clock.unsafeCurrentTimeMillis() + Duration.toMillis(entry.idleTimeToLive)\n      return core.void\n    })\n)\n"
  },
  {
    "path": "packages/effect/src/internal/rcRef.ts",
    "content": "import * as Context from \"../Context.js\"\nimport * as Duration from \"../Duration.js\"\nimport type { Effect } from \"../Effect.js\"\nimport * as Effectable from \"../Effectable.js\"\nimport type { RuntimeFiber } from \"../Fiber.js\"\nimport { identity } from \"../Function.js\"\nimport type * as RcRef from \"../RcRef.js\"\nimport * as Readable from \"../Readable.js\"\nimport type * as Scope from \"../Scope.js\"\nimport * as coreEffect from \"./core-effect.js\"\nimport * as core from \"./core.js\"\nimport * as circular from \"./effect/circular.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\n\n/** @internal */\nexport const TypeId: RcRef.TypeId = Symbol.for(\"effect/RcRef\") as RcRef.TypeId\n\ntype State<A> = State.Empty | State.Acquired<A> | State.Closed\n\ndeclare namespace State {\n  interface Empty {\n    readonly _tag: \"Empty\"\n  }\n\n  interface Acquired<A> {\n    readonly _tag: \"Acquired\"\n    readonly value: A\n    readonly scope: Scope.CloseableScope\n    fiber: RuntimeFiber<void, never> | undefined\n    refCount: number\n  }\n\n  interface Closed {\n    readonly _tag: \"Closed\"\n  }\n}\n\nconst stateEmpty: State<never> = { _tag: \"Empty\" }\nconst stateClosed: State<never> = { _tag: \"Closed\" }\n\nconst variance: RcRef.RcRef.Variance<any, any> = {\n  _A: identity,\n  _E: identity\n}\n\nclass RcRefImpl<A, E> extends Effectable.Class<A, E, Scope.Scope> implements RcRef.RcRef<A, E> {\n  readonly [TypeId]: RcRef.RcRef.Variance<A, E> = variance\n  readonly [Readable.TypeId]: Readable.TypeId = Readable.TypeId\n\n  state: State<A> = stateEmpty\n  readonly semaphore = circular.unsafeMakeSemaphore(1)\n\n  constructor(\n    readonly acquire: Effect<A, E, Scope.Scope>,\n    readonly context: Context.Context<never>,\n    readonly scope: Scope.Scope,\n    readonly idleTimeToLive: Duration.Duration | undefined\n  ) {\n    super()\n    this.get = get(this)\n  }\n  readonly get: Effect<A, E, Scope.Scope>\n\n  commit() {\n    return this.get\n  }\n}\n\n/** @internal */\nexport const make = <A, E, R>(options: {\n  readonly acquire: Effect<A, E, R>\n  readonly idleTimeToLive?: Duration.DurationInput | undefined\n}) =>\n  core.withFiberRuntime<RcRef.RcRef<A, E>, never, R | Scope.Scope>((fiber) => {\n    const context = fiber.getFiberRef(core.currentContext) as Context.Context<R | Scope.Scope>\n    const scope = Context.get(context, fiberRuntime.scopeTag)\n    const ref = new RcRefImpl<A, E>(\n      options.acquire as Effect<A, E, Scope.Scope>,\n      context,\n      scope,\n      options.idleTimeToLive ? Duration.decode(options.idleTimeToLive) : undefined\n    )\n    return core.as(\n      scope.addFinalizer(() =>\n        ref.semaphore.withPermits(1)(core.suspend(() => {\n          const close = ref.state._tag === \"Acquired\"\n            ? core.scopeClose(ref.state.scope, core.exitVoid)\n            : core.void\n          ref.state = stateClosed\n          return close\n        }))\n      ),\n      ref\n    )\n  })\n\n/** @internal */\nexport const get = <A, E>(\n  self_: RcRef.RcRef<A, E>\n): Effect<A, E, Scope.Scope> => {\n  const self = self_ as RcRefImpl<A, E>\n  const isInfinite = self.idleTimeToLive && !Duration.isFinite(self.idleTimeToLive)\n  return core.uninterruptibleMask((restore) =>\n    core.suspend(() => {\n      switch (self.state._tag) {\n        case \"Closed\": {\n          return core.interrupt\n        }\n        case \"Acquired\": {\n          self.state.refCount++\n          return self.state.fiber\n            ? core.as(core.interruptFiber(self.state.fiber), self.state)\n            : core.succeed(self.state)\n        }\n        case \"Empty\": {\n          return fiberRuntime.scopeMake().pipe(\n            coreEffect.bindTo(\"scope\"),\n            coreEffect.bind(\"value\", ({ scope }) =>\n              restore(core.fiberRefLocally(\n                self.acquire as Effect<A, E>,\n                core.currentContext,\n                Context.add(self.context, fiberRuntime.scopeTag, scope)\n              ))),\n            core.map(({ scope, value }) => {\n              const state: State.Acquired<A> = {\n                _tag: \"Acquired\",\n                value,\n                scope,\n                fiber: undefined,\n                refCount: 1\n              }\n              self.state = state\n              return state\n            })\n          )\n        }\n      }\n    })\n  ).pipe(\n    self.semaphore.withPermits(1),\n    coreEffect.bindTo(\"state\"),\n    coreEffect.bind(\"scope\", () => fiberRuntime.scopeTag),\n    core.tap(({ scope, state }) =>\n      scope.addFinalizer(() =>\n        core.suspend(() => {\n          state.refCount--\n          if (state.refCount > 0 || isInfinite) {\n            return core.void\n          }\n          if (self.idleTimeToLive === undefined) {\n            self.state = stateEmpty\n            return core.scopeClose(state.scope, core.exitVoid)\n          }\n          return coreEffect.sleep(self.idleTimeToLive).pipe(\n            core.interruptible,\n            core.zipRight(core.suspend(() => {\n              if (self.state._tag === \"Acquired\" && self.state.refCount === 0) {\n                self.state = stateEmpty\n                return core.scopeClose(state.scope, core.exitVoid)\n              }\n              return core.void\n            })),\n            fiberRuntime.ensuring(core.sync(() => {\n              state.fiber = undefined\n            })),\n            circular.forkIn(self.scope),\n            core.tap((fiber) => {\n              state.fiber = fiber\n            }),\n            self.semaphore.withPermits(1)\n          )\n        })\n      )\n    ),\n    core.map(({ state }) => state.value)\n  )\n}\n\n/** @internal */\nexport const invalidate = <A, E>(\n  self_: RcRef.RcRef<A, E>\n): Effect<void> => {\n  const self = self_ as RcRefImpl<A, E>\n  return core.uninterruptible(core.suspend(() => {\n    if (self.state._tag !== \"Acquired\") {\n      return core.void\n    }\n    const state = self.state\n    self.state = stateEmpty\n    return state.scope.close(core.exitVoid)\n  }))\n}\n"
  },
  {
    "path": "packages/effect/src/internal/redBlackTree/iterator.ts",
    "content": "import * as Arr from \"../../Array.js\"\nimport * as Option from \"../../Option.js\"\nimport type * as RBT from \"../../RedBlackTree.js\"\nimport type { RedBlackTreeImpl } from \"../redBlackTree.js\"\nimport type * as Node from \"./node.js\"\n\n/** @internal */\nexport const Direction = {\n  Forward: 0 as RBT.RedBlackTree.Direction,\n  Backward: 1 << 0 as RBT.RedBlackTree.Direction\n} as const\n\n/** @internal */\nexport class RedBlackTreeIterator<in out K, out V> implements Iterator<[K, V]> {\n  private count = 0\n\n  constructor(\n    readonly self: RBT.RedBlackTree<K, V>,\n    readonly stack: Array<Node.Node<K, V>>,\n    readonly direction: RBT.RedBlackTree.Direction\n  ) {}\n\n  /**\n   * Clones the iterator\n   */\n  clone(): RedBlackTreeIterator<K, V> {\n    return new RedBlackTreeIterator(this.self, this.stack.slice(), this.direction)\n  }\n\n  /**\n   * Reverse the traversal direction\n   */\n  reversed(): RedBlackTreeIterator<K, V> {\n    return new RedBlackTreeIterator(\n      this.self,\n      this.stack.slice(),\n      this.direction === Direction.Forward ? Direction.Backward : Direction.Forward\n    )\n  }\n\n  /**\n   * Iterator next\n   */\n  next(): IteratorResult<[K, V], number> {\n    const entry = this.entry\n    this.count++\n    if (this.direction === Direction.Forward) {\n      this.moveNext()\n    } else {\n      this.movePrev()\n    }\n    switch (entry._tag) {\n      case \"None\": {\n        return { done: true, value: this.count }\n      }\n      case \"Some\": {\n        return { done: false, value: entry.value }\n      }\n    }\n  }\n\n  /**\n   * Returns the key\n   */\n  get key(): Option.Option<K> {\n    if (this.stack.length > 0) {\n      return Option.some(this.stack[this.stack.length - 1]!.key)\n    }\n    return Option.none()\n  }\n\n  /**\n   * Returns the value\n   */\n  get value(): Option.Option<V> {\n    if (this.stack.length > 0) {\n      return Option.some(this.stack[this.stack.length - 1]!.value)\n    }\n    return Option.none()\n  }\n\n  /**\n   * Returns the key\n   */\n  get entry(): Option.Option<[K, V]> {\n    return Option.map(Arr.last(this.stack), (node) => [node.key, node.value])\n  }\n\n  /**\n   * Returns the position of this iterator in the sorted list\n   */\n  get index(): number {\n    let idx = 0\n    const stack = this.stack\n    if (stack.length === 0) {\n      const r = (this.self as RedBlackTreeImpl<K, V>)._root\n      if (r != null) {\n        return r.count\n      }\n      return 0\n    } else if (stack[stack.length - 1]!.left != null) {\n      idx = stack[stack.length - 1]!.left!.count\n    }\n    for (let s = stack.length - 2; s >= 0; --s) {\n      if (stack[s + 1] === stack[s]!.right) {\n        ++idx\n        if (stack[s]!.left != null) {\n          idx += stack[s]!.left!.count\n        }\n      }\n    }\n    return idx\n  }\n\n  /**\n   * Advances iterator to next element in list\n   */\n  moveNext() {\n    const stack = this.stack\n    if (stack.length === 0) {\n      return\n    }\n    let n: Node.Node<K, V> | undefined = stack[stack.length - 1]!\n    if (n.right != null) {\n      n = n.right\n      while (n != null) {\n        stack.push(n)\n        n = n.left\n      }\n    } else {\n      stack.pop()\n      while (stack.length > 0 && stack[stack.length - 1]!.right === n) {\n        n = stack[stack.length - 1]\n        stack.pop()\n      }\n    }\n  }\n\n  /**\n   * Checks if there is a next element\n   */\n  get hasNext() {\n    const stack = this.stack\n    if (stack.length === 0) {\n      return false\n    }\n    if (stack[stack.length - 1]!.right != null) {\n      return true\n    }\n    for (let s = stack.length - 1; s > 0; --s) {\n      if (stack[s - 1]!.left === stack[s]) {\n        return true\n      }\n    }\n    return false\n  }\n\n  /**\n   * Advances iterator to previous element in list\n   */\n  movePrev() {\n    const stack = this.stack\n    if (stack.length === 0) {\n      return\n    }\n    let n: Node.Node<K, V> | undefined = stack[stack.length - 1]\n    if (n != null && n.left != null) {\n      n = n.left\n      while (n != null) {\n        stack.push(n)\n        n = n.right\n      }\n    } else {\n      stack.pop()\n      while (stack.length > 0 && stack[stack.length - 1]!.left === n) {\n        n = stack[stack.length - 1]\n        stack.pop()\n      }\n    }\n  }\n\n  /**\n   * Checks if there is a previous element\n   */\n  get hasPrev() {\n    const stack = this.stack\n    if (stack.length === 0) {\n      return false\n    }\n    if (stack[stack.length - 1]!.left != null) {\n      return true\n    }\n    for (let s = stack.length - 1; s > 0; --s) {\n      if (stack[s - 1]!.right === stack[s]) {\n        return true\n      }\n    }\n    return false\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/redBlackTree/node.ts",
    "content": "/** @internal */\nexport const Color = {\n  Red: 0 as Node.Color,\n  Black: 1 << 0 as Node.Color\n} as const\n\nexport declare namespace Node {\n  export type Color = number & {\n    readonly Color: unique symbol\n  }\n}\n\nexport interface Node<out K, out V> {\n  color: Node.Color\n  key: K\n  value: V\n  left: Node<K, V> | undefined\n  right: Node<K, V> | undefined\n  count: number\n}\n\n/** @internal */\nexport const clone = <K, V>({\n  color,\n  count,\n  key,\n  left,\n  right,\n  value\n}: Node<K, V>) => ({\n  color,\n  key,\n  value,\n  left,\n  right,\n  count\n})\n\n/** @internal */\nexport function swap<K, V>(n: Node<K, V>, v: Node<K, V>) {\n  n.key = v.key\n  n.value = v.value\n  n.left = v.left\n  n.right = v.right\n  n.color = v.color\n  n.count = v.count\n}\n\n/** @internal */\nexport const repaint = <K, V>({\n  count,\n  key,\n  left,\n  right,\n  value\n}: Node<K, V>, color: Node.Color) => ({\n  color,\n  key,\n  value,\n  left,\n  right,\n  count\n})\n\n/** @internal */\nexport const recount = <K, V>(node: Node<K, V>) => {\n  node.count = 1 + (node.left?.count ?? 0) + (node.right?.count ?? 0)\n}\n"
  },
  {
    "path": "packages/effect/src/internal/redBlackTree.ts",
    "content": "import * as Chunk from \"../Chunk.js\"\nimport * as Equal from \"../Equal.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport * as Hash from \"../Hash.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"../Inspectable.js\"\nimport * as Option from \"../Option.js\"\nimport type * as Order from \"../Order.js\"\nimport type * as Ordering from \"../Ordering.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as RBT from \"../RedBlackTree.js\"\nimport { Direction, RedBlackTreeIterator } from \"./redBlackTree/iterator.js\"\nimport * as Node from \"./redBlackTree/node.js\"\nimport * as Stack from \"./stack.js\"\n\nconst RedBlackTreeSymbolKey = \"effect/RedBlackTree\"\n\n/** @internal */\nexport const RedBlackTreeTypeId: RBT.TypeId = Symbol.for(RedBlackTreeSymbolKey) as RBT.TypeId\n\n/** @internal */\nexport interface RedBlackTreeImpl<in out K, out V> extends RBT.RedBlackTree<K, V> {\n  readonly _ord: Order.Order<K>\n  readonly _root: Node.Node<K, V> | undefined\n}\n\nconst redBlackTreeVariance = {\n  /* c8 ignore next */\n  _Key: (_: any) => _,\n  /* c8 ignore next */\n  _Value: (_: never) => _\n}\n\nconst RedBlackTreeProto: RBT.RedBlackTree<unknown, unknown> = {\n  [RedBlackTreeTypeId]: redBlackTreeVariance,\n  [Hash.symbol](this: RBT.RedBlackTree<unknown, unknown>): number {\n    let hash = Hash.hash(RedBlackTreeSymbolKey)\n    for (const item of this) {\n      hash ^= pipe(Hash.hash(item[0]), Hash.combine(Hash.hash(item[1])))\n    }\n    return Hash.cached(this, hash)\n  },\n  [Equal.symbol]<K, V>(this: RedBlackTreeImpl<K, V>, that: unknown): boolean {\n    if (isRedBlackTree(that)) {\n      if ((this._root?.count ?? 0) !== ((that as RedBlackTreeImpl<K, V>)._root?.count ?? 0)) {\n        return false\n      }\n      const entries = Array.from(that)\n      return Array.from(this).every((itemSelf, i) => {\n        const itemThat = entries[i]\n        return Equal.equals(itemSelf[0], itemThat[0]) && Equal.equals(itemSelf[1], itemThat[1])\n      })\n    }\n    return false\n  },\n  [Symbol.iterator]<K, V>(this: RedBlackTreeImpl<K, V>): RedBlackTreeIterator<K, V> {\n    const stack: Array<Node.Node<K, V>> = []\n    let n = this._root\n    while (n != null) {\n      stack.push(n)\n      n = n.left\n    }\n    return new RedBlackTreeIterator(this, stack, Direction.Forward)\n  },\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"RedBlackTree\",\n      values: Array.from(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makeImpl = <K, V>(ord: Order.Order<K>, root: Node.Node<K, V> | undefined): RedBlackTreeImpl<K, V> => {\n  const tree = Object.create(RedBlackTreeProto)\n  tree._ord = ord\n  tree._root = root\n  return tree\n}\n\n/** @internal */\nexport const isRedBlackTree: {\n  <K, V>(u: Iterable<readonly [K, V]>): u is RBT.RedBlackTree<K, V>\n  (u: unknown): u is RBT.RedBlackTree<unknown, unknown>\n} = (u: unknown): u is RBT.RedBlackTree<unknown, unknown> => hasProperty(u, RedBlackTreeTypeId)\n\n/** @internal */\nexport const empty = <K, V = never>(ord: Order.Order<K>): RBT.RedBlackTree<K, V> => makeImpl<K, V>(ord, undefined)\n\n/** @internal */\nexport const fromIterable = dual<\n  <B>(ord: Order.Order<B>) => <K extends B, V>(entries: Iterable<readonly [K, V]>) => RBT.RedBlackTree<K, V>,\n  <K extends B, V, B>(entries: Iterable<readonly [K, V]>, ord: Order.Order<B>) => RBT.RedBlackTree<K, V>\n>(2, <K extends B, V, B>(entries: Iterable<readonly [K, V]>, ord: Order.Order<B>) => {\n  let tree = empty<K, V>(ord)\n  for (const [key, value] of entries) {\n    tree = insert(tree, key, value)\n  }\n  return tree\n})\n\n/** @internal */\nexport const make =\n  <K>(ord: Order.Order<K>) =>\n  <Entries extends Array<readonly [K, any]>>(...entries: Entries): RBT.RedBlackTree<\n    K,\n    Entries[number] extends readonly [any, infer V] ? V : never\n  > => {\n    return fromIterable(entries, ord)\n  }\n\n/** @internal */\nexport const atBackwards = dual<\n  (index: number) => <K, V>(self: RBT.RedBlackTree<K, V>) => Iterable<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, index: number) => Iterable<[K, V]>\n>(2, (self, index) => at(self, index, Direction.Backward))\n\n/** @internal */\nexport const atForwards = dual<\n  (index: number) => <K, V>(self: RBT.RedBlackTree<K, V>) => Iterable<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, index: number) => Iterable<[K, V]>\n>(2, (self, index) => at(self, index, Direction.Forward))\n\nconst at = <K, V>(\n  self: RBT.RedBlackTree<K, V>,\n  index: number,\n  direction: RBT.RedBlackTree.Direction\n): Iterable<[K, V]> => {\n  return {\n    [Symbol.iterator]: () => {\n      if (index < 0) {\n        return new RedBlackTreeIterator(self, [], direction)\n      }\n      let node = (self as RedBlackTreeImpl<K, V>)._root\n      const stack: Array<Node.Node<K, V>> = []\n      while (node !== undefined) {\n        stack.push(node)\n        if (node.left !== undefined) {\n          if (index < node.left.count) {\n            node = node.left\n            continue\n          }\n          index -= node.left.count\n        }\n        if (!index) {\n          return new RedBlackTreeIterator(self, stack, direction)\n        }\n        index -= 1\n        if (node.right !== undefined) {\n          if (index >= node.right.count) {\n            break\n          }\n          node = node.right\n        } else {\n          break\n        }\n      }\n      return new RedBlackTreeIterator(self, [], direction)\n    }\n  }\n}\n\n/** @internal */\nexport const findAll = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => Chunk.Chunk<V>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => Chunk.Chunk<V>\n>(2, <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => {\n  const stack: Array<Node.Node<K, V>> = []\n  let node = (self as RedBlackTreeImpl<K, V>)._root\n  let result = Chunk.empty<V>()\n  while (node !== undefined || stack.length > 0) {\n    if (node) {\n      stack.push(node)\n      node = node.left\n    } else {\n      const current = stack.pop()!\n      if (Equal.equals(key, current.key)) {\n        result = Chunk.prepend(current.value)(result)\n      }\n      node = current.right\n    }\n  }\n  return result\n})\n\n/** @internal */\nexport const findFirst = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => Option.Option<V>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => Option.Option<V>\n>(2, <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => {\n  const cmp = (self as RedBlackTreeImpl<K, V>)._ord\n  let node = (self as RedBlackTreeImpl<K, V>)._root\n  while (node !== undefined) {\n    const d = cmp(key, node.key)\n    if (Equal.equals(key, node.key)) {\n      return Option.some(node.value)\n    }\n    if (d <= 0) {\n      node = node.left\n    } else {\n      node = node.right\n    }\n  }\n  return Option.none()\n})\n\n/** @internal */\nexport const first = <K, V>(self: RBT.RedBlackTree<K, V>): Option.Option<[K, V]> => {\n  let node: Node.Node<K, V> | undefined = (self as RedBlackTreeImpl<K, V>)._root\n  let current: Node.Node<K, V> | undefined = (self as RedBlackTreeImpl<K, V>)._root\n  while (node !== undefined) {\n    current = node\n    node = node.left\n  }\n  return current ? Option.some([current.key, current.value]) : Option.none()\n}\n\n/** @internal */\nexport const getAt = dual<\n  (index: number) => <K, V>(self: RBT.RedBlackTree<K, V>) => Option.Option<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, index: number) => Option.Option<[K, V]>\n>(2, <K, V>(self: RBT.RedBlackTree<K, V>, index: number) => {\n  if (index < 0) {\n    return Option.none()\n  }\n  let root = (self as RedBlackTreeImpl<K, V>)._root\n  let node: Node.Node<K, V> | undefined = undefined\n  while (root !== undefined) {\n    node = root\n    if (root.left) {\n      if (index < root.left.count) {\n        root = root.left\n        continue\n      }\n      index -= root.left.count\n    }\n    if (!index) {\n      return Option.some([node.key, node.value])\n    }\n    index -= 1\n    if (root.right) {\n      if (index >= root.right.count) {\n        break\n      }\n      root = root.right\n    } else {\n      break\n    }\n  }\n  return Option.none()\n})\n\n/** @internal */\nexport const getOrder = <K, V>(tree: RBT.RedBlackTree<K, V>): Order.Order<K> => (tree as RedBlackTreeImpl<K, V>)._ord\n\n/** @internal */\nexport const has = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => boolean,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => boolean\n>(2, (self, key) => Option.isSome(findFirst(self, key)))\n\n/** @internal */\nexport const insert = dual<\n  <K, V>(key: K, value: V) => (self: RBT.RedBlackTree<K, V>) => RBT.RedBlackTree<K, V>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K, value: V) => RBT.RedBlackTree<K, V>\n>(3, <K, V>(self: RBT.RedBlackTree<K, V>, key: K, value: V) => {\n  const cmp = (self as RedBlackTreeImpl<K, V>)._ord\n  // Find point to insert new node at\n  let n: Node.Node<K, V> | undefined = (self as RedBlackTreeImpl<K, V>)._root\n  const n_stack: Array<Node.Node<K, V>> = []\n  const d_stack: Array<Ordering.Ordering> = []\n  while (n != null) {\n    const d = cmp(key, n.key)\n    n_stack.push(n)\n    d_stack.push(d)\n    if (d <= 0) {\n      n = n.left\n    } else {\n      n = n.right\n    }\n  }\n  // Rebuild path to leaf node\n  n_stack.push({\n    color: Node.Color.Red,\n    key,\n    value,\n    left: undefined,\n    right: undefined,\n    count: 1\n  })\n  for (let s = n_stack.length - 2; s >= 0; --s) {\n    const n2 = n_stack[s]!\n    if (d_stack[s]! <= 0) {\n      n_stack[s] = {\n        color: n2.color,\n        key: n2.key,\n        value: n2.value,\n        left: n_stack[s + 1],\n        right: n2.right,\n        count: n2.count + 1\n      }\n    } else {\n      n_stack[s] = {\n        color: n2.color,\n        key: n2.key,\n        value: n2.value,\n        left: n2.left,\n        right: n_stack[s + 1],\n        count: n2.count + 1\n      }\n    }\n  }\n  // Rebalance tree using rotations\n  for (let s = n_stack.length - 1; s > 1; --s) {\n    const p = n_stack[s - 1]!\n    const n3 = n_stack[s]!\n    if (p.color === Node.Color.Black || n3.color === Node.Color.Black) {\n      break\n    }\n    const pp = n_stack[s - 2]!\n    if (pp.left === p) {\n      if (p.left === n3) {\n        const y = pp.right\n        if (y && y.color === Node.Color.Red) {\n          p.color = Node.Color.Black\n          pp.right = Node.repaint(y, Node.Color.Black)\n          pp.color = Node.Color.Red\n          s -= 1\n        } else {\n          pp.color = Node.Color.Red\n          pp.left = p.right\n          p.color = Node.Color.Black\n          p.right = pp\n          n_stack[s - 2] = p\n          n_stack[s - 1] = n3\n          Node.recount(pp)\n          Node.recount(p)\n          if (s >= 3) {\n            const ppp = n_stack[s - 3]!\n            if (ppp.left === pp) {\n              ppp.left = p\n            } else {\n              ppp.right = p\n            }\n          }\n          break\n        }\n      } else {\n        const y = pp.right\n        if (y && y.color === Node.Color.Red) {\n          p.color = Node.Color.Black\n          pp.right = Node.repaint(y, Node.Color.Black)\n          pp.color = Node.Color.Red\n          s -= 1\n        } else {\n          p.right = n3.left\n          pp.color = Node.Color.Red\n          pp.left = n3.right\n          n3.color = Node.Color.Black\n          n3.left = p\n          n3.right = pp\n          n_stack[s - 2] = n3\n          n_stack[s - 1] = p\n          Node.recount(pp)\n          Node.recount(p)\n          Node.recount(n3)\n          if (s >= 3) {\n            const ppp = n_stack[s - 3]!\n            if (ppp.left === pp) {\n              ppp.left = n3\n            } else {\n              ppp.right = n3\n            }\n          }\n          break\n        }\n      }\n    } else {\n      if (p.right === n3) {\n        const y = pp.left\n        if (y && y.color === Node.Color.Red) {\n          p.color = Node.Color.Black\n          pp.left = Node.repaint(y, Node.Color.Black)\n          pp.color = Node.Color.Red\n          s -= 1\n        } else {\n          pp.color = Node.Color.Red\n          pp.right = p.left\n          p.color = Node.Color.Black\n          p.left = pp\n          n_stack[s - 2] = p\n          n_stack[s - 1] = n3\n          Node.recount(pp)\n          Node.recount(p)\n          if (s >= 3) {\n            const ppp = n_stack[s - 3]!\n            if (ppp.right === pp) {\n              ppp.right = p\n            } else {\n              ppp.left = p\n            }\n          }\n          break\n        }\n      } else {\n        const y = pp.left\n        if (y && y.color === Node.Color.Red) {\n          p.color = Node.Color.Black\n          pp.left = Node.repaint(y, Node.Color.Black)\n          pp.color = Node.Color.Red\n          s -= 1\n        } else {\n          p.left = n3.right\n          pp.color = Node.Color.Red\n          pp.right = n3.left\n          n3.color = Node.Color.Black\n          n3.right = p\n          n3.left = pp\n          n_stack[s - 2] = n3\n          n_stack[s - 1] = p\n          Node.recount(pp)\n          Node.recount(p)\n          Node.recount(n3)\n          if (s >= 3) {\n            const ppp = n_stack[s - 3]!\n            if (ppp.right === pp) {\n              ppp.right = n3\n            } else {\n              ppp.left = n3\n            }\n          }\n          break\n        }\n      }\n    }\n  }\n  // Return new tree\n  n_stack[0]!.color = Node.Color.Black\n  return makeImpl((self as RedBlackTreeImpl<K, V>)._ord, n_stack[0])\n})\n\n/** @internal */\nexport const keysForward = <K, V>(self: RBT.RedBlackTree<K, V>): IterableIterator<K> => keys(self, Direction.Forward)\n\n/** @internal */\nexport const keysBackward = <K, V>(self: RBT.RedBlackTree<K, V>): IterableIterator<K> => keys(self, Direction.Backward)\n\nconst keys = <K, V>(\n  self: RBT.RedBlackTree<K, V>,\n  direction: RBT.RedBlackTree.Direction\n): IterableIterator<K> => {\n  const begin: RedBlackTreeIterator<K, V> = self[Symbol.iterator]() as RedBlackTreeIterator<K, V>\n  let count = 0\n  return {\n    [Symbol.iterator]: () => keys(self, direction),\n    next: (): IteratorResult<K, number> => {\n      count++\n      const entry = begin.key\n      if (direction === Direction.Forward) {\n        begin.moveNext()\n      } else {\n        begin.movePrev()\n      }\n      switch (entry._tag) {\n        case \"None\": {\n          return { done: true, value: count }\n        }\n        case \"Some\": {\n          return { done: false, value: entry.value }\n        }\n      }\n    }\n  }\n}\n\n/** @internal */\nexport const last = <K, V>(self: RBT.RedBlackTree<K, V>): Option.Option<[K, V]> => {\n  let node: Node.Node<K, V> | undefined = (self as RedBlackTreeImpl<K, V>)._root\n  let current: Node.Node<K, V> | undefined = (self as RedBlackTreeImpl<K, V>)._root\n  while (node !== undefined) {\n    current = node\n    node = node.right\n  }\n  return current ? Option.some([current.key, current.value]) : Option.none()\n}\n\n/** @internal */\nexport const reversed = <K, V>(self: RBT.RedBlackTree<K, V>): Iterable<[K, V]> => {\n  return {\n    [Symbol.iterator]: () => {\n      const stack: Array<Node.Node<K, V>> = []\n      let node = (self as RedBlackTreeImpl<K, V>)._root\n      while (node !== undefined) {\n        stack.push(node)\n        node = node.right\n      }\n      return new RedBlackTreeIterator(self, stack, Direction.Backward)\n    }\n  }\n}\n\n/** @internal */\nexport const greaterThanBackwards = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => Iterable<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => Iterable<[K, V]>\n>(2, (self, key) => greaterThan(self, key, Direction.Backward))\n\n/** @internal */\nexport const greaterThanForwards = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => Iterable<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => Iterable<[K, V]>\n>(2, (self, key) => greaterThan(self, key, Direction.Forward))\n\nconst greaterThan = <K, V>(\n  self: RBT.RedBlackTree<K, V>,\n  key: K,\n  direction: RBT.RedBlackTree.Direction\n): Iterable<[K, V]> => {\n  return {\n    [Symbol.iterator]: () => {\n      const cmp = (self as RedBlackTreeImpl<K, V>)._ord\n      let node = (self as RedBlackTreeImpl<K, V>)._root\n      const stack = []\n      let last_ptr = 0\n      while (node !== undefined) {\n        const d = cmp(key, node.key)\n        stack.push(node)\n        if (d < 0) {\n          last_ptr = stack.length\n        }\n        if (d < 0) {\n          node = node.left\n        } else {\n          node = node.right\n        }\n      }\n      stack.length = last_ptr\n      return new RedBlackTreeIterator(self, stack, direction)\n    }\n  }\n}\n\n/** @internal */\nexport const greaterThanEqualBackwards = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => Iterable<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => Iterable<[K, V]>\n>(2, (self, key) => greaterThanEqual(self, key, Direction.Backward))\n\n/** @internal */\nexport const greaterThanEqualForwards = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => Iterable<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => Iterable<[K, V]>\n>(2, (self, key) => greaterThanEqual(self, key, Direction.Forward))\n\nconst greaterThanEqual = <K, V>(\n  self: RBT.RedBlackTree<K, V>,\n  key: K,\n  direction: RBT.RedBlackTree.Direction = Direction.Forward\n): Iterable<[K, V]> => {\n  return {\n    [Symbol.iterator]: () => {\n      const cmp = (self as RedBlackTreeImpl<K, V>)._ord\n      let node = (self as RedBlackTreeImpl<K, V>)._root\n      const stack = []\n      let last_ptr = 0\n      while (node !== undefined) {\n        const d = cmp(key, node.key)\n        stack.push(node)\n        if (d <= 0) {\n          last_ptr = stack.length\n        }\n        if (d <= 0) {\n          node = node.left\n        } else {\n          node = node.right\n        }\n      }\n      stack.length = last_ptr\n      return new RedBlackTreeIterator(self, stack, direction)\n    }\n  }\n}\n\n/** @internal */\nexport const lessThanBackwards = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => Iterable<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => Iterable<[K, V]>\n>(2, (self, key) => lessThan(self, key, Direction.Backward))\n\n/** @internal */\nexport const lessThanForwards = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => Iterable<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => Iterable<[K, V]>\n>(2, (self, key) => lessThan(self, key, Direction.Forward))\n\nconst lessThan = <K, V>(\n  self: RBT.RedBlackTree<K, V>,\n  key: K,\n  direction: RBT.RedBlackTree.Direction\n): Iterable<[K, V]> => {\n  return {\n    [Symbol.iterator]: () => {\n      const cmp = (self as RedBlackTreeImpl<K, V>)._ord\n      let node = (self as RedBlackTreeImpl<K, V>)._root\n      const stack = []\n      let last_ptr = 0\n      while (node !== undefined) {\n        const d = cmp(key, node.key)\n        stack.push(node)\n        if (d > 0) {\n          last_ptr = stack.length\n        }\n        if (d <= 0) {\n          node = node.left\n        } else {\n          node = node.right\n        }\n      }\n      stack.length = last_ptr\n      return new RedBlackTreeIterator(self, stack, direction)\n    }\n  }\n}\n\n/** @internal */\nexport const lessThanEqualBackwards = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => Iterable<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => Iterable<[K, V]>\n>(2, (self, key) => lessThanEqual(self, key, Direction.Backward))\n\n/** @internal */\nexport const lessThanEqualForwards = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => Iterable<[K, V]>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => Iterable<[K, V]>\n>(2, (self, key) => lessThanEqual(self, key, Direction.Forward))\n\nconst lessThanEqual = <K, V>(\n  self: RBT.RedBlackTree<K, V>,\n  key: K,\n  direction: RBT.RedBlackTree.Direction\n): Iterable<[K, V]> => {\n  return {\n    [Symbol.iterator]: () => {\n      const cmp = (self as RedBlackTreeImpl<K, V>)._ord\n      let node = (self as RedBlackTreeImpl<K, V>)._root\n      const stack = []\n      let last_ptr = 0\n      while (node !== undefined) {\n        const d = cmp(key, node.key)\n        stack.push(node)\n        if (d >= 0) {\n          last_ptr = stack.length\n        }\n        if (d < 0) {\n          node = node.left\n        } else {\n          node = node.right\n        }\n      }\n      stack.length = last_ptr\n      return new RedBlackTreeIterator(self, stack, direction)\n    }\n  }\n}\n\n/** @internal */\nexport const forEach = dual<\n  <K, V>(f: (key: K, value: V) => void) => (self: RBT.RedBlackTree<K, V>) => void,\n  <K, V>(self: RBT.RedBlackTree<K, V>, f: (key: K, value: V) => void) => void\n>(2, <K, V>(self: RBT.RedBlackTree<K, V>, f: (key: K, value: V) => void) => {\n  const root = (self as RedBlackTreeImpl<K, V>)._root\n  if (root !== undefined) {\n    visitFull(root, (key, value) => {\n      f(key, value)\n      return Option.none()\n    })\n  }\n})\n\n/** @internal */\nexport const forEachGreaterThanEqual = dual<\n  <K, V>(min: K, f: (key: K, value: V) => void) => (self: RBT.RedBlackTree<K, V>) => void,\n  <K, V>(self: RBT.RedBlackTree<K, V>, min: K, f: (key: K, value: V) => void) => void\n>(3, <K, V>(self: RBT.RedBlackTree<K, V>, min: K, f: (key: K, value: V) => void) => {\n  const root = (self as RedBlackTreeImpl<K, V>)._root\n  const ord = (self as RedBlackTreeImpl<K, V>)._ord\n  if (root !== undefined) {\n    visitGreaterThanEqual(root, min, ord, (key, value) => {\n      f(key, value)\n      return Option.none()\n    })\n  }\n})\n\n/** @internal */\nexport const forEachLessThan = dual<\n  <K, V>(max: K, f: (key: K, value: V) => void) => (self: RBT.RedBlackTree<K, V>) => void,\n  <K, V>(self: RBT.RedBlackTree<K, V>, max: K, f: (key: K, value: V) => void) => void\n>(3, <K, V>(self: RBT.RedBlackTree<K, V>, max: K, f: (key: K, value: V) => void) => {\n  const root = (self as RedBlackTreeImpl<K, V>)._root\n  const ord = (self as RedBlackTreeImpl<K, V>)._ord\n  if (root !== undefined) {\n    visitLessThan(root, max, ord, (key, value) => {\n      f(key, value)\n      return Option.none()\n    })\n  }\n})\n\n/** @internal */\nexport const forEachBetween = dual<\n  <K, V>(options: {\n    readonly min: K\n    readonly max: K\n    readonly body: (key: K, value: V) => void\n  }) => (self: RBT.RedBlackTree<K, V>) => void,\n  <K, V>(self: RBT.RedBlackTree<K, V>, options: {\n    readonly min: K\n    readonly max: K\n    readonly body: (key: K, value: V) => void\n  }) => void\n>(2, <K, V>(self: RBT.RedBlackTree<K, V>, { body, max, min }: {\n  readonly min: K\n  readonly max: K\n  readonly body: (key: K, value: V) => void\n}) => {\n  const root = (self as RedBlackTreeImpl<K, V>)._root\n  const ord = (self as RedBlackTreeImpl<K, V>)._ord\n  if (root) {\n    visitBetween(root, min, max, ord, (key, value) => {\n      body(key, value)\n      return Option.none()\n    })\n  }\n})\n\n/** @internal */\nexport const reduce = dual<\n  <Z, V, K>(\n    zero: Z,\n    f: (accumulator: Z, value: V, key: K) => Z\n  ) => (self: RBT.RedBlackTree<K, V>) => Z,\n  <Z, V, K>(self: RBT.RedBlackTree<K, V>, zero: Z, f: (accumulator: Z, value: V, key: K) => Z) => Z\n>(3, (self, zero, f) => {\n  let accumulator = zero\n  for (const entry of self) {\n    accumulator = f(accumulator, entry[1], entry[0])\n  }\n  return accumulator\n})\n\n/** @internal */\nexport const removeFirst = dual<\n  <K>(key: K) => <V>(self: RBT.RedBlackTree<K, V>) => RBT.RedBlackTree<K, V>,\n  <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => RBT.RedBlackTree<K, V>\n>(2, <K, V>(self: RBT.RedBlackTree<K, V>, key: K) => {\n  if (!has(self, key)) {\n    return self\n  }\n  const ord = (self as RedBlackTreeImpl<K, V>)._ord\n  const cmp = ord\n  let node: Node.Node<K, V> | undefined = (self as RedBlackTreeImpl<K, V>)._root\n  const stack = []\n  while (node !== undefined) {\n    const d = cmp(key, node.key)\n    stack.push(node)\n    if (Equal.equals(key, node.key)) {\n      node = undefined\n    } else if (d <= 0) {\n      node = node.left\n    } else {\n      node = node.right\n    }\n  }\n  if (stack.length === 0) {\n    return self\n  }\n  const cstack = new Array<Node.Node<K, V>>(stack.length)\n  let n = stack[stack.length - 1]!\n  cstack[cstack.length - 1] = {\n    color: n.color,\n    key: n.key,\n    value: n.value,\n    left: n.left,\n    right: n.right,\n    count: n.count\n  }\n  for (let i = stack.length - 2; i >= 0; --i) {\n    n = stack[i]!\n    if (n.left === stack[i + 1]) {\n      cstack[i] = {\n        color: n.color,\n        key: n.key,\n        value: n.value,\n        left: cstack[i + 1],\n        right: n.right,\n        count: n.count\n      }\n    } else {\n      cstack[i] = {\n        color: n.color,\n        key: n.key,\n        value: n.value,\n        left: n.left,\n        right: cstack[i + 1],\n        count: n.count\n      }\n    }\n  }\n  // Get node\n  n = cstack[cstack.length - 1]!\n  // If not leaf, then swap with previous node\n  if (n.left !== undefined && n.right !== undefined) {\n    // First walk to previous leaf\n    const split = cstack.length\n    n = n.left\n    while (n.right != null) {\n      cstack.push(n)\n      n = n.right\n    }\n    // Copy path to leaf\n    const v = cstack[split - 1]\n    cstack.push({\n      color: n.color,\n      key: v!.key,\n      value: v!.value,\n      left: n.left,\n      right: n.right,\n      count: n.count\n    })\n    cstack[split - 1]!.key = n.key\n    cstack[split - 1]!.value = n.value\n    // Fix up stack\n    for (let i = cstack.length - 2; i >= split; --i) {\n      n = cstack[i]!\n      cstack[i] = {\n        color: n.color,\n        key: n.key,\n        value: n.value,\n        left: n.left,\n        right: cstack[i + 1],\n        count: n.count\n      }\n    }\n    cstack[split - 1]!.left = cstack[split]\n  }\n\n  // Remove leaf node\n  n = cstack[cstack.length - 1]!\n  if (n.color === Node.Color.Red) {\n    // Easy case: removing red leaf\n    const p = cstack[cstack.length - 2]!\n    if (p.left === n) {\n      p.left = undefined\n    } else if (p.right === n) {\n      p.right = undefined\n    }\n    cstack.pop()\n    for (let i = 0; i < cstack.length; ++i) {\n      cstack[i]!.count--\n    }\n    return makeImpl(ord, cstack[0])\n  } else {\n    if (n.left !== undefined || n.right !== undefined) {\n      // Second easy case:  Single child black parent\n      if (n.left !== undefined) {\n        Node.swap(n, n.left)\n      } else if (n.right !== undefined) {\n        Node.swap(n, n.right)\n      }\n      // Child must be red, so repaint it black to balance color\n      n.color = Node.Color.Black\n      for (let i = 0; i < cstack.length - 1; ++i) {\n        cstack[i]!.count--\n      }\n      return makeImpl(ord, cstack[0])\n    } else if (cstack.length === 1) {\n      // Third easy case: root\n      return makeImpl(ord, undefined)\n    } else {\n      // Hard case: Repaint n, and then do some nasty stuff\n      for (let i = 0; i < cstack.length; ++i) {\n        cstack[i]!.count--\n      }\n      const parent = cstack[cstack.length - 2]\n      fixDoubleBlack(cstack)\n      // Fix up links\n      if (parent!.left === n) {\n        parent!.left = undefined\n      } else {\n        parent!.right = undefined\n      }\n    }\n  }\n  return makeImpl(ord, cstack[0])\n})\n\n/** @internal */\nexport const size = <K, V>(self: RBT.RedBlackTree<K, V>): number => (self as RedBlackTreeImpl<K, V>)._root?.count ?? 0\n\n/** @internal */\nexport const valuesForward = <K, V>(self: RBT.RedBlackTree<K, V>): IterableIterator<V> =>\n  values(self, Direction.Forward)\n\n/** @internal */\nexport const valuesBackward = <K, V>(self: RBT.RedBlackTree<K, V>): IterableIterator<V> =>\n  values(self, Direction.Backward)\n\n/** @internal */\nconst values = <K, V>(\n  self: RBT.RedBlackTree<K, V>,\n  direction: RBT.RedBlackTree.Direction\n): IterableIterator<V> => {\n  const begin: RedBlackTreeIterator<K, V> = self[Symbol.iterator]() as RedBlackTreeIterator<K, V>\n  let count = 0\n  return {\n    [Symbol.iterator]: () => values(self, direction),\n    next: (): IteratorResult<V, number> => {\n      count++\n      const entry = begin.value\n      if (direction === Direction.Forward) {\n        begin.moveNext()\n      } else {\n        begin.movePrev()\n      }\n      switch (entry._tag) {\n        case \"None\": {\n          return { done: true, value: count }\n        }\n        case \"Some\": {\n          return { done: false, value: entry.value }\n        }\n      }\n    }\n  }\n}\n\nconst visitFull = <K, V, A>(\n  node: Node.Node<K, V>,\n  visit: (key: K, value: V) => Option.Option<A>\n): Option.Option<A> => {\n  let current: Node.Node<K, V> | undefined = node\n  let stack: Stack.Stack<Node.Node<K, V>> | undefined = undefined\n  let done = false\n  while (!done) {\n    if (current != null) {\n      stack = Stack.make(current, stack)\n      current = current.left\n    } else if (stack != null) {\n      const value = visit(stack.value.key, stack.value.value)\n      if (Option.isSome(value)) {\n        return value\n      }\n      current = stack.value.right\n      stack = stack.previous\n    } else {\n      done = true\n    }\n  }\n  return Option.none()\n}\n\nconst visitGreaterThanEqual = <K, V, A>(\n  node: Node.Node<K, V>,\n  min: K,\n  ord: Order.Order<K>,\n  visit: (key: K, value: V) => Option.Option<A>\n): Option.Option<A> => {\n  let current: Node.Node<K, V> | undefined = node\n  let stack: Stack.Stack<Node.Node<K, V>> | undefined = undefined\n  let done = false\n  while (!done) {\n    if (current !== undefined) {\n      stack = Stack.make(current, stack)\n      if (ord(min, current.key) <= 0) {\n        current = current.left\n      } else {\n        current = undefined\n      }\n    } else if (stack !== undefined) {\n      if (ord(min, stack.value.key) <= 0) {\n        const value = visit(stack.value.key, stack.value.value)\n        if (Option.isSome(value)) {\n          return value\n        }\n      }\n      current = stack.value.right\n      stack = stack.previous\n    } else {\n      done = true\n    }\n  }\n  return Option.none()\n}\n\nconst visitLessThan = <K, V, A>(\n  node: Node.Node<K, V>,\n  max: K,\n  ord: Order.Order<K>,\n  visit: (key: K, value: V) => Option.Option<A>\n): Option.Option<A> => {\n  let current: Node.Node<K, V> | undefined = node\n  let stack: Stack.Stack<Node.Node<K, V>> | undefined = undefined\n  let done = false\n  while (!done) {\n    if (current !== undefined) {\n      stack = Stack.make(current, stack)\n      current = current.left\n    } else if (stack !== undefined && ord(max, stack.value.key) > 0) {\n      const value = visit(stack.value.key, stack.value.value)\n      if (Option.isSome(value)) {\n        return value\n      }\n      current = stack.value.right\n      stack = stack.previous\n    } else {\n      done = true\n    }\n  }\n  return Option.none()\n}\n\nconst visitBetween = <K, V, A>(\n  node: Node.Node<K, V>,\n  min: K,\n  max: K,\n  ord: Order.Order<K>,\n  visit: (key: K, value: V) => Option.Option<A>\n): Option.Option<A> => {\n  let current: Node.Node<K, V> | undefined = node\n  let stack: Stack.Stack<Node.Node<K, V>> | undefined = undefined\n  let done = false\n  while (!done) {\n    if (current !== undefined) {\n      stack = Stack.make(current, stack)\n      if (ord(min, current.key) <= 0) {\n        current = current.left\n      } else {\n        current = undefined\n      }\n    } else if (stack !== undefined && ord(max, stack.value.key) > 0) {\n      if (ord(min, stack.value.key) <= 0) {\n        const value = visit(stack.value.key, stack.value.value)\n        if (Option.isSome(value)) {\n          return value\n        }\n      }\n      current = stack.value.right\n      stack = stack.previous\n    } else {\n      done = true\n    }\n  }\n  return Option.none()\n}\n\n/**\n * Fix up a double black node in a Red-Black Tree.\n */\nconst fixDoubleBlack = <K, V>(stack: Array<Node.Node<K, V>>) => {\n  let n, p, s, z\n  for (let i = stack.length - 1; i >= 0; --i) {\n    n = stack[i]!\n    if (i === 0) {\n      n.color = Node.Color.Black\n      return\n    }\n    p = stack[i - 1]!\n    if (p.left === n) {\n      s = p.right\n      if (s !== undefined && s.right !== undefined && s.right.color === Node.Color.Red) {\n        s = p.right = Node.clone(s)\n        z = s.right = Node.clone(s.right!)\n        p.right = s.left\n        s.left = p\n        s.right = z\n        s.color = p.color\n        n.color = Node.Color.Black\n        p.color = Node.Color.Black\n        z.color = Node.Color.Black\n        Node.recount(p)\n        Node.recount(s)\n        if (i > 1) {\n          const pp = stack[i - 2]!\n          if (pp.left === p) {\n            pp.left = s\n          } else {\n            pp.right = s\n          }\n        }\n        stack[i - 1] = s\n        return\n      } else if (s !== undefined && s.left !== undefined && s.left.color === Node.Color.Red) {\n        s = p.right = Node.clone(s)\n        z = s.left = Node.clone(s.left!)\n        p.right = z.left\n        s.left = z.right\n        z.left = p\n        z.right = s\n        z.color = p.color\n        p.color = Node.Color.Black\n        s.color = Node.Color.Black\n        n.color = Node.Color.Black\n        Node.recount(p)\n        Node.recount(s)\n        Node.recount(z)\n        if (i > 1) {\n          const pp = stack[i - 2]!\n          if (pp.left === p) {\n            pp.left = z\n          } else {\n            pp.right = z\n          }\n        }\n        stack[i - 1] = z\n        return\n      }\n      if (s !== undefined && s.color === Node.Color.Black) {\n        if (p.color === Node.Color.Red) {\n          p.color = Node.Color.Black\n          p.right = Node.repaint(s, Node.Color.Red)\n          return\n        } else {\n          p.right = Node.repaint(s, Node.Color.Red)\n          continue\n        }\n      } else if (s !== undefined) {\n        s = Node.clone(s)\n        p.right = s.left\n        s.left = p\n        s.color = p.color\n        p.color = Node.Color.Red\n        Node.recount(p)\n        Node.recount(s)\n        if (i > 1) {\n          const pp = stack[i - 2]!\n          if (pp.left === p) {\n            pp.left = s\n          } else {\n            pp.right = s\n          }\n        }\n        stack[i - 1] = s\n        stack[i] = p\n        if (i + 1 < stack.length) {\n          stack[i + 1] = n\n        } else {\n          stack.push(n)\n        }\n        i = i + 2\n      }\n    } else {\n      s = p.left\n      if (s !== undefined && s.left !== undefined && s.left.color === Node.Color.Red) {\n        s = p.left = Node.clone(s)\n        z = s.left = Node.clone(s.left!)\n        p.left = s.right\n        s.right = p\n        s.left = z\n        s.color = p.color\n        n.color = Node.Color.Black\n        p.color = Node.Color.Black\n        z.color = Node.Color.Black\n        Node.recount(p)\n        Node.recount(s)\n        if (i > 1) {\n          const pp = stack[i - 2]!\n          if (pp.right === p) {\n            pp.right = s\n          } else {\n            pp.left = s\n          }\n        }\n        stack[i - 1] = s\n        return\n      } else if (s !== undefined && s.right !== undefined && s.right.color === Node.Color.Red) {\n        s = p.left = Node.clone(s)\n        z = s.right = Node.clone(s.right!)\n        p.left = z.right\n        s.right = z.left\n        z.right = p\n        z.left = s\n        z.color = p.color\n        p.color = Node.Color.Black\n        s.color = Node.Color.Black\n        n.color = Node.Color.Black\n        Node.recount(p)\n        Node.recount(s)\n        Node.recount(z)\n        if (i > 1) {\n          const pp = stack[i - 2]!\n          if (pp.right === p) {\n            pp.right = z\n          } else {\n            pp.left = z\n          }\n        }\n        stack[i - 1] = z\n        return\n      }\n      if (s !== undefined && s.color === Node.Color.Black) {\n        if (p.color === Node.Color.Red) {\n          p.color = Node.Color.Black\n          p.left = Node.repaint(s, Node.Color.Red)\n          return\n        } else {\n          p.left = Node.repaint(s, Node.Color.Red)\n          continue\n        }\n      } else if (s !== undefined) {\n        s = Node.clone(s)\n        p.left = s.right\n        s.right = p\n        s.color = p.color\n        p.color = Node.Color.Red\n        Node.recount(p)\n        Node.recount(s)\n        if (i > 1) {\n          const pp = stack[i - 2]!\n          if (pp.right === p) {\n            pp.right = s\n          } else {\n            pp.left = s\n          }\n        }\n        stack[i - 1] = s\n        stack[i] = p\n        if (i + 1 < stack.length) {\n          stack[i + 1] = n\n        } else {\n          stack.push(n)\n        }\n        i = i + 2\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/redacted.ts",
    "content": "import * as Equal from \"../Equal.js\"\nimport { pipe } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport * as Hash from \"../Hash.js\"\nimport { NodeInspectSymbol } from \"../Inspectable.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as Redacted from \"../Redacted.js\"\n\n/** @internal */\nconst RedactedSymbolKey = \"effect/Redacted\"\n\n/** @internal */\nexport const redactedRegistry = globalValue(\n  \"effect/Redacted/redactedRegistry\",\n  () => new WeakMap<Redacted.Redacted<any>, any>()\n)\n\n/** @internal */\nexport const RedactedTypeId: Redacted.RedactedTypeId = Symbol.for(\n  RedactedSymbolKey\n) as Redacted.RedactedTypeId\n\n/** @internal */\nexport const proto = {\n  [RedactedTypeId]: {\n    _A: (_: never) => _\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  toString() {\n    return \"<redacted>\"\n  },\n  toJSON() {\n    return \"<redacted>\"\n  },\n  [NodeInspectSymbol]() {\n    return \"<redacted>\"\n  },\n  [Hash.symbol]<T>(this: Redacted.Redacted<T>): number {\n    return pipe(\n      Hash.hash(RedactedSymbolKey),\n      Hash.combine(Hash.hash(redactedRegistry.get(this))),\n      Hash.cached(this)\n    )\n  },\n  [Equal.symbol]<T>(this: Redacted.Redacted<T>, that: unknown): boolean {\n    return isRedacted(that) && Equal.equals(redactedRegistry.get(this), redactedRegistry.get(that))\n  }\n}\n\n/** @internal */\nexport const isRedacted = (u: unknown): u is Redacted.Redacted<unknown> => hasProperty(u, RedactedTypeId)\n\n/** @internal */\nexport const make = <T>(value: T): Redacted.Redacted<T> => {\n  const redacted = Object.create(proto)\n  redactedRegistry.set(redacted, value)\n  return redacted\n}\n\n/** @internal */\nexport const value = <T>(self: Redacted.Redacted<T>): T => {\n  if (redactedRegistry.has(self)) {\n    return redactedRegistry.get(self)\n  } else {\n    throw new Error(\"Unable to get redacted value\")\n  }\n}\n\n/** @internal */\nexport const unsafeWipe = <T>(self: Redacted.Redacted<T>): boolean => redactedRegistry.delete(self)\n"
  },
  {
    "path": "packages/effect/src/internal/ref.ts",
    "content": "import type * as Effect from \"../Effect.js\"\nimport * as Effectable from \"../Effectable.js\"\nimport { dual } from \"../Function.js\"\nimport * as MutableRef from \"../MutableRef.js\"\nimport * as Option from \"../Option.js\"\nimport * as Readable from \"../Readable.js\"\nimport type * as Ref from \"../Ref.js\"\nimport * as core from \"./core.js\"\n\n/** @internal */\nexport const RefTypeId: Ref.RefTypeId = Symbol.for(\"effect/Ref\") as Ref.RefTypeId\n\n/** @internal */\nexport const refVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\nclass RefImpl<in out A> extends Effectable.Class<A> implements Ref.Ref<A> {\n  commit() {\n    return this.get\n  }\n  readonly [RefTypeId] = refVariance\n  readonly [Readable.TypeId]: Readable.TypeId = Readable.TypeId\n  constructor(readonly ref: MutableRef.MutableRef<A>) {\n    super()\n    this.get = core.sync(() => MutableRef.get(this.ref))\n  }\n  readonly get: Effect.Effect<A>\n  modify<B>(f: (a: A) => readonly [B, A]): Effect.Effect<B> {\n    return core.sync(() => {\n      const current = MutableRef.get(this.ref)\n      const [b, a] = f(current)\n      if ((current as unknown) !== (a as unknown)) {\n        MutableRef.set(a)(this.ref)\n      }\n      return b\n    })\n  }\n}\n\n/** @internal */\nexport const unsafeMake = <A>(value: A): Ref.Ref<A> => new RefImpl(MutableRef.make(value))\n\n/** @internal */\nexport const make = <A>(value: A): Effect.Effect<Ref.Ref<A>> => core.sync(() => unsafeMake(value))\n\n/** @internal */\nexport const get = <A>(self: Ref.Ref<A>) => self.get\n\n/** @internal */\nexport const set = dual<\n  <A>(value: A) => (self: Ref.Ref<A>) => Effect.Effect<void>,\n  <A>(self: Ref.Ref<A>, value: A) => Effect.Effect<void>\n>(2, <A>(self: Ref.Ref<A>, value: A) => self.modify((): [void, A] => [void 0, value]))\n\n/** @internal */\nexport const getAndSet = dual<\n  <A>(value: A) => (self: Ref.Ref<A>) => Effect.Effect<A>,\n  <A>(self: Ref.Ref<A>, value: A) => Effect.Effect<A>\n>(2, <A>(self: Ref.Ref<A>, value: A) => self.modify((a): [A, A] => [a, value]))\n\n/** @internal */\nexport const getAndUpdate = dual<\n  <A>(f: (a: A) => A) => (self: Ref.Ref<A>) => Effect.Effect<A>,\n  <A>(self: Ref.Ref<A>, f: (a: A) => A) => Effect.Effect<A>\n>(2, <A>(self: Ref.Ref<A>, f: (a: A) => A) => self.modify((a): [A, A] => [a, f(a)]))\n\n/** @internal */\nexport const getAndUpdateSome = dual<\n  <A>(pf: (a: A) => Option.Option<A>) => (self: Ref.Ref<A>) => Effect.Effect<A>,\n  <A>(self: Ref.Ref<A>, pf: (a: A) => Option.Option<A>) => Effect.Effect<A>\n>(2, <A>(self: Ref.Ref<A>, pf: (a: A) => Option.Option<A>) =>\n  self.modify((value): [A, A] => {\n    const option = pf(value)\n    switch (option._tag) {\n      case \"None\": {\n        return [value, value]\n      }\n      case \"Some\": {\n        return [value, option.value]\n      }\n    }\n  }))\n\n/** @internal */\nexport const setAndGet = dual<\n  <A>(value: A) => (self: Ref.Ref<A>) => Effect.Effect<A>,\n  <A>(self: Ref.Ref<A>, value: A) => Effect.Effect<A>\n>(2, <A>(self: Ref.Ref<A>, value: A) => self.modify((): [A, A] => [value, value]))\n\n/** @internal */\nexport const modify = dual<\n  <A, B>(f: (a: A) => readonly [B, A]) => (self: Ref.Ref<A>) => Effect.Effect<B>,\n  <A, B>(self: Ref.Ref<A>, f: (a: A) => readonly [B, A]) => Effect.Effect<B>\n>(2, (self, f) => self.modify(f))\n\n/** @internal */\nexport const modifySome = dual<\n  <B, A>(\n    fallback: B,\n    pf: (a: A) => Option.Option<readonly [B, A]>\n  ) => (self: Ref.Ref<A>) => Effect.Effect<B>,\n  <A, B>(\n    self: Ref.Ref<A>,\n    fallback: B,\n    pf: (a: A) => Option.Option<readonly [B, A]>\n  ) => Effect.Effect<B>\n>(3, (self, fallback, pf) =>\n  self.modify((value) => {\n    const option = pf(value)\n    switch (option._tag) {\n      case \"None\": {\n        return [fallback, value]\n      }\n      case \"Some\": {\n        return option.value\n      }\n    }\n  }))\n\n/** @internal */\nexport const update = dual<\n  <A>(f: (a: A) => A) => (self: Ref.Ref<A>) => Effect.Effect<void>,\n  <A>(self: Ref.Ref<A>, f: (a: A) => A) => Effect.Effect<void>\n>(2, <A>(self: Ref.Ref<A>, f: (a: A) => A) => self.modify((a): [void, A] => [void 0, f(a)]))\n\n/** @internal */\nexport const updateAndGet = dual<\n  <A>(f: (a: A) => A) => (self: Ref.Ref<A>) => Effect.Effect<A>,\n  <A>(self: Ref.Ref<A>, f: (a: A) => A) => Effect.Effect<A>\n>(2, <A>(self: Ref.Ref<A>, f: (a: A) => A) =>\n  self.modify((a): [A, A] => {\n    const result = f(a)\n    return [result, result]\n  }))\n\n/** @internal */\nexport const updateSome = dual<\n  <A>(f: (a: A) => Option.Option<A>) => (self: Ref.Ref<A>) => Effect.Effect<void>,\n  <A>(self: Ref.Ref<A>, f: (a: A) => Option.Option<A>) => Effect.Effect<void>\n>(2, <A>(self: Ref.Ref<A>, f: (a: A) => Option.Option<A>) =>\n  self.modify(\n    (a): [void, A] => [\n      void 0,\n      Option.match(f(a), {\n        onNone: () => a,\n        onSome: (b) => b\n      })\n    ]\n  ))\n\n/** @internal */\nexport const updateSomeAndGet = dual<\n  <A>(pf: (a: A) => Option.Option<A>) => (self: Ref.Ref<A>) => Effect.Effect<A>,\n  <A>(self: Ref.Ref<A>, pf: (a: A) => Option.Option<A>) => Effect.Effect<A>\n>(2, <A>(self: Ref.Ref<A>, pf: (a: A) => Option.Option<A>) =>\n  self.modify((value): [A, A] => {\n    const option = pf(value)\n    switch (option._tag) {\n      case \"None\": {\n        return [value, value]\n      }\n      case \"Some\": {\n        return [option.value, option.value]\n      }\n    }\n  }))\n\n/** @internal */\nexport const unsafeGet = <A>(self: Ref.Ref<A>): A => MutableRef.get((self as RefImpl<A>).ref)\n"
  },
  {
    "path": "packages/effect/src/internal/reloadable.ts",
    "content": "import * as Context from \"../Context.js\"\nimport type * as Effect from \"../Effect.js\"\nimport { pipe } from \"../Function.js\"\nimport type * as Layer from \"../Layer.js\"\nimport type * as Reloadable from \"../Reloadable.js\"\nimport type * as Schedule from \"../Schedule.js\"\nimport * as effect from \"./core-effect.js\"\nimport * as core from \"./core.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\nimport * as layer_ from \"./layer.js\"\nimport * as schedule_ from \"./schedule.js\"\nimport * as scopedRef from \"./scopedRef.js\"\n\n/** @internal */\nconst ReloadableSymbolKey = \"effect/Reloadable\"\n\n/** @internal */\nexport const ReloadableTypeId: Reloadable.ReloadableTypeId = Symbol.for(\n  ReloadableSymbolKey\n) as Reloadable.ReloadableTypeId\n\nconst reloadableVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nexport const auto = <I, S, E, In, R>(\n  tag: Context.Tag<I, S>,\n  options: {\n    readonly layer: Layer.Layer<I, E, In>\n    readonly schedule: Schedule.Schedule<unknown, unknown, R>\n  }\n): Layer.Layer<Reloadable.Reloadable<I>, E, R | In> =>\n  layer_.scoped(\n    reloadableTag(tag),\n    pipe(\n      layer_.build(manual(tag, { layer: options.layer })),\n      core.map(Context.unsafeGet(reloadableTag(tag))),\n      core.tap((reloadable) =>\n        fiberRuntime.acquireRelease(\n          pipe(\n            reloadable.reload,\n            effect.ignoreLogged,\n            schedule_.schedule_Effect(options.schedule),\n            fiberRuntime.forkDaemon\n          ),\n          core.interruptFiber\n        )\n      )\n    )\n  )\n\n/** @internal */\nexport const autoFromConfig = <I, S, E, In, R>(\n  tag: Context.Tag<I, S>,\n  options: {\n    readonly layer: Layer.Layer<I, E, In>\n    readonly scheduleFromConfig: (context: Context.Context<In>) => Schedule.Schedule<unknown, unknown, R>\n  }\n): Layer.Layer<Reloadable.Reloadable<I>, E, R | In> =>\n  layer_.scoped(\n    reloadableTag(tag),\n    pipe(\n      core.context<In>(),\n      core.flatMap((env) =>\n        pipe(\n          layer_.build(auto(tag, {\n            layer: options.layer,\n            schedule: options.scheduleFromConfig(env)\n          })),\n          core.map(Context.unsafeGet(reloadableTag(tag)))\n        )\n      )\n    )\n  )\n\n/** @internal */\nexport const get = <I, S>(\n  tag: Context.Tag<I, S>\n): Effect.Effect<S, never, Reloadable.Reloadable<I>> =>\n  core.flatMap(\n    reloadableTag(tag),\n    (reloadable) => scopedRef.get(reloadable.scopedRef)\n  )\n\n/** @internal */\nexport const manual = <I, S, In, E>(\n  tag: Context.Tag<I, S>,\n  options: {\n    readonly layer: Layer.Layer<I, E, In>\n  }\n): Layer.Layer<Reloadable.Reloadable<I>, E, In> =>\n  layer_.scoped(\n    reloadableTag(tag),\n    pipe(\n      core.context<In>(),\n      core.flatMap((env) =>\n        pipe(\n          scopedRef.fromAcquire(pipe(layer_.build(options.layer), core.map(Context.unsafeGet(tag)))),\n          core.map((ref) => ({\n            [ReloadableTypeId]: reloadableVariance,\n            scopedRef: ref,\n            reload: pipe(\n              scopedRef.set(ref, pipe(layer_.build(options.layer), core.map(Context.unsafeGet(tag)))),\n              core.provideContext(env)\n            )\n          }))\n        )\n      )\n    )\n  )\n\n/** @internal */\nexport const reloadableTag = <I, S>(\n  tag: Context.Tag<I, S>\n): Context.Tag<Reloadable.Reloadable<I>, Reloadable.Reloadable<S>> => {\n  return Context.GenericTag<Reloadable.Reloadable<I>, Reloadable.Reloadable<S>>(`effect/Reloadable<${tag.key}>`)\n}\n\n/** @internal */\nexport const reload = <I, S>(\n  tag: Context.Tag<I, S>\n): Effect.Effect<void, unknown, Reloadable.Reloadable<I>> =>\n  core.flatMap(\n    reloadableTag(tag),\n    (reloadable) => reloadable.reload\n  )\n\n/** @internal */\nexport const reloadFork = <I, S>(\n  tag: Context.Tag<I, S>\n): Effect.Effect<void, unknown, Reloadable.Reloadable<I>> =>\n  core.flatMap(reloadableTag(tag), (reloadable) =>\n    pipe(\n      reloadable.reload,\n      effect.ignoreLogged,\n      fiberRuntime.forkDaemon,\n      core.asVoid\n    ))\n"
  },
  {
    "path": "packages/effect/src/internal/request.ts",
    "content": "import type * as Cause from \"../Cause.js\"\nimport type * as Effect from \"../Effect.js\"\nimport { dual } from \"../Function.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as Request from \"../Request.js\"\nimport type * as Types from \"../Types.js\"\nimport * as completedRequestMap from \"./completedRequestMap.js\"\nimport * as core from \"./core.js\"\nimport { StructuralPrototype } from \"./effectable.js\"\n\n/** @internal */\nconst RequestSymbolKey = \"effect/Request\"\n\n/** @internal */\nexport const RequestTypeId: Request.RequestTypeId = Symbol.for(\n  RequestSymbolKey\n) as Request.RequestTypeId\n\nconst requestVariance = {\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _A: (_: never) => _\n}\n\nconst RequestPrototype = {\n  ...StructuralPrototype,\n  [RequestTypeId]: requestVariance\n}\n\n/** @internal */\nexport const isRequest = (u: unknown): u is Request.Request<unknown, unknown> => hasProperty(u, RequestTypeId)\n\n/** @internal */\nexport const of = <R extends Request.Request<any, any>>(): Request.Request.Constructor<R> => (args) =>\n  Object.assign(Object.create(RequestPrototype), args)\n\n/** @internal */\nexport const tagged = <R extends Request.Request<any, any> & { _tag: string }>(\n  tag: R[\"_tag\"]\n): Request.Request.Constructor<R, \"_tag\"> =>\n(args) => {\n  const request = Object.assign(Object.create(RequestPrototype), args)\n  request._tag = tag\n  return request\n}\n\n/** @internal */\nexport const Class: new<Success, Error, A extends Record<string, any>>(\n  args: Types.Equals<Omit<A, keyof Request.Request<unknown, unknown>>, {}> extends true ? void\n    : { readonly [P in keyof A as P extends keyof Request.Request<unknown, unknown> ? never : P]: A[P] }\n) => Request.Request<Success, Error> & Readonly<A> = (function() {\n  function Class(this: any, args: any) {\n    if (args) {\n      Object.assign(this, args)\n    }\n  }\n  Class.prototype = RequestPrototype\n  return Class as any\n})()\n\n/** @internal */\nexport const TaggedClass = <Tag extends string>(\n  tag: Tag\n): new<Success, Error, A extends Record<string, any>>(\n  args: Types.Equals<Omit<A, keyof Request.Request<unknown, unknown>>, {}> extends true ? void\n    : { readonly [P in keyof A as P extends \"_tag\" | keyof Request.Request<unknown, unknown> ? never : P]: A[P] }\n) => Request.Request<Success, Error> & Readonly<A> & { readonly _tag: Tag } => {\n  return class TaggedClass extends Class<any, any, any> {\n    readonly _tag = tag\n  } as any\n}\n\n/** @internal */\nexport const complete = dual<\n  <A extends Request.Request<any, any>>(\n    result: Request.Request.Result<A>\n  ) => (self: A) => Effect.Effect<void>,\n  <A extends Request.Request<any, any>>(\n    self: A,\n    result: Request.Request.Result<A>\n  ) => Effect.Effect<void>\n>(2, (self, result) =>\n  core.fiberRefGetWith(\n    completedRequestMap.currentRequestMap,\n    (map) =>\n      core.sync(() => {\n        if (map.has(self)) {\n          const entry = map.get(self)!\n          if (!entry.state.completed) {\n            entry.state.completed = true\n            core.deferredUnsafeDone(entry.result, result)\n          }\n        }\n      })\n  ))\n\n/** @internal */\nexport const completeEffect = dual<\n  <A extends Request.Request<any, any>, R>(\n    effect: Effect.Effect<Request.Request.Success<A>, Request.Request.Error<A>, R>\n  ) => (self: A) => Effect.Effect<void, never, R>,\n  <A extends Request.Request<any, any>, R>(\n    self: A,\n    effect: Effect.Effect<Request.Request.Success<A>, Request.Request.Error<A>, R>\n  ) => Effect.Effect<void, never, R>\n>(2, (self, effect) =>\n  core.matchEffect(effect, {\n    onFailure: (error) => complete(self, core.exitFail(error) as any),\n    onSuccess: (value) => complete(self, core.exitSucceed(value) as any)\n  }))\n\n/** @internal */\nexport const fail = dual<\n  <A extends Request.Request<any, any>>(\n    error: Request.Request.Error<A>\n  ) => (self: A) => Effect.Effect<void>,\n  <A extends Request.Request<any, any>>(\n    self: A,\n    error: Request.Request.Error<A>\n  ) => Effect.Effect<void>\n>(2, (self, error) => complete(self, core.exitFail(error) as any))\n\n/** @internal */\nexport const failCause = dual<\n  <A extends Request.Request<any, any>>(\n    cause: Cause.Cause<Request.Request.Error<A>>\n  ) => (self: A) => Effect.Effect<void>,\n  <A extends Request.Request<any, any>>(\n    self: A,\n    cause: Cause.Cause<Request.Request.Error<A>>\n  ) => Effect.Effect<void>\n>(2, (self, cause) => complete(self, core.exitFailCause(cause) as any))\n\n/** @internal */\nexport const succeed = dual<\n  <A extends Request.Request<any, any>>(\n    value: Request.Request.Success<A>\n  ) => (self: A) => Effect.Effect<void>,\n  <A extends Request.Request<any, any>>(\n    self: A,\n    value: Request.Request.Success<A>\n  ) => Effect.Effect<void>\n>(2, (self, value) => complete(self, core.exitSucceed(value) as any))\n\n/** @internal */\nexport class Listeners {\n  count = 0\n  observers: Set<(count: number) => void> = new Set()\n  interrupted = false\n  addObserver(f: (count: number) => void): void {\n    this.observers.add(f)\n  }\n  removeObserver(f: (count: number) => void): void {\n    this.observers.delete(f)\n  }\n  increment() {\n    this.count++\n    this.observers.forEach((f) => f(this.count))\n  }\n  decrement() {\n    this.count--\n    this.observers.forEach((f) => f(this.count))\n  }\n}\n\n/**\n * @internal\n */\nexport const filterOutCompleted = <A extends Request.Request<any, any>>(requests: Array<A>) =>\n  core.fiberRefGetWith(\n    completedRequestMap.currentRequestMap,\n    (map) =>\n      core.succeed(\n        requests.filter((request) => !(map.get(request)?.state.completed === true))\n      )\n  )\n"
  },
  {
    "path": "packages/effect/src/internal/resource.ts",
    "content": "import type * as Effect from \"../Effect.js\"\nimport { identity, pipe } from \"../Function.js\"\nimport type * as Resource from \"../Resource.js\"\nimport type * as Schedule from \"../Schedule.js\"\nimport type * as Scope from \"../Scope.js\"\nimport * as core from \"./core.js\"\nimport * as effectable from \"./effectable.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\nimport * as schedule_ from \"./schedule.js\"\nimport * as scopedRef from \"./scopedRef.js\"\n\n/** @internal */\nconst ResourceSymbolKey = \"effect/Resource\"\n\n/** @internal */\nexport const ResourceTypeId: Resource.ResourceTypeId = Symbol.for(\n  ResourceSymbolKey\n) as Resource.ResourceTypeId\n\nconst resourceVariance = {\n  /* c8 ignore next */\n  _E: (_: any) => _,\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal  */\nconst proto: ThisType<Resource.Resource<any, any>> = {\n  ...effectable.CommitPrototype,\n  commit() {\n    return get(this)\n  },\n  [ResourceTypeId]: resourceVariance\n}\n\n/** @internal */\nexport const auto = <A, E, R, Out, R2>(\n  acquire: Effect.Effect<A, E, R>,\n  policy: Schedule.Schedule<Out, unknown, R2>\n): Effect.Effect<Resource.Resource<A, E>, never, R | R2 | Scope.Scope> =>\n  core.tap(manual(acquire), (manual) =>\n    fiberRuntime.acquireRelease(\n      pipe(\n        refresh(manual),\n        schedule_.schedule_Effect(policy),\n        core.interruptible,\n        fiberRuntime.forkDaemon\n      ),\n      core.interruptFiber\n    ))\n\n/** @internal */\nexport const manual = <A, E, R>(\n  acquire: Effect.Effect<A, E, R>\n): Effect.Effect<Resource.Resource<A, E>, never, R | Scope.Scope> =>\n  core.flatMap(core.context<R>(), (env) =>\n    pipe(\n      scopedRef.fromAcquire(core.exit(acquire)),\n      core.map((ref) => {\n        const resource = Object.create(proto)\n        resource.scopedRef = ref\n        resource.acquire = core.provideContext(acquire, env)\n        return resource\n      })\n    ))\n\n/** @internal */\nexport const get = <A, E>(self: Resource.Resource<A, E>): Effect.Effect<A, E> =>\n  core.flatMap(scopedRef.get(self.scopedRef), identity)\n\n/** @internal */\nexport const refresh = <A, E>(self: Resource.Resource<A, E>): Effect.Effect<void, E> =>\n  scopedRef.set(\n    self.scopedRef,\n    core.map(self.acquire, core.exitSucceed)\n  )\n"
  },
  {
    "path": "packages/effect/src/internal/ringBuffer.ts",
    "content": "import * as Chunk from \"../Chunk.js\"\nimport { constUndefined } from \"../Function.js\"\nimport * as Option from \"../Option.js\"\n\n/** @internal */\nexport class RingBuffer<out A> {\n  private array: Array<A | undefined>\n  private size = 0\n  private current = 0\n\n  constructor(public readonly capacity: number) {\n    this.array = Array.from({ length: capacity }, constUndefined)\n  }\n\n  head(): Option.Option<A> {\n    return Option.fromNullable(this.array[this.current])\n  }\n\n  lastOrNull(): A | undefined {\n    if (this.size === 0) {\n      return undefined\n    }\n\n    const index = this.current === 0 ? this.array.length - 1 : this.current - 1\n\n    return this.array[index] ?? undefined\n  }\n\n  put(value: A): void {\n    this.array[this.current] = value\n    this.increment()\n  }\n\n  dropLast(): void {\n    if (this.size > 0) {\n      this.decrement()\n      this.array[this.current] = undefined\n    }\n  }\n\n  toChunk(): Chunk.Chunk<A> {\n    const begin = this.current - this.size\n    const newArray = begin < 0\n      ? [\n        ...this.array.slice(this.capacity + begin, this.capacity),\n        ...this.array.slice(0, this.current)\n      ]\n      : this.array.slice(begin, this.current)\n\n    return Chunk.fromIterable(newArray) as Chunk.Chunk<A>\n  }\n\n  private increment(): void {\n    if (this.size < this.capacity) {\n      this.size += 1\n    }\n    this.current = (this.current + 1) % this.capacity\n  }\n\n  private decrement(): void {\n    this.size -= 1\n    if (this.current > 0) {\n      this.current -= 1\n    } else {\n      this.current = this.capacity - 1\n    }\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/runtime.ts",
    "content": "import type * as ReadonlyArray from \"../Array.js\"\nimport type * as Cause from \"../Cause.js\"\nimport * as Context from \"../Context.js\"\nimport type * as Effect from \"../Effect.js\"\nimport { equals } from \"../Equal.js\"\nimport * as Exit from \"../Exit.js\"\nimport * as Fiber from \"../Fiber.js\"\nimport * as FiberId from \"../FiberId.js\"\nimport type * as FiberRef from \"../FiberRef.js\"\nimport * as FiberRefs from \"../FiberRefs.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport * as Inspectable from \"../Inspectable.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport * as Predicate from \"../Predicate.js\"\nimport type * as Runtime from \"../Runtime.js\"\nimport type * as RuntimeFlags from \"../RuntimeFlags.js\"\nimport * as scheduler_ from \"../Scheduler.js\"\nimport * as scope_ from \"../Scope.js\"\nimport * as InternalCause from \"./cause.js\"\nimport * as core from \"./core.js\"\nimport * as executionStrategy from \"./executionStrategy.js\"\nimport * as FiberRuntime from \"./fiberRuntime.js\"\nimport * as fiberScope from \"./fiberScope.js\"\nimport * as OpCodes from \"./opCodes/effect.js\"\nimport * as runtimeFlags from \"./runtimeFlags.js\"\nimport * as supervisor_ from \"./supervisor.js\"\n\nconst makeDual = <Args extends Array<any>, Return>(\n  f: (runtime: Runtime.Runtime<never>, effect: Effect.Effect<any, any>, ...args: Args) => Return\n): {\n  <R>(runtime: Runtime.Runtime<R>): <A, E>(effect: Effect.Effect<A, E, R>, ...args: Args) => Return\n  <R, A, E>(runtime: Runtime.Runtime<R>, effect: Effect.Effect<A, E, R>, ...args: Args): Return\n} =>\n  function(this: any) {\n    if (arguments.length === 1) {\n      const runtime = arguments[0]\n      return (effect: any, ...args: Args) => f(runtime, effect, ...args)\n    }\n    return f.apply(this, arguments as any)\n  } as any\n\n/** @internal */\nexport const unsafeFork: {\n  <R>(runtime: Runtime.Runtime<R>): <A, E>(\n    effect: Effect.Effect<A, E, R>,\n    options?: Runtime.RunForkOptions | undefined\n  ) => Fiber.RuntimeFiber<A, E>\n  <R, A, E>(\n    runtime: Runtime.Runtime<R>,\n    effect: Effect.Effect<A, E, R>,\n    options?: Runtime.RunForkOptions | undefined\n  ): Fiber.RuntimeFiber<A, E>\n} = makeDual(<R, A, E>(\n  runtime: Runtime.Runtime<R>,\n  self: Effect.Effect<A, E, R>,\n  options?: Runtime.RunForkOptions\n): Fiber.RuntimeFiber<A, E> => {\n  const fiberId = FiberId.unsafeMake()\n  const fiberRefUpdates: ReadonlyArray.NonEmptyArray<\n    readonly [FiberRef.FiberRef<any>, ReadonlyArray.NonEmptyReadonlyArray<readonly [FiberId.Runtime, any]>]\n  > = [[core.currentContext, [[fiberId, runtime.context]]]]\n\n  if (options?.scheduler) {\n    fiberRefUpdates.push([scheduler_.currentScheduler, [[fiberId, options.scheduler]]])\n  }\n\n  let fiberRefs = FiberRefs.updateManyAs(runtime.fiberRefs, {\n    entries: fiberRefUpdates,\n    forkAs: fiberId\n  })\n\n  if (options?.updateRefs) {\n    fiberRefs = options.updateRefs(fiberRefs, fiberId)\n  }\n\n  const fiberRuntime: FiberRuntime.FiberRuntime<A, E> = new FiberRuntime.FiberRuntime<A, E>(\n    fiberId,\n    fiberRefs,\n    runtime.runtimeFlags\n  )\n\n  let effect: Effect.Effect<A, E, R> = self\n\n  if (options?.scope) {\n    effect = core.flatMap(\n      scope_.fork(options.scope, executionStrategy.sequential),\n      (closeableScope) =>\n        core.zipRight(\n          core.scopeAddFinalizer(\n            closeableScope,\n            core.fiberIdWith((id) =>\n              equals(id, fiberRuntime.id()) ? core.void : core.interruptAsFiber(fiberRuntime, id)\n            )\n          ),\n          core.onExit(self, (exit) => scope_.close(closeableScope, exit))\n        )\n    )\n  }\n\n  const supervisor = fiberRuntime.currentSupervisor\n\n  // we can compare by reference here as _supervisor.none is wrapped with globalValue\n  if (supervisor !== supervisor_.none) {\n    supervisor.onStart(runtime.context, effect, Option.none(), fiberRuntime)\n\n    fiberRuntime.addObserver((exit) => supervisor.onEnd(exit, fiberRuntime))\n  }\n\n  fiberScope.globalScope.add(runtime.runtimeFlags, fiberRuntime)\n\n  // Only an explicit false will prevent immediate execution\n  if (options?.immediate === false) {\n    fiberRuntime.resume(effect)\n  } else {\n    fiberRuntime.start(effect)\n  }\n\n  return fiberRuntime\n})\n\n/** @internal */\nexport const unsafeRunCallback: {\n  <R>(runtime: Runtime.Runtime<R>): <A, E>(\n    effect: Effect.Effect<A, E, R>,\n    options?: Runtime.RunCallbackOptions<A, E> | undefined\n  ) => (fiberId?: FiberId.FiberId, options?: Runtime.RunCallbackOptions<A, E> | undefined) => void\n  <R, A, E>(\n    runtime: Runtime.Runtime<R>,\n    effect: Effect.Effect<A, E, R>,\n    options?: Runtime.RunCallbackOptions<A, E> | undefined\n  ): (fiberId?: FiberId.FiberId, options?: Runtime.RunCallbackOptions<A, E> | undefined) => void\n} = makeDual((\n  runtime,\n  effect,\n  options: Runtime.RunCallbackOptions<any, any> = {}\n): (fiberId?: FiberId.FiberId, options?: Runtime.RunCallbackOptions<any, any> | undefined) => void => {\n  const fiberRuntime = unsafeFork(runtime, effect, options)\n\n  if (options.onExit) {\n    fiberRuntime.addObserver((exit) => {\n      options.onExit!(exit)\n    })\n  }\n\n  return (id, cancelOptions) =>\n    unsafeRunCallback(runtime)(\n      pipe(fiberRuntime, Fiber.interruptAs(id ?? FiberId.none)),\n      {\n        ...cancelOptions,\n        onExit: cancelOptions?.onExit\n          ? (exit) => cancelOptions.onExit!(Exit.flatten(exit))\n          : undefined\n      }\n    )\n})\n\n/** @internal */\nexport const unsafeRunSync: {\n  <A, E, R>(runtime: Runtime.Runtime<R>, effect: Effect.Effect<A, E, R>): A\n  <R>(runtime: Runtime.Runtime<R>): <A, E>(effect: Effect.Effect<A, E, R>) => A\n} = makeDual((runtime, effect) => {\n  const result = unsafeRunSyncExit(runtime)(effect)\n  if (result._tag === \"Failure\") {\n    throw fiberFailure(result.effect_instruction_i0)\n  }\n  return result.effect_instruction_i0\n})\n\nclass AsyncFiberExceptionImpl<A, E = never> extends Error implements Runtime.AsyncFiberException<A, E> {\n  readonly _tag = \"AsyncFiberException\"\n  constructor(readonly fiber: Fiber.RuntimeFiber<A, E>) {\n    super(\n      `Fiber #${fiber.id().id} cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work`\n    )\n    this.name = this._tag\n    this.stack = this.message\n  }\n}\n\nconst asyncFiberException = <A, E>(fiber: Fiber.RuntimeFiber<A, E>): Runtime.AsyncFiberException<A, E> => {\n  const limit = Error.stackTraceLimit\n  Error.stackTraceLimit = 0\n  const error = new AsyncFiberExceptionImpl(fiber)\n  Error.stackTraceLimit = limit\n  return error\n}\n\n/** @internal */\nexport const isAsyncFiberException = (u: unknown): u is Runtime.AsyncFiberException<unknown, unknown> =>\n  Predicate.isTagged(u, \"AsyncFiberException\") && \"fiber\" in u\n\n/** @internal */\nexport const FiberFailureId: Runtime.FiberFailureId = Symbol.for(\"effect/Runtime/FiberFailure\") as any\n/** @internal */\nexport const FiberFailureCauseId: Runtime.FiberFailureCauseId = Symbol.for(\n  \"effect/Runtime/FiberFailure/Cause\"\n) as any\n\nclass FiberFailureImpl extends Error implements Runtime.FiberFailure {\n  readonly [FiberFailureId]: Runtime.FiberFailureId\n  readonly [FiberFailureCauseId]: Cause.Cause<unknown>\n  constructor(cause: Cause.Cause<unknown>) {\n    const head = InternalCause.prettyErrors(cause)[0]\n\n    super(head?.message || \"An error has occurred\")\n    this[FiberFailureId] = FiberFailureId\n    this[FiberFailureCauseId] = cause\n\n    this.name = head ? `(FiberFailure) ${head.name}` : \"FiberFailure\"\n    if (head?.stack) {\n      this.stack = head.stack\n    }\n  }\n\n  toJSON(): unknown {\n    return {\n      _id: \"FiberFailure\",\n      cause: this[FiberFailureCauseId].toJSON()\n    }\n  }\n\n  toString(): string {\n    return \"(FiberFailure) \" + InternalCause.pretty(this[FiberFailureCauseId], { renderErrorCause: true })\n  }\n  [Inspectable.NodeInspectSymbol](): unknown {\n    return this.toString()\n  }\n}\n\n/** @internal */\nexport const fiberFailure = <E>(cause: Cause.Cause<E>): Runtime.FiberFailure => {\n  const limit = Error.stackTraceLimit\n  Error.stackTraceLimit = 0\n  const error = new FiberFailureImpl(cause)\n  Error.stackTraceLimit = limit\n  return error\n}\n\n/** @internal */\nexport const isFiberFailure = (u: unknown): u is Runtime.FiberFailure => Predicate.hasProperty(u, FiberFailureId)\n\nconst fastPath = <A, E, R>(effect: Effect.Effect<A, E, R>): Exit.Exit<A, E> | undefined => {\n  const op = effect as core.Primitive\n  switch (op._op) {\n    case \"Failure\":\n    case \"Success\": {\n      // @ts-expect-error\n      return op\n    }\n    case \"Left\": {\n      return core.exitFail(op.left)\n    }\n    case \"Right\": {\n      return core.exitSucceed(op.right)\n    }\n    case \"Some\": {\n      return core.exitSucceed(op.value)\n    }\n    case \"None\": {\n      // @ts-expect-error\n      return core.exitFail(new core.NoSuchElementException())\n    }\n  }\n}\n\n/** @internal */\nexport const unsafeRunSyncExit: {\n  <A, E, R>(runtime: Runtime.Runtime<R>, effect: Effect.Effect<A, E, R>): Exit.Exit<A, E>\n  <R>(runtime: Runtime.Runtime<R>): <A, E>(effect: Effect.Effect<A, E, R>) => Exit.Exit<A, E>\n} = makeDual((runtime, effect) => {\n  const op = fastPath(effect)\n  if (op) {\n    return op\n  }\n  const scheduler = new scheduler_.SyncScheduler()\n  const fiberRuntime = unsafeFork(runtime)(effect, { scheduler })\n  scheduler.flush()\n  const result = fiberRuntime.unsafePoll()\n  if (result) {\n    return result\n  }\n  return core.exitDie(core.capture(asyncFiberException(fiberRuntime), core.currentSpanFromFiber(fiberRuntime)))\n})\n\n/** @internal */\nexport const unsafeRunPromise: {\n  <R>(runtime: Runtime.Runtime<R>): <A, E>(\n    effect: Effect.Effect<A, E, R>,\n    options?: {\n      readonly signal?: AbortSignal | undefined\n    } | undefined\n  ) => Promise<A>\n  <R, A, E>(\n    runtime: Runtime.Runtime<R>,\n    effect: Effect.Effect<A, E, R>,\n    options?: {\n      readonly signal?: AbortSignal | undefined\n    } | undefined\n  ): Promise<A>\n} = makeDual((\n  runtime,\n  effect,\n  options?: {\n    readonly signal?: AbortSignal | undefined\n  } | undefined\n) =>\n  unsafeRunPromiseExit(runtime, effect, options).then((result) => {\n    switch (result._tag) {\n      case OpCodes.OP_SUCCESS: {\n        return result.effect_instruction_i0\n      }\n      case OpCodes.OP_FAILURE: {\n        throw fiberFailure(result.effect_instruction_i0)\n      }\n    }\n  })\n)\n\n/** @internal */\nexport const unsafeRunPromiseExit: {\n  <R>(\n    runtime: Runtime.Runtime<R>\n  ): <A, E>(\n    effect: Effect.Effect<A, E, R>,\n    options?: { readonly signal?: AbortSignal | undefined } | undefined\n  ) => Promise<Exit.Exit<A, E>>\n  <R, A, E>(\n    runtime: Runtime.Runtime<R>,\n    effect: Effect.Effect<A, E, R>,\n    options?: { readonly signal?: AbortSignal | undefined } | undefined\n  ): Promise<Exit.Exit<A, E>>\n} = makeDual((\n  runtime,\n  effect,\n  options?: {\n    readonly signal?: AbortSignal | undefined\n  } | undefined\n) =>\n  new Promise<Exit.Exit<any, any>>((resolve) => {\n    const op = fastPath(effect)\n    if (op) {\n      resolve(op)\n    }\n    const fiber = unsafeFork(runtime)(effect)\n    fiber.addObserver((exit) => {\n      resolve(exit)\n    })\n    if (options?.signal !== undefined) {\n      if (options.signal.aborted) {\n        fiber.unsafeInterruptAsFork(fiber.id())\n      } else {\n        options.signal.addEventListener(\"abort\", () => {\n          fiber.unsafeInterruptAsFork(fiber.id())\n        }, { once: true })\n      }\n    }\n  })\n)\n\n/** @internal */\nexport class RuntimeImpl<in R> implements Runtime.Runtime<R> {\n  constructor(\n    readonly context: Context.Context<R>,\n    readonly runtimeFlags: RuntimeFlags.RuntimeFlags,\n    readonly fiberRefs: FiberRefs.FiberRefs\n  ) {}\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const make = <R>(\n  options: {\n    readonly context: Context.Context<R>\n    readonly runtimeFlags: RuntimeFlags.RuntimeFlags\n    readonly fiberRefs: FiberRefs.FiberRefs\n  }\n): Runtime.Runtime<R> => new RuntimeImpl(options.context, options.runtimeFlags, options.fiberRefs)\n\n/** @internal */\nexport const runtime = <R>(): Effect.Effect<Runtime.Runtime<R>, never, R> =>\n  core.withFiberRuntime((state, status) =>\n    core.succeed(\n      new RuntimeImpl<R>(\n        state.getFiberRef(core.currentContext as unknown as FiberRef.FiberRef<Context.Context<R>>),\n        status.runtimeFlags,\n        state.getFiberRefs()\n      )\n    )\n  )\n\n/** @internal */\nexport const defaultRuntimeFlags: RuntimeFlags.RuntimeFlags = runtimeFlags.make(\n  runtimeFlags.Interruption,\n  runtimeFlags.CooperativeYielding,\n  runtimeFlags.RuntimeMetrics\n)\n\n/** @internal */\nexport const defaultRuntime = make({\n  context: Context.empty(),\n  runtimeFlags: defaultRuntimeFlags,\n  fiberRefs: FiberRefs.empty()\n})\n\n/** @internal */\nexport const updateRuntimeFlags: {\n  (\n    f: (flags: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags\n  ): <R>(self: Runtime.Runtime<R>) => Runtime.Runtime<R>\n  <R>(self: Runtime.Runtime<R>, f: (flags: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags): Runtime.Runtime<R>\n} = dual(\n  2,\n  <R>(self: Runtime.Runtime<R>, f: (flags: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags) =>\n    make({\n      context: self.context,\n      runtimeFlags: f(self.runtimeFlags),\n      fiberRefs: self.fiberRefs\n    })\n)\n\n/** @internal */\nexport const disableRuntimeFlag: {\n  (flag: RuntimeFlags.RuntimeFlag): <R>(self: Runtime.Runtime<R>) => Runtime.Runtime<R>\n  <R>(self: Runtime.Runtime<R>, flag: RuntimeFlags.RuntimeFlag): Runtime.Runtime<R>\n} = dual(\n  2,\n  <R>(self: Runtime.Runtime<R>, flag: RuntimeFlags.RuntimeFlag) => updateRuntimeFlags(self, runtimeFlags.disable(flag))\n)\n\n/** @internal */\nexport const enableRuntimeFlag: {\n  (flag: RuntimeFlags.RuntimeFlag): <R>(self: Runtime.Runtime<R>) => Runtime.Runtime<R>\n  <R>(self: Runtime.Runtime<R>, flag: RuntimeFlags.RuntimeFlag): Runtime.Runtime<R>\n} = dual(\n  2,\n  <R>(self: Runtime.Runtime<R>, flag: RuntimeFlags.RuntimeFlag) => updateRuntimeFlags(self, runtimeFlags.enable(flag))\n)\n\n/** @internal */\nexport const updateContext: {\n  <R, R2>(f: (context: Context.Context<R>) => Context.Context<R2>): (self: Runtime.Runtime<R>) => Runtime.Runtime<R2>\n  <R, R2>(self: Runtime.Runtime<R>, f: (context: Context.Context<R>) => Context.Context<R2>): Runtime.Runtime<R2>\n} = dual(\n  2,\n  <R, R2>(self: Runtime.Runtime<R>, f: (context: Context.Context<R>) => Context.Context<R2>) =>\n    make({\n      context: f(self.context),\n      runtimeFlags: self.runtimeFlags,\n      fiberRefs: self.fiberRefs\n    })\n)\n\n/** @internal */\nexport const provideService: {\n  <I, S>(tag: Context.Tag<I, S>, service: S): <R>(self: Runtime.Runtime<R>) => Runtime.Runtime<R | I>\n  <R, I, S>(self: Runtime.Runtime<R>, tag: Context.Tag<I, S>, service: S): Runtime.Runtime<R | I>\n} = dual(\n  3,\n  <R, I, S>(self: Runtime.Runtime<R>, tag: Context.Tag<I, S>, service: S) =>\n    updateContext(self, Context.add(tag, service))\n)\n\n/** @internal */\nexport const updateFiberRefs: {\n  (f: (fiberRefs: FiberRefs.FiberRefs) => FiberRefs.FiberRefs): <R>(self: Runtime.Runtime<R>) => Runtime.Runtime<R>\n  <R>(self: Runtime.Runtime<R>, f: (fiberRefs: FiberRefs.FiberRefs) => FiberRefs.FiberRefs): Runtime.Runtime<R>\n} = dual(\n  2,\n  <R>(self: Runtime.Runtime<R>, f: (fiberRefs: FiberRefs.FiberRefs) => FiberRefs.FiberRefs): Runtime.Runtime<R> =>\n    make({\n      context: self.context,\n      runtimeFlags: self.runtimeFlags,\n      fiberRefs: f(self.fiberRefs)\n    })\n)\n\n/** @internal */\nexport const setFiberRef: {\n  <A>(fiberRef: FiberRef.FiberRef<A>, value: A): <R>(self: Runtime.Runtime<R>) => Runtime.Runtime<R>\n  <R, A>(self: Runtime.Runtime<R>, fiberRef: FiberRef.FiberRef<A>, value: A): Runtime.Runtime<R>\n} = dual(\n  3,\n  <R, A>(self: Runtime.Runtime<R>, fiberRef: FiberRef.FiberRef<A>, value: A): Runtime.Runtime<R> =>\n    updateFiberRefs(\n      self,\n      FiberRefs.updateAs({\n        fiberId: FiberId.none,\n        fiberRef,\n        value\n      })\n    )\n)\n\n/** @internal */\nexport const deleteFiberRef: {\n  <A>(fiberRef: FiberRef.FiberRef<A>): <R>(self: Runtime.Runtime<R>) => Runtime.Runtime<R>\n  <R, A>(self: Runtime.Runtime<R>, fiberRef: FiberRef.FiberRef<A>): Runtime.Runtime<R>\n} = dual(\n  2,\n  <R, A>(self: Runtime.Runtime<R>, fiberRef: FiberRef.FiberRef<A>): Runtime.Runtime<R> =>\n    updateFiberRefs(self, FiberRefs.delete(fiberRef))\n)\n\n/** @internal */\nexport const unsafeRunEffect = unsafeRunCallback(defaultRuntime)\n\n/** @internal */\nexport const unsafeForkEffect = unsafeFork(defaultRuntime)\n\n/** @internal */\nexport const unsafeRunPromiseEffect = unsafeRunPromise(defaultRuntime)\n\n/** @internal */\nexport const unsafeRunPromiseExitEffect = unsafeRunPromiseExit(defaultRuntime)\n\n/** @internal */\nexport const unsafeRunSyncEffect = unsafeRunSync(defaultRuntime)\n\n/** @internal */\nexport const unsafeRunSyncExitEffect = unsafeRunSyncExit(defaultRuntime)\n\n// circular with Effect\n\n/** @internal */\nexport const asyncEffect = <A, E, R, R3, E2, R2>(\n  register: (\n    callback: (_: Effect.Effect<A, E, R>) => void\n  ) => Effect.Effect<Effect.Effect<void, never, R3> | void, E2, R2>\n): Effect.Effect<A, E | E2, R | R2 | R3> =>\n  core.suspend(() => {\n    let cleanup: Effect.Effect<void, never, R3> | void = undefined\n    return core.flatMap(\n      core.deferredMake<A, E | E2>(),\n      (deferred) =>\n        core.flatMap(runtime<R | R2 | R3>(), (runtime) =>\n          core.uninterruptibleMask((restore) =>\n            core.zipRight(\n              FiberRuntime.fork(restore(\n                core.matchCauseEffect(\n                  register((cb) => unsafeRunCallback(runtime)(core.intoDeferred(cb, deferred))),\n                  {\n                    onFailure: (cause) => core.deferredFailCause(deferred, cause),\n                    onSuccess: (cleanup_) => {\n                      cleanup = cleanup_\n                      return core.void\n                    }\n                  }\n                )\n              )),\n              restore(core.onInterrupt(core.deferredAwait(deferred), () => cleanup ?? core.void))\n            )\n          ))\n    )\n  })\n"
  },
  {
    "path": "packages/effect/src/internal/runtimeFlags.ts",
    "content": "import type * as Differ from \"../Differ.js\"\nimport { dual } from \"../Function.js\"\nimport type * as RuntimeFlags from \"../RuntimeFlags.js\"\nimport type * as RuntimeFlagsPatch from \"../RuntimeFlagsPatch.js\"\nimport * as internalDiffer from \"./differ.js\"\nimport * as runtimeFlagsPatch from \"./runtimeFlagsPatch.js\"\n\n/** @internal */\nexport const None: RuntimeFlags.RuntimeFlag = 0 as RuntimeFlags.RuntimeFlag\n\n/** @internal */\nexport const Interruption: RuntimeFlags.RuntimeFlag = 1 << 0 as RuntimeFlags.RuntimeFlag\n\n/** @internal */\nexport const OpSupervision: RuntimeFlags.RuntimeFlag = 1 << 1 as RuntimeFlags.RuntimeFlag\n\n/** @internal */\nexport const RuntimeMetrics: RuntimeFlags.RuntimeFlag = 1 << 2 as RuntimeFlags.RuntimeFlag\n\n/** @internal */\nexport const WindDown: RuntimeFlags.RuntimeFlag = 1 << 4 as RuntimeFlags.RuntimeFlag\n\n/** @internal */\nexport const CooperativeYielding: RuntimeFlags.RuntimeFlag = 1 << 5 as RuntimeFlags.RuntimeFlag\n\n/** @internal */\nexport const allFlags: ReadonlyArray<RuntimeFlags.RuntimeFlag> = [\n  None,\n  Interruption,\n  OpSupervision,\n  RuntimeMetrics,\n  WindDown,\n  CooperativeYielding\n]\n\nconst print = (flag: RuntimeFlags.RuntimeFlag) => {\n  switch (flag) {\n    case CooperativeYielding: {\n      return \"CooperativeYielding\"\n    }\n    case WindDown: {\n      return \"WindDown\"\n    }\n    case RuntimeMetrics: {\n      return \"RuntimeMetrics\"\n    }\n    case OpSupervision: {\n      return \"OpSupervision\"\n    }\n    case Interruption: {\n      return \"Interruption\"\n    }\n    case None: {\n      return \"None\"\n    }\n  }\n}\n\n/** @internal */\nexport const cooperativeYielding = (self: RuntimeFlags.RuntimeFlags): boolean => isEnabled(self, CooperativeYielding)\n\n/** @internal */\nexport const disable = dual<\n  (flag: RuntimeFlags.RuntimeFlag) => (self: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags,\n  (self: RuntimeFlags.RuntimeFlags, flag: RuntimeFlags.RuntimeFlag) => RuntimeFlags.RuntimeFlags\n>(2, (self, flag) => (self & ~flag) as RuntimeFlags.RuntimeFlags)\n\n/** @internal */\nexport const disableAll = dual<\n  (flags: RuntimeFlags.RuntimeFlags) => (self: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags,\n  (self: RuntimeFlags.RuntimeFlags, flags: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags\n>(2, (self, flags) => (self & ~flags) as RuntimeFlags.RuntimeFlags)\n\n/** @internal */\nexport const enable = dual<\n  (flag: RuntimeFlags.RuntimeFlag) => (self: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags,\n  (self: RuntimeFlags.RuntimeFlags, flag: RuntimeFlags.RuntimeFlag) => RuntimeFlags.RuntimeFlags\n>(2, (self, flag) => (self | flag) as RuntimeFlags.RuntimeFlags)\n\n/** @internal */\nexport const enableAll = dual<\n  (flags: RuntimeFlags.RuntimeFlags) => (self: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags,\n  (self: RuntimeFlags.RuntimeFlags, flags: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags\n>(2, (self, flags) => (self | flags) as RuntimeFlags.RuntimeFlags)\n\n/** @internal */\nexport const interruptible = (self: RuntimeFlags.RuntimeFlags): boolean => interruption(self) && !windDown(self)\n\n/** @internal */\nexport const interruption = (self: RuntimeFlags.RuntimeFlags): boolean => isEnabled(self, Interruption)\n\n/** @internal */\nexport const isDisabled = dual<\n  (flag: RuntimeFlags.RuntimeFlag) => (self: RuntimeFlags.RuntimeFlags) => boolean,\n  (self: RuntimeFlags.RuntimeFlags, flag: RuntimeFlags.RuntimeFlag) => boolean\n>(2, (self, flag) => !isEnabled(self, flag))\n\n/** @internal */\nexport const isEnabled = dual<\n  (flag: RuntimeFlags.RuntimeFlag) => (self: RuntimeFlags.RuntimeFlags) => boolean,\n  (self: RuntimeFlags.RuntimeFlags, flag: RuntimeFlags.RuntimeFlag) => boolean\n>(2, (self, flag) => (self & flag) !== 0)\n\n/** @internal */\nexport const make = (...flags: ReadonlyArray<RuntimeFlags.RuntimeFlag>): RuntimeFlags.RuntimeFlags =>\n  flags.reduce((a, b) => a | b, 0) as RuntimeFlags.RuntimeFlags\n\n/** @internal */\nexport const none: RuntimeFlags.RuntimeFlags = make(None)\n\n/** @internal */\nexport const opSupervision = (self: RuntimeFlags.RuntimeFlags): boolean => isEnabled(self, OpSupervision)\n\n/** @internal */\nexport const render = (self: RuntimeFlags.RuntimeFlags): string => {\n  const active: Array<string> = []\n  allFlags.forEach((flag) => {\n    if (isEnabled(self, flag)) {\n      active.push(`${print(flag)}`)\n    }\n  })\n  return `RuntimeFlags(${active.join(\", \")})`\n}\n\n/** @internal */\nexport const runtimeMetrics = (self: RuntimeFlags.RuntimeFlags): boolean => isEnabled(self, RuntimeMetrics)\n\n/** @internal */\nexport const toSet = (self: RuntimeFlags.RuntimeFlags): ReadonlySet<RuntimeFlags.RuntimeFlag> =>\n  new Set(allFlags.filter((flag) => isEnabled(self, flag)))\n\nexport const windDown = (self: RuntimeFlags.RuntimeFlags): boolean => isEnabled(self, WindDown)\n\n// circular with RuntimeFlagsPatch\n\n/** @internal */\nexport const enabledSet = (self: RuntimeFlagsPatch.RuntimeFlagsPatch): ReadonlySet<RuntimeFlags.RuntimeFlag> =>\n  toSet((runtimeFlagsPatch.active(self) & runtimeFlagsPatch.enabled(self)) as RuntimeFlags.RuntimeFlags)\n\n/** @internal */\nexport const disabledSet = (self: RuntimeFlagsPatch.RuntimeFlagsPatch): ReadonlySet<RuntimeFlags.RuntimeFlag> =>\n  toSet((runtimeFlagsPatch.active(self) & ~runtimeFlagsPatch.enabled(self)) as RuntimeFlags.RuntimeFlags)\n\n/** @internal */\nexport const diff = dual<\n  (that: RuntimeFlags.RuntimeFlags) => (self: RuntimeFlags.RuntimeFlags) => RuntimeFlagsPatch.RuntimeFlagsPatch,\n  (self: RuntimeFlags.RuntimeFlags, that: RuntimeFlags.RuntimeFlags) => RuntimeFlagsPatch.RuntimeFlagsPatch\n>(2, (self, that) => runtimeFlagsPatch.make(self ^ that, that))\n\n/** @internal */\nexport const patch = dual<\n  (patch: RuntimeFlagsPatch.RuntimeFlagsPatch) => (self: RuntimeFlags.RuntimeFlags) => RuntimeFlags.RuntimeFlags,\n  (self: RuntimeFlags.RuntimeFlags, patch: RuntimeFlagsPatch.RuntimeFlagsPatch) => RuntimeFlags.RuntimeFlags\n>(2, (self, patch) =>\n  (\n    (self & (runtimeFlagsPatch.invert(runtimeFlagsPatch.active(patch)) | runtimeFlagsPatch.enabled(patch))) |\n    (runtimeFlagsPatch.active(patch) & runtimeFlagsPatch.enabled(patch))\n  ) as RuntimeFlags.RuntimeFlags)\n\n/** @internal */\nexport const renderPatch = (self: RuntimeFlagsPatch.RuntimeFlagsPatch): string => {\n  const enabled = Array.from(enabledSet(self))\n    .map((flag) => print(flag))\n    .join(\", \")\n  const disabled = Array.from(disabledSet(self))\n    .map((flag) => print(flag))\n    .join(\", \")\n  return `RuntimeFlagsPatch(enabled = (${enabled}), disabled = (${disabled}))`\n}\n\n/** @internal */\nexport const differ: Differ.Differ<RuntimeFlags.RuntimeFlags, RuntimeFlagsPatch.RuntimeFlagsPatch> = internalDiffer\n  .make({\n    empty: runtimeFlagsPatch.empty,\n    diff: (oldValue, newValue) => diff(oldValue, newValue),\n    combine: (first, second) => runtimeFlagsPatch.andThen(second)(first),\n    patch: (_patch, oldValue) => patch(oldValue, _patch)\n  })\n"
  },
  {
    "path": "packages/effect/src/internal/runtimeFlagsPatch.ts",
    "content": "import { dual } from \"../Function.js\"\nimport type * as RuntimeFlags from \"../RuntimeFlags.js\"\nimport type * as RuntimeFlagsPatch from \"../RuntimeFlagsPatch.js\"\n\n/** @internal */\nconst BIT_MASK = 0xff\n\n/** @internal */\nconst BIT_SHIFT = 0x08\n\n/** @internal */\nexport const active = (patch: RuntimeFlagsPatch.RuntimeFlagsPatch): number => patch & BIT_MASK\n\n/** @internal */\nexport const enabled = (patch: RuntimeFlagsPatch.RuntimeFlagsPatch): number => (patch >> BIT_SHIFT) & BIT_MASK\n\n/** @internal */\nexport const make = (active: number, enabled: number): RuntimeFlagsPatch.RuntimeFlagsPatch =>\n  ((active & BIT_MASK) + (((enabled & active) & BIT_MASK) << BIT_SHIFT)) as RuntimeFlagsPatch.RuntimeFlagsPatch\n\n/** @internal */\nexport const empty = make(0, 0)\n\n/** @internal */\nexport const enable = (flag: RuntimeFlags.RuntimeFlag): RuntimeFlagsPatch.RuntimeFlagsPatch => make(flag, flag)\n\n/** @internal */\nexport const disable = (flag: RuntimeFlags.RuntimeFlag): RuntimeFlagsPatch.RuntimeFlagsPatch => make(flag, 0)\n\n/** @internal */\nexport const isEmpty = (patch: RuntimeFlagsPatch.RuntimeFlagsPatch): boolean => patch === 0\n\n/** @internal */\nexport const isActive = dual<\n  (flag: RuntimeFlagsPatch.RuntimeFlagsPatch) => (self: RuntimeFlagsPatch.RuntimeFlagsPatch) => boolean,\n  (self: RuntimeFlagsPatch.RuntimeFlagsPatch, flag: RuntimeFlagsPatch.RuntimeFlagsPatch) => boolean\n>(2, (self, flag) => (active(self) & flag) !== 0)\n\n/** @internal */\nexport const isEnabled = dual<\n  (flag: RuntimeFlags.RuntimeFlag) => (self: RuntimeFlagsPatch.RuntimeFlagsPatch) => boolean,\n  (self: RuntimeFlagsPatch.RuntimeFlagsPatch, flag: RuntimeFlags.RuntimeFlag) => boolean\n>(2, (self, flag) => (enabled(self) & flag) !== 0)\n\n/** @internal */\nexport const isDisabled = dual<\n  (flag: RuntimeFlags.RuntimeFlag) => (self: RuntimeFlagsPatch.RuntimeFlagsPatch) => boolean,\n  (self: RuntimeFlagsPatch.RuntimeFlagsPatch, flag: RuntimeFlags.RuntimeFlag) => boolean\n>(2, (self, flag) => ((active(self) & flag) !== 0) && ((enabled(self) & flag) === 0))\n\n/** @internal */\nexport const exclude = dual<\n  (\n    flag: RuntimeFlags.RuntimeFlag\n  ) => (self: RuntimeFlagsPatch.RuntimeFlagsPatch) => RuntimeFlagsPatch.RuntimeFlagsPatch,\n  (self: RuntimeFlagsPatch.RuntimeFlagsPatch, flag: RuntimeFlags.RuntimeFlag) => RuntimeFlagsPatch.RuntimeFlagsPatch\n>(2, (self, flag) => make(active(self) & ~flag, enabled(self)))\n\n/** @internal */\nexport const both = dual<\n  (\n    that: RuntimeFlagsPatch.RuntimeFlagsPatch\n  ) => (\n    self: RuntimeFlagsPatch.RuntimeFlagsPatch\n  ) => RuntimeFlagsPatch.RuntimeFlagsPatch,\n  (\n    self: RuntimeFlagsPatch.RuntimeFlagsPatch,\n    that: RuntimeFlagsPatch.RuntimeFlagsPatch\n  ) => RuntimeFlagsPatch.RuntimeFlagsPatch\n>(2, (self, that) => make(active(self) | active(that), enabled(self) & enabled(that)))\n\n/** @internal */\nexport const either = dual<\n  (\n    that: RuntimeFlagsPatch.RuntimeFlagsPatch\n  ) => (\n    self: RuntimeFlagsPatch.RuntimeFlagsPatch\n  ) => RuntimeFlagsPatch.RuntimeFlagsPatch,\n  (\n    self: RuntimeFlagsPatch.RuntimeFlagsPatch,\n    that: RuntimeFlagsPatch.RuntimeFlagsPatch\n  ) => RuntimeFlagsPatch.RuntimeFlagsPatch\n>(2, (self, that) => make(active(self) | active(that), enabled(self) | enabled(that)))\n\n/** @internal */\nexport const andThen = dual<\n  (\n    that: RuntimeFlagsPatch.RuntimeFlagsPatch\n  ) => (\n    self: RuntimeFlagsPatch.RuntimeFlagsPatch\n  ) => RuntimeFlagsPatch.RuntimeFlagsPatch,\n  (\n    self: RuntimeFlagsPatch.RuntimeFlagsPatch,\n    that: RuntimeFlagsPatch.RuntimeFlagsPatch\n  ) => RuntimeFlagsPatch.RuntimeFlagsPatch\n>(2, (self, that) => (self | that) as RuntimeFlagsPatch.RuntimeFlagsPatch)\n\n/** @internal */\nexport const inverse = (patch: RuntimeFlagsPatch.RuntimeFlagsPatch): RuntimeFlagsPatch.RuntimeFlagsPatch =>\n  make(enabled(patch), invert(active(patch)))\n\n/** @internal */\nexport const invert = (n: number): number => (~n >>> 0) & BIT_MASK\n"
  },
  {
    "path": "packages/effect/src/internal/schedule/decision.ts",
    "content": "import * as Chunk from \"../../Chunk.js\"\nimport type * as ScheduleDecision from \"../../ScheduleDecision.js\"\nimport type * as Interval from \"../../ScheduleInterval.js\"\nimport * as Intervals from \"../../ScheduleIntervals.js\"\n\n/** @internal */\nexport const OP_CONTINUE = \"Continue\" as const\n\n/** @internal */\nexport type OP_CONTINUE = typeof OP_CONTINUE\n\n/** @internal */\nexport const OP_DONE = \"Done\" as const\n\n/** @internal */\nexport type OP_DONE = typeof OP_DONE\n\n/** @internal */\nexport const _continue = (intervals: Intervals.Intervals): ScheduleDecision.ScheduleDecision => {\n  return {\n    _tag: OP_CONTINUE,\n    intervals\n  }\n}\n\n/** @internal */\nexport const continueWith = (interval: Interval.Interval): ScheduleDecision.ScheduleDecision => {\n  return {\n    _tag: OP_CONTINUE,\n    intervals: Intervals.make(Chunk.of(interval))\n  }\n}\n\n/** @internal */\nexport const done: ScheduleDecision.ScheduleDecision = {\n  _tag: OP_DONE\n}\n\n/** @internal */\nexport const isContinue = (self: ScheduleDecision.ScheduleDecision): self is ScheduleDecision.Continue => {\n  return self._tag === OP_CONTINUE\n}\n\n/** @internal */\nexport const isDone = (self: ScheduleDecision.ScheduleDecision): self is ScheduleDecision.Done => {\n  return self._tag === OP_DONE\n}\n"
  },
  {
    "path": "packages/effect/src/internal/schedule/interval.ts",
    "content": "import * as Duration from \"../../Duration.js\"\nimport { dual } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport type * as Interval from \"../../ScheduleInterval.js\"\n\n/** @internal */\nconst IntervalSymbolKey = \"effect/ScheduleInterval\"\n\n/** @internal */\nexport const IntervalTypeId: Interval.IntervalTypeId = Symbol.for(\n  IntervalSymbolKey\n) as Interval.IntervalTypeId\n\n/** @internal */\nexport const empty: Interval.Interval = {\n  [IntervalTypeId]: IntervalTypeId,\n  startMillis: 0,\n  endMillis: 0\n}\n\n/** @internal */\nexport const make = (startMillis: number, endMillis: number): Interval.Interval => {\n  if (startMillis > endMillis) {\n    return empty\n  }\n  return {\n    [IntervalTypeId]: IntervalTypeId,\n    startMillis,\n    endMillis\n  }\n}\n\n/** @internal */\nexport const lessThan = dual<\n  (that: Interval.Interval) => (self: Interval.Interval) => boolean,\n  (self: Interval.Interval, that: Interval.Interval) => boolean\n>(2, (self, that) => min(self, that) === self)\n\n/** @internal */\nexport const min = dual<\n  (that: Interval.Interval) => (self: Interval.Interval) => Interval.Interval,\n  (self: Interval.Interval, that: Interval.Interval) => Interval.Interval\n>(2, (self, that) => {\n  if (self.endMillis <= that.startMillis) return self\n  if (that.endMillis <= self.startMillis) return that\n  if (self.startMillis < that.startMillis) return self\n  if (that.startMillis < self.startMillis) return that\n  if (self.endMillis <= that.endMillis) return self\n  return that\n})\n\n/** @internal */\nexport const max = dual<\n  (that: Interval.Interval) => (self: Interval.Interval) => Interval.Interval,\n  (self: Interval.Interval, that: Interval.Interval) => Interval.Interval\n>(2, (self, that) => min(self, that) === self ? that : self)\n\n/** @internal */\nexport const isEmpty = (self: Interval.Interval): boolean => {\n  return self.startMillis >= self.endMillis\n}\n\n/** @internal */\nexport const isNonEmpty = (self: Interval.Interval): boolean => {\n  return !isEmpty(self)\n}\n\n/** @internal */\nexport const intersect = dual<\n  (that: Interval.Interval) => (self: Interval.Interval) => Interval.Interval,\n  (self: Interval.Interval, that: Interval.Interval) => Interval.Interval\n>(2, (self, that) => {\n  const start = Math.max(self.startMillis, that.startMillis)\n  const end = Math.min(self.endMillis, that.endMillis)\n  return make(start, end)\n})\n\n/** @internal */\nexport const size = (self: Interval.Interval): Duration.Duration => {\n  return Duration.millis(self.endMillis - self.startMillis)\n}\n\n/** @internal */\nexport const union = dual<\n  (that: Interval.Interval) => (self: Interval.Interval) => Option.Option<Interval.Interval>,\n  (self: Interval.Interval, that: Interval.Interval) => Option.Option<Interval.Interval>\n>(2, (self, that) => {\n  const start = Math.max(self.startMillis, that.startMillis)\n  const end = Math.min(self.endMillis, that.endMillis)\n  return start < end ? Option.none() : Option.some(make(start, end))\n})\n\n/** @internal */\nexport const after = (startMilliseconds: number): Interval.Interval => {\n  return make(startMilliseconds, Number.POSITIVE_INFINITY)\n}\n\n/** @internal */\nexport const before = (endMilliseconds: number): Interval.Interval => {\n  return make(Number.NEGATIVE_INFINITY, endMilliseconds)\n}\n"
  },
  {
    "path": "packages/effect/src/internal/schedule/intervals.ts",
    "content": "import * as Chunk from \"../../Chunk.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport * as Interval from \"../../ScheduleInterval.js\"\nimport type * as Intervals from \"../../ScheduleIntervals.js\"\nimport { getBugErrorMessage } from \"../errors.js\"\n\n/** @internal */\nconst IntervalsSymbolKey = \"effect/ScheduleIntervals\"\n\n/** @internal */\nexport const IntervalsTypeId: Intervals.IntervalsTypeId = Symbol.for(\n  IntervalsSymbolKey\n) as Intervals.IntervalsTypeId\n\n/** @internal */\nexport const make = (intervals: Chunk.Chunk<Interval.Interval>): Intervals.Intervals => {\n  return {\n    [IntervalsTypeId]: IntervalsTypeId,\n    intervals\n  }\n}\n/** @internal */\nexport const empty: Intervals.Intervals = make(Chunk.empty())\n\n/** @internal */\nexport const fromIterable = (intervals: Iterable<Interval.Interval>): Intervals.Intervals =>\n  Array.from(intervals).reduce(\n    (intervals, interval) => pipe(intervals, union(make(Chunk.of(interval)))),\n    empty\n  )\n\n/** @internal */\nexport const union = dual<\n  (that: Intervals.Intervals) => (self: Intervals.Intervals) => Intervals.Intervals,\n  (self: Intervals.Intervals, that: Intervals.Intervals) => Intervals.Intervals\n>(2, (self, that) => {\n  if (!Chunk.isNonEmpty(that.intervals)) {\n    return self\n  }\n  if (!Chunk.isNonEmpty(self.intervals)) {\n    return that\n  }\n  if (Chunk.headNonEmpty(self.intervals).startMillis < Chunk.headNonEmpty(that.intervals).startMillis) {\n    return unionLoop(\n      Chunk.tailNonEmpty(self.intervals),\n      that.intervals,\n      Chunk.headNonEmpty(self.intervals),\n      Chunk.empty()\n    )\n  }\n  return unionLoop(\n    self.intervals,\n    Chunk.tailNonEmpty(that.intervals),\n    Chunk.headNonEmpty(that.intervals),\n    Chunk.empty()\n  )\n})\n\n/** @internal */\nconst unionLoop = (\n  _self: Chunk.Chunk<Interval.Interval>,\n  _that: Chunk.Chunk<Interval.Interval>,\n  _interval: Interval.Interval,\n  _acc: Chunk.Chunk<Interval.Interval>\n): Intervals.Intervals => {\n  let self = _self\n  let that = _that\n  let interval = _interval\n  let acc = _acc\n  while (Chunk.isNonEmpty(self) || Chunk.isNonEmpty(that)) {\n    if (!Chunk.isNonEmpty(self) && Chunk.isNonEmpty(that)) {\n      if (interval.endMillis < Chunk.headNonEmpty(that).startMillis) {\n        acc = pipe(acc, Chunk.prepend(interval))\n        interval = Chunk.headNonEmpty(that)\n        that = Chunk.tailNonEmpty(that)\n        self = Chunk.empty()\n      } else {\n        interval = Interval.make(interval.startMillis, Chunk.headNonEmpty(that).endMillis)\n        that = Chunk.tailNonEmpty(that)\n        self = Chunk.empty()\n      }\n    } else if (Chunk.isNonEmpty(self) && Chunk.isEmpty(that)) {\n      if (interval.endMillis < Chunk.headNonEmpty(self).startMillis) {\n        acc = pipe(acc, Chunk.prepend(interval))\n        interval = Chunk.headNonEmpty(self)\n        that = Chunk.empty()\n        self = Chunk.tailNonEmpty(self)\n      } else {\n        interval = Interval.make(interval.startMillis, Chunk.headNonEmpty(self).endMillis)\n        that = Chunk.empty()\n        self = Chunk.tailNonEmpty(self)\n      }\n    } else if (Chunk.isNonEmpty(self) && Chunk.isNonEmpty(that)) {\n      if (Chunk.headNonEmpty(self).startMillis < Chunk.headNonEmpty(that).startMillis) {\n        if (interval.endMillis < Chunk.headNonEmpty(self).startMillis) {\n          acc = pipe(acc, Chunk.prepend(interval))\n          interval = Chunk.headNonEmpty(self)\n          self = Chunk.tailNonEmpty(self)\n        } else {\n          interval = Interval.make(interval.startMillis, Chunk.headNonEmpty(self).endMillis)\n          self = Chunk.tailNonEmpty(self)\n        }\n      } else if (interval.endMillis < Chunk.headNonEmpty(that).startMillis) {\n        acc = pipe(acc, Chunk.prepend(interval))\n        interval = Chunk.headNonEmpty(that)\n        that = Chunk.tailNonEmpty(that)\n      } else {\n        interval = Interval.make(interval.startMillis, Chunk.headNonEmpty(that).endMillis)\n        that = Chunk.tailNonEmpty(that)\n      }\n    } else {\n      throw new Error(getBugErrorMessage(\"Intervals.unionLoop\"))\n    }\n  }\n  return make(pipe(acc, Chunk.prepend(interval), Chunk.reverse))\n}\n\n/** @internal */\nexport const intersect = dual<\n  (that: Intervals.Intervals) => (self: Intervals.Intervals) => Intervals.Intervals,\n  (self: Intervals.Intervals, that: Intervals.Intervals) => Intervals.Intervals\n>(2, (self, that) => intersectLoop(self.intervals, that.intervals, Chunk.empty()))\n\n/** @internal */\nconst intersectLoop = (\n  _left: Chunk.Chunk<Interval.Interval>,\n  _right: Chunk.Chunk<Interval.Interval>,\n  _acc: Chunk.Chunk<Interval.Interval>\n): Intervals.Intervals => {\n  let left = _left\n  let right = _right\n  let acc = _acc\n  while (Chunk.isNonEmpty(left) && Chunk.isNonEmpty(right)) {\n    const interval = pipe(Chunk.headNonEmpty(left), Interval.intersect(Chunk.headNonEmpty(right)))\n    const intervals = Interval.isEmpty(interval) ? acc : pipe(acc, Chunk.prepend(interval))\n    if (pipe(Chunk.headNonEmpty(left), Interval.lessThan(Chunk.headNonEmpty(right)))) {\n      left = Chunk.tailNonEmpty(left)\n    } else {\n      right = Chunk.tailNonEmpty(right)\n    }\n    acc = intervals\n  }\n  return make(Chunk.reverse(acc))\n}\n\n/** @internal */\nexport const start = (self: Intervals.Intervals): number => {\n  return pipe(\n    self.intervals,\n    Chunk.head,\n    Option.getOrElse(() => Interval.empty)\n  ).startMillis\n}\n\n/** @internal */\nexport const end = (self: Intervals.Intervals): number => {\n  return pipe(\n    self.intervals,\n    Chunk.head,\n    Option.getOrElse(() => Interval.empty)\n  ).endMillis\n}\n\n/** @internal */\nexport const lessThan = dual<\n  (that: Intervals.Intervals) => (self: Intervals.Intervals) => boolean,\n  (self: Intervals.Intervals, that: Intervals.Intervals) => boolean\n>(2, (self, that) => start(self) < start(that))\n\n/** @internal */\nexport const isNonEmpty = (self: Intervals.Intervals): boolean => {\n  return Chunk.isNonEmpty(self.intervals)\n}\n\n/** @internal */\nexport const max = dual<\n  (that: Intervals.Intervals) => (self: Intervals.Intervals) => Intervals.Intervals,\n  (self: Intervals.Intervals, that: Intervals.Intervals) => Intervals.Intervals\n>(2, (self, that) => lessThan(self, that) ? that : self)\n"
  },
  {
    "path": "packages/effect/src/internal/schedule.ts",
    "content": "import type * as Cause from \"../Cause.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport * as Clock from \"../Clock.js\"\nimport * as Context from \"../Context.js\"\nimport * as Cron from \"../Cron.js\"\nimport type * as DateTime from \"../DateTime.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport * as Equal from \"../Equal.js\"\nimport type * as Fiber from \"../Fiber.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { constVoid, dual, pipe } from \"../Function.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty, type Predicate } from \"../Predicate.js\"\nimport * as Random from \"../Random.js\"\nimport type * as Ref from \"../Ref.js\"\nimport type * as Schedule from \"../Schedule.js\"\nimport * as ScheduleDecision from \"../ScheduleDecision.js\"\nimport * as Interval from \"../ScheduleInterval.js\"\nimport * as Intervals from \"../ScheduleIntervals.js\"\nimport type { Scope } from \"../Scope.js\"\nimport type * as Types from \"../Types.js\"\nimport * as internalCause from \"./cause.js\"\nimport * as effect from \"./core-effect.js\"\nimport * as core from \"./core.js\"\nimport { forkScoped } from \"./effect/circular.js\"\nimport * as ref from \"./ref.js\"\n\n/** @internal */\nconst ScheduleSymbolKey = \"effect/Schedule\"\n\n/** @internal */\nexport const ScheduleTypeId: Schedule.ScheduleTypeId = Symbol.for(\n  ScheduleSymbolKey\n) as Schedule.ScheduleTypeId\n\n/** @internal */\nexport const isSchedule = (u: unknown): u is Schedule.Schedule<unknown, never, unknown> =>\n  hasProperty(u, ScheduleTypeId)\n\n/** @internal */\nconst ScheduleDriverSymbolKey = \"effect/ScheduleDriver\"\n\n/** @internal */\nexport const ScheduleDriverTypeId: Schedule.ScheduleDriverTypeId = Symbol.for(\n  ScheduleDriverSymbolKey\n) as Schedule.ScheduleDriverTypeId\n\n/** @internal */\nconst defaultIterationMetadata: Schedule.IterationMetadata = {\n  start: 0,\n  now: 0,\n  input: undefined,\n  output: undefined,\n  elapsed: Duration.zero,\n  elapsedSincePrevious: Duration.zero,\n  recurrence: 0\n}\n\n/** @internal */\nexport const CurrentIterationMetadata = Context.Reference<Schedule.CurrentIterationMetadata>()(\n  \"effect/Schedule/CurrentIterationMetadata\",\n  { defaultValue: () => defaultIterationMetadata }\n)\n\nconst scheduleVariance = {\n  /* c8 ignore next */\n  _Out: (_: never) => _,\n  /* c8 ignore next */\n  _In: (_: unknown) => _,\n  /* c8 ignore next */\n  _R: (_: never) => _\n}\n\nconst scheduleDriverVariance = {\n  /* c8 ignore next */\n  _Out: (_: never) => _,\n  /* c8 ignore next */\n  _In: (_: unknown) => _,\n  /* c8 ignore next */\n  _R: (_: never) => _\n}\n\n/** @internal */\nclass ScheduleImpl<S, Out, In, R> implements Schedule.Schedule<Out, In, R> {\n  [ScheduleTypeId] = scheduleVariance\n  constructor(\n    readonly initial: S,\n    readonly step: (\n      now: number,\n      input: In,\n      state: S\n    ) => Effect.Effect<readonly [S, Out, ScheduleDecision.ScheduleDecision], never, R>\n  ) {\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nconst updateInfo = (\n  iterationMetaRef: Ref.Ref<Schedule.IterationMetadata>,\n  now: number,\n  input: unknown,\n  output: unknown\n) =>\n  ref.update(iterationMetaRef, (prev) =>\n    (prev.recurrence === 0) ?\n      {\n        now,\n        input,\n        output,\n        recurrence: prev.recurrence + 1,\n        elapsed: Duration.zero,\n        elapsedSincePrevious: Duration.zero,\n        start: now\n      } :\n      {\n        now,\n        input,\n        output,\n        recurrence: prev.recurrence + 1,\n        elapsed: Duration.millis(now - prev.start),\n        elapsedSincePrevious: Duration.millis(now - prev.now),\n        start: prev.start\n      })\n\n/** @internal */\nclass ScheduleDriverImpl<Out, In, R> implements Schedule.ScheduleDriver<Out, In, R> {\n  [ScheduleDriverTypeId] = scheduleDriverVariance\n\n  constructor(\n    readonly schedule: Schedule.Schedule<Out, In, R>,\n    readonly ref: Ref.Ref<readonly [Option.Option<Out>, any]>\n  ) {}\n\n  get state(): Effect.Effect<unknown> {\n    return core.map(ref.get(this.ref), (tuple) => tuple[1])\n  }\n\n  get last(): Effect.Effect<Out, Cause.NoSuchElementException> {\n    return core.flatMap(ref.get(this.ref), ([element, _]) => {\n      switch (element._tag) {\n        case \"None\": {\n          return core.failSync(() => new core.NoSuchElementException())\n        }\n        case \"Some\": {\n          return core.succeed(element.value)\n        }\n      }\n    })\n  }\n\n  iterationMeta = ref.unsafeMake(defaultIterationMetadata)\n\n  get reset(): Effect.Effect<void> {\n    return ref.set(this.ref, [Option.none(), this.schedule.initial]).pipe(\n      core.zipLeft(ref.set(this.iterationMeta, defaultIterationMetadata))\n    )\n  }\n\n  next(input: In): Effect.Effect<Out, Option.Option<never>, R> {\n    return pipe(\n      core.map(ref.get(this.ref), (tuple) => tuple[1]),\n      core.flatMap((state) =>\n        pipe(\n          Clock.currentTimeMillis,\n          core.flatMap((now) =>\n            pipe(\n              core.suspend(() => this.schedule.step(now, input, state)),\n              core.flatMap(([state, out, decision]) => {\n                const setState = ref.set(this.ref, [Option.some(out), state] as const)\n                if (ScheduleDecision.isDone(decision)) {\n                  return setState.pipe(\n                    core.zipRight(core.fail(Option.none()))\n                  )\n                }\n                const millis = Intervals.start(decision.intervals) - now\n                if (millis <= 0) {\n                  return setState.pipe(\n                    core.zipRight(updateInfo(this.iterationMeta, now, input, out)),\n                    core.as(out)\n                  )\n                }\n                const duration = Duration.millis(millis)\n                return pipe(\n                  setState,\n                  core.zipRight(updateInfo(this.iterationMeta, now, input, out)),\n                  core.zipRight(effect.sleep(duration)),\n                  core.as(out)\n                )\n              })\n            )\n          )\n        )\n      )\n    )\n  }\n}\n\n/** @internal */\nexport const makeWithState = <S, In, Out, R = never>(\n  initial: S,\n  step: (\n    now: number,\n    input: In,\n    state: S\n  ) => Effect.Effect<readonly [S, Out, ScheduleDecision.ScheduleDecision], never, R>\n): Schedule.Schedule<Out, In, R> => new ScheduleImpl(initial, step)\n\n/** @internal */\nexport const addDelay = dual<\n  <Out>(\n    f: (out: Out) => Duration.DurationInput\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out) => Duration.DurationInput\n  ) => Schedule.Schedule<Out, In, R>\n>(2, (self, f) => addDelayEffect(self, (out) => core.sync(() => f(out))))\n\n/** @internal */\nexport const addDelayEffect = dual<\n  <Out, R2>(\n    f: (out: Out) => Effect.Effect<Duration.DurationInput, never, R2>\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R | R2>,\n  <Out, In, R, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<Duration.DurationInput, never, R2>\n  ) => Schedule.Schedule<Out, In, R | R2>\n>(2, (self, f) =>\n  modifyDelayEffect(self, (out, duration) =>\n    core.map(\n      f(out),\n      (delay) => Duration.sum(duration, Duration.decode(delay))\n    )))\n\n/** @internal */\nexport const andThen = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<\n    Out | Out2,\n    In & In2,\n    R | R2\n  >,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => Schedule.Schedule<\n    Out | Out2,\n    In & In2,\n    R | R2\n  >\n>(2, (self, that) => map(andThenEither(self, that), Either.merge))\n\n/** @internal */\nexport const andThenEither = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>\n  ) => Schedule.Schedule<Either.Either<Out2, Out>, In & In2, R | R2>,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => Schedule.Schedule<Either.Either<Out2, Out>, In & In2, R | R2>\n>(2, <Out, In, R, Out2, In2, R2>(\n  self: Schedule.Schedule<Out, In, R>,\n  that: Schedule.Schedule<Out2, In2, R2>\n): Schedule.Schedule<Either.Either<Out2, Out>, In & In2, R | R2> =>\n  makeWithState(\n    [self.initial, that.initial, true as boolean] as const,\n    (now, input, state) =>\n      state[2] ?\n        core.flatMap(self.step(now, input, state[0]), ([lState, out, decision]) => {\n          if (ScheduleDecision.isDone(decision)) {\n            return core.map(that.step(now, input, state[1]), ([rState, out, decision]) =>\n              [\n                [lState, rState, false as boolean] as const,\n                Either.right(out) as Either.Either<Out2, Out>,\n                decision as ScheduleDecision.ScheduleDecision\n              ] as const)\n          }\n          return core.succeed(\n            [\n              [lState, state[1], true as boolean] as const,\n              Either.left(out),\n              decision\n            ] as const\n          )\n        }) :\n        core.map(that.step(now, input, state[1]), ([rState, out, decision]) =>\n          [\n            [state[0], rState, false as boolean] as const,\n            Either.right(out) as Either.Either<Out2, Out>,\n            decision\n          ] as const)\n  ))\n\n/** @internal */\nexport const as = dual<\n  <Out2>(out: Out2) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out2, In, R>,\n  <Out, In, R, Out2>(self: Schedule.Schedule<Out, In, R>, out: Out2) => Schedule.Schedule<Out2, In, R>\n>(2, (self, out) => map(self, () => out))\n\n/** @internal */\nexport const asVoid = <Out, In, R>(\n  self: Schedule.Schedule<Out, In, R>\n): Schedule.Schedule<void, In, R> => map(self, constVoid)\n\n/** @internal */\nexport const bothInOut = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>\n  ) => Schedule.Schedule<[Out, Out2], readonly [In, In2], R | R2>,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => Schedule.Schedule<[Out, Out2], readonly [In, In2], R | R2>\n>(2, (self, that) =>\n  makeWithState([self.initial, that.initial], (now, [in1, in2], state) =>\n    core.zipWith(\n      self.step(now, in1, state[0]),\n      that.step(now, in2, state[1]),\n      ([lState, out, lDecision], [rState, out2, rDecision]) => {\n        if (ScheduleDecision.isContinue(lDecision) && ScheduleDecision.isContinue(rDecision)) {\n          const interval = pipe(lDecision.intervals, Intervals.union(rDecision.intervals))\n          return [\n            [lState, rState],\n            [out, out2],\n            ScheduleDecision.continue(interval)\n          ]\n        }\n        return [[lState, rState], [out, out2], ScheduleDecision.done]\n      }\n    )))\n\n/** @internal */\nexport const check = dual<\n  <In, Out>(\n    test: (input: In, output: Out) => boolean\n  ) => <R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>,\n    test: (input: In, output: Out) => boolean\n  ) => Schedule.Schedule<Out, In, R>\n>(2, (self, test) => checkEffect(self, (input, out) => core.sync(() => test(input, out))))\n\n/** @internal */\nexport const checkEffect = dual<\n  <In, Out, R2>(\n    test: (input: In, output: Out) => Effect.Effect<boolean, never, R2>\n  ) => <R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R | R2>,\n  <Out, In, R, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    test: (input: In, output: Out) => Effect.Effect<boolean, never, R2>\n  ) => Schedule.Schedule<Out, In, R | R2>\n>(2, (self, test) =>\n  makeWithState(\n    self.initial,\n    (now, input, state) =>\n      core.flatMap(self.step(now, input, state), ([state, out, decision]) => {\n        if (ScheduleDecision.isDone(decision)) {\n          return core.succeed([state, out, ScheduleDecision.done] as const)\n        }\n        return core.map(test(input, out), (cont) =>\n          cont ?\n            [state, out, decision] as const :\n            [state, out, ScheduleDecision.done] as const)\n      })\n  ))\n/** @internal */\nexport const collectAllInputs = <A>(): Schedule.Schedule<Chunk.Chunk<A>, A> => collectAllOutputs(identity<A>())\n\n/** @internal */\nexport const collectAllOutputs = <Out, In, R>(\n  self: Schedule.Schedule<Out, In, R>\n): Schedule.Schedule<Chunk.Chunk<Out>, In, R> =>\n  reduce(self, Chunk.empty<Out>(), (outs, out) => pipe(outs, Chunk.append(out)))\n\n/** @internal */\nexport const collectUntil = <A>(f: Predicate<A>): Schedule.Schedule<Chunk.Chunk<A>, A> =>\n  collectAllOutputs(recurUntil(f))\n\n/** @internal */\nexport const collectUntilEffect = <A, R>(\n  f: (a: A) => Effect.Effect<boolean, never, R>\n): Schedule.Schedule<Chunk.Chunk<A>, A, R> => collectAllOutputs(recurUntilEffect(f))\n\n/** @internal */\nexport const collectWhile = <A>(f: Predicate<A>): Schedule.Schedule<Chunk.Chunk<A>, A> =>\n  collectAllOutputs(recurWhile(f))\n\n/** @internal */\nexport const collectWhileEffect = <A, R>(\n  f: (a: A) => Effect.Effect<boolean, never, R>\n): Schedule.Schedule<Chunk.Chunk<A>, A, R> => collectAllOutputs(recurWhileEffect(f))\n\n/** @internal */\nexport const compose = dual<\n  <Out2, Out, R2>(\n    that: Schedule.Schedule<Out2, Out, R2>\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out2, In, R | R2>,\n  <Out, In, R, Out2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, Out, R2>\n  ) => Schedule.Schedule<Out2, In, R | R2>\n>(2, (self, that) =>\n  makeWithState(\n    [self.initial, that.initial] as const,\n    (now, input, state) =>\n      core.flatMap(\n        self.step(now, input, state[0]),\n        ([lState, out, lDecision]) =>\n          core.map(that.step(now, out, state[1]), ([rState, out2, rDecision]) =>\n            ScheduleDecision.isDone(lDecision)\n              ? [[lState, rState] as const, out2, ScheduleDecision.done] as const\n              : ScheduleDecision.isDone(rDecision)\n              ? [[lState, rState] as const, out2, ScheduleDecision.done] as const\n              : [\n                [lState, rState] as const,\n                out2,\n                ScheduleDecision.continue(pipe(lDecision.intervals, Intervals.max(rDecision.intervals)))\n              ] as const)\n      )\n  ))\n\n/** @internal */\nexport const mapInput = dual<\n  <In, In2>(\n    f: (in2: In2) => In\n  ) => <Out, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In2, R>,\n  <Out, In, R, In2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (in2: In2) => In\n  ) => Schedule.Schedule<Out, In2, R>\n>(2, (self, f) => mapInputEffect(self, (input2) => core.sync(() => f(input2))))\n\n/** @internal */\nexport const mapInputContext = dual<\n  <R0, R>(\n    f: (env0: Context.Context<R0>) => Context.Context<R>\n  ) => <Out, In>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R0>,\n  <Out, In, R, R0>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (env0: Context.Context<R0>) => Context.Context<R>\n  ) => Schedule.Schedule<Out, In, R0>\n>(2, (self, f) =>\n  makeWithState(\n    self.initial,\n    (now, input, state) => core.mapInputContext(self.step(now, input, state), f)\n  ))\n\n/** @internal */\nexport const mapInputEffect = dual<\n  <In2, In, R2>(\n    f: (in2: In2) => Effect.Effect<In, never, R2>\n  ) => <Out, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In2, R | R2>,\n  <Out, In, R, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (in2: In2) => Effect.Effect<In, never, R2>\n  ) => Schedule.Schedule<Out, In2, R | R2>\n>(2, (self, f) =>\n  makeWithState(self.initial, (now, input2, state) =>\n    core.flatMap(\n      f(input2),\n      (input) => self.step(now, input, state)\n    )))\n\n/** @internal */\nexport const cron: {\n  (expression: Cron.Cron): Schedule.Schedule<[number, number]>\n  (expression: string, tz?: DateTime.TimeZone | string): Schedule.Schedule<[number, number]>\n} = (expression: string | Cron.Cron, tz?: DateTime.TimeZone | string): Schedule.Schedule<[number, number]> => {\n  const parsed = Cron.isCron(expression) ? Either.right(expression) : Cron.parse(expression, tz)\n  return makeWithState<[boolean, [number, number, number]], unknown, [number, number]>(\n    [true, [Number.MIN_SAFE_INTEGER, 0, 0]],\n    (now, _, [initial, previous]) => {\n      if (now < previous[0]) {\n        return core.succeed([\n          [false, previous],\n          [previous[1], previous[2]],\n          ScheduleDecision.continueWith(Interval.make(previous[1], previous[2]))\n        ])\n      }\n\n      if (Either.isLeft(parsed)) {\n        return core.die(parsed.left)\n      }\n\n      const cron = parsed.right\n      const date = new Date(now)\n\n      let next: number\n      if (initial && Cron.match(cron, date)) {\n        next = now\n      }\n\n      next = Cron.next(cron, date).getTime()\n      const start = beginningOfSecond(next)\n      const end = endOfSecond(next)\n      return core.succeed([\n        [false, [next, start, end]],\n        [start, end],\n        ScheduleDecision.continueWith(Interval.make(start, end))\n      ])\n    }\n  )\n}\n\n/** @internal */\nexport const dayOfMonth = (day: number): Schedule.Schedule<number> => {\n  return makeWithState<[number, number], unknown, number>(\n    [Number.NEGATIVE_INFINITY, 0],\n    (now, _, state) => {\n      if (!Number.isInteger(day) || day < 1 || 31 < day) {\n        return core.dieSync(() =>\n          new core.IllegalArgumentException(\n            `Invalid argument in: dayOfMonth(${day}). Must be in range 1...31`\n          )\n        )\n      }\n      const n = state[1]\n      const initial = n === 0\n      const day0 = nextDayOfMonth(now, day, initial)\n      const start = beginningOfDay(day0)\n      const end = endOfDay(day0)\n      const interval = Interval.make(start, end)\n      return core.succeed(\n        [\n          [end, n + 1],\n          n,\n          ScheduleDecision.continueWith(interval)\n        ]\n      )\n    }\n  )\n}\n\n/** @internal */\nexport const dayOfWeek = (day: number): Schedule.Schedule<number> => {\n  return makeWithState<[number, number], unknown, number>(\n    [Number.MIN_SAFE_INTEGER, 0],\n    (now, _, state) => {\n      if (!Number.isInteger(day) || day < 1 || 7 < day) {\n        return core.dieSync(() =>\n          new core.IllegalArgumentException(\n            `Invalid argument in: dayOfWeek(${day}). Must be in range 1 (Monday)...7 (Sunday)`\n          )\n        )\n      }\n      const n = state[1]\n      const initial = n === 0\n      const day0 = nextDay(now, day, initial)\n      const start = beginningOfDay(day0)\n      const end = endOfDay(day0)\n      const interval = Interval.make(start, end)\n      return core.succeed(\n        [\n          [end, n + 1],\n          n,\n          ScheduleDecision.continueWith(interval)\n        ]\n      )\n    }\n  )\n}\n\n/** @internal */\nexport const delayed = dual<\n  (\n    f: (duration: Duration.Duration) => Duration.DurationInput\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (duration: Duration.Duration) => Duration.DurationInput\n  ) => Schedule.Schedule<Out, In, R>\n>(2, (self, f) => delayedEffect(self, (duration) => core.sync(() => f(duration))))\n\n/** @internal */\nexport const delayedEffect = dual<\n  <R2>(\n    f: (duration: Duration.Duration) => Effect.Effect<Duration.DurationInput, never, R2>\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R | R2>,\n  <Out, In, R, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (duration: Duration.Duration) => Effect.Effect<Duration.DurationInput, never, R2>\n  ) => Schedule.Schedule<Out, In, R | R2>\n>(2, (self, f) => modifyDelayEffect(self, (_, delay) => f(delay)))\n\n/** @internal */\nexport const delayedSchedule = <In, R>(\n  schedule: Schedule.Schedule<Duration.Duration, In, R>\n): Schedule.Schedule<Duration.Duration, In, R> => addDelay(schedule, (x) => x)\n\n/** @internal */\nexport const delays = <Out, In, R>(\n  self: Schedule.Schedule<Out, In, R>\n): Schedule.Schedule<Duration.Duration, In, R> =>\n  makeWithState(self.initial, (now, input, state) =>\n    pipe(\n      self.step(now, input, state),\n      core.flatMap((\n        [state, _, decision]\n      ): Effect.Effect<[any, Duration.Duration, ScheduleDecision.ScheduleDecision]> => {\n        if (ScheduleDecision.isDone(decision)) {\n          return core.succeed([state, Duration.zero, decision])\n        }\n        return core.succeed(\n          [\n            state,\n            Duration.millis(Intervals.start(decision.intervals) - now),\n            decision\n          ]\n        )\n      })\n    ))\n\n/** @internal */\nexport const mapBoth = dual<\n  <In2, In, Out, Out2>(\n    options: {\n      readonly onInput: (in2: In2) => In\n      readonly onOutput: (out: Out) => Out2\n    }\n  ) => <R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out2, In2, R>,\n  <Out, In, R, In2, Out2>(\n    self: Schedule.Schedule<Out, In, R>,\n    options: {\n      readonly onInput: (in2: In2) => In\n      readonly onOutput: (out: Out) => Out2\n    }\n  ) => Schedule.Schedule<Out2, In2, R>\n>(2, (self, { onInput, onOutput }) => map(mapInput(self, onInput), onOutput))\n\n/** @internal */\nexport const mapBothEffect = dual<\n  <In2, In, R2, Out, R3, Out2>(\n    options: {\n      readonly onInput: (input: In2) => Effect.Effect<In, never, R2>\n      readonly onOutput: (out: Out) => Effect.Effect<Out2, never, R3>\n    }\n  ) => <R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out2, In2, R | R2 | R3>,\n  <Out, In, R, In2, R2, Out2, R3>(\n    self: Schedule.Schedule<Out, In, R>,\n    options: {\n      readonly onInput: (input: In2) => Effect.Effect<In, never, R2>\n      readonly onOutput: (out: Out) => Effect.Effect<Out2, never, R3>\n    }\n  ) => Schedule.Schedule<Out2, In2, R | R2 | R3>\n>(2, (self, { onInput, onOutput }) => mapEffect(mapInputEffect(self, onInput), onOutput))\n\n/** @internal */\nexport const driver = <Out, In, R>(\n  self: Schedule.Schedule<Out, In, R>\n): Effect.Effect<Schedule.ScheduleDriver<Out, In, R>> =>\n  pipe(\n    ref.make<readonly [Option.Option<Out>, any]>([Option.none(), self.initial]),\n    core.map((ref) => new ScheduleDriverImpl(self, ref))\n  )\n\n/** @internal */\nexport const duration = (\n  durationInput: Duration.DurationInput\n): Schedule.Schedule<Duration.Duration> => {\n  const duration = Duration.decode(durationInput)\n  const durationMillis = Duration.toMillis(duration)\n  return makeWithState(true as boolean, (now, _, state) =>\n    core.succeed(\n      state\n        ? [\n          false,\n          duration,\n          ScheduleDecision.continueWith(Interval.after(now + durationMillis))\n        ] as const\n        : [false, Duration.zero, ScheduleDecision.done] as const\n    ))\n}\n\n/** @internal */\nexport const either = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>\n>(2, (self, that) => union(self, that))\n\n/** @internal */\nexport const eitherWith = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>\n>(3, (self, that, f) => unionWith(self, that, f))\n\n/** @internal */\nexport const ensuring = dual<\n  <X>(\n    finalizer: Effect.Effect<X>\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R, X>(\n    self: Schedule.Schedule<Out, In, R>,\n    finalizer: Effect.Effect<X>\n  ) => Schedule.Schedule<Out, In, R>\n>(2, (self, finalizer) =>\n  makeWithState(\n    self.initial,\n    (now, input, state) =>\n      core.flatMap(self.step(now, input, state), ([state, out, decision]) =>\n        ScheduleDecision.isDone(decision)\n          ? core.as(finalizer, [state, out, decision as ScheduleDecision.ScheduleDecision] as const)\n          : core.succeed([state, out, decision] as const))\n  ))\n\n/** @internal */\nexport const exponential = (\n  baseInput: Duration.DurationInput,\n  factor = 2.0\n): Schedule.Schedule<Duration.Duration> => {\n  const base = Duration.decode(baseInput)\n  return delayedSchedule(\n    map(forever, (i) => Duration.times(base, Math.pow(factor, i)))\n  )\n}\n\n/** @internal */\nexport const fibonacci = (oneInput: Duration.DurationInput): Schedule.Schedule<Duration.Duration> => {\n  const one = Duration.decode(oneInput)\n  return delayedSchedule(\n    pipe(\n      unfold(\n        [one, one] as const,\n        ([a, b]) => [b, Duration.sum(a, b)] as const\n      ),\n      map((out) => out[0])\n    )\n  )\n}\n\n/** @internal */\nexport const fixed = (intervalInput: Duration.DurationInput): Schedule.Schedule<number> => {\n  const interval = Duration.decode(intervalInput)\n  const intervalMillis = Duration.toMillis(interval)\n  return makeWithState<[Option.Option<[number, number]>, number], unknown, number>(\n    [Option.none(), 0],\n    (now, _, [option, n]) =>\n      core.sync(() => {\n        switch (option._tag) {\n          case \"None\": {\n            return [\n              [Option.some([now, now + intervalMillis]), n + 1],\n              n,\n              ScheduleDecision.continueWith(Interval.after(now + intervalMillis))\n            ]\n          }\n          case \"Some\": {\n            const [startMillis, lastRun] = option.value\n            const runningBehind = now > (lastRun + intervalMillis)\n            const boundary = Equal.equals(interval, Duration.zero)\n              ? interval\n              : Duration.millis(intervalMillis - ((now - startMillis) % intervalMillis))\n            const sleepTime = Equal.equals(boundary, Duration.zero) ? interval : boundary\n            const nextRun = runningBehind ? now : now + Duration.toMillis(sleepTime)\n            return [\n              [Option.some([startMillis, nextRun]), n + 1],\n              n,\n              ScheduleDecision.continueWith(Interval.after(nextRun))\n            ]\n          }\n        }\n      })\n  )\n}\n\n/** @internal */\nexport const fromDelay = (delay: Duration.DurationInput): Schedule.Schedule<Duration.Duration> => duration(delay)\n\n/** @internal */\nexport const fromDelays = (\n  delay: Duration.DurationInput,\n  ...delays: Array<Duration.DurationInput>\n): Schedule.Schedule<Duration.Duration> =>\n  makeWithState(\n    [[delay, ...delays].map((_) => Duration.decode(_)) as Array<Duration.Duration>, true as boolean] as const,\n    (now, _, [durations, cont]) =>\n      core.sync(() => {\n        if (cont) {\n          const x = durations[0]!\n          const interval = Interval.after(now + Duration.toMillis(x))\n          if (durations.length >= 2) {\n            return [\n              [durations.slice(1), true] as const,\n              x,\n              ScheduleDecision.continueWith(interval)\n            ] as const\n          }\n          const y = durations.slice(1)\n          return [\n            [[x, ...y] as Array<Duration.Duration>, false] as const,\n            x,\n            ScheduleDecision.continueWith(interval)\n          ] as const\n        }\n        return [[durations, false] as const, Duration.zero, ScheduleDecision.done] as const\n      })\n  )\n\n/** @internal */\nexport const fromFunction = <A, B>(f: (a: A) => B): Schedule.Schedule<B, A> => map(identity<A>(), f)\n\n/** @internal */\nexport const hourOfDay = (hour: number): Schedule.Schedule<number> =>\n  makeWithState<[number, number], unknown, number>(\n    [Number.NEGATIVE_INFINITY, 0],\n    (now, _, state) => {\n      if (!Number.isInteger(hour) || hour < 0 || 23 < hour) {\n        return core.dieSync(() =>\n          new core.IllegalArgumentException(\n            `Invalid argument in: hourOfDay(${hour}). Must be in range 0...23`\n          )\n        )\n      }\n      const n = state[1]\n      const initial = n === 0\n      const hour0 = nextHour(now, hour, initial)\n      const start = beginningOfHour(hour0)\n      const end = endOfHour(hour0)\n      const interval = Interval.make(start, end)\n      return core.succeed(\n        [\n          [end, n + 1],\n          n,\n          ScheduleDecision.continueWith(interval)\n        ]\n      )\n    }\n  )\n\n/** @internal */\nexport const identity = <A>(): Schedule.Schedule<A, A> =>\n  makeWithState(void 0, (now, input, state) =>\n    core.succeed(\n      [\n        state,\n        input,\n        ScheduleDecision.continueWith(Interval.after(now))\n      ] as const\n    ))\n\n/** @internal */\nexport const intersect = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>\n>(2, (self, that) => intersectWith(self, that, Intervals.intersect))\n\n/** @internal */\nexport const intersectWith = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>\n>(3, <Env, In, Out, Env2, In2, Out2>(\n  self: Schedule.Schedule<Out, In, Env>,\n  that: Schedule.Schedule<Out2, In2, Env2>,\n  f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n): Schedule.Schedule<[Out, Out2], In & In2, Env | Env2> =>\n  makeWithState<[any, any], In & In2, [Out, Out2], Env | Env2>(\n    [self.initial, that.initial],\n    (now, input: In & In2, state) =>\n      pipe(\n        core.zipWith(\n          self.step(now, input, state[0]),\n          that.step(now, input, state[1]),\n          (a, b) => [a, b] as const\n        ),\n        core.flatMap(([\n          [lState, out, lDecision],\n          [rState, out2, rDecision]\n        ]) => {\n          if (ScheduleDecision.isContinue(lDecision) && ScheduleDecision.isContinue(rDecision)) {\n            return intersectWithLoop(\n              self,\n              that,\n              input,\n              lState,\n              out,\n              lDecision.intervals,\n              rState,\n              out2,\n              rDecision.intervals,\n              f\n            )\n          }\n          return core.succeed(\n            [\n              [lState, rState],\n              [out, out2],\n              ScheduleDecision.done\n            ]\n          )\n        })\n      )\n  ))\n\n/** @internal */\nconst intersectWithLoop = <State, State1, Env, In, Out, Env1, In1, Out2>(\n  self: Schedule.Schedule<Out, In, Env>,\n  that: Schedule.Schedule<Out2, In1, Env1>,\n  input: In & In1,\n  lState: State,\n  out: Out,\n  lInterval: Intervals.Intervals,\n  rState: State1,\n  out2: Out2,\n  rInterval: Intervals.Intervals,\n  f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n): Effect.Effect<\n  [[State, State1], [Out, Out2], ScheduleDecision.ScheduleDecision],\n  never,\n  Env | Env1\n> => {\n  const combined = f(lInterval, rInterval)\n  if (Intervals.isNonEmpty(combined)) {\n    return core.succeed([\n      [lState, rState],\n      [out, out2],\n      ScheduleDecision.continue(combined)\n    ])\n  }\n\n  if (pipe(lInterval, Intervals.lessThan(rInterval))) {\n    return core.flatMap(self.step(Intervals.end(lInterval), input, lState), ([lState, out, decision]) => {\n      if (ScheduleDecision.isDone(decision)) {\n        return core.succeed([\n          [lState, rState],\n          [out, out2],\n          ScheduleDecision.done\n        ])\n      }\n      return intersectWithLoop(\n        self,\n        that,\n        input,\n        lState,\n        out,\n        decision.intervals,\n        rState,\n        out2,\n        rInterval,\n        f\n      )\n    })\n  }\n  return core.flatMap(that.step(Intervals.end(rInterval), input, rState), ([rState, out2, decision]) => {\n    if (ScheduleDecision.isDone(decision)) {\n      return core.succeed([\n        [lState, rState],\n        [out, out2],\n        ScheduleDecision.done\n      ])\n    }\n    return intersectWithLoop(\n      self,\n      that,\n      input,\n      lState,\n      out,\n      lInterval,\n      rState,\n      out2,\n      decision.intervals,\n      f\n    )\n  })\n}\n\n/** @internal */\nexport const jittered = <Out, In, R>(self: Schedule.Schedule<Out, In, R>): Schedule.Schedule<Out, In, R> =>\n  jitteredWith(self, { min: 0.8, max: 1.2 })\n\n/** @internal */\nexport const jitteredWith = dual<\n  (options: { min?: number | undefined; max?: number | undefined }) => <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>\n  ) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>,\n    options: { min?: number | undefined; max?: number | undefined }\n  ) => Schedule.Schedule<Out, In, R>\n>(2, (self, options) => {\n  const { max, min } = Object.assign({ min: 0.8, max: 1.2 }, options)\n  return delayedEffect(self, (duration) =>\n    core.map(Random.next, (random) => {\n      const d = Duration.toMillis(duration)\n      const jittered = d * min * (1 - random) + d * max * random\n      return Duration.millis(jittered)\n    }))\n})\n\n/** @internal */\nexport const linear = (baseInput: Duration.DurationInput): Schedule.Schedule<Duration.Duration> => {\n  const base = Duration.decode(baseInput)\n  return delayedSchedule(map(forever, (i) => Duration.times(base, i + 1)))\n}\n\n/** @internal */\nexport const map = dual<\n  <Out, Out2>(\n    f: (out: Out) => Out2\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out2, In, R>,\n  <Out, In, R, Out2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out) => Out2\n  ) => Schedule.Schedule<Out2, In, R>\n>(2, (self, f) => mapEffect(self, (out) => core.sync(() => f(out))))\n\n/** @internal */\nexport const mapEffect = dual<\n  <Out, Out2, R2>(\n    f: (out: Out) => Effect.Effect<Out2, never, R2>\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out2, In, R | R2>,\n  <Out, In, R, Out2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<Out2, never, R2>\n  ) => Schedule.Schedule<Out2, In, R | R2>\n>(2, (self, f) =>\n  makeWithState(\n    self.initial,\n    (now, input, state) =>\n      core.flatMap(self.step(now, input, state), ([state, out, decision]) =>\n        core.map(\n          f(out),\n          (out2) => [state, out2, decision] as const\n        ))\n  ))\n\n/** @internal */\nexport const minuteOfHour = (minute: number): Schedule.Schedule<number> =>\n  makeWithState<[number, number], unknown, number>(\n    [Number.MIN_SAFE_INTEGER, 0],\n    (now, _, state) => {\n      if (!Number.isInteger(minute) || minute < 0 || 59 < minute) {\n        return core.dieSync(() =>\n          new core.IllegalArgumentException(\n            `Invalid argument in: minuteOfHour(${minute}). Must be in range 0...59`\n          )\n        )\n      }\n      const n = state[1]\n      const initial = n === 0\n      const minute0 = nextMinute(now, minute, initial)\n      const start = beginningOfMinute(minute0)\n      const end = endOfMinute(minute0)\n      const interval = Interval.make(start, end)\n      return core.succeed(\n        [\n          [end, n + 1],\n          n,\n          ScheduleDecision.continueWith(interval)\n        ]\n      )\n    }\n  )\n\n/** @internal */\nexport const modifyDelay = dual<\n  <Out>(\n    f: (out: Out, duration: Duration.Duration) => Duration.DurationInput\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out, duration: Duration.Duration) => Duration.DurationInput\n  ) => Schedule.Schedule<Out, In, R>\n>(2, (self, f) => modifyDelayEffect(self, (out, duration) => core.sync(() => f(out, duration))))\n\n/** @internal */\nexport const modifyDelayEffect = dual<\n  <Out, R2>(\n    f: (out: Out, duration: Duration.Duration) => Effect.Effect<Duration.DurationInput, never, R2>\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R | R2>,\n  <Out, In, R, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out, duration: Duration.Duration) => Effect.Effect<Duration.DurationInput, never, R2>\n  ) => Schedule.Schedule<Out, In, R | R2>\n>(2, (self, f) =>\n  makeWithState(\n    self.initial,\n    (now, input, state) =>\n      core.flatMap(self.step(now, input, state), ([state, out, decision]) => {\n        if (ScheduleDecision.isDone(decision)) {\n          return core.succeed([state, out, decision] as const)\n        }\n        const intervals = decision.intervals\n        const delay = Interval.size(Interval.make(now, Intervals.start(intervals)))\n        return core.map(f(out, delay), (durationInput) => {\n          const duration = Duration.decode(durationInput)\n          const oldStart = Intervals.start(intervals)\n          const newStart = now + Duration.toMillis(duration)\n          const delta = newStart - oldStart\n          const newEnd = Math.max(0, Intervals.end(intervals) + delta)\n          const newInterval = Interval.make(newStart, newEnd)\n          return [state, out, ScheduleDecision.continueWith(newInterval)] as const\n        })\n      })\n  ))\n\n/** @internal */\nexport const onDecision = dual<\n  <Out, X, R2>(\n    f: (out: Out, decision: ScheduleDecision.ScheduleDecision) => Effect.Effect<X, never, R2>\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R | R2>,\n  <Out, In, R, X, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out, decision: ScheduleDecision.ScheduleDecision) => Effect.Effect<X, never, R2>\n  ) => Schedule.Schedule<Out, In, R | R2>\n>(2, (self, f) =>\n  makeWithState(\n    self.initial,\n    (now, input, state) =>\n      core.flatMap(\n        self.step(now, input, state),\n        ([state, out, decision]) => core.as(f(out, decision), [state, out, decision] as const)\n      )\n  ))\n\n/** @internal */\nexport const passthrough = <Out, In, R>(\n  self: Schedule.Schedule<Out, In, R>\n): Schedule.Schedule<In, In, R> =>\n  makeWithState(self.initial, (now, input, state) =>\n    pipe(\n      self.step(now, input, state),\n      core.map(([state, _, decision]) => [state, input, decision] as const)\n    ))\n\n/** @internal */\nexport const provideContext = dual<\n  <R>(\n    context: Context.Context<R>\n  ) => <Out, In>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In>,\n  <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>,\n    context: Context.Context<R>\n  ) => Schedule.Schedule<Out, In>\n>(2, (self, context) =>\n  makeWithState(self.initial, (now, input, state) =>\n    core.provideContext(\n      self.step(now, input, state),\n      context\n    )))\n\n/** @internal */\nexport const provideService = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ) => <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>\n  ) => Schedule.Schedule<Out, In, Exclude<R, I>>,\n  <Out, In, R, I, S>(\n    self: Schedule.Schedule<Out, In, R>,\n    tag: Context.Tag<I, S>,\n    service: Types.NoInfer<S>\n  ) => Schedule.Schedule<Out, In, Exclude<R, I>>\n>(3, <Out, In, R, I, S>(\n  self: Schedule.Schedule<Out, In, R>,\n  tag: Context.Tag<I, S>,\n  service: Types.NoInfer<S>\n): Schedule.Schedule<Out, In, Exclude<R, I>> =>\n  makeWithState(self.initial, (now, input, state) =>\n    core.contextWithEffect((env) =>\n      core.provideContext(\n        // @ts-expect-error\n        self.step(now, input, state),\n        Context.add(env, tag, service)\n      )\n    )))\n\n/** @internal */\nexport const recurUntil = <A>(f: Predicate<A>): Schedule.Schedule<A, A> => untilInput(identity<A>(), f)\n\n/** @internal */\nexport const recurUntilEffect = <A, R>(\n  f: (a: A) => Effect.Effect<boolean, never, R>\n): Schedule.Schedule<A, A, R> => untilInputEffect(identity<A>(), f)\n\n/** @internal */\nexport const recurUntilOption = <A, B>(pf: (a: A) => Option.Option<B>): Schedule.Schedule<Option.Option<B>, A> =>\n  untilOutput(map(identity<A>(), pf), Option.isSome)\n\n/** @internal */\nexport const recurUpTo = (\n  durationInput: Duration.DurationInput\n): Schedule.Schedule<Duration.Duration> => {\n  const duration = Duration.decode(durationInput)\n  return whileOutput(elapsed, (elapsed) => Duration.lessThan(elapsed, duration))\n}\n\n/** @internal */\nexport const recurWhile = <A>(f: Predicate<A>): Schedule.Schedule<A, A> => whileInput(identity<A>(), f)\n\n/** @internal */\nexport const recurWhileEffect = <A, R>(\n  f: (a: A) => Effect.Effect<boolean, never, R>\n): Schedule.Schedule<A, A, R> => whileInputEffect(identity<A>(), f)\n\n/** @internal */\nexport const recurs = (n: number): Schedule.Schedule<number> => whileOutput(forever, (out) => out < n)\n\n/** @internal */\nexport const reduce = dual<\n  <Out, Z>(\n    zero: Z,\n    f: (z: Z, out: Out) => Z\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Z, In, R>,\n  <Out, In, R, Z>(\n    self: Schedule.Schedule<Out, In, R>,\n    zero: Z,\n    f: (z: Z, out: Out) => Z\n  ) => Schedule.Schedule<Z, In, R>\n>(3, (self, zero, f) => reduceEffect(self, zero, (z, out) => core.sync(() => f(z, out))))\n\n/** @internal */\nexport const reduceEffect = dual<\n  <Z, Out, R2>(\n    zero: Z,\n    f: (z: Z, out: Out) => Effect.Effect<Z, never, R2>\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Z, In, R | R2>,\n  <Out, In, R, Z, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    zero: Z,\n    f: (z: Z, out: Out) => Effect.Effect<Z, never, R2>\n  ) => Schedule.Schedule<Z, In, R | R2>\n>(3, (self, zero, f) =>\n  makeWithState(\n    [self.initial, zero] as const,\n    (now, input, [s, z]) =>\n      core.flatMap(self.step(now, input, s), ([s, out, decision]) =>\n        ScheduleDecision.isDone(decision)\n          ? core.succeed([[s, z], z, decision as ScheduleDecision.ScheduleDecision] as const)\n          : core.map(f(z, out), (z2) => [[s, z2], z, decision] as const))\n  ))\n\n/** @internal */\nexport const repeatForever = <Env, In, Out>(self: Schedule.Schedule<Out, In, Env>): Schedule.Schedule<Out, In, Env> =>\n  makeWithState(self.initial, (now, input, state) => {\n    const step = (\n      now: number,\n      input: In,\n      state: any\n    ): Effect.Effect<[any, Out, ScheduleDecision.ScheduleDecision], never, Env> =>\n      core.flatMap(\n        self.step(now, input, state),\n        ([state, out, decision]) =>\n          ScheduleDecision.isDone(decision)\n            ? step(now, input, self.initial)\n            : core.succeed([state, out, decision])\n      )\n    return step(now, input, state)\n  })\n\n/** @internal */\nexport const repetitions = <Out, In, R>(self: Schedule.Schedule<Out, In, R>): Schedule.Schedule<number, In, R> =>\n  reduce(self, 0, (n, _) => n + 1)\n\n/** @internal */\nexport const resetAfter = dual<\n  (\n    duration: Duration.DurationInput\n  ) => <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>\n  ) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>,\n    duration: Duration.DurationInput\n  ) => Schedule.Schedule<Out, In, R>\n>(2, (self, durationInput) => {\n  const duration = Duration.decode(durationInput)\n  return pipe(\n    self,\n    intersect(elapsed),\n    resetWhen(([, time]) => Duration.greaterThanOrEqualTo(time, duration)),\n    map((out) => out[0])\n  )\n})\n\n/** @internal */\nexport const resetWhen = dual<\n  <Out>(f: Predicate<Out>) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(self: Schedule.Schedule<Out, In, R>, f: Predicate<Out>) => Schedule.Schedule<Out, In, R>\n>(2, (self, f) =>\n  makeWithState(\n    self.initial,\n    (now, input, state) =>\n      core.flatMap(self.step(now, input, state), ([state, out, decision]) =>\n        f(out)\n          ? self.step(now, input, self.initial)\n          : core.succeed([state, out, decision] as const))\n  ))\n\n/** @internal */\nexport const run = dual<\n  <In>(\n    now: number,\n    input: Iterable<In>\n  ) => <Out, R>(self: Schedule.Schedule<Out, In, R>) => Effect.Effect<Chunk.Chunk<Out>, never, R>,\n  <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>,\n    now: number,\n    input: Iterable<In>\n  ) => Effect.Effect<Chunk.Chunk<Out>, never, R>\n>(3, (self, now, input) =>\n  pipe(\n    runLoop(self, now, Chunk.fromIterable(input), self.initial, Chunk.empty()),\n    core.map((list) => Chunk.reverse(list))\n  ))\n\n/** @internal */\nconst runLoop = <Env, In, Out>(\n  self: Schedule.Schedule<Out, In, Env>,\n  now: number,\n  inputs: Chunk.Chunk<In>,\n  state: any,\n  acc: Chunk.Chunk<Out>\n): Effect.Effect<Chunk.Chunk<Out>, never, Env> => {\n  if (!Chunk.isNonEmpty(inputs)) {\n    return core.succeed(acc)\n  }\n  const input = Chunk.headNonEmpty(inputs)\n  const nextInputs = Chunk.tailNonEmpty(inputs)\n  return core.flatMap(self.step(now, input, state), ([state, out, decision]) => {\n    if (ScheduleDecision.isDone(decision)) {\n      return core.sync(() => pipe(acc, Chunk.prepend(out)))\n    }\n    return runLoop(\n      self,\n      Intervals.start(decision.intervals),\n      nextInputs,\n      state,\n      Chunk.prepend(acc, out)\n    )\n  })\n}\n\n/** @internal */\nexport const secondOfMinute = (second: number): Schedule.Schedule<number> =>\n  makeWithState<[number, number], unknown, number>(\n    [Number.NEGATIVE_INFINITY, 0],\n    (now, _, state) => {\n      if (!Number.isInteger(second) || second < 0 || 59 < second) {\n        return core.dieSync(() =>\n          new core.IllegalArgumentException(\n            `Invalid argument in: secondOfMinute(${second}). Must be in range 0...59`\n          )\n        )\n      }\n      const n = state[1]\n      const initial = n === 0\n      const second0 = nextSecond(now, second, initial)\n      const start = beginningOfSecond(second0)\n      const end = endOfSecond(second0)\n      const interval = Interval.make(start, end)\n      return core.succeed(\n        [\n          [end, n + 1],\n          n,\n          ScheduleDecision.continueWith(interval)\n        ]\n      )\n    }\n  )\n\n/** @internal */\nexport const spaced = (duration: Duration.DurationInput): Schedule.Schedule<number> => addDelay(forever, () => duration)\n\n/** @internal */\nexport const succeed = <A>(value: A): Schedule.Schedule<A> => map(forever, () => value)\n\n/** @internal */\nexport const sync = <A>(evaluate: LazyArg<A>): Schedule.Schedule<A> => map(forever, evaluate)\n\n/** @internal */\nexport const tapInput = dual<\n  <In2, X, R2>(\n    f: (input: In2) => Effect.Effect<X, never, R2>\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In & In2, R | R2>,\n  <Out, In, R, In2, X, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (input: In2) => Effect.Effect<X, never, R2>\n  ) => Schedule.Schedule<Out, In & In2, R | R2>\n>(2, (self, f) =>\n  makeWithState(self.initial, (now, input, state) =>\n    core.zipRight(\n      f(input),\n      self.step(now, input, state)\n    )))\n\n/** @internal */\nexport const tapOutput = dual<\n  <X, R2, Out>(\n    f: (out: Types.NoInfer<Out>) => Effect.Effect<X, never, R2>\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R2 | R>,\n  <Out, In, R, X, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<X, never, R2>\n  ) => Schedule.Schedule<Out, In, R | R2>\n>(\n  2,\n  <Out, In, R, X, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<X, never, R2>\n  ): Schedule.Schedule<Out, In, R | R2> =>\n    makeWithState(self.initial, (now, input, state) =>\n      core.tap(\n        self.step(now, input, state),\n        ([, out]) => f(out)\n      ))\n)\n\n/** @internal */\nexport const unfold = <A>(initial: A, f: (a: A) => A): Schedule.Schedule<A> =>\n  makeWithState(initial, (now, _, state) =>\n    core.sync(() =>\n      [\n        f(state),\n        state,\n        ScheduleDecision.continueWith(Interval.after(now))\n      ] as const\n    ))\n\n/** @internal */\nexport const union = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>\n>(2, (self, that) => unionWith(self, that, Intervals.union))\n\n/** @internal */\nexport const unionWith = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>,\n    f: (x: Intervals.Intervals, y: Intervals.Intervals) => Intervals.Intervals\n  ) => Schedule.Schedule<[Out, Out2], In & In2, R | R2>\n>(3, (self, that, f) =>\n  makeWithState([self.initial, that.initial], (now, input, state) =>\n    core.zipWith(\n      self.step(now, input, state[0]),\n      that.step(now, input, state[1]),\n      ([lState, l, lDecision], [rState, r, rDecision]) => {\n        if (ScheduleDecision.isDone(lDecision) && ScheduleDecision.isDone(rDecision)) {\n          return [[lState, rState], [l, r], ScheduleDecision.done]\n        }\n        if (ScheduleDecision.isDone(lDecision) && ScheduleDecision.isContinue(rDecision)) {\n          return [\n            [lState, rState],\n            [l, r],\n            ScheduleDecision.continue(rDecision.intervals)\n          ]\n        }\n        if (ScheduleDecision.isContinue(lDecision) && ScheduleDecision.isDone(rDecision)) {\n          return [\n            [lState, rState],\n            [l, r],\n            ScheduleDecision.continue(lDecision.intervals)\n          ]\n        }\n        if (ScheduleDecision.isContinue(lDecision) && ScheduleDecision.isContinue(rDecision)) {\n          const combined = f(lDecision.intervals, rDecision.intervals)\n          return [\n            [lState, rState],\n            [l, r],\n            ScheduleDecision.continue(combined)\n          ]\n        }\n        throw new Error(\n          \"BUG: Schedule.unionWith - please report an issue at https://github.com/Effect-TS/effect/issues\"\n        )\n      }\n    )))\n\n/** @internal */\nexport const untilInput = dual<\n  <In>(f: Predicate<In>) => <Out, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(self: Schedule.Schedule<Out, In, R>, f: Predicate<In>) => Schedule.Schedule<Out, In, R>\n>(2, (self, f) => check(self, (input, _) => !f(input)))\n\n/** @internal */\nexport const untilInputEffect = dual<\n  <In, R2>(\n    f: (input: In) => Effect.Effect<boolean, never, R2>\n  ) => <Out, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R | R2>,\n  <Out, In, R, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (input: In) => Effect.Effect<boolean, never, R2>\n  ) => Schedule.Schedule<Out, In, R | R2>\n>(2, (self, f) => checkEffect(self, (input, _) => effect.negate(f(input))))\n\n/** @internal */\nexport const untilOutput = dual<\n  <Out>(f: Predicate<Out>) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(self: Schedule.Schedule<Out, In, R>, f: Predicate<Out>) => Schedule.Schedule<Out, In, R>\n>(2, (self, f) => check(self, (_, out) => !f(out)))\n\n/** @internal */\nexport const untilOutputEffect = dual<\n  <Out, R2>(\n    f: (out: Out) => Effect.Effect<boolean, never, R2>\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R | R2>,\n  <Out, In, R, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<boolean, never, R2>\n  ) => Schedule.Schedule<Out, In, R | R2>\n>(2, (self, f) => checkEffect(self, (_, out) => effect.negate(f(out))))\n\n/** @internal */\nexport const upTo = dual<\n  (duration: Duration.DurationInput) => <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>\n  ) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(\n    self: Schedule.Schedule<Out, In, R>,\n    duration: Duration.DurationInput\n  ) => Schedule.Schedule<Out, In, R>\n>(2, (self, duration) => zipLeft(self, recurUpTo(duration)))\n\n/** @internal */\nexport const whileInput = dual<\n  <In>(f: Predicate<In>) => <Out, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(self: Schedule.Schedule<Out, In, R>, f: Predicate<In>) => Schedule.Schedule<Out, In, R>\n>(2, (self, f) => check(self, (input, _) => f(input)))\n\n/** @internal */\nexport const whileInputEffect = dual<\n  <In, R2>(\n    f: (input: In) => Effect.Effect<boolean, never, R2>\n  ) => <Out, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R | R2>,\n  <Out, In, R, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (input: In) => Effect.Effect<boolean, never, R2>\n  ) => Schedule.Schedule<Out, In, R | R2>\n>(2, (self, f) => checkEffect(self, (input, _) => f(input)))\n\n/** @internal */\nexport const whileOutput = dual<\n  <Out>(f: Predicate<Out>) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R>,\n  <Out, In, R>(self: Schedule.Schedule<Out, In, R>, f: Predicate<Out>) => Schedule.Schedule<Out, In, R>\n>(2, (self, f) => check(self, (_, out) => f(out)))\n\n/** @internal */\nexport const whileOutputEffect = dual<\n  <Out, R2>(\n    f: (out: Out) => Effect.Effect<boolean, never, R2>\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In, R | R2>,\n  <Out, In, R, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    f: (out: Out) => Effect.Effect<boolean, never, R2>\n  ) => Schedule.Schedule<Out, In, R | R2>\n>(2, (self, f) => checkEffect(self, (_, out) => f(out)))\n\n/** @internal */\nexport const windowed = (intervalInput: Duration.DurationInput): Schedule.Schedule<number> => {\n  const interval = Duration.decode(intervalInput)\n  const millis = Duration.toMillis(interval)\n  return makeWithState<[Option.Option<number>, number], unknown, number>(\n    [Option.none(), 0],\n    (now, _, [option, n]) => {\n      switch (option._tag) {\n        case \"None\": {\n          return core.succeed(\n            [\n              [Option.some(now), n + 1],\n              n,\n              ScheduleDecision.continueWith(Interval.after(now + millis))\n            ]\n          )\n        }\n        case \"Some\": {\n          return core.succeed(\n            [\n              [Option.some(option.value), n + 1],\n              n,\n              ScheduleDecision.continueWith(\n                Interval.after(now + (millis - ((now - option.value) % millis)))\n              )\n            ]\n          )\n        }\n      }\n    }\n  )\n}\n\n/** @internal */\nexport const zipLeft = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out, In & In2, R | R2>,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => Schedule.Schedule<Out, In & In2, R | R2>\n>(2, (self, that) => map(intersect(self, that), (out) => out[0]))\n\n/** @internal */\nexport const zipRight = dual<\n  <Out2, In2, R2>(\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => <Out, In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out2, In & In2, R | R2>,\n  <Out, In, R, Out2, In2, R2>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>\n  ) => Schedule.Schedule<Out2, In & In2, R | R2>\n>(2, (self, that) => map(intersect(self, that), (out) => out[1]))\n\n/** @internal */\nexport const zipWith = dual<\n  <Out2, In2, R2, Out, Out3>(\n    that: Schedule.Schedule<Out2, In2, R2>,\n    f: (out: Out, out2: Out2) => Out3\n  ) => <In, R>(self: Schedule.Schedule<Out, In, R>) => Schedule.Schedule<Out3, In & In2, R | R2>,\n  <Out, In, R, Out2, In2, R2, Out3>(\n    self: Schedule.Schedule<Out, In, R>,\n    that: Schedule.Schedule<Out2, In2, R2>,\n    f: (out: Out, out2: Out2) => Out3\n  ) => Schedule.Schedule<Out3, In & In2, R | R2>\n>(3, (self, that, f) => map(intersect(self, that), ([out, out2]) => f(out, out2)))\n\n// -----------------------------------------------------------------------------\n// Seconds\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const beginningOfSecond = (now: number): number => {\n  const date = new Date(now)\n  return new Date(\n    date.getFullYear(),\n    date.getMonth(),\n    date.getDate(),\n    date.getHours(),\n    date.getMinutes(),\n    date.getSeconds(),\n    0\n  ).getTime()\n}\n\n/** @internal */\nexport const endOfSecond = (now: number): number => {\n  const date = new Date(beginningOfSecond(now))\n  return date.setSeconds(date.getSeconds() + 1)\n}\n\n/** @internal */\nexport const nextSecond = (now: number, second: number, initial: boolean): number => {\n  const date = new Date(now)\n  if (date.getSeconds() === second && initial) {\n    return now\n  }\n  if (date.getSeconds() < second) {\n    return date.setSeconds(second)\n  }\n  // Set seconds to the provided value and add one minute\n  const newDate = new Date(date.setSeconds(second))\n  return newDate.setTime(newDate.getTime() + 1000 * 60)\n}\n\n// -----------------------------------------------------------------------------\n// Minutes\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const beginningOfMinute = (now: number): number => {\n  const date = new Date(now)\n  return new Date(\n    date.getFullYear(),\n    date.getMonth(),\n    date.getDate(),\n    date.getHours(),\n    date.getMinutes(),\n    0,\n    0\n  ).getTime()\n}\n\n/** @internal */\nexport const endOfMinute = (now: number): number => {\n  const date = new Date(beginningOfMinute(now))\n  return date.setMinutes(date.getMinutes() + 1)\n}\n\n/** @internal */\nexport const nextMinute = (now: number, minute: number, initial: boolean): number => {\n  const date = new Date(now)\n  if (date.getMinutes() === minute && initial) {\n    return now\n  }\n  if (date.getMinutes() < minute) {\n    return date.setMinutes(minute)\n  }\n  // Set minutes to the provided value and add one hour\n  const newDate = new Date(date.setMinutes(minute))\n  return newDate.setTime(newDate.getTime() + 1000 * 60 * 60)\n}\n\n// -----------------------------------------------------------------------------\n// Hours\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const beginningOfHour = (now: number): number => {\n  const date = new Date(now)\n  return new Date(\n    date.getFullYear(),\n    date.getMonth(),\n    date.getDate(),\n    date.getHours(),\n    0,\n    0,\n    0\n  ).getTime()\n}\n\n/** @internal */\nexport const endOfHour = (now: number): number => {\n  const date = new Date(beginningOfHour(now))\n  return date.setHours(date.getHours() + 1)\n}\n\n/** @internal */\nexport const nextHour = (now: number, hour: number, initial: boolean): number => {\n  const date = new Date(now)\n  if (date.getHours() === hour && initial) {\n    return now\n  }\n  if (date.getHours() < hour) {\n    return date.setHours(hour)\n  }\n  // Set hours to the provided value and add one day\n  const newDate = new Date(date.setHours(hour))\n  return newDate.setTime(newDate.getTime() + 1000 * 60 * 60 * 24)\n}\n\n// -----------------------------------------------------------------------------\n// Days\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport const beginningOfDay = (now: number): number => {\n  const date = new Date(now)\n  return new Date(\n    date.getFullYear(),\n    date.getMonth(),\n    date.getDate(),\n    0,\n    0,\n    0,\n    0\n  ).getTime()\n}\n\n/** @internal */\nexport const endOfDay = (now: number): number => {\n  const date = new Date(beginningOfDay(now))\n  return date.setDate(date.getDate() + 1)\n}\n\n/** @internal */\nexport const nextDay = (now: number, dayOfWeek: number, initial: boolean): number => {\n  const date = new Date(now)\n  if (date.getDay() === dayOfWeek && initial) {\n    return now\n  }\n  const nextDayOfWeek = (7 + dayOfWeek - date.getDay()) % 7\n  return date.setDate(date.getDate() + (nextDayOfWeek === 0 ? 7 : nextDayOfWeek))\n}\n\n/** @internal */\nexport const nextDayOfMonth = (now: number, day: number, initial: boolean): number => {\n  const date = new Date(now)\n  if (date.getDate() === day && initial) {\n    return now\n  }\n  if (date.getDate() < day) {\n    return date.setDate(day)\n  }\n  return findNextMonth(now, day, 1)\n}\n\n/** @internal */\nexport const findNextMonth = (now: number, day: number, months: number): number => {\n  const d = new Date(now)\n  const tmp1 = new Date(d.setDate(day))\n  const tmp2 = new Date(tmp1.setMonth(tmp1.getMonth() + months))\n  if (tmp2.getDate() === day) {\n    const d2 = new Date(now)\n    const tmp3 = new Date(d2.setDate(day))\n    return tmp3.setMonth(tmp3.getMonth() + months)\n  }\n  return findNextMonth(now, day, months + 1)\n}\n\n// circular with Effect\n\nconst ScheduleDefectTypeId = Symbol.for(\"effect/Schedule/ScheduleDefect\")\nclass ScheduleDefect<E> {\n  readonly [ScheduleDefectTypeId]: typeof ScheduleDefectTypeId\n  constructor(readonly error: E) {\n    this[ScheduleDefectTypeId] = ScheduleDefectTypeId\n  }\n}\nconst isScheduleDefect = <E = unknown>(u: unknown): u is ScheduleDefect<E> => hasProperty(u, ScheduleDefectTypeId)\nconst scheduleDefectWrap = <A, E, R>(self: Effect.Effect<A, E, R>) =>\n  core.catchAll(self, (e) => core.die(new ScheduleDefect(e)))\n\n/** @internal */\nexport const scheduleDefectRefailCause = <E>(cause: Cause.Cause<E>) =>\n  Option.match(\n    internalCause.find(\n      cause,\n      (_) => internalCause.isDieType(_) && isScheduleDefect<E>(_.defect) ? Option.some(_.defect) : Option.none()\n    ),\n    {\n      onNone: () => cause,\n      onSome: (error) => internalCause.fail(error.error)\n    }\n  )\n\n/** @internal */\nexport const scheduleDefectRefail = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n  core.catchAllCause(effect, (cause) => core.failCause(scheduleDefectRefailCause(cause)))\n\n/** @internal */\nexport const repeat_Effect = dual<\n  <R1, A, B>(\n    schedule: Schedule.Schedule<B, A, R1>\n  ) => <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E, R | R1>,\n  <A, E, R, R1, B>(\n    self: Effect.Effect<A, E, R>,\n    schedule: Schedule.Schedule<B, A, R1>\n  ) => Effect.Effect<B, E, R | R1>\n>(2, (self, schedule) => repeatOrElse_Effect(self, schedule, (e, _) => core.fail(e)))\n\n/** @internal */\nexport const repeat_combined = dual<{\n  <O extends Types.NoExcessProperties<Effect.Repeat.Options<A>, O>, A>(\n    options: O\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Repeat.Return<R, E, A, O>\n  <B, A, R1>(\n    schedule: Schedule.Schedule<B, A, R1>\n  ): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E, R | R1>\n}, {\n  <A, E, R, O extends Types.NoExcessProperties<Effect.Repeat.Options<A>, O>>(\n    self: Effect.Effect<A, E, R>,\n    options: O\n  ): Effect.Repeat.Return<R, E, A, O>\n  <A, E, R, B, R1>(\n    self: Effect.Effect<A, E, R>,\n    schedule: Schedule.Schedule<B, A, R1>\n  ): Effect.Effect<B, E, R | R1>\n}>(\n  2,\n  (self: Effect.Effect<any, any, any>, options: Effect.Repeat.Options<any> | Schedule.Schedule<any, any, any>) => {\n    if (isSchedule(options)) {\n      return repeat_Effect(self, options)\n    }\n\n    const base = options.schedule ?? passthrough(forever)\n    const withWhile = options.while ?\n      whileInputEffect(base, (a) => {\n        const applied = options.while!(a)\n        if (typeof applied === \"boolean\") {\n          return core.succeed(applied)\n        }\n        return scheduleDefectWrap(applied)\n      }) :\n      base\n    const withUntil = options.until ?\n      untilInputEffect(withWhile, (a) => {\n        const applied = options.until!(a)\n        if (typeof applied === \"boolean\") {\n          return core.succeed(applied)\n        }\n        return scheduleDefectWrap(applied)\n      }) :\n      withWhile\n    const withTimes = options.times ?\n      intersect(withUntil, recurs(options.times)).pipe(map((intersectionPair) => intersectionPair[0])) :\n      withUntil\n    return scheduleDefectRefail(repeat_Effect(self, withTimes))\n  }\n)\n\n/** @internal */\nexport const repeatOrElse_Effect = dual<\n  <R2, A, B, E, E2, R3>(\n    schedule: Schedule.Schedule<B, A, R2>,\n    orElse: (error: E, option: Option.Option<B>) => Effect.Effect<B, E2, R3>\n  ) => <R>(self: Effect.Effect<A, E, R>) => Effect.Effect<B, E2, R | R2 | R3>,\n  <A, E, R, R2, B, E2, R3>(\n    self: Effect.Effect<A, E, R>,\n    schedule: Schedule.Schedule<B, A, R2>,\n    orElse: (error: E, option: Option.Option<B>) => Effect.Effect<B, E2, R3>\n  ) => Effect.Effect<B, E2, R | R2 | R3>\n>(3, (self, schedule, orElse) =>\n  core.flatMap(driver(schedule), (driver) =>\n    core.matchEffect(self, {\n      onFailure: (error) => orElse(error, Option.none()),\n      onSuccess: (value) =>\n        repeatOrElseEffectLoop(\n          effect.provideServiceEffect(\n            self,\n            CurrentIterationMetadata,\n            ref.get(driver.iterationMeta)\n          ),\n          driver,\n          (error, option) =>\n            effect.provideServiceEffect(\n              orElse(error, option),\n              CurrentIterationMetadata,\n              ref.get(driver.iterationMeta)\n            ),\n          value\n        )\n    })))\n\n/** @internal */\nconst repeatOrElseEffectLoop = <A, E, R, R1, B, C, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  driver: Schedule.ScheduleDriver<B, A, R1>,\n  orElse: (error: E, option: Option.Option<B>) => Effect.Effect<C, E2, R2>,\n  value: A\n): Effect.Effect<B | C, E2, R | R1 | R2> =>\n  core.matchEffect(driver.next(value), {\n    onFailure: () => core.orDie(driver.last),\n    onSuccess: (b) =>\n      core.matchEffect(self, {\n        onFailure: (error) => orElse(error, Option.some(b)),\n        onSuccess: (value) => repeatOrElseEffectLoop(self, driver, orElse, value)\n      })\n  })\n\n/** @internal */\nexport const retry_Effect = dual<\n  <B, E, R1>(\n    policy: Schedule.Schedule<B, E, R1>\n  ) => <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R | R1>,\n  <A, E, R, B, R1>(\n    self: Effect.Effect<A, E, R>,\n    policy: Schedule.Schedule<B, E, R1>\n  ) => Effect.Effect<A, E, R | R1>\n>(2, (self, policy) => retryOrElse_Effect(self, policy, (e, _) => core.fail(e)))\n\n/** @internal */\nexport const retry_combined: {\n  <E, O extends Types.NoExcessProperties<Effect.Retry.Options<E>, O>>(\n    options: O\n  ): <A, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Retry.Return<R, E, A, O>\n  <B, E, R1>(\n    policy: Schedule.Schedule<B, Types.NoInfer<E>, R1>\n  ): <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R1 | R>\n  <A, E, R, O extends Types.NoExcessProperties<Effect.Retry.Options<E>, O>>(\n    self: Effect.Effect<A, E, R>,\n    options: O\n  ): Effect.Retry.Return<R, E, A, O>\n  <A, E, R, B, R1>(\n    self: Effect.Effect<A, E, R>,\n    policy: Schedule.Schedule<B, Types.NoInfer<E>, R1>\n  ): Effect.Effect<A, E, R1 | R>\n} = dual(\n  2,\n  (\n    self: Effect.Effect<any, any, any>,\n    options: Effect.Retry.Options<any> | Schedule.Schedule<any, any, any>\n  ) => {\n    if (isSchedule(options)) {\n      return retry_Effect(self, options)\n    }\n    return scheduleDefectRefail(retry_Effect(self, fromRetryOptions(options)))\n  }\n)\n\n/** @internal */\nexport const fromRetryOptions = (options: Effect.Retry.Options<any>): Schedule.Schedule<any, any, any> => {\n  const base = options.schedule ?? forever\n  const withWhile = options.while ?\n    whileInputEffect(base, (e) => {\n      const applied = options.while!(e)\n      if (typeof applied === \"boolean\") {\n        return core.succeed(applied)\n      }\n      return scheduleDefectWrap(applied)\n    }) :\n    base\n  const withUntil = options.until ?\n    untilInputEffect(withWhile, (e) => {\n      const applied = options.until!(e)\n      if (typeof applied === \"boolean\") {\n        return core.succeed(applied)\n      }\n      return scheduleDefectWrap(applied)\n    }) :\n    withWhile\n  return options.times !== undefined ?\n    intersect(withUntil, recurs(options.times)) :\n    withUntil\n}\n\n/** @internal */\nexport const retryOrElse_Effect = dual<\n  <A1, E, R1, A2, E2, R2>(\n    policy: Schedule.Schedule<A1, Types.NoInfer<E>, R1>,\n    orElse: (e: Types.NoInfer<E>, out: A1) => Effect.Effect<A2, E2, R2>\n  ) => <A, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A | A2, E2, R | R1 | R2>,\n  <A, E, R, A1, R1, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    policy: Schedule.Schedule<A1, Types.NoInfer<E>, R1>,\n    orElse: (e: Types.NoInfer<E>, out: A1) => Effect.Effect<A2, E2, R2>\n  ) => Effect.Effect<A | A2, E2, R | R1 | R2>\n>(3, (self, policy, orElse) =>\n  core.flatMap(\n    driver(policy),\n    (driver) =>\n      retryOrElse_EffectLoop(\n        effect.provideServiceEffect(\n          self,\n          CurrentIterationMetadata,\n          ref.get(driver.iterationMeta)\n        ),\n        driver,\n        (e, out) =>\n          effect.provideServiceEffect(\n            orElse(e, out),\n            CurrentIterationMetadata,\n            ref.get(driver.iterationMeta)\n          )\n      )\n  ))\n\n/** @internal */\nconst retryOrElse_EffectLoop = <A, E, R, R1, A1, A2, E2, R2>(\n  self: Effect.Effect<A, E, R>,\n  driver: Schedule.ScheduleDriver<A1, E, R1>,\n  orElse: (e: E, out: A1) => Effect.Effect<A2, E2, R2>\n): Effect.Effect<A | A2, E2, R | R1 | R2> => {\n  return core.catchAll(\n    self,\n    (e) =>\n      core.matchEffect(driver.next(e), {\n        onFailure: () =>\n          pipe(\n            driver.last,\n            core.orDie,\n            core.flatMap((out) => orElse(e, out))\n          ),\n        onSuccess: () => retryOrElse_EffectLoop(self, driver, orElse)\n      })\n  )\n}\n\n/** @internal */\nexport const schedule_Effect = dual<\n  <A, R2, Out>(\n    schedule: Schedule.Schedule<Out, NoInfer<A> | undefined, R2>\n  ) => <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<Out, E, R | R2>,\n  <A, E, R, R2, Out>(\n    self: Effect.Effect<A, E, R>,\n    schedule: Schedule.Schedule<Out, A | undefined, R2>\n  ) => Effect.Effect<Out, E, R | R2>\n>(2, <A, E, R, R2, Out>(\n  self: Effect.Effect<A, E, R>,\n  schedule: Schedule.Schedule<Out, A | undefined, R2>\n) => scheduleFrom_Effect(self, void 0, schedule))\n\n/** @internal */\nexport const scheduleFrom_Effect = dual<\n  <R2, In, Out>(\n    initial: In,\n    schedule: Schedule.Schedule<Out, In, R2>\n  ) => <E, R>(self: Effect.Effect<In, E, R>) => Effect.Effect<Out, E, R | R2>,\n  <In, E, R, R2, Out>(\n    self: Effect.Effect<In, E, R>,\n    initial: In,\n    schedule: Schedule.Schedule<Out, In, R2>\n  ) => Effect.Effect<Out, E, R | R2>\n>(3, (self, initial, schedule) =>\n  core.flatMap(\n    driver(schedule),\n    (driver) =>\n      scheduleFrom_EffectLoop(\n        effect.provideServiceEffect(\n          self,\n          CurrentIterationMetadata,\n          ref.get(driver.iterationMeta)\n        ),\n        initial,\n        driver\n      )\n  ))\n\n/** @internal */\nconst scheduleFrom_EffectLoop = <In, E, R, R2, Out>(\n  self: Effect.Effect<In, E, R>,\n  initial: In,\n  driver: Schedule.ScheduleDriver<Out, In, R2>\n): Effect.Effect<Out, E, R | R2> =>\n  core.matchEffect(driver.next(initial), {\n    onFailure: () => core.orDie(driver.last),\n    onSuccess: () =>\n      core.flatMap(\n        self,\n        (a) => scheduleFrom_EffectLoop(self, a, driver)\n      )\n  })\n\n/** @internal */\nexport const count: Schedule.Schedule<number> = unfold(0, (n) => n + 1)\n\n/** @internal */\nexport const elapsed: Schedule.Schedule<Duration.Duration> = makeWithState(\n  Option.none() as Option.Option<number>,\n  (now, _, state) => {\n    switch (state._tag) {\n      case \"None\": {\n        return core.succeed(\n          [\n            Option.some(now),\n            Duration.zero,\n            ScheduleDecision.continueWith(Interval.after(now))\n          ] as const\n        )\n      }\n      case \"Some\": {\n        return core.succeed(\n          [\n            Option.some(state.value),\n            Duration.millis(now - state.value),\n            ScheduleDecision.continueWith(Interval.after(now))\n          ] as const\n        )\n      }\n    }\n  }\n)\n\n/** @internal */\nexport const forever: Schedule.Schedule<number> = unfold(0, (n) => n + 1)\n\n/** @internal */\nexport const once: Schedule.Schedule<void> = asVoid(recurs(1))\n\n/** @internal */\nexport const stop: Schedule.Schedule<void> = asVoid(recurs(0))\n\n/** @internal */\nexport const scheduleForked = dual<\n  <Out, R2>(\n    schedule: Schedule.Schedule<Out, unknown, R2>\n  ) => <A, E, R>(\n    self: Effect.Effect<A, E, R>\n  ) => Effect.Effect<Fiber.RuntimeFiber<Out, E>, never, R | R2 | Scope>,\n  <A, E, R, Out, R2>(\n    self: Effect.Effect<A, E, R>,\n    schedule: Schedule.Schedule<Out, unknown, R2>\n  ) => Effect.Effect<Fiber.RuntimeFiber<Out, E>, never, R | R2 | Scope>\n>(2, (self, schedule) => forkScoped(schedule_Effect(self, schedule)))\n"
  },
  {
    "path": "packages/effect/src/internal/schema/errors.ts",
    "content": "import * as array_ from \"../../Array.js\"\nimport * as Inspectable from \"../../Inspectable.js\"\nimport type * as AST from \"../../SchemaAST.js\"\nimport * as util_ from \"./util.js\"\n\nconst getErrorMessage = (\n  reason: string,\n  details?: string,\n  path?: ReadonlyArray<PropertyKey>,\n  ast?: AST.AST\n): string => {\n  let out = reason\n\n  if (path && array_.isNonEmptyReadonlyArray(path)) {\n    out += `\\nat path: ${util_.formatPath(path)}`\n  }\n\n  if (details !== undefined) {\n    out += `\\ndetails: ${details}`\n  }\n\n  if (ast) {\n    out += `\\nschema (${ast._tag}): ${ast}`\n  }\n\n  return out\n}\n\n// ---------------------------------------------\n// generic\n// ---------------------------------------------\n\n/** @internal */\nexport const getInvalidArgumentErrorMessage = (details: string) => getErrorMessage(\"Invalid Argument\", details)\n\nconst getUnsupportedSchemaErrorMessage = (details?: string, path?: ReadonlyArray<PropertyKey>, ast?: AST.AST): string =>\n  getErrorMessage(\"Unsupported schema\", details, path, ast)\n\nconst getMissingAnnotationErrorMessage = (details?: string, path?: ReadonlyArray<PropertyKey>, ast?: AST.AST): string =>\n  getErrorMessage(\"Missing annotation\", details, path, ast)\n\n// ---------------------------------------------\n// Arbitrary\n// ---------------------------------------------\n\n/** @internal */\nexport const getArbitraryUnsupportedErrorMessage = (path: ReadonlyArray<PropertyKey>, ast: AST.AST) =>\n  getUnsupportedSchemaErrorMessage(\"Cannot build an Arbitrary for this schema\", path, ast)\n\n/** @internal */\nexport const getArbitraryMissingAnnotationErrorMessage = (\n  path: ReadonlyArray<PropertyKey>,\n  ast: AST.AST\n) =>\n  getMissingAnnotationErrorMessage(\n    `Generating an Arbitrary for this schema requires an \"arbitrary\" annotation`,\n    path,\n    ast\n  )\n\n/** @internal */\nexport const getArbitraryEmptyEnumErrorMessage = (path: ReadonlyArray<PropertyKey>) =>\n  getErrorMessage(\"Empty Enums schema\", \"Generating an Arbitrary for this schema requires at least one enum\", path)\n\n// ---------------------------------------------\n// Equivalence\n// ---------------------------------------------\n\n/** @internal */\nexport const getEquivalenceUnsupportedErrorMessage = (ast: AST.AST, path: ReadonlyArray<PropertyKey>) =>\n  getUnsupportedSchemaErrorMessage(\"Cannot build an Equivalence\", path, ast)\n\n// ---------------------------------------------\n// JSON Schema\n// ---------------------------------------------\n\n/** @internal */\nexport const getJSONSchemaMissingAnnotationErrorMessage = (\n  path: ReadonlyArray<PropertyKey>,\n  ast: AST.AST\n) =>\n  getMissingAnnotationErrorMessage(\n    `Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation`,\n    path,\n    ast\n  )\n\n/** @internal */\nexport const getJSONSchemaMissingIdentifierAnnotationErrorMessage = (\n  path: ReadonlyArray<PropertyKey>,\n  ast: AST.AST\n) =>\n  getMissingAnnotationErrorMessage(\n    `Generating a JSON Schema for this schema requires an \"identifier\" annotation`,\n    path,\n    ast\n  )\n\n/** @internal */\nexport const getJSONSchemaUnsupportedPostRestElementsErrorMessage = (path: ReadonlyArray<PropertyKey>): string =>\n  getErrorMessage(\n    \"Generating a JSON Schema for post-rest elements is not currently supported. You're welcome to contribute by submitting a Pull Request\",\n    undefined,\n    path\n  )\n\n/** @internal */\nexport const getJSONSchemaUnsupportedKeyErrorMessage = (key: PropertyKey, path: ReadonlyArray<PropertyKey>): string =>\n  getErrorMessage(\"Unsupported key\", `Cannot encode ${Inspectable.formatPropertyKey(key)} key to JSON Schema`, path)\n\n// ---------------------------------------------\n// Pretty\n// ---------------------------------------------\n\n/** @internal */\nexport const getPrettyMissingAnnotationErrorMessage = (\n  path: ReadonlyArray<PropertyKey>,\n  ast: AST.AST\n) => getMissingAnnotationErrorMessage(`Generating a Pretty for this schema requires a \"pretty\" annotation`, path, ast)\n\n/** @internal */\nexport const getPrettyNeverErrorMessage = \"Cannot pretty print a `never` value\"\n\n/** @internal */\nexport const getPrettyNoMatchingSchemaErrorMessage = (\n  actual: unknown,\n  path: ReadonlyArray<PropertyKey>,\n  ast: AST.AST\n) =>\n  getErrorMessage(\n    \"Unexpected Error\",\n    `Cannot find a matching schema for ${Inspectable.formatUnknown(actual)}`,\n    path,\n    ast\n  )\n\n// ---------------------------------------------\n// Schema\n// ---------------------------------------------\n\n/** @internal */\nexport const getSchemaExtendErrorMessage = (x: AST.AST, y: AST.AST, path: ReadonlyArray<PropertyKey>) =>\n  getErrorMessage(\"Unsupported schema or overlapping types\", `cannot extend ${x} with ${y}`, path)\n\n/** @internal */\nexport const getSchemaUnsupportedLiteralSpanErrorMessage = (ast: AST.AST) =>\n  getErrorMessage(\"Unsupported template literal span\", undefined, undefined, ast)\n\n// ---------------------------------------------\n// AST\n// ---------------------------------------------\n\n/** @internal */\nexport const getASTUnsupportedSchemaErrorMessage = (ast: AST.AST) =>\n  getUnsupportedSchemaErrorMessage(undefined, undefined, ast)\n\n/** @internal */\nexport const getASTUnsupportedKeySchemaErrorMessage = (ast: AST.AST) =>\n  getErrorMessage(\"Unsupported key schema\", undefined, undefined, ast)\n\n/** @internal */\nexport const getASTUnsupportedLiteralErrorMessage = (literal: AST.LiteralValue) =>\n  getErrorMessage(\"Unsupported literal\", `literal value: ${Inspectable.formatUnknown(literal)}`)\n\n/** @internal */\nexport const getASTDuplicateIndexSignatureErrorMessage = (type: \"string\" | \"symbol\"): string =>\n  getErrorMessage(\"Duplicate index signature\", `${type} index signature`)\n\n/** @internal */\nexport const getASTIndexSignatureParameterErrorMessage = getErrorMessage(\n  \"Unsupported index signature parameter\",\n  \"An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types\"\n)\n\n/** @internal */\nexport const getASTRequiredElementFollowinAnOptionalElementErrorMessage = getErrorMessage(\n  \"Invalid element\",\n  \"A required element cannot follow an optional element. ts(1257)\"\n)\n\n/** @internal */\nexport const getASTDuplicatePropertySignatureTransformationErrorMessage = (key: PropertyKey): string =>\n  getErrorMessage(\"Duplicate property signature transformation\", `Duplicate key ${Inspectable.formatUnknown(key)}`)\n\n/** @internal */\nexport const getASTUnsupportedRenameSchemaErrorMessage = (ast: AST.AST): string =>\n  getUnsupportedSchemaErrorMessage(undefined, undefined, ast)\n\n/** @internal */\nexport const getASTDuplicatePropertySignatureErrorMessage = (key: PropertyKey): string =>\n  getErrorMessage(\"Duplicate property signature\", `Duplicate key ${Inspectable.formatUnknown(key)}`)\n"
  },
  {
    "path": "packages/effect/src/internal/schema/schemaId.ts",
    "content": "import type * as Schema from \"../../Schema.js\"\n\n/** @internal */\nexport const DateFromSelfSchemaId: Schema.DateFromSelfSchemaId = Symbol.for(\n  \"effect/SchemaId/DateFromSelf\"\n) as Schema.DateFromSelfSchemaId\n\n/** @internal */\nexport const GreaterThanSchemaId: Schema.GreaterThanSchemaId = Symbol.for(\n  \"effect/SchemaId/GreaterThan\"\n) as Schema.GreaterThanSchemaId\n\n/** @internal */\nexport const GreaterThanOrEqualToSchemaId: Schema.GreaterThanOrEqualToSchemaId = Symbol.for(\n  \"effect/SchemaId/GreaterThanOrEqualTo\"\n) as Schema.GreaterThanOrEqualToSchemaId\n\n/** @internal */\nexport const LessThanSchemaId: Schema.LessThanSchemaId = Symbol.for(\n  \"effect/SchemaId/LessThan\"\n) as Schema.LessThanSchemaId\n\n/** @internal */\nexport const LessThanOrEqualToSchemaId: Schema.LessThanOrEqualToSchemaId = Symbol.for(\n  \"effect/SchemaId/LessThanOrEqualTo\"\n) as Schema.LessThanOrEqualToSchemaId\n\n/** @internal */\nexport const IntSchemaId: Schema.IntSchemaId = Symbol.for(\n  \"effect/SchemaId/Int\"\n) as Schema.IntSchemaId\n\n/** @internal */\nexport const NonNaNSchemaId: Schema.NonNaNSchemaId = Symbol.for(\n  \"effect/SchemaId/NonNaN\"\n) as Schema.NonNaNSchemaId\n\n/** @internal */\nexport const FiniteSchemaId: Schema.FiniteSchemaId = Symbol.for(\n  \"effect/SchemaId/Finite\"\n) as Schema.FiniteSchemaId\n\n/** @internal */\nexport const JsonNumberSchemaId: Schema.JsonNumberSchemaId = Symbol.for(\n  \"effect/SchemaId/JsonNumber\"\n) as Schema.JsonNumberSchemaId\n\n/** @internal */\nexport const BetweenSchemaId: Schema.BetweenSchemaId = Symbol.for(\n  \"effect/SchemaId/Between\"\n) as Schema.BetweenSchemaId\n\n/** @internal */\nexport const GreaterThanBigintSchemaId: Schema.GreaterThanBigIntSchemaId = Symbol.for(\n  \"effect/SchemaId/GreaterThanBigint\"\n) as Schema.GreaterThanBigIntSchemaId\n\n/** @internal */\nexport const GreaterThanOrEqualToBigIntSchemaId: Schema.GreaterThanOrEqualToBigIntSchemaId = Symbol.for(\n  \"effect/SchemaId/GreaterThanOrEqualToBigint\"\n) as Schema.GreaterThanOrEqualToBigIntSchemaId\n\n/** @internal */\nexport const LessThanBigIntSchemaId: Schema.LessThanBigIntSchemaId = Symbol.for(\n  \"effect/SchemaId/LessThanBigint\"\n) as Schema.LessThanBigIntSchemaId\n\n/** @internal */\nexport const LessThanOrEqualToBigIntSchemaId: Schema.LessThanOrEqualToBigIntSchemaId = Symbol.for(\n  \"effect/SchemaId/LessThanOrEqualToBigint\"\n) as Schema.LessThanOrEqualToBigIntSchemaId\n\n/** @internal */\nexport const BetweenBigintSchemaId: Schema.BetweenBigIntSchemaId = Symbol.for(\n  \"effect/SchemaId/BetweenBigint\"\n) as Schema.BetweenBigIntSchemaId\n\n/** @internal */\nexport const MinLengthSchemaId: Schema.MinLengthSchemaId = Symbol.for(\n  \"effect/SchemaId/MinLength\"\n) as Schema.MinLengthSchemaId\n\n/** @internal */\nexport const MaxLengthSchemaId: Schema.MaxLengthSchemaId = Symbol.for(\n  \"effect/SchemaId/MaxLength\"\n) as Schema.MaxLengthSchemaId\n\n/** @internal */\nexport const LengthSchemaId: Schema.LengthSchemaId = Symbol.for(\n  \"effect/SchemaId/Length\"\n) as Schema.LengthSchemaId\n\n/** @internal */\nexport const MinItemsSchemaId: Schema.MinItemsSchemaId = Symbol.for(\n  \"effect/SchemaId/MinItems\"\n) as Schema.MinItemsSchemaId\n\n/** @internal */\nexport const MaxItemsSchemaId: Schema.MaxItemsSchemaId = Symbol.for(\n  \"effect/SchemaId/MaxItems\"\n) as Schema.MaxItemsSchemaId\n\n/** @internal */\nexport const ItemsCountSchemaId: Schema.ItemsCountSchemaId = Symbol.for(\n  \"effect/SchemaId/ItemsCount\"\n) as Schema.ItemsCountSchemaId\n"
  },
  {
    "path": "packages/effect/src/internal/schema/util.ts",
    "content": "import type { NonEmptyReadonlyArray } from \"../../Array.js\"\nimport * as Inspectable from \"../../Inspectable.js\"\nimport type * as ParseResult from \"../../ParseResult.js\"\nimport type * as AST from \"../../SchemaAST.js\"\n\n/** @internal */\nexport const getKeysForIndexSignature = (\n  input: { readonly [x: PropertyKey]: unknown },\n  parameter: AST.Parameter\n): ReadonlyArray<string> | ReadonlyArray<symbol> => {\n  switch (parameter._tag) {\n    case \"StringKeyword\":\n    case \"TemplateLiteral\":\n      return Object.keys(input)\n    case \"SymbolKeyword\":\n      return Object.getOwnPropertySymbols(input)\n    case \"Refinement\":\n      return getKeysForIndexSignature(input, parameter.from)\n  }\n}\n\n/** @internal */\nexport const memoizeThunk = <A>(f: () => A): () => A => {\n  let done = false\n  let a: A\n  return () => {\n    if (done) {\n      return a\n    }\n    a = f()\n    done = true\n    return a\n  }\n}\n\n/** @internal */\nexport type SingleOrArray<A> = A | ReadonlyArray<A>\n\n/** @internal */\nexport const isNonEmpty = <A>(x: ParseResult.SingleOrNonEmpty<A>): x is NonEmptyReadonlyArray<A> => Array.isArray(x)\n\n/** @internal */\nexport const isSingle = <A>(x: A | ReadonlyArray<A>): x is A => !Array.isArray(x)\n\n/** @internal */\nexport const formatPathKey = (key: PropertyKey): string => `[${Inspectable.formatPropertyKey(key)}]`\n\n/** @internal */\nexport const formatPath = (path: ParseResult.Path): string =>\n  isNonEmpty(path) ? path.map(formatPathKey).join(\"\") : formatPathKey(path)\n"
  },
  {
    "path": "packages/effect/src/internal/scopedCache.ts",
    "content": "import type * as Cache from \"../Cache.js\"\nimport type * as Clock from \"../Clock.js\"\nimport * as Context from \"../Context.js\"\nimport * as Data from \"../Data.js\"\nimport * as Duration from \"../Duration.js\"\nimport type * as Effect from \"../Effect.js\"\nimport * as Equal from \"../Equal.js\"\nimport * as Exit from \"../Exit.js\"\nimport { pipe } from \"../Function.js\"\nimport * as HashSet from \"../HashSet.js\"\nimport * as MutableHashMap from \"../MutableHashMap.js\"\nimport * as MutableQueue from \"../MutableQueue.js\"\nimport * as MutableRef from \"../MutableRef.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport * as Scope from \"../Scope.js\"\nimport type * as ScopedCache from \"../ScopedCache.js\"\nimport * as cache_ from \"./cache.js\"\nimport * as effect from \"./core-effect.js\"\nimport * as core from \"./core.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\n\n/**\n * The `CacheState` represents the mutable state underlying the cache.\n *\n * @internal\n */\nexport interface CacheState<in out Key, out Value, out Error = never> {\n  map: MutableHashMap.MutableHashMap<Key, MapValue<Key, Value, Error>> // mutable by design\n  keys: cache_.KeySet<Key> // mutable by design\n  accesses: MutableQueue.MutableQueue<cache_.MapKey<Key>> // mutable by design\n  updating: MutableRef.MutableRef<boolean> // mutable by design\n  hits: number // mutable by design\n  misses: number // mutable by design\n}\n\n/** @internal */\nexport const makeCacheState = <Key, Value, Error = never>(\n  map: MutableHashMap.MutableHashMap<Key, MapValue<Key, Value, Error>>,\n  keys: cache_.KeySet<Key>,\n  accesses: MutableQueue.MutableQueue<cache_.MapKey<Key>>,\n  updating: MutableRef.MutableRef<boolean>,\n  hits: number,\n  misses: number\n): CacheState<Key, Value, Error> => ({\n  map,\n  keys,\n  accesses,\n  updating,\n  hits,\n  misses\n})\n\n/**\n * Constructs an initial cache state.\n *\n * @internal\n */\nexport const initialCacheState = <Key, Value, Error = never>(): CacheState<Key, Value, Error> =>\n  makeCacheState(\n    MutableHashMap.empty(),\n    cache_.makeKeySet(),\n    MutableQueue.unbounded(),\n    MutableRef.make(false),\n    0,\n    0\n  )\n\n/**\n * A `MapValue` represents a value in the cache. A value may either be\n * `Pending` with a `Promise` that will contain the result of computing the\n * lookup function, when it is available, or `Complete` with an `Exit` value\n * that contains the result of computing the lookup function.\n *\n * @internal\n */\nexport type MapValue<Key, Value, Error> =\n  | Complete<Key, Value, Error>\n  | Pending<Key, Value, Error>\n  | Refreshing<Key, Value, Error>\n\n/** @internal */\nexport interface Complete<out Key, out Value, out Error> {\n  readonly _tag: \"Complete\"\n  readonly key: cache_.MapKey<Key>\n  readonly exit: Exit.Exit<readonly [Value, Scope.Scope.Finalizer], Error>\n  readonly ownerCount: MutableRef.MutableRef<number>\n  readonly entryStats: Cache.EntryStats\n  readonly timeToLive: number\n}\n\n/** @internal */\nexport interface Pending<out Key, out Value, out Error> {\n  readonly _tag: \"Pending\"\n  readonly key: cache_.MapKey<Key>\n  readonly scoped: Effect.Effect<Effect.Effect<Value, Error, Scope.Scope>>\n}\n\n/** @internal */\nexport interface Refreshing<out Key, out Value, out Error> {\n  readonly _tag: \"Refreshing\"\n  readonly scoped: Effect.Effect<Effect.Effect<Value, Error, Scope.Scope>>\n  readonly complete: Complete<Key, Value, Error>\n}\n\n/** @internal */\nexport const complete = <Key, Value, Error = never>(\n  key: cache_.MapKey<Key>,\n  exit: Exit.Exit<readonly [Value, Scope.Scope.Finalizer], Error>,\n  ownerCount: MutableRef.MutableRef<number>,\n  entryStats: Cache.EntryStats,\n  timeToLive: number\n): Complete<Key, Value, Error> =>\n  Data.struct({\n    _tag: \"Complete\",\n    key,\n    exit,\n    ownerCount,\n    entryStats,\n    timeToLive\n  })\n\n/** @internal */\nexport const pending = <Key, Value, Error = never>(\n  key: cache_.MapKey<Key>,\n  scoped: Effect.Effect<Effect.Effect<Value, Error, Scope.Scope>>\n): Pending<Key, Value, Error> =>\n  Data.struct({\n    _tag: \"Pending\",\n    key,\n    scoped\n  })\n\n/** @internal */\nexport const refreshing = <Key, Value, Error = never>(\n  scoped: Effect.Effect<Effect.Effect<Value, Error, Scope.Scope>>,\n  complete: Complete<Key, Value, Error>\n): Refreshing<Key, Value, Error> =>\n  Data.struct({\n    _tag: \"Refreshing\",\n    scoped,\n    complete\n  })\n\n/** @internal */\nexport const toScoped = <Key, Value, Error = never>(\n  self: Complete<Key, Value, Error>\n): Effect.Effect<Value, Error, Scope.Scope> =>\n  Exit.matchEffect(self.exit, {\n    onFailure: (cause) => core.failCause(cause),\n    onSuccess: ([value]) =>\n      fiberRuntime.acquireRelease(\n        core.as(core.sync(() => MutableRef.incrementAndGet(self.ownerCount)), value),\n        () => releaseOwner(self)\n      )\n  })\n\n/** @internal */\nexport const releaseOwner = <Key, Value, Error = never>(\n  self: Complete<Key, Value, Error>\n): Effect.Effect<void> =>\n  Exit.matchEffect(self.exit, {\n    onFailure: () => core.void,\n    onSuccess: ([, finalizer]) =>\n      core.flatMap(\n        core.sync(() => MutableRef.decrementAndGet(self.ownerCount)),\n        (numOwner) => effect.when(finalizer(Exit.void), () => numOwner === 0)\n      )\n  })\n\n/** @internal */\nconst ScopedCacheSymbolKey = \"effect/ScopedCache\"\n\n/** @internal */\nexport const ScopedCacheTypeId: ScopedCache.ScopedCacheTypeId = Symbol.for(\n  ScopedCacheSymbolKey\n) as ScopedCache.ScopedCacheTypeId\n\nconst scopedCacheVariance = {\n  /* c8 ignore next */\n  _Key: (_: unknown) => _,\n  /* c8 ignore next */\n  _Error: (_: never) => _,\n  /* c8 ignore next */\n  _Value: (_: never) => _\n}\n\nclass ScopedCacheImpl<in out Key, in out Environment, in out Error, in out Value>\n  implements ScopedCache.ScopedCache<Key, Value, Error>\n{\n  readonly [ScopedCacheTypeId] = scopedCacheVariance\n  readonly cacheState: CacheState<Key, Value, Error>\n  constructor(\n    readonly capacity: number,\n    readonly scopedLookup: ScopedCache.Lookup<Key, Value, Error, Environment>,\n    readonly clock: Clock.Clock,\n    readonly timeToLive: (exit: Exit.Exit<Value, Error>) => Duration.Duration,\n    readonly context: Context.Context<Environment>\n  ) {\n    this.cacheState = initialCacheState()\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n\n  get cacheStats(): Effect.Effect<Cache.CacheStats> {\n    return core.sync(() =>\n      cache_.makeCacheStats({\n        hits: this.cacheState.hits,\n        misses: this.cacheState.misses,\n        size: MutableHashMap.size(this.cacheState.map)\n      })\n    )\n  }\n\n  getOption(key: Key): Effect.Effect<Option.Option<Value>, Error, Scope.Scope> {\n    return core.suspend(() =>\n      Option.match(MutableHashMap.get(this.cacheState.map, key), {\n        onNone: () => effect.succeedNone,\n        onSome: (value) => core.flatten(this.resolveMapValue(value))\n      })\n    )\n  }\n\n  getOptionComplete(key: Key): Effect.Effect<Option.Option<Value>, never, Scope.Scope> {\n    return core.suspend(() =>\n      Option.match(MutableHashMap.get(this.cacheState.map, key), {\n        onNone: () => effect.succeedNone,\n        onSome: (value) =>\n          core.flatten(this.resolveMapValue(value, true)) as Effect.Effect<Option.Option<Value>, never, Scope.Scope>\n      })\n    )\n  }\n\n  contains(key: Key): Effect.Effect<boolean> {\n    return core.sync(() => MutableHashMap.has(this.cacheState.map, key))\n  }\n\n  entryStats(key: Key): Effect.Effect<Option.Option<Cache.EntryStats>> {\n    return core.sync(() => {\n      const value = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key))\n      if (value === undefined) {\n        return Option.none()\n      }\n      switch (value._tag) {\n        case \"Complete\": {\n          return Option.some(cache_.makeEntryStats(value.entryStats.loadedMillis))\n        }\n        case \"Pending\": {\n          return Option.none()\n        }\n        case \"Refreshing\": {\n          return Option.some(cache_.makeEntryStats(value.complete.entryStats.loadedMillis))\n        }\n      }\n    })\n  }\n\n  get(key: Key): Effect.Effect<Value, Error, Scope.Scope> {\n    return pipe(\n      this.lookupValueOf(key),\n      effect.memoize,\n      core.flatMap((lookupValue) =>\n        core.suspend(() => {\n          let k: cache_.MapKey<Key> | undefined = undefined\n          let value = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key))\n          if (value === undefined) {\n            k = cache_.makeMapKey(key)\n            if (MutableHashMap.has(this.cacheState.map, key)) {\n              value = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key))\n            } else {\n              MutableHashMap.set(this.cacheState.map, key, pending(k, lookupValue))\n            }\n          }\n          if (value === undefined) {\n            this.trackMiss()\n            return core.zipRight(\n              this.ensureMapSizeNotExceeded(k!),\n              lookupValue\n            )\n          }\n\n          return core.map(\n            this.resolveMapValue(value),\n            core.flatMap(Option.match({\n              onNone: () => {\n                const val = value as Complete<Key, Value, Error>\n                const current = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key))\n                if (Equal.equals(current, value)) {\n                  MutableHashMap.remove(this.cacheState.map, key)\n                }\n                return pipe(\n                  this.ensureMapSizeNotExceeded(val.key),\n                  core.zipRight(releaseOwner(val)),\n                  core.zipRight(this.get(key))\n                )\n              },\n              onSome: core.succeed\n            }))\n          )\n        })\n      ),\n      core.flatten\n    )\n  }\n\n  invalidate(key: Key): Effect.Effect<void> {\n    return core.suspend(() => {\n      if (MutableHashMap.has(this.cacheState.map, key)) {\n        const mapValue = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key))!\n        MutableHashMap.remove(this.cacheState.map, key)\n        switch (mapValue._tag) {\n          case \"Complete\": {\n            return releaseOwner(mapValue)\n          }\n          case \"Pending\": {\n            return core.void\n          }\n          case \"Refreshing\": {\n            return releaseOwner(mapValue.complete)\n          }\n        }\n      }\n      return core.void\n    })\n  }\n\n  get invalidateAll(): Effect.Effect<void> {\n    return fiberRuntime.forEachConcurrentDiscard(\n      HashSet.fromIterable(Array.from(this.cacheState.map).map(([key]) => key)),\n      (key) => this.invalidate(key),\n      false,\n      false\n    )\n  }\n\n  refresh(key: Key): Effect.Effect<void, Error> {\n    return pipe(\n      this.lookupValueOf(key),\n      effect.memoize,\n      core.flatMap((scoped) => {\n        let value = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key))\n        let newKey: cache_.MapKey<Key> | undefined = undefined\n        if (value === undefined) {\n          newKey = cache_.makeMapKey(key)\n          if (MutableHashMap.has(this.cacheState.map, key)) {\n            value = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key))\n          } else {\n            MutableHashMap.set(this.cacheState.map, key, pending(newKey, scoped))\n          }\n        }\n        let finalScoped: Effect.Effect<Effect.Effect<Value, Error, Scope.Scope>>\n        if (value === undefined) {\n          finalScoped = core.zipRight(\n            this.ensureMapSizeNotExceeded(newKey!),\n            scoped\n          )\n        } else {\n          switch (value._tag) {\n            case \"Complete\": {\n              if (this.hasExpired(value.timeToLive)) {\n                finalScoped = core.succeed(this.get(key))\n              } else {\n                const current = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key))\n                if (Equal.equals(current, value)) {\n                  const mapValue = refreshing(scoped, value)\n                  MutableHashMap.set(this.cacheState.map, key, mapValue)\n                  finalScoped = scoped\n                } else {\n                  finalScoped = core.succeed(this.get(key))\n                }\n              }\n              break\n            }\n            case \"Pending\": {\n              finalScoped = value.scoped\n              break\n            }\n            case \"Refreshing\": {\n              finalScoped = value.scoped\n              break\n            }\n          }\n        }\n        return core.flatMap(finalScoped, (s) => fiberRuntime.scopedEffect(core.asVoid(s)))\n      })\n    )\n  }\n\n  get size(): Effect.Effect<number> {\n    return core.sync(() => MutableHashMap.size(this.cacheState.map))\n  }\n\n  resolveMapValue(\n    value: MapValue<Key, Value, Error>,\n    ignorePending = false\n  ): Effect.Effect<Effect.Effect<Option.Option<Value>, Error, Scope.Scope>> {\n    switch (value._tag) {\n      case \"Complete\": {\n        this.trackHit()\n        if (this.hasExpired(value.timeToLive)) {\n          return core.succeed(effect.succeedNone)\n        }\n        return core.as(\n          this.ensureMapSizeNotExceeded(value.key),\n          effect.asSome(toScoped(value))\n        )\n      }\n      case \"Pending\": {\n        this.trackHit()\n\n        if (ignorePending) {\n          return core.succeed(effect.succeedNone)\n        }\n\n        return core.zipRight(\n          this.ensureMapSizeNotExceeded(value.key),\n          core.map(value.scoped, effect.asSome)\n        )\n      }\n      case \"Refreshing\": {\n        this.trackHit()\n        if (this.hasExpired(value.complete.timeToLive)) {\n          if (ignorePending) {\n            return core.succeed(effect.succeedNone)\n          }\n          return core.zipRight(\n            this.ensureMapSizeNotExceeded(value.complete.key),\n            core.map(value.scoped, effect.asSome)\n          )\n        }\n        return core.as(\n          this.ensureMapSizeNotExceeded(value.complete.key),\n          effect.asSome(toScoped(value.complete))\n        )\n      }\n    }\n  }\n\n  lookupValueOf(key: Key): Effect.Effect<Effect.Effect<Value, Error, Scope.Scope>> {\n    return pipe(\n      core.onInterrupt(\n        core.flatMap(Scope.make(), (scope) =>\n          pipe(\n            this.scopedLookup(key),\n            core.provideContext(pipe(this.context, Context.add(Scope.Scope, scope))),\n            core.exit,\n            core.map((exit) => [exit, ((exit) => Scope.close(scope, exit)) as Scope.Scope.Finalizer] as const)\n          )),\n        () => core.sync(() => MutableHashMap.remove(this.cacheState.map, key))\n      ),\n      core.flatMap(([exit, release]) => {\n        const now = this.clock.unsafeCurrentTimeMillis()\n        const expiredAt = now + Duration.toMillis(this.timeToLive(exit))\n        switch (exit._tag) {\n          case \"Success\": {\n            const exitWithFinalizer: Exit.Exit<[Value, Scope.Scope.Finalizer]> = Exit.succeed([\n              exit.value,\n              release\n            ])\n            const completedResult = complete<Key, Value, Error>(\n              cache_.makeMapKey(key),\n              exitWithFinalizer,\n              MutableRef.make(1),\n              cache_.makeEntryStats(now),\n              expiredAt\n            )\n            let previousValue: MapValue<Key, Value, Error> | undefined = undefined\n            if (MutableHashMap.has(this.cacheState.map, key)) {\n              previousValue = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key))\n            }\n            MutableHashMap.set(this.cacheState.map, key, completedResult)\n            return core.sync(() =>\n              core.flatten(\n                core.as(\n                  this.cleanMapValue(previousValue),\n                  toScoped(completedResult)\n                )\n              )\n            )\n          }\n          case \"Failure\": {\n            const completedResult = complete<Key, Value, Error>(\n              cache_.makeMapKey(key),\n              exit as Exit.Exit<readonly [Value, Scope.Scope.Finalizer], Error>,\n              MutableRef.make(0),\n              cache_.makeEntryStats(now),\n              expiredAt\n            )\n            let previousValue: MapValue<Key, Value, Error> | undefined = undefined\n            if (MutableHashMap.has(this.cacheState.map, key)) {\n              previousValue = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key))\n            }\n            MutableHashMap.set(this.cacheState.map, key, completedResult)\n            return core.zipRight(\n              release(exit),\n              core.sync(() =>\n                core.flatten(\n                  core.as(\n                    this.cleanMapValue(previousValue),\n                    toScoped(completedResult)\n                  )\n                )\n              )\n            )\n          }\n        }\n      }),\n      effect.memoize,\n      core.flatten\n    )\n  }\n\n  hasExpired(timeToLive: number): boolean {\n    return this.clock.unsafeCurrentTimeMillis() > timeToLive\n  }\n\n  trackHit(): void {\n    this.cacheState.hits = this.cacheState.hits + 1\n  }\n\n  trackMiss(): void {\n    this.cacheState.misses = this.cacheState.misses + 1\n  }\n\n  trackAccess(key: cache_.MapKey<Key>): Array<MapValue<Key, Value, Error>> {\n    const cleanedKeys: Array<MapValue<Key, Value, Error>> = []\n    MutableQueue.offer(this.cacheState.accesses, key)\n    if (MutableRef.compareAndSet(this.cacheState.updating, false, true)) {\n      let loop = true\n      while (loop) {\n        const key = MutableQueue.poll(this.cacheState.accesses, MutableQueue.EmptyMutableQueue)\n        if (key === MutableQueue.EmptyMutableQueue) {\n          loop = false\n        } else {\n          this.cacheState.keys.add(key)\n        }\n      }\n      let size = MutableHashMap.size(this.cacheState.map)\n      loop = size > this.capacity\n      while (loop) {\n        const key = this.cacheState.keys.remove()\n        if (key === undefined) {\n          loop = false\n        } else {\n          if (MutableHashMap.has(this.cacheState.map, key.current)) {\n            const removed = Option.getOrUndefined(MutableHashMap.get(this.cacheState.map, key.current))!\n            MutableHashMap.remove(this.cacheState.map, key.current)\n            size = size - 1\n            cleanedKeys.push(removed)\n            loop = size > this.capacity\n          }\n        }\n      }\n      MutableRef.set(this.cacheState.updating, false)\n    }\n    return cleanedKeys\n  }\n\n  cleanMapValue(mapValue: MapValue<Key, Value, Error> | undefined): Effect.Effect<void> {\n    if (mapValue === undefined) {\n      return core.void\n    }\n    switch (mapValue._tag) {\n      case \"Complete\": {\n        return releaseOwner(mapValue)\n      }\n      case \"Pending\": {\n        return core.void\n      }\n      case \"Refreshing\": {\n        return releaseOwner(mapValue.complete)\n      }\n    }\n  }\n\n  ensureMapSizeNotExceeded(key: cache_.MapKey<Key>): Effect.Effect<void> {\n    return fiberRuntime.forEachConcurrentDiscard(\n      this.trackAccess(key),\n      (cleanedMapValue) => this.cleanMapValue(cleanedMapValue),\n      false,\n      false\n    )\n  }\n}\n\n/** @internal */\nexport const make = <Key, Value, Error = never, Environment = never>(\n  options: {\n    readonly lookup: ScopedCache.Lookup<Key, Value, Error, Environment>\n    readonly capacity: number\n    readonly timeToLive: Duration.DurationInput\n  }\n): Effect.Effect<ScopedCache.ScopedCache<Key, Value, Error>, never, Environment | Scope.Scope> => {\n  const timeToLive = Duration.decode(options.timeToLive)\n  return makeWith({\n    capacity: options.capacity,\n    lookup: options.lookup,\n    timeToLive: () => timeToLive\n  })\n}\n\n/** @internal */\nexport const makeWith = <Key, Value, Error = never, Environment = never>(\n  options: {\n    readonly capacity: number\n    readonly lookup: ScopedCache.Lookup<Key, Value, Error, Environment>\n    readonly timeToLive: (exit: Exit.Exit<Value, Error>) => Duration.DurationInput\n  }\n): Effect.Effect<ScopedCache.ScopedCache<Key, Value, Error>, never, Environment | Scope.Scope> =>\n  core.flatMap(\n    effect.clock,\n    (clock) =>\n      buildWith(\n        options.capacity,\n        options.lookup,\n        clock,\n        (exit) => Duration.decode(options.timeToLive(exit))\n      )\n  )\n\nconst buildWith = <Key, Value, Error = never, Environment = never>(\n  capacity: number,\n  scopedLookup: ScopedCache.Lookup<Key, Value, Error, Environment>,\n  clock: Clock.Clock,\n  timeToLive: (exit: Exit.Exit<Value, Error>) => Duration.Duration\n): Effect.Effect<ScopedCache.ScopedCache<Key, Value, Error>, never, Environment | Scope.Scope> =>\n  fiberRuntime.acquireRelease(\n    core.flatMap(\n      core.context<Environment>(),\n      (context) =>\n        core.sync(() =>\n          new ScopedCacheImpl(\n            capacity,\n            scopedLookup,\n            clock,\n            timeToLive,\n            context\n          )\n        )\n    ),\n    (cache) => cache.invalidateAll\n  )\n"
  },
  {
    "path": "packages/effect/src/internal/scopedRef.ts",
    "content": "import * as Context from \"../Context.js\"\nimport type * as Effect from \"../Effect.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport type * as Scope from \"../Scope.js\"\nimport type * as ScopedRef from \"../ScopedRef.js\"\nimport * as core from \"./core.js\"\nimport * as circular from \"./effect/circular.js\"\nimport * as effectable from \"./effectable.js\"\nimport * as fiberRuntime from \"./fiberRuntime.js\"\nimport * as ref from \"./ref.js\"\nimport * as synchronized from \"./synchronizedRef.js\"\n\n/** @internal */\nconst ScopedRefSymbolKey = \"effect/ScopedRef\"\n\n/** @internal */\nexport const ScopedRefTypeId: ScopedRef.ScopedRefTypeId = Symbol.for(\n  ScopedRefSymbolKey\n) as ScopedRef.ScopedRefTypeId\n\n/** @internal */\nconst scopedRefVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal  */\nconst proto: ThisType<ScopedRef.ScopedRef<any>> = {\n  ...effectable.CommitPrototype,\n  commit() {\n    return get(this)\n  },\n  [ScopedRefTypeId]: scopedRefVariance\n}\n\n/** @internal  */\nconst close = <A>(self: ScopedRef.ScopedRef<A>): Effect.Effect<void> =>\n  core.flatMap(ref.get(self.ref), (tuple) => tuple[0].close(core.exitVoid))\n\n/** @internal */\nexport const fromAcquire = <A, E, R>(\n  acquire: Effect.Effect<A, E, R>\n): Effect.Effect<ScopedRef.ScopedRef<A>, E, R | Scope.Scope> =>\n  core.uninterruptible(\n    fiberRuntime.scopeMake().pipe(core.flatMap((newScope) =>\n      acquire.pipe(\n        core.mapInputContext<R, Scope.Scope | R>(Context.add(fiberRuntime.scopeTag, newScope)),\n        core.onError((cause) => newScope.close(core.exitFail(cause))),\n        core.flatMap((value) =>\n          circular.makeSynchronized([newScope, value] as const).pipe(\n            core.flatMap((ref) => {\n              const scopedRef = Object.create(proto)\n              scopedRef.ref = ref\n              return pipe(\n                fiberRuntime.addFinalizer(() => close(scopedRef)),\n                core.as(scopedRef)\n              )\n            })\n          )\n        )\n      )\n    ))\n  )\n\n/** @internal */\nexport const get = <A>(self: ScopedRef.ScopedRef<A>): Effect.Effect<A> =>\n  core.map(ref.get(self.ref), (tuple) => tuple[1])\n\n/** @internal */\nexport const make = <A>(evaluate: LazyArg<A>): Effect.Effect<ScopedRef.ScopedRef<A>, never, Scope.Scope> =>\n  fromAcquire(core.sync(evaluate))\n\n/** @internal */\nexport const set = dual<\n  <A, R, E>(\n    acquire: Effect.Effect<A, E, R>\n  ) => (self: ScopedRef.ScopedRef<A>) => Effect.Effect<void, E, Exclude<R, Scope.Scope>>,\n  <A, R, E>(\n    self: ScopedRef.ScopedRef<A>,\n    acquire: Effect.Effect<A, E, R>\n  ) => Effect.Effect<void, E, Exclude<R, Scope.Scope>>\n>(2, <A, R, E>(\n  self: ScopedRef.ScopedRef<A>,\n  acquire: Effect.Effect<A, E, R>\n) =>\n  core.flatten(\n    synchronized.modifyEffect(self.ref, ([oldScope, value]) =>\n      core.uninterruptible(\n        core.scopeClose(oldScope, core.exitVoid).pipe(\n          core.zipRight(fiberRuntime.scopeMake()),\n          core.flatMap((newScope) =>\n            core.exit(fiberRuntime.scopeExtend(acquire, newScope)).pipe(\n              core.flatMap((exit) =>\n                core.exitMatch(exit, {\n                  onFailure: (cause) =>\n                    core.scopeClose(newScope, core.exitVoid).pipe(\n                      core.as(\n                        [\n                          core.failCause(cause) as Effect.Effect<void, E>,\n                          [oldScope, value] as const\n                        ] as const\n                      )\n                    ),\n                  onSuccess: (value) =>\n                    core.succeed(\n                      [\n                        core.void as Effect.Effect<void, E>,\n                        [newScope, value] as const\n                      ] as const\n                    )\n                })\n              )\n            )\n          )\n        )\n      ))\n  ))\n"
  },
  {
    "path": "packages/effect/src/internal/secret.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as Secret from \"../Secret.js\"\nimport * as redacted_ from \"./redacted.js\"\n\n/**\n * @internal\n * @deprecated\n */\nconst SecretSymbolKey = \"effect/Secret\"\n\n/**\n * @internal\n * @deprecated\n */\nexport const SecretTypeId: Secret.SecretTypeId = Symbol.for(\n  SecretSymbolKey\n) as Secret.SecretTypeId\n\n/**\n * @internal\n * @deprecated\n */\nexport const isSecret = (u: unknown): u is Secret.Secret => hasProperty(u, SecretTypeId)\n\nconst SecretProto = {\n  ...redacted_.proto,\n  [SecretTypeId]: SecretTypeId\n}\n\n/**\n * @internal\n * @deprecated\n */\nexport const make = (bytes: Array<number>): Secret.Secret => {\n  const secret = Object.create(SecretProto)\n  Object.defineProperty(secret, \"toString\", {\n    enumerable: false,\n    value() {\n      return \"Secret(<redacted>)\"\n    }\n  })\n  Object.defineProperty(secret, \"toJSON\", {\n    enumerable: false,\n    value() {\n      return \"<redacted>\"\n    }\n  })\n  Object.defineProperty(secret, \"raw\", {\n    enumerable: false,\n    value: bytes\n  })\n  redacted_.redactedRegistry.set(secret, bytes.map((byte) => String.fromCharCode(byte)).join(\"\"))\n  return secret\n}\n\n/**\n * @internal\n * @deprecated\n */\nexport const fromIterable = (iterable: Iterable<string>): Secret.Secret =>\n  make(Arr.fromIterable(iterable).map((char) => char.charCodeAt(0)))\n\n/**\n * @internal\n * @deprecated\n */\nexport const fromString = (text: string): Secret.Secret => {\n  return make(text.split(\"\").map((char) => char.charCodeAt(0)))\n}\n\n/**\n * @internal\n * @deprecated\n */\nexport const value = (self: Secret.Secret): string => {\n  return self.raw.map((byte) => String.fromCharCode(byte)).join(\"\")\n}\n\n/**\n * @internal\n * @deprecated\n */\nexport const unsafeWipe = (self: Secret.Secret): void => {\n  for (let i = 0; i < self.raw.length; i++) {\n    self.raw[i] = 0\n  }\n  redacted_.redactedRegistry.delete(self)\n}\n"
  },
  {
    "path": "packages/effect/src/internal/singleShotGen.ts",
    "content": "/** @internal */\nexport class SingleShotGen<T, A> implements Generator<T, A> {\n  called = false\n\n  constructor(readonly self: T) {\n  }\n\n  next(a: A): IteratorResult<T, A> {\n    return this.called ?\n      ({\n        value: a,\n        done: true\n      }) :\n      (this.called = true,\n        ({\n          value: this.self,\n          done: false\n        }))\n  }\n\n  return(a: A): IteratorResult<T, A> {\n    return ({\n      value: a,\n      done: true\n    })\n  }\n\n  throw(e: unknown): IteratorResult<T, A> {\n    throw e\n  }\n\n  [Symbol.iterator](): Generator<T, A> {\n    return new SingleShotGen<T, A>(this.self)\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/sink.ts",
    "content": "import * as Arr from \"../Array.js\"\nimport * as Cause from \"../Cause.js\"\nimport type * as Channel from \"../Channel.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport * as Clock from \"../Clock.js\"\nimport type * as Context from \"../Context.js\"\nimport * as Duration from \"../Duration.js\"\nimport * as Effect from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport * as Exit from \"../Exit.js\"\nimport { constTrue, dual, identity, pipe } from \"../Function.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport * as HashMap from \"../HashMap.js\"\nimport * as HashSet from \"../HashSet.js\"\nimport type * as MergeDecision from \"../MergeDecision.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty, type Predicate, type Refinement } from \"../Predicate.js\"\nimport * as PubSub from \"../PubSub.js\"\nimport * as Queue from \"../Queue.js\"\nimport * as Ref from \"../Ref.js\"\nimport * as Scope from \"../Scope.js\"\nimport type * as Sink from \"../Sink.js\"\nimport type * as Types from \"../Types.js\"\nimport * as channel from \"./channel.js\"\nimport * as mergeDecision from \"./channel/mergeDecision.js\"\nimport * as core from \"./core-stream.js\"\n\n/** @internal */\nexport const SinkTypeId: Sink.SinkTypeId = Symbol.for(\"effect/Sink\") as Sink.SinkTypeId\n\nconst sinkVariance = {\n  /* c8 ignore next */\n  _A: (_: never) => _,\n  /* c8 ignore next */\n  _In: (_: unknown) => _,\n  /* c8 ignore next */\n  _L: (_: never) => _,\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _R: (_: never) => _\n}\n\n/** @internal */\nexport class SinkImpl<out A, in In = unknown, out L = never, out E = never, out R = never>\n  implements Sink.Sink<A, In, L, E, R>\n{\n  readonly [SinkTypeId] = sinkVariance\n  constructor(\n    readonly channel: Channel.Channel<Chunk.Chunk<L>, Chunk.Chunk<In>, E, never, A, unknown, R>\n  ) {\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const isSink = (u: unknown): u is Sink.Sink<unknown, unknown, unknown, unknown, unknown> =>\n  hasProperty(u, SinkTypeId)\n\n/** @internal */\nexport const suspend = <A, In, L, E, R>(evaluate: LazyArg<Sink.Sink<A, In, L, E, R>>): Sink.Sink<A, In, L, E, R> =>\n  new SinkImpl(core.suspend(() => toChannel(evaluate())))\n\n/** @internal */\nexport const as = dual<\n  <A2>(a: A2) => <A, In, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A2, In, L, E, R>,\n  <A, In, L, E, R, A2>(self: Sink.Sink<A, In, L, E, R>, a: A2) => Sink.Sink<A2, In, L, E, R>\n>(\n  2,\n  (self, a) => pipe(self, map(() => a))\n)\n\n/** @internal */\nexport const collectAll = <In>(): Sink.Sink<Chunk.Chunk<In>, In> => new SinkImpl(collectAllLoop(Chunk.empty()))\n\n/** @internal */\nconst collectAllLoop = <In>(\n  acc: Chunk.Chunk<In>\n): Channel.Channel<never, Chunk.Chunk<In>, never, never, Chunk.Chunk<In>, unknown> =>\n  core.readWithCause({\n    onInput: (chunk: Chunk.Chunk<In>) => collectAllLoop(pipe(acc, Chunk.appendAll(chunk))),\n    onFailure: core.failCause,\n    onDone: () => core.succeed(acc)\n  })\n\n/** @internal */\nexport const collectAllN = <In>(n: number): Sink.Sink<Chunk.Chunk<In>, In, In> =>\n  suspend(() => fromChannel(collectAllNLoop(n, Chunk.empty())))\n\n/** @internal */\nconst collectAllNLoop = <In>(\n  n: number,\n  acc: Chunk.Chunk<In>\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, never, never, Chunk.Chunk<In>, unknown> =>\n  core.readWithCause({\n    onInput: (chunk: Chunk.Chunk<In>) => {\n      const [collected, leftovers] = Chunk.splitAt(chunk, n)\n      if (collected.length < n) {\n        return collectAllNLoop(n - collected.length, Chunk.appendAll(acc, collected))\n      }\n      if (Chunk.isEmpty(leftovers)) {\n        return core.succeed(Chunk.appendAll(acc, collected))\n      }\n      return core.flatMap(core.write(leftovers), () => core.succeed(Chunk.appendAll(acc, collected)))\n    },\n    onFailure: core.failCause,\n    onDone: () => core.succeed(acc)\n  })\n\n/** @internal */\nexport const collectAllFrom = <A, In, L extends In, E, R>(\n  self: Sink.Sink<A, In, L, E, R>\n): Sink.Sink<Chunk.Chunk<A>, In, L, E, R> =>\n  collectAllWhileWith(self, {\n    initial: Chunk.empty<A>(),\n    while: constTrue,\n    body: (chunk, a) => pipe(chunk, Chunk.append(a))\n  })\n\n/** @internal */\nexport const collectAllToMap = <In, K>(\n  key: (input: In) => K,\n  merge: (x: In, y: In) => In\n): Sink.Sink<HashMap.HashMap<K, In>, In> => {\n  return foldLeftChunks(HashMap.empty<K, In>(), (map, chunk) =>\n    pipe(\n      chunk,\n      Chunk.reduce(map, (map, input) => {\n        const k: K = key(input)\n        const v: In = pipe(map, HashMap.has(k)) ?\n          merge(pipe(map, HashMap.unsafeGet(k)), input) :\n          input\n        return pipe(map, HashMap.set(k, v))\n      })\n    ))\n}\n\n/** @internal */\nexport const collectAllToMapN = <In, K>(\n  n: number,\n  key: (input: In) => K,\n  merge: (x: In, y: In) => In\n): Sink.Sink<HashMap.HashMap<K, In>, In, In> => {\n  return foldWeighted<HashMap.HashMap<K, In>, In>({\n    initial: HashMap.empty(),\n    maxCost: n,\n    cost: (acc, input) => pipe(acc, HashMap.has(key(input))) ? 0 : 1,\n    body: (acc, input) => {\n      const k: K = key(input)\n      const v: In = pipe(acc, HashMap.has(k)) ?\n        merge(pipe(acc, HashMap.unsafeGet(k)), input) :\n        input\n      return pipe(acc, HashMap.set(k, v))\n    }\n  })\n}\n\n/** @internal */\nexport const collectAllToSet = <In>(): Sink.Sink<HashSet.HashSet<In>, In> =>\n  foldLeftChunks<HashSet.HashSet<In>, In>(\n    HashSet.empty(),\n    (acc, chunk) => pipe(chunk, Chunk.reduce(acc, (acc, input) => pipe(acc, HashSet.add(input))))\n  )\n\n/** @internal */\nexport const collectAllToSetN = <In>(n: number): Sink.Sink<HashSet.HashSet<In>, In, In> =>\n  foldWeighted<HashSet.HashSet<In>, In>({\n    initial: HashSet.empty(),\n    maxCost: n,\n    cost: (acc, input) => HashSet.has(acc, input) ? 0 : 1,\n    body: (acc, input) => HashSet.add(acc, input)\n  })\n\n/** @internal */\nexport const collectAllUntil = <In>(p: Predicate<In>): Sink.Sink<Chunk.Chunk<In>, In, In> => {\n  return pipe(\n    fold<[Chunk.Chunk<In>, boolean], In>(\n      [Chunk.empty(), true],\n      (tuple) => tuple[1],\n      ([chunk, _], input) => [pipe(chunk, Chunk.append(input)), !p(input)]\n    ),\n    map((tuple) => tuple[0])\n  )\n}\n\n/** @internal */\nexport const collectAllUntilEffect = <In, E, R>(p: (input: In) => Effect.Effect<boolean, E, R>) => {\n  return pipe(\n    foldEffect<[Chunk.Chunk<In>, boolean], In, E, R>(\n      [Chunk.empty(), true],\n      (tuple) => tuple[1],\n      ([chunk, _], input) => pipe(p(input), Effect.map((bool) => [pipe(chunk, Chunk.append(input)), !bool]))\n    ),\n    map((tuple) => tuple[0])\n  )\n}\n\n/** @internal */\nexport const collectAllWhile: {\n  <In, Out extends In>(refinement: Refinement<In, Out>): Sink.Sink<Chunk.Chunk<Out>, In, In>\n  <In>(predicate: Predicate<In>): Sink.Sink<Chunk.Chunk<In>, In, In>\n} = <In>(predicate: Predicate<In>): Sink.Sink<Chunk.Chunk<In>, In, In> =>\n  fromChannel(collectAllWhileReader(predicate, Chunk.empty()))\n\n/** @internal */\nconst collectAllWhileReader = <In>(\n  predicate: Predicate<In>,\n  done: Chunk.Chunk<In>\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, never, never, Chunk.Chunk<In>, unknown> =>\n  core.readWith({\n    onInput: (input: Chunk.Chunk<In>) => {\n      const [collected, leftovers] = pipe(Chunk.toReadonlyArray(input), Arr.span(predicate))\n      if (leftovers.length === 0) {\n        return collectAllWhileReader(\n          predicate,\n          pipe(done, Chunk.appendAll(Chunk.unsafeFromArray(collected)))\n        )\n      }\n      return pipe(\n        core.write(Chunk.unsafeFromArray(leftovers)),\n        channel.zipRight(core.succeed(pipe(done, Chunk.appendAll(Chunk.unsafeFromArray(collected)))))\n      )\n    },\n    onFailure: core.fail,\n    onDone: () => core.succeed(done)\n  })\n\n/** @internal */\nexport const collectAllWhileEffect = <In, E, R>(\n  predicate: (input: In) => Effect.Effect<boolean, E, R>\n): Sink.Sink<Chunk.Chunk<In>, In, In, E, R> => fromChannel(collectAllWhileEffectReader(predicate, Chunk.empty()))\n\n/** @internal */\nconst collectAllWhileEffectReader = <In, R, E>(\n  predicate: (input: In) => Effect.Effect<boolean, E, R>,\n  done: Chunk.Chunk<In>\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, E, never, Chunk.Chunk<In>, unknown, R> =>\n  core.readWith({\n    onInput: (input: Chunk.Chunk<In>) =>\n      pipe(\n        core.fromEffect(pipe(input, Effect.takeWhile(predicate), Effect.map(Chunk.unsafeFromArray))),\n        core.flatMap((collected) => {\n          const leftovers = pipe(input, Chunk.drop(collected.length))\n          if (Chunk.isEmpty(leftovers)) {\n            return collectAllWhileEffectReader(predicate, pipe(done, Chunk.appendAll(collected)))\n          }\n          return pipe(core.write(leftovers), channel.zipRight(core.succeed(pipe(done, Chunk.appendAll(collected)))))\n        })\n      ),\n    onFailure: core.fail,\n    onDone: () => core.succeed(done)\n  })\n\n/** @internal */\nexport const collectAllWhileWith: {\n  <A, S>(\n    options: {\n      readonly initial: S\n      readonly while: Predicate<A>\n      readonly body: (s: S, a: A) => S\n    }\n  ): <In, L extends In, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<S, In, L, E, R>\n  <A, In, L extends In, E, R, S>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly initial: S\n      readonly while: Predicate<A>\n      readonly body: (s: S, a: A) => S\n    }\n  ): Sink.Sink<S, In, L, E, R>\n} = dual(\n  2,\n  <A, In, L extends In, E, R, S>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly initial: S\n      readonly while: Predicate<A>\n      readonly body: (s: S, a: A) => S\n    }\n  ): Sink.Sink<S, In, L, E, R> => {\n    const refs = pipe(\n      Ref.make(Chunk.empty<In>()),\n      Effect.zip(Ref.make(false))\n    )\n    const newChannel = pipe(\n      core.fromEffect(refs),\n      core.flatMap(([leftoversRef, upstreamDoneRef]) => {\n        const upstreamMarker: Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, never, never, unknown, unknown> = core\n          .readWith({\n            onInput: (input) => pipe(core.write(input), core.flatMap(() => upstreamMarker)),\n            onFailure: core.fail,\n            onDone: (done) => pipe(core.fromEffect(Ref.set(upstreamDoneRef, true)), channel.as(done))\n          })\n        return pipe(\n          upstreamMarker,\n          core.pipeTo(channel.bufferChunk(leftoversRef)),\n          core.pipeTo(\n            collectAllWhileWithLoop(self, leftoversRef, upstreamDoneRef, options.initial, options.while, options.body)\n          )\n        )\n      })\n    )\n    return new SinkImpl(newChannel)\n  }\n)\n\nconst collectAllWhileWithLoop = <Z, In, L extends In, E, R, S>(\n  self: Sink.Sink<Z, In, L, E, R>,\n  leftoversRef: Ref.Ref<Chunk.Chunk<In>>,\n  upstreamDoneRef: Ref.Ref<boolean>,\n  currentResult: S,\n  p: Predicate<Z>,\n  f: (s: S, z: Z) => S\n): Channel.Channel<Chunk.Chunk<L>, Chunk.Chunk<In>, E, never, S, unknown, R> => {\n  return pipe(\n    toChannel(self),\n    channel.doneCollect,\n    channel.foldChannel({\n      onFailure: core.fail,\n      onSuccess: ([leftovers, doneValue]) =>\n        p(doneValue)\n          ? pipe(\n            core.fromEffect(\n              Ref.set(leftoversRef, Chunk.flatten(leftovers as Chunk.Chunk<Chunk.Chunk<In>>))\n            ),\n            core.flatMap(() =>\n              pipe(\n                core.fromEffect(Ref.get(upstreamDoneRef)),\n                core.flatMap((upstreamDone) => {\n                  const accumulatedResult = f(currentResult, doneValue)\n                  return upstreamDone\n                    ? pipe(core.write(Chunk.flatten(leftovers)), channel.as(accumulatedResult))\n                    : collectAllWhileWithLoop(self, leftoversRef, upstreamDoneRef, accumulatedResult, p, f)\n                })\n              )\n            )\n          )\n          : pipe(core.write(Chunk.flatten(leftovers)), channel.as(currentResult))\n    })\n  )\n}\n\n/** @internal */\nexport const collectLeftover = <A, In, L, E, R>(\n  self: Sink.Sink<A, In, L, E, R>\n): Sink.Sink<[A, Chunk.Chunk<L>], In, never, E, R> =>\n  new SinkImpl(pipe(core.collectElements(toChannel(self)), channel.map(([chunks, z]) => [z, Chunk.flatten(chunks)])))\n\n/** @internal */\nexport const mapInput = dual<\n  <In0, In>(f: (input: In0) => In) => <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In0, L, E, R>,\n  <A, In, L, E, R, In0>(self: Sink.Sink<A, In, L, E, R>, f: (input: In0) => In) => Sink.Sink<A, In0, L, E, R>\n>(\n  2,\n  <A, In, L, E, R, In0>(self: Sink.Sink<A, In, L, E, R>, f: (input: In0) => In): Sink.Sink<A, In0, L, E, R> =>\n    pipe(self, mapInputChunks(Chunk.map(f)))\n)\n\n/** @internal */\nexport const mapInputEffect = dual<\n  <In0, In, E2, R2>(\n    f: (input: In0) => Effect.Effect<In, E2, R2>\n  ) => <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In0, L, E2 | E, R2 | R>,\n  <A, In, L, E, R, In0, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (input: In0) => Effect.Effect<In, E2, R2>\n  ) => Sink.Sink<A, In0, L, E2 | E, R2 | R>\n>(\n  2,\n  <A, In, L, E, R, In0, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (input: In0) => Effect.Effect<In, E2, R2>\n  ): Sink.Sink<A, In0, L, E | E2, R | R2> =>\n    mapInputChunksEffect(\n      self,\n      (chunk) =>\n        Effect.map(\n          Effect.forEach(chunk, (v) => f(v)),\n          Chunk.unsafeFromArray\n        )\n    )\n)\n\n/** @internal */\nexport const mapInputChunks = dual<\n  <In0, In>(\n    f: (chunk: Chunk.Chunk<In0>) => Chunk.Chunk<In>\n  ) => <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In0, L, E, R>,\n  <A, In, L, E, R, In0>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (chunk: Chunk.Chunk<In0>) => Chunk.Chunk<In>\n  ) => Sink.Sink<A, In0, L, E, R>\n>(\n  2,\n  <A, In, L, E, R, In0>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (chunk: Chunk.Chunk<In0>) => Chunk.Chunk<In>\n  ): Sink.Sink<A, In0, L, E, R> => {\n    const loop: Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In0>, never, never, unknown, unknown, R> = core.readWith({\n      onInput: (chunk) => pipe(core.write(f(chunk)), core.flatMap(() => loop)),\n      onFailure: core.fail,\n      onDone: core.succeed\n    })\n    return new SinkImpl(pipe(loop, core.pipeTo(toChannel(self))))\n  }\n)\n\n/** @internal */\nexport const mapInputChunksEffect = dual<\n  <In0, In, E2, R2>(\n    f: (chunk: Chunk.Chunk<In0>) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n  ) => <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In0, L, E2 | E, R2 | R>,\n  <A, In, L, E, R, In0, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (chunk: Chunk.Chunk<In0>) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n  ) => Sink.Sink<A, In0, L, E2 | E, R2 | R>\n>(\n  2,\n  <A, In, L, E, R, In0, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (chunk: Chunk.Chunk<In0>) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n  ): Sink.Sink<A, In0, L, E | E2, R | R2> => {\n    const loop: Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In0>, E2, never, unknown, unknown, R | R2> = core\n      .readWith({\n        onInput: (chunk) => pipe(core.fromEffect(f(chunk)), core.flatMap(core.write), core.flatMap(() => loop)),\n        onFailure: core.fail,\n        onDone: core.succeed\n      })\n    return new SinkImpl(pipe(loop, channel.pipeToOrFail(toChannel(self))))\n  }\n)\n\n/** @internal */\nexport const die = (defect: unknown): Sink.Sink<never, unknown> => failCause(Cause.die(defect))\n\n/** @internal */\nexport const dieMessage = (message: string): Sink.Sink<never, unknown> =>\n  failCause(Cause.die(new Cause.RuntimeException(message)))\n\n/** @internal */\nexport const dieSync = (evaluate: LazyArg<unknown>): Sink.Sink<never, unknown> =>\n  failCauseSync(() => Cause.die(evaluate()))\n\n/** @internal */\nexport const dimap = dual<\n  <In0, In, A, A2>(\n    options: {\n      readonly onInput: (input: In0) => In\n      readonly onDone: (a: A) => A2\n    }\n  ) => <L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A2, In0, L, E, R>,\n  <A, In, L, E, R, In0, A2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly onInput: (input: In0) => In\n      readonly onDone: (a: A) => A2\n    }\n  ) => Sink.Sink<A2, In0, L, E, R>\n>(\n  2,\n  <A, In, L, E, R, In0, A2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly onInput: (input: In0) => In\n      readonly onDone: (a: A) => A2\n    }\n  ): Sink.Sink<A2, In0, L, E, R> => map(mapInput(self, options.onInput), options.onDone)\n)\n\n/** @internal */\nexport const dimapEffect = dual<\n  <In0, In, E2, R2, A, A2, E3, R3>(\n    options: {\n      readonly onInput: (input: In0) => Effect.Effect<In, E2, R2>\n      readonly onDone: (a: A) => Effect.Effect<A2, E3, R3>\n    }\n  ) => <L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A2, In0, L, E2 | E3 | E, R2 | R3 | R>,\n  <A, In, L, E, R, In0, E2, R2, A2, E3, R3>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly onInput: (input: In0) => Effect.Effect<In, E2, R2>\n      readonly onDone: (a: A) => Effect.Effect<A2, E3, R3>\n    }\n  ) => Sink.Sink<A2, In0, L, E2 | E3 | E, R2 | R3 | R>\n>(\n  2,\n  (self, options) =>\n    mapEffect(\n      mapInputEffect(self, options.onInput),\n      options.onDone\n    )\n)\n\n/** @internal */\nexport const dimapChunks = dual<\n  <In0, In, A, A2>(\n    options: {\n      readonly onInput: (chunk: Chunk.Chunk<In0>) => Chunk.Chunk<In>\n      readonly onDone: (a: A) => A2\n    }\n  ) => <L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A2, In0, L, E, R>,\n  <A, In, L, E, R, In0, A2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly onInput: (chunk: Chunk.Chunk<In0>) => Chunk.Chunk<In>\n      readonly onDone: (a: A) => A2\n    }\n  ) => Sink.Sink<A2, In0, L, E, R>\n>(\n  2,\n  (self, options) =>\n    map(\n      mapInputChunks(self, options.onInput),\n      options.onDone\n    )\n)\n\n/** @internal */\nexport const dimapChunksEffect = dual<\n  <In0, In, E2, R2, A, A2, E3, R3>(\n    options: {\n      readonly onInput: (chunk: Chunk.Chunk<In0>) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n      readonly onDone: (a: A) => Effect.Effect<A2, E3, R3>\n    }\n  ) => <L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A2, In0, L, E2 | E3 | E, R2 | R3 | R>,\n  <A, In, L, E, R, In0, E2, R2, A2, E3, R3>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly onInput: (chunk: Chunk.Chunk<In0>) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n      readonly onDone: (a: A) => Effect.Effect<A2, E3, R3>\n    }\n  ) => Sink.Sink<A2, In0, L, E2 | E3 | E, R2 | R3 | R>\n>(\n  2,\n  (self, options) => mapEffect(mapInputChunksEffect(self, options.onInput), options.onDone)\n)\n\n/** @internal */\nexport const drain: Sink.Sink<void, unknown> = new SinkImpl(\n  channel.drain(channel.identityChannel())\n)\n\n/** @internal */\nexport const drop = <In>(n: number): Sink.Sink<unknown, In, In> => suspend(() => new SinkImpl(dropLoop(n)))\n\n/** @internal */\nconst dropLoop = <In>(\n  n: number\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, never, never, unknown, unknown> =>\n  core.readWith({\n    onInput: (input: Chunk.Chunk<In>) => {\n      const dropped = pipe(input, Chunk.drop(n))\n      const leftover = Math.max(n - input.length, 0)\n      const more = Chunk.isEmpty(input) || leftover > 0\n      if (more) {\n        return dropLoop(leftover)\n      }\n      return pipe(\n        core.write(dropped),\n        channel.zipRight(channel.identityChannel<Chunk.Chunk<In>, never, unknown>())\n      )\n    },\n    onFailure: core.fail,\n    onDone: () => core.void\n  })\n\n/** @internal */\nexport const dropUntil = <In>(predicate: Predicate<In>): Sink.Sink<unknown, In, In> =>\n  new SinkImpl(\n    pipe(toChannel(dropWhile((input: In) => !predicate(input))), channel.pipeToOrFail(toChannel(drop<In>(1))))\n  )\n\n/** @internal */\nexport const dropUntilEffect = <In, E, R>(\n  predicate: (input: In) => Effect.Effect<boolean, E, R>\n): Sink.Sink<unknown, In, In, E, R> => suspend(() => new SinkImpl(dropUntilEffectReader(predicate)))\n\n/** @internal */\nconst dropUntilEffectReader = <In, R, E>(\n  predicate: (input: In) => Effect.Effect<boolean, E, R>\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, E, E, unknown, unknown, R> =>\n  core.readWith({\n    onInput: (input: Chunk.Chunk<In>) =>\n      pipe(\n        input,\n        Effect.dropUntil(predicate),\n        Effect.map((leftover) => {\n          const more = leftover.length === 0\n          return more ?\n            dropUntilEffectReader(predicate) :\n            pipe(\n              core.write(Chunk.unsafeFromArray(leftover)),\n              channel.zipRight(channel.identityChannel<Chunk.Chunk<In>, E, unknown>())\n            )\n        }),\n        channel.unwrap\n      ),\n    onFailure: core.fail,\n    onDone: () => core.void\n  })\n\n/** @internal */\nexport const dropWhile = <In>(predicate: Predicate<In>): Sink.Sink<unknown, In, In> =>\n  new SinkImpl(dropWhileReader(predicate))\n\n/** @internal */\nconst dropWhileReader = <In>(\n  predicate: Predicate<In>\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, never, never, unknown, unknown> =>\n  core.readWith({\n    onInput: (input: Chunk.Chunk<In>) => {\n      const out = pipe(input, Chunk.dropWhile(predicate))\n      if (Chunk.isEmpty(out)) {\n        return dropWhileReader(predicate)\n      }\n      return pipe(core.write(out), channel.zipRight(channel.identityChannel<Chunk.Chunk<In>, never, unknown>()))\n    },\n    onFailure: core.fail,\n    onDone: core.succeedNow\n  })\n\n/** @internal */\nexport const dropWhileEffect = <In, E, R>(\n  predicate: (input: In) => Effect.Effect<boolean, E, R>\n): Sink.Sink<unknown, In, In, E, R> => suspend(() => new SinkImpl(dropWhileEffectReader(predicate)))\n\n/** @internal */\nconst dropWhileEffectReader = <In, R, E>(\n  predicate: (input: In) => Effect.Effect<boolean, E, R>\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, E, E, unknown, unknown, R> =>\n  core.readWith({\n    onInput: (input: Chunk.Chunk<In>) =>\n      pipe(\n        input,\n        Effect.dropWhile(predicate),\n        Effect.map((leftover) => {\n          const more = leftover.length === 0\n          return more ?\n            dropWhileEffectReader(predicate) :\n            pipe(\n              core.write(Chunk.unsafeFromArray(leftover)),\n              channel.zipRight(channel.identityChannel<Chunk.Chunk<In>, E, unknown>())\n            )\n        }),\n        channel.unwrap\n      ),\n    onFailure: core.fail,\n    onDone: () => core.void\n  })\n\n/** @internal */\nexport const ensuring = dual<\n  <X, R2>(\n    finalizer: Effect.Effect<X, never, R2>\n  ) => <A, In, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In, L, E, R2 | R>,\n  <A, In, L, E, R, X, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    finalizer: Effect.Effect<X, never, R2>\n  ) => Sink.Sink<A, In, L, E, R2 | R>\n>(\n  2,\n  (self, finalizer) => new SinkImpl(pipe(self, toChannel, channel.ensuring(finalizer)))\n)\n\n/** @internal */\nexport const ensuringWith = dual<\n  <A, E, X, R2>(\n    finalizer: (exit: Exit.Exit<A, E>) => Effect.Effect<X, never, R2>\n  ) => <In, L, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In, L, E, R2 | R>,\n  <A, In, L, E, R, X, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    finalizer: (exit: Exit.Exit<A, E>) => Effect.Effect<X, never, R2>\n  ) => Sink.Sink<A, In, L, E, R2 | R>\n>(\n  2,\n  (self, finalizer) => new SinkImpl(pipe(self, toChannel, core.ensuringWith(finalizer)))\n)\n\n/** @internal */\nexport const context = <R>(): Sink.Sink<Context.Context<R>, unknown, never, never, R> => fromEffect(Effect.context<R>())\n\n/** @internal */\nexport const contextWith = <R, Z>(\n  f: (context: Context.Context<R>) => Z\n): Sink.Sink<Z, unknown, never, never, R> => pipe(context<R>(), map(f))\n\n/** @internal */\nexport const contextWithEffect = <R0, A, E, R>(\n  f: (context: Context.Context<R0>) => Effect.Effect<A, E, R>\n): Sink.Sink<A, unknown, never, E, R0 | R> => pipe(context<R0>(), mapEffect(f))\n\n/** @internal */\nexport const contextWithSink = <R0, A, In, L, E, R>(\n  f: (context: Context.Context<R0>) => Sink.Sink<A, In, L, E, R>\n): Sink.Sink<A, In, L, E, R0 | R> =>\n  new SinkImpl(channel.unwrap(Effect.contextWith((context) => toChannel(f(context)))))\n\n/** @internal */\nexport const every = <In>(predicate: Predicate<In>): Sink.Sink<boolean, In, In> =>\n  fold(true, identity, (acc, input) => acc && predicate(input))\n\n/** @internal */\nexport const fail = <E>(e: E): Sink.Sink<never, unknown, never, E> => new SinkImpl(core.fail(e))\n\n/** @internal */\nexport const failSync = <E>(evaluate: LazyArg<E>): Sink.Sink<never, unknown, never, E> =>\n  new SinkImpl(core.failSync(evaluate))\n\n/** @internal */\nexport const failCause = <E>(cause: Cause.Cause<E>): Sink.Sink<never, unknown, never, E> =>\n  new SinkImpl(core.failCause(cause))\n\n/** @internal */\nexport const failCauseSync = <E>(evaluate: LazyArg<Cause.Cause<E>>): Sink.Sink<never, unknown, never, E> =>\n  new SinkImpl(core.failCauseSync(evaluate))\n\n/** @internal */\nexport const filterInput: {\n  <In, In1 extends In, In2 extends In1>(\n    f: Refinement<In1, In2>\n  ): <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In2, L, E, R>\n  <In, In1 extends In>(f: Predicate<In1>): <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In1, L, E, R>\n} = <In, In1 extends In>(f: Predicate<In1>) => {\n  return <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>): Sink.Sink<A, In1, L, E, R> =>\n    pipe(self, mapInputChunks(Chunk.filter(f)))\n}\n\n/** @internal */\nexport const filterInputEffect = dual<\n  <In, In1 extends In, E2, R2>(\n    f: (input: In1) => Effect.Effect<boolean, E2, R2>\n  ) => <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In1, L, E2 | E, R2 | R>,\n  <A, In, L, E, R, In1 extends In, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (input: In1) => Effect.Effect<boolean, E2, R2>\n  ) => Sink.Sink<A, In1, L, E2 | E, R2 | R>\n>(\n  2,\n  (self, f) =>\n    mapInputChunksEffect(\n      self,\n      (chunk) => Effect.map(Effect.filter(chunk, f), Chunk.unsafeFromArray)\n    )\n)\n\n/** @internal */\nexport const findEffect = dual<\n  <A, E2, R2>(\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ) => <In, L extends In, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<Option.Option<A>, In, L, E2 | E, R2 | R>,\n  <A, In, L extends In, E, R, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ) => Sink.Sink<Option.Option<A>, In, L, E2 | E, R2 | R>\n>(\n  2,\n  <A, In, L extends In, E, R, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): Sink.Sink<Option.Option<A>, In, L, E2 | E, R2 | R> => {\n    const newChannel = pipe(\n      core.fromEffect(pipe(\n        Ref.make(Chunk.empty<In>()),\n        Effect.zip(Ref.make(false))\n      )),\n      core.flatMap(([leftoversRef, upstreamDoneRef]) => {\n        const upstreamMarker: Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, never, never, unknown, unknown> = core\n          .readWith({\n            onInput: (input) => pipe(core.write(input), core.flatMap(() => upstreamMarker)),\n            onFailure: core.fail,\n            onDone: (done) => pipe(core.fromEffect(Ref.set(upstreamDoneRef, true)), channel.as(done))\n          })\n        const loop: Channel.Channel<Chunk.Chunk<L>, Chunk.Chunk<In>, E | E2, never, Option.Option<A>, unknown, R | R2> =\n          channel.foldChannel(core.collectElements(toChannel(self)), {\n            onFailure: core.fail,\n            onSuccess: ([leftovers, doneValue]) =>\n              pipe(\n                core.fromEffect(f(doneValue)),\n                core.flatMap((satisfied) =>\n                  pipe(\n                    core.fromEffect(Ref.set(leftoversRef, Chunk.flatten(leftovers))),\n                    channel.zipRight(\n                      pipe(\n                        core.fromEffect(Ref.get(upstreamDoneRef)),\n                        core.flatMap((upstreamDone) => {\n                          if (satisfied) {\n                            return pipe(core.write(Chunk.flatten(leftovers)), channel.as(Option.some(doneValue)))\n                          }\n                          if (upstreamDone) {\n                            return pipe(core.write(Chunk.flatten(leftovers)), channel.as(Option.none()))\n                          }\n                          return loop\n                        })\n                      )\n                    )\n                  )\n                )\n              )\n          })\n        return pipe(upstreamMarker, core.pipeTo(channel.bufferChunk(leftoversRef)), core.pipeTo(loop))\n      })\n    )\n    return new SinkImpl(newChannel)\n  }\n)\n\n/** @internal */\nexport const fold = <S, In>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (s: S, input: In) => S\n): Sink.Sink<S, In, In> => suspend(() => new SinkImpl(foldReader(s, contFn, f)))\n\n/** @internal */\nconst foldReader = <S, In>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (z: S, input: In) => S\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, never, never, S, unknown> => {\n  if (!contFn(s)) {\n    return core.succeedNow(s)\n  }\n  return core.readWith({\n    onInput: (input: Chunk.Chunk<In>) => {\n      const [nextS, leftovers] = foldChunkSplit(s, input, contFn, f, 0, input.length)\n      if (Chunk.isNonEmpty(leftovers)) {\n        return pipe(core.write(leftovers), channel.as(nextS))\n      }\n      return foldReader(nextS, contFn, f)\n    },\n    onFailure: core.fail,\n    onDone: () => core.succeedNow(s)\n  })\n}\n\n/** @internal */\nconst foldChunkSplit = <S, In>(\n  s: S,\n  chunk: Chunk.Chunk<In>,\n  contFn: Predicate<S>,\n  f: (z: S, input: In) => S,\n  index: number,\n  length: number\n): [S, Chunk.Chunk<In>] => {\n  if (index === length) {\n    return [s, Chunk.empty()]\n  }\n  const s1 = f(s, pipe(chunk, Chunk.unsafeGet(index)))\n  if (contFn(s1)) {\n    return foldChunkSplit(s1, chunk, contFn, f, index + 1, length)\n  }\n  return [s1, pipe(chunk, Chunk.drop(index + 1))]\n}\n\n/** @internal */\nexport const foldSink = dual<\n  <E, A1, In, In1 extends In, L1, E1, R1, A, A2, In2 extends In, L2, E2, R2>(\n    options: {\n      readonly onFailure: (err: E) => Sink.Sink<A1, In1, L1, E1, R1>\n      readonly onSuccess: (a: A) => Sink.Sink<A2, In2, L2, E2, R2>\n    }\n  ) => <L, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A1 | A2, In1 & In2, L1 | L2, E1 | E2, R1 | R2 | R>,\n  <A, In, L, E, R, A1, In1 extends In, L1, E1, R1, A2, In2 extends In, L2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly onFailure: (err: E) => Sink.Sink<A1, In1, L1, E1, R1>\n      readonly onSuccess: (a: A) => Sink.Sink<A2, In2, L2, E2, R2>\n    }\n  ) => Sink.Sink<A1 | A2, In1 & In2, L1 | L2, E1 | E2, R1 | R2 | R>\n>(\n  2,\n  <A, In, L, E, R, A1, In1 extends In, L1, E1, R1, A2, In2 extends In, L2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly onFailure: (err: E) => Sink.Sink<A1, In1, L1, E1, R1>\n      readonly onSuccess: (z: A) => Sink.Sink<A2, In2, L2, E2, R2>\n    }\n  ): Sink.Sink<A1 | A2, In1 & In2, L1 | L2, E1 | E2, R | R1 | R2> => {\n    const newChannel: Channel.Channel<\n      Chunk.Chunk<L1 | L2>,\n      Chunk.Chunk<In1 & In2>,\n      E1 | E2,\n      never,\n      A1 | A2,\n      unknown,\n      R | R1 | R2\n    > = pipe(\n      toChannel(self),\n      core.collectElements,\n      channel.foldChannel({\n        onFailure: (error) => toChannel(options.onFailure(error)),\n        onSuccess: ([leftovers, z]) =>\n          core.suspend(() => {\n            const leftoversRef = {\n              ref: pipe(leftovers, Chunk.filter(Chunk.isNonEmpty)) as Chunk.Chunk<Chunk.Chunk<L1 | L2>>\n            }\n            const refReader = pipe(\n              core.sync(() => {\n                const ref = leftoversRef.ref\n                leftoversRef.ref = Chunk.empty()\n                return ref\n              }),\n              // This cast is safe because of the L1 >: L <: In1 bound. It follows that\n              // L <: In1 and therefore Chunk[L] can be safely cast to Chunk[In1].\n              core.flatMap((chunk) => channel.writeChunk(chunk as Chunk.Chunk<Chunk.Chunk<In1 & In2>>))\n            )\n            const passthrough = channel.identityChannel<Chunk.Chunk<In1 & In2>, never, unknown>()\n            const continuationSink = pipe(\n              refReader,\n              channel.zipRight(passthrough),\n              core.pipeTo(toChannel(options.onSuccess(z)))\n            )\n            return core.flatMap(\n              core.collectElements(continuationSink),\n              ([newLeftovers, z1]) =>\n                pipe(\n                  core.succeed(leftoversRef.ref),\n                  core.flatMap(channel.writeChunk),\n                  channel.zipRight(channel.writeChunk(newLeftovers)),\n                  channel.as(z1)\n                )\n            )\n          })\n      })\n    )\n    return new SinkImpl(newChannel)\n  }\n)\n\n/** @internal */\nexport const foldChunks = <S, In>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (s: S, chunk: Chunk.Chunk<In>) => S\n): Sink.Sink<S, In> => suspend(() => new SinkImpl(foldChunksReader(s, contFn, f)))\n\n/** @internal */\nconst foldChunksReader = <S, In>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (s: S, chunk: Chunk.Chunk<In>) => S\n): Channel.Channel<never, Chunk.Chunk<In>, never, never, S, unknown> => {\n  if (!contFn(s)) {\n    return core.succeedNow(s)\n  }\n  return core.readWith({\n    onInput: (input: Chunk.Chunk<In>) => foldChunksReader(f(s, input), contFn, f),\n    onFailure: core.fail,\n    onDone: () => core.succeedNow(s)\n  })\n}\n\n/** @internal */\nexport const foldChunksEffect = <S, In, E, R>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (s: S, chunk: Chunk.Chunk<In>) => Effect.Effect<S, E, R>\n): Sink.Sink<S, In, In, E, R> => suspend(() => new SinkImpl(foldChunksEffectReader(s, contFn, f)))\n\n/** @internal */\nconst foldChunksEffectReader = <S, R, E, In>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (s: S, chunk: Chunk.Chunk<In>) => Effect.Effect<S, E, R>\n): Channel.Channel<never, Chunk.Chunk<In>, E, E, S, unknown, R> => {\n  if (!contFn(s)) {\n    return core.succeedNow(s)\n  }\n  return core.readWith({\n    onInput: (input: Chunk.Chunk<In>) =>\n      pipe(\n        core.fromEffect(f(s, input)),\n        core.flatMap((s) => foldChunksEffectReader(s, contFn, f))\n      ),\n    onFailure: core.fail,\n    onDone: () => core.succeedNow(s)\n  })\n}\n\n/** @internal */\nexport const foldEffect = <S, In, E, R>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (s: S, input: In) => Effect.Effect<S, E, R>\n): Sink.Sink<S, In, In, E, R> => suspend(() => new SinkImpl(foldEffectReader(s, contFn, f)))\n\n/** @internal */\nconst foldEffectReader = <S, In, R, E>(\n  s: S,\n  contFn: Predicate<S>,\n  f: (s: S, input: In) => Effect.Effect<S, E, R>\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, E, E, S, unknown, R> => {\n  if (!contFn(s)) {\n    return core.succeedNow(s)\n  }\n  return core.readWith({\n    onInput: (input: Chunk.Chunk<In>) =>\n      pipe(\n        core.fromEffect(foldChunkSplitEffect(s, input, contFn, f)),\n        core.flatMap(([nextS, leftovers]) =>\n          pipe(\n            leftovers,\n            Option.match({\n              onNone: () => foldEffectReader(nextS, contFn, f),\n              onSome: (leftover) => pipe(core.write(leftover), channel.as(nextS))\n            })\n          )\n        )\n      ),\n    onFailure: core.fail,\n    onDone: () => core.succeedNow(s)\n  })\n}\n\n/** @internal */\nconst foldChunkSplitEffect = <S, R, E, In>(\n  s: S,\n  chunk: Chunk.Chunk<In>,\n  contFn: Predicate<S>,\n  f: (s: S, input: In) => Effect.Effect<S, E, R>\n): Effect.Effect<[S, Option.Option<Chunk.Chunk<In>>], E, R> =>\n  foldChunkSplitEffectInternal(s, chunk, 0, chunk.length, contFn, f)\n\n/** @internal */\nconst foldChunkSplitEffectInternal = <S, R, E, In>(\n  s: S,\n  chunk: Chunk.Chunk<In>,\n  index: number,\n  length: number,\n  contFn: Predicate<S>,\n  f: (s: S, input: In) => Effect.Effect<S, E, R>\n): Effect.Effect<[S, Option.Option<Chunk.Chunk<In>>], E, R> => {\n  if (index === length) {\n    return Effect.succeed([s, Option.none()])\n  }\n  return pipe(\n    f(s, pipe(chunk, Chunk.unsafeGet(index))),\n    Effect.flatMap((s1) =>\n      contFn(s1) ?\n        foldChunkSplitEffectInternal(s1, chunk, index + 1, length, contFn, f) :\n        Effect.succeed([s1, Option.some(pipe(chunk, Chunk.drop(index + 1)))])\n    )\n  )\n}\n\n/** @internal */\nexport const foldLeft = <S, In>(s: S, f: (s: S, input: In) => S): Sink.Sink<S, In> =>\n  ignoreLeftover(fold(s, constTrue, f))\n\n/** @internal */\nexport const foldLeftChunks = <S, In>(\n  s: S,\n  f: (s: S, chunk: Chunk.Chunk<In>) => S\n): Sink.Sink<S, In> => foldChunks(s, constTrue, f)\n\n/** @internal */\nexport const foldLeftChunksEffect = <S, In, E, R>(\n  s: S,\n  f: (s: S, chunk: Chunk.Chunk<In>) => Effect.Effect<S, E, R>\n): Sink.Sink<S, In, never, E, R> => ignoreLeftover(foldChunksEffect(s, constTrue, f))\n\n/** @internal */\nexport const foldLeftEffect = <S, In, E, R>(\n  s: S,\n  f: (s: S, input: In) => Effect.Effect<S, E, R>\n): Sink.Sink<S, In, In, E, R> => foldEffect(s, constTrue, f)\n\n/** @internal */\nexport const foldUntil = <S, In>(s: S, max: number, f: (s: S, input: In) => S): Sink.Sink<S, In, In> =>\n  pipe(\n    fold<[S, number], In>(\n      [s, 0],\n      (tuple) => tuple[1] < max,\n      ([output, count], input) => [f(output, input), count + 1]\n    ),\n    map((tuple) => tuple[0])\n  )\n\n/** @internal */\nexport const foldUntilEffect = <S, In, E, R>(\n  s: S,\n  max: number,\n  f: (s: S, input: In) => Effect.Effect<S, E, R>\n): Sink.Sink<S, In, In, E, R> =>\n  pipe(\n    foldEffect(\n      [s, 0 as number] as const,\n      (tuple) => tuple[1] < max,\n      ([output, count], input: In) => pipe(f(output, input), Effect.map((s) => [s, count + 1] as const))\n    ),\n    map((tuple) => tuple[0])\n  )\n\n/** @internal */\nexport const foldWeighted = <S, In>(\n  options: {\n    readonly initial: S\n    readonly maxCost: number\n    readonly cost: (s: S, input: In) => number\n    readonly body: (s: S, input: In) => S\n  }\n): Sink.Sink<S, In, In> =>\n  foldWeightedDecompose({\n    ...options,\n    decompose: Chunk.of\n  })\n\n/** @internal */\nexport const foldWeightedDecompose = <S, In>(\n  options: {\n    readonly initial: S\n    readonly maxCost: number\n    readonly cost: (s: S, input: In) => number\n    readonly decompose: (input: In) => Chunk.Chunk<In>\n    readonly body: (s: S, input: In) => S\n  }\n): Sink.Sink<S, In, In> =>\n  suspend(() =>\n    new SinkImpl(\n      foldWeightedDecomposeLoop(\n        options.initial,\n        0,\n        false,\n        options.maxCost,\n        options.cost,\n        options.decompose,\n        options.body\n      )\n    )\n  )\n\n/** @internal */\nconst foldWeightedDecomposeLoop = <S, In>(\n  s: S,\n  cost: number,\n  dirty: boolean,\n  max: number,\n  costFn: (s: S, input: In) => number,\n  decompose: (input: In) => Chunk.Chunk<In>,\n  f: (s: S, input: In) => S\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, never, never, S, unknown> =>\n  core.readWith({\n    onInput: (input: Chunk.Chunk<In>) => {\n      const [nextS, nextCost, nextDirty, leftovers] = foldWeightedDecomposeFold(\n        input,\n        s,\n        cost,\n        dirty,\n        max,\n        costFn,\n        decompose,\n        f\n      )\n      if (Chunk.isNonEmpty(leftovers)) {\n        return pipe(core.write(leftovers), channel.zipRight(core.succeedNow(nextS)))\n      }\n      if (cost > max) {\n        return core.succeedNow(nextS)\n      }\n      return foldWeightedDecomposeLoop(nextS, nextCost, nextDirty, max, costFn, decompose, f)\n    },\n    onFailure: core.fail,\n    onDone: () => core.succeedNow(s)\n  })\n\n/** @internal */\nconst foldWeightedDecomposeFold = <In, S>(\n  input: Chunk.Chunk<In>,\n  s: S,\n  cost: number,\n  dirty: boolean,\n  max: number,\n  costFn: (s: S, input: In) => number,\n  decompose: (input: In) => Chunk.Chunk<In>,\n  f: (s: S, input: In) => S\n): [S, number, boolean, Chunk.Chunk<In>] => {\n  for (let index = 0; index < input.length; index++) {\n    const elem = Chunk.unsafeGet(input, index)\n    const prevCost = cost\n    cost = cost + costFn(s, elem)\n    if (cost <= max) {\n      s = f(s, elem)\n      dirty = true\n      continue\n    }\n    const decomposed = decompose(elem)\n    if (decomposed.length <= 1 && !dirty) {\n      // If `elem` cannot be decomposed, we need to cross the `max` threshold. To\n      // minimize \"injury\", we only allow this when we haven't added anything else\n      // to the aggregate (dirty = false).\n      return [f(s, elem), cost, true, Chunk.drop(input, index + 1)]\n    }\n    if (decomposed.length <= 1 && dirty) {\n      // If the state is dirty and `elem` cannot be decomposed, we stop folding\n      // and include `elem` in the leftovers.\n      return [s, prevCost, dirty, Chunk.drop(input, index)]\n    }\n    // `elem` got decomposed, so we will recurse with the decomposed elements pushed\n    // into the chunk we're processing and see if we can aggregate further.\n    input = Chunk.appendAll(decomposed, Chunk.drop(input, index + 1))\n    cost = prevCost\n    index = -1\n  }\n  return [s, cost, dirty, Chunk.empty<In>()]\n}\n\n/** @internal */\nexport const foldWeightedDecomposeEffect = <S, In, E, R, E2, R2, E3, R3>(\n  options: {\n    readonly initial: S\n    readonly maxCost: number\n    readonly cost: (s: S, input: In) => Effect.Effect<number, E, R>\n    readonly decompose: (input: In) => Effect.Effect<Chunk.Chunk<In>, E2, R2>\n    readonly body: (s: S, input: In) => Effect.Effect<S, E3, R3>\n  }\n): Sink.Sink<S, In, In, E | E2 | E3, R | R2 | R3> =>\n  suspend(() =>\n    new SinkImpl(\n      foldWeightedDecomposeEffectLoop(\n        options.initial,\n        options.maxCost,\n        options.cost,\n        options.decompose,\n        options.body,\n        0,\n        false\n      )\n    )\n  )\n\n/** @internal */\nexport const foldWeightedEffect = <S, In, E, R, E2, R2>(\n  options: {\n    readonly initial: S\n    readonly maxCost: number\n    readonly cost: (s: S, input: In) => Effect.Effect<number, E, R>\n    readonly body: (s: S, input: In) => Effect.Effect<S, E2, R2>\n  }\n): Sink.Sink<S, In, In, E | E2, R | R2> =>\n  foldWeightedDecomposeEffect({\n    ...options,\n    decompose: (input) => Effect.succeed(Chunk.of(input))\n  })\n\nconst foldWeightedDecomposeEffectLoop = <S, In, E, R, E2, R2, E3, R3>(\n  s: S,\n  max: number,\n  costFn: (s: S, input: In) => Effect.Effect<number, E, R>,\n  decompose: (input: In) => Effect.Effect<Chunk.Chunk<In>, E2, R2>,\n  f: (s: S, input: In) => Effect.Effect<S, E3, R3>,\n  cost: number,\n  dirty: boolean\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, E | E2 | E3, E | E2 | E3, S, unknown, R | R2 | R3> =>\n  core.readWith({\n    onInput: (input: Chunk.Chunk<In>) =>\n      pipe(\n        core.fromEffect(foldWeightedDecomposeEffectFold(s, max, costFn, decompose, f, input, dirty, cost, 0)),\n        core.flatMap(([nextS, nextCost, nextDirty, leftovers]) => {\n          if (Chunk.isNonEmpty(leftovers)) {\n            return pipe(core.write(leftovers), channel.zipRight(core.succeedNow(nextS)))\n          }\n          if (cost > max) {\n            return core.succeedNow(nextS)\n          }\n          return foldWeightedDecomposeEffectLoop(nextS, max, costFn, decompose, f, nextCost, nextDirty)\n        })\n      ),\n    onFailure: core.fail,\n    onDone: () => core.succeedNow(s)\n  })\n\n/** @internal */\nconst foldWeightedDecomposeEffectFold = <S, In, E, R, E2, R2, E3, R3>(\n  s: S,\n  max: number,\n  costFn: (s: S, input: In) => Effect.Effect<number, E, R>,\n  decompose: (input: In) => Effect.Effect<Chunk.Chunk<In>, E2, R2>,\n  f: (s: S, input: In) => Effect.Effect<S, E3, R3>,\n  input: Chunk.Chunk<In>,\n  dirty: boolean,\n  cost: number,\n  index: number\n): Effect.Effect<[S, number, boolean, Chunk.Chunk<In>], E | E2 | E3, R | R2 | R3> => {\n  if (index === input.length) {\n    return Effect.succeed([s, cost, dirty, Chunk.empty<In>()])\n  }\n  const elem = pipe(input, Chunk.unsafeGet(index))\n  return pipe(\n    costFn(s, elem),\n    Effect.map((newCost) => cost + newCost),\n    Effect.flatMap((total) => {\n      if (total <= max) {\n        return pipe(\n          f(s, elem),\n          Effect.flatMap((s) =>\n            foldWeightedDecomposeEffectFold(s, max, costFn, decompose, f, input, true, total, index + 1)\n          )\n        )\n      }\n      return pipe(\n        decompose(elem),\n        Effect.flatMap((decomposed) => {\n          if (decomposed.length <= 1 && !dirty) {\n            // If `elem` cannot be decomposed, we need to cross the `max` threshold. To\n            // minimize \"injury\", we only allow this when we haven't added anything else\n            // to the aggregate (dirty = false).\n            return pipe(\n              f(s, elem),\n              Effect.map((s) => [s, total, true, pipe(input, Chunk.drop(index + 1))])\n            )\n          }\n          if (decomposed.length <= 1 && dirty) {\n            // If the state is dirty and `elem` cannot be decomposed, we stop folding\n            // and include `elem` in th leftovers.\n            return Effect.succeed([s, cost, dirty, pipe(input, Chunk.drop(index))])\n          }\n          // `elem` got decomposed, so we will recurse with the decomposed elements pushed\n          // into the chunk we're processing and see if we can aggregate further.\n          const next = pipe(decomposed, Chunk.appendAll(pipe(input, Chunk.drop(index + 1))))\n          return foldWeightedDecomposeEffectFold(s, max, costFn, decompose, f, next, dirty, cost, 0)\n        })\n      )\n    })\n  )\n}\n\n/** @internal */\nexport const flatMap = dual<\n  <A, A1, In, In1 extends In, L1, E1, R1>(\n    f: (a: A) => Sink.Sink<A1, In1, L1, E1, R1>\n  ) => <L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A1, In & In1, L | L1, E1 | E, R1 | R>,\n  <A, In, L, E, R, A1, In1 extends In, L1, E1, R1>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (a: A) => Sink.Sink<A1, In1, L1, E1, R1>\n  ) => Sink.Sink<A1, In & In1, L | L1, E1 | E, R1 | R>\n>(\n  2,\n  (self, f) => foldSink(self, { onFailure: fail, onSuccess: f })\n)\n\n/** @internal */\nexport const forEach = <In, X, E, R>(f: (input: In) => Effect.Effect<X, E, R>): Sink.Sink<void, In, never, E, R> => {\n  const process: Channel.Channel<never, Chunk.Chunk<In>, E, E, void, unknown, R> = core.readWithCause({\n    onInput: (input: Chunk.Chunk<In>) =>\n      pipe(core.fromEffect(Effect.forEach(input, (v) => f(v), { discard: true })), core.flatMap(() => process)),\n    onFailure: core.failCause,\n    onDone: () => core.void\n  })\n  return new SinkImpl(process)\n}\n\n/** @internal */\nexport const forEachChunk = <In, X, E, R>(\n  f: (input: Chunk.Chunk<In>) => Effect.Effect<X, E, R>\n): Sink.Sink<void, In, never, E, R> => {\n  const process: Channel.Channel<never, Chunk.Chunk<In>, E, E, void, unknown, R> = core.readWithCause({\n    onInput: (input: Chunk.Chunk<In>) => pipe(core.fromEffect(f(input)), core.flatMap(() => process)),\n    onFailure: core.failCause,\n    onDone: () => core.void\n  })\n  return new SinkImpl(process)\n}\n\n/** @internal */\nexport const forEachWhile = <In, E, R>(\n  f: (input: In) => Effect.Effect<boolean, E, R>\n): Sink.Sink<void, In, In, E, R> => {\n  const process: Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, E, E, void, unknown, R> = core.readWithCause({\n    onInput: (input: Chunk.Chunk<In>) => forEachWhileReader(f, input, 0, input.length, process),\n    onFailure: core.failCause,\n    onDone: () => core.void\n  })\n  return new SinkImpl(process)\n}\n\n/** @internal */\nconst forEachWhileReader = <In, E, R>(\n  f: (input: In) => Effect.Effect<boolean, E, R>,\n  input: Chunk.Chunk<In>,\n  index: number,\n  length: number,\n  cont: Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, E, E, void, unknown, R>\n): Channel.Channel<Chunk.Chunk<In>, Chunk.Chunk<In>, E, E, void, unknown, R> => {\n  if (index === length) {\n    return cont\n  }\n  return pipe(\n    core.fromEffect(f(pipe(input, Chunk.unsafeGet(index)))),\n    core.flatMap((bool) =>\n      bool ?\n        forEachWhileReader(f, input, index + 1, length, cont) :\n        core.write(pipe(input, Chunk.drop(index)))\n    ),\n    channel.catchAll((error) => pipe(core.write(pipe(input, Chunk.drop(index))), channel.zipRight(core.fail(error))))\n  )\n}\n\n/** @internal */\nexport const forEachChunkWhile = <In, E, R>(\n  f: (input: Chunk.Chunk<In>) => Effect.Effect<boolean, E, R>\n): Sink.Sink<void, In, In, E, R> => {\n  const reader: Channel.Channel<never, Chunk.Chunk<In>, E, E, void, unknown, R> = core.readWith({\n    onInput: (input: Chunk.Chunk<In>) =>\n      pipe(\n        core.fromEffect(f(input)),\n        core.flatMap((cont) => cont ? reader : core.void)\n      ),\n    onFailure: core.fail,\n    onDone: () => core.void\n  })\n  return new SinkImpl(reader)\n}\n\n/** @internal */\nexport const fromChannel = <L, In, E, A, R>(\n  channel: Channel.Channel<Chunk.Chunk<L>, Chunk.Chunk<In>, E, never, A, unknown, R>\n): Sink.Sink<A, In, L, E, R> => new SinkImpl(channel)\n\n/** @internal */\nexport const fromEffect = <A, E, R>(effect: Effect.Effect<A, E, R>): Sink.Sink<A, unknown, never, E, R> =>\n  new SinkImpl(core.fromEffect(effect))\n\n/** @internal */\nexport const fromPubSub = <In>(\n  pubsub: PubSub.PubSub<In>,\n  options?: {\n    readonly shutdown?: boolean | undefined\n  }\n): Sink.Sink<void, In> => fromQueue(pubsub, options)\n\n/** @internal */\nexport const fromPush = <In, L0, R0, L, R>(\n  push: Effect.Effect<\n    (_: Option.Option<Chunk.Chunk<In>>) => Effect.Effect<void, readonly [Either.Either<R0, L0>, Chunk.Chunk<L>], R>,\n    never,\n    R\n  >\n): Sink.Sink<R0, In, L, L0, Exclude<R, Scope.Scope>> =>\n  new SinkImpl(channel.unwrapScoped(pipe(push, Effect.map(fromPushPull))))\n\nconst fromPushPull = <In, Z, E, L, R>(\n  push: (\n    option: Option.Option<Chunk.Chunk<In>>\n  ) => Effect.Effect<void, readonly [Either.Either<Z, E>, Chunk.Chunk<L>], R>\n): Channel.Channel<Chunk.Chunk<L>, Chunk.Chunk<In>, E, never, Z, unknown, R> =>\n  core.readWith({\n    onInput: (input: Chunk.Chunk<In>) =>\n      channel.foldChannel(core.fromEffect(push(Option.some(input))), {\n        onFailure: ([either, leftovers]) =>\n          Either.match(either, {\n            onLeft: (error) => pipe(core.write(leftovers), channel.zipRight(core.fail(error))),\n            onRight: (z) => pipe(core.write(leftovers), channel.zipRight(core.succeedNow(z)))\n          }),\n        onSuccess: () => fromPushPull(push)\n      }),\n    onFailure: core.fail,\n    onDone: () =>\n      channel.foldChannel(core.fromEffect(push(Option.none())), {\n        onFailure: ([either, leftovers]) =>\n          Either.match(either, {\n            onLeft: (error) => pipe(core.write(leftovers), channel.zipRight(core.fail(error))),\n            onRight: (z) => pipe(core.write(leftovers), channel.zipRight(core.succeedNow(z)))\n          }),\n        onSuccess: () =>\n          core.fromEffect(\n            Effect.dieMessage(\n              \"BUG: Sink.fromPush - please report an issue at https://github.com/Effect-TS/effect/issues\"\n            )\n          )\n      })\n  })\n\n/** @internal */\nexport const fromQueue = <In>(\n  queue: Queue.Enqueue<In>,\n  options?: {\n    readonly shutdown?: boolean | undefined\n  }\n): Sink.Sink<void, In> =>\n  options?.shutdown ?\n    unwrapScoped(\n      Effect.map(\n        Effect.acquireRelease(Effect.succeed(queue), Queue.shutdown),\n        fromQueue\n      )\n    ) :\n    forEachChunk((input: Chunk.Chunk<In>) => Queue.offerAll(queue, input))\n\n/** @internal */\nexport const head = <In>(): Sink.Sink<Option.Option<In>, In, In> =>\n  fold(\n    Option.none() as Option.Option<In>,\n    Option.isNone,\n    (option, input) =>\n      Option.match(option, {\n        onNone: () => Option.some(input),\n        onSome: () => option\n      })\n  )\n\n/** @internal */\nexport const ignoreLeftover = <A, In, L, E, R>(self: Sink.Sink<A, In, L, E, R>): Sink.Sink<A, In, never, E, R> =>\n  new SinkImpl(channel.drain(toChannel(self)))\n\n/** @internal */\nexport const last = <In>(): Sink.Sink<Option.Option<In>, In, In> =>\n  foldLeftChunks(Option.none<In>(), (s, input) => Option.orElse(Chunk.last(input), () => s))\n\n/** @internal */\nexport const leftover = <L>(chunk: Chunk.Chunk<L>): Sink.Sink<void, unknown, L> =>\n  new SinkImpl(core.suspend(() => core.write(chunk)))\n\n/** @internal */\nexport const map = dual<\n  <A, A2>(f: (a: A) => A2) => <In, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A2, In, L, E, R>,\n  <A, In, L, E, R, A2>(self: Sink.Sink<A, In, L, E, R>, f: (a: A) => A2) => Sink.Sink<A2, In, L, E, R>\n>(2, (self, f) => {\n  return new SinkImpl(pipe(toChannel(self), channel.map(f)))\n})\n\n/** @internal */\nexport const mapEffect = dual<\n  <A, A2, E2, R2>(\n    f: (a: A) => Effect.Effect<A2, E2, R2>\n  ) => <In, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A2, In, L, E2 | E, R2 | R>,\n  <A, In, L, E, R, A2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    f: (a: A) => Effect.Effect<A2, E2, R2>\n  ) => Sink.Sink<A2, In, L, E2 | E, R2 | R>\n>(\n  2,\n  (self, f) => new SinkImpl(pipe(toChannel(self), channel.mapEffect(f)))\n)\n\n/** @internal */\nexport const mapError = dual<\n  <E, E2>(f: (error: E) => E2) => <A, In, L, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In, L, E2, R>,\n  <A, In, L, E, R, E2>(self: Sink.Sink<A, In, L, E, R>, f: (error: E) => E2) => Sink.Sink<A, In, L, E2, R>\n>(\n  2,\n  (self, f) => new SinkImpl(pipe(toChannel(self), channel.mapError(f)))\n)\n\n/** @internal */\nexport const mapLeftover = dual<\n  <L, L2>(f: (leftover: L) => L2) => <A, In, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In, L2, E, R>,\n  <A, In, L, E, R, L2>(self: Sink.Sink<A, In, L, E, R>, f: (leftover: L) => L2) => Sink.Sink<A, In, L2, E, R>\n>(\n  2,\n  (self, f) => new SinkImpl(pipe(toChannel(self), channel.mapOut(Chunk.map(f))))\n)\n\n/** @internal */\nexport const never: Sink.Sink<never, unknown> = fromEffect(Effect.never)\n\n/** @internal */\nexport const orElse = dual<\n  <A2, In2, L2, E2, R2>(\n    that: LazyArg<Sink.Sink<A2, In2, L2, E2, R2>>\n  ) => <A, In, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A2 | A, In & In2, L2 | L, E2 | E, R2 | R>,\n  <A, In, L, E, R, A2, In2, L2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: LazyArg<Sink.Sink<A2, In2, L2, E2, R2>>\n  ) => Sink.Sink<A2 | A, In & In2, L2 | L, E2 | E, R2 | R>\n>(\n  2,\n  <A, In, L, E, R, A2, In2, L2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: LazyArg<Sink.Sink<A2, In2, L2, E2, R2>>\n  ): Sink.Sink<A | A2, In & In2, L | L2, E | E2, R | R2> =>\n    new SinkImpl<A | A2, In & In2, L | L2, E | E2, R | R2>(\n      pipe(toChannel(self), channel.orElse(() => toChannel(that())))\n    )\n)\n\n/** @internal */\nexport const provideContext = dual<\n  <R>(context: Context.Context<R>) => <A, In, L, E>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In, L, E>,\n  <A, In, L, E, R>(self: Sink.Sink<A, In, L, E, R>, context: Context.Context<R>) => Sink.Sink<A, In, L, E>\n>(\n  2,\n  (self, context) => new SinkImpl(pipe(toChannel(self), core.provideContext(context)))\n)\n\n/** @internal */\nexport const race = dual<\n  <R1, E1, In1, L1, A1>(\n    that: Sink.Sink<A1, In1, L1, E1, R1>\n  ) => <A, In, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A1 | A, In & In1, L1 | L, E1 | E, R1 | R>,\n  <A, In, L, E, R, A1, In1, L1, E1, R1>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: Sink.Sink<A1, In1, L1, E1, R1>\n  ) => Sink.Sink<A1 | A, In & In1, L1 | L, E1 | E, R1 | R>\n>(\n  2,\n  (self, that) => pipe(self, raceBoth(that), map(Either.merge))\n)\n\n/** @internal */\nexport const raceBoth = dual<\n  <A1, In1, L1, E1, R1>(\n    that: Sink.Sink<A1, In1, L1, E1, R1>,\n    options?: {\n      readonly capacity?: number | undefined\n    }\n  ) => <A, In, L, E, R>(\n    self: Sink.Sink<A, In, L, E, R>\n  ) => Sink.Sink<Either.Either<A1, A>, In & In1, L1 | L, E1 | E, R1 | R>,\n  <A, In, L, E, R, A1, In1, L1, E1, R1>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: Sink.Sink<A1, In1, L1, E1, R1>,\n    options?: {\n      readonly capacity?: number | undefined\n    }\n  ) => Sink.Sink<Either.Either<A1, A>, In & In1, L1 | L, E1 | E, R1 | R>\n>(\n  (args) => isSink(args[1]),\n  (self, that, options) =>\n    raceWith(self, {\n      other: that,\n      onSelfDone: (selfDone) => mergeDecision.Done(Effect.map(selfDone, Either.left)),\n      onOtherDone: (thatDone) => mergeDecision.Done(Effect.map(thatDone, Either.right)),\n      capacity: options?.capacity ?? 16\n    })\n)\n\n/** @internal */\nexport const raceWith = dual<\n  <A2, In2, L2, E2, R2, A, E, A3, A4>(\n    options: {\n      readonly other: Sink.Sink<A2, In2, L2, E2, R2>\n      readonly onSelfDone: (exit: Exit.Exit<A, E>) => MergeDecision.MergeDecision<R2, E2, A2, E2 | E, A3>\n      readonly onOtherDone: (exit: Exit.Exit<A2, E2>) => MergeDecision.MergeDecision<R2, E, A, E2 | E, A4>\n      readonly capacity?: number | undefined\n    }\n  ) => <In, L, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A3 | A4, In & In2, L2 | L, E2 | E, R2 | R>,\n  <A, In, L, E, R, A2, In2, L2, E2, R2, A3, A4>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly other: Sink.Sink<A2, In2, L2, E2, R2>\n      readonly onSelfDone: (exit: Exit.Exit<A, E>) => MergeDecision.MergeDecision<R2, E2, A2, E2 | E, A3>\n      readonly onOtherDone: (exit: Exit.Exit<A2, E2>) => MergeDecision.MergeDecision<R2, E, A, E2 | E, A4>\n      readonly capacity?: number | undefined\n    }\n  ) => Sink.Sink<A3 | A4, In & In2, L2 | L, E2 | E, R2 | R>\n>(\n  2,\n  <A, In, L, E, R, A2, In2, L2, E2, R2, A3, A4>(\n    self: Sink.Sink<A, In, L, E, R>,\n    options: {\n      readonly other: Sink.Sink<A2, In2, L2, E2, R2>\n      readonly onSelfDone: (exit: Exit.Exit<A, E>) => MergeDecision.MergeDecision<R2, E2, A2, E2 | E, A3>\n      readonly onOtherDone: (exit: Exit.Exit<A2, E2>) => MergeDecision.MergeDecision<R2, E, A, E2 | E, A4>\n      readonly capacity?: number | undefined\n    }\n  ): Sink.Sink<A3 | A4, In & In2, L2 | L, E2 | E, R2 | R> => {\n    function race(scope: Scope.Scope) {\n      return Effect.gen(function*() {\n        const pubsub = yield* PubSub.bounded<\n          Either.Either<Chunk.Chunk<In & In2>, Exit.Exit<unknown>>\n        >(options?.capacity ?? 16)\n        const subscription1 = yield* Scope.extend(PubSub.subscribe(pubsub), scope)\n        const subscription2 = yield* Scope.extend(PubSub.subscribe(pubsub), scope)\n        const reader = channel.toPubSub(pubsub)\n        const writer = channel.fromQueue(subscription1).pipe(\n          core.pipeTo(toChannel(self)),\n          channel.zipLeft(core.fromEffect(Queue.shutdown(subscription1))),\n          channel.mergeWith({\n            other: channel.fromQueue(subscription2).pipe(\n              core.pipeTo(toChannel(options.other)),\n              channel.zipLeft(core.fromEffect(Queue.shutdown(subscription2)))\n            ),\n            onSelfDone: options.onSelfDone,\n            onOtherDone: options.onOtherDone\n          })\n        )\n        const racedChannel = channel.mergeWith(reader, {\n          other: writer,\n          onSelfDone: () => mergeDecision.Await(identity),\n          onOtherDone: (exit) => mergeDecision.Done(exit)\n        }) as Channel.Channel<\n          Chunk.Chunk<L | L2>,\n          Chunk.Chunk<In & In2>,\n          E | E2,\n          never,\n          A3 | A4,\n          unknown,\n          R | R2\n        >\n        return new SinkImpl(racedChannel)\n      })\n    }\n    return unwrapScopedWith(race)\n  }\n)\n\n/** @internal */\nexport const refineOrDie = dual<\n  <E, E2>(\n    pf: (error: E) => Option.Option<E2>\n  ) => <A, In, L, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In, L, E2, R>,\n  <A, In, L, E, R, E2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    pf: (error: E) => Option.Option<E2>\n  ) => Sink.Sink<A, In, L, E2, R>\n>(\n  2,\n  (self, pf) => pipe(self, refineOrDieWith(pf, identity))\n)\n\n/** @internal */\nexport const refineOrDieWith = dual<\n  <E, E2>(\n    pf: (error: E) => Option.Option<E2>,\n    f: (error: E) => unknown\n  ) => <A, In, L, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In, L, E2, R>,\n  <A, In, L, E, R, E2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    pf: (error: E) => Option.Option<E2>,\n    f: (error: E) => unknown\n  ) => Sink.Sink<A, In, L, E2, R>\n>(\n  3,\n  (self, pf, f) => {\n    const newChannel = pipe(\n      self,\n      toChannel,\n      channel.catchAll((error) =>\n        Option.match(pf(error), {\n          onNone: () => core.failCauseSync(() => Cause.die(f(error))),\n          onSome: core.fail\n        })\n      )\n    )\n    return new SinkImpl(newChannel)\n  }\n)\n\n/** @internal */\nexport const service = <I, S>(\n  tag: Context.Tag<I, S>\n): Sink.Sink<S, unknown, never, never, I> => serviceWith(tag, identity)\n\n/** @internal */\nexport const serviceWith = <I, S, Z>(\n  tag: Context.Tag<I, S>,\n  f: (service: Types.NoInfer<S>) => Z\n): Sink.Sink<Z, unknown, never, never, I> => fromEffect(Effect.map(tag, f))\n\n/** @internal */\nexport const serviceWithEffect = <I, S, R, E, Z>(\n  tag: Context.Tag<I, S>,\n  f: (service: Types.NoInfer<S>) => Effect.Effect<Z, E, R>\n): Sink.Sink<Z, unknown, never, E, R | I> => fromEffect(Effect.flatMap(tag, f))\n\n/** @internal */\nexport const serviceWithSink = <I, S, R, E, In, L, Z>(\n  tag: Context.Tag<I, S>,\n  f: (service: Types.NoInfer<S>) => Sink.Sink<Z, In, L, E, R>\n): Sink.Sink<Z, In, L, E, R | I> =>\n  new SinkImpl(pipe(Effect.map(tag, (service) => toChannel(f(service))), channel.unwrap))\n\n/** @internal */\nexport const some = <In>(predicate: Predicate<In>): Sink.Sink<boolean, In, In> =>\n  fold(false, (bool) => !bool, (acc, input) => acc || predicate(input))\n\n/** @internal */\nexport const splitWhere = dual<\n  <In>(f: Predicate<In>) => <A, L extends In, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In, In, E, R>,\n  <A, In, L extends In, E, R>(self: Sink.Sink<A, In, L, E, R>, f: Predicate<In>) => Sink.Sink<A, In, In, E, R>\n>(2, <A, In, L extends In, E, R>(self: Sink.Sink<A, In, L, E, R>, f: Predicate<In>): Sink.Sink<A, In, In, E, R> => {\n  const newChannel = pipe(\n    core.fromEffect(Ref.make(Chunk.empty<In>())),\n    core.flatMap((ref) =>\n      pipe(\n        splitWhereSplitter<In, E>(false, ref, f),\n        channel.pipeToOrFail(toChannel(self)),\n        core.collectElements,\n        core.flatMap(([leftovers, z]) =>\n          pipe(\n            core.fromEffect(Ref.get(ref)),\n            core.flatMap((leftover) =>\n              pipe(\n                core.write<Chunk.Chunk<In>>(pipe(leftover, Chunk.appendAll(Chunk.flatten(leftovers)))),\n                channel.zipRight(core.succeed(z))\n              )\n            )\n          )\n        )\n      )\n    )\n  )\n  return new SinkImpl(newChannel)\n})\n\n/** @internal */\nconst splitWhereSplitter = <A, E>(\n  written: boolean,\n  leftovers: Ref.Ref<Chunk.Chunk<A>>,\n  f: Predicate<A>\n): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E, never, unknown, unknown> =>\n  core.readWithCause({\n    onInput: (input) => {\n      if (Chunk.isEmpty(input)) {\n        return splitWhereSplitter(written, leftovers, f)\n      }\n      if (written) {\n        const index = indexWhere(input, f)\n        if (index === -1) {\n          return channel.zipRight(\n            core.write(input),\n            splitWhereSplitter<A, E>(true, leftovers, f)\n          )\n        }\n        const [left, right] = Chunk.splitAt(input, index)\n        return channel.zipRight(\n          core.write(left),\n          core.fromEffect(Ref.set(leftovers, right))\n        )\n      }\n      const index = indexWhere(input, f, 1)\n      if (index === -1) {\n        return channel.zipRight(\n          core.write(input),\n          splitWhereSplitter<A, E>(true, leftovers, f)\n        )\n      }\n      const [left, right] = pipe(input, Chunk.splitAt(Math.max(index, 1)))\n      return channel.zipRight(core.write(left), core.fromEffect(Ref.set(leftovers, right)))\n    },\n    onFailure: core.failCause,\n    onDone: core.succeed\n  })\n\n/** @internal */\nconst indexWhere = <A>(self: Chunk.Chunk<A>, predicate: Predicate<A>, from = 0): number => {\n  const iterator = self[Symbol.iterator]()\n  let index = 0\n  let result = -1\n  let next: IteratorResult<A, any>\n  while (result < 0 && (next = iterator.next()) && !next.done) {\n    const a = next.value\n    if (index >= from && predicate(a)) {\n      result = index\n    }\n    index = index + 1\n  }\n  return result\n}\n\n/** @internal */\nexport const succeed = <A>(a: A): Sink.Sink<A, unknown> => new SinkImpl(core.succeed(a))\n\n/** @internal */\nexport const sum: Sink.Sink<number, number> = foldLeftChunks(\n  0,\n  (acc, chunk) => acc + Chunk.reduce(chunk, 0, (s, a) => s + a)\n)\n\n/** @internal */\nexport const summarized = dual<\n  <A2, E2, R2, A3>(\n    summary: Effect.Effect<A2, E2, R2>,\n    f: (start: A2, end: A2) => A3\n  ) => <A, In, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<[A, A3], In, L, E2 | E, R2 | R>,\n  <A, In, L, E, R, A2, E2, R2, A3>(\n    self: Sink.Sink<A, In, L, E, R>,\n    summary: Effect.Effect<A2, E2, R2>,\n    f: (start: A2, end: A2) => A3\n  ) => Sink.Sink<[A, A3], In, L, E2 | E, R2 | R>\n>(\n  3,\n  (self, summary, f) => {\n    const newChannel = pipe(\n      core.fromEffect(summary),\n      core.flatMap((start) =>\n        pipe(\n          self,\n          toChannel,\n          core.flatMap((done) =>\n            pipe(\n              core.fromEffect(summary),\n              channel.map((end) => [done, f(start, end)])\n            )\n          )\n        )\n      )\n    )\n    return new SinkImpl(newChannel)\n  }\n)\n\n/** @internal */\nexport const sync = <A>(evaluate: LazyArg<A>): Sink.Sink<A, unknown> => new SinkImpl(core.sync(evaluate))\n\n/** @internal */\nexport const take = <In>(n: number): Sink.Sink<Chunk.Chunk<In>, In, In> =>\n  pipe(\n    foldChunks<Chunk.Chunk<In>, In>(\n      Chunk.empty(),\n      (chunk) => chunk.length < n,\n      (acc, chunk) => pipe(acc, Chunk.appendAll(chunk))\n    ),\n    flatMap((acc) => {\n      const [taken, leftover] = pipe(acc, Chunk.splitAt(n))\n      return new SinkImpl(pipe(core.write(leftover), channel.zipRight(core.succeedNow(taken))))\n    })\n  )\n\n/** @internal */\nexport const toChannel = <A, In, L, E, R>(\n  self: Sink.Sink<A, In, L, E, R>\n): Channel.Channel<Chunk.Chunk<L>, Chunk.Chunk<In>, E, never, A, unknown, R> =>\n  Effect.isEffect(self) ?\n    toChannel(fromEffect(self as Effect.Effect<A, E, R>)) :\n    (self as SinkImpl<A, In, L, E, R>).channel\n\n/** @internal */\nexport const unwrap = <A, In, L, E2, R2, E, R>(\n  effect: Effect.Effect<Sink.Sink<A, In, L, E2, R2>, E, R>\n): Sink.Sink<A, In, L, E | E2, R | R2> =>\n  new SinkImpl(\n    channel.unwrap(pipe(effect, Effect.map((sink) => toChannel(sink))))\n  )\n\n/** @internal */\nexport const unwrapScoped = <A, In, L, E, R>(\n  effect: Effect.Effect<Sink.Sink<A, In, L, E, R>, E, R>\n): Sink.Sink<A, In, L, E, Exclude<R, Scope.Scope>> =>\n  new SinkImpl(\n    channel.unwrapScoped(effect.pipe(\n      Effect.map((sink) => toChannel(sink))\n    ))\n  )\n\n/** @internal */\nexport const unwrapScopedWith = <A, In, L, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<Sink.Sink<A, In, L, E, R>, E, R>\n): Sink.Sink<A, In, L, E, R> =>\n  new SinkImpl(\n    channel.unwrapScopedWith((scope) =>\n      f(scope).pipe(\n        Effect.map((sink) => toChannel(sink))\n      )\n    )\n  )\n\n/** @internal */\nexport const withDuration = <A, In, L, E, R>(\n  self: Sink.Sink<A, In, L, E, R>\n): Sink.Sink<[A, Duration.Duration], In, L, E, R> =>\n  pipe(self, summarized(Clock.currentTimeMillis, (start, end) => Duration.millis(end - start)))\n\n/** @internal */\nexport const zip = dual<\n  <A2, In, In2 extends In, L2, E2, R2>(\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<[A, A2], In & In2, L | L2, E2 | E, R2 | R>,\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => Sink.Sink<[A, A2], In & In2, L | L2, E2 | E, R2 | R>\n>(\n  (args) => isSink(args[1]),\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ): Sink.Sink<[A, A2], In & In2, L | L2, E2 | E, R2 | R> => zipWith(self, that, (z, z2) => [z, z2], options)\n)\n\n/** @internal */\nexport const zipLeft = dual<\n  <A2, In, In2 extends In, L2, E2, R2>(\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A, In & In2, L | L2, E2 | E, R2 | R>,\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => Sink.Sink<A, In & In2, L | L2, E2 | E, R2 | R>\n>(\n  (args) => isSink(args[1]),\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ): Sink.Sink<A, In & In2, L | L2, E2 | E, R2 | R> => zipWith(self, that, (z, _) => z, options)\n)\n\n/** @internal */\nexport const zipRight = dual<\n  <A2, In, In2 extends In, L2, E2, R2>(\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => <A, L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A2, In & In2, L | L2, E2 | E, R2 | R>,\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => Sink.Sink<A2, In & In2, L | L2, E2 | E, R2 | R>\n>(\n  (args) => isSink(args[1]),\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ): Sink.Sink<A2, In & In2, L | L2, E2 | E, R2 | R> => zipWith(self, that, (_, z2) => z2, options)\n)\n\n/** @internal */\nexport const zipWith = dual<\n  <A2, In, In2 extends In, L2, E2, R2, A, A3>(\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    f: (a: A, a2: A2) => A3,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => <L, E, R>(self: Sink.Sink<A, In, L, E, R>) => Sink.Sink<A3, In & In2, L | L2, E2 | E, R2 | R>,\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2, A3>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    f: (a: A, a2: A2) => A3,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ) => Sink.Sink<A3, In & In2, L | L2, E2 | E, R2 | R>\n>(\n  (args) => isSink(args[1]),\n  <A, In, L, E, R, A2, In2 extends In, L2, E2, R2, A3>(\n    self: Sink.Sink<A, In, L, E, R>,\n    that: Sink.Sink<A2, In2, L2, E2, R2>,\n    f: (a: A, a2: A2) => A3,\n    options?: {\n      readonly concurrent?: boolean | undefined\n    }\n  ): Sink.Sink<A3, In & In2, L | L2, E2 | E, R2 | R> =>\n    options?.concurrent ?\n      raceWith(self, {\n        other: that,\n        onSelfDone: Exit.match({\n          onFailure: (cause) => mergeDecision.Done(Effect.failCause(cause)),\n          onSuccess: (leftZ) =>\n            mergeDecision.Await<R | R2, E2, A2, E | E2, A3>(\n              Exit.match({\n                onFailure: Effect.failCause,\n                onSuccess: (rightZ) => Effect.succeed(f(leftZ, rightZ))\n              })\n            )\n        }),\n        onOtherDone: Exit.match({\n          onFailure: (cause) => mergeDecision.Done(Effect.failCause(cause)),\n          onSuccess: (rightZ) =>\n            mergeDecision.Await<R | R2, E, A, E | E2, A3>(\n              Exit.match({\n                onFailure: Effect.failCause,\n                onSuccess: (leftZ) => Effect.succeed(f(leftZ, rightZ))\n              })\n            )\n        })\n      }) :\n      flatMap(self, (z) => map(that, (z2) => f(z, z2)))\n)\n\n// Circular with Channel\n\n/** @internal */\nexport const channelToSink = <OutElem, InElem, OutErr, InErr, OutDone, Env>(\n  self: Channel.Channel<Chunk.Chunk<OutElem>, Chunk.Chunk<InElem>, OutErr, InErr, OutDone, unknown, Env>\n): Sink.Sink<OutDone, InElem, OutElem, OutErr, Env> => new SinkImpl(self)\n\n// Constants\n\n/** @internal */\nexport const count: Sink.Sink<number, unknown> = foldLeftChunks(\n  0,\n  (acc, chunk) => acc + chunk.length\n)\n\n/** @internal */\nexport const mkString: Sink.Sink<string, unknown> = suspend(() => {\n  const strings: Array<string> = []\n  return pipe(\n    foldLeftChunks<void, unknown>(void 0, (_, elems) =>\n      Chunk.map(elems, (elem) => {\n        strings.push(String(elem))\n      })),\n    map(() => strings.join(\"\"))\n  )\n})\n\n/** @internal */\nexport const timed: Sink.Sink<Duration.Duration, unknown> = pipe(\n  withDuration(drain),\n  map((tuple) => tuple[1])\n)\n"
  },
  {
    "path": "packages/effect/src/internal/stack.ts",
    "content": "/** @internal */\nexport interface Stack<out A> {\n  readonly value: A\n  readonly previous: Stack<A> | undefined\n}\n\nexport const make = <A>(value: A, previous?: Stack<A>): Stack<A> => ({\n  value,\n  previous\n})\n"
  },
  {
    "path": "packages/effect/src/internal/stm/core.ts",
    "content": "import * as Cause from \"../../Cause.js\"\nimport * as Context from \"../../Context.js\"\nimport * as Effect from \"../../Effect.js\"\nimport * as Either from \"../../Either.js\"\nimport * as Equal from \"../../Equal.js\"\nimport * as Exit from \"../../Exit.js\"\nimport type * as FiberId from \"../../FiberId.js\"\nimport * as FiberRef from \"../../FiberRef.js\"\nimport type { LazyArg } from \"../../Function.js\"\nimport { constVoid, dual, pipe } from \"../../Function.js\"\nimport * as Hash from \"../../Hash.js\"\nimport type * as Option from \"../../Option.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport type * as Scheduler from \"../../Scheduler.js\"\nimport type * as STM from \"../../STM.js\"\nimport { internalCall, YieldWrap } from \"../../Utils.js\"\nimport { ChannelTypeId } from \"../core-stream.js\"\nimport { withFiberRuntime } from \"../core.js\"\nimport { effectVariance, StreamTypeId } from \"../effectable.js\"\nimport { OP_COMMIT } from \"../opCodes/effect.js\"\nimport { SingleShotGen } from \"../singleShotGen.js\"\nimport { SinkTypeId } from \"../sink.js\"\nimport * as Journal from \"./journal.js\"\nimport * as OpCodes from \"./opCodes/stm.js\"\nimport * as TExitOpCodes from \"./opCodes/tExit.js\"\nimport * as TryCommitOpCodes from \"./opCodes/tryCommit.js\"\nimport * as STMState from \"./stmState.js\"\nimport * as TExit from \"./tExit.js\"\nimport * as TryCommit from \"./tryCommit.js\"\nimport * as TxnId from \"./txnId.js\"\n\n/** @internal */\nconst STMSymbolKey = \"effect/STM\"\n\n/** @internal */\nexport const STMTypeId: STM.STMTypeId = Symbol.for(\n  STMSymbolKey\n) as STM.STMTypeId\n\n/** @internal */\nexport type Primitive =\n  | STMEffect\n  | STMOnFailure\n  | STMOnRetry\n  | STMOnSuccess\n  | STMProvide\n  | STMSync\n  | STMSucceed\n  | STMRetry\n  | STMFail\n  | STMDie\n  | STMInterrupt\n\n/** @internal */\ntype Op<Tag extends string, Body = {}> = STM.STM<never> & Body & {\n  readonly _op: OP_COMMIT\n  readonly effect_instruction_i0: Tag\n}\n\n/** @internal */\ninterface STMEffect extends\n  Op<OpCodes.OP_WITH_STM_RUNTIME, {\n    readonly effect_instruction_i1: (\n      runtime: STMDriver<unknown, unknown, unknown>\n    ) => STM.STM<unknown, unknown, unknown>\n  }>\n{}\n\n/** @internal */\ninterface STMOnFailure extends\n  Op<OpCodes.OP_ON_FAILURE, {\n    readonly effect_instruction_i1: STM.STM<unknown, unknown, unknown>\n    readonly effect_instruction_i2: (error: unknown) => STM.STM<unknown, unknown, unknown>\n  }>\n{}\n\n/** @internal */\ninterface STMOnRetry extends\n  Op<OpCodes.OP_ON_RETRY, {\n    readonly effect_instruction_i1: STM.STM<unknown, unknown, unknown>\n    readonly effect_instruction_i2: () => STM.STM<unknown, unknown, unknown>\n  }>\n{}\n\n/** @internal */\ninterface STMOnSuccess extends\n  Op<OpCodes.OP_ON_SUCCESS, {\n    readonly effect_instruction_i1: STM.STM<unknown, unknown, unknown>\n    readonly effect_instruction_i2: (a: unknown) => STM.STM<unknown, unknown, unknown>\n  }>\n{}\n\n/** @internal */\ninterface STMProvide extends\n  Op<OpCodes.OP_PROVIDE, {\n    readonly effect_instruction_i1: STM.STM<unknown, unknown, unknown>\n    readonly effect_instruction_i2: (context: Context.Context<unknown>) => Context.Context<unknown>\n  }>\n{}\n\n/** @internal */\ninterface STMSync extends\n  Op<OpCodes.OP_SYNC, {\n    readonly effect_instruction_i1: () => unknown\n  }>\n{}\n\n/** @internal */\ninterface STMSucceed extends\n  Op<OpCodes.OP_SUCCEED, {\n    readonly effect_instruction_i1: unknown\n  }>\n{}\n\n/** @internal */\ninterface STMRetry extends Op<OpCodes.OP_RETRY, {}> {}\n\n/** @internal */\ninterface STMFail extends\n  Op<OpCodes.OP_FAIL, {\n    readonly effect_instruction_i1: LazyArg<unknown>\n  }>\n{}\n\n/** @internal */\ninterface STMDie extends\n  Op<OpCodes.OP_DIE, {\n    readonly effect_instruction_i1: LazyArg<unknown>\n  }>\n{}\n\n/** @internal */\ninterface STMInterrupt extends\n  Op<OpCodes.OP_INTERRUPT, {\n    readonly effect_instruction_i1: FiberId.Runtime\n  }>\n{}\n\nconst stmVariance = {\n  /* c8 ignore next */\n  _R: (_: never) => _,\n  /* c8 ignore next */\n  _E: (_: never) => _,\n  /* c8 ignore next */\n  _A: (_: never) => _\n}\n\n/** @internal */\nclass STMPrimitive implements STM.STM<any, any, any> {\n  public _op = OP_COMMIT\n  public effect_instruction_i1: any = undefined\n  public effect_instruction_i2: any = undefined;\n  [Effect.EffectTypeId]: any;\n  [StreamTypeId]: any;\n  [SinkTypeId]: any;\n  [ChannelTypeId]: any\n  get [STMTypeId]() {\n    return stmVariance\n  }\n  constructor(readonly effect_instruction_i0: Primitive[\"effect_instruction_i0\"]) {\n    this[Effect.EffectTypeId] = effectVariance\n    this[StreamTypeId] = stmVariance\n    this[SinkTypeId] = stmVariance\n    this[ChannelTypeId] = stmVariance\n  }\n  [Equal.symbol](this: {}, that: unknown) {\n    return this === that\n  }\n  [Hash.symbol](this: {}) {\n    return Hash.cached(this, Hash.random(this))\n  }\n  [Symbol.iterator]() {\n    return new SingleShotGen(new YieldWrap(this)) as any\n  }\n  commit(this: STM.STM<any, any, any>): Effect.Effect<any, any, any> {\n    return unsafeAtomically(this, constVoid, constVoid)\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const isSTM = (u: unknown): u is STM.STM<unknown, unknown, unknown> => hasProperty(u, STMTypeId)\n\n/** @internal */\nexport const commit = <A, E, R>(self: STM.STM<A, E, R>): Effect.Effect<A, E, R> =>\n  unsafeAtomically(self, constVoid, constVoid)\n\n/** @internal */\nexport const unsafeAtomically = <A, E, R>(\n  self: STM.STM<A, E, R>,\n  onDone: (exit: Exit.Exit<A, E>) => unknown,\n  onInterrupt: LazyArg<unknown>\n): Effect.Effect<A, E, R> =>\n  withFiberRuntime((state) => {\n    const fiberId = state.id()\n    const env = state.getFiberRef(FiberRef.currentContext) as Context.Context<R>\n    const scheduler = state.getFiberRef(FiberRef.currentScheduler)\n    const priority = state.getFiberRef(FiberRef.currentSchedulingPriority)\n    const commitResult = tryCommitSync(fiberId, self, env, scheduler, priority)\n    switch (commitResult._tag) {\n      case TryCommitOpCodes.OP_DONE: {\n        onDone(commitResult.exit)\n        return commitResult.exit\n      }\n      case TryCommitOpCodes.OP_SUSPEND: {\n        const txnId = TxnId.make()\n        const state: { value: STMState.STMState<A, E> } = { value: STMState.running }\n        const effect = Effect.async(\n          (k: (effect: Effect.Effect<A, E, R>) => unknown): void =>\n            tryCommitAsync(fiberId, self, txnId, state, env, scheduler, priority, k)\n        )\n        return Effect.uninterruptibleMask((restore) =>\n          pipe(\n            restore(effect),\n            Effect.catchAllCause((cause) => {\n              let currentState = state.value\n              if (STMState.isRunning(currentState)) {\n                state.value = STMState.interrupted\n              }\n              currentState = state.value\n              if (STMState.isDone(currentState)) {\n                onDone(currentState.exit)\n                return currentState.exit\n              }\n              onInterrupt()\n              return Effect.failCause(cause)\n            })\n          )\n        )\n      }\n    }\n  })\n\n/** @internal */\nconst tryCommit = <A, E, R>(\n  fiberId: FiberId.FiberId,\n  stm: STM.STM<A, E, R>,\n  state: { value: STMState.STMState<A, E> },\n  env: Context.Context<R>,\n  scheduler: Scheduler.Scheduler,\n  priority: number\n): TryCommit.TryCommit<A, E> => {\n  const journal: Journal.Journal = new Map()\n  const tExit = new STMDriver(stm, journal, fiberId, env).run()\n  const analysis = Journal.analyzeJournal(journal)\n\n  if (analysis === Journal.JournalAnalysisReadWrite) {\n    Journal.commitJournal(journal)\n  } else if (analysis === Journal.JournalAnalysisInvalid) {\n    throw new Error(\n      \"BUG: STM.TryCommit.tryCommit - please report an issue at https://github.com/Effect-TS/effect/issues\"\n    )\n  }\n\n  switch (tExit._tag) {\n    case TExitOpCodes.OP_SUCCEED: {\n      state.value = STMState.fromTExit(tExit)\n      return completeTodos(Exit.succeed(tExit.value), journal, scheduler, priority)\n    }\n    case TExitOpCodes.OP_FAIL: {\n      state.value = STMState.fromTExit(tExit)\n      const cause = Cause.fail(tExit.error)\n      return completeTodos(\n        Exit.failCause(cause),\n        journal,\n        scheduler,\n        priority\n      )\n    }\n    case TExitOpCodes.OP_DIE: {\n      state.value = STMState.fromTExit(tExit)\n      const cause = Cause.die(tExit.defect)\n      return completeTodos(\n        Exit.failCause(cause),\n        journal,\n        scheduler,\n        priority\n      )\n    }\n    case TExitOpCodes.OP_INTERRUPT: {\n      state.value = STMState.fromTExit(tExit)\n      const cause = Cause.interrupt(fiberId)\n      return completeTodos(\n        Exit.failCause(cause),\n        journal,\n        scheduler,\n        priority\n      )\n    }\n    case TExitOpCodes.OP_RETRY: {\n      return TryCommit.suspend(journal)\n    }\n  }\n}\n\n/** @internal */\nconst tryCommitSync = <A, E, R>(\n  fiberId: FiberId.FiberId,\n  stm: STM.STM<A, E, R>,\n  env: Context.Context<R>,\n  scheduler: Scheduler.Scheduler,\n  priority: number\n): TryCommit.TryCommit<A, E> => {\n  const journal: Journal.Journal = new Map()\n  const tExit = new STMDriver(stm, journal, fiberId, env).run()\n  const analysis = Journal.analyzeJournal(journal)\n\n  if (analysis === Journal.JournalAnalysisReadWrite && TExit.isSuccess(tExit)) {\n    Journal.commitJournal(journal)\n  } else if (analysis === Journal.JournalAnalysisInvalid) {\n    throw new Error(\n      \"BUG: STM.TryCommit.tryCommitSync - please report an issue at https://github.com/Effect-TS/effect/issues\"\n    )\n  }\n\n  switch (tExit._tag) {\n    case TExitOpCodes.OP_SUCCEED: {\n      return completeTodos(Exit.succeed(tExit.value), journal, scheduler, priority)\n    }\n    case TExitOpCodes.OP_FAIL: {\n      const cause = Cause.fail(tExit.error)\n      return completeTodos(\n        Exit.failCause(cause),\n        journal,\n        scheduler,\n        priority\n      )\n    }\n    case TExitOpCodes.OP_DIE: {\n      const cause = Cause.die(tExit.defect)\n      return completeTodos(\n        Exit.failCause(cause),\n        journal,\n        scheduler,\n        priority\n      )\n    }\n    case TExitOpCodes.OP_INTERRUPT: {\n      const cause = Cause.interrupt(fiberId)\n      return completeTodos(\n        Exit.failCause(cause),\n        journal,\n        scheduler,\n        priority\n      )\n    }\n    case TExitOpCodes.OP_RETRY: {\n      return TryCommit.suspend(journal)\n    }\n  }\n}\n\n/** @internal */\nconst tryCommitAsync = <A, E, R>(\n  fiberId: FiberId.FiberId,\n  self: STM.STM<A, E, R>,\n  txnId: TxnId.TxnId,\n  state: { value: STMState.STMState<A, E> },\n  context: Context.Context<R>,\n  scheduler: Scheduler.Scheduler,\n  priority: number,\n  k: (effect: Effect.Effect<A, E, R>) => unknown\n) => {\n  if (STMState.isRunning(state.value)) {\n    const result = tryCommit(fiberId, self, state, context, scheduler, priority)\n    switch (result._tag) {\n      case TryCommitOpCodes.OP_DONE: {\n        completeTryCommit(result.exit, k)\n        break\n      }\n      case TryCommitOpCodes.OP_SUSPEND: {\n        Journal.addTodo(\n          txnId,\n          result.journal,\n          () => tryCommitAsync(fiberId, self, txnId, state, context, scheduler, priority, k)\n        )\n        break\n      }\n    }\n  }\n}\n\n/** @internal */\nconst completeTodos = <A, E>(\n  exit: Exit.Exit<A, E>,\n  journal: Journal.Journal,\n  scheduler: Scheduler.Scheduler,\n  priority: number\n): TryCommit.TryCommit<A, E> => {\n  const todos = Journal.collectTodos(journal)\n  if (todos.size > 0) {\n    scheduler.scheduleTask(() => Journal.execTodos(todos), priority)\n  }\n  return TryCommit.done(exit)\n}\n\n/** @internal */\nconst completeTryCommit = <A, E, R>(\n  exit: Exit.Exit<A, E>,\n  k: (effect: Effect.Effect<A, E, R>) => unknown\n): void => {\n  k(exit)\n}\n\n/** @internal */\ntype Continuation = STMOnFailure | STMOnSuccess | STMOnRetry\n\n/** @internal */\nexport const context = <R>(): STM.STM<Context.Context<R>, never, R> =>\n  effect<R, Context.Context<R>>((_, __, env) => env)\n\n/** @internal */\nexport const contextWith = <R0, R>(f: (environment: Context.Context<R0>) => R): STM.STM<R, never, R0> =>\n  map(context<R0>(), f)\n\n/** @internal */\nexport const contextWithSTM = <R0, A, E, R>(\n  f: (environment: Context.Context<R0>) => STM.STM<A, E, R>\n): STM.STM<A, E, R0 | R> => flatMap(context<R0>(), f)\n\n/** @internal */\nexport class STMDriver<in out R, out E, out A> {\n  private contStack: Array<Continuation> = []\n  private env: Context.Context<unknown>\n\n  constructor(\n    readonly self: STM.STM<A, E, R>,\n    readonly journal: Journal.Journal,\n    readonly fiberId: FiberId.FiberId,\n    r0: Context.Context<R>\n  ) {\n    this.env = r0 as Context.Context<unknown>\n  }\n\n  getEnv(): Context.Context<R> {\n    return this.env\n  }\n\n  pushStack(cont: Continuation) {\n    this.contStack.push(cont)\n  }\n\n  popStack() {\n    return this.contStack.pop()\n  }\n\n  nextSuccess() {\n    let current = this.popStack()\n    while (current !== undefined && current.effect_instruction_i0 !== OpCodes.OP_ON_SUCCESS) {\n      current = this.popStack()\n    }\n    return current\n  }\n\n  nextFailure() {\n    let current = this.popStack()\n    while (current !== undefined && current.effect_instruction_i0 !== OpCodes.OP_ON_FAILURE) {\n      current = this.popStack()\n    }\n    return current\n  }\n\n  nextRetry() {\n    let current = this.popStack()\n    while (current !== undefined && current.effect_instruction_i0 !== OpCodes.OP_ON_RETRY) {\n      current = this.popStack()\n    }\n    return current\n  }\n\n  run(): TExit.TExit<A, E> {\n    let curr = this.self as Primitive | Context.Tag<any, any> | Either.Either<any, any> | Option.Option<any> | undefined\n    let exit: TExit.TExit<unknown, unknown> | undefined = undefined\n    while (exit === undefined && curr !== undefined) {\n      try {\n        const current = curr\n        if (current) {\n          switch (current._op) {\n            case \"Tag\": {\n              curr = effect((_, __, env) => Context.unsafeGet(env, current)) as Primitive\n              break\n            }\n            case \"Left\": {\n              curr = fail(current.left) as Primitive\n              break\n            }\n            case \"None\": {\n              curr = fail(new Cause.NoSuchElementException()) as Primitive\n              break\n            }\n            case \"Right\": {\n              curr = succeed(current.right) as Primitive\n              break\n            }\n            case \"Some\": {\n              curr = succeed(current.value) as Primitive\n              break\n            }\n            case \"Commit\": {\n              switch (current.effect_instruction_i0) {\n                case OpCodes.OP_DIE: {\n                  exit = TExit.die(internalCall(() => current.effect_instruction_i1()))\n                  break\n                }\n                case OpCodes.OP_FAIL: {\n                  const cont = this.nextFailure()\n                  if (cont === undefined) {\n                    exit = TExit.fail(internalCall(() => current.effect_instruction_i1()))\n                  } else {\n                    curr = internalCall(() =>\n                      cont.effect_instruction_i2(\n                        internalCall(() => current.effect_instruction_i1())\n                      ) as Primitive\n                    )\n                  }\n                  break\n                }\n                case OpCodes.OP_RETRY: {\n                  const cont = this.nextRetry()\n                  if (cont === undefined) {\n                    exit = TExit.retry\n                  } else {\n                    curr = internalCall(() => cont.effect_instruction_i2() as Primitive)\n                  }\n                  break\n                }\n                case OpCodes.OP_INTERRUPT: {\n                  exit = TExit.interrupt(this.fiberId)\n                  break\n                }\n                case OpCodes.OP_WITH_STM_RUNTIME: {\n                  curr = internalCall(() =>\n                    current.effect_instruction_i1(this as STMDriver<unknown, unknown, unknown>) as Primitive\n                  )\n                  break\n                }\n                case OpCodes.OP_ON_SUCCESS:\n                case OpCodes.OP_ON_FAILURE:\n                case OpCodes.OP_ON_RETRY: {\n                  this.pushStack(current)\n                  curr = current.effect_instruction_i1 as Primitive\n                  break\n                }\n                case OpCodes.OP_PROVIDE: {\n                  const env = this.env\n                  this.env = internalCall(() => current.effect_instruction_i2(env))\n                  curr = pipe(\n                    current.effect_instruction_i1,\n                    ensuring(sync(() => (this.env = env)))\n                  ) as Primitive\n                  break\n                }\n                case OpCodes.OP_SUCCEED: {\n                  const value = current.effect_instruction_i1\n                  const cont = this.nextSuccess()\n                  if (cont === undefined) {\n                    exit = TExit.succeed(value)\n                  } else {\n                    curr = internalCall(() => cont.effect_instruction_i2(value) as Primitive)\n                  }\n                  break\n                }\n                case OpCodes.OP_SYNC: {\n                  const value = internalCall(() => current.effect_instruction_i1())\n                  const cont = this.nextSuccess()\n                  if (cont === undefined) {\n                    exit = TExit.succeed(value)\n                  } else {\n                    curr = internalCall(() => cont.effect_instruction_i2(value) as Primitive)\n                  }\n                  break\n                }\n              }\n              break\n            }\n          }\n        }\n      } catch (e) {\n        curr = die(e) as Primitive\n      }\n    }\n    return exit as TExit.TExit<A, E>\n  }\n}\n\n/** @internal */\nexport const catchAll = dual<\n  <E, B, E1, R1>(\n    f: (e: E) => STM.STM<B, E1, R1>\n  ) => <A, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<B | A, E1, R1 | R>,\n  <A, E, R, B, E1, R1>(\n    self: STM.STM<A, E, R>,\n    f: (e: E) => STM.STM<B, E1, R1>\n  ) => STM.STM<B | A, E1, R1 | R>\n>(2, (self, f) => {\n  const stm = new STMPrimitive(OpCodes.OP_ON_FAILURE)\n  stm.effect_instruction_i1 = self\n  stm.effect_instruction_i2 = f\n  return stm\n})\n\n/** @internal */\nexport const mapInputContext = dual<\n  <R0, R>(\n    f: (context: Context.Context<R0>) => Context.Context<R>\n  ) => <A, E>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A, E, R0>,\n  <A, E, R0, R>(\n    self: STM.STM<A, E, R>,\n    f: (context: Context.Context<R0>) => Context.Context<R>\n  ) => STM.STM<A, E, R0>\n>(2, (self, f) => {\n  const stm = new STMPrimitive(OpCodes.OP_PROVIDE)\n  stm.effect_instruction_i1 = self\n  stm.effect_instruction_i2 = f\n  return stm\n})\n\n/** @internal */\nexport const die = (defect: unknown): STM.STM<never> => dieSync(() => defect)\n\n/** @internal */\nexport const dieMessage = (message: string): STM.STM<never> => dieSync(() => new Cause.RuntimeException(message))\n\n/** @internal */\nexport const dieSync = (evaluate: LazyArg<unknown>): STM.STM<never> => {\n  const stm = new STMPrimitive(OpCodes.OP_DIE)\n  stm.effect_instruction_i1 = evaluate\n  return stm as any\n}\n\n/** @internal */\nexport const effect = <R, A>(\n  f: (journal: Journal.Journal, fiberId: FiberId.FiberId, environment: Context.Context<R>) => A\n): STM.STM<A, never, R> => withSTMRuntime((_) => succeed(f(_.journal, _.fiberId, _.getEnv())))\n\n/** @internal */\nexport const ensuring = dual<\n  <R1, B>(finalizer: STM.STM<B, never, R1>) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E, R1 | R>,\n  <A, E, R, R1, B>(self: STM.STM<A, E, R>, finalizer: STM.STM<B, never, R1>) => STM.STM<A, E, R1 | R>\n>(2, (self, finalizer) =>\n  matchSTM(self, {\n    onFailure: (e) => zipRight(finalizer, fail(e)),\n    onSuccess: (a) => zipRight(finalizer, succeed(a))\n  }))\n\n/** @internal */\nexport const fail = <E>(error: E): STM.STM<never, E> => failSync(() => error)\n\n/** @internal */\nexport const failSync = <E>(evaluate: LazyArg<E>): STM.STM<never, E> => {\n  const stm = new STMPrimitive(OpCodes.OP_FAIL)\n  stm.effect_instruction_i1 = evaluate\n  return stm as any\n}\n\n/** @internal */\nexport const flatMap = dual<\n  <A, A2, E1, R1>(f: (a: A) => STM.STM<A2, E1, R1>) => <E, R>(self: STM.STM<A, E, R>) => STM.STM<A2, E1 | E, R1 | R>,\n  <A, E, R, A2, E1, R1>(self: STM.STM<A, E, R>, f: (a: A) => STM.STM<A2, E1, R1>) => STM.STM<A2, E1 | E, R1 | R>\n>(2, (self, f) => {\n  const stm = new STMPrimitive(OpCodes.OP_ON_SUCCESS)\n  stm.effect_instruction_i1 = self\n  stm.effect_instruction_i2 = f\n  return stm\n})\n\n/** @internal */\nexport const matchSTM = dual<\n  <E, A1, E1, R1, A, A2, E2, R2>(\n    options: {\n      readonly onFailure: (e: E) => STM.STM<A1, E1, R1>\n      readonly onSuccess: (a: A) => STM.STM<A2, E2, R2>\n    }\n  ) => <R>(self: STM.STM<A, E, R>) => STM.STM<A1 | A2, E1 | E2, R1 | R2 | R>,\n  <A, E, R, A1, E1, R1, A2, E2, R2>(\n    self: STM.STM<A, E, R>,\n    options: {\n      readonly onFailure: (e: E) => STM.STM<A1, E1, R1>\n      readonly onSuccess: (a: A) => STM.STM<A2, E2, R2>\n    }\n  ) => STM.STM<A1 | A2, E1 | E2, R1 | R2 | R>\n>(2, <A, E, R, A1, E1, R1, A2, E2, R2>(\n  self: STM.STM<A, E, R>,\n  { onFailure, onSuccess }: {\n    readonly onFailure: (e: E) => STM.STM<A1, E1, R1>\n    readonly onSuccess: (a: A) => STM.STM<A2, E2, R2>\n  }\n): STM.STM<A1 | A2, E1 | E2, R1 | R2 | R> =>\n  pipe(\n    self,\n    map(Either.right),\n    catchAll((e) => pipe(onFailure(e), map(Either.left))),\n    flatMap((either): STM.STM<A1 | A2, E1 | E2, R | R1 | R2> => {\n      switch (either._tag) {\n        case \"Left\": {\n          return succeed(either.left)\n        }\n        case \"Right\": {\n          return onSuccess(either.right)\n        }\n      }\n    })\n  ))\n\n/** @internal */\nexport const withSTMRuntime = <A, E = never, R = never>(\n  f: (runtime: STMDriver<unknown, unknown, unknown>) => STM.STM<A, E, R>\n): STM.STM<A, E, R> => {\n  const stm = new STMPrimitive(OpCodes.OP_WITH_STM_RUNTIME)\n  stm.effect_instruction_i1 = f\n  return stm\n}\n\n/** @internal */\nexport const interrupt: STM.STM<never> = withSTMRuntime((_) => {\n  const stm = new STMPrimitive(OpCodes.OP_INTERRUPT)\n  stm.effect_instruction_i1 = _.fiberId\n  return stm as any\n})\n\n/** @internal */\nexport const interruptAs = (fiberId: FiberId.FiberId): STM.STM<never> => {\n  const stm = new STMPrimitive(OpCodes.OP_INTERRUPT)\n  stm.effect_instruction_i1 = fiberId\n  return stm as any\n}\n\n/** @internal */\nexport const map = dual<\n  <A, B>(f: (a: A) => B) => <E, R>(self: STM.STM<A, E, R>) => STM.STM<B, E, R>,\n  <A, E, R, B>(self: STM.STM<A, E, R>, f: (a: A) => B) => STM.STM<B, E, R>\n>(2, (self, f) => pipe(self, flatMap((a) => sync(() => f(a)))))\n\n/** @internal */\nexport const orTry = dual<\n  <A1, E1, R1>(\n    that: LazyArg<STM.STM<A1, E1, R1>>\n  ) => <A, E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A1 | A, E1 | E, R1 | R>,\n  <A, E, R, A1, E1, R1>(\n    self: STM.STM<A, E, R>,\n    that: LazyArg<STM.STM<A1, E1, R1>>\n  ) => STM.STM<A1 | A, E1 | E, R1 | R>\n>(2, (self, that) => {\n  const stm = new STMPrimitive(OpCodes.OP_ON_RETRY)\n  stm.effect_instruction_i1 = self\n  stm.effect_instruction_i2 = that\n  return stm\n})\n\n/** @internal */\nexport const retry: STM.STM<never> = new STMPrimitive(OpCodes.OP_RETRY)\n\n/** @internal */\nexport const succeed = <A>(value: A): STM.STM<A> => {\n  const stm = new STMPrimitive(OpCodes.OP_SUCCEED)\n  stm.effect_instruction_i1 = value\n  return stm as any\n}\n\n/** @internal */\nexport const sync = <A>(evaluate: () => A): STM.STM<A> => {\n  const stm = new STMPrimitive(OpCodes.OP_SYNC)\n  stm.effect_instruction_i1 = evaluate\n  return stm as any\n}\n\n/** @internal */\nexport const zip = dual<\n  <A1, E1, R1>(\n    that: STM.STM<A1, E1, R1>\n  ) => <A, E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<[A, A1], E1 | E, R1 | R>,\n  <A, E, R, A1, E1, R1>(\n    self: STM.STM<A, E, R>,\n    that: STM.STM<A1, E1, R1>\n  ) => STM.STM<[A, A1], E1 | E, R1 | R>\n>(2, (self, that) => pipe(self, zipWith(that, (a, a1) => [a, a1])))\n\n/** @internal */\nexport const zipLeft = dual<\n  <A1, E1, R1>(that: STM.STM<A1, E1, R1>) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E1 | E, R1 | R>,\n  <A, E, R, A1, E1, R1>(self: STM.STM<A, E, R>, that: STM.STM<A1, E1, R1>) => STM.STM<A, E1 | E, R1 | R>\n>(2, (self, that) => pipe(self, flatMap((a) => pipe(that, map(() => a)))))\n\n/** @internal */\nexport const zipRight = dual<\n  <A1, E1, R1>(that: STM.STM<A1, E1, R1>) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<A1, E1 | E, R1 | R>,\n  <A, E, R, A1, E1, R1>(self: STM.STM<A, E, R>, that: STM.STM<A1, E1, R1>) => STM.STM<A1, E1 | E, R1 | R>\n>(2, (self, that) => pipe(self, flatMap(() => that)))\n\n/** @internal */\nexport const zipWith = dual<\n  <A1, E1, R1, A, A2>(\n    that: STM.STM<A1, E1, R1>,\n    f: (a: A, b: A1) => A2\n  ) => <E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A2, E1 | E, R1 | R>,\n  <A, E, R, A1, E1, R1, A2>(\n    self: STM.STM<A, E, R>,\n    that: STM.STM<A1, E1, R1>,\n    f: (a: A, b: A1) => A2\n  ) => STM.STM<A2, E1 | E, R1 | R>\n>(\n  3,\n  (self, that, f) => pipe(self, flatMap((a) => pipe(that, map((b) => f(a, b)))))\n)\n"
  },
  {
    "path": "packages/effect/src/internal/stm/entry.ts",
    "content": "import type * as TRef from \"../../TRef.js\"\nimport * as Versioned from \"./versioned.js\"\n\n/** @internal */\nexport interface Entry {\n  readonly ref: TRef.TRef<any>\n  readonly expected: Versioned.Versioned<any>\n  isChanged: boolean // mutable by design\n  readonly isNew: boolean\n  newValue: any // mutable by design\n}\n\n/** @internal */\nexport const make = <A>(ref: TRef.TRef<A>, isNew: boolean): Entry => ({\n  ref,\n  isNew,\n  isChanged: false,\n  expected: ref.versioned,\n  newValue: ref.versioned.value\n})\n\nexport const unsafeGet = (self: Entry): unknown => {\n  return self.newValue\n}\n\n/** @internal */\nexport const unsafeSet = (self: Entry, value: unknown): void => {\n  self.isChanged = true\n  self.newValue = value\n}\n\n/** @internal */\nexport const commit = (self: Entry): void => {\n  self.ref.versioned = new Versioned.Versioned(self.newValue)\n}\n\n/** @internal */\nexport const copy = (self: Entry): Entry => ({\n  ref: self.ref,\n  isNew: self.isNew,\n  isChanged: self.isChanged,\n  expected: self.expected,\n  newValue: self.newValue\n})\n\n/** @internal */\nexport const isValid = (self: Entry): boolean => {\n  return self.ref.versioned === self.expected\n}\n\n/** @internal */\nexport const isInvalid = (self: Entry): boolean => {\n  return self.ref.versioned !== self.expected\n}\n\n/** @internal */\nexport const isChanged = (self: Entry): boolean => {\n  return self.isChanged\n}\n"
  },
  {
    "path": "packages/effect/src/internal/stm/journal.ts",
    "content": "import type * as TRef from \"../../TRef.js\"\nimport * as Entry from \"./entry.js\"\nimport type * as TxnId from \"./txnId.js\"\n\n/** @internal */\nexport type Journal = Map<TRef.TRef<any>, Entry.Entry>\n\n/** @internal */\nexport type Todo = () => unknown\n\n/** @internal */\nexport type JournalAnalysis = JournalAnalysisInvalid | JournalAnalysisReadWrite | JournalAnalysisReadOnly\n\n/** @internal */\nexport const JournalAnalysisInvalid = \"Invalid\" as const\n\n/** @internal */\nexport type JournalAnalysisInvalid = typeof JournalAnalysisInvalid\n\n/** @internal */\nexport const JournalAnalysisReadWrite = \"ReadWrite\" as const\n\n/** @internal */\nexport type JournalAnalysisReadWrite = typeof JournalAnalysisReadWrite\n\n/** @internal */\nexport const JournalAnalysisReadOnly = \"ReadOnly\" as const\n\n/** @internal */\nexport type JournalAnalysisReadOnly = typeof JournalAnalysisReadOnly\n\n/** @internal */\nexport const commitJournal = (journal: Journal) => {\n  for (const entry of journal) {\n    Entry.commit(entry[1])\n  }\n}\n\n/**\n * Analyzes the journal, determining whether it is valid and whether it is\n * read only in a single pass. Note that information on whether the\n * journal is read only will only be accurate if the journal is valid, due\n * to short-circuiting that occurs on an invalid journal.\n *\n * @internal\n */\nexport const analyzeJournal = (journal: Journal): JournalAnalysis => {\n  let val: JournalAnalysis = JournalAnalysisReadOnly\n  for (const [, entry] of journal) {\n    val = Entry.isInvalid(entry) ? JournalAnalysisInvalid : Entry.isChanged(entry) ? JournalAnalysisReadWrite : val\n    if (val === JournalAnalysisInvalid) {\n      return val\n    }\n  }\n  return val\n}\n\n/** @internal */\nexport const prepareResetJournal = (journal: Journal): () => void => {\n  const saved: Journal = new Map<TRef.TRef<unknown>, Entry.Entry>()\n  for (const entry of journal) {\n    saved.set(entry[0], Entry.copy(entry[1]))\n  }\n  return () => {\n    journal.clear()\n    for (const entry of saved) {\n      journal.set(entry[0], entry[1])\n    }\n  }\n}\n\n/** @internal */\nexport const collectTodos = (journal: Journal): Map<TxnId.TxnId, Todo> => {\n  const allTodos: Map<TxnId.TxnId, Todo> = new Map()\n  for (const [, entry] of journal) {\n    for (const todo of entry.ref.todos) {\n      allTodos.set(todo[0], todo[1])\n    }\n    entry.ref.todos = new Map()\n  }\n  return allTodos\n}\n\n/** @internal */\nexport const execTodos = (todos: Map<TxnId.TxnId, Todo>) => {\n  const todosSorted = Array.from(todos.entries()).sort((x, y) => x[0] - y[0])\n  for (const [_, todo] of todosSorted) {\n    todo()\n  }\n}\n\n/** @internal */\nexport const addTodo = (\n  txnId: TxnId.TxnId,\n  journal: Journal,\n  todoEffect: Todo\n): boolean => {\n  let added = false\n  for (const [, entry] of journal) {\n    if (!entry.ref.todos.has(txnId)) {\n      entry.ref.todos.set(txnId, todoEffect)\n      added = true\n    }\n  }\n  return added\n}\n\n/** @internal */\nexport const isValid = (journal: Journal): boolean => {\n  let valid = true\n  for (const [, entry] of journal) {\n    valid = Entry.isValid(entry)\n    if (!valid) {\n      return valid\n    }\n  }\n  return valid\n}\n\n/** @internal */\nexport const isInvalid = (journal: Journal): boolean => {\n  return !isValid(journal)\n}\n"
  },
  {
    "path": "packages/effect/src/internal/stm/opCodes/stm.ts",
    "content": "/** @internal */\nexport const OP_WITH_STM_RUNTIME = \"WithSTMRuntime\" as const\n\n/** @internal */\nexport type OP_WITH_STM_RUNTIME = typeof OP_WITH_STM_RUNTIME\n\n/** @internal */\nexport const OP_ON_FAILURE = \"OnFailure\" as const\n\n/** @internal */\nexport type OP_ON_FAILURE = typeof OP_ON_FAILURE\n\n/** @internal */\nexport const OP_ON_RETRY = \"OnRetry\" as const\n\n/** @internal */\nexport type OP_ON_RETRY = typeof OP_ON_RETRY\n\n/** @internal */\nexport const OP_ON_SUCCESS = \"OnSuccess\" as const\n\n/** @internal */\nexport type OP_ON_SUCCESS = typeof OP_ON_SUCCESS\n\n/** @internal */\nexport const OP_PROVIDE = \"Provide\" as const\n\n/** @internal */\nexport type OP_PROVIDE = typeof OP_PROVIDE\n\n/** @internal */\nexport const OP_SYNC = \"Sync\" as const\n\n/** @internal */\nexport type OP_SYNC = typeof OP_SYNC\n\n/** @internal */\nexport const OP_SUCCEED = \"Succeed\" as const\n\n/** @internal */\nexport type OP_SUCCEED = typeof OP_SUCCEED\n\n/** @internal */\nexport const OP_RETRY = \"Retry\" as const\n\n/** @internal */\nexport type OP_RETRY = typeof OP_RETRY\n\n/** @internal */\nexport const OP_FAIL = \"Fail\" as const\n\n/** @internal */\nexport type OP_FAIL = typeof OP_FAIL\n\n/** @internal */\nexport const OP_DIE = \"Die\" as const\n\n/** @internal */\nexport type OP_DIE = typeof OP_DIE\n\n/** @internal */\nexport const OP_INTERRUPT = \"Interrupt\" as const\n\n/** @internal */\nexport type OP_INTERRUPT = typeof OP_INTERRUPT\n\n/** @internal */\nexport const OP_TRACED = \"Traced\" as const\n\n/** @internal */\nexport type OP_TRACED = typeof OP_TRACED\n"
  },
  {
    "path": "packages/effect/src/internal/stm/opCodes/stmState.ts",
    "content": "/** @internal */\nexport const OP_DONE = \"Done\" as const\n\n/** @internal */\nexport type OP_DONE = typeof OP_DONE\n\n/** @internal */\nexport const OP_INTERRUPTED = \"Interrupted\" as const\n\n/** @internal */\nexport type OP_INTERRUPTED = typeof OP_INTERRUPTED\n\n/** @internal */\nexport const OP_RUNNING = \"Running\" as const\n\n/** @internal */\nexport type OP_RUNNING = typeof OP_RUNNING\n"
  },
  {
    "path": "packages/effect/src/internal/stm/opCodes/strategy.ts",
    "content": "/** @internal */\nexport const OP_BACKPRESSURE_STRATEGY = \"BackPressure\" as const\n\n/** @internal */\nexport type OP_BACKPRESSURE_STRATEGY = typeof OP_BACKPRESSURE_STRATEGY\n\n/** @internal */\nexport const OP_DROPPING_STRATEGY = \"Dropping\" as const\n\n/** @internal */\nexport type OP_DROPPING_STRATEGY = typeof OP_DROPPING_STRATEGY\n\n/** @internal */\nexport const OP_SLIDING_STRATEGY = \"Sliding\" as const\n\n/** @internal */\nexport type OP_SLIDING_STRATEGY = typeof OP_SLIDING_STRATEGY\n"
  },
  {
    "path": "packages/effect/src/internal/stm/opCodes/tExit.ts",
    "content": "/** @internal */\nexport const OP_FAIL = \"Fail\" as const\n\n/** @internal */\nexport type OP_FAIL = typeof OP_FAIL\n\n/** @internal */\nexport const OP_DIE = \"Die\" as const\n\n/** @internal */\nexport type OP_DIE = typeof OP_DIE\n\n/** @internal */\nexport const OP_INTERRUPT = \"Interrupt\" as const\n\n/** @internal */\nexport type OP_INTERRUPT = typeof OP_INTERRUPT\n\n/** @internal */\nexport const OP_SUCCEED = \"Succeed\" as const\n\n/** @internal */\nexport type OP_SUCCEED = typeof OP_SUCCEED\n\n/** @internal */\nexport const OP_RETRY = \"Retry\" as const\n\n/** @internal */\nexport type OP_RETRY = typeof OP_RETRY\n"
  },
  {
    "path": "packages/effect/src/internal/stm/opCodes/tryCommit.ts",
    "content": "/** @internal */\nexport const OP_DONE = \"Done\" as const\n\n/** @internal */\nexport type OP_DONE = typeof OP_DONE\n\n/** @internal */\nexport const OP_SUSPEND = \"Suspend\" as const\n\n/** @internal */\nexport type OP_SUSPEND = typeof OP_SUSPEND\n"
  },
  {
    "path": "packages/effect/src/internal/stm/stm.ts",
    "content": "import * as RA from \"../../Array.js\"\nimport * as Cause from \"../../Cause.js\"\nimport * as Chunk from \"../../Chunk.js\"\nimport * as Context from \"../../Context.js\"\nimport * as Effect from \"../../Effect.js\"\nimport * as Either from \"../../Either.js\"\nimport * as Exit from \"../../Exit.js\"\nimport type * as FiberId from \"../../FiberId.js\"\nimport type { LazyArg } from \"../../Function.js\"\nimport { constFalse, constTrue, constVoid, dual, identity, pipe } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport type { Predicate, Refinement } from \"../../Predicate.js\"\nimport * as predicate from \"../../Predicate.js\"\nimport type * as STM from \"../../STM.js\"\nimport type * as Types from \"../../Types.js\"\nimport { yieldWrapGet } from \"../../Utils.js\"\nimport * as effectCore from \"../core.js\"\nimport * as core from \"./core.js\"\nimport * as Journal from \"./journal.js\"\nimport * as STMState from \"./stmState.js\"\n\n/** @internal */\nexport const acquireUseRelease = dual<\n  <A, A2, E2, R2, A3, E3, R3>(\n    use: (resource: A) => STM.STM<A2, E2, R2>,\n    release: (resource: A) => STM.STM<A3, E3, R3>\n  ) => <E, R>(\n    acquire: STM.STM<A, E, R>\n  ) => Effect.Effect<A2, E | E2 | E3, R | R2 | R3>,\n  <A, E, R, A2, E2, R2, A3, E3, R3>(\n    acquire: STM.STM<A, E, R>,\n    use: (resource: A) => STM.STM<A2, E2, R2>,\n    release: (resource: A) => STM.STM<A3, E3, R3>\n  ) => Effect.Effect<A2, E | E2 | E3, R | R2 | R3>\n>(3, <A, E, R, A2, E2, R2, A3, E3, R3>(\n  acquire: STM.STM<A, E, R>,\n  use: (resource: A) => STM.STM<A2, E2, R2>,\n  release: (resource: A) => STM.STM<A3, E3, R3>\n): Effect.Effect<A2, E | E2 | E3, R | R2 | R3> =>\n  Effect.uninterruptibleMask((restore) => {\n    let state: STMState.STMState<A, E> = STMState.running\n    return pipe(\n      restore(\n        core.unsafeAtomically(\n          acquire,\n          (exit) => {\n            state = STMState.done(exit)\n          },\n          () => {\n            state = STMState.interrupted\n          }\n        )\n      ),\n      Effect.matchCauseEffect({\n        onFailure: (cause) => {\n          if (STMState.isDone(state) && Exit.isSuccess(state.exit)) {\n            return pipe(\n              release(state.exit.value),\n              Effect.matchCauseEffect({\n                onFailure: (cause2) => Effect.failCause(Cause.parallel(cause, cause2)),\n                onSuccess: () => Effect.failCause(cause)\n              })\n            )\n          }\n          return Effect.failCause(cause)\n        },\n        onSuccess: (a) =>\n          pipe(\n            restore(use(a)),\n            Effect.matchCauseEffect({\n              onFailure: (cause) =>\n                pipe(\n                  release(a),\n                  Effect.matchCauseEffect({\n                    onFailure: (cause2) => Effect.failCause(Cause.parallel(cause, cause2)),\n                    onSuccess: () => Effect.failCause(cause)\n                  })\n                ),\n              onSuccess: (a2) => pipe(release(a), Effect.as(a2))\n            })\n          )\n      })\n    )\n  }))\n\n/** @internal */\nexport const as = dual<\n  <A2>(value: A2) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<A2, E, R>,\n  <A, E, R, A2>(self: STM.STM<A, E, R>, value: A2) => STM.STM<A2, E, R>\n>(2, (self, value) => pipe(self, core.map(() => value)))\n\n/** @internal */\nexport const asSome = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<Option.Option<A>, E, R> =>\n  pipe(self, core.map(Option.some))\n\n/** @internal */\nexport const asSomeError = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<A, Option.Option<E>, R> =>\n  pipe(self, mapError(Option.some))\n\n/** @internal */\nexport const asVoid = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<void, E, R> => pipe(self, core.map(constVoid))\n\n/** @internal */\nexport const attempt = <A>(evaluate: LazyArg<A>): STM.STM<A, unknown> =>\n  suspend(() => {\n    try {\n      return core.succeed(evaluate())\n    } catch (defect) {\n      return core.fail(defect)\n    }\n  })\n\nexport const bind = dual<\n  <N extends string, K, A, E2, R2>(\n    tag: Exclude<N, keyof K>,\n    f: (_: K) => STM.STM<A, E2, R2>\n  ) => <E, R>(self: STM.STM<K, E, R>) => STM.STM<Types.MergeRecord<K, { [k in N]: A }>, E | E2, R | R2>,\n  <K, E, R, N extends string, A, E2, R2>(\n    self: STM.STM<K, E, R>,\n    tag: Exclude<N, keyof K>,\n    f: (_: K) => STM.STM<A, E2, R2>\n  ) => STM.STM<Types.MergeRecord<K, { [k in N]: A }>, E | E2, R | R2>\n>(3, <K, E, R, N extends string, A, E2, R2>(\n  self: STM.STM<K, E, R>,\n  tag: Exclude<N, keyof K>,\n  f: (_: K) => STM.STM<A, E2, R2>\n) =>\n  core.flatMap(self, (k) =>\n    core.map(\n      f(k),\n      (a): Types.MergeRecord<K, { [k in N]: A }> => ({ ...k, [tag]: a } as any)\n    )))\n\n/* @internal */\nexport const bindTo = dual<\n  <N extends string>(tag: N) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<\n    Record<N, A>,\n    E,\n    R\n  >,\n  <A, E, R, N extends string>(\n    self: STM.STM<A, E, R>,\n    tag: N\n  ) => STM.STM<\n    Record<N, A>,\n    E,\n    R\n  >\n>(\n  2,\n  <A, E, R, N extends string>(self: STM.STM<A, E, R>, tag: N): STM.STM<Record<N, A>, E, R> =>\n    core.map(self, (a) => ({ [tag]: a } as Record<N, A>))\n)\n\n/* @internal */\nexport const let_ = dual<\n  <N extends string, K, A>(\n    tag: Exclude<N, keyof K>,\n    f: (_: K) => A\n  ) => <E, R>(self: STM.STM<K, E, R>) => STM.STM<\n    Types.MergeRecord<K, { [k in N]: A }>,\n    E,\n    R\n  >,\n  <K, E, R, N extends string, A>(\n    self: STM.STM<K, E, R>,\n    tag: Exclude<N, keyof K>,\n    f: (_: K) => A\n  ) => STM.STM<\n    Types.MergeRecord<K, { [k in N]: A }>,\n    E,\n    R\n  >\n>(3, <K, E, R, N extends string, A>(self: STM.STM<K, E, R>, tag: Exclude<N, keyof K>, f: (_: K) => A) =>\n  core.map(\n    self,\n    (k): Types.MergeRecord<K, { [k in N]: A }> => ({ ...k, [tag]: f(k) } as any)\n  ))\n\n/** @internal */\nexport const catchSome = dual<\n  <E, A2, E2, R2>(\n    pf: (error: E) => Option.Option<STM.STM<A2, E2, R2>>\n  ) => <A, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A2 | A, E | E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: STM.STM<A, E, R>,\n    pf: (error: E) => Option.Option<STM.STM<A2, E2, R2>>\n  ) => STM.STM<A2 | A, E | E2, R2 | R>\n>(2, <A, E, R, A2, E2, R2>(\n  self: STM.STM<A, E, R>,\n  pf: (error: E) => Option.Option<STM.STM<A2, E2, R2>>\n): STM.STM<A2 | A, E | E2, R2 | R> =>\n  core.catchAll(\n    self,\n    (e): STM.STM<A | A2, E | E2, R | R2> => Option.getOrElse(pf(e), () => core.fail(e))\n  ))\n\n/** @internal */\nexport const catchTag = dual<\n  <K extends E[\"_tag\"] & string, E extends { _tag: string }, A1, E1, R1>(\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => STM.STM<A1, E1, R1>\n  ) => <A, R>(self: STM.STM<A, E, R>) => STM.STM<A | A1, Exclude<E, { _tag: K }> | E1, R | R1>,\n  <A, E extends { _tag: string }, R, K extends E[\"_tag\"] & string, A1, E1, R1>(\n    self: STM.STM<A, E, R>,\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => STM.STM<A1, E1, R1>\n  ) => STM.STM<A | A1, Exclude<E, { _tag: K }> | E1, R | R1>\n>(3, (self, k, f) =>\n  core.catchAll(self, (e) => {\n    if (\"_tag\" in e && e[\"_tag\"] === k) {\n      return f(e as any)\n    }\n    return core.fail(e as any)\n  }))\n\n/** @internal */\nexport const catchTags: {\n  <\n    E extends { _tag: string },\n    Cases extends {\n      [K in E[\"_tag\"]]+?: (error: Extract<E, { _tag: K }>) => STM.STM<any, any, any>\n    }\n  >(\n    cases: Cases\n  ): <A, R>(self: STM.STM<A, E, R>) => STM.STM<\n    | A\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => STM.STM<infer A, any, any>) ? A : never\n    }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => STM.STM<any, infer E, any>) ? E : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => STM.STM<any, any, infer R>) ? R : never\n    }[keyof Cases]\n  >\n  <\n    R,\n    E extends { _tag: string },\n    A,\n    Cases extends {\n      [K in E[\"_tag\"]]+?: (error: Extract<E, { _tag: K }>) => STM.STM<any, any, any>\n    }\n  >(\n    self: STM.STM<A, E, R>,\n    cases: Cases\n  ): STM.STM<\n    | A\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => STM.STM<infer A, any, any>) ? A : never\n    }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => STM.STM<any, infer E, any>) ? E : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends ((...args: Array<any>) => STM.STM<any, any, infer R>) ? R : never\n    }[keyof Cases]\n  >\n} = dual(2, (self, cases) =>\n  core.catchAll(self, (e: any) => {\n    const keys = Object.keys(cases)\n    if (\"_tag\" in e && keys.includes(e[\"_tag\"])) {\n      return cases[e[\"_tag\"]](e as any)\n    }\n    return core.fail(e as any)\n  }))\n\n/** @internal */\nexport const check = (predicate: LazyArg<boolean>): STM.STM<void> => suspend(() => predicate() ? void_ : core.retry)\n\n/** @internal */\nexport const collect = dual<\n  <A, A2>(pf: (a: A) => Option.Option<A2>) => <E, R>(self: STM.STM<A, E, R>) => STM.STM<A2, E, R>,\n  <A, E, R, A2>(self: STM.STM<A, E, R>, pf: (a: A) => Option.Option<A2>) => STM.STM<A2, E, R>\n>(2, (self, pf) =>\n  collectSTM(\n    self,\n    (a) => Option.map(pf(a), core.succeed)\n  ))\n\n/** @internal */\nexport const collectSTM = dual<\n  <A, A2, E2, R2>(\n    pf: (a: A) => Option.Option<STM.STM<A2, E2, R2>>\n  ) => <E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: STM.STM<A, E, R>,\n    pf: (a: A) => Option.Option<STM.STM<A2, E2, R2>>\n  ) => STM.STM<A2, E2 | E, R2 | R>\n>(2, (self, pf) =>\n  core.matchSTM(self, {\n    onFailure: core.fail,\n    onSuccess: (a) => {\n      const option = pf(a)\n      return Option.isSome(option) ? option.value : core.retry\n    }\n  }))\n\n/** @internal */\nexport const commitEither = <A, E, R>(self: STM.STM<A, E, R>): Effect.Effect<A, E, R> =>\n  Effect.flatten(core.commit(either(self)))\n\n/** @internal */\nexport const cond = <A, E>(\n  predicate: LazyArg<boolean>,\n  error: LazyArg<E>,\n  result: LazyArg<A>\n): STM.STM<A, E> => {\n  return suspend(\n    () => predicate() ? core.sync(result) : core.failSync(error)\n  )\n}\n\n/** @internal */\nexport const either = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<Either.Either<A, E>, never, R> =>\n  match(self, { onFailure: Either.left, onSuccess: Either.right })\n\n/** @internal */\nexport const eventually = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<A, E, R> =>\n  core.matchSTM(self, { onFailure: () => eventually(self), onSuccess: core.succeed })\n\n/** @internal */\nexport const every = dual<\n  <A, R, E>(\n    predicate: (a: Types.NoInfer<A>) => STM.STM<boolean, E, R>\n  ) => (iterable: Iterable<A>) => STM.STM<boolean, E, R>,\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM.STM<boolean, E, R>) => STM.STM<boolean, E, R>\n>(\n  2,\n  <A, R, E>(\n    iterable: Iterable<A>,\n    predicate: (a: A) => STM.STM<boolean, E, R>\n  ): STM.STM<boolean, E, R> =>\n    core.flatMap(core.sync(() => iterable[Symbol.iterator]()), (iterator) => {\n      const loop: STM.STM<boolean, E, R> = suspend(() => {\n        const next = iterator.next()\n        if (next.done) {\n          return core.succeed(true)\n        }\n        return pipe(\n          predicate(next.value),\n          core.flatMap((bool) => bool ? loop : core.succeed(bool))\n        )\n      })\n      return loop\n    })\n)\n\n/** @internal */\nexport const exists = dual<\n  <A, R, E>(\n    predicate: (a: Types.NoInfer<A>) => STM.STM<boolean, E, R>\n  ) => (iterable: Iterable<A>) => STM.STM<boolean, E, R>,\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM.STM<boolean, E, R>) => STM.STM<boolean, E, R>\n>(\n  2,\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM.STM<boolean, E, R>): STM.STM<boolean, E, R> =>\n    core.flatMap(core.sync(() => iterable[Symbol.iterator]()), (iterator) => {\n      const loop: STM.STM<boolean, E, R> = suspend(() => {\n        const next = iterator.next()\n        if (next.done) {\n          return core.succeed(false)\n        }\n        return core.flatMap(\n          predicate(next.value),\n          (bool) => bool ? core.succeed(bool) : loop\n        )\n      })\n      return loop\n    })\n)\n\n/** @internal */\nexport const fiberId: STM.STM<FiberId.FiberId> = core.effect<never, FiberId.FiberId>((_, fiberId) => fiberId)\n\n/** @internal */\nexport const filter = dual<\n  <A, R, E>(\n    predicate: (a: Types.NoInfer<A>) => STM.STM<boolean, E, R>\n  ) => (iterable: Iterable<A>) => STM.STM<Array<A>, E, R>,\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM.STM<boolean, E, R>) => STM.STM<Array<A>, E, R>\n>(\n  2,\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM.STM<boolean, E, R>): STM.STM<Array<A>, E, R> =>\n    Array.from(iterable).reduce(\n      (acc, curr) =>\n        pipe(\n          acc,\n          core.zipWith(predicate(curr), (as, p) => {\n            if (p) {\n              as.push(curr)\n              return as\n            }\n            return as\n          })\n        ),\n      core.succeed([]) as STM.STM<Array<A>, E, R>\n    )\n)\n\n/** @internal */\nexport const filterNot = dual<\n  <A, R, E>(\n    predicate: (a: Types.NoInfer<A>) => STM.STM<boolean, E, R>\n  ) => (iterable: Iterable<A>) => STM.STM<Array<A>, E, R>,\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM.STM<boolean, E, R>) => STM.STM<Array<A>, E, R>\n>(\n  2,\n  <A, R, E>(iterable: Iterable<A>, predicate: (a: A) => STM.STM<boolean, E, R>): STM.STM<Array<A>, E, R> =>\n    filter(iterable, (a) => negate(predicate(a)))\n)\n\n/** @internal */\nexport const filterOrDie: {\n  <A, B extends A>(\n    refinement: Refinement<Types.NoInfer<A>, B>,\n    defect: LazyArg<unknown>\n  ): <E, R>(self: STM.STM<A, E, R>) => STM.STM<B, E, R>\n  <A>(\n    predicate: Predicate<Types.NoInfer<A>>,\n    defect: LazyArg<unknown>\n  ): <E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E, R>\n  <A, E, R, B extends A>(\n    self: STM.STM<A, E, R>,\n    refinement: Refinement<A, B>,\n    defect: LazyArg<unknown>\n  ): STM.STM<B, E, R>\n  <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>, defect: LazyArg<unknown>): STM.STM<A, E, R>\n} = dual(\n  3,\n  <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>, defect: LazyArg<unknown>): STM.STM<A, E, R> =>\n    filterOrElse(self, predicate, () => core.dieSync(defect))\n)\n\n/** @internal */\nexport const filterOrDieMessage: {\n  <A, B extends A>(\n    refinement: Refinement<Types.NoInfer<A>, B>,\n    message: string\n  ): <E, R>(self: STM.STM<A, E, R>) => STM.STM<B, E, R>\n  <A>(predicate: Predicate<Types.NoInfer<A>>, message: string): <E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E, R>\n  <A, E, R, B extends A>(self: STM.STM<A, E, R>, refinement: Refinement<A, B>, message: string): STM.STM<B, E, R>\n  <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>, message: string): STM.STM<A, E, R>\n} = dual(\n  3,\n  <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>, message: string): STM.STM<A, E, R> =>\n    filterOrElse(self, predicate, () => core.dieMessage(message))\n)\n\n/** @internal */\nexport const filterOrElse: {\n  <A, B extends A, C, E2, R2>(\n    refinement: Refinement<Types.NoInfer<A>, B>,\n    orElse: (a: Types.NoInfer<A>) => STM.STM<C, E2, R2>\n  ): <E, R>(self: STM.STM<A, E, R>) => STM.STM<B | C, E2 | E, R2 | R>\n  <A, B, E2, R2>(\n    predicate: Predicate<Types.NoInfer<A>>,\n    orElse: (a: Types.NoInfer<A>) => STM.STM<B, E2, R2>\n  ): <E, R>(self: STM.STM<A, E, R>) => STM.STM<A | B, E2 | E, R2 | R>\n  <A, E, R, B extends A, C, E2, R2>(\n    self: STM.STM<A, E, R>,\n    refinement: Refinement<A, B>,\n    orElse: (a: A) => STM.STM<C, E2, R2>\n  ): STM.STM<B | C, E | E2, R | R2>\n  <A, E, R, B, E2, R2>(\n    self: STM.STM<A, E, R>,\n    predicate: Predicate<A>,\n    orElse: (a: A) => STM.STM<B, E2, R2>\n  ): STM.STM<A | B, E | E2, R | R2>\n} = dual(\n  3,\n  <A, E, R, B, E2, R2>(\n    self: STM.STM<A, E, R>,\n    predicate: Predicate<A>,\n    orElse: (a: A) => STM.STM<B, E2, R2>\n  ): STM.STM<A | B, E | E2, R | R2> =>\n    core.flatMap(self, (a): STM.STM<A | B, E2, R2> => predicate(a) ? core.succeed(a) : orElse(a))\n)\n\n/** @internal */\nexport const filterOrFail: {\n  <A, B extends A, E2>(\n    refinement: Refinement<Types.NoInfer<A>, B>,\n    orFailWith: (a: Types.NoInfer<A>) => E2\n  ): <E, R>(self: STM.STM<A, E, R>) => STM.STM<B, E2 | E, R>\n  <A, E2>(\n    predicate: Predicate<Types.NoInfer<A>>,\n    orFailWith: (a: Types.NoInfer<A>) => E2\n  ): <E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E2 | E, R>\n  <A, E, R, B extends A, E2>(\n    self: STM.STM<A, E, R>,\n    refinement: Refinement<A, B>,\n    orFailWith: (a: A) => E2\n  ): STM.STM<B, E | E2, R>\n  <A, E, R, E2>(self: STM.STM<A, E, R>, predicate: Predicate<A>, orFailWith: (a: A) => E2): STM.STM<A, E | E2, R>\n} = dual(\n  3,\n  <A, E, R, E2>(self: STM.STM<A, E, R>, predicate: Predicate<A>, orFailWith: (a: A) => E2): STM.STM<A, E | E2, R> =>\n    filterOrElse(\n      self,\n      predicate,\n      (a) => core.failSync(() => orFailWith(a))\n    )\n)\n\n/** @internal */\nexport const flatten = <A, E2, R2, E, R>(self: STM.STM<STM.STM<A, E2, R2>, E, R>): STM.STM<A, E | E2, R | R2> =>\n  core.flatMap(self, identity)\n\n/** @internal */\nexport const flip = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<E, A, R> =>\n  core.matchSTM(self, { onFailure: core.succeed, onSuccess: core.fail })\n\n/** @internal */\nexport const flipWith = dual<\n  <E, A, R, E2, A2, R2>(\n    f: (stm: STM.STM<E, A, R>) => STM.STM<E2, A2, R2>\n  ) => (\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A | A2, E | E2, R | R2>,\n  <A, E, R, E2, A2, R2>(\n    self: STM.STM<A, E, R>,\n    f: (stm: STM.STM<E, A, R>) => STM.STM<E2, A2, R2>\n  ) => STM.STM<A | A2, E | E2, R | R2>\n>(2, (self, f) => flip(f(flip(self))))\n\n/** @internal */\nexport const match = dual<\n  <E, A2, A, A3>(options: {\n    readonly onFailure: (error: E) => A2\n    readonly onSuccess: (value: A) => A3\n  }) => <R>(self: STM.STM<A, E, R>) => STM.STM<A2 | A3, never, R>,\n  <A, E, R, A2, A3>(self: STM.STM<A, E, R>, options: {\n    readonly onFailure: (error: E) => A2\n    readonly onSuccess: (value: A) => A3\n  }) => STM.STM<A2 | A3, never, R>\n>(2, (self, { onFailure, onSuccess }) =>\n  core.matchSTM(self, {\n    onFailure: (e) => core.succeed(onFailure(e)),\n    onSuccess: (a) => core.succeed(onSuccess(a))\n  }))\n\n/** @internal */\nexport const forEach = dual<\n  {\n    <A, A2, E, R>(f: (a: A) => STM.STM<A2, E, R>, options?: {\n      readonly discard?: false | undefined\n    }): (elements: Iterable<A>) => STM.STM<Array<A2>, E, R>\n    <A, A2, E, R>(f: (a: A) => STM.STM<A2, E, R>, options: {\n      readonly discard: true\n    }): (elements: Iterable<A>) => STM.STM<void, E, R>\n  },\n  {\n    <A, A2, E, R>(elements: Iterable<A>, f: (a: A) => STM.STM<A2, E, R>, options?: {\n      readonly discard?: false | undefined\n    }): STM.STM<Array<A2>, E, R>\n    <A, A2, E, R>(elements: Iterable<A>, f: (a: A) => STM.STM<A2, E, R>, options: {\n      readonly discard: true\n    }): STM.STM<void, E, R>\n  }\n>(\n  (args) => predicate.isIterable(args[0]),\n  <A, A2, E, R>(iterable: Iterable<A>, f: (a: A) => STM.STM<A2, E, R>, options?: {\n    readonly discard?: boolean | undefined\n  }): STM.STM<any, E, R> => {\n    if (options?.discard) {\n      return pipe(\n        core.sync(() => iterable[Symbol.iterator]()),\n        core.flatMap((iterator) => {\n          const loop: STM.STM<void, E, R> = suspend(() => {\n            const next = iterator.next()\n            if (next.done) {\n              return void_\n            }\n            return pipe(f(next.value), core.flatMap(() => loop))\n          })\n          return loop\n        })\n      )\n    }\n\n    return suspend(() =>\n      RA.fromIterable(iterable).reduce(\n        (acc, curr) =>\n          core.zipWith(acc, f(curr), (array, elem) => {\n            array.push(elem)\n            return array\n          }),\n        core.succeed([]) as STM.STM<Array<A2>, E, R>\n      )\n    )\n  }\n)\n\n/** @internal */\nexport const fromEither = <A, E>(either: Either.Either<A, E>): STM.STM<A, E> => {\n  switch (either._tag) {\n    case \"Left\": {\n      return core.fail(either.left)\n    }\n    case \"Right\": {\n      return core.succeed(either.right)\n    }\n  }\n}\n\n/** @internal */\nexport const fromOption = <A>(option: Option.Option<A>): STM.STM<A, Option.Option<never>> =>\n  Option.match(option, {\n    onNone: () => core.fail(Option.none()),\n    onSome: core.succeed\n  })\n\n/**\n * Inspired by https://github.com/tusharmath/qio/pull/22 (revised)\n * @internal\n */\nexport const gen: typeof STM.gen = (...args) =>\n  suspend(() => {\n    const f = (args.length === 1)\n      ? args[0]\n      : args[1].bind(args[0])\n    const iterator = f(pipe)\n    const state = iterator.next()\n    const run = (\n      state: IteratorYieldResult<any> | IteratorReturnResult<any>\n    ): STM.STM<any, any, any> =>\n      state.done ?\n        core.succeed(state.value) :\n        core.flatMap(yieldWrapGet(state.value) as any, (val: any) => run(iterator.next(val as never)))\n    return run(state)\n  })\n\n/** @internal */\nexport const head = <A, E, R>(self: STM.STM<Iterable<A>, E, R>): STM.STM<A, Option.Option<E>, R> =>\n  pipe(\n    self,\n    core.matchSTM({\n      onFailure: (e) => core.fail(Option.some(e)),\n      onSuccess: (a) => {\n        const i = a[Symbol.iterator]()\n        const res = i.next()\n        if (res.done) {\n          return core.fail(Option.none())\n        } else {\n          return core.succeed(res.value)\n        }\n      }\n    })\n  )\n\n/** @internal */\nexport const if_ = dual<\n  <A, E1, R1, A2, E2, R2>(\n    options: {\n      readonly onTrue: STM.STM<A, E1, R1>\n      readonly onFalse: STM.STM<A2, E2, R2>\n    }\n  ) => <E = never, R = never>(\n    self: STM.STM<boolean, E, R> | boolean\n  ) => STM.STM<A | A2, E1 | E2 | E, R1 | R2 | R>,\n  {\n    <A, E1, R1, A2, E2, R2, E = never, R = never>(\n      self: boolean,\n      options: {\n        readonly onTrue: STM.STM<A, E1, R1>\n        readonly onFalse: STM.STM<A2, E2, R2>\n      }\n    ): STM.STM<A | A2, E1 | E2 | E, R1 | R2 | R>\n    <E, R, A, E1, R1, A2, E2, R2>(\n      self: STM.STM<boolean, E, R>,\n      options: {\n        readonly onTrue: STM.STM<A, E1, R1>\n        readonly onFalse: STM.STM<A2, E2, R2>\n      }\n    ): STM.STM<A | A2, E1 | E2 | E, R1 | R2 | R>\n  }\n>(\n  (args) => typeof args[0] === \"boolean\" || core.isSTM(args[0]),\n  <E, R, A, E1, R1, A2, E2, R2>(\n    self: STM.STM<boolean, E, R> | boolean,\n    { onFalse, onTrue }: {\n      readonly onTrue: STM.STM<A, E1, R1>\n      readonly onFalse: STM.STM<A2, E2, R2>\n    }\n  ) => {\n    if (typeof self === \"boolean\") {\n      return self ? onTrue : onFalse\n    }\n\n    return core.flatMap(self, (bool): STM.STM<A | A2, E1 | E2 | E, R1 | R2 | R> => bool ? onTrue : onFalse)\n  }\n)\n\n/** @internal */\nexport const ignore = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<void, never, R> =>\n  match(self, { onFailure: () => void_, onSuccess: () => void_ })\n\n/** @internal */\nexport const isFailure = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<boolean, never, R> =>\n  match(self, { onFailure: constTrue, onSuccess: constFalse })\n\n/** @internal */\nexport const isSuccess = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<boolean, never, R> =>\n  match(self, { onFailure: constFalse, onSuccess: constTrue })\n\n/** @internal */\nexport const iterate = <Z, E, R>(\n  initial: Z,\n  options: {\n    readonly while: (z: Z) => boolean\n    readonly body: (z: Z) => STM.STM<Z, E, R>\n  }\n): STM.STM<Z, E, R> => iterateLoop(initial, options.while, options.body)\n\nconst iterateLoop = <Z, E, R>(\n  initial: Z,\n  cont: (z: Z) => boolean,\n  body: (z: Z) => STM.STM<Z, E, R>\n): STM.STM<Z, E, R> => {\n  if (cont(initial)) {\n    return pipe(\n      body(initial),\n      core.flatMap((z) => iterateLoop(z, cont, body))\n    )\n  }\n  return core.succeed(initial)\n}\n\n/** @internal */\nexport const loop: {\n  <Z, A, E, R>(\n    initial: Z,\n    options: {\n      readonly while: (z: Z) => boolean\n      readonly step: (z: Z) => Z\n      readonly body: (z: Z) => STM.STM<A, E, R>\n      readonly discard?: false | undefined\n    }\n  ): STM.STM<Array<A>, E, R>\n  <Z, A, E, R>(\n    initial: Z,\n    options: {\n      readonly while: (z: Z) => boolean\n      readonly step: (z: Z) => Z\n      readonly body: (z: Z) => STM.STM<A, E, R>\n      readonly discard: true\n    }\n  ): STM.STM<void, E, R>\n} = <Z, A, E, R>(\n  initial: Z,\n  options: {\n    readonly while: (z: Z) => boolean\n    readonly step: (z: Z) => Z\n    readonly body: (z: Z) => STM.STM<A, E, R>\n    readonly discard?: boolean | undefined\n  }\n): STM.STM<any, E, R> =>\n  options.discard ?\n    loopDiscardLoop(initial, options.while, options.step, options.body) :\n    core.map(loopLoop(initial, options.while, options.step, options.body), (a) => Array.from(a))\n\nconst loopLoop = <Z, A, E, R>(\n  initial: Z,\n  cont: (z: Z) => boolean,\n  inc: (z: Z) => Z,\n  body: (z: Z) => STM.STM<A, E, R>\n): STM.STM<Chunk.Chunk<A>, E, R> => {\n  if (cont(initial)) {\n    return pipe(\n      body(initial),\n      core.flatMap((a) => pipe(loopLoop(inc(initial), cont, inc, body), core.map(Chunk.append(a))))\n    )\n  }\n  return core.succeed(Chunk.empty<A>())\n}\n\nconst loopDiscardLoop = <Z, R, E, X>(\n  initial: Z,\n  cont: (z: Z) => boolean,\n  inc: (z: Z) => Z,\n  body: (z: Z) => STM.STM<X, E, R>\n): STM.STM<void, E, R> => {\n  if (cont(initial)) {\n    return pipe(\n      body(initial),\n      core.flatMap(() => loopDiscardLoop(inc(initial), cont, inc, body))\n    )\n  }\n  return void_\n}\n\n/** @internal */\nexport const mapAttempt = dual<\n  <A, B>(f: (a: A) => B) => <E, R>(self: STM.STM<A, E, R>) => STM.STM<B, unknown, R>,\n  <A, E, R, B>(self: STM.STM<A, E, R>, f: (a: A) => B) => STM.STM<B, unknown, R>\n>(2, <A, E, R, B>(self: STM.STM<A, E, R>, f: (a: A) => B): STM.STM<B, unknown, R> =>\n  core.matchSTM(self, {\n    onFailure: (e) => core.fail(e),\n    onSuccess: (a) => attempt(() => f(a))\n  }))\n\n/** @internal */\nexport const mapBoth = dual<\n  <E, E2, A, A2>(options: {\n    readonly onFailure: (error: E) => E2\n    readonly onSuccess: (value: A) => A2\n  }) => <R>(self: STM.STM<A, E, R>) => STM.STM<A2, E2, R>,\n  <A, E, R, E2, A2>(self: STM.STM<A, E, R>, options: {\n    readonly onFailure: (error: E) => E2\n    readonly onSuccess: (value: A) => A2\n  }) => STM.STM<A2, E2, R>\n>(2, (self, { onFailure, onSuccess }) =>\n  core.matchSTM(self, {\n    onFailure: (e) => core.fail(onFailure(e)),\n    onSuccess: (a) => core.succeed(onSuccess(a))\n  }))\n\n/** @internal */\nexport const mapError = dual<\n  <E, E2>(f: (error: E) => E2) => <A, R>(self: STM.STM<A, E, R>) => STM.STM<A, E2, R>,\n  <A, E, R, E2>(self: STM.STM<A, E, R>, f: (error: E) => E2) => STM.STM<A, E2, R>\n>(2, (self, f) =>\n  core.matchSTM(self, {\n    onFailure: (e) => core.fail(f(e)),\n    onSuccess: core.succeed\n  }))\n\n/** @internal */\nexport const merge = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<E | A, never, R> =>\n  core.matchSTM(self, { onFailure: (e) => core.succeed(e), onSuccess: core.succeed })\n\n/** @internal */\nexport const mergeAll = dual<\n  <A2, A>(zero: A2, f: (a2: A2, a: A) => A2) => <E, R>(iterable: Iterable<STM.STM<A, E, R>>) => STM.STM<A2, E, R>,\n  <A, E, R, A2>(iterable: Iterable<STM.STM<A, E, R>>, zero: A2, f: (a2: A2, a: A) => A2) => STM.STM<A2, E, R>\n>(\n  3,\n  <A, E, R, A2>(iterable: Iterable<STM.STM<A, E, R>>, zero: A2, f: (a2: A2, a: A) => A2): STM.STM<A2, E, R> =>\n    suspend(() =>\n      Array.from(iterable).reduce(\n        (acc, curr) => pipe(acc, core.zipWith(curr, f)),\n        core.succeed(zero) as STM.STM<A2, E, R>\n      )\n    )\n)\n\n/** @internal */\nexport const negate = <E, R>(self: STM.STM<boolean, E, R>): STM.STM<boolean, E, R> => pipe(self, core.map((b) => !b))\n\n/** @internal */\nexport const none = <A, E, R>(self: STM.STM<Option.Option<A>, E, R>): STM.STM<void, Option.Option<E>, R> =>\n  core.matchSTM(self, {\n    onFailure: (e) => core.fail(Option.some(e)),\n    onSuccess: Option.match({\n      onNone: () => void_,\n      onSome: () => core.fail(Option.none())\n    })\n  })\n\n/** @internal */\nexport const option = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<Option.Option<A>, never, R> =>\n  match(self, { onFailure: () => Option.none(), onSuccess: Option.some })\n\n/** @internal */\nexport const orDie = <A, E, R>(self: STM.STM<A, E, R>): STM.STM<A, never, R> => pipe(self, orDieWith(identity))\n\n/** @internal */\nexport const orDieWith = dual<\n  <E>(f: (error: E) => unknown) => <A, R>(self: STM.STM<A, E, R>) => STM.STM<A, never, R>,\n  <A, E, R>(self: STM.STM<A, E, R>, f: (error: E) => unknown) => STM.STM<A, never, R>\n>(2, (self, f) => pipe(self, mapError(f), core.catchAll(core.die)))\n\n/** @internal */\nexport const orElse = dual<\n  <A2, E2, R2>(that: LazyArg<STM.STM<A2, E2, R2>>) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<A2 | A, E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(self: STM.STM<A, E, R>, that: LazyArg<STM.STM<A2, E2, R2>>) => STM.STM<A2 | A, E2, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(self: STM.STM<A, E, R>, that: LazyArg<STM.STM<A2, E2, R2>>): STM.STM<A2 | A, E2, R2 | R> =>\n    core.flatMap(core.effect<R, LazyArg<void>>((journal) => Journal.prepareResetJournal(journal)), (reset) =>\n      pipe(\n        core.orTry(self, () => core.flatMap(core.sync(reset), that)),\n        core.catchAll(() => core.flatMap(core.sync(reset), that))\n      ))\n)\n\n/** @internal */\nexport const orElseEither = dual<\n  <A2, E2, R2>(\n    that: LazyArg<STM.STM<A2, E2, R2>>\n  ) => <A, E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<Either.Either<A2, A>, E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: STM.STM<A, E, R>,\n    that: LazyArg<STM.STM<A2, E2, R2>>\n  ) => STM.STM<Either.Either<A2, A>, E2, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: STM.STM<A, E, R>,\n    that: LazyArg<STM.STM<A2, E2, R2>>\n  ): STM.STM<Either.Either<A2, A>, E2, R2 | R> =>\n    orElse(core.map(self, Either.left), () => core.map(that(), Either.right))\n)\n\n/** @internal */\nexport const orElseFail = dual<\n  <E2>(error: LazyArg<E2>) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E2, R>,\n  <A, E, R, E2>(self: STM.STM<A, E, R>, error: LazyArg<E2>) => STM.STM<A, E2, R>\n>(\n  2,\n  <A, E, R, E2>(self: STM.STM<A, E, R>, error: LazyArg<E2>): STM.STM<A, E2, R> =>\n    orElse(self, () => core.failSync(error))\n)\n\n/** @internal */\nexport const orElseOptional = dual<\n  <A2, E2, R2>(\n    that: LazyArg<STM.STM<A2, Option.Option<E2>, R2>>\n  ) => <A, E, R>(\n    self: STM.STM<A, Option.Option<E>, R>\n  ) => STM.STM<A2 | A, Option.Option<E2 | E>, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: STM.STM<A, Option.Option<E>, R>,\n    that: LazyArg<STM.STM<A2, Option.Option<E2>, R2>>\n  ) => STM.STM<A2 | A, Option.Option<E2 | E>, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: STM.STM<A, Option.Option<E>, R>,\n    that: LazyArg<STM.STM<A2, Option.Option<E2>, R2>>\n  ): STM.STM<A2 | A, Option.Option<E2 | E>, R2 | R> =>\n    core.catchAll(\n      self,\n      Option.match({\n        onNone: that,\n        onSome: (e) => core.fail(Option.some<E | E2>(e))\n      })\n    )\n)\n\n/** @internal */\nexport const orElseSucceed = dual<\n  <A2>(value: LazyArg<A2>) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<A2 | A, never, R>,\n  <A, E, R, A2>(self: STM.STM<A, E, R>, value: LazyArg<A2>) => STM.STM<A2 | A, never, R>\n>(\n  2,\n  <A, E, R, A2>(self: STM.STM<A, E, R>, value: LazyArg<A2>): STM.STM<A2 | A, never, R> =>\n    orElse(self, () => core.sync(value))\n)\n\n/** @internal */\nexport const provideContext = dual<\n  <R>(env: Context.Context<R>) => <A, E>(self: STM.STM<A, E, R>) => STM.STM<A, E>,\n  <A, E, R>(self: STM.STM<A, E, R>, env: Context.Context<R>) => STM.STM<A, E>\n>(2, (self, env) => core.mapInputContext(self, (_: Context.Context<never>) => env))\n\n/** @internal */\nexport const provideSomeContext = dual<\n  <R>(context: Context.Context<R>) => <R1, E, A>(self: STM.STM<A, E, R1>) => STM.STM<A, E, Exclude<R1, R>>,\n  <R, R1, E, A>(self: STM.STM<A, E, R1>, context: Context.Context<R>) => STM.STM<A, E, Exclude<R1, R>>\n>(2, <R, R1, E, A>(\n  self: STM.STM<A, E, R1>,\n  context: Context.Context<R>\n): STM.STM<A, E, Exclude<R1, R>> =>\n  core.mapInputContext(\n    self,\n    (parent: Context.Context<Exclude<R1, R>>): Context.Context<R1> => Context.merge(parent, context) as any\n  ))\n\n/** @internal */\nexport const provideService = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    resource: Types.NoInfer<S>\n  ) => <A, E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A, E, Exclude<R, I>>,\n  <A, E, R, I, S>(\n    self: STM.STM<A, E, R>,\n    tag: Context.Tag<I, S>,\n    resource: Types.NoInfer<S>\n  ) => STM.STM<A, E, Exclude<R, I>>\n>(3, (self, tag, resource) => provideServiceSTM(self, tag, core.succeed(resource)))\n\n/** @internal */\nexport const provideServiceSTM = dual<\n  <I, S, E1, R1>(\n    tag: Context.Tag<I, S>,\n    stm: STM.STM<Types.NoInfer<S>, E1, R1>\n  ) => <A, E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A, E1 | E, R1 | Exclude<R, I>>,\n  <A, E, R, I, S, E1, R1>(\n    self: STM.STM<A, E, R>,\n    tag: Context.Tag<I, S>,\n    stm: STM.STM<Types.NoInfer<S>, E1, R1>\n  ) => STM.STM<A, E1 | E, R1 | Exclude<R, I>>\n>(3, <A, E, R, I, S, E1, R1>(\n  self: STM.STM<A, E, R>,\n  tag: Context.Tag<I, S>,\n  stm: STM.STM<Types.NoInfer<S>, E1, R1>\n): STM.STM<A, E1 | E, R1 | Exclude<R, I>> =>\n  core.contextWithSTM((env: Context.Context<R1 | Exclude<R, I>>) =>\n    core.flatMap(\n      stm,\n      (service) =>\n        provideContext(\n          self,\n          Context.add(env, tag, service) as Context.Context<R | R1>\n        )\n    )\n  ))\n\n/** @internal */\nexport const reduce = dual<\n  <S, A, E, R>(zero: S, f: (s: S, a: A) => STM.STM<S, E, R>) => (iterable: Iterable<A>) => STM.STM<S, E, R>,\n  <S, A, E, R>(iterable: Iterable<A>, zero: S, f: (s: S, a: A) => STM.STM<S, E, R>) => STM.STM<S, E, R>\n>(\n  3,\n  <S, A, R, E>(iterable: Iterable<A>, zero: S, f: (s: S, a: A) => STM.STM<S, E, R>): STM.STM<S, E, R> =>\n    suspend(() =>\n      Array.from(iterable).reduce(\n        (acc, curr) => pipe(acc, core.flatMap((s) => f(s, curr))),\n        core.succeed(zero) as STM.STM<S, E, R>\n      )\n    )\n)\n\n/** @internal */\nexport const reduceAll = dual<\n  <A, E2, R2>(\n    initial: STM.STM<A, E2, R2>,\n    f: (x: A, y: A) => A\n  ) => <E, R>(\n    iterable: Iterable<STM.STM<A, E, R>>\n  ) => STM.STM<A, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    iterable: Iterable<STM.STM<A, E, R>>,\n    initial: STM.STM<A, E2, R2>,\n    f: (x: A, y: A) => A\n  ) => STM.STM<A, E2 | E, R2 | R>\n>(3, <A, E, R, E2, R2>(\n  iterable: Iterable<STM.STM<A, E, R>>,\n  initial: STM.STM<A, E2, R2>,\n  f: (x: A, y: A) => A\n): STM.STM<A, E2 | E, R2 | R> =>\n  suspend(() =>\n    Array.from(iterable).reduce(\n      (acc, curr) => pipe(acc, core.zipWith(curr, f)),\n      initial as STM.STM<A, E | E2, R | R2>\n    )\n  ))\n\n/** @internal */\nexport const reduceRight = dual<\n  <S, A, R, E>(zero: S, f: (s: S, a: A) => STM.STM<S, E, R>) => (iterable: Iterable<A>) => STM.STM<S, E, R>,\n  <S, A, R, E>(iterable: Iterable<A>, zero: S, f: (s: S, a: A) => STM.STM<S, E, R>) => STM.STM<S, E, R>\n>(\n  3,\n  <S, A, R, E>(iterable: Iterable<A>, zero: S, f: (s: S, a: A) => STM.STM<S, E, R>): STM.STM<S, E, R> =>\n    suspend(() =>\n      Array.from(iterable).reduceRight(\n        (acc, curr) => pipe(acc, core.flatMap((s) => f(s, curr))),\n        core.succeed(zero) as STM.STM<S, E, R>\n      )\n    )\n)\n\n/** @internal */\nexport const refineOrDie = dual<\n  <E, E2>(pf: (error: E) => Option.Option<E2>) => <A, R>(self: STM.STM<A, E, R>) => STM.STM<A, E2, R>,\n  <A, E, R, E2>(self: STM.STM<A, E, R>, pf: (error: E) => Option.Option<E2>) => STM.STM<A, E2, R>\n>(2, (self, pf) => refineOrDieWith(self, pf, identity))\n\n/** @internal */\nexport const refineOrDieWith = dual<\n  <E, E2>(\n    pf: (error: E) => Option.Option<E2>,\n    f: (error: E) => unknown\n  ) => <A, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A, E2, R>,\n  <A, E, R, E2>(\n    self: STM.STM<A, E, R>,\n    pf: (error: E) => Option.Option<E2>,\n    f: (error: E) => unknown\n  ) => STM.STM<A, E2, R>\n>(3, (self, pf, f) =>\n  core.catchAll(\n    self,\n    (e) =>\n      Option.match(pf(e), {\n        onNone: () => core.die(f(e)),\n        onSome: core.fail\n      })\n  ))\n\n/** @internal */\nexport const reject = dual<\n  <A, E2>(pf: (a: A) => Option.Option<E2>) => <E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E2 | E, R>,\n  <A, E, R, E2>(self: STM.STM<A, E, R>, pf: (a: A) => Option.Option<E2>) => STM.STM<A, E2 | E, R>\n>(2, (self, pf) =>\n  rejectSTM(\n    self,\n    (a) => Option.map(pf(a), core.fail)\n  ))\n\n/** @internal */\nexport const rejectSTM = dual<\n  <A, E2, R2>(\n    pf: (a: A) => Option.Option<STM.STM<E2, E2, R2>>\n  ) => <E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    self: STM.STM<A, E, R>,\n    pf: (a: A) => Option.Option<STM.STM<E2, E2, R2>>\n  ) => STM.STM<A, E2 | E, R2 | R>\n>(2, (self, pf) =>\n  core.flatMap(self, (a) =>\n    Option.match(pf(a), {\n      onNone: () => core.succeed(a),\n      onSome: core.flatMap(core.fail)\n    })))\n\n/** @internal */\nexport const repeatUntil = dual<\n  <A>(predicate: Predicate<A>) => <E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E, R>,\n  <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>) => STM.STM<A, E, R>\n>(2, (self, predicate) => repeatUntilLoop(self, predicate))\n\nconst repeatUntilLoop = <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>): STM.STM<A, E, R> =>\n  core.flatMap(self, (a) =>\n    predicate(a) ?\n      core.succeed(a) :\n      repeatUntilLoop(self, predicate))\n\n/** @internal */\nexport const repeatWhile = dual<\n  <A>(predicate: Predicate<A>) => <E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E, R>,\n  <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>) => STM.STM<A, E, R>\n>(2, (self, predicate) => repeatWhileLoop(self, predicate))\n\nconst repeatWhileLoop = <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>): STM.STM<A, E, R> =>\n  core.flatMap(self, (a) =>\n    predicate(a) ?\n      repeatWhileLoop(self, predicate) :\n      core.succeed(a))\n\n/** @internal */\nexport const replicate = dual<\n  (n: number) => <A, E, R>(self: STM.STM<A, E, R>) => Array<STM.STM<A, E, R>>,\n  <A, E, R>(self: STM.STM<A, E, R>, n: number) => Array<STM.STM<A, E, R>>\n>(2, (self, n) => Array.from({ length: n }, () => self))\n\n/** @internal */\nexport const replicateSTM = dual<\n  (n: number) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<Array<A>, E, R>,\n  <A, E, R>(self: STM.STM<A, E, R>, n: number) => STM.STM<Array<A>, E, R>\n>(2, (self, n) => all(replicate(self, n)))\n\n/** @internal */\nexport const replicateSTMDiscard = dual<\n  (n: number) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<void, E, R>,\n  <A, E, R>(self: STM.STM<A, E, R>, n: number) => STM.STM<void, E, R>\n>(2, (self, n) => all(replicate(self, n), { discard: true }))\n\n/** @internal */\nexport const retryUntil = dual<\n  {\n    <A, B extends A>(refinement: Refinement<Types.NoInfer<A>, B>): <E, R>(self: STM.STM<A, E, R>) => STM.STM<B, E, R>\n    <A>(predicate: Predicate<A>): <E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E, R>\n  },\n  {\n    <A, E, R, B extends A>(self: STM.STM<A, E, R>, refinement: Refinement<A, B>): STM.STM<B, E, R>\n    <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>): STM.STM<A, E, R>\n  }\n>(\n  2,\n  <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>) =>\n    core.matchSTM(self, { onFailure: core.fail, onSuccess: (a) => predicate(a) ? core.succeed(a) : core.retry })\n)\n\n/** @internal */\nexport const retryWhile = dual<\n  <A>(predicate: Predicate<A>) => <E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E, R>,\n  <A, E, R>(self: STM.STM<A, E, R>, predicate: Predicate<A>) => STM.STM<A, E, R>\n>(\n  2,\n  (self, predicate) =>\n    core.matchSTM(self, { onFailure: core.fail, onSuccess: (a) => !predicate(a) ? core.succeed(a) : core.retry })\n)\n\n/** @internal */\nexport const partition = dual<\n  <A, A2, E, R>(\n    f: (a: A) => STM.STM<A2, E, R>\n  ) => (\n    elements: Iterable<A>\n  ) => STM.STM<[excluded: Array<E>, satisfying: Array<A2>], never, R>,\n  <A, A2, E, R>(\n    elements: Iterable<A>,\n    f: (a: A) => STM.STM<A2, E, R>\n  ) => STM.STM<[excluded: Array<E>, satisfying: Array<A2>], never, R>\n>(2, (elements, f) =>\n  pipe(\n    forEach(elements, (a) => either(f(a))),\n    core.map((as) => effectCore.partitionMap(as, identity))\n  ))\n\n/** @internal */\nexport const some = <A, E, R>(self: STM.STM<Option.Option<A>, E, R>): STM.STM<A, Option.Option<E>, R> =>\n  core.matchSTM(self, {\n    onFailure: (e) => core.fail(Option.some(e)),\n    onSuccess: Option.match({\n      onNone: () => core.fail(Option.none()),\n      onSome: core.succeed\n    })\n  })\n\n/* @internal */\nexport const all = ((\n  input: Iterable<STM.All.STMAny> | Record<string, STM.All.STMAny>,\n  options?: STM.All.Options\n): STM.STM<any, any, any> => {\n  if (Symbol.iterator in input) {\n    return forEach(input, identity, options as any)\n  } else if (options?.discard) {\n    return forEach(Object.values(input), identity, options as any)\n  }\n\n  return core.map(\n    forEach(\n      Object.entries(input),\n      ([_, e]) => core.map(e, (a) => [_, a] as const)\n    ),\n    (values) => {\n      const res = {}\n      for (const [k, v] of values) {\n        ;(res as any)[k] = v\n      }\n      return res\n    }\n  )\n}) as STM.All.Signature\n\n/** @internal */\nexport const succeedNone: STM.STM<Option.Option<never>> = core.succeed(Option.none())\n\n/** @internal */\nexport const succeedSome = <A>(value: A): STM.STM<Option.Option<A>> => core.succeed(Option.some(value))\n\n/** @internal */\nexport const summarized = dual<\n  <A2, E2, R2, A3>(\n    summary: STM.STM<A2, E2, R2>,\n    f: (before: A2, after: A2) => A3\n  ) => <A, E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<[A3, A], E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2, A3>(\n    self: STM.STM<A, E, R>,\n    summary: STM.STM<A2, E2, R2>,\n    f: (before: A2, after: A2) => A3\n  ) => STM.STM<[A3, A], E2 | E, R2 | R>\n>(3, (self, summary, f) =>\n  core.flatMap(summary, (start) =>\n    core.flatMap(self, (value) =>\n      core.map(\n        summary,\n        (end) => [f(start, end), value]\n      ))))\n\n/** @internal */\nexport const suspend = <A, E, R>(evaluate: LazyArg<STM.STM<A, E, R>>): STM.STM<A, E, R> => flatten(core.sync(evaluate))\n\n/** @internal */\nexport const tap: {\n  <A, X, E2, R2>(f: (a: A) => STM.STM<X, E2, R2>): <E, R>(self: STM.STM<A, E, R>) => STM.STM<A, E2 | E, R2 | R>\n  <A, E, R, X, E2, R2>(self: STM.STM<A, E, R>, f: (a: A) => STM.STM<X, E2, R2>): STM.STM<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, X, E2, R2>(self: STM.STM<A, E, R>, f: (a: A) => STM.STM<X, E2, R2>): STM.STM<A, E | E2, R | R2> =>\n    core.flatMap(self, (a) => as(f(a), a))\n)\n\n/** @internal */\nexport const tapBoth = dual<\n  <XE extends E, A2, E2, R2, XA extends A, A3, E3, R3, A, E>(\n    options: {\n      readonly onFailure: (error: XE) => STM.STM<A2, E2, R2>\n      readonly onSuccess: (value: XA) => STM.STM<A3, E3, R3>\n    }\n  ) => <R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<A, E | E2 | E3, R2 | R3 | R>,\n  <A, E, R, XE extends E, A2, E2, R2, XA extends A, A3, E3, R3>(\n    self: STM.STM<A, E, R>,\n    options: {\n      readonly onFailure: (error: XE) => STM.STM<A2, E2, R2>\n      readonly onSuccess: (value: XA) => STM.STM<A3, E3, R3>\n    }\n  ) => STM.STM<A, E | E2 | E3, R2 | R3 | R>\n>(2, (self, { onFailure, onSuccess }) =>\n  core.matchSTM(self, {\n    onFailure: (e) => pipe(onFailure(e as any), core.zipRight(core.fail(e))),\n    onSuccess: (a) => pipe(onSuccess(a as any), as(a))\n  }))\n\n/** @internal */\nexport const tapError: {\n  <E, X, E2, R2>(\n    f: (error: Types.NoInfer<E>) => STM.STM<X, E2, R2>\n  ): <A, R>(self: STM.STM<A, E, R>) => STM.STM<A, E | E2, R2 | R>\n  <A, E, R, X, E2, R2>(self: STM.STM<A, E, R>, f: (error: E) => STM.STM<X, E2, R2>): STM.STM<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, X, E2, R2>(self: STM.STM<A, E, R>, f: (error: E) => STM.STM<X, E2, R2>): STM.STM<A, E | E2, R | R2> =>\n    core.matchSTM(self, {\n      onFailure: (e) => core.zipRight(f(e), core.fail(e)),\n      onSuccess: core.succeed\n    })\n)\n\n/** @internal */\nexport const try_: {\n  <A, E>(options: {\n    readonly try: LazyArg<A>\n    readonly catch: (u: unknown) => E\n  }): STM.STM<A, E>\n  <A>(try_: LazyArg<A>): STM.STM<A, unknown>\n} = <A, E>(\n  arg: LazyArg<A> | {\n    readonly try: LazyArg<A>\n    readonly catch: (u: unknown) => E\n  }\n) => {\n  const evaluate = typeof arg === \"function\" ? arg : arg.try\n  return suspend(() => {\n    try {\n      return core.succeed(evaluate())\n    } catch (error) {\n      return core.fail(\"catch\" in arg ? arg.catch(error) : error)\n    }\n  })\n}\n\n/** @internal */\nconst void_: STM.STM<void> = core.succeed(void 0)\nexport {\n  /** @internal */\n  void_ as void\n}\n\n/** @internal */\nexport const unless = dual<\n  (predicate: LazyArg<boolean>) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<Option.Option<A>, E, R>,\n  <A, E, R>(self: STM.STM<A, E, R>, predicate: LazyArg<boolean>) => STM.STM<Option.Option<A>, E, R>\n>(2, (self, predicate) =>\n  suspend(\n    () => predicate() ? succeedNone : asSome(self)\n  ))\n\n/** @internal */\nexport const unlessSTM = dual<\n  <E2, R2>(\n    predicate: STM.STM<boolean, E2, R2>\n  ) => <A, E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<Option.Option<A>, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    self: STM.STM<A, E, R>,\n    predicate: STM.STM<boolean, E2, R2>\n  ) => STM.STM<Option.Option<A>, E2 | E, R2 | R>\n>(2, (self, predicate) =>\n  core.flatMap(\n    predicate,\n    (bool) => bool ? succeedNone : asSome(self)\n  ))\n\n/** @internal */\nexport const unsome = <A, E, R>(self: STM.STM<A, Option.Option<E>, R>): STM.STM<Option.Option<A>, E, R> =>\n  core.matchSTM(self, {\n    onFailure: Option.match({\n      onNone: () => core.succeed(Option.none()),\n      onSome: core.fail\n    }),\n    onSuccess: (a) => core.succeed(Option.some(a))\n  })\n\n/** @internal */\nexport const validateAll = dual<\n  <A, B, E, R>(\n    f: (a: A) => STM.STM<B, E, R>\n  ) => (\n    elements: Iterable<A>\n  ) => STM.STM<Array<B>, RA.NonEmptyArray<E>, R>,\n  <A, B, E, R>(\n    elements: Iterable<A>,\n    f: (a: A) => STM.STM<B, E, R>\n  ) => STM.STM<Array<B>, RA.NonEmptyArray<E>, R>\n>(\n  2,\n  (elements, f) =>\n    core.flatMap(partition(elements, f), ([errors, values]) =>\n      RA.isNonEmptyArray(errors) ?\n        core.fail(errors) :\n        core.succeed(values))\n)\n\n/** @internal */\nexport const validateFirst = dual<\n  <A, B, E, R>(f: (a: A) => STM.STM<B, E, R>) => (elements: Iterable<A>) => STM.STM<B, Array<E>, R>,\n  <A, B, E, R>(elements: Iterable<A>, f: (a: A) => STM.STM<B, E, R>) => STM.STM<B, Array<E>, R>\n>(2, (elements, f) => flip(forEach(elements, (a) => flip(f(a)))))\n\n/** @internal */\nexport const when = dual<\n  (predicate: LazyArg<boolean>) => <A, E, R>(self: STM.STM<A, E, R>) => STM.STM<Option.Option<A>, E, R>,\n  <A, E, R>(self: STM.STM<A, E, R>, predicate: LazyArg<boolean>) => STM.STM<Option.Option<A>, E, R>\n>(2, (self, predicate) =>\n  suspend(\n    () => predicate() ? asSome(self) : succeedNone\n  ))\n\n/** @internal */\nexport const whenSTM = dual<\n  <E2, R2>(\n    predicate: STM.STM<boolean, E2, R2>\n  ) => <A, E, R>(\n    self: STM.STM<A, E, R>\n  ) => STM.STM<Option.Option<A>, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    self: STM.STM<A, E, R>,\n    predicate: STM.STM<boolean, E2, R2>\n  ) => STM.STM<Option.Option<A>, E2 | E, R2 | R>\n>(2, (self, predicate) =>\n  core.flatMap(\n    predicate,\n    (bool) => bool ? asSome(self) : succeedNone\n  ))\n"
  },
  {
    "path": "packages/effect/src/internal/stm/stmState.ts",
    "content": "import * as Equal from \"../../Equal.js\"\nimport * as Exit from \"../../Exit.js\"\nimport { pipe } from \"../../Function.js\"\nimport * as Hash from \"../../Hash.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport * as OpCodes from \"./opCodes/stmState.js\"\nimport * as TExitOpCodes from \"./opCodes/tExit.js\"\nimport type * as TExit from \"./tExit.js\"\n\n/** @internal */\nconst STMStateSymbolKey = \"effect/STM/State\"\n\n/** @internal */\nexport const STMStateTypeId = Symbol.for(STMStateSymbolKey)\n\n/** @internal */\nexport type STMStateTypeId = typeof STMStateTypeId\n\n/** @internal */\nexport type STMState<A, E = never> = Done<A, E> | Interrupted | Running\n\n/** @internal */\nexport interface Done<out A, out E = never> extends Equal.Equal {\n  readonly [STMStateTypeId]: STMStateTypeId\n  readonly _tag: OpCodes.OP_DONE\n  readonly exit: Exit.Exit<A, E>\n}\n\n/** @internal */\nexport interface Interrupted extends Equal.Equal {\n  readonly [STMStateTypeId]: STMStateTypeId\n  readonly _tag: OpCodes.OP_INTERRUPTED\n}\n\n/** @internal */\nexport interface Running extends Equal.Equal {\n  readonly [STMStateTypeId]: STMStateTypeId\n  readonly _tag: OpCodes.OP_RUNNING\n}\n\n/** @internal */\nexport const isSTMState = (u: unknown): u is STMState<unknown, unknown> => hasProperty(u, STMStateTypeId)\n\n/** @internal */\nexport const isRunning = <A, E>(self: STMState<A, E>): self is Running => {\n  return self._tag === OpCodes.OP_RUNNING\n}\n\n/** @internal */\nexport const isDone = <A, E>(self: STMState<A, E>): self is Done<A, E> => {\n  return self._tag === OpCodes.OP_DONE\n}\n\n/** @internal */\nexport const isInterrupted = <A, E>(self: STMState<A, E>): self is Interrupted => {\n  return self._tag === OpCodes.OP_INTERRUPTED\n}\n\n/** @internal */\nexport const done = <A, E>(exit: Exit.Exit<A, E>): STMState<A, E> => {\n  return {\n    [STMStateTypeId]: STMStateTypeId,\n    _tag: OpCodes.OP_DONE,\n    exit,\n    [Hash.symbol](): number {\n      return pipe(\n        Hash.hash(STMStateSymbolKey),\n        Hash.combine(Hash.hash(OpCodes.OP_DONE)),\n        Hash.combine(Hash.hash(exit)),\n        Hash.cached(this)\n      )\n    },\n    [Equal.symbol](that: unknown): boolean {\n      return isSTMState(that) && that._tag === OpCodes.OP_DONE && Equal.equals(exit, that.exit)\n    }\n  }\n}\n\nconst interruptedHash = pipe(\n  Hash.hash(STMStateSymbolKey),\n  Hash.combine(Hash.hash(OpCodes.OP_INTERRUPTED)),\n  Hash.combine(Hash.hash(\"interrupted\"))\n)\n\n/** @internal */\nexport const interrupted: STMState<never> = {\n  [STMStateTypeId]: STMStateTypeId,\n  _tag: OpCodes.OP_INTERRUPTED,\n  [Hash.symbol](): number {\n    return interruptedHash\n  },\n  [Equal.symbol](that: unknown): boolean {\n    return isSTMState(that) && that._tag === OpCodes.OP_INTERRUPTED\n  }\n}\n\nconst runningHash = pipe(\n  Hash.hash(STMStateSymbolKey),\n  Hash.combine(Hash.hash(OpCodes.OP_RUNNING)),\n  Hash.combine(Hash.hash(\"running\"))\n)\n\n/** @internal */\nexport const running: STMState<never> = {\n  [STMStateTypeId]: STMStateTypeId,\n  _tag: OpCodes.OP_RUNNING,\n  [Hash.symbol](): number {\n    return runningHash\n  },\n  [Equal.symbol](that: unknown): boolean {\n    return isSTMState(that) && that._tag === OpCodes.OP_RUNNING\n  }\n}\n\n/** @internal */\nexport const fromTExit = <A, E>(tExit: TExit.TExit<A, E>): STMState<A, E> => {\n  switch (tExit._tag) {\n    case TExitOpCodes.OP_FAIL: {\n      return done(Exit.fail(tExit.error))\n    }\n    case TExitOpCodes.OP_DIE: {\n      return done(Exit.die(tExit.defect))\n    }\n    case TExitOpCodes.OP_INTERRUPT: {\n      return done(Exit.interrupt(tExit.fiberId))\n    }\n    case TExitOpCodes.OP_SUCCEED: {\n      return done(Exit.succeed(tExit.value))\n    }\n    case TExitOpCodes.OP_RETRY: {\n      throw new Error(\n        \"BUG: STM.STMState.fromTExit - please report an issue at https://github.com/Effect-TS/effect/issues\"\n      )\n    }\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tArray.ts",
    "content": "import * as Equal from \"../../Equal.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport * as Order from \"../../Order.js\"\nimport type { Predicate } from \"../../Predicate.js\"\nimport type * as STM from \"../../STM.js\"\nimport type * as TArray from \"../../TArray.js\"\nimport type * as TRef from \"../../TRef.js\"\nimport * as core from \"./core.js\"\nimport * as stm from \"./stm.js\"\nimport * as tRef from \"./tRef.js\"\n\n/** @internal */\nconst TArraySymbolKey = \"effect/TArray\"\n\n/** @internal */\nexport const TArrayTypeId: TArray.TArrayTypeId = Symbol.for(TArraySymbolKey) as TArray.TArrayTypeId\n\nconst tArrayVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nexport class TArrayImpl<in out A> implements TArray.TArray<A> {\n  readonly [TArrayTypeId] = tArrayVariance\n  constructor(readonly chunk: Array<TRef.TRef<A>>) {}\n}\n\n/** @internal */\nexport const collectFirst = dual<\n  <A, B>(pf: (a: A) => Option.Option<B>) => (self: TArray.TArray<A>) => STM.STM<Option.Option<B>>,\n  <A, B>(self: TArray.TArray<A>, pf: (a: A) => Option.Option<B>) => STM.STM<Option.Option<B>>\n>(2, (self, pf) =>\n  collectFirstSTM(\n    self,\n    (a) => pipe(pf(a), Option.map(core.succeed))\n  ))\n\n/** @internal */\nexport const collectFirstSTM = dual<\n  <A, B, E, R>(\n    pf: (a: A) => Option.Option<STM.STM<B, E, R>>\n  ) => (\n    self: TArray.TArray<A>\n  ) => STM.STM<Option.Option<B>, E, R>,\n  <A, B, E, R>(\n    self: TArray.TArray<A>,\n    pf: (a: A) => Option.Option<STM.STM<B, E, R>>\n  ) => STM.STM<Option.Option<B>, E, R>\n>(\n  2,\n  <A, B, E, R>(self: TArray.TArray<A>, pf: (a: A) => Option.Option<STM.STM<B, E, R>>) =>\n    core.withSTMRuntime((runtime) => {\n      let index = 0\n      let result: Option.Option<STM.STM<B, E, R>> = Option.none()\n      while (Option.isNone(result) && index < self.chunk.length) {\n        const element = pipe(self.chunk[index], tRef.unsafeGet(runtime.journal))\n        const option = pf(element)\n        if (Option.isSome(option)) {\n          result = option\n        }\n        index = index + 1\n      }\n      return pipe(\n        result,\n        Option.match({\n          onNone: () => stm.succeedNone,\n          onSome: core.map(Option.some)\n        })\n      )\n    })\n)\n\n/** @internal */\nexport const contains = dual<\n  <A>(value: A) => (self: TArray.TArray<A>) => STM.STM<boolean>,\n  <A>(self: TArray.TArray<A>, value: A) => STM.STM<boolean>\n>(2, (self, value) => some(self, (a) => Equal.equals(a)(value)))\n\n/** @internal */\nexport const count = dual<\n  <A>(predicate: Predicate<A>) => (self: TArray.TArray<A>) => STM.STM<number>,\n  <A>(self: TArray.TArray<A>, predicate: Predicate<A>) => STM.STM<number>\n>(2, (self, predicate) =>\n  reduce(\n    self,\n    0,\n    (n, a) => predicate(a) ? n + 1 : n\n  ))\n\n/** @internal */\nexport const countSTM = dual<\n  <A, R, E>(predicate: (value: A) => STM.STM<boolean, E, R>) => (self: TArray.TArray<A>) => STM.STM<number, E, R>,\n  <A, R, E>(self: TArray.TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>) => STM.STM<number, E, R>\n>(2, (self, predicate) =>\n  reduceSTM(\n    self,\n    0,\n    (n, a) => core.map(predicate(a), (bool) => bool ? n + 1 : n)\n  ))\n\n/** @internal */\nexport const empty = <A>(): STM.STM<TArray.TArray<A>> => fromIterable<A>([])\n\n/** @internal */\nexport const every = dual<\n  <A>(predicate: Predicate<A>) => (self: TArray.TArray<A>) => STM.STM<boolean>,\n  <A>(self: TArray.TArray<A>, predicate: Predicate<A>) => STM.STM<boolean>\n>(2, (self, predicate) => stm.negate(some(self, (a) => !predicate(a))))\n\n/** @internal */\nexport const everySTM = dual<\n  <A, R, E>(predicate: (value: A) => STM.STM<boolean, E, R>) => (self: TArray.TArray<A>) => STM.STM<boolean, E, R>,\n  <A, R, E>(self: TArray.TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>) => STM.STM<boolean, E, R>\n>(2, (self, predicate) =>\n  core.map(\n    countSTM(self, predicate),\n    (count) => count === self.chunk.length\n  ))\n\n/** @internal */\nexport const findFirst = dual<\n  <A>(predicate: Predicate<A>) => (self: TArray.TArray<A>) => STM.STM<Option.Option<A>>,\n  <A>(self: TArray.TArray<A>, predicate: Predicate<A>) => STM.STM<Option.Option<A>>\n>(2, (self, predicate) =>\n  collectFirst(self, (a) =>\n    predicate(a)\n      ? Option.some(a)\n      : Option.none()))\n\n/** @internal */\nexport const findFirstIndex = dual<\n  <A>(value: A) => (self: TArray.TArray<A>) => STM.STM<Option.Option<number>>,\n  <A>(self: TArray.TArray<A>, value: A) => STM.STM<Option.Option<number>>\n>(2, (self, value) => findFirstIndexFrom(self, value, 0))\n\n/** @internal */\nexport const findFirstIndexFrom = dual<\n  <A>(value: A, from: number) => (self: TArray.TArray<A>) => STM.STM<Option.Option<number>>,\n  <A>(self: TArray.TArray<A>, value: A, from: number) => STM.STM<Option.Option<number>>\n>(3, (self, value, from) =>\n  findFirstIndexWhereFrom(\n    self,\n    (a) => Equal.equals(a)(value),\n    from\n  ))\n\n/** @internal */\nexport const findFirstIndexWhere = dual<\n  <A>(predicate: Predicate<A>) => (self: TArray.TArray<A>) => STM.STM<Option.Option<number>>,\n  <A>(self: TArray.TArray<A>, predicate: Predicate<A>) => STM.STM<Option.Option<number>>\n>(2, (self, predicate) => findFirstIndexWhereFrom(self, predicate, 0))\n\n/** @internal */\nexport const findFirstIndexWhereFrom = dual<\n  <A>(\n    predicate: Predicate<A>,\n    from: number\n  ) => (self: TArray.TArray<A>) => STM.STM<Option.Option<number>>,\n  <A>(self: TArray.TArray<A>, predicate: Predicate<A>, from: number) => STM.STM<Option.Option<number>>\n>(3, (self, predicate, from) => {\n  if (from < 0) {\n    return stm.succeedNone\n  }\n  return core.effect<never, Option.Option<number>>((journal) => {\n    let index: number = from\n    let found = false\n    while (!found && index < self.chunk.length) {\n      const element = tRef.unsafeGet(self.chunk[index], journal)\n      found = predicate(element)\n      index = index + 1\n    }\n    if (found) {\n      return Option.some(index - 1)\n    }\n    return Option.none()\n  })\n})\n\n/** @internal */\nexport const findFirstIndexWhereSTM = dual<\n  <A, R, E>(\n    predicate: (value: A) => STM.STM<boolean, E, R>\n  ) => (self: TArray.TArray<A>) => STM.STM<Option.Option<number>, E, R>,\n  <A, R, E>(\n    self: TArray.TArray<A>,\n    predicate: (value: A) => STM.STM<boolean, E, R>\n  ) => STM.STM<Option.Option<number>, E, R>\n>(2, (self, predicate) => findFirstIndexWhereFromSTM(self, predicate, 0))\n\n/** @internal */\nexport const findFirstIndexWhereFromSTM = dual<\n  <A, R, E>(\n    predicate: (value: A) => STM.STM<boolean, E, R>,\n    from: number\n  ) => (self: TArray.TArray<A>) => STM.STM<Option.Option<number>, E, R>,\n  <A, R, E>(\n    self: TArray.TArray<A>,\n    predicate: (value: A) => STM.STM<boolean, E, R>,\n    from: number\n  ) => STM.STM<Option.Option<number>, E, R>\n>(3, <A, R, E>(\n  self: TArray.TArray<A>,\n  predicate: (value: A) => STM.STM<boolean, E, R>,\n  from: number\n) => {\n  const forIndex = (index: number): STM.STM<Option.Option<number>, E, R> =>\n    index < self.chunk.length\n      ? pipe(\n        tRef.get(self.chunk[index]),\n        core.flatMap(predicate),\n        core.flatMap((bool) =>\n          bool ?\n            core.succeed(Option.some(index)) :\n            forIndex(index + 1)\n        )\n      )\n      : stm.succeedNone\n  return from < 0\n    ? stm.succeedNone\n    : forIndex(from)\n})\n\n/** @internal */\nexport const findFirstSTM = dual<\n  <A, R, E>(\n    predicate: (value: A) => STM.STM<boolean, E, R>\n  ) => (\n    self: TArray.TArray<A>\n  ) => STM.STM<Option.Option<A>, E, R>,\n  <A, R, E>(\n    self: TArray.TArray<A>,\n    predicate: (value: A) => STM.STM<boolean, E, R>\n  ) => STM.STM<Option.Option<A>, E, R>\n>(2, <A, R, E>(self: TArray.TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>) => {\n  const init = [Option.none() as Option.Option<A>, 0 as number] as const\n  const cont = (state: readonly [Option.Option<A>, number]) =>\n    Option.isNone(state[0]) && state[1] < self.chunk.length - 1\n  return core.map(\n    stm.iterate(init, {\n      while: cont,\n      body: (state) => {\n        const index = state[1]\n        return pipe(\n          tRef.get(self.chunk[index]),\n          core.flatMap((value) =>\n            core.map(\n              predicate(value),\n              (bool) => [bool ? Option.some(value) : Option.none(), index + 1] as const\n            )\n          )\n        )\n      }\n    }),\n    (state) => state[0]\n  )\n})\n\n/** @internal */\nexport const findLast = dual<\n  <A>(predicate: Predicate<A>) => (self: TArray.TArray<A>) => STM.STM<Option.Option<A>>,\n  <A>(self: TArray.TArray<A>, predicate: Predicate<A>) => STM.STM<Option.Option<A>>\n>(2, <A>(self: TArray.TArray<A>, predicate: Predicate<A>) =>\n  core.effect<never, Option.Option<A>>((journal) => {\n    let index = self.chunk.length - 1\n    let result: Option.Option<A> = Option.none()\n    while (Option.isNone(result) && index >= 0) {\n      const element = tRef.unsafeGet(self.chunk[index], journal)\n      if (predicate(element)) {\n        result = Option.some(element)\n      }\n      index = index - 1\n    }\n    return result\n  }))\n\n/** @internal */\nexport const findLastIndex = dual<\n  <A>(value: A) => (self: TArray.TArray<A>) => STM.STM<Option.Option<number>>,\n  <A>(self: TArray.TArray<A>, value: A) => STM.STM<Option.Option<number>>\n>(2, (self, value) => findLastIndexFrom(self, value, self.chunk.length - 1))\n\n/** @internal */\nexport const findLastIndexFrom = dual<\n  <A>(value: A, end: number) => (self: TArray.TArray<A>) => STM.STM<Option.Option<number>>,\n  <A>(self: TArray.TArray<A>, value: A, end: number) => STM.STM<Option.Option<number>>\n>(3, (self, value, end) => {\n  if (end >= self.chunk.length) {\n    return stm.succeedNone\n  }\n  return core.effect<never, Option.Option<number>>((journal) => {\n    let index: number = end\n    let found = false\n    while (!found && index >= 0) {\n      const element = tRef.unsafeGet(self.chunk[index], journal)\n      found = Equal.equals(element)(value)\n      index = index - 1\n    }\n    if (found) {\n      return Option.some(index + 1)\n    }\n    return Option.none()\n  })\n})\n\n/** @internal */\nexport const findLastSTM = dual<\n  <A, R, E>(\n    predicate: (value: A) => STM.STM<boolean, E, R>\n  ) => (self: TArray.TArray<A>) => STM.STM<Option.Option<A>, E, R>,\n  <A, R, E>(\n    self: TArray.TArray<A>,\n    predicate: (value: A) => STM.STM<boolean, E, R>\n  ) => STM.STM<Option.Option<A>, E, R>\n>(2, <A, R, E>(self: TArray.TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>) => {\n  const init = [Option.none() as Option.Option<A>, self.chunk.length - 1] as const\n  const cont = (state: readonly [Option.Option<A>, number]) => Option.isNone(state[0]) && state[1] >= 0\n  return core.map(\n    stm.iterate(init, {\n      while: cont,\n      body: (state) => {\n        const index = state[1]\n        return pipe(\n          tRef.get(self.chunk[index]),\n          core.flatMap((value) =>\n            core.map(\n              predicate(value),\n              (bool) => [bool ? Option.some(value) : Option.none(), index - 1] as const\n            )\n          )\n        )\n      }\n    }),\n    (state) => state[0]\n  )\n})\n\n/** @internal */\nexport const forEach = dual<\n  <A, R, E>(f: (value: A) => STM.STM<void, E, R>) => (self: TArray.TArray<A>) => STM.STM<void, E, R>,\n  <A, R, E>(self: TArray.TArray<A>, f: (value: A) => STM.STM<void, E, R>) => STM.STM<void, E, R>\n>(2, (self, f) => reduceSTM(self, void 0 as void, (_, a) => f(a)))\n\n/** @internal */\nexport const fromIterable = <A>(iterable: Iterable<A>): STM.STM<TArray.TArray<A>> =>\n  core.map(\n    stm.forEach(iterable, tRef.make),\n    (chunk) => new TArrayImpl(chunk)\n  )\n\n/** @internal */\nexport const get = dual<\n  (index: number) => <A>(self: TArray.TArray<A>) => STM.STM<A>,\n  <A>(self: TArray.TArray<A>, index: number) => STM.STM<A>\n>(2, (self, index) => {\n  if (index < 0 || index >= self.chunk.length) {\n    return core.dieMessage(\"Index out of bounds\")\n  }\n  return tRef.get(self.chunk[index])\n})\n\n/** @internal */\nexport const headOption = <A>(self: TArray.TArray<A>): STM.STM<Option.Option<A>> =>\n  self.chunk.length === 0 ?\n    core.succeed(Option.none()) :\n    core.map(tRef.get(self.chunk[0]), Option.some)\n\n/** @internal */\nexport const lastOption = <A>(self: TArray.TArray<A>): STM.STM<Option.Option<A>> =>\n  self.chunk.length === 0 ?\n    stm.succeedNone :\n    core.map(tRef.get(self.chunk[self.chunk.length - 1]), Option.some)\n\n/** @internal */\nexport const make = <Elements extends [any, ...Array<any>]>(\n  ...elements: Elements\n): STM.STM<TArray.TArray<Elements[number]>> => fromIterable(elements)\n\n/** @internal */\nexport const maxOption = dual<\n  <A>(order: Order.Order<A>) => (self: TArray.TArray<A>) => STM.STM<Option.Option<A>>,\n  <A>(self: TArray.TArray<A>, order: Order.Order<A>) => STM.STM<Option.Option<A>>\n>(2, (self, order) => {\n  const greaterThan = Order.greaterThan(order)\n  return reduceOption(self, (acc, curr) => greaterThan(acc)(curr) ? curr : acc)\n})\n\n/** @internal */\nexport const minOption = dual<\n  <A>(order: Order.Order<A>) => (self: TArray.TArray<A>) => STM.STM<Option.Option<A>>,\n  <A>(self: TArray.TArray<A>, order: Order.Order<A>) => STM.STM<Option.Option<A>>\n>(2, (self, order) => {\n  const lessThan = Order.lessThan(order)\n  return reduceOption(self, (acc, curr) => lessThan(acc)(curr) ? curr : acc)\n})\n\n/** @internal */\nexport const reduce = dual<\n  <Z, A>(zero: Z, f: (accumulator: Z, current: A) => Z) => (self: TArray.TArray<A>) => STM.STM<Z>,\n  <Z, A>(self: TArray.TArray<A>, zero: Z, f: (accumulator: Z, current: A) => Z) => STM.STM<Z>\n>(\n  3,\n  <Z, A>(self: TArray.TArray<A>, zero: Z, f: (accumulator: Z, current: A) => Z) =>\n    core.effect<never, Z>((journal) => {\n      let index = 0\n      let result = zero\n      while (index < self.chunk.length) {\n        const element = tRef.unsafeGet(self.chunk[index], journal)\n        result = f(result, element)\n        index = index + 1\n      }\n      return result\n    })\n)\n\n/** @internal */\nexport const reduceOption = dual<\n  <A>(f: (x: A, y: A) => A) => (self: TArray.TArray<A>) => STM.STM<Option.Option<A>>,\n  <A>(self: TArray.TArray<A>, f: (x: A, y: A) => A) => STM.STM<Option.Option<A>>\n>(\n  2,\n  <A>(self: TArray.TArray<A>, f: (x: A, y: A) => A) =>\n    core.effect<never, Option.Option<A>>((journal) => {\n      let index = 0\n      let result: A | undefined = undefined\n      while (index < self.chunk.length) {\n        const element = tRef.unsafeGet(self.chunk[index], journal)\n        result = result === undefined ? element : f(result, element)\n        index = index + 1\n      }\n      return Option.fromNullable(result)\n    })\n)\n\n/** @internal */\nexport const reduceOptionSTM = dual<\n  <A, R, E>(f: (x: A, y: A) => STM.STM<A, E, R>) => (self: TArray.TArray<A>) => STM.STM<Option.Option<A>, E, R>,\n  <A, R, E>(self: TArray.TArray<A>, f: (x: A, y: A) => STM.STM<A, E, R>) => STM.STM<Option.Option<A>, E, R>\n>(\n  2,\n  <A, R, E>(self: TArray.TArray<A>, f: (x: A, y: A) => STM.STM<A, E, R>) =>\n    reduceSTM(self, Option.none<A>(), (acc, curr) =>\n      Option.isSome(acc)\n        ? core.map(f(acc.value, curr), Option.some)\n        : stm.succeedSome(curr))\n)\n\n/** @internal */\nexport const reduceSTM = dual<\n  <Z, A, R, E>(\n    zero: Z,\n    f: (accumulator: Z, current: A) => STM.STM<Z, E, R>\n  ) => (self: TArray.TArray<A>) => STM.STM<Z, E, R>,\n  <Z, A, R, E>(\n    self: TArray.TArray<A>,\n    zero: Z,\n    f: (accumulator: Z, current: A) => STM.STM<Z, E, R>\n  ) => STM.STM<Z, E, R>\n>(3, (self, zero, f) =>\n  core.flatMap(\n    toArray(self),\n    stm.reduce(zero, f)\n  ))\n\n/** @internal */\nexport const size = <A>(self: TArray.TArray<A>): number => self.chunk.length\n\n/** @internal */\nexport const some = dual<\n  <A>(predicate: Predicate<A>) => (self: TArray.TArray<A>) => STM.STM<boolean>,\n  <A>(self: TArray.TArray<A>, predicate: Predicate<A>) => STM.STM<boolean>\n>(2, (self, predicate) =>\n  core.map(\n    findFirst(self, predicate),\n    Option.isSome\n  ))\n\n/** @internal */\nexport const someSTM = dual<\n  <A, R, E>(predicate: (value: A) => STM.STM<boolean, E, R>) => (self: TArray.TArray<A>) => STM.STM<boolean, E, R>,\n  <A, R, E>(self: TArray.TArray<A>, predicate: (value: A) => STM.STM<boolean, E, R>) => STM.STM<boolean, E, R>\n>(2, (self, predicate) => core.map(countSTM(self, predicate), (n) => n > 0))\n\n/** @internal */\nexport const toArray = <A>(self: TArray.TArray<A>): STM.STM<Array<A>> => stm.forEach(self.chunk, tRef.get)\n\n/** @internal */\nexport const transform = dual<\n  <A>(f: (value: A) => A) => (self: TArray.TArray<A>) => STM.STM<void>,\n  <A>(self: TArray.TArray<A>, f: (value: A) => A) => STM.STM<void>\n>(2, (self, f) =>\n  core.effect<never, void>((journal) => {\n    let index = 0\n    while (index < self.chunk.length) {\n      const ref = self.chunk[index]\n      tRef.unsafeSet(ref, f(tRef.unsafeGet(ref, journal)), journal)\n      index = index + 1\n    }\n    return void 0\n  }))\n\n/** @internal */\nexport const transformSTM = dual<\n  <A, R, E>(f: (value: A) => STM.STM<A, E, R>) => (self: TArray.TArray<A>) => STM.STM<void, E, R>,\n  <A, R, E>(self: TArray.TArray<A>, f: (value: A) => STM.STM<A, E, R>) => STM.STM<void, E, R>\n>(2, <A, R, E>(self: TArray.TArray<A>, f: (value: A) => STM.STM<A, E, R>) =>\n  core.flatMap(\n    stm.forEach(\n      self.chunk,\n      (ref) => core.flatMap(tRef.get(ref), f)\n    ),\n    (chunk) =>\n      core.effect<never, void>((journal) => {\n        const iterator = chunk[Symbol.iterator]()\n        let index = 0\n        let next: IteratorResult<A>\n        while ((next = iterator.next()) && !next.done) {\n          tRef.unsafeSet(self.chunk[index], next.value, journal)\n          index = index + 1\n        }\n        return void 0\n      })\n  ))\n\n/** @internal */\nexport const update = dual<\n  <A>(index: number, f: (value: A) => A) => (self: TArray.TArray<A>) => STM.STM<void>,\n  <A>(self: TArray.TArray<A>, index: number, f: (value: A) => A) => STM.STM<void>\n>(3, (self, index, f) => {\n  if (index < 0 || index >= self.chunk.length) {\n    return core.dieMessage(\"Index out of bounds\")\n  }\n  return tRef.update(self.chunk[index], f)\n})\n\n/** @internal */\nexport const updateSTM = dual<\n  <A, R, E>(index: number, f: (value: A) => STM.STM<A, E, R>) => (self: TArray.TArray<A>) => STM.STM<void, E, R>,\n  <A, R, E>(self: TArray.TArray<A>, index: number, f: (value: A) => STM.STM<A, E, R>) => STM.STM<void, E, R>\n>(3, (self, index, f) => {\n  if (index < 0 || index >= self.chunk.length) {\n    return core.dieMessage(\"Index out of bounds\")\n  }\n  return pipe(\n    tRef.get(self.chunk[index]),\n    core.flatMap(f),\n    core.flatMap((updated) => tRef.set(self.chunk[index], updated))\n  )\n})\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tDeferred.ts",
    "content": "import * as Either from \"../../Either.js\"\nimport { dual } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport type * as STM from \"../../STM.js\"\nimport type * as TDeferred from \"../../TDeferred.js\"\nimport type * as TRef from \"../../TRef.js\"\nimport * as core from \"./core.js\"\nimport * as stm from \"./stm.js\"\nimport * as tRef from \"./tRef.js\"\n\n/** @internal */\nconst TDeferredSymbolKey = \"effect/TDeferred\"\n\n/** @internal */\nexport const TDeferredTypeId: TDeferred.TDeferredTypeId = Symbol.for(\n  TDeferredSymbolKey\n) as TDeferred.TDeferredTypeId\n\n/** @internal */\nconst tDeferredVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _,\n  /* c8 ignore next */\n  _E: (_: any) => _\n}\n\n/** @internal */\nclass TDeferredImpl<in out A, in out E = never> implements TDeferred.TDeferred<A, E> {\n  readonly [TDeferredTypeId] = tDeferredVariance\n  constructor(readonly ref: TRef.TRef<Option.Option<Either.Either<A, E>>>) {}\n}\n\n/** @internal */\nexport const _await = <A, E>(self: TDeferred.TDeferred<A, E>): STM.STM<A, E> =>\n  stm.flatten(\n    stm.collect(tRef.get(self.ref), (option) =>\n      Option.isSome(option) ?\n        Option.some(stm.fromEither(option.value)) :\n        Option.none())\n  )\n\n/** @internal */\nexport const done = dual<\n  <A, E>(either: Either.Either<A, E>) => (self: TDeferred.TDeferred<A, E>) => STM.STM<boolean>,\n  <A, E>(self: TDeferred.TDeferred<A, E>, either: Either.Either<A, E>) => STM.STM<boolean>\n>(2, (self, either) =>\n  core.flatMap(\n    tRef.get(self.ref),\n    Option.match({\n      onNone: () =>\n        core.zipRight(\n          tRef.set(self.ref, Option.some(either)),\n          core.succeed(true)\n        ),\n      onSome: () => core.succeed(false)\n    })\n  ))\n\n/** @internal */\nexport const fail = dual<\n  <E>(error: E) => <A>(self: TDeferred.TDeferred<A, E>) => STM.STM<boolean>,\n  <A, E>(self: TDeferred.TDeferred<A, E>, error: E) => STM.STM<boolean>\n>(2, (self, error) => done(self, Either.left(error)))\n\n/** @internal */\nexport const make = <A, E = never>(): STM.STM<TDeferred.TDeferred<A, E>> =>\n  core.map(\n    tRef.make<Option.Option<Either.Either<A, E>>>(Option.none()),\n    (ref) => new TDeferredImpl(ref)\n  )\n\n/** @internal */\nexport const poll = <A, E>(\n  self: TDeferred.TDeferred<A, E>\n): STM.STM<Option.Option<Either.Either<A, E>>> => tRef.get(self.ref)\n\n/** @internal */\nexport const succeed = dual<\n  <A>(value: A) => <E>(self: TDeferred.TDeferred<A, E>) => STM.STM<boolean>,\n  <A, E>(self: TDeferred.TDeferred<A, E>, value: A) => STM.STM<boolean>\n>(2, (self, value) => done(self, Either.right(value)))\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tExit.ts",
    "content": "import * as Equal from \"../../Equal.js\"\nimport type * as FiberId from \"../../FiberId.js\"\nimport { pipe } from \"../../Function.js\"\nimport * as Hash from \"../../Hash.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport type * as Types from \"../../Types.js\"\nimport * as OpCodes from \"./opCodes/tExit.js\"\n\n/** @internal */\nconst TExitSymbolKey = \"effect/TExit\"\n\n/** @internal */\nexport const TExitTypeId = Symbol.for(TExitSymbolKey)\n\n/** @internal */\nexport type TExitTypeId = typeof TExitTypeId\n\n/** @internal */\nexport type TExit<A, E = never> = Fail<E> | Die | Interrupt | Succeed<A> | Retry\n\n/** @internal */\nexport declare namespace TExit {\n  /** @internal */\n  export interface Variance<out A, out E> {\n    readonly [TExitTypeId]: {\n      readonly _A: Types.Covariant<A>\n      readonly _E: Types.Covariant<E>\n    }\n  }\n}\n\nconst variance = {\n  /* c8 ignore next */\n  _A: (_: never) => _,\n  /* c8 ignore next */\n  _E: (_: never) => _\n}\n\n/** @internal */\nexport interface Fail<out E> extends TExit.Variance<never, E>, Equal.Equal {\n  readonly _tag: OpCodes.OP_FAIL\n  readonly error: E\n}\n\n/** @internal */\nexport interface Die extends TExit.Variance<never, never>, Equal.Equal {\n  readonly _tag: OpCodes.OP_DIE\n  readonly defect: unknown\n}\n\n/** @internal */\nexport interface Interrupt extends TExit.Variance<never, never>, Equal.Equal {\n  readonly _tag: OpCodes.OP_INTERRUPT\n  readonly fiberId: FiberId.FiberId\n}\n\n/** @internal */\nexport interface Succeed<out A> extends TExit.Variance<A, never>, Equal.Equal {\n  readonly _tag: OpCodes.OP_SUCCEED\n  readonly value: A\n}\n\n/** @internal */\nexport interface Retry extends TExit.Variance<never, never>, Equal.Equal {\n  readonly _tag: OpCodes.OP_RETRY\n}\n\n/** @internal */\nexport const isExit = (u: unknown): u is TExit<unknown, unknown> => hasProperty(u, TExitTypeId)\n\n/** @internal */\nexport const isFail = <A, E>(self: TExit<A, E>): self is Fail<E> => {\n  return self._tag === OpCodes.OP_FAIL\n}\n\n/** @internal */\nexport const isDie = <A, E>(self: TExit<A, E>): self is Die => {\n  return self._tag === OpCodes.OP_DIE\n}\n\n/** @internal */\nexport const isInterrupt = <A, E>(self: TExit<A, E>): self is Interrupt => {\n  return self._tag === OpCodes.OP_INTERRUPT\n}\n\n/** @internal */\nexport const isSuccess = <A, E>(self: TExit<A, E>): self is Succeed<A> => {\n  return self._tag === OpCodes.OP_SUCCEED\n}\n\n/** @internal */\nexport const isRetry = <A, E>(self: TExit<A, E>): self is Retry => {\n  return self._tag === OpCodes.OP_RETRY\n}\n\n/** @internal */\nexport const fail = <E>(error: E): TExit<never, E> => ({\n  [TExitTypeId]: variance,\n  _tag: OpCodes.OP_FAIL,\n  error,\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(TExitSymbolKey),\n      Hash.combine(Hash.hash(OpCodes.OP_FAIL)),\n      Hash.combine(Hash.hash(error)),\n      Hash.cached(this)\n    )\n  },\n  [Equal.symbol](that: unknown): boolean {\n    return isExit(that) && that._tag === OpCodes.OP_FAIL && Equal.equals(error, that.error)\n  }\n})\n\n/** @internal */\nexport const die = (defect: unknown): TExit<never> => ({\n  [TExitTypeId]: variance,\n  _tag: OpCodes.OP_DIE,\n  defect,\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(TExitSymbolKey),\n      Hash.combine(Hash.hash(OpCodes.OP_DIE)),\n      Hash.combine(Hash.hash(defect)),\n      Hash.cached(this)\n    )\n  },\n  [Equal.symbol](that: unknown): boolean {\n    return isExit(that) && that._tag === OpCodes.OP_DIE && Equal.equals(defect, that.defect)\n  }\n})\n\n/** @internal */\nexport const interrupt = (fiberId: FiberId.FiberId): TExit<never> => ({\n  [TExitTypeId]: variance,\n  _tag: OpCodes.OP_INTERRUPT,\n  fiberId,\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(TExitSymbolKey),\n      Hash.combine(Hash.hash(OpCodes.OP_INTERRUPT)),\n      Hash.combine(Hash.hash(fiberId)),\n      Hash.cached(this)\n    )\n  },\n  [Equal.symbol](that: unknown): boolean {\n    return isExit(that) && that._tag === OpCodes.OP_INTERRUPT && Equal.equals(fiberId, that.fiberId)\n  }\n})\n\n/** @internal */\nexport const succeed = <A>(value: A): TExit<A> => ({\n  [TExitTypeId]: variance,\n  _tag: OpCodes.OP_SUCCEED,\n  value,\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(TExitSymbolKey),\n      Hash.combine(Hash.hash(OpCodes.OP_SUCCEED)),\n      Hash.combine(Hash.hash(value)),\n      Hash.cached(this)\n    )\n  },\n  [Equal.symbol](that: unknown): boolean {\n    return isExit(that) && that._tag === OpCodes.OP_SUCCEED && Equal.equals(value, that.value)\n  }\n})\n\nconst retryHash = pipe(\n  Hash.hash(TExitSymbolKey),\n  Hash.combine(Hash.hash(OpCodes.OP_RETRY)),\n  Hash.combine(Hash.hash(\"retry\"))\n)\n\n/** @internal */\nexport const retry: TExit<never> = {\n  [TExitTypeId]: variance,\n  _tag: OpCodes.OP_RETRY,\n  [Hash.symbol](): number {\n    return retryHash\n  },\n  [Equal.symbol](that: unknown): boolean {\n    return isExit(that) && isRetry(that)\n  }\n}\n\nconst void_: TExit<void> = succeed(undefined)\nexport {\n  /** @internal */\n  void_ as void\n}\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tMap.ts",
    "content": "import * as RA from \"../../Array.js\"\nimport * as Chunk from \"../../Chunk.js\"\nimport * as Equal from \"../../Equal.js\"\nimport type { LazyArg } from \"../../Function.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as Hash from \"../../Hash.js\"\nimport * as HashMap from \"../../HashMap.js\"\nimport * as Option from \"../../Option.js\"\nimport { hasProperty } from \"../../Predicate.js\"\nimport * as STM from \"../../STM.js\"\nimport type * as TArray from \"../../TArray.js\"\nimport type * as TMap from \"../../TMap.js\"\nimport type * as TRef from \"../../TRef.js\"\nimport * as core from \"./core.js\"\nimport type * as Journal from \"./journal.js\"\nimport * as stm from \"./stm.js\"\nimport * as tArray from \"./tArray.js\"\nimport * as tRef from \"./tRef.js\"\n\n/** @internal */\nconst TMapSymbolKey = \"effect/TMap\"\n\n/** @internal */\nexport const TMapTypeId: TMap.TMapTypeId = Symbol.for(\n  TMapSymbolKey\n) as TMap.TMapTypeId\n\nconst tMapVariance = {\n  /* c8 ignore next */\n  _K: (_: any) => _,\n  /* c8 ignore next */\n  _V: (_: any) => _\n}\n\n/** @internal */\nclass TMapImpl<in out K, in out V> implements TMap.TMap<K, V> {\n  readonly [TMapTypeId] = tMapVariance\n  constructor(\n    readonly tBuckets: TRef.TRef<TArray.TArray<Chunk.Chunk<readonly [K, V]>>>,\n    readonly tSize: TRef.TRef<number>\n  ) {}\n}\n\nconst isTMap = (u: unknown) => hasProperty(u, TMapTypeId)\n\n/** @internal */\nconst InitialCapacity = 16\nconst LoadFactor = 0.75\n\n/** @internal */\nconst nextPowerOfTwo = (size: number): number => {\n  const n = -1 >>> Math.clz32(size - 1)\n  return n < 0 ? 1 : n + 1\n}\n\n/** @internal */\nconst hash = <K>(key: K): number => {\n  const h = Hash.hash(key)\n  return h ^ (h >>> 16)\n}\n\n/** @internal */\nconst indexOf = <K>(k: K, capacity: number): number => hash(k) & (capacity - 1)\n\n/** @internal */\nconst allocate = <K, V>(\n  capacity: number,\n  data: Chunk.Chunk<readonly [K, V]>\n): STM.STM<TMap.TMap<K, V>> => {\n  const buckets = Array.from({ length: capacity }, () => Chunk.empty<readonly [K, V]>())\n  const distinct = new Map<K, V>(data)\n  let size = 0\n  for (const entry of distinct) {\n    const index = indexOf(entry[0], capacity)\n    buckets[index] = pipe(buckets[index], Chunk.prepend(entry))\n    size = size + 1\n  }\n  return pipe(\n    tArray.fromIterable(buckets),\n    core.flatMap((buckets) =>\n      pipe(\n        tRef.make(buckets),\n        core.flatMap((tBuckets) =>\n          pipe(\n            tRef.make(size),\n            core.map((tSize) => new TMapImpl(tBuckets, tSize))\n          )\n        )\n      )\n    )\n  )\n}\n\n/** @internal */\nexport const empty = <K, V>(): STM.STM<TMap.TMap<K, V>> => fromIterable<K, V>([])\n\n/** @internal */\nexport const find = dual<\n  <K, V, A>(\n    pf: (key: K, value: V) => Option.Option<A>\n  ) => (self: TMap.TMap<K, V>) => STM.STM<Option.Option<A>>,\n  <K, V, A>(\n    self: TMap.TMap<K, V>,\n    pf: (key: K, value: V) => Option.Option<A>\n  ) => STM.STM<Option.Option<A>>\n>(2, (self, pf) =>\n  findSTM(self, (key, value) => {\n    const option = pf(key, value)\n    if (Option.isSome(option)) {\n      return core.succeed(option.value)\n    }\n    return core.fail(Option.none())\n  }))\n\n/** @internal */\nexport const findSTM = dual<\n  <K, V, A, E, R>(\n    f: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ) => (self: TMap.TMap<K, V>) => STM.STM<Option.Option<A>, E, R>,\n  <K, V, A, E, R>(\n    self: TMap.TMap<K, V>,\n    f: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ) => STM.STM<Option.Option<A>, E, R>\n>(2, <K, V, A, E, R>(\n  self: TMap.TMap<K, V>,\n  f: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n) =>\n  reduceSTM(self, Option.none<A>(), (acc, value, key) =>\n    Option.isNone(acc) ?\n      core.matchSTM(f(key, value), {\n        onFailure: Option.match({\n          onNone: () => stm.succeedNone,\n          onSome: core.fail\n        }),\n        onSuccess: stm.succeedSome\n      }) :\n      STM.succeed(acc)))\n\n/** @internal */\nexport const findAll = dual<\n  <K, V, A>(\n    pf: (key: K, value: V) => Option.Option<A>\n  ) => (self: TMap.TMap<K, V>) => STM.STM<Array<A>>,\n  <K, V, A>(\n    self: TMap.TMap<K, V>,\n    pf: (key: K, value: V) => Option.Option<A>\n  ) => STM.STM<Array<A>>\n>(2, (self, pf) =>\n  findAllSTM(self, (key, value) => {\n    const option = pf(key, value)\n    if (Option.isSome(option)) {\n      return core.succeed(option.value)\n    }\n    return core.fail(Option.none())\n  }))\n\n/** @internal */\nexport const findAllSTM = dual<\n  <K, V, A, E, R>(\n    pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ) => (self: TMap.TMap<K, V>) => STM.STM<Array<A>, E, R>,\n  <K, V, A, E, R>(\n    self: TMap.TMap<K, V>,\n    pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ) => STM.STM<Array<A>, E, R>\n>(2, <K, V, A, E, R>(\n  self: TMap.TMap<K, V>,\n  pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n) =>\n  core.map(\n    reduceSTM(self, Chunk.empty<A>(), (acc, value, key) =>\n      core.matchSTM(pf(key, value), {\n        onFailure: Option.match({\n          onNone: () => core.succeed(acc),\n          onSome: core.fail\n        }),\n        onSuccess: (a) => core.succeed(Chunk.append(acc, a))\n      })),\n    (a) => Array.from(a)\n  ))\n\n/** @internal */\nexport const forEach = dual<\n  <K, V, X, E, R>(f: (key: K, value: V) => STM.STM<X, E, R>) => (self: TMap.TMap<K, V>) => STM.STM<void, E, R>,\n  <K, V, X, E, R>(self: TMap.TMap<K, V>, f: (key: K, value: V) => STM.STM<X, E, R>) => STM.STM<void, E, R>\n>(2, (self, f) =>\n  reduceSTM(\n    self,\n    void 0 as void,\n    (_, value, key) => stm.asVoid(f(key, value))\n  ))\n\n/** @internal */\nexport const fromIterable = <K, V>(iterable: Iterable<readonly [K, V]>): STM.STM<TMap.TMap<K, V>> =>\n  stm.suspend(() => {\n    const data = Chunk.fromIterable(iterable)\n    const capacity = data.length < InitialCapacity\n      ? InitialCapacity\n      : nextPowerOfTwo(data.length)\n    return allocate(capacity, data)\n  })\n\n/** @internal */\nexport const get = dual<\n  <K>(key: K) => <V>(self: TMap.TMap<K, V>) => STM.STM<Option.Option<V>>,\n  <K, V>(self: TMap.TMap<K, V>, key: K) => STM.STM<Option.Option<V>>\n>(2, <K, V>(self: TMap.TMap<K, V>, key: K) =>\n  core.effect<never, Option.Option<V>>((journal) => {\n    const buckets = tRef.unsafeGet(self.tBuckets, journal)\n    const index = indexOf(key, buckets.chunk.length)\n    const bucket = tRef.unsafeGet(buckets.chunk[index], journal)\n    return pipe(\n      Chunk.findFirst(bucket, (entry) => Equal.equals(entry[0])(key)),\n      Option.map((entry) => entry[1])\n    )\n  }))\n\n/** @internal */\nexport const getOrElse = dual<\n  <K, V>(key: K, fallback: LazyArg<V>) => (self: TMap.TMap<K, V>) => STM.STM<V>,\n  <K, V>(self: TMap.TMap<K, V>, key: K, fallback: LazyArg<V>) => STM.STM<V>\n>(3, (self, key, fallback) =>\n  core.map(\n    get(self, key),\n    Option.getOrElse(fallback)\n  ))\n\n/** @internal */\nexport const has = dual<\n  <K>(key: K) => <V>(self: TMap.TMap<K, V>) => STM.STM<boolean>,\n  <K, V>(self: TMap.TMap<K, V>, key: K) => STM.STM<boolean>\n>(2, (self, key) => core.map(get(self, key), Option.isSome))\n\n/** @internal */\nexport const isEmpty = <K, V>(self: TMap.TMap<K, V>): STM.STM<boolean> =>\n  core.map(tRef.get(self.tSize), (size) => size === 0)\n\n/** @internal */\nexport const keys = <K, V>(self: TMap.TMap<K, V>): STM.STM<Array<K>> =>\n  core.map(toReadonlyArray(self), RA.map((entry) => entry[0]))\n\n/** @internal */\nexport const make = <K, V>(...entries: Array<readonly [K, V]>): STM.STM<TMap.TMap<K, V>> => fromIterable(entries)\n\n/** @internal */\nexport const merge = dual<\n  <K, V>(key: K, value: V, f: (x: V, y: V) => V) => (self: TMap.TMap<K, V>) => STM.STM<V>,\n  <K, V>(self: TMap.TMap<K, V>, key: K, value: V, f: (x: V, y: V) => V) => STM.STM<V>\n>(4, (self, key, value, f) =>\n  core.flatMap(\n    get(self, key),\n    Option.match({\n      onNone: () => stm.as(set(self, key, value), value),\n      onSome: (v0) => {\n        const v1 = f(v0, value)\n        return stm.as(set(self, key, v1), v1)\n      }\n    })\n  ))\n\n/** @internal */\nexport const reduce = dual<\n  <Z, K, V>(zero: Z, f: (acc: Z, value: V, key: K) => Z) => (self: TMap.TMap<K, V>) => STM.STM<Z>,\n  <K, V, Z>(self: TMap.TMap<K, V>, zero: Z, f: (acc: Z, value: V, key: K) => Z) => STM.STM<Z>\n>(\n  3,\n  <K, V, Z>(self: TMap.TMap<K, V>, zero: Z, f: (acc: Z, value: V, key: K) => Z) =>\n    core.effect<never, Z>((journal) => {\n      const buckets = tRef.unsafeGet(self.tBuckets, journal)\n      let result = zero\n      let index = 0\n      while (index < buckets.chunk.length) {\n        const bucket = buckets.chunk[index]\n        const items = tRef.unsafeGet(bucket, journal)\n        result = Chunk.reduce(items, result, (acc, entry) => f(acc, entry[1], entry[0]))\n        index = index + 1\n      }\n      return result\n    })\n)\n\n/** @internal */\nexport const reduceSTM = dual<\n  <Z, V, K, R, E>(\n    zero: Z,\n    f: (acc: Z, value: V, key: K) => STM.STM<Z, E, R>\n  ) => (self: TMap.TMap<K, V>) => STM.STM<Z, E, R>,\n  <Z, V, K, R, E>(\n    self: TMap.TMap<K, V>,\n    zero: Z,\n    f: (acc: Z, value: V, key: K) => STM.STM<Z, E, R>\n  ) => STM.STM<Z, E, R>\n>(3, (self, zero, f) =>\n  core.flatMap(\n    toReadonlyArray(self),\n    stm.reduce(zero, (acc, entry) => f(acc, entry[1], entry[0]))\n  ))\n\n/** @internal */\nexport const remove = dual<\n  <K>(key: K) => <V>(self: TMap.TMap<K, V>) => STM.STM<void>,\n  <K, V>(self: TMap.TMap<K, V>, key: K) => STM.STM<void>\n>(2, (self, key) =>\n  core.effect<never, void>((journal) => {\n    const buckets = tRef.unsafeGet(self.tBuckets, journal)\n    const index = indexOf(key, buckets.chunk.length)\n    const bucket = tRef.unsafeGet(buckets.chunk[index], journal)\n    const [toRemove, toRetain] = Chunk.partition(bucket, (entry) => Equal.equals(entry[1], key))\n    if (Chunk.isNonEmpty(toRemove)) {\n      const currentSize = tRef.unsafeGet(self.tSize, journal)\n      tRef.unsafeSet(buckets.chunk[index], toRetain, journal)\n      tRef.unsafeSet(self.tSize, currentSize - 1, journal)\n    }\n  }))\n\n/** @internal */\nexport const removeAll = dual<\n  <K>(keys: Iterable<K>) => <V>(self: TMap.TMap<K, V>) => STM.STM<void>,\n  <K, V>(self: TMap.TMap<K, V>, keys: Iterable<K>) => STM.STM<void>\n>(2, <K, V>(self: TMap.TMap<K, V>, keys: Iterable<K>) =>\n  core.effect<never, void>((journal) => {\n    const iterator = keys[Symbol.iterator]()\n    let next: IteratorResult<K, any>\n    while ((next = iterator.next()) && !next.done) {\n      const buckets = tRef.unsafeGet(self.tBuckets, journal)\n      const index = indexOf(next.value, buckets.chunk.length)\n      const bucket = tRef.unsafeGet(buckets.chunk[index], journal)\n      const [toRemove, toRetain] = Chunk.partition(bucket, (entry) => Equal.equals(next.value)(entry[0]))\n      if (Chunk.isNonEmpty(toRemove)) {\n        const currentSize = tRef.unsafeGet(self.tSize, journal)\n        tRef.unsafeSet(buckets.chunk[index], toRetain, journal)\n        tRef.unsafeSet(self.tSize, currentSize - 1, journal)\n      }\n    }\n  }))\n\n/** @internal */\nexport const removeIf: {\n  <K, V>(\n    predicate: (key: K, value: V) => boolean,\n    options: {\n      readonly discard: true\n    }\n  ): (self: TMap.TMap<K, V>) => STM.STM<void>\n  <K, V>(\n    predicate: (key: K, value: V) => boolean,\n    options?: {\n      readonly discard: false\n    }\n  ): (self: TMap.TMap<K, V>) => STM.STM<Array<[K, V]>>\n  <K, V>(\n    self: TMap.TMap<K, V>,\n    predicate: (key: K, value: V) => boolean,\n    options: {\n      readonly discard: true\n    }\n  ): STM.STM<void>\n  <K, V>(\n    self: TMap.TMap<K, V>,\n    predicate: (key: K, value: V) => boolean,\n    options?: {\n      readonly discard: false\n    }\n  ): STM.STM<Array<[K, V]>>\n} = dual((args) => isTMap(args[0]), <K, V>(\n  self: TMap.TMap<K, V>,\n  predicate: (key: K, value: V) => boolean,\n  options?: {\n    readonly discard: boolean\n  }\n) =>\n  core.effect((journal) => {\n    const discard = options?.discard === true\n    const buckets = tRef.unsafeGet(self.tBuckets, journal)\n    const capacity = buckets.chunk.length\n    const removed: Array<[K, V]> = []\n    let index = 0\n    let newSize = 0\n    while (index < capacity) {\n      const bucket = tRef.unsafeGet(buckets.chunk[index], journal)\n      const iterator = bucket[Symbol.iterator]()\n      let next: IteratorResult<readonly [K, V], any>\n      let newBucket = Chunk.empty<readonly [K, V]>()\n      while ((next = iterator.next()) && !next.done) {\n        const [k, v] = next.value\n        if (!predicate(k, v)) {\n          newBucket = Chunk.prepend(newBucket, next.value)\n          newSize = newSize + 1\n        } else {\n          if (!discard) {\n            removed.push([k, v])\n          }\n        }\n      }\n      tRef.unsafeSet(buckets.chunk[index], newBucket, journal)\n      index = index + 1\n    }\n    tRef.unsafeSet(self.tSize, newSize, journal)\n    if (!discard) {\n      return removed\n    }\n  }))\n\n/** @internal */\nexport const retainIf: {\n  <K, V>(\n    predicate: (key: K, value: V) => boolean,\n    options: {\n      readonly discard: true\n    }\n  ): (self: TMap.TMap<K, V>) => STM.STM<void>\n  <K, V>(\n    predicate: (key: K, value: V) => boolean,\n    options?: {\n      readonly discard: false\n    }\n  ): (self: TMap.TMap<K, V>) => STM.STM<Array<[K, V]>>\n  <K, V>(\n    self: TMap.TMap<K, V>,\n    predicate: (key: K, value: V) => boolean,\n    options: {\n      readonly discard: true\n    }\n  ): STM.STM<void>\n  <K, V>(\n    self: TMap.TMap<K, V>,\n    predicate: (key: K, value: V) => boolean,\n    options?: {\n      readonly discard: false\n    }\n  ): STM.STM<Array<[K, V]>>\n} = dual(\n  (args) => isTMap(args[0]),\n  (self, predicate, options) => removeIf(self, (key, value) => !predicate(key, value), options)\n)\n\n/** @internal */\nexport const set = dual<\n  <K, V>(key: K, value: V) => (self: TMap.TMap<K, V>) => STM.STM<void>,\n  <K, V>(self: TMap.TMap<K, V>, key: K, value: V) => STM.STM<void>\n>(3, <K, V>(self: TMap.TMap<K, V>, key: K, value: V) => {\n  const resize = (journal: Journal.Journal, buckets: TArray.TArray<Chunk.Chunk<readonly [K, V]>>): void => {\n    const capacity = buckets.chunk.length\n    const newCapacity = capacity << 1\n    const newBuckets = Array.from({ length: newCapacity }, () => Chunk.empty<readonly [K, V]>())\n    let index = 0\n    while (index < capacity) {\n      const pairs = tRef.unsafeGet(buckets.chunk[index], journal)\n      const iterator = pairs[Symbol.iterator]()\n      let next: IteratorResult<readonly [K, V], any>\n      while ((next = iterator.next()) && !next.done) {\n        const newIndex = indexOf(next.value[0], newCapacity)\n        newBuckets[newIndex] = Chunk.prepend(newBuckets[newIndex], next.value)\n      }\n      index = index + 1\n    }\n    // insert new pair\n    const newIndex = indexOf(key, newCapacity)\n    newBuckets[newIndex] = Chunk.prepend(newBuckets[newIndex], [key, value] as const)\n\n    const newArray: Array<TRef.TRef<Chunk.Chunk<readonly [K, V]>>> = []\n    index = 0\n    while (index < newCapacity) {\n      newArray[index] = new tRef.TRefImpl(newBuckets[index])\n      index = index + 1\n    }\n    const newTArray: TArray.TArray<Chunk.Chunk<readonly [K, V]>> = new tArray.TArrayImpl(newArray)\n    tRef.unsafeSet(self.tBuckets, newTArray, journal)\n  }\n  return core.effect<never, void>((journal) => {\n    const buckets = tRef.unsafeGet(self.tBuckets, journal)\n    const capacity = buckets.chunk.length\n    const index = indexOf(key, capacity)\n    const bucket = tRef.unsafeGet(buckets.chunk[index], journal)\n    const shouldUpdate = Chunk.some(bucket, (entry) => Equal.equals(key)(entry[0]))\n    if (shouldUpdate) {\n      const newBucket = Chunk.map(bucket, (entry) =>\n        Equal.equals(key)(entry[0]) ?\n          [key, value] as const :\n          entry)\n      tRef.unsafeSet(buckets.chunk[index], newBucket, journal)\n    } else {\n      const newSize = tRef.unsafeGet(self.tSize, journal) + 1\n      tRef.unsafeSet(self.tSize, newSize, journal)\n      if (capacity * LoadFactor < newSize) {\n        resize(journal, buckets)\n      } else {\n        const newBucket = Chunk.prepend(bucket, [key, value] as const)\n        tRef.unsafeSet(buckets.chunk[index], newBucket, journal)\n      }\n    }\n  })\n})\n\n/** @internal */\nexport const setIfAbsent = dual<\n  <K, V>(key: K, value: V) => (self: TMap.TMap<K, V>) => STM.STM<void>,\n  <K, V>(self: TMap.TMap<K, V>, key: K, value: V) => STM.STM<void>\n>(3, (self, key, value) =>\n  core.flatMap(\n    get(self, key),\n    Option.match({\n      onNone: () => set(self, key, value),\n      onSome: () => stm.void\n    })\n  ))\n\n/** @internal */\nexport const size = <K, V>(self: TMap.TMap<K, V>): STM.STM<number> => tRef.get(self.tSize)\n\n/** @internal */\nexport const takeFirst = dual<\n  <K, V, A>(pf: (key: K, value: V) => Option.Option<A>) => (self: TMap.TMap<K, V>) => STM.STM<A>,\n  <K, V, A>(self: TMap.TMap<K, V>, pf: (key: K, value: V) => Option.Option<A>) => STM.STM<A>\n>(2, <K, V, A>(self: TMap.TMap<K, V>, pf: (key: K, value: V) => Option.Option<A>) =>\n  pipe(\n    core.effect<never, Option.Option<A>>((journal) => {\n      const buckets = tRef.unsafeGet(self.tBuckets, journal)\n      const capacity = buckets.chunk.length\n      const size = tRef.unsafeGet(self.tSize, journal)\n      let result: Option.Option<A> = Option.none()\n      let index = 0\n      while (index < capacity && Option.isNone(result)) {\n        const bucket = tRef.unsafeGet(buckets.chunk[index], journal)\n        const recreate = Chunk.some(bucket, (entry) => Option.isSome(pf(entry[0], entry[1])))\n        if (recreate) {\n          const iterator = bucket[Symbol.iterator]()\n          let newBucket = Chunk.empty<readonly [K, V]>()\n          let next: IteratorResult<readonly [K, V], any>\n          while ((next = iterator.next()) && !next.done && Option.isNone(result)) {\n            const option = pf(next.value[0], next.value[1])\n            if (Option.isSome(option) && Option.isNone(result)) {\n              result = option\n            } else {\n              newBucket = Chunk.prepend(newBucket, next.value)\n            }\n          }\n          tRef.unsafeSet(buckets.chunk[index], newBucket, journal)\n        }\n        index = index + 1\n      }\n      if (Option.isSome(result)) {\n        tRef.unsafeSet(self.tSize, size - 1, journal)\n      }\n      return result\n    }),\n    stm.collect((option) =>\n      Option.isSome(option) ?\n        Option.some(option.value) :\n        Option.none<A>()\n    )\n  ))\n\n/** @internal */\nexport const takeFirstSTM = dual<\n  <K, V, A, E, R>(\n    pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ) => (self: TMap.TMap<K, V>) => STM.STM<A, E, R>,\n  <K, V, A, E, R>(self: TMap.TMap<K, V>, pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>) => STM.STM<A, E, R>\n>(2, (self, pf) =>\n  pipe(\n    findSTM(self, (key, value) => core.map(pf(key, value), (a) => [key, a] as const)),\n    stm.collect((option) => Option.isSome(option) ? Option.some(option.value) : Option.none()),\n    core.flatMap((entry) => stm.as(remove(self, entry[0]), entry[1]))\n  ))\n\n/** @internal */\nexport const takeSome = dual<\n  <K, V, A>(\n    pf: (key: K, value: V) => Option.Option<A>\n  ) => (self: TMap.TMap<K, V>) => STM.STM<RA.NonEmptyArray<A>>,\n  <K, V, A>(\n    self: TMap.TMap<K, V>,\n    pf: (key: K, value: V) => Option.Option<A>\n  ) => STM.STM<RA.NonEmptyArray<A>>\n>(2, <K, V, A>(self: TMap.TMap<K, V>, pf: (key: K, value: V) => Option.Option<A>) =>\n  pipe(\n    core.effect<never, Option.Option<RA.NonEmptyArray<A>>>((journal) => {\n      const buckets = tRef.unsafeGet(self.tBuckets, journal)\n      const capacity = buckets.chunk.length\n      const builder: Array<A> = []\n      let newSize = 0\n      let index = 0\n      while (index < capacity) {\n        const bucket = tRef.unsafeGet(buckets.chunk[index], journal)\n        const recreate = Chunk.some(bucket, (entry) => Option.isSome(pf(entry[0], entry[1])))\n        if (recreate) {\n          const iterator = bucket[Symbol.iterator]()\n          let newBucket = Chunk.empty<readonly [K, V]>()\n          let next: IteratorResult<readonly [K, V], any>\n          while ((next = iterator.next()) && !next.done) {\n            const option = pf(next.value[0], next.value[1])\n            if (Option.isSome(option)) {\n              builder.push(option.value)\n            } else {\n              newBucket = Chunk.prepend(newBucket, next.value)\n              newSize = newSize + 1\n            }\n          }\n          tRef.unsafeSet(buckets.chunk[index], newBucket, journal)\n        } else {\n          newSize = newSize + bucket.length\n        }\n        index = index + 1\n      }\n      tRef.unsafeSet(self.tSize, newSize, journal)\n      if (builder.length > 0) {\n        return Option.some(builder as RA.NonEmptyArray<A>)\n      }\n      return Option.none()\n    }),\n    stm.collect((option) =>\n      Option.isSome(option) ?\n        Option.some(option.value) :\n        Option.none<RA.NonEmptyArray<A>>()\n    )\n  ))\n\n/** @internal */\nexport const takeSomeSTM = dual<\n  <K, V, A, E, R>(\n    pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ) => (self: TMap.TMap<K, V>) => STM.STM<RA.NonEmptyArray<A>, E, R>,\n  <K, V, A, E, R>(\n    self: TMap.TMap<K, V>,\n    pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n  ) => STM.STM<RA.NonEmptyArray<A>, E, R>\n>(2, <K, V, A, E, R>(\n  self: TMap.TMap<K, V>,\n  pf: (key: K, value: V) => STM.STM<A, Option.Option<E>, R>\n) =>\n  pipe(\n    findAllSTM(\n      self,\n      (key, value) => core.map(pf(key, value), (a) => [key, a] as const)\n    ),\n    core.map((chunk) =>\n      RA.isNonEmptyArray(chunk) ?\n        Option.some(chunk) :\n        Option.none()\n    ),\n    stm.collect((option) =>\n      Option.isSome(option) ?\n        Option.some(option.value) :\n        Option.none()\n    ),\n    core.flatMap((entries) =>\n      stm.as(\n        removeAll(self, entries.map((entry) => entry[0])),\n        RA.map(entries, (entry) => entry[1]) as RA.NonEmptyArray<A>\n      )\n    )\n  ))\n\nconst toReadonlyArray = <K, V>(self: TMap.TMap<K, V>): STM.STM<ReadonlyArray<readonly [K, V]>> =>\n  core.effect<never, Array<readonly [K, V]>>((journal) => {\n    const buckets = tRef.unsafeGet(self.tBuckets, journal)\n    const capacity = buckets.chunk.length\n    const builder: Array<readonly [K, V]> = []\n    let index = 0\n    while (index < capacity) {\n      const bucket = buckets.chunk[index]\n      for (const entry of tRef.unsafeGet(bucket, journal)) {\n        builder.push(entry)\n      }\n      index = index + 1\n    }\n    return builder\n  })\n\n/** @internal */\nexport const toChunk = <K, V>(self: TMap.TMap<K, V>): STM.STM<Chunk.Chunk<[K, V]>> =>\n  reduce(\n    self,\n    Chunk.empty<[K, V]>(),\n    (acc, value, key) => Chunk.append(acc, [key, value])\n  )\n\n/** @internal */\nexport const toHashMap = <K, V>(self: TMap.TMap<K, V>): STM.STM<HashMap.HashMap<K, V>> =>\n  reduce(\n    self,\n    HashMap.empty<K, V>(),\n    (acc, value, key) => pipe(acc, HashMap.set(key, value))\n  )\n\n/** @internal */\nexport const toArray = <K, V>(self: TMap.TMap<K, V>): STM.STM<Array<[K, V]>> =>\n  reduce(\n    self,\n    [] as Array<[K, V]>,\n    (acc, value, key) => {\n      acc.unshift([key, value])\n      return acc\n    }\n  )\n\n/** @internal */\nexport const toMap = <K, V>(self: TMap.TMap<K, V>): STM.STM<Map<K, V>> =>\n  reduce(\n    self,\n    new Map<K, V>(),\n    (acc, value, key) => acc.set(key, value)\n  )\n\n/** @internal */\nexport const transform = dual<\n  <K, V>(f: (key: K, value: V) => readonly [K, V]) => (self: TMap.TMap<K, V>) => STM.STM<void>,\n  <K, V>(self: TMap.TMap<K, V>, f: (key: K, value: V) => readonly [K, V]) => STM.STM<void>\n>(\n  2,\n  <K, V>(self: TMap.TMap<K, V>, f: (key: K, value: V) => readonly [K, V]) =>\n    core.effect<never, void>((journal) => {\n      const buckets = pipe(self.tBuckets, tRef.unsafeGet(journal))\n      const capacity = buckets.chunk.length\n      const newBuckets = Array.from({ length: capacity }, () => Chunk.empty<readonly [K, V]>())\n      let newSize = 0\n      let index = 0\n      while (index < capacity) {\n        const bucket = buckets.chunk[index]\n        const pairs = tRef.unsafeGet(bucket, journal)\n        const iterator = pairs[Symbol.iterator]()\n        let next: IteratorResult<readonly [K, V], any>\n        while ((next = iterator.next()) && !next.done) {\n          const newPair = f(next.value[0], next.value[1])\n          const index = indexOf(newPair[0], capacity)\n          const newBucket = newBuckets[index]\n          if (!Chunk.some(newBucket, (entry) => Equal.equals(entry[0], newPair[0]))) {\n            newBuckets[index] = Chunk.prepend(newBucket, newPair)\n            newSize = newSize + 1\n          }\n        }\n        index = index + 1\n      }\n      index = 0\n      while (index < capacity) {\n        tRef.unsafeSet(buckets.chunk[index], newBuckets[index], journal)\n        index = index + 1\n      }\n      tRef.unsafeSet(self.tSize, newSize, journal)\n    })\n)\n\n/** @internal */\nexport const transformSTM = dual<\n  <K, V, R, E>(\n    f: (key: K, value: V) => STM.STM<readonly [K, V], E, R>\n  ) => (self: TMap.TMap<K, V>) => STM.STM<void, E, R>,\n  <K, V, R, E>(self: TMap.TMap<K, V>, f: (key: K, value: V) => STM.STM<readonly [K, V], E, R>) => STM.STM<void, E, R>\n>(\n  2,\n  <K, V, R, E>(self: TMap.TMap<K, V>, f: (key: K, value: V) => STM.STM<readonly [K, V], E, R>) =>\n    pipe(\n      core.flatMap(\n        toReadonlyArray(self),\n        stm.forEach((entry) => f(entry[0], entry[1]))\n      ),\n      core.flatMap((newData) =>\n        core.effect<never, void>((journal) => {\n          const buckets = tRef.unsafeGet(self.tBuckets, journal)\n          const capacity = buckets.chunk.length\n          const newBuckets = Array.from({ length: capacity }, () => Chunk.empty<readonly [K, V]>())\n          const iterator = newData[Symbol.iterator]()\n          let newSize = 0\n          let next: IteratorResult<readonly [K, V], any>\n          while ((next = iterator.next()) && !next.done) {\n            const index = indexOf(next.value[0], capacity)\n            const newBucket = newBuckets[index]\n            if (!Chunk.some(newBucket, (entry) => Equal.equals(entry[0])(next.value[0]))) {\n              newBuckets[index] = Chunk.prepend(newBucket, next.value)\n              newSize = newSize + 1\n            }\n          }\n          let index = 0\n          while (index < capacity) {\n            tRef.unsafeSet(buckets.chunk[index], newBuckets[index], journal)\n            index = index + 1\n          }\n          tRef.unsafeSet(self.tSize, newSize, journal)\n        })\n      )\n    )\n)\n\n/** @internal */\nexport const transformValues = dual<\n  <V>(f: (value: V) => V) => <K>(self: TMap.TMap<K, V>) => STM.STM<void>,\n  <K, V>(self: TMap.TMap<K, V>, f: (value: V) => V) => STM.STM<void>\n>(2, (self, f) => transform(self, (key, value) => [key, f(value)]))\n\n/** @internal */\nexport const transformValuesSTM = dual<\n  <V, R, E>(f: (value: V) => STM.STM<V, E, R>) => <K>(self: TMap.TMap<K, V>) => STM.STM<void, E, R>,\n  <K, V, R, E>(self: TMap.TMap<K, V>, f: (value: V) => STM.STM<V, E, R>) => STM.STM<void, E, R>\n>(2, (self, f) =>\n  transformSTM(\n    self,\n    (key, value) => core.map(f(value), (value) => [key, value])\n  ))\n\n/** @internal */\nexport const updateWith = dual<\n  <K, V>(\n    key: K,\n    f: (value: Option.Option<V>) => Option.Option<V>\n  ) => (self: TMap.TMap<K, V>) => STM.STM<Option.Option<V>>,\n  <K, V>(\n    self: TMap.TMap<K, V>,\n    key: K,\n    f: (value: Option.Option<V>) => Option.Option<V>\n  ) => STM.STM<Option.Option<V>>\n>(3, (self, key, f) =>\n  core.flatMap(get(self, key), (option) =>\n    Option.match(\n      f(option),\n      {\n        onNone: () => stm.as(remove(self, key), Option.none()),\n        onSome: (value) => stm.as(set(self, key, value), Option.some(value))\n      }\n    )))\n\n/** @internal */\nexport const values = <K, V>(self: TMap.TMap<K, V>): STM.STM<Array<V>> =>\n  core.map(toReadonlyArray(self), RA.map((entry) => entry[1]))\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tPriorityQueue.ts",
    "content": "import * as Arr from \"../../Array.js\"\nimport * as Chunk from \"../../Chunk.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport type * as Order from \"../../Order.js\"\nimport type { Predicate } from \"../../Predicate.js\"\nimport * as SortedMap from \"../../SortedMap.js\"\nimport type * as STM from \"../../STM.js\"\nimport type * as TPriorityQueue from \"../../TPriorityQueue.js\"\nimport type * as TRef from \"../../TRef.js\"\nimport * as core from \"./core.js\"\nimport * as tRef from \"./tRef.js\"\n\n/** @internal */\nconst TPriorityQueueSymbolKey = \"effect/TPriorityQueue\"\n\n/** @internal */\nexport const TPriorityQueueTypeId: TPriorityQueue.TPriorityQueueTypeId = Symbol.for(\n  TPriorityQueueSymbolKey\n) as TPriorityQueue.TPriorityQueueTypeId\n\nconst tPriorityQueueVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nexport class TPriorityQueueImpl<in out A> implements TPriorityQueue.TPriorityQueue<A> {\n  readonly [TPriorityQueueTypeId] = tPriorityQueueVariance\n  constructor(readonly ref: TRef.TRef<SortedMap.SortedMap<A, [A, ...Array<A>]>>) {}\n}\n\n/** @internal */\nexport const empty = <A>(order: Order.Order<A>): STM.STM<TPriorityQueue.TPriorityQueue<A>> =>\n  pipe(\n    tRef.make(SortedMap.empty<A, [A, ...Array<A>]>(order)),\n    core.map((ref) => new TPriorityQueueImpl(ref))\n  )\n\n/** @internal */\nexport const fromIterable =\n  <A>(order: Order.Order<A>) => (iterable: Iterable<A>): STM.STM<TPriorityQueue.TPriorityQueue<A>> =>\n    pipe(\n      tRef.make(\n        Arr.fromIterable(iterable).reduce(\n          (map, value) =>\n            pipe(\n              map,\n              SortedMap.set(\n                value,\n                pipe(\n                  map,\n                  SortedMap.get(value),\n                  Option.match({\n                    onNone: () => Arr.of(value),\n                    onSome: Arr.prepend(value)\n                  })\n                )\n              )\n            ),\n          SortedMap.empty<A, [A, ...Array<A>]>(order)\n        )\n      ),\n      core.map((ref) => new TPriorityQueueImpl(ref))\n    )\n\n/** @internal */\nexport const isEmpty = <A>(self: TPriorityQueue.TPriorityQueue<A>): STM.STM<boolean> =>\n  core.map(tRef.get(self.ref), SortedMap.isEmpty)\n\n/** @internal */\nexport const isNonEmpty = <A>(self: TPriorityQueue.TPriorityQueue<A>): STM.STM<boolean> =>\n  core.map(tRef.get(self.ref), SortedMap.isNonEmpty)\n\n/** @internal */\nexport const make = <A>(order: Order.Order<A>) => (...elements: Array<A>): STM.STM<TPriorityQueue.TPriorityQueue<A>> =>\n  fromIterable(order)(elements)\n\n/** @internal */\nexport const offer = dual<\n  <A>(value: A) => (self: TPriorityQueue.TPriorityQueue<A>) => STM.STM<void>,\n  <A>(self: TPriorityQueue.TPriorityQueue<A>, value: A) => STM.STM<void>\n>(2, (self, value) =>\n  tRef.update(self.ref, (map) =>\n    SortedMap.set(\n      map,\n      value,\n      Option.match(SortedMap.get(map, value), {\n        onNone: () => Arr.of(value),\n        onSome: Arr.prepend(value)\n      })\n    )))\n\n/** @internal */\nexport const offerAll = dual<\n  <A>(values: Iterable<A>) => (self: TPriorityQueue.TPriorityQueue<A>) => STM.STM<void>,\n  <A>(self: TPriorityQueue.TPriorityQueue<A>, values: Iterable<A>) => STM.STM<void>\n>(2, (self, values) =>\n  tRef.update(self.ref, (map) =>\n    Arr.fromIterable(values).reduce(\n      (map, value) =>\n        SortedMap.set(\n          map,\n          value,\n          Option.match(SortedMap.get(map, value), {\n            onNone: () => Arr.of(value),\n            onSome: Arr.prepend(value)\n          })\n        ),\n      map\n    )))\n\n/** @internal */\nexport const peek = <A>(self: TPriorityQueue.TPriorityQueue<A>): STM.STM<A> =>\n  core.withSTMRuntime((runtime) => {\n    const map = tRef.unsafeGet(self.ref, runtime.journal)\n    return Option.match(\n      SortedMap.headOption(map),\n      {\n        onNone: () => core.retry,\n        onSome: (elements) => core.succeed(elements[0])\n      }\n    )\n  })\n\n/** @internal */\nexport const peekOption = <A>(self: TPriorityQueue.TPriorityQueue<A>): STM.STM<Option.Option<A>> =>\n  tRef.modify(self.ref, (map) => [\n    Option.map(SortedMap.headOption(map), (elements) => elements[0]),\n    map\n  ])\n\n/** @internal */\nexport const removeIf = dual<\n  <A>(predicate: Predicate<A>) => (self: TPriorityQueue.TPriorityQueue<A>) => STM.STM<void>,\n  <A>(self: TPriorityQueue.TPriorityQueue<A>, predicate: Predicate<A>) => STM.STM<void>\n>(2, (self, predicate) => retainIf(self, (a) => !predicate(a)))\n\n/** @internal */\nexport const retainIf = dual<\n  <A>(predicate: Predicate<A>) => (self: TPriorityQueue.TPriorityQueue<A>) => STM.STM<void>,\n  <A>(self: TPriorityQueue.TPriorityQueue<A>, predicate: Predicate<A>) => STM.STM<void>\n>(\n  2,\n  <A>(self: TPriorityQueue.TPriorityQueue<A>, predicate: Predicate<A>) =>\n    tRef.update(\n      self.ref,\n      (map) =>\n        SortedMap.reduce(map, SortedMap.empty(SortedMap.getOrder(map)), (map, value, key) => {\n          const filtered: ReadonlyArray<A> = Arr.filter(value, predicate)\n          return filtered.length > 0 ?\n            SortedMap.set(map, key, filtered as [A, ...Array<A>]) :\n            SortedMap.remove(map, key)\n        })\n    )\n)\n\n/** @internal */\nexport const size = <A>(self: TPriorityQueue.TPriorityQueue<A>): STM.STM<number> =>\n  tRef.modify(\n    self.ref,\n    (map) => [SortedMap.reduce(map, 0, (n, as) => n + as.length), map]\n  )\n\n/** @internal */\nexport const take = <A>(self: TPriorityQueue.TPriorityQueue<A>): STM.STM<A> =>\n  core.withSTMRuntime((runtime) => {\n    const map = tRef.unsafeGet(self.ref, runtime.journal)\n    return Option.match(SortedMap.headOption(map), {\n      onNone: () => core.retry,\n      onSome: (values) => {\n        const head = values[1][0]\n        const tail = values[1].slice(1)\n        tRef.unsafeSet(\n          self.ref,\n          tail.length > 0 ?\n            SortedMap.set(map, head, tail as [A, ...Array<A>]) :\n            SortedMap.remove(map, head),\n          runtime.journal\n        )\n        return core.succeed(head)\n      }\n    })\n  })\n\n/** @internal */\nexport const takeAll = <A>(self: TPriorityQueue.TPriorityQueue<A>): STM.STM<Array<A>> =>\n  tRef.modify(self.ref, (map) => {\n    const builder: Array<A> = []\n    for (const entry of map) {\n      for (const value of entry[1]) {\n        builder.push(value)\n      }\n    }\n    return [builder, SortedMap.empty(SortedMap.getOrder(map))]\n  })\n\n/** @internal */\nexport const takeOption = <A>(self: TPriorityQueue.TPriorityQueue<A>): STM.STM<Option.Option<A>> =>\n  core.effect<never, Option.Option<A>>((journal) => {\n    const map = pipe(self.ref, tRef.unsafeGet(journal))\n    return Option.match(SortedMap.headOption(map), {\n      onNone: (): Option.Option<A> => Option.none(),\n      onSome: ([key, value]) => {\n        const tail = value.slice(1)\n        tRef.unsafeSet(\n          self.ref,\n          tail.length > 0 ?\n            SortedMap.set(map, key, tail as [A, ...Array<A>]) :\n            SortedMap.remove(map, key),\n          journal\n        )\n        return Option.some(value[0])\n      }\n    })\n  })\n\n/** @internal */\nexport const takeUpTo = dual<\n  (n: number) => <A>(self: TPriorityQueue.TPriorityQueue<A>) => STM.STM<Array<A>>,\n  <A>(self: TPriorityQueue.TPriorityQueue<A>, n: number) => STM.STM<Array<A>>\n>(2, <A>(self: TPriorityQueue.TPriorityQueue<A>, n: number) =>\n  tRef.modify(self.ref, (map) => {\n    const builder: Array<A> = []\n    const iterator = map[Symbol.iterator]()\n    let updated = map\n    let index = 0\n    let next: IteratorResult<readonly [A, [A, ...Array<A>]], any>\n    while ((next = iterator.next()) && !next.done && index < n) {\n      const [key, value] = next.value\n      const [left, right] = pipe(value, Arr.splitAt(n - index))\n      for (const value of left) {\n        builder.push(value)\n      }\n      if (right.length > 0) {\n        updated = SortedMap.set(updated, key, right as [A, ...Array<A>])\n      } else {\n        updated = SortedMap.remove(updated, key)\n      }\n      index = index + left.length\n    }\n    return [builder, updated]\n  }))\n\n/** @internal */\nexport const toChunk = <A>(self: TPriorityQueue.TPriorityQueue<A>): STM.STM<Chunk.Chunk<A>> =>\n  tRef.modify(self.ref, (map) => {\n    const builder: Array<A> = []\n    for (const entry of map) {\n      for (const value of entry[1]) {\n        builder.push(value)\n      }\n    }\n    return [Chunk.unsafeFromArray(builder), map]\n  })\n\n/** @internal */\nexport const toArray = <A>(self: TPriorityQueue.TPriorityQueue<A>): STM.STM<Array<A>> =>\n  tRef.modify(self.ref, (map) => {\n    const builder: Array<A> = []\n    for (const entry of map) {\n      for (const value of entry[1]) {\n        builder.push(value)\n      }\n    }\n    return [builder, map]\n  })\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tPubSub.ts",
    "content": "import * as RA from \"../../Array.js\"\nimport * as Effect from \"../../Effect.js\"\nimport { dual, identity, pipe } from \"../../Function.js\"\nimport * as HashSet from \"../../HashSet.js\"\nimport * as Option from \"../../Option.js\"\nimport type * as Scope from \"../../Scope.js\"\nimport type * as STM from \"../../STM.js\"\nimport type * as TPubSub from \"../../TPubSub.js\"\nimport type * as TQueue from \"../../TQueue.js\"\nimport type * as TRef from \"../../TRef.js\"\nimport * as core from \"./core.js\"\nimport * as OpCodes from \"./opCodes/strategy.js\"\nimport * as stm from \"./stm.js\"\nimport * as tQueue from \"./tQueue.js\"\nimport * as tRef from \"./tRef.js\"\n\n/** @internal */\nconst TPubSubSymbolKey = \"effect/TPubSub\"\n\n/** @internal */\nexport const TPubSubTypeId: TPubSub.TPubSubTypeId = Symbol.for(TPubSubSymbolKey) as TPubSub.TPubSubTypeId\n\nconst AbsentValue = Symbol.for(\"effect/TPubSub/AbsentValue\")\ntype AbsentValue = typeof AbsentValue\n\n/** @internal */\nexport interface Node<in out A> {\n  readonly head: A | AbsentValue\n  readonly subscribers: number\n  readonly tail: TRef.TRef<Node<A> | undefined>\n}\n\n/** @internal */\nexport const makeNode = <A>(\n  head: A | AbsentValue,\n  subscribers: number,\n  tail: TRef.TRef<Node<A> | undefined>\n): Node<A> => ({\n  head,\n  subscribers,\n  tail\n})\n\n/** @internal */\nclass TPubSubImpl<in out A> implements TPubSub.TPubSub<A> {\n  readonly [TPubSubTypeId] = {\n    _A: (_: any) => _\n  }\n  readonly [tQueue.TEnqueueTypeId] = tQueue.tEnqueueVariance\n  constructor(\n    readonly pubsubSize: TRef.TRef<number>,\n    readonly publisherHead: TRef.TRef<TRef.TRef<Node<A> | undefined>>,\n    readonly publisherTail: TRef.TRef<TRef.TRef<Node<A> | undefined> | undefined>,\n    readonly requestedCapacity: number,\n    readonly strategy: tQueue.TQueueStrategy,\n    readonly subscriberCount: TRef.TRef<number>,\n    readonly subscribers: TRef.TRef<HashSet.HashSet<TRef.TRef<TRef.TRef<Node<A>> | undefined>>>\n  ) {}\n\n  isShutdown: STM.STM<boolean> = core.effect<never, boolean>((journal) => {\n    const currentPublisherTail = tRef.unsafeGet(this.publisherTail, journal)\n    return currentPublisherTail === undefined\n  })\n\n  awaitShutdown: STM.STM<void> = core.flatMap(\n    this.isShutdown,\n    (isShutdown) => isShutdown ? stm.void : core.retry\n  )\n\n  capacity(): number {\n    return this.requestedCapacity\n  }\n\n  size: STM.STM<number> = core.withSTMRuntime((runtime) => {\n    const currentPublisherTail = tRef.unsafeGet(this.publisherTail, runtime.journal)\n    if (currentPublisherTail === undefined) {\n      return core.interruptAs(runtime.fiberId)\n    }\n    return core.succeed(tRef.unsafeGet(this.pubsubSize, runtime.journal))\n  })\n\n  isEmpty: STM.STM<boolean> = core.map(this.size, (size) => size === 0)\n\n  isFull: STM.STM<boolean> = core.map(this.size, (size) => size === this.capacity())\n\n  offer(value: A): STM.STM<boolean> {\n    return core.withSTMRuntime((runtime) => {\n      const currentPublisherTail = tRef.unsafeGet(this.publisherTail, runtime.journal)\n      if (currentPublisherTail === undefined) {\n        return core.interruptAs(runtime.fiberId)\n      }\n      const currentSubscriberCount = tRef.unsafeGet(this.subscriberCount, runtime.journal)\n      if (currentSubscriberCount === 0) {\n        return core.succeed(true)\n      }\n      const currentPubSubSize = tRef.unsafeGet(this.pubsubSize, runtime.journal)\n      if (currentPubSubSize < this.requestedCapacity) {\n        const updatedPublisherTail: TRef.TRef<Node<A> | undefined> = new tRef.TRefImpl<Node<A> | undefined>(void 0)\n        const updatedNode = makeNode(value, currentSubscriberCount, updatedPublisherTail)\n        tRef.unsafeSet<Node<A> | undefined>(currentPublisherTail, updatedNode, runtime.journal)\n        tRef.unsafeSet<TRef.TRef<Node<A> | undefined> | undefined>(\n          this.publisherTail,\n          updatedPublisherTail,\n          runtime.journal\n        )\n        tRef.unsafeSet(this.pubsubSize, currentPubSubSize + 1, runtime.journal)\n        return core.succeed(true)\n      }\n      switch (this.strategy._tag) {\n        case OpCodes.OP_BACKPRESSURE_STRATEGY: {\n          return core.retry\n        }\n        case OpCodes.OP_DROPPING_STRATEGY: {\n          return core.succeed(false)\n        }\n        case OpCodes.OP_SLIDING_STRATEGY: {\n          if (this.requestedCapacity > 0) {\n            let currentPublisherHead: TRef.TRef<Node<A> | undefined> = tRef.unsafeGet(\n              this.publisherHead,\n              runtime.journal\n            )\n            let loop = true\n            while (loop) {\n              const node = tRef.unsafeGet(currentPublisherHead, runtime.journal)\n              if (node === undefined) {\n                return core.retry\n              }\n              const head = node.head\n              const tail = node.tail\n              if (head !== AbsentValue) {\n                const updatedNode = makeNode<A>(AbsentValue, node.subscribers, node.tail as any)\n                tRef.unsafeSet<Node<A> | undefined>(\n                  currentPublisherHead as any,\n                  updatedNode as any,\n                  runtime.journal\n                )\n                tRef.unsafeSet(this.publisherHead, tail, runtime.journal)\n                loop = false\n              } else {\n                currentPublisherHead = tail\n              }\n            }\n          }\n          const updatedPublisherTail: TRef.TRef<Node<A> | undefined> = new tRef.TRefImpl<Node<A> | undefined>(void 0)\n          const updatedNode = makeNode(value, currentSubscriberCount, updatedPublisherTail)\n          tRef.unsafeSet<Node<A> | undefined>(currentPublisherTail, updatedNode, runtime.journal)\n          tRef.unsafeSet<TRef.TRef<Node<A> | undefined> | undefined>(\n            this.publisherTail,\n            updatedPublisherTail,\n            runtime.journal\n          )\n          return core.succeed(true)\n        }\n      }\n    })\n  }\n\n  offerAll(iterable: Iterable<A>): STM.STM<boolean> {\n    return core.map(\n      stm.forEach(iterable, (a) => this.offer(a)),\n      RA.every(identity)\n    )\n  }\n\n  shutdown: STM.STM<void> = core.effect<never, void>((journal) => {\n    const currentPublisherTail = tRef.unsafeGet(this.publisherTail, journal)\n    if (currentPublisherTail !== undefined) {\n      tRef.unsafeSet<TRef.TRef<Node<A> | undefined> | undefined>(this.publisherTail, void 0, journal)\n      const currentSubscribers = tRef.unsafeGet(this.subscribers, journal)\n      HashSet.forEach(currentSubscribers, (subscriber) => {\n        tRef.unsafeSet<TRef.TRef<Node<A>> | undefined>(subscriber, void 0, journal)\n      })\n      tRef.unsafeSet(this.subscribers, HashSet.empty<TRef.TRef<TRef.TRef<Node<A>> | undefined>>(), journal)\n    }\n  })\n}\n\n/** @internal */\nclass TPubSubSubscriptionImpl<in out A> implements TQueue.TDequeue<A> {\n  readonly [TPubSubTypeId]: TPubSub.TPubSubTypeId = TPubSubTypeId\n  readonly [tQueue.TDequeueTypeId] = tQueue.tDequeueVariance\n  constructor(\n    readonly pubsubSize: TRef.TRef<number>,\n    readonly publisherHead: TRef.TRef<TRef.TRef<Node<A> | undefined>>,\n    readonly requestedCapacity: number,\n    readonly subscriberHead: TRef.TRef<TRef.TRef<Node<A> | undefined> | undefined>,\n    readonly subscriberCount: TRef.TRef<number>,\n    readonly subscribers: TRef.TRef<HashSet.HashSet<TRef.TRef<TRef.TRef<Node<A>> | undefined>>>\n  ) {}\n\n  isShutdown: STM.STM<boolean> = core.effect<never, boolean>((journal) => {\n    const currentSubscriberHead = tRef.unsafeGet(this.subscriberHead, journal)\n    return currentSubscriberHead === undefined\n  })\n\n  awaitShutdown: STM.STM<void> = core.flatMap(\n    this.isShutdown,\n    (isShutdown) => isShutdown ? stm.void : core.retry\n  )\n\n  capacity(): number {\n    return this.requestedCapacity\n  }\n\n  size: STM.STM<number> = core.withSTMRuntime((runtime) => {\n    let currentSubscriberHead = tRef.unsafeGet(this.subscriberHead, runtime.journal)\n    if (currentSubscriberHead === undefined) {\n      return core.interruptAs(runtime.fiberId)\n    }\n    let loop = true\n    let size = 0\n    while (loop) {\n      const node = tRef.unsafeGet(currentSubscriberHead, runtime.journal)\n      if (node === undefined) {\n        loop = false\n      } else {\n        const head = node.head\n        const tail: TRef.TRef<Node<A> | undefined> = node.tail\n        if (head !== AbsentValue) {\n          size = size + 1\n          if (size >= Number.MAX_SAFE_INTEGER) {\n            loop = false\n          }\n        }\n        currentSubscriberHead = tail\n      }\n    }\n    return core.succeed(size)\n  })\n\n  isEmpty: STM.STM<boolean> = core.map(this.size, (size) => size === 0)\n\n  isFull: STM.STM<boolean> = core.map(this.size, (size) => size === this.capacity())\n\n  peek: STM.STM<A> = core.withSTMRuntime((runtime) => {\n    let currentSubscriberHead = tRef.unsafeGet(this.subscriberHead, runtime.journal)\n    if (currentSubscriberHead === undefined) {\n      return core.interruptAs(runtime.fiberId)\n    }\n    let value: A | AbsentValue = AbsentValue\n    let loop = true\n    while (loop) {\n      const node = tRef.unsafeGet(currentSubscriberHead, runtime.journal)\n      if (node === undefined) {\n        return core.retry\n      }\n      const head = node.head\n      const tail: TRef.TRef<Node<A> | undefined> = node.tail\n      if (head !== AbsentValue) {\n        value = head\n        loop = false\n      } else {\n        currentSubscriberHead = tail\n      }\n    }\n    return core.succeed(value as A)\n  })\n\n  peekOption: STM.STM<Option.Option<A>> = core.withSTMRuntime((runtime) => {\n    let currentSubscriberHead = tRef.unsafeGet(this.subscriberHead, runtime.journal)\n    if (currentSubscriberHead === undefined) {\n      return core.interruptAs(runtime.fiberId)\n    }\n    let value: Option.Option<A> = Option.none()\n    let loop = true\n    while (loop) {\n      const node = tRef.unsafeGet(currentSubscriberHead, runtime.journal)\n      if (node === undefined) {\n        value = Option.none()\n        loop = false\n      } else {\n        const head = node.head\n        const tail: TRef.TRef<Node<A> | undefined> = node.tail\n        if (head !== AbsentValue) {\n          value = Option.some(head)\n          loop = false\n        } else {\n          currentSubscriberHead = tail\n        }\n      }\n    }\n    return core.succeed(value)\n  })\n\n  shutdown: STM.STM<void> = core.effect<never, void>((journal) => {\n    let currentSubscriberHead = tRef.unsafeGet(this.subscriberHead, journal)\n    if (currentSubscriberHead !== undefined) {\n      tRef.unsafeSet<TRef.TRef<Node<A> | undefined> | undefined>(this.subscriberHead, void 0, journal)\n      let loop = true\n      while (loop) {\n        const node = tRef.unsafeGet(currentSubscriberHead, journal)\n        if (node === undefined) {\n          loop = false\n        } else {\n          const head = node.head\n          const tail: TRef.TRef<Node<A> | undefined> = node.tail\n          if (head !== AbsentValue) {\n            const subscribers = node.subscribers\n            if (subscribers === 1) {\n              const size = tRef.unsafeGet(this.pubsubSize, journal)\n              const updatedNode = makeNode<A>(AbsentValue, 0, tail)\n              tRef.unsafeSet<Node<A> | undefined>(currentSubscriberHead, updatedNode, journal)\n              tRef.unsafeSet(this.publisherHead, tail as any, journal)\n              tRef.unsafeSet(this.pubsubSize, size - 1, journal)\n            } else {\n              const updatedNode = makeNode(head, subscribers - 1, tail)\n              tRef.unsafeSet<Node<A> | undefined>(currentSubscriberHead, updatedNode, journal)\n            }\n          }\n          currentSubscriberHead = tail\n        }\n      }\n      const currentSubscriberCount = tRef.unsafeGet(this.subscriberCount, journal)\n      tRef.unsafeSet(this.subscriberCount, currentSubscriberCount - 1, journal)\n      tRef.unsafeSet(\n        this.subscribers,\n        HashSet.remove(\n          tRef.unsafeGet(this.subscribers, journal),\n          this.subscriberHead as any\n        ),\n        journal\n      )\n    }\n  })\n\n  take: STM.STM<A> = core.withSTMRuntime((runtime) => {\n    let currentSubscriberHead = tRef.unsafeGet(this.subscriberHead, runtime.journal)\n    if (currentSubscriberHead === undefined) {\n      return core.interruptAs(runtime.fiberId)\n    }\n    let value: A | AbsentValue = AbsentValue\n    let loop = true\n    while (loop) {\n      const node = tRef.unsafeGet(currentSubscriberHead, runtime.journal)\n      if (node === undefined) {\n        return core.retry\n      }\n      const head = node.head\n      const tail: TRef.TRef<Node<A> | undefined> = node.tail\n      if (head !== AbsentValue) {\n        const subscribers = node.subscribers\n        if (subscribers === 1) {\n          const size = tRef.unsafeGet(this.pubsubSize, runtime.journal)\n          const updatedNode = makeNode<A>(AbsentValue, 0, tail)\n          tRef.unsafeSet<Node<A> | undefined>(currentSubscriberHead, updatedNode, runtime.journal)\n          tRef.unsafeSet(this.publisherHead, tail as any, runtime.journal)\n          tRef.unsafeSet(this.pubsubSize, size - 1, runtime.journal)\n        } else {\n          const updatedNode = makeNode(head, subscribers - 1, tail)\n          tRef.unsafeSet<Node<A> | undefined>(currentSubscriberHead, updatedNode, runtime.journal)\n        }\n        tRef.unsafeSet<TRef.TRef<Node<A> | undefined> | undefined>(\n          this.subscriberHead,\n          tail,\n          runtime.journal\n        )\n        value = head\n        loop = false\n      } else {\n        currentSubscriberHead = tail\n      }\n    }\n    return core.succeed(value as A)\n  })\n\n  takeAll: STM.STM<Array<A>> = this.takeUpTo(Number.POSITIVE_INFINITY)\n\n  takeUpTo(max: number): STM.STM<Array<A>> {\n    return core.withSTMRuntime((runtime) => {\n      let currentSubscriberHead = tRef.unsafeGet(this.subscriberHead, runtime.journal)\n      if (currentSubscriberHead === undefined) {\n        return core.interruptAs(runtime.fiberId)\n      }\n      const builder: Array<A> = []\n      let n = 0\n      while (n !== max) {\n        const node = tRef.unsafeGet(currentSubscriberHead, runtime.journal)\n        if (node === undefined) {\n          n = max\n        } else {\n          const head = node.head\n          const tail: TRef.TRef<Node<A> | undefined> = node.tail\n          if (head !== AbsentValue) {\n            const subscribers = node.subscribers\n            if (subscribers === 1) {\n              const size = tRef.unsafeGet(this.pubsubSize, runtime.journal)\n              const updatedNode = makeNode<A>(AbsentValue, 0, tail)\n              tRef.unsafeSet<Node<A> | undefined>(currentSubscriberHead, updatedNode, runtime.journal)\n              tRef.unsafeSet(this.publisherHead, tail as any, runtime.journal)\n              tRef.unsafeSet(this.pubsubSize, size - 1, runtime.journal)\n            } else {\n              const updatedNode = makeNode(head, subscribers - 1, tail)\n              tRef.unsafeSet<Node<A> | undefined>(currentSubscriberHead, updatedNode, runtime.journal)\n            }\n            builder.push(head)\n            n = n + 1\n          }\n          currentSubscriberHead = tail\n        }\n      }\n      tRef.unsafeSet<TRef.TRef<Node<A> | undefined> | undefined>(\n        this.subscriberHead,\n        currentSubscriberHead,\n        runtime.journal\n      )\n      return core.succeed(builder)\n    })\n  }\n}\n\n/** @internal */\nconst makeTPubSub = <A>(\n  requestedCapacity: number,\n  strategy: tQueue.TQueueStrategy\n): STM.STM<TPubSub.TPubSub<A>> =>\n  pipe(\n    stm.all([\n      tRef.make<Node<A> | undefined>(void 0),\n      tRef.make(0)\n    ]),\n    core.flatMap(([empty, pubsubSize]) =>\n      pipe(\n        stm.all([\n          tRef.make(empty),\n          tRef.make(empty),\n          tRef.make(0),\n          tRef.make(HashSet.empty())\n        ]),\n        core.map(([publisherHead, publisherTail, subscriberCount, subscribers]) =>\n          new TPubSubImpl(\n            pubsubSize,\n            publisherHead,\n            publisherTail as any,\n            requestedCapacity,\n            strategy,\n            subscriberCount,\n            subscribers as any\n          )\n        )\n      )\n    )\n  )\n\nconst makeSubscription = <A>(\n  pubsubSize: TRef.TRef<number>,\n  publisherHead: TRef.TRef<TRef.TRef<Node<A> | undefined>>,\n  publisherTail: TRef.TRef<TRef.TRef<Node<A> | undefined> | undefined>,\n  requestedCapacity: number,\n  subscriberCount: TRef.TRef<number>,\n  subscribers: TRef.TRef<HashSet.HashSet<TRef.TRef<TRef.TRef<Node<A>> | undefined>>>\n): STM.STM<TQueue.TDequeue<A>> =>\n  pipe(\n    tRef.get(publisherTail),\n    core.flatMap((currentPublisherTail) =>\n      pipe(\n        stm.all([\n          tRef.make(currentPublisherTail),\n          tRef.get(subscriberCount),\n          tRef.get(subscribers)\n        ]),\n        stm.tap(([_, currentSubscriberCount]) =>\n          pipe(\n            subscriberCount,\n            tRef.set(currentSubscriberCount + 1)\n          )\n        ),\n        stm.tap(([subscriberHead, _, currentSubscribers]) =>\n          pipe(\n            subscribers as any,\n            tRef.set(pipe(currentSubscribers as any, HashSet.add(subscriberHead)))\n          )\n        ),\n        core.map(([subscriberHead]) =>\n          new TPubSubSubscriptionImpl(\n            pubsubSize,\n            publisherHead,\n            requestedCapacity,\n            subscriberHead as any,\n            subscriberCount,\n            subscribers\n          )\n        )\n      )\n    )\n  )\n\n/** @internal */\nexport const awaitShutdown = <A>(self: TPubSub.TPubSub<A>): STM.STM<void> => self.awaitShutdown\n\n/** @internal */\nexport const bounded = <A>(requestedCapacity: number): STM.STM<TPubSub.TPubSub<A>> =>\n  makeTPubSub<A>(requestedCapacity, tQueue.BackPressure)\n\n/** @internal */\nexport const capacity = <A>(self: TPubSub.TPubSub<A>): number => self.capacity()\n\n/** @internal */\nexport const dropping = <A>(requestedCapacity: number): STM.STM<TPubSub.TPubSub<A>> =>\n  makeTPubSub<A>(requestedCapacity, tQueue.Dropping)\n\n/** @internal */\nexport const isEmpty = <A>(self: TPubSub.TPubSub<A>): STM.STM<boolean> => self.isEmpty\n\n/** @internal */\nexport const isFull = <A>(self: TPubSub.TPubSub<A>): STM.STM<boolean> => self.isFull\n\n/** @internal */\nexport const isShutdown = <A>(self: TPubSub.TPubSub<A>): STM.STM<boolean> => self.isShutdown\n\n/** @internal */\nexport const publish = dual<\n  <A>(value: A) => (self: TPubSub.TPubSub<A>) => STM.STM<boolean>,\n  <A>(self: TPubSub.TPubSub<A>, value: A) => STM.STM<boolean>\n>(2, (self, value) => self.offer(value))\n\n/** @internal */\nexport const publishAll = dual<\n  <A>(iterable: Iterable<A>) => (self: TPubSub.TPubSub<A>) => STM.STM<boolean>,\n  <A>(self: TPubSub.TPubSub<A>, iterable: Iterable<A>) => STM.STM<boolean>\n>(2, (self, iterable) => self.offerAll(iterable))\n\n/** @internal */\nexport const size = <A>(self: TPubSub.TPubSub<A>): STM.STM<number> => self.size\n\n/** @internal */\nexport const shutdown = <A>(self: TPubSub.TPubSub<A>): STM.STM<void> => self.shutdown\n\n/** @internal */\nexport const sliding = <A>(requestedCapacity: number): STM.STM<TPubSub.TPubSub<A>> =>\n  makeTPubSub<A>(requestedCapacity, tQueue.Sliding)\n\n/** @internal */\nexport const subscribe = <A>(self: TPubSub.TPubSub<A>): STM.STM<TQueue.TDequeue<A>> =>\n  makeSubscription(\n    self.pubsubSize,\n    self.publisherHead,\n    self.publisherTail,\n    self.requestedCapacity,\n    self.subscriberCount,\n    self.subscribers\n  )\n\n/** @internal */\nexport const subscribeScoped = <A>(self: TPubSub.TPubSub<A>): Effect.Effect<TQueue.TDequeue<A>, never, Scope.Scope> =>\n  Effect.acquireRelease(\n    subscribe(self),\n    (dequeue) => tQueue.shutdown(dequeue)\n  )\n\n/** @internal */\nexport const unbounded = <A>(): STM.STM<TPubSub.TPubSub<A>> => makeTPubSub<A>(Number.MAX_SAFE_INTEGER, tQueue.Dropping)\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tQueue.ts",
    "content": "import * as RA from \"../../Array.js\"\nimport * as Chunk from \"../../Chunk.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport { hasProperty, type Predicate } from \"../../Predicate.js\"\nimport type * as STM from \"../../STM.js\"\nimport type * as TQueue from \"../../TQueue.js\"\nimport type * as TRef from \"../../TRef.js\"\nimport * as core from \"./core.js\"\nimport * as OpCodes from \"./opCodes/strategy.js\"\nimport * as stm from \"./stm.js\"\nimport * as tRef from \"./tRef.js\"\n\nconst TEnqueueSymbolKey = \"effect/TQueue/TEnqueue\"\n\n/** @internal */\nexport const TEnqueueTypeId: TQueue.TEnqueueTypeId = Symbol.for(TEnqueueSymbolKey) as TQueue.TEnqueueTypeId\n\nconst TDequeueSymbolKey = \"effect/TQueue/TDequeue\"\n\n/** @internal */\nexport const TDequeueTypeId: TQueue.TDequeueTypeId = Symbol.for(TDequeueSymbolKey) as TQueue.TDequeueTypeId\n\n/**\n * A `Strategy` describes how the queue will handle values if the queue is at\n * capacity.\n *\n * @internal\n */\nexport type TQueueStrategy = BackPressure | Dropping | Sliding\n\n/**\n * A strategy that retries if the queue is at capacity.\n *\n * @internal\n */\nexport interface BackPressure {\n  readonly _tag: OpCodes.OP_BACKPRESSURE_STRATEGY\n}\n\n/**\n * A strategy that drops new values if the queue is at capacity.\n *\n * @internal\n */\nexport interface Dropping {\n  readonly _tag: OpCodes.OP_DROPPING_STRATEGY\n}\n\n/**\n * A strategy that drops old values if the queue is at capacity.\n *\n * @internal\n */\nexport interface Sliding {\n  readonly _tag: OpCodes.OP_SLIDING_STRATEGY\n}\n\n/** @internal */\nexport const BackPressure: TQueueStrategy = {\n  _tag: OpCodes.OP_BACKPRESSURE_STRATEGY\n}\n\n/** @internal */\nexport const Dropping: TQueueStrategy = {\n  _tag: OpCodes.OP_DROPPING_STRATEGY\n}\n\n/** @internal */\nexport const Sliding: TQueueStrategy = {\n  _tag: OpCodes.OP_SLIDING_STRATEGY\n}\n\n/** @internal */\nexport const tDequeueVariance = {\n  /* c8 ignore next */\n  _Out: (_: never) => _\n}\n\n/** @internal */\nexport const tEnqueueVariance = {\n  /* c8 ignore next */\n  _In: (_: unknown) => _\n}\n\nclass TQueueImpl<in out A> implements TQueue.TQueue<A> {\n  readonly [TDequeueTypeId] = tDequeueVariance\n  readonly [TEnqueueTypeId] = tEnqueueVariance\n  constructor(\n    readonly ref: TRef.TRef<Array<A> | undefined>,\n    readonly requestedCapacity: number,\n    readonly strategy: TQueueStrategy\n  ) {}\n\n  capacity(): number {\n    return this.requestedCapacity\n  }\n\n  size: STM.STM<number> = core.withSTMRuntime((runtime) => {\n    const queue = tRef.unsafeGet(this.ref, runtime.journal)\n    if (queue === undefined) {\n      return core.interruptAs(runtime.fiberId)\n    }\n    return core.succeed(queue.length)\n  })\n\n  isFull: STM.STM<boolean> = core.map(this.size, (size) => size === this.requestedCapacity)\n\n  isEmpty: STM.STM<boolean> = core.map(this.size, (size) => size === 0)\n\n  shutdown: STM.STM<void> = core.withSTMRuntime((runtime) => {\n    tRef.unsafeSet(this.ref, void 0, runtime.journal)\n    return stm.void\n  })\n\n  isShutdown: STM.STM<boolean> = core.effect<never, boolean>((journal) => {\n    const queue = tRef.unsafeGet(this.ref, journal)\n    return queue === undefined\n  })\n\n  awaitShutdown: STM.STM<void> = core.flatMap(\n    this.isShutdown,\n    (isShutdown) => isShutdown ? stm.void : core.retry\n  )\n\n  offer(value: A): STM.STM<boolean> {\n    return core.withSTMRuntime((runtime) => {\n      const queue = pipe(this.ref, tRef.unsafeGet(runtime.journal))\n      if (queue === undefined) {\n        return core.interruptAs(runtime.fiberId)\n      }\n      if (queue.length < this.requestedCapacity) {\n        queue.push(value)\n        tRef.unsafeSet(this.ref, queue, runtime.journal)\n        return core.succeed(true)\n      }\n      switch (this.strategy._tag) {\n        case OpCodes.OP_BACKPRESSURE_STRATEGY: {\n          return core.retry\n        }\n        case OpCodes.OP_DROPPING_STRATEGY: {\n          return core.succeed(false)\n        }\n        case OpCodes.OP_SLIDING_STRATEGY: {\n          if (queue.length === 0) {\n            return core.succeed(true)\n          }\n          queue.shift()\n          queue.push(value)\n          tRef.unsafeSet(this.ref, queue, runtime.journal)\n          return core.succeed(true)\n        }\n      }\n    })\n  }\n\n  offerAll(iterable: Iterable<A>): STM.STM<boolean> {\n    return core.withSTMRuntime((runtime) => {\n      const as = Array.from(iterable)\n      const queue = tRef.unsafeGet(this.ref, runtime.journal)\n      if (queue === undefined) {\n        return core.interruptAs(runtime.fiberId)\n      }\n      if (queue.length + as.length <= this.requestedCapacity) {\n        tRef.unsafeSet(this.ref, [...queue, ...as], runtime.journal)\n        return core.succeed(true)\n      }\n      switch (this.strategy._tag) {\n        case OpCodes.OP_BACKPRESSURE_STRATEGY: {\n          return core.retry\n        }\n        case OpCodes.OP_DROPPING_STRATEGY: {\n          const forQueue = as.slice(0, this.requestedCapacity - queue.length)\n          tRef.unsafeSet(this.ref, [...queue, ...forQueue], runtime.journal)\n          return core.succeed(false)\n        }\n        case OpCodes.OP_SLIDING_STRATEGY: {\n          const forQueue = as.slice(0, this.requestedCapacity - queue.length)\n          const toDrop = queue.length + forQueue.length - this.requestedCapacity\n          const newQueue = queue.slice(toDrop)\n          tRef.unsafeSet(this.ref, [...newQueue, ...forQueue], runtime.journal)\n          return core.succeed(true)\n        }\n      }\n    })\n  }\n\n  peek: STM.STM<A> = core.withSTMRuntime((runtime) => {\n    const queue = tRef.unsafeGet(this.ref, runtime.journal)\n    if (queue === undefined) {\n      return core.interruptAs(runtime.fiberId)\n    }\n    if (queue.length === 0) {\n      return core.retry\n    }\n    return core.succeed(queue[0])\n  })\n\n  peekOption: STM.STM<Option.Option<A>> = core.withSTMRuntime((runtime) => {\n    const queue = tRef.unsafeGet(this.ref, runtime.journal)\n    if (queue === undefined) {\n      return core.interruptAs(runtime.fiberId)\n    }\n    return core.succeed(Option.fromNullable(queue[0]))\n  })\n\n  take: STM.STM<A> = core.withSTMRuntime((runtime) => {\n    const queue = tRef.unsafeGet(this.ref, runtime.journal)\n    if (queue === undefined) {\n      return core.interruptAs(runtime.fiberId)\n    }\n    if (queue.length === 0) {\n      return core.retry\n    }\n    const dequeued = queue.shift()!\n    tRef.unsafeSet(this.ref, queue, runtime.journal)\n    return core.succeed(dequeued)\n  })\n\n  takeAll: STM.STM<Array<A>> = core.withSTMRuntime((runtime) => {\n    const queue = tRef.unsafeGet(this.ref, runtime.journal)\n    if (queue === undefined) {\n      return core.interruptAs(runtime.fiberId)\n    }\n    tRef.unsafeSet(this.ref, [], runtime.journal)\n    return core.succeed(queue)\n  })\n\n  takeUpTo(max: number): STM.STM<Array<A>> {\n    return core.withSTMRuntime((runtime) => {\n      const queue = tRef.unsafeGet(this.ref, runtime.journal)\n      if (queue === undefined) {\n        return core.interruptAs(runtime.fiberId)\n      }\n      const [toTake, remaining] = Chunk.splitAt(Chunk.unsafeFromArray(queue), max)\n      tRef.unsafeSet<Array<A> | undefined>(this.ref, Array.from(remaining), runtime.journal)\n      return core.succeed(Array.from(toTake))\n    })\n  }\n}\n\n/** @internal */\nexport const isTQueue = (u: unknown): u is TQueue.TQueue<unknown> => {\n  return isTEnqueue(u) && isTDequeue(u)\n}\n\n/** @internal */\nexport const isTEnqueue = (u: unknown): u is TQueue.TEnqueue<unknown> => hasProperty(u, TEnqueueTypeId)\n\n/** @internal */\nexport const isTDequeue = (u: unknown): u is TQueue.TDequeue<unknown> => hasProperty(u, TDequeueTypeId)\n\n/** @internal */\nexport const awaitShutdown = <A>(self: TQueue.TDequeue<A> | TQueue.TEnqueue<A>): STM.STM<void> => self.awaitShutdown\n\n/** @internal */\nexport const bounded = <A>(requestedCapacity: number): STM.STM<TQueue.TQueue<A>> =>\n  makeQueue<A>(requestedCapacity, BackPressure)\n\n/** @internal */\nexport const capacity = <A>(self: TQueue.TDequeue<A> | TQueue.TEnqueue<A>): number => {\n  return self.capacity()\n}\n\n/** @internal */\nexport const dropping = <A>(requestedCapacity: number): STM.STM<TQueue.TQueue<A>> =>\n  makeQueue<A>(requestedCapacity, Dropping)\n\n/** @internal */\nexport const isEmpty = <A>(self: TQueue.TDequeue<A> | TQueue.TEnqueue<A>): STM.STM<boolean> => self.isEmpty\n\n/** @internal */\nexport const isFull = <A>(self: TQueue.TDequeue<A> | TQueue.TEnqueue<A>): STM.STM<boolean> => self.isFull\n\n/** @internal */\nexport const isShutdown = <A>(self: TQueue.TDequeue<A> | TQueue.TEnqueue<A>): STM.STM<boolean> => self.isShutdown\n\n/** @internal */\nexport const offer = dual<\n  <A>(value: A) => (self: TQueue.TEnqueue<A>) => STM.STM<void>,\n  <A>(self: TQueue.TEnqueue<A>, value: A) => STM.STM<void>\n>(2, (self, value) => self.offer(value))\n\n/** @internal */\nexport const offerAll = dual<\n  <A>(iterable: Iterable<A>) => (self: TQueue.TEnqueue<A>) => STM.STM<boolean>,\n  <A>(self: TQueue.TEnqueue<A>, iterable: Iterable<A>) => STM.STM<boolean>\n>(2, (self, iterable) => self.offerAll(iterable))\n\n/** @internal */\nexport const peek = <A>(self: TQueue.TDequeue<A>): STM.STM<A> => self.peek\n\n/** @internal */\nexport const peekOption = <A>(self: TQueue.TDequeue<A>): STM.STM<Option.Option<A>> => self.peekOption\n\n/** @internal */\nexport const poll = <A>(self: TQueue.TDequeue<A>): STM.STM<Option.Option<A>> =>\n  pipe(self.takeUpTo(1), core.map(RA.head))\n\n/** @internal */\nexport const seek = dual<\n  <A>(predicate: Predicate<A>) => (self: TQueue.TDequeue<A>) => STM.STM<A>,\n  <A>(self: TQueue.TDequeue<A>, predicate: Predicate<A>) => STM.STM<A>\n>(2, (self, predicate) => seekLoop(self, predicate))\n\nconst seekLoop = <A>(self: TQueue.TDequeue<A>, predicate: Predicate<A>): STM.STM<A> =>\n  core.flatMap(\n    self.take,\n    (a) => predicate(a) ? core.succeed(a) : seekLoop(self, predicate)\n  )\n\n/** @internal */\nexport const shutdown = <A>(self: TQueue.TDequeue<A> | TQueue.TEnqueue<A>): STM.STM<void> => self.shutdown\n\n/** @internal */\nexport const size = <A>(self: TQueue.TDequeue<A> | TQueue.TEnqueue<A>): STM.STM<number> => self.size\n\n/** @internal */\nexport const sliding = <A>(requestedCapacity: number): STM.STM<TQueue.TQueue<A>> =>\n  makeQueue<A>(requestedCapacity, Sliding)\n\n/** @internal */\nexport const take = <A>(self: TQueue.TDequeue<A>): STM.STM<A> => self.take\n\n/** @internal */\nexport const takeAll = <A>(self: TQueue.TDequeue<A>): STM.STM<Array<A>> => self.takeAll\n\n/** @internal */\nexport const takeBetween = dual<\n  (min: number, max: number) => <A>(self: TQueue.TDequeue<A>) => STM.STM<Array<A>>,\n  <A>(self: TQueue.TDequeue<A>, min: number, max: number) => STM.STM<Array<A>>\n>(\n  3,\n  <A>(self: TQueue.TDequeue<A>, min: number, max: number): STM.STM<Array<A>> =>\n    stm.suspend(() => {\n      const takeRemainder = (\n        min: number,\n        max: number,\n        acc: Chunk.Chunk<A>\n      ): STM.STM<Chunk.Chunk<A>> => {\n        if (max < min) {\n          return core.succeed(acc)\n        }\n        return pipe(\n          self.takeUpTo(max),\n          core.flatMap((taken) => {\n            const remaining = min - taken.length\n            if (remaining === 1) {\n              return pipe(\n                self.take,\n                core.map((a) => pipe(acc, Chunk.appendAll(Chunk.unsafeFromArray(taken)), Chunk.append(a)))\n              )\n            }\n            if (remaining > 1) {\n              return pipe(\n                self.take,\n                core.flatMap((a) =>\n                  takeRemainder(\n                    remaining - 1,\n                    max - taken.length - 1,\n                    pipe(acc, Chunk.appendAll(Chunk.unsafeFromArray(taken)), Chunk.append(a))\n                  )\n                )\n              )\n            }\n            return core.succeed(pipe(acc, Chunk.appendAll(Chunk.unsafeFromArray(taken))))\n          })\n        )\n      }\n      return core.map(takeRemainder(min, max, Chunk.empty<A>()), (c) => Array.from(c))\n    })\n)\n\n/** @internal */\nexport const takeN = dual<\n  (n: number) => <A>(self: TQueue.TDequeue<A>) => STM.STM<Array<A>>,\n  <A>(self: TQueue.TDequeue<A>, n: number) => STM.STM<Array<A>>\n>(2, (self, n) => pipe(self, takeBetween(n, n)))\n\n/** @internal */\nexport const takeUpTo = dual<\n  (max: number) => <A>(self: TQueue.TDequeue<A>) => STM.STM<Array<A>>,\n  <A>(self: TQueue.TDequeue<A>, max: number) => STM.STM<Array<A>>\n>(2, (self, max) => self.takeUpTo(max))\n\n/** @internal */\nexport const unbounded = <A>(): STM.STM<TQueue.TQueue<A>> => makeQueue<A>(Number.MAX_SAFE_INTEGER, Dropping)\n\nconst makeQueue = <A>(requestedCapacity: number, strategy: TQueueStrategy): STM.STM<TQueue.TQueue<A>> =>\n  core.map(\n    tRef.make<Array<A> | undefined>([]),\n    (ref) => new TQueueImpl<A>(ref, requestedCapacity, strategy)\n  )\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tRandom.ts",
    "content": "import * as Context from \"../../Context.js\"\nimport { pipe } from \"../../Function.js\"\nimport * as Layer from \"../../Layer.js\"\nimport type * as STM from \"../../STM.js\"\nimport type * as TArray from \"../../TArray.js\"\nimport type * as TRandom from \"../../TRandom.js\"\nimport type * as TRef from \"../../TRef.js\"\nimport * as Random from \"../../Utils.js\"\nimport * as core from \"./core.js\"\nimport * as stm from \"./stm.js\"\nimport * as tArray from \"./tArray.js\"\nimport * as tRef from \"./tRef.js\"\n\nconst TRandomSymbolKey = \"effect/TRandom\"\n\n/** @internal */\nexport const TRandomTypeId: TRandom.TRandomTypeId = Symbol.for(\n  TRandomSymbolKey\n) as TRandom.TRandomTypeId\n\nconst randomInteger = (state: Random.PCGRandomState): [number, Random.PCGRandomState] => {\n  const prng = new Random.PCGRandom()\n  prng.setState(state)\n  return [prng.integer(0), prng.getState()]\n}\n\nconst randomIntegerBetween = (low: number, high: number) => {\n  return (state: Random.PCGRandomState): [number, Random.PCGRandomState] => {\n    const prng = new Random.PCGRandom()\n    prng.setState(state)\n    return [prng.integer(high - low) + low, prng.getState()]\n  }\n}\n\nconst randomNumber = (state: Random.PCGRandomState): [number, Random.PCGRandomState] => {\n  const prng = new Random.PCGRandom()\n  prng.setState(state)\n  return [prng.number(), prng.getState()]\n}\n\nconst withState = <A>(\n  state: TRef.TRef<Random.PCGRandomState>,\n  f: (state: Random.PCGRandomState) => [A, Random.PCGRandomState]\n): STM.STM<A> => {\n  return pipe(state, tRef.modify(f))\n}\n\nconst shuffleWith = <A>(\n  iterable: Iterable<A>,\n  nextIntBounded: (n: number) => STM.STM<number>\n): STM.STM<Array<A>> => {\n  const swap = (buffer: TArray.TArray<A>, index1: number, index2: number): STM.STM<void> =>\n    pipe(\n      buffer,\n      tArray.get(index1),\n      core.flatMap((tmp) =>\n        pipe(\n          buffer,\n          tArray.updateSTM(index1, () => pipe(buffer, tArray.get(index2))),\n          core.zipRight(\n            pipe(\n              buffer,\n              tArray.update(index2, () => tmp)\n            )\n          )\n        )\n      )\n    )\n  return pipe(\n    tArray.fromIterable(iterable),\n    core.flatMap((buffer) => {\n      const array: Array<number> = []\n      for (let i = array.length; i >= 2; i = i - 1) {\n        array.push(i)\n      }\n      return pipe(\n        array,\n        stm.forEach((n) => pipe(nextIntBounded(n), core.flatMap((k) => swap(buffer, n - 1, k))), { discard: true }),\n        core.zipRight(tArray.toArray(buffer))\n      )\n    })\n  )\n}\n\n/** @internal */\nexport const Tag = Context.GenericTag<TRandom.TRandom>(\"effect/TRandom\")\n\nclass TRandomImpl implements TRandom.TRandom {\n  readonly [TRandomTypeId]: TRandom.TRandomTypeId = TRandomTypeId\n  constructor(readonly state: TRef.TRef<Random.PCGRandomState>) {\n    this.next = withState(this.state, randomNumber)\n    this.nextBoolean = core.flatMap(this.next, (n) => core.succeed(n > 0.5))\n    this.nextInt = withState(this.state, randomInteger)\n  }\n\n  next: STM.STM<number>\n  nextBoolean: STM.STM<boolean>\n  nextInt: STM.STM<number>\n\n  nextRange(min: number, max: number): STM.STM<number> {\n    return core.flatMap(this.next, (n) => core.succeed((max - min) * n + min))\n  }\n  nextIntBetween(low: number, high: number): STM.STM<number> {\n    return withState(this.state, randomIntegerBetween(low, high))\n  }\n  shuffle<A>(elements: Iterable<A>): STM.STM<Array<A>> {\n    return shuffleWith(elements, (n) => this.nextIntBetween(0, n))\n  }\n}\n\n/** @internal */\nexport const live: Layer.Layer<TRandom.TRandom> = Layer.effect(\n  Tag,\n  pipe(\n    tRef.make(new Random.PCGRandom((Math.random() * 4294967296) >>> 0).getState()),\n    core.map((seed) => new TRandomImpl(seed)),\n    core.commit\n  )\n)\n\n/** @internal */\nexport const next: STM.STM<number, never, TRandom.TRandom> = core.flatMap(Tag, (random) => random.next)\n\n/** @internal */\nexport const nextBoolean: STM.STM<boolean, never, TRandom.TRandom> = core.flatMap(Tag, (random) => random.nextBoolean)\n\n/** @internal */\nexport const nextInt: STM.STM<number, never, TRandom.TRandom> = core.flatMap(Tag, (random) => random.nextInt)\n\n/** @internal */\nexport const nextIntBetween = (low: number, high: number): STM.STM<number, never, TRandom.TRandom> =>\n  core.flatMap(Tag, (random) => random.nextIntBetween(low, high))\n\n/** @internal */\nexport const nextRange = (min: number, max: number): STM.STM<number, never, TRandom.TRandom> =>\n  core.flatMap(Tag, (random) => random.nextRange(min, max))\n\n/** @internal */\nexport const shuffle = <A>(elements: Iterable<A>): STM.STM<Array<A>, never, TRandom.TRandom> =>\n  core.flatMap(Tag, (random) => random.shuffle(elements))\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tReentrantLock.ts",
    "content": "import * as Effect from \"../../Effect.js\"\nimport * as Equal from \"../../Equal.js\"\nimport * as FiberId from \"../../FiberId.js\"\nimport { dual } from \"../../Function.js\"\nimport * as HashMap from \"../../HashMap.js\"\nimport * as Option from \"../../Option.js\"\nimport type * as Scope from \"../../Scope.js\"\nimport type * as STM from \"../../STM.js\"\nimport type * as TReentrantLock from \"../../TReentrantLock.js\"\nimport type * as TRef from \"../../TRef.js\"\nimport * as core from \"./core.js\"\nimport * as tRef from \"./tRef.js\"\n\nconst TReentrantLockSymbolKey = \"effect/TReentrantLock\"\n\n/** @internal */\nexport const TReentrantLockTypeId: TReentrantLock.TReentrantLockTypeId = Symbol.for(\n  TReentrantLockSymbolKey\n) as TReentrantLock.TReentrantLockTypeId\n\nconst WriteLockTypeId = Symbol.for(\"effect/TReentrantLock/WriteLock\")\n\ntype WriteLockTypeId = typeof WriteLockTypeId\n\nconst ReadLockTypeId = Symbol.for(\"effect/TReentrantLock/ReadLock\")\n\ntype ReadLockTypeId = typeof ReadLockTypeId\n\nclass TReentranLockImpl implements TReentrantLock.TReentrantLock {\n  readonly [TReentrantLockTypeId]: TReentrantLock.TReentrantLockTypeId = TReentrantLockTypeId\n  constructor(readonly state: TRef.TRef<LockState>) {}\n}\n\n/** @internal */\nexport interface LockState {\n  /**\n   * Computes the total number of read locks acquired.\n   */\n  readonly readLocks: number\n  /**\n   * Computes the total number of write locks acquired.\n   */\n  readonly writeLocks: number\n  /**\n   * Computes the number of read locks held by the specified fiber id.\n   */\n  readLocksHeld(fiberId: FiberId.FiberId): number\n  /**\n   * Computes the number of write locks held by the specified fiber id.\n   */\n  writeLocksHeld(fiberId: FiberId.FiberId): number\n}\n\n/**\n * This data structure describes the state of the lock when multiple fibers\n * have acquired read locks. The state is tracked as a map from fiber identity\n * to number of read locks acquired by the fiber. This level of detail permits\n * upgrading a read lock to a write lock.\n *\n * @internal\n */\nexport class ReadLock implements LockState {\n  readonly [ReadLockTypeId]: ReadLockTypeId = ReadLockTypeId\n  constructor(readonly readers: HashMap.HashMap<FiberId.FiberId, number>) {}\n  get readLocks(): number {\n    return Array.from(this.readers).reduce((acc, curr) => acc + curr[1], 0)\n  }\n  get writeLocks(): number {\n    return 0\n  }\n  readLocksHeld(fiberId: FiberId.FiberId): number {\n    return Option.getOrElse(\n      HashMap.get(this.readers, fiberId),\n      () => 0\n    )\n  }\n  writeLocksHeld(_fiberId: FiberId.FiberId): number {\n    return 0\n  }\n}\n\n/**\n * This data structure describes the state of the lock when a single fiber has\n * a write lock. The fiber has an identity, and may also have acquired a\n * certain number of read locks.\n *\n * @internal\n */\nexport class WriteLock implements LockState {\n  readonly [WriteLockTypeId]: WriteLockTypeId = WriteLockTypeId\n  constructor(\n    readonly readLocks: number,\n    readonly writeLocks: number,\n    readonly fiberId: FiberId.FiberId\n  ) {}\n  readLocksHeld(fiberId: FiberId.FiberId): number {\n    return Equal.equals(fiberId)(this.fiberId) ? this.readLocks : 0\n  }\n  writeLocksHeld(fiberId: FiberId.FiberId): number {\n    return Equal.equals(fiberId)(this.fiberId) ? this.writeLocks : 0\n  }\n}\n\nconst isReadLock = (lock: LockState): lock is ReadLock => {\n  return ReadLockTypeId in lock\n}\n\nconst isWriteLock = (lock: LockState): lock is WriteLock => {\n  return WriteLockTypeId in lock\n}\n\n/**\n * An empty read lock state, in which no fiber holds any read locks.\n */\nconst emptyReadLock = new ReadLock(HashMap.empty())\n\n/**\n * Creates a new read lock where the specified fiber holds the specified\n * number of read locks.\n */\nconst makeReadLock = (fiberId: FiberId.FiberId, count: number): ReadLock => {\n  if (count <= 0) {\n    return emptyReadLock\n  }\n  return new ReadLock(HashMap.make([fiberId, count]))\n}\n\n/**\n * Determines if there is no other holder of read locks aside from the\n * specified fiber id. If there are no other holders of read locks aside\n * from the specified fiber id, then it is safe to upgrade the read lock\n * into a write lock.\n */\nconst noOtherHolder = (readLock: ReadLock, fiberId: FiberId.FiberId): boolean => {\n  return HashMap.isEmpty(readLock.readers) ||\n    (HashMap.size(readLock.readers) === 1 && HashMap.has(readLock.readers, fiberId))\n}\n\n/**\n * Adjusts the number of read locks held by the specified fiber id.\n */\nconst adjustReadLock = (readLock: ReadLock, fiberId: FiberId.FiberId, adjustment: number): ReadLock => {\n  const total = readLock.readLocksHeld(fiberId)\n  const newTotal = total + adjustment\n  if (newTotal < 0) {\n    throw new Error(\n      \"BUG - TReentrantLock.ReadLock.adjust - please report an issue at https://github.com/Effect-TS/effect/issues\"\n    )\n  }\n  if (newTotal === 0) {\n    return new ReadLock(HashMap.remove(readLock.readers, fiberId))\n  }\n  return new ReadLock(HashMap.set(readLock.readers, fiberId, newTotal))\n}\n\nconst adjustRead = (self: TReentrantLock.TReentrantLock, delta: number): STM.STM<number> =>\n  core.withSTMRuntime((runtime) => {\n    const lock = tRef.unsafeGet(self.state, runtime.journal)\n    if (isReadLock(lock)) {\n      const result = adjustReadLock(lock, runtime.fiberId, delta)\n      tRef.unsafeSet(self.state, result, runtime.journal)\n      return core.succeed(result.readLocksHeld(runtime.fiberId))\n    }\n    if (isWriteLock(lock) && Equal.equals(runtime.fiberId)(lock.fiberId)) {\n      const newTotal = lock.readLocks + delta\n      if (newTotal < 0) {\n        throw new Error(\n          `Defect: Fiber ${\n            FiberId.threadName(runtime.fiberId)\n          } releasing read locks it does not hold, newTotal: ${newTotal}`\n        )\n      }\n      tRef.unsafeSet(\n        self.state,\n        new WriteLock(newTotal, lock.writeLocks, runtime.fiberId),\n        runtime.journal\n      )\n      return core.succeed(newTotal)\n    }\n    return core.retry\n  })\n\n/** @internal */\nexport const acquireRead = (self: TReentrantLock.TReentrantLock): STM.STM<number> => adjustRead(self, 1)\n\n/** @internal */\nexport const acquireWrite = (self: TReentrantLock.TReentrantLock): STM.STM<number> =>\n  core.withSTMRuntime((runtime) => {\n    const lock = tRef.unsafeGet(self.state, runtime.journal)\n    if (isReadLock(lock) && noOtherHolder(lock, runtime.fiberId)) {\n      tRef.unsafeSet(\n        self.state,\n        new WriteLock(lock.readLocksHeld(runtime.fiberId), 1, runtime.fiberId),\n        runtime.journal\n      )\n      return core.succeed(1)\n    }\n    if (isWriteLock(lock) && Equal.equals(runtime.fiberId)(lock.fiberId)) {\n      tRef.unsafeSet(\n        self.state,\n        new WriteLock(lock.readLocks, lock.writeLocks + 1, runtime.fiberId),\n        runtime.journal\n      )\n      return core.succeed(lock.writeLocks + 1)\n    }\n    return core.retry\n  })\n\n/** @internal */\nexport const fiberReadLocks = (self: TReentrantLock.TReentrantLock): STM.STM<number> =>\n  core.effect<never, number>((journal, fiberId) =>\n    tRef.unsafeGet(\n      self.state,\n      journal\n    ).readLocksHeld(fiberId)\n  )\n\n/** @internal */\nexport const fiberWriteLocks = (self: TReentrantLock.TReentrantLock): STM.STM<number> =>\n  core.effect<never, number>((journal, fiberId) =>\n    tRef.unsafeGet(\n      self.state,\n      journal\n    ).writeLocksHeld(fiberId)\n  )\n\n/** @internal */\nexport const lock = (self: TReentrantLock.TReentrantLock): Effect.Effect<number, never, Scope.Scope> => writeLock(self)\n\n/** @internal */\nexport const locked = (self: TReentrantLock.TReentrantLock): STM.STM<boolean> =>\n  core.zipWith(\n    readLocked(self),\n    writeLocked(self),\n    (x, y) => x || y\n  )\n\n/** @internal */\nexport const make: STM.STM<TReentrantLock.TReentrantLock> = core.map(\n  tRef.make<LockState>(emptyReadLock),\n  (readLock) => new TReentranLockImpl(readLock)\n)\n\n/** @internal */\nexport const readLock = (self: TReentrantLock.TReentrantLock): Effect.Effect<number, never, Scope.Scope> =>\n  Effect.acquireRelease(\n    core.commit(acquireRead(self)),\n    () => core.commit(releaseRead(self))\n  )\n\n/** @internal */\nexport const readLocks = (self: TReentrantLock.TReentrantLock): STM.STM<number> =>\n  core.map(\n    tRef.get(self.state),\n    (state) => state.readLocks\n  )\n\n/** @internal */\nexport const readLocked = (self: TReentrantLock.TReentrantLock): STM.STM<boolean> =>\n  core.map(\n    tRef.get(self.state),\n    (state) => state.readLocks > 0\n  )\n\n/** @internal */\nexport const releaseRead = (self: TReentrantLock.TReentrantLock): STM.STM<number> => adjustRead(self, -1)\n\n/** @internal */\nexport const releaseWrite = (self: TReentrantLock.TReentrantLock): STM.STM<number> =>\n  core.withSTMRuntime((runtime) => {\n    const lock = tRef.unsafeGet(self.state, runtime.journal)\n    if (isWriteLock(lock) && lock.writeLocks === 1 && Equal.equals(runtime.fiberId)(lock.fiberId)) {\n      const result = makeReadLock(lock.fiberId, lock.readLocks)\n      tRef.unsafeSet(self.state, result, runtime.journal)\n      return core.succeed(result.writeLocksHeld(runtime.fiberId))\n    }\n    if (isWriteLock(lock) && Equal.equals(runtime.fiberId)(lock.fiberId)) {\n      const result = new WriteLock(lock.readLocks, lock.writeLocks - 1, runtime.fiberId)\n      tRef.unsafeSet(self.state, result, runtime.journal)\n      return core.succeed(result.writeLocksHeld(runtime.fiberId))\n    }\n    throw new Error(\n      `Defect: Fiber ${FiberId.threadName(runtime.fiberId)} releasing write lock it does not hold`\n    )\n  })\n\n/** @internal */\nexport const withLock = dual<\n  (\n    self: TReentrantLock.TReentrantLock\n  ) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    self: TReentrantLock.TReentrantLock\n  ) => Effect.Effect<A, E, R>\n>(2, (effect, self) => withWriteLock(effect, self))\n\n/** @internal */\nexport const withReadLock = dual<\n  (self: TReentrantLock.TReentrantLock) => <A, E, R>(\n    effect: Effect.Effect<A, E, R>\n  ) => Effect.Effect<A, E, R>,\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    self: TReentrantLock.TReentrantLock\n  ) => Effect.Effect<A, E, R>\n>(2, (effect, self) =>\n  Effect.uninterruptibleMask((restore) =>\n    Effect.zipRight(\n      restore(core.commit(acquireRead(self))),\n      Effect.ensuring(\n        effect,\n        core.commit(releaseRead(self))\n      )\n    )\n  ))\n\n/** @internal */\nexport const withWriteLock = dual<\n  (self: TReentrantLock.TReentrantLock) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(effect: Effect.Effect<A, E, R>, self: TReentrantLock.TReentrantLock) => Effect.Effect<A, E, R>\n>(2, (effect, self) =>\n  Effect.uninterruptibleMask((restore) =>\n    Effect.zipRight(\n      restore(core.commit(acquireWrite(self))),\n      Effect.ensuring(\n        effect,\n        core.commit(releaseWrite(self))\n      )\n    )\n  ))\n\n/** @internal */\nexport const writeLock = (self: TReentrantLock.TReentrantLock): Effect.Effect<number, never, Scope.Scope> =>\n  Effect.acquireRelease(\n    core.commit(acquireWrite(self)),\n    () => core.commit(releaseWrite(self))\n  )\n\n/** @internal */\nexport const writeLocked = (self: TReentrantLock.TReentrantLock): STM.STM<boolean> =>\n  core.map(\n    tRef.get(self.state),\n    (state) => state.writeLocks > 0\n  )\n\n/** @internal */\nexport const writeLocks = (self: TReentrantLock.TReentrantLock): STM.STM<number> =>\n  core.map(\n    tRef.get(self.state),\n    (state) => state.writeLocks\n  )\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tRef.ts",
    "content": "import { dual } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport type { Pipeable } from \"../../Pipeable.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport type * as STM from \"../../STM.js\"\nimport type * as TRef from \"../../TRef.js\"\nimport * as core from \"./core.js\"\nimport * as Entry from \"./entry.js\"\nimport type * as Journal from \"./journal.js\"\nimport type * as TxnId from \"./txnId.js\"\nimport * as Versioned from \"./versioned.js\"\n\n/** @internal */\nconst TRefSymbolKey = \"effect/TRef\"\n\n/** @internal */\nexport const TRefTypeId: TRef.TRefTypeId = Symbol.for(\n  TRefSymbolKey\n) as TRef.TRefTypeId\n\nexport const tRefVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nexport class TRefImpl<in out A> implements TRef.TRef<A>, Pipeable {\n  readonly [TRefTypeId] = tRefVariance\n  /** @internal */\n  todos: Map<TxnId.TxnId, Journal.Todo>\n  /** @internal */\n  versioned: Versioned.Versioned<A>\n  constructor(value: A) {\n    this.versioned = new Versioned.Versioned(value)\n    this.todos = new Map()\n  }\n  modify<B>(f: (a: A) => readonly [B, A]): STM.STM<B> {\n    return core.effect<never, B>((journal) => {\n      const entry = getOrMakeEntry(this, journal)\n      const [retValue, newValue] = f(Entry.unsafeGet(entry) as A)\n      Entry.unsafeSet(entry, newValue)\n      return retValue\n    })\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const make = <A>(value: A): STM.STM<TRef.TRef<A>> =>\n  core.effect<never, TRef.TRef<A>>((journal) => {\n    const ref = new TRefImpl(value)\n    journal.set(ref, Entry.make(ref, true))\n    return ref\n  })\n\n/** @internal */\nexport const get = <A>(self: TRef.TRef<A>) => self.modify((a) => [a, a])\n\n/** @internal */\nexport const set = dual<\n  <A>(value: A) => (self: TRef.TRef<A>) => STM.STM<void>,\n  <A>(self: TRef.TRef<A>, value: A) => STM.STM<void>\n>(\n  2,\n  <A>(self: TRef.TRef<A>, value: A): STM.STM<void> => self.modify((): [void, A] => [void 0, value])\n)\n\n/** @internal */\nexport const getAndSet = dual<\n  <A>(value: A) => (self: TRef.TRef<A>) => STM.STM<A>,\n  <A>(self: TRef.TRef<A>, value: A) => STM.STM<A>\n>(2, (self, value) => self.modify((a) => [a, value]))\n\n/** @internal */\nexport const getAndUpdate = dual<\n  <A>(f: (a: A) => A) => (self: TRef.TRef<A>) => STM.STM<A>,\n  <A>(self: TRef.TRef<A>, f: (a: A) => A) => STM.STM<A>\n>(2, (self, f) => self.modify((a) => [a, f(a)]))\n\n/** @internal */\nexport const getAndUpdateSome = dual<\n  <A>(f: (a: A) => Option.Option<A>) => (self: TRef.TRef<A>) => STM.STM<A>,\n  <A>(self: TRef.TRef<A>, f: (a: A) => Option.Option<A>) => STM.STM<A>\n>(2, (self, f) =>\n  self.modify((a) =>\n    Option.match(f(a), {\n      onNone: () => [a, a],\n      onSome: (b) => [a, b]\n    })\n  ))\n\n/** @internal */\nexport const setAndGet = dual<\n  <A>(value: A) => (self: TRef.TRef<A>) => STM.STM<A>,\n  <A>(self: TRef.TRef<A>, value: A) => STM.STM<A>\n>(2, (self, value) => self.modify(() => [value, value]))\n\n/** @internal */\nexport const modify = dual<\n  <A, B>(f: (a: A) => readonly [B, A]) => (self: TRef.TRef<A>) => STM.STM<B>,\n  <A, B>(self: TRef.TRef<A>, f: (a: A) => readonly [B, A]) => STM.STM<B>\n>(2, (self, f) => self.modify(f))\n\n/** @internal */\nexport const modifySome = dual<\n  <A, B>(fallback: B, f: (a: A) => Option.Option<readonly [B, A]>) => (self: TRef.TRef<A>) => STM.STM<B>,\n  <A, B>(self: TRef.TRef<A>, fallback: B, f: (a: A) => Option.Option<readonly [B, A]>) => STM.STM<B>\n>(3, (self, fallback, f) =>\n  self.modify((a) =>\n    Option.match(f(a), {\n      onNone: () => [fallback, a],\n      onSome: (b) => b\n    })\n  ))\n\n/** @internal */\nexport const update = dual<\n  <A>(f: (a: A) => A) => (self: TRef.TRef<A>) => STM.STM<void>,\n  <A>(self: TRef.TRef<A>, f: (a: A) => A) => STM.STM<void>\n>(2, (self, f) => self.modify((a) => [void 0, f(a)]))\n\n/** @internal */\nexport const updateAndGet = dual<\n  <A>(f: (a: A) => A) => (self: TRef.TRef<A>) => STM.STM<A>,\n  <A>(self: TRef.TRef<A>, f: (a: A) => A) => STM.STM<A>\n>(2, (self, f) =>\n  self.modify((a) => {\n    const b = f(a)\n    return [b, b]\n  }))\n\n/** @internal */\nexport const updateSome = dual<\n  <A>(f: (a: A) => Option.Option<A>) => (self: TRef.TRef<A>) => STM.STM<void>,\n  <A>(self: TRef.TRef<A>, f: (a: A) => Option.Option<A>) => STM.STM<void>\n>(\n  2,\n  (self, f) =>\n    self.modify((a) => [\n      void 0,\n      Option.match(f(a), {\n        onNone: () => a,\n        onSome: (b) => b\n      })\n    ])\n)\n\n/** @internal */\nexport const updateSomeAndGet = dual<\n  <A>(f: (a: A) => Option.Option<A>) => (self: TRef.TRef<A>) => STM.STM<A>,\n  <A>(self: TRef.TRef<A>, f: (a: A) => Option.Option<A>) => STM.STM<A>\n>(\n  2,\n  (self, f) =>\n    self.modify((a) =>\n      Option.match(f(a), {\n        onNone: () => [a, a],\n        onSome: (b) => [b, b]\n      })\n    )\n)\n\n/** @internal */\nconst getOrMakeEntry = <A>(self: TRef.TRef<A>, journal: Journal.Journal): Entry.Entry => {\n  if (journal.has(self)) {\n    return journal.get(self)!\n  }\n  const entry = Entry.make(self, false)\n  journal.set(self, entry)\n  return entry\n}\n\n/** @internal */\nexport const unsafeGet: {\n  (journal: Journal.Journal): <A>(self: TRef.TRef<A>) => A\n  <A>(self: TRef.TRef<A>, journal: Journal.Journal): A\n} = dual<\n  (journal: Journal.Journal) => <A>(self: TRef.TRef<A>) => A,\n  <A>(self: TRef.TRef<A>, journal: Journal.Journal) => A\n>(2, <A>(self: TRef.TRef<A>, journal: Journal.Journal) => Entry.unsafeGet(getOrMakeEntry(self, journal)) as A)\n\n/** @internal */\nexport const unsafeSet: {\n  <A>(value: A, journal: Journal.Journal): (self: TRef.TRef<A>) => void\n  <A>(self: TRef.TRef<A>, value: A, journal: Journal.Journal): void\n} = dual<\n  <A>(value: A, journal: Journal.Journal) => (self: TRef.TRef<A>) => void,\n  <A>(self: TRef.TRef<A>, value: A, journal: Journal.Journal) => void\n>(3, (self, value, journal) => {\n  const entry = getOrMakeEntry(self, journal)\n  Entry.unsafeSet(entry, value)\n  return undefined\n})\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tSemaphore.ts",
    "content": "import * as Cause from \"../../Cause.js\"\nimport * as Effect from \"../../Effect.js\"\nimport { dual } from \"../../Function.js\"\nimport type * as Scope from \"../../Scope.js\"\nimport * as STM from \"../../STM.js\"\nimport type * as TRef from \"../../TRef.js\"\nimport type * as TSemaphore from \"../../TSemaphore.js\"\nimport * as core from \"./core.js\"\nimport * as tRef from \"./tRef.js\"\n\n/** @internal */\nconst TSemaphoreSymbolKey = \"effect/TSemaphore\"\n\n/** @internal */\nexport const TSemaphoreTypeId: TSemaphore.TSemaphoreTypeId = Symbol.for(\n  TSemaphoreSymbolKey\n) as TSemaphore.TSemaphoreTypeId\n\n/** @internal */\nclass TSemaphoreImpl implements TSemaphore.TSemaphore {\n  readonly [TSemaphoreTypeId]: TSemaphore.TSemaphoreTypeId = TSemaphoreTypeId\n  constructor(readonly permits: TRef.TRef<number>) {}\n}\n\n/** @internal */\nexport const make = (permits: number): STM.STM<TSemaphore.TSemaphore> =>\n  STM.map(tRef.make(permits), (permits) => new TSemaphoreImpl(permits))\n\n/** @internal */\nexport const acquire = (self: TSemaphore.TSemaphore): STM.STM<void> => acquireN(self, 1)\n\n/** @internal */\nexport const acquireN = dual<\n  (n: number) => (self: TSemaphore.TSemaphore) => STM.STM<void>,\n  (self: TSemaphore.TSemaphore, n: number) => STM.STM<void>\n>(2, (self, n) =>\n  core.withSTMRuntime((driver) => {\n    if (n < 0) {\n      throw new Cause.IllegalArgumentException(`Unexpected negative value ${n} passed to Semaphore.acquireN`)\n    }\n    const value = tRef.unsafeGet(self.permits, driver.journal)\n    if (value < n) {\n      return STM.retry\n    } else {\n      return STM.succeed(tRef.unsafeSet(self.permits, value - n, driver.journal))\n    }\n  }))\n\n/** @internal */\nexport const available = (self: TSemaphore.TSemaphore) => tRef.get(self.permits)\n\n/** @internal */\nexport const release = (self: TSemaphore.TSemaphore): STM.STM<void> => releaseN(self, 1)\n\n/** @internal */\nexport const releaseN = dual<\n  (n: number) => (self: TSemaphore.TSemaphore) => STM.STM<void>,\n  (self: TSemaphore.TSemaphore, n: number) => STM.STM<void>\n>(2, (self, n) =>\n  core.withSTMRuntime((driver) => {\n    if (n < 0) {\n      throw new Cause.IllegalArgumentException(`Unexpected negative value ${n} passed to Semaphore.releaseN`)\n    }\n    const current = tRef.unsafeGet(self.permits, driver.journal)\n    return STM.succeed(tRef.unsafeSet(self.permits, current + n, driver.journal))\n  }))\n\n/** @internal */\nexport const withPermit = dual<\n  (semaphore: TSemaphore.TSemaphore) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(self: Effect.Effect<A, E, R>, semaphore: TSemaphore.TSemaphore) => Effect.Effect<A, E, R>\n>(2, (self, semaphore) => withPermits(self, semaphore, 1))\n\n/** @internal */\nexport const withPermits = dual<\n  (\n    semaphore: TSemaphore.TSemaphore,\n    permits: number\n  ) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>,\n  <A, E, R>(\n    self: Effect.Effect<A, E, R>,\n    semaphore: TSemaphore.TSemaphore,\n    permits: number\n  ) => Effect.Effect<A, E, R>\n>(3, (self, semaphore, permits) =>\n  Effect.uninterruptibleMask((restore) =>\n    Effect.zipRight(\n      restore(core.commit(acquireN(permits)(semaphore))),\n      Effect.ensuring(\n        self,\n        core.commit(releaseN(permits)(semaphore))\n      )\n    )\n  ))\n\n/** @internal */\nexport const withPermitScoped = (self: TSemaphore.TSemaphore): Effect.Effect<void, never, Scope.Scope> =>\n  withPermitsScoped(self, 1)\n\n/** @internal */\nexport const withPermitsScoped = dual<\n  (permits: number) => (self: TSemaphore.TSemaphore) => Effect.Effect<void, never, Scope.Scope>,\n  (self: TSemaphore.TSemaphore, permits: number) => Effect.Effect<void, never, Scope.Scope>\n>(2, (self, permits) =>\n  Effect.acquireReleaseInterruptible(\n    core.commit(acquireN(self, permits)),\n    () => core.commit(releaseN(self, permits))\n  ))\n\n/** @internal */\nexport const unsafeMakeSemaphore = (permits: number): TSemaphore.TSemaphore => {\n  return new TSemaphoreImpl(new tRef.TRefImpl(permits))\n}\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tSet.ts",
    "content": "import * as RA from \"../../Array.js\"\nimport * as Chunk from \"../../Chunk.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as HashSet from \"../../HashSet.js\"\nimport type * as Option from \"../../Option.js\"\nimport { hasProperty, type Predicate } from \"../../Predicate.js\"\nimport * as STM from \"../../STM.js\"\nimport type * as TMap from \"../../TMap.js\"\nimport type * as TSet from \"../../TSet.js\"\nimport * as core from \"./core.js\"\nimport * as tMap from \"./tMap.js\"\n\n/** @internal */\nconst TSetSymbolKey = \"effect/TSet\"\n\n/** @internal */\nexport const TSetTypeId: TSet.TSetTypeId = Symbol.for(\n  TSetSymbolKey\n) as TSet.TSetTypeId\n\nconst tSetVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nclass TSetImpl<in out A> implements TSet.TSet<A> {\n  readonly [TSetTypeId] = tSetVariance\n  constructor(readonly tMap: TMap.TMap<A, void>) {}\n}\n\nconst isTSet = (u: unknown) => hasProperty(u, TSetTypeId)\n\n/** @internal */\nexport const add = dual<\n  <A>(value: A) => (self: TSet.TSet<A>) => STM.STM<void>,\n  <A>(self: TSet.TSet<A>, value: A) => STM.STM<void>\n>(2, (self, value) => tMap.set(self.tMap, value, void 0 as void))\n\n/** @internal */\nexport const difference = dual<\n  <A>(other: TSet.TSet<A>) => (self: TSet.TSet<A>) => STM.STM<void>,\n  <A>(self: TSet.TSet<A>, other: TSet.TSet<A>) => STM.STM<void>\n>(2, (self, other) =>\n  core.flatMap(\n    toHashSet(other),\n    (values) => removeIf(self, (value) => HashSet.has(values, value), { discard: true })\n  ))\n\n/** @internal */\nexport const empty = <A>(): STM.STM<TSet.TSet<A>> => fromIterable<A>([])\n\n/** @internal */\nexport const forEach = dual<\n  <A, R, E>(f: (value: A) => STM.STM<void, E, R>) => (self: TSet.TSet<A>) => STM.STM<void, E, R>,\n  <A, R, E>(self: TSet.TSet<A>, f: (value: A) => STM.STM<void, E, R>) => STM.STM<void, E, R>\n>(2, (self, f) => reduceSTM(self, void 0 as void, (_, value) => f(value)))\n\n/** @internal */\nexport const fromIterable = <A>(iterable: Iterable<A>): STM.STM<TSet.TSet<A>> =>\n  core.map(\n    tMap.fromIterable(Array.from(iterable).map((a): [A, void] => [a, void 0])),\n    (tMap) => new TSetImpl(tMap)\n  )\n\n/** @internal */\nexport const has = dual<\n  <A>(value: A) => (self: TSet.TSet<A>) => STM.STM<boolean>,\n  <A>(self: TSet.TSet<A>, value: A) => STM.STM<boolean>\n>(2, (self, value) => tMap.has(self.tMap, value))\n\n/** @internal */\nexport const intersection = dual<\n  <A>(other: TSet.TSet<A>) => (self: TSet.TSet<A>) => STM.STM<void>,\n  <A>(self: TSet.TSet<A>, other: TSet.TSet<A>) => STM.STM<void>\n>(2, (self, other) =>\n  core.flatMap(\n    toHashSet(other),\n    (values) => pipe(self, retainIf((value) => pipe(values, HashSet.has(value)), { discard: true }))\n  ))\n\n/** @internal */\nexport const isEmpty = <A>(self: TSet.TSet<A>): STM.STM<boolean> => tMap.isEmpty(self.tMap)\n\n/** @internal */\nexport const make = <Elements extends Array<any>>(\n  ...elements: Elements\n): STM.STM<TSet.TSet<Elements[number]>> => fromIterable(elements)\n\n/** @internal */\nexport const reduce = dual<\n  <Z, A>(zero: Z, f: (accumulator: Z, value: A) => Z) => (self: TSet.TSet<A>) => STM.STM<Z>,\n  <Z, A>(self: TSet.TSet<A>, zero: Z, f: (accumulator: Z, value: A) => Z) => STM.STM<Z>\n>(3, (self, zero, f) =>\n  tMap.reduce(\n    self.tMap,\n    zero,\n    (acc, _, key) => f(acc, key)\n  ))\n\n/** @internal */\nexport const reduceSTM = dual<\n  <Z, A, R, E>(zero: Z, f: (accumulator: Z, value: A) => STM.STM<Z, E, R>) => (self: TSet.TSet<A>) => STM.STM<Z, E, R>,\n  <Z, A, R, E>(self: TSet.TSet<A>, zero: Z, f: (accumulator: Z, value: A) => STM.STM<Z, E, R>) => STM.STM<Z, E, R>\n>(3, (self, zero, f) =>\n  tMap.reduceSTM(\n    self.tMap,\n    zero,\n    (acc, _, key) => f(acc, key)\n  ))\n\n/** @internal */\nexport const remove = dual<\n  <A>(value: A) => (self: TSet.TSet<A>) => STM.STM<void>,\n  <A>(self: TSet.TSet<A>, value: A) => STM.STM<void>\n>(2, (self, value) => tMap.remove(self.tMap, value))\n\n/** @internal */\nexport const removeAll = dual<\n  <A>(iterable: Iterable<A>) => (self: TSet.TSet<A>) => STM.STM<void>,\n  <A>(self: TSet.TSet<A>, iterable: Iterable<A>) => STM.STM<void>\n>(2, (self, iterable) => tMap.removeAll(self.tMap, iterable))\n\n/** @internal */\nexport const removeIf: {\n  <A>(predicate: Predicate<A>, options: {\n    readonly discard: true\n  }): (self: TSet.TSet<A>) => STM.STM<void>\n  <A>(\n    predicate: Predicate<A>,\n    options?: {\n      readonly discard: false\n    }\n  ): (self: TSet.TSet<A>) => STM.STM<Array<A>>\n  <A>(self: TSet.TSet<A>, predicate: Predicate<A>, options: {\n    readonly discard: true\n  }): STM.STM<void>\n  <A>(\n    self: TSet.TSet<A>,\n    predicate: Predicate<A>,\n    options?: {\n      readonly discard: false\n    }\n  ): STM.STM<Array<A>>\n} = dual(\n  (args) => isTSet(args[0]),\n  (self, predicate, options) =>\n    options?.discard === true ? tMap.removeIf(self.tMap, (key) => predicate(key), { discard: true }) : pipe(\n      tMap.removeIf(self.tMap, (key) => predicate(key)),\n      core.map(RA.map((entry) => entry[0]))\n    )\n)\n\n/** @internal */\nexport const retainIf: {\n  <A>(predicate: Predicate<A>, options: {\n    readonly discard: true\n  }): (self: TSet.TSet<A>) => STM.STM<void>\n  <A>(\n    predicate: Predicate<A>,\n    options?: {\n      readonly discard: false\n    }\n  ): (self: TSet.TSet<A>) => STM.STM<Array<A>>\n  <A>(self: TSet.TSet<A>, predicate: Predicate<A>, options: {\n    readonly discard: true\n  }): STM.STM<void>\n  <A>(\n    self: TSet.TSet<A>,\n    predicate: Predicate<A>,\n    options?: {\n      readonly discard: false\n    }\n  ): STM.STM<Array<A>>\n} = dual((args) => isTSet(args[0]), (self, predicate, options) =>\n  options?.discard === true ?\n    tMap.retainIf(self.tMap, (key) => predicate(key), { discard: true }) :\n    pipe(\n      tMap.retainIf(self.tMap, (key) => predicate(key)),\n      core.map(RA.map((entry) => entry[0]))\n    ))\n\n/** @internal */\nexport const size = <A>(self: TSet.TSet<A>): STM.STM<number> => core.map(toChunk(self), (chunk) => chunk.length)\n\n/** @internal */\nexport const takeFirst = dual<\n  <A, B>(pf: (a: A) => Option.Option<B>) => (self: TSet.TSet<A>) => STM.STM<B>,\n  <A, B>(self: TSet.TSet<A>, pf: (a: A) => Option.Option<B>) => STM.STM<B>\n>(2, (self, pf) => tMap.takeFirst(self.tMap, (key) => pf(key)))\n\n/** @internal */\nexport const takeFirstSTM = dual<\n  <A, B, E, R>(pf: (a: A) => STM.STM<B, Option.Option<E>, R>) => (self: TSet.TSet<A>) => STM.STM<B, E, R>,\n  <A, B, E, R>(self: TSet.TSet<A>, pf: (a: A) => STM.STM<B, Option.Option<E>, R>) => STM.STM<B, E, R>\n>(2, (self, pf) => tMap.takeFirstSTM(self.tMap, (key) => pf(key)))\n\n/** @internal */\nexport const takeSome = dual<\n  <A, B>(pf: (a: A) => Option.Option<B>) => (self: TSet.TSet<A>) => STM.STM<RA.NonEmptyArray<B>>,\n  <A, B>(self: TSet.TSet<A>, pf: (a: A) => Option.Option<B>) => STM.STM<RA.NonEmptyArray<B>>\n>(2, (self, pf) => tMap.takeSome(self.tMap, (key) => pf(key)))\n\n/** @internal */\nexport const takeSomeSTM = dual<\n  <A, B, E, R>(\n    pf: (a: A) => STM.STM<B, Option.Option<E>, R>\n  ) => (self: TSet.TSet<A>) => STM.STM<RA.NonEmptyArray<B>, E, R>,\n  <A, B, E, R>(\n    self: TSet.TSet<A>,\n    pf: (a: A) => STM.STM<B, Option.Option<E>, R>\n  ) => STM.STM<RA.NonEmptyArray<B>, E, R>\n>(2, (self, pf) => tMap.takeSomeSTM(self.tMap, (key) => pf(key)))\n\n/** @internal */\nexport const toChunk = <A>(self: TSet.TSet<A>): STM.STM<Chunk.Chunk<A>> =>\n  tMap.keys(self.tMap).pipe(STM.map(Chunk.unsafeFromArray))\n\n/** @internal */\nexport const toHashSet = <A>(self: TSet.TSet<A>): STM.STM<HashSet.HashSet<A>> =>\n  reduce(\n    self,\n    HashSet.empty<A>(),\n    (acc, value) => pipe(acc, HashSet.add(value))\n  )\n\n/** @internal */\nexport const toArray = <A>(self: TSet.TSet<A>): STM.STM<Array<A>> =>\n  reduce<Array<A>, A>(\n    self,\n    [],\n    (acc, value) => [...acc, value]\n  )\n\n/** @internal */\nexport const toReadonlySet = <A>(self: TSet.TSet<A>): STM.STM<ReadonlySet<A>> =>\n  core.map(toArray(self), (values) => new Set(values))\n\n/** @internal */\nexport const transform = dual<\n  <A>(f: (a: A) => A) => (self: TSet.TSet<A>) => STM.STM<void>,\n  <A>(self: TSet.TSet<A>, f: (a: A) => A) => STM.STM<void>\n>(2, (self, f) => tMap.transform(self.tMap, (key, value) => [f(key), value]))\n\n/** @internal */\nexport const transformSTM = dual<\n  <A, R, E>(f: (a: A) => STM.STM<A, E, R>) => (self: TSet.TSet<A>) => STM.STM<void, E, R>,\n  <A, R, E>(self: TSet.TSet<A>, f: (a: A) => STM.STM<A, E, R>) => STM.STM<void, E, R>\n>(2, (self, f) =>\n  tMap.transformSTM(\n    self.tMap,\n    (key, value) => core.map(f(key), (a) => [a, value])\n  ))\n\n/** @internal */\nexport const union = dual<\n  <A>(other: TSet.TSet<A>) => (self: TSet.TSet<A>) => STM.STM<void>,\n  <A>(self: TSet.TSet<A>, other: TSet.TSet<A>) => STM.STM<void>\n>(2, (self, other) => forEach(other, (value) => add(self, value)))\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tSubscriptionRef.ts",
    "content": "import * as Effect from \"../../Effect.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport { pipeArguments } from \"../../Pipeable.js\"\nimport * as STM from \"../../STM.js\"\nimport * as TPubSub from \"../../TPubSub.js\"\nimport * as TQueue from \"../../TQueue.js\"\nimport * as TRef from \"../../TRef.js\"\nimport type * as TSubscriptionRef from \"../../TSubscriptionRef.js\"\nimport * as stream from \"../stream.js\"\nimport { tDequeueVariance } from \"./tQueue.js\"\nimport { tRefVariance } from \"./tRef.js\"\n\n/** @internal */\nconst TSubscriptionRefSymbolKey = \"effect/TSubscriptionRef\"\n\n/** @internal */\nexport const TSubscriptionRefTypeId: TSubscriptionRef.TSubscriptionRefTypeId = Symbol.for(\n  TSubscriptionRefSymbolKey\n) as TSubscriptionRef.TSubscriptionRefTypeId\n\nconst TSubscriptionRefVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\nclass TDequeueMerge<A> implements TQueue.TDequeue<A> {\n  [TQueue.TDequeueTypeId] = tDequeueVariance\n\n  constructor(\n    readonly first: TQueue.TDequeue<A>,\n    readonly second: TQueue.TDequeue<A>\n  ) {}\n\n  peek: STM.STM<A> = STM.gen(this, function*() {\n    const first = yield* this.peekOption\n    if (first._tag === \"Some\") {\n      return first.value\n    }\n    return yield* STM.retry\n  })\n\n  peekOption: STM.STM<Option.Option<A>> = STM.gen(this, function*() {\n    const first = yield* this.first.peekOption\n    if (first._tag === \"Some\") {\n      return first\n    }\n    const second = yield* this.second.peekOption\n    if (second._tag === \"Some\") {\n      return second\n    }\n    return Option.none()\n  })\n\n  take: STM.STM<A> = STM.gen(this, function*() {\n    if (!(yield* this.first.isEmpty)) {\n      return yield* this.first.take\n    }\n    if (!(yield* this.second.isEmpty)) {\n      return yield* this.second.take\n    }\n    return yield* STM.retry\n  })\n\n  takeAll: STM.STM<Array<A>> = STM.gen(this, function*() {\n    return [...yield* this.first.takeAll, ...yield* this.second.takeAll]\n  })\n\n  takeUpTo(max: number): STM.STM<Array<A>> {\n    return STM.gen(this, function*() {\n      const first = yield* this.first.takeUpTo(max)\n      if (first.length >= max) {\n        return first\n      }\n      return [...first, ...yield* this.second.takeUpTo(max - first.length)]\n    })\n  }\n\n  capacity(): number {\n    return this.first.capacity() + this.second.capacity()\n  }\n\n  size: STM.STM<number> = STM.gen(this, function*() {\n    return (yield* this.first.size) + (yield* this.second.size)\n  })\n\n  isFull: STM.STM<boolean> = STM.gen(this, function*() {\n    return (yield* this.first.isFull) && (yield* this.second.isFull)\n  })\n\n  isEmpty: STM.STM<boolean> = STM.gen(this, function*() {\n    return (yield* this.first.isEmpty) && (yield* this.second.isEmpty)\n  })\n\n  shutdown: STM.STM<void> = STM.gen(this, function*() {\n    yield* this.first.shutdown\n    yield* this.second.shutdown\n  })\n\n  isShutdown: STM.STM<boolean> = STM.gen(this, function*() {\n    return (yield* this.first.isShutdown) && (yield* this.second.isShutdown)\n  })\n\n  awaitShutdown: STM.STM<void> = STM.gen(this, function*() {\n    yield* this.first.awaitShutdown\n    yield* this.second.awaitShutdown\n  })\n}\n\n/** @internal */\nclass TSubscriptionRefImpl<in out A> implements TSubscriptionRef.TSubscriptionRef<A> {\n  readonly [TSubscriptionRefTypeId] = TSubscriptionRefVariance\n  readonly [TRef.TRefTypeId] = tRefVariance\n\n  constructor(\n    readonly ref: TRef.TRef<A>,\n    readonly pubsub: TPubSub.TPubSub<A>\n  ) {}\n\n  get todos() {\n    return this.ref.todos\n  }\n\n  get versioned() {\n    return this.ref.versioned\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n\n  get changes(): STM.STM<TQueue.TDequeue<A>> {\n    return STM.gen(this, function*() {\n      const first = yield* TQueue.unbounded<A>()\n      yield* TQueue.offer(first, yield* TRef.get(this.ref))\n      return new TDequeueMerge(first, yield* TPubSub.subscribe(this.pubsub))\n    })\n  }\n\n  modify<B>(f: (a: A) => readonly [B, A]): STM.STM<B> {\n    return pipe(\n      TRef.get(this.ref),\n      STM.map(f),\n      STM.flatMap(([b, a]) =>\n        pipe(\n          TRef.set(this.ref, a),\n          STM.as(b),\n          STM.zipLeft(TPubSub.publish(this.pubsub, a))\n        )\n      )\n    )\n  }\n}\n\n/** @internal */\nexport const make = <A>(value: A): STM.STM<TSubscriptionRef.TSubscriptionRef<A>> =>\n  pipe(\n    STM.all([\n      TPubSub.unbounded<A>(),\n      TRef.make(value)\n    ]),\n    STM.map(([pubsub, ref]) => new TSubscriptionRefImpl(ref, pubsub))\n  )\n\n/** @internal */\nexport const get = <A>(self: TSubscriptionRef.TSubscriptionRef<A>) => TRef.get(self.ref)\n\n/** @internal */\nexport const set = dual<\n  <A>(value: A) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<void>,\n  <A>(self: TSubscriptionRef.TSubscriptionRef<A>, value: A) => STM.STM<void>\n>(\n  2,\n  <A>(self: TSubscriptionRef.TSubscriptionRef<A>, value: A): STM.STM<void> =>\n    self.modify((): [void, A] => [void 0, value])\n)\n\n/** @internal */\nexport const getAndSet = dual<\n  <A>(value: A) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<A>,\n  <A>(self: TSubscriptionRef.TSubscriptionRef<A>, value: A) => STM.STM<A>\n>(2, (self, value) => self.modify((a) => [a, value]))\n\n/** @internal */\nexport const getAndUpdate = dual<\n  <A>(f: (a: A) => A) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<A>,\n  <A>(self: TSubscriptionRef.TSubscriptionRef<A>, f: (a: A) => A) => STM.STM<A>\n>(2, (self, f) => self.modify((a) => [a, f(a)]))\n\n/** @internal */\nexport const getAndUpdateSome = dual<\n  <A>(f: (a: A) => Option.Option<A>) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<A>,\n  <A>(self: TSubscriptionRef.TSubscriptionRef<A>, f: (a: A) => Option.Option<A>) => STM.STM<A>\n>(2, (self, f) =>\n  self.modify((a) =>\n    Option.match(f(a), {\n      onNone: () => [a, a],\n      onSome: (b) => [a, b]\n    })\n  ))\n\n/** @internal */\nexport const setAndGet = dual<\n  <A>(value: A) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<A>,\n  <A>(self: TSubscriptionRef.TSubscriptionRef<A>, value: A) => STM.STM<A>\n>(2, (self, value) => self.modify(() => [value, value]))\n\n/** @internal */\nexport const modify = dual<\n  <A, B>(f: (a: A) => readonly [B, A]) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<B>,\n  <A, B>(self: TSubscriptionRef.TSubscriptionRef<A>, f: (a: A) => readonly [B, A]) => STM.STM<B>\n>(2, (self, f) => self.modify(f))\n\n/** @internal */\nexport const modifySome = dual<\n  <A, B>(\n    fallback: B,\n    f: (a: A) => Option.Option<readonly [B, A]>\n  ) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<B>,\n  <A, B>(\n    self: TSubscriptionRef.TSubscriptionRef<A>,\n    fallback: B,\n    f: (a: A) => Option.Option<readonly [B, A]>\n  ) => STM.STM<B>\n>(3, (self, fallback, f) =>\n  self.modify((a) =>\n    Option.match(f(a), {\n      onNone: () => [fallback, a],\n      onSome: (b) => b\n    })\n  ))\n\n/** @internal */\nexport const update = dual<\n  <A>(f: (a: A) => A) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<void>,\n  <A>(self: TSubscriptionRef.TSubscriptionRef<A>, f: (a: A) => A) => STM.STM<void>\n>(2, (self, f) => self.modify((a) => [void 0, f(a)]))\n\n/** @internal */\nexport const updateAndGet = dual<\n  <A>(f: (a: A) => A) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<A>,\n  <A>(self: TSubscriptionRef.TSubscriptionRef<A>, f: (a: A) => A) => STM.STM<A>\n>(2, (self, f) =>\n  self.modify((a) => {\n    const b = f(a)\n    return [b, b]\n  }))\n\n/** @internal */\nexport const updateSome = dual<\n  <A>(f: (a: A) => Option.Option<A>) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<void>,\n  <A>(self: TSubscriptionRef.TSubscriptionRef<A>, f: (a: A) => Option.Option<A>) => STM.STM<void>\n>(\n  2,\n  (self, f) =>\n    self.modify((a) => [\n      void 0,\n      Option.match(f(a), {\n        onNone: () => a,\n        onSome: (b) => b\n      })\n    ])\n)\n\n/** @internal */\nexport const updateSomeAndGet = dual<\n  <A>(f: (a: A) => Option.Option<A>) => (self: TSubscriptionRef.TSubscriptionRef<A>) => STM.STM<A>,\n  <A>(self: TSubscriptionRef.TSubscriptionRef<A>, f: (a: A) => Option.Option<A>) => STM.STM<A>\n>(\n  2,\n  (self, f) =>\n    self.modify((a) =>\n      Option.match(f(a), {\n        onNone: () => [a, a],\n        onSome: (b) => [b, b]\n      })\n    )\n)\n\n/** @internal */\nexport const changesScoped = <A>(self: TSubscriptionRef.TSubscriptionRef<A>) =>\n  Effect.acquireRelease(self.changes, TQueue.shutdown)\n\n/** @internal */\nexport const changesStream = <A>(self: TSubscriptionRef.TSubscriptionRef<A>) =>\n  stream.unwrap(Effect.map(self.changes, stream.fromTQueue))\n"
  },
  {
    "path": "packages/effect/src/internal/stm/tryCommit.ts",
    "content": "import type * as Exit from \"../../Exit.js\"\nimport type * as Journal from \"./journal.js\"\nimport * as OpCodes from \"./opCodes/tryCommit.js\"\n\n/** @internal */\nexport type TryCommit<A, E = never> = Done<A, E> | Suspend\n\n/** @internal */\nexport interface Done<out A, out E> {\n  readonly _tag: OpCodes.OP_DONE\n  readonly exit: Exit.Exit<A, E>\n}\n\n/** @internal */\nexport interface Suspend {\n  readonly _tag: OpCodes.OP_SUSPEND\n  readonly journal: Journal.Journal\n}\n\n/** @internal */\nexport const done = <A, E>(exit: Exit.Exit<A, E>): TryCommit<A, E> => {\n  return {\n    _tag: OpCodes.OP_DONE,\n    exit\n  }\n}\n\n/** @internal */\nexport const suspend = (journal: Journal.Journal): TryCommit<never> => {\n  return {\n    _tag: OpCodes.OP_SUSPEND,\n    journal\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/stm/txnId.ts",
    "content": "/** @internal */\nexport type TxnId = number & {\n  readonly TransactioId: unique symbol\n}\n\n/** @internal */\nconst txnCounter = { ref: 0 }\n\n/** @internal */\nexport const make = (): TxnId => {\n  const newId = txnCounter.ref + 1\n  txnCounter.ref = newId\n  return newId as TxnId\n}\n"
  },
  {
    "path": "packages/effect/src/internal/stm/versioned.ts",
    "content": "/** @internal */\nexport class Versioned<out A> {\n  constructor(readonly value: A) {}\n}\n"
  },
  {
    "path": "packages/effect/src/internal/stream/debounceState.ts",
    "content": "import type * as Chunk from \"../../Chunk.js\"\nimport type * as Fiber from \"../../Fiber.js\"\nimport type * as HandoffSignal from \"./handoffSignal.js\"\n\n/** @internal */\nexport type DebounceState<A, E = never> = NotStarted | Previous<A> | Current<A, E>\n\n/** @internal */\nexport const OP_NOT_STARTED = \"NotStarted\" as const\n\n/** @internal */\nexport type OP_NOT_STARTED = typeof OP_NOT_STARTED\n\n/** @internal */\nexport const OP_PREVIOUS = \"Previous\" as const\n\n/** @internal */\nexport type OP_PREVIOUS = typeof OP_PREVIOUS\n\n/** @internal */\nexport const OP_CURRENT = \"Current\" as const\n\n/** @internal */\nexport type OP_CURRENT = typeof OP_CURRENT\n\nexport interface NotStarted {\n  readonly _tag: OP_NOT_STARTED\n}\n\n/** @internal */\nexport interface Previous<out A> {\n  readonly _tag: OP_PREVIOUS\n  readonly fiber: Fiber.Fiber<Chunk.Chunk<A>>\n}\n\n/** @internal */\nexport interface Current<out A, out E = never> {\n  readonly _tag: OP_CURRENT\n  readonly fiber: Fiber.Fiber<HandoffSignal.HandoffSignal<A, E>, E>\n}\n\n/** @internal */\nexport const notStarted: DebounceState<never> = {\n  _tag: OP_NOT_STARTED\n}\n\n/** @internal */\nexport const previous = <A>(fiber: Fiber.Fiber<Chunk.Chunk<A>>): DebounceState<A> => ({\n  _tag: OP_PREVIOUS,\n  fiber\n})\n\n/** @internal */\nexport const current = <A, E>(fiber: Fiber.Fiber<HandoffSignal.HandoffSignal<A, E>, E>): DebounceState<A, E> => ({\n  _tag: OP_CURRENT,\n  fiber\n})\n"
  },
  {
    "path": "packages/effect/src/internal/stream/emit.ts",
    "content": "import * as Cause from \"../../Cause.js\"\nimport * as Chunk from \"../../Chunk.js\"\nimport * as Effect from \"../../Effect.js\"\nimport * as Exit from \"../../Exit.js\"\nimport { pipe } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport type * as Queue from \"../../Queue.js\"\nimport type * as Scheduler from \"../../Scheduler.js\"\nimport type * as Emit from \"../../StreamEmit.js\"\n\n/** @internal */\nexport const make = <R, E, A, B>(\n  emit: (f: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R>) => Promise<B>\n): Emit.Emit<R, E, A, B> => {\n  const ops: Emit.EmitOps<R, E, A, B> = {\n    chunk(this: Emit.Emit<R, E, A, B>, as: Chunk.Chunk<A>) {\n      return this(Effect.succeed(as))\n    },\n    die<Err>(this: Emit.Emit<R, E, A, B>, defect: Err) {\n      return this(Effect.die(defect))\n    },\n    dieMessage(this: Emit.Emit<R, E, A, B>, message: string) {\n      return this(Effect.dieMessage(message))\n    },\n    done(this: Emit.Emit<R, E, A, B>, exit: Exit.Exit<A, E>) {\n      return this(Effect.suspend(() => Exit.mapBoth(exit, { onFailure: Option.some, onSuccess: Chunk.of })))\n    },\n    end(this: Emit.Emit<R, E, A, B>) {\n      return this(Effect.fail(Option.none()))\n    },\n    fail(this: Emit.Emit<R, E, A, B>, e: E) {\n      return this(Effect.fail(Option.some(e)))\n    },\n    fromEffect(this: Emit.Emit<R, E, A, B>, effect: Effect.Effect<A, E, R>) {\n      return this(Effect.mapBoth(effect, { onFailure: Option.some, onSuccess: Chunk.of }))\n    },\n    fromEffectChunk(this: Emit.Emit<R, E, A, B>, effect: Effect.Effect<Chunk.Chunk<A>, E, R>) {\n      return this(pipe(effect, Effect.mapError(Option.some)))\n    },\n    halt(this: Emit.Emit<R, E, A, B>, cause: Cause.Cause<E>) {\n      return this(Effect.failCause(pipe(cause, Cause.map(Option.some))))\n    },\n    single(this: Emit.Emit<R, E, A, B>, value: A) {\n      return this(Effect.succeed(Chunk.of(value)))\n    }\n  }\n  return Object.assign(emit, ops)\n}\n\n/** @internal */\nexport const makePush = <E, A>(\n  queue: Queue.Queue<Array<A> | Exit.Exit<void, E>>,\n  scheduler: Scheduler.Scheduler\n): Emit.EmitOpsPush<E, A> => {\n  let finished = false\n  let buffer: Array<A> = []\n  let running = false\n  function array(items: ReadonlyArray<A>) {\n    if (finished) return false\n    if (items.length <= 50_000) {\n      buffer.push.apply(buffer, items as Array<A>)\n    } else {\n      for (let i = 0; i < items.length; i++) {\n        buffer.push(items[0])\n      }\n    }\n    if (!running) {\n      running = true\n      scheduler.scheduleTask(flush, 0)\n    }\n    return true\n  }\n  function flush() {\n    running = false\n    if (buffer.length > 0) {\n      queue.unsafeOffer(buffer)\n      buffer = []\n    }\n  }\n  function done(exit: Exit.Exit<A, E>) {\n    if (finished) return\n    finished = true\n    if (exit._tag === \"Success\") {\n      buffer.push(exit.value)\n    }\n    flush()\n    queue.unsafeOffer(exit._tag === \"Success\" ? Exit.void : exit)\n  }\n  return {\n    single(value: A) {\n      if (finished) return false\n      buffer.push(value)\n      if (!running) {\n        running = true\n        scheduler.scheduleTask(flush, 0)\n      }\n      return true\n    },\n    array,\n    chunk(chunk) {\n      return array(Chunk.toReadonlyArray(chunk))\n    },\n    done,\n    end() {\n      if (finished) return\n      finished = true\n      flush()\n      queue.unsafeOffer(Exit.void)\n    },\n    halt(cause: Cause.Cause<E>) {\n      return done(Exit.failCause(cause))\n    },\n    fail(error: E) {\n      return done(Exit.fail(error))\n    },\n    die<Err>(defect: Err): void {\n      return done(Exit.die(defect))\n    },\n    dieMessage(message: string): void {\n      return done(Exit.die(new Error(message)))\n    }\n  }\n}\n"
  },
  {
    "path": "packages/effect/src/internal/stream/haltStrategy.ts",
    "content": "import { dual } from \"../../Function.js\"\nimport type * as HaltStrategy from \"../../StreamHaltStrategy.js\"\nimport * as OpCodes from \"../opCodes/streamHaltStrategy.js\"\n\n/** @internal */\nexport const Left: HaltStrategy.HaltStrategy = {\n  _tag: OpCodes.OP_LEFT\n}\n\n/** @internal */\nexport const Right: HaltStrategy.HaltStrategy = {\n  _tag: OpCodes.OP_RIGHT\n}\n\n/** @internal */\nexport const Both: HaltStrategy.HaltStrategy = {\n  _tag: OpCodes.OP_BOTH\n}\n\n/** @internal */\nexport const Either: HaltStrategy.HaltStrategy = {\n  _tag: OpCodes.OP_EITHER\n}\n\n/** @internal */\nexport const fromInput = (input: HaltStrategy.HaltStrategyInput): HaltStrategy.HaltStrategy => {\n  switch (input) {\n    case \"left\":\n      return Left\n    case \"right\":\n      return Right\n    case \"both\":\n      return Both\n    case \"either\":\n      return Either\n    default:\n      return input\n  }\n}\n\n/** @internal */\nexport const isLeft = (self: HaltStrategy.HaltStrategy): self is HaltStrategy.Left => self._tag === OpCodes.OP_LEFT\n\n/** @internal */\nexport const isRight = (self: HaltStrategy.HaltStrategy): self is HaltStrategy.Right => self._tag === OpCodes.OP_RIGHT\n\n/** @internal */\nexport const isBoth = (self: HaltStrategy.HaltStrategy): self is HaltStrategy.Both => self._tag === OpCodes.OP_BOTH\n\n/** @internal */\nexport const isEither = (self: HaltStrategy.HaltStrategy): self is HaltStrategy.Either =>\n  self._tag === OpCodes.OP_EITHER\n\n/** @internal */\nexport const match = dual<\n  <Z>(options: {\n    readonly onLeft: () => Z\n    readonly onRight: () => Z\n    readonly onBoth: () => Z\n    readonly onEither: () => Z\n  }) => (self: HaltStrategy.HaltStrategy) => Z,\n  <Z>(\n    self: HaltStrategy.HaltStrategy,\n    options: {\n      readonly onLeft: () => Z\n      readonly onRight: () => Z\n      readonly onBoth: () => Z\n      readonly onEither: () => Z\n    }\n  ) => Z\n>(2, <Z>(\n  self: HaltStrategy.HaltStrategy,\n  options: {\n    readonly onLeft: () => Z\n    readonly onRight: () => Z\n    readonly onBoth: () => Z\n    readonly onEither: () => Z\n  }\n): Z => {\n  switch (self._tag) {\n    case OpCodes.OP_LEFT: {\n      return options.onLeft()\n    }\n    case OpCodes.OP_RIGHT: {\n      return options.onRight()\n    }\n    case OpCodes.OP_BOTH: {\n      return options.onBoth()\n    }\n    case OpCodes.OP_EITHER: {\n      return options.onEither()\n    }\n  }\n})\n"
  },
  {
    "path": "packages/effect/src/internal/stream/handoff.ts",
    "content": "import * as Deferred from \"../../Deferred.js\"\nimport * as Effect from \"../../Effect.js\"\nimport { dual, pipe } from \"../../Function.js\"\nimport * as Option from \"../../Option.js\"\nimport * as Ref from \"../../Ref.js\"\n\n/** @internal */\nexport const HandoffTypeId = Symbol.for(\"effect/Stream/Handoff\")\n\n/** @internal */\nexport type HandoffTypeId = typeof HandoffTypeId\n\n/**\n * A synchronous queue-like abstraction that allows a producer to offer an\n * element and wait for it to be taken, and allows a consumer to wait for an\n * element to be available.\n *\n * @internal\n */\nexport interface Handoff<in out A> extends Handoff.Variance<A> {\n  readonly ref: Ref.Ref<Handoff.State<A>>\n}\n\n/** @internal */\nexport const OP_HANDOFF_STATE_EMPTY = \"Empty\" as const\n\n/** @internal */\nexport type OP_HANDOFF_STATE_EMPTY = typeof OP_HANDOFF_STATE_EMPTY\n\n/** @internal */\nexport const OP_HANDOFF_STATE_FULL = \"Full\" as const\n\n/** @internal */\nexport type OP_HANDOFF_STATE_FULL = typeof OP_HANDOFF_STATE_FULL\n\n/** @internal */\nexport declare namespace Handoff {\n  /** @internal */\n  export interface Variance<in out A> {\n    readonly [HandoffTypeId]: {\n      readonly _A: (_: A) => A\n    }\n  }\n\n  /** @internal */\n  export type State<A> = Empty | Full<A>\n\n  /** @internal */\n  export interface Empty {\n    readonly _tag: OP_HANDOFF_STATE_EMPTY\n    readonly notifyConsumer: Deferred.Deferred<void>\n  }\n\n  /** @internal */\n  export interface Full<out A> {\n    readonly _tag: OP_HANDOFF_STATE_FULL\n    readonly value: A\n    readonly notifyProducer: Deferred.Deferred<void>\n  }\n}\n\n/** @internal */\nconst handoffStateEmpty = <A>(notifyConsumer: Deferred.Deferred<void>): Handoff.State<A> => ({\n  _tag: OP_HANDOFF_STATE_EMPTY,\n  notifyConsumer\n})\n\n/** @internal */\nconst handoffStateFull = <A>(value: A, notifyProducer: Deferred.Deferred<void>): Handoff.State<A> => ({\n  _tag: OP_HANDOFF_STATE_FULL,\n  value,\n  notifyProducer\n})\n\n/** @internal */\nconst handoffStateMatch = <A, Z>(\n  onEmpty: (notifyConsumer: Deferred.Deferred<void>) => Z,\n  onFull: (value: A, notifyProducer: Deferred.Deferred<void>) => Z\n) => {\n  return (self: Handoff.State<A>): Z => {\n    switch (self._tag) {\n      case OP_HANDOFF_STATE_EMPTY: {\n        return onEmpty(self.notifyConsumer)\n      }\n      case OP_HANDOFF_STATE_FULL: {\n        return onFull(self.value, self.notifyProducer)\n      }\n    }\n  }\n}\n\nconst handoffVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nexport const make = <A>(): Effect.Effect<Handoff<A>> =>\n  pipe(\n    Deferred.make<void>(),\n    Effect.flatMap((deferred) => Ref.make(handoffStateEmpty<A>(deferred))),\n    Effect.map((ref): Handoff<A> => ({\n      [HandoffTypeId]: handoffVariance,\n      ref\n    }))\n  )\n\n/** @internal */\nexport const offer = dual<\n  <A>(value: A) => (self: Handoff<A>) => Effect.Effect<void>,\n  <A>(self: Handoff<A>, value: A) => Effect.Effect<void>\n>(2, (self, value): Effect.Effect<void> => {\n  return Effect.flatMap(Deferred.make<void>(), (deferred) =>\n    Effect.flatten(\n      Ref.modify(self.ref, (state) =>\n        pipe(\n          state,\n          handoffStateMatch(\n            (notifyConsumer) => [\n              Effect.zipRight(\n                Deferred.succeed(notifyConsumer, void 0),\n                Deferred.await(deferred)\n              ),\n              handoffStateFull(value, deferred)\n            ],\n            (_, notifyProducer) => [\n              Effect.flatMap(\n                Deferred.await(notifyProducer),\n                () => pipe(self, offer(value))\n              ),\n              state\n            ]\n          )\n        ))\n    ))\n})\n\n/** @internal */\nexport const take = <A>(self: Handoff<A>): Effect.Effect<A> =>\n  Effect.flatMap(Deferred.make<void>(), (deferred) =>\n    Effect.flatten(\n      Ref.modify(self.ref, (state) =>\n        pipe(\n          state,\n          handoffStateMatch(\n            (notifyConsumer) =>\n              [\n                Effect.flatMap(\n                  Deferred.await(notifyConsumer),\n                  () => take(self)\n                ),\n                state\n              ] as const,\n            (value, notifyProducer) => [\n              Effect.as(\n                Deferred.succeed(notifyProducer, void 0),\n                value\n              ),\n              handoffStateEmpty<A>(deferred)\n            ]\n          )\n        ))\n    ))\n\n/** @internal */\nexport const poll = <A>(self: Handoff<A>): Effect.Effect<Option.Option<A>> =>\n  Effect.flatMap(Deferred.make<void>(), (deferred) =>\n    Effect.flatten(\n      Ref.modify(self.ref, (state) =>\n        pipe(\n          state,\n          handoffStateMatch(\n            () =>\n              [\n                Effect.succeed(Option.none<A>()),\n                state\n              ] as const,\n            (value, notifyProducer) => [\n              Effect.as(\n                Deferred.succeed(notifyProducer, void 0),\n                Option.some(value)\n              ),\n              handoffStateEmpty<A>(deferred)\n            ]\n          )\n        ))\n    ))\n"
  },
  {
    "path": "packages/effect/src/internal/stream/handoffSignal.ts",
    "content": "import type * as Cause from \"../../Cause.js\"\nimport type * as Chunk from \"../../Chunk.js\"\nimport type * as SinkEndReason from \"./sinkEndReason.js\"\n\n/** @internal */\nexport type HandoffSignal<A, E = never> = Emit<A> | Halt<E> | End\n\n/** @internal */\nexport const OP_EMIT = \"Emit\" as const\n\n/** @internal */\nexport type OP_EMIT = typeof OP_EMIT\n\n/** @internal */\nexport const OP_HALT = \"Halt\" as const\n\n/** @internal */\nexport type OP_HALT = typeof OP_HALT\n\n/** @internal */\nexport const OP_END = \"End\" as const\n\n/** @internal */\nexport type OP_END = typeof OP_END\n\nexport interface Emit<out A> {\n  readonly _tag: OP_EMIT\n  readonly elements: Chunk.Chunk<A>\n}\n\n/** @internal */\nexport interface Halt<out E> {\n  readonly _tag: OP_HALT\n  readonly cause: Cause.Cause<E>\n}\n\n/** @internal */\nexport interface End {\n  readonly _tag: OP_END\n  readonly reason: SinkEndReason.SinkEndReason\n}\n\n/** @internal */\nexport const emit = <A>(elements: Chunk.Chunk<A>): HandoffSignal<A> => ({\n  _tag: OP_EMIT,\n  elements\n})\n\n/** @internal */\nexport const halt = <E>(cause: Cause.Cause<E>): HandoffSignal<never, E> => ({\n  _tag: OP_HALT,\n  cause\n})\n\n/** @internal */\nexport const end = (reason: SinkEndReason.SinkEndReason): HandoffSignal<never> => ({\n  _tag: OP_END,\n  reason\n})\n"
  },
  {
    "path": "packages/effect/src/internal/stream/pull.ts",
    "content": "import type * as Cause from \"../../Cause.js\"\nimport * as Chunk from \"../../Chunk.js\"\nimport * as Effect from \"../../Effect.js\"\nimport * as Option from \"../../Option.js\"\nimport * as Queue from \"../../Queue.js\"\nimport type * as Take from \"../../Take.js\"\nimport * as take from \"../take.js\"\n\n/** @internal */\nexport interface Pull<out R, out E, out A> extends Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R> {}\n\n/** @internal */\nexport const emit = <A>(value: A): Effect.Effect<Chunk.Chunk<A>> => Effect.succeed(Chunk.of(value))\n\n/** @internal */\nexport const emitChunk = <A>(chunk: Chunk.Chunk<A>): Effect.Effect<Chunk.Chunk<A>> => Effect.succeed(chunk)\n\n/** @internal */\nexport const empty = <A>(): Effect.Effect<Chunk.Chunk<A>> => Effect.succeed(Chunk.empty<A>())\n\n/** @internal */\nexport const end = (): Effect.Effect<never, Option.Option<never>> => Effect.fail(Option.none())\n\n/** @internal */\nexport const fail = <E>(error: E): Effect.Effect<never, Option.Option<E>> => Effect.fail(Option.some(error))\n\n/** @internal */\nexport const failCause = <E>(cause: Cause.Cause<E>): Effect.Effect<never, Option.Option<E>> =>\n  Effect.mapError(Effect.failCause(cause), Option.some)\n\n/** @internal */\nexport const fromDequeue = <A, E>(\n  dequeue: Queue.Dequeue<Take.Take<A, E>>\n): Effect.Effect<Chunk.Chunk<A>, Option.Option<E>> => Effect.flatMap(Queue.take(dequeue), take.done)\n"
  },
  {
    "path": "packages/effect/src/internal/stream/sinkEndReason.ts",
    "content": "/** @internal */\nexport type SinkEndReason = ScheduleEnd | UpstreamEnd\n\n/** @internal */\nexport const OP_SCHEDULE_END = \"ScheduleEnd\" as const\n\n/** @internal */\nexport type OP_SCHEDULE_END = typeof OP_SCHEDULE_END\n\n/** @internal */\nexport const OP_UPSTREAM_END = \"UpstreamEnd\" as const\n\n/** @internal */\nexport type OP_UPSTREAM_END = typeof OP_UPSTREAM_END\n\n/** @internal */\nexport interface ScheduleEnd {\n  readonly _tag: OP_SCHEDULE_END\n}\n\n/** @internal */\nexport interface UpstreamEnd {\n  readonly _tag: OP_UPSTREAM_END\n}\n\n/** @internal */\nexport const ScheduleEnd: SinkEndReason = { _tag: OP_SCHEDULE_END }\n\n/** @internal */\nexport const UpstreamEnd: SinkEndReason = { _tag: OP_UPSTREAM_END }\n"
  },
  {
    "path": "packages/effect/src/internal/stream/zipAllState.ts",
    "content": "import type * as Chunk from \"../../Chunk.js\"\n\n/** @internal */\nexport type ZipAllState<A, A2> = DrainLeft | DrainRight | PullBoth | PullLeft<A2> | PullRight<A>\n\n/** @internal */\nexport const OP_DRAIN_LEFT = \"DrainLeft\" as const\n\n/** @internal */\nexport type OP_DRAIN_LEFT = typeof OP_DRAIN_LEFT\n\n/** @internal */\nexport const OP_DRAIN_RIGHT = \"DrainRight\" as const\n\n/** @internal */\nexport type OP_DRAIN_RIGHT = typeof OP_DRAIN_RIGHT\n\n/** @internal */\nexport const OP_PULL_BOTH = \"PullBoth\" as const\n\n/** @internal */\nexport type OP_PULL_BOTH = typeof OP_PULL_BOTH\n\n/** @internal */\nexport const OP_PULL_LEFT = \"PullLeft\" as const\n\n/** @internal */\nexport type OP_PULL_LEFT = typeof OP_PULL_LEFT\n\n/** @internal */\nexport const OP_PULL_RIGHT = \"PullRight\" as const\n\n/** @internal */\nexport type OP_PULL_RIGHT = typeof OP_PULL_RIGHT\n\n/** @internal */\nexport interface DrainLeft {\n  readonly _tag: OP_DRAIN_LEFT\n}\n\n/** @internal */\nexport interface DrainRight {\n  readonly _tag: OP_DRAIN_RIGHT\n}\n\n/** @internal */\nexport interface PullBoth {\n  readonly _tag: OP_PULL_BOTH\n}\n\n/** @internal */\nexport interface PullLeft<A> {\n  readonly _tag: OP_PULL_LEFT\n  readonly rightChunk: Chunk.Chunk<A>\n}\n\n/** @internal */\nexport interface PullRight<A> {\n  readonly _tag: OP_PULL_RIGHT\n  readonly leftChunk: Chunk.Chunk<A>\n}\n\n/** @internal */\nexport const DrainLeft: ZipAllState<never, never> = {\n  _tag: OP_DRAIN_LEFT\n}\n\n/** @internal */\nexport const DrainRight: ZipAllState<never, never> = {\n  _tag: OP_DRAIN_RIGHT\n}\n\n/** @internal */\nexport const PullBoth: ZipAllState<never, never> = {\n  _tag: OP_PULL_BOTH\n}\n\n/** @internal */\nexport const PullLeft = <A>(rightChunk: Chunk.Chunk<A>): ZipAllState<never, A> => ({\n  _tag: OP_PULL_LEFT,\n  rightChunk\n})\n\n/** @internal */\nexport const PullRight = <A>(leftChunk: Chunk.Chunk<A>): ZipAllState<A, never> => ({\n  _tag: OP_PULL_RIGHT,\n  leftChunk\n})\n"
  },
  {
    "path": "packages/effect/src/internal/stream/zipChunksState.ts",
    "content": "import type * as Chunk from \"../../Chunk.js\"\n\n/** @internal */\nexport type ZipChunksState<A, A2> = PullBoth | PullLeft<A2> | PullRight<A>\n\n/** @internal */\nexport const OP_PULL_BOTH = \"PullBoth\" as const\n\n/** @internal */\nexport type OP_PULL_BOTH = typeof OP_PULL_BOTH\n\n/** @internal */\nexport const OP_PULL_LEFT = \"PullLet\" as const\n\n/** @internal */\nexport type OP_PULL_LEFT = typeof OP_PULL_LEFT\n\n/** @internal */\nexport const OP_PULL_RIGHT = \"PullRight\" as const\n\n/** @internal */\nexport type OP_PULL_RIGHT = typeof OP_PULL_RIGHT\n\n/** @internal */\nexport interface PullBoth {\n  readonly _tag: OP_PULL_BOTH\n}\n\n/** @internal */\nexport interface PullLeft<A> {\n  readonly _tag: OP_PULL_LEFT\n  readonly rightChunk: Chunk.Chunk<A>\n}\n\n/** @internal */\nexport interface PullRight<A> {\n  readonly _tag: OP_PULL_RIGHT\n  readonly leftChunk: Chunk.Chunk<A>\n}\n\n/** @internal */\nexport const PullBoth: ZipChunksState<never, never> = {\n  _tag: OP_PULL_BOTH\n}\n\n/** @internal */\nexport const PullLeft = <A>(rightChunk: Chunk.Chunk<A>): ZipChunksState<never, A> => ({\n  _tag: OP_PULL_LEFT,\n  rightChunk\n})\n\n/** @internal */\nexport const PullRight = <A>(leftChunk: Chunk.Chunk<A>): ZipChunksState<A, never> => ({\n  _tag: OP_PULL_RIGHT,\n  leftChunk\n})\n"
  },
  {
    "path": "packages/effect/src/internal/stream.ts",
    "content": "import * as Cause from \"../Cause.js\"\nimport type * as Channel from \"../Channel.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport * as Clock from \"../Clock.js\"\nimport * as Context from \"../Context.js\"\nimport * as Deferred from \"../Deferred.js\"\nimport * as Duration from \"../Duration.js\"\nimport * as Effect from \"../Effect.js\"\nimport * as Either from \"../Either.js\"\nimport * as Equal from \"../Equal.js\"\nimport type { ExecutionPlan } from \"../ExecutionPlan.js\"\nimport * as Exit from \"../Exit.js\"\nimport * as Fiber from \"../Fiber.js\"\nimport * as FiberRef from \"../FiberRef.js\"\nimport type { LazyArg } from \"../Function.js\"\nimport { constTrue, dual, identity, pipe } from \"../Function.js\"\nimport * as internalExecutionPlan from \"../internal/executionPlan.js\"\nimport * as Layer from \"../Layer.js\"\nimport * as MergeDecision from \"../MergeDecision.js\"\nimport * as Option from \"../Option.js\"\nimport type * as Order from \"../Order.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty, type Predicate, type Refinement } from \"../Predicate.js\"\nimport * as PubSub from \"../PubSub.js\"\nimport * as Queue from \"../Queue.js\"\nimport * as RcRef from \"../RcRef.js\"\nimport * as Ref from \"../Ref.js\"\nimport * as Runtime from \"../Runtime.js\"\nimport * as Schedule from \"../Schedule.js\"\nimport type * as Scope from \"../Scope.js\"\nimport type * as Sink from \"../Sink.js\"\nimport type * as Stream from \"../Stream.js\"\nimport type * as Emit from \"../StreamEmit.js\"\nimport * as HaltStrategy from \"../StreamHaltStrategy.js\"\nimport type * as Take from \"../Take.js\"\nimport * as TPubSub from \"../TPubSub.js\"\nimport * as TQueue from \"../TQueue.js\"\nimport type * as Tracer from \"../Tracer.js\"\nimport * as Tuple from \"../Tuple.js\"\nimport type * as Types from \"../Types.js\"\nimport * as channel from \"./channel.js\"\nimport * as channelExecutor from \"./channel/channelExecutor.js\"\nimport * as MergeStrategy from \"./channel/mergeStrategy.js\"\nimport * as core from \"./core-stream.js\"\nimport * as doNotation from \"./doNotation.js\"\nimport { RingBuffer } from \"./ringBuffer.js\"\nimport * as InternalSchedule from \"./schedule.js\"\nimport * as sink_ from \"./sink.js\"\nimport * as DebounceState from \"./stream/debounceState.js\"\nimport * as emit from \"./stream/emit.js\"\nimport * as haltStrategy from \"./stream/haltStrategy.js\"\nimport * as Handoff from \"./stream/handoff.js\"\nimport * as HandoffSignal from \"./stream/handoffSignal.js\"\nimport * as pull from \"./stream/pull.js\"\nimport * as SinkEndReason from \"./stream/sinkEndReason.js\"\nimport * as ZipAllState from \"./stream/zipAllState.js\"\nimport * as ZipChunksState from \"./stream/zipChunksState.js\"\nimport * as InternalTake from \"./take.js\"\nimport * as InternalTracer from \"./tracer.js\"\n\n/** @internal */\nconst StreamSymbolKey = \"effect/Stream\"\n\n/** @internal */\nexport const StreamTypeId: Stream.StreamTypeId = Symbol.for(\n  StreamSymbolKey\n) as Stream.StreamTypeId\n\n/** @internal */\nconst streamVariance = {\n  _R: (_: never) => _,\n  _E: (_: never) => _,\n  _A: (_: never) => _\n}\n\n/** @internal */\nexport class StreamImpl<out A, out E = never, out R = never> implements Stream.Stream<A, E, R> {\n  readonly [StreamTypeId] = streamVariance\n  constructor(\n    readonly channel: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, unknown, unknown, R>\n  ) {\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const isStream = (u: unknown): u is Stream.Stream<unknown, unknown, unknown> =>\n  hasProperty(u, StreamTypeId) || Effect.isEffect(u)\n\n/** @internal */\nexport const DefaultChunkSize = 4096\n\n/** @internal */\nexport const accumulate = <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<Chunk.Chunk<A>, E, R> =>\n  chunks(accumulateChunks(self))\n\n/** @internal */\nexport const accumulateChunks = <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<A, E, R> => {\n  const accumulator = (\n    s: Chunk.Chunk<A>\n  ): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E, E, void, unknown> =>\n    core.readWith({\n      onInput: (input: Chunk.Chunk<A>) => {\n        const next = Chunk.appendAll(s, input)\n        return core.flatMap(\n          core.write(next),\n          () => accumulator(next)\n        )\n      },\n      onFailure: core.fail,\n      onDone: () => core.void\n    })\n  return new StreamImpl(core.pipeTo(toChannel(self), accumulator(Chunk.empty())))\n}\n\n/** @internal */\nexport const acquireRelease = <A, E, R, R2, X>(\n  acquire: Effect.Effect<A, E, R>,\n  release: (resource: A, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<X, never, R2>\n): Stream.Stream<A, E, R | R2> => scoped(Effect.acquireRelease(acquire, release))\n\n/** @internal */\nexport const aggregate = dual<\n  <B, A, A2, E2, R2>(\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E2 | E, R2 | R>,\n  <A, E, R, B, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>\n  ) => Stream.Stream<B, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, B, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>\n  ): Stream.Stream<B, E2 | E, R2 | R> => aggregateWithin(self, sink, Schedule.forever)\n)\n\n/** @internal */\nexport const aggregateWithin = dual<\n  <B, A, A2, E2, R2, C, R3>(\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>,\n    schedule: Schedule.Schedule<C, Option.Option<B>, R3>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E2 | E, R2 | R3 | R>,\n  <A, E, R, B, A2, E2, R2, C, R3>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>,\n    schedule: Schedule.Schedule<C, Option.Option<B>, R3>\n  ) => Stream.Stream<B, E2 | E, R2 | R3 | R>\n>(\n  3,\n  <A, E, R, B, A2, E2, R2, C, R3>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>,\n    schedule: Schedule.Schedule<C, Option.Option<B>, R3>\n  ): Stream.Stream<B, E2 | E, R2 | R3 | R> =>\n    filterMap(\n      aggregateWithinEither(self, sink, schedule),\n      (_) =>\n        Either.match(_, {\n          onLeft: Option.none,\n          onRight: Option.some\n        })\n    )\n)\n\n/** @internal */\nexport const aggregateWithinEither = dual<\n  <B, A, A2, E2, R2, C, R3>(\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>,\n    schedule: Schedule.Schedule<C, Option.Option<B>, R3>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Either.Either<B, C>, E2 | E, R2 | R3 | R>,\n  <A, E, R, B, A2, E2, R2, C, R3>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>,\n    schedule: Schedule.Schedule<C, Option.Option<B>, R3>\n  ) => Stream.Stream<Either.Either<B, C>, E2 | E, R2 | R3 | R>\n>(\n  3,\n  <A, E, R, B, A2, E2, R2, C, R3>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<B, A | A2, A2, E2, R2>,\n    schedule: Schedule.Schedule<C, Option.Option<B>, R3>\n  ): Stream.Stream<Either.Either<B, C>, E2 | E, R2 | R3 | R> => {\n    const layer = Effect.all([\n      Handoff.make<HandoffSignal.HandoffSignal<A, E | E2>>(),\n      Ref.make<SinkEndReason.SinkEndReason>(SinkEndReason.ScheduleEnd),\n      Ref.make(Chunk.empty<A | A2>()),\n      Schedule.driver(schedule),\n      Ref.make(false),\n      Ref.make(false)\n    ])\n    return fromEffect(layer).pipe(\n      flatMap(([handoff, sinkEndReason, sinkLeftovers, scheduleDriver, consumed, endAfterEmit]) => {\n        const handoffProducer: Channel.Channel<never, Chunk.Chunk<A>, never, E | E2, unknown, unknown> = core\n          .readWithCause({\n            onInput: (input: Chunk.Chunk<A>) =>\n              core.flatMap(\n                core.fromEffect(pipe(\n                  handoff,\n                  Handoff.offer<HandoffSignal.HandoffSignal<A, E | E2>>(HandoffSignal.emit(input)),\n                  Effect.when(() => Chunk.isNonEmpty(input))\n                )),\n                () => handoffProducer\n              ),\n            onFailure: (cause) =>\n              core.fromEffect(\n                Handoff.offer<HandoffSignal.HandoffSignal<A, E | E2>>(\n                  handoff,\n                  HandoffSignal.halt(cause)\n                )\n              ),\n            onDone: () =>\n              core.fromEffect(\n                Handoff.offer<HandoffSignal.HandoffSignal<A, E | E2>>(\n                  handoff,\n                  HandoffSignal.end(SinkEndReason.UpstreamEnd)\n                )\n              )\n          })\n        const handoffConsumer: Channel.Channel<Chunk.Chunk<A | A2>, unknown, E | E2, unknown, void, unknown> = pipe(\n          Ref.getAndSet(sinkLeftovers, Chunk.empty()),\n          Effect.flatMap((leftovers) => {\n            if (Chunk.isNonEmpty(leftovers)) {\n              return pipe(\n                Ref.set(consumed, true),\n                Effect.zipRight(Effect.succeed(pipe(\n                  core.write(leftovers),\n                  core.flatMap(() => handoffConsumer)\n                )))\n              )\n            }\n            return pipe(\n              Handoff.take(handoff),\n              Effect.map((signal) => {\n                switch (signal._tag) {\n                  case HandoffSignal.OP_EMIT: {\n                    return pipe(\n                      core.fromEffect(Ref.set(consumed, true)),\n                      channel.zipRight(core.write(signal.elements)),\n                      channel.zipRight(core.fromEffect(Ref.get(endAfterEmit))),\n                      core.flatMap((bool) => bool ? core.void : handoffConsumer)\n                    )\n                  }\n                  case HandoffSignal.OP_HALT: {\n                    return core.failCause(signal.cause)\n                  }\n                  case HandoffSignal.OP_END: {\n                    if (signal.reason._tag === SinkEndReason.OP_SCHEDULE_END) {\n                      return pipe(\n                        Ref.get(consumed),\n                        Effect.map((bool) =>\n                          bool ?\n                            core.fromEffect(\n                              pipe(\n                                Ref.set(sinkEndReason, SinkEndReason.ScheduleEnd),\n                                Effect.zipRight(Ref.set(endAfterEmit, true))\n                              )\n                            ) :\n                            pipe(\n                              core.fromEffect(\n                                pipe(\n                                  Ref.set(sinkEndReason, SinkEndReason.ScheduleEnd),\n                                  Effect.zipRight(Ref.set(endAfterEmit, true))\n                                )\n                              ),\n                              core.flatMap(() => handoffConsumer)\n                            )\n                        ),\n                        channel.unwrap\n                      )\n                    }\n                    return pipe(\n                      Ref.set<SinkEndReason.SinkEndReason>(sinkEndReason, signal.reason),\n                      Effect.zipRight(Ref.set(endAfterEmit, true)),\n                      core.fromEffect\n                    )\n                  }\n                }\n              })\n            )\n          }),\n          channel.unwrap\n        )\n        const timeout = (lastB: Option.Option<B>): Effect.Effect<C, Option.Option<never>, R2 | R3> =>\n          scheduleDriver.next(lastB)\n        const scheduledAggregator = (\n          sinkFiber: Fiber.RuntimeFiber<readonly [Chunk.Chunk<Chunk.Chunk<A | A2>>, B], E | E2>,\n          scheduleFiber: Fiber.RuntimeFiber<C, Option.Option<never>>,\n          scope: Scope.Scope\n        ): Channel.Channel<Chunk.Chunk<Either.Either<B, C>>, unknown, E | E2, unknown, unknown, unknown, R2 | R3> => {\n          const forkSink = pipe(\n            Ref.set(consumed, false),\n            Effect.zipRight(Ref.set(endAfterEmit, false)),\n            Effect.zipRight(\n              pipe(\n                handoffConsumer,\n                channel.pipeToOrFail(sink_.toChannel(sink)),\n                core.collectElements,\n                channel.run,\n                Effect.forkIn(scope)\n              )\n            )\n          )\n          const handleSide = (\n            leftovers: Chunk.Chunk<Chunk.Chunk<A | A2>>,\n            b: B,\n            c: Option.Option<C>\n          ): Channel.Channel<Chunk.Chunk<Either.Either<B, C>>, unknown, E | E2, unknown, unknown, unknown, R2 | R3> =>\n            pipe(\n              Ref.set(sinkLeftovers, Chunk.flatten(leftovers)),\n              Effect.zipRight(\n                Effect.map(Ref.get(sinkEndReason), (reason) => {\n                  switch (reason._tag) {\n                    case SinkEndReason.OP_SCHEDULE_END: {\n                      return pipe(\n                        Effect.all([\n                          Ref.get(consumed),\n                          forkSink,\n                          pipe(timeout(Option.some(b)), Effect.forkIn(scope))\n                        ]),\n                        Effect.map(([wasConsumed, sinkFiber, scheduleFiber]) => {\n                          const toWrite = pipe(\n                            c,\n                            Option.match({\n                              onNone: (): Chunk.Chunk<Either.Either<B, C>> => Chunk.of(Either.right(b)),\n                              onSome: (c): Chunk.Chunk<Either.Either<B, C>> =>\n                                Chunk.make(Either.right(b), Either.left(c))\n                            })\n                          )\n                          if (wasConsumed) {\n                            return pipe(\n                              core.write(toWrite),\n                              core.flatMap(() => scheduledAggregator(sinkFiber, scheduleFiber, scope))\n                            )\n                          }\n                          return scheduledAggregator(sinkFiber, scheduleFiber, scope)\n                        }),\n                        channel.unwrap\n                      )\n                    }\n                    case SinkEndReason.OP_UPSTREAM_END: {\n                      return pipe(\n                        Ref.get(consumed),\n                        Effect.map((wasConsumed) =>\n                          wasConsumed ?\n                            core.write(Chunk.of<Either.Either<B, C>>(Either.right(b))) :\n                            core.void\n                        ),\n                        channel.unwrap\n                      )\n                    }\n                  }\n                })\n              ),\n              channel.unwrap\n            )\n          return channel.unwrap(\n            Effect.raceWith(Fiber.join(sinkFiber), Fiber.join(scheduleFiber), {\n              onSelfDone: (sinkExit, _) =>\n                pipe(\n                  Fiber.interrupt(scheduleFiber),\n                  Effect.zipRight(pipe(\n                    Effect.suspend(() => sinkExit),\n                    Effect.map(([leftovers, b]) => handleSide(leftovers, b, Option.none()))\n                  ))\n                ),\n              onOtherDone: (scheduleExit, _) =>\n                Effect.matchCauseEffect(Effect.suspend(() => scheduleExit), {\n                  onFailure: (cause) =>\n                    Either.match(\n                      Cause.failureOrCause(cause),\n                      {\n                        onLeft: () =>\n                          pipe(\n                            handoff,\n                            Handoff.offer<HandoffSignal.HandoffSignal<A, E | E2>>(\n                              HandoffSignal.end(SinkEndReason.ScheduleEnd)\n                            ),\n                            Effect.forkDaemon,\n                            Effect.zipRight(\n                              pipe(\n                                Fiber.join(sinkFiber),\n                                Effect.map(([leftovers, b]) => handleSide(leftovers, b, Option.none()))\n                              )\n                            )\n                          ),\n                        onRight: (cause) =>\n                          pipe(\n                            handoff,\n                            Handoff.offer<HandoffSignal.HandoffSignal<A, E | E2>>(\n                              HandoffSignal.halt(cause)\n                            ),\n                            Effect.forkDaemon,\n                            Effect.zipRight(\n                              pipe(\n                                Fiber.join(sinkFiber),\n                                Effect.map(([leftovers, b]) => handleSide(leftovers, b, Option.none()))\n                              )\n                            )\n                          )\n                      }\n                    ),\n                  onSuccess: (c) =>\n                    pipe(\n                      handoff,\n                      Handoff.offer<HandoffSignal.HandoffSignal<A, E | E2>>(\n                        HandoffSignal.end(SinkEndReason.ScheduleEnd)\n                      ),\n                      Effect.forkDaemon,\n                      Effect.zipRight(\n                        pipe(\n                          Fiber.join(sinkFiber),\n                          Effect.map(([leftovers, b]) => handleSide(leftovers, b, Option.some(c)))\n                        )\n                      )\n                    )\n                })\n            })\n          )\n        }\n        return unwrapScopedWith((scope) =>\n          core.pipeTo(toChannel(self), handoffProducer).pipe(\n            channel.run,\n            Effect.forkIn(scope),\n            Effect.zipRight(\n              channel.pipeToOrFail(handoffConsumer, sink_.toChannel(sink)).pipe(\n                core.collectElements,\n                channel.run,\n                Effect.forkIn(scope),\n                Effect.flatMap((sinkFiber) =>\n                  timeout(Option.none()).pipe(\n                    Effect.forkIn(scope),\n                    Effect.map((scheduleFiber) =>\n                      new StreamImpl(\n                        scheduledAggregator(sinkFiber, scheduleFiber, scope)\n                      )\n                    )\n                  )\n                )\n              )\n            )\n          )\n        )\n      })\n    )\n  }\n)\n\n/** @internal */\nexport const as = dual<\n  <B>(value: B) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E, R>,\n  <A, E, R, B>(self: Stream.Stream<A, E, R>, value: B) => Stream.Stream<B, E, R>\n>(2, <A, E, R, B>(self: Stream.Stream<A, E, R>, value: B): Stream.Stream<B, E, R> => map(self, () => value))\n\nconst queueFromBufferOptions = <A, E>(\n  bufferSize?: number | \"unbounded\" | {\n    readonly bufferSize?: number | undefined\n    readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n  } | undefined\n): Effect.Effect<Queue.Queue<Take.Take<A, E>>> => {\n  if (bufferSize === \"unbounded\") {\n    return Queue.unbounded()\n  } else if (typeof bufferSize === \"number\" || bufferSize === undefined) {\n    return Queue.bounded(bufferSize ?? 16)\n  }\n  switch (bufferSize.strategy) {\n    case \"dropping\":\n      return Queue.dropping(bufferSize.bufferSize ?? 16)\n    case \"sliding\":\n      return Queue.sliding(bufferSize.bufferSize ?? 16)\n    default:\n      return Queue.bounded(bufferSize.bufferSize ?? 16)\n  }\n}\n\n/** @internal */\nexport const _async = <A, E = never, R = never>(\n  register: (\n    emit: Emit.Emit<R, E, A, void>\n  ) => Effect.Effect<void, never, R> | void,\n  bufferSize?: number | \"unbounded\" | {\n    readonly bufferSize?: number | undefined\n    readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n  } | undefined\n): Stream.Stream<A, E, R> =>\n  Effect.acquireRelease(\n    queueFromBufferOptions<A, E>(bufferSize),\n    (queue) => Queue.shutdown(queue)\n  ).pipe(\n    Effect.flatMap((output) =>\n      Effect.runtime<R>().pipe(\n        Effect.flatMap((runtime) =>\n          Effect.sync(() => {\n            const runPromiseExit = Runtime.runPromiseExit(runtime)\n            const canceler = register(emit.make<R, E, A, void>((resume) =>\n              InternalTake.fromPull(resume).pipe(\n                Effect.flatMap((take) => Queue.offer(output, take)),\n                Effect.asVoid,\n                runPromiseExit\n              ).then((exit) => {\n                if (Exit.isFailure(exit)) {\n                  if (!Cause.isInterrupted(exit.cause)) {\n                    throw Cause.squash(exit.cause)\n                  }\n                }\n              })\n            ))\n            return canceler\n          })\n        ),\n        Effect.map((value) => {\n          const loop: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, void, unknown> = Queue.take(output).pipe(\n            Effect.flatMap((take) => InternalTake.done(take)),\n            Effect.match({\n              onFailure: (maybeError) =>\n                core.fromEffect(Queue.shutdown(output)).pipe(\n                  channel.zipRight(Option.match(maybeError, {\n                    onNone: () => core.void,\n                    onSome: (error) => core.fail(error)\n                  }))\n                ),\n              onSuccess: (chunk) => core.write(chunk).pipe(core.flatMap(() => loop))\n            }),\n            channel.unwrap\n          )\n          return fromChannel(loop).pipe(ensuring(value ?? Effect.void))\n        })\n      )\n    ),\n    unwrapScoped\n  )\n\n/** @internal */\nexport const asyncEffect = <A, E = never, R = never>(\n  register: (emit: Emit.Emit<R, E, A, void>) => Effect.Effect<unknown, E, R>,\n  bufferSize?: number | \"unbounded\" | {\n    readonly bufferSize?: number | undefined\n    readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n  } | undefined\n): Stream.Stream<A, E, R> =>\n  pipe(\n    Effect.acquireRelease(\n      queueFromBufferOptions<A, E>(bufferSize),\n      (queue) => Queue.shutdown(queue)\n    ),\n    Effect.flatMap((output) =>\n      pipe(\n        Effect.runtime<R>(),\n        Effect.flatMap((runtime) =>\n          pipe(\n            register(\n              emit.make((k) =>\n                pipe(\n                  InternalTake.fromPull(k),\n                  Effect.flatMap((take) => Queue.offer(output, take)),\n                  Effect.asVoid,\n                  Runtime.runPromiseExit(runtime)\n                ).then((exit) => {\n                  if (Exit.isFailure(exit)) {\n                    if (!Cause.isInterrupted(exit.cause)) {\n                      throw Cause.squash(exit.cause)\n                    }\n                  }\n                })\n              )\n            ),\n            Effect.map(() => {\n              const loop: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, void, unknown> = pipe(\n                Queue.take(output),\n                Effect.flatMap(InternalTake.done),\n                Effect.match({\n                  onFailure: (maybeError) =>\n                    pipe(\n                      core.fromEffect(Queue.shutdown(output)),\n                      channel.zipRight(Option.match(maybeError, { onNone: () => core.void, onSome: core.fail }))\n                    ),\n                  onSuccess: (chunk) => pipe(core.write(chunk), core.flatMap(() => loop))\n                }),\n                channel.unwrap\n              )\n              return loop\n            })\n          )\n        )\n      )\n    ),\n    channel.unwrapScoped,\n    fromChannel\n  )\n\nconst queueFromBufferOptionsPush = <A, E>(\n  options?: { readonly bufferSize: \"unbounded\" } | {\n    readonly bufferSize?: number | undefined\n    readonly strategy?: \"dropping\" | \"sliding\" | undefined\n  } | undefined\n): Effect.Effect<Queue.Queue<Array<A> | Exit.Exit<void, E>>> => {\n  if (options?.bufferSize === \"unbounded\" || (options?.bufferSize === undefined && options?.strategy === undefined)) {\n    return Queue.unbounded()\n  }\n  switch (options?.strategy) {\n    case \"sliding\":\n      return Queue.sliding(options.bufferSize ?? 16)\n    default:\n      return Queue.dropping(options?.bufferSize ?? 16)\n  }\n}\n\n/** @internal */\nexport const asyncPush = <A, E = never, R = never>(\n  register: (emit: Emit.EmitOpsPush<E, A>) => Effect.Effect<unknown, E, R | Scope.Scope>,\n  options?: {\n    readonly bufferSize: \"unbounded\"\n  } | {\n    readonly bufferSize?: number | undefined\n    readonly strategy?: \"dropping\" | \"sliding\" | undefined\n  } | undefined\n): Stream.Stream<A, E, Exclude<R, Scope.Scope>> =>\n  Effect.acquireRelease(\n    queueFromBufferOptionsPush<A, E>(options),\n    Queue.shutdown\n  ).pipe(\n    Effect.tap((queue) =>\n      FiberRef.getWith(FiberRef.currentScheduler, (scheduler) => register(emit.makePush(queue, scheduler)))\n    ),\n    Effect.map((queue) => {\n      const loop: Channel.Channel<Chunk.Chunk<A>, unknown, E> = core.flatMap(Queue.take(queue), (item) =>\n        Exit.isExit(item)\n          ? Exit.isSuccess(item) ? core.void : core.failCause(item.cause)\n          : channel.zipRight(core.write(Chunk.unsafeFromArray(item)), loop))\n      return loop\n    }),\n    channel.unwrapScoped,\n    fromChannel\n  )\n\n/** @internal */\nexport const asyncScoped = <A, E = never, R = never>(\n  register: (emit: Emit.Emit<R, E, A, void>) => Effect.Effect<unknown, E, R | Scope.Scope>,\n  bufferSize?: number | \"unbounded\" | {\n    readonly bufferSize?: number | undefined\n    readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n  } | undefined\n): Stream.Stream<A, E, Exclude<R, Scope.Scope>> =>\n  pipe(\n    Effect.acquireRelease(\n      queueFromBufferOptions<A, E>(bufferSize),\n      (queue) => Queue.shutdown(queue)\n    ),\n    Effect.flatMap((output) =>\n      pipe(\n        Effect.runtime<R>(),\n        Effect.flatMap((runtime) =>\n          pipe(\n            register(\n              emit.make((k) =>\n                pipe(\n                  InternalTake.fromPull(k),\n                  Effect.flatMap((take) => Queue.offer(output, take)),\n                  Effect.asVoid,\n                  Runtime.runPromiseExit(runtime)\n                ).then((exit) => {\n                  if (Exit.isFailure(exit)) {\n                    if (!Cause.isInterrupted(exit.cause)) {\n                      throw Cause.squash(exit.cause)\n                    }\n                  }\n                })\n              )\n            ),\n            Effect.zipRight(Ref.make(false)),\n            Effect.flatMap((ref) =>\n              pipe(\n                Ref.get(ref),\n                Effect.map((isDone) =>\n                  isDone ?\n                    pull.end() :\n                    pipe(\n                      Queue.take(output),\n                      Effect.flatMap(InternalTake.done),\n                      Effect.onError(() =>\n                        pipe(\n                          Ref.set(ref, true),\n                          Effect.zipRight(Queue.shutdown(output))\n                        )\n                      )\n                    )\n                )\n              )\n            )\n          )\n        )\n      )\n    ),\n    scoped,\n    flatMap(repeatEffectChunkOption)\n  )\n\n/** @internal */\nexport const branchAfter = dual<\n  <A, A2, E2, R2>(\n    n: number,\n    f: (input: Chunk.Chunk<A>) => Stream.Stream<A2, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    n: number,\n    f: (input: Chunk.Chunk<A>) => Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  3,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    n: number,\n    f: (input: Chunk.Chunk<A>) => Stream.Stream<A2, E2, R2>\n  ) =>\n    suspend(() => {\n      const buffering = (\n        acc: Chunk.Chunk<A>\n      ): Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, never, unknown, unknown, R | R2> =>\n        core.readWith({\n          onInput: (input) => {\n            const nextSize = acc.length + input.length\n            if (nextSize >= n) {\n              const [b1, b2] = pipe(input, Chunk.splitAt(n - acc.length))\n              return running(pipe(acc, Chunk.appendAll(b1)), b2)\n            }\n            return buffering(pipe(acc, Chunk.appendAll(input)))\n          },\n          onFailure: core.fail,\n          onDone: () => running(acc, Chunk.empty())\n        })\n      const running = (\n        prefix: Chunk.Chunk<A>,\n        leftover: Chunk.Chunk<A>\n      ): Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, never, unknown, unknown, R | R2> =>\n        core.pipeTo(\n          channel.zipRight(\n            core.write(leftover),\n            channel.identityChannel()\n          ),\n          toChannel(f(prefix))\n        )\n      return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(buffering(Chunk.empty<A>()))))\n    })\n)\n\n/** @internal */\nexport const broadcast = dual<\n  <N extends number>(\n    n: N,\n    maximumLag: number | {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ) => <A, E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<Types.TupleOf<N, Stream.Stream<A, E>>, never, Scope.Scope | R>,\n  <A, E, R, N extends number>(\n    self: Stream.Stream<A, E, R>,\n    n: N,\n    maximumLag: number | {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ) => Effect.Effect<Types.TupleOf<N, Stream.Stream<A, E>>, never, Scope.Scope | R>\n>(3, <A, E, R, N extends number>(\n  self: Stream.Stream<A, E, R>,\n  n: N,\n  maximumLag: number | {\n    readonly capacity: \"unbounded\"\n    readonly replay?: number | undefined\n  } | {\n    readonly capacity: number\n    readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n    readonly replay?: number | undefined\n  }\n): Effect.Effect<Types.TupleOf<N, Stream.Stream<A, E>>, never, Scope.Scope | R> =>\n  pipe(\n    self,\n    broadcastedQueues(n, maximumLag),\n    Effect.map((tuple) =>\n      tuple.map((queue) => flattenTake(fromQueue(queue, { shutdown: true }))) as Types.TupleOf<N, Stream.Stream<A, E>>\n    )\n  ))\n\n/** @internal */\nexport const broadcastDynamic = dual<\n  (\n    maximumLag: number | {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<Stream.Stream<A, E>, never, Scope.Scope | R>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    maximumLag: number | {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ) => Effect.Effect<Stream.Stream<A, E>, never, Scope.Scope | R>\n>(2, <A, E, R>(\n  self: Stream.Stream<A, E, R>,\n  maximumLag: number | {\n    readonly capacity: \"unbounded\"\n    readonly replay?: number | undefined\n  } | {\n    readonly capacity: number\n    readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n    readonly replay?: number | undefined\n  }\n): Effect.Effect<Stream.Stream<A, E>, never, Scope.Scope | R> =>\n  Effect.map(toPubSub(self, maximumLag), (pubsub) => flattenTake(fromPubSub(pubsub))))\n\nexport const share = dual<\n  <A, E>(\n    config: {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n    }\n  ) => <R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<Stream.Stream<A, E>, never, R | Scope.Scope>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    config: {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n    }\n  ) => Effect.Effect<Stream.Stream<A, E>, never, R | Scope.Scope>\n>(\n  2,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n      readonly idleTimeToLive?: Duration.DurationInput | undefined\n    }\n  ): Effect.Effect<Stream.Stream<A, E>, never, R | Scope.Scope> =>\n    Effect.map(\n      RcRef.make({\n        acquire: broadcastDynamic(self, options),\n        idleTimeToLive: options.idleTimeToLive\n      }),\n      (rcRef) => unwrapScoped(RcRef.get(rcRef))\n    )\n)\n\n/** @internal */\nexport const broadcastedQueues = dual<\n  <N extends number>(\n    n: N,\n    maximumLag: number | {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ) => <A, E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<Types.TupleOf<N, Queue.Dequeue<Take.Take<A, E>>>, never, Scope.Scope | R>,\n  <A, E, R, N extends number>(\n    self: Stream.Stream<A, E, R>,\n    n: N,\n    maximumLag: number | {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ) => Effect.Effect<Types.TupleOf<N, Queue.Dequeue<Take.Take<A, E>>>, never, Scope.Scope | R>\n>(3, <A, E, R, N extends number>(\n  self: Stream.Stream<A, E, R>,\n  n: N,\n  maximumLag: number | {\n    readonly capacity: \"unbounded\"\n    readonly replay?: number | undefined\n  } | {\n    readonly capacity: number\n    readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n    readonly replay?: number | undefined\n  }\n): Effect.Effect<Types.TupleOf<N, Queue.Dequeue<Take.Take<A, E>>>, never, Scope.Scope | R> =>\n  Effect.flatMap(pubsubFromOptions(maximumLag), (pubsub) =>\n    pipe(\n      Effect.all(Array.from({ length: n }, () => PubSub.subscribe(pubsub))) as Effect.Effect<\n        Types.TupleOf<N, Queue.Dequeue<Take.Take<A, E>>>,\n        never,\n        R\n      >,\n      Effect.tap(() => Effect.forkScoped(runIntoPubSubScoped(self, pubsub)))\n    )))\n\n/** @internal */\nexport const broadcastedQueuesDynamic = dual<\n  (\n    maximumLag: number | {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ) => <A, E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<Effect.Effect<Queue.Dequeue<Take.Take<A, E>>, never, Scope.Scope>, never, Scope.Scope | R>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    maximumLag: number | {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ) => Effect.Effect<Effect.Effect<Queue.Dequeue<Take.Take<A, E>>, never, Scope.Scope>, never, Scope.Scope | R>\n>(2, <A, E, R>(\n  self: Stream.Stream<A, E, R>,\n  maximumLag: number | {\n    readonly capacity: \"unbounded\"\n    readonly replay?: number | undefined\n  } | {\n    readonly capacity: number\n    readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n    readonly replay?: number | undefined\n  }\n): Effect.Effect<Effect.Effect<Queue.Dequeue<Take.Take<A, E>>, never, Scope.Scope>, never, Scope.Scope | R> =>\n  Effect.map(toPubSub(self, maximumLag), PubSub.subscribe))\n\n/** @internal */\nexport const buffer = dual<\n  (\n    options: {\n      readonly capacity: \"unbounded\"\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n    }\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly capacity: \"unbounded\"\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n    }\n  ) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(\n  self: Stream.Stream<A, E, R>,\n  options: {\n    readonly capacity: \"unbounded\"\n  } | {\n    readonly capacity: number\n    readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n  }\n): Stream.Stream<A, E, R> => {\n  if (options.capacity === \"unbounded\") {\n    return bufferUnbounded(self)\n  } else if (options.strategy === \"dropping\") {\n    return bufferDropping(self, options.capacity)\n  } else if (options.strategy === \"sliding\") {\n    return bufferSliding(self, options.capacity)\n  }\n  const queue = toQueueOfElements(self, options)\n  return new StreamImpl(\n    channel.unwrapScoped(\n      Effect.map(queue, (queue) => {\n        const process: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, void, unknown> = pipe(\n          core.fromEffect(Queue.take(queue)),\n          core.flatMap(Exit.match({\n            onFailure: (cause) =>\n              pipe(\n                Cause.flipCauseOption(cause),\n                Option.match({ onNone: () => core.void, onSome: core.failCause })\n              ),\n            onSuccess: (value) => core.flatMap(core.write(Chunk.of(value)), () => process)\n          }))\n        )\n        return process\n      })\n    )\n  )\n})\n\n/** @internal */\nexport const bufferChunks = dual<\n  (options: {\n    readonly capacity: number\n    readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n  }) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, options: {\n    readonly capacity: number\n    readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n  }) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, options: {\n  readonly capacity: number\n  readonly strategy?: \"dropping\" | \"sliding\" | \"suspend\" | undefined\n}): Stream.Stream<A, E, R> => {\n  if (options.strategy === \"dropping\") {\n    return bufferChunksDropping(self, options.capacity)\n  } else if (options.strategy === \"sliding\") {\n    return bufferChunksSliding(self, options.capacity)\n  }\n  const queue = toQueue(self, options)\n  return new StreamImpl(\n    channel.unwrapScoped(\n      Effect.map(queue, (queue) => {\n        const process: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, void, unknown> = pipe(\n          core.fromEffect(Queue.take(queue)),\n          core.flatMap(InternalTake.match({\n            onEnd: () => core.void,\n            onFailure: core.failCause,\n            onSuccess: (value) => pipe(core.write(value), core.flatMap(() => process))\n          }))\n        )\n        return process\n      })\n    )\n  )\n})\n\nconst bufferChunksDropping = dual<\n  (capacity: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, capacity: number) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, capacity: number): Stream.Stream<A, E, R> => {\n  const queue = Effect.acquireRelease(\n    Queue.dropping<readonly [Take.Take<A, E>, Deferred.Deferred<void>]>(capacity),\n    (queue) => Queue.shutdown(queue)\n  )\n  return new StreamImpl(bufferSignal(queue, toChannel(self)))\n})\n\nconst bufferChunksSliding = dual<\n  (capacity: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, capacity: number) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, capacity: number): Stream.Stream<A, E, R> => {\n  const queue = Effect.acquireRelease(\n    Queue.sliding<readonly [Take.Take<A, E>, Deferred.Deferred<void>]>(capacity),\n    (queue) => Queue.shutdown(queue)\n  )\n  return new StreamImpl(bufferSignal(queue, toChannel(self)))\n})\n\nconst bufferDropping = dual<\n  (capacity: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, capacity: number) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, capacity: number): Stream.Stream<A, E, R> => {\n  const queue = Effect.acquireRelease(\n    Queue.dropping<readonly [Take.Take<A, E>, Deferred.Deferred<void>]>(capacity),\n    (queue) => Queue.shutdown(queue)\n  )\n  return new StreamImpl(bufferSignal(queue, toChannel(rechunk(1)(self))))\n})\n\nconst bufferSliding = dual<\n  (capacity: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, capacity: number) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, capacity: number): Stream.Stream<A, E, R> => {\n  const queue = Effect.acquireRelease(\n    Queue.sliding<readonly [Take.Take<A, E>, Deferred.Deferred<void>]>(capacity),\n    (queue) => Queue.shutdown(queue)\n  )\n  return new StreamImpl(bufferSignal(queue, toChannel(pipe(self, rechunk(1)))))\n})\n\nconst bufferUnbounded = <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<A, E, R> => {\n  const queue = toQueue(self, { strategy: \"unbounded\" })\n  return new StreamImpl(\n    channel.unwrapScoped(\n      Effect.map(queue, (queue) => {\n        const process: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, void, unknown> = pipe(\n          core.fromEffect(Queue.take(queue)),\n          core.flatMap(InternalTake.match({\n            onEnd: () => core.void,\n            onFailure: core.failCause,\n            onSuccess: (value) => core.flatMap(core.write(value), () => process)\n          }))\n        )\n        return process\n      })\n    )\n  )\n}\n\nconst bufferSignal = <A, E, R>(\n  scoped: Effect.Effect<Queue.Queue<readonly [Take.Take<A, E>, Deferred.Deferred<void>]>, never, Scope.Scope>,\n  bufferChannel: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, void, unknown, R>\n): Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, void, unknown, R> => {\n  const producer = (\n    queue: Queue.Queue<readonly [Take.Take<A, E>, Deferred.Deferred<void>]>,\n    ref: Ref.Ref<Deferred.Deferred<void>>\n  ): Channel.Channel<never, Chunk.Chunk<A>, never, E, unknown, unknown, R> => {\n    const terminate = (take: Take.Take<A, E>): Channel.Channel<never, Chunk.Chunk<A>, never, E, unknown, unknown, R> =>\n      pipe(\n        Ref.get(ref),\n        Effect.tap(Deferred.await),\n        Effect.zipRight(Deferred.make<void>()),\n        Effect.flatMap((deferred) =>\n          pipe(\n            Queue.offer(queue, [take, deferred] as const),\n            Effect.zipRight(Ref.set(ref, deferred)),\n            Effect.zipRight(Deferred.await(deferred))\n          )\n        ),\n        Effect.asVoid,\n        core.fromEffect\n      )\n    return core.readWithCause({\n      onInput: (input: Chunk.Chunk<A>) =>\n        pipe(\n          Deferred.make<void>(),\n          Effect.flatMap(\n            (deferred) =>\n              pipe(\n                Queue.offer(queue, [InternalTake.chunk(input), deferred] as const),\n                Effect.flatMap((added) => pipe(Ref.set(ref, deferred), Effect.when(() => added)))\n              )\n          ),\n          Effect.asVoid,\n          core.fromEffect,\n          core.flatMap(() => producer(queue, ref))\n        ),\n      onFailure: (error) => terminate(InternalTake.failCause(error)),\n      onDone: () => terminate(InternalTake.end)\n    })\n  }\n  const consumer = (\n    queue: Queue.Queue<readonly [Take.Take<A, E>, Deferred.Deferred<void>]>\n  ): Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, void, unknown, R> => {\n    const process: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, void, unknown> = pipe(\n      core.fromEffect(Queue.take(queue)),\n      core.flatMap(([take, deferred]) =>\n        channel.zipRight(\n          core.fromEffect(Deferred.succeed(deferred, void 0)),\n          InternalTake.match(take, {\n            onEnd: () => core.void,\n            onFailure: core.failCause,\n            onSuccess: (value) => pipe(core.write(value), core.flatMap(() => process))\n          })\n        )\n      )\n    )\n    return process\n  }\n  return channel.unwrapScoped(\n    pipe(\n      scoped,\n      Effect.flatMap((queue) =>\n        pipe(\n          Deferred.make<void>(),\n          Effect.tap((start) => Deferred.succeed(start, void 0)),\n          Effect.flatMap((start) =>\n            pipe(\n              Ref.make(start),\n              Effect.flatMap((ref) =>\n                pipe(\n                  bufferChannel,\n                  core.pipeTo(producer(queue, ref)),\n                  channel.runScoped,\n                  Effect.forkScoped\n                )\n              ),\n              Effect.as(consumer(queue))\n            )\n          )\n        )\n      )\n    )\n  )\n}\n\n/** @internal */\nexport const catchAll = dual<\n  <E, A2, E2, R2>(\n    f: (error: E) => Stream.Stream<A2, E2, R2>\n  ) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (error: E) => Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<A2 | A, E2, R2 | R>\n>(2, <A, E, R, A2, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  f: (error: E) => Stream.Stream<A2, E2, R2>\n): Stream.Stream<A2 | A, E2, R2 | R> =>\n  catchAllCause(self, (cause) =>\n    Either.match(Cause.failureOrCause(cause), {\n      onLeft: f,\n      onRight: failCause\n    })))\n\n/** @internal */\nexport const catchAllCause = dual<\n  <E, A2, E2, R2>(\n    f: (cause: Cause.Cause<E>) => Stream.Stream<A2, E2, R2>\n  ) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (cause: Cause.Cause<E>) => Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<A2 | A, E2, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (cause: Cause.Cause<E>) => Stream.Stream<A2, E2, R2>\n  ): Stream.Stream<A | A2, E2, R | R2> =>\n    new StreamImpl<A | A2, E2, R | R2>(pipe(toChannel(self), core.catchAllCause((cause) => toChannel(f(cause)))))\n)\n\n/** @internal */\nexport const catchSome = dual<\n  <E, A2, E2, R2>(\n    pf: (error: E) => Option.Option<Stream.Stream<A2, E2, R2>>\n  ) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E | E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    pf: (error: E) => Option.Option<Stream.Stream<A2, E2, R2>>\n  ) => Stream.Stream<A2 | A, E | E2, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    pf: (error: E) => Option.Option<Stream.Stream<A2, E2, R2>>\n  ): Stream.Stream<A2 | A, E | E2, R2 | R> =>\n    pipe(self, catchAll((error) => pipe(pf(error), Option.getOrElse(() => fail<E | E2>(error)))))\n)\n\n/** @internal */\nexport const catchSomeCause = dual<\n  <E, A2, E2, R2>(\n    pf: (cause: Cause.Cause<E>) => Option.Option<Stream.Stream<A2, E2, R2>>\n  ) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E | E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    pf: (cause: Cause.Cause<E>) => Option.Option<Stream.Stream<A2, E2, R2>>\n  ) => Stream.Stream<A2 | A, E | E2, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    pf: (cause: Cause.Cause<E>) => Option.Option<Stream.Stream<A2, E2, R2>>\n  ): Stream.Stream<A2 | A, E | E2, R2 | R> =>\n    pipe(self, catchAllCause((cause) => pipe(pf(cause), Option.getOrElse(() => failCause<E | E2>(cause)))))\n)\n\n/* @internal */\nexport const catchTag = dual<\n  <K extends E[\"_tag\"] & string, E extends { _tag: string }, A1, E1, R1>(\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Stream.Stream<A1, E1, R1>\n  ) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A | A1, Exclude<E, { _tag: K }> | E1, R | R1>,\n  <A, E extends { _tag: string }, R, K extends E[\"_tag\"] & string, A1, E1, R1>(\n    self: Stream.Stream<A, E, R>,\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Stream.Stream<A1, E1, R1>\n  ) => Stream.Stream<A | A1, Exclude<E, { _tag: K }> | E1, R | R1>\n>(3, (self, k, f) =>\n  catchAll(self, (e) => {\n    if (\"_tag\" in e && e[\"_tag\"] === k) {\n      return f(e as any)\n    }\n    return fail(e as any)\n  }))\n\n/** @internal */\nexport const catchTags: {\n  <\n    E extends { _tag: string },\n    Cases extends {\n      [K in E[\"_tag\"]]+?: (error: Extract<E, { _tag: K }>) => Stream.Stream<any, any, any>\n    }\n  >(\n    cases: Cases\n  ): <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<\n    | A\n    | {\n      [K in keyof Cases]: Cases[K] extends\n        ((...args: Array<any>) => Stream.Stream.Variance<infer A, infer _E, infer _R>) ? A\n        : never\n    }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends\n        ((...args: Array<any>) => Stream.Stream.Variance<infer _A, infer E, infer _R>) ? E\n        : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends\n        ((...args: Array<any>) => Stream.Stream.Variance<infer _A, infer _E, infer R>) ? R\n        : never\n    }[keyof Cases]\n  >\n  <\n    A,\n    E extends { _tag: string },\n    R,\n    Cases extends {\n      [K in E[\"_tag\"]]+?: (error: Extract<E, { _tag: K }>) => Stream.Stream<any, any, any>\n    }\n  >(\n    self: Stream.Stream<A, E, R>,\n    cases: Cases\n  ): Stream.Stream<\n    | A\n    | {\n      [K in keyof Cases]: Cases[K] extends\n        ((...args: Array<any>) => Stream.Stream.Variance<infer _R, infer _E, infer A>) ? A\n        : never\n    }[keyof Cases],\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends\n        ((...args: Array<any>) => Stream.Stream.Variance<infer _R, infer E, infer _A>) ? E\n        : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends\n        ((...args: Array<any>) => Stream.Stream.Variance<infer R, infer _E, infer _A>) ? R\n        : never\n    }[keyof Cases]\n  >\n} = dual(2, (self, cases) =>\n  catchAll(self, (e: any) => {\n    const keys = Object.keys(cases)\n    if (\"_tag\" in e && keys.includes(e[\"_tag\"])) {\n      return cases[e[\"_tag\"]](e as any)\n    }\n    return fail(e as any)\n  }))\n\n/** @internal */\nexport const changes = <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<A, E, R> =>\n  pipe(self, changesWith((x, y) => Equal.equals(y)(x)))\n\n/** @internal */\nexport const changesWith = dual<\n  <A>(f: (x: A, y: A) => boolean) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, f: (x: A, y: A) => boolean) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, f: (x: A, y: A) => boolean): Stream.Stream<A, E, R> => {\n  const writer = (\n    last: Option.Option<A>\n  ): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E, E, void, unknown> =>\n    core.readWithCause({\n      onInput: (input: Chunk.Chunk<A>) => {\n        const [newLast, newChunk] = Chunk.reduce(\n          input,\n          [last, Chunk.empty<A>()] as const,\n          ([option, outputs], output) => {\n            if (Option.isSome(option) && f(option.value, output)) {\n              return [Option.some(output), outputs] as const\n            }\n            return [Option.some(output), pipe(outputs, Chunk.append(output))] as const\n          }\n        )\n        if (Chunk.isEmpty(newChunk)) return writer(newLast)\n        return core.flatMap(\n          core.write(newChunk),\n          () => writer(newLast)\n        )\n      },\n      onFailure: core.failCause,\n      onDone: () => core.void\n    })\n  return new StreamImpl(pipe(toChannel(self), core.pipeTo(writer(Option.none()))))\n})\n\n/** @internal */\nexport const changesWithEffect = dual<\n  <A, E2, R2>(\n    f: (x: A, y: A) => Effect.Effect<boolean, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (x: A, y: A) => Effect.Effect<boolean, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (x: A, y: A) => Effect.Effect<boolean, E2, R2>\n  ): Stream.Stream<A, E2 | E, R2 | R> => {\n    const writer = (\n      last: Option.Option<A>\n    ): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E | E2, void, unknown, R | R2> =>\n      core.readWithCause({\n        onInput: (input: Chunk.Chunk<A>) =>\n          pipe(\n            input,\n            Effect.reduce([last, Chunk.empty<A>()] as const, ([option, outputs], output) => {\n              if (Option.isSome(option)) {\n                return pipe(\n                  f(option.value, output),\n                  Effect.map((bool) =>\n                    bool ?\n                      [Option.some(output), outputs] as const :\n                      [Option.some(output), pipe(outputs, Chunk.append(output))] as const\n                  )\n                )\n              }\n              return Effect.succeed(\n                [\n                  Option.some(output),\n                  pipe(outputs, Chunk.append(output))\n                ] as const\n              )\n            }),\n            core.fromEffect,\n            core.flatMap(([newLast, newChunk]) =>\n              pipe(\n                core.write(newChunk),\n                core.flatMap(() => writer(newLast))\n              )\n            )\n          ),\n        onFailure: core.failCause,\n        onDone: () => core.void\n      })\n    return new StreamImpl(pipe(toChannel(self), core.pipeTo(writer(Option.none()))))\n  }\n)\n\n/** @internal */\nexport const chunks = <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<Chunk.Chunk<A>, E, R> =>\n  pipe(self, mapChunks(Chunk.of))\n\n/** @internal */\nexport const chunksWith = dual<\n  <A, E, R, A2, E2, R2>(\n    f: (stream: Stream.Stream<Chunk.Chunk<A>, E, R>) => Stream.Stream<Chunk.Chunk<A2>, E2, R2>\n  ) => (self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E | E2, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (stream: Stream.Stream<Chunk.Chunk<A>, E, R>) => Stream.Stream<Chunk.Chunk<A2>, E2, R2>\n  ) => Stream.Stream<A2, E | E2, R | R2>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (stream: Stream.Stream<Chunk.Chunk<A>, E, R>) => Stream.Stream<Chunk.Chunk<A2>, E2, R2>\n  ): Stream.Stream<A2, E | E2, R | R2> => flattenChunks(f(chunks(self)))\n)\n\nconst unsome = <A, E, R>(effect: Effect.Effect<A, Option.Option<E>, R>): Effect.Effect<Option.Option<A>, E, R> =>\n  Effect.catchAll(\n    Effect.asSome(effect),\n    (o) => o._tag === \"None\" ? Effect.succeedNone : Effect.fail(o.value)\n  )\n\n/** @internal */\nexport const combine = dual<\n  <A2, E2, R2, S, R3, E, A, R4, R5, A3>(\n    that: Stream.Stream<A2, E2, R2>,\n    s: S,\n    f: (\n      s: S,\n      pullLeft: Effect.Effect<A, Option.Option<E>, R3>,\n      pullRight: Effect.Effect<A2, Option.Option<E2>, R4>\n    ) => Effect.Effect<Exit.Exit<readonly [A3, S], Option.Option<E2 | E>>, never, R5>\n  ) => <R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A3, E2 | E, R2 | R3 | R4 | R5 | R>,\n  <R, A2, E2, R2, S, R3, E, A, R4, R5, A3>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>,\n    s: S,\n    f: (\n      s: S,\n      pullLeft: Effect.Effect<A, Option.Option<E>, R3>,\n      pullRight: Effect.Effect<A2, Option.Option<E2>, R4>\n    ) => Effect.Effect<Exit.Exit<readonly [A3, S], Option.Option<E2 | E>>, never, R5>\n  ) => Stream.Stream<A3, E2 | E, R2 | R3 | R4 | R5 | R>\n>(4, <R, A2, E2, R2, S, R3, E, A, R4, R5, A3>(\n  self: Stream.Stream<A, E, R>,\n  that: Stream.Stream<A2, E2, R2>,\n  s: S,\n  f: (\n    s: S,\n    pullLeft: Effect.Effect<A, Option.Option<E>, R3>,\n    pullRight: Effect.Effect<A2, Option.Option<E2>, R4>\n  ) => Effect.Effect<Exit.Exit<readonly [A3, S], Option.Option<E2 | E>>, never, R5>\n): Stream.Stream<A3, E2 | E, R2 | R3 | R4 | R5 | R> => {\n  function producer<Err, Elem>(\n    handoff: Handoff.Handoff<Exit.Exit<Elem, Option.Option<Err>>>,\n    latch: Handoff.Handoff<void>\n  ): Channel.Channel<never, Elem, never, Err, unknown, unknown, R> {\n    return core.fromEffect(Handoff.take(latch)).pipe(\n      channel.zipRight(core.readWithCause({\n        onInput: (input) =>\n          core.flatMap(\n            core.fromEffect(\n              Handoff.offer<Exit.Exit<Elem, Option.Option<Err>>>(\n                handoff,\n                Exit.succeed(input)\n              )\n            ),\n            () => producer(handoff, latch)\n          ),\n        onFailure: (cause) =>\n          core.fromEffect(\n            Handoff.offer<Exit.Exit<Elem, Option.Option<Err>>>(\n              handoff,\n              Exit.failCause(pipe(cause, Cause.map(Option.some)))\n            )\n          ),\n        onDone: () =>\n          core.flatMap(\n            core.fromEffect(\n              Handoff.offer<Exit.Exit<Elem, Option.Option<Err>>>(\n                handoff,\n                Exit.fail(Option.none())\n              )\n            ),\n            () => producer(handoff, latch)\n          )\n      }))\n    )\n  }\n  return new StreamImpl(\n    channel.unwrapScopedWith((scope) =>\n      Effect.all([\n        Handoff.make<Exit.Exit<A, Option.Option<E>>>(),\n        Handoff.make<Exit.Exit<A2, Option.Option<E2>>>(),\n        Handoff.make<void>(),\n        Handoff.make<void>()\n      ]).pipe(\n        Effect.tap(([left, _, latchL]) =>\n          toChannel(self).pipe(\n            channel.concatMap(channel.writeChunk),\n            core.pipeTo(producer(left, latchL)),\n            channelExecutor.runIn(scope),\n            Effect.forkIn(scope)\n          )\n        ),\n        Effect.tap(([, right, _, rightL]) =>\n          toChannel(that).pipe(\n            channel.concatMap(channel.writeChunk),\n            core.pipeTo(producer(right, rightL)),\n            channelExecutor.runIn(scope),\n            Effect.forkIn(scope)\n          )\n        ),\n        Effect.map(([left, right, latchL, latchR]) => {\n          const pullLeft = Handoff.offer<void>(latchL, void 0).pipe(\n            Effect.zipRight(Handoff.take(left).pipe(Effect.flatMap(identity)))\n          )\n          const pullRight = Handoff.offer<void>(latchR, void 0).pipe(\n            Effect.zipRight(Handoff.take(right).pipe(Effect.flatMap(identity)))\n          )\n          return toChannel(unfoldEffect(s, (s) => Effect.flatMap(f(s, pullLeft, pullRight), unsome)))\n        })\n      )\n    )\n  )\n})\n\n/** @internal */\nexport const combineChunks = dual<\n  <A2, E2, R2, S, R3, E, A, R4, R5, A3>(\n    that: Stream.Stream<A2, E2, R2>,\n    s: S,\n    f: (\n      s: S,\n      pullLeft: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R3>,\n      pullRight: Effect.Effect<Chunk.Chunk<A2>, Option.Option<E2>, R4>\n    ) => Effect.Effect<Exit.Exit<readonly [Chunk.Chunk<A3>, S], Option.Option<E2 | E>>, never, R5>\n  ) => <R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A3, E2 | E, R2 | R3 | R4 | R5 | R>,\n  <R, A2, E2, R2, S, R3, E, A, R4, R5, A3>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>,\n    s: S,\n    f: (\n      s: S,\n      pullLeft: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R3>,\n      pullRight: Effect.Effect<Chunk.Chunk<A2>, Option.Option<E2>, R4>\n    ) => Effect.Effect<Exit.Exit<readonly [Chunk.Chunk<A3>, S], Option.Option<E2 | E>>, never, R5>\n  ) => Stream.Stream<A3, E2 | E, R2 | R3 | R4 | R5 | R>\n>(4, <R, A2, E2, R2, S, R3, E, A, R4, R5, A3>(\n  self: Stream.Stream<A, E, R>,\n  that: Stream.Stream<A2, E2, R2>,\n  s: S,\n  f: (\n    s: S,\n    pullLeft: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R3>,\n    pullRight: Effect.Effect<Chunk.Chunk<A2>, Option.Option<E2>, R4>\n  ) => Effect.Effect<Exit.Exit<readonly [Chunk.Chunk<A3>, S], Option.Option<E2 | E>>, never, R5>\n): Stream.Stream<A3, E2 | E, R2 | R3 | R4 | R5 | R> => {\n  const producer = <Err, Elem>(\n    handoff: Handoff.Handoff<Take.Take<Elem, Err>>,\n    latch: Handoff.Handoff<void>\n  ): Channel.Channel<never, Chunk.Chunk<Elem>, never, Err, unknown, unknown, R> =>\n    channel.zipRight(\n      core.fromEffect(Handoff.take(latch)),\n      core.readWithCause({\n        onInput: (input) =>\n          core.flatMap(\n            core.fromEffect(pipe(\n              handoff,\n              Handoff.offer<Take.Take<Elem, Err>>(InternalTake.chunk(input))\n            )),\n            () => producer(handoff, latch)\n          ),\n        onFailure: (cause) =>\n          core.fromEffect(\n            Handoff.offer<Take.Take<Elem, Err>>(\n              handoff,\n              InternalTake.failCause(cause)\n            )\n          ),\n        onDone: (): Channel.Channel<never, Chunk.Chunk<Elem>, never, Err, unknown, unknown, R> =>\n          core.fromEffect(Handoff.offer<Take.Take<Elem, Err>>(handoff, InternalTake.end))\n      })\n    )\n  return new StreamImpl(\n    channel.unwrapScopedWith((scope) =>\n      Effect.all([\n        Handoff.make<Take.Take<A, E>>(),\n        Handoff.make<Take.Take<A2, E2>>(),\n        Handoff.make<void>(),\n        Handoff.make<void>()\n      ]).pipe(\n        Effect.tap(([left, _, latchL]) =>\n          core.pipeTo(toChannel(self), producer(left, latchL)).pipe(\n            channelExecutor.runIn(scope),\n            Effect.forkIn(scope)\n          )\n        ),\n        Effect.tap(([_, right, __, latchR]) =>\n          core.pipeTo(toChannel(that), producer(right, latchR)).pipe(\n            channelExecutor.runIn(scope),\n            Effect.forkIn(scope)\n          )\n        ),\n        Effect.map(([left, right, latchL, latchR]) => {\n          const pullLeft = Handoff.offer<void>(latchL, void 0).pipe(\n            Effect.zipRight(Handoff.take(left).pipe(Effect.flatMap(InternalTake.done)))\n          )\n          const pullRight = Handoff.offer<void>(latchR, void 0).pipe(\n            Effect.zipRight(Handoff.take(right).pipe(Effect.flatMap(InternalTake.done)))\n          )\n          return toChannel(unfoldChunkEffect(s, (s) => Effect.flatMap(f(s, pullLeft, pullRight), unsome)))\n        })\n      )\n    )\n  )\n})\n\n/** @internal */\nexport const concat = dual<\n  <A2, E2, R2>(\n    that: Stream.Stream<A2, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<A2 | A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ): Stream.Stream<A2 | A, E2 | E, R2 | R> =>\n    new StreamImpl<A2 | A, E2 | E, R2 | R>(pipe(toChannel(self), channel.zipRight(toChannel(that))))\n)\n\n/** @internal */\nexport const concatAll = <A, E, R>(streams: Chunk.Chunk<Stream.Stream<A, E, R>>): Stream.Stream<A, E, R> =>\n  suspend(() => pipe(streams, Chunk.reduce(empty as Stream.Stream<A, E, R>, (x, y) => concat(y)(x))))\n\n/** @internal */\nexport const cross: {\n  <AR, ER, RR>(\n    right: Stream.Stream<AR, ER, RR>\n  ): <AL, EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<[AL, AR], EL | ER, RL | RR>\n  <AL, ER, RR, AR, EL, RL>(\n    left: Stream.Stream<AL, ER, RR>,\n    right: Stream.Stream<AR, EL, RL>\n  ): Stream.Stream<[AL, AR], EL | ER, RL | RR>\n} = dual(\n  2,\n  <AL, ER, RR, AR, EL, RL>(\n    left: Stream.Stream<AL, ER, RR>,\n    right: Stream.Stream<AR, EL, RL>\n  ): Stream.Stream<[AL, AR], EL | ER, RL | RR> => pipe(left, crossWith(right, (a, a2) => [a, a2]))\n)\n\n/** @internal */\nexport const crossLeft: {\n  <AR, ER, RR>(\n    right: Stream.Stream<AR, ER, RR>\n  ): <AL, EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<AL, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AL, EL | ER, RL | RR>\n} = dual(\n  2,\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AL, EL | ER, RL | RR> => pipe(left, crossWith(right, (a, _) => a))\n)\n\n/** @internal */\nexport const crossRight: {\n  <AR, ER, RR>(\n    right: Stream.Stream<AR, ER, RR>\n  ): <AL, EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<AR, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AR, EL | ER, RL | RR>\n} = dual(\n  2,\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AR, EL | ER, RL | RR> => flatMap(left, () => right)\n)\n\n/** @internal */\nexport const crossWith: {\n  <AR, ER, RR, AL, A>(\n    right: Stream.Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): <EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<A, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR, A>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): Stream.Stream<A, EL | ER, RL | RR>\n} = dual(\n  3,\n  <AL, EL, RL, AR, ER, RR, A>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): Stream.Stream<A, EL | ER, RL | RR> => pipe(left, flatMap((a) => pipe(right, map((b) => f(a, b)))))\n)\n\n/** @internal */\nexport const debounce = dual<\n  (duration: Duration.DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, duration: Duration.DurationInput) => Stream.Stream<A, E, R>\n>(\n  2,\n  <A, E, R>(self: Stream.Stream<A, E, R>, duration: Duration.DurationInput): Stream.Stream<A, E, R> =>\n    unwrapScopedWith((scope) =>\n      Effect.gen(function*() {\n        const handoff = yield* Handoff.make<HandoffSignal.HandoffSignal<A, E>>()\n\n        function enqueue(last: Chunk.Chunk<A>): Effect.Effect<\n          Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, unknown, unknown>\n        > {\n          return Clock.sleep(duration).pipe(\n            Effect.as(last),\n            Effect.forkIn(scope),\n            Effect.map((fiber) => consumer(DebounceState.previous(fiber)))\n          )\n        }\n\n        const producer: Channel.Channel<never, Chunk.Chunk<A>, E, E, unknown, unknown> = core.readWithCause({\n          onInput: (input: Chunk.Chunk<A>) =>\n            Option.match(Chunk.last(input), {\n              onNone: () => producer,\n              onSome: (elem) =>\n                core.fromEffect(Handoff.offer(handoff, HandoffSignal.emit(Chunk.of(elem)))).pipe(\n                  core.flatMap(() => producer)\n                )\n            }),\n          onFailure: (cause) =>\n            core.fromEffect(\n              Handoff.offer<HandoffSignal.HandoffSignal<A, E>>(handoff, HandoffSignal.halt(cause))\n            ),\n          onDone: () =>\n            core.fromEffect(\n              Handoff.offer<HandoffSignal.HandoffSignal<A, E>>(\n                handoff,\n                HandoffSignal.end(SinkEndReason.UpstreamEnd)\n              )\n            )\n        })\n\n        function consumer(\n          state: DebounceState.DebounceState<A, E>\n        ): Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, unknown, unknown> {\n          switch (state._tag) {\n            case DebounceState.OP_NOT_STARTED: {\n              return channel.unwrap(\n                Handoff.take(handoff).pipe(\n                  Effect.map((signal) => {\n                    switch (signal._tag) {\n                      case HandoffSignal.OP_EMIT: {\n                        return channel.unwrap(enqueue(signal.elements))\n                      }\n                      case HandoffSignal.OP_HALT: {\n                        return core.failCause(signal.cause)\n                      }\n                      case HandoffSignal.OP_END: {\n                        return core.void\n                      }\n                    }\n                  })\n                )\n              )\n            }\n            case DebounceState.OP_PREVIOUS: {\n              return channel.unwrap(\n                Handoff.take(handoff).pipe(\n                  Effect.forkIn(scope),\n                  Effect.flatMap((handoffFiber) =>\n                    Effect.raceWith(Fiber.join(state.fiber), Fiber.join(handoffFiber), {\n                      onSelfDone: (leftExit, current) =>\n                        Exit.match(leftExit, {\n                          onFailure: (cause) =>\n                            Fiber.interrupt(current).pipe(\n                              Effect.as(core.failCause(cause))\n                            ),\n                          onSuccess: (chunk) =>\n                            Fiber.interrupt(current).pipe(\n                              Effect.zipRight(Effect.succeed(\n                                core.write(chunk).pipe(\n                                  core.flatMap(() => consumer(DebounceState.current(handoffFiber)))\n                                )\n                              ))\n                            )\n                        }),\n                      onOtherDone: (rightExit, previous) =>\n                        Exit.match(rightExit, {\n                          onFailure: (cause) =>\n                            Fiber.interrupt(previous).pipe(\n                              Effect.as(core.failCause(cause))\n                            ),\n                          onSuccess: (signal) => {\n                            switch (signal._tag) {\n                              case HandoffSignal.OP_EMIT: {\n                                return Fiber.interrupt(previous).pipe(\n                                  Effect.zipRight(enqueue(signal.elements))\n                                )\n                              }\n                              case HandoffSignal.OP_HALT: {\n                                return Fiber.interrupt(previous).pipe(\n                                  Effect.as(core.failCause(signal.cause))\n                                )\n                              }\n                              case HandoffSignal.OP_END: {\n                                return Fiber.join(previous).pipe(\n                                  Effect.map((chunk) =>\n                                    core.write(chunk).pipe(\n                                      channel.zipRight(core.void)\n                                    )\n                                  )\n                                )\n                              }\n                            }\n                          }\n                        })\n                    })\n                  )\n                )\n              )\n            }\n            case DebounceState.OP_CURRENT: {\n              return channel.unwrap(\n                Fiber.join(state.fiber).pipe(\n                  Effect.map((signal) => {\n                    switch (signal._tag) {\n                      case HandoffSignal.OP_EMIT: {\n                        return channel.unwrap(enqueue(signal.elements))\n                      }\n                      case HandoffSignal.OP_HALT: {\n                        return core.failCause(signal.cause)\n                      }\n                      case HandoffSignal.OP_END: {\n                        return core.void\n                      }\n                    }\n                  })\n                )\n              )\n            }\n          }\n        }\n\n        return scopedWith((scope) =>\n          core.pipeTo(toChannel(self), producer).pipe(\n            channelExecutor.runIn(scope),\n            Effect.forkIn(scope)\n          )\n        ).pipe(crossRight(new StreamImpl(consumer(DebounceState.notStarted))))\n      })\n    )\n)\n\n/** @internal */\nexport const die = (defect: unknown): Stream.Stream<never> => fromEffect(Effect.die(defect))\n\n/** @internal */\nexport const dieSync = (evaluate: LazyArg<unknown>): Stream.Stream<never> => fromEffect(Effect.dieSync(evaluate))\n\n/** @internal */\nexport const dieMessage = (message: string): Stream.Stream<never> => fromEffect(Effect.dieMessage(message))\n\n/** @internal */\nexport const distributedWith = dual<\n  <N extends number, A>(\n    options: {\n      readonly size: N\n      readonly maximumLag: number\n      readonly decide: (a: A) => Effect.Effect<Predicate<number>>\n    }\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<\n    Types.TupleOf<N, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>>,\n    never,\n    Scope.Scope | R\n  >,\n  <A, E, R, N extends number>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly size: N\n      readonly maximumLag: number\n      readonly decide: (a: A) => Effect.Effect<Predicate<number>>\n    }\n  ) => Effect.Effect<\n    Types.TupleOf<N, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>>,\n    never,\n    Scope.Scope | R\n  >\n>(\n  2,\n  <A, E, R, N extends number>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly size: N\n      readonly maximumLag: number\n      readonly decide: (a: A) => Effect.Effect<Predicate<number>>\n    }\n  ): Effect.Effect<\n    Types.TupleOf<N, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>>,\n    never,\n    Scope.Scope | R\n  > =>\n    pipe(\n      Deferred.make<(a: A) => Effect.Effect<Predicate<number>>>(),\n      Effect.flatMap((deferred) =>\n        pipe(\n          self,\n          distributedWithDynamic({\n            maximumLag: options.maximumLag,\n            decide: (a) => Effect.flatMap(Deferred.await(deferred), (f) => f(a))\n          }),\n          Effect.flatMap((next) =>\n            pipe(\n              Effect.all(\n                Chunk.map(\n                  Chunk.range(0, options.size - 1),\n                  (id) => Effect.map(next, ([key, queue]) => [[key, id], queue] as const)\n                )\n              ),\n              Effect.map(Chunk.unsafeFromArray),\n              Effect.flatMap((entries) => {\n                const [mappings, queues] = Chunk.reduceRight(\n                  entries,\n                  [\n                    new Map<number, number>(),\n                    Chunk.empty<Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>>()\n                  ] as const,\n                  ([mappings, queues], [mapping, queue]) =>\n                    [\n                      mappings.set(mapping[0], mapping[1]),\n                      pipe(queues, Chunk.prepend(queue))\n                    ] as const\n                )\n                return pipe(\n                  Deferred.succeed(deferred, (a: A) =>\n                    Effect.map(options.decide(a), (f) => (key: number) => f(mappings.get(key)!))),\n                  Effect.as(\n                    Array.from(queues) as Types.TupleOf<N, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>>\n                  )\n                )\n              })\n            )\n          )\n        )\n      )\n    )\n)\n\n/** @internal */\nconst distributedWithDynamicId = { ref: 0 }\n\nconst newDistributedWithDynamicId = () => {\n  const current = distributedWithDynamicId.ref\n  distributedWithDynamicId.ref = current + 1\n  return current\n}\n\n/** @internal */\nexport const distributedWithDynamic = dual<\n  <A>(\n    options: {\n      readonly maximumLag: number\n      readonly decide: (a: A) => Effect.Effect<Predicate<number>>\n    }\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<\n    Effect.Effect<[number, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>]>,\n    never,\n    Scope.Scope | R\n  >,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly maximumLag: number\n      readonly decide: (a: A) => Effect.Effect<Predicate<number>>\n    }\n  ) => Effect.Effect<\n    Effect.Effect<[number, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>]>,\n    never,\n    Scope.Scope | R\n  >\n>(2, <A, E, R>(\n  self: Stream.Stream<A, E, R>,\n  options: {\n    readonly maximumLag: number\n    readonly decide: (a: A) => Effect.Effect<Predicate<number>>\n  }\n): Effect.Effect<\n  Effect.Effect<[number, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>]>,\n  never,\n  Scope.Scope | R\n> => distributedWithDynamicCallback(self, options.maximumLag, options.decide, () => Effect.void))\n\n/** @internal */\nexport const distributedWithDynamicCallback = dual<\n  <A, E, X>(\n    maximumLag: number,\n    decide: (a: A) => Effect.Effect<Predicate<number>>,\n    done: (exit: Exit.Exit<never, Option.Option<E>>) => Effect.Effect<X>\n  ) => <R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<\n    Effect.Effect<[number, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>]>,\n    never,\n    Scope.Scope | R\n  >,\n  <A, E, R, X>(\n    self: Stream.Stream<A, E, R>,\n    maximumLag: number,\n    decide: (a: A) => Effect.Effect<Predicate<number>>,\n    done: (exit: Exit.Exit<never, Option.Option<E>>) => Effect.Effect<X>\n  ) => Effect.Effect<\n    Effect.Effect<[number, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>]>,\n    never,\n    Scope.Scope | R\n  >\n>(4, <A, E, R, X>(\n  self: Stream.Stream<A, E, R>,\n  maximumLag: number,\n  decide: (a: A) => Effect.Effect<Predicate<number>>,\n  done: (exit: Exit.Exit<never, Option.Option<E>>) => Effect.Effect<X>\n): Effect.Effect<\n  Effect.Effect<[number, Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>]>,\n  never,\n  Scope.Scope | R\n> =>\n  pipe(\n    Effect.acquireRelease(\n      Ref.make<Map<number, Queue.Queue<Exit.Exit<A, Option.Option<E>>>>>(new Map()),\n      (ref, _) => pipe(Ref.get(ref), Effect.flatMap((queues) => pipe(queues.values(), Effect.forEach(Queue.shutdown))))\n    ),\n    Effect.flatMap((queuesRef) =>\n      Effect.gen(function*() {\n        const offer = (a: A): Effect.Effect<void> =>\n          pipe(\n            decide(a),\n            Effect.flatMap((shouldProcess) =>\n              pipe(\n                Ref.get(queuesRef),\n                Effect.flatMap((queues) =>\n                  pipe(\n                    queues.entries(),\n                    Effect.reduce(Chunk.empty<number>(), (acc, [id, queue]) => {\n                      if (shouldProcess(id)) {\n                        return pipe(\n                          Queue.offer(queue, Exit.succeed(a)),\n                          Effect.matchCauseEffect({\n                            onFailure: (cause) =>\n                              // Ignore all downstream queues that were shut\n                              // down and remove them later\n                              Cause.isInterrupted(cause) ?\n                                Effect.succeed(pipe(acc, Chunk.prepend(id))) :\n                                Effect.failCause(cause),\n                            onSuccess: () => Effect.succeed(acc)\n                          })\n                        )\n                      }\n                      return Effect.succeed(acc)\n                    }),\n                    Effect.flatMap((ids) => {\n                      if (Chunk.isNonEmpty(ids)) {\n                        return Ref.update(queuesRef, (map) => {\n                          for (const id of ids) {\n                            map.delete(id)\n                          }\n                          return map\n                        })\n                      }\n                      return Effect.void\n                    })\n                  )\n                )\n              )\n            ),\n            Effect.asVoid\n          )\n        const queuesLock = yield* Effect.makeSemaphore(1)\n        const newQueue = yield* Ref.make<Effect.Effect<[number, Queue.Queue<Exit.Exit<A, Option.Option<E>>>]>>(\n          pipe(\n            Queue.bounded<Exit.Exit<A, Option.Option<E>>>(maximumLag),\n            Effect.flatMap((queue) => {\n              const id = newDistributedWithDynamicId()\n              return pipe(\n                Ref.update(queuesRef, (map) => map.set(id, queue)),\n                Effect.as([id, queue])\n              )\n            })\n          )\n        )\n        const finalize = (endTake: Exit.Exit<never, Option.Option<E>>): Effect.Effect<void> =>\n          // Make sure that no queues are currently being added\n          queuesLock.withPermits(1)(\n            pipe(\n              Ref.set(\n                newQueue,\n                pipe(\n                  // All newly created queues should end immediately\n                  Queue.bounded<Exit.Exit<A, Option.Option<E>>>(1),\n                  Effect.tap((queue) => Queue.offer(queue, endTake)),\n                  Effect.flatMap((queue) => {\n                    const id = newDistributedWithDynamicId()\n                    return pipe(\n                      Ref.update(queuesRef, (map) => map.set(id, queue)),\n                      Effect.as(Tuple.make(id, queue))\n                    )\n                  })\n                )\n              ),\n              Effect.zipRight(\n                pipe(\n                  Ref.get(queuesRef),\n                  Effect.flatMap((map) =>\n                    pipe(\n                      Chunk.fromIterable(map.values()),\n                      Effect.forEach((queue) =>\n                        pipe(\n                          Queue.offer(queue, endTake),\n                          Effect.catchSomeCause((cause) =>\n                            Cause.isInterrupted(cause) ? Option.some(Effect.void) : Option.none()\n                          )\n                        )\n                      )\n                    )\n                  )\n                )\n              ),\n              Effect.zipRight(done(endTake)),\n              Effect.asVoid\n            )\n          )\n        yield* pipe(\n          self,\n          runForEachScoped(offer),\n          Effect.matchCauseEffect({\n            onFailure: (cause) => finalize(Exit.failCause(pipe(cause, Cause.map(Option.some)))),\n            onSuccess: () => finalize(Exit.fail(Option.none()))\n          }),\n          Effect.forkScoped\n        )\n        return queuesLock.withPermits(1)(\n          Effect.flatten(Ref.get(newQueue))\n        )\n      })\n    )\n  ))\n\n/** @internal */\nexport const drain = <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<never, E, R> =>\n  new StreamImpl(channel.drain(toChannel(self)))\n\n/** @internal */\nexport const drainFork = dual<\n  <A2, E2, R2>(\n    that: Stream.Stream<A2, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ): Stream.Stream<A, E2 | E, R2 | R> =>\n    fromEffect(Deferred.make<never, E2>()).pipe(flatMap((backgroundDied) =>\n      scopedWith((scope) =>\n        toChannel(that).pipe(\n          channel.drain,\n          channelExecutor.runIn(scope),\n          Effect.catchAllCause((cause) => Deferred.failCause(backgroundDied, cause)),\n          Effect.forkIn(scope)\n        )\n      ).pipe(crossRight(interruptWhenDeferred(self, backgroundDied)))\n    ))\n)\n\n/** @internal */\nexport const drop = dual<\n  (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, n: number) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, n: number): Stream.Stream<A, E, R> => {\n  const loop = (r: number): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, never, never, unknown, unknown> =>\n    core.readWith({\n      onInput: (input: Chunk.Chunk<A>) => {\n        const dropped = pipe(input, Chunk.drop(r))\n        const leftover = Math.max(0, r - input.length)\n        const more = Chunk.isEmpty(input) || leftover > 0\n        if (more) {\n          return loop(leftover)\n        }\n        return pipe(\n          core.write(dropped),\n          channel.zipRight(channel.identityChannel<Chunk.Chunk<A>, never, unknown>())\n        )\n      },\n      onFailure: core.fail,\n      onDone: () => core.void\n    })\n  return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(loop(n))))\n})\n\n/** @internal */\nexport const dropRight = dual<\n  (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, n: number) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, n: number): Stream.Stream<A, E, R> => {\n  if (n <= 0) {\n    return identityStream()\n  }\n  return suspend(() => {\n    const queue = new RingBuffer<A>(n)\n    const reader: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E, E, void, unknown> = core.readWith({\n      onInput: (input: Chunk.Chunk<A>) => {\n        const outputs = pipe(\n          input,\n          Chunk.filterMap((elem) => {\n            const head = queue.head()\n            queue.put(elem)\n            return head\n          })\n        )\n        return pipe(core.write(outputs), core.flatMap(() => reader))\n      },\n      onFailure: core.fail,\n      onDone: () => core.void\n    })\n    return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(reader)))\n  })\n})\n\n/** @internal */\nexport const dropUntil = dual<\n  <A>(predicate: Predicate<Types.NoInfer<A>>) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>) => Stream.Stream<A, E, R>\n>(\n  2,\n  <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>): Stream.Stream<A, E, R> =>\n    drop(dropWhile(self, (a) => !predicate(a)), 1)\n)\n\n/** @internal */\nexport const dropUntilEffect = dual<\n  <A, E2, R2>(\n    predicate: (a: Types.NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    predicate: (a: Types.NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    predicate: (a: Types.NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): Stream.Stream<A, E2 | E, R2 | R> => {\n    const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R2> = core.readWith({\n      onInput: (input: Chunk.Chunk<A>) =>\n        pipe(\n          Effect.dropUntil(input, predicate),\n          Effect.map(Chunk.unsafeFromArray),\n          Effect.map((leftover) => {\n            const more = Chunk.isEmpty(leftover)\n            if (more) {\n              return core.suspend(() => loop)\n            }\n            return pipe(\n              core.write(leftover),\n              channel.zipRight(channel.identityChannel<Chunk.Chunk<A>, E | E2, unknown>())\n            )\n          }),\n          channel.unwrap\n        ),\n      onFailure: core.fail,\n      onDone: () => core.void\n    })\n    return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(loop)))\n  }\n)\n\n/** @internal */\nexport const dropWhile = dual<\n  <A>(predicate: Predicate<Types.NoInfer<A>>) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>): Stream.Stream<A, E, R> => {\n  const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, never, never, unknown, unknown> = core.readWith({\n    onInput: (input: Chunk.Chunk<A>) => {\n      const output = Chunk.dropWhile(input, predicate)\n      if (Chunk.isEmpty(output)) {\n        return core.suspend(() => loop)\n      }\n      return channel.zipRight(\n        core.write(output),\n        channel.identityChannel<Chunk.Chunk<A>, never, unknown>()\n      )\n    },\n    onFailure: core.fail,\n    onDone: core.succeedNow\n  })\n  return new StreamImpl(channel.pipeToOrFail(toChannel(self), loop))\n})\n\n/** @internal */\nexport const dropWhileEffect = dual<\n  <A, E2, R2>(\n    predicate: (a: Types.NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    predicate: (a: A) => Effect.Effect<boolean, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    predicate: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): Stream.Stream<A, E2 | E, R2 | R> => {\n    const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R2> = core.readWith({\n      onInput: (input: Chunk.Chunk<A>) =>\n        pipe(\n          Effect.dropWhile(input, predicate),\n          Effect.map(Chunk.unsafeFromArray),\n          Effect.map((leftover) => {\n            const more = Chunk.isEmpty(leftover)\n            if (more) {\n              return core.suspend(() => loop)\n            }\n            return channel.zipRight(\n              core.write(leftover),\n              channel.identityChannel<Chunk.Chunk<A>, E | E2, unknown>()\n            )\n          }),\n          channel.unwrap\n        ),\n      onFailure: core.fail,\n      onDone: () => core.void\n    })\n    return new StreamImpl(channel.pipeToOrFail(\n      toChannel(self),\n      loop\n    ))\n  }\n)\n\n/** @internal */\nexport const either = <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<Either.Either<A, E>, never, R> =>\n  pipe(self, map(Either.right), catchAll((error) => make(Either.left(error))))\n\n/** @internal */\nexport const empty: Stream.Stream<never> = new StreamImpl(core.void)\n\n/** @internal */\nexport const ensuring = dual<\n  <X, R2>(\n    finalizer: Effect.Effect<X, never, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R2 | R>,\n  <A, E, R, X, R2>(self: Stream.Stream<A, E, R>, finalizer: Effect.Effect<X, never, R2>) => Stream.Stream<A, E, R2 | R>\n>(\n  2,\n  <A, E, R, X, R2>(self: Stream.Stream<A, E, R>, finalizer: Effect.Effect<X, never, R2>): Stream.Stream<A, E, R2 | R> =>\n    new StreamImpl(pipe(toChannel(self), channel.ensuring(finalizer)))\n)\n\n/** @internal */\nexport const ensuringWith = dual<\n  <E, R2>(\n    finalizer: (exit: Exit.Exit<unknown, E>) => Effect.Effect<unknown, never, R2>\n  ) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R | R2>,\n  <A, E, R, R2>(\n    self: Stream.Stream<A, E, R>,\n    finalizer: (exit: Exit.Exit<unknown, E>) => Effect.Effect<unknown, never, R2>\n  ) => Stream.Stream<A, E, R | R2>\n>(2, (self, finalizer) => new StreamImpl(core.ensuringWith(toChannel(self), finalizer)))\n\n/** @internal */\nexport const context = <R>(): Stream.Stream<Context.Context<R>, never, R> => fromEffect(Effect.context<R>())\n\n/** @internal */\nexport const contextWith = <R, A>(f: (env: Context.Context<R>) => A): Stream.Stream<A, never, R> =>\n  pipe(context<R>(), map(f))\n\n/** @internal */\nexport const contextWithEffect = <R0, A, E, R>(\n  f: (env: Context.Context<R0>) => Effect.Effect<A, E, R>\n): Stream.Stream<A, E, R0 | R> => pipe(context<R0>(), mapEffectSequential(f))\n\n/** @internal */\nexport const contextWithStream = <R0, A, E, R>(\n  f: (env: Context.Context<R0>) => Stream.Stream<A, E, R>\n): Stream.Stream<A, E, R0 | R> => pipe(context<R0>(), flatMap(f))\n\n/** @internal */\nexport const execute = <X, E, R>(effect: Effect.Effect<X, E, R>): Stream.Stream<never, E, R> =>\n  drain(fromEffect(effect))\n\n/** @internal */\nexport const fail = <E>(error: E): Stream.Stream<never, E> => fromEffectOption(Effect.fail(Option.some(error)))\n\n/** @internal */\nexport const failSync = <E>(evaluate: LazyArg<E>): Stream.Stream<never, E> =>\n  fromEffectOption(Effect.failSync(() => Option.some(evaluate())))\n\n/** @internal */\nexport const failCause = <E>(cause: Cause.Cause<E>): Stream.Stream<never, E> => fromEffect(Effect.failCause(cause))\n\n/** @internal */\nexport const failCauseSync = <E>(evaluate: LazyArg<Cause.Cause<E>>): Stream.Stream<never, E> =>\n  fromEffect(Effect.failCauseSync(evaluate))\n\n/** @internal */\nexport const filter: {\n  <A, B extends A>(\n    refinement: Refinement<Types.NoInfer<A>, B>\n  ): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E, R>\n  <A, B extends A>(predicate: Predicate<B>): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>\n  <A, E, R, B extends A>(self: Stream.Stream<A, E, R>, refinement: Refinement<A, B>): Stream.Stream<B, E, R>\n  <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>): Stream.Stream<A, E, R>\n} = dual(\n  2,\n  <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>) => mapChunks(self, Chunk.filter(predicate))\n)\n\n/** @internal */\nexport const filterEffect = dual<\n  <A, E2, R2>(\n    f: (a: Types.NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): Stream.Stream<A, E2 | E, R2 | R> => {\n    const loop = (\n      iterator: Iterator<A>\n    ): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R2> => {\n      const next = iterator.next()\n      if (next.done) {\n        return core.readWithCause({\n          onInput: (input) => loop(input[Symbol.iterator]()),\n          onFailure: core.failCause,\n          onDone: core.succeed\n        })\n      } else {\n        return pipe(\n          f(next.value),\n          Effect.map((bool) =>\n            bool ?\n              pipe(core.write(Chunk.of(next.value)), core.flatMap(() => loop(iterator))) :\n              loop(iterator)\n          ),\n          channel.unwrap\n        )\n      }\n    }\n    return new StreamImpl(\n      core.suspend(() => pipe(toChannel(self), core.pipeTo(loop(Chunk.empty<A>()[Symbol.iterator]()))))\n    )\n  }\n)\n\n/** @internal */\nexport const filterMap = dual<\n  <A, B>(pf: (a: A) => Option.Option<B>) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E, R>,\n  <A, E, R, B>(self: Stream.Stream<A, E, R>, pf: (a: A) => Option.Option<B>) => Stream.Stream<B, E, R>\n>(\n  2,\n  <A, E, R, B>(self: Stream.Stream<A, E, R>, pf: (a: A) => Option.Option<B>): Stream.Stream<B, E, R> =>\n    mapChunks(self, Chunk.filterMap(pf))\n)\n\n/** @internal */\nexport const filterMapEffect = dual<\n  <A, A2, E2, R2>(\n    pf: (a: A) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    pf: (a: A) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    pf: (a: A) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ): Stream.Stream<A2, E | E2, R | R2> =>\n    suspend(() => {\n      const loop = (\n        iterator: Iterator<A>\n      ): Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R | R2> => {\n        const next = iterator.next()\n        if (next.done) {\n          return core.readWithCause({\n            onInput: (input) => loop(input[Symbol.iterator]()),\n            onFailure: core.failCause,\n            onDone: core.succeed\n          })\n        } else {\n          return pipe(\n            pf(next.value),\n            Option.match({\n              onNone: () => Effect.sync(() => loop(iterator)),\n              onSome: Effect.map((a2) => core.flatMap(core.write(Chunk.of(a2)), () => loop(iterator)))\n            }),\n            channel.unwrap\n          )\n        }\n      }\n      return new StreamImpl(pipe(toChannel(self), core.pipeTo(loop(Chunk.empty<A>()[Symbol.iterator]()))))\n    })\n)\n\n/** @internal */\nexport const filterMapWhile = dual<\n  <A, A2>(\n    pf: (a: A) => Option.Option<A2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E, R>,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, pf: (a: A) => Option.Option<A2>) => Stream.Stream<A2, E, R>\n>(\n  2,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, pf: (a: A) => Option.Option<A2>) => {\n    const loop: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E, E, unknown, unknown> = core.readWith({\n      onInput: (input: Chunk.Chunk<A>) => {\n        const mapped = Chunk.filterMapWhile(input, pf)\n        if (mapped.length === input.length) {\n          return pipe(core.write(mapped), core.flatMap(() => loop))\n        }\n        return core.write(mapped)\n      },\n      onFailure: core.fail,\n      onDone: core.succeed\n    })\n    return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(loop)))\n  }\n)\n\n/** @internal */\nexport const filterMapWhileEffect = dual<\n  <A, A2, E2, R2>(\n    pf: (a: A) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    pf: (a: A) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    pf: (a: A) => Option.Option<Effect.Effect<A2, E2, R2>>\n  ): Stream.Stream<A2, E | E2, R | R2> =>\n    suspend(() => {\n      const loop = (\n        iterator: Iterator<A>\n      ): Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R | R2> => {\n        const next = iterator.next()\n        if (next.done) {\n          return core.readWithCause({\n            onInput: (input) => loop(input[Symbol.iterator]()),\n            onFailure: core.failCause,\n            onDone: core.succeed\n          })\n        } else {\n          return channel.unwrap(\n            Option.match(pf(next.value), {\n              onNone: () => Effect.succeed(core.void),\n              onSome: Effect.map(\n                (a2) => core.flatMap(core.write(Chunk.of(a2)), () => loop(iterator))\n              )\n            })\n          )\n        }\n      }\n      return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(loop(Chunk.empty<A>()[Symbol.iterator]()))))\n    })\n)\n\n/** @internal */\nexport const finalizer = <R, X>(finalizer: Effect.Effect<X, never, R>): Stream.Stream<void, never, R> =>\n  acquireRelease(Effect.void, () => finalizer)\n\n/** @internal */\nexport const find: {\n  <A, B extends A>(\n    refinement: Refinement<Types.NoInfer<A>, B>\n  ): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E, R>\n  <A>(predicate: Predicate<Types.NoInfer<A>>): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>\n  <A, E, R, B extends A>(self: Stream.Stream<A, E, R>, refinement: Refinement<A, B>): Stream.Stream<B, E, R>\n  <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>): Stream.Stream<A, E, R>\n} = dual(2, <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>): Stream.Stream<A, E, R> => {\n  const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E, E, unknown, unknown, R> = core.readWith({\n    onInput: (input: Chunk.Chunk<A>) =>\n      Option.match(Chunk.findFirst(input, predicate), {\n        onNone: () => loop,\n        onSome: (n) => core.write(Chunk.of(n))\n      }),\n    onFailure: core.fail,\n    onDone: () => core.void\n  })\n  return new StreamImpl(pipe(toChannel(self), core.pipeTo(loop)))\n})\n\n/** @internal */\nexport const findEffect: {\n  <A, E2, R2>(\n    predicate: (a: Types.NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    predicate: (a: Types.NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    predicate: (a: Types.NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> => {\n    const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R2> = core.readWith({\n      onInput: (input: Chunk.Chunk<A>) =>\n        pipe(\n          Effect.findFirst(input, predicate),\n          Effect.map(Option.match({\n            onNone: () => loop,\n            onSome: (n) => core.write(Chunk.of(n))\n          })),\n          channel.unwrap\n        ),\n      onFailure: core.fail,\n      onDone: () => core.void\n    })\n    return new StreamImpl(pipe(toChannel(self), core.pipeTo(loop)))\n  }\n)\n\n/** @internal */\nexport const flatMap = dual<\n  <A, A2, E2, R2>(\n    f: (a: A) => Stream.Stream<A2, E2, R2>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly bufferSize?: number | undefined\n      readonly switch?: boolean | undefined\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Stream.Stream<A2, E2, R2>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly bufferSize?: number | undefined\n      readonly switch?: boolean | undefined\n    }\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  (args) => isStream(args[0]),\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Stream.Stream<A2, E2, R2>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly bufferSize?: number | undefined\n      readonly switch?: boolean | undefined\n    }\n  ): Stream.Stream<A2, E | E2, R | R2> => {\n    const bufferSize = options?.bufferSize ?? 16\n\n    if (options?.switch) {\n      return matchConcurrency(\n        options?.concurrency,\n        () => flatMapParSwitchBuffer(self, 1, bufferSize, f),\n        (n) => flatMapParSwitchBuffer(self, n, bufferSize, f)\n      )\n    }\n\n    return matchConcurrency(\n      options?.concurrency,\n      () =>\n        new StreamImpl(\n          channel.concatMap(\n            toChannel(self),\n            (as) =>\n              pipe(\n                as,\n                Chunk.map((a) => toChannel(f(a))),\n                Chunk.reduce(\n                  core.void as Channel.Channel<Chunk.Chunk<A2>, unknown, E2, unknown, unknown, unknown, R2>,\n                  (left, right) => pipe(left, channel.zipRight(right))\n                )\n              )\n          )\n        ),\n      (_) =>\n        new StreamImpl(\n          pipe(\n            toChannel(self),\n            channel.concatMap(channel.writeChunk),\n            channel.mergeMap((out) => toChannel(f(out)), options as any)\n          )\n        )\n    )\n  }\n)\n\n/** @internal */\nexport const matchConcurrency = <A>(\n  concurrency: number | \"unbounded\" | undefined,\n  sequential: () => A,\n  bounded: (n: number) => A\n) => {\n  switch (concurrency) {\n    case undefined:\n      return sequential()\n    case \"unbounded\":\n      return bounded(Number.MAX_SAFE_INTEGER)\n    default:\n      return concurrency > 1 ? bounded(concurrency) : sequential()\n  }\n}\n\nconst flatMapParSwitchBuffer = dual<\n  <A, A2, E2, R2>(\n    n: number,\n    bufferSize: number,\n    f: (a: A) => Stream.Stream<A2, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    n: number,\n    bufferSize: number,\n    f: (a: A) => Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  4,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    n: number,\n    bufferSize: number,\n    f: (a: A) => Stream.Stream<A2, E2, R2>\n  ): Stream.Stream<A2, E | E2, R | R2> =>\n    new StreamImpl(\n      pipe(\n        toChannel(self),\n        channel.concatMap(channel.writeChunk),\n        channel.mergeMap((out) => toChannel(f(out)), {\n          concurrency: n,\n          mergeStrategy: MergeStrategy.BufferSliding(),\n          bufferSize\n        })\n      )\n    )\n)\n\n/** @internal */\nexport const flatten = dual<\n  (options?: {\n    readonly concurrency?: number | \"unbounded\" | undefined\n    readonly bufferSize?: number | undefined\n  }) => <A, E2, R2, E, R>(\n    self: Stream.Stream<Stream.Stream<A, E2, R2>, E, R>\n  ) => Stream.Stream<A, E | E2, R | R2>,\n  <A, E2, R2, E, R>(\n    self: Stream.Stream<Stream.Stream<A, E2, R2>, E, R>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly bufferSize?: number | undefined\n    }\n  ) => Stream.Stream<A, E | E2, R | R2>\n>((args) => isStream(args[0]), (self, options) => flatMap(self, identity, options))\n\n/** @internal */\nexport const flattenChunks = <A, E, R>(self: Stream.Stream<Chunk.Chunk<A>, E, R>): Stream.Stream<A, E, R> => {\n  const flatten: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<Chunk.Chunk<A>>, E, E, unknown, unknown> = core\n    .readWithCause({\n      onInput: (chunks: Chunk.Chunk<Chunk.Chunk<A>>) =>\n        core.flatMap(\n          channel.writeChunk(chunks),\n          () => flatten\n        ),\n      onFailure: core.failCause,\n      onDone: () => core.void\n    })\n  return new StreamImpl(pipe(toChannel(self), core.pipeTo(flatten)))\n}\n\n/** @internal */\nexport const flattenEffect = dual<\n  (\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly unordered?: boolean | undefined\n    }\n  ) => <A, E2, R2, E, R>(\n    self: Stream.Stream<Effect.Effect<A, E2, R2>, E, R>\n  ) => Stream.Stream<A, E | E2, R | R2>,\n  <A, E2, R2, E, R>(\n    self: Stream.Stream<Effect.Effect<A, E2, R2>, E, R>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly unordered?: boolean | undefined\n    }\n  ) => Stream.Stream<A, E | E2, R | R2>\n>(\n  (args) => isStream(args[0]),\n  (self, options) =>\n    options?.unordered ?\n      flatMap(self, (a) => fromEffect(a), { concurrency: options.concurrency }) :\n      matchConcurrency(\n        options?.concurrency,\n        () => mapEffectSequential(self, identity),\n        (n) =>\n          new StreamImpl(\n            pipe(\n              toChannel(self),\n              channel.concatMap(channel.writeChunk),\n              channel.mapOutEffectPar(identity, n),\n              channel.mapOut(Chunk.of)\n            )\n          )\n      )\n)\n\n/** @internal */\nexport const flattenExitOption = <A, E2, E, R>(\n  self: Stream.Stream<Exit.Exit<A, Option.Option<E2>>, E, R>\n): Stream.Stream<A, E | E2, R> => {\n  const processChunk = (\n    chunk: Chunk.Chunk<Exit.Exit<A, Option.Option<E2>>>,\n    cont: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<Exit.Exit<A, Option.Option<E2>>>, E | E2, E, unknown, unknown, R>\n  ) => {\n    const [toEmit, rest] = pipe(chunk, Chunk.splitWhere((exit) => !Exit.isSuccess(exit)))\n    const next = pipe(\n      Chunk.head(rest),\n      Option.match({\n        onNone: () => cont,\n        onSome: Exit.match({\n          onFailure: (cause) =>\n            Option.match(Cause.flipCauseOption(cause), {\n              onNone: () => core.void,\n              onSome: core.failCause\n            }),\n          onSuccess: () => core.void\n        })\n      })\n    )\n    return pipe(\n      core.write(pipe(\n        toEmit,\n        Chunk.filterMap((exit) =>\n          Exit.isSuccess(exit) ?\n            Option.some(exit.value) :\n            Option.none()\n        )\n      )),\n      core.flatMap(() => next)\n    )\n  }\n  const process: Channel.Channel<\n    Chunk.Chunk<A>,\n    Chunk.Chunk<Exit.Exit<A, Option.Option<E2>>>,\n    E | E2,\n    E,\n    unknown,\n    unknown,\n    R\n  > = core.readWithCause({\n    onInput: (chunk: Chunk.Chunk<Exit.Exit<A, Option.Option<E2>>>) => processChunk(chunk, process),\n    onFailure: (cause) => core.failCause<E | E2>(cause),\n    onDone: () => core.void\n  })\n  return new StreamImpl(pipe(toChannel(self), core.pipeTo(process)))\n}\n\n/** @internal */\nexport const flattenIterables = <A, E, R>(self: Stream.Stream<Iterable<A>, E, R>): Stream.Stream<A, E, R> =>\n  pipe(self, map(Chunk.fromIterable), flattenChunks)\n\n/** @internal */\nexport const flattenTake = <A, E2, E, R>(self: Stream.Stream<Take.Take<A, E2>, E, R>): Stream.Stream<A, E | E2, R> =>\n  flattenChunks(flattenExitOption(pipe(self, map((take) => take.exit))))\n\n/** @internal */\nexport const forever = <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<A, E, R> =>\n  new StreamImpl(channel.repeated(toChannel(self)))\n\n/** @internal */\nexport const fromAsyncIterable = <A, E>(\n  iterable: AsyncIterable<A>,\n  onError: (e: unknown) => E\n) =>\n  pipe(\n    Effect.acquireRelease(\n      Effect.sync(() => iterable[Symbol.asyncIterator]()),\n      (iterator) => iterator.return ? Effect.promise(async () => iterator.return!()) : Effect.void\n    ),\n    Effect.map((iterator) =>\n      repeatEffectOption(pipe(\n        Effect.tryPromise({\n          try: async () => iterator.next(),\n          catch: (reason) => Option.some(onError(reason))\n        }),\n        Effect.flatMap((result) => result.done ? Effect.fail(Option.none()) : Effect.succeed(result.value))\n      ))\n    ),\n    unwrapScoped\n  )\n\n/** @internal */\nexport const fromChannel = <A, E, R>(\n  channel: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, unknown, unknown, R>\n): Stream.Stream<A, E, R> => new StreamImpl(channel)\n\n/** @internal */\nexport const toChannel = <A, E, R>(\n  stream: Stream.Stream<A, E, R>\n): Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, unknown, unknown, R> => {\n  if (\"channel\" in stream) {\n    return (stream as StreamImpl<A, E, R>).channel\n  } else if (Effect.isEffect(stream)) {\n    return toChannel(fromEffect(stream)) as any\n  } else {\n    throw new TypeError(`Expected a Stream.`)\n  }\n}\n\n/** @internal */\nexport const fromChunk = <A>(chunk: Chunk.Chunk<A>): Stream.Stream<A> =>\n  new StreamImpl(Chunk.isEmpty(chunk) ? core.void : core.write(chunk))\n\n/** @internal */\nexport const fromChunkPubSub: {\n  <A>(pubsub: PubSub.PubSub<Chunk.Chunk<A>>, options: {\n    readonly scoped: true\n    readonly shutdown?: boolean | undefined\n  }): Effect.Effect<Stream.Stream<A>, never, Scope.Scope>\n  <A>(pubsub: PubSub.PubSub<Chunk.Chunk<A>>, options?: {\n    readonly scoped?: false | undefined\n    readonly shutdown?: boolean | undefined\n  }): Stream.Stream<A>\n} = (pubsub, options): any => {\n  if (options?.scoped) {\n    const effect = Effect.map(PubSub.subscribe(pubsub), fromChunkQueue)\n    return options.shutdown ? Effect.map(effect, ensuring(PubSub.shutdown(pubsub))) : effect\n  }\n  const stream = flatMap(scoped(PubSub.subscribe(pubsub)), fromChunkQueue)\n  return options?.shutdown ? ensuring(stream, PubSub.shutdown(pubsub)) : stream\n}\n\n/** @internal */\nexport const fromChunkQueue = <A>(queue: Queue.Dequeue<Chunk.Chunk<A>>, options?: {\n  readonly shutdown?: boolean | undefined\n}): Stream.Stream<A> =>\n  pipe(\n    Queue.take(queue),\n    Effect.catchAllCause((cause) =>\n      pipe(\n        Queue.isShutdown(queue),\n        Effect.flatMap((isShutdown) =>\n          isShutdown && Cause.isInterrupted(cause) ?\n            pull.end() :\n            pull.failCause(cause)\n        )\n      )\n    ),\n    repeatEffectChunkOption,\n    options?.shutdown ? ensuring(Queue.shutdown(queue)) : identity\n  )\n\n/** @internal */\nexport const fromChunks = <A>(\n  ...chunks: Array<Chunk.Chunk<A>>\n): Stream.Stream<A> => pipe(fromIterable(chunks), flatMap(fromChunk))\n\n/** @internal */\nexport const fromEffect = <A, E, R>(effect: Effect.Effect<A, E, R>): Stream.Stream<A, E, R> =>\n  pipe(effect, Effect.mapError(Option.some), fromEffectOption)\n\n/** @internal */\nexport const fromEffectOption = <A, E, R>(effect: Effect.Effect<A, Option.Option<E>, R>): Stream.Stream<A, E, R> =>\n  new StreamImpl(\n    channel.unwrap(\n      Effect.match(effect, {\n        onFailure: Option.match({\n          onNone: () => core.void,\n          onSome: core.fail\n        }),\n        onSuccess: (a) => core.write(Chunk.of(a))\n      })\n    )\n  )\n\n/** @internal */\nexport const fromPubSub: {\n  <A>(pubsub: PubSub.PubSub<A>, options: {\n    readonly scoped: true\n    readonly maxChunkSize?: number | undefined\n    readonly shutdown?: boolean | undefined\n  }): Effect.Effect<Stream.Stream<A>, never, Scope.Scope>\n  <A>(pubsub: PubSub.PubSub<A>, options?: {\n    readonly scoped?: false | undefined\n    readonly maxChunkSize?: number | undefined\n    readonly shutdown?: boolean | undefined\n  }): Stream.Stream<A>\n} = (pubsub, options): any => {\n  const maxChunkSize = options?.maxChunkSize ?? DefaultChunkSize\n\n  if (options?.scoped) {\n    const effect = Effect.map(\n      PubSub.subscribe(pubsub),\n      (queue) => fromQueue(queue, { maxChunkSize, shutdown: true })\n    )\n\n    return options.shutdown ? Effect.map(effect, ensuring(PubSub.shutdown(pubsub))) : effect\n  }\n  const stream = flatMap(\n    scoped(PubSub.subscribe(pubsub)),\n    (queue) => fromQueue(queue, { maxChunkSize })\n  )\n  return options?.shutdown ? ensuring(stream, PubSub.shutdown(pubsub)) : stream\n}\n\n/** @internal */\nexport const fromTPubSub = <A>(pubsub: TPubSub.TPubSub<A>): Stream.Stream<A> => {\n  return unwrapScoped(Effect.map(\n    TPubSub.subscribeScoped(pubsub),\n    (queue) => fromTQueue(queue)\n  ))\n}\n\n/** @internal */\nexport const fromIterable = <A>(iterable: Iterable<A>): Stream.Stream<A> =>\n  suspend(() =>\n    Chunk.isChunk(iterable) ?\n      fromChunk(iterable) :\n      fromIteratorSucceed(iterable[Symbol.iterator]())\n  )\n\n/** @internal */\nexport const fromIterableEffect = <A, E, R>(\n  effect: Effect.Effect<Iterable<A>, E, R>\n): Stream.Stream<A, E, R> => pipe(effect, Effect.map(fromIterable), unwrap)\n\n/** @internal */\nexport const fromIteratorSucceed = <A>(\n  iterator: Iterator<A>,\n  maxChunkSize = DefaultChunkSize\n): Stream.Stream<A> => {\n  return pipe(\n    Effect.sync(() => {\n      let builder: Array<A> = []\n      const loop = (\n        iterator: Iterator<A>\n      ): Channel.Channel<Chunk.Chunk<A>, unknown, never, unknown, unknown, unknown> =>\n        pipe(\n          Effect.sync(() => {\n            let next: IteratorResult<A, any> = iterator.next()\n            if (maxChunkSize === 1) {\n              if (next.done) {\n                return core.void\n              }\n              return pipe(\n                core.write(Chunk.of(next.value)),\n                core.flatMap(() => loop(iterator))\n              )\n            }\n            builder = []\n            let count = 0\n            while (next.done === false) {\n              builder.push(next.value)\n              count = count + 1\n              if (count >= maxChunkSize) {\n                break\n              }\n              next = iterator.next()\n            }\n            if (count > 0) {\n              return pipe(\n                core.write(Chunk.unsafeFromArray(builder)),\n                core.flatMap(() => loop(iterator))\n              )\n            }\n            return core.void\n          }),\n          channel.unwrap\n        )\n      return new StreamImpl(loop(iterator))\n    }),\n    unwrap\n  )\n}\n\n/** @internal */\nexport const fromPull = <R, R2, E, A>(\n  effect: Effect.Effect<Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R2>, never, R | Scope.Scope>\n): Stream.Stream<A, E, Exclude<R, Scope.Scope> | R2> => pipe(effect, Effect.map(repeatEffectChunkOption), unwrapScoped)\n\n/** @internal */\nexport const fromQueue = <A>(\n  queue: Queue.Dequeue<A>,\n  options?: {\n    readonly maxChunkSize?: number | undefined\n    readonly shutdown?: boolean | undefined\n  }\n): Stream.Stream<A> =>\n  pipe(\n    Queue.takeBetween(queue, 1, options?.maxChunkSize ?? DefaultChunkSize),\n    Effect.catchAllCause((cause) =>\n      pipe(\n        Queue.isShutdown(queue),\n        Effect.flatMap((isShutdown) =>\n          isShutdown && Cause.isInterrupted(cause) ?\n            pull.end() :\n            pull.failCause(cause)\n        )\n      )\n    ),\n    repeatEffectChunkOption,\n    options?.shutdown ? ensuring(Queue.shutdown(queue)) : identity\n  )\n\n/** @internal */\nexport const fromTQueue = <A>(queue: TQueue.TDequeue<A>): Stream.Stream<A> =>\n  pipe(\n    TQueue.take(queue),\n    Effect.map(Chunk.of),\n    Effect.catchAllCause((cause) =>\n      pipe(\n        TQueue.isShutdown(queue),\n        Effect.flatMap((isShutdown) =>\n          isShutdown && Cause.isInterrupted(cause) ?\n            pull.end() :\n            pull.failCause(cause)\n        )\n      )\n    ),\n    repeatEffectChunkOption\n  )\n\n/** @internal */\nexport const fromSchedule = <A, R>(schedule: Schedule.Schedule<A, unknown, R>): Stream.Stream<A, never, R> =>\n  pipe(\n    Schedule.driver(schedule),\n    Effect.map((driver) => repeatEffectOption(driver.next(void 0))),\n    unwrap\n  )\n\n/** @internal */\nexport const fromReadableStream: {\n  <A, E>(\n    options: {\n      readonly evaluate: LazyArg<ReadableStream<A>>\n      readonly onError: (error: unknown) => E\n      readonly releaseLockOnEnd?: boolean | undefined\n    }\n  ): Stream.Stream<A, E>\n  <A, E>(\n    evaluate: LazyArg<ReadableStream<A>>,\n    onError: (error: unknown) => E\n  ): Stream.Stream<A, E>\n} = <A, E>(\n  ...args: [options: {\n    readonly evaluate: LazyArg<ReadableStream<A>>\n    readonly onError: (error: unknown) => E\n    readonly releaseLockOnEnd?: boolean | undefined\n  }] | [\n    evaluate: LazyArg<ReadableStream<A>>,\n    onError: (error: unknown) => E\n  ]\n): Stream.Stream<A, E> => {\n  const evaluate = args.length === 1 ? args[0].evaluate : args[0]\n  const onError = args.length === 1 ? args[0].onError : args[1]\n  const releaseLockOnEnd = args.length === 1 ? args[0].releaseLockOnEnd === true : false\n  return unwrapScoped(Effect.map(\n    Effect.acquireRelease(\n      Effect.sync(() => evaluate().getReader()),\n      (reader) =>\n        releaseLockOnEnd\n          ? Effect.sync(() => reader.releaseLock())\n          : Effect.promise(() => reader.cancel())\n    ),\n    (reader) =>\n      repeatEffectOption(\n        Effect.flatMap(\n          Effect.tryPromise({\n            try: () => reader.read(),\n            catch: (reason) => Option.some(onError(reason))\n          }),\n          ({ done, value }) => done ? Effect.fail(Option.none()) : Effect.succeed(value)\n        )\n      )\n  ))\n}\n\n/** @internal */\nexport const fromReadableStreamByob: {\n  <E>(\n    options: {\n      readonly evaluate: LazyArg<ReadableStream<Uint8Array>>\n      readonly onError: (error: unknown) => E\n      readonly bufferSize?: number | undefined\n      readonly releaseLockOnEnd?: boolean | undefined\n    }\n  ): Stream.Stream<Uint8Array, E>\n  <E>(\n    evaluate: LazyArg<ReadableStream<Uint8Array>>,\n    onError: (error: unknown) => E,\n    allocSize?: number\n  ): Stream.Stream<Uint8Array, E>\n} = <E>(\n  ...args: [options: {\n    readonly evaluate: LazyArg<ReadableStream<Uint8Array>>\n    readonly onError: (error: unknown) => E\n    readonly bufferSize?: number | undefined\n    readonly releaseLockOnEnd?: boolean | undefined\n  }] | [\n    evaluate: LazyArg<ReadableStream<Uint8Array>>,\n    onError: (error: unknown) => E,\n    allocSize?: number | undefined\n  ]\n): Stream.Stream<Uint8Array, E> => {\n  const evaluate = args.length === 1 ? args[0].evaluate : args[0]\n  const onError = args.length === 1 ? args[0].onError : args[1]\n  const allocSize = (args.length === 1 ? args[0].bufferSize : args[2]) ?? 4096\n  const releaseLockOnEnd = args.length === 1 ? args[0].releaseLockOnEnd === true : false\n  return unwrapScoped(Effect.map(\n    Effect.acquireRelease(\n      Effect.sync(() => evaluate().getReader({ mode: \"byob\" })),\n      (reader) => releaseLockOnEnd ? Effect.sync(() => reader.releaseLock()) : Effect.promise(() => reader.cancel())\n    ),\n    (reader) =>\n      catchAll(\n        forever(readChunkStreamByobReader(reader, onError, allocSize)),\n        (error) => error === EOF ? empty : fail(error)\n      )\n  ))\n}\n\nconst EOF = Symbol.for(\"effect/Stream/EOF\")\n\nconst readChunkStreamByobReader = <E>(\n  reader: ReadableStreamBYOBReader,\n  onError: (error: unknown) => E,\n  size: number\n): Stream.Stream<Uint8Array, E | typeof EOF> => {\n  const buffer = new ArrayBuffer(size)\n  return paginateEffect(0, (offset) =>\n    Effect.flatMap(\n      Effect.tryPromise({\n        try: () => reader.read(new Uint8Array(buffer, offset, buffer.byteLength - offset)),\n        catch: (reason) => onError(reason)\n      }),\n      ({ done, value }) => {\n        if (done) {\n          return Effect.fail(EOF)\n        }\n        const newOffset = offset + value.byteLength\n        return Effect.succeed([\n          value,\n          newOffset >= buffer.byteLength\n            ? Option.none<number>()\n            : Option.some(newOffset)\n        ])\n      }\n    ))\n}\n\n/** @internal */\nexport const groupAdjacentBy = dual<\n  <A, K>(\n    f: (a: A) => K\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<[K, Chunk.NonEmptyChunk<A>], E, R>,\n  <A, E, R, K>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => K\n  ) => Stream.Stream<[K, Chunk.NonEmptyChunk<A>], E, R>\n>(\n  2,\n  <A, E, R, K>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => K\n  ): Stream.Stream<[K, Chunk.NonEmptyChunk<A>], E, R> => {\n    type Output = [K, Chunk.NonEmptyChunk<A>]\n    const groupAdjacentByChunk = (\n      state: Option.Option<Output>,\n      chunk: Chunk.Chunk<A>\n    ): [Option.Option<Output>, Chunk.Chunk<Output>] => {\n      if (Chunk.isEmpty(chunk)) {\n        return [state, Chunk.empty()]\n      }\n      const builder: Array<Output> = []\n      let from = 0\n      let until = 0\n      let key: K | undefined = undefined\n      let previousChunk = Chunk.empty<A>()\n      switch (state._tag) {\n        case \"Some\": {\n          const tuple = state.value\n          key = tuple[0]\n          let loop = true\n          while (loop && until < chunk.length) {\n            const input = Chunk.unsafeGet(chunk, until)\n            const updatedKey = f(input)\n            if (!Equal.equals(key, updatedKey)) {\n              const previousChunk = tuple[1]\n              const additionalChunk = Chunk.unsafeFromArray(Array.from(chunk).slice(from, until))\n              const group = Chunk.appendAll(previousChunk, additionalChunk)\n              builder.push([key, group])\n              key = updatedKey\n              from = until\n              loop = false\n            }\n            until = until + 1\n          }\n          if (loop) {\n            previousChunk = tuple[1]\n          }\n          break\n        }\n        case \"None\": {\n          key = f(Chunk.unsafeGet(chunk, until))\n          until = until + 1\n          break\n        }\n      }\n      while (until < chunk.length) {\n        const input = Chunk.unsafeGet(chunk, until)\n        const updatedKey = f(input)\n        if (!Equal.equals(key, updatedKey)) {\n          builder.push([key, Chunk.unsafeFromArray(Array.from(chunk).slice(from, until)) as Chunk.NonEmptyChunk<A>])\n          key = updatedKey\n          from = until\n        }\n        until = until + 1\n      }\n      const nonEmptyChunk = Chunk.appendAll(previousChunk, Chunk.unsafeFromArray(Array.from(chunk).slice(from, until)))\n      const output = Chunk.unsafeFromArray(builder)\n      return [Option.some([key, nonEmptyChunk as Chunk.NonEmptyChunk<A>]), output]\n    }\n\n    const groupAdjacent = (\n      state: Option.Option<Output>\n    ): Channel.Channel<Chunk.Chunk<Output>, Chunk.Chunk<A>, never, never, unknown, unknown> =>\n      core.readWithCause({\n        onInput: (input: Chunk.Chunk<A>) => {\n          const [updatedState, output] = groupAdjacentByChunk(state, input)\n          return Chunk.isEmpty(output)\n            ? groupAdjacent(updatedState)\n            : core.flatMap(core.write(output), () => groupAdjacent(updatedState))\n        },\n        onFailure: (cause) =>\n          Option.match(state, {\n            onNone: () => core.failCause(cause),\n            onSome: (output) => core.flatMap(core.write(Chunk.of(output)), () => core.failCause(cause))\n          }),\n        onDone: (done) =>\n          Option.match(state, {\n            onNone: () => core.succeedNow(done),\n            onSome: (output) => core.flatMap(core.write(Chunk.of(output)), () => core.succeedNow(done))\n          })\n      })\n    return new StreamImpl(channel.pipeToOrFail(toChannel(self), groupAdjacent(Option.none())))\n  }\n)\n\n/** @internal */\nexport const grouped = dual<\n  (chunkSize: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Chunk.Chunk<A>, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, chunkSize: number) => Stream.Stream<Chunk.Chunk<A>, E, R>\n>(\n  2,\n  <A, E, R>(self: Stream.Stream<A, E, R>, chunkSize: number): Stream.Stream<Chunk.Chunk<A>, E, R> =>\n    pipe(self, rechunk(chunkSize), chunks)\n)\n\n/** @internal */\nexport const groupedWithin = dual<\n  (\n    chunkSize: number,\n    duration: Duration.DurationInput\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Chunk.Chunk<A>, E, R>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    chunkSize: number,\n    duration: Duration.DurationInput\n  ) => Stream.Stream<Chunk.Chunk<A>, E, R>\n>(\n  3,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    chunkSize: number,\n    duration: Duration.DurationInput\n  ): Stream.Stream<Chunk.Chunk<A>, E, R> =>\n    aggregateWithin(self, sink_.collectAllN(chunkSize), Schedule.spaced(duration))\n)\n\n/** @internal */\nexport const haltWhen = dual<\n  <X, E2, R2>(\n    effect: Effect.Effect<X, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    effect: Effect.Effect<X, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    effect: Effect.Effect<X, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> => {\n    const writer = (\n      fiber: Fiber.Fiber<X, E2>\n    ): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E | E2, void, unknown, R2> =>\n      pipe(\n        Fiber.poll(fiber),\n        Effect.map(Option.match({\n          onNone: () =>\n            core.readWith({\n              onInput: (input: Chunk.Chunk<A>) => core.flatMap(core.write(input), () => writer(fiber)),\n              onFailure: core.fail,\n              onDone: () => core.void\n            }),\n          onSome: Exit.match({\n            onFailure: core.failCause,\n            onSuccess: () => core.void\n          })\n        })),\n        channel.unwrap\n      )\n    return new StreamImpl(\n      channel.unwrapScopedWith((scope) =>\n        effect.pipe(\n          Effect.forkIn(scope),\n          Effect.map((fiber) => toChannel(self).pipe(core.pipeTo(writer(fiber))))\n        )\n      )\n    )\n  }\n)\n\n/** @internal */\nexport const haltAfter = dual<\n  (duration: Duration.DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, duration: Duration.DurationInput) => Stream.Stream<A, E, R>\n>(\n  2,\n  <A, E, R>(self: Stream.Stream<A, E, R>, duration: Duration.DurationInput): Stream.Stream<A, E, R> =>\n    pipe(self, haltWhen(Clock.sleep(duration)))\n)\n\n/** @internal */\nexport const haltWhenDeferred = dual<\n  <X, E2>(deferred: Deferred.Deferred<X, E2>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R>,\n  <A, E, R, X, E2>(self: Stream.Stream<A, E, R>, deferred: Deferred.Deferred<X, E2>) => Stream.Stream<A, E2 | E, R>\n>(\n  2,\n  <A, E, R, X, E2>(self: Stream.Stream<A, E, R>, deferred: Deferred.Deferred<X, E2>): Stream.Stream<A, E | E2, R> => {\n    const writer: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E | E2, void, unknown, R> = pipe(\n      Deferred.poll(deferred),\n      Effect.map(Option.match({\n        onNone: () =>\n          core.readWith({\n            onInput: (input: Chunk.Chunk<A>) => pipe(core.write(input), core.flatMap(() => writer)),\n            onFailure: core.fail,\n            onDone: () => core.void\n          }),\n        onSome: (effect) =>\n          channel.unwrap(Effect.match(effect, {\n            onFailure: core.fail,\n            onSuccess: () => core.void\n          }))\n      })),\n      channel.unwrap\n    )\n    return new StreamImpl(pipe(toChannel(self), core.pipeTo(writer)))\n  }\n)\n\n/** @internal */\nexport const identityStream = <A, E = never, R = never>(): Stream.Stream<A, E, R> =>\n  new StreamImpl(\n    channel.identityChannel() as Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, unknown, unknown>\n  )\n\n/** @internal */\nexport const interleave = dual<\n  <A2, E2, R2>(\n    that: Stream.Stream<A2, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<A2 | A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ): Stream.Stream<A2 | A, E2 | E, R2 | R> => pipe(self, interleaveWith(that, forever(make(true, false))))\n)\n\n/** @internal */\nexport const interleaveWith = dual<\n  <A2, E2, R2, E3, R3>(\n    that: Stream.Stream<A2, E2, R2>,\n    decider: Stream.Stream<boolean, E3, R3>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E2 | E3 | E, R2 | R3 | R>,\n  <A, E, R, A2, E2, R2, E3, R3>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>,\n    decider: Stream.Stream<boolean, E3, R3>\n  ) => Stream.Stream<A2 | A, E2 | E3 | E, R2 | R3 | R>\n>(\n  3,\n  <A, E, R, A2, E2, R2, E3, R3>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>,\n    decider: Stream.Stream<boolean, E3, R3>\n  ): Stream.Stream<A2 | A, E2 | E3 | E, R2 | R3 | R> => {\n    const producer = (\n      handoff: Handoff.Handoff<Take.Take<A | A2, E | E2 | E3>>\n    ): Channel.Channel<never, A | A2, never, E | E2 | E3, void, unknown, R | R2 | R3> =>\n      core.readWithCause({\n        onInput: (value: A | A2) =>\n          core.flatMap(\n            core.fromEffect(\n              Handoff.offer<Take.Take<A | A2, E | E2 | E3>>(handoff, InternalTake.of(value))\n            ),\n            () => producer(handoff)\n          ),\n        onFailure: (cause) =>\n          core.fromEffect(\n            Handoff.offer<Take.Take<A | A2, E | E2 | E3>>(\n              handoff,\n              InternalTake.failCause(cause)\n            )\n          ),\n        onDone: () =>\n          core.fromEffect(\n            Handoff.offer<Take.Take<A | A2, E | E2 | E3>>(handoff, InternalTake.end)\n          )\n      })\n    return new StreamImpl(\n      channel.unwrapScopedWith((scope) =>\n        pipe(\n          Handoff.make<Take.Take<A | A2, E | E2 | E3>>(),\n          Effect.zip(Handoff.make<Take.Take<A | A2, E | E2 | E3>>()),\n          Effect.tap(([left]) =>\n            toChannel(self).pipe(\n              channel.concatMap(channel.writeChunk),\n              core.pipeTo(producer(left)),\n              channelExecutor.runIn(scope),\n              Effect.forkIn(scope)\n            )\n          ),\n          Effect.tap(([_, right]) =>\n            toChannel(that).pipe(\n              channel.concatMap(channel.writeChunk),\n              core.pipeTo(producer(right)),\n              channelExecutor.runIn(scope),\n              Effect.forkIn(scope)\n            )\n          ),\n          Effect.map(([left, right]) => {\n            const process = (\n              leftDone: boolean,\n              rightDone: boolean\n            ): Channel.Channel<Chunk.Chunk<A | A2>, boolean, E | E2 | E3, E | E2 | E3, void, unknown, R> =>\n              core.readWithCause({\n                onInput: (bool: boolean) => {\n                  if (bool && !leftDone) {\n                    return pipe(\n                      core.fromEffect(Handoff.take(left)),\n                      core.flatMap(InternalTake.match({\n                        onEnd: () => rightDone ? core.void : process(true, rightDone),\n                        onFailure: core.failCause,\n                        onSuccess: (chunk) => pipe(core.write(chunk), core.flatMap(() => process(leftDone, rightDone)))\n                      }))\n                    )\n                  }\n                  if (!bool && !rightDone) {\n                    return pipe(\n                      core.fromEffect(Handoff.take(right)),\n                      core.flatMap(InternalTake.match({\n                        onEnd: () => leftDone ? core.void : process(leftDone, true),\n                        onFailure: core.failCause,\n                        onSuccess: (chunk) => pipe(core.write(chunk), core.flatMap(() => process(leftDone, rightDone)))\n                      }))\n                    )\n                  }\n                  return process(leftDone, rightDone)\n                },\n                onFailure: core.failCause,\n                onDone: () => core.void\n              })\n            return pipe(\n              toChannel(decider),\n              channel.concatMap(channel.writeChunk),\n              core.pipeTo(process(false, false))\n            )\n          })\n        )\n      )\n    )\n  }\n)\n\n/** @internal */\nexport const intersperse = dual<\n  <A2>(element: A2) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E, R>,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, element: A2) => Stream.Stream<A2 | A, E, R>\n>(2, <A, E, R, A2>(self: Stream.Stream<A, E, R>, element: A2): Stream.Stream<A2 | A, E, R> =>\n  new StreamImpl(\n    pipe(\n      toChannel(self),\n      channel.pipeToOrFail(\n        core.suspend(() => {\n          const writer = (\n            isFirst: boolean\n          ): Channel.Channel<Chunk.Chunk<A | A2>, Chunk.Chunk<A>, E, E, unknown, unknown> =>\n            core.readWithCause({\n              onInput: (chunk: Chunk.Chunk<A>) => {\n                const builder: Array<A | A2> = []\n                let flagResult = isFirst\n                for (const output of chunk) {\n                  if (flagResult) {\n                    flagResult = false\n                    builder.push(output)\n                  } else {\n                    builder.push(element)\n                    builder.push(output)\n                  }\n                }\n                return pipe(\n                  core.write(Chunk.unsafeFromArray(builder)),\n                  core.flatMap(() => writer(flagResult))\n                )\n              },\n              onFailure: core.failCause,\n              onDone: () => core.void\n            })\n          return writer(true)\n        })\n      )\n    )\n  ))\n\n/** @internal */\nexport const intersperseAffixes = dual<\n  <A2, A3, A4>(\n    options: {\n      readonly start: A2\n      readonly middle: A3\n      readonly end: A4\n    }\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A3 | A4 | A, E, R>,\n  <A, E, R, A2, A3, A4>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly start: A2\n      readonly middle: A3\n      readonly end: A4\n    }\n  ) => Stream.Stream<A2 | A3 | A4 | A, E, R>\n>(\n  2,\n  <A, E, R, A2, A3, A4>(\n    self: Stream.Stream<A, E, R>,\n    { end, middle, start }: {\n      readonly start: A2\n      readonly middle: A3\n      readonly end: A4\n    }\n  ): Stream.Stream<A2 | A3 | A4 | A, E, R> =>\n    pipe(\n      make(start),\n      concat(pipe(self, intersperse(middle))),\n      concat(make(end))\n    )\n)\n\n/** @internal */\nexport const interruptAfter = dual<\n  (duration: Duration.DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, duration: Duration.DurationInput) => Stream.Stream<A, E, R>\n>(\n  2,\n  <A, E, R>(self: Stream.Stream<A, E, R>, duration: Duration.DurationInput): Stream.Stream<A, E, R> =>\n    pipe(self, interruptWhen(Clock.sleep(duration)))\n)\n\n/** @internal */\nexport const interruptWhen = dual<\n  <X, E2, R2>(\n    effect: Effect.Effect<X, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    effect: Effect.Effect<X, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    effect: Effect.Effect<X, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> => new StreamImpl(pipe(toChannel(self), channel.interruptWhen(effect)))\n)\n\n/** @internal */\nexport const interruptWhenDeferred = dual<\n  <X, E2>(deferred: Deferred.Deferred<X, E2>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R>,\n  <A, E, R, X, E2>(self: Stream.Stream<A, E, R>, deferred: Deferred.Deferred<X, E2>) => Stream.Stream<A, E2 | E, R>\n>(\n  2,\n  <A, E, R, X, E2>(self: Stream.Stream<A, E, R>, deferred: Deferred.Deferred<X, E2>): Stream.Stream<A, E2 | E, R> =>\n    new StreamImpl(pipe(toChannel(self), channel.interruptWhenDeferred(deferred)))\n)\n\n/** @internal */\nexport const iterate = <A>(value: A, next: (value: A) => A): Stream.Stream<A> =>\n  unfold(value, (a) => Option.some([a, next(a)] as const))\n\n/** @internal */\nexport const make = <As extends Array<any>>(...as: As): Stream.Stream<As[number]> => fromIterable(as)\n\n/** @internal */\nexport const map = dual<\n  <A, B>(f: (a: A) => B) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E, R>,\n  <A, E, R, B>(self: Stream.Stream<A, E, R>, f: (a: A) => B) => Stream.Stream<B, E, R>\n>(\n  2,\n  <A, E, R, B>(self: Stream.Stream<A, E, R>, f: (a: A) => B): Stream.Stream<B, E, R> =>\n    new StreamImpl(pipe(toChannel(self), channel.mapOut(Chunk.map(f))))\n)\n\n/** @internal */\nexport const mapAccum = dual<\n  <S, A, A2>(\n    s: S,\n    f: (s: S, a: A) => readonly [S, A2]\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E, R>,\n  <A, E, R, S, A2>(self: Stream.Stream<A, E, R>, s: S, f: (s: S, a: A) => readonly [S, A2]) => Stream.Stream<A2, E, R>\n>(\n  3,\n  <A, E, R, S, A2>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => readonly [S, A2]\n  ): Stream.Stream<A2, E, R> => {\n    const accumulator = (s: S): Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E, E, void, unknown> =>\n      core.readWith({\n        onInput: (input: Chunk.Chunk<A>) => {\n          const [nextS, chunk] = Chunk.mapAccum(input, s, f)\n          return core.flatMap(\n            core.write(chunk),\n            () => accumulator(nextS)\n          )\n        },\n        onFailure: core.fail,\n        onDone: () => core.void\n      })\n    return new StreamImpl(pipe(toChannel(self), core.pipeTo(accumulator(s))))\n  }\n)\n\n/** @internal */\nexport const mapAccumEffect = dual<\n  <S, A, A2, E2, R2>(\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<readonly [S, A2], E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, S, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<readonly [S, A2], E2, R2>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  3,\n  <A, E, R, S, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<readonly [S, A2], E2, R2>\n  ): Stream.Stream<A2, E | E2, R | R2> =>\n    suspend(() => {\n      const accumulator = (\n        s: S\n      ): Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R | R2> =>\n        core.readWith({\n          onInput: (input: Chunk.Chunk<A>) =>\n            pipe(\n              Effect.suspend(() => {\n                const outputs: Array<A2> = []\n                const emit = (output: A2) =>\n                  Effect.sync(() => {\n                    outputs.push(output)\n                  })\n                return pipe(\n                  input,\n                  Effect.reduce(s, (s, a) =>\n                    pipe(\n                      f(s, a),\n                      Effect.flatMap(([s, a]) => pipe(emit(a), Effect.as(s)))\n                    )),\n                  Effect.match({\n                    onFailure: (error) => {\n                      if (outputs.length !== 0) {\n                        return channel.zipRight(core.write(Chunk.unsafeFromArray(outputs)), core.fail(error))\n                      }\n                      return core.fail(error)\n                    },\n                    onSuccess: (s) => core.flatMap(core.write(Chunk.unsafeFromArray(outputs)), () => accumulator(s))\n                  })\n                )\n              }),\n              channel.unwrap\n            ),\n          onFailure: core.fail,\n          onDone: () => core.void\n        })\n      return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(accumulator(s))))\n    })\n)\n\n/** @internal */\nexport const mapBoth = dual<\n  <E, E2, A, A2>(\n    options: {\n      readonly onFailure: (e: E) => E2\n      readonly onSuccess: (a: A) => A2\n    }\n  ) => <R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2, R>,\n  <A, E, R, E2, A2>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly onFailure: (e: E) => E2\n      readonly onSuccess: (a: A) => A2\n    }\n  ) => Stream.Stream<A2, E2, R>\n>(\n  2,\n  <A, E, R, E2, A2>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly onFailure: (e: E) => E2\n      readonly onSuccess: (a: A) => A2\n    }\n  ): Stream.Stream<A2, E2, R> => pipe(self, mapError(options.onFailure), map(options.onSuccess))\n)\n\n/** @internal */\nexport const mapChunks = dual<\n  <A, B>(\n    f: (chunk: Chunk.Chunk<A>) => Chunk.Chunk<B>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E, R>,\n  <A, E, R, B>(self: Stream.Stream<A, E, R>, f: (chunk: Chunk.Chunk<A>) => Chunk.Chunk<B>) => Stream.Stream<B, E, R>\n>(\n  2,\n  <A, E, R, B>(self: Stream.Stream<A, E, R>, f: (chunk: Chunk.Chunk<A>) => Chunk.Chunk<B>): Stream.Stream<B, E, R> =>\n    new StreamImpl(pipe(toChannel(self), channel.mapOut(f)))\n)\n\n/** @internal */\nexport const mapChunksEffect = dual<\n  <A, B, E2, R2>(\n    f: (chunk: Chunk.Chunk<A>) => Effect.Effect<Chunk.Chunk<B>, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E2 | E, R2 | R>,\n  <A, E, R, B, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (chunk: Chunk.Chunk<A>) => Effect.Effect<Chunk.Chunk<B>, E2, R2>\n  ) => Stream.Stream<B, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, B, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (chunk: Chunk.Chunk<A>) => Effect.Effect<Chunk.Chunk<B>, E2, R2>\n  ): Stream.Stream<B, E2 | E, R2 | R> => new StreamImpl(pipe(toChannel(self), channel.mapOutEffect(f)))\n)\n\n/** @internal */\nexport const mapConcat = dual<\n  <A, A2>(f: (a: A) => Iterable<A2>) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E, R>,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, f: (a: A) => Iterable<A2>) => Stream.Stream<A2, E, R>\n>(\n  2,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, f: (a: A) => Iterable<A2>): Stream.Stream<A2, E, R> =>\n    pipe(self, mapConcatChunk((a) => Chunk.fromIterable(f(a))))\n)\n\n/** @internal */\nexport const mapConcatChunk = dual<\n  <A, A2>(f: (a: A) => Chunk.Chunk<A2>) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E, R>,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, f: (a: A) => Chunk.Chunk<A2>) => Stream.Stream<A2, E, R>\n>(\n  2,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, f: (a: A) => Chunk.Chunk<A2>): Stream.Stream<A2, E, R> =>\n    pipe(self, mapChunks(Chunk.flatMap(f)))\n)\n\n/** @internal */\nexport const mapConcatChunkEffect = dual<\n  <A, A2, E2, R2>(\n    f: (a: A) => Effect.Effect<Chunk.Chunk<A2>, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<Chunk.Chunk<A2>, E2, R2>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<Chunk.Chunk<A2>, E2, R2>\n  ): Stream.Stream<A2, E | E2, R | R2> => pipe(self, mapEffectSequential(f), mapConcatChunk(identity))\n)\n\n/** @internal */\nexport const mapConcatEffect = dual<\n  <A, A2, E2, R2>(\n    f: (a: A) => Effect.Effect<Iterable<A2>, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<Iterable<A2>, E2, R2>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<Iterable<A2>, E2, R2>\n  ): Stream.Stream<A2, E | E2, R | R2> =>\n    pipe(self, mapEffectSequential((a) => pipe(f(a), Effect.map(Chunk.fromIterable))), mapConcatChunk(identity))\n)\n\n/** @internal */\nexport const mapEffectSequential = dual<\n  <A, A2, E2, R2>(\n    f: (a: A) => Effect.Effect<A2, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<A2, E2, R2>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<A2, E2, R2>\n  ): Stream.Stream<A2, E | E2, R | R2> => {\n    const loop = (\n      iterator: Iterator<A>\n    ): Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R2> => {\n      const next = iterator.next()\n      if (next.done) {\n        return core.readWithCause({\n          onInput: (elem) => loop(elem[Symbol.iterator]()),\n          onFailure: core.failCause,\n          onDone: core.succeed\n        })\n      } else {\n        const value = next.value\n        return channel.unwrap(\n          Effect.map(f(value), (a2) =>\n            core.flatMap(\n              core.write(Chunk.of(a2)),\n              () => loop(iterator)\n            ))\n        )\n      }\n    }\n    return new StreamImpl(pipe(\n      toChannel(self),\n      core.pipeTo(core.suspend(() => loop(Chunk.empty<A>()[Symbol.iterator]())))\n    ))\n  }\n)\n\n/** @internal */\nexport const mapEffectPar = dual<\n  <A, A2, E2, R2>(\n    n: number,\n    f: (a: A) => Effect.Effect<A2, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    n: number,\n    f: (a: A) => Effect.Effect<A2, E2, R2>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  3,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    n: number,\n    f: (a: A) => Effect.Effect<A2, E2, R2>\n  ): Stream.Stream<A2, E | E2, R | R2> =>\n    new StreamImpl(\n      pipe(\n        toChannel(self),\n        channel.concatMap(channel.writeChunk),\n        channel.mapOutEffectPar(f, n),\n        channel.mapOut(Chunk.of)\n      )\n    )\n)\n\n/** @internal */\nexport const mapError = dual<\n  <E, E2>(f: (error: E) => E2) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2, R>,\n  <A, E, R, E2>(self: Stream.Stream<A, E, R>, f: (error: E) => E2) => Stream.Stream<A, E2, R>\n>(\n  2,\n  <A, E, R, E2>(self: Stream.Stream<A, E, R>, f: (error: E) => E2): Stream.Stream<A, E2, R> =>\n    new StreamImpl(pipe(toChannel(self), channel.mapError(f)))\n)\n\n/** @internal */\nexport const mapErrorCause = dual<\n  <E, E2>(\n    f: (cause: Cause.Cause<E>) => Cause.Cause<E2>\n  ) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2, R>,\n  <A, E, R, E2>(self: Stream.Stream<A, E, R>, f: (cause: Cause.Cause<E>) => Cause.Cause<E2>) => Stream.Stream<A, E2, R>\n>(\n  2,\n  <A, E, R, E2>(self: Stream.Stream<A, E, R>, f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): Stream.Stream<A, E2, R> =>\n    new StreamImpl(pipe(toChannel(self), channel.mapErrorCause(f)))\n)\n\n/** @internal */\nexport const merge = dual<\n  <A2, E2, R2>(\n    that: Stream.Stream<A2, E2, R2>,\n    options?: {\n      readonly haltStrategy?: HaltStrategy.HaltStrategyInput | undefined\n    }\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>,\n    options?: {\n      readonly haltStrategy?: HaltStrategy.HaltStrategyInput | undefined\n    }\n  ) => Stream.Stream<A2 | A, E2 | E, R2 | R>\n>(\n  (args) => isStream(args[1]),\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>,\n    options?: {\n      readonly haltStrategy?: HaltStrategy.HaltStrategyInput | undefined\n    }\n  ): Stream.Stream<A2 | A, E2 | E, R2 | R> =>\n    mergeWith(self, that, {\n      onSelf: identity,\n      onOther: identity,\n      haltStrategy: options?.haltStrategy\n    })\n)\n\n/** @internal */\nexport const mergeAll = dual<\n  (options: {\n    readonly concurrency: number | \"unbounded\"\n    readonly bufferSize?: number | undefined\n  }) => <A, E, R>(streams: Iterable<Stream.Stream<A, E, R>>) => Stream.Stream<A, E, R>,\n  <A, E, R>(streams: Iterable<Stream.Stream<A, E, R>>, options: {\n    readonly concurrency: number | \"unbounded\"\n    readonly bufferSize?: number | undefined\n  }) => Stream.Stream<A, E, R>\n>((args) => Symbol.iterator in args[0], (streams, options) => flatten(fromIterable(streams), options))\n\n/** @internal */\nexport const mergeWithTag: {\n  <S extends { [k in string]: Stream.Stream<any, any, any> }>(\n    streams: S,\n    options: {\n      readonly concurrency: number | \"unbounded\"\n      readonly bufferSize?: number | undefined\n    }\n  ): Stream.Stream<\n    { [K in keyof S]: { _tag: K; value: Stream.Stream.Success<S[K]> } }[keyof S],\n    Stream.Stream.Error<S[keyof S]>,\n    Stream.Stream.Context<S[keyof S]>\n  >\n  (options: {\n    readonly concurrency: number | \"unbounded\"\n    readonly bufferSize?: number | undefined\n  }): <S extends { [k in string]: Stream.Stream<any, any, any> }>(streams: S) => Stream.Stream<\n    { [K in keyof S]: { _tag: K; value: Stream.Stream.Success<S[K]> } }[keyof S],\n    Stream.Stream.Error<S[keyof S]>,\n    Stream.Stream.Context<S[keyof S]>\n  >\n} = dual(2, (streams, options) => {\n  const keys = Object.keys(streams)\n  const values = keys.map((key) => streams[key].pipe(map((value) => ({ _tag: key, value })))) as any\n  return mergeAll(values, options)\n})\n\n/** @internal */\nexport const mergeEither = dual<\n  <A2, E2, R2>(\n    that: Stream.Stream<A2, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Either.Either<A2, A>, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<Either.Either<A2, A>, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ): Stream.Stream<Either.Either<A2, A>, E2 | E, R2 | R> =>\n    mergeWith(self, that, { onSelf: Either.left, onOther: Either.right })\n)\n\n/** @internal */\nexport const mergeLeft = dual<\n  <AR, ER, RR>(\n    right: Stream.Stream<AR, ER, RR>\n  ) => <AL, EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<AL, ER | EL, RR | RL>,\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ) => Stream.Stream<AL, ER | EL, RR | RL>\n>(\n  2,\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AL, EL | ER, RL | RR> => pipe(left, merge(drain(right)))\n)\n\n/** @internal */\nexport const mergeRight = dual<\n  <AR, ER, RR>(\n    right: Stream.Stream<AR, ER, RR>\n  ) => <AL, EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<AR, ER | EL, RR | RL>,\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ) => Stream.Stream<AR, ER | EL, RR | RL>\n>(\n  2,\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AR, EL | ER, RL | RR> => pipe(drain(left), merge(right))\n)\n\n/** @internal */\nexport const mergeWith = dual<\n  <A2, E2, R2, A, A3, A4>(\n    other: Stream.Stream<A2, E2, R2>,\n    options: {\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A4\n      readonly haltStrategy?: HaltStrategy.HaltStrategyInput | undefined\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A3 | A4, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2, A3, A4>(\n    self: Stream.Stream<A, E, R>,\n    other: Stream.Stream<A2, E2, R2>,\n    options: {\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A4\n      readonly haltStrategy?: HaltStrategy.HaltStrategyInput | undefined\n    }\n  ) => Stream.Stream<A3 | A4, E2 | E, R2 | R>\n>(\n  3,\n  <A, E, R, A2, E2, R2, A3, A4>(\n    self: Stream.Stream<A, E, R>,\n    other: Stream.Stream<A2, E2, R2>,\n    options: {\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A4\n      readonly haltStrategy?: HaltStrategy.HaltStrategyInput | undefined\n    }\n  ): Stream.Stream<A3 | A4, E2 | E, R2 | R> => {\n    const strategy = options.haltStrategy ? haltStrategy.fromInput(options.haltStrategy) : HaltStrategy.Both\n    const handler =\n      (terminate: boolean) =>\n      (exit: Exit.Exit<unknown, E | E2>): MergeDecision.MergeDecision<R | R2, E | E2, unknown, E | E2, unknown> =>\n        terminate || !Exit.isSuccess(exit) ?\n          // TODO: remove\n          MergeDecision.Done(Effect.suspend(() => exit)) :\n          MergeDecision.Await((exit) => Effect.suspend(() => exit))\n\n    return new StreamImpl<A3 | A4, E | E2, R | R2>(\n      channel.mergeWith(toChannel(map(self, options.onSelf)), {\n        other: toChannel(map(other, options.onOther)),\n        onSelfDone: handler(strategy._tag === \"Either\" || strategy._tag === \"Left\"),\n        onOtherDone: handler(strategy._tag === \"Either\" || strategy._tag === \"Right\")\n      })\n    )\n  }\n)\n\n/** @internal */\nexport const mkString = <E, R>(self: Stream.Stream<string, E, R>): Effect.Effect<string, E, R> =>\n  run(self, sink_.mkString)\n\n/** @internal */\nexport const never: Stream.Stream<never> = fromEffect(Effect.never)\n\n/** @internal */\nexport const onEnd: {\n  <_, E2, R2>(\n    effect: Effect.Effect<_, E2, R2>\n  ): <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>\n  <A, E, R, _, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    effect: Effect.Effect<_, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, _, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    effect: Effect.Effect<_, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> => concat(self, drain(fromEffect(effect)))\n)\n\n/** @internal */\nexport const onError = dual<\n  <E, X, R2>(\n    cleanup: (cause: Cause.Cause<E>) => Effect.Effect<X, never, R2>\n  ) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R2 | R>,\n  <A, E, R, X, R2>(\n    self: Stream.Stream<A, E, R>,\n    cleanup: (cause: Cause.Cause<E>) => Effect.Effect<X, never, R2>\n  ) => Stream.Stream<A, E, R2 | R>\n>(\n  2,\n  <A, E, R, X, R2>(\n    self: Stream.Stream<A, E, R>,\n    cleanup: (cause: Cause.Cause<E>) => Effect.Effect<X, never, R2>\n  ): Stream.Stream<A, E, R | R2> =>\n    pipe(self, catchAllCause((cause) => fromEffect(pipe(cleanup(cause), Effect.zipRight(Effect.failCause(cause))))))\n)\n\n/** @internal */\nexport const onDone = dual<\n  <X, R2>(\n    cleanup: () => Effect.Effect<X, never, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R2 | R>,\n  <A, E, R, X, R2>(\n    self: Stream.Stream<A, E, R>,\n    cleanup: () => Effect.Effect<X, never, R2>\n  ) => Stream.Stream<A, E, R2 | R>\n>(\n  2,\n  <A, E, R, X, R2>(\n    self: Stream.Stream<A, E, R>,\n    cleanup: () => Effect.Effect<X, never, R2>\n  ): Stream.Stream<A, E, R | R2> =>\n    new StreamImpl<A, E, R | R2>(\n      pipe(toChannel(self), core.ensuringWith((exit) => Exit.isSuccess(exit) ? cleanup() : Effect.void))\n    )\n)\n\n/** @internal */\nexport const onStart: {\n  <_, E2, R2>(\n    effect: Effect.Effect<_, E2, R2>\n  ): <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>\n  <A, E, R, _, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    effect: Effect.Effect<_, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, _, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    effect: Effect.Effect<_, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> => unwrap(Effect.as(effect, self))\n)\n\n/** @internal */\nexport const orDie = <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<A, never, R> =>\n  pipe(self, orDieWith(identity))\n\n/** @internal */\nexport const orDieWith = dual<\n  <E>(f: (e: E) => unknown) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, never, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, f: (e: E) => unknown) => Stream.Stream<A, never, R>\n>(\n  2,\n  <A, E, R>(self: Stream.Stream<A, E, R>, f: (e: E) => unknown): Stream.Stream<A, never, R> =>\n    new StreamImpl(pipe(toChannel(self), channel.orDieWith(f)))\n)\n\n/** @internal */\nexport const orElse = dual<\n  <A2, E2, R2>(\n    that: LazyArg<Stream.Stream<A2, E2, R2>>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: LazyArg<Stream.Stream<A2, E2, R2>>\n  ) => Stream.Stream<A2 | A, E2, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: LazyArg<Stream.Stream<A2, E2, R2>>\n  ): Stream.Stream<A2 | A, E2, R2 | R> =>\n    new StreamImpl<A | A2, E2, R | R2>(pipe(toChannel(self), channel.orElse(() => toChannel(that()))))\n)\n\n/** @internal */\nexport const orElseEither = dual<\n  <A2, E2, R2>(\n    that: LazyArg<Stream.Stream<A2, E2, R2>>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Either.Either<A2, A>, E2, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: LazyArg<Stream.Stream<A2, E2, R2>>\n  ) => Stream.Stream<Either.Either<A2, A>, E2, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: LazyArg<Stream.Stream<A2, E2, R2>>\n  ): Stream.Stream<Either.Either<A2, A>, E2, R2 | R> =>\n    pipe(self, map(Either.left), orElse(() => pipe(that(), map(Either.right))))\n)\n\n/** @internal */\nexport const orElseFail = dual<\n  <E2>(error: LazyArg<E2>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2, R>,\n  <A, E, R, E2>(self: Stream.Stream<A, E, R>, error: LazyArg<E2>) => Stream.Stream<A, E2, R>\n>(\n  2,\n  <A, E, R, E2>(self: Stream.Stream<A, E, R>, error: LazyArg<E2>): Stream.Stream<A, E2, R> =>\n    pipe(self, orElse(() => failSync(error)))\n)\n\n/** @internal */\nexport const orElseIfEmpty = dual<\n  <A2>(element: LazyArg<A2>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E, R>,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, element: LazyArg<A2>) => Stream.Stream<A2 | A, E, R>\n>(\n  2,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, element: LazyArg<A2>): Stream.Stream<A | A2, E, R> =>\n    pipe(self, orElseIfEmptyChunk(() => Chunk.of(element())))\n)\n\n/** @internal */\nexport const orElseIfEmptyChunk = dual<\n  <A2>(chunk: LazyArg<Chunk.Chunk<A2>>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E, R>,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, chunk: LazyArg<Chunk.Chunk<A2>>) => Stream.Stream<A2 | A, E, R>\n>(\n  2,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, chunk: LazyArg<Chunk.Chunk<A2>>): Stream.Stream<A | A2, E, R> =>\n    pipe(self, orElseIfEmptyStream(() => new StreamImpl(core.write(chunk()))))\n)\n\n/** @internal */\nexport const orElseIfEmptyStream = dual<\n  <A2, E2, R2>(\n    stream: LazyArg<Stream.Stream<A2, E2, R2>>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    stream: LazyArg<Stream.Stream<A2, E2, R2>>\n  ) => Stream.Stream<A2 | A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    stream: LazyArg<Stream.Stream<A2, E2, R2>>\n  ): Stream.Stream<A2 | A, E2 | E, R2 | R> => {\n    const writer: Channel.Channel<Chunk.Chunk<A | A2>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R2> = core.readWith(\n      {\n        onInput: (input: Chunk.Chunk<A>) => {\n          if (Chunk.isEmpty(input)) {\n            return core.suspend(() => writer)\n          }\n          return pipe(\n            core.write(input),\n            channel.zipRight(channel.identityChannel<Chunk.Chunk<A>, E, unknown>())\n          )\n        },\n        onFailure: core.fail,\n        onDone: () => core.suspend(() => toChannel(stream()))\n      }\n    )\n    return new StreamImpl(pipe(toChannel(self), core.pipeTo(writer)))\n  }\n)\n\n/** @internal */\nexport const orElseSucceed = dual<\n  <A2>(value: LazyArg<A2>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, never, R>,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, value: LazyArg<A2>) => Stream.Stream<A2 | A, never, R>\n>(\n  2,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, value: LazyArg<A2>): Stream.Stream<A2 | A, never, R> =>\n    pipe(self, orElse(() => sync(value)))\n)\n\n/** @internal */\nexport const paginate = <S, A>(s: S, f: (s: S) => readonly [A, Option.Option<S>]): Stream.Stream<A> =>\n  paginateChunk(s, (s) => {\n    const page = f(s)\n    return [Chunk.of(page[0]), page[1]] as const\n  })\n\n/** @internal */\nexport const paginateChunk = <S, A>(\n  s: S,\n  f: (s: S) => readonly [Chunk.Chunk<A>, Option.Option<S>]\n): Stream.Stream<A> => {\n  const loop = (s: S): Channel.Channel<Chunk.Chunk<A>, unknown, never, unknown, unknown, unknown> => {\n    const page = f(s)\n    return Option.match(page[1], {\n      onNone: () => channel.zipRight(core.write(page[0]), core.void),\n      onSome: (s) => core.flatMap(core.write(page[0]), () => loop(s))\n    })\n  }\n  return new StreamImpl(core.suspend(() => loop(s)))\n}\n\n/** @internal */\nexport const paginateChunkEffect = <S, A, E, R>(\n  s: S,\n  f: (s: S) => Effect.Effect<readonly [Chunk.Chunk<A>, Option.Option<S>], E, R>\n): Stream.Stream<A, E, R> => {\n  const loop = (s: S): Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, unknown, unknown, R> =>\n    channel.unwrap(\n      Effect.map(f(s), ([chunk, option]) =>\n        Option.match(option, {\n          onNone: () => channel.zipRight(core.write(chunk), core.void),\n          onSome: (s) => core.flatMap(core.write(chunk), () => loop(s))\n        }))\n    )\n  return new StreamImpl(core.suspend(() => loop(s)))\n}\n\n/** @internal */\nexport const paginateEffect = <S, A, E, R>(\n  s: S,\n  f: (s: S) => Effect.Effect<readonly [A, Option.Option<S>], E, R>\n): Stream.Stream<A, E, R> =>\n  paginateChunkEffect(s, (s) => pipe(f(s), Effect.map(([a, s]) => [Chunk.of(a), s] as const)))\n\n/** @internal */\nexport const peel = dual<\n  <A2, A, E2, R2>(\n    sink: Sink.Sink<A2, A, A, E2, R2>\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<[A2, Stream.Stream<A, E>], E2 | E, Scope.Scope | R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<A2, A, A, E2, R2>\n  ) => Effect.Effect<[A2, Stream.Stream<A, E>], E2 | E, Scope.Scope | R2 | R>\n>(2, <A, E, R, A2, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  sink: Sink.Sink<A2, A, A, E2, R2>\n): Effect.Effect<[A2, Stream.Stream<A, E>], E2 | E, Scope.Scope | R2 | R> => {\n  type Signal = Emit | Halt | End\n  const OP_EMIT = \"Emit\" as const\n  type OP_EMIT = typeof OP_EMIT\n  const OP_HALT = \"Halt\" as const\n  type OP_HALT = typeof OP_HALT\n  const OP_END = \"End\" as const\n  type OP_END = typeof OP_END\n  interface Emit {\n    readonly _tag: OP_EMIT\n    readonly elements: Chunk.Chunk<A>\n  }\n  interface Halt {\n    readonly _tag: OP_HALT\n    readonly cause: Cause.Cause<E>\n  }\n  interface End {\n    readonly _tag: OP_END\n  }\n  return pipe(\n    Deferred.make<A2, E | E2>(),\n    Effect.flatMap((deferred) =>\n      pipe(\n        Handoff.make<Signal>(),\n        Effect.map((handoff) => {\n          const consumer = sink_.foldSink(sink_.collectLeftover(sink), {\n            onFailure: (error) =>\n              sink_.zipRight(\n                sink_.fromEffect(Deferred.fail(deferred, error)),\n                sink_.fail(error)\n              ),\n            onSuccess: ([z, leftovers]) => {\n              const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, void, unknown> = core\n                .readWithCause({\n                  onInput: (elements) =>\n                    core.flatMap(\n                      core.fromEffect(\n                        Handoff.offer<Signal>(handoff, { _tag: OP_EMIT, elements })\n                      ),\n                      () => loop\n                    ),\n                  onFailure: (cause) =>\n                    channel.zipRight(\n                      core.fromEffect(Handoff.offer<Signal>(handoff, { _tag: OP_HALT, cause })),\n                      core.failCause(cause)\n                    ),\n                  onDone: (_) =>\n                    channel.zipRight(\n                      core.fromEffect(Handoff.offer<Signal>(handoff, { _tag: OP_END })),\n                      core.void\n                    )\n                })\n              return sink_.fromChannel(\n                pipe(\n                  core.fromEffect(Deferred.succeed(deferred, z)),\n                  channel.zipRight(core.fromEffect(\n                    pipe(\n                      handoff,\n                      Handoff.offer<Signal>({ _tag: OP_EMIT, elements: leftovers })\n                    )\n                  )),\n                  channel.zipRight(loop)\n                )\n              )\n            }\n          })\n\n          const producer: Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, void, unknown> = pipe(\n            Handoff.take(handoff),\n            Effect.map((signal) => {\n              switch (signal._tag) {\n                case OP_EMIT: {\n                  return pipe(core.write(signal.elements), core.flatMap(() => producer))\n                }\n                case OP_HALT: {\n                  return core.failCause(signal.cause)\n                }\n                case OP_END: {\n                  return core.void\n                }\n              }\n            }),\n            channel.unwrap\n          )\n\n          return pipe(\n            self,\n            tapErrorCause((cause) => Deferred.failCause(deferred, cause)),\n            run(consumer),\n            Effect.forkScoped,\n            Effect.zipRight(Deferred.await(deferred)),\n            Effect.map((z) => [z, new StreamImpl(producer)] as [A2, StreamImpl<A, E>])\n          )\n        })\n      )\n    ),\n    Effect.flatten\n  )\n})\n\n/** @internal */\nexport const partition: {\n  <C extends A, B extends A, A = C>(\n    refinement: Refinement<Types.NoInfer<A>, B>,\n    options?: {\n      bufferSize?: number | undefined\n    }\n  ): <E, R>(\n    self: Stream.Stream<C, E, R>\n  ) => Effect.Effect<\n    [excluded: Stream.Stream<Exclude<C, B>, E>, satisfying: Stream.Stream<B, E>],\n    E,\n    Scope.Scope | R\n  >\n  <A>(\n    predicate: Predicate<A>,\n    options?: {\n      bufferSize?: number | undefined\n    }\n  ): <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<[excluded: Stream.Stream<A, E>, satisfying: Stream.Stream<A, E>], E, Scope.Scope | R>\n  <C extends A, E, R, B extends A, A = C>(\n    self: Stream.Stream<C, E, R>,\n    refinement: Refinement<A, B>,\n    options?: {\n      bufferSize?: number | undefined\n    }\n  ): Effect.Effect<\n    [excluded: Stream.Stream<Exclude<C, B>, E>, satisfying: Stream.Stream<B, E>],\n    E,\n    Scope.Scope | R\n  >\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    predicate: Predicate<A>,\n    options?: {\n      bufferSize?: number | undefined\n    }\n  ): Effect.Effect<[excluded: Stream.Stream<A, E>, satisfying: Stream.Stream<A, E>], E, Scope.Scope | R>\n} = dual(\n  (args) => typeof args[1] === \"function\",\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    predicate: Predicate<A>,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ): Effect.Effect<\n    [Stream.Stream<A, E>, Stream.Stream<A, E>],\n    E,\n    R | Scope.Scope\n  > =>\n    partitionEither(\n      self,\n      (a) => Effect.succeed(predicate(a) ? Either.right(a) : Either.left(a)),\n      options\n    )\n)\n\n/** @internal */\nexport const partitionEither = dual<\n  <A, A3, A2, E2, R2>(\n    predicate: (a: Types.NoInfer<A>) => Effect.Effect<Either.Either<A3, A2>, E2, R2>,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<\n    [left: Stream.Stream<A2, E2 | E>, right: Stream.Stream<A3, E2 | E>],\n    E2 | E,\n    Scope.Scope | R2 | R\n  >,\n  <A, E, R, A3, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    predicate: (a: A) => Effect.Effect<Either.Either<A3, A2>, E2, R2>,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ) => Effect.Effect<\n    [left: Stream.Stream<A2, E2 | E>, right: Stream.Stream<A3, E2 | E>],\n    E2 | E,\n    Scope.Scope | R2 | R\n  >\n>(\n  (args) => typeof args[1] === \"function\",\n  <A, E, R, A3, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    predicate: (a: A) => Effect.Effect<Either.Either<A3, A2>, E2, R2>,\n    options?: {\n      readonly bufferSize?: number | undefined\n    }\n  ): Effect.Effect<\n    [left: Stream.Stream<A2, E2 | E>, right: Stream.Stream<A3, E2 | E>],\n    E | E2,\n    R | R2 | Scope.Scope\n  > =>\n    pipe(\n      mapEffectSequential(self, predicate),\n      distributedWith({\n        size: 2,\n        maximumLag: options?.bufferSize ?? 16,\n        decide: Either.match({\n          onLeft: () => Effect.succeed((n) => n === 0),\n          onRight: () => Effect.succeed((n) => n === 1)\n        })\n      }),\n      Effect.flatMap(([queue1, queue2]) =>\n        Effect.succeed([\n          filterMap(\n            flattenExitOption(fromQueue(queue1, { shutdown: true })),\n            (_) =>\n              Either.match(_, {\n                onLeft: Option.some,\n                onRight: Option.none\n              })\n          ),\n          filterMap(\n            flattenExitOption(fromQueue(queue2, { shutdown: true })),\n            (_) =>\n              Either.match(_, {\n                onLeft: Option.none,\n                onRight: Option.some\n              })\n          )\n        ])\n      )\n    )\n)\n\n/** @internal */\nexport const pipeThrough = dual<\n  <A2, A, L, E2, R2>(\n    sink: Sink.Sink<A2, A, L, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<L, E2 | E, R2 | R>,\n  <A, E, R, A2, L, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<A2, A, L, E2, R2>\n  ) => Stream.Stream<L, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, L, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<A2, A, L, E2, R2>\n  ): Stream.Stream<L, E2 | E, R2 | R> =>\n    new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(sink_.toChannel(sink))))\n)\n\n/** @internal */\nexport const pipeThroughChannel = dual<\n  <R2, E, E2, A, A2>(\n    channel: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, E, unknown, unknown, R2>\n  ) => <R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2, R2 | R>,\n  <R, R2, E, E2, A, A2>(\n    self: Stream.Stream<A, E, R>,\n    channel: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, E, unknown, unknown, R2>\n  ) => Stream.Stream<A2, E2, R2 | R>\n>(\n  2,\n  <R, R2, E, E2, A, A2>(\n    self: Stream.Stream<A, E, R>,\n    channel: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, E, unknown, unknown, R2>\n  ): Stream.Stream<A2, E2, R2 | R> => new StreamImpl(core.pipeTo(toChannel(self), channel))\n)\n\n/** @internal */\nexport const pipeThroughChannelOrFail = dual<\n  <R2, E, E2, A, A2>(\n    chan: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, E, unknown, unknown, R2>\n  ) => <R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E | E2, R2 | R>,\n  <R, R2, E, E2, A, A2>(\n    self: Stream.Stream<A, E, R>,\n    chan: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, E, unknown, unknown, R2>\n  ) => Stream.Stream<A2, E | E2, R2 | R>\n>(\n  2,\n  <R, R2, E, E2, A, A2>(\n    self: Stream.Stream<A, E, R>,\n    chan: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E2, E, unknown, unknown, R2>\n  ): Stream.Stream<A2, E | E2, R2 | R> => new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(chan)))\n)\n\n/** @internal */\nexport const prepend = dual<\n  <B>(values: Chunk.Chunk<B>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A | B, E, R>,\n  <A, E, R, B>(self: Stream.Stream<A, E, R>, values: Chunk.Chunk<B>) => Stream.Stream<A | B, E, R>\n>(2, (self, values) =>\n  new StreamImpl(\n    channel.zipRight(\n      core.write(values as Chunk.Chunk<any>),\n      toChannel(self)\n    )\n  ))\n\n/** @internal */\nexport const provideContext = dual<\n  <R>(context: Context.Context<R>) => <A, E>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, context: Context.Context<R>) => Stream.Stream<A, E>\n>(\n  2,\n  <A, E, R>(self: Stream.Stream<A, E, R>, context: Context.Context<R>): Stream.Stream<A, E> =>\n    new StreamImpl(pipe(toChannel(self), core.provideContext(context)))\n)\n\n/** @internal */\nexport const provideSomeContext = dual<\n  <R2>(context: Context.Context<R2>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, Exclude<R, R2>>,\n  <A, E, R, R2>(self: Stream.Stream<A, E, R>, context: Context.Context<R2>) => Stream.Stream<A, E, Exclude<R, R2>>\n>(\n  2,\n  <A, E, R, R2>(self: Stream.Stream<A, E, R>, context: Context.Context<R2>): Stream.Stream<A, E, Exclude<R, R2>> =>\n    mapInputContext(self as any, Context.merge(context))\n)\n\n/** @internal */\nexport const provideLayer = dual<\n  <RIn, E2, ROut>(\n    layer: Layer.Layer<ROut, E2, RIn>\n  ) => <A, E>(self: Stream.Stream<A, E, ROut>) => Stream.Stream<A, E2 | E, RIn>,\n  <A, E, RIn, E2, ROut>(\n    self: Stream.Stream<A, E, ROut>,\n    layer: Layer.Layer<ROut, E2, RIn>\n  ) => Stream.Stream<A, E2 | E, RIn>\n>(\n  2,\n  <A, E, RIn, E2, ROut>(\n    self: Stream.Stream<A, E, ROut>,\n    layer: Layer.Layer<ROut, E2, RIn>\n  ): Stream.Stream<A, E2 | E, RIn> =>\n    new StreamImpl(\n      channel.unwrapScopedWith((scope) =>\n        Layer.buildWithScope(layer, scope).pipe(\n          Effect.map((env) => pipe(toChannel(self), core.provideContext(env)))\n        )\n      )\n    )\n)\n\n/** @internal */\nexport const provideService = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    resource: Types.NoInfer<S>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, Exclude<R, I>>,\n  <A, E, R, I, S>(\n    self: Stream.Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    resource: Types.NoInfer<S>\n  ) => Stream.Stream<A, E, Exclude<R, I>>\n>(\n  3,\n  <A, E, R, I, S>(\n    self: Stream.Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    resource: Types.NoInfer<S>\n  ) => provideServiceEffect(self, tag, Effect.succeed(resource))\n)\n\n/** @internal */\nexport const provideServiceEffect = dual<\n  <I, S, E2, R2>(\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<Types.NoInfer<S>, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | Exclude<R, I>>,\n  <A, E, R, I, S, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<Types.NoInfer<S>, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | Exclude<R, I>>\n>(\n  3,\n  <A, E, R, I, S, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    effect: Effect.Effect<Types.NoInfer<S>, E2, R2>\n  ) => provideServiceStream(self, tag, fromEffect(effect))\n)\n\n/** @internal */\nexport const provideServiceStream = dual<\n  <I, S, E2, R2>(\n    tag: Context.Tag<I, S>,\n    stream: Stream.Stream<Types.NoInfer<S>, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | Exclude<R, I>>,\n  <A, E, R, I, S, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    stream: Stream.Stream<Types.NoInfer<S>, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | Exclude<R, I>>\n>(\n  3,\n  <A, E, R, I, S, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    stream: Stream.Stream<Types.NoInfer<S>, E2, R2>\n  ): Stream.Stream<A, E2 | E, R2 | Exclude<R, I>> =>\n    contextWithStream((env: Context.Context<R2 | Exclude<R, I>>) =>\n      flatMap(\n        stream,\n        (service) => pipe(self, provideContext(Context.add(env, tag, service) as Context.Context<R | R2>))\n      )\n    )\n)\n\n/** @internal */\nexport const mapInputContext = dual<\n  <R0, R>(\n    f: (env: Context.Context<R0>) => Context.Context<R>\n  ) => <A, E>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R0>,\n  <A, E, R0, R>(\n    self: Stream.Stream<A, E, R>,\n    f: (env: Context.Context<R0>) => Context.Context<R>\n  ) => Stream.Stream<A, E, R0>\n>(\n  2,\n  <A, E, R0, R>(\n    self: Stream.Stream<A, E, R>,\n    f: (env: Context.Context<R0>) => Context.Context<R>\n  ): Stream.Stream<A, E, R0> => contextWithStream((env) => pipe(self, provideContext(f(env))))\n)\n\n/** @internal */\nexport const provideSomeLayer = dual<\n  <RIn, E2, ROut>(\n    layer: Layer.Layer<ROut, E2, RIn>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, RIn | Exclude<R, ROut>>,\n  <A, E, R, RIn, E2, ROut>(\n    self: Stream.Stream<A, E, R>,\n    layer: Layer.Layer<ROut, E2, RIn>\n  ) => Stream.Stream<A, E2 | E, RIn | Exclude<R, ROut>>\n>(\n  2,\n  <A, E, R, RIn, E2, ROut>(\n    self: Stream.Stream<A, E, R>,\n    layer: Layer.Layer<ROut, E2, RIn>\n  ): Stream.Stream<A, E2 | E, RIn | Exclude<R, ROut>> =>\n    // @ts-expect-error\n    // @effect-diagnostics-next-line missingEffectContext:off\n    pipe(\n      self,\n      provideLayer(pipe(Layer.context(), Layer.merge(layer)))\n    )\n)\n\n/** @internal */\nexport const range = (min: number, max: number, chunkSize = DefaultChunkSize): Stream.Stream<number> =>\n  suspend(() => {\n    if (min > max) {\n      return empty as Stream.Stream<number>\n    }\n    const go = (\n      min: number,\n      max: number,\n      chunkSize: number\n    ): Channel.Channel<Chunk.Chunk<number>, unknown, never, unknown, unknown, unknown> => {\n      const remaining = max - min + 1\n      if (remaining > chunkSize) {\n        return pipe(\n          core.write(Chunk.range(min, min + chunkSize - 1)),\n          core.flatMap(() => go(min + chunkSize, max, chunkSize))\n        )\n      }\n      return core.write(Chunk.range(min, min + remaining - 1))\n    }\n    return new StreamImpl(go(min, max, chunkSize))\n  })\n\n/** @internal */\nexport const race: {\n  <AR, ER, RR>(\n    right: Stream.Stream<AR, ER, RR>\n  ): <AL, EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<AL | AR, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AL | AR, EL | ER, RL | RR>\n} = dual(\n  2,\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AL | AR, EL | ER, RL | RR> => raceAll(left, right)\n)\n\n/** @internal */\nexport const raceAll = <S extends ReadonlyArray<Stream.Stream<any, any, any>>>(\n  ...streams: S\n): Stream.Stream<\n  Stream.Stream.Success<S[number]>,\n  Stream.Stream.Error<S[number]>,\n  Stream.Stream.Context<S[number]>\n> =>\n  Deferred.make<void>().pipe(\n    Effect.map((halt) => {\n      let winner: number | null = null\n      return mergeAll(\n        streams.map((stream, index) =>\n          stream.pipe(\n            takeWhile(() => {\n              if (winner === null) {\n                winner = index\n                Deferred.unsafeDone(halt, Exit.void)\n                return true\n              }\n              return winner === index\n            }),\n            interruptWhen(\n              Deferred.await(halt).pipe(\n                Effect.flatMap(() => winner === index ? Effect.never : Effect.void)\n              )\n            )\n          )\n        ),\n        { concurrency: streams.length }\n      )\n    }),\n    unwrap\n  )\n\n/** @internal */\nexport const rechunk = dual<\n  (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, n: number) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, n: number): Stream.Stream<A, E, R> =>\n  suspend(() => {\n    const target = Math.max(n, 1)\n    const process = rechunkProcess(new StreamRechunker(target), target)\n    return new StreamImpl(pipe(toChannel(self), core.pipeTo(process)))\n  }))\n\n/** @internal */\nconst rechunkProcess = <A, E>(\n  rechunker: StreamRechunker<A, E>,\n  target: number\n): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E, E, unknown, unknown> =>\n  core.readWithCause({\n    onInput: (chunk: Chunk.Chunk<A>) => {\n      if (chunk.length === target && rechunker.isEmpty()) {\n        return core.flatMap(\n          core.write(chunk),\n          () => rechunkProcess(rechunker, target)\n        )\n      }\n      if (chunk.length > 0) {\n        const chunks: Array<Chunk.Chunk<A>> = []\n        let result: Chunk.Chunk<A> | undefined = undefined\n        let index = 0\n        while (index < chunk.length) {\n          while (index < chunk.length && result === undefined) {\n            result = rechunker.write(pipe(chunk, Chunk.unsafeGet(index)))\n            index = index + 1\n          }\n          if (result !== undefined) {\n            chunks.push(result)\n            result = undefined\n          }\n        }\n        return core.flatMap(\n          channel.writeAll(...chunks),\n          () => rechunkProcess(rechunker, target)\n        )\n      }\n      return core.suspend(() => rechunkProcess(rechunker, target))\n    },\n    onFailure: (cause) => channel.zipRight(rechunker.emitIfNotEmpty(), core.failCause(cause)),\n    onDone: () => rechunker.emitIfNotEmpty()\n  })\n\nclass StreamRechunker<out A, in out E> {\n  private builder: Array<A> = []\n  private pos = 0\n\n  constructor(readonly n: number) {\n  }\n\n  isEmpty(): boolean {\n    return this.pos === 0\n  }\n\n  write(elem: A): Chunk.Chunk<A> | undefined {\n    this.builder.push(elem)\n    this.pos += 1\n\n    if (this.pos === this.n) {\n      const result = Chunk.unsafeFromArray(this.builder)\n      this.builder = []\n      this.pos = 0\n      return result\n    }\n\n    return undefined\n  }\n\n  emitIfNotEmpty(): Channel.Channel<Chunk.Chunk<A>, unknown, E, E, void, unknown> {\n    if (this.pos !== 0) {\n      return core.write(Chunk.unsafeFromArray(this.builder))\n    }\n    return core.void\n  }\n}\n\n/** @internal */\nexport const refineOrDie = dual<\n  <E, E2>(pf: (error: E) => Option.Option<E2>) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2, R>,\n  <A, E, R, E2>(self: Stream.Stream<A, E, R>, pf: (error: E) => Option.Option<E2>) => Stream.Stream<A, E2, R>\n>(\n  2,\n  <A, E, R, E2>(self: Stream.Stream<A, E, R>, pf: (error: E) => Option.Option<E2>): Stream.Stream<A, E2, R> =>\n    pipe(self, refineOrDieWith(pf, identity))\n)\n\n/** @internal */\nexport const refineOrDieWith = dual<\n  <E, E2>(\n    pf: (error: E) => Option.Option<E2>,\n    f: (error: E) => unknown\n  ) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2, R>,\n  <A, E, R, E2>(\n    self: Stream.Stream<A, E, R>,\n    pf: (error: E) => Option.Option<E2>,\n    f: (error: E) => unknown\n  ) => Stream.Stream<A, E2, R>\n>(\n  3,\n  <A, E, R, E2>(\n    self: Stream.Stream<A, E, R>,\n    pf: (error: E) => Option.Option<E2>,\n    f: (error: E) => unknown\n  ): Stream.Stream<A, E2, R> =>\n    new StreamImpl(\n      channel.catchAll(toChannel(self), (error) =>\n        Option.match(pf(error), {\n          onNone: () => core.failCause(Cause.die(f(error))),\n          onSome: core.fail\n        }))\n    )\n)\n\n/** @internal */\nexport const repeat = dual<\n  <B, R2>(\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R2 | R>,\n  <A, E, R, B, R2>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ) => Stream.Stream<A, E, R2 | R>\n>(\n  2,\n  <A, E, R, B, R2>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ): Stream.Stream<A, E, R | R2> =>\n    filterMap(\n      repeatEither(self, schedule),\n      (_) =>\n        Either.match(_, {\n          onLeft: Option.none,\n          onRight: Option.some\n        })\n    )\n)\n\n/** @internal */\nexport const repeatEffect = <A, E, R>(effect: Effect.Effect<A, E, R>): Stream.Stream<A, E, R> =>\n  repeatEffectOption(pipe(effect, Effect.mapError(Option.some)))\n\n/** @internal */\nexport const repeatEffectChunk = <A, E, R>(effect: Effect.Effect<Chunk.Chunk<A>, E, R>): Stream.Stream<A, E, R> =>\n  repeatEffectChunkOption(pipe(effect, Effect.mapError(Option.some)))\n\n/** @internal */\nexport const repeatEffectChunkOption = <A, E, R>(\n  effect: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R>\n): Stream.Stream<A, E, R> =>\n  unfoldChunkEffect(effect, (effect) =>\n    pipe(\n      Effect.map(effect, (chunk) => Option.some([chunk, effect] as const)),\n      Effect.catchAll(Option.match({\n        onNone: () => Effect.succeed(Option.none()),\n        onSome: Effect.fail\n      }))\n    ))\n\n/** @internal */\nexport const repeatEffectOption = <A, E, R>(effect: Effect.Effect<A, Option.Option<E>, R>): Stream.Stream<A, E, R> =>\n  repeatEffectChunkOption(pipe(effect, Effect.map(Chunk.of)))\n\n/** @internal */\nexport const repeatEither = dual<\n  <B, R2>(\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Either.Either<A, B>, E, R2 | R>,\n  <A, E, R, B, R2>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ) => Stream.Stream<Either.Either<A, B>, E, R2 | R>\n>(\n  2,\n  <A, E, R, B, R2>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ): Stream.Stream<Either.Either<A, B>, E, R2 | R> =>\n    repeatWith(self, schedule, {\n      onElement: (a): Either.Either<A, B> => Either.right(a),\n      onSchedule: Either.left\n    })\n)\n\n/** @internal */\nexport const repeatElements = dual<\n  <B, R2>(\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R2 | R>,\n  <A, E, R, B, R2>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ) => Stream.Stream<A, E, R2 | R>\n>(\n  2,\n  <A, E, R, B, R2>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>\n  ): Stream.Stream<A, E, R | R2> =>\n    filterMap(\n      repeatElementsWith(self, schedule, { onElement: (a) => Option.some(a), onSchedule: Option.none }),\n      identity\n    )\n)\n\n/** @internal */\nexport const repeatElementsWith = dual<\n  <B, R2, A, C>(\n    schedule: Schedule.Schedule<B, unknown, R2>,\n    options: {\n      readonly onElement: (a: A) => C\n      readonly onSchedule: (b: B) => C\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<C, E, R2 | R>,\n  <A, E, R, B, R2, C>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>,\n    options: {\n      readonly onElement: (a: A) => C\n      readonly onSchedule: (b: B) => C\n    }\n  ) => Stream.Stream<C, E, R2 | R>\n>(\n  3,\n  <A, E, R, B, R2, C>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>,\n    options: {\n      readonly onElement: (a: A) => C\n      readonly onSchedule: (b: B) => C\n    }\n  ): Stream.Stream<C, E, R | R2> => {\n    const driver = pipe(\n      Schedule.driver(schedule),\n      Effect.map((driver) => {\n        const feed = (\n          input: Chunk.Chunk<A>\n        ): Channel.Channel<Chunk.Chunk<C>, Chunk.Chunk<A>, E, E, void, unknown, R2> =>\n          Option.match(Chunk.head(input), {\n            onNone: () => loop,\n            onSome: (a) =>\n              channel.zipRight(\n                core.write(Chunk.of(options.onElement(a))),\n                step(pipe(input, Chunk.drop(1)), a)\n              )\n          })\n        const step = (\n          input: Chunk.Chunk<A>,\n          a: A\n        ): Channel.Channel<Chunk.Chunk<C>, Chunk.Chunk<A>, E, E, void, unknown, R2> => {\n          const advance = pipe(\n            driver.next(a),\n            Effect.as(pipe(core.write(Chunk.of(options.onElement(a))), core.flatMap(() => step(input, a))))\n          )\n          const reset: Effect.Effect<\n            Channel.Channel<Chunk.Chunk<C>, Chunk.Chunk<A>, E, E, void, unknown, R2>,\n            never,\n            R2\n          > = pipe(\n            driver.last,\n            Effect.orDie,\n            Effect.flatMap((b) =>\n              pipe(\n                driver.reset,\n                Effect.map(() =>\n                  pipe(\n                    core.write(Chunk.of(options.onSchedule(b))),\n                    channel.zipRight(feed(input))\n                  )\n                )\n              )\n            )\n          )\n          return pipe(advance, Effect.orElse(() => reset), channel.unwrap)\n        }\n        const loop: Channel.Channel<Chunk.Chunk<C>, Chunk.Chunk<A>, E, E, void, unknown, R2> = core.readWith({\n          onInput: feed,\n          onFailure: core.fail,\n          onDone: () => core.void\n        })\n        return loop\n      }),\n      channel.unwrap\n    )\n    return new StreamImpl(pipe(toChannel(self), core.pipeTo(driver)))\n  }\n)\n\n/** @internal */\nexport const repeatValue = <A>(value: A): Stream.Stream<A> =>\n  new StreamImpl(\n    channel.repeated(core.write(Chunk.of(value)))\n  )\n\n/** @internal */\nexport const repeatWith = dual<\n  <B, R2, A, C>(\n    schedule: Schedule.Schedule<B, unknown, R2>,\n    options: {\n      readonly onElement: (a: A) => C\n      readonly onSchedule: (b: B) => C\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<C, E, R2 | R>,\n  <A, E, R, B, R2, C>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>,\n    options: {\n      readonly onElement: (a: A) => C\n      readonly onSchedule: (b: B) => C\n    }\n  ) => Stream.Stream<C, E, R2 | R>\n>(\n  3,\n  <A, E, R, B, R2, C>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, unknown, R2>,\n    options: {\n      readonly onElement: (a: A) => C\n      readonly onSchedule: (b: B) => C\n    }\n  ): Stream.Stream<C, E, R | R2> => {\n    return pipe(\n      Schedule.driver(schedule),\n      Effect.map((driver) => {\n        const provideLastIterationInfo = provideServiceEffect(\n          Schedule.CurrentIterationMetadata,\n          Ref.get(driver.iterationMeta)\n        )\n\n        const process = pipe(self, provideLastIterationInfo, map(options.onElement), toChannel)\n        const loop: Channel.Channel<Chunk.Chunk<C>, unknown, E, unknown, void, unknown, R | R2> = channel.unwrap(\n          Effect.match(\n            driver.next(void 0),\n            {\n              onFailure: () => core.void,\n              onSuccess: (output) =>\n                core.flatMap(\n                  process,\n                  () => channel.zipRight(core.write(Chunk.of(options.onSchedule(output))), loop)\n                )\n            }\n          )\n        )\n        return new StreamImpl(channel.zipRight(process, loop))\n      }),\n      unwrap\n    )\n  }\n)\n\nconst repeatWithSchedule = <A, R, X>(\n  value: A,\n  schedule: Schedule.Schedule<X, A, R>\n): Stream.Stream<A, never, R> => repeatEffectWithSchedule(Effect.succeed(value), schedule)\n\n/** @internal */\nexport const repeatEffectWithSchedule = <A, E, R, X, A0 extends A, R2>(\n  effect: Effect.Effect<A, E, R>,\n  schedule: Schedule.Schedule<X, A0, R2>\n): Stream.Stream<A, E, R | R2> =>\n  flatMap(\n    fromEffect(Effect.zip(effect, Schedule.driver(schedule))),\n    ([a, driver]) => {\n      const provideLastIterationInfo = Effect.provideServiceEffect(\n        Schedule.CurrentIterationMetadata,\n        Ref.get(driver.iterationMeta)\n      )\n      return concat(\n        succeed(a),\n        unfoldEffect(a, (s) =>\n          Effect.matchEffect(driver.next(s as A0), {\n            onFailure: Effect.succeed,\n            onSuccess: () =>\n              Effect.map(provideLastIterationInfo(effect), (nextA) => Option.some([nextA, nextA] as const))\n          }))\n      )\n    }\n  )\n\n/** @internal */\nexport const retry = dual<\n  <E, R2, X>(\n    policy: Schedule.Schedule<X, Types.NoInfer<E>, R2>\n  ) => <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R2 | R>,\n  <A, E, R, X, R2>(\n    self: Stream.Stream<A, E, R>,\n    policy: Schedule.Schedule<X, Types.NoInfer<E>, R2>\n  ) => Stream.Stream<A, E, R2 | R>\n>(\n  2,\n  <A, E, R, X, R2>(\n    self: Stream.Stream<A, E, R>,\n    policy: Schedule.Schedule<X, Types.NoInfer<E>, R2>\n  ): Stream.Stream<A, E, R2 | R> =>\n    Schedule.driver(policy).pipe(\n      Effect.map((driver) => {\n        const provideLastIterationInfo = provideServiceEffect(\n          Schedule.CurrentIterationMetadata,\n          Ref.get(driver.iterationMeta)\n        )\n\n        const loop: Channel.Channel<\n          Chunk.Chunk<A>,\n          unknown,\n          E,\n          unknown,\n          unknown,\n          unknown,\n          R2 | R\n        > = toChannel(provideLastIterationInfo(self)).pipe(\n          channel.mapOutEffect((out) => Effect.as(driver.reset, out)),\n          channel.catchAll((error) =>\n            driver.next(error).pipe(\n              Effect.match({\n                onFailure: () => core.fail(error),\n                onSuccess: () => loop\n              }),\n              channel.unwrap\n            )\n          )\n        )\n        return loop\n      }),\n      channel.unwrap,\n      fromChannel\n    )\n)\n\n/** @internal */\nexport const withExecutionPlan: {\n  <Input, R2, Provides, PolicyE>(\n    policy: ExecutionPlan<{\n      provides: Provides\n      input: Input\n      error: PolicyE\n      requirements: R2\n    }>,\n    options?: {\n      readonly preventFallbackOnPartialStream?: boolean | undefined\n    }\n  ): <A, E extends Input, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Stream.Stream<A, E | PolicyE, R2 | Exclude<R, Provides>>\n  <A, E extends Input, R, R2, Input, Provides, PolicyE>(\n    self: Stream.Stream<A, E, R>,\n    policy: ExecutionPlan<{\n      provides: Provides\n      input: Input\n      error: PolicyE\n      requirements: R2\n    }>,\n    options?: {\n      readonly preventFallbackOnPartialStream?: boolean | undefined\n    }\n  ): Stream.Stream<A, E | PolicyE, R2 | Exclude<R, Provides>>\n} = dual((args) => isStream(args[0]), <A, E extends Input, R, R2, Input, Provides, PolicyE>(\n  self: Stream.Stream<A, E, R>,\n  policy: ExecutionPlan<{\n    provides: Provides\n    input: Input\n    error: PolicyE\n    requirements: R2\n  }>,\n  options?: {\n    readonly preventFallbackOnPartialStream?: boolean | undefined\n  }\n): Stream.Stream<A, E | PolicyE, R2 | Exclude<R, Provides>> =>\n  suspend(() => {\n    const preventFallbackOnPartialStream = options?.preventFallbackOnPartialStream ?? false\n    let i = 0\n    let lastError = Option.none<E | PolicyE>()\n    const loop: Stream.Stream<\n      A,\n      E | PolicyE,\n      R2 | Exclude<R, Provides>\n    > = suspend(() => {\n      const step = policy.steps[i++]\n      if (!step) {\n        return fail(Option.getOrThrow(lastError))\n      }\n\n      let nextStream: Stream.Stream<A, E | PolicyE, R2 | Exclude<R, Provides>> = Context.isContext(step.provide)\n        ? provideSomeContext(self, step.provide)\n        : provideSomeLayer(self, step.provide as Layer.Layer<Provides, E | PolicyE, R2>)\n      let receivedElements = false\n\n      if (Option.isSome(lastError)) {\n        const error = lastError.value\n        let attempted = false\n        const wrapped = nextStream\n        // ensure the schedule is applied at least once\n        nextStream = suspend(() => {\n          if (attempted) return wrapped\n          attempted = true\n          return fail(error)\n        })\n        nextStream = scheduleDefectRefail(retry(nextStream, internalExecutionPlan.scheduleFromStep(step, false)!))\n      } else {\n        const schedule = internalExecutionPlan.scheduleFromStep(step, true)\n        nextStream = schedule ? scheduleDefectRefail(retry(nextStream, schedule)) : nextStream\n      }\n\n      return catchAll(\n        preventFallbackOnPartialStream ?\n          mapChunks(nextStream, (chunk) => {\n            receivedElements = true\n            return chunk\n          }) :\n          nextStream,\n        (error) => {\n          if (preventFallbackOnPartialStream && receivedElements) {\n            return fail(error)\n          }\n          lastError = Option.some(error)\n          return loop\n        }\n      )\n    })\n    return loop\n  }))\n\nconst scheduleDefectRefail = <A, E, R>(self: Stream.Stream<A, E, R>) =>\n  catchAllCause(self, (cause) => failCause(InternalSchedule.scheduleDefectRefailCause(cause)))\n\n/** @internal */\nexport const run = dual<\n  <A2, A, E2, R2>(\n    sink: Sink.Sink<A2, A, unknown, E2, R2>\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<A2, E2 | E, R | R2>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<A2, A, unknown, E2, R2>\n  ) => Effect.Effect<A2, E2 | E, R | R2>\n>(2, <A, E, R, A2, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  sink: Sink.Sink<A2, A, unknown, E2, R2>\n): Effect.Effect<A2, E2 | E, R | R2> =>\n  toChannel(self).pipe(\n    channel.pipeToOrFail(sink_.toChannel(sink)),\n    channel.runDrain\n  ))\n\n/** @internal */\nexport const runCollect = <A, E, R>(\n  self: Stream.Stream<A, E, R>\n): Effect.Effect<Chunk.Chunk<A>, E, R> => run(self, sink_.collectAll())\n\n/** @internal */\nexport const runCount = <A, E, R>(self: Stream.Stream<A, E, R>): Effect.Effect<number, E, R> => run(self, sink_.count)\n\n/** @internal */\nexport const runDrain = <A, E, R>(self: Stream.Stream<A, E, R>): Effect.Effect<void, E, R> => run(self, sink_.drain)\n\n/** @internal */\nexport const runFold = dual<\n  <S, A>(\n    s: S,\n    f: (s: S, a: A) => S\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<S, E, R>,\n  <A, E, R, S>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => S\n  ) => Effect.Effect<S, E, R>\n>(\n  3,\n  <A, E, R, S>(self: Stream.Stream<A, E, R>, s: S, f: (s: S, a: A) => S): Effect.Effect<S, E, R> =>\n    runFoldWhile(self, s, constTrue, f)\n)\n\n/** @internal */\nexport const runFoldEffect = dual<\n  <S, A, E2, R2>(\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<S, E2 | E, R | R2>,\n  <A, E, R, S, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ) => Effect.Effect<S, E2 | E, R | R2>\n>(3, <A, E, R, S, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  s: S,\n  f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n): Effect.Effect<S, E2 | E, R | R2> => runFoldWhileEffect(self, s, constTrue, f))\n\n/** @internal */\nexport const runFoldScoped = dual<\n  <S, A>(s: S, f: (s: S, a: A) => S) => <E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<S, E, Scope.Scope | R>,\n  <A, E, R, S>(self: Stream.Stream<A, E, R>, s: S, f: (s: S, a: A) => S) => Effect.Effect<S, E, Scope.Scope | R>\n>(\n  3,\n  <A, E, R, S>(self: Stream.Stream<A, E, R>, s: S, f: (s: S, a: A) => S): Effect.Effect<S, E, Scope.Scope | R> =>\n    pipe(self, runFoldWhileScoped(s, constTrue, f))\n)\n\n/** @internal */\nexport const runFoldScopedEffect = dual<\n  <S, A, E2, R2>(\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<S, E2 | E, Scope.Scope | R2 | R>,\n  <A, E, R, S, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ) => Effect.Effect<S, E2 | E, Scope.Scope | R2 | R>\n>(3, <A, E, R, S, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  s: S,\n  f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n): Effect.Effect<S, E2 | E, Scope.Scope | R2 | R> => pipe(self, runFoldWhileScopedEffect(s, constTrue, f)))\n\n/** @internal */\nexport const runFoldWhile = dual<\n  <S, A>(\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => S\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<S, E, R>,\n  <A, E, R, S>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => S\n  ) => Effect.Effect<S, E, R>\n>(4, <A, E, R, S>(\n  self: Stream.Stream<A, E, R>,\n  s: S,\n  cont: Predicate<S>,\n  f: (s: S, a: A) => S\n): Effect.Effect<S, E, R> => run(self, sink_.fold(s, cont, f)))\n\n/** @internal */\nexport const runFoldWhileEffect = dual<\n  <S, A, E2, R2>(\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<S, E2 | E, R | R2>,\n  <A, E, R, S, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ) => Effect.Effect<S, E2 | E, R | R2>\n>(4, <A, E, R, S, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  s: S,\n  cont: Predicate<S>,\n  f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n): Effect.Effect<S, E2 | E, R | R2> => run(self, sink_.foldEffect(s, cont, f)))\n\n/** @internal */\nexport const runFoldWhileScoped = dual<\n  <S, A>(\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => S\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<S, E, Scope.Scope | R>,\n  <A, E, R, S>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => S\n  ) => Effect.Effect<S, E, Scope.Scope | R>\n>(4, <A, E, R, S>(\n  self: Stream.Stream<A, E, R>,\n  s: S,\n  cont: Predicate<S>,\n  f: (s: S, a: A) => S\n): Effect.Effect<S, E, Scope.Scope | R> => pipe(self, runScoped(sink_.fold(s, cont, f))))\n\n/** @internal */\nexport const runFoldWhileScopedEffect = dual<\n  <S, A, E2, R2>(\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<S, E2 | E, Scope.Scope | R2 | R>,\n  <A, E, R, S, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    cont: Predicate<S>,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ) => Effect.Effect<S, E2 | E, Scope.Scope | R2 | R>\n>(4, <A, E, R, S, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  s: S,\n  cont: Predicate<S>,\n  f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n): Effect.Effect<S, E2 | E, Scope.Scope | R2 | R> => pipe(self, runScoped(sink_.foldEffect(s, cont, f))))\n\n/** @internal */\nexport const runForEach = dual<\n  <A, X, E2, R2>(\n    f: (a: A) => Effect.Effect<X, E2, R2>\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<void, E2 | E, R | R2>,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<X, E2, R2>\n  ) => Effect.Effect<void, E2 | E, R | R2>\n>(2, <A, E, R, X, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  f: (a: A) => Effect.Effect<X, E2, R2>\n): Effect.Effect<void, E2 | E, R | R2> => run(self, sink_.forEach(f)))\n\n/** @internal */\nexport const runForEachChunk = dual<\n  <A, X, E2, R2>(\n    f: (a: Chunk.Chunk<A>) => Effect.Effect<X, E2, R2>\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<void, E2 | E, R | R2>,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: Chunk.Chunk<A>) => Effect.Effect<X, E2, R2>\n  ) => Effect.Effect<void, E2 | E, R | R2>\n>(2, <A, E, R, X, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  f: (a: Chunk.Chunk<A>) => Effect.Effect<X, E2, R2>\n): Effect.Effect<void, E2 | E, R | R2> => run(self, sink_.forEachChunk(f)))\n\n/** @internal */\nexport const runForEachChunkScoped = dual<\n  <A, X, E2, R2>(\n    f: (a: Chunk.Chunk<A>) => Effect.Effect<X, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<void, E2 | E, Scope.Scope | R2 | R>,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: Chunk.Chunk<A>) => Effect.Effect<X, E2, R2>\n  ) => Effect.Effect<void, E2 | E, Scope.Scope | R2 | R>\n>(2, <A, E, R, X, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  f: (a: Chunk.Chunk<A>) => Effect.Effect<X, E2, R2>\n): Effect.Effect<void, E2 | E, Scope.Scope | R2 | R> => pipe(self, runScoped(sink_.forEachChunk(f))))\n\n/** @internal */\nexport const runForEachScoped = dual<\n  <A, X, E2, R2>(\n    f: (a: A) => Effect.Effect<X, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<void, E2 | E, R2 | R | Scope.Scope>,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<X, E2, R2>\n  ) => Effect.Effect<void, E2 | E, R2 | R | Scope.Scope>\n>(2, <A, E, R, X, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  f: (a: A) => Effect.Effect<X, E2, R2>\n): Effect.Effect<void, E2 | E, R2 | R | Scope.Scope> => pipe(self, runScoped(sink_.forEach(f))))\n\n/** @internal */\nexport const runForEachWhile = dual<\n  <A, E2, R2>(\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ) => <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<void, E2 | E, R | R2>,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ) => Effect.Effect<void, E2 | E, R | R2>\n>(2, <A, E, R, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  f: (a: A) => Effect.Effect<boolean, E2, R2>\n): Effect.Effect<void, E2 | E, R | R2> => run(self, sink_.forEachWhile(f)))\n\n/** @internal */\nexport const runForEachWhileScoped = dual<\n  <A, E2, R2>(\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<void, E2 | E, R2 | R | Scope.Scope>,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: A) => Effect.Effect<boolean, E2, R2>\n  ) => Effect.Effect<void, E2 | E, R2 | R | Scope.Scope>\n>(2, <A, E, R, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  f: (a: A) => Effect.Effect<boolean, E2, R2>\n): Effect.Effect<void, E2 | E, R2 | R | Scope.Scope> => pipe(self, runScoped(sink_.forEachWhile(f))))\n\n/** @internal */\nexport const runHead = <A, E, R>(\n  self: Stream.Stream<A, E, R>\n): Effect.Effect<Option.Option<A>, E, R> => run(self, sink_.head<A>())\n\n/** @internal */\nexport const runIntoPubSub = dual<\n  <A, E>(\n    pubsub: PubSub.PubSub<Take.Take<A, E>>\n  ) => <R>(self: Stream.Stream<A, E, R>) => Effect.Effect<void, never, Exclude<R, Scope.Scope>>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    pubsub: PubSub.PubSub<Take.Take<A, E>>\n  ) => Effect.Effect<void, never, Exclude<R, Scope.Scope>>\n>(\n  2,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    pubsub: PubSub.PubSub<Take.Take<A, E>>\n  ): Effect.Effect<void, never, Exclude<R, Scope.Scope>> => pipe(self, runIntoQueue(pubsub))\n)\n\n/** @internal */\nexport const runIntoPubSubScoped = dual<\n  <A, E>(\n    pubsub: PubSub.PubSub<Take.Take<A, E>>\n  ) => <R>(self: Stream.Stream<A, E, R>) => Effect.Effect<void, never, Scope.Scope | R>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    pubsub: PubSub.PubSub<Take.Take<A, E>>\n  ) => Effect.Effect<void, never, Scope.Scope | R>\n>(2, <A, E, R>(\n  self: Stream.Stream<A, E, R>,\n  pubsub: PubSub.PubSub<Take.Take<A, E>>\n): Effect.Effect<void, never, Scope.Scope | R> => pipe(self, runIntoQueueScoped(pubsub)))\n\n/** @internal */\nexport const runIntoQueue = dual<\n  <A, E>(\n    queue: Queue.Enqueue<Take.Take<A, E>>\n  ) => <R>(self: Stream.Stream<A, E, R>) => Effect.Effect<void, never, Exclude<R, Scope.Scope>>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    queue: Queue.Enqueue<Take.Take<A, E>>\n  ) => Effect.Effect<void, never, Exclude<R, Scope.Scope>>\n>(\n  2,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    queue: Queue.Enqueue<Take.Take<A, E>>\n  ): Effect.Effect<void, never, Exclude<R, Scope.Scope>> => pipe(self, runIntoQueueScoped(queue), Effect.scoped)\n)\n\n/** @internal */\nexport const runIntoQueueElementsScoped = dual<\n  <A, E>(\n    queue: Queue.Enqueue<Exit.Exit<A, Option.Option<E>>>\n  ) => <R>(self: Stream.Stream<A, E, R>) => Effect.Effect<void, never, Scope.Scope | R>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    queue: Queue.Enqueue<Exit.Exit<A, Option.Option<E>>>\n  ) => Effect.Effect<void, never, Scope.Scope | R>\n>(2, <A, E, R>(\n  self: Stream.Stream<A, E, R>,\n  queue: Queue.Enqueue<Exit.Exit<A, Option.Option<E>>>\n): Effect.Effect<void, never, Scope.Scope | R> => {\n  const writer: Channel.Channel<Exit.Exit<A, Option.Option<E>>, Chunk.Chunk<A>, never, E, unknown, unknown, R> = core\n    .readWithCause({\n      onInput: (input: Chunk.Chunk<A>) =>\n        core.flatMap(\n          core.fromEffect(Queue.offerAll(queue, Chunk.map(input, Exit.succeed))),\n          () => writer\n        ),\n      onFailure: (cause) => core.fromEffect(Queue.offer(queue, Exit.failCause(Cause.map(cause, Option.some)))),\n      onDone: () => core.fromEffect(Queue.offer(queue, Exit.fail(Option.none())))\n    })\n  return pipe(\n    core.pipeTo(toChannel(self), writer),\n    channel.drain,\n    channel.runScoped,\n    Effect.asVoid\n  )\n})\n\n/** @internal */\nexport const runIntoQueueScoped = dual<\n  <A, E>(\n    queue: Queue.Enqueue<Take.Take<A, E>>\n  ) => <R>(self: Stream.Stream<A, E, R>) => Effect.Effect<void, never, Scope.Scope | R>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    queue: Queue.Enqueue<Take.Take<A, E>>\n  ) => Effect.Effect<void, never, Scope.Scope | R>\n>(2, <A, E, R>(\n  self: Stream.Stream<A, E, R>,\n  queue: Queue.Enqueue<Take.Take<A, E>>\n): Effect.Effect<void, never, Scope.Scope | R> => {\n  const writer: Channel.Channel<Take.Take<A, E>, Chunk.Chunk<A>, never, E, unknown, unknown, R> = core\n    .readWithCause({\n      onInput: (input: Chunk.Chunk<A>) => core.flatMap(core.write(InternalTake.chunk(input)), () => writer),\n      onFailure: (cause) => core.write(InternalTake.failCause(cause)),\n      onDone: () => core.write(InternalTake.end)\n    })\n  return pipe(\n    core.pipeTo(toChannel(self), writer),\n    channel.mapOutEffect((take) => Queue.offer(queue, take)),\n    channel.drain,\n    channel.runScoped,\n    Effect.asVoid\n  )\n})\n\n/** @internal */\nexport const runLast = <A, E, R>(\n  self: Stream.Stream<A, E, R>\n): Effect.Effect<Option.Option<A>, E, R> => run(self, sink_.last())\n\n/** @internal */\nexport const runScoped = dual<\n  <A2, A, E2, R2>(\n    sink: Sink.Sink<A2, A, unknown, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<A2, E | E2, R | R2 | Scope.Scope>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<A2, A, unknown, E2, R2>\n  ) => Effect.Effect<A2, E | E2, R | R2 | Scope.Scope>\n>(2, <A, E, R, A2, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  sink: Sink.Sink<A2, A, unknown, E2, R2>\n): Effect.Effect<A2, E | E2, R | R2 | Scope.Scope> =>\n  pipe(\n    toChannel(self),\n    channel.pipeToOrFail(sink_.toChannel(sink)),\n    channel.drain,\n    channel.runScoped\n  ))\n\n/** @internal */\nexport const runSum = <E, R>(self: Stream.Stream<number, E, R>): Effect.Effect<number, E, R> => run(self, sink_.sum)\n\n/** @internal */\nexport const scan = dual<\n  <S, A>(s: S, f: (s: S, a: A) => S) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<S, E, R>,\n  <A, E, R, S>(self: Stream.Stream<A, E, R>, s: S, f: (s: S, a: A) => S) => Stream.Stream<S, E, R>\n>(\n  3,\n  <A, E, R, S>(self: Stream.Stream<A, E, R>, s: S, f: (s: S, a: A) => S): Stream.Stream<S, E, R> =>\n    pipe(self, scanEffect(s, (s, a) => Effect.succeed(f(s, a))))\n)\n\n/** @internal */\nexport const scanReduce = dual<\n  <A2, A>(f: (a2: A2 | A, a: A) => A2) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E, R>,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, f: (a2: A2 | A, a: A) => A2) => Stream.Stream<A2 | A, E, R>\n>(\n  2,\n  <A, E, R, A2>(self: Stream.Stream<A, E, R>, f: (a2: A | A2, a: A) => A2): Stream.Stream<A | A2, E, R> =>\n    pipe(self, scanReduceEffect((a2, a) => Effect.succeed(f(a2, a))))\n)\n\n/** @internal */\nexport const scanReduceEffect = dual<\n  <A2, A, E2, R2>(\n    f: (a2: A2 | A, a: A) => Effect.Effect<A2 | A, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a2: A2 | A, a: A) => Effect.Effect<A2 | A, E2, R2>\n  ) => Stream.Stream<A2 | A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a2: A | A2, a: A) => Effect.Effect<A2 | A, E2, R2>\n  ): Stream.Stream<A2 | A, E2 | E, R2 | R> =>\n    pipe(\n      self,\n      mapAccumEffect<Option.Option<A | A2>, A, A | A2, E2, R2>(Option.none() as Option.Option<A | A2>, (option, a) => {\n        switch (option._tag) {\n          case \"None\": {\n            return Effect.succeed([Option.some<A | A2>(a), a] as const)\n          }\n          case \"Some\": {\n            return pipe(\n              f(option.value, a),\n              Effect.map((b) => [Option.some<A | A2>(b), b] as const)\n            )\n          }\n        }\n      })\n    )\n)\n\n/** @internal */\nexport const schedule = dual<\n  <X, A0 extends A, R2, A>(\n    schedule: Schedule.Schedule<X, A0, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R2 | R>,\n  <A, E, R, X, A0 extends A, R2>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<X, A0, R2>\n  ) => Stream.Stream<A, E, R2 | R>\n>(\n  2,\n  <A, E, R, X, A0 extends A, R2>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<X, A0, R2>\n  ): Stream.Stream<A, E, R | R2> =>\n    filterMap(\n      scheduleWith(self, schedule, { onElement: Option.some, onSchedule: Option.none }),\n      identity\n    )\n)\n\n/** @internal */\nexport const scheduleWith = dual<\n  <B, A0 extends A, R2, A, C>(\n    schedule: Schedule.Schedule<B, A0, R2>,\n    options: {\n      readonly onElement: (a: A) => C\n      readonly onSchedule: (b: B) => C\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<C, E, R2 | R>,\n  <A, E, R, B, A0 extends A, R2, C>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, A0, R2>,\n    options: {\n      readonly onElement: (a: A) => C\n      readonly onSchedule: (b: B) => C\n    }\n  ) => Stream.Stream<C, E, R2 | R>\n>(\n  3,\n  <A, E, R, B, A0 extends A, R2, C>(\n    self: Stream.Stream<A, E, R>,\n    schedule: Schedule.Schedule<B, A0, R2>,\n    options: {\n      readonly onElement: (a: A) => C\n      readonly onSchedule: (b: B) => C\n    }\n  ): Stream.Stream<C, E, R | R2> => {\n    const loop = (\n      driver: Schedule.ScheduleDriver<B, A0, R2>,\n      iterator: Iterator<A>\n    ): Channel.Channel<Chunk.Chunk<C>, Chunk.Chunk<A>, E, E, unknown, unknown, R2> => {\n      const next = iterator.next()\n      if (next.done) {\n        return core.readWithCause({\n          onInput: (chunk: Chunk.Chunk<A>) => loop(driver, chunk[Symbol.iterator]()),\n          onFailure: core.failCause,\n          onDone: core.succeedNow\n        })\n      }\n      return channel.unwrap(\n        Effect.matchEffect(driver.next(next.value as A0), {\n          onFailure: () =>\n            pipe(\n              driver.last,\n              Effect.orDie,\n              Effect.map((b) =>\n                pipe(\n                  core.write(Chunk.make(options.onElement(next.value), options.onSchedule(b))),\n                  core.flatMap(() => loop(driver, iterator))\n                )\n              ),\n              Effect.zipLeft(driver.reset)\n            ),\n          onSuccess: () =>\n            Effect.succeed(pipe(\n              core.write(Chunk.of(options.onElement(next.value))),\n              core.flatMap(() => loop(driver, iterator))\n            ))\n        })\n      )\n    }\n    return new StreamImpl(\n      pipe(\n        core.fromEffect(Schedule.driver(schedule)),\n        core.flatMap((driver) =>\n          pipe(\n            toChannel(self),\n            core.pipeTo(loop(driver, Chunk.empty<A>()[Symbol.iterator]()))\n          )\n        )\n      )\n    )\n  }\n)\n\n/** @internal */\nexport const scanEffect = dual<\n  <S, A, E2, R2>(\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<S, E2 | E, R2 | R>,\n  <A, E, R, S, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ) => Stream.Stream<S, E2 | E, R2 | R>\n>(\n  3,\n  <A, E, R, S, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    s: S,\n    f: (s: S, a: A) => Effect.Effect<S, E2, R2>\n  ): Stream.Stream<S, E2 | E, R2 | R> =>\n    new StreamImpl(\n      pipe(\n        core.write(Chunk.of(s)),\n        core.flatMap(() =>\n          toChannel(pipe(\n            self,\n            mapAccumEffect(s, (s, a) => pipe(f(s, a), Effect.map((s) => [s, s])))\n          ))\n        )\n      )\n    )\n)\n\n/** @internal */\nexport const scoped = <A, E, R>(\n  effect: Effect.Effect<A, E, R>\n): Stream.Stream<A, E, Exclude<R, Scope.Scope>> =>\n  new StreamImpl(channel.ensuring(channel.scoped(pipe(effect, Effect.map(Chunk.of))), Effect.void))\n\n/** @internal */\nexport const scopedWith = <A, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<A, E, R>\n): Stream.Stream<A, E, R> =>\n  new StreamImpl(channel.scopedWith((scope) =>\n    f(scope).pipe(\n      Effect.map(Chunk.of)\n    )\n  ))\n\n/** @internal */\nexport const some = <A, E, R>(self: Stream.Stream<Option.Option<A>, E, R>): Stream.Stream<A, Option.Option<E>, R> =>\n  pipe(self, mapError(Option.some), someOrFail(() => Option.none()))\n\n/** @internal */\nexport const someOrElse = dual<\n  <A2>(fallback: LazyArg<A2>) => <A, E, R>(self: Stream.Stream<Option.Option<A>, E, R>) => Stream.Stream<A2 | A, E, R>,\n  <A, E, R, A2>(self: Stream.Stream<Option.Option<A>, E, R>, fallback: LazyArg<A2>) => Stream.Stream<A2 | A, E, R>\n>(\n  2,\n  <A, E, R, A2>(self: Stream.Stream<Option.Option<A>, E, R>, fallback: LazyArg<A2>): Stream.Stream<A | A2, E, R> =>\n    pipe(self, map(Option.getOrElse(fallback)))\n)\n\n/** @internal */\nexport const someOrFail = dual<\n  <E2>(error: LazyArg<E2>) => <A, E, R>(self: Stream.Stream<Option.Option<A>, E, R>) => Stream.Stream<A, E2 | E, R>,\n  <A, E, R, E2>(self: Stream.Stream<Option.Option<A>, E, R>, error: LazyArg<E2>) => Stream.Stream<A, E2 | E, R>\n>(\n  2,\n  <A, E, R, E2>(self: Stream.Stream<Option.Option<A>, E, R>, error: LazyArg<E2>): Stream.Stream<A, E | E2, R> =>\n    mapEffectSequential(\n      self,\n      Option.match({\n        onNone: () => Effect.failSync(error),\n        onSome: Effect.succeed\n      })\n    )\n)\n\n/** @internal */\nexport const sliding = dual<\n  (\n    chunkSize: number\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Chunk.Chunk<A>, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, chunkSize: number) => Stream.Stream<Chunk.Chunk<A>, E, R>\n>(\n  2,\n  <A, E, R>(self: Stream.Stream<A, E, R>, chunkSize: number): Stream.Stream<Chunk.Chunk<A>, E, R> =>\n    slidingSize(self, chunkSize, 1)\n)\n\n/** @internal */\nexport const slidingSize = dual<\n  (\n    chunkSize: number,\n    stepSize: number\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Chunk.Chunk<A>, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, chunkSize: number, stepSize: number) => Stream.Stream<Chunk.Chunk<A>, E, R>\n>(\n  3,\n  <A, E, R>(self: Stream.Stream<A, E, R>, chunkSize: number, stepSize: number): Stream.Stream<Chunk.Chunk<A>, E, R> => {\n    if (chunkSize <= 0 || stepSize <= 0) {\n      return die(\n        new Cause.IllegalArgumentException(\"Invalid bounds - `chunkSize` and `stepSize` must be greater than zero\")\n      )\n    }\n    return new StreamImpl(core.suspend(() => {\n      const queue = new RingBuffer<A>(chunkSize)\n      const emitOnStreamEnd = (\n        queueSize: number,\n        channelEnd: Channel.Channel<Chunk.Chunk<Chunk.Chunk<A>>, Chunk.Chunk<A>, E, E, unknown, unknown>\n      ) => {\n        if (queueSize < chunkSize) {\n          const items = queue.toChunk()\n          const result = Chunk.isEmpty(items) ? Chunk.empty<Chunk.Chunk<A>>() : Chunk.of(items)\n          return pipe(core.write(result), core.flatMap(() => channelEnd))\n        }\n        const lastEmitIndex = queueSize - (queueSize - chunkSize) % stepSize\n        if (lastEmitIndex === queueSize) {\n          return channelEnd\n        }\n        const leftovers = queueSize - (lastEmitIndex - chunkSize + stepSize)\n        const lastItems = pipe(queue.toChunk(), Chunk.takeRight(leftovers))\n        const result = Chunk.isEmpty(lastItems) ? Chunk.empty<Chunk.Chunk<A>>() : Chunk.of(lastItems)\n        return pipe(core.write(result), core.flatMap(() => channelEnd))\n      }\n      const reader = (\n        queueSize: number\n      ): Channel.Channel<Chunk.Chunk<Chunk.Chunk<A>>, Chunk.Chunk<A>, E, E, unknown, unknown> =>\n        core.readWithCause({\n          onInput: (input: Chunk.Chunk<A>) =>\n            core.flatMap(\n              core.write(\n                Chunk.filterMap(input, (element, index) => {\n                  queue.put(element)\n                  const currentIndex = queueSize + index + 1\n                  if (currentIndex < chunkSize || (currentIndex - chunkSize) % stepSize > 0) {\n                    return Option.none()\n                  }\n                  return Option.some(queue.toChunk())\n                })\n              ),\n              () => reader(queueSize + input.length)\n            ),\n          onFailure: (cause) => emitOnStreamEnd(queueSize, core.failCause(cause)),\n          onDone: () => emitOnStreamEnd(queueSize, core.void)\n        })\n      return pipe(toChannel(self), core.pipeTo(reader(0)))\n    }))\n  }\n)\n\n/** @internal */\nexport const split: {\n  <A, B extends A>(\n    refinement: Refinement<Types.NoInfer<A>, B>\n  ): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Chunk.Chunk<Exclude<A, B>>, E, R>\n  <A>(\n    predicate: Predicate<Types.NoInfer<A>>\n  ): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Chunk.Chunk<A>, E, R>\n  <A, E, R, B extends A>(\n    self: Stream.Stream<A, E, R>,\n    refinement: Refinement<A, B>\n  ): Stream.Stream<Chunk.Chunk<Exclude<A, B>>, E, R>\n  <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>): Stream.Stream<Chunk.Chunk<A>, E, R>\n} = dual(\n  2,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    predicate: Predicate<A>\n  ): Stream.Stream<Chunk.Chunk<A>, E, R> => {\n    const split = (\n      leftovers: Chunk.Chunk<A>,\n      input: Chunk.Chunk<A>\n    ): Channel.Channel<Chunk.Chunk<Chunk.Chunk<A>>, Chunk.Chunk<A>, E, E, unknown, unknown, R> => {\n      const [chunk, remaining] = pipe(leftovers, Chunk.appendAll(input), Chunk.splitWhere(predicate))\n      if (Chunk.isEmpty(chunk) || Chunk.isEmpty(remaining)) {\n        return loop(pipe(chunk, Chunk.appendAll(pipe(remaining, Chunk.drop(1)))))\n      }\n      return pipe(\n        core.write(Chunk.of(chunk)),\n        core.flatMap(() => split(Chunk.empty(), pipe(remaining, Chunk.drop(1))))\n      )\n    }\n    const loop = (\n      leftovers: Chunk.Chunk<A>\n    ): Channel.Channel<Chunk.Chunk<Chunk.Chunk<A>>, Chunk.Chunk<A>, E, E, unknown, unknown, R> =>\n      core.readWith({\n        onInput: (input: Chunk.Chunk<A>) => split(leftovers, input),\n        onFailure: core.fail,\n        onDone: () => {\n          if (Chunk.isEmpty(leftovers)) {\n            return core.void\n          }\n          if (Option.isNone(pipe(leftovers, Chunk.findFirst(predicate)))) {\n            return channel.zipRight(core.write(Chunk.of(leftovers)), core.void)\n          }\n          return channel.zipRight(\n            split(Chunk.empty(), leftovers),\n            core.void\n          )\n        }\n      })\n    return new StreamImpl(pipe(toChannel(self), core.pipeTo(loop(Chunk.empty()))))\n  }\n)\n\n/** @internal */\nexport const splitOnChunk = dual<\n  <A>(delimiter: Chunk.Chunk<A>) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<Chunk.Chunk<A>, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, delimiter: Chunk.Chunk<A>) => Stream.Stream<Chunk.Chunk<A>, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, delimiter: Chunk.Chunk<A>): Stream.Stream<Chunk.Chunk<A>, E, R> => {\n  const next = (\n    leftover: Option.Option<Chunk.Chunk<A>>,\n    delimiterIndex: number\n  ): Channel.Channel<Chunk.Chunk<Chunk.Chunk<A>>, Chunk.Chunk<A>, E, E, unknown, unknown, R> =>\n    core.readWithCause({\n      onInput: (inputChunk: Chunk.Chunk<A>) => {\n        let buffer: Array<Chunk.Chunk<A>> | undefined\n        const [carry, delimiterCursor] = pipe(\n          inputChunk,\n          Chunk.reduce(\n            [pipe(leftover, Option.getOrElse(() => Chunk.empty<A>())), delimiterIndex] as const,\n            ([carry, delimiterCursor], a) => {\n              const concatenated = pipe(carry, Chunk.append(a))\n              if (\n                delimiterCursor < delimiter.length &&\n                Equal.equals(a, pipe(delimiter, Chunk.unsafeGet(delimiterCursor)))\n              ) {\n                if (delimiterCursor + 1 === delimiter.length) {\n                  if (buffer === undefined) {\n                    buffer = []\n                  }\n                  buffer.push(pipe(concatenated, Chunk.take(concatenated.length - delimiter.length)))\n                  return [Chunk.empty<A>(), 0] as const\n                }\n                return [concatenated, delimiterCursor + 1] as const\n              }\n              return [concatenated, Equal.equals(a, pipe(delimiter, Chunk.unsafeGet(0))) ? 1 : 0] as const\n            }\n          )\n        )\n        const output = buffer === undefined ? Chunk.empty<Chunk.Chunk<A>>() : Chunk.unsafeFromArray(buffer)\n        return core.flatMap(\n          core.write(output),\n          () => next(Chunk.isNonEmpty(carry) ? Option.some(carry) : Option.none(), delimiterCursor)\n        )\n      },\n      onFailure: (cause) =>\n        Option.match(leftover, {\n          onNone: () => core.failCause(cause),\n          onSome: (chunk) =>\n            channel.zipRight(\n              core.write(Chunk.of(chunk)),\n              core.failCause(cause)\n            )\n        }),\n      onDone: (done) =>\n        Option.match(leftover, {\n          onNone: () => core.succeed(done),\n          onSome: (chunk) => channel.zipRight(core.write(Chunk.of(chunk)), core.succeed(done))\n        })\n    })\n  return new StreamImpl(pipe(toChannel(self), core.pipeTo(next(Option.none(), 0))))\n})\n\n/** @internal */\nexport const splitLines = <E, R>(self: Stream.Stream<string, E, R>): Stream.Stream<string, E, R> =>\n  pipeThroughChannel(self, channel.splitLines())\n\n/** @internal */\nexport const succeed = <A>(value: A): Stream.Stream<A> => fromChunk(Chunk.of(value))\n\n/** @internal */\nexport const sync = <A>(evaluate: LazyArg<A>): Stream.Stream<A> => suspend(() => fromChunk(Chunk.of(evaluate())))\n\n/** @internal */\nexport const suspend = <A, E, R>(stream: LazyArg<Stream.Stream<A, E, R>>): Stream.Stream<A, E, R> =>\n  new StreamImpl(core.suspend(() => toChannel(stream())))\n\n/** @internal */\nexport const take = dual<\n  (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, n: number) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, n: number): Stream.Stream<A, E, R> => {\n  if (!Number.isInteger(n)) {\n    return die(new Cause.IllegalArgumentException(`${n} must be an integer`))\n  }\n  const loop = (n: number): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, never, never, unknown, unknown> =>\n    core.readWith({\n      onInput: (input: Chunk.Chunk<A>) => {\n        const taken = pipe(input, Chunk.take(Math.min(n, Number.POSITIVE_INFINITY)))\n        const leftover = Math.max(0, n - taken.length)\n        const more = leftover > 0\n        if (more) {\n          return pipe(core.write(taken), core.flatMap(() => loop(leftover)))\n        }\n        return core.write(taken)\n      },\n      onFailure: core.fail,\n      onDone: core.succeed\n    })\n  return new StreamImpl(\n    pipe(\n      toChannel(self),\n      channel.pipeToOrFail(0 < n ? loop(n) : core.void)\n    )\n  )\n})\n\n/** @internal */\nexport const takeRight = dual<\n  (n: number) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, n: number) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, n: number): Stream.Stream<A, E, R> => {\n  if (n <= 0) {\n    return empty\n  }\n  return new StreamImpl(\n    pipe(\n      Effect.succeed(new RingBuffer<A>(n)),\n      Effect.map((queue) => {\n        const reader: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E, E, void, unknown> = core.readWith({\n          onInput: (input: Chunk.Chunk<A>) => {\n            for (const element of input) {\n              queue.put(element)\n            }\n            return reader\n          },\n          onFailure: core.fail,\n          onDone: () => pipe(core.write(queue.toChunk()), channel.zipRight(core.void))\n        })\n        return pipe(toChannel(self), core.pipeTo(reader))\n      }),\n      channel.unwrap\n    )\n  )\n})\n\n/** @internal */\nexport const takeUntil: {\n  <A>(predicate: Predicate<Types.NoInfer<A>>): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>\n  <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>): Stream.Stream<A, E, R>\n} = dual(2, <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>): Stream.Stream<A, E, R> => {\n  const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, never, never, unknown, unknown> = core.readWith({\n    onInput: (input: Chunk.Chunk<A>) => {\n      const taken = pipe(input, Chunk.takeWhile((a) => !predicate(a)))\n      const last = pipe(input, Chunk.drop(taken.length), Chunk.take(1))\n      if (Chunk.isEmpty(last)) {\n        return pipe(core.write(taken), core.flatMap(() => loop))\n      }\n      return core.write(pipe(taken, Chunk.appendAll(last)))\n    },\n    onFailure: core.fail,\n    onDone: core.succeed\n  })\n  return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(loop)))\n})\n\n/** @internal */\nexport const takeUntilEffect: {\n  <A, E2, R2>(\n    predicate: (a: Types.NoInfer<A>) => Effect.Effect<boolean, E2, R2>\n  ): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    predicate: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    predicate: (a: A) => Effect.Effect<boolean, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> => {\n    const loop = (\n      iterator: Iterator<A>\n    ): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R2> => {\n      const next = iterator.next()\n      if (next.done) {\n        return core.readWithCause({\n          onInput: (elem) => loop(elem[Symbol.iterator]()),\n          onFailure: core.failCause,\n          onDone: core.succeed\n        })\n      }\n      return pipe(\n        predicate(next.value),\n        Effect.map((bool) =>\n          bool ?\n            core.write(Chunk.of(next.value)) :\n            pipe(\n              core.write(Chunk.of(next.value)),\n              core.flatMap(() => loop(iterator))\n            )\n        ),\n        channel.unwrap\n      )\n    }\n    return new StreamImpl(pipe(toChannel(self), core.pipeTo(loop(Chunk.empty<A>()[Symbol.iterator]()))))\n  }\n)\n\n/** @internal */\nexport const takeWhile: {\n  <A, B extends A>(\n    refinement: Refinement<Types.NoInfer<A>, B>\n  ): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<B, E, R>\n  <A>(predicate: Predicate<Types.NoInfer<A>>): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>\n  <A, E, R, B extends A>(self: Stream.Stream<A, E, R>, refinement: Refinement<A, B>): Stream.Stream<B, E, R>\n  <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>): Stream.Stream<A, E, R>\n} = dual(2, <A, E, R>(self: Stream.Stream<A, E, R>, predicate: Predicate<A>): Stream.Stream<A, E, R> => {\n  const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, never, never, unknown, unknown> = core.readWith({\n    onInput: (input: Chunk.Chunk<A>) => {\n      const taken = pipe(input, Chunk.takeWhile(predicate))\n      const more = taken.length === input.length\n      if (more) {\n        return pipe(core.write(taken), core.flatMap(() => loop))\n      }\n      return core.write(taken)\n    },\n    onFailure: core.fail,\n    onDone: core.succeed\n  })\n  return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(loop)))\n})\n\n/** @internal */\nexport const tap: {\n  <A, X, E2, R2>(\n    f: (a: Types.NoInfer<A>) => Effect.Effect<X, E2, R2>\n  ): <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: Types.NoInfer<A>) => Effect.Effect<X, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (a: Types.NoInfer<A>) => Effect.Effect<X, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> => mapEffectSequential(self, (a) => Effect.as(f(a), a))\n)\n\n/** @internal */\nexport const tapBoth: {\n  <E, X1, E2, R2, A, X2, E3, R3>(\n    options: {\n      readonly onFailure: (e: Types.NoInfer<E>) => Effect.Effect<X1, E2, R2>\n      readonly onSuccess: (a: Types.NoInfer<A>) => Effect.Effect<X2, E3, R3>\n    }\n  ): <R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E | E2 | E3, R | R2 | R3>\n  <A, E, R, X1, E2, R2, X2, E3, R3>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly onFailure: (e: Types.NoInfer<E>) => Effect.Effect<X1, E2, R2>\n      readonly onSuccess: (a: Types.NoInfer<A>) => Effect.Effect<X2, E3, R3>\n    }\n  ): Stream.Stream<A, E | E2 | E3, R | R2 | R3>\n} = dual(\n  2,\n  <A, E, R, X1, E2, R2, X2, E3, R3>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly onFailure: (e: Types.NoInfer<E>) => Effect.Effect<X1, E2, R2>\n      readonly onSuccess: (a: Types.NoInfer<A>) => Effect.Effect<X2, E3, R3>\n    }\n  ): Stream.Stream<A, E | E2 | E3, R | R2 | R3> => pipe(self, tapError(options.onFailure), tap(options.onSuccess))\n)\n\n/** @internal */\nexport const tapError: {\n  <E, X, E2, R2>(\n    f: (error: Types.NoInfer<E>) => Effect.Effect<X, E2, R2>\n  ): <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E | E2, R2 | R>\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (error: E) => Effect.Effect<X, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (error: E) => Effect.Effect<X, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> =>\n    catchAll(self, (error) => fromEffect(Effect.zipRight(f(error), Effect.fail(error))))\n)\n\n/** @internal */\nexport const tapErrorCause: {\n  <E, X, E2, R2>(\n    f: (cause: Cause.Cause<Types.NoInfer<E>>) => Effect.Effect<X, E2, R2>\n  ): <A, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E | E2, R2 | R>\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (cause: Cause.Cause<E>) => Effect.Effect<X, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2>\n} = dual(\n  2,\n  <A, E, R, X, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    f: (cause: Cause.Cause<E>) => Effect.Effect<X, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> => {\n    const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R | R2> = core\n      .readWithCause({\n        onInput: (chunk) => core.flatMap(core.write(chunk), () => loop),\n        onFailure: (cause) => core.fromEffect(Effect.zipRight(f(cause), Effect.failCause(cause))),\n        onDone: core.succeedNow\n      })\n\n    return new StreamImpl(pipe(toChannel(self), core.pipeTo(loop)))\n  }\n)\n\n/** @internal */\nexport const tapSink = dual<\n  <A, E2, R2>(\n    sink: Sink.Sink<unknown, A, unknown, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<unknown, A, unknown, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<unknown, A, unknown, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> =>\n    pipe(\n      fromEffect(Effect.all([Queue.bounded<Take.Take<A, E | E2>>(1), Deferred.make<void>()])),\n      flatMap(([queue, deferred]) => {\n        const right = flattenTake(fromQueue(queue, { maxChunkSize: 1 }))\n        const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R2> = core\n          .readWithCause({\n            onInput: (chunk: Chunk.Chunk<A>) =>\n              pipe(\n                core.fromEffect(Queue.offer(queue, InternalTake.chunk(chunk))),\n                core.foldCauseChannel({\n                  onFailure: () => core.flatMap(core.write(chunk), () => channel.identityChannel()),\n                  onSuccess: () => core.flatMap(core.write(chunk), () => loop)\n                })\n              ) as Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, unknown, unknown, R2>,\n            onFailure: (cause: Cause.Cause<E | E2>) =>\n              pipe(\n                core.fromEffect(Queue.offer(queue, InternalTake.failCause(cause))),\n                core.foldCauseChannel({\n                  onFailure: () => core.failCause(cause),\n                  onSuccess: () => core.failCause(cause)\n                })\n              ),\n            onDone: () =>\n              pipe(\n                core.fromEffect(Queue.offer(queue, InternalTake.end)),\n                core.foldCauseChannel({\n                  onFailure: () => core.void,\n                  onSuccess: () => core.void\n                })\n              )\n          })\n        return pipe(\n          new StreamImpl(pipe(\n            core.pipeTo(toChannel(self), loop),\n            channel.ensuring(Effect.zipRight(\n              Effect.forkDaemon(Queue.offer(queue, InternalTake.end)),\n              Deferred.await(deferred)\n            ))\n          )),\n          merge(\n            execute(pipe(\n              run(right, sink),\n              Effect.ensuring(Effect.zipRight(\n                Queue.shutdown(queue),\n                Deferred.succeed(deferred, void 0)\n              ))\n            ))\n          )\n        )\n      })\n    )\n)\n\n/** @internal */\nexport const throttle = dual<\n  <A>(\n    options: {\n      readonly cost: (chunk: Chunk.Chunk<A>) => number\n      readonly units: number\n      readonly duration: Duration.DurationInput\n      readonly burst?: number | undefined\n      readonly strategy?: \"enforce\" | \"shape\" | undefined\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly cost: (chunk: Chunk.Chunk<A>) => number\n      readonly units: number\n      readonly duration: Duration.DurationInput\n      readonly burst?: number | undefined\n      readonly strategy?: \"enforce\" | \"shape\" | undefined\n    }\n  ) => Stream.Stream<A, E, R>\n>(\n  2,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly cost: (chunk: Chunk.Chunk<A>) => number\n      readonly units: number\n      readonly duration: Duration.DurationInput\n      readonly burst?: number | undefined\n      readonly strategy?: \"enforce\" | \"shape\" | undefined\n    }\n  ): Stream.Stream<A, E, R> =>\n    throttleEffect(self, {\n      ...options,\n      cost: (chunk) => Effect.succeed(options.cost(chunk))\n    })\n)\n\n/** @internal */\nexport const throttleEffect = dual<\n  <A, E2, R2>(\n    options: {\n      readonly cost: (chunk: Chunk.Chunk<A>) => Effect.Effect<number, E2, R2>\n      readonly units: number\n      readonly duration: Duration.DurationInput\n      readonly burst?: number | undefined\n      readonly strategy?: \"enforce\" | \"shape\" | undefined\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly cost: (chunk: Chunk.Chunk<A>) => Effect.Effect<number, E2, R2>\n      readonly units: number\n      readonly duration: Duration.DurationInput\n      readonly burst?: number | undefined\n      readonly strategy?: \"enforce\" | \"shape\" | undefined\n    }\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly cost: (chunk: Chunk.Chunk<A>) => Effect.Effect<number, E2, R2>\n      readonly units: number\n      readonly duration: Duration.DurationInput\n      readonly burst?: number | undefined\n      readonly strategy?: \"enforce\" | \"shape\" | undefined\n    }\n  ): Stream.Stream<A, E | E2, R | R2> => {\n    if (options.strategy === \"enforce\") {\n      return throttleEnforceEffect(self, options.cost, options.units, options.duration, options.burst ?? 0)\n    }\n    return throttleShapeEffect(self, options.cost, options.units, options.duration, options.burst ?? 0)\n  }\n)\n\nconst throttleEnforceEffect = <A, E, R, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  cost: (chunk: Chunk.Chunk<A>) => Effect.Effect<number, E2, R2>,\n  units: number,\n  duration: Duration.DurationInput,\n  burst: number\n): Stream.Stream<A, E | E2, R | R2> => {\n  const loop = (\n    tokens: number,\n    timestampMillis: number\n  ): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, void, unknown, R2> =>\n    core.readWithCause({\n      onInput: (input: Chunk.Chunk<A>) =>\n        pipe(\n          cost(input),\n          Effect.zip(Clock.currentTimeMillis),\n          Effect.map(([weight, currentTimeMillis]) => {\n            const elapsed = currentTimeMillis - timestampMillis\n            const cycles = elapsed / Duration.toMillis(duration)\n            const sum = tokens + (cycles * units)\n            const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst\n            const available = sum < 0 ? max : Math.min(sum, max)\n            if (weight <= available) {\n              return pipe(\n                core.write(input),\n                core.flatMap(() => loop(available - weight, currentTimeMillis))\n              )\n            }\n            return loop(tokens, timestampMillis)\n          }),\n          channel.unwrap\n        ),\n      onFailure: core.failCause,\n      onDone: () => core.void\n    })\n  const throttled = pipe(\n    Clock.currentTimeMillis,\n    Effect.map((currentTimeMillis) => loop(units, currentTimeMillis)),\n    channel.unwrap\n  )\n  return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(throttled)))\n}\n\nconst throttleShapeEffect = <A, E, R, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  costFn: (chunk: Chunk.Chunk<A>) => Effect.Effect<number, E2, R2>,\n  units: number,\n  duration: Duration.DurationInput,\n  burst: number\n): Stream.Stream<A, E | E2, R | R2> => {\n  const loop = (\n    tokens: number,\n    timestampMillis: number\n  ): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, void, unknown, R2> =>\n    core.readWithCause({\n      onInput: (input: Chunk.Chunk<A>) =>\n        pipe(\n          costFn(input),\n          Effect.zip(Clock.currentTimeMillis),\n          Effect.map(([weight, currentTimeMillis]) => {\n            const elapsed = currentTimeMillis - timestampMillis\n            const cycles = elapsed / Duration.toMillis(duration)\n            const sum = tokens + (cycles * units)\n            const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst\n            const available = sum < 0 ? max : Math.min(sum, max)\n            const remaining = available - weight\n            const waitCycles = remaining >= 0 ? 0 : -remaining / units\n            const delay = Duration.millis(Math.max(0, waitCycles * Duration.toMillis(duration)))\n            if (Duration.greaterThan(delay, Duration.zero)) {\n              return pipe(\n                core.fromEffect(Clock.sleep(delay)),\n                channel.zipRight(core.write(input)),\n                core.flatMap(() => loop(remaining, currentTimeMillis))\n              )\n            }\n            return core.flatMap(\n              core.write(input),\n              () => loop(remaining, currentTimeMillis)\n            )\n          }),\n          channel.unwrap\n        ),\n      onFailure: core.failCause,\n      onDone: () => core.void\n    })\n  const throttled = pipe(\n    Clock.currentTimeMillis,\n    Effect.map((currentTimeMillis) => loop(units, currentTimeMillis)),\n    channel.unwrap\n  )\n  return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(throttled)))\n}\n\n/** @internal */\nexport const tick = (interval: Duration.DurationInput): Stream.Stream<void> =>\n  repeatWithSchedule(void 0, Schedule.spaced(interval))\n\n/** @internal */\nexport const timeout = dual<\n  (duration: Duration.DurationInput) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, duration: Duration.DurationInput) => Stream.Stream<A, E, R>\n>(2, <A, E, R>(self: Stream.Stream<A, E, R>, duration: Duration.DurationInput): Stream.Stream<A, E, R> =>\n  pipe(\n    toPull(self),\n    Effect.map(Effect.timeoutFail<Option.Option<E>>({\n      onTimeout: () => Option.none(),\n      duration\n    })),\n    fromPull\n  ))\n\n/** @internal */\nexport const timeoutFail = dual<\n  <E2>(\n    error: LazyArg<E2>,\n    duration: Duration.DurationInput\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R>,\n  <A, E, R, E2>(\n    self: Stream.Stream<A, E, R>,\n    error: LazyArg<E2>,\n    duration: Duration.DurationInput\n  ) => Stream.Stream<A, E2 | E, R>\n>(\n  3,\n  <A, E, R, E2>(\n    self: Stream.Stream<A, E, R>,\n    error: LazyArg<E2>,\n    duration: Duration.DurationInput\n  ): Stream.Stream<A, E | E2, R> => pipe(self, timeoutTo(duration, failSync(error)))\n)\n\n/** @internal */\nexport const timeoutFailCause = dual<\n  <E2>(\n    cause: LazyArg<Cause.Cause<E2>>,\n    duration: Duration.DurationInput\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R>,\n  <A, E, R, E2>(\n    self: Stream.Stream<A, E, R>,\n    cause: LazyArg<Cause.Cause<E2>>,\n    duration: Duration.DurationInput\n  ) => Stream.Stream<A, E2 | E, R>\n>(\n  3,\n  <A, E, R, E2>(\n    self: Stream.Stream<A, E, R>,\n    cause: LazyArg<Cause.Cause<E2>>,\n    duration: Duration.DurationInput\n  ): Stream.Stream<A, E | E2, R> =>\n    pipe(\n      toPull(self),\n      Effect.map(\n        Effect.timeoutFailCause<Option.Option<E | E2>>({\n          onTimeout: () => Cause.map(cause(), Option.some),\n          duration\n        })\n      ),\n      fromPull\n    )\n)\n\n/** @internal */\nexport const timeoutTo = dual<\n  <A2, E2, R2>(\n    duration: Duration.DurationInput,\n    that: Stream.Stream<A2, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2 | A, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    duration: Duration.DurationInput,\n    that: Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<A2 | A, E2 | E, R2 | R>\n>(\n  3,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    duration: Duration.DurationInput,\n    that: Stream.Stream<A2, E2, R2>\n  ): Stream.Stream<A2 | A, E2 | E, R2 | R> => {\n    const StreamTimeout = new Cause.RuntimeException(\"Stream Timeout\")\n    return pipe(\n      self,\n      timeoutFailCause<E | E2>(() => Cause.die(StreamTimeout), duration),\n      catchSomeCause((cause) =>\n        Cause.isDieType(cause) &&\n          Cause.isRuntimeException(cause.defect) &&\n          cause.defect.message !== undefined &&\n          cause.defect.message === \"Stream Timeout\" ?\n          Option.some(that) :\n          Option.none()\n      )\n    )\n  }\n)\n\nconst pubsubFromOptions = <A, E>(\n  options: number | {\n    readonly capacity: \"unbounded\"\n    readonly replay?: number | undefined\n  } | {\n    readonly capacity: number\n    readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n    readonly replay?: number | undefined\n  }\n): Effect.Effect<PubSub.PubSub<Take.Take<A, E>>> => {\n  if (typeof options === \"number\") {\n    return PubSub.bounded(options)\n  } else if (options.capacity === \"unbounded\") {\n    return PubSub.unbounded({ replay: options.replay })\n  }\n  switch (options.strategy) {\n    case \"dropping\":\n      return PubSub.dropping(options)\n    case \"sliding\":\n      return PubSub.sliding(options)\n    default:\n      return PubSub.bounded(options)\n  }\n}\n\n/** @internal */\nexport const toPubSub = dual<\n  (\n    capacity: number | {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<PubSub.PubSub<Take.Take<A, E>>, never, Scope.Scope | R>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    capacity: number | {\n      readonly capacity: \"unbounded\"\n      readonly replay?: number | undefined\n    } | {\n      readonly capacity: number\n      readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n      readonly replay?: number | undefined\n    }\n  ) => Effect.Effect<PubSub.PubSub<Take.Take<A, E>>, never, Scope.Scope | R>\n>(2, <A, E, R>(\n  self: Stream.Stream<A, E, R>,\n  capacity: number | {\n    readonly capacity: \"unbounded\"\n    readonly replay?: number | undefined\n  } | {\n    readonly capacity: number\n    readonly strategy?: \"sliding\" | \"dropping\" | \"suspend\" | undefined\n    readonly replay?: number | undefined\n  }\n): Effect.Effect<PubSub.PubSub<Take.Take<A, E>>, never, Scope.Scope | R> =>\n  pipe(\n    Effect.acquireRelease(pubsubFromOptions<A, E>(capacity), (pubsub) => PubSub.shutdown(pubsub)),\n    Effect.tap((pubsub) => pipe(self, runIntoPubSubScoped(pubsub), Effect.forkScoped))\n  ))\n\n/** @internal */\nexport const toPull = <A, E, R>(\n  self: Stream.Stream<A, E, R>\n): Effect.Effect<Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R>, never, R | Scope.Scope> =>\n  Effect.map(channel.toPull(toChannel(self)), (pull) =>\n    pipe(\n      pull,\n      Effect.mapError(Option.some),\n      Effect.flatMap(Either.match({\n        onLeft: () => Effect.fail(Option.none()),\n        onRight: Effect.succeed\n      }))\n    ))\n\n/** @internal */\nexport const toQueue = dual<\n  (\n    options?: {\n      readonly strategy?: \"suspend\" | \"sliding\" | \"dropping\" | undefined\n      readonly capacity?: number | undefined\n    } | {\n      readonly strategy: \"unbounded\"\n    }\n  ) => <A, E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<Queue.Dequeue<Take.Take<A, E>>, never, R | Scope.Scope>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    options?: {\n      readonly strategy?: \"suspend\" | \"sliding\" | \"dropping\" | undefined\n      readonly capacity?: number | undefined\n    } | {\n      readonly strategy: \"unbounded\"\n    }\n  ) => Effect.Effect<Queue.Dequeue<Take.Take<A, E>>, never, R | Scope.Scope>\n>((args) => isStream(args[0]), <A, E, R>(\n  self: Stream.Stream<A, E, R>,\n  options?: {\n    readonly strategy?: \"suspend\" | \"sliding\" | \"dropping\" | undefined\n    readonly capacity?: number | undefined\n  } | {\n    readonly strategy: \"unbounded\"\n  }\n) =>\n  Effect.tap(\n    Effect.acquireRelease(\n      options?.strategy === \"unbounded\" ?\n        Queue.unbounded<Take.Take<A, E>>() :\n        options?.strategy === \"dropping\" ?\n        Queue.dropping<Take.Take<A, E>>(options.capacity ?? 2) :\n        options?.strategy === \"sliding\" ?\n        Queue.sliding<Take.Take<A, E>>(options.capacity ?? 2) :\n        Queue.bounded<Take.Take<A, E>>(options?.capacity ?? 2),\n      (queue) => Queue.shutdown(queue)\n    ),\n    (queue) => Effect.forkScoped(runIntoQueueScoped(self, queue))\n  ))\n\n/** @internal */\nexport const toQueueOfElements = dual<\n  (options?: {\n    readonly capacity?: number | undefined\n  }) => <A, E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Effect.Effect<Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>, never, R | Scope.Scope>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    options?: {\n      readonly capacity?: number | undefined\n    }\n  ) => Effect.Effect<Queue.Dequeue<Exit.Exit<A, Option.Option<E>>>, never, R | Scope.Scope>\n>((args) => isStream(args[0]), <A, E, R>(\n  self: Stream.Stream<A, E, R>,\n  options?: {\n    readonly capacity?: number | undefined\n  }\n) =>\n  Effect.tap(\n    Effect.acquireRelease(\n      Queue.bounded<Exit.Exit<A, Option.Option<E>>>(options?.capacity ?? 2),\n      (queue) => Queue.shutdown(queue)\n    ),\n    (queue) => Effect.forkScoped(runIntoQueueElementsScoped(self, queue))\n  ))\n\n/** @internal */\nexport const toReadableStream = dual<\n  <A>(\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ) => <E>(self: Stream.Stream<A, E>) => ReadableStream<A>,\n  <A, E>(\n    self: Stream.Stream<A, E>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ) => ReadableStream<A>\n>(\n  (args) => isStream(args[0]),\n  <A, E>(\n    self: Stream.Stream<A, E>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ) => toReadableStreamRuntime(self, Runtime.defaultRuntime, options)\n)\n\n/** @internal */\nexport const toReadableStreamEffect = dual<\n  <A>(\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Effect.Effect<ReadableStream<A>, never, R>,\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ) => Effect.Effect<ReadableStream<A>, never, R>\n>(\n  (args) => isStream(args[0]),\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ) => Effect.map(Effect.runtime<R>(), (runtime) => toReadableStreamRuntime(self, runtime, options))\n)\n\n/** @internal */\nexport const toReadableStreamRuntime = dual<\n  <A, XR>(\n    runtime: Runtime.Runtime<XR>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ) => <E, R extends XR>(self: Stream.Stream<A, E, R>) => ReadableStream<A>,\n  <A, E, XR, R extends XR>(\n    self: Stream.Stream<A, E, R>,\n    runtime: Runtime.Runtime<XR>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ) => ReadableStream<A>\n>(\n  (args) => isStream(args[0]),\n  <A, E, XR, R extends XR>(\n    self: Stream.Stream<A, E, R>,\n    runtime: Runtime.Runtime<XR>,\n    options?: { readonly strategy?: QueuingStrategy<A> | undefined }\n  ): ReadableStream<A> => {\n    const runFork = Runtime.runFork(runtime)\n    let currentResolve: (() => void) | undefined = undefined\n    let fiber: Fiber.RuntimeFiber<void, E> | undefined = undefined\n    const latch = Effect.unsafeMakeLatch(false)\n\n    return new ReadableStream<A>({\n      start(controller) {\n        fiber = runFork(runForEachChunk(self, (chunk) => {\n          if (chunk.length === 0) return Effect.void\n          return latch.whenOpen(Effect.sync(() => {\n            latch.unsafeClose()\n            for (const item of chunk) {\n              controller.enqueue(item)\n            }\n            currentResolve!()\n            currentResolve = undefined\n          }))\n        }))\n        fiber.addObserver((exit) => {\n          try {\n            if (exit._tag === \"Failure\") {\n              controller.error(Cause.squash(exit.cause))\n            } else {\n              controller.close()\n            }\n          } catch {\n            // ignore\n          }\n        })\n      },\n      pull() {\n        return new Promise<void>((resolve) => {\n          currentResolve = resolve\n          Effect.runSync(latch.open)\n        })\n      },\n      cancel() {\n        if (!fiber) return\n        return Effect.runPromise(Effect.asVoid(Fiber.interrupt(fiber)))\n      }\n    }, options?.strategy)\n  }\n)\n\n/** @internal */\nexport const transduce = dual<\n  <A2, A, E2, R2>(\n    sink: Sink.Sink<A2, A, A, E2, R2>\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<A2, A, A, E2, R2>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    sink: Sink.Sink<A2, A, A, E2, R2>\n  ): Stream.Stream<A2, E2 | E, R2 | R> => {\n    const newChannel = core.suspend(() => {\n      const leftovers = { ref: Chunk.empty<Chunk.Chunk<A>>() }\n      const upstreamDone = { ref: false }\n      const buffer: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E, E, unknown, unknown> = core.suspend(\n        () => {\n          const leftover = leftovers.ref\n          if (Chunk.isEmpty(leftover)) {\n            return core.readWith({\n              onInput: (input) => pipe(core.write(input), core.flatMap(() => buffer)),\n              onFailure: core.fail,\n              onDone: core.succeedNow\n            })\n          }\n          leftovers.ref = Chunk.empty<Chunk.Chunk<A>>()\n          return pipe(channel.writeChunk(leftover), core.flatMap(() => buffer))\n        }\n      )\n      const concatAndGet = (chunk: Chunk.Chunk<Chunk.Chunk<A>>): Chunk.Chunk<Chunk.Chunk<A>> => {\n        const leftover = leftovers.ref\n        const concatenated = Chunk.appendAll(leftover, Chunk.filter(chunk, (chunk) => chunk.length !== 0))\n        leftovers.ref = concatenated\n        return concatenated\n      }\n      const upstreamMarker: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E, E, unknown, unknown> = core\n        .readWith({\n          onInput: (input: Chunk.Chunk<A>) => core.flatMap(core.write(input), () => upstreamMarker),\n          onFailure: core.fail,\n          onDone: (done) =>\n            channel.zipRight(\n              core.sync(() => {\n                upstreamDone.ref = true\n              }),\n              core.succeedNow(done)\n            )\n        })\n      const transducer: Channel.Channel<Chunk.Chunk<A2>, Chunk.Chunk<A>, E | E2, never, void, unknown, R | R2> = pipe(\n        sink,\n        sink_.toChannel,\n        core.collectElements,\n        core.flatMap(([leftover, z]) =>\n          pipe(\n            core.succeed([upstreamDone.ref, concatAndGet(leftover)] as const),\n            core.flatMap(([done, newLeftovers]) => {\n              const nextChannel = done && Chunk.isEmpty(newLeftovers) ?\n                core.void :\n                transducer\n              return pipe(core.write(Chunk.of(z)), core.flatMap(() => nextChannel))\n            })\n          )\n        )\n      )\n      return pipe(\n        toChannel(self),\n        core.pipeTo(upstreamMarker),\n        core.pipeTo(buffer),\n        channel.pipeToOrFail(transducer)\n      )\n    })\n    return new StreamImpl(newChannel)\n  }\n)\n\n/** @internal */\nexport const toAsyncIterableRuntime = dual<\n  <A, XR>(\n    runtime: Runtime.Runtime<XR>\n  ) => <E, R extends XR>(self: Stream.Stream<A, E, R>) => AsyncIterable<A>,\n  <A, E, XR, R extends XR>(\n    self: Stream.Stream<A, E, R>,\n    runtime: Runtime.Runtime<XR>\n  ) => AsyncIterable<A>\n>(\n  (args) => isStream(args[0]),\n  <A, E, XR, R extends XR>(\n    self: Stream.Stream<A, E, R>,\n    runtime: Runtime.Runtime<XR>\n  ): AsyncIterable<A> => {\n    const runFork = Runtime.runFork(runtime)\n    return {\n      [Symbol.asyncIterator]() {\n        let currentResolve: ((value: IteratorResult<A>) => void) | undefined = undefined\n        let currentReject: ((reason: any) => void) | undefined = undefined\n        let fiber: Fiber.RuntimeFiber<void, E> | undefined = undefined\n        const latch = Effect.unsafeMakeLatch(false)\n        let returned = false\n        return {\n          next() {\n            if (!fiber) {\n              fiber = runFork(runForEach(self, (value) =>\n                latch.whenOpen(Effect.sync(() => {\n                  latch.unsafeClose()\n                  currentResolve!({ done: false, value })\n                  currentResolve = currentReject = undefined\n                }))))\n              fiber.addObserver((exit) => {\n                if (returned) return\n                fiber = Effect.runFork(latch.whenOpen(Effect.sync(() => {\n                  if (exit._tag === \"Failure\") {\n                    currentReject!(Cause.squash(exit.cause))\n                  } else {\n                    currentResolve!({ done: true, value: void 0 })\n                  }\n                  currentResolve = currentReject = undefined\n                })))\n              })\n            }\n            return new Promise<IteratorResult<A>>((resolve, reject) => {\n              currentResolve = resolve\n              currentReject = reject\n              latch.unsafeOpen()\n            })\n          },\n          return() {\n            returned = true\n            if (!fiber) return Promise.resolve({ done: true, value: void 0 })\n            return Effect.runPromise(Effect.as(Fiber.interrupt(fiber), { done: true, value: void 0 }))\n          }\n        }\n      }\n    }\n  }\n)\n\n/** @internal */\nexport const toAsyncIterable = <A, E>(self: Stream.Stream<A, E>): AsyncIterable<A> =>\n  toAsyncIterableRuntime(self, Runtime.defaultRuntime)\n\n/** @internal */\nexport const toAsyncIterableEffect = <A, E, R>(\n  self: Stream.Stream<A, E, R>\n): Effect.Effect<AsyncIterable<A>, never, R> =>\n  Effect.map(Effect.runtime<R>(), (runtime) => toAsyncIterableRuntime(self, runtime))\n\n/** @internal */\nexport const unfold = <S, A>(s: S, f: (s: S) => Option.Option<readonly [A, S]>): Stream.Stream<A> =>\n  unfoldChunk(s, (s) => pipe(f(s), Option.map(([a, s]) => [Chunk.of(a), s])))\n\n/** @internal */\nexport const unfoldChunk = <S, A>(\n  s: S,\n  f: (s: S) => Option.Option<readonly [Chunk.Chunk<A>, S]>\n): Stream.Stream<A> => {\n  const loop = (s: S): Channel.Channel<Chunk.Chunk<A>, unknown, never, unknown, unknown, unknown> =>\n    Option.match(f(s), {\n      onNone: () => core.void,\n      onSome: ([chunk, s]) => core.flatMap(core.write(chunk), () => loop(s))\n    })\n  return new StreamImpl(core.suspend(() => loop(s)))\n}\n\n/** @internal */\nexport const unfoldChunkEffect = <S, A, E, R>(\n  s: S,\n  f: (s: S) => Effect.Effect<Option.Option<readonly [Chunk.Chunk<A>, S]>, E, R>\n): Stream.Stream<A, E, R> =>\n  suspend(() => {\n    const loop = (s: S): Channel.Channel<Chunk.Chunk<A>, unknown, E, unknown, unknown, unknown, R> =>\n      channel.unwrap(\n        Effect.map(\n          f(s),\n          Option.match({\n            onNone: () => core.void,\n            onSome: ([chunk, s]) => core.flatMap(core.write(chunk), () => loop(s))\n          })\n        )\n      )\n    return new StreamImpl(loop(s))\n  })\n\n/** @internal */\nexport const unfoldEffect = <S, A, E, R>(\n  s: S,\n  f: (s: S) => Effect.Effect<Option.Option<readonly [A, S]>, E, R>\n): Stream.Stream<A, E, R> =>\n  unfoldChunkEffect(s, (s) => pipe(f(s), Effect.map(Option.map(([a, s]) => [Chunk.of(a), s]))))\n\nconst void_: Stream.Stream<void> = succeed(void 0)\nexport {\n  /** @internal */\n  void_ as void\n}\n\n/** @internal */\nexport const unwrap = <A, E2, R2, E, R>(\n  effect: Effect.Effect<Stream.Stream<A, E2, R2>, E, R>\n): Stream.Stream<A, E | E2, R | R2> => flatten(fromEffect(effect))\n\n/** @internal */\nexport const unwrapScoped = <A, E2, R2, E, R>(\n  effect: Effect.Effect<Stream.Stream<A, E2, R2>, E, R>\n): Stream.Stream<A, E | E2, Exclude<R, Scope.Scope> | R2> => flatten(scoped(effect))\n\n/** @internal */\nexport const unwrapScopedWith = <A, E2, R2, E, R>(\n  f: (scope: Scope.Scope) => Effect.Effect<Stream.Stream<A, E2, R2>, E, R>\n): Stream.Stream<A, E | E2, R | R2> => flatten(scopedWith((scope) => f(scope)))\n\n/** @internal */\nexport const updateService = dual<\n  <I, S>(\n    tag: Context.Tag<I, S>,\n    f: (service: Types.NoInfer<S>) => Types.NoInfer<S>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, I | R>,\n  <A, E, R, I, S>(\n    self: Stream.Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    f: (service: Types.NoInfer<S>) => Types.NoInfer<S>\n  ) => Stream.Stream<A, E, I | R>\n>(\n  3,\n  <A, E, R, I, S>(\n    self: Stream.Stream<A, E, R>,\n    tag: Context.Tag<I, S>,\n    f: (service: Types.NoInfer<S>) => Types.NoInfer<S>\n  ): Stream.Stream<A, E, I | R> =>\n    pipe(\n      self,\n      mapInputContext((context) =>\n        pipe(\n          context,\n          Context.add(tag, f(pipe(context, Context.unsafeGet(tag))))\n        )\n      )\n    )\n)\n\n/** @internal */\nexport const when = dual<\n  (test: LazyArg<boolean>) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, R>,\n  <A, E, R>(self: Stream.Stream<A, E, R>, test: LazyArg<boolean>) => Stream.Stream<A, E, R>\n>(\n  2,\n  <A, E, R>(self: Stream.Stream<A, E, R>, test: LazyArg<boolean>): Stream.Stream<A, E, R> =>\n    pipe(self, whenEffect(Effect.sync(test)))\n)\n\n/** @internal */\nexport const whenCase = <A, A2, E, R>(\n  evaluate: LazyArg<A>,\n  pf: (a: A) => Option.Option<Stream.Stream<A2, E, R>>\n) => whenCaseEffect(pf)(Effect.sync(evaluate))\n\n/** @internal */\nexport const whenCaseEffect = dual<\n  <A, A2, E2, R2>(\n    pf: (a: A) => Option.Option<Stream.Stream<A2, E2, R2>>\n  ) => <E, R>(self: Effect.Effect<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    pf: (a: A) => Option.Option<Stream.Stream<A2, E2, R2>>\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Effect.Effect<A, E, R>,\n    pf: (a: A) => Option.Option<Stream.Stream<A2, E2, R2>>\n  ): Stream.Stream<A2, E | E2, R | R2> =>\n    pipe(\n      fromEffect(self),\n      flatMap((a) => pipe(pf(a), Option.getOrElse(() => empty)))\n    )\n)\n\n/** @internal */\nexport const whenEffect = dual<\n  <E2, R2>(\n    effect: Effect.Effect<boolean, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    effect: Effect.Effect<boolean, E2, R2>\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    effect: Effect.Effect<boolean, E2, R2>\n  ): Stream.Stream<A, E | E2, R | R2> => pipe(fromEffect(effect), flatMap((bool) => bool ? self : empty))\n)\n\n/** @internal */\nexport const withSpan: {\n  (\n    name: string,\n    options?: Tracer.SpanOptions\n  ): <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E, Exclude<R, Tracer.ParentSpan>>\n  <A, E, R>(\n    self: Stream.Stream<A, E, R>,\n    name: string,\n    options?: Tracer.SpanOptions\n  ): Stream.Stream<A, E, Exclude<R, Tracer.ParentSpan>>\n} = function() {\n  const dataFirst = typeof arguments[0] !== \"string\"\n  const name = dataFirst ? arguments[1] : arguments[0]\n  const options = InternalTracer.addSpanStackTrace(dataFirst ? arguments[2] : arguments[1])\n  if (dataFirst) {\n    const self = arguments[0]\n    return new StreamImpl(channel.withSpan(toChannel(self), name, options))\n  }\n  return (self: Stream.Stream<any, any, any>) => new StreamImpl(channel.withSpan(toChannel(self), name, options))\n} as any\n\n/** @internal */\nexport const zip = dual<\n  <A2, E2, R2>(\n    that: Stream.Stream<A2, E2, R2>\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<[A, A2], E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<[A, A2], E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ): Stream.Stream<[A, A2], E2 | E, R2 | R> => pipe(self, zipWith(that, (a, a2) => [a, a2]))\n)\n\n/** @internal */\nexport const zipFlatten = dual<\n  <A2, E2, R2>(\n    that: Stream.Stream<A2, E2, R2>\n  ) => <A extends ReadonlyArray<any>, E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Stream.Stream<[...A, A2], E2 | E, R2 | R>,\n  <A extends ReadonlyArray<any>, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ) => Stream.Stream<[...A, A2], E2 | E, R2 | R>\n>(\n  2,\n  <A extends ReadonlyArray<any>, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>\n  ): Stream.Stream<[...A, A2], E2 | E, R2 | R> => pipe(self, zipWith(that, (a, a2) => [...a, a2]))\n)\n\n/** @internal */\nexport const zipAll = dual<\n  <A2, E2, R2, A>(\n    options: {\n      readonly other: Stream.Stream<A2, E2, R2>\n      readonly defaultSelf: A\n      readonly defaultOther: A2\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<[A, A2], E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly other: Stream.Stream<A2, E2, R2>\n      readonly defaultSelf: A\n      readonly defaultOther: A2\n    }\n  ) => Stream.Stream<[A, A2], E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly other: Stream.Stream<A2, E2, R2>\n      readonly defaultSelf: A\n      readonly defaultOther: A2\n    }\n  ): Stream.Stream<[A, A2], E2 | E, R2 | R> =>\n    zipAllWith(self, {\n      other: options.other,\n      onSelf: (a) => [a, options.defaultOther],\n      onOther: (a2) => [options.defaultSelf, a2],\n      onBoth: (a, a2) => [a, a2]\n    })\n)\n\n/** @internal */\nexport const zipAllLeft = dual<\n  <A2, E2, R2, A>(\n    that: Stream.Stream<A2, E2, R2>,\n    defaultLeft: A\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>,\n    defaultLeft: A\n  ) => Stream.Stream<A, E2 | E, R2 | R>\n>(\n  3,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    other: Stream.Stream<A2, E2, R2>,\n    defaultSelf: A\n  ): Stream.Stream<A, E | E2, R | R2> =>\n    zipAllWith(self, {\n      other,\n      onSelf: identity,\n      onOther: () => defaultSelf,\n      onBoth: (a) => a\n    })\n)\n\n/** @internal */\nexport const zipAllRight = dual<\n  <A2, E2, R2>(\n    that: Stream.Stream<A2, E2, R2>,\n    defaultRight: A2\n  ) => <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A2, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>,\n    defaultRight: A2\n  ) => Stream.Stream<A2, E2 | E, R2 | R>\n>(\n  3,\n  <A, E, R, A2, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    other: Stream.Stream<A2, E2, R2>,\n    defaultRight: A2\n  ): Stream.Stream<A2, E | E2, R | R2> =>\n    zipAllWith(self, {\n      other,\n      onSelf: () => defaultRight,\n      onOther: identity,\n      onBoth: (_, a2) => a2\n    })\n)\n\n/** @internal */\nexport const zipAllSortedByKey = dual<\n  <A2, E2, R2, A, K>(\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly defaultSelf: A\n      readonly defaultOther: A2\n      readonly order: Order.Order<K>\n    }\n  ) => <E, R>(\n    self: Stream.Stream<readonly [K, A], E, R>\n  ) => Stream.Stream<[K, [A, A2]], E2 | E, R2 | R>,\n  <K, A, E, R, A2, E2, R2>(\n    self: Stream.Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly defaultSelf: A\n      readonly defaultOther: A2\n      readonly order: Order.Order<K>\n    }\n  ) => Stream.Stream<[K, [A, A2]], E2 | E, R2 | R>\n>(\n  2,\n  <K, A, E, R, A2, E2, R2>(\n    self: Stream.Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly defaultSelf: A\n      readonly defaultOther: A2\n      readonly order: Order.Order<K>\n    }\n  ): Stream.Stream<[K, [A, A2]], E2 | E, R2 | R> =>\n    zipAllSortedByKeyWith(self, {\n      other: options.other,\n      onSelf: (a) => [a, options.defaultOther],\n      onOther: (a2) => [options.defaultSelf, a2],\n      onBoth: (a, a2) => [a, a2],\n      order: options.order\n    })\n)\n\n/** @internal */\nexport const zipAllSortedByKeyLeft = dual<\n  <A2, E2, R2, A, K>(\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly defaultSelf: A\n      readonly order: Order.Order<K>\n    }\n  ) => <E, R>(self: Stream.Stream<readonly [K, A], E, R>) => Stream.Stream<[K, A], E2 | E, R2 | R>,\n  <K, A, E, R, A2, E2, R2>(\n    self: Stream.Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly defaultSelf: A\n      readonly order: Order.Order<K>\n    }\n  ) => Stream.Stream<[K, A], E2 | E, R2 | R>\n>(\n  2,\n  <K, A, E, R, A2, E2, R2>(\n    self: Stream.Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly defaultSelf: A\n      readonly order: Order.Order<K>\n    }\n  ): Stream.Stream<[K, A], E2 | E, R2 | R> =>\n    zipAllSortedByKeyWith(self, {\n      other: options.other,\n      onSelf: identity,\n      onOther: () => options.defaultSelf,\n      onBoth: (a) => a,\n      order: options.order\n    })\n)\n\n/** @internal */\nexport const zipAllSortedByKeyRight = dual<\n  <K, A2, E2, R2>(\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly defaultOther: A2\n      readonly order: Order.Order<K>\n    }\n  ) => <A, E, R>(self: Stream.Stream<readonly [K, A], E, R>) => Stream.Stream<[K, A2], E2 | E, R2 | R>,\n  <A, E, R, K, A2, E2, R2>(\n    self: Stream.Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly defaultOther: A2\n      readonly order: Order.Order<K>\n    }\n  ) => Stream.Stream<[K, A2], E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, K, A2, E2, R2>(\n    self: Stream.Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly defaultOther: A2\n      readonly order: Order.Order<K>\n    }\n  ): Stream.Stream<[K, A2], E2 | E, R2 | R> =>\n    zipAllSortedByKeyWith(self, {\n      other: options.other,\n      onSelf: () => options.defaultOther,\n      onOther: identity,\n      onBoth: (_, a2) => a2,\n      order: options.order\n    })\n)\n\n/** @internal */\nexport const zipAllSortedByKeyWith = dual<\n  <K, A2, E2, R2, A, A3>(\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A3\n      readonly onBoth: (a: A, a2: A2) => A3\n      readonly order: Order.Order<K>\n    }\n  ) => <E, R>(self: Stream.Stream<readonly [K, A], E, R>) => Stream.Stream<[K, A3], E2 | E, R2 | R>,\n  <K, A, E, R, A2, E2, R2, A3>(\n    self: Stream.Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A3\n      readonly onBoth: (a: A, a2: A2) => A3\n      readonly order: Order.Order<K>\n    }\n  ) => Stream.Stream<[K, A3], E2 | E, R2 | R>\n>(\n  2,\n  <K, A, E, R, A2, E2, R2, A3>(\n    self: Stream.Stream<readonly [K, A], E, R>,\n    options: {\n      readonly other: Stream.Stream<readonly [K, A2], E2, R2>\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A3\n      readonly onBoth: (a: A, a2: A2) => A3\n      readonly order: Order.Order<K>\n    }\n  ): Stream.Stream<[K, A3], E2 | E, R2 | R> => {\n    const pull = (\n      state: ZipAllState.ZipAllState<readonly [K, A], readonly [K, A2]>,\n      pullLeft: Effect.Effect<Chunk.Chunk<readonly [K, A]>, Option.Option<E>, R>,\n      pullRight: Effect.Effect<Chunk.Chunk<readonly [K, A2]>, Option.Option<E2>, R2>\n    ): Effect.Effect<\n      Exit.Exit<\n        readonly [\n          Chunk.Chunk<[K, A3]>,\n          ZipAllState.ZipAllState<readonly [K, A], readonly [K, A2]>\n        ],\n        Option.Option<E | E2>\n      >,\n      never,\n      R | R2\n    > => {\n      switch (state._tag) {\n        case ZipAllState.OP_DRAIN_LEFT: {\n          return pipe(\n            pullLeft,\n            Effect.match({\n              onFailure: Exit.fail,\n              onSuccess: (leftChunk) =>\n                Exit.succeed(\n                  [\n                    Chunk.map(leftChunk, ([k, a]) => [k, options.onSelf(a)]),\n                    ZipAllState.DrainLeft\n                  ] as const\n                )\n            })\n          )\n        }\n        case ZipAllState.OP_DRAIN_RIGHT: {\n          return pipe(\n            pullRight,\n            Effect.match({\n              onFailure: Exit.fail,\n              onSuccess: (rightChunk) =>\n                Exit.succeed(\n                  [\n                    Chunk.map(rightChunk, ([k, a2]) => [k, options.onOther(a2)]),\n                    ZipAllState.DrainRight\n                  ] as const\n                )\n            })\n          )\n        }\n        case ZipAllState.OP_PULL_BOTH: {\n          return pipe(\n            unsome(pullLeft),\n            Effect.zip(unsome(pullRight), { concurrent: true }),\n            Effect.matchEffect({\n              onFailure: (error) => Effect.succeed(Exit.fail(Option.some(error))),\n              onSuccess: ([leftOption, rightOption]) => {\n                if (Option.isSome(leftOption) && Option.isSome(rightOption)) {\n                  if (Chunk.isEmpty(leftOption.value) && Chunk.isEmpty(rightOption.value)) {\n                    return pull(ZipAllState.PullBoth, pullLeft, pullRight)\n                  }\n                  if (Chunk.isEmpty(leftOption.value)) {\n                    return pull(ZipAllState.PullLeft(rightOption.value), pullLeft, pullRight)\n                  }\n                  if (Chunk.isEmpty(rightOption.value)) {\n                    return pull(ZipAllState.PullRight(leftOption.value), pullLeft, pullRight)\n                  }\n                  return Effect.succeed(Exit.succeed(merge(leftOption.value, rightOption.value)))\n                }\n                if (Option.isSome(leftOption) && Option.isNone(rightOption)) {\n                  if (Chunk.isEmpty(leftOption.value)) {\n                    return pull(ZipAllState.DrainLeft, pullLeft, pullRight)\n                  }\n                  return Effect.succeed(\n                    Exit.succeed(\n                      [\n                        pipe(leftOption.value, Chunk.map(([k, a]) => [k, options.onSelf(a)])),\n                        ZipAllState.DrainLeft\n                      ] as const\n                    )\n                  )\n                }\n                if (Option.isNone(leftOption) && Option.isSome(rightOption)) {\n                  if (Chunk.isEmpty(rightOption.value)) {\n                    return pull(ZipAllState.DrainRight, pullLeft, pullRight)\n                  }\n                  return Effect.succeed(\n                    Exit.succeed(\n                      [\n                        pipe(rightOption.value, Chunk.map(([k, a2]) => [k, options.onOther(a2)])),\n                        ZipAllState.DrainRight\n                      ] as const\n                    )\n                  )\n                }\n                return Effect.succeed(Exit.fail<Option.Option<E | E2>>(Option.none()))\n              }\n            })\n          )\n        }\n        case ZipAllState.OP_PULL_LEFT: {\n          return Effect.matchEffect(pullLeft, {\n            onFailure: Option.match({\n              onNone: () =>\n                Effect.succeed(\n                  Exit.succeed([\n                    pipe(state.rightChunk, Chunk.map(([k, a2]) => [k, options.onOther(a2)])),\n                    ZipAllState.DrainRight\n                  ])\n                ),\n              onSome: (error) =>\n                Effect.succeed<\n                  Exit.Exit<\n                    readonly [\n                      Chunk.Chunk<[K, A3]>,\n                      ZipAllState.ZipAllState<readonly [K, A], readonly [K, A2]>\n                    ],\n                    Option.Option<E | E2>\n                  >\n                >(Exit.fail(Option.some(error)))\n            }),\n            onSuccess: (leftChunk) =>\n              Chunk.isEmpty(leftChunk) ?\n                pull(ZipAllState.PullLeft(state.rightChunk), pullLeft, pullRight) :\n                Effect.succeed(Exit.succeed(merge(leftChunk, state.rightChunk)))\n          })\n        }\n        case ZipAllState.OP_PULL_RIGHT: {\n          return Effect.matchEffect(pullRight, {\n            onFailure: Option.match({\n              onNone: () =>\n                Effect.succeed(\n                  Exit.succeed(\n                    [\n                      Chunk.map(state.leftChunk, ([k, a]) => [k, options.onSelf(a)]),\n                      ZipAllState.DrainLeft\n                    ] as const\n                  )\n                ),\n              onSome: (error) =>\n                Effect.succeed<\n                  Exit.Exit<\n                    readonly [\n                      Chunk.Chunk<[K, A3]>,\n                      ZipAllState.ZipAllState<readonly [K, A], readonly [K, A2]>\n                    ],\n                    Option.Option<E | E2>\n                  >\n                >(Exit.fail(Option.some(error)))\n            }),\n            onSuccess: (rightChunk) =>\n              Chunk.isEmpty(rightChunk) ?\n                pull(ZipAllState.PullRight(state.leftChunk), pullLeft, pullRight) :\n                Effect.succeed(Exit.succeed(merge(state.leftChunk, rightChunk)))\n          })\n        }\n      }\n    }\n    const merge = (\n      leftChunk: Chunk.Chunk<readonly [K, A]>,\n      rightChunk: Chunk.Chunk<readonly [K, A2]>\n    ): readonly [\n      Chunk.Chunk<[K, A3]>,\n      ZipAllState.ZipAllState<readonly [K, A], readonly [K, A2]>\n    ] => {\n      const hasNext = <T>(chunk: Chunk.Chunk<T>, index: number) => index < chunk.length - 1\n      const builder: Array<[K, A3]> = []\n      let state:\n        | ZipAllState.ZipAllState<\n          readonly [K, A],\n          readonly [K, A2]\n        >\n        | undefined = undefined\n      let leftIndex = 0\n      let rightIndex = 0\n      let leftTuple = pipe(leftChunk, Chunk.unsafeGet(leftIndex))\n      let rightTuple = pipe(rightChunk, Chunk.unsafeGet(rightIndex))\n      let k1 = leftTuple[0]\n      let a = leftTuple[1]\n      let k2 = rightTuple[0]\n      let a2 = rightTuple[1]\n      let loop = true\n      while (loop) {\n        const compare = options.order(k1, k2)\n        if (compare === 0) {\n          builder.push([k1, options.onBoth(a, a2)])\n          if (hasNext(leftChunk, leftIndex) && hasNext(rightChunk, rightIndex)) {\n            leftIndex = leftIndex + 1\n            rightIndex = rightIndex + 1\n            leftTuple = pipe(leftChunk, Chunk.unsafeGet(leftIndex))\n            rightTuple = pipe(rightChunk, Chunk.unsafeGet(rightIndex))\n            k1 = leftTuple[0]\n            a = leftTuple[1]\n            k2 = rightTuple[0]\n            a2 = rightTuple[1]\n          } else if (hasNext(leftChunk, leftIndex)) {\n            state = ZipAllState.PullRight(pipe(leftChunk, Chunk.drop(leftIndex + 1)))\n            loop = false\n          } else if (hasNext(rightChunk, rightIndex)) {\n            state = ZipAllState.PullLeft(pipe(rightChunk, Chunk.drop(rightIndex + 1)))\n            loop = false\n          } else {\n            state = ZipAllState.PullBoth\n            loop = false\n          }\n        } else if (compare < 0) {\n          builder.push([k1, options.onSelf(a)])\n          if (hasNext(leftChunk, leftIndex)) {\n            leftIndex = leftIndex + 1\n            leftTuple = pipe(leftChunk, Chunk.unsafeGet(leftIndex))\n            k1 = leftTuple[0]\n            a = leftTuple[1]\n          } else {\n            const rightBuilder: Array<readonly [K, A2]> = []\n            rightBuilder.push(rightTuple)\n            while (hasNext(rightChunk, rightIndex)) {\n              rightIndex = rightIndex + 1\n              rightTuple = pipe(rightChunk, Chunk.unsafeGet(rightIndex))\n              rightBuilder.push(rightTuple)\n            }\n            state = ZipAllState.PullLeft(Chunk.unsafeFromArray(rightBuilder))\n            loop = false\n          }\n        } else {\n          builder.push([k2, options.onOther(a2)])\n          if (hasNext(rightChunk, rightIndex)) {\n            rightIndex = rightIndex + 1\n            rightTuple = pipe(rightChunk, Chunk.unsafeGet(rightIndex))\n            k2 = rightTuple[0]\n            a2 = rightTuple[1]\n          } else {\n            const leftBuilder: Array<readonly [K, A]> = []\n            leftBuilder.push(leftTuple)\n            while (hasNext(leftChunk, leftIndex)) {\n              leftIndex = leftIndex + 1\n              leftTuple = pipe(leftChunk, Chunk.unsafeGet(leftIndex))\n              leftBuilder.push(leftTuple)\n            }\n            state = ZipAllState.PullRight(Chunk.unsafeFromArray(leftBuilder))\n            loop = false\n          }\n        }\n      }\n      return [Chunk.unsafeFromArray(builder), state!]\n    }\n    return combineChunks(self, options.other, ZipAllState.PullBoth, pull)\n  }\n)\n\n/** @internal */\nexport const zipAllWith = dual<\n  <A2, E2, R2, A, A3>(\n    options: {\n      readonly other: Stream.Stream<A2, E2, R2>\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A3\n      readonly onBoth: (a: A, a2: A2) => A3\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A3, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2, A3>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly other: Stream.Stream<A2, E2, R2>\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A3\n      readonly onBoth: (a: A, a2: A2) => A3\n    }\n  ) => Stream.Stream<A3, E2 | E, R2 | R>\n>(\n  2,\n  <A, E, R, A2, E2, R2, A3>(\n    self: Stream.Stream<A, E, R>,\n    options: {\n      readonly other: Stream.Stream<A2, E2, R2>\n      readonly onSelf: (a: A) => A3\n      readonly onOther: (a2: A2) => A3\n      readonly onBoth: (a: A, a2: A2) => A3\n    }\n  ): Stream.Stream<A3, E2 | E, R2 | R> => {\n    const pull = (\n      state: ZipAllState.ZipAllState<A, A2>,\n      pullLeft: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R>,\n      pullRight: Effect.Effect<Chunk.Chunk<A2>, Option.Option<E2>, R2>\n    ): Effect.Effect<\n      Exit.Exit<readonly [Chunk.Chunk<A3>, ZipAllState.ZipAllState<A, A2>], Option.Option<E | E2>>,\n      never,\n      R | R2\n    > => {\n      switch (state._tag) {\n        case ZipAllState.OP_DRAIN_LEFT: {\n          return Effect.matchEffect(pullLeft, {\n            onFailure: (error) => Effect.succeed(Exit.fail(error)),\n            onSuccess: (leftChunk) =>\n              Effect.succeed(Exit.succeed(\n                [\n                  Chunk.map(leftChunk, options.onSelf),\n                  ZipAllState.DrainLeft\n                ] as const\n              ))\n          })\n        }\n        case ZipAllState.OP_DRAIN_RIGHT: {\n          return Effect.matchEffect(pullRight, {\n            onFailure: (error) => Effect.succeed(Exit.fail(error)),\n            onSuccess: (rightChunk) =>\n              Effect.succeed(Exit.succeed(\n                [\n                  Chunk.map(rightChunk, options.onOther),\n                  ZipAllState.DrainRight\n                ] as const\n              ))\n          })\n        }\n        case ZipAllState.OP_PULL_BOTH: {\n          return pipe(\n            unsome(pullLeft),\n            Effect.zip(unsome(pullRight), { concurrent: true }),\n            Effect.matchEffect({\n              onFailure: (error) => Effect.succeed(Exit.fail(Option.some(error))),\n              onSuccess: ([leftOption, rightOption]) => {\n                if (Option.isSome(leftOption) && Option.isSome(rightOption)) {\n                  if (Chunk.isEmpty(leftOption.value) && Chunk.isEmpty(rightOption.value)) {\n                    return pull(ZipAllState.PullBoth, pullLeft, pullRight)\n                  }\n                  if (Chunk.isEmpty(leftOption.value)) {\n                    return pull(ZipAllState.PullLeft(rightOption.value), pullLeft, pullRight)\n                  }\n                  if (Chunk.isEmpty(rightOption.value)) {\n                    return pull(ZipAllState.PullRight(leftOption.value), pullLeft, pullRight)\n                  }\n                  return Effect.succeed(Exit.succeed(zip(leftOption.value, rightOption.value, options.onBoth)))\n                }\n                if (Option.isSome(leftOption) && Option.isNone(rightOption)) {\n                  return Effect.succeed(Exit.succeed(\n                    [\n                      Chunk.map(leftOption.value, options.onSelf),\n                      ZipAllState.DrainLeft\n                    ] as const\n                  ))\n                }\n                if (Option.isNone(leftOption) && Option.isSome(rightOption)) {\n                  return Effect.succeed(Exit.succeed(\n                    [\n                      Chunk.map(rightOption.value, options.onOther),\n                      ZipAllState.DrainRight\n                    ] as const\n                  ))\n                }\n                return Effect.succeed(Exit.fail<Option.Option<E | E2>>(Option.none()))\n              }\n            })\n          )\n        }\n        case ZipAllState.OP_PULL_LEFT: {\n          return Effect.matchEffect(pullLeft, {\n            onFailure: Option.match({\n              onNone: () =>\n                Effect.succeed(Exit.succeed(\n                  [\n                    Chunk.map(state.rightChunk, options.onOther),\n                    ZipAllState.DrainRight\n                  ] as const\n                )),\n              onSome: (error) =>\n                Effect.succeed<\n                  Exit.Exit<readonly [Chunk.Chunk<A3>, ZipAllState.ZipAllState<A, A2>], Option.Option<E | E2>>\n                >(\n                  Exit.fail(Option.some(error))\n                )\n            }),\n            onSuccess: (leftChunk) => {\n              if (Chunk.isEmpty(leftChunk)) {\n                return pull(ZipAllState.PullLeft(state.rightChunk), pullLeft, pullRight)\n              }\n              if (Chunk.isEmpty(state.rightChunk)) {\n                return pull(ZipAllState.PullRight(leftChunk), pullLeft, pullRight)\n              }\n              return Effect.succeed(Exit.succeed(zip(leftChunk, state.rightChunk, options.onBoth)))\n            }\n          })\n        }\n        case ZipAllState.OP_PULL_RIGHT: {\n          return Effect.matchEffect(pullRight, {\n            onFailure: Option.match({\n              onNone: () =>\n                Effect.succeed(\n                  Exit.succeed(\n                    [\n                      Chunk.map(state.leftChunk, options.onSelf),\n                      ZipAllState.DrainLeft\n                    ] as const\n                  )\n                ),\n              onSome: (error) =>\n                Effect.succeed<\n                  Exit.Exit<readonly [Chunk.Chunk<A3>, ZipAllState.ZipAllState<A, A2>], Option.Option<E | E2>>\n                >(\n                  Exit.fail(Option.some(error))\n                )\n            }),\n            onSuccess: (rightChunk) => {\n              if (Chunk.isEmpty(rightChunk)) {\n                return pull(\n                  ZipAllState.PullRight(state.leftChunk),\n                  pullLeft,\n                  pullRight\n                )\n              }\n              if (Chunk.isEmpty(state.leftChunk)) {\n                return pull(\n                  ZipAllState.PullLeft(rightChunk),\n                  pullLeft,\n                  pullRight\n                )\n              }\n              return Effect.succeed(Exit.succeed(zip(state.leftChunk, rightChunk, options.onBoth)))\n            }\n          })\n        }\n      }\n    }\n    const zip = (\n      leftChunk: Chunk.Chunk<A>,\n      rightChunk: Chunk.Chunk<A2>,\n      f: (a: A, a2: A2) => A3\n    ): readonly [Chunk.Chunk<A3>, ZipAllState.ZipAllState<A, A2>] => {\n      const [output, either] = zipChunks(leftChunk, rightChunk, f)\n      switch (either._tag) {\n        case \"Left\": {\n          if (Chunk.isEmpty(either.left)) {\n            return [output, ZipAllState.PullBoth] as const\n          }\n          return [output, ZipAllState.PullRight(either.left)] as const\n        }\n        case \"Right\": {\n          if (Chunk.isEmpty(either.right)) {\n            return [output, ZipAllState.PullBoth] as const\n          }\n          return [output, ZipAllState.PullLeft(either.right)] as const\n        }\n      }\n    }\n    return combineChunks(self, options.other, ZipAllState.PullBoth, pull)\n  }\n)\n\n/** @internal */\nexport const zipLatest: {\n  <AR, ER, RR>(\n    right: Stream.Stream<AR, ER, RR>\n  ): <AL, EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<[AL, AR], EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<[AL, AR], EL | ER, RL | RR>\n} = dual(\n  2,\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<[AL, AR], EL | ER, RL | RR> => pipe(left, zipLatestWith(right, (a, a2) => [a, a2]))\n)\n\nexport const zipLatestAll = <T extends ReadonlyArray<Stream.Stream<any, any, any>>>(\n  ...streams: T\n): Stream.Stream<\n  [T[number]] extends [never] ? never\n    : { [K in keyof T]: T[K] extends Stream.Stream<infer A, infer _E, infer _R> ? A : never },\n  [T[number]] extends [never] ? never : T[number] extends Stream.Stream<infer _A, infer _E, infer _R> ? _E : never,\n  [T[number]] extends [never] ? never : T[number] extends Stream.Stream<infer _A, infer _E, infer _R> ? _R : never\n> => {\n  if (streams.length === 0) {\n    return empty\n  } else if (streams.length === 1) {\n    return map(streams[0]!, (x) => [x]) as any\n  }\n  const [head, ...tail] = streams\n  return zipLatestWith(\n    head,\n    zipLatestAll(...tail),\n    (first, second) => [first, ...second]\n  ) as any\n}\n\n/** @internal */\nexport const zipLatestWith: {\n  <AR, ER, RR, AL, A>(\n    right: Stream.Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): <EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<A, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR, A>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): Stream.Stream<A, EL | ER, RL | RR>\n} = dual(\n  3,\n  <AL, EL, RL, AR, ER, RR, A>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): Stream.Stream<A, EL | ER, RL | RR> => {\n    const pullNonEmpty = <_R, _E, _A>(\n      pull: Effect.Effect<Chunk.Chunk<_A>, Option.Option<_E>, _R>\n    ): Effect.Effect<Chunk.Chunk<_A>, Option.Option<_E>, _R> =>\n      pipe(pull, Effect.flatMap((chunk) => Chunk.isEmpty(chunk) ? pullNonEmpty(pull) : Effect.succeed(chunk)))\n    return pipe(\n      toPull(left),\n      Effect.map(pullNonEmpty),\n      Effect.zip(pipe(toPull(right), Effect.map(pullNonEmpty))),\n      Effect.flatMap(([left, right]) =>\n        pipe(\n          fromEffectOption<readonly [Chunk.Chunk<AL>, Chunk.Chunk<AR>, boolean], EL | ER, RL | RR>(\n            Effect.raceWith(left, right, {\n              onSelfDone: (leftDone, rightFiber) =>\n                pipe(\n                  Effect.suspend(() => leftDone),\n                  Effect.zipWith(Fiber.join(rightFiber), (l, r) => [l, r, true] as const)\n                ),\n              onOtherDone: (rightDone, leftFiber) =>\n                pipe(\n                  Effect.suspend(() => rightDone),\n                  Effect.zipWith(Fiber.join(leftFiber), (l, r) => [r, l, false] as const)\n                )\n            })\n          ),\n          flatMap(([l, r, leftFirst]) =>\n            pipe(\n              fromEffect(\n                Ref.make([Chunk.unsafeLast(l), Chunk.unsafeLast(r)] as const)\n              ),\n              flatMap((latest) =>\n                pipe(\n                  fromChunk(\n                    leftFirst ?\n                      pipe(r, Chunk.map((a2) => f(Chunk.unsafeLast(l), a2))) :\n                      pipe(l, Chunk.map((a) => f(a, Chunk.unsafeLast(r))))\n                  ),\n                  concat(\n                    pipe(\n                      repeatEffectOption(left),\n                      mergeEither(repeatEffectOption(right)),\n                      mapEffectSequential(Either.match({\n                        onLeft: (leftChunk) =>\n                          Ref.modify(latest, ([_, rightLatest]) =>\n                            [\n                              pipe(leftChunk, Chunk.map((a) => f(a, rightLatest))),\n                              [Chunk.unsafeLast(leftChunk), rightLatest] as const\n                            ] as const),\n                        onRight: (rightChunk) =>\n                          Ref.modify(latest, ([leftLatest, _]) =>\n                            [\n                              pipe(rightChunk, Chunk.map((a2) => f(leftLatest, a2))),\n                              [leftLatest, Chunk.unsafeLast(rightChunk)] as const\n                            ] as const)\n                      })),\n                      flatMap(fromChunk)\n                    )\n                  )\n                )\n              )\n            )\n          ),\n          toPull\n        )\n      ),\n      fromPull\n    )\n  }\n)\n\n/** @internal */\nexport const zipLeft: {\n  <AR, ER, RR>(\n    right: Stream.Stream<AR, ER, RR>\n  ): <AL, EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<AL, ER | EL, RR | RL>\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AL, EL | ER, RL | RR>\n} = dual(\n  2,\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AL, EL | ER, RL | RR> =>\n    pipe(\n      left,\n      zipWithChunks(right, (left, right) => {\n        if (left.length > right.length) {\n          return [\n            pipe(left, Chunk.take(right.length)),\n            Either.left(pipe(left, Chunk.take(right.length)))\n          ] as const\n        }\n        return [\n          left,\n          Either.right(pipe(right, Chunk.drop(left.length)))\n        ]\n      })\n    )\n)\n\n/** @internal */\nexport const zipRight: {\n  <AR, ER, RR>(\n    right: Stream.Stream<AR, ER, RR>\n  ): <AL, EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<AR, ER | EL, RR | RL>\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AR, EL | ER, RL | RR>\n} = dual(\n  2,\n  <AL, EL, RL, AR, ER, RR>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>\n  ): Stream.Stream<AR, EL | ER, RL | RR> =>\n    pipe(\n      left,\n      zipWithChunks(right, (left, right) => {\n        if (left.length > right.length) {\n          return [\n            right,\n            Either.left(pipe(left, Chunk.take(right.length)))\n          ] as const\n        }\n        return [\n          pipe(right, Chunk.take(left.length)),\n          Either.right(pipe(right, Chunk.drop(left.length)))\n        ]\n      })\n    )\n)\n\n/** @internal */\nexport const zipWith: {\n  <AR, ER, RR, AL, A>(\n    right: Stream.Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): <EL, RL>(left: Stream.Stream<AL, EL, RL>) => Stream.Stream<A, EL | ER, RL | RR>\n  <AL, EL, RL, AR, ER, RR, A>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): Stream.Stream<A, EL | ER, RL | RR>\n} = dual(\n  3,\n  <AL, EL, RL, AR, ER, RR, A>(\n    left: Stream.Stream<AL, EL, RL>,\n    right: Stream.Stream<AR, ER, RR>,\n    f: (left: AL, right: AR) => A\n  ): Stream.Stream<A, EL | ER, RL | RR> =>\n    pipe(left, zipWithChunks(right, (leftChunk, rightChunk) => zipChunks(leftChunk, rightChunk, f)))\n)\n\n/** @internal */\nexport const zipWithChunks = dual<\n  <A2, E2, R2, A, A3>(\n    that: Stream.Stream<A2, E2, R2>,\n    f: (\n      left: Chunk.Chunk<A>,\n      right: Chunk.Chunk<A2>\n    ) => readonly [Chunk.Chunk<A3>, Either.Either<Chunk.Chunk<A2>, Chunk.Chunk<A>>]\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<A3, E2 | E, R2 | R>,\n  <A, E, R, A2, E2, R2, A3>(\n    self: Stream.Stream<A, E, R>,\n    that: Stream.Stream<A2, E2, R2>,\n    f: (\n      left: Chunk.Chunk<A>,\n      right: Chunk.Chunk<A2>\n    ) => readonly [Chunk.Chunk<A3>, Either.Either<Chunk.Chunk<A2>, Chunk.Chunk<A>>]\n  ) => Stream.Stream<A3, E2 | E, R2 | R>\n>(3, <A, E, R, A2, E2, R2, A3>(\n  self: Stream.Stream<A, E, R>,\n  that: Stream.Stream<A2, E2, R2>,\n  f: (\n    left: Chunk.Chunk<A>,\n    right: Chunk.Chunk<A2>\n  ) => readonly [Chunk.Chunk<A3>, Either.Either<Chunk.Chunk<A2>, Chunk.Chunk<A>>]\n): Stream.Stream<A3, E2 | E, R2 | R> => {\n  const pull = (\n    state: ZipChunksState.ZipChunksState<A, A2>,\n    pullLeft: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R>,\n    pullRight: Effect.Effect<Chunk.Chunk<A2>, Option.Option<E2>, R2>\n  ): Effect.Effect<\n    Exit.Exit<readonly [Chunk.Chunk<A3>, ZipChunksState.ZipChunksState<A, A2>], Option.Option<E | E2>>,\n    never,\n    R | R2\n  > => {\n    switch (state._tag) {\n      case ZipChunksState.OP_PULL_BOTH: {\n        return pipe(\n          unsome(pullLeft),\n          Effect.zip(unsome(pullRight), { concurrent: true }),\n          Effect.matchEffect({\n            onFailure: (error) => Effect.succeed(Exit.fail(Option.some(error))),\n            onSuccess: ([leftOption, rightOption]) => {\n              if (Option.isSome(leftOption) && Option.isSome(rightOption)) {\n                if (Chunk.isEmpty(leftOption.value) && Chunk.isEmpty(rightOption.value)) {\n                  return pull(ZipChunksState.PullBoth, pullLeft, pullRight)\n                }\n                if (Chunk.isEmpty(leftOption.value)) {\n                  return pull(ZipChunksState.PullLeft(rightOption.value), pullLeft, pullRight)\n                }\n                if (Chunk.isEmpty(rightOption.value)) {\n                  return pull(ZipChunksState.PullRight(leftOption.value), pullLeft, pullRight)\n                }\n                return Effect.succeed(Exit.succeed(zip(leftOption.value, rightOption.value)))\n              }\n              return Effect.succeed(Exit.fail(Option.none()))\n            }\n          })\n        )\n      }\n      case ZipChunksState.OP_PULL_LEFT: {\n        return Effect.matchEffect(pullLeft, {\n          onFailure: (error) => Effect.succeed(Exit.fail(error)),\n          onSuccess: (leftChunk) => {\n            if (Chunk.isEmpty(leftChunk)) {\n              return pull(ZipChunksState.PullLeft(state.rightChunk), pullLeft, pullRight)\n            }\n            if (Chunk.isEmpty(state.rightChunk)) {\n              return pull(ZipChunksState.PullRight(leftChunk), pullLeft, pullRight)\n            }\n            return Effect.succeed(Exit.succeed(zip(leftChunk, state.rightChunk)))\n          }\n        })\n      }\n      case ZipChunksState.OP_PULL_RIGHT: {\n        return Effect.matchEffect(pullRight, {\n          onFailure: (error) => Effect.succeed(Exit.fail(error)),\n          onSuccess: (rightChunk) => {\n            if (Chunk.isEmpty(rightChunk)) {\n              return pull(ZipChunksState.PullRight(state.leftChunk), pullLeft, pullRight)\n            }\n            if (Chunk.isEmpty(state.leftChunk)) {\n              return pull(ZipChunksState.PullLeft(rightChunk), pullLeft, pullRight)\n            }\n            return Effect.succeed(Exit.succeed(zip(state.leftChunk, rightChunk)))\n          }\n        })\n      }\n    }\n  }\n  const zip = (\n    leftChunk: Chunk.Chunk<A>,\n    rightChunk: Chunk.Chunk<A2>\n  ): readonly [Chunk.Chunk<A3>, ZipChunksState.ZipChunksState<A, A2>] => {\n    const [output, either] = f(leftChunk, rightChunk)\n    switch (either._tag) {\n      case \"Left\": {\n        if (Chunk.isEmpty(either.left)) {\n          return [output, ZipChunksState.PullBoth] as const\n        }\n        return [output, ZipChunksState.PullRight(either.left)] as const\n      }\n      case \"Right\": {\n        if (Chunk.isEmpty(either.right)) {\n          return [output, ZipChunksState.PullBoth] as const\n        }\n        return [output, ZipChunksState.PullLeft(either.right)] as const\n      }\n    }\n  }\n  return pipe(\n    self,\n    combineChunks(that, ZipChunksState.PullBoth, pull)\n  )\n})\n\n/** @internal */\nexport const zipWithIndex = <A, E, R>(self: Stream.Stream<A, E, R>): Stream.Stream<[A, number], E, R> =>\n  pipe(self, mapAccum(0, (index, a) => [index + 1, [a, index]]))\n\n/** @internal */\nexport const zipWithNext = <A, E, R>(\n  self: Stream.Stream<A, E, R>\n): Stream.Stream<[A, Option.Option<A>], E, R> => {\n  const process = (\n    last: Option.Option<A>\n  ): Channel.Channel<Chunk.Chunk<readonly [A, Option.Option<A>]>, Chunk.Chunk<A>, never, never, void, unknown> =>\n    core.readWithCause({\n      onInput: (input: Chunk.Chunk<A>) => {\n        const [newLast, chunk] = Chunk.mapAccum(\n          input,\n          last,\n          (prev, curr) => [Option.some(curr), pipe(prev, Option.map((a) => [a, curr] as const))] as const\n        )\n        const output = Chunk.filterMap(\n          chunk,\n          (option) =>\n            Option.isSome(option) ?\n              Option.some([option.value[0], Option.some(option.value[1])] as const) :\n              Option.none()\n        )\n        return core.flatMap(\n          core.write(output),\n          () => process(newLast)\n        )\n      },\n      onFailure: core.failCause,\n      onDone: () =>\n        Option.match(last, {\n          onNone: () => core.void,\n          onSome: (value) =>\n            channel.zipRight(\n              core.write(Chunk.of<readonly [A, Option.Option<A>]>([value, Option.none()])),\n              core.void\n            )\n        })\n    })\n  return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(process(Option.none()))))\n}\n\n/** @internal */\nexport const zipWithPrevious = <A, E, R>(\n  self: Stream.Stream<A, E, R>\n): Stream.Stream<[Option.Option<A>, A], E, R> =>\n  pipe(\n    self,\n    mapAccum<Option.Option<A>, A, [Option.Option<A>, A]>(\n      Option.none(),\n      (prev, curr) => [Option.some(curr), [prev, curr]]\n    )\n  )\n\n/** @internal */\nexport const zipWithPreviousAndNext = <A, E, R>(\n  self: Stream.Stream<A, E, R>\n): Stream.Stream<[Option.Option<A>, A, Option.Option<A>], E, R> =>\n  pipe(\n    zipWithNext(zipWithPrevious(self)),\n    map(([[prev, curr], next]) => [prev, curr, pipe(next, Option.map((tuple) => tuple[1]))])\n  )\n\n/** @internal */\nconst zipChunks = <A, B, C>(\n  left: Chunk.Chunk<A>,\n  right: Chunk.Chunk<B>,\n  f: (a: A, b: B) => C\n): [Chunk.Chunk<C>, Either.Either<Chunk.Chunk<B>, Chunk.Chunk<A>>] => {\n  if (left.length > right.length) {\n    return [\n      pipe(left, Chunk.take(right.length), Chunk.zipWith(right, f)),\n      Either.left(pipe(left, Chunk.drop(right.length)))\n    ]\n  }\n  return [\n    pipe(left, Chunk.zipWith(pipe(right, Chunk.take(left.length)), f)),\n    Either.right(pipe(right, Chunk.drop(left.length)))\n  ]\n}\n\n// Do notation\n\n/** @internal */\nexport const Do: Stream.Stream<{}> = succeed({})\n\n/** @internal */\nexport const bind = dual<\n  <N extends string, A, B, E2, R2>(\n    tag: Exclude<N, keyof A>,\n    f: (_: Types.NoInfer<A>) => Stream.Stream<B, E2, R2>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly bufferSize?: number | undefined\n    }\n  ) => <E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<\n    { [K in keyof A | N]: K extends keyof A ? A[K] : B },\n    E | E2,\n    R | R2\n  >,\n  <A, E, R, N extends string, B, E2, R2>(\n    self: Stream.Stream<A, E, R>,\n    tag: Exclude<N, keyof A>,\n    f: (_: Types.NoInfer<A>) => Stream.Stream<B, E2, R2>,\n    options?: {\n      readonly concurrency?: number | \"unbounded\" | undefined\n      readonly bufferSize?: number | undefined\n    }\n  ) => Stream.Stream<\n    { [K in keyof A | N]: K extends keyof A ? A[K] : B },\n    E | E2,\n    R | R2\n  >\n>((args) => typeof args[0] !== \"string\", <A, E, R, N extends string, B, E2, R2>(\n  self: Stream.Stream<A, E, R>,\n  tag: Exclude<N, keyof A>,\n  f: (_: A) => Stream.Stream<B, E2, R2>,\n  options?: {\n    readonly concurrency?: number | \"unbounded\" | undefined\n    readonly bufferSize?: number | undefined\n  }\n) =>\n  flatMap(self, (k) =>\n    map(\n      f(k),\n      (a) => ({ ...k, [tag]: a } as { [K in keyof A | N]: K extends keyof A ? A[K] : B })\n    ), options))\n\n/* @internal */\nexport const bindTo: {\n  <N extends string>(name: N): <A, E, R>(self: Stream.Stream<A, E, R>) => Stream.Stream<{ [K in N]: A }, E, R>\n  <A, E, R, N extends string>(self: Stream.Stream<A, E, R>, name: N): Stream.Stream<{ [K in N]: A }, E, R>\n} = doNotation.bindTo<Stream.StreamTypeLambda>(map)\n\n/* @internal */\nexport const let_: {\n  <N extends string, A extends object, B>(\n    name: Exclude<N, keyof A>,\n    f: (a: Types.NoInfer<A>) => B\n  ): <E, R>(\n    self: Stream.Stream<A, E, R>\n  ) => Stream.Stream<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E, R>\n  <A extends object, E, R, N extends string, B>(\n    self: Stream.Stream<A, E, R>,\n    name: Exclude<N, keyof A>,\n    f: (a: Types.NoInfer<A>) => B\n  ): Stream.Stream<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E, R>\n} = doNotation.let_<Stream.StreamTypeLambda>(map)\n\n// Circular with Channel\n\n/** @internal */\nexport const channelToStream = <OutElem, OutErr, OutDone, Env>(\n  self: Channel.Channel<Chunk.Chunk<OutElem>, unknown, OutErr, unknown, OutDone, unknown, Env>\n): Stream.Stream<OutElem, OutErr, Env> => {\n  return new StreamImpl(self)\n}\n\n// =============================================================================\n// encoding\n// =============================================================================\n\n/** @internal */\nexport const decodeText = dual<\n  (encoding?: string) => <E, R>(self: Stream.Stream<Uint8Array, E, R>) => Stream.Stream<string, E, R>,\n  <E, R>(self: Stream.Stream<Uint8Array, E, R>, encoding?: string) => Stream.Stream<string, E, R>\n>((args) => isStream(args[0]), (self, encoding = \"utf-8\") =>\n  suspend(() => {\n    const decoder = new TextDecoder(encoding)\n    return map(self, (s) => decoder.decode(s, { stream: true }))\n  }))\n\n/** @internal */\nexport const encodeText = <E, R>(self: Stream.Stream<string, E, R>): Stream.Stream<Uint8Array, E, R> =>\n  suspend(() => {\n    const encoder = new TextEncoder()\n    return map(self, (s) => encoder.encode(s))\n  })\n\n/** @internal */\nexport const fromEventListener = <A = unknown>(\n  target: Stream.EventListener<A>,\n  type: string,\n  options?: boolean | {\n    readonly capture?: boolean\n    readonly passive?: boolean\n    readonly once?: boolean\n    readonly bufferSize?: number | \"unbounded\" | undefined\n  } | undefined\n): Stream.Stream<A> =>\n  asyncPush<A>((emit) =>\n    Effect.acquireRelease(\n      Effect.sync(() => target.addEventListener(type, emit.single as any, options)),\n      () => Effect.sync(() => target.removeEventListener(type, emit.single, options))\n    ), { bufferSize: typeof options === \"object\" ? options.bufferSize : undefined })\n"
  },
  {
    "path": "packages/effect/src/internal/string-utils.ts",
    "content": "/**\n * Adapted from the `change-case` library.\n *\n * Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com)\n */\n\n/** @internal */\nexport const lowerCase = (str: string) => str.toLowerCase()\n\n/** @internal */\nexport const upperCase = (str: string) => str.toUpperCase()\n\ninterface Options {\n  splitRegexp?: RegExp | ReadonlyArray<RegExp>\n  stripRegexp?: RegExp | ReadonlyArray<RegExp>\n  delimiter?: string\n  transform?: (part: string, index: number, parts: ReadonlyArray<string>) => string\n}\n\n/**\n * Replace `re` in the input string with the replacement value.\n */\nconst replace = (input: string, re: RegExp | ReadonlyArray<RegExp>, value: string): string =>\n  re instanceof RegExp\n    ? input.replace(re, value)\n    : re.reduce((input, re) => input.replace(re, value), input)\n\n// Support camel case (\"camelCase\" -> \"camel Case\" and \"CAMELCase\" -> \"CAMEL Case\").\nconst DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g]\n\n// Remove all non-word characters.\nconst DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi\n\n/**\n * Normalize the string into something other libraries can manipulate easier.\n */\nconst noCase = (input: string, options: Options = {}): string => {\n  const {\n    delimiter = \" \",\n    splitRegexp = DEFAULT_SPLIT_REGEXP,\n    stripRegexp = DEFAULT_STRIP_REGEXP,\n    transform = lowerCase\n  } = options\n  const result = replace(replace(input, splitRegexp, \"$1\\0$2\"), stripRegexp, \"\\0\")\n  let start = 0\n  let end = result.length\n  // Trim the delimiter from around the output string.\n  while (result.charAt(start) === \"\\0\") {\n    start++\n  }\n  while (result.charAt(end - 1) === \"\\0\") {\n    end--\n  }\n  // Transform each token independently.\n  return result.slice(start, end).split(\"\\0\").map(transform).join(delimiter)\n}\n\nconst pascalCaseTransform = (input: string, index: number): string => {\n  const firstChar = input.charAt(0)\n  const lowerChars = input.substring(1).toLowerCase()\n  if (index > 0 && firstChar >= \"0\" && firstChar <= \"9\") {\n    return `_${firstChar}${lowerChars}`\n  }\n  return `${firstChar.toUpperCase()}${lowerChars}`\n}\n\n/** @internal */\nexport const pascalCase = (input: string, options?: Options): string =>\n  noCase(input, {\n    delimiter: \"\",\n    transform: pascalCaseTransform,\n    ...options\n  })\n\nconst camelCaseTransform = (input: string, index: number): string =>\n  index === 0\n    ? input.toLowerCase()\n    : pascalCaseTransform(input, index)\n\n/** @internal */\nexport const camelCase = (input: string, options?: Options): string =>\n  pascalCase(input, {\n    transform: camelCaseTransform,\n    ...options\n  })\n\n/** @internal */\nexport const constantCase = (input: string, options?: Options): string =>\n  noCase(input, {\n    delimiter: \"_\",\n    transform: upperCase,\n    ...options\n  })\n\n/** @internal */\nexport const kebabCase = (input: string, options?: Options) =>\n  noCase(input, {\n    delimiter: \"-\",\n    ...options\n  })\n\n/** @internal */\nexport const snakeCase = (input: string, options?: Options) =>\n  noCase(input, {\n    delimiter: \"_\",\n    ...options\n  })\n"
  },
  {
    "path": "packages/effect/src/internal/subscriptionRef.ts",
    "content": "import * as Effect from \"../Effect.js\"\nimport * as Effectable from \"../Effectable.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport * as PubSub from \"../PubSub.js\"\nimport * as Readable from \"../Readable.js\"\nimport * as Ref from \"../Ref.js\"\nimport type { Stream } from \"../Stream.js\"\nimport * as Subscribable from \"../Subscribable.js\"\nimport type * as SubscriptionRef from \"../SubscriptionRef.js\"\nimport * as Synchronized from \"../SynchronizedRef.js\"\nimport * as circular_ from \"./effect/circular.js\"\nimport * as ref_ from \"./ref.js\"\nimport * as stream from \"./stream.js\"\n\n/** @internal */\nconst SubscriptionRefSymbolKey = \"effect/SubscriptionRef\"\n\n/** @internal */\nexport const SubscriptionRefTypeId: SubscriptionRef.SubscriptionRefTypeId = Symbol.for(\n  SubscriptionRefSymbolKey\n) as SubscriptionRef.SubscriptionRefTypeId\n\nconst subscriptionRefVariance = {\n  /* c8 ignore next */\n  _A: (_: any) => _\n}\n\n/** @internal */\nclass SubscriptionRefImpl<in out A> extends Effectable.Class<A> implements SubscriptionRef.SubscriptionRef<A> {\n  readonly [Readable.TypeId]: Readable.TypeId = Readable.TypeId\n  readonly [Subscribable.TypeId]: Subscribable.TypeId = Subscribable.TypeId\n  readonly [Ref.RefTypeId] = ref_.refVariance\n  readonly [Synchronized.SynchronizedRefTypeId] = circular_.synchronizedVariance\n  readonly [SubscriptionRefTypeId] = subscriptionRefVariance\n  constructor(\n    readonly ref: Ref.Ref<A>,\n    readonly pubsub: PubSub.PubSub<A>,\n    readonly semaphore: Effect.Semaphore\n  ) {\n    super()\n    this.get = Ref.get(this.ref)\n  }\n  commit() {\n    return this.get\n  }\n  readonly get: Effect.Effect<A>\n  get changes(): Stream<A> {\n    return pipe(\n      Ref.get(this.ref),\n      Effect.flatMap((a) =>\n        Effect.map(\n          stream.fromPubSub(this.pubsub, { scoped: true }),\n          (s) =>\n            stream.concat(\n              stream.make(a),\n              s\n            )\n        )\n      ),\n      this.semaphore.withPermits(1),\n      stream.unwrapScoped\n    )\n  }\n  modify<B>(f: (a: A) => readonly [B, A]): Effect.Effect<B> {\n    return this.modifyEffect((a) => Effect.succeed(f(a)))\n  }\n  modifyEffect<B, E, R>(f: (a: A) => Effect.Effect<readonly [B, A], E, R>): Effect.Effect<B, E, R> {\n    return pipe(\n      Ref.get(this.ref),\n      Effect.flatMap(f),\n      Effect.flatMap(([b, a]) =>\n        pipe(\n          Ref.set(this.ref, a),\n          Effect.as(b),\n          Effect.zipLeft(PubSub.publish(this.pubsub, a))\n        )\n      ),\n      this.semaphore.withPermits(1)\n    )\n  }\n}\n\n/** @internal */\nexport const get = <A>(self: SubscriptionRef.SubscriptionRef<A>): Effect.Effect<A> => Ref.get(self.ref)\n\n/** @internal */\nexport const make = <A>(value: A): Effect.Effect<SubscriptionRef.SubscriptionRef<A>> =>\n  pipe(\n    Effect.all([\n      PubSub.unbounded<A>(),\n      Ref.make(value),\n      Effect.makeSemaphore(1)\n    ]),\n    Effect.map(([pubsub, ref, semaphore]) => new SubscriptionRefImpl(ref, pubsub, semaphore))\n  )\n\n/** @internal */\nexport const modify = dual<\n  <A, B>(f: (a: A) => readonly [B, A]) => (self: SubscriptionRef.SubscriptionRef<A>) => Effect.Effect<B>,\n  <A, B>(\n    self: SubscriptionRef.SubscriptionRef<A>,\n    f: (a: A) => readonly [B, A]\n  ) => Effect.Effect<B>\n>(2, <A, B>(\n  self: SubscriptionRef.SubscriptionRef<A>,\n  f: (a: A) => readonly [B, A]\n): Effect.Effect<B> => self.modify(f))\n\n/** @internal */\nexport const modifyEffect = dual<\n  <B, A, E, R>(\n    f: (a: A) => Effect.Effect<readonly [B, A], E, R>\n  ) => (self: SubscriptionRef.SubscriptionRef<A>) => Effect.Effect<B, E, R>,\n  <A, B, E, R>(\n    self: SubscriptionRef.SubscriptionRef<A>,\n    f: (a: A) => Effect.Effect<readonly [B, A], E, R>\n  ) => Effect.Effect<B, E, R>\n>(2, <A, B, E, R>(\n  self: SubscriptionRef.SubscriptionRef<A>,\n  f: (a: A) => Effect.Effect<readonly [B, A], E, R>\n): Effect.Effect<B, E, R> => self.modifyEffect(f))\n\n/** @internal */\nexport const set = dual<\n  <A>(value: A) => (self: SubscriptionRef.SubscriptionRef<A>) => Effect.Effect<void>,\n  <A>(\n    self: SubscriptionRef.SubscriptionRef<A>,\n    value: A\n  ) => Effect.Effect<void>\n>(2, <A>(\n  self: SubscriptionRef.SubscriptionRef<A>,\n  value: A\n): Effect.Effect<void> =>\n  pipe(\n    Ref.set(self.ref, value),\n    Effect.zipLeft(PubSub.publish(self.pubsub, value)),\n    self.semaphore.withPermits(1)\n  ))\n"
  },
  {
    "path": "packages/effect/src/internal/supervisor/patch.ts",
    "content": "import * as Chunk from \"../../Chunk.js\"\nimport * as Differ from \"../../Differ.js\"\nimport * as Equal from \"../../Equal.js\"\nimport { pipe } from \"../../Function.js\"\nimport * as HashSet from \"../../HashSet.js\"\nimport type * as Supervisor from \"../../Supervisor.js\"\nimport * as supervisor from \"../supervisor.js\"\n\n/** @internal */\nexport type SupervisorPatch = Empty | AddSupervisor | RemoveSupervisor | AndThen\n\n/** @internal */\nexport const OP_EMPTY = \"Empty\" as const\n\n/** @internal */\nexport type OP_EMPTY = typeof OP_EMPTY\n\n/** @internal */\nexport const OP_ADD_SUPERVISOR = \"AddSupervisor\" as const\n\n/** @internal */\nexport type OP_ADD_SUPERVISOR = typeof OP_ADD_SUPERVISOR\n\n/** @internal */\nexport const OP_REMOVE_SUPERVISOR = \"RemoveSupervisor\" as const\n\n/** @internal */\nexport type OP_REMOVE_SUPERVISOR = typeof OP_REMOVE_SUPERVISOR\n\n/** @internal */\nexport const OP_AND_THEN = \"AndThen\" as const\n\n/** @internal */\nexport type OP_AND_THEN = typeof OP_AND_THEN\n\n/** @internal */\nexport interface Empty {\n  readonly _tag: OP_EMPTY\n}\n\n/** @internal */\nexport interface AddSupervisor {\n  readonly _tag: OP_ADD_SUPERVISOR\n  readonly supervisor: Supervisor.Supervisor<any>\n}\n\n/** @internal */\nexport interface RemoveSupervisor {\n  readonly _tag: OP_REMOVE_SUPERVISOR\n  readonly supervisor: Supervisor.Supervisor<any>\n}\n\n/** @internal */\nexport interface AndThen {\n  readonly _tag: OP_AND_THEN\n  readonly first: SupervisorPatch\n  readonly second: SupervisorPatch\n}\n\n/**\n * The empty `SupervisorPatch`.\n *\n * @internal\n */\nexport const empty: SupervisorPatch = { _tag: OP_EMPTY }\n\n/**\n * Combines two patches to produce a new patch that describes applying the\n * updates from this patch and then the updates from the specified patch.\n *\n * @internal\n */\nexport const combine = (self: SupervisorPatch, that: SupervisorPatch): SupervisorPatch => {\n  return {\n    _tag: OP_AND_THEN,\n    first: self,\n    second: that\n  }\n}\n\n/**\n * Applies a `SupervisorPatch` to a `Supervisor` to produce a new `Supervisor`.\n *\n * @internal\n */\nexport const patch = (\n  self: SupervisorPatch,\n  supervisor: Supervisor.Supervisor<any>\n): Supervisor.Supervisor<any> => {\n  return patchLoop(supervisor, Chunk.of(self))\n}\n\n/** @internal */\nconst patchLoop = (\n  _supervisor: Supervisor.Supervisor<any>,\n  _patches: Chunk.Chunk<SupervisorPatch>\n): Supervisor.Supervisor<any> => {\n  let supervisor = _supervisor\n  let patches = _patches\n  while (Chunk.isNonEmpty(patches)) {\n    const head = Chunk.headNonEmpty(patches)\n    switch (head._tag) {\n      case OP_EMPTY: {\n        patches = Chunk.tailNonEmpty(patches)\n        break\n      }\n      case OP_ADD_SUPERVISOR: {\n        supervisor = supervisor.zip(head.supervisor)\n        patches = Chunk.tailNonEmpty(patches)\n        break\n      }\n      case OP_REMOVE_SUPERVISOR: {\n        supervisor = removeSupervisor(supervisor, head.supervisor)\n        patches = Chunk.tailNonEmpty(patches)\n        break\n      }\n      case OP_AND_THEN: {\n        patches = Chunk.prepend(head.first)(Chunk.prepend(head.second)(Chunk.tailNonEmpty(patches)))\n        break\n      }\n    }\n  }\n  return supervisor\n}\n\n/** @internal */\nconst removeSupervisor = (\n  self: Supervisor.Supervisor<any>,\n  that: Supervisor.Supervisor<any>\n): Supervisor.Supervisor<any> => {\n  if (Equal.equals(self, that)) {\n    return supervisor.none\n  } else {\n    if (supervisor.isZip(self)) {\n      return removeSupervisor(self.left, that).zip(removeSupervisor(self.right, that))\n    } else {\n      return self\n    }\n  }\n}\n\n/** @internal */\nconst toSet = (self: Supervisor.Supervisor<any>): HashSet.HashSet<Supervisor.Supervisor<any>> => {\n  if (Equal.equals(self, supervisor.none)) {\n    return HashSet.empty()\n  } else {\n    if (supervisor.isZip(self)) {\n      return pipe(toSet(self.left), HashSet.union(toSet(self.right)))\n    } else {\n      return HashSet.make(self)\n    }\n  }\n}\n\n/** @internal */\nexport const diff = (\n  oldValue: Supervisor.Supervisor<any>,\n  newValue: Supervisor.Supervisor<any>\n): SupervisorPatch => {\n  if (Equal.equals(oldValue, newValue)) {\n    return empty\n  }\n  const oldSupervisors = toSet(oldValue)\n  const newSupervisors = toSet(newValue)\n  const added = pipe(\n    newSupervisors,\n    HashSet.difference(oldSupervisors),\n    HashSet.reduce(\n      empty as SupervisorPatch,\n      (patch, supervisor) => combine(patch, { _tag: OP_ADD_SUPERVISOR, supervisor })\n    )\n  )\n  const removed = pipe(\n    oldSupervisors,\n    HashSet.difference(newSupervisors),\n    HashSet.reduce(\n      empty as SupervisorPatch,\n      (patch, supervisor) => combine(patch, { _tag: OP_REMOVE_SUPERVISOR, supervisor })\n    )\n  )\n  return combine(added, removed)\n}\n\n/** @internal */\nexport const differ = Differ.make<Supervisor.Supervisor<any>, SupervisorPatch>({\n  empty,\n  patch,\n  combine,\n  diff\n})\n"
  },
  {
    "path": "packages/effect/src/internal/supervisor.ts",
    "content": "import type * as Context from \"../Context.js\"\nimport type * as Effect from \"../Effect.js\"\nimport type * as Exit from \"../Exit.js\"\nimport type * as Fiber from \"../Fiber.js\"\nimport { pipe } from \"../Function.js\"\nimport { globalValue } from \"../GlobalValue.js\"\nimport * as MutableRef from \"../MutableRef.js\"\nimport type * as Option from \"../Option.js\"\nimport { hasProperty, isTagged } from \"../Predicate.js\"\nimport * as SortedSet from \"../SortedSet.js\"\nimport type * as Supervisor from \"../Supervisor.js\"\nimport * as core from \"./core.js\"\n\n/** @internal */\nconst SupervisorSymbolKey = \"effect/Supervisor\"\n\n/** @internal */\nexport const SupervisorTypeId: Supervisor.SupervisorTypeId = Symbol.for(\n  SupervisorSymbolKey\n) as Supervisor.SupervisorTypeId\n\n/** @internal */\nexport const supervisorVariance = {\n  /* c8 ignore next */\n  _T: (_: never) => _\n}\n\n/** @internal */\nexport class ProxySupervisor<out T> implements Supervisor.Supervisor<T> {\n  readonly [SupervisorTypeId] = supervisorVariance\n\n  constructor(\n    readonly underlying: Supervisor.Supervisor<any>,\n    readonly value0: Effect.Effect<T>\n  ) {\n  }\n\n  get value(): Effect.Effect<T> {\n    return this.value0\n  }\n\n  onStart<A, E, R>(\n    context: Context.Context<R>,\n    effect: Effect.Effect<A, E, R>,\n    parent: Option.Option<Fiber.RuntimeFiber<any, any>>,\n    fiber: Fiber.RuntimeFiber<A, E>\n  ): void {\n    this.underlying.onStart(context, effect, parent, fiber)\n  }\n\n  onEnd<A, E>(value: Exit.Exit<A, E>, fiber: Fiber.RuntimeFiber<A, E>): void {\n    this.underlying.onEnd(value, fiber)\n  }\n\n  onEffect<A, E>(fiber: Fiber.RuntimeFiber<A, E>, effect: Effect.Effect<any, any, any>): void {\n    this.underlying.onEffect(fiber, effect)\n  }\n\n  onSuspend<A, E>(fiber: Fiber.RuntimeFiber<A, E>): void {\n    this.underlying.onSuspend(fiber)\n  }\n\n  onResume<A, E>(fiber: Fiber.RuntimeFiber<A, E>): void {\n    this.underlying.onResume(fiber)\n  }\n\n  map<B>(f: (a: T) => B): Supervisor.Supervisor<B> {\n    return new ProxySupervisor(this, pipe(this.value, core.map(f)))\n  }\n\n  zip<B>(right: Supervisor.Supervisor<B>): Supervisor.Supervisor<[T, B]> {\n    return new Zip(this, right)\n  }\n}\n\n/** @internal */\nexport class Zip<out T0, out T1> implements Supervisor.Supervisor<readonly [T0, T1]> {\n  readonly _tag = \"Zip\"\n  readonly [SupervisorTypeId] = supervisorVariance\n\n  constructor(\n    readonly left: Supervisor.Supervisor<T0>,\n    readonly right: Supervisor.Supervisor<T1>\n  ) {\n  }\n\n  get value(): Effect.Effect<[T0, T1]> {\n    return core.zip(this.left.value, this.right.value)\n  }\n\n  onStart<A, E, R>(\n    context: Context.Context<R>,\n    effect: Effect.Effect<A, E, R>,\n    parent: Option.Option<Fiber.RuntimeFiber<any, any>>,\n    fiber: Fiber.RuntimeFiber<A, E>\n  ): void {\n    this.left.onStart(context, effect, parent, fiber)\n    this.right.onStart(context, effect, parent, fiber)\n  }\n\n  onEnd<A, E>(value: Exit.Exit<A, E>, fiber: Fiber.RuntimeFiber<A, E>): void {\n    this.left.onEnd(value, fiber)\n    this.right.onEnd(value, fiber)\n  }\n\n  onEffect<A, E>(fiber: Fiber.RuntimeFiber<A, E>, effect: Effect.Effect<any, any, any>): void {\n    this.left.onEffect(fiber, effect)\n    this.right.onEffect(fiber, effect)\n  }\n\n  onSuspend<A, E>(fiber: Fiber.RuntimeFiber<A, E>): void {\n    this.left.onSuspend(fiber)\n    this.right.onSuspend(fiber)\n  }\n\n  onResume<A, E>(fiber: Fiber.RuntimeFiber<A, E>): void {\n    this.left.onResume(fiber)\n    this.right.onResume(fiber)\n  }\n\n  map<B>(f: (a: [T0, T1]) => B): Supervisor.Supervisor<B> {\n    return new ProxySupervisor(this, pipe(this.value, core.map(f)))\n  }\n\n  zip<A>(right: Supervisor.Supervisor<A>): Supervisor.Supervisor<[[T0, T1], A]> {\n    return new Zip(this, right)\n  }\n}\n\n/** @internal */\nexport const isZip = (self: unknown): self is Zip<any, any> =>\n  hasProperty(self, SupervisorTypeId) && isTagged(self, \"Zip\")\n\n/** @internal */\nexport class Track implements Supervisor.Supervisor<Array<Fiber.RuntimeFiber<any, any>>> {\n  readonly [SupervisorTypeId] = supervisorVariance\n\n  readonly fibers: Set<Fiber.RuntimeFiber<any, any>> = new Set()\n\n  get value(): Effect.Effect<Array<Fiber.RuntimeFiber<any, any>>> {\n    return core.sync(() => Array.from(this.fibers))\n  }\n\n  onStart<A, E, R>(\n    _context: Context.Context<R>,\n    _effect: Effect.Effect<A, E, R>,\n    _parent: Option.Option<Fiber.RuntimeFiber<any, any>>,\n    fiber: Fiber.RuntimeFiber<A, E>\n  ): void {\n    this.fibers.add(fiber)\n  }\n\n  onEnd<A, E>(_value: Exit.Exit<A, E>, fiber: Fiber.RuntimeFiber<A, E>): void {\n    this.fibers.delete(fiber)\n  }\n\n  onEffect<A, E>(_fiber: Fiber.RuntimeFiber<A, E>, _effect: Effect.Effect<any, any, any>): void {\n    //\n  }\n\n  onSuspend<A, E>(_fiber: Fiber.RuntimeFiber<A, E>): void {\n    //\n  }\n\n  onResume<A, E>(_fiber: Fiber.RuntimeFiber<A, E>): void {\n    //\n  }\n\n  map<B>(f: (a: Array<Fiber.RuntimeFiber<any, any>>) => B): Supervisor.Supervisor<B> {\n    return new ProxySupervisor(this, pipe(this.value, core.map(f)))\n  }\n\n  zip<A>(\n    right: Supervisor.Supervisor<A>\n  ): Supervisor.Supervisor<[Array<Fiber.RuntimeFiber<any, any>>, A]> {\n    return new Zip(this, right)\n  }\n\n  onRun<E, A, X>(execution: () => X, _fiber: Fiber.RuntimeFiber<A, E>): X {\n    return execution()\n  }\n}\n\n/** @internal */\nexport class Const<out T> implements Supervisor.Supervisor<T> {\n  readonly [SupervisorTypeId] = supervisorVariance\n\n  constructor(readonly effect: Effect.Effect<T>) {\n  }\n\n  get value(): Effect.Effect<T> {\n    return this.effect\n  }\n\n  onStart<A, E, R>(\n    _context: Context.Context<R>,\n    _effect: Effect.Effect<A, E, R>,\n    _parent: Option.Option<Fiber.RuntimeFiber<any, any>>,\n    _fiber: Fiber.RuntimeFiber<A, E>\n  ): void {\n    //\n  }\n\n  onEnd<A, E>(_value: Exit.Exit<A, E>, _fiber: Fiber.RuntimeFiber<A, E>): void {\n    //\n  }\n\n  onEffect<A, E>(_fiber: Fiber.RuntimeFiber<A, E>, _effect: Effect.Effect<any, any, any>): void {\n    //\n  }\n\n  onSuspend<A, E>(_fiber: Fiber.RuntimeFiber<A, E>): void {\n    //\n  }\n\n  onResume<A, E>(_fiber: Fiber.RuntimeFiber<A, E>): void {\n    //\n  }\n\n  map<B>(f: (a: T) => B): Supervisor.Supervisor<B> {\n    return new ProxySupervisor(this, pipe(this.value, core.map(f)))\n  }\n\n  zip<A>(right: Supervisor.Supervisor<A>): Supervisor.Supervisor<[T, A]> {\n    return new Zip(this, right)\n  }\n\n  onRun<E, A, X>(execution: () => X, _fiber: Fiber.RuntimeFiber<A, E>): X {\n    return execution()\n  }\n}\n\nclass FibersIn implements Supervisor.Supervisor<SortedSet.SortedSet<Fiber.RuntimeFiber<any, any>>> {\n  readonly [SupervisorTypeId] = supervisorVariance\n\n  constructor(readonly ref: MutableRef.MutableRef<SortedSet.SortedSet<Fiber.RuntimeFiber<any, any>>>) {\n  }\n\n  get value(): Effect.Effect<SortedSet.SortedSet<Fiber.RuntimeFiber<any, any>>> {\n    return core.sync(() => MutableRef.get(this.ref))\n  }\n\n  onStart<A, E, R>(\n    _context: Context.Context<R>,\n    _effect: Effect.Effect<A, E, R>,\n    _parent: Option.Option<Fiber.RuntimeFiber<any, any>>,\n    fiber: Fiber.RuntimeFiber<A, E>\n  ): void {\n    pipe(this.ref, MutableRef.set(pipe(MutableRef.get(this.ref), SortedSet.add(fiber))))\n  }\n\n  onEnd<A, E>(_value: Exit.Exit<A, E>, fiber: Fiber.RuntimeFiber<A, E>): void {\n    pipe(this.ref, MutableRef.set(pipe(MutableRef.get(this.ref), SortedSet.remove(fiber))))\n  }\n\n  onEffect<A, E>(_fiber: Fiber.RuntimeFiber<A, E>, _effect: Effect.Effect<any, any, any>): void {\n    //\n  }\n\n  onSuspend<A, E>(_fiber: Fiber.RuntimeFiber<A, E>): void {\n    //\n  }\n\n  onResume<A, E>(_fiber: Fiber.RuntimeFiber<A, E>): void {\n    //\n  }\n\n  map<B>(f: (a: SortedSet.SortedSet<Fiber.RuntimeFiber<any, any>>) => B): Supervisor.Supervisor<B> {\n    return new ProxySupervisor(this, pipe(this.value, core.map(f)))\n  }\n\n  zip<A>(\n    right: Supervisor.Supervisor<A>\n  ): Supervisor.Supervisor<[SortedSet.SortedSet<Fiber.RuntimeFiber<any, any>>, A]> {\n    return new Zip(this, right)\n  }\n\n  onRun<E, A, X>(execution: () => X, _fiber: Fiber.RuntimeFiber<A, E>): X {\n    return execution()\n  }\n}\n\n/** @internal */\nexport const unsafeTrack = (): Supervisor.Supervisor<Array<Fiber.RuntimeFiber<any, any>>> => {\n  return new Track()\n}\n\n/** @internal */\nexport const track: Effect.Effect<Supervisor.Supervisor<Array<Fiber.RuntimeFiber<any, any>>>> = core.sync(unsafeTrack)\n\n/** @internal */\nexport const fromEffect = <A>(effect: Effect.Effect<A>): Supervisor.Supervisor<A> => {\n  return new Const(effect)\n}\n\n/** @internal */\nexport const none = globalValue(\"effect/Supervisor/none\", () => fromEffect(core.void))\n\n/** @internal */\nexport const fibersIn = (\n  ref: MutableRef.MutableRef<SortedSet.SortedSet<Fiber.RuntimeFiber<any, any>>>\n): Effect.Effect<Supervisor.Supervisor<SortedSet.SortedSet<Fiber.RuntimeFiber<any, any>>>> =>\n  core.sync(() => new FibersIn(ref))\n"
  },
  {
    "path": "packages/effect/src/internal/synchronizedRef.ts",
    "content": "import type * as Effect from \"../Effect.js\"\nimport { dual, pipe } from \"../Function.js\"\nimport * as Option from \"../Option.js\"\nimport type * as Synchronized from \"../SynchronizedRef.js\"\nimport * as core from \"./core.js\"\n\n/** @internal */\nexport const getAndUpdateEffect = dual<\n  <A, R, E>(f: (a: A) => Effect.Effect<A, E, R>) => (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<A, E, R>,\n  <A, R, E>(self: Synchronized.SynchronizedRef<A>, f: (a: A) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n>(2, (self, f) =>\n  self.modifyEffect(\n    (value) => core.map(f(value), (result) => [value, result] as const)\n  ))\n\n/** @internal */\nexport const getAndUpdateSomeEffect = dual<\n  <A, R, E>(\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ) => (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<A, E, R>,\n  <A, R, E>(\n    self: Synchronized.SynchronizedRef<A>,\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ) => Effect.Effect<A, E, R>\n>(2, (self, pf) =>\n  self.modifyEffect((value) => {\n    const result = pf(value)\n    switch (result._tag) {\n      case \"None\": {\n        return core.succeed([value, value] as const)\n      }\n      case \"Some\": {\n        return core.map(result.value, (newValue) => [value, newValue] as const)\n      }\n    }\n  }))\n\n/** @internal */\nexport const modify = dual<\n  <A, B>(f: (a: A) => readonly [B, A]) => (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<B>,\n  <A, B>(self: Synchronized.SynchronizedRef<A>, f: (a: A) => readonly [B, A]) => Effect.Effect<B>\n>(2, (self, f) => self.modify(f))\n\n/** @internal */\nexport const modifyEffect = dual<\n  <A, B, E, R>(\n    f: (a: A) => Effect.Effect<readonly [B, A], E, R>\n  ) => (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<B, E, R>,\n  <A, B, E, R>(\n    self: Synchronized.SynchronizedRef<A>,\n    f: (a: A) => Effect.Effect<readonly [B, A], E, R>\n  ) => Effect.Effect<B, E, R>\n>(2, (self, f) => self.modifyEffect(f))\n\n/** @internal */\nexport const modifySomeEffect = dual<\n  <A, B, R, E>(\n    fallback: B,\n    pf: (a: A) => Option.Option<Effect.Effect<readonly [B, A], E, R>>\n  ) => (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<B, E, R>,\n  <A, B, R, E>(\n    self: Synchronized.SynchronizedRef<A>,\n    fallback: B,\n    pf: (a: A) => Option.Option<Effect.Effect<readonly [B, A], E, R>>\n  ) => Effect.Effect<B, E, R>\n>(3, (self, fallback, pf) =>\n  self.modifyEffect(\n    (value) => pipe(pf(value), Option.getOrElse(() => core.succeed([fallback, value] as const)))\n  ))\n\n/** @internal */\nexport const updateEffect = dual<\n  <A, R, E>(\n    f: (a: A) => Effect.Effect<A, E, R>\n  ) => (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<void, E, R>,\n  <A, R, E>(self: Synchronized.SynchronizedRef<A>, f: (a: A) => Effect.Effect<A, E, R>) => Effect.Effect<void, E, R>\n>(2, (self, f) =>\n  self.modifyEffect((value) =>\n    core.map(\n      f(value),\n      (result) => [undefined as void, result] as const\n    )\n  ))\n\n/** @internal */\nexport const updateAndGetEffect = dual<\n  <A, R, E>(f: (a: A) => Effect.Effect<A, E, R>) => (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<A, E, R>,\n  <A, R, E>(self: Synchronized.SynchronizedRef<A>, f: (a: A) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n>(2, (self, f) =>\n  self.modifyEffect(\n    (value) => core.map(f(value), (result) => [result, result] as const)\n  ))\n\n/** @internal */\nexport const updateSomeEffect = dual<\n  <A, R, E>(\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ) => (self: Synchronized.SynchronizedRef<A>) => Effect.Effect<void, E, R>,\n  <A, R, E>(\n    self: Synchronized.SynchronizedRef<A>,\n    pf: (a: A) => Option.Option<Effect.Effect<A, E, R>>\n  ) => Effect.Effect<void, E, R>\n>(2, (self, pf) =>\n  self.modifyEffect((value) => {\n    const result = pf(value)\n    switch (result._tag) {\n      case \"None\": {\n        return core.succeed([void 0, value] as const)\n      }\n      case \"Some\": {\n        return core.map(result.value, (a) => [void 0, a] as const)\n      }\n    }\n  }))\n"
  },
  {
    "path": "packages/effect/src/internal/take.ts",
    "content": "import * as Cause from \"../Cause.js\"\nimport * as Chunk from \"../Chunk.js\"\nimport * as Effect from \"../Effect.js\"\nimport * as Exit from \"../Exit.js\"\nimport { constFalse, constTrue, dual, pipe } from \"../Function.js\"\nimport * as Option from \"../Option.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport type * as Take from \"../Take.js\"\n\n/** @internal */\nconst TakeSymbolKey = \"effect/Take\"\n\n/** @internal */\nexport const TakeTypeId: Take.TakeTypeId = Symbol.for(\n  TakeSymbolKey\n) as Take.TakeTypeId\n\nconst takeVariance = {\n  /* c8 ignore next */\n  _A: (_: never) => _,\n  /* c8 ignore next */\n  _E: (_: never) => _\n}\n\n/** @internal */\nexport class TakeImpl<out A, out E = never> implements Take.Take<A, E> {\n  readonly [TakeTypeId] = takeVariance\n  constructor(readonly exit: Exit.Exit<Chunk.Chunk<A>, Option.Option<E>>) {\n  }\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/** @internal */\nexport const chunk = <A>(chunk: Chunk.Chunk<A>): Take.Take<A> => new TakeImpl(Exit.succeed(chunk))\n\n/** @internal */\nexport const die = (defect: unknown): Take.Take<never> => new TakeImpl(Exit.die(defect))\n\n/** @internal */\nexport const dieMessage = (message: string): Take.Take<never> =>\n  new TakeImpl(Exit.die(new Cause.RuntimeException(message)))\n\n/** @internal */\nexport const done = <A, E>(self: Take.Take<A, E>): Effect.Effect<Chunk.Chunk<A>, Option.Option<E>> =>\n  Effect.suspend(() => self.exit)\n\n/** @internal */\nexport const end: Take.Take<never> = new TakeImpl(Exit.fail(Option.none()))\n\n/** @internal */\nexport const fail = <E>(error: E): Take.Take<never, E> => new TakeImpl(Exit.fail(Option.some(error)))\n\n/** @internal */\nexport const failCause = <E>(cause: Cause.Cause<E>): Take.Take<never, E> =>\n  new TakeImpl(Exit.failCause(pipe(cause, Cause.map(Option.some))))\n\n/** @internal */\nexport const fromEffect = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<Take.Take<A, E>, never, R> =>\n  Effect.matchCause(effect, { onFailure: failCause, onSuccess: of })\n\n/** @internal */\nexport const fromExit = <A, E>(exit: Exit.Exit<A, E>): Take.Take<A, E> =>\n  new TakeImpl(pipe(exit, Exit.mapBoth({ onFailure: Option.some, onSuccess: Chunk.of })))\n\n/** @internal */\nexport const fromPull = <A, E, R>(\n  pull: Effect.Effect<Chunk.Chunk<A>, Option.Option<E>, R>\n): Effect.Effect<Take.Take<A, E>, never, R> =>\n  Effect.matchCause(pull, {\n    onFailure: (cause) =>\n      Option.match(Cause.flipCauseOption(cause), {\n        onNone: () => end,\n        onSome: failCause\n      }),\n    onSuccess: chunk\n  })\n\n/** @internal */\nexport const isDone = <A, E>(self: Take.Take<A, E>): boolean =>\n  Exit.match(self.exit, {\n    onFailure: (cause) => Option.isNone(Cause.flipCauseOption(cause)),\n    onSuccess: constFalse\n  })\n\n/** @internal */\nexport const isFailure = <A, E>(self: Take.Take<A, E>): boolean =>\n  Exit.match(self.exit, {\n    onFailure: (cause) => Option.isSome(Cause.flipCauseOption(cause)),\n    onSuccess: constFalse\n  })\n\n/** @internal */\nexport const isSuccess = <A, E>(self: Take.Take<A, E>): boolean =>\n  Exit.match(self.exit, {\n    onFailure: constFalse,\n    onSuccess: constTrue\n  })\n\n/** @internal */\nexport const make = <A, E>(\n  exit: Exit.Exit<Chunk.Chunk<A>, Option.Option<E>>\n): Take.Take<A, E> => new TakeImpl(exit)\n\n/** @internal */\nexport const match = dual<\n  <Z, E, Z2, A, Z3>(\n    options: {\n      readonly onEnd: () => Z\n      readonly onFailure: (cause: Cause.Cause<E>) => Z2\n      readonly onSuccess: (chunk: Chunk.Chunk<A>) => Z3\n    }\n  ) => (self: Take.Take<A, E>) => Z | Z2 | Z3,\n  <A, E, Z, Z2, Z3>(\n    self: Take.Take<A, E>,\n    options: {\n      readonly onEnd: () => Z\n      readonly onFailure: (cause: Cause.Cause<E>) => Z2\n      readonly onSuccess: (chunk: Chunk.Chunk<A>) => Z3\n    }\n  ) => Z | Z2 | Z3\n>(2, <A, E, Z, Z2, Z3>(\n  self: Take.Take<A, E>,\n  { onEnd, onFailure, onSuccess }: {\n    readonly onEnd: () => Z\n    readonly onFailure: (cause: Cause.Cause<E>) => Z2\n    readonly onSuccess: (chunk: Chunk.Chunk<A>) => Z3\n  }\n): Z | Z2 | Z3 =>\n  Exit.match(self.exit, {\n    onFailure: (cause) =>\n      Option.match(Cause.flipCauseOption(cause), {\n        onNone: onEnd,\n        onSome: onFailure\n      }),\n    onSuccess\n  }))\n\n/** @internal */\nexport const matchEffect = dual<\n  <Z, E2, R, E, Z2, R2, A, Z3, E3, R3>(\n    options: {\n      readonly onEnd: Effect.Effect<Z, E2, R>\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<Z2, E2, R2>\n      readonly onSuccess: (chunk: Chunk.Chunk<A>) => Effect.Effect<Z3, E3, R3>\n    }\n  ) => (self: Take.Take<A, E>) => Effect.Effect<Z | Z2 | Z3, E2 | E | E3, R | R2 | R3>,\n  <A, E, Z, E2, R, Z2, R2, Z3, E3, R3>(\n    self: Take.Take<A, E>,\n    options: {\n      readonly onEnd: Effect.Effect<Z, E2, R>\n      readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<Z2, E2, R2>\n      readonly onSuccess: (chunk: Chunk.Chunk<A>) => Effect.Effect<Z3, E3, R3>\n    }\n  ) => Effect.Effect<Z | Z2 | Z3, E2 | E | E3, R | R2 | R3>\n>(2, <A, E, Z, E2, R, Z2, R2, Z3, E3, R3>(\n  self: Take.Take<A, E>,\n  { onEnd, onFailure, onSuccess }: {\n    readonly onEnd: Effect.Effect<Z, E2, R>\n    readonly onFailure: (cause: Cause.Cause<E>) => Effect.Effect<Z2, E2, R2>\n    readonly onSuccess: (chunk: Chunk.Chunk<A>) => Effect.Effect<Z3, E3, R3>\n  }\n): Effect.Effect<Z | Z2 | Z3, E2 | E | E3, R | R2 | R3> =>\n  Exit.matchEffect(self.exit, {\n    onFailure: (cause) =>\n      Option.match<Cause.Cause<E>, Effect.Effect<Z | Z2, E2 | E, R | R2>>(Cause.flipCauseOption(cause), {\n        onNone: () => onEnd,\n        onSome: onFailure\n      }),\n    onSuccess\n  }))\n\n/** @internal */\nexport const map = dual<\n  <A, B>(f: (a: A) => B) => <E>(self: Take.Take<A, E>) => Take.Take<B, E>,\n  <A, E, B>(self: Take.Take<A, E>, f: (a: A) => B) => Take.Take<B, E>\n>(\n  2,\n  <A, E, B>(self: Take.Take<A, E>, f: (a: A) => B): Take.Take<B, E> =>\n    new TakeImpl(pipe(self.exit, Exit.map(Chunk.map(f))))\n)\n\n/** @internal */\nexport const of = <A>(value: A): Take.Take<A> => new TakeImpl(Exit.succeed(Chunk.of(value)))\n\n/** @internal */\nexport const tap = dual<\n  <A, X, E2, R>(\n    f: (chunk: Chunk.Chunk<A>) => Effect.Effect<X, E2, R>\n  ) => <E>(self: Take.Take<A, E>) => Effect.Effect<void, E2 | E, R>,\n  <A, E, X, E2, R>(\n    self: Take.Take<A, E>,\n    f: (chunk: Chunk.Chunk<A>) => Effect.Effect<X, E2, R>\n  ) => Effect.Effect<void, E2 | E, R>\n>(2, <A, E, X, E2, R>(\n  self: Take.Take<A, E>,\n  f: (chunk: Chunk.Chunk<A>) => Effect.Effect<X, E2, R>\n): Effect.Effect<void, E2 | E, R> => pipe(self.exit, Exit.forEachEffect(f), Effect.asVoid))\n"
  },
  {
    "path": "packages/effect/src/internal/testing/sleep.ts",
    "content": "import type * as Deferred from \"../../Deferred.js\"\nimport type * as Duration from \"../../Duration.js\"\nimport type * as FiberId from \"../../FiberId.js\"\n\n/**\n * `Sleep` represents the state of a scheduled effect, including the time the\n * effect is scheduled to run, a promise that can be completed to resume\n * execution of the effect, and the fiber executing the effect.\n *\n * @internal\n */\nexport interface Sleep {\n  readonly duration: Duration.Duration\n  readonly deferred: Deferred.Deferred<void>\n  readonly fiberId: FiberId.FiberId\n}\n\n/** @internal */\nexport const make = (\n  duration: Duration.Duration,\n  deferred: Deferred.Deferred<void>,\n  fiberId: FiberId.FiberId\n): Sleep => ({\n  duration,\n  deferred,\n  fiberId\n})\n"
  },
  {
    "path": "packages/effect/src/internal/testing/suspendedWarningData.ts",
    "content": "import type * as Fiber from \"../../Fiber.js\"\n\n/** @internal */\nexport type SuspendedWarningData = Start | Pending | Done\n\n/** @internal */\nexport const OP_SUSPENDED_WARNING_DATA_START = \"Start\" as const\n\n/** @internal */\nexport type OP_SUSPENDED_WARNING_DATA_START = typeof OP_SUSPENDED_WARNING_DATA_START\n\n/** @internal */\nexport const OP_SUSPENDED_WARNING_DATA_PENDING = \"Pending\" as const\n\n/** @internal */\nexport type OP_SUSPENDED_WARNING_DATA_PENDING = typeof OP_SUSPENDED_WARNING_DATA_PENDING\n\n/** @internal */\nexport const OP_SUSPENDED_WARNING_DATA_DONE = \"Done\" as const\n\n/** @internal */\nexport type OP_SUSPENDED_WARNING_DATA_DONE = typeof OP_SUSPENDED_WARNING_DATA_DONE\n\n/** @internal */\nexport interface Start {\n  readonly _tag: OP_SUSPENDED_WARNING_DATA_START\n}\n\n/** @internal */\nexport interface Pending {\n  readonly _tag: OP_SUSPENDED_WARNING_DATA_PENDING\n  readonly fiber: Fiber.Fiber<void, Error>\n}\n\n/** @internal */\nexport interface Done {\n  readonly _tag: OP_SUSPENDED_WARNING_DATA_DONE\n}\n\n/**\n * State indicating that a test has not adjusted the clock.\n *\n * @internal\n */\nexport const start: SuspendedWarningData = {\n  _tag: OP_SUSPENDED_WARNING_DATA_START\n}\n\n/**\n * State indicating that a test has adjusted the clock but a fiber is still\n * running with a reference to the fiber that will display the warning\n * message.\n *\n * @internal\n */\nexport const pending = (fiber: Fiber.Fiber<void, Error>): SuspendedWarningData => {\n  return {\n    _tag: OP_SUSPENDED_WARNING_DATA_PENDING,\n    fiber\n  }\n}\n\n/**\n * State indicating that the warning message has already been displayed.\n *\n * @internal\n */\nexport const done: SuspendedWarningData = {\n  _tag: OP_SUSPENDED_WARNING_DATA_DONE\n}\n\n/** @internal */\nexport const isStart = (self: SuspendedWarningData): self is Start => {\n  return self._tag === OP_SUSPENDED_WARNING_DATA_START\n}\n\n/** @internal */\nexport const isPending = (self: SuspendedWarningData): self is Pending => {\n  return self._tag === OP_SUSPENDED_WARNING_DATA_PENDING\n}\n\n/** @internal */\nexport const isDone = (self: SuspendedWarningData): self is Done => {\n  return self._tag === OP_SUSPENDED_WARNING_DATA_DONE\n}\n"
  },
  {
    "path": "packages/effect/src/internal/testing/warningData.ts",
    "content": "import type * as Fiber from \"../../Fiber.js\"\n\n/**\n * `WarningData` describes the state of the warning message that is displayed\n * if a test is using time by is not advancing the `TestClock`. The possible\n * states are `Start` if a test has not used time, `Pending` if a test has\n * used time but has not adjusted the `TestClock`, and `Done` if a test has\n * adjusted the `TestClock` or the warning message has already been displayed.\n *\n * @internal\n */\nexport type WarningData = Start | Pending | Done\n\n/** @internal */\nexport const OP_WARNING_DATA_START = \"Start\" as const\n\n/** @internal */\nexport type OP_WARNING_DATA_START = typeof OP_WARNING_DATA_START\n\n/** @internal */\nexport const OP_WARNING_DATA_PENDING = \"Pending\" as const\n\n/** @internal */\nexport type OP_WARNING_DATA_PENDING = typeof OP_WARNING_DATA_PENDING\n\n/** @internal */\nexport const OP_WARNING_DATA_DONE = \"Done\" as const\n\n/** @internal */\nexport type OP_WARNING_DATA_DONE = typeof OP_WARNING_DATA_DONE\n\n/** @internal */\nexport interface Start {\n  readonly _tag: OP_WARNING_DATA_START\n}\n\n/** @internal */\nexport interface Pending {\n  readonly _tag: OP_WARNING_DATA_PENDING\n  readonly fiber: Fiber.Fiber<void, Error>\n}\n\n/** @internal */\nexport interface Done {\n  readonly _tag: OP_WARNING_DATA_DONE\n}\n\n/**\n * State indicating that a test has not used time.\n *\n * @internal\n */\nexport const start: WarningData = {\n  _tag: OP_WARNING_DATA_START\n}\n\n/**\n * State indicating that a test has used time but has not adjusted the\n * `TestClock` with a reference to the fiber that will display the warning\n * message.\n *\n * @internal\n */\nexport const pending = (fiber: Fiber.Fiber<void, Error>): WarningData => {\n  return {\n    _tag: OP_WARNING_DATA_PENDING,\n    fiber\n  }\n}\n\n/**\n * State indicating that a test has used time or the warning message has\n * already been displayed.\n *\n * @internal\n */\nexport const done: WarningData = {\n  _tag: OP_WARNING_DATA_DONE\n}\n\n/** @internal */\nexport const isStart = (self: WarningData): self is Start => {\n  return self._tag === OP_WARNING_DATA_START\n}\n\n/** @internal */\nexport const isPending = (self: WarningData): self is Pending => {\n  return self._tag === OP_WARNING_DATA_PENDING\n}\n\n/** @internal */\nexport const isDone = (self: WarningData): self is Done => {\n  return self._tag === OP_WARNING_DATA_DONE\n}\n"
  },
  {
    "path": "packages/effect/src/internal/tracer.ts",
    "content": "/**\n * @since 2.0.0\n */\nimport * as Context from \"../Context.js\"\nimport type * as Exit from \"../Exit.js\"\nimport { constFalse } from \"../Function.js\"\nimport type * as Option from \"../Option.js\"\nimport type * as Tracer from \"../Tracer.js\"\n\n/** @internal */\nexport const TracerTypeId: Tracer.TracerTypeId = Symbol.for(\"effect/Tracer\") as Tracer.TracerTypeId\n\n/** @internal */\nexport const make = (options: Omit<Tracer.Tracer, Tracer.TracerTypeId>): Tracer.Tracer => ({\n  [TracerTypeId]: TracerTypeId,\n  ...options\n})\n\n/** @internal */\nexport const tracerTag = Context.GenericTag<Tracer.Tracer>(\"effect/Tracer\")\n\n/** @internal */\nexport const spanTag = Context.GenericTag<Tracer.ParentSpan, Tracer.AnySpan>(\"effect/ParentSpan\")\n\nconst randomHexString = (function() {\n  const characters = \"abcdef0123456789\"\n  const charactersLength = characters.length\n  return function(length: number) {\n    let result = \"\"\n    for (let i = 0; i < length; i++) {\n      result += characters.charAt(Math.floor(Math.random() * charactersLength))\n    }\n    return result\n  }\n})()\n\n/** @internal */\nexport class NativeSpan implements Tracer.Span {\n  readonly _tag = \"Span\"\n  readonly spanId: string\n  readonly traceId: string = \"native\"\n  readonly sampled = true\n\n  status: Tracer.SpanStatus\n  attributes: Map<string, unknown>\n  events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]> = []\n  links: Array<Tracer.SpanLink>\n\n  constructor(\n    readonly name: string,\n    readonly parent: Option.Option<Tracer.AnySpan>,\n    readonly context: Context.Context<never>,\n    links: Iterable<Tracer.SpanLink>,\n    readonly startTime: bigint,\n    readonly kind: Tracer.SpanKind\n  ) {\n    this.status = {\n      _tag: \"Started\",\n      startTime\n    }\n    this.attributes = new Map()\n    this.traceId = parent._tag === \"Some\" ? parent.value.traceId : randomHexString(32)\n    this.spanId = randomHexString(16)\n    this.links = Array.from(links)\n  }\n\n  end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {\n    this.status = {\n      _tag: \"Ended\",\n      endTime,\n      exit,\n      startTime: this.status.startTime\n    }\n  }\n\n  attribute(key: string, value: unknown): void {\n    this.attributes.set(key, value)\n  }\n\n  event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {\n    this.events.push([name, startTime, attributes ?? {}])\n  }\n\n  addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {\n    // eslint-disable-next-line no-restricted-syntax\n    this.links.push(...links)\n  }\n}\n\n/** @internal */\nexport const nativeTracer: Tracer.Tracer = make({\n  span: (name, parent, context, links, startTime, kind) =>\n    new NativeSpan(\n      name,\n      parent,\n      context,\n      links,\n      startTime,\n      kind\n    ),\n  context: (f) => f()\n})\n\n/** @internal */\nexport const externalSpan = (options: {\n  readonly spanId: string\n  readonly traceId: string\n  readonly sampled?: boolean | undefined\n  readonly context?: Context.Context<never> | undefined\n}): Tracer.ExternalSpan => ({\n  _tag: \"ExternalSpan\",\n  spanId: options.spanId,\n  traceId: options.traceId,\n  sampled: options.sampled ?? true,\n  context: options.context ?? Context.empty()\n})\n\n/** @internal */\nexport const addSpanStackTrace = (options: Tracer.SpanOptions | undefined): Tracer.SpanOptions => {\n  if (options?.captureStackTrace === false) {\n    return options\n  } else if (options?.captureStackTrace !== undefined && typeof options.captureStackTrace !== \"boolean\") {\n    return options\n  }\n  const limit = Error.stackTraceLimit\n  Error.stackTraceLimit = 3\n  const traceError = new Error()\n  Error.stackTraceLimit = limit\n  let cache: false | string = false\n  return {\n    ...options,\n    captureStackTrace: () => {\n      if (cache !== false) {\n        return cache\n      }\n      if (traceError.stack !== undefined) {\n        const stack = traceError.stack.split(\"\\n\")\n        if (stack[3] !== undefined) {\n          cache = stack[3].trim()\n          return cache\n        }\n      }\n    }\n  }\n}\n\n/** @internal */\nexport const DisablePropagation = Context.Reference<Tracer.DisablePropagation>()(\"effect/Tracer/DisablePropagation\", {\n  defaultValue: constFalse\n})\n"
  },
  {
    "path": "packages/effect/src/internal/trie.ts",
    "content": "import * as Equal from \"../Equal.js\"\nimport { dual, identity, pipe } from \"../Function.js\"\nimport * as Hash from \"../Hash.js\"\nimport { format, NodeInspectSymbol, toJSON } from \"../Inspectable.js\"\nimport * as Option from \"../Option.js\"\nimport type * as Ordering from \"../Ordering.js\"\nimport { pipeArguments } from \"../Pipeable.js\"\nimport { hasProperty } from \"../Predicate.js\"\nimport type * as TR from \"../Trie.js\"\nimport type { NoInfer } from \"../Types.js\"\n\nconst TrieSymbolKey = \"effect/Trie\"\n\n/** @internal */\nexport const TrieTypeId: TR.TypeId = Symbol.for(TrieSymbolKey) as TR.TypeId\n\ntype TraversalMap<K, V, A> = (k: K, v: V) => A\n\ntype TraversalFilter<K, V> = (k: K, v: V) => boolean\n\n/** @internal */\nexport interface TrieImpl<in out V> extends TR.Trie<V> {\n  readonly _root: Node<V> | undefined\n  readonly _count: number\n}\n\nconst trieVariance = {\n  /* c8 ignore next */\n  _Value: (_: never) => _\n}\n\nconst TrieProto: TR.Trie<unknown> = {\n  [TrieTypeId]: trieVariance,\n  [Symbol.iterator]<V>(this: TrieImpl<V>): Iterator<[string, V]> {\n    return new TrieIterator(this, (k, v) => [k, v], () => true)\n  },\n  [Hash.symbol](this: TR.Trie<unknown>): number {\n    let hash = Hash.hash(TrieSymbolKey)\n    for (const item of this) {\n      hash ^= pipe(Hash.hash(item[0]), Hash.combine(Hash.hash(item[1])))\n    }\n    return Hash.cached(this, hash)\n  },\n  [Equal.symbol]<V>(this: TrieImpl<V>, that: unknown): boolean {\n    if (isTrie(that)) {\n      const entries = Array.from(that)\n      return Array.from(this).every((itemSelf, i) => {\n        const itemThat = entries[i]\n        return Equal.equals(itemSelf[0], itemThat[0]) && Equal.equals(itemSelf[1], itemThat[1])\n      })\n    }\n    return false\n  },\n  toString() {\n    return format(this.toJSON())\n  },\n  toJSON() {\n    return {\n      _id: \"Trie\",\n      values: Array.from(this).map(toJSON)\n    }\n  },\n  [NodeInspectSymbol]() {\n    return this.toJSON()\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makeImpl = <V>(root: Node<V> | undefined): TrieImpl<V> => {\n  const trie = Object.create(TrieProto)\n  trie._root = root\n  trie._count = root?.count ?? 0\n  return trie\n}\n\nclass TrieIterator<in out V, out T> implements IterableIterator<T> {\n  stack: Array<[Node<V>, string, boolean]> = []\n\n  constructor(\n    readonly trie: TrieImpl<V>,\n    readonly f: TraversalMap<string, V, T>,\n    readonly filter: TraversalFilter<string, V>\n  ) {\n    const root = trie._root !== undefined ? trie._root : undefined\n    if (root !== undefined) {\n      this.stack.push([root, \"\", false])\n    }\n  }\n\n  next(): IteratorResult<T> {\n    while (this.stack.length > 0) {\n      const [node, keyString, isAdded] = this.stack.pop()!\n\n      if (isAdded) {\n        const value = node.value\n        if (value !== undefined) {\n          const key = keyString + node.key\n          if (this.filter(key, value)) {\n            return { done: false, value: this.f(key, value) }\n          }\n        }\n      } else {\n        this.addToStack(node, keyString)\n      }\n    }\n\n    return { done: true, value: undefined }\n  }\n\n  addToStack(node: Node<V>, keyString: string) {\n    if (node.right !== undefined) {\n      this.stack.push([node.right, keyString, false])\n    }\n    if (node.mid !== undefined) {\n      this.stack.push([node.mid, keyString + node.key, false])\n    }\n    this.stack.push([node, keyString, true])\n    if (node.left !== undefined) {\n      this.stack.push([node.left, keyString, false])\n    }\n  }\n\n  [Symbol.iterator](): IterableIterator<T> {\n    return new TrieIterator(this.trie, this.f, this.filter)\n  }\n}\n\n/** @internal */\nexport const isTrie: {\n  <V>(u: Iterable<readonly [string, V]>): u is TR.Trie<V>\n  (u: unknown): u is TR.Trie<unknown>\n} = (u: unknown): u is TR.Trie<unknown> => hasProperty(u, TrieTypeId)\n\n/** @internal */\nexport const empty = <V = never>(): TR.Trie<V> => makeImpl<V>(undefined)\n\n/** @internal */\nexport const fromIterable = <V>(entries: Iterable<readonly [string, V]>) => {\n  let trie = empty<V>()\n  for (const [key, value] of entries) {\n    trie = insert(trie, key, value)\n  }\n  return trie\n}\n\n/** @internal */\nexport const make = <Entries extends Array<readonly [string, any]>>(...entries: Entries): TR.Trie<\n  Entries[number] extends readonly [any, infer V] ? V : never\n> => {\n  return fromIterable(entries)\n}\n\n/** @internal */\nexport const insert = dual<\n  <V>(key: string, value: V) => (self: TR.Trie<V>) => TR.Trie<V>,\n  <V>(self: TR.Trie<V>, key: string, value: V) => TR.Trie<V>\n>(3, <V>(self: TR.Trie<V>, key: string, value: V) => {\n  if (key.length === 0) return self\n\n  // -1:left | 0:mid | 1:right\n  const dStack: Array<Ordering.Ordering> = []\n  const nStack: Array<Node<V>> = []\n  let n: Node<V> = (self as TrieImpl<V>)._root ?? {\n    key: key[0],\n    count: 0\n  }\n  const count = n.count + 1\n  let cIndex = 0\n\n  while (cIndex < key.length) {\n    const c = key[cIndex]\n    nStack.push(n)\n    if (c > n.key) {\n      dStack.push(1)\n      if (n.right === undefined) {\n        n = { key: c, count }\n      } else {\n        n = n.right\n      }\n    } else if (c < n.key) {\n      dStack.push(-1)\n      if (n.left === undefined) {\n        n = { key: c, count }\n      } else {\n        n = n.left\n      }\n    } else {\n      if (cIndex === key.length - 1) {\n        n.value = value\n      } else if (n.mid === undefined) {\n        dStack.push(0)\n        n = { key: key[cIndex + 1], count }\n      } else {\n        dStack.push(0)\n        n = n.mid\n      }\n\n      cIndex += 1\n    }\n  }\n\n  // Rebuild path to leaf node (Path-copying immutability)\n  for (let s = nStack.length - 2; s >= 0; --s) {\n    const n2 = nStack[s]\n    const d = dStack[s]\n    if (d === -1) {\n      // left\n      nStack[s] = {\n        key: n2.key,\n        count,\n        value: n2.value,\n        left: nStack[s + 1],\n        mid: n2.mid,\n        right: n2.right\n      }\n    } else if (d === 1) {\n      // right\n      nStack[s] = {\n        key: n2.key,\n        count,\n        value: n2.value,\n        left: n2.left,\n        mid: n2.mid,\n        right: nStack[s + 1]\n      }\n    } else {\n      // mid\n      nStack[s] = {\n        key: n2.key,\n        count,\n        value: n2.value,\n        left: n2.left,\n        mid: nStack[s + 1],\n        right: n2.right\n      }\n    }\n  }\n\n  nStack[0].count = count\n  return makeImpl(nStack[0])\n})\n\n/** @internal */\nexport const size = <V>(self: TR.Trie<V>): number => (self as TrieImpl<V>)._root?.count ?? 0\n\n/** @internal */\nexport const isEmpty = <V>(self: TR.Trie<V>): boolean => size(self) === 0\n\n/** @internal */\nexport const keys = <V>(self: TR.Trie<V>): IterableIterator<string> =>\n  new TrieIterator(self as TrieImpl<V>, (key) => key, () => true)\n\n/** @internal */\nexport const values = <V>(self: TR.Trie<V>): IterableIterator<V> =>\n  new TrieIterator(self as TrieImpl<V>, (_, value) => value, () => true)\n\n/** @internal */\nexport const entries = <V>(self: TR.Trie<V>): IterableIterator<[string, V]> =>\n  new TrieIterator(self as TrieImpl<V>, (key, value) => [key, value], () => true)\n\n/** @internal */\nexport const reduce = dual<\n  <Z, V>(\n    zero: Z,\n    f: (accumulator: Z, value: V, key: string) => Z\n  ) => (self: TR.Trie<V>) => Z,\n  <Z, V>(self: TR.Trie<V>, zero: Z, f: (accumulator: Z, value: V, key: string) => Z) => Z\n>(3, (self, zero, f) => {\n  let accumulator = zero\n  for (const entry of self) {\n    accumulator = f(accumulator, entry[1], entry[0])\n  }\n  return accumulator\n})\n\n/** @internal */\nexport const map = dual<\n  <A, V>(f: (value: V, key: string) => A) => (self: TR.Trie<V>) => TR.Trie<A>,\n  <V, A>(self: TR.Trie<V>, f: (value: V, key: string) => A) => TR.Trie<A>\n>(2, (self, f) =>\n  reduce(\n    self,\n    empty(),\n    (trie, value, key) => insert(trie, key, f(value, key))\n  ))\n\n/** @internal */\nexport const filter: {\n  <A, B extends A>(f: (a: NoInfer<A>, k: string) => a is B): (self: TR.Trie<A>) => TR.Trie<B>\n  <A>(f: (a: NoInfer<A>, k: string) => boolean): (self: TR.Trie<A>) => TR.Trie<A>\n  <A, B extends A>(self: TR.Trie<A>, f: (a: A, k: string) => a is B): TR.Trie<B>\n  <A>(self: TR.Trie<A>, f: (a: A, k: string) => boolean): TR.Trie<A>\n} = dual(\n  2,\n  <A>(self: TR.Trie<A>, f: (a: A, k: string) => boolean): TR.Trie<A> =>\n    reduce(\n      self,\n      empty(),\n      (trie, value, key) => f(value, key) ? insert(trie, key, value) : trie\n    )\n)\n\n/** @internal */\nexport const filterMap = dual<\n  <A, B>(\n    f: (value: A, key: string) => Option.Option<B>\n  ) => (self: TR.Trie<A>) => TR.Trie<B>,\n  <A, B>(self: TR.Trie<A>, f: (value: A, key: string) => Option.Option<B>) => TR.Trie<B>\n>(2, (self, f) =>\n  reduce(\n    self,\n    empty(),\n    (trie, value, key) => {\n      const option = f(value, key)\n      return Option.isSome(option) ? insert(trie, key, option.value) : trie\n    }\n  ))\n\n/** @internal */\nexport const compact = <A>(self: TR.Trie<Option.Option<A>>) => filterMap(self, identity)\n\n/** @internal */\nexport const forEach = dual<\n  <V>(f: (value: V, key: string) => void) => (self: TR.Trie<V>) => void,\n  <V>(self: TR.Trie<V>, f: (value: V, key: string) => void) => void\n>(2, (self, f) => reduce(self, void 0 as void, (_, value, key) => f(value, key)))\n\n/** @internal */\nexport const keysWithPrefix = dual<\n  (prefix: string) => <V>(self: TR.Trie<V>) => IterableIterator<string>,\n  <V>(self: TR.Trie<V>, prefix: string) => IterableIterator<string>\n>(\n  2,\n  <V>(self: TR.Trie<V>, prefix: string): IterableIterator<string> =>\n    new TrieIterator(self as TrieImpl<V>, (key) => key, (key) => key.startsWith(prefix))\n)\n\n/** @internal */\nexport const valuesWithPrefix = dual<\n  (prefix: string) => <V>(self: TR.Trie<V>) => IterableIterator<V>,\n  <V>(self: TR.Trie<V>, prefix: string) => IterableIterator<V>\n>(\n  2,\n  <V>(self: TR.Trie<V>, prefix: string): IterableIterator<V> =>\n    new TrieIterator(self as TrieImpl<V>, (_, value) => value, (key) => key.startsWith(prefix))\n)\n\n/** @internal */\nexport const entriesWithPrefix = dual<\n  (prefix: string) => <V>(self: TR.Trie<V>) => IterableIterator<[string, V]>,\n  <V>(self: TR.Trie<V>, prefix: string) => IterableIterator<[string, V]>\n>(\n  2,\n  <V>(self: TR.Trie<V>, prefix: string): IterableIterator<[string, V]> =>\n    new TrieIterator(self as TrieImpl<V>, (key, value) => [key, value], (key) => key.startsWith(prefix))\n)\n\n/** @internal */\nexport const toEntriesWithPrefix = dual<\n  (prefix: string) => <V>(self: TR.Trie<V>) => Array<[string, V]>,\n  <V>(self: TR.Trie<V>, prefix: string) => Array<[string, V]>\n>(\n  2,\n  <V>(self: TR.Trie<V>, prefix: string): Array<[string, V]> => Array.from(entriesWithPrefix(self, prefix))\n)\n\n/** @internal */\nexport const get = dual<\n  (key: string) => <V>(self: TR.Trie<V>) => Option.Option<V>,\n  <V>(self: TR.Trie<V>, key: string) => Option.Option<V>\n>(\n  2,\n  <V>(self: TR.Trie<V>, key: string) => {\n    let n: Node<V> | undefined = (self as TrieImpl<V>)._root\n    if (n === undefined || key.length === 0) return Option.none()\n    let cIndex = 0\n    while (cIndex < key.length) {\n      const c = key[cIndex]\n      if (c > n.key) {\n        if (n.right === undefined) {\n          return Option.none()\n        } else {\n          n = n.right\n        }\n      } else if (c < n.key) {\n        if (n.left === undefined) {\n          return Option.none()\n        } else {\n          n = n.left\n        }\n      } else {\n        if (cIndex === key.length - 1) {\n          return Option.fromNullable(n.value)\n        } else {\n          if (n.mid === undefined) {\n            return Option.none()\n          } else {\n            n = n.mid\n            cIndex += 1\n          }\n        }\n      }\n    }\n    return Option.none()\n  }\n)\n\n/** @internal */\nexport const has = dual<\n  (key: string) => <V>(self: TR.Trie<V>) => boolean,\n  <V>(self: TR.Trie<V>, key: string) => boolean\n>(2, (self, key) => Option.isSome(get(self, key)))\n\n/** @internal */\nexport const unsafeGet = dual<\n  (key: string) => <V>(self: TR.Trie<V>) => V,\n  <V>(self: TR.Trie<V>, key: string) => V\n>(2, (self, key) => {\n  const element = get(self, key)\n  if (Option.isNone(element)) {\n    throw new Error(\"Expected trie to contain key\")\n  }\n  return element.value\n})\n\n/** @internal */\nexport const remove = dual<\n  (key: string) => <V>(self: TR.Trie<V>) => TR.Trie<V>,\n  <V>(self: TR.Trie<V>, key: string) => TR.Trie<V>\n>(\n  2,\n  <V>(self: TR.Trie<V>, key: string) => {\n    let n: Node<V> | undefined = (self as TrieImpl<V>)._root\n    if (n === undefined || key.length === 0) return self\n\n    const count = n.count - 1\n    // -1:left | 0:mid | 1:right\n    const dStack: Array<Ordering.Ordering> = []\n    const nStack: Array<Node<V>> = []\n\n    let cIndex = 0\n    while (cIndex < key.length) {\n      const c = key[cIndex]\n      if (c > n.key) {\n        if (n.right === undefined) {\n          return self\n        } else {\n          nStack.push(n)\n          dStack.push(1)\n          n = n.right\n        }\n      } else if (c < n.key) {\n        if (n.left === undefined) {\n          return self\n        } else {\n          nStack.push(n)\n          dStack.push(-1)\n          n = n.left\n        }\n      } else {\n        if (cIndex === key.length - 1) {\n          if (n.value !== undefined) {\n            nStack.push(n)\n            dStack.push(0)\n            cIndex += 1\n          } else {\n            return self\n          }\n        } else {\n          if (n.mid === undefined) {\n            return self\n          } else {\n            nStack.push(n)\n            dStack.push(0)\n            n = n.mid\n            cIndex += 1\n          }\n        }\n      }\n    }\n\n    const removeNode = nStack[nStack.length - 1]\n    nStack[nStack.length - 1] = {\n      key: removeNode.key,\n      count,\n      left: removeNode.left,\n      mid: removeNode.mid,\n      right: removeNode.right\n    }\n\n    // Rebuild path to leaf node (Path-copying immutability)\n    for (let s = nStack.length - 2; s >= 0; --s) {\n      const n2 = nStack[s]\n      const d = dStack[s]\n      const child = nStack[s + 1]\n      const nc = child.left === undefined && child.mid === undefined && child.right === undefined ? undefined : child\n      if (d === -1) {\n        // left\n        nStack[s] = {\n          key: n2.key,\n          count,\n          value: n2.value,\n          left: nc,\n          mid: n2.mid,\n          right: n2.right\n        }\n      } else if (d === 1) {\n        // right\n        nStack[s] = {\n          key: n2.key,\n          count,\n          value: n2.value,\n          left: n2.left,\n          mid: n2.mid,\n          right: nc\n        }\n      } else {\n        // mid\n        nStack[s] = {\n          key: n2.key,\n          count,\n          value: n2.value,\n          left: n2.left,\n          mid: nc,\n          right: n2.right\n        }\n      }\n    }\n\n    nStack[0].count = count\n    return makeImpl(nStack[0])\n  }\n)\n\n/** @internal */\nexport const removeMany = dual<\n  (keys: Iterable<string>) => <V>(self: TR.Trie<V>) => TR.Trie<V>,\n  <V>(self: TR.Trie<V>, keys: Iterable<string>) => TR.Trie<V>\n>(2, (self, keys) => {\n  let trie = self\n  for (const key of keys) {\n    trie = remove(key)(trie)\n  }\n  return trie\n})\n\n/** @internal */\nexport const insertMany = dual<\n  <V>(iter: Iterable<[string, V]>) => (self: TR.Trie<V>) => TR.Trie<V>,\n  <V>(self: TR.Trie<V>, iter: Iterable<[string, V]>) => TR.Trie<V>\n>(2, (self, iter) => {\n  let trie = self\n  for (const [key, value] of iter) {\n    trie = insert(key, value)(trie)\n  }\n  return trie\n})\n\n/** @internal */\nexport const modify = dual<\n  <V>(key: string, f: (v: V) => V) => (self: TR.Trie<V>) => TR.Trie<V>,\n  <V>(self: TR.Trie<V>, key: string, f: (v: V) => V) => TR.Trie<V>\n>(\n  3,\n  <V>(self: TR.Trie<V>, key: string, f: (v: V) => V): TR.Trie<V> => {\n    let n: Node<V> | undefined = (self as TrieImpl<V>)._root\n    if (n === undefined || key.length === 0) return self\n\n    // -1:left | 0:mid | 1:right\n    const dStack: Array<Ordering.Ordering> = []\n    const nStack: Array<Node<V>> = []\n\n    let cIndex = 0\n    while (cIndex < key.length) {\n      const c = key[cIndex]\n      if (c > n.key) {\n        if (n.right === undefined) {\n          return self\n        } else {\n          nStack.push(n)\n          dStack.push(1)\n          n = n.right\n        }\n      } else if (c < n.key) {\n        if (n.left === undefined) {\n          return self\n        } else {\n          nStack.push(n)\n          dStack.push(-1)\n          n = n.left\n        }\n      } else {\n        if (cIndex === key.length - 1) {\n          if (n.value !== undefined) {\n            nStack.push(n)\n            dStack.push(0)\n            cIndex += 1\n          } else {\n            return self\n          }\n        } else {\n          if (n.mid === undefined) {\n            return self\n          } else {\n            nStack.push(n)\n            dStack.push(0)\n            n = n.mid\n            cIndex += 1\n          }\n        }\n      }\n    }\n\n    const updateNode = nStack[nStack.length - 1]\n    if (updateNode.value === undefined) {\n      return self\n    }\n\n    nStack[nStack.length - 1] = {\n      key: updateNode.key,\n      count: updateNode.count,\n      value: f(updateNode.value), // Update\n      left: updateNode.left,\n      mid: updateNode.mid,\n      right: updateNode.right\n    }\n\n    // Rebuild path to leaf node (Path-copying immutability)\n    for (let s = nStack.length - 2; s >= 0; --s) {\n      const n2 = nStack[s]\n      const d = dStack[s]\n      const child = nStack[s + 1]\n      if (d === -1) {\n        // left\n        nStack[s] = {\n          key: n2.key,\n          count: n2.count,\n          value: n2.value,\n          left: child,\n          mid: n2.mid,\n          right: n2.right\n        }\n      } else if (d === 1) {\n        // right\n        nStack[s] = {\n          key: n2.key,\n          count: n2.count,\n          value: n2.value,\n          left: n2.left,\n          mid: n2.mid,\n          right: child\n        }\n      } else {\n        // mid\n        nStack[s] = {\n          key: n2.key,\n          count: n2.count,\n          value: n2.value,\n          left: n2.left,\n          mid: child,\n          right: n2.right\n        }\n      }\n    }\n\n    return makeImpl(nStack[0])\n  }\n)\n\n/** @internal */\nexport const longestPrefixOf = dual<\n  (key: string) => <V>(self: TR.Trie<V>) => Option.Option<[string, V]>,\n  <V>(self: TR.Trie<V>, key: string) => Option.Option<[string, V]>\n>(\n  2,\n  <V>(self: TR.Trie<V>, key: string) => {\n    let n: Node<V> | undefined = (self as TrieImpl<V>)._root\n    if (n === undefined || key.length === 0) return Option.none()\n    let longestPrefixNode: [string, V] | undefined = undefined\n    let cIndex = 0\n    while (cIndex < key.length) {\n      const c = key[cIndex]\n      if (n.value !== undefined) {\n        longestPrefixNode = [key.slice(0, cIndex + 1), n.value]\n      }\n\n      if (c > n.key) {\n        if (n.right === undefined) {\n          break\n        } else {\n          n = n.right\n        }\n      } else if (c < n.key) {\n        if (n.left === undefined) {\n          break\n        } else {\n          n = n.left\n        }\n      } else {\n        if (n.mid === undefined) {\n          break\n        } else {\n          n = n.mid\n          cIndex += 1\n        }\n      }\n    }\n\n    return Option.fromNullable(longestPrefixNode)\n  }\n)\n\ninterface Node<V> {\n  key: string\n  count: number\n  value?: V | undefined\n  left?: Node<V> | undefined\n  mid?: Node<V> | undefined\n  right?: Node<V> | undefined\n}\n"
  },
  {
    "path": "packages/effect/src/internal/version.ts",
    "content": "let moduleVersion = \"3.21.0\"\n\nexport const getCurrentVersion = () => moduleVersion\n\nexport const setCurrentVersion = (version: string) => {\n  moduleVersion = version\n}\n"
  },
  {
    "path": "packages/effect/test/Array.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertSome, deepStrictEqual, strictEqual, throws } from \"@effect/vitest/utils\"\nimport {\n  Array as Arr,\n  Either,\n  FastCheck as fc,\n  identity,\n  Number as Num,\n  Option,\n  Order,\n  pipe,\n  type Predicate,\n  String as Str\n} from \"effect\"\n\nconst symA = Symbol.for(\"a\")\nconst symB = Symbol.for(\"b\")\nconst symC = Symbol.for(\"c\")\n\nconst double = (n: number) => n * 2\n\ndescribe(\"Array\", () => {\n  it(\"of\", () => {\n    deepStrictEqual(Arr.of(1), [1])\n  })\n\n  it(\"fromIterable/Array should return the same reference if the iterable is an Array\", () => {\n    const i = [1, 2, 3]\n    strictEqual(Arr.fromIterable(i), i)\n  })\n\n  it(\"fromIterable/Iterable\", () => {\n    deepStrictEqual(Arr.fromIterable(new Set([1, 2, 3])), [1, 2, 3])\n  })\n\n  it(\"ensure\", () => {\n    deepStrictEqual(Arr.ensure(1), [1])\n    deepStrictEqual(Arr.ensure(null), [null])\n    deepStrictEqual(Arr.ensure([1]), [1])\n    deepStrictEqual(Arr.ensure([1, 2]), [1, 2])\n    deepStrictEqual(Arr.ensure(new Set([1, 2])), [new Set([1, 2])])\n  })\n\n  describe(\"iterable inputs\", () => {\n    it(\"prepend\", () => {\n      deepStrictEqual(pipe([1, 2, 3], Arr.prepend(0)), [0, 1, 2, 3])\n      deepStrictEqual(pipe([[2]], Arr.prepend([1])), [[1], [2]])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.prepend(0)), [0, 1, 2, 3])\n      deepStrictEqual(pipe(new Set([[2]]), Arr.prepend([1])), [[1], [2]])\n    })\n\n    it(\"prependAll\", () => {\n      deepStrictEqual(pipe([3, 4], Arr.prependAll([1, 2])), [1, 2, 3, 4])\n\n      deepStrictEqual(pipe([3, 4], Arr.prependAll(new Set([1, 2]))), [1, 2, 3, 4])\n      deepStrictEqual(pipe(new Set([3, 4]), Arr.prependAll([1, 2])), [1, 2, 3, 4])\n    })\n\n    it(\"append\", () => {\n      deepStrictEqual(pipe([1, 2, 3], Arr.append(4)), [1, 2, 3, 4])\n      deepStrictEqual(pipe([[1]], Arr.append([2])), [[1], [2]])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.append(4)), [1, 2, 3, 4])\n      deepStrictEqual(pipe(new Set([[1]]), Arr.append([2])), [[1], [2]])\n    })\n\n    it(\"appendAll\", () => {\n      deepStrictEqual(pipe([1, 2], Arr.appendAll([3, 4])), [1, 2, 3, 4])\n\n      deepStrictEqual(pipe([1, 2], Arr.appendAll(new Set([3, 4]))), [1, 2, 3, 4])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.appendAll([3, 4])), [1, 2, 3, 4])\n    })\n\n    it(\"scan\", () => {\n      const f = (b: number, a: number) => b - a\n      deepStrictEqual(pipe([1, 2, 3], Arr.scan(10, f)), [10, 9, 7, 4])\n      deepStrictEqual(pipe([0], Arr.scan(10, f)), [10, 10])\n      deepStrictEqual(pipe([], Arr.scan(10, f)), [10])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.scan(10, f)), [10, 9, 7, 4])\n      deepStrictEqual(pipe(new Set([0]), Arr.scan(10, f)), [10, 10])\n      deepStrictEqual(pipe(new Set([]), Arr.scan(10, f)), [10])\n    })\n\n    it(\"scanRight\", () => {\n      const f = (b: number, a: number) => a - b\n      deepStrictEqual(pipe([1, 2, 3], Arr.scanRight(10, f)), [-8, 9, -7, 10])\n      deepStrictEqual(pipe([0], Arr.scanRight(10, f)), [-10, 10])\n      deepStrictEqual(pipe([], Arr.scanRight(10, f)), [10])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.scanRight(10, f)), [-8, 9, -7, 10])\n      deepStrictEqual(pipe(new Set([0]), Arr.scanRight(10, f)), [-10, 10])\n      deepStrictEqual(pipe(new Set([]), Arr.scanRight(10, f)), [10])\n    })\n\n    it(\"tail\", () => {\n      assertSome(Arr.tail([1, 2, 3]), [2, 3])\n      assertNone(Arr.tail([]))\n\n      assertSome(Arr.tail(new Set([1, 2, 3])), [2, 3])\n      assertNone(Arr.tail(new Set([])))\n    })\n\n    it(\"init\", () => {\n      assertSome(Arr.init([1, 2, 3]), [1, 2])\n      assertNone(Arr.init([]))\n\n      assertSome(Arr.init(new Set([1, 2, 3])), [1, 2])\n      assertNone(Arr.init(new Set([])))\n    })\n\n    it(\"take\", () => {\n      deepStrictEqual(pipe([1, 2, 3, 4], Arr.take(2)), [1, 2])\n      deepStrictEqual(pipe([1, 2, 3, 4], Arr.take(0)), [])\n      // out of bounds\n      deepStrictEqual(pipe([1, 2, 3, 4], Arr.take(-10)), [])\n      deepStrictEqual(pipe([1, 2, 3, 4], Arr.take(10)), [1, 2, 3, 4])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3, 4]), Arr.take(2)), [1, 2])\n      deepStrictEqual(pipe(new Set([1, 2, 3, 4]), Arr.take(0)), [])\n      // out of bounds\n      deepStrictEqual(pipe(new Set([1, 2, 3, 4]), Arr.take(-10)), [])\n      deepStrictEqual(pipe(new Set([1, 2, 3, 4]), Arr.take(10)), [1, 2, 3, 4])\n    })\n\n    it(\"takeRight\", () => {\n      deepStrictEqual(pipe(Arr.empty(), Arr.takeRight(0)), [])\n      deepStrictEqual(pipe([1, 2], Arr.takeRight(0)), [])\n      deepStrictEqual(pipe([1, 2], Arr.takeRight(1)), [2])\n      deepStrictEqual(pipe([1, 2], Arr.takeRight(2)), [1, 2])\n      // out of bound\n      deepStrictEqual(pipe(Arr.empty(), Arr.takeRight(1)), [])\n      deepStrictEqual(pipe(Arr.empty(), Arr.takeRight(-1)), [])\n      deepStrictEqual(pipe([1, 2], Arr.takeRight(3)), [1, 2])\n      deepStrictEqual(pipe([1, 2], Arr.takeRight(-1)), [])\n\n      deepStrictEqual(pipe(new Set(), Arr.takeRight(0)), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.takeRight(0)), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.takeRight(1)), [2])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.takeRight(2)), [1, 2])\n      // out of bound\n      deepStrictEqual(pipe(new Set(), Arr.takeRight(1)), [])\n      deepStrictEqual(pipe(new Set(), Arr.takeRight(-1)), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.takeRight(3)), [1, 2])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.takeRight(-1)), [])\n    })\n\n    it(\"takeWhile\", () => {\n      const f = (n: number) => n % 2 === 0\n      deepStrictEqual(pipe([2, 4, 3, 6], Arr.takeWhile(f)), [2, 4])\n      deepStrictEqual(pipe(Arr.empty(), Arr.takeWhile(f)), [])\n      deepStrictEqual(pipe([1, 2, 4], Arr.takeWhile(f)), [])\n      deepStrictEqual(pipe([2, 4], Arr.takeWhile(f)), [2, 4])\n\n      deepStrictEqual(pipe(new Set([2, 4, 3, 6]), Arr.takeWhile(f)), [2, 4])\n      deepStrictEqual(pipe(new Set<number>(), Arr.takeWhile(f)), [])\n      deepStrictEqual(pipe(new Set([1, 2, 4]), Arr.takeWhile(f)), [])\n      deepStrictEqual(pipe(new Set([2, 4]), Arr.takeWhile(f)), [2, 4])\n    })\n\n    it(\"span\", () => {\n      const f = Arr.span<number>((n) => n % 2 === 1)\n      const assertSpan = (\n        input: Iterable<number>,\n        expectedInit: ReadonlyArray<number>,\n        expectedRest: ReadonlyArray<number>\n      ) => {\n        const [init, rest] = f(input)\n        deepStrictEqual(init, expectedInit)\n        deepStrictEqual(rest, expectedRest)\n      }\n      assertSpan([1, 3, 2, 4, 5], [1, 3], [2, 4, 5])\n      assertSpan(Arr.empty(), Arr.empty(), Arr.empty())\n      assertSpan([1, 3], [1, 3], Arr.empty())\n      assertSpan([2, 4], Arr.empty(), [2, 4])\n\n      assertSpan(new Set([1, 3, 2, 4, 5]), [1, 3], [2, 4, 5])\n      assertSpan(new Set(), Arr.empty(), Arr.empty())\n      assertSpan(new Set([1, 3]), [1, 3], Arr.empty())\n      assertSpan(new Set([2, 4]), Arr.empty(), [2, 4])\n    })\n\n    it(\"splitWhere\", () => {\n      const f = Arr.splitWhere<number>((n) => n % 2 !== 1)\n      const assertSplitWhere = (\n        input: Iterable<number>,\n        expectedInit: ReadonlyArray<number>,\n        expectedRest: ReadonlyArray<number>\n      ) => {\n        const [init, rest] = f(input)\n        deepStrictEqual(init, expectedInit)\n        deepStrictEqual(rest, expectedRest)\n      }\n      assertSplitWhere([1, 3, 2, 4, 5], [1, 3], [2, 4, 5])\n      assertSplitWhere(Arr.empty(), Arr.empty(), Arr.empty())\n      assertSplitWhere([1, 3], [1, 3], Arr.empty())\n      assertSplitWhere([2, 4], Arr.empty(), [2, 4])\n\n      assertSplitWhere(new Set([1, 3, 2, 4, 5]), [1, 3], [2, 4, 5])\n      assertSplitWhere(new Set(), Arr.empty(), Arr.empty())\n      assertSplitWhere(new Set([1, 3]), [1, 3], Arr.empty())\n      assertSplitWhere(new Set([2, 4]), Arr.empty(), [2, 4])\n    })\n\n    it(\"split\", () => {\n      deepStrictEqual(pipe(Arr.empty(), Arr.split(2)), Arr.empty())\n      deepStrictEqual(pipe(Arr.make(1), Arr.split(2)), Arr.make(Arr.make(1)))\n      deepStrictEqual(pipe(Arr.make(1, 2), Arr.split(2)), Arr.make(Arr.make(1), Arr.make(2)))\n      deepStrictEqual(pipe(Arr.make(1, 2, 3, 4, 5), Arr.split(2)), Arr.make(Arr.make(1, 2, 3), Arr.make(4, 5)))\n      deepStrictEqual(\n        pipe(Arr.make(1, 2, 3, 4, 5), Arr.split(3)),\n        Arr.make(Arr.make(1, 2), Arr.make(3, 4), Arr.make(5))\n      )\n    })\n\n    it(\"drop\", () => {\n      deepStrictEqual(pipe(Arr.empty(), Arr.drop(0)), [])\n      deepStrictEqual(pipe([1, 2], Arr.drop(0)), [1, 2])\n      deepStrictEqual(pipe([1, 2], Arr.drop(1)), [2])\n      deepStrictEqual(pipe([1, 2], Arr.drop(2)), [])\n      // out of bound\n      deepStrictEqual(pipe(Arr.empty(), Arr.drop(1)), [])\n      deepStrictEqual(pipe(Arr.empty(), Arr.drop(-1)), [])\n      deepStrictEqual(pipe([1, 2], Arr.drop(3)), [])\n      deepStrictEqual(pipe([1, 2], Arr.drop(-1)), [1, 2])\n\n      deepStrictEqual(pipe(new Set(), Arr.drop(0)), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.drop(0)), [1, 2])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.drop(1)), [2])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.drop(2)), [])\n      // out of bound\n      deepStrictEqual(pipe(new Set(), Arr.drop(1)), [])\n      deepStrictEqual(pipe(new Set(), Arr.drop(-1)), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.drop(3)), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.drop(-1)), [1, 2])\n    })\n\n    it(\"dropRight\", () => {\n      deepStrictEqual(pipe([], Arr.dropRight(0)), [])\n      deepStrictEqual(pipe([1, 2], Arr.dropRight(0)), [1, 2])\n      deepStrictEqual(pipe([1, 2], Arr.dropRight(1)), [1])\n      deepStrictEqual(pipe([1, 2], Arr.dropRight(2)), [])\n      // out of bound\n      deepStrictEqual(pipe([], Arr.dropRight(1)), [])\n      deepStrictEqual(pipe([1, 2], Arr.dropRight(3)), [])\n      deepStrictEqual(pipe([], Arr.dropRight(-1)), [])\n      deepStrictEqual(pipe([1, 2], Arr.dropRight(-1)), [1, 2])\n\n      deepStrictEqual(pipe(new Set(), Arr.dropRight(0)), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.dropRight(0)), [1, 2])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.dropRight(1)), [1])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.dropRight(2)), [])\n      // out of bound\n      deepStrictEqual(pipe(new Set(), Arr.dropRight(1)), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.dropRight(3)), [])\n      deepStrictEqual(pipe(new Set(), Arr.dropRight(-1)), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.dropRight(-1)), [1, 2])\n    })\n\n    it(\"dropWhile\", () => {\n      const f = Arr.dropWhile<number>((n) => n > 0)\n\n      deepStrictEqual(f([]), [])\n      deepStrictEqual(f([1, 2]), Arr.empty())\n      deepStrictEqual(f([-1, -2]), [-1, -2])\n      deepStrictEqual(f([-1, 2]), [-1, 2])\n      deepStrictEqual(f([1, -2, 3]), [-2, 3])\n\n      deepStrictEqual(f(new Set<number>()), [])\n      deepStrictEqual(f(new Set([1, 2])), Arr.empty())\n      deepStrictEqual(f(new Set([-1, -2])), [-1, -2])\n      deepStrictEqual(f(new Set([-1, 2])), [-1, 2])\n      deepStrictEqual(f(new Set([1, -2, 3])), [-2, 3])\n    })\n\n    it(\"findFirstIndex\", () => {\n      assertNone(pipe([], Arr.findFirstIndex((n) => n % 2 === 0)))\n      assertSome(pipe([1, 2, 3], Arr.findFirstIndex((n) => n % 2 === 0)), 1)\n      assertSome(pipe([1, 2, 3, 1], Arr.findFirstIndex((n) => n % 2 === 0)), 1)\n\n      assertNone(pipe(new Set<number>(), Arr.findFirstIndex((n) => n % 2 === 0)))\n      assertSome(pipe(new Set([1, 2, 3]), Arr.findFirstIndex((n) => n % 2 === 0)), 1)\n      assertSome(pipe(new Set([1, 2, 3, 4]), Arr.findFirstIndex((n) => n % 2 === 0)), 1)\n    })\n\n    it(\"findLastIndex\", () => {\n      assertNone(pipe([], Arr.findLastIndex((n) => n % 2 === 0)))\n      assertSome(pipe([1, 2, 3], Arr.findLastIndex((n) => n % 2 === 0)), 1)\n      assertSome(pipe([1, 2, 3, 4], Arr.findLastIndex((n) => n % 2 === 0)), 3)\n\n      assertNone(pipe(new Set<number>(), Arr.findLastIndex((n) => n % 2 === 0)))\n      assertSome(pipe(new Set([1, 2, 3]), Arr.findLastIndex((n) => n % 2 === 0)), 1)\n      assertSome(pipe(new Set([1, 2, 3, 4]), Arr.findLastIndex((n) => n % 2 === 0)), 3)\n    })\n\n    describe(\"findFirst\", () => {\n      it(\"boolean-returning overloads\", () => {\n        assertNone(pipe([], Arr.findFirst((n) => n % 2 === 0)))\n        assertSome(pipe([1, 2, 3], Arr.findFirst((n) => n % 2 === 0)), 2)\n        assertSome(pipe([1, 2, 3, 4], Arr.findFirst((n) => n % 2 === 0)), 2)\n\n        assertNone(pipe(new Set<number>(), Arr.findFirst((n) => n % 2 === 0)))\n        assertSome(pipe(new Set([1, 2, 3]), Arr.findFirst((n) => n % 2 === 0)), 2)\n        assertSome(pipe(new Set([1, 2, 3, 4]), Arr.findFirst((n) => n % 2 === 0)), 2)\n      })\n\n      it(\"Option-returning overloads\", () => {\n        assertNone(\n          pipe([], Arr.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none()))\n        )\n        assertSome(\n          pipe([1, 2, 3], Arr.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n        assertSome(\n          pipe([1, 2, 3, 4], Arr.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n\n        assertNone(\n          pipe(new Set<number>(), Arr.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none()))\n        )\n        assertSome(\n          pipe(new Set([1, 2, 3]), Arr.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n        assertSome(\n          pipe(new Set([1, 2, 3, 4]), Arr.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n      })\n    })\n\n    describe(\"findFirstWithIndex\", () => {\n      it(\"boolean-returning overloads\", () => {\n        assertNone(pipe([], Arr.findFirstWithIndex((n) => n % 2 === 0)))\n        assertSome(pipe([1, 2, 3], Arr.findFirstWithIndex((n) => n % 2 === 0)), [2, 1])\n        assertSome(pipe([1, 2, 3, 4], Arr.findFirstWithIndex((n) => n % 2 === 0)), [2, 1])\n\n        assertNone(pipe(new Set<number>(), Arr.findFirstWithIndex((n) => n % 2 === 0)))\n        assertSome(pipe(new Set([1, 2, 3]), Arr.findFirstWithIndex((n) => n % 2 === 0)), [2, 1])\n        assertSome(pipe(new Set([1, 2, 3, 4]), Arr.findFirstWithIndex((n) => n % 2 === 0)), [2, 1])\n      })\n\n      it(\"Option-returning overloads\", () => {\n        assertNone(\n          pipe([], Arr.findFirstWithIndex((n) => n % 2 === 0 ? Option.some(n + 1) : Option.none()))\n        )\n        assertSome(\n          pipe([1, 2, 3], Arr.findFirstWithIndex((n) => n % 2 === 0 ? Option.some(n + 1) : Option.none())),\n          [3, 1]\n        )\n        assertSome(\n          pipe([1, 2, 3, 4], Arr.findFirstWithIndex((n) => n % 2 === 0 ? Option.some(n + 1) : Option.none())),\n          [3, 1]\n        )\n\n        assertNone(\n          pipe(new Set<number>(), Arr.findFirstWithIndex((n) => n % 2 === 0 ? Option.some(n + 1) : Option.none()))\n        )\n        assertSome(\n          pipe(new Set([1, 2, 3]), Arr.findFirstWithIndex((n) => n % 2 === 0 ? Option.some(n + 1) : Option.none())),\n          [3, 1]\n        )\n        assertSome(\n          pipe(new Set([1, 2, 3, 4]), Arr.findFirstWithIndex((n) => n % 2 === 0 ? Option.some(n + 1) : Option.none())),\n          [3, 1]\n        )\n      })\n    })\n\n    describe(\"findLast\", () => {\n      it(\"boolean-returning overloads\", () => {\n        assertNone(pipe([], Arr.findLast((n) => n % 2 === 0)))\n        assertSome(pipe([1, 2, 3], Arr.findLast((n) => n % 2 === 0)), 2)\n        assertSome(pipe([1, 2, 3, 4], Arr.findLast((n) => n % 2 === 0)), 4)\n\n        assertNone(pipe(new Set<number>(), Arr.findLast((n) => n % 2 === 0)))\n        assertSome(pipe(new Set([1, 2, 3]), Arr.findLast((n) => n % 2 === 0)), 2)\n        assertSome(pipe(new Set([1, 2, 3, 4]), Arr.findLast((n) => n % 2 === 0)), 4)\n      })\n\n      it(\"Option-returning overloads\", () => {\n        assertNone(\n          pipe([], Arr.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none()))\n        )\n        assertSome(\n          pipe([1, 2, 3], Arr.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n        assertSome(\n          pipe([1, 2, 3, 4], Arr.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [4, 3]\n        )\n\n        assertNone(\n          pipe(new Set<number>(), Arr.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none()))\n        )\n        assertSome(\n          pipe(new Set([1, 2, 3]), Arr.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n        assertSome(\n          pipe(new Set([1, 2, 3, 4]), Arr.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [4, 3]\n        )\n      })\n    })\n\n    it(\"insertAt\", () => {\n      assertNone(Arr.insertAt(1, 1)([]))\n      assertSome(Arr.insertAt(0, 1)([]), [1])\n      assertSome(Arr.insertAt(2, 5)([1, 2, 3, 4]), [1, 2, 5, 3, 4])\n      // out of bound\n      assertNone(Arr.insertAt(-1, 5)([1, 2, 3, 4]))\n      assertNone(Arr.insertAt(10, 5)([1, 2, 3, 4]))\n\n      assertNone(Arr.insertAt(1, 1)(new Set([])))\n      assertSome(Arr.insertAt(0, 1)(new Set([])), [1])\n      assertSome(Arr.insertAt(2, 5)(new Set([1, 2, 3, 4])), [1, 2, 5, 3, 4])\n      // out of bound\n      assertNone(Arr.insertAt(-1, 5)(new Set([1, 2, 3, 4])))\n      assertNone(Arr.insertAt(10, 5)(new Set([1, 2, 3, 4])))\n    })\n\n    it(\"replace\", () => {\n      deepStrictEqual(pipe([1, 2, 3], Arr.replace(1, \"a\")), [1, \"a\", 3])\n      // out of bound\n      deepStrictEqual(pipe([], Arr.replace(1, \"a\")), [])\n      deepStrictEqual(pipe([1, 2, 3], Arr.replace(-1, \"a\")), [1, 2, 3])\n      deepStrictEqual(pipe([1, 2, 3], Arr.replace(10, \"a\")), [1, 2, 3])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.replace(1, \"a\")), [1, \"a\", 3])\n      // out of bound\n      deepStrictEqual(pipe(new Set([]), Arr.replace(1, \"a\")), [])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.replace(-1, \"a\")), [1, 2, 3])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.replace(10, \"a\")), [1, 2, 3])\n    })\n\n    it(\"replaceOption\", () => {\n      assertSome(pipe([1, 2, 3], Arr.replaceOption(1, \"a\")), [1, \"a\", 3])\n      // out of bound\n      assertNone(pipe([], Arr.replaceOption(1, \"a\")))\n      assertNone(pipe([1, 2, 3], Arr.replaceOption(-1, \"a\")))\n      assertNone(pipe([1, 2, 3], Arr.replaceOption(10, \"a\")))\n\n      assertSome(pipe(new Set([1, 2, 3]), Arr.replaceOption(1, \"a\")), [1, \"a\", 3])\n      // out of bound\n      assertNone(pipe(new Set([]), Arr.replaceOption(1, \"a\")))\n      assertNone(pipe(new Set([1, 2, 3]), Arr.replaceOption(-1, \"a\")))\n      assertNone(pipe(new Set([1, 2, 3]), Arr.replaceOption(10, \"a\")))\n    })\n\n    it(\"modify\", () => {\n      deepStrictEqual(pipe([1, 2, 3], Arr.modify(1, double)), [1, 4, 3])\n      // out of bound\n      deepStrictEqual(pipe([], Arr.modify(1, double)), [])\n      deepStrictEqual(pipe([1, 2, 3], Arr.modify(10, double)), [1, 2, 3])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.modify(1, double)), [1, 4, 3])\n      // out of bound\n      deepStrictEqual(pipe(new Set([]), Arr.modify(1, double)), [])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.modify(10, double)), [1, 2, 3])\n    })\n\n    it(\"modifyOption\", () => {\n      assertSome(pipe([1, 2, 3], Arr.modifyOption(1, double)), [1, 4, 3])\n      // out of bound\n      assertNone(pipe([], Arr.modifyOption(1, double)))\n      assertNone(pipe([1, 2, 3], Arr.modifyOption(10, double)))\n\n      assertSome(pipe(new Set([1, 2, 3]), Arr.modifyOption(1, double)), [1, 4, 3])\n      // out of bound\n      assertNone(pipe(new Set([]), Arr.modifyOption(1, double)))\n      assertNone(pipe(new Set([1, 2, 3]), Arr.modifyOption(10, double)))\n    })\n\n    it(\"remove\", () => {\n      deepStrictEqual(pipe([1, 2, 3], Arr.remove(0)), [2, 3])\n      // out of bound\n      deepStrictEqual(pipe([], Arr.remove(0)), [])\n      deepStrictEqual(pipe([1, 2, 3], Arr.remove(-1)), [1, 2, 3])\n      deepStrictEqual(pipe([1, 2, 3], Arr.remove(10)), [1, 2, 3])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.remove(0)), [2, 3])\n      // out of bound\n      deepStrictEqual(pipe(new Set([]), Arr.remove(0)), [])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.remove(-1)), [1, 2, 3])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.remove(10)), [1, 2, 3])\n    })\n\n    it(\"removeOption\", () => {\n      assertSome(pipe([1, 2, 3], Arr.removeOption(0)), [2, 3])\n      // out of bound\n      assertNone(pipe([], Arr.removeOption(0)))\n      assertNone(pipe([1, 2, 3], Arr.removeOption(-1)))\n      assertNone(pipe([1, 2, 3], Arr.removeOption(10)))\n\n      assertSome(pipe(new Set([1, 2, 3]), Arr.removeOption(0)), [2, 3])\n      // out of bound\n      assertNone(pipe(new Set([]), Arr.removeOption(0)))\n      assertNone(pipe(new Set([1, 2, 3]), Arr.removeOption(-1)))\n      assertNone(pipe(new Set([1, 2, 3]), Arr.removeOption(10)))\n    })\n\n    it(\"reverse\", () => {\n      deepStrictEqual(Arr.reverse([]), [])\n      deepStrictEqual(Arr.reverse([1]), [1])\n      deepStrictEqual(Arr.reverse([1, 2, 3]), [3, 2, 1])\n\n      deepStrictEqual(Arr.reverse(new Set([])), [])\n      deepStrictEqual(Arr.reverse(new Set([1])), [1])\n      deepStrictEqual(Arr.reverse(new Set([1, 2, 3])), [3, 2, 1])\n    })\n\n    it(\"sort\", () => {\n      deepStrictEqual(Arr.sort(Num.Order)([]), [])\n      deepStrictEqual(Arr.sort(Num.Order)([1, 3, 2]), [1, 2, 3])\n\n      deepStrictEqual(Arr.sort(Num.Order)(new Set<number>()), [])\n      deepStrictEqual(Arr.sort(Num.Order)(new Set([1, 3, 2])), [1, 2, 3])\n    })\n\n    it(\"zip\", () => {\n      deepStrictEqual(pipe(new Set([]), Arr.zip(new Set([\"a\", \"b\", \"c\", \"d\"]))), [])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.zip(new Set([]))), [])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.zip(new Set([\"a\", \"b\", \"c\", \"d\"]))), [\n        [1, \"a\"],\n        [2, \"b\"],\n        [3, \"c\"]\n      ])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.zip(new Set([\"a\", \"b\", \"c\", \"d\"]))), [\n        [1, \"a\"],\n        [2, \"b\"],\n        [3, \"c\"]\n      ])\n    })\n\n    it(\"zipWith\", () => {\n      deepStrictEqual(\n        pipe(new Set([1, 2, 3]), Arr.zipWith(new Set([]), (n, s) => s + n)),\n        []\n      )\n      deepStrictEqual(\n        pipe(new Set([]), Arr.zipWith(new Set([\"a\", \"b\", \"c\", \"d\"]), (n, s) => s + n)),\n        []\n      )\n      deepStrictEqual(\n        pipe(new Set([]), Arr.zipWith(new Set([]), (n, s) => s + n)),\n        []\n      )\n      deepStrictEqual(\n        pipe(new Set([1, 2, 3]), Arr.zipWith(new Set([\"a\", \"b\", \"c\", \"d\"]), (n, s) => s + n)),\n        [\"a1\", \"b2\", \"c3\"]\n      )\n    })\n\n    it(\"unzip\", () => {\n      deepStrictEqual(Arr.unzip(new Set([])), [[], []])\n      deepStrictEqual(\n        Arr.unzip(\n          new Set(\n            [\n              [1, \"a\"],\n              [2, \"b\"],\n              [3, \"c\"]\n            ] as const\n          )\n        ),\n        [\n          [1, 2, 3],\n          [\"a\", \"b\", \"c\"]\n        ]\n      )\n    })\n\n    it(\"intersperse\", () => {\n      deepStrictEqual(pipe([], Arr.intersperse(0)), [])\n      deepStrictEqual(pipe([1], Arr.intersperse(0)), [1])\n      deepStrictEqual(pipe([1, 2, 3], Arr.intersperse(0)), [1, 0, 2, 0, 3])\n      deepStrictEqual(pipe([1, 2], Arr.intersperse(0)), [1, 0, 2])\n      deepStrictEqual(pipe([1, 2, 3, 4], Arr.intersperse(0)), [1, 0, 2, 0, 3, 0, 4])\n\n      deepStrictEqual(pipe(new Set([]), Arr.intersperse(0)), [])\n      deepStrictEqual(pipe(new Set([1]), Arr.intersperse(0)), [1])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Arr.intersperse(0)), [1, 0, 2, 0, 3])\n      deepStrictEqual(pipe(new Set([1, 2]), Arr.intersperse(0)), [1, 0, 2])\n      deepStrictEqual(pipe(new Set([1, 2, 3, 4]), Arr.intersperse(0)), [1, 0, 2, 0, 3, 0, 4])\n    })\n\n    it(\"rotate\", () => {\n      deepStrictEqual(Arr.rotate(0)(Arr.empty()), Arr.empty())\n      deepStrictEqual(Arr.rotate(1)(Arr.empty()), Arr.empty())\n      deepStrictEqual(Arr.rotate(1)([1]), [1])\n      deepStrictEqual(Arr.rotate(2)([1]), [1])\n      deepStrictEqual(Arr.rotate(-1)([1]), [1])\n      deepStrictEqual(Arr.rotate(-2)([1]), [1])\n      deepStrictEqual(Arr.rotate(2)([1, 2]), [1, 2])\n      deepStrictEqual(Arr.rotate(0)([1, 2]), [1, 2])\n      deepStrictEqual(Arr.rotate(-2)([1, 2]), [1, 2])\n      deepStrictEqual(Arr.rotate(1)([1, 2]), [2, 1])\n      deepStrictEqual(Arr.rotate(1)(new Set([1, 2, 3, 4, 5])), [5, 1, 2, 3, 4])\n      deepStrictEqual(Arr.rotate(2)(new Set([1, 2, 3, 4, 5])), [4, 5, 1, 2, 3])\n      deepStrictEqual(Arr.rotate(-1)(new Set([1, 2, 3, 4, 5])), [2, 3, 4, 5, 1])\n      deepStrictEqual(Arr.rotate(-2)(new Set([1, 2, 3, 4, 5])), [3, 4, 5, 1, 2])\n      // out of bounds\n      deepStrictEqual(Arr.rotate(7)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3])\n      deepStrictEqual(Arr.rotate(-7)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2])\n      deepStrictEqual(Arr.rotate(2.2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3])\n      deepStrictEqual(Arr.rotate(-2.2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2])\n    })\n\n    it(\"containsWith\", () => {\n      const contains = Arr.containsWith(Num.Equivalence)\n      deepStrictEqual(pipe([1, 2, 3], contains(2)), true)\n      deepStrictEqual(pipe([1, 2, 3], contains(0)), false)\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), contains(2)), true)\n      deepStrictEqual(pipe(new Set([1, 2, 3]), contains(0)), false)\n    })\n\n    it(\"contains\", () => {\n      const contains = Arr.contains\n      deepStrictEqual(pipe([1, 2, 3], contains(2)), true)\n      deepStrictEqual(pipe([1, 2, 3], contains(0)), false)\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), contains(2)), true)\n      deepStrictEqual(pipe(new Set([1, 2, 3]), contains(0)), false)\n    })\n\n    it(\"dedupeWith\", () => {\n      const dedupe = Arr.dedupeWith(Num.Equivalence)\n      deepStrictEqual(dedupe([]), [])\n      deepStrictEqual(dedupe([-0, -0]), [-0])\n      deepStrictEqual(dedupe([0, -0]), [0])\n      deepStrictEqual(dedupe([1]), [1])\n      deepStrictEqual(dedupe([2, 1, 2]), [2, 1])\n      deepStrictEqual(dedupe([1, 2, 1]), [1, 2])\n      deepStrictEqual(dedupe([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])\n      deepStrictEqual(dedupe([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]), [1, 2, 3, 4, 5])\n      deepStrictEqual(dedupe([1, 2, 3, 4, 5, 1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])\n    })\n\n    it(\"dedupeAdjacentWith\", () => {\n      const dedupeAdjacent = Arr.dedupeAdjacentWith(Num.Equivalence)\n      deepStrictEqual(dedupeAdjacent([]), [])\n      deepStrictEqual(dedupeAdjacent([1, 2, 3]), [1, 2, 3])\n      deepStrictEqual(dedupeAdjacent([1, 2, 2, 3, 3]), [1, 2, 3])\n    })\n\n    it(\"splitAt\", () => {\n      const assertSplitAt = (\n        input: ReadonlyArray<number>,\n        index: number,\n        expectedInit: ReadonlyArray<number>,\n        expectedRest: ReadonlyArray<number>\n      ) => {\n        const [init, rest] = Arr.splitAt(index)(input)\n        deepStrictEqual(init, expectedInit)\n        deepStrictEqual(rest, expectedRest)\n      }\n      deepStrictEqual(Arr.splitAt(1)([1, 2]), [[1], [2]])\n      assertSplitAt([1, 2], 2, [1, 2], [])\n      deepStrictEqual(Arr.splitAt(2)([1, 2, 3, 4, 5]), [\n        [1, 2],\n        [3, 4, 5]\n      ])\n      deepStrictEqual(Arr.splitAt(2)(new Set([1, 2, 3, 4, 5])), [\n        [1, 2],\n        [3, 4, 5]\n      ])\n      assertSplitAt([], 0, [], [])\n      assertSplitAt([1, 2], 0, [], [1, 2])\n\n      // out of bounds\n      assertSplitAt([], -1, [], [])\n      assertSplitAt([1, 2], -1, [], [1, 2])\n      assertSplitAt([1, 2], 3, [1, 2], [])\n      assertSplitAt([], 3, [], [])\n    })\n  })\n\n  it(\"splitNonEmptyAt\", () => {\n    deepStrictEqual(pipe(Arr.make(1, 2, 3, 4), Arr.splitNonEmptyAt(2)), [[1, 2], [3, 4]])\n    deepStrictEqual(pipe(Arr.make(1, 2, 3, 4), Arr.splitNonEmptyAt(10)), [[1, 2, 3, 4], []])\n  })\n\n  describe(\"unsafeGet\", () => {\n    it(\"should throw on index out of bound\", () => {\n      throws(() => pipe([], Arr.unsafeGet(100)), new Error(\"Index 100 out of bounds\"))\n    })\n  })\n\n  it(\"fromNullable\", () => {\n    deepStrictEqual(Arr.fromNullable(undefined), [])\n    deepStrictEqual(Arr.fromNullable(null), [])\n    deepStrictEqual(Arr.fromNullable(1), [1])\n  })\n\n  it(\"liftNullable\", () => {\n    const f = Arr.liftNullable((n: number) => (n > 0 ? n : null))\n    deepStrictEqual(f(1), [1])\n    deepStrictEqual(f(-1), [])\n  })\n\n  it(\"flatMapNullable\", () => {\n    const f = Arr.flatMapNullable((n: number) => (n > 0 ? n : null))\n    deepStrictEqual(pipe([], f), [])\n    deepStrictEqual(pipe([1], f), [1])\n    deepStrictEqual(pipe([1, 2], f), [1, 2])\n    deepStrictEqual(pipe([-1], f), [])\n    deepStrictEqual(pipe([-1, 2], f), [2])\n  })\n\n  it(\"liftPredicate\", () => {\n    const p = (n: number): boolean => n > 2\n    const f = Arr.liftPredicate(p)\n    deepStrictEqual(f(1), [])\n    deepStrictEqual(f(3), [3])\n  })\n\n  it(\"liftOption\", () => {\n    const f = Arr.liftOption((n: number) => (n > 0 ? Option.some(n) : Option.none()))\n    deepStrictEqual(f(1), [1])\n    deepStrictEqual(f(-1), [])\n  })\n\n  it(\"unprepend\", () => {\n    deepStrictEqual(Arr.unprepend([0]), [0, []])\n    deepStrictEqual(Arr.unprepend([1, 2, 3, 4]), [1, [2, 3, 4]])\n  })\n\n  it(\"unappend\", () => {\n    deepStrictEqual(Arr.unappend([0]), [[], 0])\n    deepStrictEqual(Arr.unappend([1, 2, 3, 4]), [\n      Arr.make(1, 2, 3),\n      4\n    ])\n    deepStrictEqual(Arr.unappend([0]), [[], 0])\n    deepStrictEqual(Arr.unappend([1, 2, 3, 4]), [\n      Arr.make(1, 2, 3),\n      4\n    ])\n  })\n\n  it(\"modifyNonEmptyHead\", () => {\n    const f = (s: string) => s + \"!\"\n    deepStrictEqual(pipe([\"a\"], Arr.modifyNonEmptyHead(f)), [\"a!\"])\n    deepStrictEqual(pipe([\"a\", \"b\"], Arr.modifyNonEmptyHead(f)), [\"a!\", \"b\"])\n    deepStrictEqual(pipe([\"a\", \"b\", \"c\"], Arr.modifyNonEmptyHead(f)), [\"a!\", \"b\", \"c\"])\n  })\n\n  it(\"modifyNonEmptyLast\", () => {\n    const f = (s: string) => s + \"!\"\n    deepStrictEqual(pipe([\"a\"], Arr.modifyNonEmptyLast(f)), [\"a!\"])\n    deepStrictEqual(pipe([\"a\", \"b\"], Arr.modifyNonEmptyLast(f)), [\"a\", \"b!\"])\n    deepStrictEqual(pipe([\"a\", \"b\", \"c\"], Arr.modifyNonEmptyLast(f)), [\"a\", \"b\", \"c!\"])\n  })\n\n  it(\"setNonEmptyHead\", () => {\n    deepStrictEqual(pipe(Arr.make(\"a\"), Arr.setNonEmptyHead(\"d\")), [\"d\"])\n    deepStrictEqual(pipe(Arr.make(\"a\", \"b\"), Arr.setNonEmptyHead(\"d\")), [\"d\", \"b\"])\n    deepStrictEqual(pipe(Arr.make(\"a\", \"b\", \"c\"), Arr.setNonEmptyHead(\"d\")), [\"d\", \"b\", \"c\"])\n  })\n\n  it(\"setNonEmptyLast\", () => {\n    deepStrictEqual(pipe(Arr.make(\"a\"), Arr.setNonEmptyLast(\"d\")), [\"d\"])\n    deepStrictEqual(pipe(Arr.make(\"a\", \"b\"), Arr.setNonEmptyLast(\"d\")), [\"a\", \"d\"])\n    deepStrictEqual(pipe(Arr.make(\"a\", \"b\", \"c\"), Arr.setNonEmptyLast(\"d\")), [\"a\", \"b\", \"d\"])\n  })\n\n  it(\"liftEither\", () => {\n    const f = Arr.liftEither((s: string) => s.length > 2 ? Either.right(s.length) : Either.left(\"e\"))\n    deepStrictEqual(f(\"a\"), [])\n    deepStrictEqual(f(\"aaa\"), [3])\n  })\n\n  it(\"headNonEmpty\", () => {\n    deepStrictEqual(Arr.headNonEmpty(Arr.make(1, 2)), 1)\n  })\n\n  it(\"tailNonEmpty\", () => {\n    deepStrictEqual(Arr.tailNonEmpty(Arr.make(1, 2)), [2])\n  })\n\n  it(\"lastNonEmpty\", () => {\n    deepStrictEqual(Arr.lastNonEmpty(Arr.make(1, 2, 3)), 3)\n    deepStrictEqual(Arr.lastNonEmpty([1]), 1)\n  })\n\n  it(\"initNonEmpty\", () => {\n    deepStrictEqual(\n      Arr.initNonEmpty(Arr.make(1, 2, 3)),\n      Arr.make(1, 2)\n    )\n    deepStrictEqual(Arr.initNonEmpty([1]), [])\n  })\n\n  it(\"get\", () => {\n    assertSome(pipe([1, 2, 3], Arr.get(0)), 1)\n    assertNone(pipe([1, 2, 3], Arr.get(3)))\n  })\n\n  it(\"unfold\", () => {\n    const as = Arr.unfold(5, (n) => (n > 0 ? Option.some([n, n - 1]) : Option.none()))\n    deepStrictEqual(as, [5, 4, 3, 2, 1])\n  })\n\n  it(\"map\", () => {\n    deepStrictEqual(\n      pipe([1, 2, 3], Arr.map((n) => n * 2)),\n      [2, 4, 6]\n    )\n    deepStrictEqual(\n      pipe([\"a\", \"b\"], Arr.map((s, i) => s + i)),\n      [\"a0\", \"b1\"]\n    )\n  })\n\n  it(\"flatMap\", () => {\n    deepStrictEqual(\n      pipe([1, 2, 3], Arr.flatMap((n) => [n, n + 1])),\n      [1, 2, 2, 3, 3, 4]\n    )\n    const f = Arr.flatMap((n: number, i) => [n + i])\n    deepStrictEqual(pipe([], f), [])\n    deepStrictEqual(pipe([1, 2, 3], f), [1, 3, 5])\n  })\n\n  it(\"extend\", () => {\n    deepStrictEqual(pipe([1, 2, 3, 4], Arr.extend(Num.sumAll)), [10, 9, 7, 4])\n    deepStrictEqual(pipe([1, 2, 3, 4], Arr.extend(identity)), [\n      [1, 2, 3, 4],\n      [2, 3, 4],\n      [3, 4],\n      [4]\n    ])\n  })\n\n  it(\"compact\", () => {\n    deepStrictEqual(Arr.getSomes([]), [])\n    deepStrictEqual(Arr.getSomes([Option.some(1), Option.some(2), Option.some(3)]), [\n      1,\n      2,\n      3\n    ])\n    deepStrictEqual(Arr.getSomes([Option.some(1), Option.none(), Option.some(3)]), [\n      1,\n      3\n    ])\n  })\n\n  it(\"separate\", () => {\n    deepStrictEqual(Arr.separate([]), [[], []])\n    deepStrictEqual(Arr.separate([Either.right(1), Either.left(\"e\"), Either.left(2), Either.right(2)]), [\n      [\"e\", 2],\n      [1, 2]\n    ])\n  })\n\n  it(\"filter\", () => {\n    deepStrictEqual(Arr.filter([1, 2, 3], (n) => n % 2 === 1), [1, 3])\n    deepStrictEqual(Arr.filter([Option.some(3), Option.some(2), Option.some(1)], Option.isSome), [\n      Option.some(3),\n      Option.some(2),\n      Option.some(1)\n    ])\n    deepStrictEqual(Arr.filter([Option.some(3), Option.none(), Option.some(1)], Option.isSome), [\n      Option.some(3),\n      Option.some(1)\n    ])\n    deepStrictEqual(Arr.filter([\"a\", \"b\", \"c\"], (_, i) => i % 2 === 0), [\"a\", \"c\"])\n  })\n\n  it(\"filterMap\", () => {\n    const f = (n: number) => (n % 2 === 0 ? Option.none() : Option.some(n))\n    deepStrictEqual(pipe([1, 2, 3], Arr.filterMap(f)), [1, 3])\n    deepStrictEqual(pipe([], Arr.filterMap(f)), [])\n    const g = (n: number, i: number) => ((i + n) % 2 === 0 ? Option.none() : Option.some(n))\n    deepStrictEqual(pipe([1, 2, 4], Arr.filterMap(g)), [1, 2])\n    deepStrictEqual(pipe([], Arr.filterMap(g)), [])\n  })\n\n  it(\"partitionMap\", () => {\n    deepStrictEqual(Arr.partitionMap([], identity), [[], []])\n    deepStrictEqual(Arr.partitionMap([Either.right(1), Either.left(\"a\"), Either.right(2)], identity), [[\"a\"], [1, 2]])\n  })\n\n  it(\"partition\", () => {\n    deepStrictEqual(Arr.partition([], (n) => n > 2), [[], []])\n    deepStrictEqual(Arr.partition([1, 3], (n) => n > 2), [[1], [3]])\n\n    deepStrictEqual(Arr.partition([], (n, i) => n + i > 2), [[], []])\n    deepStrictEqual(Arr.partition([1, 2], (n, i) => n + i > 2), [[1], [2]])\n  })\n\n  it(\"reduce\", () => {\n    deepStrictEqual(pipe([\"a\", \"b\", \"c\"], Arr.reduce(\"\", (b, a) => b + a)), \"abc\")\n    deepStrictEqual(\n      pipe(\n        [\"a\", \"b\"],\n        Arr.reduce(\"\", (b, a, i) => b + i + a)\n      ),\n      \"0a1b\"\n    )\n  })\n\n  it(\"reduceRight\", () => {\n    const f = (b: string, a: string) => b + a\n    deepStrictEqual(pipe([\"a\", \"b\", \"c\"], Arr.reduceRight(\"\", f)), \"cba\")\n    deepStrictEqual(pipe([], Arr.reduceRight(\"\", f)), \"\")\n    deepStrictEqual(\n      pipe(\n        [\"a\", \"b\"],\n        Arr.reduceRight(\"\", (b, a, i) => b + i + a)\n      ),\n      \"1b0a\"\n    )\n  })\n\n  it(\"getOrder\", () => {\n    const O = Arr.getOrder(Str.Order)\n    deepStrictEqual(O([], []), 0)\n    deepStrictEqual(O([\"a\"], [\"a\"]), 0)\n\n    deepStrictEqual(O([\"a\"], [\"b\"]), -1)\n    deepStrictEqual(O([\"b\"], [\"a\"]), 1)\n\n    deepStrictEqual(O([], [\"a\"]), -1)\n    deepStrictEqual(O([\"a\"], []), 1)\n    deepStrictEqual(O([\"a\"], [\"a\", \"a\"]), -1)\n    deepStrictEqual(O([\"b\"], [\"a\", \"a\"]), 1)\n\n    deepStrictEqual(O([\"a\", \"a\"], [\"a\", \"a\"]), 0)\n    deepStrictEqual(O([\"a\", \"b\"], [\"a\", \"b\"]), 0)\n\n    deepStrictEqual(O([\"a\", \"b\"], [\"a\", \"a\"]), 1)\n    deepStrictEqual(O([\"a\", \"a\"], [\"a\", \"b\"]), -1)\n\n    deepStrictEqual(O([\"b\", \"a\"], [\"a\", \"b\"]), 1)\n    deepStrictEqual(O([\"a\", \"a\"], [\"b\", \"a\"]), -1)\n    deepStrictEqual(O([\"a\", \"b\"], [\"b\", \"a\"]), -1)\n    deepStrictEqual(O([\"b\", \"a\"], [\"b\", \"b\"]), -1)\n    deepStrictEqual(O([\"b\", \"b\"], [\"b\", \"a\"]), 1)\n  })\n\n  it(\"isEmptyReadonlyArray\", () => {\n    deepStrictEqual(Arr.isEmptyReadonlyArray([1, 2, 3]), false)\n    deepStrictEqual(Arr.isEmptyReadonlyArray([]), true)\n  })\n\n  it(\"isEmptyArray\", () => {\n    deepStrictEqual(Arr.isEmptyArray([1, 2, 3]), false)\n    deepStrictEqual(Arr.isEmptyArray([]), true)\n  })\n\n  it(\"isNonEmptyReadonlyArray\", () => {\n    deepStrictEqual(Arr.isNonEmptyReadonlyArray([1, 2, 3]), true)\n    deepStrictEqual(Arr.isNonEmptyReadonlyArray([]), false)\n  })\n\n  it(\"isNonEmptyArray\", () => {\n    deepStrictEqual(Arr.isNonEmptyArray([1, 2, 3]), true)\n    deepStrictEqual(Arr.isNonEmptyArray([]), false)\n  })\n\n  it(\"head\", () => {\n    const as: ReadonlyArray<number> = [1, 2, 3]\n    assertSome(Arr.head(as), 1)\n    assertNone(Arr.head([]))\n  })\n\n  it(\"last\", () => {\n    const as: ReadonlyArray<number> = [1, 2, 3]\n    assertSome(Arr.last(as), 3)\n    assertNone(Arr.last([]))\n  })\n\n  it(\"chunksOf\", () => {\n    deepStrictEqual(Arr.chunksOf(2)([1, 2, 3, 4, 5]), [\n      Arr.make(1, 2),\n      [3, 4],\n      [5]\n    ])\n    deepStrictEqual(Arr.chunksOf(2)([1, 2, 3, 4, 5, 6]), [\n      Arr.make(1, 2),\n      [3, 4],\n      [5, 6]\n    ])\n    deepStrictEqual(Arr.chunksOf(1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])\n    deepStrictEqual(Arr.chunksOf(5)([1, 2, 3, 4, 5]), [[1, 2, 3, 4, 5]])\n    // out of bounds\n    deepStrictEqual(Arr.chunksOf(0)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])\n    deepStrictEqual(Arr.chunksOf(-1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])\n\n    const assertSingleChunk = (\n      input: Arr.NonEmptyReadonlyArray<number>,\n      n: number\n    ) => {\n      const chunks = Arr.chunksOf(n)(input)\n      strictEqual(chunks.length, 1)\n      deepStrictEqual(Arr.headNonEmpty(chunks), input)\n    }\n    // n = length\n    assertSingleChunk(Arr.make(1, 2), 2)\n    // n out of bounds\n    assertSingleChunk(Arr.make(1, 2), 3)\n  })\n\n  it(\"window\", () => {\n    deepStrictEqual(Arr.window(2)([]), [])\n\n    deepStrictEqual(Arr.window(2)([1, 2, 3, 4, 5]), [[1, 2], [2, 3], [3, 4], [4, 5]])\n    deepStrictEqual(Arr.window(3)([1, 2, 3, 4, 5]), [[1, 2, 3], [2, 3, 4], [3, 4, 5]])\n\n    // n out of bounds\n    deepStrictEqual(Arr.window([1, 2, 3, 4, 5], 6), [])\n    deepStrictEqual(Arr.window([1, 2, 3, 4, 5], 0), [])\n    deepStrictEqual(Arr.window([1, 2, 3, 4, 5], -1), [])\n  })\n\n  it(\"min\", () => {\n    deepStrictEqual(Arr.min(Num.Order)([2, 1, 3]), 1)\n    deepStrictEqual(Arr.min(Num.Order)([3]), 3)\n  })\n\n  it(\"max\", () => {\n    deepStrictEqual(\n      Arr.max(Num.Order)(Arr.make(1, 2, 3)),\n      3\n    )\n    deepStrictEqual(Arr.max(Num.Order)([1]), 1)\n  })\n\n  it(\"flatten\", () => {\n    deepStrictEqual(Arr.flatten([[1], [2], [3]]), [1, 2, 3])\n  })\n\n  it(\"groupWith\", () => {\n    const groupWith = Arr.groupWith(Num.Equivalence)\n    deepStrictEqual(groupWith([1, 2, 1, 1]), [[1], [2], [1, 1]])\n    deepStrictEqual(groupWith([1, 2, 1, 1, 3]), [[1], [2], [1, 1], [3]])\n  })\n\n  it(\"groupBy\", () => {\n    deepStrictEqual(Arr.groupBy((_) => \"\")([]), {})\n    deepStrictEqual(Arr.groupBy((a) => `${a}`)([1]), { \"1\": [1] })\n    deepStrictEqual(\n      Arr.groupBy((s: string) => `${s.length}`)([\"foo\", \"bar\", \"foobar\"]),\n      {\n        \"3\": [\"foo\", \"bar\"],\n        \"6\": [\"foobar\"]\n      }\n    )\n    deepStrictEqual(Arr.groupBy([\"a\", \"b\"], (s) => s === \"a\" ? symA : s === \"b\" ? symB : symC), {\n      [symA]: [\"a\"],\n      [symB]: [\"b\"]\n    })\n    deepStrictEqual(Arr.groupBy([\"a\", \"b\", \"c\", \"d\"], (s) => s === \"a\" ? symA : s === \"b\" ? symB : symC), {\n      [symA]: [\"a\"],\n      [symB]: [\"b\"],\n      [symC]: [\"c\", \"d\"]\n    })\n  })\n\n  it(\"match\", () => {\n    const len: <A>(as: ReadonlyArray<A>) => number = Arr.match({\n      onEmpty: () => 0,\n      onNonEmpty: (as) => 1 + len(as.slice(1))\n    })\n    deepStrictEqual(len([1, 2, 3]), 3)\n  })\n\n  it(\"matchLeft\", () => {\n    const len: <A>(as: ReadonlyArray<A>) => number = Arr.matchLeft({\n      onEmpty: () => 0,\n      onNonEmpty: (_, tail) => 1 + len(tail)\n    })\n    deepStrictEqual(len([1, 2, 3]), 3)\n  })\n\n  it(\"matchRight\", () => {\n    const len: <A>(as: ReadonlyArray<A>) => number = Arr.matchRight({\n      onEmpty: () => 0,\n      onNonEmpty: (init, _) => 1 + len(init)\n    })\n    deepStrictEqual(len([1, 2, 3]), 3)\n  })\n\n  it(\"sortBy\", () => {\n    interface X {\n      readonly a: string\n      readonly b: number\n      readonly c: boolean\n    }\n\n    const byName = pipe(\n      Str.Order,\n      Order.mapInput((p: { readonly a: string; readonly b: number }) => p.a)\n    )\n\n    const byAge = pipe(\n      Num.Order,\n      Order.mapInput((p: { readonly a: string; readonly b: number }) => p.b)\n    )\n\n    const sortByNameByAge = Arr.sortBy(byName, byAge)\n\n    const xs: Arr.NonEmptyArray<X> = [\n      { a: \"a\", b: 1, c: true },\n      { a: \"b\", b: 3, c: true },\n      { a: \"c\", b: 2, c: true },\n      { a: \"b\", b: 2, c: true }\n    ]\n\n    deepStrictEqual(Arr.sortBy()(xs), xs)\n    deepStrictEqual(sortByNameByAge([]), [])\n    deepStrictEqual(sortByNameByAge(xs), [\n      { a: \"a\", b: 1, c: true },\n      { a: \"b\", b: 2, c: true },\n      { a: \"b\", b: 3, c: true },\n      { a: \"c\", b: 2, c: true }\n    ])\n\n    deepStrictEqual(Arr.sortBy()(new Set(xs)), xs)\n    deepStrictEqual(sortByNameByAge(new Set([])), [])\n    deepStrictEqual(sortByNameByAge(new Set(xs)), [\n      { a: \"a\", b: 1, c: true },\n      { a: \"b\", b: 2, c: true },\n      { a: \"b\", b: 3, c: true },\n      { a: \"c\", b: 2, c: true }\n    ])\n\n    const sortByAgeByName = Arr.sortBy(byAge, byName)\n    deepStrictEqual(sortByAgeByName(xs), [\n      { a: \"a\", b: 1, c: true },\n      { a: \"b\", b: 2, c: true },\n      { a: \"c\", b: 2, c: true },\n      { a: \"b\", b: 3, c: true }\n    ])\n  })\n\n  it(\"copy\", () => {\n    deepStrictEqual(pipe([], Arr.copy), [])\n    deepStrictEqual(pipe([1, 2, 3], Arr.copy), [1, 2, 3])\n  })\n\n  it(\"chop\", () => {\n    deepStrictEqual(pipe([], Arr.chop((as) => [as[0] * 2, as.slice(1)])), [])\n    deepStrictEqual(pipe([1, 2, 3], Arr.chop((as) => [as[0] * 2, as.slice(1)])), [2, 4, 6])\n  })\n\n  it(\"pad\", () => {\n    deepStrictEqual(pipe([], Arr.pad(0, 0)), [])\n    deepStrictEqual(pipe([1, 2, 3], Arr.pad(0, 0)), [])\n    deepStrictEqual(pipe([1, 2, 3], Arr.pad(2, 0)), [1, 2])\n    deepStrictEqual(pipe([1, 2, 3], Arr.pad(6, 0)), [1, 2, 3, 0, 0, 0])\n    deepStrictEqual(pipe([1, 2, 3], Arr.pad(-2, 0)), [])\n  })\n\n  describe(\"chunksOf\", () => {\n    it(\"should split a `ReadonlyArray` into length-n pieces\", () => {\n      deepStrictEqual(Arr.chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]])\n      deepStrictEqual(Arr.chunksOf(2)([1, 2, 3, 4, 5, 6]), [\n        [1, 2],\n        [3, 4],\n        [5, 6]\n      ])\n      deepStrictEqual(Arr.chunksOf(1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])\n      deepStrictEqual(Arr.chunksOf(5)([1, 2, 3, 4, 5]), [[1, 2, 3, 4, 5]])\n      // out of bounds\n      deepStrictEqual(Arr.chunksOf(0)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])\n      deepStrictEqual(Arr.chunksOf(-1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])\n\n      const assertSingleChunk = (input: ReadonlyArray<number>, n: number) => {\n        const chunks = Arr.chunksOf(n)(input)\n        deepStrictEqual(chunks.length, 1)\n        deepStrictEqual(chunks[0], input)\n      }\n      // n = length\n      assertSingleChunk([1, 2], 2)\n      // n out of bounds\n      assertSingleChunk([1, 2], 3)\n    })\n\n    it(\"returns an empty array if provided an empty array\", () => {\n      const empty: ReadonlyArray<number> = []\n      deepStrictEqual(Arr.chunksOf(0)(empty), Arr.empty())\n      deepStrictEqual(Arr.chunksOf(0)(Arr.empty()), Arr.empty())\n      deepStrictEqual(Arr.chunksOf(1)(empty), Arr.empty())\n      deepStrictEqual(Arr.chunksOf(1)(Arr.empty()), Arr.empty())\n      deepStrictEqual(Arr.chunksOf(2)(empty), Arr.empty())\n      deepStrictEqual(Arr.chunksOf(2)(Arr.empty()), Arr.empty())\n    })\n\n    it(\"should respect the law: chunksOf(n)(xs).concat(chunksOf(n)(ys)) == chunksOf(n)(xs.concat(ys)))\", () => {\n      const xs: ReadonlyArray<number> = []\n      const ys: ReadonlyArray<number> = [1, 2]\n      deepStrictEqual(\n        Arr.chunksOf(2)(xs).concat(Arr.chunksOf(2)(ys)),\n        Arr.chunksOf(2)(xs.concat(ys))\n      )\n      fc.assert(\n        fc.property(\n          fc.array(fc.integer()).filter((xs) => xs.length % 2 === 0), // Ensures `xs.length` is even\n          fc.array(fc.integer()),\n          fc.integer({ min: 1, max: 1 }).map((x) => x * 2), // Generates `n` to be even so that it evenly divides `xs`\n          (xs, ys, n) => {\n            const as = Arr.chunksOf(n)(xs).concat(Arr.chunksOf(n)(ys))\n            const bs = Arr.chunksOf(n)(xs.concat(ys))\n            deepStrictEqual(as, bs)\n          }\n        )\n      )\n    })\n  })\n\n  it(\"makeBy\", () => {\n    deepStrictEqual(Arr.makeBy(5, (n) => n * 2), [0, 2, 4, 6, 8])\n    deepStrictEqual(Arr.makeBy((n) => n * 2)(5), [0, 2, 4, 6, 8])\n    deepStrictEqual(Arr.makeBy(2.2, (n) => n * 2), [0, 2])\n    deepStrictEqual(Arr.makeBy((n) => n * 2)(2.2), [0, 2])\n  })\n\n  it(\"replicate\", () => {\n    deepStrictEqual(Arr.replicate(\"a\", 0), [\"a\"])\n    deepStrictEqual(Arr.replicate(\"a\", -1), [\"a\"])\n    deepStrictEqual(Arr.replicate(\"a\", 3), [\"a\", \"a\", \"a\"])\n    deepStrictEqual(Arr.replicate(\"a\", 2.2), [\"a\", \"a\"])\n  })\n\n  it(\"range\", () => {\n    deepStrictEqual(Arr.range(0, 0), [0])\n    deepStrictEqual(Arr.range(0, 1), [0, 1])\n    deepStrictEqual(Arr.range(1, 5), [1, 2, 3, 4, 5])\n    deepStrictEqual(Arr.range(10, 15), [10, 11, 12, 13, 14, 15])\n    deepStrictEqual(Arr.range(-1, 0), [-1, 0])\n    deepStrictEqual(Arr.range(-5, -1), [-5, -4, -3, -2, -1])\n    // out of bound\n    deepStrictEqual(Arr.range(2, 1), [2])\n    deepStrictEqual(Arr.range(-1, -2), [-1])\n  })\n\n  it(\"unionWith\", () => {\n    const two: ReadonlyArray<number> = [1, 2]\n    deepStrictEqual(pipe(two, Arr.unionWith([3, 4], Num.Equivalence)), [1, 2, 3, 4])\n    deepStrictEqual(pipe(two, Arr.unionWith([2, 3], Num.Equivalence)), [1, 2, 3])\n    deepStrictEqual(pipe(two, Arr.unionWith([1, 2], Num.Equivalence)), [1, 2])\n    deepStrictEqual(pipe(two, Arr.unionWith(Arr.empty(), Num.Equivalence)), two)\n    deepStrictEqual(pipe(Arr.empty(), Arr.unionWith(two, Num.Equivalence)), two)\n    deepStrictEqual(\n      pipe(Arr.empty(), Arr.unionWith(Arr.empty(), Num.Equivalence)),\n      Arr.empty()\n    )\n  })\n\n  it(\"intersectionWith\", () => {\n    const intersectionWith = Arr.intersectionWith(Num.Equivalence)\n    deepStrictEqual(pipe([1, 2], intersectionWith([3, 4])), [])\n    deepStrictEqual(pipe([1, 2], intersectionWith([2, 3])), [2])\n    deepStrictEqual(pipe([1, 2], intersectionWith([1, 2])), [1, 2])\n    deepStrictEqual(pipe([1, 2], intersectionWith([3, 4][Symbol.iterator]())), [])\n    deepStrictEqual(pipe([1, 2], intersectionWith([2, 3][Symbol.iterator]())), [2])\n    deepStrictEqual(pipe([1, 2], intersectionWith([1, 2][Symbol.iterator]())), [1, 2])\n  })\n\n  it(\"differenceWith\", () => {\n    const differenceWith = Arr.differenceWith(Num.Equivalence)\n    deepStrictEqual(pipe([1, 2], differenceWith([3, 4])), [1, 2])\n    deepStrictEqual(pipe([1, 2], differenceWith([2, 3])), [1])\n    deepStrictEqual(pipe([1, 2], differenceWith([1, 2])), [])\n    deepStrictEqual(pipe([1, 2], differenceWith([3, 4][Symbol.iterator]())), [1, 2])\n    deepStrictEqual(pipe([1, 2], differenceWith([2, 3][Symbol.iterator]())), [1])\n    deepStrictEqual(pipe([1, 2], differenceWith([1, 2][Symbol.iterator]())), [])\n  })\n\n  it(\"empty\", () => {\n    deepStrictEqual(Arr.empty.length, 0)\n  })\n\n  it(\"every\", () => {\n    const isPositive: Predicate.Predicate<number> = (n) => n > 0\n    deepStrictEqual(Arr.every([1, 2, 3], isPositive), true)\n    deepStrictEqual(Arr.every([1, 2, -3], isPositive), false)\n  })\n\n  it(\"some\", () => {\n    const isPositive: Predicate.Predicate<number> = (n) => n > 0\n    deepStrictEqual(Arr.some([-1, -2, 3], isPositive), true)\n    deepStrictEqual(Arr.some([-1, -2, -3], isPositive), false)\n  })\n\n  it(\"length\", () => {\n    deepStrictEqual(Arr.length(Arr.empty()), 0)\n    deepStrictEqual(Arr.length([]), 0)\n    deepStrictEqual(Arr.length([\"a\"]), 1)\n  })\n\n  it(\"fromOption\", () => {\n    deepStrictEqual(Arr.fromOption(Option.some(\"hello\")), [\"hello\"])\n    deepStrictEqual(Arr.fromOption(Option.none()), [])\n  })\n\n  it(\"forEach\", () => {\n    const log: Array<string> = []\n    Arr.forEach([\"a\", \"b\", \"c\"], (a, i) => log.push(`${a}-${i}`))\n    deepStrictEqual(log, [\"a-0\", \"b-1\", \"c-2\"])\n  })\n\n  it(\"sortWith\", () => {\n    type X = {\n      a: string\n      b: number\n    }\n    const arr: ReadonlyArray<X> = [{ a: \"a\", b: 2 }, { a: \"b\", b: 1 }]\n    deepStrictEqual(Arr.sortWith(arr, (x) => x.b, Order.number), [{ a: \"b\", b: 1 }, { a: \"a\", b: 2 }])\n  })\n\n  it(\"countBy\", () => {\n    deepStrictEqual(Arr.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0), 2)\n    deepStrictEqual(pipe([1, 2, 3, 4, 5], Arr.countBy((n) => n % 2 === 0)), 2)\n  })\n\n  it(\"Do notation\", () => {\n    const _do = Arr.Do\n    deepStrictEqual(_do, Arr.of({}))\n\n    const doA = Arr.bind(_do, \"a\", () => [\"a\"])\n    deepStrictEqual(doA, Arr.of({ a: \"a\" }))\n\n    const doAB = Arr.bind(doA, \"b\", (x) => [\"b\", x.a + \"b\"])\n    deepStrictEqual(doAB, [\n      { a: \"a\", b: \"b\" },\n      { a: \"a\", b: \"ab\" }\n    ])\n    const doABC = Arr.let(doAB, \"c\", (x) => [x.a, x.b, x.a + x.b])\n    deepStrictEqual(doABC, [\n      { a: \"a\", b: \"b\", c: [\"a\", \"b\", \"ab\"] },\n      { a: \"a\", b: \"ab\", c: [\"a\", \"ab\", \"aab\"] }\n    ])\n\n    const doABCD = Arr.bind(doABC, \"d\", () => Arr.empty())\n    deepStrictEqual(doABCD, [])\n\n    const doAB__proto__C = pipe(\n      Arr.let(doAB, \"__proto__\", (x) => [x.a, x.b, x.a + x.b]),\n      Arr.let(\"c\", (x) => [x.a, x.b, x.a + x.b])\n    )\n    deepStrictEqual(doAB__proto__C, [\n      { a: \"a\", b: \"b\", c: [\"a\", \"b\", \"ab\"], [\"__proto__\"]: [\"a\", \"b\", \"ab\"] },\n      { a: \"a\", b: \"ab\", c: [\"a\", \"ab\", \"aab\"], [\"__proto__\"]: [\"a\", \"ab\", \"aab\"] }\n    ])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/BigDecimal.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertEquals,\n  assertFalse,\n  assertNone,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { BigDecimal, Equal, FastCheck as fc, Option } from \"effect\"\n\nconst $ = BigDecimal.unsafeFromString\n\nconst assertDivide = (x: string, y: string, z: string) => {\n  assertEquals(BigDecimal.divide($(x), $(y)).pipe(Option.getOrThrow), $(z), `Expected ${x} / ${y} to be ${z}`)\n  assertEquals(BigDecimal.unsafeDivide($(x), $(y)), $(z), `Expected ${x} / ${y} to be ${z}`)\n}\n\ndescribe(\"BigDecimal\", () => {\n  it(\"isBigDecimal\", () => {\n    assertTrue(BigDecimal.isBigDecimal($(\"0\")))\n    assertTrue(BigDecimal.isBigDecimal($(\"987\")))\n    assertTrue(BigDecimal.isBigDecimal($(\"123.0\")))\n    assertTrue(BigDecimal.isBigDecimal($(\"0.123\")))\n    assertTrue(BigDecimal.isBigDecimal($(\"123.456\")))\n    assertFalse(BigDecimal.isBigDecimal(\"1\"))\n    assertFalse(BigDecimal.isBigDecimal(true))\n  })\n\n  it(\"sign\", () => {\n    strictEqual(BigDecimal.sign($(\"-5\")), -1)\n    strictEqual(BigDecimal.sign($(\"0\")), 0)\n    strictEqual(BigDecimal.sign($(\"5\")), 1)\n    strictEqual(BigDecimal.sign($(\"-123.456\")), -1)\n    strictEqual(BigDecimal.sign($(\"456.789\")), 1)\n  })\n\n  it(\"equals\", () => {\n    assertTrue(BigDecimal.equals($(\"1\"), $(\"1\")))\n    assertTrue(BigDecimal.equals($(\"0.00012300\"), $(\"0.000123\")))\n    assertTrue(BigDecimal.equals($(\"5\"), $(\"5.0\")))\n    assertTrue(BigDecimal.equals($(\"123.0000\"), $(\"123.00\")))\n    assertFalse(BigDecimal.equals($(\"1\"), $(\"2\")))\n    assertFalse(BigDecimal.equals($(\"1\"), $(\"1.1\")))\n    assertFalse(BigDecimal.equals($(\"1\"), $(\"0.1\")))\n  })\n\n  it(\"sum\", () => {\n    assertEquals(BigDecimal.sum($(\"2\"), $(\"0\")), $(\"2\"))\n    assertEquals(BigDecimal.sum($(\"0\"), $(\"2\")), $(\"2\"))\n    assertEquals(BigDecimal.sum($(\"0\"), $(\"0\")), $(\"0\"))\n    assertEquals(BigDecimal.sum($(\"2\"), $(\"1\")), $(\"3\"))\n    assertEquals(BigDecimal.sum($(\"3.00000\"), $(\"50\")), $(\"53\"))\n    assertEquals(BigDecimal.sum($(\"1.23\"), $(\"0.0045678\")), $(\"1.2345678\"))\n    assertEquals(BigDecimal.sum($(\"123.456\"), $(\"-123.456\")), $(\"0\"))\n  })\n\n  it(\"multiply\", () => {\n    assertEquals(BigDecimal.multiply($(\"3\"), $(\"2\")), $(\"6\"))\n    assertEquals(BigDecimal.multiply($(\"3\"), $(\"0\")), $(\"0\"))\n    assertEquals(BigDecimal.multiply($(\"3\"), $(\"-1\")), $(\"-3\"))\n    assertEquals(BigDecimal.multiply($(\"3\"), $(\"0.5\")), $(\"1.5\"))\n    assertEquals(BigDecimal.multiply($(\"3\"), $(\"-2.5\")), $(\"-7.5\"))\n  })\n\n  it(\"subtract\", () => {\n    assertEquals(BigDecimal.subtract($(\"0\"), $(\"1\")), $(\"-1\"))\n    assertEquals(BigDecimal.subtract($(\"2.1\"), $(\"1\")), $(\"1.1\"))\n    assertEquals(BigDecimal.subtract($(\"3\"), $(\"1\")), $(\"2\"))\n    assertEquals(BigDecimal.subtract($(\"3\"), $(\"0\")), $(\"3\"))\n    assertEquals(BigDecimal.subtract($(\"3\"), $(\"-1\")), $(\"4\"))\n    assertEquals(BigDecimal.subtract($(\"3\"), $(\"0.5\")), $(\"2.5\"))\n    assertEquals(BigDecimal.subtract($(\"3\"), $(\"-2.5\")), $(\"5.5\"))\n  })\n\n  it(\"roundTerminal\", () => {\n    strictEqual(BigDecimal.roundTerminal(0n), 0n)\n    strictEqual(BigDecimal.roundTerminal(4n), 0n)\n    strictEqual(BigDecimal.roundTerminal(5n), 1n)\n    strictEqual(BigDecimal.roundTerminal(9n), 1n)\n    strictEqual(BigDecimal.roundTerminal(49n), 0n)\n    strictEqual(BigDecimal.roundTerminal(59n), 1n)\n    strictEqual(BigDecimal.roundTerminal(99n), 1n)\n    strictEqual(BigDecimal.roundTerminal(-4n), 0n)\n    strictEqual(BigDecimal.roundTerminal(-5n), 1n)\n    strictEqual(BigDecimal.roundTerminal(-9n), 1n)\n    strictEqual(BigDecimal.roundTerminal(-49n), 0n)\n    strictEqual(BigDecimal.roundTerminal(-59n), 1n)\n    strictEqual(BigDecimal.roundTerminal(-99n), 1n)\n  })\n\n  it(\"divide\", () => {\n    assertDivide(\"0\", \"1\", \"0\")\n    assertDivide(\"0\", \"10\", \"0\")\n    assertDivide(\"2\", \"1\", \"2\")\n    assertDivide(\"20\", \"1\", \"20\")\n    assertDivide(\"10\", \"10\", \"1\")\n    assertDivide(\"100\", \"10.0\", \"10\")\n    assertDivide(\"20.0\", \"200\", \"0.1\")\n    assertDivide(\"4\", \"2\", \"2.0\")\n    assertDivide(\"15\", \"3\", \"5.0\")\n    assertDivide(\"1\", \"2\", \"0.5\")\n    assertDivide(\"1\", \"0.02\", \"50\")\n    assertDivide(\"1\", \"0.2\", \"5\")\n    assertDivide(\"1.0\", \"0.02\", \"50\")\n    assertDivide(\"1\", \"0.020\", \"50\")\n    assertDivide(\"5.0\", \"4.00\", \"1.25\")\n    assertDivide(\"5.0\", \"4.000\", \"1.25\")\n    assertDivide(\"5\", \"4.000\", \"1.25\")\n    assertDivide(\"5\", \"4\", \"1.25\")\n    assertDivide(\"100\", \"5\", \"20\")\n    assertDivide(\"-50\", \"5\", \"-10\")\n    assertDivide(\"200\", \"-5\", \"-40.0\")\n    assertDivide(\n      \"1\",\n      \"3\",\n      \"0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333\"\n    )\n    assertDivide(\n      \"-2\",\n      \"-3\",\n      \"0.6666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666667\"\n    )\n    assertDivide(\n      \"-12.34\",\n      \"1.233\",\n      \"-10.00811030008110300081103000811030008110300081103000811030008110300081103000811030008110300081103001\"\n    )\n    assertDivide(\n      \"125348\",\n      \"352.2283\",\n      \"355.8714617763535752237966114591019517738921035021887792661748076460636467881768727839301952739175132\"\n    )\n\n    assertNone(BigDecimal.divide($(\"5\"), $(\"0\")))\n    throws(() => BigDecimal.unsafeDivide($(\"5\"), $(\"0\")), new RangeError(\"Division by zero\"))\n  })\n\n  it(\"Equivalence\", () => {\n    assertTrue(BigDecimal.Equivalence($(\"1\"), $(\"1\")))\n    assertTrue(BigDecimal.Equivalence($(\"0.00012300\"), $(\"0.000123\")))\n    assertTrue(BigDecimal.Equivalence($(\"5\"), $(\"5.00\")))\n    assertFalse(BigDecimal.Equivalence($(\"1\"), $(\"2\")))\n    assertFalse(BigDecimal.Equivalence($(\"1\"), $(\"1.1\")))\n  })\n\n  it(\"Order\", () => {\n    strictEqual(BigDecimal.Order($(\"1\"), $(\"2\")), -1)\n    strictEqual(BigDecimal.Order($(\"2\"), $(\"1\")), 1)\n    strictEqual(BigDecimal.Order($(\"2\"), $(\"2\")), 0)\n    strictEqual(BigDecimal.Order($(\"1\"), $(\"1.1\")), -1)\n    strictEqual(BigDecimal.Order($(\"1.1\"), $(\"1\")), 1)\n    strictEqual(BigDecimal.Order($(\"0.00012300\"), $(\"0.000123\")), 0)\n    strictEqual(BigDecimal.Order($(\"5\"), $(\"5.000\")), 0)\n    strictEqual(BigDecimal.Order($(\"5\"), $(\"0.500\")), 1)\n    strictEqual(BigDecimal.Order($(\"5\"), $(\"50.00\")), -1)\n  })\n\n  it(\"lessThan\", () => {\n    assertTrue(BigDecimal.lessThan($(\"2\"), $(\"3\")))\n    assertFalse(BigDecimal.lessThan($(\"3\"), $(\"3\")))\n    assertFalse(BigDecimal.lessThan($(\"4\"), $(\"3\")))\n  })\n\n  it(\"lessThanOrEqualTo\", () => {\n    assertTrue(BigDecimal.lessThanOrEqualTo($(\"2\"), $(\"3\")))\n    assertTrue(BigDecimal.lessThanOrEqualTo($(\"3\"), $(\"3\")))\n    assertFalse(BigDecimal.lessThanOrEqualTo($(\"4\"), $(\"3\")))\n  })\n\n  it(\"greaterThan\", () => {\n    assertFalse(BigDecimal.greaterThan($(\"2\"), $(\"3\")))\n    assertFalse(BigDecimal.greaterThan($(\"3\"), $(\"3\")))\n    assertTrue(BigDecimal.greaterThan($(\"4\"), $(\"3\")))\n  })\n\n  it(\"greaterThanOrEqualTo\", () => {\n    assertFalse(BigDecimal.greaterThanOrEqualTo($(\"2\"), $(\"3\")))\n    assertTrue(BigDecimal.greaterThanOrEqualTo($(\"3\"), $(\"3\")))\n    assertTrue(BigDecimal.greaterThanOrEqualTo($(\"4\"), $(\"3\")))\n  })\n\n  it(\"between\", () => {\n    assertTrue(BigDecimal.between({ minimum: $(\"0\"), maximum: $(\"5\") })($(\"3\")))\n    assertFalse(BigDecimal.between({ minimum: $(\"0\"), maximum: $(\"5\") })($(\"-1\")))\n    assertFalse(BigDecimal.between({ minimum: $(\"0\"), maximum: $(\"5\") })($(\"6\")))\n    assertFalse(BigDecimal.between({ minimum: $(\"0.02\"), maximum: $(\"5\") })($(\"0.0123\")))\n    assertTrue(BigDecimal.between({ minimum: $(\"0.02\"), maximum: $(\"5\") })($(\"0.05\")))\n\n    assertTrue(BigDecimal.between($(\"3\"), { minimum: $(\"0\"), maximum: $(\"5\") }))\n  })\n\n  it(\"clamp\", () => {\n    assertEquals(BigDecimal.clamp({ minimum: $(\"0\"), maximum: $(\"5\") })($(\"3\")), $(\"3\"))\n    assertEquals(BigDecimal.clamp({ minimum: $(\"0\"), maximum: $(\"5\") })($(\"-1\")), $(\"0\"))\n    assertEquals(BigDecimal.clamp({ minimum: $(\"0\"), maximum: $(\"5\") })($(\"6\")), $(\"5\"))\n    assertEquals(BigDecimal.clamp({ minimum: $(\"0.02\"), maximum: $(\"5\") })($(\"0.0123\")), $(\"0.02\"))\n\n    assertEquals(BigDecimal.clamp($(\"3\"), { minimum: $(\"0\"), maximum: $(\"5\") }), $(\"3\"))\n  })\n\n  it(\"min\", () => {\n    assertEquals(BigDecimal.min($(\"2\"), $(\"3\")), $(\"2\"))\n    assertEquals(BigDecimal.min($(\"5\"), $(\"0.1\")), $(\"0.1\"))\n    assertEquals(BigDecimal.min($(\"0.005\"), $(\"3\")), $(\"0.005\"))\n    assertEquals(BigDecimal.min($(\"123.456\"), $(\"1.2\")), $(\"1.2\"))\n  })\n\n  it(\"max\", () => {\n    assertEquals(BigDecimal.max($(\"2\"), $(\"3\")), $(\"3\"))\n    assertEquals(BigDecimal.max($(\"5\"), $(\"0.1\")), $(\"5\"))\n    assertEquals(BigDecimal.max($(\"0.005\"), $(\"3\")), $(\"3\"))\n    assertEquals(BigDecimal.max($(\"123.456\"), $(\"1.2\")), $(\"123.456\"))\n  })\n\n  it(\"abs\", () => {\n    assertEquals(BigDecimal.abs($(\"2\")), $(\"2\"))\n    assertEquals(BigDecimal.abs($(\"-3\")), $(\"3\"))\n    assertEquals(BigDecimal.abs($(\"0.000456\")), $(\"0.000456\"))\n    assertEquals(BigDecimal.abs($(\"-0.123\")), $(\"0.123\"))\n  })\n\n  it(\"negate\", () => {\n    assertEquals(BigDecimal.negate($(\"2\")), $(\"-2\"))\n    assertEquals(BigDecimal.negate($(\"-3\")), $(\"3\"))\n    assertEquals(BigDecimal.negate($(\"0.000456\")), $(\"-0.000456\"))\n    assertEquals(BigDecimal.negate($(\"-0.123\")), $(\"0.123\"))\n  })\n\n  it(\"remainder\", () => {\n    assertEquals(BigDecimal.remainder($(\"5\"), $(\"2\")).pipe(Option.getOrThrow), $(\"1\"))\n    assertEquals(BigDecimal.remainder($(\"4\"), $(\"2\")).pipe(Option.getOrThrow), $(\"0\"))\n    assertEquals(BigDecimal.remainder($(\"123.456\"), $(\"0.2\")).pipe(Option.getOrThrow), $(\"0.056\"))\n    assertNone(BigDecimal.remainder($(\"5\"), $(\"0\")))\n  })\n\n  it(\"unsafeRemainder\", () => {\n    assertEquals(BigDecimal.unsafeRemainder($(\"5\"), $(\"2\")), $(\"1\"))\n    assertEquals(BigDecimal.unsafeRemainder($(\"4\"), $(\"2\")), $(\"0\"))\n    assertEquals(BigDecimal.unsafeRemainder($(\"123.456\"), $(\"0.2\")), $(\"0.056\"))\n    throws(() => BigDecimal.unsafeRemainder($(\"5\"), $(\"0\")), new RangeError(\"Division by zero\"))\n  })\n\n  it(\"normalize\", () => {\n    deepStrictEqual(BigDecimal.normalize($(\"0\")), BigDecimal.unsafeMakeNormalized(0n, 0))\n    deepStrictEqual(BigDecimal.normalize($(\"0.123000\")), BigDecimal.unsafeMakeNormalized(123n, 3))\n    deepStrictEqual(BigDecimal.normalize($(\"123.000\")), BigDecimal.unsafeMakeNormalized(123n, 0))\n    deepStrictEqual(BigDecimal.normalize($(\"-0.000123000\")), BigDecimal.unsafeMakeNormalized(-123n, 6))\n    deepStrictEqual(BigDecimal.normalize($(\"-123.000\")), BigDecimal.unsafeMakeNormalized(-123n, 0))\n    deepStrictEqual(BigDecimal.normalize($(\"12300000\")), BigDecimal.unsafeMakeNormalized(123n, -5))\n  })\n\n  it(\"fromString\", () => {\n    assertSome(BigDecimal.fromString(\"2\"), BigDecimal.make(2n, 0))\n    assertSome(BigDecimal.fromString(\"-2\"), BigDecimal.make(-2n, 0))\n    assertSome(BigDecimal.fromString(\"0.123\"), BigDecimal.make(123n, 3))\n    assertSome(BigDecimal.fromString(\"200\"), BigDecimal.make(200n, 0))\n    assertSome(BigDecimal.fromString(\"20000000\"), BigDecimal.make(20000000n, 0))\n    assertSome(BigDecimal.fromString(\"-20000000\"), BigDecimal.make(-20000000n, 0))\n    assertSome(BigDecimal.fromString(\"2.00\"), BigDecimal.make(200n, 2))\n    assertSome(BigDecimal.fromString(\"0.0000200\"), BigDecimal.make(200n, 7))\n    assertSome(BigDecimal.fromString(\"\"), BigDecimal.normalize(BigDecimal.make(0n, 0)))\n    assertSome(BigDecimal.fromString(\"1e5\"), BigDecimal.make(1n, -5))\n    assertSome(BigDecimal.fromString(\"1E15\"), BigDecimal.make(1n, -15))\n    assertSome(BigDecimal.fromString(\"1e+5\"), BigDecimal.make(1n, -5))\n    assertSome(BigDecimal.fromString(\"1E+15\"), BigDecimal.make(1n, -15))\n    assertSome(BigDecimal.fromString(\"-1.5E3\"), BigDecimal.make(-15n, -2))\n    assertSome(BigDecimal.fromString(\"-1.5e3\"), BigDecimal.make(-15n, -2))\n    assertSome(BigDecimal.fromString(\"-.5e3\"), BigDecimal.make(-5n, -2))\n    assertSome(BigDecimal.fromString(\"-5e3\"), BigDecimal.make(-5n, -3))\n    assertSome(BigDecimal.fromString(\"-5e-3\"), BigDecimal.make(-5n, 3))\n    assertSome(BigDecimal.fromString(\"15e-3\"), BigDecimal.make(15n, 3))\n    assertSome(BigDecimal.fromString(\"0.00002e5\"), BigDecimal.make(2n, 0))\n    assertSome(BigDecimal.fromString(\"0.00002e-5\"), BigDecimal.make(2n, 10))\n    assertNone(BigDecimal.fromString(\"0.0000e2e1\"))\n    assertNone(BigDecimal.fromString(\"0.1.2\"))\n  })\n\n  it(\"format\", () => {\n    strictEqual(BigDecimal.format($(\"2\")), \"2\")\n    strictEqual(BigDecimal.format($(\"-2\")), \"-2\")\n    strictEqual(BigDecimal.format($(\"0.123\")), \"0.123\")\n    strictEqual(BigDecimal.format($(\"200\")), \"200\")\n    strictEqual(BigDecimal.format($(\"20000000\")), \"20000000\")\n    strictEqual(BigDecimal.format($(\"-20000000\")), \"-20000000\")\n    strictEqual(BigDecimal.format($(\"2.00\")), \"2\")\n    strictEqual(BigDecimal.format($(\"0.200\")), \"0.2\")\n    strictEqual(BigDecimal.format($(\"0.123000\")), \"0.123\")\n    strictEqual(BigDecimal.format($(\"-456.123\")), \"-456.123\")\n    strictEqual(BigDecimal.format(BigDecimal.make(10n, -1)), \"100\")\n    strictEqual(BigDecimal.format(BigDecimal.make(1n, -25)), \"1e+25\")\n    strictEqual(BigDecimal.format(BigDecimal.make(12345n, -25)), \"1.2345e+29\")\n    strictEqual(BigDecimal.format(BigDecimal.make(12345n, 25)), \"1.2345e-21\")\n    strictEqual(BigDecimal.format(BigDecimal.make(-12345n, 20)), \"-1.2345e-16\")\n  })\n\n  it(\"toJSON()\", () => {\n    deepStrictEqual(JSON.stringify($(\"2\")), JSON.stringify({ _id: \"BigDecimal\", value: \"2\", scale: 0 }))\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window === \"undefined\") {\n      // eslint-disable-next-line @typescript-eslint/no-require-imports\n      const { inspect } = require(\"node:util\")\n      deepStrictEqual(inspect($(\"2\")), inspect({ _id: \"BigDecimal\", value: \"2\", scale: 0 }))\n    }\n  })\n\n  it(\"toString()\", () => {\n    strictEqual(String($(\"2\")), \"BigDecimal(2)\")\n  })\n\n  it(\"Equal.symbol\", () => {\n    assertTrue(Equal.equals($(\"2\"), $(\"2\")))\n  })\n\n  it(\"pipe()\", () => {\n    deepStrictEqual($(\"2\").pipe(BigDecimal.multiply($(\"3\"))), $(\"6\"))\n  })\n\n  it(\"scale\", () => {\n    deepStrictEqual(BigDecimal.scale($(\"3.0005\"), 3), $(\"3.000\"))\n  })\n\n  it(\"fromBigInt\", () => {\n    deepStrictEqual(BigDecimal.fromBigInt(1n), BigDecimal.make(1n, 0))\n  })\n\n  it(\"fromNumber\", () => {\n    deepStrictEqual(BigDecimal.fromNumber(123), BigDecimal.make(123n, 0))\n    deepStrictEqual(BigDecimal.fromNumber(123.456), BigDecimal.make(123456n, 3))\n  })\n\n  it(\"unsafeToNumber\", () => {\n    strictEqual(BigDecimal.unsafeToNumber($(\"123.456\")), 123.456)\n  })\n\n  it(\"isInteger\", () => {\n    assertTrue(BigDecimal.isInteger($(\"0\")))\n    assertTrue(BigDecimal.isInteger($(\"1\")))\n    assertFalse(BigDecimal.isInteger($(\"1.1\")))\n  })\n\n  it(\"isZero\", () => {\n    assertTrue(BigDecimal.isZero($(\"0\")))\n    assertFalse(BigDecimal.isZero($(\"1\")))\n  })\n\n  it(\"isNegative\", () => {\n    assertTrue(BigDecimal.isNegative($(\"-1\")))\n    assertFalse(BigDecimal.isNegative($(\"0\")))\n    assertFalse(BigDecimal.isNegative($(\"1\")))\n  })\n\n  it(\"isPositive\", () => {\n    assertFalse(BigDecimal.isPositive($(\"-1\")))\n    assertFalse(BigDecimal.isPositive($(\"0\")))\n    assertTrue(BigDecimal.isPositive($(\"1\")))\n  })\n\n  it(\"digitAt\", () => {\n    assertEquals(BigDecimal.digitAt($(\"12.34\"), -2), 0n)\n    assertEquals(BigDecimal.digitAt($(\"12.34\"), -1), 1n)\n    assertEquals(BigDecimal.digitAt($(\"12.34\"), 0), 2n)\n    assertEquals(BigDecimal.digitAt($(\"12.34\"), 1), 3n)\n    assertEquals(BigDecimal.digitAt($(\"12.34\"), 2), 4n)\n    assertEquals(BigDecimal.digitAt($(\"12.34\"), 3), 0n)\n  })\n\n  it(\"round: ceil\", () => {\n    assertEquals(BigDecimal.ceil($(\"145\"), -1), $(\"150\"))\n    assertEquals(BigDecimal.ceil(-1)($(\"145\")), $(\"150\"))\n    assertEquals(BigDecimal.ceil($(\"-14.5\")), $(\"-14\"))\n\n    assertEquals(BigDecimal.round($(\"321.123\"), { mode: \"ceil\", scale: -3 }), $(\"1000\"))\n    assertEquals(BigDecimal.round($(\"145\"), { mode: \"ceil\", scale: -1 }), $(\"150\"))\n    assertEquals(BigDecimal.round($(\"-2.0\"), { mode: \"ceil\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"-1.9\"), { mode: \"ceil\", scale: 0 }), $(\"-1\"))\n    assertEquals(BigDecimal.round($(\"0.12345678987654321\"), { mode: \"ceil\", scale: 13 }), $(\"0.1234567898766\"))\n    assertEquals(BigDecimal.round($(\"-0.12345678987654321\"), { mode: \"ceil\", scale: 13 }), $(\"-0.1234567898765\"))\n  })\n\n  it(\"round: floor)\", () => {\n    assertEquals(BigDecimal.floor($(\"145\"), -1), $(\"140\"))\n    assertEquals(BigDecimal.floor(-1)($(\"145\")), $(\"140\"))\n    assertEquals(BigDecimal.floor($(\"-14.5\")), $(\"-15\"))\n\n    assertEquals(BigDecimal.round($(\"321.123\"), { mode: \"floor\", scale: -3 }), $(\"0\"))\n    assertEquals(BigDecimal.round($(\"145\"), { mode: \"floor\", scale: -1 }), $(\"140\"))\n    assertEquals(BigDecimal.round($(\"-2.1\"), { mode: \"floor\", scale: 0 }), $(\"-3\"))\n    assertEquals(BigDecimal.round($(\"-1.9\"), { mode: \"floor\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"0.12345678987654321\"), { mode: \"floor\", scale: 13 }), $(\"0.1234567898765\"))\n    assertEquals(BigDecimal.round($(\"-0.12345678987654321\"), { mode: \"floor\", scale: 13 }), $(\"-0.1234567898766\"))\n  })\n\n  it(\"round: to-zero (truncate)\", () => {\n    assertEquals(BigDecimal.truncate($(\"145\"), -1), $(\"140\"))\n    assertEquals(BigDecimal.truncate(-1)($(\"145\")), $(\"140\"))\n    assertEquals(BigDecimal.truncate($(\"-14.5\")), $(\"-14\"))\n\n    assertEquals(BigDecimal.round($(\"321.123\"), { mode: \"to-zero\", scale: -3 }), $(\"0\"))\n    assertEquals(BigDecimal.round($(\"145\"), { mode: \"to-zero\", scale: -1 }), $(\"140\"))\n    assertEquals(BigDecimal.round($(\"-2.1\"), { mode: \"to-zero\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"-1.9\"), { mode: \"to-zero\", scale: 0 }), $(\"-1\"))\n    assertEquals(BigDecimal.round($(\"0.12345678987654321\"), { mode: \"to-zero\", scale: 13 }), $(\"0.1234567898765\"))\n    assertEquals(BigDecimal.round($(\"-0.12345678987654321\"), { mode: \"to-zero\", scale: 13 }), $(\"-0.1234567898765\"))\n  })\n\n  it(\"round: from-zero\", () => {\n    assertEquals(BigDecimal.round($(\"321.123\"), { mode: \"from-zero\", scale: -3 }), $(\"1000\"))\n    assertEquals(BigDecimal.round($(\"145\"), { mode: \"from-zero\", scale: -1 }), $(\"150\"))\n    assertEquals(BigDecimal.round($(\"-2.1\"), { mode: \"from-zero\", scale: 0 }), $(\"-3\"))\n    assertEquals(BigDecimal.round($(\"-1.9\"), { mode: \"from-zero\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"0.12345678987654321\"), { mode: \"from-zero\", scale: 13 }), $(\"0.1234567898766\"))\n    assertEquals(BigDecimal.round($(\"-0.12345678987654321\"), { mode: \"from-zero\", scale: 13 }), $(\"-0.1234567898766\"))\n  })\n\n  it(\"round: half-ceil\", () => {\n    assertEquals(BigDecimal.round($(\"321.123\"), { mode: \"half-ceil\", scale: -3 }), $(\"0\"))\n    assertEquals(BigDecimal.round($(\"145\"), { mode: \"half-ceil\", scale: -1 }), $(\"150\"))\n    assertEquals(BigDecimal.round($(\"-2.5\"), { mode: \"half-ceil\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"1.95\"), { mode: \"half-ceil\", scale: 1 }), $(\"2\"))\n    assertEquals(BigDecimal.round($(\"-1.95\"), { mode: \"half-ceil\", scale: 1 }), $(\"-1.9\"))\n    assertEquals(BigDecimal.round($(\"0.1234567898765\"), { mode: \"half-ceil\", scale: 12 }), $(\"0.123456789877\"))\n    assertEquals(BigDecimal.round($(\"-0.1234567898765\"), { mode: \"half-ceil\", scale: 12 }), $(\"-0.123456789876\"))\n  })\n\n  it(\"round: half-floor\", () => {\n    assertEquals(BigDecimal.round($(\"321.123\"), { mode: \"half-floor\", scale: -3 }), $(\"0\"))\n    assertEquals(BigDecimal.round($(\"145\"), { mode: \"half-floor\", scale: -1 }), $(\"140\"))\n    assertEquals(BigDecimal.round($(\"-2.4\"), { mode: \"half-floor\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"-2.5\"), { mode: \"half-floor\", scale: 0 }), $(\"-3\"))\n    assertEquals(BigDecimal.round($(\"1.95\"), { mode: \"half-floor\", scale: 1 }), $(\"1.9\"))\n    assertEquals(BigDecimal.round($(\"-1.95\"), { mode: \"half-floor\", scale: 1 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"0.1234567898765\"), { mode: \"half-floor\", scale: 12 }), $(\"0.123456789876\"))\n    assertEquals(BigDecimal.round($(\"-0.1234567898765\"), { mode: \"half-floor\", scale: 12 }), $(\"-0.123456789877\"))\n  })\n\n  it(\"round: half-to-zero\", () => {\n    assertEquals(BigDecimal.round($(\"321.123\"), { mode: \"half-to-zero\", scale: -3 }), $(\"0\"))\n    assertEquals(BigDecimal.round($(\"145\"), { mode: \"half-to-zero\", scale: -1 }), $(\"140\"))\n    assertEquals(BigDecimal.round($(\"-2.4\"), { mode: \"half-to-zero\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"-2.5\"), { mode: \"half-to-zero\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"1.95\"), { mode: \"half-to-zero\", scale: 1 }), $(\"1.9\"))\n    assertEquals(BigDecimal.round($(\"-1.95\"), { mode: \"half-to-zero\", scale: 1 }), $(\"-1.9\"))\n    assertEquals(BigDecimal.round($(\"0.1234567898765\"), { mode: \"half-to-zero\", scale: 12 }), $(\"0.123456789876\"))\n    assertEquals(BigDecimal.round($(\"-0.1234567898765\"), { mode: \"half-to-zero\", scale: 12 }), $(\"-0.123456789876\"))\n  })\n\n  it(\"round: half-from-zero\", () => {\n    assertEquals(BigDecimal.round($(\"321.123\"), { mode: \"half-from-zero\", scale: -3 }), $(\"0\"))\n    assertEquals(BigDecimal.round($(\"145\"), { mode: \"half-from-zero\", scale: -1 }), $(\"150\"))\n    assertEquals(BigDecimal.round($(\"-2.4\"), { mode: \"half-from-zero\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"-2.5\"), { mode: \"half-from-zero\", scale: 0 }), $(\"-3\"))\n    assertEquals(BigDecimal.round($(\"1.95\"), { mode: \"half-from-zero\", scale: 1 }), $(\"2\"))\n    assertEquals(BigDecimal.round($(\"-1.95\"), { mode: \"half-from-zero\", scale: 1 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"0.1234567898765\"), { mode: \"half-from-zero\", scale: 12 }), $(\"0.123456789877\"))\n    assertEquals(BigDecimal.round($(\"-0.1234567898765\"), { mode: \"half-from-zero\", scale: 12 }), $(\"-0.123456789877\"))\n  })\n\n  it(\"round: half-even\", () => {\n    assertEquals(BigDecimal.round($(\"321.123\"), { mode: \"half-even\", scale: -3 }), $(\"0\"))\n    assertEquals(BigDecimal.round($(\"145\"), { mode: \"half-even\", scale: -1 }), $(\"140\"))\n    assertEquals(BigDecimal.round($(\"-2.4\"), { mode: \"half-even\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"-2.5\"), { mode: \"half-even\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"1.95\"), { mode: \"half-even\", scale: 1 }), $(\"2\"))\n    assertEquals(BigDecimal.round($(\"-1.95\"), { mode: \"half-even\", scale: 1 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"0.1234567898765\"), { mode: \"half-even\", scale: 12 }), $(\"0.123456789876\"))\n    assertEquals(BigDecimal.round($(\"-0.1234567898765\"), { mode: \"half-even\", scale: 12 }), $(\"-0.123456789876\"))\n  })\n\n  it(\"round: half-odd\", () => {\n    assertEquals(BigDecimal.round($(\"321.123\"), { mode: \"half-even\", scale: -3 }), $(\"0\"))\n    assertEquals(BigDecimal.round($(\"145\"), { mode: \"half-even\", scale: -1 }), $(\"140\"))\n    assertEquals(BigDecimal.round($(\"-2.4\"), { mode: \"half-even\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"-2.5\"), { mode: \"half-even\", scale: 0 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"1.95\"), { mode: \"half-even\", scale: 1 }), $(\"2\"))\n    assertEquals(BigDecimal.round($(\"-1.95\"), { mode: \"half-even\", scale: 1 }), $(\"-2\"))\n    assertEquals(BigDecimal.round($(\"0.1234567898765\"), { mode: \"half-even\", scale: 12 }), $(\"0.123456789876\"))\n    assertEquals(BigDecimal.round($(\"-0.1234567898765\"), { mode: \"half-even\", scale: 12 }), $(\"-0.123456789876\"))\n  })\n\n  it(\"sumAll\", () => {\n    assertEquals(BigDecimal.sumAll([]), $(\"0\"))\n    assertEquals(BigDecimal.sumAll([$(\"2.5\"), $(\"0.5\")]), $(\"3\"))\n    assertEquals(BigDecimal.sumAll([$(\"2.5\"), $(\"1500\"), $(\"123.456\")]), $(\"1625.956\"))\n  })\n})\n\n// This test is skipped because it is slow. It remains here as an opt-in test for\n// debugging or active development of features in the `BigDecimal` module.\ndescribe.skip(\"Property based testing\", () => {\n  const zeroArb = fc.constant(BigDecimal.unsafeMakeNormalized(0n, 0))\n  const bigDecimalArb = fc.tuple(fc.bigInt(), fc.integer()).map(([value, scale]) => BigDecimal.make(value, scale))\n  const arbWithZero = fc.oneof({ arbitrary: zeroArb, weight: 1 }, { arbitrary: bigDecimalArb, weight: 3 })\n\n  it(\"unsafeFromString and format should be inverses\", () => {\n    fc.assert(fc.property(arbWithZero, (bd) => {\n      return BigDecimal.equals(BigDecimal.unsafeFromString(BigDecimal.format(bd)), bd)\n    }))\n  })\n\n  it(\"toExponential should harmonize with Number.prototype.toExponential\", () => {\n    const actualNumbers = fc.float().filter((n) => Number.isFinite(n))\n    fc.assert(fc.property(actualNumbers, (n) => {\n      return n.toExponential() === BigDecimal.toExponential(BigDecimal.unsafeFromNumber(n))\n    }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/BigInt.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertNone,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { BigInt as BigInt_, pipe } from \"effect\"\n\ndescribe(\"BigInt\", () => {\n  it(\"sign\", () => {\n    strictEqual(BigInt_.sign(-5n), -1)\n    strictEqual(BigInt_.sign(0n), 0)\n    strictEqual(BigInt_.sign(5n), 1)\n  })\n\n  it(\"isBigInt\", () => {\n    assertTrue(BigInt_.isBigInt(1n))\n    assertFalse(BigInt_.isBigInt(1))\n    assertFalse(BigInt_.isBigInt(\"a\"))\n    assertFalse(BigInt_.isBigInt(true))\n  })\n\n  it(\"sum\", () => {\n    deepStrictEqual(pipe(1n, BigInt_.sum(2n)), 3n)\n  })\n\n  it(\"multiply\", () => {\n    deepStrictEqual(pipe(2n, BigInt_.multiply(3n)), 6n)\n  })\n\n  it(\"subtract\", () => {\n    deepStrictEqual(pipe(3n, BigInt_.subtract(1n)), 2n)\n  })\n\n  it(\"divide\", () => {\n    assertSome(pipe(6n, BigInt_.divide(2n)), 3n)\n    assertNone(pipe(6n, BigInt_.divide(0n)))\n  })\n\n  it(\"unsafeDivide\", () => {\n    deepStrictEqual(pipe(6n, BigInt_.unsafeDivide(2n)), 3n)\n  })\n\n  it(\"increment\", () => {\n    deepStrictEqual(BigInt_.increment(2n), 3n)\n  })\n\n  it(\"decrement\", () => {\n    deepStrictEqual(BigInt_.decrement(2n), 1n)\n  })\n\n  it(\"Equivalence\", () => {\n    assertTrue(BigInt_.Equivalence(1n, 1n))\n    assertFalse(BigInt_.Equivalence(1n, 2n))\n  })\n\n  it(\"Order\", () => {\n    deepStrictEqual(BigInt_.Order(1n, 2n), -1)\n    deepStrictEqual(BigInt_.Order(2n, 1n), 1)\n    deepStrictEqual(BigInt_.Order(2n, 2n), 0)\n  })\n\n  it(\"lessThan\", () => {\n    deepStrictEqual(BigInt_.lessThan(2n, 3n), true)\n    deepStrictEqual(BigInt_.lessThan(3n, 3n), false)\n    deepStrictEqual(BigInt_.lessThan(4n, 3n), false)\n  })\n\n  it(\"lessThanOrEqualTo\", () => {\n    deepStrictEqual(BigInt_.lessThanOrEqualTo(2n, 3n), true)\n    deepStrictEqual(BigInt_.lessThanOrEqualTo(3n, 3n), true)\n    deepStrictEqual(BigInt_.lessThanOrEqualTo(4n, 3n), false)\n  })\n\n  it(\"greaterThan\", () => {\n    deepStrictEqual(BigInt_.greaterThan(2n, 3n), false)\n    deepStrictEqual(BigInt_.greaterThan(3n, 3n), false)\n    deepStrictEqual(BigInt_.greaterThan(4n, 3n), true)\n  })\n\n  it(\"greaterThanOrEqualTo\", () => {\n    deepStrictEqual(BigInt_.greaterThanOrEqualTo(2n, 3n), false)\n    deepStrictEqual(BigInt_.greaterThanOrEqualTo(3n, 3n), true)\n    deepStrictEqual(BigInt_.greaterThanOrEqualTo(4n, 3n), true)\n  })\n\n  it(\"between\", () => {\n    deepStrictEqual(BigInt_.between({ minimum: 0n, maximum: 5n })(3n), true)\n    deepStrictEqual(BigInt_.between({ minimum: 0n, maximum: 5n })(-1n), false)\n    deepStrictEqual(BigInt_.between({ minimum: 0n, maximum: 5n })(6n), false)\n\n    deepStrictEqual(BigInt_.between(3n, { minimum: 0n, maximum: 5n }), true)\n  })\n\n  it(\"clamp\", () => {\n    deepStrictEqual(BigInt_.clamp({ minimum: 0n, maximum: 5n })(3n), 3n)\n    deepStrictEqual(BigInt_.clamp({ minimum: 0n, maximum: 5n })(-1n), 0n)\n    deepStrictEqual(BigInt_.clamp({ minimum: 0n, maximum: 5n })(6n), 5n)\n\n    deepStrictEqual(BigInt_.clamp(3n, { minimum: 0n, maximum: 5n }), 3n)\n  })\n\n  it(\"min\", () => {\n    deepStrictEqual(BigInt_.min(2n, 3n), 2n)\n  })\n\n  it(\"max\", () => {\n    deepStrictEqual(BigInt_.max(2n, 3n), 3n)\n  })\n\n  it(\"sumAll\", () => {\n    deepStrictEqual(BigInt_.sumAll([2n, 3n, 4n]), 9n)\n  })\n\n  it(\"multiplyAll\", () => {\n    deepStrictEqual(BigInt_.multiplyAll([2n, 0n, 4n]), 0n)\n    deepStrictEqual(BigInt_.multiplyAll([2n, 3n, 4n]), 24n)\n  })\n\n  it(\"abs\", () => {\n    deepStrictEqual(BigInt_.abs(2n), 2n)\n    deepStrictEqual(BigInt_.abs(-3n), 3n)\n  })\n\n  it(\"gcd\", () => {\n    deepStrictEqual(BigInt_.gcd(2n, 4n), 2n)\n    deepStrictEqual(BigInt_.gcd(3n, 4n), 1n)\n  })\n\n  it(\"lcm\", () => {\n    deepStrictEqual(BigInt_.lcm(2n, 4n), 4n)\n    deepStrictEqual(BigInt_.lcm(3n, 4n), 12n)\n  })\n\n  it(\"sqrt\", () => {\n    assertSome(BigInt_.sqrt(1n), 1n)\n    assertSome(BigInt_.sqrt(16n), 4n)\n    assertSome(BigInt_.sqrt(81n), 9n)\n    assertNone(BigInt_.sqrt(-123n))\n  })\n\n  it(\"sqrt\", () => {\n    throws(() => BigInt_.unsafeSqrt(-1n), new RangeError(\"Cannot take the square root of a negative number\"))\n  })\n\n  it(\"toNumber\", () => {\n    assertSome(BigInt_.toNumber(BigInt(Number.MAX_SAFE_INTEGER)), Number.MAX_SAFE_INTEGER)\n    assertNone(BigInt_.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)))\n    assertSome(BigInt_.toNumber(BigInt(Number.MIN_SAFE_INTEGER)), Number.MIN_SAFE_INTEGER)\n    assertNone(BigInt_.toNumber(BigInt(Number.MIN_SAFE_INTEGER) - BigInt(1)))\n    assertSome(BigInt_.toNumber(BigInt(0)), 0)\n    assertSome(BigInt_.toNumber(BigInt(42)), 42)\n    assertSome(BigInt_.toNumber(BigInt(-42)), -42)\n  })\n\n  it(\"fromString\", () => {\n    assertNone(BigInt_.fromString(\"NaN\"))\n    assertNone(BigInt_.fromString(\"Infinity\"))\n    assertNone(BigInt_.fromString(\"-Infinity\"))\n    assertNone(BigInt_.fromString(\"3.14\"))\n    assertNone(BigInt_.fromString(\"-3.14\"))\n    assertNone(BigInt_.fromString(\"1e3\"))\n    assertNone(BigInt_.fromString(\"1e-3\"))\n    assertNone(BigInt_.fromString(\"\"))\n    assertNone(BigInt_.fromString(\"a\"))\n    assertSome(BigInt_.fromString(\"42\"), BigInt(42))\n    assertSome(BigInt_.fromString(\"\\n\\r\\t 42 \\n\\r\\t\"), BigInt(42))\n  })\n\n  it(\"fromNumber\", () => {\n    assertSome(BigInt_.fromNumber(Number.MAX_SAFE_INTEGER), BigInt(Number.MAX_SAFE_INTEGER))\n    assertNone(BigInt_.fromNumber(Number.MAX_SAFE_INTEGER + 1))\n    assertSome(BigInt_.fromNumber(Number.MIN_SAFE_INTEGER), BigInt(Number.MIN_SAFE_INTEGER))\n    assertNone(BigInt_.fromNumber(Number.MIN_SAFE_INTEGER - 1))\n    assertNone(BigInt_.fromNumber(Infinity))\n    assertNone(BigInt_.fromNumber(-Infinity))\n    assertNone(BigInt_.fromNumber(NaN))\n    assertNone(BigInt_.fromNumber(1e100))\n    assertNone(BigInt_.fromNumber(-1e100))\n    assertNone(BigInt_.fromNumber(3.14))\n    assertNone(BigInt_.fromNumber(-3.14))\n    assertSome(BigInt_.fromNumber(0), BigInt(0))\n    assertSome(BigInt_.fromNumber(42), BigInt(42))\n    assertSome(BigInt_.fromNumber(-42), BigInt(-42))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Boolean.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Boolean, pipe } from \"effect\"\n\ndescribe(\"Boolean\", () => {\n  it(\"isBoolean\", () => {\n    assertTrue(Boolean.isBoolean(true))\n    assertTrue(Boolean.isBoolean(false))\n    assertFalse(Boolean.isBoolean(\"a\"))\n    assertFalse(Boolean.isBoolean(1))\n  })\n\n  it(\"and\", () => {\n    assertTrue(pipe(true, Boolean.and(true)))\n    assertFalse(pipe(true, Boolean.and(false)))\n    assertFalse(pipe(false, Boolean.and(true)))\n    assertFalse(pipe(false, Boolean.and(false)))\n  })\n\n  it(\"nand\", () => {\n    assertFalse(pipe(true, Boolean.nand(true)))\n    assertTrue(pipe(true, Boolean.nand(false)))\n    assertTrue(pipe(false, Boolean.nand(true)))\n    assertTrue(pipe(false, Boolean.nand(false)))\n  })\n\n  it(\"or\", () => {\n    assertTrue(pipe(true, Boolean.or(true)))\n    assertTrue(pipe(true, Boolean.or(false)))\n    assertTrue(pipe(false, Boolean.or(true)))\n    assertFalse(pipe(false, Boolean.or(false)))\n  })\n\n  it(\"nor\", () => {\n    assertFalse(pipe(true, Boolean.nor(true)))\n    assertFalse(pipe(true, Boolean.nor(false)))\n    assertFalse(pipe(false, Boolean.nor(true)))\n    assertTrue(pipe(false, Boolean.nor(false)))\n  })\n\n  it(\"xor\", () => {\n    assertFalse(pipe(true, Boolean.xor(true)))\n    assertTrue(pipe(true, Boolean.xor(false)))\n    assertTrue(pipe(false, Boolean.xor(true)))\n    assertFalse(pipe(false, Boolean.xor(false)))\n  })\n\n  it(\"eqv\", () => {\n    assertTrue(pipe(true, Boolean.eqv(true)))\n    assertFalse(pipe(true, Boolean.eqv(false)))\n    assertFalse(pipe(false, Boolean.eqv(true)))\n    assertTrue(pipe(false, Boolean.eqv(false)))\n  })\n\n  it(\"implies\", () => {\n    assertTrue(pipe(true, Boolean.implies(true)))\n    assertFalse(pipe(true, Boolean.implies(false)))\n    assertTrue(pipe(false, Boolean.implies(true)))\n    assertTrue(pipe(false, Boolean.implies(false)))\n  })\n\n  it(\"not\", () => {\n    assertFalse(pipe(true, Boolean.not))\n    assertTrue(pipe(false, Boolean.not))\n  })\n\n  it(\"match\", () => {\n    const match = Boolean.match({\n      onFalse: () => \"false\",\n      onTrue: () => \"true\"\n    })\n    deepStrictEqual(match(true), \"true\")\n    deepStrictEqual(match(false), \"false\")\n  })\n\n  it(\"Equivalence\", () => {\n    assertTrue(Boolean.Equivalence(true, true))\n    assertTrue(Boolean.Equivalence(false, false))\n    assertFalse(Boolean.Equivalence(true, false))\n    assertFalse(Boolean.Equivalence(false, true))\n  })\n\n  it(\"Order\", () => {\n    deepStrictEqual(Boolean.Order(false, true), -1)\n    deepStrictEqual(Boolean.Order(true, false), 1)\n    deepStrictEqual(Boolean.Order(true, true), 0)\n  })\n\n  it(\"every\", () => {\n    assertTrue(Boolean.every([true, true, true]))\n    assertFalse(Boolean.every([true, false, true]))\n  })\n\n  it(\"some\", () => {\n    assertTrue(Boolean.some([true, false, true]))\n    assertFalse(Boolean.some([false, false, false]))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Brand.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertLeft,\n  assertNone,\n  assertRight,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { Brand, Option } from \"effect\"\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\ndeclare const IntTypeId: unique symbol\ntype Int = number & Brand.Brand<typeof IntTypeId>\nconst Int = Brand.refined<Int>(\n  (n) => Number.isInteger(n),\n  (n) => Brand.error(`Expected ${n} to be an integer`)\n)\n\ntype Positive = number & Brand.Brand<\"Positive\">\nconst Positive = Brand.refined<Positive>(\n  (n) => n > 0,\n  (n) => Brand.error(`Expected ${n} to be positive`)\n)\n\ntype PositiveInt = Positive & Int\nconst PositiveInt = Brand.all(Int, Positive)\n\ndescribe(\"Brand\", () => {\n  it(\"nominal\", () => {\n    type MyNumber = number & Brand.Brand<\"MyNumber\">\n    const MyNumber = Brand.nominal<MyNumber>()\n    strictEqual(MyNumber(1), 1)\n    strictEqual(MyNumber(1.1), 1.1)\n    assertTrue(MyNumber.is(1))\n    assertTrue(MyNumber.is(1.1))\n  })\n\n  it(\"refined (predicate overload)\", () => {\n    strictEqual(Int(1), 1)\n    throws(() => Int(1.1))\n    assertSome(Int.option(1), 1 as Int)\n    assertNone(Int.option(1.1))\n    assertRight(Int.either(1), 1 as Int)\n    assertLeft(\n      Int.either(1.1),\n      Brand.error(\"Expected 1.1 to be an integer\")\n    )\n    assertTrue(Int.is(1))\n    assertFalse(Int.is(1.1))\n    throws(() => Int(1.1), (err) => {\n      deepStrictEqual(err, Brand.error(\"Expected 1.1 to be an integer\"))\n    })\n  })\n\n  it(\"refined (Option overload)\", () => {\n    const Int = Brand.refined<Int>(\n      (n) => Number.isInteger(n) ? Option.none() : Option.some(Brand.error(`Expected ${n} to be an integer`))\n    )\n    throws(() => Int(1.1), (err) => {\n      deepStrictEqual(err, Brand.error(\"Expected 1.1 to be an integer\"))\n    })\n  })\n\n  it(\"composition\", () => {\n    strictEqual(PositiveInt(1), 1)\n    throws(() => PositiveInt(1.1))\n    assertSome(PositiveInt.option(1), 1 as PositiveInt)\n    assertNone(PositiveInt.option(1.1))\n    assertRight(PositiveInt.either(1), 1 as PositiveInt)\n    assertLeft(\n      PositiveInt.either(1.1),\n      Brand.error(\"Expected 1.1 to be an integer\")\n    )\n    assertLeft(\n      PositiveInt.either(-1.1),\n      Brand.errors(\n        Brand.error(\"Expected -1.1 to be an integer\"),\n        Brand.error(\"Expected -1.1 to be positive\")\n      )\n    )\n    assertTrue(PositiveInt.is(1))\n    assertFalse(PositiveInt.is(1.1))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Cache.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { Cache, Effect, TestClock } from \"effect\"\n\ndescribe(\"Cache\", () => {\n  it.effect(\"should not increment cache hits on expired entries\", () =>\n    Effect.gen(function*() {\n      const cache = yield* Cache.make({\n        capacity: 100,\n        timeToLive: \"1 seconds\",\n        lookup: (n: number): Effect.Effect<number, 2> => Effect.succeed(n)\n      })\n      yield* cache.get(42)\n      yield* TestClock.adjust(\"2 seconds\")\n      yield* cache.get(42)\n      const { hits, misses } = yield* cache.cacheStats\n      strictEqual(hits, 0)\n      strictEqual(misses, 2)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Cause.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertInclude,\n  assertLeft,\n  assertNone,\n  assertRight,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual\n} from \"@effect/vitest/utils\"\nimport {\n  Array as Arr,\n  Cause,\n  Effect,\n  Equal,\n  FastCheck as fc,\n  FiberId,\n  Hash,\n  Inspectable,\n  Option,\n  Predicate\n} from \"effect\"\nimport * as internal from \"../src/internal/cause.js\"\nimport { causes, equalCauses, errorCauseFunctions, errors } from \"./utils/cause.js\"\n\ndescribe(\"Cause\", () => {\n  const empty = Cause.empty\n  const failure = Cause.fail(\"error\")\n  const defect = Cause.die(\"defect\")\n  const interruption = Cause.interrupt(FiberId.runtime(1, 0))\n  const sequential = Cause.sequential(failure, defect)\n  const parallel = Cause.parallel(failure, defect)\n\n  describe(\"InterruptedException\", () => {\n    it(\"correctly implements toString() and the NodeInspectSymbol\", () => {\n      // Referenced line to be included in the string output\n      const ex = new Cause.InterruptedException(\"my message\")\n      assertInclude(ex.toString(), \"InterruptedException: my message\")\n\n      // In Node.js environments, ensure the 'inspect' method includes line information\n      if (typeof window === \"undefined\") {\n        // eslint-disable-next-line @typescript-eslint/no-require-imports\n        const { inspect } = require(\"node:util\")\n        assertInclude(inspect(ex), \"Cause.test.ts:39\") // <= reference to the line above\n      }\n    })\n  })\n\n  describe(\"UnknownException\", () => {\n    it(\"exposes its `error` property\", () => {\n      strictEqual(new Cause.UnknownException(\"my message\").error, \"my message\")\n      const { error } = new Cause.UnknownException(new Error(\"my error\"))\n      assertTrue(Predicate.isError(error))\n      strictEqual(error.message, \"my error\")\n    })\n\n    it(\"exposes its `cause` property\", () => {\n      strictEqual(new Cause.UnknownException(\"my message\").cause, \"my message\")\n      const err2 = new Cause.UnknownException(new Error(\"my error\"))\n      assertTrue(Predicate.isError(err2.cause))\n      strictEqual(err2.cause.message, \"my error\")\n    })\n\n    it(\"uses a default message when none is provided\", () => {\n      strictEqual(new Cause.UnknownException(\"my message\").message, \"An unknown error occurred\")\n    })\n\n    it(\"accepts a custom override message\", () => {\n      strictEqual(new Cause.UnknownException(new Error(\"my error\"), \"my message\").message, \"my message\")\n    })\n  })\n\n  it(\"[internal] prettyErrorMessage converts errors into readable JSON-like strings\", () => {\n    class Error1 {\n      readonly _tag = \"WithTag\"\n    }\n    strictEqual(internal.prettyErrorMessage(new Error1()), `{\"_tag\":\"WithTag\"}`)\n    class Error2 {\n      readonly _tag = \"WithMessage\"\n      readonly message = \"my message\"\n    }\n    strictEqual(internal.prettyErrorMessage(new Error2()), `{\"_tag\":\"WithMessage\",\"message\":\"my message\"}`)\n    class Error3 {\n      readonly _tag = \"WithName\"\n      readonly name = \"my name\"\n    }\n    strictEqual(internal.prettyErrorMessage(new Error3()), `{\"_tag\":\"WithName\",\"name\":\"my name\"}`)\n    class Error4 {\n      readonly _tag = \"WithName\"\n      readonly name = \"my name\"\n      readonly message = \"my message\"\n    }\n    strictEqual(\n      internal.prettyErrorMessage(new Error4()),\n      `{\"_tag\":\"WithName\",\"name\":\"my name\",\"message\":\"my message\"}`\n    )\n    class Error5 {\n      readonly _tag = \"WithToString\"\n      toString() {\n        return \"Error: my string\"\n      }\n    }\n    strictEqual(internal.prettyErrorMessage(new Error5()), `Error: my string`)\n  })\n\n  describe(\"Cause prototype\", () => {\n    describe(\"toJSON / [NodeInspectSymbol]\", () => {\n      const expectJSON = (cause: Cause.Cause<unknown>, expected: unknown) => {\n        deepStrictEqual(cause.toJSON(), expected)\n        deepStrictEqual(cause[Inspectable.NodeInspectSymbol](), expected)\n      }\n\n      it(\"Empty\", () => {\n        expectJSON(Cause.empty, {\n          _id: \"Cause\",\n          _tag: \"Empty\"\n        })\n      })\n\n      it(\"Fail\", () => {\n        expectJSON(Cause.fail(Option.some(1)), {\n          _id: \"Cause\",\n          _tag: \"Fail\",\n          failure: {\n            _id: \"Option\",\n            _tag: \"Some\",\n            value: 1\n          }\n        })\n      })\n\n      it(\"Die\", () => {\n        expectJSON(Cause.die(Option.some(1)), {\n          _id: \"Cause\",\n          _tag: \"Die\",\n          defect: {\n            _id: \"Option\",\n            _tag: \"Some\",\n            value: 1\n          }\n        })\n      })\n\n      it(\"Interrupt\", () => {\n        expectJSON(Cause.interrupt(FiberId.none), {\n          _id: \"Cause\",\n          _tag: \"Interrupt\",\n          fiberId: {\n            _id: \"FiberId\",\n            _tag: \"None\"\n          }\n        })\n        expectJSON(Cause.interrupt(FiberId.runtime(1, 0)), {\n          _id: \"Cause\",\n          _tag: \"Interrupt\",\n          fiberId: {\n            _id: \"FiberId\",\n            _tag: \"Runtime\",\n            id: 1,\n            startTimeMillis: 0\n          }\n        })\n        expectJSON(Cause.interrupt(FiberId.composite(FiberId.none, FiberId.runtime(1, 0))), {\n          _id: \"Cause\",\n          _tag: \"Interrupt\",\n          fiberId: {\n            _id: \"FiberId\",\n            _tag: \"Composite\",\n            left: {\n              _id: \"FiberId\",\n              _tag: \"None\"\n            },\n            right: {\n              _id: \"FiberId\",\n              _tag: \"Runtime\",\n              id: 1,\n              startTimeMillis: 0\n            }\n          }\n        })\n      })\n\n      it(\"Sequential\", () => {\n        expectJSON(Cause.sequential(Cause.fail(\"failure 1\"), Cause.fail(\"failure 2\")), {\n          _id: \"Cause\",\n          _tag: \"Sequential\",\n          left: {\n            _id: \"Cause\",\n            _tag: \"Fail\",\n            failure: \"failure 1\"\n          },\n          right: {\n            _id: \"Cause\",\n            _tag: \"Fail\",\n            failure: \"failure 2\"\n          }\n        })\n      })\n\n      it(\"Parallel\", () => {\n        expectJSON(Cause.parallel(Cause.fail(\"failure 1\"), Cause.fail(\"failure 2\")), {\n          _id: \"Cause\",\n          _tag: \"Parallel\",\n          left: {\n            _id: \"Cause\",\n            _tag: \"Fail\",\n            failure: \"failure 1\"\n          },\n          right: {\n            _id: \"Cause\",\n            _tag: \"Fail\",\n            failure: \"failure 2\"\n          }\n        })\n      })\n    })\n\n    describe(\"toString\", () => {\n      it(\"Empty\", () => {\n        strictEqual(String(Cause.empty), `All fibers interrupted without errors.`)\n      })\n\n      it(\"Fail\", () => {\n        strictEqual(String(Cause.fail(\"my failure\")), `Error: my failure`)\n        assertInclude(String(Cause.fail(new Error(\"my failure\"))), \"Error: my failure\")\n      })\n\n      it(\"Die\", () => {\n        strictEqual(String(Cause.die(\"die message\")), `Error: die message`)\n        assertInclude(String(Cause.die(new Error(\"die message\"))), \"Error: die message\")\n      })\n\n      it(\"Interrupt\", () => {\n        strictEqual(String(Cause.interrupt(FiberId.none)), `All fibers interrupted without errors.`)\n        strictEqual(String(Cause.interrupt(FiberId.runtime(1, 0))), `All fibers interrupted without errors.`)\n        strictEqual(\n          String(Cause.interrupt(FiberId.composite(FiberId.none, FiberId.runtime(1, 0)))),\n          `All fibers interrupted without errors.`\n        )\n      })\n\n      it(\"Sequential\", () => {\n        strictEqual(\n          String(Cause.sequential(Cause.fail(\"failure 1\"), Cause.fail(\"failure 2\"))),\n          `Error: failure 1\\nError: failure 2`\n        )\n        const actual = String(Cause.sequential(Cause.fail(new Error(\"failure 1\")), Cause.fail(new Error(\"failure 2\"))))\n        assertInclude(actual, \"Error: failure 1\")\n        assertInclude(actual, \"Error: failure 2\")\n      })\n\n      it(\"Parallel\", () => {\n        strictEqual(\n          String(Cause.parallel(Cause.fail(\"failure 1\"), Cause.fail(\"failure 2\"))),\n          `Error: failure 1\\nError: failure 2`\n        )\n        const actual = String(\n          String(Cause.parallel(Cause.fail(new Error(\"failure 1\")), Cause.fail(new Error(\"failure 2\"))))\n        )\n        assertInclude(actual, \"Error: failure 1\")\n        assertInclude(actual, \"Error: failure 2\")\n      })\n    })\n\n    describe(\"Equal.symbol implementation\", () => {\n      it(\"compares causes by value\", () => {\n        assertTrue(Equal.equals(Cause.fail(0), Cause.fail(0)))\n        assertTrue(Equal.equals(Cause.die(0), Cause.die(0)))\n        assertFalse(Equal.equals(Cause.fail(0), Cause.fail(1)))\n        assertFalse(Equal.equals(Cause.die(0), Cause.die(1)))\n      })\n\n      it(\"is symmetric\", () => {\n        fc.assert(fc.property(causes, causes, (causeA, causeB) => {\n          strictEqual(\n            Equal.equals(causeA, causeB),\n            Equal.equals(causeB, causeA)\n          )\n        }))\n      })\n\n      it(\"generates identical hashes for equal causes\", () => {\n        fc.assert(fc.property(equalCauses, ([causeA, causeB]) => {\n          strictEqual(Hash.hash(causeA), Hash.hash(causeB))\n        }))\n      })\n\n      it(\"distinguishes different failure types\", () => {\n        assertFalse(Equal.equals(Cause.die(0), Cause.fail(0)))\n        assertFalse(\n          Equal.equals(\n            Cause.parallel(Cause.fail(\"fail1\"), Cause.die(\"fail2\")),\n            Cause.parallel(Cause.fail(\"fail2\"), Cause.die(\"fail1\"))\n          )\n        )\n        assertFalse(\n          Equal.equals(\n            Cause.sequential(Cause.fail(\"fail1\"), Cause.die(\"fail2\")),\n            Cause.parallel(Cause.fail(\"fail1\"), Cause.die(\"fail2\"))\n          )\n        )\n      })\n    })\n  })\n\n  describe(\"Guards\", () => {\n    it(\"isCause\", () => {\n      assertTrue(Cause.isCause(empty))\n      assertTrue(Cause.isCause(failure))\n      assertTrue(Cause.isCause(defect))\n      assertTrue(Cause.isCause(interruption))\n      assertTrue(Cause.isCause(sequential))\n      assertTrue(Cause.isCause(parallel))\n\n      assertFalse(Cause.isCause({}))\n    })\n\n    it(\"isEmptyType\", () => {\n      assertTrue(Cause.isEmptyType(empty))\n      assertFalse(Cause.isEmptyType(failure))\n      assertFalse(Cause.isEmptyType(defect))\n      assertFalse(Cause.isEmptyType(interruption))\n      assertFalse(Cause.isEmptyType(sequential))\n      assertFalse(Cause.isEmptyType(parallel))\n    })\n\n    it(\"isFailType\", () => {\n      assertFalse(Cause.isFailType(empty))\n      assertTrue(Cause.isFailType(failure))\n      assertFalse(Cause.isFailType(defect))\n      assertFalse(Cause.isFailType(interruption))\n      assertFalse(Cause.isFailType(sequential))\n      assertFalse(Cause.isFailType(parallel))\n    })\n\n    it(\"isDieType\", () => {\n      assertFalse(Cause.isDieType(empty))\n      assertFalse(Cause.isDieType(failure))\n      assertTrue(Cause.isDieType(defect))\n      assertFalse(Cause.isDieType(interruption))\n      assertFalse(Cause.isDieType(sequential))\n      assertFalse(Cause.isDieType(parallel))\n    })\n\n    it(\"isInterruptType\", () => {\n      assertFalse(Cause.isInterruptType(empty))\n      assertFalse(Cause.isInterruptType(failure))\n      assertFalse(Cause.isInterruptType(defect))\n      assertTrue(Cause.isInterruptType(interruption))\n      assertFalse(Cause.isInterruptType(sequential))\n      assertFalse(Cause.isInterruptType(parallel))\n    })\n\n    it(\"isSequentialType\", () => {\n      assertFalse(Cause.isSequentialType(empty))\n      assertFalse(Cause.isSequentialType(failure))\n      assertFalse(Cause.isSequentialType(defect))\n      assertFalse(Cause.isSequentialType(interruption))\n      assertTrue(Cause.isSequentialType(sequential))\n      assertFalse(Cause.isSequentialType(parallel))\n    })\n\n    it(\"isParallelType\", () => {\n      assertFalse(Cause.isParallelType(empty))\n      assertFalse(Cause.isParallelType(failure))\n      assertFalse(Cause.isParallelType(defect))\n      assertFalse(Cause.isParallelType(interruption))\n      assertFalse(Cause.isParallelType(sequential))\n      assertTrue(Cause.isParallelType(parallel))\n    })\n  })\n\n  describe(\"Getters\", () => {\n    it(\"isEmpty\", () => {\n      assertTrue(Cause.isEmpty(empty))\n      assertTrue(Cause.isEmpty(Cause.sequential(empty, empty)))\n      assertTrue(Cause.isEmpty(Cause.parallel(empty, empty)))\n      assertTrue(Cause.isEmpty(Cause.parallel(empty, Cause.sequential(empty, empty))))\n      assertTrue(Cause.isEmpty(Cause.sequential(empty, Cause.parallel(empty, empty))))\n\n      assertFalse(Cause.isEmpty(defect))\n      assertFalse(Cause.isEmpty(Cause.sequential(empty, failure)))\n      assertFalse(Cause.isEmpty(Cause.parallel(empty, failure)))\n      assertFalse(Cause.isEmpty(Cause.parallel(empty, Cause.sequential(empty, failure))))\n      assertFalse(Cause.isEmpty(Cause.sequential(empty, Cause.parallel(empty, failure))))\n    })\n\n    it(\"isFailure\", () => {\n      assertTrue(Cause.isFailure(failure))\n      assertTrue(Cause.isFailure(Cause.sequential(empty, failure)))\n      assertTrue(Cause.isFailure(Cause.parallel(empty, failure)))\n      assertTrue(Cause.isFailure(Cause.parallel(empty, Cause.sequential(empty, failure))))\n      assertTrue(Cause.isFailure(Cause.sequential(empty, Cause.parallel(empty, failure))))\n\n      assertFalse(Cause.isFailure(Cause.sequential(empty, Cause.parallel(empty, empty))))\n    })\n\n    it(\"isDie\", () => {\n      assertTrue(Cause.isDie(defect))\n      assertTrue(Cause.isDie(Cause.sequential(empty, defect)))\n      assertTrue(Cause.isDie(Cause.parallel(empty, defect)))\n      assertTrue(Cause.isDie(Cause.parallel(empty, Cause.sequential(empty, defect))))\n      assertTrue(Cause.isDie(Cause.sequential(empty, Cause.parallel(empty, defect))))\n\n      assertFalse(Cause.isDie(Cause.sequential(empty, Cause.parallel(empty, empty))))\n    })\n\n    it(\"isInterrupted\", () => {\n      assertTrue(Cause.isInterrupted(interruption))\n      assertTrue(Cause.isInterrupted(Cause.sequential(empty, interruption)))\n      assertTrue(Cause.isInterrupted(Cause.parallel(empty, interruption)))\n      assertTrue(Cause.isInterrupted(Cause.parallel(empty, Cause.sequential(empty, interruption))))\n      assertTrue(Cause.isInterrupted(Cause.sequential(empty, Cause.parallel(empty, interruption))))\n\n      assertTrue(Cause.isInterrupted(Cause.sequential(failure, interruption)))\n      assertTrue(Cause.isInterrupted(Cause.parallel(failure, interruption)))\n      assertTrue(Cause.isInterrupted(Cause.parallel(failure, Cause.sequential(empty, interruption))))\n      assertTrue(Cause.isInterrupted(Cause.sequential(failure, Cause.parallel(empty, interruption))))\n\n      assertFalse(Cause.isInterrupted(Cause.sequential(empty, Cause.parallel(empty, empty))))\n    })\n\n    it(\"isInterruptedOnly\", () => {\n      assertTrue(Cause.isInterruptedOnly(interruption))\n      assertTrue(Cause.isInterruptedOnly(Cause.sequential(empty, interruption)))\n      assertTrue(Cause.isInterruptedOnly(Cause.parallel(empty, interruption)))\n      assertTrue(Cause.isInterruptedOnly(Cause.parallel(empty, Cause.sequential(empty, interruption))))\n      assertTrue(Cause.isInterruptedOnly(Cause.sequential(empty, Cause.parallel(empty, interruption))))\n      // Cause.empty is considered a valid candidate\n      assertTrue(Cause.isInterruptedOnly(Cause.sequential(empty, Cause.parallel(empty, empty))))\n\n      assertFalse(Cause.isInterruptedOnly(Cause.sequential(failure, interruption)))\n      assertFalse(Cause.isInterruptedOnly(Cause.parallel(failure, interruption)))\n      assertFalse(Cause.isInterruptedOnly(Cause.parallel(failure, Cause.sequential(empty, interruption))))\n      assertFalse(Cause.isInterruptedOnly(Cause.sequential(failure, Cause.parallel(empty, interruption))))\n    })\n\n    describe(\"failures\", () => {\n      it(\"should return a Chunk of all recoverable errors\", () => {\n        const expectFailures = <E>(cause: Cause.Cause<E>, expected: Array<E>) => {\n          deepStrictEqual([...Cause.failures(cause)], expected)\n        }\n        expectFailures(empty, [])\n        expectFailures(failure, [\"error\"])\n        expectFailures(Cause.parallel(Cause.fail(\"error1\"), Cause.fail(\"error2\")), [\"error1\", \"error2\"])\n        expectFailures(Cause.sequential(Cause.fail(\"error1\"), Cause.fail(\"error2\")), [\"error1\", \"error2\"])\n        expectFailures(Cause.parallel(failure, defect), [\"error\"])\n        expectFailures(Cause.sequential(failure, defect), [\"error\"])\n        expectFailures(Cause.sequential(interruption, Cause.parallel(empty, failure)), [\"error\"])\n      })\n\n      it(\"fails safely for large parallel cause constructions\", () => {\n        const n = 10_000\n        const cause = Array.from({ length: n - 1 }, () => Cause.fail(\"fail\")).reduce(Cause.parallel, Cause.fail(\"fail\"))\n        const result = Cause.failures(cause)\n        strictEqual(Array.from(result).length, n)\n      })\n    })\n\n    it(\"defects\", () => {\n      const expectDefects = <E>(cause: Cause.Cause<E>, expected: Array<unknown>) => {\n        deepStrictEqual([...Cause.defects(cause)], expected)\n      }\n      expectDefects(empty, [])\n      expectDefects(defect, [\"defect\"])\n      expectDefects(Cause.parallel(Cause.die(\"defect1\"), Cause.die(\"defect2\")), [\"defect1\", \"defect2\"])\n      expectDefects(Cause.sequential(Cause.die(\"defect1\"), Cause.die(\"defect2\")), [\"defect1\", \"defect2\"])\n      expectDefects(Cause.parallel(failure, defect), [\"defect\"])\n      expectDefects(Cause.sequential(failure, defect), [\"defect\"])\n      expectDefects(Cause.sequential(interruption, Cause.parallel(empty, defect)), [\"defect\"])\n    })\n\n    it(\"interruptors\", () => {\n      const expectInterruptors = <E>(cause: Cause.Cause<E>, expected: Array<FiberId.FiberId>) => {\n        deepStrictEqual([...Cause.interruptors(cause)], expected)\n      }\n      expectInterruptors(empty, [])\n      expectInterruptors(interruption, [FiberId.runtime(1, 0)])\n      expectInterruptors(\n        Cause.sequential(\n          Cause.interrupt(FiberId.runtime(1, 0)),\n          Cause.parallel(empty, Cause.interrupt(FiberId.runtime(2, 0)))\n        ),\n        [FiberId.runtime(2, 0), FiberId.runtime(1, 0)]\n      )\n    })\n\n    it(\"size\", () => {\n      strictEqual(Cause.size(empty), 0)\n      strictEqual(Cause.size(failure), 1)\n      strictEqual(Cause.size(defect), 1)\n      strictEqual(Cause.size(Cause.parallel(Cause.fail(\"error1\"), Cause.fail(\"error2\"))), 2)\n      strictEqual(Cause.size(Cause.sequential(Cause.fail(\"error1\"), Cause.fail(\"error2\"))), 2)\n      strictEqual(Cause.size(Cause.parallel(failure, defect)), 2)\n      strictEqual(Cause.size(Cause.sequential(failure, defect)), 2)\n      strictEqual(Cause.size(Cause.sequential(interruption, Cause.parallel(empty, failure))), 2)\n      strictEqual(Cause.size(Cause.sequential(interruption, Cause.parallel(defect, failure))), 3)\n    })\n\n    it(\"failureOption\", () => {\n      const expectFailureOption = <E>(cause: Cause.Cause<E>, expected: Option.Option<E>) => {\n        deepStrictEqual(Cause.failureOption(cause), expected)\n      }\n      expectFailureOption(empty, Option.none())\n      expectFailureOption(failure, Option.some(\"error\"))\n      expectFailureOption(Cause.sequential(Cause.fail(\"error1\"), Cause.fail(\"error2\")), Option.some(\"error1\"))\n      expectFailureOption(Cause.parallel(Cause.fail(\"error1\"), Cause.fail(\"error2\")), Option.some(\"error1\"))\n      expectFailureOption(Cause.parallel(failure, defect), Option.some(\"error\"))\n      expectFailureOption(Cause.sequential(failure, defect), Option.some(\"error\"))\n      expectFailureOption(Cause.sequential(interruption, Cause.parallel(empty, failure)), Option.some(\"error\"))\n    })\n\n    it(\"failureOrCause\", () => {\n      const expectLeft = <E>(cause: Cause.Cause<E>, expected: E) => {\n        assertLeft(Cause.failureOrCause(cause), expected)\n      }\n      const expectRight = (cause: Cause.Cause<never>) => {\n        assertRight(Cause.failureOrCause(cause), cause)\n      }\n\n      expectLeft(failure, \"error\")\n      expectLeft(Cause.parallel(Cause.fail(\"error1\"), Cause.fail(\"error2\")), \"error1\")\n      expectLeft(Cause.sequential(Cause.fail(\"error1\"), Cause.fail(\"error2\")), \"error1\")\n      expectLeft(Cause.sequential(interruption, Cause.parallel(empty, failure)), \"error\")\n\n      expectRight(empty)\n      expectRight(defect)\n      expectRight(interruption)\n      expectRight(Cause.sequential(interruption, Cause.parallel(empty, defect)))\n    })\n\n    it(\"flipCauseOption\", () => {\n      assertSome(Cause.flipCauseOption(empty), empty)\n      assertSome(Cause.flipCauseOption(defect), defect)\n      assertSome(Cause.flipCauseOption(interruption), interruption)\n      assertNone(Cause.flipCauseOption(Cause.fail(Option.none())))\n      assertSome(Cause.flipCauseOption(Cause.fail(Option.some(\"error\"))), Cause.fail(\"error\"))\n      // sequential\n      assertSome(\n        Cause.flipCauseOption(Cause.sequential(Cause.fail(Option.some(\"error1\")), Cause.fail(Option.some(\"error2\")))),\n        Cause.sequential(Cause.fail(\"error1\"), Cause.fail(\"error2\"))\n      )\n      assertSome(\n        Cause.flipCauseOption(Cause.sequential(Cause.fail(Option.some(\"error1\")), Cause.fail(Option.none()))),\n        Cause.fail(\"error1\")\n      )\n      assertSome(\n        Cause.flipCauseOption(Cause.sequential(Cause.fail(Option.none()), Cause.fail(Option.some(\"error2\")))),\n        Cause.fail(\"error2\")\n      )\n      assertNone(\n        Cause.flipCauseOption(Cause.sequential(Cause.fail(Option.none()), Cause.fail(Option.none())))\n      )\n      // parallel\n      assertSome(\n        Cause.flipCauseOption(Cause.parallel(Cause.fail(Option.some(\"error1\")), Cause.fail(Option.some(\"error2\")))),\n        Cause.parallel(Cause.fail(\"error1\"), Cause.fail(\"error2\"))\n      )\n      assertSome(\n        Cause.flipCauseOption(Cause.parallel(Cause.fail(Option.some(\"error1\")), Cause.fail(Option.none()))),\n        Cause.fail(\"error1\")\n      )\n      assertSome(\n        Cause.flipCauseOption(Cause.parallel(Cause.fail(Option.none()), Cause.fail(Option.some(\"error2\")))),\n        Cause.fail(\"error2\")\n      )\n      assertNone(\n        Cause.flipCauseOption(Cause.parallel(Cause.fail(Option.none()), Cause.fail(Option.none())))\n      )\n    })\n\n    it(\"dieOption\", () => {\n      const expectDieOption = <E>(cause: Cause.Cause<E>, expected: Option.Option<unknown>) => {\n        deepStrictEqual(Cause.dieOption(cause), expected)\n      }\n      expectDieOption(empty, Option.none())\n      expectDieOption(defect, Option.some(\"defect\"))\n      expectDieOption(Cause.parallel(Cause.die(\"defect1\"), Cause.die(\"defect2\")), Option.some(\"defect1\"))\n      expectDieOption(Cause.sequential(Cause.die(\"defect1\"), Cause.die(\"defect2\")), Option.some(\"defect1\"))\n      expectDieOption(Cause.parallel(failure, defect), Option.some(\"defect\"))\n      expectDieOption(Cause.sequential(failure, defect), Option.some(\"defect\"))\n      expectDieOption(Cause.sequential(interruption, Cause.parallel(empty, defect)), Option.some(\"defect\"))\n    })\n\n    it(\"interruptOption\", () => {\n      const expectInterruptOption = <E>(cause: Cause.Cause<E>, expected: Option.Option<FiberId.FiberId>) => {\n        deepStrictEqual(Cause.interruptOption(cause), expected)\n      }\n      expectInterruptOption(empty, Option.none())\n      expectInterruptOption(interruption, Option.some(FiberId.runtime(1, 0)))\n      expectInterruptOption(\n        Cause.sequential(\n          Cause.interrupt(FiberId.runtime(1, 0)),\n          Cause.parallel(empty, Cause.interrupt(FiberId.runtime(2, 0)))\n        ),\n        Option.some(FiberId.runtime(1, 0))\n      )\n    })\n\n    it(\"keepDefects\", () => {\n      assertNone(Cause.keepDefects(empty))\n      assertNone(Cause.keepDefects(failure))\n      assertSome(Cause.keepDefects(defect), defect)\n      assertSome(\n        Cause.keepDefects(Cause.sequential(Cause.die(\"defect1\"), Cause.die(\"defect2\"))),\n        Cause.sequential(Cause.die(\"defect1\"), Cause.die(\"defect2\"))\n      )\n      assertNone(Cause.keepDefects(Cause.sequential(empty, empty)))\n      assertSome(Cause.keepDefects(Cause.sequential(defect, failure)), defect)\n      assertNone(Cause.keepDefects(Cause.parallel(empty, empty)))\n      assertSome(Cause.keepDefects(Cause.parallel(defect, failure)), defect)\n      assertSome(\n        Cause.keepDefects(Cause.parallel(Cause.die(\"defect1\"), Cause.die(\"defect2\"))),\n        Cause.parallel(Cause.die(\"defect1\"), Cause.die(\"defect2\"))\n      )\n      assertSome(\n        Cause.keepDefects(\n          Cause.sequential(failure, Cause.parallel(Cause.die(\"defect1\"), Cause.die(\"defect2\")))\n        ),\n        Cause.parallel(Cause.die(\"defect1\"), Cause.die(\"defect2\"))\n      )\n      assertSome(\n        Cause.keepDefects(\n          Cause.sequential(Cause.die(\"defect1\"), Cause.parallel(failure, Cause.die(\"defect2\")))\n        ),\n        Cause.sequential(Cause.die(\"defect1\"), Cause.die(\"defect2\"))\n      )\n    })\n\n    it(\"ensures isDie and keepDefects are consistent\", () => {\n      fc.assert(fc.property(causes, (cause) => {\n        const result = Cause.keepDefects(cause)\n        if (Cause.isDie(cause)) {\n          return Option.isSome(result)\n        } else {\n          return Option.isNone(result)\n        }\n      }))\n    })\n\n    it(\"linearize\", () => {\n      const expectLinearize = <E>(cause: Cause.Cause<E>, expected: Array<Cause.Cause<E>>) => {\n        deepStrictEqual([...Cause.linearize(cause)], expected)\n      }\n      expectLinearize(empty, [])\n      expectLinearize(failure, [failure])\n      expectLinearize(defect, [defect])\n      expectLinearize(interruption, [interruption])\n      expectLinearize(Cause.sequential(failure, defect), [Cause.sequential(failure, defect)])\n      expectLinearize(Cause.parallel(failure, defect), [Cause.parallel(failure, defect)])\n      expectLinearize(Cause.sequential(failure, Cause.sequential(interruption, defect)), [\n        Cause.sequential(failure, Cause.sequential(interruption, defect))\n      ])\n      expectLinearize(Cause.parallel(failure, Cause.parallel(interruption, defect)), [\n        Cause.parallel(failure, Cause.parallel(interruption, defect))\n      ])\n      expectLinearize(\n        Cause.sequential(\n          Cause.sequential(Cause.fail(\"error1\"), Cause.fail(\"error2\")),\n          Cause.sequential(Cause.fail(\"error3\"), Cause.fail(\"error4\"))\n        ),\n        [\n          Cause.sequential(\n            Cause.sequential(Cause.fail(\"error1\"), Cause.fail(\"error2\")),\n            Cause.sequential(Cause.fail(\"error3\"), Cause.fail(\"error4\"))\n          )\n        ]\n      )\n      expectLinearize(\n        Cause.parallel(\n          Cause.parallel(Cause.fail(\"error1\"), Cause.fail(\"error2\")),\n          Cause.parallel(Cause.fail(\"error3\"), Cause.fail(\"error4\"))\n        ),\n        [\n          Cause.parallel(\n            Cause.parallel(Cause.fail(\"error1\"), Cause.fail(\"error2\")),\n            Cause.parallel(Cause.fail(\"error3\"), Cause.fail(\"error4\"))\n          )\n        ]\n      )\n    })\n\n    it(\"stripFailures\", () => {\n      const expectStripFailures = <E>(cause: Cause.Cause<E>, expected: Cause.Cause<never>) => {\n        deepStrictEqual(Cause.stripFailures(cause), expected)\n      }\n      expectStripFailures(empty, empty)\n      expectStripFailures(failure, empty)\n      expectStripFailures(defect, defect)\n      expectStripFailures(interruption, interruption)\n      expectStripFailures(interruption, interruption)\n      expectStripFailures(Cause.sequential(failure, defect), Cause.sequential(empty, defect))\n      expectStripFailures(Cause.parallel(failure, defect), Cause.parallel(empty, defect))\n    })\n\n    it(\"stripSomeDefects\", () => {\n      const cause1 = Cause.die({\n        _tag: \"NumberFormatException\",\n        msg: \"can't parse to int\"\n      })\n      const cause2 = Cause.die({\n        _tag: \"ArithmeticException\",\n        msg: \"division by zero\"\n      })\n      const stripNumberFormatException = Cause.stripSomeDefects((defect) =>\n        Predicate.isTagged(defect, \"NumberFormatException\")\n          ? Option.some(defect) :\n          Option.none()\n      )\n      assertSome(stripNumberFormatException(empty), empty)\n      assertSome(stripNumberFormatException(failure), failure)\n      assertSome(stripNumberFormatException(interruption), interruption)\n      assertNone(stripNumberFormatException(cause1))\n      assertNone(stripNumberFormatException(Cause.sequential(cause1, cause1)))\n      assertSome(stripNumberFormatException(Cause.sequential(cause1, cause2)), cause2)\n      assertSome(stripNumberFormatException(Cause.sequential(cause2, cause1)), cause2)\n      assertSome(\n        stripNumberFormatException(Cause.sequential(cause2, cause2)),\n        Cause.sequential(cause2, cause2)\n      )\n      assertNone(stripNumberFormatException(Cause.parallel(cause1, cause1)))\n      assertSome(stripNumberFormatException(Cause.parallel(cause1, cause2)), cause2)\n      assertSome(stripNumberFormatException(Cause.parallel(cause2, cause1)), cause2)\n      assertSome(\n        stripNumberFormatException(Cause.parallel(cause2, cause2)),\n        Cause.parallel(cause2, cause2)\n      )\n    })\n  })\n\n  describe(\"Mapping\", () => {\n    it(\"as\", () => {\n      const expectAs = <E>(cause: Cause.Cause<E>, expected: Cause.Cause<number>) => {\n        deepStrictEqual(Cause.as(cause, 2), expected)\n      }\n      expectAs(empty, empty)\n      expectAs(failure, Cause.fail(2))\n      expectAs(defect, defect)\n      expectAs(interruption, interruption)\n      expectAs(sequential, Cause.sequential(Cause.fail(2), defect))\n      expectAs(parallel, Cause.parallel(Cause.fail(2), defect))\n    })\n\n    it(\"map\", () => {\n      const expectMap = <E>(cause: Cause.Cause<E>, expected: Cause.Cause<number>) => {\n        deepStrictEqual(Cause.map(cause, () => 2), expected)\n      }\n      expectMap(empty, empty)\n      expectMap(failure, Cause.fail(2))\n      expectMap(defect, defect)\n      expectMap(interruption, interruption)\n      expectMap(sequential, Cause.sequential(Cause.fail(2), defect))\n      expectMap(parallel, Cause.parallel(Cause.fail(2), defect))\n    })\n  })\n\n  describe(\"Sequencing\", () => {\n    describe(\"flatMap\", () => {\n      it(\"obeys left identity\", () => {\n        fc.assert(fc.property(causes, (cause) => {\n          const left = cause.pipe(Cause.flatMap(Cause.fail))\n          const right = cause\n          assertTrue(Equal.equals(left, right))\n        }))\n      })\n\n      it(\"obeys right identity\", () => {\n        fc.assert(fc.property(errors, errorCauseFunctions, (error, f) => {\n          const left = Cause.fail(error).pipe(Cause.flatMap(f))\n          const right = f(error)\n          assertTrue(Equal.equals(left, right))\n        }))\n      })\n\n      it(\"is associative\", () => {\n        fc.assert(fc.property(causes, errorCauseFunctions, errorCauseFunctions, (cause, f, g) => {\n          const left = cause.pipe(Cause.flatMap(f), Cause.flatMap(g))\n          const right = cause.pipe(Cause.flatMap((error) => f(error).pipe(Cause.flatMap(g))))\n          assertTrue(Equal.equals(left, right))\n        }))\n      })\n    })\n\n    it(\"andThen returns the second cause if the first one is failing\", () => {\n      const err1 = Cause.fail(\"err1\")\n      const err2 = Cause.fail(\"err2\")\n      deepStrictEqual(err1.pipe(Cause.andThen(() => err2)), err2)\n      deepStrictEqual(err1.pipe(Cause.andThen(err2)), err2)\n      deepStrictEqual(Cause.andThen(err1, () => err2), err2)\n      deepStrictEqual(Cause.andThen(err1, err2), err2)\n    })\n\n    it(\"flatten\", () => {\n      const expectFlatten = <E>(cause: Cause.Cause<Cause.Cause<E>>, expected: Cause.Cause<E>) => {\n        deepStrictEqual(Cause.flatten(cause), expected)\n      }\n      expectFlatten(Cause.fail(empty), empty)\n      expectFlatten(Cause.fail(failure), failure)\n      expectFlatten(Cause.fail(defect), defect)\n      expectFlatten(Cause.fail(interruption), interruption)\n      expectFlatten(Cause.fail(sequential), sequential)\n      expectFlatten(Cause.fail(parallel), parallel)\n    })\n  })\n\n  describe(\"Elements\", () => {\n    it(\"contains\", () => {\n      const expectContains = <E, E2>(cause: Cause.Cause<E>, expected: Cause.Cause<E2>) => {\n        assertTrue(Cause.contains(cause, expected))\n      }\n\n      expectContains(empty, empty)\n      expectContains(failure, failure)\n      expectContains(defect, defect)\n      expectContains(interruption, interruption)\n      expectContains(sequential, sequential)\n      expectContains(parallel, parallel)\n      expectContains(sequential, failure)\n      expectContains(sequential, defect)\n      expectContains(parallel, failure)\n      expectContains(parallel, defect)\n    })\n\n    it(\"find\", () => {\n      const expectFind = <E>(cause: Cause.Cause<E>, expected: Option.Option<string>) => {\n        deepStrictEqual(\n          Cause.find(\n            cause,\n            (cause) =>\n              Cause.isFailType(cause) && Predicate.isString(cause.error) ? Option.some(cause.error) : Option.none()\n          ),\n          expected\n        )\n      }\n\n      expectFind(empty, Option.none())\n      expectFind(failure, Option.some(\"error\"))\n      expectFind(defect, Option.none())\n      expectFind(interruption, Option.none())\n      expectFind(sequential, Option.some(\"error\"))\n      expectFind(parallel, Option.some(\"error\"))\n    })\n  })\n\n  describe(\"Destructors\", () => {\n    it(\"squash\", () => {\n      const expectSquash = <E>(cause: Cause.Cause<E>, expected: unknown) => {\n        deepStrictEqual(Cause.squash(cause), expected)\n      }\n\n      expectSquash(empty, new Cause.InterruptedException(\"Interrupted by fibers: \"))\n      expectSquash(failure, \"error\")\n      expectSquash(defect, \"defect\")\n      expectSquash(interruption, new Cause.InterruptedException(\"Interrupted by fibers: #1\"))\n      expectSquash(sequential, \"error\")\n      expectSquash(parallel, \"error\")\n      expectSquash(Cause.sequential(empty, defect), \"defect\")\n      expectSquash(Cause.parallel(empty, defect), \"defect\")\n    })\n\n    it.todo(\"squashWith\", () => {\n    })\n  })\n\n  describe(\"Filtering\", () => {\n    it(\"filter\", () => {\n      const expectFilter = <E>(cause: Cause.Cause<E>, expected: Cause.Cause<E>) => {\n        deepStrictEqual(\n          Cause.filter(\n            cause,\n            (cause) => Cause.isFailType(cause) && Predicate.isString(cause.error) && cause.error === \"error\"\n          ),\n          expected\n        )\n      }\n\n      expectFilter(empty, empty)\n      expectFilter(failure, failure)\n      expectFilter(defect, defect)\n      expectFilter(interruption, interruption)\n      expectFilter(sequential, failure)\n      expectFilter(Cause.sequential(failure, failure), Cause.sequential(failure, failure))\n      expectFilter(Cause.sequential(defect, failure), failure)\n      expectFilter(Cause.sequential(defect, defect), empty)\n      expectFilter(parallel, failure)\n      expectFilter(Cause.parallel(failure, failure), Cause.parallel(failure, failure))\n      expectFilter(Cause.parallel(defect, failure), failure)\n      expectFilter(Cause.parallel(defect, defect), empty)\n    })\n  })\n\n  describe(\"Matching\", () => {\n    it(\"match\", () => {\n      const expectMatch = <E>(cause: Cause.Cause<E>, expected: string) => {\n        strictEqual(\n          Cause.match(cause, {\n            onEmpty: \"Empty\",\n            onFail: () => \"Fail\",\n            onDie: () => \"Die\",\n            onInterrupt: () => \"Interrupt\",\n            onSequential: () => \"Sequential\",\n            onParallel: () => \"Parallel\"\n          }),\n          expected\n        )\n      }\n      expectMatch(empty, \"Empty\")\n      expectMatch(failure, \"Fail\")\n      expectMatch(defect, \"Die\")\n      expectMatch(interruption, \"Interrupt\")\n      expectMatch(sequential, \"Sequential\")\n      expectMatch(parallel, \"Parallel\")\n    })\n  })\n\n  describe(\"Reducing\", () => {\n    it.todo(\"reduce\", () => {\n    })\n\n    it.todo(\"reduceWithContext\", () => {\n    })\n  })\n\n  describe(\"Formatting\", () => {\n    it(\"prettyErrors\", () => {\n      deepStrictEqual(Cause.prettyErrors(empty), [])\n      deepStrictEqual(Cause.prettyErrors(failure), [internal.makePrettyError(\"error\")])\n      deepStrictEqual(Cause.prettyErrors(defect), [internal.makePrettyError(\"defect\")])\n      deepStrictEqual(Cause.prettyErrors(interruption), [])\n      deepStrictEqual(Cause.prettyErrors(sequential), [\n        internal.makePrettyError(\"error\"),\n        internal.makePrettyError(\"defect\")\n      ])\n      deepStrictEqual(Cause.prettyErrors(parallel), [\n        internal.makePrettyError(\"error\"),\n        internal.makePrettyError(\"defect\")\n      ])\n    })\n\n    describe(\"pretty\", () => {\n      const simplifyStackTrace = (s: string): Array<string> => {\n        return Arr.filterMap(s.split(\"\\n\"), (s) => {\n          const t = s.trimStart()\n          if (t === \"}\") {\n            return Option.none()\n          }\n          if (t.startsWith(\"at [\")) {\n            return Option.some(t.substring(0, t.indexOf(\"] \") + 1))\n          }\n          if (t.startsWith(\"at \")) {\n            return Option.none()\n          }\n          return Option.some(t)\n        })\n      }\n\n      describe(\"renderErrorCause: false\", () => {\n        const expectPretty = <E>(cause: Cause.Cause<E>, expected: string | undefined) => {\n          deepStrictEqual(Cause.pretty(cause), expected)\n          deepStrictEqual(Cause.pretty(cause, { renderErrorCause: false }), expected)\n        }\n\n        it(\"handles array-based errors without throwing\", () => {\n          expectPretty(Cause.fail([{ toString: \"\" }]), `Error: [{\"toString\":\"\"}]`)\n        })\n\n        it(\"Empty\", () => {\n          expectPretty(empty, \"All fibers interrupted without errors.\")\n        })\n\n        it(\"Fail\", () => {\n          class Error1 {\n            readonly _tag = \"WithTag\"\n          }\n          expectPretty(Cause.fail(new Error1()), `Error: {\"_tag\":\"WithTag\"}`)\n          class Error2 {\n            readonly _tag = \"WithMessage\"\n            readonly message = \"my message\"\n          }\n          expectPretty(Cause.fail(new Error2()), `Error: {\"_tag\":\"WithMessage\",\"message\":\"my message\"}`)\n          class Error3 {\n            readonly _tag = \"WithName\"\n            readonly name = \"my name\"\n          }\n          expectPretty(Cause.fail(new Error3()), `Error: {\"_tag\":\"WithName\",\"name\":\"my name\"}`)\n          class Error4 {\n            readonly _tag = \"WithName\"\n            readonly name = \"my name\"\n            readonly message = \"my message\"\n          }\n          expectPretty(Cause.fail(new Error4()), `Error: {\"_tag\":\"WithName\",\"name\":\"my name\",\"message\":\"my message\"}`)\n          class Error5 {\n            readonly _tag = \"WithToString\"\n            toString() {\n              return \"my string\"\n            }\n          }\n          expectPretty(Cause.fail(new Error5()), `Error: my string`)\n\n          const err1 = new Error(\"message\", { cause: \"my cause\" })\n          expectPretty(Cause.fail(err1), err1.stack)\n        })\n\n        it(\"Interrupt\", () => {\n          strictEqual(Cause.pretty(Cause.interrupt(FiberId.none)), \"All fibers interrupted without errors.\")\n          strictEqual(Cause.pretty(Cause.interrupt(FiberId.runtime(1, 0))), \"All fibers interrupted without errors.\")\n          strictEqual(\n            Cause.pretty(Cause.interrupt(FiberId.composite(FiberId.none, FiberId.runtime(1, 0)))),\n            \"All fibers interrupted without errors.\"\n          )\n        })\n\n        describe(\"Die\", () => {\n          it(\"with span\", () => {\n            const exit: any = Effect.die(new Error(\"my message\")).pipe(\n              Effect.withSpan(\"[myspan]\"),\n              Effect.exit,\n              Effect.runSync\n            )\n            const cause = exit.cause\n            const pretty = Cause.pretty(cause)\n            deepStrictEqual(simplifyStackTrace(pretty), [`Error: my message`, \"at [myspan]\"])\n          })\n        })\n      })\n\n      describe(\"renderErrorCause: true\", () => {\n        describe(\"Fail\", () => {\n          it(\"no cause\", () => {\n            const pretty = Cause.pretty(Cause.fail(new Error(\"my message\")), { renderErrorCause: true })\n            deepStrictEqual(simplifyStackTrace(pretty), [\"Error: my message\"])\n          })\n\n          it(\"string cause\", () => {\n            const pretty = Cause.pretty(Cause.fail(new Error(\"my message\", { cause: \"my cause\" })), {\n              renderErrorCause: true\n            })\n            deepStrictEqual(simplifyStackTrace(pretty), [\"Error: my message\", \"[cause]: Error: my cause\"])\n          })\n\n          it(\"error cause\", () => {\n            const pretty = Cause.pretty(Cause.fail(new Error(\"my message\", { cause: new Error(\"my cause\") })), {\n              renderErrorCause: true\n            })\n            deepStrictEqual(simplifyStackTrace(pretty), [\"Error: my message\", \"[cause]: Error: my cause\"])\n          })\n\n          it(\"error cause with nested cause\", () => {\n            const pretty = Cause.pretty(\n              Cause.fail(new Error(\"my message\", { cause: new Error(\"my cause\", { cause: \"nested cause\" }) })),\n              {\n                renderErrorCause: true\n              }\n            )\n            deepStrictEqual(simplifyStackTrace(pretty), [\n              \"Error: my message\",\n              \"[cause]: Error: my cause\",\n              \"[cause]: Error: nested cause\"\n            ])\n          })\n        })\n\n        describe(\"Die\", () => {\n          it(\"with span\", () => {\n            const exit: any = Effect.die(new Error(\"my message\", { cause: \"my cause\" })).pipe(\n              Effect.withSpan(\"[myspan]\"),\n              Effect.exit,\n              Effect.runSync\n            )\n            const cause = exit.cause\n            const pretty = Cause.pretty(cause, { renderErrorCause: true })\n            deepStrictEqual(simplifyStackTrace(pretty), [\n              `Error: my message`,\n              \"at [myspan]\",\n              \"[cause]: Error: my cause\"\n            ])\n          })\n        })\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/constructors.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Channel from \"effect/Channel\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\n\ndescribe(\"Channel\", () => {\n  it.effect(\"succeed\", () =>\n    Effect.gen(function*() {\n      const [chunk, value] = yield* Channel.runCollect(Channel.succeed(1))\n      assertTrue(Chunk.isEmpty(chunk))\n      strictEqual(value, 1)\n    }))\n\n  it.effect(\"fail\", () =>\n    Effect.gen(function*() {\n      const result = yield* Effect.exit(Channel.runCollect(Channel.fail(\"uh oh\")))\n      deepStrictEqual(result, Exit.fail(\"uh oh\"))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/environment.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Channel from \"effect/Channel\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport { pipe } from \"effect/Function\"\nimport * as Hash from \"effect/Hash\"\n\nconst NumberServiceSymbolKey = \"effect/test/NumberService\"\n\nconst NumberServiceTypeId = Symbol.for(NumberServiceSymbolKey)\n\ntype NumberServiceTypeId = typeof NumberServiceTypeId\n\nexport interface NumberService extends Equal.Equal {\n  readonly [NumberServiceTypeId]: NumberServiceTypeId\n  readonly n: number\n}\n\nexport const NumberService = Context.GenericTag<NumberService>(\"NumberService\")\n\nexport class NumberServiceImpl implements NumberService {\n  readonly [NumberServiceTypeId]: NumberServiceTypeId = NumberServiceTypeId\n\n  constructor(readonly n: number) {}\n\n  [Hash.symbol](): number {\n    return pipe(\n      Hash.hash(NumberServiceSymbolKey),\n      Hash.combine(Hash.hash(this.n))\n    )\n  }\n\n  [Equal.symbol](u: unknown): boolean {\n    return isNumberService(u) && u.n === this.n\n  }\n}\n\nexport const isNumberService = (u: unknown): u is NumberService => {\n  return typeof u === \"object\" && u != null && NumberServiceTypeId in u\n}\n\ndescribe(\"Channel\", () => {\n  it.effect(\"provide - simple\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        NumberService,\n        Channel.provideService(NumberService, new NumberServiceImpl(100)),\n        Channel.run\n      )\n      deepStrictEqual(result, new NumberServiceImpl(100))\n    }))\n\n  it.effect(\"provide -> zip -> provide\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        NumberService,\n        Channel.provideService(NumberService, new NumberServiceImpl(100)),\n        Channel.zip(\n          pipe(\n            NumberService,\n            Channel.provideService(NumberService, new NumberServiceImpl(200))\n          )\n        ),\n        Channel.run\n      )\n      deepStrictEqual(result, [new NumberServiceImpl(100), new NumberServiceImpl(200)])\n    }))\n\n  it.effect(\"concatMap(provide).provide\", () =>\n    Effect.gen(function*() {\n      const [chunk, value] = yield* pipe(\n        Channel.fromEffect(NumberService),\n        Channel.emitCollect,\n        Channel.mapOut((tuple) => tuple[1]),\n        Channel.concatMap((n) =>\n          pipe(\n            NumberService,\n            Effect.map((m) => [n, m] as const),\n            Channel.provideService(NumberService, new NumberServiceImpl(200)),\n            Channel.flatMap(Channel.write)\n          )\n        ),\n        Channel.provideService(NumberService, new NumberServiceImpl(100)),\n        Channel.runCollect\n      )\n      deepStrictEqual(Array.from(chunk), [[new NumberServiceImpl(100), new NumberServiceImpl(200)] as const])\n      strictEqual(value, undefined)\n    }))\n\n  it.effect(\"provide is modular\", () =>\n    Effect.gen(function*() {\n      const channel1 = Channel.fromEffect(NumberService)\n      const channel2 = pipe(\n        NumberService,\n        Effect.provide(pipe(Context.empty(), Context.add(NumberService, new NumberServiceImpl(2)))),\n        Channel.fromEffect\n      )\n      const channel3 = Channel.fromEffect(NumberService)\n      const [[result1, result2], result3] = yield* pipe(\n        channel1,\n        Channel.zip(channel2),\n        Channel.zip(channel3),\n        Channel.runDrain,\n        Effect.provideService(NumberService, new NumberServiceImpl(4))\n      )\n      deepStrictEqual(result1, new NumberServiceImpl(4))\n      deepStrictEqual(result2, new NumberServiceImpl(2))\n      deepStrictEqual(result3, new NumberServiceImpl(4))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/error-handling.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Channel from \"effect/Channel\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\n\ndescribe(\"Channel\", () => {\n  it.effect(\"catchAll - structure confusion\", () =>\n    Effect.gen(function*() {\n      const channel = pipe(\n        Channel.write(8),\n        Channel.catchAll(() =>\n          pipe(\n            Channel.write(0),\n            Channel.concatMap(() => Channel.fail(\"error1\"))\n          )\n        ),\n        Channel.concatMap(() => Channel.fail(\"error2\"))\n      )\n      const result = yield* (Effect.exit(Channel.runCollect(channel)))\n      deepStrictEqual(result, Exit.fail(\"error2\"))\n    }))\n\n  it.effect(\"error cause is propagated on channel interruption\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<void>())\n      const finished = yield* (Deferred.make<void>())\n      const ref = yield* (Ref.make<Exit.Exit<void>>(Exit.void))\n      const effect = pipe(\n        Deferred.succeed(deferred, void 0),\n        Effect.zipRight(Effect.never)\n      )\n      yield* pipe(\n        Channel.fromEffect(effect),\n        Channel.runDrain,\n        Effect.onExit((exit) => Ref.set(ref, exit as Exit.Exit<void>)),\n        Effect.ensuring(Deferred.succeed(finished, void 0)),\n        Effect.race(Deferred.await(deferred)),\n        Effect.either\n      )\n      yield* (Deferred.await(finished)) // Note: interruption in race is now done in the background\n      const result = yield* (Ref.get(ref))\n      assertTrue(Exit.isInterrupted(result))\n    }))\n\n  it.effect(\"scoped failures\", () =>\n    Effect.gen(function*() {\n      const channel = Channel.scoped(Effect.fail(\"error\"))\n      const result = yield* pipe(Channel.runCollect(channel), Effect.exit)\n      deepStrictEqual(result, Exit.fail(\"error\"))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/finalization.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Channel from \"effect/Channel\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\n\ninterface First {\n  readonly _tag: \"First\"\n  readonly n: number\n}\n\nconst First = (n: number): First => ({ _tag: \"First\", n })\n\ninterface Second {\n  readonly _tag: \"Second\"\n  readonly first: First\n}\n\nconst Second = (first: First): Second => ({ _tag: \"Second\", first })\n\ndescribe(\"Channel\", () => {\n  it.effect(\"ensuring - prompt closure between continuations\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<ReadonlyArray<string>>([]))\n      const event = (label: string) => Ref.update(ref, (array) => [...array, label])\n      const channel = pipe(\n        Channel.fromEffect(event(\"Acquire1\")),\n        Channel.ensuring(event(\"Release11\")),\n        Channel.ensuring(event(\"Release12\")),\n        Channel.flatMap(() =>\n          pipe(\n            Channel.fromEffect(event(\"Acquire2\")),\n            Channel.ensuring(event(\"Release2\"))\n          )\n        )\n      )\n      const result = yield* pipe(Channel.runDrain(channel), Effect.zipRight(Ref.get(ref)))\n      deepStrictEqual(result, [\n        \"Acquire1\",\n        \"Release11\",\n        \"Release12\",\n        \"Acquire2\",\n        \"Release2\"\n      ])\n    }))\n\n  it.effect(\"ensuring - last finalizers are deferred to the scope\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<ReadonlyArray<string>>([]))\n      function event(label: string) {\n        return Ref.update(ref, (array) => [...array, label])\n      }\n      const channel = pipe(\n        Channel.fromEffect(event(\"Acquire1\")),\n        Channel.ensuring(event(\"Release11\")),\n        Channel.ensuring(event(\"Release12\")),\n        Channel.zipRight(\n          pipe(\n            Channel.fromEffect(event(\"Acquire2\")),\n            Channel.ensuring(event(\"Release2\"))\n          )\n        ),\n        Channel.ensuring(event(\"ReleaseOuter\"))\n      )\n      const [eventsInScope, eventsOutsideScope] = yield* pipe(\n        Channel.toPull(channel),\n        Effect.flatMap((pull) => pipe(Effect.exit(pull), Effect.zipRight(Ref.get(ref)))),\n        Effect.scoped,\n        Effect.zip(Ref.get(ref))\n      )\n      deepStrictEqual(eventsInScope, [\n        \"Acquire1\",\n        \"Release11\",\n        \"Release12\",\n        \"Acquire2\"\n      ])\n      deepStrictEqual(eventsOutsideScope, [\n        \"Acquire1\",\n        \"Release11\",\n        \"Release12\",\n        \"Acquire2\",\n        \"Release2\",\n        \"ReleaseOuter\"\n      ])\n    }))\n\n  it.effect(\"ensuring - mixture of concatMap and ensuring\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<ReadonlyArray<string>>([]))\n      const event = (label: string) => Ref.update(ref, (array) => [...array, label])\n      const channel = pipe(\n        Channel.writeAll(1, 2, 3),\n        Channel.ensuring(event(\"Inner\")),\n        Channel.concatMap((i) =>\n          pipe(\n            Channel.write(First(i)),\n            Channel.ensuring(event(\"First write\"))\n          )\n        ),\n        Channel.ensuring(event(\"First concatMap\")),\n        Channel.concatMap((first) =>\n          pipe(\n            Channel.write(Second(first)),\n            Channel.ensuring(event(\"Second write\"))\n          )\n        ),\n        Channel.ensuring(event(\"Second concatMap\"))\n      )\n      const [[elements], events] = yield* pipe(\n        Channel.runCollect(channel),\n        Effect.zip(Ref.get(ref))\n      )\n      deepStrictEqual(events, [\n        \"Second write\",\n        \"First write\",\n        \"Second write\",\n        \"First write\",\n        \"Second write\",\n        \"First write\",\n        \"Inner\",\n        \"First concatMap\",\n        \"Second concatMap\"\n      ])\n      deepStrictEqual(Array.from(elements), [\n        Second(First(1)),\n        Second(First(2)),\n        Second(First(3))\n      ])\n    }))\n\n  it.effect(\"ensuring - finalizer ordering 2\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<ReadonlyArray<string>>([]))\n      const event = (label: string) => Ref.update(ref, (array) => [...array, label])\n      const channel = pipe(\n        Channel.writeAll(1, 2),\n        Channel.mapOutEffect((n) => pipe(event(`pulled ${n}`), Effect.as(n))),\n        Channel.concatMap((n) =>\n          pipe(\n            Channel.write(n),\n            Channel.ensuring(event(`close ${n}`))\n          )\n        )\n      )\n      yield* (Channel.runDrain(channel))\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [\n        \"pulled 1\",\n        \"close 1\",\n        \"pulled 2\",\n        \"close 2\"\n      ])\n    }))\n\n  it.effect(\"ensuring - finalizer failure is propagated\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Channel.void,\n        Channel.ensuring(Effect.dieMessage(\"die\")),\n        Channel.ensuring(Effect.void),\n        Channel.runDrain,\n        Effect.exit\n      )\n      assertTrue(Exit.isFailure(result))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/foreign.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { Channel, Context, Effect, Either, Exit, Option, pipe, Random } from \"effect\"\nimport { unify } from \"effect/Unify\"\n\ndescribe(\"Channel.Foreign\", () => {\n  it.effect(\"Tag\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<number>(\"number\")\n      const result = yield* pipe(tag, Channel.run, Effect.provideService(tag, 10))\n      strictEqual(result, 10)\n    }))\n\n  it.effect(\"Unify\", () =>\n    Effect.gen(function*() {\n      const unifiedEffect = unify((yield* (Random.nextInt)) > 1 ? Effect.succeed(0) : Effect.fail(1))\n      const unifiedExit = unify((yield* (Random.nextInt)) > 1 ? Exit.succeed(0) : Exit.fail(1))\n      const unifiedEither = unify((yield* (Random.nextInt)) > 1 ? Either.right(0) : Either.left(1))\n      const unifiedOption = unify((yield* (Random.nextInt)) > 1 ? Option.some(0) : Option.none())\n      strictEqual(yield* (Channel.run(unifiedEffect)), 0)\n      strictEqual(yield* (Channel.run(unifiedExit)), 0)\n      strictEqual(yield* (Channel.run(unifiedEither)), 0)\n      strictEqual(yield* (Channel.run(unifiedOption)), 0)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/interruption.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport * as Channel from \"effect/Channel\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\n\ndescribe(\"Channel\", () => {\n  it.effect(\"interruptWhen - interrupts the current element\", () =>\n    Effect.gen(function*() {\n      const interrupted = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const halt = yield* (Deferred.make<void>())\n      const started = yield* (Deferred.make<void>())\n      const channel = pipe(\n        Deferred.succeed(started, void 0),\n        Effect.zipRight(Deferred.await(latch)),\n        Effect.onInterrupt(() => Ref.set(interrupted, true)),\n        Channel.fromEffect,\n        Channel.interruptWhen(Deferred.await(halt))\n      )\n      const fiber = yield* (Effect.fork(Channel.runDrain(channel)))\n      yield* pipe(\n        Deferred.await(started),\n        Effect.zipRight(Deferred.succeed(halt, void 0))\n      )\n      yield* (Fiber.await(fiber))\n      const result = yield* (Ref.get(interrupted))\n      assertTrue(result)\n    }))\n\n  it.effect(\"interruptWhen - propagates errors\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<never, string>())\n      const channel = pipe(\n        Channel.fromEffect(Effect.never),\n        Channel.interruptWhen(Deferred.await(deferred))\n      )\n      yield* (Deferred.fail(deferred, \"fail\"))\n      const result = yield* (Effect.either(Channel.runDrain(channel)))\n      assertLeft(result, \"fail\")\n    }))\n\n  it.effect(\"interruptWhenDeferred - interrupts the current element\", () =>\n    Effect.gen(function*() {\n      const interrupted = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const halt = yield* (Deferred.make<void>())\n      const started = yield* (Deferred.make<void>())\n      const channel = pipe(\n        Deferred.succeed(started, void 0),\n        Effect.zipRight(Deferred.await(latch)),\n        Effect.onInterrupt(() => Ref.set(interrupted, true)),\n        Channel.fromEffect,\n        Channel.interruptWhenDeferred(halt)\n      )\n      const fiber = yield* (Effect.fork(Channel.runDrain(channel)))\n      yield* pipe(\n        Deferred.await(started),\n        Effect.zipRight(Deferred.succeed(halt, void 0))\n      )\n      yield* (Fiber.await(fiber))\n      const result = yield* (Ref.get(interrupted))\n      assertTrue(result)\n    }))\n\n  it.effect(\"interruptWhenDeferred - propagates errors\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<never, string>())\n      const channel = pipe(\n        Channel.fromEffect(Effect.never),\n        Channel.interruptWhenDeferred(deferred)\n      )\n      yield* (Deferred.fail(deferred, \"fail\"))\n      const result = yield* (Effect.either(Channel.runDrain(channel)))\n      assertLeft(result, \"fail\")\n    }))\n\n  it.effect(\"runScoped - in uninterruptible region\", () =>\n    Effect.gen(function*() {\n      const result = yield* Effect.uninterruptible(Channel.run(Channel.void))\n      strictEqual(result, undefined)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/mapping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Channel from \"effect/Channel\"\nimport * as ChildExecutorDecision from \"effect/ChildExecutorDecision\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { constVoid, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as UpstreamPullRequest from \"effect/UpstreamPullRequest\"\nimport * as UpstreamPullStrategy from \"effect/UpstreamPullStrategy\"\n\ninterface First {\n  readonly _tag: \"First\"\n  readonly n: number\n}\n\nconst First = (n: number): First => ({ _tag: \"First\", n })\n\ninterface Second {\n  readonly _tag: \"Second\"\n  readonly first: First\n}\n\nconst Second = (first: First): Second => ({ _tag: \"Second\", first })\n\ndescribe(\"Channel\", () => {\n  it.effect(\"map\", () =>\n    Effect.gen(function*() {\n      const [chunk, value] = yield* pipe(\n        Channel.succeed(1),\n        Channel.map((n) => n + 1),\n        Channel.runCollect\n      )\n      assertTrue(Chunk.isEmpty(chunk))\n      strictEqual(value, 2)\n    }))\n\n  it.effect(\"mapError - structure confusion\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Channel.fail(\"error\"),\n        Channel.mapError(() => 1),\n        Channel.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(1))\n    }))\n\n  it.effect(\"mapOut - simple\", () =>\n    Effect.gen(function*() {\n      const [chunk, value] = yield* pipe(\n        Channel.writeAll(1, 2, 3),\n        Channel.mapOut((n) => n + 1),\n        Channel.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(chunk), [2, 3, 4])\n      strictEqual(value, undefined)\n    }))\n\n  it.effect(\"mapOut - mixed with flatMap\", () =>\n    Effect.gen(function*() {\n      const [chunk, value] = yield* pipe(\n        Channel.write(1),\n        Channel.mapOut((n) => `${n}`),\n        Channel.flatMap(() => Channel.write(\"x\")),\n        Channel.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(chunk), [\"1\", \"x\"])\n      strictEqual(value, undefined)\n    }))\n\n  it.effect(\"concatMap - plain\", () =>\n    Effect.gen(function*() {\n      const [result] = yield* pipe(\n        Channel.writeAll(1, 2, 3),\n        Channel.concatMap((i) => Channel.writeAll(i, i)),\n        Channel.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1, 1, 2, 2, 3, 3])\n    }))\n\n  it.effect(\"concatMap - complex\", () =>\n    Effect.gen(function*() {\n      const [result] = yield* pipe(\n        Channel.writeAll(1, 2),\n        Channel.concatMap((i) => Channel.writeAll(i, i)),\n        Channel.mapOut(First),\n        Channel.concatMap((i) => Channel.writeAll(i, i)),\n        Channel.mapOut(Second),\n        Channel.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [\n        Second(First(1)),\n        Second(First(1)),\n        Second(First(1)),\n        Second(First(1)),\n        Second(First(2)),\n        Second(First(2)),\n        Second(First(2)),\n        Second(First(2))\n      ])\n    }))\n\n  it.effect(\"concatMap - read from inner channel\", () =>\n    Effect.gen(function*() {\n      const source = Channel.writeAll(1, 2, 3, 4)\n      const reader = pipe(\n        Channel.read<number>(),\n        Channel.flatMap(Channel.write)\n      )\n      const readers = pipe(\n        Channel.writeAll(void 0, void 0),\n        Channel.concatMap(() => pipe(reader, Channel.flatMap(() => reader)))\n      )\n      const [result] = yield* pipe(\n        source,\n        Channel.pipeTo(readers),\n        Channel.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"concatMap - downstream failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Channel.write(0),\n        Channel.concatMap(() => Channel.fail(\"error\")),\n        Channel.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(\"error\"))\n    }))\n\n  it.effect(\"concatMap - upstream acquireReleaseOut + downstream failure\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<ReadonlyArray<string>>([]))\n      const event = (label: string) => Ref.update(ref, (array) => [...array, label])\n      const effect = pipe(\n        Channel.acquireReleaseOut(event(\"Acquired\"), () => event(\"Released\")),\n        Channel.concatMap(() => Channel.fail(\"error\")),\n        Channel.runDrain,\n        Effect.exit\n      )\n      const [exit, events] = yield* pipe(effect, Effect.zip(Ref.get(ref)))\n      deepStrictEqual(exit, Exit.fail(\"error\"))\n      deepStrictEqual(events, [\"Acquired\", \"Released\"])\n    }))\n\n  it.effect(\"concatMap - multiple concatMaps with failure in first\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Channel.write(void 0),\n        Channel.concatMap(() => Channel.write(Channel.fail(\"error\"))),\n        Channel.concatMap((e) => e),\n        Channel.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(\"error\"))\n    }))\n\n  it.effect(\"concatMap - with failure then flatMap\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Channel.write(void 0),\n        Channel.concatMap(() => Channel.fail(\"error\")),\n        Channel.flatMap(() => Channel.write(void 0)),\n        Channel.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(\"error\"))\n    }))\n\n  it.effect(\"concatMap - multiple concatMaps with failure in first and catchAll in second\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Channel.write(void 0),\n        Channel.concatMap(() => Channel.write(Channel.fail(\"error\"))),\n        Channel.concatMap(Channel.catchAllCause(() => Channel.fail(\"error2\"))),\n        Channel.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(\"error2\"))\n    }))\n\n  it.effect(\"concatMap - done value combination\", () =>\n    Effect.gen(function*() {\n      const [chunk, [array1, array2]] = yield* pipe(\n        Channel.writeAll(1, 2, 3),\n        Channel.as([\"Outer-0\"]),\n        Channel.concatMapWith(\n          (i) => pipe(Channel.write(i), Channel.as([`Inner-${i}`])),\n          (a: Array<string>, b) => [...a, ...b],\n          (a, b) => [a, b] as const\n        ),\n        Channel.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(chunk), [1, 2, 3])\n      deepStrictEqual(array1, [\"Inner-1\", \"Inner-2\", \"Inner-3\"])\n      deepStrictEqual(array2, [\"Outer-0\"])\n    }))\n\n  it.effect(\"concatMap - custom 1\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Channel.writeAll(1, 2, 3, 4),\n        Channel.concatMapWithCustom(\n          (x) =>\n            Channel.writeAll(\n              Option.some([x, 1]) as Option.Option<readonly [number, number]>,\n              Option.none() as Option.Option<readonly [number, number]>,\n              Option.some([x, 2]) as Option.Option<readonly [number, number]>,\n              Option.none() as Option.Option<readonly [number, number]>,\n              Option.some([x, 3]) as Option.Option<readonly [number, number]>,\n              Option.none() as Option.Option<readonly [number, number]>,\n              Option.some([x, 4]) as Option.Option<readonly [number, number]>\n            ),\n          constVoid,\n          constVoid,\n          UpstreamPullRequest.match({\n            onPulled: () => UpstreamPullStrategy.PullAfterNext(Option.none()),\n            onNoUpstream: () => UpstreamPullStrategy.PullAfterAllEnqueued(Option.none())\n          }),\n          Option.match({\n            onNone: () => ChildExecutorDecision.Yield(),\n            onSome: () => ChildExecutorDecision.Continue()\n          })\n        ),\n        Channel.runCollect,\n        Effect.map(([chunk]) => pipe(Chunk.toReadonlyArray(chunk), Array.getSomes))\n      )\n      deepStrictEqual(result, [\n        [1, 1] as const,\n        [2, 1] as const,\n        [3, 1] as const,\n        [4, 1] as const,\n        [1, 2] as const,\n        [2, 2] as const,\n        [3, 2] as const,\n        [4, 2] as const,\n        [1, 3] as const,\n        [2, 3] as const,\n        [3, 3] as const,\n        [4, 3] as const,\n        [1, 4] as const,\n        [2, 4] as const,\n        [3, 4] as const,\n        [4, 4] as const\n      ])\n    }))\n\n  it.effect(\"concatMap - custom 2\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Channel.writeAll(1, 2, 3, 4),\n        Channel.concatMapWithCustom(\n          (x) =>\n            Channel.writeAll(\n              Option.some([x, 1]) as Option.Option<readonly [number, number]>,\n              Option.none() as Option.Option<readonly [number, number]>,\n              Option.some([x, 2]) as Option.Option<readonly [number, number]>,\n              Option.none() as Option.Option<readonly [number, number]>,\n              Option.some([x, 3]) as Option.Option<readonly [number, number]>,\n              Option.none() as Option.Option<readonly [number, number]>,\n              Option.some([x, 4]) as Option.Option<readonly [number, number]>\n            ),\n          constVoid,\n          constVoid,\n          () => UpstreamPullStrategy.PullAfterAllEnqueued(Option.none()),\n          Option.match({\n            onNone: () => ChildExecutorDecision.Yield(),\n            onSome: () => ChildExecutorDecision.Continue()\n          })\n        ),\n        Channel.runCollect,\n        Effect.map(([chunk]) => pipe(Chunk.toReadonlyArray(chunk), Array.getSomes))\n      )\n      deepStrictEqual(result, [\n        [1, 1] as const,\n        [2, 1] as const,\n        [1, 2] as const,\n        [3, 1] as const,\n        [2, 2] as const,\n        [1, 3] as const,\n        [4, 1] as const,\n        [3, 2] as const,\n        [2, 3] as const,\n        [1, 4] as const,\n        [4, 2] as const,\n        [3, 3] as const,\n        [2, 4] as const,\n        [4, 3] as const,\n        [3, 4] as const,\n        [4, 4] as const\n      ])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/merging.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Channel from \"effect/Channel\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { constTrue, pipe } from \"effect/Function\"\nimport * as MergeDecision from \"effect/MergeDecision\"\nimport * as Ref from \"effect/Ref\"\n\ndescribe(\"Channel\", () => {\n  it.effect(\"mergeWith - simple merge\", () =>\n    Effect.gen(function*() {\n      const [chunk, value] = yield* pipe(\n        Channel.writeAll(1, 2, 3),\n        Channel.mergeWith({\n          other: Channel.writeAll(4, 5, 6),\n          // TODO: remove\n          onSelfDone: (leftDone) => MergeDecision.AwaitConst(Effect.suspend(() => leftDone)),\n          onOtherDone: (rightDone) => MergeDecision.AwaitConst(Effect.suspend(() => rightDone))\n        }),\n        Channel.runCollect\n      )\n      deepStrictEqual(Array.from(chunk), [1, 2, 3, 4, 5, 6])\n      strictEqual(value, undefined)\n    }))\n\n  it.effect(\"mergeWith - merge with different types\", () =>\n    Effect.gen(function*() {\n      const left = pipe(\n        Channel.write(1),\n        Channel.zipRight(\n          pipe(\n            Effect.try(() => \"whatever\"),\n            Effect.catchAllCause((cause) =>\n              Cause.isRuntimeException(cause) ?\n                Effect.failCause(cause) :\n                Effect.die(cause)\n            ),\n            Channel.fromEffect\n          )\n        )\n      )\n      const right = pipe(\n        Channel.write(2),\n        Channel.zipRight(\n          pipe(\n            Effect.try(constTrue),\n            Effect.catchAllCause((cause) =>\n              Cause.isIllegalArgumentException(cause) ?\n                Effect.failCause(cause) :\n                Effect.die(cause)\n            ),\n            Channel.fromEffect\n          )\n        )\n      )\n      const [chunk, value] = yield* pipe(\n        left,\n        Channel.mergeWith({\n          other: right,\n          // TODO: remove\n          onSelfDone: (leftDone) =>\n            MergeDecision.Await((rightDone) => Effect.suspend(() => Exit.zip(leftDone, rightDone))),\n          onOtherDone: (rightDone) =>\n            MergeDecision.Await((leftDone) => Effect.suspend(() => Exit.zip(leftDone, rightDone)))\n        }),\n        Channel.runCollect\n      )\n      deepStrictEqual(Array.from(chunk), [1, 2])\n      deepStrictEqual(value, [\"whatever\", true])\n    }))\n\n  it.effect(\"mergeWith - handles polymorphic failures\", () =>\n    Effect.gen(function*() {\n      const left = pipe(\n        Channel.write(1),\n        Channel.zipRight(pipe(Channel.fail(\"boom\"), Channel.as(true)))\n      )\n      const right = pipe(\n        Channel.write(2),\n        Channel.zipRight(pipe(Channel.fail(true), Channel.as(true)))\n      )\n      const result = yield* pipe(\n        left,\n        Channel.mergeWith({\n          other: right,\n          onSelfDone: (leftDone) =>\n            MergeDecision.Await((rightDone) =>\n              pipe(\n                // TODO: remove\n                Effect.suspend(() => leftDone),\n                Effect.flip,\n                // TODO: remove\n                Effect.zip(Effect.flip(Effect.suspend(() => rightDone))),\n                Effect.flip\n              )\n            ),\n          onOtherDone: (rightDone) =>\n            MergeDecision.Await((leftDone) =>\n              pipe(\n                // TODO: remove\n                Effect.suspend(() => leftDone),\n                Effect.flip,\n                // TODO: remove\n                Effect.zip(Effect.flip(Effect.suspend(() => rightDone))),\n                Effect.flip\n              )\n            )\n        }),\n        Channel.runDrain,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail<[string, boolean]>([\"boom\", true]))\n    }))\n\n  it.effect(\"mergeWith - interrupts losing side\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<void>())\n      const interrupted = yield* (Ref.make(false))\n      const left = Channel.zipRight(\n        Channel.write(1),\n        pipe(\n          Deferred.succeed(latch, void 0),\n          Effect.zipRight(Effect.never),\n          Effect.onInterrupt(() => Ref.set(interrupted, true)),\n          Channel.fromEffect\n        )\n      )\n      const right = Channel.zipRight(\n        Channel.write(2),\n        Channel.fromEffect(Deferred.await(latch))\n      )\n      const merged = Channel.mergeWith(left, {\n        other: right,\n        // TODO: remove\n        onSelfDone: (leftDone) => MergeDecision.Done(Effect.suspend(() => leftDone)),\n        onOtherDone: (_rightDone) =>\n          MergeDecision.Done(pipe(\n            Ref.get(interrupted),\n            Effect.flatMap((isInterrupted) => isInterrupted ? Effect.void : Effect.fail(void 0))\n          ))\n      })\n      const result = yield* (Effect.exit(Channel.runDrain(merged)))\n      deepStrictEqual(result, Exit.succeed(void 0))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/reading.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Channel from \"effect/Channel\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport { pipe } from \"effect/Function\"\nimport * as Hash from \"effect/Hash\"\nimport * as HashSet from \"effect/HashSet\"\nimport * as MergeDecision from \"effect/MergeDecision\"\nimport * as Option from \"effect/Option\"\nimport * as Random from \"effect/Random\"\nimport * as Ref from \"effect/Ref\"\n\nexport const mapper = <A, B>(\n  f: (a: A) => B\n): Channel.Channel<B, A, never, unknown, void, unknown> => {\n  return Channel.readWith({\n    onInput: (a: A) =>\n      Channel.flatMap(\n        Channel.write(f(a)),\n        () => mapper(f)\n      ),\n    onFailure: () => Channel.void,\n    onDone: () => Channel.void\n  })\n}\n\nexport const refWriter = <A>(\n  ref: Ref.Ref<ReadonlyArray<A>>\n): Channel.Channel<never, A, never, unknown, void, unknown> => {\n  return Channel.readWith({\n    onInput: (a: A) =>\n      Channel.flatMap(\n        Channel.fromEffect(Effect.asVoid(Ref.update(ref, Array.prepend(a)))),\n        () => refWriter(ref)\n      ),\n    onFailure: () => Channel.void,\n    onDone: () => Channel.void\n  })\n}\n\nexport const refReader = <A>(\n  ref: Ref.Ref<Array<A>>\n): Channel.Channel<A, unknown, never, unknown, void, unknown> => {\n  return pipe(\n    Channel.fromEffect(\n      Ref.modify(ref, (array) => {\n        if (Array.isEmptyReadonlyArray(array)) {\n          return [Option.none(), Array.empty<A>()] as const\n        }\n        return [Option.some(array[0]!), array.slice(1)] as const\n      })\n    ),\n    Channel.flatMap(Option.match({\n      onNone: () => Channel.void,\n      onSome: (i) => Channel.flatMap(Channel.write(i), () => refReader(ref))\n    }))\n  )\n}\n\ndescribe(\"Channel\", () => {\n  it.effect(\"simple reads\", () =>\n    Effect.gen(function*() {\n      class Whatever implements Equal.Equal {\n        constructor(readonly i: number) {}\n        [Hash.symbol](): number {\n          return Hash.hash(this.i)\n        }\n        [Equal.symbol](u: unknown): boolean {\n          return u instanceof Whatever && u.i === this.i\n        }\n      }\n      const left = Channel.writeAll(1, 2, 3)\n      const right = pipe(\n        Channel.read<number>(),\n        Channel.catchAll(() => Channel.succeed(4)),\n        Channel.flatMap((i) => Channel.write(new Whatever(i)))\n      )\n      const channel = pipe(\n        left,\n        Channel.pipeTo(\n          pipe(\n            right,\n            Channel.zipRight(right),\n            Channel.zipRight(right),\n            Channel.zipRight(right)\n          )\n        )\n      )\n      const result = yield* (Channel.runCollect(channel))\n      const [chunk, value] = result\n      deepStrictEqual(Chunk.toReadonlyArray(chunk), [\n        new Whatever(1),\n        new Whatever(2),\n        new Whatever(3),\n        new Whatever(4)\n      ])\n      strictEqual(value, undefined)\n    }))\n\n  it.effect(\"read pipelining\", () =>\n    Effect.gen(function*() {\n      const innerChannel = pipe(\n        Channel.fromEffect(Ref.make<ReadonlyArray<number>>([])),\n        Channel.flatMap((ref) => {\n          const inner = (): Channel.Channel<number, number, never, unknown, void, unknown> =>\n            Channel.readWith({\n              onInput: (input: number) =>\n                pipe(\n                  Channel.fromEffect(Ref.update(ref, (array) => [...array, input])),\n                  Channel.zipRight(Channel.write(input)),\n                  Channel.flatMap(inner)\n                ),\n              onFailure: () => Channel.void,\n              onDone: () => Channel.void\n            })\n          return pipe(\n            inner(),\n            Channel.zipRight(Channel.fromEffect(Ref.get(ref)))\n          )\n        })\n      )\n      const f = (n: number) => n\n      const g = (n: number) => [n, n]\n      const channel = pipe(\n        Channel.writeAll(1, 2),\n        Channel.pipeTo(mapper(f)),\n        Channel.pipeTo(pipe(mapper(g), Channel.concatMap((ns) => Channel.writeAll(...ns)), Channel.asVoid)),\n        Channel.pipeTo(innerChannel)\n      )\n      const [chunk, list] = yield* (Channel.runCollect(channel))\n      deepStrictEqual(Chunk.toReadonlyArray(chunk), [1, 1, 2, 2])\n      deepStrictEqual(list, [1, 1, 2, 2])\n    }))\n\n  it.effect(\"read pipelining 2\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<ReadonlyArray<number>>([]))\n      const intProducer: Channel.Channel<number, unknown, never, unknown, void, unknown> = Channel.writeAll(\n        1,\n        2,\n        3,\n        4,\n        5\n      )\n      const readIntsN = (\n        n: number\n      ): Channel.Channel<number, number, never, unknown, string, unknown> =>\n        n > 0\n          ? Channel.readWith({\n            onInput: (i: number) => pipe(Channel.write(i), Channel.flatMap(() => readIntsN(n - 1))),\n            onFailure: () => Channel.succeed(\"EOF\"),\n            onDone: () => Channel.succeed(\"EOF\")\n          })\n          : Channel.succeed(\"end\")\n\n      const sum = (\n        label: string,\n        n: number\n      ): Channel.Channel<never, number, unknown, unknown, void, unknown> =>\n        Channel.readWith({\n          onInput: (input: number) => sum(label, n + input),\n          onFailure: () => Channel.fromEffect(Ref.update(ref, (array) => [...array, n])),\n          onDone: () => Channel.fromEffect(Ref.update(ref, (array) => [...array, n]))\n        })\n\n      const channel = pipe(\n        intProducer,\n        Channel.pipeTo(\n          pipe(\n            readIntsN(2),\n            Channel.pipeTo(sum(\"left\", 0)),\n            Channel.zipRight(readIntsN(2)),\n            Channel.pipeTo(sum(\"right\", 0))\n          )\n        )\n      )\n      const result = yield* pipe(Channel.run(channel), Effect.zipRight(Ref.get(ref)))\n      deepStrictEqual(result, [3, 7])\n    }))\n\n  it.effect(\"reading with resources\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<ReadonlyArray<string>>([]))\n      const event = (label: string) => Ref.update(ref, (array) => [...array, label])\n      const left = pipe(\n        Channel.acquireReleaseOut(\n          event(\"Acquire outer\"),\n          () => event(\"Release outer\")\n        ),\n        Channel.concatMap(\n          () =>\n            pipe(\n              Channel.writeAll(1, 2, 3),\n              Channel.concatMap((i) =>\n                Channel.acquireReleaseOut(\n                  pipe(event(`Acquire ${i}`), Effect.as(i)),\n                  () => event(`Release ${i}`)\n                )\n              )\n            )\n        )\n      )\n      const read = pipe(\n        Channel.read<number>(),\n        Channel.mapEffect((i) => event(`Read ${i}`)),\n        Channel.asVoid\n      )\n      const right = pipe(\n        read,\n        Channel.zipRight(read),\n        Channel.catchAll(() => Channel.void)\n      )\n      const channel = pipe(left, Channel.pipeTo(right))\n      const result = yield* pipe(Channel.runDrain(channel), Effect.zipRight(Ref.get(ref)))\n      deepStrictEqual(result, [\n        \"Acquire outer\",\n        \"Acquire 1\",\n        \"Read 1\",\n        \"Release 1\",\n        \"Acquire 2\",\n        \"Read 2\",\n        \"Release 2\",\n        \"Release outer\"\n      ])\n    }))\n\n  it.effect(\"simple concurrent reads\", () =>\n    Effect.gen(function*() {\n      const capacity = 128\n      const elements = yield* (Effect.replicateEffect(Random.nextInt, capacity))\n      const source = yield* (Ref.make(Array.fromIterable(elements)))\n      const destination = yield* (Ref.make<ReadonlyArray<number>>([]))\n      const twoWriters = pipe(\n        refWriter(destination),\n        Channel.mergeWith({\n          other: refWriter(destination),\n          onSelfDone: () => MergeDecision.AwaitConst(Effect.void),\n          onOtherDone: () => MergeDecision.AwaitConst(Effect.void)\n        })\n      )\n      const [missing, surplus] = yield* pipe(\n        refReader(source),\n        Channel.pipeTo(twoWriters),\n        Channel.mapEffect(() => Ref.get(destination)),\n        Channel.run,\n        Effect.map((result) => {\n          let missing = HashSet.fromIterable(elements)\n          let surplus = HashSet.fromIterable(result)\n          for (const value of result) {\n            missing = pipe(missing, HashSet.remove(value))\n          }\n          for (const value of elements) {\n            surplus = pipe(surplus, HashSet.remove(value))\n          }\n          return [missing, surplus] as const\n        })\n      )\n\n      strictEqual(HashSet.size(missing), 0)\n      strictEqual(HashSet.size(surplus), 0)\n    }))\n\n  it.effect(\"nested concurrent reads\", () =>\n    Effect.gen(function*() {\n      const capacity = 128\n      const f = (n: number) => n + 1\n      const elements = yield* (Effect.replicateEffect(Random.nextInt, capacity))\n      const source = yield* (Ref.make(Array.fromIterable(elements)))\n      const destination = yield* (Ref.make<ReadonlyArray<number>>([]))\n      const twoWriters = pipe(\n        mapper(f),\n        Channel.pipeTo(refWriter(destination)),\n        Channel.mergeWith({\n          other: pipe(mapper(f), Channel.pipeTo(refWriter(destination))),\n          onSelfDone: () => MergeDecision.AwaitConst(Effect.void),\n          onOtherDone: () => MergeDecision.AwaitConst(Effect.void)\n        })\n      )\n      const [missing, surplus] = yield* pipe(\n        refReader(source),\n        Channel.pipeTo(twoWriters),\n        Channel.mapEffect(() => Ref.get(destination)),\n        Channel.run,\n        Effect.map((result) => {\n          const expected = HashSet.fromIterable(elements.map(f))\n          let missing = HashSet.fromIterable(expected)\n          let surplus = HashSet.fromIterable(result)\n          for (const value of result) {\n            missing = pipe(missing, HashSet.remove(value))\n          }\n          for (const value of expected) {\n            surplus = pipe(surplus, HashSet.remove(value))\n          }\n          return [missing, surplus] as const\n        })\n      )\n      strictEqual(HashSet.size(missing), 0)\n      strictEqual(HashSet.size(surplus), 0)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/scoping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Channel from \"effect/Channel\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberId from \"effect/FiberId\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\n\ndescribe(\"Channel\", () => {\n  it(\"acquireUseReleaseOut - acquire is executed uninterruptibly\", async () => {\n    const latch = Deferred.unsafeMake<void>(FiberId.none)\n    const program = Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const acquire = Effect.zipRight(Ref.update(ref, (n) => n + 1), Effect.yieldNow())\n      const release = Ref.update(ref, (n) => n - 1)\n      yield* pipe(\n        Channel.acquireReleaseOut(acquire, () => release),\n        Channel.as(Channel.fromEffect(Deferred.await(latch))),\n        Channel.runDrain,\n        Effect.fork,\n        Effect.flatMap((fiber) => pipe(Effect.yieldNow(), Effect.zipRight(Fiber.interrupt(fiber)))),\n        Effect.repeatN(1_000)\n      )\n      return yield* (Ref.get(ref))\n    })\n    const result = await Effect.runPromise(program)\n    await Effect.runPromise(Deferred.succeed(latch, void 0))\n    strictEqual(result, 0)\n  }, 35_000)\n\n  it(\"scoped closes the scope\", async () => {\n    const latch = Deferred.unsafeMake<void>(FiberId.none)\n    const program = Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const acquire = Effect.zipRight(Ref.update(ref, (n) => n + 1), Effect.yieldNow())\n      const release = () => Ref.update(ref, (n) => n - 1)\n      const scoped = Effect.acquireRelease(acquire, release)\n      yield* pipe(\n        Channel.unwrapScoped(pipe(scoped, Effect.as(Channel.fromEffect(Deferred.await(latch))))),\n        Channel.runDrain,\n        Effect.fork,\n        Effect.flatMap((fiber) => pipe(Effect.yieldNow(), Effect.zipRight(Fiber.interrupt(fiber)))),\n        Effect.repeatN(1_000)\n      )\n      return yield* (Ref.get(ref))\n    })\n    const result = await Effect.runPromise(program)\n    await Effect.runPromise(Deferred.succeed(latch, void 0))\n    strictEqual(result, 0)\n  }, 35_000)\n\n  it.effect(\"finalizer failure is propagated\", () =>\n    Effect.gen(function*() {\n      const exit = yield* pipe(\n        Channel.void,\n        Channel.ensuring(Effect.die(\"ok\")),\n        Channel.ensuring(Effect.void),\n        Channel.runDrain,\n        Effect.sandbox,\n        Effect.either\n      )\n\n      assertLeft(exit, Cause.die(\"ok\"))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/sequencing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Channel from \"effect/Channel\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\n\ndescribe(\"Channel\", () => {\n  it.effect(\"flatMap - simple\", () =>\n    Effect.gen(function*() {\n      const channel = pipe(\n        Channel.succeed(1),\n        Channel.flatMap((x) =>\n          pipe(\n            Channel.succeed(x * 2),\n            Channel.flatMap((y) =>\n              pipe(\n                Channel.succeed(x + y),\n                Channel.map((z) => x + y + z)\n              )\n            )\n          )\n        )\n      )\n      const [chunk, value] = yield* (Channel.runCollect(channel))\n      assertTrue(Chunk.isEmpty(chunk))\n      strictEqual(value, 6)\n    }))\n\n  it.effect(\"flatMap - structure confusion\", () =>\n    Effect.gen(function*() {\n      const channel = pipe(\n        Channel.write(Chunk.make(1, 2)),\n        Channel.concatMap(Channel.writeAll),\n        Channel.zipRight(Channel.fail(\"hello\"))\n      )\n      const result = yield* (Effect.exit(Channel.runDrain(channel)))\n      deepStrictEqual(result, Exit.fail(\"hello\"))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Channel/stack-safety.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Channel from \"effect/Channel\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\n\ndescribe(\"Channel\", () => {\n  it.effect(\"mapOut is stack safe\", () =>\n    Effect.gen(function*() {\n      const N = 10_000\n      const [chunk, value] = yield* pipe(\n        Chunk.range(1, N),\n        Chunk.reduce(\n          Channel.write<number>(1),\n          (channel, n) => pipe(channel, Channel.mapOut((i) => i + n))\n        ),\n        Channel.runCollect\n      )\n      const expected = pipe(\n        Chunk.range(1, N),\n        Chunk.reduce(1, (x, y) => x + y)\n      )\n      strictEqual(Chunk.unsafeHead(chunk), expected)\n      strictEqual(value, undefined)\n    }), 20_000)\n\n  it.effect(\"concatMap is stack safe\", () =>\n    Effect.gen(function*() {\n      const N = 10_000\n      const [chunk, value] = yield* pipe(\n        Chunk.range(1, N),\n        Chunk.reduce(\n          Channel.write<number>(1),\n          (channel, n) =>\n            pipe(\n              channel,\n              Channel.concatMap(() => Channel.write(n)),\n              Channel.asVoid\n            )\n        ),\n        Channel.runCollect\n      )\n      strictEqual(Chunk.unsafeHead(chunk), N)\n      strictEqual(value, undefined)\n    }), 20_000)\n\n  it.effect(\"flatMap is stack safe\", () =>\n    Effect.gen(function*() {\n      const N = 10_000\n      const [chunk, value] = yield* pipe(\n        Chunk.range(1, N),\n        Chunk.reduce(\n          Channel.write<number>(0),\n          (channel, n) => pipe(channel, Channel.flatMap(() => Channel.write(n)))\n        ),\n        Channel.runCollect\n      )\n      deepStrictEqual(Array.from(chunk), Array.from(Chunk.range(0, N)))\n      strictEqual(value, undefined)\n    }), 20_000)\n})\n"
  },
  {
    "path": "packages/effect/test/Chunk.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertEquals,\n  assertFalse,\n  assertNone,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  doesNotThrow,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport {\n  Array as Arr,\n  Chunk,\n  Either,\n  Equal,\n  FastCheck as fc,\n  identity,\n  Number as Num,\n  Option,\n  Order,\n  pipe,\n  type Predicate\n} from \"effect\"\n\nconst assertTuple = <A, B>(\n  actual: [Chunk.Chunk<A>, Chunk.Chunk<B>],\n  expected: [Chunk.Chunk<A>, Chunk.Chunk<B>]\n) => {\n  assertEquals(actual[0], expected[0])\n  assertEquals(actual[1], expected[1])\n}\n\ndescribe(\"Chunk\", () => {\n  it(\"Equal.equals\", () => {\n    assertTrue(Equal.equals(Chunk.make(0), Chunk.make(0)))\n    assertTrue(Equal.equals(Chunk.make(1, 2, 3), Chunk.make(1, 2, 3)))\n    assertFalse(Equal.equals(Chunk.make(1, 2, 3), Chunk.make(1, 2)))\n    assertFalse(Equal.equals(Chunk.make(1, 2), Chunk.make(1, 2, 3)))\n    assertFalse(Equal.equals(Chunk.make(1, 2, 3), Chunk.make(1, \"a\", 3)))\n    assertFalse(Equal.equals(Chunk.make(0), [0]))\n  })\n\n  it(\"toString\", () => {\n    strictEqual(\n      String(Chunk.make(0, 1, 2)),\n      `{\n  \"_id\": \"Chunk\",\n  \"values\": [\n    0,\n    1,\n    2\n  ]\n}`\n    )\n    strictEqual(\n      String(Chunk.make(Chunk.make(1, 2, 3))),\n      `{\n  \"_id\": \"Chunk\",\n  \"values\": [\n    {\n      \"_id\": \"Chunk\",\n      \"values\": [\n        1,\n        2,\n        3\n      ]\n    }\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    deepStrictEqual(Chunk.make(0, 1, 2).toJSON(), { _id: \"Chunk\", values: [0, 1, 2] })\n    deepStrictEqual(Chunk.make(Chunk.make(1, 2, 3)).toJSON(), {\n      _id: \"Chunk\",\n      values: [{ _id: \"Chunk\", values: [1, 2, 3] }]\n    })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window === \"undefined\") {\n      // eslint-disable-next-line @typescript-eslint/no-require-imports\n      const { inspect } = require(\"node:util\")\n      assertEquals(inspect(Chunk.make(0, 1, 2)), inspect({ _id: \"Chunk\", values: [0, 1, 2] }))\n    }\n  })\n\n  it(\"modifyOption\", () => {\n    assertNone(pipe(Chunk.empty(), Chunk.modifyOption(0, (n: number) => n * 2)))\n    assertSome(\n      pipe(Chunk.make(1, 2, 3), Chunk.modifyOption(0, (n: number) => n * 2)),\n      Chunk.make(2, 2, 3)\n    )\n  })\n\n  it(\"modify\", () => {\n    assertEquals(pipe(Chunk.empty(), Chunk.modify(0, (n: number) => n * 2)), Chunk.empty())\n    assertEquals(pipe(Chunk.make(1, 2, 3), Chunk.modify(0, (n: number) => n * 2)), Chunk.make(2, 2, 3))\n  })\n\n  it(\"replaceOption\", () => {\n    assertNone(pipe(Chunk.empty(), Chunk.replaceOption(0, 2)))\n    assertSome(pipe(Chunk.make(1, 2, 3), Chunk.replaceOption(0, 2)), Chunk.make(2, 2, 3))\n  })\n\n  it(\"replace\", () => {\n    assertEquals(pipe(Chunk.empty(), Chunk.replace(0, 2)), Chunk.empty())\n    assertEquals(pipe(Chunk.make(1, 2, 3), Chunk.replace(0, 2)), Chunk.make(2, 2, 3))\n  })\n\n  it(\"remove\", () => {\n    assertEquals(pipe(Chunk.empty(), Chunk.remove(0)), Chunk.empty())\n    assertEquals(pipe(Chunk.make(1, 2, 3), Chunk.remove(0)), Chunk.make(2, 3))\n  })\n\n  it(\"removeOption\", () => {\n    assertNone(pipe(Chunk.empty(), Chunk.removeOption(0)))\n    assertSome(pipe(Chunk.make(1, 2, 3), Chunk.removeOption(0)), Chunk.make(2, 3))\n  })\n\n  it(\"chunksOf\", () => {\n    assertEquals(pipe(Chunk.empty(), Chunk.chunksOf(2)), Chunk.empty())\n    assertEquals(\n      pipe(Chunk.make(1, 2, 3, 4, 5), Chunk.chunksOf(2)),\n      Chunk.make(Chunk.make(1, 2), Chunk.make(3, 4), Chunk.make(5))\n    )\n    assertEquals(\n      pipe(Chunk.make(1, 2, 3, 4, 5, 6), Chunk.chunksOf(2)),\n      Chunk.make(Chunk.make(1, 2), Chunk.make(3, 4), Chunk.make(5, 6))\n    )\n    assertEquals(\n      pipe(Chunk.make(1, 2, 3, 4, 5), Chunk.chunksOf(1)),\n      Chunk.make(Chunk.make(1), Chunk.make(2), Chunk.make(3), Chunk.make(4), Chunk.make(5))\n    )\n    assertEquals(pipe(Chunk.make(1, 2, 3, 4, 5), Chunk.chunksOf(5)), Chunk.make(Chunk.make(1, 2, 3, 4, 5)))\n    // out of bounds\n    assertEquals(\n      pipe(Chunk.make(1, 2, 3, 4, 5), Chunk.chunksOf(0)),\n      Chunk.make(Chunk.make(1), Chunk.make(2), Chunk.make(3), Chunk.make(4), Chunk.make(5))\n    )\n    assertEquals(\n      pipe(Chunk.make(1, 2, 3, 4, 5), Chunk.chunksOf(-1)),\n      Chunk.make(Chunk.make(1), Chunk.make(2), Chunk.make(3), Chunk.make(4), Chunk.make(5))\n    )\n    assertEquals(pipe(Chunk.make(1, 2, 3, 4, 5), Chunk.chunksOf(10)), Chunk.make(Chunk.make(1, 2, 3, 4, 5)))\n  })\n\n  it(\".pipe() method\", () => {\n    assertEquals(Chunk.empty().pipe(Chunk.append(1)), Chunk.make(1))\n  })\n\n  describe(\"toArray\", () => {\n    it(\"should return an empty array for an empty chunk\", () => {\n      deepStrictEqual(Chunk.toArray(Chunk.empty()), [])\n    })\n\n    it(\"should return an array with the elements of the chunk\", () => {\n      deepStrictEqual(Chunk.toArray(Chunk.make(1, 2, 3)), [1, 2, 3])\n    })\n\n    it(\"should not affect the original chunk when the array is mutated\", () => {\n      const chunk = Chunk.make(1, 2, 3)\n      const arr = Chunk.toArray(chunk)\n      // mutate the array\n      arr[1] = 4\n      // the chunk should not be affected\n      deepStrictEqual(Chunk.toArray(chunk), [1, 2, 3])\n    })\n  })\n\n  describe(\"toReadonlyArray\", () => {\n    describe(\"Given an empty Chunk\", () => {\n      const chunk = Chunk.empty()\n      it(\"should give back an empty readonly array\", () => {\n        deepStrictEqual(Chunk.toReadonlyArray(chunk), [])\n      })\n    })\n\n    describe(\"Given a large Chunk\", () => {\n      const len = 100_000\n      let chunk = Chunk.empty<number>()\n      for (let i = 0; i < len; i++) chunk = Chunk.appendAll(Chunk.of(i), chunk)\n\n      it(\"gives back a readonly array\", () => {\n        doesNotThrow(() => Chunk.toReadonlyArray(chunk))\n        deepStrictEqual(Chunk.toReadonlyArray(chunk), Arr.reverse(Arr.range(0, len - 1)))\n      })\n    })\n\n    describe(`Given an imbalanced left and right chunk`, () => {\n      const len = 1_000\n      let rchunk = Chunk.empty<number>()\n      let lchunk = Chunk.empty<number>()\n      for (let i = 0; i < len; i++) {\n        rchunk = Chunk.appendAll(Chunk.of(i), rchunk)\n        lchunk = Chunk.appendAll(lchunk, Chunk.of(i))\n      }\n      it(\"should have depth of +/- 3\", () => {\n        assertTrue(rchunk.depth >= lchunk.depth - 3)\n        assertTrue(rchunk.depth <= lchunk.depth + 3)\n      })\n    })\n  })\n\n  describe(\"isChunk\", () => {\n    describe(\"Given a chunk\", () => {\n      const chunk = Chunk.make(0, 1)\n      it(\"should be true\", () => {\n        assertTrue(Chunk.isChunk(chunk))\n      })\n    })\n    describe(\"Given an object\", () => {\n      const object = {}\n      it(\"should be false\", () => {\n        assertFalse(Chunk.isChunk(object))\n      })\n    })\n  })\n\n  describe(\"fromIterable\", () => {\n    describe(\"Given an iterable\", () => {\n      const myIterable = {\n        [Symbol.iterator]() {\n          let i = 0\n\n          return {\n            next() {\n              i++\n              return { value: i, done: i > 5 }\n            }\n          }\n        }\n      }\n\n      it(\"should process it\", () => {\n        assertEquals(Chunk.fromIterable(myIterable), Chunk.unsafeFromArray([1, 2, 3, 4, 5]))\n      })\n    })\n\n    it(\"should return the same reference if the input is a Chunk\", () => {\n      const expected = Chunk.make(1, 2, 3)\n      const actual = Chunk.fromIterable(expected)\n      assertTrue(actual === expected)\n    })\n  })\n\n  describe(\"get\", () => {\n    describe(\"Given a Chunk and an index within the bounds\", () => {\n      const chunk = Chunk.unsafeFromArray([1, 2, 3])\n      const index = 0\n\n      it(\"should a Some with the value\", () => {\n        deepStrictEqual(pipe(chunk, Chunk.get(index)), Option.some(1))\n      })\n    })\n\n    describe(\"Given a Chunk and an index out of bounds\", () => {\n      const chunk = Chunk.unsafeFromArray([1, 2, 3])\n\n      it(\"should return a None\", () => {\n        assertNone(pipe(chunk, Chunk.get(4)))\n      })\n    })\n  })\n\n  describe(\"unsafeGet\", () => {\n    describe(\"Given an empty Chunk and an index\", () => {\n      const chunk = Chunk.empty()\n      const index = 4\n\n      it(\"should throw\", () => {\n        throws(() => pipe(chunk, Chunk.unsafeGet(index)))\n      })\n    })\n\n    describe(\"Given an appended Chunk and an index out of bounds\", () => {\n      const chunk = pipe(Chunk.empty(), Chunk.append(1))\n      const index = 4\n\n      it(\"should throw\", () => {\n        throws(() => pipe(chunk, Chunk.unsafeGet(index)))\n      })\n    })\n\n    describe(\"Given an appended Chunk and an index in bounds\", () => {\n      it(\"should return the value\", () => {\n        const chunk = pipe(Chunk.make(0, 1, 2), Chunk.append(3))\n        strictEqual(Chunk.unsafeGet(1)(chunk), 1)\n      })\n    })\n\n    describe(\"Given a prepended Chunk and an index out of bounds\", () => {\n      it(\"should throw\", () => {\n        fc.assert(fc.property(fc.array(fc.anything()), (array) => {\n          let chunk: Chunk.Chunk<unknown> = Chunk.empty()\n          array.forEach((e) => {\n            chunk = pipe(chunk, Chunk.prepend(e))\n          })\n          throws(() => pipe(chunk, Chunk.unsafeGet(array.length)))\n        }))\n      })\n    })\n\n    describe(\"Given a prepended Chunk and an index in bounds\", () => {\n      it(\"should return the value\", () => {\n        const chunk = pipe(Chunk.make(0, 1, 2), Chunk.prepend(3))\n        strictEqual(Chunk.unsafeGet(1)(chunk), 0)\n      })\n    })\n\n    describe(\"Given a singleton Chunk and an index out of bounds\", () => {\n      const chunk = Chunk.make(1)\n      const index = 4\n\n      it(\"should throw\", () => {\n        throws(() => pipe(chunk, Chunk.unsafeGet(index)))\n      })\n    })\n\n    describe(\"Given an array Chunk and an index out of bounds\", () => {\n      const chunk = Chunk.unsafeFromArray([1, 2])\n      const index = 4\n\n      it(\"should throw\", () => {\n        throws(() => pipe(chunk, Chunk.unsafeGet(index)))\n      })\n    })\n\n    describe(\"Given a concat Chunk and an index out of bounds\", () => {\n      it(\"should throw\", () => {\n        fc.assert(fc.property(fc.array(fc.anything()), fc.array(fc.anything()), (arr1, arr2) => {\n          const chunk: Chunk.Chunk<unknown> = Chunk.appendAll(Chunk.fromIterable(arr2))(Chunk.unsafeFromArray(arr1))\n          throws(() => pipe(chunk, Chunk.unsafeGet(arr1.length + arr2.length)))\n        }))\n      })\n    })\n\n    describe(\"Given an appended Chunk and an index in bounds\", () => {\n      const chunk = pipe(Chunk.empty(), Chunk.append(1), Chunk.append(2))\n      const index = 1\n\n      it(\"should return the value\", () => {\n        strictEqual(pipe(chunk, Chunk.unsafeGet(index)), 2)\n      })\n    })\n\n    describe(\"Given a prepended Chunk and an index in bounds\", () => {\n      const chunk = pipe(Chunk.empty(), Chunk.prepend(2), Chunk.prepend(1))\n      const index = 1\n\n      it(\"should return the value\", () => {\n        strictEqual(pipe(chunk, Chunk.unsafeGet(index)), 2)\n      })\n    })\n\n    describe(\"Given a singleton Chunk and an index in bounds\", () => {\n      const chunk = Chunk.make(1)\n      const index = 0\n\n      it(\"should return the value\", () => {\n        strictEqual(pipe(chunk, Chunk.unsafeGet(index)), 1)\n      })\n    })\n\n    describe(\"Given an array Chunk and an index in bounds\", () => {\n      const chunk = pipe(Chunk.unsafeFromArray([1, 2, 3]))\n      const index = 1\n\n      it(\"should return the value\", () => {\n        strictEqual(pipe(chunk, Chunk.unsafeGet(index)), 2)\n      })\n    })\n\n    describe(\"Given a concat Chunk and an index in bounds\", () => {\n      it(\"should return the value\", () => {\n        fc.assert(fc.property(fc.array(fc.anything()), fc.array(fc.anything()), (a, b) => {\n          const c = [...a, ...b]\n          const d = Chunk.appendAll(Chunk.unsafeFromArray(b))(Chunk.unsafeFromArray(a))\n          for (let i = 0; i < c.length; i++) {\n            deepStrictEqual(Chunk.unsafeGet(i)(d), c[i])\n          }\n        }))\n      })\n    })\n  })\n\n  it(\"append\", () => {\n    fc.assert(\n      fc.property(\n        fc.array(fc.integer()),\n        fc.array(fc.integer(), { minLength: 0, maxLength: 120, size: \"xlarge\" }),\n        (a, b) => {\n          let chunk = Chunk.unsafeFromArray(a)\n          b.forEach((e) => {\n            chunk = Chunk.append(e)(chunk)\n          })\n          deepStrictEqual(Chunk.toReadonlyArray(chunk), [...a, ...b])\n        }\n      )\n    )\n  })\n\n  it(\"prependAll\", () => {\n    assertEquals(pipe(Chunk.empty(), Chunk.prependAll(Chunk.make(1))), Chunk.make(1))\n    assertEquals(pipe(Chunk.make(1), Chunk.prependAll(Chunk.empty())), Chunk.make(1))\n\n    assertEquals(pipe(Chunk.empty(), Chunk.prependAll(Chunk.make(1, 2))), Chunk.make(1, 2))\n    assertEquals(pipe(Chunk.make(1, 2), Chunk.prependAll(Chunk.empty())), Chunk.make(1, 2))\n\n    assertEquals(pipe(Chunk.make(2, 3), Chunk.prependAll(Chunk.make(1))), Chunk.make(1, 2, 3))\n    assertEquals(pipe(Chunk.make(3), Chunk.prependAll(Chunk.make(1, 2))), Chunk.make(1, 2, 3))\n  })\n\n  it(\"prepend\", () => {\n    fc.assert(\n      fc.property(\n        fc.array(fc.integer()),\n        fc.array(fc.integer(), { minLength: 0, maxLength: 120, size: \"xlarge\" }),\n        (a, b) => {\n          let chunk = Chunk.unsafeFromArray(a)\n          for (let i = b.length - 1; i >= 0; i--) {\n            chunk = Chunk.prepend(b[i])(chunk)\n          }\n          deepStrictEqual(Chunk.toReadonlyArray(chunk), [...b, ...a])\n        }\n      )\n    )\n  })\n\n  describe(\"take\", () => {\n    describe(\"Given a Chunk with more elements than the amount taken\", () => {\n      it(\"should return the subset\", () => {\n        assertEquals(pipe(Chunk.unsafeFromArray([1, 2, 3]), Chunk.take(2)), Chunk.unsafeFromArray([1, 2]))\n      })\n    })\n\n    describe(\"Given a Chunk with fewer elements than the amount taken\", () => {\n      const chunk = Chunk.unsafeFromArray([1, 2, 3])\n      const amount = 5\n\n      it(\"should return the available subset\", () => {\n        assertEquals(pipe(chunk, Chunk.take(amount)), Chunk.unsafeFromArray([1, 2, 3]))\n      })\n    })\n\n    describe(\"Given a slice Chunk with and an amount\", () => {\n      const chunk = pipe(Chunk.unsafeFromArray([1, 2, 3, 4, 5]), Chunk.take(4))\n      const amount = 3\n\n      it(\"should return the available subset\", () => {\n        assertEquals(pipe(chunk, Chunk.take(amount)), Chunk.unsafeFromArray([1, 2, 3]))\n      })\n    })\n\n    describe(\"Given a singleton Chunk with and an amount > 1\", () => {\n      const chunk = Chunk.make(1)\n      const amount = 2\n\n      it(\"should return the available subset\", () => {\n        assertEquals(pipe(chunk, Chunk.take(amount)), Chunk.unsafeFromArray([1]))\n      })\n    })\n\n    describe(\"Given a concatenated Chunk and an amount > 1\", () => {\n      const chunk = pipe(Chunk.of(1), Chunk.appendAll(Chunk.make(2, 3, 4)))\n      const amount = 2\n\n      it(\"should return the available subset\", () => {\n        deepStrictEqual(pipe(chunk, Chunk.take(amount), Chunk.toReadonlyArray), [1, 2])\n      })\n    })\n\n    describe(\"Given a concatenated Chunk and an amount <= self.left\", () => {\n      it(\"should return the available subset\", () => {\n        const chunk = Chunk.appendAll(Chunk.make(2, 3, 4), Chunk.of(1))\n        deepStrictEqual(pipe(chunk, Chunk.take(2), Chunk.toReadonlyArray), [2, 3])\n        deepStrictEqual(pipe(chunk, Chunk.take(3), Chunk.toReadonlyArray), [2, 3, 4])\n      })\n    })\n  })\n\n  describe(\"make\", () => {\n    it(\"should return a NonEmptyChunk\", () => {\n      strictEqual(Chunk.make(0, 1).length, 2)\n    })\n  })\n\n  describe(\"singleton\", () => {\n    it(\"should return a NonEmptyChunk\", () => {\n      strictEqual(Chunk.of(1).length, 1)\n    })\n    it(\"should return a ISingleton\", () => {\n      strictEqual(Chunk.of(1).backing._tag, \"ISingleton\")\n    })\n  })\n\n  describe(\"drop\", () => {\n    it(\"should return self on 0\", () => {\n      const self = Chunk.make(0, 1)\n      strictEqual(Chunk.drop(0)(self), self)\n    })\n    it(\"should drop twice\", () => {\n      const self = Chunk.make(0, 1, 2, 3)\n      deepStrictEqual(Chunk.toReadonlyArray(Chunk.drop(1)(Chunk.drop(1)(self))), [2, 3])\n    })\n    it(\"should handle concatenated chunks\", () => {\n      const self = pipe(Chunk.make(1), Chunk.appendAll(Chunk.make(2, 3, 4)))\n      deepStrictEqual(pipe(self, Chunk.drop(2), Chunk.toReadonlyArray), [3, 4])\n    })\n  })\n\n  describe(\"dropRight\", () => {\n    describe(\"Given a Chunk and an amount to drop below the length\", () => {\n      const chunk = Chunk.unsafeFromArray([1, 2, 3])\n      const toDrop = 1\n\n      it(\"should remove the given amount of items\", () => {\n        assertEquals(pipe(chunk, Chunk.dropRight(toDrop)), Chunk.unsafeFromArray([1, 2]))\n      })\n    })\n\n    describe(\"Given a Chunk and an amount to drop above the length\", () => {\n      const chunk = Chunk.unsafeFromArray([1, 2])\n      const toDrop = 3\n\n      it(\"should return an empty chunk\", () => {\n        assertEquals(pipe(chunk, Chunk.dropRight(toDrop)), Chunk.unsafeFromArray([]))\n      })\n    })\n  })\n\n  describe(\"dropWhile\", () => {\n    describe(\"Given a Chunk and a criteria that applies to part of the chunk\", () => {\n      const chunk = Chunk.unsafeFromArray([1, 2, 3])\n      const criteria = (n: number) => n < 3\n\n      it(\"should return the subset that doesn't pass the criteria\", () => {\n        assertEquals(pipe(chunk, Chunk.dropWhile(criteria)), Chunk.unsafeFromArray([3]))\n      })\n    })\n\n    describe(\"Given a Chunk and a criteria that applies to the whole chunk\", () => {\n      const chunk = Chunk.unsafeFromArray([1, 2, 3])\n      const criteria = (n: number) => n < 4\n\n      it(\"should return an empty chunk\", () => {\n        assertEquals(pipe(chunk, Chunk.dropWhile(criteria)), Chunk.unsafeFromArray([]))\n      })\n    })\n  })\n\n  describe(\"concat\", () => {\n    describe(\"Given 2 chunks of the same length\", () => {\n      const chunk1 = Chunk.unsafeFromArray([0, 1])\n      const chunk2 = Chunk.unsafeFromArray([2, 3])\n\n      it(\"should concatenate them following order\", () => {\n        assertEquals(pipe(chunk1, Chunk.appendAll(chunk2)), Chunk.unsafeFromArray([0, 1, 2, 3]))\n      })\n    })\n\n    describe(\"Given 2 chunks where the first one has more elements than the second one\", () => {\n      const chunk1 = Chunk.unsafeFromArray([1, 2])\n      const chunk2 = Chunk.unsafeFromArray([3])\n\n      it(\"should concatenate them following order\", () => {\n        assertEquals(pipe(chunk1, Chunk.appendAll(chunk2)), Chunk.unsafeFromArray([1, 2, 3]))\n      })\n    })\n\n    describe(\"Given 2 chunks where the first one has fewer elements than the second one\", () => {\n      const chunk1 = Chunk.unsafeFromArray([1])\n      const chunk2 = Chunk.unsafeFromArray([2, 3, 4])\n\n      it(\"should concatenate them following order\", () => {\n        assertEquals(pipe(chunk1, Chunk.appendAll(chunk2)), Chunk.unsafeFromArray([1, 2, 3, 4]))\n      })\n    })\n\n    describe(\"Given 2 chunks where the first one is appended\", () => {\n      const chunk1 = pipe(\n        Chunk.empty(),\n        Chunk.append(1)\n      )\n      const chunk2 = Chunk.unsafeFromArray([2, 3, 4])\n\n      it(\"should concatenate them following order\", () => {\n        assertEquals(pipe(chunk1, Chunk.appendAll(chunk2)), Chunk.unsafeFromArray([1, 2, 3, 4]))\n      })\n    })\n\n    describe(\"Given 2 chunks where the second one is appended\", () => {\n      const chunk1 = Chunk.unsafeFromArray([1])\n      const chunk2 = pipe(\n        Chunk.empty(),\n        Chunk.prepend(2)\n      )\n\n      it(\"should concatenate them following order\", () => {\n        assertEquals(pipe(chunk1, Chunk.appendAll(chunk2)), Chunk.unsafeFromArray([1, 2]))\n      })\n    })\n\n    describe(\"Given 2 chunks where the first one is empty\", () => {\n      const chunk1 = Chunk.empty()\n      const chunk2 = Chunk.unsafeFromArray([1, 2])\n\n      it(\"should concatenate them following order\", () => {\n        assertEquals(pipe(chunk1, Chunk.appendAll(chunk2)), Chunk.unsafeFromArray([1, 2]))\n      })\n    })\n\n    describe(\"Given 2 chunks where the second one is empty\", () => {\n      const chunk1 = Chunk.unsafeFromArray([1, 2])\n      const chunk2 = Chunk.empty()\n\n      it(\"should concatenate them following order\", () => {\n        assertEquals(pipe(chunk1, Chunk.appendAll(chunk2)), Chunk.unsafeFromArray([1, 2]))\n      })\n    })\n\n    describe(\"Given several chunks concatenated with each\", () => {\n      const chunk1 = Chunk.empty()\n      const chunk2 = Chunk.unsafeFromArray([1])\n      const chunk3 = Chunk.unsafeFromArray([2])\n      const chunk4 = Chunk.unsafeFromArray([3, 4])\n      const chunk5 = Chunk.unsafeFromArray([5, 6])\n\n      it(\"should concatenate them following order\", () => {\n        assertEquals(\n          pipe(\n            chunk1,\n            Chunk.appendAll(chunk2),\n            Chunk.appendAll(chunk3),\n            Chunk.appendAll(chunk4),\n            Chunk.appendAll(chunk5)\n          ),\n          Chunk.unsafeFromArray([1, 2, 3, 4, 5, 6])\n        )\n      })\n    })\n  })\n\n  it(\"zip\", () => {\n    assertEquals(Chunk.zip(Chunk.empty(), Chunk.empty()), Chunk.empty())\n    assertEquals(Chunk.zip(Chunk.make(1), Chunk.empty()), Chunk.empty())\n    assertEquals(Chunk.zip(Chunk.empty(), Chunk.make(1)), Chunk.empty())\n    deepStrictEqual(Chunk.toArray(Chunk.zip(Chunk.make(1), Chunk.make(2))), [[1, 2]])\n  })\n\n  describe(\"Given two non-materialized chunks of different sizes\", () => {\n    it(\"should zip the chunks together and drop the leftover\", () => {\n      // Create two non-materialized Chunks\n      const left = pipe(Chunk.make(-1, 0, 1), Chunk.drop(1))\n      const right = pipe(Chunk.make(1, 0, 0, 1), Chunk.drop(1))\n      const zipped = pipe(left, Chunk.zipWith(pipe(right, Chunk.take(left.length)), (a, b) => [a, b]))\n      deepStrictEqual(Array.from(zipped), [[0, 0], [1, 0]])\n    })\n  })\n\n  it(\"last\", () => {\n    assertNone(Chunk.last(Chunk.empty()))\n    assertSome(Chunk.last(Chunk.make(1, 2, 3)), 3)\n  })\n\n  it(\"map\", () => {\n    assertEquals(Chunk.map(Chunk.empty(), (n) => n + 1), Chunk.empty())\n    assertEquals(Chunk.map(Chunk.of(1), (n) => n + 1), Chunk.of(2))\n    assertEquals(Chunk.map(Chunk.make(1, 2, 3), (n) => n + 1), Chunk.make(2, 3, 4))\n    assertEquals(Chunk.map(Chunk.make(1, 2, 3), (n, i) => n + i), Chunk.make(1, 3, 5))\n  })\n\n  it(\"mapAccum\", () => {\n    deepStrictEqual(Chunk.mapAccum(Chunk.make(1, 2, 3), \"-\", (s, a) => [s + a, a + 1]), [\"-123\", Chunk.make(2, 3, 4)])\n  })\n\n  it(\"partition\", () => {\n    assertTuple(Chunk.partition(Chunk.empty(), (n) => n > 2), [Chunk.empty(), Chunk.empty()])\n    assertTuple(Chunk.partition(Chunk.make(1, 3), (n) => n > 2), [Chunk.make(1), Chunk.make(3)])\n\n    assertTuple(Chunk.partition(Chunk.empty(), (n, i) => n + i > 2), [Chunk.empty(), Chunk.empty()])\n    assertTuple(Chunk.partition(Chunk.make(1, 2), (n, i) => n + i > 2), [Chunk.make(1), Chunk.make(2)])\n  })\n\n  it(\"partitionMap\", () => {\n    assertTuple(Chunk.partitionMap(Chunk.empty(), identity), [Chunk.empty(), Chunk.empty()])\n    assertTuple(Chunk.partitionMap(Chunk.make(Either.right(1), Either.left(\"a\"), Either.right(2)), identity), [\n      Chunk.make(\"a\"),\n      Chunk.make(1, 2)\n    ])\n  })\n\n  it(\"separate\", () => {\n    assertTuple(Chunk.separate(Chunk.empty()), [Chunk.empty(), Chunk.empty()])\n    assertTuple(Chunk.separate(Chunk.make(Either.right(1), Either.left(\"e\"), Either.right(2))), [\n      Chunk.make(\"e\"),\n      Chunk.make(1, 2)\n    ])\n  })\n\n  it(\"size\", () => {\n    strictEqual(Chunk.size(Chunk.empty()), 0)\n    strictEqual(Chunk.size(Chunk.make(1, 2, 3)), 3)\n  })\n\n  it(\"split\", () => {\n    assertEquals(pipe(Chunk.empty(), Chunk.split(2)), Chunk.empty())\n    assertEquals(pipe(Chunk.make(1), Chunk.split(2)), Chunk.make(Chunk.make(1)))\n    assertEquals(pipe(Chunk.make(1, 2), Chunk.split(2)), Chunk.make(Chunk.make(1), Chunk.make(2)))\n    assertEquals(pipe(Chunk.make(1, 2, 3, 4, 5), Chunk.split(2)), Chunk.make(Chunk.make(1, 2, 3), Chunk.make(4, 5)))\n    assertEquals(\n      pipe(Chunk.make(1, 2, 3, 4, 5), Chunk.split(3)),\n      Chunk.make(Chunk.make(1, 2), Chunk.make(3, 4), Chunk.make(5))\n    )\n  })\n\n  it(\"tail\", () => {\n    assertNone(Chunk.tail(Chunk.empty()))\n    // TODO: use assertSome?\n    assertEquals(Chunk.tail(Chunk.make(1, 2, 3)), Option.some(Chunk.make(2, 3)))\n  })\n\n  it(\"filter\", () => {\n    assertEquals(Chunk.filter(Chunk.make(1, 2, 3), (n) => n % 2 === 1), Chunk.make(1, 3))\n    assertEquals(\n      Chunk.filter(Chunk.make(Option.some(3), Option.some(2), Option.some(1)), Option.isSome),\n      Chunk.make(Option.some(3), Option.some(2), Option.some(1)) as any\n    )\n    assertEquals(\n      Chunk.filter(Chunk.make(Option.some(3), Option.none(), Option.some(1)), Option.isSome),\n      Chunk.make(Option.some(3), Option.some(1)) as any\n    )\n  })\n\n  it(\"filterMapWhile\", () => {\n    assertEquals(\n      Chunk.filterMapWhile(Chunk.make(1, 3, 4, 5), (n) => n % 2 === 1 ? Option.some(n) : Option.none()),\n      Chunk.make(1, 3)\n    )\n  })\n\n  it(\"compact\", () => {\n    assertEquals(Chunk.compact(Chunk.empty()), Chunk.empty())\n    assertEquals(Chunk.compact(Chunk.make(Option.some(1), Option.some(2), Option.some(3))), Chunk.make(1, 2, 3))\n    assertEquals(Chunk.compact(Chunk.make(Option.some(1), Option.none(), Option.some(3))), Chunk.make(1, 3))\n  })\n\n  it(\"dedupeAdjacent\", () => {\n    assertEquals(Chunk.dedupeAdjacent(Chunk.empty()), Chunk.empty())\n    assertEquals(Chunk.dedupeAdjacent(Chunk.make(1, 2, 3)), Chunk.make(1, 2, 3))\n    assertEquals(Chunk.dedupeAdjacent(Chunk.make(1, 2, 2, 3, 3)), Chunk.make(1, 2, 3))\n  })\n\n  it(\"flatMap\", () => {\n    assertEquals(Chunk.flatMap(Chunk.make(1), (n) => Chunk.make(n, n + 1)), Chunk.make(1, 2))\n    assertEquals(Chunk.flatMap(Chunk.make(1, 2, 3), (n) => Chunk.make(n, n + 1)), Chunk.make(1, 2, 2, 3, 3, 4))\n  })\n\n  it(\"union\", () => {\n    assertEquals(Chunk.union(Chunk.make(1, 2, 3), Chunk.empty()), Chunk.make(1, 2, 3))\n    assertEquals(Chunk.union(Chunk.empty(), Chunk.make(1, 2, 3)), Chunk.make(1, 2, 3))\n    assertEquals(Chunk.union(Chunk.make(1, 2, 3), Chunk.make(2, 3, 4)), Chunk.make(1, 2, 3, 4))\n  })\n\n  it(\"intersection\", () => {\n    assertEquals(Chunk.intersection(Chunk.make(1, 2, 3), Chunk.empty()), Chunk.empty())\n    assertEquals(Chunk.intersection(Chunk.empty(), Chunk.make(2, 3, 4)), Chunk.empty())\n    assertEquals(Chunk.intersection(Chunk.make(1, 2, 3), Chunk.make(2, 3, 4)), Chunk.make(2, 3))\n  })\n\n  it(\"isEmpty\", () => {\n    assertTrue(Chunk.isEmpty(Chunk.empty()))\n    assertFalse(Chunk.isEmpty(Chunk.make(1)))\n  })\n\n  it(\"unsafeLast\", () => {\n    strictEqual(Chunk.unsafeLast(Chunk.make(1)), 1)\n    strictEqual(Chunk.unsafeLast(Chunk.make(1, 2, 3)), 3)\n    throws(() => Chunk.unsafeLast(Chunk.empty()), new Error(\"Index out of bounds\"))\n  })\n\n  it(\"splitNonEmptyAt\", () => {\n    assertTuple(Chunk.splitNonEmptyAt(Chunk.make(1, 2, 3, 4), 2), [Chunk.make(1, 2), Chunk.make(3, 4)])\n    assertTuple(Chunk.splitNonEmptyAt(Chunk.make(1, 2, 3, 4), 10), [Chunk.make(1, 2, 3, 4), Chunk.empty()])\n  })\n\n  it(\"splitWhere\", () => {\n    assertTuple(Chunk.splitWhere(Chunk.empty(), (n) => n > 1), [Chunk.empty(), Chunk.empty()])\n    assertTuple(Chunk.splitWhere(Chunk.make(1, 2, 3), (n) => n > 1), [Chunk.make(1), Chunk.make(2, 3)])\n  })\n\n  it(\"takeWhile\", () => {\n    assertEquals(Chunk.takeWhile(Chunk.empty(), (n) => n <= 2), Chunk.empty())\n    assertEquals(Chunk.takeWhile(Chunk.make(1, 2, 3), (n) => n <= 2), Chunk.make(1, 2))\n  })\n\n  it(\"dedupe\", () => {\n    assertEquals(Chunk.dedupe(Chunk.empty()), Chunk.empty())\n    assertEquals(Chunk.dedupe(Chunk.make(1, 2, 3)), Chunk.make(1, 2, 3))\n    assertEquals(Chunk.dedupe(Chunk.make(1, 2, 3, 2, 1, 3)), Chunk.make(1, 2, 3))\n  })\n\n  it(\"unzip\", () => {\n    assertTuple(Chunk.unzip(Chunk.empty()), [Chunk.empty(), Chunk.empty()])\n    assertTuple(Chunk.unzip(Chunk.make([\"a\", 1] as const, [\"b\", 2] as const)), [\n      Chunk.make(\"a\", \"b\"),\n      Chunk.make(1, 2)\n    ])\n  })\n\n  it(\"reverse\", () => {\n    assertEquals(Chunk.reverse(Chunk.empty()), Chunk.empty())\n    assertEquals(Chunk.reverse(Chunk.make(1, 2, 3)), Chunk.make(3, 2, 1))\n    assertEquals(Chunk.reverse(Chunk.take(Chunk.make(1, 2, 3, 4), 3)), Chunk.make(3, 2, 1))\n  })\n\n  it(\"flatten\", () => {\n    assertEquals(Chunk.flatten(Chunk.make(Chunk.make(1), Chunk.make(2), Chunk.make(3))), Chunk.make(1, 2, 3))\n  })\n\n  it(\"makeBy\", () => {\n    assertEquals(Chunk.makeBy(5, (n) => n * 2), Chunk.make(0, 2, 4, 6, 8))\n    assertEquals(Chunk.makeBy(2.2, (n) => n * 2), Chunk.make(0, 2))\n  })\n\n  it(\"range\", () => {\n    assertEquals(Chunk.range(0, 0), Chunk.make(0))\n    assertEquals(Chunk.range(0, 1), Chunk.make(0, 1))\n    assertEquals(Chunk.range(1, 5), Chunk.make(1, 2, 3, 4, 5))\n    assertEquals(Chunk.range(10, 15), Chunk.make(10, 11, 12, 13, 14, 15))\n    assertEquals(Chunk.range(-1, 0), Chunk.make(-1, 0))\n    assertEquals(Chunk.range(-5, -1), Chunk.make(-5, -4, -3, -2, -1))\n    // out of bound\n    assertEquals(Chunk.range(2, 1), Chunk.make(2))\n    assertEquals(Chunk.range(-1, -2), Chunk.make(-1))\n  })\n\n  it(\"some\", () => {\n    const isPositive: Predicate.Predicate<number> = (n) => n > 0\n    assertTrue(Chunk.some(Chunk.make(-1, -2, 3), isPositive))\n    assertFalse(Chunk.some(Chunk.make(-1, -2, -3), isPositive))\n  })\n\n  it(\"forEach\", () => {\n    const as: Array<string> = []\n    Chunk.forEach(Chunk.make(1, 2, 3, 4), (n, i) => as.push(`${n}-${i}`))\n    deepStrictEqual(as, [\"1-0\", \"2-1\", \"3-2\", \"4-3\"])\n  })\n\n  it(\"sortWith\", () => {\n    type X = {\n      a: string\n      b: number\n    }\n    const chunk: Chunk.Chunk<X> = Chunk.make({ a: \"a\", b: 2 }, { a: \"b\", b: 1 })\n    deepStrictEqual(Chunk.sortWith(chunk, (x) => x.b, Order.number), Chunk.make({ a: \"b\", b: 1 }, { a: \"a\", b: 2 }))\n  })\n\n  it(\"getEquivalence\", () => {\n    const equivalence = Chunk.getEquivalence(Num.Equivalence)\n    assertTrue(equivalence(Chunk.empty(), Chunk.empty()))\n    assertTrue(equivalence(Chunk.make(1, 2, 3), Chunk.make(1, 2, 3)))\n    assertFalse(equivalence(Chunk.make(1, 2, 3), Chunk.make(1, 2)))\n    assertFalse(equivalence(Chunk.make(1, 2, 3), Chunk.make(1, 2, 4)))\n  })\n\n  it(\"differenceWith\", () => {\n    const eq = <E extends { id: number }>(a: E, b: E) => a.id === b.id\n    const differenceWith = pipe(eq, Chunk.differenceWith)\n\n    const chunk = Chunk.make({ id: 1 }, { id: 2 }, { id: 3 })\n\n    deepStrictEqual(differenceWith(Chunk.make({ id: 1 }, { id: 2 }), chunk), Chunk.make({ id: 3 }))\n    assertEquals(differenceWith(Chunk.empty(), chunk), chunk)\n    assertEquals(differenceWith(chunk, Chunk.empty()), Chunk.empty())\n    assertEquals(differenceWith(chunk, chunk), Chunk.empty())\n  })\n\n  it(\"difference\", () => {\n    const curr = Chunk.make(1, 3, 5, 7, 9)\n\n    assertEquals(Chunk.difference(Chunk.make(1, 2, 3, 4, 5), curr), Chunk.make(7, 9))\n    assertEquals(Chunk.difference(Chunk.empty(), curr), curr)\n    assertEquals(Chunk.difference(curr, Chunk.empty()), Chunk.empty())\n    assertEquals(Chunk.difference(curr, curr), Chunk.empty())\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Config.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFailure, assertSuccess, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport {\n  Brand,\n  Cause,\n  Chunk,\n  Config,\n  ConfigError,\n  ConfigProvider,\n  Duration,\n  Effect,\n  Equal,\n  HashSet,\n  LogLevel,\n  Option,\n  pipe,\n  Redacted,\n  Secret\n} from \"effect\"\n\ntype Str = Brand.Branded<string, \"Str\">\nconst Str = Brand.refined<Str>(\n  (n) => n.length > 2,\n  (n) => Brand.error(`Brand: Expected ${n} to be longer than 2`)\n)\n\nconst assertConfigError = <A>(\n  config: Config.Config<A>,\n  map: ReadonlyArray<readonly [string, string]>,\n  error: ConfigError.ConfigError\n) => {\n  const configProvider = ConfigProvider.fromMap(new Map(map))\n  const result = Effect.runSyncExit(configProvider.load(config))\n  assertFailure(result, Cause.fail(error))\n}\n\nconst assertConfig = <A>(\n  config: Config.Config<A>,\n  map: ReadonlyArray<readonly [string, string]>,\n  a: A\n) => {\n  const configProvider = ConfigProvider.fromMap(new Map(map))\n  const result = Effect.runSyncExit(configProvider.load(config))\n  assertSuccess(result, a)\n}\n\ndescribe(\"Config\", () => {\n  describe(\"boolean\", () => {\n    it(\"name = undefined\", () => {\n      const config = Config.array(Config.boolean(), \"ITEMS\")\n      assertConfig(config, [[\"ITEMS\", \"true\"]], [true])\n      assertConfigError(\n        config,\n        [[\"ITEMS\", \"value\"]],\n        ConfigError.InvalidData([\"ITEMS\"], `Expected a boolean value but received \"value\"`)\n      )\n    })\n\n    it(\"name != undefined\", () => {\n      const config = Config.boolean(\"BOOL\")\n      assertConfig(config, [[\"BOOL\", \"true\"]], true)\n      assertConfig(config, [[\"BOOL\", \"yes\"]], true)\n      assertConfig(config, [[\"BOOL\", \"on\"]], true)\n      assertConfig(config, [[\"BOOL\", \"1\"]], true)\n      assertConfig(config, [[\"BOOL\", \"false\"]], false)\n      assertConfig(config, [[\"BOOL\", \"no\"]], false)\n      assertConfig(config, [[\"BOOL\", \"off\"]], false)\n      assertConfig(config, [[\"BOOL\", \"0\"]], false)\n\n      assertConfigError(config, [], ConfigError.MissingData([\"BOOL\"], \"Expected BOOL to exist in the provided map\"))\n      assertConfigError(\n        config,\n        [[\"BOOL\", \"value\"]],\n        ConfigError.InvalidData([\"BOOL\"], `Expected a boolean value but received \"value\"`)\n      )\n    })\n  })\n\n  describe(\"url\", () => {\n    it(\"name != undefined\", () => {\n      const config = Config.url(\"WEBSITE_URL\")\n      assertConfig(\n        config,\n        [[\"WEBSITE_URL\", \"https://effect.website/docs/introduction#what-is-effect\"]],\n        new URL(\"https://effect.website/docs/introduction#what-is-effect\")\n      )\n      assertConfigError(\n        config,\n        [[\"WEBSITE_URL\", \"abra-kadabra\"]],\n        ConfigError.InvalidData([\"WEBSITE_URL\"], `Expected an URL value but received \"abra-kadabra\"`)\n      )\n      assertConfigError(\n        config,\n        [],\n        ConfigError.MissingData([\"WEBSITE_URL\"], \"Expected WEBSITE_URL to exist in the provided map\")\n      )\n    })\n  })\n\n  describe(\"port\", () => {\n    it(\"name != undefined\", () => {\n      const config = Config.port(\"WEBSITE_PORT\")\n\n      assertConfig(\n        config,\n        [[\"WEBSITE_PORT\", \"123\"]],\n        123\n      )\n      assertConfigError(\n        config,\n        [[\"WEBSITE_PORT\", \"abra-kadabra\"]],\n        ConfigError.InvalidData([\"WEBSITE_PORT\"], `Expected a network port value but received \"abra-kadabra\"`)\n      )\n      assertConfigError(\n        config,\n        [],\n        ConfigError.MissingData([\"WEBSITE_PORT\"], \"Expected WEBSITE_PORT to exist in the provided map\")\n      )\n    })\n  })\n\n  describe(\"branded\", () => {\n    it(\"name != undefined\", () => {\n      const config = Config.branded(Config.string(\"STR\"), Str)\n\n      assertConfig(\n        config,\n        [[\"STR\", \"123\"]],\n        Str(\"123\")\n      )\n      assertConfigError(\n        config,\n        [[\"STR\", \"1\"]],\n        ConfigError.InvalidData([\"STR\"], \"Brand: Expected 1 to be longer than 2\")\n      )\n      assertConfigError(\n        config,\n        [],\n        ConfigError.MissingData([\"STR\"], \"Expected STR to exist in the provided map\")\n      )\n    })\n    it(\"name != undefined from name\", () => {\n      const config = Config.branded(\"STR\", Str)\n\n      assertConfig(\n        config,\n        [[\"STR\", \"123\"]],\n        Str(\"123\")\n      )\n      assertConfigError(\n        config,\n        [[\"STR\", \"1\"]],\n        ConfigError.InvalidData([\"STR\"], \"Brand: Expected 1 to be longer than 2\")\n      )\n      assertConfigError(\n        config,\n        [],\n        ConfigError.MissingData([\"STR\"], \"Expected STR to exist in the provided map\")\n      )\n    })\n  })\n\n  describe(\"nonEmptyString\", () => {\n    it(\"name = undefined\", () => {\n      const config = Config.array(Config.nonEmptyString(), \"ITEMS\")\n      assertConfig(config, [[\"ITEMS\", \"foo\"]], [\"foo\"])\n      assertConfigError(config, [[\"ITEMS\", \"\"]], ConfigError.MissingData([\"ITEMS\"], \"Expected a non-empty string\"))\n    })\n\n    it(\"name != undefined\", () => {\n      const config = Config.nonEmptyString(\"NON_EMPTY_STRING\")\n      assertConfig(config, [[\"NON_EMPTY_STRING\", \"foo\"]], \"foo\")\n      assertConfig(config, [[\"NON_EMPTY_STRING\", \" \"]], \" \")\n      assertConfigError(\n        config,\n        [[\"NON_EMPTY_STRING\", \"\"]],\n        ConfigError.MissingData([\"NON_EMPTY_STRING\"], \"Expected a non-empty string\")\n      )\n    })\n  })\n\n  describe(\"number\", () => {\n    it(\"name = undefined\", () => {\n      const config = Config.array(Config.number(), \"ITEMS\")\n      assertConfig(config, [[\"ITEMS\", \"1\"]], [1])\n      assertConfigError(\n        config,\n        [[\"ITEMS\", \"123qq\"]],\n        ConfigError.InvalidData([\"ITEMS\"], `Expected a number value but received \"123qq\"`)\n      )\n      assertConfigError(\n        config,\n        [[\"ITEMS\", \"value\"]],\n        ConfigError.InvalidData([\"ITEMS\"], `Expected a number value but received \"value\"`)\n      )\n    })\n\n    it(\"name != undefined\", () => {\n      const config = Config.number(\"NUMBER\")\n      assertConfig(config, [[\"NUMBER\", \"1\"]], 1)\n      assertConfig(config, [[\"NUMBER\", \"1.2\"]], 1.2)\n      assertConfig(config, [[\"NUMBER\", \"-1\"]], -1)\n      assertConfig(config, [[\"NUMBER\", \"-1.2\"]], -1.2)\n      assertConfig(config, [[\"NUMBER\", \"0\"]], 0)\n      assertConfig(config, [[\"NUMBER\", \"-0\"]], -0)\n\n      assertConfigError(config, [], ConfigError.MissingData([\"NUMBER\"], \"Expected NUMBER to exist in the provided map\"))\n      assertConfigError(\n        config,\n        [[\"NUMBER\", \"value\"]],\n        ConfigError.InvalidData([\"NUMBER\"], `Expected a number value but received \"value\"`)\n      )\n    })\n  })\n\n  describe(\"literal\", () => {\n    it(\"name = undefined\", () => {\n      const config = Config.array(Config.literal(\"a\", \"b\")(), \"ITEMS\")\n      assertConfig(config, [[\"ITEMS\", \"a\"]], [\"a\"])\n      assertConfigError(\n        config,\n        [[\"ITEMS\", \"value\"]],\n        ConfigError.InvalidData([\"ITEMS\"], `Expected one of (a, b) but received \"value\"`)\n      )\n    })\n\n    it(\"name != undefined\", () => {\n      const config = Config.literal(\"a\", 0, -0.3, BigInt(5), false, null)(\"LITERAL\")\n      assertConfig(config, [[\"LITERAL\", \"a\"]], \"a\")\n      assertConfig(config, [[\"LITERAL\", \"0\"]], 0)\n      assertConfig(config, [[\"LITERAL\", \"-0.3\"]], -0.3)\n      assertConfig(config, [[\"LITERAL\", \"5\"]], BigInt(5))\n      assertConfig(config, [[\"LITERAL\", \"false\"]], false)\n      assertConfig(config, [[\"LITERAL\", \"null\"]], null)\n\n      assertConfigError(\n        config,\n        [],\n        ConfigError.MissingData([\"LITERAL\"], \"Expected LITERAL to exist in the provided map\")\n      )\n      assertConfigError(\n        config,\n        [[\"LITERAL\", \"value\"]],\n        ConfigError.InvalidData([\"LITERAL\"], `Expected one of (a, 0, -0.3, 5, false, null) but received \"value\"`)\n      )\n    })\n  })\n\n  describe(\"date\", () => {\n    it(\"name = undefined\", () => {\n      const config = Config.date()\n      assertConfig(config, [[\"\", \"0\"]], new Date(Date.parse(\"0\")))\n      assertConfigError(\n        config,\n        [[\"\", \"value\"]],\n        ConfigError.InvalidData([], `Expected a Date value but received \"value\"`)\n      )\n    })\n\n    it(\"name != undefined\", () => {\n      const config = Config.date(\"DATE\")\n      assertConfig(config, [[\"DATE\", \"0\"]], new Date(Date.parse(\"0\")))\n\n      assertConfigError(config, [], ConfigError.MissingData([\"DATE\"], \"Expected DATE to exist in the provided map\"))\n      assertConfigError(\n        config,\n        [[\"DATE\", \"value\"]],\n        ConfigError.InvalidData([\"DATE\"], `Expected a Date value but received \"value\"`)\n      )\n    })\n  })\n\n  it(\"fail\", () => {\n    const config = Config.fail(\"failure message\")\n    assertConfigError(config, [], ConfigError.MissingData([], \"failure message\"))\n  })\n\n  it(\"mapAttempt\", () => {\n    const config = Config.string(\"STRING\").pipe(Config.mapAttempt((s) => {\n      const n = parseFloat(s)\n      if (Number.isNaN(n)) {\n        throw new Error(\"invalid number\")\n      }\n      if (n < 0) {\n        throw \"invalid negative number\"\n      }\n      return n\n    }))\n    assertConfig(config, [[\"STRING\", \"1\"]], 1)\n    assertConfigError(\n      config,\n      [[\"STRING\", \"value\"]],\n      ConfigError.InvalidData([\"STRING\"], \"invalid number\")\n    )\n    assertConfigError(\n      config,\n      [[\"STRING\", \"-1\"]],\n      ConfigError.InvalidData([\"STRING\"], \"invalid negative number\")\n    )\n    assertConfigError(config, [], ConfigError.MissingData([\"STRING\"], \"Expected STRING to exist in the provided map\"))\n  })\n\n  describe(\"logLevel\", () => {\n    it(\"name = undefined\", () => {\n      const config = Config.logLevel()\n      assertConfig(config, [[\"\", \"DEBUG\"]], LogLevel.Debug)\n\n      assertConfigError(config, [[\"\", \"-\"]], ConfigError.InvalidData([], `Expected a log level but received \"-\"`))\n    })\n\n    it(\"name != undefined\", () => {\n      const config = Config.logLevel(\"LOG_LEVEL\")\n      assertConfig(config, [[\"LOG_LEVEL\", \"DEBUG\"]], LogLevel.Debug)\n\n      assertConfigError(\n        config,\n        [[\"LOG_LEVEL\", \"-\"]],\n        ConfigError.InvalidData([\"LOG_LEVEL\"], `Expected a log level but received \"-\"`)\n      )\n    })\n  })\n\n  describe(\"duration\", () => {\n    it(\"name = undefined\", () => {\n      const config = Config.duration()\n      assertConfig(config, [[\"\", \"10 seconds\"]], Duration.decode(\"10 seconds\"))\n\n      assertConfigError(config, [[\"\", \"-\"]], ConfigError.InvalidData([], `Expected a duration but received \"-\"`))\n    })\n\n    it(\"name != undefined\", () => {\n      const config = Config.duration(\"DURATION\")\n      assertConfig(config, [[\"DURATION\", \"10 seconds\"]], Duration.decode(\"10 seconds\"))\n\n      assertConfigError(\n        config,\n        [[\"DURATION\", \"-\"]],\n        ConfigError.InvalidData([\"DURATION\"], `Expected a duration but received \"-\"`)\n      )\n    })\n  })\n\n  describe(\"validate\", () => {\n    it(\"should preserve the original path\", () => {\n      const flat = Config.number(\"NUMBER\").pipe(\n        Config.validate({\n          message: \"a positive number\",\n          validation: (n) => n >= 0\n        })\n      )\n      assertConfig(flat, [[\"NUMBER\", \"1\"]], 1)\n      assertConfig(flat, [[\"NUMBER\", \"1.2\"]], 1.2)\n      assertConfigError(\n        flat,\n        [[\"NUMBER\", \"-1\"]],\n        ConfigError.InvalidData([\"NUMBER\"], \"a positive number\")\n      )\n\n      const nested = flat.pipe(\n        Config.nested(\"NESTED1\")\n      )\n      assertConfig(nested, [[\"NESTED1.NUMBER\", \"1\"]], 1)\n      assertConfig(nested, [[\"NESTED1.NUMBER\", \"1.2\"]], 1.2)\n      assertConfigError(\n        nested,\n        [[\"NESTED1.NUMBER\", \"-1\"]],\n        ConfigError.InvalidData([\"NESTED1\", \"NUMBER\"], \"a positive number\")\n      )\n\n      const doubleNested = nested.pipe(Config.nested(\"NESTED2\"))\n      assertConfig(doubleNested, [[\"NESTED2.NESTED1.NUMBER\", \"1\"]], 1)\n      assertConfig(doubleNested, [[\"NESTED2.NESTED1.NUMBER\", \"1.2\"]], 1.2)\n      assertConfigError(\n        doubleNested,\n        [[\"NESTED2.NESTED1.NUMBER\", \"-1\"]],\n        ConfigError.InvalidData([\"NESTED2\", \"NESTED1\", \"NUMBER\"], \"a positive number\")\n      )\n    })\n  })\n\n  describe(\"withDefault\", () => {\n    it(\"recovers from missing data error\", () => {\n      const config = pipe(\n        Config.integer(\"key\"),\n        Config.withDefault(0)\n      )\n      // available data\n      assertConfig(config, [[\"key\", \"1\"]], 1)\n      // missing data\n      assertConfig(config, [], 0)\n    })\n\n    it(\"does not recover from other errors\", () => {\n      const config = pipe(\n        Config.integer(\"key\"),\n        Config.withDefault(0)\n      )\n      assertConfig(config, [[\"key\", \"1\"]], 1)\n      assertConfigError(\n        config,\n        [[\"key\", \"1.2\"]],\n        // available data but not an integer\n        ConfigError.InvalidData([\"key\"], `Expected an integer value but received \"1.2\"`)\n      )\n      assertConfigError(\n        config,\n        [[\"key\", \"value\"]],\n        // available data but not an integer\n        ConfigError.InvalidData([\"key\"], `Expected an integer value but received \"value\"`)\n      )\n    })\n\n    it(\"does not recover from missing data and other error\", () => {\n      const config = pipe(\n        Config.integer(\"key1\"),\n        Config.zip(Config.integer(\"key2\")),\n        Config.withDefault([0, 0])\n      )\n      assertConfig(config, [], [0, 0])\n      assertConfig(config, [[\"key1\", \"1\"], [\"key2\", \"2\"]], [1, 2])\n      assertConfigError(\n        config,\n        [[\"key2\", \"value\"]],\n        ConfigError.And(\n          ConfigError.MissingData([\"key1\"], \"Expected key1 to exist in the provided map\"),\n          ConfigError.InvalidData([\"key2\"], `Expected an integer value but received \"value\"`)\n        )\n      )\n    })\n\n    it(\"does not recover from missing data or other error\", () => {\n      const config = pipe(\n        Config.integer(\"key1\"),\n        Config.orElse(() => Config.integer(\"key2\")),\n        Config.withDefault(0)\n      )\n      assertConfig(config, [], 0)\n      assertConfig(config, [[\"key1\", \"1\"]], 1)\n      assertConfig(config, [[\"key2\", \"2\"]], 2)\n      assertConfigError(\n        config,\n        [[\"key2\", \"value\"]],\n        ConfigError.Or(\n          ConfigError.MissingData([\"key1\"], \"Expected key1 to exist in the provided map\"),\n          ConfigError.InvalidData([\"key2\"], `Expected an integer value but received \"value\"`)\n        )\n      )\n    })\n  })\n\n  describe(\"option\", () => {\n    it(\"recovers from missing data error\", () => {\n      const config = Config.option(Config.integer(\"key\"))\n      assertConfig(config, [], Option.none())\n      assertConfig(config, [[\"key\", \"1\"]], Option.some(1))\n    })\n\n    it(\"does not recover from other errors\", () => {\n      const config = Config.option(Config.integer(\"key\"))\n      assertConfigError(\n        config,\n        [[\"key\", \"value\"]],\n        ConfigError.InvalidData([\"key\"], `Expected an integer value but received \"value\"`)\n      )\n    })\n\n    it(\"does not recover from other errors\", () => {\n      const config = pipe(\n        Config.integer(\"key1\"),\n        Config.zip(Config.integer(\"key2\")),\n        Config.option\n      )\n      assertConfig(config, [[\"key1\", \"1\"], [\"key2\", \"2\"]], Option.some([1, 2]))\n      assertConfigError(\n        config,\n        [[\"key1\", \"value\"]],\n        ConfigError.And(\n          ConfigError.InvalidData([\"key1\"], `Expected an integer value but received \"value\"`),\n          ConfigError.MissingData([\"key2\"], \"Expected key2 to exist in the provided map\")\n        )\n      )\n      assertConfigError(\n        config,\n        [[\"key2\", \"value\"]],\n        ConfigError.And(\n          ConfigError.MissingData([\"key1\"], \"Expected key1 to exist in the provided map\"),\n          ConfigError.InvalidData([\"key2\"], `Expected an integer value but received \"value\"`)\n        )\n      )\n    })\n\n    it(\"does not recover from other errors\", () => {\n      const config = pipe(\n        Config.integer(\"key1\"),\n        Config.orElse(() => Config.integer(\"key2\")),\n        Config.option\n      )\n      assertConfig(config, [[\"key1\", \"1\"]], Option.some(1))\n      assertConfig(config, [[\"key1\", \"value\"], [\"key2\", \"2\"]], Option.some(2))\n      assertConfigError(\n        config,\n        [[\"key2\", \"value\"]],\n        ConfigError.Or(\n          ConfigError.MissingData([\"key1\"], \"Expected key1 to exist in the provided map\"),\n          ConfigError.InvalidData([\"key2\"], `Expected an integer value but received \"value\"`)\n        )\n      )\n    })\n  })\n\n  describe(\"Wrap\", () => {\n    it(\"unwrap correctly builds config\", () => {\n      const wrapper = (\n        _: Config.Config.Wrap<{\n          key1: number\n          list: ReadonlyArray<number>\n          option: Option.Option<number>\n          secret: Redacted.Redacted\n          nested?:\n            | Partial<{\n              key2: string\n            }>\n            | undefined\n        }>\n      ) => Config.unwrap(_)\n\n      const config = wrapper({\n        key1: Config.integer(\"key1\"),\n        list: Config.array(Config.integer(), \"items\"),\n        option: Config.option(Config.integer(\"option\")),\n        secret: Config.redacted(\"secret\"),\n        nested: {\n          key2: Config.string(\"key2\")\n        }\n      })\n      assertConfig(config, [[\"key1\", \"123\"], [\"items\", \"1,2,3\"], [\"option\", \"123\"], [\"secret\", \"sauce\"], [\n        \"key2\",\n        \"value\"\n      ]], {\n        key1: 123,\n        list: [1, 2, 3],\n        option: Option.some(123),\n        secret: Redacted.make(\"sauce\"),\n        nested: {\n          key2: \"value\"\n        }\n      })\n      assertConfigError(\n        config,\n        [[\"key1\", \"123\"], [\"items\", \"1,value,3\"], [\"option\", \"123\"], [\"secret\", \"sauce\"], [\"key2\", \"value\"]],\n        ConfigError.InvalidData([\"items\"], `Expected an integer value but received \"value\"`)\n      )\n    })\n  })\n\n  it(\"sync\", () => {\n    const config = Config.sync(() => 1)\n    assertConfig(config, [], 1)\n  })\n\n  describe(\"all\", () => {\n    describe(\"tuple\", () => {\n      it(\"length = 0\", () => {\n        const config = Config.all([])\n        assertConfig(config, [], [])\n      })\n\n      it(\"length = 1\", () => {\n        const config = Config.all([Config.number(\"NUMBER\")])\n        assertConfig(config, [[\"NUMBER\", \"1\"]], [1])\n      })\n\n      it(\"length > 1\", () => {\n        const config = Config.all([Config.number(\"NUMBER\"), Config.boolean(\"BOOL\")])\n        assertConfig(config, [[\"NUMBER\", \"1\"], [\"BOOL\", \"true\"]], [1, true])\n        assertConfigError(\n          config,\n          [[\"NUMBER\", \"value\"], [\"BOOL\", \"true\"]],\n          ConfigError.InvalidData([\"NUMBER\"], `Expected a number value but received \"value\"`)\n        )\n        assertConfigError(\n          config,\n          [[\"NUMBER\", \"1\"], [\"BOOL\", \"value\"]],\n          ConfigError.InvalidData([\"BOOL\"], `Expected a boolean value but received \"value\"`)\n        )\n      })\n    })\n\n    it(\"iterable\", () => {\n      const set = new Set([Config.number(\"NUMBER\"), Config.boolean(\"BOOL\")])\n      const config = Config.all(set)\n      assertConfig(config, [[\"NUMBER\", \"1\"], [\"BOOL\", \"true\"]], [1, true])\n      assertConfigError(\n        config,\n        [[\"NUMBER\", \"value\"], [\"BOOL\", \"true\"]],\n        ConfigError.InvalidData([\"NUMBER\"], `Expected a number value but received \"value\"`)\n      )\n      assertConfigError(\n        config,\n        [[\"NUMBER\", \"1\"], [\"BOOL\", \"value\"]],\n        ConfigError.InvalidData([\"BOOL\"], `Expected a boolean value but received \"value\"`)\n      )\n    })\n  })\n\n  describe(\"Config.redacted\", () => {\n    it(\"name = undefined\", () => {\n      const config = Config.array(Config.redacted(), \"ITEMS\")\n      assertConfig(config, [[\"ITEMS\", \"a\"]], [Redacted.make(\"a\")])\n    })\n\n    it(\"name != undefined\", () => {\n      const config = Config.redacted(\"SECRET\")\n      assertConfig(config, [[\"SECRET\", \"a\"]], Redacted.make(\"a\"))\n    })\n\n    it(\"can wrap generic Config\", () => {\n      const config = Config.redacted(Config.integer(\"NUM\"))\n      assertConfig(config, [[\"NUM\", \"2\"]], Redacted.make(2))\n    })\n  })\n\n  describe(\"Secret\", () => {\n    describe(\"Config.secret\", () => {\n      it(\"name = undefined\", () => {\n        const config = Config.array(Config.secret(), \"ITEMS\")\n        assertConfig(config, [[\"ITEMS\", \"a\"]], [Secret.fromString(\"a\")])\n      })\n\n      it(\"name != undefined\", () => {\n        const config = Config.secret(\"SECRET\")\n        assertConfig(config, [[\"SECRET\", \"a\"]], Secret.fromString(\"a\"))\n      })\n    })\n\n    it(\"chunk constructor\", () => {\n      const secret = Secret.fromIterable(Chunk.fromIterable(\"secret\".split(\"\")))\n      assertTrue(Equal.equals(secret, Secret.fromString(\"secret\")))\n    })\n\n    it(\"value\", () => {\n      const secret = Secret.fromIterable(Chunk.fromIterable(\"secret\".split(\"\")))\n      const value = Secret.value(secret)\n      strictEqual(value, \"secret\")\n    })\n\n    it(\"toString\", () => {\n      const secret = Secret.fromString(\"secret\")\n      strictEqual(`${secret}`, \"Secret(<redacted>)\")\n    })\n\n    it(\"toJSON\", () => {\n      const secret = Secret.fromString(\"secret\")\n      strictEqual(JSON.stringify(secret), \"\\\"<redacted>\\\"\")\n    })\n\n    it(\"wipe\", () => {\n      const secret = Secret.fromString(\"secret\")\n      Secret.unsafeWipe(secret)\n      assertTrue(\n        Equal.equals(\n          Secret.value(secret),\n          Array.from({ length: \"secret\".length }, () => String.fromCharCode(0)).join(\"\")\n        )\n      )\n    })\n  })\n\n  it(\"withDescription\", () => {\n    const config = Config.number(\"NUMBER\").pipe(Config.withDescription(\"my description\"))\n    assertTrue(\"description\" in config)\n  })\n\n  describe(\"hashSet\", () => {\n    it(\"name = undefined\", () => {\n      const config = Config.array(Config.hashSet(Config.string()), \"ITEMS\")\n      assertConfig(config, [[\"ITEMS\", \"a,b,c\"]], [HashSet.make(\"a\", \"b\", \"c\")])\n    })\n\n    it(\"name != undefined\", () => {\n      const config = Config.hashSet(Config.string(), \"HASH_SET\")\n      assertConfig(config, [[\"HASH_SET\", \"a,b,c\"]], HashSet.make(\"a\", \"b\", \"c\"))\n    })\n  })\n\n  it(\"can be yielded\", () => {\n    const result = Effect.runSync(Effect.withConfigProvider(\n      Config.string(\"STRING\"),\n      ConfigProvider.fromMap(new Map([[\"STRING\", \"value\"]]))\n    ))\n    strictEqual(result, \"value\")\n  })\n\n  it(\"array nested\", () => {\n    const result = Config.array(Config.number(), \"ARRAY\").pipe(\n      Effect.withConfigProvider(\n        ConfigProvider.fromMap(new Map([[\"NESTED.ARRAY\", \"1,2,3\"]])).pipe(\n          ConfigProvider.nested(\"NESTED\")\n        )\n      ),\n      Effect.runSync\n    )\n    deepStrictEqual(result, [1, 2, 3])\n  })\n\n  it(\"ConfigError message\", () => {\n    const missingData = ConfigError.MissingData([\"PATH\"], \"missing PATH\")\n    const invalidData = ConfigError.InvalidData([\"PATH1\"], \"invalid PATH1\")\n    const andError = ConfigError.And(missingData, invalidData)\n    const orError = ConfigError.Or(missingData, invalidData)\n\n    strictEqual(\n      andError.message,\n      \"(Missing data at PATH: \\\"missing PATH\\\") and (Invalid data at PATH1: \\\"invalid PATH1\\\")\"\n    )\n    strictEqual(\n      orError.message,\n      \"(Missing data at PATH: \\\"missing PATH\\\") or (Invalid data at PATH1: \\\"invalid PATH1\\\")\"\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/ConfigProvider.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport {\n  Cause,\n  Chunk,\n  Config,\n  ConfigError,\n  ConfigProvider,\n  Effect,\n  Either,\n  Equal,\n  Exit,\n  HashMap,\n  HashSet,\n  LogLevel,\n  Option,\n  Secret\n} from \"effect\"\n\ninterface HostPort {\n  readonly host: string\n  readonly port: number\n}\n\nconst hostPortConfig: Config.Config<HostPort> = Config.all({\n  host: Config.string(\"host\"),\n  port: Config.integer(\"port\")\n})\n\ninterface HostPorts {\n  readonly hostPorts: ReadonlyArray<HostPort>\n}\n\nconst hostPortsConfig: Config.Config<HostPorts> = Config.all({\n  hostPorts: Config.array(hostPortConfig, \"hostPorts\")\n})\n\ninterface ServiceConfig {\n  readonly hostPort: HostPort\n  readonly timeout: number\n}\n\nconst serviceConfigConfig: Config.Config<ServiceConfig> = Config.all({\n  hostPort: hostPortConfig.pipe(Config.nested(\"hostPort\")),\n  timeout: Config.integer(\"timeout\")\n})\n\ninterface StockDay {\n  readonly date: Date\n  readonly open: number\n  readonly close: number\n  readonly low: number\n  readonly high: number\n  readonly volume: number\n}\n\nconst stockDayConfig: Config.Config<StockDay> = Config.all({\n  date: Config.date(\"date\"),\n  open: Config.number(\"open\"),\n  close: Config.number(\"close\"),\n  low: Config.number(\"low\"),\n  high: Config.number(\"high\"),\n  volume: Config.integer(\"volume\")\n})\n\ninterface SNP500 {\n  readonly stockDays: HashMap.HashMap<string, StockDay>\n}\n\nconst snp500Config: Config.Config<SNP500> = Config.all({\n  stockDays: Config.hashMap(stockDayConfig)\n})\n\ninterface WebScrapingTargets {\n  readonly targets: HashSet.HashSet<string>\n}\n\nconst webScrapingTargetsConfig: Config.Config<WebScrapingTargets> = Config.all({\n  targets: Config.hashSet(Config.string(), \"targets\")\n})\n\nconst webScrapingTargetsConfigWithDefault = Config.all({\n  targets: Config.chunk(Config.string()).pipe(\n    Config.withDefault(Chunk.make(\"https://effect.website2\", \"https://github.com/Effect-TS2\"))\n  )\n})\n\nconst provider = (map: Map<string, string>): ConfigProvider.ConfigProvider => {\n  return ConfigProvider.fromMap(map)\n}\n\ndescribe(\"ConfigProvider\", () => {\n  it.effect(\"flat atoms\", () =>\n    Effect.gen(function*() {\n      const map = new Map([[\"host\", \"localhost\"], [\"port\", \"8080\"]])\n      const result = yield* provider(map).load(hostPortConfig)\n      deepStrictEqual(result, {\n        host: \"localhost\",\n        port: 8080\n      })\n    }))\n\n  it.effect(\"nested atoms\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"hostPort.host\", \"localhost\"],\n        [\"hostPort.port\", \"8080\"],\n        [\"timeout\", \"1000\"]\n      ])\n      const result = yield* provider(map).load(serviceConfigConfig)\n      deepStrictEqual(result, {\n        hostPort: {\n          host: \"localhost\",\n          port: 8080\n        },\n        timeout: 1000\n      })\n    }))\n\n  it.effect(\"top-level list with same number of elements per key\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"hostPorts.host\", \"localhost,localhost,localhost\"],\n        [\"hostPorts.port\", \"8080,8080,8080\"]\n      ])\n      const result = yield* provider(map).load(hostPortsConfig)\n      deepStrictEqual(result, {\n        hostPorts: Array.from({ length: 3 }, () => ({ host: \"localhost\", port: 8080 }))\n      })\n    }))\n\n  it.effect(\"top-level missing list\", () =>\n    Effect.gen(function*() {\n      const map = new Map()\n      const result = yield* Effect.exit(provider(map).load(hostPortsConfig))\n      assertTrue(Exit.isFailure(result))\n    }))\n\n  it.effect(\"simple map\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"name\", \"Sherlock Holmes\"],\n        [\"address\", \"221B Baker Street\"]\n      ])\n      const result = yield* provider(map).load(Config.hashMap(Config.string()))\n      deepStrictEqual(\n        result,\n        HashMap.make(\n          [\"name\", \"Sherlock Holmes\"],\n          [\"address\", \"221B Baker Street\"]\n        )\n      )\n    }))\n\n  it.effect(\"top-level lists with multi-character sequence delimiters\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"hostPorts.host\", \"localhost///localhost///localhost\"],\n        [\"hostPorts.port\", \"8080///8080///8080\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map, { seqDelim: \"///\" }).load(hostPortsConfig)\n      deepStrictEqual(result, {\n        hostPorts: Array.from({ length: 3 }, () => ({ host: \"localhost\", port: 8080 }))\n      })\n    }))\n\n  it.effect(\"top-level lists with special regex multi-character sequence delimiter\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"hostPorts.host\", \"localhost|||localhost|||localhost\"],\n        [\"hostPorts.port\", \"8080|||8080|||8080\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map, { seqDelim: \"|||\" }).load(hostPortsConfig)\n      deepStrictEqual(result, {\n        hostPorts: Array.from({ length: 3 }, () => ({ host: \"localhost\", port: 8080 }))\n      })\n    }))\n\n  it.effect(\"top-level lists with special regex character sequence delimiter\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"hostPorts.host\", \"localhost*localhost*localhost\"],\n        [\"hostPorts.port\", \"8080*8080*8080\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map, { seqDelim: \"*\" }).load(hostPortsConfig)\n      deepStrictEqual(result, {\n        hostPorts: Array.from({ length: 3 }, () => ({ host: \"localhost\", port: 8080 }))\n      })\n    }))\n\n  it.effect(\"top-level list with different number of elements per key fails\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"hostPorts.host\", \"localhost\"],\n        [\"hostPorts.port\", \"8080,8080,8080\"]\n      ])\n      const result = yield* Effect.exit(provider(map).load(hostPortsConfig))\n      deepStrictEqual(\n        result,\n        Exit.fail(\n          ConfigError.MissingData(\n            [\"hostPorts\"],\n            \"The element at index 1 in a sequence at path \\\"hostPorts\\\" was missing\"\n          )\n        )\n      )\n    }))\n\n  it.effect(\"flat atoms of different types\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"date\", \"2022-10-28\"],\n        [\"open\", \"98.8\"],\n        [\"close\", \"150.0\"],\n        [\"low\", \"98.0\"],\n        [\"high\", \"151.5\"],\n        [\"volume\", \"100091990\"]\n      ])\n      const result = yield* provider(map).load(stockDayConfig)\n      deepStrictEqual(result, {\n        date: new Date(\"2022-10-28\"),\n        open: 98.8,\n        close: 150.0,\n        low: 98.0,\n        high: 151.5,\n        volume: 100091990\n      })\n    }))\n\n  it.effect(\"tables\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"Effect.date\", \"2022-10-28\"],\n        [\"Effect.open\", \"98.8\"],\n        [\"Effect.close\", \"150.0\"],\n        [\"Effect.low\", \"98.0\"],\n        [\"Effect.high\", \"151.5\"],\n        [\"Effect.volume\", \"100091990\"]\n      ])\n      const result = yield* provider(map).load(snp500Config)\n      deepStrictEqual(result, {\n        stockDays: HashMap.make([\n          \"Effect\",\n          {\n            date: new Date(\"2022-10-28\"),\n            open: 98.8,\n            close: 150.0,\n            low: 98.0,\n            high: 151.5,\n            volume: 100091990\n          }\n        ])\n      })\n    }))\n\n  it.effect(\"empty tables\", () =>\n    Effect.gen(function*() {\n      const result = yield* provider(new Map()).load(snp500Config)\n      deepStrictEqual(result, { stockDays: HashMap.empty() })\n    }))\n\n  it.effect(\"collection of atoms\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"targets\", \"https://effect.website,https://github.com/Effect-TS\"]\n      ])\n      const result = yield* provider(map).load(webScrapingTargetsConfig)\n      deepStrictEqual(result, {\n        targets: HashSet.make(\"https://effect.website\", \"https://github.com/Effect-TS\")\n      })\n    }))\n\n  it.effect(\"collection of atoms falls back to default\", () =>\n    Effect.gen(function*() {\n      const map = new Map()\n      const result = yield* provider(map).load(webScrapingTargetsConfigWithDefault)\n      deepStrictEqual(result, {\n        targets: Chunk.make(\"https://effect.website2\", \"https://github.com/Effect-TS2\")\n      })\n    }))\n\n  it.effect(\"indexed - simple\", () =>\n    Effect.gen(function*() {\n      const config = Config.array(Config.integer(), \"id\")\n      const map = new Map([\n        [\"id[0]\", \"1\"],\n        [\"id[1]\", \"2\"],\n        [\"id[2]\", \"3\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      deepStrictEqual(result, [1, 2, 3])\n    }))\n\n  it.effect(\"indexed sequence - simple with list values\", () =>\n    Effect.gen(function*() {\n      const config = Config.array(Config.array(Config.integer()), \"id\")\n      const map = new Map([\n        [\"id[0]\", \"1, 2\"],\n        [\"id[1]\", \"3, 4\"],\n        [\"id[2]\", \"5, 6\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      deepStrictEqual(result, [[1, 2], [3, 4], [5, 6]])\n    }))\n\n  it.effect(\"indexed sequence - one product type\", () =>\n    Effect.gen(function*() {\n      const config = Config.array(\n        Config.all({\n          age: Config.integer(\"age\"),\n          id: Config.integer(\"id\")\n        }),\n        \"employees\"\n      )\n      const map = new Map([\n        [\"employees[0].age\", \"1\"],\n        [\"employees[0].id\", \"1\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      deepStrictEqual(result, [{ age: 1, id: 1 }])\n    }))\n\n  it.effect(\"indexed sequence - multiple product types\", () =>\n    Effect.gen(function*() {\n      const config = Config.array(\n        Config.all({\n          age: Config.integer(\"age\"),\n          id: Config.integer(\"id\")\n        }),\n        \"employees\"\n      )\n      const map = new Map([\n        [\"employees[0].age\", \"1\"],\n        [\"employees[0].id\", \"2\"],\n        [\"employees[1].age\", \"3\"],\n        [\"employees[1].id\", \"4\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      deepStrictEqual(result, [{ age: 1, id: 2 }, { age: 3, id: 4 }])\n    }))\n\n  it.effect(\"indexed sequence - multiple product types with missing fields\", () =>\n    Effect.gen(function*() {\n      const config = Config.array(\n        Config.all({\n          age: Config.integer(\"age\"),\n          id: Config.integer(\"id\")\n        }),\n        \"employees\"\n      )\n      const map = new Map([\n        [\"employees[0].age\", \"1\"],\n        [\"employees[0].id\", \"2\"],\n        [\"employees[1].age\", \"3\"],\n        [\"employees[1]\", \"4\"]\n      ])\n      const result = yield* Effect.exit(ConfigProvider.fromMap(map).load(config))\n      assertTrue(\n        Exit.isFailure(result) &&\n          Cause.isFailType(result.effect_instruction_i0) &&\n          ConfigError.isMissingData(result.effect_instruction_i0.error) &&\n          // TODO: fix error message to not include `.[index]`\n          result.effect_instruction_i0.error.message === \"Expected employees.[1].id to exist in the provided map\" &&\n          Equal.equals(\n            Chunk.unsafeFromArray(result.effect_instruction_i0.error.path),\n            Chunk.make(\"employees\", \"[1]\", \"id\")\n          )\n      )\n    }))\n\n  it.effect(\"indexed sequence - multiple product types with optional fields\", () =>\n    Effect.gen(function*() {\n      const config = Config.array(\n        Config.all({\n          age: Config.option(Config.integer(\"age\")),\n          id: Config.integer(\"id\")\n        }),\n        \"employees\"\n      )\n      const map = new Map([\n        [\"employees[0].age\", \"1\"],\n        [\"employees[0].id\", \"2\"],\n        [\"employees[1].id\", \"4\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      deepStrictEqual(result, [{ age: Option.some(1), id: 2 }, { age: Option.none(), id: 4 }])\n    }))\n\n  it.effect(\"indexed sequence - multiple product types with sequence fields\", () =>\n    Effect.gen(function*() {\n      const config = Config.array(\n        Config.all({\n          refunds: Config.array(Config.integer(), \"refunds\"),\n          id: Config.integer(\"id\")\n        }),\n        \"employees\"\n      )\n      const map = new Map([\n        [\"employees[0].refunds\", \"1,2,3\"],\n        [\"employees[0].id\", \"0\"],\n        [\"employees[1].id\", \"1\"],\n        [\"employees[1].refunds\", \"4,5,6\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      deepStrictEqual(result, [{ refunds: [1, 2, 3], id: 0 }, { refunds: [4, 5, 6], id: 1 }])\n    }))\n\n  it.effect(\"indexed sequence - product type of indexed sequences with reusable config\", () =>\n    Effect.gen(function*() {\n      const idAndAge = Config.all({\n        id: Config.integer(\"id\"),\n        age: Config.integer(\"age\")\n      })\n      const config = Config.all({\n        employees: Config.array(idAndAge, \"employees\"),\n        students: Config.array(idAndAge, \"students\")\n      })\n      const map = new Map([\n        [\"employees[0].id\", \"0\"],\n        [\"employees[1].id\", \"1\"],\n        [\"employees[0].age\", \"10\"],\n        [\"employees[1].age\", \"11\"],\n        [\"students[0].id\", \"20\"],\n        [\"students[1].id\", \"30\"],\n        [\"students[0].age\", \"2\"],\n        [\"students[1].age\", \"3\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      deepStrictEqual(result, {\n        employees: [{ id: 0, age: 10 }, { id: 1, age: 11 }],\n        students: [{ id: 20, age: 2 }, { id: 30, age: 3 }]\n      })\n    }))\n\n  it.effect(\"indexed sequence - map of indexed sequences\", () =>\n    Effect.gen(function*() {\n      const employee = Config.all({\n        age: Config.integer(\"age\"),\n        id: Config.integer(\"id\")\n      })\n      const config = Config.hashMap(Config.array(employee, \"employees\"), \"departments\")\n      const map = new Map([\n        [\"departments.department1.employees[0].age\", \"10\"],\n        [\"departments.department1.employees[0].id\", \"0\"],\n        [\"departments.department1.employees[1].age\", \"20\"],\n        [\"departments.department1.employees[1].id\", \"1\"],\n        [\"departments.department2.employees[0].age\", \"10\"],\n        [\"departments.department2.employees[0].id\", \"0\"],\n        [\"departments.department2.employees[1].age\", \"20\"],\n        [\"departments.department2.employees[1].id\", \"1\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      const expectedEmployees = [{ age: 10, id: 0 }, { age: 20, id: 1 }]\n      deepStrictEqual(Array.from(result), [\n        [\"department1\", expectedEmployees],\n        [\"department2\", expectedEmployees]\n      ])\n    }))\n\n  it.effect(\"indexed sequence - map\", () =>\n    Effect.gen(function*() {\n      const employee = Config.hashMap(Config.integer(), \"details\")\n      const config = Config.array(employee, \"employees\")\n      const map = new Map([\n        [\"employees[0].details.age\", \"10\"],\n        [\"employees[0].details.id\", \"0\"],\n        [\"employees[1].details.age\", \"20\"],\n        [\"employees[1].details.id\", \"1\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      deepStrictEqual(result.map((table) => Array.from(table)), [\n        [[\"age\", 10], [\"id\", 0]],\n        [[\"age\", 20], [\"id\", 1]]\n      ])\n    }))\n\n  it.effect(\"indexed sequence - indexed sequences\", () =>\n    Effect.gen(function*() {\n      const employee = Config.all({\n        age: Config.integer(\"age\"),\n        id: Config.integer(\"id\")\n      })\n      const department = Config.array(employee, \"employees\")\n      const config = Config.array(department, \"departments\")\n      const map = new Map([\n        [\"departments[0].employees[0].age\", \"10\"],\n        [\"departments[0].employees[0].id\", \"0\"],\n        [\"departments[0].employees[1].age\", \"20\"],\n        [\"departments[0].employees[1].id\", \"1\"],\n        [\"departments[1].employees[0].age\", \"10\"],\n        [\"departments[1].employees[0].id\", \"0\"],\n        [\"departments[1].employees[1].age\", \"20\"],\n        [\"departments[1].employees[1].id\", \"1\"]\n      ])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      const expectedEmployees = [{ age: 10, id: 0 }, { age: 20, id: 1 }]\n      deepStrictEqual(result, [expectedEmployees, expectedEmployees])\n    }))\n\n  it.effect(\"indexed sequence - multiple product types nested\", () =>\n    Effect.gen(function*() {\n      const employee = Config.all({\n        age: Config.integer(\"age\"),\n        id: Config.integer(\"id\")\n      })\n      const config = Config.array(employee, \"employees\")\n      const map = new Map([\n        [\"parent.child.employees[0].age\", \"1\"],\n        [\"parent.child.employees[0].id\", \"2\"],\n        [\"parent.child.employees[1].age\", \"3\"],\n        [\"parent.child.employees[1].id\", \"4\"]\n      ])\n      const provider = ConfigProvider.fromMap(map).pipe(\n        ConfigProvider.nested(\"child\"),\n        ConfigProvider.nested(\"parent\")\n      )\n      const result = yield* provider.load(config)\n      deepStrictEqual(result, [{ age: 1, id: 2 }, { age: 3, id: 4 }])\n    }))\n\n  it.effect(\"indexed sequence - multiple product types unnested\", () =>\n    Effect.gen(function*() {\n      const employee = Config.all({\n        age: Config.integer(\"age\"),\n        id: Config.integer(\"id\")\n      })\n      const config = Config.array(employee, \"employees\").pipe(\n        Config.nested(\"child\"),\n        Config.nested(\"parent\")\n      )\n      const map = new Map([\n        [\"employees[0].age\", \"1\"],\n        [\"employees[0].id\", \"2\"],\n        [\"employees[1].age\", \"3\"],\n        [\"employees[1].id\", \"4\"]\n      ])\n      const provider = ConfigProvider.fromMap(map).pipe(\n        ConfigProvider.unnested(\"parent\"),\n        ConfigProvider.unnested(\"child\")\n      )\n      const result = yield* provider.load(config)\n      deepStrictEqual(result, [{ age: 1, id: 2 }, { age: 3, id: 4 }])\n    }))\n\n  it.effect(\"logLevel\", () =>\n    Effect.gen(function*() {\n      const config = Config.logLevel(\"level\")\n      const map = new Map([[\"level\", \"ERROR\"]])\n      const result = yield* ConfigProvider.fromMap(map).load(config)\n      strictEqual(result, LogLevel.Error)\n    }))\n\n  it.effect(\"accessing a non-existent key fails\", () =>\n    Effect.gen(function*() {\n      const map = new Map([\n        [\"k1.k3\", \"v\"]\n      ])\n      const config = Config.string(\"k2\").pipe(\n        Config.nested(\"k1\")\n      )\n      const result = yield* Effect.exit(provider(map).load(config))\n      deepStrictEqual(\n        result,\n        Exit.fail(\n          ConfigError.MissingData(\n            [\"k1\", \"k2\"],\n            \"Expected k1.k2 to exist in the provided map\"\n          )\n        )\n      )\n    }))\n\n  it.effect(\"values are not split unless a sequence is expected\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(new Map([[\"greeting\", \"Hello, World!\"]]))\n      const result = yield* configProvider.load(Config.string(\"greeting\"))\n      strictEqual(result, \"Hello, World!\")\n    }))\n\n  it.effect(\"constantCase\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(new Map([[\"CONSTANT_CASE\", \"value\"]])).pipe(\n        ConfigProvider.constantCase\n      )\n      const result = yield* configProvider.load(Config.string(\"constant.case\"))\n      strictEqual(result, \"value\")\n    }))\n\n  it.effect(\"mapInputPath\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(new Map([[\"KEY\", \"VALUE\"]])).pipe(\n        ConfigProvider.mapInputPath((path) => path.toUpperCase())\n      )\n      const result = yield* configProvider.load(Config.string(\"key\"))\n      strictEqual(result, \"VALUE\")\n    }))\n\n  it.effect(\"kebabCase\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(new Map([[\"kebab-case\", \"value\"]])).pipe(\n        ConfigProvider.kebabCase\n      )\n      const result = yield* configProvider.load(Config.string(\"kebabCase\"))\n      strictEqual(result, \"value\")\n    }))\n\n  it.effect(\"lowerCase\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(new Map([[\"lowercase\", \"value\"]])).pipe(\n        ConfigProvider.lowerCase\n      )\n      const result = yield* configProvider.load(Config.string(\"lowerCase\"))\n      strictEqual(result, \"value\")\n    }))\n\n  it.effect(\"nested\", () =>\n    Effect.gen(function*() {\n      const configProvider1 = ConfigProvider.fromMap(new Map([[\"nested.key\", \"value\"]]))\n      const config1 = Config.string(\"key\").pipe(Config.nested(\"nested\"))\n      const configProvider2 = ConfigProvider.fromMap(new Map([[\"nested.key\", \"value\"]])).pipe(\n        ConfigProvider.nested(\"nested\")\n      )\n      const config2 = Config.string(\"key\")\n      const result1 = yield* configProvider1.load(config1)\n      const result2 = yield* configProvider2.load(config2)\n      strictEqual(result1, \"value\")\n      strictEqual(result2, \"value\")\n    }))\n\n  it.effect(\"nested - multiple layers of nesting\", () =>\n    Effect.gen(function*() {\n      const configProvider1 = ConfigProvider.fromMap(new Map([[\"parent.child.key\", \"value\"]]))\n      const config1 = Config.string(\"key\").pipe(\n        Config.nested(\"child\"),\n        Config.nested(\"parent\")\n      )\n      const configProvider2 = ConfigProvider.fromMap(new Map([[\"parent.child.key\", \"value\"]])).pipe(\n        ConfigProvider.nested(\"child\"),\n        ConfigProvider.nested(\"parent\")\n      )\n      const config2 = Config.string(\"key\")\n      const result1 = yield* configProvider1.load(config1)\n      const result2 = yield* configProvider2.load(config2)\n      strictEqual(result1, \"value\")\n      strictEqual(result2, \"value\")\n    }))\n\n  it.effect(\"orElse - with flat data\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(\n        new Map([\n          [\"key1\", \"value1\"],\n          [\"key4\", \"value41\"]\n        ])\n      ).pipe(\n        ConfigProvider.orElse(() =>\n          ConfigProvider.fromMap(\n            new Map([\n              [\"key2\", \"value2\"],\n              [\"key4\", \"value42\"]\n            ])\n          )\n        )\n      )\n      const result1 = yield* configProvider.load(Config.string(\"key1\"))\n      const result2 = yield* configProvider.load(Config.string(\"key2\"))\n      const result31 = yield* configProvider.load(Config.option(Config.string(\"key3\")))\n      const result32 = yield* Effect.either(configProvider.load(Config.string(\"key3\")))\n      const result4 = yield* configProvider.load(Config.string(\"key4\"))\n\n      strictEqual(result1, \"value1\")\n      strictEqual(result2, \"value2\")\n      assertNone(result31)\n      deepStrictEqual(\n        result32,\n        Either.left(ConfigError.Or(\n          ConfigError.MissingData([\"key3\"], \"Expected key3 to exist in the provided map\"),\n          ConfigError.MissingData([\"key3\"], \"Expected key3 to exist in the provided map\")\n        ))\n      )\n      strictEqual(result4, \"value41\")\n    }))\n\n  it.effect(\"orElse - with indexed sequences\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(\n        new Map([\n          [\"parent1.child.employees[0].age\", \"1\"],\n          [\"parent1.child.employees[0].id\", \"2\"],\n          [\"parent1.child.employees[1].age\", \"3\"],\n          [\"parent1.child.employees[1].id\", \"4\"]\n        ])\n      ).pipe(\n        ConfigProvider.orElse(() =>\n          ConfigProvider.fromMap(\n            new Map([\n              [\"parent1.child.employees[2].age\", \"5\"],\n              [\"parent1.child.employees[2].id\", \"6\"],\n              [\"parent2.child.employees[0].age\", \"11\"],\n              [\"parent2.child.employees[0].id\", \"21\"],\n              [\"parent2.child.employees[1].age\", \"31\"],\n              [\"parent2.child.employees[1].id\", \"41\"]\n            ])\n          )\n        )\n      )\n\n      const product = Config.zip(Config.integer(\"age\"), Config.integer(\"id\"))\n      const arrayConfig = Config.array(product, \"employees\")\n      const config1 = arrayConfig.pipe(Config.nested(\"child\"), Config.nested(\"parent1\"))\n      const config2 = arrayConfig.pipe(Config.nested(\"child\"), Config.nested(\"parent2\"))\n\n      const result1 = yield* configProvider.load(config1)\n      const result2 = yield* configProvider.load(config2)\n\n      deepStrictEqual(result1, [[1, 2], [3, 4], [5, 6]])\n      deepStrictEqual(result2, [[11, 21], [31, 41]])\n    }))\n\n  it.effect(\"orElse - with indexed sequences and each provider unnested\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(\n        new Map([\n          [\"employees[0].age\", \"1\"],\n          [\"employees[0].id\", \"2\"],\n          [\"employees[1].age\", \"3\"],\n          [\"employees[1].id\", \"4\"]\n        ])\n      ).pipe(\n        ConfigProvider.unnested(\"parent1\"),\n        ConfigProvider.unnested(\"child\"),\n        ConfigProvider.orElse(() =>\n          ConfigProvider.fromMap(\n            new Map([\n              [\"employees[0].age\", \"11\"],\n              [\"employees[0].id\", \"21\"],\n              [\"employees[1].age\", \"31\"],\n              [\"employees[1].id\", \"41\"]\n            ])\n          ).pipe(\n            ConfigProvider.unnested(\"parent2\"),\n            ConfigProvider.unnested(\"child\")\n          )\n        )\n      )\n\n      const product = Config.zip(Config.integer(\"age\"), Config.integer(\"id\"))\n      const arrayConfig = Config.array(product, \"employees\")\n      const config1 = arrayConfig.pipe(Config.nested(\"child\"), Config.nested(\"parent1\"))\n      const config2 = arrayConfig.pipe(Config.nested(\"child\"), Config.nested(\"parent2\"))\n      const config3 = arrayConfig.pipe(Config.nested(\"child\"), Config.nested(\"parent3\"))\n\n      const result1 = yield* configProvider.load(config1)\n      const result2 = yield* configProvider.load(config2)\n      const result3 = yield* Effect.either(configProvider.load(config3))\n\n      deepStrictEqual(result1, [[1, 2], [3, 4]])\n      deepStrictEqual(result2, [[11, 21], [31, 41]])\n      deepStrictEqual(\n        result3,\n        Either.left(ConfigError.And(\n          ConfigError.MissingData(\n            [\"parent3\", \"child\", \"employees\"],\n            \"Expected parent1 to be in path in ConfigProvider#unnested\"\n          ),\n          ConfigError.MissingData(\n            [\"parent3\", \"child\", \"employees\"],\n            \"Expected parent2 to be in path in ConfigProvider#unnested\"\n          )\n        ))\n      )\n    }))\n\n  it.effect(\"orElse - with index sequences and combined provider unnested\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(\n        new Map([\n          [\"employees[0].age\", \"1\"],\n          [\"employees[0].id\", \"2\"]\n        ])\n      ).pipe(\n        ConfigProvider.orElse(() =>\n          ConfigProvider.fromMap(\n            new Map([\n              [\"employees[1].age\", \"3\"],\n              [\"employees[1].id\", \"4\"]\n            ])\n          )\n        ),\n        ConfigProvider.unnested(\"parent1\"),\n        ConfigProvider.unnested(\"child\")\n      )\n\n      const product = Config.zip(Config.integer(\"age\"), Config.integer(\"id\"))\n      const arrayConfig = Config.array(product, \"employees\")\n      const config = arrayConfig.pipe(Config.nested(\"child\"), Config.nested(\"parent1\"))\n\n      const result = yield* configProvider.load(config)\n\n      deepStrictEqual(result, [[1, 2], [3, 4]])\n    }))\n\n  it.effect(\"secret\", () =>\n    Effect.gen(function*() {\n      const value = \"Hello, World!\"\n      const configProvider = ConfigProvider.fromMap(new Map([[\"greeting\", value]]))\n      const result = yield* configProvider.load(Config.secret(\"greeting\"))\n      deepStrictEqual(result, Secret.make(value.split(\"\").map((c) => c.charCodeAt(0))))\n    }))\n\n  it.effect(\"snakeCase\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(new Map([[\"snake_case\", \"value\"]])).pipe(\n        ConfigProvider.snakeCase\n      )\n      const result = yield* configProvider.load(Config.string(\"snakeCase\"))\n      strictEqual(result, \"value\")\n    }))\n\n  it.effect(\"unnested\", () =>\n    Effect.gen(function*() {\n      const configProvider1 = ConfigProvider.fromMap(new Map([[\"key\", \"value\"]]))\n      const config1 = Config.string(\"key\")\n      const configProvider2 = ConfigProvider.fromMap(new Map([[\"key\", \"value\"]])).pipe(\n        ConfigProvider.unnested(\"nested\")\n      )\n      const config2 = Config.string(\"key\").pipe(Config.nested(\"nested\"))\n      const result1 = yield* configProvider1.load(config1)\n      const result2 = yield* configProvider2.load(config2)\n      strictEqual(result1, \"value\")\n      strictEqual(result2, \"value\")\n    }))\n\n  it.effect(\"unnested - multiple layers of nesting\", () =>\n    Effect.gen(function*() {\n      const configProvider1 = ConfigProvider.fromMap(new Map([[\"key\", \"value\"]]))\n      const config1 = Config.string(\"key\")\n      const configProvider2 = ConfigProvider.fromMap(new Map([[\"key\", \"value\"]])).pipe(\n        ConfigProvider.unnested(\"parent\"),\n        ConfigProvider.unnested(\"child\")\n      )\n      const config2 = Config.string(\"key\").pipe(\n        Config.nested(\"child\"),\n        Config.nested(\"parent\")\n      )\n      const result1 = yield* configProvider1.load(config1)\n      const result2 = yield* configProvider2.load(config2)\n      strictEqual(result1, \"value\")\n      strictEqual(result2, \"value\")\n    }))\n\n  it.effect(\"unnested - failure\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(new Map([[\"key\", \"value\"]])).pipe(\n        ConfigProvider.unnested(\"nested\")\n      )\n      const config = Config.string(\"key\")\n      const result = yield* Effect.exit(configProvider.load(config))\n      const error = ConfigError.MissingData(\n        [\"key\"],\n        \"Expected nested to be in path in ConfigProvider#unnested\"\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"upperCase\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(new Map([[\"UPPERCASE\", \"value\"]])).pipe(\n        ConfigProvider.upperCase\n      )\n      const result = yield* configProvider.load(Config.string(\"upperCase\"))\n      strictEqual(result, \"value\")\n    }))\n\n  it.effect(\"within\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(new Map([[\"nesting1.key1\", \"value1\"], [\"nesting2.KEY2\", \"value2\"]]))\n        .pipe(\n          ConfigProvider.within([\"nesting2\"], ConfigProvider.mapInputPath((s) => s.toUpperCase()))\n        )\n      const config = Config.string(\"key1\").pipe(\n        Config.nested(\"nesting1\"),\n        Config.zip(\n          Config.string(\"key2\").pipe(\n            Config.nested(\"nesting2\")\n          )\n        )\n      )\n      const result = yield* configProvider.load(config)\n      deepStrictEqual(result, [\"value1\", \"value2\"])\n    }))\n\n  it.effect(\"within - multiple layers of nesting\", () =>\n    Effect.gen(function*() {\n      const configProvider = ConfigProvider.fromMap(\n        new Map([[\"nesting1.key1\", \"value1\"], [\"nesting2.nesting3.KEY2\", \"value2\"]])\n      ).pipe(\n        ConfigProvider.within([\"nesting2\", \"nesting3\"], ConfigProvider.mapInputPath((s) => s.toUpperCase()))\n      )\n      const config = Config.string(\"key1\").pipe(\n        Config.nested(\"nesting1\"),\n        Config.zip(\n          Config.string(\"key2\").pipe(\n            Config.nested(\"nesting3\"),\n            Config.nested(\"nesting2\")\n          )\n        )\n      )\n      const result = yield* configProvider.load(config)\n      deepStrictEqual(result, [\"value1\", \"value2\"])\n    }))\n\n  it.effect(\"fromJson - should load configs from flat JSON\", () =>\n    Effect.gen(function*() {\n      const result = yield* ConfigProvider.fromJson({\n        host: \"localhost\",\n        port: 8080\n      }).load(hostPortConfig)\n      deepStrictEqual(result, {\n        host: \"localhost\",\n        port: 8080\n      })\n    }))\n\n  it.effect(\"fromJson - should load configs from nested JSON\", () =>\n    Effect.gen(function*() {\n      const result = yield* ConfigProvider.fromJson({\n        hostPorts: [{\n          host: \"localhost\",\n          port: 8080\n        }, {\n          host: \"localhost\",\n          port: 8080\n        }, {\n          host: \"localhost\",\n          port: 8080\n        }]\n      }).load(hostPortsConfig)\n      deepStrictEqual(result, {\n        hostPorts: Array.from({ length: 3 }, () => ({ host: \"localhost\", port: 8080 }))\n      })\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Context.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertInclude,\n  assertInstanceOf,\n  assertMatch,\n  assertNone,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { Context, Differ, Option, pipe } from \"effect\"\n\ninterface A {\n  a: number\n}\nconst A = Context.GenericTag<A>(\"A\")\n\ninterface B {\n  b: number\n}\nconst B = Context.GenericTag<B>(\"B\")\n\ninterface C {\n  c: number\n}\nconst C = Context.GenericTag<C>(\"C\")\n\nclass D extends Context.Tag(\"D\")<D, { readonly d: number }>() {}\n\nclass E extends Context.Reference<E>()(\"E\", {\n  defaultValue: () => ({ e: 0 })\n}) {}\n\ndescribe(\"Context\", () => {\n  it(\"error messages\", () => {\n    throws(() => {\n      Context.unsafeGet(Context.empty(), A)\n    }, (e) => {\n      assertInstanceOf(e, Error)\n      assertInclude(e.message, \"Service not found: A\")\n    })\n    throws(() => {\n      Context.get(Context.empty(), A as never)\n    }, (e) => {\n      assertInstanceOf(e, Error)\n      assertInclude(e.message, \"Service not found: A\")\n    })\n    throws(() => {\n      Context.unsafeGet(Context.empty(), C)\n    }, (e) => {\n      assertInstanceOf(e, Error)\n      assertInclude(e.message, \"Service not found: C\")\n    })\n    throws(() => {\n      Context.get(Context.empty(), C as never)\n    }, (e) => {\n      assertInstanceOf(e, Error)\n      assertInclude(e.message, \"Service not found: C\")\n    })\n    if (typeof window === \"undefined\") {\n      throws(\n        () => {\n          Context.get(Context.empty(), C as never)\n        },\n        (e) => {\n          assertInstanceOf(e, Error)\n          assertMatch(e.message, /Service not found: C \\(defined at (.*)Context.test.ts:29:19\\)/)\n        }\n      )\n      throws(\n        () => {\n          Context.get(Context.empty(), D as never)\n        },\n        (e) => {\n          assertInstanceOf(e, Error)\n          assertMatch(e.message, /Service not found: D \\(defined at (.*)Context.test.ts:31:32\\)/)\n        }\n      )\n    }\n  })\n\n  it(\"Tag.toJson()\", () => {\n    const json: any = A.toJSON()\n    strictEqual(json[\"_id\"], \"Tag\")\n    strictEqual(json[\"key\"], \"A\")\n    strictEqual(typeof json[\"stack\"], \"string\")\n  })\n\n  it(\"TagClass.toJson()\", () => {\n    const json: any = D.toJSON()\n    strictEqual(json[\"_id\"], \"Tag\")\n    strictEqual(json[\"key\"], \"D\")\n    strictEqual(typeof json[\"stack\"], \"string\")\n  })\n\n  it(\"Context.toJson()\", () => {\n    const json: any = Context.empty().toJSON()\n    strictEqual(json[\"_id\"], \"Context\")\n    deepStrictEqual(json[\"services\"], [])\n  })\n\n  it(\"aliased tags\", () => {\n    interface Foo {\n      readonly _tag: \"Foo\"\n    }\n    interface Bar {\n      readonly _tag: \"Bar\"\n    }\n    interface FooBar {\n      readonly FooBar: unique symbol\n    }\n    const Service = Context.GenericTag<FooBar, Foo | Bar>(\"FooBar\")\n    const context = Context.make(Service, { _tag: \"Foo\" }).pipe(\n      Context.add(Service, { _tag: \"Foo\" })\n    )\n    deepStrictEqual(Context.get(context, Service), { _tag: \"Foo\" })\n  })\n\n  it(\"adds and retrieve services\", () => {\n    const Services = pipe(\n      Context.make(A, { a: 0 }),\n      Context.add(B, { b: 1 }),\n      Context.add(D, { d: 2 })\n    )\n\n    deepStrictEqual(Context.get(Services, A), { a: 0 })\n    assertSome(pipe(Services, Context.getOption(B)), { b: 1 })\n    deepStrictEqual(pipe(Services, Context.get(D)), { d: 2 })\n    assertNone(pipe(Services, Context.getOption(C)))\n    deepStrictEqual(pipe(Services, Context.get(E)), { e: 0 })\n\n    throws(() => {\n      pipe(\n        Services,\n        Context.unsafeGet(C)\n      )\n    }, (e) => {\n      assertInstanceOf(e, Error)\n      assertInclude(e.message, \"Service not found: C\")\n    })\n  })\n\n  it(\"picks services in env and merges\", () => {\n    const env = pipe(\n      Context.empty(),\n      Context.add(A, { a: 0 }),\n      Context.merge(pipe(\n        Context.empty(),\n        Context.add(B, { b: 1 }),\n        Context.add(C, { c: 2 })\n      ))\n    )\n\n    const pruned = pipe(\n      env,\n      Context.pick(A, B)\n    )\n\n    deepStrictEqual(pipe(pruned, Context.get(A)), { a: 0 })\n    assertSome(pipe(pruned, Context.getOption(B)), { b: 1 })\n    assertNone(pipe(pruned, Context.getOption(C)))\n    assertSome(pipe(env, Context.getOption(C)), { c: 2 })\n  })\n\n  it(\"omits services from env\", () => {\n    const env = pipe(\n      Context.empty(),\n      Context.add(A, { a: 0 }),\n      Context.merge(pipe(\n        Context.empty(),\n        Context.add(B, { b: 1 }),\n        Context.add(C, { c: 2 })\n      ))\n    )\n\n    const pruned = pipe(\n      env,\n      Context.omit(A, B)\n    )\n\n    assertNone(pipe(pruned, Context.getOption(A)))\n    deepStrictEqual(pipe(env, Context.get(C)), { c: 2 })\n  })\n\n  it(\"applies a patch to the environment\", () => {\n    const a: A = { a: 0 }\n    const b: B = { b: 1 }\n    const c: C = { c: 2 }\n    const oldEnv = pipe(\n      Context.empty(),\n      Context.add(A, a),\n      Context.add(B, b),\n      Context.add(C, c)\n    ) as Context.Context<A | B | C>\n    const newEnv = pipe(\n      Context.empty(),\n      Context.add(A, a),\n      Context.add(B, { b: 3 })\n    ) as Context.Context<A | B | C>\n    const differ = Differ.environment<A | B | C>()\n    const patch = differ.diff(oldEnv, newEnv)\n    const result = differ.patch(patch, oldEnv)\n\n    assertTrue(Option.isSome(Context.getOption(A)(result)))\n    assertTrue(Option.isSome(Context.getOption(B)(result)))\n    assertTrue(Option.isNone(Context.getOption(C)(result)))\n    strictEqual(pipe(result, Context.get(B)).b, 3)\n  })\n\n  it(\"creates a proper diff\", () => {\n    const a: A = { a: 0 }\n    const b: B = { b: 1 }\n    const c: C = { c: 2 }\n    const oldEnv = pipe(\n      Context.empty(),\n      Context.add(A, a),\n      Context.add(B, b),\n      Context.add(C, c)\n    ) as Context.Context<A | B | C>\n    const newEnv = pipe(\n      Context.empty(),\n      Context.add(A, a),\n      Context.add(B, { b: 3 })\n    ) as Context.Context<A | B | C>\n    const differ = Differ.environment<A | B | C>()\n    const result: any = differ.diff(oldEnv, newEnv)\n\n    strictEqual(result.first._tag, \"AndThen\")\n    strictEqual(result.first.first._tag, \"Empty\")\n    strictEqual(result.first.second._tag, \"UpdateService\")\n    strictEqual(result.first.second.key, B.key)\n    strictEqual(result.second._tag, \"RemoveService\")\n    strictEqual(result.second.key, C.key)\n  })\n\n  it(\"pipe()\", () => {\n    const result = Context.empty().pipe(Context.add(A, { a: 0 }))\n    deepStrictEqual(result.pipe(Context.get(A)), { a: 0 })\n  })\n\n  it(\"tag pipe\", () => {\n    const result = A.pipe((tag) => Context.make(tag, { a: 0 }))\n    deepStrictEqual(result.pipe(Context.get(A)), { a: 0 })\n  })\n\n  it(\"mergeAll\", () => {\n    const env = Context.mergeAll(\n      Context.make(A, { a: 0 }),\n      Context.make(B, { b: 1 }),\n      Context.make(C, { c: 2 })\n    )\n\n    const pruned = pipe(\n      env,\n      Context.pick(A, B)\n    )\n\n    deepStrictEqual(pipe(pruned, Context.get(A)), { a: 0 })\n    assertSome(pipe(pruned, Context.getOption(B)), { b: 1 })\n    assertNone(pipe(pruned, Context.getOption(C)))\n    assertSome(pipe(env, Context.getOption(C)), { c: 2 })\n  })\n\n  it(\"isContext\", () => {\n    assertTrue(Context.isContext(Context.empty()))\n    assertFalse(Context.isContext(null))\n  })\n\n  it(\"isTag\", () => {\n    assertTrue(Context.isTag(Context.GenericTag(\"Demo\")))\n    assertFalse(Context.isContext(null))\n  })\n\n  it(\"isReference\", () => {\n    assertTrue(Context.isTag(E))\n    assertTrue(Context.isReference(E))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Cron.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, throws } from \"@effect/vitest/utils\"\nimport { Cron, DateTime, Either, Equal, Option } from \"effect\"\n\nconst match = (input: Cron.Cron | string, date: DateTime.DateTime.Input) =>\n  Cron.match(Cron.isCron(input) ? input : Cron.unsafeParse(input), date)\n\nconst next = (input: Cron.Cron | string, after?: DateTime.DateTime.Input) =>\n  Cron.next(Cron.isCron(input) ? input : Cron.unsafeParse(input), after)\n\nconst prev = (input: Cron.Cron | string, after?: DateTime.DateTime.Input) =>\n  Cron.prev(Cron.isCron(input) ? input : Cron.unsafeParse(input), after)\n\ndescribe(\"Cron\", () => {\n  it(\"parse\", () => {\n    // At 04:00 on every day-of-month from 8 through 14.\n    deepStrictEqual(\n      Cron.parse(\"0 4 8-14 * 0-6\"),\n      Either.right(Cron.make({\n        minutes: [0],\n        hours: [4],\n        days: [8, 9, 10, 11, 12, 13, 14],\n        months: [],\n        weekdays: []\n      }))\n    )\n    // At 00:00 on day-of-month 1 and 15 and on Wednesday.\n    deepStrictEqual(\n      Cron.parse(\"0 0 1,15 * 3\"),\n      Either.right(Cron.make({\n        minutes: [0],\n        hours: [0],\n        days: [1, 15],\n        months: [],\n        weekdays: [3]\n      }))\n    )\n    // At 00:00 on day-of-month 1 and 15 and on Wednesday.\n    deepStrictEqual(\n      Cron.parse(\"23 0-20/2 * * *\"),\n      Either.right(Cron.make({\n        minutes: [23],\n        hours: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20],\n        days: [],\n        months: [],\n        weekdays: []\n      }))\n    )\n  })\n\n  it(\"unsafeParse\", () => {\n    throws(\n      () => Cron.unsafeParse(\"\"),\n      new Cron.ParseError({ message: \"Invalid number of segments in cron expression\", input: \"\" })\n    )\n    throws(\n      () => Cron.unsafeParse(\"0 0 4 8-14 * *\", \"\"),\n      new Cron.ParseError({ message: \"Invalid time zone in cron expression\", input: \"\" })\n    )\n  })\n\n  it(\"match\", () => {\n    assertTrue(match(\"5 0 * 8 *\", new Date(\"2024-08-01 00:05:00\")))\n    assertFalse(match(\"5 0 * 8 *\", new Date(\"2024-09-01 00:05:00\")))\n    assertFalse(match(\"5 0 * 8 *\", new Date(\"2024-08-01 01:05:00\")))\n\n    assertTrue(match(\"15 14 1 * *\", new Date(\"2024-02-01 14:15:00\")))\n    assertFalse(match(\"15 14 1 * *\", new Date(\"2024-02-01 15:15:00\")))\n    assertFalse(match(\"15 14 1 * *\", new Date(\"2024-02-02 14:15:00\")))\n\n    assertTrue(match(\"23 0-20/2 * * 0\", new Date(\"2024-01-07 00:23:00\")))\n    assertFalse(match(\"23 0-20/2 * * 0\", new Date(\"2024-01-07 03:23:00\")))\n    assertFalse(match(\"23 0-20/2 * * 0\", new Date(\"2024-01-08 00:23:00\")))\n\n    assertTrue(match(\"5 4 * * SUN\", new Date(\"2024-01-07 04:05:00\")))\n    assertFalse(match(\"5 4 * * SUN\", new Date(\"2024-01-08 04:05:00\")))\n    assertFalse(match(\"5 4 * * SUN\", new Date(\"2025-01-07 04:05:00\")))\n\n    assertTrue(match(\"5 4 * DEC SUN\", new Date(\"2024-12-01 04:05:00\")))\n    assertFalse(match(\"5 4 * DEC SUN\", new Date(\"2024-12-01 04:06:00\")))\n    assertFalse(match(\"5 4 * DEC SUN\", new Date(\"2024-12-02 04:05:00\")))\n\n    assertTrue(match(\"5 4 * * SUN\", new Date(\"2024-01-07 04:05:00\")))\n    assertFalse(match(\"5 4 * * SUN\", new Date(\"2024-01-08 04:05:00\")))\n    assertFalse(match(\"5 4 * * SUN\", new Date(\"2025-01-07 04:05:00\")))\n\n    assertTrue(match(\"42 5 0 * 8 *\", new Date(\"2024-08-01 00:05:42\")))\n    assertFalse(match(\"42 5 0 * 8 *\", new Date(\"2024-09-01 00:05:42\")))\n    assertFalse(match(\"42 5 0 * 8 *\", new Date(\"2024-08-01 01:05:42\")))\n\n    const london = DateTime.zoneUnsafeMakeNamed(\"Europe/London\")\n    const londonTime = DateTime.unsafeMakeZoned(\"2024-06-01 14:15:00Z\", {\n      timeZone: london,\n      adjustForTimeZone: true\n    })\n\n    const amsterdam = DateTime.zoneUnsafeMakeNamed(\"Europe/Amsterdam\")\n    const amsterdamTime = DateTime.unsafeMakeZoned(\"2024-06-01 15:15:00Z\", {\n      timeZone: amsterdam,\n      adjustForTimeZone: true\n    })\n\n    assertTrue(match(Cron.unsafeParse(\"15 14 1 * *\", london), londonTime))\n    assertTrue(match(Cron.unsafeParse(\"15 14 1 * *\", london), amsterdamTime))\n  })\n\n  it(\"next\", () => {\n    const after = new Date(\"2024-01-04 16:21:00\")\n    deepStrictEqual(next(\"5 0 8 2 *\", after), new Date(\"2024-02-08 00:05:00\"))\n    deepStrictEqual(next(\"15 14 1 * *\", after), new Date(\"2024-02-01 14:15:00\"))\n    deepStrictEqual(next(\"23 0-20/2 * * 0\", after), new Date(\"2024-01-07 00:23:00\"))\n    deepStrictEqual(next(\"5 4 * * SUN\", after), new Date(\"2024-01-07 04:05:00\"))\n    deepStrictEqual(next(\"5 4 * DEC SUN\", after), new Date(\"2024-12-01 04:05:00\"))\n    deepStrictEqual(next(\"30 5 0 8 2 *\", after), new Date(\"2024-02-08 00:05:30\"))\n\n    const london = DateTime.zoneUnsafeMakeNamed(\"Europe/London\")\n    const londonTime = DateTime.unsafeMakeZoned(\"2024-02-08 00:05:00Z\", {\n      timeZone: london,\n      adjustForTimeZone: true\n    })\n\n    const amsterdam = DateTime.zoneUnsafeMakeNamed(\"Europe/Amsterdam\")\n    const amsterdamTime = DateTime.unsafeMakeZoned(\"2024-02-08 01:05:00Z\", {\n      timeZone: amsterdam,\n      adjustForTimeZone: true\n    })\n\n    deepStrictEqual(next(Cron.unsafeParse(\"5 0 8 2 *\", london), after), DateTime.toDateUtc(londonTime))\n    deepStrictEqual(next(Cron.unsafeParse(\"5 0 8 2 *\", london), after), DateTime.toDateUtc(amsterdamTime))\n  })\n\n  it(\"prev\", () => {\n    const utc = DateTime.zoneUnsafeMakeNamed(\"UTC\")\n    const before = new Date(\"2024-01-04T16:21:00Z\")\n    deepStrictEqual(prev(Cron.unsafeParse(\"5 0 8 2 *\", utc), before), new Date(\"2023-02-08T00:05:00.000Z\"))\n    deepStrictEqual(prev(Cron.unsafeParse(\"15 14 1 * *\", utc), before), new Date(\"2024-01-01T14:15:00.000Z\"))\n    deepStrictEqual(prev(Cron.unsafeParse(\"23 0-20/2 * * * 0\", utc), before), new Date(\"2023-12-31T23:20:23.000Z\"))\n    deepStrictEqual(prev(Cron.unsafeParse(\"5 4 * * SUN\", utc), before), new Date(\"2023-12-31T04:05:00.000Z\"))\n    deepStrictEqual(prev(Cron.unsafeParse(\"5 4 * DEC SUN\", utc), before), new Date(\"2023-12-31T04:05:00.000Z\"))\n    deepStrictEqual(prev(Cron.unsafeParse(\"30 5 0 8 2 *\", utc), before), new Date(\"2023-02-08T00:05:30.000Z\"))\n\n    const wednesday = new Date(\"2025-10-22T01:00:00.000Z\")\n    deepStrictEqual(prev(Cron.unsafeParse(\"0 1 * * MON\", utc), wednesday), new Date(\"2025-10-20T01:00:00.000Z\"))\n    deepStrictEqual(next(Cron.unsafeParse(\"0 1 * * MON\", utc), wednesday), new Date(\"2025-10-27T01:00:00.000Z\"))\n    deepStrictEqual(prev(Cron.unsafeParse(\"0 1 * * TUE\", utc), wednesday), new Date(\"2025-10-21T01:00:00.000Z\"))\n    deepStrictEqual(next(Cron.unsafeParse(\"0 1 * * TUE\", utc), wednesday), new Date(\"2025-10-28T01:00:00.000Z\"))\n  })\n\n  it(\"returns the latest second when rolling back a minute\", () => {\n    const utc = DateTime.zoneUnsafeMakeNamed(\"UTC\")\n    const expr = Cron.unsafeParse(\"10,30 * * * * *\", utc)\n    const before = new Date(\"2024-01-01T00:00:05.000Z\")\n    deepStrictEqual(prev(expr, before), new Date(\"2023-12-31T23:59:30.000Z\"))\n  })\n\n  it(\"forward and reverse sequences stay aligned\", () => {\n    const cases = [\n      [\"5 2 * * 1\", \"2020-01-01T00:00:01Z\", \"2021-01-01T00:00:01Z\"],\n      [\"0 12 1 * *\", \"2020-01-01T00:00:01Z\", \"2021-01-01T00:00:01Z\"],\n      [\"10,30 * * * * *\", \"2024-01-01T00:00:00Z\", \"2024-01-02T00:00:00Z\"]\n    ] as const\n\n    const gather = (\n      generator: IterableIterator<Date>,\n      lower: Date,\n      upper: Date,\n      direction: \"forward\" | \"reverse\"\n    ) => {\n      const res: Array<Date> = []\n      for (const date of generator) {\n        if (direction === \"forward\" ? date >= upper : date <= lower) {\n          break\n        }\n        res.push(date)\n      }\n      return res\n    }\n\n    for (const [expr, lowerStr, upperStr] of cases) {\n      const lower = new Date(lowerStr)\n      const upper = new Date(upperStr)\n      const cron = Cron.unsafeParse(expr, DateTime.zoneUnsafeMakeNamed(\"UTC\"))\n\n      const forward = gather(Cron.sequence(cron, lower), lower, upper, \"forward\")\n      const reverse = gather(Cron.sequenceReverse(cron, upper), lower, upper, \"reverse\").reverse()\n\n      deepStrictEqual(forward, reverse)\n    }\n  })\n\n  it(\"prev prefers the latest matching day within the previous month\", () => {\n    const cron = Cron.unsafeParse(\"0 0 8 5,20 * *\", DateTime.zoneUnsafeMakeNamed(\"UTC\"))\n    const before = new Date(\"2024-06-03T00:00:00.000Z\")\n    deepStrictEqual(prev(cron, before), new Date(\"2024-05-20T08:00:00.000Z\"))\n  })\n\n  it(\"prev wraps weekday using the last allowed value\", () => {\n    const cron = Cron.unsafeParse(\"0 1 * * MON,FRI\", DateTime.zoneUnsafeMakeNamed(\"UTC\"))\n    const sunday = new Date(\"2025-10-19T12:00:00.000Z\") // Sunday\n    deepStrictEqual(prev(cron, sunday), new Date(\"2025-10-17T01:00:00.000Z\")) // Friday\n  })\n\n  it(\"prev chooses the later occurrence in DST fall-back\", () => {\n    const make = (s: string) => DateTime.makeZonedFromString(s).pipe(Option.getOrThrow)\n    const tz = \"Europe/Berlin\"\n    const cron = Cron.unsafeParse(\"0 30 2 * * *\", tz)\n    const before = make(\"2024-10-27T03:30:00.000+01:00[Europe/Berlin]\")\n    const result = DateTime.unsafeMakeZoned(prev(cron, before), { timeZone: tz })\n    deepStrictEqual(result.pipe(DateTime.formatIsoZoned), \"2024-10-27T02:30:00.000+02:00[Europe/Berlin]\")\n  })\n\n  it(\"prev respects combined day-of-month and weekday constraints\", () => {\n    const tz = DateTime.zoneUnsafeMakeNamed(\"UTC\")\n    const cron = Cron.unsafeParse(\"0 0 9 1,15 * MON\", tz)\n    const before = new Date(\"2024-04-02T12:00:00.000Z\") // Tue after a matching Monday the 1st\n    deepStrictEqual(prev(cron, before), new Date(\"2024-04-01T09:00:00.000Z\"))\n  })\n\n  it(\"prev handles step expressions across day boundary\", () => {\n    const tz = DateTime.zoneUnsafeMakeNamed(\"UTC\")\n    const cron = Cron.unsafeParse(\"0 */7 8-10 * * *\", tz)\n    const before = new Date(\"2024-01-01T08:01:00.000Z\")\n    deepStrictEqual(prev(cron, before), new Date(\"2024-01-01T08:00:00.000Z\"))\n  })\n\n  it(\"prev works with fixed offset time zones\", () => {\n    const offset = DateTime.zoneMakeOffset(2 * 60 * 60 * 1000) // UTC+2\n    const cron = Cron.unsafeParse(\"0 0 10 * * *\", offset)\n    const before = new Date(\"2024-05-01T07:00:00.000Z\") // before 10:00 local (08:00Z)\n    deepStrictEqual(prev(cron, before), new Date(\"2024-04-30T08:00:00.000Z\"))\n  })\n\n  it(\"prev wraps across year boundary\", () => {\n    const tz = DateTime.zoneUnsafeMakeNamed(\"UTC\")\n    const cron = Cron.unsafeParse(\"0 0 1 1 *\", tz)\n    const from = new Date(\"2024-01-01T00:00:00.000Z\")\n    deepStrictEqual(prev(cron, from), new Date(\"2023-01-01T00:00:00.000Z\"))\n  })\n\n  it(\"prev handles day 31 skipping months without it\", () => {\n    const tz = DateTime.zoneUnsafeMakeNamed(\"UTC\")\n    const cron = Cron.unsafeParse(\"0 0 31 * *\", tz)\n    const from = new Date(\"2024-03-01T00:00:00.000Z\")\n    // Should skip Feb (no day 31) and go to Jan 31\n    deepStrictEqual(prev(cron, from), new Date(\"2024-01-31T00:00:00.000Z\"))\n  })\n\n  it(\"prev clamps to the last valid day when rolling back a month with only month constraints\", () => {\n    const tz = DateTime.zoneUnsafeMakeNamed(\"UTC\")\n    const cron = Cron.unsafeParse(\"0 0 0 * FEB *\", tz)\n    const from = new Date(\"2024-03-31T12:00:00.000Z\")\n    deepStrictEqual(prev(cron, from), new Date(\"2024-02-29T00:00:00.000Z\"))\n  })\n\n  it(\"prev with multiple months specified\", () => {\n    const tz = DateTime.zoneUnsafeMakeNamed(\"UTC\")\n    const cron = Cron.unsafeParse(\"0 0 15 1,4,7,10 *\", tz) // Quarterly on 15th\n    const from = new Date(\"2024-05-01T00:00:00.000Z\")\n    deepStrictEqual(prev(cron, from), new Date(\"2024-04-15T00:00:00.000Z\"))\n  })\n\n  it(\"sequence\", () => {\n    const start = new Date(\"2024-01-01 00:00:00\")\n    const generator = Cron.sequence(Cron.unsafeParse(\"23 0-20/2 * * 0\"), start)\n    deepStrictEqual(generator.next().value, new Date(\"2024-01-07 00:23:00\"))\n    deepStrictEqual(generator.next().value, new Date(\"2024-01-07 02:23:00\"))\n    deepStrictEqual(generator.next().value, new Date(\"2024-01-07 04:23:00\"))\n    deepStrictEqual(generator.next().value, new Date(\"2024-01-07 06:23:00\"))\n    deepStrictEqual(generator.next().value, new Date(\"2024-01-07 08:23:00\"))\n  })\n\n  it(\"sequenceReverse\", () => {\n    const start = new Date(\"2024-01-01 00:00:00Z\")\n    const utc = DateTime.zoneUnsafeMakeNamed(\"UTC\")\n    const generator = Cron.sequenceReverse(Cron.unsafeParse(\"23 0-20/2 * * 0\", utc), start)\n    deepStrictEqual(generator.next().value, new Date(\"2023-12-31 20:23:00Z\"))\n    deepStrictEqual(generator.next().value, new Date(\"2023-12-31 18:23:00Z\"))\n    deepStrictEqual(generator.next().value, new Date(\"2023-12-31 16:23:00Z\"))\n    deepStrictEqual(generator.next().value, new Date(\"2023-12-31 14:23:00Z\"))\n    deepStrictEqual(generator.next().value, new Date(\"2023-12-31 12:23:00Z\"))\n  })\n\n  it(\"equal\", () => {\n    const cron = Cron.unsafeParse(\"23 0-20/2 * * 0\")\n    assertTrue(Equal.equals(cron, cron))\n    assertTrue(Equal.equals(cron, Cron.unsafeParse(\"23 0-20/2 * * 0\")))\n    assertFalse(Equal.equals(cron, Cron.unsafeParse(\"23 0-20/2 * * 1\")))\n    assertFalse(Equal.equals(cron, Cron.unsafeParse(\"23 0-20/2 * * 0-6\")))\n    assertFalse(Equal.equals(cron, Cron.unsafeParse(\"23 0-20/2 1 * 0\")))\n  })\n\n  it(\"handles leap years\", () => {\n    assertTrue(match(\"0 0 29 2 *\", new Date(\"2024-02-29 00:00:00\")))\n    assertFalse(match(\"0 0 29 2 *\", new Date(\"2025-02-29 00:00:00\")))\n    assertFalse(match(\"0 0 29 2 *\", new Date(\"2026-02-29 00:00:00\")))\n    assertFalse(match(\"0 0 29 2 *\", new Date(\"2027-02-29 00:00:00\")))\n    assertTrue(match(\"0 0 29 2 *\", new Date(\"2028-02-29 00:00:00\")))\n\n    deepStrictEqual(next(\"0 0 29 2 *\", new Date(\"2024-01-01 00:00:00\")), new Date(\"2024-02-29 00:00:00\"))\n    deepStrictEqual(next(\"0 0 29 2 *\", new Date(\"2025-01-01 00:00:00\")), new Date(\"2028-02-29 00:00:00\"))\n  })\n\n  it(\"handles transition into daylight savings time\", () => {\n    const make = (date: string) => DateTime.makeZonedFromString(date).pipe(Option.getOrThrow)\n    const sequence = Cron.sequence(\n      Cron.unsafeParse(\"30 * * * *\", \"Europe/Berlin\"),\n      make(\"2024-03-31T00:00:00.000+01:00[Europe/Berlin]\")\n    )\n    const next = (): DateTime.Zoned => DateTime.unsafeMakeZoned(sequence.next().value, { timeZone: \"Europe/Berlin\" })\n\n    const a = make(\"2024-03-31T00:30:00.000+01:00[Europe/Berlin]\")\n    const b = make(\"2024-03-31T01:30:00.000+01:00[Europe/Berlin]\")\n    const c = make(\"2024-03-31T03:30:00.000+02:00[Europe/Berlin]\")\n    const d = make(\"2024-03-31T04:30:00.000+02:00[Europe/Berlin]\")\n\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), a.pipe(DateTime.formatIsoZoned))\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), b.pipe(DateTime.formatIsoZoned))\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), c.pipe(DateTime.formatIsoZoned))\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), d.pipe(DateTime.formatIsoZoned))\n  })\n\n  it(\"handles transition out of daylight savings time\", () => {\n    // DST fall-back transition in Europe/Berlin on 2024-10-27:\n    // At 3:00 AM +02:00, clocks \"fall back\" to 2:00 AM +01:00\n    // This means times from 2:00-2:59 AM occur twice (ambiguous period)\n    //\n    // Correct \"once\" mode behavior for cron:\n    // - Include all normal times (00:30, 01:30)\n    // - Return first occurrence only of ambiguous times (02:30 +02:00)\n    // - Skip second occurrence of ambiguous times (02:30 +01:00)\n    // - Continue normally after transition (03:30 +01:00)\n\n    const make = (date: string) => DateTime.makeZonedFromString(date).pipe(Option.getOrThrow)\n    const sequence = Cron.sequence(\n      Cron.unsafeParse(\"30 * * * *\", \"Europe/Berlin\"),\n      make(\"2024-10-27T00:00:00.000+02:00[Europe/Berlin]\")\n    )\n    const next = (): DateTime.Zoned => DateTime.unsafeMakeZoned(sequence.next().value, { timeZone: \"Europe/Berlin\" })\n\n    const a = make(\"2024-10-27T00:30:00.000+02:00[Europe/Berlin]\") // Normal time\n    const b = make(\"2024-10-27T01:30:00.000+02:00[Europe/Berlin]\") // Normal time (not ambiguous)\n    const c = make(\"2024-10-27T02:30:00.000+02:00[Europe/Berlin]\") // First occurrence during DST\n    const d = make(\"2024-10-27T03:30:00.000+01:00[Europe/Berlin]\") // Standard time (skips 2nd 02:30)\n    const e = make(\"2024-10-27T04:30:00.000+01:00[Europe/Berlin]\") // Standard time\n\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), a.pipe(DateTime.formatIsoZoned))\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), b.pipe(DateTime.formatIsoZoned))\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), c.pipe(DateTime.formatIsoZoned))\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), d.pipe(DateTime.formatIsoZoned))\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), e.pipe(DateTime.formatIsoZoned))\n  })\n\n  it(\"handles utc timezone\", () => {\n    const utc = DateTime.zoneUnsafeMakeNamed(\"UTC\")\n    const make = (date: string) => DateTime.makeZonedFromString(date).pipe(Option.getOrThrow)\n    const sequence = Cron.sequence(Cron.unsafeParse(\"30 * * * *\", utc), make(\"2024-10-27T00:00:00.000+00:00[UTC]\"))\n    const next = (): DateTime.Zoned => DateTime.unsafeMakeZoned(sequence.next().value, { timeZone: utc })\n\n    const a = make(\"2024-10-27T00:30:00.000+00:00[UTC]\")\n    const b = make(\"2024-10-27T01:30:00.000+00:00[UTC]\")\n    const c = make(\"2024-10-27T02:30:00.000+00:00[UTC]\")\n    const d = make(\"2024-10-27T03:30:00.000+00:00[UTC]\")\n\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), a.pipe(DateTime.formatIsoZoned))\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), b.pipe(DateTime.formatIsoZoned))\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), c.pipe(DateTime.formatIsoZoned))\n    deepStrictEqual(next().pipe(DateTime.formatIsoZoned), d.pipe(DateTime.formatIsoZoned))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Data.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Data, Equal, pipe } from \"effect\"\n\ndescribe(\"Data\", () => {\n  it(\"struct\", () => {\n    const x = Data.struct({ a: 0, b: 1, c: 2 })\n    const y = Data.struct({ a: 0, b: 1, c: 2 })\n    const { a, b, c } = x\n    strictEqual(a, 0)\n    strictEqual(b, 1)\n    strictEqual(c, 2)\n    assertTrue(Equal.equals(x, y))\n    assertFalse(Equal.equals(x, Data.struct({ a: 0 })))\n\n    // different keys length\n    assertFalse(Equal.equals(Data.struct({ a: 0, b: 1 }), Data.struct({ a: 0 })))\n    // same length but different keys\n    assertFalse(Equal.equals(Data.struct({ a: 0 }), Data.struct({ b: 1 })))\n  })\n\n  it(\"unsafeStruct\", () => {\n    const x = Data.unsafeStruct({ a: 0, b: 1, c: 2 })\n    const y = Data.unsafeStruct({ a: 0, b: 1, c: 2 })\n    const { a, b, c } = x\n    strictEqual(a, 0)\n    strictEqual(b, 1)\n    strictEqual(c, 2)\n    assertTrue(Equal.equals(x, y))\n  })\n\n  it(\"tuple\", () => {\n    const x = Data.tuple(0, 1, 2)\n    const y = Data.tuple(0, 1, 2)\n    const [a, b, c] = x\n    strictEqual(a, 0)\n    strictEqual(b, 1)\n    strictEqual(c, 2)\n    assertTrue(Equal.equals(x, y))\n    assertFalse(Equal.equals(x, Data.tuple(0, 1)))\n  })\n\n  it(\"array\", () => {\n    const x = Data.array([0, 1, 2])\n    const y = Data.array([0, 1, 2])\n    const [a, b, c] = x\n    strictEqual(a, 0)\n    strictEqual(b, 1)\n    strictEqual(c, 2)\n    assertTrue(Equal.equals(x, y))\n    assertTrue(Equal.equals(x, Data.tuple(0, 1, 2)))\n    assertFalse(Equal.equals(x, Data.array([0, 1])))\n\n    // different length\n    assertFalse(Equal.equals(Data.array([0, 1, 2]), Data.array([0, 1])))\n  })\n\n  it(\"case\", () => {\n    interface Person {\n      readonly name: string\n    }\n\n    const Person = Data.case<Person>()\n\n    const a = Person({ name: \"Mike\" })\n    const b = Person({ name: \"Mike\" })\n    const c = Person({ name: \"Foo\" })\n\n    strictEqual(a.name, \"Mike\")\n    strictEqual(b.name, \"Mike\")\n    strictEqual(c.name, \"Foo\")\n    assertTrue(Equal.equals(a, b))\n    assertFalse(Equal.equals(a, c))\n\n    const Empty = Data.case()\n    assertTrue(Equal.equals(Empty(), Empty()))\n  })\n\n  it(\"tagged\", () => {\n    interface Person {\n      readonly _tag: \"Person\"\n      readonly name: string\n    }\n\n    const Person = Data.tagged<Person>(\"Person\")\n\n    const a = Person({ name: \"Mike\" })\n    const b = Person({ name: \"Mike\" })\n    const c = Person({ name: \"Foo\" })\n\n    strictEqual(a._tag, \"Person\")\n    strictEqual(a.name, \"Mike\")\n    strictEqual(b.name, \"Mike\")\n    strictEqual(c.name, \"Foo\")\n    assertTrue(Equal.equals(a, b))\n    assertFalse(Equal.equals(a, c))\n  })\n\n  it(\"case class\", () => {\n    class Person extends Data.Class<{ name: string }> {}\n    const a = new Person({ name: \"Mike\" })\n    const b = new Person({ name: \"Mike\" })\n    const c = new Person({ name: \"Foo\" })\n\n    strictEqual(a.name, \"Mike\")\n    strictEqual(b.name, \"Mike\")\n    strictEqual(c.name, \"Foo\")\n    assertTrue(Equal.equals(a, b))\n    assertFalse(Equal.equals(a, c))\n\n    // different keys length\n    class D extends Data.Class<{ d: string; e: string }> {}\n    const d = new D({ d: \"d\", e: \"e\" })\n    assertFalse(Equal.equals(a, d))\n    // same length but different keys\n    class E extends Data.Class<{ e: string }> {}\n    const e = new E({ e: \"e\" })\n    assertFalse(Equal.equals(a, e))\n  })\n\n  it(\"date compares by value\", () => {\n    const date = new Date()\n    const a = Data.struct({ date: new Date(date.toISOString()) })\n    const b = Data.struct({ date: new Date(date.toISOString()) })\n\n    assertTrue(Equal.equals(a, b))\n  })\n\n  it(\"URL compares by value\", () => {\n    const a = Data.struct({ date: new URL(\"http://example.com\") })\n    const b = Data.struct({ date: new URL(\"http://example.com\") })\n    const c = Data.struct({ date: new URL(\"https://effect.website\") })\n\n    assertTrue(Equal.equals(a, b))\n    assertFalse(Equal.equals(a, c))\n  })\n\n  it(\"tagged class\", () => {\n    class Person extends Data.TaggedClass(\"Person\")<{ name: string }> {}\n    const a = new Person({ name: \"Mike\" })\n    const b = new Person({ name: \"Mike\" })\n    const c = new Person({ name: \"Foo\" })\n\n    strictEqual(a._tag, \"Person\")\n    strictEqual(a.name, \"Mike\")\n    strictEqual(b.name, \"Mike\")\n    strictEqual(c.name, \"Foo\")\n    assertTrue(Equal.equals(a, b))\n    assertFalse(Equal.equals(a, c))\n  })\n\n  it(\"tagged - empty\", () => {\n    interface Person {\n      readonly _tag: \"Person\"\n    }\n\n    const Person = Data.tagged<Person>(\"Person\")\n\n    const a = Person()\n    const b = Person()\n\n    assertTrue(Equal.equals(a, b))\n  })\n\n  it(\"TaggedClass - empty\", () => {\n    class Person extends Data.TaggedClass(\"Person\")<{}> {}\n\n    const a = new Person()\n    const b = new Person()\n\n    assertTrue(Equal.equals(a, b))\n  })\n\n  it(\"tagged - don't override tag\", () => {\n    interface Foo {\n      readonly _tag: \"Foo\"\n      readonly value: string\n    }\n    const Foo = Data.tagged<Foo>(\"Foo\")\n    interface Bar {\n      readonly _tag: \"Bar\"\n      readonly value: number\n    }\n    const Bar = Data.tagged<Bar>(\"Bar\")\n\n    const foo = Foo({ value: \"test\" })\n    const bar = Bar({ ...foo, value: 10 })\n\n    strictEqual(bar._tag, \"Bar\")\n  })\n\n  it(\"taggedEnum\", () => {\n    type HttpError = Data.TaggedEnum<{\n      NotFound: {}\n      InternalServerError: { reason: string }\n    }>\n    const {\n      $is,\n      $match,\n      InternalServerError,\n      NotFound\n    } = Data.taggedEnum<HttpError>()\n\n    const a = NotFound()\n    const b = InternalServerError({ reason: \"test\" })\n    const c = InternalServerError({ reason: \"test\" })\n\n    strictEqual(a._tag, \"NotFound\")\n    strictEqual(b._tag, \"InternalServerError\")\n\n    strictEqual(b.reason, \"test\")\n    strictEqual(c.reason, \"test\")\n\n    assertFalse(Equal.equals(a, b))\n    assertTrue(Equal.equals(b, c))\n\n    assertTrue($is(\"NotFound\")(a))\n    assertFalse($is(\"InternalServerError\")(a))\n    const matcher = $match({\n      NotFound: () => 0,\n      InternalServerError: () => 1\n    })\n    strictEqual(matcher(a), 0)\n    strictEqual(matcher(b), 1)\n  })\n\n  it(\"taggedEnum - generics\", () => {\n    type Result<E, A> = Data.TaggedEnum<{\n      Success: { value: A }\n      Failure: {\n        error: E\n        message?: string\n      }\n    }>\n    interface ResultDefinition extends Data.TaggedEnum.WithGenerics<2> {\n      readonly taggedEnum: Result<this[\"A\"], this[\"B\"]>\n    }\n    const { $is, $match, Failure, Success } = Data.taggedEnum<ResultDefinition>()\n\n    const a = Success({ value: 1 }) satisfies Result<unknown, number>\n    const b = Failure({ error: \"test\" }) satisfies Result<string, unknown>\n    const c = Success({ value: 1 }) satisfies Result<string, number>\n\n    strictEqual(a._tag, \"Success\")\n    strictEqual(b._tag, \"Failure\")\n    strictEqual(c._tag, \"Success\")\n\n    strictEqual(a.value, 1)\n    strictEqual(b.error, \"test\")\n\n    assertFalse(Equal.equals(a, b))\n    assertTrue(Equal.equals(a, c))\n\n    const aResult = Success({ value: 1 }) as Result<unknown, number>\n    const bResult = Failure({ error: \"boom\" }) as Result<string, number>\n\n    strictEqual(\n      $match(aResult, {\n        Success: (_) => 1,\n        Failure: (_) => 2\n      }),\n      1\n    )\n    const result = pipe(\n      bResult,\n      $match({\n        Success: (_) => _.value,\n        Failure: (_) => _.error\n      })\n    )\n    result satisfies string | number\n    strictEqual(result, \"boom\")\n\n    assertTrue($is(\"Success\")(aResult))\n    aResult satisfies { readonly _tag: \"Success\"; readonly value: number }\n    strictEqual(aResult.value, 1)\n\n    assertTrue($is(\"Failure\")(bResult))\n    bResult satisfies { readonly _tag: \"Failure\"; readonly error: string }\n    strictEqual(bResult.error, \"boom\")\n  })\n\n  describe(\"Error\", () => {\n    it(\"should support a message field\", () => {\n      class MyError extends Data.Error<{ message: string; a: number }> {}\n      const e = new MyError({ message: \"Oh no!\", a: 1 })\n      strictEqual(e.message, \"Oh no!\")\n      strictEqual(e.a, 1)\n    })\n\n    it(\"toJSON includes all args\", () => {\n      class MyError extends Data.Error<{ message: string; a: number; cause: string }> {}\n      const e = new MyError({ message: \"Oh no!\", a: 1, cause: \"Boom\" })\n      deepStrictEqual(e.toJSON(), { message: \"Oh no!\", a: 1, cause: \"Boom\" })\n    })\n  })\n\n  describe(\"TaggedError\", () => {\n    it(\"toJSON includes all args\", () => {\n      class MyError extends Data.TaggedError(\"MyError\")<{ message: string; a: number; cause: string }> {}\n      const e = new MyError({ message: \"Oh no!\", a: 1, cause: \"Boom\" })\n      deepStrictEqual(e.toJSON(), {\n        _tag: \"MyError\",\n        message: \"Oh no!\",\n        a: 1,\n        cause: \"Boom\"\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/DateTime.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertRight, assertSome, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { DateTime, Duration, Effect, Option, TestClock } from \"effect\"\n\nconst setTo2024NZ = TestClock.setTime(new Date(\"2023-12-31T11:00:00.000Z\").getTime())\nconst assertSomeIso = (value: Option.Option<DateTime.DateTime>, expected: string) => {\n  const iso = value.pipe(Option.map((value) => DateTime.formatIso(DateTime.toUtc(value))))\n  assertSome(iso, expected)\n}\n\ndescribe(\"DateTime\", () => {\n  describe(\"mutate\", () => {\n    it.effect(\"should mutate the date\", () =>\n      Effect.gen(function*() {\n        const now = yield* DateTime.now\n        const tomorrow = DateTime.mutate(now, (date) => {\n          date.setUTCDate(date.getUTCDate() + 1)\n        })\n        const diff = DateTime.distanceDurationEither(now, tomorrow)\n        assertRight(diff, Duration.decode(\"1 day\"))\n      }))\n\n    it.effect(\"correctly preserves the time zone\", () =>\n      Effect.gen(function*() {\n        yield* setTo2024NZ\n        const now = yield* DateTime.nowInCurrentZone.pipe(\n          DateTime.withCurrentZoneNamed(\"Pacific/Auckland\")\n        )\n        const future = DateTime.mutate(now, (date) => {\n          date.setUTCMonth(date.getUTCMonth() + 6)\n        })\n        strictEqual(DateTime.toDateUtc(future).toISOString(), \"2024-06-30T12:00:00.000Z\")\n        strictEqual(DateTime.toDate(future).toISOString(), \"2024-07-01T00:00:00.000Z\")\n        const plusOne = DateTime.mutate(future, (date) => {\n          date.setUTCDate(date.getUTCDate() + 1)\n        })\n        strictEqual(DateTime.toDateUtc(plusOne).toISOString(), \"2024-07-01T12:00:00.000Z\")\n        strictEqual(DateTime.toDate(plusOne).toISOString(), \"2024-07-02T00:00:00.000Z\")\n      }))\n  })\n\n  describe(\"add\", () => {\n    it.effect(\"utc\", () =>\n      Effect.gen(function*() {\n        const now = yield* DateTime.now\n        const tomorrow = DateTime.add(now, { days: 1 })\n        const diff = DateTime.distanceDurationEither(now, tomorrow)\n        assertRight(diff, Duration.decode(\"1 day\"))\n      }))\n\n    it(\"to month with less days\", () => {\n      const jan = DateTime.unsafeMake({ year: 2023, month: 1, day: 31 })\n      let feb = DateTime.add(jan, { months: 1 })\n      strictEqual(feb.toJSON(), \"2023-02-28T00:00:00.000Z\")\n\n      const mar = DateTime.unsafeMake({ year: 2023, month: 3, day: 31 })\n      feb = DateTime.subtract(mar, { months: 1 })\n      strictEqual(feb.toJSON(), \"2023-02-28T00:00:00.000Z\")\n    })\n\n    it.effect(\"correctly preserves the time zone\", () =>\n      Effect.gen(function*() {\n        yield* setTo2024NZ\n        const now = yield* DateTime.nowInCurrentZone.pipe(\n          DateTime.withCurrentZoneNamed(\"Pacific/Auckland\")\n        )\n        const future = DateTime.add(now, { months: 6 })\n        strictEqual(DateTime.toDateUtc(future).toISOString(), \"2024-06-30T12:00:00.000Z\")\n        strictEqual(DateTime.toDate(future).toISOString(), \"2024-07-01T00:00:00.000Z\")\n        const plusOne = DateTime.add(future, { days: 1 })\n        strictEqual(DateTime.toDateUtc(plusOne).toISOString(), \"2024-07-01T12:00:00.000Z\")\n        strictEqual(DateTime.toDate(plusOne).toISOString(), \"2024-07-02T00:00:00.000Z\")\n        const minusOne = DateTime.subtract(plusOne, { days: 1 })\n        strictEqual(DateTime.toDateUtc(minusOne).toISOString(), \"2024-06-30T12:00:00.000Z\")\n        strictEqual(DateTime.toDate(minusOne).toISOString(), \"2024-07-01T00:00:00.000Z\")\n      }))\n\n    it.effect(\"leap years\", () =>\n      Effect.gen(function*() {\n        yield* setTo2024NZ\n        const now = yield* DateTime.make({ year: 2024, month: 2, day: 29 })\n        const future = DateTime.add(now, { years: 1 })\n        strictEqual(DateTime.formatIso(future), \"2025-02-28T00:00:00.000Z\")\n      }))\n  })\n\n  describe(\"endOf\", () => {\n    it(\"month\", () => {\n      const mar = DateTime.unsafeMake(\"2024-03-15T12:00:00.000Z\")\n      const end = DateTime.endOf(mar, \"month\")\n      strictEqual(end.toJSON(), \"2024-03-31T23:59:59.999Z\")\n    })\n\n    it(\"feb leap year\", () => {\n      const feb = DateTime.unsafeMake(\"2024-02-15T12:00:00.000Z\")\n      const end = DateTime.endOf(feb, \"month\")\n      strictEqual(end.toJSON(), \"2024-02-29T23:59:59.999Z\")\n    })\n\n    it(\"week\", () => {\n      const start = DateTime.unsafeMake(\"2024-03-15T12:00:00.000Z\")\n      const end = DateTime.endOf(start, \"week\")\n      strictEqual(end.toJSON(), \"2024-03-16T23:59:59.999Z\")\n      strictEqual(DateTime.getPartUtc(end, \"weekDay\"), 6)\n    })\n\n    it(\"week last day\", () => {\n      const start = DateTime.unsafeMake(\"2024-03-16T12:00:00.000Z\")\n      const end = DateTime.endOf(start, \"week\")\n      strictEqual(end.toJSON(), \"2024-03-16T23:59:59.999Z\")\n    })\n\n    it(\"week with options\", () => {\n      const start = DateTime.unsafeMake(\"2024-03-15T12:00:00.000Z\")\n      const end = DateTime.endOf(start, \"week\", {\n        weekStartsOn: 1\n      })\n      strictEqual(end.toJSON(), \"2024-03-17T23:59:59.999Z\")\n    })\n\n    it.effect(\"correctly preserves the time zone\", () =>\n      Effect.gen(function*() {\n        yield* setTo2024NZ\n        const now = yield* DateTime.nowInCurrentZone.pipe(\n          DateTime.withCurrentZoneNamed(\"Pacific/Auckland\")\n        )\n        const future = DateTime.endOf(now, \"month\")\n        strictEqual(DateTime.toDateUtc(future).toISOString(), \"2024-01-31T10:59:59.999Z\")\n        strictEqual(DateTime.toDate(future).toISOString(), \"2024-01-31T23:59:59.999Z\")\n      }))\n  })\n\n  describe(\"startOf\", () => {\n    it(\"month\", () => {\n      const mar = DateTime.unsafeMake(\"2024-03-15T12:00:00.000Z\")\n      const end = DateTime.startOf(mar, \"month\")\n      strictEqual(end.toJSON(), \"2024-03-01T00:00:00.000Z\")\n    })\n\n    it(\"month duplicated\", () => {\n      const mar = DateTime.unsafeMake(\"2024-03-15T12:00:00.000Z\")\n      const end = DateTime.startOf(mar, \"month\").pipe(\n        DateTime.startOf(\"month\")\n      )\n      strictEqual(end.toJSON(), \"2024-03-01T00:00:00.000Z\")\n    })\n\n    it(\"feb leap year\", () => {\n      const feb = DateTime.unsafeMake(\"2024-02-15T12:00:00.000Z\")\n      const end = DateTime.startOf(feb, \"month\")\n      strictEqual(end.toJSON(), \"2024-02-01T00:00:00.000Z\")\n    })\n\n    it(\"week\", () => {\n      const start = DateTime.unsafeMake(\"2024-03-15T12:00:00.000Z\")\n      const end = DateTime.startOf(start, \"week\")\n      strictEqual(end.toJSON(), \"2024-03-10T00:00:00.000Z\")\n      strictEqual(DateTime.getPartUtc(end, \"weekDay\"), 0)\n    })\n\n    it(\"week first day\", () => {\n      const start = DateTime.unsafeMake(\"2024-03-10T12:00:00.000Z\")\n      const end = DateTime.startOf(start, \"week\")\n      strictEqual(end.toJSON(), \"2024-03-10T00:00:00.000Z\")\n    })\n\n    it(\"week with options\", () => {\n      const start = DateTime.unsafeMake(\"2024-03-15T12:00:00.000Z\")\n      const end = DateTime.startOf(start, \"week\", {\n        weekStartsOn: 1\n      })\n      strictEqual(end.toJSON(), \"2024-03-11T00:00:00.000Z\")\n    })\n  })\n\n  describe(\"nearest\", () => {\n    it(\"month up\", () => {\n      const mar = DateTime.unsafeMake(\"2024-03-16T12:00:00.000Z\")\n      const end = DateTime.nearest(mar, \"month\")\n      strictEqual(end.toJSON(), \"2024-04-01T00:00:00.000Z\")\n    })\n\n    it(\"month down\", () => {\n      const mar = DateTime.unsafeMake(\"2024-03-16T11:00:00.000Z\")\n      const end = DateTime.nearest(mar, \"month\")\n      strictEqual(end.toJSON(), \"2024-03-01T00:00:00.000Z\")\n    })\n\n    it(\"second up\", () => {\n      const mar = DateTime.unsafeMake(\"2024-03-20T12:00:00.500Z\")\n      const end = DateTime.nearest(mar, \"second\")\n      strictEqual(end.toJSON(), \"2024-03-20T12:00:01.000Z\")\n    })\n\n    it(\"second down\", () => {\n      const mar = DateTime.unsafeMake(\"2024-03-20T12:00:00.400Z\")\n      const end = DateTime.nearest(mar, \"second\")\n      strictEqual(end.toJSON(), \"2024-03-20T12:00:00.000Z\")\n    })\n  })\n\n  describe(\"format\", () => {\n    it.effect(\"full\", () =>\n      Effect.gen(function*() {\n        const now = yield* DateTime.now\n        strictEqual(\n          DateTime.format(now, {\n            locale: \"en-US\",\n            dateStyle: \"full\",\n            timeStyle: \"full\"\n          }),\n          \"Thursday, January 1, 1970 at 12:00:00 AM Coordinated Universal Time\"\n        )\n      }))\n  })\n\n  describe(\"formatUtc\", () => {\n    it.effect(\"full\", () =>\n      Effect.gen(function*() {\n        const now = yield* DateTime.now\n        strictEqual(\n          DateTime.formatUtc(now, {\n            locale: \"en-US\",\n            dateStyle: \"full\",\n            timeStyle: \"full\"\n          }),\n          \"Thursday, January 1, 1970 at 12:00:00 AM Coordinated Universal Time\"\n        )\n      }))\n  })\n\n  describe(\"format zoned\", () => {\n    it.effect(\"full\", () =>\n      Effect.gen(function*() {\n        const now = yield* DateTime.nowInCurrentZone.pipe(\n          DateTime.withCurrentZoneNamed(\"Pacific/Auckland\")\n        )\n        strictEqual(\n          DateTime.format(now, {\n            locale: \"en-US\",\n            dateStyle: \"full\",\n            timeStyle: \"full\"\n          }),\n          \"Thursday, January 1, 1970 at 12:00:00 PM New Zealand Standard Time\"\n        )\n      }))\n\n    it.effect(\"long with offset\", () =>\n      Effect.gen(function*() {\n        const now = yield* DateTime.now\n        const formatted = now.pipe(\n          DateTime.setZoneOffset(10 * 60 * 60 * 1000),\n          DateTime.format({\n            locale: \"en-US\",\n            dateStyle: \"long\",\n            timeStyle: \"short\"\n          })\n        )\n        strictEqual(formatted, \"January 1, 1970 at 10:00 AM\")\n      }))\n  })\n\n  describe(\"fromParts\", () => {\n    it(\"partial\", () => {\n      const date = DateTime.unsafeMake({\n        year: 2024,\n        month: 12,\n        day: 25\n      })\n      strictEqual(date.toJSON(), \"2024-12-25T00:00:00.000Z\")\n    })\n\n    it(\"month is set correctly\", () => {\n      const date = DateTime.unsafeMake({ year: 2024 })\n      strictEqual(date.toJSON(), \"2024-01-01T00:00:00.000Z\")\n    })\n  })\n\n  describe(\"setPartsUtc\", () => {\n    it(\"partial\", () => {\n      const date = DateTime.unsafeMake({\n        year: 2024,\n        month: 12,\n        day: 25\n      })\n      strictEqual(date.toJSON(), \"2024-12-25T00:00:00.000Z\")\n\n      const updated = DateTime.setPartsUtc(date, {\n        year: 2023,\n        month: 1\n      })\n      strictEqual(updated.toJSON(), \"2023-01-25T00:00:00.000Z\")\n    })\n\n    it(\"ignores time zones\", () => {\n      const date = DateTime.unsafeMake({\n        year: 2024,\n        month: 12,\n        day: 25\n      }).pipe(DateTime.unsafeSetZoneNamed(\"Pacific/Auckland\"))\n      strictEqual(date.toJSON(), \"2024-12-25T00:00:00.000Z\")\n\n      const updated = DateTime.setPartsUtc(date, {\n        year: 2023,\n        month: 1\n      })\n      strictEqual(updated.toJSON(), \"2023-01-25T00:00:00.000Z\")\n    })\n  })\n\n  describe(\"setParts\", () => {\n    it(\"partial\", () => {\n      const date = DateTime.unsafeMake({\n        year: 2024,\n        month: 12,\n        day: 25\n      })\n      strictEqual(date.toJSON(), \"2024-12-25T00:00:00.000Z\")\n\n      const updated = DateTime.setParts(date, {\n        year: 2023,\n        month: 1\n      })\n      strictEqual(updated.toJSON(), \"2023-01-25T00:00:00.000Z\")\n    })\n\n    it(\"accounts for time zone\", () => {\n      const date = DateTime.unsafeMake({\n        year: 2024,\n        month: 12,\n        day: 25\n      }).pipe(DateTime.unsafeSetZoneNamed(\"Pacific/Auckland\"))\n      strictEqual(date.toJSON(), \"2024-12-25T00:00:00.000Z\")\n\n      const updated = DateTime.setParts(date, {\n        year: 2023,\n        month: 6,\n        hours: 12\n      })\n      strictEqual(updated.toJSON(), \"2023-06-25T00:00:00.000Z\")\n    })\n  })\n\n  describe(\"formatIso\", () => {\n    it(\"full\", () => {\n      const now = DateTime.unsafeMake(\"2024-03-15T12:00:00.000Z\")\n      strictEqual(DateTime.formatIso(now), \"2024-03-15T12:00:00.000Z\")\n    })\n  })\n\n  describe(\"formatIsoOffset\", () => {\n    it.effect(\"correctly adds offset\", () =>\n      Effect.gen(function*() {\n        const now = yield* DateTime.nowInCurrentZone.pipe(\n          DateTime.withCurrentZoneNamed(\"Pacific/Auckland\")\n        )\n        strictEqual(DateTime.formatIsoOffset(now), \"1970-01-01T12:00:00.000+12:00\")\n      }))\n  })\n\n  describe(\"layerCurrentZoneNamed\", () => {\n    it.effect(\"correctly adds offset\", () =>\n      Effect.gen(function*() {\n        const now = yield* DateTime.nowInCurrentZone\n        strictEqual(DateTime.formatIsoOffset(now), \"1970-01-01T12:00:00.000+12:00\")\n      }).pipe(\n        Effect.provide(DateTime.layerCurrentZoneNamed(\"Pacific/Auckland\"))\n      ))\n  })\n\n  describe(\"removeTime\", () => {\n    it(\"removes time\", () => {\n      const dt = DateTime.unsafeMakeZoned(\"2024-01-01T01:00:00Z\", {\n        timeZone: \"Pacific/Auckland\",\n        adjustForTimeZone: true\n      }).pipe(DateTime.removeTime)\n      strictEqual(dt.toJSON(), \"2024-01-01T00:00:00.000Z\")\n    })\n  })\n\n  describe(\"makeZonedFromString\", () => {\n    it.effect(\"parses time + zone\", () =>\n      Effect.gen(function*() {\n        const dt = yield* DateTime.makeZonedFromString(\"2024-07-21T20:12:34.112546348+12:00[Pacific/Auckland]\")\n        strictEqual(dt.toJSON(), \"2024-07-21T08:12:34.112Z\")\n      }))\n\n    it.effect(\"only offset\", () =>\n      Effect.gen(function*() {\n        const dt = yield* DateTime.makeZonedFromString(\"2024-07-21T20:12:34.112546348+12:00\")\n        strictEqual(dt.zone._tag, \"Offset\")\n        strictEqual(dt.toJSON(), \"2024-07-21T08:12:34.112Z\")\n      }))\n\n    it.effect(\"only offset with 00:00\", () =>\n      Effect.gen(function*() {\n        const dt = yield* DateTime.makeZonedFromString(\"2024-07-21T20:12:34.112546348+00:00\")\n        strictEqual(dt.zone._tag, \"Offset\")\n        strictEqual(dt.toJSON(), \"2024-07-21T20:12:34.112Z\")\n      }))\n\n    it.effect(\"roundtrip\", () =>\n      Effect.gen(function*() {\n        const dt = yield* DateTime.makeZonedFromString(\"2024-07-21T20:12:34.112546348+12:00[Pacific/Auckland]\").pipe(\n          Option.map(DateTime.formatIsoZoned),\n          Option.flatMap(DateTime.makeZonedFromString)\n        )\n        deepStrictEqual(dt.zone, DateTime.zoneUnsafeMakeNamed(\"Pacific/Auckland\"))\n        strictEqual(dt.toJSON(), \"2024-07-21T08:12:34.112Z\")\n      }))\n  })\n\n  it(\"parts equality\", () => {\n    const d1 = DateTime.unsafeMake(\"2025-01-01\")\n    const d2 = DateTime.unsafeMake(\"2025-01-01\")\n    deepStrictEqual(d1, d2)\n    DateTime.toPartsUtc(d2)\n    deepStrictEqual(d1, d2)\n  })\n\n  // doesnt work in CI\n  it.skip(\"unsafeMakeZoned no options\", () => {\n    const date = new Date(\"2024-07-21T20:12:34.112Z\")\n    ;(date as any).getTimezoneOffset = () => -60\n    const dt = DateTime.unsafeMakeZoned(date)\n    deepStrictEqual(dt.zone, DateTime.zoneMakeOffset(60 * 60 * 1000))\n  })\n\n  describe(\"toUtc\", () => {\n    it.effect(\"with a Utc\", () =>\n      Effect.gen(function*() {\n        const dt = DateTime.unsafeMake(\"2024-01-01T01:00:00Z\")\n        strictEqual(dt.toJSON(), \"2024-01-01T01:00:00.000Z\")\n      }))\n\n    it.effect(\"with a Zoned\", () =>\n      Effect.gen(function*() {\n        const dt = DateTime.unsafeMakeZoned(\"2024-01-01T01:00:00Z\", {\n          timeZone: \"Pacific/Auckland\",\n          adjustForTimeZone: true\n        })\n        strictEqual(dt.toJSON(), \"2023-12-31T12:00:00.000Z\")\n      }))\n  })\n\n  describe(\"nowAsDate\", () => {\n    it.effect(\"should return the current Date\", () =>\n      Effect.gen(function*() {\n        yield* setTo2024NZ\n        const now = yield* DateTime.nowAsDate\n        deepStrictEqual(now, new Date(\"2023-12-31T11:00:00.000Z\"))\n      }))\n  })\n\n  describe(\"unsafeMake\", () => {\n    it(\"treats strings without zone info as UTC\", () => {\n      let dt = DateTime.unsafeMake(\"2024-01-01 01:00:00\")\n      strictEqual(dt.toJSON(), \"2024-01-01T01:00:00.000Z\")\n\n      dt = DateTime.unsafeMake(\"2020-02-01T11:17:00+1100\")\n      strictEqual(dt.toJSON(), \"2020-02-01T00:17:00.000Z\")\n    })\n  })\n\n  describe(\"Disambiguation\", () => {\n    it.each<{\n      zone: string\n      time: Partial<DateTime.DateTime.Parts>\n      description: string\n      expectedResults: Record<DateTime.Disambiguation, string>\n    }>(\n      [\n        {\n          zone: \"America/New_York\",\n          time: { year: 2024, month: 3, day: 10, hours: 2 },\n          description: \"America/New_York 02:00 gap time during leap year (2024)\",\n          expectedResults: {\n            compatible: \"2024-03-10T07:00:00.000Z\",\n            earlier: \"2024-03-10T06:00:00.000Z\",\n            later: \"2024-03-10T07:00:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2024, month: 11, day: 3, hours: 1, minutes: 30 },\n          description: \"America/New_York 01:30 ambiguous time during leap year (2024)\",\n          expectedResults: {\n            compatible: \"2024-11-03T05:30:00.000Z\",\n            earlier: \"2024-11-03T05:30:00.000Z\",\n            later: \"2024-11-03T06:30:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2025, month: 3, day: 9, hours: 1 },\n          description: \"America/New_York 01:00 before DST transition\",\n          expectedResults: {\n            compatible: \"2025-03-09T06:00:00.000Z\",\n            earlier: \"2025-03-09T06:00:00.000Z\",\n            later: \"2025-03-09T06:00:00.000Z\",\n            reject: \"2025-03-09T06:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2025, month: 3, day: 9, hours: 1, minutes: 59, seconds: 59 },\n          description: \"America/New_York 01:59:59 last second before DST gap\",\n          expectedResults: {\n            compatible: \"2025-03-09T06:59:59.000Z\",\n            earlier: \"2025-03-09T06:59:59.000Z\",\n            later: \"2025-03-09T06:59:59.000Z\",\n            reject: \"2025-03-09T06:59:59.000Z\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2025, month: 3, day: 9, hours: 2 },\n          description: \"America/New_York 02:00 gap time (DST spring forward)\",\n          expectedResults: {\n            compatible: \"2025-03-09T07:00:00.000Z\",\n            earlier: \"2025-03-09T06:00:00.000Z\",\n            later: \"2025-03-09T07:00:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2025, month: 3, day: 9, hours: 2, minutes: 15 },\n          description: \"America/New_York 02:15 gap time (DST spring forward)\",\n          expectedResults: {\n            compatible: \"2025-03-09T07:15:00.000Z\",\n            earlier: \"2025-03-09T06:15:00.000Z\",\n            later: \"2025-03-09T07:15:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2025, month: 3, day: 9, hours: 2, minutes: 30 },\n          description: \"America/New_York 02:30 gap time (DST spring forward)\",\n          expectedResults: {\n            compatible: \"2025-03-09T07:30:00.000Z\",\n            earlier: \"2025-03-09T06:30:00.000Z\",\n            later: \"2025-03-09T07:30:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2025, month: 3, day: 9, hours: 2, minutes: 45 },\n          description: \"America/New_York 02:45 gap time (DST spring forward)\",\n          expectedResults: {\n            compatible: \"2025-03-09T07:45:00.000Z\",\n            earlier: \"2025-03-09T06:45:00.000Z\",\n            later: \"2025-03-09T07:45:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2025, month: 3, day: 9, hours: 3 },\n          description: \"America/New_York 03:00 first valid time after DST gap\",\n          expectedResults: {\n            compatible: \"2025-03-09T07:00:00.000Z\",\n            earlier: \"2025-03-09T07:00:00.000Z\",\n            later: \"2025-03-09T07:00:00.000Z\",\n            reject: \"2025-03-09T07:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2025, month: 11, day: 2, hours: 1, minutes: 0, seconds: 0 },\n          description: \"America/New_York 01:00:00 exact start of ambiguous period\",\n          expectedResults: {\n            compatible: \"2025-11-02T05:00:00.000Z\",\n            earlier: \"2025-11-02T05:00:00.000Z\",\n            later: \"2025-11-02T06:00:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2025, month: 11, day: 2, hours: 1, minutes: 30 },\n          description: \"America/New_York 01:30 ambiguous time (DST fall back)\",\n          expectedResults: {\n            compatible: \"2025-11-02T05:30:00.000Z\",\n            earlier: \"2025-11-02T05:30:00.000Z\",\n            later: \"2025-11-02T06:30:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"America/New_York\",\n          time: { year: 2025, month: 11, day: 2, hours: 1, minutes: 59, seconds: 59 },\n          description: \"America/New_York 01:59:59 last second of ambiguous period\",\n          expectedResults: {\n            compatible: \"2025-11-02T05:59:59.000Z\",\n            earlier: \"2025-11-02T05:59:59.000Z\",\n            later: \"2025-11-02T06:59:59.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Asia/Kathmandu\",\n          time: { year: 2025, month: 6, day: 15, hours: 12 },\n          description: \"Asia/Kathmandu 12:00 unusual offset (UTC+05:45)\",\n          expectedResults: {\n            compatible: \"2025-06-15T06:15:00.000Z\",\n            earlier: \"2025-06-15T06:15:00.000Z\",\n            later: \"2025-06-15T06:15:00.000Z\",\n            reject: \"2025-06-15T06:15:00.000Z\"\n          }\n        },\n        {\n          zone: \"Australia/Melbourne\",\n          time: { year: 2025, month: 10, day: 5, hours: 2 },\n          description: \"Australia/Melbourne 02:00 gap time (DST starts, spring forward)\",\n          expectedResults: {\n            compatible: \"2025-10-04T16:00:00.000Z\",\n            earlier: \"2025-10-04T15:00:00.000Z\",\n            later: \"2025-10-04T16:00:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Australia/Sydney\",\n          time: { year: 2025, month: 4, day: 6, hours: 1 },\n          description: \"Australia/Sydney 01:00 normal timezone conversion\",\n          expectedResults: {\n            compatible: \"2025-04-05T14:00:00.000Z\",\n            earlier: \"2025-04-05T14:00:00.000Z\",\n            later: \"2025-04-05T14:00:00.000Z\",\n            reject: \"2025-04-05T14:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"Australia/Sydney\",\n          time: { year: 2025, month: 4, day: 6, hours: 2, minutes: 30 },\n          description: \"Australia/Sydney 02:30 ambiguous time (DST ends, fall back)\",\n          expectedResults: {\n            compatible: \"2025-04-05T15:30:00.000Z\",\n            earlier: \"2025-04-05T15:30:00.000Z\",\n            later: \"2025-04-05T16:30:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Australia/Sydney\",\n          time: { year: 2025, month: 10, day: 5, hours: 2, minutes: 30 },\n          description: \"Australia/Sydney 02:30 gap time (DST starts, spring forward)\",\n          expectedResults: {\n            compatible: \"2025-10-04T16:30:00.000Z\",\n            earlier: \"2025-10-04T15:30:00.000Z\",\n            later: \"2025-10-04T16:30:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Europe/Athens\",\n          time: { year: 2024, month: 10, day: 27, hours: 3 },\n          description: \"Europe/Athens 03:00 ambiguous time during leap year (2024)\",\n          expectedResults: {\n            compatible: \"2024-10-27T00:00:00.000Z\",\n            earlier: \"2024-10-27T00:00:00.000Z\",\n            later: \"2024-10-27T01:00:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Europe/Athens\",\n          time: { year: 2025, month: 3, day: 27, hours: 1 },\n          description: \"Europe/Athens 01:00 normal time before DST\",\n          expectedResults: {\n            compatible: \"2025-03-26T23:00:00.000Z\",\n            earlier: \"2025-03-26T23:00:00.000Z\",\n            later: \"2025-03-26T23:00:00.000Z\",\n            reject: \"2025-03-26T23:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"Europe/Athens\",\n          time: { year: 2025, month: 3, day: 30, hours: 1 },\n          description: \"Europe/Athens 01:00 before DST transition (UTC+2)\",\n          expectedResults: {\n            compatible: \"2025-03-29T23:00:00.000Z\",\n            earlier: \"2025-03-29T23:00:00.000Z\",\n            later: \"2025-03-29T23:00:00.000Z\",\n            reject: \"2025-03-29T23:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"Europe/Athens\",\n          time: { year: 2025, month: 3, day: 30, hours: 2, minutes: 30 },\n          description: \"Europe/Athens 02:30 normal time before DST transition\",\n          expectedResults: {\n            compatible: \"2025-03-30T00:30:00.000Z\",\n            earlier: \"2025-03-30T00:30:00.000Z\",\n            later: \"2025-03-30T00:30:00.000Z\",\n            reject: \"2025-03-30T00:30:00.000Z\"\n          }\n        },\n        {\n          zone: \"Europe/Athens\",\n          time: { year: 2025, month: 3, day: 30, hours: 3 },\n          description: \"Europe/Athens 03:00 gap time (DST spring forward)\",\n          expectedResults: {\n            compatible: \"2025-03-30T01:00:00.000Z\",\n            earlier: \"2025-03-30T00:00:00.000Z\",\n            later: \"2025-03-30T01:00:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Europe/Athens\",\n          time: { year: 2025, month: 3, day: 30, hours: 4 },\n          description: \"Europe/Athens 04:00 normal time after DST transition\",\n          expectedResults: {\n            compatible: \"2025-03-30T01:00:00.000Z\",\n            earlier: \"2025-03-30T01:00:00.000Z\",\n            later: \"2025-03-30T01:00:00.000Z\",\n            reject: \"2025-03-30T01:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"Europe/Athens\",\n          time: { year: 2025, month: 10, day: 26, hours: 3 },\n          description: \"Europe/Athens 03:00 ambiguous time (DST fall back)\",\n          expectedResults: {\n            compatible: \"2025-10-26T00:00:00.000Z\",\n            earlier: \"2025-10-26T00:00:00.000Z\",\n            later: \"2025-10-26T01:00:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Europe/Berlin\",\n          time: { year: 2025, month: 10, day: 26, hours: 2, minutes: 30 },\n          description: \"Europe/Berlin 02:30 ambiguous time (DST fall back)\",\n          expectedResults: {\n            compatible: \"2025-10-26T00:30:00.000Z\",\n            earlier: \"2025-10-26T00:30:00.000Z\",\n            later: \"2025-10-26T01:30:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Europe/London\",\n          time: { year: 2024, month: 3, day: 31, hours: 1 },\n          description: \"Europe/London 01:00 gap time during leap year (2024)\",\n          expectedResults: {\n            compatible: \"2024-03-31T01:00:00.000Z\",\n            earlier: \"2024-03-31T00:00:00.000Z\",\n            later: \"2024-03-31T01:00:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Europe/London\",\n          time: { year: 2025, month: 3, day: 29, hours: 1 },\n          description: \"Europe/London 01:00 normal time day before DST\",\n          expectedResults: {\n            compatible: \"2025-03-29T01:00:00.000Z\",\n            earlier: \"2025-03-29T01:00:00.000Z\",\n            later: \"2025-03-29T01:00:00.000Z\",\n            reject: \"2025-03-29T01:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"Europe/London\",\n          time: { year: 2025, month: 3, day: 30, hours: 1 },\n          description: \"Europe/London 01:00 gap time (DST spring forward)\",\n          expectedResults: {\n            compatible: \"2025-03-30T01:00:00.000Z\",\n            earlier: \"2025-03-30T00:00:00.000Z\",\n            later: \"2025-03-30T01:00:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Europe/London\",\n          time: { year: 2025, month: 10, day: 26, hours: 1, minutes: 30 },\n          description: \"Europe/London 01:30 ambiguous time (DST fall back)\",\n          expectedResults: {\n            compatible: \"2025-10-26T00:30:00.000Z\",\n            earlier: \"2025-10-26T00:30:00.000Z\",\n            later: \"2025-10-26T01:30:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Pacific/Auckland\",\n          time: { year: 2025, month: 1, day: 15, hours: 12 },\n          description: \"Pacific/Auckland 12:00 during DST period (NZDT, UTC+13)\",\n          expectedResults: {\n            compatible: \"2025-01-14T23:00:00.000Z\",\n            earlier: \"2025-01-14T23:00:00.000Z\",\n            later: \"2025-01-14T23:00:00.000Z\",\n            reject: \"2025-01-14T23:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"Pacific/Auckland\",\n          time: { year: 2025, month: 4, day: 6, hours: 1, minutes: 59 },\n          description: \"Pacific/Auckland 01:59 last minute before DST ends\",\n          expectedResults: {\n            compatible: \"2025-04-05T12:59:00.000Z\",\n            earlier: \"2025-04-05T12:59:00.000Z\",\n            later: \"2025-04-05T12:59:00.000Z\",\n            reject: \"2025-04-05T12:59:00.000Z\"\n          }\n        },\n        {\n          zone: \"Pacific/Auckland\",\n          time: { year: 2025, month: 4, day: 6, hours: 2, minutes: 30 },\n          description: \"Pacific/Auckland 02:30 ambiguous time (DST ends, fall back)\",\n          expectedResults: {\n            compatible: \"2025-04-05T13:30:00.000Z\",\n            earlier: \"2025-04-05T13:30:00.000Z\",\n            later: \"2025-04-05T14:30:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Pacific/Auckland\",\n          time: { year: 2025, month: 4, day: 6, hours: 3 },\n          description: \"Pacific/Auckland 03:00 normal time after DST ends\",\n          expectedResults: {\n            compatible: \"2025-04-05T15:00:00.000Z\",\n            earlier: \"2025-04-05T15:00:00.000Z\",\n            later: \"2025-04-05T15:00:00.000Z\",\n            reject: \"2025-04-05T15:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"Pacific/Auckland\",\n          time: { year: 2025, month: 7, day: 15, hours: 12 },\n          description: \"Pacific/Auckland 12:00 during standard time (NZST, UTC+12)\",\n          expectedResults: {\n            compatible: \"2025-07-15T00:00:00.000Z\",\n            earlier: \"2025-07-15T00:00:00.000Z\",\n            later: \"2025-07-15T00:00:00.000Z\",\n            reject: \"2025-07-15T00:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"Pacific/Auckland\",\n          time: { year: 2025, month: 9, day: 28, hours: 1, minutes: 59, seconds: 59 },\n          description: \"Pacific/Auckland 01:59:59 last second before DST starts\",\n          expectedResults: {\n            compatible: \"2025-09-27T13:59:59.000Z\",\n            earlier: \"2025-09-27T13:59:59.000Z\",\n            later: \"2025-09-27T13:59:59.000Z\",\n            reject: \"2025-09-27T13:59:59.000Z\"\n          }\n        },\n        {\n          zone: \"Pacific/Auckland\",\n          time: { year: 2025, month: 9, day: 28, hours: 2, minutes: 30 },\n          description: \"Pacific/Auckland 02:30 gap time (DST starts, spring forward)\",\n          expectedResults: {\n            compatible: \"2025-09-27T14:30:00.000Z\",\n            earlier: \"2025-09-27T13:30:00.000Z\",\n            later: \"2025-09-27T14:30:00.000Z\",\n            reject: \"REJECT\"\n          }\n        },\n        {\n          zone: \"Pacific/Auckland\",\n          time: { year: 2025, month: 9, day: 28, hours: 3 },\n          description: \"Pacific/Auckland 03:00 first valid time after DST gap\",\n          expectedResults: {\n            compatible: \"2025-09-27T14:00:00.000Z\",\n            earlier: \"2025-09-27T14:00:00.000Z\",\n            later: \"2025-09-27T14:00:00.000Z\",\n            reject: \"2025-09-27T14:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"Pacific/Kiritimati\",\n          time: { year: 2025, month: 6, day: 15, hours: 12 },\n          description: \"Pacific/Kiritimati 12:00 extreme positive offset (UTC+14)\",\n          expectedResults: {\n            compatible: \"2025-06-14T22:00:00.000Z\",\n            earlier: \"2025-06-14T22:00:00.000Z\",\n            later: \"2025-06-14T22:00:00.000Z\",\n            reject: \"2025-06-14T22:00:00.000Z\"\n          }\n        },\n        {\n          zone: \"Pacific/Marquesas\",\n          time: { year: 2025, month: 6, day: 15, hours: 12 },\n          description: \"Pacific/Marquesas 12:00 unusual negative offset (UTC-09:30)\",\n          expectedResults: {\n            compatible: \"2025-06-15T21:30:00.000Z\",\n            earlier: \"2025-06-15T21:30:00.000Z\",\n            later: \"2025-06-15T21:30:00.000Z\",\n            reject: \"2025-06-15T21:30:00.000Z\"\n          }\n        }\n      ]\n    )(\n      \"should handle $description\",\n      ({ expectedResults, time, zone }) => {\n        // Test normal strategies\n        for (const strategy of [\"compatible\", \"earlier\", \"later\"] as const) {\n          const result = DateTime.makeZoned(time, {\n            timeZone: zone,\n            adjustForTimeZone: true,\n            disambiguation: strategy\n          })\n          assertSomeIso(result, expectedResults[strategy])\n        }\n\n        // Test default behavior (\"compatible\")\n        const defaultResult = DateTime.makeZoned(time, {\n          timeZone: zone,\n          adjustForTimeZone: true\n        })\n        assertSomeIso(defaultResult, expectedResults.compatible)\n\n        // Test reject strategy\n        const rejectResult = DateTime.makeZoned(time, {\n          timeZone: zone,\n          adjustForTimeZone: true,\n          disambiguation: \"reject\"\n        })\n\n        if (expectedResults.reject === \"REJECT\") {\n          assertNone(rejectResult)\n        } else {\n          assertSomeIso(rejectResult, expectedResults.reject)\n        }\n      }\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Deferred.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Deferred, Effect, Exit, Option, pipe, Ref } from \"effect\"\n\ndescribe(\"Deferred\", () => {\n  it.effect(\"complete a deferred using succeed\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number>()\n      const success = yield* Deferred.succeed(deferred, 32)\n      const result = yield* Deferred.await(deferred)\n      assertTrue(success)\n      strictEqual(result, 32)\n    }))\n  it.effect(\"complete a deferred using complete\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number>()\n      const ref = yield* Ref.make(13)\n      yield* Deferred.complete(deferred, Ref.updateAndGet(ref, (n) => n + 1))\n      const result1 = yield* Deferred.await(deferred)\n      const result2 = yield* Deferred.await(deferred)\n      strictEqual(result1, 14)\n      strictEqual(result2, 14)\n    }))\n  it.effect(\"complete a deferred using completeWith\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number>()\n      const ref = yield* Ref.make(13)\n      yield* Deferred.completeWith(deferred, Ref.updateAndGet(ref, (n) => n + 1))\n      const result1 = yield* Deferred.await(deferred)\n      const result2 = yield* Deferred.await(deferred)\n      strictEqual(result1, 14)\n      strictEqual(result2, 15)\n    }))\n  it.effect(\"complete a deferred twice\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      yield* Deferred.succeed(deferred, 1)\n      const success = yield* Deferred.complete(deferred, Effect.succeed(9))\n      const result = yield* Deferred.await(deferred)\n      assertFalse(success)\n      strictEqual(result, 1)\n    }))\n  it.effect(\"fail a deferred using fail\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      const success = yield* Deferred.fail(deferred, \"error with fail\")\n      const result = yield* pipe(deferred, Deferred.await, Effect.exit)\n      assertTrue(success)\n      assertTrue(Exit.isFailure(result))\n    }))\n  it.effect(\"fail a deferred using complete\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      const ref = yield* Ref.make([\"first error\", \"second error\"])\n      const success = yield* Deferred.complete(deferred, Effect.flip(Ref.modify(ref, (as) => [as[0]!, as.slice(1)])))\n      const result1 = yield* pipe(deferred, Deferred.await, Effect.exit)\n      const result2 = yield* pipe(deferred, Deferred.await, Effect.exit)\n      assertTrue(success)\n      assertTrue(Exit.isFailure(result1))\n      assertTrue(Exit.isFailure(result2))\n    }))\n  it.effect(\"fail a deferred using completeWith\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      const ref = yield* Ref.make([\"first error\", \"second error\"])\n      const success = yield* Deferred.completeWith(\n        deferred,\n        Effect.flip(\n          Ref.modify(ref, (as) => [as[0]!, as.slice(1)])\n        )\n      )\n      const result1 = yield* pipe(deferred, Deferred.await, Effect.exit)\n      const result2 = yield* pipe(deferred, Deferred.await, Effect.exit)\n      assertTrue(success)\n      assertTrue(Exit.isFailure(result1))\n      assertTrue(Exit.isFailure(result2))\n    }))\n  it.effect(\"is done when a deferred is completed\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      yield* Deferred.succeed(deferred, 0)\n      const result = yield* Deferred.isDone(deferred)\n      assertTrue(result)\n    }))\n  it.effect(\"is done when a deferred is failed\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      yield* Deferred.fail(deferred, \"failure\")\n      const result = yield* Deferred.isDone(deferred)\n      assertTrue(result)\n    }))\n  it.effect(\"should interrupt a deferred\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      const result = yield* Deferred.interrupt(deferred)\n      assertTrue(result)\n    }))\n  it.effect(\"poll a deferred that is not completed yet\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      const result = yield* Deferred.poll(deferred)\n      assertTrue(Option.isNone(result))\n    }))\n  it.effect(\"poll a deferred that is completed\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      yield* Deferred.succeed(deferred, 12)\n      const result = yield* Deferred.poll(deferred).pipe(\n        Effect.flatMap(Option.match({\n          onNone: () => Effect.fail(\"fail\"),\n          onSome: Effect.succeed\n        })),\n        Effect.flatten,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.succeed(12))\n    }))\n  it.effect(\"poll a deferred that is failed\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      yield* Deferred.fail(deferred, \"failure\")\n      const result = yield* Deferred.poll(deferred).pipe(\n        Effect.flatMap(Option.match({\n          onNone: () => Effect.fail(\"fail\"),\n          onSome: Effect.succeed\n        })),\n        Effect.flatten,\n        Effect.exit\n      )\n      assertTrue(Exit.isFailure(result))\n    }))\n  it.effect(\"poll a deferred that is interrupted\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number, string>()\n      yield* Deferred.interrupt(deferred)\n      const result = yield* Deferred.poll(deferred).pipe(\n        Effect.flatMap(Option.match({\n          onNone: () => Effect.fail(\"fail\"),\n          onSome: Effect.succeed\n        })),\n        Effect.flatten,\n        Effect.exit\n      )\n      assertTrue(Exit.isInterrupted(result))\n    }))\n  it.effect(\"is subtype of Effect\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<number>()\n      const ref = yield* Ref.make(13)\n      yield* Deferred.complete(deferred, Ref.updateAndGet(ref, (n) => n + 1))\n      const result1 = yield* deferred\n      const result2 = yield* deferred\n      strictEqual(result1, 14)\n      strictEqual(result2, 14)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Differ.test.ts",
    "content": "import { describe, it as it_ } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Array as Arr, Chunk, Differ, Equal, HashMap, HashSet, pipe } from \"effect\"\n\nfunction diffLaws<Value, Patch>(\n  differ: Differ.Differ<Value, Patch>,\n  gen: () => Value,\n  equal: (a: Value, b: Value) => boolean\n): void {\n  const it = (name: string, f: () => void) =>\n    it_(name, () => {\n      for (let i = 0; i < 100; i++) {\n        f()\n      }\n    })\n\n  describe(\"differ laws\", () => {\n    it(\"combining patches is associative\", () => {\n      const value1 = gen()\n      const value2 = gen()\n      const value3 = gen()\n      const value4 = gen()\n      const patch1 = differ.diff(value1, value2)\n      const patch2 = differ.diff(value2, value3)\n      const patch3 = differ.diff(value3, value4)\n      const left = differ.combine(differ.combine(patch1, patch2), patch3)\n      const right = differ.combine(patch1, differ.combine(patch2, patch3))\n      assertTrue(equal(differ.patch(left, value1), differ.patch(right, value1)))\n    })\n\n    it(\"combining a patch with an empty patch is an identity\", () => {\n      const oldValue = gen()\n      const newValue = gen()\n      const patch = differ.diff(oldValue, newValue)\n      const left = differ.combine(patch, differ.empty)\n      const right = differ.combine(differ.empty, patch)\n      assertTrue(equal(differ.patch(left, oldValue), newValue))\n      assertTrue(equal(differ.patch(right, oldValue), newValue))\n    })\n\n    it(\"diffing a value with itself returns an empty patch\", () => {\n      const value = gen()\n      deepStrictEqual(differ.diff(value, value), differ.empty)\n    })\n\n    it(\"diffing and then patching is an identity\", () => {\n      const oldValue = gen()\n      const newValue = gen()\n      const patch = differ.diff(oldValue, newValue)\n      assertTrue(equal(differ.patch(patch, oldValue), newValue))\n    })\n\n    it(\"patching with an empty patch is an identity\", () => {\n      const value = gen()\n      assertTrue(equal(differ.patch(differ.empty, value), value))\n    })\n  })\n}\n\nconst min = 1\nconst max = 100\n\nfunction smallInt(): number {\n  return Math.floor(Math.random() * (max - min + 1) + min)\n}\n\nfunction randomChunk(): Chunk.Chunk<number> {\n  return Chunk.fromIterable(Array.from({ length: 20 }, smallInt))\n}\n\nfunction randomHashMap(): HashMap.HashMap<number, number> {\n  return pipe(\n    Arr.fromIterable(Array.from({ length: 2 }, smallInt)),\n    Arr.cartesian(Arr.fromIterable(Array.from({ length: 2 }, smallInt))),\n    HashMap.fromIterable\n  )\n}\n\nfunction randomHashSet(): HashSet.HashSet<number> {\n  return HashSet.fromIterable(Array.from({ length: 20 }, smallInt))\n}\n\nfunction randomReadonlyArray(): ReadonlyArray<number> {\n  return Array.from({ length: 20 }, smallInt)\n}\n\nfunction randomPair(): readonly [number, number] {\n  return [smallInt(), smallInt()]\n}\n\ndescribe(\"Differ\", () => {\n  describe(\"chunk\", () => {\n    diffLaws(\n      Differ.chunk<number, (n: number) => number>(Differ.update()),\n      randomChunk,\n      Equal.equals\n    )\n  })\n\n  describe(\"hashMap\", () => {\n    diffLaws(\n      Differ.hashMap<number, number, (n: number) => number>(Differ.update<number>()),\n      randomHashMap,\n      Equal.equals\n    )\n  })\n\n  describe(\"hashSet\", () => {\n    diffLaws(\n      Differ.hashSet<number>(),\n      randomHashSet,\n      Equal.equals\n    )\n  })\n\n  describe(\"readonlyArray\", () => {\n    diffLaws(\n      Differ.readonlyArray<number, (n: number) => number>(Differ.update()),\n      randomReadonlyArray,\n      Arr.getEquivalence(Equal.equals)\n    )\n  })\n\n  describe(\"tuple\", () => {\n    diffLaws(\n      Differ.update<number>()\n        .pipe(\n          Differ.zip(Differ.update<number>())\n        ),\n      randomPair,\n      (a, b) => Equal.equals(a[0], b[0]) && Equal.equals(a[1], b[1])\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Duration.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertNone,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { Duration, Equal, pipe } from \"effect\"\n\ndescribe(\"Duration\", () => {\n  it(\"decode\", () => {\n    const millis100 = Duration.millis(100)\n    assertTrue(Duration.decode(millis100) === millis100)\n\n    deepStrictEqual(Duration.decode(100), millis100)\n\n    deepStrictEqual(Duration.decode(10n), Duration.nanos(10n))\n\n    deepStrictEqual(Duration.decode(\"1 nano\"), Duration.nanos(1n))\n    deepStrictEqual(Duration.decode(\"10 nanos\"), Duration.nanos(10n))\n    deepStrictEqual(Duration.decode(\"1 micro\"), Duration.micros(1n))\n    deepStrictEqual(Duration.decode(\"10 micros\"), Duration.micros(10n))\n    deepStrictEqual(Duration.decode(\"1 milli\"), Duration.millis(1))\n    deepStrictEqual(Duration.decode(\"10 millis\"), Duration.millis(10))\n    deepStrictEqual(Duration.decode(\"1 second\"), Duration.seconds(1))\n    deepStrictEqual(Duration.decode(\"10 seconds\"), Duration.seconds(10))\n    deepStrictEqual(Duration.decode(\"1 minute\"), Duration.minutes(1))\n    deepStrictEqual(Duration.decode(\"10 minutes\"), Duration.minutes(10))\n    deepStrictEqual(Duration.decode(\"1 hour\"), Duration.hours(1))\n    deepStrictEqual(Duration.decode(\"10 hours\"), Duration.hours(10))\n    deepStrictEqual(Duration.decode(\"1 day\"), Duration.days(1))\n    deepStrictEqual(Duration.decode(\"10 days\"), Duration.days(10))\n    deepStrictEqual(Duration.decode(\"1 week\"), Duration.weeks(1))\n    deepStrictEqual(Duration.decode(\"10 weeks\"), Duration.weeks(10))\n\n    deepStrictEqual(Duration.decode(\"1.5 seconds\"), Duration.seconds(1.5))\n    deepStrictEqual(Duration.decode(\"-1.5 seconds\"), Duration.zero)\n\n    deepStrictEqual(Duration.decode([500, 123456789]), Duration.nanos(500123456789n))\n    deepStrictEqual(Duration.decode([-500, 123456789]), Duration.zero)\n    deepStrictEqual(Duration.decode([Infinity, 0]), Duration.infinity)\n    deepStrictEqual(Duration.decode([-Infinity, 0]), Duration.zero)\n    deepStrictEqual(Duration.decode([NaN, 0]), Duration.zero)\n    deepStrictEqual(Duration.decode([0, Infinity]), Duration.infinity)\n    deepStrictEqual(Duration.decode([0, -Infinity]), Duration.zero)\n    deepStrictEqual(Duration.decode([0, NaN]), Duration.zero)\n    throws(() => Duration.decode(\"1.5 secs\" as any), new Error(\"Invalid DurationInput\"))\n    throws(() => Duration.decode(true as any), new Error(\"Invalid DurationInput\"))\n    throws(() => Duration.decode({} as any), new Error(\"Invalid DurationInput\"))\n  })\n\n  it(\"decodeUnknown\", () => {\n    const millis100 = Duration.millis(100)\n    assertSome(Duration.decodeUnknown(millis100), millis100)\n\n    assertSome(Duration.decodeUnknown(100), millis100)\n\n    assertSome(Duration.decodeUnknown(10n), Duration.nanos(10n))\n\n    assertSome(Duration.decodeUnknown(\"1 nano\"), Duration.nanos(1n))\n    assertSome(Duration.decodeUnknown(\"10 nanos\"), Duration.nanos(10n))\n    assertSome(Duration.decodeUnknown(\"1 micro\"), Duration.micros(1n))\n    assertSome(Duration.decodeUnknown(\"10 micros\"), Duration.micros(10n))\n    assertSome(Duration.decodeUnknown(\"1 milli\"), Duration.millis(1))\n    assertSome(Duration.decodeUnknown(\"10 millis\"), Duration.millis(10))\n    assertSome(Duration.decodeUnknown(\"1 second\"), Duration.seconds(1))\n    assertSome(Duration.decodeUnknown(\"10 seconds\"), Duration.seconds(10))\n    assertSome(Duration.decodeUnknown(\"1 minute\"), Duration.minutes(1))\n    assertSome(Duration.decodeUnknown(\"10 minutes\"), Duration.minutes(10))\n    assertSome(Duration.decodeUnknown(\"1 hour\"), Duration.hours(1))\n    assertSome(Duration.decodeUnknown(\"10 hours\"), Duration.hours(10))\n    assertSome(Duration.decodeUnknown(\"1 day\"), Duration.days(1))\n    assertSome(Duration.decodeUnknown(\"10 days\"), Duration.days(10))\n    assertSome(Duration.decodeUnknown(\"1 week\"), Duration.weeks(1))\n    assertSome(Duration.decodeUnknown(\"10 weeks\"), Duration.weeks(10))\n\n    assertSome(Duration.decodeUnknown(\"1.5 seconds\"), Duration.seconds(1.5))\n    assertSome(Duration.decodeUnknown(\"-1.5 seconds\"), Duration.zero)\n\n    assertSome(Duration.decodeUnknown([500, 123456789]), Duration.nanos(500123456789n))\n    assertSome(Duration.decodeUnknown([-500, 123456789]), Duration.zero)\n    assertSome(Duration.decodeUnknown([Infinity, 0]), Duration.infinity)\n    assertSome(Duration.decodeUnknown([-Infinity, 0]), Duration.zero)\n    assertSome(Duration.decodeUnknown([NaN, 0]), Duration.zero)\n    assertSome(Duration.decodeUnknown([0, Infinity]), Duration.infinity)\n    assertSome(Duration.decodeUnknown([0, -Infinity]), Duration.zero)\n    assertSome(Duration.decodeUnknown([0, NaN]), Duration.zero)\n    assertNone(Duration.decodeUnknown(\"1.5 secs\"))\n    assertNone(Duration.decodeUnknown(true))\n    assertNone(Duration.decodeUnknown({}))\n  })\n\n  it(\"Order\", () => {\n    deepStrictEqual(Duration.Order(Duration.millis(1), Duration.millis(2)), -1)\n    deepStrictEqual(Duration.Order(Duration.millis(2), Duration.millis(1)), 1)\n    deepStrictEqual(Duration.Order(Duration.millis(2), Duration.millis(2)), 0)\n\n    deepStrictEqual(Duration.Order(Duration.nanos(1n), Duration.nanos(2n)), -1)\n    deepStrictEqual(Duration.Order(Duration.nanos(2n), Duration.nanos(1n)), 1)\n    deepStrictEqual(Duration.Order(Duration.nanos(2n), Duration.nanos(2n)), 0)\n  })\n\n  it(\"Equivalence\", () => {\n    deepStrictEqual(Duration.Equivalence(Duration.millis(1), Duration.millis(1)), true)\n    deepStrictEqual(Duration.Equivalence(Duration.millis(1), Duration.millis(2)), false)\n    deepStrictEqual(Duration.Equivalence(Duration.millis(1), Duration.millis(2)), false)\n\n    deepStrictEqual(Duration.Equivalence(Duration.nanos(1n), Duration.nanos(1n)), true)\n    deepStrictEqual(Duration.Equivalence(Duration.nanos(1n), Duration.nanos(2n)), false)\n    deepStrictEqual(Duration.Equivalence(Duration.nanos(1n), Duration.nanos(2n)), false)\n  })\n\n  it(\"max\", () => {\n    deepStrictEqual(Duration.max(Duration.millis(1), Duration.millis(2)), Duration.millis(2))\n    deepStrictEqual(Duration.max(Duration.minutes(1), Duration.millis(2)), Duration.minutes(1))\n\n    deepStrictEqual(Duration.max(\"1 minutes\", \"2 millis\"), Duration.minutes(1))\n  })\n\n  it(\"min\", () => {\n    deepStrictEqual(Duration.min(Duration.millis(1), Duration.millis(2)), Duration.millis(1))\n    deepStrictEqual(Duration.min(Duration.minutes(1), Duration.millis(2)), Duration.millis(2))\n\n    deepStrictEqual(Duration.min(\"1 minutes\", \"2 millis\"), Duration.millis(2))\n  })\n\n  it(\"clamp\", () => {\n    deepStrictEqual(\n      Duration.clamp(Duration.millis(1), {\n        minimum: Duration.millis(2),\n        maximum: Duration.millis(3)\n      }),\n      Duration.millis(2)\n    )\n    deepStrictEqual(\n      Duration.clamp(Duration.minutes(1.5), {\n        minimum: Duration.minutes(1),\n        maximum: Duration.minutes(2)\n      }),\n      Duration.minutes(1.5)\n    )\n\n    deepStrictEqual(\n      Duration.clamp(\"1 millis\", {\n        minimum: \"2 millis\",\n        maximum: \"3 millis\"\n      }),\n      Duration.millis(2)\n    )\n  })\n\n  it(\"equals\", () => {\n    assertTrue(pipe(Duration.hours(1), Duration.equals(Duration.minutes(60))))\n    assertTrue(Duration.equals(\"2 seconds\", \"2 seconds\"))\n    assertFalse(Duration.equals(\"2 seconds\", \"3 seconds\"))\n  })\n\n  it(\"between\", () => {\n    assertTrue(Duration.between(Duration.hours(1), {\n      minimum: Duration.minutes(59),\n      maximum: Duration.minutes(61)\n    }))\n    assertTrue(\n      Duration.between(Duration.minutes(1), {\n        minimum: Duration.seconds(59),\n        maximum: Duration.seconds(61)\n      })\n    )\n\n    assertTrue(Duration.between(\"1 minutes\", {\n      minimum: \"59 seconds\",\n      maximum: \"61 seconds\"\n    }))\n  })\n\n  it(\"divide\", () => {\n    assertSome(Duration.divide(Duration.minutes(1), 2), Duration.seconds(30))\n    assertSome(Duration.divide(Duration.seconds(1), 3), Duration.nanos(333333333n))\n    assertSome(Duration.divide(Duration.nanos(2n), 2), Duration.nanos(1n))\n    assertSome(Duration.divide(Duration.nanos(1n), 3), Duration.zero)\n    assertSome(Duration.divide(Duration.infinity, 2), Duration.infinity)\n    assertSome(Duration.divide(Duration.zero, 2), Duration.zero)\n    assertNone(Duration.divide(Duration.minutes(1), 0))\n    assertNone(Duration.divide(Duration.minutes(1), -0))\n    assertNone(Duration.divide(Duration.nanos(1n), 0))\n    assertNone(Duration.divide(Duration.nanos(1n), -0))\n    assertSome(Duration.divide(Duration.minutes(1), 0.5), Duration.minutes(2))\n    assertSome(Duration.divide(Duration.minutes(1), 1.5), Duration.seconds(40))\n    assertNone(Duration.divide(Duration.minutes(1), NaN))\n    assertNone(Duration.divide(Duration.nanos(1n), 0.5))\n    assertNone(Duration.divide(Duration.nanos(1n), 1.5))\n    assertNone(Duration.divide(Duration.nanos(1n), NaN))\n\n    assertSome(Duration.divide(\"1 minute\", 2), Duration.seconds(30))\n  })\n\n  it(\"unsafeDivide\", () => {\n    deepStrictEqual(Duration.unsafeDivide(Duration.minutes(1), 2), Duration.seconds(30))\n    deepStrictEqual(Duration.unsafeDivide(Duration.seconds(1), 3), Duration.nanos(333333333n))\n    deepStrictEqual(Duration.unsafeDivide(Duration.nanos(2n), 2), Duration.nanos(1n))\n    deepStrictEqual(Duration.unsafeDivide(Duration.nanos(1n), 3), Duration.zero)\n    deepStrictEqual(Duration.unsafeDivide(Duration.infinity, 2), Duration.infinity)\n    deepStrictEqual(Duration.unsafeDivide(Duration.zero, 2), Duration.zero)\n    deepStrictEqual(Duration.unsafeDivide(Duration.minutes(1), 0), Duration.infinity)\n    deepStrictEqual(Duration.unsafeDivide(Duration.minutes(1), -0), Duration.zero)\n    deepStrictEqual(Duration.unsafeDivide(Duration.nanos(1n), 0), Duration.infinity)\n    deepStrictEqual(Duration.unsafeDivide(Duration.nanos(1n), -0), Duration.zero)\n    deepStrictEqual(Duration.unsafeDivide(Duration.minutes(1), 0.5), Duration.minutes(2))\n    deepStrictEqual(Duration.unsafeDivide(Duration.minutes(1), 1.5), Duration.seconds(40))\n    deepStrictEqual(Duration.unsafeDivide(Duration.minutes(1), NaN), Duration.zero)\n    throws(() => Duration.unsafeDivide(Duration.nanos(1n), 0.5))\n    throws(() => Duration.unsafeDivide(Duration.nanos(1n), 1.5))\n    deepStrictEqual(Duration.unsafeDivide(Duration.nanos(1n), NaN), Duration.zero)\n\n    deepStrictEqual(Duration.unsafeDivide(\"1 minute\", 2), Duration.seconds(30))\n  })\n\n  it(\"times\", () => {\n    deepStrictEqual(Duration.times(Duration.seconds(1), 60), Duration.minutes(1))\n    deepStrictEqual(Duration.times(Duration.nanos(2n), 10), Duration.nanos(20n))\n    deepStrictEqual(Duration.times(Duration.seconds(Infinity), 60), Duration.seconds(Infinity))\n\n    deepStrictEqual(Duration.times(\"1 seconds\", 60), Duration.minutes(1))\n  })\n\n  it(\"sum\", () => {\n    deepStrictEqual(Duration.sum(Duration.seconds(30), Duration.seconds(30)), Duration.minutes(1))\n    deepStrictEqual(Duration.sum(Duration.nanos(30n), Duration.nanos(30n)), Duration.nanos(60n))\n    deepStrictEqual(Duration.sum(Duration.seconds(Infinity), Duration.seconds(30)), Duration.seconds(Infinity))\n    deepStrictEqual(Duration.sum(Duration.seconds(30), Duration.seconds(Infinity)), Duration.seconds(Infinity))\n\n    deepStrictEqual(Duration.sum(\"30 seconds\", \"30 seconds\"), Duration.minutes(1))\n  })\n\n  it(\"subtract\", () => {\n    deepStrictEqual(Duration.subtract(Duration.seconds(30), Duration.seconds(10)), Duration.seconds(20))\n    deepStrictEqual(Duration.subtract(Duration.seconds(30), Duration.seconds(30)), Duration.zero)\n    deepStrictEqual(Duration.subtract(Duration.nanos(30n), Duration.nanos(10n)), Duration.nanos(20n))\n    deepStrictEqual(Duration.subtract(Duration.nanos(30n), Duration.nanos(30n)), Duration.zero)\n    deepStrictEqual(Duration.subtract(Duration.seconds(Infinity), Duration.seconds(30)), Duration.seconds(Infinity))\n    deepStrictEqual(Duration.subtract(Duration.seconds(30), Duration.seconds(Infinity)), Duration.zero)\n\n    deepStrictEqual(Duration.subtract(\"30 seconds\", \"10 seconds\"), Duration.seconds(20))\n  })\n\n  it(\"greaterThan\", () => {\n    assertTrue(pipe(Duration.seconds(30), Duration.greaterThan(Duration.seconds(20))))\n    assertFalse(pipe(Duration.seconds(30), Duration.greaterThan(Duration.seconds(30))))\n    assertFalse(pipe(Duration.seconds(30), Duration.greaterThan(Duration.seconds(60))))\n\n    assertTrue(pipe(Duration.nanos(30n), Duration.greaterThan(Duration.nanos(20n))))\n    assertFalse(pipe(Duration.nanos(30n), Duration.greaterThan(Duration.nanos(30n))))\n    assertFalse(pipe(Duration.nanos(30n), Duration.greaterThan(Duration.nanos(60n))))\n\n    assertTrue(pipe(Duration.millis(1), Duration.greaterThan(Duration.nanos(1n))))\n\n    assertFalse(Duration.greaterThan(\"2 seconds\", \"2 seconds\"))\n    assertTrue(Duration.greaterThan(\"3 seconds\", \"2 seconds\"))\n    assertFalse(Duration.greaterThan(\"2 seconds\", \"3 seconds\"))\n  })\n\n  it(\"greaterThan - Infinity\", () => {\n    assertTrue(pipe(Duration.infinity, Duration.greaterThan(Duration.seconds(20))))\n    assertFalse(pipe(Duration.seconds(-Infinity), Duration.greaterThan(Duration.infinity)))\n    assertFalse(pipe(Duration.nanos(1n), Duration.greaterThan(Duration.infinity)))\n  })\n\n  it(\"greaterThanOrEqualTo\", () => {\n    assertTrue(pipe(Duration.seconds(30), Duration.greaterThanOrEqualTo(Duration.seconds(20))))\n    assertTrue(pipe(Duration.seconds(30), Duration.greaterThanOrEqualTo(Duration.seconds(30))))\n    assertFalse(pipe(Duration.seconds(30), Duration.greaterThanOrEqualTo(Duration.seconds(60))))\n\n    assertTrue(pipe(Duration.nanos(30n), Duration.greaterThanOrEqualTo(Duration.nanos(20n))))\n    assertTrue(pipe(Duration.nanos(30n), Duration.greaterThanOrEqualTo(Duration.nanos(30n))))\n    assertFalse(pipe(Duration.nanos(30n), Duration.greaterThanOrEqualTo(Duration.nanos(60n))))\n\n    assertTrue(Duration.greaterThanOrEqualTo(\"2 seconds\", \"2 seconds\"))\n    assertTrue(Duration.greaterThanOrEqualTo(\"3 seconds\", \"2 seconds\"))\n    assertFalse(Duration.greaterThanOrEqualTo(\"2 seconds\", \"3 seconds\"))\n  })\n\n  it(\"lessThan\", () => {\n    assertTrue(pipe(Duration.seconds(20), Duration.lessThan(Duration.seconds(30))))\n    assertFalse(pipe(Duration.seconds(30), Duration.lessThan(Duration.seconds(30))))\n    assertFalse(pipe(Duration.seconds(60), Duration.lessThan(Duration.seconds(30))))\n\n    assertTrue(pipe(Duration.nanos(20n), Duration.lessThan(Duration.nanos(30n))))\n    assertFalse(pipe(Duration.nanos(30n), Duration.lessThan(Duration.nanos(30n))))\n    assertFalse(pipe(Duration.nanos(60n), Duration.lessThan(Duration.nanos(30n))))\n\n    assertTrue(pipe(Duration.nanos(1n), Duration.lessThan(Duration.millis(1))))\n\n    assertFalse(Duration.lessThan(\"2 seconds\", \"2 seconds\"))\n    assertFalse(Duration.lessThan(\"3 seconds\", \"2 seconds\"))\n    assertTrue(Duration.lessThan(\"2 seconds\", \"3 seconds\"))\n  })\n\n  it(\"lessThanOrEqualTo\", () => {\n    assertTrue(pipe(Duration.seconds(20), Duration.lessThanOrEqualTo(Duration.seconds(30))))\n    assertTrue(pipe(Duration.seconds(30), Duration.lessThanOrEqualTo(Duration.seconds(30))))\n    assertFalse(pipe(Duration.seconds(60), Duration.lessThanOrEqualTo(Duration.seconds(30))))\n\n    assertTrue(pipe(Duration.nanos(20n), Duration.lessThanOrEqualTo(Duration.nanos(30n))))\n    assertTrue(pipe(Duration.nanos(30n), Duration.lessThanOrEqualTo(Duration.nanos(30n))))\n    assertFalse(pipe(Duration.nanos(60n), Duration.lessThanOrEqualTo(Duration.nanos(30n))))\n\n    assertTrue(Duration.lessThanOrEqualTo(\"2 seconds\", \"2 seconds\"))\n    assertFalse(Duration.lessThanOrEqualTo(\"3 seconds\", \"2 seconds\"))\n    assertTrue(Duration.lessThanOrEqualTo(\"2 seconds\", \"3 seconds\"))\n  })\n\n  it(\"String()\", () => {\n    strictEqual(String(Duration.infinity), `Duration(Infinity)`)\n    strictEqual(String(Duration.nanos(10n)), `Duration(10ns)`)\n    strictEqual(String(Duration.millis(2)), `Duration(2ms)`)\n    strictEqual(String(Duration.millis(2.125)), `Duration(2ms 125000ns)`)\n    strictEqual(String(Duration.seconds(2)), `Duration(2s)`)\n    strictEqual(String(Duration.seconds(2.5)), `Duration(2s 500ms)`)\n  })\n\n  it(\"format\", () => {\n    strictEqual(Duration.format(Duration.infinity), `Infinity`)\n    strictEqual(Duration.format(Duration.minutes(5)), `5m`)\n    strictEqual(Duration.format(Duration.minutes(5.325)), `5m 19s 500ms`)\n    strictEqual(Duration.format(Duration.hours(3)), `3h`)\n    strictEqual(Duration.format(Duration.hours(3.11125)), `3h 6m 40s 500ms`)\n    strictEqual(Duration.format(Duration.days(2)), `2d`)\n    strictEqual(Duration.format(Duration.days(2.25)), `2d 6h`)\n    strictEqual(Duration.format(Duration.weeks(1)), `7d`)\n    strictEqual(Duration.format(Duration.zero), `0`)\n  })\n\n  it(\"format\", () => {\n    deepStrictEqual(Duration.parts(Duration.infinity), {\n      days: Infinity,\n      hours: Infinity,\n      minutes: Infinity,\n      seconds: Infinity,\n      millis: Infinity,\n      nanos: Infinity\n    })\n\n    deepStrictEqual(Duration.parts(Duration.minutes(5.325)), {\n      days: 0,\n      hours: 0,\n      minutes: 5,\n      seconds: 19,\n      millis: 500,\n      nanos: 0\n    })\n\n    deepStrictEqual(Duration.parts(Duration.minutes(3.11125)), {\n      days: 0,\n      hours: 0,\n      minutes: 3,\n      seconds: 6,\n      millis: 675,\n      nanos: 0\n    })\n  })\n\n  it(\"toJSON\", () => {\n    deepStrictEqual(Duration.seconds(2).toJSON(), { _id: \"Duration\", _tag: \"Millis\", millis: 2000 })\n  })\n\n  it(\"toJSON/ non-integer millis\", () => {\n    deepStrictEqual(Duration.millis(1.5).toJSON(), { _id: \"Duration\", _tag: \"Nanos\", hrtime: [0, 1_500_000] })\n  })\n\n  it(\"toJSON/ nanos\", () => {\n    deepStrictEqual(Duration.nanos(5n).toJSON(), { _id: \"Duration\", _tag: \"Nanos\", hrtime: [0, 5] })\n  })\n\n  it(\"toJSON/ infinity\", () => {\n    deepStrictEqual(Duration.infinity.toJSON(), { _id: \"Duration\", _tag: \"Infinity\" })\n  })\n\n  it(`inspect`, () => {\n    if (typeof window === \"undefined\") {\n      // eslint-disable-next-line @typescript-eslint/no-require-imports\n      const { inspect } = require(\"node:util\")\n      deepStrictEqual(inspect(Duration.millis(1000)), inspect({ _id: \"Duration\", _tag: \"Millis\", millis: 1000 }))\n    }\n  })\n\n  it(\"sum/ Infinity\", () => {\n    deepStrictEqual(Duration.sum(Duration.seconds(1), Duration.infinity), Duration.infinity)\n  })\n\n  it(\".pipe()\", () => {\n    deepStrictEqual(Duration.seconds(1).pipe(Duration.sum(Duration.seconds(1))), Duration.seconds(2))\n  })\n\n  it(\"isDuration\", () => {\n    assertTrue(Duration.isDuration(Duration.millis(100)))\n    assertFalse(Duration.isDuration(null))\n  })\n\n  it(\"zero\", () => {\n    deepStrictEqual(Duration.zero.value, { _tag: \"Millis\", millis: 0 })\n  })\n\n  it(\"infinity\", () => {\n    deepStrictEqual(Duration.infinity.value, { _tag: \"Infinity\" })\n  })\n\n  it(\"weeks\", () => {\n    assertTrue(Equal.equals(Duration.weeks(1), Duration.days(7)))\n    assertFalse(Equal.equals(Duration.weeks(1), Duration.days(1)))\n  })\n\n  it(\"toMillis\", () => {\n    strictEqual(Duration.millis(1).pipe(Duration.toMillis), 1)\n    strictEqual(Duration.nanos(1n).pipe(Duration.toMillis), 0.000001)\n    strictEqual(Duration.infinity.pipe(Duration.toMillis), Infinity)\n\n    strictEqual(Duration.toMillis(\"1 millis\"), 1)\n  })\n\n  it(\"toSeconds\", () => {\n    strictEqual(Duration.millis(1).pipe(Duration.toSeconds), 0.001)\n    strictEqual(Duration.nanos(1n).pipe(Duration.toSeconds), 1e-9)\n    strictEqual(Duration.infinity.pipe(Duration.toSeconds), Infinity)\n\n    strictEqual(Duration.toSeconds(\"1 seconds\"), 1)\n    strictEqual(Duration.toSeconds(\"3 seconds\"), 3)\n    strictEqual(Duration.toSeconds(\"3 minutes\"), 180)\n  })\n\n  it(\"toNanos\", () => {\n    assertSome(Duration.nanos(1n).pipe(Duration.toNanos), 1n)\n    assertNone(Duration.infinity.pipe(Duration.toNanos))\n    assertSome(Duration.millis(1.0005).pipe(Duration.toNanos), 1_000_500n)\n    assertSome(Duration.millis(100).pipe(Duration.toNanos), 100_000_000n)\n\n    assertSome(Duration.toNanos(\"1 nanos\"), 1n)\n  })\n\n  it(\"unsafeToNanos\", () => {\n    strictEqual(Duration.nanos(1n).pipe(Duration.unsafeToNanos), 1n)\n    throws(() => Duration.infinity.pipe(Duration.unsafeToNanos))\n    strictEqual(Duration.millis(1.0005).pipe(Duration.unsafeToNanos), 1_000_500n)\n    strictEqual(Duration.millis(100).pipe(Duration.unsafeToNanos), 100_000_000n)\n\n    strictEqual(Duration.unsafeToNanos(\"1 nanos\"), 1n)\n  })\n\n  it(\"toHrTime\", () => {\n    deepStrictEqual(Duration.millis(1).pipe(Duration.toHrTime), [0, 1_000_000])\n    deepStrictEqual(Duration.nanos(1n).pipe(Duration.toHrTime), [0, 1])\n    deepStrictEqual(Duration.nanos(1_000_000_001n).pipe(Duration.toHrTime), [1, 1])\n    deepStrictEqual(Duration.millis(1001).pipe(Duration.toHrTime), [1, 1_000_000])\n    deepStrictEqual(Duration.infinity.pipe(Duration.toHrTime), [Infinity, 0])\n\n    deepStrictEqual(Duration.toHrTime(\"1 millis\"), [0, 1_000_000])\n  })\n\n  it(\"floor is 0\", () => {\n    deepStrictEqual(Duration.millis(-1), Duration.zero)\n    deepStrictEqual(Duration.nanos(-1n), Duration.zero)\n  })\n\n  it(\"match\", () => {\n    const match = Duration.match({\n      onMillis: () => \"millis\",\n      onNanos: () => \"nanos\"\n    })\n    strictEqual(match(Duration.decode(\"100 millis\")), \"millis\")\n    strictEqual(match(Duration.decode(\"10 nanos\")), \"nanos\")\n    strictEqual(match(Duration.decode(Infinity)), \"millis\")\n\n    strictEqual(match(\"100 millis\"), \"millis\")\n  })\n\n  it(\"isFinite\", () => {\n    assertTrue(Duration.isFinite(Duration.millis(100)))\n    assertTrue(Duration.isFinite(Duration.nanos(100n)))\n    assertFalse(Duration.isFinite(Duration.infinity))\n  })\n\n  it(\"isZero\", () => {\n    assertTrue(Duration.isZero(Duration.zero))\n    assertTrue(Duration.isZero(Duration.millis(0)))\n    assertTrue(Duration.isZero(Duration.nanos(0n)))\n    assertFalse(Duration.isZero(Duration.infinity))\n    assertFalse(Duration.isZero(Duration.millis(1)))\n    assertFalse(Duration.isZero(Duration.nanos(1n)))\n  })\n\n  it(\"toMinutes\", () => {\n    strictEqual(Duration.millis(60000).pipe(Duration.toMinutes), 1)\n    strictEqual(Duration.nanos(60000000000n).pipe(Duration.toMinutes), 1)\n    strictEqual(Duration.infinity.pipe(Duration.toMinutes), Infinity)\n\n    strictEqual(Duration.toMinutes(\"1 minute\"), 1)\n    strictEqual(Duration.toMinutes(\"2 minutes\"), 2)\n    strictEqual(Duration.toMinutes(\"1 hour\"), 60)\n  })\n\n  it(\"toHours\", () => {\n    strictEqual(Duration.millis(3_600_000).pipe(Duration.toHours), 1)\n    strictEqual(Duration.nanos(3_600_000_000_000n).pipe(Duration.toHours), 1)\n    strictEqual(Duration.infinity.pipe(Duration.toHours), Infinity)\n\n    strictEqual(Duration.toHours(\"1 hour\"), 1)\n    strictEqual(Duration.toHours(\"2 hours\"), 2)\n    strictEqual(Duration.toHours(\"1 day\"), 24)\n  })\n\n  it(\"toDays\", () => {\n    strictEqual(Duration.millis(86_400_000).pipe(Duration.toDays), 1)\n    strictEqual(Duration.nanos(86_400_000_000_000n).pipe(Duration.toDays), 1)\n    strictEqual(Duration.infinity.pipe(Duration.toDays), Infinity)\n\n    strictEqual(Duration.toDays(\"1 day\"), 1)\n    strictEqual(Duration.toDays(\"2 days\"), 2)\n    strictEqual(Duration.toDays(\"1 week\"), 7)\n  })\n\n  it(\"toWeeks\", () => {\n    strictEqual(Duration.millis(604_800_000).pipe(Duration.toWeeks), 1)\n    strictEqual(Duration.nanos(604_800_000_000_000n).pipe(Duration.toWeeks), 1)\n    strictEqual(Duration.infinity.pipe(Duration.toWeeks), Infinity)\n\n    strictEqual(Duration.toWeeks(\"1 week\"), 1)\n    strictEqual(Duration.toWeeks(\"2 weeks\"), 2)\n    strictEqual(Duration.toWeeks(\"14 days\"), 2)\n  })\n\n  it(\"formatIso\", () => {\n    assertSome(Duration.formatIso(Duration.zero), \"PT0S\")\n    assertSome(Duration.formatIso(Duration.seconds(2)), \"PT2S\")\n    assertSome(Duration.formatIso(Duration.minutes(5)), \"PT5M\")\n    assertSome(Duration.formatIso(Duration.hours(3)), \"PT3H\")\n    assertSome(Duration.formatIso(Duration.days(1)), \"P1D\")\n\n    assertSome(Duration.formatIso(Duration.minutes(90)), \"PT1H30M\")\n    assertSome(Duration.formatIso(Duration.hours(25)), \"P1DT1H\")\n    assertSome(Duration.formatIso(Duration.days(7)), \"P1W\")\n    assertSome(Duration.formatIso(Duration.days(10)), \"P1W3D\")\n\n    assertSome(Duration.formatIso(Duration.millis(1500)), \"PT1.5S\")\n    assertSome(Duration.formatIso(Duration.micros(1500n)), \"PT0.0015S\")\n    assertSome(Duration.formatIso(Duration.nanos(1500n)), \"PT0.0000015S\")\n\n    assertSome(\n      Duration.formatIso(\n        Duration.seconds(\n          365 * 24 * 60 * 60 + // 1 year\n            60 * 24 * 60 * 60 + // 2 months\n            3 * 24 * 60 * 60 + // 3 days\n            4 * 60 * 60 + // 4 hours\n            5 * 60 + // 5 minutes\n            6.789 // 6.789 seconds\n        )\n      ),\n      \"P1Y2M3DT4H5M6.789S\"\n    )\n\n    assertSome(\n      Duration.formatIso(\n        Duration.days(1).pipe(\n          Duration.sum(Duration.hours(2)),\n          Duration.sum(Duration.minutes(30))\n        )\n      ),\n      \"P1DT2H30M\"\n    )\n\n    assertSome(\n      Duration.formatIso(\n        Duration.hours(2).pipe(\n          Duration.sum(Duration.minutes(30)),\n          Duration.sum(Duration.millis(1500))\n        )\n      ),\n      \"PT2H30M1.5S\"\n    )\n\n    assertSome(Duration.formatIso(\"1 day\"), \"P1D\")\n    assertSome(Duration.formatIso(\"90 minutes\"), \"PT1H30M\")\n    assertSome(Duration.formatIso(\"1.5 seconds\"), \"PT1.5S\")\n\n    assertNone(Duration.formatIso(Duration.infinity))\n  })\n\n  it(\"fromIso\", () => {\n    assertSome(Duration.fromIso(\"P1D\"), Duration.days(1))\n    assertSome(Duration.fromIso(\"PT1H\"), Duration.hours(1))\n    assertSome(Duration.fromIso(\"PT1M\"), Duration.minutes(1))\n    assertSome(Duration.fromIso(\"PT1.5S\"), Duration.seconds(1.5))\n    assertSome(Duration.fromIso(\"P1Y\"), Duration.days(365))\n    assertSome(Duration.fromIso(\"P1M\"), Duration.days(30))\n    assertSome(Duration.fromIso(\"P1W\"), Duration.days(7))\n    assertSome(Duration.fromIso(\"P1DT12H\"), Duration.hours(36))\n    assertSome(\n      Duration.fromIso(\"P1Y2M3DT4H5M6.789S\"),\n      Duration.seconds(\n        365 * 24 * 60 * 60 + // 1 year\n          60 * 24 * 60 * 60 + // 2 months\n          3 * 24 * 60 * 60 + // 3 days\n          4 * 60 * 60 + // 4 hours\n          5 * 60 + // 5 minutes\n          6.789 // 6.789 seconds\n      )\n    )\n\n    assertNone(Duration.fromIso(\"1D\"))\n    assertNone(Duration.fromIso(\"P1H\"))\n    assertNone(Duration.fromIso(\"PT1D\"))\n    assertNone(Duration.fromIso(\"P1.5D\"))\n    assertNone(Duration.fromIso(\"P1.5Y\"))\n    assertNone(Duration.fromIso(\"P1.5M\"))\n    assertNone(Duration.fromIso(\"PT1.5H\"))\n    assertNone(Duration.fromIso(\"PT1.5M\"))\n    assertNone(Duration.fromIso(\"PDT1H\"))\n    assertNone(Duration.fromIso(\"P1D2H\"))\n    assertNone(Duration.fromIso(\"P\"))\n    assertNone(Duration.fromIso(\"PT\"))\n    assertNone(Duration.fromIso(\"random string\"))\n    assertNone(Duration.fromIso(\"P1YT\"))\n    assertNone(Duration.fromIso(\"P1S\"))\n    assertNone(Duration.fromIso(\"P1DT1S1H\"))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/acquire-release.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { equals } from \"effect/Equal\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"acquireUseRelease - happy path\", () =>\n    Effect.gen(function*() {\n      const release = yield* (Ref.make(false))\n      const result = yield* (\n        Effect.acquireUseRelease(\n          Effect.succeed(42),\n          (n) => Effect.succeed(n + 1),\n          () => Ref.set(release, true)\n        )\n      )\n      const released = yield* (Ref.get(release))\n      strictEqual(result, 43)\n      assertTrue(released)\n    }))\n  it.effect(\"acquireUseRelease - happy path + disconnect\", () =>\n    Effect.gen(function*() {\n      const release = yield* (Ref.make(false))\n      const result = yield* pipe(\n        Effect.acquireUseRelease(\n          Effect.succeed(42),\n          (n) => Effect.succeed(n + 1),\n          () => Ref.set(release, true)\n        ),\n        Effect.disconnect\n      )\n      const released = yield* (Ref.get(release))\n      strictEqual(result, 43)\n      assertTrue(released)\n    }))\n  it.effect(\"acquireUseRelease - error handling\", () =>\n    Effect.gen(function*() {\n      const releaseDied = new Cause.RuntimeException(\"release died\")\n      const exit = yield* pipe(\n        Effect.acquireUseRelease(\n          Effect.succeed(42),\n          () => Effect.fail(\"use failed\"),\n          () => Effect.die(releaseDied)\n        ),\n        Effect.exit\n      )\n      const result = yield* pipe(\n        exit,\n        Exit.matchEffect({ onFailure: Effect.succeed, onSuccess: () => Effect.fail(\"effect should have failed\") })\n      )\n      assertTrue(equals(Cause.failures(result), Chunk.of(\"use failed\")))\n      assertTrue(equals(Cause.defects(result), Chunk.of(releaseDied)))\n    }))\n  it.effect(\"acquireUseRelease - error handling + disconnect\", () =>\n    Effect.gen(function*() {\n      const releaseDied = new Cause.RuntimeException(\"release died\")\n      const exit = yield* pipe(\n        Effect.acquireUseRelease(\n          Effect.succeed(42),\n          () => Effect.fail(\"use failed\"),\n          () => Effect.die(releaseDied)\n        ),\n        Effect.disconnect,\n        Effect.exit\n      )\n      const result = yield* pipe(\n        exit,\n        Exit.matchEffect({\n          onFailure: Effect.succeed,\n          onSuccess: () => Effect.fail(\"effect should have failed\")\n        })\n      )\n      assertTrue(equals(Cause.failures(result), Chunk.of(\"use failed\")))\n      assertTrue(equals(Cause.defects(result), Chunk.of(releaseDied)))\n    }))\n  it.effect(\"acquireUseRelease - beast mode error handling + disconnect\", () =>\n    Effect.gen(function*() {\n      const useDied = new Cause.RuntimeException(\"use died\")\n      const release = yield* (Ref.make(false))\n      const exit = yield* (\n        pipe(\n          Effect.acquireUseRelease(\n            Effect.succeed(42),\n            (): Effect.Effect<unknown, unknown> => {\n              throw useDied\n            },\n            () => Ref.set(release, true)\n          ),\n          Effect.disconnect,\n          Effect.exit\n        )\n      )\n      const result = yield* (\n        pipe(\n          exit,\n          Exit.matchEffect({\n            onFailure: Effect.succeed,\n            onSuccess: () => Effect.fail(\"effect should have failed\")\n          })\n        )\n      )\n      const released = yield* (Ref.get(release))\n      assertTrue(equals(Cause.defects(result), Chunk.of(useDied)))\n      assertTrue(released)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/applicative.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, strictEqual } from \"@effect/vitest/utils\"\nimport { Effect, pipe } from \"effect\"\n\ndescribe(\"Effect\", () => {\n  const add = (a: number) => (b: number) => a + b\n\n  it.effect(\"two successes should succeed\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.succeed(add).pipe(Effect.ap(Effect.succeed(1)), Effect.ap(Effect.succeed(2))))\n      strictEqual(result, 3)\n    }))\n\n  it.effect(\"one failure in data-last position should fail\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.succeed(add).pipe(Effect.ap(Effect.succeed(1)), Effect.ap(Effect.fail(\"c\"))),\n        Effect.either\n      )\n      assertLeft(result, \"c\")\n    }))\n\n  it.effect(\"one failure in data-first position should fail\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.succeed(add).pipe(Effect.ap(Effect.fail(\"b\")), Effect.ap(Effect.fail(\"c\"))),\n        Effect.either\n      )\n      assertLeft(result, \"b\")\n    }))\n\n  it.effect(\"an applicative operation that starts with a failure should fail\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        (Effect.fail(\"a\") as Effect.Effect<typeof add, string>).pipe(\n          Effect.ap(Effect.succeed(1)),\n          Effect.ap(Effect.succeed(2))\n        ),\n        Effect.either\n      )\n      assertLeft(result, \"a\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/async.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertSome, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as Runtime from \"effect/Runtime\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"simple async must return\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.async<number, unknown, never>((cb) => {\n        cb(Effect.succeed(42))\n      }))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"simple asyncEffect must return\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.asyncEffect<number, never, never, never, never, never>((resume) => {\n        return Effect.succeed(resume(Effect.succeed(42)))\n      }))\n      strictEqual(result, 42)\n    }))\n  if (typeof window === \"undefined\") {\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const os = require(\"node:os\")\n    it.effect(\"deep asyncEffect doesn't block\", () =>\n      Effect.gen(function*() {\n        const asyncIO = (cont: Effect.Effect<number>): Effect.Effect<number> => {\n          return Effect.asyncEffect((cb) => {\n            return pipe(\n              Effect.sleep(Duration.millis(5)),\n              Effect.zipRight(cont),\n              Effect.zipRight(Effect.succeed(cb(Effect.succeed(42))))\n            )\n          })\n        }\n        const stackIOs = (count: number): Effect.Effect<number> => {\n          return count < 0 ? Effect.succeed(42) : asyncIO(stackIOs(count - 1))\n        }\n        const procNum = Effect.sync(() => os.cpus().length)\n        const result = yield* pipe(procNum, Effect.flatMap(stackIOs))\n        strictEqual(result, 42)\n      }))\n  }\n  it.effect(\"interrupt of asyncEffect register\", () =>\n    Effect.gen(function*() {\n      const release = yield* (Deferred.make<void>())\n      const acquire = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Effect.asyncEffect<unknown, unknown, never, never, never, never>(() =>\n          // This will never complete because we never call the callback\n          Effect.acquireUseRelease(\n            Deferred.succeed(acquire, void 0),\n            () => Effect.never,\n            () => Deferred.succeed(release, void 0)\n          )\n        ),\n        Effect.disconnect,\n        Effect.fork\n      )\n\n      yield* (Deferred.await(acquire))\n      yield* (Fiber.interruptFork(fiber))\n      const result = yield* (Deferred.await(release))\n      strictEqual(result, undefined)\n    }))\n  it.live(\"async should not resume fiber twice after interruption\", () =>\n    Effect.gen(function*() {\n      const step = yield* (Deferred.make<void>())\n      const unexpectedPlace = yield* (Ref.make(Chunk.empty<number>()))\n      const runtime = yield* (Effect.runtime<never>())\n      const fiber = yield* pipe(\n        Effect.async<void, never, never>((cb) => {\n          Runtime.runCallback(runtime)(pipe(\n            Deferred.await(step),\n            Effect.zipRight(Effect.sync(() => cb(Ref.update(unexpectedPlace, Chunk.prepend(1)))))\n          ))\n        }),\n        Effect.ensuring(Effect.async<void, never, never>(() => {\n          // The callback is never called so this never completes\n          Runtime.runCallback(runtime)(Deferred.succeed(step, undefined))\n        })),\n        Effect.ensuring(Ref.update(unexpectedPlace, Chunk.prepend(2))),\n        Effect.forkDaemon\n      )\n      const result = yield* pipe(Fiber.interrupt(fiber), Effect.timeout(Duration.seconds(1)), Effect.option)\n      const unexpected = yield* (Ref.get(unexpectedPlace))\n      deepStrictEqual(unexpected, Chunk.empty())\n      assertNone(result) // the timeout should happen\n    }))\n  it.live(\"async should not resume fiber twice after synchronous result\", () =>\n    Effect.gen(function*() {\n      const step = yield* (Deferred.make<void>())\n      const unexpectedPlace = yield* (Ref.make(Chunk.empty<number>()))\n      const runtime = yield* (Effect.runtime<never>())\n      const fiber = yield* pipe(\n        Effect.async<void, never, never>((resume) => {\n          Runtime.runCallback(runtime)(pipe(\n            Deferred.await(step),\n            Effect.zipRight(Effect.sync(() => resume(Ref.update(unexpectedPlace, Chunk.prepend(1)))))\n          ))\n          return Effect.void\n        }),\n        Effect.flatMap(() =>\n          Effect.async<void, never, never>(() => {\n            // The callback is never called so this never completes\n            Runtime.runCallback(runtime)(Deferred.succeed(step, void 0))\n          })\n        ),\n        Effect.ensuring(Ref.update(unexpectedPlace, Chunk.prepend(2))),\n        Effect.uninterruptible,\n        Effect.forkDaemon\n      )\n      const result = yield* pipe(Fiber.interrupt(fiber), Effect.timeout(Duration.seconds(1)), Effect.option)\n      const unexpected = yield* (Ref.get(unexpectedPlace))\n      deepStrictEqual(unexpected, Chunk.empty())\n      assertNone(result) // timeout should happen\n    }))\n  it.effect(\"sleep 0 must return\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.sleep(Duration.zero))\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"shallow bind of async chain\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 10 }, (_, i) => i)\n      const result = yield* (array.reduce((acc, _) =>\n        pipe(\n          acc,\n          Effect.flatMap((n) =>\n            Effect.async<number, never, never>((cb) => {\n              cb(Effect.succeed(n + 1))\n            })\n          )\n        ), Effect.succeed(0)))\n      strictEqual(result, 10)\n    }))\n  it.effect(\"asyncEffect can fail before registering\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.asyncEffect<unknown, unknown, never, never, string, never>((_) => {\n          return Effect.fail(\"ouch\")\n        }),\n        Effect.flip\n      )\n      strictEqual(result, \"ouch\")\n    }))\n  it.effect(\"asyncEffect can defect before registering\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.asyncEffect<unknown, unknown, never, never, string, never>((_) =>\n          Effect.sync(() => {\n            throw new Error(\"ouch\")\n          })\n        ),\n        Effect.exit,\n        Effect.map(Exit.match({\n          onFailure: (cause) =>\n            pipe(\n              Cause.defects(cause),\n              Chunk.head,\n              Option.map((e) => (e as Error).message)\n            ),\n          onSuccess: () => Option.none()\n        }))\n      )\n      assertSome(result, \"ouch\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/caching.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"cached - returns new instances after duration\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const cache = yield* pipe(\n        Ref.updateAndGet(ref, (n) => n + 1),\n        Effect.cachedWithTTL(Duration.minutes(60))\n      )\n      const a = yield* cache\n      yield* (TestClock.adjust(Duration.minutes(59)))\n      const b = yield* cache\n      yield* (TestClock.adjust(Duration.minutes(1)))\n      const c = yield* cache\n      yield* (TestClock.adjust(Duration.minutes(59)))\n      const d = yield* cache\n      strictEqual(a, b)\n      assertTrue(b !== c)\n      strictEqual(c, d)\n    }))\n  it.effect(\"cached - correctly handles an infinite duration time to live\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const cached = yield* pipe(\n        Ref.modify(ref, (curr) => [curr, curr + 1]),\n        Effect.cachedWithTTL(Duration.infinity)\n      )\n      const a = yield* cached\n      const b = yield* cached\n      const c = yield* cached\n      strictEqual(a, 0)\n      strictEqual(b, 0)\n      strictEqual(c, 0)\n    }))\n  it.effect(\"cachedInvalidate - returns new instances after duration\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const [cached, invalidate] = yield* (\n        pipe(\n          Ref.updateAndGet(ref, (n) => n + 1),\n          Effect.cachedInvalidateWithTTL(Duration.minutes(60))\n        )\n      )\n      const a = yield* cached\n      yield* (TestClock.adjust(Duration.minutes(59)))\n      const b = yield* cached\n      yield* invalidate\n      const c = yield* cached\n      yield* (TestClock.adjust(Duration.minutes(1)))\n      const d = yield* cached\n      yield* (TestClock.adjust(Duration.minutes(59)))\n      const e = yield* cached\n      strictEqual(a, b)\n      assertTrue(b !== c)\n      strictEqual(c, d)\n      assertTrue(d !== e)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/cause-rendering.test.ts",
    "content": "import { describe, expect, it } from \"@effect/vitest\"\nimport { assertFalse, assertInclude, assertInstanceOf, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport { Cause, Effect, Option, pipe } from \"effect\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"Cause should include span data\", () =>\n    Effect.gen(function*() {\n      const cause = yield* (Effect.flip(Effect.sandbox(\n        Effect.withSpan(\"spanB\")(\n          Effect.withSpan(\"spanA\")(\n            Effect.fail(new Error(\"ok\"))\n          )\n        )\n      )))\n      const rendered = Cause.pretty(cause)\n      assertInclude(rendered, \"spanA\")\n      assertInclude(rendered, \"cause-rendering.test.ts:10:18\")\n      assertInclude(rendered, \"spanB\")\n      assertInclude(rendered, \"cause-rendering.test.ts:9:16\")\n    }))\n  it.effect(\"catchTag should not invalidate traces\", () =>\n    Effect.gen(function*() {\n      class E1 {\n        readonly _tag = \"E1\"\n      }\n      class E2 {\n        readonly _tag = \"E2\"\n      }\n      const err = new E1()\n      const effect = Effect.withSpan(\"spanB\")(\n        Effect.withSpan(\"spanA\")(\n          Effect.if(Effect.sync(() => Math.random() > 1), {\n            onTrue: () => Effect.fail(new E2()),\n            onFalse: () => Effect.fail(err)\n          })\n        )\n      ).pipe(Effect.catchTag(\"E2\", (e) => Effect.die(e)))\n      const cause = yield* (Effect.flip(Effect.sandbox(effect)))\n      const rendered = Cause.pretty(cause)\n      assertInclude(rendered, \"spanA\")\n      assertInclude(rendered, \"spanB\")\n      const obj = Option.getOrThrow(Cause.failureOption(cause))\n      assertInstanceOf(obj, E1)\n      assertFalse(err === obj)\n      assertTrue(err === Cause.originalError(obj))\n    }))\n  it.effect(\"refail should not invalidate traces\", () =>\n    Effect.gen(function*() {\n      class E1 {\n        readonly _tag = \"E1\"\n      }\n      class E2 {\n        readonly _tag = \"E2\"\n      }\n      const effect = Effect.withSpan(\"spanB\")(\n        Effect.withSpan(\"spanA\")(\n          Effect.if(Effect.sync(() => Math.random() > 1), {\n            onTrue: () => Effect.fail(new E2()),\n            onFalse: () => Effect.fail(new E1())\n          })\n        )\n      ).pipe(Effect.catchAll((e) => Effect.fail(e)))\n      const cause = yield* (Effect.flip(Effect.sandbox(effect)))\n      const rendered = Cause.pretty(cause)\n      assertInclude(rendered, \"spanA\")\n      assertInclude(rendered, \"spanB\")\n    }))\n  it.effect(\"catchTags should not invalidate traces\", () =>\n    Effect.gen(function*() {\n      class E1 {\n        readonly _tag = \"E1\"\n      }\n      class E2 {\n        readonly _tag = \"E2\"\n      }\n      const effect = Effect.withSpan(\"spanB\")(\n        Effect.withSpan(\"spanA\")(\n          Effect.if(Effect.sync(() => Math.random() > 1), {\n            onTrue: () => Effect.fail(new E2()),\n            onFalse: () => Effect.fail(new E1())\n          })\n        )\n      ).pipe(Effect.catchTags({ E2: (e) => Effect.die(e) }))\n      const cause = yield* (Effect.flip(Effect.sandbox(effect)))\n      const rendered = Cause.pretty(cause)\n      assertInclude(rendered, \"spanA\")\n      assertInclude(rendered, \"spanB\")\n    }))\n  it.effect(\"shows line where error was created\", () =>\n    Effect.gen(function*() {\n      const cause = yield* pipe(\n        Effect.sync(() => {\n          throw new Error(\"ok\")\n        }),\n        Effect.sandbox,\n        Effect.flip\n      )\n      const pretty = Cause.pretty(cause)\n      assertInclude(pretty, \"cause-rendering.test.ts\")\n    }))\n\n  it.effect(\"functionWithSpan PrettyError stack\", () =>\n    Effect.gen(function*() {\n      const fail = Effect.functionWithSpan({\n        body: (_id: number) => Effect.fail(new Error(\"boom\")),\n        options: (id) => ({ name: `span-${id}` })\n      })\n      const cause = yield* fail(123).pipe(Effect.sandbox, Effect.flip)\n      const prettyErrors = Cause.prettyErrors(cause)\n      strictEqual(prettyErrors.length, 1)\n      const error = prettyErrors[0]\n      strictEqual(error.name, \"Error\")\n      assertInclude(error.stack, \"cause-rendering.test.ts:105\")\n      assertInclude(error.stack, \"span-123\")\n      assertInclude(error.stack, \"cause-rendering.test.ts:108\")\n    }))\n\n  it.effect(\"includes span name in stack\", () =>\n    Effect.gen(function*() {\n      const fn = Effect.functionWithSpan({\n        options: (n) => ({ name: `fn-${n}` }),\n        body: (a: number) =>\n          Effect.sync(() => {\n            strictEqual(a, 2)\n          })\n      })\n      const cause = yield* fn(0).pipe(\n        Effect.sandbox,\n        Effect.flip\n      )\n      const prettyErrors = Cause.prettyErrors(cause)\n      assertInclude(prettyErrors[0].stack, \"at fn-0 \")\n    }))\n\n  // ENABLE TO TEST EXPECT OUTPUT\n  it.effect.skip(\"shows assertion message\", () =>\n    Effect.gen(function*() {\n      yield* Effect.void\n      expect({ foo: \"ok\" }).toStrictEqual({ foo: \"bar\" })\n    }))\n\n  it.effect(\"multiline message\", () =>\n    Effect.gen(function*() {\n      const cause = yield* Effect.fail(new Error(\"Multi-line\\nerror\\nmessage\")).pipe(\n        Effect.sandbox,\n        Effect.flip\n      )\n      const pretty = Cause.pretty(cause)\n      assertTrue(pretty.startsWith(`Error: Multi-line\nerror\nmessage\n    at`))\n    }))\n\n  it.effect(\"pretty includes error.cause with renderErrorCause: true\", () =>\n    Effect.gen(function*() {\n      const cause = yield* Effect.fail(new Error(\"parent\", { cause: new Error(\"child\") })).pipe(\n        Effect.sandbox,\n        Effect.flip\n      )\n      const pretty = Cause.pretty(cause, { renderErrorCause: true })\n      assertInclude(pretty, \"[cause]: Error: child\")\n    }))\n\n  it.effect(\"pretty nested cause\", () =>\n    Effect.gen(function*() {\n      const cause = yield* Effect.fail(\n        new Error(\"parent\", { cause: new Error(\"child\", { cause: new Error(\"child2\") }) })\n      ).pipe(\n        Effect.sandbox,\n        Effect.flip\n      )\n      const pretty = Cause.pretty(cause, { renderErrorCause: true })\n      assertInclude(pretty, \"[cause]: Error: child\")\n      assertInclude(pretty, \"[cause]: Error: child2\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/collecting.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, notDeepStrictEqual } from \"@effect/vitest/utils\"\nimport { Cause, Effect, pipe, Ref } from \"effect\"\n\ndescribe(\"Effect\", () => {\n  describe(\"all\", () => {\n    describe(\"returns results in the same order\", () => {\n      it.effect(\"unbounded\", () =>\n        Effect.gen(function*() {\n          const result = yield* (Effect.all([1, 2, 3].map(Effect.succeed), {\n            concurrency: \"unbounded\"\n          }))\n          deepStrictEqual(Array.from(result), [1, 2, 3])\n        }))\n\n      it.effect(\"concurrency > 1\", () =>\n        Effect.gen(function*() {\n          const result = yield* (Effect.all([1, 2, 3].map(Effect.succeed), {\n            concurrency: 2\n          }))\n          deepStrictEqual(Array.from(result), [1, 2, 3])\n        }))\n    })\n\n    it.effect(\"is referentially transparent\", () =>\n      Effect.gen(function*() {\n        const counter = yield* (Ref.make(0))\n        const op = Ref.getAndUpdate(counter, (n) => n + 1)\n        const ops3 = Effect.all([op, op, op], { concurrency: \"unbounded\" })\n        const result = yield* pipe(ops3, Effect.zip(ops3, { concurrent: true }))\n        notDeepStrictEqual(Array.from(result[0]), Array.from(result[1]))\n      }))\n\n    it.effect(\"preserves failures\", () =>\n      Effect.gen(function*() {\n        const result = yield* pipe(\n          Effect.all(Array.from({ length: 10 }, () => Effect.fail(new Cause.RuntimeException())), {\n            concurrency: 5,\n            discard: true\n          }),\n          Effect.flip\n        )\n        deepStrictEqual(result, new Cause.RuntimeException())\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/concurrency.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertLeft, assertRight, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport { adjust } from \"effect/TestClock\"\nimport { withLatch } from \"../utils/latch.js\"\n\nexport const ExampleError = new Error(\"Oh noes!\")\n\nconst fib = (n: number): number => {\n  if (n <= 1) {\n    return n\n  }\n  return fib(n - 1) + fib(n - 2)\n}\n\nconst concurrentFib = (n: number): Effect.Effect<number> => {\n  if (n <= 1) {\n    return Effect.succeed(n)\n  }\n  return Effect.gen(function*() {\n    const fiber1 = yield* (Effect.fork(concurrentFib(n - 1)))\n    const fiber2 = yield* (Effect.fork(concurrentFib(n - 2)))\n    const v1 = yield* (Fiber.join(fiber1))\n    const v2 = yield* (Fiber.join(fiber2))\n    return v1 + v2\n  })\n}\n\ndescribe(\"Effect\", () => {\n  it.effect(\"shallow fork/join identity\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.succeed(42), Effect.fork, Effect.flatMap(Fiber.join))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"deep fork/join identity\", () =>\n    Effect.gen(function*() {\n      const result = yield* (concurrentFib(20))\n      strictEqual(result, fib(20))\n    }))\n  it.effect(\"asyncEffect creation is interruptible\", () =>\n    Effect.gen(function*() {\n      const release = yield* (Deferred.make<number>())\n      const acquire = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Effect.asyncEffect<void, never, never, never, never, never>((_) =>\n          // This will never complete because the callback is never invoked\n          Effect.acquireUseRelease(\n            Deferred.succeed(acquire, void 0),\n            () => Effect.never,\n            () => Effect.asVoid(Deferred.succeed(release, 42))\n          )\n        ),\n        Effect.fork\n      )\n      yield* (Deferred.await(acquire))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Deferred.await(release))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"daemon fiber is unsupervised\", () =>\n    Effect.gen(function*() {\n      const child = (ref: Ref.Ref<boolean>) => {\n        return withLatch((release) =>\n          pipe(\n            release,\n            Effect.zipRight(Effect.never),\n            Effect.ensuring(Ref.set(ref, true))\n          )\n        )\n      }\n      const ref = yield* (Ref.make(false))\n      const fiber1 = yield* pipe(child(ref), Effect.forkDaemon, Effect.fork)\n      const fiber2 = yield* (Fiber.join(fiber1))\n      const result = yield* (Ref.get(ref))\n      yield* (Fiber.interrupt(fiber2))\n      assertFalse(result)\n    }))\n  it.effect(\"daemon fiber race interruption\", () =>\n    Effect.gen(function*() {\n      const plus1 = <X>(latch: Deferred.Deferred<void, never>, finalizer: Effect.Effect<X>) => {\n        return pipe(\n          Deferred.succeed(latch, void 0),\n          Effect.zipRight(Effect.sleep(Duration.hours(1))),\n          Effect.onInterrupt(() => pipe(finalizer, Effect.map((x) => x)))\n        )\n      }\n      const interruptionRef = yield* (Ref.make(0))\n      const latch1Start = yield* (Deferred.make<void>())\n      const latch2Start = yield* (Deferred.make<void>())\n      const inc = Ref.updateAndGet(interruptionRef, (n) => n + 1)\n      const left = plus1(latch1Start, inc)\n      const right = plus1(latch2Start, inc)\n      const fiber = yield* pipe(left, Effect.race(right), Effect.fork)\n      yield* (\n        pipe(\n          Deferred.await(latch1Start),\n          Effect.zipRight(Deferred.await(latch2Start)),\n          Effect.zipRight(Fiber.interrupt(fiber))\n        )\n      )\n      const result = yield* (Ref.get(interruptionRef))\n      strictEqual(result, 2)\n    }))\n  it.effect(\"race in daemon is executed\", () =>\n    Effect.gen(function*() {\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const loser1 = Effect.acquireUseRelease(\n        Deferred.succeed(latch1, void 0),\n        () => Effect.never,\n        () => Deferred.succeed(deferred1, void 0)\n      )\n      const loser2 = Effect.acquireUseRelease(\n        Deferred.succeed(latch2, void 0),\n        () => Effect.never,\n        () => Deferred.succeed(deferred2, void 0)\n      )\n      const fiber = yield* pipe(loser1, Effect.race(loser2), Effect.forkDaemon)\n      yield* (Deferred.await(latch1))\n      yield* (Deferred.await(latch2))\n      yield* (Fiber.interrupt(fiber))\n      const res1 = yield* (Deferred.await(deferred1))\n      const res2 = yield* (Deferred.await(deferred2))\n      strictEqual(res1, undefined)\n      strictEqual(res2, undefined)\n    }))\n  it.live(\"supervise fibers\", () =>\n    Effect.gen(function*() {\n      const makeChild = (n: number): Effect.Effect<Fiber.Fiber<void>> => {\n        return pipe(Effect.sleep(Duration.millis(20 * n)), Effect.zipRight(Effect.never), Effect.fork)\n      }\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        makeChild(1),\n        Effect.zipRight(makeChild(2)),\n        Effect.ensuringChildren((fs) =>\n          Array.from(fs).reduce(\n            (acc, fiber) =>\n              pipe(\n                acc,\n                Effect.zipRight(Fiber.interrupt(fiber)),\n                Effect.zipRight(Ref.update(ref, (n) => n + 1))\n              ),\n            Effect.void\n          )\n        )\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 2)\n    }))\n  it.effect(\"race of fail with success\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.fail(42), Effect.race(Effect.succeed(24)), Effect.either)\n      assertRight(result, 24)\n    }))\n  it.effect(\"race of terminate with success\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.dieSync(() => new Error()), Effect.race(Effect.succeed(24)))\n      strictEqual(result, 24)\n    }))\n  it.effect(\"race of fail with fail\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.fail(42), Effect.race(Effect.fail(24)), Effect.either)\n      assertLeft(result, 42)\n    }))\n  it.effect(\"race of value and never\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.succeed(42), Effect.race(Effect.never))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"race in uninterruptible region\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<boolean>())\n      const fiber = yield* pipe(\n        Effect.void,\n        Effect.race(Effect.zip(Deferred.succeed(latch, true), Effect.sleep(\"45 seconds\"))),\n        Effect.uninterruptible,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (adjust(\"30 seconds\"))\n      strictEqual(fiber.unsafePoll(), null)\n      yield* (adjust(\"60 seconds\"))\n      assertTrue(fiber.unsafePoll() !== null)\n    }), 20_000)\n  it.effect(\"race of two forks does not interrupt winner\", () =>\n    Effect.gen(function*() {\n      const forkWaiter = (\n        interrupted: Ref.Ref<number>,\n        latch: Deferred.Deferred<void, never>,\n        done: Deferred.Deferred<void, never>\n      ) => {\n        return Effect.uninterruptibleMask((restore) =>\n          pipe(\n            restore(Deferred.await(latch)),\n            Effect.onInterrupt(() =>\n              pipe(Ref.update(interrupted, (_) => _ + 1), Effect.zipRight(Deferred.succeed(done, void 0)))\n            ),\n            Effect.fork\n          )\n        )\n      }\n      const interrupted = yield* (Ref.make(0))\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const done1 = yield* (Deferred.make<void>())\n      const done2 = yield* (Deferred.make<void>())\n      const forkWaiter1 = forkWaiter(interrupted, latch1, done1)\n      const forkWaiter2 = forkWaiter(interrupted, latch2, done2)\n      yield* pipe(forkWaiter1, Effect.race(forkWaiter2))\n      const count = yield* (\n        pipe(\n          Deferred.succeed(latch1, void 0),\n          Effect.zipRight(Deferred.await(done1)),\n          Effect.zipRight(Deferred.await(done2)),\n          Effect.zipRight(Ref.get(interrupted))\n        )\n      )\n      strictEqual(count, 2)\n    }))\n  it.effect(\"firstSuccessOf of values\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.firstSuccessOf([\n          Effect.fail(0),\n          Effect.succeed(100)\n        ]),\n        Effect.either\n      )\n      assertRight(result, 100)\n    }))\n  it.live(\"firstSuccessOf of failures\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.firstSuccessOf([\n          pipe(Effect.fail(0), Effect.delay(Duration.millis(10))),\n          Effect.fail(101)\n        ]),\n        Effect.either\n      )\n\n      assertLeft(result, 101)\n    }))\n  it.live(\"firstSuccessOf of failures & 1 success\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.firstSuccessOf([\n          Effect.fail(0),\n          pipe(Effect.succeed(102), Effect.delay(Duration.millis(1)))\n        ]),\n        Effect.either\n      )\n      assertRight(result, 102)\n    }))\n  it.effect(\"raceFirst interrupts loser on success\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<void>())\n      const effect = yield* (Deferred.make<number>())\n      const winner = Either.right(void 0)\n      const loser = Effect.acquireUseRelease(\n        Deferred.succeed(deferred, void 0),\n        () => Effect.never,\n        () => Deferred.succeed(effect, 42)\n      )\n      yield* pipe(winner, Effect.raceFirst(loser))\n      const result = yield* (Deferred.await(effect))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"raceFirst interrupts loser on failure\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<void>())\n      const effect = yield* (Deferred.make<number>())\n      const winner = pipe(Deferred.await(deferred), Effect.zipRight(Either.left(new Error())))\n      const loser = Effect.acquireUseRelease(\n        Deferred.succeed(deferred, void 0),\n        () => Effect.never,\n        () => Deferred.succeed(effect, 42)\n      )\n      yield* pipe(winner, Effect.raceFirst(loser), Effect.either)\n      const result = yield* (Deferred.await(effect))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"mergeAll\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe([\"a\", \"aa\", \"aaa\", \"aaaa\"].map((a) => Effect.succeed(a)), Effect.mergeAll(0, (b, a) => b + a.length))\n      )\n      strictEqual(result, 10)\n    }))\n  it.effect(\"mergeAll - empty\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe([] as ReadonlyArray<Effect.Effect<number>>, Effect.mergeAll(0, (b, a) => b + a))\n      )\n      strictEqual(result, 0)\n    }))\n  it.effect(\"reduceEffect\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe([2, 3, 4].map((n) => Effect.succeed(n)), Effect.reduceEffect(Effect.succeed(1), (acc, a) => acc + a))\n      )\n      strictEqual(result, 10)\n    }))\n  it.effect(\"reduceEffect - empty list\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          [] as ReadonlyArray<Effect.Effect<number>>,\n          Effect.reduceEffect(Effect.succeed(1), (acc, a) => acc + a)\n        )\n      )\n      strictEqual(result, 1)\n    }))\n  it.effect(\"timeout of failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.fail(\"uh oh\"), Effect.timeout(Duration.hours(1)), Effect.exit)\n      deepStrictEqual(result, Exit.fail(\"uh oh\"))\n    }))\n  it.effect(\"timeout of terminate\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.die(ExampleError), Effect.timeout(Duration.hours(1)), Effect.exit)\n      deepStrictEqual(result, Exit.die(ExampleError))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/constructors.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertSome, strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"can lift a value to an option\", () =>\n    Effect.gen(function*() {\n      const result = yield* Effect.succeedSome(42)\n      assertSome(result, 42)\n    }))\n  it.effect(\"using the none value\", () =>\n    Effect.gen(function*() {\n      const result = yield* Effect.succeedNone\n      assertNone(result)\n    }))\n  it.effect(\"can use .pipe for composition\", () =>\n    Effect.gen(function*() {\n      return yield* Effect.succeed(1)\n    }).pipe(\n      Effect.map((n) => n + 1),\n      Effect.flatMap((n) =>\n        Effect.gen(function*() {\n          return yield* Effect.succeed(n + 1)\n        })\n      ),\n      Effect.tap((n) =>\n        Effect.sync(() => {\n          strictEqual(n, 3)\n        })\n      )\n    ))\n  it.effect(\"can pass this to generator\", () => {\n    class MyService {\n      readonly local = 1\n      compute = Effect.gen(this, function*() {\n        return yield* Effect.succeed(this.local + 1)\n      })\n    }\n    const instance = new MyService()\n\n    return Effect.map(instance.compute, (n) => {\n      strictEqual(n, 2)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/destructors.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFailure,\n  assertFalse,\n  assertLeft,\n  assertNone,\n  assertRight,\n  assertSome,\n  assertTrue,\n  strictEqual\n} from \"@effect/vitest/utils\"\nimport { Cause, Effect, Option, pipe } from \"effect\"\n\nconst ExampleError = new Error(\"Oh noes!\")\n\ndescribe(\"Effect\", () => {\n  it.effect(\"head - on non empty list\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.succeed([1, 2, 3]), Effect.head, Effect.either)\n      assertRight(result, 1)\n    }))\n  it.effect(\"head - on empty list\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.succeed([] as ReadonlyArray<number>), Effect.head, Effect.option)\n      assertNone(result)\n    }))\n  it.effect(\"head - on failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.fail(\"fail\"), Effect.head, Effect.either)\n      assertLeft(result, \"fail\")\n    }))\n  it.effect(\"isFailure - returns true when the effect is a failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.isFailure(Effect.fail(\"fail\")))\n      assertTrue(result)\n    }))\n  it.effect(\"isFailure - returns false when the effect is a success\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.isFailure(Effect.succeed(\"succeed\")))\n      assertFalse(result)\n    }))\n  it.effect(\"isSuccess - returns false when the effect is a failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.isSuccess(Effect.fail(\"fail\")))\n      assertFalse(result)\n    }))\n  it.effect(\"isSuccess - returns true when the effect is a success\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.isSuccess(Effect.succeed(\"succeed\")))\n      assertTrue(result)\n    }))\n  it.effect(\"none - on Some fails with NoSuchElementException\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.exit(Effect.none(Effect.succeed(Option.some(1)))))\n      assertFailure(result, Cause.fail(new Cause.NoSuchElementException()))\n    }))\n  it.effect(\"none - on None succeeds with undefined\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.none(Effect.succeed(Option.none())))\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"none - fails with ex when effect fails with ex\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"failed task\")\n      const result = yield* (Effect.exit(Effect.none(Effect.fail(error))))\n      assertFailure(result, Cause.fail(error))\n    }))\n  it.effect(\"option - return success in Some\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.option(Effect.succeed(11)))\n      assertSome(result, 11)\n    }))\n  it.effect(\"option - return failure as None\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.option(Effect.fail(123)))\n      assertNone(result)\n    }))\n  it.effect(\"option - not catch throwable\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.exit(Effect.option(Effect.die(ExampleError))))\n      assertFailure(result, Cause.die(ExampleError))\n    }))\n  it.effect(\"option - catch throwable after sandboxing\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.option(Effect.sandbox(Effect.die(ExampleError))))\n      assertNone(result)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/do-notation.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Util from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport type { NoExcessProperties } from \"effect/Types\"\n\nconst expectRight = <R, L>(e: Effect.Effect<R, L>, expected: R) => {\n  Util.deepStrictEqual(Effect.runSync(Effect.either(e)), Either.right(expected))\n}\n\nconst expectLeft = <R, L>(e: Effect.Effect<R, L>, expected: L) => {\n  Util.deepStrictEqual(Effect.runSync(Effect.either(e)), Either.left(expected))\n}\n\ndescribe(\"do notation\", () => {\n  it(\"Do\", () => {\n    expectRight(Effect.Do, {})\n  })\n\n  it(\"bindTo\", () => {\n    expectRight(pipe(Effect.succeed(1), Effect.bindTo(\"a\")), { a: 1 })\n    expectLeft(pipe(Effect.fail(\"left\"), Effect.bindTo(\"a\")), \"left\")\n    expectRight(\n      pipe(\n        Effect.succeed(1),\n        Effect.bindTo(\"__proto__\"),\n        Effect.bind(\"x\", () => Effect.succeed(2))\n      ),\n      { x: 2, [\"__proto__\"]: 1 }\n    )\n  })\n\n  it(\"bind\", () => {\n    expectRight(pipe(Effect.succeed(1), Effect.bindTo(\"a\"), Effect.bind(\"b\", ({ a }) => Effect.succeed(a + 1))), {\n      a: 1,\n      b: 2\n    })\n    expectLeft(\n      pipe(Effect.succeed(1), Effect.bindTo(\"a\"), Effect.bind(\"b\", () => Effect.fail(\"left\"))),\n      \"left\"\n    )\n    expectLeft(\n      pipe(Effect.fail(\"left\"), Effect.bindTo(\"a\"), Effect.bind(\"b\", () => Effect.succeed(2))),\n      \"left\"\n    )\n    expectRight(\n      pipe(\n        Effect.Do,\n        Effect.bind(\"__proto__\", () => Effect.succeed(1)),\n        Effect.bind(\"b\", ({ __proto__ }) => Effect.succeed(2))\n      ),\n      { b: 2, [\"__proto__\"]: 1 }\n    )\n  })\n\n  it(\"let\", () => {\n    expectRight(pipe(Effect.succeed(1), Effect.bindTo(\"a\"), Effect.let(\"b\", ({ a }) => a + 1)), { a: 1, b: 2 })\n    expectLeft(\n      pipe(Effect.fail(\"left\"), Effect.bindTo(\"a\"), Effect.let(\"b\", () => 2)),\n      \"left\"\n    )\n    expectRight(\n      pipe(\n        Effect.succeed(1),\n        Effect.bindTo(\"a\"),\n        Effect.let(\"__proto__\", ({ a }) => a + 1),\n        Effect.bind(\"x\", () => Effect.succeed(3))\n      ),\n      { a: 1, x: 3, [\"__proto__\"]: 2 }\n    )\n  })\n\n  describe(\"bindAll\", () => {\n    it(\"succeed\", () => {\n      const getTest = <O extends NoExcessProperties<{ mode: \"default\" | \"either\" | \"validate\" }, O>>(options: O) =>\n        Effect.Do.pipe(\n          Effect.bind(\"x\", () => Effect.succeed(2)),\n          Effect.bindAll(({ x }) => ({\n            a: Effect.succeed(x),\n            b: Effect.succeed(\"ops\")\n          }), options)\n        )\n\n      expectRight(getTest({ mode: \"default\" }), {\n        a: 2,\n        b: \"ops\",\n        x: 2\n      })\n\n      expectRight(getTest({ mode: \"either\" }), {\n        a: Either.right(2),\n        b: Either.right(\"ops\"),\n        x: 2\n      })\n\n      expectRight(getTest({ mode: \"validate\" }), {\n        a: 2,\n        b: \"ops\",\n        x: 2\n      })\n    })\n\n    it(\"with failure\", () => {\n      const getTest = <O extends NoExcessProperties<{ mode: \"default\" | \"either\" | \"validate\" }, O>>(options: O) =>\n        Effect.Do.pipe(\n          Effect.bind(\"x\", () => Effect.succeed(2)),\n          Effect.bindAll(({ x }) => ({\n            a: Effect.fail(x), // <-- fail\n            b: Effect.succeed(\"ops\")\n          }), options)\n        )\n\n      expectLeft(getTest({ mode: \"default\" }), 2)\n      expectRight(getTest({ mode: \"either\" }), {\n        a: Either.left(2),\n        b: Either.right(\"ops\"),\n        x: 2\n      })\n\n      expectLeft(getTest({ mode: \"validate\" }), {\n        a: Option.some(2),\n        b: Option.none()\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/environment.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\n\ninterface NumberService {\n  readonly n: number\n}\n\nconst NumberService = Context.GenericTag<NumberService>(\"NumberService\")\n\ninterface StringService {\n  readonly s: string\n}\n\nconst StringService = Context.GenericTag<StringService>(\"StringService\")\n\nclass NumberRepo extends Context.Tag(\"NumberRepo\")<NumberRepo, {\n  readonly numbers: Array<number>\n}>() {\n  static numbers = Effect.serviceConstants(NumberRepo).numbers\n}\n\nclass DemoTag extends Effect.Tag(\"DemoTag\")<DemoTag, {\n  readonly getNumbers: () => Array<number>\n  readonly strings: Array<string>\n  readonly fn: (...args: ReadonlyArray<string>) => Array<string>\n  readonly fnParamsUnion: (\n    ...args: ReadonlyArray<string> | [number] | [false, true]\n  ) => ReadonlyArray<string> | [number] | [false, true]\n  readonly fnGen: <S>(s: S) => Array<S>\n}>() {\n}\n\nclass DateTag extends Effect.Tag(\"DateTag\")<DateTag, Date>() {\n  static date = new Date(1970, 1, 1)\n  static Live = Layer.succeed(this, this.date)\n}\n\nclass MapTag extends Effect.Tag(\"MapTag\")<MapTag, Map<string, string>>() {\n  static Live = Layer.effect(this, Effect.sync(() => new Map()))\n}\n\nclass NumberTag extends Effect.Tag(\"NumberTag\")<NumberTag, number>() {\n  static Live = Layer.succeed(this, 100)\n}\n\ndescribe(\"Effect\", () => {\n  it.effect(\"provide runtime is additive\", () =>\n    Effect.gen(function*() {\n      const runtime = yield* Effect.runtime<never>()\n      const env = yield* NumberService.pipe(\n        Effect.provide(runtime),\n        Effect.provideService(NumberService, { n: 1 })\n      )\n      deepStrictEqual(env, { n: 1 })\n    }))\n  describe(\"and Then\", () => {\n    it.effect(\"effect tag\", () =>\n      Effect.gen(function*() {\n        const [n, s, z] = yield* (Effect.all([\n          Effect.andThen(Effect.void, DemoTag.getNumbers),\n          Effect.andThen(Effect.succeed(\"a\"), DemoTag.strings),\n          Effect.andThen(Effect.succeed(\"a\"), DemoTag.fn)\n        ]))\n        deepStrictEqual(n, [0, 1])\n        deepStrictEqual(s, [\"a\", \"b\"])\n        deepStrictEqual(z, [\"a\"])\n      }).pipe(Effect.provideService(DemoTag, {\n        getNumbers: () => [0, 1],\n        strings: [\"a\", \"b\"],\n        fn: (...args) => Array.from(args),\n        fnGen: (s) => [s],\n        fnParamsUnion: (..._args) => _args\n      })))\n  })\n  it.effect(\"effect tag\", () =>\n    Effect.gen(function*() {\n      const [n, s, z, zUnion] = yield* (Effect.all([\n        DemoTag.getNumbers(),\n        DemoTag.strings,\n        DemoTag.fn(\"a\", \"b\", \"c\"),\n        DemoTag.fnParamsUnion(1)\n      ]))\n      const s2 = yield* (DemoTag.pipe(Effect.map((_) => _.strings)))\n      const s3 = yield* (DemoTag.use((_) => _.fnGen(\"hello\")))\n      deepStrictEqual(n, [0, 1])\n      deepStrictEqual(s, [\"a\", \"b\"])\n      deepStrictEqual(z, [\"a\", \"b\", \"c\"])\n      deepStrictEqual(zUnion, [1])\n      deepStrictEqual(s2, [\"a\", \"b\"])\n      deepStrictEqual(s3, [\"hello\"])\n    }).pipe(Effect.provideService(DemoTag, {\n      getNumbers: () => [0, 1],\n      strings: [\"a\", \"b\"],\n      fn: (...args) => Array.from(args),\n      fnGen: (s) => [s],\n      fnParamsUnion: (..._args) => _args\n    })))\n  it.effect(\"effect tag with primitives\", () =>\n    Effect.gen(function*() {\n      strictEqual(yield* (DateTag.getTime()), DateTag.date.getTime())\n      strictEqual(yield* NumberTag, 100)\n      deepStrictEqual(Array.from(yield* (MapTag.keys())), [])\n      yield* (MapTag.set(\"foo\", \"bar\"))\n      deepStrictEqual(Array.from(yield* (MapTag.keys())), [\"foo\"])\n      strictEqual(yield* (MapTag.get(\"foo\")), \"bar\")\n    }).pipe(\n      Effect.provide(Layer.mergeAll(\n        DateTag.Live,\n        NumberTag.Live,\n        MapTag.Live\n      ))\n    ))\n  it.effect(\"class tag\", () =>\n    Effect.gen(function*() {\n      yield* (\n        Effect.flatMap(NumberRepo.numbers, (_) => Effect.log(`Numbers: ${_}`)).pipe(\n          Effect.provideService(NumberRepo, { numbers: [0, 1, 2] })\n        )\n      )\n    }))\n  it.effect(\"environment - provide is modular\", () =>\n    pipe(\n      Effect.gen(function*() {\n        const v1 = yield* NumberService\n        const v2 = yield* (\n          pipe(\n            NumberService,\n            Effect.provide(Context.make(NumberService, { n: 2 }))\n          )\n        )\n        const v3 = yield* NumberService\n        strictEqual(v1.n, 4)\n        strictEqual(v2.n, 2)\n        strictEqual(v3.n, 4)\n      }),\n      Effect.provide(Context.make(NumberService, { n: 4 }))\n    ))\n  it.effect(\"environment - provideSomeContext provides context in the right order\", () =>\n    pipe(\n      Effect.gen(function*() {\n        const v1 = yield* NumberService\n        const v2 = yield* StringService\n        strictEqual(v1.n, 1)\n        strictEqual(v2.s, \"ok\")\n      }),\n      Effect.provide(Context.make(NumberService, { n: 1 })),\n      Effect.provide(Context.make(NumberService, { n: 2 })),\n      Effect.provide(Context.make(StringService, { s: \"ok\" }))\n    ))\n  it.effect(\"environment - async can use environment\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.async<number, never, NumberService>((cb) => cb(Effect.map(NumberService, ({ n }) => n))),\n        Effect.provide(Context.make(NumberService, { n: 10 }))\n      )\n      strictEqual(result, 10)\n    }))\n  it.effect(\"serviceWith - effectfully accesses a service in the environment\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.flatMap(NumberService, ({ n }) => Effect.succeed(n + 3)),\n        Effect.provide(Context.make(NumberService, { n: 0 }))\n      )\n      strictEqual(result, 3)\n    }))\n  // TODO: remove\n  // it.effect(\"serviceWith - traced tag\", () =>\n  //   Effect.gen(function*() {\n  //     const result = yield* (\n  //       Effect.flatMap(NumberService.traced(sourceLocation(new Error())), ({ n }) => Effect.succeed(n + 3)),\n  //       Effect.provide(Context.make(NumberService, { n: 0 }))\n  //     )\n  //     strictEqual(result, 3)\n  //   }))\n  it.effect(\"updateService - updates a service in the environment\", () =>\n    pipe(\n      Effect.gen(function*() {\n        const a = yield* pipe(NumberService, Effect.updateService(NumberService, ({ n }) => ({ n: n + 1 })))\n        const b = yield* NumberService\n        strictEqual(a.n, 1)\n        strictEqual(b.n, 0)\n      }),\n      Effect.provide(Context.make(NumberService, { n: 0 }))\n    ))\n\n  it.effect(\"serviceFunctions - expose service functions\", () => {\n    interface Service {\n      foo: (x: string, y: number) => Effect.Effect<string>\n    }\n    const Service = Context.GenericTag<Service>(\"Service\")\n    const { foo } = Effect.serviceFunctions(Service)\n    return pipe(\n      Effect.gen(function*() {\n        strictEqual(yield* foo(\"a\", 3), \"a3\")\n      }),\n      Effect.provideService(\n        Service,\n        Service.of({\n          foo: (x, y) => Effect.succeed(`${x}${y}`)\n        })\n      )\n    )\n  })\n\n  it.effect(\"serviceConstants - expose service constants\", () => {\n    interface Service {\n      baz: Effect.Effect<string>\n    }\n    const Service = Context.GenericTag<Service>(\"Service\")\n    const { baz } = Effect.serviceConstants(Service)\n    return pipe(\n      Effect.gen(function*() {\n        strictEqual(yield* baz, \"42!\")\n      }),\n      Effect.provideService(\n        Service,\n        Service.of({\n          baz: Effect.succeed(\"42!\")\n        })\n      )\n    )\n  })\n\n  it.effect(\"serviceMembers - expose both service functions and constants\", () => {\n    interface Service {\n      foo: (x: string, y: number) => Effect.Effect<string>\n      baz: Effect.Effect<string>\n    }\n    const Service = Context.GenericTag<Service>(\"Service\")\n    const { constants, functions } = Effect.serviceMembers(Service)\n    return pipe(\n      Effect.gen(function*() {\n        strictEqual(yield* constants.baz, \"42!\")\n        strictEqual(yield* functions.foo(\"a\", 3), \"a3\")\n      }),\n      Effect.provideService(\n        Service,\n        Service.of({\n          baz: Effect.succeed(\"42!\"),\n          foo: (x, y) => Effect.succeed(`${x}${y}`)\n        })\n      )\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/error-handling.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport * as fc from \"effect/FastCheck\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberId from \"effect/FiberId\"\nimport { constFalse, constTrue, identity, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport { causesArb } from \"../utils/cause.js\"\n\nconst ExampleError = new Error(\"Oh noes!\")\n\nexport const InterruptError1 = new Error(\"Oh noes 1!\")\nexport const InterruptError2 = new Error(\"Oh noes 2!\")\nexport const InterruptError3 = new Error(\"Oh noes 3!\")\n\nconst ExampleErrorFail: Effect.Effect<never, Error, never> = Effect.fail(ExampleError)\n\nconst deepErrorEffect = (n: number): Effect.Effect<void, Cause.UnknownException> => {\n  if (n === 0) {\n    return Effect.try(() => {\n      throw ExampleError\n    })\n  }\n  return pipe(Effect.void, Effect.zipRight(deepErrorEffect(n - 1)))\n}\n\nconst deepErrorFail = (n: number): Effect.Effect<never, Error> => {\n  if (n === 0) {\n    return Effect.fail(ExampleError)\n  }\n  return pipe(Effect.void, Effect.zipRight(deepErrorFail(n - 1)))\n}\n\ndescribe(\"Effect\", () => {\n  it.effect(\"attempt - error in sync effect\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.try(() => {\n          throw ExampleError\n        }),\n        Effect.flip\n      )\n      deepStrictEqual(result.error, ExampleError)\n    }))\n  it.effect(\"attempt - fail\", () =>\n    Effect.gen(function*() {\n      const io1 = Effect.either(ExampleErrorFail)\n      const io2 = Effect.suspend(() => Effect.either(Effect.suspend(() => ExampleErrorFail)))\n      const [first, second] = yield* pipe(io1, Effect.zip(io2))\n      assertLeft(first, ExampleError)\n      assertLeft(second, ExampleError)\n    }))\n  it.effect(\"attempt - deep attempt sync effect error\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.flip(deepErrorEffect(100)))\n      deepStrictEqual(result.error, ExampleError)\n    }))\n  it.effect(\"attempt - deep attempt fail error\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.either(deepErrorFail(100)))\n      assertLeft(result, ExampleError)\n    }))\n  it.effect(\"attempt - sandbox -> terminate\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.sync(() => {\n          throw ExampleError\n        }),\n        Effect.sandbox,\n        Effect.either\n      )\n      assertLeft(result, Cause.die(ExampleError))\n    }))\n  it.effect(\"catch - sandbox terminate\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.sync(() => {\n          throw ExampleError\n        }),\n        Effect.sandbox,\n        Effect.merge\n      )\n      deepStrictEqual(result, Cause.die(ExampleError))\n    }))\n  it.effect(\"catch failing finalizers with fail\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.fail(ExampleError),\n        Effect.ensuring(Effect.sync(() => {\n          throw InterruptError1\n        })),\n        Effect.ensuring(Effect.sync(() => {\n          throw InterruptError2\n        })),\n        Effect.ensuring(Effect.sync(() => {\n          throw InterruptError3\n        })),\n        Effect.exit\n      )\n      const expected = Cause.sequential(\n        Cause.sequential(\n          Cause.sequential(Cause.fail(ExampleError), Cause.die(InterruptError1)),\n          Cause.die(InterruptError2)\n        ),\n        Cause.die(InterruptError3)\n      )\n      deepStrictEqual(result, Exit.failCause(expected))\n    }))\n  it.effect(\"catch failing finalizers with terminate\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.die(ExampleError),\n        Effect.ensuring(Effect.sync(() => {\n          throw InterruptError1\n        })),\n        Effect.ensuring(Effect.sync(() => {\n          throw InterruptError2\n        })),\n        Effect.ensuring(Effect.sync(() => {\n          throw InterruptError3\n        })),\n        Effect.exit\n      )\n      const expected = Cause.sequential(\n        Cause.sequential(\n          Cause.sequential(Cause.die(ExampleError), Cause.die(InterruptError1)),\n          Cause.die(InterruptError2)\n        ),\n        Cause.die(InterruptError3)\n      )\n      deepStrictEqual(result, Exit.failCause(expected))\n    }))\n  it.effect(\"catchAllCause\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(Effect.succeed(42), Effect.zipRight(Effect.fail(\"uh oh\")), Effect.catchAllCause(Effect.succeed))\n      )\n      deepStrictEqual(result, Cause.fail(\"uh oh\"))\n    }))\n  it.effect(\"catchAllDefect - recovers from all defects\", () =>\n    Effect.gen(function*() {\n      const message = \"division by zero\"\n      const result = yield* pipe(\n        Effect.die(new Cause.IllegalArgumentException(message)),\n        Effect.catchAllDefect((e) => Effect.succeed((e as Error).message))\n      )\n      strictEqual(result, message)\n    }))\n  it.effect(\"catchAllDefect - leaves errors\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.IllegalArgumentException(\"division by zero\")\n      const result = yield* (\n        pipe(Effect.fail(error), Effect.catchAllDefect((e) => Effect.succeed((e as Error).message)), Effect.exit)\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n  it.effect(\"catchAllDefect - leaves values\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.IllegalArgumentException(\"division by zero\")\n      const result = yield* (\n        pipe(Effect.succeed(error), Effect.catchAllDefect((e) => Effect.succeed((e as Error).message)))\n      )\n      deepStrictEqual(result, error)\n    }))\n  it.effect(\"catchSomeDefect - recovers from some defects\", () =>\n    Effect.gen(function*() {\n      const message = \"division by zero\"\n      const result = yield* pipe(\n        Effect.die(new Cause.IllegalArgumentException(message)),\n        Effect.catchSomeDefect((e) =>\n          Cause.isIllegalArgumentException(e)\n            ? Option.some(Effect.succeed(e.message))\n            : Option.none()\n        )\n      )\n      strictEqual(result, message)\n    }))\n  it.effect(\"catchSomeDefect - leaves the rest\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.IllegalArgumentException(\"division by zero\")\n      const result = yield* pipe(\n        Effect.die(error),\n        Effect.catchSomeDefect((e) =>\n          Cause.isRuntimeException(e) ?\n            Option.some(Effect.succeed(e.message)) :\n            Option.none()\n        ),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n  it.effect(\"catchSomeDefect - leaves errors\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.IllegalArgumentException(\"division by zero\")\n      const result = yield* pipe(\n        Effect.fail(error),\n        Effect.catchSomeDefect((e) =>\n          Cause.isIllegalArgumentException(e)\n            ? Option.some(Effect.succeed(e.message))\n            : Option.none()\n        ),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n  it.effect(\"catchSomeDefect - leaves values\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.IllegalArgumentException(\"division by zero\")\n      const result = yield* pipe(\n        Effect.succeed(error),\n        Effect.catchSomeDefect((e) =>\n          Cause.isIllegalArgumentException(e)\n            ? Option.some(Effect.succeed(e.message))\n            : Option.none()\n        )\n      )\n      deepStrictEqual(result, error)\n    }))\n  it.effect(\"catch - recovers from one of several tagged errors\", () =>\n    Effect.gen(function*() {\n      interface ErrorA {\n        readonly _tag: \"ErrorA\"\n      }\n      interface ErrorB {\n        readonly _tag: \"ErrorB\"\n      }\n      const effect: Effect.Effect<never, ErrorA | ErrorB, never> = Effect.fail({ _tag: \"ErrorA\" })\n      const result = yield* (Effect.catch(effect, \"_tag\", {\n        failure: \"ErrorA\",\n        onFailure: Effect.succeed\n      }))\n      deepStrictEqual(result, { _tag: \"ErrorA\" })\n    }))\n  it.effect(\"catch - does not recover from one of several tagged errors\", () =>\n    Effect.gen(function*() {\n      interface ErrorA {\n        readonly _tag: \"ErrorA\"\n      }\n      interface ErrorB {\n        readonly _tag: \"ErrorB\"\n      }\n      const effect: Effect.Effect<never, ErrorA | ErrorB, never> = Effect.fail({ _tag: \"ErrorB\" })\n      const result = yield* pipe(\n        Effect.catch(effect, \"_tag\", {\n          failure: \"ErrorA\",\n          onFailure: Effect.succeed\n        }),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail({ _tag: \"ErrorB\" as const }))\n    }))\n  it.effect(\"catchIf - does not recover from one of several tagged errors\", () =>\n    Effect.gen(function*() {\n      interface ErrorA {\n        readonly _tag: \"ErrorA\"\n      }\n      interface ErrorB {\n        readonly _tag: \"ErrorB\"\n      }\n      const effect: Effect.Effect<never, ErrorA | ErrorB, never> = Effect.fail({ _tag: \"ErrorB\" })\n      const result = yield* pipe(\n        Effect.catchIf(effect, (e): e is ErrorA => e._tag === \"ErrorA\", Effect.succeed),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail({ _tag: \"ErrorB\" as const }))\n    }))\n  it.effect(\"catchTags - recovers from one of several tagged errors\", () =>\n    Effect.gen(function*() {\n      interface ErrorA {\n        readonly _tag: \"ErrorA\"\n      }\n      interface ErrorB {\n        readonly _tag: \"ErrorB\"\n      }\n      const effect: Effect.Effect<never, ErrorA | ErrorB, never> = Effect.fail({ _tag: \"ErrorA\" })\n      const result = yield* (Effect.catchTags(effect, {\n        ErrorA: (e) => Effect.succeed(e)\n      }))\n      deepStrictEqual(result, { _tag: \"ErrorA\" })\n    }))\n  it.effect(\"catchTags - does not recover from one of several tagged errors\", () =>\n    Effect.gen(function*() {\n      interface ErrorA {\n        readonly _tag: \"ErrorA\"\n      }\n      interface ErrorB {\n        readonly _tag: \"ErrorB\"\n      }\n      const effect: Effect.Effect<never, ErrorA | ErrorB, never> = Effect.fail({ _tag: \"ErrorB\" })\n      const result = yield* (Effect.exit(\n        Effect.catchTags(effect, {\n          ErrorA: (e) => Effect.succeed(e)\n        })\n      ))\n      deepStrictEqual(result, Exit.fail<ErrorB>({ _tag: \"ErrorB\" }))\n    }))\n  it.effect(\"catchTags - recovers from all tagged errors\", () =>\n    Effect.gen(function*() {\n      interface ErrorA {\n        readonly _tag: \"ErrorA\"\n      }\n      interface ErrorB {\n        readonly _tag: \"ErrorB\"\n      }\n      const effect: Effect.Effect<never, ErrorA | ErrorB, never> = Effect.fail({ _tag: \"ErrorB\" })\n      const result = yield* (Effect.catchTags(effect, {\n        ErrorA: (e) => Effect.succeed(e),\n        ErrorB: (e) => Effect.succeed(e)\n      }))\n      deepStrictEqual(result, { _tag: \"ErrorB\" })\n    }))\n  it.effect(\"fold - sandbox -> terminate\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.sync(() => {\n          throw ExampleError\n        }),\n        Effect.sandbox,\n        Effect.match({\n          onFailure: Option.some,\n          onSuccess: () => Option.none() as Option.Option<Cause.Cause<never>>\n        })\n      )\n      deepStrictEqual(result, Option.some(Cause.die(ExampleError)))\n    }))\n  it.effect(\"ignore - return success as unit\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.ignore(Effect.succeed(11)))\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"ignore - return failure as unit\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.ignore(Effect.fail(123)))\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"ignore - not catch throwable\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.exit(Effect.ignore(Effect.die(ExampleError))))\n      deepStrictEqual(result, Exit.die(ExampleError))\n    }))\n  it.effect(\"orElse - does not recover from defects\", () =>\n    Effect.gen(function*() {\n      const error = new Error(\"died\")\n      const fiberId = FiberId.make(0, 123)\n      const bothCause = Cause.parallel(Cause.interrupt(fiberId), Cause.die(error))\n      const thenCause = Cause.sequential(Cause.interrupt(fiberId), Cause.die(error))\n      const plain = yield* pipe(Effect.die(error), Effect.orElse(() => Effect.void), Effect.exit)\n      const both = yield* pipe(Effect.failCause(bothCause), Effect.orElse(() => Effect.void), Effect.exit)\n      const then = yield* pipe(Effect.failCause(thenCause), Effect.orElse(() => Effect.void), Effect.exit)\n      const fail = yield* pipe(Effect.fail(error), Effect.orElse(() => Effect.void), Effect.exit)\n      deepStrictEqual(plain, Exit.die(error))\n      deepStrictEqual(both, Exit.die(error))\n      deepStrictEqual(then, Exit.die(error))\n      deepStrictEqual(fail, Exit.succeed(void 0))\n    }))\n  it.effect(\"orElse - left failed and right died with kept cause\", () =>\n    Effect.gen(function*() {\n      const z1 = Effect.fail(new Cause.RuntimeException(\"1\"))\n      const z2 = Effect.die(new Cause.RuntimeException(\"2\"))\n      const result = yield* pipe(\n        z1,\n        Effect.orElse(() => z2),\n        Effect.catchAllCause((cause) => {\n          if (Cause.isDie(cause)) {\n            const defects = Cause.defects(cause)\n            if (Chunk.isNonEmpty(defects)) {\n              const head = Chunk.headNonEmpty(defects)\n              return Effect.succeed((head as Cause.RuntimeException).message === \"2\")\n            }\n          }\n          return Effect.succeed(false)\n        })\n      )\n      assertTrue(result)\n    }))\n  it.effect(\"orElse - left failed and right failed with kept cause\", () =>\n    Effect.gen(function*() {\n      const z1 = Effect.fail(new Cause.RuntimeException(\"1\"))\n      const z2 = Effect.fail(new Cause.RuntimeException(\"2\"))\n      const result = yield* pipe(\n        z1,\n        Effect.orElse(() => z2),\n        Effect.catchAllCause((cause) => {\n          if (Cause.isFailure(cause)) {\n            const failures = Cause.failures(cause)\n            if (Chunk.isNonEmpty(failures)) {\n              const head = Chunk.headNonEmpty(failures)\n              return Effect.succeed(head.message === \"2\")\n            }\n          }\n          return Effect.succeed(false)\n        })\n      )\n      assertTrue(result)\n    }))\n  it(\"orElse - is associative\", async () => {\n    const smallInts = fc.integer({ min: 0, max: 100 })\n    const causes = causesArb(1, smallInts, fc.string())\n    const successes = smallInts.map(Effect.succeed)\n    const exits = fc.oneof(\n      causes.map((s): Either.Either<Effect.Effect<number>, Cause.Cause<number>> => Either.left(s)),\n      successes.map((s): Either.Either<Effect.Effect<number>, Cause.Cause<number>> => Either.right(s))\n    ).map(Either.match({\n      onLeft: Exit.failCause,\n      onRight: Exit.succeed\n    }))\n    await fc.assert(fc.asyncProperty(exits, exits, exits, async (exit1, exit2, exit3) => {\n      const leftEffect = pipe(exit1, Effect.orElse(() => exit2), Effect.orElse(() => exit3))\n      const rightEffect = pipe(exit1, Effect.orElse(() => pipe(exit2, Effect.orElse(() => exit3))))\n      const program = Effect.gen(function*() {\n        const left = yield* (Effect.exit(leftEffect))\n        const right = yield* (Effect.exit(rightEffect))\n        return { left, right }\n      })\n      const { left, right } = await Effect.runPromise(program)\n      deepStrictEqual(left, right)\n    }))\n  })\n  it.effect(\"orElseFail - executes this effect and returns its value if it succeeds\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.succeed(true), Effect.orElseFail(constFalse))\n      assertTrue(result)\n    }))\n  it.effect(\"orElseFail - otherwise fails with the specified error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.fail(false), Effect.orElseFail(constTrue), Effect.flip)\n      assertTrue(result)\n    }))\n  it.effect(\"orElseSucceed - executes this effect and returns its value if it succeeds\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.succeed(true), Effect.orElseSucceed(constFalse))\n      assertTrue(result)\n    }))\n  it.effect(\"orElseSucceed - otherwise succeeds with the specified value\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.fail(false), Effect.orElseSucceed(constTrue))\n      assertTrue(result)\n    }))\n  it.effect(\"parallelErrors - one failure\", () =>\n    Effect.gen(function*() {\n      const fiber1 = yield* (Effect.fork(Effect.fail(\"error1\")))\n      const fiber2 = yield* (Effect.fork(Effect.succeed(\"success1\")))\n      const result = yield* pipe(fiber1, Fiber.zip(fiber2), Fiber.join, Effect.parallelErrors, Effect.flip)\n      deepStrictEqual(Array.from(result), [\"error1\"])\n    }))\n  it.effect(\"parallelErrors - all failures\", () =>\n    Effect.gen(function*() {\n      const fiber1 = yield* (Effect.fork(Effect.fail(\"error1\")))\n      const fiber2 = yield* (Effect.fork(Effect.fail(\"error2\")))\n      const result = yield* pipe(fiber1, Fiber.zip(fiber2), Fiber.join, Effect.parallelErrors, Effect.flip)\n      deepStrictEqual(Array.from(result), [\"error1\", \"error2\"])\n    }))\n  it.effect(\"promise - exception does not kill fiber\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.promise(() => {\n          throw ExampleError\n        }),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(ExampleError))\n    }))\n  it.effect(\"try = handles exceptions\", () =>\n    Effect.gen(function*() {\n      const message = \"hello\"\n      const result = yield* pipe(\n        Effect.try({\n          try: () => {\n            throw message\n          },\n          catch: identity\n        }),\n        Effect.exit\n      )\n\n      deepStrictEqual(result, Exit.fail(message))\n    }))\n  it.effect(\"uncaught - fail\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.exit(ExampleErrorFail))\n      deepStrictEqual(result, Exit.fail(ExampleError))\n    }))\n  it.effect(\"uncaught - sync effect error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.sync(() => {\n          throw ExampleError\n        }),\n        Effect.exit\n      )\n\n      deepStrictEqual(result, Exit.die(ExampleError))\n    }))\n  it.effect(\"uncaught - deep sync effect error\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.flip(deepErrorEffect(100)))\n      deepStrictEqual(result.error, ExampleError)\n    }))\n  it.effect(\"unwraps exception\", () =>\n    Effect.gen(function*() {\n      const failure = Effect.fail(Cause.fail(new Error(\"fail\")))\n      const success = Effect.succeed(100)\n      const message = yield* pipe(\n        failure,\n        Effect.unsandbox,\n        Effect.matchEffect({\n          onFailure: (e) => Effect.succeed(e.message),\n          onSuccess: () => Effect.succeed(\"unexpected\")\n        })\n      )\n      const result = yield* (Effect.unsandbox(success))\n      strictEqual(message, \"fail\")\n      strictEqual(result, 100)\n    }))\n  it.effect(\"no information is lost during composition\", () =>\n    Effect.gen(function*() {\n      const cause = <R, E>(effect: Effect.Effect<never, E, R>): Effect.Effect<Cause.Cause<E>, never, R> => {\n        return Effect.cause(effect)\n      }\n      const expectedCause = Cause.fail(\"oh no\")\n      const result = yield* (cause(pipe(Effect.failCause(expectedCause), Effect.sandbox, Effect.unsandbox)))\n      deepStrictEqual(result, expectedCause)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/error.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInclude, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Cause, Data, Effect, pipe } from \"effect\"\n\nclass TestError extends Data.TaggedError(\"TestError\")<{}> {}\n\ndescribe(\"Effect\", () => {\n  it.effect(\"TaggedError has a stack\", () =>\n    Effect.gen(function*() {\n      const cause = yield* (Effect.flip(Effect.sandbox(Effect.withSpan(\"A\")(new TestError()))))\n      const log = Cause.pretty(cause)\n      assertInclude(log, \"TestError\")\n      if (typeof window === \"undefined\") {\n        assertInclude(log.replaceAll(\"\\\\\", \"/\"), \"test/Effect/error.test.ts:10:77\")\n      }\n      assertInclude(log, \"at A\")\n    }))\n\n  it.effect(\"tryPromise\", () =>\n    Effect.gen(function*() {\n      const cause = yield* pipe(\n        Effect.tryPromise({\n          try: () => Promise.reject(\"fail\"),\n          catch: () => new TestError()\n        }),\n        Effect.withSpan(\"A\"),\n        Effect.sandbox,\n        Effect.flip\n      )\n      const log = Cause.pretty(cause)\n      if (typeof window === \"undefined\") {\n        assertInclude(log.replaceAll(\"\\\\\", \"/\"), \"test/Effect/error.test.ts:24\")\n      }\n      assertInclude(log, \"at A\")\n    }))\n\n  it.effect(\"allow message prop\", () =>\n    Effect.gen(function*() {\n      class MessageError extends Data.TaggedError(\"MessageError\")<{\n        readonly name: string\n        readonly message: string\n      }> {}\n      const cause = yield* pipe(\n        Effect.tryPromise({\n          try: () => Promise.reject(\"fail\"),\n          catch: () => new MessageError({ name: \"Failure\", message: \"some message\" })\n        }),\n        Effect.withSpan(\"A\"),\n        Effect.sandbox,\n        Effect.flip\n      )\n      const log = Cause.pretty(cause)\n      assertInclude(log, \"Failure: some message\")\n      if (typeof window === \"undefined\") {\n        assertInclude(log.replaceAll(\"\\\\\", \"/\"), \"test/Effect/error.test.ts:46\")\n      }\n      assertInclude(log, \"at A\")\n    }))\n\n  if (typeof window === \"undefined\") {\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n\n    it(\"inspect\", () => {\n      class MessageError extends Data.TaggedError(\"MessageError\") {\n        get message() {\n          return \"fail\"\n        }\n      }\n      const err = new MessageError()\n      assertInclude(inspect(err), \"MessageError: fail\")\n      assertInclude(inspect(err).replaceAll(\"\\\\\", \"/\"), \"test/Effect/error.test.ts:70\")\n    })\n\n    it(\"toString\", () => {\n      class MessageError extends Data.TaggedError(\"MessageError\") {\n        toString() {\n          return \"fail\"\n        }\n      }\n      assertTrue(inspect(new MessageError()).startsWith(\"fail\\n\"))\n      deepStrictEqual(new MessageError().toJSON(), { _tag: \"MessageError\" })\n    })\n\n    it(\"cause\", () => {\n      class MessageError extends Data.TaggedError(\"MessageError\")<{\n        cause: unknown\n      }> {}\n      assertInclude(inspect(new MessageError({ cause: new Error(\"boom\") })), \"[cause]: Error: boom\")\n    })\n  }\n\n  it(\"toJSON\", () => {\n    class MessageError extends Data.TaggedError(\"MessageError\")<{}> {}\n    deepStrictEqual(new MessageError().toJSON(), { _tag: \"MessageError\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/filtering.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertRight, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport { strictEqual } from \"node:assert\"\n\nconst exactlyOnce = <R, A, A1>(\n  value: A,\n  f: (_: Effect.Effect<A>) => Effect.Effect<A1, string, R>\n): Effect.Effect<A1, string, R> => {\n  return Effect.gen(function*() {\n    const ref = yield* (Ref.make(0))\n    const res = yield* (f(pipe(Ref.update(ref, (n) => n + 1), Effect.zipRight(Effect.succeed(value)))))\n    const count = yield* (Ref.get(ref))\n    yield* (count !== 1 ? Effect.fail(\"Accessed more than once\") : Effect.void)\n    return res\n  })\n}\n\ndescribe(\"Effect\", () => {\n  it.effect(\"filter - filters a collection using an effectual predicate\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<ReadonlyArray<number>>([]))\n      const results = yield* (\n        pipe(\n          [2, 4, 6, 3, 5, 6],\n          Effect.filter((n) => pipe(Ref.update(ref, (ns) => [n, ...ns]), Effect.as(n % 2 === 0)))\n        )\n      )\n      const effects = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(results), [2, 4, 6, 6])\n      deepStrictEqual(Array.from(effects), [2, 4, 6, 3, 5, 6])\n    }))\n  it.effect(\"filter/negate - filters a collection using an effectual predicate, removing all elements that satisfy the predicate\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<ReadonlyArray<number>>([]))\n      const results = yield* (\n        pipe(\n          [2, 4, 6, 3, 5, 6],\n          Effect.filter((n) => pipe(Ref.update(ref, (ns) => [n, ...ns]), Effect.as(n % 2 === 0)), { negate: true })\n        )\n      )\n      const effects = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(results), [3, 5])\n      deepStrictEqual(Array.from(effects), [2, 4, 6, 3, 5, 6])\n    }))\n  it.effect(\"filter/concurrency - filters a collection in parallel using an effectual predicate\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          [2, 4, 6, 3, 5, 6, 10, 11, 15, 17, 20, 22, 23, 25, 28],\n          Effect.filter((n) => Effect.succeed(n % 2 === 0), { concurrency: \"unbounded\" })\n        )\n      )\n      deepStrictEqual(Array.from(result), [2, 4, 6, 6, 10, 20, 22, 28])\n    }))\n  it.effect(\"filter/concurrency+negate - filters a collection in parallel using an effectual predicate, removing all elements that satisfy the predicate\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          [2, 4, 6, 3, 5, 6, 10, 11, 15, 17, 20, 22, 23, 25, 28],\n          Effect.filter((n) => Effect.succeed(n % 2 === 0), {\n            concurrency: \"unbounded\",\n            negate: true\n          })\n        )\n      )\n      deepStrictEqual(Array.from(result), [3, 5, 11, 15, 17, 23, 25])\n    }))\n  it.effect(\"filterOrElse - returns checked failure from held value\", () =>\n    Effect.gen(function*() {\n      const goodCase = yield* pipe(\n        exactlyOnce(0, (effect) =>\n          pipe(\n            effect,\n            Effect.filterOrElse(\n              (n) => n === 0,\n              (n) => Effect.fail(`${n} was not 0`)\n            )\n          )),\n        Effect.sandbox,\n        Effect.either\n      )\n      const badCase = yield* pipe(\n        exactlyOnce(1, (effect) =>\n          pipe(\n            effect,\n            Effect.filterOrElse(\n              (n) => n === 0,\n              (n) => Effect.fail(`${n} was not 0`)\n            )\n          )),\n        Effect.sandbox,\n        Effect.either,\n        Effect.map(Either.mapLeft(Cause.failureOrCause))\n      )\n      assertRight(goodCase, 0)\n      assertLeft(badCase, Either.left(\"1 was not 0\"))\n    }))\n  it.effect(\"filterOrElse - returns checked failure ignoring value\", () =>\n    Effect.gen(function*() {\n      const goodCase = yield* pipe(\n        exactlyOnce(0, (effect) =>\n          pipe(\n            effect,\n            Effect.filterOrElse(\n              (n) => n === 0,\n              () => Effect.fail(\"predicate failed!\")\n            )\n          )),\n        Effect.sandbox,\n        Effect.either\n      )\n      const badCase = yield* pipe(\n        exactlyOnce(1, (effect) =>\n          pipe(\n            effect,\n            Effect.filterOrElse(\n              (n) => n === 0,\n              () => Effect.fail(\"predicate failed!\")\n            )\n          )),\n        Effect.sandbox,\n        Effect.either,\n        Effect.map(Either.mapLeft(Cause.failureOrCause))\n      )\n      assertRight(goodCase, 0)\n      assertLeft(badCase, Either.left(\"predicate failed!\"))\n    }))\n  it.effect(\"filterOrFail - returns failure ignoring value\", () =>\n    Effect.gen(function*() {\n      const goodCase = yield* pipe(\n        exactlyOnce(0, (effect) =>\n          pipe(\n            effect,\n            Effect.filterOrFail(\n              (n) => n === 0,\n              () => \"predicate failed!\"\n            )\n          )),\n        Effect.sandbox,\n        Effect.either\n      )\n      const badCase = yield* pipe(\n        exactlyOnce(1, (effect) =>\n          pipe(\n            effect,\n            Effect.filterOrFail(\n              (n) => n === 0,\n              () => \"predicate failed!\"\n            )\n          )),\n        Effect.sandbox,\n        Effect.either,\n        Effect.map(Either.mapLeft(Cause.failureOrCause))\n      )\n      assertRight(goodCase, 0)\n      assertLeft(badCase, Either.left(\"predicate failed!\"))\n    }))\n  it.effect(\"filterOrFail - returns failure\", () =>\n    Effect.gen(function*() {\n      const goodCase = yield* pipe(\n        exactlyOnce(0, (effect) =>\n          pipe(\n            effect,\n            Effect.filterOrFail(\n              (n) => n === 0,\n              (n) => `predicate failed, got ${n}!`\n            )\n          )),\n        Effect.sandbox,\n        Effect.either\n      )\n      const badCase = yield* pipe(\n        exactlyOnce(1, (effect) =>\n          pipe(\n            effect,\n            Effect.filterOrFail(\n              (n) => n === 0,\n              (n) => `predicate failed, got ${n}!`\n            )\n          )),\n        Effect.sandbox,\n        Effect.either,\n        Effect.map(Either.mapLeft(Cause.failureOrCause))\n      )\n      assertRight(goodCase, 0)\n      assertLeft(badCase, Either.left(\"predicate failed, got 1!\"))\n    }))\n\n  it.effect(\"filterOrFail - without orFailWith\", () =>\n    Effect.gen(function*() {\n      const goodCase = yield* pipe(\n        Effect.succeed(0),\n        Effect.filterOrFail((n) => n === 0)\n      )\n      const goodCaseDataFirst = yield* Effect.filterOrFail(Effect.succeed(0), (n) => n === 0)\n      const badCase = yield* pipe(\n        Effect.succeed(1),\n        Effect.filterOrFail((n) => n === 0),\n        Effect.flip\n      )\n      deepStrictEqual(goodCase, 0)\n      deepStrictEqual(goodCaseDataFirst, 0)\n      deepStrictEqual(badCase, new Cause.NoSuchElementException())\n    }))\n\n  describe(\"filterEffectOrElse\", () => {\n    it.effect(\"executes fallback\", () =>\n      Effect.gen(function*() {\n        const result = yield* Effect.succeed(1).pipe(\n          Effect.filterEffectOrElse({\n            predicate: (n) => Effect.succeed(n === 0),\n            orElse: () => Effect.succeed(0)\n          })\n        )\n        strictEqual(result, 0)\n      }))\n  })\n\n  describe(\"filterEffectOrFails\", () => {\n    it.effect(\"executes orFailWith\", () =>\n      Effect.gen(function*() {\n        const result = yield* Effect.succeed(1).pipe(\n          Effect.filterEffectOrElse({\n            predicate: (n) => Effect.succeed(n === 0),\n            orElse: () => Effect.fail(\"boom\")\n          }),\n          Effect.flip\n        )\n        strictEqual(result, \"boom\")\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/finalization.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\n\nconst ExampleError = new Error(\"Oh noes!\")\n\nconst asyncExampleError = <A>(): Effect.Effect<A, unknown> => {\n  return Effect.async((cb) => {\n    cb(Effect.fail(ExampleError))\n  })\n}\n\nconst asyncVoid = <E>(): Effect.Effect<void, E> => {\n  return Effect.async((cb) => {\n    cb(Effect.void)\n  })\n}\n\ndescribe(\"Effect\", () => {\n  it.effect(\"fail ensuring\", () =>\n    Effect.gen(function*() {\n      let finalized = false\n      const result = yield* pipe(\n        Effect.fail(ExampleError),\n        Effect.ensuring(Effect.sync(() => {\n          finalized = true\n        })),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(ExampleError))\n      assertTrue(finalized)\n    }))\n  it.effect(\"fail on error\", () =>\n    Effect.gen(function*() {\n      let finalized = false\n      const result = yield* pipe(\n        Effect.fail(ExampleError),\n        Effect.onError(() =>\n          Effect.sync(() => {\n            finalized = true\n          })\n        ),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(ExampleError))\n      assertTrue(finalized)\n    }))\n  it.effect(\"finalizer errors not caught\", () =>\n    Effect.gen(function*() {\n      const e2 = new Error(\"e2\")\n      const e3 = new Error(\"e3\")\n      const result = yield* (\n        pipe(\n          Effect.fail(ExampleError),\n          Effect.ensuring(Effect.die(e2)),\n          Effect.ensuring(Effect.die(e3)),\n          Effect.sandbox,\n          Effect.flip,\n          Effect.map((cause) => cause)\n        )\n      )\n      const expected = Cause.sequential(Cause.sequential(Cause.fail(ExampleError), Cause.die(e2)), Cause.die(e3))\n      deepStrictEqual(result, expected)\n    }))\n  it.effect(\"finalizer errors reported\", () =>\n    Effect.gen(function*() {\n      let reported: Exit.Exit<number> | undefined\n      const result = yield* (\n        pipe(\n          Effect.succeed(42),\n          Effect.ensuring(Effect.die(ExampleError)),\n          Effect.fork,\n          Effect.flatMap((fiber) =>\n            pipe(\n              Fiber.await(fiber),\n              Effect.flatMap((e) =>\n                Effect.sync(() => {\n                  reported = e\n                })\n              )\n            )\n          )\n        )\n      )\n      strictEqual(result, undefined)\n      assertFalse(reported !== undefined && Exit.isSuccess(reported))\n    }))\n  it.effect(\"acquireUseRelease exit.effect() is usage result\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.acquireUseRelease(\n        Effect.void,\n        () => Effect.succeed(42),\n        () => Effect.void\n      ))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"error in just acquisition\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          Effect.acquireUseRelease(\n            Effect.fail(ExampleError),\n            () => Effect.void,\n            () => Effect.void\n          ),\n          Effect.exit\n        )\n      )\n      deepStrictEqual(result, Exit.fail(ExampleError))\n    }))\n  it.effect(\"error in just release\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          Effect.acquireUseRelease(\n            Effect.void,\n            () => Effect.void,\n            () => Effect.die(ExampleError)\n          ),\n          Effect.exit\n        )\n      )\n      deepStrictEqual(result, Exit.die(ExampleError))\n    }))\n  it.effect(\"error in just usage\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          Effect.acquireUseRelease(\n            Effect.void,\n            () => Effect.fail(ExampleError),\n            () => Effect.void\n          ),\n          Effect.exit\n        )\n      )\n      deepStrictEqual(result, Exit.fail(ExampleError))\n    }))\n  it.effect(\"rethrown caught error in acquisition\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.acquireUseRelease(\n          Effect.fail(ExampleError),\n          () => Effect.void,\n          () => Effect.void\n        ),\n        Effect.either,\n        Effect.flatMap(identity),\n        Effect.flip\n      )\n      deepStrictEqual(result, ExampleError)\n    }))\n  it.effect(\"rethrown caught error in release\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          Effect.acquireUseRelease(\n            Effect.void,\n            () => Effect.void,\n            () => Effect.die(ExampleError)\n          ),\n          Effect.exit\n        )\n      )\n      deepStrictEqual(result, Exit.die(ExampleError))\n    }))\n  it.effect(\"rethrown caught error in usage\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.acquireUseRelease(\n          Effect.void,\n          () => Effect.fail(ExampleError),\n          () => Effect.void\n        ),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(ExampleError))\n    }))\n  it.effect(\"test eval of async fail\", () =>\n    Effect.gen(function*() {\n      const io1 = Effect.acquireUseRelease(\n        Effect.void,\n        () => asyncExampleError<void>(),\n        () => asyncVoid<never>()\n      )\n      const io2 = Effect.acquireUseRelease(\n        asyncVoid<never>(),\n        () => asyncExampleError<void>(),\n        () => asyncVoid<never>()\n      )\n      const a1 = yield* (Effect.exit(io1))\n      const a2 = yield* (Effect.exit(io2))\n      const a3 = yield* pipe(io1, Effect.exit)\n      const a4 = yield* pipe(io2, Effect.exit)\n      deepStrictEqual(a1, Exit.fail(ExampleError))\n      deepStrictEqual(a2, Exit.fail(ExampleError))\n      deepStrictEqual(a3, Exit.fail(ExampleError))\n      deepStrictEqual(a4, Exit.fail(ExampleError))\n    }))\n  it.live(\"acquireUseRelease regression 1\", () =>\n    Effect.gen(function*() {\n      const makeLogger = (ref: Ref.Ref<Chunk.Chunk<string>>) => {\n        return (line: string): Effect.Effect<void> => {\n          return Ref.update(ref, Chunk.prepend(line))\n        }\n      }\n      const ref = yield* (Ref.make(Chunk.empty<string>()))\n      const log = makeLogger(ref)\n      const fiber = yield* pipe(\n        Effect.acquireUseRelease(\n          Effect.acquireUseRelease(\n            Effect.void,\n            () => Effect.void,\n            () =>\n              pipe(\n                log(\"start 1\"),\n                Effect.zipRight(Effect.sleep(Duration.millis(10))),\n                Effect.zipRight(log(\"release 1\"))\n              )\n          ),\n          () => Effect.void,\n          () =>\n            pipe(\n              log(\"start 2\"),\n              Effect.zipRight(Effect.sleep(Duration.millis(10))),\n              Effect.zipRight(log(\"release 2\"))\n            )\n        ),\n        Effect.fork\n      )\n      yield* pipe(\n        Ref.get(ref),\n        Effect.zipLeft(Effect.sleep(Duration.millis(1))),\n        Effect.repeat({ until: (list) => pipe(list, Array.findFirst((s) => s === \"start 1\"), Option.isSome) })\n      )\n      yield* (Fiber.interrupt(fiber))\n      yield* pipe(\n        Ref.get(ref),\n        Effect.zipLeft(Effect.sleep(Duration.millis(1))),\n        Effect.repeat({ until: (list) => pipe(list, Array.findFirst((s) => s === \"release 2\"), Option.isSome) })\n      )\n      const result = yield* (Ref.get(ref))\n      assertTrue(pipe(\n        result,\n        Array.findFirst((s) => s === \"start 1\"),\n        Option.isSome\n      ))\n      assertTrue(pipe(\n        result,\n        Array.findFirst((s) => s === \"release 1\"),\n        Option.isSome\n      ))\n      assertTrue(pipe(result, Array.findFirst((s) => s === \"start 2\"), Option.isSome))\n      assertTrue(pipe(result, Array.findFirst((s) => s === \"release 2\"), Option.isSome))\n    }))\n  it.live(\"interrupt waits for finalizer\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<number>())\n      const fiber = yield* (\n        pipe(\n          Deferred.succeed(deferred1, void 0),\n          Effect.zipRight(Deferred.await(deferred2)),\n          Effect.ensuring(pipe(Ref.set(ref, true), Effect.zipRight(Effect.sleep(Duration.millis(10))))),\n          Effect.fork\n        )\n      )\n      yield* (Deferred.await(deferred1))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n  it.effect(\"onExit - executes that a cleanup function runs when effect succeeds\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      yield* pipe(\n        Effect.void,\n        Effect.onExit(Exit.match({\n          onFailure: () => Effect.void,\n          onSuccess: () => Ref.set(ref, true)\n        }))\n      )\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n  it.effect(\"onExit - ensures that a cleanup function runs when an effect fails\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      yield* pipe(\n        Effect.die(Cause.RuntimeException),\n        Effect.onExit((exit) =>\n          Exit.isFailure(exit) && Cause.isDie(exit.effect_instruction_i0) ?\n            Ref.set(ref, true) :\n            Effect.void\n        ),\n        Effect.sandbox,\n        Effect.ignore\n      )\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n  it.effect(\"onExit - ensures that a cleanup function runs when an effect is interrupted\", () =>\n    Effect.gen(function*() {\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const fiber = yield* (\n        pipe(\n          Deferred.succeed(latch1, void 0),\n          Effect.zipRight(Effect.never),\n          Effect.onExit((exit) =>\n            Exit.isFailure(exit) && Cause.isInterrupted(exit.effect_instruction_i0) ?\n              pipe(Deferred.succeed(latch2, void 0), Effect.asVoid) :\n              Effect.void\n          ),\n          Effect.fork\n        )\n      )\n      yield* (Deferred.await(latch1))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Deferred.await(latch2))\n      strictEqual(result, undefined)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/fn.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertEquals, assertInstanceOf, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Cause, Chunk, Effect, Stream } from \"effect\"\n\ndescribe(\"Effect.fn\", () => {\n  it.effect(\"catches defects in the function\", () =>\n    Effect.gen(function*() {\n      let caught: Cause.Cause<never> | undefined\n      const fn = Effect.fn(\"test\")(\n        (): Effect.Effect<void> => {\n          throw new Error(\"test\")\n        },\n        Effect.tapErrorCause((cause) => {\n          caught = cause\n          return Effect.void\n        })\n      )\n      const cause = yield* fn().pipe(\n        Effect.sandbox,\n        Effect.flip\n      )\n      assertTrue(Cause.isDieType(cause))\n      assertInstanceOf(cause.defect, Error)\n      strictEqual(cause.defect.message, \"test\")\n      strictEqual(caught, cause)\n    }))\n\n  it.effect(\"catches defects in pipeline\", () =>\n    Effect.gen(function*() {\n      const fn = Effect.fn(\"test\")(\n        () => Effect.void,\n        (_): Effect.Effect<void> => {\n          throw new Error(\"test\")\n        }\n      )\n      const cause = yield* fn().pipe(\n        Effect.sandbox,\n        Effect.flip\n      )\n      assertTrue(Cause.isDieType(cause))\n      assertInstanceOf(cause.defect, Error)\n      strictEqual(cause.defect.message, \"test\")\n    }))\n\n  it.effect(\"catches defects in both fn & pipeline\", () =>\n    Effect.gen(function*() {\n      const fn = Effect.fn(\"test\")(\n        (): Effect.Effect<void> => {\n          throw new Error(\"test\")\n        },\n        (_): Effect.Effect<void> => {\n          throw new Error(\"test2\")\n        }\n      )\n      const cause = yield* fn().pipe(\n        Effect.sandbox,\n        Effect.flip\n      )\n      assertTrue(Cause.isSequentialType(cause))\n      assertTrue(Cause.isDieType(cause.left))\n      assertTrue(Cause.isDieType(cause.right))\n      assertInstanceOf(cause.left.defect, Error)\n      strictEqual(cause.left.defect.message, \"test\")\n      assertInstanceOf(cause.right.defect, Error)\n      strictEqual(cause.right.defect.message, \"test2\")\n    }))\n\n  it(\"should preserve the function length\", () => {\n    const f = function*(n: number) {\n      return n\n    }\n    const fn1 = Effect.fn(\"fn1\")(f)\n    strictEqual(fn1.length, 1)\n    strictEqual(Effect.runSync(fn1(2)), 2)\n    const fn2 = Effect.fn(f)\n    strictEqual(fn2.length, 1)\n    strictEqual(Effect.runSync(fn2(2)), 2)\n  })\n})\n\ndescribe(\"Effect.fnUntraced\", () => {\n  it(\"should preserve the function length\", () => {\n    const f = function*(n: number) {\n      return n\n    }\n    const fn1 = Effect.fnUntraced(f)\n    strictEqual(fn1.length, 1)\n    strictEqual(Effect.runSync(fn1(2)), 2)\n    const fn2 = Effect.fnUntraced(f, (x) => x)\n    strictEqual(fn2.length, 1)\n    strictEqual(Effect.runSync(fn2(2)), 2)\n  })\n\n  it.effect(\"can access args in single pipe\", () =>\n    Effect.gen(function*() {\n      const fn = Effect.fnUntraced(\n        function*(n: number) {\n          return n\n        },\n        (effect, n) => Effect.map(effect, (a) => a + n),\n        (effect, n) => Effect.map(effect, (a) => a + n)\n      )\n      const n = yield* fn(1)\n      assertEquals(n, 3)\n    }))\n\n  it.effect(\"can return non-effects\", () =>\n    Effect.gen(function*() {\n      const fn = Effect.fnUntraced(\n        function*(n: number) {\n          return n\n        },\n        (effect, n) => Effect.map(effect, (a) => a + n),\n        Stream.fromEffect\n      )\n      const n = yield* Stream.runCollect(fn(1))\n      deepStrictEqual(Chunk.toReadonlyArray(n), [2])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/foreign.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Cause, Context, Effect, Either, Exit, Option, pipe } from \"effect\"\nimport { nextInt } from \"effect/Random\"\nimport { unify } from \"effect/Unify\"\n\ndescribe(\"Foreign\", () => {\n  it.effect(\"Unify\", () =>\n    Effect.gen(function*() {\n      const unifiedEffect = unify((yield* nextInt) > 1 ? Effect.succeed(0) : Effect.fail(1))\n      const unifiedExit = unify((yield* nextInt) > 1 ? Exit.succeed(0) : Exit.fail(1))\n      const unifiedEither = unify((yield* nextInt) > 1 ? Either.right(0) : Either.left(1))\n      const unifiedOption = unify((yield* nextInt) > 1 ? Option.some(0) : Option.none())\n      deepStrictEqual(yield* unifiedEffect, 0)\n      deepStrictEqual(yield* unifiedExit, 0)\n      deepStrictEqual(yield* unifiedEither, 0)\n      deepStrictEqual(yield* unifiedOption, 0)\n    }))\n  it.effect(\"Tag\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<number>(\"number\")\n      const result = yield* pipe(tag, Effect.provideService(tag, 10))\n      deepStrictEqual(result, 10)\n    }))\n  it.effect(\"Either\", () =>\n    Effect.gen(function*() {\n      const a = yield* (Either.right(10))\n      const b = yield* (Effect.either(Either.left(10)))\n      const c = yield* pipe(\n        Either.right(2),\n        Effect.flatMap(\n          (n) => Effect.succeed(n + 1)\n        )\n      )\n      deepStrictEqual(a, 10)\n      assertLeft(b, 10)\n      deepStrictEqual(c, 3)\n    }))\n  it.effect(\"Option\", () =>\n    Effect.gen(function*() {\n      const a = yield* (Option.some(10))\n      const b = yield* (Effect.either(Option.none()))\n      const c = yield* pipe(\n        Option.some(2),\n        Effect.flatMap(\n          (n) => Effect.succeed(n + 1)\n        )\n      )\n      deepStrictEqual(a, 10)\n      assertLeft(b, new Cause.NoSuchElementException())\n      deepStrictEqual(c, 3)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/forking.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"fork - propagates interruption\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.never, Effect.fork, Effect.flatMap(Fiber.interrupt))\n      assertTrue(Exit.isInterrupted(result))\n    }))\n  it.effect(\"fork - propagates interruption with zip of defect\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Deferred.succeed(latch, void 0),\n        Effect.zipRight(Effect.die(new Error())),\n        Effect.zip(Effect.never, { concurrent: true }),\n        Effect.fork\n      )\n\n      yield* (Deferred.await(latch))\n      const result = yield* pipe(Fiber.interrupt(fiber), Effect.map(Exit.mapErrorCause((cause) => cause)))\n      assertTrue(Exit.isInterrupted(result))\n    }))\n  it.effect(\"fork - interruption status is heritable\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<void>())\n      const ref = yield* (Ref.make(true))\n      yield* pipe(\n        Effect.checkInterruptible((isInterruptible) =>\n          pipe(Ref.set(ref, isInterruptible), Effect.zipRight(Deferred.succeed(latch, void 0)))\n        ),\n        Effect.fork,\n        Effect.zipRight(Deferred.await(latch)),\n        Effect.uninterruptible\n      )\n\n      const result = yield* (Ref.get(ref))\n      assertFalse(result)\n    }))\n  it.effect(\"forkWithErrorHandler - calls provided function when task fails\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<void>())\n      yield* pipe(\n        Effect.fail<void>(void 0),\n        Effect.forkWithErrorHandler((e) => pipe(Deferred.succeed(deferred, e), Effect.asVoid))\n      )\n      const result = yield* (Deferred.await(deferred))\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"forkAll - returns the list of results in the same order\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([1, 2, 3].map(Effect.succeed), Effect.forkAll(), Effect.flatMap(Fiber.join))\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n  it.effect(\"forkAll - happy-path\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Array.from({ length: 1000 }, (_, i) => i + 1).map(Effect.succeed),\n        Effect.forkAll(),\n        Effect.flatMap(Fiber.join)\n      )\n      deepStrictEqual(\n        Array.from(result),\n        Array.from({ length: 1000 }, (_, i) => i + 1)\n      )\n    }))\n  it.effect(\"forkAll - empty input\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe([] as ReadonlyArray<Effect.Effect<number>>, Effect.forkAll(), Effect.flatMap(Fiber.join))\n      )\n      strictEqual(result.length, 0)\n    }))\n  it.effect(\"forkAll - propagate failures\", () =>\n    Effect.gen(function*() {\n      const boom = new Error()\n      const fail = Effect.fail(boom)\n      const result = yield* pipe([fail], Effect.forkAll(), Effect.flatMap((fiber) => Effect.flip(Fiber.join(fiber))))\n      strictEqual(result, boom)\n    }))\n  it.effect(\"forkAll - propagates defects\", () =>\n    Effect.gen(function*() {\n      const boom = new Error(\"boom\")\n      const die = Effect.die(boom)\n      const joinDefect = (fiber: Fiber.Fiber<unknown>) => {\n        return pipe(fiber, Fiber.join, Effect.sandbox, Effect.flip)\n      }\n      const fiber1 = yield* (Effect.forkAll([die]))\n      const fiber2 = yield* (Effect.forkAll([die, Effect.succeed(42)]))\n      const fiber3 = yield* (Effect.forkAll([die, Effect.succeed(42), Effect.never]))\n      const result1 = yield* pipe(joinDefect(fiber1), Effect.map((cause) => cause))\n      const result2 = yield* pipe(joinDefect(fiber2), Effect.map((cause) => cause))\n      const result3 = yield* pipe(joinDefect(fiber3), Effect.map((cause) => cause))\n      deepStrictEqual(Cause.dieOption(result1), Option.some(boom))\n      deepStrictEqual(Cause.dieOption(result2), Option.some(boom))\n      deepStrictEqual(Cause.dieOption(result3), Option.some(boom))\n      assertTrue(Cause.isInterrupted(result3))\n    }))\n  it.effect(\"forkAll - infers correctly\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const worker = Effect.never\n      const workers = Array.from({ length: 4 }, () => worker)\n      const fiber = yield* (Effect.forkAll(workers))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 0)\n    }))\n  it.effect(\"forkAll - infers correctly with error type\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const worker = Effect.forever(Effect.fail(new Cause.RuntimeException(\"fail\")))\n      const workers = Array.from({ length: 4 }, () => worker)\n      const fiber = yield* (Effect.forkAll(workers))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 0)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/interruption.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertSome, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberId from \"effect/FiberId\"\nimport { constVoid, pipe } from \"effect/Function\"\nimport * as HashSet from \"effect/HashSet\"\nimport * as MutableRef from \"effect/MutableRef\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as TestClock from \"effect/TestClock\"\nimport { withLatch, withLatchAwait } from \"../utils/latch.js\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"sync forever is interruptible\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(Effect.succeed(1), Effect.forever, Effect.fork)\n      const result = yield* (Fiber.interrupt(fiber))\n      assertTrue(Exit.isFailure(result) && Cause.isInterruptedOnly(result.effect_instruction_i0))\n    }))\n  it.effect(\"interrupt of never is interrupted with cause\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(Effect.never, Effect.fork)\n      const result = yield* (Fiber.interrupt(fiber))\n      assertTrue(Exit.isFailure(result) && Cause.isInterruptedOnly(result.effect_instruction_i0))\n    }))\n  it.effect(\"asyncEffect is interruptible\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* (\n        pipe(Effect.asyncEffect<never, never, never, never, never, never>(() => Effect.never), Effect.fork)\n      )\n      const result = yield* (Fiber.interrupt(fiber))\n      assertTrue(Exit.isFailure(result) && Cause.isInterruptedOnly(result.effect_instruction_i0))\n    }))\n  it.effect(\"async is interruptible\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(Effect.async<void, never, never>(constVoid), Effect.fork)\n      const result = yield* (Fiber.interrupt(fiber))\n      assertTrue(Exit.isFailure(result) && Cause.isInterruptedOnly(result.effect_instruction_i0))\n    }))\n  it.effect(\"acquireUseRelease - acquire is uninterruptible\", () =>\n    Effect.gen(function*() {\n      const awaiter = Deferred.unsafeMake<void>(FiberId.none)\n      const program = Effect.gen(function*() {\n        const deferred = yield* (Deferred.make<void>())\n        const fiber = yield* (\n          pipe(\n            Effect.acquireUseRelease(\n              pipe(Deferred.succeed(deferred, void 0), Effect.zipLeft(Deferred.await(awaiter))),\n              () => Effect.void,\n              () => Effect.void\n            ),\n            Effect.forkDaemon\n          )\n        )\n        return yield* (\n          pipe(\n            Deferred.await(deferred),\n            Effect.zipRight(pipe(\n              Fiber.interrupt(fiber),\n              Effect.timeoutTo({\n                onTimeout: () => 42,\n                onSuccess: () => 0,\n                duration: Duration.millis(500)\n              })\n            )),\n            Effect.zipLeft(TestClock.adjust(Duration.seconds(1)), { concurrent: true })\n          )\n        )\n      })\n      const result = yield* program\n      yield* (Deferred.succeed(awaiter, void 0))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"acquireUseRelease - use is interruptible\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* (\n        Effect.fork(\n          Effect.acquireUseRelease(\n            Effect.void,\n            () => Effect.never,\n            () => Effect.void\n          )\n        )\n      )\n      const result = yield* (Fiber.interrupt(fiber))\n      assertTrue(Exit.isInterrupted(result))\n    }))\n  it.effect(\"acquireUseRelease - release is called on interrupt\", () =>\n    Effect.gen(function*() {\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const fiber = yield* Effect.fork(\n        Effect.acquireUseRelease(\n          Effect.void,\n          () => pipe(Deferred.succeed(deferred1, void 0), Effect.zipRight(Effect.never)),\n          () => pipe(Deferred.succeed(deferred2, void 0), Effect.zipRight(Effect.void))\n        )\n      )\n      yield* (Deferred.await(deferred1))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* pipe(\n        Deferred.await(deferred2),\n        Effect.timeoutTo({\n          onTimeout: () => 42,\n          onSuccess: () => 0,\n          duration: Duration.seconds(1)\n        })\n      )\n      strictEqual(result, 0)\n    }))\n  it.effect(\"acquireUseRelease acquire returns immediately on interrupt\", () =>\n    Effect.gen(function*() {\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<number, never>())\n      const deferred3 = yield* (Deferred.make<void>())\n      const fiber = yield* (\n        pipe(\n          Effect.acquireUseRelease(\n            pipe(Deferred.succeed(deferred1, void 0), Effect.zipRight(Deferred.await(deferred2))),\n            () => Effect.void,\n            () => Deferred.await(deferred3)\n          ),\n          Effect.disconnect,\n          Effect.fork\n        )\n      )\n      yield* (Deferred.await(deferred1))\n      const result = yield* (Fiber.interrupt(fiber))\n      yield* (Deferred.succeed(deferred3, void 0))\n      assertTrue(Exit.isInterrupted(result))\n    }))\n  it.effect(\"acquireUseRelease disconnect use is interruptible\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(\n        Effect.acquireUseRelease(\n          Effect.void,\n          () => Effect.never,\n          () => Effect.void\n        ),\n        Effect.disconnect,\n        Effect.fork\n      )\n      const result = yield* (Fiber.interrupt(fiber))\n      assertTrue(Exit.isInterrupted(result))\n    }))\n  it.effect(\"acquireUseRelease disconnect release called on interrupt in separate fiber\", () =>\n    Effect.gen(function*() {\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const fiber = yield* (\n        pipe(\n          Effect.acquireUseRelease(\n            Effect.void,\n            () => pipe(Deferred.succeed(deferred1, void 0), Effect.zipRight(Effect.never)),\n            () => pipe(Deferred.succeed(deferred2, void 0), Effect.zipRight(Effect.void))\n          ),\n          Effect.disconnect,\n          Effect.fork\n        )\n      )\n      yield* (Deferred.await(deferred1))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (\n        pipe(\n          Deferred.await(deferred2),\n          Effect.timeoutTo({\n            onTimeout: () => false,\n            onSuccess: () => true,\n            duration: Duration.seconds(10)\n          })\n        )\n      )\n      assertTrue(result)\n    }))\n  it.effect(\"catchAll + ensuring + interrupt\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<void>())\n      const deferred = yield* (Deferred.make<boolean>())\n      const fiber = yield* (\n        pipe(\n          Deferred.succeed(latch, void 0),\n          Effect.zipRight(Effect.never),\n          Effect.catchAll(Effect.fail),\n          Effect.ensuring(Deferred.succeed(deferred, true)),\n          Effect.fork\n        )\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Deferred.await(deferred))\n      assertTrue(result)\n    }))\n  it.effect(\"finalizer can detect interruption\", () =>\n    Effect.gen(function*() {\n      const deferred1 = yield* (Deferred.make<boolean>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const fiber = yield* (\n        pipe(\n          Deferred.succeed(deferred2, void 0),\n          Effect.zipRight(Effect.never),\n          Effect.ensuring(\n            pipe(\n              Effect.descriptor,\n              Effect.flatMap((descriptor) => Deferred.succeed(deferred1, HashSet.size(descriptor.interruptors) > 0))\n            )\n          ),\n          Effect.fork\n        )\n      )\n      yield* (Deferred.await(deferred2))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Deferred.await(deferred1))\n      assertTrue(result)\n    }))\n  it.effect(\"interrupted cause persists after catching\", () =>\n    Effect.gen(function*() {\n      const process = (list: Chunk.Chunk<Exit.Exit<any>>): Chunk.Chunk<Exit.Exit<any>> => {\n        return pipe(list, Chunk.map(Exit.mapErrorCause((cause) => cause)))\n      }\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const exits = yield* (Ref.make(Chunk.empty<Exit.Exit<any>>()))\n      const fiber = yield* pipe(\n        Effect.uninterruptibleMask((restore) =>\n          pipe(\n            restore(pipe(\n              Effect.uninterruptibleMask((restore) =>\n                pipe(\n                  restore(pipe(Deferred.succeed(latch1, void 0), Effect.zipRight(Deferred.await(latch2)))),\n                  Effect.onExit((exit) => Ref.update(exits, Chunk.prepend(exit)))\n                )\n              ),\n              Effect.asVoid\n            )),\n            Effect.exit,\n            Effect.flatMap((exit) => Ref.update(exits, Chunk.prepend(exit)))\n          )\n        ),\n        Effect.fork\n      )\n      yield* pipe(Deferred.await(latch1), Effect.zipRight(Fiber.interrupt(fiber)))\n      const result = yield* pipe(Ref.get(exits), Effect.map(process))\n      strictEqual(Chunk.size(result), 2)\n      assertTrue(pipe(\n        result,\n        Array.reduce(true, (acc, curr) =>\n          acc && Exit.isFailure(curr) && Cause.isInterruptedOnly(curr.effect_instruction_i0))\n      ))\n    }))\n  it.effect(\"interruption of raced\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<number>(0))\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const make = (deferred: Deferred.Deferred<void, never>) => {\n        return pipe(\n          Deferred.succeed(deferred, void 0),\n          Effect.zipRight(Effect.never),\n          Effect.onInterrupt(() => Ref.update(ref, (n) => n + 1))\n        )\n      }\n      const raced = yield* pipe(make(latch1), Effect.race(make(latch2)), Effect.fork)\n      yield* pipe(Deferred.await(latch1), Effect.zipRight(Deferred.await(latch2)))\n      yield* (Fiber.interrupt(raced))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 2)\n    }))\n  it.effect(\"recovery of error in finalizer\", () =>\n    Effect.gen(function*() {\n      const recovered = yield* (Ref.make(false))\n      const fiber = yield* (withLatch((release) =>\n        pipe(\n          release,\n          Effect.zipRight(Effect.never),\n          Effect.ensuring(pipe(\n            Effect.void,\n            Effect.zipRight(Effect.fail(\"uh oh\")),\n            Effect.catchAll(() => Ref.set(recovered, true))\n          )),\n          Effect.fork\n        )\n      ))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(recovered))\n      assertTrue(result)\n    }))\n  it.effect(\"recovery of interruptible\", () =>\n    Effect.gen(function*() {\n      const recovered = yield* (Ref.make(false))\n      const fiber = yield* (withLatch((release) =>\n        pipe(\n          release,\n          Effect.zipRight(pipe(Effect.never, Effect.interruptible)),\n          Effect.matchCauseEffect({\n            onFailure: (cause) => Ref.set(recovered, Cause.isInterrupted(cause)),\n            onSuccess: () => Ref.set(recovered, false)\n          }),\n          Effect.uninterruptible,\n          Effect.fork\n        )\n      ))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(recovered))\n      assertTrue(result)\n    }))\n  it.effect(\"sandbox of interruptible\", () =>\n    Effect.gen(function*() {\n      const recovered = yield* (Ref.make<Option.Option<Either.Either<never, boolean>>>(Option.none()))\n      const fiber = yield* (withLatch((release) =>\n        pipe(\n          release,\n          Effect.zipRight(pipe(Effect.never, Effect.interruptible)),\n          Effect.sandbox,\n          Effect.either,\n          Effect.flatMap((either) =>\n            Ref.set(recovered, Option.some(pipe(either, Either.mapLeft(Cause.isInterrupted))))\n          ),\n          Effect.uninterruptible,\n          Effect.fork\n        )\n      ))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(recovered))\n      assertSome(result, Either.left(true))\n    }))\n  it.effect(\"run of interruptible\", () =>\n    Effect.gen(function*() {\n      const recovered = yield* (Ref.make<Option.Option<boolean>>(Option.none()))\n      const fiber = yield* (withLatch((release) =>\n        pipe(\n          release,\n          Effect.zipRight(pipe(Effect.never, Effect.interruptible)),\n          Effect.exit,\n          Effect.flatMap((exit) => Ref.set(recovered, Option.some(Exit.isInterrupted(exit)))),\n          Effect.uninterruptible,\n          Effect.fork\n        )\n      ))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(recovered))\n      assertSome(result, true)\n    }))\n  it.effect(\"alternating interruptibility\", () =>\n    Effect.gen(function*() {\n      const counter = yield* (Ref.make(0))\n      const fiber = yield* (withLatch((release) =>\n        pipe(\n          release,\n          Effect.zipRight(pipe(Effect.never, Effect.interruptible, Effect.exit)),\n          Effect.zipRight(Ref.update(counter, (n) => n + 1)),\n          Effect.uninterruptible,\n          Effect.interruptible,\n          Effect.exit,\n          Effect.zipRight(Ref.update(counter, (n) => n + 1)),\n          Effect.uninterruptible,\n          Effect.fork\n        )\n      ))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(counter))\n      strictEqual(result, 2)\n    }))\n  it.effect(\"interruption after defect\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const fiber = yield* (withLatch((release) =>\n        pipe(\n          Effect.try(() => {\n            throw new Error()\n          }),\n          Effect.exit,\n          Effect.zipRight(release),\n          Effect.zipRight(Effect.never),\n          Effect.ensuring(Ref.set(ref, true)),\n          Effect.fork\n        )\n      ))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n  it.effect(\"interruption after defect 2\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const fiber = yield* (withLatch((release) =>\n        pipe(\n          Effect.try(() => {\n            throw new Error()\n          }),\n          Effect.exit,\n          Effect.zipRight(release),\n          Effect.zipRight(pipe(Effect.void, Effect.forever)),\n          Effect.ensuring(Ref.set(ref, true)),\n          Effect.fork\n        )\n      ))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n  it.effect(\"disconnect returns immediately on interrupt\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<void>())\n      const fiber = yield* (\n        pipe(\n          Deferred.succeed(deferred, void 0),\n          Effect.zipRight(Effect.never),\n          Effect.ensuring(Effect.never),\n          Effect.disconnect,\n          Effect.fork\n        )\n      )\n      yield* (Deferred.await(deferred))\n      const result = yield* (Fiber.interrupt(fiber))\n      assertTrue(Exit.isInterrupted(result))\n    }))\n  it.live(\"disconnected effect that is then interrupted eventually performs interruption\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const fiber = yield* (\n        pipe(\n          Deferred.succeed(deferred1, void 0),\n          Effect.zipRight(Effect.never),\n          Effect.ensuring(\n            pipe(\n              Ref.set(ref, true),\n              Effect.zipRight(Effect.sleep(Duration.millis(10))),\n              Effect.zipRight(Deferred.succeed(deferred2, void 0))\n            )\n          ),\n          Effect.disconnect,\n          Effect.fork\n        )\n      )\n      yield* (Deferred.await(deferred1))\n      yield* (Fiber.interrupt(fiber))\n      yield* (Deferred.await(deferred2))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n  it.effect(\"cause reflects interruption\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        withLatch((release) => pipe(release, Effect.zipRight(Effect.fail(\"foo\")), Effect.fork)),\n        Effect.flatMap(Fiber.interrupt)\n      )\n      deepStrictEqual(result, Exit.fail(\"foo\"))\n    }))\n  it.live(\"acquireRelease use inherits interrupt status\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const fiber = yield* (withLatchAwait((release2, await2) =>\n        pipe(\n          withLatch((release1) =>\n            pipe(\n              Effect.acquireUseRelease(\n                release1,\n                () =>\n                  pipe(\n                    await2,\n                    Effect.zipRight(Effect.sleep(Duration.millis(10))),\n                    Effect.zipRight(Ref.set(ref, true))\n                  ),\n                () => Effect.void\n              ),\n              Effect.uninterruptible,\n              Effect.fork\n            )\n          ),\n          Effect.zipLeft(release2)\n        )\n      ))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n  it.live(\"acquireRelease use inherits interrupt status 2\", () =>\n    Effect.gen(function*() {\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const ref = yield* (Ref.make(false))\n      const fiber = yield* pipe(\n        Effect.acquireUseRelease(\n          Deferred.succeed(latch1, void 0),\n          () =>\n            pipe(\n              Deferred.await(latch2),\n              Effect.zipRight(Effect.sleep(Duration.millis(10))),\n              Effect.zipRight(Ref.set(ref, true)),\n              Effect.asVoid\n            ),\n          () => Effect.void\n        ),\n        Effect.uninterruptible,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch1))\n      yield* (Deferred.succeed(latch2, void 0))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n  it.live(\"async can be uninterruptible\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const fiber = yield* (withLatch((release) =>\n        pipe(\n          release,\n          Effect.zipRight(Effect.sleep(Duration.millis(10))),\n          Effect.zipRight(pipe(Ref.set(ref, true), Effect.asVoid)),\n          Effect.uninterruptible,\n          Effect.fork\n        )\n      ))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n  it.live(\"closing scope is uninterruptible\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const deferred = yield* (Deferred.make<void>())\n      const child = pipe(\n        Deferred.succeed(deferred, void 0),\n        Effect.zipRight(Effect.sleep(Duration.millis(10))),\n        Effect.zipRight(Ref.set(ref, true))\n      )\n      const parent = pipe(child, Effect.uninterruptible, Effect.fork, Effect.zipRight(Deferred.await(deferred)))\n      const fiber = yield* (Effect.fork(parent))\n      yield* (Deferred.await(deferred))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n  it.effect(\"async cancelation\", () =>\n    Effect.gen(function*() {\n      const ref = MutableRef.make(0)\n      const effect = Effect.async(() => {\n        pipe(ref, MutableRef.set(MutableRef.get(ref) + 1))\n        return Effect.sync(() => {\n          pipe(ref, MutableRef.set(MutableRef.get(ref) - 1))\n        })\n      })\n      yield* pipe(Effect.void, Effect.race(effect))\n      const result = MutableRef.get(ref)\n      strictEqual(result, 0)\n    }))\n  it.effect(\"interruption status is inheritable\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<void>())\n      const ref = yield* (Ref.make(true))\n      yield* pipe(\n        Effect.checkInterruptible((isInterruptible) =>\n          pipe(Ref.set(ref, isInterruptible), Effect.zipRight(Deferred.succeed(latch, void 0)))\n        ),\n        Effect.fork,\n        Effect.zipRight(Deferred.await(latch)),\n        Effect.uninterruptible\n      )\n      const result = yield* (Ref.get(ref))\n      assertFalse(result)\n    }))\n  it.effect(\"running an effect preserves interruption status\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<void>())\n      const fiber = yield* (\n        pipe(Deferred.succeed(deferred, void 0), Effect.zipRight(Effect.never), Effect.fork)\n      )\n      yield* (Deferred.await(deferred))\n      const result = yield* (Fiber.interrupt(fiber))\n      assertTrue(\n        Exit.isFailure(result) && Exit.isInterrupted(result) && Cause.isInterruptedOnly(result.effect_instruction_i0)\n      )\n    }))\n  it.effect(\"running an effect swallows inner interruption\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<number>())\n      yield* pipe(Effect.interrupt, Effect.exit, Effect.zipRight(Deferred.succeed(deferred, 42)))\n      const result = yield* (Deferred.await(deferred))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"AbortSignal is aborted\", () =>\n    Effect.gen(function*() {\n      let signal: AbortSignal\n      const fiber = yield* pipe(\n        Effect.async<void, never, never>((_cb, signal_) => {\n          signal = signal_\n        }),\n        Effect.fork\n      )\n      yield* (Effect.yieldNow())\n      yield* (Fiber.interrupt(fiber))\n      strictEqual(signal!.aborted, true)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/join-order.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"zip/all joins fibers in the correct order\", () =>\n    Effect.gen(function*() {\n      const ref = yield* FiberRef.make(5)\n      const fiber = yield* Effect.fork(Effect.zip(\n        FiberRef.set(ref, 10).pipe(Effect.delay(\"2 seconds\")),\n        FiberRef.set(ref, 15),\n        { concurrent: true }\n      ))\n      yield* TestClock.adjust(\"3 seconds\")\n      yield* Fiber.join(fiber)\n      strictEqual(yield* FiberRef.get(ref), 10)\n    }).pipe(Effect.scoped))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/latch.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Effect, Exit } from \"effect\"\n\ndescribe(\"Latch\", () => {\n  it.effect(\"open works\", () =>\n    Effect.gen(function*() {\n      const latch = yield* Effect.makeLatch()\n      let fiber = yield* latch.await.pipe(\n        Effect.fork\n      )\n      yield* Effect.yieldNow()\n      strictEqual(fiber.unsafePoll(), null)\n      yield* latch.open\n      deepStrictEqual(yield* fiber.await, Exit.void)\n\n      fiber = yield* latch.await.pipe(\n        Effect.fork\n      )\n      yield* Effect.yieldNow()\n      deepStrictEqual(fiber.unsafePoll(), Exit.void)\n\n      yield* latch.close\n      fiber = yield* Effect.void.pipe(\n        latch.whenOpen,\n        Effect.fork\n      )\n      yield* Effect.yieldNow()\n      strictEqual(fiber.unsafePoll(), null)\n\n      yield* latch.release\n      deepStrictEqual(yield* fiber.await, Exit.void)\n    }))\n\n  it.effect(\"subtype of Effect\", () =>\n    Effect.gen(function*() {\n      const latch = yield* Effect.makeLatch()\n      const fiber = yield* Effect.fork(latch)\n\n      yield* latch.open\n\n      deepStrictEqual(yield* fiber.await, Exit.void)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/lifting.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"liftPredicate\", () => {\n    const isPositivePredicate = (n: number) => n > 0\n    const onPositivePredicateError = (n: number) => `${n} is not positive`\n    const isNumberRefinement = (n: string | number): n is number => typeof n === \"number\"\n    const onNumberRefinementError = (n: string | number) => `${n} is not a number`\n\n    return Effect.gen(function*() {\n      strictEqual(\n        yield* pipe(1, Effect.liftPredicate(isPositivePredicate, onPositivePredicateError)),\n        1\n      )\n      strictEqual(\n        yield* pipe(-1, Effect.liftPredicate(isPositivePredicate, onPositivePredicateError), Effect.flip),\n        `-1 is not positive`\n      )\n      strictEqual(\n        yield* pipe(1, Effect.liftPredicate(isNumberRefinement, onNumberRefinementError)),\n        1\n      )\n      strictEqual(\n        yield* pipe(\"string\", Effect.liftPredicate(isNumberRefinement, onNumberRefinementError), Effect.flip),\n        `string is not a number`\n      )\n      strictEqual(\n        yield* Effect.liftPredicate(1, isPositivePredicate, onPositivePredicateError),\n        1\n      )\n      strictEqual(\n        yield* Effect.liftPredicate(-1, isPositivePredicate, onPositivePredicateError).pipe(Effect.flip),\n        `-1 is not positive`\n      )\n      strictEqual(\n        yield* Effect.liftPredicate(1, isNumberRefinement, onNumberRefinementError),\n        1\n      )\n      strictEqual(\n        yield* Effect.liftPredicate(\"string\", isNumberRefinement, onNumberRefinementError).pipe(Effect.flip),\n        `string is not a number`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/mapping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\n\nconst ExampleError = new Error(\"Oh noes!\")\n\nconst parseInt = (s: string): number => {\n  const n = Number.parseInt(s)\n  if (Number.isNaN(n)) {\n    throw new Cause.IllegalArgumentException()\n  }\n  return n\n}\n\nconst fib = (n: number): number => {\n  if (n <= 1) {\n    return n\n  }\n  return fib(n - 1) + fib(n - 2)\n}\n\ndescribe(\"Effect\", () => {\n  it.effect(\"flip must make error into value\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.flip(Effect.fail(ExampleError)))\n      deepStrictEqual(result, ExampleError)\n    }))\n  it.effect(\"flip must make value into error\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.either(Effect.flip(Effect.succeed(42))))\n      assertLeft(result, 42)\n    }))\n  it.effect(\"flipping twice returns the identical value\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.flip(Effect.flip(Effect.succeed(42))))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"mapBoth - maps over both error and value channels\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.fail(10),\n        Effect.mapBoth({\n          onFailure: (n) => n.toString(),\n          onSuccess: identity\n        }),\n        Effect.either\n      )\n      assertLeft(result, \"10\")\n    }))\n  it.effect(\"mapAccum\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        Effect.mapAccum([\"a\", \"b\"], \"\", (prev, cur, i) => Effect.succeed([prev + cur + i, cur]))\n      )\n      deepStrictEqual(result, [\"a0b1\", [\"a\", \"b\"]])\n    }))\n  it.effect(\"tryMap - returns an effect whose success is mapped by the specified side effecting function\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.succeed(\"123\"), Effect.tryMap({ try: parseInt, catch: identity }))\n      strictEqual(result, 123)\n    }))\n  it.effect(\"tryMap - translates any thrown exceptions into typed failed effects\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.succeed(\"hello\"),\n        Effect.tryMap({ try: parseInt, catch: identity }),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(new Cause.IllegalArgumentException()))\n    }))\n  it.effect(\"negate - on true returns false\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.negate(Effect.succeed(true)))\n      assertFalse(result)\n    }))\n  it.effect(\"negate - on false returns true\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.negate(Effect.succeed(false)))\n      assertTrue(result)\n    }))\n  it.effect(\"summarized - returns summary and value\", () =>\n    Effect.gen(function*() {\n      const counter = yield* (Ref.make(0))\n      const increment = Ref.updateAndGet(counter, (n) => n + 1)\n      const [[start, end], value] = yield* (\n        pipe(increment, Effect.summarized(increment, (start, end) => [start, end] as const))\n      )\n      strictEqual(start, 1)\n      strictEqual(value, 2)\n      strictEqual(end, 3)\n    }))\n  it.effect(\"point, bind, map\", () =>\n    Effect.gen(function*() {\n      const fibEffect = (n: number): Effect.Effect<number> => {\n        if (n <= 1) {\n          return Effect.succeed(n)\n        }\n        return pipe(fibEffect(n - 1), Effect.zipWith(fibEffect(n - 2), (a, b) => a + b))\n      }\n      const result = yield* (fibEffect(10))\n      strictEqual(result, fib(10))\n    }))\n  it.effect(\"effect, bind, map\", () =>\n    Effect.gen(function*() {\n      const fibEffect = (n: number): Effect.Effect<number, unknown> => {\n        if (n <= 1) {\n          return Effect.try(() => n)\n        }\n        return pipe(fibEffect(n - 1), Effect.zipWith(fibEffect(n - 2), (a, b) => a + b))\n      }\n      const result = yield* (fibEffect(10))\n      strictEqual(result, fib(10))\n    }))\n  it.effect(\"effect, bind, map, redeem\", () =>\n    Effect.gen(function*() {\n      const fibEffect = (n: number): Effect.Effect<number, unknown> => {\n        if (n <= 1) {\n          return pipe(\n            Effect.try(() => {\n              throw ExampleError\n            }),\n            Effect.catchAll(() => Effect.try(() => n))\n          )\n        }\n        return pipe(fibEffect(n - 1), Effect.zipWith(fibEffect(n - 2), (a, b) => a + b))\n      }\n      const result = yield* (fibEffect(10))\n      strictEqual(result, fib(10))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/memoization.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { notStrictEqual } from \"assert\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Random from \"effect/Random\"\nimport * as Ref from \"effect/Ref\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"non-memoized returns new instances on repeated calls\", () =>\n    it.flakyTest(Effect.gen(function*() {\n      const random = Random.nextInt\n      const [first, second] = yield* pipe(random, Effect.zip(random))\n      notStrictEqual(first, second)\n    })))\n  it.effect(\"memoized returns the same instance on repeated calls\", () =>\n    it.flakyTest(Effect.gen(function*() {\n      const memo = Effect.cached(Random.nextInt)\n      const [first, second] = yield* pipe(memo, Effect.flatMap((effect) => pipe(effect, Effect.zip(effect))))\n      strictEqual(first, second)\n    })))\n  it.effect(\"memoized function returns the same instance on repeated calls\", () =>\n    it.flakyTest(Effect.gen(function*() {\n      const randomNumber = (n: number) => Random.nextIntBetween(n, n + n + 1)\n      const memoized = yield* (Effect.cachedFunction(randomNumber))\n      const a = yield* (memoized(10))\n      const b = yield* (memoized(10))\n      const c = yield* (memoized(11))\n      const d = yield* (memoized(11))\n      strictEqual(a, b)\n      notStrictEqual(b, c)\n      strictEqual(c, d)\n    })))\n  it.effect(\"once returns an effect that will only be executed once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const effect: Effect.Effect<void> = yield* pipe(Ref.update(ref, (n) => n + 1), Effect.once)\n      yield* (\n        Effect.all(Effect.replicate(effect, 100), {\n          concurrency: \"unbounded\",\n          discard: true\n        })\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/optional-wrapping-unwrapping.test.ts",
    "content": "import { assert, describe, it } from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\n\ndescribe(\"Effect\", () => {\n  describe(\"transposeOption\", () => {\n    it.effect(\"None\", () =>\n      Effect.gen(function*() {\n        const result = yield* Effect.transposeOption(Option.none())\n        assert.ok(Option.isNone(result))\n      }))\n\n    it.effect(\"Some\", () =>\n      Effect.gen(function*() {\n        const result = yield* Effect.transposeOption(Option.some(Effect.succeed(42)))\n        assert.deepStrictEqual(result, Option.some(42))\n      }))\n  })\n  describe(\"transposeMapOption\", () => {\n    describe(\"None\", () => {\n      it.effect(\"Success\", () =>\n        Effect.gen(function*() {\n          const resultDataFirst = yield* Effect.transposeMapOption(Option.none(), () => Effect.succeed(42))\n          assert.ok(Option.isNone(resultDataFirst))\n\n          const resultDataLast = yield* pipe(\n            Option.none(),\n            Effect.transposeMapOption(() => Effect.succeed(42))\n          )\n          assert.ok(Option.isNone(resultDataLast))\n        }))\n      it.effect(\"Failure\", () =>\n        Effect.gen(function*() {\n          const resultDataFirst = yield* Effect.transposeMapOption(Option.none(), () => Effect.fail(\"Error\"))\n          assert.ok(Option.isNone(resultDataFirst))\n\n          const resultDataLast = yield* pipe(\n            Option.none(),\n            Effect.transposeMapOption(() => Effect.fail(\"Error\"))\n          )\n          assert.ok(Option.isNone(resultDataLast))\n        }))\n    })\n\n    describe(\"Some\", () => {\n      describe(\"None\", () => {\n        it.effect(\"Success\", () =>\n          Effect.gen(function*() {\n            const resultDataFirst = yield* Effect.transposeMapOption(Option.some(42), (value) =>\n              Effect.succeed(value * 2))\n            assert.deepStrictEqual(resultDataFirst, Option.some(84))\n\n            const resultDataLast = yield* pipe(\n              Option.some(42),\n              Effect.transposeMapOption((value) =>\n                Effect.succeed(value * 2)\n              )\n            )\n            assert.deepStrictEqual(resultDataLast, Option.some(84))\n          }))\n        it.effect(\"Failure\", () =>\n          Effect.gen(function*() {\n            const resultDataFirst = yield* pipe(\n              Effect.transposeMapOption(Option.some(42), () => Effect.fail(\"error\")),\n              Effect.flip\n            )\n            assert.equal(resultDataFirst, \"error\")\n\n            const resultDataLast = yield* pipe(\n              Option.some(42),\n              Effect.transposeMapOption(() => Effect.fail(\"error\")),\n              Effect.flip\n            )\n            assert.equal(resultDataLast, \"error\")\n          }))\n      })\n    })\n  })\n})\n\ndescribe(\"Either\", () => {\n  describe(\"transposeOption\", () => {\n    it.effect(\"None\", () =>\n      Effect.gen(function*() {\n        const result = yield* Either.transposeOption(Option.none())\n        assert.ok(Option.isNone(result))\n      }))\n\n    it.effect(\"Some\", () =>\n      Effect.gen(function*() {\n        const result = yield* Either.transposeOption(Option.some(Either.right(42)))\n        assert.deepStrictEqual(result, Option.some(42))\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/promise.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFailure, assertSuccess, assertTrue } from \"@effect/vitest/utils\"\nimport { Cause, Effect, Option } from \"effect\"\n\nconst succeedPromiseLike: PromiseLike<string> = {\n  // @ts-ignore\n  then(onfulfilled) {\n    if (onfulfilled) {\n      onfulfilled(\"succeed\")\n    }\n    return this\n  }\n}\n\nconst failPromiseLike: PromiseLike<string> = {\n  // @ts-ignore\n  then(_, onrejected) {\n    if (onrejected) {\n      onrejected(\"fail\")\n    }\n    return this\n  }\n}\n\ndescribe(\"Effect\", () => {\n  it(\"promise - success with AbortSignal\", async () => {\n    let aborted = false\n    const effect = Effect.promise<void>((signal) => {\n      signal.addEventListener(\"abort\", () => {\n        aborted = true\n      }, { once: true })\n      return new Promise((resolve) => {\n        setTimeout(() => {\n          resolve()\n        }, 100)\n      })\n    })\n    const program = effect.pipe(\n      Effect.timeout(\"10 millis\"),\n      Effect.option\n    )\n    const exit = await Effect.runPromiseExit(program)\n    assertSuccess(exit, Option.none())\n    assertTrue(aborted)\n  })\n\n  it(\"PromiseLike - succeed\", async () => {\n    const effect = Effect.promise<string>(() => succeedPromiseLike)\n    const program = effect.pipe(\n      Effect.timeout(\"10 millis\"),\n      Effect.option\n    )\n    const exit = await Effect.runPromiseExit(program)\n    assertSuccess(exit, Option.some(\"succeed\"))\n  })\n\n  it(\"PromiseLike - fail\", async () => {\n    const effect = Effect.promise<string>(() => failPromiseLike)\n    const program = effect.pipe(\n      Effect.timeout(\"10 millis\"),\n      Effect.option\n    )\n    const exit = await Effect.runPromiseExit(program)\n    assertFailure(exit, Cause.die(\"fail\"))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/provide-runtime.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport * as Exit from \"effect/Exit\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport { pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as RuntimeFlags from \"effect/RuntimeFlags\"\nimport * as Scope from \"effect/Scope\"\n\ninterface A {\n  readonly value: number\n}\nconst A = Context.GenericTag<A>(\"A\")\nconst LiveA = Layer.succeed(A, { value: 1 })\nconst ref = FiberRef.unsafeMake(0)\nconst LiveEnv = Layer.mergeAll(\n  LiveA,\n  RuntimeFlags.enableOpSupervision,\n  Layer.scopedDiscard(Effect.locallyScoped(ref, 2))\n)\n\ndescribe(\"Effect\", () => {\n  it.effect(\"provideSomeRuntime doesn't break env\", () => {\n    const someServiceImpl = {\n      value: 42\n    } as const\n    interface SomeService {\n      readonly _: unique symbol\n    }\n    const SomeService = Context.GenericTag<SomeService, typeof someServiceImpl>(\"SomeService\")\n    return Effect.gen(function*() {\n      const rt = yield* pipe(Layer.succeedContext(Context.empty()), Layer.toRuntime)\n      const pre = yield* Effect.context<never>()\n      yield* Effect.provide(Effect.void, rt)\n      const post = yield* Effect.context<never>()\n      assertTrue(Equal.equals(pre, post))\n    }).pipe(\n      Effect.scoped,\n      Effect.provide(Layer.succeed(SomeService, someServiceImpl))\n    )\n  })\n  it(\"provideSomeRuntime\", async () => {\n    const { runtime, scope } = await Effect.runPromise(\n      Effect.flatMap(Scope.make(), (scope) =>\n        Effect.map(\n          Scope.extend(Layer.toRuntime(LiveEnv), scope),\n          (runtime) => ({ runtime, scope })\n        ))\n    )\n\n    const all = await Effect.runPromise(Effect.all(\n      [\n        Effect.provide(\n          Effect.gen(function*() {\n            const a = yield* FiberRef.get(ref)\n            const b = yield* A\n            const c = RuntimeFlags.isEnabled(yield* Effect.getRuntimeFlags, RuntimeFlags.OpSupervision)\n            return { a, b, c }\n          }),\n          runtime\n        ),\n        Effect.gen(function*() {\n          const a = yield* FiberRef.get(ref)\n          const c = RuntimeFlags.isEnabled(yield* Effect.getRuntimeFlags, RuntimeFlags.OpSupervision)\n          return { a, c }\n        })\n      ]\n    ))\n\n    await Effect.runPromise(Scope.close(scope, Exit.void))\n\n    strictEqual(all[0].a, 2)\n    deepStrictEqual(all[0].b, { value: 1 })\n    assertTrue(all[0].c)\n    strictEqual(all[1].a, 0)\n    assertFalse(all[1].c)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/query-deadlock.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Request from \"effect/Request\"\nimport * as Resolver from \"effect/RequestResolver\"\n\nexport const userIds: ReadonlyArray<number> = [1, 1]\n\ninterface GetNameById extends Request.Request<string, string> {\n  readonly _tag: \"GetNameById\"\n  readonly id: number\n}\nconst GetNameById = Request.tagged<GetNameById>(\"GetNameById\")\n\nconst UserResolver = Resolver.makeBatched((requests: Array<GetNameById>) =>\n  Effect.forEach(requests, (request) =>\n    Request.complete(\n      request,\n      Exit.succeed(\"ok\")\n    ), { discard: true })\n)\n\nconst getUserNameById = (id: number) => Effect.request(GetNameById({ id }), UserResolver)\nconst getAllUserNames = Effect.forEach([1, 1], getUserNameById, { batching: true })\n\ndescribe(\"Effect\", () => {\n  it(\"requests are executed correctly\", () =>\n    Effect.runPromise(\n      Effect.asVoid(pipe(\n        getAllUserNames,\n        Effect.withRequestCaching(true),\n        Effect.withRequestBatching(true)\n      ))\n    ))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/query-nested.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Context from \"effect/Context\"\nimport { seconds } from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Request from \"effect/Request\"\nimport * as Resolver from \"effect/RequestResolver\"\n\ninterface Counter {\n  readonly _: unique symbol\n}\nconst Counter = Context.GenericTag<Counter, { count: number }>(\"counter\")\ninterface Requests {\n  readonly _: unique symbol\n}\nconst Requests = Context.GenericTag<Requests, { count: number }>(\"requests\")\n\ninterface Parent {\n  readonly id: number\n}\n\ninterface Child {\n  readonly id: number\n  readonly parentId: number\n}\n\ninterface ChildInfo {\n  readonly id: number\n  readonly childId: number\n  readonly name: string\n}\n\ninterface ChildExtra {\n  readonly id: number\n  readonly childId: number\n  readonly extra: string\n}\n\nexport interface GetAllParents extends Request.Request<ReadonlyArray<Parent>> {\n  readonly _tag: \"GetAllParents\"\n}\n\nexport const GetAllParents = Request.tagged<GetAllParents>(\"GetAllParents\")\n\nexport interface GetParentChildren extends Request.Request<ReadonlyArray<Child>> {\n  readonly _tag: \"GetParentChildren\"\n  readonly id: number\n}\n\nexport const GetParentChildren = Request.tagged<GetParentChildren>(\"GetParentChildren\")\n\nexport interface GetChildInfo extends Request.Request<ChildInfo> {\n  readonly _tag: \"GetChildInfo\"\n  readonly id: number\n}\n\nexport const GetChildInfo = Request.tagged<GetChildInfo>(\"GetChildInfo\")\n\nexport interface GetChildExtra extends Request.Request<ChildExtra> {\n  readonly _tag: \"GetChildExtra\"\n  readonly id: number\n}\n\nexport const GetChildExtra = Request.tagged<GetChildExtra>(\"GetChildExtra\")\n\nexport const parents = Array.range(1, 2).map<Parent>((id) => ({ id }))\n\nexport const children: ReadonlyMap<number, ReadonlyArray<Child>> = new Map(\n  Array.map(parents, (p) => [\n    p.id,\n    Array.of({ id: p.id * 10, parentId: p.id })\n  ])\n)\n\nconst counted = <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.tap(self, () => Effect.map(Counter, (c) => c.count++))\n\nconst AllResolver = Resolver.makeBatched((\n  requests: Array<GetParentChildren | GetAllParents | GetChildExtra | GetChildInfo>\n) =>\n  Effect.flatMap(Requests, (r) => {\n    r.count += requests.length\n    return counted(Effect.all([\n      Effect.forEach(\n        requests.filter((_): _ is GetParentChildren => _._tag === \"GetParentChildren\"),\n        (request) => Request.succeed(request, children.get(request.id)!)\n      ),\n      Effect.forEach(\n        requests.filter((_): _ is GetChildExtra => _._tag === \"GetChildExtra\"),\n        (request) =>\n          Request.succeed(request, {\n            id: request.id * 10,\n            childId: request.id,\n            extra: \"more stuff\"\n          })\n      ),\n      Effect.forEach(\n        requests.filter((_): _ is GetChildInfo => _._tag === \"GetChildInfo\"),\n        (request) =>\n          Request.succeed(request, {\n            id: request.id * 10,\n            childId: request.id,\n            name: \"Mike\"\n          })\n      ),\n      Effect.forEach(\n        requests.filter((_): _ is GetAllParents => _._tag === \"GetAllParents\"),\n        (request) => Request.succeed(request, parents)\n      )\n    ]))\n  })\n).pipe(\n  Resolver.batchN(15),\n  Resolver.contextFromServices(Counter, Requests)\n)\n\nexport const getAllParents = Effect.request(GetAllParents({}), AllResolver)\nexport const getChildren = (id: number) => Effect.request(GetParentChildren({ id }), AllResolver)\nexport const getChildInfo = (id: number) => Effect.request(GetChildInfo({ id }), AllResolver)\nexport const getChildExtra = (id: number) => Effect.request(GetChildExtra({ id }), AllResolver)\n\nconst EnvLive = Layer.mergeAll(\n  Layer.sync(Counter, () => ({ count: 0 })),\n  Layer.sync(Requests, () => ({ count: 0 }))\n).pipe(Layer.provideMerge(\n  Layer.mergeAll(\n    Layer.setRequestCache(Request.makeCache({\n      capacity: 100,\n      timeToLive: seconds(60)\n    })),\n    Layer.setRequestCaching(true),\n    Layer.setRequestBatching(true)\n  )\n))\n\ndescribe(\"Effect\", () => {\n  it.effect(\"nested queries are batched\", () =>\n    Effect.gen(function*() {\n      const parents = yield* getAllParents\n\n      yield* Effect.forEach(\n        parents,\n        (parent) =>\n          Effect.flatMap(\n            getChildren(parent.id),\n            (children) =>\n              Effect.forEach(\n                children,\n                (child) =>\n                  Effect.zip(\n                    getChildInfo(child.id),\n                    getChildExtra(child.id),\n                    {\n                      concurrent: true,\n                      batching: \"inherit\"\n                    }\n                  ),\n                {\n                  concurrency: \"unbounded\",\n                  batching: \"inherit\"\n                }\n              )\n          ),\n        {\n          concurrency: \"inherit\",\n          batching: \"inherit\"\n        }\n      )\n\n      const count = yield* Counter\n      const requests = yield* Requests\n\n      strictEqual(count.count, 3)\n      strictEqual(requests.count, 7)\n    }).pipe(\n      Effect.provide(EnvLive)\n    ))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/query-repro.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Request from \"effect/Request\"\nimport * as RequestResolver from \"effect/RequestResolver\"\n\nexport class FindIntraday extends Request.TaggedClass(\"FindIntraday\")<string | null, never, { symbol: string }> {}\n\nconst make = Effect.sync(function() {\n  const getIntradayResolver = RequestResolver.makeBatched((requests: Array<FindIntraday>) =>\n    Effect.all(requests.map(Request.succeed(null)))\n  )\n\n  const getIntraday = (symbol: string) =>\n    Effect.withRequestCaching(true)(\n      Effect.request(new FindIntraday({ symbol }), getIntradayResolver)\n    )\n\n  return { getIntraday }\n})\n\nclass Svc extends Effect.Tag(\"svc\")<Svc, Effect.Effect.Success<typeof make>>() {\n  static readonly Live = Layer.scoped(Svc, make)\n}\n\nconst getSub = (symbol: string) =>\n  Effect.all([\n    Effect.sleep(\"20 millis\"),\n    Svc.getIntraday(symbol)\n  ], { concurrency: 2, batching: true })\n\nconst getItems = getSub(\"test_1\")\n\ndescribe(\"interruption\", () => {\n  it.live(\"forEach interrupts residual requests\", () =>\n    Effect.gen(function*() {\n      const exit = yield* getItems.pipe(\n        Effect.timeout(\"10 millis\"),\n        Effect.catchAll(() => getItems),\n        Effect.provide(Svc.Live),\n        Effect.exit\n      )\n      strictEqual(exit._tag, \"Success\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/query.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport { seconds } from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport { pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Request from \"effect/Request\"\nimport * as Resolver from \"effect/RequestResolver\"\nimport * as TestClock from \"effect/TestClock\"\nimport type { Concurrency } from \"effect/Types\"\n\ninterface Counter {\n  readonly _: unique symbol\n}\nconst Counter = Context.GenericTag<Counter, { count: number }>(\"counter\")\ninterface Requests {\n  readonly _: unique symbol\n}\nconst Requests = Context.GenericTag<Requests, { count: number }>(\"requests\")\n\nexport const userIds: ReadonlyArray<number> = Array.range(1, 26)\n\nexport const userNames: ReadonlyMap<number, string> = new Map(\n  Array.zipWith(\n    userIds,\n    Array.map(Array.range(97, 122), (a) => String.fromCharCode(a)),\n    (a, b) => [a, b] as const\n  )\n)\n\nexport type UserRequest = GetAllIds | GetNameById\n\nexport interface GetAllIds extends Request.Request<ReadonlyArray<number>> {\n  readonly _tag: \"GetAllIds\"\n}\n\nexport const GetAllIds = Request.tagged<GetAllIds>(\"GetAllIds\")\n\nexport class GetNameById extends Request.TaggedClass(\"GetNameById\")<string, string, {\n  readonly id: number\n}> {}\n\nconst delay = <A, E, R>(self: Effect.Effect<A, E, R>) =>\n  Effect.zipRight(\n    Effect.promise(() => new Promise((r) => setTimeout(() => r(0), 0))),\n    self\n  )\n\nconst counted = <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.tap(self, () => Effect.map(Counter, (c) => c.count++))\n\nconst UserResolver = Resolver.makeBatched((requests: Array<UserRequest>) =>\n  Effect.flatMap(Requests, (r) => {\n    r.count += requests.length\n    return counted(Effect.forEach(requests, (request) => delay(processRequest(request)), { discard: true }))\n  })\n).pipe(\n  Resolver.batchN(15),\n  Resolver.contextFromServices(Counter, Requests)\n)\n\nexport const getAllUserIds = Effect.request(GetAllIds({}), UserResolver)\n\nexport const interrupts = FiberRef.unsafeMake({ interrupts: 0 })\n\nexport const getUserNameById = (id: number) => Effect.request(new GetNameById({ id }), UserResolver)\n\nexport const getUserNameByIdPiped = (id: number) => pipe(new GetNameById({ id }), Effect.request(UserResolver))\n\nexport const getAllUserNamesN = (concurrency: Concurrency) =>\n  getAllUserIds.pipe(\n    Effect.flatMap(Effect.forEach(getUserNameById, { concurrency, batching: true })),\n    Effect.onInterrupt(() => FiberRef.getWith(interrupts, (i) => Effect.sync(() => i.interrupts++)))\n  )\n\nexport const getAllUserNamesPipedN = (concurrency: Concurrency) =>\n  getAllUserIds.pipe(\n    Effect.flatMap(Effect.forEach(getUserNameById, { concurrency, batching: true })),\n    Effect.onInterrupt(() => FiberRef.getWith(interrupts, (i) => Effect.sync(() => i.interrupts++)))\n  )\n\nexport const getAllUserNames = getAllUserNamesN(\"unbounded\")\n\nexport const getAllUserNamesPiped = getAllUserNamesPipedN(\"unbounded\")\n\nexport const print = (request: UserRequest): string => {\n  switch (request._tag) {\n    case \"GetAllIds\": {\n      return request._tag\n    }\n    case \"GetNameById\": {\n      return `${request._tag}(${request.id})`\n    }\n  }\n}\n\nconst processRequest = (request: UserRequest): Effect.Effect<void> => {\n  switch (request._tag) {\n    case \"GetAllIds\": {\n      return Request.complete(request, Exit.succeed(userIds))\n    }\n    case \"GetNameById\": {\n      if (userNames.has(request.id)) {\n        const userName = userNames.get(request.id)!\n        return Request.complete(request, Exit.succeed(userName))\n      }\n      return Request.completeEffect(request, Exit.fail(\"Not Found\"))\n    }\n  }\n}\n\nconst UserResolverTagged = Resolver.fromEffectTagged<UserRequest>()({\n  GetAllIds: (reqs) =>\n    counted(Effect.flatMap(Requests, (_) => {\n      _.count += reqs.length\n      return Effect.forEach(reqs, () => Effect.succeed(userIds))\n    })),\n  GetNameById: (reqs) =>\n    counted(Effect.flatMap(Requests, (_) => {\n      _.count += reqs.length\n      return Effect.forEach(reqs, (req) => {\n        if (userNames.has(req.id)) {\n          const userName = userNames.get(req.id)!\n          return Effect.succeed(userName)\n        }\n        return Effect.fail(\"Not Found\")\n      })\n    }))\n}).pipe(\n  Resolver.batchN(15),\n  Resolver.contextFromServices(Counter, Requests)\n)\nexport const getAllUserIdsTagged = Effect.request(GetAllIds({}), UserResolverTagged)\nexport const getUserNameByIdTagged = (id: number) => Effect.request(new GetNameById({ id }), UserResolverTagged)\nexport const getAllUserNamesTagged = getAllUserIdsTagged.pipe(\n  Effect.flatMap(Effect.forEach(getUserNameByIdTagged, { batching: true }))\n)\n\nconst EnvLive = Layer.mergeAll(\n  Layer.sync(Counter, () => ({ count: 0 })),\n  Layer.sync(Requests, () => ({ count: 0 }))\n).pipe(\n  Layer.provideMerge(\n    Layer.mergeAll(\n      Layer.setRequestCache(Request.makeCache({\n        capacity: 100,\n        timeToLive: seconds(60)\n      })),\n      Layer.setRequestCaching(true),\n      Layer.setRequestBatching(true)\n    )\n  )\n)\n\nconst provideEnv = Effect.provide(EnvLive)\n\ndescribe(\"Effect\", () => {\n  it.effect(\"avoid false interruption when concurrency happens in resolver\", () =>\n    Effect.gen(function*() {\n      class RequestUserById extends Request.TaggedClass(\"RequestUserById\")<number, never, {\n        id: string\n      }> {}\n      let count = 0\n      const resolver = Resolver.makeBatched((i) => {\n        count++\n        return Effect.forEach(i, Request.complete(Exit.succeed(1)), { concurrency: \"unbounded\" })\n      })\n      yield* Effect.request(new RequestUserById({ id: \"1\" }), resolver).pipe(\n        Effect.withRequestCaching(true),\n        Effect.repeatN(3)\n      )\n      strictEqual(count, 1)\n    }))\n  it.effect(\"requests are executed correctly\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        const names = yield* getAllUserNames\n        const count = yield* Counter\n        strictEqual(count.count, 3)\n        assertTrue(names.length > 2)\n        deepStrictEqual(names, userIds.map((id) => userNames.get(id)))\n      })\n    ))\n  it.effect(\"requests with dual syntax are executed correctly\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        const names = yield* getAllUserNamesPiped\n        const count = yield* Counter\n        strictEqual(count.count, 3)\n        assertTrue(names.length > 2)\n        deepStrictEqual(names, userIds.map((id) => userNames.get(id)))\n      })\n    ))\n  it.effect(\"requests are executed correctly with fromEffectTagged\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        const names = yield* getAllUserNamesTagged\n        const count = yield* Counter\n        strictEqual(count.count, 3)\n        assertTrue(names.length > 2)\n        deepStrictEqual(names, userIds.map((id) => userNames.get(id)))\n      })\n    ))\n  it.effect(\"batching composes\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        const cache = yield* (FiberRef.get(FiberRef.currentRequestCache))\n        yield* (cache.invalidateAll)\n        const names = yield* (Effect.zip(getAllUserNames, getAllUserNames, {\n          concurrent: true,\n          batching: true\n        }))\n        const count = yield* Counter\n        strictEqual(count.count, 3)\n        assertTrue(names[0].length > 2)\n        deepStrictEqual(names[0], userIds.map((id) => userNames.get(id)))\n        deepStrictEqual(names[0], names[1])\n      })\n    ))\n  it.effect(\"withSpan doesn't break batching\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        yield* pipe(\n          Effect.zip(\n            getAllUserIds.pipe(Effect.withSpan(\"A\")),\n            getAllUserIds.pipe(Effect.withSpan(\"B\")),\n            { concurrent: true, batching: true }\n          ),\n          Effect.withRequestCaching(false)\n        )\n        const count = yield* Counter\n        strictEqual(count.count, 1)\n      })\n    ))\n  it.effect(\"batching is independent from parallelism\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        const names = yield* (getAllUserNamesN(5))\n        const count = yield* Counter\n        strictEqual(count.count, 3)\n        assertTrue(names.length > 2)\n        deepStrictEqual(names, userIds.map((id) => userNames.get(id)))\n      })\n    ))\n  it.effect(\"batching doesn't break interruption\", () =>\n    Effect.locally(interrupts, { interrupts: 0 })(\n      provideEnv(\n        Effect.gen(function*() {\n          const exit = yield* pipe(\n            getAllUserNames,\n            Effect.zipLeft(Effect.interrupt, {\n              concurrent: true,\n              batching: true\n            }),\n            Effect.exit\n          )\n          strictEqual(exit._tag, \"Failure\")\n          if (exit._tag === \"Failure\") {\n            assertTrue(Cause.isInterruptedOnly(exit.cause))\n          }\n          const cache = yield* (FiberRef.get(FiberRef.currentRequestCache))\n          const values = yield* (cache.values)\n          strictEqual(values[0].handle.state.current._tag, \"Done\")\n          deepStrictEqual(yield* Counter, { count: 0 })\n          deepStrictEqual(yield* (FiberRef.get(interrupts)), { interrupts: 1 })\n        })\n      )\n    ))\n  it.effect(\"requests dont't break interruption\", () =>\n    Effect.locally(interrupts, { interrupts: 0 })(\n      provideEnv(\n        Effect.gen(function*() {\n          const fiber = yield* pipe(getAllUserNames, Effect.fork)\n          yield* (Effect.yieldNow())\n          yield* (Fiber.interrupt(fiber))\n          const exit = yield* (Fiber.await(fiber))\n          strictEqual(exit._tag, \"Failure\")\n          if (exit._tag === \"Failure\") {\n            assertTrue(Cause.isInterruptedOnly(exit.cause))\n          }\n          deepStrictEqual(yield* Counter, { count: 0 })\n          deepStrictEqual(yield* (FiberRef.get(interrupts)), { interrupts: 1 })\n        })\n      )\n    ))\n  it.effect(\"requests work with uninterruptible\", () =>\n    Effect.locally(interrupts, { interrupts: 0 })(\n      provideEnv(\n        Effect.gen(function*() {\n          const fiber = yield* pipe(getAllUserNames, Effect.uninterruptible, Effect.fork)\n          yield* (Effect.yieldNow())\n          yield* (Fiber.interrupt(fiber))\n          const exit = yield* (Fiber.await(fiber))\n          strictEqual(exit._tag, \"Failure\")\n          if (exit._tag === \"Failure\") {\n            assertTrue(Cause.isInterruptedOnly(exit.cause))\n          }\n          deepStrictEqual(yield* Counter, { count: 3 })\n          deepStrictEqual(yield* (FiberRef.get(interrupts)), { interrupts: 0 })\n        })\n      )\n    ))\n  it.effect(\"batching doesn't break interruption when limited\", () =>\n    Effect.locally(interrupts, { interrupts: 0 })(\n      provideEnv(\n        Effect.gen(function*() {\n          const exit = yield* pipe(\n            getAllUserNames,\n            Effect.zipLeft(Effect.interrupt, {\n              concurrent: true,\n              batching: true\n            }),\n            Effect.exit\n          )\n          strictEqual(exit._tag, \"Failure\")\n          if (exit._tag === \"Failure\") {\n            assertTrue(Cause.isInterruptedOnly(exit.cause))\n          }\n          deepStrictEqual(yield* Counter, { count: 0 })\n          deepStrictEqual(yield* (FiberRef.get(interrupts)), { interrupts: 1 })\n        })\n      )\n    ))\n  it.effect(\"zip/parallel is not batched when specified\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        const [a, b] = yield* pipe(\n          Effect.zip(\n            getUserNameById(userIds[0]),\n            getUserNameById(userIds[1]),\n            {\n              concurrent: true,\n              batching: false\n            }\n          ),\n          Effect.withRequestBatching(true)\n        )\n        const count = yield* Counter\n        strictEqual(count.count, 2)\n        deepStrictEqual(a, userNames.get(userIds[0]))\n        deepStrictEqual(b, userNames.get(userIds[1]))\n      })\n    ))\n  it.effect(\"zip/parallel is batched by default\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        const [a, b] = yield* (\n          Effect.zip(\n            getUserNameById(userIds[0]),\n            getUserNameById(userIds[1]),\n            {\n              concurrent: true,\n              batching: true\n            }\n          )\n        )\n        const count = yield* Counter\n        strictEqual(count.count, 1)\n        deepStrictEqual(a, userNames.get(userIds[0]))\n        deepStrictEqual(b, userNames.get(userIds[1]))\n      })\n    ))\n  it.effect(\"cache respects ttl\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        yield* getAllUserIds\n        yield* getAllUserIds\n        deepStrictEqual(yield* Counter, { count: 1 })\n        yield* (TestClock.adjust(seconds(10)))\n        yield* getAllUserIds\n        yield* getAllUserIds\n        deepStrictEqual(yield* Counter, { count: 1 })\n        yield* (TestClock.adjust(seconds(60)))\n        yield* getAllUserIds\n        yield* getAllUserIds\n        deepStrictEqual(yield* Counter, { count: 2 })\n      })\n    ))\n  it.effect(\"cache can be warmed up\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        yield* (Effect.cacheRequestResult(GetAllIds({}), Exit.succeed(userIds)))\n        yield* getAllUserIds\n        yield* getAllUserIds\n        deepStrictEqual(yield* Counter, { count: 0 })\n        yield* (TestClock.adjust(seconds(65)))\n        yield* getAllUserIds\n        yield* getAllUserIds\n        deepStrictEqual(yield* Counter, { count: 1 })\n      })\n    ))\n  it.effect(\"cache can be disabled\", () =>\n    provideEnv(\n      Effect.withRequestCaching(false)(Effect.gen(function*() {\n        yield* getAllUserIds\n        yield* getAllUserIds\n        deepStrictEqual(yield* Counter, { count: 2 })\n        yield* (TestClock.adjust(seconds(10)))\n        yield* getAllUserIds\n        yield* getAllUserIds\n        deepStrictEqual(yield* Counter, { count: 4 })\n        yield* (TestClock.adjust(seconds(60)))\n        yield* getAllUserIds\n        yield* getAllUserIds\n        deepStrictEqual(yield* Counter, { count: 6 })\n      }))\n    ))\n\n  it.effect(\"batching preserves individual & identical requests\", () =>\n    provideEnv(\n      Effect.gen(function*() {\n        yield* pipe(\n          Effect.all([getUserNameById(userIds[0]), getUserNameById(userIds[0])], {\n            concurrency: \"unbounded\",\n            batching: true,\n            discard: true\n          }),\n          Effect.withRequestCaching(false)\n        )\n        const requests = yield* Requests\n        const invocations = yield* Counter\n        deepStrictEqual(requests.count, 2)\n        deepStrictEqual(invocations.count, 1)\n      })\n    ))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/racing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"raceAll waits losers interruption\", () =>\n    Effect.gen(function*() {\n      const messages: Array<string> = []\n\n      const a = Effect.gen(function*() {\n        yield* Effect.addFinalizer(() => Effect.sync(() => messages.push(\"finalize a\")))\n        yield* Effect.sleep(\"100 millis\")\n        yield* Effect.sync(() => messages.push(\"done a\"))\n      })\n\n      const b = Effect.gen(function*() {\n        yield* Effect.addFinalizer(() => Effect.sync(() => messages.push(\"finalize b\")))\n        yield* Effect.sleep(\"200 millis\")\n        yield* Effect.sync(() => messages.push(\"done b\"))\n      })\n\n      yield* Effect.raceAll([\n        Effect.scoped(a),\n        Effect.scoped(b)\n      ]).pipe(\n        Effect.tap(() => Effect.sync(() => messages.push(\"race done\"))),\n        Effect.fork\n      )\n\n      yield* TestClock.adjust(\"300 millis\")\n\n      deepStrictEqual(messages, [\n        \"done a\",\n        \"finalize a\",\n        \"finalize b\",\n        \"race done\"\n      ])\n    }))\n  it.effect(\"returns first success\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.raceAll([Effect.fail(\"fail\"), Effect.succeed(24)]))\n      strictEqual(result, 24)\n    }))\n  it.live(\"returns last failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          Effect.raceAll([pipe(Effect.sleep(Duration.millis(100)), Effect.zipRight(Effect.fail(24))), Effect.fail(25)]),\n          Effect.flip\n        )\n      )\n      strictEqual(result, 24)\n    }))\n  it.live(\"returns success when it happens after failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        Effect.raceAll([\n          Effect.fail(42),\n          pipe(Effect.succeed(24), Effect.zipLeft(Effect.sleep(Duration.millis(100))))\n        ])\n      )\n      strictEqual(result, 24)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/rendezvous.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as Queue from \"effect/Queue\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"bounded 0 is rendezvous\", () =>\n    Effect.gen(function*() {\n      const rendevous = yield* Queue.bounded<string>(0)\n      const logs: Array<string> = []\n\n      const fiber = yield* (\n        Effect.fork(\n          Effect.gen(function*() {\n            yield* Effect.sleep(\"50 millis\")\n            logs.push(\"sending message\")\n            yield* Queue.offer(rendevous, \"Hello World\")\n            logs.push(\"sent message\")\n          })\n        )\n      )\n\n      const fiber2 = yield* (\n        Effect.fork(\n          Effect.gen(function*() {\n            yield* Effect.sleep(\"100 millis\")\n            logs.push(\"receiving message\")\n            const message = yield* Queue.take(rendevous)\n            logs.push(\"received message\")\n            logs.push(message)\n          })\n        )\n      )\n\n      yield* TestClock.adjust(\"200 millis\")\n\n      yield* Fiber.join(Fiber.zip(fiber, fiber2))\n\n      deepStrictEqual(logs, [\n        \"sending message\",\n        \"receiving message\",\n        \"received message\",\n        \"Hello World\",\n        \"sent message\"\n      ])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/repeating.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { constFalse, constTrue, pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"succeeds eventually\", () =>\n    Effect.gen(function*() {\n      const effect = (ref: Ref.Ref<number>) => {\n        return pipe(\n          Ref.get(ref),\n          Effect.flatMap((n) =>\n            n < 10 ?\n              pipe(Ref.update(ref, (n) => n + 1), Effect.zipRight(Effect.fail(\"Ouch\"))) :\n              Effect.succeed(n)\n          )\n        )\n      }\n      const ref = yield* (Ref.make(0))\n      const result = yield* (Effect.eventually(effect(ref)))\n      strictEqual(result, 10)\n    }))\n\n  it.effect(\"repeat/until - repeats until condition is true\", () =>\n    Effect.gen(function*() {\n      const input = yield* (Ref.make(10))\n      const output = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(input, (n) => n - 1),\n        Effect.zipLeft(Ref.update(output, (n) => n + 1)),\n        Effect.repeat({ until: (n) => n === 0 })\n      )\n      const result = yield* (Ref.get(output))\n      strictEqual(result, 10)\n    }))\n\n  it.effect(\"repeat/until - preserves return value\", () =>\n    Effect.gen(function*() {\n      const input = yield* (Ref.make(10))\n      const result = yield* pipe(\n        Ref.updateAndGet(input, (n) => n - 1),\n        Effect.repeat({ until: (n) => n === 0 })\n      )\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"repeat/until - always evaluates effect at least once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(Ref.update(ref, (n) => n + 1), Effect.repeat({ until: constTrue }))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1)\n    }))\n  it.effect(\"repeat/until - repeats until the effectful condition is true\", () =>\n    Effect.gen(function*() {\n      const input = yield* (Ref.make(10))\n      const output = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(input, (n) => n - 1),\n        Effect.zipLeft(Ref.update(output, (n) => n + 1)),\n        Effect.repeat({ until: (n) => Effect.succeed(n === 0) })\n      )\n      const result = yield* (Ref.get(output))\n      strictEqual(result, 10)\n    }))\n  it.effect(\"repeat/until - always evaluates the effect at least once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(Ref.update(ref, (n) => n + 1), Effect.repeat({ until: () => Effect.succeed(true) }))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1)\n    }))\n  it.effect(\"repeat/while - repeats while the condition is true\", () =>\n    Effect.gen(function*() {\n      const input = yield* (Ref.make(10))\n      const output = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(input, (n) => n - 1),\n        Effect.zipLeft(Ref.update(output, (n) => n + 1)),\n        Effect.repeat({ while: (n) => n >= 0 })\n      )\n      const result = yield* (Ref.get(output))\n      strictEqual(result, 11)\n    }))\n  it.effect(\"repeat/while - always evaluates the effect at least once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(Ref.update(ref, (n) => n + 1), Effect.repeat({ while: constFalse }))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1)\n    }))\n  it.effect(\"repeat/while - repeats while condition is true\", () =>\n    Effect.gen(function*() {\n      const input = yield* (Ref.make(10))\n      const output = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(input, (n) => n - 1),\n        Effect.zipLeft(Ref.update(output, (n) => n + 1)),\n        Effect.repeat({ while: (v) => Effect.succeed(v >= 0) })\n      )\n      const result = yield* (Ref.get(output))\n      strictEqual(result, 11)\n    }))\n  it.effect(\"repeat/while - always evaluates effect at least once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(Ref.update(ref, (n) => n + 1), Effect.repeat({ while: () => Effect.succeed(false) }))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"repeat/schedule\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(Ref.update(ref, (n) => n + 1), Effect.repeat(Schedule.recurs(3)))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 4)\n    }))\n\n  it.effect(\"repeat/schedule - CurrentIterationMetadata\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<Array<undefined | Schedule.IterationMetadata>>([])\n      yield* Effect.gen(function*() {\n        const currentIterationMeta = yield* Schedule.CurrentIterationMetadata\n        yield* Ref.update(ref, (infos) => [...infos, currentIterationMeta])\n      }).pipe(\n        Effect.repeat(\n          Schedule.intersect(Schedule.fixed(\"1 second\"), Schedule.recurs(2))\n        ),\n        Effect.fork\n      )\n      yield* TestClock.adjust(Duration.seconds(50))\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(result, [\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          recurrence: 0,\n          input: undefined,\n          output: undefined,\n          now: 0,\n          start: 0\n        },\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          recurrence: 1,\n          input: undefined,\n          output: [0, 0],\n          now: 0,\n          start: 0\n        },\n        {\n          elapsed: Duration.seconds(1),\n          elapsedSincePrevious: Duration.seconds(1),\n          recurrence: 2,\n          input: undefined,\n          output: [1, 1],\n          now: 1000,\n          start: 0\n        }\n      ])\n    }))\n\n  it.effect(\"repeat/schedule + until\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(ref, (n) => n + 1),\n        Effect.repeat({ schedule: Schedule.recurs(3), until: (n) => n === 3 })\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 3)\n    }))\n\n  it.effect(\"repeat/schedule + while\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(ref, (n) => n + 1),\n        Effect.repeat({ schedule: Schedule.recurs(3), while: (n) => n < 3 })\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 3)\n    }))\n\n  it.effect(\"repeat/times \", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<Array<number>>([]))\n      const effectResult = yield* pipe(\n        Ref.updateAndGet(ref, (arr) => {\n          arr.push(arr.length)\n          return arr\n        }),\n        Effect.repeat({ times: 2 })\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(result, [0, 1, 2])\n      deepStrictEqual(effectResult, [0, 1, 2])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/retrying.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { constFalse, constTrue, pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"retry/until - retries until condition is true\", () =>\n    Effect.gen(function*() {\n      const input = yield* (Ref.make(10))\n      const output = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(input, (n) => n - 1),\n        Effect.zipLeft(Ref.update(output, (n) => n + 1)),\n        Effect.flipWith(Effect.retry({ until: (n) => n === 0 }))\n      )\n      const result = yield* (Ref.get(output))\n      strictEqual(result, 10)\n    }))\n  it.effect(\"retry/until - runs at least once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(Ref.update(ref, (n) => n + 1), Effect.flipWith(Effect.retry({ until: constTrue })))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1)\n    }))\n  it.effect(\"retry/until - retries until condition is true\", () =>\n    Effect.gen(function*() {\n      const input = yield* (Ref.make(10))\n      const output = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(input, (n) => n - 1),\n        Effect.zipLeft(Ref.update(output, (n) => n + 1)),\n        Effect.flipWith(Effect.retry({ until: (n) => Effect.succeed(n === 0) }))\n      )\n      const result = yield* (Ref.get(output))\n      strictEqual(result, 10)\n    }))\n  it.effect(\"retry/until - runs at least once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.update(ref, (n) => n + 1),\n        Effect.flipWith(Effect.retry({ until: () => Effect.succeed(true) }))\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1)\n    }))\n  it.effect(\"retry/while - retries while condition is true\", () =>\n    Effect.gen(function*() {\n      const input = yield* (Ref.make(10))\n      const output = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(input, (n) => n - 1),\n        Effect.zipLeft(Ref.update(output, (n) => n + 1)),\n        Effect.flipWith(Effect.retry({ while: (n) => n >= 0 }))\n      )\n      const result = yield* (Ref.get(output))\n      strictEqual(result, 11)\n    }))\n  it.effect(\"retry/while - runs at least once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(Ref.update(ref, (n) => n + 1), Effect.flipWith(Effect.retry({ while: constFalse })))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1)\n    }))\n  it.effect(\"retry/while - retries while condition is true\", () =>\n    Effect.gen(function*() {\n      const input = yield* (Ref.make(10))\n      const output = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(input, (n) => n - 1),\n        Effect.zipLeft(Ref.update(output, (n) => n + 1)),\n        Effect.flipWith(Effect.retry({ while: (n) => Effect.succeed(n >= 0) }))\n      )\n      const result = yield* (Ref.get(output))\n      strictEqual(result, 11)\n    }))\n  it.effect(\"retry/while - runs at least once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.update(ref, (n) => n + 1),\n        Effect.flipWith(Effect.retry({ while: () => Effect.succeed(false) }))\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1)\n    }))\n  it.effect(\"retry/schedule\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.update(ref, (n) => n + 1),\n        Effect.flipWith(Effect.retry(Schedule.recurs(3)))\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 4)\n    }))\n  it.effect(\"retry/schedule - CurrentIterationMetadata\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<Array<undefined | Schedule.IterationMetadata>>([])\n      yield* pipe(\n        Effect.gen(function*() {\n          const currentIterationMeta = yield* Schedule.CurrentIterationMetadata\n          yield* Ref.update(ref, (infos) => [...infos, currentIterationMeta])\n        }),\n        Effect.flipWith(Effect.retry(Schedule.recurs(3)))\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(result, [\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          recurrence: 0,\n          input: undefined,\n          output: undefined,\n          now: 0,\n          start: 0\n        },\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          recurrence: 1,\n          input: undefined,\n          output: 0,\n          now: 0,\n          start: 0\n        },\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          recurrence: 2,\n          input: undefined,\n          output: 1,\n          now: 0,\n          start: 0\n        },\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          recurrence: 3,\n          input: undefined,\n          output: 2,\n          now: 0,\n          start: 0\n        }\n      ])\n    }))\n\n  it.effect(\"retry/schedule + until\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(ref, (n) => n + 1),\n        Effect.flipWith(Effect.retry({\n          schedule: Schedule.recurs(3),\n          until: (n) => n === 3\n        }))\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 3)\n    }))\n\n  it.effect(\"retry/schedule + until effect\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(ref, (n) => n + 1),\n        Effect.flipWith(Effect.retry({\n          schedule: Schedule.recurs(3),\n          until: (n) => Effect.succeed(n === 3)\n        }))\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 3)\n    }))\n\n  it.effect(\"retry/schedule + until error\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const result = yield* pipe(\n        Ref.updateAndGet(ref, (n) => n + 1),\n        Effect.flipWith(Effect.retry({\n          schedule: Schedule.recurs(3),\n          until: (_n) => Effect.fail(\"err\" as const)\n        }))\n      )\n      strictEqual(result, \"err\")\n    }))\n\n  it.effect(\"retry/schedule + while\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(ref, (n) => n + 1),\n        Effect.flipWith(Effect.retry({\n          schedule: Schedule.recurs(3),\n          while: (n) => n < 3\n        }))\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 3)\n    }))\n\n  it.effect(\"retry/schedule + while error\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const result = yield* pipe(\n        Ref.updateAndGet(ref, (n) => n + 1),\n        Effect.flipWith(Effect.retry({\n          schedule: Schedule.recurs(3),\n          while: (_n) => Effect.fail(\"err\" as const)\n        }))\n      )\n      strictEqual(result, \"err\")\n    }))\n\n  it.effect(\"retry/schedule + while effect\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Ref.updateAndGet(ref, (n) => n + 1),\n        Effect.flipWith(Effect.retry({\n          schedule: Schedule.recurs(3),\n          while: (n) => Effect.succeed(n < 3)\n        }))\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 3)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/runtimeFlags.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Flags from \"effect/RuntimeFlags\"\nimport * as Patch from \"effect/RuntimeFlagsPatch\"\n\ndescribe(\"Effect\", () => {\n  it(\"should enable flags in the current fiber\", () =>\n    Effect.runPromise(Effect.gen(function*() {\n      const before = yield* Effect.getRuntimeFlags\n      assertFalse(Flags.isEnabled(before, Flags.OpSupervision))\n      yield* Effect.patchRuntimeFlags(Patch.enable(Flags.OpSupervision))\n      const after = yield* Effect.getRuntimeFlags\n      assertTrue(Flags.isEnabled(after, Flags.OpSupervision))\n    })))\n  it(\"should enable flags in the wrapped effect\", () =>\n    Effect.runPromise(Effect.gen(function*() {\n      const before = yield* Effect.getRuntimeFlags\n      assertFalse(Flags.isEnabled(before, Flags.OpSupervision))\n      const inside = yield* pipe(\n        Effect.getRuntimeFlags,\n        Effect.withRuntimeFlagsPatch(Patch.enable(Flags.OpSupervision))\n      )\n      const after = yield* Effect.getRuntimeFlags\n      assertFalse(Flags.isEnabled(after, Flags.OpSupervision))\n      assertTrue(Flags.isEnabled(inside, Flags.OpSupervision))\n    })))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/scheduler.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Scheduler from \"effect/Scheduler\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"matrix schedules according to priority\", () =>\n    Effect.gen(function*() {\n      const ps000: Array<number> = []\n      const ps100: Array<number> = []\n      const ps200: Array<number> = []\n      const scheduler = Scheduler.makeMatrix(\n        [\n          0,\n          Scheduler.makeBatched((runBatch) => {\n            ps000.push(0)\n            setTimeout(runBatch, 0)\n          })\n        ],\n        [\n          100,\n          Scheduler.makeBatched((runBatch) => {\n            ps100.push(100)\n            setTimeout(runBatch, 0)\n          })\n        ],\n        [\n          200,\n          Scheduler.makeBatched((runBatch) => {\n            ps200.push(200)\n            setTimeout(runBatch, 0)\n          })\n        ],\n        [\n          300,\n          Scheduler.makeBatched((runBatch) => {\n            setTimeout(runBatch, 0)\n          })\n        ]\n      )\n      yield* pipe(\n        Effect.yieldNow(),\n        Effect.withScheduler(scheduler)\n      )\n      deepStrictEqual(ps000, [0])\n      yield* pipe(\n        Effect.yieldNow({ priority: 50 }),\n        Effect.withScheduler(scheduler)\n      )\n      deepStrictEqual(ps000, [0, 0])\n      yield* pipe(\n        Effect.yieldNow({ priority: 100 }),\n        Effect.withScheduler(scheduler)\n      )\n      deepStrictEqual(ps100, [100])\n      yield* pipe(\n        Effect.yieldNow({ priority: 150 }),\n        Effect.withScheduler(scheduler)\n      )\n      deepStrictEqual(ps100, [100, 100])\n      yield* pipe(\n        Effect.yieldNow({ priority: 200 }),\n        Effect.withScheduler(scheduler)\n      )\n      deepStrictEqual(ps100, [100, 100])\n      deepStrictEqual(ps200, [200])\n      yield* pipe(\n        Effect.yieldNow({ priority: 300 }),\n        Effect.withScheduler(scheduler)\n      )\n      deepStrictEqual(ps100, [100, 100])\n      deepStrictEqual(ps200, [200])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/scheduling.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Clock from \"effect/Clock\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"schedule - runs effect for each recurrence of the schedule\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<ReadonlyArray<Duration.Duration>>([])\n      const effect = pipe(\n        Clock.currentTimeMillis,\n        Effect.flatMap((duration) => Ref.update(ref, (array) => [...array, Duration.millis(duration)]))\n      )\n      const schedule = pipe(Schedule.spaced(Duration.seconds(1)), Schedule.intersect(Schedule.recurs(5)))\n      yield* pipe(effect, Effect.schedule(schedule), Effect.fork)\n      yield* TestClock.adjust(Duration.seconds(5))\n      const value = yield* Ref.get(ref)\n      const expected = [1, 2, 3, 4, 5].map(Duration.seconds)\n      deepStrictEqual(value, expected)\n    }))\n\n  it.effect(\"schedule - Schedule.CurrentIterationMetadata\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<Array<undefined | Schedule.IterationMetadata>>([])\n      const effect = Effect.gen(function*() {\n        const lastIterationInfo = yield* Schedule.CurrentIterationMetadata\n\n        yield* Ref.update(ref, (array) => [...array, lastIterationInfo])\n      })\n      const schedule = pipe(Schedule.fibonacci(\"1 second\"), Schedule.intersect(Schedule.recurs(4)))\n      yield* pipe(effect, Effect.schedule(schedule), Effect.fork)\n      yield* TestClock.adjust(Duration.seconds(50))\n      const value = yield* Ref.get(ref)\n\n      deepStrictEqual(value, [\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          recurrence: 1,\n          input: undefined,\n          output: [Duration.millis(1000), 0],\n          now: 0,\n          start: 0\n        },\n        {\n          elapsed: Duration.seconds(1),\n          elapsedSincePrevious: Duration.seconds(1),\n          recurrence: 2,\n          input: undefined,\n          output: [Duration.millis(1000), 1],\n          now: 1000,\n          start: 0\n        },\n        {\n          elapsed: Duration.seconds(2),\n          elapsedSincePrevious: Duration.seconds(1),\n          recurrence: 3,\n          input: undefined,\n          output: [Duration.millis(2000), 2],\n          now: 2000,\n          start: 0\n        },\n        {\n          elapsed: Duration.seconds(4),\n          elapsedSincePrevious: Duration.seconds(2),\n          recurrence: 4,\n          input: undefined,\n          output: [Duration.millis(3000), 3],\n          now: 4000,\n          start: 0\n        }\n      ])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/scope-ref.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport { GenericTag } from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport { pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as List from \"effect/List\"\nimport * as Logger from \"effect/Logger\"\n\nconst ref = FiberRef.unsafeMake(List.empty<string>())\nconst env = GenericTag<\"context\", number>(\"context\")\n\nconst withValue = (value: string) => Effect.locallyWith(ref, List.prepend(value))\n\nconst logRef = (msg: string) =>\n  Effect.gen(function*() {\n    const stack = yield* FiberRef.get(ref)\n    const value = yield* env\n    yield* Effect.log(`${value} | ${msg} | ${List.toArray(stack).join(\" > \")}`)\n  })\n\ndescribe(\"Effect\", () => {\n  it.effect(\"scoped ref\", () =>\n    Effect.gen(function*() {\n      const messages: Array<unknown> = []\n      const layer = Layer.mergeAll(\n        Logger.replace(\n          Logger.defaultLogger,\n          Logger.make((_) => {\n            messages.push(_.message)\n          })\n        ),\n        Layer.succeed(env, 1)\n      )\n\n      yield* pipe(\n        Effect.acquireRelease(\n          withValue(\"A\")(logRef(\"acquire\")),\n          () => withValue(\"R\")(logRef(\"release\"))\n        ),\n        withValue(\"INNER\"),\n        Effect.scoped,\n        withValue(\"OUTER\"),\n        Effect.provide(layer),\n        withValue(\"EXTERN\")\n      )\n\n      deepStrictEqual(messages, [\n        [\"1 | acquire | A > INNER > OUTER > EXTERN\"],\n        [\"1 | release | R > INNER > OUTER > EXTERN\"]\n      ])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/semaphore.test.ts",
    "content": "import { assert, describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as D from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberId from \"effect/FiberId\"\nimport * as Option from \"effect/Option\"\nimport * as Scheduler from \"effect/Scheduler\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"semaphore works\", () =>\n    Effect.gen(function*() {\n      const sem = yield* Effect.makeSemaphore(4)\n      const messages: Array<string> = []\n      yield* Effect.fork(Effect.all(\n        [0, 1, 2, 3].map((n) =>\n          sem.withPermits(2)(Effect.delay(D.seconds(2))(Effect.sync(() => messages.push(`process: ${n}`))))\n        ),\n        { concurrency: \"unbounded\", discard: true }\n      ))\n      yield* (TestClock.adjust(D.seconds(3)))\n      strictEqual(messages.length, 2)\n      yield* (TestClock.adjust(D.seconds(3)))\n      strictEqual(messages.length, 4)\n      yield* (\n        Effect.fork(Effect.all(\n          [0, 1, 2, 3].map((n) =>\n            sem.withPermits(2)(Effect.delay(D.seconds(2))(Effect.sync(() => messages.push(`process: ${n}`))))\n          ),\n          { concurrency: \"unbounded\", discard: true }\n        ))\n      )\n      yield* (TestClock.adjust(D.seconds(3)))\n      strictEqual(messages.length, 6)\n      yield* (TestClock.adjust(D.seconds(3)))\n      strictEqual(messages.length, 8)\n    }))\n\n  it.effect(\"releaseAll\", () =>\n    Effect.gen(function*() {\n      const sem = yield* Effect.makeSemaphore(4)\n      yield* sem.take(4)\n      yield* sem.releaseAll\n      yield* sem.take(1)\n    }))\n\n  it.effect(\"resize\", () =>\n    Effect.gen(function*() {\n      const sem = yield* Effect.makeSemaphore(4)\n      yield* sem.take(4)\n      yield* sem.resize(2)\n      const fiber = yield* Effect.fork(sem.take(1))\n      yield* TestClock.adjust(1)\n      assert.isNull(fiber.unsafePoll())\n      yield* sem.release(2)\n      yield* TestClock.adjust(1)\n      assert.isNull(fiber.unsafePoll())\n      yield* sem.release(1)\n      yield* TestClock.adjust(1)\n      assert.isTrue(fiber.unsafePoll() !== null)\n    }))\n\n  it.effect(\"take interruption does not leak permits\", () =>\n    Effect.gen(function*() {\n      const scheduler = new Scheduler.ControlledScheduler()\n      const sem = yield* Effect.makeSemaphore(0)\n      const waiter = yield* sem.take(1).pipe(\n        Effect.withScheduler(scheduler),\n        Effect.fork\n      )\n\n      yield* Effect.yieldNow()\n      yield* sem.release(1).pipe(Effect.withScheduler(scheduler))\n      assert.isNull(waiter.unsafePoll())\n\n      scheduler.step()\n      assert.isNull(waiter.unsafePoll())\n\n      waiter.unsafeInterruptAsFork(FiberId.none)\n      scheduler.step()\n\n      const result = yield* sem.withPermitsIfAvailable(1)(Effect.void)\n      assert.isTrue(Option.isSome(result))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/sequencing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { constFalse, constTrue, pipe } from \"effect/Function\"\nimport * as HashSet from \"effect/HashSet\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"andThen\", () =>\n    Effect.gen(function*() {\n      const a0 = Effect.andThen(Effect.succeed(0), Effect.succeed(1))\n      const a1 = Effect.succeed(0).pipe(Effect.andThen(Effect.succeed(1)))\n      const a2 = Effect.andThen(Effect.succeed(0), (n) => Effect.succeed(n + 1))\n      const a3 = Effect.succeed(0).pipe(Effect.andThen((n) => Effect.succeed(n + 1)))\n      const a4 = Effect.succeed(0).pipe(Effect.andThen(\"ok\"))\n      const a5 = Effect.succeed(0).pipe(Effect.andThen(() => \"ok\"))\n      const a6 = Effect.andThen(Effect.succeed(0), () => \"ok\")\n      const a7 = Effect.andThen(Effect.succeed(0), \"ok\")\n      const a8 = Effect.andThen(Effect.succeed(0), () => Promise.resolve(\"ok\"))\n      const a9 = Effect.andThen(Effect.succeed(0), Promise.resolve(\"ok\"))\n      strictEqual(yield* a0, 1)\n      strictEqual(yield* a1, 1)\n      strictEqual(yield* a2, 1)\n      strictEqual(yield* a3, 1)\n      strictEqual(yield* a4, \"ok\")\n      strictEqual(yield* a5, \"ok\")\n      strictEqual(yield* a6, \"ok\")\n      strictEqual(yield* a7, \"ok\")\n      strictEqual(yield* a8, \"ok\")\n      strictEqual(yield* a9, \"ok\")\n    }))\n  it.effect(\"tap\", () =>\n    Effect.gen(function*() {\n      const a0 = Effect.tap(Effect.succeed(0), Effect.succeed(1))\n      const a1 = Effect.succeed(0).pipe(Effect.tap(Effect.succeed(1)))\n      const a2 = Effect.succeed(0).pipe(Effect.tap(Effect.succeed(1), { onlyEffect: true }))\n      const a3 = Effect.tap(Effect.succeed(0), (n) => Effect.succeed(n + 1))\n      const a4 = Effect.tap(Effect.succeed(0), (n) => Effect.succeed(n + 1), { onlyEffect: true })\n      const a5 = Effect.succeed(0).pipe(Effect.tap((n) => Effect.succeed(n + 1)))\n      const a6 = Effect.succeed(0).pipe(Effect.tap((n) => Effect.succeed(n + 1), { onlyEffect: true }))\n      const a7 = Effect.succeed(0).pipe(Effect.tap(\"ok\"))\n      const a8 = Effect.succeed(0).pipe(Effect.tap(() => \"ok\"))\n      const a9 = Effect.tap(Effect.succeed(0), () => \"ok\")\n      const a10 = Effect.tap(Effect.succeed(0), \"ok\")\n      const a11 = Effect.tap(Effect.succeed(0), () => Promise.resolve(\"ok\"))\n      const a12 = Effect.tap(Effect.succeed(0), Promise.resolve(\"ok\"))\n      strictEqual(yield* a0, 0)\n      strictEqual(yield* a1, 0)\n      strictEqual(yield* a2, 0)\n      strictEqual(yield* a3, 0)\n      strictEqual(yield* a4, 0)\n      strictEqual(yield* a5, 0)\n      strictEqual(yield* a6, 0)\n      strictEqual(yield* a7, 0)\n      strictEqual(yield* a8, 0)\n      strictEqual(yield* a9, 0)\n      strictEqual(yield* a10, 0)\n      strictEqual(yield* a11, 0)\n      strictEqual(yield* a12, 0)\n    }))\n  it.effect(\"flattens nested effects\", () =>\n    Effect.gen(function*() {\n      const effect = Effect.succeed(Effect.succeed(\"test\"))\n      const flatten1 = yield* (Effect.flatten(effect))\n      const flatten2 = yield* (Effect.flatten(effect))\n      strictEqual(flatten1, \"test\")\n      strictEqual(flatten2, \"test\")\n    }))\n  it.effect(\"if - runs `onTrue` if result of `b` is `true`\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        true,\n        Effect.if({\n          onTrue: () => Effect.succeed(true),\n          onFalse: () => Effect.succeed(false)\n        })\n      )\n      assertTrue(result)\n    }))\n  it.effect(\"if - runs `onFalse` if result of `b` is `false`\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.succeed(false),\n        Effect.if({\n          onFalse: () => Effect.succeed(true),\n          onTrue: () => Effect.succeed(false)\n        })\n      )\n      assertTrue(result)\n    }))\n  describe(\"\", () => {\n    it.effect(\"tapErrorCause - effectually peeks at the cause of the failure of this effect\", () =>\n      Effect.gen(function*() {\n        const ref = yield* (Ref.make(false))\n        const result = yield* (\n          pipe(Effect.dieMessage(\"die\"), Effect.tapErrorCause(() => Ref.set(ref, true)), Effect.exit)\n        )\n        const effect = yield* (Ref.get(ref))\n        assertTrue(Exit.isFailure(result) && Option.isSome(Cause.dieOption(result.effect_instruction_i0)))\n        assertTrue(effect)\n      }))\n  })\n  it.effect(\"tapDefect - effectually peeks at defects\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const result = yield* pipe(\n        Effect.dieMessage(\"die\"),\n        Effect.tapDefect(() => Ref.set(ref, true)),\n        Effect.exit\n      )\n      const effect = yield* (Ref.get(ref))\n      assertTrue(Exit.isFailure(result) && Option.isSome(Cause.dieOption(result.effect_instruction_i0)))\n      assertTrue(effect)\n    }))\n  it.effect(\"tapDefect - leaves failures\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const result = yield* pipe(\n        Effect.fail(\"fail\"),\n        Effect.tapDefect(() => Ref.set(ref, true)),\n        Effect.exit\n      )\n      const effect = yield* (Ref.get(ref))\n      deepStrictEqual(result, Exit.fail(\"fail\"))\n      assertFalse(effect)\n    }))\n  it.effect(\"unless - executes correct branch only\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(Ref.set(ref, 1), Effect.unless(constTrue))\n      const v1 = yield* (Ref.get(ref))\n      yield* pipe(Ref.set(ref, 2), Effect.unless(constFalse))\n      const v2 = yield* (Ref.get(ref))\n      const failure = new Error(\"expected\")\n      yield* pipe(Effect.fail(failure), Effect.unless(constTrue))\n      const failed = yield* pipe(Effect.fail(failure), Effect.unless(constFalse), Effect.either)\n      strictEqual(v1, 0)\n      strictEqual(v2, 2)\n      assertLeft(failed, failure)\n    }))\n  it.effect(\"unlessEffect - executes condition effect and correct branch\", () =>\n    Effect.gen(function*() {\n      const effectRef = yield* (Ref.make(0))\n      const conditionRef = yield* (Ref.make(0))\n      const conditionTrue = pipe(Ref.update(conditionRef, (n) => n + 1), Effect.as(true))\n      const conditionFalse = pipe(Ref.update(conditionRef, (n) => n + 1), Effect.as(false))\n      yield* pipe(Ref.set(effectRef, 1), Effect.unlessEffect(conditionTrue))\n      const v1 = yield* (Ref.get(effectRef))\n      const c1 = yield* (Ref.get(conditionRef))\n      yield* pipe(Ref.set(effectRef, 2), Effect.unlessEffect(conditionFalse))\n      const v2 = yield* (Ref.get(effectRef))\n      const c2 = yield* (Ref.get(conditionRef))\n      const failure = new Error(\"expected\")\n      yield* pipe(Effect.fail(failure), Effect.unlessEffect(conditionTrue))\n      const failed = yield* pipe(Effect.fail(failure), Effect.unlessEffect(conditionFalse), Effect.either)\n      strictEqual(v1, 0)\n      strictEqual(c1, 1)\n      strictEqual(v2, 2)\n      strictEqual(c2, 2)\n      assertLeft(failed, failure)\n    }))\n  it.effect(\"when - executes correct branch only\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(Ref.set(ref, 1), Effect.when(constFalse))\n      const v1 = yield* (Ref.get(ref))\n      yield* pipe(Ref.set(ref, 2), Effect.when(constTrue))\n      const v2 = yield* (Ref.get(ref))\n      const failure = new Error(\"expected\")\n      yield* pipe(Effect.fail(failure), Effect.when(constFalse))\n      const failed = yield* pipe(Effect.fail(failure), Effect.when(constTrue), Effect.either)\n      strictEqual(v1, 0)\n      strictEqual(v2, 2)\n      assertLeft(failed, failure)\n    }))\n  it.effect(\"whenEffect - executes condition effect and correct branch\", () =>\n    Effect.gen(function*() {\n      const effectRef = yield* (Ref.make(0))\n      const conditionRef = yield* (Ref.make(0))\n      const conditionTrue = pipe(Ref.update(conditionRef, (n) => n + 1), Effect.as(true))\n      const conditionFalse = pipe(Ref.update(conditionRef, (n) => n + 1), Effect.as(false))\n      yield* pipe(Ref.set(effectRef, 1), Effect.whenEffect(conditionFalse))\n      const v1 = yield* (Ref.get(effectRef))\n      const c1 = yield* (Ref.get(conditionRef))\n      yield* pipe(Ref.set(effectRef, 2), Effect.whenEffect(conditionTrue))\n      const v2 = yield* (Ref.get(effectRef))\n      const c2 = yield* (Ref.get(conditionRef))\n      const failure = new Error(\"expected\")\n      yield* pipe(Effect.fail(failure), Effect.whenEffect(conditionFalse))\n      const failed = yield* pipe(Effect.fail(failure), Effect.whenEffect(conditionTrue), Effect.either)\n      strictEqual(v1, 0)\n      strictEqual(c1, 1)\n      strictEqual(v2, 2)\n      strictEqual(c2, 2)\n      assertLeft(failed, failure)\n    }))\n  it.effect(\"zip/parallel - combines results\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.succeed(1),\n        Effect.zip(Effect.succeed(2), { concurrent: true }),\n        Effect.flatMap((tuple) => Effect.succeed(tuple[0] + tuple[1])),\n        Effect.map((n) => n === 3)\n      )\n      assertTrue(result)\n    }))\n  it.effect(\"zip/parallel - does not swallow exit causes of loser\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          Effect.interrupt,\n          Effect.zip(Effect.interrupt, { concurrent: true }),\n          Effect.exit,\n          Effect.map((exit) =>\n            pipe(Exit.causeOption(exit), Option.map(Cause.interruptors), Option.getOrElse(() => HashSet.empty()))\n          )\n        )\n      )\n      assertTrue(HashSet.size(result) > 0)\n    }))\n  it.effect(\"zip/parallel - does not report failure when interrupting loser after it succeeded\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          Effect.interrupt,\n          Effect.zip(Effect.succeed(1), { concurrent: true }),\n          Effect.sandbox,\n          Effect.either,\n          Effect.map(Either.mapLeft(Cause.isInterrupted))\n        )\n      )\n      assertLeft(result, true)\n    }))\n  it.effect(\"zip/parallel - paralellizes simple success values\", () =>\n    Effect.gen(function*() {\n      const countdown = (n: number): Effect.Effect<number> => {\n        return n === 0\n          ? Effect.succeed(0)\n          : pipe(\n            Effect.succeed(1),\n            Effect.zip(Effect.succeed(2), { concurrent: true }),\n            Effect.flatMap((tuple) => pipe(countdown(n - 1), Effect.map((y) => tuple[0] + tuple[1] + y)))\n          )\n      }\n      const result = yield* (countdown(50))\n      strictEqual(result, 150)\n    }))\n  it.effect(\"zip/parallel - does not kill fiber when forked on parent scope\", () =>\n    Effect.gen(function*() {\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const latch3 = yield* (Deferred.make<void>())\n      const ref = yield* (Ref.make(false))\n      const left = Effect.uninterruptibleMask((restore) =>\n        pipe(\n          Deferred.succeed(latch2, void 0),\n          Effect.zipRight(restore(pipe(Deferred.await(latch1), Effect.zipRight(Effect.succeed(\"foo\"))))),\n          Effect.onInterrupt(() => Ref.set(ref, true))\n        )\n      )\n      const right = pipe(Deferred.succeed(latch3, void 0), Effect.as(42))\n      yield* pipe(\n        Deferred.await(latch2),\n        Effect.zipRight(Deferred.await(latch3)),\n        Effect.zipRight(Deferred.succeed(latch1, void 0)),\n        Effect.fork\n      )\n\n      const result = yield* pipe(Effect.fork(left), Effect.zip(right, { concurrent: true }))\n      const leftInnerFiber = result[0]\n      const rightResult = result[1]\n      const leftResult = yield* (Fiber.await(leftInnerFiber))\n      const interrupted = yield* (Ref.get(ref))\n      assertFalse(interrupted)\n      deepStrictEqual(leftResult, Exit.succeed(\"foo\"))\n      strictEqual(rightResult, 42)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/service.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInstanceOf, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Cause } from \"effect\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { flow, pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Scope from \"effect/Scope\"\n\nclass Prefix extends Effect.Service<Prefix>()(\"Prefix\", {\n  sync: () => ({\n    prefix: \"PRE\"\n  })\n}) {}\n\nclass Postfix extends Effect.Service<Postfix>()(\"Postfix\", {\n  sync: () => ({\n    postfix: \"POST\"\n  })\n}) {}\n\nconst messages: Array<string> = []\n\nclass Logger extends Effect.Service<Logger>()(\"Logger\", {\n  accessors: true,\n  effect: Effect.gen(function*() {\n    const { prefix } = yield* Prefix\n    const { postfix } = yield* Postfix\n    return {\n      info: (message: string) =>\n        Effect.sync(() => {\n          messages.push(`[${prefix}][${message}][${postfix}]`)\n        })\n    }\n  }),\n  dependencies: [Prefix.Default, Postfix.Default]\n}) {\n  static Test = Layer.succeed(this, new Logger({ info: () => Effect.void }))\n}\n\nclass Scoped extends Effect.Service<Scoped>()(\"Scoped\", {\n  accessors: true,\n  scoped: Effect.gen(function*() {\n    const { prefix } = yield* Prefix\n    const { postfix } = yield* Postfix\n    yield* Scope.Scope\n    return {\n      info: (message: string) =>\n        Effect.sync(() => {\n          messages.push(`[${prefix}][${message}][${postfix}]`)\n        })\n    }\n  }),\n  dependencies: [Prefix.Default, Postfix.Default]\n}) {}\n\ndescribe(\"Effect.Service\", () => {\n  it(\"make is a function\", () => {\n    assertTrue(pipe({ prefix: \"OK\" }, Prefix.make) instanceof Prefix)\n  })\n  it(\"tags is a tag and default is a layer\", () => {\n    assertTrue(Layer.isLayer(Logger.Default))\n    assertTrue(Layer.isLayer(Logger.DefaultWithoutDependencies))\n    assertTrue(Context.isTag(Logger))\n  })\n\n  it.effect(\"correctly wires dependencies\", () =>\n    Effect.gen(function*() {\n      yield* Logger.info(\"Ok\")\n      deepStrictEqual(messages, [\"[PRE][Ok][POST]\"])\n      const { prefix } = yield* Prefix\n      strictEqual(prefix, \"PRE\")\n      const { postfix } = yield* Postfix\n      strictEqual(postfix, \"POST\")\n      strictEqual(yield* Prefix.use((_) => _._tag), \"Prefix\")\n    }).pipe(\n      Effect.provide([\n        Logger.Default,\n        Prefix.Default,\n        Postfix.Default\n      ])\n    ))\n\n  it.effect(\"inherits prototype\", () => {\n    class Time extends Effect.Service<Time>()(\"Time\", {\n      sync: () => ({}),\n      accessors: true\n    }) {\n      #now: Date | undefined\n      get now() {\n        return this.#now ||= new Date()\n      }\n    }\n    return Effect.gen(function*() {\n      const time = yield* Time.use((_) => _.now)\n      assertInstanceOf(time, Date)\n    }).pipe(Effect.provide(Time.Default))\n  })\n\n  it.effect(\"support values with prototype\", () => {\n    class DateTest {\n      #now: Date | undefined\n      get now() {\n        return this.#now ||= new Date()\n      }\n    }\n    class Time extends Effect.Service<Time>()(\"Time\", {\n      sync: () => new DateTest(),\n      accessors: true\n    }) {\n      get now2() {\n        return this.now\n      }\n    }\n    return Effect.gen(function*() {\n      const time = yield* Time.use((_) => _.now)\n      const time2 = yield* Time.use((_) => _.now2)\n      strictEqual(time, time2)\n    }).pipe(Effect.provide(Time.Default))\n  })\n\n  it.effect(\"prototype chain\", () => {\n    class TimeLive {\n      #now: Date | undefined\n      constructor(now?: Date) {\n        this.#now = now\n      }\n      get now() {\n        return this.#now ||= new Date()\n      }\n    }\n\n    class Time extends Effect.Service<Time>()(\"Time\", {\n      effect: Effect.sync(() => new TimeLive()),\n      accessors: true\n    }) {}\n\n    return Effect.gen(function*() {\n      const time = yield* Time\n      const date = yield* Time.use((_) => _.now)\n      assertInstanceOf(date, Date)\n      assertInstanceOf(time, Time)\n      assertInstanceOf(time, TimeLive)\n    }).pipe(Effect.provide(Time.Default))\n  })\n\n  it.effect(\"js primitive\", () =>\n    Effect.gen(function*() {\n      class MapThing extends Effect.Service<MapThing>()(\"MapThing\", {\n        sync: () => new Map<string, number>(),\n        accessors: true\n      }) {}\n\n      const map = yield* MapThing.use((_) => _.set(\"a\", 1)).pipe(\n        Effect.provide(MapThing.Default)\n      )\n\n      assertInstanceOf(map, MapThing)\n      assertInstanceOf(map, Map)\n\n      const map2 = yield* MapThing.set(\"a\", 1).pipe(\n        Effect.provide(MapThing.Default)\n      )\n\n      assertInstanceOf(map2, MapThing)\n      assertInstanceOf(map2, Map)\n    }))\n\n  it.effect(\"scoped\", () =>\n    Effect.gen(function*() {\n      yield* Scoped.info(\"Ok\").pipe(Effect.provide(Scoped.Default))\n    }))\n\n  it.effect(\"promises\", () =>\n    Effect.gen(function*() {\n      class Service extends Effect.Service<Service>()(\"Service\", {\n        succeed: {\n          foo: () => Promise.reject(new Error(\"foo\")),\n          bar: () => Promise.resolve(\"bar\")\n        },\n        accessors: true\n      }) {}\n\n      const withUse = yield* Service.use((_) => _.foo()).pipe(Effect.flip, Effect.provide(Service.Default))\n      deepStrictEqual(\n        withUse,\n        new Cause.UnknownException(new Error(\"foo\"), \"An unknown error occurred in Effect.andThen\")\n      )\n\n      const accessor = yield* Service.foo().pipe(Effect.flip, Effect.provide(Service.Default))\n      deepStrictEqual(\n        accessor,\n        new Cause.UnknownException(new Error(\"foo\"), \"An unknown error occurred in Effect.andThen\")\n      )\n\n      const accessorSuccess = yield* Service.bar().pipe(Effect.provide(Service.Default))\n      strictEqual(accessorSuccess, \"bar\")\n    }))\n\n  it.effect(\"scoped with arguments\", () =>\n    Effect.gen(function*() {\n      class Service extends Effect.Service<Service>()(\"Service\", {\n        accessors: true,\n        scoped: Effect.fnUntraced(function*(x: number) {\n          return { x }\n        })\n      }) {}\n\n      const x = yield* Service.x.pipe(Effect.provide(Service.Default(42)))\n      strictEqual(x, 42)\n      const x2 = yield* Service.x.pipe(Effect.provide(Service.Default(43)))\n      strictEqual(x2, 43)\n    }))\n\n  it.effect(\"scoped with arguments & deps\", () =>\n    Effect.gen(function*() {\n      class Service extends Effect.Service<Service>()(\"Service\", {\n        accessors: true,\n        dependencies: [Prefix.Default],\n        scoped: Effect.fnUntraced(function*(x: number) {\n          return { x }\n        })\n      }) {}\n\n      const x = yield* Service.x.pipe(Effect.provide(Service.Default(42)))\n      strictEqual(x, 42)\n      const x2 = yield* Service.x.pipe(Effect.provide(Service.DefaultWithoutDependencies(42)))\n      strictEqual(x2, 42)\n      const x3 = yield* Service.x.pipe(Effect.provide(Service.Default(43)))\n      strictEqual(x3, 43)\n    }))\n\n  it.effect(\"works with flow\", () =>\n    Effect.gen(function*() {\n      class Inc extends Effect.Service<Inc>()(\"Inc\", {\n        accessors: true,\n        effect: Effect.gen(function*() {\n          return { inc: (x: number) => Effect.succeed(x + 1) }\n        })\n      }) {}\n\n      const x = flow(Inc.inc, Effect.map((n) => n + 2))\n\n      strictEqual(yield* x(2).pipe(Effect.provide(Inc.Default)), 5)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/stack-safety.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport { constVoid, identity, pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\n\nconst deepMapEffect = (n: number): Effect.Effect<number> => {\n  const loop = (n: number, acc: Effect.Effect<number>): Effect.Effect<number> => {\n    if (n <= 0) {\n      return acc\n    }\n    return Effect.suspend(() => loop(n - 1, pipe(acc, Effect.map((n) => n + 1))))\n  }\n  return loop(n, Effect.succeed(0))\n}\n\ndescribe(\"Effect\", () => {\n  it.effect(\"deep map of sync effect\", () =>\n    Effect.gen(function*() {\n      const result = yield* (deepMapEffect(10000))\n      strictEqual(result, 10000)\n    }))\n  it.effect(\"deep attempt\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 10000 }, (_, i) => i)\n      const result = yield* (array.reduce(\n        (acc, _) => pipe(Effect.orDie(acc), Effect.either, Effect.asVoid),\n        Effect.orDie(Effect.try(constVoid))\n      ))\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"deep flatMap\", () =>\n    Effect.gen(function*() {\n      const fib = (\n        n: number,\n        a: BigInt = BigInt(\"0\"),\n        b: BigInt = BigInt(\"1\")\n      ): Effect.Effect<BigInt, Error> => {\n        return pipe(\n          Effect.sync(() => ((a as any) + (b as any)) as BigInt),\n          Effect.flatMap((b2) => n > 0 ? fib(n - 1, b, b2) : Effect.succeed(b2))\n        )\n      }\n      const result = yield* (fib(1000))\n      const expected = BigInt(\n        \"113796925398360272257523782552224175572745930353730513145086634176691092536145985470146129334641866902783673042322088625863396052888690096969577173696370562180400527049497109023054114771394568040040412172632376\"\n      )\n      deepStrictEqual(result, expected)\n    }))\n  it.effect(\"deep absolve/attempt is identity\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 100 }, (_, i) => i)\n      const result = yield* (\n        array.reduce((acc, _) => Effect.flatMap(Effect.either(acc), identity), Effect.succeed(42))\n      )\n      strictEqual(result, 42)\n    }))\n  it.effect(\"deep async absolve/attempt is identity\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 1000 }, (_, i) => i)\n      const result = yield* (array.reduce(\n        (acc, _) => Effect.flatMap(Effect.either(acc), identity),\n        Effect.async<unknown, unknown, never>((cb) => {\n          cb(Effect.succeed(42))\n        })\n      ))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"deep effects\", () =>\n    Effect.gen(function*() {\n      const incLeft = (n: number, ref: Ref.Ref<number>): Effect.Effect<number> => {\n        if (n <= 0) {\n          return Ref.get(ref)\n        }\n        return pipe(incLeft(n - 1, ref), Effect.zipLeft(Ref.update(ref, (n) => n + 1)))\n      }\n      const incRight = (n: number, ref: Ref.Ref<number>): Effect.Effect<number> => {\n        if (n <= 0) {\n          return Ref.get(ref)\n        }\n        return pipe(Ref.update(ref, (n) => n + 1), Effect.zipRight(incRight(n - 1, ref)))\n      }\n      const left = pipe(Ref.make(0), Effect.flatMap((ref) => incLeft(100, ref)), Effect.map((n) => n === 0))\n      const right = pipe(Ref.make(0), Effect.flatMap((ref) => incRight(1000, ref)), Effect.map((n) => n === 1000))\n      const result = yield* pipe(left, Effect.zipWith(right, (a, b) => a && b))\n      assertTrue(result)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/structural.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertNone, assertRight, assertSome, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\n\ndescribe(\"Effect\", () => {\n  describe(\"all\", () => {\n    it.effect(\"should work with one array argument\", () =>\n      Effect.gen(function*() {\n        const res = yield* (Effect.all([Effect.succeed(0), Effect.succeed(1)]))\n        deepStrictEqual(res, [0, 1])\n      }))\n    it.effect(\"should work with one empty array argument\", () =>\n      Effect.gen(function*() {\n        const x = yield* (Effect.all([]))\n        deepStrictEqual(x, [])\n      }))\n    it.effect(\"should work with an array argument\", () =>\n      Effect.gen(function*() {\n        const y = Effect.all([0, 1, 2].map((n) => Effect.succeed(n + 1)))\n        const x = yield* y\n        deepStrictEqual(x, [1, 2, 3])\n      }))\n    it.effect(\"should work with one record argument\", () =>\n      Effect.gen(function*() {\n        const result = yield* (Effect.all({ a: Effect.succeed(0), b: Effect.succeed(1) }))\n        const { a, b } = result\n        deepStrictEqual(a, 0)\n        deepStrictEqual(b, 1)\n      }))\n    it.effect(\"should work with one iterable argument\", () =>\n      Effect.gen(function*() {\n        const result = yield* (Effect.all(new Set([Effect.succeed(0), Effect.succeed(1)])))\n        deepStrictEqual(result, [0, 1])\n      }))\n    it.effect(\"should work with one empty record\", () =>\n      Effect.gen(function*() {\n        const x = yield* (Effect.all({}))\n        deepStrictEqual(x, {})\n      }))\n  })\n  describe(\"all/ concurrency\", () => {\n    it.effect(\"should work with one array argument\", () =>\n      Effect.gen(function*() {\n        const res = yield* (Effect.all([Effect.succeed(0), Effect.succeed(1)], {\n          concurrency: \"unbounded\"\n        }))\n        deepStrictEqual(res, [0, 1])\n      }))\n    it.effect(\"should work with one empty array argument\", () =>\n      Effect.gen(function*() {\n        const x = yield* (Effect.all([], {\n          concurrency: \"unbounded\"\n        }))\n        deepStrictEqual(x, [])\n      }))\n    it.effect(\"should work with one record argument\", () =>\n      Effect.gen(function*() {\n        const result = yield* (Effect.all({ a: Effect.succeed(0), b: Effect.succeed(1) }, {\n          concurrency: \"unbounded\"\n        }))\n        const { a, b } = result\n        deepStrictEqual(a, 0)\n        deepStrictEqual(b, 1)\n      }))\n    it.effect(\"should work with one empty record\", () =>\n      Effect.gen(function*() {\n        const x = yield* (Effect.all({}, { concurrency: \"unbounded\" }))\n        deepStrictEqual(x, {})\n      }))\n  })\n  describe(\"all/ validate mode\", () => {\n    it.effect(\"should work with one array argument\", () =>\n      Effect.gen(function*() {\n        const res = yield* (Effect.all([Effect.succeed(0), Effect.succeed(1)], { mode: \"validate\" }))\n        deepStrictEqual(res, [0, 1])\n      }))\n    it.effect(\"failure should work with one array argument\", () =>\n      Effect.gen(function*() {\n        const res = yield* (Effect.flip(Effect.all([Effect.fail(0), Effect.succeed(1)], { mode: \"validate\" })))\n        deepStrictEqual(res, [Option.some(0), Option.none()])\n      }))\n    it.effect(\"should work with one record argument\", () =>\n      Effect.gen(function*() {\n        const result = yield* (Effect.all({ a: Effect.succeed(0), b: Effect.succeed(1) }, { mode: \"validate\" }))\n        const { a, b } = result\n        deepStrictEqual(a, 0)\n        deepStrictEqual(b, 1)\n      }))\n    it.effect(\"failure should work with one record argument\", () =>\n      Effect.gen(function*() {\n        const result = yield* (\n          Effect.flip(Effect.all({ a: Effect.fail(0), b: Effect.succeed(1) }, { mode: \"validate\" }))\n        )\n        const { a, b } = result\n        assertSome(a, 0)\n        assertNone(b)\n      }))\n    it.effect(\"should work with one iterable argument\", () =>\n      Effect.gen(function*() {\n        const result = yield* (Effect.all(new Set([Effect.succeed(0), Effect.succeed(1)]), { mode: \"validate\" }))\n        deepStrictEqual(result, [0, 1])\n      }))\n  })\n  describe(\"all/ either mode\", () => {\n    it.effect(\"should work with one array argument\", () =>\n      Effect.gen(function*() {\n        const res = yield* (Effect.all([Effect.succeed(0), Effect.succeed(1)], { mode: \"either\" }))\n        deepStrictEqual(res, [Either.right(0), Either.right(1)])\n      }))\n    it.effect(\"failure should work with one array argument\", () =>\n      Effect.gen(function*() {\n        const res = yield* (Effect.all([Effect.fail(0), Effect.succeed(1)], { mode: \"either\" }))\n        deepStrictEqual(res, [Either.left(0), Either.right(1)])\n      }))\n    it.effect(\"should work with one record argument\", () =>\n      Effect.gen(function*() {\n        const result = yield* (Effect.all({ a: Effect.succeed(0), b: Effect.succeed(1) }, { mode: \"either\" }))\n        const { a, b } = result\n        assertRight(a, 0)\n        assertRight(b, 1)\n      }))\n    it.effect(\"failure should work with one record argument\", () =>\n      Effect.gen(function*() {\n        const result = yield* (\n          Effect.all({ a: Effect.fail(0), b: Effect.succeed(1) }, { mode: \"either\" })\n        )\n        const { a, b } = result\n        assertLeft(a, 0)\n        assertRight(b, 1)\n      }))\n    it.effect(\"should work with one iterable argument\", () =>\n      Effect.gen(function*() {\n        const result = yield* (Effect.all(new Set([Effect.succeed(0), Effect.succeed(1)]), { mode: \"either\" }))\n        deepStrictEqual(result, [Either.right(0), Either.right(1)])\n      }))\n  })\n  describe(\"allWith\", () => {\n    it.effect(\"should work with one array argument\", () =>\n      Effect.gen(function*() {\n        const res = yield* pipe(\n          [Effect.succeed(0), Effect.succeed(1)] as const,\n          Effect.allWith()\n        )\n        deepStrictEqual(res, [0, 1])\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/sync.test.ts",
    "content": "import { describe, expect, it } from \"@effect/vitest\"\nimport { assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\n\nconst sum = (n: number): number => {\n  if (n < 0) {\n    return 0\n  }\n  return n + sum(n - 1)\n}\n\ndescribe(\"Effect\", () => {\n  it(\"runSyncExit with async is a defect with stack\", () => {\n    const exit = Effect.runSyncExit(\n      Effect.promise(() => Promise.resolve(0)).pipe(Effect.withSpan(\"asyncSpan\"))\n    )\n    if (Exit.isFailure(exit)) {\n      expect(Cause.pretty(exit.cause)).toContain(\"asyncSpan\")\n    } else {\n      expect(exit._tag).toBe(\"Failure\")\n    }\n  })\n  it(\"sync - effect subtype fastPath with NoSuchElementException\", () => {\n    const exit = Effect.runSyncExit(Option.none())\n    deepStrictEqual(exit, Exit.fail(new Cause.NoSuchElementException()))\n  })\n  it.effect(\"sync - effect\", () =>\n    Effect.gen(function*() {\n      const sumEffect = (n: number): Effect.Effect<number, unknown> => {\n        if (n < 0) {\n          return Effect.sync(() => 0)\n        }\n        return pipe(Effect.sync(() => n), Effect.flatMap((b) => pipe(sumEffect(n - 1), Effect.map((a) => a + b))))\n      }\n      const result = yield* (sumEffect(1000))\n      strictEqual(result, sum(1000))\n    }))\n  it(\"sync - must be lazy\", async () => {\n    let program\n    try {\n      program = Effect.sync(() => {\n        throw new Error(\"shouldn't happen!\")\n      })\n      program = Effect.succeed(true)\n    } catch {\n      program = Effect.succeed(false)\n    }\n    const result = await Effect.runPromise(program)\n    assertTrue(result)\n  })\n  it(\"suspend - must be lazy\", async () => {\n    let program\n    try {\n      program = Effect.suspend(() => {\n        throw new Error(\"shouldn't happen!\")\n      })\n      program = Effect.succeed(true)\n    } catch {\n      program = Effect.succeed(false)\n    }\n    const result = await Effect.runPromise(program)\n    assertTrue(result)\n  })\n  it.effect(\"suspend - must catch throwable\", () =>\n    Effect.gen(function*() {\n      const error = new Error(\"woops\")\n      const result = yield* pipe(\n        Effect.suspend<never, never, never>(() => {\n          throw error\n        }),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n  it.effect(\"suspendSucceed - must be evaluatable\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.suspend(() => Effect.succeed(42)))\n      strictEqual(result, 42)\n    }))\n  it.effect(\"suspendSucceed - must not catch throwable\", () =>\n    Effect.gen(function*() {\n      const error = new Error(\"woops\")\n      const result = yield* pipe(\n        Effect.suspend<never, never, never>(() => {\n          throw error\n        }),\n        Effect.sandbox,\n        Effect.either\n      )\n      assertLeft(result, Cause.die(error))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/tapping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\n\nclass TestError1 {\n  readonly _tag = \"TestError1\"\n  constructor() {}\n}\n\nclass TestError2 {\n  readonly _tag = \"TestError2\"\n  constructor() {}\n}\n\ndescribe(\"Effect\", () => {\n  it(\"tapErrorTag\", async () => {\n    let val = 0\n\n    await pipe(\n      Effect.fail<TestError1 | TestError2>(new TestError2()),\n      Effect.tapErrorTag(\"TestError1\", () => Effect.sync(() => val += 1)), // not called\n      Effect.tapErrorTag(\"TestError2\", () => Effect.sync(() => val += 1)), // called\n      Effect.catchAll(() => Effect.succeed(\"\")),\n      Effect.runPromise\n    )\n\n    strictEqual(val, 1)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/timeout.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { constFalse, pipe } from \"effect/Function\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"timeout produces a useful error message\", () =>\n    Effect.gen(function*() {\n      const duration = Duration.millis(1500)\n      const fiber = yield* Effect.never.pipe(\n        Effect.timeout(duration),\n        Effect.flip,\n        Effect.fork\n      )\n      yield* TestClock.adjust(Duration.millis(2000))\n      const result = yield* Fiber.join(fiber)\n      assertTrue(\n        result.toString().includes(\n          \"TimeoutException: Operation timed out after '1s 500ms'\"\n        )\n      )\n    }))\n  it.live(\"timeout a long computation\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          Effect.sleep(Duration.seconds(5)),\n          Effect.zipRight(Effect.succeed(true)),\n          Effect.timeoutFail({\n            onTimeout: constFalse,\n            duration: Duration.millis(10)\n          }),\n          Effect.exit\n        )\n      )\n      deepStrictEqual(result, Exit.fail(false))\n    }))\n  it.live(\"timeout a long computation with a cause\", () =>\n    Effect.gen(function*() {\n      const cause = Cause.die(new Error(\"boom\"))\n      const result = yield* (\n        pipe(\n          Effect.sleep(Duration.seconds(5)),\n          Effect.zipRight(Effect.succeed(true)),\n          Effect.timeoutFailCause({\n            onTimeout: () => cause,\n            duration: Duration.millis(10)\n          }),\n          Effect.sandbox,\n          Effect.flip\n        )\n      )\n      deepStrictEqual(result, cause)\n    }))\n  it.live(\"timeout repetition of uninterruptible effect\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(Effect.void, Effect.uninterruptible, Effect.forever, Effect.timeout(Duration.millis(10)), Effect.option)\n      )\n      assertNone(result)\n    }))\n  it.effect(\"timeout in uninterruptible region\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.void, Effect.timeout(Duration.seconds(20)), Effect.uninterruptible)\n      deepStrictEqual(result, void 0)\n    }))\n  it.effect(\"timeout - disconnect - returns with the produced value if the effect completes before the timeout elapses\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.void, Effect.disconnect, Effect.timeout(Duration.millis(100)))\n      deepStrictEqual(result, void 0)\n    }))\n  it.effect(\"timeout - disconnect - returns `NoSuchElementException` otherwise\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* (\n        pipe(\n          Effect.never,\n          Effect.uninterruptible,\n          Effect.disconnect,\n          Effect.timeout(Duration.millis(100)),\n          Effect.option,\n          Effect.fork\n        )\n      )\n      yield* (TestClock.adjust(Duration.millis(100)))\n      const result = yield* (Fiber.join(fiber))\n      assertNone(result)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/traversing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { constVoid, identity, pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"dropWhile - happy path\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          [1, 2, 3, 4, 5],\n          Effect.dropWhile((n) => Effect.succeed(n % 2 === 1))\n        )\n      )\n      deepStrictEqual(result, [2, 3, 4, 5])\n    }))\n  it.effect(\"dropWhile - error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [1, 1, 1],\n        Effect.dropWhile(() => Effect.fail(\"Ouch\")),\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n  it.effect(\"exists - determines whether any element satisfies the effectual predicate\", () =>\n    Effect.gen(function*() {\n      const array = [1, 2, 3, 4, 5]\n      const result1 = yield* pipe(array, Effect.exists((n) => Effect.succeed(n > 3)))\n      const result2 = yield* pipe(\n        array,\n        Effect.exists((n) => Effect.succeed(n > 5), {\n          concurrency: \"unbounded\"\n        })\n      )\n      assertTrue(result1)\n      assertFalse(result2)\n    }))\n  it.effect(\"forAll - determines whether all elements satisfy the effectual predicate\", () =>\n    Effect.gen(function*() {\n      const array = [1, 2, 3, 4, 5, 6]\n      const result1 = yield* pipe(array, Effect.every((n) => Effect.succeed(n > 3)))\n      const result2 = yield* pipe(array, Effect.every((n) => Effect.succeed(n > 0)))\n      assertFalse(result1)\n      assertTrue(result2)\n    }))\n  it.effect(\"iterate - iterates with the specified effectual function\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.iterate(100, {\n        while: (n) => n > 0,\n        body: (n) => Effect.succeed(n - 1)\n      }))\n      strictEqual(result, 0)\n    }))\n  it.effect(\"loop - loops with the specified effectual function\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Array.empty<number>()))\n      yield* (\n        Effect.loop(0, {\n          while: (n) => n < 5,\n          step: (n) => n + 1,\n          body: (n) => Ref.update(ref, Array.append(n))\n        })\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(result, [0, 1, 2, 3, 4])\n    }))\n  it.effect(\"loop/discard - loops with the specified effectual function\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Array.empty<number>()))\n      yield* (Effect.loop(0, {\n        while: (n) => n < 5,\n        step: (n) => n + 1,\n        body: (n) => Ref.update(ref, Array.append(n)),\n        discard: true\n      }))\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(result, [0, 1, 2, 3, 4])\n    }))\n  it.effect(\"replicate - zero\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.all(pipe(Effect.succeed(12), Effect.replicate(0))))\n      strictEqual(result.length, 0)\n    }))\n  it.effect(\"replicate - negative\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.all(pipe(Effect.succeed(12), Effect.replicate(-2))))\n      strictEqual(result.length, 0)\n    }))\n  it.effect(\"replicate - positive\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.all(pipe(Effect.succeed(12), Effect.replicate(2))))\n      deepStrictEqual(result, [12, 12])\n    }))\n  it.effect(\" - returns the list of results\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([1, 2, 3, 4, 5, 6], Effect.forEach((n) => Effect.succeed(n + 1)))\n      deepStrictEqual(result, [2, 3, 4, 5, 6, 7])\n    }))\n  it.effect(\"forEach - both evaluates effects and returns results in the same order\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<string>()))\n      const result = yield* pipe(\n        Chunk.make(\"1\", \"2\", \"3\"),\n        Effect.forEach((s) =>\n          pipe(\n            Ref.update(ref, Chunk.prepend(s)),\n            Effect.zipRight(Effect.sync(() => Number.parseInt(s)))\n          )\n        )\n      )\n      const effects = yield* pipe(Ref.get(ref), Effect.map(Chunk.reverse))\n      deepStrictEqual(Chunk.toReadonlyArray(effects), [\"1\", \"2\", \"3\"])\n      deepStrictEqual(result, [1, 2, 3])\n    }))\n  it.effect(\"forEach - fails if one of the effects fails\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [\"1\", \"h\", \"3\"],\n        Effect.forEach((s) =>\n          Effect.sync(() => {\n            const n = Number.parseInt(s)\n            if (Number.isNaN(n)) {\n              throw new Cause.IllegalArgumentException()\n            }\n            return n\n          })\n        ),\n        Effect.exit\n      )\n\n      deepStrictEqual(result, Exit.die(new Cause.IllegalArgumentException()))\n    }))\n  it.effect(\"forEach/discard - runs effects in order\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Array.empty<number>()))\n      yield* pipe([1, 2, 3, 4, 5], Effect.forEach((n) => Ref.update(ref, Array.append(n)), { discard: true }))\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(result, [1, 2, 3, 4, 5])\n    }))\n  it.effect(\"forEach/discard - can be run twice\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const effect = pipe([1, 2, 3, 4, 5], Effect.forEach((n) => Ref.update(ref, (_) => _ + n), { discard: true }))\n      yield* effect\n      yield* effect\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 30)\n    }))\n  it.effect(\"forEach/concurrency - runs single task\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([2], Effect.forEach((n) => Effect.succeed(n * 2), { concurrency: \"unbounded\" }))\n      deepStrictEqual(result, [4])\n    }))\n  it.effect(\"forEach/concurrency - runs two tasks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([2, 3], Effect.forEach((n) => Effect.succeed(n * 2), { concurrency: \"unbounded\" }))\n      deepStrictEqual(result, [4, 6])\n    }))\n  it.effect(\"forEach/concurrency - runs many tasks\", () =>\n    Effect.gen(function*() {\n      const array = Array.makeBy(100, (i) => i + 1)\n      const result = yield* pipe(array, Effect.forEach((n) => Effect.succeed(n * 2), { concurrency: \"unbounded\" }))\n      deepStrictEqual(result, array.map((n) => n * 2))\n    }))\n  it.effect(\"forEach/concurrency - runs a task that fails\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Array.makeBy(10, (i) => i + 1),\n        Effect.forEach((n) => n === 5 ? Effect.fail(\"boom\") : Effect.succeed(n * 2), { concurrency: \"unbounded\" }),\n        Effect.flip\n      )\n      strictEqual(result, \"boom\")\n    }))\n  it.effect(\"forEach/concurrency - runs two failed tasks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Array.makeBy(10, (i) => i + 1),\n        Effect.forEach((n) =>\n          n === 5\n            ? Effect.fail(\"boom1\")\n            : n === 8\n            ? Effect.fail(\"boom2\")\n            : Effect.succeed(n * 2), { concurrency: \"unbounded\" }),\n        Effect.flip\n      )\n      assertTrue(result === \"boom1\" || result === \"boom2\")\n    }))\n  it.effect(\"forEach/concurrency - runs a task that dies\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Array.makeBy(10, (i) => i + 1),\n        Effect.forEach((n) => n === 5 ? Effect.dieMessage(\"boom\") : Effect.succeed(n * 2), {\n          concurrency: \"unbounded\"\n        }),\n        Effect.exit\n      )\n      assertTrue(Exit.isFailure(result) && Cause.isDie(result.effect_instruction_i0))\n    }))\n  it.effect(\"forEach/concurrency - runs a task that is interrupted\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Array.makeBy(10, (i) => i + 1),\n        Effect.forEach((n) => n === 5 ? Effect.interrupt : Effect.succeed(n * 2), { concurrency: \"unbounded\" }),\n        Effect.exit\n      )\n      assertTrue(Exit.isInterrupted(result))\n    }))\n  it.effect(\"forEach/concurrency - runs a task that throws an unsuspended exception\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [1],\n        Effect.forEach((n) =>\n          Effect.sync(() => {\n            throw new Error(n.toString())\n          }), { concurrency: \"unbounded\" }),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(new Error(\"1\")))\n    }))\n  it.effect(\"forEach/concurrency - returns results in the same order\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [\"1\", \"2\", \"3\"],\n        Effect.forEach((s) => Effect.sync(() => Number.parseInt(s)), { concurrency: \"unbounded\" })\n      )\n      deepStrictEqual(result, [1, 2, 3])\n    }))\n  it.effect(\"forEach/concurrency - runs effects in parallel\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<void>())\n      yield* (\n        pipe(\n          [Effect.never, Deferred.succeed(deferred, void 0)],\n          Effect.forEach(identity, { concurrency: \"unbounded\" }),\n          Effect.fork\n        )\n      )\n      const result = yield* (Deferred.await(deferred))\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"forEach/concurrency - propagates error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [1, 2, 3, 4, 5, 6],\n        Effect.forEach((n) => n % 2 !== 0 ? Effect.succeed(n) : Effect.fail(\"not odd\"), { concurrency: \"unbounded\" }),\n        Effect.flip\n      )\n      strictEqual(result, \"not odd\")\n    }))\n  it.effect(\"forEach/concurrency - interrupts effects on first failure\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const deferred = yield* (Deferred.make<void>())\n      const actions = [\n        Effect.never,\n        Effect.succeed(1),\n        Effect.fail(\"C\"),\n        pipe(Deferred.await(deferred), Effect.zipRight(Ref.set(ref, true)), Effect.as(1))\n      ]\n      const error = yield* pipe(actions, Effect.forEach(identity, { concurrency: \"unbounded\" }), Effect.flip)\n      const value = yield* (Ref.get(ref))\n      strictEqual(error, \"C\")\n      assertFalse(value)\n    }))\n  it.effect(\"forEach/concurrency - does not kill fiber when forked on the parent scope\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const fibers = yield* pipe(\n        Array.makeBy(100, (i) => i + 1),\n        Effect.forEach(() => pipe(Ref.update(ref, (_) => _ + 1), Effect.fork), { concurrency: \"unbounded\" })\n      )\n      yield* pipe(fibers, Effect.forEach(Fiber.await))\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 100)\n    }))\n  it.effect(\"forEach/concurrency - parallelism - returns the results in the appropriate order\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          [1, 2, 3],\n          Effect.forEach((n) => Effect.succeed(n.toString()), { concurrency: 2 })\n        )\n      )\n      deepStrictEqual(result, [\"1\", \"2\", \"3\"])\n    }))\n  it.effect(\"forEach/concurrency - parallelism - works on large lists\", () =>\n    Effect.gen(function*() {\n      const parallelism = 10\n      const array = Array.makeBy(100000, (i) => i)\n      const result = yield* (\n        pipe(\n          array,\n          Effect.forEach((n) => Effect.succeed(n), { concurrency: parallelism })\n        )\n      )\n      deepStrictEqual(result, array)\n    }))\n  it.effect(\"forEach/concurrency - parallelism - runs effects in parallel\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<void>())\n      yield* (\n        pipe(\n          [Effect.never, Deferred.succeed(deferred, void 0)],\n          Effect.forEach(identity, { concurrency: 2 }),\n          Effect.fork\n        )\n      )\n      const result = yield* (Deferred.await(deferred))\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"forEach/concurrency - parallelism - propagates error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [1, 2, 3, 4, 5, 6],\n        Effect.forEach((n) => n % 2 !== 0 ? Effect.succeed(n) : Effect.fail(\"not odd\"), { concurrency: 4 }),\n        Effect.either\n      )\n      assertLeft(result, \"not odd\")\n    }))\n  it.effect(\"forEach/concurrency - parallelism - interrupts effects on first failure\", () =>\n    Effect.gen(function*() {\n      const actions = [\n        Effect.never,\n        Effect.succeed(1),\n        Effect.fail(\"C\")\n      ]\n      const result = yield* pipe(\n        actions,\n        Effect.forEach(identity, { concurrency: 4 }),\n        Effect.either\n      )\n      assertLeft(result, \"C\")\n    }))\n  it.effect(\"forEach/concurrency+discard - accumulates errors\", () =>\n    Effect.gen(function*() {\n      const task = (\n        started: Ref.Ref<number>,\n        trigger: Deferred.Deferred<void, never>,\n        n: number\n      ): Effect.Effect<void, number> => {\n        return pipe(\n          Ref.updateAndGet(started, (n) => n + 1),\n          Effect.flatMap((count) =>\n            pipe(\n              Deferred.succeed(trigger, void 0),\n              Effect.when(() => count === 3),\n              Effect.zipRight(Deferred.await(trigger)),\n              Effect.zipRight(Effect.fail(n))\n            )\n          )\n        )\n      }\n      const started = yield* (Ref.make(0))\n      const trigger = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        [1, 2, 3],\n        Effect.forEach((n) => pipe(task(started, trigger, n), Effect.uninterruptible), {\n          concurrency: \"unbounded\",\n          discard: true\n        }),\n        Effect.matchCause({\n          onFailure: Cause.failures,\n          onSuccess: () => Chunk.empty<number>()\n        })\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2, 3])\n    }))\n  it.effect(\"forEach/concurrency+discard - runs all effects\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      yield* pipe(\n        [1, 2, 3, 4, 5],\n        Effect.forEach((n) => Ref.update(ref, Chunk.prepend(n)), {\n          concurrency: \"unbounded\",\n          discard: true\n        })\n      )\n      const result = yield* pipe(Ref.get(ref), Effect.map(Chunk.reverse))\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2, 3, 4, 5])\n    }))\n  it.effect(\"forEach/concurrency+discard - completes on empty input\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [],\n        Effect.forEach(() => Effect.void, {\n          concurrency: \"unbounded\",\n          discard: true\n        })\n      )\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"forEach/concurrency+discard - parallelism - runs all effects\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      yield* pipe(\n        [1, 2, 3, 4, 5],\n        Effect.forEach((n) => Ref.update(ref, Chunk.prepend(n)), {\n          concurrency: 2,\n          discard: true\n        })\n      )\n      const result = yield* pipe(Ref.get(ref), Effect.map(Chunk.reverse))\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2, 3, 4, 5])\n    }))\n  it.effect(\"merge - on flipped result\", () =>\n    Effect.gen(function*() {\n      const effect: Effect.Effect<number, number> = Effect.succeed(1)\n      const a = yield* (Effect.merge(effect))\n      const b = yield* (Effect.merge(Effect.flip(effect)))\n      strictEqual(a, b)\n    }))\n  it.effect(\"mergeAll - return zero element on empty input\", () =>\n    Effect.gen(function*() {\n      const zeroElement = 42\n      const nonZero = 43\n      const result = yield* (\n        pipe([] as ReadonlyArray<Effect.Effect<unknown>>, Effect.mergeAll(zeroElement, () => nonZero))\n      )\n      strictEqual(result, zeroElement)\n    }))\n  it.effect(\"mergeAll - merge list using function\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([3, 5, 7].map(Effect.succeed), Effect.mergeAll(1, (b, a) => b + a))\n      strictEqual(result, 1 + 3 + 5 + 7)\n    }))\n  it.effect(\"mergeAll - should work when Z is an interable\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [3, 5, 7].map(Effect.succeed),\n        Effect.mergeAll([] as Array<number>, (b, a) => [...b, a])\n      )\n      deepStrictEqual(result, [3, 5, 7])\n    }))\n  it.effect(\"mergeAll - should work when Z is a function\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([3, 5, 7].map(Effect.succeed), Effect.mergeAll(() => 1, (_b, a) => () => a))\n      deepStrictEqual(result(), 7)\n    }))\n  it.effect(\"mergeAll - return error if it exists in list\", () =>\n    Effect.gen(function*() {\n      const effects: ReadonlyArray<Effect.Effect<void, number>> = [Effect.void, Effect.fail(1)]\n      const result = yield* pipe(effects, Effect.mergeAll(void 0 as void, constVoid), Effect.exit)\n      deepStrictEqual(result, Exit.fail(1))\n    }))\n  it.effect(\"mergeAll/concurrency - return zero element on empty input\", () =>\n    Effect.gen(function*() {\n      const zeroElement = 42\n      const nonZero = 43\n      const result = yield* (\n        pipe(\n          [] as ReadonlyArray<Effect.Effect<unknown>>,\n          Effect.mergeAll(zeroElement, () => nonZero, {\n            concurrency: \"unbounded\"\n          })\n        )\n      )\n      strictEqual(result, zeroElement)\n    }))\n  it.effect(\"mergeAll/concurrency - merge list using function\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [3, 5, 7].map(Effect.succeed),\n        Effect.mergeAll(1, (b, a) => b + a, {\n          concurrency: \"unbounded\"\n        })\n      )\n      strictEqual(result, 1 + 3 + 5 + 7)\n    }))\n  it.effect(\"mergeAll/concurrency - return error if it exists in list\", () =>\n    Effect.gen(function*() {\n      const effects: ReadonlyArray<Effect.Effect<void, number>> = [Effect.void, Effect.fail(1)]\n      const result = yield* pipe(\n        effects,\n        Effect.mergeAll(void 0 as void, constVoid, {\n          concurrency: \"unbounded\"\n        }),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.failCause(Cause.fail(1)))\n    }))\n  it.effect(\"partition - collects only successes\", () =>\n    Effect.gen(function*() {\n      const array = Array.makeBy(10, (i) => i)\n      const [left, right] = yield* pipe(array, Effect.partition(Effect.succeed))\n      deepStrictEqual(left, [])\n      deepStrictEqual(right, array)\n    }))\n  it.effect(\"partition - collects only failures\", () =>\n    Effect.gen(function*() {\n      const array = Array.makeBy(10, () => 0)\n      const [left, right] = yield* pipe(array, Effect.partition(Effect.fail))\n      deepStrictEqual(left, array)\n      deepStrictEqual(right, [])\n    }))\n  it.effect(\"partition - collects failures and successes\", () =>\n    Effect.gen(function*() {\n      const array = Array.makeBy(10, (i) => i)\n      const [left, right] = yield* (\n        pipe(array, Effect.partition((n) => n % 2 === 0 ? Effect.fail(n) : Effect.succeed(n)))\n      )\n      deepStrictEqual(left, [0, 2, 4, 6, 8])\n      deepStrictEqual(right, [1, 3, 5, 7, 9])\n    }))\n  it.effect(\"partition - evaluates effects in correct order\", () =>\n    Effect.gen(function*() {\n      const array = [2, 4, 6, 3, 5, 6]\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      yield* pipe(array, Effect.partition((n) => Ref.update(ref, Chunk.prepend(n))))\n      const result = yield* pipe(Ref.get(ref), Effect.map(Chunk.reverse))\n      deepStrictEqual(Chunk.toReadonlyArray(result), [2, 4, 6, 3, 5, 6])\n    }))\n  it.effect(\"partition/concurrency - collects successes\", () =>\n    Effect.gen(function*() {\n      const array = Array.makeBy(1000, (i) => i)\n      const [left, right] = yield* pipe(\n        array,\n        Effect.partition(Effect.succeed, {\n          concurrency: \"unbounded\"\n        })\n      )\n      deepStrictEqual(left, [])\n      deepStrictEqual(right, array)\n    }))\n  it.effect(\"partition/concurrency - collects failures\", () =>\n    Effect.gen(function*() {\n      const array = Array.makeBy(10, () => 0)\n      const [left, right] = yield* pipe(\n        array,\n        Effect.partition(Effect.fail, {\n          concurrency: \"unbounded\"\n        })\n      )\n      deepStrictEqual(left, array)\n      deepStrictEqual(right, [])\n    }))\n  it.effect(\"partition/concurrency - collects failures and successes\", () =>\n    Effect.gen(function*() {\n      const array = Array.makeBy(10, (i) => i)\n      const [left, right] = yield* (\n        pipe(\n          array,\n          Effect.partition((n) => n % 2 === 0 ? Effect.fail(n) : Effect.succeed(n), {\n            concurrency: \"unbounded\"\n          })\n        )\n      )\n      deepStrictEqual(left, [0, 2, 4, 6, 8])\n      deepStrictEqual(right, [1, 3, 5, 7, 9])\n    }))\n  it.effect(\"partition/concurrency - parallelism - collects successes\", () =>\n    Effect.gen(function*() {\n      const array = Array.makeBy(1000, (i) => i)\n      const [left, right] = yield* pipe(\n        array,\n        Effect.partition(Effect.succeed, {\n          concurrency: 3\n        })\n      )\n      deepStrictEqual(left, [])\n      deepStrictEqual(right, array)\n    }))\n  it.effect(\"partition/concurrency - parallelism - collects failures\", () =>\n    Effect.gen(function*() {\n      const array = Array.makeBy(10, () => 0)\n      const [left, right] = yield* pipe(\n        array,\n        Effect.partition(Effect.fail, { concurrency: 3 })\n      )\n      deepStrictEqual(left, array)\n      deepStrictEqual(right, [])\n    }))\n  it.effect(\"partition/concurrency - parallelism - collects failures and successes\", () =>\n    Effect.gen(function*() {\n      const array = Array.makeBy(10, (i) => i)\n      const [left, right] = yield* pipe(\n        array,\n        Effect.partition((n) => n % 2 === 0 ? Effect.fail(n) : Effect.succeed(n), {\n          concurrency: 3\n        })\n      )\n      deepStrictEqual(left, [0, 2, 4, 6, 8])\n      deepStrictEqual(right, [1, 3, 5, 7, 9])\n    }))\n  it.effect(\"reduce - with a successful step function sums the list properly\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([1, 2, 3, 4, 5], Effect.reduce(0, (acc, curr) => Effect.succeed(acc + curr)))\n      strictEqual(result, 15)\n    }))\n  it.effect(\"reduce - with a failing step function returns a failed IO\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([1, 2, 3, 4, 5], Effect.reduce(0, () => Effect.fail(\"fail\")), Effect.exit)\n      deepStrictEqual(result, Exit.fail(\"fail\"))\n    }))\n  it.effect(\"reduce - run sequentially from left to right\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe([1, 2, 3, 4, 5], Effect.reduce([] as ReadonlyArray<number>, (acc, curr) => Effect.succeed([...acc, curr])))\n      )\n      deepStrictEqual(result, [1, 2, 3, 4, 5])\n    }))\n  it.effect(\"reduceRight - with a successful step function sums the list properly\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([1, 2, 3, 4, 5], Effect.reduceRight(0, (acc, curr) => Effect.succeed(acc + curr)))\n      strictEqual(result, 15)\n    }))\n  it.effect(\"reduceRight - with a failing step function returns a failed IO\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([1, 2, 3, 4, 5], Effect.reduceRight(0, () => Effect.fail(\"fail\")), Effect.exit)\n      deepStrictEqual(result, Exit.fail(\"fail\"))\n    }))\n  it.effect(\"reduceRight - run sequentially from right to left\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [1, 2, 3, 4, 5],\n        Effect.reduceRight([] as ReadonlyArray<number>, (curr, acc) => Effect.succeed([curr, ...acc]))\n      )\n      deepStrictEqual(result, [1, 2, 3, 4, 5])\n    }))\n  it.effect(\"reduceEffect/concurrency - return zero element on empty input\", () =>\n    Effect.gen(function*() {\n      const zeroElement = 42\n      const nonZero = 43\n      const result = yield* (\n        pipe(\n          [] as ReadonlyArray<Effect.Effect<number>>,\n          Effect.reduceEffect(Effect.succeed(zeroElement), () => nonZero, {\n            concurrency: \"unbounded\"\n          })\n        )\n      )\n      strictEqual(result, zeroElement)\n    }))\n  it.effect(\"reduceEffect/concurrency - reduce list using function\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        [3, 5, 7].map(Effect.succeed),\n        Effect.reduceEffect(Effect.succeed(1), (acc, a) => acc + a, {\n          concurrency: \"unbounded\"\n        })\n      )\n      strictEqual(result, 1 + 3 + 5 + 7)\n    }))\n  it.effect(\"reduceEffect/concurrency - return error if zero is an error\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          [Effect.void, Effect.void],\n          Effect.reduceEffect(Effect.fail(1), constVoid, {\n            concurrency: \"unbounded\"\n          }),\n          Effect.exit\n        )\n      )\n      deepStrictEqual(result, Exit.failCause(Cause.fail(1)))\n    }))\n  it.effect(\"reduceEffect/concurrency - return error if it exists in list\", () =>\n    Effect.gen(function*() {\n      const effects: ReadonlyArray<Effect.Effect<void, number>> = [Effect.void, Effect.fail(1)]\n      const result = yield* (\n        pipe(\n          effects,\n          Effect.reduceEffect(Effect.void as Effect.Effect<void, number>, constVoid, {\n            concurrency: \"unbounded\"\n          }),\n          Effect.exit\n        )\n      )\n      deepStrictEqual(result, Exit.failCause(Cause.fail(1)))\n    }))\n  it.effect(\"takeUntil - happy path\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        Effect.takeUntil(\n          [1, 2, 3, 4, 5],\n          (n) => Effect.succeed(n >= 3)\n        )\n      )\n      deepStrictEqual(result, [1, 2, 3])\n    }))\n  it.effect(\"takeUntil - error\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          [1, 1, 1],\n          Effect.takeUntil(() => Effect.fail(\"Ouch\")),\n          Effect.either\n        )\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n  it.effect(\"takeWhile - happy path\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          [1, 2, 3, 4, 5],\n          Effect.takeWhile((n) => Effect.succeed(n % 2 === 1))\n        )\n      )\n      deepStrictEqual(result, [1])\n    }))\n  it.effect(\"takeWhile - error\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          [1, 1, 1],\n          Effect.takeWhile(() => Effect.fail(\"Ouch\")),\n          Effect.either\n        )\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/tryPromise.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertSuccess, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Cause, Effect, Option } from \"effect\"\n\ndescribe(\"Effect\", () => {\n  it(\"tryPromise - success, no catch, no AbortSignal\", async () => {\n    const effect = Effect.tryPromise<number>(() =>\n      new Promise((resolve) => {\n        setTimeout(() => {\n          resolve(1)\n        }, 100)\n      })\n    )\n    const n = await Effect.runPromise(effect)\n    strictEqual(n, 1)\n  })\n\n  it(\"tryPromise - failure, no catch, no AbortSignal\", async () => {\n    const effect = Effect.tryPromise<void>(() =>\n      new Promise((_resolve, reject) => {\n        setTimeout(() => {\n          reject(\"error\")\n        }, 100)\n      })\n    )\n    const either = await Effect.runPromise(Effect.either(effect))\n    assertLeft(either, new Cause.UnknownException(\"error\", \"An unknown error occurred in Effect.tryPromise\"))\n  })\n\n  it(\"tryPromise - failure, catch, no AbortSignal\", async () => {\n    const effect = Effect.tryPromise({\n      try: () =>\n        new Promise((_resolve, reject) => {\n          setTimeout(() => {\n            reject(\"error\")\n          }, 100)\n        }),\n      catch: (error) => new Error(String(error))\n    })\n    const either = await Effect.runPromise(Effect.either(effect))\n    assertLeft(either, new Error(\"error\"))\n  })\n\n  it(\"tryPromise - success, no catch, AbortSignal\", async () => {\n    let aborted = false\n    const effect = Effect.tryPromise<void>((signal) => {\n      signal.addEventListener(\"abort\", () => {\n        aborted = true\n      }, { once: true })\n      return new Promise((resolve) => {\n        setTimeout(() => {\n          resolve()\n        }, 100)\n      })\n    })\n    const program = effect.pipe(\n      Effect.timeout(\"10 millis\"),\n      Effect.asSome,\n      Effect.catchTag(\"TimeoutException\", () => Effect.succeedNone)\n    )\n    const exit = await Effect.runPromiseExit(program)\n    assertSuccess(exit, Option.none())\n    assertTrue(aborted)\n  })\n\n  it(\"tryPromise - success, catch, AbortSignal\", async () => {\n    let aborted = false\n    const effect = Effect.tryPromise<void, Error>({\n      try: (signal) => {\n        signal.addEventListener(\"abort\", () => {\n          aborted = true\n        }, { once: true })\n        return new Promise((resolve) => {\n          setTimeout(() => {\n            resolve()\n          }, 100)\n        })\n      },\n      catch: () => new Error()\n    })\n    const program = effect.pipe(\n      Effect.timeout(\"10 millis\"),\n      Effect.asSome,\n      Effect.catchTag(\"TimeoutException\", () => Effect.succeedNone)\n    )\n    const exit = await Effect.runPromiseExit(program)\n    assertSuccess(exit, Option.none())\n    assertTrue(aborted)\n  })\n\n  it.effect(\"tryPromise - defects in catch\", () =>\n    Effect.gen(function*() {\n      const cause = yield* Effect.tryPromise({\n        try: () => Promise.reject(\"error\"),\n        catch: (error) => {\n          throw new Error(String(error))\n        }\n      }).pipe(\n        Effect.sandbox,\n        Effect.flip\n      )\n      deepStrictEqual(cause, Cause.die(new Error(\"error\")))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Effect/validation.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\n\ndescribe(\"Effect\", () => {\n  it.effect(\"validate - fails\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          Effect.succeed(1),\n          Effect.validate(Effect.fail(2)),\n          Effect.sandbox,\n          Effect.either\n        )\n      )\n      assertLeft(result, Cause.fail(2))\n    }))\n  it.effect(\"validate - combines both cause\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        pipe(\n          Effect.fail(1),\n          Effect.validate(Effect.fail(2)),\n          Effect.sandbox,\n          Effect.either\n        )\n      )\n      deepStrictEqual(result, Either.left(Cause.sequential(Cause.fail(1), Cause.fail(2))))\n    }))\n  it.effect(\"validateWith - succeeds\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Effect.succeed(1), Effect.validateWith(Effect.succeed(2), (a, b) => a + b))\n      strictEqual(result, 3)\n    }))\n  it.effect(\"validateAll - accumulate successes\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 10 }, (_, i) => i)\n      const result = yield* pipe(array, Effect.validateAll(Effect.succeed))\n      deepStrictEqual(Array.from(result), array)\n    }))\n  it.effect(\"validateAll - returns all errors if never valid\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 10 }, () => 0)\n      const result = yield* pipe(array, Effect.validateAll(Effect.fail), Effect.flip)\n      deepStrictEqual(Array.from(result), array)\n    }))\n  it.effect(\"validateAll - accumulate errors and ignore successes\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 10 }, (_, i) => i)\n      const result = yield* (\n        pipe(array, Effect.validateAll((n) => n % 2 === 0 ? Effect.succeed(n) : Effect.fail(n)), Effect.flip)\n      )\n      deepStrictEqual(Array.from(result), [1, 3, 5, 7, 9])\n    }))\n  it.effect(\"validateAll/discard - returns all errors if never valid\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 10 }, () => 0)\n      const result = yield* pipe(array, Effect.validateAll(Effect.fail, { discard: true }), Effect.flip)\n      deepStrictEqual(Array.from(result), array)\n    }))\n  it.effect(\"validateAll/concurrency - returns all errors if never valid\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 1000 }, () => 0)\n      const result = yield* pipe(array, Effect.validateAll(Effect.fail, { concurrency: \"unbounded\" }), Effect.flip)\n      deepStrictEqual(Array.from(result), array)\n    }))\n  it.effect(\"validateAll/concurrency - accumulate errors and ignore successes\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 10 }, (_, i) => i)\n      const result = yield* (\n        pipe(\n          array,\n          Effect.validateAll((n) => n % 2 === 0 ? Effect.succeed(n) : Effect.fail(n), {\n            concurrency: \"unbounded\"\n          }),\n          Effect.flip\n        )\n      )\n      deepStrictEqual(Array.from(result), [1, 3, 5, 7, 9])\n    }))\n  it.effect(\"validateAll/concurrency - accumulate successes\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 10 }, (_, i) => i)\n      const result = yield* pipe(array, Effect.validateAll(Effect.succeed, { concurrency: \"unbounded\" }))\n      deepStrictEqual(Array.from(result), array)\n    }))\n  it.effect(\"validateAll/concurrency+discard - returns all errors if never valid\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 10 }, () => 0)\n      const result = yield* pipe(\n        array,\n        Effect.validateAll(Effect.fail, {\n          concurrency: \"unbounded\",\n          discard: true\n        }),\n        Effect.flip\n      )\n      deepStrictEqual(Array.from(result), array)\n    }))\n  it.effect(\"validateFirst - returns all errors if never valid\", () =>\n    Effect.gen(function*() {\n      const array = Array.from({ length: 10 }, () => 0)\n      const result = yield* pipe(array, Effect.validateFirst(Effect.fail), Effect.flip)\n      deepStrictEqual(Array.from(result), array)\n    }))\n  it.effect(\"validateFirst - returns [] as error if the input is empty\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([], Effect.validateFirst(Effect.succeed), Effect.flip)\n      deepStrictEqual(result, [])\n    }))\n  it.effect(\"validateFirst - runs sequentially and short circuits on first success validation\", () =>\n    Effect.gen(function*() {\n      const f = (n: number): Effect.Effect<number, number> => {\n        return n === 6 ? Effect.succeed(n) : Effect.fail(n)\n      }\n      const array = Array.from({ length: 10 }, (_, i) => i + 1)\n      const counter = yield* (Ref.make<number>(0))\n      const result = yield* (\n        pipe(\n          array,\n          Effect.validateFirst((n) =>\n            pipe(\n              Ref.update(counter, (n) => n + 1),\n              Effect.zipRight(f(n))\n            )\n          )\n        )\n      )\n      const count = yield* (Ref.get(counter))\n      strictEqual(result, 6)\n      strictEqual(count, 6)\n    }))\n  it.effect(\"validateFirst - returns errors in correct order\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe([2, 4, 6, 3, 5, 6], Effect.validateFirst(Effect.fail), Effect.flip)\n      deepStrictEqual(Array.from(result), [2, 4, 6, 3, 5, 6])\n    }))\n  describe(\"\", () => {\n    it.effect(\"validateFirst/concurrency - returns all errors if never valid\", () =>\n      Effect.gen(function*() {\n        const array = Array.from({ length: 1000 }, () => 0)\n        const result = yield* pipe(array, Effect.validateFirst(Effect.fail, { concurrency: \"unbounded\" }), Effect.flip)\n        deepStrictEqual(Array.from(result), array)\n      }))\n    it.effect(\"validateFirst/concurrency - returns success if valid\", () =>\n      Effect.gen(function*() {\n        const f = (n: number): Effect.Effect<number, number> => {\n          return n === 6 ? Effect.succeed(n) : Effect.fail(n)\n        }\n        const array = Array.from({ length: 10 }, (_, i) => i + 1)\n        const result = yield* pipe(array, Effect.validateFirst(f, { concurrency: \"unbounded\" }))\n        strictEqual(result, 6)\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Either.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertLeft,\n  assertNone,\n  assertRight,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { Chunk, Either, flow, Number as Num, Option, pipe, String as Str } from \"effect\"\n\ndescribe(\"Either\", () => {\n  it(\"void\", () => {\n    deepStrictEqual(Either.void, Either.right(undefined))\n  })\n\n  it(\"gen\", () => {\n    const a = Either.gen(function*() {\n      const x = yield* Either.right(1)\n      const y = yield* Either.right(2)\n      return x + y\n    })\n    const b = Either.gen(function*() {\n      return 10\n    })\n    const c = Either.gen(function*() {\n      yield* Either.right(1)\n      yield* Either.right(2)\n    })\n    const d = Either.gen(function*() {\n      yield* Either.right(1)\n      return yield* Either.right(2)\n    })\n    const e = Either.gen(function*() {\n      yield* Either.right(1)\n      yield* Either.left(\"err\")\n      return yield* Either.right(2)\n    })\n    const f = Either.gen(function*() {\n      yield* Either.left(\"err\")\n    })\n    const g = Either.gen({ context: \"testContext\" as const }, function*() {\n      return yield* Either.right(this.context)\n    })\n    // TODO(4.0) remove this test\n    // test adapter\n    const h = Either.gen(function*($) {\n      const x = yield* $(Either.right(1))\n      const y = yield* $(Either.right(2))\n      return x + y\n    })\n\n    assertRight(a, 3)\n    assertRight(b, 10)\n    assertRight(c, undefined)\n    assertRight(d, 2)\n    assertLeft(e, \"err\")\n    assertLeft(f, \"err\")\n    assertRight(g, \"testContext\")\n    assertRight(h, 3)\n  })\n\n  it(\"toString\", () => {\n    strictEqual(\n      String(Either.right(1)),\n      `{\n  \"_id\": \"Either\",\n  \"_tag\": \"Right\",\n  \"right\": 1\n}`\n    )\n    strictEqual(\n      String(Either.left(\"e\")),\n      `{\n  \"_id\": \"Either\",\n  \"_tag\": \"Left\",\n  \"left\": \"e\"\n}`\n    )\n    strictEqual(\n      String(Either.right(Chunk.make(1, 2, 3))),\n      `{\n  \"_id\": \"Either\",\n  \"_tag\": \"Right\",\n  \"right\": {\n    \"_id\": \"Chunk\",\n    \"values\": [\n      1,\n      2,\n      3\n    ]\n  }\n}`\n    )\n    strictEqual(\n      String(Either.left(Chunk.make(1, 2, 3))),\n      `{\n  \"_id\": \"Either\",\n  \"_tag\": \"Left\",\n  \"left\": {\n    \"_id\": \"Chunk\",\n    \"values\": [\n      1,\n      2,\n      3\n    ]\n  }\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    deepStrictEqual(Either.right(1).toJSON(), { _id: \"Either\", _tag: \"Right\", right: 1 })\n    deepStrictEqual(Either.left(\"e\").toJSON(), { _id: \"Either\", _tag: \"Left\", left: \"e\" })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window === \"undefined\") {\n      // eslint-disable-next-line @typescript-eslint/no-require-imports\n      const { inspect } = require(\"node:util\")\n      deepStrictEqual(inspect(Either.right(1)), inspect({ _id: \"Either\", _tag: \"Right\", right: 1 }))\n      deepStrictEqual(inspect(Either.left(\"e\")), inspect({ _id: \"Either\", _tag: \"Left\", left: \"e\" }))\n    }\n  })\n\n  it(\"isEither\", () => {\n    assertTrue(pipe(Either.right(1), Either.isEither))\n    assertTrue(pipe(Either.left(\"e\"), Either.isEither))\n    assertFalse(pipe(Option.some(1), Either.isEither))\n  })\n\n  it(\"getRight\", () => {\n    assertSome(pipe(Either.right(1), Either.getRight), 1)\n    assertNone(pipe(Either.left(\"a\"), Either.getRight))\n  })\n\n  it(\"getLeft\", () => {\n    assertNone(pipe(Either.right(1), Either.getLeft))\n    assertSome(pipe(Either.left(\"e\"), Either.getLeft), \"e\")\n  })\n\n  it(\"map\", () => {\n    const f = Either.map(Str.length)\n    assertRight(pipe(Either.right(\"abc\"), f), 3)\n    assertLeft(pipe(Either.left(\"s\"), f), \"s\")\n  })\n\n  it(\"mapBoth\", () => {\n    const f = Either.mapBoth({\n      onLeft: Str.length,\n      onRight: (n: number) => n > 2\n    })\n    assertRight(pipe(Either.right(1), f), false)\n    assertLeft(pipe(Either.left(\"a\"), f), 1)\n  })\n\n  it(\"mapLeft\", () => {\n    const f = Either.mapLeft((n: number) => n * 2)\n    assertRight(pipe(Either.right(\"a\"), f), \"a\")\n    assertLeft(pipe(Either.left(1), f), 2)\n  })\n\n  it(\"match\", () => {\n    const onLeft = (s: string) => `left${s.length}`\n    const onRight = (s: string) => `right${s.length}`\n    const match = Either.match({ onLeft, onRight })\n    strictEqual(match(Either.left(\"abc\")), \"left3\")\n    strictEqual(match(Either.right(\"abc\")), \"right3\")\n  })\n\n  it(\"isLeft\", () => {\n    assertFalse(Either.isLeft(Either.right(1)))\n    assertTrue(Either.isLeft(Either.left(1)))\n  })\n\n  it(\"isRight\", () => {\n    assertTrue(Either.isRight(Either.right(1)))\n    assertFalse(Either.isRight(Either.left(1)))\n  })\n\n  it(\"flip\", () => {\n    assertLeft(Either.flip(Either.right(\"a\")), \"a\")\n    assertRight(Either.flip(Either.left(\"b\")), \"b\")\n  })\n\n  it(\"liftPredicate\", () => {\n    const isPositivePredicate = (n: number) => n > 0\n    const onPositivePredicateError = (n: number) => `${n} is not positive`\n    const isNumberRefinement = (n: string | number): n is number => typeof n === \"number\"\n    const onNumberRefinementError = (n: string | number) => `${n} is not a number`\n\n    assertRight(\n      pipe(1, Either.liftPredicate(isPositivePredicate, onPositivePredicateError)),\n      1\n    )\n    assertLeft(\n      pipe(-1, Either.liftPredicate(isPositivePredicate, onPositivePredicateError)),\n      \"-1 is not positive\"\n    )\n    assertRight(\n      pipe(1, Either.liftPredicate(isNumberRefinement, onNumberRefinementError)),\n      1\n    )\n    assertLeft(\n      pipe(\"string\", Either.liftPredicate(isNumberRefinement, onNumberRefinementError)),\n      \"string is not a number\"\n    )\n\n    assertRight(\n      Either.liftPredicate(1, isPositivePredicate, onPositivePredicateError),\n      1\n    )\n    assertLeft(\n      Either.liftPredicate(-1, isPositivePredicate, onPositivePredicateError),\n      \"-1 is not positive\"\n    )\n    assertRight(\n      Either.liftPredicate(1, isNumberRefinement, onNumberRefinementError),\n      1\n    )\n    assertLeft(\n      Either.liftPredicate(\"string\", isNumberRefinement, onNumberRefinementError),\n      \"string is not a number\"\n    )\n  })\n\n  it(\"filterOrLeft\", () => {\n    deepStrictEqual(Either.filterOrLeft(Either.right(1), (n) => n > 0, () => \"a\"), Either.right(1))\n    deepStrictEqual(Either.filterOrLeft(Either.right(1), (n) => n > 1, () => \"a\"), Either.left(\"a\"))\n    deepStrictEqual(Either.filterOrLeft(Either.left(1), (n) => n > 0, () => \"a\"), Either.left(1))\n\n    deepStrictEqual(Either.right(1).pipe(Either.filterOrLeft((n) => n > 0, () => \"a\")), Either.right(1))\n    deepStrictEqual(Either.right(1).pipe(Either.filterOrLeft((n) => n > 1, () => \"a\")), Either.left(\"a\"))\n    deepStrictEqual(Either.left(1).pipe(Either.filterOrLeft((n) => n > 0, () => \"a\")), Either.left(1))\n  })\n\n  it(\"merge\", () => {\n    deepStrictEqual(Either.merge(Either.right(1)), 1)\n    deepStrictEqual(Either.merge(Either.left(\"a\")), \"a\")\n  })\n\n  it(\"getEquivalence\", () => {\n    const isEquivalent = Either.getEquivalence({ right: Num.Equivalence, left: Str.Equivalence })\n    deepStrictEqual(isEquivalent(Either.right(1), Either.right(1)), true)\n    deepStrictEqual(isEquivalent(Either.right(1), Either.right(2)), false)\n    deepStrictEqual(isEquivalent(Either.right(1), Either.left(\"foo\")), false)\n    deepStrictEqual(isEquivalent(Either.left(\"foo\"), Either.left(\"foo\")), true)\n    deepStrictEqual(isEquivalent(Either.left(\"foo\"), Either.left(\"bar\")), false)\n    deepStrictEqual(isEquivalent(Either.left(\"foo\"), Either.right(1)), false)\n  })\n\n  it(\"pipe()\", () => {\n    assertRight(Either.right(1).pipe(Either.map((n) => n + 1)), 2)\n  })\n\n  it(\"fromNullable\", () => {\n    deepStrictEqual(Either.fromNullable(null, () => \"fallback\"), Either.left(\"fallback\"))\n    deepStrictEqual(Either.fromNullable(undefined, () => \"fallback\"), Either.left(\"fallback\"))\n    deepStrictEqual(Either.fromNullable(1, () => \"fallback\"), Either.right(1))\n  })\n\n  it(\"fromOption\", () => {\n    deepStrictEqual(Either.fromOption(Option.none(), () => \"none\"), Either.left(\"none\"))\n    deepStrictEqual(Either.fromOption(Option.some(1), () => \"none\"), Either.right(1))\n  })\n\n  it(\"try\", () => {\n    deepStrictEqual(Either.try(() => 1), Either.right(1))\n    deepStrictEqual(\n      Either.try(() => {\n        throw \"b\"\n      }),\n      Either.left(\"b\")\n    )\n    deepStrictEqual(Either.try({ try: () => 1, catch: (e) => new Error(String(e)) }), Either.right(1))\n    deepStrictEqual(\n      Either.try({\n        try: () => {\n          throw \"b\"\n        },\n        catch: (e) => new Error(String(e))\n      }),\n      Either.left(new Error(\"b\"))\n    )\n  })\n\n  it(\"getOrElse\", () => {\n    strictEqual(Either.getOrElse(Either.right(1), (error) => error + \"!\"), 1)\n    strictEqual(Either.getOrElse(Either.left(\"not a number\"), (error) => error + \"!\"), \"not a number!\")\n  })\n\n  it(\"getOrNull\", () => {\n    strictEqual(Either.getOrNull(Either.right(1)), 1)\n    strictEqual(Either.getOrNull(Either.left(\"a\")), null)\n  })\n\n  it(\"getOrUndefined\", () => {\n    strictEqual(Either.getOrUndefined(Either.right(1)), 1)\n    strictEqual(Either.getOrUndefined(Either.left(\"a\")), undefined)\n  })\n\n  it(\"getOrThrowWith\", () => {\n    strictEqual(pipe(Either.right(1), Either.getOrThrowWith((e) => new Error(`Unexpected Left: ${e}`))), 1)\n    throws(() => pipe(Either.left(\"e\"), Either.getOrThrowWith((e) => new Error(`Unexpected Left: ${e}`))))\n  })\n\n  it(\"getOrThrow\", () => {\n    strictEqual(pipe(Either.right(1), Either.getOrThrow), 1)\n    throws(() => pipe(Either.left(\"e\"), Either.getOrThrow), new Error(\"getOrThrow called on a Left\"))\n  })\n\n  it(\"flatMap\", () => {\n    const f = Either.flatMap(flow(Str.length, Either.right))\n    assertRight(pipe(Either.right(\"abc\"), f), 3)\n    assertLeft(pipe(Either.left(\"maError\"), f), \"maError\")\n  })\n\n  it(\"andThen\", () => {\n    assertRight(pipe(Either.right(1), Either.andThen(() => Either.right(2))), 2)\n    assertRight(pipe(Either.right(1), Either.andThen(Either.right(2))), 2)\n    assertRight(pipe(Either.right(1), Either.andThen(2)), 2)\n    assertRight(pipe(Either.right(1), Either.andThen(() => 2)), 2)\n    assertRight(pipe(Either.right(1), Either.andThen((a) => a)), 1)\n    assertRight(Either.andThen(Either.right(1), () => Either.right(2)), 2)\n    assertRight(Either.andThen(Either.right(1), Either.right(2)), 2)\n    assertRight(Either.andThen(Either.right(1), () => 2), 2)\n    assertRight(Either.andThen(Either.right(1), 2), 2)\n    assertRight(Either.andThen(Either.right(1), (a) => a), 1)\n  })\n\n  it(\"ap\", () => {\n    const add = (a: number) => (b: number) => a + b\n    assertRight(Either.right(add).pipe(Either.ap(Either.right(1)), Either.ap(Either.right(2))), 3)\n    assertLeft(Either.right(add).pipe(Either.ap(Either.left(\"b\")), Either.ap(Either.right(2))), \"b\")\n    assertLeft(Either.right(add).pipe(Either.ap(Either.right(1)), Either.ap(Either.left(\"c\"))), \"c\")\n    assertLeft(Either.right(add).pipe(Either.ap(Either.left(\"b\")), Either.ap(Either.left(\"c\"))), \"b\")\n    assertLeft(\n      (Either.left(\"a\") as Either.Either<typeof add, string>).pipe(\n        Either.ap(Either.right(1)),\n        Either.ap(Either.right(2))\n      ),\n      \"a\"\n    )\n  })\n\n  it(\"zipWith\", () => {\n    assertLeft(pipe(Either.left(0), Either.zipWith(Either.right(2), (a, b) => a + b)), 0)\n    assertLeft(pipe(Either.right(1), Either.zipWith(Either.left(0), (a, b) => a + b)), 0)\n    assertRight(pipe(Either.right(1), Either.zipWith(Either.right(2), (a, b) => a + b)), 3)\n  })\n\n  it(\"all\", () => {\n    // tuples and arrays\n    assertRight(Either.all([]), [])\n    assertRight(Either.all([Either.right(1)]), [1])\n    assertRight(Either.all([Either.right(1), Either.right(true)]), [1, true])\n    assertLeft(Either.all([Either.right(1), Either.left(\"e\")]), \"e\")\n    // structs and records\n    assertRight(Either.all({}), {})\n    assertRight(Either.all({ a: Either.right(1) }), { a: 1 })\n    assertRight(Either.all({ a: Either.right(1), b: Either.right(true) }), { a: 1, b: true })\n    assertLeft(Either.all({ a: Either.right(1), b: Either.left(\"e\") }), \"e\")\n  })\n\n  it(\"orElse\", () => {\n    assertRight(pipe(Either.right(1), Either.orElse(() => Either.right(2))), 1)\n    assertRight(pipe(Either.right(1), Either.orElse(() => Either.left(\"b\"))), 1)\n    assertRight(pipe(Either.left(\"a\"), Either.orElse(() => Either.right(2))), 2)\n    assertLeft(pipe(Either.left(\"a\"), Either.orElse(() => Either.left(\"b\"))), \"b\")\n  })\n\n  describe(\"do notation\", () => {\n    it(\"Do\", () => {\n      assertRight(Either.Do, {})\n    })\n\n    it(\"bindTo\", () => {\n      assertRight(pipe(Either.right(1), Either.bindTo(\"a\")), { a: 1 })\n      assertLeft(pipe(Either.left(\"left\"), Either.bindTo(\"a\")), \"left\")\n      assertRight(\n        pipe(\n          Either.right(1),\n          Either.bindTo(\"__proto__\"),\n          Either.bind(\"a\", () => Either.right(1))\n        ),\n        { a: 1, [\"__proto__\"]: 1 }\n      )\n    })\n\n    it(\"bind\", () => {\n      assertRight(pipe(Either.right(1), Either.bindTo(\"a\"), Either.bind(\"b\", ({ a }) => Either.right(a + 1))), {\n        a: 1,\n        b: 2\n      })\n      assertLeft(\n        pipe(Either.right(1), Either.bindTo(\"a\"), Either.bind(\"b\", () => Either.left(\"left\"))),\n        \"left\"\n      )\n      assertLeft(\n        pipe(Either.left(\"left\"), Either.bindTo(\"a\"), Either.bind(\"b\", () => Either.right(2))),\n        \"left\"\n      )\n      assertRight(\n        pipe(\n          Either.right(1),\n          Either.bindTo(\"a\"),\n          Either.bind(\"__proto__\", ({ a }) => Either.right(a + 1)),\n          Either.bind(\"b\", ({ a }) => Either.right(a + 1))\n        ),\n        { a: 1, b: 2, [\"__proto__\"]: 2 }\n      )\n    })\n\n    it(\"let\", () => {\n      assertRight(pipe(Either.right(1), Either.bindTo(\"a\"), Either.let(\"b\", ({ a }) => a + 1)), { a: 1, b: 2 })\n      assertLeft(\n        pipe(Either.left(\"left\"), Either.bindTo(\"a\"), Either.let(\"b\", () => 2)),\n        \"left\"\n      )\n      assertRight(\n        pipe(\n          Either.right(1),\n          Either.bindTo(\"a\"),\n          Either.let(\"__proto__\", ({ a }) => a + 1),\n          Either.let(\"b\", ({ a }) => a + 1)\n        ),\n        { a: 1, b: 2, [\"__proto__\"]: 2 }\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Encoding.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Either, Encoding } from \"effect\"\n\ndescribe(\"Base64\", () => {\n  const valid: Array<[string, string]> = [\n    [\"\", \"\"],\n    [\"ß\", \"w58=\"],\n    [\"f\", \"Zg==\"],\n    [\"fo\", \"Zm8=\"],\n    [\"foo\", \"Zm9v\"],\n    [\"foob\", \"Zm9vYg==\"],\n    [\"fooba\", \"Zm9vYmE=\"],\n    [\"foobar\", \"Zm9vYmFy\"]\n  ]\n\n  const invalid: Array<string> = [\n    \"ab\\fcd\",\n    \"ab\\t\\n\\f\\r cd\",\n    \" \\t\\n\\f\\r ab\\t\\n\\f\\r cd\\t\\n\\f\\r \",\n    \"a=b\",\n    \"abc=d\",\n    \"a\",\n    \"ab\\t\\n\\f\\r =\\t\\n\\f\\r =\\t\\n\\f\\r \",\n    \"abcde\",\n    \"ab=c\",\n    \"=a\",\n    \"ab\\u00a0cd\",\n    \"A\",\n    \"////A\",\n    \"/\",\n    \"AAAA/\",\n    \"\\0nonsense\",\n    \"abcd\\0nonsense\"\n  ]\n\n  it.each(valid)(`should decode %j <= %j`, (raw: string, b64: string) => {\n    const bytes = new TextEncoder().encode(raw)\n    const decoded = Encoding.decodeBase64(b64)\n    assertTrue(Either.isRight(decoded))\n    deepStrictEqual(decoded.right, bytes)\n  })\n\n  it.each(valid)(`should decode %j <= %j (to string)`, (raw: string, b64: string) => {\n    const decoded = Encoding.decodeBase64String(b64)\n    assertTrue(Either.isRight(decoded))\n    deepStrictEqual(decoded.right, raw)\n  })\n\n  it.each(valid)(`should encode %j => %j`, (raw: string, b64: string) => {\n    strictEqual(Encoding.encodeBase64(raw), b64)\n    strictEqual(Encoding.encodeBase64(new TextEncoder().encode(raw)), b64)\n  })\n\n  it.each(invalid)(`should refuse to decode %j`, (b64: string) => {\n    const result = Encoding.decodeBase64(b64)\n    assertTrue(Either.isLeft(result))\n    assertTrue(Encoding.isDecodeException(result.left))\n  })\n})\n\ndescribe(\"Base64Url\", () => {\n  const valid: Array<[string, string]> = [\n    [\"\", \"\"],\n    [\"ß\", \"w58\"],\n    [\"f\", \"Zg\"],\n    [\"fo\", \"Zm8\"],\n    [\"foo\", \"Zm9v\"],\n    [\"foob\", \"Zm9vYg\"],\n    [\"fooba\", \"Zm9vYmE\"],\n    [\"foobar\", \"Zm9vYmFy\"],\n    [\">?>d?ß\", \"Pj8-ZD_Dnw\"]\n  ]\n\n  const invalid: Array<string> = [\n    \"Pj8/ZD+Dnw\",\n    \"PDw/Pz8+Pg\",\n    \"Pj8/ZD+Dnw==\",\n    \"PDw/Pz8+Pg==\"\n  ]\n\n  it.each(valid)(`should decode %j <= %j`, (raw: string, b64url: string) => {\n    const bytes = new TextEncoder().encode(raw)\n    const decoded = Encoding.decodeBase64Url(b64url)\n    assertTrue(Either.isRight(decoded))\n    deepStrictEqual(decoded.right, bytes)\n  })\n\n  it.each(valid)(`should decode %j <= %j (to string)`, (raw: string, b64: string) => {\n    const decoded = Encoding.decodeBase64UrlString(b64)\n    assertTrue(Either.isRight(decoded))\n    deepStrictEqual(decoded.right, raw)\n  })\n\n  it.each(valid)(`should encode %j => %j`, (raw: string, b64url: string) => {\n    strictEqual(Encoding.encodeBase64Url(raw), b64url)\n    strictEqual(Encoding.encodeBase64Url(new TextEncoder().encode(raw)), b64url)\n  })\n\n  it.each(invalid)(`should refuse to decode %j`, (b64url: string) => {\n    const result = Encoding.decodeBase64Url(b64url)\n    assertTrue(Either.isLeft(result))\n    assertTrue(Encoding.isDecodeException(result.left))\n  })\n})\n\ndescribe(\"Hex\", () => {\n  const valid: Array<[hex: string, bytes: Uint8Array]> = [\n    [\"\", Uint8Array.from([])],\n    [\"0001020304050607\", Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7])],\n    [\"08090a0b0c0d0e0f\", Uint8Array.from([8, 9, 10, 11, 12, 13, 14, 15])],\n    [\"f0f1f2f3f4f5f6f7\", Uint8Array.from([0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7])],\n    [\"f8f9fafbfcfdfeff\", Uint8Array.from([0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff])],\n    [\"67\", new TextEncoder().encode(\"g\")],\n    [\"e3a1\", Uint8Array.from([0xe3, 0xa1])]\n  ]\n\n  const strings: Array<[hex: string, raw: string]> = [\n    [\"\", \"\"],\n    [\"68656c6c6f20776f726c64\", \"hello world\"],\n    [\"666f6f\", \"foo\"],\n    [\"666f6f20626172\", \"foo bar\"],\n    [\"67\", \"g\"]\n  ]\n\n  const invalid: Array<string> = [\n    \"0\",\n    \"zd4aa\",\n    \"d4aaz\",\n    \"30313\",\n    \"0g\",\n    \"00gg\",\n    \"0\\x01\",\n    \"ffeed\"\n  ]\n\n  it.each(valid)(`should decode %j => %o`, (hex: string, bytes: Uint8Array) => {\n    const decoded = Encoding.decodeHex(hex)\n    assertTrue(Either.isRight(decoded))\n    deepStrictEqual(decoded.right, bytes)\n  })\n\n  it.each(strings)(`should decode %j => %j to string`, (hex: string, str: string) => {\n    const decoded = Encoding.decodeHexString(hex)\n    assertTrue(Either.isRight(decoded))\n    deepStrictEqual(decoded.right, str)\n  })\n\n  it.each(valid)(`should encode %j <= %o`, (hex: string, bytes: Uint8Array) => {\n    strictEqual(Encoding.encodeHex(bytes), hex)\n  })\n\n  it.each(strings)(`should encode %j <= %j`, (hex: string, raw: string) => {\n    strictEqual(Encoding.encodeHex(raw), hex)\n  })\n\n  it.each(invalid)(`should refuse to decode %j`, (hex: string) => {\n    const result = Encoding.decodeHex(hex)\n    assertTrue(Either.isLeft(result))\n    assertTrue(Encoding.isDecodeException(result.left))\n  })\n})\n\ndescribe(\"UriComponent\", () => {\n  const valid: Array<[uri: string, raw: string]> = [\n    [\"\", \"\"],\n    [\"hello\", \"hello\"],\n    [\"hello%20world\", \"hello world\"],\n    [\"hello%20world%2F\", \"hello world/\"],\n    [\"%20\", \" \"],\n    [\"%2F\", \"/\"]\n  ]\n\n  const invalidDecode: Array<string> = [\n    \"hello%2world\"\n  ]\n\n  const invalidEncode: Array<string> = [\n    \"\\uD800\",\n    \"\\uDFFF\"\n  ]\n\n  it.each(valid)(`should decode %j => %j`, (uri: string, raw: string) => {\n    const decoded = Encoding.decodeUriComponent(uri)\n    assertTrue(Either.isRight(decoded))\n    deepStrictEqual(decoded.right, raw)\n  })\n\n  it.each(valid)(`should encode %j => %j`, (uri: string, raw: string) => {\n    const encoded = Encoding.encodeUriComponent(raw)\n    assertTrue(Either.isRight(encoded))\n    deepStrictEqual(encoded.right, uri)\n  })\n\n  it.each(invalidDecode)(`should refuse to decode %j`, (uri: string) => {\n    const result = Encoding.decodeUriComponent(uri)\n    assertTrue(Either.isLeft(result))\n    assertTrue(Encoding.isDecodeException(result.left))\n  })\n\n  it.each(invalidEncode)(`should refuse to encode %j`, (raw: string) => {\n    const result = Encoding.encodeUriComponent(raw)\n    assertTrue(Either.isLeft(result))\n    assertTrue(Encoding.isEncodeException(result.left))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Equal.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport { Equal, Utils } from \"effect\"\n\ndescribe(\"Equal\", () => {\n  it(\"invalid Date\", () => {\n    const d1 = new Date(\"invalid\")\n    const d2 = new Date(\"invalid\")\n    assertTrue(Equal.equals(d1, d2))\n  })\n\n  it(\"Date(0) vs invalid Date\", () => {\n    const epoch = new Date(0)\n    const invalid = new Date(\"invalid\")\n    assertFalse(Equal.equals(epoch, invalid))\n  })\n\n  describe(\"structuralRegion\", () => {\n    it(\"null vs null\", () => {\n      Utils.structuralRegion(() => {\n        assertTrue(Equal.equals(null, null))\n      })\n    })\n\n    it(\"null vs object\", () => {\n      Utils.structuralRegion(() => {\n        assertFalse(Equal.equals(null, { a: 1 }))\n      })\n    })\n\n    it(\"object vs null\", () => {\n      Utils.structuralRegion(() => {\n        assertFalse(Equal.equals({ a: 1 }, null))\n      })\n    })\n\n    it(\"null vs string\", () => {\n      Utils.structuralRegion(() => {\n        assertFalse(Equal.equals(null, \"hello\"))\n      })\n    })\n\n    it(\"null vs array\", () => {\n      Utils.structuralRegion(() => {\n        assertFalse(Equal.equals(null, [1, 2, 3]))\n      })\n    })\n\n    it(\"nested object with null values\", () => {\n      const a = { name: \"test\", address: { city: \"NYC\", zip: null } }\n      const b = { name: \"test\", address: { city: \"NYC\", zip: null } }\n      Utils.structuralRegion(() => {\n        assertTrue(Equal.equals(a, b))\n      })\n    })\n\n    it(\"nested object with null vs non-null\", () => {\n      const a = { name: \"test\", value: null }\n      const b = { name: \"test\", value: 42 }\n      Utils.structuralRegion(() => {\n        assertFalse(Equal.equals(a, b))\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Equivalence.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport { Equivalence, pipe } from \"effect\"\n\ndescribe(\"Equivalence\", () => {\n  it(\"array\", () => {\n    const eq = Equivalence.array(Equivalence.number)\n\n    assertTrue(eq([], []))\n    assertTrue(eq([1, 2, 3], [1, 2, 3]))\n    assertFalse(eq([1, 2, 3], [1, 2, 4]))\n    assertFalse(eq([1, 2, 3], [1, 2]))\n  })\n\n  it(\"strict returns an Equivalence that uses strict equality (===) to compare values\", () => {\n    const eq = Equivalence.strict<{ a: number }>()\n    const a = { a: 1 }\n    assertTrue(eq(a, a))\n    assertFalse(eq({ a: 1 }, { a: 1 }))\n  })\n\n  it(\"mapInput\", () => {\n    interface Person {\n      readonly name: string\n      readonly age: number\n    }\n    const eqPerson = pipe(Equivalence.string, Equivalence.mapInput((p: Person) => p.name))\n    assertTrue(eqPerson({ name: \"a\", age: 1 }, { name: \"a\", age: 2 }))\n    assertTrue(eqPerson({ name: \"a\", age: 1 }, { name: \"a\", age: 1 }))\n    assertFalse(eqPerson({ name: \"a\", age: 1 }, { name: \"b\", age: 1 }))\n    assertFalse(eqPerson({ name: \"a\", age: 1 }, { name: \"b\", age: 2 }))\n  })\n\n  it(\"Date\", () => {\n    const eq = Equivalence.Date\n    assertTrue(eq(new Date(0), new Date(0)))\n    assertFalse(eq(new Date(0), new Date(1)))\n    assertFalse(eq(new Date(1), new Date(0)))\n  })\n\n  it(\"product\", () => {\n    const eq = Equivalence.product(Equivalence.string, Equivalence.string)\n    assertTrue(eq([\"a\", \"b\"], [\"a\", \"b\"]))\n    assertFalse(eq([\"a\", \"b\"], [\"c\", \"b\"]))\n    assertFalse(eq([\"a\", \"b\"], [\"a\", \"c\"]))\n  })\n\n  it(\"productMany\", () => {\n    const eq = Equivalence.productMany(Equivalence.string, [Equivalence.string])\n    assertTrue(eq([\"a\", \"b\"], [\"a\", \"b\"]))\n    assertTrue(eq([\"a\", \"b\"], [\"a\", \"b\", \"c\"]))\n    assertTrue(eq([\"a\", \"b\", \"c\"], [\"a\", \"b\"]))\n    assertFalse(eq([\"a\", \"b\"], [\"c\", \"b\"]))\n    assertFalse(eq([\"a\", \"b\"], [\"a\", \"c\"]))\n  })\n\n  it(\"all\", () => {\n    const eq = Equivalence.all([Equivalence.string, Equivalence.string])\n    assertTrue(eq([], []))\n    assertTrue(eq([], [\"a\"]))\n    assertTrue(eq([\"a\"], []))\n    assertTrue(eq([\"a\"], [\"a\"]))\n    assertFalse(eq([\"a\"], [\"b\"]))\n    assertTrue(eq([\"a\"], [\"a\", \"b\"]))\n    assertTrue(eq([\"a\", \"b\"], [\"a\"]))\n    assertTrue(eq([\"a\", \"b\"], [\"a\", \"b\"]))\n    assertFalse(eq([\"a\", \"b\"], [\"a\", \"c\"]))\n  })\n\n  it(\"combine\", () => {\n    type T = readonly [string, number, boolean]\n    const E0: Equivalence.Equivalence<T> = Equivalence.mapInput((x: T) => x[0])(Equivalence.string)\n    const E1: Equivalence.Equivalence<T> = Equivalence.mapInput((x: T) => x[1])(Equivalence.number)\n    const eqE0E1 = Equivalence.combine(E0, E1)\n    assertTrue(eqE0E1([\"a\", 1, true], [\"a\", 1, true]))\n    assertTrue(eqE0E1([\"a\", 1, true], [\"a\", 1, false]))\n    assertFalse(eqE0E1([\"a\", 1, true], [\"b\", 1, true]))\n    assertFalse(eqE0E1([\"a\", 1, true], [\"a\", 2, false]))\n  })\n\n  it(\"combineMany\", () => {\n    type T = readonly [string, number, boolean]\n    const E0: Equivalence.Equivalence<T> = Equivalence.mapInput((x: T) => x[0])(Equivalence.string)\n    const E1: Equivalence.Equivalence<T> = Equivalence.mapInput((x: T) => x[1])(Equivalence.number)\n    const E2: Equivalence.Equivalence<T> = Equivalence.mapInput((x: T) => x[2])(Equivalence.boolean)\n    const eqE0E1E2 = Equivalence.combineMany(E0, [E1, E2])\n    assertTrue(eqE0E1E2([\"a\", 1, true], [\"a\", 1, true]))\n    assertFalse(eqE0E1E2([\"a\", 1, true], [\"b\", 1, true]))\n    assertFalse(eqE0E1E2([\"a\", 1, true], [\"a\", 2, true]))\n    assertFalse(eqE0E1E2([\"a\", 1, true], [\"a\", 1, false]))\n  })\n\n  it(\"combineAll\", () => {\n    type T = readonly [string, number, boolean]\n    const E0: Equivalence.Equivalence<T> = Equivalence.mapInput((x: T) => x[0])(Equivalence.string)\n    const E1: Equivalence.Equivalence<T> = Equivalence.mapInput((x: T) => x[1])(Equivalence.number)\n    const E2: Equivalence.Equivalence<T> = Equivalence.mapInput((x: T) => x[2])(Equivalence.boolean)\n    const eqE0E1E2 = Equivalence.combineAll([E0, E1, E2])\n    assertTrue(eqE0E1E2([\"a\", 1, true], [\"a\", 1, true]))\n    assertFalse(eqE0E1E2([\"a\", 1, true], [\"b\", 1, true]))\n    assertFalse(eqE0E1E2([\"a\", 1, true], [\"a\", 2, true]))\n    assertFalse(eqE0E1E2([\"a\", 1, true], [\"a\", 1, false]))\n  })\n\n  it(\"tuple\", () => {\n    const eq = Equivalence.tuple(Equivalence.string, Equivalence.string)\n    assertTrue(eq([\"a\", \"b\"], [\"a\", \"b\"]))\n    assertFalse(eq([\"a\", \"b\"], [\"c\", \"b\"]))\n    assertFalse(eq([\"a\", \"b\"], [\"a\", \"c\"]))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/ExecutionPlan.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Array, Effect, ExecutionPlan, Exit, Layer, Stream } from \"effect\"\n\ndescribe(\"ExecutionPlan\", () => {\n  class Service extends Effect.Service<Service>()(\"Service\", {\n    succeed: {\n      stream: Stream.fail(\"A\") as Stream.Stream<number, string>\n    }\n  }) {\n    static B = Layer.succeed(\n      Service,\n      new Service({\n        stream: Stream.fail(\"B\")\n      })\n    )\n    static C = Layer.succeed(\n      Service,\n      new Service({\n        stream: Stream.make(1, 2, 3)\n      })\n    )\n  }\n\n  const Plan = ExecutionPlan.make({\n    provide: Service.Default\n  }, {\n    provide: Service.B\n  }, {\n    provide: Service.C\n  })\n\n  const PlanPartial = ExecutionPlan.make({\n    provide: Layer.succeed(\n      Service,\n      new Service({\n        stream: Stream.make(1, 2, 3).pipe(\n          Stream.concat(Stream.fail(\"Partial\"))\n        )\n      })\n    )\n  }, {\n    provide: Service.C\n  })\n\n  describe(\"Stream.withExecutionPlan\", () => {\n    it.effect(\"fallback\", () =>\n      Effect.gen(function*() {\n        const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream))\n        const items = Array.empty<number>()\n        const result = yield* stream.pipe(\n          Stream.withExecutionPlan(Plan),\n          Stream.runForEach((n) =>\n            Effect.sync(() => {\n              items.push(n)\n            })\n          ),\n          Effect.exit\n        )\n        deepStrictEqual(items, [1, 2, 3])\n        assertTrue(Exit.isSuccess(result))\n      }))\n\n    it.effect(\"fallback from partial stream\", () =>\n      Effect.gen(function*() {\n        const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream))\n        const items = Array.empty<number>()\n        const result = yield* stream.pipe(\n          Stream.withExecutionPlan(PlanPartial),\n          Stream.runForEach((n) =>\n            Effect.sync(() => {\n              items.push(n)\n            })\n          ),\n          Effect.exit\n        )\n        deepStrictEqual(items, [1, 2, 3, 1, 2, 3])\n        assertTrue(Exit.isSuccess(result))\n      }))\n\n    it.effect(\"preventFallbackOnPartialStream\", () =>\n      Effect.gen(function*() {\n        const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream))\n        const items = Array.empty<number>()\n        const result = yield* stream.pipe(\n          Stream.withExecutionPlan(PlanPartial, {\n            preventFallbackOnPartialStream: true\n          }),\n          Stream.runForEach((n) =>\n            Effect.sync(() => {\n              items.push(n)\n            })\n          ),\n          Effect.exit\n        )\n        deepStrictEqual(items, [1, 2, 3])\n        deepStrictEqual(result, Exit.fail(\"Partial\"))\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Exit.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Exit } from \"effect\"\n\ndescribe(\"Exit\", () => {\n  describe(\"toJSON\", () => {\n    it(\"succeed\", () => {\n      deepStrictEqual(Exit.succeed(1).toJSON(), {\n        _id: \"Exit\",\n        _tag: \"Success\",\n        value: 1\n      })\n    })\n\n    it(\"fail\", () => {\n      deepStrictEqual(Exit.fail(\"failure\").toJSON(), {\n        _id: \"Exit\",\n        _tag: \"Failure\",\n        cause: {\n          _id: \"Cause\",\n          _tag: \"Fail\",\n          failure: \"failure\"\n        }\n      })\n      class MyError {\n        readonly _tag = \"MyError\"\n      }\n      deepStrictEqual(Exit.fail(new MyError()).toJSON(), {\n        _id: \"Exit\",\n        _tag: \"Failure\",\n        cause: {\n          _id: \"Cause\",\n          _tag: \"Fail\",\n          failure: new MyError()\n        }\n      })\n    })\n  })\n\n  describe(\"toString\", () => {\n    it(\"succeed\", () => {\n      deepStrictEqual(\n        String(Exit.succeed(1)),\n        `{\n  \"_id\": \"Exit\",\n  \"_tag\": \"Success\",\n  \"value\": 1\n}`\n      )\n    })\n\n    it(\"fail\", () => {\n      deepStrictEqual(\n        String(Exit.fail(\"failure\")),\n        `{\n  \"_id\": \"Exit\",\n  \"_tag\": \"Failure\",\n  \"cause\": {\n    \"_id\": \"Cause\",\n    \"_tag\": \"Fail\",\n    \"failure\": \"failure\"\n  }\n}`\n      )\n      class Error1 {\n        readonly _tag = \"WithTag\"\n      }\n      deepStrictEqual(\n        String(Exit.fail(new Error1())),\n        `{\n  \"_id\": \"Exit\",\n  \"_tag\": \"Failure\",\n  \"cause\": {\n    \"_id\": \"Cause\",\n    \"_tag\": \"Fail\",\n    \"failure\": {\n      \"_tag\": \"WithTag\"\n    }\n  }\n}`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Fiber.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport {\n  Array,\n  Chunk,\n  Deferred,\n  Effect,\n  Exit,\n  Fiber,\n  FiberId,\n  FiberRef,\n  FiberStatus,\n  Function as Fun,\n  HashSet,\n  pipe,\n  Queue,\n  Ref\n} from \"effect\"\nimport { withLatch } from \"./utils/latch.js\"\n\nconst initial = \"initial\"\nconst update = \"update\"\nconst fibers = Array.makeBy(10000, () => Fiber.void)\n\ndescribe(\"Fiber\", () => {\n  it.effect(\"should track blockingOn in await\", () =>\n    Effect.gen(function*() {\n      const fiber1 = yield* pipe(Effect.never, Effect.fork)\n      const fiber2 = yield* pipe(Fiber.await(fiber1), Effect.fork)\n      const blockingOn = yield* pipe(\n        Fiber.status(fiber2),\n        Effect.flatMap((status) =>\n          FiberStatus.isSuspended(status)\n            ? Effect.succeed(status.blockingOn)\n            : Effect.failSync(Fun.constVoid)\n        ),\n        Effect.eventually\n      )\n      deepStrictEqual(blockingOn, Fiber.id(fiber1))\n    }))\n  it.effect(\"should track blockingOn in race\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(Effect.never, Effect.race(Effect.never), Effect.fork)\n      const blockingOn = yield* pipe(\n        Fiber.status(fiber),\n        Effect.flatMap(\n          (status) => FiberStatus.isSuspended(status) ? Effect.succeed(status.blockingOn) : Effect.fail(void 0 as void)\n        ),\n        Effect.eventually\n      )\n      strictEqual(HashSet.size(FiberId.toSet(blockingOn)), 2)\n    }))\n  it.scoped(\"inheritLocals works for Fiber created using map\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const child = yield* withLatch((release) =>\n        FiberRef.set(fiberRef, update).pipe(Effect.zipRight(release), Effect.fork)\n      )\n      yield* pipe(child, Fiber.map(Fun.constVoid), Fiber.inheritAll)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, update)\n    }))\n  it.scoped(\"inheritLocals works for Fiber created using orElse\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const latch1 = yield* Deferred.make<void>()\n      const latch2 = yield* Deferred.make<void>()\n      const child1 = yield* pipe(\n        FiberRef.set(fiberRef, \"child1\"),\n        Effect.zipRight(Deferred.succeed(latch1, void 0)),\n        Effect.fork\n      )\n      const child2 = yield* pipe(\n        FiberRef.set(fiberRef, \"child2\"),\n        Effect.zipRight(Deferred.succeed(latch2, void 0)),\n        Effect.fork\n      )\n      yield* pipe(Deferred.await(latch1), Effect.zipRight(Deferred.await(latch2)))\n      yield* pipe(child1, Fiber.orElse(child2), Fiber.inheritAll)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, \"child1\")\n    }))\n  it.scoped(\"inheritLocals works for Fiber created using zip\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const latch1 = yield* Deferred.make<void>()\n      const latch2 = yield* Deferred.make<void>()\n      const child1 = yield* pipe(\n        FiberRef.set(fiberRef, \"child1\"),\n        Effect.zipRight(Deferred.succeed(latch1, void 0)),\n        Effect.fork\n      )\n      const child2 = yield* pipe(\n        FiberRef.set(fiberRef, \"child2\"),\n        Effect.zipRight(Deferred.succeed(latch2, void 0)),\n        Effect.fork\n      )\n      yield* pipe(Deferred.await(latch1), Effect.zipRight(Deferred.await(latch2)))\n      yield* pipe(child1, Fiber.zip(child2), Fiber.inheritAll)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, \"child1\")\n    }))\n  it.effect(\"join on interrupted Fiber is an inner interruption\", () =>\n    Effect.gen(function*() {\n      const fiberId = FiberId.make(0, 123)\n      const result = yield* pipe(Fiber.interrupted(fiberId), Fiber.join, Effect.exit)\n      deepStrictEqual(result, Exit.interrupt(fiberId))\n    }))\n  it.effect(\"scoped should create a new Fiber and scope it\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(false)\n      const fiber = yield* withLatch((release) =>\n        Effect.fork(\n          Effect.acquireUseRelease(\n            Effect.asVoid(release),\n            () => Effect.never,\n            () => Ref.set(ref, true)\n          )\n        )\n      )\n      yield* Effect.scoped(Fiber.scoped(fiber))\n      yield* Fiber.await(fiber)\n      const result = yield* Ref.get(ref)\n      assertTrue(result)\n    }))\n  it.effect(\"shard example\", () =>\n    Effect.gen(function*() {\n      const shard = <A, E, R>(\n        queue: Queue.Queue<A>,\n        n: number,\n        worker: (a: A) => Effect.Effect<void, E, R>\n      ): Effect.Effect<never, E, R> => {\n        const worker1 = pipe(\n          Queue.take(queue),\n          Effect.flatMap((a) => Effect.uninterruptible(worker(a))),\n          Effect.forever\n        )\n        return pipe(\n          Effect.forkAll(Array.makeBy(n, () => worker1)),\n          Effect.flatMap(Fiber.join),\n          Effect.zipRight(Effect.never)\n        )\n      }\n      const worker = (n: number) => {\n        if (n === 100) {\n          return pipe(Queue.shutdown(queue), Effect.zipRight(Effect.fail(\"fail\")))\n        }\n        return pipe(Queue.offer(queue, n), Effect.asVoid)\n      }\n      const queue = yield* Queue.unbounded<number>()\n      yield* Queue.offerAll(queue, Array.range(1, 100))\n      const result = yield* Effect.exit(shard(queue, 4, worker))\n      yield* Queue.shutdown(queue)\n      assertTrue(Exit.isFailure(result))\n    }))\n  it.effect(\"child becoming interruptible is interrupted due to auto-supervision of uninterruptible parent\", () =>\n    Effect.gen(function*() {\n      const latch = yield* Deferred.make<void>()\n      const child = pipe(\n        Effect.interruptible(Effect.never),\n        Effect.onInterrupt(() => Deferred.succeed(latch, void 0)),\n        Effect.fork\n      )\n      yield* Effect.uninterruptible(Effect.fork(child))\n      const result = yield* Deferred.await(latch)\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"dual roots\", () =>\n    Effect.gen(function*() {\n      const rootContains = (fiber: Fiber.RuntimeFiber<any, any>): Effect.Effect<boolean> => {\n        return pipe(Fiber.roots, Effect.map(Chunk.unsafeFromArray), Effect.map(Array.contains(fiber)))\n      }\n      const fiber1 = yield* Effect.forkDaemon(Effect.never)\n      const fiber2 = yield* Effect.forkDaemon(Effect.never)\n      yield* pipe(\n        rootContains(fiber1),\n        Effect.flatMap((a) => a ? rootContains(fiber2) : Effect.succeed(false)),\n        Effect.repeat({ until: (_) => _ })\n      )\n      const result = yield* pipe(Fiber.interrupt(fiber1), Effect.zipRight(Fiber.interrupt(fiber2)))\n      assertTrue(Exit.isInterrupted(result))\n    }))\n  it.effect(\"interruptAll interrupts fibers in parallel\", () =>\n    Effect.gen(function*() {\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const fiber1 = yield* pipe(Deferred.succeed(deferred1, void 0), Effect.zipRight(Effect.never), Effect.forkDaemon)\n      const fiber2 = yield* pipe(\n        Deferred.succeed(deferred2, void 0),\n        Effect.zipRight(Fiber.await(fiber1)),\n        Effect.uninterruptible,\n        Effect.forkDaemon\n      )\n      yield* Deferred.await(deferred1)\n      yield* Deferred.await(deferred2)\n      yield* Fiber.interruptAll([fiber2, fiber1])\n      const result = yield* Fiber.await(fiber2)\n      assertTrue(Exit.isInterrupted(result))\n    }))\n  it.effect(\"await does not return until all fibers have completed execution\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(0)\n      const fiber = yield* Effect.forkAll(Array.makeBy(100, () => Ref.set(ref, 10)))\n      yield* Fiber.interrupt(fiber)\n      yield* Ref.set(ref, -1)\n      const result = yield* Ref.get(ref)\n      strictEqual(result, -1)\n    }))\n  it.effect(\"awaitAll - stack safety\", () =>\n    Effect.gen(function*() {\n      const result = yield* Fiber.awaitAll(fibers)\n      assertTrue(Array.isArray(result))\n      assertTrue(result.length === fibers.length)\n      result.forEach((_) => assertTrue(Exit.isSuccess(_) && _.value === undefined))\n    }), 10000)\n  it.effect(\"joinAll - stack safety\", () =>\n    Effect.gen(function*() {\n      const result = yield* Fiber.joinAll(fibers)\n      assertTrue(Array.isArray(result))\n      assertTrue(result.length === fibers.length)\n      result.forEach((x) => strictEqual(x, undefined))\n    }), 10000)\n  it.effect(\"all - stack safety\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Fiber.join(Fiber.all(fibers)), Effect.asVoid)\n      strictEqual(result, undefined)\n    }), 10000)\n  it.effect(\"is subtype of Effect\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* Effect.fork(Effect.succeed(1))\n      const fiberResult = yield* fiber\n      assertTrue(1 === fiberResult)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/FiberHandle.test.ts",
    "content": "import { assert, describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport { Deferred, Effect, Exit, Fiber, FiberHandle, pipe, Ref, TestClock } from \"effect\"\n\ndescribe(\"FiberHandle\", () => {\n  it.effect(\"interrupts fibers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Effect.gen(function*() {\n          const handle = yield* (FiberHandle.make())\n          yield* (FiberHandle.run(handle, Effect.onInterrupt(Effect.never, () => Ref.update(ref, (n) => n + 1))))\n          yield* (Effect.yieldNow())\n        }),\n        Effect.scoped\n      )\n\n      strictEqual(yield* (Ref.get(ref)), 1)\n    }))\n\n  it.effect(\"runtime\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Effect.gen(function*() {\n          const handle = yield* (FiberHandle.make())\n          const run = yield* (FiberHandle.runtime(handle)<never>())\n          run(Effect.onInterrupt(Effect.never, () => Ref.update(ref, (n) => n + 1)))\n          yield* (Effect.yieldNow())\n          run(Effect.onInterrupt(Effect.never, () => Ref.update(ref, (n) => n + 1)))\n          yield* (Effect.yieldNow())\n          run(Effect.onInterrupt(Effect.never, () => Ref.update(ref, (n) => n + 1)), {\n            onlyIfMissing: true\n          })\n          yield* (Effect.yieldNow())\n          strictEqual(yield* (Ref.get(ref)), 1)\n        }),\n        Effect.scoped\n      )\n\n      strictEqual(yield* (Ref.get(ref)), 2)\n    }))\n\n  it.scoped(\"join\", () =>\n    Effect.gen(function*() {\n      const handle = yield* (FiberHandle.make())\n      FiberHandle.unsafeSet(handle, Effect.runFork(Effect.void))\n      FiberHandle.unsafeSet(handle, Effect.runFork(Effect.fail(\"fail\")))\n      const result = yield* pipe(FiberHandle.join(handle), Effect.flip)\n      strictEqual(result, \"fail\")\n    }))\n\n  it.scoped(\"onlyIfMissing\", () =>\n    Effect.gen(function*() {\n      const handle = yield* (FiberHandle.make())\n      const fiberA = yield* (FiberHandle.run(handle, Effect.never))\n      const fiberB = yield* (FiberHandle.run(handle, Effect.never, { onlyIfMissing: true }))\n      const fiberC = yield* (FiberHandle.run(handle, Effect.never, { onlyIfMissing: true }))\n      yield* (Effect.yieldNow())\n      assertTrue(Exit.isInterrupted(yield* (fiberB.await)))\n      assertTrue(Exit.isInterrupted(yield* (fiberC.await)))\n      strictEqual(fiberA.unsafePoll(), null)\n    }))\n\n  it.scoped(\"runtime onlyIfMissing\", () =>\n    Effect.gen(function*() {\n      const run = yield* (FiberHandle.makeRuntime<never>())\n      const fiberA = run(Effect.never)\n      const fiberB = run(Effect.never, { onlyIfMissing: true })\n      const fiberC = run(Effect.never, { onlyIfMissing: true })\n      yield* (Effect.yieldNow())\n      assertTrue(Exit.isInterrupted(yield* (fiberB.await)))\n      assertTrue(Exit.isInterrupted(yield* (fiberC.await)))\n      strictEqual(fiberA.unsafePoll(), null)\n    }))\n\n  it.scoped(\"propagateInterruption: false\", () =>\n    Effect.gen(function*() {\n      const handle = yield* FiberHandle.make()\n      const fiber = yield* FiberHandle.run(handle, Effect.never, {\n        propagateInterruption: false\n      })\n      yield* Effect.yieldNow()\n      yield* Fiber.interrupt(fiber)\n      assertFalse(yield* Deferred.isDone(handle.deferred))\n    }))\n\n  it.scoped(\"propagateInterruption: true\", () =>\n    Effect.gen(function*() {\n      const handle = yield* FiberHandle.make()\n      const fiber = yield* FiberHandle.run(handle, Effect.never, {\n        propagateInterruption: true\n      })\n      yield* Effect.yieldNow()\n      yield* Fiber.interrupt(fiber)\n      assertTrue(Exit.isInterrupted(\n        yield* FiberHandle.join(handle).pipe(\n          Effect.exit\n        )\n      ))\n    }))\n\n  it.scoped(\"awaitEmpty\", () =>\n    Effect.gen(function*() {\n      const handle = yield* FiberHandle.make()\n      yield* FiberHandle.run(handle, Effect.sleep(1000))\n\n      const fiber = yield* Effect.fork(FiberHandle.awaitEmpty(handle))\n      yield* TestClock.adjust(500)\n      assert.isNull(fiber.unsafePoll())\n      yield* TestClock.adjust(500)\n      assert.isDefined(fiber.unsafePoll())\n    }))\n\n  it.scoped(\"makeRuntimePromise\", () =>\n    Effect.gen(function*() {\n      const run = yield* FiberHandle.makeRuntimePromise()\n      const result = yield* Effect.promise(() => run(Effect.succeed(\"done\")))\n      strictEqual(result, \"done\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/FiberMap.test.ts",
    "content": "import { assert, describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport { Array, Deferred, Effect, Exit, Fiber, FiberMap, pipe, Ref, Scope, TestClock } from \"effect\"\n\ndescribe(\"FiberMap\", () => {\n  it.effect(\"interrupts fibers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Effect.gen(function*() {\n          const map = yield* (FiberMap.make<number>())\n          yield* (\n            Effect.forEach(Array.range(1, 10), (i) =>\n              Effect.onInterrupt(\n                Effect.never,\n                () => Ref.update(ref, (n) => n + 1)\n              ).pipe(\n                FiberMap.run(map, i)\n              ))\n          )\n          yield* (Effect.yieldNow())\n        }),\n        Effect.scoped\n      )\n\n      strictEqual(yield* (Ref.get(ref)), 10)\n    }))\n\n  it.effect(\"runtime\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Effect.gen(function*() {\n          const map = yield* (FiberMap.make<number>())\n          const run = yield* (FiberMap.runtime(map)<never>())\n          Array.range(1, 10).forEach((i) =>\n            run(\n              i,\n              Effect.onInterrupt(\n                Effect.never,\n                () => Ref.update(ref, (n) => n + 1)\n              )\n            )\n          )\n          yield* (Effect.yieldNow())\n        }),\n        Effect.scoped\n      )\n\n      strictEqual(yield* (Ref.get(ref)), 10)\n    }))\n\n  it.scoped(\"join\", () =>\n    Effect.gen(function*() {\n      const map = yield* (FiberMap.make<string>())\n      FiberMap.unsafeSet(map, \"a\", Effect.runFork(Effect.void))\n      FiberMap.unsafeSet(map, \"b\", Effect.runFork(Effect.void))\n      FiberMap.unsafeSet(map, \"c\", Effect.runFork(Effect.fail(\"fail\")))\n      FiberMap.unsafeSet(map, \"d\", Effect.runFork(Effect.fail(\"ignored\")))\n      const result = yield* pipe(FiberMap.join(map), Effect.flip)\n      strictEqual(result, \"fail\")\n    }))\n\n  it.effect(\"size\", () =>\n    Effect.gen(function*() {\n      const scope = yield* (Scope.make())\n      const set = yield* pipe(FiberMap.make<string>(), Scope.extend(scope))\n      FiberMap.unsafeSet(set, \"a\", Effect.runFork(Effect.never))\n      FiberMap.unsafeSet(set, \"b\", Effect.runFork(Effect.never))\n      strictEqual(yield* (FiberMap.size(set)), 2)\n      yield* (Scope.close(scope, Exit.void))\n      strictEqual(yield* (FiberMap.size(set)), 0)\n    }))\n\n  it.scoped(\"onlyIfMissing\", () =>\n    Effect.gen(function*() {\n      const handle = yield* (FiberMap.make<string>())\n      const fiberA = yield* (FiberMap.run(handle, \"a\", Effect.never))\n      const fiberB = yield* (FiberMap.run(handle, \"a\", Effect.never, { onlyIfMissing: true }))\n      const fiberC = yield* (FiberMap.run(handle, \"a\", Effect.never, { onlyIfMissing: true }))\n      yield* (Effect.yieldNow())\n      assertTrue(Exit.isInterrupted(yield* (fiberB.await)))\n      assertTrue(Exit.isInterrupted(yield* (fiberC.await)))\n      strictEqual(fiberA.unsafePoll(), null)\n    }))\n\n  it.scoped(\"runtime onlyIfMissing\", () =>\n    Effect.gen(function*() {\n      const run = yield* (FiberMap.makeRuntime<never, string>())\n      const fiberA = run(\"a\", Effect.never)\n      const fiberB = run(\"a\", Effect.never, { onlyIfMissing: true })\n      const fiberC = run(\"a\", Effect.never, { onlyIfMissing: true })\n      yield* (Effect.yieldNow())\n      assertTrue(Exit.isInterrupted(yield* (fiberB.await)))\n      assertTrue(Exit.isInterrupted(yield* (fiberC.await)))\n      strictEqual(fiberA.unsafePoll(), null)\n    }))\n\n  it.scoped(\"propagateInterruption false\", () =>\n    Effect.gen(function*() {\n      const map = yield* FiberMap.make<string>()\n      const fiber = yield* FiberMap.run(map, \"a\", Effect.never, {\n        propagateInterruption: false\n      })\n      yield* Effect.yieldNow()\n      yield* Fiber.interrupt(fiber)\n      assertFalse(yield* Deferred.isDone(map.deferred))\n    }))\n\n  it.scoped(\"propagateInterruption true\", () =>\n    Effect.gen(function*() {\n      const map = yield* FiberMap.make<string>()\n      const fiber = yield* FiberMap.run(map, \"a\", Effect.never, {\n        propagateInterruption: true\n      })\n      yield* Effect.yieldNow()\n      yield* Fiber.interrupt(fiber)\n      assertTrue(Exit.isInterrupted(\n        yield* FiberMap.join(map).pipe(\n          Effect.exit\n        )\n      ))\n    }))\n\n  it.scoped(\"awaitEmpty\", () =>\n    Effect.gen(function*() {\n      const map = yield* FiberMap.make<string>()\n      yield* FiberMap.run(map, \"a\", Effect.sleep(1000))\n      yield* FiberMap.run(map, \"b\", Effect.sleep(1000))\n      yield* FiberMap.run(map, \"c\", Effect.sleep(1000))\n      yield* FiberMap.run(map, \"d\", Effect.sleep(1000))\n\n      const fiber = yield* Effect.fork(FiberMap.awaitEmpty(map))\n      yield* TestClock.adjust(500)\n      assert.isNull(fiber.unsafePoll())\n      yield* TestClock.adjust(500)\n      assert.isDefined(fiber.unsafePoll())\n    }))\n\n  it.scoped(\"makeRuntimePromise\", () =>\n    Effect.gen(function*() {\n      const run = yield* FiberMap.makeRuntimePromise<never, string>()\n      const result = yield* Effect.promise(() => run(\"a\", Effect.succeed(\"done\")))\n      strictEqual(result, \"done\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/FiberRef.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInclude, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport {\n  Chunk,\n  Clock,\n  Deferred,\n  Duration,\n  Effect,\n  Fiber,\n  FiberRef,\n  Function as Fun,\n  identity,\n  Option,\n  pipe,\n  Runtime\n} from \"effect\"\n\nconst initial = \"initial\"\nconst update = \"update\"\nconst update1 = \"update1\"\nconst update2 = \"update2\"\n\nconst increment = (n: number): number => n + 1\n\nconst loseTimeAndCpu: Effect.Effect<void> = Effect.yieldNow().pipe(\n  Effect.zipLeft(Clock.sleep(Duration.millis(1))),\n  Effect.repeatN(100)\n)\n\ndescribe(\"FiberRef\", () => {\n  it.scoped(\"get returns the current value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, initial)\n    }))\n  it.scoped(\"get returns the correct value for a child\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const fiber = yield* Effect.fork(FiberRef.get(fiberRef))\n      const result = yield* Fiber.join(fiber)\n      strictEqual(result, initial)\n    }))\n  it.scoped(\"getAndUpdate - changing the value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const value1 = yield* FiberRef.getAndUpdate(fiberRef, () => update)\n      const value2 = yield* FiberRef.get(fiberRef)\n      strictEqual(value1, initial)\n      strictEqual(value2, update)\n    }))\n  it.scoped(\"getAndUpdateSome - changing the value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const value1 = yield* FiberRef.getAndUpdateSome(fiberRef, () => Option.some(update))\n      const value2 = yield* FiberRef.get(fiberRef)\n      strictEqual(value1, initial)\n      strictEqual(value2, update)\n    }))\n  it.scoped(\"getAndUpdateSome - not changing value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const value1 = yield* FiberRef.getAndUpdateSome(fiberRef, () => Option.none())\n      const value2 = yield* FiberRef.get(fiberRef)\n      strictEqual(value1, initial)\n      strictEqual(value2, initial)\n    }))\n  it.scoped(\"set updates the current value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      yield* FiberRef.set(fiberRef, update)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, update)\n    }))\n  it.scoped(\"set by a child doesn't update parent's value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const deferred = yield* Deferred.make<void>()\n      yield* FiberRef.set(fiberRef, update).pipe(\n        Effect.zipRight(Deferred.succeed(deferred, void 0)),\n        Effect.fork\n      )\n      yield* Deferred.await(deferred)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, initial)\n    }))\n  it.scoped(\"modify - changing the value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const value1 = yield* FiberRef.modify(fiberRef, () => [1, update])\n      const value2 = yield* FiberRef.get(fiberRef)\n      strictEqual(value1, 1)\n      strictEqual(value2, update)\n    }))\n  it.scoped(\"modifySome - not changing the value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const value1 = yield* FiberRef.modifySome(fiberRef, 2, () => Option.none())\n      const value2 = yield* FiberRef.get(fiberRef)\n      strictEqual(value1, 2)\n      strictEqual(value2, initial)\n    }))\n  it.scoped(\"updateAndGet - changing the value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const value1 = yield* FiberRef.updateAndGet(fiberRef, () => update)\n      const value2 = yield* FiberRef.get(fiberRef)\n      strictEqual(value1, update)\n      strictEqual(value2, update)\n    }))\n  it.scoped(\"updateSomeAndGet - changing the value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const value1 = yield* FiberRef.updateSomeAndGet(fiberRef, () => Option.some(update))\n      const value2 = yield* FiberRef.get(fiberRef)\n      strictEqual(value1, update)\n      strictEqual(value2, update)\n    }))\n  it.scoped(\"updateSomeAndGet - not changing the value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const value1 = yield* FiberRef.updateSomeAndGet(fiberRef, () => Option.none())\n      const value2 = yield* FiberRef.get(fiberRef)\n      strictEqual(value1, initial)\n      strictEqual(value2, initial)\n    }))\n  it.scoped(\"restores the original value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      yield* FiberRef.set(fiberRef, update)\n      yield* FiberRef.delete(fiberRef)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, initial)\n    }))\n  it.scoped(\"locally - restores original value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const local = yield* Effect.locally(fiberRef, update)(FiberRef.get(fiberRef))\n      const value = yield* FiberRef.get(fiberRef)\n      strictEqual(local, update)\n      strictEqual(value, initial)\n    }))\n  it.scoped(\"locally - restores parent's value\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const child = yield* Effect.locally(fiberRef, update)(FiberRef.get(fiberRef).pipe(Effect.fork))\n      const local = yield* Fiber.join(child)\n      const value = yield* FiberRef.get(fiberRef)\n      strictEqual(local, update)\n      strictEqual(value, initial)\n    }))\n  it.scoped(\"locally - restores undefined value\", () =>\n    Effect.gen(function*() {\n      const child = yield* Effect.fork(FiberRef.make(initial)) // Don't use join as it inherits values from child\n      // Don't use join as it inherits values from child\n      const fiberRef = yield* pipe(Fiber.await(child), Effect.flatten)\n      const localValue = yield* Effect.locally(fiberRef, update)(FiberRef.get(fiberRef))\n      const value = yield* FiberRef.get(fiberRef)\n      strictEqual(localValue, update)\n      strictEqual(value, initial)\n    }))\n  it.scoped(\"initial value is inherited on join\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const child = yield* Effect.fork(FiberRef.set(fiberRef, update))\n      yield* Fiber.join(child)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, update)\n    }))\n  it.scoped(\"initial value is always available\", () =>\n    Effect.gen(function*() {\n      const child = yield* Effect.fork(FiberRef.make(initial))\n      const fiberRef = yield* pipe(Fiber.await(child), Effect.flatten)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, initial)\n    }))\n  it.scoped(\"fork function is applied on fork - 1\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(0, { fork: increment })\n      const child = yield* Effect.fork(Effect.void)\n      yield* Fiber.join(child)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, 1)\n    }))\n  it.scoped(\"fork function is applied on fork - 2\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(0, { fork: increment })\n      const child = yield* pipe(Effect.void, Effect.fork, Effect.flatMap(Fiber.join), Effect.fork)\n      yield* Fiber.join(child)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, 2)\n    }))\n  it.scoped(\"join function is applied on join - 1\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(0, { fork: identity, join: Math.max })\n      const child = yield* Effect.fork(FiberRef.update(fiberRef, increment))\n      yield* Fiber.join(child)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, 1)\n    }))\n  it.scoped(\"join function is applied on join - 2\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(0, { fork: identity, join: Math.max })\n      const child = yield* Effect.fork(FiberRef.update(fiberRef, increment))\n      yield* FiberRef.update(fiberRef, (n) => n + 2)\n      yield* Fiber.join(child)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, 2)\n    }))\n  it.scopedLive(\"the value of the loser is inherited in zipPar\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const latch = yield* Deferred.make<void>()\n      const winner = FiberRef.set(fiberRef, update1).pipe(Effect.zipRight(Deferred.succeed(latch, void 0)))\n      const loser = Deferred.await(latch).pipe(\n        Effect.zipRight(Clock.sleep(Duration.millis(1))),\n        Effect.zipRight(FiberRef.set(fiberRef, update2))\n      )\n      yield* pipe(winner, Effect.zip(loser, { concurrent: true }))\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, update2)\n    }))\n  it.scoped(\"nothing gets inherited with a failure in zipPar\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const success = FiberRef.set(fiberRef, update)\n      const failure1 = FiberRef.set(fiberRef, update).pipe(Effect.zipRight(Effect.fail(\":-(\")))\n      const failure2 = FiberRef.set(fiberRef, update).pipe(Effect.zipRight(Effect.fail(\":-O\")))\n      yield* pipe(\n        success,\n        Effect.zip(failure1.pipe(Effect.zip(failure2, { concurrent: true })), { concurrent: true }),\n        Effect.orElse(() => Effect.void)\n      )\n      const result = yield* FiberRef.get(fiberRef)\n      assertInclude(result, initial)\n    }))\n  it.scoped(\"the value of all fibers in inherited when running many effects with collectAllPar\", () =>\n    Effect.gen(function*() {\n      const n = 1000\n      const fiberRef = yield* FiberRef.make(0, {\n        fork: Fun.constant(0),\n        join: (a, b) => a + b\n      })\n      yield* Effect.all(Array.from({ length: n }, () => FiberRef.update(fiberRef, (n) => n + 1)), {\n        concurrency: \"unbounded\",\n        discard: true\n      })\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, n)\n    }))\n  it.scoped(\"its value is inherited after simple race\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      yield* pipe(FiberRef.set(fiberRef, update1), Effect.race(FiberRef.set(fiberRef, update2)))\n      const result = yield* FiberRef.get(fiberRef)\n      assertTrue(new RegExp(`${update1}|${update2}`).test(result))\n    }))\n  it.scopedLive(\"its value is inherited after a race with a bad winner\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const latch = yield* Deferred.make<void>()\n      const badWinner = FiberRef.set(fiberRef, update1).pipe(\n        Effect.zipRight(Effect.fail(\"ups\").pipe(Effect.ensuring(Deferred.succeed(latch, void 0))))\n      )\n      const goodLoser = FiberRef.set(fiberRef, update2).pipe(\n        Effect.zipRight(Deferred.await(latch)),\n        Effect.zipRight(Effect.sleep(Duration.seconds(1)))\n      )\n      yield* pipe(badWinner, Effect.race(goodLoser))\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, update2)\n    }))\n  it.scoped(\"its value is not inherited after a race of losers\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const loser1 = FiberRef.set(fiberRef, update1).pipe(Effect.zipRight(Effect.fail(\"ups1\")))\n      const loser2 = FiberRef.set(fiberRef, update2).pipe(Effect.zipRight(Effect.fail(\"ups2\")))\n      yield* pipe(loser1, Effect.race(loser2), Effect.ignore)\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, initial)\n    }))\n  it.scoped(\"its value is inherited in a trivial race\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      yield* Effect.raceAll([FiberRef.set(fiberRef, update)])\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, update)\n    }))\n  it.scoped(\"the value of the winner is inherited when racing two effects with raceAll\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const latch = yield* Deferred.make<void>()\n      const winner1 = FiberRef.set(fiberRef, update1).pipe(\n        Effect.zipRight(Deferred.succeed(latch, void 0))\n      )\n      const loser1 = Deferred.await(latch).pipe(\n        Effect.zipRight(FiberRef.set(fiberRef, update2)),\n        Effect.zipRight(loseTimeAndCpu)\n      )\n      yield* Effect.raceAll([loser1, winner1])\n      const value1 = yield* pipe(FiberRef.get(fiberRef), Effect.zipLeft(FiberRef.set(fiberRef, initial)))\n      const winner2 = FiberRef.set(fiberRef, update1)\n      const loser2 = FiberRef.set(fiberRef, update2).pipe(Effect.zipRight(Effect.fail(\":-O\")))\n      yield* Effect.raceAll([loser2, winner2])\n      const value2 = yield* pipe(FiberRef.get(fiberRef), Effect.zipLeft(FiberRef.set(fiberRef, initial)))\n      strictEqual(value1, update1)\n      strictEqual(value2, update1)\n    }))\n  it.scoped(\"the value of the winner is inherited when racing many effects with raceAll\", () =>\n    Effect.gen(function*() {\n      const n = 63\n      const fiberRef = yield* FiberRef.make(initial)\n      const latch = yield* Deferred.make<void>()\n      const winner1 = FiberRef.set(fiberRef, update1).pipe(\n        Effect.zipRight(Deferred.succeed(latch, void 0)),\n        Effect.asVoid\n      )\n      const losers1 = Deferred.await(latch).pipe(\n        Effect.zipRight(FiberRef.set(fiberRef, update2)),\n        Effect.zipRight(loseTimeAndCpu),\n        Effect.replicate(n)\n      )\n      yield* pipe(Chunk.unsafeFromArray(losers1), Chunk.prepend(winner1), Effect.raceAll)\n      const value1 = yield* pipe(FiberRef.get(fiberRef), Effect.zipLeft(FiberRef.set(fiberRef, initial)))\n      const winner2 = FiberRef.set(fiberRef, update1)\n      const losers2 = FiberRef.set(fiberRef, update1).pipe(Effect.zipRight(Effect.fail(\":-O\")), Effect.replicate(n))\n      yield* pipe(Chunk.unsafeFromArray(losers2), Chunk.prepend(winner2), Effect.raceAll)\n      const value2 = yield* pipe(FiberRef.get(fiberRef), Effect.zipLeft(FiberRef.set(fiberRef, initial)))\n      strictEqual(value1, update1)\n      strictEqual(value2, update1)\n    }))\n  it.scoped(\"nothing gets inherited when racing failures with raceAll\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const loser = FiberRef.set(fiberRef, update).pipe(Effect.zipRight(Effect.fail(\"darn\")))\n      yield* pipe(Effect.raceAll([loser, ...Array.from({ length: 63 }, () => loser)]), Effect.orElse(() => Effect.void))\n      const result = yield* FiberRef.get(fiberRef)\n      strictEqual(result, initial)\n    }))\n  it.scoped(\"fork patch is applied when a fiber is unsafely run\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make<boolean>(true, { fork: Fun.constTrue })\n      const deferred = yield* Deferred.make<boolean>()\n      const runtime: Runtime.Runtime<never> = yield* Effect.runtime<never>().pipe(Effect.locally(fiberRef, false))\n      yield* Effect.sync(() => FiberRef.get(fiberRef).pipe(Effect.intoDeferred(deferred), Runtime.runCallback(runtime)))\n      const result = yield* Deferred.await(deferred)\n      assertTrue(result)\n    }))\n  it.scoped(\"fork patch is applied when a fiber is unsafely forked\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make<boolean>(true, { fork: Fun.constTrue })\n      const deferred = yield* Deferred.make<boolean>()\n      const runtime: Runtime.Runtime<never> = yield* Effect.locally(Effect.runtime<never>(), fiberRef, false)\n      const fiber = yield* Effect.sync(() =>\n        Runtime.runFork(runtime)(Effect.intoDeferred(FiberRef.get(fiberRef), deferred))\n      )\n      yield* Fiber.join(fiber)\n      const result = yield* Deferred.await(deferred)\n      assertTrue(result)\n    }))\n  it.scoped(\"is subtype of Effect\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(initial)\n      const result = yield* fiberRef\n      strictEqual(result, initial)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/FiberRefs.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Cause, Effect, Exit, Fiber, FiberId, FiberRef, FiberRefs, HashMap, Option, pipe, Queue, Scope } from \"effect\"\n\ndescribe(\"FiberRefs\", () => {\n  it.scoped(\"propagate FiberRef values across fiber boundaries\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make(false)\n      const queue = yield* Queue.unbounded<FiberRefs.FiberRefs>()\n      const producer = yield* FiberRef.set(fiberRef, true).pipe(\n        Effect.zipRight(Effect.getFiberRefs.pipe(Effect.flatMap((a) => Queue.offer(queue, a)))),\n        Effect.fork\n      )\n      const consumer = yield* pipe(\n        Queue.take(queue),\n        Effect.flatMap((fiberRefs) => Effect.setFiberRefs(fiberRefs).pipe(Effect.zipRight(FiberRef.get(fiberRef)))),\n        Effect.fork\n      )\n      yield* Fiber.join(producer)\n      const result = yield* Fiber.join(consumer)\n      assertTrue(result)\n    }))\n  it(\"interruptedCause\", () => {\n    const parent = FiberId.make(1, Date.now()) as FiberId.Runtime\n    const child = FiberId.make(2, Date.now()) as FiberId.Runtime\n    const parentFiberRefs = FiberRefs.unsafeMake(new Map())\n    const childFiberRefs = FiberRefs.updateAs(parentFiberRefs, {\n      fiberId: child,\n      fiberRef: FiberRef.interruptedCause,\n      value: Cause.interrupt(parent)\n    })\n    const newParentFiberRefs = FiberRefs.joinAs(parentFiberRefs, parent, childFiberRefs)\n    deepStrictEqual(FiberRefs.get(newParentFiberRefs, FiberRef.interruptedCause), Option.some(Cause.empty))\n  })\n\n  describe(\"currentLogAnnotations\", () => {\n    it(\"doesnt leak\", () => {\n      Effect.void.pipe(Effect.annotateLogs(\"test\", \"abc\"), Effect.runSync)\n      strictEqual(FiberRef.currentLogAnnotations.pipe(FiberRef.get, Effect.map(HashMap.size), Effect.runSync), 0)\n    })\n\n    it.effect(\"annotateLogsScoped\", () =>\n      Effect.gen(function*() {\n        const scope = yield* Scope.make()\n        strictEqual(HashMap.size(yield* FiberRef.get(FiberRef.currentLogAnnotations)), 0)\n        yield* Effect.annotateLogsScoped({\n          test: 123\n        }).pipe(Scope.extend(scope))\n        strictEqual(HashMap.size(yield* FiberRef.get(FiberRef.currentLogAnnotations)), 1)\n        yield* Scope.close(scope, Exit.void)\n        strictEqual(HashMap.size(yield* FiberRef.get(FiberRef.currentLogAnnotations)), 0)\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/FiberSet.test.ts",
    "content": "import { assert, describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport { Array, Deferred, Effect, Exit, Fiber, FiberSet, pipe, Ref, Scope, TestClock } from \"effect\"\n\ndescribe(\"FiberSet\", () => {\n  it.effect(\"interrupts fibers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Effect.gen(function*() {\n          const set = yield* (FiberSet.make())\n          yield* pipe(\n            Effect.onInterrupt(\n              Effect.never,\n              () => Ref.update(ref, (n) => n + 1)\n            ).pipe(FiberSet.run(set)),\n            Effect.replicateEffect(10)\n          )\n          yield* (Effect.yieldNow())\n        }),\n        Effect.scoped\n      )\n\n      strictEqual(yield* (Ref.get(ref)), 10)\n    }))\n\n  it.effect(\"runtime\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Effect.gen(function*() {\n          const set = yield* (FiberSet.make())\n          const run = yield* (FiberSet.runtime(set)<never>())\n          Array.range(1, 10).forEach(() =>\n            run(\n              Effect.onInterrupt(\n                Effect.never,\n                () => Ref.update(ref, (n) => n + 1)\n              )\n            )\n          )\n          yield* (Effect.yieldNow())\n        }),\n        Effect.scoped\n      )\n\n      strictEqual(yield* (Ref.get(ref)), 10)\n    }))\n\n  it.scoped(\"join\", () =>\n    Effect.gen(function*() {\n      const set = yield* (FiberSet.make())\n      FiberSet.unsafeAdd(set, Effect.runFork(Effect.void))\n      FiberSet.unsafeAdd(set, Effect.runFork(Effect.void))\n      FiberSet.unsafeAdd(set, Effect.runFork(Effect.fail(\"fail\")))\n      const result = yield* pipe(FiberSet.join(set), Effect.flip)\n      strictEqual(result, \"fail\")\n    }))\n\n  it.effect(\"size\", () =>\n    Effect.gen(function*() {\n      const scope = yield* (Scope.make())\n      const set = yield* pipe(FiberSet.make(), Scope.extend(scope))\n      FiberSet.unsafeAdd(set, Effect.runFork(Effect.never))\n      FiberSet.unsafeAdd(set, Effect.runFork(Effect.never))\n      strictEqual(yield* (FiberSet.size(set)), 2)\n      yield* (Scope.close(scope, Exit.void))\n      strictEqual(yield* (FiberSet.size(set)), 0)\n    }))\n\n  it.scoped(\"propagateInterruption false\", () =>\n    Effect.gen(function*() {\n      const set = yield* FiberSet.make()\n      const fiber = yield* FiberSet.run(set, Effect.never, {\n        propagateInterruption: false\n      })\n      yield* Effect.yieldNow()\n      yield* Fiber.interrupt(fiber)\n      assertFalse(yield* Deferred.isDone(set.deferred))\n    }))\n\n  it.scoped(\"propagateInterruption true\", () =>\n    Effect.gen(function*() {\n      const set = yield* FiberSet.make()\n      const fiber = yield* FiberSet.run(set, Effect.never, {\n        propagateInterruption: true\n      })\n      yield* Effect.yieldNow()\n      yield* Fiber.interrupt(fiber)\n      assertTrue(Exit.isInterrupted(\n        yield* FiberSet.join(set).pipe(\n          Effect.exit\n        )\n      ))\n    }))\n\n  it.scoped(\"awaitEmpty\", () =>\n    Effect.gen(function*() {\n      const set = yield* FiberSet.make()\n      yield* FiberSet.run(set, Effect.sleep(1000))\n      yield* FiberSet.run(set, Effect.sleep(1000))\n      yield* FiberSet.run(set, Effect.sleep(1000))\n      yield* FiberSet.run(set, Effect.sleep(1000))\n\n      const fiber = yield* Effect.fork(FiberSet.awaitEmpty(set))\n      yield* TestClock.adjust(500)\n      assert.isNull(fiber.unsafePoll())\n      yield* TestClock.adjust(500)\n      assert.isDefined(fiber.unsafePoll())\n    }))\n\n  it.scoped(\"makeRuntimePromise\", () =>\n    Effect.gen(function*() {\n      const run = yield* FiberSet.makeRuntimePromise()\n      const result = yield* Effect.promise(() => run(Effect.succeed(\"done\")))\n      strictEqual(result, \"done\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Function.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual, throws } from \"@effect/vitest/utils\"\nimport { Function, String } from \"effect\"\n\nconst f = (n: number): number => n + 1\nconst g = (n: number) => n * 2\n\ndescribe(\"Function\", () => {\n  it(\"apply\", () => {\n    const countArgs = (...args: Array<unknown>) => args.length\n\n    deepStrictEqual(Function.pipe(countArgs, Function.apply(\"a\")), 1)\n    deepStrictEqual(Function.pipe(countArgs, Function.apply(\"a\", \"b\", \"c\")), 3)\n  })\n\n  it(\"compose\", () => {\n    deepStrictEqual(Function.pipe(String.length, Function.compose((n) => n * 2))(\"aaa\"), 6)\n    deepStrictEqual(Function.compose(String.length, (n) => n * 2)(\"aaa\"), 6)\n  })\n\n  it(\"flip\", () => {\n    const f = (a: number) => (b: string) => a - b.length\n    const g = (a: number, i = 0) => (b: number) => a ** b + i\n\n    deepStrictEqual(Function.flip(f)(\"aaa\")(2), -1)\n    deepStrictEqual(Function.flip(g)(2)(2, 1), 5)\n  })\n\n  it(\"unsafeCoerce\", () => {\n    deepStrictEqual(Function.unsafeCoerce, Function.identity)\n  })\n\n  it(\"satisfies\", () => {\n    deepStrictEqual(Function.satisfies<number>()(5), 5)\n    // @ts-expect-error\n    deepStrictEqual(Function.satisfies<string>()(5), 5)\n  })\n\n  it(\"constant\", () => {\n    deepStrictEqual(Function.constant(\"a\")(), \"a\")\n  })\n\n  it(\"constTrue\", () => {\n    deepStrictEqual(Function.constTrue(), true)\n  })\n\n  it(\"constFalse\", () => {\n    deepStrictEqual(Function.constFalse(), false)\n  })\n\n  it(\"constNull\", () => {\n    deepStrictEqual(Function.constNull(), null)\n  })\n\n  it(\"constUndefined\", () => {\n    deepStrictEqual(Function.constUndefined(), undefined)\n  })\n\n  it(\"constVoid\", () => {\n    deepStrictEqual(Function.constVoid(), undefined)\n  })\n\n  it(\"absurd\", () => {\n    throws(() => Function.absurd<string>(null as any as never))\n  })\n\n  it(\"hole\", () => {\n    throws(() => Function.hole<string>())\n  })\n\n  it(\"SK\", () => {\n    strictEqual(Function.SK(1, 2), 2)\n  })\n\n  it(\"tupled\", () => {\n    const f1 = (a: number): number => a * 2\n    const f2 = (a: number, b: number): number => a + b\n    const u1 = Function.tupled(f1)\n    const u2 = Function.tupled(f2)\n    deepStrictEqual(u1([1]), 2)\n    deepStrictEqual(u2([1, 2]), 3)\n  })\n\n  it(\"untupled\", () => {\n    const f1 = (a: readonly [number]): number => a[0] * 2\n    const f2 = (a: readonly [number, number]): number => a[0] + a[1]\n    const u1 = Function.untupled(f1)\n    const u2 = Function.untupled(f2)\n    deepStrictEqual(u1(1), 2)\n    deepStrictEqual(u2(1, 2), 3)\n  })\n\n  it(\"pipe()\", () => {\n    const pipe = Function.pipe // this alias is required in order to exclude the `@effect/babel-plugin` compiler and get 100% coverage\n    // @effect-diagnostics-next-line unnecessaryPipe:off\n    deepStrictEqual(pipe(2), 2)\n    deepStrictEqual(pipe(2, f), 3)\n    deepStrictEqual(pipe(2, f, g), 6)\n    deepStrictEqual(pipe(2, f, g, f), 7)\n    deepStrictEqual(pipe(2, f, g, f, g), 14)\n    deepStrictEqual(pipe(2, f, g, f, g, f), 15)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g), 30)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f), 31)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g), 62)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f), 63)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f, g), 126)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f, g, f), 127)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f, g, f, g), 254)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f), 255)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g), 510)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f), 511)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g), 1022)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f), 1023)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g), 2046)\n    deepStrictEqual(pipe(2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f), 2047)\n    deepStrictEqual(\n      (Function.pipe as any)(...[2, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g, f, g]),\n      4094\n    )\n  })\n\n  it(\"flow\", () => {\n    const flow = Function.flow // this alias is required in order to exclude the `@effect/babel-plugin` compiler and get 100% coverage\n    deepStrictEqual(flow(f)(2), 3)\n    deepStrictEqual(flow(f, g)(2), 6)\n    deepStrictEqual(flow(f, g, f)(2), 7)\n    deepStrictEqual(flow(f, g, f, g)(2), 14)\n    deepStrictEqual(flow(f, g, f, g, f)(2), 15)\n    deepStrictEqual(flow(f, g, f, g, f, g)(2), 30)\n    deepStrictEqual(flow(f, g, f, g, f, g, f)(2), 31)\n    deepStrictEqual(flow(f, g, f, g, f, g, f, g)(2), 62)\n    deepStrictEqual(flow(f, g, f, g, f, g, f, g, f)(2), 63)\n    // this is just to satisfy noImplicitReturns and 100% coverage\n    deepStrictEqual((Function.flow as any)(...[f, g, f, g, f, g, f, g, f, g]), undefined)\n  })\n\n  describe(\"dual\", () => {\n    it(\"arity as predicate\", () => {\n      const f = Function.dual<\n        (that: number) => (self: number) => number,\n        (self: number, that: number) => number\n      >((args) => args.length >= 2, (a: number, b: number): number => a - b)\n      deepStrictEqual(f(3, 2), 1)\n      deepStrictEqual(Function.pipe(3, f(2)), 1)\n      // should ignore excess arguments\n      deepStrictEqual(f.apply(null, [3, 2, 100] as any), 1)\n    })\n\n    it(\"arity: 0\", () => {\n      throws(() =>\n        Function.dual<\n          () => () => number,\n          () => number\n        >(0, (): number => 2), new RangeError(\"Invalid arity 0\"))\n    })\n\n    it(\"arity: 1\", () => {\n      throws(() =>\n        Function.dual<\n          () => (self: number) => number,\n          (self: number) => number\n        >(1, (self: number): number => self * 2), new RangeError(\"Invalid arity 1\"))\n    })\n\n    it(\"arity: 2\", () => {\n      const f = Function.dual<\n        (that: number) => (self: number) => number,\n        (self: number, that: number) => number\n      >(2, (a: number, b: number): number => a - b)\n      deepStrictEqual(f(3, 2), 1)\n      deepStrictEqual(Function.pipe(3, f(2)), 1)\n      // should ignore excess arguments\n      deepStrictEqual(f.apply(null, [3, 2, 100] as any), 1)\n    })\n\n    it(\"arity: 5\", () => {\n      const f = Function.dual<\n        (a: string, b: string, c: string, d: string) => (self: string) => string,\n        (self: string, a: string, b: string, c: string, d: string) => string\n      >(5, (self: string, a: string, b: string, c: string, d: string): string => self + a + b + c + d)\n      deepStrictEqual(f(\"_\", \"a\", \"b\", \"c\", \"d\"), \"_abcd\")\n      deepStrictEqual(Function.pipe(\"_\", f(\"a\", \"b\", \"c\", \"d\")), \"_abcd\")\n      // should ignore excess arguments\n      deepStrictEqual(f.apply(null, [\"_\", \"a\", \"b\", \"c\", \"d\", \"e\"] as any), \"_abcd\")\n    })\n\n    it(\"arity > 5\", () => {\n      const f = Function.dual<\n        (a: string, b: string, c: string, d: string, e: string) => (self: string) => string,\n        (self: string, a: string, b: string, c: string, d: string, e: string) => string\n      >(6, (self: string, a: string, b: string, c: string, d: string, e: string): string => self + a + b + c + d + e)\n      deepStrictEqual(f(\"_\", \"a\", \"b\", \"c\", \"d\", \"e\"), \"_abcde\")\n      deepStrictEqual(Function.pipe(\"_\", f(\"a\", \"b\", \"c\", \"d\", \"e\")), \"_abcde\")\n      // should ignore excess arguments\n      deepStrictEqual(f.apply(null, [\"_\", \"a\", \"b\", \"c\", \"d\", \"e\", \"f\"] as any), \"_abcde\")\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/GlobalValue.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { GlobalValue as G } from \"effect\"\n\nconst a = G.globalValue(\"id\", () => ({}))\nconst b = G.globalValue(\"id\", () => ({}))\n\ndescribe(\"GlobalValue\", () => {\n  it(\"should give the same value when invoked with the same id\", () => {\n    strictEqual(a, b)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Graph.test.ts",
    "content": "import { describe, expect, it } from \"@effect/vitest\"\nimport { Equal, Graph, Hash, Option } from \"effect\"\n\ndescribe(\"Graph\", () => {\n  describe(\"constructors\", () => {\n    it(\"should create empty directed graph\", () => {\n      const graph = Graph.directed<string, number>()\n\n      expect(graph.type).toBe(\"directed\")\n      expect(Graph.nodeCount(graph)).toBe(0)\n      expect(Graph.edgeCount(graph)).toBe(0)\n    })\n\n    it(\"should create empty undirected graph\", () => {\n      const graph = Graph.undirected<string, number>()\n\n      expect(graph.type).toBe(\"undirected\")\n      expect(Graph.nodeCount(graph)).toBe(0)\n      expect(Graph.edgeCount(graph)).toBe(0)\n    })\n  })\n\n  describe(\"isGraph\", () => {\n    it(\"should return true for graph instances\", () => {\n      const directedGraph = Graph.directed<string, number>()\n      const undirectedGraph = Graph.undirected<string, number>()\n\n      expect(Graph.isGraph(directedGraph)).toBe(true)\n      expect(Graph.isGraph(undirectedGraph)).toBe(true)\n    })\n\n    it(\"should return false for non-graph values\", () => {\n      expect(Graph.isGraph({})).toBe(false)\n      expect(Graph.isGraph(null)).toBe(false)\n      expect(Graph.isGraph(undefined)).toBe(false)\n      expect(Graph.isGraph(\"string\")).toBe(false)\n      expect(Graph.isGraph(42)).toBe(false)\n      expect(Graph.isGraph([])).toBe(false)\n    })\n\n    it(\"should be iterable using for...of syntax\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Node A\")\n        Graph.addNode(mutable, \"Node B\")\n        Graph.addNode(mutable, \"Node C\")\n      })\n\n      const collected: Array<readonly [number, string]> = []\n      for (const entry of graph) {\n        collected.push(entry)\n      }\n\n      expect(collected).toHaveLength(3)\n      expect(collected).toEqual([\n        [0, \"Node A\"],\n        [1, \"Node B\"],\n        [2, \"Node C\"]\n      ])\n    })\n\n    it(\"should support manual iterator operations\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Node A\")\n        Graph.addNode(mutable, \"Node B\")\n      })\n\n      const iterator = graph[Symbol.iterator]()\n      const first = iterator.next()\n      const second = iterator.next()\n      const third = iterator.next()\n\n      expect(first.done).toBe(false)\n      expect(first.value).toEqual([0, \"Node A\"])\n      expect(second.done).toBe(false)\n      expect(second.value).toEqual([1, \"Node B\"])\n      expect(third.done).toBe(true)\n    })\n  })\n\n  describe(\"undefined data handling\", () => {\n    describe(\"undefined node data\", () => {\n      it(\"should allow adding nodes with undefined data\", () => {\n        const graph = Graph.directed<undefined, number>((mutable) => {\n          const nodeA = Graph.addNode(mutable, undefined)\n          const nodeB = Graph.addNode(mutable, undefined)\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n        })\n\n        expect(Graph.nodeCount(graph)).toBe(2)\n        expect(Graph.edgeCount(graph)).toBe(1)\n        expect(Graph.getNode(graph, 0)).toEqual(Option.some(undefined))\n        expect(Graph.getNode(graph, 1)).toEqual(Option.some(undefined))\n      })\n\n      it(\"should correctly update nodes with undefined data\", () => {\n        const graph = Graph.directed<undefined | string, number>((mutable) => {\n          Graph.addNode(mutable, undefined)\n          Graph.addNode(mutable, \"defined\")\n        })\n\n        const updated = Graph.mutate(graph, (mutable) => {\n          Graph.updateNode(mutable, 0, () => \"now defined\")\n          Graph.updateNode(mutable, 1, () => undefined)\n        })\n\n        expect(Graph.getNode(updated, 0)).toEqual(Option.some(\"now defined\"))\n        expect(Graph.getNode(updated, 1)).toEqual(Option.some(undefined))\n      })\n\n      it(\"should correctly compare graphs with undefined node data\", () => {\n        const graph1 = Graph.directed<undefined, number>((mutable) => {\n          Graph.addNode(mutable, undefined)\n          Graph.addNode(mutable, undefined)\n        })\n\n        const graph2 = Graph.directed<undefined, number>((mutable) => {\n          Graph.addNode(mutable, undefined)\n          Graph.addNode(mutable, undefined)\n        })\n\n        expect(Equal.equals(graph1, graph2)).toBe(true)\n      })\n\n      it(\"should find nodes with undefined data using predicates\", () => {\n        const graph = Graph.directed<undefined | string, number>((mutable) => {\n          Graph.addNode(mutable, undefined)\n          Graph.addNode(mutable, \"defined\")\n          Graph.addNode(mutable, undefined)\n        })\n\n        const undefinedNode = Graph.findNode(graph, (data) => data === undefined)\n        const undefinedNodes = Graph.findNodes(graph, (data) => data === undefined)\n\n        expect(undefinedNode).toEqual(Option.some(0))\n        expect(undefinedNodes).toEqual([0, 2])\n      })\n\n      it(\"should iterate correctly over graphs with undefined node data\", () => {\n        const graph = Graph.directed<undefined, number>((mutable) => {\n          Graph.addNode(mutable, undefined)\n          Graph.addNode(mutable, undefined)\n        })\n\n        const collected: Array<readonly [number, undefined]> = []\n        for (const entry of graph) {\n          collected.push(entry)\n        }\n\n        expect(collected).toEqual([\n          [0, undefined],\n          [1, undefined]\n        ])\n      })\n    })\n\n    describe(\"undefined edge data\", () => {\n      it(\"should allow adding edges with undefined data\", () => {\n        const graph = Graph.directed<string, undefined>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"A\")\n          const nodeB = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, nodeA, nodeB, undefined)\n        })\n\n        expect(Graph.edgeCount(graph)).toBe(1)\n        expect(Graph.getEdge(graph, 0)).toEqual(Option.some({ source: 0, target: 1, data: undefined }))\n      })\n\n      it(\"should correctly update edges with undefined data\", () => {\n        const graph = Graph.directed<string, undefined | number>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"A\")\n          const nodeB = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, nodeA, nodeB, undefined)\n          Graph.addEdge(mutable, nodeB, nodeA, 42)\n        })\n\n        const updated = Graph.mutate(graph, (mutable) => {\n          Graph.updateEdge(mutable, 0, () => 100)\n          Graph.updateEdge(mutable, 1, () => undefined)\n        })\n\n        const edge0 = Graph.getEdge(updated, 0)\n        const edge1 = Graph.getEdge(updated, 1)\n\n        expect(edge0).toEqual(Option.some({ source: 0, target: 1, data: 100 }))\n        expect(edge1).toEqual(Option.some({ source: 1, target: 0, data: undefined }))\n      })\n\n      it(\"should correctly compare graphs with undefined edge data\", () => {\n        const graph1 = Graph.directed<string, undefined>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, undefined)\n        })\n\n        const graph2 = Graph.directed<string, undefined>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, undefined)\n        })\n\n        expect(Equal.equals(graph1, graph2)).toBe(true)\n      })\n\n      it(\"should find edges with undefined data using predicates\", () => {\n        const graph = Graph.directed<string, undefined | number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, undefined)\n          Graph.addEdge(mutable, b, c, 42)\n          Graph.addEdge(mutable, c, a, undefined)\n        })\n\n        const undefinedEdge = Graph.findEdge(graph, (data) => data === undefined)\n        const undefinedEdges = Graph.findEdges(graph, (data) => data === undefined)\n\n        expect(undefinedEdge).toEqual(Option.some(0))\n        expect(undefinedEdges).toEqual([0, 2])\n      })\n\n      it(\"should produce consistent hashes for graphs with undefined edge data\", () => {\n        const graph1 = Graph.directed<string, undefined | number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, undefined)\n          Graph.addEdge(mutable, b, c, 42)\n        })\n\n        const graph2 = Graph.directed<string, undefined | number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, undefined)\n          Graph.addEdge(mutable, b, c, 42)\n        })\n\n        // Graphs with identical structure should have the same hash\n        expect(Hash.hash(graph1)).toBe(Hash.hash(graph2))\n\n        // Graph with different edge data should have different hash\n        const graph3 = Graph.directed<string, undefined | number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 100) // Different data\n          Graph.addEdge(mutable, b, c, 42)\n        })\n\n        expect(Hash.hash(graph1)).not.toBe(Hash.hash(graph3))\n      })\n\n      it(\"should correctly handle Equal.equals with graphs containing undefined edge data\", () => {\n        const graph1 = Graph.directed<string, undefined | number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, undefined)\n        })\n\n        const graph2 = Graph.directed<string, undefined | number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, undefined)\n        })\n\n        const graph3 = Graph.directed<string, undefined | number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 42)\n        })\n\n        // Equal graphs with undefined edge data should be equal\n        expect(Equal.equals(graph1, graph2)).toBe(true)\n\n        // Graphs with different edge data should not be equal\n        expect(Equal.equals(graph1, graph3)).toBe(false)\n      })\n    })\n\n    describe(\"mixed undefined scenarios\", () => {\n      it(\"should handle graphs with both undefined nodes and edges\", () => {\n        const graph = Graph.directed<undefined, undefined>((mutable) => {\n          const nodeA = Graph.addNode(mutable, undefined)\n          const nodeB = Graph.addNode(mutable, undefined)\n          Graph.addEdge(mutable, nodeA, nodeB, undefined)\n        })\n\n        expect(Graph.nodeCount(graph)).toBe(2)\n        expect(Graph.edgeCount(graph)).toBe(1)\n        expect(Graph.getNode(graph, 0)).toEqual(Option.some(undefined))\n        expect(Graph.getEdge(graph, 0)).toEqual(Option.some({ source: 0, target: 1, data: undefined }))\n      })\n\n      it(\"should correctly handle graph operations with mixed undefined data\", () => {\n        const graph = Graph.directed<undefined | string, undefined | number>((mutable) => {\n          const a = Graph.addNode(mutable, undefined)\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, undefined)\n          Graph.addEdge(mutable, a, b, undefined)\n          Graph.addEdge(mutable, b, c, 42)\n          Graph.addEdge(mutable, c, a, undefined)\n        })\n\n        // Test neighbors\n        const neighborsOfA = Graph.neighbors(graph, 0)\n        const neighborsOfB = Graph.neighbors(graph, 1)\n\n        expect(neighborsOfA).toEqual([1])\n        expect(neighborsOfB).toEqual([2])\n\n        // Test filtering\n        const nodesWithUndefined = Graph.findNodes(graph, (data) => data === undefined)\n        const edgesWithUndefined = Graph.findEdges(graph, (data) => data === undefined)\n\n        expect(nodesWithUndefined).toEqual([0, 2])\n        expect(edgesWithUndefined).toEqual([0, 2])\n      })\n    })\n  })\n\n  describe(\"beginMutation\", () => {\n    it(\"should create a mutable graph from an immutable graph\", () => {\n      const graph = Graph.directed<string, number>()\n      const mutable = Graph.beginMutation(graph)\n\n      expect(mutable.type).toBe(\"directed\")\n      expect(Graph.nodeCount(mutable)).toBe(Graph.nodeCount(graph))\n      expect(Graph.edgeCount(mutable)).toBe(Graph.edgeCount(graph))\n    })\n  })\n\n  describe(\"endMutation\", () => {\n    it(\"should convert a mutable graph back to immutable\", () => {\n      const graph = Graph.directed<string, number>()\n      const mutable = Graph.beginMutation(graph)\n      const result = Graph.endMutation(mutable)\n\n      expect(result.type).toBe(\"directed\")\n      expect(Graph.nodeCount(result)).toBe(Graph.nodeCount(mutable))\n      expect(Graph.edgeCount(result)).toBe(Graph.edgeCount(mutable))\n    })\n  })\n\n  describe(\"mutate\", () => {\n    it(\"should create a new graph instance\", () => {\n      const graph = Graph.directed<string, number>()\n\n      const result = Graph.mutate(graph, () => {\n        // No mutations performed\n      })\n\n      expect(result).not.toBe(graph)\n      expect(Equal.equals(result, graph)).toBe(true) // Structural equality\n    })\n\n    it(\"should handle empty mutation function\", () => {\n      const graph = Graph.directed<string, number>()\n\n      const result = Graph.mutate(graph, () => {\n        // Do nothing\n      })\n\n      expect(Graph.nodeCount(result)).toBe(0)\n      expect(Graph.edgeCount(result)).toBe(0)\n    })\n  })\n\n  describe(\"addNode\", () => {\n    it(\"should add a node to a mutable graph and return its index\", () => {\n      const graph = Graph.directed<string, number>()\n      let nodeIndex: Graph.NodeIndex\n\n      const result = Graph.mutate(graph, (mutable) => {\n        nodeIndex = Graph.addNode(mutable, \"Node A\")\n      })\n\n      expect(Graph.nodeCount(result)).toBe(1)\n      expect(Graph.getNode(result, nodeIndex!)).toEqual(Option.some(\"Node A\"))\n    })\n  })\n\n  describe(\"getNode\", () => {\n    it(\"should return the node data for existing nodes\", () => {\n      let nodeA: Graph.NodeIndex\n      let nodeB: Graph.NodeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        nodeA = Graph.addNode(mutable, \"Node A\")\n        nodeB = Graph.addNode(mutable, \"Node B\")\n      })\n\n      expect(Graph.getNode(graph, nodeA!)).toEqual(Option.some(\"Node A\"))\n      expect(Graph.getNode(graph, nodeB!)).toEqual(Option.some(\"Node B\"))\n    })\n\n    it(\"should return None for non-existent nodes\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Node A\")\n      })\n\n      const nonExistent = Graph.getNode(graph, 999)\n      expect(Option.isNone(nonExistent)).toBe(true)\n    })\n  })\n\n  describe(\"hasNode\", () => {\n    it(\"should return true for existing nodes\", () => {\n      let nodeA: Graph.NodeIndex\n      let nodeB: Graph.NodeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        nodeA = Graph.addNode(mutable, \"Node A\")\n        nodeB = Graph.addNode(mutable, \"Node B\")\n      })\n\n      expect(Graph.hasNode(graph, nodeA!)).toBe(true)\n      expect(Graph.hasNode(graph, nodeB!)).toBe(true)\n    })\n\n    it(\"should return false for non-existent nodes\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Node A\")\n      })\n\n      expect(Graph.hasNode(graph, 999)).toBe(false)\n      expect(Graph.hasNode(graph, -1)).toBe(false)\n    })\n  })\n\n  describe(\"nodeCount\", () => {\n    it(\"should return 0 for empty graph\", () => {\n      const graph = Graph.directed<string, number>()\n      expect(Graph.nodeCount(graph)).toBe(0)\n    })\n\n    it(\"should return correct count after adding nodes\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        expect(Graph.nodeCount(mutable)).toBe(0)\n        Graph.addNode(mutable, \"Node A\")\n        expect(Graph.nodeCount(mutable)).toBe(1)\n        Graph.addNode(mutable, \"Node B\")\n        expect(Graph.nodeCount(mutable)).toBe(2)\n        Graph.addNode(mutable, \"Node C\")\n        expect(Graph.nodeCount(mutable)).toBe(3)\n      })\n\n      expect(Graph.nodeCount(graph)).toBe(3)\n    })\n  })\n\n  describe(\"findNode\", () => {\n    it(\"should find node by predicate\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Node A\")\n        Graph.addNode(mutable, \"Node B\")\n        Graph.addNode(mutable, \"Node C\")\n      })\n\n      const result = Graph.findNode(graph, (data) => data === \"Node B\")\n      expect(Option.isSome(result)).toBe(true)\n      if (Option.isSome(result)) {\n        expect(result.value).toBe(1)\n      }\n    })\n\n    it(\"should return None when no node matches\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Node A\")\n        Graph.addNode(mutable, \"Node B\")\n      })\n\n      const result = Graph.findNode(graph, (data) => data === \"Node C\")\n      expect(Option.isNone(result)).toBe(true)\n    })\n\n    it(\"should find first matching node when multiple match\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Start A\")\n        Graph.addNode(mutable, \"Start B\")\n        Graph.addNode(mutable, \"Start C\")\n      })\n\n      const result = Graph.findNode(graph, (data) => data.startsWith(\"Start\"))\n      expect(Option.isSome(result)).toBe(true)\n      if (Option.isSome(result)) {\n        expect(result.value).toBe(0) // First matching node\n      }\n    })\n  })\n\n  describe(\"findNodes\", () => {\n    it(\"should find all matching nodes\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Start A\")\n        Graph.addNode(mutable, \"Node B\")\n        Graph.addNode(mutable, \"Start C\")\n        Graph.addNode(mutable, \"Start D\")\n      })\n\n      const result = Graph.findNodes(graph, (data) => data.startsWith(\"Start\"))\n      expect(result).toEqual([0, 2, 3])\n    })\n  })\n\n  describe(\"findEdge\", () => {\n    it(\"should find edge by predicate\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        const nodeC = Graph.addNode(mutable, \"Node C\")\n        Graph.addEdge(mutable, nodeA, nodeB, 10)\n        Graph.addEdge(mutable, nodeB, nodeC, 20)\n      })\n\n      const result = Graph.findEdge(graph, (data) => data === 20)\n      expect(Option.isSome(result)).toBe(true)\n      if (Option.isSome(result)) {\n        expect(result.value).toBe(1)\n      }\n    })\n\n    it(\"should return None when no edge matches\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        Graph.addEdge(mutable, nodeA, nodeB, 10)\n      })\n\n      const result = Graph.findEdge(graph, (data) => data === 99)\n      expect(Option.isNone(result)).toBe(true)\n    })\n\n    it(\"should find first matching edge when multiple match\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        const nodeC = Graph.addNode(mutable, \"Node C\")\n        Graph.addEdge(mutable, nodeA, nodeB, 15)\n        Graph.addEdge(mutable, nodeB, nodeC, 25)\n        Graph.addEdge(mutable, nodeC, nodeA, 35)\n      })\n\n      const result = Graph.findEdge(graph, (data) => data > 20)\n      expect(Option.isSome(result)).toBe(true)\n      if (Option.isSome(result)) {\n        expect(result.value).toBe(1) // First matching edge\n      }\n    })\n  })\n\n  describe(\"findEdges\", () => {\n    it(\"should find all matching edges\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        const nodeC = Graph.addNode(mutable, \"Node C\")\n        Graph.addEdge(mutable, nodeA, nodeB, 10)\n        Graph.addEdge(mutable, nodeB, nodeC, 20)\n        Graph.addEdge(mutable, nodeC, nodeA, 30)\n        Graph.addEdge(mutable, nodeA, nodeC, 25)\n      })\n\n      const result = Graph.findEdges(graph, (data) => data >= 20)\n      expect(result).toEqual([1, 2, 3])\n    })\n  })\n\n  describe(\"updateNode\", () => {\n    it(\"should update node data\", () => {\n      const updated = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Node A\")\n        Graph.addNode(mutable, \"Node B\")\n        Graph.updateNode(mutable, 0, (data) => data.toUpperCase())\n      })\n\n      const nodeData = Graph.getNode(updated, 0)\n      expect(Option.isSome(nodeData)).toBe(true)\n      if (Option.isSome(nodeData)) {\n        expect(nodeData.value).toBe(\"NODE A\")\n      }\n    })\n\n    it(\"should do nothing if node doesn't exist\", () => {\n      let nodeA: Graph.NodeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        nodeA = Graph.addNode(mutable, \"Node A\")\n        Graph.updateNode(mutable, 999, (data) => data.toUpperCase())\n      })\n\n      // Original node should be unchanged\n      const nodeData = Graph.getNode(graph, nodeA!)\n      expect(Option.isSome(nodeData)).toBe(true)\n      if (Option.isSome(nodeData)) {\n        expect(nodeData.value).toBe(\"Node A\")\n      }\n    })\n  })\n\n  describe(\"updateEdge\", () => {\n    it(\"should update edge data\", () => {\n      const result = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        const edgeIndex = Graph.addEdge(mutable, nodeA, nodeB, 10)\n        Graph.updateEdge(mutable, edgeIndex, (data) => data * 2)\n      })\n\n      const edge = Graph.getEdge(result, 0)\n      expect(Option.isSome(edge)).toBe(true)\n      if (Option.isSome(edge)) {\n        expect(edge.value.source).toBe(0)\n        expect(edge.value.target).toBe(1)\n        expect(edge.value.data).toBe(20)\n      }\n    })\n\n    it(\"should do nothing if edge doesn't exist\", () => {\n      Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        const edgeIndex = Graph.addEdge(mutable, nodeA, nodeB, 10)\n\n        // Try to update non-existent edge\n        Graph.updateEdge(mutable, 999, (data) => data * 2)\n\n        // Original edge should be unchanged\n        const edge = Graph.getEdge(mutable, edgeIndex)\n        expect(Option.isSome(edge)).toBe(true)\n        if (Option.isSome(edge)) {\n          expect(edge.value.data).toBe(10)\n        }\n      })\n    })\n  })\n\n  describe(\"mapNodes\", () => {\n    it(\"should transform all node data\", () => {\n      let nodeA: Graph.NodeIndex\n      let nodeB: Graph.NodeIndex\n      let nodeC: Graph.NodeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        nodeA = Graph.addNode(mutable, \"node a\")\n        nodeB = Graph.addNode(mutable, \"node b\")\n        nodeC = Graph.addNode(mutable, \"node c\")\n        Graph.mapNodes(mutable, (data) => data.toUpperCase())\n      })\n\n      expect(Graph.getNode(graph, nodeA!)).toEqual(Option.some(\"NODE A\"))\n      expect(Graph.getNode(graph, nodeB!)).toEqual(Option.some(\"NODE B\"))\n      expect(Graph.getNode(graph, nodeC!)).toEqual(Option.some(\"NODE C\"))\n    })\n\n    it(\"should apply transformation to all nodes\", () => {\n      let firstNode: Graph.NodeIndex\n      let secondNode: Graph.NodeIndex\n      let thirdNode: Graph.NodeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        firstNode = Graph.addNode(mutable, \"first\")\n        secondNode = Graph.addNode(mutable, \"second\")\n        thirdNode = Graph.addNode(mutable, \"third\")\n        Graph.mapNodes(mutable, (data) => data + \" (transformed)\")\n      })\n\n      const node0 = Graph.getNode(graph, firstNode!)\n      const node1 = Graph.getNode(graph, secondNode!)\n      const node2 = Graph.getNode(graph, thirdNode!)\n\n      expect(Option.isSome(node0)).toBe(true)\n      expect(Option.isSome(node1)).toBe(true)\n      expect(Option.isSome(node2)).toBe(true)\n\n      if (Option.isSome(node0) && Option.isSome(node1) && Option.isSome(node2)) {\n        expect(node0.value).toBe(\"first (transformed)\")\n        expect(node1.value).toBe(\"second (transformed)\")\n        expect(node2.value).toBe(\"third (transformed)\")\n      }\n    })\n\n    it(\"should modify graph in place during construction\", () => {\n      let originalNode: Graph.NodeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        originalNode = Graph.addNode(mutable, \"original\")\n        // Before transformation\n        const beforeData = Graph.getNode(mutable, originalNode!)\n        expect(Option.isSome(beforeData)).toBe(true)\n        if (Option.isSome(beforeData)) {\n          expect(beforeData.value).toBe(\"original\")\n        }\n\n        // Apply transformation\n        Graph.mapNodes(mutable, (data) => data.toUpperCase())\n      })\n\n      // After transformation\n      const afterData = Graph.getNode(graph, originalNode!)\n      expect(Option.isSome(afterData)).toBe(true)\n      if (Option.isSome(afterData)) {\n        expect(afterData.value).toBe(\"ORIGINAL\")\n      }\n    })\n  })\n\n  describe(\"mapEdges\", () => {\n    it(\"should transform all edge data\", () => {\n      let edgeAB: Graph.EdgeIndex\n      let edgeBC: Graph.EdgeIndex\n      let edgeCA: Graph.EdgeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        const a = Graph.addNode(mutable, \"A\")\n        const b = Graph.addNode(mutable, \"B\")\n        const c = Graph.addNode(mutable, \"C\")\n        edgeAB = Graph.addEdge(mutable, a, b, 10)\n        edgeBC = Graph.addEdge(mutable, b, c, 20)\n        edgeCA = Graph.addEdge(mutable, c, a, 30)\n        Graph.mapEdges(mutable, (data) => data * 2)\n      })\n\n      const edge0 = Graph.getEdge(graph, edgeAB!)\n      const edge1 = Graph.getEdge(graph, edgeBC!)\n      const edge2 = Graph.getEdge(graph, edgeCA!)\n\n      expect(Option.isSome(edge0)).toBe(true)\n      expect(Option.isSome(edge1)).toBe(true)\n      expect(Option.isSome(edge2)).toBe(true)\n\n      if (Option.isSome(edge0) && Option.isSome(edge1) && Option.isSome(edge2)) {\n        expect(edge0.value.data).toBe(20)\n        expect(edge1.value.data).toBe(40)\n        expect(edge2.value.data).toBe(60)\n      }\n    })\n\n    it(\"should modify graph in place during construction\", () => {\n      let edgeAB: Graph.EdgeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        const a = Graph.addNode(mutable, \"A\")\n        const b = Graph.addNode(mutable, \"B\")\n        edgeAB = Graph.addEdge(mutable, a, b, 10)\n\n        // Before transformation\n        const beforeData = Graph.getEdge(mutable, edgeAB!)\n        expect(Option.isSome(beforeData)).toBe(true)\n        if (Option.isSome(beforeData)) {\n          expect(beforeData.value.data).toBe(10)\n        }\n\n        // Apply transformation\n        Graph.mapEdges(mutable, (data) => data * 5)\n      })\n\n      // After transformation\n      const afterData = Graph.getEdge(graph, edgeAB!)\n      expect(Option.isSome(afterData)).toBe(true)\n      if (Option.isSome(afterData)) {\n        expect(afterData.value.data).toBe(50)\n      }\n    })\n  })\n\n  describe(\"reverse\", () => {\n    it(\"should reverse all edge directions\", () => {\n      let nodeA: Graph.NodeIndex\n      let nodeB: Graph.NodeIndex\n      let nodeC: Graph.NodeIndex\n      let edgeAB: Graph.EdgeIndex\n      let edgeBC: Graph.EdgeIndex\n      let edgeCA: Graph.EdgeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        nodeA = Graph.addNode(mutable, \"A\")\n        nodeB = Graph.addNode(mutable, \"B\")\n        nodeC = Graph.addNode(mutable, \"C\")\n        edgeAB = Graph.addEdge(mutable, nodeA, nodeB, 1) // A -> B\n        edgeBC = Graph.addEdge(mutable, nodeB, nodeC, 2) // B -> C\n        edgeCA = Graph.addEdge(mutable, nodeC, nodeA, 3) // C -> A\n        Graph.reverse(mutable) // Now B -> A, C -> B, A -> C\n      })\n\n      const edge0 = Graph.getEdge(graph, edgeAB!)\n      const edge1 = Graph.getEdge(graph, edgeBC!)\n      const edge2 = Graph.getEdge(graph, edgeCA!)\n\n      expect(Option.isSome(edge0)).toBe(true)\n      expect(Option.isSome(edge1)).toBe(true)\n      expect(Option.isSome(edge2)).toBe(true)\n\n      if (Option.isSome(edge0) && Option.isSome(edge1) && Option.isSome(edge2)) {\n        // Edge 0: was A -> B, now B -> A\n        expect(edge0.value.source).toBe(nodeB!)\n        expect(edge0.value.target).toBe(nodeA!)\n        expect(edge0.value.data).toBe(1)\n\n        // Edge 1: was B -> C, now C -> B\n        expect(edge1.value.source).toBe(nodeC!)\n        expect(edge1.value.target).toBe(nodeB!)\n        expect(edge1.value.data).toBe(2)\n\n        // Edge 2: was C -> A, now A -> C\n        expect(edge2.value.source).toBe(nodeA!)\n        expect(edge2.value.target).toBe(nodeC!)\n        expect(edge2.value.data).toBe(3)\n      }\n    })\n\n    it(\"should update adjacency lists correctly\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        const a = Graph.addNode(mutable, \"A\")\n        const b = Graph.addNode(mutable, \"B\")\n        const c = Graph.addNode(mutable, \"C\")\n        Graph.addEdge(mutable, a, b, 1) // A -> B\n        Graph.addEdge(mutable, a, c, 2) // A -> C\n        Graph.reverse(mutable) // Now B -> A, C -> A\n      })\n\n      // After reversal:\n      // - Node A should have no outgoing edges\n      // - Node B should have edge to A\n      // - Node C should have edge to A\n\n      const neighborsA = Graph.neighbors(graph, 0)\n      const neighborsB = Graph.neighbors(graph, 1)\n      const neighborsC = Graph.neighbors(graph, 2)\n\n      expect(Array.from(neighborsA)).toEqual([]) // A has no outgoing edges\n      expect(Array.from(neighborsB)).toEqual([0]) // B -> A\n      expect(Array.from(neighborsC)).toEqual([0]) // C -> A\n    })\n  })\n\n  describe(\"filterMapNodes\", () => {\n    it(\"should filter and transform nodes\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"active\")\n        Graph.addNode(mutable, \"inactive\")\n        Graph.addNode(mutable, \"active\")\n        Graph.addNode(mutable, \"pending\")\n\n        // Keep only \"active\" nodes and transform to uppercase\n        Graph.filterMapNodes(mutable, (data) => data === \"active\" ? Option.some(data.toUpperCase()) : Option.none())\n      })\n\n      // Should only have 2 nodes remaining (the \"active\" ones)\n      expect(Graph.nodeCount(graph)).toBe(2)\n\n      // Check the remaining nodes have been transformed\n      const nodeData0 = Graph.getNode(graph, 0)\n      const nodeData2 = Graph.getNode(graph, 2)\n\n      expect(Option.isSome(nodeData0)).toBe(true)\n      expect(Option.isSome(nodeData2)).toBe(true)\n\n      if (Option.isSome(nodeData0) && Option.isSome(nodeData2)) {\n        expect(nodeData0.value).toBe(\"ACTIVE\")\n        expect(nodeData2.value).toBe(\"ACTIVE\")\n      }\n\n      // Filtered out nodes should not exist\n      expect(Option.isNone(Graph.getNode(graph, 1))).toBe(true)\n      expect(Option.isNone(Graph.getNode(graph, 3))).toBe(true)\n    })\n\n    it(\"should remove edges connected to filtered nodes\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        const a = Graph.addNode(mutable, \"keep\")\n        const b = Graph.addNode(mutable, \"remove\")\n        const c = Graph.addNode(mutable, \"keep\")\n\n        Graph.addEdge(mutable, a, b, 1) // keep -> remove\n        Graph.addEdge(mutable, b, c, 2) // remove -> keep\n        Graph.addEdge(mutable, a, c, 3) // keep -> keep\n\n        // Filter out \"remove\" nodes\n        Graph.filterMapNodes(mutable, (data) => data === \"keep\" ? Option.some(data) : Option.none())\n      })\n\n      // Should have 2 nodes and 1 edge remaining\n      expect(Graph.nodeCount(graph)).toBe(2)\n      expect(Graph.edgeCount(graph)).toBe(1)\n\n      // Only the keep -> keep edge should remain\n      const remainingEdge = Graph.getEdge(graph, 2)\n      expect(Option.isSome(remainingEdge)).toBe(true)\n      if (Option.isSome(remainingEdge)) {\n        expect(remainingEdge.value.source).toBe(0)\n        expect(remainingEdge.value.target).toBe(2)\n        expect(remainingEdge.value.data).toBe(3)\n      }\n\n      // Edges involving removed node should be gone\n      expect(Option.isNone(Graph.getEdge(graph, 0))).toBe(true)\n      expect(Option.isNone(Graph.getEdge(graph, 1))).toBe(true)\n    })\n\n    it(\"should handle transformation without filtering\", () => {\n      const graph = Graph.directed<number, string>((mutable) => {\n        Graph.addNode(mutable, 1)\n        Graph.addNode(mutable, 2)\n        Graph.addNode(mutable, 3)\n\n        // Transform all nodes by doubling them\n        Graph.filterMapNodes(mutable, (data) => Option.some(data * 2))\n      })\n\n      expect(Graph.nodeCount(graph)).toBe(3)\n\n      const node0 = Graph.getNode(graph, 0)\n      const node1 = Graph.getNode(graph, 1)\n      const node2 = Graph.getNode(graph, 2)\n\n      expect(Option.isSome(node0)).toBe(true)\n      expect(Option.isSome(node1)).toBe(true)\n      expect(Option.isSome(node2)).toBe(true)\n\n      if (Option.isSome(node0) && Option.isSome(node1) && Option.isSome(node2)) {\n        expect(node0.value).toBe(2)\n        expect(node1.value).toBe(4)\n        expect(node2.value).toBe(6)\n      }\n    })\n\n    it(\"should handle filtering without transformation\", () => {\n      const graph = Graph.directed<number, string>((mutable) => {\n        Graph.addNode(mutable, 1)\n        Graph.addNode(mutable, 2)\n        Graph.addNode(mutable, 3)\n        Graph.addNode(mutable, 4)\n\n        // Keep only even numbers\n        Graph.filterMapNodes(mutable, (data) => data % 2 === 0 ? Option.some(data) : Option.none())\n      })\n\n      expect(Graph.nodeCount(graph)).toBe(2)\n\n      const node1 = Graph.getNode(graph, 1)\n      const node3 = Graph.getNode(graph, 3)\n\n      expect(Option.isSome(node1)).toBe(true)\n      expect(Option.isSome(node3)).toBe(true)\n\n      if (Option.isSome(node1) && Option.isSome(node3)) {\n        expect(node1.value).toBe(2)\n        expect(node3.value).toBe(4)\n      }\n\n      // Odd numbers should be removed\n      expect(Option.isNone(Graph.getNode(graph, 0))).toBe(true)\n      expect(Option.isNone(Graph.getNode(graph, 2))).toBe(true)\n    })\n  })\n\n  describe(\"filterMapEdges\", () => {\n    it(\"should filter and transform edges\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        const a = Graph.addNode(mutable, \"A\")\n        const b = Graph.addNode(mutable, \"B\")\n        const c = Graph.addNode(mutable, \"C\")\n        Graph.addEdge(mutable, a, b, 5) // Remove (< 10)\n        Graph.addEdge(mutable, b, c, 15) // Keep and double (30)\n        Graph.addEdge(mutable, c, a, 25) // Keep and double (50)\n\n        // Keep only edges with weight >= 10 and double their weight\n        Graph.filterMapEdges(mutable, (data) => data >= 10 ? Option.some(data * 2) : Option.none())\n      })\n\n      // Should have 2 edges remaining\n      expect(Graph.edgeCount(graph)).toBe(2)\n      expect(Graph.nodeCount(graph)).toBe(3) // All nodes should remain\n\n      // Check that remaining edges have been transformed\n      const edge1 = Graph.getEdge(graph, 1)\n      const edge2 = Graph.getEdge(graph, 2)\n\n      expect(Option.isSome(edge1)).toBe(true)\n      expect(Option.isSome(edge2)).toBe(true)\n\n      if (Option.isSome(edge1) && Option.isSome(edge2)) {\n        expect(edge1.value.data).toBe(30) // 15 * 2\n        expect(edge2.value.data).toBe(50) // 25 * 2\n      }\n\n      // Filtered out edge should not exist\n      expect(Option.isNone(Graph.getEdge(graph, 0))).toBe(true)\n    })\n\n    it(\"should update adjacency lists when removing edges\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        const a = Graph.addNode(mutable, \"A\")\n        const b = Graph.addNode(mutable, \"B\")\n        const c = Graph.addNode(mutable, \"C\")\n\n        Graph.addEdge(mutable, a, b, 1) // Keep\n        Graph.addEdge(mutable, a, c, 2) // Remove\n        Graph.addEdge(mutable, b, c, 3) // Keep\n\n        // Keep only odd numbers\n        Graph.filterMapEdges(mutable, (data) => data % 2 === 1 ? Option.some(data) : Option.none())\n      })\n\n      // Should have 2 edges remaining (1 and 3)\n      expect(Graph.edgeCount(graph)).toBe(2)\n\n      // Check adjacency: A should only connect to B now\n      const neighborsA = Array.from(Graph.neighbors(graph, 0))\n      expect(neighborsA).toEqual([1]) // A -> B only\n\n      // Check that B still connects to C\n      const neighborsB = Array.from(Graph.neighbors(graph, 1))\n      expect(neighborsB).toEqual([2]) // B -> C\n\n      // Check that C has no outgoing edges\n      const neighborsC = Array.from(Graph.neighbors(graph, 2))\n      expect(neighborsC).toEqual([]) // C has no outgoing edges\n    })\n\n    it(\"should handle transformation without filtering\", () => {\n      const graph = Graph.directed<string, number>((mutable) => {\n        const a = Graph.addNode(mutable, \"A\")\n        const b = Graph.addNode(mutable, \"B\")\n        const c = Graph.addNode(mutable, \"C\")\n        Graph.addEdge(mutable, a, b, 10)\n        Graph.addEdge(mutable, b, c, 20)\n        Graph.addEdge(mutable, c, a, 30)\n\n        // Transform all edges by adding 100\n        Graph.filterMapEdges(mutable, (data) => Option.some(data + 100))\n      })\n\n      expect(Graph.edgeCount(graph)).toBe(3)\n\n      const edge0 = Graph.getEdge(graph, 0)\n      const edge1 = Graph.getEdge(graph, 1)\n      const edge2 = Graph.getEdge(graph, 2)\n\n      expect(Option.isSome(edge0)).toBe(true)\n      expect(Option.isSome(edge1)).toBe(true)\n      expect(Option.isSome(edge2)).toBe(true)\n\n      if (Option.isSome(edge0) && Option.isSome(edge1) && Option.isSome(edge2)) {\n        expect(edge0.value.data).toBe(110)\n        expect(edge1.value.data).toBe(120)\n        expect(edge2.value.data).toBe(130)\n      }\n    })\n\n    it(\"should handle filtering without transformation\", () => {\n      const graph = Graph.directed<string, { weight: number; type: string }>((mutable) => {\n        const a = Graph.addNode(mutable, \"A\")\n        const b = Graph.addNode(mutable, \"B\")\n        const c = Graph.addNode(mutable, \"C\")\n        Graph.addEdge(mutable, a, b, { weight: 10, type: \"primary\" })\n        Graph.addEdge(mutable, b, c, { weight: 20, type: \"secondary\" })\n        Graph.addEdge(mutable, c, a, { weight: 30, type: \"primary\" })\n\n        // Keep only \"primary\" edges\n        Graph.filterMapEdges(mutable, (data) => data.type === \"primary\" ? Option.some(data) : Option.none())\n      })\n\n      expect(Graph.edgeCount(graph)).toBe(2)\n\n      const edge0 = Graph.getEdge(graph, 0)\n      const edge2 = Graph.getEdge(graph, 2)\n\n      expect(Option.isSome(edge0)).toBe(true)\n      expect(Option.isSome(edge2)).toBe(true)\n\n      if (Option.isSome(edge0) && Option.isSome(edge2)) {\n        expect(edge0.value.data.type).toBe(\"primary\")\n        expect(edge2.value.data.type).toBe(\"primary\")\n      }\n\n      // Secondary edge should be removed\n      expect(Option.isNone(Graph.getEdge(graph, 1))).toBe(true)\n    })\n  })\n\n  describe(\"filterNodes\", () => {\n    it(\"should filter nodes by predicate\", () => {\n      let activeNode1: Graph.NodeIndex\n      let inactiveNode: Graph.NodeIndex\n      let activeNode2: Graph.NodeIndex\n      let pendingNode: Graph.NodeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        activeNode1 = Graph.addNode(mutable, \"active\")\n        inactiveNode = Graph.addNode(mutable, \"inactive\")\n        activeNode2 = Graph.addNode(mutable, \"active\")\n        pendingNode = Graph.addNode(mutable, \"pending\")\n\n        // Keep only \"active\" nodes\n        Graph.filterNodes(mutable, (data) => data === \"active\")\n      })\n\n      expect(Graph.nodeCount(graph)).toBe(2)\n\n      const node0 = Graph.getNode(graph, activeNode1!)\n      const node2 = Graph.getNode(graph, activeNode2!)\n\n      expect(Option.isSome(node0)).toBe(true)\n      expect(Option.isSome(node2)).toBe(true)\n\n      if (Option.isSome(node0) && Option.isSome(node2)) {\n        expect(node0.value).toBe(\"active\")\n        expect(node2.value).toBe(\"active\")\n      }\n\n      // Filtered out nodes should be removed\n      expect(Option.isNone(Graph.getNode(graph, inactiveNode!))).toBe(true) // \"inactive\"\n      expect(Option.isNone(Graph.getNode(graph, pendingNode!))).toBe(true) // \"pending\"\n    })\n\n    it(\"should remove connected edges when filtering nodes\", () => {\n      let edgeAB: Graph.EdgeIndex\n      let edgeBC: Graph.EdgeIndex\n      let edgeAC: Graph.EdgeIndex\n\n      const graph = Graph.directed<string, string>((mutable) => {\n        const a = Graph.addNode(mutable, \"keep\")\n        const b = Graph.addNode(mutable, \"remove\")\n        const c = Graph.addNode(mutable, \"keep\")\n\n        edgeAB = Graph.addEdge(mutable, a, b, \"A-B\")\n        edgeBC = Graph.addEdge(mutable, b, c, \"B-C\")\n        edgeAC = Graph.addEdge(mutable, a, c, \"A-C\")\n\n        // Remove node \"remove\"\n        Graph.filterNodes(mutable, (data) => data === \"keep\")\n      })\n\n      expect(Graph.nodeCount(graph)).toBe(2) // Only \"keep\" nodes remain\n      expect(Graph.edgeCount(graph)).toBe(1) // Only A-C edge remains\n\n      // Check remaining edge\n      const edge2 = Graph.getEdge(graph, edgeAC!)\n      expect(Option.isSome(edge2)).toBe(true)\n      if (Option.isSome(edge2)) {\n        expect(edge2.value.data).toBe(\"A-C\")\n      }\n\n      // Check removed edges\n      expect(Option.isNone(Graph.getEdge(graph, edgeAB!))).toBe(true) // A-B removed\n      expect(Option.isNone(Graph.getEdge(graph, edgeBC!))).toBe(true) // B-C removed\n    })\n  })\n\n  describe(\"filterEdges\", () => {\n    it(\"should filter edges by predicate\", () => {\n      let edgeAB: Graph.EdgeIndex\n      let edgeBC: Graph.EdgeIndex\n      let edgeCA: Graph.EdgeIndex\n\n      const graph = Graph.directed<string, number>((mutable) => {\n        const a = Graph.addNode(mutable, \"A\")\n        const b = Graph.addNode(mutable, \"B\")\n        const c = Graph.addNode(mutable, \"C\")\n\n        edgeAB = Graph.addEdge(mutable, a, b, 5)\n        edgeBC = Graph.addEdge(mutable, b, c, 15)\n        edgeCA = Graph.addEdge(mutable, c, a, 25)\n\n        // Keep only edges with weight >= 10\n        Graph.filterEdges(mutable, (data) => data >= 10)\n      })\n\n      expect(Graph.nodeCount(graph)).toBe(3) // All nodes remain\n      expect(Graph.edgeCount(graph)).toBe(2) // Edge with weight 5 removed\n\n      const edge1 = Graph.getEdge(graph, edgeBC!)\n      const edge2 = Graph.getEdge(graph, edgeCA!)\n\n      expect(Option.isSome(edge1)).toBe(true)\n      expect(Option.isSome(edge2)).toBe(true)\n\n      if (Option.isSome(edge1) && Option.isSome(edge2)) {\n        expect(edge1.value.data).toBe(15)\n        expect(edge2.value.data).toBe(25)\n      }\n\n      // Edge with weight 5 should be removed\n      expect(Option.isNone(Graph.getEdge(graph, edgeAB!))).toBe(true)\n    })\n\n    it(\"should update adjacency lists when filtering edges\", () => {\n      let nodeA: Graph.NodeIndex\n      let nodeB: Graph.NodeIndex\n      let nodeC: Graph.NodeIndex\n\n      const graph = Graph.directed<string, string>((mutable) => {\n        nodeA = Graph.addNode(mutable, \"A\")\n        nodeB = Graph.addNode(mutable, \"B\")\n        nodeC = Graph.addNode(mutable, \"C\")\n\n        Graph.addEdge(mutable, nodeA, nodeB, \"primary\")\n        Graph.addEdge(mutable, nodeA, nodeC, \"secondary\")\n        Graph.addEdge(mutable, nodeB, nodeC, \"primary\")\n\n        // Keep only \"primary\" edges\n        Graph.filterEdges(mutable, (data) => data === \"primary\")\n      })\n\n      expect(Graph.edgeCount(graph)).toBe(2)\n\n      // Check adjacency - A should only connect to B now\n      const neighborsA = Array.from(Graph.neighbors(graph, nodeA!))\n      expect(neighborsA).toEqual([nodeB!]) // A -> B only\n\n      const neighborsB = Array.from(Graph.neighbors(graph, nodeB!))\n      expect(neighborsB).toEqual([nodeC!]) // B -> C\n\n      const neighborsC = Array.from(Graph.neighbors(graph, nodeC!))\n      expect(neighborsC).toEqual([]) // C has no outgoing edges\n    })\n  })\n\n  describe(\"addEdge\", () => {\n    it(\"should add an edge between two existing nodes\", () => {\n      let edgeIndex: Graph.EdgeIndex\n\n      const result = Graph.directed<string, number>((mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        edgeIndex = Graph.addEdge(mutable, nodeA, nodeB, 42)\n      })\n\n      expect(edgeIndex!).toBe(0)\n      expect(Graph.edgeCount(result)).toBe(1)\n    })\n\n    it(\"should add multiple edges with sequential indices\", () => {\n      let edgeA: Graph.EdgeIndex\n      let edgeB: Graph.EdgeIndex\n      let edgeC: Graph.EdgeIndex\n\n      const result = Graph.directed<string, number>((mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        const nodeC = Graph.addNode(mutable, \"Node C\")\n\n        edgeA = Graph.addEdge(mutable, nodeA, nodeB, 10)\n        edgeB = Graph.addEdge(mutable, nodeB, nodeC, 20)\n        edgeC = Graph.addEdge(mutable, nodeA, nodeC, 30)\n      })\n\n      expect(edgeA!).toBe(0)\n      expect(edgeB!).toBe(1)\n      expect(edgeC!).toBe(2)\n      expect(Graph.edgeCount(result)).toBe(3)\n    })\n\n    it(\"should throw error when source node doesn't exist\", () => {\n      expect(() => {\n        Graph.directed<string, number>((mutable) => {\n          const nodeB = Graph.addNode(mutable, \"Node B\")\n          const nonExistentNode = 999\n          Graph.addEdge(mutable, nonExistentNode, nodeB, 42)\n        })\n      }).toThrow(\"Node 999 does not exist\")\n    })\n\n    it(\"should throw error when target node doesn't exist\", () => {\n      expect(() => {\n        Graph.directed<string, number>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"Node A\")\n          const nonExistentNode = 999\n          Graph.addEdge(mutable, nodeA, nonExistentNode, 42)\n        })\n      }).toThrow(\"Node 999 does not exist\")\n    })\n  })\n\n  describe(\"removeNode\", () => {\n    it(\"should remove a node and all its incident edges\", () => {\n      const result = Graph.directed<string, number>((mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        const nodeC = Graph.addNode(mutable, \"Node C\")\n\n        Graph.addEdge(mutable, nodeA, nodeB, 10)\n        Graph.addEdge(mutable, nodeB, nodeC, 20)\n        Graph.addEdge(mutable, nodeC, nodeA, 30)\n\n        expect(Graph.nodeCount(mutable)).toBe(3)\n        expect(Graph.edgeCount(mutable)).toBe(3)\n\n        // Remove nodeB which has 2 incident edges\n        Graph.removeNode(mutable, nodeB)\n\n        expect(Graph.nodeCount(mutable)).toBe(2)\n        expect(Graph.edgeCount(mutable)).toBe(1) // Only nodeC -> nodeA edge remains\n      })\n\n      expect(Graph.nodeCount(result)).toBe(2)\n      expect(Graph.edgeCount(result)).toBe(1)\n    })\n\n    it(\"should handle removing non-existent node gracefully\", () => {\n      const result = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Node A\") // Just need one node for count\n        const nonExistentNode = 999\n\n        expect(Graph.nodeCount(mutable)).toBe(1)\n        Graph.removeNode(mutable, nonExistentNode) // Should not throw\n        expect(Graph.nodeCount(mutable)).toBe(1) // Should remain unchanged\n      })\n\n      expect(Graph.nodeCount(result)).toBe(1)\n    })\n\n    it(\"should handle isolated node removal\", () => {\n      const result = Graph.directed<string, number>((mutable) => {\n        Graph.addNode(mutable, \"Node A\") // Keep for final count\n        const nodeB = Graph.addNode(mutable, \"Node B\") // Isolated node to remove\n\n        expect(Graph.nodeCount(mutable)).toBe(2)\n        expect(Graph.edgeCount(mutable)).toBe(0)\n\n        Graph.removeNode(mutable, nodeB)\n\n        expect(Graph.nodeCount(mutable)).toBe(1)\n        expect(Graph.edgeCount(mutable)).toBe(0)\n      })\n\n      expect(Graph.nodeCount(result)).toBe(1)\n    })\n  })\n\n  describe(\"removeEdge\", () => {\n    it(\"should remove an edge between two nodes\", () => {\n      let edgeIndex: Graph.EdgeIndex\n\n      const result = Graph.directed<string, number>((mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        edgeIndex = Graph.addEdge(mutable, nodeA, nodeB, 42)\n\n        expect(Graph.edgeCount(mutable)).toBe(1)\n\n        Graph.removeEdge(mutable, edgeIndex)\n\n        expect(Graph.edgeCount(mutable)).toBe(0)\n      })\n\n      expect(Graph.edgeCount(result)).toBe(0)\n    })\n\n    it(\"should handle removing non-existent edge gracefully\", () => {\n      const result = Graph.directed<string, number>((mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n        Graph.addEdge(mutable, nodeA, nodeB, 42)\n\n        const nonExistentEdge = 999\n\n        expect(Graph.edgeCount(mutable)).toBe(1)\n        Graph.removeEdge(mutable, nonExistentEdge) // Should not throw\n        expect(Graph.edgeCount(mutable)).toBe(1) // Should remain unchanged\n      })\n\n      expect(Graph.edgeCount(result)).toBe(1)\n    })\n\n    it(\"should handle multiple edges between same nodes\", () => {\n      const result = Graph.directed<string, number>((mutable) => {\n        const nodeA = Graph.addNode(mutable, \"Node A\")\n        const nodeB = Graph.addNode(mutable, \"Node B\")\n\n        const edge1 = Graph.addEdge(mutable, nodeA, nodeB, 10)\n        const edge2 = Graph.addEdge(mutable, nodeA, nodeB, 20)\n\n        expect(Graph.edgeCount(mutable)).toBe(2)\n\n        Graph.removeEdge(mutable, edge1)\n\n        expect(Graph.edgeCount(mutable)).toBe(1)\n\n        // Verify second edge still exists\n        const edge2Data = mutable.edges.get(edge2)\n        expect(edge2Data).toBeDefined()\n      })\n\n      expect(Graph.edgeCount(result)).toBe(1)\n    })\n  })\n\n  describe(\"Edge query operations\", () => {\n    describe(\"getEdge\", () => {\n      it(\"should return edge data for existing edge\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"Node A\")\n          const nodeB = Graph.addNode(mutable, \"Node B\")\n          Graph.addEdge(mutable, nodeA, nodeB, 42)\n        })\n\n        const edgeIndex = 0\n        const edge = Graph.getEdge(graph, edgeIndex)\n\n        expect(Option.isSome(edge)).toBe(true)\n        if (Option.isSome(edge)) {\n          expect(edge.value.source).toBe(0)\n          expect(edge.value.target).toBe(1)\n          expect(edge.value.data).toBe(42)\n        }\n      })\n\n      it(\"should return None for non-existent edge\", () => {\n        const graph = Graph.directed<string, number>()\n        const edgeIndex = 999\n        const edge = Graph.getEdge(graph, edgeIndex)\n\n        expect(Option.isNone(edge)).toBe(true)\n      })\n    })\n\n    describe(\"hasEdge\", () => {\n      it(\"should return true for existing edge\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"Node A\")\n          const nodeB = Graph.addNode(mutable, \"Node B\")\n          Graph.addEdge(mutable, nodeA, nodeB, 42)\n        })\n\n        const nodeA = 0\n        const nodeB = 1\n\n        expect(Graph.hasEdge(graph, nodeA, nodeB)).toBe(true)\n      })\n\n      it(\"should return false for non-existent edge\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"Node A\")\n          const nodeB = Graph.addNode(mutable, \"Node B\")\n          Graph.addNode(mutable, \"Node C\")\n          Graph.addEdge(mutable, nodeA, nodeB, 42)\n        })\n\n        const nodeA = 0\n        const nodeC = 2\n\n        expect(Graph.hasEdge(graph, nodeA, nodeC)).toBe(false)\n      })\n\n      it(\"should return false for non-existent source node\", () => {\n        const graph = Graph.directed<string, number>()\n        const nodeA = 0\n        const nodeB = 1\n\n        expect(Graph.hasEdge(graph, nodeA, nodeB)).toBe(false)\n      })\n    })\n\n    describe(\"edgeCount\", () => {\n      it(\"should return 0 for empty graph\", () => {\n        const graph = Graph.directed<string, number>()\n        expect(Graph.edgeCount(graph)).toBe(0)\n      })\n\n      it(\"should return correct edge count\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"Node A\")\n          const nodeB = Graph.addNode(mutable, \"Node B\")\n          const nodeC = Graph.addNode(mutable, \"Node C\")\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n          Graph.addEdge(mutable, nodeB, nodeC, 2)\n          Graph.addEdge(mutable, nodeC, nodeA, 3)\n        })\n\n        expect(Graph.edgeCount(graph)).toBe(3)\n      })\n    })\n\n    describe(\"neighbors\", () => {\n      it(\"should return correct neighbors for directed graph\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"Node A\")\n          const nodeB = Graph.addNode(mutable, \"Node B\")\n          const nodeC = Graph.addNode(mutable, \"Node C\")\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n          Graph.addEdge(mutable, nodeA, nodeC, 2)\n        })\n\n        const nodeA = 0\n        const nodeB = 1\n        const nodeC = 2\n\n        const neighborsA = Graph.neighbors(graph, nodeA)\n        expect(neighborsA).toContain(nodeB)\n        expect(neighborsA).toContain(nodeC)\n        expect(neighborsA).toHaveLength(2)\n\n        const neighborsB = Graph.neighbors(graph, nodeB)\n        expect(neighborsB).toEqual([])\n      })\n    })\n\n    describe(\"neighbors with undirected graphs\", () => {\n      it(\"should return correct neighbors for single edge\", () => {\n        const graph = Graph.undirected<number, void>((mutable) => {\n          Graph.addNode(mutable, 0)\n          Graph.addNode(mutable, 1)\n          Graph.addEdge(mutable, 0, 1, undefined)\n        })\n\n        expect(Graph.neighbors(graph, 0)).toEqual([1])\n        expect(Graph.neighbors(graph, 1)).toEqual([0])\n      })\n\n      it(\"should return correct neighbors for linear graph\", () => {\n        const graph = Graph.undirected<number, void>((mutable) => {\n          Graph.addNode(mutable, 0)\n          Graph.addNode(mutable, 1)\n          Graph.addNode(mutable, 2)\n          Graph.addEdge(mutable, 0, 1, undefined)\n          Graph.addEdge(mutable, 1, 2, undefined)\n        })\n\n        expect(Graph.neighbors(graph, 0)).toEqual([1])\n        expect(Graph.neighbors(graph, 1).sort()).toEqual([0, 2])\n        expect(Graph.neighbors(graph, 2)).toEqual([1])\n      })\n\n      it(\"should handle multiple edges between same nodes\", () => {\n        const graph = Graph.undirected<number, void>((mutable) => {\n          Graph.addNode(mutable, 0)\n          Graph.addNode(mutable, 1)\n          Graph.addEdge(mutable, 0, 1, undefined)\n          Graph.addEdge(mutable, 0, 1, undefined)\n        })\n\n        // Should deduplicate neighbors\n        expect(Graph.neighbors(graph, 0)).toEqual([1])\n        expect(Graph.neighbors(graph, 1)).toEqual([0])\n      })\n\n      it(\"should handle self-loops\", () => {\n        const graph = Graph.undirected<number, void>((mutable) => {\n          Graph.addNode(mutable, 0)\n          Graph.addEdge(mutable, 0, 0, undefined)\n        })\n\n        expect(Graph.neighbors(graph, 0)).toEqual([0])\n      })\n\n      it(\"should handle node with no neighbors\", () => {\n        const graph = Graph.undirected<number, void>((mutable) => {\n          Graph.addNode(mutable, 0)\n          Graph.addNode(mutable, 1)\n        })\n\n        expect(Graph.neighbors(graph, 0)).toEqual([])\n        expect(Graph.neighbors(graph, 1)).toEqual([])\n      })\n    })\n\n    describe(\"neighborsDirected\", () => {\n      it(\"should return incoming neighbors\", () => {\n        let nodeA: Graph.NodeIndex\n        let nodeB: Graph.NodeIndex\n        let nodeC: Graph.NodeIndex\n\n        const graph = Graph.directed<string, number>((mutable) => {\n          nodeA = Graph.addNode(mutable, \"Node A\")\n          nodeB = Graph.addNode(mutable, \"Node B\")\n          nodeC = Graph.addNode(mutable, \"Node C\")\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n          Graph.addEdge(mutable, nodeC, nodeB, 2)\n        })\n\n        const incomingB = Graph.neighborsDirected(graph, nodeB!, \"incoming\")\n        expect(incomingB.sort()).toEqual([nodeA!, nodeC!].sort())\n\n        const incomingA = Graph.neighborsDirected(graph, nodeA!, \"incoming\")\n        expect(incomingA).toEqual([])\n      })\n\n      it(\"should return outgoing neighbors\", () => {\n        let nodeA: Graph.NodeIndex\n        let nodeB: Graph.NodeIndex\n        let nodeC: Graph.NodeIndex\n\n        const graph = Graph.directed<string, number>((mutable) => {\n          nodeA = Graph.addNode(mutable, \"Node A\")\n          nodeB = Graph.addNode(mutable, \"Node B\")\n          nodeC = Graph.addNode(mutable, \"Node C\")\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n          Graph.addEdge(mutable, nodeA, nodeC, 2)\n        })\n\n        const outgoingA = Graph.neighborsDirected(graph, nodeA!, \"outgoing\")\n        expect(outgoingA.sort()).toEqual([nodeB!, nodeC!].sort())\n\n        const outgoingB = Graph.neighborsDirected(graph, nodeB!, \"outgoing\")\n        expect(outgoingB).toEqual([])\n      })\n\n      it(\"should handle node with no connections\", () => {\n        let nodeA: Graph.NodeIndex\n\n        const graph = Graph.directed<string, number>((mutable) => {\n          nodeA = Graph.addNode(mutable, \"Node A\")\n        })\n\n        expect(Graph.neighborsDirected(graph, nodeA!, \"incoming\")).toEqual([])\n        expect(Graph.neighborsDirected(graph, nodeA!, \"outgoing\")).toEqual([])\n      })\n    })\n  })\n\n  describe(\"GraphViz export\", () => {\n    describe(\"toGraphViz\", () => {\n      it(\"should export empty directed graph\", () => {\n        const graph = Graph.directed<string, number>()\n        const dot = Graph.toGraphViz(graph)\n\n        expect(dot).toBe(\"digraph G {\\n}\")\n      })\n\n      it(\"should export empty undirected graph\", () => {\n        const graph = Graph.undirected<string, number>()\n        const dot = Graph.toGraphViz(graph)\n\n        expect(dot).toBe(\"graph G {\\n}\")\n      })\n\n      it(\"should export directed graph with nodes and edges\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"Node A\")\n          const nodeB = Graph.addNode(mutable, \"Node B\")\n          const nodeC = Graph.addNode(mutable, \"Node C\")\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n          Graph.addEdge(mutable, nodeB, nodeC, 2)\n          Graph.addEdge(mutable, nodeC, nodeA, 3)\n        })\n\n        const dot = Graph.toGraphViz(graph)\n\n        expect(dot).toContain(\"digraph G {\")\n        expect(dot).toContain(\"\\\"0\\\" [label=\\\"Node A\\\"];\")\n        expect(dot).toContain(\"\\\"1\\\" [label=\\\"Node B\\\"];\")\n        expect(dot).toContain(\"\\\"2\\\" [label=\\\"Node C\\\"];\")\n        expect(dot).toContain(\"\\\"0\\\" -> \\\"1\\\" [label=\\\"1\\\"];\")\n        expect(dot).toContain(\"\\\"1\\\" -> \\\"2\\\" [label=\\\"2\\\"];\")\n        expect(dot).toContain(\"\\\"2\\\" -> \\\"0\\\" [label=\\\"3\\\"];\")\n        expect(dot).toContain(\"}\")\n      })\n\n      it(\"should export undirected graph with correct edge format\", () => {\n        const graph = Graph.undirected<string, number>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"A\")\n          const nodeB = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n        })\n\n        const dot = Graph.toGraphViz(graph)\n\n        expect(dot).toContain(\"graph G {\")\n        expect(dot).toContain(\"\\\"0\\\" -- \\\"1\\\" [label=\\\"1\\\"];\")\n      })\n\n      it(\"should support custom node and edge labels\", () => {\n        const graph = Graph.directed<{ name: string }, { weight: number }>((mutable) => {\n          const nodeA = Graph.addNode(mutable, { name: \"Alice\" })\n          const nodeB = Graph.addNode(mutable, { name: \"Bob\" })\n          Graph.addEdge(mutable, nodeA, nodeB, { weight: 42 })\n        })\n\n        const dot = Graph.toGraphViz(graph, {\n          nodeLabel: (data) => data.name,\n          edgeLabel: (data) => `weight: ${data.weight}`,\n          graphName: \"MyGraph\"\n        })\n\n        expect(dot).toContain(\"digraph MyGraph {\")\n        expect(dot).toContain(\"\\\"0\\\" [label=\\\"Alice\\\"];\")\n        expect(dot).toContain(\"\\\"1\\\" [label=\\\"Bob\\\"];\")\n        expect(dot).toContain(\"\\\"0\\\" -> \\\"1\\\" [label=\\\"weight: 42\\\"];\")\n      })\n\n      it(\"should escape quotes in labels\", () => {\n        const graph = Graph.directed<string, string>((mutable) => {\n          const nodeA = Graph.addNode(mutable, \"Node \\\"A\\\"\")\n          const nodeB = Graph.addNode(mutable, \"Node \\\"B\\\"\")\n          Graph.addEdge(mutable, nodeA, nodeB, \"Edge \\\"1\\\"\")\n        })\n\n        const dot = Graph.toGraphViz(graph)\n\n        expect(dot).toContain(\"\\\"0\\\" [label=\\\"Node \\\\\\\"A\\\\\\\"\\\"];\")\n        expect(dot).toContain(\"\\\"1\\\" [label=\\\"Node \\\\\\\"B\\\\\\\"\\\"];\")\n        expect(dot).toContain(\"\\\"0\\\" -> \\\"1\\\" [label=\\\"Edge \\\\\\\"1\\\\\\\"\\\"];\")\n      })\n\n      it(\"should demonstrate graph visualization\", () => {\n        // Create a simple directed graph representing a dependency graph\n        const graph = Graph.directed<string, string>((mutable) => {\n          const app = Graph.addNode(mutable, \"App\")\n          const auth = Graph.addNode(mutable, \"Auth\")\n          const db = Graph.addNode(mutable, \"Database\")\n          const cache = Graph.addNode(mutable, \"Cache\")\n\n          Graph.addEdge(mutable, app, auth, \"uses\")\n          Graph.addEdge(mutable, app, db, \"stores\")\n          Graph.addEdge(mutable, auth, db, \"validates\")\n          Graph.addEdge(mutable, app, cache, \"caches\")\n        })\n\n        const dot = Graph.toGraphViz(graph, {\n          graphName: \"DependencyGraph\"\n        })\n\n        // Uncomment the next line to see the GraphViz output in test console\n        // console.log(\"\\nDependency Graph DOT format:\\n\" + dot)\n\n        expect(dot).toContain(\"digraph DependencyGraph {\")\n        expect(dot).toContain(\"\\\"0\\\" [label=\\\"App\\\"];\")\n        expect(dot).toContain(\"\\\"0\\\" -> \\\"1\\\" [label=\\\"uses\\\"];\")\n        expect(dot).toContain(\"\\\"0\\\" -> \\\"2\\\" [label=\\\"stores\\\"];\")\n        expect(dot).toContain(\"\\\"1\\\" -> \\\"2\\\" [label=\\\"validates\\\"];\")\n        expect(dot).toContain(\"\\\"0\\\" -> \\\"3\\\" [label=\\\"caches\\\"];\")\n      })\n\n      it(\"should demonstrate undirected graph visualization\", () => {\n        // Create a simple social network graph\n        const graph = Graph.undirected<string, string>((mutable) => {\n          const alice = Graph.addNode(mutable, \"Alice\")\n          const bob = Graph.addNode(mutable, \"Bob\")\n          const charlie = Graph.addNode(mutable, \"Charlie\")\n          const diana = Graph.addNode(mutable, \"Diana\")\n\n          Graph.addEdge(mutable, alice, bob, \"friends\")\n          Graph.addEdge(mutable, bob, charlie, \"friends\")\n          Graph.addEdge(mutable, charlie, diana, \"friends\")\n          Graph.addEdge(mutable, alice, diana, \"friends\")\n        })\n\n        const dot = Graph.toGraphViz(graph, {\n          graphName: \"SocialNetwork\"\n        })\n\n        // Uncomment the next line to see the GraphViz output in test console\n        // console.log(\"\\nSocial Network DOT format:\\n\" + dot)\n\n        expect(dot).toContain(\"graph SocialNetwork {\")\n        expect(dot).toContain(\"\\\"0\\\" [label=\\\"Alice\\\"];\")\n        expect(dot).toContain(\"\\\"0\\\" -- \\\"1\\\" [label=\\\"friends\\\"];\")\n        expect(dot).toContain(\"\\\"1\\\" -- \\\"2\\\" [label=\\\"friends\\\"];\")\n        expect(dot).toContain(\"\\\"2\\\" -- \\\"3\\\" [label=\\\"friends\\\"];\")\n        expect(dot).toContain(\"\\\"0\\\" -- \\\"3\\\" [label=\\\"friends\\\"];\")\n      })\n    })\n\n    describe(\"toMermaid\", () => {\n      it(\"should export empty directed graph\", () => {\n        const graph = Graph.directed<string, number>()\n        const mermaid = Graph.toMermaid(graph)\n        expect(mermaid).toBe(\"flowchart TD\")\n      })\n\n      it(\"should export empty undirected graph\", () => {\n        const graph = Graph.undirected<string, number>()\n        const mermaid = Graph.toMermaid(graph)\n        expect(mermaid).toBe(\"graph TD\")\n      })\n\n      it(\"should export directed graph with nodes\", () => {\n        const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n          Graph.addNode(mutable, \"Node A\")\n          Graph.addNode(mutable, \"Node B\")\n          Graph.addNode(mutable, \"Node C\")\n        })\n\n        const mermaid = Graph.toMermaid(graph)\n        expect(mermaid).toContain(\"flowchart TD\")\n        expect(mermaid).toContain(\"0[\\\"Node A\\\"]\")\n        expect(mermaid).toContain(\"1[\\\"Node B\\\"]\")\n        expect(mermaid).toContain(\"2[\\\"Node C\\\"]\")\n      })\n\n      it(\"should export undirected graph with nodes\", () => {\n        const graph = Graph.mutate(Graph.undirected<string, number>(), (mutable) => {\n          Graph.addNode(mutable, \"Alice\")\n          Graph.addNode(mutable, \"Bob\")\n        })\n\n        const mermaid = Graph.toMermaid(graph)\n        expect(mermaid).toContain(\"graph TD\")\n        expect(mermaid).toContain(\"0[\\\"Alice\\\"]\")\n        expect(mermaid).toContain(\"1[\\\"Bob\\\"]\")\n      })\n\n      it(\"should support all node shapes\", () => {\n        const shapes: Array<[string, Graph.MermaidNodeShape]> = [\n          [\"rectangle\", \"rectangle\"],\n          [\"rounded\", \"rounded\"],\n          [\"circle\", \"circle\"],\n          [\"diamond\", \"diamond\"],\n          [\"hexagon\", \"hexagon\"],\n          [\"stadium\", \"stadium\"],\n          [\"subroutine\", \"subroutine\"],\n          [\"cylindrical\", \"cylindrical\"]\n        ]\n\n        shapes.forEach(([shapeName, shapeValue]) => {\n          const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n            Graph.addNode(mutable, \"Test\")\n          })\n\n          const mermaid = Graph.toMermaid(graph, {\n            nodeShape: () => shapeValue\n          })\n\n          expect(mermaid).toContain(\"flowchart TD\")\n\n          // Test expected shape format\n          switch (shapeName) {\n            case \"rectangle\":\n              expect(mermaid).toContain(\"0[\\\"Test\\\"]\")\n              break\n            case \"rounded\":\n              expect(mermaid).toContain(\"0(\\\"Test\\\")\")\n              break\n            case \"circle\":\n              expect(mermaid).toContain(\"0((\\\"Test\\\"))\")\n              break\n            case \"diamond\":\n              expect(mermaid).toContain(\"0{\\\"Test\\\"}\")\n              break\n            case \"hexagon\":\n              expect(mermaid).toContain(\"0{{\\\"Test\\\"}}\")\n              break\n            case \"stadium\":\n              expect(mermaid).toContain(\"0([\\\"Test\\\"])\")\n              break\n            case \"subroutine\":\n              expect(mermaid).toContain(\"0[[\\\"Test\\\"]]\")\n              break\n            case \"cylindrical\":\n              expect(mermaid).toContain(\"0[(\\\"Test\\\")]\")\n              break\n          }\n        })\n      })\n\n      it(\"should escape special characters in labels\", () => {\n        const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n          Graph.addNode(mutable, \"Node with \\\"quotes\\\"\")\n          Graph.addNode(mutable, \"Node with [brackets]\")\n          Graph.addNode(mutable, \"Node with | pipe\")\n          Graph.addNode(mutable, \"Node with \\\\ backslash\")\n          Graph.addNode(mutable, \"Node with \\n newline\")\n        })\n\n        const mermaid = Graph.toMermaid(graph)\n\n        expect(mermaid).toContain(\"0[\\\"Node with #quot;quotes#quot;\\\"]\")\n        expect(mermaid).toContain(\"1[\\\"Node with #91;brackets#93;\\\"]\")\n        expect(mermaid).toContain(\"2[\\\"Node with #124; pipe\\\"]\")\n        expect(mermaid).toContain(\"3[\\\"Node with #92; backslash\\\"]\")\n        expect(mermaid).toContain(\"4[\\\"Node with <br/> newline\\\"]\")\n      })\n\n      it(\"should export directed graph with edges\", () => {\n        const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n          const nodeA = Graph.addNode(mutable, \"Node A\")\n          const nodeB = Graph.addNode(mutable, \"Node B\")\n          const nodeC = Graph.addNode(mutable, \"Node C\")\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n          Graph.addEdge(mutable, nodeB, nodeC, 2)\n          Graph.addEdge(mutable, nodeC, nodeA, 3)\n        })\n\n        const mermaid = Graph.toMermaid(graph)\n        expect(mermaid).toContain(\"flowchart TD\")\n        expect(mermaid).toContain(\"0[\\\"Node A\\\"]\")\n        expect(mermaid).toContain(\"1[\\\"Node B\\\"]\")\n        expect(mermaid).toContain(\"2[\\\"Node C\\\"]\")\n        expect(mermaid).toContain(\"0 -->|\\\"1\\\"| 1\")\n        expect(mermaid).toContain(\"1 -->|\\\"2\\\"| 2\")\n        expect(mermaid).toContain(\"2 -->|\\\"3\\\"| 0\")\n      })\n\n      it(\"should export undirected graph with edges\", () => {\n        const graph = Graph.mutate(Graph.undirected<string, string>(), (mutable) => {\n          const alice = Graph.addNode(mutable, \"Alice\")\n          const bob = Graph.addNode(mutable, \"Bob\")\n          const charlie = Graph.addNode(mutable, \"Charlie\")\n          Graph.addEdge(mutable, alice, bob, \"friends\")\n          Graph.addEdge(mutable, bob, charlie, \"colleagues\")\n        })\n\n        const mermaid = Graph.toMermaid(graph)\n        expect(mermaid).toContain(\"graph TD\")\n        expect(mermaid).toContain(\"0[\\\"Alice\\\"]\")\n        expect(mermaid).toContain(\"1[\\\"Bob\\\"]\")\n        expect(mermaid).toContain(\"2[\\\"Charlie\\\"]\")\n        expect(mermaid).toContain(\"0 ---|\\\"friends\\\"| 1\")\n        expect(mermaid).toContain(\"1 ---|\\\"colleagues\\\"| 2\")\n      })\n\n      it(\"should handle empty edge labels\", () => {\n        const graph = Graph.mutate(Graph.directed<string, string>(), (mutable) => {\n          const nodeA = Graph.addNode(mutable, \"A\")\n          const nodeB = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, nodeA, nodeB, \"\")\n        })\n\n        const mermaid = Graph.toMermaid(graph)\n        expect(mermaid).toContain(\"0 --> 1\")\n      })\n\n      it(\"should support all diagram directions\", () => {\n        const directions: Array<Graph.MermaidDirection> = [\"TB\", \"TD\", \"BT\", \"RL\", \"LR\"]\n\n        directions.forEach((dir) => {\n          const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n            Graph.addNode(mutable, \"A\")\n            Graph.addNode(mutable, \"B\")\n          })\n\n          const mermaid = Graph.toMermaid(graph, { direction: dir })\n          expect(mermaid).toContain(`flowchart ${dir}`)\n          expect(mermaid).toContain(\"0[\\\"A\\\"]\")\n          expect(mermaid).toContain(\"1[\\\"B\\\"]\")\n        })\n      })\n\n      it(\"should auto-detect diagram type based on graph type\", () => {\n        // Directed graph should auto-detect as flowchart\n        const directedGraph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n          Graph.addNode(mutable, \"A\")\n        })\n        const directedMermaid = Graph.toMermaid(directedGraph)\n        expect(directedMermaid).toContain(\"flowchart TD\")\n\n        // Undirected graph should auto-detect as graph\n        const undirectedGraph = Graph.mutate(Graph.undirected<string, number>(), (mutable) => {\n          Graph.addNode(mutable, \"A\")\n        })\n        const undirectedMermaid = Graph.toMermaid(undirectedGraph)\n        expect(undirectedMermaid).toContain(\"graph TD\")\n      })\n\n      it(\"should allow manual diagram type override\", () => {\n        // Override directed graph to use 'graph' type\n        const directedGraph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n          Graph.addNode(mutable, \"A\")\n        })\n        const overriddenMermaid = Graph.toMermaid(directedGraph, {\n          diagramType: \"graph\"\n        })\n        expect(overriddenMermaid).toContain(\"graph TD\")\n\n        // Override undirected graph to use 'flowchart' type\n        const undirectedGraph = Graph.mutate(Graph.undirected<string, number>(), (mutable) => {\n          Graph.addNode(mutable, \"B\")\n        })\n        const overriddenFlowchart = Graph.toMermaid(undirectedGraph, {\n          diagramType: \"flowchart\"\n        })\n        expect(overriddenFlowchart).toContain(\"flowchart TD\")\n      })\n\n      it(\"should combine direction and diagram type options\", () => {\n        const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n          Graph.addNode(mutable, \"Test\")\n        })\n\n        const mermaid = Graph.toMermaid(graph, {\n          direction: \"LR\",\n          diagramType: \"graph\"\n        })\n\n        expect(mermaid).toContain(\"graph LR\")\n        expect(mermaid).toContain(\"0[\\\"Test\\\"]\")\n      })\n\n      it(\"should handle self-loops correctly\", () => {\n        const graph = Graph.mutate(Graph.directed<string, string>(), (mutable) => {\n          const nodeA = Graph.addNode(mutable, \"A\")\n          Graph.addEdge(mutable, nodeA, nodeA, \"self\")\n        })\n\n        const mermaid = Graph.toMermaid(graph)\n        expect(mermaid).toContain(\"flowchart TD\")\n        expect(mermaid).toContain(\"0[\\\"A\\\"]\")\n        expect(mermaid).toContain(\"0 -->|\\\"self\\\"| 0\")\n      })\n\n      it(\"should handle multi-edges correctly\", () => {\n        const graph = Graph.mutate(Graph.directed<string, number>(), (mutable) => {\n          const nodeA = Graph.addNode(mutable, \"A\")\n          const nodeB = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n          Graph.addEdge(mutable, nodeA, nodeB, 2)\n          Graph.addEdge(mutable, nodeA, nodeB, 3)\n        })\n\n        const mermaid = Graph.toMermaid(graph)\n        expect(mermaid).toContain(\"flowchart TD\")\n        expect(mermaid).toContain(\"0[\\\"A\\\"]\")\n        expect(mermaid).toContain(\"1[\\\"B\\\"]\")\n        // Should contain all three edges\n        expect(mermaid).toContain(\"0 -->|\\\"1\\\"| 1\")\n        expect(mermaid).toContain(\"0 -->|\\\"2\\\"| 1\")\n        expect(mermaid).toContain(\"0 -->|\\\"3\\\"| 1\")\n      })\n\n      it(\"should handle disconnected components\", () => {\n        const graph = Graph.mutate(Graph.directed<string, string>(), (mutable) => {\n          // Component 1: A -> B\n          const nodeA = Graph.addNode(mutable, \"A\")\n          const nodeB = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, nodeA, nodeB, \"A->B\")\n\n          // Component 2: C -> D (disconnected)\n          const nodeC = Graph.addNode(mutable, \"C\")\n          const nodeD = Graph.addNode(mutable, \"D\")\n          Graph.addEdge(mutable, nodeC, nodeD, \"C->D\")\n\n          // Isolated node E\n          Graph.addNode(mutable, \"E\")\n        })\n\n        const mermaid = Graph.toMermaid(graph)\n        expect(mermaid).toContain(\"flowchart TD\")\n        expect(mermaid).toContain(\"0[\\\"A\\\"]\")\n        expect(mermaid).toContain(\"1[\\\"B\\\"]\")\n        expect(mermaid).toContain(\"2[\\\"C\\\"]\")\n        expect(mermaid).toContain(\"3[\\\"D\\\"]\")\n        expect(mermaid).toContain(\"4[\\\"E\\\"]\")\n        expect(mermaid).toContain(\"0 -->|\\\"A-#gt;B\\\"| 1\")\n        expect(mermaid).toContain(\"2 -->|\\\"C-#gt;D\\\"| 3\")\n      })\n\n      it(\"should handle custom labels with complex data\", () => {\n        interface NodeData {\n          id: string\n          value: number\n          metadata: { type: string }\n        }\n\n        interface EdgeData {\n          weight: number\n          type: string\n        }\n\n        const graph = Graph.mutate(Graph.directed<NodeData, EdgeData>(), (mutable) => {\n          const node1 = Graph.addNode(mutable, {\n            id: \"node1\",\n            value: 42,\n            metadata: { type: \"input\" }\n          })\n          const node2 = Graph.addNode(mutable, {\n            id: \"node2\",\n            value: 84,\n            metadata: { type: \"processing\" }\n          })\n          Graph.addEdge(mutable, node1, node2, { weight: 1.5, type: \"data\" })\n        })\n\n        const mermaid = Graph.toMermaid(graph, {\n          nodeLabel: (data) => `${data.id}:${data.value}`,\n          edgeLabel: (data) => `${data.type}(${data.weight})`,\n          direction: \"LR\"\n        })\n\n        expect(mermaid).toContain(\"flowchart LR\")\n        expect(mermaid).toContain(\"0[\\\"node1:42\\\"]\")\n        expect(mermaid).toContain(\"1[\\\"node2:84\\\"]\")\n        expect(mermaid).toContain(\"0 -->|\\\"data#40;1.5#41;\\\"| 1\")\n      })\n    })\n  })\n\n  describe(\"Graph Structure Analysis Algorithms (Phase 5A)\", () => {\n    describe(\"isAcyclic\", () => {\n      it(\"should detect acyclic directed graphs (DAGs)\", () => {\n        const dag = Graph.directed<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n          Graph.addEdge(mutable, a, b, \"A->B\")\n          Graph.addEdge(mutable, a, c, \"A->C\")\n          Graph.addEdge(mutable, b, d, \"B->D\")\n          Graph.addEdge(mutable, c, d, \"C->D\")\n        })\n\n        expect(Graph.isAcyclic(dag)).toBe(true)\n      })\n\n      it(\"should detect cycles in directed graphs\", () => {\n        const cyclic = Graph.directed<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, \"A->B\")\n          Graph.addEdge(mutable, b, c, \"B->C\")\n          Graph.addEdge(mutable, c, a, \"C->A\") // Creates cycle\n        })\n\n        expect(Graph.isAcyclic(cyclic)).toBe(false)\n      })\n\n      it(\"should handle disconnected components\", () => {\n        const disconnected = Graph.directed<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n          Graph.addEdge(mutable, a, b, \"A->B\") // Component 1: A->B (acyclic)\n          Graph.addEdge(mutable, c, d, \"C->D\") // Component 2: C->D (acyclic)\n          // No connections between components\n        })\n\n        expect(Graph.isAcyclic(disconnected)).toBe(true)\n      })\n\n      it(\"should detect cycles in one component of disconnected graph\", () => {\n        const mixedComponents = Graph.directed<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n          Graph.addEdge(mutable, a, b, \"A->B\") // Component 1: A->B (acyclic)\n          Graph.addEdge(mutable, c, d, \"C->D\") // Component 2: C->D->C (cyclic)\n          Graph.addEdge(mutable, d, c, \"D->C\")\n        })\n\n        expect(Graph.isAcyclic(mixedComponents)).toBe(false)\n      })\n    })\n\n    describe(\"isBipartite\", () => {\n      it(\"should detect bipartite undirected graphs\", () => {\n        const bipartite = Graph.undirected<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n          Graph.addEdge(mutable, a, b, \"edge\") // Set 1: {A, C}, Set 2: {B, D}\n          Graph.addEdge(mutable, b, c, \"edge\")\n          Graph.addEdge(mutable, c, d, \"edge\")\n          Graph.addEdge(mutable, d, a, \"edge\")\n        })\n\n        expect(Graph.isBipartite(bipartite)).toBe(true)\n      })\n\n      it(\"should detect non-bipartite graphs (odd cycles)\", () => {\n        const triangle = Graph.undirected<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, \"edge\")\n          Graph.addEdge(mutable, b, c, \"edge\")\n          Graph.addEdge(mutable, c, a, \"edge\") // Triangle (3-cycle)\n        })\n\n        expect(Graph.isBipartite(triangle)).toBe(false)\n      })\n\n      it(\"should handle path graphs (always bipartite)\", () => {\n        const path = Graph.undirected<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n          Graph.addEdge(mutable, a, b, \"edge\")\n          Graph.addEdge(mutable, b, c, \"edge\")\n          Graph.addEdge(mutable, c, d, \"edge\")\n        })\n\n        expect(Graph.isBipartite(path)).toBe(true)\n      })\n\n      it(\"should handle disconnected components\", () => {\n        const disconnected = Graph.undirected<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n          Graph.addEdge(mutable, a, b, \"edge\") // Component 1: A-B (bipartite)\n          Graph.addEdge(mutable, c, d, \"edge\") // Component 2: C-D (bipartite)\n          // No connections between components\n        })\n\n        expect(Graph.isBipartite(disconnected)).toBe(true)\n      })\n\n      it(\"should detect non-bipartite component in disconnected graph\", () => {\n        const mixedComponents = Graph.undirected<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n          const e = Graph.addNode(mutable, \"E\")\n          Graph.addEdge(mutable, a, b, \"edge\") // Component 1: A-B (bipartite)\n          Graph.addEdge(mutable, c, d, \"edge\") // Component 2: triangle (non-bipartite)\n          Graph.addEdge(mutable, d, e, \"edge\")\n          Graph.addEdge(mutable, e, c, \"edge\")\n        })\n\n        expect(Graph.isBipartite(mixedComponents)).toBe(false)\n      })\n    })\n\n    describe(\"connectedComponents\", () => {\n      it(\"should find connected components in disconnected undirected graph\", () => {\n        const graph = Graph.undirected<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n          Graph.addNode(mutable, \"E\")\n          Graph.addEdge(mutable, a, b, \"edge\") // Component 1: A-B\n          Graph.addEdge(mutable, c, d, \"edge\") // Component 2: C-D\n          // E is isolated - Component 3: E\n        })\n\n        const components = Graph.connectedComponents(graph)\n        expect(components).toHaveLength(3)\n\n        // Sort components by size and first element for deterministic testing\n        components.sort((a, b) => a.length - b.length || a[0] - b[0])\n        expect(components[0]).toEqual([4]) // E isolated\n        expect(components[1]).toHaveLength(2) // A-B or C-D\n        expect(components[2]).toHaveLength(2) // A-B or C-D\n      })\n\n      it(\"should handle fully connected component\", () => {\n        const graph = Graph.undirected<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, \"edge\")\n          Graph.addEdge(mutable, b, c, \"edge\")\n          Graph.addEdge(mutable, c, a, \"edge\")\n        })\n\n        const components = Graph.connectedComponents(graph)\n        expect(components).toHaveLength(1)\n        expect(components[0]).toHaveLength(3)\n        expect(components[0].sort()).toEqual([0, 1, 2])\n      })\n    })\n\n    describe(\"stronglyConnectedComponents\", () => {\n      it(\"should find strongly connected components in directed graph\", () => {\n        const graph = Graph.directed<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n          Graph.addEdge(mutable, a, b, \"A->B\")\n          Graph.addEdge(mutable, b, c, \"B->C\")\n          Graph.addEdge(mutable, c, a, \"C->A\") // SCC: A-B-C\n          Graph.addEdge(mutable, b, d, \"B->D\") // D is separate\n        })\n\n        const sccs = Graph.stronglyConnectedComponents(graph)\n        expect(sccs).toHaveLength(2)\n\n        // Sort SCCs by size for deterministic testing\n        sccs.sort((a, b) => a.length - b.length)\n        expect(sccs[0]).toEqual([3]) // D is alone\n        expect(sccs[1]).toHaveLength(3) // A-B-C cycle\n        expect(sccs[1].sort()).toEqual([0, 1, 2])\n      })\n\n      it(\"should handle acyclic directed graph (each node is its own SCC)\", () => {\n        const dag = Graph.directed<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, \"A->B\")\n          Graph.addEdge(mutable, b, c, \"B->C\")\n        })\n\n        const sccs = Graph.stronglyConnectedComponents(dag)\n        expect(sccs).toHaveLength(3)\n        // Each SCC should contain exactly one node\n        sccs.forEach((scc) => {\n          expect(scc).toHaveLength(1)\n        })\n      })\n\n      it(\"should handle fully connected components\", () => {\n        const graph = Graph.directed<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          // Create bidirectional edges (fully connected)\n          Graph.addEdge(mutable, a, b, \"A->B\")\n          Graph.addEdge(mutable, b, a, \"B->A\")\n          Graph.addEdge(mutable, b, c, \"B->C\")\n          Graph.addEdge(mutable, c, b, \"C->B\")\n          Graph.addEdge(mutable, a, c, \"A->C\")\n          Graph.addEdge(mutable, c, a, \"C->A\")\n        })\n\n        const sccs = Graph.stronglyConnectedComponents(graph)\n        expect(sccs).toHaveLength(1)\n        expect(sccs[0]).toHaveLength(3)\n        expect(sccs[0].sort()).toEqual([0, 1, 2])\n      })\n\n      it(\"should handle disconnected components with cycles\", () => {\n        const graph = Graph.directed<string, string>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n          // First SCC: A->B->A\n          Graph.addEdge(mutable, a, b, \"A->B\")\n          Graph.addEdge(mutable, b, a, \"B->A\")\n          // Second SCC: C->D->C\n          Graph.addEdge(mutable, c, d, \"C->D\")\n          Graph.addEdge(mutable, d, c, \"D->C\")\n        })\n\n        const sccs = Graph.stronglyConnectedComponents(graph)\n        expect(sccs).toHaveLength(2)\n        sccs.forEach((scc) => {\n          expect(scc).toHaveLength(2)\n        })\n      })\n    })\n\n    describe(\"dijkstra\", () => {\n      it(\"should find shortest path in simple graph\", () => {\n        let nodeA: Graph.NodeIndex\n        let nodeB: Graph.NodeIndex\n        let nodeC: Graph.NodeIndex\n\n        const graph = Graph.directed<string, number>((mutable) => {\n          nodeA = Graph.addNode(mutable, \"A\")\n          nodeB = Graph.addNode(mutable, \"B\")\n          nodeC = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, nodeA, nodeB, 5)\n          Graph.addEdge(mutable, nodeA, nodeC, 10)\n          Graph.addEdge(mutable, nodeB, nodeC, 2)\n        })\n\n        const result = Graph.dijkstra(graph, { source: nodeA!, target: nodeC!, cost: (edge) => edge })\n        expect(Option.isSome(result)).toBe(true)\n        if (Option.isSome(result)) {\n          expect(result.value.path).toEqual([nodeA!, nodeB!, nodeC!])\n          expect(result.value.distance).toBe(7)\n          expect(result.value.costs).toEqual([5, 2])\n        }\n      })\n\n      it(\"should return None for unreachable nodes\", () => {\n        let nodeA: Graph.NodeIndex\n        let nodeB: Graph.NodeIndex\n        let nodeC: Graph.NodeIndex\n\n        const graph = Graph.directed<string, number>((mutable) => {\n          nodeA = Graph.addNode(mutable, \"A\")\n          nodeB = Graph.addNode(mutable, \"B\")\n          nodeC = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n          // No path from A to C\n        })\n\n        const result = Graph.dijkstra(graph, { source: nodeA!, target: nodeC!, cost: (edge) => edge })\n        expect(Option.isNone(result)).toBe(true)\n      })\n\n      it(\"should handle same source and target\", () => {\n        let nodeA: Graph.NodeIndex\n\n        const graph = Graph.directed<string, number>((mutable) => {\n          nodeA = Graph.addNode(mutable, \"A\")\n        })\n\n        const result = Graph.dijkstra(graph, { source: nodeA!, target: nodeA!, cost: (edge) => edge })\n        expect(Option.isSome(result)).toBe(true)\n        if (Option.isSome(result)) {\n          expect(result.value.path).toEqual([nodeA!])\n          expect(result.value.distance).toBe(0)\n          expect(result.value.costs).toEqual([])\n        }\n      })\n\n      it(\"should throw for negative weights\", () => {\n        let nodeA: Graph.NodeIndex\n        let nodeB: Graph.NodeIndex\n\n        const graph = Graph.directed<string, number>((mutable) => {\n          nodeA = Graph.addNode(mutable, \"A\")\n          nodeB = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, nodeA, nodeB, -1)\n        })\n\n        expect(() => Graph.dijkstra(graph, { source: nodeA!, target: nodeB!, cost: (edge) => edge })).toThrow(\n          \"Dijkstra's algorithm requires non-negative edge weights\"\n        )\n      })\n\n      it(\"should throw for non-existent nodes\", () => {\n        const graph = Graph.directed<string, number>()\n\n        expect(() => Graph.dijkstra(graph, { source: 0, target: 1, cost: (edge) => edge })).toThrow(\n          \"Node 0 does not exist\"\n        )\n      })\n    })\n\n    describe(\"astar\", () => {\n      it(\"should find shortest path with heuristic\", () => {\n        let nodeA: Graph.NodeIndex\n        let nodeB: Graph.NodeIndex\n        let nodeC: Graph.NodeIndex\n\n        const graph = Graph.directed<{ x: number; y: number }, number>((mutable) => {\n          nodeA = Graph.addNode(mutable, { x: 0, y: 0 })\n          nodeB = Graph.addNode(mutable, { x: 1, y: 0 })\n          nodeC = Graph.addNode(mutable, { x: 2, y: 0 })\n          Graph.addEdge(mutable, nodeA, nodeB, 1)\n          Graph.addEdge(mutable, nodeB, nodeC, 1)\n        })\n\n        const heuristic = (source: { x: number; y: number }, target: { x: number; y: number }) =>\n          Math.abs(source.x - target.x) + Math.abs(source.y - target.y)\n\n        const result = Graph.astar(graph, { source: nodeA!, target: nodeC!, cost: (edge) => edge, heuristic })\n        expect(Option.isSome(result)).toBe(true)\n        if (Option.isSome(result)) {\n          expect(result.value.path).toEqual([nodeA!, nodeB!, nodeC!])\n          expect(result.value.distance).toBe(2)\n          expect(result.value.costs).toEqual([1, 1])\n        }\n      })\n\n      it(\"should return None for unreachable nodes\", () => {\n        const graph = Graph.directed<{ x: number; y: number }, number>((mutable) => {\n          const a = Graph.addNode(mutable, { x: 0, y: 0 })\n          const b = Graph.addNode(mutable, { x: 1, y: 0 })\n          Graph.addNode(mutable, { x: 2, y: 0 })\n          Graph.addEdge(mutable, a, b, 1)\n          // No path from A to C\n        })\n\n        const heuristic = (source: { x: number; y: number }, target: { x: number; y: number }) =>\n          Math.abs(source.x - target.x) + Math.abs(source.y - target.y)\n\n        const result = Graph.astar(graph, { source: 0, target: 2, cost: (edge) => edge, heuristic })\n        expect(Option.isNone(result)).toBe(true)\n      })\n\n      it(\"should handle same source and target\", () => {\n        const graph = Graph.directed<{ x: number; y: number }, number>((mutable) => {\n          Graph.addNode(mutable, { x: 0, y: 0 })\n        })\n\n        const heuristic = (source: { x: number; y: number }, target: { x: number; y: number }) =>\n          Math.abs(source.x - target.x) + Math.abs(source.y - target.y)\n\n        const result = Graph.astar(graph, { source: 0, target: 0, cost: (edge) => edge, heuristic })\n        expect(Option.isSome(result)).toBe(true)\n        if (Option.isSome(result)) {\n          expect(result.value.path).toEqual([0])\n          expect(result.value.distance).toBe(0)\n          expect(result.value.costs).toEqual([])\n        }\n      })\n\n      it(\"should throw for negative weights\", () => {\n        const graph = Graph.directed<{ x: number; y: number }, number>((mutable) => {\n          const a = Graph.addNode(mutable, { x: 0, y: 0 })\n          const b = Graph.addNode(mutable, { x: 1, y: 0 })\n          Graph.addEdge(mutable, a, b, -1)\n        })\n\n        const heuristic = (source: { x: number; y: number }, target: { x: number; y: number }) =>\n          Math.abs(source.x - target.x) + Math.abs(source.y - target.y)\n\n        expect(() => Graph.astar(graph, { source: 0, target: 1, cost: (edge) => edge, heuristic })).toThrow(\n          \"A* algorithm requires non-negative edge weights\"\n        )\n      })\n    })\n\n    describe(\"bellmanFord\", () => {\n      it(\"should find shortest path with negative weights\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, -1)\n          Graph.addEdge(mutable, b, c, 3)\n          Graph.addEdge(mutable, a, c, 5)\n        })\n\n        const result = Graph.bellmanFord(graph, { source: 0, target: 2, cost: (edge) => edge })\n        expect(Option.isSome(result)).toBe(true)\n        if (Option.isSome(result)) {\n          expect(result.value.path).toEqual([0, 1, 2])\n          expect(result.value.distance).toBe(2)\n          expect(result.value.costs).toEqual([-1, 3])\n        }\n      })\n\n      it(\"should return None for unreachable nodes\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          // No path from A to C\n        })\n\n        const result = Graph.bellmanFord(graph, { source: 0, target: 2, cost: (edge) => edge })\n        expect(Option.isNone(result)).toBe(true)\n      })\n\n      it(\"should handle same source and target\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          Graph.addNode(mutable, \"A\")\n        })\n\n        const result = Graph.bellmanFord(graph, { source: 0, target: 0, cost: (edge) => edge })\n        expect(Option.isSome(result)).toBe(true)\n        if (Option.isSome(result)) {\n          expect(result.value.path).toEqual([0])\n          expect(result.value.distance).toBe(0)\n          expect(result.value.costs).toEqual([])\n        }\n      })\n\n      it(\"should detect negative cycles\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, -3)\n          Graph.addEdge(mutable, c, a, 1)\n        })\n\n        const result = Graph.bellmanFord(graph, { source: 0, target: 2, cost: (edge) => edge })\n        expect(Option.isNone(result)).toBe(true)\n      })\n    })\n\n    describe(\"floydWarshall\", () => {\n      it(\"should find all-pairs shortest paths\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 3)\n          Graph.addEdge(mutable, b, c, 2)\n          Graph.addEdge(mutable, a, c, 7)\n        })\n\n        const result = Graph.floydWarshall(graph, (edge) => edge)\n\n        // Check distance A to C (should be 5 via B, not 7 direct)\n        expect(result.distances.get(0)?.get(2)).toBe(5)\n        expect(result.paths.get(0)?.get(2)).toEqual([0, 1, 2])\n        expect(result.costs.get(0)?.get(2)).toEqual([3, 2])\n\n        // Check distance A to B\n        expect(result.distances.get(0)?.get(1)).toBe(3)\n        expect(result.paths.get(0)?.get(1)).toEqual([0, 1])\n\n        // Check distance B to C\n        expect(result.distances.get(1)?.get(2)).toBe(2)\n        expect(result.paths.get(1)?.get(2)).toEqual([1, 2])\n      })\n\n      it(\"should handle unreachable nodes\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          // No path from A to C\n        })\n\n        const result = Graph.floydWarshall(graph, (edge) => edge)\n\n        expect(result.distances.get(0)?.get(2)).toBe(Infinity)\n        expect(result.paths.get(0)?.get(2)).toBeNull()\n      })\n\n      it(\"should handle same source and target\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          Graph.addNode(mutable, \"A\")\n        })\n\n        const result = Graph.floydWarshall(graph, (edge) => edge)\n\n        expect(result.distances.get(0)?.get(0)).toBe(0)\n        expect(result.paths.get(0)?.get(0)).toEqual([0])\n        expect(result.costs.get(0)?.get(0)).toEqual([])\n      })\n\n      it(\"should detect negative cycles\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, -3)\n          Graph.addEdge(mutable, c, a, 1)\n        })\n\n        expect(() => Graph.floydWarshall(graph, (edge) => edge)).toThrow(\"Negative cycle detected\")\n      })\n    })\n\n    describe(\"Iterator Base Methods\", () => {\n      it(\"should provide values() method for DFS iterator\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        const dfsIterator = Graph.dfs(graph, { start: [0] })\n        const values = Array.from(Graph.values(dfsIterator))\n\n        expect(values).toEqual([\"A\", \"B\", \"C\"])\n      })\n\n      it(\"should provide entries() method for DFS iterator\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        const dfsIterator = Graph.dfs(graph, { start: [0] })\n        const entries = Array.from(Graph.entries(dfsIterator))\n\n        expect(entries).toEqual([[0, \"A\"], [1, \"B\"], [2, \"C\"]])\n      })\n\n      it(\"should provide values() method for BFS iterator\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, a, c, 2)\n        })\n\n        const bfsIterator = Graph.bfs(graph, { start: [0] })\n        const values = Array.from(Graph.values(bfsIterator))\n\n        expect(values).toEqual([\"A\", \"B\", \"C\"])\n      })\n\n      it(\"should provide entries() method for BFS iterator\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, a, c, 2)\n        })\n\n        const bfsIterator = Graph.bfs(graph, { start: [0] })\n        const entries = Array.from(Graph.entries(bfsIterator))\n\n        expect(entries).toEqual([[0, \"A\"], [1, \"B\"], [2, \"C\"]])\n      })\n\n      it(\"should provide values() method for Topo iterator\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        const topoIterator = Graph.topo(graph)\n\n        const values = Array.from(Graph.values(topoIterator))\n        expect(values).toEqual([\"A\", \"B\", \"C\"])\n      })\n\n      it(\"should provide entries() method for Topo iterator\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        const topoIterator = Graph.topo(graph)\n\n        const entries = Array.from(Graph.entries(topoIterator))\n        expect(entries).toEqual([[0, \"A\"], [1, \"B\"], [2, \"C\"]])\n      })\n\n      it(\"should throw for cyclic graphs\", () => {\n        const cyclicGraph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, a, 2) // Creates cycle\n        })\n\n        expect(() => Graph.topo(cyclicGraph)).toThrow(\"Cannot perform topological sort on cyclic graph\")\n      })\n\n      it(\"should handle corrupted graph state during topological sort\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 1)\n        })\n\n        // Test edge case by corrupting graph internals during iteration\n        const mutableGraph = graph as any\n        const originalGetNode = mutableGraph.nodes.get\n\n        let callCount = 0\n        // Mock getNode to return undefined for certain calls to trigger the recursive edge case\n        mutableGraph.nodes.get = function(key: any) {\n          callCount++\n          // On specific call, return undefined to trigger the Option.isNone path\n          if (callCount === 2) {\n            return undefined\n          }\n          return originalGetNode.call(this, key)\n        }\n\n        const iterator = Graph.topo(graph)\n        const results = Array.from(iterator)\n\n        // Restore original method\n        mutableGraph.nodes.get = originalGetNode\n\n        // Should complete without crashing\n        expect(results.length).toBeGreaterThanOrEqual(0)\n      })\n\n      it(\"should provide values() method for DfsPostOrder iterator\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        const dfsPostIterator = Graph.dfsPostOrder(graph, { start: [0] })\n        const values = Array.from(Graph.values(dfsPostIterator))\n\n        expect(values).toEqual([\"C\", \"B\", \"A\"]) // Postorder: children before parents\n      })\n\n      it(\"should provide entries() method for DfsPostOrder iterator\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        const dfsPostIterator = Graph.dfsPostOrder(graph, { start: [0] })\n        const entries = Array.from(Graph.entries(dfsPostIterator))\n\n        expect(entries).toEqual([[2, \"C\"], [1, \"B\"], [0, \"A\"]]) // Postorder: children before parents\n      })\n    })\n\n    describe(\"DfsPostOrder Iterator\", () => {\n      it(\"should traverse in postorder for simple chain\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        const postOrder = Array.from(Graph.indices(Graph.dfsPostOrder(graph, { start: [0] })))\n        expect(postOrder).toEqual([2, 1, 0]) // Children before parents\n      })\n\n      it(\"should traverse in postorder for branching tree\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const root = Graph.addNode(mutable, \"root\") // 0\n          const left = Graph.addNode(mutable, \"left\") // 1\n          const right = Graph.addNode(mutable, \"right\") // 2\n          const leaf1 = Graph.addNode(mutable, \"leaf1\") // 3\n          const leaf2 = Graph.addNode(mutable, \"leaf2\") // 4\n\n          Graph.addEdge(mutable, root, left, 1)\n          Graph.addEdge(mutable, root, right, 2)\n          Graph.addEdge(mutable, left, leaf1, 3)\n          Graph.addEdge(mutable, right, leaf2, 4)\n        })\n\n        const postOrder = Array.from(Graph.indices(Graph.dfsPostOrder(graph, { start: [0] })))\n        // Should visit leaves first, then parents\n        expect(postOrder).toEqual([3, 1, 4, 2, 0])\n      })\n\n      it(\"should handle empty start nodes\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          Graph.addNode(mutable, \"A\")\n        })\n\n        const postOrder = Array.from(Graph.dfsPostOrder(graph, { start: [] }))\n        expect(postOrder).toEqual([])\n      })\n\n      it(\"should handle disconnected components with multiple start nodes\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          const d = Graph.addNode(mutable, \"D\")\n\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, c, d, 2)\n          // No connection between (A,B) and (C,D)\n        })\n\n        const postOrder = Array.from(Graph.indices(Graph.dfsPostOrder(graph, { start: [0, 2] })))\n        expect(postOrder).toEqual([1, 0, 3, 2]) // Each component in postorder\n      })\n\n      it(\"should support incoming direction\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        // Starting from C, going backwards\n        const postOrder = Array.from(\n          Graph.indices(Graph.dfsPostOrder(graph, {\n            start: [2],\n            direction: \"incoming\"\n          }))\n        )\n        expect(postOrder).toEqual([0, 1, 2]) // A, B, C in reverse postorder\n      })\n\n      it(\"should handle cycles correctly\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n          Graph.addEdge(mutable, c, a, 3) // Creates cycle\n        })\n\n        const postOrder = Array.from(Graph.indices(Graph.dfsPostOrder(graph, { start: [0] })))\n        // Should handle cycle without infinite loop, visiting each node once\n        expect(postOrder.length).toBe(3)\n        expect(new Set(postOrder)).toEqual(new Set([0, 1, 2]))\n      })\n\n      it(\"should throw error for non-existent start node\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          Graph.addNode(mutable, \"A\")\n        })\n\n        expect(() => Graph.dfsPostOrder(graph, { start: [99] }))\n          .toThrow(\"Node 99 does not exist\")\n      })\n\n      it(\"should be iterable multiple times with fresh state\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 1)\n        })\n\n        const iterator = Graph.dfsPostOrder(graph, { start: [0] })\n\n        const firstRun = Array.from(Graph.indices(iterator))\n        const secondRun = Array.from(Graph.indices(iterator))\n\n        expect(firstRun).toEqual([1, 0])\n        expect(secondRun).toEqual([1, 0])\n        expect(firstRun).toEqual(secondRun)\n      })\n\n      it(\"should handle corrupted graph state during iteration\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 1)\n        })\n\n        // Test edge case by corrupting graph internals during iteration\n        const mutableGraph = graph as any\n        const originalGetNode = mutableGraph.nodes.get\n\n        let callCount = 0\n        // Mock getNode to return undefined for certain calls to trigger the recursive edge case\n        mutableGraph.nodes.get = function(key: any) {\n          callCount++\n          // On specific call, return undefined to trigger the Option.isNone path\n          if (callCount === 3) {\n            return undefined\n          }\n          return originalGetNode.call(this, key)\n        }\n\n        const iterator = Graph.dfsPostOrder(graph, { start: [0] })\n        const results = Array.from(iterator)\n\n        // Restore original method\n        mutableGraph.nodes.get = originalGetNode\n\n        // Should complete without crashing\n        expect(results.length).toBeGreaterThanOrEqual(0)\n      })\n    })\n\n    describe(\"Graph Element Iterators\", () => {\n      describe(\"nodes\", () => {\n        it(\"should iterate over all node indices\", () => {\n          const graph = Graph.directed<string, number>((mutable) => {\n            Graph.addNode(mutable, \"A\")\n            Graph.addNode(mutable, \"B\")\n            Graph.addNode(mutable, \"C\")\n          })\n\n          const indices = Array.from(Graph.indices(Graph.nodes(graph)))\n          expect(indices).toEqual([0, 1, 2])\n        })\n\n        it(\"should work with manual iterator control\", () => {\n          const graph = Graph.directed<string, number>((mutable) => {\n            Graph.addNode(mutable, \"A\")\n            Graph.addNode(mutable, \"B\")\n          })\n\n          const iterator = Graph.indices(Graph.nodes(graph))[Symbol.iterator]()\n          expect(iterator.next().value).toBe(0)\n          expect(iterator.next().value).toBe(1)\n          expect(iterator.next().done).toBe(true)\n        })\n      })\n\n      describe(\"edges\", () => {\n        it(\"should iterate over all edge indices\", () => {\n          const graph = Graph.directed<string, number>((mutable) => {\n            const a = Graph.addNode(mutable, \"A\")\n            const b = Graph.addNode(mutable, \"B\")\n            const c = Graph.addNode(mutable, \"C\")\n            Graph.addEdge(mutable, a, b, 1)\n            Graph.addEdge(mutable, b, c, 2)\n            Graph.addEdge(mutable, c, a, 3)\n          })\n\n          const indices = Array.from(Graph.indices(Graph.edges(graph)))\n          expect(indices).toEqual([0, 1, 2])\n        })\n\n        it(\"should handle graph with no edges\", () => {\n          const graph = Graph.directed<string, number>((mutable) => {\n            Graph.addNode(mutable, \"A\")\n            Graph.addNode(mutable, \"B\")\n          })\n\n          const indices = Array.from(Graph.indices(Graph.edges(graph)))\n          expect(indices).toEqual([])\n        })\n      })\n\n      describe(\"externals\", () => {\n        it(\"should find nodes with no outgoing edges (sinks)\", () => {\n          const graph = Graph.directed<string, number>((mutable) => {\n            const source = Graph.addNode(mutable, \"source\") // 0\n            const middle = Graph.addNode(mutable, \"middle\") // 1\n            const sink = Graph.addNode(mutable, \"sink\") // 2\n            Graph.addNode(mutable, \"isolated\") // 3\n\n            Graph.addEdge(mutable, source, middle, 1)\n            Graph.addEdge(mutable, middle, sink, 2)\n            // No outgoing edges from sink (2) or isolated (3)\n          })\n\n          const sinks = Array.from(Graph.indices(Graph.externals(graph, { direction: \"outgoing\" })))\n          expect(sinks.sort()).toEqual([2, 3])\n        })\n\n        it(\"should find nodes with no incoming edges (sources)\", () => {\n          const graph = Graph.directed<string, number>((mutable) => {\n            const source = Graph.addNode(mutable, \"source\") // 0\n            const middle = Graph.addNode(mutable, \"middle\") // 1\n            const sink = Graph.addNode(mutable, \"sink\") // 2\n            Graph.addNode(mutable, \"isolated\") // 3\n\n            Graph.addEdge(mutable, source, middle, 1)\n            Graph.addEdge(mutable, middle, sink, 2)\n            // No incoming edges to source (0) or isolated (3)\n          })\n\n          const sources = Array.from(Graph.indices(Graph.externals(graph, { direction: \"incoming\" })))\n          expect(sources.sort()).toEqual([0, 3])\n        })\n\n        it(\"should default to outgoing direction\", () => {\n          const graph = Graph.directed<string, number>((mutable) => {\n            const a = Graph.addNode(mutable, \"A\")\n            const b = Graph.addNode(mutable, \"B\")\n            Graph.addEdge(mutable, a, b, 1)\n            // b has no outgoing edges\n          })\n\n          const externalsDefault = Array.from(Graph.indices(Graph.externals(graph)))\n          const externalsExplicit = Array.from(Graph.indices(Graph.externals(graph, { direction: \"outgoing\" })))\n\n          expect(externalsDefault).toEqual(externalsExplicit)\n          expect(externalsDefault).toEqual([1])\n        })\n\n        it(\"should handle fully connected components\", () => {\n          const graph = Graph.directed<string, number>((mutable) => {\n            const a = Graph.addNode(mutable, \"A\")\n            const b = Graph.addNode(mutable, \"B\")\n            const c = Graph.addNode(mutable, \"C\")\n            Graph.addEdge(mutable, a, b, 1)\n            Graph.addEdge(mutable, b, c, 2)\n            Graph.addEdge(mutable, c, a, 3) // Creates cycle\n          })\n\n          const outgoingExternals = Array.from(Graph.indices(Graph.externals(graph, { direction: \"outgoing\" })))\n          const incomingExternals = Array.from(Graph.indices(Graph.externals(graph, { direction: \"incoming\" })))\n\n          expect(outgoingExternals).toEqual([]) // All nodes have outgoing edges\n          expect(incomingExternals).toEqual([]) // All nodes have incoming edges\n        })\n\n        it(\"should work with manual iterator control\", () => {\n          const graph = Graph.directed<string, number>((mutable) => {\n            const a = Graph.addNode(mutable, \"A\")\n            const b = Graph.addNode(mutable, \"B\")\n            Graph.addNode(mutable, \"C\")\n            Graph.addEdge(mutable, a, b, 1)\n            // b and c have no outgoing edges\n          })\n\n          const iterator = Graph.indices(Graph.externals(graph, { direction: \"outgoing\" }))[Symbol.iterator]()\n\n          const first = iterator.next().value\n          const second = iterator.next().value\n          const third = iterator.next()\n\n          expect([first, second].sort()).toEqual([1, 2])\n          expect(third.done).toBe(true)\n        })\n      })\n\n      it(\"should allow combining different element iterators\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 100)\n        })\n\n        // Combine different iterators\n        const nodeCount = Array.from(Graph.indices(Graph.nodes(graph))).length\n        const edgeCount = Array.from(Graph.indices(Graph.edges(graph))).length\n        const nodeData = Array.from(Graph.values(Graph.nodes(graph)))\n        const edge = Array.from(Graph.values(Graph.edges(graph)))\n\n        expect(nodeCount).toBe(2)\n        expect(edgeCount).toBe(1)\n        expect(nodeData).toEqual([\"A\", \"B\"])\n        expect(edge).toEqual([{ source: 0, target: 1, data: 100 }])\n      })\n    })\n\n    describe(\"GraphIterable abstraction\", () => {\n      it(\"should enable iteration over different types\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        // Should work with different iterator types\n        const dfsIterable = Graph.dfs(graph, { start: [0] })\n        const nodesIterable = Graph.nodes(graph)\n        const externalsIterable = Graph.externals(graph)\n\n        // All should be iterable and have expected structure\n        expect(Array.from(dfsIterable)).toHaveLength(3)\n        expect(Array.from(nodesIterable)).toHaveLength(3)\n        expect(Array.from(externalsIterable)).toHaveLength(1) // Only one node with no outgoing edges\n      })\n    })\n\n    describe(\"NodeIterable abstraction\", () => {\n      it(\"should provide common interface for node index iterables\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        // Utility function that works with any NodeWalker\n        function collectNodes<N>(\n          nodeIterable: Graph.NodeWalker<N>\n        ): Array<number> {\n          return Array.from(Graph.indices(nodeIterable)).sort()\n        }\n\n        // Both traversal and element iterators implement NodeWalker\n        const dfsNodes = Graph.dfs(graph, { start: [0] })\n        const allNodes = Graph.nodes(graph)\n        const externalNodes = Graph.externals(graph, { direction: \"outgoing\" })\n\n        // All should work with the same utility function\n        expect(collectNodes(dfsNodes)).toEqual([0, 1, 2])\n        expect(collectNodes(allNodes)).toEqual([0, 1, 2])\n        expect(collectNodes(externalNodes)).toEqual([2]) // Only node 2 has no outgoing edges\n      })\n\n      it(\"should allow type-safe node iterable operations\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 1)\n        })\n\n        const nodeIterable: Graph.NodeWalker<string> = Graph.nodes(graph)\n        const traversalIterable: Graph.NodeWalker<string> = Graph.dfs(graph, {\n          start: [0]\n        })\n\n        expect(Array.from(Graph.indices(nodeIterable))).toEqual([0, 1])\n        expect(Array.from(Graph.indices(traversalIterable))).toEqual([0, 1])\n      })\n    })\n\n    describe(\"Standalone utility functions\", () => {\n      it(\"should work with values() function on any NodeIterable\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          const c = Graph.addNode(mutable, \"C\")\n          Graph.addEdge(mutable, a, b, 1)\n          Graph.addEdge(mutable, b, c, 2)\n        })\n\n        // Test with traversal iterators\n        const dfsIterable = Graph.dfs(graph, { start: [0] })\n        const dfsValues = Array.from(Graph.values(dfsIterable))\n        expect(dfsValues).toEqual([\"A\", \"B\", \"C\"])\n\n        // Test with element iterators\n        const nodesIterable = Graph.nodes(graph)\n        const nodeValues = Array.from(Graph.values(nodesIterable))\n        expect(nodeValues.sort()).toEqual([\"A\", \"B\", \"C\"])\n\n        // Test with externals iterator\n        const externalsIterable = Graph.externals(graph, { direction: \"outgoing\" })\n        const externalValues = Array.from(Graph.values(externalsIterable))\n        expect(externalValues).toEqual([\"C\"]) // Only C has no outgoing edges\n      })\n\n      it(\"should work with entries() function on any NodeIterable\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 1)\n        })\n\n        // Test with traversal iterator\n        const dfsIterable = Graph.dfs(graph, { start: [0] })\n        const dfsEntries = Array.from(Graph.entries(dfsIterable))\n        expect(dfsEntries).toEqual([[0, \"A\"], [1, \"B\"]])\n\n        // Test with element iterator\n        const nodesIterable = Graph.nodes(graph)\n        const nodeEntries = Array.from(Graph.entries(nodesIterable))\n        expect(nodeEntries.sort()).toEqual([[0, \"A\"], [1, \"B\"]])\n\n        // Test with externals iterator\n        const externalsIterable = Graph.externals(graph, { direction: \"outgoing\" })\n        const externalEntries = Array.from(Graph.entries(externalsIterable))\n        expect(externalEntries).toEqual([[1, \"B\"]]) // Only B has no outgoing edges\n      })\n\n      it(\"should work with instance methods\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 1)\n        })\n\n        const dfs = Graph.dfs(graph, { start: [0] })\n\n        // Instance methods should work\n        const instanceValues = Array.from(Graph.values(dfs))\n        const instanceEntries = Array.from(Graph.entries(dfs))\n\n        expect(instanceValues).toEqual([\"A\", \"B\"])\n        expect(instanceEntries).toEqual([[0, \"A\"], [1, \"B\"]])\n      })\n\n      it(\"should work with mapEntry for NodeIterable\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 1)\n        })\n\n        const dfs = Graph.dfs(graph, { start: [0] })\n\n        // Test mapEntry with custom mapping\n        const custom = Array.from(dfs.visit((index, data) => ({ id: index, name: data })))\n        expect(custom).toEqual([{ id: 0, name: \"A\" }, { id: 1, name: \"B\" }])\n\n        // Test that values() is implemented using mapEntry\n        const values = Array.from(Graph.values(dfs))\n        expect(values).toEqual([\"A\", \"B\"])\n\n        // Test that entries() is implemented using mapEntry\n        const entries = Array.from(Graph.entries(dfs))\n        expect(entries).toEqual([[0, \"A\"], [1, \"B\"]])\n      })\n\n      it(\"should work with mapEntry for EdgeIterable\", () => {\n        const graph = Graph.directed<string, number>((mutable) => {\n          const a = Graph.addNode(mutable, \"A\")\n          const b = Graph.addNode(mutable, \"B\")\n          Graph.addEdge(mutable, a, b, 42)\n        })\n\n        const edgesIterable = Graph.edges(graph)\n\n        // Test mapEntry with custom mapping\n        const connections = Array.from(edgesIterable.visit((index, edge) => ({\n          id: index,\n          from: edge.source,\n          to: edge.target,\n          weight: edge.data\n        })))\n        expect(connections).toEqual([{ id: 0, from: 0, to: 1, weight: 42 }])\n\n        // Test that values() is implemented using mapEntry\n        const weights = Array.from(edgesIterable.visit((_, edge) => edge.data))\n        expect(weights).toEqual([42])\n\n        // Test that entries() is implemented using mapEntry\n        const entries = Array.from(Graph.entries(edgesIterable))\n        expect(entries).toEqual([[0, { source: 0, target: 1, data: 42 }]])\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Hash.test.ts",
    "content": "import { describe, expect, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport { absurd, Equal, Hash, HashSet, identity, Option, Utils } from \"effect\"\n\ndescribe(\"Hash\", () => {\n  it(\"structural\", () => {\n    const a = { foo: { bar: \"ok\", baz: { arr: [0, 1, 2] } } }\n    const b = { foo: { bar: \"ok\", baz: { arr: [0, 1, 2] } } }\n    assertTrue(Hash.hash(a) !== Hash.hash(b))\n    assertFalse(Equal.equals(a, b))\n    Utils.structuralRegion(() => {\n      strictEqual(Hash.hash(a), Hash.hash(b))\n      assertTrue(Equal.equals(a, b))\n    })\n    assertTrue(Hash.hash(a) !== Hash.hash(b))\n    assertFalse(Equal.equals(a, b))\n  })\n  it(\"structural cached\", () => {\n    const a = Option.some({ foo: { bar: \"ok\", baz: { arr: [0, 1, 2] } } })\n    const b = Option.some({ foo: { bar: \"ok\", baz: { arr: [0, 1, 2] } } })\n    assertTrue(Hash.hash(a) !== Hash.hash(b))\n    assertFalse(Equal.equals(a, b))\n    Utils.structuralRegion(() => {\n      strictEqual(Hash.hash(a), Hash.hash(b))\n      assertTrue(Equal.equals(a, b))\n    })\n    assertTrue(Hash.hash(a) !== Hash.hash(b))\n    assertFalse(Equal.equals(a, b))\n  })\n\n  it(\"number\", () => {\n    const set: HashSet.HashSet<number> = HashSet.make(Infinity)\n    assertTrue(HashSet.has(set, Infinity))\n    assertFalse(HashSet.has(set, -Infinity))\n    assertTrue(Hash.number(0.1) !== Hash.number(0))\n  })\n\n  it(\"bigint\", () => {\n    const set = HashSet.make(1n)\n    assertTrue(HashSet.has(set, 1n))\n    assertFalse(HashSet.has(set, 2n))\n  })\n\n  it(\"symbol\", () => {\n    const a = Symbol.for(\"effect/test/Hash/a\")\n    const b = Symbol.for(\"effect/test/Hash/b\")\n    const set: HashSet.HashSet<symbol> = HashSet.make(a)\n    assertTrue(HashSet.has(set, a))\n    assertFalse(HashSet.has(set, b))\n  })\n\n  it(\"undefined\", () => {\n    const set: HashSet.HashSet<number | undefined> = HashSet.make(1, undefined)\n    assertTrue(HashSet.has(set, undefined))\n    assertFalse(HashSet.has(set, 2))\n  })\n\n  it(\"null\", () => {\n    const set: HashSet.HashSet<number | null> = HashSet.make(1, null)\n    assertTrue(HashSet.has(set, null))\n    assertFalse(HashSet.has(set, 2))\n  })\n\n  it(\"function\", () => {\n    const set: HashSet.HashSet<Function> = HashSet.make(identity)\n    assertTrue(HashSet.has(set, identity))\n    assertFalse(HashSet.has(set, absurd))\n  })\n\n  it(\"isHash\", () => {\n    assertTrue(Hash.isHash(HashSet.empty()))\n    assertFalse(Hash.isHash(null))\n    assertFalse(Hash.isHash({}))\n  })\n\n  it(\"invalid Date\", () => {\n    const invalidDate = new Date(\"invalid\")\n    expect(() => Hash.hash(invalidDate)).not.toThrow()\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/HashMap.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertNone,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { Equal, Hash, HashMap as HM, Option, pipe } from \"effect\"\n\nclass Key implements Equal.Equal {\n  constructor(readonly n: number) {}\n\n  [Hash.symbol](): number {\n    return Hash.hash(this.n)\n  }\n\n  [Equal.symbol](u: unknown): boolean {\n    return u instanceof Key && this.n === u.n\n  }\n}\n\nclass Value implements Equal.Equal {\n  constructor(readonly s: string) {}\n\n  [Hash.symbol](): number {\n    return Hash.hash(this.s)\n  }\n\n  [Equal.symbol](u: unknown): boolean {\n    return u instanceof Value && this.s === u.s\n  }\n}\n\ndescribe(\"HashMap\", () => {\n  function key(n: number): Key {\n    return new Key(n)\n  }\n\n  function value(s: string): Value {\n    return new Value(s)\n  }\n\n  it(\"option\", () => {\n    const map = HM.make([Option.some(1), 0], [Option.none(), 1])\n    assertTrue(pipe(map, HM.has(Option.none())))\n    assertTrue(pipe(map, HM.has(Option.some(1))))\n    assertFalse(pipe(map, HM.has(Option.some(2))))\n  })\n\n  it(\"toString\", () => {\n    const map = HM.make([0, \"a\"])\n    strictEqual(\n      String(map),\n      `{\n  \"_id\": \"HashMap\",\n  \"values\": [\n    [\n      0,\n      \"a\"\n    ]\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    const map = HM.make([0, \"a\"])\n    deepStrictEqual(map.toJSON(), { _id: \"HashMap\", values: [[0, \"a\"]] })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window === \"undefined\") {\n      // eslint-disable-next-line @typescript-eslint/no-require-imports\n      const { inspect } = require(\"node:util\")\n      const map = HM.make([0, \"a\"])\n      deepStrictEqual(inspect(map), inspect({ _id: \"HashMap\", values: [[0, \"a\"]] }))\n    }\n  })\n\n  it(\"has\", () => {\n    const map = HM.make([key(0), value(\"a\")])\n\n    assertTrue(HM.has(key(0))(map))\n    assertFalse(HM.has(key(1))(map))\n  })\n\n  it(\"hasHash\", () => {\n    const map = HM.make([key(0), value(\"a\")])\n\n    assertTrue(HM.hasHash(key(0), Hash.hash(key(0)))(map))\n    assertFalse(HM.hasHash(key(1), Hash.hash(key(0)))(map))\n  })\n\n  it(\"hasBy\", () => {\n    const map = HM.make([key(0), value(\"a\")])\n\n    assertTrue(HM.hasBy(map, (v) => Equal.equals(v, value(\"a\"))))\n    assertTrue(HM.hasBy(map, (_, k) => Equal.equals(k, key(0))))\n    assertTrue(pipe(map, HM.hasBy((v) => Equal.equals(v, value(\"a\")))))\n    assertFalse(HM.hasBy(map, (v) => Equal.equals(v, value(\"b\"))))\n    assertFalse(HM.hasBy(map, (_, k) => Equal.equals(k, key(1))))\n    assertFalse(pipe(map, HM.hasBy((v) => Equal.equals(v, value(\"b\")))))\n  })\n\n  it(\"get\", () => {\n    const map = HM.make([key(0), value(\"a\")])\n\n    assertSome(HM.get(key(0))(map), value(\"a\"))\n    assertNone(HM.get(key(1))(map))\n  })\n\n  it(\"getHash\", () => {\n    const map = HM.make([key(0), value(\"a\")])\n\n    assertSome(HM.getHash(key(0), Hash.hash(0))(map), value(\"a\"))\n    assertNone(HM.getHash(key(1), Hash.hash(0))(map))\n  })\n\n  it(\"set\", () => {\n    const map = pipe(HM.empty<Key, Value>(), HM.set(key(0), value(\"a\")))\n\n    assertSome(HM.get(key(0))(map), value(\"a\"))\n  })\n\n  it(\"mutation\", () => {\n    let map: any = HM.empty()\n\n    assertFalse(map._editable)\n    map = HM.beginMutation(map)\n    assertTrue(map._editable)\n    map = HM.endMutation(map)\n    assertFalse(map._editable)\n  })\n\n  it(\"mutate\", () => {\n    const map = HM.empty<number, string>()\n    const result = pipe(\n      map,\n      HM.mutate((map) => {\n        pipe(map, HM.set(0, \"a\"))\n      })\n    )\n\n    assertSome(HM.get(0)(result), \"a\")\n    assertNone(HM.get(1)(result))\n  })\n\n  it(\"flatMap\", () => {\n    const map1 = HM.make([key(0), value(\"a\")], [key(1), value(\"bb\")])\n    const result1 = pipe(\n      map1,\n      HM.flatMap(({ s }) => {\n        const newKey = key(s.length)\n        const newValue = value(s)\n        return pipe(HM.empty<Key, Value>(), HM.set(newKey, newValue))\n      })\n    )\n\n    assertSome(HM.get(key(1))(result1), value(\"a\"))\n    assertSome(HM.get(key(2))(result1), value(\"bb\"))\n    assertNone(HM.get(key(3))(result1))\n\n    const map2 = HM.make([key(1), value(\"a\")], [key(2), value(\"bb\")])\n    const result2 = pipe(\n      map2,\n      HM.flatMap(({ s }, { n }) => {\n        const newKey = key(s.length + n)\n        const newValue = value(s)\n        return pipe(HM.empty<Key, Value>(), HM.set(newKey, newValue))\n      })\n    )\n\n    assertSome(HM.get(key(2))(result2), value(\"a\"))\n    assertSome(HM.get(key(4))(result2), value(\"bb\"))\n    assertNone(HM.get(key(6))(result2))\n  })\n\n  it(\"filterMap\", () => {\n    const map1 = HM.make([key(0), value(\"a\")], [key(1), value(\"bb\")])\n    const result1 = pipe(\n      map1,\n      HM.filterMap(({ s }) => s.length > 1 ? Option.some(value(s)) : Option.none())\n    )\n\n    assertNone(HM.get(key(0))(result1))\n    assertSome(HM.get(key(1))(result1), value(\"bb\"))\n\n    const map2 = HM.make([key(0), value(\"a\")], [key(1), value(\"bb\")])\n    const result2 = pipe(\n      map2,\n      HM.filterMap((v, { n }) => n > 0 ? Option.some(v) : Option.none())\n    )\n\n    assertNone(HM.get(key(0))(result2))\n    assertSome(HM.get(key(1))(result2), value(\"bb\"))\n  })\n\n  it(\"compact\", () => {\n    const map = HM.make([0, Option.some(\"a\")], [1, Option.none()])\n    const result = HM.compact(map)\n\n    strictEqual(HM.unsafeGet(0)(result), \"a\")\n    throws(() => HM.unsafeGet(1)(result))\n  })\n\n  it(\"filter\", () => {\n    const map1 = HM.make([key(0), value(\"a\")], [key(1), value(\"bb\")])\n    const result1 = pipe(map1, HM.filter(({ s }) => s.length > 1))\n\n    assertNone(HM.get(key(0))(result1))\n    assertSome(HM.get(key(1))(result1), value(\"bb\"))\n\n    const map2 = HM.make([key(0), value(\"a\")], [key(1), value(\"bb\")])\n    const result2 = pipe(map2, HM.filter(({ s }, { n }) => n > 0 && s.length > 0))\n\n    assertNone(HM.get(key(0))(result2))\n    assertSome(HM.get(key(1))(result2), value(\"bb\"))\n  })\n\n  it(\"forEach\", () => {\n    const map1 = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result1: Array<string> = []\n    pipe(\n      map1,\n      HM.forEach((v) => {\n        result1.push(v.s)\n      })\n    )\n\n    deepStrictEqual(result1, [\"a\", \"b\"])\n\n    const map2 = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result2: Array<readonly [number, string]> = []\n    pipe(\n      map2,\n      HM.forEach(({ s }, { n }) => {\n        result2.push([n, s])\n      })\n    )\n\n    deepStrictEqual(result2, [[0, \"a\"], [1, \"b\"]])\n  })\n\n  it(\"isEmpty\", () => {\n    assertTrue(HM.isEmpty(HM.make()))\n    assertFalse(HM.isEmpty(HM.make([key(0), value(\"a\")])))\n  })\n\n  it(\"map\", () => {\n    const map1 = HM.make([key(0), value(\"a\")], [key(1), value(\"bb\")])\n    const result1 = pipe(map1, HM.map(({ s }) => s.length))\n\n    assertSome(HM.get(key(0))(result1), 1)\n    assertSome(HM.get(key(1))(result1), 2)\n    assertNone(HM.get(key(2))(result1))\n\n    const map2 = HM.make([key(0), value(\"a\")], [key(1), value(\"bb\")])\n    const result2 = pipe(map2, HM.map(({ s }, { n }) => n + s.length))\n\n    assertSome(HM.get(key(0))(result2), 1)\n    assertSome(HM.get(key(1))(result2), 3)\n    assertNone(HM.get(key(2))(result2))\n  })\n\n  it(\"modifyAt\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result = pipe(\n      map,\n      HM.modifyAt(key(0), (maybe) =>\n        Option.isSome(maybe) ?\n          Option.some(value(\"test\")) :\n          Option.none())\n    )\n\n    assertSome(HM.get(key(0))(result), value(\"test\"))\n    assertSome(HM.get(key(1))(result), value(\"b\"))\n    assertNone(HM.get(key(2))(result))\n\n    assertNone(\n      HM.get(key(0))(pipe(\n        map,\n        HM.modifyAt(key(0), (): Option.Option<Value> => Option.none())\n      ))\n    )\n  })\n\n  it(\"modifyHash\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result = pipe(\n      map,\n      HM.modifyHash(key(0), Hash.hash(key(0)), (maybe) =>\n        Option.isSome(maybe) ?\n          Option.some(value(\"test\")) :\n          Option.none())\n    )\n\n    assertSome(HM.get(key(0))(result), value(\"test\"))\n    assertSome(HM.get(key(1))(result), value(\"b\"))\n    assertNone(HM.get(key(2))(result))\n  })\n\n  it(\"some\", () => {\n    const mapWith3LettersMax = HM.make([0, \"a\"], [1, \"bb\"], [3, \"ccc\"])\n\n    deepStrictEqual(HM.some(mapWith3LettersMax, (value) => value.length > 3), false)\n    deepStrictEqual(pipe(mapWith3LettersMax, HM.some((value) => value.length > 3)), false)\n\n    deepStrictEqual(HM.some(mapWith3LettersMax, (value) => value.length > 1), true)\n\n    deepStrictEqual(HM.some(mapWith3LettersMax, (value, key) => value.length > 1 && key === 0), false)\n\n    deepStrictEqual(HM.some(mapWith3LettersMax, (value, key) => value.length > 1 && key === 1), true)\n  })\n\n  it(\"every\", () => {\n    const mapWith3LettersMax = HM.make([0, \"a\"], [1, \"bb\"], [3, \"ccc\"])\n\n    deepStrictEqual(HM.every(mapWith3LettersMax, (value) => value.length > 2), false)\n    deepStrictEqual(pipe(mapWith3LettersMax, HM.every((value) => value.length > 2)), false)\n\n    deepStrictEqual(HM.every(mapWith3LettersMax, (value) => value.length >= 1), true)\n\n    deepStrictEqual(HM.every(mapWith3LettersMax, (value, key) => value.length >= 1 && key === 0), false)\n\n    deepStrictEqual(HM.every(mapWith3LettersMax, (value, key) => value.length >= 1 && key >= 0), true)\n  })\n\n  it(\"reduce\", () => {\n    const map1 = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result1 = pipe(map1, HM.reduce(\"\", (acc, { s }) => acc.length > 0 ? `${acc},${s}` : s))\n\n    strictEqual(result1, \"a,b\")\n\n    const map2 = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result2 = pipe(\n      map2,\n      HM.reduce(\n        \"\",\n        (acc, { s }, { n }) => acc.length > 0 ? `${acc},${n}:${s}` : `${n}:${s}`\n      )\n    )\n\n    strictEqual(result2, \"0:a,1:b\")\n  })\n\n  it(\"remove\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result = pipe(map, HM.remove(key(0)))\n\n    assertNone(HM.get(key(0))(result))\n    assertSome(HM.get(key(1))(result), value(\"b\"))\n  })\n\n  it(\"remove non existing key doesn't change the array\", () => {\n    const map = HM.make([13, 95], [90, 4])\n    const result = pipe(map, HM.remove(75))\n\n    deepStrictEqual(Array.from(HM.keySet(map)), Array.from(HM.keySet(result)))\n  })\n\n  it(\"removeMany\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result = pipe(map, HM.removeMany([key(0), key(1)]))\n\n    assertFalse(HM.isEmpty(map))\n    assertTrue(HM.isEmpty(result))\n  })\n\n  it(\"size\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result = HM.size(map)\n\n    strictEqual(result, 2)\n  })\n\n  it(\"union\", () => {\n    const map1 = HM.make([0, \"a\"], [1, \"b\"])\n    const map2 = HM.make([\"foo\", true], [\"bar\", false])\n    const result = HM.union(map2)(map1)\n\n    assertSome(pipe(result, HM.get(0)), \"a\")\n    assertSome(pipe(result, HM.get(1)), \"b\")\n    assertSome(pipe(result, HM.get(\"foo\")), true)\n    assertSome(pipe(result, HM.get(\"bar\")), false)\n  })\n\n  it(\"modify\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result = pipe(map, HM.modify(key(0), ({ s }) => value(`${s}-${s}`)))\n\n    assertSome(HM.get(key(0))(result), value(\"a-a\"))\n    assertSome(HM.get(key(1))(result), value(\"b\"))\n    assertNone(HM.get(key(2))(result))\n\n    assertNone(\n      HM.get(key(2))(pipe(map, HM.modify(key(2), ({ s }) => value(`${s}-${s}`))))\n    )\n  })\n\n  it(\"keys\", () => {\n    const map = HM.make([0, \"a\"], [1, \"b\"])\n    const result = Array.from(HM.keys(map))\n\n    deepStrictEqual(result, [0, 1])\n  })\n\n  it(\"keySet\", () => {\n    const hashMap = HM.make(\n      [key(0), value(\"a\")],\n      [key(1), value(\"b\")],\n      [key(1), value(\"c\")]\n    )\n\n    const result = HM.keySet(hashMap)\n\n    deepStrictEqual([...result], [key(0), key(1)])\n  })\n\n  it(\"values\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result = Array.from(HM.values(map))\n\n    deepStrictEqual(result, [value(\"a\"), value(\"b\")])\n  })\n\n  it(\"toValues\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result = HM.toValues(map)\n\n    deepStrictEqual(result, [value(\"a\"), value(\"b\")])\n  })\n\n  it(\"entries\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result = Array.from(HM.entries(map))\n\n    deepStrictEqual(result, [[key(0), value(\"a\")], [key(1), value(\"b\")]])\n  })\n\n  it(\"toEntries\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"b\")])\n    const result = HM.toEntries(map)\n\n    deepStrictEqual(result, [[key(0), value(\"a\")], [key(1), value(\"b\")]])\n  })\n\n  it(\"pipe()\", () => {\n    strictEqual(HM.empty().pipe(HM.set(\"key\", \"value\")).pipe(HM.size), HM.make([\"key\", \"value\"]).pipe(HM.size))\n  })\n\n  it(\"isHashMap\", () => {\n    assertTrue(HM.isHashMap(HM.empty()))\n    assertFalse(HM.isHashMap(null))\n    assertFalse(HM.isHashMap({}))\n  })\n\n  it(\"findFirst\", () => {\n    const map = HM.make([key(0), value(\"a\")], [key(1), value(\"bb\")])\n    assertSome(HM.findFirst(map, (_v, k) => k.n === 0), [key(0), value(\"a\")])\n    assertSome(HM.findFirst(map, (v, _k) => v.s === \"bb\"), [key(1), value(\"bb\")])\n    assertNone(HM.findFirst(map, (v, k) => k.n === 0 && v.s === \"bb\"))\n  })\n\n  it(\"countBy\", () => {\n    const map = HM.make([key(1), value(\"a\")], [key(2), value(\"b\")], [key(3), value(\"c\")])\n    strictEqual(HM.countBy(map, (_v, k) => k.n % 2 === 1), 2)\n    strictEqual(HM.countBy(map, (v, k) => k.n % 2 === 1 && v.s === \"a\"), 1)\n    strictEqual(HM.countBy(map, (v, k) => k.n % 2 === 1 && v.s === \"b\"), 0)\n\n    strictEqual(pipe(map, HM.countBy((_v, k) => k.n % 2 === 1)), 2)\n    strictEqual(pipe(map, HM.countBy((v, k) => k.n % 2 === 1 && v.s === \"a\")), 1)\n    strictEqual(pipe(map, HM.countBy((v, k) => k.n % 2 === 1 && v.s === \"b\")), 0)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/HashSet.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Equal, Hash, HashSet, pipe } from \"effect\"\n\nclass Value implements Equal.Equal {\n  constructor(readonly n: number) {}\n\n  [Hash.symbol](): number {\n    return Hash.hash(this.n)\n  }\n\n  [Equal.symbol](u: unknown): boolean {\n    return u instanceof Value && this.n === u.n\n  }\n}\n\ndescribe(\"HashSet\", () => {\n  function value(n: number): Value {\n    return new Value(n)\n  }\n\n  function makeTestHashSet(...values: Array<number>): HashSet.HashSet<Value> {\n    return HashSet.mutate<Value>((set) => {\n      for (const _value of values) {\n        HashSet.add(value(_value))(set)\n      }\n    })(HashSet.empty())\n  }\n\n  it(\"toString\", () => {\n    const map = HashSet.make(0, \"a\")\n    strictEqual(\n      String(map),\n      `{\n  \"_id\": \"HashSet\",\n  \"values\": [\n    0,\n    \"a\"\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    const map = HashSet.make(0, \"a\")\n    deepStrictEqual(map.toJSON(), { _id: \"HashSet\", values: [0, \"a\"] })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n    const map = HashSet.make(0, \"a\")\n    deepStrictEqual(inspect(map), inspect({ _id: \"HashSet\", values: [0, \"a\"] }))\n  })\n\n  it(\"add\", () => {\n    const set = makeTestHashSet(0, 1, 2)\n\n    deepStrictEqual(set, HashSet.make(value(0), value(1), value(2)))\n  })\n\n  it(\"mutation\", () => {\n    let set: any = HashSet.empty<number>()\n\n    assertFalse(set._keyMap._editable)\n    set = HashSet.beginMutation(set)\n    assertTrue(set._keyMap._editable)\n    set = HashSet.endMutation(set)\n    assertFalse(set._keyMap._editable)\n  })\n\n  it(\"flatMap\", () => {\n    const set = makeTestHashSet(0, 1, 2)\n    const result = pipe(set, HashSet.flatMap((v) => [`${v.n}`]))\n\n    deepStrictEqual(result, HashSet.make(\"0\", \"1\", \"2\"))\n  })\n\n  it(\"difference\", () => {\n    const set1 = makeTestHashSet(0, 1, 2)\n    const set2 = makeTestHashSet(2, 3, 4)\n    const result = pipe(set1, HashSet.difference(set2))\n\n    assertTrue(Equal.equals(result, HashSet.make(value(0), value(1))))\n  })\n\n  it(\"every\", () => {\n    const set = makeTestHashSet(0, 1, 2)\n\n    assertTrue(pipe(set, HashSet.every(({ n }) => n >= 0)))\n    assertFalse(pipe(set, HashSet.every(({ n }) => n > 0)))\n  })\n\n  it(\"filter\", () => {\n    const set = makeTestHashSet(0, 1, 2)\n    const result = pipe(set, HashSet.filter(({ n }) => n > 0))\n\n    deepStrictEqual(result, HashSet.make(value(1), value(2)))\n  })\n\n  it(\"forEach\", () => {\n    const set = makeTestHashSet(0, 1, 2)\n    const result: Array<number> = []\n\n    pipe(\n      set,\n      HashSet.forEach(({ n }) => {\n        result.push(n)\n      })\n    )\n\n    deepStrictEqual(result, [0, 1, 2])\n  })\n\n  it(\"has\", () => {\n    const set = makeTestHashSet(0, 1, 2)\n\n    assertTrue(pipe(set, HashSet.has(value(0))))\n    assertTrue(pipe(set, HashSet.has(value(1))))\n    assertTrue(pipe(set, HashSet.has(value(2))))\n    assertFalse(pipe(set, HashSet.has(value(3))))\n  })\n\n  it(\"intersection\", () => {\n    const set1 = makeTestHashSet(0, 1, 2)\n    const set2 = makeTestHashSet(2, 3, 4)\n    const result = pipe(set1, HashSet.intersection(set2))\n\n    deepStrictEqual(result, HashSet.make(value(2)))\n  })\n\n  it(\"isSubset\", () => {\n    const set1 = makeTestHashSet(0, 1)\n    const set2 = makeTestHashSet(1, 2)\n    const set3 = makeTestHashSet(0, 1, 2)\n\n    assertFalse(pipe(set1, HashSet.isSubset(set2)))\n    assertTrue(pipe(set1, HashSet.isSubset(set3)))\n  })\n\n  it(\"map\", () => {\n    const set = makeTestHashSet(0, 1, 2)\n    const result = pipe(set, HashSet.map(({ n }) => value(n + 1)))\n\n    deepStrictEqual(result, HashSet.make(value(1), value(2), value(3)))\n  })\n\n  it(\"mutate\", () => {\n    const set = makeTestHashSet(0, 1, 2)\n    const result = pipe(\n      set,\n      HashSet.mutate((set) => {\n        pipe(set, HashSet.add(value(3)))\n        pipe(set, HashSet.remove(value(0)))\n      })\n    )\n\n    assertFalse(pipe(result, HashSet.has(value(0))))\n    assertTrue(pipe(result, HashSet.has(value(1))))\n    assertTrue(pipe(result, HashSet.has(value(2))))\n    assertTrue(pipe(result, HashSet.has(value(3))))\n  })\n\n  it(\"partition\", () => {\n    const set = makeTestHashSet(0, 1, 2, 3, 4, 5)\n    const result = pipe(set, HashSet.partition(({ n }) => n > 2))\n\n    deepStrictEqual(result[0], HashSet.make(value(0), value(1), value(2)))\n    deepStrictEqual(result[1], HashSet.make(value(3), value(4), value(5)))\n  })\n\n  it(\"remove\", () => {\n    const set = makeTestHashSet(0, 1, 2)\n    const result = pipe(set, HashSet.remove(value(0)))\n\n    assertFalse(pipe(result, HashSet.has(value(0))))\n    assertTrue(pipe(result, HashSet.has(value(1))))\n    assertTrue(pipe(result, HashSet.has(value(2))))\n  })\n\n  it(\"size\", () => {\n    const hashSet = makeTestHashSet(0, 1, 2)\n    const result = HashSet.size(hashSet)\n\n    strictEqual(result, 3)\n  })\n\n  it(\"some\", () => {\n    const set = makeTestHashSet(0, 1, 2)\n\n    assertTrue(pipe(set, HashSet.some(({ n }) => n > 0)))\n    assertFalse(pipe(set, HashSet.some(({ n }) => n > 2)))\n  })\n\n  it(\"toggle\", () => {\n    let set = makeTestHashSet(0, 1, 2)\n    assertTrue(pipe(set, HashSet.has(value(0))))\n    set = pipe(set, HashSet.toggle(value(0)))\n    assertFalse(pipe(set, HashSet.has(value(0))))\n    set = pipe(set, HashSet.toggle(value(0)))\n    assertTrue(pipe(set, HashSet.has(value(0))))\n  })\n\n  it(\"union\", () => {\n    const set1 = makeTestHashSet(0, 1, 2)\n    const set2 = makeTestHashSet(2, 3, 4)\n    const result = pipe(set1, HashSet.union(set2))\n\n    deepStrictEqual(result, HashSet.make(value(0), value(1), value(2), value(3), value(4)))\n  })\n\n  it(\"values\", () => {\n    const hashSet = makeTestHashSet(0, 1, 2)\n\n    const result = Array.from(HashSet.values(hashSet))\n\n    deepStrictEqual(result, [value(0), value(1), value(2)])\n  })\n\n  it(\"toValues\", () => {\n    const hashSet = makeTestHashSet(0, 1, 2)\n\n    const result = HashSet.toValues(hashSet)\n\n    deepStrictEqual(result, [value(0), value(1), value(2)])\n  })\n\n  it(\"pipe()\", () => {\n    strictEqual(\n      HashSet.empty<string>().pipe(HashSet.add(\"value\"), HashSet.size),\n      HashSet.make(\"value\").pipe(HashSet.size)\n    )\n  })\n\n  it(\"isHashSet\", () => {\n    assertTrue(HashSet.isHashSet(HashSet.empty()))\n    assertFalse(HashSet.isHashSet(null))\n    assertFalse(HashSet.isHashSet({}))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Inspectable.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { Inspectable, Redacted } from \"effect\"\n\ndescribe(\"Inspectable\", () => {\n  describe(\"formatUnknown\", () => {\n    const format = Inspectable.formatUnknown\n    it(\"null\", () => {\n      strictEqual(format(null), `null`)\n    })\n\n    it(\"undefined\", () => {\n      strictEqual(format(undefined), `undefined`)\n    })\n\n    it(\"string\", () => {\n      strictEqual(format(\"a\"), `\"a\"`)\n    })\n\n    it(\"number\", () => {\n      strictEqual(format(123), `123`)\n    })\n\n    it(\"boolean\", () => {\n      strictEqual(format(true), `true`)\n    })\n\n    it(\"symbol\", () => {\n      strictEqual(format(Symbol(\"a\")), `Symbol(a)`)\n    })\n\n    it(\"bigint\", () => {\n      strictEqual(format(BigInt(123)), `123n`)\n    })\n\n    it(\"custom toString method\", () => {\n      strictEqual(format({ toString: () => \"custom\" }), `custom`)\n    })\n\n    it(\"array\", () => {\n      strictEqual(format([1, 2, 3n]), `[1,2,3n]`)\n    })\n\n    it(\"circular array\", () => {\n      const arr: any = [1]\n      arr.push(arr)\n      strictEqual(format(arr), `[1,[Circular]]`)\n    })\n\n    it(\"Set\", () => {\n      strictEqual(format(new Set([1, 2, 3])), `Set([1,2,3])`)\n    })\n\n    it(\"Map\", () => {\n      strictEqual(format(new Map([[\"a\", 1], [\"b\", 2]])), `Map([[\"a\",1],[\"b\",2]])`)\n    })\n\n    it(\"circular Map contents\", () => {\n      const obj: any = { a: 1 }\n      const map = new Map([[\"obj\", obj]])\n      obj.map = map\n      strictEqual(format(map), `Map([[\"obj\",{\"a\":1,\"map\":[Circular]}]])`)\n    })\n\n    it(\"circular Set contents\", () => {\n      const obj: any = { a: 1 }\n      const set = new Set([obj])\n      obj.set = set\n      strictEqual(format(set), `Set([{\"a\":1,\"set\":[Circular]}])`)\n    })\n\n    it(\"object\", () => {\n      strictEqual(format({ a: 1 }), `{\"a\":1}`)\n      strictEqual(format({ a: 1, b: 2 }), `{\"a\":1,\"b\":2}`)\n      strictEqual(format({ [Symbol.for(\"a\")]: 1 }), `{Symbol(a):1}`)\n      strictEqual(format({ a: 1, b: [1, 2, 3n] }), `{\"a\":1,\"b\":[1,2,3n]}`)\n    })\n\n    it(\"circular object\", () => {\n      const obj: any = { a: 1 }\n      obj.b = obj\n      strictEqual(format(obj), `{\"a\":1,\"b\":[Circular]}`)\n    })\n\n    it(\"object with null prototype\", () => {\n      strictEqual(format(Object.create(null)), `{}`)\n      strictEqual(format(Object.create(null, { a: { value: 1 } })), `{\"a\":1}`)\n    })\n\n    it(\"Error\", () => {\n      strictEqual(format(new Error(\"a\")), `Error: a`)\n      strictEqual(format(new Error(\"a\", { cause: \"b\" })), `Error: a (cause: \"b\")`)\n    })\n\n    it(\"Date\", () => {\n      strictEqual(format(new Date(0)), `1970-01-01T00:00:00.000Z`)\n      strictEqual(format(new Date(\"invalid\")), `Invalid Date`)\n    })\n\n    it(\"RegExp\", () => {\n      strictEqual(format(/a/), `/a/`)\n    })\n\n    it(\"Redacted\", () => {\n      strictEqual(format(Redacted.make(\"a\")), `<redacted>`)\n    })\n\n    describe(\"whitespace\", () => {\n      it(\"object\", () => {\n        strictEqual(format({ a: 1 }, { space: 2 }), `{\"a\":1}`)\n        strictEqual(\n          format({ a: 1, b: 2 }, { space: 2 }),\n          `{\n  \"a\": 1,\n  \"b\": 2\n}`\n        )\n        strictEqual(\n          format({ a: 1, b: [1, 2, 3n] }, { space: 2 }),\n          `{\n  \"a\": 1,\n  \"b\": [\n    1,\n    2,\n    3n\n  ]\n}`\n        )\n        strictEqual(format({ [Symbol.for(\"a\")]: 1 }, { space: 2 }), `{Symbol(a):1}`)\n      })\n\n      it(\"circular object\", () => {\n        const obj: any = { a: 1 }\n        obj.b = obj\n        strictEqual(\n          format(obj, { space: 2 }),\n          `{\n  \"a\": 1,\n  \"b\": [Circular]\n}`\n        )\n      })\n\n      it(\"object with null prototype\", () => {\n        strictEqual(format(Object.create(null), { space: 2 }), `{}`)\n        strictEqual(\n          format(Object.create(null, { a: { value: 1 } }), { space: 2 }),\n          `{\"a\":1}`\n        )\n      })\n    })\n  })\n\n  describe(\"toString\", () => {\n    it(\"primitives\", () => {\n      strictEqual(Inspectable.format(null), \"null\")\n      strictEqual(Inspectable.format(undefined), undefined)\n      strictEqual(Inspectable.format(1), \"1\")\n      strictEqual(Inspectable.format(\"a\"), `\"a\"`)\n      strictEqual(Inspectable.format(true), \"true\")\n    })\n\n    it(\"empty collections\", () => {\n      strictEqual(Inspectable.format({}), \"{}\")\n      strictEqual(Inspectable.format([]), \"[]\")\n    })\n\n    it(\"objects\", () => {\n      strictEqual(\n        Inspectable.format({ a: 1 }),\n        `{\n  \"a\": 1\n}`\n      )\n      strictEqual(\n        Inspectable.format({ a: 1, b: 2 }),\n        `{\n  \"a\": 1,\n  \"b\": 2\n}`\n      )\n      strictEqual(\n        Inspectable.format({ a: 1, b: { c: 2 } }),\n        `{\n  \"a\": 1,\n  \"b\": {\n    \"c\": 2\n  }\n}`\n      )\n      strictEqual(Inspectable.format({ a: undefined }), \"{}\")\n    })\n\n    it(\"arrays\", () => {\n      strictEqual(\n        Inspectable.format([1, 2, 3]),\n        `[\n  1,\n  2,\n  3\n]`\n      )\n      strictEqual(\n        Inspectable.format([1, [2, 3], 4]),\n        `[\n  1,\n  [\n    2,\n    3\n  ],\n  4\n]`\n      )\n    })\n\n    it(\"mixed\", () => {\n      strictEqual(\n        Inspectable.format({ \"a\": [] }),\n        `{\n  \"a\": []\n}`\n      )\n      strictEqual(\n        Inspectable.format({\n          \"_id\": \"Cause\",\n          \"_tag\": \"Fail\",\n          \"errors\": [\n            {\n              \"value\": { \"_id\": \"Chunk\", \"values\": [0, 1, 2] }\n            },\n            {\n              \"value\": { \"_id\": \"Chunk\", \"values\": [\"a\", \"b\"] }\n            }\n          ]\n        }),\n        `{\n  \"_id\": \"Cause\",\n  \"_tag\": \"Fail\",\n  \"errors\": [\n    {\n      \"value\": {\n        \"_id\": \"Chunk\",\n        \"values\": [\n          0,\n          1,\n          2\n        ]\n      }\n    },\n    {\n      \"value\": {\n        \"_id\": \"Chunk\",\n        \"values\": [\n          \"a\",\n          \"b\"\n        ]\n      }\n    }\n  ]\n}`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Iterable.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertNone, assertSome, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Iterable as Iter, Number, Option, pipe } from \"effect\"\nimport type { Predicate } from \"effect/Predicate\"\n\nconst symA = Symbol.for(\"a\")\nconst symB = Symbol.for(\"b\")\nconst symC = Symbol.for(\"c\")\n\nconst toArray = <A>(i: Iterable<A>) => {\n  if (Array.isArray(i)) {\n    throw new Error(\"not an iterable\")\n  }\n  return Array.from(i)\n}\n\ndescribe(\"Iterable\", () => {\n  it(\"of\", () => {\n    deepStrictEqual(Array.from(Iter.of(1)), [1])\n  })\n\n  describe(\"iterable inputs\", () => {\n    it(\"prepend\", () => {\n      deepStrictEqual(pipe([1, 2, 3], Iter.prepend(0), toArray), [0, 1, 2, 3])\n      deepStrictEqual(pipe([[2]], Iter.prepend([1]), toArray), [[1], [2]])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Iter.prepend(0), toArray), [0, 1, 2, 3])\n      deepStrictEqual(pipe(new Set([[2]]), Iter.prepend([1]), toArray), [[1], [2]])\n    })\n\n    it(\"prependAll\", () => {\n      deepStrictEqual(pipe([3, 4], Iter.prependAll([1, 2]), toArray), [1, 2, 3, 4])\n\n      deepStrictEqual(pipe([3, 4], Iter.prependAll(new Set([1, 2])), toArray), [1, 2, 3, 4])\n      deepStrictEqual(pipe(new Set([3, 4]), Iter.prependAll([1, 2]), toArray), [1, 2, 3, 4])\n    })\n\n    it(\"append\", () => {\n      deepStrictEqual(pipe([1, 2, 3], Iter.append(4), toArray), [1, 2, 3, 4])\n      deepStrictEqual(pipe([[1]], Iter.append([2]), toArray), [[1], [2]])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Iter.append(4), toArray), [1, 2, 3, 4])\n      deepStrictEqual(pipe(new Set([[1]]), Iter.append([2]), toArray), [[1], [2]])\n    })\n\n    it(\"appendAll\", () => {\n      deepStrictEqual(pipe([1, 2], Iter.appendAll([3, 4]), toArray), [1, 2, 3, 4])\n\n      deepStrictEqual(pipe([1, 2], Iter.appendAll(new Set([3, 4])), toArray), [1, 2, 3, 4])\n      deepStrictEqual(pipe(new Set([1, 2]), Iter.appendAll([3, 4]), toArray), [1, 2, 3, 4])\n    })\n\n    it(\"scan\", () => {\n      const f = (b: number, a: number) => b - a\n      deepStrictEqual(pipe([1, 2, 3], Iter.scan(10, f), toArray), [10, 9, 7, 4])\n      deepStrictEqual(pipe([0], Iter.scan(10, f), toArray), [10, 10])\n      deepStrictEqual(pipe([], Iter.scan(10, f), toArray), [10])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Iter.scan(10, f), toArray), [10, 9, 7, 4])\n      deepStrictEqual(pipe(new Set([0]), Iter.scan(10, f), toArray), [10, 10])\n      deepStrictEqual(pipe(new Set([]), Iter.scan(10, f), toArray), [10])\n    })\n\n    it(\"take\", () => {\n      deepStrictEqual(pipe([1, 2, 3, 4], Iter.take(2), toArray), [1, 2])\n      deepStrictEqual(pipe([1, 2, 3, 4], Iter.take(0), toArray), [])\n      // out of bounds\n      deepStrictEqual(pipe([1, 2, 3, 4], Iter.take(-10), toArray), [])\n      deepStrictEqual(pipe([1, 2, 3, 4], Iter.take(10), toArray), [1, 2, 3, 4])\n\n      deepStrictEqual(pipe(new Set([1, 2, 3, 4]), Iter.take(2), toArray), [1, 2])\n      deepStrictEqual(pipe(new Set([1, 2, 3, 4]), Iter.take(0), toArray), [])\n      // out of bounds\n      deepStrictEqual(pipe(new Set([1, 2, 3, 4]), Iter.take(-10), toArray), [])\n      deepStrictEqual(pipe(new Set([1, 2, 3, 4]), Iter.take(10), toArray), [1, 2, 3, 4])\n    })\n\n    it(\"takeWhile\", () => {\n      const f = (n: number) => n % 2 === 0\n      deepStrictEqual(pipe([2, 4, 3, 6], Iter.takeWhile(f), toArray), [2, 4])\n      deepStrictEqual(pipe(Iter.empty(), Iter.takeWhile(f), toArray), [])\n      deepStrictEqual(pipe([1, 2, 4], Iter.takeWhile(f), toArray), [])\n      deepStrictEqual(pipe([2, 4], Iter.takeWhile(f), toArray), [2, 4])\n\n      deepStrictEqual(pipe(new Set([2, 4, 3, 6]), Iter.takeWhile(f), toArray), [2, 4])\n      deepStrictEqual(pipe(new Set<number>(), Iter.takeWhile(f), toArray), [])\n      deepStrictEqual(pipe(new Set([1, 2, 4]), Iter.takeWhile(f), toArray), [])\n      deepStrictEqual(pipe(new Set([2, 4]), Iter.takeWhile(f), toArray), [2, 4])\n    })\n\n    it(\"drop\", () => {\n      deepStrictEqual(pipe(Iter.empty(), Iter.drop(0), toArray), [])\n      deepStrictEqual(pipe([1, 2], Iter.drop(0), toArray), [1, 2])\n      deepStrictEqual(pipe([1, 2], Iter.drop(1), toArray), [2])\n      deepStrictEqual(pipe([1, 2], Iter.drop(2), toArray), [])\n      // out of bound\n      deepStrictEqual(pipe(Iter.empty(), Iter.drop(1), toArray), [])\n      deepStrictEqual(pipe(Iter.empty(), Iter.drop(-1), toArray), [])\n      deepStrictEqual(pipe([1, 2], Iter.drop(3), toArray), [])\n      deepStrictEqual(pipe([1, 2], Iter.drop(-1), toArray), [1, 2])\n\n      deepStrictEqual(pipe(new Set(), Iter.drop(0), toArray), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Iter.drop(0), toArray), [1, 2])\n      deepStrictEqual(pipe(new Set([1, 2]), Iter.drop(1), toArray), [2])\n      deepStrictEqual(pipe(new Set([1, 2]), Iter.drop(2), toArray), [])\n      // out of bound\n      deepStrictEqual(pipe(new Set(), Iter.drop(1), toArray), [])\n      deepStrictEqual(pipe(new Set(), Iter.drop(-1), toArray), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Iter.drop(3), toArray), [])\n      deepStrictEqual(pipe(new Set([1, 2]), Iter.drop(-1), toArray), [1, 2])\n    })\n\n    describe(\"findFirst\", () => {\n      it(\"boolean-returning overloads\", () => {\n        assertNone(pipe([], Iter.findFirst((n) => n % 2 === 0)))\n        assertSome(pipe([1, 2, 3], Iter.findFirst((n) => n % 2 === 0)), 2)\n        assertSome(pipe([1, 2, 3, 4], Iter.findFirst((n) => n % 2 === 0)), 2)\n\n        assertNone(pipe(new Set<number>(), Iter.findFirst((n) => n % 2 === 0)))\n        assertSome(pipe(new Set([1, 2, 3]), Iter.findFirst((n) => n % 2 === 0)), 2)\n        assertSome(pipe(new Set([1, 2, 3, 4]), Iter.findFirst((n) => n % 2 === 0)), 2)\n      })\n\n      it(\"Option-returning overloads\", () => {\n        assertNone(pipe([], Iter.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())))\n        assertSome(\n          pipe([1, 2, 3], Iter.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n        assertSome(\n          pipe([1, 2, 3, 4], Iter.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n\n        assertNone(\n          pipe(new Set<number>(), Iter.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none()))\n        )\n        assertSome(\n          pipe(new Set([1, 2, 3]), Iter.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n        assertSome(\n          pipe(new Set([1, 2, 3, 4]), Iter.findFirst((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n      })\n    })\n\n    describe(\"findLast\", () => {\n      it(\"boolean-returning overloads\", () => {\n        assertNone(pipe([], Iter.findLast((n) => n % 2 === 0)))\n        assertSome(pipe([1, 2, 3], Iter.findLast((n) => n % 2 === 0)), 2)\n        assertSome(pipe([1, 2, 3, 4], Iter.findLast((n) => n % 2 === 0)), 4)\n\n        assertNone(pipe(new Set<number>(), Iter.findLast((n) => n % 2 === 0)))\n        assertSome(pipe(new Set([1, 2, 3]), Iter.findLast((n) => n % 2 === 0)), 2)\n        assertSome(pipe(new Set([1, 2, 3, 4]), Iter.findLast((n) => n % 2 === 0)), 4)\n      })\n\n      it(\"Option-returning overloads\", () => {\n        assertNone(pipe([], Iter.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())))\n        assertSome(\n          pipe([1, 2, 3], Iter.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n        assertSome(\n          pipe([1, 2, 3, 4], Iter.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [4, 3]\n        )\n\n        assertNone(\n          pipe(new Set<number>(), Iter.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none()))\n        )\n        assertSome(\n          pipe(new Set([1, 2, 3]), Iter.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [2, 1]\n        )\n        assertSome(\n          pipe(new Set([1, 2, 3, 4]), Iter.findLast((n, i) => n % 2 === 0 ? Option.some([n, i]) : Option.none())),\n          [4, 3]\n        )\n      })\n    })\n\n    it(\"zip\", () => {\n      deepStrictEqual(pipe(new Set([]), Iter.zip(new Set([\"a\", \"b\", \"c\", \"d\"])), toArray), [])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Iter.zip(new Set([])), toArray), [])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Iter.zip(new Set([\"a\", \"b\", \"c\", \"d\"])), toArray), [\n        [1, \"a\"],\n        [2, \"b\"],\n        [3, \"c\"]\n      ])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Iter.zip(new Set([\"a\", \"b\", \"c\", \"d\"])), toArray), [\n        [1, \"a\"],\n        [2, \"b\"],\n        [3, \"c\"]\n      ])\n    })\n\n    it(\"zipWith\", () => {\n      deepStrictEqual(\n        pipe(new Set([1, 2, 3]), Iter.zipWith(new Set([]), (n, s) => s + n), toArray),\n        []\n      )\n      deepStrictEqual(\n        pipe(new Set([]), Iter.zipWith(new Set([\"a\", \"b\", \"c\", \"d\"]), (n, s) => s + n), toArray),\n        []\n      )\n      deepStrictEqual(\n        pipe(new Set([]), Iter.zipWith(new Set([]), (n, s) => s + n), toArray),\n        []\n      )\n      deepStrictEqual(\n        pipe(new Set([1, 2, 3]), Iter.zipWith(new Set([\"a\", \"b\", \"c\", \"d\"]), (n, s) => s + n), toArray),\n        [\"a1\", \"b2\", \"c3\"]\n      )\n    })\n\n    it(\"intersperse\", () => {\n      deepStrictEqual(pipe([], Iter.intersperse(0), toArray), [])\n      deepStrictEqual(pipe([1], Iter.intersperse(0), toArray), [1])\n      deepStrictEqual(pipe([1, 2, 3], Iter.intersperse(0), toArray), [1, 0, 2, 0, 3])\n      deepStrictEqual(pipe([1, 2], Iter.intersperse(0), toArray), [1, 0, 2])\n      deepStrictEqual(pipe([1, 2, 3, 4], Iter.intersperse(0), toArray), [1, 0, 2, 0, 3, 0, 4])\n\n      deepStrictEqual(pipe(new Set([]), Iter.intersperse(0), toArray), [])\n      deepStrictEqual(pipe(new Set([1]), Iter.intersperse(0), toArray), [1])\n      deepStrictEqual(pipe(new Set([1, 2, 3]), Iter.intersperse(0), toArray), [1, 0, 2, 0, 3])\n      deepStrictEqual(pipe(new Set([1, 2]), Iter.intersperse(0), toArray), [1, 0, 2])\n      deepStrictEqual(pipe(new Set([1, 2, 3, 4]), Iter.intersperse(0), toArray), [1, 0, 2, 0, 3, 0, 4])\n    })\n\n    it(\"containsWith\", () => {\n      const contains = Iter.containsWith(Number.Equivalence)\n      assertTrue(pipe([1, 2, 3], contains(2)))\n      assertFalse(pipe([1, 2, 3], contains(0)))\n\n      assertTrue(pipe(new Set([1, 2, 3]), contains(2)))\n      assertFalse(pipe(new Set([1, 2, 3]), contains(0)))\n    })\n\n    it(\"contains\", () => {\n      const contains = Iter.contains\n      assertTrue(pipe([1, 2, 3], contains(2)))\n      assertFalse(pipe([1, 2, 3], contains(0)))\n\n      assertTrue(pipe(new Set([1, 2, 3]), contains(2)))\n      assertFalse(pipe(new Set([1, 2, 3]), contains(0)))\n    })\n\n    it(\"dedupeAdjacentWith\", () => {\n      const dedupeAdjacent = Iter.dedupeAdjacentWith(Number.Equivalence)\n      deepStrictEqual(toArray(dedupeAdjacent([])), [])\n      deepStrictEqual(toArray(dedupeAdjacent([1, 2, 3])), [1, 2, 3])\n      deepStrictEqual(toArray(dedupeAdjacent([1, 2, 2, 3, 3])), [1, 2, 3])\n    })\n  })\n\n  it(\"flatMapNullable\", () => {\n    const f = Iter.flatMapNullable((n: number) => (n > 0 ? n : null))\n    deepStrictEqual(pipe([], f, toArray), [])\n    deepStrictEqual(pipe([1], f, toArray), [1])\n    deepStrictEqual(pipe([-1], f, toArray), [])\n  })\n\n  it(\"unfold\", () => {\n    const as = Iter.unfold(5, (n) => (n > 0 ? Option.some([n, n - 1]) : Option.none()))\n    deepStrictEqual(toArray(as), [5, 4, 3, 2, 1])\n  })\n\n  it(\"map\", () => {\n    deepStrictEqual(\n      pipe([1, 2, 3], Iter.map((n) => n * 2), toArray),\n      [2, 4, 6]\n    )\n    deepStrictEqual(\n      pipe([\"a\", \"b\"], Iter.map((s, i) => s + i), toArray),\n      [\"a0\", \"b1\"]\n    )\n  })\n\n  it(\"flatMap\", () => {\n    deepStrictEqual(\n      pipe([1, 2, 3], Iter.flatMap((n) => [n, n + 1]), toArray),\n      [1, 2, 2, 3, 3, 4]\n    )\n    const f = (n: number, i: number) => [n + i]\n    deepStrictEqual(pipe([], Iter.flatMap(f), toArray), [])\n    deepStrictEqual(pipe([1, 2, 3], Iter.flatMap(f), toArray), [1, 3, 5])\n  })\n\n  it(\"getSomes\", () => {\n    deepStrictEqual(toArray(Iter.getSomes([])), [])\n    deepStrictEqual(toArray(Iter.getSomes([Option.some(1), Option.some(2), Option.some(3)])), [\n      1,\n      2,\n      3\n    ])\n    deepStrictEqual(toArray(Iter.getSomes([Option.some(1), Option.none(), Option.some(3)])), [\n      1,\n      3\n    ])\n  })\n\n  it(\"filter\", () => {\n    deepStrictEqual(toArray(Iter.filter([1, 2, 3], (n) => n % 2 === 1)), [1, 3])\n    deepStrictEqual(toArray(Iter.filter([Option.some(3), Option.some(2), Option.some(1)], Option.isSome)), [\n      Option.some(3),\n      Option.some(2),\n      Option.some(1)\n    ])\n    deepStrictEqual(toArray(Iter.filter([Option.some(3), Option.none(), Option.some(1)], Option.isSome)), [\n      Option.some(3),\n      Option.some(1)\n    ])\n    deepStrictEqual(toArray(Iter.filter([\"a\", \"b\", \"c\"], (_, i) => i % 2 === 0)), [\"a\", \"c\"])\n  })\n\n  it(\"filterMap\", () => {\n    const f = (n: number) => (n % 2 === 0 ? Option.none() : Option.some(n))\n    deepStrictEqual(pipe([1, 2, 3], Iter.filterMap(f), toArray), [1, 3])\n    deepStrictEqual(pipe([], Iter.filterMap(f), toArray), [])\n    const g = (n: number, i: number) => ((i + n) % 2 === 0 ? Option.none() : Option.some(n))\n    deepStrictEqual(pipe([1, 2, 4], Iter.filterMap(g), toArray), [1, 2])\n    deepStrictEqual(pipe([], Iter.filterMap(g), toArray), [])\n  })\n\n  it(\"isEmpty\", () => {\n    assertFalse(Iter.isEmpty([1, 2, 3]))\n    assertTrue(Iter.isEmpty([]))\n  })\n\n  it(\"head\", () => {\n    const as: ReadonlyArray<number> = [1, 2, 3]\n    assertSome(Iter.head(as), 1)\n    assertNone(Iter.head([]))\n  })\n\n  it(\"chunksOf\", () => {\n    deepStrictEqual(toArray(Iter.chunksOf(2)([1, 2, 3, 4, 5])), [\n      [1, 2],\n      [3, 4],\n      [5]\n    ])\n    deepStrictEqual(toArray(Iter.chunksOf(2)([1, 2, 3, 4, 5, 6])), [\n      [1, 2],\n      [3, 4],\n      [5, 6]\n    ])\n    deepStrictEqual(toArray(Iter.chunksOf(1)([1, 2, 3, 4, 5])), [[1], [2], [3], [4], [5]])\n    deepStrictEqual(toArray(Iter.chunksOf(5)([1, 2, 3, 4, 5])), [[1, 2, 3, 4, 5]])\n    // out of bounds\n    deepStrictEqual(toArray(Iter.chunksOf(0)([1, 2, 3, 4, 5])), [[1], [2], [3], [4], [5]])\n    deepStrictEqual(toArray(Iter.chunksOf(-1)([1, 2, 3, 4, 5])), [[1], [2], [3], [4], [5]])\n\n    const assertSingleChunk = (\n      input: Iterable<number>,\n      n: number\n    ) => {\n      const chunks = toArray(Iter.chunksOf(n)(input))\n      strictEqual(chunks.length, 1)\n      deepStrictEqual(chunks[0], input)\n    }\n    // n = length\n    assertSingleChunk([1, 2], 2)\n    // n out of bounds\n    assertSingleChunk([1, 2], 3)\n  })\n\n  it(\"flatten\", () => {\n    deepStrictEqual(toArray(Iter.flatten([[1], [2], [3]])), [1, 2, 3])\n  })\n\n  it(\"groupWith\", () => {\n    const groupWith = Iter.groupWith(Number.Equivalence)\n    deepStrictEqual(toArray(groupWith([1, 2, 1, 1])), [[1], [2], [1, 1]])\n    deepStrictEqual(toArray(groupWith([1, 2, 1, 1, 3])), [[1], [2], [1, 1], [3]])\n  })\n\n  it(\"groupBy\", () => {\n    deepStrictEqual(Iter.groupBy((_) => \"\")([]), {})\n    deepStrictEqual(Iter.groupBy((a) => `${a}`)([1]), { \"1\": [1] })\n    deepStrictEqual(\n      Iter.groupBy((s: string) => `${s.length}`)([\"foo\", \"bar\", \"foobar\"]),\n      {\n        \"3\": [\"foo\", \"bar\"],\n        \"6\": [\"foobar\"]\n      }\n    )\n    deepStrictEqual(Iter.groupBy([\"a\", \"b\"], (s) => s === \"a\" ? symA : s === \"b\" ? symB : symC), {\n      [symA]: [\"a\"],\n      [symB]: [\"b\"]\n    })\n    deepStrictEqual(Iter.groupBy([\"a\", \"b\", \"c\", \"d\"], (s) => s === \"a\" ? symA : s === \"b\" ? symB : symC), {\n      [symA]: [\"a\"],\n      [symB]: [\"b\"],\n      [symC]: [\"c\", \"d\"]\n    })\n  })\n\n  it(\"makeBy\", () => {\n    deepStrictEqual(\n      pipe(\n        Iter.makeBy((n) => n * 2),\n        Iter.take(5),\n        toArray\n      ),\n      [0, 2, 4, 6, 8]\n    )\n    deepStrictEqual(toArray(Iter.makeBy((n) => n * 2, { length: 5 })), [0, 2, 4, 6, 8])\n    deepStrictEqual(toArray(Iter.makeBy((n) => n * 2, { length: 2.2 })), [0, 2])\n  })\n\n  it(\"replicate\", () => {\n    deepStrictEqual(toArray(Iter.replicate(\"a\", 0)), [\"a\"])\n    deepStrictEqual(toArray(Iter.replicate(\"a\", -1)), [\"a\"])\n    deepStrictEqual(toArray(Iter.replicate(\"a\", 3)), [\"a\", \"a\", \"a\"])\n    deepStrictEqual(toArray(Iter.replicate(\"a\", 2.2)), [\"a\", \"a\"])\n  })\n\n  it(\"range\", () => {\n    deepStrictEqual(toArray(Iter.range(0, 0)), [0])\n    deepStrictEqual(toArray(Iter.range(0, 1)), [0, 1])\n    deepStrictEqual(toArray(Iter.range(1, 5)), [1, 2, 3, 4, 5])\n    deepStrictEqual(toArray(Iter.range(10, 15)), [10, 11, 12, 13, 14, 15])\n    deepStrictEqual(toArray(Iter.range(-1, 0)), [-1, 0])\n    deepStrictEqual(toArray(Iter.range(-5, -1)), [-5, -4, -3, -2, -1])\n    // out of bound\n    deepStrictEqual(Array.from(Iter.range(2, 1)), [2])\n    deepStrictEqual(Array.from(Iter.range(-1, -2)), [-1])\n  })\n\n  it(\"empty\", () => {\n    deepStrictEqual(toArray(Iter.empty()).length, 0)\n  })\n\n  it(\"some\", () => {\n    const isPositive: Predicate<number> = (n) => n > 0\n    assertTrue(Iter.some([-1, -2, 3], isPositive))\n    assertFalse(Iter.some([-1, -2, -3], isPositive))\n  })\n\n  it(\"size\", () => {\n    strictEqual(Iter.size(Iter.empty()), 0)\n    strictEqual(Iter.size([]), 0)\n    strictEqual(Iter.size([\"a\"]), 1)\n  })\n\n  it(\"forEach\", () => {\n    const log: Array<string> = []\n    Iter.forEach([\"a\", \"b\", \"c\"], (a, i) => log.push(`${a}-${i}`))\n    deepStrictEqual(log, [\"a-0\", \"b-1\", \"c-2\"])\n  })\n\n  it(\"countBy\", () => {\n    deepStrictEqual(Iter.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0), 2)\n    deepStrictEqual(pipe([1, 2, 3, 4, 5], Iter.countBy((n) => n % 2 === 0)), 2)\n\n    deepStrictEqual(Iter.countBy(new Map([[\"a\", 1], [\"b\", 2], [\"c\", 3]]), ([key, n]) => n % 2 === 1 && key !== \"c\"), 1)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/KeyedPool.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { Array, Duration, Effect, Fiber, KeyedPool, pipe, Random, Ref } from \"effect\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"KeyedPool\", () => {\n  it.scoped(\"acquire release many successfully while other key is blocked\", () =>\n    Effect.gen(function*() {\n      const N = 10\n      const pool = yield* KeyedPool.make({\n        acquire: (key: string) => Effect.succeed(key),\n        size: 4\n      })\n      yield* pool.pipe(\n        KeyedPool.get(\"key1\"),\n        Effect.repeatN(3),\n        Effect.asVoid\n      )\n      const fiber = yield* Effect.fork(\n        Effect.forEach(\n          Array.range(1, N),\n          () =>\n            Effect.scoped(\n              Effect.zipRight(\n                KeyedPool.get(pool, \"key2\"),\n                Effect.sleep(Duration.millis(10))\n              )\n            ),\n          { concurrency: \"unbounded\", discard: true }\n        )\n      )\n      yield* TestClock.adjust(Duration.millis(10 * N))\n      const result = yield* Fiber.join(fiber)\n      strictEqual(result, undefined)\n    }))\n\n  it.scoped(\"acquire release many with invalidates\", () =>\n    Effect.gen(function*() {\n      const N = 10\n      const counter = yield* Ref.make(0)\n      const pool = yield* KeyedPool.make({\n        acquire: (key) => Ref.modify(counter, (n) => [`${key}-${n}`, n + 1] as const),\n        size: 4\n      })\n      const fiber = yield* Effect.fork(\n        Effect.forEach(\n          Array.range(1, N),\n          () =>\n            Effect.scoped(pipe(\n              KeyedPool.get(pool, \"key1\"),\n              Effect.flatMap((value) =>\n                Effect.zipRight(\n                  Effect.whenEffect(\n                    KeyedPool.invalidate(pool, value),\n                    Random.nextBoolean\n                  ),\n                  Effect.flatMap(\n                    Random.nextIntBetween(0, 15 + 1),\n                    (n) => Effect.sleep(Duration.millis(n))\n                  )\n                )\n              )\n            )),\n          { concurrency: \"unbounded\", discard: true }\n        )\n      )\n      yield* TestClock.adjust(Duration.millis(15 * N))\n      const result = yield* Fiber.join(fiber)\n      strictEqual(result, undefined)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Layer.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport {\n  Chunk,\n  Context,\n  Deferred,\n  Duration,\n  Effect,\n  Exit,\n  Fiber,\n  FiberRef,\n  identity,\n  Layer,\n  pipe,\n  Ref,\n  Schedule,\n  Scope,\n  Stream\n} from \"effect\"\n\nconst acquire1 = \"Acquiring Module 1\"\nconst acquire2 = \"Acquiring Module 2\"\nconst acquire3 = \"Acquiring Module 3\"\nconst release1 = \"Releasing Module 1\"\nconst release2 = \"Releasing Module 2\"\nconst release3 = \"Releasing Module 3\"\n\ndescribe(\"Layer\", () => {\n  it.effect(\"layers can be acquired in parallel\", () =>\n    Effect.gen(function*() {\n      const BoolTag = Context.GenericTag<boolean>(\"boolean\")\n      const deferred = yield* Deferred.make<void>()\n      const layer1 = Layer.effectContext<never, never, never>(Effect.never)\n      const layer2 = Layer.scopedContext(\n        Effect.acquireRelease(\n          Deferred.succeed(deferred, void 0).pipe(\n            Effect.map((bool) => Context.make(BoolTag, bool))\n          ),\n          () => Effect.void\n        )\n      )\n      const env = layer1.pipe(Layer.merge(layer2), Layer.build)\n      const fiber = yield* pipe(Effect.scoped(env), Effect.forkDaemon)\n      yield* Deferred.await(deferred)\n      const result = yield* pipe(Fiber.interrupt(fiber), Effect.asVoid)\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"preserves identity of acquired resources\", () =>\n    Effect.gen(function*() {\n      const ChunkTag = Context.GenericTag<Ref.Ref<Chunk.Chunk<string>>>(\"Ref.Ref<Chunk.Chunk<string>>\")\n      const testRef = yield* Ref.make<Chunk.Chunk<string>>(Chunk.empty())\n      const layer = Layer.scoped(\n        ChunkTag,\n        Effect.acquireRelease(\n          Ref.make<Chunk.Chunk<string>>(Chunk.empty()),\n          (ref) =>\n            Ref.get(ref).pipe(\n              Effect.flatMap((chunk) => Ref.set(testRef, chunk))\n            )\n        ).pipe(\n          Effect.tap(() => Effect.void)\n        )\n      )\n      yield* pipe(\n        Layer.build(layer),\n        Effect.flatMap((context) =>\n          Ref.update(\n            context.pipe(Context.get(ChunkTag)),\n            Chunk.append(\"test\")\n          )\n        ),\n        Effect.scoped\n      )\n      const result = yield* Ref.get(testRef)\n      deepStrictEqual(Array.from(result), [\"test\"])\n    }))\n  it.effect(\"sharing with merge\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer = makeLayer1(ref)\n      const env = layer.pipe(Layer.merge(layer), Layer.build)\n      yield* Effect.scoped(env)\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Array.from(result), [acquire1, release1])\n    }))\n  it.scoped(\"sharing itself with merge\", () =>\n    Effect.gen(function*() {\n      const service1 = new Service1()\n      const layer = Layer.succeed(Service1Tag, service1)\n      const env = layer.pipe(Layer.merge(layer), Layer.merge(layer), Layer.build)\n      const result = yield* env.pipe(\n        Effect.flatMap((context) => Effect.try(() => context.pipe(Context.get(Service1Tag))))\n      )\n      strictEqual(result, service1)\n    }))\n  it.effect(\"finalizers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const env = layer1.pipe(Layer.merge(layer2), Layer.build)\n      yield* Effect.scoped(env)\n      const result = yield* Ref.get(ref)\n      assertTrue(Array.from(result).slice(0, 2).find((s) => s === acquire1) !== undefined)\n      assertTrue(Array.from(result).slice(0, 2).find((s) => s === acquire2) !== undefined)\n      assertTrue(Array.from(result).slice(2, 4).find((s) => s === release1) !== undefined)\n      assertTrue(Array.from(result).slice(2, 4).find((s) => s === release2) !== undefined)\n    }))\n  it.effect(\"caching values in dependencies\", () =>\n    Effect.gen(function*() {\n      class Config {\n        constructor(readonly value: number) {}\n      }\n      const ConfigTag = Context.GenericTag<Config>(\"Config\")\n      class A {\n        constructor(readonly value: number) {}\n      }\n      const ATag = Context.GenericTag<A>(\"A\")\n      const aLayer = Layer.function(ConfigTag, ATag, (config) => new A(config.value))\n      class B {\n        constructor(readonly value: number) {}\n      }\n      const BTag = Context.GenericTag<B>(\"B\")\n      const bLayer = Layer.function(ATag, BTag, (_: A) => new B(_.value))\n      class C {\n        constructor(readonly value: number) {}\n      }\n      const CTag = Context.GenericTag<C>(\"C\")\n      const cLayer = Layer.function(ATag, CTag, (_: A) => new C(_.value))\n      const fedB = bLayer.pipe(\n        Layer.provideMerge(aLayer),\n        Layer.provideMerge(Layer.succeed(ConfigTag, new Config(1)))\n      )\n      const fedC = cLayer.pipe(\n        Layer.provideMerge(aLayer),\n        Layer.provide(Layer.succeed(ConfigTag, new Config(2)))\n      )\n      const result = yield* pipe(\n        fedB,\n        Layer.merge(fedC),\n        Layer.build,\n        Effect.map((context) =>\n          [\n            context.pipe(Context.get(BTag)),\n            context.pipe(Context.get(CTag))\n          ] as const\n        ),\n        Effect.scoped\n      )\n      strictEqual(result[0].value, 1)\n      strictEqual(result[1].value, 1)\n    }))\n  it.effect(\"orElse - uses an alternative layer\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const env = Layer.fail(\"failed!\").pipe(Layer.provideMerge(layer1), Layer.orElse(() => layer2), Layer.build)\n      yield* Effect.scoped(env)\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Array.from(result), [acquire1, release1, acquire2, release2])\n    }))\n  it.effect(\"handles errors gracefully\", () =>\n    Effect.gen(function*() {\n      interface Bar {\n        readonly bar: string\n      }\n      const BarTag = Context.GenericTag<Bar>(\"Bar\")\n      interface Baz {\n        readonly baz: string\n      }\n      const BazTag = Context.GenericTag<Baz>(\"Baz\")\n      const ScopedTag = Context.GenericTag<void>(\"void\")\n      const sleep = Effect.sleep(Duration.millis(100))\n      const layer1 = Layer.fail(\"foo\")\n      const layer2 = Layer.succeed(BarTag, { bar: \"bar\" })\n      const layer3 = Layer.succeed(BazTag, { baz: \"baz\" })\n      const layer4 = Layer.scoped(\n        ScopedTag,\n        Effect.scoped(Effect.acquireRelease(sleep, () => sleep))\n      )\n\n      const layer = Layer.merge(\n        layer1,\n        layer4.pipe(\n          Layer.provide(Layer.merge(layer2, layer3))\n        )\n      )\n      const result = yield* pipe(Effect.void, Effect.provide(layer), Effect.exit)\n      assertTrue(Exit.isFailure(result))\n    }))\n  it.effect(\"fresh with merge\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer = makeLayer1(ref)\n      const env = layer.pipe(Layer.merge(Layer.fresh(layer)), Layer.build)\n      yield* Effect.scoped(env)\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Array.from(result), [acquire1, acquire1, release1, release1])\n    }))\n  it.effect(\"fresh with to provideTo\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer = makeLayer1(ref)\n      const env = Layer.fresh(layer).pipe(\n        Layer.provide(layer),\n        Layer.build\n      )\n      yield* Effect.scoped(env)\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Array.from(result), [acquire1, acquire1, release1, release1])\n    }))\n  it.effect(\"with multiple layers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer = makeLayer1(ref)\n      const env = layer.pipe(\n        Layer.merge(layer),\n        Layer.merge(layer.pipe(Layer.merge(layer), Layer.fresh)),\n        Layer.build\n      )\n      yield* Effect.scoped(env)\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Array.from(result), [acquire1, acquire1, release1, release1])\n    }))\n  it.effect(\"with identical fresh layers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const layer3 = makeLayer3(ref)\n      const env = layer2.pipe(\n        Layer.merge(\n          layer3.pipe(\n            Layer.provide(layer1),\n            Layer.fresh\n          )\n        ),\n        Layer.provide(Layer.fresh(layer1)),\n        Layer.build\n      )\n      yield* Effect.scoped(env)\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Array.from(result), [\n        acquire1,\n        acquire2,\n        acquire1,\n        acquire3,\n        release3,\n        release1,\n        release2,\n        release1\n      ])\n    }))\n  it.effect(\"interruption with merge\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const env = layer1.pipe(Layer.merge(layer2), Layer.build)\n      const fiber = yield* pipe(Effect.scoped(env), Effect.fork)\n      yield* Fiber.interrupt(fiber)\n      const result = yield* pipe(Ref.get(ref), Effect.map((chunk) => Array.from(chunk)))\n      if (result.find((s) => s === acquire1) !== undefined) {\n        assertTrue(result.some((s) => s === release1))\n      }\n      if (result.find((s) => s === acquire2) !== undefined) {\n        assertTrue(result.some((s) => s === release2))\n      }\n    }))\n  it.effect(\"interruption with provideTo\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const env = layer2.pipe(Layer.provide(layer1), Layer.build)\n      const fiber = yield* pipe(Effect.scoped(env), Effect.fork)\n      yield* Fiber.interrupt(fiber)\n      const result = yield* pipe(Ref.get(ref), Effect.map((chunk) => Array.from(chunk)))\n      if (result.find((s) => s === acquire1) !== undefined) {\n        assertTrue(result.some((s) => s === release1))\n      }\n      if (result.find((s) => s === acquire2) !== undefined) {\n        assertTrue(result.some((s) => s === release2))\n      }\n    }))\n  it.effect(\"interruption with multiple layers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const layer3 = makeLayer3(ref)\n      const env = layer3.pipe(\n        Layer.provide(layer1),\n        Layer.merge(layer2),\n        Layer.provide(layer1),\n        Layer.build\n      )\n      const fiber = yield* pipe(Effect.scoped(env), Effect.fork)\n      yield* Fiber.interrupt(fiber)\n      const result = yield* pipe(Ref.get(ref), Effect.map((chunk) => Array.from(chunk)))\n      if (result.find((s) => s === acquire1) !== undefined) {\n        assertTrue(result.some((s) => s === release1))\n      }\n      if (result.find((s) => s === acquire2) !== undefined) {\n        assertTrue(result.some((s) => s === release2))\n      }\n      if (result.find((s) => s === acquire3) !== undefined) {\n        assertTrue(result.some((s) => s === release3))\n      }\n    }))\n  it.effect(\"can map a layer to an unrelated type\", () =>\n    Effect.gen(function*() {\n      interface ServiceA {\n        readonly name: string\n        readonly value: number\n      }\n      const ServiceATag = Context.GenericTag<ServiceA>(\"ServiceA\")\n      interface ServiceB {\n        readonly name: string\n      }\n      const ServiceBTag = Context.GenericTag<ServiceB>(\"ServiceB\")\n      const StringTag = Context.GenericTag<string>(\"string\")\n      const layer1 = Layer.succeed(ServiceATag, { name: \"name\", value: 1 })\n      const layer2 = Layer.function(StringTag, ServiceBTag, (name) => ({ name }))\n      const live = layer2.pipe(\n        Layer.provide(\n          Layer.map(layer1, (context) => Context.make(StringTag, context.pipe(Context.get(ServiceATag)).name))\n        )\n      )\n      const result = yield* pipe(ServiceBTag, Effect.provide(live))\n      strictEqual(result.name, \"name\")\n    }))\n  it.effect(\"memoizes acquisition of resources\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const memoized = Layer.memoize(makeLayer1(ref))\n      yield* pipe(\n        memoized,\n        Effect.flatMap((layer) =>\n          Effect.context<Service1>().pipe(\n            Effect.provide(layer),\n            Effect.flatMap(() => Effect.context<Service1>().pipe(Effect.provide(layer)))\n          )\n        ),\n        Effect.scoped\n      )\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Array.from(result), [acquire1, release1])\n    }))\n  it.scoped(\"fiberRef changes are memoized\", () =>\n    Effect.gen(function*() {\n      const fiberRef = yield* FiberRef.make<boolean>(false)\n      const tag = Context.GenericTag<boolean>(\"boolean\")\n      const layer1 = Layer.scopedDiscard(Effect.locallyScoped(fiberRef, true))\n      const layer2 = Layer.effect(tag, FiberRef.get(fiberRef))\n      const layer3 = layer2.pipe(\n        Layer.provide(layer1),\n        Layer.merge(layer1)\n      )\n      const result = yield* Layer.build(layer3)\n      assertTrue(result.pipe(Context.unsafeGet(tag)))\n    }))\n  it.effect(\"provides a partial environment to an effect\", () =>\n    Effect.gen(function*() {\n      const NumberTag = Context.GenericTag<number>(\"number\")\n      const StringTag = Context.GenericTag<string>(\"string\")\n      const needsNumberAndString = Effect.all([NumberTag, StringTag])\n      const providesNumber = Layer.succeed(NumberTag, 10)\n      const providesString = Layer.succeed(StringTag, \"hi\")\n      const needsString = needsNumberAndString.pipe(Effect.provide(providesNumber))\n      const result = yield* pipe(needsString, Effect.provide(providesString))\n      strictEqual(result[0], 10)\n      strictEqual(result[1], \"hi\")\n    }))\n  it.effect(\"to provides a partial environment to another layer\", () =>\n    Effect.gen(function*() {\n      const StringTag = Context.GenericTag<string>(\"string\")\n      const NumberRefTag = Context.GenericTag<Ref.Ref<number>>(\"Ref.Ref<number>\")\n      interface FooService {\n        readonly ref: Ref.Ref<number>\n        readonly string: string\n        readonly get: Effect.Effect<\n          readonly [\n            number,\n            string\n          ]\n        >\n      }\n      const FooTag = Context.GenericTag<FooService>(\"FooService\")\n      const fooBuilder = Layer.context<string | Ref.Ref<number>>().pipe(\n        Layer.map((context) => {\n          const s = Context.get(context, StringTag)\n          const ref = Context.get(context, NumberRefTag)\n          return Context.make(FooTag, {\n            ref,\n            string: s,\n            get: Ref.get(ref).pipe(Effect.map((i) => [i, s] as const))\n          })\n        })\n      )\n      const provideNumberRef = Layer.effect(NumberRefTag)(Ref.make(10))\n      const provideString = Layer.succeed(StringTag, \"hi\")\n      const needsString = fooBuilder.pipe(Layer.provide(provideNumberRef))\n      const layer = needsString.pipe(Layer.provide(provideString))\n      const result = yield* pipe(Effect.flatMap(FooTag, (_) => _.get), Effect.provide(layer))\n      strictEqual(result[0], 10)\n      strictEqual(result[1], \"hi\")\n    }))\n  it.effect(\"andTo provides a partial environment to another layer\", () =>\n    Effect.gen(function*() {\n      const StringTag = Context.GenericTag<string>(\"string\")\n      const NumberRefTag = Context.GenericTag<Ref.Ref<number>>(\"Ref.Ref<number>\")\n      interface FooService {\n        readonly ref: Ref.Ref<number>\n        readonly string: string\n        readonly get: Effect.Effect<\n          readonly [\n            number,\n            string\n          ]\n        >\n      }\n      const FooTag = Context.GenericTag<FooService>(\"FooService\")\n      const fooBuilder = Layer.context<string | Ref.Ref<number>>().pipe(\n        Layer.map((context) => {\n          const s = Context.get(context, StringTag)\n          const ref = Context.get(context, NumberRefTag)\n          return Context.make(FooTag, {\n            ref,\n            string: s,\n            get: Ref.get(ref).pipe(Effect.map((i) => [i, s] as const))\n          })\n        })\n      )\n      const provideNumberRef = Layer.effect(NumberRefTag, Ref.make(10))\n      const provideString = Layer.succeed(StringTag, \"hi\")\n      const needsString = fooBuilder.pipe(Layer.provideMerge(provideNumberRef))\n      const layer = needsString.pipe(Layer.provideMerge(provideString))\n      const result = yield* pipe(\n        Effect.flatMap(FooTag, (foo) => foo.get),\n        Effect.flatMap(([i1, s]) =>\n          NumberRefTag.pipe(Effect.flatMap(Ref.get), Effect.map((i2) => [i1, i2, s] as const))\n        ),\n        Effect.provide(layer)\n      )\n      strictEqual(result[0], 10)\n      strictEqual(result[1], 10)\n      strictEqual(result[2], \"hi\")\n    }))\n  it.effect(\"passthrough passes the inputs through to the next layer\", () =>\n    Effect.gen(function*() {\n      interface NumberService {\n        readonly value: number\n      }\n      const NumberTag = Context.GenericTag<NumberService>(\"NumberService\")\n      interface ToStringService {\n        readonly value: string\n      }\n      const ToStringTag = Context.GenericTag<ToStringService>(\"ToStringService\")\n      const layer = Layer.function(NumberTag, ToStringTag, (numberService) => ({\n        value: numberService.value.toString()\n      }))\n      const live = Layer.passthrough(layer).pipe(Layer.provide(Layer.succeed(NumberTag, { value: 1 })))\n      const { i, s } = yield* pipe(\n        Effect.all({\n          i: NumberTag,\n          s: ToStringTag\n        }),\n        Effect.provide(live)\n      )\n      strictEqual(i.value, 1)\n      strictEqual(s.value, \"1\")\n    }))\n  it.effect(\"project\", () =>\n    Effect.gen(function*() {\n      interface PersonService {\n        readonly name: string\n        readonly age: number\n      }\n      interface AgeService extends Pick<PersonService, \"age\"> {\n      }\n      const PersonTag = Context.GenericTag<PersonService>(\"PersonService\")\n      const AgeTag = Context.GenericTag<AgeService>(\"AgeService\")\n      const personLayer = Layer.succeed(PersonTag, { name: \"User\", age: 42 })\n      const ageLayer = personLayer.pipe(Layer.project(PersonTag, AgeTag, (_) => ({ age: _.age })))\n      const { age } = yield* pipe(AgeTag, Effect.provide(ageLayer))\n      strictEqual(age, 42)\n    }))\n  it.effect(\"sharing with provideTo\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer = makeLayer1(ref)\n      const env = layer.pipe(Layer.provide(layer), Layer.build)\n      yield* Effect.scoped(env)\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Array.from(result), [acquire1, release1])\n    }))\n  it.effect(\"sharing with multiple layers with provideTo\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const layer3 = makeLayer3(ref)\n      const env = layer3.pipe(\n        Layer.provide(layer1),\n        Layer.merge(layer2.pipe(Layer.provide(layer1))),\n        Layer.build\n      )\n      yield* Effect.scoped(env)\n      const result = yield* pipe(Ref.get(ref), Effect.map((chunk) => Array.from(chunk)))\n      strictEqual(result[0], acquire1)\n      assertTrue(result.slice(1, 3).some((s) => s === acquire2))\n      assertTrue(result.slice(1, 3).some((s) => s === acquire3))\n      assertTrue(result.slice(3, 5).some((s) => s === release3))\n      assertTrue(result.slice(3, 5).some((s) => s === release2))\n      strictEqual(result[5], release1)\n    }))\n  it.effect(\"finalizers with provideTo\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const env = layer2.pipe(Layer.provide(layer1), Layer.build)\n      yield* Effect.scoped(env)\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Array.from(result), [acquire1, acquire2, release2, release1])\n    }))\n  it.effect(\"finalizers with multiple layers with provideTo\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const layer3 = makeLayer3(ref)\n      const env = layer3.pipe(Layer.provide(layer2), Layer.provide(layer1), Layer.build)\n      yield* Effect.scoped(env)\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Array.from(result), [acquire1, acquire2, acquire3, release3, release2, release1])\n    }))\n  it.effect(\"retry\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(0)\n      const effect = ref.pipe(Ref.update((n) => n + 1), Effect.zipRight(Effect.fail(\"fail\")))\n      const layer = Layer.effectContext(effect).pipe(Layer.retry(Schedule.recurs(3)))\n      yield* Effect.ignore(Effect.scoped(Layer.build(layer)))\n      const result = yield* Ref.get(ref)\n      strictEqual(result, 4)\n    }))\n  it.effect(\"map does not interfere with sharing\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const layer3 = makeLayer3(ref)\n      const env = layer3.pipe(\n        Layer.provide(layer1),\n        Layer.provide(layer2),\n        Layer.provide(Layer.map(layer1, identity)),\n        Layer.build\n      )\n      yield* Effect.scoped(env)\n      const result = yield* pipe(Ref.get(ref), Effect.map((chunk) => Array.from(chunk)))\n      strictEqual(result[0], acquire1)\n      assertTrue(result.slice(1, 3).some((s) => s === acquire2))\n      assertTrue(result.slice(1, 3).some((s) => s === acquire3))\n      assertTrue(result.slice(3, 5).some((s) => s === release3))\n      assertTrue(result.slice(3, 5).some((s) => s === release2))\n      strictEqual(result[5], release1)\n    }))\n  it.effect(\"mapError does not interfere with sharing\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const layer3 = makeLayer3(ref)\n      const env = layer3.pipe(\n        Layer.provide(layer1),\n        Layer.provide(layer2),\n        Layer.provide(Layer.mapError(layer1, identity)),\n        Layer.build\n      )\n      yield* Effect.scoped(env)\n      const result = yield* pipe(Ref.get(ref), Effect.map((chunk) => Array.from(chunk)))\n      strictEqual(result[0], acquire1)\n      assertTrue(result.slice(1, 3).some((s) => s === acquire2))\n      assertTrue(result.slice(1, 3).some((s) => s === acquire3))\n      assertTrue(result.slice(3, 5).some((s) => s === release3))\n      assertTrue(result.slice(3, 5).some((s) => s === release2))\n      strictEqual(result[5], release1)\n    }))\n  it.effect(\"orDie does not interfere with sharing\", () =>\n    Effect.gen(function*() {\n      const ref = yield* makeRef()\n      const layer1 = makeLayer1(ref)\n      const layer2 = makeLayer2(ref)\n      const layer3 = makeLayer3(ref)\n      const env = layer3.pipe(\n        Layer.provide(layer1),\n        Layer.provide(layer2),\n        Layer.provide(Layer.orDie(layer1)),\n        Layer.build\n      )\n      yield* Effect.scoped(env)\n      const result = yield* pipe(Ref.get(ref), Effect.map((chunk) => Array.from(chunk)))\n      strictEqual(result[0], acquire1)\n      assertTrue(result.slice(1, 3).some((s) => s === acquire2))\n      assertTrue(result.slice(1, 3).some((s) => s === acquire3))\n      assertTrue(result.slice(3, 5).some((s) => s === release3))\n      assertTrue(result.slice(3, 5).some((s) => s === release2))\n      strictEqual(result[5], release1)\n    }))\n  it.effect(\"tap peeks at an acquired resource\", () =>\n    Effect.gen(function*() {\n      interface BarService {\n        readonly bar: string\n      }\n      const BarTag = Context.GenericTag<BarService>(\"BarService\")\n      const ref: Ref.Ref<string> = yield* Ref.make(\"foo\")\n      const layer = Layer.succeed(BarTag, { bar: \"bar\" }).pipe(\n        Layer.tap((context) => Ref.set(ref, context.pipe(Context.get(BarTag)).bar))\n      )\n      yield* Effect.scoped(Layer.build(layer))\n      const result = yield* Ref.get(ref)\n      strictEqual(result, \"bar\")\n    }))\n  it.effect(\"locally\", () =>\n    Effect.gen(function*() {\n      interface BarService {\n        readonly bar: string\n      }\n      const BarTag = Context.GenericTag<BarService>(\"BarService\")\n      const fiberRef = FiberRef.unsafeMake(0)\n      const layer = Layer.locally(fiberRef, 100)(\n        Layer.effect(\n          BarTag,\n          Effect.map(\n            FiberRef.get(fiberRef),\n            (n): BarService => ({ bar: `bar: ${n}` })\n          )\n        )\n      )\n      const env = yield* Effect.scoped(Layer.build(layer))\n      const result = Context.get(env, BarTag)\n      strictEqual(result.bar, \"bar: 100\")\n    }))\n  it.effect(\"locallyWith\", () =>\n    Effect.gen(function*() {\n      interface BarService {\n        readonly bar: string\n      }\n      const BarTag = Context.GenericTag<BarService>(\"BarService\")\n      const fiberRef = FiberRef.unsafeMake(0)\n      const layer = Layer.locallyWith(fiberRef, (n) => n + 1)(\n        Layer.effect(\n          BarTag,\n          Effect.map(\n            FiberRef.get(fiberRef),\n            (n): BarService => ({ bar: `bar: ${n}` })\n          )\n        )\n      )\n      const env = yield* Effect.scoped(Layer.build(layer))\n      const result = Context.get(env, BarTag)\n      strictEqual(result.bar, \"bar: 1\")\n    }))\n\n  it.effect(\"Updates service via updateService\", () =>\n    Effect.gen(function*() {\n      const Foo = Context.GenericTag<\"Foo\", string>(\"Foo\")\n      const FooDefault = Layer.succeed(Foo, \"Foo\")\n      const Bar = Context.GenericTag<\"Bar\", string>(\"Bar\")\n      const BarDefault = Layer.effect(Bar, Foo).pipe(\n        Layer.updateService(Foo, (x) => `Bar: ${x}`),\n        Layer.provide(FooDefault)\n      )\n      const result = yield* Bar.pipe(Effect.provide(BarDefault))\n      deepStrictEqual(result, \"Bar: Foo\")\n    }))\n\n  it.effect(\"allows passing partial service\", () =>\n    Effect.gen(function*() {\n      class Service1 extends Effect.Service<Service1>()(\"Service1\", {\n        succeed: {\n          one: Effect.succeed(123),\n          two: () => Effect.succeed(2),\n          stream: Stream.succeed(3)\n        }\n      }) {}\n\n      yield* Effect.gen(function*() {\n        const service = yield* Service1\n\n        deepStrictEqual(yield* service.one, 123)\n\n        yield* service.two().pipe(\n          Effect.catchAllDefect(Effect.fail),\n          Effect.flip\n        )\n        yield* service.stream.pipe(\n          Stream.runDrain,\n          Effect.catchAllDefect(Effect.fail),\n          Effect.flip\n        )\n      }).pipe(\n        Effect.provide(Layer.mock(Service1, {\n          _tag: \"Service1\",\n          one: Effect.succeed(123)\n        }))\n      )\n    }))\n\n  describe(\"MemoMap\", () => {\n    it.effect(\"memoizes layer across builds\", () =>\n      Effect.gen(function*() {\n        const ref = yield* makeRef()\n        const layer1 = makeLayer1(ref)\n        const layer2 = makeLayer2(ref).pipe(\n          Layer.provide(layer1)\n        )\n        const memoMap = yield* Layer.makeMemoMap\n        const scope1 = yield* Scope.make()\n        const scope2 = yield* Scope.make()\n\n        yield* Layer.buildWithMemoMap(layer1, memoMap, scope1)\n        yield* Layer.buildWithMemoMap(layer2, memoMap, scope2)\n        yield* Scope.close(scope2, Exit.void)\n        yield* Layer.buildWithMemoMap(layer2, memoMap, scope1)\n        yield* Scope.close(scope1, Exit.void)\n\n        const result = yield* Ref.get(ref)\n        deepStrictEqual(Array.from(result), [acquire1, acquire2, release2, acquire2, release2, release1])\n      }))\n\n    it.effect(\"layers are not released early\", () =>\n      Effect.gen(function*() {\n        const ref = yield* makeRef()\n        const layer1 = makeLayer1(ref)\n        const layer2 = makeLayer2(ref).pipe(\n          Layer.provide(layer1)\n        )\n        const memoMap = yield* Layer.makeMemoMap\n        const scope1 = yield* Scope.make()\n        const scope2 = yield* Scope.make()\n\n        yield* Layer.buildWithMemoMap(layer1, memoMap, scope1)\n        yield* Layer.buildWithMemoMap(layer2, memoMap, scope2)\n        yield* Scope.close(scope1, Exit.void)\n        yield* Scope.close(scope2, Exit.void)\n\n        const result = yield* Ref.get(ref)\n        deepStrictEqual(Array.from(result), [acquire1, acquire2, release2, release1])\n      }))\n  })\n})\nexport const makeRef = (): Effect.Effect<Ref.Ref<Chunk.Chunk<string>>> => {\n  return Ref.make(Chunk.empty())\n}\nexport class Service1 {\n  one(): Effect.Effect<number> {\n    return Effect.succeed(1)\n  }\n}\nexport const Service1Tag = Context.GenericTag<Service1>(\"Service1\")\nexport const makeLayer1 = (ref: Ref.Ref<Chunk.Chunk<string>>): Layer.Layer<Service1> => {\n  return Layer.scoped(\n    Service1Tag,\n    Effect.acquireRelease(\n      ref.pipe(Ref.update(Chunk.append(acquire1)), Effect.as(new Service1())),\n      () => Ref.update(ref, Chunk.append(release1))\n    )\n  )\n}\nexport class Service2 {\n  two(): Effect.Effect<number> {\n    return Effect.succeed(2)\n  }\n}\nexport const Service2Tag = Context.GenericTag<Service2>(\"Service2\")\nexport const makeLayer2 = (ref: Ref.Ref<Chunk.Chunk<string>>): Layer.Layer<Service2> => {\n  return Layer.scoped(\n    Service2Tag,\n    Effect.acquireRelease(\n      ref.pipe(Ref.update(Chunk.append(acquire2)), Effect.as(new Service2())),\n      () => Ref.update(ref, Chunk.append(release2))\n    )\n  )\n}\nexport class Service3 {\n  three(): Effect.Effect<number> {\n    return Effect.succeed(3)\n  }\n}\nexport const Service3Tag = Context.GenericTag<Service3>(\"Service3\")\nexport const makeLayer3 = (ref: Ref.Ref<Chunk.Chunk<string>>): Layer.Layer<Service3> => {\n  return Layer.scoped(\n    Service3Tag,\n    Effect.acquireRelease(\n      ref.pipe(Ref.update(Chunk.append(acquire3)), Effect.as(new Service3())),\n      () => Ref.update(ref, Chunk.append(release3))\n    )\n  )\n}\n"
  },
  {
    "path": "packages/effect/test/List.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertNone,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { Array, Chunk, Duration, Either, List, Option } from \"effect\"\nimport { equals, symbol } from \"effect/Equal\"\n\nconst testStructuralSharing = <A>(a: List.List<A>, b: List.List<A>, n = 0): number | undefined => {\n  if (a === b) {\n    return n\n  }\n  if (List.isCons(a)) {\n    return testStructuralSharing(a.tail, b, n + 1)\n  }\n}\n\ndescribe(\"List\", () => {\n  it(\"is an iterable\", () => {\n    deepStrictEqual(Array.fromIterable(List.make(0, 1, 2, 3)), [0, 1, 2, 3])\n  })\n\n  it(\"isList\", () => {\n    assertTrue(List.isList(List.empty()))\n    assertTrue(List.isList(List.make(1)))\n    assertFalse(List.isList(null))\n    assertFalse(List.isList({}))\n  })\n\n  it(\"append\", () => {\n    deepStrictEqual(List.append(List.make(1, 2), 3), List.make(1, 2, 3))\n  })\n\n  it(\"appendAll\", () => {\n    deepStrictEqual(List.appendAll(List.make(1, 2), List.make(3, 4)), List.make(1, 2, 3, 4))\n  })\n\n  it(\"drop\", () => {\n    deepStrictEqual(List.drop(List.make(1, 2, 3, 4), 2), List.make(3, 4))\n    // out of bound\n    deepStrictEqual(List.drop(List.make(1, 2), -2), List.make(1, 2))\n    deepStrictEqual(List.drop(List.make(1, 2), 3), List.empty())\n  })\n\n  it(\"every\", () => {\n    assertTrue(List.every(List.empty(), (n) => n > 2))\n    assertFalse(List.every(List.make(1, 2), (n) => n > 2))\n    assertFalse(List.every(List.make(2, 3), (n) => n > 2))\n    assertTrue(List.every(List.make(3, 4), (n) => n > 2))\n  })\n\n  it(\"findFirst\", () => {\n    const item = (a: string, b: string) => ({ a, b })\n    const list = List.make(item(\"a1\", \"b1\"), item(\"a2\", \"b2\"), item(\"a3\", \"b2\"))\n    assertSome(List.findFirst(list, ({ b }) => b === \"b2\"), item(\"a2\", \"b2\"))\n    assertNone(List.findFirst(list, ({ b }) => b === \"-\"))\n  })\n\n  it(\"flatMap\", () => {\n    deepStrictEqual(List.flatMap(List.empty(), (n) => List.make(n - 1, n + 1)), List.empty())\n    deepStrictEqual(\n      List.flatMap(List.make(1, 2, 3, 4), (n) => List.make(n - 1, n + 1)),\n      List.make(0, 2, 1, 3, 2, 4, 3, 5)\n    )\n    deepStrictEqual(List.flatMap(List.make(1, 2, 3, 4), () => List.empty()), List.empty())\n  })\n\n  it(\"forEach\", () => {\n    const as: Array<number> = []\n    List.forEach(List.make(1, 2, 3, 4), (n) => as.push(n))\n    deepStrictEqual(as, [1, 2, 3, 4])\n  })\n\n  it(\"head\", () => {\n    assertNone(List.head(List.empty()))\n    assertSome(List.head(List.make(1, 2, 3)), 1)\n  })\n\n  it(\"isCons\", () => {\n    assertFalse(List.isCons(List.empty()))\n    assertTrue(List.isCons(List.make(1)))\n  })\n\n  it(\"isNil\", () => {\n    assertTrue(List.isNil(List.nil()))\n    assertFalse(List.isNil(List.make(1)))\n  })\n\n  it(\"map\", () => {\n    deepStrictEqual(List.map(List.empty(), (n) => n + 1), List.empty())\n    deepStrictEqual(List.map(List.make(1, 2, 3, 4), (n) => n + 1), List.make(2, 3, 4, 5))\n  })\n\n  it(\"mapWithIndex\", () => {\n    deepStrictEqual(List.map(List.empty(), (n, i) => [i, n + 1]), List.empty())\n    deepStrictEqual(List.map(List.make(1, 2, 3, 4), (n, i) => [i, n ** 2]), List.make([0, 1], [1, 4], [2, 9], [3, 16]))\n  })\n\n  it(\"partition\", () => {\n    deepStrictEqual(List.partition(List.make(1, 2, 3, 4), (n) => n > 2), [\n      List.make(1, 2),\n      List.make(3, 4)\n    ])\n  })\n\n  it(\"partitionMap\", () => {\n    deepStrictEqual(\n      List.partitionMap(List.make(1, 2, 3, 4), (n) =>\n        n > 2 ?\n          Either.right(n) :\n          Either.left(n)),\n      [List.make(1, 2), List.make(3, 4)]\n    )\n  })\n\n  it(\"prependAll\", () => {\n    deepStrictEqual(List.prependAll(List.empty(), List.make(1, 2)), List.make(1, 2))\n    deepStrictEqual(List.prependAll(List.make(1, 2), List.empty()), List.make(1, 2))\n    deepStrictEqual(List.prependAll(List.make(3), List.make(1, 2)), List.make(1, 2, 3))\n  })\n\n  it(\"prependAllReversed\", () => {\n    deepStrictEqual(List.prependAllReversed(List.empty(), List.make(1, 2)), List.make(2, 1))\n    deepStrictEqual(List.prependAllReversed(List.make(1, 2), List.empty()), List.make(1, 2))\n    deepStrictEqual(List.prependAllReversed(List.make(3), List.make(1, 2)), List.make(2, 1, 3))\n  })\n\n  it(\"reduce\", () => {\n    deepStrictEqual(List.reduce(List.empty(), \"-\", (b, a) => b + a), \"-\")\n    deepStrictEqual(List.reduce(List.make(\"a\", \"b\", \"c\"), \"-\", (b, a) => b + a), \"-abc\")\n  })\n\n  it(\"reduceRight\", () => {\n    const f = (b: string, a: string) => b + a\n    deepStrictEqual(List.reduceRight(List.empty(), \"\", f), \"\")\n    deepStrictEqual(List.reduceRight(List.make(\"a\", \"b\", \"c\"), \"\", f), \"cba\")\n  })\n\n  it(\"reverse\", () => {\n    deepStrictEqual(List.reverse(List.empty()), List.empty())\n    deepStrictEqual(List.reverse(List.make(1, 2, 3)), List.make(3, 2, 1))\n  })\n\n  it(\"toChunk\", () => {\n    deepStrictEqual(List.toChunk(List.empty()), Chunk.empty())\n    deepStrictEqual(List.toChunk(List.make(1, 2, 3)), Chunk.make(1, 2, 3))\n  })\n\n  it(\"toChunk\", () => {\n    throws(() => List.unsafeHead(List.empty()), new Error(\"Expected List to be non-empty\"))\n    deepStrictEqual(List.unsafeHead(List.make(1, 2, 3)), 1)\n  })\n\n  it(\"some\", () => {\n    assertFalse(List.some(List.empty(), (n) => n > 2))\n    assertFalse(List.some(List.make(1, 2), (n) => n > 2))\n    assertTrue(List.some(List.make(2, 3), (n) => n > 2))\n    assertTrue(List.some(List.make(3, 4), (n) => n > 2))\n  })\n\n  it(\"splitAt\", () => {\n    deepStrictEqual(List.splitAt(List.make(1, 2, 3, 4), 2), [List.make(1, 2), List.make(3, 4)])\n  })\n\n  it(\"take\", () => {\n    deepStrictEqual(List.take(List.make(1, 2, 3, 4), 2), List.make(1, 2))\n    deepStrictEqual(List.take(List.make(1, 2, 3, 4), 0), List.nil())\n    deepStrictEqual(List.take(List.make(1, 2, 3, 4), -10), List.nil())\n    deepStrictEqual(List.take(List.make(1, 2, 3, 4), 10), List.make(1, 2, 3, 4))\n  })\n\n  it(\"tail\", () => {\n    assertNone(List.tail(List.empty()))\n    assertSome(List.tail(List.make(1, 2, 3)), List.make(2, 3))\n  })\n\n  it(\"unsafeLast\", () => {\n    throws(() => List.unsafeLast(List.empty()), new Error(\"Expected List to be non-empty\"))\n    strictEqual(List.unsafeLast(List.make(1, 2, 3, 4)), 4)\n  })\n\n  it(\"unsafeTail\", () => {\n    throws(() => List.unsafeTail(List.empty()), new Error(\"Expected List to be non-empty\"))\n    deepStrictEqual(List.unsafeTail(List.make(1, 2, 3, 4)), List.make(2, 3, 4))\n  })\n\n  it(\"pipe()\", () => {\n    deepStrictEqual(List.empty<string>().pipe(List.prepend(\"a\")), List.make(\"a\"))\n  })\n\n  it(\"toString\", () => {\n    strictEqual(\n      String(List.empty()),\n      `{\n  \"_id\": \"List\",\n  \"_tag\": \"Nil\"\n}`\n    )\n    strictEqual(\n      String(List.make(0, 1, 2)),\n      `{\n  \"_id\": \"List\",\n  \"_tag\": \"Cons\",\n  \"values\": [\n    0,\n    1,\n    2\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    deepStrictEqual(List.empty().toJSON(), { _id: \"List\", _tag: \"Nil\" })\n    deepStrictEqual(List.make(0, 1, 2).toJSON(), { _id: \"List\", _tag: \"Cons\", values: [0, 1, 2] })\n    deepStrictEqual(List.make(0, 1, List.empty()).toJSON(), {\n      _id: \"List\",\n      _tag: \"Cons\",\n      values: [0, 1, { _id: \"List\", _tag: \"Nil\" }]\n    })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n    deepStrictEqual(inspect(List.empty()), inspect({ _id: \"List\", _tag: \"Nil\" }))\n    deepStrictEqual(inspect(List.make(0, 1, 2)), inspect({ _id: \"List\", _tag: \"Cons\", values: [0, 1, 2] }))\n  })\n\n  it(\"equals\", () => {\n    assertTrue(List.empty()[symbol](List.empty()))\n    assertTrue(List.make(0)[symbol](List.make(0)))\n    assertFalse(List.empty()[symbol](Duration.millis(1)))\n    assertFalse(List.make(0)[symbol](Duration.millis(1)))\n\n    assertTrue(equals(List.empty(), List.empty()))\n    assertTrue(equals(List.make(0), List.make(0)))\n    assertFalse(equals(List.empty(), Duration.millis(1)))\n    assertFalse(equals(List.make(0), Duration.millis(1)))\n  })\n\n  it(\"to iterable\", () => {\n    deepStrictEqual(Array.fromIterable(List.empty()), [])\n    deepStrictEqual(Array.fromIterable(List.make(1, 2, 3)), [1, 2, 3])\n  })\n\n  it(\"fromIterable\", () => {\n    deepStrictEqual(List.fromIterable([]), List.empty())\n    deepStrictEqual(List.fromIterable([1, 2, 3]), List.make(1, 2, 3))\n  })\n\n  it(\".pipe\", () => {\n    deepStrictEqual(List.empty().pipe(List.prepend(1)), List.make(1))\n    deepStrictEqual(List.make(2).pipe(List.prepend(1)), List.make(1, 2))\n  })\n\n  it(\"getEquivalence\", () => {\n    const equivalence = List.getEquivalence(equals)\n    assertTrue(equivalence(List.empty(), List.empty()))\n    assertFalse(equivalence(List.empty(), List.of(1)))\n    assertFalse(equivalence(List.of(1), List.empty()))\n    assertFalse(equivalence(List.of(1), List.of(\"a\")))\n    assertFalse(equivalence(List.make(1, 2, 3), List.make(1, 2)))\n    assertFalse(equivalence(List.make(1, 2), List.make(1, 2, 3)))\n  })\n\n  it(\"compact\", () => {\n    deepStrictEqual(List.compact(List.empty()), List.empty())\n    deepStrictEqual(List.compact(List.make(Option.some(1), Option.some(2), Option.some(3))), List.make(1, 2, 3))\n    deepStrictEqual(List.compact(List.make(Option.some(1), Option.none(), Option.some(3))), List.make(1, 3))\n  })\n\n  it(\"last\", () => {\n    assertNone(List.last(List.empty()))\n    assertSome(List.last(List.make(1, 2, 3)), 3)\n  })\n\n  it(\"filter\", () => {\n    const isEven = (n: number) => n % 2 === 0\n    strictEqual(testStructuralSharing(List.filter(List.empty(), isEven), List.empty()), 0)\n\n    const share1 = List.of(2)\n    const input1 = List.cons(1, share1) // 1, 2\n    const r1 = List.filter(input1, isEven)\n    deepStrictEqual(r1, List.make(2))\n    strictEqual(testStructuralSharing(r1, share1), 0)\n\n    const share2 = List.make(2, 4)\n    const input2 = List.cons(1, share2) // 1, 2, 4\n    const r2 = List.filter(input2, isEven)\n    deepStrictEqual(r2, List.make(2, 4))\n    strictEqual(testStructuralSharing(r2, share2), 0)\n\n    const input3 = List.cons(4, List.cons(3, share1)) // 4, 3, 2\n    const r3 = List.filter(input3, isEven)\n    deepStrictEqual(r3, List.make(4, 2))\n    strictEqual(testStructuralSharing(r3, share1), 1)\n\n    deepStrictEqual(List.filter(List.make(2, 4, 1), isEven), List.make(2, 4))\n    deepStrictEqual(List.filter(List.make(2, 4, 1, 3), isEven), List.make(2, 4))\n    deepStrictEqual(List.filter(List.make(2, 4, 1, 6, 3), isEven), List.make(2, 4, 6))\n    const share3 = List.of(6)\n    const r4 = List.filter(List.appendAll(List.make(2, 4, 1, 3), share3), isEven)\n    deepStrictEqual(r4, List.make(2, 4, 6))\n    strictEqual(testStructuralSharing(r4, share3), 2)\n    const r5 = List.filter(List.appendAll(List.make(2, 4, 1), share3), isEven)\n    deepStrictEqual(r5, List.make(2, 4, 6))\n    strictEqual(testStructuralSharing(r5, share3), 2)\n  })\n\n  it(\"toArray\", () => {\n    deepStrictEqual(List.toArray(List.empty()), [])\n    deepStrictEqual(List.toArray(List.make(1, 2, 3)), [1, 2, 3])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/LogLevel.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { LogLevel } from \"effect\"\n\ndescribe(\"LogLevel\", () => {\n  it(\"fromLiteral\", () => {\n    strictEqual(LogLevel.fromLiteral(\"All\"), LogLevel.All)\n    strictEqual(LogLevel.fromLiteral(\"Debug\"), LogLevel.Debug)\n    strictEqual(LogLevel.fromLiteral(\"Error\"), LogLevel.Error)\n    strictEqual(LogLevel.fromLiteral(\"Fatal\"), LogLevel.Fatal)\n    strictEqual(LogLevel.fromLiteral(\"Info\"), LogLevel.Info)\n    strictEqual(LogLevel.fromLiteral(\"None\"), LogLevel.None)\n    strictEqual(LogLevel.fromLiteral(\"Trace\"), LogLevel.Trace)\n    strictEqual(LogLevel.fromLiteral(\"Warning\"), LogLevel.Warning)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Logger.test.ts",
    "content": "import { afterEach, beforeEach, describe, it, vi } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport {\n  Cause,\n  Chunk,\n  Effect,\n  FiberId,\n  FiberRefs,\n  HashMap,\n  identity,\n  List,\n  Logger,\n  LogLevel,\n  LogSpan,\n  pipe\n} from \"effect\"\nimport { logLevelInfo } from \"../src/internal/core.js\"\n\ndescribe(\"Logger\", () => {\n  it(\"isLogger\", () => {\n    assertTrue(Logger.isLogger(Logger.stringLogger))\n    assertTrue(Logger.isLogger(Logger.logfmtLogger))\n    assertFalse(Logger.isLogger({}))\n    assertFalse(Logger.isLogger(null))\n    assertFalse(Logger.isLogger(undefined))\n  })\n\n  it(\".pipe\", () => {\n    strictEqual(Logger.stringLogger.pipe(identity), Logger.stringLogger)\n    strictEqual(logLevelInfo.pipe(identity), logLevelInfo)\n  })\n})\n\ndescribe(\"withLeveledConsole\", () => {\n  it.effect(\"calls the respective Console functions on a given level\", () =>\n    Effect.gen(function*() {\n      const c = yield* Effect.console\n      const logs: Array<{ level: string; value: unknown }> = []\n      const pusher = (level: string) => (value: unknown) => {\n        logs.push({ level, value })\n      }\n      const newConsole: typeof c = {\n        ...c,\n        unsafe: {\n          ...c.unsafe,\n          log: pusher(\"log\"),\n          warn: pusher(\"warn\"),\n          error: pusher(\"error\"),\n          info: pusher(\"info\"),\n          debug: pusher(\"debug\"),\n          trace: pusher(\"trace\")\n        }\n      }\n\n      const logger = Logger.make((o) => String(o.message)).pipe(Logger.withLeveledConsole)\n      yield* Effect.gen(function*() {\n        yield* Effect.log(\"log plain\")\n        yield* Effect.logInfo(\"log info\")\n        yield* Effect.logWarning(\"log warn\")\n        yield* Effect.logError(\"log err\")\n        yield* Effect.logFatal(\"log fatal\")\n        yield* Effect.logDebug(\"log debug\")\n        yield* Effect.logTrace(\"log trace\")\n      }).pipe(\n        Effect.provide(Logger.replace(Logger.defaultLogger, logger)),\n        Logger.withMinimumLogLevel(LogLevel.Trace),\n        Effect.withConsole(newConsole)\n      )\n\n      deepStrictEqual(logs, [\n        { level: \"info\", value: \"log plain\" },\n        { level: \"info\", value: \"log info\" },\n        { level: \"warn\", value: \"log warn\" },\n        { level: \"error\", value: \"log err\" },\n        { level: \"error\", value: \"log fatal\" },\n        { level: \"debug\", value: \"log debug\" },\n        { level: \"trace\", value: \"log trace\" }\n      ])\n    }))\n})\n\ndescribe(\"stringLogger\", () => {\n  beforeEach(() => {\n    vi.useFakeTimers()\n  })\n  afterEach(() => {\n    vi.useRealTimers()\n  })\n\n  it(\"keys with special chars\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n    const spans = List.make(LogSpan.make(\"imma span=\\\"\", date.getTime() - 7))\n    const annotations = HashMap.make(\n      [\"just_a_key\", \"just_a_value\"],\n      [\"I am bad key name\", { coolValue: \"cool value\" }],\n      [\"good_key\", \"I am a good value\"],\n      [\"good_bool\", true],\n      [\"good_number\", 123]\n    )\n\n    const result = Logger.stringLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: \"My message\",\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans,\n      annotations,\n      date\n    })\n\n    strictEqual(\n      result,\n      `timestamp=${date.toJSON()} level=INFO fiber= message=\"My message\" imma_span__=7ms just_a_key=just_a_value good_key=\"I am a good value\" good_bool=true I_am_bad_key_name=\"{\n  \\\\\"coolValue\\\\\": \\\\\"cool value\\\\\"\n}\" good_number=123`\n    )\n  })\n\n  it(\"with linebreaks\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n    const spans = List.make(LogSpan.make(\"imma\\nspan=\\\"\", date.getTime() - 7))\n    const annotations = HashMap.make(\n      [\"I am also\\na bad key name\", { return: \"cool\\nvalue\" }],\n      [\"good_key\", { returnWithSpace: \"cool\\nvalue or not\" }],\n      [\"good_key2\", \"I am a good value\\nwith line breaks\"],\n      [\"good_key3\", \"I_have=a\"]\n    )\n\n    const result = Logger.stringLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: \"My\\nmessage\",\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans,\n      annotations,\n      date\n    })\n\n    strictEqual(\n      result,\n      `timestamp=${date.toJSON()} level=INFO fiber= message=\"My\nmessage\" imma_span__=7ms I_am_also_a_bad_key_name=\"{\n  \\\\\"return\\\\\": \\\\\"cool\\\\nvalue\\\\\"\n}\" good_key=\"{\n  \\\\\"returnWithSpace\\\\\": \\\\\"cool\\\\nvalue or not\\\\\"\n}\" good_key2=\"I am a good value\nwith line breaks\" good_key3=\"I_have=a\"`\n    )\n  })\n\n  it(\"multiple messages\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const result = Logger.stringLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: [\"a\", \"b\", \"c\"],\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations: HashMap.empty(),\n      date\n    })\n\n    strictEqual(result, `timestamp=${date.toJSON()} level=INFO fiber= message=a message=b message=c`)\n  })\n})\n\n// Adding sequential to the describe block because otherwise the \"batched\" test fails locally\ndescribe.sequential(\"logfmtLogger\", () => {\n  beforeEach(() => {\n    vi.useFakeTimers()\n  })\n  afterEach(() => {\n    vi.useRealTimers()\n  })\n\n  it(\"keys with special chars\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n    const spans = List.make(LogSpan.make(\"imma span=\\\"\", date.getTime() - 7))\n    const annotations = HashMap.make(\n      [\"just_a_key\", \"just_a_value\"],\n      [\"I am bad key name\", { coolValue: \"cool value\" }],\n      [\"good_key\", \"I am a good value\"]\n    )\n\n    const result = Logger.logfmtLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: \"My message\",\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans,\n      annotations,\n      date\n    })\n\n    strictEqual(\n      result,\n      `timestamp=${date.toJSON()} level=INFO fiber= message=\"My message\" imma_span__=7ms just_a_key=just_a_value good_key=\"I am a good value\" I_am_bad_key_name=\"{\\\\\"coolValue\\\\\":\\\\\"cool value\\\\\"}\"`\n    )\n  })\n\n  it(\"with linebreaks\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n    const spans = List.make(LogSpan.make(\"imma\\nspan=\\\"\", date.getTime() - 7))\n    const annotations = HashMap.make(\n      [\"I am also\\na bad key name\", { return: \"cool\\nvalue\" }],\n      [\"good_key\", { returnWithSpace: \"cool\\nvalue or not\" }],\n      [\"good_key2\", \"I am a good value\\nwith line breaks\"],\n      [\"good_key3\", \"I_have=a\"],\n      [\"good_bool\", true],\n      [\"good_number\", 123]\n    )\n\n    const result = Logger.logfmtLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: \"My\\nmessage\",\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans,\n      annotations,\n      date\n    })\n\n    strictEqual(\n      result,\n      `timestamp=${date.toJSON()} level=INFO fiber= message=\"My\\\\nmessage\" imma_span__=7ms I_am_also_a_bad_key_name=\"{\\\\\"return\\\\\":\\\\\"cool\\\\\\\\nvalue\\\\\"}\" good_key=\"{\\\\\"returnWithSpace\\\\\":\\\\\"cool\\\\\\\\nvalue or not\\\\\"}\" good_bool=true good_number=123 good_key2=\"I am a good value\\\\nwith line breaks\" good_key3=\"I_have=a\"`\n    )\n  })\n\n  it(\"objects\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const result = Logger.logfmtLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: { hello: \"world\" },\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations: HashMap.empty(),\n      date\n    })\n\n    strictEqual(result, `timestamp=${date.toJSON()} level=INFO fiber= message=\"{\\\\\"hello\\\\\":\\\\\"world\\\\\"}\"`)\n  })\n\n  it(\"circular objects\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const msg: Record<string, any> = { hello: \"world\" }\n    msg.msg = msg\n\n    const result = Logger.logfmtLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: msg,\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations: HashMap.empty(),\n      date\n    })\n\n    strictEqual(result, `timestamp=${date.toJSON()} level=INFO fiber= message=\"{\\\\\"hello\\\\\":\\\\\"world\\\\\"}\"`)\n  })\n\n  it(\"symbols\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const result = Logger.logfmtLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: Symbol.for(\"effect/Logger/test\"),\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations: HashMap.empty(),\n      date\n    })\n\n    strictEqual(result, `timestamp=${date.toJSON()} level=INFO fiber= message=Symbol(effect/Logger/test)`)\n  })\n\n  it(\"functions\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const result = Logger.logfmtLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: () => \"hello world\",\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations: HashMap.empty(),\n      date\n    })\n\n    strictEqual(result, `timestamp=${date.toJSON()} level=INFO fiber= message=\"() => \\\\\"hello world\\\\\"\"`)\n  })\n\n  it(\"annotations\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const annotations = HashMap.make([\"hashmap\", HashMap.make([\"key\", 2])], [\"chunk\", Chunk.make(1, 2)])\n\n    const result = Logger.logfmtLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: \"hello world\",\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations,\n      date\n    })\n\n    strictEqual(\n      result,\n      `timestamp=${date.toJSON()} level=INFO fiber= message=\"hello world\" hashmap=\"{\\\\\"_id\\\\\":\\\\\"HashMap\\\\\",\\\\\"values\\\\\":[[\\\\\"key\\\\\",2]]}\" chunk=\"{\\\\\"_id\\\\\":\\\\\"Chunk\\\\\",\\\\\"values\\\\\":[1,2]}\"`\n    )\n  })\n\n  it(\"batched\", () =>\n    Effect.gen(function*() {\n      const state: Array<Array<string>> = []\n      const date = new Date()\n      vi.setSystemTime(date)\n      const logger = yield* pipe(\n        Logger.logfmtLogger,\n        Logger.batched(\"100 millis\", (strings) =>\n          Effect.sync(() => {\n            state.push(strings)\n          }))\n      )\n      const log = (message: string) =>\n        logger.log({\n          fiberId: FiberId.none,\n          logLevel: logLevelInfo,\n          message,\n          cause: Cause.empty,\n          context: FiberRefs.unsafeMake(new Map()),\n          spans: List.empty(),\n          annotations: HashMap.empty(),\n          date\n        })\n\n      log(\"a\")\n      log(\"b\")\n      log(\"c\")\n      yield* Effect.promise(() => vi.advanceTimersByTimeAsync(100))\n      log(\"d\")\n      log(\"e\")\n      yield* Effect.promise(() => vi.advanceTimersByTimeAsync(100))\n\n      deepStrictEqual(state, [\n        [\n          `timestamp=${date.toISOString()} level=INFO fiber= message=a`,\n          `timestamp=${date.toISOString()} level=INFO fiber= message=b`,\n          `timestamp=${date.toISOString()} level=INFO fiber= message=c`\n        ],\n        [\n          `timestamp=${date.toISOString()} level=INFO fiber= message=d`,\n          `timestamp=${date.toISOString()} level=INFO fiber= message=e`\n        ]\n      ])\n    }).pipe(Effect.scoped, Effect.runPromise))\n\n  it(\"multiple messages\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const result = Logger.logfmtLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: [\"a\", \"b\", \"c\"],\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations: HashMap.empty(),\n      date\n    })\n\n    strictEqual(result, `timestamp=${date.toJSON()} level=INFO fiber= message=a message=b message=c`)\n  })\n})\n\ndescribe(\"jsonLogger\", () => {\n  beforeEach(() => {\n    vi.useFakeTimers()\n  })\n  afterEach(() => {\n    vi.useRealTimers()\n  })\n\n  it(\"keys with special chars\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n    const spans = List.make(LogSpan.make(\"imma span=\\\"\", date.getTime() - 7))\n    const annotations = HashMap.make(\n      [\"just_a_key\", \"just_a_value\"],\n      [\"I am bad key name\", { coolValue: \"cool value\" }],\n      [\"good_key\", \"I am a good value\"],\n      [\"good_bool\", true],\n      [\"good_number\", 123]\n    )\n\n    const result = Logger.jsonLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: \"My message\",\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans,\n      annotations,\n      date\n    })\n\n    strictEqual(\n      result,\n      JSON.stringify({\n        message: \"My message\",\n        logLevel: \"INFO\",\n        timestamp: date.toJSON(),\n        annotations: {\n          just_a_key: \"just_a_value\",\n          good_key: \"I am a good value\",\n          good_bool: true,\n          \"I am bad key name\": { coolValue: \"cool value\" },\n          good_number: 123\n        },\n        spans: { \"imma span=\\\"\": 7 },\n        fiberId: \"\"\n      })\n    )\n  })\n\n  it(\"objects\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const result = Logger.jsonLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: { hello: \"world\" },\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations: HashMap.empty(),\n      date\n    })\n\n    strictEqual(\n      result,\n      JSON.stringify({\n        message: { hello: \"world\" },\n        logLevel: \"INFO\",\n        timestamp: date.toJSON(),\n        annotations: {},\n        spans: {},\n        fiberId: \"\"\n      })\n    )\n  })\n\n  it(\"circular objects\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const msg: Record<string, any> = { hello: \"world\" }\n    msg.msg = msg\n\n    const result = Logger.jsonLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: msg,\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations: HashMap.empty(),\n      date\n    })\n\n    strictEqual(\n      result,\n      JSON.stringify({\n        message: { hello: \"world\" },\n        logLevel: \"INFO\",\n        timestamp: date.toJSON(),\n        annotations: {},\n        spans: {},\n        fiberId: \"\"\n      })\n    )\n  })\n\n  it(\"symbols\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const result = Logger.jsonLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: Symbol.for(\"effect/Logger/test\"),\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations: HashMap.empty(),\n      date\n    })\n\n    strictEqual(\n      result,\n      JSON.stringify({\n        message: Symbol.for(\"effect/Logger/test\").toString(),\n        logLevel: \"INFO\",\n        timestamp: date.toJSON(),\n        annotations: {},\n        spans: {},\n        fiberId: \"\"\n      })\n    )\n  })\n\n  it(\"functions\", () => {\n    const date = new Date()\n    vi.setSystemTime(date)\n\n    const result = Logger.jsonLogger.log({\n      fiberId: FiberId.none,\n      logLevel: logLevelInfo,\n      message: () => \"hello world\",\n      cause: Cause.empty,\n      context: FiberRefs.unsafeMake(new Map()),\n      spans: List.empty(),\n      annotations: HashMap.empty(),\n      date\n    })\n\n    strictEqual(\n      result,\n      JSON.stringify({\n        message: \"() => \\\"hello world\\\"\",\n        logLevel: \"INFO\",\n        timestamp: date.toJSON(),\n        annotations: {},\n        spans: {},\n        fiberId: \"\"\n      })\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Mailbox.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertNone, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Chunk, Effect, Exit, Fiber, Mailbox, Stream } from \"effect\"\n\ndescribe(\"Mailbox\", () => {\n  it.effect(\"offerAll with capacity\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number>(2)\n      const fiber = yield* mailbox.offerAll([1, 2, 3, 4]).pipe(\n        Effect.fork\n      )\n      yield* Effect.yieldNow({ priority: 1 })\n      assertTrue(fiber.unsafePoll() === null)\n\n      let result = yield* mailbox\n      deepStrictEqual(Chunk.toReadonlyArray(result[0]), [1, 2])\n      assertFalse(result[1])\n\n      yield* Effect.yieldNow({ priority: 1 })\n      assertTrue(fiber.unsafePoll() !== null)\n\n      result = yield* mailbox.takeAll\n      deepStrictEqual(Chunk.toReadonlyArray(result[0]), [3, 4])\n      assertFalse(result[1])\n\n      yield* Effect.yieldNow({ priority: 1 })\n      deepStrictEqual(fiber.unsafePoll(), Exit.succeed(Chunk.empty()))\n    }))\n\n  it.effect(\"offer dropping\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number>({ capacity: 2, strategy: \"dropping\" })\n      const remaining = yield* mailbox.offerAll([1, 2, 3, 4])\n      deepStrictEqual(Chunk.toReadonlyArray(remaining), [3, 4])\n      const result = yield* mailbox.offer(5)\n      assertFalse(result)\n      deepStrictEqual(Chunk.toReadonlyArray((yield* mailbox.takeAll)[0]), [1, 2])\n    }))\n\n  it.effect(\"offer sliding\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number>({ capacity: 2, strategy: \"sliding\" })\n      const remaining = yield* mailbox.offerAll([1, 2, 3, 4])\n      deepStrictEqual(Chunk.toReadonlyArray(remaining), [])\n      const result = yield* mailbox.offer(5)\n      assertTrue(result)\n      deepStrictEqual(Chunk.toReadonlyArray((yield* mailbox.takeAll)[0]), [4, 5])\n    }))\n\n  it.effect(\"offerAll can be interrupted\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number>(2)\n      const fiber = yield* mailbox.offerAll([1, 2, 3, 4]).pipe(\n        Effect.fork\n      )\n\n      yield* Effect.yieldNow({ priority: 1 })\n      yield* Fiber.interrupt(fiber)\n      yield* Effect.yieldNow({ priority: 1 })\n\n      let result = yield* mailbox.takeAll\n      deepStrictEqual(Chunk.toReadonlyArray(result[0]), [1, 2])\n      assertFalse(result[1])\n\n      yield* mailbox.offer(5)\n      yield* Effect.yieldNow({ priority: 1 })\n\n      result = yield* mailbox.takeAll\n      deepStrictEqual(Chunk.toReadonlyArray(result[0]), [5])\n      assertFalse(result[1])\n    }))\n\n  it.effect(\"done completes takes\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number>(2)\n      const fiber = yield* mailbox.takeAll.pipe(\n        Effect.fork\n      )\n      yield* Effect.yieldNow()\n      yield* mailbox.done(Exit.void)\n      deepStrictEqual(yield* fiber.await, Exit.succeed([Chunk.empty(), true] as const))\n    }))\n\n  it.effect(\"end\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number>(2)\n      yield* Effect.fork(mailbox.offerAll([1, 2, 3, 4]))\n      yield* Effect.fork(mailbox.offerAll([5, 6, 7, 8]))\n      yield* Effect.fork(mailbox.offer(9))\n      yield* Effect.fork(mailbox.end)\n      const items = yield* Stream.runCollect(Mailbox.toStream(mailbox))\n      deepStrictEqual(Chunk.toReadonlyArray(items), [1, 2, 3, 4, 5, 6, 7, 8, 9])\n      strictEqual(yield* mailbox.await, void 0)\n      strictEqual(yield* mailbox.offer(10), false)\n    }))\n\n  it.effect(\"end with take\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number>(2)\n      yield* Effect.fork(mailbox.offerAll([1, 2]))\n      yield* Effect.fork(mailbox.offer(3))\n      yield* Effect.fork(mailbox.end)\n      strictEqual(yield* mailbox.take, 1)\n      strictEqual(yield* mailbox.take, 2)\n      strictEqual(yield* mailbox.take, 3)\n      assertNone(yield* mailbox.take.pipe(Effect.optionFromOptional))\n      strictEqual(yield* mailbox.await, void 0)\n      strictEqual(yield* mailbox.offer(10), false)\n    }))\n\n  it.effect(\"fail\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number, string>(2)\n      yield* Effect.fork(mailbox.offerAll([1, 2, 3, 4]))\n      yield* Effect.fork(mailbox.offer(5))\n      yield* Effect.fork(mailbox.fail(\"boom\"))\n      const takeArr = Effect.map(mailbox.takeAll, ([_]) => Chunk.toReadonlyArray(_))\n      deepStrictEqual(yield* takeArr, [1, 2])\n      deepStrictEqual(yield* takeArr, [3, 4])\n      const [items, done] = yield* mailbox.takeAll\n      deepStrictEqual(Chunk.toReadonlyArray(items), [5])\n      strictEqual(done, false)\n      const error = yield* mailbox.takeAll.pipe(Effect.flip)\n      deepStrictEqual(error, \"boom\")\n      strictEqual(yield* mailbox.await.pipe(Effect.flip), \"boom\")\n      strictEqual(yield* mailbox.offer(6), false)\n    }))\n\n  it.effect(\"shutdown\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number>(2)\n      yield* Effect.fork(mailbox.offerAll([1, 2, 3, 4]))\n      yield* Effect.fork(mailbox.offerAll([5, 6, 7, 8]))\n      yield* Effect.fork(mailbox.shutdown)\n      const items = yield* Stream.runCollect(Mailbox.toStream(mailbox))\n      deepStrictEqual(Chunk.toReadonlyArray(items), [])\n      strictEqual(yield* mailbox.await, void 0)\n      strictEqual(yield* mailbox.offer(10), false)\n    }))\n\n  it.effect(\"fail doesnt drop items\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number, string>(2)\n      yield* Effect.fork(mailbox.offerAll([1, 2, 3, 4]))\n      yield* Effect.fork(mailbox.offer(5))\n      yield* Effect.fork(mailbox.fail(\"boom\"))\n      const items: Array<number> = []\n      const error = yield* Mailbox.toStream(mailbox).pipe(\n        Stream.runForEach((item) => Effect.sync(() => items.push(item))),\n        Effect.flip\n      )\n      deepStrictEqual(items, [1, 2, 3, 4, 5])\n      strictEqual(error, \"boom\")\n    }))\n\n  it.effect(\"await waits for no items\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number>()\n      const fiber = yield* mailbox.await.pipe(Effect.fork)\n      yield* Effect.yieldNow()\n      yield* mailbox.offer(1)\n      yield* mailbox.end\n\n      yield* Effect.yieldNow()\n      assertTrue(fiber.unsafePoll() === null)\n      const [result, done] = yield* mailbox.takeAll\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1])\n      assertTrue(done)\n      yield* Effect.yieldNow()\n      assertTrue(fiber.unsafePoll() !== null)\n    }))\n\n  it.effect(\"bounded 0 capacity\", () =>\n    Effect.gen(function*() {\n      const mailbox = yield* Mailbox.make<number>(0)\n      yield* mailbox.offer(1).pipe(Effect.fork)\n      let result = yield* mailbox.take\n      strictEqual(result, 1)\n\n      const fiber = yield* mailbox.take.pipe(Effect.fork)\n      yield* mailbox.offer(2)\n      result = yield* Fiber.join(fiber)\n      strictEqual(result, 2)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/ManagedRuntime.test.ts",
    "content": "import { describe, it, test } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Context, Effect, FiberRef, FiberRefs, Layer, List, ManagedRuntime } from \"effect\"\n\ndescribe(\"ManagedRuntime\", () => {\n  test(\"memoizes the layer build\", async () => {\n    let count = 0\n    const layer = Layer.effectDiscard(Effect.sync(() => {\n      count++\n    }))\n    const runtime = ManagedRuntime.make(layer)\n    await runtime.runPromise(Effect.void)\n    await runtime.runPromise(Effect.void)\n    await runtime.dispose()\n    strictEqual(count, 1)\n  })\n\n  test(\"provides context\", async () => {\n    const tag = Context.GenericTag<string>(\"string\")\n    const layer = Layer.succeed(tag, \"test\")\n    const runtime = ManagedRuntime.make(layer)\n    const result = await runtime.runPromise(tag)\n    await runtime.dispose()\n    strictEqual(result, \"test\")\n  })\n\n  test(\"provides fiberRefs\", async () => {\n    const layer = Layer.setRequestCaching(true)\n    const runtime = ManagedRuntime.make(layer)\n    const result = await runtime.runPromise(FiberRef.get(FiberRef.currentRequestCacheEnabled))\n    await runtime.dispose()\n    strictEqual(result, true)\n  })\n\n  test(\"allows sharing a MemoMap\", async () => {\n    let count = 0\n    const layer = Layer.effectDiscard(Effect.sync(() => {\n      count++\n    }))\n    const runtimeA = ManagedRuntime.make(layer)\n    const runtimeB = ManagedRuntime.make(layer, runtimeA.memoMap)\n    await runtimeA.runPromise(Effect.void)\n    await runtimeB.runPromise(Effect.void)\n    await runtimeA.dispose()\n    await runtimeB.dispose()\n    strictEqual(count, 1)\n  })\n\n  it.effect(\"is subtype of effect\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<string>(\"string\")\n      const layer = Layer.succeed(tag, \"test\")\n      const managedRuntime = ManagedRuntime.make(layer)\n      const runtime = yield* managedRuntime\n      const result = Context.get(runtime.context, tag)\n      strictEqual(result, \"test\")\n    }))\n\n  it.effect(\"does not inherit fiber refs\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<string>(\"string\")\n      const layer = Layer.succeed(tag, \"test\")\n      const managedRuntime = ManagedRuntime.make(layer)\n      const runtime = yield* managedRuntime.runtimeEffect.pipe(\n        Effect.withLogSpan(\"test\")\n      )\n      const result = FiberRefs.getOrDefault(runtime.fiberRefs, FiberRef.currentLogSpan)\n      deepStrictEqual(result, List.empty())\n    }))\n\n  it(\"can be build synchronously\", () => {\n    const tag = Context.GenericTag<string>(\"string\")\n    const layer = Layer.succeed(tag, \"test\")\n    const managedRuntime = ManagedRuntime.make(layer)\n    const runtime = Effect.runSync(managedRuntime.runtimeEffect)\n    const result = Context.get(runtime.context, tag)\n    strictEqual(result, \"test\")\n  })\n\n  it(\"is built synchronously with runFork\", () => {\n    const runtime = ManagedRuntime.make(Layer.empty)\n    runtime.runFork(Effect.void)\n    runtime.runSync(Effect.void)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Match.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertLeft,\n  assertNone,\n  assertRight,\n  assertSome,\n  assertTrue,\n  doesNotThrow,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { Either, Match as M, Option, pipe, Predicate } from \"effect\"\n\ndescribe(\"Match\", () => {\n  it(\"TypeMatcher.pipe() method\", () => {\n    const match = M.type<string | number>().pipe(\n      M.when(M.number, (n) => `number: ${n}`),\n      M.when(M.string, (s) => `string: ${s}`),\n      M.exhaustive\n    )\n\n    strictEqual(match(123), \"number: 123\")\n    strictEqual(match(\"hello\"), \"string: hello\")\n  })\n\n  it(\"ValueMatcher.pipe() method\", () => {\n    const input: string | number = 123\n    const match = M.value(input).pipe(\n      M.when(M.number, (n) => `number: ${n}`),\n      M.when(M.string, (s) => `string: ${s}`),\n      M.exhaustive\n    )\n\n    strictEqual(match, \"number: 123\")\n  })\n\n  it(\"exhaustive\", () => {\n    const match = pipe(\n      M.type<{ a: number } | { b: number }>(),\n      M.when({ a: M.number }, (_) => _.a),\n      M.when({ b: M.number }, (_) => _.b),\n      M.exhaustive\n    )\n    strictEqual(match({ a: 0 }), 0)\n    strictEqual(match({ b: 1 }), 1)\n  })\n\n  it(\"exhaustive-literal\", () => {\n    const match = pipe(\n      M.type<{ _tag: \"A\"; a: number } | { _tag: \"B\"; b: number }>(),\n      M.when({ _tag: \"A\" }, (_) => Either.right(_.a)),\n      M.when({ _tag: \"B\" }, (_) => Either.right(_.b)),\n      M.exhaustive\n    )\n    assertRight(match({ _tag: \"A\", a: 0 }), 0)\n    assertRight(match({ _tag: \"B\", b: 1 }), 1)\n  })\n\n  it(\"schema exhaustive-literal\", () => {\n    const match = pipe(\n      M.type<{ _tag: \"A\"; a: number | string } | { _tag: \"B\"; b: number }>(),\n      M.when({ _tag: M.is(\"A\", \"B\"), a: M.number }, (_) => {\n        return Either.right(_._tag)\n      }),\n      M.when({ _tag: M.string, a: M.string }, (_) => {\n        return Either.right(_._tag)\n      }),\n      M.when({ b: M.number }, (_) => Either.left(_._tag)),\n      M.orElse((_) => {\n        throw \"absurd\"\n      })\n    )\n    assertRight(match({ _tag: \"A\", a: 0 }), \"A\")\n    assertRight(match({ _tag: \"A\", a: \"hi\" }), \"A\")\n    assertLeft(match({ _tag: \"B\", b: 1 }), \"B\")\n  })\n\n  it(\"exhaustive literal with not\", () => {\n    const match = pipe(\n      M.type<number>(),\n      M.when(1, (_) => true),\n      M.not(1, (_) => false),\n      M.exhaustive\n    )\n    assertTrue(match(1))\n    assertFalse(match(2))\n  })\n\n  it(\"inline\", () => {\n    const result = pipe(\n      M.value(Either.right(0)),\n      M.tag(\"Right\", (_) => _.right),\n      M.tag(\"Left\", (_) => _.left),\n      M.exhaustive\n    )\n    strictEqual(result, 0)\n  })\n\n  it(\"piped\", () => {\n    const result = pipe(\n      Either.right(0),\n      M.value,\n      M.when({ _tag: \"Right\" }, (_) => _.right),\n      M.option\n    )\n    assertSome(result, 0)\n  })\n\n  it(\"tuples\", () => {\n    const match = pipe(\n      M.type<[string, string]>(),\n      M.when([\"yeah\"], (_) => {\n        return true\n      }),\n      M.option\n    )\n\n    assertNone(match({ length: 2 } as any))\n    assertNone(match([\"a\", \"b\"]))\n    assertSome(match([\"yeah\", \"a\"]), true)\n  })\n\n  it(\"literals\", () => {\n    const match = pipe(\n      M.type<string>(),\n      M.when(\"yeah\", (_) => _ === \"yeah\"),\n      M.orElse(() => \"nah\")\n    )\n\n    strictEqual(match(\"yeah\"), true)\n    strictEqual(match(\"a\"), \"nah\")\n  })\n\n  it(\"piped\", () => {\n    const result = pipe(\n      Either.right(0),\n      M.value,\n      M.when({ _tag: \"Right\" }, (_) => _.right),\n      M.option\n    )\n    assertSome(result, 0)\n  })\n\n  it(\"not schema\", () => {\n    const match = pipe(\n      M.type<string | number>(),\n      M.not(M.number, (_) => \"a\"),\n      M.when(M.number, (_) => \"b\"),\n      M.exhaustive\n    )\n    strictEqual(match(\"hi\"), \"a\")\n    strictEqual(match(123), \"b\")\n  })\n\n  it(\"not literal\", () => {\n    const match = pipe(\n      M.type<string | number>(),\n      M.not(\"hi\", (_) => {\n        return \"a\"\n      }),\n      M.orElse((_) => \"b\")\n    )\n    strictEqual(match(\"hello\"), \"a\")\n    strictEqual(match(\"hi\"), \"b\")\n  })\n\n  it(\"literals\", () => {\n    const match = pipe(\n      M.type<string>(),\n      M.when(\"yeah\", (_) => {\n        return _ === \"yeah\"\n      }),\n      M.orElse(() => \"nah\")\n    )\n\n    strictEqual(match(\"yeah\"), true)\n    strictEqual(match(\"a\"), \"nah\")\n  })\n\n  it(\"literals duplicate\", () => {\n    const result = pipe(\n      M.value(\"yeah\" as string),\n      M.when(\"yeah\", (_) => _ === \"yeah\"),\n      M.when(\"yeah\", (_) => \"dupe\"),\n      M.orElse((_) => \"nah\")\n    )\n\n    strictEqual(result, true)\n  })\n\n  it(\"discriminator\", () => {\n    const match = pipe(\n      M.type<{ type: \"A\" } | { type: \"B\" }>(),\n      M.discriminator(\"type\")(\"A\", (_) => _.type),\n      M.discriminator(\"type\")(\"B\", (_) => _.type),\n      M.exhaustive\n    )\n    strictEqual(match({ type: \"B\" }), \"B\")\n  })\n\n  it(\"discriminator with nullables\", () => {\n    const match = M.type<{ _tag: \"A\" } | undefined>().pipe(\n      M.tags({ A: (x) => x._tag }),\n      M.orElse(() => null)\n    )\n    doesNotThrow(() => match(undefined))\n  })\n\n  it(\"Match.tag with nullable union\", () => {\n    const match = M.type<{ _tag: \"A\" } | undefined>().pipe(\n      M.tag(\"A\", () => \"matched A\"),\n      M.when(undefined, () => \"matched undefined\"),\n      M.exhaustive\n    )\n    strictEqual(match({ _tag: \"A\" }), \"matched A\")\n    strictEqual(match(undefined), \"matched undefined\")\n  })\n\n  it(\"Match.tag with null union\", () => {\n    const match = M.type<{ _tag: \"A\" } | null>().pipe(\n      M.tag(\"A\", () => \"matched A\"),\n      M.when(null, () => \"matched null\"),\n      M.exhaustive\n    )\n    strictEqual(match({ _tag: \"A\" }), \"matched A\")\n    strictEqual(match(null), \"matched null\")\n  })\n\n  it(\"Match.tagStartsWith with nullable union\", () => {\n    const match = M.type<{ _tag: \"A.B\" } | undefined>().pipe(\n      M.tagStartsWith(\"A\", () => \"matched A prefix\"),\n      M.when(undefined, () => \"matched undefined\"),\n      M.exhaustive\n    )\n    strictEqual(match({ _tag: \"A.B\" }), \"matched A prefix\")\n    strictEqual(match(undefined), \"matched undefined\")\n  })\n\n  it(\"discriminator multiple\", () => {\n    const result = pipe(\n      M.value(Either.right(0)),\n      M.discriminator(\"_tag\")(\"Right\", \"Left\", (_) => \"match\"),\n      M.exhaustive\n    )\n    strictEqual(result, \"match\")\n  })\n\n  it(\"nested\", () => {\n    const match = pipe(\n      M.type<\n        | { foo: { bar: { baz: { qux: string } } } }\n        | { foo: { bar: { baz: { qux: number } } } }\n        | { foo: { bar: null } }\n      >(),\n      M.when({ foo: { bar: { baz: { qux: 2 } } } }, (_) => {\n        return `literal ${_.foo.bar.baz.qux}`\n      }),\n      M.when({ foo: { bar: { baz: { qux: \"b\" } } } }, (_) => {\n        return `literal ${_.foo.bar.baz.qux}`\n      }),\n      M.when(\n        { foo: { bar: { baz: { qux: M.number } } } },\n        (_) => _.foo.bar.baz.qux\n      ),\n      M.when(\n        { foo: { bar: { baz: { qux: M.string } } } },\n        (_) => _.foo.bar.baz.qux\n      ),\n      M.when({ foo: { bar: null } }, (_) => _.foo.bar),\n      M.exhaustive\n    )\n\n    strictEqual(match({ foo: { bar: { baz: { qux: 1 } } } }), 1)\n    strictEqual(match({ foo: { bar: { baz: { qux: 2 } } } }), \"literal 2\")\n    strictEqual(match({ foo: { bar: { baz: { qux: \"a\" } } } }), \"a\")\n    strictEqual(match({ foo: { bar: { baz: { qux: \"b\" } } } }), \"literal b\")\n    strictEqual(match({ foo: { bar: null } }), null)\n  })\n\n  it(\"nested Option\", () => {\n    const match = pipe(\n      M.type<{ user: Option.Option<{ readonly name: string }> }>(),\n      M.when({ user: { _tag: \"Some\" } }, (_) => _.user.value.name),\n      M.orElse((_) => \"fail\")\n    )\n\n    strictEqual(match({ user: Option.some({ name: \"a\" }) }), \"a\")\n    strictEqual(match({ user: Option.none() }), \"fail\")\n  })\n\n  it(\"predicate\", () => {\n    const match = pipe(\n      M.type<{ age: number }>(),\n      M.when({ age: (a) => a >= 5 }, (_) => `Age: ${_.age}`),\n      M.orElse((_) => `${_.age} is too young`)\n    )\n\n    strictEqual(match({ age: 5 }), \"Age: 5\")\n    strictEqual(match({ age: 4 }), \"4 is too young\")\n  })\n\n  it(\"predicate not\", () => {\n    const match = pipe(\n      M.type<{ age: number }>(),\n      M.not({ age: (a) => a >= 5 }, (_) => `Age: ${_.age}`),\n      M.orElse((_) => `${_.age} is too old`)\n    )\n\n    strictEqual(match({ age: 4 }), \"Age: 4\")\n    strictEqual(match({ age: 5 }), \"5 is too old\")\n\n    const result = pipe(\n      M.value({ age: 4 }),\n      M.not({ age: (a) => a >= 5 }, (_) => `Age: ${_.age}`),\n      M.orElse((_) => `${_.age} is too old`)\n    )\n    strictEqual(result, \"Age: 4\")\n  })\n\n  it(\"predicate with functions\", () => {\n    const match = pipe(\n      M.type<{\n        a: number\n        b: {\n          c: string\n          f?: (status: number) => Promise<string>\n        }\n      }>(),\n      M.when({ a: 400 }, (_) => \"400\"),\n      M.when({ b: (b) => b.c === \"nested\" }, (_) => _.b.c),\n      M.orElse(() => \"fail\")\n    )\n\n    strictEqual(match({ b: { c: \"nested\" }, a: 200 }), \"nested\")\n    strictEqual(match({ b: { c: \"nested\" }, a: 400 }), \"400\")\n  })\n\n  it(\"predicate at root level\", () => {\n    const match = pipe(\n      M.type<{\n        a: number\n        b: {\n          c: string\n          f?: (status: number) => Promise<string>\n        }\n      }>(),\n      M.when(\n        (_) => _.a === 400,\n        (_) => \"400\"\n      ),\n      M.when({ b: (b) => b.c === \"nested\" }, (_) => _.b.c),\n      M.orElse(() => \"fail\")\n    )\n\n    strictEqual(match({ b: { c: \"nested\" }, a: 200 }), \"nested\")\n    strictEqual(match({ b: { c: \"nested\" }, a: 400 }), \"400\")\n  })\n\n  it(\"symbols\", () => {\n    const thing = {\n      symbol: Symbol(),\n      name: \"thing\"\n    } as const\n\n    const match = pipe(\n      M.value(thing),\n      M.when({ name: \"thing\" }, (_) => _.name),\n      M.exhaustive\n    )\n\n    strictEqual(match, \"thing\")\n  })\n\n  it(\"unify\", () => {\n    const match = pipe(\n      M.type<{ readonly _tag: \"A\" } | { readonly _tag: \"B\" }>(),\n      M.tag(\"A\", () => Either.right(\"a\") as Either.Either<string, number>),\n      M.tag(\"B\", () => Either.right(123) as Either.Either<number, string>),\n      M.exhaustive\n    )\n\n    assertRight(match({ _tag: \"B\" }), 123)\n  })\n\n  it(\"optional props\", () => {\n    const match = pipe(\n      M.type<{ readonly user?: { readonly name: string } | undefined }>(),\n      M.when({ user: M.any }, (_) => _.user?.name),\n      M.orElse(() => \"no user\")\n    )\n\n    strictEqual(match({}), \"no user\")\n    strictEqual(match({ user: undefined }), undefined)\n    strictEqual(match({ user: { name: \"Tim\" } }), \"Tim\")\n  })\n\n  it(\"optional props defined\", () => {\n    const match = pipe(\n      M.type<{ readonly user?: { readonly name: string } | null | undefined }>(),\n      M.when({ user: M.defined }, (_) => _.user.name),\n      M.orElse(() => \"no user\")\n    )\n\n    strictEqual(match({}), \"no user\")\n    strictEqual(match({ user: undefined }), \"no user\")\n    strictEqual(match({ user: null }), \"no user\")\n    strictEqual(match({ user: { name: \"Tim\" } }), \"Tim\")\n  })\n\n  it(\"deep recursive\", () => {\n    type A =\n      | null\n      | string\n      | number\n      | { [K in string]: A }\n\n    const match = pipe(\n      M.type<A>(),\n      M.when(Predicate.isNull, (_) => {\n        return \"null\"\n      }),\n      M.when(Predicate.isBoolean, (_) => {\n        return \"boolean\"\n      }),\n      M.when(Predicate.isNumber, (_) => {\n        return \"number\"\n      }),\n      M.when(Predicate.isString, (_) => {\n        return \"string\"\n      }),\n      M.when(M.record, (_) => {\n        return \"record\"\n      }),\n      M.when(Predicate.isSymbol, (_) => {\n        return \"symbol\"\n      }),\n      M.when(Predicate.isReadonlyRecord, (_) => {\n        return \"readonlyrecord\"\n      }),\n      M.exhaustive\n    )\n\n    strictEqual(match(null), \"null\")\n    strictEqual(match(123), \"number\")\n    strictEqual(match(\"hi\"), \"string\")\n    strictEqual(match({}), \"record\")\n  })\n\n  it(\"nested option\", () => {\n    type ABC =\n      | { readonly _tag: \"A\" }\n      | { readonly _tag: \"B\" }\n      | { readonly _tag: \"C\" }\n\n    const match = pipe(\n      M.type<{ readonly abc: Option.Option<ABC> }>(),\n      M.when({ abc: { value: { _tag: \"A\" } } }, (_) => _.abc.value._tag),\n      M.orElse((_) => \"no match\")\n    )\n\n    strictEqual(match({ abc: Option.some({ _tag: \"A\" }) }), \"A\")\n    strictEqual(match({ abc: Option.some({ _tag: \"B\" }) }), \"no match\")\n    strictEqual(match({ abc: Option.none() }), \"no match\")\n  })\n\n  it(\"getters\", () => {\n    class Thing {\n      get name() {\n        return \"thing\"\n      }\n    }\n\n    const match = pipe(\n      M.value(new Thing()),\n      M.when({ name: \"thing\" }, (_) => _.name),\n      M.orElse(() => \"fail\")\n    )\n\n    strictEqual(match, \"thing\")\n  })\n\n  it(\"whenOr\", () => {\n    const match = pipe(\n      M.type<\n        { _tag: \"A\"; a: number } | { _tag: \"B\"; b: number } | { _tag: \"C\" }\n      >(),\n      M.whenOr({ _tag: \"A\" }, { _tag: \"B\" }, (_) => \"A or B\"),\n      M.when({ _tag: \"C\" }, (_) => \"C\"),\n      M.exhaustive\n    )\n    strictEqual(match({ _tag: \"A\", a: 0 }), \"A or B\")\n    strictEqual(match({ _tag: \"B\", b: 1 }), \"A or B\")\n    strictEqual(match({ _tag: \"C\" }), \"C\")\n  })\n\n  it(\"optional array\", () => {\n    const match = pipe(\n      M.type<{ a?: ReadonlyArray<{ name: string }> }>(),\n      M.when({ a: (_) => _.length > 0 }, (_) => `match ${_.a.length}`),\n      M.orElse(() => \"no match\")\n    )\n\n    strictEqual(match({ a: [{ name: \"Tim\" }] }), \"match 1\")\n    strictEqual(match({ a: [] }), \"no match\")\n    strictEqual(match({}), \"no match\")\n  })\n\n  it(\"whenAnd\", () => {\n    const match = pipe(\n      M.type<\n        { _tag: \"A\"; a: number } | { _tag: \"B\"; b: number } | { _tag: \"C\" }\n      >(),\n      M.whenAnd({ _tag: \"A\" }, { a: M.number }, (_) => \"A\"),\n      M.whenAnd({ _tag: \"B\" }, { b: M.number }, (_) => \"B\"),\n      M.when({ _tag: \"C\" }, (_) => \"C\"),\n      M.exhaustive\n    )\n    strictEqual(match({ _tag: \"A\", a: 0 }), \"A\")\n    strictEqual(match({ _tag: \"B\", b: 1 }), \"B\")\n    strictEqual(match({ _tag: \"C\" }), \"C\")\n  })\n\n  it(\"whenAnd nested\", () => {\n    const match = pipe(\n      M.type<{\n        status: number\n        user?: {\n          name: string\n          manager?: {\n            name: string\n          }\n        }\n        company?: {\n          name: string\n        }\n      }>(),\n      M.whenAnd(\n        { status: 200 },\n        { user: { name: M.string } },\n        { user: { manager: { name: M.string } } },\n        { company: { name: M.string } },\n        (_) =>\n          [_.status, _.user.name, _.user.manager.name, _.company.name].join(\n            \", \"\n          )\n      ),\n      M.whenAnd(\n        { status: 200 },\n        { user: { name: M.string } },\n        { company: { name: M.string } },\n        (_) => [_.status, _.user.name, _.company.name].join(\", \")\n      ),\n      M.whenAnd(\n        { status: 200 },\n        { user: { name: M.string } },\n        (_) => [_.status, _.user.name].join(\", \")\n      ),\n      M.whenAnd(\n        { status: M.number },\n        { user: { name: M.string } },\n        (_) => [\"number\", _.user.name].join(\", \")\n      ),\n      M.when({ status: M.number }, (_) => \"number\"),\n      M.exhaustive\n    )\n    strictEqual(\n      match({\n        status: 200,\n        user: { name: \"Tim\", manager: { name: \"Joe\" } },\n        company: { name: \"Apple\" }\n      }),\n      \"200, Tim, Joe, Apple\"\n    )\n    strictEqual(\n      match({\n        status: 200,\n        user: { name: \"Tim\" },\n        company: { name: \"Apple\" }\n      }),\n      \"200, Tim, Apple\"\n    )\n    strictEqual(\n      match({\n        status: 200,\n        user: { name: \"Tim\" },\n        company: { name: \"Apple\" }\n      }),\n      \"200, Tim, Apple\"\n    )\n    strictEqual(\n      match({\n        status: 200,\n        user: { name: \"Tim\" }\n      }),\n      \"200, Tim\"\n    )\n    strictEqual(match({ status: 100, user: { name: \"Tim\" } }), \"number, Tim\")\n    strictEqual(match({ status: 100 }), \"number\")\n  })\n\n  it(\"instanceOf\", () => {\n    const match = pipe(\n      M.type<Uint8Array | Uint16Array>(),\n      M.when(M.instanceOf(Uint8Array), (_) => {\n        return \"uint8\"\n      }),\n      M.when(M.instanceOf(Uint16Array), (_) => {\n        return \"uint16\"\n      }),\n      M.orElse((_) => {\n        throw \"absurd\"\n      })\n    )\n\n    strictEqual(match(new Uint8Array([1, 2, 3])), \"uint8\")\n    strictEqual(match(new Uint16Array([1, 2, 3])), \"uint16\")\n  })\n\n  it(\"tags\", () => {\n    const match = pipe(\n      M.type<{ _tag: \"A\"; a: number } | { _tag: \"B\"; b: number }>(),\n      M.tags({\n        A: (_) => _.a,\n        B: (_) => \"B\"\n      }),\n      M.exhaustive\n    )\n\n    strictEqual(match({ _tag: \"A\", a: 1 }), 1)\n    strictEqual(match({ _tag: \"B\", b: 1 }), \"B\")\n  })\n\n  it(\"tagsExhaustive\", () => {\n    const match = pipe(\n      M.type<{ _tag: \"A\"; a: number } | { _tag: \"B\"; b: number }>(),\n      M.tagsExhaustive({\n        A: (_) => _.a,\n        B: (_) => \"B\"\n      })\n    )\n\n    strictEqual(match({ _tag: \"A\", a: 1 }), 1)\n    strictEqual(match({ _tag: \"B\", b: 1 }), \"B\")\n  })\n\n  it(\"valueTags\", () => {\n    type Value = { _tag: \"A\"; a: number } | { _tag: \"B\"; b: number }\n    const match = pipe(\n      { _tag: \"A\", a: 123 } as Value,\n      M.valueTags({\n        A: (_) => _.a,\n        B: (_) => \"B\"\n      })\n    )\n\n    strictEqual(match, 123)\n  })\n\n  it(\"typeTags\", () => {\n    type Value = { _tag: \"A\"; a: number } | { _tag: \"B\"; b: number }\n    const matcher = M.typeTags<Value>()\n\n    strictEqual(\n      matcher({\n        A: (_) => _.a,\n        B: (_) => \"fail\"\n      })({ _tag: \"A\", a: 123 }),\n      123\n    )\n\n    strictEqual(\n      matcher({\n        A: (_) => _.a,\n        B: (_) => \"B\"\n      })({ _tag: \"B\", b: 123 }),\n      \"B\"\n    )\n  })\n\n  it(\"refinement - with unknown\", () => {\n    const isArray = (_: unknown): _ is ReadonlyArray<unknown> => Array.isArray(_)\n\n    const match = pipe(\n      M.type<string | Array<number>>(),\n      M.when(isArray, (_) => {\n        return \"array\"\n      }),\n      M.when(Predicate.isString, () => \"string\"),\n      M.exhaustive\n    )\n\n    strictEqual(match([]), \"array\")\n    strictEqual(match(\"fail\"), \"string\")\n  })\n\n  it(\"refinement nested - with unknown\", () => {\n    const isArray = (_: unknown): _ is ReadonlyArray<unknown> => Array.isArray(_)\n\n    const match = pipe(\n      M.type<{ readonly a: string | Array<number> }>(),\n      M.when({ a: isArray }, (_) => \"array\"),\n      M.orElse(() => \"fail\")\n    )\n\n    strictEqual(match({ a: [123] }), \"array\")\n    strictEqual(match({ a: \"fail\" }), \"fail\")\n  })\n\n  it(\"unknown - refinement\", () => {\n    const match = pipe(\n      M.type<unknown>(),\n      M.when(Predicate.isReadonlyRecord, (_) => \"record\"),\n      M.orElse(() => \"unknown\")\n    )\n\n    strictEqual(match({}), \"record\")\n    strictEqual(match([]), \"unknown\")\n  })\n\n  it(\"any - refinement\", () => {\n    const match = pipe(\n      M.type<any>(),\n      M.when(Predicate.isReadonlyRecord, (_) => \"record\"),\n      M.orElse(() => \"unknown\")\n    )\n\n    strictEqual(match({}), \"record\")\n    strictEqual(match([]), \"unknown\")\n  })\n\n  it(\"discriminatorStartsWith\", () => {\n    const match = pipe(\n      M.type<{ type: \"A\" } | { type: \"B\" } | { type: \"A.A\" } | {}>(),\n      M.discriminatorStartsWith(\"type\")(\"A\", (_) => 1 as const),\n      M.discriminatorStartsWith(\"type\")(\"B\", (_) => 2 as const),\n      M.orElse((_) => 3 as const)\n    )\n    strictEqual(match({ type: \"A\" }), 1)\n    strictEqual(match({ type: \"A.A\" }), 1)\n    strictEqual(match({ type: \"B\" }), 2)\n    strictEqual(match({}), 3)\n  })\n\n  it(\"symbol\", () => {\n    const match = pipe(\n      M.type<unknown>(),\n      M.when(M.symbol, (_) => \"symbol\"),\n      M.orElse(() => \"else\")\n    )\n    strictEqual(match(Symbol.for(\"a\")), \"symbol\")\n    strictEqual(match(123), \"else\")\n  })\n\n  it(\"withReturnType\", () => {\n    const match = pipe(\n      M.type<string>(),\n      M.withReturnType<string>(),\n      M.when(\"A\", (_) => \"A\"),\n      M.orElse(() => \"else\")\n    )\n    strictEqual(match(\"A\"), \"A\")\n    strictEqual(match(\"a\"), \"else\")\n  })\n\n  it(\"withReturnType after predicate\", () => {\n    const match = pipe(\n      M.type<string>(),\n      M.when(\"A\", (_) => \"A\"),\n      M.withReturnType<string>(),\n      M.orElse(() => \"else\")\n    )\n    strictEqual(match(\"A\"), \"A\")\n    strictEqual(match(\"a\"), \"else\")\n  })\n\n  it(\"withReturnType mismatch\", () => {\n    const match = pipe(\n      M.type<string>(),\n      M.withReturnType<string>(),\n      // @ts-expect-error\n      M.when(\"A\", (_) => 123),\n      M.orElse(() => \"else\")\n    )\n    // @ts-expect-error\n    strictEqual(match(\"A\"), 123)\n    strictEqual(match(\"a\"), \"else\")\n  })\n\n  it(\"withReturnType constraint mismatch\", () => {\n    pipe(\n      M.type<string>(),\n      M.when(\"A\", (_) => 123),\n      M.withReturnType<string>(),\n      // @ts-expect-error\n      M.orElse(() => \"else\")\n    )\n  })\n\n  it(\"withReturnType union\", () => {\n    const match = pipe(\n      M.type<string>(),\n      M.withReturnType<\"a\" | \"b\">(),\n      M.when(\"A\", (_) => \"a\"),\n      M.orElse((_) => \"b\")\n    )\n    strictEqual(match(\"A\"), \"a\")\n    strictEqual(match(\"a\"), \"b\")\n  })\n\n  it(\"withReturnType union mismatch\", () => {\n    pipe(\n      M.type<string>(),\n      M.withReturnType<\"a\" | \"b\">(),\n      M.when(\"A\", (_) => \"a\"),\n      // @ts-expect-error\n      M.orElse((_) => \"c\")\n    )\n  })\n\n  it(\"nonEmptyString\", () => {\n    const match = M.type<string | number>().pipe(\n      M.when(M.nonEmptyString, () => \"ok\"),\n      M.orElse(() => \"empty\")\n    )\n\n    strictEqual(match(\"hello\"), \"ok\")\n    strictEqual(match(\"\"), \"empty\")\n  })\n\n  it(\"is\", () => {\n    const match = M.type<string>().pipe(\n      M.when(M.is(\"A\"), () => \"ok\"),\n      M.orElse(() => \"ko\")\n    )\n\n    strictEqual(match(\"A\"), \"ok\")\n    strictEqual(match(\"C\"), \"ko\")\n  })\n\n  it(\"orElseAbsurd should throw if a match is not found\", () => {\n    const match = M.type<string>().pipe(\n      M.when(M.is(\"A\", \"B\"), () => \"ok\"),\n      M.orElseAbsurd\n    )\n    strictEqual(match(\"A\"), \"ok\")\n    strictEqual(match(\"B\"), \"ok\")\n    throws(() => match(\"C\"), new Error(\"effect/Match/orElseAbsurd: absurd\"))\n  })\n\n  it(\"option (with M.value) should return None if a match is not found\", () => {\n    const result = M.value(\"C\").pipe(\n      M.when(M.is(\"A\", \"B\"), () => \"ok\"),\n      M.option\n    )\n    assertNone(result)\n  })\n\n  it(\"exhaustive should throw on invalid inputs\", () => {\n    const match = M.type<\"A\">().pipe(\n      M.when(M.is(\"A\"), () => \"ok\"),\n      M.exhaustive\n    )\n\n    throws(() => match(\"C\" as \"A\"))\n\n    throws(() =>\n      M.value(\"C\" as \"A\").pipe(\n        M.when(M.is(\"A\"), () => \"ok\"),\n        M.exhaustive\n      )\n    )\n  })\n\n  it(\"orElse (with M.value) should return the default if a match is not found\", () => {\n    const result = M.value(\"C\").pipe(\n      M.when(M.is(\"A\", \"B\"), () => \"ok\"),\n      M.orElse(() => \"default\")\n    )\n    strictEqual(result, \"default\")\n  })\n\n  it(\"tag + withReturnType doesn't need as const for string literals\", () => {\n    type Value = { _tag: \"A\"; a: number } | { _tag: \"B\"; b: number }\n    const result = M.value<Value>({ _tag: \"A\", a: 1 }).pipe(\n      M.withReturnType<\"a\" | \"b\">(),\n      M.tag(\"A\", () => \"a\"),\n      M.tag(\"B\", () => \"b\"),\n      M.exhaustive\n    )\n    strictEqual(result, \"a\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Metric.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport {\n  Array,\n  Clock,\n  Duration,\n  Effect,\n  Equal,\n  Fiber,\n  Metric,\n  MetricBoundaries,\n  MetricKey,\n  MetricLabel,\n  MetricPolling,\n  MetricState,\n  Option,\n  pipe,\n  Schedule\n} from \"effect\"\n\nconst labels = [MetricLabel.make(\"x\", \"a\"), MetricLabel.make(\"y\", \"b\")]\n\nconst makePollingGauge = (name: string, increment: number) => {\n  const gauge = Metric.gauge(name)\n  const metric = MetricPolling.make(gauge, Metric.value(gauge).pipe(Effect.map((gauge) => gauge.value + increment)))\n  return [gauge, metric] as const\n}\n\nlet nameCount = 0\nconst nextName = () => `m${++nameCount}`\n\ndescribe(\"Metric\", () => {\n  describe(\"Counter\", () => {\n    it.effect(\"custom increment as aspect\", () =>\n      Effect.gen(function*() {\n        const id = nextName()\n        const counter = Metric.counter(id).pipe(Metric.taggedWithLabels(labels), Metric.withConstantInput(1))\n        const result = yield* counter(Effect.void).pipe(\n          Effect.zipRight(counter(Effect.void)),\n          Effect.zipRight(Metric.value(counter))\n        )\n        deepStrictEqual(result, MetricState.counter(2))\n      }))\n    it.effect(\"direct increment\", () =>\n      Effect.gen(function*() {\n        const id = nextName()\n        const counter = Metric.counter(id).pipe(Metric.taggedWithLabels(labels))\n        const result = yield* Metric.increment(counter).pipe(\n          Effect.zipRight(Metric.increment(counter)),\n          Effect.zipRight(Metric.value(counter))\n        )\n        deepStrictEqual(result, MetricState.counter(2))\n      }))\n\n    it.effect(\"direct increment bigint\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const counter = Metric.counter(name, {\n          bigint: true\n        }).pipe(Metric.taggedWithLabels(labels))\n        const result = yield* Metric.increment(counter).pipe(\n          Effect.zipRight(Metric.increment(counter)),\n          Effect.zipRight(Metric.value(counter))\n        )\n        deepStrictEqual(result, MetricState.counter(BigInt(2)))\n      }))\n\n    it.effect(\"cannot decrement incremental\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const counter = Metric.counter(name, { incremental: true }).pipe(Metric.taggedWithLabels(labels))\n        const result = yield* Metric.increment(counter).pipe(\n          Effect.zipRight(Metric.increment(counter)),\n          Effect.zipRight(Metric.incrementBy(counter, -1)),\n          Effect.zipRight(Metric.value(counter))\n        )\n        deepStrictEqual(result, MetricState.counter(2))\n      }))\n\n    it.effect(\"cannot decrement incremental bigint\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const counter = Metric.counter(name, {\n          incremental: true,\n          bigint: true\n        }).pipe(Metric.taggedWithLabels(labels))\n        const result = yield* Metric.increment(counter).pipe(\n          Effect.zipRight(Metric.increment(counter)),\n          Effect.zipRight(Metric.incrementBy(counter, BigInt(-1))),\n          Effect.zipRight(Metric.value(counter))\n        )\n        deepStrictEqual(result, MetricState.counter(BigInt(2)))\n      }))\n\n    it.effect(\"custom increment by value as aspect\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const counter = Metric.counter(name).pipe(Metric.taggedWithLabels(labels))\n        const result = yield* counter(Effect.succeed(10)).pipe(\n          Effect.zipRight(counter(Effect.succeed(5))),\n          Effect.zipRight(Metric.value(counter))\n        )\n        deepStrictEqual(result, MetricState.counter(15))\n      }))\n\n    it.effect(\"custom increment by bigint value as aspect\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const counter = Metric.counter(name, { bigint: true }).pipe(Metric.taggedWithLabels(labels))\n        const result = yield* counter(Effect.succeed(BigInt(10))).pipe(\n          Effect.zipRight(counter(Effect.succeed(BigInt(5)))),\n          Effect.zipRight(Metric.value(counter))\n        )\n        deepStrictEqual(result, MetricState.counter(BigInt(15)))\n      }))\n\n    it.effect(\"direct increment referential transparency\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const result = yield* pipe(\n          Effect.void,\n          Effect.withMetric(\n            Metric.counter(name).pipe(\n              Metric.taggedWithLabels(labels),\n              Metric.withConstantInput(1)\n            )\n          ),\n          Effect.zipRight(\n            pipe(\n              Effect.void,\n              Effect.withMetric(pipe(\n                Metric.counter(name),\n                Metric.taggedWithLabels(labels),\n                Metric.withConstantInput(1)\n              ))\n            )\n          ),\n          Effect.zipRight(pipe(\n            Metric.counter(name),\n            Metric.taggedWithLabels(labels),\n            Metric.withConstantInput(1),\n            Metric.value\n          ))\n        )\n        deepStrictEqual(result, MetricState.counter(2))\n      }))\n    it.effect(\"custom increment referential transparency\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const result = yield* pipe(\n          Effect.succeed(10),\n          Effect.withMetric(pipe(Metric.counter(name), Metric.taggedWithLabels(labels))),\n          Effect.zipRight(\n            pipe(Effect.succeed(5), Effect.withMetric(pipe(Metric.counter(name), Metric.taggedWithLabels(labels))))\n          ),\n          Effect.zipRight(pipe(Metric.counter(name), Metric.taggedWithLabels(labels), Metric.value))\n        )\n        deepStrictEqual(result, MetricState.counter(15))\n      }))\n    it.effect(\"custom increment with mapInput\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const result = yield* pipe(\n          Effect.succeed(\"hello\"),\n          Effect.withMetric(\n            pipe(\n              Metric.counter(name),\n              Metric.taggedWithLabels(labels),\n              Metric.mapInput((input: string) => input.length)\n            )\n          ),\n          Effect.zipRight(\n            pipe(\n              Effect.succeed(\"!\"),\n              Effect.withMetric(\n                pipe(\n                  Metric.counter(name),\n                  Metric.taggedWithLabels(labels),\n                  Metric.mapInput((input: string) => input.length)\n                )\n              )\n            )\n          ),\n          Effect.zipRight(pipe(Metric.counter(name), Metric.taggedWithLabels(labels), Metric.value))\n        )\n        deepStrictEqual(result, MetricState.counter(6))\n      }))\n    it.effect(\"does not count errors\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const counter = pipe(Metric.counter(name), Metric.withConstantInput(1))\n        const result = yield* pipe(\n          Effect.void,\n          Effect.withMetric(counter),\n          Effect.zipRight(pipe(Effect.fail(\"error\"), Effect.withMetric(counter), Effect.ignore)),\n          Effect.zipRight(Metric.value(counter))\n        )\n        deepStrictEqual(result, MetricState.counter(1))\n      }))\n    it.effect(\"count + taggedWith\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const base = pipe(Metric.counter(name), Metric.tagged(\"static\", \"0\"), Metric.withConstantInput(1))\n        const counter = pipe(\n          base,\n          Metric.taggedWithLabelsInput((input: string) => [MetricLabel.make(\"dyn\", input)])\n        )\n        const result = yield* pipe(\n          Effect.succeed(\"hello\"),\n          Effect.withMetric(counter),\n          Effect.zipRight(pipe(Effect.succeed(\"!\"), Effect.withMetric(counter))),\n          Effect.zipRight(pipe(Effect.succeed(\"!\"), Effect.withMetric(counter))),\n          Effect.zipRight(pipe(base, Metric.tagged(\"dyn\", \"!\"), Metric.value))\n        )\n        deepStrictEqual(result, MetricState.counter(2))\n      }))\n    it.effect(\"tags are a region setting\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const counter = Metric.counter(name)\n        const result = yield* pipe(\n          Metric.increment(counter),\n          Effect.tagMetrics({ key: \"value\" }),\n          Effect.zipRight(\n            pipe(\n              counter,\n              Metric.tagged(\"key\", \"value\"),\n              Metric.value\n            )\n          )\n        )\n        deepStrictEqual(result, MetricState.counter(1))\n      }))\n  })\n  describe(\"Frequency\", () => {\n    it.effect(\"custom occurrences as aspect\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const frequency = pipe(Metric.frequency(name), Metric.taggedWithLabels(labels))\n        const result = yield* pipe(\n          Effect.succeed(\"hello\"),\n          Effect.withMetric(frequency),\n          Effect.zipRight(pipe(Effect.succeed(\"hello\"), Effect.withMetric(frequency))),\n          Effect.zipRight(pipe(Effect.succeed(\"world\"), Effect.withMetric(frequency))),\n          Effect.zipRight(Metric.value(frequency))\n        )\n        deepStrictEqual(result.occurrences, new Map([[\"hello\", 2] as const, [\"world\", 1] as const]))\n      }))\n    it.effect(\"direct occurrences\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const frequency = pipe(Metric.frequency(name), Metric.taggedWithLabels(labels))\n        const result = yield* pipe(\n          frequency,\n          Metric.update(\"hello\"),\n          Effect.zipRight(pipe(frequency, Metric.update(\"hello\"))),\n          Effect.zipRight(pipe(frequency, Metric.update(\"world\"))),\n          Effect.zipRight(Metric.value(frequency))\n        )\n        deepStrictEqual(result.occurrences, new Map([[\"hello\", 2] as const, [\"world\", 1] as const]))\n      }))\n    it.effect(\"custom occurrences with mapInput\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const frequency = pipe(\n          Metric.frequency(name),\n          Metric.taggedWithLabels(labels),\n          Metric.mapInput((n: number) => `${n}`)\n        )\n        const result = yield* pipe(\n          Effect.succeed(1),\n          Effect.withMetric(frequency),\n          Effect.zipRight(pipe(Effect.succeed(1), Effect.withMetric(frequency))),\n          Effect.zipRight(pipe(Effect.succeed(2), Effect.withMetric(frequency))),\n          Effect.zipRight(Metric.value(frequency))\n        )\n        deepStrictEqual(result.occurrences, new Map([[\"1\", 2] as const, [\"2\", 1] as const]))\n      }))\n    it.effect(\"occurences + taggedWith\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const base = pipe(Metric.frequency(name), Metric.taggedWithLabels(labels))\n        const frequency = pipe(\n          base,\n          Metric.taggedWithLabelsInput((s: string) => [MetricLabel.make(\"dyn\", s)])\n        )\n        const { result1, result2, result3 } = yield* pipe(\n          Effect.succeed(\"hello\"),\n          Effect.withMetric(frequency),\n          Effect.zipRight(pipe(Effect.succeed(\"hello\"), Effect.withMetric(frequency))),\n          Effect.zipRight(pipe(Effect.succeed(\"world\"), Effect.withMetric(frequency))),\n          Effect.zipRight(Effect.all({\n            result1: Metric.value(base),\n            result2: pipe(base, Metric.tagged(\"dyn\", \"hello\"), Metric.value),\n            result3: pipe(base, Metric.tagged(\"dyn\", \"world\"), Metric.value)\n          }))\n        )\n        strictEqual(result1.occurrences.size, 0)\n        deepStrictEqual(result2.occurrences, new Map([[\"hello\", 2] as const]))\n        deepStrictEqual(result3.occurrences, new Map([[\"world\", 1] as const]))\n      }))\n  })\n  describe(\"Gauge\", () => {\n    it.effect(\"custom set as aspect\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const gauge = pipe(Metric.gauge(name), Metric.taggedWithLabels(labels))\n        const result = yield* pipe(\n          Effect.succeed(1),\n          Effect.withMetric(gauge),\n          Effect.zipRight(pipe(Effect.succeed(3), Effect.withMetric(gauge))),\n          Effect.zipRight(Metric.value(gauge))\n        )\n        deepStrictEqual(result, MetricState.gauge(3))\n      }))\n    it.effect(\"direct set\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const gauge = pipe(Metric.gauge(name), Metric.taggedWithLabels(labels))\n        const result = yield* pipe(\n          gauge,\n          Metric.set(1),\n          Effect.zipRight(pipe(gauge, Metric.set(3))),\n          Effect.zipRight(Metric.value(gauge))\n        )\n        deepStrictEqual(result, MetricState.gauge(3))\n      }))\n    it.effect(\"increment\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const gauge = pipe(Metric.gauge(name), Metric.taggedWithLabels(labels))\n        yield* Effect.forEach(Array.range(0, 99), () => Metric.increment(gauge), { concurrency: \"unbounded\" })\n        const result = yield* Metric.value(gauge)\n        deepStrictEqual(result, MetricState.gauge(100))\n      }))\n    it.effect(\"custom set with mapInput\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const gauge = pipe(Metric.gauge(name), Metric.taggedWithLabels(labels), Metric.mapInput((n: number) => n * 2))\n        const result = yield* pipe(\n          Effect.succeed(1),\n          Effect.withMetric(gauge),\n          Effect.zipRight(pipe(Effect.succeed(3), Effect.withMetric(gauge))),\n          Effect.zipRight(Metric.value(gauge))\n        )\n        deepStrictEqual(result, MetricState.gauge(6))\n      }))\n    it.effect(\"gauge + taggedWith\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const base = pipe(Metric.gauge(name), Metric.tagged(\"static\", \"0\"), Metric.mapInput((s: string) => s.length))\n        const gauge = pipe(\n          base,\n          Metric.taggedWithLabelsInput((input: string) => [MetricLabel.make(\"dyn\", input)])\n        )\n        const result = yield* pipe(\n          Effect.succeed(\"hello\"),\n          Effect.withMetric(gauge),\n          Effect.zipRight(pipe(Effect.succeed(\"!\"), Effect.withMetric(gauge))),\n          Effect.zipRight(pipe(Effect.succeed(\"!\"), Effect.withMetric(gauge))),\n          Effect.zipRight(pipe(base, Metric.tagged(\"dyn\", \"!\"), Metric.value))\n        )\n        deepStrictEqual(result, MetricState.gauge(1))\n      }))\n  })\n  describe(\"Histogram\", () => {\n    it.effect(\"custom observe as aspect\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const boundaries = MetricBoundaries.linear({ start: 0, width: 1, count: 10 })\n        const histogram = pipe(Metric.histogram(name, boundaries), Metric.taggedWithLabels(labels))\n        const result = yield* pipe(\n          Effect.succeed(1),\n          Effect.withMetric(histogram),\n          Effect.zipRight(pipe(Effect.succeed(3), Effect.withMetric(histogram))),\n          Effect.zipRight(Metric.value(histogram))\n        )\n        strictEqual(result.count, 2)\n        strictEqual(result.sum, 4)\n        strictEqual(result.min, 1)\n        strictEqual(result.max, 3)\n      }))\n\n    it.effect(\"direct observe\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const boundaries = MetricBoundaries.linear({ start: 0, width: 1, count: 10 })\n        const histogram = pipe(Metric.histogram(name, boundaries), Metric.taggedWithLabels(labels))\n        const result = yield* pipe(\n          histogram,\n          Metric.update(1),\n          Effect.zipRight(pipe(histogram, Metric.update(3))),\n          Effect.zipRight(Metric.value(histogram))\n        )\n        strictEqual(result.count, 2)\n        strictEqual(result.sum, 4)\n        strictEqual(result.min, 1)\n        strictEqual(result.max, 3)\n      }))\n\n    it.live(\"histogram with sleeps\", () =>\n      it.flakyTest(\n        Effect.gen(function*() {\n          const name = nextName()\n          const boundaries = MetricBoundaries.linear({ start: 0, width: 1, count: 10 })\n          const histogram = pipe(\n            Metric.histogram(name, boundaries),\n            Metric.taggedWithLabels(labels),\n            Metric.mapInput((duration: Duration.Duration) => Duration.toMillis(duration) / 1000)\n          )\n          // NOTE: trackDuration always uses the **real** Clock\n          const start = yield* Effect.sync(() => Date.now())\n          yield* pipe(Effect.sleep(Duration.millis(100)), Metric.trackDuration(histogram))\n          yield* pipe(Effect.sleep(Duration.millis(300)), Metric.trackDuration(histogram))\n          const end = yield* Effect.sync(() => Date.now())\n          const elapsed = end - start\n          const result = yield* Metric.value(histogram)\n          strictEqual(result.count, 2)\n          assertTrue(result.sum > 0.39)\n          assertTrue(result.sum <= elapsed)\n          assertTrue(result.min >= 0.1)\n          assertTrue(result.min < result.max)\n          assertTrue(result.max >= 0.3)\n          assertTrue(result.max < elapsed)\n        })\n      ))\n\n    it.effect(\"custom observe with mapInput\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const boundaries = MetricBoundaries.linear({ start: 0, width: 1, count: 10 })\n        const histogram = pipe(\n          Metric.histogram(name, boundaries),\n          Metric.taggedWithLabels(labels),\n          Metric.mapInput((s: string) => s.length)\n        )\n        const result = yield* pipe(\n          Effect.succeed(\"x\"),\n          Effect.withMetric(histogram),\n          Effect.zipRight(pipe(Effect.succeed(\"xyz\"), Effect.withMetric(histogram))),\n          Effect.zipRight(Metric.value(histogram))\n        )\n        strictEqual(result.count, 2)\n        strictEqual(result.sum, 4)\n        strictEqual(result.min, 1)\n        strictEqual(result.max, 3)\n      }))\n\n    it.effect(\"observe + taggedWith\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const boundaries = MetricBoundaries.linear({ start: 0, width: 1, count: 10 })\n        const base = pipe(\n          Metric.histogram(name, boundaries),\n          Metric.taggedWithLabels(labels),\n          Metric.mapInput((s: string) => s.length)\n        )\n        const histogram = base.pipe(\n          Metric.taggedWithLabelsInput((input: string) => [MetricLabel.make(\"dyn\", input)])\n        )\n        const { result1, result2, result3 } = yield* pipe(\n          Effect.succeed(\"x\"),\n          Effect.withMetric(histogram),\n          Effect.zipRight(pipe(Effect.succeed(\"xyz\"), Effect.withMetric(histogram))),\n          Effect.zipRight(Effect.all({\n            result1: Metric.value(base),\n            result2: pipe(base, Metric.tagged(\"dyn\", \"x\"), Metric.value),\n            result3: pipe(base, Metric.tagged(\"dyn\", \"xyz\"), Metric.value)\n          }))\n        )\n        strictEqual(result1.count, 0)\n        strictEqual(result2.count, 1)\n        strictEqual(result3.count, 1)\n      }))\n\n    it.effect(\"preserves precision of boundary values\", () =>\n      Effect.gen(function*() {\n        const preciseBoundaries = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1]\n\n        const histogram = Metric.histogram(\n          \"precision_test\",\n          MetricBoundaries.fromIterable(preciseBoundaries)\n        )\n\n        const result = yield* Metric.value(histogram)\n\n        result.buckets.forEach(([boundary], index) => {\n          if (index < preciseBoundaries.length) {\n            strictEqual(boundary, preciseBoundaries[index])\n          }\n        })\n      }))\n  })\n\n  describe(\"Summary\", () => {\n    it.effect(\"custom observe as aspect\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const summary = Metric.summary({\n          name,\n          maxAge: Duration.minutes(1),\n          maxSize: 10,\n          error: 0,\n          quantiles: [0.25, 0.5, 0.75]\n        }).pipe(\n          Metric.taggedWithLabels(labels)\n        )\n        const result = yield* pipe(\n          Effect.succeed(1),\n          Effect.withMetric(summary),\n          Effect.zipRight(pipe(Effect.succeed(3), Effect.withMetric(summary))),\n          Effect.zipRight(Metric.value(summary))\n        )\n        strictEqual(result.count, 2)\n        strictEqual(result.sum, 4)\n        strictEqual(result.min, 1)\n        strictEqual(result.max, 3)\n        const medianQuantileValue = result.quantiles[1][1]\n        strictEqual(Option.getOrNull(medianQuantileValue), 1)\n      }))\n    it.effect(\"direct observe\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const summary = Metric.summary({\n          name,\n          maxAge: Duration.minutes(1),\n          maxSize: 10,\n          error: 0,\n          quantiles: [0.25, 0.5, 0.75]\n        }).pipe(\n          Metric.taggedWithLabels(labels)\n        )\n        const result = yield* pipe(\n          summary,\n          Metric.update(1),\n          Effect.zipRight(pipe(summary, Metric.update(3))),\n          Effect.zipRight(Metric.value(summary))\n        )\n        strictEqual(result.count, 2)\n        strictEqual(result.sum, 4)\n        strictEqual(result.min, 1)\n        strictEqual(result.max, 3)\n        const medianQuantileValue = result.quantiles[1][1]\n        strictEqual(Option.getOrNull(medianQuantileValue), 1)\n      }))\n    it.effect(\"custom observe with mapInput\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const summary = Metric.summary({\n          name,\n          maxAge: Duration.minutes(1),\n          maxSize: 10,\n          error: 0,\n          quantiles: [0.25, 0.5, 0.75]\n        }).pipe(\n          Metric.taggedWithLabels(labels),\n          Metric.mapInput((s: string) => s.length)\n        )\n        const result = yield* pipe(\n          Effect.succeed(\"x\"),\n          Effect.withMetric(summary),\n          Effect.zipRight(pipe(Effect.succeed(\"xyz\"), Effect.withMetric(summary))),\n          Effect.zipRight(Metric.value(summary))\n        )\n        strictEqual(result.count, 2)\n        strictEqual(result.sum, 4)\n        strictEqual(result.min, 1)\n        strictEqual(result.max, 3)\n        const medianQuantileValue = result.quantiles[1][1]\n        strictEqual(Option.getOrNull(medianQuantileValue), 1)\n      }))\n    it.effect(\"observeSummaryWith + taggedWith\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const base = Metric.summary({\n          name,\n          maxAge: Duration.minutes(1),\n          maxSize: 10,\n          error: 0,\n          quantiles: [0.25, 0.5, 0.75]\n        }).pipe(\n          Metric.taggedWithLabels(labels),\n          Metric.mapInput((s: string) => s.length)\n        )\n        const summary = base.pipe(\n          Metric.taggedWithLabelsInput((input: string) => [MetricLabel.make(\"dyn\", input)])\n        )\n        const { result1, result2, result3 } = yield* pipe(\n          Effect.succeed(\"x\"),\n          Effect.withMetric(summary),\n          Effect.zipRight(pipe(Effect.succeed(\"xyz\"), Effect.withMetric(summary))),\n          Effect.zipRight(Effect.all({\n            result1: Metric.value(base),\n            result2: pipe(base, Metric.tagged(\"dyn\", \"x\"), Metric.value),\n            result3: pipe(base, Metric.tagged(\"dyn\", \"xyz\"), Metric.value)\n          }))\n        )\n        strictEqual(result1.count, 0)\n        strictEqual(result2.count, 1)\n        strictEqual(result3.count, 1)\n      }))\n    it.effect(\"should return correct quantile when first chunk overshoots\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        // Samples: [10 (x6), 20, 30, 40, 50] (10 samples)\n        // Target rank for 0.5 quantile = 0.5 * 10 = 5\n        // Allowed error = (0.01 / 2) * 5 = 0.025. Range [4.975, 5.025]\n        // First chunk: 6 * 10. candConsumed = 6. 6 > 5.025\n        const samples = [10, 10, 10, 10, 10, 10, 20, 30, 40, 50]\n        const summary = Metric.summary({\n          name,\n          maxAge: Duration.minutes(1),\n          maxSize: 15,\n          error: 0.01,\n          quantiles: [0.5]\n        })\n\n        yield* Effect.forEach(samples, (value) => Metric.update(summary, value), { discard: true })\n\n        const result = yield* Metric.value(summary)\n\n        const medianQuantileValue = result.quantiles[0][1]\n\n        strictEqual(Option.getOrNull(medianQuantileValue), 10)\n      }))\n    it.effect(\"should return no values when no samples are present\", () =>\n      Effect.gen(function*() {\n        const name = nextName()\n        const summary = Metric.summary({\n          name,\n          maxAge: Duration.minutes(1),\n          maxSize: 15,\n          error: 0.01,\n          quantiles: [0.5]\n        })\n\n        const result = yield* Metric.value(summary)\n\n        const medianQuantileValue = result.quantiles[0][1]\n        const minValue = result.min\n        const maxValue = result.max\n        const countValue = result.count\n        const sumValue = result.sum\n\n        strictEqual(Option.isNone(medianQuantileValue), true)\n        strictEqual(minValue, 0)\n        strictEqual(maxValue, 0)\n        strictEqual(countValue, 0)\n        strictEqual(sumValue, 0)\n      }))\n  })\n  describe(\"Polling\", () => {\n    it.scopedLive(\"launch should be interruptible\", () =>\n      Effect.gen(function*() {\n        const name = yield* pipe(Clock.currentTimeMillis, Effect.map((now) => `gauge-${now}`))\n        const [gauge, metric] = makePollingGauge(name, 1)\n        const schedule = pipe(Schedule.forever, Schedule.delayed(() => Duration.millis(250)))\n        const fiber = yield* pipe(metric, MetricPolling.launch(schedule))\n        yield* Fiber.interrupt(fiber)\n        const result = yield* Metric.value(gauge)\n        strictEqual(result.value, 0)\n      }))\n    it.scoped(\"launch should update the internal metric using the provided Schedule\", () =>\n      Effect.gen(function*() {\n        const name = yield* pipe(Clock.currentTimeMillis, Effect.map((now) => `gauge-${now}`))\n        const [gauge, metric] = makePollingGauge(name, 1)\n        const fiber = yield* pipe(metric, MetricPolling.launch(Schedule.once))\n        yield* Fiber.join(fiber)\n        const result = yield* Metric.value(gauge)\n        strictEqual(result.value, 1)\n      }))\n    it.scoped(\"collectAll should generate a metric that polls all the provided metrics\", () =>\n      Effect.gen(function*() {\n        const gaugeIncrement1 = 1\n        const gaugeIncrement2 = 2\n        const pollingCount = 2\n        const name1 = yield* pipe(Clock.currentTimeMillis, Effect.map((now) => `gauge1-${now}`))\n        const name2 = yield* pipe(Clock.currentTimeMillis, Effect.map((now) => `gauge2-${now}`))\n        const [gauge1, metric1] = makePollingGauge(name1, gaugeIncrement1)\n        const [gauge2, metric2] = makePollingGauge(name2, gaugeIncrement2)\n        const metric = MetricPolling.collectAll([metric1, metric2])\n        const fiber = yield* pipe(metric, MetricPolling.launch(Schedule.recurs(pollingCount)))\n        yield* Fiber.join(fiber)\n        const result1 = yield* Metric.value(gauge1)\n        const result2 = yield* Metric.value(gauge2)\n        strictEqual(result1.value, gaugeIncrement1 * pollingCount)\n        strictEqual(result2.value, gaugeIncrement2 * pollingCount)\n      }))\n  })\n\n  it.effect(\"with a description\", () =>\n    Effect.gen(function*() {\n      const name = \"counterName\"\n      const counter1 = Metric.counter(name)\n      const counter2 = Metric.counter(name, { description: \"description1\" })\n      const counter3 = Metric.counter(name, { description: \"description2\" })\n\n      yield* (Metric.update(counter1, 1))\n      yield* (Metric.update(counter2, 1))\n      yield* (Metric.update(counter3, 1))\n\n      const result1 = yield* (Metric.value(counter1))\n      const result2 = yield* (Metric.value(counter2))\n      const result3 = yield* (Metric.value(counter3))\n\n      const snapshot = yield* (Metric.snapshot)\n      const pair1 = yield* (\n        Array.findFirst(snapshot, (key) => Equal.equals(key.metricKey, MetricKey.counter(name)))\n      )\n      const pair2 = yield* (\n        Array.findFirst(snapshot, (key) =>\n          Equal.equals(\n            key.metricKey,\n            MetricKey.counter(name, {\n              description: \"description1\"\n            })\n          ))\n      )\n      const pair3 = yield* (\n        Array.findFirst(snapshot, (key) =>\n          Equal.equals(\n            key.metricKey,\n            MetricKey.counter(name, {\n              description: \"description2\"\n            })\n          ))\n      )\n\n      assertTrue(Equal.equals(result1, MetricState.counter(1)))\n      assertTrue(Equal.equals(result2, MetricState.counter(1)))\n      assertTrue(Equal.equals(result3, MetricState.counter(1)))\n      assertTrue(Equal.equals(pair1.metricState, MetricState.counter(1)))\n      assertTrue(Option.isNone(pair1.metricKey.description))\n      assertTrue(Equal.equals(pair2.metricState, MetricState.counter(1)))\n      assertTrue(Equal.equals(\n        pair2.metricKey,\n        MetricKey.counter(name, {\n          description: \"description1\"\n        })\n      ))\n      assertTrue(Equal.equals(pair3.metricState, MetricState.counter(1)))\n      assertTrue(Equal.equals(\n        pair3.metricKey,\n        MetricKey.counter(name, {\n          description: \"description2\"\n        })\n      ))\n    }))\n\n  it.effect(\".register()\", () =>\n    Effect.gen(function*() {\n      const id = nextName()\n      Metric.counter(id).register()\n      const snapshot = yield* (Metric.snapshot)\n      const value = pipe(\n        Array.fromIterable(snapshot),\n        Array.findFirst((_) => _.metricKey.name === id)\n      )\n      strictEqual(value._tag, \"Some\")\n    }))\n  describe(\"trackSuccessWith\", () => {\n    it.effect(\"infers types in Effectful pipes\", () => {\n      const counter = Metric.counter(\"counter\")\n      const frequency = Metric.frequency(\"frequency\")\n      const gauge = Metric.gauge(\"gauge\")\n      const histogram = Metric.histogram(\n        \"histogram\",\n        MetricBoundaries.linear({ start: 0, width: 10, count: 11 })\n      )\n      const summary = Metric.summary({\n        name: \"summary\",\n        maxAge: Duration.minutes(1),\n        maxSize: 10,\n        error: 0,\n        quantiles: [0.25, 0.5, 1]\n      })\n      return Effect.Do.pipe(\n        Effect.let(\"step1\", () => 1),\n        Metric.trackSuccessWith(counter, ({ step1 }) => step1),\n        Effect.let(\"someThingElse\", () => ({ a: 3 })),\n        Metric.trackSuccessWith(gauge, ({ step1 }) => step1),\n        Metric.trackSuccessWith(histogram, ({ step1 }) => step1),\n        Effect.let(\"anotherPartOfTheState\", () => ({ b: \"seven\" })),\n        Metric.trackSuccessWith(summary, ({ step1 }) => step1),\n        Effect.let(\"step2\", () => 4),\n        Effect.let(\"step3\", () => \"foo\"),\n        Metric.trackSuccessWith(counter, ({ step2 }) => step2),\n        Effect.let(\"irrelevant\", () => \"irrelevant\"),\n        Metric.trackSuccessWith(gauge, ({ step2 }) => step2),\n        Metric.trackSuccessWith(histogram, ({ step2 }) => step2),\n        Effect.let(\"moreIrrelevant\", () => \"moreIrrelevant\"),\n        Metric.trackSuccessWith(summary, ({ step2 }) => step2),\n        Effect.let(\"otherStuff\", () => ({ x: \"otherStuff\" })),\n        Metric.trackSuccessWith(frequency, ({ step3 }) => step3),\n        Effect.let(\"step4\", () => \"bar\"),\n        Metric.trackSuccessWith(frequency, ({ step4 }) => step4),\n        Effect.bind(\"results\", () =>\n          Effect.all({\n            counter: Metric.value(counter),\n            gauge: Metric.value(gauge),\n            histogram: Metric.value(histogram),\n            summary: Metric.value(summary),\n            frequency: Metric.value(frequency)\n          }))\n      ).pipe(\n        Effect.map(({ results }) => {\n          deepStrictEqual(results.counter, MetricState.counter(5))\n          deepStrictEqual(results.gauge, MetricState.gauge(4))\n          strictEqual(results.histogram.count, 2)\n          strictEqual(results.histogram.sum, 5)\n          strictEqual(results.histogram.min, 1)\n          strictEqual(results.histogram.max, 4)\n          strictEqual(results.summary.count, 2)\n          strictEqual(results.summary.sum, 5)\n          strictEqual(results.summary.min, 1)\n          strictEqual(results.summary.max, 4)\n          deepStrictEqual(results.summary.quantiles.map((x) => x[1]).map(Option.getOrNull), [1, 1, 4])\n          deepStrictEqual(\n            results.frequency.occurrences,\n            new Map([\n              [\"bar\", 1],\n              [\"foo\", 1]\n            ])\n          )\n        })\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Micro.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertInclude,\n  assertInstanceOf,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual\n} from \"@effect/vitest/utils\"\nimport { Cause, Context, Effect, Either, Exit, Fiber, Micro, Option, pipe } from \"effect\"\n\nclass ATag extends Context.Tag(\"ATag\")<ATag, \"A\">() {}\nclass TestError extends Micro.TaggedError(\"TestError\") {}\n\ndescribe.concurrent(\"Micro\", () => {\n  describe(\"tracing\", () => {\n    it.effect(\"Micro.TaggedError\", () =>\n      Micro.gen(function*() {\n        // Referenced line to be included in the string output\n        const error = yield* new TestError().pipe(Micro.flip)\n        deepStrictEqual(error, new TestError())\n        assertInclude(error.stack, \"Micro.test.ts:20\") // <= reference to the line above\n      }))\n\n    it.effect(\"withTrace\", () =>\n      Micro.gen(function*() {\n        const error = yield* Micro.fail(\"boom\").pipe(\n          // Referenced line to be included in the string output\n          Micro.withTrace(\"test trace\"),\n          Micro.sandbox,\n          Micro.flip\n        )\n        assertInclude(error.stack, \"at test trace\")\n        assertInclude(error.stack, \"Micro.test.ts:29\") // <= reference to the line above\n      }))\n  })\n\n  it(\"runPromise\", async () => {\n    const result = await Micro.runPromise(Micro.succeed(1))\n    strictEqual(result, 1)\n  })\n\n  it(\"acquireUseRelease interrupt\", async () => {\n    let acquire = false\n    let use = false\n    let release = false\n    const fiber = Micro.acquireUseRelease(\n      Micro.sync(() => {\n        acquire = true\n        return 123\n      }).pipe(Micro.delay(100)),\n      () =>\n        Micro.sync(() => {\n          use = true\n        }),\n      (_) =>\n        Micro.sync(() => {\n          strictEqual(_, 123)\n          release = true\n        })\n    ).pipe(Micro.runFork)\n    fiber.unsafeInterrupt()\n    const result = await Micro.runPromise(Micro.fiberAwait(fiber))\n    deepStrictEqual(result, Micro.exitInterrupt)\n    assertTrue(acquire)\n    assertFalse(use)\n    assertTrue(release)\n  })\n\n  it(\"acquireUseRelease uninterruptible\", async () => {\n    let acquire = false\n    let use = false\n    let release = false\n    const fiber = Micro.acquireUseRelease(\n      Micro.sync(() => {\n        acquire = true\n        return 123\n      }).pipe(Micro.delay(100)),\n      (_) =>\n        Micro.sync(() => {\n          use = true\n          return _\n        }),\n      (_) =>\n        Micro.sync(() => {\n          strictEqual(_, 123)\n          release = true\n        })\n    ).pipe(Micro.uninterruptible, Micro.runFork)\n    fiber.unsafeInterrupt()\n    const result = await Micro.runPromise(Micro.fiberAwait(fiber))\n    deepStrictEqual(result, Micro.exitInterrupt)\n    assertTrue(acquire)\n    assertTrue(use)\n    assertTrue(release)\n  })\n\n  it(\"Context.Tag\", () =>\n    Micro.service(ATag).pipe(\n      Micro.tap((_) => Micro.sync(() => strictEqual(_, \"A\"))),\n      Micro.provideService(ATag, \"A\"),\n      Micro.runPromise\n    ))\n\n  describe(\"fromOption\", () => {\n    it(\"from a some\", () =>\n      Option.some(\"A\").pipe(\n        Micro.fromOption,\n        Micro.tap((_) => strictEqual(_, \"A\")),\n        Micro.runPromise\n      ))\n\n    it(\"from a none\", () =>\n      Option.none().pipe(\n        Micro.fromOption,\n        Micro.flip,\n        Micro.tap((error) => assertInstanceOf(error, Micro.NoSuchElementException)),\n        Micro.runPromise\n      ))\n  })\n\n  describe(\"fromEither\", () => {\n    it(\"from a right\", () =>\n      Either.right(\"A\").pipe(\n        Micro.fromEither,\n        Micro.tap((_) => Micro.sync(() => strictEqual(_, \"A\"))),\n        Micro.runPromise\n      ))\n\n    it(\"from a left\", () =>\n      Either.left(\"error\").pipe(\n        Micro.fromEither,\n        Micro.flip,\n        Micro.tap((error) => Micro.sync(() => strictEqual(error, \"error\"))),\n        Micro.runPromise\n      ))\n  })\n\n  describe(\"gen\", () => {\n    it(\"gen\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.succeed(1)\n        strictEqual(result, 1)\n        return result\n      }).pipe(Micro.runPromise).then((_) => deepStrictEqual(_, 1)))\n\n    it(\"gen with context\", () =>\n      Micro.gen({ a: 1, b: 2 }, function*() {\n        const result = yield* Micro.succeed(this.a)\n        strictEqual(result, 1)\n        return result + this.b\n      }).pipe(Micro.runPromise).then((_) => deepStrictEqual(_, 3)))\n  })\n\n  describe(\"forEach\", () => {\n    it(\"sequential\", () =>\n      Micro.gen(function*() {\n        const results = yield* Micro.forEach([1, 2, 3], (_) => Micro.succeed(_))\n        deepStrictEqual(results, [1, 2, 3])\n      }).pipe(Micro.runPromise))\n\n    it(\"unbounded\", () =>\n      Micro.gen(function*() {\n        const results = yield* Micro.forEach([1, 2, 3], (_) => Micro.succeed(_), { concurrency: \"unbounded\" })\n        deepStrictEqual(results, [1, 2, 3])\n      }).pipe(Micro.runPromise))\n\n    it(\"bounded\", () =>\n      Micro.gen(function*() {\n        const results = yield* Micro.forEach([1, 2, 3, 4, 5], (_) => Micro.succeed(_), { concurrency: 2 })\n        deepStrictEqual(results, [1, 2, 3, 4, 5])\n      }).pipe(Micro.runPromise))\n\n    it(\"inherit unbounded\", () =>\n      Micro.gen(function*() {\n        const handle = yield* Micro.forEach([1, 2, 3], (_) => Micro.succeed(_).pipe(Micro.delay(50)), {\n          concurrency: \"inherit\"\n        }).pipe(\n          Micro.withConcurrency(\"unbounded\"),\n          Micro.fork\n        )\n        yield* Micro.sleep(90)\n        deepStrictEqual(handle.unsafePoll(), Micro.exitSucceed([1, 2, 3]))\n      }).pipe(Micro.runPromise))\n\n    it(\"sequential interrupt\", () =>\n      Micro.gen(function*() {\n        const done: Array<number> = []\n        const fiber = yield* Micro.forEach([1, 2, 3, 4, 5, 6], (i) =>\n          Micro.sync(() => {\n            done.push(i)\n            return i\n          }).pipe(Micro.delay(300))).pipe(Micro.fork)\n        yield* Micro.sleep(800)\n        yield* Micro.fiberInterrupt(fiber)\n        const result = yield* Micro.fiberAwait(fiber)\n        deepStrictEqual(result, Micro.exitInterrupt)\n        deepStrictEqual(done, [1, 2])\n      }).pipe(Micro.runPromise))\n\n    it(\"unbounded interrupt\", () =>\n      Micro.gen(function*() {\n        const done: Array<number> = []\n        const fiber = yield* Micro.forEach([1, 2, 3], (i) =>\n          Micro.sync(() => {\n            done.push(i)\n            return i\n          }).pipe(Micro.delay(150)), { concurrency: \"unbounded\" }).pipe(Micro.fork)\n        yield* Micro.sleep(50)\n        yield* Micro.fiberInterrupt(fiber)\n        const result = yield* Micro.fiberAwait(fiber)\n        deepStrictEqual(result, Micro.exitInterrupt)\n        deepStrictEqual(done, [])\n      }).pipe(Micro.runPromise))\n\n    it(\"bounded interrupt\", () =>\n      Micro.gen(function*() {\n        const done: Array<number> = []\n        const fiber = yield* Micro.forEach([1, 2, 3, 4, 5, 6], (i) =>\n          Micro.sync(() => {\n            done.push(i)\n            return i\n          }).pipe(Micro.delay(200)), { concurrency: 2 }).pipe(Micro.fork)\n        yield* Micro.sleep(350)\n        yield* Micro.fiberInterrupt(fiber)\n        const result = yield* Micro.fiberAwait(fiber)\n        deepStrictEqual(result, Micro.exitInterrupt)\n        deepStrictEqual(done, [1, 2])\n      }).pipe(Micro.runPromise))\n\n    // TODO: mark this test as flaky, unfortunately I was not able to reproduce it locally\n    it(\"unbounded fail\", { retry: 3 }, () =>\n      Micro.gen(function*() {\n        const done: Array<number> = []\n        const handle = yield* Micro.forEach([1, 2, 3, 4, 5], (i) =>\n          Micro.suspend(() => {\n            done.push(i)\n            return i === 3 ? Micro.fail(\"error\") : Micro.succeed(i)\n          }).pipe(Micro.delay(i * 100)), {\n          concurrency: \"unbounded\"\n        }).pipe(Micro.fork)\n        const result = yield* Micro.fiberAwait(handle)\n        deepStrictEqual(result, Micro.exitFail(\"error\"))\n        deepStrictEqual(done, [1, 2, 3])\n      }).pipe(Micro.runPromise))\n\n    it(\"length = 0\", () =>\n      Micro.gen(function*() {\n        const results = yield* Micro.forEach([], (_) => Micro.succeed(_))\n        deepStrictEqual(results, [])\n      }).pipe(Micro.runPromise))\n  })\n\n  describe(\"all\", () => {\n    it(\"tuple\", () =>\n      Micro.gen(function*() {\n        const results = (yield* Micro.all([\n          Micro.succeed(1),\n          Micro.succeed(2),\n          Micro.succeed(3)\n        ])) satisfies [\n          number,\n          number,\n          number\n        ]\n        deepStrictEqual(results, [1, 2, 3])\n      }).pipe(Micro.runPromise))\n\n    it(\"record\", () =>\n      Micro.gen(function*() {\n        const results = (yield* Micro.all({\n          a: Micro.succeed(1),\n          b: Micro.succeed(\"2\"),\n          c: Micro.succeed(true)\n        })) satisfies {\n          a: number\n          b: string\n          c: boolean\n        }\n        deepStrictEqual(results, {\n          a: 1,\n          b: \"2\",\n          c: true\n        })\n      }).pipe(Micro.runPromise))\n\n    it.effect(\"record discard\", () =>\n      Micro.gen(function*() {\n        const results = (yield* Micro.all({\n          a: Micro.succeed(1),\n          b: Micro.succeed(\"2\"),\n          c: Micro.succeed(true)\n        }, { discard: true })) satisfies void\n        deepStrictEqual(results, void 0)\n      }))\n\n    it.effect(\"iterable\", () =>\n      Micro.gen(function*() {\n        const results = (yield* Micro.all(\n          new Set([\n            Micro.succeed(1),\n            Micro.succeed(2),\n            Micro.succeed(3)\n          ])\n        )) satisfies Array<number>\n        deepStrictEqual(results, [1, 2, 3])\n      }))\n  })\n\n  describe(\"filter\", () => {\n    it.live(\"odd numbers\", () =>\n      Micro.gen(function*() {\n        const results = yield* Micro.filter([1, 2, 3, 4, 5], (_) => Micro.succeed(_ % 2 === 1))\n        deepStrictEqual(results, [1, 3, 5])\n      }))\n\n    it.live(\"iterable\", () =>\n      Micro.gen(function*() {\n        const results = yield* Micro.filter(new Set([1, 2, 3, 4, 5]), (_) => Micro.succeed(_ % 2 === 1))\n        deepStrictEqual(results, [1, 3, 5])\n      }))\n  })\n\n  describe(\"acquireRelease\", () => {\n    it(\"releases on interrupt\", () =>\n      Micro.gen(function*() {\n        let release = false\n        const fiber = yield* Micro.acquireRelease(\n          Micro.delay(Micro.succeed(\"foo\"), 100),\n          () =>\n            Micro.sync(() => {\n              release = true\n            })\n        ).pipe(Micro.scoped, Micro.fork)\n        yield* Micro.yieldFlush\n        fiber.unsafeInterrupt()\n        yield* Micro.fiberAwait(fiber)\n        strictEqual(release, true)\n      }).pipe(Micro.runPromise))\n  })\n\n  it.effect(\"raceAll\", () =>\n    Micro.gen(function*() {\n      const interrupted: Array<number> = []\n      const result = yield* Micro.raceAll([500, 300, 200, 0, 100].map((ms) =>\n        (ms === 0 ? Micro.fail(\"boom\") : Micro.succeed(ms)).pipe(\n          Micro.delay(ms),\n          Micro.onInterrupt(\n            Micro.sync(() => {\n              interrupted.push(ms)\n            })\n          )\n        )\n      ))\n      strictEqual(result, 100)\n      deepStrictEqual(interrupted, [500, 300, 200])\n    }))\n\n  it(\"raceAllFirst\", () =>\n    Micro.gen(function*() {\n      const interrupted: Array<number> = []\n      const result = yield* Micro.raceAllFirst([500, 300, 200, 0, 100].map((ms) =>\n        (ms === 0 ? Micro.fail(\"boom\") : Micro.succeed(ms)).pipe(\n          Micro.delay(ms),\n          Micro.onInterrupt(\n            Micro.sync(() => {\n              interrupted.push(ms)\n            })\n          )\n        )\n      )).pipe(Micro.exit)\n      deepStrictEqual(result, Micro.exitFail(\"boom\"))\n      deepStrictEqual(interrupted, [500, 300, 200, 100])\n    }).pipe(Micro.runPromise))\n\n  describe(\"valid Effect\", () => {\n    it.effect(\"success\", () =>\n      Effect.gen(function*() {\n        const result = yield* Micro.succeed(123)\n        strictEqual(result, 123)\n      }))\n\n    it.effect(\"failure\", () =>\n      Effect.gen(function*() {\n        const result = yield* Micro.fail(\"boom\").pipe(\n          Effect.sandbox,\n          Effect.flip\n        )\n        deepStrictEqual(result, Cause.fail(\"boom\"))\n      }))\n\n    it.effect(\"defects\", () =>\n      Effect.gen(function*() {\n        const result = yield* Micro.die(\"boom\").pipe(\n          Effect.sandbox,\n          Effect.flip\n        )\n        deepStrictEqual(result, Cause.die(\"boom\"))\n      }))\n\n    it.effect(\"context\", () =>\n      Effect.gen(function*() {\n        const result = yield* Micro.service(ATag).pipe(\n          Micro.map((_) => _)\n        )\n        deepStrictEqual(result, \"A\")\n      }).pipe(Effect.provideService(ATag, \"A\")))\n\n    it.effect(\"interruption\", () =>\n      Effect.gen(function*() {\n        const fiber = yield* Micro.never.pipe(\n          Effect.fork\n        )\n        yield* Effect.yieldNow()\n        yield* Fiber.interrupt(fiber)\n        const exit = yield* fiber.await\n        assertTrue(Exit.isInterrupted(exit))\n      }))\n  })\n\n  describe(\"repeat\", () => {\n    it.effect(\"is stack safe\", () =>\n      Micro.void.pipe(\n        Micro.repeat({ times: 10000 })\n      ))\n\n    it.effect(\"is interruptible\", () =>\n      Micro.void.pipe(\n        Micro.forever,\n        Micro.timeoutOption(50)\n      ))\n\n    it(\"works with runSync\", () => {\n      const result = Micro.succeed(123).pipe(\n        Micro.repeat({ times: 1000 }),\n        Micro.runSync\n      )\n      deepStrictEqual(result, 123)\n    })\n\n    it.effect(\"scheduleRecurs\", () =>\n      Micro.gen(function*() {\n        let count = 0\n        yield* Micro.sync(() => count++).pipe(\n          Micro.repeat({\n            schedule: Micro.scheduleRecurs(3)\n          })\n        )\n        deepStrictEqual(count, 4)\n      }))\n  })\n\n  describe(\"retry\", () => {\n    it.live(\"nothing on success\", () =>\n      Micro.gen(function*() {\n        let count = 0\n        yield* Micro.sync(() => count++).pipe(\n          Micro.retry({ times: 10000 })\n        )\n        strictEqual(count, 1)\n      }))\n\n    it.effect(\"initial + retries\", () =>\n      Micro.gen(function*() {\n        let count = 0\n        const error = yield* Micro.failSync(() => ++count).pipe(\n          Micro.retry({ times: 2 }),\n          Micro.flip\n        )\n        strictEqual(error, 3)\n      }))\n\n    it.effect(\"predicate\", () =>\n      Micro.gen(function*() {\n        let count = 0\n        const error = yield* Micro.failSync(() => ++count).pipe(\n          Micro.retry({ while: (i) => i < 3 }),\n          Micro.flip\n        )\n        strictEqual(error, 3)\n      }))\n  })\n\n  describe(\"timeoutOption\", () => {\n    it.live(\"timeout a long computation\", () =>\n      Micro.gen(function*() {\n        const result = yield* pipe(\n          Micro.sleep(60_000),\n          Micro.andThen(Micro.succeed(true)),\n          Micro.timeoutOption(10)\n        )\n        deepStrictEqual(result, Option.none())\n      }))\n    it.live(\"timeout a long computation with a failure\", () =>\n      Micro.gen(function*() {\n        const error = new Error(\"boom\")\n        const result = yield* pipe(\n          Micro.sleep(5000),\n          Micro.andThen(Micro.succeed(true)),\n          Micro.timeoutOrElse({\n            onTimeout: () => Micro.die(error),\n            duration: 10\n          }),\n          Micro.sandbox,\n          Micro.flip\n        )\n        deepStrictEqual(result, Micro.causeDie(error))\n      }))\n    it.effect(\"timeout repetition of uninterruptible effect\", () =>\n      Micro.gen(function*() {\n        const result = yield* pipe(\n          Micro.void,\n          Micro.uninterruptible,\n          Micro.forever,\n          Micro.timeoutOption(10)\n        )\n        deepStrictEqual(result, Option.none())\n      }))\n    it.effect(\"timeout in uninterruptible region\", () =>\n      Micro.gen(function*() {\n        yield* Micro.void.pipe(Micro.timeoutOption(20_000), Micro.uninterruptible)\n      }), { timeout: 1000 })\n  })\n\n  describe(\"timeout\", () => {\n    it.live(\"timeout a long computation\", () =>\n      Micro.gen(function*() {\n        const result = yield* pipe(\n          Micro.sleep(60_000),\n          Micro.andThen(Micro.succeed(true)),\n          Micro.timeout(10),\n          Micro.flip\n        )\n        deepStrictEqual(result, new Micro.TimeoutException())\n      }))\n  })\n\n  describe(\"Error\", () => {\n    class TestError extends Micro.Error {}\n\n    it.effect(\"is yieldable\", () =>\n      Micro.gen(function*() {\n        const error = yield* new TestError().pipe(Micro.flip)\n        deepStrictEqual(error, new TestError())\n      }))\n\n    it.effect(\"is a valid Effect\", () =>\n      Effect.gen(function*() {\n        const error = yield* new TestError().pipe(Effect.flip)\n        deepStrictEqual(error, new TestError())\n      }))\n  })\n\n  describe(\"TaggedError\", () => {\n    it.effect(\"is a valid Effect\", () =>\n      Effect.gen(function*() {\n        const error = yield* new TestError().pipe(Effect.flip)\n        deepStrictEqual(error, new TestError())\n      }))\n\n    it.effect(\"has a _tag\", () =>\n      Micro.gen(function*() {\n        const result = yield* new TestError().pipe(\n          Micro.catchTag(\"TestError\", (_) => Micro.succeed(true))\n        )\n        strictEqual(result, true)\n      }))\n  })\n\n  describe(\"failure rendering\", () => {\n    it.effect(\"renders non-error defects\", () =>\n      Micro.gen(function*() {\n        const failure = yield* Micro.die({ some: \"error\" }).pipe(\n          Micro.withTrace(\"test trace\"),\n          Micro.sandbox,\n          Micro.flip\n        )\n        strictEqual(failure.name, \"MicroCause.Die\")\n        strictEqual(failure.message, JSON.stringify({ some: \"error\" }))\n        assertInclude(failure.stack, `MicroCause.Die: ${JSON.stringify({ some: \"error\" })}`)\n        assertInclude(failure.stack, \"at test trace (\")\n      }))\n\n    it.effect(\"renders non-errors\", () =>\n      Micro.gen(function*() {\n        const failure = yield* Micro.fail({ some: \"error\" }).pipe(\n          Micro.withTrace(\"test trace\"),\n          Micro.sandbox,\n          Micro.flip\n        )\n        strictEqual(failure.name, \"MicroCause.Fail\")\n        strictEqual(failure.message, JSON.stringify({ some: \"error\" }))\n        assertInclude(failure.stack, `MicroCause.Fail: ${JSON.stringify({ some: \"error\" })}`)\n        assertInclude(failure.stack, \"at test trace (\")\n      }))\n\n    it.effect(\"renders errors\", () =>\n      Micro.gen(function*() {\n        const failure = yield* Micro.fail(new Error(\"boom\")).pipe(\n          Micro.withTrace(\"test trace\"),\n          Micro.sandbox,\n          Micro.flip\n        )\n        strictEqual(failure.name, \"(MicroCause.Fail) Error\")\n        strictEqual(failure.message, \"boom\")\n        assertInclude(failure.stack, `(MicroCause.Fail) Error: boom`)\n        assertInclude(failure.stack, \"at test trace (\")\n      }))\n  })\n\n  describe(\"interruption\", () => {\n    it.effect(\"sync forever is interruptible\", () =>\n      Micro.gen(function*() {\n        const fiber = yield* pipe(Micro.succeed(1), Micro.forever, Micro.fork)\n        yield* Micro.fiberInterrupt(fiber)\n        deepStrictEqual(fiber.unsafePoll(), Micro.exitInterrupt)\n      }))\n\n    it.effect(\"interrupt of never is interrupted with cause\", () =>\n      Micro.gen(function*() {\n        const fiber = yield* Micro.fork(Micro.never)\n        yield* Micro.fiberInterrupt(fiber)\n        deepStrictEqual(fiber.unsafePoll(), Micro.exitInterrupt)\n      }))\n\n    it.effect(\"catchAll + ensuring + interrupt\", () =>\n      Micro.gen(function*() {\n        let catchFailure = false\n        let ensuring = false\n        const handle = yield* Micro.never.pipe(\n          Micro.catchAllCause((_) =>\n            Micro.sync(() => {\n              catchFailure = true\n            })\n          ),\n          Micro.ensuring(Micro.sync(() => {\n            ensuring = true\n          })),\n          Micro.fork\n        )\n        yield* Micro.yieldFlush\n        yield* Micro.fiberInterrupt(handle)\n        assertFalse(catchFailure)\n        assertTrue(ensuring)\n      }))\n\n    it.effect(\"run of interruptible\", () =>\n      Micro.gen(function*() {\n        let recovered = false\n        const fiber = yield* Micro.never.pipe(\n          Micro.interruptible,\n          Micro.exit,\n          Micro.flatMap((result) =>\n            Micro.sync(() => {\n              recovered = result._tag === \"Failure\" && result.cause._tag === \"Interrupt\"\n            })\n          ),\n          Micro.uninterruptible,\n          Micro.fork\n        )\n        yield* Micro.yieldFlush\n        yield* Micro.fiberInterrupt(fiber)\n        assertTrue(recovered)\n      }))\n\n    it.effect(\"alternating interruptibility\", () =>\n      Micro.gen(function*() {\n        let counter = 0\n        const fiber = yield* Micro.never.pipe(\n          Micro.interruptible,\n          Micro.exit,\n          Micro.andThen(Micro.sync(() => {\n            counter++\n          })),\n          Micro.uninterruptible,\n          Micro.interruptible,\n          Micro.exit,\n          Micro.andThen(Micro.sync(() => {\n            counter++\n          })),\n          Micro.uninterruptible,\n          Micro.fork\n        )\n        yield* Micro.yieldFlush\n        yield* Micro.fiberInterrupt(fiber)\n        strictEqual(counter, 2)\n      }))\n\n    it.live(\"acquireUseRelease use inherits interrupt status\", () =>\n      Micro.gen(function*() {\n        let ref = false\n        const fiber = yield* Micro.acquireUseRelease(\n          Micro.succeed(123),\n          (_) =>\n            Micro.sync(() => {\n              ref = true\n            }).pipe(\n              Micro.delay(10)\n            ),\n          () => Micro.void\n        ).pipe(\n          Micro.uninterruptible,\n          Micro.fork\n        )\n        yield* Micro.yieldFlush\n        yield* Micro.fiberInterrupt(fiber)\n        assertTrue(ref)\n      }))\n\n    it.live(\"async can be uninterruptible\", () =>\n      Micro.gen(function*() {\n        let ref = false\n        const fiber = yield* Micro.sleep(10).pipe(\n          Micro.andThen(() => {\n            ref = true\n          }),\n          Micro.uninterruptible,\n          Micro.fork\n        )\n        yield* Micro.yieldFlush\n        yield* Micro.fiberInterrupt(fiber)\n        assertTrue(ref)\n      }))\n\n    it.live(\"async cannot resume on interrupt\", () =>\n      Micro.gen(function*() {\n        const fiber = yield* Micro.async<string>((resume) => {\n          setTimeout(() => {\n            resume(Micro.succeed(\"foo\"))\n          }, 10)\n        }).pipe(\n          Micro.onInterrupt(Micro.sleep(30)),\n          Micro.fork\n        )\n        yield* Micro.yieldFlush\n        yield* Micro.fiberInterrupt(fiber)\n        deepStrictEqual(fiber.unsafePoll(), Micro.exitInterrupt)\n      }))\n\n    it.live(\"closing scope is uninterruptible\", () =>\n      Micro.gen(function*() {\n        let ref = false\n        const child = pipe(\n          Micro.sleep(10),\n          Micro.andThen(() => {\n            ref = true\n          })\n        )\n        const fiber = yield* child.pipe(Micro.uninterruptible, Micro.fork)\n        yield* Micro.yieldFlush\n        yield* Micro.fiberInterrupt(fiber)\n        assertTrue(ref)\n      }))\n\n    it.effect(\"AbortSignal is aborted\", () =>\n      Micro.gen(function*() {\n        let signal: AbortSignal\n        const fiber = yield* Micro.async<void, never, never>((_cb, signal_) => {\n          signal = signal_\n        }).pipe(Micro.fork)\n        yield* Micro.yieldFlush\n        yield* Micro.fiberInterrupt(fiber)\n        strictEqual(signal!.aborted, true)\n      }))\n  })\n\n  describe(\"fork\", () => {\n    it.effect(\"is interrupted with parent\", () =>\n      Micro.gen(function*() {\n        let child = false\n        let parent = false\n        const fiber = yield* Micro.never.pipe(\n          Micro.onInterrupt(Micro.sync(() => {\n            child = true\n          })),\n          Micro.fork,\n          Micro.andThen(Micro.never),\n          Micro.onInterrupt(Micro.sync(() => {\n            parent = true\n          })),\n          Micro.fork\n        )\n        yield* Micro.yieldFlush\n        yield* Micro.fiberInterrupt(fiber)\n        yield* Micro.yieldFlush\n        assertTrue(child)\n        assertTrue(parent)\n      }))\n  })\n\n  describe(\"forkDaemon\", () => {\n    it.effect(\"is not interrupted with parent\", () =>\n      Micro.gen(function*() {\n        let child = false\n        let parent = false\n        const handle = yield* Micro.never.pipe(\n          Micro.onInterrupt(Micro.sync(() => {\n            child = true\n          })),\n          Micro.forkDaemon,\n          Micro.andThen(Micro.never),\n          Micro.onInterrupt(Micro.sync(() => {\n            parent = true\n          })),\n          Micro.fork\n        )\n        yield* Micro.yieldFlush\n        yield* Micro.fiberInterrupt(handle)\n        assertFalse(child)\n        assertTrue(parent)\n      }))\n  })\n\n  describe(\"forkIn\", () => {\n    it.effect(\"is interrupted when scope is closed\", () =>\n      Micro.gen(function*() {\n        let interrupted = false\n        const scope = yield* Micro.scopeMake\n        yield* Micro.never.pipe(\n          Micro.onInterrupt(Micro.sync(() => {\n            interrupted = true\n          })),\n          Micro.forkIn(scope)\n        )\n        yield* Micro.yieldFlush\n        yield* scope.close(Micro.exitVoid)\n        assertTrue(interrupted)\n      }))\n  })\n\n  describe(\"forkScoped\", () => {\n    it.effect(\"is interrupted when scope is closed\", () =>\n      Micro.gen(function*() {\n        let interrupted = false\n        const scope = yield* Micro.scopeMake\n        yield* Micro.never.pipe(\n          Micro.onInterrupt(Micro.sync(() => {\n            interrupted = true\n          })),\n          Micro.forkScoped,\n          Micro.provideScope(scope)\n        )\n        yield* Micro.yieldFlush\n        yield* scope.close(Micro.exitVoid)\n        assertTrue(interrupted)\n      }))\n  })\n\n  describe(\"do notation\", () => {\n    it.effect(\"works\", () =>\n      Micro.succeed(1).pipe(\n        Micro.bindTo(\"a\"),\n        Micro.let(\"b\", ({ a }) => a + 1),\n        Micro.bind(\"b\", ({ b }) => Micro.succeed(b.toString())),\n        Micro.tap((_) => {\n          deepStrictEqual(_, {\n            a: 1,\n            b: \"2\"\n          })\n        })\n      ))\n    it.effect(\"does not bindTo __proto__\", () =>\n      pipe(\n        Micro.succeed(1),\n        Micro.bindTo(\"__proto__\"),\n        Micro.bind(\"x\", () => Micro.succeed(2)),\n        Micro.tap((_) => {\n          deepStrictEqual(_, {\n            x: 2,\n            [\"__proto__\"]: 1\n          })\n        })\n      ))\n    it.effect(\"does not let __proto__\", () =>\n      pipe(\n        Micro.Do,\n        Micro.let(\"__proto__\", () => 1),\n        Micro.bind(\"x\", () => Micro.succeed(2)),\n        Micro.tap((_) => {\n          deepStrictEqual(_, {\n            x: 2,\n            [\"__proto__\"]: 1\n          })\n        })\n      ))\n    it.effect(\"does not bind __proto__\", () =>\n      pipe(\n        Micro.Do,\n        Micro.bind(\"__proto__\", () => Micro.succeed(1)),\n        Micro.bind(\"x\", () => Micro.succeed(2)),\n        Micro.tap((_) => {\n          deepStrictEqual(_, {\n            x: 2,\n            [\"__proto__\"]: 1\n          })\n        })\n      ))\n  })\n\n  describe(\"stack safety\", () => {\n    it.effect(\"recursion\", () => {\n      const loop: Micro.Micro<void> = Micro.void.pipe(\n        Micro.flatMap((_) => loop)\n      )\n      return loop.pipe(\n        Micro.timeoutOption(50)\n      )\n    })\n  })\n\n  describe(\"finalization\", () => {\n    const ExampleError = new Error(\"Oh noes!\")\n\n    it.effect(\"fail ensuring\", () =>\n      Micro.gen(function*() {\n        let finalized = false\n        const result = yield* Micro.fail(ExampleError).pipe(\n          Micro.ensuring(Micro.sync(() => {\n            finalized = true\n          })),\n          Micro.exit\n        )\n        deepStrictEqual(result, Micro.exitFail(ExampleError))\n        assertTrue(finalized)\n      }))\n\n    it.effect(\"fail on error\", () =>\n      Micro.gen(function*() {\n        let finalized = false\n        const result = yield* Micro.fail(ExampleError).pipe(\n          Micro.onError(() =>\n            Micro.sync(() => {\n              finalized = true\n            })\n          ),\n          Micro.exit\n        )\n        deepStrictEqual(result, Micro.exitFail(ExampleError))\n        assertTrue(finalized)\n      }))\n\n    it.effect(\"finalizer errors not caught\", () =>\n      Micro.gen(function*() {\n        const e2 = new Error(\"e2\")\n        const e3 = new Error(\"e3\")\n        const result = yield* pipe(\n          Micro.fail(ExampleError),\n          Micro.ensuring(Micro.die(e2)),\n          Micro.ensuring(Micro.die(e3)),\n          Micro.sandbox,\n          Micro.flip,\n          Micro.map((cause) => cause)\n        )\n        deepStrictEqual(result, Micro.causeDie(e3))\n      }))\n\n    it.effect(\"finalizer errors reported\", () =>\n      Micro.gen(function*() {\n        let reported: Micro.MicroExit<number> | undefined\n        const result = yield* pipe(\n          Micro.succeed(42),\n          Micro.ensuring(Micro.die(ExampleError)),\n          Micro.fork,\n          Micro.flatMap((fiber) =>\n            pipe(\n              Micro.fiberAwait(fiber),\n              Micro.flatMap((e) =>\n                Micro.sync(() => {\n                  reported = e\n                })\n              )\n            )\n          )\n        )\n        strictEqual(result, undefined)\n        assertFalse(reported !== undefined && Micro.exitIsSuccess(reported))\n      }))\n\n    it.effect(\"acquireUseRelease usage result\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.acquireUseRelease(\n          Micro.void,\n          () => Micro.succeed(42),\n          () => Micro.void\n        )\n        strictEqual(result, 42)\n      }))\n\n    it.effect(\"error in just acquisition\", () =>\n      Micro.gen(function*() {\n        const result = yield* pipe(\n          Micro.acquireUseRelease(\n            Micro.fail(ExampleError),\n            () => Micro.void,\n            () => Micro.void\n          ),\n          Micro.exit\n        )\n        deepStrictEqual(result, Micro.exitFail(ExampleError))\n      }))\n\n    it.effect(\"error in just release\", () =>\n      Micro.gen(function*() {\n        const result = yield* pipe(\n          Micro.acquireUseRelease(\n            Micro.void,\n            () => Micro.void,\n            () => Micro.die(ExampleError)\n          ),\n          Micro.exit\n        )\n        deepStrictEqual(result, Micro.exitDie(ExampleError))\n      }))\n\n    it.effect(\"error in just usage\", () =>\n      Micro.gen(function*() {\n        const result = yield* pipe(\n          Micro.acquireUseRelease(\n            Micro.void,\n            () => Micro.fail(ExampleError),\n            () => Micro.void\n          ),\n          Micro.exit\n        )\n        deepStrictEqual(result, Micro.exitFail(ExampleError))\n      }))\n\n    it.effect(\"rethrown caught error in acquisition\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.acquireUseRelease(\n          Micro.fail(ExampleError),\n          () => Micro.void,\n          () => Micro.void\n        ).pipe(Micro.flip)\n        deepStrictEqual(result, ExampleError)\n      }))\n\n    it.effect(\"rethrown caught error in release\", () =>\n      Micro.gen(function*() {\n        const result = yield* pipe(\n          Micro.acquireUseRelease(\n            Micro.void,\n            () => Micro.void,\n            () => Micro.die(ExampleError)\n          ),\n          Micro.exit\n        )\n        deepStrictEqual(result, Micro.exitDie(ExampleError))\n      }))\n\n    it.effect(\"rethrown caught error in usage\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.acquireUseRelease(\n          Micro.void,\n          () => Micro.fail(ExampleError),\n          () => Micro.void\n        ).pipe(Micro.exit)\n        deepStrictEqual(result, Micro.exitFail(ExampleError))\n      }))\n\n    it.effect(\"onResult - ensures that a cleanup function runs when an effect fails\", () =>\n      Micro.gen(function*() {\n        let ref = false\n        yield* Micro.die(\"boom\").pipe(\n          Micro.onExit((result) =>\n            Micro.exitIsDie(result) ?\n              Micro.sync(() => {\n                ref = true\n              }) :\n              Micro.void\n          ),\n          Micro.sandbox,\n          Micro.ignore\n        )\n        assertTrue(ref)\n      }))\n  })\n\n  describe(\"error handling\", () => {\n    class ErrorA extends Micro.TaggedError(\"A\") {}\n    class ErrorB extends Micro.TaggedError(\"B\") {}\n    class ErrorC extends Micro.Error {}\n\n    it.effect(\"catchTag\", () =>\n      Micro.gen(function*() {\n        let error: ErrorA | ErrorB | ErrorC = new ErrorA()\n        const effect = Micro.failSync(() => error).pipe(\n          Micro.catchTag(\"A\", (_) => Micro.succeed(1)),\n          Micro.catchTag(\"B\", (_) => Micro.succeed(2)),\n          Micro.orElseSucceed(() => 3)\n        )\n        strictEqual(yield* effect, 1)\n        error = new ErrorB()\n        strictEqual(yield* effect, 2)\n        error = new ErrorC()\n        strictEqual(yield* effect, 3)\n      }))\n  })\n\n  describe(\"zip\", () => {\n    it.effect(\"concurrent: false\", () => {\n      const executionOrder: Array<string> = []\n      const task1 = Micro.succeed(\"a\").pipe(Micro.delay(5), Micro.tap(() => executionOrder.push(\"task1\")))\n      const task2 = Micro.succeed(1).pipe(Micro.delay(1), Micro.tap(() => executionOrder.push(\"task2\")))\n      return Micro.gen(function*() {\n        const result = yield* Micro.zip(task1, task2)\n        deepStrictEqual(result, [\"a\", 1])\n        deepStrictEqual(executionOrder, [\"task1\", \"task2\"])\n      })\n    })\n    it.effect(\"concurrent: true\", () => {\n      const executionOrder: Array<string> = []\n      const task1 = Micro.succeed(\"a\").pipe(Micro.delay(50), Micro.tap(() => executionOrder.push(\"task1\")))\n      const task2 = Micro.succeed(1).pipe(Micro.delay(1), Micro.tap(() => executionOrder.push(\"task2\")))\n      return Micro.gen(function*() {\n        const result = yield* Micro.zip(task1, task2, { concurrent: true })\n        deepStrictEqual(result, [\"a\", 1])\n        deepStrictEqual(executionOrder, [\"task2\", \"task1\"])\n      })\n    })\n  })\n\n  describe(\"zipWith\", () => {\n    it.effect(\"concurrent: false\", () => {\n      const executionOrder: Array<string> = []\n      const task1 = Micro.succeed(\"a\").pipe(Micro.delay(50), Micro.tap(() => executionOrder.push(\"task1\")))\n      const task2 = Micro.succeed(1).pipe(Micro.delay(1), Micro.tap(() => executionOrder.push(\"task2\")))\n      return Micro.gen(function*() {\n        const result = yield* Micro.zipWith(task1, task2, (a, b) => a + b)\n        deepStrictEqual(result, \"a1\")\n        deepStrictEqual(executionOrder, [\"task1\", \"task2\"])\n      })\n    })\n    it.effect(\"concurrent: true\", () => {\n      const executionOrder: Array<string> = []\n      const task1 = Micro.succeed(\"a\").pipe(Micro.delay(50), Micro.tap(() => executionOrder.push(\"task1\")))\n      const task2 = Micro.succeed(1).pipe(Micro.delay(1), Micro.tap(() => executionOrder.push(\"task2\")))\n      return Micro.gen(function*() {\n        const result = yield* Micro.zipWith(task1, task2, (a, b) => a + b, { concurrent: true })\n        deepStrictEqual(result, \"a1\")\n        deepStrictEqual(executionOrder, [\"task2\", \"task1\"])\n      })\n    })\n  })\n\n  describe(\"catchCauseIf\", () => {\n    it.effect(\"first argument as success\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.catchCauseIf(Micro.succeed(1), () => false, () => Micro.fail(\"e2\"))\n        deepStrictEqual(result, 1)\n      }))\n    it.effect(\"first argument as failure and predicate return false\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.flip(\n          Micro.catchCauseIf(Micro.fail(\"e1\" as const), () => false, () => Micro.fail(\"e2\" as const))\n        )\n        deepStrictEqual(result, \"e1\")\n      }))\n    it.effect(\"first argument as failure and predicate return true\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.flip(\n          Micro.catchCauseIf(Micro.fail(\"e1\" as const), () => true, () => Micro.fail(\"e2\" as const))\n        )\n        deepStrictEqual(result, \"e2\")\n      }))\n  })\n\n  describe(\"catchAll\", () => {\n    it.effect(\"first argument as success\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.catchAll(Micro.succeed(1), () => Micro.fail(\"e2\" as const))\n        deepStrictEqual(result, 1)\n      }))\n    it.effect(\"first argument as failure\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.flip(Micro.catchAll(Micro.fail(\"e1\" as const), () => Micro.fail(\"e2\" as const)))\n        deepStrictEqual(result, \"e2\")\n      }))\n  })\n\n  describe(\"catchAllCause\", () => {\n    it.effect(\"first argument as success\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.catchAllCause(Micro.succeed(1), () => Micro.fail(\"e2\" as const))\n        deepStrictEqual(result, 1)\n      }))\n    it.effect(\"first argument as failure\", () =>\n      Micro.gen(function*() {\n        const result = yield* Micro.flip(\n          Micro.catchAllCause(Micro.fail(\"e1\" as const), () => Micro.fail(\"e2\" as const))\n        )\n        deepStrictEqual(result, \"e2\")\n      }))\n  })\n\n  describe(\"schedules\", () => {\n    // returns an array of delays, an item for each attempt\n    const dryRun = (schedule: Micro.MicroSchedule, maxAttempt: number = 7): Array<number> => {\n      let attempt = 1\n      let elapsed = 0\n      let duration = schedule(attempt, elapsed)\n      const out: Array<number> = []\n      while (Option.isSome(duration) && attempt <= maxAttempt) {\n        const value = duration.value\n        attempt++\n        elapsed += value\n        out.push(value)\n        duration = schedule(attempt, elapsed)\n      }\n      return out\n    }\n\n    it(\"scheduleRecurs\", () => {\n      const out = dryRun(Micro.scheduleRecurs(5))\n      deepStrictEqual(out, [0, 0, 0, 0, 0])\n    })\n\n    it(\"scheduleSpaced\", () => {\n      const out = dryRun(Micro.scheduleSpaced(10))\n      deepStrictEqual(out, [10, 10, 10, 10, 10, 10, 10])\n    })\n\n    it(\"scheduleExponential\", () => {\n      const out = dryRun(Micro.scheduleExponential(10))\n      deepStrictEqual(out, [20, 40, 80, 160, 320, 640, 1280])\n    })\n\n    it(\"scheduleAddDelay\", () => {\n      const out = dryRun(Micro.scheduleAddDelay(Micro.scheduleRecurs(5), () => 10))\n      deepStrictEqual(out, [10, 10, 10, 10, 10])\n    })\n\n    it(\"scheduleWithMaxDelay\", () => {\n      const out = dryRun(Micro.scheduleWithMaxDelay(Micro.scheduleExponential(10), 400))\n      deepStrictEqual(out, [20, 40, 80, 160, 320, 400, 400])\n    })\n\n    it(\"scheduleWithMaxElapsed\", () => {\n      const out = dryRun(Micro.scheduleWithMaxElapsed(Micro.scheduleExponential(10), 400))\n      deepStrictEqual(out, [20, 40, 80, 160, 320])\n    })\n\n    it(\"scheduleUnion\", () => {\n      const out = dryRun(Micro.scheduleUnion(\n        Micro.scheduleExponential(10),\n        Micro.scheduleSpaced(100)\n      ))\n      deepStrictEqual(out, [20, 40, 80, 100, 100, 100, 100])\n    })\n\n    it(\"scheduleIntersect\", () => {\n      const out = dryRun(Micro.scheduleIntersect(\n        Micro.scheduleExponential(10),\n        Micro.scheduleSpaced(100)\n      ))\n      deepStrictEqual(out, [100, 100, 100, 160, 320, 640, 1280])\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/MutableHashMap.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertNone, assertSome, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Equal, Hash, MutableHashMap as HM, Option, pipe } from \"effect\"\n\nclass Key implements Equal.Equal {\n  constructor(readonly a: number, readonly b: number) {}\n\n  [Hash.symbol]() {\n    return Hash.hash(`${this.a}-${this.b}`)\n  }\n\n  [Equal.symbol](that: unknown): boolean {\n    return that instanceof Key && this.a === that.a && this.b === that.b\n  }\n}\n\nclass Value implements Equal.Equal {\n  constructor(readonly c: number, readonly d: number) {}\n\n  [Hash.symbol]() {\n    return Hash.hash(`${this.c}-${this.d}`)\n  }\n\n  [Equal.symbol](that: unknown): boolean {\n    return that instanceof Value && this.c === that.c && this.d === that.d\n  }\n}\n\nfunction key(a: number, b: number): Key {\n  return new Key(a, b)\n}\n\nfunction value(c: number, d: number): Value {\n  return new Value(c, d)\n}\n\ndescribe(\"MutableHashMap\", () => {\n  it(\"toString\", () => {\n    const map = HM.make(\n      [0, \"a\"],\n      [1, \"b\"]\n    )\n\n    strictEqual(\n      String(map),\n      `{\n  \"_id\": \"MutableHashMap\",\n  \"values\": [\n    [\n      0,\n      \"a\"\n    ],\n    [\n      1,\n      \"b\"\n    ]\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    const map = HM.make(\n      [0, \"a\"],\n      [1, \"b\"]\n    )\n\n    deepStrictEqual(map.toJSON(), { _id: \"MutableHashMap\", values: [[0, \"a\"], [1, \"b\"]] })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n\n    const map = HM.make(\n      [0, \"a\"],\n      [1, \"b\"]\n    )\n\n    deepStrictEqual(inspect(map), inspect({ _id: \"MutableHashMap\", values: [[0, \"a\"], [1, \"b\"]] }))\n  })\n\n  it(\"make\", () => {\n    const map = HM.make(\n      [key(0, 0), value(0, 0)],\n      [key(1, 1), value(1, 1)]\n    )\n\n    strictEqual(HM.size(map), 2)\n    assertTrue(pipe(map, HM.has(key(0, 0))))\n    assertTrue(pipe(map, HM.has(key(1, 1))))\n  })\n\n  it(\"fromIterable\", () => {\n    const map = HM.fromIterable([\n      [key(0, 0), value(0, 0)],\n      [key(1, 1), value(1, 1)]\n    ])\n\n    strictEqual(HM.size(map), 2)\n    assertTrue(pipe(map, HM.has(key(0, 0))))\n    assertTrue(pipe(map, HM.has(key(1, 1))))\n  })\n\n  it(\"iterate\", () => {\n    class Hello {\n      [Hash.symbol]() {\n        return 0\n      }\n\n      [Equal.symbol](that: unknown) {\n        return this === that\n      }\n    }\n\n    const a = new Hello()\n    const b = new Hello()\n\n    const map = HM.make(\n      [a, 0],\n      [b, 0]\n    )\n\n    strictEqual(Array.from(map).length, 2)\n  })\n\n  it(\"get\", () => {\n    const map = pipe(\n      HM.empty<Key, Value>(),\n      HM.set(key(0, 0), value(0, 0)),\n      HM.set(key(0, 0), value(1, 1))\n    )\n\n    const result = pipe(\n      map,\n      HM.get(key(0, 0))\n    )\n\n    assertSome(result, value(1, 1))\n  })\n\n  it(\"has\", () => {\n    const map = HM.make(\n      [key(0, 0), value(0, 0)],\n      [key(0, 0), value(1, 1)],\n      [key(1, 1), value(2, 2)],\n      [key(1, 1), value(3, 3)],\n      [key(0, 0), value(4, 4)]\n    )\n\n    pipe(\n      map,\n      HM.has(key(0, 0)),\n      assertTrue\n    )\n\n    pipe(\n      map,\n      HM.has(key(1, 1)),\n      assertTrue\n    )\n\n    pipe(\n      map,\n      HM.has(key(4, 4)),\n      assertFalse\n    )\n  })\n\n  it(\"keys\", () => {\n    const map = pipe(\n      HM.empty<Key, Value>(),\n      HM.set(key(0, 0), value(0, 0)),\n      HM.set(key(1, 1), value(1, 1))\n    )\n\n    deepStrictEqual(HM.keys(map), [\n      key(0, 0),\n      key(1, 1)\n    ])\n  })\n\n  it(\"modifyAt\", () => {\n    const map = pipe(\n      HM.empty<Key, Value>(),\n      HM.set(key(0, 0), value(0, 0)),\n      HM.set(key(1, 1), value(1, 1))\n    )\n\n    pipe(\n      map,\n      HM.modifyAt(\n        key(0, 0),\n        () => Option.some(value(0, 1))\n      )\n    )\n\n    strictEqual(HM.size(map), 2)\n    assertSome(pipe(map, HM.get(key(0, 0))), value(0, 1))\n\n    pipe(\n      map,\n      HM.modifyAt(\n        key(2, 2),\n        Option.match({\n          onNone: () => Option.some(value(2, 2)),\n          onSome: Option.some\n        })\n      )\n    )\n\n    strictEqual(HM.size(map), 3)\n    assertSome(pipe(map, HM.get(key(2, 2))), value(2, 2))\n\n    pipe(\n      map,\n      HM.modifyAt(\n        key(2, 2),\n        () => Option.none()\n      )\n    )\n\n    strictEqual(HM.size(map), 2)\n  })\n\n  it(\"remove\", () => {\n    const map = pipe(\n      HM.empty<Key, Value>(),\n      HM.set(key(0, 0), value(0, 0)),\n      HM.set(key(1, 1), value(1, 1))\n    )\n\n    strictEqual(HM.size(map), 2)\n\n    pipe(\n      map,\n      HM.has(key(1, 1)),\n      assertTrue\n    )\n\n    pipe(\n      map,\n      HM.remove(key(1, 1))\n    )\n\n    strictEqual(HM.size(map), 1)\n\n    pipe(\n      map,\n      HM.has(key(1, 1)),\n      assertFalse\n    )\n  })\n\n  it(\"set\", () => {\n    const map = pipe(\n      HM.empty<Key, Value>(),\n      HM.set(key(0, 0), value(0, 0)),\n      HM.set(key(0, 0), value(1, 1)),\n      HM.set(key(1, 1), value(2, 2)),\n      HM.set(key(1, 1), value(3, 3)),\n      HM.set(key(0, 0), value(4, 4))\n    )\n\n    deepStrictEqual(Array.from(map), [\n      [key(0, 0), value(4, 4)],\n      [key(1, 1), value(3, 3)]\n    ])\n  })\n\n  it(\"size\", () => {\n    const map = pipe(\n      HM.empty<Key, Value>(),\n      HM.set(key(0, 0), value(0, 0)),\n      HM.set(key(0, 0), value(1, 1)),\n      HM.set(key(1, 1), value(2, 2)),\n      HM.set(key(1, 1), value(3, 3)),\n      HM.set(key(0, 0), value(4, 4))\n    )\n\n    strictEqual(HM.size(map), 2)\n  })\n\n  it(\"modify\", () => {\n    const map = pipe(\n      HM.empty<Key, Value>(),\n      HM.set(key(0, 0), value(0, 0)),\n      HM.set(key(1, 1), value(1, 1))\n    )\n\n    pipe(\n      map,\n      HM.modify(key(0, 0), (v) => value(v.c + 1, v.d + 1))\n    )\n\n    assertSome(pipe(map, HM.get(key(0, 0))), value(1, 1))\n\n    pipe(\n      map,\n      HM.modify(key(1, 1), (v) => value(v.c + 1, v.d + 1))\n    )\n\n    assertNone(pipe(\n      map,\n      HM.remove(key(0, 0)),\n      HM.get(key(0, 0))\n    ))\n  })\n\n  it(\"pipe()\", () => {\n    deepStrictEqual(HM.empty<string, string>().pipe(HM.set(\"key\", \"value\")), HM.make([\"key\", \"value\"]))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/MutableHashSet.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Equal, Hash, MutableHashSet } from \"effect\"\n\nclass Value implements Equal.Equal {\n  constructor(readonly a: number, readonly b: number) {}\n\n  [Hash.symbol]() {\n    return Hash.hash(`${this.a}-${this.b}`)\n  }\n\n  [Equal.symbol](that: unknown): boolean {\n    return that instanceof Value && this.a === that.a && this.b === that.b\n  }\n\n  toJSON() {\n    return { _id: \"Value\", a: this.a, b: this.b }\n  }\n}\n\ndescribe(\"MutableHashSet\", () => {\n  it(\"toString\", () => {\n    const set = MutableHashSet.make(\n      new Value(0, 1),\n      new Value(2, 3)\n    )\n\n    strictEqual(\n      String(set),\n      `{\n  \"_id\": \"MutableHashSet\",\n  \"values\": [\n    {\n      \"_id\": \"Value\",\n      \"a\": 0,\n      \"b\": 1\n    },\n    {\n      \"_id\": \"Value\",\n      \"a\": 2,\n      \"b\": 3\n    }\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    const set = MutableHashSet.make(\n      new Value(0, 1),\n      new Value(2, 3)\n    )\n\n    deepStrictEqual(set.toJSON(), {\n      _id: \"MutableHashSet\",\n      values: [{ _id: \"Value\", a: 0, b: 1 }, { _id: \"Value\", a: 2, b: 3 }]\n    })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n\n    const set = MutableHashSet.make(\n      new Value(0, 1),\n      new Value(2, 3)\n    )\n\n    deepStrictEqual(\n      inspect(set),\n      inspect({ _id: \"MutableHashSet\", values: [{ _id: \"Value\", a: 0, b: 1 }, { _id: \"Value\", a: 2, b: 3 }] })\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/MutableList.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { MutableList, pipe } from \"effect\"\n\ndescribe(\"MutableList\", () => {\n  it(\"toString\", () => {\n    strictEqual(\n      String(MutableList.make(0, 1, 2)),\n      `{\n  \"_id\": \"MutableList\",\n  \"values\": [\n    0,\n    1,\n    2\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    deepStrictEqual(MutableList.make(0, 1, 2).toJSON(), { _id: \"MutableList\", values: [0, 1, 2] })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n    deepStrictEqual(inspect(MutableList.make(0, 1, 2)), inspect({ _id: \"MutableList\", values: [0, 1, 2] }))\n  })\n\n  it(\"pipe()\", () => {\n    deepStrictEqual(MutableList.empty<string>().pipe(MutableList.prepend(\"a\")), MutableList.make(\"a\"))\n  })\n\n  it(\"empty\", () => {\n    deepStrictEqual(Array.from(MutableList.empty<number>()), [])\n  })\n\n  it(\"fromIterable\", () => {\n    deepStrictEqual(Array.from(MutableList.fromIterable([])), [])\n    deepStrictEqual(Array.from(MutableList.fromIterable([1, 2, 3])), [1, 2, 3])\n  })\n\n  it(\"make\", () => {\n    deepStrictEqual(Array.from(MutableList.make()), [])\n    deepStrictEqual(Array.from(MutableList.make(1, 2, 3)), [1, 2, 3])\n  })\n\n  it(\"isEmpty\", () => {\n    assertTrue(MutableList.isEmpty(MutableList.empty<number>()))\n    assertFalse(MutableList.isEmpty(MutableList.make(1, 2, 3)))\n  })\n\n  it(\"length\", () => {\n    strictEqual(MutableList.length(MutableList.empty<number>()), 0)\n    strictEqual(MutableList.length(MutableList.make(1, 2, 3)), 3)\n  })\n\n  it(\"tail\", () => {\n    strictEqual(MutableList.tail(MutableList.make()), undefined)\n    deepStrictEqual(MutableList.tail(MutableList.make(1, 2, 3)), 3)\n  })\n\n  it(\"head\", () => {\n    strictEqual(MutableList.head(MutableList.make()), undefined)\n    deepStrictEqual(MutableList.head(MutableList.make(1, 2, 3)), 1)\n  })\n\n  it(\"forEach\", () => {\n    const accumulator: Array<number> = []\n    const list = MutableList.make(1, 2, 3)\n    pipe(\n      list,\n      MutableList.forEach((n) => {\n        accumulator.push(n * 2)\n      })\n    )\n\n    deepStrictEqual(Array.from(list), [1, 2, 3])\n    deepStrictEqual(accumulator, [2, 4, 6])\n  })\n\n  it(\"reset\", () => {\n    const list = MutableList.make(1, 2, 3)\n    deepStrictEqual(Array.from(list), [1, 2, 3])\n    deepStrictEqual(Array.from(MutableList.reset(list)), [])\n  })\n\n  it(\"append\", () => {\n    const list = pipe(\n      MutableList.empty<number>(),\n      MutableList.append(1),\n      MutableList.append(2),\n      MutableList.append(3)\n    )\n\n    deepStrictEqual(Array.from(list), [1, 2, 3])\n  })\n\n  it(\"shift\", () => {\n    const list = MutableList.make(1, 2, 3)\n    strictEqual(MutableList.shift(list), 1)\n    strictEqual(MutableList.shift(list), 2)\n    strictEqual(MutableList.shift(list), 3)\n    strictEqual(MutableList.shift(list), undefined)\n  })\n\n  it(\"pop\", () => {\n    const list = MutableList.make(1, 2, 3)\n    strictEqual(MutableList.pop(list), 3)\n    strictEqual(MutableList.pop(list), 2)\n    strictEqual(MutableList.pop(list), 1)\n    strictEqual(MutableList.pop(list), undefined)\n  })\n\n  it(\"prepend\", () => {\n    const list = pipe(\n      MutableList.empty<number>(),\n      MutableList.prepend(1),\n      MutableList.prepend(2),\n      MutableList.prepend(3),\n      MutableList.append(4)\n    )\n    deepStrictEqual(Array.from(list), [3, 2, 1, 4])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/MutableQueue.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { MutableQueue } from \"effect\"\n\ndescribe(\"MutableQueue\", () => {\n  it(\"toString\", () => {\n    const queue = MutableQueue.bounded<number>(2)\n    MutableQueue.offerAll([0, 1, 2])(queue)\n    strictEqual(\n      String(queue),\n      `{\n  \"_id\": \"MutableQueue\",\n  \"values\": [\n    0,\n    1\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    const queue = MutableQueue.bounded<number>(2)\n    MutableQueue.offerAll([0, 1, 2])(queue)\n    deepStrictEqual(queue.toJSON(), { _id: \"MutableQueue\", values: [0, 1] })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n    const queue = MutableQueue.bounded<number>(2)\n    MutableQueue.offerAll([0, 1, 2])(queue)\n    deepStrictEqual(inspect(queue), inspect({ _id: \"MutableQueue\", values: [0, 1] }))\n  })\n\n  describe(\"bounded\", () => {\n    it(\"length\", () => {\n      const queue = MutableQueue.bounded<number>(2)\n      strictEqual(MutableQueue.length(queue), 0)\n      MutableQueue.offerAll([0, 1, 2, 3, 4, 5])(queue)\n      strictEqual(MutableQueue.length(queue), 2)\n    })\n\n    it(\"isEmpty\", () => {\n      const queue = MutableQueue.bounded<number>(2)\n      assertTrue(MutableQueue.isEmpty(queue))\n      MutableQueue.offerAll([1, 2, 3])(queue)\n      assertFalse(MutableQueue.isEmpty(queue))\n    })\n\n    it(\"isFull\", () => {\n      const queue = MutableQueue.bounded<number>(2)\n      assertFalse(MutableQueue.isFull(queue))\n      MutableQueue.offer(0)(queue)\n      assertFalse(MutableQueue.isFull(queue))\n      MutableQueue.offer(1)(queue)\n      assertTrue(MutableQueue.isFull(queue))\n    })\n\n    it(\"offer\", () => {\n      const queue = MutableQueue.bounded<number>(2)\n      MutableQueue.offer(0)(queue)\n      MutableQueue.offer(1)(queue)\n      MutableQueue.offer(2)(queue)\n\n      deepStrictEqual(Array.from(queue), [0, 1])\n    })\n\n    it(\"offerAll\", () => {\n      const queue = MutableQueue.bounded<number>(2)\n      const remainder = MutableQueue.offerAll([0, 1, 2, 3, 4, 5])(queue)\n\n      deepStrictEqual(Array.from(queue), [0, 1])\n      deepStrictEqual(Array.from(remainder), [2, 3, 4, 5])\n    })\n\n    it(\"poll\", () => {\n      const queue = MutableQueue.bounded<number>(2)\n      strictEqual(\n        MutableQueue.poll(MutableQueue.EmptyMutableQueue)(queue),\n        MutableQueue.EmptyMutableQueue\n      )\n      MutableQueue.offer(0)(queue)\n      strictEqual(MutableQueue.poll(MutableQueue.EmptyMutableQueue)(queue), 0)\n    })\n\n    it(\"pollUpTo\", () => {\n      const queue = MutableQueue.bounded<number>(5)\n      deepStrictEqual(Array.from(MutableQueue.pollUpTo(2)(queue)), [])\n      MutableQueue.offerAll([1, 2, 3, 4, 5])(queue)\n      strictEqual(MutableQueue.length(queue), 5)\n      deepStrictEqual(Array.from(MutableQueue.pollUpTo(2)(queue)), [1, 2])\n      strictEqual(MutableQueue.length(queue), 3)\n    })\n  })\n\n  describe(\"unbounded\", () => {\n    it(\"capacity\", () => {\n      const queue = MutableQueue.unbounded<number>()\n\n      strictEqual(MutableQueue.capacity(queue), Infinity)\n    })\n\n    it(\"length\", () => {\n      const queue = MutableQueue.unbounded<number>()\n      strictEqual(MutableQueue.length(queue), 0)\n      MutableQueue.offerAll([0, 1, 2, 3, 4, 5])(queue)\n      strictEqual(MutableQueue.length(queue), 6)\n    })\n\n    it(\"isEmpty\", () => {\n      const queue = MutableQueue.unbounded<number>()\n      assertTrue(MutableQueue.isEmpty(queue))\n      MutableQueue.offerAll([1, 2, 3])(queue)\n      assertFalse(MutableQueue.isEmpty(queue))\n    })\n\n    it(\"isFull\", () => {\n      const queue = MutableQueue.unbounded<number>()\n      assertFalse(MutableQueue.isFull(queue))\n      MutableQueue.offer(0)(queue)\n      assertFalse(MutableQueue.isFull(queue))\n      MutableQueue.offer(1)(queue)\n      assertFalse(MutableQueue.isFull(queue))\n    })\n\n    it(\"offer\", () => {\n      const queue = MutableQueue.unbounded<number>()\n      MutableQueue.offer(0)(queue)\n      MutableQueue.offer(1)(queue)\n      MutableQueue.offer(2)(queue)\n\n      deepStrictEqual(Array.from(queue), [0, 1, 2])\n    })\n\n    it(\"offerAll\", () => {\n      const queue = MutableQueue.unbounded<number>()\n      const remainder = MutableQueue.offerAll([0, 1, 2, 3, 4, 5])(queue)\n\n      deepStrictEqual(Array.from(queue), [0, 1, 2, 3, 4, 5])\n      deepStrictEqual(Array.from(remainder), [])\n    })\n\n    it(\"poll\", () => {\n      const queue = MutableQueue.unbounded<number>()\n      strictEqual(\n        MutableQueue.poll(MutableQueue.EmptyMutableQueue)(queue),\n        MutableQueue.EmptyMutableQueue\n      )\n      MutableQueue.offer(0)(queue)\n      strictEqual(MutableQueue.poll(MutableQueue.EmptyMutableQueue)(queue), 0)\n    })\n\n    it(\"pollUpTo\", () => {\n      const queue = MutableQueue.unbounded<number>()\n      deepStrictEqual(Array.from(MutableQueue.pollUpTo(2)(queue)), [])\n      MutableQueue.offerAll([1, 2, 3, 4, 5])(queue)\n      strictEqual(MutableQueue.length(queue), 5)\n      deepStrictEqual(Array.from(MutableQueue.pollUpTo(2)(queue)), [1, 2])\n      strictEqual(MutableQueue.length(queue), 3)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/MutableRef.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Chunk, MutableRef } from \"effect\"\n\ndescribe(\"MutableRef\", () => {\n  it(\"toString\", () => {\n    strictEqual(\n      String(MutableRef.make(Chunk.make(1, 2, 3))),\n      `{\n  \"_id\": \"MutableRef\",\n  \"current\": {\n    \"_id\": \"Chunk\",\n    \"values\": [\n      1,\n      2,\n      3\n    ]\n  }\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    deepStrictEqual(MutableRef.make(Chunk.make(1, 2, 3)).toJSON(), {\n      _id: \"MutableRef\",\n      current: { _id: \"Chunk\", values: [1, 2, 3] }\n    })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n    deepStrictEqual(\n      inspect(MutableRef.make(Chunk.make(1, 2, 3))),\n      inspect({ _id: \"MutableRef\", current: { _id: \"Chunk\", values: [1, 2, 3] } })\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/NonEmptyIterable.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual, throws } from \"@effect/vitest/utils\"\nimport { Chunk, NonEmptyIterable } from \"effect\"\n\ndescribe(\"NonEmptyIterable\", () => {\n  it(\"should get head and rest\", () => {\n    const [head, rest] = NonEmptyIterable.unprepend(Chunk.make(0, 1, 2))\n    const restArray: Array<number> = []\n    let next = rest.next()\n    while (!next.done) {\n      restArray.push(next.value)\n      next = rest.next()\n    }\n    strictEqual(head, 0)\n    deepStrictEqual(restArray, [1, 2])\n  })\n  it(\"should throw\", () => {\n    throws(() => NonEmptyIterable.unprepend(Chunk.empty as any))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Number.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertNone, assertSome, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport { Number, pipe } from \"effect\"\n\ndescribe(\"Number\", () => {\n  it(\"isNumber\", () => {\n    assertTrue(Number.isNumber(1))\n    assertFalse(Number.isNumber(\"a\"))\n    assertFalse(Number.isNumber(true))\n  })\n\n  it(\"sum\", () => {\n    strictEqual(pipe(1, Number.sum(2)), 3)\n  })\n\n  it(\"multiply\", () => {\n    strictEqual(pipe(2, Number.multiply(3)), 6)\n  })\n\n  it(\"subtract\", () => {\n    strictEqual(pipe(3, Number.subtract(1)), 2)\n  })\n\n  it(\"divide\", () => {\n    assertSome(pipe(6, Number.divide(2)), 3)\n    assertNone(pipe(6, Number.divide(0)))\n  })\n\n  it(\"unsafeDivide\", () => {\n    const six = 6 as const\n    const two = 2 as const\n\n    strictEqual(pipe(six, Number.unsafeDivide(two)), Number.unsafeDivide(six, two))\n\n    strictEqual(pipe(six, Number.unsafeDivide(two)), 3)\n    strictEqual(pipe(six, Number.unsafeDivide(two)), 3)\n\n    strictEqual(Number.unsafeDivide(0, six), 0)\n    strictEqual(\n      Number.unsafeDivide(six, 0),\n      Infinity\n    )\n    strictEqual(\n      Number.unsafeDivide(0, 0),\n      NaN\n    )\n  })\n\n  it(\"decrement\", () => {\n    strictEqual(Number.decrement(3.14), 2.14)\n\n    strictEqual(Number.decrement(-0.69314), -1.69314)\n\n    strictEqual(\n      pipe(\n        100,\n        Number.decrement,\n        Number.decrement,\n        Number.decrement,\n        Number.decrement,\n        Number.decrement,\n        Number.decrement,\n        Number.decrement\n      ),\n      93\n    )\n  })\n\n  it(\"Equivalence\", () => {\n    assertTrue(Number.Equivalence(1, 1))\n    assertFalse(Number.Equivalence(1, 2))\n  })\n\n  it(\"Order\", () => {\n    strictEqual(Number.Order(1, 2), -1)\n    strictEqual(Number.Order(2, 1), 1)\n    strictEqual(Number.Order(2, 2), 0)\n  })\n\n  it(\"sign\", () => {\n    strictEqual(Number.sign(0), 0)\n    strictEqual(Number.sign(0.0), 0)\n    strictEqual(Number.sign(-0.1), -1)\n    strictEqual(Number.sign(-10), -1)\n    strictEqual(Number.sign(10), 1)\n    strictEqual(Number.sign(0.1), 1)\n  })\n\n  it(\"remainder\", () => {\n    strictEqual(Number.remainder(2, 2), 0)\n    strictEqual(Number.remainder(3, 2), 1)\n    strictEqual(Number.remainder(4, 2), 0)\n    strictEqual(Number.remainder(2.5, 2), 0.5)\n    strictEqual(Number.remainder(-2, 2), -0)\n    strictEqual(Number.remainder(-3, 2), -1)\n    strictEqual(Number.remainder(-4, 2), -0)\n    strictEqual(Number.remainder(-2.8, -.2), -0)\n    strictEqual(Number.remainder(-2, -.2), -0)\n    strictEqual(Number.remainder(-1.5, -.2), -0.1)\n    strictEqual(Number.remainder(0, -.2), 0)\n    strictEqual(Number.remainder(1, -.2), 0)\n    strictEqual(Number.remainder(2.6, -.2), 0)\n    strictEqual(Number.remainder(3.1, -.2), 0.1)\n  })\n\n  it(\"lessThan\", () => {\n    assertTrue(Number.lessThan(2, 3))\n    assertFalse(Number.lessThan(3, 3))\n    assertFalse(Number.lessThan(4, 3))\n  })\n\n  it(\"lessThanOrEqualTo\", () => {\n    assertTrue(Number.lessThanOrEqualTo(2, 3))\n    assertTrue(Number.lessThanOrEqualTo(3, 3))\n    assertFalse(Number.lessThanOrEqualTo(4, 3))\n  })\n\n  it(\"greaterThan\", () => {\n    assertFalse(Number.greaterThan(2, 3))\n    assertFalse(Number.greaterThan(3, 3))\n    assertTrue(Number.greaterThan(4, 3))\n  })\n\n  it(\"greaterThanOrEqualTo\", () => {\n    assertFalse(Number.greaterThanOrEqualTo(2, 3))\n    assertTrue(Number.greaterThanOrEqualTo(3, 3))\n    assertTrue(Number.greaterThanOrEqualTo(4, 3))\n  })\n\n  it(\"between\", () => {\n    assertTrue(Number.between({ minimum: 0, maximum: 5 })(3))\n    assertFalse(Number.between({ minimum: 0, maximum: 5 })(-1))\n    assertFalse(Number.between({ minimum: 0, maximum: 5 })(6))\n\n    assertTrue(Number.between(3, { minimum: 0, maximum: 5 }))\n  })\n\n  it(\"clamp\", () => {\n    strictEqual(Number.clamp({ minimum: 0, maximum: 5 })(3), 3)\n    strictEqual(Number.clamp({ minimum: 0, maximum: 5 })(-1), 0)\n    strictEqual(Number.clamp({ minimum: 0, maximum: 5 })(6), 5)\n  })\n\n  it(\"min\", () => {\n    strictEqual(Number.min(2, 3), 2)\n  })\n\n  it(\"max\", () => {\n    strictEqual(Number.max(2, 3), 3)\n  })\n\n  it(\"sumAll\", () => {\n    strictEqual(Number.sumAll([2, 3, 4]), 9)\n    strictEqual(Number.sumAll([]), 0)\n  })\n\n  it(\"multiplyAll\", () => {\n    strictEqual(Number.multiplyAll([2, 0, 4]), 0)\n    strictEqual(Number.multiplyAll([]), 1)\n    strictEqual(Number.multiplyAll([2, 3, 4]), 24)\n  })\n\n  describe(\"nextPow2\", () => {\n    // Positive integers test cases\n    it(\"calculates the next power of 2 for positive integers\", () => {\n      // Examples from documentation\n      strictEqual(Number.nextPow2(5), 2 ** 3) // 8\n      strictEqual(Number.nextPow2(17), 2 ** 5) // 32\n\n      // Additional positive integer cases\n      strictEqual(Number.nextPow2(1), 2 ** 1) // 2\n      strictEqual(Number.nextPow2(2), 2 ** 1) // 2\n      strictEqual(Number.nextPow2(3), 2 ** 2) // 4\n      strictEqual(Number.nextPow2(4), 2 ** 2) // 4\n      strictEqual(Number.nextPow2(7), 2 ** 3) // 8\n      strictEqual(Number.nextPow2(8), 2 ** 3) // 8\n      strictEqual(Number.nextPow2(9), 2 ** 4) // 16\n      strictEqual(Number.nextPow2(15), 2 ** 4) // 16\n      strictEqual(Number.nextPow2(16), 2 ** 4) // 16\n      strictEqual(Number.nextPow2(100), 2 ** 7) // 128\n      strictEqual(Number.nextPow2(1000), 2 ** 10) // 1024\n    })\n\n    // Positive non-integer test cases\n    it(\"calculates the next power of 2 for positive non-integers\", () => {\n      strictEqual(Number.nextPow2(0.1), 2 ** 1) // 2\n      strictEqual(Number.nextPow2(0.5), 2 ** 1) // 2\n      strictEqual(Number.nextPow2(1.5), 2 ** 1) // 2\n      strictEqual(Number.nextPow2(2.1), 2 ** 2) // 4\n      strictEqual(Number.nextPow2(3.99), 2 ** 2) // 4\n      strictEqual(Number.nextPow2(4.01), 2 ** 3) // 8\n    })\n\n    // Zero test case\n    it(\"returns 2 for zero input\", () => {\n      strictEqual(Number.nextPow2(0), 2 ** 1) // 2\n    })\n\n    // Negative input test cases\n    it(\"returns NaN for negative inputs\", () => {\n      // Document the current behavior: negative inputs produce NaN\n      strictEqual(isNaN(Number.nextPow2(-1)), true)\n      strictEqual(isNaN(Number.nextPow2(-5)), true)\n      strictEqual(isNaN(Number.nextPow2(-10)), true)\n      strictEqual(isNaN(Number.nextPow2(-100)), true)\n    })\n\n    // Special values test cases\n    it(\"handles special values as expected\", () => {\n      // NaN input produces NaN output\n      strictEqual(isNaN(Number.nextPow2(NaN)), true)\n\n      // Infinity input produces Infinity output\n      strictEqual(Number.nextPow2(Infinity), Infinity)\n\n      // Negative Infinity produces NaN\n      strictEqual(isNaN(Number.nextPow2(-Infinity)), true)\n    })\n\n    // Mathematical property test\n    it(\"preserves mathematical properties for valid inputs\", () => {\n      // Test on valid inputs (non-negative numbers)\n      const validInputs = [0, 0.3, 1, 2, 3.5, 7, 10, 15.9, 32.1, 100.1, 1000]\n\n      for (const val of validInputs) {\n        const result = Number.nextPow2(val)\n\n        // Result should be an integer\n        strictEqual(Math.floor(result), result, `Result for ${val} should be an integer`)\n\n        // Result should be positive\n        strictEqual(result > 0, true, `Result for ${val} should be positive`)\n\n        // Result should be a power of 2 (a number is a power of 2 if only one bit is set)\n        strictEqual((result & (result - 1)) === 0, true, `Result for ${val} should be a power of 2`)\n\n        // Result should be at least 2\n        strictEqual(result >= 2, true, `Result for ${val} should be at least 2`)\n\n        // Result should be >= input (for all non-negative inputs)\n        strictEqual(result >= val, true, `Result for ${val} should be >= input`)\n      }\n    })\n  })\n\n  it(\"parse\", () => {\n    assertSome(Number.parse(\"NaN\"), NaN)\n    assertSome(Number.parse(\"Infinity\"), Infinity)\n    assertSome(Number.parse(\"-Infinity\"), -Infinity)\n    assertSome(Number.parse(\"42\"), 42)\n    assertNone(Number.parse(\"a\"))\n  })\n\n  it(\"round\", () => {\n    strictEqual(Number.round(1.1234, 2), 1.12)\n    strictEqual(Number.round(2)(1.1234), 1.12)\n    strictEqual(Number.round(0)(1.1234), 1)\n    strictEqual(Number.round(0)(1.1234), 1)\n    strictEqual(Number.round(1.567, 2), 1.57)\n    strictEqual(Number.round(2)(1.567), 1.57)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Option.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertNone,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { Chunk, Either, Equal, Hash, Number as N, Option, pipe, String as S } from \"effect\"\n\nconst gt2 = (n: number): boolean => n > 2\n\ndescribe(\"Option\", () => {\n  it(\"gen\", () => {\n    const a = Option.gen(function*() {\n      const x = yield* Option.some(1)\n      const y = yield* Option.some(2)\n      return x + y\n    })\n    const b = Option.gen(function*() {\n      return 10\n    })\n    const c = Option.gen(function*() {\n      yield* Option.some(1)\n      yield* Option.some(2)\n    })\n    const d = Option.gen(function*() {\n      yield* Option.some(1)\n      return yield* Option.some(2)\n    })\n    const e = Option.gen(function*() {\n      yield* Option.some(1)\n      yield* Option.none()\n      return yield* Option.some(2)\n    })\n    const f = Option.gen(function*() {\n      yield* Option.none()\n    })\n    const g = Option.gen({ ctx: \"testContext\" as const }, function*() {\n      return yield* Option.some(this.ctx)\n    })\n    // TODO(4.0) remove this test\n    // test adapter\n    const h = Option.gen(function*($) {\n      const x = yield* $(Option.some(1))\n      const y = yield* $(Option.some(2))\n      return x + y\n    })\n\n    assertSome(a, 3)\n    assertSome(b, 10)\n    assertSome(c, undefined)\n    assertSome(d, 2)\n    assertNone(e)\n    assertNone(f)\n    assertSome(g, \"testContext\")\n    assertSome(h, 3)\n  })\n\n  it(\"toString\", () => {\n    strictEqual(\n      String(Option.none()),\n      `{\n  \"_id\": \"Option\",\n  \"_tag\": \"None\"\n}`\n    )\n    strictEqual(\n      String(Option.some(1)),\n      `{\n  \"_id\": \"Option\",\n  \"_tag\": \"Some\",\n  \"value\": 1\n}`\n    )\n    strictEqual(\n      String(Option.some(Chunk.make(1, 2, 3))),\n      `{\n  \"_id\": \"Option\",\n  \"_tag\": \"Some\",\n  \"value\": {\n    \"_id\": \"Chunk\",\n    \"values\": [\n      1,\n      2,\n      3\n    ]\n  }\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    deepStrictEqual(Option.none().toJSON(), { _id: \"Option\", _tag: \"None\" })\n    deepStrictEqual(Option.some(1).toJSON(), { _id: \"Option\", _tag: \"Some\", value: 1 })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n    deepStrictEqual(inspect(Option.none()), inspect({ _id: \"Option\", _tag: \"None\" }))\n    deepStrictEqual(inspect(Option.some(1)), inspect({ _id: \"Option\", _tag: \"Some\", value: 1 }))\n  })\n\n  it(\"Equal\", () => {\n    assertTrue(Equal.equals(Option.some(1), Option.some(1)))\n    assertFalse(Equal.equals(Option.some(1), Option.some(2)))\n    assertTrue(Equal.equals(Option.none(), Option.none()))\n  })\n\n  it(\"Hash\", () => {\n    strictEqual(Hash.hash(Option.some(1)), Hash.hash(Option.some(1)))\n    strictEqual(Hash.hash(Option.some(1)) === Hash.hash(Option.some(2)), false)\n    strictEqual(Hash.hash(Option.none()), Hash.hash(Option.none()))\n  })\n\n  it(\"getRight\", () => {\n    assertSome(Option.getRight(Either.right(1)), 1)\n    assertNone(Option.getRight(Either.left(\"a\")))\n  })\n\n  it(\"getLeft\", () => {\n    assertNone(Option.getLeft(Either.right(1)))\n    assertSome(Option.getLeft(Either.left(\"a\")), \"a\")\n  })\n\n  it(\"toRefinement\", () => {\n    const f = (\n      s: string | number\n    ): Option.Option<string> => (typeof s === \"string\" ? Option.some(s) : Option.none())\n    const isString = Option.toRefinement(f)\n\n    assertTrue(isString(\"s\"))\n    assertFalse(isString(1))\n\n    type A = { readonly type: \"A\" }\n    type B = { readonly type: \"B\" }\n    type C = A | B\n    const isA = Option.toRefinement<C, A>((c) => (c.type === \"A\" ? Option.some(c) : Option.none()))\n\n    assertTrue(isA({ type: \"A\" }))\n    assertFalse(isA({ type: \"B\" }))\n  })\n\n  it(\"isOption\", () => {\n    assertTrue(pipe(Option.some(1), Option.isOption))\n    assertTrue(pipe(Option.none(), Option.isOption))\n    assertFalse(pipe(Either.right(1), Option.isOption))\n  })\n\n  it(\"firstSomeOf\", () => {\n    assertNone(Option.firstSomeOf([]))\n    assertSome(Option.firstSomeOf([Option.some(1)]), 1)\n    assertNone(Option.firstSomeOf([Option.none()]))\n    assertSome(\n      Option.firstSomeOf([Option.none(), Option.none(), Option.none(), Option.none(), Option.some(1)]),\n      1\n    )\n    assertNone(\n      Option.firstSomeOf([Option.none(), Option.none(), Option.none(), Option.none()])\n    )\n  })\n\n  it(\"orElseEither\", () => {\n    assertSome(pipe(Option.some(1), Option.orElseEither(() => Option.some(2))), Either.left(1))\n    assertSome(pipe(Option.some(1), Option.orElseEither(() => Option.none())), Either.left(1))\n    assertSome(pipe(Option.none(), Option.orElseEither(() => Option.some(2))), Either.right(2))\n    assertNone(pipe(Option.none(), Option.orElseEither(() => Option.none())))\n  })\n\n  it(\"orElseSome\", () => {\n    assertSome(pipe(Option.some(1), Option.orElseSome(() => 2)), 1)\n    assertSome(pipe(Option.none(), Option.orElseSome(() => 2)), 2)\n  })\n\n  it(\"getOrThrow\", () => {\n    strictEqual(pipe(Option.some(1), Option.getOrThrow), 1)\n    throws(() => pipe(Option.none(), Option.getOrThrow), new Error(\"getOrThrow called on a None\"))\n  })\n\n  it(\"getOrThrowWith\", () => {\n    strictEqual(pipe(Option.some(1), Option.getOrThrowWith(() => new Error(\"Unexpected None\"))), 1)\n    throws(\n      () => pipe(Option.none(), Option.getOrThrowWith(() => new Error(\"Unexpected None\"))),\n      new Error(\"Unexpected None\")\n    )\n  })\n\n  it(\"unit\", () => {\n    assertSome(Option.void, undefined)\n  })\n\n  it(\"product\", () => {\n    const product = Option.product\n    assertNone(product(Option.none(), Option.none()))\n    assertNone(product(Option.some(1), Option.none()))\n    assertNone(product(Option.none(), Option.some(\"a\")))\n    assertSome(product(Option.some(1), Option.some(\"a\")), [1, \"a\"])\n  })\n\n  it(\"productMany\", () => {\n    const productMany = Option.productMany\n    assertNone(productMany(Option.none(), []))\n    assertSome(productMany(Option.some(1), []), [1])\n    assertNone(productMany(Option.some(1), [Option.none()]))\n    assertSome(productMany(Option.some(1), [Option.some(2)]), [1, 2])\n  })\n\n  it(\"fromIterable\", () => {\n    assertNone(Option.fromIterable([]))\n    assertSome(Option.fromIterable([\"a\"]), \"a\")\n  })\n\n  it(\"map\", () => {\n    assertSome(pipe(Option.some(2), Option.map((n) => n * 2)), 4)\n    assertNone(pipe(Option.none(), Option.map((n) => n * 2)))\n  })\n\n  it(\"flatMap\", () => {\n    const f = (n: number) => Option.some(n * 2)\n    const g = () => Option.none()\n    assertSome(pipe(Option.some(1), Option.flatMap(f)), 2)\n    assertNone(pipe(Option.none(), Option.flatMap(f)))\n    assertNone(pipe(Option.some(1), Option.flatMap(g)))\n    assertNone(pipe(Option.none(), Option.flatMap(g)))\n  })\n\n  it(\"andThen\", () => {\n    assertSome(pipe(Option.some(1), Option.andThen(() => Option.some(2))), 2)\n    assertSome(pipe(Option.some(1), Option.andThen(Option.some(2))), 2)\n    assertSome(pipe(Option.some(1), Option.andThen(2)), 2)\n    assertSome(pipe(Option.some(1), Option.andThen(() => 2)), 2)\n    assertSome(pipe(Option.some(1), Option.andThen((a) => a)), 1)\n    assertSome(Option.andThen(Option.some(1), () => Option.some(2)), 2)\n    assertSome(Option.andThen(Option.some(1), Option.some(2)), 2)\n    assertSome(Option.andThen(Option.some(1), 2), 2)\n    assertSome(Option.andThen(Option.some(1), () => 2), 2)\n    assertSome(Option.andThen(Option.some(1), (a) => a), 1)\n  })\n\n  it(\"orElse\", () => {\n    const assertOrElse = (\n      a: Option.Option<number>,\n      b: Option.Option<number>,\n      expected: Option.Option<number>\n    ) => {\n      deepStrictEqual(pipe(a, Option.orElse(() => b)), expected)\n    }\n    assertOrElse(Option.some(1), Option.some(2), Option.some(1))\n    assertOrElse(Option.some(1), Option.none(), Option.some(1))\n    assertOrElse(Option.none(), Option.some(2), Option.some(2))\n    assertOrElse(Option.none(), Option.none(), Option.none())\n  })\n\n  it(\"partitionMap\", () => {\n    const f = (n: number) => (gt2(n) ? Either.right(n + 1) : Either.left(n - 1))\n    deepStrictEqual(pipe(Option.none(), Option.partitionMap(f)), [Option.none(), Option.none()])\n    deepStrictEqual(pipe(Option.some(1), Option.partitionMap(f)), [Option.some(0), Option.none()])\n    deepStrictEqual(pipe(Option.some(3), Option.partitionMap(f)), [Option.none(), Option.some(4)])\n  })\n\n  it(\"filterMap\", () => {\n    const f = (n: number) => (gt2(n) ? Option.some(n + 1) : Option.none())\n    assertNone(pipe(Option.none(), Option.filterMap(f)))\n    assertNone(pipe(Option.some(1), Option.filterMap(f)))\n    assertSome(pipe(Option.some(3), Option.filterMap(f)), 4)\n  })\n\n  it(\"match\", () => {\n    const onNone = () => \"none\"\n    const onSome = (s: string) => `some${s.length}`\n    const match = Option.match({ onNone, onSome })\n    strictEqual(match(Option.none()), \"none\")\n    strictEqual(match(Option.some(\"abc\")), \"some3\")\n  })\n\n  it(\"getOrElse\", () => {\n    strictEqual(pipe(Option.some(1), Option.getOrElse(() => 0)), 1)\n    strictEqual(pipe(Option.none(), Option.getOrElse(() => 0)), 0)\n  })\n\n  it(\"getOrNull\", () => {\n    strictEqual(Option.getOrNull(Option.none()), null)\n    strictEqual(Option.getOrNull(Option.some(1)), 1)\n  })\n\n  it(\"getOrUndefined\", () => {\n    strictEqual(Option.getOrUndefined(Option.none()), undefined)\n    strictEqual(Option.getOrUndefined(Option.some(1)), 1)\n  })\n\n  it(\"getOrder\", () => {\n    const OS = Option.getOrder(S.Order)\n    strictEqual(OS(Option.none(), Option.none()), 0)\n    strictEqual(OS(Option.some(\"a\"), Option.none()), 1)\n    strictEqual(OS(Option.none(), Option.some(\"a\")), -1)\n    strictEqual(OS(Option.some(\"a\"), Option.some(\"a\")), 0)\n    strictEqual(OS(Option.some(\"a\"), Option.some(\"b\")), -1)\n    strictEqual(OS(Option.some(\"b\"), Option.some(\"a\")), 1)\n  })\n\n  it(\"flatMapNullable\", () => {\n    interface X {\n      readonly a?: {\n        readonly b?: {\n          readonly c?: {\n            readonly d: number\n          }\n        }\n      }\n    }\n    const x1: X = { a: {} }\n    const x2: X = { a: { b: {} } }\n    const x3: X = { a: { b: { c: { d: 1 } } } }\n    assertNone(\n      pipe(\n        Option.fromNullable(x1.a),\n        Option.flatMapNullable((x) => x.b),\n        Option.flatMapNullable((x) => x.c),\n        Option.flatMapNullable((x) => x.d)\n      )\n    )\n    assertNone(\n      pipe(\n        Option.fromNullable(x2.a),\n        Option.flatMapNullable((x) => x.b),\n        Option.flatMapNullable((x) => x.c),\n        Option.flatMapNullable((x) => x.d)\n      )\n    )\n    assertSome(\n      pipe(\n        Option.fromNullable(x3.a),\n        Option.flatMapNullable((x) => x.b),\n        Option.flatMapNullable((x) => x.c),\n        Option.flatMapNullable((x) => x.d)\n      ),\n      1\n    )\n  })\n\n  it(\"fromNullable\", () => {\n    assertSome(Option.fromNullable(2), 2)\n    assertNone(Option.fromNullable(null))\n    assertNone(Option.fromNullable(undefined))\n  })\n\n  it(\"liftPredicate\", () => {\n    assertNone(pipe(1, Option.liftPredicate(gt2)))\n    assertSome(pipe(3, Option.liftPredicate(gt2)), 3)\n    assertNone(Option.liftPredicate(1, gt2))\n    assertSome(Option.liftPredicate(3, gt2), 3)\n\n    type Direction = \"asc\" | \"desc\"\n    const isDirection = (s: string): s is Direction => s === \"asc\" || s === \"desc\"\n    assertSome(pipe(\"asc\", Option.liftPredicate(isDirection)), \"asc\")\n    assertNone(pipe(\"foo\", Option.liftPredicate(isDirection)))\n    assertSome(Option.liftPredicate(\"asc\", isDirection), \"asc\")\n    assertNone(Option.liftPredicate(\"foo\", isDirection))\n  })\n\n  it(\"containsWith\", () => {\n    const containsWith = Option.containsWith<number>((self, that) => self % 2 === that % 2)\n    assertTrue(pipe(Option.some(2), containsWith(2)))\n    assertTrue(pipe(Option.some(4), containsWith(4)))\n    assertTrue(pipe(Option.some(1), containsWith(3)))\n\n    assertFalse(pipe(Option.none(), containsWith(2)))\n    assertFalse(pipe(Option.some(2), containsWith(1)))\n  })\n\n  it(\"contains\", () => {\n    assertFalse(pipe(Option.none(), Option.contains(2)))\n    assertTrue(pipe(Option.some(2), Option.contains(2)))\n    assertFalse(pipe(Option.some(2), Option.contains(1)))\n  })\n\n  it(\"isNone\", () => {\n    assertTrue(Option.isNone(Option.none()))\n    assertFalse(Option.isNone(Option.some(1)))\n  })\n\n  it(\"isSome\", () => {\n    assertFalse(Option.isSome(Option.none()))\n    assertTrue(Option.isSome(Option.some(1)))\n  })\n\n  it(\"exists\", () => {\n    const predicate = (a: number) => a === 2\n    assertFalse(pipe(Option.none(), Option.exists(predicate)))\n    assertFalse(pipe(Option.some(1), Option.exists(predicate)))\n    assertTrue(pipe(Option.some(2), Option.exists(predicate)))\n  })\n\n  it(\"liftNullable\", () => {\n    const f = Option.liftNullable((n: number) => (n > 0 ? n : null))\n    assertSome(f(1), 1)\n    assertNone(f(-1))\n  })\n\n  it(\"liftThrowable\", () => {\n    const parse = Option.liftThrowable(JSON.parse)\n    assertSome(parse(\"1\"), 1)\n    assertNone(parse(\"\"))\n  })\n\n  it(\"tap\", () => {\n    assertNone(Option.tap(Option.none(), () => Option.none()))\n    assertNone(Option.tap(Option.some(1), () => Option.none()))\n    assertNone(Option.tap(Option.none(), (n) => Option.some(n * 2)))\n    assertSome(Option.tap(Option.some(1), (n) => Option.some(n * 2)), 1)\n  })\n\n  it(\"guard\", () => {\n    assertSome(\n      pipe(\n        Option.Do,\n        Option.bind(\"x\", () => Option.some(\"a\")),\n        Option.bind(\"y\", () => Option.some(\"a\")),\n        Option.filter(({ x, y }) => x === y)\n      ),\n      { x: \"a\", y: \"a\" }\n    )\n    assertNone(\n      pipe(\n        Option.Do,\n        Option.bind(\"x\", () => Option.some(\"a\")),\n        Option.bind(\"y\", () => Option.some(\"b\")),\n        Option.filter(({ x, y }) => x === y)\n      )\n    )\n  })\n\n  it(\"zipWith\", () => {\n    assertNone(pipe(Option.none(), Option.zipWith(Option.some(2), (a, b) => a + b)))\n    assertNone(pipe(Option.some(1), Option.zipWith(Option.none(), (a, b) => a + b)))\n    assertSome(pipe(Option.some(1), Option.zipWith(Option.some(2), (a, b) => a + b)), 3)\n  })\n\n  it(\"ap\", () => {\n    assertNone(\n      pipe(Option.some((a: number) => (b: number) => a + b), Option.ap(Option.none()), Option.ap(Option.some(2)))\n    )\n    assertNone(\n      pipe(Option.some((a: number) => (b: number) => a + b), Option.ap(Option.some(1)), Option.ap(Option.none()))\n    )\n    assertSome(\n      pipe(Option.some((a: number) => (b: number) => a + b), Option.ap(Option.some(1)), Option.ap(Option.some(2))),\n      3\n    )\n  })\n\n  it(\"reduceCompact\", () => {\n    const sumCompact = Option.reduceCompact(0, N.sum)\n    strictEqual(sumCompact([]), 0)\n    strictEqual(sumCompact([Option.some(2), Option.some(3)]), 5)\n    strictEqual(sumCompact([Option.some(2), Option.none(), Option.some(3)]), 5)\n  })\n\n  it(\"getEquivalence\", () => {\n    const isEquivalent = Option.getEquivalence(N.Equivalence)\n    assertTrue(isEquivalent(Option.none(), Option.none()))\n    assertFalse(isEquivalent(Option.none(), Option.some(1)))\n    assertFalse(isEquivalent(Option.some(1), Option.none()))\n    assertFalse(isEquivalent(Option.some(2), Option.some(1)))\n    assertFalse(isEquivalent(Option.some(1), Option.some(2)))\n    assertTrue(isEquivalent(Option.some(2), Option.some(2)))\n  })\n\n  it(\"all/ tuple\", () => {\n    assertSome(Option.all([]), [])\n    assertSome(Option.all([Option.some(1), Option.some(\"hello\")]), [1, \"hello\"])\n    assertNone(Option.all([Option.some(1), Option.none()]))\n  })\n\n  it(\"all/ iterable\", () => {\n    assertSome(Option.all([]), [])\n    assertNone(Option.all([Option.none()]))\n    assertSome(Option.all([Option.some(1), Option.some(2)]), [1, 2])\n    assertSome(Option.all(new Set([Option.some(1), Option.some(2)])), [1, 2])\n    assertNone(Option.all([Option.some(1), Option.none()]))\n  })\n\n  it(\"all/ struct\", () => {\n    assertSome(\n      Option.all({ a: Option.some(1), b: Option.some(\"hello\") }),\n      { a: 1, b: \"hello\" }\n    )\n    assertNone(Option.all({ a: Option.some(1), b: Option.none() }))\n  })\n\n  it(\".pipe()\", () => {\n    assertSome(Option.some(1).pipe(Option.map((n) => n + 1)), 2)\n  })\n\n  it(\"lift2\", () => {\n    const f = Option.lift2((a: number, b: number): number => a + b)\n    assertNone(f(Option.none(), Option.none()))\n    assertNone(f(Option.some(1), Option.none()))\n    assertNone(f(Option.none(), Option.some(2)))\n    assertSome(f(Option.some(1), Option.some(2)), 3)\n  })\n\n  describe(\"do notation\", () => {\n    it(\"Do\", () => {\n      assertSome(Option.Do, {})\n    })\n\n    it(\"bindTo\", () => {\n      assertSome(pipe(Option.some(1), Option.bindTo(\"a\")), { a: 1 })\n      assertNone(pipe(Option.none(), Option.bindTo(\"a\")))\n      assertSome(\n        pipe(\n          Option.some(1),\n          Option.bindTo(\"__proto__\"),\n          Option.bind(\"x\", () => Option.some(2))\n        ),\n        { x: 2, [\"__proto__\"]: 1 }\n      )\n    })\n\n    it(\"bind\", () => {\n      assertSome(pipe(Option.some(1), Option.bindTo(\"a\"), Option.bind(\"b\", ({ a }) => Option.some(a + 1))), {\n        a: 1,\n        b: 2\n      })\n      assertNone(\n        pipe(Option.some(1), Option.bindTo(\"a\"), Option.bind(\"b\", () => Option.none()))\n      )\n      assertNone(\n        pipe(Option.none(), Option.bindTo(\"a\"), Option.bind(\"b\", () => Option.some(2)))\n      )\n      assertSome(\n        pipe(\n          Option.some(1),\n          Option.bindTo(\"a\"),\n          Option.bind(\"__proto__\", ({ a }) => Option.some(a + 1)),\n          Option.bind(\"b\", ({ a }) => Option.some(a + 1))\n        ),\n        { a: 1, b: 2, [\"__proto__\"]: 2 }\n      )\n    })\n\n    it(\"let\", () => {\n      assertSome(pipe(Option.some(1), Option.bindTo(\"a\"), Option.let(\"b\", ({ a }) => a + 1)), { a: 1, b: 2 })\n      assertNone(\n        pipe(Option.none(), Option.bindTo(\"a\"), Option.let(\"b\", () => 2))\n      )\n      assertSome(\n        pipe(\n          Option.some(1),\n          Option.bindTo(\"a\"),\n          Option.let(\"__proto__\", ({ a }) => a + 1),\n          Option.let(\"b\", ({ a }) => a + 1)\n        ),\n        { a: 1, b: 2, [\"__proto__\"]: 2 }\n      )\n    })\n  })\n\n  it(\"as\", () => {\n    assertNone(Option.none().pipe(Option.as(\"a\")))\n    assertSome(Option.some(1).pipe(Option.as(\"a\")), \"a\")\n\n    assertNone(Option.as(Option.none(), \"a\"))\n    assertSome(Option.as(Option.some(1), \"a\"), \"a\")\n  })\n\n  it(\"asVoid\", () => {\n    assertNone(Option.none().pipe(Option.asVoid))\n    assertSome(Option.some(1).pipe(Option.asVoid), undefined)\n  })\n\n  it(\"[internal] mergeWith\", () => {\n    const mergeWith = Option.mergeWith(N.sum)\n    assertNone(mergeWith(Option.none(), Option.none()))\n    assertSome(mergeWith(Option.some(1), Option.none()), 1)\n    assertSome(mergeWith(Option.none(), Option.some(2)), 2)\n    assertSome(mergeWith(Option.some(1), Option.some(2)), 3)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Order.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Array as Arr, Order, pipe } from \"effect\"\n\ndescribe(\"Order\", () => {\n  it(\"struct\", () => {\n    const O = Order.struct({ a: Order.string, b: Order.string })\n    strictEqual(O({ a: \"a\", b: \"b\" }, { a: \"a\", b: \"c\" }), -1)\n    strictEqual(O({ a: \"a\", b: \"b\" }, { a: \"a\", b: \"b\" }), 0)\n    strictEqual(O({ a: \"a\", b: \"c\" }, { a: \"a\", b: \"b\" }), 1)\n  })\n\n  it(\"tuple\", () => {\n    const O = Order.tuple(Order.string, Order.string)\n    strictEqual(O([\"a\", \"b\"], [\"a\", \"c\"]), -1)\n    strictEqual(O([\"a\", \"b\"], [\"a\", \"b\"]), 0)\n    strictEqual(O([\"a\", \"b\"], [\"a\", \"a\"]), 1)\n    strictEqual(O([\"a\", \"b\"], [\"b\", \"a\"]), -1)\n  })\n\n  it(\"all\", () => {\n    const O = Order.all([Order.string, Order.string, Order.string])\n    strictEqual(O([], []), 0)\n    strictEqual(O([\"a\", \"b\"], [\"a\"]), 0)\n    strictEqual(O([\"a\"], [\"a\", \"c\"]), 0)\n    strictEqual(O([\"a\", \"b\"], [\"a\", \"c\"]), -1)\n    strictEqual(O([\"a\", \"b\"], [\"a\", \"b\"]), 0)\n    strictEqual(O([\"a\", \"b\"], [\"a\", \"a\"]), 1)\n    strictEqual(O([\"a\", \"b\"], [\"b\", \"a\"]), -1)\n  })\n\n  it(\"mapInput\", () => {\n    const O = Order.mapInput(Order.number, (s: string) => s.length)\n    strictEqual(O(\"a\", \"b\"), 0)\n    strictEqual(O(\"a\", \"bb\"), -1)\n    strictEqual(O(\"aa\", \"b\"), 1)\n  })\n\n  it(\"Date\", () => {\n    const O = Order.Date\n    strictEqual(O(new Date(0), new Date(1)), -1)\n    strictEqual(O(new Date(1), new Date(1)), 0)\n    strictEqual(O(new Date(1), new Date(0)), 1)\n  })\n\n  it(\"clamp\", () => {\n    const clamp = Order.clamp(Order.number)({ minimum: 1, maximum: 10 })\n    strictEqual(clamp(2), 2)\n    strictEqual(clamp(10), 10)\n    strictEqual(clamp(20), 10)\n    strictEqual(clamp(1), 1)\n    strictEqual(clamp(-10), 1)\n\n    strictEqual(Order.clamp(Order.number)({ minimum: 1, maximum: 10 })(2), 2)\n  })\n\n  it(\"between\", () => {\n    const between = Order.between(Order.number)({ minimum: 1, maximum: 10 })\n    assertTrue(between(2))\n    assertTrue(between(10))\n    assertFalse(between(20))\n    assertTrue(between(1))\n    assertFalse(between(-10))\n\n    assertTrue(Order.between(Order.number)(2, { minimum: 1, maximum: 10 }))\n  })\n\n  it(\"reverse\", () => {\n    const O = Order.reverse(Order.number)\n    strictEqual(O(1, 2), 1)\n    strictEqual(O(2, 1), -1)\n    strictEqual(O(2, 2), 0)\n  })\n\n  it(\"lessThan\", () => {\n    const lessThan = Order.lessThan(Order.number)\n    assertTrue(lessThan(0, 1))\n    assertFalse(lessThan(1, 1))\n    assertFalse(lessThan(2, 1))\n  })\n\n  it(\"lessThanOrEqualTo\", () => {\n    const lessThanOrEqualTo = Order.lessThanOrEqualTo(Order.number)\n    assertTrue(lessThanOrEqualTo(0, 1))\n    assertTrue(lessThanOrEqualTo(1, 1))\n    assertFalse(lessThanOrEqualTo(2, 1))\n  })\n\n  it(\"greaterThan\", () => {\n    const greaterThan = Order.greaterThan(Order.number)\n    assertFalse(greaterThan(0, 1))\n    assertFalse(greaterThan(1, 1))\n    assertTrue(greaterThan(2, 1))\n  })\n\n  it(\"greaterThanOrEqualTo\", () => {\n    const greaterThanOrEqualTo = Order.greaterThanOrEqualTo(Order.number)\n    assertFalse(greaterThanOrEqualTo(0, 1))\n    assertTrue(greaterThanOrEqualTo(1, 1))\n    assertTrue(greaterThanOrEqualTo(2, 1))\n  })\n\n  it(\"min\", () => {\n    type A = { a: number }\n    const min = Order.min(\n      pipe(\n        Order.number,\n        Order.mapInput((a: A) => a.a)\n      )\n    )\n    deepStrictEqual(min({ a: 1 }, { a: 2 }), { a: 1 })\n    deepStrictEqual(min({ a: 2 }, { a: 1 }), { a: 1 })\n    const first = { a: 1 }\n    const second = { a: 1 }\n    deepStrictEqual(min(first, second), first)\n  })\n\n  it(\"max\", () => {\n    type A = { a: number }\n    const max = Order.max(\n      pipe(\n        Order.number,\n        Order.mapInput((a: A) => a.a)\n      )\n    )\n    deepStrictEqual(max({ a: 1 }, { a: 2 }), { a: 2 })\n    deepStrictEqual(max({ a: 2 }, { a: 1 }), { a: 2 })\n    const first = { a: 1 }\n    const second = { a: 1 }\n    deepStrictEqual(max(first, second), first)\n  })\n\n  it(\"product\", () => {\n    const O = Order.product(Order.string, Order.number)\n    strictEqual(O([\"a\", 1], [\"a\", 2]), -1)\n    strictEqual(O([\"a\", 1], [\"a\", 1]), 0)\n    strictEqual(O([\"a\", 1], [\"a\", 0]), 1)\n    strictEqual(O([\"a\", 1], [\"b\", 1]), -1)\n  })\n\n  it(\"productMany\", () => {\n    const O = Order.productMany(Order.string, [Order.string, Order.string])\n    strictEqual(O([\"a\", \"b\"], [\"a\", \"c\"]), -1)\n    strictEqual(O([\"a\", \"b\"], [\"a\", \"b\"]), 0)\n    strictEqual(O([\"a\", \"b\"], [\"a\", \"a\"]), 1)\n    strictEqual(O([\"a\", \"b\"], [\"b\", \"a\"]), -1)\n  })\n\n  it(\"combine / combineMany\", () => {\n    type T = [number, string]\n    const tuples: Array<T> = [\n      [2, \"c\"],\n      [1, \"b\"],\n      [2, \"a\"],\n      [1, \"c\"]\n    ]\n    const sortByFst = pipe(\n      Order.number,\n      Order.mapInput((x: T) => x[0])\n    )\n    const sortBySnd = pipe(\n      Order.string,\n      Order.mapInput((x: T) => x[1])\n    )\n    deepStrictEqual(Arr.sort(Order.combine(sortByFst, sortBySnd))(tuples), [\n      [1, \"b\"],\n      [1, \"c\"],\n      [2, \"a\"],\n      [2, \"c\"]\n    ])\n    deepStrictEqual(Arr.sort(Order.combine(sortBySnd, sortByFst))(tuples), [\n      [2, \"a\"],\n      [1, \"b\"],\n      [1, \"c\"],\n      [2, \"c\"]\n    ])\n    deepStrictEqual(Arr.sort(Order.combineMany(sortBySnd, []))(tuples), [\n      [2, \"a\"],\n      [1, \"b\"],\n      [2, \"c\"],\n      [1, \"c\"]\n    ])\n    deepStrictEqual(Arr.sort(Order.combineMany(sortBySnd, [sortByFst]))(tuples), [\n      [2, \"a\"],\n      [1, \"b\"],\n      [1, \"c\"],\n      [2, \"c\"]\n    ])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Ordering.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { Ordering } from \"effect\"\n\ndescribe(\"Ordering\", () => {\n  it(\"match\", () => {\n    const f = Ordering.match({\n      onLessThan: () => \"lt\",\n      onEqual: () => \"eq\",\n      onGreaterThan: () => \"gt\"\n    })\n    strictEqual(f(-1), \"lt\")\n    strictEqual(f(0), \"eq\")\n    strictEqual(f(1), \"gt\")\n  })\n\n  it(\"reverse\", () => {\n    strictEqual(Ordering.reverse(-1), 1)\n    strictEqual(Ordering.reverse(0), 0)\n    strictEqual(Ordering.reverse(1), -1)\n  })\n\n  it(\"combine\", () => {\n    strictEqual(Ordering.combine(0, 0), 0)\n    strictEqual(Ordering.combine(0, 1), 1)\n    strictEqual(Ordering.combine(1, -1), 1)\n    strictEqual(Ordering.combine(-1, 1), -1)\n  })\n\n  it(\"combineMany\", () => {\n    strictEqual(Ordering.combineMany(0, []), 0)\n    strictEqual(Ordering.combineMany(1, []), 1)\n    strictEqual(Ordering.combineMany(-1, []), -1)\n    strictEqual(Ordering.combineMany(0, [0, 0, 0]), 0)\n    strictEqual(Ordering.combineMany(0, [0, 0, 1]), 1)\n    strictEqual(Ordering.combineMany(1, [0, 0, -1]), 1)\n    strictEqual(Ordering.combineMany(-1, [0, 0, 1]), -1)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/PartitionedSemaphore.test.ts",
    "content": "import { assert, describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Duration, Effect, Fiber, PartitionedSemaphore, TestClock } from \"effect\"\n\ndescribe(\"PartitionedSemaphore\", () => {\n  it.effect(\"basic single partition operation\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 4 })\n      const messages: Array<string> = []\n\n      yield* Effect.fork(Effect.all(\n        [0, 1, 2, 3].map((n) =>\n          sem.withPermits(\"partition-1\", 2)(\n            Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(`process: ${n}`)))\n          )\n        ),\n        { concurrency: \"unbounded\", discard: true }\n      ))\n\n      yield* TestClock.adjust(Duration.seconds(3))\n      strictEqual(messages.length, 2)\n\n      yield* TestClock.adjust(Duration.seconds(3))\n      strictEqual(messages.length, 4)\n    }))\n\n  it.effect(\"multiple partitions share total permits\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 4 })\n      const messages: Array<string> = []\n\n      yield* Effect.fork(Effect.all([\n        sem.withPermits(\"partition-1\", 2)(\n          Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(\"p1-task1\")))\n        ),\n        sem.withPermits(\"partition-2\", 2)(\n          Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(\"p2-task1\")))\n        ),\n        sem.withPermits(\"partition-1\", 2)(\n          Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(\"p1-task2\")))\n        )\n      ], { concurrency: \"unbounded\", discard: true }))\n\n      yield* TestClock.adjust(Duration.seconds(3))\n      // Only 2 tasks can run simultaneously (4 permits / 2 permits each)\n      strictEqual(messages.length, 2)\n\n      yield* TestClock.adjust(Duration.seconds(3))\n      strictEqual(messages.length, 3)\n    }))\n\n  it.effect(\"round-robin fairness across partitions\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 2 })\n      const messages: Array<string> = []\n\n      // Start with 2 permits taken\n      yield* Effect.fork(\n        sem.withPermits(\"partition-1\", 2)(\n          Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(\"p1-initial\")))\n        )\n      )\n\n      yield* TestClock.adjust(1)\n\n      // Queue 3 tasks from partition-1 (needs 3 permits total)\n      yield* Effect.fork(Effect.all([\n        sem.withPermits(\"partition-1\", 1)(Effect.sync(() => messages.push(\"p1-task1\"))),\n        sem.withPermits(\"partition-1\", 1)(Effect.sync(() => messages.push(\"p1-task2\"))),\n        sem.withPermits(\"partition-1\", 1)(Effect.sync(() => messages.push(\"p1-task3\")))\n      ], { concurrency: \"unbounded\", discard: true }))\n\n      yield* TestClock.adjust(1)\n\n      // Queue 3 tasks from partition-2 (needs 3 permits total)\n      yield* Effect.fork(Effect.all([\n        sem.withPermits(\"partition-2\", 1)(Effect.sync(() => messages.push(\"p2-task1\"))),\n        sem.withPermits(\"partition-2\", 1)(Effect.sync(() => messages.push(\"p2-task2\"))),\n        sem.withPermits(\"partition-2\", 1)(Effect.sync(() => messages.push(\"p2-task3\")))\n      ], { concurrency: \"unbounded\", discard: true }))\n\n      yield* TestClock.adjust(Duration.seconds(3))\n\n      // After initial task completes, permits should be distributed in round-robin fashion\n      // Initial task completes first, then permits alternate between partitions\n      deepStrictEqual(messages, [\n        \"p1-initial\",\n        \"p1-task1\",\n        \"p2-task1\",\n        \"p1-task2\",\n        \"p2-task2\",\n        \"p1-task3\",\n        \"p2-task3\"\n      ])\n    }))\n\n  it.effect(\"requesting more permits than total returns never\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 4 })\n\n      const fiber = yield* Effect.fork(\n        sem.withPermits(\"partition-1\", 5)(Effect.succeed(42))\n      )\n\n      yield* TestClock.adjust(Duration.seconds(10))\n\n      // Should still be running (never completes)\n      assert.isNull(fiber.unsafePoll())\n    }))\n\n  it.effect(\"single permit operations\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 1 })\n      const messages: Array<string> = []\n\n      yield* Effect.fork(Effect.all(\n        [0, 1, 2].map((n) =>\n          sem.withPermits(\"partition-1\", 1)(\n            Effect.delay(Duration.seconds(1))(Effect.sync(() => messages.push(`task: ${n}`)))\n          )\n        ),\n        { concurrency: \"unbounded\", discard: true }\n      ))\n\n      yield* TestClock.adjust(Duration.seconds(1.5))\n      strictEqual(messages.length, 1)\n\n      yield* TestClock.adjust(Duration.seconds(1))\n      strictEqual(messages.length, 2)\n\n      yield* TestClock.adjust(Duration.seconds(1))\n      strictEqual(messages.length, 3)\n    }))\n\n  it.effect(\"different permit sizes on same partition\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 5 })\n      const messages: Array<string> = []\n\n      yield* Effect.fork(Effect.all([\n        sem.withPermits(\"partition-1\", 3)(\n          Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(\"large\")))\n        ),\n        sem.withPermits(\"partition-1\", 1)(\n          Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(\"small-1\")))\n        ),\n        sem.withPermits(\"partition-1\", 1)(\n          Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(\"small-2\")))\n        )\n      ], { concurrency: \"unbounded\", discard: true }))\n\n      yield* TestClock.adjust(Duration.seconds(3))\n      // All can run simultaneously (3 + 1 + 1 = 5 permits)\n      strictEqual(messages.length, 3)\n    }))\n\n  it.effect(\"interruption releases permits\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 2 })\n      const messages: Array<string> = []\n\n      const fiber = yield* Effect.fork(\n        sem.withPermits(\"partition-1\", 2)(\n          Effect.delay(Duration.seconds(10))(Effect.sync(() => messages.push(\"long-task\")))\n        )\n      )\n\n      yield* TestClock.adjust(Duration.seconds(1))\n\n      // Interrupt the long-running task\n      yield* Fiber.interrupt(fiber)\n\n      // Now we should be able to acquire permits again\n      yield* sem.withPermits(\"partition-1\", 2)(\n        Effect.sync(() => messages.push(\"after-interrupt\"))\n      )\n\n      strictEqual(messages.length, 1)\n      strictEqual(messages[0], \"after-interrupt\")\n    }))\n\n  it.effect(\"interruption with partial permit acquisition releases all taken permits\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 3 })\n      const messages: Array<string> = []\n\n      // First task takes 2 permits, leaving 1 available\n      const fiber1 = yield* Effect.fork(\n        sem.withPermits(\"partition-1\", 2)(\n          Effect.delay(Duration.seconds(5))(Effect.sync(() => messages.push(\"first\")))\n        )\n      )\n\n      yield* TestClock.adjust(Duration.millis(1))\n\n      // Second task requests 3 permits\n      // It should take the 1 available permit and wait for 2 more\n      const fiber2 = yield* Effect.fork(\n        sem.withPermits(\"partition-2\", 3)(\n          Effect.sync(() => messages.push(\"second\"))\n        )\n      )\n\n      yield* TestClock.adjust(Duration.millis(1))\n\n      // At this point:\n      // - Task 1 has taken 2 permits (running)\n      // - Task 2 has taken 1 permit and is waiting for 2 more\n      // - Total available: 0\n\n      // Interrupt the second task while it's waiting with 1 permit taken\n      yield* Fiber.interrupt(fiber2)\n\n      // The interrupted task should release its partially taken permit (1)\n      // Total available should now be 1\n\n      // Verify we can acquire 1 permit now (proves the partial permit was released)\n      yield* sem.withPermits(\"partition-3\", 1)(\n        Effect.sync(() => messages.push(\"can-acquire-one\"))\n      )\n\n      strictEqual(messages.length, 1)\n      deepStrictEqual(messages, [\"can-acquire-one\"])\n\n      yield* TestClock.adjust(Duration.seconds(5))\n\n      // Wait for first task to complete\n      yield* Fiber.join(fiber1)\n\n      deepStrictEqual(messages, [\"can-acquire-one\", \"first\"])\n\n      // Now all 3 permits should be available again\n      yield* sem.withPermits(\"partition-4\", 3)(\n        Effect.sync(() => messages.push(\"all-three\"))\n      )\n\n      deepStrictEqual(messages, [\"can-acquire-one\", \"first\", \"all-three\"])\n    }))\n\n  it.effect(\"exact permit match\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 4 })\n      const messages: Array<string> = []\n\n      yield* Effect.fork(Effect.all([\n        sem.withPermits(\"partition-1\", 4)(\n          Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(\"exact-match\")))\n        ),\n        sem.withPermits(\"partition-2\", 1)(\n          Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(\"waiting\")))\n        )\n      ], { concurrency: \"unbounded\", discard: true }))\n\n      yield* TestClock.adjust(Duration.seconds(3))\n      // First task takes all permits\n      strictEqual(messages.length, 1)\n      strictEqual(messages[0], \"exact-match\")\n\n      yield* TestClock.adjust(Duration.seconds(3))\n      // Second task runs after first completes\n      strictEqual(messages.length, 2)\n    }))\n\n  it.effect(\"many partitions\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 3 })\n      const messages: Array<string> = []\n\n      yield* Effect.fork(Effect.all(\n        Array.from({ length: 10 }, (_, i) =>\n          sem.withPermits(`partition-${i % 5}`, 1)(\n            Effect.delay(Duration.seconds(1))(Effect.sync(() => messages.push(`p${i % 5}-task`)))\n          )),\n        { concurrency: \"unbounded\", discard: true }\n      ))\n\n      yield* TestClock.adjust(Duration.seconds(1.5))\n      // 3 permits allow 3 concurrent tasks\n      strictEqual(messages.length, 3)\n\n      yield* TestClock.adjust(Duration.seconds(1))\n      strictEqual(messages.length, 6)\n\n      yield* TestClock.adjust(Duration.seconds(1))\n      strictEqual(messages.length, 9)\n\n      yield* TestClock.adjust(Duration.seconds(1))\n      strictEqual(messages.length, 10)\n    }))\n\n  it.effect(\"partial permit allocation\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 3 })\n      const messages: Array<string> = []\n\n      // First task takes 2 permits\n      yield* Effect.fork(\n        sem.withPermits(\"partition-1\", 2)(\n          Effect.delay(Duration.seconds(2))(Effect.sync(() => messages.push(\"first\")))\n        )\n      )\n\n      yield* TestClock.adjust(Duration.millis(100))\n\n      // Second task needs 2 permits, but only 1 available\n      // It should take the 1 available and wait for 1 more\n      const fiber = yield* Effect.fork(\n        sem.withPermits(\"partition-2\", 2)(\n          Effect.sync(() => messages.push(\"second\"))\n        )\n      )\n\n      yield* TestClock.adjust(Duration.millis(100))\n\n      // Second task should not have completed yet\n      assert.isNull(fiber.unsafePoll())\n      strictEqual(messages.length, 0)\n\n      yield* TestClock.adjust(Duration.seconds(3))\n\n      // After first task completes, second should run\n      strictEqual(messages.length, 2)\n      deepStrictEqual(messages, [\"first\", \"second\"])\n    }))\n\n  it.effect(\"zero permits requested\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 2 })\n      let executed = false\n\n      yield* sem.withPermits(\"partition-1\", 0)(\n        Effect.sync(() => {\n          executed = true\n        })\n      )\n\n      assert.isTrue(executed)\n    }))\n\n  it.effect(\"sequential tasks in same partition\", () =>\n    Effect.gen(function*() {\n      const sem = yield* PartitionedSemaphore.make({ permits: 2 })\n      const messages: Array<string> = []\n\n      yield* sem.withPermits(\"partition-1\", 2)(\n        Effect.sync(() => messages.push(\"task-1\"))\n      )\n\n      yield* sem.withPermits(\"partition-1\", 2)(\n        Effect.sync(() => messages.push(\"task-2\"))\n      )\n\n      yield* sem.withPermits(\"partition-1\", 2)(\n        Effect.sync(() => messages.push(\"task-3\"))\n      )\n\n      deepStrictEqual(messages, [\"task-1\", \"task-2\", \"task-3\"])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Pipeable.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInstanceOf, assertSome, deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Option, Pipeable } from \"effect\"\n\ndescribe(\"Pipeable\", () => {\n  it(\"pipeArguments\", () => {\n    const f = (n: number): number => n + 1\n    const g = (n: number): number => n * 2\n    assertSome(Option.some(2).pipe(Option.map(f)), 3)\n    assertSome(Option.some(2).pipe(Option.map(f), Option.map(g)), 6)\n    assertSome(Option.some(2).pipe(Option.map(f), Option.map(g), Option.map(f)), 7)\n    assertSome(Option.some(2).pipe(Option.map(f), Option.map(g), Option.map(f), Option.map(g)), 14)\n    assertSome(Option.some(2).pipe(Option.map(f), Option.map(g), Option.map(f), Option.map(g), Option.map(f)), 15)\n    assertSome(\n      Option.some(2).pipe(Option.map(f), Option.map(g), Option.map(f), Option.map(g), Option.map(f), Option.map(g)),\n      30\n    )\n    assertSome(\n      Option.some(2).pipe(\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g),\n        Option.map(f)\n      ),\n      31\n    )\n    assertSome(\n      Option.some(2).pipe(\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g)\n      ),\n      62\n    )\n    assertSome(\n      Option.some(2).pipe(\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g),\n        Option.map(f)\n      ),\n      63\n    )\n    assertSome(\n      Option.some(2).pipe(\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g),\n        Option.map(f),\n        Option.map(g)\n      ),\n      126\n    )\n  })\n  it(\"pipeable\", () => {\n    class A {\n      constructor(public a: number) {}\n      methodA() {\n        return this.a\n      }\n    }\n    class B extends Pipeable.Class(A) {\n      constructor(private b: string) {\n        super(b.length)\n      }\n      methodB() {\n        return [this.b, this.methodA()]\n      }\n    }\n    const b = new B(\"bb\")\n\n    assertInstanceOf(b, A)\n    assertInstanceOf(b, B)\n    deepStrictEqual(b.methodB(), [\"bb\", 2])\n    deepStrictEqual(b.pipe((x) => x.methodB()), [\"bb\", 2])\n  })\n  it(\"Class\", () => {\n    class A extends Pipeable.Class() {\n      constructor(public a: number) {\n        super()\n      }\n      methodA() {\n        return this.a\n      }\n    }\n    const a = new A(2)\n\n    assertInstanceOf(a, A)\n    assertInstanceOf(a, Pipeable.Class())\n    deepStrictEqual(a.methodA(), 2)\n    deepStrictEqual(a.pipe((x) => x.methodA()), 2)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Pool.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Deferred, Duration, Effect, Exit, Fiber, pipe, Pool, Ref, Scope, TestClock, TestServices } from \"effect\"\n\ndescribe(\"Pool\", () => {\n  it.scoped(\"preallocates pool items\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      yield* Pool.make({ acquire: get, size: 10 })\n      yield* Effect.repeat(Ref.get(count), { until: (n) => n === 10 })\n      const result = yield* Ref.get(count)\n      strictEqual(result, 10)\n    }))\n\n  // it.scoped(\"benchmark\", () =>\n  //   Effect.gen(function*() {\n  //     const get = Effect.succeed(\"resource\")\n  //     const pool = yield* Pool.make({ acquire: get, size: 10 })\n  //     yield* Pool.get(pool).pipe(\n  //       Effect.scoped,\n  //       Effect.repeatN(10000),\n  //       Console.withTime(\"Pool.get\")\n  //     )\n  //   }))\n\n  it.scoped(\"cleans up items when shut down\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const scope = yield* Scope.make()\n      yield* Scope.extend(Pool.make({ acquire: get, size: 10 }), scope)\n      yield* Effect.repeat(Ref.get(count), { until: (n) => n === 10 })\n      yield* Scope.close(scope, Exit.succeed(void 0))\n      const result = yield* Ref.get(count)\n      strictEqual(result, 0)\n    }))\n\n  it.scoped(\"defects don't prevent cleanup\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Effect.zipRight(Ref.update(count, (n) => n - 1), Effect.die(\"boom\"))\n      )\n      const scope = yield* Scope.make()\n      yield* Scope.extend(Pool.make({ acquire: get, size: 10 }), scope)\n      yield* Effect.repeat(Ref.get(count), { until: (n) => n === 10 })\n      yield* Scope.close(scope, Exit.succeed(void 0))\n      const result = yield* Ref.get(count)\n      strictEqual(result, 0)\n    }))\n\n  it.scoped(\"acquire one item\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const pool = yield* Pool.make({ acquire: get, size: 10 })\n      yield* Effect.repeat(Ref.get(count), { until: (n) => n === 10 })\n      const item = yield* Pool.get(pool)\n      strictEqual(item, 1)\n    }))\n\n  it.scoped(\"reports failures via get\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Effect.flatMap(\n          Ref.updateAndGet(count, (n) => n + 1),\n          Effect.fail\n        ),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const pool = yield* Pool.make({ acquire: get, size: 10 })\n      const values = yield* Effect.all(Effect.replicate(9)(Effect.flip(Pool.get(pool))))\n      deepStrictEqual(Array.from(values), [1, 2, 3, 4, 5, 6, 7, 8, 9])\n    }))\n\n  it.scoped(\"blocks when item not available\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const pool = yield* Pool.make({ acquire: get, size: 10 })\n      yield* Effect.repeat(Ref.get(count), { until: (n) => n === 10 })\n      yield* Effect.all(Effect.replicate(10)(Pool.get(pool)))\n      const result = yield* TestServices.provideLive(\n        Effect.scoped(Pool.get(pool)).pipe(\n          Effect.disconnect,\n          Effect.timeout(Duration.millis(1)),\n          Effect.option\n        )\n      )\n      assertNone(result)\n    }))\n\n  it.scoped(\"reuse released items\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const pool = yield* Pool.make({ acquire: get, size: 10 })\n      yield* Effect.repeatN(99)(Effect.scoped(Pool.get(pool)))\n      const result = yield* Ref.get(count)\n      strictEqual(result, 10)\n    }))\n\n  it.scoped(\"invalidate item\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const pool = yield* Pool.make({ acquire: get, size: 10 })\n      yield* Effect.repeat(Ref.get(count), { until: (n) => n === 10 })\n      yield* Pool.invalidate(pool, 1)\n      yield* Effect.repeat(Ref.get(count), { until: (n) => n === 10 })\n      const result = yield* Effect.scoped(Pool.get(pool))\n      const value = yield* Ref.get(count)\n      strictEqual(result, 2)\n      strictEqual(value, 10)\n    }))\n\n  it.scoped(\"invalidate all items in pool and check that pool.get doesn't hang forever\", () =>\n    Effect.gen(function*() {\n      const allocated = yield* Ref.make(0)\n      const finalized = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(allocated, (n) => n + 1),\n        () => Ref.update(finalized, (n) => n + 1)\n      )\n      const pool = yield* Pool.make({ acquire: get, size: 2 })\n      yield* Effect.repeat(Ref.get(allocated), { until: (n) => n === 2 })\n      yield* Pool.invalidate(pool, 1)\n      yield* Pool.invalidate(pool, 2)\n      const result = yield* Effect.scoped(Pool.get(pool))\n      const allocatedCount = yield* Ref.get(allocated)\n      const finalizedCount = yield* Ref.get(finalized)\n      strictEqual(result, 3)\n      strictEqual(allocatedCount, 4)\n      strictEqual(finalizedCount, 2)\n    }))\n\n  it.scoped(\"retry on failed acquire should not exhaust pool\", () =>\n    Effect.gen(function*() {\n      const acquire = Effect.as(Effect.fail(\"error\"), 1)\n      const pool = yield* Pool.makeWithTTL({ acquire, min: 0, max: 1, timeToLive: Duration.infinity })\n      const result = yield* pipe(\n        Effect.scoped(Effect.retry(Pool.get(pool), { times: 5 })),\n        Effect.timeoutFail({\n          onTimeout: () => \"timeout\",\n          duration: Duration.seconds(1)\n        }),\n        Effect.flip,\n        TestServices.provideLive\n      )\n      strictEqual(result, \"error\")\n    }))\n\n  it.scoped(\"compositional retry\", () =>\n    Effect.gen(function*() {\n      const cond = (i: number) => (i <= 10 ? Effect.fail(i) : Effect.succeed(i))\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1).pipe(\n          Effect.flatMap(cond)\n        ),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const pool = yield* Pool.make({ acquire: get, size: 10 })\n      const result = yield* Effect.eventually(Effect.scoped(Pool.get(pool)))\n      strictEqual(result, 11)\n    }))\n\n  it.scoped(\"max pool size\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<void>()\n      const count = yield* Ref.make(0)\n      const acquire = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const pool = yield* Pool.makeWithTTL({\n        acquire,\n        min: 10,\n        max: 15,\n        timeToLive: Duration.seconds(60)\n      })\n      yield* pipe(\n        Effect.scoped(Effect.zipRight(\n          Pool.get(pool),\n          Deferred.await(deferred)\n        )),\n        Effect.fork,\n        Effect.repeatN(14)\n      )\n      yield* Effect.repeat(Ref.get(count), { until: (n) => n === 15 })\n      yield* Deferred.succeed(deferred, void 0)\n      const max = yield* Ref.get(count)\n      yield* TestClock.adjust(Duration.seconds(60))\n      const min = yield* Ref.get(count)\n      strictEqual(min, 10)\n      strictEqual(max, 15)\n    }))\n\n  it.scoped(\"max pool size with concurrency: 3\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<void>()\n      const count = yield* Ref.make(0)\n      const acquire = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const pool = yield* Pool.makeWithTTL({\n        acquire,\n        min: 10,\n        max: 15,\n        concurrency: 3,\n        timeToLive: Duration.seconds(60)\n      })\n      yield* pipe(\n        Effect.scoped(Effect.zipRight(\n          Pool.get(pool),\n          Deferred.await(deferred)\n        )),\n        Effect.fork,\n        Effect.repeatN(14 * 3)\n      )\n      yield* Effect.repeat(Ref.get(count), { until: (n) => n === 15 })\n      yield* Deferred.succeed(deferred, void 0)\n      const max = yield* Ref.get(count)\n      yield* TestClock.adjust(Duration.seconds(60))\n      const min = yield* Ref.get(count)\n      strictEqual(min, 10)\n      strictEqual(max, 15)\n    }))\n\n  it.scoped(\"concurrency reclaim\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const acquire = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const pool = yield* Pool.makeWithTTL({\n        acquire,\n        min: 0,\n        max: 2,\n        concurrency: 2,\n        timeToLive: Duration.seconds(60)\n      })\n\n      const scope1 = yield* Scope.make()\n      yield* Scope.extend(Pool.get(pool), scope1)\n      yield* Pool.get(pool)\n      yield* Effect.scoped(Pool.get(pool))\n      yield* TestClock.adjust(Duration.seconds(60))\n      yield* Scope.close(scope1, Exit.void)\n      yield* Pool.get(pool)\n      yield* Pool.get(pool)\n      strictEqual(yield* Pool.get(pool), 1)\n      strictEqual(yield* Ref.get(count), 2)\n    }))\n\n  it.scoped(\"scale to zero\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<void>()\n      const count = yield* Ref.make(0)\n      const acquire = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const pool = yield* Pool.makeWithTTL({\n        acquire,\n        min: 0,\n        max: 10,\n        concurrency: 3,\n        timeToLive: Duration.seconds(60)\n      })\n      yield* pipe(\n        Effect.scoped(Effect.zipRight(\n          Pool.get(pool),\n          Deferred.await(deferred)\n        )),\n        Effect.fork,\n        Effect.repeatN(29)\n      )\n      yield* Effect.repeat(Ref.get(count), { until: (n) => n === 10 })\n      yield* Deferred.succeed(deferred, void 0)\n      const max = yield* Ref.get(count)\n      yield* TestClock.adjust(Duration.seconds(60))\n      const min = yield* Ref.get(count)\n      strictEqual(min, 0)\n      strictEqual(max, 10)\n    }))\n\n  it.scoped(\"max pool size creation strategy\", () =>\n    Effect.gen(function*() {\n      const invalidated = yield* Ref.make(0)\n      const acquire = Effect.acquireRelease(\n        Effect.succeed(\"resource\"),\n        () => Ref.update(invalidated, (n) => n + 1)\n      )\n      const pool = yield* Pool.makeWithTTL({\n        acquire,\n        min: 10,\n        max: 15,\n        timeToLive: Duration.seconds(60),\n        timeToLiveStrategy: \"creation\"\n      })\n      const scope = yield* Scope.make()\n      yield* Pool.get(pool).pipe(\n        Effect.repeatN(14),\n        Scope.extend(scope)\n      )\n      const one = yield* Ref.get(invalidated)\n      yield* TestClock.adjust(Duration.seconds(60))\n      const two = yield* Ref.get(invalidated)\n      yield* Scope.close(scope, Exit.void)\n      const three = yield* Ref.get(invalidated)\n      strictEqual(one, 0)\n      strictEqual(two, 0)\n      strictEqual(three, 15)\n    }))\n\n  it.scoped(\"shutdown robustness\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const scope = yield* Scope.make()\n      const pool = yield* Scope.extend(Pool.make({ acquire: get, size: 10 }), scope)\n      yield* pipe(\n        Effect.scoped(Pool.get(pool)),\n        Effect.fork,\n        Effect.repeatN(99)\n      )\n      yield* Scope.close(scope, Exit.succeed(void 0))\n      const result = yield* Effect.repeat(Ref.get(count), { until: (n) => n === 0 })\n      strictEqual(result, 0)\n    }))\n\n  it.scoped(\"shutdown with pending takers\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const scope = yield* Scope.make()\n      const pool = yield* Scope.extend(Pool.make({ acquire: get, size: 10 }), scope)\n      yield* pipe(\n        Pool.get(pool),\n        Scope.extend(scope),\n        Effect.fork,\n        Effect.repeatN(99)\n      )\n      yield* Scope.close(scope, Exit.succeed(void 0))\n      const result = yield* Effect.repeat(Ref.get(count), { until: (n) => n === 0 })\n      strictEqual(result, 0)\n    }))\n\n  it.scoped(\"get is interruptible\", () =>\n    Effect.gen(function*() {\n      const count = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(count, (n) => n + 1),\n        () => Ref.update(count, (n) => n - 1)\n      )\n      const fiberId = yield* Effect.fiberId\n      const pool = yield* Pool.make({ acquire: get, size: 10 })\n      yield* Effect.repeatN(Pool.get(pool), 9)\n      const fiber = yield* Effect.fork(Pool.get(pool))\n      const result = yield* Fiber.interrupt(fiber)\n      deepStrictEqual(result, Exit.interrupt(fiberId))\n    }))\n\n  it.scoped(\"get is interruptible with dynamic size\", () =>\n    Effect.gen(function*() {\n      const get = Effect.never.pipe(Effect.forkScoped)\n      const fiberId = yield* Effect.fiberId\n      const pool = yield* Pool.makeWithTTL({ acquire: get, min: 0, max: 10, timeToLive: Duration.infinity })\n      yield* Effect.repeatN(Pool.get(pool), 9)\n      const fiber = yield* Effect.fork(Pool.get(pool))\n      const result = yield* Fiber.interrupt(fiber)\n      deepStrictEqual(result, Exit.interrupt(fiberId))\n    }))\n\n  it.scoped(\"finalizer is called for failed allocations\", () =>\n    Effect.gen(function*() {\n      const scope = yield* Scope.make()\n      const allocations = yield* Ref.make(0)\n      const released = yield* Ref.make(0)\n      const get = Effect.acquireRelease(\n        Ref.updateAndGet(allocations, (n) => n + 1),\n        () => Ref.update(released, (n) => n + 1)\n      ).pipe(\n        Effect.andThen(Effect.fail(\"boom\"))\n      )\n      const pool = yield* Pool.make({ acquire: get, size: 10 }).pipe(\n        Scope.extend(scope)\n      )\n      yield* Effect.scoped(pool.get).pipe(\n        Effect.ignore\n      )\n      strictEqual(yield* Ref.get(allocations), 10)\n      strictEqual(yield* Ref.get(released), 10)\n    }))\n\n  it.scoped(\"is subtype of Effect\", () =>\n    Effect.gen(function*() {\n      const pool = yield* Pool.make({\n        acquire: Effect.succeed(1),\n        size: 1\n      })\n      const item = yield* pool\n      strictEqual(item, 1)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Predicate.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport { Function as Fun, pipe, Predicate } from \"effect\"\n\nconst isPositive: Predicate.Predicate<number> = (n) => n > 0\nconst isNegative: Predicate.Predicate<number> = (n) => n < 0\nconst isLessThan2: Predicate.Predicate<number> = (n) => n < 2\nconst isString: Predicate.Refinement<unknown, string> = (u: unknown): u is string => typeof u === \"string\"\n\ninterface NonEmptyStringBrand {\n  readonly NonEmptyString: unique symbol\n}\n\ntype NonEmptyString = string & NonEmptyStringBrand\n\nconst isNonEmptyString: Predicate.Refinement<string, NonEmptyString> = (s): s is NonEmptyString => s.length > 0\n\ndescribe(\"Predicate\", () => {\n  it(\"compose\", () => {\n    const refinement = pipe(isString, Predicate.compose(isNonEmptyString))\n    assertTrue(refinement(\"a\"))\n    assertFalse(refinement(null))\n    assertFalse(refinement(\"\"))\n  })\n\n  it(\"mapInput\", () => {\n    type A = {\n      readonly a: number\n    }\n    const predicate = pipe(\n      isPositive,\n      Predicate.mapInput((a: A) => a.a)\n    )\n    assertFalse(predicate({ a: -1 }))\n    assertFalse(predicate({ a: 0 }))\n    assertTrue(predicate({ a: 1 }))\n  })\n\n  it(\"product\", () => {\n    const product = Predicate.product\n    const p = product(isPositive, isNegative)\n    assertTrue(p([1, -1]))\n    assertFalse(p([1, 1]))\n    assertFalse(p([-1, -1]))\n    assertFalse(p([-1, 1]))\n  })\n\n  it(\"productMany\", () => {\n    const productMany = Predicate.productMany\n    const p = productMany(isPositive, [isNegative])\n    assertTrue(p([1, -1]))\n    assertFalse(p([1, 1]))\n    assertFalse(p([-1, -1]))\n    assertFalse(p([-1, 1]))\n  })\n\n  it(\"tuple\", () => {\n    const p = Predicate.tuple(isPositive, isNegative)\n    assertTrue(p([1, -1]))\n    assertFalse(p([1, 1]))\n    assertFalse(p([-1, -1]))\n    assertFalse(p([-1, 1]))\n  })\n\n  it(\"struct\", () => {\n    const p = Predicate.struct({ a: isPositive, b: isNegative })\n    assertTrue(p({ a: 1, b: -1 }))\n    assertFalse(p({ a: 1, b: 1 }))\n    assertFalse(p({ a: -1, b: -1 }))\n    assertFalse(p({ a: -1, b: 1 }))\n  })\n\n  it(\"all\", () => {\n    const p = Predicate.all([isPositive, isNegative])\n    assertTrue(p([1]))\n    assertTrue(p([1, -1]))\n    assertFalse(p([1, 1]))\n    assertFalse(p([-1, -1]))\n    assertFalse(p([-1, 1]))\n  })\n\n  it(\"not\", () => {\n    const p = Predicate.not(isPositive)\n    assertFalse(p(1))\n    assertTrue(p(0))\n    assertTrue(p(-1))\n  })\n\n  it(\"or\", () => {\n    const p = pipe(isPositive, Predicate.or(isNegative))\n    assertTrue(p(-1))\n    assertTrue(p(1))\n    assertFalse(p(0))\n  })\n\n  it(\"and\", () => {\n    const p = pipe(isPositive, Predicate.and(isLessThan2))\n    assertTrue(p(1))\n    assertFalse(p(-1))\n    assertFalse(p(3))\n  })\n\n  it(\"xor\", () => {\n    assertFalse(pipe(Fun.constTrue, Predicate.xor(Fun.constTrue))(null)) // true xor true = false\n    assertTrue(pipe(Fun.constTrue, Predicate.xor(Fun.constFalse))(null)) // true xor false = true\n    assertTrue(pipe(Fun.constFalse, Predicate.xor(Fun.constTrue))(null)) // false xor true = true\n    assertFalse(pipe(Fun.constFalse, Predicate.xor(Fun.constFalse))(null)) // false xor false = false\n  })\n\n  it(\"eqv\", () => {\n    assertTrue(pipe(Fun.constTrue, Predicate.eqv(Fun.constTrue))(null)) // true eqv true = true\n    assertFalse(pipe(Fun.constTrue, Predicate.eqv(Fun.constFalse))(null)) // true eqv false = false\n    assertFalse(pipe(Fun.constFalse, Predicate.eqv(Fun.constTrue))(null)) // false eqv true = false\n    assertTrue(pipe(Fun.constFalse, Predicate.eqv(Fun.constFalse))(null)) // false eqv false = true\n  })\n\n  it(\"implies\", () => {\n    assertTrue(pipe(Fun.constTrue, Predicate.implies(Fun.constTrue))(null)) // true implies true = true\n    assertFalse(pipe(Fun.constTrue, Predicate.implies(Fun.constFalse))(null)) // true implies false = false\n    assertTrue(pipe(Fun.constFalse, Predicate.implies(Fun.constTrue))(null)) // false implies true = true\n    assertTrue(pipe(Fun.constFalse, Predicate.implies(Fun.constFalse))(null)) // false implies false = true\n  })\n\n  it(\"nor\", () => {\n    assertFalse(pipe(Fun.constTrue, Predicate.nor(Fun.constTrue))(null)) // true nor true = false\n    assertFalse(pipe(Fun.constTrue, Predicate.nor(Fun.constFalse))(null)) // true nor false = false\n    assertFalse(pipe(Fun.constFalse, Predicate.nor(Fun.constTrue))(null)) // false nor true = false\n    assertTrue(pipe(Fun.constFalse, Predicate.nor(Fun.constFalse))(null)) // false nor false = true\n  })\n\n  it(\"nand\", () => {\n    assertFalse(pipe(Fun.constTrue, Predicate.nand(Fun.constTrue))(null)) // true nand true = false\n    assertTrue(pipe(Fun.constTrue, Predicate.nand(Fun.constFalse))(null)) // true nand false = true\n    assertTrue(pipe(Fun.constFalse, Predicate.nand(Fun.constTrue))(null)) // false nand true = true\n    assertTrue(pipe(Fun.constFalse, Predicate.nand(Fun.constFalse))(null)) // false nand false = true\n  })\n\n  it(\"some\", () => {\n    const predicate = Predicate.some([isPositive, isNegative])\n    assertFalse(predicate(0))\n    assertTrue(predicate(-1))\n    assertTrue(predicate(1))\n  })\n\n  it(\"every\", () => {\n    const predicate = Predicate.every([isPositive, isLessThan2])\n    assertFalse(predicate(0))\n    assertFalse(predicate(-2))\n    assertTrue(predicate(1))\n  })\n\n  it(\"isTruthy\", () => {\n    assertTrue(Predicate.isTruthy(true))\n    assertFalse(Predicate.isTruthy(false))\n    assertTrue(Predicate.isTruthy(\"a\"))\n    assertFalse(Predicate.isTruthy(\"\"))\n    assertTrue(Predicate.isTruthy(1))\n    assertFalse(Predicate.isTruthy(0))\n    assertTrue(Predicate.isTruthy(1n))\n    assertFalse(Predicate.isTruthy(0n))\n  })\n\n  it(\"isFunction\", () => {\n    assertTrue(Predicate.isFunction(Predicate.isFunction))\n    assertFalse(Predicate.isFunction(\"function\"))\n  })\n\n  it(\"isUndefined\", () => {\n    assertTrue(Predicate.isUndefined(undefined))\n    assertFalse(Predicate.isUndefined(null))\n    assertFalse(Predicate.isUndefined(\"undefined\"))\n  })\n\n  it(\"isNotUndefined\", () => {\n    assertFalse(Predicate.isNotUndefined(undefined))\n    assertTrue(Predicate.isNotUndefined(null))\n    assertTrue(Predicate.isNotUndefined(\"undefined\"))\n  })\n\n  it(\"isNull\", () => {\n    assertTrue(Predicate.isNull(null))\n    assertFalse(Predicate.isNull(undefined))\n    assertFalse(Predicate.isNull(\"null\"))\n  })\n\n  it(\"isNotNull\", () => {\n    assertFalse(Predicate.isNotNull(null))\n    assertTrue(Predicate.isNotNull(undefined))\n    assertTrue(Predicate.isNotNull(\"null\"))\n  })\n\n  it(\"isNever\", () => {\n    assertFalse(Predicate.isNever(null))\n    assertFalse(Predicate.isNever(undefined))\n    assertFalse(Predicate.isNever({}))\n    assertFalse(Predicate.isNever([]))\n  })\n\n  it(\"isUnknown\", () => {\n    assertTrue(Predicate.isUnknown(null))\n    assertTrue(Predicate.isUnknown(undefined))\n    assertTrue(Predicate.isUnknown({}))\n    assertTrue(Predicate.isUnknown([]))\n  })\n\n  it(\"isObject\", () => {\n    assertTrue(Predicate.isObject({}))\n    assertTrue(Predicate.isObject([]))\n    assertTrue(Predicate.isObject(() => 1))\n    assertFalse(Predicate.isObject(null))\n    assertFalse(Predicate.isObject(undefined))\n    assertFalse(Predicate.isObject(\"a\"))\n    assertFalse(Predicate.isObject(1))\n    assertFalse(Predicate.isObject(true))\n    assertFalse(Predicate.isObject(1n))\n    assertFalse(Predicate.isObject(Symbol.for(\"a\")))\n  })\n\n  it(\"isSet\", () => {\n    assertTrue(Predicate.isSet(new Set([1, 2])))\n    assertTrue(Predicate.isSet(new Set()))\n    assertFalse(Predicate.isSet({}))\n    assertFalse(Predicate.isSet(null))\n    assertFalse(Predicate.isSet(undefined))\n  })\n\n  it(\"isMap\", () => {\n    assertTrue(Predicate.isMap(new Map()))\n    assertFalse(Predicate.isMap({}))\n    assertFalse(Predicate.isMap(null))\n    assertFalse(Predicate.isMap(undefined))\n  })\n\n  it(\"hasProperty\", () => {\n    const a = Symbol.for(\"effect/test/a\")\n\n    assertTrue(Predicate.hasProperty({ a: 1 }, \"a\"))\n    assertTrue(Predicate.hasProperty(\"a\")({ a: 1 }))\n    assertTrue(Predicate.hasProperty({ [a]: 1 }, a))\n    assertTrue(Predicate.hasProperty(a)({ [a]: 1 }))\n\n    assertFalse(Predicate.hasProperty({}, \"a\"))\n    assertFalse(Predicate.hasProperty(null, \"a\"))\n    assertFalse(Predicate.hasProperty(undefined, \"a\"))\n    assertFalse(Predicate.hasProperty({}, \"a\"))\n    assertFalse(Predicate.hasProperty(() => {}, \"a\"))\n\n    assertFalse(Predicate.hasProperty({}, a))\n    assertFalse(Predicate.hasProperty(null, a))\n    assertFalse(Predicate.hasProperty(undefined, a))\n    assertFalse(Predicate.hasProperty({}, a))\n    assertFalse(Predicate.hasProperty(() => {}, a))\n  })\n\n  it(\"isTagged\", () => {\n    assertFalse(Predicate.isTagged(1, \"a\"))\n    assertFalse(Predicate.isTagged(\"\", \"a\"))\n    assertFalse(Predicate.isTagged({}, \"a\"))\n    assertFalse(Predicate.isTagged(\"a\")({}))\n    assertFalse(Predicate.isTagged({ a: \"a\" }, \"a\"))\n    assertTrue(Predicate.isTagged({ _tag: \"a\" }, \"a\"))\n    assertTrue(Predicate.isTagged(\"a\")({ _tag: \"a\" }))\n  })\n\n  it(\"isNullable\", () => {\n    assertTrue(Predicate.isNullable(null))\n    assertTrue(Predicate.isNullable(undefined))\n    assertFalse(Predicate.isNullable({}))\n    assertFalse(Predicate.isNullable([]))\n  })\n\n  it(\"isNotNullable\", () => {\n    assertTrue(Predicate.isNotNullable({}))\n    assertTrue(Predicate.isNotNullable([]))\n    assertFalse(Predicate.isNotNullable(null))\n    assertFalse(Predicate.isNotNullable(undefined))\n  })\n\n  it(\"isError\", () => {\n    assertTrue(Predicate.isError(new Error()))\n    assertFalse(Predicate.isError(null))\n    assertFalse(Predicate.isError({}))\n  })\n\n  it(\"isUint8Array\", () => {\n    assertTrue(Predicate.isUint8Array(new Uint8Array()))\n    assertFalse(Predicate.isUint8Array(null))\n    assertFalse(Predicate.isUint8Array({}))\n  })\n\n  it(\"isDate\", () => {\n    assertTrue(Predicate.isDate(new Date()))\n    assertFalse(Predicate.isDate(null))\n    assertFalse(Predicate.isDate({}))\n  })\n\n  it(\"isIterable\", () => {\n    assertTrue(Predicate.isIterable([]))\n    assertTrue(Predicate.isIterable(new Set()))\n    assertFalse(Predicate.isIterable(null))\n    assertFalse(Predicate.isIterable({}))\n  })\n\n  it(\"isRecord\", () => {\n    assertTrue(Predicate.isRecord({}))\n    assertTrue(Predicate.isRecord({ a: 1 }))\n\n    assertFalse(Predicate.isRecord([]))\n    assertFalse(Predicate.isRecord([1, 2, 3]))\n    assertFalse(Predicate.isRecord(null))\n    assertFalse(Predicate.isRecord(undefined))\n    assertFalse(Predicate.isRecord(() => null))\n  })\n\n  it(\"isReadonlyRecord\", () => {\n    assertTrue(Predicate.isReadonlyRecord({}))\n    assertTrue(Predicate.isReadonlyRecord({ a: 1 }))\n\n    assertFalse(Predicate.isReadonlyRecord([]))\n    assertFalse(Predicate.isReadonlyRecord([1, 2, 3]))\n    assertFalse(Predicate.isReadonlyRecord(null))\n    assertFalse(Predicate.isReadonlyRecord(undefined))\n  })\n\n  it(\"isTupleOf\", () => {\n    assertTrue(Predicate.isTupleOf([1, 2, 3], 3))\n    assertFalse(Predicate.isTupleOf([1, 2, 3], 4))\n    assertFalse(Predicate.isTupleOf([1, 2, 3], 2))\n  })\n\n  it(\"isTupleOfAtLeast\", () => {\n    assertTrue(Predicate.isTupleOfAtLeast([1, 2, 3], 3))\n    assertTrue(Predicate.isTupleOfAtLeast([1, 2, 3], 2))\n    assertFalse(Predicate.isTupleOfAtLeast([1, 2, 3], 4))\n  })\n\n  it(\"isRegExp\", () => {\n    assertTrue(Predicate.isRegExp(/a/))\n    assertFalse(Predicate.isRegExp(null))\n    assertFalse(Predicate.isRegExp(\"a\"))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/PubSub.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertSome, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Array, Chunk, Deferred, Effect, Fiber, pipe, PubSub, Queue } from \"effect\"\n\ndescribe(\"PubSub\", () => {\n  it.effect(\"publishAll - capacity 2 (BoundedPubSubPow2)\", () => {\n    const messages = [1, 2]\n    return PubSub.bounded<number>(2).pipe(\n      Effect.flatMap((pubsub) =>\n        Effect.scoped(\n          Effect.gen(function*() {\n            const dequeue1 = yield* (PubSub.subscribe(pubsub))\n            const dequeue2 = yield* (PubSub.subscribe(pubsub))\n            yield* (PubSub.publishAll(pubsub, messages))\n            const takes1 = yield* (Queue.takeAll(dequeue1))\n            const takes2 = yield* (Queue.takeAll(dequeue2))\n            deepStrictEqual([...takes1], messages)\n            deepStrictEqual([...takes2], messages)\n          })\n        )\n      )\n    )\n  })\n  it.effect(\"publishAll - capacity 4 (BoundedPubSubPow2)\", () => {\n    const messages = [1, 2]\n    return PubSub.bounded<number>(4).pipe(\n      Effect.flatMap((pubsub) =>\n        Effect.scoped(\n          Effect.gen(function*() {\n            const dequeue1 = yield* (PubSub.subscribe(pubsub))\n            const dequeue2 = yield* (PubSub.subscribe(pubsub))\n            yield* (PubSub.publishAll(pubsub, messages))\n            const takes1 = yield* (Queue.takeAll(dequeue1))\n            const takes2 = yield* (Queue.takeAll(dequeue2))\n            deepStrictEqual([...takes1], messages)\n            deepStrictEqual([...takes2], messages)\n          })\n        )\n      )\n    )\n  })\n  it.effect(\"publishAll - capacity 3 (BoundedPubSubArb)\", () => {\n    const messages = [1, 2]\n    return PubSub.bounded<number>(3).pipe(\n      Effect.flatMap((pubsub) =>\n        Effect.scoped(\n          Effect.gen(function*() {\n            const dequeue1 = yield* (PubSub.subscribe(pubsub))\n            const dequeue2 = yield* (PubSub.subscribe(pubsub))\n            yield* (PubSub.publishAll(pubsub, messages))\n            const takes1 = yield* (Queue.takeAll(dequeue1))\n            const takes2 = yield* (Queue.takeAll(dequeue2))\n            deepStrictEqual([...takes1], messages)\n            deepStrictEqual([...takes2], messages)\n          })\n        )\n      )\n    )\n  })\n  it.effect(\"sequential publishers and subscribers with one publisher and one subscriber\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(0, 9)\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.bounded<number>(10)\n      const subscriber = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(Deferred.await(deferred2)),\n            Effect.zipRight(pipe(values, Effect.forEach(() => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred1)\n      yield* pipe(values, Effect.forEach((n) => PubSub.publish(pubsub, n)))\n      yield* Deferred.succeed(deferred2, void 0)\n      const result = yield* Fiber.join(subscriber)\n      deepStrictEqual(result, values)\n    }))\n  it.effect(\"sequential publishers and subscribers with one publisher and two subscribers\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(0, 9)\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const deferred3 = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.bounded<number>(10)\n      const subscriber1 = yield* pubsub.pipe(\n        PubSub.subscribe,\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(Deferred.await(deferred3)),\n            Effect.zipRight(pipe(values, Effect.forEach(() => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      const subscriber2 = yield* pubsub.pipe(\n        PubSub.subscribe,\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred2, void 0),\n            Effect.zipRight(Deferred.await(deferred3)),\n            Effect.zipRight(pipe(values, Effect.forEach(() => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred1)\n      yield* Deferred.await(deferred2)\n      yield* pipe(values, Effect.forEach((n) => PubSub.publish(pubsub, n)))\n      yield* Deferred.succeed(deferred3, undefined)\n      const result1 = yield* Fiber.join(subscriber1)\n      const result2 = yield* Fiber.join(subscriber2)\n      deepStrictEqual(result1, values)\n      deepStrictEqual(result2, values)\n    }))\n  it.effect(\"backpressured concurrent publishers and subscribers - one to one\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(0, 64)\n      const deferred = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.bounded<number>(64)\n      const subscriber = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred)\n      yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      const result = yield* Fiber.join(subscriber)\n      deepStrictEqual(result, values)\n    }))\n  it.effect(\"backpressured concurrent publishers and subscribers - one to many\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(0, 64)\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.bounded<number>(64)\n      const subscriber1 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      const subscriber2 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred2, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred1)\n      yield* Deferred.await(deferred2)\n      yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      const result1 = yield* Fiber.join(subscriber1)\n      const result2 = yield* Fiber.join(subscriber2)\n      deepStrictEqual(result1, values)\n      deepStrictEqual(result2, values)\n    }))\n  it.effect(\"backpressured concurrent publishers and subscribers - many to many\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(1, 64)\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.bounded<number>(64 * 2)\n      const subscriber1 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(pipe(\n              values,\n              Array.appendAll(values),\n              Effect.forEach((_) => Queue.take(subscription))\n            ))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      const subscriber2 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred2, void 0),\n            Effect.zipRight(pipe(\n              values,\n              Array.appendAll(values),\n              Effect.forEach((_) => Queue.take(subscription))\n            ))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred1)\n      yield* Deferred.await(deferred2)\n      const fiber = yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      yield* pipe(values, Array.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork)\n      const result1 = yield* Fiber.join(subscriber1)\n      const result2 = yield* Fiber.join(subscriber2)\n      yield* Fiber.join(fiber)\n      deepStrictEqual(pipe(result1, Array.filter((n) => n > 0)), values)\n      deepStrictEqual(\n        pipe(result1, Array.filter((n) => n < 0)),\n        pipe(values, Array.map((n) => -n))\n      )\n      deepStrictEqual(pipe(result2, Array.filter((n) => n > 0)), values)\n      deepStrictEqual(\n        pipe(result2, Array.filter((n) => n < 0)),\n        pipe(values, Array.map((n) => -n))\n      )\n    }))\n  it.effect(\"dropping concurrent publishers and subscribers - one to one\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(0, 64)\n      const deferred = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.dropping<number>(64)\n      const subscriber = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred)\n      yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      const result = yield* Fiber.join(subscriber)\n      deepStrictEqual(result, values)\n    }))\n  it.effect(\"dropping concurrent publishers and subscribers - one to many\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(0, 64)\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.dropping<number>(64)\n      const subscriber1 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      const subscriber2 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred2, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred1)\n      yield* Deferred.await(deferred2)\n      yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      const result1 = yield* Fiber.join(subscriber1)\n      const result2 = yield* Fiber.join(subscriber2)\n      deepStrictEqual(result1, values)\n      deepStrictEqual(result2, values)\n    }))\n  it.effect(\"dropping concurrent publishers and subscribers - many to many\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(1, 64)\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.dropping<number>(64 * 2)\n      const subscriber1 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(pipe(\n              values,\n              Array.appendAll(values),\n              Effect.forEach((_) => Queue.take(subscription))\n            ))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      const subscriber2 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred2, void 0),\n            Effect.zipRight(pipe(\n              values,\n              Array.appendAll(values),\n              Effect.forEach((_) => Queue.take(subscription))\n            ))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred1)\n      yield* Deferred.await(deferred2)\n      const fiber = yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      yield* pipe(values, Array.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork)\n      const result1 = yield* Fiber.join(subscriber1)\n      const result2 = yield* Fiber.join(subscriber2)\n      yield* Fiber.join(fiber)\n      deepStrictEqual(pipe(result1, Array.filter((n) => n > 0)), values)\n      deepStrictEqual(\n        pipe(result1, Array.filter((n) => n < 0)),\n        pipe(values, Array.map((n) => -n))\n      )\n      deepStrictEqual(pipe(result2, Array.filter((n) => n > 0)), values)\n      deepStrictEqual(\n        pipe(result2, Array.filter((n) => n < 0)),\n        pipe(values, Array.map((n) => -n))\n      )\n    }))\n  it.effect(\"sliding concurrent publishers and subscribers - one to one\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(0, 64)\n      const deferred = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.sliding<number>(64)\n      const subscriber = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred)\n      yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      const result = yield* Fiber.join(subscriber)\n      deepStrictEqual(result, values)\n    }))\n  it.effect(\"sliding concurrent publishers and subscribers - one to many\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(0, 64)\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.sliding<number>(64)\n      const subscriber1 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      const subscriber2 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred2, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred1)\n      yield* Deferred.await(deferred2)\n      yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      const result1 = yield* Fiber.join(subscriber1)\n      const result2 = yield* Fiber.join(subscriber2)\n      deepStrictEqual(result1, values)\n      deepStrictEqual(result2, values)\n    }))\n  it.effect(\"sliding concurrent publishers and subscribers - many to many\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(1, 64)\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.sliding<number>(64 * 2)\n      const subscriber1 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(pipe(\n              values,\n              Array.appendAll(values),\n              Effect.forEach((_) => Queue.take(subscription))\n            ))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      const subscriber2 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred2, void 0),\n            Effect.zipRight(pipe(\n              values,\n              Array.appendAll(values),\n              Effect.forEach((_) => Queue.take(subscription))\n            ))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred1)\n      yield* Deferred.await(deferred2)\n      const fiber = yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      yield* pipe(values, Array.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork)\n      const result1 = yield* Fiber.join(subscriber1)\n      const result2 = yield* Fiber.join(subscriber2)\n      yield* Fiber.join(fiber)\n      deepStrictEqual(pipe(result1, Array.filter((n) => n > 0)), values)\n      deepStrictEqual(\n        pipe(result1, Array.filter((n) => n < 0)),\n        pipe(values, Array.map((n) => -n))\n      )\n      deepStrictEqual(pipe(result2, Array.filter((n) => n > 0)), values)\n      deepStrictEqual(\n        pipe(result2, Array.filter((n) => n < 0)),\n        pipe(values, Array.map((n) => -n))\n      )\n    }))\n  it.effect(\"unbounded concurrent publishers and subscribers - one to one\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(0, 64)\n      const deferred = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.unbounded<number>()\n      const subscriber = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred)\n      yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n\n      const result = yield* Fiber.join(subscriber)\n      deepStrictEqual(result, values)\n    }))\n  it.effect(\"unbounded concurrent publishers and subscribers - one to many\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(0, 64)\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.unbounded<number>()\n      const subscriber1 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      const subscriber2 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred2, void 0),\n            Effect.zipRight(pipe(values, Effect.forEach((_) => Queue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred1)\n      yield* Deferred.await(deferred2)\n      yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      const result1 = yield* Fiber.join(subscriber1)\n      const result2 = yield* Fiber.join(subscriber2)\n      deepStrictEqual(result1, values)\n      deepStrictEqual(result2, values)\n    }))\n  it.effect(\"unbounded concurrent publishers and subscribers - many to many\", () =>\n    Effect.gen(function*() {\n      const values = Array.range(1, 64)\n      const deferred1 = yield* Deferred.make<void>()\n      const deferred2 = yield* Deferred.make<void>()\n      const pubsub = yield* PubSub.unbounded<number>()\n      const subscriber1 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(pipe(\n              values,\n              Array.appendAll(values),\n              Effect.forEach((_) => Queue.take(subscription))\n            ))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n\n      const subscriber2 = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred2, void 0),\n            Effect.zipRight(pipe(\n              values,\n              Array.appendAll(values),\n              Effect.forEach((_) => Queue.take(subscription))\n            ))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* Deferred.await(deferred1)\n      yield* Deferred.await(deferred2)\n      const fiber = yield* pipe(\n        values,\n        Effect.forEach((n) => PubSub.publish(pubsub, n)),\n        Effect.fork\n      )\n      yield* pipe(values, Array.map((n) => -n), Effect.forEach((n) => PubSub.publish(pubsub, n)), Effect.fork)\n      const result1 = yield* Fiber.join(subscriber1)\n      const result2 = yield* Fiber.join(subscriber2)\n      yield* Fiber.join(fiber)\n      deepStrictEqual(Array.filter(result1, (n) => n > 0), values)\n      deepStrictEqual(\n        Array.filter(result1, (n) => n < 0),\n        Array.map(values, (n) => -n)\n      )\n      deepStrictEqual(Array.filter(result2, (n) => n > 0), values)\n      deepStrictEqual(\n        Array.filter(result2, (n) => n < 0),\n        Array.map(values, (n) => -n)\n      )\n    }))\n  it.effect(\"null values\", () => {\n    const messages = [1, null]\n    return PubSub.unbounded<number | null>().pipe(\n      Effect.flatMap((pubsub) =>\n        Effect.scoped(\n          Effect.gen(function*() {\n            const dequeue1 = yield* PubSub.subscribe(pubsub)\n            const dequeue2 = yield* PubSub.subscribe(pubsub)\n            yield* PubSub.publishAll(pubsub, messages)\n            const takes1 = yield* Queue.takeAll(dequeue1)\n            const takes2 = yield* Queue.takeAll(dequeue2)\n            deepStrictEqual([...takes1], messages)\n            deepStrictEqual([...takes2], messages)\n          })\n        )\n      )\n    )\n  })\n\n  it.scoped(\"publish does not increase size while no subscribers\", () =>\n    Effect.gen(function*() {\n      const pubsub = yield* PubSub.dropping<number>(2)\n      yield* PubSub.publish(pubsub, 1)\n      yield* PubSub.publish(pubsub, 2)\n      assertSome(pubsub.unsafeSize(), 0)\n    }))\n\n  it.scoped(\"publishAll does not increase size while no subscribers\", () =>\n    Effect.gen(function*() {\n      const pubsub = yield* PubSub.dropping<number>(2)\n      yield* PubSub.publishAll(pubsub, [1, 2])\n      assertSome(pubsub.unsafeSize(), 0)\n    }))\n\n  describe(\"replay\", () => {\n    it.scoped(\"unbounded\", () =>\n      Effect.gen(function*() {\n        const messages = [1, 2, 3, 4, 5]\n        const pubsub = yield* PubSub.unbounded<number>({ replay: 3 })\n        yield* PubSub.publishAll(pubsub, messages)\n        const sub = yield* PubSub.subscribe(pubsub)\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub)), [3, 4, 5])\n      }))\n\n    it.effect(\"unbounded takeUpTo\", () => {\n      const messages = [1, 2, 3, 4, 5]\n      return PubSub.unbounded<number>({ replay: 3 }).pipe(\n        Effect.flatMap((pubsub) =>\n          Effect.scoped(\n            Effect.gen(function*() {\n              yield* PubSub.publishAll(pubsub, messages)\n\n              const dequeue1 = yield* PubSub.subscribe(pubsub)\n              yield* PubSub.publish(pubsub, 6)\n              const dequeue2 = yield* PubSub.subscribe(pubsub)\n\n              strictEqual(yield* Queue.size(dequeue1), 4)\n              strictEqual(yield* Queue.size(dequeue2), 3)\n              deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeUpTo(dequeue1, 2)), [3, 4])\n              deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeUpTo(dequeue1, 2)), [5, 6])\n              deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeUpTo(dequeue2, 3)), [4, 5, 6])\n            })\n          )\n        )\n      )\n    })\n\n    it.scoped(\"dropping\", () =>\n      Effect.gen(function*() {\n        const messages = [1, 2, 3, 4, 5]\n        const pubsub = yield* PubSub.dropping<number>({ capacity: 2, replay: 3 })\n\n        yield* PubSub.publishAll(pubsub, messages)\n        const sub = yield* PubSub.subscribe(pubsub)\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub)), [3, 4, 5])\n        yield* PubSub.publishAll(pubsub, [6, 7])\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub)), [6, 7])\n\n        const sub2 = yield* PubSub.subscribe(pubsub)\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub2)), [5, 6, 7])\n\n        yield* PubSub.publishAll(pubsub, [8, 9, 10, 11])\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub)), [8, 9])\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub2)), [8, 9])\n\n        const sub3 = yield* PubSub.subscribe(pubsub)\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub3)), [7, 8, 9])\n      }))\n\n    it.scoped(\"sliding\", () =>\n      Effect.gen(function*() {\n        const messages = [1, 2, 3, 4, 5]\n        const pubsub = yield* PubSub.sliding<number>({ capacity: 4, replay: 3 })\n\n        yield* PubSub.publishAll(pubsub, messages)\n        const sub = yield* PubSub.subscribe(pubsub)\n        deepStrictEqual(yield* Queue.take(sub), 3)\n        yield* PubSub.publishAll(pubsub, [6, 7, 8, 9, 10])\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub)), [5, 6, 7, 8, 9, 10])\n\n        const sub2 = yield* PubSub.subscribe(pubsub)\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub2)), [8, 9, 10])\n\n        yield* PubSub.publishAll(pubsub, [11, 12, 13, 14, 15, 16])\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub)), [13, 14, 15, 16])\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub2)), [13, 14, 15, 16])\n\n        const sub3 = yield* PubSub.subscribe(pubsub)\n        deepStrictEqual(Chunk.toReadonlyArray(yield* Queue.takeAll(sub3)), [14, 15, 16])\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Queue.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertLeft,\n  assertNone,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual\n} from \"@effect/vitest/utils\"\nimport { Array, Cause, Chunk, Deferred, Effect, Exit, Fiber, identity, pipe, Queue, Ref } from \"effect\"\n\nexport const waitForValue = <A>(ref: Effect.Effect<A>, value: A): Effect.Effect<A> => {\n  return ref.pipe(Effect.zipLeft(Effect.yieldNow()), Effect.repeat({ until: (a) => value === a }))\n}\n\nexport const waitForSize = <A>(queue: Queue.Queue<A>, size: number): Effect.Effect<number> => {\n  return waitForValue(Queue.size(queue), size)\n}\n\ndescribe(\"Queue\", () => {\n  it.effect(\"bounded - offerAll returns true when there is enough space\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(5)\n      const result = yield* Queue.offerAll(queue, [1, 2, 3])\n      assertTrue(result)\n    }))\n  it.effect(\"dropping - with offerAll\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.dropping<number>(4)\n      const result1 = yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n      const result2 = yield* Queue.takeAll(queue)\n      assertFalse(result1)\n      deepStrictEqual(Chunk.toReadonlyArray(result2), [1, 2, 3, 4])\n    }))\n  it.effect(\"dropping - with offerAll, check offer returns false\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.dropping<number>(2)\n      const result1 = yield* Queue.offerAll(queue, [1, 2, 3, 4, 5, 6])\n      const result2 = yield* Queue.takeAll(queue)\n      assertFalse(result1)\n      deepStrictEqual(Chunk.toReadonlyArray(result2), [1, 2])\n    }))\n  it.effect(\"dropping - with offerAll, check ordering\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.dropping<number>(128)\n      const result1 = yield* Queue.offerAll(queue, Array.makeBy(256, (i) => i + 1))\n      const result2 = yield* Queue.takeAll(queue)\n      assertFalse(result1)\n      deepStrictEqual(Chunk.toReadonlyArray(result2), Array.makeBy(128, (i) => i + 1))\n    }))\n  it.effect(\"dropping - with pending taker\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.dropping<number>(2)\n      const fiber = yield* Effect.fork(Queue.take(queue))\n      yield* waitForSize(queue, -1)\n      const result1 = yield* Queue.offerAll(queue, [1, 2, 3, 4])\n      const result2 = yield* Fiber.join(fiber)\n      assertFalse(result1)\n      strictEqual(result2, 1)\n    }))\n  it.effect(\"sliding - with offer\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.sliding<number>(2)\n      yield* Queue.offer(queue, 1)\n      const result1 = yield* Queue.offer(queue, 2)\n      const result2 = yield* Queue.offer(queue, 3)\n      const result3 = yield* Queue.takeAll(queue)\n      assertTrue(result1)\n      assertTrue(result2)\n      deepStrictEqual(Chunk.toReadonlyArray(result3), [2, 3])\n    }))\n  it.effect(\"sliding - with offerAll\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.sliding<number>(2)\n      const result1 = yield* Queue.offerAll(queue, [1, 2, 3])\n      const result2 = yield* Queue.size(queue)\n      assertTrue(result1)\n      strictEqual(result2, 2)\n    }))\n  it.effect(\"sliding - with enough capacity\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.sliding<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      const result = yield* Queue.takeAll(queue)\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2, 3])\n    }))\n  it.effect(\"sliding - with offerAll and takeAll\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.sliding<number>(2)\n      const result1 = yield* Queue.offerAll(queue, [1, 2, 3, 4, 5, 6])\n      const result2 = yield* Queue.takeAll(queue)\n      assertTrue(result1)\n      deepStrictEqual(Chunk.toReadonlyArray(result2), [5, 6])\n    }))\n  it.effect(\"sliding - with pending taker\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.sliding<number>(2)\n      yield* Effect.fork(Queue.take(queue))\n      yield* waitForSize(queue, -1)\n      const result1 = yield* Queue.offerAll(queue, [1, 2, 3, 4])\n      const result2 = yield* Queue.take(queue)\n      assertTrue(result1)\n      strictEqual(result2, 3)\n    }))\n  it.effect(\"sliding - check offerAll returns true\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.sliding<number>(5)\n      const result = yield* Queue.offerAll(queue, [1, 2, 3])\n      assertTrue(result)\n    }))\n  it.effect(\"awaitShutdown - once\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(3)\n      const deferred = yield* Deferred.make<boolean>()\n      yield* pipe(Queue.awaitShutdown(queue), Effect.zipRight(Deferred.succeed(deferred, true)), Effect.fork)\n      yield* Queue.shutdown(queue)\n      const result = yield* Deferred.await(deferred)\n      assertTrue(result)\n    }))\n  it.effect(\"awaitShutdown - multiple\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(3)\n      const deferred1 = yield* Deferred.make<boolean>()\n      const deferred2 = yield* Deferred.make<boolean>()\n      yield* pipe(Queue.awaitShutdown(queue), Effect.zipRight(Deferred.succeed(deferred1, true)), Effect.fork)\n      yield* pipe(Queue.awaitShutdown(queue), Effect.zipRight(Deferred.succeed(deferred2, true)), Effect.fork)\n      yield* Queue.shutdown(queue)\n      const result1 = yield* Deferred.await(deferred1)\n      const result2 = yield* Deferred.await(deferred2)\n      assertTrue(result1)\n      assertTrue(result2)\n    }))\n  it.effect(\"offers are suspended by back pressure\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(10)\n      const ref = yield* Ref.make(true)\n      yield* pipe(queue.offer(1), Effect.repeatN(9))\n      const fiber = yield* pipe(Queue.offer(queue, 2), Effect.zipRight(Ref.set(ref, false)), Effect.fork)\n      yield* waitForSize(queue, 11)\n      const result = yield* Ref.get(ref)\n      yield* Fiber.interrupt(fiber)\n      assertTrue(result)\n    }))\n  it.effect(\"back pressured offers are retrieved\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(10)\n      const ref = yield* Ref.make<ReadonlyArray<number>>([])\n      const values = Array.makeBy(10, (i) => i + 1)\n      const fiber = yield* Effect.forkAll(values.map((n) => Queue.offer(queue, n)))\n      yield* waitForSize(queue, 10)\n      yield* pipe(\n        Queue.take(queue),\n        Effect.flatMap((n) => Ref.update(ref, (values) => [...values, n])),\n        Effect.repeatN(9)\n      )\n      const result = yield* Ref.get(ref)\n      yield* Fiber.join(fiber)\n      deepStrictEqual(result, values)\n    }))\n  it.effect(\"back-pressured offer completes after take\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      yield* Queue.offerAll(queue, [1, 2])\n      const fiber = yield* pipe(Queue.offer(queue, 3), Effect.fork)\n      yield* waitForSize(queue, 3)\n      const result1 = yield* Queue.take(queue)\n      const result2 = yield* Queue.take(queue)\n      yield* Fiber.join(fiber)\n      strictEqual(result1, 1)\n      strictEqual(result2, 2)\n    }))\n  it.effect(\"back-pressured offer completes after takeAll\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      yield* Queue.offerAll(queue, [1, 2])\n      const fiber = yield* pipe(Queue.offer(queue, 3), Effect.fork)\n      yield* waitForSize(queue, 3)\n      const result = yield* Queue.takeAll(queue)\n      yield* Fiber.join(fiber)\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2])\n    }))\n  it.effect(\"back-pressured offer completes after takeUpTo\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      yield* Queue.offerAll(queue, [1, 2])\n      const fiber = yield* pipe(Queue.offer(queue, 3), Effect.fork)\n      yield* waitForSize(queue, 3)\n      const result = yield* Queue.takeUpTo(queue, 2)\n      yield* Fiber.join(fiber)\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2])\n    }))\n  it.effect(\"back-pressured offerAll completes after takeAll\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      yield* Queue.offerAll(queue, [1, 2])\n      const fiber = yield* pipe(Queue.offerAll(queue, [3, 4, 5]), Effect.fork)\n      yield* waitForSize(queue, 5)\n      const result1 = yield* Queue.takeAll(queue)\n      const result2 = yield* Queue.takeAll(queue)\n      const result3 = yield* Queue.takeAll(queue)\n      yield* Fiber.join(fiber)\n      deepStrictEqual(Chunk.toReadonlyArray(result1), [1, 2])\n      deepStrictEqual(Chunk.toReadonlyArray(result2), [3, 4])\n      deepStrictEqual(Chunk.toReadonlyArray(result3), [5])\n    }))\n  it.effect(\"take interruption\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      const fiber = yield* Effect.fork(Queue.take(queue))\n      yield* waitForSize(queue, -1)\n      yield* Fiber.interrupt(fiber)\n      const result = yield* Queue.size(queue)\n      strictEqual(result, 0)\n    }))\n  it.effect(\"offer interruption\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 1)\n      const fiber = yield* pipe(Queue.offer(queue, 1), Effect.fork)\n      yield* waitForSize(queue, 3)\n      yield* Fiber.interrupt(fiber)\n      const result = yield* Queue.size(queue)\n      strictEqual(result, 2)\n    }))\n  it.effect(\"offerAll with takeAll\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(10)\n      const values = Array.range(1, 10)\n      yield* Queue.offerAll(queue, values)\n      yield* waitForSize(queue, 10)\n      const result = yield* Queue.takeAll(queue)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 10))\n    }))\n  it.effect(\"offerAll with takeAll and back pressure\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      const values = Array.range(1, 3)\n      const fiber = yield* pipe(Queue.offerAll(queue, values), Effect.fork)\n      const size = yield* waitForSize(queue, 3)\n      const result = yield* Queue.takeAll(queue)\n      yield* Fiber.interrupt(fiber)\n      strictEqual(size, 3)\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1, 2])\n    }))\n  it.effect(\"offerAll with takeAll and back pressure + interruption\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      const values1 = Array.range(1, 2)\n      const values2 = Array.range(3, 4)\n      yield* Queue.offerAll(queue, values1)\n      const fiber = yield* pipe(Queue.offerAll(queue, values2), Effect.fork)\n      yield* waitForSize(queue, 4)\n      yield* Fiber.interrupt(fiber)\n      const result1 = yield* Queue.takeAll(queue)\n      const result2 = yield* Queue.takeAll(queue)\n      deepStrictEqual(Chunk.toReadonlyArray(result1), values1)\n      assertTrue(Chunk.isEmpty(result2))\n    }))\n  it.effect(\"offerAll with takeAll and back pressure, check ordering\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(64)\n      const fiber = yield* pipe(Queue.offerAll(queue, Array.makeBy(128, (i) => i + 1)), Effect.fork)\n      yield* waitForSize(queue, 128)\n      const result = yield* Queue.takeAll(queue)\n      yield* Fiber.interrupt(fiber)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 64))\n    }))\n  it.effect(\"offerAll with pending takers\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(50)\n      const takers = yield* Effect.forkAll(Array.makeBy(100, () => Queue.take(queue)))\n      yield* waitForSize(queue, -100)\n      yield* queue.offerAll(Array.makeBy(100, (i) => i + 1))\n      const result = yield* Fiber.join(takers)\n      const size = yield* Queue.size(queue)\n      strictEqual(size, 0)\n      deepStrictEqual(result, Array.range(1, 100))\n    }))\n  it.effect(\"offerAll with pending takers, check ordering\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(256)\n      const takers = yield* Effect.forkAll(Array.makeBy(64, () => Queue.take(queue)))\n      yield* waitForSize(queue, -64)\n      yield* Queue.offerAll(queue, Array.makeBy(128, (i) => i + 1))\n      const result = yield* Fiber.join(takers)\n      const size = yield* Queue.size(queue)\n      strictEqual(size, 64)\n      deepStrictEqual(result, Array.range(1, 64))\n    }))\n  it.effect(\"offerAll with pending takers, check ordering of taker resolution\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(200)\n      const takers = yield* Effect.forkAll(Array.makeBy(100, () => Queue.take(queue)))\n      yield* waitForSize(queue, -100)\n      const fiber = yield* Effect.forkAll(Array.makeBy(100, () => Queue.take(queue)))\n      yield* waitForSize(queue, -200)\n      yield* Queue.offerAll(queue, Array.makeBy(100, (i) => i + 1))\n      const result = yield* Fiber.join(takers)\n      const size = yield* Queue.size(queue)\n      yield* Fiber.interrupt(fiber)\n      strictEqual(size, -100)\n      deepStrictEqual(result, Array.range(1, 100))\n    }))\n  it.effect(\"offerAll with take and back pressure\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      yield* pipe(Queue.offerAll(queue, [1, 2, 3]), Effect.fork)\n      yield* waitForSize(queue, 3)\n      const result1 = yield* Queue.take(queue)\n      const result2 = yield* Queue.take(queue)\n      const result3 = yield* Queue.take(queue)\n      strictEqual(result1, 1)\n      strictEqual(result2, 2)\n      strictEqual(result3, 3)\n    }))\n  it.effect(\"offerAll multiple with back pressure\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      yield* pipe(Queue.offerAll(queue, [1, 2, 3]), Effect.fork)\n      yield* waitForSize(queue, 3)\n      yield* pipe(Queue.offerAll(queue, [4, 5]), Effect.fork)\n      yield* waitForSize(queue, 5)\n      const result1 = yield* Queue.take(queue)\n      const result2 = yield* Queue.take(queue)\n      const result3 = yield* Queue.take(queue)\n      const result4 = yield* Queue.take(queue)\n      const result5 = yield* Queue.take(queue)\n      strictEqual(result1, 1)\n      strictEqual(result2, 2)\n      strictEqual(result3, 3)\n      strictEqual(result4, 4)\n      strictEqual(result5, 5)\n    }))\n  it.effect(\"offerAll with takeAll, check ordering\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(1000)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offerAll(queue, Array.range(2, 1000))\n      yield* waitForSize(queue, 1000)\n      const result = yield* Queue.takeAll(queue)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 1000))\n    }))\n  it.effect(\"offerAll combination of offer, offerAll, take, takeAll\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(32)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* pipe(Queue.offerAll(queue, Array.range(3, 35)), Effect.fork)\n      yield* waitForSize(queue, 35)\n      const result1 = yield* Queue.takeAll(queue)\n      const result2 = yield* Queue.take(queue)\n      const result3 = yield* Queue.take(queue)\n      const result4 = yield* Queue.take(queue)\n      deepStrictEqual(Chunk.toReadonlyArray(result1), Array.range(1, 32))\n      strictEqual(result2, 33)\n      strictEqual(result3, 34)\n      strictEqual(result4, 35)\n    }))\n  it.effect(\"parallel takes and sequential offers\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      const fiber = yield* Effect.forkAll(Array.makeBy(10, () => Queue.take(queue)))\n      yield* Array.makeBy(10, (i) => Queue.offer(queue, i + 1))\n        .reduce((acc, curr) => pipe(acc, Effect.zipRight(curr)), Effect.succeed(false))\n      const result = yield* Fiber.join(fiber)\n      deepStrictEqual(result, Array.range(1, 10))\n    }))\n  it.effect(\"parallel offers and sequential takes\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(10)\n      const fiber = yield* Effect.forkAll(Array.makeBy(10, (i) => Queue.offer(queue, i + 1)))\n      yield* waitForSize(queue, 10)\n      const ref = yield* Ref.make<ReadonlyArray<number>>([])\n      yield* pipe(\n        Queue.take(queue),\n        Effect.flatMap((n) => Ref.update(ref, (ns) => [...ns, n])),\n        Effect.repeatN(9)\n      )\n      const result = yield* Ref.get(ref)\n      yield* Fiber.join(fiber)\n      deepStrictEqual(result, Array.makeBy(10, (i) => i + 1))\n    }))\n  it.effect(\"sequential offer and take\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      const offer1 = yield* Queue.offer(queue, 10)\n      const result1 = yield* Queue.take(queue)\n      const offer2 = yield* Queue.offer(queue, 20)\n      const result2 = yield* Queue.take(queue)\n      assertTrue(offer1)\n      strictEqual(result1, 10)\n      assertTrue(offer2)\n      strictEqual(result2, 20)\n    }))\n  it.effect(\"sequential take and offer\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<string>(100)\n      const fiber = yield* pipe(Queue.take(queue), Effect.zipWith(Queue.take(queue), (a, b) => a + b), Effect.fork)\n      yield* pipe(Queue.offer(queue, \"don't \"), Effect.zipRight(Queue.offer(queue, \"give up :D\")))\n      const result = yield* Fiber.join(fiber)\n      strictEqual(result, \"don't give up :D\")\n    }))\n  it.effect(\"poll on empty queue\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(5)\n      const result = yield* Queue.poll(queue)\n      assertNone(result)\n    }))\n  it.effect(\"poll on queue just emptied\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(5)\n      yield* Queue.offerAll(queue, [1, 2, 3, 4])\n      yield* Queue.takeAll(queue)\n      const result = yield* Queue.poll(queue)\n      assertNone(result)\n    }))\n  it.effect(\"multiple polls\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(5)\n      yield* Queue.offerAll(queue, [1, 2])\n      const result1 = yield* Queue.poll(queue)\n      const result2 = yield* Queue.poll(queue)\n      const result3 = yield* Queue.poll(queue)\n      const result4 = yield* Queue.poll(queue)\n      assertSome(result1, 1)\n      assertSome(result2, 2)\n      assertNone(result3)\n      assertNone(result4)\n    }))\n  it.effect(\"shutdown with take fiber\", () =>\n    Effect.gen(function*() {\n      const fiberId = yield* Effect.fiberId\n      const queue = yield* Queue.bounded<number>(3)\n      const fiber = yield* Effect.fork(Queue.take(queue))\n      yield* waitForSize(queue, -1)\n      yield* Queue.shutdown(queue)\n      const result = yield* Effect.either(Effect.sandbox(Fiber.join(fiber)))\n      assertLeft(result, Cause.interrupt(fiberId))\n    }))\n  it.effect(\"shutdown with offer fiber\", () =>\n    Effect.gen(function*() {\n      const fiberId = yield* Effect.fiberId\n      const queue = yield* Queue.bounded<number>(2)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 1)\n      const fiber = yield* pipe(Queue.offer(queue, 1), Effect.fork)\n      yield* waitForSize(queue, 3)\n      yield* Queue.shutdown(queue)\n      const result = yield* Effect.either(Effect.sandbox(Fiber.join(fiber)))\n      assertLeft(result, Cause.interrupt(fiberId))\n    }))\n  it.effect(\"shutdown with offer\", () =>\n    Effect.gen(function*() {\n      const fiberId = yield* Effect.fiberId\n      const queue = yield* Queue.bounded<number>(1)\n      yield* Queue.shutdown(queue)\n      const result = yield* pipe(Queue.offer(queue, 1), Effect.sandbox, Effect.either)\n      assertLeft(result, Cause.interrupt(fiberId))\n    }))\n  it.effect(\"shutdown with take\", () =>\n    Effect.gen(function*() {\n      const fiberId = yield* Effect.fiberId\n      const queue = yield* Queue.bounded<number>(1)\n      yield* Queue.shutdown(queue)\n      const result = yield* pipe(Queue.take(queue), Effect.sandbox, Effect.either)\n      assertLeft(result, Cause.interrupt(fiberId))\n    }))\n  it.effect(\"shutdown with takeAll\", () =>\n    Effect.gen(function*() {\n      const fiberId = yield* Effect.fiberId\n      const queue = yield* Queue.bounded<number>(1)\n      yield* Queue.shutdown(queue)\n      const result = yield* pipe(Queue.takeAll(queue), Effect.sandbox, Effect.either)\n      assertLeft(result, Cause.interrupt(fiberId))\n    }))\n  it.effect(\"shutdown with takeUpTo\", () =>\n    Effect.gen(function*() {\n      const fiberId = yield* Effect.fiberId\n      const queue = yield* Queue.bounded<number>(1)\n      yield* Queue.shutdown(queue)\n      const result = yield* pipe(Queue.takeUpTo(queue, 1), Effect.sandbox, Effect.either)\n      assertLeft(result, Cause.interrupt(fiberId))\n    }))\n  it.effect(\"shutdown with size\", () =>\n    Effect.gen(function*() {\n      const fiberId = yield* Effect.fiberId\n      const queue = yield* Queue.bounded<number>(1)\n      yield* Queue.shutdown(queue)\n      const result = yield* pipe(Queue.size(queue), Effect.sandbox, Effect.either)\n      assertLeft(result, Cause.interrupt(fiberId))\n    }))\n  it.effect(\"shutdown race condition with offer\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      const fiber = yield* pipe(Queue.offer(queue, 1), Effect.forever, Effect.fork)\n      yield* Queue.shutdown(queue)\n      const result = yield* Fiber.await(fiber)\n      assertTrue(Exit.isFailure(result))\n    }))\n  it.effect(\"shutdown race condition with take\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(2)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 1)\n      const fiber = yield* pipe(Queue.take(queue), Effect.forever, Effect.fork)\n      yield* Queue.shutdown(queue)\n      const result = yield* Fiber.await(fiber)\n      assertTrue(Exit.isFailure(result))\n    }))\n  it.effect(\"isShutdown indicates shutdown status\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(5)\n      const result1 = yield* Queue.isShutdown(queue)\n      yield* Queue.offer(queue, 1)\n      const result2 = yield* Queue.isShutdown(queue)\n      yield* Queue.takeAll(queue)\n      const result3 = yield* Queue.isShutdown(queue)\n      yield* Queue.shutdown(queue)\n      const result4 = yield* Queue.isShutdown(queue)\n      assertFalse(result1)\n      assertFalse(result2)\n      assertFalse(result3)\n      assertTrue(result4)\n    }))\n  it.effect(\"takeAll returns all values from a non-empty queue\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.unbounded<number>()\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      const result = yield* Queue.takeAll(queue)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 3))\n    }))\n  it.effect(\"elements can be enqueued syncroniously when there is space\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.unbounded<number>()\n      Queue.unsafeOffer(queue, 1)\n      Queue.unsafeOffer(queue, 2)\n      Queue.unsafeOffer(queue, 3)\n      const result = yield* Queue.takeAll(queue)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 3))\n    }))\n  it.effect(\"takeAll returns all values from an empty queue\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.unbounded<number>()\n      const result1 = yield* Queue.takeAll(queue)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.take(queue)\n      const result2 = yield* Queue.takeAll(queue)\n      assertTrue(Chunk.isEmpty(result1))\n      assertTrue(Chunk.isEmpty(result2))\n    }))\n  it.effect(\"takeAll does not return more than the queue size\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(4)\n      yield* [1, 2, 3, 4]\n        .map((n) => Queue.offer(queue, n))\n        .reduce((acc, curr) => pipe(acc, Effect.zipRight(curr)), Effect.succeed(false))\n      yield* pipe(Queue.offer(queue, 5), Effect.fork)\n      yield* waitForSize(queue, 5)\n      const result1 = yield* Queue.takeAll(queue)\n      const result2 = yield* Queue.take(queue)\n      deepStrictEqual(Chunk.toReadonlyArray(result1), Array.range(1, 4))\n      strictEqual(result2, 5)\n    }))\n  it.effect(\"takeBetween returns immediately if there is enough elements\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      const result = yield* Queue.takeBetween(queue, 2, 5)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 3))\n    }))\n  it.effect(\"takeBetween returns an empty list if boundaries are inverted\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      const result = yield* Queue.takeBetween(queue, 5, 2)\n      assertTrue(Chunk.isEmpty(result))\n    }))\n  it.effect(\"takeBetween returns an empty list if boundaries are negative\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      const result = yield* Queue.takeBetween(queue, -5, -2)\n      assertTrue(Chunk.isEmpty(result))\n    }))\n  it.effect(\"takeBetween blocks until a required minimum of elements is collected\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      const updater = pipe(Queue.offer(queue, 10), Effect.forever)\n      const getter = Queue.takeBetween(queue, 5, 10)\n      const result = yield* pipe(getter, Effect.race(updater))\n      assertTrue(result.length >= 5)\n    }))\n  it.effect(\"takeBetween returns elements in the correct order\", () =>\n    Effect.gen(function*() {\n      const values = [-10, -7, -4, -1, 5, 10]\n      const queue = yield* Queue.bounded<number>(100)\n      const fiber = yield* pipe(values, Effect.forEach((n) => Queue.offer(queue, n)), Effect.fork)\n      const result = yield* Queue.takeBetween(queue, values.length, values.length)\n      yield* Fiber.interrupt(fiber)\n      deepStrictEqual(Array.fromIterable(result), values)\n    }))\n  it.effect(\"takeN returns immediately if there is enough elements\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offerAll(queue, [1, 2, 3, 4, 5])\n      const result = yield* Queue.takeN(queue, 3)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 3))\n    }))\n  it.effect(\"takeN returns an empty list if a negative number or zero is specified\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offerAll(queue, [1, 2, 3])\n      const result1 = yield* Queue.takeN(queue, -3)\n      const result2 = yield* Queue.takeN(queue, 0)\n      assertTrue(Chunk.isEmpty(result1))\n      assertTrue(Chunk.isEmpty(result2))\n    }))\n  it.effect(\"takeN blocks until the required number of elements is available\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      const updater = pipe(Queue.offer(queue, 10), Effect.forever)\n      const getter = Queue.takeN(queue, 5)\n      const result = yield* pipe(getter, Effect.race(updater))\n      strictEqual(result.length, 5)\n    }))\n  it.effect(\"should return the specified number of elements from a non-empty queue\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      const result = yield* Queue.takeUpTo(queue, 2)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 2))\n    }))\n  it.effect(\"should return an empty collection from an empty queue\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      const result = yield* Queue.takeUpTo(queue, 2)\n      assertTrue(Chunk.isEmpty(result))\n    }))\n  it.effect(\"should handle an empty queue with max higher than queue size\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      const result = yield* Queue.takeUpTo(queue, 101)\n      assertTrue(Chunk.isEmpty(result))\n    }))\n  it.effect(\"should leave behind elements if necessary\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      yield* Queue.offer(queue, 4)\n      const result = yield* Queue.takeUpTo(queue, 2)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 2))\n    }))\n  it.effect(\"should handle not enough items\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      yield* Queue.offer(queue, 4)\n      const result = yield* Queue.takeUpTo(queue, 10)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 4))\n    }))\n  it.effect(\"should handle taking up to 0 items\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      yield* Queue.offer(queue, 4)\n      const result = yield* Queue.takeUpTo(queue, 0)\n      assertTrue(Chunk.isEmpty(result))\n    }))\n  it.effect(\"should handle taking up to -1 items\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      yield* Queue.offer(queue, 4)\n      const result = yield* Queue.takeUpTo(queue, -1)\n      assertTrue(Chunk.isEmpty(result))\n    }))\n  it.effect(\"should handle taking up to Number.POSITIVE_INFINITY items\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      const result = yield* Queue.takeUpTo(queue, Number.POSITIVE_INFINITY)\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1])\n    }))\n  it.effect(\"multiple take up to calls\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      const result1 = yield* Queue.takeUpTo(queue, 2)\n      yield* Queue.offer(queue, 3)\n      yield* Queue.offer(queue, 4)\n      const result2 = yield* Queue.takeUpTo(queue, 2)\n      deepStrictEqual(Chunk.toReadonlyArray(result1), Array.range(1, 2))\n      deepStrictEqual(Chunk.toReadonlyArray(result2), Array.range(3, 4))\n    }))\n  it.effect(\"consecutive take up to calls\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(100)\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      yield* Queue.offer(queue, 4)\n      const result1 = yield* Queue.takeUpTo(queue, 2)\n      const result2 = yield* Queue.takeUpTo(queue, 2)\n      deepStrictEqual(Chunk.toReadonlyArray(result1), Array.range(1, 2))\n      deepStrictEqual(Chunk.toReadonlyArray(result2), Array.range(3, 4))\n    }))\n  it.effect(\"does not return back-pressured offers\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.bounded<number>(4)\n      yield* [1, 2, 3, 4]\n        .map((n) => Queue.offer(queue, n))\n        .reduce((acc, curr) => pipe(acc, Effect.zipRight(curr)), Effect.succeed(false))\n      const fiber = yield* pipe(Queue.offer(queue, 5), Effect.fork)\n      yield* waitForSize(queue, 5)\n      const result = yield* Queue.takeUpTo(queue, 5)\n      yield* Fiber.interrupt(fiber)\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 4))\n    }))\n  it.effect(\"rts - handles falsy values\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.unbounded<number>()\n      yield* Queue.offer(queue, 0)\n      const result = yield* Queue.take(queue)\n      strictEqual(result, 0)\n    }))\n  it.effect(\"rts - queue is ordered\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.unbounded<number>()\n      yield* Queue.offer(queue, 1)\n      yield* Queue.offer(queue, 2)\n      yield* Queue.offer(queue, 3)\n      const result1 = yield* Queue.take(queue)\n      const result2 = yield* Queue.take(queue)\n      const result3 = yield* Queue.take(queue)\n      strictEqual(result1, 1)\n      strictEqual(result2, 2)\n      strictEqual(result3, 3)\n    }))\n  it.effect(\n    \".pipe\",\n    () =>\n      Effect.gen(function*() {\n        const queue = yield* Queue.unbounded<number>()\n        strictEqual(queue.pipe(identity), queue)\n      })\n  )\n  it.effect(\n    \"is subtype of Effect\",\n    () =>\n      Effect.gen(function*() {\n        const queue = yield* Queue.unbounded<number>()\n        yield* Queue.offer(queue, 1)\n        const result1 = yield* queue\n        strictEqual(result1, 1)\n      })\n  )\n})\n"
  },
  {
    "path": "packages/effect/test/Random.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Array, Cause, Chunk, Data, Effect, Random } from \"effect\"\n\ndescribe(\"Random\", () => {\n  it.effect(\"integer is correctly distributed\", () =>\n    Effect.gen(function*() {\n      const tenYearsMillis = 10 * 365 * 24 * 60 * 60 * 1000\n      let lastRandom = 0\n      while (lastRandom < tenYearsMillis / 2) {\n        lastRandom = yield* Random.nextIntBetween(0, tenYearsMillis)\n      }\n      assertTrue(lastRandom >= tenYearsMillis / 2)\n    }))\n  it.effect(\"shuffle\", () =>\n    Effect.gen(function*() {\n      const start = Array.range(0, 100)\n      const end = yield* Random.shuffle(start)\n      assertTrue(Chunk.every(end, (n) => n !== undefined))\n      deepStrictEqual(start.sort(), Array.fromIterable(end).sort())\n    }).pipe(Effect.repeatN(100)))\n\n  it.effect(\"make\", () =>\n    Effect.gen(function*() {\n      const random0 = Random.make(\"foo\")\n      const random1 = Random.make(\"foo\")\n      const random2 = Random.make(Data.struct({ foo: \"bar\" }))\n      const random3 = Random.make(Data.struct({ foo: \"bar\" }))\n      const n0 = yield* random0.next\n      const n1 = yield* random1.next\n      const n2 = yield* random2.next\n      const n3 = yield* random3.next\n      strictEqual(n0, n1)\n      strictEqual(n2, n3)\n      assertTrue(n0 !== n2)\n    }))\n\n  it.live(\"choice\", () =>\n    Effect.gen(function*() {\n      deepStrictEqual(\n        yield* Random.choice([]).pipe(Effect.flip),\n        new Cause.NoSuchElementException(\"Cannot select a random element from an empty array\")\n      )\n      strictEqual(yield* Random.choice([1]), 1)\n\n      const randomItems = yield* Random.choice([1, 2, 3]).pipe(Array.replicate(100), Effect.all)\n      strictEqual(Array.intersection(randomItems, [1, 2, 3]).length, randomItems.length)\n\n      assertTrue([1, 2, 3].includes(yield* Random.choice(Chunk.fromIterable([1, 2, 3]))))\n    }))\n\n  describe(\"fixed\", () => {\n    it.effect(\"cycles through numeric values\", () =>\n      Effect.gen(function*() {\n        strictEqual(yield* Random.next, 0.2)\n        strictEqual(yield* Random.next, 0.5)\n        strictEqual(yield* Random.next, 0.8)\n        strictEqual(yield* Random.next, 0.2)\n        strictEqual(yield* Random.next, 0.5)\n      }).pipe(Effect.withRandomFixed([0.2, 0.5, 0.8])))\n\n    it.effect(\"cycles through boolean values\", () =>\n      Effect.gen(function*() {\n        strictEqual(yield* Random.nextBoolean, true)\n        strictEqual(yield* Random.nextBoolean, false)\n        strictEqual(yield* Random.nextBoolean, true)\n        strictEqual(yield* Random.nextBoolean, true)\n      }).pipe(Effect.withRandom(Random.fixed([true, false, true]))))\n\n    it.effect(\"cycles through integer values\", () =>\n      Effect.gen(function*() {\n        strictEqual(yield* Random.nextInt, 10)\n        strictEqual(yield* Random.nextInt, 20)\n        strictEqual(yield* Random.nextInt, 30)\n        strictEqual(yield* Random.nextInt, 10)\n      }).pipe(Effect.withRandom(Random.fixed([10, 20, 30]))))\n\n    it.effect(\"handles mixed value types\", () =>\n      Effect.gen(function*() {\n        strictEqual(yield* Random.next, 0.5)\n        strictEqual(yield* Random.nextBoolean, true)\n        const next = yield* Random.next\n        assertTrue(next >= 0 && next <= 1)\n        strictEqual(yield* Random.nextInt, 4)\n      }).pipe(Effect.withRandom(Random.fixed([0.5, true, \"hello\", 4.2]))))\n\n    it.effect(\"nextRange works correctly\", () =>\n      Effect.gen(function*() {\n        const value1 = yield* Random.nextRange(10, 20)\n        const value2 = yield* Random.nextRange(10, 20)\n        const value3 = yield* Random.nextRange(10, 20)\n        strictEqual(value1, 12)\n        strictEqual(value2, 15)\n        strictEqual(value3, 18)\n      }).pipe(Effect.withRandom(Random.fixed([0.2, 0.5, 0.8]))))\n\n    it.effect(\"nextIntBetween works correctly\", () =>\n      Effect.gen(function*() {\n        strictEqual(yield* Random.nextIntBetween(10, 20), 15)\n        strictEqual(yield* Random.nextIntBetween(20, 30), 25)\n        strictEqual(yield* Random.nextIntBetween(30, 40), 35)\n        strictEqual(yield* Random.nextIntBetween(10, 20), 15)\n      }).pipe(Effect.withRandom(Random.fixed([15, 25, 35]))))\n\n    it.effect(\"clamps numeric values to valid range\", () =>\n      Effect.gen(function*() {\n        strictEqual(yield* Random.next, 0)\n        strictEqual(yield* Random.next, 1)\n        strictEqual(yield* Random.next, 0.5)\n      }).pipe(Effect.withRandom(Random.fixed([-1, 2, 0.5]))))\n\n    it.effect(\"handles non-numeric values by hashing\", () =>\n      Effect.gen(function*() {\n        const value1 = yield* Random.next\n        const value2 = yield* Random.next\n        const value3 = yield* Random.next\n        assertTrue(value1 >= 0 && value1 <= 1)\n        assertTrue(value2 >= 0 && value2 <= 1)\n        assertTrue(value3 >= 0 && value3 <= 1)\n        assertTrue(value1 !== value2)\n        assertTrue(value2 !== value3)\n      }).pipe(Effect.withRandom(Random.fixed([\"a\", \"b\", \"c\"]))))\n\n    it.effect(\"shuffle works with array values\", () =>\n      Effect.gen(function*() {\n        const shuffled = yield* Random.shuffle([1, 2, 3, 4, 5])\n        deepStrictEqual(Array.fromIterable(shuffled).sort(), [1, 2, 3, 4, 5])\n      }).pipe(Effect.withRandom(Random.fixed([1, 2, 3, 4, 5]))))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/RateLimiter.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Array, Clock, Deferred, Effect, Fiber, Function, Option, pipe, RateLimiter, Ref, TestClock } from \"effect\"\n\ndescribe(\"RateLimiter\", () => {\n  describe.concurrent(\"fixed-window\", () => {\n    RateLimiterTestSuite(\"fixed-window\")\n\n    it.scoped(\"will use the provided cost\", () =>\n      Effect.gen(function*() {\n        const rl = yield* (RateLimiter.make({\n          limit: 100,\n          interval: \"1 seconds\",\n          algorithm: \"fixed-window\"\n        }))\n\n        const now = yield* (Clock.currentTimeMillis)\n        const fib = yield* (\n          Effect.replicateEffect(rl(Clock.currentTimeMillis).pipe(RateLimiter.withCost(10)), 20).pipe(\n            Effect.fork\n          )\n        )\n\n        yield* (TestClock.adjust(\"1 seconds\"))\n        const nowAfter1Second = yield* (Clock.currentTimeMillis)\n\n        const times = yield* (Fiber.join(fib))\n        assertTrue(times.slice(0, 10).every((t) => t === now))\n        assertTrue(times.slice(10).every((t) => t === nowAfter1Second))\n      }))\n\n    it.scoped(\"will respect different costs per effect and interleave them.\", () =>\n      Effect.gen(function*() {\n        const rl = yield* (RateLimiter.make({\n          limit: 10,\n          interval: \"1 seconds\",\n          algorithm: \"fixed-window\"\n        }))\n        const rl1 = Function.compose(rl, RateLimiter.withCost(7))\n        const rl2 = Function.compose(rl, RateLimiter.withCost(3))\n\n        const start = yield* (Clock.currentTimeMillis)\n\n        const tasks = [\n          rl1(Clock.currentTimeMillis).pipe(Effect.map((x) => [\"rl1\", x] as const)),\n          rl1(Clock.currentTimeMillis).pipe(Effect.map((x) => [\"rl1\", x] as const)),\n          rl2(Clock.currentTimeMillis).pipe(Effect.map((x) => [\"rl2\", x] as const)),\n          rl2(Clock.currentTimeMillis).pipe(Effect.map((x) => [\"rl2\", x] as const))\n        ]\n\n        const fib = yield* (\n          Effect.all(tasks, { concurrency: \"unbounded\" }).pipe(Effect.fork)\n        )\n\n        yield* (TestClock.adjust(\"1 seconds\"))\n        const after1Second = yield* (Clock.currentTimeMillis)\n\n        const times = yield* (Fiber.join(fib))\n\n        deepStrictEqual(\n          times,\n          [\n            [\"rl1\", start],\n            [\"rl1\", after1Second],\n            [\"rl2\", start],\n            [\"rl2\", after1Second]\n          ]\n        )\n      }))\n\n    it.scoped(\"will be composable with other `RateLimiters`\", () =>\n      Effect.gen(function*() {\n        // Max 30 calls per minute\n        const rl1 = yield* (RateLimiter.make({\n          limit: 30,\n          interval: \"1 minutes\",\n          algorithm: \"fixed-window\"\n        }))\n        // Max 2 calls per second\n        const rl2 = yield* (RateLimiter.make({\n          limit: 2,\n          interval: \"1 seconds\",\n          algorithm: \"fixed-window\"\n        }))\n        // This rate limiter respects both the 30 calls per minute\n        // and the 2 calls per second constraints.\n        const rl = Function.compose(rl1, rl2)\n\n        const now = yield* (Clock.currentTimeMillis)\n\n        // 32 calls should take 1 minute to complete based on the constraints\n        // of the rate limiter defined above.\n        // First 30 calls should trigger in the first 15 seconds\n        // and the next 2 calls should trigger at the 1 minute mark.\n        const fib = yield* (\n          Effect.replicateEffect(rl(Clock.currentTimeMillis), 32).pipe(Effect.fork)\n        )\n\n        const timestamps = yield* (\n          Effect.replicateEffect(\n            Effect.zipRight(TestClock.adjust(\"1 seconds\"), Clock.currentTimeMillis),\n            60\n          )\n        )\n\n        const times = yield* (Fiber.join(fib))\n\n        assertTrue(timestamps.length === 60)\n        assertTrue(times.length === 32)\n\n        const resultTimes = [\n          now,\n          now,\n          ...timestamps.slice(0, 14).flatMap((x) => [x, x]),\n          ...timestamps.slice(59).flatMap((x) => [x, x])\n        ]\n\n        deepStrictEqual(times, resultTimes)\n      }), 10_000)\n  })\n\n  describe.concurrent(\"token-bucket\", () => {\n    RateLimiterTestSuite(\"token-bucket\")\n\n    it.scoped(\"uses the token-bucket algorithm for token replenishment\", () =>\n      Effect.scoped(Effect.gen(function*() {\n        // The limiter below should allow be to execute 10 requests immediately,\n        // prevent further requests from being executed, and then after 100 ms\n        // allow execution of another request.\n        const limit = yield* (RateLimiter.make({\n          limit: 10,\n          interval: \"1 seconds\",\n          algorithm: \"token-bucket\"\n        }))\n        const deferred = yield* (Deferred.make<void>())\n\n        // Use up all of the available tokens\n        yield* (Effect.forEach(Array.range(1, 10), () => limit(Effect.void)))\n\n        // Make an additional request when there are no tokens available\n        yield* pipe(\n          limit(Effect.void),\n          Effect.zipRight(Deferred.succeed(deferred, void 0)),\n          Effect.fork\n        )\n        assertFalse(yield* (Deferred.isDone(deferred)))\n\n        // Ensure that the request is successful once a token is replenished\n        yield* (TestClock.adjust(\"100 millis\"))\n        yield* (Effect.yieldNow())\n\n        assertTrue(yield* (Deferred.isDone(deferred)))\n      })))\n  })\n})\n\nconst RateLimiterTestSuite = (algorithm: \"fixed-window\" | \"token-bucket\") => {\n  it.scoped(`${algorithm} - execute up to max calls immediately`, () =>\n    Effect.gen(function*() {\n      const limit = yield* (RateLimiter.make({\n        limit: 10,\n        interval: \"1 seconds\",\n        algorithm\n      }))\n      const now = yield* (Clock.currentTimeMillis)\n      const times = yield* (Effect.forEach(\n        Array.range(1, 10),\n        () => limit(Clock.currentTimeMillis)\n      ))\n      const result = Array.every(times, (time) => time === now)\n      assertTrue(result)\n    }))\n\n  it.scoped(`${algorithm} - is not affected by stream chunk size`, () =>\n    Effect.gen(function*() {\n      const limiter = yield* (RateLimiter.make({\n        limit: 10,\n        interval: \"1 seconds\",\n        algorithm\n      }))\n      const now = yield* (Clock.currentTimeMillis)\n      const times1 = yield* (Effect.forEach(\n        Array.range(1, 5),\n        () => limiter(Clock.currentTimeMillis),\n        { concurrency: \"unbounded\" }\n      ))\n      const fibers = yield* (Effect.forEach(\n        Array.range(1, 15),\n        () => Effect.fork(limiter(Clock.currentTimeMillis)),\n        { concurrency: \"unbounded\" }\n      ))\n      yield* (TestClock.adjust(\"1 seconds\"))\n      const times2 = yield* (Effect.forEach(fibers, Fiber.join, { concurrency: \"unbounded\" }))\n      const times = Array.appendAll(times1, times2)\n      const result = Array.filter(times, (time) => time === now)\n      strictEqual(result.length, 10)\n    }))\n\n  it.scoped(`${algorithm} - succeed with the result of the call`, () =>\n    Effect.gen(function*() {\n      const limit = yield* (RateLimiter.make({\n        limit: 10,\n        interval: \"1 seconds\",\n        algorithm\n      }))\n      const result = yield* (limit(Effect.succeed(3)))\n      strictEqual(result, 3)\n    }))\n\n  it.scoped(`${algorithm} - fail with the result of a failed call`, () =>\n    Effect.gen(function*() {\n      const limit = yield* (RateLimiter.make({\n        limit: 10,\n        interval: \"1 seconds\",\n        algorithm\n      }))\n      const result = yield* (limit(Effect.either(Effect.fail(Option.none()))))\n      assertLeft(result, Option.none())\n    }))\n\n  it.scoped(`${algorithm} - continue after a failed call`, () =>\n    Effect.gen(function*() {\n      const limit = yield* RateLimiter.make({\n        limit: 10,\n        interval: \"1 seconds\",\n        algorithm\n      })\n      yield* limit(Effect.either(Effect.fail(Option.none())))\n      yield* limit(Effect.succeed(3))\n    }))\n\n  it.scoped(`${algorithm} - holds back up calls after the max`, () =>\n    Effect.gen(function*() {\n      const limit = yield* (RateLimiter.make({\n        limit: 10,\n        interval: \"1 seconds\",\n        algorithm\n      }))\n\n      const now = yield* (Clock.currentTimeMillis)\n\n      const fiber = yield* pipe(\n        Effect.replicateEffect(\n          limit(Clock.currentTimeMillis),\n          20\n        ),\n        Effect.fork\n      )\n\n      yield* (TestClock.adjust(\"1 seconds\"))\n\n      const times = yield* (Fiber.join(fiber))\n      const later = yield* (Clock.currentTimeMillis)\n\n      assertTrue(times.slice(0, 10).every((x) => x === now))\n      assertTrue(times.slice(10).every((x) => x > now && x <= later))\n    }))\n\n  it.scoped(`${algorithm} - will interrupt the effect when a call is interrupted`, () =>\n    Effect.gen(function*() {\n      const limit = yield* (RateLimiter.make({\n        limit: 10,\n        interval: \"1 seconds\",\n        algorithm\n      }))\n      const latch = yield* (Deferred.make<void>())\n      const interrupted = yield* (Deferred.make<void>())\n      const fib = yield* pipe(\n        Deferred.succeed(latch, void 0),\n        Effect.zipRight(Effect.never),\n        Effect.onInterrupt(() => Deferred.succeed(interrupted, void 0)),\n        limit,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fib))\n      yield* (Deferred.await(interrupted))\n    }))\n\n  it.scoped(`${algorithm} - will not start execution of an effect when it is interrupted before getting its turn to execute`, () =>\n    Effect.gen(function*() {\n      const count = yield* (Ref.make(0))\n      const limit = yield* (RateLimiter.make({\n        limit: 1,\n        interval: \"1 seconds\",\n        algorithm\n      }))\n      yield* (limit(Effect.void))\n      const fiber = yield* (Effect.fork(limit(Ref.set(count, 1))))\n      const interruption = yield* (Effect.fork(Fiber.interrupt(fiber)))\n      yield* (Fiber.join(interruption))\n      strictEqual(yield* (Ref.get(count)), 0)\n    }))\n\n  it.scoped(`${algorithm} - will wait for interruption to complete of an effect that is already executing`, () =>\n    Effect.gen(function*() {\n      const limit = yield* (RateLimiter.make({\n        limit: 1,\n        interval: \"1 seconds\",\n        algorithm\n      }))\n      const latch = yield* (Deferred.make<void>())\n      const effectInterrupted = yield* (Ref.make(0))\n      const fiber = yield* pipe(\n        Deferred.succeed(latch, void 0),\n        Effect.zipRight(Effect.never),\n        Effect.onInterrupt(() => Ref.set(effectInterrupted, 1)),\n        limit,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const interruptions = yield* (Ref.get(effectInterrupted))\n      strictEqual(interruptions, 1)\n    }))\n\n  it.scoped(`${algorithm} - will make effects wait for interrupted effects to pass through the rate limiter`, () =>\n    Effect.gen(function*() {\n      const limit = yield* (RateLimiter.make({\n        limit: 1,\n        interval: \"1 seconds\",\n        algorithm\n      }))\n      yield* (limit(Effect.void))\n      const fiber1 = yield* (Effect.fork(limit(Effect.void)))\n      yield* (TestClock.adjust(\"1 seconds\"))\n      yield* (Fiber.interrupt(fiber1))\n      const fiber2 = yield* (Effect.fork(limit(Clock.currentTimeMillis)))\n      yield* (TestClock.adjust(\"1 seconds\"))\n      const lastExecutionTime = yield* (Fiber.join(fiber2))\n      strictEqual(lastExecutionTime, 2000)\n    }))\n\n  it.scoped(\"will not include interrupted effects in the throttling\", () =>\n    Effect.gen(function*() {\n      const rate = 10\n      const limit = yield* (RateLimiter.make({ limit: rate, interval: \"1 seconds\", algorithm }))\n      const latch = yield* (Deferred.make<void>())\n      const latched = yield* (Ref.make(0))\n      const wait = yield* (Deferred.make<void>())\n      yield* pipe(\n        Deferred.succeed(latch, void 0),\n        Effect.whenEffect(latched.pipe(\n          Ref.updateAndGet((x) => x + 1),\n          Effect.map((x) => x === rate)\n        )),\n        Effect.zipRight(Deferred.await(wait)),\n        limit,\n        Effect.fork,\n        Effect.replicateEffect(rate)\n      )\n      yield* (Deferred.await(latch))\n      const fibers = yield* pipe(\n        Effect.fork(limit(Effect.void)),\n        Effect.replicateEffect(1000)\n      )\n      yield* (Fiber.interruptAll(fibers))\n      const fiber = yield* (Effect.fork(limit(Effect.void)))\n      yield* (TestClock.adjust(\"1 seconds\"))\n      yield* (Fiber.join(fiber))\n    }), 10_000)\n\n  it.scoped(`${algorithm} - will not drop tokens if interrupted`, () =>\n    Effect.gen(function*() {\n      const limit = yield* (RateLimiter.make({\n        limit: 10,\n        interval: \"1 seconds\",\n        algorithm\n      }))\n\n      yield* (limit(Effect.void))\n      const fiber = yield* pipe(limit(Effect.void), RateLimiter.withCost(10), Effect.fork)\n      yield* (Effect.yieldNow())\n      yield* (Fiber.interrupt(fiber))\n      yield* pipe(limit(Effect.void), RateLimiter.withCost(9))\n    }))\n}\n"
  },
  {
    "path": "packages/effect/test/RcMap.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Cause, Data, Effect, Exit, RcMap, Scope, TestClock } from \"effect\"\n\ndescribe(\"RcMap\", () => {\n  it.effect(\"deallocation\", () =>\n    Effect.gen(function*() {\n      const acquired: Array<string> = []\n      const released: Array<string> = []\n      const mapScope = yield* Scope.make()\n      const map = yield* RcMap.make({\n        lookup: (key: string) =>\n          Effect.acquireRelease(\n            Effect.sync(() => {\n              acquired.push(key)\n              return key\n            }),\n            () => Effect.sync(() => released.push(key))\n          )\n      }).pipe(\n        Scope.extend(mapScope)\n      )\n\n      deepStrictEqual(acquired, [])\n      strictEqual(yield* Effect.scoped(RcMap.get(map, \"foo\")), \"foo\")\n      deepStrictEqual(acquired, [\"foo\"])\n      deepStrictEqual(released, [\"foo\"])\n\n      const scopeA = yield* Scope.make()\n      const scopeB = yield* Scope.make()\n      yield* RcMap.get(map, \"bar\").pipe(Scope.extend(scopeA))\n      yield* Effect.scoped(RcMap.get(map, \"bar\"))\n      yield* RcMap.get(map, \"baz\").pipe(Scope.extend(scopeB))\n      yield* Effect.scoped(RcMap.get(map, \"baz\"))\n      deepStrictEqual(acquired, [\"foo\", \"bar\", \"baz\"])\n      deepStrictEqual(released, [\"foo\"])\n      yield* Scope.close(scopeB, Exit.void)\n      deepStrictEqual(acquired, [\"foo\", \"bar\", \"baz\"])\n      deepStrictEqual(released, [\"foo\", \"baz\"])\n      yield* Scope.close(scopeA, Exit.void)\n      deepStrictEqual(acquired, [\"foo\", \"bar\", \"baz\"])\n      deepStrictEqual(released, [\"foo\", \"baz\", \"bar\"])\n\n      const scopeC = yield* Scope.make()\n      yield* RcMap.get(map, \"qux\").pipe(Scope.extend(scopeC))\n      deepStrictEqual(acquired, [\"foo\", \"bar\", \"baz\", \"qux\"])\n      deepStrictEqual(released, [\"foo\", \"baz\", \"bar\"])\n\n      yield* Scope.close(mapScope, Exit.void)\n      deepStrictEqual(acquired, [\"foo\", \"bar\", \"baz\", \"qux\"])\n      deepStrictEqual(released, [\"foo\", \"baz\", \"bar\", \"qux\"])\n\n      const exit = yield* RcMap.get(map, \"boom\").pipe(Effect.scoped, Effect.exit)\n      assertTrue(Exit.isInterrupted(exit))\n    }))\n\n  it.scoped(\"idleTimeToLive\", () =>\n    Effect.gen(function*() {\n      const acquired: Array<string> = []\n      const released: Array<string> = []\n      const map = yield* RcMap.make({\n        lookup: (key: string) =>\n          Effect.acquireRelease(\n            Effect.sync(() => {\n              acquired.push(key)\n              return key\n            }),\n            () => Effect.sync(() => released.push(key))\n          ),\n        idleTimeToLive: 1000\n      })\n\n      deepStrictEqual(acquired, [])\n      strictEqual(yield* Effect.scoped(RcMap.get(map, \"foo\")), \"foo\")\n      deepStrictEqual(acquired, [\"foo\"])\n      deepStrictEqual(released, [])\n\n      yield* TestClock.adjust(1000)\n      deepStrictEqual(released, [\"foo\"])\n\n      strictEqual(yield* Effect.scoped(RcMap.get(map, \"bar\")), \"bar\")\n      deepStrictEqual(acquired, [\"foo\", \"bar\"])\n      deepStrictEqual(released, [\"foo\"])\n\n      yield* TestClock.adjust(500)\n      strictEqual(yield* Effect.scoped(RcMap.get(map, \"bar\")), \"bar\")\n      deepStrictEqual(acquired, [\"foo\", \"bar\"])\n      deepStrictEqual(released, [\"foo\"])\n\n      yield* TestClock.adjust(1000)\n      deepStrictEqual(released, [\"foo\", \"bar\"])\n\n      yield* Effect.scoped(RcMap.get(map, \"baz\"))\n      deepStrictEqual(acquired, [\"foo\", \"bar\", \"baz\"])\n      yield* RcMap.invalidate(map, \"baz\")\n      deepStrictEqual(acquired, [\"foo\", \"bar\", \"baz\"])\n      deepStrictEqual(released, [\"foo\", \"bar\", \"baz\"])\n    }))\n\n  it.scoped(\".touch\", () =>\n    Effect.gen(function*() {\n      const acquired: Array<string> = []\n      const released: Array<string> = []\n      const map = yield* RcMap.make({\n        lookup: (key: string) =>\n          Effect.acquireRelease(\n            Effect.sync(() => {\n              acquired.push(key)\n              return key\n            }),\n            () => Effect.sync(() => released.push(key))\n          ),\n        idleTimeToLive: 1000\n      })\n\n      deepStrictEqual(acquired, [])\n      strictEqual(yield* Effect.scoped(RcMap.get(map, \"foo\")), \"foo\")\n      deepStrictEqual(acquired, [\"foo\"])\n      deepStrictEqual(released, [])\n\n      yield* TestClock.adjust(500)\n      deepStrictEqual(released, [])\n\n      yield* RcMap.touch(map, \"foo\")\n      yield* TestClock.adjust(500)\n      deepStrictEqual(released, [])\n      yield* TestClock.adjust(500)\n      deepStrictEqual(released, [\"foo\"])\n    }))\n\n  it.scoped(\"capacity\", () =>\n    Effect.gen(function*() {\n      const map = yield* RcMap.make({\n        lookup: (key: string) => Effect.succeed(key),\n        capacity: 2,\n        idleTimeToLive: 1000\n      })\n\n      strictEqual(yield* Effect.scoped(RcMap.get(map, \"foo\")), \"foo\")\n      strictEqual(yield* Effect.scoped(RcMap.get(map, \"foo\")), \"foo\")\n      strictEqual(yield* Effect.scoped(RcMap.get(map, \"bar\")), \"bar\")\n\n      const exit = yield* RcMap.get(map, \"baz\").pipe(Effect.scoped, Effect.exit)\n      deepStrictEqual(\n        exit,\n        Exit.fail(new Cause.ExceededCapacityException(`RcMap attempted to exceed capacity of 2`))\n      )\n\n      yield* TestClock.adjust(1000)\n      strictEqual(yield* Effect.scoped(RcMap.get(map, \"baz\")), \"baz\")\n    }))\n\n  it.scoped(\"complex key\", () =>\n    Effect.gen(function*() {\n      class Key extends Data.Class<{ readonly id: number }> {}\n      const map = yield* RcMap.make({\n        lookup: (key: Key) => Effect.succeed(key.id),\n        capacity: 1\n      })\n\n      strictEqual(yield* RcMap.get(map, new Key({ id: 1 })), 1)\n      // no failure means a hit\n      strictEqual(yield* RcMap.get(map, new Key({ id: 1 })), 1)\n    }))\n\n  it.scoped(\"keys lookup\", () =>\n    Effect.gen(function*() {\n      const map = yield* RcMap.make({\n        lookup: (key: string) => Effect.succeed(key)\n      })\n\n      yield* RcMap.get(map, \"foo\")\n      yield* RcMap.get(map, \"bar\")\n      yield* RcMap.get(map, \"baz\")\n\n      deepStrictEqual(yield* RcMap.keys(map), [\"foo\", \"bar\", \"baz\"])\n    }))\n\n  it.scoped(\"dynamic idleTimeToLive\", () =>\n    Effect.gen(function*() {\n      const acquired: Array<string> = []\n      const released: Array<string> = []\n      const map = yield* RcMap.make({\n        lookup: (key: string) =>\n          Effect.acquireRelease(\n            Effect.sync(() => {\n              acquired.push(key)\n              return key\n            }),\n            () => Effect.sync(() => released.push(key))\n          ),\n        idleTimeToLive: (key: string) => key.startsWith(\"short:\") ? 500 : 2000\n      })\n\n      deepStrictEqual(acquired, [])\n\n      yield* Effect.scoped(RcMap.get(map, \"short:a\"))\n      yield* Effect.scoped(RcMap.get(map, \"long:b\"))\n      deepStrictEqual(acquired, [\"short:a\", \"long:b\"])\n      deepStrictEqual(released, [])\n\n      yield* TestClock.adjust(500)\n      deepStrictEqual(released, [\"short:a\"])\n\n      yield* TestClock.adjust(1500)\n      deepStrictEqual(released, [\"short:a\", \"long:b\"])\n    }))\n\n  it.scoped(\"dynamic idleTimeToLive with touch\", () =>\n    Effect.gen(function*() {\n      const acquired: Array<string> = []\n      const released: Array<string> = []\n      const map = yield* RcMap.make({\n        lookup: (key: string) =>\n          Effect.acquireRelease(\n            Effect.sync(() => {\n              acquired.push(key)\n              return key\n            }),\n            () => Effect.sync(() => released.push(key))\n          ),\n        idleTimeToLive: (key: string) => key.startsWith(\"short:\") ? 500 : 2000\n      })\n\n      yield* Effect.scoped(RcMap.get(map, \"short:a\"))\n      deepStrictEqual(acquired, [\"short:a\"])\n      deepStrictEqual(released, [])\n\n      yield* TestClock.adjust(250)\n      yield* RcMap.touch(map, \"short:a\")\n      yield* TestClock.adjust(250)\n      deepStrictEqual(released, [])\n\n      yield* TestClock.adjust(250)\n      deepStrictEqual(released, [\"short:a\"])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/RcRef.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport { Effect, Exit, RcRef, Scope, TestClock } from \"effect\"\n\ndescribe(\"RcRef\", () => {\n  it.effect(\"deallocation\", () =>\n    Effect.gen(function*() {\n      let acquired = 0\n      let released = 0\n      const refScope = yield* Scope.make()\n      const ref = yield* RcRef.make({\n        acquire: Effect.acquireRelease(\n          Effect.sync(() => {\n            acquired++\n            return \"foo\"\n          }),\n          () =>\n            Effect.sync(() => {\n              released++\n            })\n        )\n      }).pipe(\n        Scope.extend(refScope)\n      )\n\n      strictEqual(acquired, 0)\n      strictEqual(yield* Effect.scoped(ref), \"foo\")\n      strictEqual(acquired, 1)\n      strictEqual(released, 1)\n\n      const scopeA = yield* Scope.make()\n      const scopeB = yield* Scope.make()\n      yield* ref.pipe(Scope.extend(scopeA))\n      yield* ref.pipe(Scope.extend(scopeB))\n      strictEqual(acquired, 2)\n      strictEqual(released, 1)\n      yield* Scope.close(scopeB, Exit.void)\n      strictEqual(acquired, 2)\n      strictEqual(released, 1)\n      yield* Scope.close(scopeA, Exit.void)\n      strictEqual(acquired, 2)\n      strictEqual(released, 2)\n\n      const scopeC = yield* Scope.make()\n      yield* ref.pipe(Scope.extend(scopeC))\n      strictEqual(acquired, 3)\n      strictEqual(released, 2)\n\n      yield* Scope.close(refScope, Exit.void)\n      strictEqual(acquired, 3)\n      strictEqual(released, 3)\n\n      const exit = yield* ref.get.pipe(Effect.scoped, Effect.exit)\n      assertTrue(Exit.isInterrupted(exit))\n    }))\n\n  it.scoped(\"idleTimeToLive\", () =>\n    Effect.gen(function*() {\n      let acquired = 0\n      let released = 0\n      const ref = yield* RcRef.make({\n        acquire: Effect.acquireRelease(\n          Effect.sync(() => {\n            acquired++\n            return \"foo\"\n          }),\n          () =>\n            Effect.sync(() => {\n              released++\n            })\n        ),\n        idleTimeToLive: 1000\n      })\n\n      strictEqual(acquired, 0)\n      strictEqual(yield* Effect.scoped(RcRef.get(ref)), \"foo\")\n      strictEqual(acquired, 1)\n      strictEqual(released, 0)\n\n      yield* TestClock.adjust(1000)\n      strictEqual(released, 1)\n\n      strictEqual(yield* Effect.scoped(RcRef.get(ref)), \"foo\")\n      strictEqual(acquired, 2)\n      strictEqual(released, 1)\n\n      yield* TestClock.adjust(500)\n      strictEqual(yield* Effect.scoped(RcRef.get(ref)), \"foo\")\n      strictEqual(acquired, 2)\n      strictEqual(released, 1)\n\n      yield* TestClock.adjust(1000)\n      strictEqual(released, 2)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Record.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertNone, assertSome, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Either, Number as Num, Option, pipe, Record } from \"effect\"\n\nconst symA = Symbol.for(\"a\")\nconst symB = Symbol.for(\"b\")\nconst symC = Symbol.for(\"c\")\n\nconst stringRecord: Record<string, number> = { a: 1, [symA]: null }\nconst symbolRecord: Record<symbol, number> = { [symA]: 1, [symB]: 2 }\n\ndescribe(\"Record\", () => {\n  describe(\"string | symbol APIs\", () => {\n    it(\"empty\", () => {\n      deepStrictEqual(Record.empty(), {})\n    })\n\n    it(\"fromIterableWith\", () => {\n      deepStrictEqual(Record.fromIterableWith([1, 2, 3, 4], (a) => [a === 3 ? \"a\" : String(a), a * 2]), {\n        \"1\": 2,\n        \"2\": 4,\n        a: 6,\n        \"4\": 8\n      })\n      deepStrictEqual(Record.fromIterableWith([1, 2, 3, 4], (a) => [a === 3 ? symA : String(a), a * 2]), {\n        \"1\": 2,\n        \"2\": 4,\n        [symA]: 6,\n        \"4\": 8\n      })\n    })\n\n    it(\"fromIterableBy\", () => {\n      const users = [\n        { id: \"2\", name: \"name2\" },\n        { id: \"1\", name: \"name1\" }\n      ]\n      deepStrictEqual(Record.fromIterableBy(users, (user) => user.id), {\n        \"2\": { id: \"2\", name: \"name2\" },\n        \"1\": { id: \"1\", name: \"name1\" }\n      })\n\n      deepStrictEqual(Record.fromIterableBy([\"a\", symA], (s) => s), { a: \"a\", [symA]: symA })\n    })\n\n    it(\"fromEntries\", () => {\n      deepStrictEqual(Record.fromEntries([[\"1\", 2], [\"2\", 4], [\"3\", 6], [\"4\", 8]]), {\n        \"1\": 2,\n        \"2\": 4,\n        \"3\": 6,\n        \"4\": 8\n      })\n      deepStrictEqual(Record.fromEntries([[\"1\", 2], [\"2\", 4], [\"3\", 6], [\"4\", 8], [symA, 10], [symB, 12]]), {\n        \"1\": 2,\n        \"2\": 4,\n        \"3\": 6,\n        \"4\": 8,\n        [symA]: 10,\n        [symB]: 12\n      })\n    })\n\n    it(\"has\", () => {\n      assertTrue(Record.has(stringRecord, \"a\"))\n      assertFalse(Record.has(stringRecord, \"c\"))\n\n      assertTrue(Record.has(symbolRecord, symA))\n      assertFalse(Record.has(symbolRecord, symC))\n    })\n\n    it(\"get\", () => {\n      assertNone(pipe(Record.empty<string>(), Record.get(\"a\")))\n      assertSome(pipe(stringRecord, Record.get(\"a\")), 1)\n\n      assertNone(pipe(Record.empty<symbol>(), Record.get(symA)))\n      assertSome(pipe(symbolRecord, Record.get(symA)), 1)\n    })\n\n    it(\"modify\", () => {\n      deepStrictEqual(pipe(Record.empty<string>(), Record.modify(\"a\", (n: number) => n + 1)), {})\n      deepStrictEqual(pipe(stringRecord, Record.modify(\"a\", (n: number) => n + 1)), { a: 2, [symA]: null })\n      deepStrictEqual(pipe(stringRecord, Record.modify(\"a\", (n: number) => String(n))), { a: \"1\", [symA]: null })\n\n      deepStrictEqual(pipe(Record.empty<symbol>(), Record.modify(symA, (n: number) => n + 1)), {})\n      deepStrictEqual(pipe(symbolRecord, Record.modify(symA, (n: number) => n + 1)), {\n        [symA]: 2,\n        [symB]: 2\n      })\n      deepStrictEqual(pipe(symbolRecord, Record.modify(symA, (n: number) => String(n))), { [symA]: \"1\", [symB]: 2 })\n    })\n\n    it(\"modifyOption\", () => {\n      assertNone(pipe(Record.empty<string>(), Record.modifyOption(\"a\", (n) => n + 1)))\n      assertSome(pipe(stringRecord, Record.modifyOption(\"a\", (n: number) => n + 1)), { a: 2, [symA]: null })\n      assertSome(pipe(stringRecord, Record.modifyOption(\"a\", (n: number) => String(n))), { a: \"1\", [symA]: null })\n\n      assertNone(pipe(Record.empty<symbol>(), Record.modifyOption(symA, (n) => n + 1)))\n      assertSome(pipe(symbolRecord, Record.modifyOption(symA, (n: number) => n + 1)), { [symA]: 2, [symB]: 2 })\n      assertSome(\n        pipe(symbolRecord, Record.modifyOption(symA, (n: number) => String(n))),\n        { [symA]: \"1\", [symB]: 2 }\n      )\n    })\n\n    it(\"replaceOption\", () => {\n      assertNone(pipe(Record.empty<string>(), Record.replaceOption(\"a\", 2)))\n      assertSome(pipe(stringRecord, Record.replaceOption(\"a\", 2)), { a: 2, [symA]: null })\n      assertSome(pipe(stringRecord, Record.replaceOption(\"a\", true)), { a: true, [symA]: null })\n\n      assertNone(pipe(Record.empty<symbol>(), Record.replaceOption(symA, 2)))\n      assertSome(pipe(symbolRecord, Record.replaceOption(symA, 2)), { [symA]: 2, [symB]: 2 })\n      assertSome(pipe(symbolRecord, Record.replaceOption(symA, true)), { [symA]: true, [symB]: 2 })\n    })\n\n    it(\"remove\", () => {\n      deepStrictEqual(Record.remove(stringRecord, \"a\"), { [symA]: null })\n      deepStrictEqual(Record.remove(stringRecord, \"c\"), stringRecord)\n\n      deepStrictEqual(Record.remove(symbolRecord, symA), { [symB]: 2 })\n      deepStrictEqual(Record.remove(symbolRecord, symC), symbolRecord)\n    })\n\n    describe(\"pop\", () => {\n      it(\"should return the value associated with the given key, if the key is present in the record\", () => {\n        const result1 = Record.pop(stringRecord, \"a\")\n        assertSome(result1, [1, { [symA]: null }])\n\n        const result2 = Record.pop(symbolRecord, symA)\n        assertSome(result2, [1, { [symB]: 2 }])\n      })\n\n      it(\"should return none if the key is not present in the record\", () => {\n        const result1 = Record.pop(stringRecord, \"c\")\n        assertNone(result1)\n\n        const result2 = Record.pop(symbolRecord, symC)\n        assertNone(result2)\n      })\n    })\n\n    describe(\"set\", () => {\n      it(\"should replace an existing value\", () => {\n        deepStrictEqual(Record.set(stringRecord, \"a\", 2), { a: 2, [symA]: null })\n\n        deepStrictEqual(Record.set(symbolRecord, symA, 2), { [symA]: 2, [symB]: 2 })\n      })\n\n      it(\"should add the key / value pair\", () => {\n        deepStrictEqual(Record.set(stringRecord, \"c\", 3), { a: 1, [symA]: null, c: 3 })\n\n        deepStrictEqual(Record.set(symbolRecord, symC, 3), { [symA]: 1, [symB]: 2, [symC]: 3 })\n      })\n    })\n\n    it(\"replace\", () => {\n      deepStrictEqual(Record.replace(stringRecord, \"c\", 3), stringRecord)\n      deepStrictEqual(Record.replace(stringRecord, \"a\", 2), { a: 2, [symA]: null })\n\n      deepStrictEqual(Record.replace(symbolRecord, symC, 3), symbolRecord)\n      deepStrictEqual(Record.replace(symbolRecord, symA, 2), { [symA]: 2, [symB]: 2 })\n    })\n\n    it(\"singleton\", () => {\n      deepStrictEqual(Record.singleton(\"a\", 1), { a: 1 })\n\n      deepStrictEqual(Record.singleton(symA, 1), { [symA]: 1 })\n    })\n  })\n\n  describe(\"string only APIs\", () => {\n    it(\"map\", () => {\n      deepStrictEqual(pipe(stringRecord, Record.map((n) => n * 2)), { a: 2, [symA]: null })\n      deepStrictEqual(pipe(stringRecord, Record.map((n, k) => `${k}-${n}`)), { a: \"a-1\", [symA]: null })\n    })\n\n    it(\"collect\", () => {\n      const x = { a: 1, b: 2, c: 3, [symA]: null }\n      deepStrictEqual(Record.collect(x, (key, n) => [key, n]), [[\"a\", 1], [\"b\", 2], [\"c\", 3]])\n    })\n\n    it(\"toEntries\", () => {\n      const x = { a: 1, b: 2, c: 3, [symA]: null }\n      deepStrictEqual(Record.toEntries(x), [[\"a\", 1], [\"b\", 2], [\"c\", 3]])\n    })\n\n    it(\"filterMap\", () => {\n      const x: Record<string, number> = { a: 1, b: 2, c: 3, [symA]: null }\n      const filtered = Record.filterMap(x, (value, key) => (value > 2 ? Option.some(key) : Option.none()))\n      deepStrictEqual(filtered, { c: \"c\" })\n    })\n\n    it(\"getSomes\", () => {\n      const x = { a: Option.some(1), b: Option.none(), c: Option.some(2), [symA]: null }\n      deepStrictEqual(Record.getSomes(x), { a: 1, c: 2 })\n    })\n\n    it(\"filter\", () => {\n      const x: Record<string, number> = { a: 1, b: 2, c: 3, d: 4, [symA]: null }\n      deepStrictEqual(Record.filter(x, (value) => value > 2), { c: 3, d: 4 })\n    })\n\n    it(\"partitionMap\", () => {\n      const f = (n: number) => (n > 2 ? Either.right(n + 1) : Either.left(n - 1))\n      deepStrictEqual(Record.partitionMap({}, f), [{}, {}])\n      deepStrictEqual(Record.partitionMap({ a: 1, b: 3, [symA]: null }, f), [{ a: 0 }, { b: 4 }])\n    })\n\n    it(\"partition\", () => {\n      const f = (n: number) => n > 2\n      deepStrictEqual(Record.partition({}, f), [{}, {}])\n      deepStrictEqual(Record.partition({ a: 1, b: 3, [symA]: null }, f), [{ a: 1 }, { b: 3 }])\n    })\n\n    it(\"separate\", () => {\n      deepStrictEqual(\n        Record.separate({ a: Either.left(\"e\"), b: Either.right(1), [symA]: null }),\n        [{ a: \"e\" }, { b: 1 }]\n      )\n      // should ignore non own properties\n      const o: Record.ReadonlyRecord<\"a\", Either.Either<number, string>> = Object.create({ a: 1 })\n      deepStrictEqual(pipe(o, Record.separate), [{}, {}])\n    })\n\n    it(\"isEmptyRecord\", () => {\n      deepStrictEqual(Record.isEmptyRecord({}), true)\n      deepStrictEqual(Record.isEmptyRecord({ [symA]: null }), true)\n      deepStrictEqual(Record.isEmptyRecord({ a: 3 }), false)\n    })\n\n    it(\"isEmptyReadonlyRecord\", () => {\n      deepStrictEqual(Record.isEmptyReadonlyRecord({}), true)\n      deepStrictEqual(Record.isEmptyReadonlyRecord({ [symA]: null }), true)\n      deepStrictEqual(Record.isEmptyReadonlyRecord({ a: 3 }), false)\n    })\n\n    it(\"size\", () => {\n      deepStrictEqual(Record.size({ a: \"a\", b: 1, c: true, [symA]: null }), 3)\n    })\n\n    it(\"keys\", () => {\n      deepStrictEqual(Record.keys({ a: 1, b: 2, [symA]: null }), [\"a\", \"b\"])\n    })\n\n    it(\"values\", () => {\n      deepStrictEqual(Record.values({ a: 1, b: 2, [symA]: null }), [1, 2])\n    })\n\n    it(\"isSubrecord\", () => {\n      assertTrue(Record.isSubrecord(Record.empty(), {}))\n      assertTrue(Record.isSubrecord(Record.empty<string>(), { a: 1 }))\n      assertTrue(Record.isSubrecord({ a: 1 }, { a: 1 }))\n      assertTrue(Record.isSubrecord(stringRecord, { a: 1 }))\n      assertTrue(Record.isSubrecord({ a: 1 }, stringRecord))\n      assertTrue(Record.isSubrecord({ a: 1 } as Record<string, number>, { a: 1, b: 2 }))\n      assertTrue(Record.isSubrecord({ b: 2, a: 1 }, { a: 1, b: 2 }))\n      assertFalse(Record.isSubrecord({ a: 1 }, { a: 2 }))\n      assertFalse(Record.isSubrecord({ b: 2 } as Record<string, number>, { a: 1 }))\n    })\n\n    it(\"reduce\", () => {\n      // data-first\n      deepStrictEqual(\n        Record.reduce({ k1: \"a\", k2: \"b\", [symA]: null }, \"-\", (accumulator, value, key) => accumulator + key + value),\n        \"-k1ak2b\"\n      )\n      // data-last\n      deepStrictEqual(\n        pipe(\n          { k1: \"a\", k2: \"b\", [symA]: null },\n          Record.reduce(\"-\", (accumulator, value, key) => accumulator + key + value)\n        ),\n        \"-k1ak2b\"\n      )\n    })\n\n    it(\"every\", () => {\n      assertTrue(Record.every((n: number) => n <= 2)({ a: 1, b: 2, [symA]: null }))\n      assertFalse(Record.every((n: number) => n <= 1)({ a: 1, b: 2, [symA]: null }))\n    })\n\n    it(\"some\", () => {\n      assertTrue(Record.some((n: number) => n <= 1)({ a: 1, b: 2, [symA]: null }))\n      assertFalse(Record.some((n: number) => n <= 0)({ a: 1, b: 2, [symA]: null }))\n    })\n\n    it(\"union\", () => {\n      const combine = (s1: string, s2: string) => s1 + s2\n      const x: Record.ReadonlyRecord<string, string> = {\n        a: \"a1\",\n        b: \"b1\",\n        c: \"c1\",\n        [symA]: null\n      }\n      const y: Record.ReadonlyRecord<string, string> = {\n        b: \"b2\",\n        c: \"c2\",\n        d: \"d2\",\n        [symA]: null\n      }\n      deepStrictEqual(Record.union(x, {}, combine), x)\n      deepStrictEqual(Record.union({}, x, combine), x)\n      deepStrictEqual(Record.union(x, {}, combine), x)\n      deepStrictEqual(Record.union({}, x, combine), x)\n      deepStrictEqual(Record.union(x, y, combine), {\n        a: \"a1\",\n        b: \"b1b2\",\n        c: \"c1c2\",\n        d: \"d2\"\n      })\n    })\n\n    it(\"intersection\", () => {\n      const combine = (s1: string, s2: string) => s1 + s2\n      const x: Record.ReadonlyRecord<string, string> = {\n        a: \"a1\",\n        b: \"b1\",\n        c: \"c1\",\n        [symA]: null\n      }\n      const y: Record.ReadonlyRecord<string, string> = {\n        b: \"b2\",\n        c: \"c2\",\n        d: \"d2\",\n        [symA]: null\n      }\n      deepStrictEqual(Record.intersection(x, {}, combine), {})\n      deepStrictEqual(Record.intersection({}, y, combine), {})\n      deepStrictEqual(Record.intersection(x, y, combine), {\n        b: \"b1b2\",\n        c: \"c1c2\"\n      })\n    })\n\n    it(\"difference\", () => {\n      const x: Record.ReadonlyRecord<string, string> = {\n        a: \"a1\",\n        b: \"b1\",\n        c: \"c1\",\n        [symA]: null\n      }\n      const y: Record.ReadonlyRecord<string, string> = {\n        b: \"b2\",\n        c: \"c2\",\n        d: \"d2\",\n        [symA]: null\n      }\n      deepStrictEqual(Record.difference({}, x), x)\n      deepStrictEqual(Record.difference(x, {}), x)\n      deepStrictEqual(Record.difference({}, x), x)\n      deepStrictEqual(Record.difference(x, {}), x)\n      deepStrictEqual(Record.difference(x, y), {\n        a: \"a1\",\n        d: \"d2\"\n      })\n    })\n\n    it(\"getEquivalence\", () => {\n      deepStrictEqual(Record.getEquivalence(Num.Equivalence)({ a: 1 }, { a: 1 }), true)\n      deepStrictEqual(Record.getEquivalence(Num.Equivalence)({ a: 1 }, stringRecord), true)\n      deepStrictEqual(Record.getEquivalence(Num.Equivalence)({ a: 1 }, { a: 2 }), false)\n      deepStrictEqual(Record.getEquivalence(Num.Equivalence)({ a: 1 }, { b: 1 }), false)\n      const noPrototype = Object.create(null)\n      deepStrictEqual(Record.getEquivalence(Num.Equivalence)(noPrototype, { b: 1 }), false)\n    })\n\n    it(\"mapKeys\", () => {\n      deepStrictEqual(pipe({ a: 1, b: 2, [symA]: null }, Record.mapKeys((key) => key.toUpperCase())), {\n        A: 1,\n        B: 2\n      })\n    })\n\n    it(\"mapEntries\", () => {\n      deepStrictEqual(pipe(stringRecord, Record.mapEntries((a, key) => [key.toUpperCase(), a + 1])), { A: 2 })\n    })\n\n    describe(\"findFirst\", () => {\n      it(\"refinement/predicate\", () => {\n        const record = {\n          a: 1,\n          b: 2,\n          c: 1\n        }\n        deepStrictEqual(\n          pipe(record, Record.findFirst((v) => v < 2)),\n          Option.some([\"a\", 1])\n        )\n        deepStrictEqual(\n          pipe(record, Record.findFirst((v, k) => v < 2 && k !== \"a\")),\n          Option.some([\"c\", 1])\n        )\n        deepStrictEqual(\n          pipe(record, Record.findFirst((v) => v > 2)),\n          Option.none()\n        )\n        deepStrictEqual(\n          Record.findFirst(record, (v) => v < 2),\n          Option.some([\"a\", 1])\n        )\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/RedBlackTree.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Equal, Hash, Number as Num, Option, Order, pipe, RedBlackTree } from \"effect\"\n\ndescribe(\"RedBlackTree\", () => {\n  it(\"toString\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\")\n    )\n\n    strictEqual(\n      String(tree),\n      `{\n  \"_id\": \"RedBlackTree\",\n  \"values\": [\n    [\n      0,\n      \"b\"\n    ],\n    [\n      1,\n      \"a\"\n    ]\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\")\n    )\n\n    deepStrictEqual(tree.toJSON(), { _id: \"RedBlackTree\", values: [[0, \"b\"], [1, \"a\"]] })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\")\n    )\n\n    deepStrictEqual(inspect(tree), inspect({ _id: \"RedBlackTree\", values: [[0, \"b\"], [1, \"a\"]] }))\n  })\n\n  it(\"forEach\", () => {\n    const ordered: Array<[number, string]> = []\n    pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\"),\n      RedBlackTree.forEach((n, s) => {\n        ordered.push([n, s])\n      })\n    )\n\n    deepStrictEqual(ordered, [\n      [-2, \"d\"],\n      [-1, \"c\"],\n      [0, \"b\"],\n      [1, \"a\"],\n      [3, \"e\"]\n    ])\n  })\n\n  it(\"iterable\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\")\n    )\n\n    strictEqual(RedBlackTree.size(tree), 5)\n    deepStrictEqual(Array.from(tree), [\n      [-2, \"d\"],\n      [-1, \"c\"],\n      [0, \"b\"],\n      [1, \"a\"],\n      [3, \"e\"]\n    ])\n  })\n\n  it(\"iterable empty\", () => {\n    const tree = RedBlackTree.empty<number, string>(Num.Order)\n\n    strictEqual(RedBlackTree.size(tree), 0)\n    deepStrictEqual(Array.from(tree), [])\n  })\n\n  it(\"backwards\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\")\n    )\n\n    strictEqual(RedBlackTree.size(tree), 5)\n    deepStrictEqual(Array.from(RedBlackTree.reversed(tree)), [\n      [3, \"e\"],\n      [1, \"a\"],\n      [0, \"b\"],\n      [-1, \"c\"],\n      [-2, \"d\"]\n    ])\n  })\n\n  it(\"backwards empty\", () => {\n    const tree = RedBlackTree.empty<number, string>(Num.Order)\n\n    strictEqual(RedBlackTree.size(tree), 0)\n    deepStrictEqual(Array.from(RedBlackTree.reversed(tree)), [])\n  })\n\n  it(\"values\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\")\n    )\n\n    strictEqual(RedBlackTree.size(tree), 5)\n    deepStrictEqual(Array.from(RedBlackTree.values(tree)), [\"d\", \"c\", \"b\", \"a\", \"e\"])\n  })\n\n  it(\"keys\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\")\n    )\n\n    strictEqual(RedBlackTree.size(tree), 5)\n    deepStrictEqual(Array.from(RedBlackTree.keys(tree)), [-2, -1, 0, 1, 3])\n  })\n\n  it(\"begin/end\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\")\n    )\n\n    deepStrictEqual(RedBlackTree.first(tree), Option.some([-2, \"d\"]))\n    deepStrictEqual(RedBlackTree.last(tree), Option.some([3, \"e\"]))\n    deepStrictEqual(RedBlackTree.getAt(1)(tree), Option.some([-1, \"c\"]))\n  })\n\n  it(\"forEachGreaterThanEqual\", () => {\n    const ordered: Array<[number, string]> = []\n    pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\"),\n      RedBlackTree.forEachGreaterThanEqual(0, (k, v) => {\n        ordered.push([k, v])\n      })\n    )\n\n    deepStrictEqual(ordered, [[0, \"b\"], [1, \"a\"], [3, \"e\"]])\n  })\n\n  it(\"forEachLessThan\", () => {\n    const ordered: Array<[number, string]> = []\n    pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\"),\n      RedBlackTree.forEachLessThan(0, (k, v) => {\n        ordered.push([k, v])\n      })\n    )\n\n    deepStrictEqual(ordered, [[-2, \"d\"], [-1, \"c\"]])\n  })\n\n  it(\"forEachBetween\", () => {\n    const ordered: Array<[number, string]> = []\n    pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\"),\n      RedBlackTree.forEachBetween({\n        min: -1,\n        max: 2,\n        body: (k, v) => {\n          ordered.push([k, v])\n        }\n      })\n    )\n\n    deepStrictEqual(ordered, [[-1, \"c\"], [0, \"b\"], [1, \"a\"]])\n  })\n\n  it(\"greaterThan\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\")\n    )\n\n    deepStrictEqual(Array.from(RedBlackTree.greaterThan(0)(tree)), [\n      [1, \"a\"],\n      [3, \"e\"]\n    ])\n    deepStrictEqual(\n      Array.from(RedBlackTree.greaterThanReversed(0)(tree)),\n      [\n        [1, \"a\"],\n        [0, \"b\"],\n        [-1, \"c\"],\n        [-2, \"d\"]\n      ]\n    )\n  })\n\n  it(\"greaterThanEqual\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\")\n    )\n\n    deepStrictEqual(Array.from(RedBlackTree.greaterThanEqual(0)(tree)), [\n      [0, \"b\"],\n      [1, \"a\"],\n      [3, \"e\"]\n    ])\n    deepStrictEqual(\n      Array.from(RedBlackTree.greaterThanEqualReversed(0)(tree)),\n      [\n        [0, \"b\"],\n        [-1, \"c\"],\n        [-2, \"d\"]\n      ]\n    )\n  })\n\n  it(\"lessThan\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\")\n    )\n\n    deepStrictEqual(Array.from(RedBlackTree.lessThan(0)(tree)), [\n      [-1, \"c\"],\n      [0, \"b\"],\n      [1, \"a\"],\n      [3, \"e\"]\n    ])\n    deepStrictEqual(\n      Array.from(RedBlackTree.lessThanReversed(0)(tree)),\n      [\n        [-1, \"c\"],\n        [-2, \"d\"]\n      ]\n    )\n  })\n\n  it(\"lessThanEqual\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(0, \"b\"),\n      RedBlackTree.insert(-1, \"c\"),\n      RedBlackTree.insert(-2, \"d\"),\n      RedBlackTree.insert(3, \"e\")\n    )\n\n    deepStrictEqual(Array.from(RedBlackTree.lessThanEqual(0)(tree)), [\n      [0, \"b\"],\n      [1, \"a\"],\n      [3, \"e\"]\n    ])\n    deepStrictEqual(\n      Array.from(RedBlackTree.lessThanEqualReversed(0)(tree)),\n      [\n        [0, \"b\"],\n        [-1, \"c\"],\n        [-2, \"d\"]\n      ]\n    )\n  })\n\n  it(\"findAll\", () => {\n    const tree = pipe(\n      RedBlackTree.empty<number, string>(Num.Order),\n      RedBlackTree.insert(1, \"a\"),\n      RedBlackTree.insert(2, \"c\"),\n      RedBlackTree.insert(1, \"b\"),\n      RedBlackTree.insert(3, \"d\"),\n      RedBlackTree.insert(1, \"e\")\n    )\n\n    deepStrictEqual(Array.from(RedBlackTree.findAll(1)(tree)), [\"a\", \"b\", \"e\"])\n\n    const bigintTree = pipe(\n      RedBlackTree.empty(Order.bigint),\n      RedBlackTree.insert(1n, 1),\n      RedBlackTree.insert(1n, 2),\n      RedBlackTree.insert(1n, 3),\n      RedBlackTree.insert(1n, 4),\n      RedBlackTree.insert(1n, 5),\n      RedBlackTree.insert(2n, 6)\n    )\n\n    deepStrictEqual(Array.from(RedBlackTree.findAll(1n)(bigintTree)), [1, 2, 3, 4, 5])\n  })\n\n  it(\"findAll Eq/Ord\", () => {\n    class Key {\n      constructor(readonly n: number, readonly s: string) {}\n\n      [Hash.symbol](): number {\n        return Hash.combine(Hash.hash(this.n))(Hash.hash(this.s))\n      }\n\n      [Equal.symbol](that: unknown): boolean {\n        return that instanceof Key && this.n === that.n && this.s === that.s\n      }\n    }\n\n    const ord = pipe(Num.Order, Order.mapInput((key: Key) => key.n))\n\n    const tree = pipe(\n      RedBlackTree.empty<Key, string>(ord),\n      RedBlackTree.insert(new Key(1, \"0\"), \"a\"),\n      RedBlackTree.insert(new Key(2, \"0\"), \"c\"),\n      RedBlackTree.insert(new Key(1, \"1\"), \"b\"),\n      RedBlackTree.insert(new Key(3, \"0\"), \"d\"),\n      RedBlackTree.insert(new Key(1, \"0\"), \"e\"),\n      RedBlackTree.insert(new Key(1, \"0\"), \"f\"),\n      RedBlackTree.insert(new Key(1, \"1\"), \"g\")\n    )\n\n    deepStrictEqual(Array.from(RedBlackTree.values(tree)), [\"g\", \"f\", \"e\", \"b\", \"a\", \"c\", \"d\"])\n    deepStrictEqual(Array.from(RedBlackTree.findAll(new Key(1, \"0\"))(tree)), [\"a\", \"e\", \"f\"])\n    deepStrictEqual(\n      Array.from(RedBlackTree.values(RedBlackTree.removeFirst(new Key(1, \"1\"))(tree))),\n      [\n        \"f\",\n        \"e\",\n        \"b\",\n        \"a\",\n        \"c\",\n        \"d\"\n      ]\n    )\n    deepStrictEqual(\n      Array.from(RedBlackTree.values(RedBlackTree.removeFirst(new Key(1, \"0\"))(tree))),\n      [\n        \"g\",\n        \"f\",\n        \"e\",\n        \"b\",\n        \"c\",\n        \"d\"\n      ]\n    )\n  })\n\n  it(\"Equal.symbol\", () => {\n    assertTrue(\n      Equal.equals(RedBlackTree.empty<number, string>(Num.Order), RedBlackTree.empty<number, string>(Num.Order))\n    )\n    assertTrue(\n      Equal.equals(\n        RedBlackTree.make(Num.Order)([1, true], [2, true]),\n        RedBlackTree.make(Num.Order)([1, true], [2, true])\n      )\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Redacted.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual, throws } from \"@effect/vitest/utils\"\nimport { Chunk, Equal, Hash, Redacted, Secret } from \"effect\"\n\ndescribe(\"Redacted\", () => {\n  it(\"chunk constructor\", () => {\n    const redacted = Redacted.make(Chunk.fromIterable(\"redacted\".split(\"\")))\n    assertTrue(Equal.equals(redacted, Redacted.make(Chunk.fromIterable(\"redacted\".split(\"\")))))\n  })\n\n  it(\"value\", () => {\n    const redacted = Redacted.make(Chunk.fromIterable(\"redacted\".split(\"\")))\n    const value = Redacted.value(redacted)\n    assertTrue(Equal.equals(value, Chunk.fromIterable(\"redacted\".split(\"\"))))\n  })\n\n  it(\"pipe\", () => {\n    const value = { asd: 123 }\n    const redacted = Redacted.make(value)\n    const extractedValue = redacted.pipe(Redacted.value)\n    strictEqual(value, extractedValue)\n  })\n\n  it(\"toString\", () => {\n    const redacted = Redacted.make(\"redacted\")\n    strictEqual(`${redacted}`, \"<redacted>\")\n  })\n\n  it(\"toJSON\", () => {\n    const redacted = Redacted.make(\"redacted\")\n    strictEqual(JSON.stringify(redacted), \"\\\"<redacted>\\\"\")\n  })\n\n  it(\"unsafeWipe\", () => {\n    const redacted = Redacted.make(\"redacted\")\n    assertTrue(Redacted.unsafeWipe(redacted))\n    throws(() => Redacted.value(redacted), new Error(\"Unable to get redacted value\"))\n  })\n\n  it(\"Equal\", () => {\n    assertTrue(Equal.equals(Redacted.make(1), Redacted.make(1)))\n    assertFalse(Equal.equals(Redacted.make(1), Redacted.make(2)))\n  })\n\n  it(\"Hash\", () => {\n    strictEqual(Hash.hash(Redacted.make(1)), Hash.hash(Redacted.make(1)))\n    assertTrue(Hash.hash(Redacted.make(1)) !== Hash.hash(Redacted.make(2)))\n  })\n\n  describe(\"Secret extends Redacted\", () => {\n    it(\"Redacted.isRedacted\", () => {\n      const secret = Secret.fromString(\"test\")\n      assertTrue(\n        Redacted.isRedacted(secret)\n      )\n    })\n    it(\"Redacted.unsafeWipe\", () => {\n      const secret = Secret.fromString(\"test\")\n      assertTrue(Redacted.unsafeWipe(secret))\n    })\n    it(\"Redacted.value\", () => {\n      const value = \"test\"\n      const secret = Secret.fromString(value)\n      strictEqual(value, Redacted.value(secret))\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Ref.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Effect, Option, pipe, Readable, Ref } from \"effect\"\n\nconst current = \"value\"\nconst update = \"new value\"\n\ntype State = Active | Changed | Closed\n\ninterface Active {\n  readonly _tag: \"Active\"\n}\n\ninterface Changed {\n  readonly _tag: \"Changed\"\n}\n\ninterface Closed {\n  readonly _tag: \"Closed\"\n}\n\nexport const Active: State = { _tag: \"Active\" }\nexport const Changed: State = { _tag: \"Changed\" }\nexport const Closed: State = { _tag: \"Closed\" }\n\nconst isActive = (self: State): boolean => self._tag === \"Active\"\nconst isChanged = (self: State): boolean => self._tag === \"Changed\"\nconst isClosed = (self: State): boolean => self._tag === \"Closed\"\n\ndescribe(\"Ref\", () => {\n  it.effect(\"implements Readable\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(123)\n      assertTrue(Readable.isReadable(ref))\n      strictEqual(yield* ref, 123)\n    }))\n\n  it.effect(\"get\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Ref.make(current), Effect.flatMap(Ref.get))\n      strictEqual(result, current)\n    }))\n  it.effect(\"getAndSet\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(current)\n      const result1 = yield* Ref.getAndSet(ref, update)\n\n      const result2 = yield* ref\n      strictEqual(result1, current)\n      strictEqual(result2, update)\n    }))\n  it.effect(\"getAndUpdate\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(current)\n      const result1 = yield* Ref.getAndUpdate(ref, () => update)\n      const result2 = yield* ref\n      strictEqual(result1, current)\n      strictEqual(result2, update)\n    }))\n  it.effect(\"getAndUpdateSome - once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<State>(Active)\n      const result1 = yield* Ref.getAndUpdateSome(\n        ref,\n        (state) => isClosed(state) ? Option.some(Changed) : Option.none()\n      )\n      const result2 = yield* Ref.get(ref)\n      strictEqual(result1, Active)\n      strictEqual(result2, Active)\n    }))\n  it.effect(\"getAndUpdateSome - twice\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<State>(Active)\n      const result1 = yield* Ref.getAndUpdateSome(\n        ref,\n        (state) => isActive(state) ? Option.some(Changed) : Option.none()\n      )\n      const result2 = yield* Ref.getAndUpdateSome(ref, (state) =>\n        isActive(state) ?\n          Option.some(Changed) :\n          isChanged(state) ?\n          Option.some(Closed) :\n          Option.none())\n      const result3 = yield* Ref.get(ref)\n      strictEqual(result1, Active)\n      strictEqual(result2, Changed)\n      strictEqual(result3, Closed)\n    }))\n  it.effect(\"set\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(current)\n      yield* Ref.set(ref, update)\n      const result = yield* Ref.get(ref)\n      strictEqual(result, update)\n    }))\n  it.effect(\"update\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(current)\n      yield* Ref.update(ref, () => update)\n      const result = yield* Ref.get(ref)\n      strictEqual(result, update)\n    }))\n  it.effect(\"updateAndGet\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(current)\n      const result = yield* Ref.updateAndGet(ref, () => update)\n      strictEqual(result, update)\n    }))\n  it.effect(\"updateSome - once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<State>(Active)\n      yield* Ref.updateSome(ref, (state) => isClosed(state) ? Option.some(Changed) : Option.none())\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(result, Active)\n    }))\n  it.effect(\"updateSome - twice\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<State>(Active)\n      yield* Ref.updateSome(ref, (state) => isActive(state) ? Option.some(Changed) : Option.none())\n      const result1 = yield* Ref.get(ref)\n      yield* Ref.updateSome(ref, (state) =>\n        isActive(state) ?\n          Option.some(Changed) :\n          isChanged(state) ?\n          Option.some(Closed) :\n          Option.none())\n      const result2 = yield* Ref.get(ref)\n      deepStrictEqual(result1, Changed)\n      deepStrictEqual(result2, Closed)\n    }))\n  it.effect(\"updateSomeAndGet - once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<State>(Active)\n      const result = yield* Ref.updateSomeAndGet(ref, (state) => isClosed(state) ? Option.some(Changed) : Option.none())\n      strictEqual(result, Active)\n    }))\n  it.effect(\"updateSomeAndGet - twice\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<State>(Active)\n      const result1 = yield* Ref.updateSomeAndGet(\n        ref,\n        (state) => isActive(state) ? Option.some(Changed) : Option.none()\n      )\n      const result2 = yield* Ref.updateSomeAndGet(ref, (state): Option.Option<State> => {\n        return isActive(state) ?\n          Option.some(Changed) :\n          isChanged(state) ?\n          Option.some(Closed) :\n          Option.none()\n      })\n      deepStrictEqual(result1, Changed)\n      deepStrictEqual(result2, Closed)\n    }))\n  it.effect(\"modify\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(current)\n      const result1 = yield* Ref.modify(ref, () => [\"hello\", update])\n      const result2 = yield* Ref.get(ref)\n      strictEqual(result1, \"hello\")\n      strictEqual(result2, update)\n    }))\n  it.effect(\"modifySome - once\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<State>(Active)\n      const result = yield* Ref.modifySome(ref, \"state does not change\", (state) =>\n        isClosed(state) ?\n          Option.some([\"active\", Active]) :\n          Option.none())\n      strictEqual(result, \"state does not change\")\n    }))\n  it.effect(\"modifySome - twice\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<State>(Active)\n      const result1 = yield* Ref.modifySome(ref, \"state does not change\", (state) =>\n        isActive(state) ?\n          Option.some([\"changed\", Changed]) :\n          Option.none())\n      const result2 = yield* Ref.modifySome(ref, \"state does not change\", (state) =>\n        isActive(state) ?\n          Option.some([\"changed\", Changed]) :\n          isChanged(state) ?\n          Option.some([\"closed\", Closed]) :\n          Option.none())\n      strictEqual(result1, \"changed\")\n      strictEqual(result2, \"closed\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/RegExp.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport { RegExp } from \"effect\"\n\ndescribe(\"RegExp\", () => {\n  it(\"isRegExp\", () => {\n    assertTrue(RegExp.isRegExp(/a/))\n    assertFalse(RegExp.isRegExp(null))\n    assertFalse(RegExp.isRegExp(\"a\"))\n  })\n\n  describe(\"escape\", () => {\n    it(\"should escape special characters correctly\", () => {\n      const testCases: Array<[string, string]> = [\n        [\"abc\", \"abc\"],\n        [\"a*b\", \"a\\\\*b\"],\n        [\"a.b\", \"a\\\\.b\"],\n        [\"a|b\", \"a\\\\|b\"],\n        [\"a?b\", \"a\\\\?b\"],\n        [\"a+b\", \"a\\\\+b\"],\n        [\"a(b\", \"a\\\\(b\"],\n        [\"a)b\", \"a\\\\)b\"],\n        [\"a[b\", \"a\\\\[b\"],\n        [\"a]b\", \"a\\\\]b\"],\n        [\"a{b\", \"a\\\\{b\"],\n        [\"a}b\", \"a\\\\}b\"],\n        [\"a^b\", \"a\\\\^b\"],\n        [\"a$b\", \"a\\\\$b\"],\n        [\"a\\\\b\", \"a\\\\\\\\b\"],\n        [\"a/b\", \"a\\\\/b\"]\n      ]\n\n      testCases.forEach(([input, expected]) => {\n        const result = RegExp.escape(input)\n        strictEqual(result, expected)\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Reloadable.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { Context, Effect, Layer, pipe, Reloadable } from \"effect\"\nimport * as Counter from \"./utils/counter.js\"\n\nconst DummyServiceTypeId = Symbol.for(\"effect/test/Reloadable/DummyService\")\ntype DummyServiceTypeId = typeof DummyServiceTypeId\n\ninterface DummyService {\n  readonly [DummyServiceTypeId]: DummyServiceTypeId\n}\n\nconst DummyService: DummyService = {\n  [DummyServiceTypeId]: DummyServiceTypeId\n}\n\nconst Tag = Context.GenericTag<DummyService>(\"DummyService\")\n\ndescribe(\"Reloadable\", () => {\n  it.effect(\"initialization\", () =>\n    Effect.gen(function*() {\n      const counter = yield* Counter.make()\n      const layer = Reloadable.manual(Tag, {\n        layer: Layer.scoped(Tag, pipe(counter.acquire(), Effect.as(DummyService)))\n      })\n      yield* pipe(Reloadable.get(Tag), Effect.provide(layer))\n      const acquired = yield* counter.acquired()\n      strictEqual(acquired, 1)\n    }))\n  it.effect(\"reload\", () =>\n    Effect.gen(function*() {\n      const counter = yield* Counter.make()\n      const layer = Reloadable.manual(Tag, {\n        layer: Layer.scoped(Tag, pipe(counter.acquire(), Effect.as(DummyService)))\n      })\n      yield* pipe(Reloadable.reload(Tag), Effect.provide(layer))\n      const acquired = yield* counter.acquired()\n      strictEqual(acquired, 2)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Resource.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { Duration, Effect, Either, identity, pipe, Ref, Resource, Schedule } from \"effect\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Resource\", () => {\n  it.scoped(\"manual\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(0)\n      const cached = yield* Resource.manual(Ref.get(ref))\n      const resul1 = yield* Resource.get(cached)\n      const result2 = yield* pipe(\n        Ref.set(ref, 1),\n        Effect.zipRight(Resource.refresh(cached)),\n        Effect.zipRight(Resource.get(cached))\n      )\n      strictEqual(resul1, 0)\n      strictEqual(result2, 1)\n    }))\n  it.scoped(\"auto\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(0)\n      const cached = yield* Resource.auto(Ref.get(ref), Schedule.spaced(Duration.millis(4)))\n      const result1 = yield* Resource.get(cached)\n      const result2 = yield* pipe(\n        Ref.set(ref, 1),\n        Effect.zipRight(TestClock.adjust(Duration.millis(5))),\n        Effect.zipRight(Resource.get(cached))\n      )\n      strictEqual(result1, 0)\n      strictEqual(result2, 1)\n    }))\n  it.scopedLive(\"failed refresh doesn't affect cached value\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<Either.Either<number, string>>(Either.right(0))\n      const cached = yield* Resource.auto(Effect.flatMap(Ref.get(ref), identity), Schedule.spaced(Duration.millis(4)))\n      const result1 = yield* Resource.get(cached)\n      const result2 = yield* pipe(\n        Ref.set(ref, Either.left(\"Uh oh!\")),\n        Effect.zipRight(Effect.sleep(Duration.millis(5))),\n        Effect.zipRight(Resource.get(cached))\n      )\n      strictEqual(result1, 0)\n      strictEqual(result2, 0)\n    }))\n  it.scoped(\"subtype of Effect\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(0)\n      const cached = yield* Resource.manual(ref)\n      const resul1 = yield* cached\n\n      strictEqual(resul1, 0)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Runtime.test.ts",
    "content": "import { AsyncLocalStorage } from \"node:async_hooks\"\n\nimport { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual, throwsAsync } from \"@effect/vitest/utils\"\nimport { Effect, Exit, FiberRef, Layer, pipe, Runtime } from \"effect\"\n\ndescribe(\"Runtime\", () => {\n  it.effect(\"setFiberRef\", () =>\n    Effect.gen(function*() {\n      const ref = FiberRef.unsafeMake(0)\n      const runtime = Runtime.defaultRuntime.pipe(\n        Runtime.setFiberRef(ref, 1)\n      )\n      let result = Runtime.runSync(runtime)(FiberRef.get(ref))\n      strictEqual(result, 1)\n\n      result = yield* pipe(FiberRef.get(ref), Effect.provide(runtime))\n      strictEqual(result, 1)\n    }))\n\n  it.scoped(\"deleteFiberRef\", () =>\n    Effect.gen(function*() {\n      const ref = FiberRef.unsafeMake({ value: 0 })\n      const runtime = yield* (Layer.toRuntime(Layer.effectDiscard(FiberRef.set(ref, { value: 1 }))))\n\n      let result = Runtime.runSync(runtime)(FiberRef.get(ref))\n      deepStrictEqual(result, { value: 1 })\n\n      result = Runtime.runSync(Runtime.deleteFiberRef(runtime, ref))(FiberRef.get(ref))\n      deepStrictEqual(result, { value: 0 })\n    }))\n\n  it(\"runSync\", () => {\n    deepStrictEqual(Runtime.runSync(Runtime.defaultRuntime)(Effect.succeed(1)), 1)\n    deepStrictEqual(Runtime.runSync(Runtime.defaultRuntime, Effect.succeed(1)), 1)\n  })\n\n  it(\"runSyncExit\", () => {\n    deepStrictEqual(Runtime.runSyncExit(Runtime.defaultRuntime)(Effect.succeed(1)), Exit.succeed(1))\n    deepStrictEqual(Runtime.runSyncExit(Runtime.defaultRuntime, Effect.succeed(1)), Exit.succeed(1))\n\n    deepStrictEqual(Runtime.runSyncExit(Runtime.defaultRuntime)(Effect.fail(1)), Exit.fail(1))\n    deepStrictEqual(Runtime.runSyncExit(Runtime.defaultRuntime, Effect.fail(1)), Exit.fail(1))\n  })\n\n  it(\"runPromise\", async () => {\n    deepStrictEqual(\n      await Runtime.runPromise(Runtime.defaultRuntime)(Effect.promise(async () => 1)),\n      1\n    )\n    throwsAsync(\n      async () => {\n        await Runtime.runPromise(Runtime.defaultRuntime)(\n          Effect.tryPromise({ try: () => new Promise((_, reject) => reject(1)), catch: () => \"error\" })\n        )\n      }\n    )\n\n    deepStrictEqual(\n      await Runtime.runPromise(Runtime.defaultRuntime, Effect.promise(async () => 1)),\n      1\n    )\n    throwsAsync(\n      async () => {\n        await Runtime.runPromise(\n          Runtime.defaultRuntime,\n          Effect.tryPromise({ try: () => new Promise((_, reject) => reject(1)), catch: () => \"error\" })\n        )\n      }\n    )\n  })\n\n  it.effect(\"runPromise isolates AsyncLocalStorage across concurrent calls\", () =>\n    Effect.gen(function*() {\n      type RequestStore = {\n        readonly userId: string\n      }\n\n      type Result = {\n        readonly expected: string\n        readonly observed: string\n      }\n\n      const requestStore = new AsyncLocalStorage<RequestStore>()\n\n      const readAlsOnScheduledContinuation = Effect.withFiberRuntime<Result>((fiber) =>\n        Effect.sync(() => requestStore.getStore()?.userId ?? \"NONE\").pipe(\n          Effect.flatMap((expected) =>\n            Effect.async<Result>((resume) => {\n              fiber.currentScheduler.scheduleTask(\n                () => {\n                  resume(\n                    Effect.succeed({\n                      expected,\n                      observed: requestStore.getStore()?.userId ?? \"NONE\"\n                    })\n                  )\n                },\n                0,\n                fiber\n              )\n            })\n          )\n        )\n      )\n\n      const runtime = yield* Effect.runtime<never>()\n\n      const runRequest = (userId: string): Promise<Result> =>\n        requestStore.run(\n          { userId },\n          () => Runtime.runPromise(runtime)(readAlsOnScheduledContinuation)\n        )\n\n      const results = yield* Effect.promise(() =>\n        Promise.all([\n          runRequest(\"user-A\"),\n          runRequest(\"user-B\")\n        ])\n      )\n\n      deepStrictEqual(results, [\n        { expected: \"user-A\", observed: \"user-A\" },\n        { expected: \"user-B\", observed: \"user-B\" }\n      ])\n    }))\n\n  it(\"runPromiseExit\", async () => {\n    deepStrictEqual(\n      await Runtime.runPromiseExit(Runtime.defaultRuntime)(Effect.promise(async () => 1)),\n      Exit.succeed(1)\n    )\n    deepStrictEqual(\n      await Runtime.runPromiseExit(Runtime.defaultRuntime)(\n        Effect.tryPromise({ try: () => new Promise((_, reject) => reject(1)), catch: () => \"error\" })\n      ),\n      Exit.fail(\"error\")\n    )\n\n    deepStrictEqual(\n      await Runtime.runPromiseExit(Runtime.defaultRuntime, Effect.promise(async () => 1)),\n      Exit.succeed(1)\n    )\n    deepStrictEqual(\n      await Runtime.runPromiseExit(\n        Runtime.defaultRuntime,\n        Effect.tryPromise({ try: () => new Promise((_, reject) => reject(1)), catch: () => \"error\" })\n      ),\n      Exit.fail(\"error\")\n    )\n  })\n\n  it(\"runPromiseExit/signal\", async () => {\n    const aborted = AbortSignal.abort()\n    assertTrue(\n      Exit.isInterrupted(await Runtime.runPromiseExit(Runtime.defaultRuntime)(Effect.never, { signal: aborted }))\n    )\n    assertTrue(\n      Exit.isInterrupted(await Runtime.runPromiseExit(Runtime.defaultRuntime, Effect.never, { signal: aborted }))\n    )\n\n    const controller = new AbortController()\n    setTimeout(() => controller.abort(), 10)\n    assertTrue(\n      Exit.isInterrupted(\n        await Runtime.runPromiseExit(Runtime.defaultRuntime)(Effect.never, { signal: controller.signal })\n      )\n    )\n    assertTrue(\n      Exit.isInterrupted(\n        await Runtime.runPromiseExit(Runtime.defaultRuntime, Effect.never, { signal: controller.signal })\n      )\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/RuntimeFlags.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport { FastCheck as fc, pipe, RuntimeFlags, RuntimeFlagsPatch } from \"effect\"\n\nconst arbRuntimeFlag = fc.constantFrom(\n  RuntimeFlags.None,\n  RuntimeFlags.Interruption,\n  RuntimeFlags.OpSupervision,\n  RuntimeFlags.RuntimeMetrics,\n  RuntimeFlags.WindDown,\n  RuntimeFlags.CooperativeYielding\n)\n\nconst arbRuntimeFlags = fc.uniqueArray(arbRuntimeFlag).map(\n  (flags) => RuntimeFlags.make(...flags)\n)\n\ndescribe(\"RuntimeFlags\", () => {\n  it(\"isDisabled & isEnabled\", () => {\n    const flags = RuntimeFlags.make(\n      RuntimeFlags.RuntimeMetrics,\n      RuntimeFlags.Interruption\n    )\n    assertTrue(RuntimeFlags.isEnabled(flags, RuntimeFlags.RuntimeMetrics))\n    assertTrue(RuntimeFlags.isEnabled(flags, RuntimeFlags.Interruption))\n    assertFalse(RuntimeFlags.isEnabled(flags, RuntimeFlags.CooperativeYielding))\n    assertFalse(RuntimeFlags.isEnabled(flags, RuntimeFlags.OpSupervision))\n    assertFalse(RuntimeFlags.isEnabled(flags, RuntimeFlags.WindDown))\n  })\n\n  it(\"enabled patching\", () => {\n    const patch = pipe(\n      RuntimeFlagsPatch.enable(RuntimeFlags.RuntimeMetrics),\n      RuntimeFlagsPatch.andThen(RuntimeFlagsPatch.enable(RuntimeFlags.OpSupervision))\n    )\n    const result = RuntimeFlags.patch(RuntimeFlags.none, patch)\n\n    const expected = RuntimeFlags.make(\n      RuntimeFlags.RuntimeMetrics,\n      RuntimeFlags.OpSupervision\n    )\n    strictEqual(result, expected)\n  })\n\n  it(\"inverse patching\", () => {\n    const flags = RuntimeFlags.make(\n      RuntimeFlags.RuntimeMetrics,\n      RuntimeFlags.OpSupervision\n    )\n    const patch1 = pipe(\n      RuntimeFlagsPatch.enable(RuntimeFlags.RuntimeMetrics),\n      RuntimeFlagsPatch.inverse\n    )\n    const patch2 = pipe(\n      RuntimeFlagsPatch.enable(RuntimeFlags.RuntimeMetrics),\n      RuntimeFlagsPatch.andThen(RuntimeFlagsPatch.enable(RuntimeFlags.OpSupervision)),\n      RuntimeFlagsPatch.inverse\n    )\n    strictEqual(\n      RuntimeFlags.patch(flags, patch1),\n      RuntimeFlags.make(RuntimeFlags.OpSupervision)\n    )\n    strictEqual(\n      RuntimeFlags.patch(flags, patch2),\n      RuntimeFlags.none\n    )\n  })\n\n  it(\"diff\", () => {\n    const flags1 = RuntimeFlags.make(RuntimeFlags.RuntimeMetrics)\n    const flags2 = RuntimeFlags.make(RuntimeFlags.RuntimeMetrics, RuntimeFlags.OpSupervision)\n    strictEqual(\n      RuntimeFlags.diff(flags1, flags2),\n      RuntimeFlagsPatch.enable(RuntimeFlags.OpSupervision)\n    )\n  })\n\n  it(\"flags within a set of RuntimeFlags is enabled\", () => {\n    fc.assert(fc.property(arbRuntimeFlags, (flags) => {\n      const result = Array.from(RuntimeFlags.toSet(flags)).every(\n        (flag) => RuntimeFlags.isEnabled(flags, flag)\n      )\n      assertTrue(result)\n    }))\n  })\n\n  it(\"patching a diff between `none` and a set of flags is an identity\", () => {\n    fc.assert(fc.property(arbRuntimeFlags, (flags) => {\n      const diff = RuntimeFlags.diff(RuntimeFlags.none, flags)\n      strictEqual(\n        RuntimeFlags.patch(RuntimeFlags.none, diff),\n        flags\n      )\n    }))\n  })\n\n  it(\"patching the inverse diff between `non` and a set of flags is `none`\", () => {\n    fc.assert(fc.property(arbRuntimeFlags, (flags) => {\n      const diff = RuntimeFlags.diff(RuntimeFlags.none, flags)\n      strictEqual(\n        RuntimeFlags.patch(flags, RuntimeFlagsPatch.inverse(diff)),\n        RuntimeFlags.none\n      )\n      strictEqual(\n        RuntimeFlags.patch(flags, RuntimeFlagsPatch.inverse(RuntimeFlagsPatch.inverse(diff))),\n        flags\n      )\n    }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/STM.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFailure,\n  assertFalse,\n  assertLeft,\n  assertNone,\n  assertRight,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual\n} from \"@effect/vitest/utils\"\nimport {\n  Cause,\n  Chunk,\n  Context,\n  Deferred,\n  Effect,\n  Either,\n  Exit,\n  FastCheck as fc,\n  Fiber,\n  Option,\n  pipe,\n  STM,\n  TDeferred,\n  TQueue,\n  TRef\n} from \"effect\"\nimport { constFalse, constTrue, constVoid } from \"effect/Function\"\n\ninterface STMEnv {\n  readonly ref: TRef.TRef<number>\n}\n\nconst STMEnv = Context.GenericTag<STMEnv>(\"STMEnv\")\n\nconst makeSTMEnv = (n: number): Effect.Effect<STMEnv> =>\n  pipe(\n    TRef.make(n),\n    Effect.map((ref) => ({ ref }))\n  )\n\nclass UnpureBarrier {\n  #isOpen = false\n  open(): void {\n    this.#isOpen = true\n  }\n  await(): Effect.Effect<unknown> {\n    return Effect.async((cb) => {\n      const check = () => {\n        if (this.#isOpen) {\n          cb(Effect.void)\n        } else {\n          setTimeout(() => {\n            check()\n          }, 100)\n        }\n      }\n      setTimeout(check, 100)\n    })\n  }\n}\n\nconst chain = (depth: number) =>\n(\n  next: (stm: STM.STM<number>) => STM.STM<number>\n): Effect.Effect<number> => {\n  const loop = (_n: number, _acc: STM.STM<number>): Effect.Effect<number> => {\n    let n = _n\n    let acc = _acc\n    while (n > 0) {\n      acc = next(acc)\n      n = n - 1\n    }\n    return STM.commit(acc)\n  }\n  return loop(depth, STM.succeed(0))\n}\n\nconst chainError = (depth: number): Effect.Effect<never, number> => {\n  const loop = (_n: number, _acc: STM.STM<never, number, never>): Effect.Effect<never, number> => {\n    let n = _n\n    let acc = _acc\n    while (n > 0) {\n      acc = pipe(acc, STM.mapError((n) => n + 1))\n      n = n - 1\n    }\n    return STM.commit(acc)\n  }\n  return loop(depth, STM.fail(0))\n}\n\nconst incrementTRefN = (n: number, ref: TRef.TRef<number>): Effect.Effect<number> =>\n  pipe(\n    TRef.get(ref),\n    STM.tap((n) => pipe(ref, TRef.set(n + 1))),\n    STM.zipRight(TRef.get(ref)),\n    STM.commit,\n    Effect.repeatN(n)\n  )\n\nconst transfer = (\n  receiver: TRef.TRef<number>,\n  sender: TRef.TRef<number>,\n  much: number\n): Effect.Effect<number> =>\n  pipe(\n    TRef.get(sender),\n    STM.tap((balance) => STM.check(() => balance >= much)),\n    STM.tap(() => pipe(receiver, TRef.update((n) => n + much))),\n    STM.tap(() => pipe(sender, TRef.update((n) => n - much))),\n    STM.zipRight(TRef.get(receiver)),\n    STM.commit\n  )\n\nconst compute3TRefN = (\n  n: number,\n  ref1: TRef.TRef<number>,\n  ref2: TRef.TRef<number>,\n  ref3: TRef.TRef<number>\n): Effect.Effect<number> =>\n  pipe(\n    STM.all([TRef.get(ref1), TRef.get(ref2)]),\n    STM.tap(([v1, v2]) => pipe(ref3, TRef.set(v1 + v2))),\n    STM.flatMap(([v1, v2]) =>\n      pipe(\n        TRef.get(ref3),\n        STM.flatMap((v3) =>\n          pipe(\n            ref1,\n            TRef.set(v1 - 1),\n            STM.zipRight(pipe(ref2, TRef.set(v2 + 1))),\n            STM.as(v3)\n          )\n        )\n      )\n    ),\n    STM.commit,\n    Effect.repeatN(n)\n  )\n\nconst permutation = (ref1: TRef.TRef<number>, ref2: TRef.TRef<number>): STM.STM<void> =>\n  pipe(\n    STM.all([TRef.get(ref1), TRef.get(ref2)]),\n    STM.flatMap(([a, b]) =>\n      pipe(\n        ref1,\n        TRef.set(b),\n        STM.tap(() => pipe(ref2, TRef.set(a))),\n        STM.asVoid\n      )\n    )\n  )\n\ndescribe(\"STM\", () => {\n  it.effect(\"catchAll\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.fail(\"Ouch!\"),\n        STM.tap(() => STM.succeed(\"everything is fine\")),\n        STM.catchAll((s) => STM.succeed(`${s} phew`))\n      )\n      const result = yield* STM.commit(transaction)\n      deepStrictEqual(result, \"Ouch! phew\")\n    }))\n\n  it.effect(\"collectAll - ordering\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TQueue.bounded<number>(3),\n        STM.tap((queue) => pipe(queue, TQueue.offer(1))),\n        STM.tap((queue) => pipe(queue, TQueue.offer(2))),\n        STM.tap((queue) => pipe(queue, TQueue.offer(3))),\n        STM.flatMap((queue) => STM.all(Array.from({ length: 3 }, () => TQueue.take(queue))))\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"catchSome - catches matched errors\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.fail(new Cause.RuntimeException(\"Ouch\")),\n        STM.tap(() => STM.succeed(\"everything is fine\")),\n        STM.catchSome((e) =>\n          Cause.isRuntimeException(e) ?\n            Option.some(STM.succeed(\"gotcha\")) :\n            Option.none()\n        )\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, \"gotcha\")\n    }))\n\n  it.effect(\"catchSome - lets the error pass\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const transaction = pipe(\n        STM.fail(error),\n        STM.tap(() => STM.succeed(\"everything is fine\")),\n        STM.catchSome((e) =>\n          Cause.isIllegalArgumentException(e) ?\n            Option.some(STM.succeed(\"gotcha\")) :\n            Option.none()\n        )\n      )\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"collectAll - collects a list of transactional effects to a single transaction\", () =>\n    Effect.gen(function*() {\n      const chunk: Chunk.Chunk<number> = Chunk.range(1, 100)\n      const iterable = yield* (Effect.succeed(pipe(chunk, Chunk.map(TRef.make))))\n      const refs = yield* (STM.all(iterable))\n      const result = yield* (\n        Effect.forEach(refs, TRef.get, {\n          concurrency: \"unbounded\"\n        })\n      )\n      deepStrictEqual(Array.from(result), Array.from(chunk))\n    }))\n\n  it.effect(\"either - convert a successful computation into a Right\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.either(STM.succeed(42))\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, Either.right(42))\n    }))\n\n  it.effect(\"either - convert a failed computation into a Left\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.either(STM.fail(\"Ouch\"))\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, Either.left(\"Ouch\"))\n    }))\n\n  it.effect(\"environment - access and provide outside transaction\", () =>\n    Effect.gen(function*() {\n      const result = yield* (pipe(\n        makeSTMEnv(0),\n        Effect.flatMap((env) =>\n          pipe(\n            STM.flatMap(STMEnv, (env) => pipe(env.ref, TRef.update((n) => n + 1))),\n            STM.provideContext(Context.make(STMEnv, env)),\n            STM.commit,\n            Effect.zipRight(TRef.get(env.ref))\n          )\n        )\n      ))\n      deepStrictEqual(result, 1)\n    }))\n\n  it.effect(\"environment - access and provide inside transaction\", () =>\n    Effect.gen(function*() {\n      const result = yield* (pipe(\n        makeSTMEnv(0),\n        Effect.flatMap((env) =>\n          pipe(\n            STM.flatMap(STMEnv, (env) => pipe(env.ref, TRef.update((n) => n + 1))),\n            STM.provideContext(Context.make(STMEnv, env)),\n            STM.zipRight(TRef.get(env.ref))\n          )\n        )\n      ))\n      deepStrictEqual(result, 1)\n    }))\n\n  it.effect(\"eventually - succeeds\", () =>\n    Effect.gen(function*() {\n      const f = (ref: TRef.TRef<number>) =>\n        STM.gen(function*() {\n          const n = yield* TRef.get(ref)\n          return yield* n < 10 ?\n            pipe(ref, TRef.update((n) => n + 1), STM.zipRight(STM.fail(\"Ouch\"))) :\n            STM.succeed(n)\n        })\n      const transaction = pipe(\n        TRef.make(0),\n        STM.flatMap((ref) => STM.eventually(f(ref)))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 10)\n    }))\n\n  it.effect(\"fail\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.exit(STM.commit(STM.fail(\"Ouch\"))))\n      deepStrictEqual(result, Exit.fail(\"Ouch\"))\n    }))\n\n  it.effect(\"filter - filters a collection using an effectual predicate\", () =>\n    Effect.gen(function*() {\n      const array = [2, 4, 6, 3, 5, 6]\n      const transaction = STM.gen(function*() {\n        const ref = yield* (TRef.make(Chunk.empty<number>()))\n        const results = yield* (pipe(\n          array,\n          STM.filter((n) => pipe(ref, TRef.update(Chunk.append(n)), STM.as(n % 2 === 0)))\n        ))\n        const effects = yield* (TRef.get(ref))\n        return { results, effects }\n      })\n      const { effects, results } = yield* (STM.commit(transaction))\n      deepStrictEqual(Array.from(results), [2, 4, 6, 6])\n      deepStrictEqual(Array.from(effects), array)\n    }))\n\n  it.effect(\"filterOrDie - dies when predicate fails\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const transaction = pipe(\n        STM.succeed(1),\n        STM.filterOrDie((n) => n !== 1, () => error)\n      )\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"filterOrDieMessage - dies with message when predicate fails\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(1),\n        STM.filterOrDieMessage((n) => n !== 1, \"Ouch\")\n      )\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.die(new Cause.RuntimeException(\"Ouch\")))\n    }))\n\n  it.effect(\"filterOrElse - returns checked failure\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(1),\n        STM.filterOrElse((n) => n === 1, () => STM.succeed(2))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"filterOrElse - returns held value\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(1),\n        STM.filterOrElse((n) => n !== 1, () => STM.succeed(2))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 2)\n    }))\n\n  it.effect(\"filterOrElse - returns checked failure\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(1),\n        STM.filterOrElse((n) => n === 1, (n) => STM.succeed(n + 1))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"filterOrElse - returns held value\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(1),\n        STM.filterOrElse((n) => n !== 1, (n) => STM.succeed(n + 1))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 2)\n    }))\n\n  it.effect(\"filterOrElse - returns error\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const transaction = pipe(\n        STM.fail(error),\n        STM.zipRight(STM.succeed(1)),\n        STM.filterOrElse((n) => n === 1, (n) => STM.succeed(n + 1))\n      )\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"filterOrFail - returns failure when predicate fails\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const transaction = pipe(\n        STM.succeed(1),\n        STM.filterOrFail((n) => n !== 1, () => error)\n      )\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"flatten\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.flatten(STM.succeed(STM.succeed(\"test\")))\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, \"test\")\n    }))\n\n  it.effect(\"forEach - performs an action on each chunk element and return a single transaction\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TRef.make(0))\n      const chunk = Chunk.range(1, 5)\n      yield* (pipe(chunk, STM.forEach((n) => pipe(ref, TRef.update((i) => i + n)))))\n      const expected = pipe(chunk, Chunk.reduceRight(0, (acc, curr) => acc + curr))\n      const result = yield* (TRef.get(ref))\n      strictEqual(result, expected)\n    }))\n\n  it.effect(\"forEach - performs an action on each chunk element\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TRef.make(0))\n      const chunk = Chunk.range(1, 5)\n      yield* (STM.forEach(chunk, (n) => pipe(ref, TRef.update((i) => i + n)), { discard: true }))\n      const expected = pipe(chunk, Chunk.reduceRight(0, (acc, curr) => acc + curr))\n      const result = yield* (TRef.get(ref))\n      strictEqual(result, expected)\n    }))\n\n  it.effect(\"fold - handles both failure and success\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.all({\n        success: pipe(STM.succeed(\"yes\"), STM.match({ onFailure: () => -1, onSuccess: () => 1 })),\n        failure: pipe(STM.fail(\"no\"), STM.match({ onFailure: () => -1, onSuccess: () => 1 }))\n      })\n      const { failure, success } = yield* (STM.commit(transaction))\n      strictEqual(success, 1)\n      strictEqual(failure, -1)\n    }))\n\n  it.effect(\"foldSTM - folds over the `STM` effect, and handle failure and success\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.all({\n        success: pipe(STM.succeed(\"yes\"), STM.matchSTM({ onFailure: () => STM.succeed(\"no\"), onSuccess: STM.succeed })),\n        failure: pipe(STM.fail(\"no\"), STM.matchSTM({ onFailure: STM.succeed, onSuccess: () => STM.succeed(\"yes\") }))\n      })\n      const { failure, success } = yield* (STM.commit(transaction))\n      strictEqual(failure, \"no\")\n      strictEqual(success, \"yes\")\n    }))\n\n  it.effect(\"head - extracts the first value from an iterable\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.head(STM.succeed([1, 2]))\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"head - returns None if the iterable is empty\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.head(STM.succeed([]))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      assertFailure(result, Cause.fail(Option.none()))\n    }))\n\n  it.effect(\"head - returns Some if there is an error\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.head(STM.fail(\"Ouch\"))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      assertFailure(result, Cause.fail(Option.some(\"Ouch\")))\n    }))\n\n  it.effect(\"if - runs `onTrue` if result is `true`\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(true),\n        STM.if({\n          onFalse: STM.succeed(-1),\n          onTrue: STM.succeed(1)\n        })\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"if - runs `onFalse` if result is `false`\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(false),\n        STM.if({\n          onFalse: STM.succeed(-1),\n          onTrue: STM.succeed(1)\n        })\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, -1)\n    }))\n\n  it.effect(\"mapBoth - success value\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.succeed(1), STM.mapBoth({ onFailure: () => -1, onSuccess: (n) => `${n} as string` }))\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, \"1 as string\")\n    }))\n\n  it.effect(\"mapBoth - success value\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.fail(-1), STM.mapBoth({ onFailure: (n) => `${n} as string`, onSuccess: () => 0 }))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(\"-1 as string\"))\n    }))\n\n  it.effect(\"mapError - map from one error to another\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.fail(-1), STM.mapError(() => \"Ouch\"))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(\"Ouch\"))\n    }))\n\n  it.effect(\"merge - on error\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.merge(STM.fromEither(Either.left(1)))\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"merge - on success\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.merge(STM.fromEither(Either.right(1)))\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"mergeAll - return zero element on empty input\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        Chunk.empty<STM.STM<number>>(),\n        STM.mergeAll(42, () => 43)\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 42)\n    }))\n\n  it.effect(\"mergeAll - merge iterable using function\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        [3, 5, 7].map((n) => STM.succeed(n)),\n        STM.mergeAll(1, (acc, curr) => acc + curr)\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1 + 3 + 5 + 7)\n    }))\n\n  it.effect(\"mergeAll - return error if it exists in list\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        [STM.void, STM.fail(1)] as Array<STM.STM<void, number>>,\n        STM.mergeAll(void 0 as void, constVoid)\n      )\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(1))\n    }))\n\n  it.effect(\"none - on None\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.none(STM.succeed(Option.none()))\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, undefined)\n    }))\n\n  it.effect(\"none - on Some\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.none(STM.succeed(Option.some(1)))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      assertFailure(result, Cause.fail(Option.none()))\n    }))\n\n  it.effect(\"none - on error\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const transaction = STM.none(STM.fail(error))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      assertFailure(result, Cause.fail(Option.some(error)))\n    }))\n\n  it.effect(\"option - success converts to Some\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.option(STM.succeed(42))\n      const result = yield* (STM.commit(transaction))\n      assertSome(result, 42)\n    }))\n\n  it.effect(\"option - failure converts to None\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.option(STM.fail(\"Ouch\"))\n      const result = yield* (STM.commit(transaction))\n      assertNone(result)\n    }))\n\n  it.effect(\"orElse - succeeds if left succeeds\", () =>\n    Effect.gen(function*() {\n      const left = STM.succeed(\"left\")\n      const right = STM.succeed(\"right\")\n      const result = yield* (STM.commit(pipe(left, STM.orElse(() => right))))\n      strictEqual(result, \"left\")\n    }))\n\n  it.effect(\"orElse - succeeds if right succeeds\", () =>\n    Effect.gen(function*() {\n      const left = STM.retry\n      const right = STM.succeed(\"right\")\n      const result = yield* (STM.commit(pipe(left, STM.orElse(() => right))))\n      strictEqual(result, \"right\")\n    }))\n\n  it.effect(\"orElse - tries alternative once left retries\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TRef.make(0))\n      const left = pipe(ref, TRef.update((n) => n + 100), STM.zipRight(STM.retry))\n      const right = pipe(ref, TRef.update((n) => n + 200))\n      yield* (pipe(left, STM.orElse(() => right)))\n      const result = yield* (TRef.get(ref))\n      strictEqual(result, 200)\n    }))\n\n  it.effect(\"orElse - tries alternative once left fails\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TRef.make(0))\n      const left = pipe(ref, TRef.update((n) => n + 100), STM.zipRight(STM.fail(\"boom\")))\n      const right = pipe(ref, TRef.update((n) => n + 200))\n      yield* (pipe(left, STM.orElse(() => right)))\n      const result = yield* (TRef.get(ref))\n      strictEqual(result, 200)\n    }))\n\n  it.effect(\"orElse - fail if alternative fails\", () =>\n    Effect.gen(function*() {\n      const left = STM.fail(\"left\")\n      const right = STM.fail(\"right\")\n      const result = yield* (pipe(left, STM.orElse(() => right), Effect.exit))\n      assertFailure(result, Cause.fail(\"right\"))\n    }))\n\n  it.effect(\"orElseEither - orElseEither returns result of the first successful transaction\", () =>\n    Effect.gen(function*() {\n      const result1 = yield* (pipe(STM.retry, STM.orElseEither(() => STM.succeed(42))))\n      const result2 = yield* (pipe(STM.succeed(1), STM.orElseEither(() => STM.succeed(\"no\"))))\n      const result3 = yield* (pipe(STM.succeed(2), STM.orElseEither(() => STM.retry)))\n      assertRight(result1, 42)\n      assertLeft(result2, 1)\n      assertLeft(result3, 2)\n    }))\n\n  it.effect(\"orElseFail - tries left first\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.succeed(true), STM.orElseFail(() => false))\n      const result = yield* (STM.commit(transaction))\n      assertTrue(result)\n    }))\n\n  it.effect(\"orElseFail - fails with the specified error once left retries\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.retry, STM.orElseFail(() => false), STM.either)\n      const result = yield* (STM.commit(transaction))\n      assertLeft(result, false)\n    }))\n\n  it.effect(\"orElseFail - fails with the specified error once left fails\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.fail(true), STM.orElseFail(() => false), STM.either)\n      const result = yield* (STM.commit(transaction))\n      assertLeft(result, false)\n    }))\n\n  it.effect(\"orElseSucceed - tries left first\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.succeed(true), STM.orElseSucceed(() => false))\n      const result = yield* (STM.commit(transaction))\n      assertTrue(result)\n    }))\n\n  it.effect(\"orElseSucceed - succeeds with the specified error once left retries\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.retry, STM.orElseSucceed(() => false))\n      const result = yield* (STM.commit(transaction))\n      assertFalse(result)\n    }))\n\n  it.effect(\"orElseSucceed - succeeds with the specified error once left fails\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.fail(true), STM.orElseSucceed(() => false))\n      const result = yield* (STM.commit(transaction))\n      assertFalse(result)\n    }))\n\n  it.effect(\"unsome - converts Some in E to error in E\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.unsome(STM.fromEither(Either.left(Option.some(\"Ouch\"))))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(\"Ouch\"))\n    }))\n\n  it.effect(\"unsome - converts None in E to None in A\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.unsome(STM.fromEither(Either.left(Option.none())))\n      const result = yield* (STM.commit(transaction))\n      assertNone(result)\n    }))\n\n  it.effect(\"unsome - no error\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.unsome(STM.fromEither(Either.right(42)))\n      const result = yield* (STM.commit(transaction))\n      assertSome(result, 42)\n    }))\n\n  it.effect(\"orDie - when failure should die\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const transaction = STM.orDie(STM.fail(error))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"orDie - when succeed should keep going\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.orDie(STM.succeed(1))\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"orDieWith - when failure should die\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const transaction = pipe(STM.fail(\"-1\"), STM.orDieWith(() => error))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"orDieWith - when succeed should keep going\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const transaction = pipe(STM.succeed(1), STM.orDieWith(() => error))\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"partition - collects only successes\", () =>\n    Effect.gen(function*() {\n      const input = Chunk.range(0, 9)\n      const transaction = pipe(input, STM.partition(STM.succeed))\n      const [left, right] = yield* (STM.commit(transaction))\n      assertTrue(left.length === 0)\n      deepStrictEqual(Array.from(right), Array.from(input))\n    }))\n\n  it.effect(\"partition - collects only failures\", () =>\n    Effect.gen(function*() {\n      const input = Chunk.range(0, 9)\n      const transaction = pipe(input, STM.partition(STM.fail))\n      const [left, right] = yield* (STM.commit(transaction))\n      assertTrue(right.length === 0)\n      deepStrictEqual(Array.from(left), Array.from(input))\n    }))\n\n  it.effect(\"partition - collects successes and failures\", () =>\n    Effect.gen(function*() {\n      const input = Chunk.range(0, 9)\n      const transaction = pipe(input, STM.partition((n) => n % 2 === 0 ? STM.fail(n) : STM.succeed(n)))\n      const [left, right] = yield* (STM.commit(transaction))\n      deepStrictEqual(Array.from(left), [0, 2, 4, 6, 8])\n      deepStrictEqual(Array.from(right), [1, 3, 5, 7, 9])\n    }))\n\n  it.effect(\"partition - evaluates effects in the correct order\", () =>\n    Effect.gen(function*() {\n      const input = [2, 4, 6, 3, 5, 6]\n      const transaction = STM.gen(function*() {\n        const ref = yield* (TRef.make(Chunk.empty<number>()))\n        yield* (pipe(input, STM.partition((n) => pipe(ref, TRef.update(Chunk.append(n))))))\n        return yield* (TRef.get(ref))\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(Array.from(result), input)\n    }))\n\n  it(\"reduce - with a successful step function sums the list properly\", () =>\n    fc.assert(fc.asyncProperty(fc.array(fc.integer()), async (array) => {\n      const transaction = pipe(array, STM.reduce(0, (acc, curr) => STM.succeed(acc + curr)))\n      const result = await Effect.runPromise(STM.commit(transaction))\n      strictEqual(result, array.reduce((acc, curr) => acc + curr, 0))\n    })))\n\n  it(\"reduce - with a failing step function returns a failed transaction\", () =>\n    fc.assert(fc.asyncProperty(fc.array(fc.integer(), { minLength: 1 }), async (array) => {\n      const transaction = pipe(array, STM.reduce(0, () => STM.fail(\"Ouch\")))\n      const result = await Effect.runPromise(Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(\"Ouch\"))\n    })))\n\n  it(\"reduce - run sequentially from left to right\", () =>\n    fc.assert(fc.asyncProperty(fc.array(fc.integer(), { minLength: 1 }), async (array) => {\n      const transaction = pipe(\n        array,\n        STM.reduce(\n          Chunk.empty<number>(),\n          (acc, curr) => STM.succeed(pipe(acc, Chunk.append(curr)))\n        )\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      deepStrictEqual(Array.from(result), array)\n    })))\n\n  it.effect(\"reduceAll\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        [2, 3, 4].map((n) => STM.succeed(n)),\n        STM.reduceAll(STM.succeed(1), (a, b) => a + b)\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 10)\n    }))\n\n  it.effect(\"reduceAll - empty iterable\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        Chunk.empty<STM.STM<number>>(),\n        STM.reduceAll(STM.succeed(1), (a, b) => a + b)\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it(\"reduceRight - with a successful step function sums the list properly\", () =>\n    fc.assert(fc.asyncProperty(fc.array(fc.integer()), async (array) => {\n      const transaction = pipe(array, STM.reduceRight(0, (acc, curr) => STM.succeed(acc + curr)))\n      const result = await Effect.runPromise(STM.commit(transaction))\n      strictEqual(result, array.reduce((acc, curr) => acc + curr, 0))\n    })))\n\n  it(\"reduceRight - with a failing step function returns a failed transaction\", () =>\n    fc.assert(fc.asyncProperty(fc.array(fc.integer(), { minLength: 1 }), async (array) => {\n      const transaction = pipe(array, STM.reduceRight(0, () => STM.fail(\"Ouch\")))\n      const result = await Effect.runPromise(Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(\"Ouch\"))\n    })))\n\n  it(\"reduceRight - run sequentially from right to left\", () =>\n    fc.assert(fc.asyncProperty(fc.array(fc.integer(), { minLength: 1 }), async (array) => {\n      const transaction = pipe(\n        array,\n        STM.reduceRight(\n          Chunk.empty<number>(),\n          (acc, curr) => STM.succeed(pipe(acc, Chunk.prepend(curr)))\n        )\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      deepStrictEqual(Array.from(result), array)\n    })))\n\n  it.effect(\"reject - doesnt collect value\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(0),\n        STM.reject((n) => n !== 0 ? Option.some(\"Ouch\") : Option.none())\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"reject - returns failure ignoring value\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(1),\n        STM.reject((n) => n !== 0 ? Option.some(\"Ouch\") : Option.none())\n      )\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(\"Ouch\"))\n    }))\n\n  it.effect(\"rejectSTM - doesnt collect value\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(0),\n        STM.rejectSTM((n) => n !== 0 ? Option.some(STM.succeed(\"Ouch\")) : Option.none())\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"rejectSTM - returns failure ignoring value\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.succeed(1),\n        STM.rejectSTM((n) => n !== 0 ? Option.some(STM.succeed(\"Ouch\")) : Option.none())\n      )\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      deepStrictEqual(result, Exit.fail(\"Ouch\"))\n    }))\n\n  it.effect(\"repeatWhile - runs effect while it satisfies predicate\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TQueue.bounded<number>(5),\n        STM.tap((queue) => pipe(queue, TQueue.offerAll([0, 0, 0, 1, 2]))),\n        STM.flatMap((queue) =>\n          pipe(\n            TQueue.take(queue),\n            STM.repeatWhile((n) => n === 0)\n          )\n        )\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"repeatUntil - runs effect until it satisfies predicate\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TQueue.bounded<number>(5),\n        STM.tap((queue) => pipe(queue, TQueue.offerAll([0, 0, 0, 1, 2]))),\n        STM.flatMap((queue) =>\n          pipe(\n            TQueue.take(queue),\n            STM.repeatUntil((n) => n === 1)\n          )\n        )\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"replicate - zero\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.all(STM.replicate(STM.succeed(12), 0))\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"replicate - negative\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.all(STM.replicate(STM.succeed(12), -1))\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"replicate - positive\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.all(STM.replicate(STM.succeed(12), 2))\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(Array.from(result), [12, 12])\n    }))\n\n  it.effect(\"some - extracts the value from Some\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.some(STM.succeed(Option.some(1)))\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"some - fails on None\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.some(STM.succeed(Option.none()))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      assertFailure(result, Cause.fail(Option.none()))\n    }))\n\n  it.effect(\"some - fails on error\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const transaction = STM.some(STM.fail(error))\n      const result = yield* (Effect.exit(STM.commit(transaction)))\n      assertFailure(result, Cause.fail(Option.some(error)))\n    }))\n\n  it.effect(\"succeed\", () =>\n    Effect.gen(function*() {\n      const result = yield* (STM.commit(STM.succeed(\"test\")))\n      strictEqual(result, \"test\")\n    }))\n\n  it.effect(\"gen with context\", () =>\n    STM.gen({ context: \"Context\" as const }, function*() {\n      const result = yield* STM.succeed(this.context)\n      strictEqual(result, \"Context\")\n    }))\n\n  it.effect(\"summarized - returns summary and value\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const ref = yield* (TRef.make(0))\n        const increment = pipe(ref, TRef.updateAndGet((n) => n + 1))\n        const result = yield* (pipe(\n          increment,\n          STM.summarized(increment, (before, after) => [before, after] as const)\n        ))\n        return [result[0][0], result[1], result[0][1]] as const\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [1, 2, 3])\n    }))\n\n  it.effect(\"tap - applies the function to the result preserving the original result\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        STM.all([TRef.make(10), TRef.make(0)]),\n        STM.flatMap(([refA, refB]) =>\n          STM.all({\n            result1: pipe(TRef.get(refA), STM.tap((n) => pipe(refB, TRef.set(n + 1)))),\n            result2: TRef.get(refB)\n          })\n        )\n      )\n      const { result1, result2 } = yield* (STM.commit(transaction))\n      strictEqual(result1, 10)\n      strictEqual(result2, 11)\n    }))\n\n  it.effect(\"tapBoth - applies the function to success values preserving the original result\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const tapSuccess = yield* (TDeferred.make<number>())\n        const tapError = yield* (TDeferred.make<string>())\n        const result = yield* (pipe(\n          STM.succeed(42),\n          STM.tapBoth({\n            onFailure: (e: string) => pipe(tapError, TDeferred.succeed(e)),\n            onSuccess: (n) => pipe(tapSuccess, TDeferred.succeed(n))\n          })\n        ))\n        const success = yield* (TDeferred.await(tapSuccess))\n        return [result, success] as const\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [42, 42])\n    }))\n\n  it.effect(\"tapBoth - applies the function to error values preserving the original error\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const tapSuccess = yield* (TDeferred.make<number>())\n        const tapError = yield* (TDeferred.make<string>())\n        const result = yield* (pipe(\n          STM.fail(\"error\"),\n          STM.tapBoth({\n            onFailure: (e) => pipe(tapError, TDeferred.succeed(e)),\n            onSuccess: (n: number) => pipe(tapSuccess, TDeferred.succeed(n))\n          }),\n          STM.either\n        ))\n        const error = yield* (TDeferred.await(tapError))\n        return [result, error] as const\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [Either.left(\"error\"), \"error\"])\n    }))\n\n  it.effect(\"tapError - should apply the function to the error result preserving the original error\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const errorRef = yield* (TDeferred.make<string>())\n        const result = yield* (pipe(\n          STM.fail(\"error\"),\n          STM.zipRight(STM.succeed(0)),\n          STM.tapError((e) => pipe(errorRef, TDeferred.succeed(e))),\n          STM.either\n        ))\n        const error = yield* (TDeferred.await(errorRef))\n        return [result, error]\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [Either.left(\"error\"), \"error\"])\n    }))\n\n  it.effect(\"validateAll - returns all errors if never valid\", () =>\n    Effect.gen(function*() {\n      const input = Array.from({ length: 10 }, () => 0)\n      const transaction = pipe(input, STM.validateAll(STM.fail))\n      const result = yield* (pipe(\n        STM.commit(transaction),\n        Effect.mapError((chunk) => Array.from(chunk)),\n        Effect.exit\n      ))\n      deepStrictEqual(result, Exit.fail(input))\n    }))\n\n  it.effect(\"validateAll - accumulate errors and ignore successes\", () =>\n    Effect.gen(function*() {\n      const input = Chunk.range(0, 9)\n      const transaction = pipe(input, STM.validateAll((n) => n % 2 === 0 ? STM.succeed(n) : STM.fail(n)))\n      const result = yield* (pipe(\n        STM.commit(transaction),\n        Effect.mapError((chunk) => Array.from(chunk)),\n        Effect.exit\n      ))\n      deepStrictEqual(result, Exit.fail([1, 3, 5, 7, 9]))\n    }))\n\n  it.effect(\"validateAll - accumulate successes\", () =>\n    Effect.gen(function*() {\n      const input = Array.from({ length: 10 }, () => 0)\n      const transaction = pipe(input, STM.validateAll(STM.succeed))\n      const result = yield* (pipe(\n        STM.commit(transaction),\n        Effect.map((chunk) => Array.from(chunk))\n      ))\n      deepStrictEqual(result, input)\n    }))\n\n  it.effect(\"validateFirst - returns all errors if never valid\", () =>\n    Effect.gen(function*() {\n      const input = Array.from({ length: 10 }, () => 0)\n      const transaction = pipe(input, STM.validateFirst(STM.fail))\n      const result = yield* (pipe(\n        STM.commit(transaction),\n        Effect.mapError((chunk) => Array.from(chunk)),\n        Effect.exit\n      ))\n      deepStrictEqual(result, Exit.fail(input))\n    }))\n\n  it.effect(\"validateFirst - runs sequentially and short circuits on first success validation\", () =>\n    Effect.gen(function*() {\n      const input = Chunk.range(1, 9)\n      const f = (n: number) => n === 6 ? STM.succeed(n) : STM.fail(n)\n      const transaction = STM.gen(function*() {\n        const ref = yield* (TRef.make(0))\n        const result = yield* (pipe(\n          input,\n          STM.validateFirst((n) => pipe(ref, TRef.update((n) => n + 1), STM.zipRight(f(n))))\n        ))\n        const counter = yield* (TRef.get(ref))\n        return [result, counter] as const\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [6, 6])\n    }))\n\n  it.effect(\"validateFirst - returns errors in correct order\", () =>\n    Effect.gen(function*() {\n      const input = [2, 4, 6, 3, 5, 6]\n      const transaction = pipe(input, STM.validateFirst(STM.fail))\n      const result = yield* (pipe(\n        STM.commit(transaction),\n        Effect.mapError((chunk) => Array.from(chunk)),\n        Effect.exit\n      ))\n      deepStrictEqual(result, Exit.fail(input))\n    }))\n\n  it.effect(\"when - true\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TRef.make(false))\n      const transaction = pipe(\n        ref,\n        TRef.set(true),\n        STM.when(constTrue),\n        STM.zipRight(TRef.get(ref))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertTrue(result)\n    }))\n\n  it.effect(\"when - false\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TRef.make(false))\n      const transaction = pipe(\n        ref,\n        TRef.set(true),\n        STM.when(constFalse),\n        STM.zipRight(TRef.get(ref))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertFalse(result)\n    }))\n\n  it.effect(\"whenSTM - true\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TRef.make(0))\n      const isZero = pipe(TRef.get(ref), STM.map((n) => n === 0))\n      const transaction = pipe(\n        ref,\n        TRef.update((n) => n + 1),\n        STM.whenSTM(isZero),\n        STM.zipRight(TRef.get(ref))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"whenSTM - false\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TRef.make(0))\n      const isZero = pipe(TRef.get(ref), STM.map((n) => n !== 0))\n      const transaction = pipe(\n        ref,\n        TRef.update((n) => n + 1),\n        STM.whenSTM(isZero),\n        STM.zipRight(TRef.get(ref))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"zip - return a tuple of two computations\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.succeed(1), STM.zip(STM.succeed(\"A\")))\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [1, \"A\"])\n    }))\n\n  it.effect(\"zipWith - perform an action on two computations\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(STM.succeed(578), STM.zipWith(STM.succeed(2), (a, b) => a + b))\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 580)\n    }))\n\n  it.effect(\"stack-safety - long orElse chains\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const ref = yield* (TRef.make(0))\n        const value = yield* (STM.loop(10_000, {\n          while: (n) => n > 0,\n          step: (n) => n - 1,\n          body: () =>\n            pipe(\n              STM.retry,\n              STM.orTry(() => pipe(ref, TRef.getAndUpdate((n) => n + 1)))\n            ),\n          discard: true\n        }))\n        strictEqual(value, void 0)\n        return yield* (TRef.get(ref))\n      })\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 10_000)\n    }))\n\n  it.effect(\"stack-safety - long map chains\", () =>\n    Effect.gen(function*() {\n      const result = yield* (chain(10_000)(STM.map((n) => n + 1)))\n      strictEqual(result, 10_000)\n    }))\n\n  it.effect(\"stack-safety - long collect chains\", () =>\n    Effect.gen(function*() {\n      const result = yield* (chain(10_000)(STM.collect((n) => Option.some(n + 1))))\n      strictEqual(result, 10_000)\n    }))\n\n  it.effect(\"stack-safety - long collectSTM chains\", () =>\n    Effect.gen(function*() {\n      const result = yield* (chain(10_000)(STM.collectSTM((n) => Option.some(STM.succeed(n + 1)))))\n      strictEqual(result, 10_000)\n    }))\n\n  it.effect(\"stack-safety - long flatMap chains\", () =>\n    Effect.gen(function*() {\n      const result = yield* (chain(10_000)(STM.flatMap((n) => STM.succeed(n + 1))))\n      strictEqual(result, 10_000)\n    }))\n\n  it.effect(\"stack-safety - long fold chains\", () =>\n    Effect.gen(function*() {\n      const result = yield* (chain(10_000)(STM.match({ onFailure: () => 0, onSuccess: (n) => n + 1 })))\n      strictEqual(result, 10_000)\n    }))\n\n  it.effect(\"stack-safety - long foldSTM chains\", () =>\n    Effect.gen(function*() {\n      const result = yield* (\n        chain(10_000)(STM.matchSTM({ onFailure: () => STM.succeed(0), onSuccess: (n) => STM.succeed(n + 1) }))\n      )\n      strictEqual(result, 10_000)\n    }))\n\n  it.effect(\"stack-safety - long mapError chains\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Effect.exit(chainError(10_000)))\n      deepStrictEqual(result, Exit.fail(10_000))\n    }))\n\n  it.effect(\"stack-safety - long orElse chains\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TRef.make(0),\n        STM.tap((ref) =>\n          STM.loop(10_000, {\n            while: (n) => n > 0,\n            step: (n) => n - 1,\n            body: () => pipe(STM.retry, STM.orElse(() => pipe(ref, TRef.getAndUpdate((n) => n + 1)))),\n            discard: true\n          })\n        ),\n        STM.flatMap(TRef.get)\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 10_000)\n    }))\n\n  it.effect(\"stack-safety - long provideEnvironment chains\", () =>\n    Effect.gen(function*() {\n      const result = yield* (chain(10_000)(STM.provideContext(Context.empty())))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"ZIO STM (Issue #2073)\", () =>\n    Effect.gen(function*() {\n      const ref0 = yield* (TRef.make(0))\n      const ref1 = yield* (TRef.make(0))\n      const fiber = yield* (pipe(\n        TRef.get(ref0),\n        STM.flatMap((value0) =>\n          pipe(\n            TRef.get(ref1),\n            STM.map((value1) => value0 + value1)\n          )\n        ),\n        STM.commit,\n        Effect.fork\n      ))\n      yield* (pipe(\n        ref0,\n        TRef.update((n) => n + 1),\n        STM.flatMap(() => pipe(ref1, TRef.update((n) => n + 1))),\n        STM.commit\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(result === 0 || result === 2)\n    }))\n\n  describe(\"concurrent computations\", () => {\n    it.effect(\"increment `TRef` 100 times in 100 fibers\", () =>\n      Effect.gen(function*() {\n        const ref = yield* (TRef.make(0))\n        const fiber = yield* (Effect.forkAll(\n          Array.from({ length: 10 }, () => incrementTRefN(99, ref))\n        ))\n        yield* (Fiber.join(fiber))\n        const result = yield* (TRef.get(ref))\n        strictEqual(result, 1_000)\n      }))\n\n    it.effect(\"compute a `TRef` from 2 variables, increment the first `TRef` and decrement the second `TRef` in different fibers\", () =>\n      Effect.gen(function*() {\n        const refs = yield* (STM.all([TRef.make(10_000), TRef.make(0), TRef.make(0)]))\n        const fiber = yield* (Effect.forkAll(\n          Array.from({ length: 10 }, () => compute3TRefN(99, refs[0], refs[1], refs[2]))\n        ))\n        yield* (Fiber.join(fiber))\n        const result = yield* (TRef.get(refs[2]))\n        strictEqual(result, 10_000)\n      }))\n  })\n\n  it.effect(\"condition locks - resume directly when the condition is already satisfied\", () =>\n    Effect.gen(function*() {\n      const ref1 = yield* (TRef.make(10))\n      const ref2 = yield* (TRef.make(\"failed\"))\n      const result = yield* (pipe(\n        TRef.get(ref1),\n        STM.tap((n) => STM.check(() => n > 0)),\n        STM.tap(() => pipe(ref2, TRef.set(\"success\"))),\n        STM.zipRight(TRef.get(ref2)),\n        STM.commit\n      ))\n      strictEqual(result, \"success\")\n    }))\n\n  it.effect(\"condition locks - resume directly when the condition is already satisfied and change the ref with non-satisfying value\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TRef.make(42))\n      const result = yield* (pipe(\n        TRef.get(ref),\n        STM.retryUntil((n) => n === 42),\n        STM.commit\n      ))\n      yield* (pipe(ref, TRef.set(9), STM.commit))\n      const value = yield* (TRef.get(ref))\n      strictEqual(result, 42)\n      strictEqual(value, 9)\n    }))\n\n  it.effect(\"condition locks - resume after satisfying the condition\", () => {\n    const barrier = new UnpureBarrier()\n    return Effect.gen(function*() {\n      const done = yield* (Deferred.make<void>())\n      const ref1 = yield* (TRef.make(0))\n      const ref2 = yield* (TRef.make(\"failed\"))\n      const transaction = pipe(\n        TRef.get(ref1),\n        STM.tap(() => STM.sync(() => barrier.open())),\n        STM.tap((n) => STM.check(() => n > 42)),\n        STM.tap(() => pipe(ref2, TRef.set(\"success\"))),\n        STM.zipRight(TRef.get(ref2))\n      )\n      const fiber = yield* (pipe(\n        STM.commit(transaction),\n        Effect.zipLeft(pipe(done, Deferred.succeed<void>(void 0))),\n        Effect.fork\n      ))\n      yield* (barrier.await())\n      const oldValue = yield* (TRef.get(ref2))\n      yield* (pipe(ref1, TRef.set(43)))\n      yield* (Deferred.await(done))\n      const newValue = yield* (TRef.get(ref2))\n      const result = yield* (Fiber.join(fiber))\n      strictEqual(oldValue, \"failed\")\n      strictEqual(newValue, result)\n    })\n  })\n\n  it.effect(\"condition locks - resume directly when the condition is already satisfied\", () =>\n    Effect.gen(function*() {\n      const sender = yield* (TRef.make(100))\n      const receiver = yield* (TRef.make(0))\n      yield* (Effect.fork(transfer(receiver, sender, 150)))\n      yield* (pipe(sender, TRef.update((n) => n + 100)))\n      yield* (pipe(TRef.get(sender), STM.retryUntil((n) => n === 50)))\n      const senderValue = yield* (TRef.get(sender))\n      const receiverValue = yield* (TRef.get(receiver))\n      strictEqual(senderValue, 50)\n      strictEqual(receiverValue, 150)\n    }))\n\n  it.effect(\"condition locks - run both transactions sequentially\", () =>\n    Effect.gen(function*() {\n      const sender = yield* (TRef.make(100))\n      const receiver = yield* (TRef.make(0))\n      const toReceiver = transfer(receiver, sender, 150)\n      const toSender = transfer(sender, receiver, 150)\n      const fiber = yield* (pipe(\n        Array.from({ length: 10 }, () => pipe(toReceiver, Effect.zipRight(toSender))),\n        Effect.forkAll()\n      ))\n      yield* (pipe(sender, TRef.update((n) => n + 50)))\n      yield* (Fiber.join(fiber))\n      const senderValue = yield* (TRef.get(sender))\n      const receiverValue = yield* (TRef.get(receiver))\n      strictEqual(senderValue, 150)\n      strictEqual(receiverValue, 0)\n    }))\n\n  it.effect(\"condition locks - run both transactions concurrently #1\", () =>\n    Effect.gen(function*() {\n      const sender = yield* (TRef.make(50))\n      const receiver = yield* (TRef.make(0))\n      const toReceiver = transfer(receiver, sender, 100)\n      const toSender = transfer(sender, receiver, 100)\n      const fiber1 = yield* (pipe(\n        Array.from({ length: 10 }, () => toReceiver),\n        Effect.forkAll()\n      ))\n      const fiber2 = yield* (pipe(\n        Array.from({ length: 10 }, () => toSender),\n        Effect.forkAll()\n      ))\n      yield* (pipe(sender, TRef.update((n) => n + 50)))\n      yield* (Fiber.join(fiber1))\n      yield* (Fiber.join(fiber2))\n      const senderValue = yield* (TRef.get(sender))\n      const receiverValue = yield* (TRef.get(receiver))\n      strictEqual(senderValue, 100)\n      strictEqual(receiverValue, 0)\n    }))\n\n  it.effect(\"condition locks - run both transactions concurrently #2\", () =>\n    Effect.gen(function*() {\n      const sender = yield* (TRef.make(50))\n      const receiver = yield* (TRef.make(0))\n      const toReceiver = pipe(transfer(receiver, sender, 100), Effect.repeatN(9))\n      const toSender = pipe(transfer(sender, receiver, 100), Effect.repeatN(9))\n      const fiber = yield* (pipe(toReceiver, Effect.zip(toSender, { concurrent: true }), Effect.fork))\n      yield* (pipe(sender, TRef.update((n) => n + 50)))\n      yield* (Fiber.join(fiber))\n      const senderValue = yield* (TRef.get(sender))\n      const receiverValue = yield* (TRef.get(receiver))\n      strictEqual(senderValue, 100)\n      strictEqual(receiverValue, 0)\n    }))\n\n  it.effect(\"condition locks - atomically run a transaction with a TRef for 20 fibers, each one checking and incrementing the value\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TRef.make(1))\n      const fiber = yield* (pipe(\n        Chunk.range(1, 20),\n        Chunk.map((i) =>\n          pipe(\n            TRef.get(ref),\n            STM.tap((n) => STM.check(() => n === i)),\n            STM.tap(() => pipe(ref, TRef.update((n) => n + 1))),\n            STM.commit\n          )\n        ),\n        Effect.forkAll()\n      ))\n      yield* (Fiber.join(fiber))\n      const result = yield* (TRef.get(ref))\n      strictEqual(result, 21)\n    }))\n\n  it.effect(\"condition locks - atomically run a transaction that could not be satisfied\", () => {\n    const barrier = new UnpureBarrier()\n    return Effect.gen(function*() {\n      const ref = yield* (TRef.make(0))\n      const fiber = yield* (pipe(\n        TRef.get(ref),\n        STM.tap(() => STM.sync(() => barrier.open())),\n        STM.tap((n) => STM.check(() => n > 0)),\n        STM.tap(() => pipe(ref, TRef.update((n) => Math.floor(10 / n)))),\n        STM.commit,\n        Effect.fork\n      ))\n      yield* (barrier.await())\n      yield* (Fiber.interrupt(fiber))\n      yield* (pipe(ref, TRef.set(10)))\n      const result = yield* (pipe(Effect.yieldNow(), Effect.zipRight(TRef.get(ref))))\n      strictEqual(result, 10)\n    })\n  })\n\n  it.effect(\"condition locks - interrupt one fiber executing a transaction should terminate all transactions\", () => {\n    const barrier = new UnpureBarrier()\n    return Effect.gen(function*() {\n      const ref = yield* (TRef.make(0))\n      const fiber = yield* (pipe(\n        Array.from({ length: 100 }, () =>\n          pipe(\n            TRef.get(ref),\n            STM.tap(() => STM.sync(() => barrier.open())),\n            STM.tap((n) => STM.check(() => n < 0)),\n            STM.tap(() => pipe(ref, TRef.set(10))),\n            STM.commit\n          )),\n        Effect.forkAll()\n      ))\n      yield* (barrier.await())\n      yield* (Fiber.interrupt(fiber))\n      yield* (pipe(ref, TRef.set(-1)))\n      const result = yield* (pipe(Effect.yieldNow(), Effect.zipRight(TRef.get(ref))))\n      strictEqual(result, -1)\n    })\n  })\n\n  it.effect(\"condition locks - interrupt fiber and observe it\", () =>\n    Effect.gen(function*() {\n      const fiberId = yield* (Effect.fiberId)\n      const ref = yield* (TRef.make(1))\n      const fiber = yield* (pipe(\n        TRef.get(ref),\n        STM.flatMap((n) => STM.check(() => n === 0)),\n        STM.commit,\n        Effect.fork\n      ))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (pipe(Fiber.join(fiber), Effect.sandbox, Effect.either))\n      assertTrue(\n        Either.isLeft(result) &&\n          pipe(\n            result.left,\n            Cause.contains(Cause.interrupt(fiberId))\n          )\n      )\n    }))\n\n  it.effect(\"permutations - permutes two variables\", () =>\n    Effect.gen(function*() {\n      const ref1 = yield* (TRef.make(1))\n      const ref2 = yield* (TRef.make(2))\n      yield* (permutation(ref1, ref2))\n      const result1 = yield* (TRef.get(ref1))\n      const result2 = yield* (TRef.get(ref2))\n      strictEqual(result1, 2)\n      strictEqual(result2, 1)\n    }))\n\n  it.effect(\"permutations - permutes two variables in 100 fibers\", () =>\n    Effect.gen(function*() {\n      const ref1 = yield* (TRef.make(1))\n      const ref2 = yield* (TRef.make(2))\n      const oldValue1 = yield* (TRef.get(ref1))\n      const oldValue2 = yield* (TRef.get(ref2))\n      const fiber = yield* (pipe(\n        Array.from({ length: 100 }, () => STM.commit(permutation(ref1, ref2))),\n        Effect.forkAll()\n      ))\n      yield* (Fiber.join(fiber))\n      const result1 = yield* (TRef.get(ref1))\n      const result2 = yield* (TRef.get(ref2))\n      strictEqual(result1, oldValue1)\n      strictEqual(result2, oldValue2)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Schedule.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport {\n  Array,\n  Cause,\n  Chunk,\n  Clock,\n  Deferred,\n  Duration,\n  Effect,\n  Exit,\n  Fiber,\n  Option,\n  pipe,\n  Ref,\n  Schedule,\n  ScheduleDecision,\n  ScheduleIntervals\n} from \"effect\"\nimport { constVoid } from \"effect/Function\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Schedule\", () => {\n  it.effect(\"collect all inputs into a list as long as the condition f holds\", () =>\n    Effect.gen(function*() {\n      const result = yield* repeat(Schedule.collectWhile((n) => n < 10))\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 9))\n    }))\n  it.effect(\"collect all inputs into a list as long as the effectful condition f holds\", () =>\n    Effect.gen(function*() {\n      const result = yield* repeat(Schedule.collectWhileEffect((n) => Effect.succeed(n > 10)))\n      assertTrue(Chunk.isEmpty(result))\n    }))\n  it.effect(\"collect all inputs into a list until the effectful condition f fails\", () =>\n    Effect.gen(function*() {\n      const result = yield* repeat(Schedule.collectUntil((n) => n < 10 && n > 1))\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1])\n    }))\n  it.effect(\"collect all inputs into a list until the effectful condition f fails\", () =>\n    Effect.gen(function*() {\n      const result = yield* repeat(Schedule.collectUntilEffect((n) => Effect.succeed(n > 10)))\n      deepStrictEqual(Chunk.toReadonlyArray(result), Array.range(1, 10))\n    }))\n  it.effect(\"union composes\", () =>\n    Effect.gen(function*() {\n      const monday = Schedule.dayOfMonth(1)\n      const wednesday = Schedule.dayOfMonth(3)\n      const friday = Schedule.dayOfMonth(5)\n      const mondayOrWednesday = monday.pipe(Schedule.union(wednesday))\n      const wednesdayOrFriday = wednesday.pipe(Schedule.union(friday))\n      const alsoWednesday = mondayOrWednesday.pipe(Schedule.intersect(wednesdayOrFriday))\n      const now = yield* Effect.sync(() => Date.now())\n      const input = Array.range(1, 5)\n      const actual = yield* pipe(alsoWednesday, Schedule.delays, Schedule.run(now, input))\n      const expected = yield* pipe(wednesday, Schedule.delays, Schedule.run(now, input))\n      deepStrictEqual(Chunk.toReadonlyArray(actual), Chunk.toReadonlyArray(expected))\n    }))\n  it.effect(\"either should not wait if neither schedule wants to continue\", () =>\n    Effect.gen(function*() {\n      const schedule = Schedule.stop.pipe(\n        Schedule.union(Schedule.spaced(\"2 seconds\").pipe(Schedule.intersect(Schedule.stop))),\n        Schedule.compose(Schedule.elapsed)\n      )\n      const input = Array.makeBy(4, constVoid)\n      const result = yield* runCollect(schedule, input)\n      deepStrictEqual(Chunk.toReadonlyArray(result), [Duration.zero])\n    }))\n  it.effect(\"perform log for each recurrence of effect\", () =>\n    Effect.gen(function*() {\n      const schedule = (ref: Ref.Ref<number>) => {\n        return Schedule.recurs(3).pipe(Schedule.onDecision(() => Ref.update(ref, (n) => n + 1)))\n      }\n      const ref = yield* Ref.make(0)\n      yield* pipe(Ref.getAndUpdate(ref, (n) => n + 1), Effect.repeat(schedule(ref)))\n      const result = yield* Ref.get(ref)\n      strictEqual(result, 8)\n    }))\n  it.effect(\"reset after some inactivity\", () =>\n    Effect.gen(function*() {\n      const io = (ref: Ref.Ref<number>, latch: Deferred.Deferred<void, never>): Effect.Effect<void, string> => {\n        return Ref.updateAndGet(ref, (n) => n + 1).pipe(\n          Effect.flatMap((retries) => {\n            // The 5th retry will fail after 10 seconds to let the schedule reset\n            if (retries == 5) {\n              return Deferred.succeed(latch, void 0).pipe(\n                Effect.zipRight(io(ref, latch).pipe(Effect.delay(\"10 seconds\")))\n              )\n            }\n            // The 10th retry will succeed, which is only possible if the schedule was reset\n            if (retries == 10) {\n              return Effect.void\n            }\n            return Effect.fail(\"Boom\")\n          })\n        )\n      }\n      const schedule = Schedule.recurs(5).pipe(Schedule.resetAfter(\"5 seconds\"))\n      const retriesCounter = yield* Ref.make(-1)\n      const latch = yield* Deferred.make<void>()\n      const fiber = yield* pipe(io(retriesCounter, latch), Effect.retry(schedule), Effect.fork)\n      yield* Deferred.await(latch)\n      yield* TestClock.adjust(\"10 seconds\")\n      yield* Fiber.join(fiber)\n      const retries = yield* Ref.get(retriesCounter)\n      strictEqual(retries, 10)\n    }))\n  it.effect(\"union of two schedules should continue as long as either wants to continue\", () =>\n    Effect.gen(function*() {\n      const schedule = Schedule.recurWhile((b: boolean) => b).pipe(Schedule.union(Schedule.fixed(\"1 seconds\")))\n      const input = Chunk.make(true, false, false, false, false)\n      const result = yield* runCollect(schedule.pipe(Schedule.compose(Schedule.elapsed)), input)\n      const expected = [0, 0, 1, 2, 3].map(Duration.seconds)\n      deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n    }))\n  it.effect(\"Schedule.fixed should compute delays correctly\", () =>\n    Effect.gen(function*() {\n      const inputs = Chunk.make([0, undefined] as const, [6500, undefined] as const)\n      const result = yield* pipe(\n        runManually(Schedule.fixed(\"5 seconds\"), inputs),\n        Effect.map((output) => output[0].pipe(Chunk.map((tuple) => tuple[0])))\n      )\n      deepStrictEqual(result, Chunk.make(5000, 10000))\n    }))\n  it.effect(\"intersection of schedules recurring in bounded intervals\", () =>\n    Effect.gen(function*() {\n      const schedule = Schedule.hourOfDay(4).pipe(Schedule.intersect(Schedule.minuteOfHour(20)))\n      const now = yield* Effect.sync(() => Date.now())\n      const input = Array.range(1, 5)\n      const delays = yield* pipe(Schedule.delays(schedule), Schedule.run(now, input))\n      const actual = Chunk.toReadonlyArray(scanLeft(delays, now, (now, delay) => now + Duration.toMillis(delay))).slice(\n        1\n      )\n      assertTrue(actual.map((n) => new Date(n).getHours()).every((n) => n === 4))\n      assertTrue(actual.map((n) => new Date(n).getMinutes()).every((n) => n === 20))\n    }))\n  it.effect(\"passthrough\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(0)\n      const result = yield* Ref.getAndUpdate(ref, (n) => n + 1).pipe(\n        Effect.repeat(Schedule.recurs(10).pipe(Schedule.passthrough))\n      )\n      strictEqual(result, 10)\n    }))\n  describe(\"simulate a schedule\", () => {\n    it.effect(\"without timing out\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.exponential(\"1 minutes\")\n        const result = yield* pipe(\n          Clock.currentTimeMillis,\n          Effect.flatMap((now) => schedule.pipe(Schedule.run(now, Array.makeBy(5, constVoid))))\n        )\n        deepStrictEqual(Chunk.toReadonlyArray(result), [\n          Duration.minutes(1),\n          Duration.minutes(2),\n          Duration.minutes(4),\n          Duration.minutes(8),\n          Duration.minutes(16)\n        ])\n      }))\n    it.effect(\"respect Schedule.recurs even if more input is provided than needed\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.recurs(2).pipe(Schedule.intersect(Schedule.exponential(\"1 minutes\")))\n        const result = yield* Clock.currentTimeMillis.pipe(\n          Effect.flatMap((now) => schedule.pipe(Schedule.run(now, Array.range(1, 10))))\n        )\n        deepStrictEqual(Chunk.toReadonlyArray(result), [\n          [0, Duration.minutes(1)],\n          [1, Duration.minutes(2)],\n          [2, Duration.minutes(4)]\n        ])\n      }))\n    it.effect(\"respect Schedule.upTo even if more input is provided than needed\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.spaced(\"1 seconds\").pipe(Schedule.upTo(\"5 seconds\"))\n        const result = yield* Clock.currentTimeMillis.pipe(\n          Effect.flatMap((now) => schedule.pipe(Schedule.run(now, Array.range(1, 10))))\n        )\n        deepStrictEqual(Chunk.toReadonlyArray(result), [0, 1, 2, 3, 4, 5])\n      }))\n  })\n  describe(\"repeat an action a single time\", () => {\n    it.effect(\"repeat on failure does not actually repeat\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make(0)\n        const result = yield* Effect.flip(alwaysFail(ref))\n        strictEqual(result, \"Error: 1\")\n      }))\n    it.effect(\"repeat a scheduled repeat repeats the whole number\", () =>\n      Effect.gen(function*() {\n        const n = 42\n        const ref = yield* Ref.make(0)\n        const effect = ref.pipe(Ref.update((n) => n + 1), Effect.repeat(Schedule.recurs(n)))\n        yield* pipe(effect, Effect.repeat(Schedule.recurs(1)))\n        const result = yield* Ref.get(ref)\n        strictEqual(result, (n + 1) * 2)\n      }))\n  })\n  describe(\"repeat an action two times and call ensuring should\", () => {\n    it.effect(\"run the specified finalizer as soon as the schedule is complete\", () =>\n      Effect.gen(function*() {\n        const deferred = yield* Deferred.make<void>()\n        const ref = yield* Ref.make(0)\n        yield* pipe(\n          Ref.update(ref, (n) => n + 2),\n          Effect.repeat(Schedule.recurs(2)),\n          Effect.ensuring(Deferred.succeed(deferred, void 0))\n        )\n        const value = yield* Ref.get(ref)\n        const finalizerValue = yield* Deferred.poll(deferred)\n        strictEqual(value, 6)\n        assertTrue(Option.isSome(finalizerValue))\n      }))\n  })\n  describe(\"repeat on success according to a provided strategy\", () => {\n    it.effect(\"for 'recurs(a negative number)' repeats 0 additional time\", () =>\n      Effect.gen(function*() {\n        // A repeat with a negative number of times should not repeat the action at all\n        const result = yield* repeat(Schedule.recurs(-5))\n        strictEqual(result, 0)\n      }))\n    it.effect(\"for 'recurs(0)' does repeat 0 additional time\", () =>\n      Effect.gen(function*() {\n        // A repeat with 0 number of times should not repeat the action at all\n        const result = yield* repeat(Schedule.recurs(0))\n        strictEqual(result, 0)\n      }))\n    it.effect(\"for 'recurs(1)' does repeat 1 additional time\", () =>\n      Effect.gen(function*() {\n        const result = yield* repeat(Schedule.recurs(1))\n        strictEqual(result, 1)\n      }))\n    it.effect(\"for 'once' will repeat 1 additional time\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make(0)\n        yield* pipe(Ref.update(ref, (n) => n + 1), Effect.repeat(Schedule.once))\n        const result = yield* Ref.get(ref)\n        strictEqual(result, 2)\n      }))\n    it.effect(\"for 'recurs(a positive given number)' repeats that additional number of time\", () =>\n      Effect.gen(function*() {\n        const result = yield* repeat(Schedule.recurs(42))\n        strictEqual(result, 42)\n      }))\n    it.effect(\"for 'recurWhile(cond)' repeats while the cond still holds\", () =>\n      Effect.gen(function*() {\n        const result = yield* repeat(Schedule.recurWhile((n) => n < 10))\n        strictEqual(result, 10)\n      }))\n    it.effect(\"for 'recurWhileEffect(cond)' repeats while the effectful cond still holds\", () =>\n      Effect.gen(function*() {\n        const result = yield* repeat(Schedule.recurWhileEffect((n) => Effect.succeed(n > 10)))\n        strictEqual(result, 1)\n      }))\n    it.effect(\"for 'recurUntil(cond)' repeats until the cond is satisfied\", () =>\n      Effect.gen(function*() {\n        const result = yield* repeat(Schedule.recurUntil((n) => n < 10))\n        strictEqual(result, 1)\n      }))\n    it.effect(\"for 'recurUntilEffect(cond)' repeats until the effectful cond is satisfied\", () =>\n      Effect.gen(function*() {\n        const result = yield* repeat(Schedule.recurUntilEffect((n) => Effect.succeed(n > 10)))\n        strictEqual(result, 11)\n      }))\n  })\n  describe(\"delays\", () => {\n    it.effect(\"duration\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkDelays(Schedule.duration(\"1 seconds\"))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"exponential\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkDelays(Schedule.exponential(\"1 seconds\"))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"fibonacci\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkDelays(Schedule.fibonacci(\"1 seconds\"))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"fromDelay\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkDelays(Schedule.fromDelay(\"1 seconds\"))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"fromDelays\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkDelays(\n          Schedule.fromDelays(\"1 seconds\", \"2 seconds\", \"3 seconds\", \"4 seconds\")\n        )\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"linear\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkDelays(Schedule.linear(\"1 seconds\"))\n        deepStrictEqual(actual, expected)\n      }))\n  })\n  describe(\"repetitions\", () => {\n    it.effect(\"forever\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.repeatForever)\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"count\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.count)\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"dayOfMonth\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.dayOfMonth(1))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"dayOfWeek\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.dayOfWeek(1))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"hourOfDay\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.hourOfDay(1))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"minuteOfHour\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.minuteOfHour(1))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"secondOfMinute\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.secondOfMinute(1))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"fixed\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.fixed(\"1 seconds\"))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"repeatForever\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.repeatForever)\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"recurs\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.recurs(2))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"spaced\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.spaced(\"1 seconds\"))\n        deepStrictEqual(actual, expected)\n      }))\n    it.effect(\"windowed\", () =>\n      Effect.gen(function*() {\n        const [actual, expected] = yield* checkRepetitions(Schedule.windowed(\"1 seconds\"))\n        deepStrictEqual(actual, expected)\n      }))\n  })\n  describe(\"retries\", () => {\n    it.effect(\"for up to 10 times\", () =>\n      Effect.gen(function*() {\n        let i = 0\n        const strategy = Schedule.recurs(10)\n        const io = Effect.sync(() => {\n          i = i + 1\n        }).pipe(\n          Effect.flatMap(() => i < 5 ? Effect.fail(\"KeepTryingError\") : Effect.succeed(i))\n        )\n        const result = yield* pipe(io, Effect.retry(strategy))\n        strictEqual(result, 5)\n      }))\n    it.effect(\"retry exactly one time for `once` when second time succeeds - retryOrElse\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make(0)\n        const result = yield* pipe(failOn0(ref), Effect.retryOrElse(Schedule.once, ioFail))\n        strictEqual(result, 2)\n      }))\n    it.effect(\"if fallback succeeded - retryOrElse\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make(0)\n        const result = yield* pipe(alwaysFail(ref), Effect.retryOrElse(Schedule.once, ioSucceed))\n        strictEqual(result, \"OrElse\")\n      }))\n    it.effect(\"if fallback failed - retryOrElse\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make(0)\n        const result = yield* alwaysFail(ref).pipe(\n          Effect.retryOrElse(Schedule.once, ioFail),\n          Effect.flip\n        )\n        strictEqual(result, \"OrElseFailed\")\n      }))\n    it.effect(\"retry 0 time for `once` when first time succeeds\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make(0)\n        yield* pipe(Ref.update(ref, (n) => n + 1), Effect.retry(Schedule.once))\n        const result = yield* Ref.get(ref)\n        strictEqual(result, 1)\n      }))\n    it.effect(\"retry 0 time for `recurs(0)`\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make(0)\n        const result = yield* alwaysFail(ref).pipe(\n          Effect.retry(Schedule.recurs(0)),\n          Effect.flip\n        )\n        strictEqual(result, \"Error: 1\")\n      }))\n    it.effect(\"retry exactly one time for `once` when second time succeeds\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make(0) // One retry on failure\n        // One retry on failure\n        yield* pipe(failOn0(ref), Effect.retry(Schedule.once))\n        const result = yield* Ref.get(ref)\n        strictEqual(result, 2)\n      }))\n    it.effect(\"retry exactly one time for `once` even if still in error\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make(0) // No more than one retry on retry `once`\n        // No more than one retry on retry `once`\n        const result = yield* alwaysFail(ref).pipe(\n          Effect.retry(Schedule.once),\n          Effect.flip\n        )\n        strictEqual(result, \"Error: 2\")\n      }))\n    it.effect(\"retry exactly 'n' times after failure\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make(0)\n        const result = yield* pipe(alwaysFail(ref), Effect.retry({ times: 3 }), Effect.flip)\n        strictEqual(result, \"Error: 4\")\n      }))\n    // TODO(Max): after TestRandom\n    // it.skip(\"for a given number of times with random jitter in (0, 1)\")\n    // Effect.gen(function*(){\n    // const schedule = Schedule.spaced((500).millis).jittered(0, 1)\n    // const result = $(runCollect(schedule.compose(Schedule.elapsed), Chunk.fill(5, constVoid)))\n    // const expected = Chunk((0).millis, (250).millis, (500).millis, (750).millis, (1000).millis)\n    // assertTrue()\n    // }).unsafeRunPromise()\n    // TODO(Max): after TestRandom\n    // it.skip(\"for a given number of times with random jitter in custom interval\")\n    // Effect.gen(function*(){\n    // const schedule = Schedule.spaced((500).millis).jittered(2, 4)\n    // const result = $(runCollect(schedule.compose(Schedule.elapsed), Chunk.fill(5, constVoid)))\n    // const expected = Chunk((0).millis, (1500).millis, (3000).millis, (5000).millis, (7000).millis)\n    // assertTrue()\n    // }).unsafeRunPromise()\n    it.effect(\"fixed delay with error predicate\", () =>\n      Effect.gen(function*() {\n        let i = 0\n        const effect = Effect.sync(() => {\n          i = i + 1\n        }).pipe(\n          Effect.flatMap(() => i < 5 ? Effect.fail(\"KeepTryingError\") : Effect.fail(\"GiveUpError\"))\n        )\n        const strategy = Schedule.spaced(\"200 millis\").pipe(\n          Schedule.whileInput((s: string) => s === \"KeepTryingError\")\n        )\n        const program = effect.pipe(\n          Effect.retryOrElse(strategy, (s, n) =>\n            TestClock.currentTimeMillis.pipe(Effect.map((now) => [Duration.millis(now), s, n] as const)))\n        )\n        const result = yield* run(program)\n        deepStrictEqual(result, [Duration.millis(800), \"GiveUpError\", 4] as const)\n      }))\n    it.effect(\"fibonacci delay\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.fibonacci(\"100 millis\").pipe(Schedule.compose(Schedule.elapsed))\n        const result = yield* runCollect(schedule, Array.makeBy(5, constVoid))\n        const expected = [0, 100, 200, 400, 700].map(Duration.millis)\n        deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n      }))\n    it.effect(\"linear delay\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.linear(\"100 millis\").pipe(Schedule.compose(Schedule.elapsed))\n        const result = yield* runCollect(schedule, Array.makeBy(5, constVoid))\n        const expected = [0, 100, 300, 600, 1000].map(Duration.millis)\n        deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n      }))\n    it.effect(\"spaced delay\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.spaced(\"100 millis\").pipe(Schedule.compose(Schedule.elapsed))\n        const result = yield* runCollect(schedule, Array.makeBy(5, constVoid))\n        const expected = [0, 100, 200, 300, 400].map(Duration.millis)\n        deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n      }))\n    it.effect(\"fixed delay\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.fixed(\"100 millis\").pipe(Schedule.compose(Schedule.elapsed))\n        const result = yield* runCollect(schedule, Array.makeBy(5, constVoid))\n        const expected = [0, 100, 200, 300, 400].map(Duration.millis)\n        deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n      }))\n    it.effect(\"fixed delay with zero delay\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.fixed(Duration.zero).pipe(Schedule.compose(Schedule.elapsed))\n        const result = yield* runCollect(schedule, Array.makeBy(5, constVoid))\n        const expected = Array.makeBy(5, () => Duration.zero)\n        deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n      }))\n    it.effect(\"windowed\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.windowed(\"100 millis\").pipe(Schedule.compose(Schedule.elapsed))\n        const result = yield* runCollect(schedule, Array.makeBy(5, constVoid))\n        const expected = [0, 100, 200, 300, 400].map(Duration.millis)\n        deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n      }))\n    it.effect(\"modified linear delay\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.linear(\"100 millis\").pipe(\n          Schedule.modifyDelayEffect((_, duration) => Effect.succeed(duration.pipe(Duration.times(2)))),\n          Schedule.compose(Schedule.elapsed)\n        )\n        const result = yield* runCollect(schedule, Array.makeBy(5, constVoid))\n        const expected = [0, 200, 600, 1200, 2000].map(Duration.millis)\n        deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n      }))\n    it.effect(\"exponential delay with default factor\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.exponential(\"100 millis\").pipe(Schedule.compose(Schedule.elapsed))\n        const result = yield* runCollect(schedule, Array.makeBy(5, constVoid))\n        const expected = [0, 100, 300, 700, 1500].map(Duration.millis)\n        deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n      }))\n    it.effect(\"exponential delay with other factor\", () =>\n      Effect.gen(function*() {\n        const schedule = Schedule.exponential(\"100 millis\", 3).pipe(Schedule.compose(Schedule.elapsed))\n        const result = yield* runCollect(schedule, Array.makeBy(5, constVoid))\n        const expected = [0, 100, 400, 1300, 4000].map(Duration.millis)\n        deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n      }))\n    it.effect(\"fromDelays\", () =>\n      Effect.gen(function*() {\n        const delays = Schedule.fromDelays(\n          \"4 seconds\",\n          \"7 seconds\",\n          \"12 seconds\",\n          \"19 seconds\"\n        )\n        const schedule = delays.pipe(Schedule.compose(Schedule.elapsed))\n        const result = yield* runCollect(schedule, Array.makeBy(5, constVoid))\n        const expected = [0, 4, 11, 23, 42].map(Duration.seconds)\n        deepStrictEqual(Chunk.toReadonlyArray(result), expected)\n      }))\n    it.effect(\"retry a failed action 2 times and call `ensuring` should run the specified finalizer as soon as the schedule is complete\", () =>\n      Effect.gen(function*() {\n        const deferred = yield* Deferred.make<void>()\n        const value = yield* Effect.fail(\"oh no\").pipe(\n          Effect.retry(Schedule.recurs(2)),\n          Effect.ensuring(Deferred.succeed(deferred, void 0)),\n          Effect.option\n        )\n        const finalizerValue = yield* Deferred.poll(deferred)\n        assertTrue(Option.isNone(value))\n        assertTrue(Option.isSome(finalizerValue))\n      }))\n  })\n  describe(\"cron-like scheduling - repeats at point of time (minute of hour, day of week, ...)\", () => {\n    it.effect(\"recur every second minute using cron\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make<ReadonlyArray<string>>([])\n        yield* TestClock.setTime(new Date(2024, 0, 1, 0, 0, 35).getTime())\n        const schedule = Schedule.cron(\"*/2 * * * *\")\n        yield* pipe(\n          TestClock.currentTimeMillis,\n          Effect.tap((instant) => Ref.update(ref, Array.append(format(instant)))),\n          Effect.repeat(schedule),\n          Effect.fork\n        )\n        yield* TestClock.adjust(\"8 minutes\")\n        const result = yield* Ref.get(ref)\n        const expected = [\n          \"Mon Jan 01 2024 00:00:35\",\n          \"Mon Jan 01 2024 00:02:00\",\n          \"Mon Jan 01 2024 00:04:00\",\n          \"Mon Jan 01 2024 00:06:00\",\n          \"Mon Jan 01 2024 00:08:00\"\n        ]\n        deepStrictEqual(result, expected)\n      }))\n    it.effect(\"recur at time matching cron expression\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make<ReadonlyArray<string>>([])\n        yield* TestClock.setTime(new Date(2024, 0, 1, 0, 0, 0).getTime())\n        // At 04:30 on day-of-month 5 and 15 and on Wednesday.\n        const schedule = Schedule.cron(\"30 4 5,15 * WED\")\n        yield* pipe(\n          TestClock.currentTimeMillis,\n          Effect.tap((instant) => Ref.update(ref, Array.append(format(instant)))),\n          Effect.repeat(schedule),\n          Effect.fork\n        )\n        yield* TestClock.adjust(\"4 weeks\")\n        const result = yield* Ref.get(ref)\n        const expected = [\n          \"Mon Jan 01 2024 00:00:00\",\n          \"Wed Jan 03 2024 04:30:00\",\n          \"Fri Jan 05 2024 04:30:00\",\n          \"Wed Jan 10 2024 04:30:00\",\n          \"Mon Jan 15 2024 04:30:00\",\n          \"Wed Jan 17 2024 04:30:00\",\n          \"Wed Jan 24 2024 04:30:00\"\n        ]\n        deepStrictEqual(result, expected)\n      }))\n    it.effect(\"recur at time matching cron expression (second granularity)\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make<ReadonlyArray<string>>([])\n        yield* TestClock.setTime(new Date(2024, 0, 1, 0, 0, 0).getTime())\n        const schedule = Schedule.cron(\"*/3 * * * * *\")\n        yield* pipe(\n          TestClock.currentTimeMillis,\n          Effect.tap((instant) => Ref.update(ref, Array.append(format(instant)))),\n          Effect.repeat(schedule),\n          Effect.fork\n        )\n        yield* TestClock.adjust(\"30 seconds\")\n        const result = yield* Ref.get(ref)\n        const expected = [\n          \"Mon Jan 01 2024 00:00:00\",\n          \"Mon Jan 01 2024 00:00:03\",\n          \"Mon Jan 01 2024 00:00:06\",\n          \"Mon Jan 01 2024 00:00:09\",\n          \"Mon Jan 01 2024 00:00:12\",\n          \"Mon Jan 01 2024 00:00:15\",\n          \"Mon Jan 01 2024 00:00:18\",\n          \"Mon Jan 01 2024 00:00:21\",\n          \"Mon Jan 01 2024 00:00:24\",\n          \"Mon Jan 01 2024 00:00:27\",\n          \"Mon Jan 01 2024 00:00:30\"\n        ]\n        deepStrictEqual(result, expected)\n      }))\n    it.effect(\"recur at 01 second of each minute\", () =>\n      Effect.gen(function*() {\n        const originOffset = new Date(new Date(new Date().setMinutes(0)).setSeconds(0)).setMilliseconds(0)\n        const inTimeSecondMillis = new Date(new Date(originOffset).setSeconds(1)).setMilliseconds(1)\n        const inTimeSecond = new Date(originOffset).setSeconds(1)\n        const beforeTime = new Date(originOffset).setSeconds(0)\n        const afterTime = new Date(originOffset).setSeconds(3)\n        const input = Chunk.make(inTimeSecondMillis, inTimeSecond, beforeTime, afterTime).pipe(\n          Chunk.map((n) => [n, void 0] as const)\n        )\n        const result = yield* pipe(\n          runManually(Schedule.secondOfMinute(1), input),\n          Effect.map((output) => output[0].pipe(Chunk.map((tuple) => tuple[0])))\n        )\n        const expectedDate = new Date(new Date(originOffset).setSeconds(1))\n        const expected = expectedDate.getTime()\n        const afterTimeExpected = new Date(expectedDate).setMinutes(expectedDate.getMinutes() + 1)\n        const expectedOutput = Chunk.make(expected, afterTimeExpected, expected, afterTimeExpected)\n        deepStrictEqual(result, expectedOutput)\n      }))\n    it.effect(\"recur at 01 minute of each hour\", () =>\n      Effect.gen(function*() {\n        const originOffset = new Date(new Date(new Date().setHours(0)).setSeconds(0)).setMilliseconds(0)\n        const inTimeMinuteMillis = new Date(new Date(originOffset).setMinutes(1)).setMilliseconds(1)\n        const inTimeMinute = new Date(originOffset).setMinutes(1)\n        const beforeTime = new Date(originOffset).setMinutes(0)\n        const afterTime = new Date(originOffset).setMinutes(3)\n        const input = Chunk.make(inTimeMinuteMillis, inTimeMinute, beforeTime, afterTime).pipe(\n          Chunk.map((n) => [n, void 0] as const)\n        )\n        const result = yield* pipe(\n          runManually(Schedule.minuteOfHour(1), input),\n          Effect.map((output) => output[0].pipe(Chunk.map((tuple) => tuple[0])))\n        )\n        const expected = new Date(new Date(originOffset).setMinutes(1))\n        const afterTimeExpected = new Date(expected).setHours(expected.getHours() + 1)\n        const expectedOutput = Chunk.make(expected.getTime(), afterTimeExpected, expected.getTime(), afterTimeExpected)\n        deepStrictEqual(result, expectedOutput)\n      }))\n    it.effect(\"recur at 01 hour of each day\", () =>\n      Effect.gen(function*() {\n        const originOffset = roundToNearestHour(new Date())\n        const inTimeHourSecond = new Date(new Date(originOffset).setHours(1)).setSeconds(1)\n        const inTimeHour = new Date(originOffset).setHours(1)\n        const beforeTime = new Date(originOffset).setHours(0)\n        const afterTime = new Date(originOffset).setHours(3)\n        const input = Chunk.make(inTimeHourSecond, inTimeHour, beforeTime, afterTime).pipe(\n          Chunk.map((n) => [n, void 0] as const)\n        )\n        const result = yield* pipe(\n          runManually(Schedule.hourOfDay(1), input),\n          Effect.map((output) => output[0].pipe(Chunk.map((tuple) => tuple[0])))\n        )\n        const expectedDate = new Date(new Date(originOffset).setHours(1))\n        const expected = expectedDate.getTime()\n        const afterTimeExpected = new Date(expectedDate).setDate(expectedDate.getDate() + 1)\n        const expectedOutput = Chunk.make(expected, afterTimeExpected, expected, afterTimeExpected)\n        deepStrictEqual(result, expectedOutput)\n      }))\n    it.effect(\"recur at Tuesday of each week\", () =>\n      Effect.gen(function*() {\n        const withDayOfWeek = (now: number, dayOfWeek: number): number => {\n          const date = new Date(now)\n          return date.setDate(date.getDate() + (7 + dayOfWeek - date.getDay()) % 7)\n        }\n        const originOffset = new Date().setHours(0, 0, 0, 0)\n        const tuesday = new Date(withDayOfWeek(originOffset, 2))\n        const tuesdayHour = new Date(tuesday).setHours(1)\n        const monday = new Date(tuesday).setDate(tuesday.getDate() - 1)\n        const wednesday = new Date(tuesday).setDate(tuesday.getDate() + 1)\n        const input = Chunk.make(tuesdayHour, tuesday.getTime(), monday, wednesday).pipe(\n          Chunk.map((n) => [n, void 0] as const)\n        )\n        const result = yield* pipe(\n          runManually(Schedule.dayOfWeek(2), input),\n          Effect.map((output) => output[0].pipe(Chunk.map((tuple) => tuple[0])))\n        )\n        const expectedTuesday = new Date(tuesday)\n        const nextTuesday = new Date(expectedTuesday).setDate(expectedTuesday.getDate() + 7)\n        const expectedOutput = Chunk.make(\n          expectedTuesday.getTime(),\n          nextTuesday,\n          expectedTuesday.getTime(),\n          nextTuesday\n        )\n        deepStrictEqual(result, expectedOutput)\n      }))\n    it.effect(\"recur in the 2nd day of each month\", () =>\n      Effect.gen(function*() {\n        const originOffset = new Date(2020, 0, 1, 0, 0, 0).getTime()\n        const inTimeDate1 = new Date(new Date(originOffset).setDate(2)).setHours(1)\n        const inTimeDate2 = new Date(originOffset).setDate(2)\n        const before = new Date(originOffset).setDate(1)\n        const after = new Date(originOffset).setDate(2)\n        const input = Chunk.make(inTimeDate1, inTimeDate2, before, after).pipe(Chunk.map((n) => [n, void 0] as const))\n        const result = yield* pipe(\n          runManually(Schedule.dayOfMonth(2), input),\n          Effect.map((output) => output[0].pipe(Chunk.map((tuple) => tuple[0])))\n        )\n        const expectedFirstInTime = new Date(new Date(originOffset).setDate(2))\n        const expectedSecondInTime = new Date(expectedFirstInTime).setMonth(expectedFirstInTime.getMonth() + 1)\n        const expectedBefore = new Date(originOffset).setDate(2)\n        const expectedAfter = new Date(new Date(expectedBefore).setDate(2)).setMonth(\n          new Date(expectedBefore).getMonth() + 1\n        )\n        const expected = Chunk.make(expectedFirstInTime.getTime(), expectedSecondInTime, expectedBefore, expectedAfter)\n        deepStrictEqual(result, expected)\n      }))\n    it.effect(\"recur only in months containing valid number of days\", () =>\n      Effect.gen(function*() {\n        const originOffset = new Date(2020, 0, 31, 0, 0, 0).getTime()\n        const input = Chunk.of([originOffset, void 0] as const)\n        const result = yield* pipe(\n          runManually(Schedule.dayOfMonth(30), input),\n          Effect.map((output) => output[0].pipe(Chunk.map((tuple) => tuple[0])))\n        )\n        const expected = Chunk.make(new Date(originOffset).setMonth(2, 30))\n        deepStrictEqual(result, expected)\n      }))\n    it.effect(\"union with cron like schedules\", () =>\n      Effect.gen(function*() {\n        const ref = yield* Ref.make<ReadonlyArray<number>>([])\n        yield* TestClock.adjust(\"5 seconds\")\n        const schedule = Schedule.spaced(\"20 seconds\").pipe(Schedule.union(Schedule.secondOfMinute(30)))\n        yield* pipe(\n          TestClock.currentTimeMillis,\n          Effect.tap((instant) => Ref.update(ref, (seconds) => [...seconds, instant / 1000])),\n          Effect.repeat(schedule),\n          Effect.fork\n        )\n        yield* TestClock.adjust(\"2 minutes\")\n        const result = yield* Ref.get(ref)\n        const expected = [5, 25, 30, 50, 70, 90, 110]\n        deepStrictEqual(result, expected)\n      }))\n    it.effect(\"throw IllegalArgumentException on invalid `second` argument of `secondOfMinute`\", () =>\n      Effect.gen(function*() {\n        const input = Chunk.of(Date.now())\n        const exit = yield* Effect.exit(runCollect(Schedule.secondOfMinute(60), input))\n        const exception = new Cause.IllegalArgumentException(\n          \"Invalid argument in: secondOfMinute(60). Must be in range 0...59\"\n        )\n        deepStrictEqual(exit, Exit.die(exception))\n      }))\n    it.effect(\"throw IllegalArgumentException on invalid `minute` argument of `minuteOfHour`\", () =>\n      Effect.gen(function*() {\n        const input = Chunk.of(Date.now())\n        const exit = yield* Effect.exit(runCollect(Schedule.minuteOfHour(60), input))\n        const exception = new Cause.IllegalArgumentException(\n          \"Invalid argument in: minuteOfHour(60). Must be in range 0...59\"\n        )\n        deepStrictEqual(exit, Exit.die(exception))\n      }))\n    it.effect(\"throw IllegalArgumentException on invalid `hour` argument of `hourOfDay`\", () =>\n      Effect.gen(function*() {\n        const input = Chunk.of(Date.now())\n        const exit = yield* Effect.exit(runCollect(Schedule.hourOfDay(24), input))\n        const exception = new Cause.IllegalArgumentException(\n          \"Invalid argument in: hourOfDay(24). Must be in range 0...23\"\n        )\n        deepStrictEqual(exit, Exit.die(exception))\n      }))\n    it.effect(\"throw IllegalArgumentException on invalid `day` argument of `dayOfWeek`\", () =>\n      Effect.gen(function*() {\n        const input = Chunk.of(Date.now())\n        const exit = yield* Effect.exit(runCollect(Schedule.dayOfWeek(8), input))\n        const exception = new Cause.IllegalArgumentException(\n          \"Invalid argument in: dayOfWeek(8). Must be in range 1 (Monday)...7 (Sunday)\"\n        )\n        deepStrictEqual(exit, Exit.die(exception))\n      }))\n    it.effect(\"throw IllegalArgumentException on invalid `day` argument of `dayOfMonth`\", () =>\n      Effect.gen(function*() {\n        const input = Chunk.of(Date.now())\n        const exit = yield* Effect.exit(runCollect(Schedule.dayOfMonth(32), input))\n        const exception = new Cause.IllegalArgumentException(\n          \"Invalid argument in: dayOfMonth(32). Must be in range 1...31\"\n        )\n        deepStrictEqual(exit, Exit.die(exception))\n      }))\n    it.effect(\"tapOutput\", () =>\n      Effect.gen(function*() {\n        const log: Array<number | string> = []\n        const schedule = Schedule.once.pipe(\n          Schedule.as<number | string>(1),\n          Schedule.tapOutput((x) =>\n            Effect.sync(() => {\n              log.push(x)\n            })\n          )\n        )\n        yield* Effect.void.pipe(Effect.schedule(schedule))\n        deepStrictEqual(log, [1, 1])\n      }))\n  })\n})\n\nconst format = (value: number): string => {\n  const date = new Date(value)\n  const hours = `0${date.getHours()}`.slice(-2)\n  const minutes = `0${date.getMinutes()}`.slice(-2)\n  const seconds = `0${date.getSeconds()}`.slice(-2)\n  return `${date.toDateString()} ${hours}:${minutes}:${seconds}`\n}\n\nconst ioSucceed = () => Effect.succeed(\"OrElse\")\nconst ioFail = () => Effect.fail(\"OrElseFailed\")\nconst failOn0 = (ref: Ref.Ref<number>): Effect.Effect<number, string> => {\n  return Effect.gen(function*() {\n    const i = yield* Ref.updateAndGet(ref, (n) => n + 1)\n    return yield* i <= 1 ? Effect.fail(`Error: ${i}`) : Effect.succeed(i)\n  })\n}\nconst alwaysFail = (ref: Ref.Ref<number>): Effect.Effect<number, string> => {\n  return Ref.updateAndGet(ref, (n) => n + 1).pipe(Effect.flatMap((n) => Effect.fail(`Error: ${n}`)))\n}\nconst repeat = <Env, B>(schedule: Schedule.Schedule<B, number, Env>): Effect.Effect<B, never, Env> => {\n  return Ref.make(0).pipe(\n    Effect.flatMap((ref) => ref.pipe(Ref.updateAndGet((n) => n + 1), Effect.repeat(schedule)))\n  )\n}\nconst roundToNearestHour = (date: Date): number => {\n  date.setMinutes(date.getMinutes() + 30)\n  date.setMinutes(0, 0, 0)\n  return date.getMilliseconds()\n}\nconst checkDelays = <Env>(\n  schedule: Schedule.Schedule<Duration.Duration, number, Env>\n): Effect.Effect<\n  readonly [\n    Chunk.Chunk<Duration.Duration>,\n    Chunk.Chunk<Duration.Duration>\n  ],\n  never,\n  Env\n> => {\n  return Effect.gen(function*() {\n    const now = yield* Effect.sync(() => Date.now())\n    const input = Array.range(1, 5)\n    const actual = yield* pipe(schedule, Schedule.run(now, input))\n    const expected = yield* pipe(Schedule.delays(schedule), Schedule.run(now, input))\n    return [actual, expected] as const\n  })\n}\nconst checkRepetitions = <Env>(schedule: Schedule.Schedule<number, number, Env>): Effect.Effect<\n  readonly [\n    Chunk.Chunk<number>,\n    Chunk.Chunk<number>\n  ],\n  never,\n  Env\n> => {\n  return Effect.gen(function*() {\n    const now = yield* Effect.sync(() => Date.now())\n    const input = Array.range(1, 5)\n    const actual = yield* pipe(schedule, Schedule.run(now, input))\n    const expected = yield* pipe(Schedule.repetitions(schedule), Schedule.run(now, input))\n    return [actual, expected] as const\n  })\n}\nexport const run = <A, E, R>(\n  effect: Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => {\n  return Effect.fork(effect).pipe(\n    Effect.tap(() => TestClock.setTime(Number.POSITIVE_INFINITY)),\n    Effect.flatMap(Fiber.join)\n  )\n}\nexport const runCollect = <Env, In, Out>(\n  schedule: Schedule.Schedule<Out, In, Env>,\n  input: Iterable<In>\n): Effect.Effect<Chunk.Chunk<Out>, never, Env> => {\n  return run(\n    Schedule.driver(schedule).pipe(\n      Effect.flatMap((driver) => runCollectLoop(driver, Chunk.fromIterable(input), Chunk.empty()))\n    )\n  )\n}\nconst runCollectLoop = <Env, In, Out>(\n  driver: Schedule.ScheduleDriver<Out, In, Env>,\n  input: Chunk.Chunk<In>,\n  acc: Chunk.Chunk<Out>\n): Effect.Effect<Chunk.Chunk<Out>, never, Env> => {\n  if (!Chunk.isNonEmpty(input)) {\n    return Effect.succeed(acc)\n  }\n  const head = Chunk.headNonEmpty(input)\n  const tail = Chunk.tailNonEmpty(input)\n  return driver.next(head).pipe(\n    Effect.matchEffect({\n      onFailure: () =>\n        driver.last.pipe(\n          Effect.match({\n            onFailure: () => acc,\n            onSuccess: (b) => Chunk.append(acc, b)\n          })\n        ),\n      onSuccess: (b) => runCollectLoop(driver, tail, acc.pipe(Chunk.append(b)))\n    })\n  )\n}\nconst runManually = <Env, In, Out>(\n  schedule: Schedule.Schedule<Out, In, Env>,\n  inputs: Iterable<\n    readonly [\n      number,\n      In\n    ]\n  >\n): Effect.Effect<\n  readonly [\n    Chunk.Chunk<\n      readonly [\n        number,\n        Out\n      ]\n    >,\n    Option.Option<Out>\n  ],\n  never,\n  Env\n> => {\n  return runManuallyLoop(schedule, schedule.initial, Chunk.fromIterable(inputs), Chunk.empty())\n}\nconst runManuallyLoop = <Env, In, Out>(\n  schedule: Schedule.Schedule<Out, In, Env>,\n  state: unknown,\n  inputs: Chunk.Chunk<\n    readonly [\n      number,\n      In\n    ]\n  >,\n  acc: Chunk.Chunk<\n    readonly [\n      number,\n      Out\n    ]\n  >\n): Effect.Effect<\n  readonly [\n    Chunk.Chunk<\n      readonly [\n        number,\n        Out\n      ]\n    >,\n    Option.Option<Out>\n  ],\n  never,\n  Env\n> => {\n  if (!Chunk.isNonEmpty(inputs)) {\n    return Effect.succeed([Chunk.reverse(acc), Option.none()] as const)\n  }\n  const [offset, input] = Chunk.headNonEmpty(inputs)\n  const rest = Chunk.tailNonEmpty(inputs)\n  return schedule.step(offset, input, state).pipe(\n    Effect.flatMap(([state, out, decision]) => {\n      if (ScheduleDecision.isDone(decision)) {\n        return Effect.succeed([Chunk.reverse(acc), Option.some(out)] as const)\n      }\n      return runManuallyLoop(\n        schedule,\n        state,\n        rest,\n        acc.pipe(Chunk.prepend([ScheduleIntervals.start(decision.intervals), out] as const))\n      )\n    })\n  )\n}\n// TODO(Mike/Max): remove if added to `effect`\nconst scanLeft = <A, B>(self: Chunk.Chunk<A>, b: B, f: (b: B, a: A) => B): Chunk.Chunk<B> => {\n  const len = self.length\n  const out = Array.allocate<B>(len + 1) as Array<B>\n  out[0] = b\n  for (let i = 0; i < len; i++) {\n    out[i + 1] = f(out[i], self.pipe(Chunk.unsafeGet(i)))\n  }\n  return Chunk.unsafeFromArray(out)\n}\n"
  },
  {
    "path": "packages/effect/test/Schema/Arbitrary/Arbitrary.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual, throws } from \"@effect/vitest/utils\"\nimport type { FastCheck } from \"effect\"\nimport { Arbitrary, FastCheck as fc, Order, Predicate, Schema as S, SchemaAST } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"Arb\", () => {\n  describe(\"getDescription\", () => {\n    describe(\"String\", () => {\n      it(\"String\", () => {\n        const schema = S.String\n        deepStrictEqual(Arbitrary.getDescription(schema.ast, []), {\n          _tag: \"StringKeyword\",\n          constraints: [],\n          path: [],\n          refinements: [],\n          annotations: []\n        })\n      })\n\n      it(\"String & minLength(2) & maxLength(5)\", () => {\n        const schema = S.String.pipe(S.minLength(2), S.maxLength(5))\n        const ast = schema.ast\n        assertTrue(SchemaAST.isRefinement(ast))\n        assertTrue(SchemaAST.isRefinement(ast.from))\n        deepStrictEqual(Arbitrary.getDescription(ast, []), {\n          _tag: \"StringKeyword\",\n          constraints: [\n            {\n              _tag: \"StringConstraints\",\n              constraints: {\n                \"minLength\": 2\n              }\n            },\n            {\n              _tag: \"StringConstraints\",\n              constraints: {\n                maxLength: 5\n              }\n            }\n          ],\n          path: [],\n          refinements: [\n            ast.from,\n            ast\n          ],\n          annotations: []\n        })\n      })\n\n      it(\"String & annotation\", () => {\n        const f = () => (fc: typeof FastCheck) => fc.constant(\"a\")\n        const schema = S.String.annotations({ arbitrary: f })\n        deepStrictEqual(Arbitrary.getDescription(schema.ast, []), {\n          _tag: \"StringKeyword\",\n          constraints: [],\n          path: [],\n          refinements: [],\n          annotations: [f]\n        })\n      })\n\n      it(\"String & annotation & minLength(2)\", () => {\n        const f = () => (fc: typeof FastCheck) => fc.constant(\"a\")\n        const schema = S.String.annotations({ arbitrary: f }).pipe(S.minLength(2))\n        const ast = schema.ast\n        assertTrue(SchemaAST.isRefinement(ast))\n        deepStrictEqual(Arbitrary.getDescription(ast, []), {\n          _tag: \"StringKeyword\",\n          constraints: [\n            {\n              _tag: \"StringConstraints\",\n              constraints: {\n                minLength: 2\n              }\n            }\n          ],\n          path: [],\n          refinements: [ast],\n          annotations: [f]\n        })\n      })\n\n      it(\"String & minLength(2) & annotation\", () => {\n        const f = () => (fc: typeof FastCheck) => fc.constant(\"a\")\n        const schema = S.String.pipe(S.minLength(2, { arbitrary: f }))\n        const ast = schema.ast\n        assertTrue(SchemaAST.isRefinement(ast))\n        deepStrictEqual(Arbitrary.getDescription(ast, []), {\n          _tag: \"StringKeyword\",\n          constraints: [\n            {\n              _tag: \"StringConstraints\",\n              constraints: {\n                minLength: 2\n              }\n            }\n          ],\n          path: [],\n          refinements: [ast],\n          annotations: [f]\n        })\n      })\n    })\n  })\n\n  describe(\"makeLazy\", () => {\n    describe(\"Errors\", () => {\n      it(\"should throw on `Declaration`s without annotations\", () => {\n        const schema = S.declare(Predicate.isUnknown)\n        throws(\n          () => Arbitrary.makeLazy(schema),\n          new Error(`Missing annotation\ndetails: Generating an Arbitrary for this schema requires an \"arbitrary\" annotation\nschema (Declaration): <declaration schema>`)\n        )\n        throws(\n          () => Arbitrary.makeLazy(S.Tuple(S.declare(Predicate.isUnknown))),\n          new Error(`Missing annotation\nat path: [0]\ndetails: Generating an Arbitrary for this schema requires an \"arbitrary\" annotation\nschema (Declaration): <declaration schema>`)\n        )\n        throws(\n          () => Arbitrary.makeLazy(S.Struct({ a: S.declare(Predicate.isUnknown) })),\n          new Error(`Missing annotation\nat path: [\"a\"]\ndetails: Generating an Arbitrary for this schema requires an \"arbitrary\" annotation\nschema (Declaration): <declaration schema>`)\n        )\n        throws(\n          () =>\n            Arbitrary.makeLazy(\n              S.Record({ key: S.String, value: S.declare(Predicate.isUnknown) })\n            ),\n          new Error(`Missing annotation\ndetails: Generating an Arbitrary for this schema requires an \"arbitrary\" annotation\nschema (Declaration): <declaration schema>`)\n        )\n      })\n\n      it(\"should throw on `NeverKeyword`s without annotations\", () => {\n        throws(\n          () => Arbitrary.makeLazy(S.Never),\n          new Error(`Missing annotation\ndetails: Generating an Arbitrary for this schema requires an \"arbitrary\" annotation\nschema (NeverKeyword): never`)\n        )\n      })\n\n      it(\"should throw on `Enums`s with no enums\", () => {\n        enum Fruits {}\n        const schema = S.Enums(Fruits)\n        throws(\n          () => Arbitrary.makeLazy(schema)(fc),\n          new Error(`Empty Enums schema\ndetails: Generating an Arbitrary for this schema requires at least one enum`)\n        )\n      })\n    })\n\n    describe(\"Unrefined Primitives\", () => {\n      it(\"Void\", () => {\n        Util.assertions.arbitrary.validateGeneratedValues(S.Void)\n      })\n\n      it(\"String\", () => {\n        const schema = S.String\n        Util.assertions.arbitrary.validateGeneratedValues(schema)\n      })\n\n      it(\"Number\", () => {\n        Util.assertions.arbitrary.validateGeneratedValues(S.Number)\n      })\n\n      it(\"Boolean\", () => {\n        Util.assertions.arbitrary.validateGeneratedValues(S.Boolean)\n      })\n\n      it(\"BigIntFromSelf\", () => {\n        Util.assertions.arbitrary.validateGeneratedValues(S.BigIntFromSelf)\n      })\n\n      it(\"SymbolFromSelf\", () => {\n        Util.assertions.arbitrary.validateGeneratedValues(S.SymbolFromSelf)\n      })\n\n      it(\"Object\", () => {\n        Util.assertions.arbitrary.validateGeneratedValues(S.Object)\n      })\n\n      it(\"Any\", () => {\n        Util.assertions.arbitrary.validateGeneratedValues(S.Any)\n      })\n\n      it(\"Unknown\", () => {\n        Util.assertions.arbitrary.validateGeneratedValues(S.Unknown)\n      })\n\n      it(\"UniqueSymbolFromSelf\", () => {\n        const a = Symbol.for(\"effect/Schema/test/a\")\n        const schema = S.UniqueSymbolFromSelf(a)\n        Util.assertions.arbitrary.validateGeneratedValues(schema)\n      })\n\n      describe(\"Literal\", () => {\n        it(\"single literal\", () => {\n          const schema = S.Literal(1)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"multiple literals\", () => {\n          const schema = S.Literal(1, \"a\")\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      describe(\"TemplateLiteral\", () => {\n        it(\"a\", () => {\n          const schema = S.TemplateLiteral(S.Literal(\"a\"))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"a b\", () => {\n          const schema = S.TemplateLiteral(S.Literal(\"a\"), S.Literal(\" \"), S.Literal(\"b\"))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"a${string}\", () => {\n          const schema = S.TemplateLiteral(S.Literal(\"a\"), S.String)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"a${number}\", () => {\n          const schema = S.TemplateLiteral(S.Literal(\"a\"), S.Number)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"a\", () => {\n          const schema = S.TemplateLiteral(S.Literal(\"a\"))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"${string}\", () => {\n          const schema = S.TemplateLiteral(S.String)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"a${string}b\", () => {\n          const schema = S.TemplateLiteral(S.Literal(\"a\"), S.String, S.Literal(\"b\"))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html\", async () => {\n          const EmailLocaleIDs = S.Literal(\"welcome_email\", \"email_heading\")\n          const FooterLocaleIDs = S.Literal(\"footer_title\", \"footer_sendoff\")\n          const schema = S.TemplateLiteral(S.Union(EmailLocaleIDs, FooterLocaleIDs), \"_id\")\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"< + h + (1|2) + >\", async () => {\n          const schema = S.TemplateLiteral(\"<\", S.TemplateLiteral(\"h\", S.Literal(1, 2)), \">\")\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      describe(\"Enums\", () => {\n        it(\"Numeric enums\", () => {\n          enum Fruits {\n            Apple,\n            Banana\n          }\n          const schema = S.Enums(Fruits)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"String enums\", () => {\n          enum Fruits {\n            Apple = \"apple\",\n            Banana = \"banana\",\n            Cantaloupe = 0\n          }\n          const schema = S.Enums(Fruits)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"Const enums\", () => {\n          const Fruits = {\n            Apple: \"apple\",\n            Banana: \"banana\",\n            Cantaloupe: 3\n          } as const\n          const schema = S.Enums(Fruits)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      describe(\"Struct\", () => {\n        it(\"fields\", () => {\n          const schema = S.Struct({ a: S.String, b: S.Number })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"fields + record\", () => {\n          const schema = S.Struct({ a: S.String }, S.Record({ key: S.String, value: S.Union(S.String, S.Number) }))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"required property signature\", () => {\n          const schema = S.Struct({ a: S.Number })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"required property signature with undefined\", () => {\n          const schema = S.Struct({ a: S.Union(S.Number, S.Undefined) })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"optional property signature\", () => {\n          const schema = S.Struct({ a: S.optionalWith(S.Number, { exact: true }) })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"optional property signature with undefined\", () => {\n          const schema = S.Struct({\n            a: S.optionalWith(S.Union(S.Number, S.Undefined), { exact: true })\n          })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      describe(\"Record\", () => {\n        it(\"Record(string, string)\", () => {\n          const schema = S.Record({ key: S.String, value: S.String })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"Record(symbol, string)\", () => {\n          const schema = S.Record({ key: S.SymbolFromSelf, value: S.String })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      it(\"Union\", () => {\n        const schema = S.Union(S.String, S.Number)\n        Util.assertions.arbitrary.validateGeneratedValues(schema)\n      })\n\n      describe(\"Tuple\", () => {\n        it(\"empty\", () => {\n          const schema = S.Tuple()\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"required element\", () => {\n          const schema = S.Tuple(S.Number)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"required element with undefined\", () => {\n          const schema = S.Tuple(S.Union(S.Number, S.Undefined))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"optional element\", () => {\n          const schema = S.Tuple(S.optionalElement(S.Number))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"optional element with undefined\", () => {\n          const schema = S.Tuple(S.optionalElement(S.Union(S.Number, S.Undefined)))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"e e?\", () => {\n          const schema = S.Tuple(S.String, S.optionalElement(S.Number))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"e r\", () => {\n          const schema = S.Tuple([S.String], S.Number)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"e? r\", () => {\n          const schema = S.Tuple([S.optionalElement(S.String)], S.Number)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"r\", () => {\n          const schema = S.Array(S.Number)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"r e\", () => {\n          const schema = S.Tuple([], S.String, S.Number)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"e r e\", () => {\n          const schema = S.Tuple([S.String], S.Number, S.Boolean)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      describe(\"suspend\", () => {\n        it(\"should support an arbitrary annotation\", () => {\n          interface A {\n            readonly a: string\n            readonly as: ReadonlyArray<A>\n          }\n          const arb: fc.Arbitrary<any> = fc.letrec((tie) => ({\n            root: fc.record({\n              a: fc.string(),\n              as: fc.oneof(\n                { depthSize: \"small\" },\n                fc.constant([]),\n                fc.array(tie(\"root\"))\n              )\n            })\n          })).root\n          const schema = S.Struct({\n            a: S.String,\n            as: S.Array(\n              S.suspend((): S.Schema<A> => schema).annotations({ arbitrary: () => () => arb })\n            )\n          })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"make(S.encodedSchema(schema))\", () => {\n          const NumberFromString = S.NumberFromString\n          interface I {\n            readonly a: string | I\n          }\n          interface A {\n            readonly a: number | A\n          }\n          const schema = S.Struct({\n            a: S.Union(NumberFromString, S.suspend((): S.Schema<A, I> => schema))\n          })\n\n          Util.assertions.arbitrary.validateGeneratedValues(S.encodedSchema(schema))\n        })\n\n        it(\"Tuple\", () => {\n          type A = readonly [number, A | null]\n          const schema = S.Tuple(\n            S.Number,\n            S.NullOr(S.suspend((): S.Schema<A> => schema))\n          )\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"Array\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.Array(S.Union(S.String, Rec))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"Struct\", () => {\n          interface A {\n            readonly a: string\n            readonly as: ReadonlyArray<A>\n          }\n          const schema = S.Struct({\n            a: S.String,\n            as: S.Array(S.suspend((): S.Schema<A> => schema))\n          })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"Record\", () => {\n          type A = {\n            [_: string]: A\n          }\n          const schema = S.Record({ key: S.String, value: S.suspend((): S.Schema<A> => schema) })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"optional\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.Struct({\n            a: S.optional(Rec)\n          })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"Array + Array\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.Struct({\n            a: S.Array(Rec),\n            b: S.Array(Rec)\n          })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"optional + Array\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.Struct({\n            a: S.optional(Rec),\n            b: S.Array(Rec)\n          })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it.skip(\"mutually suspended schemas\", { retry: 5 }, () => {\n          interface Expression {\n            readonly type: \"expression\"\n            readonly value: number | Operation\n          }\n\n          interface Operation {\n            readonly type: \"operation\"\n            readonly operator: \"+\" | \"-\"\n            readonly left: Expression\n            readonly right: Expression\n          }\n\n          const Expression = S.Struct({\n            type: S.Literal(\"expression\"),\n            value: S.Union(S.JsonNumber, S.suspend((): S.Schema<Operation> => Operation))\n          })\n\n          const Operation = S.Struct({\n            type: S.Literal(\"operation\"),\n            operator: S.Union(S.Literal(\"+\"), S.Literal(\"-\")),\n            left: Expression,\n            right: Expression\n          })\n          Util.assertions.arbitrary.validateGeneratedValues(Operation)\n        })\n      })\n\n      describe(\"Transformation\", () => {\n        it(\"clamp\", () => {\n          const schema = S.Number.pipe(S.clamp(1.3, 3.1))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n    })\n\n    describe(\"Data Types\", () => {\n      describe(\"Unrefined\", () => {\n        it(\"DateFromSelf\", () => {\n          const schema = S.DateFromSelf\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"DurationFromSelf\", () => {\n          const schema = S.DurationFromSelf\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      describe(\"Suspend\", () => {\n        it(\"RedactedFromSelf\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.RedactedFromSelf(S.NullOr(Rec))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"OptionFromSelf\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.OptionFromSelf(Rec)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"EitherFromSelf\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.EitherFromSelf({ left: S.String, right: Rec })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"MapFromSelf\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.MapFromSelf({ key: S.String, value: Rec })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"SetFromSelf\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.SetFromSelf(Rec)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"ChunkFromSelf\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.ChunkFromSelf(Rec)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"HashSetFromSelf\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.HashSetFromSelf(Rec)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"HashMapFromSelf\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.HashMapFromSelf({ key: S.String, value: Rec })\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"ListFromSelf\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.ListFromSelf(Rec)\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"SortedSetFromSelf\", () => {\n          const Rec = S.suspend((): any => schema)\n          const schema: any = S.SortedSetFromSelf(Rec, Order.empty(), Order.empty())\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        describe(\"DateTime\", () => {\n          it(\"DateTimeUtcFromSelf\", () => {\n            Util.assertions.arbitrary.validateGeneratedValues(S.DateTimeUtcFromSelf)\n          })\n\n          it(\"TimeZoneOffsetFromSelf\", () => {\n            Util.assertions.arbitrary.validateGeneratedValues(S.TimeZoneOffsetFromSelf)\n          })\n\n          it(\"TimeZoneNamedFromSelf\", () => {\n            Util.assertions.arbitrary.validateGeneratedValues(S.TimeZoneNamedFromSelf)\n          })\n\n          it(\"DateTimeZonedFromSelf\", () => {\n            Util.assertions.arbitrary.validateGeneratedValues(S.DateTimeZonedFromSelf)\n          })\n        })\n      })\n    })\n\n    describe(\"Refinement\", () => {\n      const assertConstraints = <A, I>(\n        schema: S.Schema<A, I, never>,\n        constraints: ReadonlyArray<\n          | ReturnType<typeof Arbitrary.makeStringConstraints>\n          | ReturnType<typeof Arbitrary.makeNumberConstraints>\n          | ReturnType<typeof Arbitrary.makeBigIntConstraints>\n          | ReturnType<typeof Arbitrary.makeDateConstraints>\n          | ReturnType<typeof Arbitrary.makeArrayConstraints>\n        >\n      ) => {\n        const description = Arbitrary.getDescription(schema.ast, [])\n        switch (description._tag) {\n          case \"StringKeyword\": {\n            assertTrue(constraints.every((c) => c._tag === \"StringConstraints\"))\n            deepStrictEqual(description.constraints, constraints)\n            break\n          }\n          case \"NumberKeyword\": {\n            assertTrue(constraints.every((c) => c._tag === \"NumberConstraints\"))\n            deepStrictEqual(description.constraints, constraints)\n            break\n          }\n          case \"BigIntKeyword\": {\n            assertTrue(constraints.every((c) => c._tag === \"BigIntConstraints\"))\n            deepStrictEqual(description.constraints, constraints)\n            break\n          }\n          case \"DateFromSelf\": {\n            assertTrue(constraints.every((c) => c._tag === \"DateConstraints\"))\n            deepStrictEqual(description.constraints, constraints)\n            break\n          }\n          case \"TupleType\": {\n            assertTrue(constraints.every((c) => c._tag === \"ArrayConstraints\"))\n            deepStrictEqual(description.constraints, constraints)\n            break\n          }\n        }\n      }\n\n      describe(\"array filters\", () => {\n        it(\"Array\", () => {\n          const schema = S.Array(S.String).pipe(S.filter(() => true))\n          assertConstraints(schema, [Arbitrary.makeArrayConstraints({})])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"minItems (Array)\", () => {\n          const schema = S.Array(S.String).pipe(S.minItems(2))\n          assertConstraints(schema, [Arbitrary.makeArrayConstraints({ minLength: 2 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"minItems (NonEmptyArray)\", () => {\n          const schema = S.NonEmptyArray(S.String).pipe(S.minItems(2))\n          assertConstraints(schema, [Arbitrary.makeArrayConstraints({ minLength: 2 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"maxItems (Array)\", () => {\n          const schema = S.Array(S.String).pipe(S.maxItems(5))\n          assertConstraints(schema, [Arbitrary.makeArrayConstraints({ maxLength: 5 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"maxItems (NonEmptyArray)\", () => {\n          const schema = S.NonEmptyArray(S.String).pipe(S.maxItems(5))\n          assertConstraints(schema, [Arbitrary.makeArrayConstraints({ maxLength: 5 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"itemsCount (Array)\", () => {\n          const schema = S.Array(S.String).pipe(S.itemsCount(3))\n          assertConstraints(schema, [Arbitrary.makeArrayConstraints({ minLength: 3, maxLength: 3 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"itemsCount (NonEmptyArray)\", () => {\n          const schema = S.NonEmptyArray(S.String).pipe(S.itemsCount(3))\n          assertConstraints(schema, [Arbitrary.makeArrayConstraints({ minLength: 3, maxLength: 3 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      describe(\"string filters\", () => {\n        it(\"String\", () => {\n          const schema = S.String.pipe(S.filter(() => true))\n          assertConstraints(schema, [Arbitrary.makeStringConstraints({})])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"minLength\", () => {\n          const schema = S.String.pipe(S.minLength(2))\n          assertConstraints(schema, [Arbitrary.makeStringConstraints({ minLength: 2 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"maxLength\", () => {\n          const schema = S.String.pipe(S.maxLength(5))\n          assertConstraints(schema, [Arbitrary.makeStringConstraints({ maxLength: 5 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"length: number\", () => {\n          const schema = S.String.pipe(S.length(10))\n          assertConstraints(schema, [Arbitrary.makeStringConstraints({ minLength: 10, maxLength: 10 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"length: { min, max }\", () => {\n          const schema = S.String.pipe(S.length({ min: 2, max: 5 }))\n          assertConstraints(schema, [Arbitrary.makeStringConstraints({ minLength: 2, maxLength: 5 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"minLength + maxLength\", () => {\n          const schema = S.String.pipe(S.minLength(2), S.maxLength(5))\n          assertConstraints(schema, [\n            Arbitrary.makeStringConstraints({ minLength: 2 }),\n            Arbitrary.makeStringConstraints({ maxLength: 5 })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"annotation + minLength + maxLength\", () => {\n          const schema = S.String.annotations({ arbitrary: () => (fc) => fc.string() }).pipe(\n            S.minLength(2),\n            S.maxLength(5)\n          )\n          assertConstraints(schema, [\n            Arbitrary.makeStringConstraints({ minLength: 2 }),\n            Arbitrary.makeStringConstraints({ maxLength: 5 })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"minLength + maxLength + annotation\", () => {\n          const schema = S.String.pipe(\n            S.minLength(2),\n            S.maxLength(5)\n          ).annotations({ arbitrary: () => (fc) => fc.string() })\n          assertConstraints(schema, [\n            Arbitrary.makeStringConstraints({ minLength: 2 }),\n            Arbitrary.makeStringConstraints({ maxLength: 5 })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"startsWith\", () => {\n          const schema = S.String.pipe(S.startsWith(\"a\"))\n          assertConstraints(schema, [Arbitrary.makeStringConstraints({ pattern: \"^a\" })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"endsWith\", () => {\n          const schema = S.String.pipe(S.endsWith(\"a\"))\n          assertConstraints(schema, [Arbitrary.makeStringConstraints({ pattern: \"^.*a$\" })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"pattern\", () => {\n          const regex = /^[A-Z]{3}[0-9]{3}$/\n          const schema = S.String.pipe(S.pattern(regex))\n          assertConstraints(schema, [Arbitrary.makeStringConstraints({ pattern: regex.source })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"nonEmptyString + pattern\", () => {\n          const regex = /^[-]*$/\n          const schema = S.String.pipe(S.nonEmptyString(), S.pattern(regex))\n          assertConstraints(schema, [\n            Arbitrary.makeStringConstraints({ minLength: 1 }),\n            Arbitrary.makeStringConstraints({ pattern: regex.source })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"pattern + pattern\", () => {\n          const regexp1 = /^[^A-Z]*$/\n          const regexp2 = /^0x[0-9a-f]{40}$/\n          const schema = S.String.pipe(S.pattern(regexp1), S.pattern(regexp2))\n          assertConstraints(\n            schema,\n            [\n              Arbitrary.makeStringConstraints({ pattern: regexp1.source }),\n              Arbitrary.makeStringConstraints({ pattern: regexp2.source })\n            ]\n          )\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      describe(\"number filters\", () => {\n        it(\"Number\", () => {\n          const schema = S.Number.pipe(S.filter(() => true))\n          assertConstraints(schema, [Arbitrary.makeNumberConstraints({})])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"nonNaN\", () => {\n          const schema = S.Number.pipe(S.nonNaN())\n          assertConstraints(schema, [Arbitrary.makeNumberConstraints({ noNaN: true })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"finite\", () => {\n          const schema = S.Number.pipe(S.finite())\n          assertConstraints(schema, [Arbitrary.makeNumberConstraints({ noNaN: true, noDefaultInfinity: true })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"JsonNumber\", () => {\n          const schema = S.JsonNumber\n          assertConstraints(schema, [Arbitrary.makeNumberConstraints({ noDefaultInfinity: true, noNaN: true })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"int\", () => {\n          const schema = S.Number.pipe(S.int())\n          assertConstraints(schema, [Arbitrary.makeNumberConstraints({ isInteger: true })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"between int\", () => {\n          const schema = S.Number.pipe(S.between(2, 5), S.int())\n          assertConstraints(schema, [\n            Arbitrary.makeNumberConstraints({ min: 2, max: 5 }),\n            Arbitrary.makeNumberConstraints({ isInteger: true })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"int between\", () => {\n          const schema = S.Number.pipe(S.int(), S.between(2, 5))\n          assertConstraints(schema, [\n            Arbitrary.makeNumberConstraints({ isInteger: true }),\n            Arbitrary.makeNumberConstraints({ min: 2, max: 5 })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"lessThanOrEqualTo\", () => {\n          const schema = S.Number.pipe(S.lessThanOrEqualTo(5))\n          assertConstraints(schema, [Arbitrary.makeNumberConstraints({ max: 5 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"greaterThanOrEqualTo\", () => {\n          const schema = S.Number.pipe(S.greaterThanOrEqualTo(2))\n          assertConstraints(schema, [Arbitrary.makeNumberConstraints({ min: 2 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"lessThan\", () => {\n          const schema = S.Number.pipe(S.lessThan(5))\n          assertConstraints(schema, [Arbitrary.makeNumberConstraints({ max: 5, maxExcluded: true })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"greaterThan\", () => {\n          const schema = S.Number.pipe(S.greaterThan(2))\n          assertConstraints(schema, [Arbitrary.makeNumberConstraints({ min: 2, minExcluded: true })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"between\", () => {\n          const schema = S.Number.pipe(S.between(2, 5))\n          assertConstraints(schema, [Arbitrary.makeNumberConstraints({ min: 2, max: 5 })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      describe(\"bigint filters\", () => {\n        it(\"BigIntFromSelf\", () => {\n          const schema = S.BigIntFromSelf.pipe(S.filter(() => true))\n          assertConstraints(schema, [])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"lessThanOrEqualTo\", () => {\n          const schema = S.BigIntFromSelf.pipe(S.lessThanOrEqualToBigInt(BigInt(5)))\n          assertConstraints(schema, [Arbitrary.makeBigIntConstraints({ max: BigInt(5) })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"greaterThanOrEqualTo\", () => {\n          const schema = S.BigIntFromSelf.pipe(S.greaterThanOrEqualToBigInt(BigInt(2)))\n          assertConstraints(schema, [Arbitrary.makeBigIntConstraints({ min: BigInt(2) })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"lessThan\", () => {\n          const schema = S.BigIntFromSelf.pipe(S.lessThanBigInt(BigInt(5)))\n          assertConstraints(schema, [Arbitrary.makeBigIntConstraints({ max: BigInt(5) })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"greaterThan\", () => {\n          const schema = S.BigIntFromSelf.pipe(S.greaterThanBigInt(BigInt(2)))\n          assertConstraints(schema, [Arbitrary.makeBigIntConstraints({ min: BigInt(2) })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"between\", () => {\n          const schema = S.BigIntFromSelf.pipe(S.betweenBigInt(BigInt(2), BigInt(5)))\n          assertConstraints(schema, [Arbitrary.makeBigIntConstraints({ min: BigInt(2), max: BigInt(5) })])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n\n      describe(\"date filters\", () => {\n        it(\"DateFromSelf\", () => {\n          const schema = S.DateFromSelf\n          assertConstraints(schema, [\n            Arbitrary.makeDateConstraints({ noInvalidDate: false })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"ValidDateFromSelf\", () => {\n          const schema = S.ValidDateFromSelf\n          assertConstraints(schema, [\n            Arbitrary.makeDateConstraints({ noInvalidDate: false }),\n            Arbitrary.makeDateConstraints({ noInvalidDate: true })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"lessThanOrEqualTo\", () => {\n          const schema = S.DateFromSelf.pipe(S.lessThanOrEqualToDate(new Date(5)))\n          assertConstraints(schema, [\n            Arbitrary.makeDateConstraints({ noInvalidDate: false }),\n            Arbitrary.makeDateConstraints({ max: new Date(5) })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"greaterThanOrEqualTo\", () => {\n          const schema = S.DateFromSelf.pipe(S.greaterThanOrEqualToDate(new Date(2)))\n          assertConstraints(schema, [\n            Arbitrary.makeDateConstraints({ noInvalidDate: false }),\n            Arbitrary.makeDateConstraints({ min: new Date(2) })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"lessThan\", () => {\n          const schema = S.DateFromSelf.pipe(S.lessThanDate(new Date(5)))\n          assertConstraints(schema, [\n            Arbitrary.makeDateConstraints({ noInvalidDate: false }),\n            Arbitrary.makeDateConstraints({ max: new Date(5) })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"greaterThan\", () => {\n          const schema = S.DateFromSelf.pipe(S.greaterThanDate(new Date(2)))\n          assertConstraints(schema, [\n            Arbitrary.makeDateConstraints({ noInvalidDate: false }),\n            Arbitrary.makeDateConstraints({ min: new Date(2) })\n          ])\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"between\", () => {\n          const schema = S.DateFromSelf.pipe(S.betweenDate(new Date(2), new Date(5)))\n          assertConstraints(\n            schema,\n            [\n              Arbitrary.makeDateConstraints({ noInvalidDate: false }),\n              Arbitrary.makeDateConstraints({ min: new Date(2), max: new Date(5) })\n            ]\n          )\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n      })\n    })\n\n    describe(\"Annotations\", () => {\n      const assertAnnotation = <A, I>(source: S.Schema<A, I>) => {\n        const schema = source.annotations({ arbitrary: () => (fc) => fc.constant(\"custom arbitrary\") as any })\n        const arb = Arbitrary.make(schema)\n        strictEqual(fc.sample(arb, 1)[0], \"custom arbitrary\" as any)\n      }\n\n      it(\"Never\", () => {\n        assertAnnotation(S.Never)\n      })\n\n      it(\"Void\", () => {\n        assertAnnotation(S.Void)\n      })\n\n      it(\"Literal\", () => {\n        assertAnnotation(S.Literal(\"a\"))\n      })\n\n      it(\"Symbol\", () => {\n        assertAnnotation(S.Symbol)\n      })\n\n      it(\"UniqueSymbolFromSelf\", () => {\n        assertAnnotation(S.UniqueSymbolFromSelf(Symbol.for(\"effect/schema/test/a\")))\n      })\n\n      it(\"TemplateLiteral\", () => {\n        assertAnnotation(S.TemplateLiteral(S.Literal(\"a\"), S.String, S.Literal(\"b\")))\n      })\n\n      it(\"Undefined\", () => {\n        assertAnnotation(S.Undefined)\n      })\n\n      it(\"Unknown\", () => {\n        assertAnnotation(S.Unknown)\n      })\n\n      it(\"Any\", () => {\n        assertAnnotation(S.Any)\n      })\n\n      it(\"Object\", () => {\n        assertAnnotation(S.Object)\n      })\n\n      it(\"String\", () => {\n        assertAnnotation(S.String)\n      })\n\n      it(\"Number\", () => {\n        assertAnnotation(S.Number)\n      })\n\n      it(\"Boolean\", () => {\n        assertAnnotation(S.Boolean)\n      })\n\n      it(\"BigIntFromSelf\", () => {\n        assertAnnotation(S.BigIntFromSelf)\n      })\n\n      it(\"Enums\", () => {\n        enum Fruits {\n          Apple,\n          Banana\n        }\n        assertAnnotation(S.Enums(Fruits))\n      })\n\n      it(\"Tuple\", () => {\n        assertAnnotation(S.Tuple(S.String, S.Number))\n      })\n\n      it(\"Struct\", () => {\n        assertAnnotation(S.Struct({ a: S.String, b: S.Number }))\n      })\n\n      it(\"Union\", () => {\n        assertAnnotation(S.Union(S.String, S.Number))\n      })\n\n      it(\"suspend\", () => {\n        interface A {\n          readonly a: string\n          readonly as: ReadonlyArray<A>\n        }\n        const schema = S.Struct({\n          a: S.String,\n          as: S.Array(S.suspend((): S.Schema<A> => schema))\n        })\n        assertAnnotation(schema)\n      })\n\n      describe(\"Refinement\", () => {\n        it(\"should provide the `from` Arbitrary\", () => {\n          const schema = S.String.pipe(S.filter((s) => s.length > 2, {\n            arbitrary: (from, ctx) => (fc) => {\n              assertTrue(Predicate.isFunction(from))\n              assertTrue(Predicate.isObject(ctx))\n              return from(fc)\n            }\n          }))\n          Util.assertions.arbitrary.validateGeneratedValues(schema)\n        })\n\n        it(\"NonEmptyString\", () => {\n          assertAnnotation(S.NonEmptyString)\n        })\n      })\n\n      it(\"Transformation\", () => {\n        assertAnnotation(S.NumberFromString)\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Arbitrary/Class.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Arbitrary, FastCheck, Schema as S } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"Class\", () => {\n  it(\"baseline\", () => {\n    class Class extends S.Class<Class>(\"Class\")({\n      a: S.String,\n      b: S.NumberFromString\n    }) {}\n    Util.assertions.arbitrary.validateGeneratedValues(Class)\n  })\n\n  it(\"required property signature\", () => {\n    class Class extends S.Class<Class>(\"Class\")({\n      a: S.Number\n    }) {}\n    Util.assertions.arbitrary.validateGeneratedValues(Class)\n  })\n\n  it(\"required property signature with undefined\", () => {\n    class Class extends S.Class<Class>(\"Class\")({\n      a: S.Union(S.Number, S.Undefined)\n    }) {}\n    Util.assertions.arbitrary.validateGeneratedValues(Class)\n  })\n\n  it(\"exact optional property signature\", () => {\n    class Class extends S.Class<Class>(\"Class\")({\n      a: S.optionalWith(S.Number, { exact: true })\n    }) {}\n    Util.assertions.arbitrary.validateGeneratedValues(Class)\n  })\n\n  it(\"exact optional property signature with undefined\", () => {\n    class Class extends S.Class<Class>(\"Class\")({\n      a: S.optionalWith(S.Union(S.Number, S.Undefined), { exact: true })\n    }) {}\n    Util.assertions.arbitrary.validateGeneratedValues(Class)\n  })\n\n  it(\"transformation property signature with annotation (#4550)\", () => {\n    class Class extends S.Class<Class>(\"Class\")({\n      a: S.NumberFromString.annotations({\n        arbitrary: () => (fc) => fc.constant(1)\n      })\n    }) {}\n    const arb = Arbitrary.make(Class)\n    FastCheck.assert(FastCheck.property(arb, (a) => a.a === 1))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/JSONSchema.new.test.ts",
    "content": "import { assertFalse, assertTrue, deepStrictEqual, strictEqual, throws } from \"@effect/vitest/utils\"\nimport type { Options as AjvOptions } from \"ajv\"\nimport Ajv from \"ajv\"\nimport * as JSONSchema from \"effect/JSONSchema\"\nimport * as Schema from \"effect/Schema\"\nimport { describe, it } from \"vitest\"\n\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst Ajv2020 = require(\"ajv/dist/2020\")\n\nconst ajvOptions: Ajv.Options = {\n  strictTuples: false,\n  allowMatchingProperties: true\n}\n\nfunction getAjvValidate(jsonSchema: object): Ajv.ValidateFunction {\n  return new Ajv.default(ajvOptions).compile(jsonSchema)\n}\n\nconst baseAjvOptions: AjvOptions = {\n  allErrors: true,\n  strict: false, // warns/throws on unknown keywords depending on Ajv version\n  validateSchema: true,\n  code: { esm: true } // optional\n}\n\nconst ajvDraft7 = new Ajv.default(baseAjvOptions)\nconst ajv2020 = new Ajv2020.default(baseAjvOptions)\n\nconst expectError = <A, I>(schema: Schema.Schema<A, I>, message: string) => {\n  throws(() => JSONSchema.make(schema), new Error(message))\n}\n\nasync function assertDraft7<A, I, R>(schema: Schema.Schema<A, I, R>, expected: object) {\n  const jsonSchema = JSONSchema.make(schema)\n  deepStrictEqual(jsonSchema, {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    ...expected\n  } as any)\n  const valid = ajvDraft7.validateSchema(jsonSchema)\n  if (valid instanceof Promise) {\n    await valid\n  }\n  strictEqual(ajvDraft7.errors, null)\n  return jsonSchema\n}\n\nasync function assertDraft201909<S extends Schema.Schema.All>(\n  schema: S,\n  expected: object\n) {\n  const definitions = {}\n  const jsonSchema = JSONSchema.fromAST(schema.ast, {\n    definitions,\n    target: \"jsonSchema2019-09\"\n  })\n  deepStrictEqual(jsonSchema, expected)\n  const valid = ajv2020.validateSchema(jsonSchema)\n  if (valid instanceof Promise) {\n    await valid\n  }\n  strictEqual(ajv2020.errors, null)\n  return jsonSchema\n}\n\nasync function assertOpenApi3_1<S extends Schema.Schema.All>(\n  schema: S,\n  expected: object\n) {\n  const definitions = {}\n  const jsonSchema = JSONSchema.fromAST(schema.ast, {\n    definitions,\n    target: \"openApi3.1\"\n  })\n  deepStrictEqual(jsonSchema, expected)\n  const valid = ajv2020.validateSchema(jsonSchema)\n  if (valid instanceof Promise) {\n    await valid\n  }\n  strictEqual(ajvDraft7.errors, null)\n  return jsonSchema\n}\n\nasync function assertDraft2020_12<S extends Schema.Schema.All>(\n  schema: S,\n  expected: object\n) {\n  const definitions = {}\n  const jsonSchema = JSONSchema.fromAST(schema.ast, {\n    definitions,\n    target: \"jsonSchema2020-12\"\n  })\n  deepStrictEqual(jsonSchema, expected)\n  const valid = ajv2020.validateSchema(jsonSchema)\n  if (valid instanceof Promise) {\n    await valid\n  }\n  strictEqual(ajv2020.errors, null)\n  return jsonSchema\n}\n\nfunction assertAjvDraft7Success<S extends Schema.Schema.Any>(\n  schema: S,\n  input: S[\"Type\"]\n) {\n  const jsonSchema = JSONSchema.make(schema)\n  const validate = getAjvValidate(jsonSchema)\n  assertTrue(validate(input))\n}\n\nfunction assertAjvDraft7Failure<S extends Schema.Schema.Any>(\n  schema: S,\n  input: unknown\n) {\n  const jsonSchema = JSONSchema.make(schema)\n  const validate = getAjvValidate(jsonSchema)\n  assertFalse(validate(input))\n}\n\ndescribe(\"JSONSchema\", () => {\n  describe(\"fromAST\", () => {\n    it(\"definitionsPath\", () => {\n      const schema = Schema.String.annotations({ identifier: \"08368672-2c02-4d6d-92b0-dd0019b33a7b\" })\n      const definitions = {}\n      const jsonSchema = JSONSchema.fromAST(schema.ast, {\n        definitions,\n        definitionPath: \"#/components/schemas/\"\n      })\n      deepStrictEqual(jsonSchema, {\n        \"$ref\": \"#/components/schemas/08368672-2c02-4d6d-92b0-dd0019b33a7b\"\n      })\n      deepStrictEqual(definitions, {\n        \"08368672-2c02-4d6d-92b0-dd0019b33a7b\": {\n          \"type\": \"string\"\n        }\n      })\n    })\n\n    describe(\"topLevelReferenceStrategy\", () => {\n      describe(`\"skip\"`, () => {\n        it(\"top level identifier\", () => {\n          const schema = Schema.String.annotations({ identifier: \"1b205579-f159-48d4-a218-f09426bca040\" })\n          const definitions = {}\n          const jsonSchema = JSONSchema.fromAST(schema.ast, {\n            definitions,\n            topLevelReferenceStrategy: \"skip\"\n          })\n          deepStrictEqual(jsonSchema, {\n            \"type\": \"string\"\n          })\n          deepStrictEqual(definitions, {})\n        })\n\n        it(\"nested identifiers\", () => {\n          class A extends Schema.Class<A>(\"A\")({ a: Schema.String.annotations({ identifier: \"ID4\" }) }) {}\n          const schema = Schema.Struct({\n            a: Schema.String.annotations({ identifier: \"ID\" }),\n            b: Schema.Date,\n            c: Schema.Struct({\n              d: Schema.String.annotations({ identifier: \"ID3\" })\n            }).annotations({ identifier: \"ID2\" }),\n            e: A\n          })\n          const definitions = {}\n          const jsonSchema = JSONSchema.fromAST(schema.ast, {\n            definitions,\n            topLevelReferenceStrategy: \"skip\"\n          })\n          deepStrictEqual(jsonSchema, {\n            \"type\": \"object\",\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\"\n              },\n              \"b\": {\n                \"type\": \"string\",\n                \"description\": \"a string to be decoded into a Date\"\n              },\n              \"c\": {\n                \"type\": \"object\",\n                \"properties\": {\n                  \"d\": { \"type\": \"string\" }\n                },\n                \"required\": [\"d\"],\n                \"additionalProperties\": false\n              },\n              \"e\": {\n                \"type\": \"object\",\n                \"properties\": {\n                  \"a\": { \"type\": \"string\" }\n                },\n                \"required\": [\"a\"],\n                \"additionalProperties\": false\n              }\n            },\n            \"required\": [\"a\", \"b\", \"c\", \"e\"],\n            \"additionalProperties\": false\n          })\n          deepStrictEqual(definitions, {})\n        })\n\n        it(\"suspended schema\", () => {\n          interface A {\n            readonly a: string\n            readonly as: ReadonlyArray<A>\n          }\n          const schema: Schema.Schema<A> = Schema.suspend(() =>\n            Schema.Struct({\n              a: Schema.String.annotations({ identifier: \"ID2\" }),\n              as: Schema.Array(schema)\n            })\n          ).annotations({ identifier: \"ID\" })\n          const definitions = {}\n          const jsonSchema = JSONSchema.fromAST(schema.ast, {\n            definitions,\n            topLevelReferenceStrategy: \"skip\"\n          })\n          deepStrictEqual(jsonSchema, {\n            \"$ref\": \"#/$defs/ID\"\n          })\n          deepStrictEqual(definitions, {\n            \"ID\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"a\": { \"type\": \"string\" },\n                \"as\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/ID\" } }\n              },\n              \"required\": [\"a\", \"as\"],\n              \"additionalProperties\": false\n            }\n          })\n        })\n      })\n    })\n\n    describe(\"additionalPropertiesStrategy\", () => {\n      it(`\"allow\"`, () => {\n        const schema = Schema.Struct({\n          a: Schema.String,\n          b: Schema.Struct({\n            c: Schema.String\n          })\n        })\n        const definitions = {}\n        const jsonSchema = JSONSchema.fromAST(schema.ast, {\n          definitions,\n          additionalPropertiesStrategy: \"allow\"\n        })\n        deepStrictEqual(jsonSchema, {\n          \"type\": \"object\",\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\"\n            },\n            \"b\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"c\": { \"type\": \"string\" }\n              },\n              \"required\": [\"c\"],\n              \"additionalProperties\": true\n            }\n          },\n          \"required\": [\"a\", \"b\"],\n          \"additionalProperties\": true\n        })\n        deepStrictEqual(definitions, {})\n      })\n    })\n  })\n\n  describe(\"Unsupported schemas\", () => {\n    it(\"Tuple with an unsupported component\", () => {\n      expectError(\n        Schema.Tuple(Schema.Undefined),\n        `Missing annotation\nat path: [0]\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (UndefinedKeyword): undefined`\n      )\n    })\n\n    it(\"Struct with an unsupported field\", () => {\n      expectError(\n        Schema.Struct({ a: Schema.SymbolFromSelf }),\n        `Missing annotation\nat path: [\"a\"]\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (SymbolKeyword): symbol`\n      )\n    })\n\n    it(\"Declaration\", async () => {\n      expectError(\n        Schema.ChunkFromSelf(Schema.String),\n        `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (Declaration): Chunk<string>`\n      )\n    })\n\n    it(\"Undefined\", async () => {\n      expectError(\n        Schema.Undefined,\n        `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (UndefinedKeyword): undefined`\n      )\n    })\n\n    it(\"BigIntFromSelf\", async () => {\n      expectError(\n        Schema.BigIntFromSelf,\n        `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (BigIntKeyword): bigint`\n      )\n    })\n\n    it(\"UniqueSymbolFromSelf\", async () => {\n      expectError(\n        Schema.UniqueSymbolFromSelf(Symbol.for(\"effect/Schema/test/a\")),\n        `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (UniqueSymbol): Symbol(effect/Schema/test/a)`\n      )\n    })\n\n    it(\"SymbolFromSelf\", async () => {\n      expectError(\n        Schema.SymbolFromSelf,\n        `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (SymbolKeyword): symbol`\n      )\n    })\n\n    it(\"Literal(bigint)\", () => {\n      expectError(\n        Schema.Literal(1n),\n        `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (Literal): 1n`\n      )\n    })\n\n    it(\"Suspend\", () => {\n      interface A {\n        readonly a: string\n        readonly as: ReadonlyArray<A>\n      }\n      const schema = Schema.Struct({\n        a: Schema.String,\n        as: Schema.Array(Schema.suspend((): Schema.Schema<A> => schema))\n      })\n      expectError(\n        schema,\n        `Missing annotation\nat path: [\"as\"]\ndetails: Generating a JSON Schema for this schema requires an \"identifier\" annotation\nschema (Suspend): <suspended schema>`\n      )\n    })\n\n    it(\"Unsupported property signature key\", () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      expectError(\n        Schema.Struct({ [a]: Schema.String }),\n        `Unsupported key\ndetails: Cannot encode Symbol(effect/Schema/test/a) key to JSON Schema`\n      )\n    })\n\n    it(\"Unsupported index signature parameter\", () => {\n      expectError(\n        Schema.Record({ key: Schema.SymbolFromSelf, value: Schema.Number }),\n        `Missing annotation\nat path: [\"[symbol]\"]\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (SymbolKeyword): symbol`\n      )\n    })\n\n    it(\"Unsupported post-rest elements\", () => {\n      expectError(\n        Schema.Tuple([], Schema.Number, Schema.String),\n        \"Generating a JSON Schema for post-rest elements is not currently supported. You're welcome to contribute by submitting a Pull Request\"\n      )\n    })\n  })\n\n  describe(\"jsonSchema7\", () => {\n    describe(\"nullable handling\", () => {\n      it(\"Null\", async () => {\n        const schema = Schema.Null\n        await assertDraft7(schema, { \"type\": \"null\" })\n      })\n\n      it(\"NullOr(String)\", async () => {\n        const schema = Schema.NullOr(Schema.String)\n        await assertDraft7(schema, {\n          \"anyOf\": [\n            { \"type\": \"string\" },\n            { \"type\": \"null\" }\n          ]\n        })\n      })\n\n      it(\"NullOr(Any)\", async () => {\n        const schema = Schema.NullOr(Schema.Any)\n        await assertDraft7(schema, {\n          \"$id\": \"/schemas/any\",\n          \"title\": \"any\"\n        })\n      })\n\n      it(\"NullOr(Unknown)\", async () => {\n        const schema = Schema.NullOr(Schema.Unknown)\n        await assertDraft7(schema, {\n          \"$id\": \"/schemas/unknown\",\n          \"title\": \"unknown\"\n        })\n      })\n\n      it(\"NullOr(Void)\", async () => {\n        const schema = Schema.NullOr(Schema.Void)\n        await assertDraft7(schema, {\n          \"$id\": \"/schemas/void\",\n          \"title\": \"void\"\n        })\n      })\n\n      it(\"Literal | null\", async () => {\n        const schema = Schema.Literal(\"a\", null)\n        await assertDraft7(schema, {\n          \"anyOf\": [\n            {\n              \"type\": \"string\",\n              \"enum\": [\"a\"]\n            },\n            { \"type\": \"null\" }\n          ]\n        })\n      })\n\n      it(\"Literal | null(with description)\", async () => {\n        const schema = Schema.Union(Schema.Literal(\"a\"), Schema.Null.annotations({ description: \"mydescription\" }))\n        await assertDraft7(schema, {\n          \"anyOf\": [\n            {\n              \"type\": \"string\",\n              \"enum\": [\"a\"]\n            },\n            {\n              \"type\": \"null\",\n              \"description\": \"mydescription\"\n            }\n          ]\n        })\n      })\n\n      it(\"Nested nullable unions\", async () => {\n        const schema = Schema.Union(Schema.NullOr(Schema.String), Schema.Literal(\"a\", null))\n        await assertDraft7(schema, {\n          \"anyOf\": [\n            {\n              \"anyOf\": [\n                { \"type\": \"string\" },\n                { \"type\": \"null\" }\n              ]\n            },\n            {\n              \"anyOf\": [\n                { \"type\": \"string\", \"enum\": [\"a\"] },\n                { \"type\": \"null\" }\n              ]\n            }\n          ]\n        })\n      })\n    })\n\n    it(\"parseJson handling\", async () => {\n      const schema = Schema.parseJson(Schema.Struct({\n        a: Schema.parseJson(Schema.NumberFromString)\n      }))\n      await assertDraft7(\n        schema,\n        {\n          \"type\": \"object\",\n          \"required\": [\"a\"],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\",\n              \"contentMediaType\": \"application/json\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    describe(\"primitives\", () => {\n      it(\"Never\", async () => {\n        await assertDraft7(Schema.Never, {\n          \"$id\": \"/schemas/never\",\n          \"not\": {},\n          \"title\": \"never\"\n        })\n        await assertDraft7(Schema.Never.annotations({ description: \"description\" }), {\n          \"$id\": \"/schemas/never\",\n          \"not\": {},\n          \"title\": \"never\",\n          \"description\": \"description\"\n        })\n      })\n\n      it(\"Void\", async () => {\n        await assertDraft7(Schema.Void, {\n          \"$id\": \"/schemas/void\",\n          \"title\": \"void\"\n        })\n        await assertDraft7(Schema.Void.annotations({ description: \"description\" }), {\n          \"$id\": \"/schemas/void\",\n          \"title\": \"void\",\n          \"description\": \"description\"\n        })\n      })\n\n      it(\"Unknown\", async () => {\n        await assertDraft7(Schema.Unknown, {\n          \"$id\": \"/schemas/unknown\",\n          \"title\": \"unknown\"\n        })\n        await assertDraft7(Schema.Unknown.annotations({ description: \"description\" }), {\n          \"$id\": \"/schemas/unknown\",\n          \"title\": \"unknown\",\n          \"description\": \"description\"\n        })\n      })\n\n      it(\"Any\", async () => {\n        await assertDraft7(Schema.Any, {\n          \"$id\": \"/schemas/any\",\n          \"title\": \"any\"\n        })\n        await assertDraft7(Schema.Any.annotations({ description: \"description\" }), {\n          \"$id\": \"/schemas/any\",\n          \"title\": \"any\",\n          \"description\": \"description\"\n        })\n      })\n\n      it(\"Object\", async () => {\n        await assertDraft7(Schema.Object, {\n          \"$id\": \"/schemas/object\",\n          \"anyOf\": [\n            { \"type\": \"object\" },\n            { \"type\": \"array\" }\n          ],\n          \"title\": \"object\",\n          \"description\": \"an object in the TypeScript meaning, i.e. the `object` type\"\n        })\n        await assertDraft7(Schema.Object.annotations({ description: \"description\" }), {\n          \"$id\": \"/schemas/object\",\n          \"anyOf\": [\n            { \"type\": \"object\" },\n            { \"type\": \"array\" }\n          ],\n          \"title\": \"object\",\n          \"description\": \"description\"\n        })\n      })\n\n      it(\"String\", async () => {\n        const schema = Schema.String\n        await assertDraft7(schema, {\n          \"type\": \"string\"\n        })\n        await assertDraft7(schema.annotations({ description: \"description\" }), {\n          \"type\": \"string\",\n          \"description\": \"description\"\n        })\n        assertAjvDraft7Success(schema, \"a\")\n        assertAjvDraft7Failure(schema, null)\n      })\n\n      it(\"Number\", async () => {\n        await assertDraft7(Schema.Number, {\n          \"type\": \"number\"\n        })\n        await assertDraft7(Schema.Number.annotations({ description: \"description\" }), {\n          \"type\": \"number\",\n          \"description\": \"description\"\n        })\n      })\n\n      it(\"Boolean\", async () => {\n        await assertDraft7(Schema.Boolean, {\n          \"type\": \"boolean\"\n        })\n        await assertDraft7(Schema.Boolean.annotations({ description: \"description\" }), {\n          \"type\": \"boolean\",\n          \"description\": \"description\"\n        })\n      })\n    })\n\n    describe(\"Literal\", () => {\n      const schema = Schema.Literal(null)\n      it(\"null literal\", async () => {\n        await assertDraft7(schema, {\n          \"type\": \"null\"\n        })\n        await assertDraft7(schema.annotations({ description: \"description\" }), {\n          \"type\": \"null\",\n          \"description\": \"description\"\n        })\n        assertAjvDraft7Success(schema, null)\n        assertAjvDraft7Failure(schema, \"a\")\n      })\n\n      it(\"string literal\", async () => {\n        await assertDraft7(Schema.Literal(\"a\"), {\n          \"type\": \"string\",\n          \"enum\": [\"a\"]\n        })\n        await assertDraft7(Schema.Literal(\"a\").annotations({ description: \"description\" }), {\n          \"type\": \"string\",\n          \"enum\": [\"a\"],\n          \"description\": \"description\"\n        })\n      })\n\n      it(\"number literal\", async () => {\n        await assertDraft7(Schema.Literal(1), {\n          \"type\": \"number\",\n          \"enum\": [1]\n        })\n        await assertDraft7(Schema.Literal(1).annotations({ description: \"description\" }), {\n          \"type\": \"number\",\n          \"enum\": [1],\n          \"description\": \"description\"\n        })\n      })\n\n      it(\"boolean literal\", async () => {\n        await assertDraft7(Schema.Literal(true), {\n          \"type\": \"boolean\",\n          \"enum\": [true]\n        })\n        await assertDraft7(Schema.Literal(true).annotations({ description: \"description\" }), {\n          \"type\": \"boolean\",\n          \"enum\": [true],\n          \"description\": \"description\"\n        })\n      })\n    })\n\n    describe(\"Literals\", () => {\n      it(\"string literals\", async () => {\n        await assertDraft7(Schema.Literal(\"a\", \"b\"), {\n          \"type\": \"string\",\n          \"enum\": [\"a\", \"b\"]\n        })\n      })\n\n      it(\"number literals\", async () => {\n        await assertDraft7(Schema.Literal(1, 2), {\n          \"type\": \"number\",\n          \"enum\": [1, 2]\n        })\n      })\n\n      it(\"boolean literals\", async () => {\n        await assertDraft7(Schema.Literal(true, false), {\n          \"type\": \"boolean\",\n          \"enum\": [true, false]\n        })\n      })\n\n      it(\"mixed literals\", async () => {\n        await assertDraft7(Schema.Literal(1, \"a\", true), {\n          \"anyOf\": [\n            { \"type\": \"number\", \"enum\": [1] },\n            { \"type\": \"string\", \"enum\": [\"a\"] },\n            { \"type\": \"boolean\", \"enum\": [true] }\n          ]\n        })\n        await assertDraft7(Schema.Literal(\"a\", \"b\", 1), {\n          \"anyOf\": [\n            { \"type\": \"string\", \"enum\": [\"a\", \"b\"] },\n            { \"type\": \"number\", \"enum\": [1] }\n          ]\n        })\n        await assertDraft7(Schema.Literal(\"a\", 1, \"b\"), {\n          \"anyOf\": [\n            { \"type\": \"string\", \"enum\": [\"a\"] },\n            { \"type\": \"number\", \"enum\": [1] },\n            { \"type\": \"string\", \"enum\": [\"b\"] }\n          ]\n        })\n      })\n    })\n\n    describe(\"Enums\", () => {\n      it(\"empty enum\", async () => {\n        enum Empty {}\n        await assertDraft7(Schema.Enums(Empty), {\n          \"$id\": \"/schemas/never\",\n          \"not\": {}\n        })\n        await assertDraft7(Schema.Enums(Empty).annotations({ description: \"description\" }), {\n          \"$id\": \"/schemas/never\",\n          \"not\": {},\n          \"description\": \"description\"\n        })\n      })\n\n      it(\"single enum\", async () => {\n        enum Fruits {\n          Apple\n        }\n        await assertDraft7(Schema.Enums(Fruits), {\n          \"$comment\": \"/schemas/enums\",\n          \"anyOf\": [\n            { \"type\": \"number\", \"title\": \"Apple\", \"enum\": [0] }\n          ]\n        })\n        await assertDraft7(Schema.Enums(Fruits).annotations({ description: \"description\" }), {\n          \"$comment\": \"/schemas/enums\",\n          \"anyOf\": [\n            { \"type\": \"number\", \"title\": \"Apple\", \"enum\": [0] }\n          ],\n          \"description\": \"description\"\n        })\n      })\n\n      it(\"numeric enums\", async () => {\n        enum Fruits {\n          Apple,\n          Banana\n        }\n        await assertDraft7(Schema.Enums(Fruits), {\n          \"$comment\": \"/schemas/enums\",\n          \"anyOf\": [\n            { \"type\": \"number\", \"title\": \"Apple\", \"enum\": [0] },\n            { \"type\": \"number\", \"title\": \"Banana\", \"enum\": [1] }\n          ]\n        })\n      })\n\n      it(\"string enums\", async () => {\n        enum Fruits {\n          Apple = \"apple\",\n          Banana = \"banana\"\n        }\n        await assertDraft7(Schema.Enums(Fruits), {\n          \"$comment\": \"/schemas/enums\",\n          \"anyOf\": [\n            { \"type\": \"string\", \"title\": \"Apple\", \"enum\": [\"apple\"] },\n            { \"type\": \"string\", \"title\": \"Banana\", \"enum\": [\"banana\"] }\n          ]\n        })\n      })\n\n      it(\"mix of string/number enums\", async () => {\n        enum Fruits {\n          Apple = \"apple\",\n          Banana = \"banana\",\n          Cantaloupe = 0\n        }\n        await assertDraft7(Schema.Enums(Fruits), {\n          \"$comment\": \"/schemas/enums\",\n          \"anyOf\": [\n            { \"type\": \"string\", \"title\": \"Apple\", \"enum\": [\"apple\"] },\n            { \"type\": \"string\", \"title\": \"Banana\", \"enum\": [\"banana\"] },\n            { \"type\": \"number\", \"title\": \"Cantaloupe\", \"enum\": [0] }\n          ]\n        })\n      })\n\n      it(\"const enums\", async () => {\n        const Fruits = {\n          Apple: \"apple\",\n          Banana: \"banana\",\n          Cantaloupe: 3\n        } as const\n        await assertDraft7(Schema.Enums(Fruits), {\n          \"$comment\": \"/schemas/enums\",\n          \"anyOf\": [\n            { \"type\": \"string\", \"title\": \"Apple\", \"enum\": [\"apple\"] },\n            { \"type\": \"string\", \"title\": \"Banana\", \"enum\": [\"banana\"] },\n            { \"type\": \"number\", \"title\": \"Cantaloupe\", \"enum\": [3] }\n          ]\n        })\n      })\n    })\n\n    it(\"TemplateLiteral\", async () => {\n      const schema = Schema.TemplateLiteral(Schema.Literal(\"a\"), Schema.Number)\n      await assertDraft7(schema, {\n        \"type\": \"string\",\n        \"pattern\": \"^a[+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?$\",\n        \"title\": \"`a${number}`\",\n        \"description\": \"a template literal\"\n      })\n    })\n\n    describe(\"Refinement\", () => {\n      it(\"itemsCount (Array)\", async () => {\n        await assertDraft7(Schema.Array(Schema.String).pipe(Schema.itemsCount(2)), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"description\": \"an array of exactly 2 item(s)\",\n          \"title\": \"itemsCount(2)\",\n          \"minItems\": 2,\n          \"maxItems\": 2\n        })\n      })\n\n      it(\"itemsCount (NonEmptyArray)\", async () => {\n        await assertDraft7(Schema.NonEmptyArray(Schema.String).pipe(Schema.itemsCount(2)), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"description\": \"an array of exactly 2 item(s)\",\n          \"title\": \"itemsCount(2)\",\n          \"minItems\": 2,\n          \"maxItems\": 2\n        })\n      })\n\n      it(\"minItems (Array)\", async () => {\n        await assertDraft7(Schema.Array(Schema.String).pipe(Schema.minItems(2)), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"description\": \"an array of at least 2 item(s)\",\n          \"title\": \"minItems(2)\",\n          \"minItems\": 2\n        })\n      })\n\n      it(\"minItems (NonEmptyArray)\", async () => {\n        await assertDraft7(Schema.NonEmptyArray(Schema.String).pipe(Schema.minItems(2)), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"description\": \"an array of at least 2 item(s)\",\n          \"title\": \"minItems(2)\",\n          \"minItems\": 2\n        })\n      })\n\n      it(\"maxItems (Array)\", async () => {\n        await assertDraft7(Schema.Array(Schema.String).pipe(Schema.maxItems(2)), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"description\": \"an array of at most 2 item(s)\",\n          \"title\": \"maxItems(2)\",\n          \"maxItems\": 2\n        })\n      })\n\n      it(\"maxItems (NonEmptyArray)\", async () => {\n        await assertDraft7(Schema.NonEmptyArray(Schema.String).pipe(Schema.maxItems(2)), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"description\": \"an array of at most 2 item(s)\",\n          \"title\": \"maxItems(2)\",\n          \"minItems\": 1,\n          \"maxItems\": 2\n        })\n      })\n\n      it(\"minLength\", async () => {\n        await assertDraft7(Schema.String.pipe(Schema.minLength(1)), {\n          \"type\": \"string\",\n          \"title\": \"minLength(1)\",\n          \"description\": \"a string at least 1 character(s) long\",\n          \"minLength\": 1\n        })\n      })\n\n      it(\"maxLength\", async () => {\n        await assertDraft7(Schema.String.pipe(Schema.maxLength(1)), {\n          \"type\": \"string\",\n          \"title\": \"maxLength(1)\",\n          \"description\": \"a string at most 1 character(s) long\",\n          \"maxLength\": 1\n        })\n      })\n\n      it(\"length: number\", async () => {\n        await assertDraft7(Schema.String.pipe(Schema.length(1)), {\n          \"type\": \"string\",\n          \"title\": \"length(1)\",\n          \"description\": \"a single character\",\n          \"maxLength\": 1,\n          \"minLength\": 1\n        })\n      })\n\n      it(\"length: { min, max }\", async () => {\n        await assertDraft7(Schema.String.pipe(Schema.length({ min: 2, max: 4 })), {\n          \"type\": \"string\",\n          \"title\": \"length({ min: 2, max: 4)\",\n          \"description\": \"a string at least 2 character(s) and at most 4 character(s) long\",\n          \"maxLength\": 4,\n          \"minLength\": 2\n        })\n      })\n\n      it(\"greaterThan\", async () => {\n        await assertDraft7(Schema.Number.pipe(Schema.greaterThan(1)), {\n          \"type\": \"number\",\n          \"title\": \"greaterThan(1)\",\n          \"description\": \"a number greater than 1\",\n          \"exclusiveMinimum\": 1\n        })\n      })\n\n      it(\"greaterThanOrEqualTo\", async () => {\n        await assertDraft7(Schema.Number.pipe(Schema.greaterThanOrEqualTo(1)), {\n          \"type\": \"number\",\n          \"title\": \"greaterThanOrEqualTo(1)\",\n          \"description\": \"a number greater than or equal to 1\",\n          \"minimum\": 1\n        })\n      })\n\n      it(\"lessThan\", async () => {\n        await assertDraft7(Schema.Number.pipe(Schema.lessThan(1)), {\n          \"type\": \"number\",\n          \"title\": \"lessThan(1)\",\n          \"description\": \"a number less than 1\",\n          \"exclusiveMaximum\": 1\n        })\n      })\n\n      it(\"lessThanOrEqualTo\", async () => {\n        await assertDraft7(Schema.Number.pipe(Schema.lessThanOrEqualTo(1)), {\n          \"type\": \"number\",\n          \"title\": \"lessThanOrEqualTo(1)\",\n          \"description\": \"a number less than or equal to 1\",\n          \"maximum\": 1\n        })\n      })\n\n      it(\"pattern\", async () => {\n        await assertDraft7(Schema.String.pipe(Schema.pattern(/^abb+$/)), {\n          \"type\": \"string\",\n          \"description\": \"a string matching the pattern ^abb+$\",\n          \"pattern\": \"^abb+$\"\n        })\n      })\n\n      it(\"int\", async () => {\n        await assertDraft7(Schema.Number.pipe(Schema.int()), {\n          \"type\": \"integer\",\n          \"title\": \"int\",\n          \"description\": \"an integer\"\n        })\n      })\n\n      it(\"Trimmed\", async () => {\n        const schema = Schema.Trimmed\n        await assertDraft7(schema, {\n          \"$defs\": {\n            \"Trimmed\": {\n              \"title\": \"trimmed\",\n              \"description\": \"a string with no leading or trailing whitespace\",\n              \"pattern\": \"^\\\\S[\\\\s\\\\S]*\\\\S$|^\\\\S$|^$\",\n              \"type\": \"string\"\n            }\n          },\n          \"$ref\": \"#/$defs/Trimmed\"\n        })\n      })\n\n      it(\"Lowercased\", async () => {\n        const schema = Schema.Lowercased\n        await assertDraft7(schema, {\n          \"$defs\": {\n            \"Lowercased\": {\n              \"title\": \"lowercased\",\n              \"description\": \"a lowercase string\",\n              \"pattern\": \"^[^A-Z]*$\",\n              \"type\": \"string\"\n            }\n          },\n          \"$ref\": \"#/$defs/Lowercased\"\n        })\n      })\n\n      it(\"Uppercased\", async () => {\n        const schema = Schema.Uppercased\n        await assertDraft7(schema, {\n          \"$defs\": {\n            \"Uppercased\": {\n              \"title\": \"uppercased\",\n              \"description\": \"an uppercase string\",\n              \"pattern\": \"^[^a-z]*$\",\n              \"type\": \"string\"\n            }\n          },\n          \"$ref\": \"#/$defs/Uppercased\"\n        })\n      })\n\n      it(\"Capitalized\", async () => {\n        const schema = Schema.Capitalized\n        await assertDraft7(schema, {\n          \"$defs\": {\n            \"Capitalized\": {\n              \"title\": \"capitalized\",\n              \"description\": \"a capitalized string\",\n              \"pattern\": \"^[^a-z]?.*$\",\n              \"type\": \"string\"\n            }\n          },\n          \"$ref\": \"#/$defs/Capitalized\"\n        })\n      })\n\n      it(\"Uncapitalized\", async () => {\n        const schema = Schema.Uncapitalized\n        await assertDraft7(schema, {\n          \"$defs\": {\n            \"Uncapitalized\": {\n              \"title\": \"uncapitalized\",\n              \"description\": \"a uncapitalized string\",\n              \"pattern\": \"^[^A-Z]?.*$\",\n              \"type\": \"string\"\n            }\n          },\n          \"$ref\": \"#/$defs/Uncapitalized\"\n        })\n      })\n\n      describe(\"should handle merge conflicts\", () => {\n        it(\"minLength + minLength\", async () => {\n          await assertDraft7(Schema.String.pipe(Schema.minLength(1), Schema.minLength(2)), {\n            \"type\": \"string\",\n            \"title\": \"minLength(2)\",\n            \"description\": \"a string at least 2 character(s) long\",\n            \"minLength\": 2\n          })\n          await assertDraft7(Schema.String.pipe(Schema.minLength(2), Schema.minLength(1)), {\n            \"type\": \"string\",\n            \"title\": \"minLength(1)\",\n            \"description\": \"a string at least 1 character(s) long\",\n            \"minLength\": 1,\n            \"allOf\": [\n              { \"minLength\": 2 }\n            ]\n          })\n          await assertDraft7(Schema.String.pipe(Schema.minLength(2), Schema.minLength(1), Schema.minLength(2)), {\n            \"type\": \"string\",\n            \"title\": \"minLength(2)\",\n            \"description\": \"a string at least 2 character(s) long\",\n            \"minLength\": 2\n          })\n        })\n\n        it(\"maxLength + maxLength\", async () => {\n          await assertDraft7(Schema.String.pipe(Schema.maxLength(1), Schema.maxLength(2)), {\n            \"type\": \"string\",\n            \"title\": \"maxLength(2)\",\n            \"description\": \"a string at most 2 character(s) long\",\n            \"maxLength\": 2,\n            \"allOf\": [\n              { \"maxLength\": 1 }\n            ]\n          })\n          await assertDraft7(Schema.String.pipe(Schema.maxLength(2), Schema.maxLength(1)), {\n            \"type\": \"string\",\n            \"title\": \"maxLength(1)\",\n            \"description\": \"a string at most 1 character(s) long\",\n            \"maxLength\": 1\n          })\n          await assertDraft7(Schema.String.pipe(Schema.maxLength(1), Schema.maxLength(2), Schema.maxLength(1)), {\n            \"type\": \"string\",\n            \"title\": \"maxLength(1)\",\n            \"description\": \"a string at most 1 character(s) long\",\n            \"maxLength\": 1\n          })\n        })\n\n        it(\"pattern + pattern\", async () => {\n          await assertDraft7(Schema.String.pipe(Schema.startsWith(\"a\"), Schema.endsWith(\"c\")), {\n            \"type\": \"string\",\n            \"title\": \"endsWith(\\\"c\\\")\",\n            \"description\": \"a string ending with \\\"c\\\"\",\n            \"pattern\": \"^.*c$\",\n            \"allOf\": [\n              { \"pattern\": \"^a\" }\n            ]\n          })\n          await assertDraft7(\n            Schema.String.pipe(Schema.startsWith(\"a\"), Schema.endsWith(\"c\"), Schema.startsWith(\"a\")),\n            {\n              \"type\": \"string\",\n              \"title\": \"startsWith(\\\"a\\\")\",\n              \"description\": \"a string starting with \\\"a\\\"\",\n              \"pattern\": \"^a\",\n              \"allOf\": [\n                { \"pattern\": \"^.*c$\" }\n              ]\n            }\n          )\n          await assertDraft7(\n            Schema.String.pipe(Schema.endsWith(\"c\"), Schema.startsWith(\"a\"), Schema.endsWith(\"c\")),\n            {\n              \"type\": \"string\",\n              \"title\": \"endsWith(\\\"c\\\")\",\n              \"description\": \"a string ending with \\\"c\\\"\",\n              \"pattern\": \"^.*c$\",\n              \"allOf\": [\n                { \"pattern\": \"^a\" }\n              ]\n            }\n          )\n        })\n\n        it(\"minItems + minItems\", async () => {\n          await assertDraft7(Schema.Array(Schema.String).pipe(Schema.minItems(1), Schema.minItems(2)), {\n            \"type\": \"array\",\n            \"items\": {\n              \"type\": \"string\"\n            },\n            \"description\": \"an array of at least 2 item(s)\",\n            \"title\": \"minItems(2)\",\n            \"minItems\": 2\n          })\n          await assertDraft7(Schema.Array(Schema.String).pipe(Schema.minItems(2), Schema.minItems(1)), {\n            \"type\": \"array\",\n            \"items\": {\n              \"type\": \"string\"\n            },\n            \"title\": \"minItems(1)\",\n            \"description\": \"an array of at least 1 item(s)\",\n            \"minItems\": 1,\n            \"allOf\": [\n              { \"minItems\": 2 }\n            ]\n          })\n          await assertDraft7(\n            Schema.Array(Schema.String).pipe(Schema.minItems(2), Schema.minItems(1), Schema.minItems(2)),\n            {\n              \"type\": \"array\",\n              \"items\": {\n                \"type\": \"string\"\n              },\n              \"description\": \"an array of at least 2 item(s)\",\n              \"title\": \"minItems(2)\",\n              \"minItems\": 2\n            }\n          )\n        })\n\n        it(\"maxItems + maxItems\", async () => {\n          await assertDraft7(Schema.Array(Schema.String).pipe(Schema.maxItems(1), Schema.maxItems(2)), {\n            \"type\": \"array\",\n            \"items\": {\n              \"type\": \"string\"\n            },\n            \"title\": \"maxItems(2)\",\n            \"description\": \"an array of at most 2 item(s)\",\n            \"maxItems\": 2,\n            \"allOf\": [\n              { \"maxItems\": 1 }\n            ]\n          })\n          await assertDraft7(Schema.Array(Schema.String).pipe(Schema.maxItems(2), Schema.maxItems(1)), {\n            \"type\": \"array\",\n            \"items\": {\n              \"type\": \"string\"\n            },\n            \"title\": \"maxItems(1)\",\n            \"description\": \"an array of at most 1 item(s)\",\n            \"maxItems\": 1\n          })\n          await assertDraft7(\n            Schema.Array(Schema.String).pipe(Schema.maxItems(1), Schema.maxItems(2), Schema.maxItems(1)),\n            {\n              \"type\": \"array\",\n              \"items\": {\n                \"type\": \"string\"\n              },\n              \"title\": \"maxItems(1)\",\n              \"description\": \"an array of at most 1 item(s)\",\n              \"maxItems\": 1\n            }\n          )\n        })\n\n        it(\"minimum + minimum\", async () => {\n          await assertDraft7(Schema.Number.pipe(Schema.greaterThanOrEqualTo(1), Schema.greaterThanOrEqualTo(2)), {\n            \"type\": \"number\",\n            \"title\": \"greaterThanOrEqualTo(2)\",\n            \"description\": \"a number greater than or equal to 2\",\n            \"minimum\": 2\n          })\n          await assertDraft7(Schema.Number.pipe(Schema.greaterThanOrEqualTo(2), Schema.greaterThanOrEqualTo(1)), {\n            \"type\": \"number\",\n            \"minimum\": 1,\n            \"title\": \"greaterThanOrEqualTo(1)\",\n            \"description\": \"a number greater than or equal to 1\",\n            \"allOf\": [\n              { \"minimum\": 2 }\n            ]\n          })\n          await assertDraft7(\n            Schema.Number.pipe(\n              Schema.greaterThanOrEqualTo(2),\n              Schema.greaterThanOrEqualTo(1),\n              Schema.greaterThanOrEqualTo(2)\n            ),\n            {\n              \"type\": \"number\",\n              \"title\": \"greaterThanOrEqualTo(2)\",\n              \"description\": \"a number greater than or equal to 2\",\n              \"minimum\": 2\n            }\n          )\n        })\n\n        it(\"maximum + maximum\", async () => {\n          await assertDraft7(Schema.Number.pipe(Schema.lessThanOrEqualTo(1), Schema.lessThanOrEqualTo(2)), {\n            \"type\": \"number\",\n            \"title\": \"lessThanOrEqualTo(2)\",\n            \"description\": \"a number less than or equal to 2\",\n            \"maximum\": 2,\n            \"allOf\": [\n              { \"maximum\": 1 }\n            ]\n          })\n          await assertDraft7(Schema.Number.pipe(Schema.lessThanOrEqualTo(2), Schema.lessThanOrEqualTo(1)), {\n            \"type\": \"number\",\n            \"title\": \"lessThanOrEqualTo(1)\",\n            \"description\": \"a number less than or equal to 1\",\n            \"maximum\": 1\n          })\n          await assertDraft7(\n            Schema.Number.pipe(Schema.lessThanOrEqualTo(1), Schema.lessThanOrEqualTo(2), Schema.lessThanOrEqualTo(1)),\n            {\n              \"type\": \"number\",\n              \"title\": \"lessThanOrEqualTo(1)\",\n              \"description\": \"a number less than or equal to 1\",\n              \"maximum\": 1\n            }\n          )\n        })\n\n        it(\"exclusiveMinimum + exclusiveMinimum\", async () => {\n          await assertDraft7(Schema.Number.pipe(Schema.greaterThan(1), Schema.greaterThan(2)), {\n            \"type\": \"number\",\n            \"title\": \"greaterThan(2)\",\n            \"description\": \"a number greater than 2\",\n            \"exclusiveMinimum\": 2\n          })\n          await assertDraft7(Schema.Number.pipe(Schema.greaterThan(2), Schema.greaterThan(1)), {\n            \"type\": \"number\",\n            \"exclusiveMinimum\": 1,\n            \"title\": \"greaterThan(1)\",\n            \"description\": \"a number greater than 1\",\n            \"allOf\": [\n              { \"exclusiveMinimum\": 2 }\n            ]\n          })\n          await assertDraft7(\n            Schema.Number.pipe(\n              Schema.greaterThan(2),\n              Schema.greaterThan(1),\n              Schema.greaterThan(2)\n            ),\n            {\n              \"type\": \"number\",\n              \"title\": \"greaterThan(2)\",\n              \"description\": \"a number greater than 2\",\n              \"exclusiveMinimum\": 2\n            }\n          )\n        })\n\n        it(\"exclusiveMaximum + exclusiveMaximum\", async () => {\n          await assertDraft7(Schema.Number.pipe(Schema.lessThan(1), Schema.lessThan(2)), {\n            \"type\": \"number\",\n            \"title\": \"lessThan(2)\",\n            \"description\": \"a number less than 2\",\n            \"exclusiveMaximum\": 2,\n            \"allOf\": [\n              { \"exclusiveMaximum\": 1 }\n            ]\n          })\n          await assertDraft7(Schema.Number.pipe(Schema.lessThan(2), Schema.lessThan(1)), {\n            \"type\": \"number\",\n            \"title\": \"lessThan(1)\",\n            \"description\": \"a number less than 1\",\n            \"exclusiveMaximum\": 1\n          })\n          await assertDraft7(\n            Schema.Number.pipe(Schema.lessThan(1), Schema.lessThan(2), Schema.lessThan(1)),\n            {\n              \"type\": \"number\",\n              \"title\": \"lessThan(1)\",\n              \"description\": \"a number less than 1\",\n              \"exclusiveMaximum\": 1\n            }\n          )\n        })\n\n        it(\"multipleOf + multipleOf\", async () => {\n          await assertDraft7(Schema.Number.pipe(Schema.multipleOf(2), Schema.multipleOf(3)), {\n            \"type\": \"number\",\n            \"title\": \"multipleOf(3)\",\n            \"description\": \"a number divisible by 3\",\n            \"multipleOf\": 3,\n            \"allOf\": [\n              { \"multipleOf\": 2 }\n            ]\n          })\n          await assertDraft7(\n            Schema.Number.pipe(Schema.multipleOf(2), Schema.multipleOf(3), Schema.multipleOf(3)),\n            {\n              \"type\": \"number\",\n              \"title\": \"multipleOf(3)\",\n              \"description\": \"a number divisible by 3\",\n              \"multipleOf\": 3,\n              \"allOf\": [\n                { \"multipleOf\": 2 }\n              ]\n            }\n          )\n          await assertDraft7(\n            Schema.Number.pipe(Schema.multipleOf(3), Schema.multipleOf(2), Schema.multipleOf(3)),\n            {\n              \"type\": \"number\",\n              \"title\": \"multipleOf(3)\",\n              \"description\": \"a number divisible by 3\",\n              \"multipleOf\": 3,\n              \"allOf\": [\n                { \"multipleOf\": 2 }\n              ]\n            }\n          )\n        })\n      })\n    })\n\n    describe(\"Tuple\", () => {\n      it(\"empty tuple\", async () => {\n        const schema = Schema.Tuple()\n        await assertDraft7(schema, {\n          \"type\": \"array\",\n          \"maxItems\": 0\n        })\n      })\n\n      it(\"element\", async () => {\n        const schema = Schema.Tuple(Schema.Number)\n        await assertDraft7(schema, {\n          \"type\": \"array\",\n          \"items\": [{\n            \"type\": \"number\"\n          }],\n          \"minItems\": 1,\n          \"additionalItems\": false\n        })\n      })\n\n      it(\"element + inner annotations\", async () => {\n        await assertDraft7(\n          Schema.Tuple(Schema.Number.annotations({ description: \"inner\" })),\n          {\n            \"type\": \"array\",\n            \"items\": [{\n              \"type\": \"number\",\n              \"description\": \"inner\"\n            }],\n            \"minItems\": 1,\n            \"additionalItems\": false\n          }\n        )\n      })\n\n      it(\"element + outer annotations should override inner annotations\", async () => {\n        await assertDraft7(\n          Schema.Tuple(\n            Schema.element(Schema.Number.annotations({ description: \"inner\" })).annotations({ description: \"outer\" })\n          ),\n          {\n            \"type\": \"array\",\n            \"items\": [{\n              \"type\": \"number\",\n              \"description\": \"outer\"\n            }],\n            \"minItems\": 1,\n            \"additionalItems\": false\n          }\n        )\n      })\n\n      it(\"optionalElement\", async () => {\n        const schema = Schema.Tuple(Schema.optionalElement(Schema.Number))\n        await assertDraft7(schema, {\n          \"type\": \"array\",\n          \"minItems\": 0,\n          \"items\": [\n            {\n              \"type\": \"number\"\n            }\n          ],\n          \"additionalItems\": false\n        })\n      })\n\n      it(\"optionalElement + inner annotations\", async () => {\n        await assertDraft7(\n          Schema.Tuple(Schema.optionalElement(Schema.Number).annotations({ description: \"inner\" })),\n          {\n            \"type\": \"array\",\n            \"minItems\": 0,\n            \"items\": [\n              {\n                \"type\": \"number\",\n                \"description\": \"inner\"\n              }\n            ],\n            \"additionalItems\": false\n          }\n        )\n      })\n\n      it(\"optionalElement + outer annotations should override inner annotations\", async () => {\n        await assertDraft7(\n          Schema.Tuple(\n            Schema.optionalElement(Schema.Number).annotations({ description: \"inner\" }).annotations({\n              description: \"outer\"\n            })\n          ),\n          {\n            \"type\": \"array\",\n            \"minItems\": 0,\n            \"items\": [\n              {\n                \"type\": \"number\",\n                \"description\": \"outer\"\n              }\n            ],\n            \"additionalItems\": false\n          }\n        )\n      })\n\n      it(\"element + optionalElement\", async () => {\n        const schema = Schema.Tuple(\n          Schema.element(Schema.String.annotations({ description: \"inner\" })).annotations({ description: \"outer\" }),\n          Schema.optionalElement(Schema.Number.annotations({ description: \"inner?\" })).annotations({\n            description: \"outer?\"\n          })\n        )\n        await assertDraft7(schema, {\n          \"type\": \"array\",\n          \"minItems\": 1,\n          \"items\": [\n            {\n              \"type\": \"string\",\n              \"description\": \"outer\"\n            },\n            {\n              \"type\": \"number\",\n              \"description\": \"outer?\"\n            }\n          ],\n          \"additionalItems\": false\n        })\n      })\n\n      it(\"rest\", async () => {\n        const schema = Schema.Array(Schema.Number)\n        await assertDraft7(schema, {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"number\"\n          }\n        })\n      })\n\n      it(\"rest + inner annotations\", async () => {\n        await assertDraft7(Schema.Array(Schema.Number.annotations({ description: \"inner\" })), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"number\",\n            \"description\": \"inner\"\n          }\n        })\n      })\n\n      it(\"optionalElement + rest + inner annotations\", async () => {\n        const schema = Schema.Tuple(\n          [Schema.optionalElement(Schema.String)],\n          Schema.element(Schema.Number.annotations({ description: \"inner\" }))\n        )\n        await assertDraft7(schema, {\n          \"type\": \"array\",\n          \"minItems\": 0,\n          \"items\": [\n            {\n              \"type\": \"string\"\n            }\n          ],\n          \"additionalItems\": {\n            \"type\": \"number\",\n            \"description\": \"inner\"\n          }\n        })\n      })\n\n      it(\"optionalElement + rest + outer annotations should override inner annotations\", async () => {\n        await assertDraft7(\n          Schema.Tuple(\n            [Schema.optionalElement(Schema.String)],\n            Schema.element(Schema.Number.annotations({ description: \"inner\" })).annotations({ description: \"outer\" })\n          ),\n          {\n            \"type\": \"array\",\n            \"minItems\": 0,\n            \"items\": [\n              {\n                \"type\": \"string\"\n              }\n            ],\n            \"additionalItems\": {\n              \"type\": \"number\",\n              \"description\": \"outer\"\n            }\n          }\n        )\n      })\n\n      it(\"element + rest\", async () => {\n        const schema = Schema.Tuple([Schema.String], Schema.Number)\n        await assertDraft7(schema, {\n          \"type\": \"array\",\n          \"items\": [{\n            \"type\": \"string\"\n          }],\n          \"minItems\": 1,\n          \"additionalItems\": {\n            \"type\": \"number\"\n          }\n        })\n      })\n\n      it(\"NonEmptyArray\", async () => {\n        await assertDraft7(\n          Schema.NonEmptyArray(Schema.String),\n          {\n            type: \"array\",\n            minItems: 1,\n            items: { type: \"string\" }\n          }\n        )\n      })\n    })\n\n    describe(\"Struct\", () => {\n      it(\"empty struct: Schema.Struct({})\", async () => {\n        const schema = Schema.Struct({})\n        await assertDraft7(schema, {\n          \"$id\": \"/schemas/%7B%7D\",\n          \"anyOf\": [{\n            \"type\": \"object\"\n          }, {\n            \"type\": \"array\"\n          }]\n        })\n      })\n\n      it(\"required property signatures\", async () => {\n        const schema = Schema.Struct({\n          a: Schema.String,\n          b: Schema.String.annotations({ description: \"b-inner\" }),\n          c: Schema.propertySignature(Schema.String).annotations({ description: \"c-outer\" }),\n          d: Schema.propertySignature(Schema.String.annotations({ description: \"d-inner\" })).annotations({\n            description: \"d-outer\"\n          })\n        })\n        await assertDraft7(schema, {\n          \"type\": \"object\",\n          \"properties\": {\n            \"a\": { \"type\": \"string\" },\n            \"b\": { \"type\": \"string\", \"description\": \"b-inner\" },\n            \"c\": { \"type\": \"string\", \"description\": \"c-outer\" },\n            \"d\": { \"type\": \"string\", \"description\": \"d-outer\" }\n          },\n          \"required\": [\"a\", \"b\", \"c\", \"d\"],\n          \"additionalProperties\": false\n        })\n      })\n\n      it(\"optional\", async () => {\n        const schema = Schema.Struct({\n          a: Schema.optional(Schema.String),\n          b: Schema.optional(Schema.String.annotations({ description: \"b-inner\" })),\n          c: Schema.optional(Schema.String).annotations({ description: \"c-outer\" }),\n          d: Schema.optional(Schema.String.annotations({ description: \"d-inner\" })).annotations({\n            description: \"d-outer\"\n          }),\n          e: Schema.optional(Schema.UndefinedOr(Schema.String))\n        })\n        await assertDraft7(schema, {\n          \"type\": \"object\",\n          \"properties\": {\n            \"a\": { \"type\": \"string\" },\n            \"b\": { \"type\": \"string\", \"description\": \"b-inner\" },\n            \"c\": { \"type\": \"string\", \"description\": \"c-outer\" },\n            \"d\": { \"type\": \"string\", \"description\": \"d-outer\" },\n            \"e\": { \"type\": \"string\" }\n          },\n          \"required\": [],\n          \"additionalProperties\": false\n        })\n      })\n\n      describe(\"optionalWith\", () => {\n        it(\"{ nullable: true }\", async () => {\n          const schema = Schema.Struct({\n            a: Schema.optionalWith(Schema.String, { nullable: true }),\n            b: Schema.optionalWith(Schema.String.annotations({ description: \"b-inner\" }), { nullable: true }),\n            c: Schema.optionalWith(Schema.String, { nullable: true }).annotations({ description: \"c-outer\" }),\n            d: Schema.optionalWith(Schema.String.annotations({ description: \"d-inner\" }), { nullable: true })\n              .annotations({\n                description: \"d-outer\"\n              }),\n            e: Schema.optionalWith(Schema.UndefinedOr(Schema.String), { nullable: true })\n          })\n          await assertDraft7(schema, {\n            \"type\": \"object\",\n            \"properties\": {\n              \"a\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }] },\n              \"b\": {\n                \"anyOf\": [{ \"type\": \"string\", \"description\": \"b-inner\" }, { \"type\": \"null\" }],\n                \"description\": \"b-inner\"\n              },\n              \"c\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }], \"description\": \"c-outer\" },\n              \"d\": {\n                \"anyOf\": [{ \"type\": \"string\", \"description\": \"d-inner\" }, { \"type\": \"null\" }],\n                \"description\": \"d-outer\"\n              },\n              \"e\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }] }\n            },\n            \"required\": [],\n            \"additionalProperties\": false\n          })\n        })\n\n        it(\"{ exact: true }\", async () => {\n          const schema = Schema.Struct({\n            a: Schema.optionalWith(Schema.String, { exact: true }),\n            b: Schema.optionalWith(Schema.String.annotations({ description: \"b-inner\" }), { exact: true }),\n            c: Schema.optionalWith(Schema.String, { exact: true }).annotations({ description: \"c-outer\" }),\n            d: Schema.optionalWith(Schema.String.annotations({ description: \"d-inner\" }), { exact: true }).annotations({\n              description: \"d-outer\"\n            }),\n            e: Schema.optionalWith(Schema.UndefinedOr(Schema.String), { exact: true })\n          })\n          await assertDraft7(schema, {\n            \"type\": \"object\",\n            \"properties\": {\n              \"a\": { \"type\": \"string\" },\n              \"b\": { \"type\": \"string\", \"description\": \"b-inner\" },\n              \"c\": { \"type\": \"string\", \"description\": \"c-outer\" },\n              \"d\": { \"type\": \"string\", \"description\": \"d-outer\" },\n              \"e\": { \"type\": \"string\" }\n            },\n            \"required\": [],\n            \"additionalProperties\": false\n          })\n        })\n\n        it(\"{ exact: true, nullable: true }\", async () => {\n          const schema = Schema.Struct({\n            a: Schema.optionalWith(Schema.String, { exact: true, nullable: true }),\n            b: Schema.optionalWith(Schema.String.annotations({ description: \"b-inner\" }), {\n              exact: true,\n              nullable: true\n            }),\n            c: Schema.optionalWith(Schema.String, { exact: true, nullable: true }).annotations({\n              description: \"c-outer\"\n            }),\n            d: Schema.optionalWith(Schema.String.annotations({ description: \"d-inner\" }), {\n              exact: true,\n              nullable: true\n            }).annotations({\n              description: \"d-outer\"\n            }),\n            e: Schema.optionalWith(Schema.UndefinedOr(Schema.String), { exact: true, nullable: true })\n          })\n          await assertDraft7(schema, {\n            \"type\": \"object\",\n            \"properties\": {\n              \"a\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }] },\n              \"b\": {\n                \"anyOf\": [{ \"type\": \"string\", \"description\": \"b-inner\" }, { \"type\": \"null\" }],\n                \"description\": \"b-inner\"\n              },\n              \"c\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }], \"description\": \"c-outer\" },\n              \"d\": {\n                \"anyOf\": [{ \"type\": \"string\", \"description\": \"d-inner\" }, { \"type\": \"null\" }],\n                \"description\": \"d-outer\"\n              },\n              \"e\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }] }\n            },\n            \"required\": [],\n            \"additionalProperties\": false\n          })\n        })\n\n        it(\"{ default }\", async () => {\n          const schema = Schema.Struct({\n            a: Schema.optionalWith(Schema.String, { default: () => \"\" }),\n            b: Schema.optionalWith(Schema.String.annotations({ description: \"b-inner\" }), { default: () => \"\" }),\n            c: Schema.optionalWith(Schema.String, { default: () => \"\" }).annotations({ description: \"c-outer\" }),\n            d: Schema.optionalWith(Schema.String.annotations({ description: \"d-inner\" }), { default: () => \"\" })\n              .annotations({ description: \"d-outer\" }),\n            e: Schema.optionalWith(Schema.UndefinedOr(Schema.String), { default: () => \"\" })\n          })\n          await assertDraft7(schema, {\n            \"type\": \"object\",\n            \"properties\": {\n              \"a\": { \"type\": \"string\" },\n              \"b\": { \"type\": \"string\", \"description\": \"b-inner\" },\n              \"c\": { \"type\": \"string\", \"description\": \"c-outer\" },\n              \"d\": { \"type\": \"string\", \"description\": \"d-outer\" },\n              \"e\": { \"type\": \"string\" }\n            },\n            \"required\": [],\n            \"additionalProperties\": false\n          })\n        })\n\n        it(\"{ default, nullable: true }\", async () => {\n          const schema = Schema.Struct({\n            a: Schema.optionalWith(Schema.String, { default: () => \"\", nullable: true }),\n            b: Schema.optionalWith(Schema.String.annotations({ description: \"b-inner\" }), {\n              default: () => \"\",\n              nullable: true\n            }),\n            c: Schema.optionalWith(Schema.String, { default: () => \"\", nullable: true }).annotations({\n              description: \"c-outer\"\n            }),\n            d: Schema.optionalWith(Schema.String.annotations({ description: \"d-inner\" }), {\n              default: () => \"\",\n              nullable: true\n            })\n              .annotations({ description: \"d-outer\" }),\n            e: Schema.optionalWith(Schema.UndefinedOr(Schema.String), { default: () => \"\", nullable: true })\n          })\n          await assertDraft7(schema, {\n            \"type\": \"object\",\n            \"properties\": {\n              \"a\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }] },\n              \"b\": {\n                \"anyOf\": [{ \"type\": \"string\", \"description\": \"b-inner\" }, { \"type\": \"null\" }],\n                \"description\": \"b-inner\"\n              },\n              \"c\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }], \"description\": \"c-outer\" },\n              \"d\": {\n                \"anyOf\": [{ \"type\": \"string\", \"description\": \"d-inner\" }, { \"type\": \"null\" }],\n                \"description\": \"d-outer\"\n              },\n              \"e\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }] }\n            },\n            \"required\": [],\n            \"additionalProperties\": false\n          })\n        })\n\n        it(`{ as: \"Option\" }`, async () => {\n          const schema = Schema.Struct({\n            a: Schema.optionalWith(Schema.String, { as: \"Option\" }),\n            b: Schema.optionalWith(Schema.String.annotations({ description: \"b-inner\" }), { as: \"Option\" }),\n            c: Schema.optionalWith(Schema.String, { as: \"Option\" }).annotations({ description: \"c-outer\" }),\n            d: Schema.optionalWith(Schema.String.annotations({ description: \"d-inner\" }), { as: \"Option\" })\n              .annotations({ description: \"d-outer\" }),\n            e: Schema.optionalWith(Schema.UndefinedOr(Schema.String), { as: \"Option\" })\n          })\n          await assertDraft7(schema, {\n            \"type\": \"object\",\n            \"properties\": {\n              \"a\": { \"type\": \"string\" },\n              \"b\": { \"type\": \"string\", \"description\": \"b-inner\" },\n              \"c\": { \"type\": \"string\", \"description\": \"c-outer\" },\n              \"d\": { \"type\": \"string\", \"description\": \"d-outer\" },\n              \"e\": { \"type\": \"string\" }\n            },\n            \"required\": [],\n            \"additionalProperties\": false\n          })\n        })\n\n        it(`{ as: \"Option\", nullable: true }`, async () => {\n          const schema = Schema.Struct({\n            a: Schema.optionalWith(Schema.String, { as: \"Option\", nullable: true }),\n            b: Schema.optionalWith(Schema.String.annotations({ description: \"b-inner\" }), {\n              as: \"Option\",\n              nullable: true\n            }),\n            c: Schema.optionalWith(Schema.String, { as: \"Option\", nullable: true }).annotations({\n              description: \"c-outer\"\n            }),\n            d: Schema.optionalWith(Schema.String.annotations({ description: \"d-inner\" }), {\n              as: \"Option\",\n              nullable: true\n            }).annotations({\n              description: \"d-outer\"\n            }),\n            e: Schema.optionalWith(Schema.UndefinedOr(Schema.String), { as: \"Option\", nullable: true })\n          })\n          await assertDraft7(schema, {\n            \"type\": \"object\",\n            \"properties\": {\n              \"a\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }] },\n              \"b\": {\n                \"anyOf\": [{ \"type\": \"string\", \"description\": \"b-inner\" }, { \"type\": \"null\" }]\n              },\n              \"c\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }], \"description\": \"c-outer\" },\n              \"d\": {\n                \"anyOf\": [{ \"type\": \"string\", \"description\": \"d-inner\" }, { \"type\": \"null\" }],\n                \"description\": \"d-outer\"\n              },\n              \"e\": { \"anyOf\": [{ \"type\": \"string\" }, { \"type\": \"null\" }] }\n            },\n            \"required\": [],\n            \"additionalProperties\": false\n          })\n        })\n      })\n\n      it(\"Struct + Record\", async () => {\n        const schema = Schema.Struct({\n          a: Schema.String\n        }, Schema.Record({ key: Schema.String, value: Schema.String }))\n\n        await assertDraft7(schema, {\n          \"type\": \"object\",\n          \"required\": [\n            \"a\"\n          ],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\"\n            }\n          },\n          \"additionalProperties\": {\n            \"type\": \"string\"\n          }\n        })\n      })\n\n      describe(\"identifier annotation\", () => {\n        it(\"should use the identifier annotation of the property signature values\", async () => {\n          const schemaWithIdentifier = Schema.String.annotations({\n            identifier: \"my-id\"\n          })\n\n          const schema = Schema.Struct({\n            a: schemaWithIdentifier,\n            b: schemaWithIdentifier\n          })\n\n          await assertDraft7(schema, {\n            \"$defs\": {\n              \"my-id\": {\n                \"type\": \"string\"\n              }\n            },\n            \"type\": \"object\",\n            \"required\": [\n              \"a\",\n              \"b\"\n            ],\n            \"properties\": {\n              \"a\": {\n                \"$ref\": \"#/$defs/my-id\"\n              },\n              \"b\": {\n                \"$ref\": \"#/$defs/my-id\"\n              }\n            },\n            \"additionalProperties\": false\n          })\n        })\n\n        it(\"should ignore the identifier annotation when annotating the value schema\", async () => {\n          const schemaWithIdentifier = Schema.String.annotations({\n            identifier: \"my-id\"\n          })\n\n          const schema = Schema.Struct({\n            a: schemaWithIdentifier.annotations({\n              description: \"a-description\"\n            }),\n            b: schemaWithIdentifier.annotations({\n              description: \"b-description\"\n            })\n          })\n\n          await assertDraft7(schema, {\n            \"type\": \"object\",\n            \"required\": [\n              \"a\",\n              \"b\"\n            ],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\",\n                \"description\": \"a-description\"\n              },\n              \"b\": {\n                \"type\": \"string\",\n                \"description\": \"b-description\"\n              }\n            },\n            \"additionalProperties\": false\n          })\n        })\n\n        it(\"should use the identifier annotation when annotating the property signature\", async () => {\n          const schemaWithIdentifier = Schema.String.annotations({\n            identifier: \"my-id\"\n          })\n\n          const schema = Schema.Struct({\n            a: Schema.propertySignature(schemaWithIdentifier).annotations({\n              description: \"a-description\"\n            }),\n            b: Schema.propertySignature(schemaWithIdentifier).annotations({\n              description: \"b-description\"\n            })\n          })\n\n          await assertDraft7(schema, {\n            \"$defs\": {\n              \"my-id\": {\n                \"type\": \"string\"\n              }\n            },\n            \"type\": \"object\",\n            \"required\": [\n              \"a\",\n              \"b\"\n            ],\n            \"properties\": {\n              \"a\": {\n                \"allOf\": [\n                  {\n                    \"$ref\": \"#/$defs/my-id\"\n                  }\n                ],\n                \"description\": \"a-description\"\n              },\n              \"b\": {\n                \"allOf\": [\n                  {\n                    \"$ref\": \"#/$defs/my-id\"\n                  }\n                ],\n                \"description\": \"b-description\"\n              }\n            },\n            \"additionalProperties\": false\n          })\n        })\n      })\n    })\n\n    describe(\"Record\", () => {\n      it(\"Record(refinement, number)\", async () => {\n        await assertDraft7(\n          Schema.Record({ key: Schema.String.pipe(Schema.minLength(1)), value: Schema.Number }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {},\n            \"patternProperties\": {\n              \"\": {\n                \"type\": \"number\"\n              }\n            },\n            \"propertyNames\": {\n              \"type\": \"string\",\n              \"title\": \"minLength(1)\",\n              \"description\": \"a string at least 1 character(s) long\",\n              \"minLength\": 1\n            }\n          }\n        )\n      })\n\n      it(\"Record(string, number)\", async () => {\n        await assertDraft7(Schema.Record({ key: Schema.String, value: Schema.Number }), {\n          \"type\": \"object\",\n          \"properties\": {},\n          \"required\": [],\n          \"additionalProperties\": {\n            \"type\": \"number\"\n          }\n        })\n      })\n\n      it(\"Record('a' | 'b', number)\", async () => {\n        await assertDraft7(\n          Schema.Record(\n            { key: Schema.Union(Schema.Literal(\"a\"), Schema.Literal(\"b\")), value: Schema.Number }\n          ),\n          {\n            \"type\": \"object\",\n            \"properties\": {\n              \"a\": {\n                \"type\": \"number\"\n              },\n              \"b\": {\n                \"type\": \"number\"\n              }\n            },\n            \"required\": [\"a\", \"b\"],\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"Record(${string}-${string}, number)\", async () => {\n        const schema = Schema.Record(\n          { key: Schema.TemplateLiteral(Schema.String, Schema.Literal(\"-\"), Schema.String), value: Schema.Number }\n        )\n        await assertDraft7(schema, {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {},\n          \"patternProperties\": {\n            \"\": { \"type\": \"number\" }\n          },\n          \"propertyNames\": {\n            \"pattern\": \"^[\\\\s\\\\S]*?-[\\\\s\\\\S]*?$\",\n            \"type\": \"string\"\n          }\n        })\n      })\n\n      it(\"Record(pattern, number)\", async () => {\n        const schema = Schema.Record(\n          { key: Schema.String.pipe(Schema.pattern(new RegExp(\"^.*-.*$\"))), value: Schema.Number }\n        )\n        await assertDraft7(schema, {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {},\n          \"patternProperties\": {\n            \"\": {\n              \"type\": \"number\"\n            }\n          },\n          \"propertyNames\": {\n            \"description\": \"a string matching the pattern ^.*-.*$\",\n            \"pattern\": \"^.*-.*$\",\n            \"type\": \"string\"\n          }\n        })\n      })\n\n      it(\"Record(SymbolFromSelf & annotation, number)\", async () => {\n        await assertDraft7(\n          Schema.Record({\n            key: Schema.SymbolFromSelf.annotations({ jsonSchema: { \"type\": \"string\" } }),\n            value: Schema.Number\n          }),\n          {\n            \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {},\n            \"additionalProperties\": {\n              \"type\": \"number\"\n            },\n            \"propertyNames\": {\n              \"type\": \"string\"\n            }\n          }\n        )\n      })\n\n      it(\"Record(string, UndefinedOr(number))\", async () => {\n        await assertDraft7(Schema.Record({ key: Schema.String, value: Schema.UndefinedOr(Schema.Number) }), {\n          \"type\": \"object\",\n          \"properties\": {},\n          \"required\": [],\n          \"additionalProperties\": { \"type\": \"number\" }\n        })\n      })\n\n      it(\"partial(Struct + Record(string, number))\", async () => {\n        const schema = Schema.partial(\n          Schema.Struct(\n            { foo: Schema.Number },\n            {\n              key: Schema.String,\n              value: Schema.Number\n            }\n          )\n        )\n\n        await assertDraft7(schema, {\n          \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"foo\": {\n              \"type\": \"number\"\n            }\n          },\n          \"additionalProperties\": {\n            \"type\": \"number\"\n          }\n        })\n      })\n    })\n\n    describe(\"Union\", () => {\n      it(\"never members\", async () => {\n        await assertDraft7(Schema.Union(Schema.String, Schema.Never), {\n          \"type\": \"string\"\n        })\n        await assertDraft7(Schema.Union(Schema.String, Schema.Union(Schema.Never, Schema.Never)), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"String | Number\", async () => {\n        await assertDraft7(Schema.Union(Schema.String, Schema.Number), {\n          \"anyOf\": [\n            { \"type\": \"string\" },\n            { \"type\": \"number\" }\n          ]\n        })\n      })\n\n      describe(\"Union including literals\", () => {\n        it(`1 | 2`, async () => {\n          await assertDraft7(\n            Schema.Union(Schema.Literal(1), Schema.Literal(2)),\n            {\n              \"type\": \"number\",\n              \"enum\": [1, 2]\n            }\n          )\n        })\n\n        it(`1(with description) | 2`, async () => {\n          await assertDraft7(\n            Schema.Union(\n              Schema.Literal(1).annotations({ description: \"1-description\" }),\n              Schema.Literal(2)\n            ),\n            {\n              \"anyOf\": [\n                {\n                  \"type\": \"number\",\n                  \"enum\": [1],\n                  \"description\": \"1-description\"\n                },\n                { \"type\": \"number\", \"enum\": [2] }\n              ]\n            }\n          )\n        })\n\n        it(`1 | 2(with description)`, async () => {\n          await assertDraft7(\n            Schema.Union(\n              Schema.Literal(1),\n              Schema.Literal(2).annotations({ description: \"2-description\" })\n            ),\n            {\n              \"anyOf\": [\n                { \"type\": \"number\", \"enum\": [1] },\n                {\n                  \"type\": \"number\",\n                  \"enum\": [2],\n                  \"description\": \"2-description\"\n                }\n              ]\n            }\n          )\n        })\n\n        it(`1 | 2 | string`, async () => {\n          await assertDraft7(Schema.Union(Schema.Literal(1), Schema.Literal(2), Schema.String), {\n            \"anyOf\": [\n              { \"type\": \"number\", \"enum\": [1, 2] },\n              { \"type\": \"string\" }\n            ]\n          })\n        })\n\n        it(`(1 | 2) | string`, async () => {\n          await assertDraft7(Schema.Union(Schema.Literal(1, 2), Schema.String), {\n            \"anyOf\": [\n              { \"type\": \"number\", \"enum\": [1, 2] },\n              { \"type\": \"string\" }\n            ]\n          })\n        })\n\n        it(`(1 | 2)(with description) | string`, async () => {\n          await assertDraft7(\n            Schema.Union(\n              Schema.Literal(1, 2).annotations({ description: \"1-2-description\" }),\n              Schema.String\n            ),\n            {\n              \"anyOf\": [\n                {\n                  \"type\": \"number\",\n                  \"enum\": [1, 2],\n                  \"description\": \"1-2-description\"\n                },\n                { \"type\": \"string\" }\n              ]\n            }\n          )\n        })\n\n        it(`(1 | 2)(with description) | 3 | string`, async () => {\n          await assertDraft7(\n            Schema.Union(\n              Schema.Literal(1, 2).annotations({ description: \"1-2-description\" }),\n              Schema.Literal(3),\n              Schema.String\n            ),\n            {\n              \"anyOf\": [\n                {\n                  \"type\": \"number\",\n                  \"enum\": [1, 2],\n                  \"description\": \"1-2-description\"\n                },\n                { \"enum\": [3], \"type\": \"number\" },\n                {\n                  \"type\": \"string\"\n                }\n              ]\n            }\n          )\n        })\n\n        it(`1(with description) | 2 | string`, async () => {\n          await assertDraft7(\n            Schema.Union(\n              Schema.Literal(1).annotations({ description: \"1-description\" }),\n              Schema.Literal(2),\n              Schema.String\n            ),\n            {\n              \"anyOf\": [\n                {\n                  \"type\": \"number\",\n                  \"description\": \"1-description\",\n                  \"enum\": [1]\n                },\n                { \"type\": \"number\", \"enum\": [2] },\n                { \"type\": \"string\" }\n              ]\n            }\n          )\n        })\n\n        it(`1 | 2(with description) | string`, async () => {\n          await assertDraft7(\n            Schema.Union(\n              Schema.Literal(1),\n              Schema.Literal(2).annotations({ description: \"2-description\" }),\n              Schema.String\n            ),\n            {\n              \"anyOf\": [\n                { \"type\": \"number\", \"enum\": [1] },\n                {\n                  \"type\": \"number\",\n                  \"description\": \"2-description\",\n                  \"enum\": [2]\n                },\n                { \"type\": \"string\" }\n              ]\n            }\n          )\n        })\n\n        it(`string | 1 | 2 `, async () => {\n          await assertDraft7(Schema.Union(Schema.String, Schema.Literal(1), Schema.Literal(2)), {\n            \"anyOf\": [\n              { \"type\": \"string\" },\n              { \"type\": \"number\", \"enum\": [1, 2] }\n            ]\n          })\n        })\n\n        it(`string | (1 | 2) `, async () => {\n          await assertDraft7(Schema.Union(Schema.String, Schema.Literal(1, 2)), {\n            \"anyOf\": [\n              { \"type\": \"string\" },\n              { \"type\": \"number\", \"enum\": [1, 2] }\n            ]\n          })\n        })\n\n        it(`string | 1(with description) | 2`, async () => {\n          await assertDraft7(\n            Schema.Union(\n              Schema.String,\n              Schema.Literal(1).annotations({ description: \"1-description\" }),\n              Schema.Literal(2)\n            ),\n            {\n              \"anyOf\": [\n                { \"type\": \"string\" },\n                {\n                  \"type\": \"number\",\n                  \"description\": \"1-description\",\n                  \"enum\": [1]\n                },\n                { \"type\": \"number\", \"enum\": [2] }\n              ]\n            }\n          )\n        })\n\n        it(`string | 1 | 2(with description)`, async () => {\n          await assertDraft7(\n            Schema.Union(\n              Schema.String,\n              Schema.Literal(1),\n              Schema.Literal(2).annotations({ description: \"2-description\" })\n            ),\n            {\n              \"anyOf\": [\n                { \"type\": \"string\" },\n                { \"type\": \"number\", \"enum\": [1] },\n                {\n                  \"type\": \"number\",\n                  \"description\": \"2-description\",\n                  \"enum\": [2]\n                }\n              ]\n            }\n          )\n        })\n      })\n    })\n\n    describe(\"Suspend\", () => {\n      it(\"suspend(() => schema).annotations({ identifier: '...' })\", async () => {\n        interface A {\n          readonly a: string\n          readonly as: ReadonlyArray<A>\n        }\n        const schema: Schema.Schema<A> = Schema.suspend(() =>\n          Schema.Struct({\n            a: Schema.String,\n            as: Schema.Array(schema)\n          })\n        ).annotations({ identifier: \"ID\" })\n        await assertDraft7(schema, {\n          \"$ref\": \"#/$defs/ID\",\n          \"$defs\": {\n            \"ID\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"a\",\n                \"as\"\n              ],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                },\n                \"as\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/$defs/ID\"\n                  }\n                }\n              },\n              \"additionalProperties\": false\n            }\n          }\n        })\n      })\n\n      it(\"suspend(() => schema.annotations({ identifier: '...' }))\", async () => {\n        interface A {\n          readonly a: string\n          readonly as: ReadonlyArray<A>\n        }\n        const schema: Schema.Schema<A> = Schema.suspend(() =>\n          Schema.Struct({\n            a: Schema.String,\n            as: Schema.Array(schema)\n          }).annotations({ identifier: \"ID\" })\n        )\n        await assertDraft7(schema, {\n          \"$ref\": \"#/$defs/ID\",\n          \"$defs\": {\n            \"ID\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"a\",\n                \"as\"\n              ],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                },\n                \"as\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/$defs/ID\"\n                  }\n                }\n              },\n              \"additionalProperties\": false\n            }\n          }\n        })\n      })\n\n      it(\"inner annotation\", async () => {\n        interface A {\n          readonly a: string\n          readonly as: ReadonlyArray<A>\n        }\n        const schema = Schema.Struct({\n          a: Schema.String,\n          as: Schema.Array(\n            Schema.suspend((): Schema.Schema<A> => schema).annotations({\n              identifier: \"ID\"\n            })\n          )\n        })\n        await assertDraft7(schema, {\n          \"type\": \"object\",\n          \"required\": [\n            \"a\",\n            \"as\"\n          ],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\"\n            },\n            \"as\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"$ref\": \"#/$defs/ID\"\n              }\n            }\n          },\n          \"additionalProperties\": false,\n          \"$defs\": {\n            \"ID\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"a\",\n                \"as\"\n              ],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                },\n                \"as\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/$defs/ID\"\n                  }\n                }\n              },\n              \"additionalProperties\": false\n            }\n          }\n        })\n      })\n\n      it(\"outer annotation\", async () => {\n        interface A {\n          readonly a: string\n          readonly as: ReadonlyArray<A>\n        }\n        const schema = Schema.Struct({\n          a: Schema.String,\n          as: Schema.Array(Schema.suspend((): Schema.Schema<A> => schema))\n        }).annotations({ identifier: \"ID\" })\n        await assertDraft7(schema, {\n          \"$ref\": \"#/$defs/ID\",\n          \"$defs\": {\n            \"ID\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"a\",\n                \"as\"\n              ],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                },\n                \"as\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/$defs/ID\"\n                  }\n                }\n              },\n              \"additionalProperties\": false\n            }\n          }\n        })\n      })\n\n      it(\"should support mutually suspended schemas\", async () => {\n        interface Expression {\n          readonly type: \"expression\"\n          readonly value: number | Operation\n        }\n\n        interface Operation {\n          readonly type: \"operation\"\n          readonly operator: \"+\" | \"-\"\n          readonly left: Expression\n          readonly right: Expression\n        }\n\n        // intended outer suspend\n        const Expression: Schema.Schema<Expression> = Schema.suspend(() =>\n          Schema.Struct({\n            type: Schema.Literal(\"expression\"),\n            value: Schema.Union(Schema.Number, Operation)\n          })\n        ).annotations({ identifier: \"2ad5683a-878f-4e4d-909c-496e59ce62e0\" })\n\n        // intended outer suspend\n        const Operation: Schema.Schema<Operation> = Schema.suspend(() =>\n          Schema.Struct({\n            type: Schema.Literal(\"operation\"),\n            operator: Schema.Union(Schema.Literal(\"+\"), Schema.Literal(\"-\")),\n            left: Expression,\n            right: Expression\n          })\n        ).annotations({ identifier: \"e0f2ce47-eac7-4991-8730-90ebe4e0ffda\" })\n\n        await assertDraft7(Operation, {\n          \"$ref\": \"#/$defs/e0f2ce47-eac7-4991-8730-90ebe4e0ffda\",\n          \"$defs\": {\n            \"e0f2ce47-eac7-4991-8730-90ebe4e0ffda\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"type\",\n                \"operator\",\n                \"left\",\n                \"right\"\n              ],\n              \"properties\": {\n                \"type\": {\n                  \"type\": \"string\",\n                  \"enum\": [\"operation\"]\n                },\n                \"operator\": {\n                  \"type\": \"string\",\n                  \"enum\": [\"+\", \"-\"]\n                },\n                \"left\": {\n                  \"$ref\": \"#/$defs/2ad5683a-878f-4e4d-909c-496e59ce62e0\"\n                },\n                \"right\": {\n                  \"$ref\": \"#/$defs/2ad5683a-878f-4e4d-909c-496e59ce62e0\"\n                }\n              },\n              \"additionalProperties\": false\n            },\n            \"2ad5683a-878f-4e4d-909c-496e59ce62e0\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"type\",\n                \"value\"\n              ],\n              \"properties\": {\n                \"type\": {\n                  \"type\": \"string\",\n                  \"enum\": [\"expression\"]\n                },\n                \"value\": {\n                  \"anyOf\": [\n                    {\n                      \"type\": \"number\"\n                    },\n                    {\n                      \"$ref\": \"#/$defs/e0f2ce47-eac7-4991-8730-90ebe4e0ffda\"\n                    }\n                  ]\n                }\n              },\n              \"additionalProperties\": false\n            }\n          }\n        })\n      })\n    })\n\n    describe(\"Class\", () => {\n      it(\"should use the identifier as JSON Schema identifier\", async () => {\n        class A extends Schema.Class<A>(\"A\")(Schema.Struct({ a: Schema.String })) {}\n        await assertDraft7(A, {\n          \"$defs\": {\n            \"A\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"a\"\n              ],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"additionalProperties\": false\n            }\n          },\n          \"$ref\": \"#/$defs/A\"\n        })\n      })\n\n      it(\"type side json schema annotation\", async () => {\n        class A extends Schema.Class<A>(\"A\")(Schema.Struct({ a: Schema.String }), {\n          identifier: \"A2\"\n        }) {}\n        await assertDraft7(A, {\n          \"$defs\": {\n            \"A2\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"a\"\n              ],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"additionalProperties\": false\n            }\n          },\n          \"$ref\": \"#/$defs/A2\"\n        })\n      })\n\n      it(\"transformation side json schema annotation\", async () => {\n        class A extends Schema.Class<A>(\"A\")(Schema.Struct({ a: Schema.String }), [\n          undefined,\n          {\n            identifier: \"A2\"\n          }\n        ]) {}\n        await assertDraft7(A, {\n          \"$defs\": {\n            \"A2\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"a\"\n              ],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"additionalProperties\": false\n            }\n          },\n          \"$ref\": \"#/$defs/A2\"\n        })\n      })\n\n      it(\"from side json schema annotation\", async () => {\n        class A extends Schema.Class<A>(\"A\")(Schema.Struct({ a: Schema.String }), [\n          undefined,\n          undefined,\n          {\n            identifier: \"A2\"\n          }\n        ]) {}\n        await assertDraft7(A, {\n          \"$defs\": {\n            \"A\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"a\"\n              ],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"additionalProperties\": false\n            }\n          },\n          \"$ref\": \"#/$defs/A\"\n        })\n      })\n\n      it(\"should escape special characters in the $ref\", async () => {\n        class A extends Schema.Class<A>(\"~package/name\")(Schema.Struct({ a: Schema.String })) {}\n        await assertDraft7(A, {\n          \"$defs\": {\n            \"~package/name\": {\n              \"type\": \"object\",\n              \"required\": [\n                \"a\"\n              ],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"additionalProperties\": false\n            }\n          },\n          \"$ref\": \"#/$defs/~0package~1name\"\n        })\n      })\n    })\n\n    it(\"compose\", async () => {\n      const schema = Schema.Struct({\n        a: Schema.NonEmptyString.pipe(Schema.compose(Schema.NumberFromString))\n      })\n      await assertDraft7(schema, {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"type\": \"string\",\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1\n          }\n        },\n        \"type\": \"object\",\n        \"required\": [\n          \"a\"\n        ],\n        \"properties\": {\n          \"a\": {\n            \"$ref\": \"#/$defs/NonEmptyString\"\n          }\n        },\n        \"additionalProperties\": false\n      })\n    })\n\n    it(\"should correctly generate JSON Schemas for a schema created by extending two refinements\", async () => {\n      await assertDraft7(\n        Schema.Struct({\n          a: Schema.String\n        }).pipe(\n          Schema.filter(() => true, {\n            jsonSchema: { \"examples\": [\"c5052c04-d6c9-44f3-9c8f-ede707d6ce38\"] }\n          })\n        ).pipe(Schema.extend(\n          Schema.Struct({\n            b: Schema.Number\n          }).pipe(\n            Schema.filter(() => true, {\n              jsonSchema: { \"$comment\": \"940b4ea4-6313-4b59-9e64-ff7a41b8eb15\" }\n            })\n          )\n        )),\n        {\n          \"type\": \"object\",\n          \"required\": [\"a\", \"b\"],\n          \"properties\": {\n            \"a\": { \"type\": \"string\" },\n            \"b\": { \"type\": \"number\" }\n          },\n          \"examples\": [\"c5052c04-d6c9-44f3-9c8f-ede707d6ce38\"],\n          \"$comment\": \"940b4ea4-6313-4b59-9e64-ff7a41b8eb15\",\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    describe(\"identifier annotation support\", () => {\n      it(\"String\", async () => {\n        await assertDraft7(Schema.String.annotations({ identifier: \"ID\" }), {\n          \"$defs\": {\n            \"ID\": {\n              \"type\": \"string\"\n            }\n          },\n          \"$ref\": \"#/$defs/ID\"\n        })\n        await assertDraft7(Schema.String.annotations({ identifier: \"ID\", description: \"description\" }), {\n          \"$defs\": {\n            \"ID\": {\n              \"type\": \"string\",\n              \"description\": \"description\"\n            }\n          },\n          \"$ref\": \"#/$defs/ID\"\n        })\n      })\n\n      it(\"Refinement\", async () => {\n        await assertDraft7(\n          Schema.String.pipe(Schema.minLength(2)).annotations({ identifier: \"ID\" }),\n          {\n            \"$defs\": {\n              \"ID\": {\n                \"type\": \"string\",\n                \"title\": \"minLength(2)\",\n                \"description\": \"a string at least 2 character(s) long\",\n                \"minLength\": 2\n              }\n            },\n            \"$ref\": \"#/$defs/ID\"\n          }\n        )\n      })\n\n      describe(\"Struct\", () => {\n        it(\"annotation\", async () => {\n          await assertDraft7(\n            Schema.Struct({\n              a: Schema.String\n            }).annotations({ identifier: \"ID\" }),\n            {\n              \"$defs\": {\n                \"ID\": {\n                  \"type\": \"object\",\n                  \"required\": [\"a\"],\n                  \"properties\": {\n                    \"a\": { \"type\": \"string\" }\n                  },\n                  \"additionalProperties\": false\n                }\n              },\n              \"$ref\": \"#/$defs/ID\"\n            }\n          )\n        })\n\n        it(\"field annotations\", async () => {\n          const Name = Schema.String.annotations({\n            identifier: \"ID\",\n            description: \"description\"\n          })\n          const schema = Schema.Struct({\n            a: Name\n          })\n          await assertDraft7(schema, {\n            \"$defs\": {\n              \"ID\": {\n                \"type\": \"string\",\n                \"description\": \"description\"\n              }\n            },\n            \"type\": \"object\",\n            \"required\": [\"a\"],\n            \"properties\": {\n              \"a\": {\n                \"$ref\": \"#/$defs/ID\"\n              }\n            },\n            \"additionalProperties\": false\n          })\n        })\n\n        it(\"self annotation + field annotations\", async () => {\n          const Name = Schema.String.annotations({\n            identifier: \"b49f125d-1646-4eb5-8120-9524ab6039de\",\n            description: \"703b7ff0-cb8d-49de-aeeb-05d92faa4599\",\n            title: \"4b6d9ea6-7c4d-4073-a427-8d1b82fd1677\"\n          })\n          await assertDraft7(\n            Schema.Struct({\n              a: Name\n            }).annotations({ identifier: \"7e559891-9143-4138-ae3e-81a5f0907380\" }),\n            {\n              \"$defs\": {\n                \"7e559891-9143-4138-ae3e-81a5f0907380\": {\n                  \"type\": \"object\",\n                  \"required\": [\"a\"],\n                  \"properties\": {\n                    \"a\": { \"$ref\": \"#/$defs/b49f125d-1646-4eb5-8120-9524ab6039de\" }\n                  },\n                  \"additionalProperties\": false\n                },\n                \"b49f125d-1646-4eb5-8120-9524ab6039de\": {\n                  \"type\": \"string\",\n                  \"description\": \"703b7ff0-cb8d-49de-aeeb-05d92faa4599\",\n                  \"title\": \"4b6d9ea6-7c4d-4073-a427-8d1b82fd1677\"\n                }\n              },\n              \"$ref\": \"#/$defs/7e559891-9143-4138-ae3e-81a5f0907380\"\n            }\n          )\n        })\n\n        it(\"deeply nested field annotations\", async () => {\n          const Name = Schema.String.annotations({\n            identifier: \"434a08dd-3f8f-4de4-b91d-8846aab1fb05\",\n            description: \"eb183f5c-404c-4686-b78b-1bd00d18f8fd\",\n            title: \"c0cbd438-1fb5-47fe-bf81-1ff5527e779a\"\n          })\n          const schema = Schema.Struct({ a: Name, b: Schema.Struct({ c: Name }) })\n          await assertDraft7(schema, {\n            \"$defs\": {\n              \"434a08dd-3f8f-4de4-b91d-8846aab1fb05\": {\n                \"type\": \"string\",\n                \"description\": \"eb183f5c-404c-4686-b78b-1bd00d18f8fd\",\n                \"title\": \"c0cbd438-1fb5-47fe-bf81-1ff5527e779a\"\n              }\n            },\n            \"type\": \"object\",\n            \"required\": [\"a\", \"b\"],\n            \"properties\": {\n              \"a\": {\n                \"$ref\": \"#/$defs/434a08dd-3f8f-4de4-b91d-8846aab1fb05\"\n              },\n              \"b\": {\n                \"type\": \"object\",\n                \"required\": [\"c\"],\n                \"properties\": {\n                  \"c\": { \"$ref\": \"#/$defs/434a08dd-3f8f-4de4-b91d-8846aab1fb05\" }\n                },\n                \"additionalProperties\": false\n              }\n            },\n            \"additionalProperties\": false\n          })\n        })\n      })\n\n      describe(\"Union\", () => {\n        it(\"Union of literals with identifiers\", async () => {\n          await assertDraft7(\n            Schema.Union(\n              Schema.Literal(\"a\").annotations({\n                description: \"ef296f1c-01fe-4a20-bd35-ed449c964c49\",\n                identifier: \"170d659f-112e-4e3b-85db-464b668f2aed\"\n              }),\n              Schema.Literal(\"b\").annotations({\n                description: \"effbf54b-a62d-455b-86fa-97a5af46c6f3\",\n                identifier: \"2a4e4f67-3732-4f7b-a505-856e51dd1578\"\n              })\n            ),\n            {\n              \"$defs\": {\n                \"170d659f-112e-4e3b-85db-464b668f2aed\": {\n                  \"type\": \"string\",\n                  \"enum\": [\"a\"],\n                  \"description\": \"ef296f1c-01fe-4a20-bd35-ed449c964c49\"\n                },\n                \"2a4e4f67-3732-4f7b-a505-856e51dd1578\": {\n                  \"type\": \"string\",\n                  \"enum\": [\"b\"],\n                  \"description\": \"effbf54b-a62d-455b-86fa-97a5af46c6f3\"\n                }\n              },\n              \"anyOf\": [\n                { \"$ref\": \"#/$defs/170d659f-112e-4e3b-85db-464b668f2aed\" },\n                { \"$ref\": \"#/$defs/2a4e4f67-3732-4f7b-a505-856e51dd1578\" }\n              ]\n            }\n          )\n        })\n      })\n    })\n\n    it(\"should filter out invalid examples\", async () => {\n      await assertDraft7(Schema.NonEmptyString.annotations({ examples: [\"\", \"a\"] }), {\n        \"type\": \"string\",\n        \"title\": \"nonEmptyString\",\n        \"description\": \"a non empty string\",\n        \"minLength\": 1,\n        \"examples\": [\"a\"]\n      })\n    })\n\n    it(\"should filter out invalid defaults\", async () => {\n      await assertDraft7(Schema.NonEmptyString.annotations({ default: \"\" }), {\n        \"type\": \"string\",\n        \"title\": \"nonEmptyString\",\n        \"description\": \"a non empty string\",\n        \"minLength\": 1\n      })\n    })\n\n    describe(\"should encode the examples\", () => {\n      it(\"property signatures\", async () => {\n        const schema = Schema.Struct({\n          a: Schema.NumberFromString.pipe(Schema.propertySignature).annotations({ examples: [1, 2] })\n        })\n        await assertDraft7(schema, {\n          \"$defs\": {\n            \"NumberFromString\": {\n              \"description\": \"a string to be decoded into a number\",\n              \"type\": \"string\"\n            }\n          },\n          \"type\": \"object\",\n          \"required\": [\n            \"a\"\n          ],\n          \"properties\": {\n            \"a\": {\n              \"allOf\": [\n                {\n                  \"$ref\": \"#/$defs/NumberFromString\"\n                }\n              ],\n              \"examples\": [\"1\", \"2\"]\n            }\n          },\n          \"additionalProperties\": false\n        })\n      })\n\n      it(\"elements\", async () => {\n        const schema = Schema.Tuple(Schema.NumberFromString.pipe(Schema.element).annotations({ examples: [1, 2] }))\n        await assertDraft7(schema, {\n          \"$defs\": {\n            \"NumberFromString\": {\n              \"description\": \"a string to be decoded into a number\",\n              \"type\": \"string\"\n            }\n          },\n          \"type\": \"array\",\n          \"items\": [\n            {\n              \"allOf\": [\n                {\n                  \"$ref\": \"#/$defs/NumberFromString\"\n                }\n              ],\n              \"examples\": [\"1\", \"2\"]\n            }\n          ],\n          \"minItems\": 1,\n          \"additionalItems\": false\n        })\n      })\n    })\n\n    it(\"Exit\", async () => {\n      const schema = Schema.Exit({\n        failure: Schema.String,\n        success: Schema.Number,\n        defect: Schema.Defect\n      })\n      await assertDraft7(schema, {\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n        \"$defs\": {\n          \"CauseEncoded0\": {\n            \"anyOf\": [\n              {\n                \"type\": \"object\",\n                \"required\": [\n                  \"_tag\"\n                ],\n                \"properties\": {\n                  \"_tag\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"Empty\"\n                    ]\n                  }\n                },\n                \"additionalProperties\": false\n              },\n              {\n                \"type\": \"object\",\n                \"required\": [\n                  \"_tag\",\n                  \"error\"\n                ],\n                \"properties\": {\n                  \"_tag\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"Fail\"\n                    ]\n                  },\n                  \"error\": {\n                    \"type\": \"string\"\n                  }\n                },\n                \"additionalProperties\": false\n              },\n              {\n                \"type\": \"object\",\n                \"required\": [\n                  \"_tag\",\n                  \"defect\"\n                ],\n                \"properties\": {\n                  \"_tag\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"Die\"\n                    ]\n                  },\n                  \"defect\": {\n                    \"$ref\": \"#/$defs/Defect\"\n                  }\n                },\n                \"additionalProperties\": false\n              },\n              {\n                \"type\": \"object\",\n                \"required\": [\n                  \"_tag\",\n                  \"fiberId\"\n                ],\n                \"properties\": {\n                  \"_tag\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"Interrupt\"\n                    ]\n                  },\n                  \"fiberId\": {\n                    \"$ref\": \"#/$defs/FiberIdEncoded\"\n                  }\n                },\n                \"additionalProperties\": false\n              },\n              {\n                \"type\": \"object\",\n                \"required\": [\n                  \"_tag\",\n                  \"left\",\n                  \"right\"\n                ],\n                \"properties\": {\n                  \"_tag\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"Sequential\"\n                    ]\n                  },\n                  \"left\": {\n                    \"$ref\": \"#/$defs/CauseEncoded0\"\n                  },\n                  \"right\": {\n                    \"$ref\": \"#/$defs/CauseEncoded0\"\n                  }\n                },\n                \"additionalProperties\": false\n              },\n              {\n                \"type\": \"object\",\n                \"required\": [\n                  \"_tag\",\n                  \"left\",\n                  \"right\"\n                ],\n                \"properties\": {\n                  \"_tag\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"Parallel\"\n                    ]\n                  },\n                  \"left\": {\n                    \"$ref\": \"#/$defs/CauseEncoded0\"\n                  },\n                  \"right\": {\n                    \"$ref\": \"#/$defs/CauseEncoded0\"\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            ],\n            \"title\": \"CauseEncoded<string>\"\n          },\n          \"Defect\": {\n            \"$id\": \"/schemas/unknown\",\n            \"title\": \"unknown\"\n          },\n          \"FiberIdEncoded\": {\n            \"anyOf\": [\n              {\n                \"$ref\": \"#/$defs/FiberIdNoneEncoded\"\n              },\n              {\n                \"$ref\": \"#/$defs/FiberIdRuntimeEncoded\"\n              },\n              {\n                \"$ref\": \"#/$defs/FiberIdCompositeEncoded\"\n              }\n            ]\n          },\n          \"FiberIdNoneEncoded\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"None\"\n                ]\n              }\n            },\n            \"additionalProperties\": false\n          },\n          \"FiberIdRuntimeEncoded\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\",\n              \"id\",\n              \"startTimeMillis\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"Runtime\"\n                ]\n              },\n              \"id\": {\n                \"$ref\": \"#/$defs/Int\"\n              },\n              \"startTimeMillis\": {\n                \"$ref\": \"#/$defs/Int\"\n              }\n            },\n            \"additionalProperties\": false\n          },\n          \"Int\": {\n            \"type\": \"integer\",\n            \"description\": \"an integer\",\n            \"title\": \"int\"\n          },\n          \"FiberIdCompositeEncoded\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\",\n              \"left\",\n              \"right\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"Composite\"\n                ]\n              },\n              \"left\": {\n                \"$ref\": \"#/$defs/FiberIdEncoded\"\n              },\n              \"right\": {\n                \"$ref\": \"#/$defs/FiberIdEncoded\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        },\n        \"anyOf\": [\n          {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\",\n              \"cause\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"Failure\"\n                ]\n              },\n              \"cause\": {\n                \"$ref\": \"#/$defs/CauseEncoded0\"\n              }\n            },\n            \"additionalProperties\": false\n          },\n          {\n            \"type\": \"object\",\n            \"required\": [\n              \"_tag\",\n              \"value\"\n            ],\n            \"properties\": {\n              \"_tag\": {\n                \"type\": \"string\",\n                \"enum\": [\n                  \"Success\"\n                ]\n              },\n              \"value\": {\n                \"type\": \"number\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        ],\n        \"title\": \"ExitEncoded<number, string, Defect>\"\n      })\n    })\n\n    describe(\"Schema.encodedBoundSchema / Schema.encodedSchema\", () => {\n      describe(\"Suspend\", () => {\n        it(\"without inner transformations\", async () => {\n          interface Category {\n            readonly name: string\n            readonly categories: ReadonlyArray<Category>\n          }\n\n          const schema: Schema.Schema<Category> = Schema.Struct({\n            name: Schema.String,\n            categories: Schema.Array(\n              Schema.suspend(() => schema).annotations({ identifier: \"ID\" })\n            )\n          })\n\n          await assertDraft7(Schema.encodedBoundSchema(schema), {\n            \"type\": \"object\",\n            \"required\": [\n              \"name\",\n              \"categories\"\n            ],\n            \"properties\": {\n              \"name\": {\n                \"type\": \"string\"\n              },\n              \"categories\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/IDEncodedBound\"\n                }\n              }\n            },\n            \"additionalProperties\": false,\n            \"$defs\": {\n              \"IDEncodedBound\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"name\",\n                  \"categories\"\n                ],\n                \"properties\": {\n                  \"name\": {\n                    \"type\": \"string\"\n                  },\n                  \"categories\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                      \"$ref\": \"#/$defs/IDEncodedBound\"\n                    }\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            }\n          })\n          await assertDraft7(Schema.encodedSchema(schema), {\n            \"type\": \"object\",\n            \"required\": [\n              \"name\",\n              \"categories\"\n            ],\n            \"properties\": {\n              \"name\": {\n                \"type\": \"string\"\n              },\n              \"categories\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/IDEncoded\"\n                }\n              }\n            },\n            \"additionalProperties\": false,\n            \"$defs\": {\n              \"IDEncoded\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"name\",\n                  \"categories\"\n                ],\n                \"properties\": {\n                  \"name\": {\n                    \"type\": \"string\"\n                  },\n                  \"categories\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                      \"$ref\": \"#/$defs/IDEncoded\"\n                    }\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            }\n          })\n        })\n\n        it(\"with inner transformations\", async () => {\n          interface Category {\n            readonly name: number\n            readonly categories: ReadonlyArray<Category>\n          }\n          interface CategoryEncoded {\n            readonly name: string\n            readonly categories: ReadonlyArray<CategoryEncoded>\n          }\n\n          const schema: Schema.Schema<Category, CategoryEncoded> = Schema.Struct({\n            name: Schema.NumberFromString,\n            categories: Schema.Array(\n              Schema.suspend(() => schema).annotations({ identifier: \"ID\" })\n            )\n          })\n\n          await assertDraft7(Schema.encodedBoundSchema(schema), {\n            \"type\": \"object\",\n            \"required\": [\n              \"name\",\n              \"categories\"\n            ],\n            \"properties\": {\n              \"name\": {\n                \"type\": \"string\",\n                \"description\": \"a string to be decoded into a number\"\n              },\n              \"categories\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/IDEncodedBound\"\n                }\n              }\n            },\n            \"additionalProperties\": false,\n            \"$defs\": {\n              \"IDEncodedBound\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"name\",\n                  \"categories\"\n                ],\n                \"properties\": {\n                  \"name\": {\n                    \"type\": \"string\",\n                    \"description\": \"a string to be decoded into a number\"\n                  },\n                  \"categories\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                      \"$ref\": \"#/$defs/IDEncodedBound\"\n                    }\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            }\n          })\n          await assertDraft7(Schema.encodedSchema(schema), {\n            \"type\": \"object\",\n            \"required\": [\n              \"name\",\n              \"categories\"\n            ],\n            \"properties\": {\n              \"name\": {\n                \"type\": \"string\",\n                \"description\": \"a string to be decoded into a number\"\n              },\n              \"categories\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/IDEncoded\"\n                }\n              }\n            },\n            \"additionalProperties\": false,\n            \"$defs\": {\n              \"IDEncoded\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"name\",\n                  \"categories\"\n                ],\n                \"properties\": {\n                  \"name\": {\n                    \"type\": \"string\",\n                    \"description\": \"a string to be decoded into a number\"\n                  },\n                  \"categories\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                      \"$ref\": \"#/$defs/IDEncoded\"\n                    }\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            }\n          })\n        })\n      })\n    })\n\n    describe(\"jsonSchema annotation support\", () => {\n      describe(\"Class\", () => {\n        it(\"custom annotation\", async () => {\n          class A extends Schema.Class<A>(\"A\")({ a: Schema.String }, {\n            jsonSchema: { \"type\": \"string\" }\n          }) {}\n          await assertDraft7(A, {\n            \"$defs\": {\n              \"A\": {\n                \"type\": \"string\"\n              }\n            },\n            \"$ref\": \"#/$defs/A\"\n          })\n        })\n\n        it(\"should support typeSchema(Class) with custom annotation\", async () => {\n          class A extends Schema.Class<A>(\"A\")({ a: Schema.String }, {\n            jsonSchema: { \"type\": \"string\" }\n          }) {}\n          await assertDraft7(Schema.typeSchema(A), {\n            \"$defs\": {\n              \"A\": {\n                \"type\": \"string\"\n              }\n            },\n            \"$ref\": \"#/$defs/A\"\n          })\n        })\n      })\n\n      it(\"Declaration\", async () => {\n        class MyType {}\n        const schema = Schema.declare<MyType>((x) => x instanceof MyType, {\n          jsonSchema: {\n            type: \"string\",\n            description: \"default-description\"\n          }\n        })\n        await assertDraft7(schema, {\n          \"type\": \"string\",\n          \"description\": \"default-description\"\n        })\n        await assertDraft7(\n          schema.annotations({\n            description: \"description\"\n          }),\n          {\n            \"type\": \"string\",\n            \"description\": \"description\"\n          }\n        )\n      })\n\n      it(\"Void\", async () => {\n        await assertDraft7(Schema.Void.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"Never\", async () => {\n        await assertDraft7(Schema.Never.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"Literal\", async () => {\n        await assertDraft7(Schema.Literal(\"a\").annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"SymbolFromSelf\", async () => {\n        await assertDraft7(Schema.SymbolFromSelf.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"UniqueSymbolFromSelf\", async () => {\n        await assertDraft7(\n          Schema.UniqueSymbolFromSelf(Symbol.for(\"effect/schema/test/a\")).annotations({\n            jsonSchema: { \"type\": \"string\" }\n          }),\n          { \"type\": \"string\" }\n        )\n      })\n\n      it(\"TemplateLiteral\", async () => {\n        await assertDraft7(\n          Schema.TemplateLiteral(Schema.Literal(\"a\"), Schema.String, Schema.Literal(\"b\")).annotations({\n            jsonSchema: { \"type\": \"string\" }\n          }),\n          { \"type\": \"string\" }\n        )\n      })\n\n      it(\"Undefined\", async () => {\n        await assertDraft7(Schema.Undefined.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"Unknown\", async () => {\n        await assertDraft7(Schema.Unknown.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"Any\", async () => {\n        await assertDraft7(Schema.Any.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"Object\", async () => {\n        await assertDraft7(Schema.Object.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"String\", async () => {\n        await assertDraft7(\n          Schema.String.annotations({\n            jsonSchema: {\n              \"type\": \"string\",\n              \"description\": \"description\",\n              \"format\": \"uuid\"\n            }\n          }),\n          {\n            \"type\": \"string\",\n            \"description\": \"description\",\n            \"format\": \"uuid\"\n          }\n        )\n        await assertDraft7(\n          Schema.String.annotations({\n            identifier: \"630d10c4-7030-45e7-894d-2c0bf5acadcf\",\n            jsonSchema: { \"type\": \"string\", \"description\": \"description\" }\n          }),\n          {\n            \"$defs\": {\n              \"630d10c4-7030-45e7-894d-2c0bf5acadcf\": {\n                \"type\": \"string\",\n                \"description\": \"description\"\n              }\n            },\n            \"$ref\": \"#/$defs/630d10c4-7030-45e7-894d-2c0bf5acadcf\"\n          }\n        )\n      })\n\n      it(\"Number\", async () => {\n        await assertDraft7(Schema.Number.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"BigintFromSelf\", async () => {\n        await assertDraft7(Schema.BigIntFromSelf.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"Boolean\", async () => {\n        await assertDraft7(Schema.Boolean.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"Enums\", async () => {\n        enum Fruits {\n          Apple,\n          Banana\n        }\n        await assertDraft7(Schema.Enums(Fruits).annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"Tuple\", async () => {\n        await assertDraft7(\n          Schema.Tuple(Schema.String, Schema.Number).annotations({ jsonSchema: { \"type\": \"string\" } }),\n          { \"type\": \"string\" }\n        )\n      })\n\n      it(\"Struct\", async () => {\n        await assertDraft7(\n          Schema.Struct({ a: Schema.String, b: Schema.Number }).annotations({\n            jsonSchema: { \"type\": \"string\" }\n          }),\n          { \"type\": \"string\" }\n        )\n      })\n\n      it(\"Union\", async () => {\n        await assertDraft7(\n          Schema.Union(Schema.String, Schema.Number).annotations({ jsonSchema: { \"type\": \"string\" } }),\n          { \"type\": \"string\" }\n        )\n      })\n\n      it(\"UUID\", async () => {\n        await assertDraft7(\n          Schema.UUID,\n          {\n            \"$defs\": {\n              \"UUID\": {\n                \"description\": \"a Universally Unique Identifier\",\n                \"pattern\": \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\",\n                \"type\": \"string\",\n                \"format\": \"uuid\"\n              }\n            },\n            \"$ref\": \"#/$defs/UUID\"\n          }\n        )\n      })\n\n      it(\"Suspend\", async () => {\n        interface A {\n          readonly a: string\n          readonly as: ReadonlyArray<A>\n        }\n        const schema = Schema.Struct({\n          a: Schema.String,\n          as: Schema.Array(\n            Schema.suspend((): Schema.Schema<A> => schema).annotations({ jsonSchema: { \"type\": \"string\" } })\n          )\n        })\n\n        await assertDraft7(schema, {\n          \"type\": \"object\",\n          \"required\": [\n            \"a\",\n            \"as\"\n          ],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\"\n            },\n            \"as\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"type\": \"string\"\n              }\n            }\n          },\n          \"additionalProperties\": false\n        })\n      })\n\n      describe(\"Refinement\", () => {\n        it(\"Int\", async () => {\n          await assertDraft7(Schema.Int.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n            \"type\": \"string\"\n          })\n        })\n\n        it(\"custom\", async () => {\n          await assertDraft7(\n            Schema.String.pipe(Schema.filter(() => true, { jsonSchema: {} })).annotations({\n              identifier: \"ID\"\n            }),\n            {\n              \"$ref\": \"#/$defs/ID\",\n              \"$defs\": {\n                \"ID\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          )\n        })\n      })\n\n      it(\"Transformation\", async () => {\n        await assertDraft7(Schema.NumberFromString.annotations({ jsonSchema: { \"type\": \"string\" } }), {\n          \"type\": \"string\"\n        })\n      })\n\n      it(\"refinement of a transformation with an override annotation\", async () => {\n        await assertDraft7(Schema.Date.annotations({ jsonSchema: { type: \"string\", format: \"date-time\" } }), {\n          \"format\": \"date-time\",\n          \"type\": \"string\"\n        })\n        await assertDraft7(\n          Schema.Date.annotations({\n            jsonSchema: { anyOf: [{ type: \"object\" }, { type: \"array\" }] }\n          }),\n          {\n            \"anyOf\": [{ \"type\": \"object\" }, { \"type\": \"array\" }]\n          }\n        )\n        await assertDraft7(Schema.Date.annotations({ jsonSchema: { \"$ref\": \"x\" } }), {\n          \"$ref\": \"x\"\n        })\n        await assertDraft7(Schema.Date.annotations({ jsonSchema: { \"type\": \"number\", \"const\": 1 } }), {\n          \"type\": \"number\",\n          \"const\": 1\n        })\n        await assertDraft7(Schema.Date.annotations({ jsonSchema: { \"type\": \"number\", \"enum\": [1] } }), {\n          \"type\": \"number\",\n          \"enum\": [1]\n        })\n      })\n\n      it(\"refinement of a transformation without an override annotation\", async () => {\n        await assertDraft7(Schema.Trim.pipe(Schema.nonEmptyString()), {\n          \"type\": \"string\",\n          \"description\": \"a string that will be trimmed\"\n        })\n        await assertDraft7(\n          Schema.Trim.pipe(Schema.nonEmptyString({ jsonSchema: { title: \"a0ba6c10-091e-4ceb-9773-25fb1466fb1b\" } })),\n          {\n            \"type\": \"string\",\n            \"description\": \"a string that will be trimmed\"\n          }\n        )\n        await assertDraft7(\n          Schema.Trim.pipe(Schema.nonEmptyString()).annotations({\n            jsonSchema: { title: \"75f7eb4f-626d-4dc6-af48-c17094418d85\" }\n          }),\n          {\n            \"type\": \"string\",\n            \"description\": \"a string that will be trimmed\"\n          }\n        )\n      })\n\n      it(\"should detect a fragment on a non-refinement schema\", async () => {\n        const schema = Schema.UUID.pipe(\n          Schema.compose(Schema.String),\n          Schema.annotations({\n            identifier: \"UUID\",\n            title: \"title\",\n            description: \"description\",\n            jsonSchema: {\n              format: \"uuid\" // fragment\n            }\n          })\n        )\n        await assertDraft7(\n          schema,\n          {\n            \"$defs\": {\n              \"UUID\": {\n                \"type\": \"string\",\n                \"description\": \"description\",\n                \"title\": \"title\",\n                \"format\": \"uuid\",\n                \"pattern\": \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\"\n              }\n            },\n            \"$ref\": \"#/$defs/UUID\"\n          }\n        )\n      })\n    })\n\n    describe(\"Pruning `undefined` and make the property optional by default\", () => {\n      it(\"Undefined\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.Undefined\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"$id\": \"/schemas/never\",\n                \"not\": {},\n                \"title\": \"never\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"UndefinedOr(Undefined)\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.UndefinedOr(Schema.Undefined)\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"$id\": \"/schemas/never\",\n                \"not\": {},\n                \"title\": \"never\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"Nested `Undefined`s\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.UndefinedOr(Schema.UndefinedOr(Schema.Undefined))\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"$id\": \"/schemas/never\",\n                \"not\": {},\n                \"title\": \"never\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"Schema.optional\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.optional(Schema.String)\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": { \"type\": \"string\" }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"Schema.optional + inner annotation\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.optional(Schema.String.annotations({ description: \"inner\" }))\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\",\n                \"description\": \"inner\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"Schema.optional + outer annotation should override inner annotation\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.optional(Schema.String.annotations({ description: \"inner\" })).annotations({\n              description: \"outer\"\n            })\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\",\n                \"description\": \"outer\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"UndefinedOr\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.UndefinedOr(Schema.String)\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"UndefinedOr + inner annotation\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.UndefinedOr(Schema.String.annotations({ description: \"inner\" }))\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\",\n                \"description\": \"inner\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"UndefinedOr + annotation should not override inner annotations\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.UndefinedOr(Schema.String.annotations({ description: \"inner\" })).annotations({\n              description: \"middle\"\n            })\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\",\n                \"description\": \"inner\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"UndefinedOr + propertySignature annotation should override inner and middle annotations\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.propertySignature(\n              Schema.UndefinedOr(Schema.String.annotations({ description: \"inner\" })).annotations({\n                description: \"middle\"\n              })\n            ).annotations({ description: \"outer\" })\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\",\n                \"description\": \"outer\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"UndefinedOr + jsonSchema annotation should keep the property required\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.UndefinedOr(Schema.String).annotations({ jsonSchema: { \"type\": \"string\" } })\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [\"a\"],\n            \"properties\": {\n              \"a\": { \"type\": \"string\" }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"Transformation: OptionFromUndefinedOr\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.OptionFromUndefinedOr(Schema.String)\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n\n      it(\"Suspend\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.suspend(() => Schema.UndefinedOr(Schema.String))\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        )\n      })\n    })\n\n    describe(\"fromKey\", () => {\n      it(\"with transformation identifier annotation\", async () => {\n        await assertDraft7(\n          Schema.Struct({\n            a: Schema.NonEmptyString.pipe(Schema.propertySignature, Schema.fromKey(\"b\"))\n          }).annotations({\n            identifier: \"ID\",\n            description: \"struct-description\"\n          }),\n          {\n            \"$ref\": \"#/$defs/ID\",\n            \"$defs\": {\n              \"NonEmptyString\": {\n                \"type\": \"string\",\n                \"title\": \"nonEmptyString\",\n                \"description\": \"a non empty string\",\n                \"minLength\": 1\n              },\n              \"ID\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"b\"\n                ],\n                \"properties\": {\n                  \"b\": {\n                    \"$ref\": \"#/$defs/NonEmptyString\"\n                  }\n                },\n                \"additionalProperties\": false,\n                \"description\": \"struct-description\"\n              }\n            }\n          }\n        )\n      })\n    })\n  })\n\n  describe(\"jsonSchema2019-09\", () => {\n    describe(\"nullable handling\", () => {\n      it(\"Null\", async () => {\n        const schema = Schema.Null\n        await assertDraft201909(schema, { \"type\": \"null\" })\n      })\n\n      it(\"NullOr(String)\", async () => {\n        const schema = Schema.NullOr(Schema.String)\n        await assertDraft201909(schema, {\n          \"anyOf\": [\n            { \"type\": \"string\" },\n            { \"type\": \"null\" }\n          ]\n        })\n      })\n\n      it(\"NullOr(Any)\", async () => {\n        const schema = Schema.NullOr(Schema.Any)\n        await assertDraft201909(schema, {\n          \"$id\": \"/schemas/any\",\n          \"title\": \"any\"\n        })\n      })\n\n      it(\"NullOr(Unknown)\", async () => {\n        const schema = Schema.NullOr(Schema.Unknown)\n        await assertDraft201909(schema, {\n          \"$id\": \"/schemas/unknown\",\n          \"title\": \"unknown\"\n        })\n      })\n\n      it(\"NullOr(Void)\", async () => {\n        const schema = Schema.NullOr(Schema.Void)\n        await assertDraft201909(schema, {\n          \"$id\": \"/schemas/void\",\n          \"title\": \"void\"\n        })\n      })\n\n      it(\"Literal | null\", async () => {\n        const schema = Schema.Literal(\"a\", null)\n        await assertDraft201909(schema, {\n          \"anyOf\": [\n            {\n              \"type\": \"string\",\n              \"enum\": [\"a\"]\n            },\n            { \"type\": \"null\" }\n          ]\n        })\n      })\n\n      it(\"Literal | null(with description)\", async () => {\n        const schema = Schema.Union(Schema.Literal(\"a\"), Schema.Null.annotations({ description: \"mydescription\" }))\n        await assertDraft201909(schema, {\n          \"anyOf\": [\n            {\n              \"type\": \"string\",\n              \"enum\": [\"a\"]\n            },\n            {\n              \"type\": \"null\",\n              \"description\": \"mydescription\"\n            }\n          ]\n        })\n      })\n\n      it(\"Nested nullable unions\", async () => {\n        const schema = Schema.Union(Schema.NullOr(Schema.String), Schema.Literal(\"a\", null))\n        await assertDraft201909(schema, {\n          \"anyOf\": [\n            {\n              \"anyOf\": [\n                { \"type\": \"string\" },\n                { \"type\": \"null\" }\n              ]\n            },\n            {\n              \"anyOf\": [\n                { \"type\": \"string\", \"enum\": [\"a\"] },\n                { \"type\": \"null\" }\n              ]\n            }\n          ]\n        })\n      })\n    })\n\n    it(\"parseJson handling\", async () => {\n      const schema = Schema.parseJson(Schema.Struct({\n        a: Schema.parseJson(Schema.NumberFromString)\n      }))\n      await assertDraft201909(\n        schema,\n        {\n          \"type\": \"string\",\n          \"contentMediaType\": \"application/json\",\n          \"contentSchema\": {\n            \"type\": \"object\",\n            \"required\": [\"a\"],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\",\n                \"contentMediaType\": \"application/json\",\n                \"contentSchema\": {\n                  \"$ref\": \"#/$defs/NumberFromString\"\n                }\n              }\n            },\n            \"additionalProperties\": false\n          }\n        }\n      )\n    })\n  })\n\n  describe(\"openApi3.1\", () => {\n    describe(\"nullable handling\", () => {\n      it(\"Null\", async () => {\n        const schema = Schema.Null\n        await assertOpenApi3_1(schema, { \"type\": \"null\" })\n      })\n\n      it(\"NullOr(String)\", async () => {\n        const schema = Schema.NullOr(Schema.String)\n        await assertOpenApi3_1(schema, {\n          \"anyOf\": [\n            { \"type\": \"string\" },\n            { \"type\": \"null\" }\n          ]\n        })\n      })\n\n      it(\"NullOr(Any)\", async () => {\n        const schema = Schema.NullOr(Schema.Any)\n        await assertOpenApi3_1(schema, {\n          \"$id\": \"/schemas/any\",\n          \"title\": \"any\"\n        })\n      })\n\n      it(\"NullOr(Unknown)\", async () => {\n        const schema = Schema.NullOr(Schema.Unknown)\n        await assertOpenApi3_1(schema, {\n          \"$id\": \"/schemas/unknown\",\n          \"title\": \"unknown\"\n        })\n      })\n\n      it(\"NullOr(Void)\", async () => {\n        const schema = Schema.NullOr(Schema.Void)\n        await assertOpenApi3_1(schema, {\n          \"$id\": \"/schemas/void\",\n          \"title\": \"void\"\n        })\n      })\n\n      it(\"Literal | null\", async () => {\n        const schema = Schema.Literal(\"a\", null)\n        await assertOpenApi3_1(schema, {\n          \"anyOf\": [\n            {\n              \"type\": \"string\",\n              \"enum\": [\"a\"]\n            },\n            { \"type\": \"null\" }\n          ]\n        })\n      })\n\n      it(\"Literal | null(with description)\", async () => {\n        const schema = Schema.Union(Schema.Literal(\"a\"), Schema.Null.annotations({ description: \"mydescription\" }))\n        await assertOpenApi3_1(schema, {\n          \"anyOf\": [\n            {\n              \"type\": \"string\",\n              \"enum\": [\"a\"]\n            },\n            {\n              \"type\": \"null\",\n              \"description\": \"mydescription\"\n            }\n          ]\n        })\n      })\n\n      it(\"Nested nullable unions\", async () => {\n        const schema = Schema.Union(Schema.NullOr(Schema.String), Schema.Literal(\"a\", null))\n        await assertOpenApi3_1(schema, {\n          \"anyOf\": [\n            {\n              \"anyOf\": [\n                { \"type\": \"string\" },\n                { \"type\": \"null\" }\n              ]\n            },\n            {\n              \"anyOf\": [\n                { \"type\": \"string\", \"enum\": [\"a\"] },\n                { \"type\": \"null\" }\n              ]\n            }\n          ]\n        })\n      })\n    })\n\n    it(\"parseJson handling\", async () => {\n      const schema = Schema.parseJson(Schema.Struct({\n        a: Schema.parseJson(Schema.NumberFromString)\n      }))\n      await assertOpenApi3_1(\n        schema,\n        {\n          \"type\": \"string\",\n          \"contentMediaType\": \"application/json\",\n          \"contentSchema\": {\n            \"type\": \"object\",\n            \"required\": [\"a\"],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\",\n                \"contentMediaType\": \"application/json\",\n                \"contentSchema\": {\n                  \"$ref\": \"#/$defs/NumberFromString\"\n                }\n              }\n            },\n            \"additionalProperties\": false\n          }\n        }\n      )\n    })\n  })\n})\n\ndescribe(\"jsonSchema2020-12\", () => {\n  describe(\"Tuple\", () => {\n    it(\"empty tuple\", async () => {\n      const schema = Schema.Tuple()\n      await assertDraft2020_12(schema, {\n        \"type\": \"array\",\n        \"maxItems\": 0\n      })\n    })\n\n    it(\"element\", async () => {\n      const schema = Schema.Tuple(Schema.Number)\n      await assertDraft2020_12(schema, {\n        \"type\": \"array\",\n        \"prefixItems\": [{\n          \"type\": \"number\"\n        }],\n        \"minItems\": 1,\n        \"items\": false\n      })\n    })\n\n    it(\"element + inner annotations\", async () => {\n      await assertDraft2020_12(\n        Schema.Tuple(Schema.Number.annotations({ description: \"inner\" })),\n        {\n          \"type\": \"array\",\n          \"prefixItems\": [{\n            \"type\": \"number\",\n            \"description\": \"inner\"\n          }],\n          \"minItems\": 1,\n          \"items\": false\n        }\n      )\n    })\n\n    it(\"element + outer annotations should override inner annotations\", async () => {\n      await assertDraft2020_12(\n        Schema.Tuple(\n          Schema.element(Schema.Number.annotations({ description: \"inner\" })).annotations({ description: \"outer\" })\n        ),\n        {\n          \"type\": \"array\",\n          \"prefixItems\": [{\n            \"type\": \"number\",\n            \"description\": \"outer\"\n          }],\n          \"minItems\": 1,\n          \"items\": false\n        }\n      )\n    })\n\n    it(\"optionalElement\", async () => {\n      const schema = Schema.Tuple(Schema.optionalElement(Schema.Number))\n      await assertDraft2020_12(schema, {\n        \"type\": \"array\",\n        \"minItems\": 0,\n        \"prefixItems\": [\n          {\n            \"type\": \"number\"\n          }\n        ],\n        \"items\": false\n      })\n    })\n\n    it(\"optionalElement + inner annotations\", async () => {\n      await assertDraft2020_12(\n        Schema.Tuple(Schema.optionalElement(Schema.Number).annotations({ description: \"inner\" })),\n        {\n          \"type\": \"array\",\n          \"minItems\": 0,\n          \"prefixItems\": [\n            {\n              \"type\": \"number\",\n              \"description\": \"inner\"\n            }\n          ],\n          \"items\": false\n        }\n      )\n    })\n\n    it(\"optionalElement + outer annotations should override inner annotations\", async () => {\n      await assertDraft2020_12(\n        Schema.Tuple(\n          Schema.optionalElement(Schema.Number).annotations({ description: \"inner\" }).annotations({\n            description: \"outer\"\n          })\n        ),\n        {\n          \"type\": \"array\",\n          \"minItems\": 0,\n          \"prefixItems\": [\n            {\n              \"type\": \"number\",\n              \"description\": \"outer\"\n            }\n          ],\n          \"items\": false\n        }\n      )\n    })\n\n    it(\"element + optionalElement\", async () => {\n      const schema = Schema.Tuple(\n        Schema.element(Schema.String.annotations({ description: \"inner\" })).annotations({ description: \"outer\" }),\n        Schema.optionalElement(Schema.Number.annotations({ description: \"inner?\" })).annotations({\n          description: \"outer?\"\n        })\n      )\n      await assertDraft2020_12(schema, {\n        \"type\": \"array\",\n        \"minItems\": 1,\n        \"prefixItems\": [\n          {\n            \"type\": \"string\",\n            \"description\": \"outer\"\n          },\n          {\n            \"type\": \"number\",\n            \"description\": \"outer?\"\n          }\n        ],\n        \"items\": false\n      })\n    })\n\n    it(\"rest\", async () => {\n      const schema = Schema.Array(Schema.Number)\n      await assertDraft2020_12(schema, {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"number\"\n        }\n      })\n    })\n\n    it(\"rest + inner annotations\", async () => {\n      await assertDraft2020_12(Schema.Array(Schema.Number.annotations({ description: \"inner\" })), {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"number\",\n          \"description\": \"inner\"\n        }\n      })\n    })\n\n    it(\"optionalElement + rest + inner annotations\", async () => {\n      const schema = Schema.Tuple(\n        [Schema.optionalElement(Schema.String)],\n        Schema.element(Schema.Number.annotations({ description: \"inner\" }))\n      )\n      await assertDraft2020_12(schema, {\n        \"type\": \"array\",\n        \"minItems\": 0,\n        \"prefixItems\": [\n          {\n            \"type\": \"string\"\n          }\n        ],\n        \"items\": {\n          \"type\": \"number\",\n          \"description\": \"inner\"\n        }\n      })\n    })\n\n    it(\"optionalElement + rest + outer annotations should override inner annotations\", async () => {\n      await assertDraft2020_12(\n        Schema.Tuple(\n          [Schema.optionalElement(Schema.String)],\n          Schema.element(Schema.Number.annotations({ description: \"inner\" })).annotations({ description: \"outer\" })\n        ),\n        {\n          \"type\": \"array\",\n          \"minItems\": 0,\n          \"prefixItems\": [\n            {\n              \"type\": \"string\"\n            }\n          ],\n          \"items\": {\n            \"type\": \"number\",\n            \"description\": \"outer\"\n          }\n        }\n      )\n    })\n\n    it(\"element + rest\", async () => {\n      const schema = Schema.Tuple([Schema.String], Schema.Number)\n      await assertDraft2020_12(schema, {\n        \"type\": \"array\",\n        \"prefixItems\": [{\n          \"type\": \"string\"\n        }],\n        \"minItems\": 1,\n        \"items\": {\n          \"type\": \"number\"\n        }\n      })\n    })\n\n    it(\"NonEmptyArray\", async () => {\n      await assertDraft2020_12(\n        Schema.NonEmptyArray(Schema.String),\n        {\n          type: \"array\",\n          minItems: 1,\n          items: { type: \"string\" }\n        }\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/JSONSchema.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, throws } from \"@effect/vitest/utils\"\nimport Ajv from \"ajv\"\nimport * as A from \"effect/Arbitrary\"\nimport * as fc from \"effect/FastCheck\"\nimport * as JSONSchema from \"effect/JSONSchema\"\nimport * as Schema from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ntype Root = JSONSchema.JsonSchema7Root\n\nconst ajvOptions: Ajv.Options = {\n  strictTuples: false,\n  allowMatchingProperties: true\n}\n\nconst getAjvValidate = (jsonSchema: Root): Ajv.ValidateFunction =>\n  // new instance of Ajv is created for each schema to avoid error: \"schema with key or id \"/schemas/any\" already exists\"\n  new Ajv.default(ajvOptions).compile(jsonSchema)\n\nconst expectProperty = <A, I>(\n  schema: Schema.Schema<A, I>,\n  jsonSchema: JSONSchema.JsonSchema7,\n  params?: fc.Parameters<[I]>\n) => {\n  if (false as boolean) {\n    const encodedBoundSchema = Schema.encodedBoundSchema(schema)\n    const arb = A.make(encodedBoundSchema)\n    const is = Schema.is(encodedBoundSchema)\n    const validate = getAjvValidate(jsonSchema)\n    fc.assert(fc.property(arb, (i) => is(i) && validate(i)), params)\n  }\n}\n\nconst expectJSONSchema = <A, I>(\n  schema: Schema.Schema<A, I>,\n  expectedJsonSchema: object\n) => {\n  const jsonSchema = JSONSchema.make(schema)\n  deepStrictEqual(jsonSchema, {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    ...expectedJsonSchema\n  } as any)\n  return jsonSchema\n}\n\nconst expectJSONSchema2019 = <A, I>(\n  schema: Schema.Schema<A, I>,\n  expectedJsonSchema: object,\n  expectedDefinitions: object\n) => {\n  const definitions = {}\n  const jsonSchema = JSONSchema.fromAST(schema.ast, {\n    definitions,\n    target: \"jsonSchema2019-09\"\n  })\n  deepStrictEqual(jsonSchema, expectedJsonSchema)\n  deepStrictEqual(definitions, expectedDefinitions)\n  return jsonSchema\n}\n\nconst expectJSONSchemaOpenApi31 = <A, I>(\n  schema: Schema.Schema<A, I>,\n  expectedJsonSchema: object,\n  expectedDefinitions: object\n) => {\n  const definitions = {}\n  const jsonSchema = JSONSchema.fromAST(schema.ast, {\n    definitions,\n    target: \"openApi3.1\"\n  })\n  deepStrictEqual(jsonSchema, expectedJsonSchema)\n  deepStrictEqual(definitions, expectedDefinitions)\n  return jsonSchema\n}\n\nconst expectJSONSchemaProperty = <A, I>(\n  schema: Schema.Schema<A, I>,\n  expected: object,\n  params?: fc.Parameters<[I]>\n) => {\n  const jsonSchema = expectJSONSchema(schema, expected)\n  expectProperty(schema, jsonSchema, params)\n}\n\nconst expectJSONSchemaAnnotations = <A, I>(\n  schema: Schema.Schema<A, I>,\n  expected: object,\n  params?: fc.Parameters<[I]>\n) => {\n  expectJSONSchemaProperty(schema, expected, params)\n  const jsonSchemaAnnotations = {\n    description: \"269d3e58-8fb2-43cb-a389-8146c353fdd5\",\n    title: \"5401c637-61f2-49b8-b74d-17f058c2670f\"\n  }\n  expectJSONSchemaProperty(schema.annotations(jsonSchemaAnnotations), { ...expected, ...jsonSchemaAnnotations }, params)\n}\n\nconst expectError = <A, I>(schema: Schema.Schema<A, I>, message: string) => {\n  throws(() => JSONSchema.make(schema), new Error(message))\n}\n\n// Using this instead of Schema.JsonNumber to avoid cluttering the output with unnecessary description and title\nconst JsonNumber = Schema.Number.pipe(Schema.filter((n) => Number.isFinite(n), { jsonSchema: {} }))\n\ndescribe(\"fromAST\", () => {\n  it(\"definitionsPath\", () => {\n    const schema = Schema.String.annotations({ identifier: \"08368672-2c02-4d6d-92b0-dd0019b33a7b\" })\n    const definitions = {}\n    const jsonSchema = JSONSchema.fromAST(schema.ast, {\n      definitions,\n      definitionPath: \"#/components/schemas/\"\n    })\n    deepStrictEqual(jsonSchema, {\n      \"$ref\": \"#/components/schemas/08368672-2c02-4d6d-92b0-dd0019b33a7b\"\n    })\n    deepStrictEqual(definitions, {\n      \"08368672-2c02-4d6d-92b0-dd0019b33a7b\": {\n        \"type\": \"string\"\n      }\n    })\n  })\n\n  describe(\"target\", () => {\n    describe(\"jsonSchema7\", () => {\n      describe(\"nullable handling\", () => {\n        it(\"Null\", () => {\n          const schema = Schema.Null\n          expectJSONSchemaAnnotations(schema, { \"type\": \"null\" })\n        })\n\n        it(\"NullOr(String)\", () => {\n          const schema = Schema.NullOr(Schema.String)\n          expectJSONSchemaAnnotations(schema, {\n            \"anyOf\": [\n              { \"type\": \"string\" },\n              { \"type\": \"null\" }\n            ]\n          })\n        })\n\n        it(\"NullOr(Any)\", () => {\n          const schema = Schema.NullOr(Schema.Any)\n          expectJSONSchemaAnnotations(schema, {\n            \"$id\": \"/schemas/any\",\n            \"title\": \"any\"\n          })\n        })\n\n        it(\"NullOr(Unknown)\", () => {\n          const schema = Schema.NullOr(Schema.Unknown)\n          expectJSONSchemaAnnotations(schema, {\n            \"$id\": \"/schemas/unknown\",\n            \"title\": \"unknown\"\n          })\n        })\n\n        it(\"NullOr(Void)\", () => {\n          const schema = Schema.NullOr(Schema.Void)\n          expectJSONSchemaAnnotations(schema, {\n            \"$id\": \"/schemas/void\",\n            \"title\": \"void\"\n          })\n        })\n\n        it(\"Literal | null\", () => {\n          const schema = Schema.Literal(\"a\", null)\n          expectJSONSchemaAnnotations(schema, {\n            \"anyOf\": [\n              {\n                \"type\": \"string\",\n                \"enum\": [\"a\"]\n              },\n              { \"type\": \"null\" }\n            ]\n          })\n        })\n\n        it(\"Literal | null(with description)\", () => {\n          const schema = Schema.Union(Schema.Literal(\"a\"), Schema.Null.annotations({ description: \"mydescription\" }))\n          expectJSONSchemaAnnotations(schema, {\n            \"anyOf\": [\n              {\n                \"type\": \"string\",\n                \"enum\": [\"a\"]\n              },\n              {\n                \"type\": \"null\",\n                \"description\": \"mydescription\"\n              }\n            ]\n          })\n        })\n\n        it(\"Nested nullable unions\", () => {\n          const schema = Schema.Union(Schema.NullOr(Schema.String), Schema.Literal(\"a\", null))\n          expectJSONSchemaAnnotations(schema, {\n            \"anyOf\": [\n              {\n                \"anyOf\": [\n                  { \"type\": \"string\" },\n                  { \"type\": \"null\" }\n                ]\n              },\n              {\n                \"anyOf\": [\n                  { \"type\": \"string\", \"enum\": [\"a\"] },\n                  { \"type\": \"null\" }\n                ]\n              }\n            ]\n          })\n        })\n      })\n\n      it(\"parseJson handling\", () => {\n        const schema = Schema.parseJson(Schema.Struct({\n          a: Schema.parseJson(Schema.NumberFromString)\n        }))\n        const definitions = {}\n        const jsonSchema = JSONSchema.fromAST(schema.ast, {\n          definitions\n        })\n        deepStrictEqual(jsonSchema, {\n          \"type\": \"string\",\n          \"contentMediaType\": \"application/json\"\n        })\n        deepStrictEqual(definitions, {})\n      })\n    })\n\n    describe(\"jsonSchema2019-09\", () => {\n      describe(\"nullable handling\", () => {\n        it(\"Null\", () => {\n          const schema = Schema.Null\n          expectJSONSchema2019(schema, { \"type\": \"null\" }, {})\n        })\n\n        it(\"NullOr(String)\", () => {\n          const schema = Schema.NullOr(Schema.String)\n          expectJSONSchema2019(schema, {\n            \"anyOf\": [\n              { \"type\": \"string\" },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"NullOr(Any)\", () => {\n          const schema = Schema.NullOr(Schema.Any)\n          expectJSONSchema2019(schema, {\n            \"$id\": \"/schemas/any\",\n            \"title\": \"any\"\n          }, {})\n        })\n\n        it(\"NullOr(Unknown)\", () => {\n          const schema = Schema.NullOr(Schema.Unknown)\n          expectJSONSchema2019(schema, {\n            \"$id\": \"/schemas/unknown\",\n            \"title\": \"unknown\"\n          }, {})\n        })\n\n        it(\"NullOr(Void)\", () => {\n          const schema = Schema.NullOr(Schema.Void)\n          expectJSONSchema2019(schema, {\n            \"$id\": \"/schemas/void\",\n            \"title\": \"void\"\n          }, {})\n        })\n\n        it(\"Literal | null\", () => {\n          const schema = Schema.Literal(\"a\", null)\n          expectJSONSchema2019(schema, {\n            \"anyOf\": [\n              {\n                \"type\": \"string\",\n                \"enum\": [\"a\"]\n              },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"Literal | null(with description)\", () => {\n          const schema = Schema.Union(Schema.Literal(\"a\"), Schema.Null.annotations({ description: \"mydescription\" }))\n          expectJSONSchema2019(schema, {\n            \"anyOf\": [\n              {\n                \"type\": \"string\",\n                \"enum\": [\"a\"]\n              },\n              {\n                \"type\": \"null\",\n                \"description\": \"mydescription\"\n              }\n            ]\n          }, {})\n        })\n\n        it(\"Nested nullable unions\", () => {\n          const schema = Schema.Union(Schema.NullOr(Schema.String), Schema.Literal(\"a\", null))\n          expectJSONSchema2019(schema, {\n            \"anyOf\": [\n              {\n                \"anyOf\": [\n                  { \"type\": \"string\" },\n                  { \"type\": \"null\" }\n                ]\n              },\n              {\n                \"anyOf\": [\n                  { \"type\": \"string\", \"enum\": [\"a\"] },\n                  { \"type\": \"null\" }\n                ]\n              }\n            ]\n          }, {})\n        })\n      })\n\n      it(\"parseJson handling\", () => {\n        const schema = Schema.parseJson(Schema.Struct({\n          a: Schema.parseJson(Schema.NumberFromString)\n        }))\n        expectJSONSchema2019(schema, {\n          \"type\": \"string\",\n          \"contentMediaType\": \"application/json\",\n          \"contentSchema\": {\n            \"type\": \"object\",\n            \"required\": [\"a\"],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\",\n                \"contentMediaType\": \"application/json\",\n                \"contentSchema\": {\n                  \"$ref\": \"#/$defs/NumberFromString\"\n                }\n              }\n            },\n            \"additionalProperties\": false\n          }\n        }, {\n          \"NumberFromString\": {\n            \"description\": \"a string to be decoded into a number\",\n            \"type\": \"string\"\n          }\n        })\n      })\n    })\n\n    describe(\"openApi3.1\", () => {\n      describe(\"nullable handling\", () => {\n        it(\"Null\", () => {\n          const schema = Schema.Null\n          expectJSONSchemaOpenApi31(schema, { \"type\": \"null\" }, {})\n        })\n\n        it(\"NullOr(String)\", () => {\n          const schema = Schema.NullOr(Schema.String)\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              { \"type\": \"string\" },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"NullOr(Any)\", () => {\n          const schema = Schema.NullOr(Schema.Any)\n          expectJSONSchemaOpenApi31(schema, {\n            \"$id\": \"/schemas/any\",\n            \"title\": \"any\"\n          }, {})\n        })\n\n        it(\"NullOr(Unknown)\", () => {\n          const schema = Schema.NullOr(Schema.Unknown)\n          expectJSONSchemaOpenApi31(schema, {\n            \"$id\": \"/schemas/unknown\",\n            \"title\": \"unknown\"\n          }, {})\n        })\n\n        it(\"NullOr(Void)\", () => {\n          const schema = Schema.NullOr(Schema.Void)\n          expectJSONSchemaOpenApi31(schema, {\n            \"$id\": \"/schemas/void\",\n            \"title\": \"void\"\n          }, {})\n        })\n\n        it(\"NullOr(Object)\", () => {\n          const schema = Schema.NullOr(Schema.Object)\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"$id\": \"/schemas/object\",\n                \"anyOf\": [\n                  { \"type\": \"object\" },\n                  { \"type\": \"array\" }\n                ],\n                \"description\": \"an object in the TypeScript meaning, i.e. the `object` type\",\n                \"title\": \"object\"\n              },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"NullOr(Struct({}))\", () => {\n          const schema = Schema.NullOr(Schema.Struct({}))\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"$id\": \"/schemas/%7B%7D\",\n                \"anyOf\": [\n                  { \"type\": \"object\" },\n                  { \"type\": \"array\" }\n                ]\n              },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"NullOr(Ref)\", () => {\n          const schema = Schema.NullOr(\n            Schema.String.annotations({ identifier: \"b812aaa1-cfe1-4dda-8c9c-360bfa6cb855\" })\n          )\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"$ref\": \"#/$defs/b812aaa1-cfe1-4dda-8c9c-360bfa6cb855\"\n              },\n              { \"type\": \"null\" }\n            ]\n          }, {\n            \"b812aaa1-cfe1-4dda-8c9c-360bfa6cb855\": {\n              \"type\": \"string\"\n            }\n          })\n        })\n\n        it(\"NullOr(Number)\", () => {\n          const schema = Schema.NullOr(Schema.Number)\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              { \"type\": \"number\" },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"NullOr(Int)\", () => {\n          const schema = Schema.NullOr(Schema.Int)\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"$ref\": \"#/$defs/Int\"\n              },\n              { \"type\": \"null\" }\n            ]\n          }, {\n            \"Int\": {\n              \"title\": \"int\",\n              \"description\": \"an integer\",\n              \"type\": \"integer\"\n            }\n          })\n        })\n\n        it(\"NullOr(Boolean)\", () => {\n          const schema = Schema.NullOr(Schema.Boolean)\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              { \"type\": \"boolean\" },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"NullOr(Array)\", () => {\n          const schema = Schema.NullOr(Schema.Array(Schema.String))\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"items\": { \"type\": \"string\" },\n                \"type\": \"array\"\n              },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"NullOr(Enum)\", () => {\n          enum Fruits {\n            Apple,\n            Banana\n          }\n          const schema = Schema.NullOr(Schema.Enums(Fruits))\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"$comment\": \"/schemas/enums\",\n                \"anyOf\": [\n                  {\n                    \"type\": \"number\",\n                    \"title\": \"Apple\",\n                    \"enum\": [0]\n                  },\n                  {\n                    \"type\": \"number\",\n                    \"title\": \"Banana\",\n                    \"enum\": [1]\n                  }\n                ]\n              },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"NullOr(Literal)\", () => {\n          const schema = Schema.NullOr(Schema.Literal(\"a\"))\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"type\": \"string\",\n                \"enum\": [\"a\"]\n              },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"Literal | null\", () => {\n          const schema = Schema.Literal(\"a\", null)\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"type\": \"string\",\n                \"enum\": [\"a\"]\n              },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n\n        it(\"Literal | null(with description)\", () => {\n          const schema = Schema.Union(Schema.Literal(\"a\"), Schema.Null.annotations({ description: \"mydescription\" }))\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"type\": \"string\",\n                \"enum\": [\"a\"]\n              },\n              {\n                \"description\": \"mydescription\",\n                \"type\": \"null\"\n              }\n            ]\n          }, {})\n        })\n\n        it(\"Nested nullable unions\", () => {\n          const schema = Schema.Union(Schema.NullOr(Schema.String), Schema.Literal(\"a\", null))\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"anyOf\": [\n                  { \"type\": \"string\" },\n                  { \"type\": \"null\" }\n                ]\n              },\n              {\n                \"anyOf\": [\n                  { \"type\": \"string\", \"enum\": [\"a\"] },\n                  { \"type\": \"null\" }\n                ]\n              }\n            ]\n          }, {})\n        })\n\n        it(\"NullOr(Struct({ a: String }))\", () => {\n          const schema = Schema.NullOr(Schema.Struct({ a: Schema.String }))\n          expectJSONSchemaOpenApi31(schema, {\n            \"anyOf\": [\n              {\n                \"additionalProperties\": false,\n                \"properties\": { \"a\": { \"type\": \"string\" } },\n                \"required\": [\"a\"],\n                \"type\": \"object\"\n              },\n              { \"type\": \"null\" }\n            ]\n          }, {})\n        })\n      })\n\n      it(\"parseJson handling\", () => {\n        const schema = Schema.parseJson(Schema.Struct({\n          a: Schema.parseJson(Schema.NumberFromString)\n        }))\n        expectJSONSchemaOpenApi31(schema, {\n          \"type\": \"string\",\n          \"contentMediaType\": \"application/json\",\n          \"contentSchema\": {\n            \"type\": \"object\",\n            \"required\": [\"a\"],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\",\n                \"contentMediaType\": \"application/json\",\n                \"contentSchema\": {\n                  \"$ref\": \"#/$defs/NumberFromString\"\n                }\n              }\n            },\n            \"additionalProperties\": false\n          }\n        }, {\n          \"NumberFromString\": {\n            \"description\": \"a string to be decoded into a number\",\n            \"type\": \"string\"\n          }\n        })\n      })\n    })\n  })\n\n  describe(\"topLevelReferenceStrategy\", () => {\n    it(`\"skip\"`, () => {\n      const schema = Schema.String.annotations({ identifier: \"1b205579-f159-48d4-a218-f09426bca040\" })\n      const definitions = {}\n      const jsonSchema = JSONSchema.fromAST(schema.ast, {\n        definitions,\n        topLevelReferenceStrategy: \"skip\"\n      })\n      deepStrictEqual(jsonSchema, {\n        \"type\": \"string\"\n      })\n      deepStrictEqual(definitions, {})\n    })\n  })\n\n  describe(\"additionalPropertiesStrategy\", () => {\n    it(`\"allow\"`, () => {\n      const schema = Schema.Struct({ a: Schema.String })\n      const definitions = {}\n      const jsonSchema = JSONSchema.fromAST(schema.ast, {\n        definitions,\n        additionalPropertiesStrategy: \"allow\"\n      })\n      deepStrictEqual(jsonSchema, {\n        \"type\": \"object\",\n        \"properties\": {\n          \"a\": {\n            \"type\": \"string\"\n          }\n        },\n        \"required\": [\"a\"],\n        \"additionalProperties\": true\n      })\n      deepStrictEqual(definitions, {})\n    })\n  })\n})\n\ndescribe(\"make\", () => {\n  it(\"should filter out non-JSON values and cyclic references from default and examples\", () => {\n    const cyclic: any = { value: \"test\" }\n    cyclic.self = cyclic\n    const schema = Schema.String.annotations({ default: 1n as any, examples: [\"a\", 1n as any, cyclic, \"b\"] })\n    expectJSONSchemaAnnotations(schema, {\n      \"type\": \"string\",\n      \"examples\": [\"a\", \"b\"]\n    })\n  })\n\n  it(\"handling of a top level `parseJson` should targeting the \\\"to\\\" side\", () => {\n    const schema = Schema.parseJson(Schema.Struct({\n      a: Schema.parseJson(Schema.NumberFromString)\n    }))\n    expectJSONSchema(\n      schema,\n      {\n        \"type\": \"object\",\n        \"required\": [\"a\"],\n        \"properties\": {\n          \"a\": {\n            \"type\": \"string\",\n            \"contentMediaType\": \"application/json\"\n          }\n        },\n        \"additionalProperties\": false\n      }\n    )\n  })\n\n  describe(\"Unsupported schemas\", () => {\n    describe(\"Missing jsonSchema annotation Error\", () => {\n      it(\"Declaration\", () => {\n        expectError(\n          Schema.ChunkFromSelf(JsonNumber),\n          `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (Declaration): Chunk<{ number | filter }>`\n        )\n      })\n\n      it(\"BigIntFromSelf\", () => {\n        expectError(\n          Schema.BigIntFromSelf,\n          `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (BigIntKeyword): bigint`\n        )\n      })\n\n      it(\"SymbolFromSelf\", () => {\n        expectError(\n          Schema.SymbolFromSelf,\n          `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (SymbolKeyword): symbol`\n        )\n      })\n\n      it(\"UniqueSymbolFromSelf\", () => {\n        expectError(\n          Schema.UniqueSymbolFromSelf(Symbol.for(\"effect/Schema/test/a\")),\n          `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (UniqueSymbol): Symbol(effect/Schema/test/a)`\n        )\n      })\n\n      it(\"Undefined\", () => {\n        expectError(\n          Schema.Undefined,\n          `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (UndefinedKeyword): undefined`\n        )\n      })\n\n      it(\"Schema.Literal with a bigint literal\", () => {\n        expectError(\n          Schema.Literal(1n),\n          `Missing annotation\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (Literal): 1n`\n        )\n      })\n\n      it(\"Tuple with an unsupported component\", () => {\n        expectError(\n          Schema.Tuple(Schema.Undefined),\n          `Missing annotation\nat path: [0]\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (UndefinedKeyword): undefined`\n        )\n      })\n\n      it(\"Struct with an unsupported field\", () => {\n        expectError(\n          Schema.Struct({ a: Schema.SymbolFromSelf }),\n          `Missing annotation\nat path: [\"a\"]\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (SymbolKeyword): symbol`\n        )\n      })\n    })\n\n    describe(\"Missing identifier annotation Error\", () => {\n      it(\"Suspend\", () => {\n        interface A {\n          readonly a: string\n          readonly as: ReadonlyArray<A>\n        }\n        const schema = Schema.Struct({\n          a: Schema.String,\n          as: Schema.Array(Schema.suspend((): Schema.Schema<A> => schema))\n        })\n        expectError(\n          schema,\n          `Missing annotation\nat path: [\"as\"]\ndetails: Generating a JSON Schema for this schema requires an \"identifier\" annotation\nschema (Suspend): <suspended schema>`\n        )\n      })\n    })\n\n    describe(\"Unsupported index signature parameter\", () => {\n      it(\"Record(SymbolFromSelf, number)\", () => {\n        expectError(\n          Schema.Record({ key: Schema.SymbolFromSelf, value: JsonNumber }),\n          `Missing annotation\nat path: [\"[symbol]\"]\ndetails: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\nschema (SymbolKeyword): symbol`\n        )\n      })\n    })\n\n    describe(\"Unsupported key\", () => {\n      it(\"should raise an error if there is a property named with a symbol\", () => {\n        const a = Symbol.for(\"effect/Schema/test/a\")\n        expectError(\n          Schema.Struct({ [a]: Schema.String }),\n          `Unsupported key\ndetails: Cannot encode Symbol(effect/Schema/test/a) key to JSON Schema`\n        )\n      })\n    })\n\n    describe(\"Unsupported post-rest elements\", () => {\n      it(\"r e should raise an error\", () => {\n        expectError(\n          Schema.Tuple([], JsonNumber, Schema.String),\n          \"Generating a JSON Schema for post-rest elements is not currently supported. You're welcome to contribute by submitting a Pull Request\"\n        )\n      })\n    })\n  })\n\n  it(\"Never\", () => {\n    const jsonSchema: Root = {\n      \"$id\": \"/schemas/never\",\n      \"not\": {},\n      \"title\": \"never\"\n    }\n    expectJSONSchema(Schema.Never, jsonSchema)\n    const validate = getAjvValidate(jsonSchema)\n    assertFalse(validate(null))\n  })\n\n  it(\"Any\", () => {\n    expectJSONSchemaAnnotations(Schema.Any, {\n      \"$id\": \"/schemas/any\",\n      \"title\": \"any\"\n    })\n  })\n\n  it(\"Unknown\", () => {\n    expectJSONSchemaAnnotations(Schema.Unknown, {\n      \"$id\": \"/schemas/unknown\",\n      \"title\": \"unknown\"\n    })\n  })\n\n  it(\"Object\", () => {\n    const jsonSchema: Root = {\n      \"$id\": \"/schemas/object\",\n      \"anyOf\": [\n        { \"type\": \"object\" },\n        { \"type\": \"array\" }\n      ],\n      \"description\": \"an object in the TypeScript meaning, i.e. the `object` type\",\n      \"title\": \"object\"\n    }\n    expectJSONSchemaAnnotations(Schema.Object, jsonSchema)\n\n    const validate = getAjvValidate(jsonSchema)\n    assertTrue(validate({}))\n    assertTrue(validate({ a: 1 }))\n    assertTrue(validate([]))\n    assertFalse(validate(\"a\"))\n    assertFalse(validate(1))\n    assertFalse(validate(true))\n  })\n\n  it(\"empty struct: Schema.Struct({})\", () => {\n    const schema = Schema.Struct({})\n    const jsonSchema: Root = {\n      \"$id\": \"/schemas/%7B%7D\",\n      \"anyOf\": [{\n        \"type\": \"object\"\n      }, {\n        \"type\": \"array\"\n      }]\n    }\n    expectJSONSchemaAnnotations(schema, jsonSchema)\n    const validate = getAjvValidate(jsonSchema)\n    assertTrue(validate({}))\n    assertTrue(validate({ a: 1 }))\n    assertTrue(validate([]))\n    assertFalse(validate(null))\n    assertFalse(validate(1))\n    assertFalse(validate(true))\n  })\n\n  it(\"Void\", () => {\n    expectJSONSchemaAnnotations(Schema.Void, {\n      \"$id\": \"/schemas/void\",\n      \"title\": \"void\"\n    })\n  })\n\n  it(\"String\", () => {\n    expectJSONSchemaAnnotations(Schema.String, {\n      \"type\": \"string\"\n    })\n  })\n\n  it(\"Number\", () => {\n    expectJSONSchema(Schema.Number, {\n      \"type\": \"number\"\n    })\n  })\n\n  it(\"JsonNumber\", () => {\n    expectJSONSchemaProperty(Schema.JsonNumber, {\n      \"$defs\": {\n        \"JsonNumber\": {\n          \"type\": \"number\",\n          \"title\": \"finite\",\n          \"description\": \"a finite number\"\n        }\n      },\n      \"$ref\": \"#/$defs/JsonNumber\"\n    })\n  })\n\n  it(\"Boolean\", () => {\n    expectJSONSchemaAnnotations(Schema.Boolean, {\n      \"type\": \"boolean\"\n    })\n  })\n\n  it(\"TemplateLiteral\", () => {\n    const schema = Schema.TemplateLiteral(Schema.Literal(\"a\"), Schema.Number)\n    const jsonSchema: Root = {\n      \"type\": \"string\",\n      \"pattern\": \"^a[+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?$\",\n      \"title\": \"`a${number}`\",\n      \"description\": \"a template literal\"\n    }\n    expectJSONSchemaAnnotations(schema, jsonSchema)\n    const validate = getAjvValidate(jsonSchema)\n    assertTrue(validate(\"a1\"))\n    assertTrue(validate(\"a12\"))\n    assertFalse(validate(\"a\"))\n    assertFalse(validate(\"aa\"))\n  })\n\n  describe(\"Literal\", () => {\n    it(\"null literal\", () => {\n      expectJSONSchemaAnnotations(Schema.Null, {\n        \"type\": \"null\"\n      })\n      expectJSONSchemaProperty(Schema.Null.annotations({ identifier: \"9b7d3b2b-3b3a-4741-8c4c-9cae776c47f6\" }), {\n        \"$defs\": {\n          \"9b7d3b2b-3b3a-4741-8c4c-9cae776c47f6\": {\n            \"type\": \"null\"\n          }\n        },\n        \"$ref\": \"#/$defs/9b7d3b2b-3b3a-4741-8c4c-9cae776c47f6\"\n      })\n    })\n\n    it(\"string literals\", () => {\n      expectJSONSchemaAnnotations(Schema.Literal(\"a\"), {\n        \"type\": \"string\",\n        \"enum\": [\"a\"]\n      })\n      expectJSONSchemaAnnotations(Schema.Literal(\"a\", \"b\"), {\n        \"type\": \"string\",\n        \"enum\": [\"a\", \"b\"]\n      })\n    })\n\n    it(\"number literals\", () => {\n      expectJSONSchemaAnnotations(Schema.Literal(1), {\n        \"type\": \"number\",\n        \"enum\": [1]\n      })\n      expectJSONSchemaAnnotations(Schema.Literal(1, 2), {\n        \"type\": \"number\",\n        \"enum\": [1, 2]\n      })\n    })\n\n    it(\"boolean literals\", () => {\n      expectJSONSchemaAnnotations(Schema.Literal(true), {\n        \"type\": \"boolean\",\n        \"enum\": [true]\n      })\n      expectJSONSchemaAnnotations(Schema.Literal(false), {\n        \"type\": \"boolean\",\n        \"enum\": [false]\n      })\n      expectJSONSchemaAnnotations(Schema.Literal(true, false), {\n        \"type\": \"boolean\",\n        \"enum\": [true, false]\n      })\n    })\n\n    it(\"union of literals\", () => {\n      expectJSONSchemaAnnotations(Schema.Literal(1, true), {\n        \"anyOf\": [\n          { \"type\": \"number\", \"enum\": [1] },\n          { \"type\": \"boolean\", \"enum\": [true] }\n        ]\n      })\n    })\n  })\n\n  describe(\"Enums\", () => {\n    it(\"empty enum\", () => {\n      enum Empty {}\n      const jsonSchema = expectJSONSchema(Schema.Enums(Empty), {\n        \"$id\": \"/schemas/never\",\n        \"not\": {}\n      })\n      const validate = getAjvValidate(jsonSchema)\n      assertFalse(validate(1))\n    })\n\n    it(\"single enum\", () => {\n      enum Fruits {\n        Apple\n      }\n      expectJSONSchemaAnnotations(Schema.Enums(Fruits), {\n        \"$comment\": \"/schemas/enums\",\n        \"anyOf\": [\n          {\n            \"type\": \"number\",\n            \"title\": \"Apple\",\n            \"enum\": [0]\n          }\n        ]\n      })\n    })\n\n    it(\"numeric enums\", () => {\n      enum Fruits {\n        Apple,\n        Banana\n      }\n      expectJSONSchemaAnnotations(Schema.Enums(Fruits), {\n        \"$comment\": \"/schemas/enums\",\n        \"anyOf\": [\n          {\n            \"type\": \"number\",\n            \"title\": \"Apple\",\n            \"enum\": [0]\n          },\n          {\n            \"type\": \"number\",\n            \"title\": \"Banana\",\n            \"enum\": [1]\n          }\n        ]\n      })\n    })\n\n    it(\"string enums\", () => {\n      enum Fruits {\n        Apple = \"apple\",\n        Banana = \"banana\"\n      }\n      expectJSONSchemaAnnotations(Schema.Enums(Fruits), {\n        \"$comment\": \"/schemas/enums\",\n        \"anyOf\": [\n          {\n            \"type\": \"string\",\n            \"title\": \"Apple\",\n            \"enum\": [\"apple\"]\n          },\n          {\n            \"type\": \"string\",\n            \"title\": \"Banana\",\n            \"enum\": [\"banana\"]\n          }\n        ]\n      })\n    })\n\n    it(\"mix of string/number enums\", () => {\n      enum Fruits {\n        Apple = \"apple\",\n        Banana = \"banana\",\n        Cantaloupe = 0\n      }\n      expectJSONSchemaAnnotations(Schema.Enums(Fruits), {\n        \"$comment\": \"/schemas/enums\",\n        \"anyOf\": [\n          {\n            \"type\": \"string\",\n            \"title\": \"Apple\",\n            \"enum\": [\"apple\"]\n          },\n          {\n            \"type\": \"string\",\n            \"title\": \"Banana\",\n            \"enum\": [\"banana\"]\n          },\n          {\n            \"type\": \"number\",\n            \"title\": \"Cantaloupe\",\n            \"enum\": [0]\n          }\n        ]\n      })\n    })\n\n    it(\"const enums\", () => {\n      const Fruits = {\n        Apple: \"apple\",\n        Banana: \"banana\",\n        Cantaloupe: 3\n      } as const\n      expectJSONSchemaAnnotations(Schema.Enums(Fruits), {\n        \"$comment\": \"/schemas/enums\",\n        \"anyOf\": [\n          {\n            \"type\": \"string\",\n            \"title\": \"Apple\",\n            \"enum\": [\"apple\"]\n          },\n          {\n            \"type\": \"string\",\n            \"title\": \"Banana\",\n            \"enum\": [\"banana\"]\n          },\n          {\n            \"type\": \"number\",\n            \"title\": \"Cantaloupe\",\n            \"enum\": [3]\n          }\n        ]\n      })\n    })\n  })\n\n  describe(\"Refinement\", () => {\n    it(\"itemsCount (Array)\", () => {\n      expectJSONSchemaAnnotations(Schema.Array(Schema.String).pipe(Schema.itemsCount(2)), {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"string\"\n        },\n        \"description\": \"an array of exactly 2 item(s)\",\n        \"title\": \"itemsCount(2)\",\n        \"minItems\": 2,\n        \"maxItems\": 2\n      })\n    })\n\n    it(\"itemsCount (NonEmptyArray)\", () => {\n      expectJSONSchemaAnnotations(Schema.NonEmptyArray(Schema.String).pipe(Schema.itemsCount(2)), {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"string\"\n        },\n        \"description\": \"an array of exactly 2 item(s)\",\n        \"title\": \"itemsCount(2)\",\n        \"minItems\": 2,\n        \"maxItems\": 2\n      })\n    })\n\n    it(\"minItems (Array)\", () => {\n      expectJSONSchemaAnnotations(Schema.Array(Schema.String).pipe(Schema.minItems(2)), {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"string\"\n        },\n        \"description\": \"an array of at least 2 item(s)\",\n        \"title\": \"minItems(2)\",\n        \"minItems\": 2\n      })\n    })\n\n    it(\"minItems (NonEmptyArray)\", () => {\n      expectJSONSchemaAnnotations(Schema.NonEmptyArray(Schema.String).pipe(Schema.minItems(2)), {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"string\"\n        },\n        \"description\": \"an array of at least 2 item(s)\",\n        \"title\": \"minItems(2)\",\n        \"minItems\": 2\n      })\n    })\n\n    it(\"maxItems (Array)\", () => {\n      expectJSONSchemaAnnotations(Schema.Array(Schema.String).pipe(Schema.maxItems(2)), {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"string\"\n        },\n        \"description\": \"an array of at most 2 item(s)\",\n        \"title\": \"maxItems(2)\",\n        \"maxItems\": 2\n      })\n    })\n\n    it(\"maxItems (NonEmptyArray)\", () => {\n      expectJSONSchemaAnnotations(Schema.NonEmptyArray(Schema.String).pipe(Schema.maxItems(2)), {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"string\"\n        },\n        \"description\": \"an array of at most 2 item(s)\",\n        \"title\": \"maxItems(2)\",\n        \"minItems\": 1,\n        \"maxItems\": 2\n      })\n    })\n\n    it(\"minLength\", () => {\n      expectJSONSchemaAnnotations(Schema.String.pipe(Schema.minLength(1)), {\n        \"type\": \"string\",\n        \"title\": \"minLength(1)\",\n        \"description\": \"a string at least 1 character(s) long\",\n        \"minLength\": 1\n      })\n    })\n\n    it(\"maxLength\", () => {\n      expectJSONSchemaAnnotations(Schema.String.pipe(Schema.maxLength(1)), {\n        \"type\": \"string\",\n        \"title\": \"maxLength(1)\",\n        \"description\": \"a string at most 1 character(s) long\",\n        \"maxLength\": 1\n      })\n    })\n\n    it(\"length: number\", () => {\n      expectJSONSchemaAnnotations(Schema.String.pipe(Schema.length(1)), {\n        \"type\": \"string\",\n        \"title\": \"length(1)\",\n        \"description\": \"a single character\",\n        \"maxLength\": 1,\n        \"minLength\": 1\n      })\n    })\n\n    it(\"length: { min, max }\", () => {\n      expectJSONSchemaAnnotations(Schema.String.pipe(Schema.length({ min: 2, max: 4 })), {\n        \"type\": \"string\",\n        \"title\": \"length({ min: 2, max: 4)\",\n        \"description\": \"a string at least 2 character(s) and at most 4 character(s) long\",\n        \"maxLength\": 4,\n        \"minLength\": 2\n      })\n    })\n\n    it(\"greaterThan\", () => {\n      expectJSONSchemaAnnotations(JsonNumber.pipe(Schema.greaterThan(1)), {\n        \"type\": \"number\",\n        \"title\": \"greaterThan(1)\",\n        \"description\": \"a number greater than 1\",\n        \"exclusiveMinimum\": 1\n      })\n    })\n\n    it(\"greaterThanOrEqualTo\", () => {\n      expectJSONSchemaAnnotations(JsonNumber.pipe(Schema.greaterThanOrEqualTo(1)), {\n        \"type\": \"number\",\n        \"title\": \"greaterThanOrEqualTo(1)\",\n        \"description\": \"a number greater than or equal to 1\",\n        \"minimum\": 1\n      })\n    })\n\n    it(\"lessThan\", () => {\n      expectJSONSchemaAnnotations(JsonNumber.pipe(Schema.lessThan(1)), {\n        \"type\": \"number\",\n        \"title\": \"lessThan(1)\",\n        \"description\": \"a number less than 1\",\n        \"exclusiveMaximum\": 1\n      })\n    })\n\n    it(\"lessThanOrEqualTo\", () => {\n      expectJSONSchemaAnnotations(JsonNumber.pipe(Schema.lessThanOrEqualTo(1)), {\n        \"type\": \"number\",\n        \"title\": \"lessThanOrEqualTo(1)\",\n        \"description\": \"a number less than or equal to 1\",\n        \"maximum\": 1\n      })\n    })\n\n    it(\"pattern\", () => {\n      expectJSONSchemaAnnotations(Schema.String.pipe(Schema.pattern(/^abb+$/)), {\n        \"type\": \"string\",\n        \"description\": \"a string matching the pattern ^abb+$\",\n        \"pattern\": \"^abb+$\"\n      })\n    })\n\n    it(\"int\", () => {\n      expectJSONSchemaAnnotations(JsonNumber.pipe(Schema.int()), {\n        \"type\": \"integer\",\n        \"title\": \"int\",\n        \"description\": \"an integer\"\n      })\n    })\n\n    it(\"Trimmed\", () => {\n      const schema = Schema.Trimmed\n      expectJSONSchemaProperty(schema, {\n        \"$defs\": {\n          \"Trimmed\": {\n            \"title\": \"trimmed\",\n            \"description\": \"a string with no leading or trailing whitespace\",\n            \"pattern\": \"^\\\\S[\\\\s\\\\S]*\\\\S$|^\\\\S$|^$\",\n            \"type\": \"string\"\n          }\n        },\n        \"$ref\": \"#/$defs/Trimmed\"\n      })\n    })\n\n    it(\"Lowercased\", () => {\n      const schema = Schema.Lowercased\n      expectJSONSchemaProperty(schema, {\n        \"$defs\": {\n          \"Lowercased\": {\n            \"title\": \"lowercased\",\n            \"description\": \"a lowercase string\",\n            \"pattern\": \"^[^A-Z]*$\",\n            \"type\": \"string\"\n          }\n        },\n        \"$ref\": \"#/$defs/Lowercased\"\n      })\n    })\n\n    it(\"Uppercased\", () => {\n      const schema = Schema.Uppercased\n      expectJSONSchemaProperty(schema, {\n        \"$defs\": {\n          \"Uppercased\": {\n            \"title\": \"uppercased\",\n            \"description\": \"an uppercase string\",\n            \"pattern\": \"^[^a-z]*$\",\n            \"type\": \"string\"\n          }\n        },\n        \"$ref\": \"#/$defs/Uppercased\"\n      })\n    })\n\n    it(\"Capitalized\", () => {\n      const schema = Schema.Capitalized\n      expectJSONSchemaProperty(schema, {\n        \"$defs\": {\n          \"Capitalized\": {\n            \"title\": \"capitalized\",\n            \"description\": \"a capitalized string\",\n            \"pattern\": \"^[^a-z]?.*$\",\n            \"type\": \"string\"\n          }\n        },\n        \"$ref\": \"#/$defs/Capitalized\"\n      })\n    })\n\n    it(\"Uncapitalized\", () => {\n      const schema = Schema.Uncapitalized\n      expectJSONSchemaProperty(schema, {\n        \"$defs\": {\n          \"Uncapitalized\": {\n            \"title\": \"uncapitalized\",\n            \"description\": \"a uncapitalized string\",\n            \"pattern\": \"^[^A-Z]?.*$\",\n            \"type\": \"string\"\n          }\n        },\n        \"$ref\": \"#/$defs/Uncapitalized\"\n      })\n    })\n\n    describe(\"should handle merge conflicts\", () => {\n      it(\"minLength + minLength\", () => {\n        expectJSONSchemaProperty(Schema.String.pipe(Schema.minLength(1), Schema.minLength(2)), {\n          \"type\": \"string\",\n          \"title\": \"minLength(2)\",\n          \"description\": \"a string at least 2 character(s) long\",\n          \"minLength\": 2\n        })\n        expectJSONSchemaProperty(Schema.String.pipe(Schema.minLength(2), Schema.minLength(1)), {\n          \"type\": \"string\",\n          \"title\": \"minLength(1)\",\n          \"description\": \"a string at least 1 character(s) long\",\n          \"minLength\": 1,\n          \"allOf\": [\n            { \"minLength\": 2 }\n          ]\n        })\n        expectJSONSchemaProperty(Schema.String.pipe(Schema.minLength(2), Schema.minLength(1), Schema.minLength(2)), {\n          \"type\": \"string\",\n          \"title\": \"minLength(2)\",\n          \"description\": \"a string at least 2 character(s) long\",\n          \"minLength\": 2\n        })\n      })\n\n      it(\"maxLength + maxLength\", () => {\n        expectJSONSchemaProperty(Schema.String.pipe(Schema.maxLength(1), Schema.maxLength(2)), {\n          \"type\": \"string\",\n          \"title\": \"maxLength(2)\",\n          \"description\": \"a string at most 2 character(s) long\",\n          \"maxLength\": 2,\n          \"allOf\": [\n            { \"maxLength\": 1 }\n          ]\n        })\n        expectJSONSchemaProperty(Schema.String.pipe(Schema.maxLength(2), Schema.maxLength(1)), {\n          \"type\": \"string\",\n          \"title\": \"maxLength(1)\",\n          \"description\": \"a string at most 1 character(s) long\",\n          \"maxLength\": 1\n        })\n        expectJSONSchemaProperty(Schema.String.pipe(Schema.maxLength(1), Schema.maxLength(2), Schema.maxLength(1)), {\n          \"type\": \"string\",\n          \"title\": \"maxLength(1)\",\n          \"description\": \"a string at most 1 character(s) long\",\n          \"maxLength\": 1\n        })\n      })\n\n      it(\"pattern + pattern\", () => {\n        expectJSONSchemaProperty(Schema.String.pipe(Schema.startsWith(\"a\"), Schema.endsWith(\"c\")), {\n          \"type\": \"string\",\n          \"title\": \"endsWith(\\\"c\\\")\",\n          \"description\": \"a string ending with \\\"c\\\"\",\n          \"pattern\": \"^.*c$\",\n          \"allOf\": [\n            { \"pattern\": \"^a\" }\n          ]\n        })\n        expectJSONSchemaProperty(\n          Schema.String.pipe(Schema.startsWith(\"a\"), Schema.endsWith(\"c\"), Schema.startsWith(\"a\")),\n          {\n            \"type\": \"string\",\n            \"title\": \"startsWith(\\\"a\\\")\",\n            \"description\": \"a string starting with \\\"a\\\"\",\n            \"pattern\": \"^a\",\n            \"allOf\": [\n              { \"pattern\": \"^.*c$\" }\n            ]\n          }\n        )\n        expectJSONSchemaProperty(\n          Schema.String.pipe(Schema.endsWith(\"c\"), Schema.startsWith(\"a\"), Schema.endsWith(\"c\")),\n          {\n            \"type\": \"string\",\n            \"title\": \"endsWith(\\\"c\\\")\",\n            \"description\": \"a string ending with \\\"c\\\"\",\n            \"pattern\": \"^.*c$\",\n            \"allOf\": [\n              { \"pattern\": \"^a\" }\n            ]\n          }\n        )\n      })\n\n      it(\"minItems + minItems\", () => {\n        expectJSONSchemaProperty(Schema.Array(Schema.String).pipe(Schema.minItems(1), Schema.minItems(2)), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"description\": \"an array of at least 2 item(s)\",\n          \"title\": \"minItems(2)\",\n          \"minItems\": 2\n        })\n        expectJSONSchemaProperty(Schema.Array(Schema.String).pipe(Schema.minItems(2), Schema.minItems(1)), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"title\": \"minItems(1)\",\n          \"description\": \"an array of at least 1 item(s)\",\n          \"minItems\": 1,\n          \"allOf\": [\n            { \"minItems\": 2 }\n          ]\n        })\n        expectJSONSchemaProperty(\n          Schema.Array(Schema.String).pipe(Schema.minItems(2), Schema.minItems(1), Schema.minItems(2)),\n          {\n            \"type\": \"array\",\n            \"items\": {\n              \"type\": \"string\"\n            },\n            \"description\": \"an array of at least 2 item(s)\",\n            \"title\": \"minItems(2)\",\n            \"minItems\": 2\n          }\n        )\n      })\n\n      it(\"maxItems + maxItems\", () => {\n        expectJSONSchemaProperty(Schema.Array(Schema.String).pipe(Schema.maxItems(1), Schema.maxItems(2)), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"title\": \"maxItems(2)\",\n          \"description\": \"an array of at most 2 item(s)\",\n          \"maxItems\": 2,\n          \"allOf\": [\n            { \"maxItems\": 1 }\n          ]\n        })\n        expectJSONSchemaProperty(Schema.Array(Schema.String).pipe(Schema.maxItems(2), Schema.maxItems(1)), {\n          \"type\": \"array\",\n          \"items\": {\n            \"type\": \"string\"\n          },\n          \"title\": \"maxItems(1)\",\n          \"description\": \"an array of at most 1 item(s)\",\n          \"maxItems\": 1\n        })\n        expectJSONSchemaProperty(\n          Schema.Array(Schema.String).pipe(Schema.maxItems(1), Schema.maxItems(2), Schema.maxItems(1)),\n          {\n            \"type\": \"array\",\n            \"items\": {\n              \"type\": \"string\"\n            },\n            \"title\": \"maxItems(1)\",\n            \"description\": \"an array of at most 1 item(s)\",\n            \"maxItems\": 1\n          }\n        )\n      })\n\n      it(\"minimum + minimum\", () => {\n        expectJSONSchemaProperty(JsonNumber.pipe(Schema.greaterThanOrEqualTo(1), Schema.greaterThanOrEqualTo(2)), {\n          \"type\": \"number\",\n          \"title\": \"greaterThanOrEqualTo(2)\",\n          \"description\": \"a number greater than or equal to 2\",\n          \"minimum\": 2\n        })\n        expectJSONSchemaProperty(JsonNumber.pipe(Schema.greaterThanOrEqualTo(2), Schema.greaterThanOrEqualTo(1)), {\n          \"type\": \"number\",\n          \"minimum\": 1,\n          \"title\": \"greaterThanOrEqualTo(1)\",\n          \"description\": \"a number greater than or equal to 1\",\n          \"allOf\": [\n            { \"minimum\": 2 }\n          ]\n        })\n        expectJSONSchemaProperty(\n          JsonNumber.pipe(\n            Schema.greaterThanOrEqualTo(2),\n            Schema.greaterThanOrEqualTo(1),\n            Schema.greaterThanOrEqualTo(2)\n          ),\n          {\n            \"type\": \"number\",\n            \"title\": \"greaterThanOrEqualTo(2)\",\n            \"description\": \"a number greater than or equal to 2\",\n            \"minimum\": 2\n          }\n        )\n      })\n\n      it(\"maximum + maximum\", () => {\n        expectJSONSchemaProperty(JsonNumber.pipe(Schema.lessThanOrEqualTo(1), Schema.lessThanOrEqualTo(2)), {\n          \"type\": \"number\",\n          \"title\": \"lessThanOrEqualTo(2)\",\n          \"description\": \"a number less than or equal to 2\",\n          \"maximum\": 2,\n          \"allOf\": [\n            { \"maximum\": 1 }\n          ]\n        })\n        expectJSONSchemaProperty(JsonNumber.pipe(Schema.lessThanOrEqualTo(2), Schema.lessThanOrEqualTo(1)), {\n          \"type\": \"number\",\n          \"title\": \"lessThanOrEqualTo(1)\",\n          \"description\": \"a number less than or equal to 1\",\n          \"maximum\": 1\n        })\n        expectJSONSchemaProperty(\n          JsonNumber.pipe(Schema.lessThanOrEqualTo(1), Schema.lessThanOrEqualTo(2), Schema.lessThanOrEqualTo(1)),\n          {\n            \"type\": \"number\",\n            \"title\": \"lessThanOrEqualTo(1)\",\n            \"description\": \"a number less than or equal to 1\",\n            \"maximum\": 1\n          }\n        )\n      })\n\n      it(\"exclusiveMinimum + exclusiveMinimum\", () => {\n        expectJSONSchemaProperty(JsonNumber.pipe(Schema.greaterThan(1), Schema.greaterThan(2)), {\n          \"type\": \"number\",\n          \"title\": \"greaterThan(2)\",\n          \"description\": \"a number greater than 2\",\n          \"exclusiveMinimum\": 2\n        })\n        expectJSONSchemaProperty(JsonNumber.pipe(Schema.greaterThan(2), Schema.greaterThan(1)), {\n          \"type\": \"number\",\n          \"exclusiveMinimum\": 1,\n          \"title\": \"greaterThan(1)\",\n          \"description\": \"a number greater than 1\",\n          \"allOf\": [\n            { \"exclusiveMinimum\": 2 }\n          ]\n        })\n        expectJSONSchemaProperty(\n          JsonNumber.pipe(\n            Schema.greaterThan(2),\n            Schema.greaterThan(1),\n            Schema.greaterThan(2)\n          ),\n          {\n            \"type\": \"number\",\n            \"title\": \"greaterThan(2)\",\n            \"description\": \"a number greater than 2\",\n            \"exclusiveMinimum\": 2\n          }\n        )\n      })\n\n      it(\"exclusiveMaximum + exclusiveMaximum\", () => {\n        expectJSONSchemaProperty(JsonNumber.pipe(Schema.lessThan(1), Schema.lessThan(2)), {\n          \"type\": \"number\",\n          \"title\": \"lessThan(2)\",\n          \"description\": \"a number less than 2\",\n          \"exclusiveMaximum\": 2,\n          \"allOf\": [\n            { \"exclusiveMaximum\": 1 }\n          ]\n        })\n        expectJSONSchemaProperty(JsonNumber.pipe(Schema.lessThan(2), Schema.lessThan(1)), {\n          \"type\": \"number\",\n          \"title\": \"lessThan(1)\",\n          \"description\": \"a number less than 1\",\n          \"exclusiveMaximum\": 1\n        })\n        expectJSONSchemaProperty(\n          JsonNumber.pipe(Schema.lessThan(1), Schema.lessThan(2), Schema.lessThan(1)),\n          {\n            \"type\": \"number\",\n            \"title\": \"lessThan(1)\",\n            \"description\": \"a number less than 1\",\n            \"exclusiveMaximum\": 1\n          }\n        )\n      })\n\n      it(\"multipleOf + multipleOf\", () => {\n        expectJSONSchema(JsonNumber.pipe(Schema.multipleOf(2), Schema.multipleOf(3)), {\n          \"type\": \"number\",\n          \"title\": \"multipleOf(3)\",\n          \"description\": \"a number divisible by 3\",\n          \"multipleOf\": 3,\n          \"allOf\": [\n            { \"multipleOf\": 2 }\n          ]\n        })\n        expectJSONSchema(\n          JsonNumber.pipe(Schema.multipleOf(2), Schema.multipleOf(3), Schema.multipleOf(3)),\n          {\n            \"type\": \"number\",\n            \"title\": \"multipleOf(3)\",\n            \"description\": \"a number divisible by 3\",\n            \"multipleOf\": 3,\n            \"allOf\": [\n              { \"multipleOf\": 2 }\n            ]\n          }\n        )\n        expectJSONSchema(\n          JsonNumber.pipe(Schema.multipleOf(3), Schema.multipleOf(2), Schema.multipleOf(3)),\n          {\n            \"type\": \"number\",\n            \"title\": \"multipleOf(3)\",\n            \"description\": \"a number divisible by 3\",\n            \"multipleOf\": 3,\n            \"allOf\": [\n              { \"multipleOf\": 2 }\n            ]\n          }\n        )\n      })\n    })\n  })\n\n  describe(\"Tuple\", () => {\n    it(\"empty tuple\", () => {\n      const schema = Schema.Tuple()\n      const jsonSchema: Root = {\n        \"type\": \"array\",\n        \"maxItems\": 0\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate([]))\n      assertFalse(validate([1]))\n    })\n\n    it(\"element\", () => {\n      const schema = Schema.Tuple(JsonNumber)\n      const jsonSchema: Root = {\n        \"type\": \"array\",\n        \"items\": [{\n          \"type\": \"number\"\n        }],\n        \"minItems\": 1,\n        \"additionalItems\": false\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate([1]))\n      assertFalse(validate([]))\n      assertFalse(validate([\"a\"]))\n      assertFalse(validate([1, \"a\"]))\n    })\n\n    it(\"element + inner annotations\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Tuple(JsonNumber.annotations({ description: \"inner\" })),\n        {\n          \"type\": \"array\",\n          \"items\": [{\n            \"type\": \"number\",\n            \"description\": \"inner\"\n          }],\n          \"minItems\": 1,\n          \"additionalItems\": false\n        }\n      )\n    })\n\n    it(\"element + outer annotations should override inner annotations\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Tuple(\n          Schema.element(JsonNumber.annotations({ description: \"inner\" })).annotations({ description: \"outer\" })\n        ),\n        {\n          \"type\": \"array\",\n          \"items\": [{\n            \"type\": \"number\",\n            \"description\": \"outer\"\n          }],\n          \"minItems\": 1,\n          \"additionalItems\": false\n        }\n      )\n    })\n\n    it(\"optionalElement\", () => {\n      const schema = Schema.Tuple(Schema.optionalElement(JsonNumber))\n      const jsonSchema: Root = {\n        \"type\": \"array\",\n        \"minItems\": 0,\n        \"items\": [\n          {\n            \"type\": \"number\"\n          }\n        ],\n        \"additionalItems\": false\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate([]))\n      assertTrue(validate([1]))\n      assertFalse(validate([\"a\"]))\n      assertFalse(validate([1, 2]))\n    })\n\n    it(\"optionalElement + inner annotations\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Tuple(Schema.optionalElement(JsonNumber).annotations({ description: \"inner\" })),\n        {\n          \"type\": \"array\",\n          \"minItems\": 0,\n          \"items\": [\n            {\n              \"type\": \"number\",\n              \"description\": \"inner\"\n            }\n          ],\n          \"additionalItems\": false\n        }\n      )\n    })\n\n    it(\"optionalElement + outer annotations should override inner annotations\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Tuple(\n          Schema.optionalElement(JsonNumber).annotations({ description: \"inner\" }).annotations({ description: \"outer\" })\n        ),\n        {\n          \"type\": \"array\",\n          \"minItems\": 0,\n          \"items\": [\n            {\n              \"type\": \"number\",\n              \"description\": \"outer\"\n            }\n          ],\n          \"additionalItems\": false\n        }\n      )\n    })\n\n    it(\"element + optionalElement\", () => {\n      const schema = Schema.Tuple(\n        Schema.element(Schema.String.annotations({ description: \"inner\" })).annotations({ description: \"outer\" }),\n        Schema.optionalElement(JsonNumber.annotations({ description: \"inner?\" })).annotations({\n          description: \"outer?\"\n        })\n      )\n      const jsonSchema: Root = {\n        \"type\": \"array\",\n        \"minItems\": 1,\n        \"items\": [\n          {\n            \"type\": \"string\",\n            \"description\": \"outer\"\n          },\n          {\n            \"type\": \"number\",\n            \"description\": \"outer?\"\n          }\n        ],\n        \"additionalItems\": false\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate([\"a\"]))\n      assertTrue(validate([\"a\", 1]))\n      assertFalse(validate([]))\n      assertFalse(validate([1]))\n      assertFalse(validate([1, 2]))\n    })\n\n    it(\"rest\", () => {\n      const schema = Schema.Array(JsonNumber)\n      const jsonSchema: Root = {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"number\"\n        }\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate([]))\n      assertTrue(validate([1]))\n      assertTrue(validate([1, 2]))\n      assertTrue(validate([1, 2, 3]))\n      assertFalse(validate([\"a\"]))\n      assertFalse(validate([1, 2, 3, \"a\"]))\n    })\n\n    it(\"rest + inner annotations\", () => {\n      expectJSONSchemaAnnotations(Schema.Array(JsonNumber.annotations({ description: \"inner\" })), {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"number\",\n          \"description\": \"inner\"\n        }\n      })\n    })\n\n    it(\"optionalElement + rest + inner annotations\", () => {\n      const schema = Schema.Tuple(\n        [Schema.optionalElement(Schema.String)],\n        Schema.element(JsonNumber.annotations({ description: \"inner\" }))\n      )\n      const jsonSchema: Root = {\n        \"type\": \"array\",\n        \"minItems\": 0,\n        \"items\": [\n          {\n            \"type\": \"string\"\n          }\n        ],\n        \"additionalItems\": {\n          \"type\": \"number\",\n          \"description\": \"inner\"\n        }\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate([]))\n      assertTrue(validate([\"a\"]))\n      assertTrue(validate([\"a\", 1]))\n      assertFalse(validate([1]))\n      assertFalse(validate([1, 2]))\n      assertFalse(validate([\"a\", \"b\", 1]))\n    })\n\n    it(\"optionalElement + rest + outer annotations should override inner annotations\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Tuple(\n          [Schema.optionalElement(Schema.String)],\n          Schema.element(JsonNumber.annotations({ description: \"inner\" })).annotations({ description: \"outer\" })\n        ),\n        {\n          \"type\": \"array\",\n          \"minItems\": 0,\n          \"items\": [\n            {\n              \"type\": \"string\"\n            }\n          ],\n          \"additionalItems\": {\n            \"type\": \"number\",\n            \"description\": \"outer\"\n          }\n        }\n      )\n    })\n\n    it(\"element + rest\", () => {\n      const schema = Schema.Tuple([Schema.String], JsonNumber)\n      const jsonSchema: Root = {\n        \"type\": \"array\",\n        \"items\": [{\n          \"type\": \"string\"\n        }],\n        \"minItems\": 1,\n        \"additionalItems\": {\n          \"type\": \"number\"\n        }\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate([\"a\"]))\n      assertTrue(validate([\"a\", 1]))\n      assertTrue(validate([\"a\", 1, 2]))\n      assertTrue(validate([\"a\", 1, 2, 3]))\n      assertFalse(validate([]))\n      assertFalse(validate([1]))\n      assertFalse(validate([\"a\", \"b\"]))\n    })\n\n    it(\"NonEmptyArray\", () => {\n      expectJSONSchemaProperty(\n        Schema.NonEmptyArray(Schema.String),\n        {\n          type: \"array\",\n          minItems: 1,\n          items: { type: \"string\" }\n        }\n      )\n    })\n  })\n\n  describe(\"Struct\", () => {\n    it(\"Baseline\", () => {\n      const schema = Schema.Struct({\n        a: Schema.String,\n        b: JsonNumber\n      })\n      const jsonSchema: Root = {\n        \"type\": \"object\",\n        \"properties\": {\n          \"a\": { \"type\": \"string\" },\n          \"b\": { \"type\": \"number\" }\n        },\n        \"required\": [\"a\", \"b\"],\n        \"additionalProperties\": false\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate({ a: \"a\", b: 1 }))\n      assertFalse(validate({}))\n      assertFalse(validate({ a: \"a\" }))\n      assertFalse(validate({ b: 1 }))\n      assertFalse(validate({ a: \"a\", b: 1, c: true }))\n    })\n\n    it(\"field + inner annotation\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.String.annotations({ description: \"inner\" })\n        }),\n        {\n          \"type\": \"object\",\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\",\n              \"description\": \"inner\"\n            }\n          },\n          \"required\": [\"a\"],\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"field + outer annotation should override inner annotation\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.propertySignature(Schema.String.annotations({ description: \"inner\" })).annotations({\n            description: \"outer\"\n          })\n        }),\n        {\n          \"type\": \"object\",\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\",\n              \"description\": \"outer\"\n            }\n          },\n          \"required\": [\"a\"],\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"Struct + Record\", () => {\n      const schema = Schema.Struct({\n        a: Schema.String\n      }, Schema.Record({ key: Schema.String, value: Schema.String }))\n      const jsonSchema: Root = {\n        \"type\": \"object\",\n        \"required\": [\n          \"a\"\n        ],\n        \"properties\": {\n          \"a\": {\n            \"type\": \"string\"\n          }\n        },\n        \"additionalProperties\": {\n          \"type\": \"string\"\n        }\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate({ a: \"a\" }))\n      assertTrue(validate({ a: \"a\", b: \"b\" }))\n      assertFalse(validate({}))\n      assertFalse(validate({ b: \"b\" }))\n      assertFalse(validate({ a: 1 }))\n      assertFalse(validate({ a: \"a\", b: 1 }))\n    })\n\n    it(\"exact optional field\", () => {\n      const schema = Schema.Struct({\n        a: Schema.String,\n        b: Schema.optionalWith(JsonNumber, { exact: true })\n      })\n      const jsonSchema: Root = {\n        \"type\": \"object\",\n        \"properties\": {\n          \"a\": {\n            \"type\": \"string\"\n          },\n          \"b\": {\n            \"type\": \"number\"\n          }\n        },\n        \"required\": [\"a\"],\n        \"additionalProperties\": false\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate({ a: \"a\", b: 1 }))\n      assertTrue(validate({ a: \"a\" }))\n      assertFalse(validate({}))\n      assertFalse(validate({ b: 1 }))\n      assertFalse(validate({ a: \"a\", b: 1, c: true }))\n    })\n\n    it(\"exact optional field + inner annotation\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.optionalWith(Schema.String.annotations({ description: \"inner\" }), { exact: true })\n        }),\n        {\n          \"type\": \"object\",\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\",\n              \"description\": \"inner\"\n            }\n          },\n          \"required\": [],\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"exact optional field + outer annotation should override inner annotations\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.optionalWith(Schema.String.annotations({ description: \"inner\" }), { exact: true }).annotations({\n            description: \"outer\"\n          })\n        }),\n        {\n          \"type\": \"object\",\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\",\n              \"description\": \"outer\"\n            }\n          },\n          \"required\": [],\n          \"additionalProperties\": false\n        }\n      )\n    })\n  })\n\n  describe(\"Record\", () => {\n    it(\"Record(refinement, number)\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Record({ key: Schema.String.pipe(Schema.minLength(1)), value: JsonNumber }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {},\n          \"patternProperties\": {\n            \"\": {\n              \"type\": \"number\"\n            }\n          },\n          \"propertyNames\": {\n            \"type\": \"string\",\n            \"title\": \"minLength(1)\",\n            \"description\": \"a string at least 1 character(s) long\",\n            \"minLength\": 1\n          }\n        }\n      )\n    })\n\n    it(\"Record(string, number)\", () => {\n      expectJSONSchemaAnnotations(Schema.Record({ key: Schema.String, value: JsonNumber }), {\n        \"type\": \"object\",\n        \"properties\": {},\n        \"required\": [],\n        \"additionalProperties\": {\n          \"type\": \"number\"\n        }\n      })\n    })\n\n    it(\"Record('a' | 'b', number)\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Record(\n          { key: Schema.Union(Schema.Literal(\"a\"), Schema.Literal(\"b\")), value: JsonNumber }\n        ),\n        {\n          \"type\": \"object\",\n          \"properties\": {\n            \"a\": {\n              \"type\": \"number\"\n            },\n            \"b\": {\n              \"type\": \"number\"\n            }\n          },\n          \"required\": [\"a\", \"b\"],\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"Record(${string}-${string}, number)\", () => {\n      const schema = Schema.Record(\n        { key: Schema.TemplateLiteral(Schema.String, Schema.Literal(\"-\"), Schema.String), value: JsonNumber }\n      )\n      const jsonSchema: Root = {\n        \"type\": \"object\",\n        \"required\": [],\n        \"properties\": {},\n        \"patternProperties\": {\n          \"\": { \"type\": \"number\" }\n        },\n        \"propertyNames\": {\n          \"pattern\": \"^[\\\\s\\\\S]*?-[\\\\s\\\\S]*?$\",\n          \"type\": \"string\"\n        }\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate({}))\n      assertTrue(validate({ \"-\": 1 }))\n      assertTrue(validate({ \"a-\": 1 }))\n      assertTrue(validate({ \"-b\": 1 }))\n      assertTrue(validate({ \"a-b\": 1 }))\n      assertFalse(validate({ \"\": 1 }))\n      assertFalse(validate({ \"-\": \"a\" }))\n    })\n\n    it(\"Record(pattern, number)\", () => {\n      const schema = Schema.Record(\n        { key: Schema.String.pipe(Schema.pattern(new RegExp(\"^.*-.*$\"))), value: JsonNumber }\n      )\n      const jsonSchema: Root = {\n        \"type\": \"object\",\n        \"required\": [],\n        \"properties\": {},\n        \"patternProperties\": {\n          \"\": {\n            \"type\": \"number\"\n          }\n        },\n        \"propertyNames\": {\n          \"description\": \"a string matching the pattern ^.*-.*$\",\n          \"pattern\": \"^.*-.*$\",\n          \"type\": \"string\"\n        }\n      }\n      expectJSONSchemaAnnotations(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate({}))\n      assertTrue(validate({ \"-\": 1 }))\n      assertTrue(validate({ \"a-\": 1 }))\n      assertTrue(validate({ \"-b\": 1 }))\n      assertTrue(validate({ \"a-b\": 1 }))\n      assertFalse(validate({ \"\": 1 }))\n      assertFalse(validate({ \"-\": \"a\" }))\n    })\n\n    it(\"Record(SymbolFromSelf & annotation, number)\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Record({\n          key: Schema.SymbolFromSelf.annotations({ jsonSchema: { \"type\": \"string\" } }),\n          value: JsonNumber\n        }),\n        {\n          \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {},\n          \"additionalProperties\": {\n            \"type\": \"number\"\n          },\n          \"propertyNames\": {\n            \"type\": \"string\"\n          }\n        }\n      )\n    })\n\n    it(\"Record(string, UndefinedOr(number))\", () => {\n      expectJSONSchemaAnnotations(Schema.Record({ key: Schema.String, value: Schema.UndefinedOr(JsonNumber) }), {\n        \"type\": \"object\",\n        \"properties\": {},\n        \"required\": [],\n        \"additionalProperties\": { \"type\": \"number\" }\n      })\n    })\n\n    it(\"partial(Struct + Record(string, number))\", () => {\n      const schema = Schema.partial(\n        Schema.Struct(\n          { foo: Schema.Number },\n          {\n            key: Schema.String,\n            value: Schema.Number\n          }\n        )\n      )\n\n      expectJSONSchemaAnnotations(schema, {\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n        \"type\": \"object\",\n        \"required\": [],\n        \"properties\": {\n          \"foo\": {\n            \"type\": \"number\"\n          }\n        },\n        \"additionalProperties\": {\n          \"type\": \"number\"\n        }\n      })\n    })\n  })\n\n  describe(\"Union\", () => {\n    it(\"should ignore never members\", () => {\n      expectJSONSchema(Schema.Union(Schema.String, Schema.Never), {\n        \"type\": \"string\"\n      })\n      expectJSONSchema(Schema.Union(Schema.String, Schema.Union(Schema.Never, Schema.Never)), {\n        \"type\": \"string\"\n      })\n    })\n\n    it(\"string | JsonNumber\", () => {\n      expectJSONSchemaAnnotations(Schema.Union(Schema.String, JsonNumber), {\n        \"anyOf\": [\n          { \"type\": \"string\" },\n          { \"type\": \"number\" }\n        ]\n      })\n    })\n\n    describe(\"Union including literals\", () => {\n      it(`1 | 2`, () => {\n        expectJSONSchemaAnnotations(Schema.Union(Schema.Literal(1), Schema.Literal(2)), {\n          \"type\": \"number\",\n          \"enum\": [1, 2]\n        })\n      })\n\n      it(`1(with description) | 2`, () => {\n        expectJSONSchemaAnnotations(\n          Schema.Union(\n            Schema.Literal(1).annotations({ description: \"43d87cd1-df64-457f-8119-0401ecd1399e\" }),\n            Schema.Literal(2)\n          ),\n          {\n            \"anyOf\": [\n              {\n                \"type\": \"number\",\n                \"enum\": [1],\n                \"description\": \"43d87cd1-df64-457f-8119-0401ecd1399e\"\n              },\n              {\n                \"type\": \"number\",\n                \"enum\": [2]\n              }\n            ]\n          }\n        )\n      })\n\n      it(`1 | 2(with description)`, () => {\n        expectJSONSchemaAnnotations(\n          Schema.Union(\n            Schema.Literal(1),\n            Schema.Literal(2).annotations({ description: \"28e1ba58-7c13-4667-88cb-2baa1ac31a0f\" })\n          ),\n          {\n            \"anyOf\": [\n              {\n                \"type\": \"number\",\n                \"enum\": [1]\n              },\n              {\n                \"type\": \"number\",\n                \"enum\": [2],\n                \"description\": \"28e1ba58-7c13-4667-88cb-2baa1ac31a0f\"\n              }\n            ]\n          }\n        )\n      })\n\n      it(`1 | 2 | string`, () => {\n        expectJSONSchemaAnnotations(Schema.Union(Schema.Literal(1), Schema.Literal(2), Schema.String), {\n          \"anyOf\": [\n            {\n              \"type\": \"number\",\n              \"enum\": [1, 2]\n            },\n            { \"type\": \"string\" }\n          ]\n        })\n      })\n\n      it(`(1 | 2) | string`, () => {\n        expectJSONSchemaAnnotations(Schema.Union(Schema.Literal(1, 2), Schema.String), {\n          \"anyOf\": [\n            {\n              \"type\": \"number\",\n              \"enum\": [1, 2]\n            },\n            { \"type\": \"string\" }\n          ]\n        })\n      })\n\n      it(`(1 | 2)(with description) | string`, () => {\n        expectJSONSchemaAnnotations(\n          Schema.Union(\n            Schema.Literal(1, 2).annotations({ description: \"d0121d0e-8b56-4a2e-9963-47a0965d6a3c\" }),\n            Schema.String\n          ),\n          {\n            \"anyOf\": [\n              {\n                \"type\": \"number\",\n                \"description\": \"d0121d0e-8b56-4a2e-9963-47a0965d6a3c\",\n                \"enum\": [1, 2]\n              },\n              { \"type\": \"string\" }\n            ]\n          }\n        )\n      })\n\n      it(`(1 | 2)(with description) | 3 | string`, () => {\n        expectJSONSchemaAnnotations(\n          Schema.Union(\n            Schema.Literal(1, 2).annotations({ description: \"eca4431f-c97c-454f-8167-6c2e81430c6b\" }),\n            Schema.Literal(3),\n            Schema.String\n          ),\n          {\n            \"anyOf\": [\n              {\n                \"type\": \"number\",\n                \"description\": \"eca4431f-c97c-454f-8167-6c2e81430c6b\",\n                \"enum\": [1, 2]\n              },\n              {\n                \"type\": \"number\",\n                \"enum\": [3]\n              },\n              { \"type\": \"string\" }\n            ]\n          }\n        )\n      })\n\n      it(`1(with description) | 2 | string`, () => {\n        expectJSONSchemaAnnotations(\n          Schema.Union(\n            Schema.Literal(1).annotations({ description: \"867c07f5-5710-477c-8296-239694e86562\" }),\n            Schema.Literal(2),\n            Schema.String\n          ),\n          {\n            \"anyOf\": [\n              {\n                \"type\": \"number\",\n                \"description\": \"867c07f5-5710-477c-8296-239694e86562\",\n                \"enum\": [1]\n              },\n              {\n                \"type\": \"number\",\n                \"enum\": [2]\n              },\n              { \"type\": \"string\" }\n            ]\n          }\n        )\n      })\n\n      it(`1 | 2(with description) | string`, () => {\n        expectJSONSchemaAnnotations(\n          Schema.Union(\n            Schema.Literal(1),\n            Schema.Literal(2).annotations({ description: \"4e49a840-5fb8-43f6-916f-565cbf532db4\" }),\n            Schema.String\n          ),\n          {\n            \"anyOf\": [\n              {\n                \"type\": \"number\",\n                \"enum\": [1]\n              },\n              {\n                \"type\": \"number\",\n                \"description\": \"4e49a840-5fb8-43f6-916f-565cbf532db4\",\n                \"enum\": [2]\n              },\n              { \"type\": \"string\" }\n            ]\n          }\n        )\n      })\n\n      it(`string | 1 | 2 `, () => {\n        expectJSONSchemaAnnotations(Schema.Union(Schema.String, Schema.Literal(1), Schema.Literal(2)), {\n          \"anyOf\": [\n            { \"type\": \"string\" },\n            {\n              \"type\": \"number\",\n              \"enum\": [1, 2]\n            }\n          ]\n        })\n      })\n\n      it(`string | (1 | 2) `, () => {\n        expectJSONSchemaAnnotations(Schema.Union(Schema.String, Schema.Literal(1, 2)), {\n          \"anyOf\": [\n            { \"type\": \"string\" },\n            {\n              \"type\": \"number\",\n              \"enum\": [1, 2]\n            }\n          ]\n        })\n      })\n\n      it(`string | 1(with description) | 2`, () => {\n        expectJSONSchemaAnnotations(\n          Schema.Union(\n            Schema.String,\n            Schema.Literal(1).annotations({ description: \"26521e57-cfb6-4563-abe2-2fe920398e16\" }),\n            Schema.Literal(2)\n          ),\n          {\n            \"anyOf\": [\n              { \"type\": \"string\" },\n              {\n                \"type\": \"number\",\n                \"description\": \"26521e57-cfb6-4563-abe2-2fe920398e16\",\n                \"enum\": [1]\n              },\n              {\n                \"type\": \"number\",\n                \"enum\": [2]\n              }\n            ]\n          }\n        )\n      })\n\n      it(`string | 1 | 2(with description)`, () => {\n        expectJSONSchemaAnnotations(\n          Schema.Union(\n            Schema.String,\n            Schema.Literal(1),\n            Schema.Literal(2).annotations({ description: \"c4fb2a01-68ff-43d2-81d0-de799c06e9c0\" })\n          ),\n          {\n            \"anyOf\": [\n              { \"type\": \"string\" },\n              {\n                \"type\": \"number\",\n                \"enum\": [1]\n              },\n              {\n                \"type\": \"number\",\n                \"description\": \"c4fb2a01-68ff-43d2-81d0-de799c06e9c0\",\n                \"enum\": [2]\n              }\n            ]\n          }\n        )\n      })\n    })\n  })\n\n  describe(\"Transformation\", () => {\n    it(\"NumberFromString\", () => {\n      expectJSONSchemaProperty(Schema.NumberFromString, {\n        \"$defs\": {\n          \"NumberFromString\": {\n            \"type\": \"string\",\n            \"description\": \"a string to be decoded into a number\"\n          }\n        },\n        \"$ref\": \"#/$defs/NumberFromString\"\n      })\n    })\n\n    it(\"DateFromString\", () => {\n      expectJSONSchemaProperty(\n        Schema.DateFromString,\n        {\n          \"$defs\": {\n            \"DateFromString\": {\n              \"type\": \"string\",\n              \"description\": \"a string to be decoded into a Date\"\n            }\n          },\n          \"$ref\": \"#/$defs/DateFromString\"\n        }\n      )\n    })\n\n    it(\"Date\", () => {\n      expectJSONSchemaProperty(\n        Schema.Date,\n        {\n          \"$defs\": {\n            \"Date\": {\n              \"type\": \"string\",\n              \"description\": \"a string to be decoded into a Date\"\n            }\n          },\n          \"$ref\": \"#/$defs/Date\"\n        }\n      )\n    })\n\n    it(\"OptionFromNullOr\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.OptionFromNullOr(Schema.NonEmptyString)\n        }),\n        {\n          \"$defs\": {\n            \"NonEmptyString\": {\n              \"type\": \"string\",\n              \"title\": \"nonEmptyString\",\n              \"description\": \"a non empty string\",\n              \"minLength\": 1\n            }\n          },\n          \"type\": \"object\",\n          \"required\": [\n            \"a\"\n          ],\n          \"properties\": {\n            \"a\": {\n              \"anyOf\": [\n                { \"$ref\": \"#/$defs/NonEmptyString\" },\n                { \"type\": \"null\" }\n              ]\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"ReadonlyMapFromRecord\", () => {\n      expectJSONSchemaProperty(\n        Schema.ReadonlyMapFromRecord({\n          key: Schema.String.pipe(Schema.minLength(2)),\n          value: Schema.NumberFromString\n        }),\n        {\n          \"$defs\": {\n            \"NumberFromString\": {\n              \"type\": \"string\",\n              \"description\": \"a string to be decoded into a number\"\n            }\n          },\n          \"type\": \"object\",\n          \"description\": \"a record to be decoded into a ReadonlyMap\",\n          \"required\": [],\n          \"properties\": {},\n          \"patternProperties\": {\n            \"\": {\n              \"$ref\": \"#/$defs/NumberFromString\"\n            }\n          },\n          \"propertyNames\": {\n            \"title\": \"minLength(2)\",\n            \"description\": \"a string at least 2 character(s) long\",\n            \"minLength\": 2,\n            \"type\": \"string\"\n          }\n        }\n      )\n    })\n\n    it(\"MapFromRecord\", () => {\n      expectJSONSchemaProperty(\n        Schema.MapFromRecord({\n          key: Schema.String.pipe(Schema.minLength(2)),\n          value: Schema.NumberFromString\n        }),\n        {\n          \"$defs\": {\n            \"NumberFromString\": {\n              \"type\": \"string\",\n              \"description\": \"a string to be decoded into a number\"\n            }\n          },\n          \"type\": \"object\",\n          \"description\": \"a record to be decoded into a Map\",\n          \"required\": [],\n          \"properties\": {},\n          \"patternProperties\": {\n            \"\": {\n              \"$ref\": \"#/$defs/NumberFromString\"\n            }\n          },\n          \"propertyNames\": {\n            \"title\": \"minLength(2)\",\n            \"description\": \"a string at least 2 character(s) long\",\n            \"minLength\": 2,\n            \"type\": \"string\"\n          }\n        }\n      )\n    })\n\n    describe(\"TypeLiteralTransformation\", () => {\n      // not sure if this is a bug or not\n      it.skip(\"a title annotation on the transformation should not overwrite an annotation set on the from part\", () => {\n        const schema = Schema.make(\n          new AST.Transformation(\n            new AST.TypeLiteral([new AST.PropertySignature(\"a\", Schema.String.ast, false, true)], [], {\n              [AST.TitleAnnotationId]: \"from-title\"\n            }),\n            new AST.TypeLiteral([new AST.PropertySignature(\"a\", Schema.String.ast, false, true)], [], {\n              [AST.TitleAnnotationId]: \"to-title\"\n            }),\n            new AST.TypeLiteralTransformation([]),\n            { [AST.TitleAnnotationId]: \"transformation-title\" }\n          )\n        )\n        expectJSONSchemaProperty(schema, {\n          \"type\": \"object\",\n          \"required\": [\"a\"],\n          \"properties\": {\n            \"a\": { \"type\": \"string\" }\n          },\n          \"additionalProperties\": false,\n          \"title\": \"from-title\"\n        })\n      })\n\n      // not sure if this is a bug or not\n      it.skip(\"a description annotation on the transformation should not overwrite an annotation set on the from part\", () => {\n        const schema = Schema.make(\n          new AST.Transformation(\n            new AST.TypeLiteral([new AST.PropertySignature(\"a\", Schema.String.ast, false, true)], [], {\n              [AST.DescriptionAnnotationId]: \"from-description\"\n            }),\n            new AST.TypeLiteral([new AST.PropertySignature(\"a\", Schema.String.ast, false, true)], [], {\n              [AST.DescriptionAnnotationId]: \"to-description\"\n            }),\n            new AST.TypeLiteralTransformation([]),\n            { [AST.DescriptionAnnotationId]: \"transformation-description\" }\n          )\n        )\n        expectJSONSchemaProperty(schema, {\n          \"type\": \"object\",\n          \"required\": [\"a\"],\n          \"properties\": {\n            \"a\": { \"type\": \"string\" }\n          },\n          \"additionalProperties\": false,\n          \"description\": \"from-description\"\n        })\n      })\n\n      describe(\"optionalWith\", () => {\n        describe(`{ default: () => ... } option`, () => {\n          it(\"with transformation description and title\", () => {\n            expectJSONSchemaProperty(\n              Schema.Struct({\n                a: Schema.optionalWith(\n                  Schema.NonEmptyString.annotations({\n                    description: \"inner-description\",\n                    title: \"inner-title\"\n                  }),\n                  { default: () => \"\" }\n                ).annotations({\n                  description: \"middle-description\",\n                  title: \"middle-title\"\n                })\n              }).annotations({\n                description: \"outer-description\",\n                title: \"outer-title\"\n              }),\n              {\n                \"type\": \"object\",\n                \"description\": \"outer-description\",\n                \"title\": \"outer-title\",\n                \"required\": [],\n                \"properties\": {\n                  \"a\": {\n                    \"description\": \"middle-description\",\n                    \"minLength\": 1,\n                    \"title\": \"middle-title\",\n                    \"type\": \"string\"\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            )\n          })\n        })\n\n        describe(`{ as: \"Option\" } option`, () => {\n          it(\"base\", () => {\n            expectJSONSchemaProperty(\n              Schema.Struct({\n                a: Schema.optionalWith(Schema.NonEmptyString, { as: \"Option\" })\n              }),\n              {\n                \"$defs\": {\n                  \"NonEmptyString\": {\n                    \"type\": \"string\",\n                    \"title\": \"nonEmptyString\",\n                    \"description\": \"a non empty string\",\n                    \"minLength\": 1\n                  }\n                },\n                \"type\": \"object\",\n                \"required\": [],\n                \"properties\": {\n                  \"a\": {\n                    \"$ref\": \"#/$defs/NonEmptyString\"\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            )\n          })\n\n          it(\"with transformation identifier annotation\", () => {\n            expectJSONSchemaProperty(\n              Schema.Struct({\n                a: Schema.optionalWith(Schema.NonEmptyString, { as: \"Option\" })\n              }).annotations({\n                identifier: \"aa6f48cd-03e4-470a-beb7-5f7cc532c676\",\n                description: \"b964b873-0266-446b-acf4-97dc125e7553\",\n                title: \"aa67b73c-3161-4640-b1e1-5b5830cfb173\"\n              }),\n              {\n                \"$ref\": \"#/$defs/aa6f48cd-03e4-470a-beb7-5f7cc532c676\",\n                \"$defs\": {\n                  \"NonEmptyString\": {\n                    \"type\": \"string\",\n                    \"title\": \"nonEmptyString\",\n                    \"description\": \"a non empty string\",\n                    \"minLength\": 1\n                  },\n                  \"aa6f48cd-03e4-470a-beb7-5f7cc532c676\": {\n                    \"type\": \"object\",\n                    \"required\": [],\n                    \"properties\": {\n                      \"a\": {\n                        \"$ref\": \"#/$defs/NonEmptyString\"\n                      }\n                    },\n                    \"additionalProperties\": false,\n                    \"description\": \"b964b873-0266-446b-acf4-97dc125e7553\",\n                    \"title\": \"aa67b73c-3161-4640-b1e1-5b5830cfb173\"\n                  }\n                }\n              }\n            )\n          })\n        })\n      })\n\n      describe(\"fromKey\", () => {\n        it(\"a <- b\", () => {\n          expectJSONSchemaProperty(\n            Schema.Struct({\n              a: Schema.NonEmptyString.pipe(Schema.propertySignature, Schema.fromKey(\"b\"))\n            }),\n            {\n              \"$defs\": {\n                \"NonEmptyString\": {\n                  \"type\": \"string\",\n                  \"title\": \"nonEmptyString\",\n                  \"description\": \"a non empty string\",\n                  \"minLength\": 1\n                }\n              },\n              \"type\": \"object\",\n              \"required\": [\n                \"b\"\n              ],\n              \"properties\": {\n                \"b\": {\n                  \"$ref\": \"#/$defs/NonEmptyString\"\n                }\n              },\n              \"additionalProperties\": false\n            }\n          )\n        })\n\n        it(\"a <- b & annotations\", () => {\n          expectJSONSchemaProperty(\n            Schema.Struct({\n              a: Schema.NonEmptyString.pipe(Schema.propertySignature, Schema.fromKey(\"b\")).annotations({})\n            }),\n            {\n              \"$defs\": {\n                \"NonEmptyString\": {\n                  \"type\": \"string\",\n                  \"title\": \"nonEmptyString\",\n                  \"description\": \"a non empty string\",\n                  \"minLength\": 1\n                }\n              },\n              \"type\": \"object\",\n              \"required\": [\n                \"b\"\n              ],\n              \"properties\": {\n                \"b\": {\n                  \"$ref\": \"#/$defs/NonEmptyString\"\n                }\n              },\n              \"additionalProperties\": false\n            }\n          )\n        })\n\n        it(\"with transformation identifier annotation\", () => {\n          expectJSONSchemaProperty(\n            Schema.Struct({\n              a: Schema.NonEmptyString.pipe(Schema.propertySignature, Schema.fromKey(\"b\"))\n            }).annotations({\n              identifier: \"d5ff7bc8-1bd5-42a7-8186-e29fd4c217ea\",\n              description: \"5f7bc5b8-dd68-4ec5-b9e9-64df74bd3c45\",\n              title: \"119da226-70aa-4ae6-ab63-7db10c7e9dde\"\n            }),\n            {\n              \"$ref\": \"#/$defs/d5ff7bc8-1bd5-42a7-8186-e29fd4c217ea\",\n              \"$defs\": {\n                \"NonEmptyString\": {\n                  \"type\": \"string\",\n                  \"title\": \"nonEmptyString\",\n                  \"description\": \"a non empty string\",\n                  \"minLength\": 1\n                },\n                \"d5ff7bc8-1bd5-42a7-8186-e29fd4c217ea\": {\n                  \"type\": \"object\",\n                  \"required\": [\n                    \"b\"\n                  ],\n                  \"properties\": {\n                    \"b\": {\n                      \"$ref\": \"#/$defs/NonEmptyString\"\n                    }\n                  },\n                  \"additionalProperties\": false,\n                  \"description\": \"5f7bc5b8-dd68-4ec5-b9e9-64df74bd3c45\",\n                  \"title\": \"119da226-70aa-4ae6-ab63-7db10c7e9dde\"\n                }\n              }\n            }\n          )\n        })\n      })\n    })\n  })\n\n  describe(\"Suspend\", () => {\n    it(\"should support outer suspended schemas\", () => {\n      interface A {\n        readonly a: string\n        readonly as: ReadonlyArray<A>\n      }\n      const schema: Schema.Schema<A> = Schema.suspend(() =>\n        // intended outer suspend\n        Schema.Struct({\n          a: Schema.String,\n          as: Schema.Array(schema)\n        })\n      ).annotations({ identifier: \"cdb51157-6f4a-42c1-9075-5b9af3a1448c\" })\n      const jsonSchema: Root = {\n        \"$ref\": \"#/$defs/cdb51157-6f4a-42c1-9075-5b9af3a1448c\",\n        \"$defs\": {\n          \"cdb51157-6f4a-42c1-9075-5b9af3a1448c\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"a\",\n              \"as\"\n            ],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\"\n              },\n              \"as\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/cdb51157-6f4a-42c1-9075-5b9af3a1448c\"\n                }\n              }\n            },\n            \"additionalProperties\": false\n          }\n        }\n      }\n      expectJSONSchemaProperty(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate({ a: \"a1\", as: [] }))\n      assertTrue(validate({ a: \"a1\", as: [{ a: \"a2\", as: [] }] }))\n      assertTrue(validate({ a: \"a1\", as: [{ a: \"a2\", as: [] }, { a: \"a3\", as: [] }] }))\n      assertTrue(\n        validate({ a: \"a1\", as: [{ a: \"a2\", as: [] }, { a: \"a3\", as: [{ a: \"a4\", as: [] }] }] })\n      )\n      assertFalse(\n        validate({ a: \"a1\", as: [{ a: \"a2\", as: [] }, { a: \"a3\", as: [{ a: \"a4\", as: [1] }] }] })\n      )\n    })\n\n    it(\"should support inner suspended schemas with inner identifier annotation\", () => {\n      interface A {\n        readonly a: string\n        readonly as: ReadonlyArray<A>\n      }\n      const schema = Schema.Struct({\n        a: Schema.String,\n        as: Schema.Array(\n          Schema.suspend((): Schema.Schema<A> => schema).annotations({\n            identifier: \"c4588a13-c003-4b8d-930f-d3469925ec1b\"\n          })\n        )\n      })\n      const jsonSchema: Root = {\n        \"type\": \"object\",\n        \"required\": [\n          \"a\",\n          \"as\"\n        ],\n        \"properties\": {\n          \"a\": {\n            \"type\": \"string\"\n          },\n          \"as\": {\n            \"type\": \"array\",\n            \"items\": {\n              \"$ref\": \"#/$defs/c4588a13-c003-4b8d-930f-d3469925ec1b\"\n            }\n          }\n        },\n        \"additionalProperties\": false,\n        \"$defs\": {\n          \"c4588a13-c003-4b8d-930f-d3469925ec1b\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"a\",\n              \"as\"\n            ],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\"\n              },\n              \"as\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/c4588a13-c003-4b8d-930f-d3469925ec1b\"\n                }\n              }\n            },\n            \"additionalProperties\": false\n          }\n        }\n      }\n      expectJSONSchemaProperty(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate({ a: \"a1\", as: [] }))\n      assertTrue(validate({ a: \"a1\", as: [{ a: \"a2\", as: [] }] }))\n      assertTrue(validate({ a: \"a1\", as: [{ a: \"a2\", as: [] }, { a: \"a3\", as: [] }] }))\n      assertTrue(\n        validate({ a: \"a1\", as: [{ a: \"a2\", as: [] }, { a: \"a3\", as: [{ a: \"a4\", as: [] }] }] })\n      )\n      assertFalse(\n        validate({ a: \"a1\", as: [{ a: \"a2\", as: [] }, { a: \"a3\", as: [{ a: \"a4\", as: [1] }] }] })\n      )\n    })\n\n    it(\"should support inner suspended schemas with outer identifier annotation\", () => {\n      interface Category {\n        readonly name: string\n        readonly categories: ReadonlyArray<Category>\n      }\n      const schema = Schema.Struct({\n        name: Schema.String,\n        categories: Schema.Array(Schema.suspend((): Schema.Schema<Category> => schema))\n      }).annotations({ identifier: \"5c2a4755-f8f2-4290-a40f-ed247803a1a0\" })\n      const jsonSchema: Root = {\n        \"$ref\": \"#/$defs/5c2a4755-f8f2-4290-a40f-ed247803a1a0\",\n        \"$defs\": {\n          \"5c2a4755-f8f2-4290-a40f-ed247803a1a0\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"name\",\n              \"categories\"\n            ],\n            \"properties\": {\n              \"name\": {\n                \"type\": \"string\"\n              },\n              \"categories\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/5c2a4755-f8f2-4290-a40f-ed247803a1a0\"\n                }\n              }\n            },\n            \"additionalProperties\": false\n          }\n        }\n      }\n      expectJSONSchemaProperty(schema, jsonSchema)\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate({ name: \"a1\", categories: [] }))\n      assertTrue(validate({ name: \"a1\", categories: [{ name: \"a2\", categories: [] }] }))\n      assertTrue(validate({ name: \"a1\", categories: [{ name: \"a2\", categories: [] }, { name: \"a3\", categories: [] }] }))\n\n      assertTrue(\n        validate({\n          name: \"a1\",\n          categories: [{ name: \"a2\", categories: [] }, { name: \"a3\", categories: [{ name: \"a4\", categories: [] }] }]\n        })\n      )\n      assertFalse(\n        validate({\n          name: \"a1\",\n          categories: [{ name: \"a2\", categories: [] }, { name: \"a3\", categories: [{ name: \"a4\", categories: [1] }] }]\n        })\n      )\n    })\n\n    it(\"should support mutually suspended schemas\", () => {\n      interface Expression {\n        readonly type: \"expression\"\n        readonly value: number | Operation\n      }\n\n      interface Operation {\n        readonly type: \"operation\"\n        readonly operator: \"+\" | \"-\"\n        readonly left: Expression\n        readonly right: Expression\n      }\n\n      // intended outer suspend\n      const Expression: Schema.Schema<Expression> = Schema.suspend(() =>\n        Schema.Struct({\n          type: Schema.Literal(\"expression\"),\n          value: Schema.Union(JsonNumber, Operation)\n        })\n      ).annotations({ identifier: \"2ad5683a-878f-4e4d-909c-496e59ce62e0\" })\n\n      // intended outer suspend\n      const Operation: Schema.Schema<Operation> = Schema.suspend(() =>\n        Schema.Struct({\n          type: Schema.Literal(\"operation\"),\n          operator: Schema.Union(Schema.Literal(\"+\"), Schema.Literal(\"-\")),\n          left: Expression,\n          right: Expression\n        })\n      ).annotations({ identifier: \"e0f2ce47-eac7-4991-8730-90ebe4e0ffda\" })\n\n      const jsonSchema: Root = {\n        \"$ref\": \"#/$defs/e0f2ce47-eac7-4991-8730-90ebe4e0ffda\",\n        \"$defs\": {\n          \"e0f2ce47-eac7-4991-8730-90ebe4e0ffda\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"type\",\n              \"operator\",\n              \"left\",\n              \"right\"\n            ],\n            \"properties\": {\n              \"type\": {\n                \"type\": \"string\",\n                \"enum\": [\"operation\"]\n              },\n              \"operator\": {\n                \"type\": \"string\",\n                \"enum\": [\"+\", \"-\"]\n              },\n              \"left\": {\n                \"$ref\": \"#/$defs/2ad5683a-878f-4e4d-909c-496e59ce62e0\"\n              },\n              \"right\": {\n                \"$ref\": \"#/$defs/2ad5683a-878f-4e4d-909c-496e59ce62e0\"\n              }\n            },\n            \"additionalProperties\": false\n          },\n          \"2ad5683a-878f-4e4d-909c-496e59ce62e0\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"type\",\n              \"value\"\n            ],\n            \"properties\": {\n              \"type\": {\n                \"type\": \"string\",\n                \"enum\": [\"expression\"]\n              },\n              \"value\": {\n                \"anyOf\": [\n                  {\n                    \"type\": \"number\"\n                  },\n                  {\n                    \"$ref\": \"#/$defs/e0f2ce47-eac7-4991-8730-90ebe4e0ffda\"\n                  }\n                ]\n              }\n            },\n            \"additionalProperties\": false\n          }\n        }\n      }\n      expectJSONSchemaProperty(Operation, jsonSchema, { numRuns: 5 })\n      const validate = getAjvValidate(jsonSchema)\n      assertTrue(validate({\n        type: \"operation\",\n        operator: \"+\",\n        left: {\n          type: \"expression\",\n          value: 1\n        },\n        right: {\n          type: \"expression\",\n          value: {\n            type: \"operation\",\n            operator: \"-\",\n            left: {\n              type: \"expression\",\n              value: 3\n            },\n            right: {\n              type: \"expression\",\n              value: 2\n            }\n          }\n        }\n      }))\n    })\n  })\n\n  it(\"examples JSON Schema annotation support\", () => {\n    expectJSONSchemaAnnotations(Schema.String.annotations({ examples: [\"a\", \"b\"] }), {\n      \"type\": \"string\",\n      \"examples\": [\"a\", \"b\"]\n    })\n    expectJSONSchemaProperty(Schema.BigInt.annotations({ examples: [1n, 2n] }), {\n      \"description\": \"a string to be decoded into a bigint\",\n      \"examples\": [\n        \"1\",\n        \"2\"\n      ],\n      \"type\": \"string\"\n    })\n    expectJSONSchemaProperty(\n      Schema.Struct({\n        a: Schema.propertySignature(Schema.BigInt).annotations({ examples: [1n, 2n] })\n      }),\n      {\n        \"$defs\": {\n          \"BigInt\": {\n            \"type\": \"string\",\n            \"description\": \"a string to be decoded into a bigint\"\n          }\n        },\n        \"type\": \"object\",\n        \"required\": [\n          \"a\"\n        ],\n        \"properties\": {\n          \"a\": {\n            \"allOf\": [\n              { \"$ref\": \"#/$defs/BigInt\" }\n            ],\n            \"examples\": [\"1\", \"2\"]\n          }\n        },\n        \"additionalProperties\": false\n      }\n    )\n  })\n\n  it(\"default JSON Schema annotation support\", () => {\n    expectJSONSchemaAnnotations(Schema.String.annotations({ default: \"\" }), {\n      \"type\": \"string\",\n      \"default\": \"\"\n    })\n  })\n\n  describe(\"Class\", () => {\n    it(\"should use the identifier as JSON Schema identifier\", () => {\n      const input = Schema.Struct({ a: Schema.String })\n      class A extends Schema.Class<A>(\"7a8b06e3-ebc1-4bdd-ab0d-3ec493d96d95\")(input) {}\n      expectJSONSchemaProperty(A, {\n        \"$defs\": {\n          \"7a8b06e3-ebc1-4bdd-ab0d-3ec493d96d95\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"a\"\n            ],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        },\n        \"$ref\": \"#/$defs/7a8b06e3-ebc1-4bdd-ab0d-3ec493d96d95\"\n      })\n    })\n\n    it(\"should escape special characters in the $ref\", () => {\n      const input = Schema.Struct({ a: Schema.String })\n      class A extends Schema.Class<A>(\"~package/name\")(input) {}\n      expectJSONSchemaProperty(A, {\n        \"$defs\": {\n          \"~package/name\": {\n            \"type\": \"object\",\n            \"required\": [\n              \"a\"\n            ],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\"\n              }\n            },\n            \"additionalProperties\": false\n          }\n        },\n        \"$ref\": \"#/$defs/~0package~1name\"\n      })\n    })\n  })\n\n  it(\"compose\", () => {\n    expectJSONSchemaAnnotations(\n      Schema.Struct({\n        a: Schema.NonEmptyString.pipe(Schema.compose(Schema.NumberFromString))\n      }),\n      {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"type\": \"string\",\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1\n          }\n        },\n        \"type\": \"object\",\n        \"required\": [\n          \"a\"\n        ],\n        \"properties\": {\n          \"a\": {\n            \"$ref\": \"#/$defs/NonEmptyString\"\n          }\n        },\n        \"additionalProperties\": false\n      }\n    )\n  })\n\n  describe(\"extend\", () => {\n    it(\"should correctly generate JSON Schemas for a schema created by extending two refinements\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.String\n        }).pipe(\n          Schema.filter(() => true, {\n            jsonSchema: { \"examples\": [\"c5052c04-d6c9-44f3-9c8f-ede707d6ce38\"] }\n          })\n        ).pipe(Schema.extend(\n          Schema.Struct({\n            b: JsonNumber\n          }).pipe(\n            Schema.filter(() => true, {\n              jsonSchema: { \"$comment\": \"940b4ea4-6313-4b59-9e64-ff7a41b8eb15\" }\n            })\n          )\n        )),\n        {\n          \"type\": \"object\",\n          \"required\": [\"a\", \"b\"],\n          \"properties\": {\n            \"a\": { \"type\": \"string\" },\n            \"b\": { \"type\": \"number\" }\n          },\n          \"examples\": [\"c5052c04-d6c9-44f3-9c8f-ede707d6ce38\"],\n          \"$comment\": \"940b4ea4-6313-4b59-9e64-ff7a41b8eb15\",\n          \"additionalProperties\": false\n        }\n      )\n    })\n  })\n\n  describe(\"identifier annotation support\", () => {\n    it(\"String\", () => {\n      expectJSONSchemaProperty(Schema.String.annotations({ identifier: \"6f274f5e-be19-48e6-8f33-16e9789b2731\" }), {\n        \"$defs\": {\n          \"6f274f5e-be19-48e6-8f33-16e9789b2731\": {\n            \"type\": \"string\"\n          }\n        },\n        \"$ref\": \"#/$defs/6f274f5e-be19-48e6-8f33-16e9789b2731\"\n      })\n    })\n\n    it(\"Refinement\", () => {\n      expectJSONSchemaProperty(\n        Schema.String.pipe(Schema.minLength(2)).annotations({ identifier: \"cd6647a4-dc64-40a7-a031-61d35ed904ca\" }),\n        {\n          \"$defs\": {\n            \"cd6647a4-dc64-40a7-a031-61d35ed904ca\": {\n              \"type\": \"string\",\n              \"title\": \"minLength(2)\",\n              \"description\": \"a string at least 2 character(s) long\",\n              \"minLength\": 2\n            }\n          },\n          \"$ref\": \"#/$defs/cd6647a4-dc64-40a7-a031-61d35ed904ca\"\n        }\n      )\n    })\n\n    describe(\"Struct\", () => {\n      it(\"self annotation\", () => {\n        expectJSONSchemaProperty(\n          Schema.Struct({\n            a: Schema.String\n          }).annotations({ identifier: \"0df962f3-f649-4ffc-a3ec-a8b5344dd7de\" }),\n          {\n            \"$defs\": {\n              \"0df962f3-f649-4ffc-a3ec-a8b5344dd7de\": {\n                \"type\": \"object\",\n                \"required\": [\"a\"],\n                \"properties\": {\n                  \"a\": { \"type\": \"string\" }\n                },\n                \"additionalProperties\": false\n              }\n            },\n            \"$ref\": \"#/$defs/0df962f3-f649-4ffc-a3ec-a8b5344dd7de\"\n          }\n        )\n      })\n\n      it(\"field annotations\", () => {\n        const Name = Schema.String.annotations({\n          identifier: \"44873d66-d138-4e2a-9782-5982a29f6ea8\",\n          description: \"e5d30f53-b2df-4fa3-b151-9fc3a47d258e\",\n          title: \"0115ccbf-5d27-41ed-a658-83c5f4a8805f\"\n        })\n        const schema = Schema.Struct({\n          a: Name\n        })\n        expectJSONSchemaProperty(schema, {\n          \"$defs\": {\n            \"44873d66-d138-4e2a-9782-5982a29f6ea8\": {\n              \"type\": \"string\",\n              \"description\": \"e5d30f53-b2df-4fa3-b151-9fc3a47d258e\",\n              \"title\": \"0115ccbf-5d27-41ed-a658-83c5f4a8805f\"\n            }\n          },\n          \"type\": \"object\",\n          \"required\": [\"a\"],\n          \"properties\": {\n            \"a\": {\n              \"$ref\": \"#/$defs/44873d66-d138-4e2a-9782-5982a29f6ea8\"\n            }\n          },\n          \"additionalProperties\": false\n        })\n      })\n\n      it(\"self annotation + field annotations\", () => {\n        const Name = Schema.String.annotations({\n          identifier: \"b49f125d-1646-4eb5-8120-9524ab6039de\",\n          description: \"703b7ff0-cb8d-49de-aeeb-05d92faa4599\",\n          title: \"4b6d9ea6-7c4d-4073-a427-8d1b82fd1677\"\n        })\n        expectJSONSchemaProperty(\n          Schema.Struct({\n            a: Name\n          }).annotations({ identifier: \"7e559891-9143-4138-ae3e-81a5f0907380\" }),\n          {\n            \"$defs\": {\n              \"7e559891-9143-4138-ae3e-81a5f0907380\": {\n                \"type\": \"object\",\n                \"required\": [\"a\"],\n                \"properties\": {\n                  \"a\": { \"$ref\": \"#/$defs/b49f125d-1646-4eb5-8120-9524ab6039de\" }\n                },\n                \"additionalProperties\": false\n              },\n              \"b49f125d-1646-4eb5-8120-9524ab6039de\": {\n                \"type\": \"string\",\n                \"description\": \"703b7ff0-cb8d-49de-aeeb-05d92faa4599\",\n                \"title\": \"4b6d9ea6-7c4d-4073-a427-8d1b82fd1677\"\n              }\n            },\n            \"$ref\": \"#/$defs/7e559891-9143-4138-ae3e-81a5f0907380\"\n          }\n        )\n      })\n\n      it(\"deeply nested field annotations\", () => {\n        const Name = Schema.String.annotations({\n          identifier: \"434a08dd-3f8f-4de4-b91d-8846aab1fb05\",\n          description: \"eb183f5c-404c-4686-b78b-1bd00d18f8fd\",\n          title: \"c0cbd438-1fb5-47fe-bf81-1ff5527e779a\"\n        })\n        const schema = Schema.Struct({ a: Name, b: Schema.Struct({ c: Name }) })\n        expectJSONSchemaProperty(schema, {\n          \"$defs\": {\n            \"434a08dd-3f8f-4de4-b91d-8846aab1fb05\": {\n              \"type\": \"string\",\n              \"description\": \"eb183f5c-404c-4686-b78b-1bd00d18f8fd\",\n              \"title\": \"c0cbd438-1fb5-47fe-bf81-1ff5527e779a\"\n            }\n          },\n          \"type\": \"object\",\n          \"required\": [\"a\", \"b\"],\n          \"properties\": {\n            \"a\": {\n              \"$ref\": \"#/$defs/434a08dd-3f8f-4de4-b91d-8846aab1fb05\"\n            },\n            \"b\": {\n              \"type\": \"object\",\n              \"required\": [\"c\"],\n              \"properties\": {\n                \"c\": { \"$ref\": \"#/$defs/434a08dd-3f8f-4de4-b91d-8846aab1fb05\" }\n              },\n              \"additionalProperties\": false\n            }\n          },\n          \"additionalProperties\": false\n        })\n      })\n    })\n\n    describe(\"Union\", () => {\n      it(\"Union of literals with identifiers\", () => {\n        expectJSONSchemaAnnotations(\n          Schema.Union(\n            Schema.Literal(\"a\").annotations({\n              description: \"ef296f1c-01fe-4a20-bd35-ed449c964c49\",\n              identifier: \"170d659f-112e-4e3b-85db-464b668f2aed\"\n            }),\n            Schema.Literal(\"b\").annotations({\n              description: \"effbf54b-a62d-455b-86fa-97a5af46c6f3\",\n              identifier: \"2a4e4f67-3732-4f7b-a505-856e51dd1578\"\n            })\n          ),\n          {\n            \"$defs\": {\n              \"170d659f-112e-4e3b-85db-464b668f2aed\": {\n                \"type\": \"string\",\n                \"enum\": [\"a\"],\n                \"description\": \"ef296f1c-01fe-4a20-bd35-ed449c964c49\"\n              },\n              \"2a4e4f67-3732-4f7b-a505-856e51dd1578\": {\n                \"type\": \"string\",\n                \"enum\": [\"b\"],\n                \"description\": \"effbf54b-a62d-455b-86fa-97a5af46c6f3\"\n              }\n            },\n            \"anyOf\": [\n              { \"$ref\": \"#/$defs/170d659f-112e-4e3b-85db-464b668f2aed\" },\n              { \"$ref\": \"#/$defs/2a4e4f67-3732-4f7b-a505-856e51dd1578\" }\n            ]\n          }\n        )\n      })\n    })\n\n    describe(\"Transformation\", () => {\n      describe(\"TypeLiteralTransformation\", () => {\n        it(\"an identifier annotation on the transformation should overwrite an annotation set on the from part\", () => {\n          const schema = Schema.make(\n            new AST.Transformation(\n              new AST.TypeLiteral([new AST.PropertySignature(\"a\", Schema.String.ast, false, true)], [], {\n                [AST.IdentifierAnnotationId]: \"0f70b90b-b268-46c8-a5a3-035139ad9126\"\n              }),\n              new AST.TypeLiteral([new AST.PropertySignature(\"a\", Schema.String.ast, false, true)], [], {\n                [AST.IdentifierAnnotationId]: \"77bb2410-9cf3-47cf-af76-fa3be1a3c626\"\n              }),\n              new AST.TypeLiteralTransformation([]),\n              { [AST.IdentifierAnnotationId]: \"18e1de28-a15e-4373-bd2f-d53903942656\" }\n            )\n          )\n          expectJSONSchemaProperty(schema, {\n            \"$defs\": {\n              \"18e1de28-a15e-4373-bd2f-d53903942656\": {\n                \"type\": \"object\",\n                \"required\": [\"a\"],\n                \"properties\": {\n                  \"a\": { \"type\": \"string\" }\n                },\n                \"additionalProperties\": false\n              }\n            },\n            \"$ref\": \"#/$defs/18e1de28-a15e-4373-bd2f-d53903942656\"\n          })\n        })\n\n        it(\"with transformation description, title and identifier\", () => {\n          expectJSONSchemaProperty(\n            Schema.Struct({\n              a: Schema.optionalWith(\n                Schema.NonEmptyString.annotations({\n                  description: \"inner-description\",\n                  title: \"inner-title\"\n                }),\n                { default: () => \"\" }\n              ).annotations({\n                description: \"middle-description\",\n                title: \"middle-title\"\n              })\n            }).annotations({\n              description: \"outer-description\",\n              title: \"outer-title\",\n              identifier: \"75d9b539-eb6b-48d3-81dd-61176a9bce78\"\n            }),\n            {\n              \"$defs\": {\n                \"75d9b539-eb6b-48d3-81dd-61176a9bce78\": {\n                  \"type\": \"object\",\n                  \"description\": \"outer-description\",\n                  \"title\": \"outer-title\",\n                  \"required\": [],\n                  \"properties\": {\n                    \"a\": {\n                      \"type\": \"string\",\n                      \"description\": \"middle-description\",\n                      \"title\": \"middle-title\",\n                      \"minLength\": 1\n                    }\n                  },\n                  \"additionalProperties\": false\n                }\n              },\n              \"$ref\": \"#/$defs/75d9b539-eb6b-48d3-81dd-61176a9bce78\"\n            }\n          )\n        })\n      })\n    })\n  })\n\n  describe(\"surrogate annotation support\", () => {\n    describe(\"Class\", () => {\n      it(\"should support typeSchema(Class)\", () => {\n        class A extends Schema.Class<A>(\"A\")({ a: Schema.String }) {}\n        expectJSONSchemaProperty(Schema.typeSchema(A), {\n          \"$defs\": {\n            \"A\": {\n              \"type\": \"object\",\n              \"required\": [\"a\"],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"additionalProperties\": false\n            }\n          },\n          \"$ref\": \"#/$defs/A\"\n        })\n        expectJSONSchemaProperty(\n          Schema.typeSchema(A).annotations({\n            description: \"description\",\n            title: \"title\"\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [\"a\"],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\"\n              }\n            },\n            \"additionalProperties\": false,\n            \"description\": \"description\",\n            \"title\": \"title\"\n          }\n        )\n      })\n\n      it(\"with identifier annotation\", () => {\n        class A extends Schema.Class<A>(\"A\")({ a: Schema.String }, {\n          identifier: \"ID\",\n          description: \"description\",\n          title: \"title\"\n        }) {}\n        expectJSONSchemaProperty(Schema.typeSchema(A), {\n          \"$defs\": {\n            \"ID\": {\n              \"type\": \"object\",\n              \"required\": [\"a\"],\n              \"properties\": {\n                \"a\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"additionalProperties\": false,\n              \"description\": \"description\",\n              \"title\": \"title\"\n            }\n          },\n          \"$ref\": \"#/$defs/ID\"\n        })\n        expectJSONSchemaProperty(\n          Schema.typeSchema(A).annotations({\n            description: \"description\",\n            title: \"title\"\n          }),\n          {\n            \"type\": \"object\",\n            \"required\": [\"a\"],\n            \"properties\": {\n              \"a\": {\n                \"type\": \"string\"\n              }\n            },\n            \"additionalProperties\": false,\n            \"description\": \"description\",\n            \"title\": \"title\"\n          }\n        )\n      })\n    })\n  })\n\n  describe(\"jsonSchema annotation support\", () => {\n    it(\"refinements without a jsonSchema annotation should be ignored rather than raising an error\", () => {\n      const schema = Schema.String.pipe(Schema.filter(() => true))\n      expectJSONSchema(schema, {\n        \"type\": \"string\"\n      })\n    })\n\n    it(\"should have higher priority than surrogate annotation\", () => {\n      expectJSONSchema(\n        Schema.String.annotations({\n          [AST.SurrogateAnnotationId]: Schema.Number.ast,\n          jsonSchema: { \"type\": \"custom\" }\n        }),\n        {\n          \"type\": \"custom\"\n        }\n      )\n    })\n\n    describe(\"Class\", () => {\n      it(\"should support typeSchema(Class) with custom annotation\", () => {\n        class A extends Schema.Class<A>(\"3c9977ee-0e9b-4471-99af-c6c73340f9ed\")({ a: Schema.String }, {\n          jsonSchema: { \"type\": \"custom\" }\n        }) {}\n        expectJSONSchema(Schema.typeSchema(A), {\n          \"$defs\": {\n            \"3c9977ee-0e9b-4471-99af-c6c73340f9ed\": {\n              \"type\": \"custom\"\n            }\n          },\n          \"$ref\": \"#/$defs/3c9977ee-0e9b-4471-99af-c6c73340f9ed\"\n        })\n      })\n    })\n\n    it(\"Declaration\", () => {\n      class MyType {}\n      const schema = Schema.declare<MyType>((x) => x instanceof MyType, {\n        jsonSchema: {\n          type: \"my-type\",\n          title: \"default-title\",\n          description: \"default-description\"\n        }\n      }).annotations({\n        title: \"My Title\",\n        description: \"My Description\"\n      })\n      expectJSONSchema(schema, {\n        \"type\": \"my-type\",\n        \"title\": \"My Title\",\n        \"description\": \"My Description\"\n      })\n    })\n\n    it(\"Void\", () => {\n      expectJSONSchema(Schema.Void.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"Never\", () => {\n      expectJSONSchema(Schema.Never.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"Literal\", () => {\n      expectJSONSchema(Schema.Literal(\"a\").annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"SymbolFromSelf\", () => {\n      expectJSONSchema(Schema.SymbolFromSelf.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"UniqueSymbolFromSelf\", () => {\n      expectJSONSchema(\n        Schema.UniqueSymbolFromSelf(Symbol.for(\"effect/schema/test/a\")).annotations({\n          jsonSchema: { \"type\": \"custom\" }\n        }),\n        { \"type\": \"custom\" }\n      )\n    })\n\n    it(\"TemplateLiteral\", () => {\n      expectJSONSchema(\n        Schema.TemplateLiteral(Schema.Literal(\"a\"), Schema.String, Schema.Literal(\"b\")).annotations({\n          jsonSchema: { \"type\": \"custom\" }\n        }),\n        { \"type\": \"custom\" }\n      )\n    })\n\n    it(\"Undefined\", () => {\n      expectJSONSchema(Schema.Undefined.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"Unknown\", () => {\n      expectJSONSchema(Schema.Unknown.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"Any\", () => {\n      expectJSONSchema(Schema.Any.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"Object\", () => {\n      expectJSONSchema(Schema.Object.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"String\", () => {\n      expectJSONSchema(\n        Schema.String.annotations({\n          jsonSchema: {\n            \"type\": \"custom\",\n            \"description\": \"description\",\n            \"format\": \"uuid\"\n          }\n        }),\n        {\n          \"type\": \"custom\",\n          \"description\": \"description\",\n          \"format\": \"uuid\"\n        }\n      )\n      expectJSONSchema(\n        Schema.String.annotations({\n          identifier: \"630d10c4-7030-45e7-894d-2c0bf5acadcf\",\n          jsonSchema: { \"type\": \"custom\", \"description\": \"description\" }\n        }),\n        {\n          \"$defs\": {\n            \"630d10c4-7030-45e7-894d-2c0bf5acadcf\": {\n              \"type\": \"custom\",\n              \"description\": \"description\"\n            }\n          },\n          \"$ref\": \"#/$defs/630d10c4-7030-45e7-894d-2c0bf5acadcf\"\n        }\n      )\n    })\n\n    it(\"Number\", () => {\n      expectJSONSchema(Schema.Number.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"BigintFromSelf\", () => {\n      expectJSONSchema(Schema.BigIntFromSelf.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"Boolean\", () => {\n      expectJSONSchema(Schema.Boolean.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"Enums\", () => {\n      enum Fruits {\n        Apple,\n        Banana\n      }\n      expectJSONSchema(Schema.Enums(Fruits).annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"Tuple\", () => {\n      expectJSONSchema(\n        Schema.Tuple(Schema.String, JsonNumber).annotations({ jsonSchema: { \"type\": \"custom\" } }),\n        { \"type\": \"custom\" }\n      )\n    })\n\n    it(\"Struct\", () => {\n      expectJSONSchema(\n        Schema.Struct({ a: Schema.String, b: JsonNumber }).annotations({\n          jsonSchema: { \"type\": \"custom\" }\n        }),\n        { \"type\": \"custom\" }\n      )\n    })\n\n    it(\"Union\", () => {\n      expectJSONSchema(\n        Schema.Union(Schema.String, JsonNumber).annotations({ jsonSchema: { \"type\": \"custom\" } }),\n        { \"type\": \"custom\" }\n      )\n    })\n\n    it(\"UUID\", () => {\n      expectJSONSchema(\n        Schema.UUID,\n        {\n          \"$defs\": {\n            \"UUID\": {\n              \"description\": \"a Universally Unique Identifier\",\n              \"pattern\": \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\",\n              \"type\": \"string\",\n              \"format\": \"uuid\"\n            }\n          },\n          \"$ref\": \"#/$defs/UUID\"\n        }\n      )\n    })\n\n    it(\"Suspend\", () => {\n      interface A {\n        readonly a: string\n        readonly as: ReadonlyArray<A>\n      }\n      const schema = Schema.Struct({\n        a: Schema.String,\n        as: Schema.Array(\n          Schema.suspend((): Schema.Schema<A> => schema).annotations({ jsonSchema: { \"type\": \"custom\" } })\n        )\n      })\n\n      expectJSONSchema(schema, {\n        \"type\": \"object\",\n        \"required\": [\n          \"a\",\n          \"as\"\n        ],\n        \"properties\": {\n          \"a\": {\n            \"type\": \"string\"\n          },\n          \"as\": {\n            \"type\": \"array\",\n            \"items\": {\n              \"type\": \"custom\"\n            }\n          }\n        },\n        \"additionalProperties\": false\n      })\n    })\n\n    describe(\"Refinement\", () => {\n      it(\"Int\", () => {\n        expectJSONSchema(Schema.Int.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n          \"type\": \"custom\"\n        })\n      })\n\n      it(\"custom\", () => {\n        expectJSONSchemaProperty(\n          Schema.String.pipe(Schema.filter(() => true, { jsonSchema: {} })).annotations({\n            identifier: \"230acf3d-b3b0-4c3e-8ccc-5ca089c80014\"\n          }),\n          {\n            \"$ref\": \"#/$defs/230acf3d-b3b0-4c3e-8ccc-5ca089c80014\",\n            \"$defs\": {\n              \"230acf3d-b3b0-4c3e-8ccc-5ca089c80014\": {\n                \"type\": \"string\"\n              }\n            }\n          }\n        )\n      })\n    })\n\n    it(\"Transformation\", () => {\n      expectJSONSchema(Schema.NumberFromString.annotations({ jsonSchema: { \"type\": \"custom\" } }), {\n        \"type\": \"custom\"\n      })\n    })\n\n    it(\"refinement of a transformation with an override annotation\", () => {\n      expectJSONSchema(Schema.Date.annotations({ jsonSchema: { type: \"string\", format: \"date-time\" } }), {\n        \"format\": \"date-time\",\n        \"type\": \"string\"\n      })\n      expectJSONSchema(\n        Schema.Date.annotations({\n          jsonSchema: { anyOf: [{ type: \"object\" }, { type: \"array\" }] }\n        }),\n        {\n          \"anyOf\": [{ \"type\": \"object\" }, { \"type\": \"array\" }]\n        }\n      )\n      expectJSONSchema(\n        Schema.Date.annotations({\n          jsonSchema: { anyOf: [{ type: \"object\" }, { type: \"array\" }] }\n        }),\n        {\n          \"anyOf\": [{ \"type\": \"object\" }, { \"type\": \"array\" }]\n        }\n      )\n      expectJSONSchema(Schema.Date.annotations({ jsonSchema: { \"$ref\": \"x\" } }), {\n        \"$ref\": \"x\"\n      })\n      expectJSONSchema(Schema.Date.annotations({ jsonSchema: { \"type\": \"number\", \"const\": 1 } }), {\n        \"type\": \"number\",\n        \"const\": 1\n      })\n      expectJSONSchema(Schema.Date.annotations({ jsonSchema: { \"type\": \"number\", \"enum\": [1] } }), {\n        \"type\": \"number\",\n        \"enum\": [1]\n      })\n    })\n\n    it(\"refinement of a transformation without an override annotation\", () => {\n      expectJSONSchema(Schema.Trim.pipe(Schema.nonEmptyString()), {\n        \"type\": \"string\",\n        \"description\": \"a string that will be trimmed\"\n      })\n      expectJSONSchema(\n        Schema.Trim.pipe(Schema.nonEmptyString({ jsonSchema: { title: \"a0ba6c10-091e-4ceb-9773-25fb1466fb1b\" } })),\n        {\n          \"type\": \"string\",\n          \"description\": \"a string that will be trimmed\"\n        }\n      )\n      expectJSONSchema(\n        Schema.Trim.pipe(Schema.nonEmptyString()).annotations({\n          jsonSchema: { title: \"75f7eb4f-626d-4dc6-af48-c17094418d85\" }\n        }),\n        {\n          \"type\": \"string\",\n          \"description\": \"a string that will be trimmed\"\n        }\n      )\n    })\n  })\n\n  describe(\"Pruning `undefined` and make the property optional by default\", () => {\n    it(\"Undefined\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.Undefined\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"$id\": \"/schemas/never\",\n              \"not\": {},\n              \"title\": \"never\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"UndefinedOr(Undefined)\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.UndefinedOr(Schema.Undefined)\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"$id\": \"/schemas/never\",\n              \"not\": {},\n              \"title\": \"never\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"Nested `Undefined`s\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.UndefinedOr(Schema.UndefinedOr(Schema.Undefined))\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"$id\": \"/schemas/never\",\n              \"not\": {},\n              \"title\": \"never\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"Schema.optional\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.optional(Schema.String)\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": { \"type\": \"string\" }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"Schema.optional + inner annotation\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.optional(Schema.String.annotations({ description: \"inner\" }))\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\",\n              \"description\": \"inner\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"Schema.optional + outer annotation should override inner annotation\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.optional(Schema.String.annotations({ description: \"inner\" })).annotations({\n            description: \"outer\"\n          })\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\",\n              \"description\": \"outer\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"UndefinedOr\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.UndefinedOr(Schema.String)\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"UndefinedOr + inner annotation\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.UndefinedOr(Schema.String.annotations({ description: \"inner\" }))\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\",\n              \"description\": \"inner\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"UndefinedOr + annotation should not override inner annotations\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.UndefinedOr(Schema.String.annotations({ description: \"inner\" })).annotations({\n            description: \"middle\"\n          })\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\",\n              \"description\": \"inner\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"UndefinedOr + propertySignature annotation should override inner and middle annotations\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.propertySignature(\n            Schema.UndefinedOr(Schema.String.annotations({ description: \"inner\" })).annotations({\n              description: \"middle\"\n            })\n          ).annotations({ description: \"outer\" })\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\",\n              \"description\": \"outer\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"UndefinedOr + jsonSchema annotation should keep the property required\", () => {\n      expectJSONSchema(\n        Schema.Struct({\n          a: Schema.UndefinedOr(Schema.String).annotations({ jsonSchema: { \"type\": \"string\" } })\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [\"a\"],\n          \"properties\": {\n            \"a\": { \"type\": \"string\" }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"Transformation: OptionFromUndefinedOr\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.OptionFromUndefinedOr(Schema.String)\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n\n    it(\"Suspend\", () => {\n      expectJSONSchemaAnnotations(\n        Schema.Struct({\n          a: Schema.suspend(() => Schema.UndefinedOr(Schema.String))\n        }),\n        {\n          \"type\": \"object\",\n          \"required\": [],\n          \"properties\": {\n            \"a\": {\n              \"type\": \"string\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      )\n    })\n  })\n\n  describe(\"Schema.encodedBoundSchema / Schema.encodedSchema\", () => {\n    describe(\"borrowing the identifier\", () => {\n      describe(\"Declaration\", () => {\n        it(\"without inner transformation\", () => {\n          const schema = Schema.Chunk(Schema.String).annotations({ identifier: \"ID\" })\n          const expected = {\n            \"items\": {\n              \"type\": \"string\"\n            },\n            \"type\": \"array\"\n          }\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), expected)\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), expected)\n        })\n\n        it(\"with inner transformation\", () => {\n          const schema = Schema.Chunk(Schema.NumberFromString).annotations({\n            identifier: \"ID\"\n          })\n          const expected = {\n            \"items\": {\n              \"description\": \"a string to be decoded into a number\",\n              \"type\": \"string\"\n            },\n            \"type\": \"array\"\n          }\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), expected)\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), expected)\n        })\n      })\n\n      describe(\"Refinement\", () => {\n        it(\"without from transformation\", () => {\n          const schema = Schema.Trimmed\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), {\n            \"$defs\": {\n              \"Trimmed\": {\n                \"title\": \"trimmed\",\n                \"description\": \"a string with no leading or trailing whitespace\",\n                \"pattern\": \"^\\\\S[\\\\s\\\\S]*\\\\S$|^\\\\S$|^$\",\n                \"type\": \"string\"\n              }\n            },\n            \"$ref\": \"#/$defs/Trimmed\"\n          })\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), {\n            \"type\": \"string\"\n          })\n        })\n\n        it(\"with from transformation\", () => {\n          const schema = Schema.compose(Schema.String, Schema.Trimmed).annotations({\n            identifier: \"ID\"\n          })\n          const expected = {\n            \"type\": \"string\"\n          }\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), expected)\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), expected)\n        })\n\n        it(\"a stable filter without inner transformations\", () => {\n          const schema = Schema.Array(Schema.NumberFromString).pipe(Schema.minItems(2)).annotations(\n            { identifier: \"ID\" }\n          )\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), {\n            \"$defs\": {\n              \"ID\": {\n                \"description\": \"an array of at least 2 item(s)\",\n                \"title\": \"minItems(2)\",\n                \"items\": {\n                  \"description\": \"a string to be decoded into a number\",\n                  \"type\": \"string\"\n                },\n                \"minItems\": 2,\n                \"type\": \"array\"\n              }\n            },\n            \"$ref\": \"#/$defs/ID\"\n          })\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), {\n            \"items\": {\n              \"description\": \"a string to be decoded into a number\",\n              \"type\": \"string\"\n            },\n            \"type\": \"array\"\n          })\n        })\n\n        it(\"a stable filter with inner transformations SHOULD NOT borrow the annotations, identifier included\", () => {\n          const schema = Schema.compose(Schema.Unknown, Schema.Array(Schema.String)).pipe(Schema.minItems(1))\n          const expected = {\n            \"$id\": \"/schemas/unknown\",\n            \"title\": \"unknown\"\n          }\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), expected)\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), expected)\n        })\n      })\n\n      describe(\"Tuple\", () => {\n        it(\"without inner transformations\", () => {\n          const schema = Schema.Tuple(Schema.String).annotations({\n            identifier: \"4d8bbca3-9462-4679-8ee6-e4e718711552\"\n          })\n          const expected = {\n            \"$defs\": {\n              \"4d8bbca3-9462-4679-8ee6-e4e718711552\": {\n                \"additionalItems\": false,\n                \"items\": [{ \"type\": \"string\" }],\n                \"minItems\": 1,\n                \"type\": \"array\"\n              }\n            },\n            \"$ref\": \"#/$defs/4d8bbca3-9462-4679-8ee6-e4e718711552\"\n          }\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), expected)\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), expected)\n        })\n\n        it(\"with inner transformations\", () => {\n          const schema = Schema.Tuple(Schema.NumberFromString).annotations({\n            identifier: \"ID\"\n          })\n          const expected = {\n            \"additionalItems\": false,\n            \"items\": [{\n              \"description\": \"a string to be decoded into a number\",\n              \"type\": \"string\"\n            }],\n            \"minItems\": 1,\n            \"type\": \"array\"\n          }\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), expected)\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), expected)\n        })\n      })\n\n      describe(\"Struct\", () => {\n        it(\"without inner transformations\", () => {\n          const schema = Schema.Struct({ a: Schema.String }).annotations({\n            identifier: \"c8d0663b-c41b-4b6f-8b6e-bff59afc87c3\"\n          })\n          const expected = {\n            \"$defs\": {\n              \"c8d0663b-c41b-4b6f-8b6e-bff59afc87c3\": {\n                \"additionalProperties\": false,\n                \"properties\": {\n                  \"a\": { \"type\": \"string\" }\n                },\n                \"required\": [\"a\"],\n                \"type\": \"object\"\n              }\n            },\n            \"$ref\": \"#/$defs/c8d0663b-c41b-4b6f-8b6e-bff59afc87c3\"\n          }\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), expected)\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), expected)\n        })\n\n        it(\"with inner transformations\", () => {\n          const schema = Schema.Struct({ a: Schema.NumberFromString }).annotations({\n            identifier: \"ID\"\n          })\n          const expected = {\n            \"additionalProperties\": false,\n            \"properties\": {\n              \"a\": {\n                \"description\": \"a string to be decoded into a number\",\n                \"type\": \"string\"\n              }\n            },\n            \"required\": [\"a\"],\n            \"type\": \"object\"\n          }\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), expected)\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), expected)\n        })\n      })\n\n      describe(\"Union\", () => {\n        it(\"without inner transformations\", () => {\n          const schema = Schema.Union(Schema.String, Schema.JsonNumber).annotations({\n            identifier: \"ID\"\n          })\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), {\n            \"$defs\": {\n              \"JsonNumber\": {\n                \"description\": \"a finite number\",\n                \"title\": \"finite\",\n                \"type\": \"number\"\n              },\n              \"ID\": {\n                \"anyOf\": [\n                  { \"type\": \"string\" },\n                  { \"$ref\": \"#/$defs/JsonNumber\" }\n                ]\n              }\n            },\n            \"$ref\": \"#/$defs/ID\"\n          })\n          expectJSONSchema(Schema.encodedSchema(schema), {\n            \"anyOf\": [\n              { \"type\": \"string\" },\n              { \"type\": \"number\" }\n            ]\n          })\n        })\n\n        it(\"with inner transformations\", () => {\n          const schema = Schema.Union(Schema.String, Schema.NumberFromString).annotations({\n            identifier: \"ID\"\n          })\n          const expected = {\n            \"anyOf\": [\n              { \"type\": \"string\" },\n              { \"description\": \"a string to be decoded into a number\", \"type\": \"string\" }\n            ]\n          }\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), expected)\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), expected)\n        })\n      })\n\n      describe(\"Suspend\", () => {\n        it(\"without inner transformations\", () => {\n          interface Category {\n            readonly name: string\n            readonly categories: ReadonlyArray<Category>\n          }\n\n          const schema: Schema.Schema<Category> = Schema.Struct({\n            name: Schema.String,\n            categories: Schema.Array(\n              Schema.suspend(() => schema).annotations({ identifier: \"ID\" })\n            )\n          })\n\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), {\n            \"type\": \"object\",\n            \"required\": [\n              \"name\",\n              \"categories\"\n            ],\n            \"properties\": {\n              \"name\": {\n                \"type\": \"string\"\n              },\n              \"categories\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/IDEncodedBound\"\n                }\n              }\n            },\n            \"additionalProperties\": false,\n            \"$defs\": {\n              \"IDEncodedBound\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"name\",\n                  \"categories\"\n                ],\n                \"properties\": {\n                  \"name\": {\n                    \"type\": \"string\"\n                  },\n                  \"categories\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                      \"$ref\": \"#/$defs/IDEncodedBound\"\n                    }\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            }\n          })\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), {\n            \"type\": \"object\",\n            \"required\": [\n              \"name\",\n              \"categories\"\n            ],\n            \"properties\": {\n              \"name\": {\n                \"type\": \"string\"\n              },\n              \"categories\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/IDEncoded\"\n                }\n              }\n            },\n            \"additionalProperties\": false,\n            \"$defs\": {\n              \"IDEncoded\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"name\",\n                  \"categories\"\n                ],\n                \"properties\": {\n                  \"name\": {\n                    \"type\": \"string\"\n                  },\n                  \"categories\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                      \"$ref\": \"#/$defs/IDEncoded\"\n                    }\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            }\n          })\n        })\n\n        it(\"with inner transformations\", () => {\n          interface Category {\n            readonly name: number\n            readonly categories: ReadonlyArray<Category>\n          }\n          interface CategoryEncoded {\n            readonly name: string\n            readonly categories: ReadonlyArray<CategoryEncoded>\n          }\n\n          const schema: Schema.Schema<Category, CategoryEncoded> = Schema.Struct({\n            name: Schema.NumberFromString,\n            categories: Schema.Array(\n              Schema.suspend(() => schema).annotations({ identifier: \"ID\" })\n            )\n          })\n\n          expectJSONSchemaProperty(Schema.encodedBoundSchema(schema), {\n            \"type\": \"object\",\n            \"required\": [\n              \"name\",\n              \"categories\"\n            ],\n            \"properties\": {\n              \"name\": {\n                \"description\": \"a string to be decoded into a number\",\n                \"type\": \"string\"\n              },\n              \"categories\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/IDEncodedBound\"\n                }\n              }\n            },\n            \"additionalProperties\": false,\n            \"$defs\": {\n              \"IDEncodedBound\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"name\",\n                  \"categories\"\n                ],\n                \"properties\": {\n                  \"name\": {\n                    \"description\": \"a string to be decoded into a number\",\n                    \"type\": \"string\"\n                  },\n                  \"categories\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                      \"$ref\": \"#/$defs/IDEncodedBound\"\n                    }\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            }\n          })\n          expectJSONSchemaProperty(Schema.encodedSchema(schema), {\n            \"type\": \"object\",\n            \"required\": [\n              \"name\",\n              \"categories\"\n            ],\n            \"properties\": {\n              \"name\": {\n                \"description\": \"a string to be decoded into a number\",\n                \"type\": \"string\"\n              },\n              \"categories\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/$defs/IDEncoded\"\n                }\n              }\n            },\n            \"additionalProperties\": false,\n            \"$defs\": {\n              \"IDEncoded\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"name\",\n                  \"categories\"\n                ],\n                \"properties\": {\n                  \"name\": {\n                    \"description\": \"a string to be decoded into a number\",\n                    \"type\": \"string\"\n                  },\n                  \"categories\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                      \"$ref\": \"#/$defs/IDEncoded\"\n                    }\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            }\n          })\n        })\n      })\n\n      it(\"Transformation\", () => {\n        const expected = {\n          \"type\": \"string\",\n          \"description\": \"a string to be decoded into a number\"\n        }\n        expectJSONSchemaProperty(Schema.encodedBoundSchema(Schema.NumberFromString), expected)\n        expectJSONSchemaProperty(Schema.encodedSchema(Schema.NumberFromString), expected)\n      })\n    })\n  })\n\n  it(\"Exit\", () => {\n    const schema = Schema.Exit({\n      failure: Schema.String,\n      success: Schema.Number,\n      defect: Schema.Defect\n    })\n    expectJSONSchemaProperty(schema, {\n      \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n      \"$defs\": {\n        \"CauseEncoded0\": {\n          \"anyOf\": [\n            {\n              \"type\": \"object\",\n              \"required\": [\n                \"_tag\"\n              ],\n              \"properties\": {\n                \"_tag\": {\n                  \"type\": \"string\",\n                  \"enum\": [\n                    \"Empty\"\n                  ]\n                }\n              },\n              \"additionalProperties\": false\n            },\n            {\n              \"type\": \"object\",\n              \"required\": [\n                \"_tag\",\n                \"error\"\n              ],\n              \"properties\": {\n                \"_tag\": {\n                  \"type\": \"string\",\n                  \"enum\": [\n                    \"Fail\"\n                  ]\n                },\n                \"error\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"additionalProperties\": false\n            },\n            {\n              \"type\": \"object\",\n              \"required\": [\n                \"_tag\",\n                \"defect\"\n              ],\n              \"properties\": {\n                \"_tag\": {\n                  \"type\": \"string\",\n                  \"enum\": [\n                    \"Die\"\n                  ]\n                },\n                \"defect\": {\n                  \"$ref\": \"#/$defs/Defect\"\n                }\n              },\n              \"additionalProperties\": false\n            },\n            {\n              \"type\": \"object\",\n              \"required\": [\n                \"_tag\",\n                \"fiberId\"\n              ],\n              \"properties\": {\n                \"_tag\": {\n                  \"type\": \"string\",\n                  \"enum\": [\n                    \"Interrupt\"\n                  ]\n                },\n                \"fiberId\": {\n                  \"$ref\": \"#/$defs/FiberIdEncoded\"\n                }\n              },\n              \"additionalProperties\": false\n            },\n            {\n              \"type\": \"object\",\n              \"required\": [\n                \"_tag\",\n                \"left\",\n                \"right\"\n              ],\n              \"properties\": {\n                \"_tag\": {\n                  \"type\": \"string\",\n                  \"enum\": [\n                    \"Sequential\"\n                  ]\n                },\n                \"left\": {\n                  \"$ref\": \"#/$defs/CauseEncoded0\"\n                },\n                \"right\": {\n                  \"$ref\": \"#/$defs/CauseEncoded0\"\n                }\n              },\n              \"additionalProperties\": false\n            },\n            {\n              \"type\": \"object\",\n              \"required\": [\n                \"_tag\",\n                \"left\",\n                \"right\"\n              ],\n              \"properties\": {\n                \"_tag\": {\n                  \"type\": \"string\",\n                  \"enum\": [\n                    \"Parallel\"\n                  ]\n                },\n                \"left\": {\n                  \"$ref\": \"#/$defs/CauseEncoded0\"\n                },\n                \"right\": {\n                  \"$ref\": \"#/$defs/CauseEncoded0\"\n                }\n              },\n              \"additionalProperties\": false\n            }\n          ],\n          \"title\": \"CauseEncoded<string>\"\n        },\n        \"Defect\": {\n          \"$id\": \"/schemas/unknown\",\n          \"title\": \"unknown\"\n        },\n        \"FiberIdEncoded\": {\n          \"anyOf\": [\n            {\n              \"$ref\": \"#/$defs/FiberIdNoneEncoded\"\n            },\n            {\n              \"$ref\": \"#/$defs/FiberIdRuntimeEncoded\"\n            },\n            {\n              \"$ref\": \"#/$defs/FiberIdCompositeEncoded\"\n            }\n          ]\n        },\n        \"FiberIdNoneEncoded\": {\n          \"type\": \"object\",\n          \"required\": [\n            \"_tag\"\n          ],\n          \"properties\": {\n            \"_tag\": {\n              \"type\": \"string\",\n              \"enum\": [\n                \"None\"\n              ]\n            }\n          },\n          \"additionalProperties\": false\n        },\n        \"FiberIdRuntimeEncoded\": {\n          \"type\": \"object\",\n          \"required\": [\n            \"_tag\",\n            \"id\",\n            \"startTimeMillis\"\n          ],\n          \"properties\": {\n            \"_tag\": {\n              \"type\": \"string\",\n              \"enum\": [\n                \"Runtime\"\n              ]\n            },\n            \"id\": {\n              \"$ref\": \"#/$defs/Int\"\n            },\n            \"startTimeMillis\": {\n              \"$ref\": \"#/$defs/Int\"\n            }\n          },\n          \"additionalProperties\": false\n        },\n        \"Int\": {\n          \"type\": \"integer\",\n          \"description\": \"an integer\",\n          \"title\": \"int\"\n        },\n        \"FiberIdCompositeEncoded\": {\n          \"type\": \"object\",\n          \"required\": [\n            \"_tag\",\n            \"left\",\n            \"right\"\n          ],\n          \"properties\": {\n            \"_tag\": {\n              \"type\": \"string\",\n              \"enum\": [\n                \"Composite\"\n              ]\n            },\n            \"left\": {\n              \"$ref\": \"#/$defs/FiberIdEncoded\"\n            },\n            \"right\": {\n              \"$ref\": \"#/$defs/FiberIdEncoded\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      },\n      \"anyOf\": [\n        {\n          \"type\": \"object\",\n          \"required\": [\n            \"_tag\",\n            \"cause\"\n          ],\n          \"properties\": {\n            \"_tag\": {\n              \"type\": \"string\",\n              \"enum\": [\n                \"Failure\"\n              ]\n            },\n            \"cause\": {\n              \"$ref\": \"#/$defs/CauseEncoded0\"\n            }\n          },\n          \"additionalProperties\": false\n        },\n        {\n          \"type\": \"object\",\n          \"required\": [\n            \"_tag\",\n            \"value\"\n          ],\n          \"properties\": {\n            \"_tag\": {\n              \"type\": \"string\",\n              \"enum\": [\n                \"Success\"\n              ]\n            },\n            \"value\": {\n              \"type\": \"number\"\n            }\n          },\n          \"additionalProperties\": false\n        }\n      ],\n      \"title\": \"ExitEncoded<number, string, Defect>\"\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/ParseResult.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFailure,\n  assertLeft,\n  assertSuccess,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { Cause, Effect, Either, ParseResult } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport { inspect } from \"node:util\"\n\nconst asEffect = <A, E>(either: Either.Either<A, E>): Effect.Effect<A, E> => either\n\nconst expectGetRefinementExpected = (schema: S.Schema.Any, expected: string) => {\n  if (AST.isRefinement(schema.ast)) {\n    strictEqual(ParseResult.getRefinementExpected(schema.ast), expected)\n  } else {\n    // eslint-disable-next-line no-console\n    console.log(schema.ast)\n    throw new Error(`expected a Refinement`)\n  }\n}\n\ndescribe(\"ParseResult\", () => {\n  const typeParseError1 = ParseResult.parseError(new ParseResult.Type(S.String.ast, null))\n  const typeParseError2 = ParseResult.parseError(new ParseResult.Type(S.Number.ast, null))\n\n  it(\"getRefinementExpected\", () => {\n    expectGetRefinementExpected(S.Number.pipe(S.filter(() => true)), \"{ number | filter }\")\n    expectGetRefinementExpected(S.Number.pipe(S.int()), \"an integer\")\n    expectGetRefinementExpected(S.Number.pipe(S.int(), S.positive()), \"a positive number\")\n    expectGetRefinementExpected(S.Int.pipe(S.positive()), \"a positive number\")\n  })\n\n  describe(\"ParseError\", () => {\n    it(\"toString()\", () => {\n      const schema = S.Struct({ a: S.String })\n      assertLeft(\n        S.decodeUnknownEither(schema)({}).pipe(Either.mapLeft((e) => e.toString())),\n        `{ readonly a: string }\n└─ [\"a\"]\n   └─ is missing`\n      )\n    })\n\n    it(\"toJSON()\", () => {\n      const schema = S.Struct({ a: S.String })\n      assertLeft(S.decodeUnknownEither(schema)({}).pipe(Either.mapLeft((e) => (e as any).toJSON())), {\n        _id: \"ParseError\",\n        message: `{ readonly a: string }\n└─ [\"a\"]\n   └─ is missing`\n      })\n    })\n\n    it(\"[NodeInspectSymbol]\", () => {\n      const schema = S.Struct({ a: S.String })\n      assertLeft(\n        S.decodeUnknownEither(schema)({}).pipe(Either.mapLeft((e) => inspect(e))),\n        inspect({\n          _id: \"ParseError\",\n          message: `{ readonly a: string }\n└─ [\"a\"]\n   └─ is missing`\n        })\n      )\n    })\n\n    it(\"Error.stack\", () => {\n      assertTrue(\n        ParseResult.parseError(new ParseResult.Type(S.String.ast, 1)).stack?.startsWith(\n          `ParseError: Expected string, actual 1`\n        )\n      )\n    })\n\n    it(\"Effect.catchTag can be used to catch ParseError\", () => {\n      const program = Effect.fail(typeParseError1).pipe(\n        Effect.catchTag(\"ParseError\", () => Effect.succeed(1))\n      )\n      strictEqual(Effect.runSync(program), 1)\n    })\n  })\n\n  it(\"eitherOrUndefined\", () => {\n    deepStrictEqual(ParseResult.eitherOrUndefined(Either.right(1)), Either.right(1))\n    deepStrictEqual(ParseResult.eitherOrUndefined(Either.left(\"err\")), Either.left(\"err\"))\n    strictEqual(ParseResult.eitherOrUndefined(Effect.succeed(1)), undefined)\n    strictEqual(ParseResult.eitherOrUndefined(Effect.fail(\"err\")), undefined)\n  })\n\n  it(\"flatMap\", () => {\n    deepStrictEqual(\n      ParseResult.flatMap(Either.right(1), (a) => Either.right(a)),\n      Either.right(1) as Effect.Effect<number>\n    )\n    deepStrictEqual(\n      ParseResult.flatMap(Either.right(1), () => Either.left(\"err\")),\n      Either.left(\"err\") as Effect.Effect<never, string>\n    )\n    assertSuccess(\n      Effect.runSyncExit(\n        ParseResult.flatMap(Either.right(1), (a) => Either.right(a))\n      ),\n      1\n    )\n    assertSuccess(\n      Effect.runSyncExit(\n        ParseResult.flatMap(Either.right(1), (a) => Effect.succeed(a))\n      ),\n      1\n    )\n    assertFailure(\n      Effect.runSyncExit(ParseResult.flatMap(Either.right(1), () => Either.left(\"err\"))),\n      Cause.fail(\"err\")\n    )\n    assertFailure(\n      Effect.runSyncExit(ParseResult.flatMap(Either.right(1), () => Effect.fail(\"err\"))),\n      Cause.fail(\"err\")\n    )\n  })\n\n  it(\"map\", () => {\n    deepStrictEqual(ParseResult.map(Either.right(1), (n) => n + 1), asEffect(Either.right(2)))\n    deepStrictEqual(ParseResult.map(Either.left(typeParseError1), (n) => n + 1), asEffect(Either.left(typeParseError1)))\n    deepStrictEqual(Either.right(1).pipe(ParseResult.map((n) => n + 1)), Either.right(2))\n    assertSuccess(Effect.runSyncExit(ParseResult.map(Effect.succeed(1), (n) => n + 1)), 2)\n    assertFailure(\n      Effect.runSyncExit(ParseResult.map(Effect.fail(typeParseError1), (n) => n + 1)),\n      Cause.fail(typeParseError1)\n    )\n  })\n\n  it(\"mapError\", () => {\n    deepStrictEqual(ParseResult.mapError(Either.right(1), () => typeParseError2), asEffect(Either.right(1)))\n    deepStrictEqual(\n      ParseResult.mapError(Either.left(typeParseError1), () => typeParseError2),\n      asEffect(Either.left(typeParseError2))\n    )\n    // pipeable\n    deepStrictEqual(Either.right(1).pipe(ParseResult.mapError(() => typeParseError2)), Either.right(1))\n    assertSuccess(Effect.runSyncExit(ParseResult.mapError(Effect.succeed(1), () => typeParseError2)), 1)\n    assertFailure(\n      Effect.runSyncExit(\n        ParseResult.mapError(Effect.fail(typeParseError1), () => typeParseError2)\n      ),\n      Cause.fail(typeParseError2)\n    )\n  })\n\n  it(\"mapBoth\", () => {\n    deepStrictEqual(\n      ParseResult.mapBoth(Either.right(1), { onFailure: () => typeParseError2, onSuccess: (n) => n + 1 }),\n      asEffect(Either.right(2))\n    )\n    deepStrictEqual(\n      ParseResult.mapBoth(Either.left(typeParseError1), {\n        onFailure: () => typeParseError2,\n        onSuccess: (n) => n + 1\n      }),\n      asEffect(Either.left(typeParseError2))\n    )\n    // pipeable\n    deepStrictEqual(\n      Either.right(1).pipe(ParseResult.mapBoth({ onFailure: () => typeParseError2, onSuccess: (n) => n + 1 })),\n      Either.right(2)\n    )\n    assertSuccess(\n      Effect.runSyncExit(\n        ParseResult.mapBoth(Effect.succeed(1), { onFailure: () => typeParseError2, onSuccess: (n) => n + 1 })\n      ),\n      2\n    )\n    assertFailure(\n      Effect.runSyncExit(\n        ParseResult.mapBoth(Effect.fail(typeParseError1), {\n          onFailure: () => typeParseError2,\n          onSuccess: (n) => n + 1\n        })\n      ),\n      Cause.fail(typeParseError2)\n    )\n  })\n\n  it(\"orElse\", () => {\n    deepStrictEqual(ParseResult.orElse(Either.right(1), () => Either.right(2)), asEffect(Either.right(1)))\n    deepStrictEqual(ParseResult.orElse(Either.left(typeParseError1), () => Either.right(2)), asEffect(Either.right(2)))\n    // pipeable\n    deepStrictEqual(Either.right(1).pipe(ParseResult.orElse(() => Either.right(2))), Either.right(1))\n    assertSuccess(Effect.runSyncExit(ParseResult.orElse(Effect.succeed(1), () => Either.right(2))), 1)\n    assertSuccess(\n      Effect.runSyncExit(\n        ParseResult.orElse(Effect.fail(typeParseError1), () => Either.right(2))\n      ),\n      2\n    )\n  })\n})\n\ndescribe(\"ParseIssue.actual\", () => {\n  it(\"transform decode\", () => {\n    const result = S.decodeEither(S.transformOrFail(\n      S.NumberFromString,\n      S.Boolean,\n      {\n        strict: true,\n        decode: (n, _, ast) => ParseResult.fail(new ParseResult.Type(ast, n)),\n        encode: (b, _, ast) => ParseResult.fail(new ParseResult.Type(ast, b))\n      }\n    ))(\"1\")\n    if (Either.isRight(result)) throw new Error(\"Expected failure\")\n    strictEqual(result.left.issue.actual, \"1\")\n    strictEqual((result.left.issue as ParseResult.Transformation).issue.actual, 1)\n  })\n\n  it(\"transform encode\", () => {\n    const result = S.encodeEither(S.transformOrFail(\n      S.Boolean,\n      S.NumberFromString,\n      {\n        strict: true,\n        decode: (n, _, ast) => ParseResult.fail(new ParseResult.Type(ast, n)),\n        encode: (b, _, ast) => ParseResult.fail(new ParseResult.Type(ast, b))\n      }\n    ))(1)\n    if (Either.isRight(result)) throw new Error(\"Expected failure\")\n    strictEqual(result.left.issue.actual, 1)\n    strictEqual((result.left.issue as ParseResult.Transformation).issue.actual, \"1\")\n  })\n\n  it(\"compose decode\", () => {\n    const result = S.decodeEither(S.compose(S.NumberFromString, S.Number.pipe(S.negative())))(\"1\")\n    if (Either.isRight(result)) throw new Error(\"Expected failure\")\n    strictEqual(result.left.issue.actual, \"1\")\n    strictEqual((result.left.issue as ParseResult.Transformation).issue.actual, 1)\n  })\n\n  it(\"compose encode\", () => {\n    const result = S.encodeEither(S.compose(S.String.pipe(S.length(5)), S.NumberFromString))(1)\n    if (Either.isRight(result)) throw new Error(\"Expected failure\")\n    strictEqual(result.left.issue.actual, 1)\n    strictEqual((result.left.issue as ParseResult.Transformation).issue.actual, \"1\")\n  })\n\n  it(\"decode\", () => {\n    assertTrue(Either.isEither(ParseResult.decode(S.String)(\"a\")))\n  })\n\n  it(\"encode\", () => {\n    assertTrue(Either.isEither(ParseResult.encode(S.String)(\"a\")))\n  })\n\n  it(\"mergeInternalOptions\", () => {\n    strictEqual(ParseResult.mergeInternalOptions(undefined, undefined), undefined)\n    deepStrictEqual(ParseResult.mergeInternalOptions({}, undefined), {})\n    deepStrictEqual(ParseResult.mergeInternalOptions(undefined, {}), {})\n    deepStrictEqual(ParseResult.mergeInternalOptions({ errors: undefined }, undefined), { errors: undefined })\n    deepStrictEqual(ParseResult.mergeInternalOptions(undefined, { errors: undefined }), { errors: undefined })\n    deepStrictEqual(ParseResult.mergeInternalOptions({ errors: \"all\" }, { errors: \"first\" }), {\n      errors: \"first\"\n    })\n    deepStrictEqual(ParseResult.mergeInternalOptions({ onExcessProperty: \"ignore\" }, { onExcessProperty: \"error\" }), {\n      onExcessProperty: \"error\"\n    })\n    deepStrictEqual(ParseResult.mergeInternalOptions({}, { exact: false }), { exact: false })\n    deepStrictEqual(ParseResult.mergeInternalOptions({ exact: true }, { exact: false }), { exact: false })\n\n    deepStrictEqual(ParseResult.mergeInternalOptions({ isEffectAllowed: true }, {}), { isEffectAllowed: true })\n    deepStrictEqual(ParseResult.mergeInternalOptions({}, { isEffectAllowed: true }), { isEffectAllowed: true })\n    deepStrictEqual(ParseResult.mergeInternalOptions({ isEffectAllowed: false }, { isEffectAllowed: true }), {\n      isEffectAllowed: true\n    })\n  })\n\n  it(\"asserts\", () => {\n    const schema = S.String\n    strictEqual(ParseResult.asserts(schema)(\"a\"), undefined)\n    throws(\n      () => ParseResult.asserts(schema)(1),\n      new ParseResult.ParseError({ issue: new ParseResult.Type(schema.ast, 1) })\n    )\n  })\n\n  describe(\"getLiterals\", () => {\n    it(\"StringKeyword\", () => {\n      deepStrictEqual(ParseResult.getLiterals(S.String.ast, true), [])\n    })\n\n    it(\"Struct\", () => {\n      deepStrictEqual(ParseResult.getLiterals(S.Struct({ _tag: S.Literal(\"a\") }).ast, true), [[\n        \"_tag\",\n        new AST.Literal(\"a\")\n      ]])\n    })\n\n    it(\"Tuple\", () => {\n      deepStrictEqual(ParseResult.getLiterals(S.Tuple(S.Literal(\"a\"), S.String).ast, true), [[0, new AST.Literal(\"a\")]])\n    })\n\n    it(\"Refinement\", () => {\n      deepStrictEqual(\n        ParseResult.getLiterals(\n          S.Struct({ _tag: S.Literal(\"a\") }).pipe(\n            S.filter(() => true)\n          ).ast,\n          true\n        ),\n        [[\"_tag\", new AST.Literal(\"a\")]]\n      )\n    })\n\n    it(\"Transform (decode)\", () => {\n      deepStrictEqual(\n        ParseResult.getLiterals(\n          S.Struct({ radius: S.Number }).pipe(S.attachPropertySignature(\"kind\", \"circle\")).ast,\n          true\n        ),\n        []\n      )\n    })\n\n    it(\"Transform (encode)\", () => {\n      deepStrictEqual(\n        ParseResult.getLiterals(\n          S.Struct({ radius: S.Number }).pipe(S.attachPropertySignature(\"kind\", \"circle\")).ast,\n          false\n        ),\n        [[\"kind\", new AST.Literal(\"circle\")]]\n      )\n    })\n\n    it(\"property Transform (encode)\", () => {\n      deepStrictEqual(\n        ParseResult.getLiterals(\n          S.Struct({\n            _tag: S.transform(\n              S.Literal(\"a\"),\n              S.Literal(\"b\"),\n              { strict: true, decode: () => \"b\" as const, encode: () => \"a\" as const }\n            )\n          })\n            .ast,\n          false\n        ),\n        [[\"_tag\", new AST.Literal(\"b\")]]\n      )\n    })\n\n    it(\"Class (decode)\", () => {\n      class A extends S.Class<A>(\"A\")({ _tag: S.Literal(\"a\") }) {}\n      deepStrictEqual(ParseResult.getLiterals(A.ast, true), [[\"_tag\", new AST.Literal(\"a\")]])\n    })\n\n    it(\"Class (encode)\", () => {\n      class A extends S.Class<A>(\"A\")({ _tag: S.Literal(\"a\") }) {}\n      deepStrictEqual(ParseResult.getLiterals(A.ast, false), [[\"_tag\", new AST.Literal(\"a\")]])\n    })\n  })\n\n  describe(\"getSearchTree\", () => {\n    it(\"primitive + primitive\", () => {\n      deepStrictEqual(ParseResult.getSearchTree([S.String.ast, S.Number.ast], true), {\n        keys: {},\n        otherwise: [S.String.ast, S.Number.ast],\n        candidates: []\n      })\n    })\n\n    it(\"struct + primitive\", () => {\n      const a = S.Struct({ _tag: S.Literal(\"a\") })\n      deepStrictEqual(ParseResult.getSearchTree([a.ast, S.Number.ast], true), {\n        keys: {\n          _tag: {\n            buckets: {\n              a: [a.ast]\n            },\n            literals: [new AST.Literal(\"a\")],\n            candidates: [a.ast]\n          }\n        },\n        otherwise: [S.Number.ast],\n        candidates: [a.ast]\n      })\n    })\n\n    it(\"struct + struct (same tag key)\", () => {\n      const a = S.Struct({ _tag: S.Literal(\"a\") })\n      const b = S.Struct({ _tag: S.Literal(\"b\") })\n      deepStrictEqual(ParseResult.getSearchTree([a.ast, b.ast], true), {\n        keys: {\n          _tag: {\n            buckets: {\n              a: [a.ast],\n              b: [b.ast]\n            },\n            literals: [new AST.Literal(\"a\"), new AST.Literal(\"b\")],\n            candidates: [a.ast, b.ast]\n          }\n        },\n        otherwise: [],\n        candidates: [a.ast, b.ast]\n      })\n    })\n\n    it(\"struct + struct (different tag key)\", () => {\n      const A = S.Struct({ a: S.Literal(\"A\"), c: S.String })\n      const B = S.Struct({ b: S.Literal(\"B\"), d: S.Number })\n      deepStrictEqual(\n        ParseResult.getSearchTree([A.ast, B.ast], true),\n        {\n          keys: {\n            a: {\n              buckets: {\n                A: [A.ast]\n              },\n              literals: [new AST.Literal(\"A\")],\n              candidates: [A.ast]\n            },\n            b: {\n              buckets: {\n                B: [B.ast]\n              },\n              literals: [new AST.Literal(\"B\")],\n              candidates: [B.ast]\n            }\n          },\n          otherwise: [],\n          candidates: [A.ast, B.ast]\n        }\n      )\n    })\n\n    it(\"struct + struct (multiple tags)\", () => {\n      const A = S.Struct({ _tag: S.Literal(\"A\"), _tag2: S.Literal(\"A1\"), c: S.String })\n      const B = S.Struct({ _tag: S.Literal(\"A\"), _tag2: S.Literal(\"A2\"), d: S.Number })\n      deepStrictEqual(\n        ParseResult.getSearchTree([A.ast, B.ast], true),\n        {\n          keys: {\n            _tag: {\n              buckets: {\n                A: [A.ast]\n              },\n              literals: [new AST.Literal(\"A\")],\n              candidates: [A.ast]\n            },\n            _tag2: {\n              buckets: {\n                A2: [B.ast]\n              },\n              literals: [new AST.Literal(\"A2\")],\n              candidates: [B.ast]\n            }\n          },\n          otherwise: [],\n          candidates: [A.ast, B.ast]\n        }\n      )\n    })\n\n    it(\"tuple + tuple (same tag key)\", () => {\n      const a = S.Tuple(S.Literal(\"a\"), S.String)\n      const b = S.Tuple(S.Literal(\"b\"), S.Number)\n      deepStrictEqual(\n        ParseResult.getSearchTree([a.ast, b.ast], true),\n        {\n          keys: {\n            0: {\n              buckets: {\n                a: [a.ast],\n                b: [b.ast]\n              },\n              literals: [new AST.Literal(\"a\"), new AST.Literal(\"b\")],\n              candidates: [a.ast, b.ast]\n            }\n          },\n          otherwise: [],\n          candidates: [a.ast, b.ast]\n        }\n      )\n    })\n\n    it(\"tuple + tuple (different tag key)\", () => {\n      const a = S.Tuple(S.Literal(\"a\"), S.String)\n      const b = S.Tuple(S.Number, S.Literal(\"b\"))\n      deepStrictEqual(\n        ParseResult.getSearchTree([a.ast, b.ast], true),\n        {\n          keys: {\n            0: {\n              buckets: {\n                a: [a.ast]\n              },\n              literals: [new AST.Literal(\"a\")],\n              candidates: [a.ast]\n            },\n            1: {\n              buckets: {\n                b: [b.ast]\n              },\n              literals: [new AST.Literal(\"b\")],\n              candidates: [b.ast]\n            }\n          },\n          otherwise: [],\n          candidates: [a.ast, b.ast]\n        }\n      )\n    })\n\n    it(\"tuple + tuple (multiple tags)\", () => {\n      const a = S.Tuple(S.Literal(\"a\"), S.Literal(\"b\"), S.String)\n      const b = S.Tuple(S.Literal(\"a\"), S.Literal(\"c\"), S.Number)\n      deepStrictEqual(\n        ParseResult.getSearchTree([a.ast, b.ast], true),\n        {\n          keys: {\n            0: {\n              buckets: {\n                a: [a.ast]\n              },\n              literals: [new AST.Literal(\"a\")],\n              candidates: [a.ast]\n            },\n            1: {\n              buckets: {\n                c: [b.ast]\n              },\n              literals: [new AST.Literal(\"c\")],\n              candidates: [b.ast]\n            }\n          },\n          otherwise: [],\n          candidates: [a.ast, b.ast]\n        }\n      )\n    })\n\n    it(\"should handle multiple tags\", () => {\n      const a = S.Struct({ category: S.Literal(\"catA\"), tag: S.Literal(\"a\") })\n      const b = S.Struct({ category: S.Literal(\"catA\"), tag: S.Literal(\"b\") })\n      const c = S.Struct({ category: S.Literal(\"catA\"), tag: S.Literal(\"c\") })\n      deepStrictEqual(\n        ParseResult.getSearchTree([\n          a.ast,\n          b.ast,\n          c.ast\n        ], true),\n        {\n          keys: {\n            category: {\n              buckets: {\n                catA: [a.ast]\n              },\n              literals: [new AST.Literal(\"catA\")],\n              candidates: [a.ast]\n            },\n            tag: {\n              buckets: {\n                b: [b.ast],\n                c: [c.ast]\n              },\n              literals: [new AST.Literal(\"b\"), new AST.Literal(\"c\")],\n              candidates: [b.ast, c.ast]\n            }\n          },\n          otherwise: [],\n          candidates: [a.ast, b.ast, c.ast]\n        }\n      )\n    })\n\n    it(\"big union\", () => {\n      const a = S.Struct({ type: S.Literal(\"a\"), value: S.String })\n      const b = S.Struct({ type: S.Literal(\"b\"), value: S.String })\n      const c = S.Struct({ type: S.Literal(\"c\"), value: S.String })\n      const n = S.Struct({ type: S.Literal(null), value: S.String })\n      const schema = S.Union(\n        a,\n        b,\n        c,\n        S.Struct({ type: S.String, value: S.String }),\n        n,\n        S.Struct({ type: S.Undefined, value: S.String }),\n        S.Struct({ type: S.Literal(\"d\", \"e\"), value: S.String }),\n        S.Struct({ type: S.Struct({ nested: S.String }), value: S.String }),\n        S.Struct({ type: S.Array(S.Number), value: S.String })\n      )\n      const types = (schema.ast as AST.Union).types\n      deepStrictEqual(ParseResult.getSearchTree(types, true), {\n        keys: {\n          type: {\n            buckets: {\n              a: [a.ast],\n              b: [b.ast],\n              c: [c.ast],\n              null: [n.ast]\n            },\n            literals: [\n              new AST.Literal(\"a\"),\n              new AST.Literal(\"b\"),\n              new AST.Literal(\"c\"),\n              new AST.Literal(null)\n            ],\n            candidates: [a.ast, b.ast, c.ast, n.ast]\n          }\n        },\n        otherwise: [\n          S.Struct({ type: S.String, value: S.String }).ast,\n          S.Struct({ type: S.Undefined, value: S.String }).ast,\n          S.Struct({ type: S.Literal(\"d\", \"e\"), value: S.String }).ast,\n          S.Struct({ type: S.Struct({ nested: S.String }), value: S.String }).ast,\n          S.Struct({ type: S.Array(S.Number), value: S.String }).ast\n        ],\n        candidates: [\n          a.ast,\n          b.ast,\n          c.ast,\n          n.ast\n        ]\n      })\n    })\n\n    it(\"nested unions\", () => {\n      const a = S.Struct({ _tag: S.Literal(\"a\") })\n      const b = S.Struct({ _tag: S.Literal(\"b\") })\n      const A = S.Struct({ a: S.Literal(\"A\"), c: S.String })\n      const B = S.Struct({ b: S.Literal(\"B\"), d: S.Number })\n      const ab = S.Union(a, b)\n      const AB = S.Union(A, B)\n      const schema = S.Union(ab, AB)\n      const types = (schema.ast as AST.Union).types\n      deepStrictEqual(ParseResult.getSearchTree(types, true), {\n        keys: {},\n        otherwise: [ab.ast, AB.ast],\n        candidates: []\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/ParseResultEffectful.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Effect, ParseResult, Schema } from \"effect\"\nimport * as Util from \"./TestUtils.js\"\n\nconst EffectfulStringFailure = Schema.transformOrFail(Schema.String, Schema.String, {\n  strict: true,\n  decode: (actual, _, ast) =>\n    actual === \"\"\n      ? Effect.fail(new ParseResult.Type(ast, actual, \"Empty String\"))\n      : Effect.succeed(actual),\n  encode: Effect.succeed\n}).annotations({ identifier: \"EffectfulStringFailure\" })\n\ndescribe(\"Effectful Schemas\", () => {\n  describe(\"TupleType\", () => {\n    it(\"elements\", async () => {\n      const schema = Schema.Tuple(EffectfulStringFailure, Schema.String)\n\n      await Util.assertions.decoding.succeed(schema, [\"a\", \"b\"])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"\", \"b\"],\n        `readonly [EffectfulStringFailure, string]\n└─ [0]\n   └─ EffectfulStringFailure\n      └─ Transformation process failure\n         └─ Empty String`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"\", null],\n        `readonly [EffectfulStringFailure, string]\n├─ [0]\n│  └─ EffectfulStringFailure\n│     └─ Transformation process failure\n│        └─ Empty String\n└─ [1]\n   └─ Expected string, actual null`,\n        { parseOptions: Util.ErrorsAll }\n      )\n    })\n\n    it(\"rest\", async () => {\n      const schema = Schema.Array(EffectfulStringFailure)\n\n      await Util.assertions.decoding.succeed(schema, [\"a\", \"b\"])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"\", \"b\"],\n        `ReadonlyArray<EffectfulStringFailure>\n└─ [0]\n   └─ EffectfulStringFailure\n      └─ Transformation process failure\n         └─ Empty String`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"\", \"\"],\n        `ReadonlyArray<EffectfulStringFailure>\n├─ [0]\n│  └─ EffectfulStringFailure\n│     └─ Transformation process failure\n│        └─ Empty String\n└─ [1]\n   └─ EffectfulStringFailure\n      └─ Transformation process failure\n         └─ Empty String`,\n        { parseOptions: Util.ErrorsAll }\n      )\n    })\n\n    it(\"Rest & post rest elements\", async () => {\n      const schema = Schema.Tuple([], Schema.String, EffectfulStringFailure, EffectfulStringFailure)\n\n      await Util.assertions.decoding.succeed(schema, [\"a\", \"b\", \"c\"])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\", \"\", \"\"],\n        `readonly [...string[], EffectfulStringFailure, EffectfulStringFailure]\n└─ [1]\n   └─ EffectfulStringFailure\n      └─ Transformation process failure\n         └─ Empty String`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\", \"\", \"\"],\n        `readonly [...string[], EffectfulStringFailure, EffectfulStringFailure]\n├─ [1]\n│  └─ EffectfulStringFailure\n│     └─ Transformation process failure\n│        └─ Empty String\n└─ [2]\n   └─ EffectfulStringFailure\n      └─ Transformation process failure\n         └─ Empty String`,\n        { parseOptions: Util.ErrorsAll }\n      )\n    })\n  })\n\n  describe(\"TypeLiteral\", () => {\n    it(\"property signatures\", async () => {\n      const schema = Schema.Struct({\n        a: EffectfulStringFailure,\n        b: Schema.String\n      })\n\n      await Util.assertions.decoding.succeed(schema, { a: \"a\", b: \"b\" })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        {},\n        `{ readonly a: EffectfulStringFailure; readonly b: string }\n└─ [\"a\"]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: undefined },\n        `{ readonly a: EffectfulStringFailure; readonly b: string }\n└─ [\"a\"]\n   └─ EffectfulStringFailure\n      └─ Encoded side transformation failure\n         └─ Expected string, actual undefined`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"\", b: \"b\" },\n        `{ readonly a: EffectfulStringFailure; readonly b: string }\n└─ [\"a\"]\n   └─ EffectfulStringFailure\n      └─ Transformation process failure\n         └─ Empty String`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"\", b: null },\n        `{ readonly a: EffectfulStringFailure; readonly b: string }\n├─ [\"a\"]\n│  └─ EffectfulStringFailure\n│     └─ Transformation process failure\n│        └─ Empty String\n└─ [\"b\"]\n   └─ Expected string, actual null`,\n        { parseOptions: Util.ErrorsAll }\n      )\n    })\n\n    it(\"index signatures\", async () => {\n      const schema = Schema.Record({ key: Schema.String, value: EffectfulStringFailure })\n\n      await Util.assertions.decoding.succeed(schema, { a: \"a\", b: \"b\" })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"\" },\n        `{ readonly [x: string]: EffectfulStringFailure }\n└─ [\"a\"]\n   └─ EffectfulStringFailure\n      └─ Transformation process failure\n         └─ Empty String`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"\", b: \"\" },\n        `{ readonly [x: string]: EffectfulStringFailure }\n├─ [\"a\"]\n│  └─ EffectfulStringFailure\n│     └─ Transformation process failure\n│        └─ Empty String\n└─ [\"b\"]\n   └─ EffectfulStringFailure\n      └─ Transformation process failure\n         └─ Empty String`,\n        { parseOptions: Util.ErrorsAll }\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/ParseResultFormatter.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertTrue, deepStrictEqual, strictEqual, throws } from \"@effect/vitest/utils\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"./TestUtils.js\"\n\nconst expectSyncTree = <A, I>(\n  schema: S.Schema<A, I>,\n  input: unknown,\n  expected: string,\n  options?: {\n    readonly parseOptions?: AST.ParseOptions | undefined\n  } | undefined\n) => {\n  const actual = S.decodeUnknownEither(schema)(input, options?.parseOptions).pipe(\n    Either.mapLeft((e) => ParseResult.TreeFormatter.formatIssueSync(e.issue))\n  )\n  assertLeft(actual, expected)\n}\n\nconst expectSyncIssues = <A, I>(\n  schema: S.Schema<A, I>,\n  input: unknown,\n  expected: ReadonlyArray<ParseResult.ArrayFormatterIssue>\n) => {\n  const options: ParseOptions = { errors: \"all\", onExcessProperty: \"error\" }\n  const actual = S.decodeUnknownEither(schema)(input, options).pipe(\n    Either.mapLeft((e) => ParseResult.ArrayFormatter.formatIssueSync(e.issue))\n  )\n  assertLeft(actual, expected)\n}\n\nconst expectAsyncTree = async <A, I>(\n  schema: S.Schema<A, I>,\n  input: unknown,\n  expected: string,\n  options?: {\n    readonly parseOptions?: AST.ParseOptions | undefined\n  } | undefined\n) => {\n  const result = S.decodeUnknownEither(schema)(input, options?.parseOptions)\n  assertTrue(Either.isLeft(result))\n  const actualEffect = ParseResult.TreeFormatter.formatIssue(result.left.issue)\n  assertTrue(Effect.isEffect(actualEffect))\n  throws(() => Effect.runSync(actualEffect))\n  await Effect.runPromise(actualEffect).then((actual) => {\n    strictEqual(actual, expected)\n  })\n}\n\nconst expectAsyncIssues = async <A, I>(\n  schema: S.Schema<A, I>,\n  input: unknown,\n  expected: ReadonlyArray<ParseResult.ArrayFormatterIssue>\n) => {\n  const options: ParseOptions = { errors: \"all\", onExcessProperty: \"error\" }\n  const result = S.decodeUnknownEither(schema)(input, options)\n  assertTrue(Either.isLeft(result))\n  const actualEffect = ParseResult.ArrayFormatter.formatIssue(result.left.issue)\n  assertTrue(Effect.isEffect(actualEffect))\n  throws(() => Effect.runSync(actualEffect))\n  await Effect.runPromise(actualEffect).then((actual) => {\n    deepStrictEqual(actual, expected)\n  })\n}\n\ndescribe(\"Formatters output\", () => {\n  it(\"Effect async message\", async () => {\n    const EffectAsyncMessage = S.String.annotations({\n      message: () =>\n        Effect.gen(function*() {\n          yield* Effect.sleep(\"10 millis\")\n          return \"custom message\"\n        })\n    })\n    const schema = EffectAsyncMessage\n    const input = null\n    await expectAsyncTree(\n      schema,\n      input,\n      \"custom message\"\n    )\n    await expectAsyncIssues(\n      schema,\n      input,\n      [{\n        _tag: \"Type\",\n        path: [],\n        message: \"custom message\"\n      }]\n    )\n  })\n\n  it(\"Effect sync messages\", () => {\n    const EffectSyncMessage = S.String.annotations({\n      message: () => Effect.succeed(1).pipe(Effect.as(\"custom message\"))\n    })\n    const schema = EffectSyncMessage\n    const input = null\n    expectSyncTree(\n      schema,\n      input,\n      \"custom message\"\n    )\n    expectSyncIssues(\n      schema,\n      input,\n      [{\n        _tag: \"Type\",\n        path: [],\n        message: \"custom message\"\n      }]\n    )\n  })\n\n  describe(\"Forbidden\", () => {\n    it(\"default message\", () => {\n      const schema = Util.AsyncStringWithoutIdentifier\n      const input = \"\"\n      expectSyncTree(\n        schema,\n        input,\n        `(string <-> string)\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n      )\n      expectSyncIssues(schema, input, [{\n        _tag: \"Forbidden\",\n        path: [],\n        message:\n          `cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n      }])\n    })\n\n    it(\"default message with identifier\", () => {\n      const schema = Util.AsyncString\n      const input = \"\"\n      expectSyncTree(\n        schema,\n        input,\n        `AsyncString\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n      )\n      expectSyncIssues(schema, input, [{\n        _tag: \"Forbidden\",\n        path: [],\n        message:\n          `cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n      }])\n    })\n\n    it(\"custom message (override=false)\", () => {\n      const schema = Util.AsyncString.annotations({ message: () => \"custom message\" })\n      const input = \"\"\n      expectSyncTree(\n        schema,\n        input,\n        `(string <-> string)\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n      )\n      expectSyncIssues(schema, input, [{\n        _tag: \"Forbidden\",\n        path: [],\n        message:\n          `cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n      }])\n    })\n\n    it(\"custom message (override=true)\", () => {\n      const schema = Util.AsyncString.annotations({\n        message: () => ({ message: \"custom message\", override: true })\n      })\n      const input = \"\"\n      expectSyncTree(\n        schema,\n        input,\n        `(string <-> string)\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n      )\n      expectSyncIssues(schema, input, [{\n        _tag: \"Forbidden\",\n        path: [],\n        message:\n          `cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n      }])\n    })\n  })\n\n  describe(\"sync messages\", () => {\n    describe(\"Missing\", () => {\n      it(\"default message\", () => {\n        const schema = S.Struct({ a: S.String })\n        const input = {}\n        expectSyncTree(\n          schema,\n          input,\n          `{ readonly a: string }\n└─ [\"a\"]\n   └─ is missing`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Missing\",\n          path: [\"a\"],\n          message: \"is missing\"\n        }])\n      })\n\n      it(\"default message with parent identifier\", () => {\n        const schema = S.Struct({ a: S.String }).annotations({ identifier: \"identifier\" })\n        const input = {}\n        expectSyncTree(\n          schema,\n          input,\n          `identifier\n└─ [\"a\"]\n   └─ is missing`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Missing\",\n          path: [\"a\"],\n          message: \"is missing\"\n        }])\n      })\n\n      it(\"parent custom message with override=true\", () => {\n        const schema = S.Struct({ a: S.String }).annotations({\n          message: () => ({ message: \"custom message\", override: true })\n        })\n        const input = {}\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Composite\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n\n      describe(\"missing message\", () => {\n        describe(\"Struct\", () => {\n          it(\"PropertySignatureDeclaration\", () => {\n            const schema = S.Struct({\n              a: S.propertySignature(S.String).annotations({\n                missingMessage: () => \"a80b642a-729f-4676-ba6a-235964afd52b\"\n              })\n            })\n            const input = {}\n            expectSyncTree(\n              schema,\n              input,\n              `{ readonly a: string }\n└─ [\"a\"]\n   └─ a80b642a-729f-4676-ba6a-235964afd52b`\n            )\n            expectSyncIssues(schema, input, [{\n              _tag: \"Missing\",\n              path: [\"a\"],\n              message: \"a80b642a-729f-4676-ba6a-235964afd52b\"\n            }])\n          })\n\n          it(\"PropertySignatureDeclaration + PropertySignatureTransformation\", () => {\n            const schema = S.Struct({\n              a: S.propertySignature(S.String).annotations({\n                missingMessage: () => \"1ff9f37a-1f50-4ee2-906d-e824067d4cf7\"\n              }),\n              b: S.propertySignature(S.String).annotations({\n                missingMessage: () => \"132f0e48-ae12-4bbb-8473-3dd433de2eb0\"\n              }).pipe(S.fromKey(\"c\"))\n            })\n            const input = {}\n            expectSyncTree(\n              schema,\n              input,\n              `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      ├─ [\"a\"]\n      │  └─ 1ff9f37a-1f50-4ee2-906d-e824067d4cf7\n      └─ [\"c\"]\n         └─ 132f0e48-ae12-4bbb-8473-3dd433de2eb0`,\n              { parseOptions: Util.ErrorsAll }\n            )\n            expectSyncIssues(schema, input, [{\n              _tag: \"Missing\",\n              path: [\"a\"],\n              message: \"1ff9f37a-1f50-4ee2-906d-e824067d4cf7\"\n            }, {\n              _tag: \"Missing\",\n              path: [\"c\"],\n              message: \"132f0e48-ae12-4bbb-8473-3dd433de2eb0\"\n            }])\n          })\n        })\n\n        describe(\"Tuple\", () => {\n          it(\"e\", () => {\n            const schema = S.make(\n              new AST.TupleType(\n                [\n                  new AST.OptionalType(AST.stringKeyword, false, {\n                    [AST.MissingMessageAnnotationId]: () => \"my missing message\"\n                  })\n                ],\n                [],\n                true\n              )\n            )\n            const input: Array<string> = []\n            expectSyncTree(\n              schema,\n              input,\n              `readonly [string]\n└─ [0]\n   └─ my missing message`\n            )\n            expectSyncIssues(schema, input, [{\n              _tag: \"Missing\",\n              path: [0],\n              message: \"my missing message\"\n            }])\n          })\n\n          it(\"r + e\", () => {\n            const schema = S.Tuple(\n              [],\n              S.String,\n              S.element(S.String).annotations({ [AST.MissingMessageAnnotationId]: () => \"my missing message\" })\n            )\n            const input: Array<string> = []\n            expectSyncTree(\n              schema,\n              input,\n              `readonly [...string[], string]\n└─ [0]\n   └─ my missing message`\n            )\n            expectSyncIssues(schema, input, [{\n              _tag: \"Missing\",\n              path: [0],\n              message: \"my missing message\"\n            }])\n          })\n        })\n      })\n    })\n\n    describe(\"Unexpected\", () => {\n      it(\"default message\", () => {\n        const schema = S.Struct({ a: S.String })\n        const input = { a: \"a\", b: 1 }\n        expectSyncTree(\n          schema,\n          input,\n          `{ readonly a: string }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`,\n          { parseOptions: Util.onExcessPropertyError }\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Unexpected\",\n          path: [\"b\"],\n          message: `is unexpected, expected: \"a\"`\n        }])\n      })\n\n      it(\"default message with parent identifier\", () => {\n        const schema = S.Struct({ a: S.String }).annotations({ identifier: \"identifier\" })\n        const input = { a: \"a\", b: 1 }\n        expectSyncTree(\n          schema,\n          input,\n          `identifier\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`,\n          { parseOptions: Util.onExcessPropertyError }\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Unexpected\",\n          path: [\"b\"],\n          message: `is unexpected, expected: \"a\"`\n        }])\n      })\n\n      it(\"parent custom message with override=true\", () => {\n        const schema = S.Struct({ a: S.String }).annotations({\n          message: () => ({ message: \"custom message\", override: true })\n        })\n        const input = { a: \"a\", b: 1 }\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\",\n          { parseOptions: Util.onExcessPropertyError }\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Composite\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n    })\n\n    describe(\"Declaration\", () => {\n      it(\"default message\", () => {\n        const schema = S.OptionFromSelf(S.String)\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          \"Expected Option<string>, actual null\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected Option<string>, actual null\"\n        }])\n      })\n\n      it(\"default message with identifier\", () => {\n        const schema = S.OptionFromSelf(S.String).annotations({ identifier: \"identifier\" })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          \"Expected identifier, actual null\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected identifier, actual null\"\n        }])\n      })\n\n      it(\"custom message (override=false)\", () => {\n        const schema = S.OptionFromSelf(S.String).annotations({ message: () => \"custom message\" })\n        const input = Option.some(1)\n        expectSyncTree(\n          schema,\n          input,\n          `Option<string>\n└─ Expected string, actual 1`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual 1\"\n        }])\n      })\n\n      it(\"custom message (override=true)\", () => {\n        const schema = S.OptionFromSelf(S.String).annotations({\n          message: () => ({ message: \"custom message\", override: true })\n        })\n        const input = Option.some(1)\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Composite\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n    })\n\n    describe(\"String\", () => {\n      it(\"default message\", () => {\n        const schema = S.String\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          \"Expected string, actual null\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual null\"\n        }])\n      })\n\n      it(\"default message with identifier\", () => {\n        const schema = S.String.annotations({ identifier: \"ID\" })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          \"Expected ID, actual null\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected ID, actual null\"\n        }])\n      })\n\n      it(\"custom message\", () => {\n        const schema = S.String.annotations({ message: () => \"custom message\" })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n    })\n\n    describe(\"Transformation\", () => {\n      it(\"default message\", () => {\n        const schema = S.transformOrFail(\n          S.String,\n          S.String,\n          {\n            strict: true,\n            decode: (s, _, ast) => ParseResult.fail(new ParseResult.Type(ast, s)),\n            encode: ParseResult.succeed\n          }\n        )\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          `(string <-> string)\n└─ Encoded side transformation failure\n   └─ Expected string, actual null`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual null\"\n        }])\n      })\n\n      it(\"default message with identifier\", () => {\n        const schema = S.transformOrFail(\n          S.String,\n          S.String,\n          {\n            strict: true,\n            decode: (s, _, ast) => ParseResult.fail(new ParseResult.Type(ast, s)),\n            encode: ParseResult.succeed\n          }\n        ).annotations({ identifier: \"identifier\" })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          `identifier\n└─ Encoded side transformation failure\n   └─ Expected string, actual null`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual null\"\n        }])\n      })\n\n      it(\"default message with message field (kind=Transformation)\", () => {\n        const schema = S.transformOrFail(\n          S.String,\n          S.String,\n          {\n            strict: true,\n            decode: (s, _, ast) => ParseResult.fail(new ParseResult.Type(ast, s, \"transformation failure\")),\n            encode: ParseResult.succeed\n          }\n        )\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          `(string <-> string)\n└─ Transformation process failure\n   └─ transformation failure`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Transformation\",\n          path: [],\n          message: \"transformation failure\"\n        }])\n      })\n\n      it(\"custom message (kind=From, override=false)\", () => {\n        const schema = S.transform(\n          S.String,\n          S.String,\n          {\n            strict: true,\n            decode: identity,\n            encode: identity\n          }\n        ).annotations({ message: () => \"custom message\" })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          `(string <-> string)\n└─ Encoded side transformation failure\n   └─ Expected string, actual null`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual null\"\n        }])\n      })\n\n      it(\"custom message (kind=From, override=true)\", () => {\n        const schema = S.transform(\n          S.String,\n          S.String,\n          {\n            strict: true,\n            decode: identity,\n            encode: identity\n          }\n        ).annotations({ message: () => ({ message: \"custom message\", override: true }) })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Transformation\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n\n      it(\"custom message with inner custom message (kind=From, override=false)\", () => {\n        const schema = S.transform(\n          S.String.annotations({ message: () => \"inner custom message\" }),\n          S.String,\n          {\n            strict: true,\n            decode: identity,\n            encode: identity\n          }\n        ).annotations({ message: () => \"custom message\" })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          \"inner custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Transformation\",\n          path: [],\n          message: \"inner custom message\"\n        }])\n      })\n\n      it(\"custom message with inner custom message (kind=From, override=true)\", () => {\n        const schema = S.transform(\n          S.String.annotations({ message: () => \"inner custom message\" }),\n          S.String,\n          {\n            strict: true,\n            decode: identity,\n            encode: identity\n          }\n        ).annotations({ message: () => ({ message: \"custom message\", override: true }) })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Transformation\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n\n      it(\"custom message (kind=To, override=false)\", () => {\n        const schema = S.transform(\n          S.String,\n          S.NonEmptyString,\n          {\n            strict: true,\n            decode: identity,\n            encode: identity\n          }\n        ).annotations({ message: () => \"custom message\" })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          `(string <-> NonEmptyString)\n└─ Type side transformation failure\n   └─ NonEmptyString\n      └─ Predicate refinement failure\n         └─ Expected a non empty string, actual \"\"`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Refinement\",\n          path: [],\n          message: `Expected a non empty string, actual \"\"`\n        }])\n      })\n\n      it(\"custom message (kind=To, override=true)\", () => {\n        const schema = S.transform(\n          S.String,\n          S.NonEmptyString,\n          {\n            strict: true,\n            decode: identity,\n            encode: identity\n          }\n        ).annotations({ message: () => ({ message: \"custom message\", override: true }) })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Transformation\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n\n      it(\"custom message with inner custom message (kind=To, override=false)\", () => {\n        const schema = S.transform(\n          S.String,\n          S.NonEmptyString.annotations({ message: () => \"inner custom message\" }),\n          {\n            strict: true,\n            decode: identity,\n            encode: identity\n          }\n        ).annotations({ message: () => \"custom message\" })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          \"inner custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Transformation\",\n          path: [],\n          message: \"inner custom message\"\n        }])\n      })\n\n      it(\"custom message with inner custom message (kind=To, override=true)\", () => {\n        const schema = S.transform(\n          S.String,\n          S.NonEmptyString.annotations({ message: () => \"inner custom message\" }),\n          {\n            strict: true,\n            decode: identity,\n            encode: identity\n          }\n        ).annotations({ message: () => ({ message: \"custom message\", override: true }) })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Transformation\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n\n      it(\"custom message (kind=Transformation, override=false)\", () => {\n        const schema = S.transformOrFail(\n          S.String,\n          S.String,\n          {\n            strict: true,\n            decode: (s, _, ast) => ParseResult.fail(new ParseResult.Type(ast, s, \"message field\")),\n            encode: ParseResult.succeed\n          }\n        ).annotations({ message: () => \"custom message\" })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Transformation\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n\n      it(\"custom message (kind=Transformation, override=true)\", () => {\n        const schema = S.transformOrFail(\n          S.String,\n          S.String,\n          {\n            strict: true,\n            decode: (s, _, ast) => ParseResult.fail(new ParseResult.Type(ast, s, \"message field\")),\n            encode: ParseResult.succeed\n          }\n        ).annotations({ message: () => ({ message: \"custom message\", override: true }) })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Transformation\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n    })\n\n    describe(\"Refinement\", () => {\n      it(\"default message (kind=From)\", () => {\n        const schema = S.String.pipe(S.minLength(1))\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          `minLength(1)\n└─ From side refinement failure\n   └─ Expected string, actual null`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual null\"\n        }])\n      })\n\n      it(\"default message with identifier (kind=From)\", () => {\n        const schema = S.String.pipe(S.minLength(1)).annotations({ identifier: \"identifier\" })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          `identifier\n└─ From side refinement failure\n   └─ Expected string, actual null`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual null\"\n        }])\n      })\n\n      it(\"default message (kind=Predicate)\", () => {\n        const schema = S.String.pipe(S.minLength(1))\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          `minLength(1)\n└─ Predicate refinement failure\n   └─ Expected a string at least 1 character(s) long, actual \"\"`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Refinement\",\n          path: [],\n          message: `Expected a string at least 1 character(s) long, actual \"\"`\n        }])\n      })\n\n      it(\"default message with identifier (kind=Predicate)\", () => {\n        const schema = S.String.pipe(S.minLength(1)).annotations({ identifier: \"identifier\" })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          `identifier\n└─ Predicate refinement failure\n   └─ Expected a string at least 1 character(s) long, actual \"\"`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Refinement\",\n          path: [],\n          message: `Expected a string at least 1 character(s) long, actual \"\"`\n        }])\n      })\n\n      it(\"custom message (kind=From, override=false)\", () => {\n        const schema = S.String.pipe(S.minLength(1)).annotations({ message: () => \"custom message\" })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          `minLength(1)\n└─ From side refinement failure\n   └─ Expected string, actual null`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual null\"\n        }])\n      })\n\n      it(\"custom message (kind=From, override=true)\", () => {\n        const schema = S.String.pipe(S.minLength(1)).annotations({\n          message: () => ({ message: \"custom message\", override: true })\n        })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Refinement\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n\n      it(\"custom message (kind=Predicate, override=false)\", () => {\n        const schema = S.String.pipe(S.minLength(1)).annotations({ message: () => \"custom message\" })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Refinement\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n\n      it(\"custom message (kind=Predicate, override=true)\", () => {\n        const schema = S.String.pipe(S.minLength(1)).annotations({\n          message: () => ({ message: \"custom message\", override: true })\n        })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Refinement\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n\n      it(\"custom message with inner custom message (kind=From, override=false)\", () => {\n        const schema = S.String.pipe(S.minLength(1, { message: () => \"inner custom message\" }), S.maxLength(2))\n          .annotations({ message: () => \"custom message\" })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          \"inner custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Refinement\",\n          path: [],\n          message: \"inner custom message\"\n        }])\n      })\n\n      it(\"custom message with inner custom message (kind=From, override=true)\", () => {\n        const schema = S.String.pipe(S.minLength(1, { message: () => \"inner custom message\" }), S.maxLength(2))\n          .annotations({ message: () => ({ message: \"custom message\", override: true }) })\n        const input = \"\"\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Refinement\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n    })\n\n    describe(\"Suspend\", () => {\n      it(\"outer\", () => {\n        type A = readonly [number, A | null]\n        const schema: S.Schema<A> = S.suspend( // intended outer suspend\n          () => S.Tuple(S.Number, S.Union(schema, S.Literal(null)))\n        )\n\n        expectSyncTree(\n          schema,\n          null,\n          `Expected readonly [number, <suspended schema> | null], actual null`\n        )\n        expectSyncTree(\n          schema,\n          [1, undefined],\n          `readonly [number, <suspended schema> | null]\n└─ [1]\n   └─ <suspended schema> | null\n      ├─ Expected readonly [number, <suspended schema> | null], actual undefined\n      └─ Expected null, actual undefined`\n        )\n      })\n\n      it(\"inner\", () => {\n        type A = readonly [number, A | null]\n        const schema: S.Schema<A> = S.Tuple(\n          S.Number,\n          S.Union(S.suspend(() => schema), S.Literal(null))\n        )\n\n        expectSyncTree(\n          schema,\n          null,\n          `Expected readonly [number, <suspended schema> | null], actual null`\n        )\n        expectSyncTree(\n          schema,\n          [1, undefined],\n          `readonly [number, <suspended schema> | null]\n└─ [1]\n   └─ <suspended schema> | null\n      ├─ Expected readonly [number, <suspended schema> | null], actual undefined\n      └─ Expected null, actual undefined`\n        )\n      })\n    })\n\n    describe(\"Union\", () => {\n      it(\"default message\", () => {\n        const schema = S.Union(S.String, S.Number)\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          `string | number\n├─ Expected string, actual null\n└─ Expected number, actual null`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual null\"\n        }, {\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected number, actual null\"\n        }])\n      })\n\n      it(\"default message with identifier\", () => {\n        const schema = S.Union(S.String, S.Number).annotations({ identifier: \"identifier\" })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          `identifier\n├─ Expected string, actual null\n└─ Expected number, actual null`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual null\"\n        }, {\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected number, actual null\"\n        }])\n      })\n\n      it(\"parent custom message with override=false\", () => {\n        const schema = S.Union(S.String, S.Number).annotations({\n          message: () => \"custom message\"\n        })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          `string | number\n├─ Expected string, actual null\n└─ Expected number, actual null`\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected string, actual null\"\n        }, {\n          _tag: \"Type\",\n          path: [],\n          message: \"Expected number, actual null\"\n        }])\n      })\n\n      it(\"parent custom message with override=true\", () => {\n        const schema = S.Union(S.String, S.Number).annotations({\n          message: () => ({ message: \"custom message\", override: true })\n        })\n        const input = null\n        expectSyncTree(\n          schema,\n          input,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input, [{\n          _tag: \"Composite\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n    })\n\n    describe(\"Tuple\", () => {\n      it(\"parent custom message with override=false\", () => {\n        const schema = S.Tuple(S.String).annotations({ message: () => \"custom message\" })\n        const input1 = [1]\n        expectSyncTree(\n          schema,\n          input1,\n          `readonly [string]\n└─ [0]\n   └─ Expected string, actual 1`\n        )\n        expectSyncIssues(schema, input1, [{\n          _tag: \"Type\",\n          path: [0],\n          message: \"Expected string, actual 1\"\n        }])\n      })\n\n      it(\"parent custom message with override=true\", () => {\n        const schema = S.Tuple(S.String).annotations({ message: () => ({ message: \"custom message\", override: true }) })\n        const input1 = [1]\n        expectSyncTree(\n          schema,\n          input1,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input1, [{\n          _tag: \"Composite\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n    })\n\n    describe(\"Struct\", () => {\n      it(\"parent custom message with override=false\", () => {\n        const schema = S.Struct({\n          as: pipe(\n            S.Array(\n              S.Struct({\n                b: pipe(\n                  S.String.annotations({ message: () => \"type\" }),\n                  S.minLength(1, { message: () => \"minLength\" }),\n                  S.maxLength(2, { message: () => \"maxLength\" })\n                )\n              })\n            ).annotations({ identifier: \"C\" }),\n            S.minItems(1, { message: () => \"minItems\" })\n          ).annotations({ identifier: \"B\" })\n        }).annotations({ identifier: \"A\", message: () => \"custom message\" })\n        const input1 = null\n        expectSyncTree(\n          schema,\n          input1,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input1, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"custom message\"\n        }])\n\n        const input2 = { as: [] }\n        expectSyncTree(\n          schema,\n          input2,\n          `A\n└─ [\"as\"]\n   └─ minItems`\n        )\n        expectSyncIssues(schema, input2, [{\n          _tag: \"Refinement\",\n          path: [\"as\"],\n          message: \"minItems\"\n        }])\n\n        const input3 = { as: [{ b: null }] }\n        expectSyncTree(\n          schema,\n          input3,\n          `A\n└─ [\"as\"]\n   └─ B\n      └─ From side refinement failure\n         └─ C\n            └─ [0]\n               └─ { readonly b: minLength(1) & maxLength(2) }\n                  └─ [\"b\"]\n                     └─ type`\n        )\n        expectSyncIssues(schema, input3, [{\n          _tag: \"Refinement\",\n          path: [\"as\", 0, \"b\"],\n          message: \"type\"\n        }])\n\n        const input4 = { as: [{ b: \"\" }] }\n        expectSyncTree(\n          schema,\n          input4,\n          `A\n└─ [\"as\"]\n   └─ B\n      └─ From side refinement failure\n         └─ C\n            └─ [0]\n               └─ { readonly b: minLength(1) & maxLength(2) }\n                  └─ [\"b\"]\n                     └─ minLength`\n        )\n        expectSyncIssues(schema, input4, [{\n          _tag: \"Refinement\",\n          path: [\"as\", 0, \"b\"],\n          message: \"minLength\"\n        }])\n\n        const input5 = { as: [{ b: \"---\" }] }\n        expectSyncTree(\n          schema,\n          input5,\n          `A\n└─ [\"as\"]\n   └─ B\n      └─ From side refinement failure\n         └─ C\n            └─ [0]\n               └─ { readonly b: minLength(1) & maxLength(2) }\n                  └─ [\"b\"]\n                     └─ maxLength`\n        )\n        expectSyncIssues(schema, input5, [{\n          _tag: \"Refinement\",\n          path: [\"as\", 0, \"b\"],\n          message: \"maxLength\"\n        }])\n      })\n\n      it(\"parent custom message with override=true\", () => {\n        const schema = S.Struct({\n          as: pipe(\n            S.Array(\n              S.Struct({\n                b: pipe(\n                  S.String.annotations({ message: () => \"type\" }),\n                  S.minLength(1, { message: () => \"minLength\" }),\n                  S.maxLength(2, { message: () => \"maxLength\" })\n                )\n              })\n            ).annotations({ identifier: \"C\" }),\n            S.minItems(1, { message: () => \"minItems\" })\n          ).annotations({ identifier: \"B\" })\n        }).annotations({ identifier: \"A\", message: () => ({ message: \"custom message\", override: true }) })\n        const input1 = null\n        expectSyncTree(\n          schema,\n          input1,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input1, [{\n          _tag: \"Type\",\n          path: [],\n          message: \"custom message\"\n        }])\n        const input2 = { as: [] }\n        expectSyncTree(\n          schema,\n          input2,\n          \"custom message\"\n        )\n        expectSyncIssues(schema, input2, [{\n          _tag: \"Composite\",\n          path: [],\n          message: \"custom message\"\n        }])\n      })\n    })\n  })\n\n  describe(\"handle identifiers\", () => {\n    it(\"Struct\", () => {\n      const schema = S.Struct({\n        a: S.String.annotations({ identifier: \"MyString1\" }),\n        b: S.String.annotations({ identifier: \"MyString2\" })\n      }).annotations({ identifier: \"MySchema\" })\n\n      expectSyncTree(\n        schema,\n        { a: 1, b: 2 },\n        `MySchema\n├─ [\"a\"]\n│  └─ Expected MyString1, actual 1\n└─ [\"b\"]\n   └─ Expected MyString2, actual 2`,\n        { parseOptions: Util.ErrorsAll }\n      )\n    })\n\n    describe(\"Suspend\", () => {\n      it(\"outer\", () => {\n        type A = readonly [number, A | null]\n        const schema: S.Schema<A> = S.suspend( // intended outer suspend\n          () => S.Tuple(S.Number, S.Union(schema, S.Literal(null)))\n        ).annotations({ identifier: \"A\" })\n\n        expectSyncTree(\n          schema,\n          null,\n          `Expected readonly [number, A | null], actual null`\n        )\n        expectSyncTree(\n          schema,\n          [1, undefined],\n          `readonly [number, A | null]\n└─ [1]\n   └─ A | null\n      ├─ Expected readonly [number, A | null], actual undefined\n      └─ Expected null, actual undefined`\n        )\n      })\n\n      it(\"inner/outer\", () => {\n        type A = readonly [number, A | null]\n        const schema = S.Tuple(\n          S.Number,\n          S.Union(S.suspend((): S.Schema<A> => schema), S.Literal(null))\n        ).annotations({ identifier: \"A\" })\n\n        expectSyncTree(\n          schema,\n          null,\n          `Expected A, actual null`\n        )\n        expectSyncTree(\n          schema,\n          [1, undefined],\n          `A\n└─ [1]\n   └─ A | null\n      ├─ Expected A, actual undefined\n      └─ Expected null, actual undefined`\n        )\n      })\n\n      it(\"inner/inner\", () => {\n        type A = readonly [number, A | null]\n        const schema = S.Tuple(\n          S.Number,\n          S.Union(S.suspend((): S.Schema<A> => schema).annotations({ identifier: \"A\" }), S.Literal(null))\n        )\n\n        expectSyncTree(\n          schema,\n          null,\n          `Expected readonly [number, A | null], actual null`\n        )\n        expectSyncTree(\n          schema,\n          [1, undefined],\n          `readonly [number, A | null]\n└─ [1]\n   └─ A | null\n      ├─ Expected readonly [number, A | null], actual undefined\n      └─ Expected null, actual undefined`\n        )\n      })\n    })\n  })\n\n  it(\"Effect as message\", () => {\n    const translations = {\n      it: \"Nome non valido\",\n      en: \"Invalid name\"\n    }\n\n    class Translator extends Context.Tag(\"Translator\")<Translator, {\n      locale: keyof typeof translations\n      translations: typeof translations\n    }>() {}\n\n    const Name = S.NonEmptyString.annotations({\n      message: () =>\n        Effect.gen(function*() {\n          const service = yield* Effect.serviceOption(Translator)\n          return Option.match(service, {\n            onNone: () => \"Invalid string\",\n            onSome: (translator) => translator.translations[translator.locale]\n          })\n        })\n    })\n\n    const result = S.decodeUnknownEither(Name)(\"\")\n\n    // no service\n    assertLeft(\n      Either.mapLeft(result, (error) => Effect.runSync(ParseResult.TreeFormatter.formatError(error))),\n      \"Invalid string\"\n    )\n\n    // it locale\n    assertLeft(\n      Either.mapLeft(\n        result,\n        (error) =>\n          Effect.runSync(\n            ParseResult.TreeFormatter.formatError(error).pipe(Effect.provideService(Translator, {\n              locale: \"it\",\n              translations\n            }))\n          )\n      ),\n      \"Nome non valido\"\n    )\n\n    // en locale\n    assertLeft(\n      Either.mapLeft(\n        result,\n        (error) =>\n          Effect.runSync(\n            ParseResult.TreeFormatter.formatError(error).pipe(Effect.provideService(Translator, {\n              locale: \"en\",\n              translations\n            }))\n          )\n      ),\n      \"Invalid name\"\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Pretty.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual, throws } from \"@effect/vitest/utils\"\nimport { isUnknown } from \"effect/Predicate\"\nimport * as Pretty from \"effect/Pretty\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"./TestUtils.js\"\n\ndescribe(\"Pretty\", () => {\n  it(\"make\", () => {\n    const schema = S.NumberFromString\n    Util.assertions.pretty(schema, 1, \"1\")\n  })\n\n  it(\"make(S.encodedSchema(schema))\", () => {\n    const schema = S.encodedSchema(S.NumberFromString)\n    Util.assertions.pretty(schema, \"a\", `\"a\"`)\n  })\n\n  it(\"should throw on declarations without annotations\", () => {\n    const schema = S.declare(isUnknown)\n    throws(\n      () => Pretty.make(schema),\n      new Error(`Missing annotation\ndetails: Generating a Pretty for this schema requires a \"pretty\" annotation\nschema (Declaration): <declaration schema>`)\n    )\n  })\n\n  it(\"should throw on never\", () => {\n    const schema = S.Never\n    const pretty = Pretty.make(schema)\n    throws(() => pretty(\"a\" as any as never), new Error(\"Cannot pretty print a `never` value\"))\n  })\n\n  it(\"the errors should disply a path\", () => {\n    throws(\n      () => Pretty.make(S.Tuple(S.declare(isUnknown))),\n      new Error(`Missing annotation\nat path: [0]\ndetails: Generating a Pretty for this schema requires a \"pretty\" annotation\nschema (Declaration): <declaration schema>`)\n    )\n    throws(\n      () => Pretty.make(S.Struct({ a: S.declare(isUnknown) })),\n      new Error(`Missing annotation\nat path: [\"a\"]\ndetails: Generating a Pretty for this schema requires a \"pretty\" annotation\nschema (Declaration): <declaration schema>`)\n    )\n  })\n\n  it(\"should allow for custom compilers\", () => {\n    const match: typeof Pretty.match = {\n      ...Pretty.match,\n      \"BooleanKeyword\": () => (b: boolean) => b ? \"True\" : \"False\"\n    }\n    const go = AST.getCompiler(match)\n    const pretty = <A>(schema: S.Schema<A>) => (a: A): string => go(schema.ast, [])(a)\n    strictEqual(pretty(S.Boolean)(true), `True`)\n    const schema = S.Tuple(S.String, S.Boolean)\n    strictEqual(pretty(schema)([\"a\", true]), `[\"a\", True]`)\n  })\n\n  describe(\"templateLiteral\", () => {\n    it(\"a${string}b\", () => {\n      const schema = S.TemplateLiteral(S.Literal(\"a\"), S.String, S.Literal(\"b\"))\n      Util.assertions.pretty(schema, \"acb\", `\"acb\"`)\n    })\n  })\n\n  it(\"unknown\", () => {\n    const schema = S.Unknown\n    Util.assertions.pretty(schema, \"a\", `\"a\"`)\n    Util.assertions.pretty(schema, 1n, \"1n\")\n  })\n\n  it(\"string\", () => {\n    const schema = S.String\n    Util.assertions.pretty(schema, \"a\", `\"a\"`)\n  })\n\n  it(\"number\", () => {\n    const schema = S.Number\n    Util.assertions.pretty(schema, 1, \"1\")\n    Util.assertions.pretty(schema, NaN, \"NaN\")\n    Util.assertions.pretty(schema, Infinity, \"Infinity\")\n    Util.assertions.pretty(schema, -Infinity, \"-Infinity\")\n  })\n\n  it(\"boolean\", () => {\n    const schema = S.Boolean\n    Util.assertions.pretty(schema, true, \"true\")\n    Util.assertions.pretty(schema, false, \"false\")\n  })\n\n  it(\"bigint\", () => {\n    const schema = S.BigIntFromSelf\n    Util.assertions.pretty(schema, 1n, \"1n\")\n  })\n\n  it(\"symbol\", () => {\n    const schema = S.SymbolFromSelf\n    Util.assertions.pretty(schema, Symbol.for(\"effect/test/a\"), \"Symbol(effect/test/a)\")\n  })\n\n  it(\"void\", () => {\n    const schema = S.Void\n    Util.assertions.pretty(schema, undefined, \"void(0)\")\n  })\n\n  describe(\"literal\", () => {\n    it(\"null\", () => {\n      const schema = S.Literal(null)\n      Util.assertions.pretty(schema, null, \"null\")\n    })\n\n    it(\"bigint\", () => {\n      const schema = S.Literal(1n)\n      Util.assertions.pretty(schema, 1n, \"1n\")\n    })\n  })\n\n  it(\"uniqueSymbolFromSelf\", () => {\n    const a = Symbol.for(\"effect/Schema/test/a\")\n    const schema = S.UniqueSymbolFromSelf(a)\n    Util.assertions.pretty(schema, a, \"Symbol(effect/Schema/test/a)\")\n  })\n\n  describe(\"enums\", () => {\n    it(\"Numeric enums\", () => {\n      enum Fruits {\n        Apple,\n        Banana\n      }\n      const schema = S.Enums(Fruits)\n      Util.assertions.pretty(schema, Fruits.Apple, \"0\")\n      Util.assertions.pretty(schema, Fruits.Banana, \"1\")\n    })\n\n    it(\"String enums\", () => {\n      enum Fruits {\n        Apple = \"apple\",\n        Banana = \"banana\",\n        Cantaloupe = 0\n      }\n      const schema = S.Enums(Fruits)\n      Util.assertions.pretty(schema, Fruits.Apple, `\"apple\"`)\n      Util.assertions.pretty(schema, Fruits.Banana, `\"banana\"`)\n      Util.assertions.pretty(schema, Fruits.Cantaloupe, \"0\")\n    })\n\n    it(\"Const enums\", () => {\n      const Fruits = {\n        Apple: \"apple\",\n        Banana: \"banana\",\n        Cantaloupe: 3\n      } as const\n      const schema = S.Enums(Fruits)\n      Util.assertions.pretty(schema, Fruits.Apple, `\"apple\"`)\n      Util.assertions.pretty(schema, Fruits.Banana, `\"banana\"`)\n      Util.assertions.pretty(schema, Fruits.Cantaloupe, \"3\")\n    })\n  })\n\n  describe(\"struct\", () => {\n    it(\"empty\", () => {\n      const schema = S.Struct({})\n      Util.assertions.pretty(schema, {}, \"{}\")\n    })\n\n    it(\"required fields\", () => {\n      const schema = S.Struct({ a: S.String, b: S.Number })\n      Util.assertions.pretty(schema, { a: \"a\", b: 1 }, `{ \"a\": \"a\", \"b\": 1 }`)\n    })\n\n    it(\"should not output exact optional property signatures\", () => {\n      const schema = S.Struct({ a: S.optionalWith(S.Number, { exact: true }) })\n      Util.assertions.pretty(schema, {}, \"{}\")\n      Util.assertions.pretty(schema, { a: 1 }, `{ \"a\": 1 }`)\n    })\n\n    it(\"should escape keys\", () => {\n      const schema = S.Struct({ \"-\": S.Number })\n      Util.assertions.pretty(schema, { \"-\": 1 }, `{ \"-\": 1 }`)\n    })\n\n    it(\"required property signature\", () => {\n      const schema = S.Struct({ a: S.Number })\n      Util.assertions.pretty(schema, { a: 1 }, `{ \"a\": 1 }`)\n      const x = { a: 1, b: \"b\" }\n      Util.assertions.pretty(schema, x, `{ \"a\": 1 }`)\n    })\n\n    it(\"required property signature with undefined\", () => {\n      const schema = S.Struct({ a: S.Union(S.Number, S.Undefined) })\n      Util.assertions.pretty(schema, { a: 1 }, `{ \"a\": 1 }`)\n      Util.assertions.pretty(schema, { a: undefined }, `{ \"a\": undefined }`)\n      const x = { a: 1, b: \"b\" }\n      Util.assertions.pretty(schema, x, `{ \"a\": 1 }`)\n    })\n\n    it(\"exact optional property signature\", () => {\n      const schema = S.Struct({ a: S.optionalWith(S.Number, { exact: true }) })\n      Util.assertions.pretty(schema, {}, \"{}\")\n      Util.assertions.pretty(schema, { a: 1 }, `{ \"a\": 1 }`)\n      const x = { a: 1, b: \"b\" }\n      Util.assertions.pretty(schema, x, `{ \"a\": 1 }`)\n    })\n\n    it(\"exact optional property signature with undefined\", () => {\n      const schema = S.Struct({ a: S.optionalWith(S.Union(S.Number, S.Undefined), { exact: true }) })\n      Util.assertions.pretty(schema, {}, \"{}\")\n      Util.assertions.pretty(schema, { a: 1 }, `{ \"a\": 1 }`)\n      const x = { a: 1, b: \"b\" }\n      Util.assertions.pretty(schema, x, `{ \"a\": 1 }`)\n      Util.assertions.pretty(schema, { a: undefined }, `{ \"a\": undefined }`)\n    })\n\n    it(\"extend: struct and record\", () => {\n      const schema = S.Struct({ a: S.String }, S.Record({ key: S.String, value: S.Union(S.String, S.Number) }))\n      Util.assertions.pretty(schema, { a: \"a\" }, `{ \"a\": \"a\" }`)\n      Util.assertions.pretty(schema, { a: \"a\", b: \"b\", c: 1 }, `{ \"a\": \"a\", \"b\": \"b\", \"c\": 1 }`)\n    })\n  })\n\n  describe(\"record\", () => {\n    it(\"record(string, string)\", () => {\n      const schema = S.Record({ key: S.String, value: S.String })\n      Util.assertions.pretty(schema, { a: \"a\", b: \"b\" }, `{ \"a\": \"a\", \"b\": \"b\" }`)\n    })\n\n    it(\"record(symbol, string)\", () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const schema = S.Record({ key: S.SymbolFromSelf, value: S.String })\n      Util.assertions.pretty(schema, { [a]: \"a\" }, `{ Symbol(effect/Schema/test/a): \"a\" }`)\n    })\n  })\n\n  describe(\"tuple\", () => {\n    it(\"required element\", () => {\n      const schema = S.Tuple(S.Number)\n      Util.assertions.pretty(schema, [1], `[1]`)\n      const x = [1, \"b\"] as any\n      Util.assertions.pretty(schema, x, `[1]`)\n    })\n\n    it(\"required element with undefined\", () => {\n      const schema = S.Tuple(S.Union(S.Number, S.Undefined))\n      Util.assertions.pretty(schema, [1], `[1]`)\n      Util.assertions.pretty(schema, [undefined], `[undefined]`)\n      const x = [1, \"b\"] as any\n      Util.assertions.pretty(schema, x, `[1]`)\n    })\n\n    it(\"optional element\", () => {\n      const schema = S.Tuple(S.optionalElement(S.Number))\n      Util.assertions.pretty(schema, [], `[]`)\n      Util.assertions.pretty(schema, [1], `[1]`)\n      const x = [1, \"b\"] as any\n      Util.assertions.pretty(schema, x, `[1]`)\n    })\n\n    it(\"optional element with undefined\", () => {\n      const schema = S.Tuple(S.optionalElement(S.Union(S.Number, S.Undefined)))\n      Util.assertions.pretty(schema, [], `[]`)\n      Util.assertions.pretty(schema, [1], `[1]`)\n      const x = [1, \"b\"] as any\n      Util.assertions.pretty(schema, x, `[1]`)\n      Util.assertions.pretty(schema, [undefined], `[undefined]`)\n    })\n\n    it(\"baseline\", () => {\n      const schema = S.Tuple(S.String, S.Number)\n      Util.assertions.pretty(schema, [\"a\", 1], `[\"a\", 1]`)\n    })\n\n    it(\"empty tuple\", () => {\n      const schema = S.Tuple()\n      Util.assertions.pretty(schema, [], `[]`)\n    })\n\n    it(\"optional elements\", () => {\n      const schema = S.Tuple(S.optionalElement(S.String), S.optionalElement(S.Number))\n      Util.assertions.pretty(schema, [], `[]`)\n      Util.assertions.pretty(schema, [\"a\"], `[\"a\"]`)\n      Util.assertions.pretty(schema, [\"a\", 1], `[\"a\", 1]`)\n    })\n\n    it(\"array\", () => {\n      const schema = S.Array(S.String)\n      Util.assertions.pretty(schema, [], `[]`)\n      Util.assertions.pretty(schema, [\"a\"], `[\"a\"]`)\n    })\n\n    it(\"post rest element\", () => {\n      const schema = S.Tuple([], S.Number, S.Boolean)\n      Util.assertions.pretty(schema, [true], `[true]`)\n      Util.assertions.pretty(schema, [1, true], `[1, true]`)\n      Util.assertions.pretty(schema, [1, 2, true], `[1, 2, true]`)\n      Util.assertions.pretty(schema, [1, 2, 3, true], `[1, 2, 3, true]`)\n    })\n\n    it(\"post rest elements\", () => {\n      const schema = S.Tuple([], S.Number, S.Boolean, S.Union(S.String, S.Undefined))\n      Util.assertions.pretty(schema, [true, \"c\"], `[true, \"c\"]`)\n      Util.assertions.pretty(schema, [1, true, \"c\"], `[1, true, \"c\"]`)\n      Util.assertions.pretty(schema, [1, 2, true, \"c\"], `[1, 2, true, \"c\"]`)\n      Util.assertions.pretty(schema, [1, 2, 3, true, \"c\"], `[1, 2, 3, true, \"c\"]`)\n      Util.assertions.pretty(schema, [1, 2, 3, true, undefined], `[1, 2, 3, true, undefined]`)\n    })\n\n    it(\"post rest elements when rest is unknown\", () => {\n      const schema = S.Tuple([], S.Unknown, S.Boolean)\n      Util.assertions.pretty(schema, [1, \"a\", 2, \"b\", true], `[1, \"a\", 2, \"b\", true]`)\n      Util.assertions.pretty(schema, [true], `[true]`)\n    })\n\n    it(\"all\", () => {\n      const schema = S.Tuple([S.String], S.Number, S.Boolean)\n      Util.assertions.pretty(schema, [\"a\", true], `[\"a\", true]`)\n      Util.assertions.pretty(schema, [\"a\", 1, true], `[\"a\", 1, true]`)\n      Util.assertions.pretty(schema, [\"a\", 1, 2, true], `[\"a\", 1, 2, true]`)\n    })\n\n    it(\"nonEmptyArray\", () => {\n      const schema = S.NonEmptyArray(S.Number)\n      Util.assertions.pretty(schema, [1], `[1]`)\n      Util.assertions.pretty(schema, [1, 2], `[1, 2]`)\n    })\n\n    it(\"ReadonlyArray<unknown>\", () => {\n      const schema = S.Array(S.Unknown)\n      Util.assertions.pretty(schema, [], `[]`)\n      Util.assertions.pretty(schema, [\"a\", 1, true], `[\"a\", 1, true]`)\n    })\n\n    it(\"ReadonlyArray<any>\", () => {\n      const schema = S.Array(S.Any)\n      Util.assertions.pretty(schema, [], `[]`)\n      Util.assertions.pretty(schema, [\"a\", 1, true], `[\"a\", 1, true]`)\n    })\n  })\n\n  describe(\"union\", () => {\n    it(\"primitives\", () => {\n      const schema = S.Union(S.String, S.Number)\n      Util.assertions.pretty(schema, \"a\", `\"a\"`)\n      Util.assertions.pretty(schema, 1, \"1\")\n    })\n\n    it(\"discriminated\", () => {\n      const schema = S.Union(\n        S.Struct({ tag: S.Literal(\"a\"), a: S.String }),\n        S.Struct({ tag: S.Literal(\"b\"), b: S.Number })\n      )\n      Util.assertions.pretty(schema, { tag: \"a\", a: \"-\" }, `{ \"tag\": \"a\", \"a\": \"-\" }`)\n      Util.assertions.pretty(schema, { tag: \"b\", b: 1 }, `{ \"tag\": \"b\", \"b\": 1 }`)\n    })\n  })\n\n  it(\"suspend\", () => {\n    interface A {\n      readonly a: string\n      readonly as: ReadonlyArray<A>\n    }\n    const A = S.Struct({\n      a: S.String,\n      as: S.Array(S.suspend((): S.Schema<A> => A))\n    })\n    const schema = A\n    Util.assertions.pretty(schema, { a: \"a\", as: [] }, `{ \"a\": \"a\", \"as\": [] }`)\n  })\n\n  it(\"transformation\", () => {\n    const schema = S.Trim\n    Util.assertions.pretty(schema, \"a\", `\"a\"`)\n  })\n\n  describe(\"should handle annotations\", () => {\n    const expectHook = <A, I>(source: S.Schema<A, I>) => {\n      const schema = source.annotations({ pretty: () => () => \"custom pretty\" })\n      Util.assertions.pretty(schema, null as any, \"custom pretty\")\n    }\n\n    it(\"void\", () => {\n      expectHook(S.Void)\n    })\n\n    it(\"never\", () => {\n      expectHook(S.Never)\n    })\n\n    it(\"literal\", () => {\n      expectHook(S.Literal(\"a\"))\n    })\n\n    it(\"symbol\", () => {\n      expectHook(S.Symbol)\n    })\n\n    it(\"uniqueSymbolFromSelf\", () => {\n      expectHook(S.UniqueSymbolFromSelf(Symbol.for(\"effect/schema/test/a\")))\n    })\n\n    it(\"templateLiteral\", () => {\n      expectHook(S.TemplateLiteral(S.Literal(\"a\"), S.String, S.Literal(\"b\")))\n    })\n\n    it(\"undefined\", () => {\n      expectHook(S.Undefined)\n    })\n\n    it(\"unknown\", () => {\n      expectHook(S.Unknown)\n    })\n\n    it(\"any\", () => {\n      expectHook(S.Any)\n    })\n\n    it(\"object\", () => {\n      expectHook(S.Object)\n    })\n\n    it(\"string\", () => {\n      expectHook(S.String)\n    })\n\n    it(\"number\", () => {\n      expectHook(S.Number)\n    })\n\n    it(\"bigintFromSelf\", () => {\n      expectHook(S.BigIntFromSelf)\n    })\n\n    it(\"boolean\", () => {\n      expectHook(S.Boolean)\n    })\n\n    it(\"enums\", () => {\n      enum Fruits {\n        Apple,\n        Banana\n      }\n      expectHook(S.Enums(Fruits))\n    })\n\n    it(\"tuple\", () => {\n      expectHook(S.Tuple(S.String, S.Number))\n    })\n\n    it(\"struct\", () => {\n      expectHook(S.Struct({ a: S.String, b: S.Number }))\n    })\n\n    it(\"union\", () => {\n      expectHook(S.Union(S.String, S.Number))\n    })\n\n    it(\"suspend\", () => {\n      interface A {\n        readonly a: string\n        readonly as: ReadonlyArray<A>\n      }\n      const schema = S.Struct({\n        a: S.String,\n        as: S.Array(S.suspend((): S.Schema<A> => schema))\n      })\n      expectHook(schema)\n    })\n\n    it(\"refinement\", () => {\n      expectHook(S.Int)\n    })\n\n    it(\"transformation\", () => {\n      expectHook(S.NumberFromString)\n    })\n  })\n\n  it(\"no matching schema error\", () => {\n    const A = S.Struct({ a: S.optionalWith(S.String, { exact: true }) })\n    const schema = S.Union(A, S.Number)\n    const x: {} = { a: undefined }\n    const input: typeof A.Type = x\n    throws(\n      () => Pretty.make(schema)(input),\n      new Error(`Unexpected Error\ndetails: Cannot find a matching schema for {\"a\":undefined}\nschema (Union): { readonly a?: string } | number`)\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Any/Any.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Any\", () => {\n  const schema = S.Any\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, undefined)\n    await Util.assertions.decoding.succeed(schema, null)\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.succeed(schema, 1)\n    await Util.assertions.decoding.succeed(schema, true)\n    await Util.assertions.decoding.succeed(schema, [])\n    await Util.assertions.decoding.succeed(schema, {})\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Array/Array.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Either from \"effect/Either\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"Array\", () => {\n  it(\"should expose the value\", () => {\n    const schema = S.Array(S.String)\n    strictEqual(schema.value, S.String)\n  })\n\n  it(\"should compute the partial result\", () => {\n    const schema = S.Array(S.Number)\n    const all = S.decodeUnknownEither(schema)([1, \"a\", 2, \"b\"], { errors: \"all\" })\n    if (Either.isLeft(all)) {\n      const issue = all.left.issue\n      if (ParseResult.isComposite(issue)) {\n        deepStrictEqual(issue.output, [1, 2])\n      } else {\n        throw new Error(\"expected an And\")\n      }\n    } else {\n      throw new Error(\"expected a Left\")\n    }\n    const first = S.decodeUnknownEither(schema)([1, \"a\", 2, \"b\"], { errors: \"first\" })\n    if (Either.isLeft(first)) {\n      const issue = first.left.issue\n      if (ParseResult.isComposite(issue)) {\n        deepStrictEqual(issue.output, [1])\n      } else {\n        throw new Error(\"expected an And\")\n      }\n    } else {\n      throw new Error(\"expected a Left\")\n    }\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Array/head.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Option from \"effect/Option\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"head\", () => {\n  it(\"decoding\", async () => {\n    const schema = S.head(S.Array(S.NumberFromString))\n    await Util.assertions.decoding.succeed(schema, [], Option.none())\n    await Util.assertions.decoding.succeed(schema, [\"1\"], Option.some(1))\n    await Util.assertions.decoding.fail(\n      schema,\n      [\"a\"],\n      `(ReadonlyArray<NumberFromString> <-> Option<number>)\n└─ Encoded side transformation failure\n   └─ ReadonlyArray<NumberFromString>\n      └─ [0]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.head(S.Array(S.NumberFromString))\n    await Util.assertions.encoding.succeed(schema, Option.none(), [])\n    await Util.assertions.encoding.succeed(schema, Option.some(1), [\"1\"])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Array/headNonEmpty.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"headNonEmpty\", () => {\n  it(\"decoding\", async () => {\n    const schema = S.headNonEmpty(S.NonEmptyArray(S.NumberFromString))\n    await Util.assertions.decoding.succeed(schema, [\"1\"], 1)\n    await Util.assertions.decoding.fail(\n      schema,\n      [\"a\"],\n      `(readonly [NumberFromString, ...NumberFromString[]] <-> number | number)\n└─ Encoded side transformation failure\n   └─ readonly [NumberFromString, ...NumberFromString[]]\n      └─ [0]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.headNonEmpty(S.NonEmptyArray(S.NumberFromString))\n    await Util.assertions.encoding.succeed(schema, 1, [\"1\"])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Array/headOrElse.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"headOrElse\", () => {\n  it(\"decoding (without fallback)\", async () => {\n    const schema = S.headOrElse(S.Array(S.NumberFromString))\n    await Util.assertions.decoding.succeed(schema, [\"1\"], 1)\n    await Util.assertions.decoding.fail(\n      schema,\n      [],\n      `(ReadonlyArray<NumberFromString> <-> number)\n└─ Transformation process failure\n   └─ Unable to retrieve the first element of an empty array`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      [\"a\"],\n      `(ReadonlyArray<NumberFromString> <-> number)\n└─ Encoded side transformation failure\n   └─ ReadonlyArray<NumberFromString>\n      └─ [0]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"decoding (with fallback)\", async () => {\n    const schema = S.headOrElse(S.Array(S.NumberFromString), () => 0)\n    await Util.assertions.decoding.succeed(schema, [\"1\"], 1)\n    await Util.assertions.decoding.succeed(schema, [], 0)\n    await Util.assertions.decoding.fail(\n      schema,\n      [\"a\"],\n      `(ReadonlyArray<NumberFromString> <-> number)\n└─ Encoded side transformation failure\n   └─ ReadonlyArray<NumberFromString>\n      └─ [0]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n    )\n\n    const schema2 = S.Array(S.NumberFromString).pipe(S.headOrElse(() => 0))\n    await Util.assertions.decoding.succeed(schema2, [\"1\"], 1)\n    await Util.assertions.decoding.succeed(schema2, [], 0)\n  })\n\n  it(\"decoding (struct)\", async () => {\n    const schema = S.headOrElse(\n      S.Array(\n        S.Struct({\n          id: S.String,\n          data: S.parseJson()\n        })\n      )\n    )\n    await Util.assertions.decoding.succeed(schema, [\n      {\n        id: \"1\",\n        data: \"{\\\"a\\\":\\\"a\\\"}\"\n      }\n    ], { id: \"1\", data: { a: \"a\" } })\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.headOrElse(S.Array(S.Number))\n    await Util.assertions.encoding.succeed(schema, 1, [1])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Array/itemsCount.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { throws } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"itemsCount\", () => {\n  it(\"should throw for invalid argument\", () => {\n    throws(\n      () => S.Array(S.Number).pipe(S.itemsCount(-1)),\n      new Error(`Invalid Argument\ndetails: Expected an integer greater than or equal to 0, actual -1`)\n    )\n  })\n\n  it(\"should allow 0 as a valid argument\", async () => {\n    const schema = S.Array(S.Number).pipe(S.itemsCount(0))\n    await Util.assertions.decoding.succeed(schema, [])\n    await Util.assertions.decoding.fail(\n      schema,\n      [1],\n      `itemsCount(0)\n└─ Predicate refinement failure\n   └─ Expected an array of exactly 0 item(s), actual [1]`\n    )\n  })\n\n  describe(\"decoding\", () => {\n    it(\"Array\", async () => {\n      const schema = S.Array(S.Number).pipe(S.itemsCount(2))\n\n      await Util.assertions.decoding.succeed(schema, [1, 2])\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        `itemsCount(2)\n└─ Predicate refinement failure\n   └─ Expected an array of exactly 2 item(s), actual []`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1],\n        `itemsCount(2)\n└─ Predicate refinement failure\n   └─ Expected an array of exactly 2 item(s), actual [1]`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, 2, 3],\n        `itemsCount(2)\n└─ Predicate refinement failure\n   └─ Expected an array of exactly 2 item(s), actual [1,2,3]`\n      )\n    })\n\n    it(\"NonEmptyArray\", async () => {\n      const schema = S.NonEmptyArray(S.Number).pipe(S.itemsCount(2))\n\n      await Util.assertions.decoding.succeed(schema, [1, 2])\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        `itemsCount(2)\n└─ From side refinement failure\n   └─ readonly [number, ...number[]]\n      └─ [0]\n         └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1],\n        `itemsCount(2)\n└─ Predicate refinement failure\n   └─ Expected an array of exactly 2 item(s), actual [1]`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, 2, 3],\n        `itemsCount(2)\n└─ Predicate refinement failure\n   └─ Expected an array of exactly 2 item(s), actual [1,2,3]`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Array/maxItems.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { throws } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"maxItems\", () => {\n  it(\"should throw for invalid argument\", () => {\n    throws(\n      () => S.Array(S.Number).pipe(S.maxItems(-1)),\n      new Error(`Invalid Argument\ndetails: Expected an integer greater than or equal to 1, actual -1`)\n    )\n  })\n\n  describe(\"decoding\", () => {\n    it(\"Array\", async () => {\n      const schema = S.Array(S.Number).pipe(S.maxItems(2))\n\n      await Util.assertions.decoding.succeed(schema, [])\n      await Util.assertions.decoding.succeed(schema, [1])\n      await Util.assertions.decoding.succeed(schema, [1, 2])\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, 2, 3],\n        `maxItems(2)\n└─ Predicate refinement failure\n   └─ Expected an array of at most 2 item(s), actual [1,2,3]`\n      )\n    })\n\n    it(\"NonEmptyArray\", async () => {\n      const schema = S.NonEmptyArray(S.Number).pipe(S.maxItems(2))\n\n      await Util.assertions.decoding.succeed(schema, [1])\n      await Util.assertions.decoding.succeed(schema, [1, 2])\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        `maxItems(2)\n└─ From side refinement failure\n   └─ readonly [number, ...number[]]\n      └─ [0]\n         └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, 2, 3],\n        `maxItems(2)\n└─ Predicate refinement failure\n   └─ Expected an array of at most 2 item(s), actual [1,2,3]`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Array/minItems.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { throws } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"minItems\", () => {\n  it(\"should throw for invalid argument\", () => {\n    throws(\n      () => S.Array(S.Number).pipe(S.minItems(-1)),\n      new Error(`Invalid Argument\ndetails: Expected an integer greater than or equal to 1, actual -1`)\n    )\n  })\n\n  describe(\"decoding\", () => {\n    it(\"Array\", async () => {\n      const schema = S.Array(S.Number).pipe(S.minItems(2))\n\n      await Util.assertions.decoding.succeed(schema, [1, 2])\n      await Util.assertions.decoding.succeed(schema, [1, 2, 3])\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        `minItems(2)\n└─ Predicate refinement failure\n   └─ Expected an array of at least 2 item(s), actual []`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1],\n        `minItems(2)\n└─ Predicate refinement failure\n   └─ Expected an array of at least 2 item(s), actual [1]`\n      )\n    })\n\n    it(\"NonEmptyArray\", async () => {\n      const schema = S.NonEmptyArray(S.Number).pipe(S.minItems(2))\n\n      await Util.assertions.decoding.succeed(schema, [1, 2])\n      await Util.assertions.decoding.succeed(schema, [1, 2, 3])\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        `minItems(2)\n└─ From side refinement failure\n   └─ readonly [number, ...number[]]\n      └─ [0]\n         └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1],\n        `minItems(2)\n└─ Predicate refinement failure\n   └─ Expected an array of at least 2 item(s), actual [1]`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ArrayEnsure.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"ArrayEnsure\", () => {\n  it(\"decode non-array\", async () => {\n    const schema = S.ArrayEnsure(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, \"123\", [123])\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(NumberFromString | ReadonlyArray<NumberFromString> <-> ReadonlyArray<number>)\n└─ Encoded side transformation failure\n   └─ NumberFromString | ReadonlyArray<NumberFromString>\n      ├─ NumberFromString\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual null\n      └─ Expected ReadonlyArray<NumberFromString>, actual null`\n    )\n  })\n\n  it(\"decode empty array\", async () => {\n    const schema = S.ArrayEnsure(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, [], [])\n  })\n\n  it(\"decode array\", async () => {\n    const schema = S.ArrayEnsure(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, [\"123\"], [123])\n    await Util.assertions.decoding.fail(\n      schema,\n      [null],\n      `(NumberFromString | ReadonlyArray<NumberFromString> <-> ReadonlyArray<number>)\n└─ Encoded side transformation failure\n   └─ NumberFromString | ReadonlyArray<NumberFromString>\n      ├─ NumberFromString\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual [null]\n      └─ ReadonlyArray<NumberFromString>\n         └─ [0]\n            └─ NumberFromString\n               └─ Encoded side transformation failure\n                  └─ Expected string, actual null`\n    )\n  })\n\n  it(\"encode\", async () => {\n    const schema = S.ArrayEnsure(S.NumberFromString)\n    await Util.assertions.encoding.succeed(schema, [], [])\n    await Util.assertions.encoding.succeed(schema, [123], \"123\")\n    await Util.assertions.encoding.succeed(schema, [1, 2, 3], [\"1\", \"2\", \"3\"])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ArrayFormatterIssue/ArrayFormatterIssue.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"ArrayFormatterIssue\", () => {\n  const schema = S.ArrayFormatterIssue\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/BigDecimal.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"BigDecimal\", () => {\n  const schema = S.BigDecimal\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"2\",\n      BigDecimal.normalize(BigDecimal.make(2n, 0))\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"0.123\",\n      BigDecimal.normalize(BigDecimal.make(123n, 3))\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"\",\n      BigDecimal.normalize(BigDecimal.make(0n, 0))\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"abc\",\n      `BigDecimal\n└─ Transformation process failure\n   └─ Unable to decode \"abc\" into a BigDecimal`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      BigDecimal.make(2n, 0),\n      \"2\"\n    )\n    await Util.assertions.encoding.succeed(\n      schema,\n      BigDecimal.make(123n, 3),\n      \"0.123\"\n    )\n    await Util.assertions.encoding.succeed(\n      schema,\n      BigDecimal.make(0n, 0),\n      \"0\"\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/BigDecimalFromNumber.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"BigDecimalFromNumber\", () => {\n  const schema = S.BigDecimalFromNumber\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      2,\n      BigDecimal.make(2n, 0)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      0.123,\n      BigDecimal.make(123n, 3)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      0,\n      BigDecimal.make(0n, 0)\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"abc\",\n      `BigDecimalFromNumber\n└─ Encoded side transformation failure\n   └─ Expected number, actual \"abc\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      BigDecimal.make(2n, 0),\n      2\n    )\n    await Util.assertions.encoding.succeed(\n      schema,\n      BigDecimal.make(123n, 3),\n      0.123\n    )\n    await Util.assertions.encoding.succeed(\n      schema,\n      BigDecimal.make(0n, 0),\n      0\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/BigDecimalFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"BigDecimalFromSelf\", () => {\n  const schema = S.BigDecimalFromSelf\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, BigDecimal.make(0n, 0), BigDecimal.make(0n, 0))\n    await Util.assertions.decoding.succeed(schema, BigDecimal.make(123n, 5), BigDecimal.make(123n, 5))\n    await Util.assertions.decoding.succeed(\n      schema,\n      BigDecimal.make(-20000000n, 0),\n      BigDecimal.make(-20000000n, 0)\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, BigDecimal.make(0n, 0), BigDecimal.make(0n, 0))\n    await Util.assertions.encoding.succeed(schema, BigDecimal.make(123n, 5), BigDecimal.make(123n, 5))\n    await Util.assertions.encoding.succeed(\n      schema,\n      BigDecimal.make(-20000000n, 0),\n      BigDecimal.make(-20000000n, 0)\n    )\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.BigDecimalFromSelf\n\n    Util.assertions.pretty(schema, BigDecimal.fromNumber(123), \"BigDecimal(123)\")\n    Util.assertions.pretty(schema, BigDecimal.unsafeFromString(\"123.100\"), \"BigDecimal(123.1)\")\n    Util.assertions.pretty(schema, BigDecimal.unsafeFromString(\"\"), \"BigDecimal(0)\")\n  })\n\n  it(\"equivalence\", () => {\n    const schema = S.BigDecimalFromSelf\n    const equivalence = S.equivalence(schema)\n\n    assertTrue(equivalence(BigDecimal.fromNumber(1), BigDecimal.unsafeFromString(\"1\")))\n    assertFalse(equivalence(BigDecimal.fromNumber(2), BigDecimal.unsafeFromString(\"1\")))\n    assertFalse(equivalence(BigDecimal.fromNumber(1), BigDecimal.unsafeFromString(\"2\")))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/NegativeBigDecimalFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NegativeBigDecimalFromSelf\", () => {\n  const schema = S.NegativeBigDecimalFromSelf\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      BigDecimal.make(0n, 0),\n      `NegativeBigDecimalFromSelf\n└─ Predicate refinement failure\n   └─ Expected a negative BigDecimal, actual BigDecimal(0)`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      BigDecimal.make(2n, 0),\n      `NegativeBigDecimalFromSelf\n└─ Predicate refinement failure\n   └─ Expected a negative BigDecimal, actual BigDecimal(2)`\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      BigDecimal.make(-2n, 0),\n      BigDecimal.make(-2n, 0)\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, BigDecimal.make(-1n, 0), BigDecimal.make(-1n, 0))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/NonNegativeBigDecimalFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NonNegativeBigDecimalFromSelf\", () => {\n  const schema = S.NonNegativeBigDecimalFromSelf\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      BigDecimal.make(0n, 0),\n      BigDecimal.make(0n, 0)\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      BigDecimal.make(-2n, 0),\n      `NonNegativeBigDecimalFromSelf\n└─ Predicate refinement failure\n   └─ Expected a non-negative BigDecimal, actual BigDecimal(-2)`\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      BigDecimal.make(2n, 0),\n      BigDecimal.make(2n, 0)\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, BigDecimal.make(1n, 0), BigDecimal.make(1n, 0))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/NonPositiveBigDecimalFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NonPositiveBigDecimalFromSelf\", () => {\n  const schema = S.NonPositiveBigDecimalFromSelf\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      BigDecimal.make(0n, 0),\n      BigDecimal.make(0n, 0)\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      BigDecimal.make(2n, 0),\n      `NonPositiveBigDecimalFromSelf\n└─ Predicate refinement failure\n   └─ Expected a non-positive BigDecimal, actual BigDecimal(2)`\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      BigDecimal.make(-2n, 0),\n      BigDecimal.make(-2n, 0)\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, BigDecimal.make(-1n, 0), BigDecimal.make(-1n, 0))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/PositiveBigDecimalFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"PositiveBigDecimalFromSelf\", () => {\n  const schema = S.PositiveBigDecimalFromSelf\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      BigDecimal.make(0n, 0),\n      `PositiveBigDecimalFromSelf\n└─ Predicate refinement failure\n   └─ Expected a positive BigDecimal, actual BigDecimal(0)`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      BigDecimal.make(-2n, 0),\n      `PositiveBigDecimalFromSelf\n└─ Predicate refinement failure\n   └─ Expected a positive BigDecimal, actual BigDecimal(-2)`\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      BigDecimal.make(2n, 0),\n      BigDecimal.make(2n, 0)\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, BigDecimal.make(1n, 0), BigDecimal.make(1n, 0))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/betweenBigDecimal.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\nconst max = BigDecimal.make(1n, 0)\nconst min = BigDecimal.make(-1n, 0)\n\ndescribe(\"betweenBigDecimal\", () => {\n  const schema = S.BigDecimal.pipe(S.betweenBigDecimal(min, max))\n\n  it(\"make\", () => {\n    Util.assertions.make.succeed(schema, BigDecimal.make(0n, 0))\n    Util.assertions.make.fail(\n      schema,\n      BigDecimal.make(-2n, 0),\n      `betweenBigDecimal(-1, 1)\n└─ Predicate refinement failure\n   └─ Expected a BigDecimal between -1 and 1, actual BigDecimal(-2)`\n    )\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      \"2\",\n      `betweenBigDecimal(-1, 1)\n└─ Predicate refinement failure\n   └─ Expected a BigDecimal between -1 and 1, actual BigDecimal(2)`\n    )\n    await Util.assertions.decoding.succeed(schema, \"0\", BigDecimal.normalize(BigDecimal.make(0n, 0)))\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"0.2\",\n      BigDecimal.normalize(BigDecimal.make(2n, 1))\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, BigDecimal.make(0n, 0), \"0\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/clampBigDecimal.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"clampBigDecimal\", () => {\n  it(\"decoding\", async () => {\n    const min = BigDecimal.make(-1n, 0)\n    const max = BigDecimal.make(1n, 0)\n    const schema = S.BigDecimalFromSelf.pipe(S.clampBigDecimal(min, max)) // [-1, 1]\n\n    await Util.assertions.decoding.succeed(schema, BigDecimal.make(3n, 0), BigDecimal.normalize(BigDecimal.make(1n, 0)))\n    await Util.assertions.decoding.succeed(schema, BigDecimal.make(0n, 0), BigDecimal.make(0n, 0))\n    await Util.assertions.decoding.succeed(\n      schema,\n      BigDecimal.make(-3n, 0),\n      BigDecimal.normalize(BigDecimal.make(-1n, 0))\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/greaterThanBigDecimal.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"greaterThanBigDecimal\", () => {\n  const min = BigDecimal.fromNumber(10)\n  const schema = S.BigDecimal.pipe(S.greaterThanBigDecimal(min))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      \"0\",\n      `greaterThanBigDecimal(10)\n└─ Predicate refinement failure\n   └─ Expected a BigDecimal greater than 10, actual BigDecimal(0)`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"10\",\n      `greaterThanBigDecimal(10)\n└─ Predicate refinement failure\n   └─ Expected a BigDecimal greater than 10, actual BigDecimal(10)`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, BigDecimal.fromNumber(11), \"11\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/greaterThanOrEqualToBigDecimal.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"greaterThanOrEqualToBigDecimal\", () => {\n  const min = BigDecimal.fromNumber(10)\n  const schema = S.BigDecimal.pipe(S.greaterThanOrEqualToBigDecimal(min))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      \"0\",\n      `greaterThanOrEqualToBigDecimal(10)\n└─ Predicate refinement failure\n   └─ Expected a BigDecimal greater than or equal to 10, actual BigDecimal(0)`\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"10\",\n      BigDecimal.normalize(BigDecimal.fromNumber(10))\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, BigDecimal.fromNumber(11), \"11\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/lessThanBigDecimal.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"lessThanBigDecimal\", () => {\n  const max = BigDecimal.fromNumber(5)\n  const schema = S.BigDecimal.pipe(S.lessThanBigDecimal(max))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      \"5\",\n      `lessThanBigDecimal(5)\n└─ Predicate refinement failure\n   └─ Expected a BigDecimal less than 5, actual BigDecimal(5)`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"6\",\n      `lessThanBigDecimal(5)\n└─ Predicate refinement failure\n   └─ Expected a BigDecimal less than 5, actual BigDecimal(6)`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, BigDecimal.fromNumber(4.5), \"4.5\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigDecimal/lessThanOrEqualToBigDecimal.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { BigDecimal } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"lessThanOrEqualToBigDecimal\", () => {\n  const max = BigDecimal.unsafeFromNumber(5)\n  const schema = S.BigDecimal.pipe(S.lessThanOrEqualToBigDecimal(max))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"5\",\n      BigDecimal.normalize(BigDecimal.unsafeFromNumber(5))\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"6\",\n      `lessThanOrEqualToBigDecimal(5)\n└─ Predicate refinement failure\n   └─ Expected a BigDecimal less than or equal to 5, actual BigDecimal(6)`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, BigDecimal.fromNumber(4.5), \"4.5\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/BigInt.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"BigInt\", () => {\n  const schema = S.BigInt\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, \"0\", 0n)\n    await Util.assertions.decoding.succeed(schema, \"-0\", -0n)\n    await Util.assertions.decoding.succeed(schema, \"1\", 1n)\n\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `BigInt\n└─ Transformation process failure\n   └─ Unable to decode \"\" into a bigint`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \" \",\n      `BigInt\n└─ Transformation process failure\n   └─ Unable to decode \" \" into a bigint`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"1.2\",\n      `BigInt\n└─ Transformation process failure\n   └─ Unable to decode \"1.2\" into a bigint`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"1AB\",\n      `BigInt\n└─ Transformation process failure\n   └─ Unable to decode \"1AB\" into a bigint`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"AB1\",\n      `BigInt\n└─ Transformation process failure\n   └─ Unable to decode \"AB1\" into a bigint`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a\",\n      `BigInt\n└─ Transformation process failure\n   └─ Unable to decode \"a\" into a bigint`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a1\",\n      `BigInt\n└─ Transformation process failure\n   └─ Unable to decode \"a1\" into a bigint`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1n, \"1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/BigIntFromNumber.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"BigIntFromNumber\", () => {\n  const schema = S.BigIntFromNumber\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0, 0n)\n    await Util.assertions.decoding.succeed(schema, -0, -0n)\n    await Util.assertions.decoding.succeed(schema, 1, 1n)\n\n    await Util.assertions.decoding.fail(\n      schema,\n      1.2,\n      `BigIntFromNumber\n└─ Transformation process failure\n   └─ Unable to decode 1.2 into a bigint`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      NaN,\n      `BigIntFromNumber\n└─ Transformation process failure\n   └─ Unable to decode NaN into a bigint`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      Infinity,\n      `BigIntFromNumber\n└─ Transformation process failure\n   └─ Unable to decode Infinity into a bigint`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      -Infinity,\n      `BigIntFromNumber\n└─ Transformation process failure\n   └─ Unable to decode -Infinity into a bigint`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1n, 1)\n\n    await Util.assertions.encoding.fail(\n      schema,\n      BigInt(Number.MAX_SAFE_INTEGER) + 1n,\n      `BigIntFromNumber\n└─ Type side transformation failure\n   └─ betweenBigInt(-9007199254740991, 9007199254740991)\n      └─ Predicate refinement failure\n         └─ Expected a bigint between -9007199254740991n and 9007199254740991n, actual 9007199254740992n`\n    )\n    await Util.assertions.encoding.fail(\n      schema,\n      BigInt(Number.MIN_SAFE_INTEGER) - 1n,\n      `BigIntFromNumber\n└─ Type side transformation failure\n   └─ betweenBigInt(-9007199254740991, 9007199254740991)\n      └─ Predicate refinement failure\n         └─ Expected a bigint between -9007199254740991n and 9007199254740991n, actual -9007199254740992n`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/BigIntFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"BigIntFromSelf\", () => {\n  const schema = S.BigIntFromSelf\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0n, 0n)\n    await Util.assertions.decoding.succeed(schema, 1n, 1n)\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected bigint, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      1.2,\n      `Expected bigint, actual 1.2`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1n, 1n)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/NegativeBigIntFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NegativeBigIntFromSelf\", () => {\n  const schema = S.NegativeBigIntFromSelf\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      0n,\n      `NegativeBigintFromSelf\n└─ Predicate refinement failure\n   └─ Expected a negative bigint, actual 0n`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      1n,\n      `NegativeBigintFromSelf\n└─ Predicate refinement failure\n   └─ Expected a negative bigint, actual 1n`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, -1n, -1n)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/NonNegativeBigIntFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NonNegativeBigIntFromSelf\", () => {\n  const schema = S.NonNegativeBigIntFromSelf\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0n)\n    await Util.assertions.decoding.succeed(schema, 1n)\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.fail(\n      schema,\n      -1n,\n      `NonNegativeBigintFromSelf\n└─ Predicate refinement failure\n   └─ Expected a non-negative bigint, actual -1n`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/NonPositiveBigIntFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NonPositiveBigIntFromSelf\", () => {\n  const schema = S.NonPositiveBigIntFromSelf\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0n)\n    await Util.assertions.decoding.fail(\n      schema,\n      1n,\n      `NonPositiveBigintFromSelf\n└─ Predicate refinement failure\n   └─ Expected a non-positive bigint, actual 1n`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, -1n, -1n)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/PositiveBigIntFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"PositiveBigIntFromSelf\", () => {\n  const schema = S.PositiveBigIntFromSelf\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      -1n,\n      `PositiveBigintFromSelf\n└─ Predicate refinement failure\n   └─ Expected a positive bigint, actual -1n`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      0n,\n      `PositiveBigintFromSelf\n└─ Predicate refinement failure\n   └─ Expected a positive bigint, actual 0n`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1n, 1n)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/betweenBigInt.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"betweenBigInt\", () => {\n  const schema = S.BigIntFromSelf.pipe(S.betweenBigInt(-1n, 1n)).annotations({\n    title: \"[-1n, 1n] interval\"\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0n, 0n)\n    await Util.assertions.decoding.fail(\n      schema,\n      -2n,\n      `[-1n, 1n] interval\n└─ Predicate refinement failure\n   └─ Expected a bigint between -1n and 1n, actual -2n`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      2n,\n      `[-1n, 1n] interval\n└─ Predicate refinement failure\n   └─ Expected a bigint between -1n and 1n, actual 2n`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1n, 1n)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/clampBigInt.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"clampBigInt\", () => {\n  it(\"decoding\", async () => {\n    const schema = S.BigIntFromSelf.pipe(S.clampBigInt(-1n, 1n))\n\n    await Util.assertions.decoding.succeed(schema, 3n, 1n)\n    await Util.assertions.decoding.succeed(schema, 0n, 0n)\n    await Util.assertions.decoding.succeed(schema, -3n, -1n)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/greaterThanBigInt.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"greaterThanBigInt\", () => {\n  const schema = S.BigIntFromSelf.pipe(S.greaterThanBigInt(0n))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      -1n,\n      `greaterThanBigInt(0)\n└─ Predicate refinement failure\n   └─ Expected a positive bigint, actual -1n`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      0n,\n      `greaterThanBigInt(0)\n└─ Predicate refinement failure\n   └─ Expected a positive bigint, actual 0n`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1n, 1n)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/greaterThanOrEqualToBigInt.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"greaterThanOrEqualToBigInt\", () => {\n  const schema = S.BigIntFromSelf.pipe(S.greaterThanOrEqualToBigInt(0n))\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      -1n,\n      `greaterThanOrEqualToBigInt(0)\n└─ Predicate refinement failure\n   └─ Expected a non-negative bigint, actual -1n`\n    )\n    await Util.assertions.decoding.succeed(schema, 0n, 0n)\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1n, 1n)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/lessThanBigInt.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"lessThanBigInt\", () => {\n  const schema = S.BigIntFromSelf.pipe(S.lessThanBigInt(0n))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      0n,\n      `lessThanBigInt(0)\n└─ Predicate refinement failure\n   └─ Expected a negative bigint, actual 0n`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      1n,\n      `lessThanBigInt(0)\n└─ Predicate refinement failure\n   └─ Expected a negative bigint, actual 1n`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, -1n, -1n)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/BigInt/lessThanOrEqualToBigInt.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"lessThanOrEqualToBigInt\", () => {\n  const schema = S.BigIntFromSelf.pipe(S.lessThanOrEqualToBigInt(0n))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0n, 0n)\n    await Util.assertions.decoding.fail(\n      schema,\n      1n,\n      `lessThanOrEqualToBigInt(0)\n└─ Predicate refinement failure\n   └─ Expected a non-positive bigint, actual 1n`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, -1n, -1n)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Boolean/Boolean.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Boolean\", () => {\n  const schema = S.Boolean\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, true, true)\n    await Util.assertions.decoding.succeed(schema, false, false)\n    await Util.assertions.decoding.fail(schema, 1, `Expected boolean, actual 1`)\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, true, true)\n    await Util.assertions.encoding.succeed(schema, false, false)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Boolean/BooleanFromString.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"BooleanFromString\", () => {\n  const schema = S.BooleanFromString\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, \"true\", true)\n    await Util.assertions.decoding.succeed(schema, \"false\", false)\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a\",\n      `BooleanFromString\n└─ Encoded side transformation failure\n   └─ a string to be decoded into a boolean\n      ├─ Expected \"true\", actual \"a\"\n      └─ Expected \"false\", actual \"a\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, true, \"true\")\n    await Util.assertions.encoding.succeed(schema, false, \"false\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Boolean/BooleanFromUnknown.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"BooleanFromUnknown\", () => {\n  const schema = S.BooleanFromUnknown\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, true, true)\n    await Util.assertions.decoding.succeed(schema, 1, true)\n    await Util.assertions.decoding.succeed(schema, 1n, true)\n    await Util.assertions.decoding.succeed(schema, \"a\", true)\n\n    await Util.assertions.decoding.succeed(schema, false, false)\n    await Util.assertions.decoding.succeed(schema, 0, false)\n    await Util.assertions.decoding.succeed(schema, 0n, false)\n    await Util.assertions.decoding.succeed(schema, null, false)\n    await Util.assertions.decoding.succeed(schema, \"\", false)\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, true, true)\n    await Util.assertions.encoding.succeed(schema, false, false)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Boolean/Not.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Not\", () => {\n  const schema = S.Not\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, true, false)\n    await Util.assertions.decoding.succeed(schema, false, true)\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, true, false)\n    await Util.assertions.encoding.succeed(schema, false, true)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Cause/Cause.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Cause, FiberId } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Cause\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Cause({ error: S.NumberFromString, defect: S.Defect }))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Cause({ error: S.NumberFromString, defect: S.Defect })\n    await Util.assertions.decoding.succeed(\n      schema,\n      { _tag: \"Fail\", error: \"1\" },\n      Cause.fail(1)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      { _tag: \"Empty\" },\n      Cause.empty\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      {\n        _tag: \"Parallel\",\n        left: { _tag: \"Fail\", error: \"1\" },\n        right: { _tag: \"Empty\" }\n      },\n      Cause.parallel(Cause.fail(1), Cause.empty)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      {\n        _tag: \"Sequential\",\n        left: { _tag: \"Fail\", error: \"1\" },\n        right: { _tag: \"Empty\" }\n      },\n      Cause.sequential(Cause.fail(1), Cause.empty)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      {\n        _tag: \"Die\",\n        defect: { stack: \"fail\", message: \"error\" }\n      },\n      Cause.die(new Error(\"error\", { cause: { stack: \"fail\", message: \"error\" } }))\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      {\n        _tag: \"Interrupt\",\n        fiberId: {\n          _tag: \"Composite\",\n          left: {\n            _tag: \"Runtime\",\n            id: 1,\n            startTimeMillis: 1000\n          },\n          right: {\n            _tag: \"None\"\n          }\n        }\n      },\n      Cause.interrupt(FiberId.composite(FiberId.runtime(1, 1000), FiberId.none))\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(CauseEncoded<NumberFromString> <-> Cause<number>)\n└─ Encoded side transformation failure\n   └─ Expected CauseEncoded<NumberFromString>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      {},\n      `(CauseEncoded<NumberFromString> <-> Cause<number>)\n└─ Encoded side transformation failure\n   └─ CauseEncoded<NumberFromString>\n      └─ { readonly _tag: \"Empty\" | \"Fail\" | \"Die\" | \"Interrupt\" | \"Sequential\" | \"Parallel\" }\n         └─ [\"_tag\"]\n            └─ is missing`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { _tag: \"Parallel\", left: { _tag: \"Fail\" }, right: { _tag: \"Interrupt\" } },\n      `(CauseEncoded<NumberFromString> <-> Cause<number>)\n└─ Encoded side transformation failure\n   └─ CauseEncoded<NumberFromString>\n      └─ { readonly _tag: \"Parallel\"; readonly left: CauseEncoded<NumberFromString>; readonly right: CauseEncoded<NumberFromString> }\n         └─ [\"left\"]\n            └─ CauseEncoded<NumberFromString>\n               └─ { readonly _tag: \"Fail\"; readonly error: NumberFromString }\n                  └─ [\"error\"]\n                     └─ is missing`\n    )\n  })\n\n  describe(\"encoding\", () => {\n    it(\"handles array-based defects without throwing\", async () => {\n      const schema = S.Cause({ error: S.String, defect: S.Defect })\n      await Util.assertions.encoding.succeed(schema, Cause.die([{ toString: \"\" }]), {\n        _tag: \"Die\",\n        defect: \"[{\\\"toString\\\":\\\"\\\"}]\"\n      })\n    })\n\n    it(\"should raise an error when a non-encodable Cause is passed\", async () => {\n      const schema = S.Cause({ error: S.String, defect: Util.Defect })\n      await Util.assertions.encoding.fail(\n        schema,\n        Cause.die(null),\n        `(CauseEncoded<string> <-> Cause<string>)\n└─ Type side transformation failure\n   └─ Cause<string>\n      └─ CauseEncoded<string>\n         └─ { readonly _tag: \"Die\"; readonly defect: object }\n            └─ [\"defect\"]\n               └─ Expected object, actual null`\n      )\n    })\n\n    it(\"using the built-in Defect schema as defect argument\", async () => {\n      const schema = S.Cause({ error: S.NumberFromString, defect: S.Defect })\n      const schemaUnknown = S.Cause({ error: S.NumberFromString, defect: S.Unknown })\n\n      await Util.assertions.encoding.succeed(schema, Cause.fail(1), { _tag: \"Fail\", error: \"1\" })\n      await Util.assertions.encoding.succeed(schema, Cause.empty, { _tag: \"Empty\" })\n      await Util.assertions.encoding.succeed(schema, Cause.parallel(Cause.fail(1), Cause.empty), {\n        _tag: \"Parallel\",\n        left: { _tag: \"Fail\", error: \"1\" },\n        right: { _tag: \"Empty\" }\n      })\n      await Util.assertions.encoding.succeed(schema, Cause.sequential(Cause.fail(1), Cause.empty), {\n        _tag: \"Sequential\",\n        left: { _tag: \"Fail\", error: \"1\" },\n        right: { _tag: \"Empty\" }\n      })\n      await Util.assertions.encoding.succeed(schema, Cause.die(\"fail\"), {\n        _tag: \"Die\",\n        defect: \"fail\"\n      })\n      await Util.assertions.encoding.succeed(\n        schema,\n        Cause.interrupt(FiberId.composite(FiberId.runtime(1, 1000), FiberId.none)),\n        {\n          _tag: \"Interrupt\",\n          fiberId: {\n            _tag: \"Composite\",\n            left: {\n              _tag: \"Runtime\",\n              id: 1,\n              startTimeMillis: 1000\n            },\n            right: {\n              _tag: \"None\"\n            }\n          }\n        }\n      )\n\n      let failWithStack = S.encodeSync(schema)(Cause.die(new Error(\"fail\")))\n      assertTrue(failWithStack._tag === \"Die\")\n      deepStrictEqual(failWithStack.defect, {\n        name: \"Error\",\n        message: \"fail\"\n      })\n\n      failWithStack = S.encodeSync(schemaUnknown)(Cause.die(new Error(\"fail\")))\n      assertTrue(failWithStack._tag === \"Die\")\n      strictEqual((failWithStack.defect as Error).message, \"fail\")\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Cause/CauseFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Cause from \"effect/Cause\"\nimport * as FiberId from \"effect/FiberId\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"CauseFromSelf\", () => {\n  it(\"arbitrary\", () => {\n    Util.assertions.arbitrary.validateGeneratedValues(S.CauseFromSelf({ error: S.NumberFromString, defect: S.Unknown }))\n  })\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.CauseFromSelf({ error: S.NumberFromString, defect: S.Unknown }))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.CauseFromSelf({ error: S.NumberFromString, defect: S.Unknown })\n\n    await Util.assertions.decoding.succeed(schema, Cause.fail(\"1\"), Cause.fail(1))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected Cause<NumberFromString>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      Cause.fail(\"a\"),\n      `Cause<NumberFromString>\n└─ CauseEncoded<NumberFromString>\n   └─ { readonly _tag: \"Fail\"; readonly error: NumberFromString }\n      └─ [\"error\"]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      Cause.parallel(Cause.die(\"error\"), Cause.fail(\"a\")),\n      `Cause<NumberFromString>\n└─ CauseEncoded<NumberFromString>\n   └─ { readonly _tag: \"Parallel\"; readonly left: CauseEncoded<NumberFromString>; readonly right: CauseEncoded<NumberFromString> }\n      └─ [\"right\"]\n         └─ CauseEncoded<NumberFromString>\n            └─ { readonly _tag: \"Fail\"; readonly error: NumberFromString }\n               └─ [\"error\"]\n                  └─ NumberFromString\n                     └─ Transformation process failure\n                        └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.CauseFromSelf({ error: S.NumberFromString, defect: S.Unknown })\n\n    await Util.assertions.encoding.succeed(schema, Cause.fail(1), Cause.fail(\"1\"))\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.CauseFromSelf({ error: S.String, defect: S.Unknown })\n    Util.assertions.pretty(schema, Cause.die(\"error\"), `Cause.die(Error: error)`)\n    Util.assertions.pretty(schema, Cause.empty, `Cause.empty`)\n    Util.assertions.pretty(schema, Cause.fail(\"error\"), `Cause.fail(\"error\")`)\n    Util.assertions.pretty(\n      schema,\n      Cause.interrupt(FiberId.composite(FiberId.none, FiberId.none)),\n      `Cause.interrupt(FiberId.composite(FiberId.none, FiberId.none))`\n    )\n    Util.assertions.pretty(\n      schema,\n      Cause.parallel(Cause.die(\"error\"), Cause.fail(\"error\")),\n      `Cause.parallel(Cause.die(Error: error), Cause.fail(\"error\"))`\n    )\n    Util.assertions.pretty(\n      schema,\n      Cause.sequential(Cause.die(\"error\"), Cause.fail(\"error\")),\n      `Cause.sequential(Cause.die(Error: error), Cause.fail(\"error\"))`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Chunk/Chunk.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as C from \"effect/Chunk\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Chunk\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Chunk(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Chunk(S.Number)\n    await Util.assertions.decoding.succeed(schema, [], C.empty())\n    await Util.assertions.decoding.succeed(schema, [1, 2, 3], C.fromIterable([1, 2, 3]))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(ReadonlyArray<number> <-> Chunk<number>)\n└─ Encoded side transformation failure\n   └─ Expected ReadonlyArray<number>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      [1, \"a\"],\n      `(ReadonlyArray<number> <-> Chunk<number>)\n└─ Encoded side transformation failure\n   └─ ReadonlyArray<number>\n      └─ [1]\n         └─ Expected number, actual \"a\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.Chunk(S.Number)\n    await Util.assertions.encoding.succeed(schema, C.empty(), [])\n    await Util.assertions.encoding.succeed(schema, C.fromIterable([1, 2, 3]), [1, 2, 3])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Chunk/ChunkFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as C from \"effect/Chunk\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"ChunkFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.ChunkFromSelf(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.ChunkFromSelf(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, C.empty(), C.empty())\n    await Util.assertions.decoding.succeed(\n      schema,\n      C.fromIterable([\"1\", \"2\", \"3\"]),\n      C.fromIterable([1, 2, 3])\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected Chunk<NumberFromString>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      C.fromIterable([\"1\", \"a\", \"3\"]),\n      `Chunk<NumberFromString>\n└─ ReadonlyArray<NumberFromString>\n   └─ [1]\n      └─ NumberFromString\n         └─ Transformation process failure\n            └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.ChunkFromSelf(S.NumberFromString)\n    await Util.assertions.encoding.succeed(schema, C.empty(), C.empty())\n    await Util.assertions.encoding.succeed(\n      schema,\n      C.fromIterable([1, 2, 3]),\n      C.fromIterable([\"1\", \"2\", \"3\"])\n    )\n  })\n\n  it(\"is\", () => {\n    const schema = S.ChunkFromSelf(S.String)\n    const is = P.is(schema)\n    assertTrue(is(C.empty()))\n    assertTrue(is(C.fromIterable([\"a\", \"b\", \"c\"])))\n\n    assertFalse(is(C.fromIterable([\"a\", \"b\", 1])))\n    assertFalse(is({ _id: Symbol.for(\"effect/Schema/test/FakeChunk\") }))\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.ChunkFromSelf(S.String)\n    Util.assertions.pretty(schema, C.empty(), \"Chunk()\")\n    Util.assertions.pretty(schema, C.fromIterable([\"a\", \"b\"]), `Chunk(\"a\", \"b\")`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Chunk/NonEmptyChunk.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as C from \"effect/Chunk\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NonEmptyChunk\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.NonEmptyChunk(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.NonEmptyChunk(S.Number)\n    await Util.assertions.decoding.succeed(schema, [1, 2, 3], C.make(1, 2, 3))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(readonly [number, ...number[]] <-> NonEmptyChunk<number>)\n└─ Encoded side transformation failure\n   └─ Expected readonly [number, ...number[]], actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      [1, \"a\"],\n      `(readonly [number, ...number[]] <-> NonEmptyChunk<number>)\n└─ Encoded side transformation failure\n   └─ readonly [number, ...number[]]\n      └─ [1]\n         └─ Expected number, actual \"a\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.NonEmptyChunk(S.Number)\n    await Util.assertions.encoding.succeed(schema, C.make(1, 2, 3), [1, 2, 3])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Chunk/NonEmptyChunkFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as Arbitrary from \"effect/Arbitrary\"\nimport * as C from \"effect/Chunk\"\nimport * as FastCheck from \"effect/FastCheck\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NonEmptyChunkFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.NonEmptyChunkFromSelf(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.NonEmptyChunkFromSelf(S.NumberFromString)\n    await Util.assertions.decoding.succeed(\n      schema,\n      C.make(\"1\", \"2\", \"3\"),\n      C.make(1, 2, 3)\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected NonEmptyChunk<NumberFromString>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      C.empty(),\n      `Expected NonEmptyChunk<NumberFromString>, actual {\n  \"_id\": \"Chunk\",\n  \"values\": []\n}`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      C.make(\"1\", \"a\", \"3\"),\n      `NonEmptyChunk<NumberFromString>\n└─ readonly [NumberFromString, ...NumberFromString[]]\n   └─ [1]\n      └─ NumberFromString\n         └─ Transformation process failure\n            └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.NonEmptyChunkFromSelf(S.NumberFromString)\n    await Util.assertions.encoding.succeed(\n      schema,\n      C.make(1, 2, 3),\n      C.make(\"1\", \"2\", \"3\")\n    )\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.NonEmptyChunkFromSelf(S.String)\n    Util.assertions.pretty(schema, C.make(\"a\", \"b\"), `NonEmptyChunk(\"a\", \"b\")`)\n  })\n\n  it(\"equivalence\", () => {\n    const schema = S.NonEmptyChunkFromSelf(S.String)\n    const equivalence = S.equivalence(schema)\n    assertTrue(equivalence(C.make(\"a\", \"b\"), C.make(\"a\", \"b\")))\n    assertFalse(equivalence(C.make(\"a\", \"b\"), C.make(\"a\", \"c\")))\n    assertFalse(equivalence(C.make(\"a\", \"b\"), C.make(\"a\")))\n  })\n\n  it(\"arbitrary\", () => {\n    const schema = S.NonEmptyChunkFromSelf(S.String)\n    const arb = Arbitrary.make(schema)\n    FastCheck.assert(FastCheck.property(arb, C.isNonEmpty))\n    assertTrue(FastCheck.sample(arb, 10).every(C.isNonEmpty))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Class/Class.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertInstanceOf,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { Context, Data, Effect, Equal, JSONSchema, ParseResult, Schema as S, SchemaAST as AST } from \"effect\"\nimport * as Util from \"../../TestUtils.js\"\n\nclass Person extends S.Class<Person>(\"Person\")({\n  id: S.Number,\n  name: S.String.pipe(S.nonEmptyString())\n}) {\n  get upperName() {\n    return this.name.toUpperCase()\n  }\n}\n\nconst Name = Context.GenericTag<\"Name\", string>(\"Name\")\nconst NameString = S.String.pipe(\n  S.nonEmptyString(),\n  S.transformOrFail(\n    S.String,\n    {\n      strict: true,\n      decode: (_, _opts, ast) =>\n        Name.pipe(\n          Effect.filterOrFail(\n            (name) => _ === name,\n            () => new ParseResult.Type(ast, _, \"Does not match Name\")\n          )\n        ),\n      encode: (_) => ParseResult.succeed(_)\n    }\n  )\n)\n\nclass PersonWithAge extends Person.extend<PersonWithAge>(\"PersonWithAge\")({\n  age: S.Number\n}) {\n  get isAdult() {\n    return this.age >= 18\n  }\n}\n\ndescribe(\"Class\", () => {\n  it(\"suspend before initialization\", async () => {\n    const schema = S.suspend(() => string)\n    class A extends S.Class<A>(\"A\")({ a: S.optional(schema) }) {}\n    const string = S.String\n    await Util.assertions.decoding.succeed(A, new A({ a: \"a\" }))\n  })\n\n  it(\"should be a Schema\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String }) {}\n    assertTrue(S.isSchema(A))\n    strictEqual(String(A), \"(A (Encoded side) <-> A)\")\n    strictEqual(S.format(A), \"(A (Encoded side) <-> A)\")\n  })\n\n  it(\"should expose the fields\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String }) {}\n    deepStrictEqual(A.fields, { a: S.String })\n  })\n\n  it(\"should expose the identifier\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String }) {}\n    strictEqual(A.identifier, \"A\")\n  })\n\n  it(\"should add an identifier annotation\", () => {\n    class A extends S.Class<A>(\"MyName\")({ a: S.String }) {}\n    strictEqual(A.ast.to.annotations[AST.IdentifierAnnotationId], \"MyName\")\n  })\n\n  describe(\"constructor\", () => {\n    it(\"should be a constructor\", () => {\n      class A extends S.Class<A>(\"A\")({ a: S.String }) {}\n      const instance = new A({ a: \"a\" })\n      strictEqual(instance.a, \"a\")\n      assertInstanceOf(instance, A)\n    })\n\n    it(\"should validate the input by default\", () => {\n      class A extends S.Class<A>(\"A\")({ a: S.NonEmptyString }) {}\n      Util.assertions.parseError(\n        () => new A({ a: \"\" }),\n        `A (Constructor)\n└─ [\"a\"]\n   └─ NonEmptyString\n      └─ Predicate refinement failure\n         └─ Expected a non empty string, actual \"\"`\n      )\n      Util.assertions.parseError(\n        () => A.make({ a: \"\" }),\n        `A (Constructor)\n└─ [\"a\"]\n   └─ NonEmptyString\n      └─ Predicate refinement failure\n         └─ Expected a non empty string, actual \"\"`\n      )\n    })\n\n    it(\"validation can be disabled\", () => {\n      class A extends S.Class<A>(\"A\")({ a: S.NonEmptyString }) {}\n      strictEqual(new A({ a: \"\" }, true).a, \"\")\n      strictEqual(new A({ a: \"\" }, { disableValidation: true }).a, \"\")\n\n      strictEqual(A.make({ a: \"\" }, true).a, \"\")\n      strictEqual(A.make({ a: \"\" }, { disableValidation: true }).a, \"\")\n    })\n\n    it(\"should support defaults\", () => {\n      const b = Symbol.for(\"b\")\n      class A extends S.Class<A>(\"A\")({\n        a: S.propertySignature(S.String).pipe(S.withConstructorDefault(() => \"\")),\n        [b]: S.propertySignature(S.Number).pipe(S.withConstructorDefault(() => 1))\n      }) {}\n      deepStrictEqual({ ...new A({ a: \"a\", [b]: 2 }) }, { a: \"a\", [b]: 2 })\n      deepStrictEqual({ ...new A({ a: \"a\" }) }, { a: \"a\", [b]: 1 })\n      deepStrictEqual({ ...new A({ [b]: 2 }) }, { a: \"\", [b]: 2 })\n      deepStrictEqual({ ...new A({}) }, { a: \"\", [b]: 1 })\n\n      deepStrictEqual({ ...A.make({ a: \"a\", [b]: 2 }) }, { a: \"a\", [b]: 2 })\n      deepStrictEqual({ ...A.make({ a: \"a\" }) }, { a: \"a\", [b]: 1 })\n      deepStrictEqual({ ...A.make({ [b]: 2 }) }, { a: \"\", [b]: 2 })\n      deepStrictEqual({ ...A.make({}) }, { a: \"\", [b]: 1 })\n    })\n\n    it(\"should support lazy defaults\", () => {\n      let i = 0\n      class A extends S.Class<A>(\"A\")({\n        a: S.propertySignature(S.Number).pipe(S.withConstructorDefault(() => ++i))\n      }) {}\n      deepStrictEqual({ ...new A({}) }, { a: 1 })\n      deepStrictEqual({ ...new A({}) }, { a: 2 })\n      new A({ a: 10 })\n      deepStrictEqual({ ...new A({}) }, { a: 3 })\n\n      deepStrictEqual({ ...A.make({}) }, { a: 4 })\n      deepStrictEqual({ ...A.make({}) }, { a: 5 })\n      new A({ a: 10 })\n      deepStrictEqual({ ...A.make({}) }, { a: 6 })\n    })\n\n    it(\"should treat `undefined` as missing field\", () => {\n      class A extends S.Class<A>(\"A\")({\n        a: S.propertySignature(S.UndefinedOr(S.String)).pipe(S.withConstructorDefault(() => \"\"))\n      }) {}\n      deepStrictEqual({ ...new A({}) }, { a: \"\" })\n      deepStrictEqual({ ...new A({ a: undefined }) }, { a: \"\" })\n\n      deepStrictEqual({ ...A.make({}) }, { a: \"\" })\n      deepStrictEqual({ ...A.make({ a: undefined }) }, { a: \"\" })\n    })\n\n    it(\"should accept void if the Class has no fields\", () => {\n      class A extends S.Class<A>(\"A\")({}) {}\n      deepStrictEqual({ ...new A() }, {})\n      deepStrictEqual({ ...new A(undefined) }, {})\n      deepStrictEqual({ ...new A(undefined, true) }, {})\n      deepStrictEqual({ ...new A(undefined, false) }, {})\n      deepStrictEqual({ ...new A({}) }, {})\n\n      deepStrictEqual({ ...A.make() }, {})\n      deepStrictEqual({ ...A.make(undefined) }, {})\n      deepStrictEqual({ ...A.make(undefined, true) }, {})\n      deepStrictEqual({ ...A.make(undefined, false) }, {})\n      deepStrictEqual({ ...A.make({}) }, {})\n    })\n\n    it(\"should accept void if the Class has all the fields with a default\", () => {\n      class A extends S.Class<A>(\"A\")({\n        a: S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"\"))\n      }) {}\n      deepStrictEqual({ ...new A() }, { a: \"\" })\n      deepStrictEqual({ ...new A(undefined) }, { a: \"\" })\n      deepStrictEqual({ ...new A(undefined, true) }, { a: \"\" })\n      deepStrictEqual({ ...new A(undefined, false) }, { a: \"\" })\n      deepStrictEqual({ ...new A({}) }, { a: \"\" })\n\n      deepStrictEqual({ ...A.make() }, { a: \"\" })\n      deepStrictEqual({ ...A.make(undefined) }, { a: \"\" })\n      deepStrictEqual({ ...A.make(undefined, true) }, { a: \"\" })\n      deepStrictEqual({ ...A.make(undefined, false) }, { a: \"\" })\n      deepStrictEqual({ ...A.make({}) }, { a: \"\" })\n    })\n  })\n\n  it(\"should support methods\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String }) {\n      method(b: string) {\n        return `method: ${this.a} ${b}`\n      }\n    }\n    strictEqual(new A({ a: \"a\" }).method(\"b\"), \"method: a b\")\n  })\n\n  it(\"should support getters\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String }) {\n      get getter() {\n        return `getter: ${this.a}`\n      }\n    }\n    strictEqual(new A({ a: \"a\" }).getter, \"getter: a\")\n  })\n\n  it(\"using S.annotations() on a Class should return a Schema\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String }) {}\n    const schema = A.pipe(S.annotations({ title: \"X\" }))\n    assertTrue(S.isSchema(schema))\n    strictEqual(schema.ast._tag, \"Transformation\")\n    strictEqual(schema.ast.annotations[AST.TitleAnnotationId], \"X\")\n  })\n\n  it(\"using the .annotations() method of a Class should return a Schema\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String }) {}\n    const schema = A.annotations({ title: \"X\" })\n    assertTrue(S.isSchema(schema))\n    strictEqual(schema.ast._tag, \"Transformation\")\n    strictEqual(schema.ast.annotations[AST.TitleAnnotationId], \"X\")\n  })\n\n  it(\"default toString()\", () => {\n    const b = Symbol.for(\"b\")\n    class A extends S.Class<A>(\"A\")({ a: S.String, [b]: S.Number }) {}\n    strictEqual(String(new A({ a: \"a\", [b]: 1 })), `A({ \"a\": \"a\", Symbol(b): 1 })`)\n  })\n\n  it(\"decoding\", async () => {\n    class A extends S.Class<A>(\"A\")({ a: S.NonEmptyString }) {}\n    await Util.assertions.decoding.succeed(A, { a: \"a\" }, new A({ a: \"a\" }))\n    await Util.assertions.decoding.fail(\n      A,\n      { a: \"\" },\n      `(A (Encoded side) <-> A)\n└─ Encoded side transformation failure\n   └─ A (Encoded side)\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    class A extends S.Class<A>(\"A\")({ a: S.NonEmptyString }) {}\n    await Util.assertions.encoding.succeed(A, new A({ a: \"a\" }), { a: \"a\" })\n    await Util.assertions.encoding.succeed(A, { a: \"a\" }, { a: \"a\" })\n    await Util.assertions.encoding.fail(\n      A,\n      new A({ a: \"\" }, true),\n      `(A (Encoded side) <-> A)\n└─ Encoded side transformation failure\n   └─ A (Encoded side)\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n    )\n  })\n\n  it(\"a custom _tag field should be allowed\", () => {\n    class A extends S.Class<A>(\"A\")({ _tag: S.Literal(\"a\", \"b\") }) {}\n    Util.expectFields(A.fields, {\n      _tag: S.Literal(\"a\", \"b\")\n    })\n  })\n\n  it(\"duplicated fields should not be allowed when extending with extend()\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String }) {}\n    throws(\n      () => {\n        class A2 extends A.extend<A2>(\"A2\")({ a: S.String }) {}\n        // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n        A2\n      },\n      new Error(`Duplicate property signature\ndetails: Duplicate key \"a\"`)\n    )\n  })\n\n  it(\"can be extended with Class fields\", () => {\n    class AB extends S.Class<AB>(\"AB\")({ a: S.String, b: S.Number }) {}\n    class C extends S.Class<C>(\"C\")({\n      ...AB.fields,\n      b: S.String,\n      c: S.Boolean\n    }) {}\n    Util.expectFields(C.fields, {\n      a: S.String,\n      b: S.String,\n      c: S.Boolean\n    })\n    deepStrictEqual({ ...new C({ a: \"a\", b: \"b\", c: true }) }, { a: \"a\", b: \"b\", c: true })\n  })\n\n  it(\"can be extended with TaggedClass fields\", () => {\n    class AB extends S.Class<AB>(\"AB\")({ a: S.String, b: S.Number }) {}\n    class D extends S.TaggedClass<D>()(\"D\", {\n      ...AB.fields,\n      b: S.String,\n      c: S.Boolean\n    }) {}\n    Util.expectFields(D.fields, {\n      _tag: S.getClassTag(\"D\"),\n      a: S.String,\n      b: S.String,\n      c: S.Boolean\n    })\n    deepStrictEqual({ ...new D({ a: \"a\", b: \"b\", c: true }) }, { _tag: \"D\", a: \"a\", b: \"b\", c: true })\n  })\n\n  it(\"S.typeSchema(Class)\", async () => {\n    const PersonFromSelf = S.typeSchema(Person)\n    await Util.assertions.decoding.succeed(PersonFromSelf, new Person({ id: 1, name: \"John\" }))\n    await Util.assertions.decoding.fail(\n      PersonFromSelf,\n      { id: 1, name: \"John\" },\n      `Expected Person, actual {\"id\":1,\"name\":\"John\"}`\n    )\n  })\n\n  it(\"is\", () => {\n    const is = S.is(S.typeSchema(Person))\n    assertTrue(is(new Person({ id: 1, name: \"name\" })))\n    assertFalse(is({ id: 1, name: \"name\" }))\n  })\n\n  it(\"with a field with a context !== never\", async () => {\n    class PersonContext extends S.Class<PersonContext>(\"PersonContext\")({\n      ...Person.fields,\n      name: NameString\n    }) {}\n\n    const person = S.decodeUnknown(PersonContext)({ id: 1, name: \"John\" }).pipe(\n      Effect.provideService(Name, \"John\"),\n      Effect.runSync\n    )\n    strictEqual(person.name, \"John\")\n\n    const PersonFromSelf = S.typeSchema(Person)\n    await Util.assertions.decoding.succeed(PersonFromSelf, new Person({ id: 1, name: \"John\" }))\n    await Util.assertions.decoding.fail(\n      PersonFromSelf,\n      { id: 1, name: \"John\" },\n      `Expected Person, actual {\"id\":1,\"name\":\"John\"}`\n    )\n  })\n\n  it(\"should accept a Struct as argument\", () => {\n    const fields = { a: S.String, b: S.Number }\n    class A extends S.Class<A>(\"A\")(S.Struct(fields)) {}\n    Util.expectFields(A.fields, fields)\n  })\n\n  it(\"should accept a refinement of a Struct as argument\", async () => {\n    const fields = { a: S.Number, b: S.Number }\n    class A extends S.Class<A>(\"A\")(\n      S.Struct(fields).pipe(S.filter(({ a, b }) => a === b ? undefined : \"a should be equal to b\"))\n    ) {}\n    Util.expectFields(A.fields, fields)\n    await Util.assertions.decoding.succeed(A, new A({ a: 1, b: 1 }))\n    await Util.assertions.decoding.fail(\n      A,\n      { a: 1, b: 2 },\n      `(A (Encoded side) <-> A)\n└─ Encoded side transformation failure\n   └─ A (Encoded side)\n      └─ Predicate refinement failure\n         └─ a should be equal to b`\n    )\n    Util.assertions.parseError(\n      () => new A({ a: 1, b: 2 }),\n      `A (Constructor)\n└─ Predicate refinement failure\n   └─ a should be equal to b`\n    )\n  })\n\n  it(\"Data.Class\", () => {\n    const person = new Person({ id: 1, name: \"John\" })\n    const personAge = new PersonWithAge({ id: 1, name: \"John\", age: 30 })\n\n    strictEqual(String(person), `Person({ \"id\": 1, \"name\": \"John\" })`)\n    strictEqual(String(personAge), `PersonWithAge({ \"id\": 1, \"name\": \"John\", \"age\": 30 })`)\n\n    assertInstanceOf(person, Data.Class)\n    assertInstanceOf(personAge, Data.Class)\n\n    const person2 = new Person({ id: 1, name: \"John\" })\n    assertTrue(Equal.equals(person, person2))\n\n    const person3 = new Person({ id: 2, name: \"John\" })\n    assertFalse(Equal.equals(person, person3))\n  })\n\n  it(\"pretty\", () => {\n    const schema = Person\n    Util.assertions.pretty(schema, new Person({ id: 1, name: \"John\" }), `Person({ \"id\": 1, \"name\": \"John\" })`)\n  })\n\n  describe(\"encode\", () => {\n    it(\"struct a class without methods nor getters\", async () => {\n      class A extends S.Class<A>(\"A\")({\n        n: S.NumberFromString\n      }) {}\n      await Util.assertions.encoding.succeed(A, { n: 1 }, { n: \"1\" })\n    })\n\n    it(\"struct a class with a getter\", async () => {\n      class A extends S.Class<A>(\"A\")({\n        n: S.NumberFromString\n      }) {\n        get s() {\n          return \"s\"\n        }\n      }\n      await Util.assertions.encoding.succeed(A, { n: 1 } as any, { n: \"1\" })\n    })\n\n    it(\"struct nested classes\", async () => {\n      class A extends S.Class<A>(\"A\")({\n        n: S.NumberFromString\n      }) {}\n      class B extends S.Class<B>(\"B\")({\n        a: A\n      }) {}\n      await Util.assertions.encoding.succeed(S.Union(B, S.NumberFromString), 1, \"1\")\n      await Util.assertions.encoding.succeed(B, { a: { n: 1 } }, { a: { n: \"1\" } })\n    })\n\n    it(\"class a class with a getter\", async () => {\n      class A extends S.Class<A>(\"A\")({\n        n: S.NumberFromString\n      }) {\n        get s() {\n          return \"s\"\n        }\n      }\n      class B extends S.Class<B>(\"B\")({\n        n: S.NumberFromString,\n        s: S.String\n      }) {}\n\n      await Util.assertions.encoding.succeed(B, new A({ n: 1 }), { n: \"1\", s: \"s\" })\n    })\n\n    describe(\"encode(S.typeSchema(Class))\", () => {\n      it(\"should always return an instance\", async () => {\n        class A extends S.Class<A>(\"A\")({\n          n: S.NumberFromString\n        }) {}\n        const schema = S.typeSchema(A)\n        await Util.assertions.encoding.succeed(schema, new A({ n: 1 }), new A({ n: 1 }))\n        await Util.assertions.encoding.succeed(schema, { n: 1 }, new A({ n: 1 }))\n      })\n\n      it(\"should fail on bad values\", async () => {\n        class A extends S.Class<A>(\"A\")({\n          n: S.NumberFromString\n        }) {}\n        const schema = S.typeSchema(A)\n        await Util.assertions.encoding.fail(\n          schema,\n          null as any,\n          `Expected A (Type side), actual null`\n        )\n      })\n    })\n  })\n\n  it(\"arbitrary\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String }) {}\n    Util.assertions.arbitrary.validateGeneratedValues(A)\n  })\n\n  it(\"should expose a make constructor\", () => {\n    class A extends S.Class<A>(\"A\")({\n      n: S.NumberFromString\n    }) {\n      a() {\n        return this.n + \"a\"\n      }\n    }\n    const a = A.make({ n: 1 })\n    assertInstanceOf(a, A)\n    strictEqual(a.a(), \"1a\")\n  })\n\n  describe(\"should support annotations when declaring the Class\", () => {\n    it(\"single argument\", async () => {\n      class A extends S.Class<A>(\"A\")({\n        a: S.NonEmptyString\n      }, { title: \"mytitle\" }) {}\n\n      strictEqual(A.ast.to.annotations[AST.TitleAnnotationId], \"mytitle\")\n\n      await Util.assertions.encoding.fail(\n        A,\n        { a: \"\" },\n        `(A (Encoded side) <-> A)\n└─ Type side transformation failure\n   └─ mytitle\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n    })\n\n    it(\"tuple argument\", async () => {\n      class A extends S.Class<A>(\"A\")(\n        {\n          a: S.NonEmptyString\n        },\n        [\n          { identifier: \"TypeID\", description: \"TypeDescription\" },\n          { identifier: \"TransformationID\" },\n          { identifier: \"EncodedID\" }\n        ]\n      ) {}\n      assertSome(AST.getIdentifierAnnotation(A.ast.to), \"TypeID\")\n      assertSome(AST.getIdentifierAnnotation(A.ast), \"TransformationID\")\n      assertSome(AST.getIdentifierAnnotation(A.ast.from), \"EncodedID\")\n\n      await Util.assertions.decoding.fail(\n        A,\n        {},\n        `TransformationID\n└─ Encoded side transformation failure\n   └─ EncodedID\n      └─ [\"a\"]\n         └─ is missing`\n      )\n\n      await Util.assertions.encoding.fail(\n        A,\n        { a: \"\" },\n        `TransformationID\n└─ Type side transformation failure\n   └─ TypeID\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n\n      const ctor = { make: A.make.bind(A) }\n\n      Util.assertions.make.fail(\n        ctor,\n        null as any,\n        `TypeID\n└─ [\"a\"]\n   └─ is missing`\n      )\n\n      deepStrictEqual(JSONSchema.make(S.typeSchema(A)), {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1,\n            \"type\": \"string\"\n          },\n          \"TypeID\": {\n            \"additionalProperties\": false,\n            \"description\": \"TypeDescription\",\n            \"properties\": {\n              \"a\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              }\n            },\n            \"required\": [\n              \"a\"\n            ],\n            \"type\": \"object\"\n          }\n        },\n        \"$ref\": \"#/$defs/TypeID\",\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n      })\n\n      deepStrictEqual(JSONSchema.make(A), {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1,\n            \"type\": \"string\"\n          },\n          \"TransformationID\": {\n            \"additionalProperties\": false,\n            \"description\": \"TypeDescription\",\n            \"properties\": {\n              \"a\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              }\n            },\n            \"required\": [\n              \"a\"\n            ],\n            \"type\": \"object\"\n          }\n        },\n        \"$ref\": \"#/$defs/TransformationID\",\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Class/TaggedClass.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertInstanceOf,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual,\n  throws\n} from \"@effect/vitest/utils\"\nimport { JSONSchema, pipe, Schema as S, SchemaAST as AST, Struct } from \"effect\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"TaggedClass\", () => {\n  it(\"the constructor should add a `_tag` field\", () => {\n    class TA extends S.TaggedClass<TA>()(\"TA\", { a: S.String }) {}\n    deepStrictEqual({ ...new TA({ a: \"a\" }) }, { _tag: \"TA\", a: \"a\" })\n  })\n\n  it(\"should expose the fields and the tag\", () => {\n    class TA extends S.TaggedClass<TA>()(\"TA\", { a: S.String }) {}\n    Util.expectFields(TA.fields, { _tag: S.getClassTag(\"TA\"), a: S.String })\n    deepStrictEqual(S.Struct(TA.fields).make({ a: \"a\" }), { _tag: \"TA\", a: \"a\" })\n    strictEqual(TA._tag, \"TA\")\n  })\n\n  it(\"should expose the identifier\", () => {\n    class TA extends S.TaggedClass<TA>()(\"TA\", { a: S.String }) {}\n    strictEqual(TA.identifier, \"TA\")\n    class TB extends S.TaggedClass<TB>(\"id\")(\"TB\", { a: S.String }) {}\n    strictEqual(TB.identifier, \"id\")\n  })\n\n  it(\"constructor parameters should not overwrite the tag\", async () => {\n    class A extends S.TaggedClass<A>()(\"A\", {\n      a: S.String\n    }) {}\n    strictEqual(new A({ ...{ _tag: \"B\", a: \"a\" } })._tag, \"A\")\n    strictEqual(new A({ ...{ _tag: \"B\", a: \"a\" } }, true)._tag, \"A\")\n  })\n\n  it(\"a TaggedClass with no fields should have a void constructor\", () => {\n    class TA extends S.TaggedClass<TA>()(\"TA\", {}) {}\n    deepStrictEqual({ ...new TA() }, { _tag: \"TA\" })\n    deepStrictEqual({ ...new TA(undefined) }, { _tag: \"TA\" })\n    deepStrictEqual({ ...new TA(undefined, true) }, { _tag: \"TA\" })\n  })\n\n  it(\"a custom _tag field should be not allowed\", () => {\n    throws(\n      () => {\n        class _TA extends S.TaggedClass<_TA>()(\"TA\", { _tag: S.Literal(\"X\"), a: S.String }) {}\n        // eslint-disable-next-line @typescript-eslint/no-unused-expressions\n        _TA\n      },\n      new Error(`Duplicate property signature\ndetails: Duplicate key \"_tag\"`)\n    )\n  })\n\n  it(\"should accept a Struct as argument\", () => {\n    const fields = { a: S.String, b: S.Number }\n    class A extends S.TaggedClass<A>()(\"A\", S.Struct(fields)) {}\n    Util.expectFields(A.fields, { _tag: S.getClassTag(\"A\"), ...fields })\n  })\n\n  it(\"should accept a refinement of a Struct as argument\", async () => {\n    const fields = { a: S.Number, b: S.Number }\n    class A extends S.TaggedClass<A>()(\n      \"A\",\n      S.Struct(fields).pipe(S.filter(({ a, b }) => a === b ? undefined : \"a should be equal to b\"))\n    ) {}\n    Util.expectFields(A.fields, { _tag: S.getClassTag(\"A\"), ...fields })\n    await Util.assertions.decoding.succeed(A, new A({ a: 1, b: 1 }))\n    await Util.assertions.decoding.fail(\n      A,\n      { _tag: \"A\", a: 1, b: 2 },\n      `(A (Encoded side) <-> A)\n└─ Encoded side transformation failure\n   └─ A (Encoded side)\n      └─ Predicate refinement failure\n         └─ a should be equal to b`\n    )\n    Util.assertions.parseError(\n      () => new A({ a: 1, b: 2 }),\n      `A (Constructor)\n└─ Predicate refinement failure\n   └─ a should be equal to b`\n    )\n  })\n\n  it(\"decoding\", async () => {\n    class TA extends S.TaggedClass<TA>()(\"TA\", { a: S.NonEmptyString }) {}\n    await Util.assertions.decoding.succeed(TA, { _tag: \"TA\", a: \"a\" }, new TA({ a: \"a\" }))\n    await Util.assertions.decoding.fail(\n      TA,\n      { a: \"a\" },\n      `(TA (Encoded side) <-> TA)\n└─ Encoded side transformation failure\n   └─ TA (Encoded side)\n      └─ [\"_tag\"]\n         └─ is missing`\n    )\n    await Util.assertions.decoding.fail(\n      TA,\n      { _tag: \"TA\", a: \"\" },\n      `(TA (Encoded side) <-> TA)\n└─ Encoded side transformation failure\n   └─ TA (Encoded side)\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    class TA extends S.TaggedClass<TA>()(\"TA\", { a: S.NonEmptyString }) {}\n    await Util.assertions.encoding.succeed(TA, new TA({ a: \"a\" }), { _tag: \"TA\", a: \"a\" })\n    await Util.assertions.encoding.succeed(TA, { _tag: \"TA\", a: \"a\" } as any, { _tag: \"TA\", a: \"a\" })\n    await Util.assertions.encoding.fail(\n      TA,\n      new TA({ a: \"\" }, true),\n      `(TA (Encoded side) <-> TA)\n└─ Encoded side transformation failure\n   └─ TA (Encoded side)\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n    )\n  })\n\n  it(\"can be extended with Class fields\", () => {\n    class TA extends S.TaggedClass<TA>()(\"TA\", { a: S.String }) {}\n    class B extends S.Class<B>(\"B\")({\n      b: S.Number,\n      ...TA.fields\n    }) {}\n    Util.expectFields(B.fields, {\n      _tag: S.getClassTag(\"TA\"),\n      a: S.String,\n      b: S.Number\n    })\n    deepStrictEqual({ ...new B({ _tag: \"TA\", a: \"a\", b: 1 }) }, { _tag: \"TA\", a: \"a\", b: 1 })\n  })\n\n  it(\"can be extended with TaggedClass fields\", () => {\n    class TA extends S.TaggedClass<TA>()(\"TA\", { a: S.String }) {}\n    class TB extends S.TaggedClass<TB>()(\"TB\", {\n      b: S.Number,\n      ...pipe(TA.fields, Struct.omit(\"_tag\"))\n    }) {}\n    Util.expectFields(TB.fields, {\n      _tag: S.getClassTag(\"TB\"),\n      a: S.String,\n      b: S.Number\n    })\n    deepStrictEqual({ ...new TB({ a: \"a\", b: 1 }) }, { _tag: \"TB\", a: \"a\", b: 1 })\n  })\n\n  it(\"equivalence\", () => {\n    class A extends S.TaggedClass<A>()(\"A\", {\n      a: S.String\n    }) {}\n    const eqA = S.equivalence(A)\n    assertTrue(eqA(new A({ a: \"a\" }), new A({ a: \"a\" })))\n    assertFalse(eqA(new A({ a: \"a\" }), new A({ a: \"b\" })))\n\n    class B extends S.TaggedClass<B>()(\"B\", {\n      b: S.Number,\n      as: S.Array(A)\n    }) {}\n    const eqB = S.equivalence(B)\n    assertTrue(eqB(new B({ b: 1, as: [] }), new B({ b: 1, as: [] })))\n    assertFalse(eqB(new B({ b: 1, as: [] }), new B({ b: 2, as: [] })))\n    assertTrue(eqB(new B({ b: 1, as: [new A({ a: \"a\" })] }), new B({ b: 1, as: [new A({ a: \"a\" })] })))\n    assertFalse(eqB(new B({ b: 1, as: [new A({ a: \"a\" })] }), new B({ b: 1, as: [new A({ a: \"b\" })] })))\n  })\n\n  it(\"baseline\", () => {\n    class TaggedPerson extends S.TaggedClass<TaggedPerson>()(\"TaggedPerson\", {\n      id: S.Number,\n      name: S.String.pipe(S.nonEmptyString())\n    }) {\n      get upperName() {\n        return this.name.toUpperCase()\n      }\n    }\n\n    class TaggedPersonWithAge extends TaggedPerson.extend<TaggedPersonWithAge>(\"TaggedPersonWithAge\")({\n      age: S.Number\n    }) {\n      get isAdult() {\n        return this.age >= 18\n      }\n    }\n\n    let person = new TaggedPersonWithAge({ id: 1, name: \"John\", age: 30 })\n\n    strictEqual(String(person), `TaggedPersonWithAge({ \"_tag\": \"TaggedPerson\", \"id\": 1, \"name\": \"John\", \"age\": 30 })`)\n    strictEqual(person._tag, \"TaggedPerson\")\n    strictEqual(person.upperName, \"JOHN\")\n\n    Util.assertions.parseError(\n      () => S.decodeUnknownSync(TaggedPersonWithAge)({ id: 1, name: \"John\", age: 30 }),\n      `(TaggedPersonWithAge (Encoded side) <-> TaggedPersonWithAge)\n└─ Encoded side transformation failure\n   └─ TaggedPersonWithAge (Encoded side)\n      └─ [\"_tag\"]\n         └─ is missing`\n    )\n    person = S.decodeUnknownSync(TaggedPersonWithAge)({\n      _tag: \"TaggedPerson\",\n      id: 1,\n      name: \"John\",\n      age: 30\n    })\n    strictEqual(person._tag, \"TaggedPerson\")\n    strictEqual(person.upperName, \"JOHN\")\n  })\n\n  it(\"should expose a make constructor\", () => {\n    class TA extends S.TaggedClass<TA>()(\"TA\", {\n      n: S.NumberFromString\n    }) {\n      a() {\n        return this.n + \"a\"\n      }\n    }\n    const ta = TA.make({ n: 1 })\n    assertInstanceOf(ta, TA)\n    strictEqual(ta._tag, \"TA\")\n    strictEqual(ta.a(), \"1a\")\n  })\n\n  describe(\"should support annotations when declaring the Class\", () => {\n    it(\"single argument\", async () => {\n      class A extends S.TaggedClass<A>()(\"A\", {\n        a: S.NonEmptyString\n      }, { title: \"mytitle\" }) {}\n\n      strictEqual(A.ast.to.annotations[AST.TitleAnnotationId], \"mytitle\")\n\n      await Util.assertions.encoding.fail(\n        A,\n        { _tag: \"A\", a: \"\" },\n        `(A (Encoded side) <-> A)\n└─ Type side transformation failure\n   └─ mytitle\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n    })\n\n    it(\"tuple argument\", async () => {\n      class A extends S.TaggedClass<A>()(\"A\", {\n        a: S.NonEmptyString\n      }, [\n        { identifier: \"TypeID\", description: \"TypeDescription\" },\n        { identifier: \"TransformationID\" },\n        { identifier: \"EncodedID\" }\n      ]) {}\n      assertSome(AST.getIdentifierAnnotation(A.ast.to), \"TypeID\")\n      assertSome(AST.getIdentifierAnnotation(A.ast), \"TransformationID\")\n      assertSome(AST.getIdentifierAnnotation(A.ast.from), \"EncodedID\")\n\n      await Util.assertions.decoding.fail(\n        A,\n        {},\n        `TransformationID\n└─ Encoded side transformation failure\n   └─ EncodedID\n      └─ [\"a\"]\n         └─ is missing`\n      )\n\n      await Util.assertions.encoding.fail(\n        A,\n        { _tag: \"A\", a: \"\" },\n        `TransformationID\n└─ Type side transformation failure\n   └─ TypeID\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n\n      const ctor = { make: A.make.bind(A) }\n\n      Util.assertions.make.fail(\n        ctor,\n        null as any,\n        `TypeID\n└─ [\"a\"]\n   └─ is missing`\n      )\n\n      deepStrictEqual(JSONSchema.make(S.typeSchema(A)), {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1,\n            \"type\": \"string\"\n          },\n          \"TypeID\": {\n            \"additionalProperties\": false,\n            \"description\": \"TypeDescription\",\n            \"properties\": {\n              \"_tag\": {\n                \"enum\": [\n                  \"A\"\n                ],\n                \"type\": \"string\"\n              },\n              \"a\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              }\n            },\n            \"required\": [\"a\", \"_tag\"],\n            \"type\": \"object\"\n          }\n        },\n        \"$ref\": \"#/$defs/TypeID\",\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n      })\n\n      deepStrictEqual(JSONSchema.make(A), {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1,\n            \"type\": \"string\"\n          },\n          \"TransformationID\": {\n            \"additionalProperties\": false,\n            \"description\": \"TypeDescription\",\n            \"properties\": {\n              \"_tag\": {\n                \"enum\": [\n                  \"A\"\n                ],\n                \"type\": \"string\"\n              },\n              \"a\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              }\n            },\n            \"required\": [\"a\", \"_tag\"],\n            \"type\": \"object\"\n          }\n        },\n        \"$ref\": \"#/$defs/TransformationID\",\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Class/TaggedError.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInclude, assertInstanceOf, assertSome, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Cause, Effect, Inspectable, JSONSchema, Schema, SchemaAST as AST } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"TaggedError\", () => {\n  it(\"should expose the fields and the tag\", () => {\n    class TE extends S.TaggedError<TE>()(\"TE\", { a: S.String }) {}\n    Util.expectFields(TE.fields, { _tag: S.getClassTag(\"TE\"), a: S.String })\n    deepStrictEqual(S.Struct(TE.fields).make({ a: \"a\" }), { _tag: \"TE\", a: \"a\" })\n    strictEqual(TE._tag, \"TE\")\n  })\n\n  it(\"make should respect custom constructors\", () => {\n    class MyError extends Schema.TaggedError<MyError>()(\n      \"MyError\",\n      { message: Schema.String }\n    ) {\n      constructor({ a, b }: { a: string; b: string }) {\n        super({ message: `${a}:${b}` })\n      }\n    }\n\n    strictEqual(MyError.make({ a: \"a\", b: \"b\" }).message, \"a:b\")\n    strictEqual(new MyError({ a: \"a\", b: \"b\" }).message, \"a:b\")\n  })\n\n  it(\"should accept a Struct as argument\", () => {\n    const fields = { a: S.String, b: S.Number }\n    class A extends S.TaggedError<A>()(\"A\", S.Struct(fields)) {}\n    Util.expectFields(A.fields, { _tag: S.getClassTag(\"A\"), ...fields })\n  })\n\n  it(\"should accept a refinement of a Struct as argument\", async () => {\n    const fields = { a: S.Number, b: S.Number }\n    class A extends S.TaggedError<A>()(\n      \"A\",\n      S.Struct(fields).pipe(S.filter(({ a, b }) => a === b ? undefined : \"a should be equal to b\"))\n    ) {}\n    Util.expectFields(A.fields, { _tag: S.getClassTag(\"A\"), ...fields })\n    await Util.assertions.decoding.succeed(A, new A({ a: 1, b: 1 }))\n    await Util.assertions.decoding.fail(\n      A,\n      { _tag: \"A\", a: 1, b: 2 },\n      `(A (Encoded side) <-> A)\n└─ Encoded side transformation failure\n   └─ A (Encoded side)\n      └─ Predicate refinement failure\n         └─ a should be equal to b`\n    )\n    Util.assertions.parseError(\n      () => new A({ a: 1, b: 2 }),\n      `A (Constructor)\n└─ Predicate refinement failure\n   └─ a should be equal to b`\n    )\n  })\n\n  it(\"baseline\", () => {\n    class MyError extends S.TaggedError<MyError>()(\"MyError\", {\n      id: S.Number\n    }) {}\n\n    let err = new MyError({ id: 1 })\n\n    strictEqual(String(err), `MyError: { \"id\": 1 }`)\n    assertInclude(err.stack, \"TaggedError.test.ts:\")\n    strictEqual(err._tag, \"MyError\")\n    strictEqual(err.id, 1)\n\n    err = Effect.runSync(Effect.flip(err))\n    strictEqual(err._tag, \"MyError\")\n    strictEqual(err.id, 1)\n\n    err = S.decodeUnknownSync(MyError)({ _tag: \"MyError\", id: 1 })\n    strictEqual(err._tag, \"MyError\")\n    strictEqual(err.id, 1)\n  })\n\n  it(\"message\", () => {\n    class MyError extends S.TaggedError<MyError>()(\"MyError\", {\n      id: S.Number\n    }) {\n      get message() {\n        return `bad id: ${this.id}`\n      }\n    }\n\n    const err = new MyError({ id: 1 })\n\n    assertInclude(String(err), `MyError: bad id: 1`)\n    assertInclude(err.stack, \"TaggedError.test.ts:\")\n    strictEqual(err._tag, \"MyError\")\n    strictEqual(err.id, 1)\n  })\n\n  it(\"message field\", () => {\n    class MyError extends S.TaggedError<MyError>()(\"MyError\", {\n      id: S.Number,\n      message: S.String\n    }) {\n    }\n\n    const err = new MyError({ id: 1, message: \"boom\" })\n\n    assertInclude(String(err), `MyError: boom`)\n    assertInclude(err.stack, \"TaggedError.test.ts:\")\n    strictEqual(err._tag, \"MyError\")\n    strictEqual(err.id, 1)\n  })\n\n  it(\"should expose a make constructor\", () => {\n    class A extends S.TaggedError<A>()(\"A\", {\n      n: S.NumberFromString\n    }) {\n      a() {\n        return this.n + \"a\"\n      }\n    }\n    const a = A.make({ n: 1 })\n    assertInstanceOf(a, A)\n    strictEqual(a._tag, \"A\")\n    strictEqual(a.a(), \"1a\")\n  })\n\n  it(\"cause\", () => {\n    class MyError extends S.TaggedError<MyError>()(\"MyError\", {\n      cause: Schema.Defect\n    }) {}\n\n    const err = new MyError({ cause: new Error(\"child\") })\n    assertInclude(Cause.pretty(Cause.fail(err), { renderErrorCause: true }), \"[cause]: Error: child\")\n    // ensure node renders the error directly\n    deepStrictEqual(err[Inspectable.NodeInspectSymbol](), err)\n  })\n\n  describe(\"should support annotations when declaring the Class\", () => {\n    it(\"single argument\", async () => {\n      class A extends S.TaggedError<A>()(\"A\", {\n        a: S.NonEmptyString\n      }, { title: \"mytitle\" }) {}\n\n      strictEqual(A.ast.to.annotations[AST.TitleAnnotationId], \"mytitle\")\n\n      await Util.assertions.encoding.fail(\n        A,\n        { _tag: \"A\", a: \"\" } as any,\n        `(A (Encoded side) <-> A)\n└─ Type side transformation failure\n   └─ mytitle\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n    })\n\n    it(\"tuple argument\", async () => {\n      class A extends S.TaggedError<A>()(\"A\", {\n        a: S.NonEmptyString\n      }, [\n        { identifier: \"TypeID\", description: \"TypeDescription\" },\n        { identifier: \"TransformationID\" },\n        { identifier: \"EncodedID\" }\n      ]) {}\n      assertSome(AST.getIdentifierAnnotation(A.ast.to), \"TypeID\")\n      assertSome(AST.getIdentifierAnnotation(A.ast), \"TransformationID\")\n      assertSome(AST.getIdentifierAnnotation(A.ast.from), \"EncodedID\")\n\n      await Util.assertions.decoding.fail(\n        A,\n        {},\n        `TransformationID\n└─ Encoded side transformation failure\n   └─ EncodedID\n      └─ [\"a\"]\n         └─ is missing`\n      )\n\n      await Util.assertions.encoding.fail(\n        A,\n        { _tag: \"A\", a: \"\" } as any,\n        `TransformationID\n└─ Type side transformation failure\n   └─ TypeID\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n\n      const ctor = { make: A.make.bind(A) }\n\n      Util.assertions.make.fail(\n        ctor,\n        null as any,\n        `TypeID\n└─ [\"a\"]\n   └─ is missing`\n      )\n\n      deepStrictEqual(JSONSchema.make(S.typeSchema(A)), {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1,\n            \"type\": \"string\"\n          },\n          \"TypeID\": {\n            \"additionalProperties\": false,\n            \"description\": \"TypeDescription\",\n            \"properties\": {\n              \"_tag\": {\n                \"enum\": [\n                  \"A\"\n                ],\n                \"type\": \"string\"\n              },\n              \"a\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              }\n            },\n            \"required\": [\"a\", \"_tag\"],\n            \"type\": \"object\"\n          }\n        },\n        \"$ref\": \"#/$defs/TypeID\",\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n      })\n\n      deepStrictEqual(JSONSchema.make(A), {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1,\n            \"type\": \"string\"\n          },\n          \"TransformationID\": {\n            \"additionalProperties\": false,\n            \"description\": \"TypeDescription\",\n            \"properties\": {\n              \"_tag\": {\n                \"enum\": [\n                  \"A\"\n                ],\n                \"type\": \"string\"\n              },\n              \"a\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              }\n            },\n            \"required\": [\"a\", \"_tag\"],\n            \"type\": \"object\"\n          }\n        },\n        \"$ref\": \"#/$defs/TransformationID\",\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n      })\n    })\n  })\n\n  it(\"should allow an optional `message` field\", () => {\n    class MyError extends S.TaggedError<MyError>()(\"MyError\", {\n      message: S.optional(S.String)\n    }) {}\n\n    const err = new MyError({})\n    strictEqual(err.message, \"\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Class/TaggedRequest.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInstanceOf, assertSome, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Context, Effect, Equal, Exit, JSONSchema, ParseResult, Request, Schema as S, SchemaAST as AST } from \"effect\"\nimport * as Util from \"../../TestUtils.js\"\n\nconst Name = Context.GenericTag<\"Name\", string>(\"Name\")\nconst NameString = S.String.pipe(\n  S.nonEmptyString(),\n  S.transformOrFail(\n    S.String,\n    {\n      decode: (_, _opts, ast) =>\n        Name.pipe(\n          Effect.filterOrFail(\n            (name) => _ === name,\n            () => new ParseResult.Type(ast, _, \"Does not match Name\")\n          )\n        ),\n      encode: (_) => ParseResult.succeed(_)\n    }\n  )\n)\n\nconst Id = Context.GenericTag<\"Id\", number>(\"Name\")\nconst IdNumber = S.Number.pipe(\n  S.transformOrFail(\n    S.Number,\n    {\n      strict: true,\n      decode: (_, _opts, ast) =>\n        Effect.filterOrFail(\n          Id,\n          (id) => _ === id,\n          () => new ParseResult.Type(ast, _, \"Does not match Id\")\n        ),\n      encode: (_) => ParseResult.succeed(_)\n    }\n  )\n)\n\ndescribe(\"TaggedRequest\", () => {\n  it(\"should expose the fields, the tag, the success and the failure schema\", () => {\n    class TRA extends S.TaggedRequest<TRA>()(\"TRA\", {\n      failure: S.String,\n      success: S.Number,\n      payload: {\n        id: S.Number\n      }\n    }) {}\n    Util.expectFields(TRA.fields, {\n      _tag: S.getClassTag(\"TRA\"),\n      id: S.Number\n    })\n    strictEqual(TRA._tag, \"TRA\")\n    strictEqual(TRA.success, S.Number)\n    strictEqual(TRA.failure, S.String)\n  })\n\n  it(\"should expose the identifier\", () => {\n    class TRA extends S.TaggedRequest<TRA>()(\"TRA\", {\n      failure: S.String,\n      success: S.Number,\n      payload: {\n        id: S.Number\n      }\n    }) {}\n    strictEqual(TRA.identifier, \"TRA\")\n    class TRB extends S.TaggedRequest<TRB>(\"id\")(\"TRB\", {\n      failure: S.String,\n      success: S.Number,\n      payload: {\n        id: S.Number\n      }\n    }) {}\n    strictEqual(TRB.identifier, \"id\")\n  })\n\n  it(\"baseline\", () => {\n    class MyRequest extends S.TaggedRequest<MyRequest>()(\"MyRequest\", {\n      failure: S.String,\n      success: S.Number,\n      payload: {\n        id: S.Number\n      }\n    }) {}\n\n    let req = new MyRequest({ id: 1 })\n\n    strictEqual(String(req), `MyRequest({ \"_tag\": \"MyRequest\", \"id\": 1 })`)\n    strictEqual(req._tag, \"MyRequest\")\n    strictEqual(req.id, 1)\n    assertTrue(Request.isRequest(req))\n\n    req = S.decodeSync(MyRequest)({ _tag: \"MyRequest\", id: 1 })\n    strictEqual(req._tag, \"MyRequest\")\n    strictEqual(req.id, 1)\n    assertTrue(Request.isRequest(req))\n  })\n\n  it(\"TaggedRequest extends SerializableWithExit\", () => {\n    class MyRequest extends S.TaggedRequest<MyRequest>()(\"MyRequest\", {\n      failure: S.String,\n      success: S.NumberFromString,\n      payload: {\n        id: S.Number\n      }\n    }) {}\n\n    const req = new MyRequest({ id: 1 })\n    deepStrictEqual(\n      S.serialize(req).pipe(Effect.runSync),\n      { _tag: \"MyRequest\", id: 1 }\n    )\n    assertTrue(Equal.equals(\n      S.deserialize(req, { _tag: \"MyRequest\", id: 1 }).pipe(Effect.runSync),\n      req\n    ))\n    deepStrictEqual(\n      S.serializeExit(req, Exit.fail(\"fail\")).pipe(Effect.runSync),\n      { _tag: \"Failure\", cause: { _tag: \"Fail\", error: \"fail\" } }\n    )\n    deepStrictEqual(\n      S.deserializeExit(req, { _tag: \"Failure\", cause: { _tag: \"Fail\", error: \"fail\" } })\n        .pipe(Effect.runSync),\n      Exit.fail(\"fail\")\n    )\n    deepStrictEqual(\n      S.serializeExit(req, Exit.succeed(123)).pipe(Effect.runSync),\n      { _tag: \"Success\", value: \"123\" }\n    )\n    deepStrictEqual(\n      S.deserializeExit(req, { _tag: \"Success\", value: \"123\" }).pipe(Effect.runSync),\n      Exit.succeed(123)\n    )\n  })\n\n  it(\"TaggedRequest context\", () => {\n    class MyRequest extends S.TaggedRequest<MyRequest>()(\"MyRequest\", {\n      failure: NameString,\n      success: S.Number,\n      payload: {\n        id: IdNumber\n      }\n    }) {}\n\n    let req = new MyRequest({ id: 1 }, true)\n    strictEqual(String(req), `MyRequest({ \"_tag\": \"MyRequest\", \"id\": 1 })`)\n\n    req = S.decode(MyRequest)({ _tag: \"MyRequest\", id: 1 }).pipe(\n      Effect.provideService(Id, 1),\n      Effect.runSync\n    )\n    strictEqual(String(req), `MyRequest({ \"_tag\": \"MyRequest\", \"id\": 1 })`)\n\n    deepStrictEqual(\n      S.serialize(req).pipe(\n        Effect.provideService(Id, 1),\n        Effect.runSync\n      ),\n      { _tag: \"MyRequest\", id: 1 }\n    )\n    deepStrictEqual(\n      S.deserialize(req, { _tag: \"MyRequest\", id: 1 }).pipe(\n        Effect.provideService(Id, 1),\n        Effect.runSync\n      ),\n      req\n    )\n    deepStrictEqual(\n      S.serializeExit(req, Exit.fail(\"fail\")).pipe(\n        Effect.provideService(Name, \"fail\"),\n        Effect.runSync\n      ),\n      { _tag: \"Failure\", cause: { _tag: \"Fail\", error: \"fail\" } }\n    )\n    deepStrictEqual(\n      S.deserializeExit(req, { _tag: \"Failure\", cause: { _tag: \"Fail\", error: \"fail\" } })\n        .pipe(\n          Effect.provideService(Name, \"fail\"),\n          Effect.runSync\n        ),\n      Exit.fail(\"fail\")\n    )\n  })\n\n  it(\"should expose a make constructor\", () => {\n    class TRA extends S.TaggedRequest<TRA>()(\"TRA\", {\n      failure: S.String,\n      success: S.Number,\n      payload: {\n        n: S.NumberFromString\n      }\n    }) {\n      a() {\n        return this.n + \"a\"\n      }\n    }\n    const tra = TRA.make({ n: 1 })\n    assertInstanceOf(tra, TRA)\n    strictEqual(tra._tag, \"TRA\")\n    strictEqual(tra.a(), \"1a\")\n  })\n\n  describe(\"should support annotations when declaring the Class\", () => {\n    it(\"single argument\", async () => {\n      class A extends S.TaggedRequest<A>()(\"A\", {\n        failure: S.String,\n        success: S.Number,\n        payload: {\n          a: S.NonEmptyString\n        }\n      }, { title: \"mytitle\" }) {}\n\n      strictEqual(A.ast.to.annotations[AST.TitleAnnotationId], \"mytitle\")\n\n      await Util.assertions.encoding.fail(\n        A,\n        { _tag: \"A\", a: \"\" } as any,\n        `(A (Encoded side) <-> A)\n└─ Type side transformation failure\n   └─ mytitle\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n    })\n\n    it(\"tuple argument\", async () => {\n      class A extends S.TaggedRequest<A>()(\"A\", {\n        failure: S.String,\n        success: S.Number,\n        payload: {\n          a: S.NonEmptyString\n        }\n      }, [\n        { identifier: \"TypeID\", description: \"TypeDescription\" },\n        { identifier: \"TransformationID\" },\n        { identifier: \"EncodedID\" }\n      ]) {}\n      assertSome(AST.getIdentifierAnnotation(A.ast.to), \"TypeID\")\n      assertSome(AST.getIdentifierAnnotation(A.ast), \"TransformationID\")\n      assertSome(AST.getIdentifierAnnotation(A.ast.from), \"EncodedID\")\n\n      await Util.assertions.decoding.fail(\n        A,\n        {},\n        `TransformationID\n└─ Encoded side transformation failure\n   └─ EncodedID\n      └─ [\"_tag\"]\n         └─ is missing`\n      )\n\n      await Util.assertions.encoding.fail(\n        A,\n        { _tag: \"A\", a: \"\" } as any,\n        `TransformationID\n└─ Type side transformation failure\n   └─ TypeID\n      └─ [\"a\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n\n      const ctor = { make: A.make.bind(A) }\n\n      Util.assertions.make.fail(\n        ctor,\n        null as any,\n        `TypeID\n└─ [\"a\"]\n   └─ is missing`\n      )\n\n      deepStrictEqual(JSONSchema.make(S.typeSchema(A)), {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1,\n            \"type\": \"string\"\n          },\n          \"TypeID\": {\n            \"additionalProperties\": false,\n            \"description\": \"TypeDescription\",\n            \"properties\": {\n              \"_tag\": {\n                \"enum\": [\n                  \"A\"\n                ],\n                \"type\": \"string\"\n              },\n              \"a\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              }\n            },\n            \"required\": [\"_tag\", \"a\"],\n            \"type\": \"object\"\n          }\n        },\n        \"$ref\": \"#/$defs/TypeID\",\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n      })\n\n      deepStrictEqual(JSONSchema.make(A), {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1,\n            \"type\": \"string\"\n          },\n          \"TransformationID\": {\n            \"additionalProperties\": false,\n            \"description\": \"TypeDescription\",\n            \"properties\": {\n              \"_tag\": {\n                \"enum\": [\n                  \"A\"\n                ],\n                \"type\": \"string\"\n              },\n              \"a\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              }\n            },\n            \"required\": [\"_tag\", \"a\"],\n            \"type\": \"object\"\n          }\n        },\n        \"$ref\": \"#/$defs/TransformationID\",\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Class/extend.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInstanceOf, assertSome, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { JSONSchema, Schema as S, SchemaAST as AST } from \"effect\"\nimport * as Util from \"../../TestUtils.js\"\n\nclass Person extends S.Class<Person>(\"Person\")({\n  id: S.Number,\n  name: S.String.pipe(S.nonEmptyString())\n}) {\n  get upperName() {\n    return this.name.toUpperCase()\n  }\n}\n\nclass PersonWithAge extends Person.extend<PersonWithAge>(\"PersonWithAge\")({\n  age: S.Number\n}) {\n  get isAdult() {\n    return this.age >= 18\n  }\n}\n\nclass PersonWithNick extends PersonWithAge.extend<PersonWithNick>(\"PersonWithNick\")({\n  nick: S.String\n}) {}\n\ndescribe(\"extend\", () => {\n  it(\"1 extend\", () => {\n    const person = S.decodeUnknownSync(PersonWithAge)({\n      id: 1,\n      name: \"John\",\n      age: 30\n    })\n    deepStrictEqual(PersonWithAge.fields, {\n      ...Person.fields,\n      age: S.Number\n    })\n    strictEqual(PersonWithAge.identifier, \"PersonWithAge\")\n    strictEqual(person.name, \"John\")\n    strictEqual(person.age, 30)\n    strictEqual(person.isAdult, true)\n    strictEqual(person.upperName, \"JOHN\")\n    strictEqual(typeof person.upperName, \"string\")\n  })\n\n  it(\"2 extend\", () => {\n    const person = S.decodeUnknownSync(PersonWithNick)({\n      id: 1,\n      name: \"John\",\n      age: 30,\n      nick: \"Joe\"\n    })\n    strictEqual(person.age, 30)\n    strictEqual(person.nick, \"Joe\")\n  })\n\n  it(\"should accept a Struct as argument\", () => {\n    const baseFields = { base: S.String }\n    class Base extends S.Class<Base>(\"Base\")(baseFields) {}\n    const fields = { a: S.String, b: S.Number }\n    class A extends Base.extend<A>(\"A\")(S.Struct(fields)) {}\n    Util.expectFields(A.fields, { ...baseFields, ...fields })\n  })\n\n  it(\"should accept a refinement of a Struct as argument\", async () => {\n    const baseFields = { base: S.String }\n    class Base extends S.Class<Base>(\"Base\")(baseFields) {}\n    const fields = { a: S.Number, b: S.Number }\n    class A extends Base.extend<A>(\"A\")(\n      S.Struct(fields).pipe(S.filter(({ a, b }) => a === b ? undefined : \"a should be equal to b\"))\n    ) {}\n    Util.expectFields(A.fields, { ...baseFields, ...fields })\n    await Util.assertions.decoding.succeed(A, new A({ base: \"base\", a: 1, b: 1 }))\n    await Util.assertions.decoding.fail(\n      A,\n      { base: \"base\", a: 1, b: 2 },\n      `(A (Encoded side) <-> A)\n└─ Encoded side transformation failure\n   └─ A (Encoded side)\n      └─ Predicate refinement failure\n         └─ a should be equal to b`\n    )\n    Util.assertions.parseError(\n      () => new A({ base: \"base\", a: 1, b: 2 }),\n      `A (Constructor)\n└─ Predicate refinement failure\n   └─ a should be equal to b`\n    )\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      PersonWithAge,\n      { id: 1, name: \"John\" },\n      `(PersonWithAge (Encoded side) <-> PersonWithAge)\n└─ Encoded side transformation failure\n   └─ PersonWithAge (Encoded side)\n      └─ [\"age\"]\n         └─ is missing`\n    )\n  })\n\n  it(\"should expose a make constructor\", () => {\n    class A extends S.Class<A>(\"A\")({\n      n: S.NumberFromString\n    }) {\n      a() {\n        return this.n + \"a\"\n      }\n    }\n    class B extends A.extend<B>(\"B\")({\n      c: S.String\n    }) {\n      b() {\n        return this.n + \"b\"\n      }\n    }\n    const b = B.make({ n: 1, c: \"c\" })\n    assertInstanceOf(b, B)\n    strictEqual(b.a(), \"1a\")\n    strictEqual(b.b(), \"1b\")\n  })\n\n  it(\"users can override an instance member property\", () => {\n    class OverrideBase1 extends S.Class<OverrideBase1>(\"OverrideBase1\")(S.Struct({\n      a: S.String\n    })) {\n      readonly b: number = 1\n    }\n\n    class OverrideExtended1 extends OverrideBase1.extend<OverrideExtended1>(\n      \"OverrideExtended1\"\n    )({\n      c: S.String\n    }) {\n      override readonly b = 2\n    }\n\n    strictEqual(new OverrideExtended1({ a: \"a\", c: \"c\" }).b, 2)\n  })\n\n  it(\"users can override an instance member function\", () => {\n    class OverrideBase2 extends S.Class<OverrideBase2>(\"OverrideBase2\")(S.Struct({\n      a: S.String\n    })) {\n      b(): number {\n        return 1\n      }\n    }\n\n    class OverrideExtended2 extends OverrideBase2.extend<OverrideExtended2>(\n      \"OverrideExtended2\"\n    )({\n      c: S.String\n    }) {\n      override b(): 2 {\n        return 2\n      }\n    }\n\n    strictEqual(new OverrideExtended2({ a: \"a\", c: \"c\" }).b(), 2)\n  })\n\n  it(\"users can override a field with an instance member property\", () => {\n    class OverrideBase3 extends S.Class<OverrideBase3>(\"OverrideBase3\")(S.Struct({\n      a: S.String\n    })) {}\n\n    class OverrideExtended3 extends OverrideBase3.extend<OverrideExtended3>(\n      \"OverrideExtended3\"\n    )({\n      c: S.String\n    }) {\n      override readonly a = \"default\"\n    }\n\n    strictEqual(new OverrideExtended3({ a: \"a\", c: \"c\" }).a, \"default\")\n  })\n\n  it(\"users can't override an instance member property with a field\", () => {\n    class OverrideBase4 extends S.Class<OverrideBase4>(\"OverrideBase4\")(S.Struct({\n      a: S.String\n    })) {\n      readonly b = 1\n    }\n\n    class OverrideExtended4 extends OverrideBase4.extend<OverrideExtended4>(\n      \"OverrideExtended4\"\n    )({\n      b: S.Number\n    }) {}\n\n    strictEqual(new OverrideExtended4({ a: \"a\", b: 2 }).b, 1)\n  })\n\n  describe(\"should support annotations when declaring the Class\", () => {\n    it(\"single argument\", async () => {\n      class A extends S.Class<A>(\"A\")({\n        a: S.NonEmptyString\n      }) {}\n      class B extends A.extend<B>(\"B\")({\n        b: S.NonEmptyString\n      }, { title: \"mytitle\" }) {}\n\n      strictEqual(B.ast.to.annotations[AST.TitleAnnotationId], \"mytitle\")\n\n      await Util.assertions.encoding.fail(\n        B,\n        { a: \"a\", b: \"\" },\n        `(B (Encoded side) <-> B)\n└─ Type side transformation failure\n   └─ mytitle\n      └─ [\"b\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n    })\n\n    it(\"tuple argument\", async () => {\n      class A extends S.Class<A>(\"A\")({\n        a: S.NonEmptyString\n      }) {}\n      class B extends A.extend<B>(\"B\")({\n        b: S.NonEmptyString\n      }, [\n        { identifier: \"TypeID\", description: \"TypeDescription\" },\n        { identifier: \"TransformationID\" },\n        { identifier: \"EncodedID\" }\n      ]) {}\n      assertSome(AST.getIdentifierAnnotation(B.ast.to), \"TypeID\")\n      assertSome(AST.getIdentifierAnnotation(B.ast), \"TransformationID\")\n      assertSome(AST.getIdentifierAnnotation(B.ast.from), \"EncodedID\")\n\n      await Util.assertions.decoding.fail(\n        B,\n        {},\n        `TransformationID\n└─ Encoded side transformation failure\n   └─ EncodedID\n      └─ [\"a\"]\n         └─ is missing`\n      )\n\n      await Util.assertions.encoding.fail(\n        B,\n        { a: \"a\", b: \"\" },\n        `TransformationID\n└─ Type side transformation failure\n   └─ TypeID\n      └─ [\"b\"]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n\n      const ctor = { make: B.make.bind(B) }\n\n      Util.assertions.make.fail(\n        ctor,\n        null as any,\n        `TypeID\n└─ [\"a\"]\n   └─ is missing`\n      )\n\n      deepStrictEqual(JSONSchema.make(S.typeSchema(B)), {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1,\n            \"type\": \"string\"\n          },\n          \"TypeID\": {\n            \"additionalProperties\": false,\n            \"description\": \"TypeDescription\",\n            \"properties\": {\n              \"a\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              },\n              \"b\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              }\n            },\n            \"required\": [\"a\", \"b\"],\n            \"type\": \"object\"\n          }\n        },\n        \"$ref\": \"#/$defs/TypeID\",\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n      })\n\n      deepStrictEqual(JSONSchema.make(B), {\n        \"$defs\": {\n          \"NonEmptyString\": {\n            \"title\": \"nonEmptyString\",\n            \"description\": \"a non empty string\",\n            \"minLength\": 1,\n            \"type\": \"string\"\n          },\n          \"TransformationID\": {\n            \"additionalProperties\": false,\n            \"description\": \"TypeDescription\",\n            \"properties\": {\n              \"a\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              },\n              \"b\": {\n                \"$ref\": \"#/$defs/NonEmptyString\"\n              }\n            },\n            \"required\": [\"a\", \"b\"],\n            \"type\": \"object\"\n          }\n        },\n        \"$ref\": \"#/$defs/TransformationID\",\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Class/transformOrFail.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInstanceOf, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\nclass Person extends S.Class<Person>(\"Person\")({\n  id: S.Number,\n  name: S.String.pipe(S.nonEmptyString())\n}) {\n  get upperName() {\n    return this.name.toUpperCase()\n  }\n}\n\nconst Thing = S.optionalWith(S.Struct({ id: S.Number }), { exact: true, as: \"Option\" })\n\nclass PersonWithTransform extends Person.transformOrFail<PersonWithTransform>(\"PersonWithTransform\")(\n  {\n    thing: Thing\n  },\n  {\n    decode: (input, _, ast) =>\n      input.id === 2 ?\n        ParseResult.fail(new ParseResult.Type(ast, input)) :\n        ParseResult.succeed({\n          ...input,\n          thing: Option.some({ id: 123 })\n        }),\n    encode: (input, _, ast) =>\n      input.id === 2 ?\n        ParseResult.fail(new ParseResult.Type(ast, input)) :\n        ParseResult.succeed(input)\n  }\n) {\n  a() {\n    return this.id + \"a\"\n  }\n}\n\ndescribe(\"transformOrFail\", () => {\n  it(\"transformOrFail\", async () => {\n    const decode = S.decodeSync(PersonWithTransform)\n    const person = decode({\n      id: 1,\n      name: \"John\"\n    })\n    deepStrictEqual(PersonWithTransform.fields, {\n      ...Person.fields,\n      thing: Thing\n    })\n    strictEqual(PersonWithTransform.identifier, \"PersonWithTransform\")\n    strictEqual(person.id, 1)\n    strictEqual(person.name, \"John\")\n    assertTrue(Option.isSome(person.thing) && person.thing.value.id === 123)\n    strictEqual(person.upperName, \"JOHN\")\n    strictEqual(typeof person.upperName, \"string\")\n\n    await Util.assertions.decoding.fail(\n      PersonWithTransform,\n      {\n        id: 2,\n        name: \"John\"\n      },\n      `(PersonWithTransform (Encoded side) <-> PersonWithTransform)\n└─ Encoded side transformation failure\n   └─ PersonWithTransform (Encoded side)\n      └─ Transformation process failure\n         └─ Expected PersonWithTransform (Encoded side), actual {\"id\":2,\"name\":\"John\"}`\n    )\n    await Util.assertions.encoding.fail(\n      PersonWithTransform,\n      new PersonWithTransform({ id: 2, name: \"John\", thing: Option.some({ id: 1 }) }),\n      `(PersonWithTransform (Encoded side) <-> PersonWithTransform)\n└─ Encoded side transformation failure\n   └─ PersonWithTransform (Encoded side)\n      └─ Transformation process failure\n         └─ Expected PersonWithTransform (Encoded side), actual {\"id\":2,\"name\":\"John\",\"thing\":{\n  \"_id\": \"Option\",\n  \"_tag\": \"Some\",\n  \"value\": {\n    \"id\": 1\n  }\n}}`\n    )\n  })\n\n  it(\"should expose a make constructor\", () => {\n    const instance = PersonWithTransform.make({ id: 2, name: \"John\", thing: Option.some({ id: 1 }) })\n    assertInstanceOf(instance, PersonWithTransform)\n    strictEqual(instance.a(), \"2a\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Class/transformOrFailFrom.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInstanceOf, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\nclass Person extends S.Class<Person>(\"Person\")({\n  id: S.Number,\n  name: S.String.pipe(S.nonEmptyString())\n}) {\n  get upperName() {\n    return this.name.toUpperCase()\n  }\n}\n\nconst Thing = S.optionalWith(S.Struct({ id: S.Number }), { exact: true, as: \"Option\" })\n\nclass PersonWithTransformFrom extends Person.transformOrFailFrom<PersonWithTransformFrom>(\"PersonWithTransformFrom\")(\n  {\n    thing: Thing\n  },\n  {\n    decode: (input, _, ast) =>\n      input.id === 2 ?\n        ParseResult.fail(new ParseResult.Type(ast, input)) :\n        ParseResult.succeed({\n          ...input,\n          thing: { id: 123 }\n        }),\n    encode: (input, _, ast) =>\n      input.id === 2 ?\n        ParseResult.fail(new ParseResult.Type(ast, input)) :\n        ParseResult.succeed(input)\n  }\n) {\n  a() {\n    return this.id + \"a\"\n  }\n}\n\ndescribe(\"\", () => {\n  it(\"transformOrFailFrom\", async () => {\n    const decode = S.decodeSync(PersonWithTransformFrom)\n    const person = decode({\n      id: 1,\n      name: \"John\"\n    })\n    deepStrictEqual(PersonWithTransformFrom.fields, {\n      ...Person.fields,\n      thing: Thing\n    })\n    strictEqual(PersonWithTransformFrom.identifier, \"PersonWithTransformFrom\")\n    strictEqual(person.id, 1)\n    strictEqual(person.name, \"John\")\n    assertTrue(Option.isSome(person.thing) && person.thing.value.id === 123)\n    strictEqual(person.upperName, \"JOHN\")\n    strictEqual(typeof person.upperName, \"string\")\n\n    await Util.assertions.decoding.fail(\n      PersonWithTransformFrom,\n      {\n        id: 2,\n        name: \"John\"\n      },\n      `(PersonWithTransformFrom (Encoded side) <-> PersonWithTransformFrom)\n└─ Encoded side transformation failure\n   └─ PersonWithTransformFrom (Encoded side)\n      └─ Transformation process failure\n         └─ Expected PersonWithTransformFrom (Encoded side), actual {\"id\":2,\"name\":\"John\"}`\n    )\n    await Util.assertions.encoding.fail(\n      PersonWithTransformFrom,\n      new PersonWithTransformFrom({ id: 2, name: \"John\", thing: Option.some({ id: 1 }) }),\n      `(PersonWithTransformFrom (Encoded side) <-> PersonWithTransformFrom)\n└─ Encoded side transformation failure\n   └─ PersonWithTransformFrom (Encoded side)\n      └─ Transformation process failure\n         └─ Expected PersonWithTransformFrom (Encoded side), actual {\"id\":2,\"name\":\"John\",\"thing\":{\"id\":1}}`\n    )\n  })\n\n  it(\"should expose a make constructor\", () => {\n    const instance = PersonWithTransformFrom.make({ id: 2, name: \"John\", thing: Option.some({ id: 1 }) })\n    assertInstanceOf(instance, PersonWithTransformFrom)\n    strictEqual(instance.a(), \"2a\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Config/Config.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFailure, assertSuccess } from \"@effect/vitest/utils\"\nimport type { Config } from \"effect\"\nimport { Cause, ConfigError, ConfigProvider, Effect, Schema } from \"effect\"\n\n/**\n * Asserts that loading a configuration with invalid data fails with the expected error.\n */\nconst assertConfigFailure = <A>(\n  config: Config.Config<A>,\n  map: ReadonlyArray<readonly [string, string]>,\n  error: ConfigError.ConfigError\n) => {\n  const configProvider = ConfigProvider.fromMap(new Map(map))\n  const result = Effect.runSync(Effect.exit(configProvider.load(config)))\n  assertFailure(result, Cause.fail(error))\n}\n\n/**\n * Asserts that loading a configuration with valid data succeeds and returns the expected value.\n */\nconst assertConfigSuccess = <A>(\n  config: Config.Config<A>,\n  map: ReadonlyArray<readonly [string, string]>,\n  a: A\n) => {\n  const configProvider = ConfigProvider.fromMap(new Map(map))\n  const result = Effect.runSync(Effect.exit(configProvider.load(config)))\n  assertSuccess(result, a)\n}\n\ndescribe(\"Config\", () => {\n  it(\"should validate the configuration schema correctly\", () => {\n    const config = Schema.Config(\"A\", Schema.NonEmptyString)\n    assertConfigSuccess(config, [[\"A\", \"a\"]], \"a\")\n    assertConfigFailure(config, [], ConfigError.MissingData([\"A\"], `Expected A to exist in the provided map`))\n    assertConfigFailure(\n      config,\n      [[\"A\", \"\"]],\n      ConfigError.InvalidData(\n        [\"A\"],\n        `NonEmptyString\n└─ Predicate refinement failure\n   └─ Expected a non empty string, actual \"\"`\n      )\n    )\n  })\n\n  it(\"should work with a template literal\", () => {\n    const config = Schema.Config(\"A\", Schema.TemplateLiteral(\"a\", Schema.Number))\n    assertConfigSuccess(config, [[\"A\", \"a1\"]], \"a1\")\n    assertConfigFailure(\n      config,\n      [[\"A\", \"ab\"]],\n      ConfigError.InvalidData(\n        [\"A\"],\n        `Expected \\`a$\\{number}\\`, actual \"ab\"`\n      )\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Data/Data.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Data from \"effect/Data\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Data\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Data(S.Struct({ a: S.String, b: S.Number })))\n    Util.assertions.testRoundtripConsistency(S.Data(S.Array(S.Number)))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Data(S.Struct({ a: S.String, b: S.Number }))\n    await Util.assertions.decoding.succeed(\n      schema,\n      { a: \"ok\", b: 0 },\n      Data.struct({ a: \"ok\", b: 0 })\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: \"ok\", b: \"0\" },\n      `({ readonly a: string; readonly b: number } <-> Data<{ readonly a: string; readonly b: number }>)\n└─ Encoded side transformation failure\n   └─ { readonly a: string; readonly b: number }\n      └─ [\"b\"]\n         └─ Expected number, actual \"0\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.Data(S.Struct({ a: S.String, b: S.Number }))\n    await Util.assertions.encoding.succeed(schema, Data.struct({ a: \"ok\", b: 0 }), { a: \"ok\", b: 0 })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Data/DataFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as Data from \"effect/Data\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DataFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.DataFromSelf(S.Struct({ a: S.String, b: S.Number })))\n    Util.assertions.testRoundtripConsistency(S.DataFromSelf(S.Array(S.Number)))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.DataFromSelf(S.Struct({ a: S.String, b: S.Number }))\n    await Util.assertions.decoding.succeed(\n      schema,\n      Data.struct({ a: \"ok\", b: 0 }),\n      Data.struct({ a: \"ok\", b: 0 })\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: \"ok\", b: 0 },\n      `Expected Data<{ readonly a: string; readonly b: number }>, actual {\"a\":\"ok\",\"b\":0}`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      Data.struct({ a: \"ok\", b: \"0\" }),\n      `Data<{ readonly a: string; readonly b: number }>\n└─ { readonly a: string; readonly b: number }\n   └─ [\"b\"]\n      └─ Expected number, actual \"0\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.DataFromSelf(S.Struct({ a: S.String, b: S.Number }))\n    await Util.assertions.encoding.succeed(\n      schema,\n      Data.struct({ a: \"ok\", b: 0 }),\n      Data.struct({ a: \"ok\", b: 0 })\n    )\n  })\n\n  it(\"is\", () => {\n    const schema = S.DataFromSelf(S.Struct({ a: S.String, b: S.Number }))\n    const is = P.is(schema)\n    assertTrue(is(Data.struct({ a: \"ok\", b: 0 })))\n    assertFalse(is({ a: \"ok\", b: 0 }))\n    assertFalse(is(Data.struct({ a: \"ok\", b: \"no\" })))\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.DataFromSelf(S.Struct({ a: S.String, b: S.Number }))\n    Util.assertions.pretty(schema, Data.struct({ a: \"ok\", b: 0 }), `Data({ \"a\": \"ok\", \"b\": 0 })`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Date/Date.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Date\", () => {\n  const schema = S.Date\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"1970-01-01T00:00:00.000Z\",\n      new Date(0)\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a\",\n      `Date\n└─ Predicate refinement failure\n   └─ Expected a valid Date, actual Invalid Date`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, new Date(0), \"1970-01-01T00:00:00.000Z\")\n    await Util.assertions.encoding.fail(\n      schema,\n      new Date(\"fail\"),\n      `Date\n└─ Predicate refinement failure\n   └─ Expected a valid Date, actual Invalid Date`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Date/DateFromNumber.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DateFromNumber\", () => {\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(S.DateFromNumber, 0, new Date(0))\n    assertTrue(S.decodeSync(S.DateFromNumber)(NaN) instanceof Date)\n    assertTrue(S.decodeSync(S.DateFromNumber)(Infinity) instanceof Date)\n    assertTrue(S.decodeSync(S.DateFromNumber)(-Infinity) instanceof Date)\n\n    await Util.assertions.decoding.fail(\n      S.DateFromNumber,\n      null,\n      `DateFromNumber\n└─ Encoded side transformation failure\n   └─ Expected number, actual null`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(S.DateFromNumber, new Date(0), 0)\n    strictEqual(S.encodeSync(S.DateFromNumber)(new Date(\"invalid\")), NaN)\n    strictEqual(S.encodeSync(S.DateFromNumber)(new Date(NaN)), NaN)\n    strictEqual(S.encodeSync(S.DateFromNumber)(new Date(Infinity)), NaN)\n    strictEqual(S.encodeSync(S.DateFromNumber)(new Date(-Infinity)), NaN)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Date/DateFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DateFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.DateFromSelf)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(S.DateFromSelf, new Date(0), new Date(0))\n    await Util.assertions.decoding.succeed(S.DateFromSelf, new Date(\"invalid\"))\n\n    await Util.assertions.decoding.fail(\n      S.DateFromSelf,\n      null,\n      `Expected DateFromSelf, actual null`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const now = new Date()\n    await Util.assertions.encoding.succeed(S.DateFromSelf, now, now)\n    const invalid = new Date(\"invalid\")\n    await Util.assertions.encoding.succeed(S.DateFromSelf, invalid, invalid)\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.DateFromSelf\n    Util.assertions.pretty(schema, new Date(0), `new Date(\"1970-01-01T00:00:00.000Z\")`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Date/betweenDate.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"betweenDate\", () => {\n  const schema = S.DateFromSelf.pipe(S.betweenDate(new Date(-1), new Date(1)))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Date(-1)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Date(0)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Date(1)\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      new Date(-2),\n      `betweenDate(1969-12-31T23:59:59.999Z, 1970-01-01T00:00:00.001Z)\n└─ Predicate refinement failure\n   └─ Expected a date between 1969-12-31T23:59:59.999Z and 1970-01-01T00:00:00.001Z, actual 1969-12-31T23:59:59.998Z`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      new Date(2),\n      `betweenDate(1969-12-31T23:59:59.999Z, 1970-01-01T00:00:00.001Z)\n└─ Predicate refinement failure\n   └─ Expected a date between 1969-12-31T23:59:59.999Z and 1970-01-01T00:00:00.001Z, actual 1970-01-01T00:00:00.002Z`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Date/greaterThanDate.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"greaterThanDate\", () => {\n  const schema = S.DateFromSelf.pipe(S.greaterThanDate(new Date(0)))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Date(1)\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      new Date(0),\n      `greaterThanDate(1970-01-01T00:00:00.000Z)\n└─ Predicate refinement failure\n   └─ Expected a date after 1970-01-01T00:00:00.000Z, actual 1970-01-01T00:00:00.000Z`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      new Date(-1),\n      `greaterThanDate(1970-01-01T00:00:00.000Z)\n└─ Predicate refinement failure\n   └─ Expected a date after 1970-01-01T00:00:00.000Z, actual 1969-12-31T23:59:59.999Z`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Date/greaterThanOrEqualToDate.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"greaterThanOrEqualToDate\", () => {\n  const schema = S.DateFromSelf.pipe(S.greaterThanOrEqualToDate(new Date(0)))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Date(1)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Date(0)\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      new Date(-1),\n      `greaterThanOrEqualToDate(1970-01-01T00:00:00.000Z)\n└─ Predicate refinement failure\n   └─ Expected a date after or equal to 1970-01-01T00:00:00.000Z, actual 1969-12-31T23:59:59.999Z`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Date/lessThanDate.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"lessThanDate\", () => {\n  const schema = S.DateFromSelf.pipe(S.lessThanDate(new Date(0)))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Date(-1)\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      new Date(0),\n      `lessThanDate(1970-01-01T00:00:00.000Z)\n└─ Predicate refinement failure\n   └─ Expected a date before 1970-01-01T00:00:00.000Z, actual 1970-01-01T00:00:00.000Z`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      new Date(1),\n      `lessThanDate(1970-01-01T00:00:00.000Z)\n└─ Predicate refinement failure\n   └─ Expected a date before 1970-01-01T00:00:00.000Z, actual 1970-01-01T00:00:00.001Z`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Date/lessThanOrEqualToDate.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"lessThanOrEqualToDate\", () => {\n  const schema = S.DateFromSelf.pipe(S.lessThanOrEqualToDate(new Date(0)))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Date(-1)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Date(0)\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      new Date(1),\n      `lessThanOrEqualToDate(1970-01-01T00:00:00.000Z)\n└─ Predicate refinement failure\n   └─ Expected a date before or equal to 1970-01-01T00:00:00.000Z, actual 1970-01-01T00:00:00.001Z`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/DateTimeUtc.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { DateTime } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DateTimeUtc\", () => {\n  const schema = S.DateTimeUtc\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"1970-01-01T00:00:00.000Z\",\n      DateTime.unsafeMake(0)\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a\",\n      `DateTimeUtc\n└─ Transformation process failure\n   └─ Unable to decode \"a\" into a DateTime.Utc`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, DateTime.unsafeMake(0), \"1970-01-01T00:00:00.000Z\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/DateTimeUtcFromDate.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DateTimeUtcFromDate\", () => {\n  const schema = S.DateTimeUtcFromDate\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, new Date(0), DateTime.unsafeMake(0))\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Date(\"2024-12-06T00:00:00Z\"),\n      DateTime.unsafeMake({ day: 6, month: 12, year: 2024, hour: 0, minute: 0, second: 0, millisecond: 0 })\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `DateTimeUtcFromDate\n└─ Encoded side transformation failure\n   └─ Expected a Date to be decoded into a DateTime.Utc, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      new Date(NaN),\n      `DateTimeUtcFromDate\n└─ Transformation process failure\n   └─ Unable to decode Invalid Date into a DateTime.Utc`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, DateTime.unsafeMake(0), new Date(0))\n    deepStrictEqual(\n      S.encodeSync(schema)(\n        DateTime.unsafeMake({ day: 6, month: 12, year: 2024, hour: 0, minute: 0, second: 0, millisecond: 0 })\n      ),\n      new Date(\"2024-12-06T00:00:00Z\")\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/DateTimeUtcFromNumber.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DateTimeUtcFromNumber\", () => {\n  const schema = S.DateTimeUtcFromNumber\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/DateTimeUtcFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DateTimeUtcFromSelf\", () => {\n  const schema = S.DateTimeUtcFromSelf\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/DateTimeZoned.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { DateTime } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DateTimeZoned\", () => {\n  const schema = S.DateTimeZoned\n  const dt = DateTime.unsafeMakeZoned(0, { timeZone: \"Europe/London\" })\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, \"1970-01-01T01:00:00.000+01:00[Europe/London]\", dt)\n    await Util.assertions.decoding.fail(\n      schema,\n      \"1970-01-01T00:00:00.000Z\",\n      `DateTimeZoned\n└─ Transformation process failure\n   └─ Unable to decode \"1970-01-01T00:00:00.000Z\" into a DateTime.Zoned`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a\",\n      `DateTimeZoned\n└─ Transformation process failure\n   └─ Unable to decode \"a\" into a DateTime.Zoned`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, dt, \"1970-01-01T01:00:00.000+01:00[Europe/London]\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/DateTimeZonedFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DateTimeZonedFromSelf\", () => {\n  const schema = S.DateTimeZonedFromSelf\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/TimeZone.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"TimeZone\", () => {\n  const schema = S.TimeZone\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/TimeZoneFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"TimeZoneFromSelf\", () => {\n  const schema = S.TimeZoneFromSelf\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/TimeZoneNamed.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"TimeZoneNamed\", () => {\n  const schema = S.TimeZoneNamed\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/TimeZoneNamedFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"TimeZoneNamedFromSelf\", () => {\n  const schema = S.TimeZoneNamedFromSelf\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/TimeZoneOffset.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"TimeZoneOffset\", () => {\n  const schema = S.TimeZoneOffset\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DateTime/TimeZoneOffsetFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"TimeZoneOffsetFromSelf\", () => {\n  const schema = S.TimeZoneOffsetFromSelf\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/DecodingFallbackAnnotation.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Effect, Either } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"DecodingFallbackAnnotation\", () => {\n  it(\"using Either\", async () => {\n    const schema = S.String.annotations({ decodingFallback: () => Either.right(\"<fallback value>\") })\n    await Util.assertions.decoding.succeed(\n      schema,\n      null,\n      \"<fallback value>\"\n    )\n  })\n\n  it(\"using a sync Effect\", async () => {\n    const log: Array<unknown> = []\n    const schema = S.String.annotations({\n      decodingFallback: (issue) =>\n        Effect.gen(function*() {\n          log.push(issue.actual)\n          return yield* Effect.succeed(\"<fallback value>\")\n        })\n    })\n    await Util.assertions.decoding.succeed(\n      schema,\n      null,\n      \"<fallback value>\"\n    )\n    deepStrictEqual(log, [null])\n  })\n\n  it(\"using an async Effect\", async () => {\n    const log: Array<unknown> = []\n    const schema = S.String.annotations({\n      decodingFallback: (issue) =>\n        Effect.gen(function*() {\n          log.push(issue.actual)\n          yield* Effect.sleep(10)\n          return yield* Effect.succeed(\"<fallback value>\")\n        })\n    })\n    await Util.assertions.decoding.succeed(\n      schema,\n      null,\n      \"<fallback value>\"\n    )\n    deepStrictEqual(log, [null])\n    Util.assertions.parseError(\n      () => S.decodeUnknownSync(schema)(null),\n      `string\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n\n  it(\"nested Struct\", async () => {\n    const schema = S.Struct({\n      name: S.String.annotations({ decodingFallback: () => Either.right(\"John\") }),\n      age: S.Number.annotations({ decodingFallback: () => Either.right(18) })\n    })\n    await Util.assertions.decoding.succeed(\n      schema,\n      {},\n      { name: \"John\", age: 18 }\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Defect/Defect.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInstanceOf, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Defect\", () => {\n  describe(\"decoding\", () => {\n    it(\"a string\", async () => {\n      await Util.assertions.decoding.succeed(\n        S.Defect,\n        \"error\",\n        \"error\"\n      )\n    })\n\n    it(\"an object with a message\", () => {\n      const err = S.decodeUnknownSync(S.Defect)({ message: \"message\" })\n      deepStrictEqual(err, new Error(\"message\", { cause: { message: \"message\" } }))\n    })\n\n    it(\"a null object with a message\", async () => {\n      const defect = Object.create(null)\n      defect.message = \"message\"\n\n      const err = S.decodeUnknownSync(S.Defect)(defect)\n      deepStrictEqual(err, new Error(\"message\", { cause: defect }))\n    })\n\n    it(\"an object with a message and a name\", () => {\n      const err = S.decodeUnknownSync(S.Defect)({ message: \"message\", name: \"name\" })\n      assertInstanceOf(err, Error)\n      strictEqual(err.message, \"message\")\n      strictEqual(err.name, \"name\")\n    })\n\n    it(\"an object with a message and a stack\", () => {\n      const err = S.decodeUnknownSync(S.Defect)({ message: \"message\", stack: \"stack\" })\n      assertInstanceOf(err, Error)\n      strictEqual(err.message, \"message\")\n      strictEqual(err.stack, \"stack\")\n    })\n\n    it(\"a null object without a message\", async () => {\n      const defect = Object.create(null)\n      defect.a = 1\n\n      await Util.assertions.decoding.succeed(\n        S.Defect,\n        defect,\n        \"{\\\"a\\\":1}\"\n      )\n    })\n  })\n\n  describe(\"encoding\", () => {\n    it(\"a string\", async () => {\n      await Util.assertions.encoding.succeed(\n        S.Defect,\n        \"error\",\n        \"error\"\n      )\n    })\n\n    it(\"an object\", async () => {\n      await Util.assertions.encoding.succeed(\n        S.Defect,\n        { a: 1 },\n        \"{\\\"a\\\":1}\"\n      )\n    })\n\n    it(\"a null object\", async () => {\n      const defect = Object.create(null)\n      defect.a = 1\n\n      await Util.assertions.encoding.succeed(\n        S.Defect,\n        defect,\n        \"{\\\"a\\\":1}\"\n      )\n    })\n\n    it(\"an Error\", async () => {\n      await Util.assertions.encoding.succeed(\n        S.Defect,\n        new Error(\"message\"),\n        {\n          \"message\": \"message\",\n          \"name\": \"Error\"\n        }\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Duration/Duration.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Duration } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Duration\", () => {\n  const schema = S.Duration\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, { _tag: \"Infinity\" }, Duration.infinity)\n    await Util.assertions.decoding.succeed(schema, { _tag: \"Millis\", millis: 12345 }, Duration.millis(12345))\n    await Util.assertions.decoding.succeed(schema, { _tag: \"Nanos\", nanos: \"54321\" }, Duration.nanos(54321n))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Duration\n└─ Encoded side transformation failure\n   └─ DurationValue | HRTime\n      ├─ Expected DurationValue, actual null\n      └─ HRTime\n         ├─ Expected InfiniteHRTime, actual null\n         └─ Expected FiniteHRTime, actual null`\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      {},\n      `Duration\n└─ Encoded side transformation failure\n   └─ DurationValue | HRTime\n      ├─ DurationValue\n      │  └─ { readonly _tag: \"Millis\" | \"Nanos\" | \"Infinity\" }\n      │     └─ [\"_tag\"]\n      │        └─ is missing\n      └─ HRTime\n         ├─ InfiniteHRTime\n         │  └─ [\"0\"]\n         │     └─ is missing\n         └─ Expected FiniteHRTime, actual {}`\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      { _tag: \"Millis\", millis: -1 },\n      `Duration\n└─ Encoded side transformation failure\n   └─ DurationValue | HRTime\n      ├─ DurationValue\n      │  └─ { readonly _tag: \"Millis\"; readonly millis: NonNegativeInt }\n      │     └─ [\"millis\"]\n      │        └─ NonNegativeInt\n      │           └─ From side refinement failure\n      │              └─ NonNegative\n      │                 └─ Predicate refinement failure\n      │                    └─ Expected a non-negative number, actual -1\n      └─ HRTime\n         ├─ InfiniteHRTime\n         │  └─ [\"0\"]\n         │     └─ is missing\n         └─ Expected FiniteHRTime, actual {\"_tag\":\"Millis\",\"millis\":-1}`\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      { _tag: \"Nanos\", nanos: null },\n      `Duration\n└─ Encoded side transformation failure\n   └─ DurationValue | HRTime\n      ├─ DurationValue\n      │  └─ { readonly _tag: \"Nanos\"; readonly nanos: BigInt }\n      │     └─ [\"nanos\"]\n      │        └─ BigInt\n      │           └─ Encoded side transformation failure\n      │              └─ Expected string, actual null\n      └─ HRTime\n         ├─ InfiniteHRTime\n         │  └─ [\"0\"]\n         │     └─ is missing\n         └─ Expected FiniteHRTime, actual {\"_tag\":\"Nanos\",\"nanos\":null}`\n    )\n  })\n\n  it(\"HRTime backward compatible encoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, [-1, 0], Duration.infinity)\n    await Util.assertions.decoding.succeed(schema, [555, 123456789], Duration.nanos(555123456789n))\n    await Util.assertions.decoding.fail(\n      schema,\n      [-500, 0],\n      `Duration\n└─ Encoded side transformation failure\n   └─ DurationValue | HRTime\n      ├─ DurationValue\n      │  └─ { readonly _tag: \"Millis\" | \"Nanos\" | \"Infinity\" }\n      │     └─ [\"_tag\"]\n      │        └─ is missing\n      └─ HRTime\n         ├─ InfiniteHRTime\n         │  └─ [\"0\"]\n         │     └─ Expected -1, actual -500\n         └─ FiniteHRTime\n            └─ [0]\n               └─ NonNegativeInt\n                  └─ From side refinement failure\n                     └─ NonNegative\n                        └─ Predicate refinement failure\n                           └─ Expected a non-negative number, actual -500`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      [0, -123],\n      `Duration\n└─ Encoded side transformation failure\n   └─ DurationValue | HRTime\n      ├─ DurationValue\n      │  └─ { readonly _tag: \"Millis\" | \"Nanos\" | \"Infinity\" }\n      │     └─ [\"_tag\"]\n      │        └─ is missing\n      └─ HRTime\n         ├─ InfiniteHRTime\n         │  └─ [\"0\"]\n         │     └─ Expected -1, actual 0\n         └─ FiniteHRTime\n            └─ [1]\n               └─ NonNegativeInt\n                  └─ From side refinement failure\n                     └─ NonNegative\n                        └─ Predicate refinement failure\n                           └─ Expected a non-negative number, actual -123`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      123,\n      `Duration\n└─ Encoded side transformation failure\n   └─ DurationValue | HRTime\n      ├─ Expected DurationValue, actual 123\n      └─ HRTime\n         ├─ Expected InfiniteHRTime, actual 123\n         └─ Expected FiniteHRTime, actual 123`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      123n,\n      `Duration\n└─ Encoded side transformation failure\n   └─ DurationValue | HRTime\n      ├─ Expected DurationValue, actual 123n\n      └─ HRTime\n         ├─ Expected InfiniteHRTime, actual 123n\n         └─ Expected FiniteHRTime, actual 123n`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, Duration.infinity, { _tag: \"Infinity\" })\n    await Util.assertions.encoding.succeed(schema, Duration.seconds(5), { _tag: \"Millis\", millis: 5000 })\n    await Util.assertions.encoding.succeed(schema, Duration.millis(123456789), { _tag: \"Millis\", millis: 123456789 })\n    await Util.assertions.encoding.succeed(schema, Duration.nanos(555123456789n), {\n      _tag: \"Nanos\",\n      nanos: \"555123456789\"\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Duration/DurationFromMillis.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Duration } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DurationFromMillis\", () => {\n  const schema = S.DurationFromMillis\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, Infinity, Duration.infinity)\n    await Util.assertions.decoding.succeed(schema, 0, Duration.millis(0))\n    await Util.assertions.decoding.succeed(schema, 1000, Duration.seconds(1))\n    await Util.assertions.decoding.succeed(schema, 60 * 1000, Duration.minutes(1))\n    await Util.assertions.decoding.succeed(schema, 0.1, Duration.millis(0.1))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      -1,\n      `DurationFromMillis\n└─ Encoded side transformation failure\n   └─ nonNegative\n      └─ Predicate refinement failure\n         └─ Expected a non-negative number to be decoded into a Duration, actual -1`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      NaN,\n      `DurationFromMillis\n└─ Encoded side transformation failure\n   └─ nonNegative\n      └─ Predicate refinement failure\n         └─ Expected a non-negative number to be decoded into a Duration, actual NaN`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, Duration.infinity, Infinity)\n    await Util.assertions.encoding.succeed(schema, Duration.seconds(5), 5000)\n    await Util.assertions.encoding.succeed(schema, Duration.millis(5000), 5000)\n    await Util.assertions.encoding.succeed(schema, Duration.millis(0.1), 0.1)\n    await Util.assertions.encoding.succeed(schema, Duration.nanos(5000n), 0.005)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Duration/DurationFromNanos.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Duration } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DurationFromNanos\", () => {\n  const schema = S.DurationFromNanos\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0n, Duration.nanos(0n))\n    await Util.assertions.decoding.succeed(schema, 1000n, Duration.nanos(1000n))\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, Duration.millis(5), 5000000n)\n    await Util.assertions.encoding.succeed(schema, Duration.nanos(5000n), 5000n)\n    await Util.assertions.encoding.fail(\n      schema,\n      Duration.infinity,\n      `DurationFromNanos\n└─ Type side transformation failure\n   └─ a finite duration\n      └─ Predicate refinement failure\n         └─ Expected a finite duration, actual Duration(Infinity)`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Duration/DurationFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Duration } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"DurationFromSelf\", () => {\n  const schema = S.DurationFromSelf\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, Duration.nanos(123n), Duration.nanos(123n))\n    await Util.assertions.decoding.succeed(schema, Duration.millis(0), Duration.millis(0))\n    await Util.assertions.decoding.fail(\n      schema,\n      123,\n      `Expected DurationFromSelf, actual 123`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      123n,\n      `Expected DurationFromSelf, actual 123n`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, Duration.seconds(5), Duration.seconds(5))\n  })\n\n  it(\"pretty\", () => {\n    Util.assertions.pretty(schema, Duration.millis(500), \"Duration(500ms)\")\n    Util.assertions.pretty(schema, Duration.seconds(30), \"Duration(30s)\")\n    Util.assertions.pretty(schema, Duration.minutes(5.25), \"Duration(5m 15s)\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Duration/betweenDuration.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Duration } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"betweenDuration\", () => {\n  const schema = S.DurationFromSelf.pipe(\n    S.betweenDuration(\"5 seconds\", \"10 seconds\")\n  ).annotations({ title: \"[5 seconds, 10 seconds] interval\" })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      Duration.decode(\"4 seconds\"),\n      `[5 seconds, 10 seconds] interval\n└─ Predicate refinement failure\n   └─ Expected a Duration between Duration(5s) and Duration(10s), actual Duration(4s)`\n    )\n\n    await Util.assertions.decoding.succeed(\n      schema,\n      Duration.decode(\"7 seconds\"),\n      Duration.decode(\"7 seconds\")\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      Duration.decode(\"11 seconds\"),\n      `[5 seconds, 10 seconds] interval\n└─ Predicate refinement failure\n   └─ Expected a Duration between Duration(5s) and Duration(10s), actual Duration(11s)`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      Duration.decode(\"7 seconds\"),\n      Duration.decode(\"7 seconds\")\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Duration/clampDuration.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Duration } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"clampDuration\", () => {\n  it(\"decoding\", async () => {\n    const schema = S.DurationFromSelf.pipe(S.clampDuration(\"5 seconds\", \"10 seconds\"))\n\n    await Util.assertions.decoding.succeed(\n      schema,\n      Duration.decode(\"1 seconds\"),\n      Duration.decode(\"5 seconds\")\n    )\n\n    await Util.assertions.decoding.succeed(\n      schema,\n      Duration.decode(\"6 seconds\"),\n      Duration.decode(\"6 seconds\")\n    )\n\n    await Util.assertions.decoding.succeed(\n      schema,\n      Duration.decode(\"11 seconds\"),\n      Duration.decode(\"10 seconds\")\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Duration/greaterThanDuration.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Duration } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"greaterThanDuration\", () => {\n  const schema = S.DurationFromSelf.pipe(S.greaterThanDuration(\"5 seconds\"))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      Duration.decode(\"6 seconds\"),\n      Duration.decode(\"6 seconds\")\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      Duration.decode(\"5 seconds\"),\n      `greaterThanDuration(5 seconds)\n└─ Predicate refinement failure\n   └─ Expected a Duration greater than Duration(5s), actual Duration(5s)`\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      Duration.decode(\"4 seconds\"),\n      `greaterThanDuration(5 seconds)\n└─ Predicate refinement failure\n   └─ Expected a Duration greater than Duration(5s), actual Duration(4s)`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      Duration.decode(\"6 seconds\"),\n      Duration.decode(\"6 seconds\")\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Duration/greaterThanOrEqualToDuration.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Duration } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"greaterThanOrEqualToDuration\", () => {\n  const schema = S.DurationFromSelf.pipe(S.greaterThanOrEqualToDuration(\"5 seconds\"))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      Duration.decode(\"6 seconds\"),\n      Duration.decode(\"6 seconds\")\n    )\n\n    await Util.assertions.decoding.succeed(\n      schema,\n      Duration.decode(\"5 seconds\"),\n      Duration.decode(\"5 seconds\")\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      Duration.decode(\"4 seconds\"),\n      `greaterThanOrEqualToDuration(5 seconds)\n└─ Predicate refinement failure\n   └─ Expected a Duration greater than or equal to Duration(5s), actual Duration(4s)`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      Duration.decode(\"5 seconds\"),\n      Duration.decode(\"5 seconds\")\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Duration/lessThanDuration.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Duration } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"lessThanDuration\", () => {\n  const schema = S.DurationFromSelf.pipe(S.lessThanDuration(\"5 seconds\"))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      Duration.decode(\"4 seconds\"),\n      Duration.decode(\"4 seconds\")\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      Duration.decode(\"5 seconds\"),\n      `lessThanDuration(5 seconds)\n└─ Predicate refinement failure\n   └─ Expected a Duration less than Duration(5s), actual Duration(5s)`\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      Duration.decode(\"6 seconds\"),\n      `lessThanDuration(5 seconds)\n└─ Predicate refinement failure\n   └─ Expected a Duration less than Duration(5s), actual Duration(6s)`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      Duration.decode(\"4 seconds\"),\n      Duration.decode(\"4 seconds\")\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Duration/lessThanOrEqualToDuration.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Duration } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"lessThanOrEqualToDuration\", () => {\n  const schema = S.DurationFromSelf.pipe(S.lessThanOrEqualToDuration(\"5 seconds\"))\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      Duration.decode(\"4 seconds\"),\n      Duration.decode(\"4 seconds\")\n    )\n\n    await Util.assertions.decoding.succeed(\n      schema,\n      Duration.decode(\"5 seconds\"),\n      Duration.decode(\"5 seconds\")\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      Duration.decode(\"6 seconds\"),\n      `lessThanOrEqualToDuration(5 seconds)\n└─ Predicate refinement failure\n   └─ Expected a Duration less than or equal to Duration(5s), actual Duration(6s)`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      Duration.decode(\"5 seconds\"),\n      Duration.decode(\"5 seconds\")\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Either/Either.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as E from \"effect/Either\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Either\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Either({ left: S.String, right: S.Number }))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Either({ left: S.String, right: S.NumberFromString })\n    await Util.assertions.decoding.succeed(\n      schema,\n      JSON.parse(JSON.stringify(E.left(\"a\"))),\n      E.left(\"a\")\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      JSON.parse(JSON.stringify(E.right(\"1\"))),\n      E.right(1)\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.Either({ left: S.String, right: S.NumberFromString })\n    await Util.assertions.encoding.succeed(schema, E.left(\"a\"), { _tag: \"Left\", left: \"a\" })\n    await Util.assertions.encoding.succeed(schema, E.right(1), { _tag: \"Right\", right: \"1\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Either/EitherFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as E from \"effect/Either\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"EitherFromSelf\", () => {\n  it(\"arbitrary\", () => {\n    Util.assertions.arbitrary.validateGeneratedValues(S.EitherFromSelf({ left: S.String, right: S.Number }))\n  })\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.EitherFromSelf({ left: S.String, right: S.Number }))\n  })\n\n  it(\"is\", () => {\n    const schema = S.EitherFromSelf({ left: S.String, right: S.Number })\n    const is = P.is(schema)\n    assertTrue(is(E.left(\"a\")))\n    assertTrue(is(E.right(1)))\n    assertFalse(is(null))\n    assertFalse(is(E.right(\"a\")))\n    assertFalse(is(E.left(1)))\n\n    assertFalse(is({ _tag: \"Right\", right: 1 }))\n    assertFalse(is({ _tag: \"Left\", left: \"a\" }))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.EitherFromSelf({ left: S.NumberFromString, right: S.BooleanFromString })\n    await Util.assertions.decoding.succeed(schema, E.left(\"1\"), E.left(1))\n    await Util.assertions.decoding.succeed(schema, E.right(\"true\"), E.right(true))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected Either<BooleanFromString, NumberFromString>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      E.right(\"\"),\n      `Either<BooleanFromString, NumberFromString>\n└─ BooleanFromString\n   └─ Encoded side transformation failure\n      └─ a string to be decoded into a boolean\n         ├─ Expected \"true\", actual \"\"\n         └─ Expected \"false\", actual \"\"`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      E.left(\"a\"),\n      `Either<BooleanFromString, NumberFromString>\n└─ NumberFromString\n   └─ Transformation process failure\n      └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.EitherFromSelf({ left: S.String, right: S.Number })\n    Util.assertions.pretty(schema, E.left(\"a\"), `left(\"a\")`)\n    Util.assertions.pretty(schema, E.right(1), \"right(1)\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Either/EitherFromUnion.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue } from \"@effect/vitest/utils\"\nimport * as E from \"effect/Either\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"EitherFromUnion\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.EitherFromUnion({ left: S.String, right: S.Number }))\n  })\n\n  it(\"decoding success\", async () => {\n    const schema = S.EitherFromUnion({ left: S.DateFromString, right: S.NumberFromString })\n    await Util.assertions.decoding.succeed(schema, \"1970-01-01T00:00:00.000Z\", E.left(new Date(0)))\n    await Util.assertions.decoding.succeed(schema, \"1\", E.right(1))\n\n    assertTrue(E.isEither(S.decodeSync(schema)(\"1970-01-01T00:00:00.000Z\")))\n    assertTrue(E.isEither(S.decodeSync(schema)(\"1\")))\n  })\n\n  it(\"decoding error (Encoded side transformation failure)\", async () => {\n    const schema = S.EitherFromUnion({ left: S.Number, right: S.String })\n    await Util.assertions.decoding.fail(\n      schema,\n      undefined,\n      `((string <-> RightEncoded<string>) | (number <-> LeftEncoded<number>) <-> Either<string, number>)\n└─ Encoded side transformation failure\n   └─ (string <-> RightEncoded<string>) | (number <-> LeftEncoded<number>)\n      ├─ (string <-> RightEncoded<string>)\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual undefined\n      └─ (number <-> LeftEncoded<number>)\n         └─ Encoded side transformation failure\n            └─ Expected number, actual undefined`\n    )\n  })\n\n  it(\"decoding error (Transformation process failure)\", async () => {\n    const schema = S.EitherFromUnion({ left: S.Number, right: S.compose(S.Boolean, S.String, { strict: false }) })\n    await Util.assertions.decoding.fail(\n      schema,\n      true,\n      `(((boolean <-> string) <-> RightEncoded<string>) | (number <-> LeftEncoded<number>) <-> Either<string, number>)\n└─ Encoded side transformation failure\n   └─ ((boolean <-> string) <-> RightEncoded<string>) | (number <-> LeftEncoded<number>)\n      ├─ ((boolean <-> string) <-> RightEncoded<string>)\n      │  └─ Encoded side transformation failure\n      │     └─ (boolean <-> string)\n      │        └─ Type side transformation failure\n      │           └─ Expected string, actual true\n      └─ (number <-> LeftEncoded<number>)\n         └─ Encoded side transformation failure\n            └─ Expected number, actual true`\n    )\n  })\n\n  it(\"decoding prefer right\", async () => {\n    const schema = S.EitherFromUnion({ left: S.NumberFromString, right: S.NumberFromString })\n    await Util.assertions.decoding.succeed(schema, \"1\", E.right(1))\n  })\n\n  it(\"encoding success\", async () => {\n    const schema = S.EitherFromUnion({ left: S.DateFromString, right: S.NumberFromString })\n    await Util.assertions.encoding.succeed(schema, E.left(new Date(0)), \"1970-01-01T00:00:00.000Z\")\n    await Util.assertions.encoding.succeed(schema, E.right(1), \"1\")\n  })\n\n  it(\"encoding error\", async () => {\n    const schema = S.EitherFromUnion({\n      left: S.compose(S.DateFromString, S.Unknown, { strict: false }),\n      right: S.compose(S.NumberFromString, S.Unknown, { strict: false })\n    })\n    await Util.assertions.encoding.fail(\n      schema,\n      E.left(undefined),\n      `(((NumberFromString <-> unknown) <-> RightEncoded<unknown>) | ((DateFromString <-> unknown) <-> LeftEncoded<unknown>) <-> Either<unknown, unknown>)\n└─ Encoded side transformation failure\n   └─ ((NumberFromString <-> unknown) <-> RightEncoded<unknown>) | ((DateFromString <-> unknown) <-> LeftEncoded<unknown>)\n      └─ ((DateFromString <-> unknown) <-> LeftEncoded<unknown>)\n         └─ Encoded side transformation failure\n            └─ (DateFromString <-> unknown)\n               └─ Encoded side transformation failure\n                  └─ DateFromString\n                     └─ Type side transformation failure\n                        └─ Expected DateFromSelf, actual undefined`\n    )\n    await Util.assertions.encoding.fail(\n      schema,\n      E.right(undefined),\n      `(((NumberFromString <-> unknown) <-> RightEncoded<unknown>) | ((DateFromString <-> unknown) <-> LeftEncoded<unknown>) <-> Either<unknown, unknown>)\n└─ Encoded side transformation failure\n   └─ ((NumberFromString <-> unknown) <-> RightEncoded<unknown>) | ((DateFromString <-> unknown) <-> LeftEncoded<unknown>)\n      └─ ((NumberFromString <-> unknown) <-> RightEncoded<unknown>)\n         └─ Encoded side transformation failure\n            └─ (NumberFromString <-> unknown)\n               └─ Encoded side transformation failure\n                  └─ NumberFromString\n                     └─ Type side transformation failure\n                        └─ Expected number, actual undefined`\n    )\n  })\n\n  it(\"encoding don't overlap\", async () => {\n    const schema = S.EitherFromUnion({\n      left: S.compose(S.DateFromString, S.Unknown, { strict: false }),\n      right: S.compose(S.NumberFromString, S.Unknown, { strict: false })\n    })\n    await Util.assertions.encoding.fail(\n      schema,\n      E.left(1),\n      `(((NumberFromString <-> unknown) <-> RightEncoded<unknown>) | ((DateFromString <-> unknown) <-> LeftEncoded<unknown>) <-> Either<unknown, unknown>)\n└─ Encoded side transformation failure\n   └─ ((NumberFromString <-> unknown) <-> RightEncoded<unknown>) | ((DateFromString <-> unknown) <-> LeftEncoded<unknown>)\n      └─ ((DateFromString <-> unknown) <-> LeftEncoded<unknown>)\n         └─ Encoded side transformation failure\n            └─ (DateFromString <-> unknown)\n               └─ Encoded side transformation failure\n                  └─ DateFromString\n                     └─ Type side transformation failure\n                        └─ Expected DateFromSelf, actual 1`\n    )\n    await Util.assertions.encoding.fail(\n      schema,\n      E.right(new Date(0)),\n      `(((NumberFromString <-> unknown) <-> RightEncoded<unknown>) | ((DateFromString <-> unknown) <-> LeftEncoded<unknown>) <-> Either<unknown, unknown>)\n└─ Encoded side transformation failure\n   └─ ((NumberFromString <-> unknown) <-> RightEncoded<unknown>) | ((DateFromString <-> unknown) <-> LeftEncoded<unknown>)\n      └─ ((NumberFromString <-> unknown) <-> RightEncoded<unknown>)\n         └─ Encoded side transformation failure\n            └─ (NumberFromString <-> unknown)\n               └─ Encoded side transformation failure\n                  └─ NumberFromString\n                     └─ Type side transformation failure\n                        └─ Expected number, actual ${new Date(0).toISOString()}`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Enums/Enums.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Enums\", () => {\n  it(\"enums should be exposed\", () => {\n    enum Fruits {\n      Apple,\n      Banana\n    }\n    const schema = S.Enums(Fruits).annotations({ identifier: \"Fruits\" })\n    strictEqual(schema.enums.Apple, 0)\n    strictEqual(schema.enums.Banana, 1)\n  })\n\n  describe(\"Numeric enums\", () => {\n    enum Fruits {\n      Apple,\n      Banana\n    }\n    const schema = S.Enums(Fruits)\n\n    it(\"decoding\", async () => {\n      await Util.assertions.decoding.succeed(schema, Fruits.Apple)\n      await Util.assertions.decoding.succeed(schema, Fruits.Banana)\n      await Util.assertions.decoding.succeed(schema, 0)\n      await Util.assertions.decoding.succeed(schema, 1)\n\n      await Util.assertions.decoding.fail(\n        schema,\n        3,\n        `Expected <enum 2 value(s): 0 | 1>, actual 3`\n      )\n    })\n\n    it(\"encoding\", async () => {\n      await Util.assertions.encoding.succeed(schema, Fruits.Apple, 0)\n      await Util.assertions.encoding.succeed(schema, Fruits.Banana, 1)\n    })\n  })\n\n  describe(\"String enums\", () => {\n    enum Fruits {\n      Apple = \"apple\",\n      Banana = \"banana\",\n      Cantaloupe = 0\n    }\n    const schema = S.Enums(Fruits)\n\n    it(\"decoding\", async () => {\n      await Util.assertions.decoding.succeed(schema, Fruits.Apple)\n      await Util.assertions.decoding.succeed(schema, Fruits.Cantaloupe)\n      await Util.assertions.decoding.succeed(schema, \"apple\")\n      await Util.assertions.decoding.succeed(schema, \"banana\")\n      await Util.assertions.decoding.succeed(schema, 0)\n\n      await Util.assertions.decoding.fail(\n        schema,\n        \"Cantaloupe\",\n        `Expected <enum 3 value(s): \"apple\" | \"banana\" | 0>, actual \"Cantaloupe\"`\n      )\n    })\n\n    it(\"encoding\", async () => {\n      await Util.assertions.encoding.succeed(schema, Fruits.Apple)\n      await Util.assertions.encoding.succeed(schema, Fruits.Banana)\n      await Util.assertions.encoding.succeed(schema, Fruits.Cantaloupe)\n    })\n  })\n\n  describe(\"Const enums\", () => {\n    const Fruits = {\n      Apple: \"apple\",\n      Banana: \"banana\",\n      Cantaloupe: 3\n    } as const\n    const schema = S.Enums(Fruits)\n\n    it(\"decoding\", async () => {\n      await Util.assertions.decoding.succeed(schema, \"apple\")\n      await Util.assertions.decoding.succeed(schema, \"banana\")\n      await Util.assertions.decoding.succeed(schema, 3)\n\n      await Util.assertions.decoding.fail(\n        schema,\n        \"Cantaloupe\",\n        `Expected <enum 3 value(s): \"apple\" | \"banana\" | 3>, actual \"Cantaloupe\"`\n      )\n    })\n\n    it(\"encoding\", async () => {\n      await Util.assertions.encoding.succeed(schema, Fruits.Apple, \"apple\")\n      await Util.assertions.encoding.succeed(schema, Fruits.Banana, \"banana\")\n      await Util.assertions.encoding.succeed(schema, Fruits.Cantaloupe, 3)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Exit/Exit.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Cause, Exit, Schema as S } from \"effect\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Exit\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Exit({ failure: S.String, success: S.Number, defect: S.Defect }))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Exit({ failure: S.String, success: S.Number, defect: S.Defect })\n    await Util.assertions.decoding.succeed(\n      schema,\n      { _tag: \"Failure\", cause: { _tag: \"Fail\", error: \"error\" } },\n      Exit.fail(\"error\")\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      { _tag: \"Success\", value: 123 },\n      Exit.succeed(123)\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { _tag: \"Success\", value: null },\n      `(ExitEncoded<number, string, Defect> <-> Exit<number, string>)\n└─ Encoded side transformation failure\n   └─ ExitEncoded<number, string, Defect>\n      └─ { readonly _tag: \"Success\"; readonly value: number }\n         └─ [\"value\"]\n            └─ Expected number, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { _tag: \"Failure\", cause: null },\n      `(ExitEncoded<number, string, Defect> <-> Exit<number, string>)\n└─ Encoded side transformation failure\n   └─ ExitEncoded<number, string, Defect>\n      └─ { readonly _tag: \"Failure\"; readonly cause: CauseEncoded<string> }\n         └─ [\"cause\"]\n            └─ Expected CauseEncoded<string>, actual null`\n    )\n  })\n\n  describe(\"encoding\", async () => {\n    it(\"should raise an error when a non-encodable Cause is passed\", async () => {\n      const schema = S.Exit({ failure: S.String, success: S.Number, defect: Util.Defect })\n      await Util.assertions.encoding.fail(\n        schema,\n        Exit.failCause(Cause.die(null)),\n        `(ExitEncoded<number, string, (string <-> object)> <-> Exit<number, string>)\n└─ Type side transformation failure\n   └─ Exit<number, string>\n      └─ Cause<string>\n         └─ CauseEncoded<string>\n            └─ { readonly _tag: \"Die\"; readonly defect: object }\n               └─ [\"defect\"]\n                  └─ Expected object, actual null`\n      )\n    })\n  })\n\n  it(\"using the built-in Defect schema as defect argument\", async () => {\n    const schema = S.Exit({ failure: S.String, success: S.Number, defect: S.Defect })\n    await Util.assertions.encoding.succeed(schema, Exit.fail(\"error\"), {\n      _tag: \"Failure\",\n      cause: { _tag: \"Fail\", error: \"error\" }\n    })\n    await Util.assertions.encoding.succeed(schema, Exit.succeed(123), { _tag: \"Success\", value: 123 })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Exit/ExitFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Exit from \"effect/Exit\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"ExitFromSelf\", () => {\n  it(\"arbitrary\", () => {\n    Util.assertions.arbitrary.validateGeneratedValues(\n      S.ExitFromSelf({ failure: S.String, success: S.Number, defect: S.Unknown })\n    )\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.ExitFromSelf({ failure: S.NumberFromString, success: S.BooleanFromString, defect: S.Unknown })\n    await Util.assertions.decoding.succeed(schema, Exit.fail(\"1\"), Exit.fail(1))\n    await Util.assertions.decoding.succeed(schema, Exit.succeed(\"true\"), Exit.succeed(true))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected Exit<BooleanFromString, NumberFromString>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      Exit.succeed(\"\"),\n      `Exit<BooleanFromString, NumberFromString>\n└─ BooleanFromString\n   └─ Encoded side transformation failure\n      └─ a string to be decoded into a boolean\n         ├─ Expected \"true\", actual \"\"\n         └─ Expected \"false\", actual \"\"`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      Exit.fail(\"a\"),\n      `Exit<BooleanFromString, NumberFromString>\n└─ Cause<NumberFromString>\n   └─ CauseEncoded<NumberFromString>\n      └─ { readonly _tag: \"Fail\"; readonly error: NumberFromString }\n         └─ [\"error\"]\n            └─ NumberFromString\n               └─ Transformation process failure\n                  └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  describe(\"encoding\", async () => {\n    it(\"should handle a defect schema\", async () => {\n      const schema = S.ExitFromSelf({\n        success: S.Number,\n        failure: S.String,\n        defect: Util.Defect\n      })\n      await Util.assertions.encoding.succeed(schema, Exit.die({ a: 1 }), Exit.die(`{\"a\":1}`))\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/FiberId/FiberId.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as FiberId from \"effect/FiberId\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"FiberId\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.FiberId)\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.FiberId\n\n    await Util.assertions.decoding.succeed(schema, { _tag: \"None\" }, FiberId.none)\n    await Util.assertions.decoding.succeed(\n      schema,\n      { _tag: \"Runtime\", id: 1, startTimeMillis: 100 },\n      FiberId.runtime(1, 100)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      { _tag: \"Composite\", left: { _tag: \"None\" }, right: { _tag: \"None\" } },\n      FiberId.composite(FiberId.none, FiberId.none)\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      { _tag: \"Composite\", left: { _tag: \"None\" }, right: { _tag: \"-\" } },\n      `FiberId\n└─ Encoded side transformation failure\n   └─ FiberIdEncoded\n      └─ FiberIdCompositeEncoded\n         └─ [\"right\"]\n            └─ FiberIdEncoded\n               └─ { readonly _tag: \"None\" | \"Runtime\" | \"Composite\" }\n                  └─ [\"_tag\"]\n                     └─ Expected \"None\" | \"Runtime\" | \"Composite\", actual \"-\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/FiberId/FiberIdFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as FiberId from \"effect/FiberId\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"FiberIdFromSelf\", () => {\n  it(\"arbitrary\", () => {\n    Util.assertions.arbitrary.validateGeneratedValues(S.FiberIdFromSelf)\n  })\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.FiberIdFromSelf)\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.FiberIdFromSelf\n\n    await Util.assertions.decoding.succeed(schema, FiberId.none)\n    await Util.assertions.decoding.succeed(schema, FiberId.runtime(1, 100))\n    await Util.assertions.decoding.succeed(schema, FiberId.composite(FiberId.none, FiberId.none))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected FiberIdFromSelf, actual null`\n    )\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.FiberIdFromSelf\n    Util.assertions.pretty(schema, FiberId.none, `FiberId.none`)\n    Util.assertions.pretty(schema, FiberId.runtime(1, 100), `FiberId.runtime(1, 100)`)\n    Util.assertions.pretty(\n      schema,\n      FiberId.composite(FiberId.none, FiberId.none),\n      `FiberId.composite(FiberId.none, FiberId.none)`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/HashMap/HashMap.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"HashMap\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.HashMap({ key: S.Number, value: S.String }))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.HashMap({ key: S.Number, value: S.String })\n    await Util.assertions.decoding.succeed(schema, [], HashMap.fromIterable([]))\n    await Util.assertions.decoding.succeed(\n      schema,\n      [[1, \"a\"], [2, \"b\"], [3, \"c\"]],\n      HashMap.fromIterable([[1, \"a\"], [2, \"b\"], [3, \"c\"]])\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(ReadonlyArray<readonly [number, string]> <-> HashMap<number, string>)\n└─ Encoded side transformation failure\n   └─ Expected ReadonlyArray<readonly [number, string]>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      [[1, \"a\"], [2, 1]],\n      `(ReadonlyArray<readonly [number, string]> <-> HashMap<number, string>)\n└─ Encoded side transformation failure\n   └─ ReadonlyArray<readonly [number, string]>\n      └─ [1]\n         └─ readonly [number, string]\n            └─ [1]\n               └─ Expected string, actual 1`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.HashMap({ key: S.Number, value: S.String })\n    await Util.assertions.encoding.succeed(schema, HashMap.fromIterable([]), [])\n    await Util.assertions.encoding.succeed(schema, HashMap.fromIterable([[1, \"a\"], [2, \"b\"], [3, \"c\"]]), [[1, \"a\"], [\n      2,\n      \"b\"\n    ], [3, \"c\"]])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/HashMap/HashMapFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"HashMapFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.HashMapFromSelf({ key: S.Number, value: S.String }))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.HashMapFromSelf({ key: S.NumberFromString, value: S.String })\n    await Util.assertions.decoding.succeed(schema, HashMap.fromIterable([]))\n    await Util.assertions.decoding.succeed(\n      schema,\n      HashMap.fromIterable([[\"1\", \"a\"], [\"2\", \"b\"], [\"3\", \"c\"]]),\n      HashMap.fromIterable([[1, \"a\"], [2, \"b\"], [3, \"c\"]])\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected HashMap<NumberFromString, string>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      HashMap.fromIterable([[\"1\", \"a\"], [\"a\", \"b\"]]),\n      `HashMap<NumberFromString, string>\n└─ ReadonlyArray<readonly [NumberFromString, string]>\n   └─ [0]\n      └─ readonly [NumberFromString, string]\n         └─ [0]\n            └─ NumberFromString\n               └─ Transformation process failure\n                  └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.HashMapFromSelf({ key: S.NumberFromString, value: S.String })\n    await Util.assertions.encoding.succeed(schema, HashMap.fromIterable([]), HashMap.fromIterable([]))\n    await Util.assertions.encoding.succeed(\n      schema,\n      HashMap.fromIterable([[1, \"a\"], [2, \"b\"], [3, \"c\"]]),\n      HashMap.fromIterable([[\"1\", \"a\"], [\"2\", \"b\"], [\"3\", \"c\"]])\n    )\n  })\n\n  it(\"is\", () => {\n    const schema = S.HashMapFromSelf({ key: S.Number, value: S.String })\n    const is = P.is(schema)\n    assertTrue(is(HashMap.fromIterable([])))\n    assertTrue(is(HashMap.fromIterable([[1, \"a\"], [2, \"b\"], [3, \"c\"]])))\n\n    assertFalse(is(null))\n    assertFalse(is(undefined))\n    assertFalse(is(HashMap.fromIterable<number, string | number>([[1, \"a\"], [2, 1]])))\n    assertFalse(is(HashMap.fromIterable<number, string | number>([[1, 1], [2, \"b\"]])))\n    assertFalse(is(HashMap.fromIterable([[1, 1], [2, 2]])))\n    assertFalse(is(HashMap.fromIterable<string | number, number>([[\"a\", 1], [\"b\", 2], [3, 1]])))\n    assertFalse(is(HashMap.fromIterable<number, string | number>([[1, \"a\"], [2, \"b\"], [3, 1]])))\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.HashMapFromSelf({ key: S.Number, value: S.String })\n    Util.assertions.pretty(schema, HashMap.fromIterable([]), \"HashMap([])\")\n    Util.assertions.pretty(schema, HashMap.fromIterable([[1, \"a\"], [2, \"b\"]]), `HashMap([[1, \"a\"], [2, \"b\"]])`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/HashSet/HashSet.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as HashSet from \"effect/HashSet\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"HashSet\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.HashSet(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.HashSet(S.Number)\n    await Util.assertions.decoding.succeed(schema, [], HashSet.fromIterable([]))\n    await Util.assertions.decoding.succeed(schema, [1, 2, 3], HashSet.fromIterable([1, 2, 3]))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(ReadonlyArray<number> <-> HashSet<number>)\n└─ Encoded side transformation failure\n   └─ Expected ReadonlyArray<number>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      [1, \"a\"],\n      `(ReadonlyArray<number> <-> HashSet<number>)\n└─ Encoded side transformation failure\n   └─ ReadonlyArray<number>\n      └─ [1]\n         └─ Expected number, actual \"a\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.HashSet(S.Number)\n    await Util.assertions.encoding.succeed(schema, HashSet.empty(), [])\n    await Util.assertions.encoding.succeed(schema, HashSet.fromIterable([1, 2, 3]), [1, 2, 3])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/HashSet/HashSetFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as HashSet from \"effect/HashSet\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"HashSetFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.HashSetFromSelf(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.HashSetFromSelf(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, HashSet.empty(), HashSet.fromIterable([]))\n    await Util.assertions.decoding.succeed(\n      schema,\n      HashSet.fromIterable([\"1\", \"2\", \"3\"]),\n      HashSet.fromIterable([1, 2, 3])\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected HashSet<NumberFromString>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      HashSet.fromIterable([\"1\", \"a\", \"3\"]),\n      `HashSet<NumberFromString>\n└─ ReadonlyArray<NumberFromString>\n   └─ [0]\n      └─ NumberFromString\n         └─ Transformation process failure\n            └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.HashSetFromSelf(S.NumberFromString)\n    await Util.assertions.encoding.succeed(schema, HashSet.empty(), HashSet.fromIterable([]))\n    await Util.assertions.encoding.succeed(\n      schema,\n      HashSet.fromIterable([1, 2, 3]),\n      HashSet.fromIterable([\"1\", \"2\", \"3\"])\n    )\n  })\n\n  it(\"is\", () => {\n    const schema = S.HashSetFromSelf(S.String)\n    const is = P.is(schema)\n    assertTrue(is(HashSet.empty()))\n    assertTrue(is(HashSet.fromIterable([\"a\", \"b\", \"c\"])))\n\n    assertFalse(is(HashSet.fromIterable([\"a\", \"b\", 1])))\n    assertFalse(is({ _id: Symbol.for(\"effect/Schema/test/FakeHashSet\") }))\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.HashSetFromSelf(S.String)\n    Util.assertions.pretty(schema, HashSet.empty(), \"HashSet()\")\n    Util.assertions.pretty(schema, HashSet.fromIterable([\"a\", \"b\"]), `HashSet(\"a\", \"b\")`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/List/List.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as List from \"effect/List\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"List\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.List(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.List(S.Number)\n    await Util.assertions.decoding.succeed(schema, [], List.empty())\n    await Util.assertions.decoding.succeed(schema, [1, 2, 3], List.fromIterable([1, 2, 3]))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(ReadonlyArray<number> <-> List<number>)\n└─ Encoded side transformation failure\n   └─ Expected ReadonlyArray<number>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      [1, \"a\"],\n      `(ReadonlyArray<number> <-> List<number>)\n└─ Encoded side transformation failure\n   └─ ReadonlyArray<number>\n      └─ [1]\n         └─ Expected number, actual \"a\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.List(S.Number)\n    await Util.assertions.encoding.succeed(schema, List.empty(), [])\n    await Util.assertions.encoding.succeed(schema, List.fromIterable([1, 2, 3]), [1, 2, 3])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/List/ListFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as List from \"effect/List\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"ListFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.ListFromSelf(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.ListFromSelf(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, List.empty(), List.empty())\n    await Util.assertions.decoding.succeed(\n      schema,\n      List.fromIterable([\"1\", \"2\", \"3\"]),\n      List.fromIterable([1, 2, 3])\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected List<NumberFromString>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      List.fromIterable([\"1\", \"a\", \"3\"]),\n      `List<NumberFromString>\n└─ ReadonlyArray<NumberFromString>\n   └─ [1]\n      └─ NumberFromString\n         └─ Transformation process failure\n            └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.ListFromSelf(S.NumberFromString)\n    await Util.assertions.encoding.succeed(schema, List.empty(), List.empty())\n    await Util.assertions.encoding.succeed(\n      schema,\n      List.fromIterable([1, 2, 3]),\n      List.fromIterable([\"1\", \"2\", \"3\"])\n    )\n  })\n\n  it(\"is\", () => {\n    const schema = S.ListFromSelf(S.String)\n    const is = P.is(schema)\n    assertTrue(is(List.empty()))\n    assertTrue(is(List.fromIterable([\"a\", \"b\", \"c\"])))\n\n    assertFalse(is(List.fromIterable([\"a\", \"b\", 1])))\n    assertFalse(is({ _id: Symbol.for(\"effect/Schema/test/FakeList\") }))\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.ListFromSelf(S.String)\n    Util.assertions.pretty(schema, List.empty(), \"List()\")\n    Util.assertions.pretty(schema, List.fromIterable([\"a\", \"b\"]), `List(\"a\", \"b\")`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Literal/Literal.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Literal\", () => {\n  it(\"should expose the literals\", () => {\n    const schema = S.Literal(\"a\", \"b\")\n    deepStrictEqual(schema.literals, [\"a\", \"b\"])\n  })\n\n  it(\"should return Never when no literals are provided\", () => {\n    strictEqual(S.Literal(), S.Never)\n    strictEqual(S.Literal(...[]), S.Never)\n  })\n\n  it(\"should return an unwrapped AST with exactly one literal\", () => {\n    deepStrictEqual(S.Literal(1).ast, new AST.Literal(1))\n  })\n\n  it(\"should return a union with more than one literal\", () => {\n    deepStrictEqual(S.Literal(1, 2).ast, AST.Union.make([new AST.Literal(1), new AST.Literal(2)]))\n  })\n\n  it(\"should return the literal interface when using the .annotations() method\", () => {\n    const schema = S.Literal(\"a\", \"b\").annotations({ identifier: \"literal test\" })\n    deepStrictEqual(schema.ast.annotations, { [AST.IdentifierAnnotationId]: \"literal test\" })\n    deepStrictEqual(schema.literals, [\"a\", \"b\"])\n  })\n\n  describe(\"decoding\", () => {\n    it(\"1 member\", async () => {\n      const schema = S.Literal(1)\n      await Util.assertions.decoding.succeed(schema, 1)\n\n      await Util.assertions.decoding.fail(schema, \"a\", `Expected 1, actual \"a\"`)\n      await Util.assertions.decoding.fail(schema, null, `Expected 1, actual null`)\n    })\n\n    it(\"2 members\", async () => {\n      const schema = S.Literal(1, \"a\")\n      await Util.assertions.decoding.succeed(schema, 1)\n      await Util.assertions.decoding.succeed(schema, \"a\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `1 | \"a\"\n├─ Expected 1, actual null\n└─ Expected \"a\", actual null`\n      )\n    })\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.Literal(null)\n    await Util.assertions.encoding.succeed(schema, null, null)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Map/Map.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"Map\", () => {\n  it(\"description\", () => {\n    strictEqual(\n      String(S.Map({ key: S.String, value: S.Number })),\n      \"(ReadonlyArray<readonly [string, number]> <-> Map<string, number>)\"\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Map/MapFromRecord.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"MapFromRecord\", () => {\n  it(\"decoding\", async () => {\n    const schema = S.MapFromRecord({ key: S.NumberFromString, value: S.NumberFromString })\n    await Util.assertions.decoding.succeed(schema, {}, new Map())\n    await Util.assertions.decoding.succeed(\n      schema,\n      { 1: \"2\", 3: \"4\", 5: \"6\" },\n      new Map([[1, 2], [3, 4], [5, 6]])\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(a record to be decoded into a Map <-> Map<NumberFromString, number>)\n└─ Encoded side transformation failure\n   └─ Expected a record to be decoded into a Map, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: \"1\" },\n      `(a record to be decoded into a Map <-> Map<NumberFromString, number>)\n└─ Type side transformation failure\n   └─ Map<NumberFromString, number>\n      └─ ReadonlyArray<readonly [NumberFromString, number]>\n         └─ [0]\n            └─ readonly [NumberFromString, number]\n               └─ [0]\n                  └─ NumberFromString\n                     └─ Transformation process failure\n                        └─ Unable to decode \"a\" into a number`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { 1: \"a\" },\n      `(a record to be decoded into a Map <-> Map<NumberFromString, number>)\n└─ Encoded side transformation failure\n   └─ a record to be decoded into a Map\n      └─ [\"1\"]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.MapFromRecord({ key: S.NumberFromString, value: S.NumberFromString })\n    await Util.assertions.encoding.succeed(schema, new Map(), {})\n    await Util.assertions.encoding.succeed(schema, new Map([[1, 2], [3, 4], [5, 6]]), { 1: \"2\", 3: \"4\", 5: \"6\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Map/MapFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"MapFromSelf\", () => {\n  it(\"description\", () => {\n    strictEqual(String(S.MapFromSelf({ key: S.String, value: S.Number })), \"Map<string, number>\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Never/Never.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Never\", () => {\n  const schema = S.Never\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(schema, 1, \"Expected never, actual 1\")\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.fail(schema, 1 as any as never, \"Expected never, actual 1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/NonEmptyArrayEnsure.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"NonEmptyArrayEnsure\", () => {\n  it(\"decode non-array\", async () => {\n    const schema = S.NonEmptyArrayEnsure(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, \"123\", [123])\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(NumberFromString | readonly [NumberFromString, ...NumberFromString[]] <-> readonly [number, ...number[]])\n└─ Encoded side transformation failure\n   └─ NumberFromString | readonly [NumberFromString, ...NumberFromString[]]\n      ├─ NumberFromString\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual null\n      └─ Expected readonly [NumberFromString, ...NumberFromString[]], actual null`\n    )\n  })\n\n  it(\"decode empty array\", async () => {\n    const schema = S.NonEmptyArrayEnsure(S.NumberFromString)\n    await Util.assertions.decoding.fail(\n      schema,\n      [],\n      `(NumberFromString | readonly [NumberFromString, ...NumberFromString[]] <-> readonly [number, ...number[]])\n└─ Encoded side transformation failure\n   └─ NumberFromString | readonly [NumberFromString, ...NumberFromString[]]\n      ├─ NumberFromString\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual []\n      └─ readonly [NumberFromString, ...NumberFromString[]]\n         └─ [0]\n            └─ is missing`\n    )\n  })\n\n  it(\"decode array\", async () => {\n    const schema = S.NonEmptyArrayEnsure(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, [\"123\"], [123])\n    await Util.assertions.decoding.fail(\n      schema,\n      [null],\n      `(NumberFromString | readonly [NumberFromString, ...NumberFromString[]] <-> readonly [number, ...number[]])\n└─ Encoded side transformation failure\n   └─ NumberFromString | readonly [NumberFromString, ...NumberFromString[]]\n      ├─ NumberFromString\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual [null]\n      └─ readonly [NumberFromString, ...NumberFromString[]]\n         └─ [0]\n            └─ NumberFromString\n               └─ Encoded side transformation failure\n                  └─ Expected string, actual null`\n    )\n  })\n\n  it(\"encode\", async () => {\n    const schema = S.NonEmptyArrayEnsure(S.NumberFromString)\n    await Util.assertions.encoding.succeed(schema, [123], \"123\")\n    await Util.assertions.encoding.succeed(schema, [1, 2, 3], [\"1\", \"2\", \"3\"])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/JsonNumber.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"JsonNumber\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.JsonNumber)\n  })\n\n  it(\"should exclude NaN from decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      S.JsonNumber,\n      NaN,\n      `JsonNumber\n└─ Predicate refinement failure\n   └─ Expected a finite number, actual NaN`\n    )\n    await Util.assertions.decoding.fail(\n      S.JsonNumber,\n      Number.NaN,\n      `JsonNumber\n└─ Predicate refinement failure\n   └─ Expected a finite number, actual NaN`\n    )\n  })\n\n  it(\"should exclude +/- Infinity from decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      S.JsonNumber,\n      Infinity,\n      `JsonNumber\n└─ Predicate refinement failure\n   └─ Expected a finite number, actual Infinity`\n    )\n    await Util.assertions.decoding.fail(\n      S.JsonNumber,\n      -Infinity,\n      `JsonNumber\n└─ Predicate refinement failure\n   └─ Expected a finite number, actual -Infinity`\n    )\n    await Util.assertions.decoding.fail(\n      S.JsonNumber,\n      Number.POSITIVE_INFINITY,\n      `JsonNumber\n└─ Predicate refinement failure\n   └─ Expected a finite number, actual Infinity`\n    )\n    await Util.assertions.decoding.fail(\n      S.JsonNumber,\n      Number.NEGATIVE_INFINITY,\n      `JsonNumber\n└─ Predicate refinement failure\n   └─ Expected a finite number, actual -Infinity`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/Number.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Number\", () => {\n  const schema = S.Number\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 1, 1)\n    await Util.assertions.decoding.succeed(schema, NaN, NaN)\n    await Util.assertions.decoding.succeed(schema, Infinity, Infinity)\n    await Util.assertions.decoding.succeed(schema, -Infinity, -Infinity)\n    await Util.assertions.decoding.fail(schema, \"a\", `Expected number, actual \"a\"`)\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1, 1)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/between.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"between\", () => {\n  const schema = S.Number.pipe(S.between(-1, 1)).annotations({\n    title: \"[-1, -1] interval\"\n  })\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      -2,\n      `[-1, -1] interval\n└─ Predicate refinement failure\n   └─ Expected a number between -1 and 1, actual -2`\n    )\n    await Util.assertions.decoding.succeed(schema, 0, 0)\n    await Util.assertions.decoding.fail(\n      schema,\n      2,\n      `[-1, -1] interval\n└─ Predicate refinement failure\n   └─ Expected a number between -1 and 1, actual 2`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1, 1)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/clamp.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"clamp\", () => {\n  it(\"decoding\", async () => {\n    const schema = S.Number.pipe(S.clamp(-1, 1))\n    await Util.assertions.decoding.succeed(schema, 3, 1)\n    await Util.assertions.decoding.succeed(schema, 0, 0)\n    await Util.assertions.decoding.succeed(schema, -3, -1)\n  })\n\n  it(\"should support doubles as constraints\", async () => {\n    const schema = S.Number.pipe(S.clamp(1.3, 3.1))\n    await Util.assertions.decoding.succeed(schema, 4, 3.1)\n    await Util.assertions.decoding.succeed(schema, 2, 2)\n    await Util.assertions.decoding.succeed(schema, 1, 1.3)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/finite.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Finite\", () => {\n  const schema = S.Finite\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 1)\n    await Util.assertions.decoding.fail(\n      schema,\n      NaN,\n      `Finite\n└─ Predicate refinement failure\n   └─ Expected a finite number, actual NaN`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      Infinity,\n      `Finite\n└─ Predicate refinement failure\n   └─ Expected a finite number, actual Infinity`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      -Infinity,\n      `Finite\n└─ Predicate refinement failure\n   └─ Expected a finite number, actual -Infinity`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/greaterThan.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"greaterThan\", () => {\n  const schema = S.Number.pipe(S.greaterThan(0))\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"is\", () => {\n    const is = P.is(schema)\n    assertFalse(is(0))\n    assertTrue(is(1))\n    assertFalse(is(-1))\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 1)\n    await Util.assertions.decoding.fail(\n      schema,\n      0,\n      `greaterThan(0)\n└─ Predicate refinement failure\n   └─ Expected a positive number, actual 0`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      -1,\n      `greaterThan(0)\n└─ Predicate refinement failure\n   └─ Expected a positive number, actual -1`\n    )\n  })\n\n  it(\"pretty\", () => {\n    Util.assertions.pretty(schema, 1, \"1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/greaterThanOrEqualTo.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"greaterThanOrEqualTo\", () => {\n  const schema = S.Number.pipe(S.greaterThanOrEqualTo(0))\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"is\", () => {\n    const is = P.is(schema)\n    assertTrue(is(0))\n    assertTrue(is(1))\n    assertFalse(is(-1))\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0)\n    await Util.assertions.decoding.succeed(schema, 1)\n    await Util.assertions.decoding.fail(\n      schema,\n      -1,\n      `greaterThanOrEqualTo(0)\n└─ Predicate refinement failure\n   └─ Expected a non-negative number, actual -1`\n    )\n  })\n\n  it(\"pretty\", () => {\n    Util.assertions.pretty(schema, 1, \"1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/int.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Int\", () => {\n  const schema = S.Int\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"is\", () => {\n    const is = P.is(schema)\n    assertTrue(is(0))\n    assertTrue(is(1))\n    assertFalse(is(0.5))\n    assertFalse(is(Number.MAX_SAFE_INTEGER + 1))\n    assertFalse(is(Number.MIN_SAFE_INTEGER - 1))\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0)\n    await Util.assertions.decoding.succeed(schema, 1)\n    await Util.assertions.decoding.fail(\n      schema,\n      0.5,\n      `Int\n└─ Predicate refinement failure\n   └─ Expected an integer, actual 0.5`\n    )\n  })\n\n  it(\"pretty\", () => {\n    Util.assertions.pretty(schema, 1, \"1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/lessThan.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"lessThan\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Number.pipe(S.lessThan(0)))\n  })\n\n  it(\"is\", () => {\n    const is = P.is(S.Number.pipe(S.lessThan(0)))\n    assertFalse(is(0))\n    assertFalse(is(1))\n    assertTrue(is(-1))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Number.pipe(S.lessThan(0))\n    await Util.assertions.decoding.succeed(schema, -1)\n    await Util.assertions.decoding.fail(\n      schema,\n      0,\n      `lessThan(0)\n└─ Predicate refinement failure\n   └─ Expected a negative number, actual 0`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      1,\n      `lessThan(0)\n└─ Predicate refinement failure\n   └─ Expected a negative number, actual 1`\n    )\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.Number.pipe(S.lessThan(0))\n    Util.assertions.pretty(schema, 1, \"1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/lessThanOrEqualTo.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"lessThanOrEqualTo\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Number.pipe(S.lessThanOrEqualTo(0)))\n  })\n\n  it(\"is\", () => {\n    const is = P.is(S.Number.pipe(S.lessThanOrEqualTo(0)))\n    assertTrue(is(0))\n    assertFalse(is(1))\n    assertTrue(is(-1))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Number.pipe(S.lessThanOrEqualTo(0))\n    await Util.assertions.decoding.succeed(schema, 0)\n    await Util.assertions.decoding.succeed(schema, -1)\n    await Util.assertions.decoding.fail(\n      schema,\n      1,\n      `lessThanOrEqualTo(0)\n└─ Predicate refinement failure\n   └─ Expected a non-positive number, actual 1`\n    )\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.Number.pipe(S.lessThanOrEqualTo(0))\n    Util.assertions.pretty(schema, 1, \"1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/multipleOf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"multipleOf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Number.pipe(S.multipleOf(2)))\n  })\n\n  it(\"is\", () => {\n    const schema = S.Number.pipe(S.multipleOf(-.2))\n    const is = P.is(schema)\n    assertTrue(is(-2.8))\n    assertTrue(is(-2))\n    assertFalse(is(-1.5))\n    assertTrue(is(0))\n    assertTrue(is(1))\n    assertTrue(is(2.6))\n    assertFalse(is(3.1))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Number.pipe(S.multipleOf(2)).annotations({ identifier: \"Even\" })\n    await Util.assertions.decoding.succeed(schema, -4)\n    await Util.assertions.decoding.fail(\n      schema,\n      -3,\n      `Even\n└─ Predicate refinement failure\n   └─ Expected a number divisible by 2, actual -3`\n    )\n    await Util.assertions.decoding.succeed(schema, 0)\n    await Util.assertions.decoding.succeed(schema, 2)\n    await Util.assertions.decoding.fail(\n      schema,\n      2.5,\n      `Even\n└─ Predicate refinement failure\n   └─ Expected a number divisible by 2, actual 2.5`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `Even\n└─ From side refinement failure\n   └─ Expected number, actual \"\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/negative.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Negative\", () => {\n  const schema = S.Negative\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      0,\n      `Negative\n└─ Predicate refinement failure\n   └─ Expected a negative number, actual 0`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      1,\n      `Negative\n└─ Predicate refinement failure\n   └─ Expected a negative number, actual 1`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, -1, -1)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/nonNaN.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NonNaN\", () => {\n  const schema = S.NonNaN\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"is\", () => {\n    const is = P.is(schema)\n    assertTrue(is(1))\n    assertFalse(is(NaN))\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 1)\n    await Util.assertions.decoding.fail(\n      schema,\n      NaN,\n      `NonNaN\n└─ Predicate refinement failure\n   └─ Expected a number excluding NaN, actual NaN`\n    )\n  })\n\n  it(\"pretty\", () => {\n    Util.assertions.pretty(schema, 1, \"1\")\n    Util.assertions.pretty(schema, NaN, \"NaN\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/nonNegative.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NonNegative\", () => {\n  const schema = S.NonNegative\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0, 0)\n    await Util.assertions.decoding.succeed(schema, 1, 1)\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.fail(\n      schema,\n      -1,\n      `NonNegative\n└─ Predicate refinement failure\n   └─ Expected a non-negative number, actual -1`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/nonPositive.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NonPositive\", () => {\n  const schema = S.NonPositive\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, 0, 0)\n    await Util.assertions.decoding.fail(\n      schema,\n      1,\n      `NonPositive\n└─ Predicate refinement failure\n   └─ Expected a non-positive number, actual 1`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, -1, -1)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/numberFromString.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NumberFromString\", () => {\n  const schema = S.NumberFromString\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, \"0\", 0)\n    await Util.assertions.decoding.succeed(schema, \"-0\", -0)\n    await Util.assertions.decoding.succeed(schema, \"1\", 1)\n    await Util.assertions.decoding.succeed(schema, \"1.2\", 1.2)\n\n    await Util.assertions.decoding.succeed(schema, \"NaN\", NaN)\n    await Util.assertions.decoding.succeed(schema, \"Infinity\", Infinity)\n    await Util.assertions.decoding.succeed(schema, \"-Infinity\", -Infinity)\n\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `NumberFromString\n└─ Transformation process failure\n   └─ Unable to decode \"\" into a number`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \" \",\n      `NumberFromString\n└─ Transformation process failure\n   └─ Unable to decode \" \" into a number`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"1AB\",\n      `NumberFromString\n└─ Transformation process failure\n   └─ Unable to decode \"1AB\" into a number`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"AB1\",\n      `NumberFromString\n└─ Transformation process failure\n   └─ Unable to decode \"AB1\" into a number`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a\",\n      `NumberFromString\n└─ Transformation process failure\n   └─ Unable to decode \"a\" into a number`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a1\",\n      `NumberFromString\n└─ Transformation process failure\n   └─ Unable to decode \"a1\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1, \"1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Number/positive.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Positive\", () => {\n  const schema = S.Positive\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.fail(\n      schema,\n      -1,\n      `Positive\n└─ Predicate refinement failure\n   └─ Expected a positive number, actual -1`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      0,\n      `Positive\n└─ Predicate refinement failure\n   └─ Expected a positive number, actual 0`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, 1, 1)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Object/Object.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"object\", () => {\n  const schema = S.Object\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, {})\n    await Util.assertions.decoding.succeed(schema, [])\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected object, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a\",\n      `Expected object, actual \"a\"`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      1,\n      `Expected object, actual 1`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      true,\n      `Expected object, actual true`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, {}, {})\n    await Util.assertions.encoding.succeed(schema, [], [])\n    await Util.assertions.encoding.succeed(schema, [1, 2, 3], [1, 2, 3])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Option/Option.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as O from \"effect/Option\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Option\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Option(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Option(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, JSON.parse(JSON.stringify(O.none())), O.none())\n    await Util.assertions.decoding.succeed(schema, JSON.parse(JSON.stringify(O.some(\"1\"))), O.some(1))\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.Option(S.NumberFromString)\n    await Util.assertions.encoding.succeed(schema, O.none(), { _tag: \"None\" })\n    await Util.assertions.encoding.succeed(schema, O.some(1), { _tag: \"Some\", value: \"1\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Option/OptionFromNonEmptyTrimmedString.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as O from \"effect/Option\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"OptionFromNonEmptyTrimmedString\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.OptionFromNonEmptyTrimmedString)\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.OptionFromNonEmptyTrimmedString\n    await Util.assertions.decoding.succeed(schema, \"\", O.none())\n    await Util.assertions.decoding.succeed(schema, \"a\", O.some(\"a\"))\n    await Util.assertions.decoding.succeed(schema, \" \", O.none())\n    await Util.assertions.decoding.succeed(schema, \" a \", O.some(\"a\"))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(string <-> Option<NonEmptyTrimmedString>)\n└─ Encoded side transformation failure\n   └─ Expected string, actual null`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.OptionFromNonEmptyTrimmedString\n    await Util.assertions.encoding.succeed(schema, O.none(), \"\")\n    await Util.assertions.encoding.succeed(schema, O.some(\"a\"), \"a\")\n\n    await Util.assertions.encoding.fail(\n      schema,\n      O.some(\"\"),\n      `(string <-> Option<NonEmptyTrimmedString>)\n└─ Type side transformation failure\n   └─ Option<NonEmptyTrimmedString>\n      └─ NonEmptyTrimmedString\n         └─ Predicate refinement failure\n            └─ Expected a non empty string, actual \"\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Option/OptionFromNullOr.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue } from \"@effect/vitest/utils\"\nimport * as O from \"effect/Option\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"OptionFromNullOr\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.OptionFromNullOr(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.OptionFromNullOr(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, null, O.none())\n    await Util.assertions.decoding.succeed(schema, \"1\", O.some(1))\n\n    assertTrue(O.isOption(S.decodeSync(schema)(null)))\n    assertTrue(O.isOption(S.decodeSync(schema)(\"1\")))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      undefined,\n      `(NumberFromString | null <-> Option<number>)\n└─ Encoded side transformation failure\n   └─ NumberFromString | null\n      ├─ NumberFromString\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual undefined\n      └─ Expected null, actual undefined`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      {},\n      `(NumberFromString | null <-> Option<number>)\n└─ Encoded side transformation failure\n   └─ NumberFromString | null\n      ├─ NumberFromString\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual {}\n      └─ Expected null, actual {}`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.OptionFromNullOr(S.NumberFromString)\n    await Util.assertions.encoding.succeed(schema, O.none(), null)\n    await Util.assertions.encoding.succeed(schema, O.some(1), \"1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Option/OptionFromNullishOr.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue } from \"@effect/vitest/utils\"\nimport * as O from \"effect/Option\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"OptionFromNullishOr\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.OptionFromNullishOr(S.Number, null))\n    Util.assertions.testRoundtripConsistency(S.OptionFromNullishOr(S.Number, undefined))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.OptionFromNullishOr(S.NumberFromString, undefined)\n    await Util.assertions.decoding.succeed(schema, null, O.none())\n    await Util.assertions.decoding.succeed(schema, undefined, O.none())\n    await Util.assertions.decoding.succeed(schema, \"1\", O.some(1))\n\n    assertTrue(O.isOption(S.decodeSync(schema)(null)))\n    assertTrue(O.isOption(S.decodeSync(schema)(undefined)))\n    assertTrue(O.isOption(S.decodeSync(schema)(\"1\")))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      {},\n      `(NumberFromString | null | undefined <-> Option<number>)\n└─ Encoded side transformation failure\n   └─ NumberFromString | null | undefined\n      ├─ NumberFromString\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual {}\n      ├─ Expected null, actual {}\n      └─ Expected undefined, actual {}`\n    )\n  })\n\n  it(\"encoding null\", async () => {\n    const schema = S.OptionFromNullishOr(S.NumberFromString, null)\n    await Util.assertions.encoding.succeed(schema, O.none(), null)\n    await Util.assertions.encoding.succeed(schema, O.some(1), \"1\")\n  })\n\n  it(\"encoding undefined\", async () => {\n    const schema = S.OptionFromNullishOr(S.NumberFromString, undefined)\n    await Util.assertions.encoding.succeed(schema, O.none(), undefined)\n    await Util.assertions.encoding.succeed(schema, O.some(1), \"1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Option/OptionFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as O from \"effect/Option\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"OptionFromSelf\", () => {\n  it(\"arbitrary\", () => {\n    Util.assertions.arbitrary.validateGeneratedValues(S.OptionFromSelf(S.Number))\n  })\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.OptionFromSelf(S.NumberFromString))\n  })\n\n  it(\"is\", () => {\n    const schema = S.OptionFromSelf(S.Number)\n    const is = P.is(schema)\n    assertTrue(is(O.none()))\n    assertTrue(is(O.some(1)))\n    assertFalse(is(null))\n    assertFalse(is(O.some(\"a\")))\n\n    assertFalse(is({ _tag: \"None\" }))\n    assertFalse(is({ _tag: \"Some\", value: 1 }))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.OptionFromSelf(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, O.none(), O.none())\n    await Util.assertions.decoding.succeed(schema, O.some(\"1\"), O.some(1))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected Option<NumberFromString>, actual null`\n    )\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.OptionFromSelf(S.Number)\n    Util.assertions.pretty(schema, O.none(), \"none()\")\n    Util.assertions.pretty(schema, O.some(1), \"some(1)\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Option/OptionFromUndefinedOr.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue } from \"@effect/vitest/utils\"\nimport * as O from \"effect/Option\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"OptionFromUndefinedOr\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.OptionFromUndefinedOr(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.OptionFromUndefinedOr(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, undefined, O.none())\n    await Util.assertions.decoding.succeed(schema, \"1\", O.some(1))\n\n    assertTrue(O.isOption(S.decodeSync(schema)(undefined)))\n    assertTrue(O.isOption(S.decodeSync(schema)(\"1\")))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(NumberFromString | undefined <-> Option<number>)\n└─ Encoded side transformation failure\n   └─ NumberFromString | undefined\n      ├─ NumberFromString\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual null\n      └─ Expected undefined, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      {},\n      `(NumberFromString | undefined <-> Option<number>)\n└─ Encoded side transformation failure\n   └─ NumberFromString | undefined\n      ├─ NumberFromString\n      │  └─ Encoded side transformation failure\n      │     └─ Expected string, actual {}\n      └─ Expected undefined, actual {}`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.OptionFromUndefinedOr(S.NumberFromString)\n    await Util.assertions.encoding.succeed(schema, O.none(), undefined)\n    await Util.assertions.encoding.succeed(schema, O.some(1), \"1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ParseOptions-errors.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"`errors` option\", () => {\n  describe(\"decoding\", () => {\n    describe(\"tuple\", () => {\n      it(\"e r e\", async () => {\n        const schema = S.Tuple([S.String], S.Number, S.Boolean)\n        await Util.assertions.decoding.fail(\n          schema,\n          [true],\n          `readonly [string, ...number[], boolean]\n├─ [1]\n│  └─ is missing\n└─ [0]\n   └─ Expected string, actual true`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n\n      it(\"missing element\", async () => {\n        const schema = S.Tuple(S.String, S.Number)\n        await Util.assertions.decoding.fail(\n          schema,\n          [],\n          `readonly [string, number]\n├─ [0]\n│  └─ is missing\n└─ [1]\n   └─ is missing`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n\n      it(\"unexpected indexes\", async () => {\n        const schema = S.Tuple()\n        await Util.assertions.decoding.fail(\n          schema,\n          [\"a\", \"b\"],\n          `readonly []\n├─ [0]\n│  └─ is unexpected, expected: never\n└─ [1]\n   └─ is unexpected, expected: never`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n\n      it(\"wrong type for elements\", async () => {\n        const schema = S.Tuple(S.String, S.Number)\n        await Util.assertions.decoding.fail(\n          schema,\n          [1, \"b\"],\n          `readonly [string, number]\n├─ [0]\n│  └─ Expected string, actual 1\n└─ [1]\n   └─ Expected number, actual \"b\"`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n\n      it(\"wrong type for rest\", async () => {\n        const schema = S.Tuple([S.String], S.Number)\n        await Util.assertions.decoding.fail(\n          schema,\n          [\"a\", \"b\", \"c\"],\n          `readonly [string, ...number[]]\n├─ [1]\n│  └─ Expected number, actual \"b\"\n└─ [2]\n   └─ Expected number, actual \"c\"`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n\n      it(\"wrong type for post rest elements\", async () => {\n        const schema = S.Tuple([], S.Boolean, S.Number, S.Number)\n        await Util.assertions.decoding.fail(\n          schema,\n          [\"a\", \"b\"],\n          `readonly [...boolean[], number, number]\n├─ [0]\n│  └─ Expected number, actual \"a\"\n└─ [1]\n   └─ Expected number, actual \"b\"`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n    })\n\n    describe(\"struct\", () => {\n      it(\"missing keys\", async () => {\n        const schema = S.Struct({ a: S.String, b: S.Number })\n        await Util.assertions.decoding.fail(\n          schema,\n          {},\n          `{ readonly a: string; readonly b: number }\n├─ [\"a\"]\n│  └─ is missing\n└─ [\"b\"]\n   └─ is missing`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n\n      it(\"wrong type for values\", async () => {\n        const schema = S.Struct({ a: S.String, b: S.Number })\n        await Util.assertions.decoding.fail(\n          schema,\n          { a: 1, b: \"b\" },\n          `{ readonly a: string; readonly b: number }\n├─ [\"a\"]\n│  └─ Expected string, actual 1\n└─ [\"b\"]\n   └─ Expected number, actual \"b\"`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n\n      it(\"unexpected keys\", async () => {\n        const schema = S.Struct({ a: S.Number })\n        await Util.assertions.decoding.fail(\n          schema,\n          { a: 1, b: \"b\", c: \"c\" },\n          `{ readonly a: number }\n├─ [\"b\"]\n│  └─ is unexpected, expected: \"a\"\n└─ [\"c\"]\n   └─ is unexpected, expected: \"a\"`,\n          { parseOptions: { ...Util.ErrorsAll, ...Util.onExcessPropertyError } }\n        )\n      })\n    })\n\n    describe(\"record\", () => {\n      it(\"all key errors\", async () => {\n        const schema = S.Record({ key: S.String.pipe(S.minLength(2)), value: S.Number })\n        await Util.assertions.decoding.fail(\n          schema,\n          { a: 1, b: 2 },\n          `{ readonly [x: minLength(2)]: number }\n├─ [\"a\"]\n│  └─ is unexpected, expected: minLength(2)\n└─ [\"b\"]\n   └─ is unexpected, expected: minLength(2)`,\n          { parseOptions: { ...Util.ErrorsAll, ...Util.onExcessPropertyError } }\n        )\n      })\n\n      it(\"all value errors\", async () => {\n        const schema = S.Record({ key: S.String, value: S.Number })\n        await Util.assertions.decoding.fail(\n          schema,\n          { a: \"a\", b: \"b\" },\n          `{ readonly [x: string]: number }\n├─ [\"a\"]\n│  └─ Expected number, actual \"a\"\n└─ [\"b\"]\n   └─ Expected number, actual \"b\"`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n    })\n  })\n\n  describe(\"encoding\", () => {\n    describe(\"tuple\", () => {\n      it(\"unexpected indexes\", async () => {\n        const schema = S.Tuple()\n        await Util.assertions.encoding.fail(\n          schema,\n          [1, 1] as any,\n          `readonly []\n├─ [0]\n│  └─ is unexpected, expected: never\n└─ [1]\n   └─ is unexpected, expected: never`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n\n      it(\"wrong type for elements\", async () => {\n        const schema = S.Tuple(Util.NumberFromChar, Util.NumberFromChar)\n        await Util.assertions.encoding.fail(\n          schema,\n          [10, 10],\n          `readonly [NumberFromChar, NumberFromChar]\n├─ [0]\n│  └─ NumberFromChar\n│     └─ Encoded side transformation failure\n│        └─ Char\n│           └─ Predicate refinement failure\n│              └─ Expected a single character, actual \"10\"\n└─ [1]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n\n      it(\"wrong type for rest\", async () => {\n        const schema = S.Array(Util.NumberFromChar)\n        await Util.assertions.encoding.fail(\n          schema,\n          [10, 10],\n          `ReadonlyArray<NumberFromChar>\n├─ [0]\n│  └─ NumberFromChar\n│     └─ Encoded side transformation failure\n│        └─ Char\n│           └─ Predicate refinement failure\n│              └─ Expected a single character, actual \"10\"\n└─ [1]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n\n      it(\"wrong type for values post rest elements\", async () => {\n        const schema = S.Tuple([], S.String, Util.NumberFromChar, Util.NumberFromChar)\n        await Util.assertions.encoding.fail(\n          schema,\n          [10, 10],\n          `readonly [...string[], NumberFromChar, NumberFromChar]\n├─ [0]\n│  └─ NumberFromChar\n│     └─ Encoded side transformation failure\n│        └─ Char\n│           └─ Predicate refinement failure\n│              └─ Expected a single character, actual \"10\"\n└─ [1]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n    })\n\n    describe(\"struct\", () => {\n      it(\"wrong type for values\", async () => {\n        const schema = S.Struct({ a: Util.NumberFromChar, b: Util.NumberFromChar })\n        await Util.assertions.encoding.fail(\n          schema,\n          { a: 10, b: 10 },\n          `{ readonly a: NumberFromChar; readonly b: NumberFromChar }\n├─ [\"a\"]\n│  └─ NumberFromChar\n│     └─ Encoded side transformation failure\n│        └─ Char\n│           └─ Predicate refinement failure\n│              └─ Expected a single character, actual \"10\"\n└─ [\"b\"]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n    })\n\n    describe(\"record\", () => {\n      it(\"all key errors\", async () => {\n        const schema = S.Record({ key: S.Char, value: S.String })\n        await Util.assertions.encoding.fail(\n          schema,\n          { aa: \"a\", bb: \"bb\" },\n          `{ readonly [x: Char]: string }\n├─ [\"aa\"]\n│  └─ is unexpected, expected: Char\n└─ [\"bb\"]\n   └─ is unexpected, expected: Char`,\n          { parseOptions: { ...Util.ErrorsAll, ...Util.onExcessPropertyError } }\n        )\n      })\n\n      it(\"all value errors\", async () => {\n        const schema = S.Record({ key: S.String, value: S.Char })\n        await Util.assertions.encoding.fail(\n          schema,\n          { a: \"aa\", b: \"bb\" },\n          `{ readonly [x: string]: Char }\n├─ [\"a\"]\n│  └─ Char\n│     └─ Predicate refinement failure\n│        └─ Expected a single character, actual \"aa\"\n└─ [\"b\"]\n   └─ Char\n      └─ Predicate refinement failure\n         └─ Expected a single character, actual \"bb\"`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ParseOptions-exact.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"`exact` option\", () => {\n  describe(\"decoding\", () => {\n    it(\"false (default)\", async () => {\n      const schema = S.Struct({ a: S.Unknown })\n      await Util.assertions.decoding.succeed(schema, {}, { a: undefined })\n    })\n\n    it(\"true\", async () => {\n      const schema = S.Struct({ a: S.Unknown, b: S.Unknown })\n      await Util.assertions.decoding.fail(\n        schema,\n        {},\n        `{ readonly a: unknown; readonly b: unknown }\n└─ [\"a\"]\n   └─ is missing`,\n        { parseOptions: { exact: true } }\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        {},\n        `{ readonly a: unknown; readonly b: unknown }\n├─ [\"a\"]\n│  └─ is missing\n└─ [\"b\"]\n   └─ is missing`,\n        { parseOptions: { exact: true, errors: \"all\" } }\n      )\n    })\n  })\n\n  describe(\"is\", () => {\n    it(\"true (default)\", async () => {\n      const schema = S.Struct({ a: S.Unknown })\n      assertFalse(S.is(schema)({}))\n    })\n\n    it(\"false\", async () => {\n      const schema = S.Struct({ a: S.Unknown })\n      assertTrue(S.is(schema)({}, { exact: false }))\n    })\n  })\n\n  describe(\"asserts\", () => {\n    it(\"true (default)\", async () => {\n      const schema = S.Struct({ a: S.Unknown })\n      Util.assertions.asserts.fail(\n        schema,\n        {},\n        `{ readonly a: unknown }\n└─ [\"a\"]\n   └─ is missing`\n      )\n    })\n\n    it(\"false\", async () => {\n      const schema = S.Struct({ a: S.Unknown })\n      Util.assertions.asserts.succeed(schema, {}, { parseOptions: { exact: false } })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ParseOptions-onExcessProperty.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft } from \"@effect/vitest/utils\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"`onExcessProperty` option\", () => {\n  describe(\"`ignore` option\", () => {\n    it(\"should not change tuple behaviour\", async () => {\n      const schema = S.Tuple(S.Number)\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, \"b\"],\n        `readonly [number]\n└─ [1]\n   └─ is unexpected, expected: 0`\n      )\n      await Util.assertions.encoding.fail(\n        schema,\n        [1, \"b\"] as any,\n        `readonly [number]\n└─ [1]\n   └─ is unexpected, expected: 0`\n      )\n    })\n\n    it(\"tuple of a struct\", async () => {\n      const schema = S.Tuple(S.Struct({ b: S.Number }))\n      await Util.assertions.decoding.succeed(\n        schema,\n        [{ b: 1, c: \"c\" }],\n        [{ b: 1 }]\n      )\n    })\n\n    it(\"tuple rest element of a struct\", async () => {\n      const schema = S.Array(S.Struct({ b: S.Number }))\n      await Util.assertions.decoding.succeed(\n        schema,\n        [{ b: 1, c: \"c\" }],\n        [{ b: 1 }]\n      )\n    })\n\n    it(\"tuple. post rest elements of a struct\", async () => {\n      const schema = S.Tuple([], S.String, S.Struct({ b: S.Number }))\n      await Util.assertions.decoding.succeed(schema, [{ b: 1 }])\n      await Util.assertions.decoding.succeed(\n        schema,\n        [{ b: 1, c: \"c\" }],\n        [{ b: 1 }]\n      )\n    })\n\n    it(\"struct excess property signatures\", async () => {\n      const schema = S.Struct({ a: S.Number })\n      await Util.assertions.decoding.succeed(\n        schema,\n        { a: 1, b: \"b\" },\n        { a: 1 }\n      )\n    })\n\n    it(\"struct nested struct\", async () => {\n      const schema = S.Struct({ a: S.Struct({ b: S.Number }) })\n      await Util.assertions.decoding.succeed(\n        schema,\n        { a: { b: 1, c: \"c\" } },\n        {\n          a: { b: 1 }\n        }\n      )\n    })\n\n    it(\"record of struct\", async () => {\n      const schema = S.Record({ key: S.String, value: S.Struct({ b: S.Number }) })\n      await Util.assertions.decoding.succeed(\n        schema,\n        { a: { b: 1, c: \"c\" } },\n        { a: { b: 1 } }\n      )\n    })\n  })\n\n  describe(\"`error` option\", () => {\n    describe(\"should register the actual value\", () => {\n      it(\"struct\", () => {\n        const schema = S.Struct({ a: S.String })\n        const input = { a: \"a\", b: 1 }\n        const e = ParseResult.decodeUnknownEither(schema)(input, Util.onExcessPropertyError)\n        assertLeft(\n          e,\n          new ParseResult.Composite(\n            schema.ast,\n            input,\n            new ParseResult.Pointer(\"b\", input, new ParseResult.Unexpected(1, `is unexpected, expected: \"a\"`)),\n            {}\n          )\n        )\n      })\n\n      it(\"tuple\", () => {\n        const schema = S.Tuple(S.String)\n        const input = [\"a\", 1]\n        const e = ParseResult.decodeUnknownEither(schema)(input, Util.onExcessPropertyError)\n        assertLeft(\n          e,\n          new ParseResult.Composite(\n            schema.ast,\n            input,\n            new ParseResult.Pointer(1, input, new ParseResult.Unexpected(1, `is unexpected, expected: 0`)),\n            []\n          )\n        )\n      })\n    })\n\n    it(\"structs\", async () => {\n      const a = S.Struct({\n        a: S.optionalWith(S.Number, { exact: true }),\n        b: S.optionalWith(S.String, { exact: true })\n      })\n      const b = S.Struct({ a: S.optionalWith(S.Number, { exact: true }) })\n      const schema = S.Union(a, b)\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1, b: \"b\", c: true },\n        `{ readonly a?: number; readonly b?: string } | { readonly a?: number }\n├─ { readonly a?: number; readonly b?: string }\n│  └─ [\"c\"]\n│     └─ is unexpected, expected: \"a\" | \"b\"\n└─ { readonly a?: number }\n   └─ [\"b\"]\n      └─ is unexpected, expected: \"a\"`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"tuples\", async () => {\n      const a = S.Tuple(S.Number, S.optionalElement(S.String))\n      const b = S.Tuple(S.Number)\n      const schema = S.Union(a, b)\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, \"b\", true],\n        `readonly [number, string?] | readonly [number]\n├─ readonly [number, string?]\n│  └─ [2]\n│     └─ is unexpected, expected: 0 | 1\n└─ readonly [number]\n   └─ [1]\n      └─ is unexpected, expected: 0`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, \"b\", true],\n        `readonly [number, string?] | readonly [number]\n├─ readonly [number, string?]\n│  └─ [2]\n│     └─ is unexpected, expected: 0 | 1\n└─ readonly [number]\n   └─ [1]\n      └─ is unexpected, expected: 0`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n  })\n\n  describe(\"`preserve` option\", () => {\n    it(\"should not change tuple behaviour\", async () => {\n      const schema = S.Tuple(S.Number)\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, \"b\"],\n        `readonly [number]\n└─ [1]\n   └─ is unexpected, expected: 0`,\n        { parseOptions: Util.onExcessPropertyPreserve }\n      )\n      await Util.assertions.encoding.fail(\n        schema,\n        [1, \"b\"] as any,\n        `readonly [number]\n└─ [1]\n   └─ is unexpected, expected: 0`,\n        { parseOptions: Util.onExcessPropertyPreserve }\n      )\n    })\n\n    it(\"struct with string excess keys\", async () => {\n      const c = Symbol.for(\"effect/Schema/test/c\")\n      const schema = S.Struct({ a: S.String })\n      const input = { a: \"a\", b: 1, [c]: true }\n      await Util.assertions.decoding.succeed(schema, input, input, {\n        parseOptions: Util.onExcessPropertyPreserve\n      })\n    })\n\n    it(\"struct with symbol excess keys\", async () => {\n      const c = Symbol.for(\"effect/Schema/test/c\")\n      const schema = S.Struct({ [c]: S.Boolean })\n      const input = { a: \"a\", b: 1, [c]: true }\n      await Util.assertions.decoding.succeed(schema, input, input, {\n        parseOptions: Util.onExcessPropertyPreserve\n      })\n    })\n\n    it(\"struct with both string and symbol excess keys\", async () => {\n      const c = Symbol.for(\"effect/Schema/test/c\")\n      const schema = S.Struct({ a: S.String, [c]: S.Boolean })\n      const input = { a: \"a\", b: 1, [c]: true }\n      await Util.assertions.decoding.succeed(schema, input, input, {\n        parseOptions: Util.onExcessPropertyPreserve\n      })\n    })\n\n    it(\"record(string, string)\", async () => {\n      const c = Symbol.for(\"effect/Schema/test/c\")\n      const schema = S.Struct({ a: S.String })\n      const input = { a: \"a\", [c]: true }\n      await Util.assertions.decoding.succeed(schema, input, input, {\n        parseOptions: Util.onExcessPropertyPreserve\n      })\n    })\n\n    it(\"record(symbol, boolean)\", async () => {\n      const c = Symbol.for(\"effect/Schema/test/c\")\n      const schema = S.Struct({ [c]: S.Boolean })\n      const input = { a: \"a\", [c]: true }\n      await Util.assertions.decoding.succeed(schema, input, input, {\n        parseOptions: Util.onExcessPropertyPreserve\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ParseOptions-preserveKeyOrder.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport type { Duration } from \"effect\"\nimport * as Effect from \"effect/Effect\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"`preserveKeyOrder` option\", () => {\n  const b = Symbol.for(\"effect/Schema/test/b\")\n  const Sync = S.Struct({\n    a: S.Literal(\"a\"),\n    [b]: S.Array(S.String),\n    c: S.Record({ key: S.String, value: S.Number }),\n    d: S.NumberFromString,\n    e: S.Boolean,\n    f: S.optional(S.String),\n    g: S.optional(S.String)\n  })\n\n  const effectify = (duration: Duration.DurationInput) =>\n    S.NumberFromString.pipe(\n      S.transformOrFail(S.Number, {\n        strict: true,\n        decode: (x) => Effect.sleep(duration).pipe(Effect.andThen(ParseResult.succeed(x))),\n        encode: ParseResult.succeed\n      })\n    )\n\n  const Async = S.Struct({\n    a: effectify(\"20 millis\"),\n    [b]: effectify(\"30 millis\"),\n    c: effectify(\"10 millis\")\n  }).annotations({ concurrency: 3 })\n\n  describe(\"decoding\", () => {\n    it(\"should preserve the order of input properties (sync)\", () => {\n      const input = { [b]: [\"b\"], c: { c: 1 }, d: \"1\", e: true, a: \"a\", other: 1, f: undefined }\n      const output = S.decodeUnknownSync(Sync)(input, { propertyOrder: \"original\", onExcessProperty: \"preserve\" })\n      const expectedOutput = { [b]: [\"b\"], c: { c: 1 }, d: 1, e: true, a: \"a\", other: 1, f: undefined } as const\n      deepStrictEqual(output, expectedOutput)\n      deepStrictEqual(Reflect.ownKeys(output), Reflect.ownKeys(expectedOutput))\n    })\n\n    it(\"should preserve the order of input properties (async)\", async () => {\n      const input = { a: \"1\", c: \"3\", [b]: \"2\", other: 1 }\n      const output = await Effect.runPromise(\n        S.decodeUnknown(Async)(input, { propertyOrder: \"original\", onExcessProperty: \"preserve\" })\n      )\n      const expectedOutput = { a: 1, c: 3, [b]: 2, other: 1 }\n      deepStrictEqual(output, expectedOutput)\n      deepStrictEqual(Reflect.ownKeys(output), Reflect.ownKeys(expectedOutput))\n    })\n  })\n\n  describe(\"encoding\", () => {\n    it(\"should preserve the order of input properties (sync)\", () => {\n      const input = { [b]: [\"b\"], c: { c: 1 }, d: 1, e: true, a: \"a\", other: 1, f: undefined }\n      const output = S.encodeUnknownSync(Sync)(input, { propertyOrder: \"original\", onExcessProperty: \"preserve\" })\n      const expectedOutput = { [b]: [\"b\"], c: { c: 1 }, d: \"1\", e: true, a: \"a\", other: 1, f: undefined } as const\n      deepStrictEqual(output, expectedOutput)\n      deepStrictEqual(Reflect.ownKeys(output), Reflect.ownKeys(expectedOutput))\n    })\n\n    it(\"should preserve the order of input properties (async)\", async () => {\n      const input = { a: 1, c: 3, [b]: 2, other: 1 }\n      const output = await Effect.runPromise(\n        S.encodeUnknown(Async)(input, { propertyOrder: \"original\", onExcessProperty: \"preserve\" })\n      )\n      const expectedOutput = { a: \"1\", c: \"3\", [b]: \"2\", other: 1 }\n      deepStrictEqual(output, expectedOutput)\n      deepStrictEqual(Reflect.ownKeys(output), Reflect.ownKeys(expectedOutput))\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ParseOptionsAnnotation.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\nconst String = S.transform(S.NonEmptyString, S.String, { strict: true, decode: (s) => s, encode: (s) => s })\n  .annotations({\n    identifier: \"string\"\n  })\n\ndescribe(\"ParseOptionsAnnotation\", () => {\n  it(\"nested structs\", async () => {\n    const schema = S.Struct({\n      a: S.Struct({\n        b: String,\n        c: String\n      }).annotations({ parseOptions: { errors: \"first\" } }),\n      d: String\n    }).annotations({ parseOptions: { errors: \"all\" } })\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: {} },\n      `{ readonly a: { readonly b: string; readonly c: string }; readonly d: string }\n├─ [\"a\"]\n│  └─ { readonly b: string; readonly c: string }\n│     └─ [\"b\"]\n│        └─ is missing\n└─ [\"d\"]\n   └─ is missing`,\n      { parseOptions: { errors: \"first\" } }\n    )\n\n    await Util.assertions.encoding.fail(\n      schema,\n      { a: { b: \"\", c: \"\" }, d: \"\" },\n      `{ readonly a: { readonly b: string; readonly c: string }; readonly d: string }\n├─ [\"a\"]\n│  └─ { readonly b: string; readonly c: string }\n│     └─ [\"b\"]\n│        └─ string\n│           └─ Encoded side transformation failure\n│              └─ NonEmptyString\n│                 └─ Predicate refinement failure\n│                    └─ Expected a non empty string, actual \"\"\n└─ [\"d\"]\n   └─ string\n      └─ Encoded side transformation failure\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`,\n      { parseOptions: { errors: \"first\" } }\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/PropertyKey/PropertyKey.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as Schema from \"effect/Schema\"\n\ndescribe(\"PropertyKey\", () => {\n  it(\"should handle symbol, string, and number\", () => {\n    const encodeSync = Schema.encodeSync(Schema.PropertyKey)\n    const decodeSync = Schema.decodeSync(Schema.PropertyKey)\n    const expectRoundtrip = (pk: PropertyKey) => {\n      strictEqual(decodeSync(encodeSync(pk)), pk)\n    }\n\n    expectRoundtrip(\"path\")\n    expectRoundtrip(1)\n    expectRoundtrip(Symbol.for(\"symbol\"))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/PropertySignature.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { identity } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"PropertySignature\", () => {\n  it(\"should expose a from property\", () => {\n    const schema = S.propertySignature(S.String)\n    strictEqual(schema.from, S.String)\n  })\n\n  it(\"should expose a from property after an annotations call\", () => {\n    const schema = S.propertySignature(S.String).annotations({})\n    strictEqual(schema.from, S.String)\n  })\n\n  it(\"toString\", () => {\n    strictEqual(\n      String(S.optional(S.String)),\n      `PropertySignature<\"?:\", string | undefined, never, \"?:\", string | undefined>`\n    )\n    strictEqual(\n      String(S.optional(S.String).pipe(S.fromKey(\"a\"))),\n      `PropertySignature<\"?:\", string | undefined, \"a\", \"?:\", string | undefined>`\n    )\n  })\n\n  describe(\"annotations\", () => {\n    it(\"propertySignature(S.string)\", () => {\n      const schema = S.Struct({\n        a: S.propertySignature(S.String).annotations({ description: \"a description\" }).annotations({ title: \"a title\" })\n      })\n      const ast = schema.ast as AST.TypeLiteral\n      deepStrictEqual(ast.propertySignatures[0].annotations, {\n        [AST.DescriptionAnnotationId]: \"a description\",\n        [AST.TitleAnnotationId]: \"a title\"\n      })\n    })\n\n    it(\"propertySignature(S.NumberFromString)\", () => {\n      const schema = S.Struct({\n        a: S.propertySignature(S.NumberFromString).annotations({ description: \"a description\" }).annotations({\n          title: \"a title\"\n        })\n      })\n      const ast = schema.ast as AST.TypeLiteral\n      deepStrictEqual(ast.propertySignatures[0].annotations, {\n        [AST.DescriptionAnnotationId]: \"a description\",\n        [AST.TitleAnnotationId]: \"a title\"\n      })\n    })\n\n    it(\"optional(S.string)\", () => {\n      const schema = S.Struct({\n        a: S.optional(S.String).annotations({ description: \"a description\" }).annotations({ title: \"a title\" })\n      })\n      const ast = schema.ast as AST.TypeLiteral\n      deepStrictEqual(ast.propertySignatures[0].annotations, {\n        [AST.DescriptionAnnotationId]: \"a description\",\n        [AST.TitleAnnotationId]: \"a title\"\n      })\n    })\n\n    it(\"optional(S.NumberFromString)\", () => {\n      const schema = S.Struct({\n        a: S.optional(S.NumberFromString).annotations({ description: \"a description\" }).annotations({\n          title: \"a title\"\n        })\n      })\n      const ast = schema.ast as AST.TypeLiteral\n      deepStrictEqual(ast.propertySignatures[0].annotations, {\n        [AST.DescriptionAnnotationId]: \"a description\",\n        [AST.TitleAnnotationId]: \"a title\"\n      })\n    })\n\n    it(\"optionalWith(S.string, { default })\", () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.String, { default: () => \"\" }).annotations({ description: \"a description\" }).annotations({\n          title: \"a title\"\n        })\n      })\n      const ast = schema.ast as AST.Transformation\n      const to = ast.to as AST.TypeLiteral\n      deepStrictEqual(to.propertySignatures[0].annotations, {\n        [AST.DescriptionAnnotationId]: \"a description\",\n        [AST.TitleAnnotationId]: \"a title\"\n      })\n    })\n\n    it(\"optionalWith(S.NumberFromString, { default })\", () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { default: () => 0 }).annotations({ description: \"a description\" })\n          .annotations({ title: \"a title\" })\n      })\n      const ast = schema.ast as AST.Transformation\n      const to = ast.to as AST.TypeLiteral\n      deepStrictEqual(to.propertySignatures[0].annotations, {\n        [AST.DescriptionAnnotationId]: \"a description\",\n        [AST.TitleAnnotationId]: \"a title\"\n      })\n    })\n  })\n\n  it(\"add a decoding default to an optional field\", async () => {\n    const ps: S.PropertySignature<\":\", number, never, \"?:\", string, never> = S.makePropertySignature(\n      new S.PropertySignatureTransformation(\n        new S.FromPropertySignature(S.NumberFromString.ast, true, true, {}, undefined),\n        new S.ToPropertySignature(S.Number.ast, false, true, {}, undefined),\n        Option.orElse(() => Option.some(0)),\n        identity\n      )\n    )\n    const transform = S.Struct({ a: ps })\n    const schema = S.asSchema(transform)\n    await Util.assertions.decoding.succeed(schema, {}, { a: 0 })\n    await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: \"a\" },\n      `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n    )\n\n    await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: \"1\" })\n    await Util.assertions.encoding.succeed(schema, { a: 0 }, { a: \"0\" })\n  })\n\n  it(\"add a bidirectional (decoding/encoding) default to an optional field\", async () => {\n    const ps: S.PropertySignature<\":\", number, never, \"?:\", string, never> = S.makePropertySignature(\n      new S.PropertySignatureTransformation(\n        new S.FromPropertySignature(S.NumberFromString.ast, true, true, {}, undefined),\n        new S.ToPropertySignature(S.Number.ast, false, true, {}, undefined),\n        Option.orElse(() => Option.some(0)),\n        (o) => Option.flatMap(o, Option.liftPredicate((v) => v !== 0))\n      )\n    )\n    const transform = S.Struct({ a: ps })\n    const schema = S.asSchema(transform)\n    await Util.assertions.decoding.succeed(schema, {}, { a: 0 })\n    await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: \"a\" },\n      `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n    )\n\n    await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: \"1\" })\n    await Util.assertions.encoding.succeed(schema, { a: 0 }, {})\n  })\n\n  it(\"empty string as optional\", async () => {\n    const ps: S.PropertySignature<\"?:\", string, never, \":\", string, never> = S.makePropertySignature(\n      new S.PropertySignatureTransformation(\n        new S.FromPropertySignature(S.String.ast, false, true, {}, undefined),\n        new S.ToPropertySignature(S.String.ast, true, true, {}, undefined),\n        Option.flatMap(Option.liftPredicate((v) => v !== \"\")),\n        identity\n      )\n    )\n    const transform = S.Struct({ a: ps })\n    const schema = S.asSchema(transform)\n    await Util.assertions.decoding.succeed(schema, { a: \"\" }, {})\n    await Util.assertions.decoding.succeed(schema, { a: \"a\" }, { a: \"a\" })\n\n    await Util.assertions.encoding.succeed(schema, { a: \"a\" }, { a: \"a\" })\n  })\n\n  it(\"encoding default\", async () => {\n    const ps: S.PropertySignature<\"?:\", number, never, \":\", number, never> = S.makePropertySignature(\n      new S.PropertySignatureTransformation(\n        new S.FromPropertySignature(S.Number.ast, false, true, {}, undefined),\n        new S.ToPropertySignature(S.Number.ast, true, true, {}, undefined),\n        identity,\n        Option.orElse(() => Option.some(0))\n      )\n    )\n    const transform = S.Struct({ a: ps })\n    const schema = S.asSchema(transform)\n    await Util.assertions.decoding.succeed(schema, { a: 1 }, { a: 1 })\n    await Util.assertions.decoding.succeed(schema, { a: 0 }, { a: 0 })\n\n    await Util.assertions.encoding.succeed(schema, {}, { a: 0 })\n    await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: 1 })\n  })\n\n  describe(\"fromKey\", () => {\n    it(\"string key\", async () => {\n      const ps = S.propertySignature(S.Number).pipe(S.fromKey(\"b\"))\n      const transform = S.Struct({ a: ps })\n      const schema = S.asSchema(transform)\n      await Util.assertions.decoding.succeed(schema, { b: 1 }, { a: 1 }, { parseOptions: Util.onExcessPropertyError })\n\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { b: 1 }, { parseOptions: Util.onExcessPropertyError })\n    })\n\n    it(\"symbol key\", async () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const ps = S.propertySignature(S.Symbol).pipe(S.fromKey(a))\n      const transform = S.Struct({ a: ps })\n      const rename = S.asSchema(transform)\n      const schema = S.Struct({ b: S.Number }).pipe(S.extend(rename))\n\n      await Util.assertions.decoding.succeed(schema, { [a]: \"effect/Schema/test/a\", b: 1 }, { a, b: 1 })\n      await Util.assertions.encoding.succeed(schema, { a, b: 1 }, { [a]: \"effect/Schema/test/a\", b: 1 })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ReadonlyMap/ReadonlyMap.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"ReadonlyMap\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.ReadonlyMap({ key: S.Number, value: S.String }))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.ReadonlyMap({ key: S.Number, value: S.String })\n    await Util.assertions.decoding.succeed(schema, [], new Map())\n    await Util.assertions.decoding.succeed(\n      schema,\n      [[1, \"a\"], [2, \"b\"], [3, \"c\"]],\n      new Map([[1, \"a\"], [2, \"b\"], [3, \"c\"]])\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(ReadonlyArray<readonly [number, string]> <-> ReadonlyMap<number, string>)\n└─ Encoded side transformation failure\n   └─ Expected ReadonlyArray<readonly [number, string]>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      [[1, \"a\"], [2, 1]],\n      `(ReadonlyArray<readonly [number, string]> <-> ReadonlyMap<number, string>)\n└─ Encoded side transformation failure\n   └─ ReadonlyArray<readonly [number, string]>\n      └─ [1]\n         └─ readonly [number, string]\n            └─ [1]\n               └─ Expected string, actual 1`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.ReadonlyMap({ key: S.Number, value: S.String })\n    await Util.assertions.encoding.succeed(schema, new Map(), [])\n    await Util.assertions.encoding.succeed(schema, new Map([[1, \"a\"], [2, \"b\"], [3, \"c\"]]), [[1, \"a\"], [\n      2,\n      \"b\"\n    ], [3, \"c\"]])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ReadonlyMap/ReadonlyMapFromRecord.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"ReadonlyMapFromRecord\", () => {\n  it(\"decoding\", async () => {\n    const schema = S.ReadonlyMapFromRecord({ key: S.NumberFromString, value: S.NumberFromString })\n    await Util.assertions.decoding.succeed(schema, {}, new Map())\n    await Util.assertions.decoding.succeed(\n      schema,\n      { 1: \"2\", 3: \"4\", 5: \"6\" },\n      new Map([[1, 2], [3, 4], [5, 6]])\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(a record to be decoded into a ReadonlyMap <-> ReadonlyMap<NumberFromString, number>)\n└─ Encoded side transformation failure\n   └─ Expected a record to be decoded into a ReadonlyMap, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: \"1\" },\n      `(a record to be decoded into a ReadonlyMap <-> ReadonlyMap<NumberFromString, number>)\n└─ Type side transformation failure\n   └─ ReadonlyMap<NumberFromString, number>\n      └─ ReadonlyArray<readonly [NumberFromString, number]>\n         └─ [0]\n            └─ readonly [NumberFromString, number]\n               └─ [0]\n                  └─ NumberFromString\n                     └─ Transformation process failure\n                        └─ Unable to decode \"a\" into a number`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { 1: \"a\" },\n      `(a record to be decoded into a ReadonlyMap <-> ReadonlyMap<NumberFromString, number>)\n└─ Encoded side transformation failure\n   └─ a record to be decoded into a ReadonlyMap\n      └─ [\"1\"]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.ReadonlyMapFromRecord({ key: S.NumberFromString, value: S.NumberFromString })\n    await Util.assertions.encoding.succeed(schema, new Map(), {})\n    await Util.assertions.encoding.succeed(schema, new Map([[1, 2], [3, 4], [5, 6]]), { 1: \"2\", 3: \"4\", 5: \"6\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ReadonlyMap/ReadonlyMapFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"ReadonlyMapFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.ReadonlyMapFromSelf({ key: S.Number, value: S.String }))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.ReadonlyMapFromSelf({ key: S.NumberFromString, value: S.String })\n    await Util.assertions.decoding.succeed(schema, new Map(), new Map())\n    await Util.assertions.decoding.succeed(\n      schema,\n      new Map([[\"1\", \"a\"], [\"2\", \"b\"], [\"3\", \"c\"]]),\n      new Map([[1, \"a\"], [2, \"b\"], [3, \"c\"]])\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected ReadonlyMap<NumberFromString, string>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      new Map([[\"1\", \"a\"], [\"a\", \"b\"]]),\n      `ReadonlyMap<NumberFromString, string>\n└─ ReadonlyArray<readonly [NumberFromString, string]>\n   └─ [1]\n      └─ readonly [NumberFromString, string]\n         └─ [0]\n            └─ NumberFromString\n               └─ Transformation process failure\n                  └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.ReadonlyMapFromSelf({ key: S.NumberFromString, value: S.String })\n    await Util.assertions.encoding.succeed(schema, new Map(), new Map())\n    await Util.assertions.encoding.succeed(\n      schema,\n      new Map([[1, \"a\"], [2, \"b\"], [3, \"c\"]]),\n      new Map([[\"1\", \"a\"], [\"2\", \"b\"], [\"3\", \"c\"]])\n    )\n  })\n\n  it(\"is\", () => {\n    const schema = S.ReadonlyMapFromSelf({ key: S.Number, value: S.String })\n    const is = P.is(schema)\n    assertTrue(is(new Map()))\n    assertTrue(is(new Map([[1, \"a\"], [2, \"b\"], [3, \"c\"]])))\n\n    assertFalse(is(null))\n    assertFalse(is(undefined))\n    assertFalse(is(new Map<number, string | number>([[1, \"a\"], [2, 1]])))\n    assertFalse(is(new Map<number, string | number>([[1, 1], [2, \"b\"]])))\n    assertFalse(is(new Map([[1, 1], [2, 2]])))\n    assertFalse(is(new Map<string | number, number>([[\"a\", 1], [\"b\", 2], [3, 1]])))\n    assertFalse(is(new Map<number, string | number>([[1, \"a\"], [2, \"b\"], [3, 1]])))\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.ReadonlyMapFromSelf({ key: S.Number, value: S.String })\n    Util.assertions.pretty(schema, new Map(), \"new Map([])\")\n    Util.assertions.pretty(schema, new Map([[1, \"a\"], [2, \"b\"]]), `new Map([[1, \"a\"], [2, \"b\"]])`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ReadonlySet/ReadonlySet.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"ReadonlySet\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.ReadonlySet(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.ReadonlySet(S.Number)\n    await Util.assertions.decoding.succeed(schema, [], new Set([]))\n    await Util.assertions.decoding.succeed(schema, [1, 2, 3], new Set([1, 2, 3]))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(ReadonlyArray<number> <-> ReadonlySet<number>)\n└─ Encoded side transformation failure\n   └─ Expected ReadonlyArray<number>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      [1, \"a\"],\n      `(ReadonlyArray<number> <-> ReadonlySet<number>)\n└─ Encoded side transformation failure\n   └─ ReadonlyArray<number>\n      └─ [1]\n         └─ Expected number, actual \"a\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.ReadonlySet(S.Number)\n    await Util.assertions.encoding.succeed(schema, new Set(), [])\n    await Util.assertions.encoding.succeed(schema, new Set([1, 2, 3]), [1, 2, 3])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ReadonlySet/ReadonlySetFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"ReadonlySetFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.ReadonlySetFromSelf(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.ReadonlySetFromSelf(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, new Set(), new Set())\n    await Util.assertions.decoding.succeed(schema, new Set([\"1\", \"2\", \"3\"]), new Set([1, 2, 3]))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected ReadonlySet<NumberFromString>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      new Set([\"1\", \"a\", \"3\"]),\n      `ReadonlySet<NumberFromString>\n└─ ReadonlyArray<NumberFromString>\n   └─ [1]\n      └─ NumberFromString\n         └─ Transformation process failure\n            └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.ReadonlySetFromSelf(S.NumberFromString)\n    await Util.assertions.encoding.succeed(schema, new Set(), new Set())\n    await Util.assertions.encoding.succeed(schema, new Set([1, 2, 3]), new Set([\"1\", \"2\", \"3\"]))\n  })\n\n  it(\"is\", () => {\n    const schema = S.ReadonlySetFromSelf(S.String)\n    const is = P.is(schema)\n    assertTrue(is(new Set()))\n    assertTrue(is(new Set([\"a\", \"b\", \"c\"])))\n\n    assertFalse(is(new Set([\"a\", \"b\", 1])))\n    assertFalse(is(null))\n    assertFalse(is(undefined))\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.ReadonlySetFromSelf(S.String)\n    Util.assertions.pretty(schema, new Set(), \"new Set([])\")\n    Util.assertions.pretty(schema, new Set([\"a\", \"b\"]), `new Set([\"a\", \"b\"])`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Record/Record.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Either from \"effect/Either\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"record\", () => {\n  it(\"should expose the key and the value\", () => {\n    const schema = S.Record({ key: S.String, value: S.Number })\n    strictEqual(schema.key, S.String)\n    strictEqual(schema.value, S.Number)\n  })\n\n  it(\"should compute the partial result\", () => {\n    const schema = S.Record({ key: S.String, value: S.Number })\n    const all = S.decodeUnknownEither(schema)({ a: 1, b: \"b\", c: 2, d: \"d\" }, { errors: \"all\" })\n    if (Either.isLeft(all)) {\n      const issue = all.left.issue\n      if (ParseResult.isComposite(issue)) {\n        deepStrictEqual(issue.output, { a: 1, c: 2 })\n      } else {\n        throw new Error(\"expected an And\")\n      }\n    } else {\n      throw new Error(\"expected a Left\")\n    }\n    const first = S.decodeUnknownEither(schema)({ a: 1, b: \"b\", c: 2, d: \"d\" }, { errors: \"first\" })\n    if (Either.isLeft(first)) {\n      const issue = first.left.issue\n      if (ParseResult.isComposite(issue)) {\n        deepStrictEqual(issue.output, { a: 1 })\n      } else {\n        throw new Error(\"expected an And\")\n      }\n    } else {\n      throw new Error(\"expected a Left\")\n    }\n  })\n\n  describe(\"decoding\", () => {\n    it(\"Record(enum, number)\", async () => {\n      enum Abc {\n        A = 1,\n        B = \"b\",\n        C = \"c\"\n      }\n      const AbcSchema = S.Enums(Abc)\n      const schema = S.Record({ key: AbcSchema, value: S.String })\n      await Util.assertions.decoding.succeed(schema, { [Abc.A]: \"A\", [Abc.B]: \"B\", [Abc.C]: \"C\" })\n      await Util.assertions.decoding.succeed(schema, { [1]: \"A\", b: \"B\", c: \"C\" })\n      await Util.assertions.decoding.succeed(schema, { \"1\": \"A\", b: \"B\", c: \"C\" })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        { [Abc.B]: \"B\", [Abc.C]: \"C\" },\n        `{ readonly 1: string; readonly b: string; readonly c: string }\n└─ [1]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { [Abc.A]: \"A\", [Abc.B]: \"B\" },\n        `{ readonly 1: string; readonly b: string; readonly c: string }\n└─ [\"c\"]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { [Abc.A]: null, [Abc.B]: \"B\", [Abc.C]: \"C\" },\n        `{ readonly 1: string; readonly b: string; readonly c: string }\n└─ [1]\n   └─ Expected string, actual null`\n      )\n    })\n\n    it(\"Record(never, number)\", async () => {\n      const schema = S.Record({ key: S.Never, value: S.Number })\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { a: 1 })\n    })\n\n    it(\"Record(string, number)\", async () => {\n      const schema = S.Record({ key: S.String, value: S.Number })\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { a: 1 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        \"Expected { readonly [x: string]: number }, actual []\"\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `{ readonly [x: string]: number }\n└─ [\"a\"]\n   └─ Expected number, actual \"a\"`\n      )\n      const b = Symbol.for(\"effect/Schema/test/b\")\n      await Util.assertions.decoding.succeed(schema, { a: 1, [b]: \"b\" }, { a: 1 })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1, [b]: \"b\" },\n        `{ readonly [x: string]: number }\n└─ [Symbol(effect/Schema/test/b)]\n   └─ is unexpected, expected: string`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"Record(symbol, number)\", async () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const schema = S.Record({ key: S.SymbolFromSelf, value: S.Number })\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { [a]: 1 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        \"Expected { readonly [x: symbol]: number }, actual []\"\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { [a]: \"a\" },\n        `{ readonly [x: symbol]: number }\n└─ [Symbol(effect/Schema/test/a)]\n   └─ Expected number, actual \"a\"`\n      )\n      await Util.assertions.decoding.succeed(\n        schema,\n        { [a]: 1, b: \"b\" },\n        { [a]: 1 }\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { [a]: 1, b: \"b\" },\n        `{ readonly [x: symbol]: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: symbol`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"Record('a' | 'b', number)\", async () => {\n      const schema = S.Record({ key: S.Union(S.Literal(\"a\"), S.Literal(\"b\")), value: S.Number })\n      await Util.assertions.decoding.succeed(schema, { a: 1, b: 2 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        {},\n        `{ readonly a: number; readonly b: number }\n└─ [\"a\"]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1 },\n        `{ readonly a: number; readonly b: number }\n└─ [\"b\"]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { b: 2 },\n        `{ readonly a: number; readonly b: number }\n└─ [\"a\"]\n   └─ is missing`\n      )\n    })\n\n    it(\"Record('a' | `prefix-${string}`, number)\", async () => {\n      const schema = S.Record(\n        { key: S.Union(S.Literal(\"a\"), S.TemplateLiteral(S.Literal(\"prefix-\"), S.String)), value: S.Number }\n      )\n      await Util.assertions.decoding.succeed(schema, { a: 1 })\n      await Util.assertions.decoding.succeed(schema, { a: 1, \"prefix-b\": 2 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        {},\n        `{ readonly a: number; readonly [x: \\`prefix-\\${string}\\`]: number }\n└─ [\"a\"]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1, \"prefix-b\": \"b\" },\n        `{ readonly a: number; readonly [x: \\`prefix-\\${string}\\`]: number }\n└─ [\"prefix-b\"]\n   └─ Expected number, actual \"b\"`\n      )\n    })\n\n    it(\"Record(keyof struct({ a, b }), number)\", async () => {\n      const schema = S.Record({ key: S.keyof(S.Struct({ a: S.String, b: S.String })), value: S.Number })\n      await Util.assertions.decoding.succeed(schema, { a: 1, b: 2 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        {},\n        `{ readonly a: number; readonly b: number }\n└─ [\"a\"]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1 },\n        `{ readonly a: number; readonly b: number }\n└─ [\"b\"]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { b: 2 },\n        `{ readonly a: number; readonly b: number }\n└─ [\"a\"]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `{ readonly a: number; readonly b: number }\n└─ [\"a\"]\n   └─ Expected number, actual \"a\"`\n      )\n    })\n\n    it(\"Record(Symbol('a') | Symbol('b'), number)\", async () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const b = Symbol.for(\"effect/Schema/test/b\")\n      const schema = S.Record({ key: S.Union(S.UniqueSymbolFromSelf(a), S.UniqueSymbolFromSelf(b)), value: S.Number })\n      await Util.assertions.decoding.succeed(schema, { [a]: 1, [b]: 2 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        {},\n        `{ readonly Symbol(effect/Schema/test/a): number; readonly Symbol(effect/Schema/test/b): number }\n└─ [Symbol(effect/Schema/test/a)]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { [a]: 1 },\n        `{ readonly Symbol(effect/Schema/test/a): number; readonly Symbol(effect/Schema/test/b): number }\n└─ [Symbol(effect/Schema/test/b)]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { [b]: 2 },\n        `{ readonly Symbol(effect/Schema/test/a): number; readonly Symbol(effect/Schema/test/b): number }\n└─ [Symbol(effect/Schema/test/a)]\n   └─ is missing`\n      )\n    })\n\n    it(\"Record(${string}-${string}, number)\", async () => {\n      const schema = S.Record({ key: S.TemplateLiteral(S.String, S.Literal(\"-\"), S.String), value: S.Number })\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { \"-\": 1 })\n      await Util.assertions.decoding.succeed(schema, { \"a-\": 1 })\n      await Util.assertions.decoding.succeed(schema, { \"-b\": 1 })\n      await Util.assertions.decoding.succeed(schema, { \"a-b\": 1 })\n      await Util.assertions.decoding.succeed(schema, { \"\": 1 }, {})\n      await Util.assertions.decoding.succeed(schema, { \"a\": 1 }, {})\n      await Util.assertions.decoding.succeed(schema, { \"a\": \"a\" }, {})\n\n      await Util.assertions.decoding.fail(\n        schema,\n        { \"-\": \"a\" },\n        `{ readonly [x: \\`\\${string}-\\${string}\\`]: number }\n└─ [\"-\"]\n   └─ Expected number, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { \"a-\": \"a\" },\n        `{ readonly [x: \\`\\${string}-\\${string}\\`]: number }\n└─ [\"a-\"]\n   └─ Expected number, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { \"-b\": \"b\" },\n        `{ readonly [x: \\`\\${string}-\\${string}\\`]: number }\n└─ [\"-b\"]\n   └─ Expected number, actual \"b\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { \"a-b\": \"ab\" },\n        `{ readonly [x: \\`\\${string}-\\${string}\\`]: number }\n└─ [\"a-b\"]\n   └─ Expected number, actual \"ab\"`\n      )\n\n      await Util.assertions.decoding.fail(\n        schema,\n        { \"a\": 1 },\n        `{ readonly [x: \\`\\${string}-\\${string}\\`]: number }\n└─ [\"a\"]\n   └─ is unexpected, expected: \\`\\${string}-\\${string}\\``,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"Record(minLength(2), number)\", async () => {\n      const schema = S.Record({ key: S.String.pipe(S.minLength(2)), value: S.Number })\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { \"a\": 1 }, {})\n      await Util.assertions.decoding.succeed(schema, { \"a\": \"a\" }, {})\n      await Util.assertions.decoding.succeed(schema, { \"aa\": 1 })\n      await Util.assertions.decoding.succeed(schema, { \"aaa\": 1 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        { \"aa\": \"aa\" },\n        `{ readonly [x: minLength(2)]: number }\n└─ [\"aa\"]\n   └─ Expected number, actual \"aa\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { \"a\": 1 },\n        `{ readonly [x: minLength(2)]: number }\n└─ [\"a\"]\n   └─ is unexpected, expected: minLength(2)`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"Record(${string}-${string}, number) & record(string, string | number)\", async () => {\n      const schema = S.Struct(\n        {},\n        S.Record({ key: S.TemplateLiteral(S.String, S.Literal(\"-\"), S.String), value: S.Number }),\n        S.Record({ key: S.String, value: S.Union(S.String, S.Number) })\n      )\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { \"a\": \"a\" })\n      await Util.assertions.decoding.succeed(schema, { \"a-\": 1 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        { \"a-\": \"a\" },\n        `{ readonly [x: \\`\\${string}-\\${string}\\`]: number; readonly [x: string]: string | number }\n└─ [\"a-\"]\n   └─ Expected number, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { \"a\": true },\n        `{ readonly [x: \\`\\${string}-\\${string}\\`]: number; readonly [x: string]: string | number }\n└─ [\"a\"]\n   └─ string | number\n      ├─ Expected string, actual true\n      └─ Expected number, actual true`\n      )\n    })\n\n    it(\"should support branded keys\", async () => {\n      const schema = S.Record({ key: S.NonEmptyString.pipe(S.brand(\"UserId\")), value: S.Number })\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { \"a\": 1 })\n      await Util.assertions.decoding.succeed(schema, { \"\": 1 }, {})\n      await Util.assertions.decoding.succeed(schema, { \"\": \"\" }, {})\n\n      await Util.assertions.decoding.fail(\n        schema,\n        { \"\": 1 },\n        `{ readonly [x: nonEmptyString & Brand<\"UserId\">]: number }\n└─ [\"\"]\n   └─ is unexpected, expected: nonEmptyString & Brand<\"UserId\">`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n  })\n\n  describe(\"encoding\", () => {\n    it(\"key error\", async () => {\n      const schema = S.Record({ key: S.Char, value: S.String })\n      await Util.assertions.encoding.fail(\n        schema,\n        { aa: \"a\" },\n        `{ readonly [x: Char]: string }\n└─ [\"aa\"]\n   └─ is unexpected, expected: Char`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"value error\", async () => {\n      const schema = S.Record({ key: S.String, value: S.Char })\n      await Util.assertions.encoding.fail(\n        schema,\n        { a: \"aa\" },\n        `{ readonly [x: string]: Char }\n└─ [\"a\"]\n   └─ Char\n      └─ Predicate refinement failure\n         └─ Expected a single character, actual \"aa\"`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Redacted/Redacted.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Redacted } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Redacted\", () => {\n  const schema = S.Redacted(S.String)\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"arbitrary\", () => {\n    Util.assertions.arbitrary.validateGeneratedValues(S.RedactedFromSelf(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"keep me safe\",\n      Redacted.make(\"keep me safe\")\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      Redacted.make(123),\n      `(string <-> Redacted(<redacted>))\n└─ Encoded side transformation failure\n   └─ Expected string, actual <redacted>`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      Redacted.make(\"keep me safe\"),\n      \"keep me safe\"\n    )\n  })\n\n  it(\"Pretty\", () => {\n    Util.assertions.pretty(schema, Redacted.make(\"keep me safe\"), `Redacted(<redacted>)`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Redacted/RedactedFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Redacted } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"RedactedFromSelf\", () => {\n  const schema = S.RedactedFromSelf(S.String)\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"arbitrary\", () => {\n    Util.assertions.arbitrary.validateGeneratedValues(S.RedactedFromSelf(S.Number))\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      Redacted.make(\"keep me safe\"),\n      Redacted.make(\"keep me safe\")\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      Redacted.make(123),\n      `Redacted(<redacted>)\n└─ Expected string, actual 123`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      Redacted.make(\"keep me safe\"),\n      Redacted.make(\"keep me safe\")\n    )\n  })\n\n  it(\"Pretty\", () => {\n    Util.assertions.pretty(schema, Redacted.make(\"keep me safe\"), `Redacted(<redacted>)`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Set/Set.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"Set\", () => {\n  it(\"description\", () => {\n    strictEqual(String(S.Set(S.Number)), \"(ReadonlyArray<number> <-> Set<number>)\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Set/SetFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"SetFromSelf\", () => {\n  it(\"description\", () => {\n    strictEqual(String(S.SetFromSelf(S.Number)), \"Set<number>\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/SortedSet/SortedSet.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as N from \"effect/Number\"\nimport * as S from \"effect/Schema\"\nimport * as SortedSet from \"effect/SortedSet\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"SortedSet\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.SortedSet(S.Number, N.Order))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.SortedSet(S.Number, N.Order)\n    await Util.assertions.decoding.succeed(schema, [], SortedSet.fromIterable([] as Array<number>, N.Order))\n    await Util.assertions.decoding.succeed(\n      schema,\n      [1, 2, 3],\n      SortedSet.fromIterable([1, 2, 3] as Array<number>, N.Order)\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `(ReadonlyArray<number> <-> SortedSet<number>)\n└─ Encoded side transformation failure\n   └─ Expected ReadonlyArray<number>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      [1, \"a\"],\n      `(ReadonlyArray<number> <-> SortedSet<number>)\n└─ Encoded side transformation failure\n   └─ ReadonlyArray<number>\n      └─ [1]\n         └─ Expected number, actual \"a\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.SortedSet(S.Number, N.Order)\n    await Util.assertions.encoding.succeed(schema, SortedSet.fromIterable([] as Array<number>, N.Order), [])\n    await Util.assertions.encoding.succeed(schema, SortedSet.fromIterable([1, 2, 3] as Array<number>, N.Order), [\n      1,\n      2,\n      3\n    ])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/SortedSet/SortedSetFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as N from \"effect/Number\"\nimport * as P from \"effect/ParseResult\"\nimport * as Schema from \"effect/Schema\"\nimport * as SortedSet from \"effect/SortedSet\"\nimport * as S from \"effect/String\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"SortedSetFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(Schema.SortedSetFromSelf(Schema.Number, N.Order, N.Order))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = Schema.SortedSetFromSelf(Schema.NumberFromString, N.Order, S.Order)\n    await Util.assertions.decoding.succeed(\n      schema,\n      SortedSet.fromIterable([], S.Order),\n      SortedSet.fromIterable([] as Array<number>, N.Order)\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      SortedSet.fromIterable([\"1\", \"2\", \"3\"], S.Order),\n      SortedSet.fromIterable([1, 2, 3], N.Order)\n    )\n\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected SortedSet<NumberFromString>, actual null`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      SortedSet.fromIterable([\"1\", \"a\", \"3\"], S.Order),\n      `SortedSet<NumberFromString>\n└─ ReadonlyArray<NumberFromString>\n   └─ [2]\n      └─ NumberFromString\n         └─ Transformation process failure\n            └─ Unable to decode \"a\" into a number`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = Schema.SortedSetFromSelf(Schema.NumberFromString, N.Order, S.Order)\n    await Util.assertions.encoding.succeed(\n      schema,\n      SortedSet.fromIterable([] as Array<number>, N.Order),\n      SortedSet.fromIterable([] as Array<string>, S.Order)\n    )\n    await Util.assertions.encoding.succeed(\n      schema,\n      SortedSet.fromIterable([1, 2, 3], N.Order),\n      SortedSet.fromIterable([\"1\", \"2\", \"3\"], S.Order)\n    )\n  })\n\n  it(\"is\", () => {\n    const schema = Schema.SortedSetFromSelf(Schema.String, S.Order, S.Order)\n    const is = P.is(schema)\n    assertTrue(is(SortedSet.fromIterable([], S.Order)))\n    assertTrue(is(SortedSet.fromIterable([\"a\", \"b\", \"c\"], S.Order)))\n\n    assertFalse(is(new Set([\"a\", \"b\", 1])))\n    assertFalse(is(null))\n    assertFalse(is(undefined))\n  })\n\n  it(\"pretty\", () => {\n    const schema = Schema.SortedSetFromSelf(Schema.String, S.Order, S.Order)\n    Util.assertions.pretty(schema, SortedSet.fromIterable([] as Array<string>, S.Order), \"new SortedSet([])\")\n    Util.assertions.pretty(schema, SortedSet.fromIterable([\"a\", \"b\"], S.Order), `new SortedSet([\"a\", \"b\"])`)\n  })\n\n  it(\"equivalence\", () => {\n    const schema = Schema.SortedSetFromSelf(Schema.String, S.Order, S.Order)\n    const eq = Schema.equivalence(schema)\n\n    const a = SortedSet.fromIterable([] as Array<string>, S.Order)\n    const b = SortedSet.fromIterable([\"a\"] as Array<string>, S.Order)\n\n    assertTrue(eq(a, a))\n    assertFalse(eq(a, b))\n    assertFalse(eq(b, a))\n    assertTrue(eq(b, b))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/NonEmptyTrimmedString.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"NonEmptyTrimmedString\", () => {\n  it(\"test roundtrip consistency\", () => {\n    const schema = S.NonEmptyTrimmedString\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.NonEmptyTrimmedString\n    await Util.assertions.decoding.succeed(schema, \"a\", \"a\")\n\n    await Util.assertions.decoding.fail(\n      schema,\n      \" \",\n      `NonEmptyTrimmedString\n└─ From side refinement failure\n   └─ Trimmed\n      └─ Predicate refinement failure\n         └─ Expected a string with no leading or trailing whitespace, actual \" \"`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \" a \",\n      `NonEmptyTrimmedString\n└─ From side refinement failure\n   └─ Trimmed\n      └─ Predicate refinement failure\n         └─ Expected a string with no leading or trailing whitespace, actual \" a \"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.NonEmptyTrimmedString\n    await Util.assertions.encoding.succeed(schema, \"a\", \"a\")\n\n    await Util.assertions.encoding.fail(\n      schema,\n      \" \",\n      `NonEmptyTrimmedString\n└─ From side refinement failure\n   └─ Trimmed\n      └─ Predicate refinement failure\n         └─ Expected a string with no leading or trailing whitespace, actual \" \"`\n    )\n    await Util.assertions.encoding.fail(\n      schema,\n      \" a \",\n      `NonEmptyTrimmedString\n└─ From side refinement failure\n   └─ Trimmed\n      └─ Predicate refinement failure\n         └─ Expected a string with no leading or trailing whitespace, actual \" a \"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/String.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"String\", () => {\n  const schema = S.String\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, \"a\", \"a\")\n    await Util.assertions.decoding.fail(schema, 1, \"Expected string, actual 1\")\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, \"a\", \"a\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/StringFromBase64.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"StringFromBase64\", () => {\n  const schema = S.StringFromBase64\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"Zm9vYmFy\",\n      \"foobar\"\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"Zm9vY\",\n      `StringFromBase64\n└─ Transformation process failure\n   └─ Length must be a multiple of 4, but is 5`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"Zm9vYmF-\",\n      `StringFromBase64\n└─ Transformation process failure\n   └─ Invalid character -`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"=Zm9vYmF\",\n      `StringFromBase64\n└─ Transformation process failure\n   └─ Found a '=' character, but it is not at the end`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      \"foobar\",\n      \"Zm9vYmFy\"\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/StringFromBase64Url.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"StringFromBase64Url\", () => {\n  const schema = S.StringFromBase64Url\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"Zm9vYmFy\",\n      \"foobar\"\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"Pj8-ZD_Dnw\",\n      \">?>d?ß\"\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"Zm9vY\",\n      `StringFromBase64Url\n└─ Transformation process failure\n   └─ Length should be a multiple of 4, but is 5`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"Pj8/ZD+Dnw\",\n      `StringFromBase64Url\n└─ Transformation process failure\n   └─ Invalid input`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      \"foobar\",\n      \"Zm9vYmFy\"\n    )\n    await Util.assertions.encoding.succeed(\n      schema,\n      \">?>d?ß\",\n      \"Pj8-ZD_Dnw\"\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/StringFromHex.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"StringFromHex\", () => {\n  const schema = S.StringFromHex\n  const decoder = new TextDecoder(\"utf-8\")\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"0001020304050607\",\n      decoder.decode(Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7]))\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"f0f1f2f3f4f5f6f7\",\n      decoder.decode(Uint8Array.from([0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7]))\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"67\",\n      \"g\"\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"0\",\n      `StringFromHex\n└─ Transformation process failure\n   └─ Length must be a multiple of 2, but is 1`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"zd4aa\",\n      `StringFromHex\n└─ Transformation process failure\n   └─ Length must be a multiple of 2, but is 5`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"0\\x01\",\n      `StringFromHex\n└─ Transformation process failure\n   └─ Invalid input`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      decoder.decode(Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7])),\n      \"0001020304050607\"\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/StringFromUriComponent.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"StringFromUriComponent\", () => {\n  const schema = S.StringFromUriComponent\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, \"шеллы\", \"%D1%88%D0%B5%D0%BB%D0%BB%D1%8B\")\n    await Util.assertions.encoding.fail(\n      schema,\n      \"Hello\\uD800\",\n      `StringFromUriComponent\n└─ Transformation process failure\n   └─ URI malformed`\n    )\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, \"%D1%88%D0%B5%D0%BB%D0%BB%D1%8B\", \"шеллы\")\n    await Util.assertions.decoding.succeed(schema, \"hello\", \"hello\")\n    await Util.assertions.decoding.succeed(schema, \"hello%20world\", \"hello world\")\n\n    await Util.assertions.decoding.fail(\n      schema,\n      \"Hello%2world\",\n      `StringFromUriComponent\n└─ Transformation process failure\n   └─ URI malformed`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/capitalize.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Capitalize\", () => {\n  it(\"test roundtrip consistency\", () => {\n    const schema = S.Capitalize\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Capitalize\n    await Util.assertions.decoding.succeed(schema, \"aa\", \"Aa\")\n    await Util.assertions.decoding.succeed(schema, \"aa \", \"Aa \")\n    await Util.assertions.decoding.succeed(schema, \" aa \", \" aa \")\n    await Util.assertions.decoding.succeed(schema, \"\", \"\")\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.Capitalize\n    await Util.assertions.encoding.succeed(schema, \"\", \"\")\n    await Util.assertions.encoding.succeed(schema, \"Aa\", \"Aa\")\n\n    await Util.assertions.encoding.fail(\n      schema,\n      \"aa\",\n      `Capitalize\n└─ Type side transformation failure\n   └─ Capitalized\n      └─ Predicate refinement failure\n         └─ Expected a capitalized string, actual \"aa\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/endsWith.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"endsWith\", () => {\n  it(\"is\", () => {\n    const schema = S.String.pipe(S.endsWith(\"a\"))\n    const is = P.is(schema)\n    assertTrue(is(\"a\"))\n    assertTrue(is(\"ba\"))\n\n    assertFalse(is(\"\"))\n    assertFalse(is(\"b\"))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.String.pipe(S.endsWith(\"a\"))\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.succeed(schema, \"ba\")\n\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `endsWith(\"a\")\n└─ Predicate refinement failure\n   └─ Expected a string ending with \"a\", actual \"\"`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"b\",\n      `endsWith(\"a\")\n└─ Predicate refinement failure\n   └─ Expected a string ending with \"a\", actual \"b\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/includes.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"includes\", () => {\n  const schema = S.String.pipe(S.includes(\"a\"))\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"is\", () => {\n    const is = P.is(schema)\n    assertFalse(is(\"\"))\n    assertTrue(is(\"a\"))\n    assertTrue(is(\"aa\"))\n    assertTrue(is(\"bac\"))\n    assertTrue(is(\"ba\"))\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.succeed(schema, \"aa\")\n    await Util.assertions.decoding.succeed(schema, \"bac\")\n    await Util.assertions.decoding.succeed(schema, \"ba\")\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `includes(\"a\")\n└─ Predicate refinement failure\n   └─ Expected a string including \"a\", actual \"\"`\n    )\n  })\n\n  it(\"Pretty\", () => {\n    Util.assertions.pretty(schema, \"a\", `\"a\"`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/length.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"length\", () => {\n  describe(\"decoding\", () => {\n    it(\"length: 1\", async () => {\n      const schema = S.String.pipe(S.length(1, { identifier: \"Char\" }))\n      await Util.assertions.decoding.succeed(schema, \"a\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        `Char\n└─ Predicate refinement failure\n   └─ Expected a single character, actual \"\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"aa\",\n        `Char\n└─ Predicate refinement failure\n   └─ Expected a single character, actual \"aa\"`\n      )\n    })\n\n    it(\"length > 1\", async () => {\n      const schema = S.String.pipe(S.length(2, { identifier: \"Char2\" }))\n      await Util.assertions.decoding.succeed(schema, \"aa\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        `Char2\n└─ Predicate refinement failure\n   └─ Expected a string 2 character(s) long, actual \"\"`\n      )\n    })\n\n    it(\"length : { min > max }\", async () => {\n      const schema = S.String.pipe(S.length({ min: 2, max: 4 }, { identifier: \"Char(2-4)\" }))\n      await Util.assertions.decoding.succeed(schema, \"aa\")\n      await Util.assertions.decoding.succeed(schema, \"aaa\")\n      await Util.assertions.decoding.succeed(schema, \"aaaa\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        `Char(2-4)\n└─ Predicate refinement failure\n   └─ Expected a string at least 2 character(s) and at most 4 character(s) long, actual \"\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"aaaaa\",\n        `Char(2-4)\n└─ Predicate refinement failure\n   └─ Expected a string at least 2 character(s) and at most 4 character(s) long, actual \"aaaaa\"`\n      )\n    })\n\n    it(\"length : { min = max }\", async () => {\n      const schema = S.String.pipe(S.length({ min: 2, max: 2 }, { identifier: \"Char2\" }))\n      await Util.assertions.decoding.succeed(schema, \"aa\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        `Char2\n└─ Predicate refinement failure\n   └─ Expected a string 2 character(s) long, actual \"\"`\n      )\n    })\n\n    it(\"length : { min < max }\", async () => {\n      const schema = S.String.pipe(S.length({ min: 2, max: 1 }, { identifier: \"Char2\" }))\n      await Util.assertions.decoding.succeed(schema, \"aa\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        `Char2\n└─ Predicate refinement failure\n   └─ Expected a string 2 character(s) long, actual \"\"`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/lowercase.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Lowercase\", () => {\n  it(\"test roundtrip consistency\", () => {\n    const schema = S.Lowercase\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Lowercase\n    await Util.assertions.decoding.succeed(schema, \"a\", \"a\")\n    await Util.assertions.decoding.succeed(schema, \"A \", \"a \")\n    await Util.assertions.decoding.succeed(schema, \" A \", \" a \")\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.Lowercase\n    await Util.assertions.encoding.succeed(schema, \"\", \"\")\n    await Util.assertions.encoding.succeed(schema, \"a\", \"a\")\n\n    await Util.assertions.encoding.fail(\n      schema,\n      \"A\",\n      `Lowercase\n└─ Type side transformation failure\n   └─ Lowercased\n      └─ Predicate refinement failure\n         └─ Expected a lowercase string, actual \"A\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/maxLength.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"maxLength\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.String.pipe(S.maxLength(1)))\n  })\n\n  it(\"is\", () => {\n    const is = P.is(S.String.pipe(S.maxLength(1)))\n    assertTrue(is(\"\"))\n    assertTrue(is(\"a\"))\n    assertFalse(is(\"aa\"))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.String.pipe(S.maxLength(1))\n    await Util.assertions.decoding.succeed(schema, \"\")\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.fail(\n      schema,\n      \"aa\",\n      `maxLength(1)\n└─ Predicate refinement failure\n   └─ Expected a string at most 1 character(s) long, actual \"aa\"`\n    )\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.String.pipe(S.maxLength(1))\n    Util.assertions.pretty(schema, \"a\", `\"a\"`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/minLength.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"minLength\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.String.pipe(S.minLength(1)))\n  })\n\n  it(\"is\", () => {\n    const is = P.is(S.String.pipe(S.minLength(1)))\n    assertFalse(is(\"\"))\n    assertTrue(is(\"a\"))\n    assertTrue(is(\"aa\"))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.String.pipe(S.minLength(1))\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.succeed(schema, \"aa\")\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `minLength(1)\n└─ Predicate refinement failure\n   └─ Expected a string at least 1 character(s) long, actual \"\"`\n    )\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.String.pipe(S.minLength(1))\n    Util.assertions.pretty(schema, \"a\", `\"a\"`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/nonEmptyString.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"nonEmptyString\", () => {\n  const schema = S.NonEmptyString\n\n  it(\"make\", () => {\n    Util.assertions.make.succeed(S.NonEmptyString, \"a\")\n    Util.assertions.make.fail(\n      S.NonEmptyString,\n      \"\",\n      `NonEmptyString\n└─ Predicate refinement failure\n   └─ Expected a non empty string, actual \"\"`\n    )\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.succeed(schema, \"aa\")\n\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `NonEmptyString\n└─ Predicate refinement failure\n   └─ Expected a non empty string, actual \"\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/pattern.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"pattern\", () => {\n  it(\"is\", () => {\n    const schema = S.String.pipe(S.pattern(/^abb+$/))\n    const is = S.is(schema)\n    assertTrue(is(\"abb\"))\n    assertTrue(is(\"abbb\"))\n\n    assertFalse(is(\"ab\"))\n    assertFalse(is(\"a\"))\n  })\n\n  it(\"should reset lastIndex to 0 before each `test` call (#88)\", () => {\n    const regexp = /^(A|B)$/g\n    const schema = S.String.pipe(S.pattern(regexp))\n    strictEqual(S.decodeSync(schema)(\"A\"), \"A\")\n    strictEqual(S.decodeSync(schema)(\"A\"), \"A\")\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.String.pipe(S.pattern(/^abb+$/))\n    await Util.assertions.decoding.succeed(schema, \"abb\")\n    await Util.assertions.decoding.succeed(schema, \"abbb\")\n\n    await Util.assertions.decoding.fail(\n      schema,\n      \"ab\",\n      `a string matching the pattern ^abb+$\n└─ Predicate refinement failure\n   └─ Expected a string matching the pattern ^abb+$, actual \"ab\"`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a\",\n      `a string matching the pattern ^abb+$\n└─ Predicate refinement failure\n   └─ Expected a string matching the pattern ^abb+$, actual \"a\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/split.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"string/split\", () => {\n  it(\"split (data-last)\", async () => {\n    const schema = S.split(\",\")\n\n    Util.assertions.testRoundtripConsistency(schema)\n\n    // Decoding\n    await Util.assertions.decoding.succeed(schema, \"\", [\"\"])\n    await Util.assertions.decoding.succeed(schema, \",\", [\"\", \"\"])\n    await Util.assertions.decoding.succeed(schema, \"a\", [\"a\"])\n    await Util.assertions.decoding.succeed(schema, \",a\", [\"\", \"a\"])\n    await Util.assertions.decoding.succeed(schema, \"a,\", [\"a\", \"\"])\n    await Util.assertions.decoding.succeed(schema, \"a,b\", [\"a\", \"b\"])\n\n    // Encoding\n    await Util.assertions.encoding.succeed(schema, [], \"\")\n    await Util.assertions.encoding.succeed(schema, [\"\"], \"\")\n    await Util.assertions.encoding.succeed(schema, [\"\", \"\"], \",\")\n    await Util.assertions.encoding.succeed(schema, [\"a\"], \"a\")\n    await Util.assertions.encoding.succeed(schema, [\"\", \"a\"], \",a\")\n    await Util.assertions.encoding.succeed(schema, [\"a\", \"\"], \"a,\")\n    await Util.assertions.encoding.succeed(schema, [\"a\", \"b\"], \"a,b\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/startsWith.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"startsWith\", () => {\n  it(\"is\", () => {\n    const schema = S.String.pipe(S.startsWith(\"a\"))\n    const is = P.is(schema)\n    assertTrue(is(\"a\"))\n    assertTrue(is(\"ab\"))\n\n    assertFalse(is(\"\"))\n    assertFalse(is(\"b\"))\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.String.pipe(S.startsWith(\"a\"))\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.succeed(schema, \"ab\")\n\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `startsWith(\"a\")\n└─ Predicate refinement failure\n   └─ Expected a string starting with \"a\", actual \"\"`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"b\",\n      `startsWith(\"a\")\n└─ Predicate refinement failure\n   └─ Expected a string starting with \"a\", actual \"b\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/trim.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"trim\", () => {\n  it(\"test roundtrip consistency\", () => {\n    const schema = S.Trim\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.String.pipe(S.minLength(1), S.compose(S.Trim)).annotations({ identifier: \"MySchema\" })\n    await Util.assertions.decoding.succeed(schema, \"a\", \"a\")\n    await Util.assertions.decoding.succeed(schema, \"a \", \"a\")\n    await Util.assertions.decoding.succeed(schema, \" a \", \"a\")\n    await Util.assertions.decoding.succeed(schema, \" \", \"\")\n\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `MySchema\n└─ Encoded side transformation failure\n   └─ minLength(1)\n      └─ Predicate refinement failure\n         └─ Expected a string at least 1 character(s) long, actual \"\"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.String.pipe(S.minLength(1), S.compose(S.Trim)).annotations({ identifier: \"MySchema\" })\n    await Util.assertions.encoding.succeed(schema, \"a\", \"a\")\n\n    await Util.assertions.encoding.fail(\n      schema,\n      \"\",\n      `MySchema\n└─ Encoded side transformation failure\n   └─ minLength(1)\n      └─ Predicate refinement failure\n         └─ Expected a string at least 1 character(s) long, actual \"\"`\n    )\n    await Util.assertions.encoding.fail(\n      schema,\n      \" a\",\n      `MySchema\n└─ Type side transformation failure\n   └─ Trim\n      └─ Type side transformation failure\n         └─ Trimmed\n            └─ Predicate refinement failure\n               └─ Expected a string with no leading or trailing whitespace, actual \" a\"`\n    )\n    await Util.assertions.encoding.fail(\n      schema,\n      \"a \",\n      `MySchema\n└─ Type side transformation failure\n   └─ Trim\n      └─ Type side transformation failure\n         └─ Trimmed\n            └─ Predicate refinement failure\n               └─ Expected a string with no leading or trailing whitespace, actual \"a \"`\n    )\n    await Util.assertions.encoding.fail(\n      schema,\n      \" a \",\n      `MySchema\n└─ Type side transformation failure\n   └─ Trim\n      └─ Type side transformation failure\n         └─ Trimmed\n            └─ Predicate refinement failure\n               └─ Expected a string with no leading or trailing whitespace, actual \" a \"`\n    )\n    await Util.assertions.encoding.fail(\n      schema,\n      \" \",\n      `MySchema\n└─ Type side transformation failure\n   └─ Trim\n      └─ Type side transformation failure\n         └─ Trimmed\n            └─ Predicate refinement failure\n               └─ Expected a string with no leading or trailing whitespace, actual \" \"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/uncapitalize.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Uncapitalize\", () => {\n  it(\"test roundtrip consistency\", () => {\n    const schema = S.Uncapitalize\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Uncapitalize\n    await Util.assertions.decoding.succeed(schema, \"AA\", \"aA\")\n    await Util.assertions.decoding.succeed(schema, \"AA \", \"aA \")\n    await Util.assertions.decoding.succeed(schema, \" aa \", \" aa \")\n    await Util.assertions.decoding.succeed(schema, \"\", \"\")\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.Uncapitalize\n    await Util.assertions.encoding.succeed(schema, \"\", \"\")\n    await Util.assertions.encoding.succeed(schema, \"aA\", \"aA\")\n\n    await Util.assertions.encoding.fail(\n      schema,\n      \"AA\",\n      `Uncapitalize\n└─ Type side transformation failure\n   └─ Uncapitalized\n      └─ Predicate refinement failure\n         └─ Expected a uncapitalized string, actual \"AA\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/String/uppercase.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Uppercase\", () => {\n  it(\"test roundtrip consistency\", () => {\n    const schema = S.Uppercase\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.Uppercase\n    await Util.assertions.decoding.succeed(schema, \"A\", \"A\")\n    await Util.assertions.decoding.succeed(schema, \"a \", \"A \")\n    await Util.assertions.decoding.succeed(schema, \" a \", \" A \")\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.Uppercase\n    await Util.assertions.encoding.succeed(schema, \"\", \"\")\n    await Util.assertions.encoding.succeed(schema, \"A\", \"A\")\n\n    await Util.assertions.encoding.fail(\n      schema,\n      \"a\",\n      `Uppercase\n└─ Type side transformation failure\n   └─ Uppercased\n      └─ Predicate refinement failure\n         └─ Expected an uppercase string, actual \"a\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Struct/Struct.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Struct\", () => {\n  it(\"should expose the fields\", () => {\n    const schema = S.Struct({\n      a: S.String,\n      b: S.Number\n    })\n    deepStrictEqual(schema.fields, {\n      a: S.String,\n      b: S.Number\n    })\n  })\n\n  it(\"should return the literal interface when using the .annotations() method\", () => {\n    const schema = S.Struct({\n      a: S.String,\n      b: S.Number\n    }).annotations({ identifier: \"struct test\" })\n    deepStrictEqual(schema.ast.annotations, { [AST.IdentifierAnnotationId]: \"struct test\" })\n    deepStrictEqual(schema.fields, {\n      a: S.String,\n      b: S.Number\n    })\n  })\n\n  it(`should allow a \"constructor\" field name`, () => {\n    const schema = S.Struct({ constructor: S.String })\n    strictEqual(schema.ast._tag, \"TypeLiteral\")\n  })\n\n  describe(\"decoding\", () => {\n    it(\"should use annotations to generate a more informative error message when an incorrect data type is provided\", async () => {\n      const schema = S.Struct({}).annotations({ identifier: \"MyDataType\" })\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected MyDataType, actual null`\n      )\n    })\n\n    it(\"empty\", async () => {\n      const schema = S.Struct({})\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { a: 1 })\n      await Util.assertions.decoding.succeed(schema, [])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected {}, actual null`\n      )\n    })\n\n    it(\"required property signature\", async () => {\n      const schema = S.Struct({ a: S.Number })\n      await Util.assertions.decoding.succeed(schema, { a: 1 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected { readonly a: number }, actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        {},\n        `{ readonly a: number }\n└─ [\"a\"]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: undefined },\n        `{ readonly a: number }\n└─ [\"a\"]\n   └─ Expected number, actual undefined`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1, b: \"b\" },\n        `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"required property signature with undefined\", async () => {\n      const schema = S.Struct({ a: S.Union(S.Number, S.Undefined) })\n      await Util.assertions.decoding.succeed(schema, { a: 1 })\n      await Util.assertions.decoding.succeed(schema, { a: undefined })\n      await Util.assertions.decoding.succeed(schema, {}, { a: undefined })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected { readonly a: number | undefined }, actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `{ readonly a: number | undefined }\n└─ [\"a\"]\n   └─ number | undefined\n      ├─ Expected number, actual \"a\"\n      └─ Expected undefined, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1, b: \"b\" },\n        `{ readonly a: number | undefined }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"exact optional property signature\", async () => {\n      const schema = S.Struct({ a: S.optionalWith(S.Number, { exact: true }) })\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { a: 1 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected { readonly a?: number }, actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `{ readonly a?: number }\n└─ [\"a\"]\n   └─ Expected number, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: undefined },\n        `{ readonly a?: number }\n└─ [\"a\"]\n   └─ Expected number, actual undefined`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1, b: \"b\" },\n        `{ readonly a?: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"exact optional property signature with undefined\", async () => {\n      const schema = S.Struct({ a: S.optionalWith(S.Union(S.Number, S.Undefined), { exact: true }) })\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { a: 1 })\n      await Util.assertions.decoding.succeed(schema, { a: undefined })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected { readonly a?: number | undefined }, actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `{ readonly a?: number | undefined }\n└─ [\"a\"]\n   └─ number | undefined\n      ├─ Expected number, actual \"a\"\n      └─ Expected undefined, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1, b: \"b\" },\n        `{ readonly a?: number | undefined }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"should not add optional keys\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.String, { exact: true }),\n        b: S.optionalWith(S.Number, { exact: true })\n      })\n      await Util.assertions.decoding.succeed(schema, {})\n    })\n  })\n\n  describe(\"encoding\", () => {\n    it(\"empty\", async () => {\n      const schema = S.Struct({})\n      await Util.assertions.encoding.succeed(schema, {}, {})\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: 1 })\n      await Util.assertions.encoding.succeed(schema, [], [])\n\n      await Util.assertions.encoding.fail(\n        schema,\n        null as any,\n        `Expected {}, actual null`\n      )\n    })\n\n    it(\"required property signature\", async () => {\n      const schema = S.Struct({ a: S.Number })\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: 1 })\n      await Util.assertions.encoding.fail(\n        schema,\n        { a: 1, b: \"b\" } as any,\n        `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"required property signature with undefined\", async () => {\n      const schema = S.Struct({ a: S.Union(S.Number, S.Undefined) })\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: 1 })\n      await Util.assertions.encoding.succeed(schema, { a: undefined }, { a: undefined })\n      await Util.assertions.encoding.fail(\n        schema,\n        { a: 1, b: \"b\" } as any,\n        `{ readonly a: number | undefined }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"exact optional property signature\", async () => {\n      const schema = S.Struct({ a: S.optionalWith(S.Number, { exact: true }) })\n      await Util.assertions.encoding.succeed(schema, {}, {})\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: 1 })\n      await Util.assertions.encoding.fail(\n        schema,\n        { a: 1, b: \"b\" } as any,\n        `{ readonly a?: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"exact optional property signature with undefined\", async () => {\n      const schema = S.Struct({ a: S.optionalWith(S.Union(S.Number, S.Undefined), { exact: true }) })\n      await Util.assertions.encoding.succeed(schema, {}, {})\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: 1 })\n      await Util.assertions.encoding.succeed(schema, { a: undefined }, { a: undefined })\n      await Util.assertions.encoding.fail(\n        schema,\n        { a: 1, b: \"b\" } as any,\n        `{ readonly a?: number | undefined }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`,\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n\n    it(\"should handle symbols as keys\", async () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const schema = S.Struct({ [a]: S.String })\n      await Util.assertions.encoding.succeed(schema, { [a]: \"a\" }, { [a]: \"a\" })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Struct/make.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"make\", () => {\n  it(\"required fields\", () => {\n    const schema = S.Struct({ a: S.String })\n    Util.assertions.make.succeed(schema, { a: \"a\" })\n  })\n\n  it(\"optional fields\", () => {\n    const schema = S.Struct({ a: S.optional(S.String) })\n    Util.assertions.make.succeed(schema, { a: \"a\" })\n    Util.assertions.make.succeed(schema, {})\n  })\n\n  it(\"should validate the input by default\", () => {\n    const schema = S.Struct({ a: S.NonEmptyString })\n    Util.assertions.make.fail(\n      schema,\n      { a: \"\" },\n      `{ readonly a: NonEmptyString }\n└─ [\"a\"]\n   └─ NonEmptyString\n      └─ Predicate refinement failure\n         └─ Expected a non empty string, actual \"\"`\n    )\n  })\n\n  it(\"validation can be disabled\", () => {\n    const schema = S.Struct({ a: S.NonEmptyString })\n    deepStrictEqual(schema.make({ a: \"\" }, true), { a: \"\" })\n    deepStrictEqual(schema.make({ a: \"\" }, { disableValidation: true }), { a: \"\" })\n  })\n\n  it(\"should support defaults\", () => {\n    const schema = S.Struct({\n      a: S.propertySignature(S.Number).pipe(S.withConstructorDefault(() => 0))\n    })\n    deepStrictEqual(schema.make({}), { a: 0 })\n    deepStrictEqual(schema.make({ a: 1 }), { a: 1 })\n  })\n\n  it(\"should support lazy defaults\", () => {\n    let i = 0\n    const schema = S.Struct({\n      a: S.propertySignature(S.Number).pipe(S.withConstructorDefault(() => ++i))\n    })\n    deepStrictEqual(schema.make({}), { a: 1 })\n    deepStrictEqual(schema.make({}), { a: 2 })\n    schema.make({ a: 10 })\n    deepStrictEqual(schema.make({}), { a: 3 })\n  })\n\n  it(\"should treat `undefined` as missing field\", () => {\n    const schema = S.Struct({\n      a: S.propertySignature(S.UndefinedOr(S.Number)).pipe(S.withConstructorDefault(() => 0))\n    })\n    deepStrictEqual(schema.make({}), { a: 0 })\n    deepStrictEqual(schema.make({ a: undefined }), { a: 0 })\n  })\n\n  it(\"should accept void if the struct has no fields\", () => {\n    const schema = S.Struct({})\n    deepStrictEqual(schema.make({}), {})\n    deepStrictEqual(schema.make(undefined), {})\n    deepStrictEqual(schema.make(undefined, true), {})\n    deepStrictEqual(schema.make(undefined, false), {})\n    deepStrictEqual(schema.make(), {})\n  })\n\n  it(\"should accept void if the Class has all the fields with a default\", () => {\n    const schema = S.Struct({\n      a: S.propertySignature(S.Number).pipe(S.withConstructorDefault(() => 0))\n    })\n    deepStrictEqual(schema.make({}), { a: 0 })\n    deepStrictEqual(schema.make(undefined), { a: 0 })\n    deepStrictEqual(schema.make(undefined, true), { a: 0 })\n    deepStrictEqual(schema.make(undefined, false), { a: 0 })\n    deepStrictEqual(schema.make(), { a: 0 })\n  })\n\n  it(\"props declarations with defaults (data last)\", () => {\n    const b = Symbol.for(\"b\")\n    const schema = S.Struct({\n      a: S.String.pipe(S.propertySignature, S.withConstructorDefault(() => \"\")),\n      [b]: S.Number.pipe(S.propertySignature, S.withConstructorDefault(() => 0))\n    })\n    Util.assertions.make.succeed(schema, { a: \"a\", [b]: 2 })\n    Util.assertions.make.succeed(schema, { a: \"a\" }, { a: \"a\", [b]: 0 })\n    Util.assertions.make.succeed(schema, { [b]: 2 }, { a: \"\", [b]: 2 })\n    Util.assertions.make.succeed(schema, {}, { a: \"\", [b]: 0 })\n  })\n\n  it(\"props declarations with defaults (data first)\", () => {\n    const b = Symbol.for(\"b\")\n    const schema = S.Struct({\n      a: S.withConstructorDefault(S.propertySignature(S.String), () => \"\"),\n      [b]: S.withConstructorDefault(S.propertySignature(S.Number), () => 0)\n    })\n    Util.assertions.make.succeed(schema, { a: \"a\", [b]: 2 })\n    Util.assertions.make.succeed(schema, { a: \"a\" }, { a: \"a\", [b]: 0 })\n    Util.assertions.make.succeed(schema, { [b]: 2 }, { a: \"\", [b]: 2 })\n    Util.assertions.make.succeed(schema, {}, { a: \"\", [b]: 0 })\n  })\n\n  it(\"props transformations with defaults (data last)\", () => {\n    const b = Symbol.for(\"b\")\n    const schema = S.Struct({\n      a: S.String.pipe(S.optionalWith({ default: () => \"-\" }), S.withConstructorDefault(() => \"\")),\n      [b]: S.Number.pipe(S.optionalWith({ default: () => -1 }), S.withConstructorDefault(() => 0))\n    })\n    Util.assertions.make.succeed(schema, { a: \"a\", [b]: 2 })\n    Util.assertions.make.succeed(schema, { a: \"a\" }, { a: \"a\", [b]: 0 })\n    Util.assertions.make.succeed(schema, { [b]: 2 }, { a: \"\", [b]: 2 })\n    Util.assertions.make.succeed(schema, {}, { a: \"\", [b]: 0 })\n  })\n\n  it(\"withConstructorDefault + withDecodingDefault\", () => {\n    const schema = S.Struct({\n      a: S.optional(S.Number).pipe(S.withDecodingDefault(() => 1), S.withConstructorDefault(() => 0))\n    })\n    Util.assertions.make.succeed(schema, {}, { a: 0 })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Struct/omit.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"omit\", () => {\n  it(\"should work\", () => {\n    const schema = S.Struct({ a: S.String, b: S.Number, c: S.Boolean }).omit(\"c\")\n    deepStrictEqual(schema.fields, { a: S.String, b: S.Number })\n  })\n\n  it(\"should preserve index signatures on Struct with optionalWith default\", () => {\n    const schema = S.Struct(\n      { a: S.String, b: S.optionalWith(S.Number, { default: () => 0 }) },\n      S.Record({ key: S.String, value: S.Boolean })\n    )\n    const plain = S.Struct(\n      { a: S.String, b: S.Number },\n      S.Record({ key: S.String, value: S.Boolean })\n    )\n    deepStrictEqual(schema.pipe(S.omit(\"a\")).ast, plain.pipe(S.omit(\"a\")).ast)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Struct/pick.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"pick\", () => {\n  it(\"should work\", () => {\n    const schema = S.Struct({ a: S.String, b: S.Number, c: S.Boolean }).pick(\"a\", \"b\")\n    deepStrictEqual(schema.fields, { a: S.String, b: S.Number })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Symbol/Symbol.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Symbol\", () => {\n  const schema = S.Symbol\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, \"a\", Symbol.for(\"a\"))\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Symbol\n└─ Encoded side transformation failure\n   └─ Expected string, actual null`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, Symbol.for(\"a\"), \"a\")\n    await Util.assertions.encoding.fail(\n      schema,\n      Symbol(),\n      `Symbol\n└─ Transformation process failure\n   └─ Unable to encode a unique symbol Symbol() into a string`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Symbol/SymbolFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"SymbolFromSelf\", () => {\n  const schema = S.SymbolFromSelf\n  it(\"decoding\", async () => {\n    const a = Symbol.for(\"effect/Schema/test/a\")\n    await Util.assertions.decoding.succeed(schema, a)\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `Expected symbol, actual null`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const a = Symbol.for(\"effect/Schema/test/a\")\n    await Util.assertions.encoding.succeed(schema, a, a)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/TaggedStruct/make.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"make\", () => {\n  it(\"tag should be optional\", () => {\n    const schema = S.TaggedStruct(\"A\", { value: S.String })\n    deepStrictEqual(schema.make({ value: \"a\" }), { _tag: \"A\", value: \"a\" })\n  })\n\n  it(\"should support empty fields\", () => {\n    const schema = S.TaggedStruct(\"A\", {})\n    deepStrictEqual(schema.make({}), { _tag: \"A\" })\n  })\n\n  it(\"should expose the fields\", () => {\n    const schema = S.TaggedStruct(\"A\", { value: S.String })\n    Util.expectFields(schema.fields, { _tag: S.tag(\"A\"), value: S.String })\n  })\n\n  it(\"should support multiple tags\", () => {\n    const schema = S.TaggedStruct(\"A\", { category: S.tag(\"B\"), value: S.String })\n    deepStrictEqual(schema.make({ value: \"a\" }), { _tag: \"A\", category: \"B\", value: \"a\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/TemplateLiteral/TemplateLiteral.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual, throws } from \"@effect/vitest/utils\"\nimport * as A from \"effect/Arbitrary\"\nimport type * as array_ from \"effect/Array\"\nimport * as fc from \"effect/FastCheck\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../../TestUtils.js\"\n\ntype TemplateLiteralParameter = S.Schema.AnyNoContext | AST.LiteralValue\n\nconst expectPattern = (\n  params: array_.NonEmptyReadonlyArray<TemplateLiteralParameter>,\n  expectedPattern: string\n) => {\n  const ast = S.TemplateLiteral(...params).ast as AST.TemplateLiteral\n  strictEqual(AST.getTemplateLiteralRegExp(ast).source, expectedPattern)\n}\n\nconst expectAST = (\n  params: array_.NonEmptyReadonlyArray<TemplateLiteralParameter>,\n  expectedAST: AST.TemplateLiteral,\n  expectedString: string\n) => {\n  const ast = S.TemplateLiteral(...params).ast\n  deepStrictEqual(ast, expectedAST)\n  strictEqual(String(ast), expectedString)\n}\n\nconst expectProperty = <A>(\n  schema: S.Schema<A>,\n  params?: fc.Parameters<[A]>\n) => {\n  if (false as boolean) {\n    const arb = A.make(schema)\n    const is = S.is(schema)\n    fc.assert(fc.property(arb, (i) => is(i)), params)\n  }\n}\n\ndescribe(\"TemplateLiteral\", () => {\n  it(\"should throw on unsupported template literal spans\", () => {\n    throws(\n      () => S.TemplateLiteral(S.Boolean),\n      new Error(`Unsupported template literal span\nschema (BooleanKeyword): boolean`)\n    )\n\n    throws(\n      () => S.TemplateLiteral(S.Union(S.Boolean, S.SymbolFromSelf)),\n      new Error(`Unsupported template literal span\nschema (Union): boolean | symbol`)\n    )\n  })\n\n  it(\"getTemplateLiteralRegExp\", () => {\n    expectPattern([\"a\"], \"^a$\")\n    expectPattern([\"a\", \"b\"], \"^ab$\")\n    expectPattern([S.Literal(\"a\", \"b\"), \"c\"], \"^(a|b)c$\")\n    expectPattern([S.Literal(\"a\", \"b\"), \"c\", S.Literal(\"d\", \"e\")], \"^(a|b)c(d|e)$\")\n    expectPattern([S.Literal(\"a\", \"b\"), S.String, S.Literal(\"d\", \"e\")], \"^(a|b)[\\\\s\\\\S]*?(d|e)$\")\n    expectPattern([\"a\", S.String], \"^a[\\\\s\\\\S]*?$\")\n    expectPattern([\"a\", S.String, \"b\"], \"^a[\\\\s\\\\S]*?b$\")\n    expectPattern(\n      [\"a\", S.String, \"b\", S.Number],\n      \"^a[\\\\s\\\\S]*?b[+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?$\"\n    )\n    expectPattern([\"a\", S.Number], \"^a[+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?$\")\n    expectPattern([S.String, \"a\"], \"^[\\\\s\\\\S]*?a$\")\n    expectPattern([S.Number, \"a\"], \"^[+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?a$\")\n    expectPattern(\n      [S.Union(S.String, S.Literal(1)), S.Union(S.Number, S.Literal(true))],\n      \"^([\\\\s\\\\S]*?|1)([+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?|true)$\"\n    )\n    expectPattern([S.Union(S.Literal(\"a\", \"b\"), S.Literal(1, 2))], \"^(a|b|1|2)$\")\n    expectPattern([\"c\", S.Union(S.TemplateLiteral(\"a\", S.String, \"b\"), S.Literal(\"e\")), \"d\"], \"^c(a[\\\\s\\\\S]*?b|e)d$\")\n    expectPattern([\"<\", S.TemplateLiteral(\"h\", S.Literal(1, 2)), \">\"], \"^<h(1|2)>$\")\n    expectPattern(\n      [\"-\", S.Union(S.TemplateLiteral(\"a\", S.Literal(\"b\", \"c\")), S.TemplateLiteral(\"d\", S.Literal(\"e\", \"f\")))],\n      \"^-(a(b|c)|d(e|f))$\"\n    )\n  })\n\n  describe(\"AST and toString\", () => {\n    it(`\"a\"`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"\", [new AST.TemplateLiteralSpan(S.Literal(\"a\").ast, \"\")])\n      const expectedString = \"`a`\"\n      expectAST([S.Literal(\"a\")], expectedAST, expectedString)\n      expectAST([\"a\"], expectedAST, expectedString)\n    })\n\n    it(`\"a\" + \"b\"`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"a\", [new AST.TemplateLiteralSpan(S.Literal(\"b\").ast, \"\")])\n      const expectedString = \"`ab`\"\n      expectAST([S.Literal(\"a\"), S.Literal(\"b\")], expectedAST, expectedString)\n      expectAST([\"a\", \"b\"], expectedAST, expectedString)\n    })\n\n    it(`(\"a\" | \"b\") + \"c\"`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"\", [\n        new AST.TemplateLiteralSpan(S.Literal(\"a\", \"b\").ast, \"c\")\n      ])\n      const expectedString = \"`${\\\"a\\\" | \\\"b\\\"}c`\"\n      expectAST([S.Literal(\"a\", \"b\"), S.Literal(\"c\")], expectedAST, expectedString)\n      expectAST([S.Literal(\"a\", \"b\"), \"c\"], expectedAST, expectedString)\n    })\n\n    it(`(\"a\" | \"b) + \"c\" + (\"d\" | \"e\")`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"\", [\n        new AST.TemplateLiteralSpan(S.Literal(\"a\", \"b\").ast, \"c\"),\n        new AST.TemplateLiteralSpan(S.Literal(\"d\", \"e\").ast, \"\")\n      ])\n      const expectedString = \"`${\\\"a\\\" | \\\"b\\\"}c${\\\"d\\\" | \\\"e\\\"}`\"\n      expectAST([S.Literal(\"a\", \"b\"), S.Literal(\"c\"), S.Literal(\"d\", \"e\")], expectedAST, expectedString)\n      expectAST([S.Literal(\"a\", \"b\"), \"c\", S.Literal(\"d\", \"e\")], expectedAST, expectedString)\n    })\n\n    it(`(\"a\" | \"b\") + string + (\"d\" | \"e\")`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"\", [\n        new AST.TemplateLiteralSpan(S.Literal(\"a\", \"b\").ast, \"\"),\n        new AST.TemplateLiteralSpan(S.String.ast, \"\"),\n        new AST.TemplateLiteralSpan(S.Literal(\"d\", \"e\").ast, \"\")\n      ])\n      const expectedString = \"`${\\\"a\\\" | \\\"b\\\"}${string}${\\\"d\\\" | \\\"e\\\"}`\"\n      expectAST([S.Literal(\"a\", \"b\"), S.String, S.Literal(\"d\", \"e\")], expectedAST, expectedString)\n    })\n\n    it(`\"a\" + string`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"a\", [new AST.TemplateLiteralSpan(AST.stringKeyword, \"\")])\n      const expectedString = \"`a${string}`\"\n      expectAST([S.Literal(\"a\"), S.String], expectedAST, expectedString)\n      expectAST([\"a\", S.String], expectedAST, expectedString)\n    })\n\n    it(`\"a\" + string + \"b\"`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"a\", [\n        new AST.TemplateLiteralSpan(AST.stringKeyword, \"b\")\n      ])\n      const expectedString = \"`a${string}b`\"\n      expectAST([S.Literal(\"a\"), S.String, S.Literal(\"b\")], expectedAST, expectedString)\n      expectAST([\"a\", S.String, \"b\"], expectedAST, expectedString)\n    })\n\n    it(`\"a\" + string + \"b\" + number`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"a\", [\n        new AST.TemplateLiteralSpan(AST.stringKeyword, \"b\"),\n        new AST.TemplateLiteralSpan(AST.numberKeyword, \"\")\n      ])\n      const expectedString = \"`a${string}b${number}`\"\n      expectAST([S.Literal(\"a\"), S.String, S.Literal(\"b\"), S.Number], expectedAST, expectedString)\n      expectAST([\"a\", S.String, \"b\", S.Number], expectedAST, expectedString)\n    })\n\n    it(`\"a\" + number`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"a\", [new AST.TemplateLiteralSpan(AST.numberKeyword, \"\")])\n      const expectedString = \"`a${number}`\"\n      expectAST([S.Literal(\"a\"), S.Number], expectedAST, expectedString)\n      expectAST([\"a\", S.Number], expectedAST, expectedString)\n    })\n\n    it(`string + \"a\"`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"\", [new AST.TemplateLiteralSpan(AST.stringKeyword, \"a\")])\n      const expectedString = \"`${string}a`\"\n      expectAST([S.String, S.Literal(\"a\")], expectedAST, expectedString)\n      expectAST([S.String, \"a\"], expectedAST, expectedString)\n    })\n\n    it(`number + \"a\"`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"\", [new AST.TemplateLiteralSpan(AST.numberKeyword, \"a\")])\n      const expectedString = \"`${number}a`\"\n      expectAST([S.Number, S.Literal(\"a\")], expectedAST, expectedString)\n      expectAST([S.Number, \"a\"], expectedAST, expectedString)\n    })\n\n    it(`(string | 1) + (number | true)`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"\", [\n        new AST.TemplateLiteralSpan(S.Union(S.String, S.Literal(1)).ast, \"\"),\n        new AST.TemplateLiteralSpan(S.Union(S.Number, S.Literal(true)).ast, \"\")\n      ])\n      const expectedString = \"`${string | \\\"1\\\"}${number | \\\"true\\\"}`\"\n      expectAST([S.Union(S.String, S.Literal(1)), S.Union(S.Number, S.Literal(true))], expectedAST, expectedString)\n    })\n\n    it(`((\"a\" | \"b\") | \"c\")`, () => {\n      const expectedAST = new AST.TemplateLiteral(\"\", [\n        new AST.TemplateLiteralSpan(S.Union(S.Union(S.Literal(\"a\"), S.Literal(\"b\")), S.Literal(\"c\")).ast, \"\")\n      ])\n      const expectedString = \"`${\\\"a\\\" | \\\"b\\\" | \\\"c\\\"}`\"\n      expectAST([S.Union(S.Union(S.Literal(\"a\"), S.Literal(\"b\")), S.Literal(\"c\"))], expectedAST, expectedString)\n    })\n\n    it(\"`${string}`\", () => {\n      const expectedAST = new AST.TemplateLiteral(\"\", [new AST.TemplateLiteralSpan(S.String.ast, \"\")])\n      const expectedString = \"`${string}`\"\n      expectAST([S.String], expectedAST, expectedString)\n    })\n\n    it(\"`${number}`\", () => {\n      const expectedAST = new AST.TemplateLiteral(\"\", [new AST.TemplateLiteralSpan(S.Number.ast, \"\")])\n      const expectedString = \"`${number}`\"\n      expectAST([S.Number], expectedAST, expectedString)\n    })\n\n    it(\"`${`${string}`}`\", () => {\n      const schema = S.TemplateLiteral(S.String)\n      const expectedAST = new AST.TemplateLiteral(\"\", [\n        new AST.TemplateLiteralSpan(schema.ast, \"\")\n      ])\n      const expectedString = \"`${`${string}`}`\"\n      expectAST([schema], expectedAST, expectedString)\n    })\n\n    it(\"`${`${string}` | \\\"a\\\"}`\", () => {\n      const schema = S.Union(S.TemplateLiteral(S.String), S.Literal(\"a\"))\n      const expectedAST = new AST.TemplateLiteral(\"\", [\n        new AST.TemplateLiteralSpan(schema.ast, \"\")\n      ])\n      const expectedString = \"`${`${string}` | \\\"a\\\"}`\"\n      expectAST([schema], expectedAST, expectedString)\n    })\n  })\n\n  describe(\"decoding\", () => {\n    it(`\"a\"`, async () => {\n      const schema = S.TemplateLiteral(\"a\")\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"a\")\n\n      await Util.assertions.decoding.fail(schema, \"ab\", `Expected \\`a\\`, actual \"ab\"`)\n      await Util.assertions.decoding.fail(schema, \"\", `Expected \\`a\\`, actual \"\"`)\n      await Util.assertions.decoding.fail(schema, null, `Expected \\`a\\`, actual null`)\n    })\n\n    it(`\"a b\"`, async () => {\n      const schema = S.TemplateLiteral(\"a\", \" \", \"b\")\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"a b\")\n\n      await Util.assertions.decoding.fail(schema, \"a  b\", `Expected \\`a b\\`, actual \"a  b\"`)\n    })\n\n    it(`\"[\" + string + \"]\"`, async () => {\n      const schema = S.TemplateLiteral(\"[\", S.String, \"]\")\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"[a]\")\n\n      await Util.assertions.decoding.fail(schema, \"a\", \"Expected `[${string}]`, actual \\\"a\\\"\")\n    })\n\n    it(`\"a\" + string`, async () => {\n      const schema = S.TemplateLiteral(\"a\", S.String)\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"a\")\n      await Util.assertions.decoding.succeed(schema, \"ab\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        \"Expected `a${string}`, actual null\"\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        \"Expected `a${string}`, actual \\\"\\\"\"\n      )\n    })\n\n    it(`\"a\" + number`, async () => {\n      const schema = S.TemplateLiteral(\"a\", S.Number)\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"a1\")\n      await Util.assertions.decoding.succeed(schema, \"a1.2\")\n\n      await Util.assertions.decoding.succeed(schema, \"a-1.401298464324817e-45\")\n      await Util.assertions.decoding.succeed(schema, \"a1.401298464324817e-45\")\n      await Util.assertions.decoding.succeed(schema, \"a+1.401298464324817e-45\")\n      await Util.assertions.decoding.succeed(schema, \"a-1.401298464324817e+45\")\n      await Util.assertions.decoding.succeed(schema, \"a1.401298464324817e+45\")\n      await Util.assertions.decoding.succeed(schema, \"a+1.401298464324817e+45\")\n\n      await Util.assertions.decoding.succeed(schema, \"a-1.401298464324817E-45\")\n      await Util.assertions.decoding.succeed(schema, \"a1.401298464324817E-45\")\n      await Util.assertions.decoding.succeed(schema, \"a+1.401298464324817E-45\")\n      await Util.assertions.decoding.succeed(schema, \"a-1.401298464324817E+45\")\n      await Util.assertions.decoding.succeed(schema, \"a1.401298464324817E+45\")\n      await Util.assertions.decoding.succeed(schema, \"a+1.401298464324817E+45\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        \"Expected `a${number}`, actual null\"\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        \"Expected `a${number}`, actual \\\"\\\"\"\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"aa\",\n        \"Expected `a${number}`, actual \\\"aa\\\"\"\n      )\n    })\n\n    it(`string`, async () => {\n      const schema = S.TemplateLiteral(S.String)\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"a\")\n      await Util.assertions.decoding.succeed(schema, \"ab\")\n      await Util.assertions.decoding.succeed(schema, \"\")\n      await Util.assertions.decoding.succeed(schema, \"\\n\")\n      await Util.assertions.decoding.succeed(schema, \"\\r\")\n      await Util.assertions.decoding.succeed(schema, \"\\r\\n\")\n      await Util.assertions.decoding.succeed(schema, \"\\t\")\n    })\n\n    it(`\\\\n + string`, async () => {\n      const schema = S.TemplateLiteral(\"\\n\", S.String)\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"\\n\")\n      await Util.assertions.decoding.succeed(schema, \"\\na\")\n      await Util.assertions.decoding.fail(\n        schema,\n        \"a\",\n        \"Expected `\\n${string}`, actual \\\"a\\\"\"\n      )\n    })\n\n    it(`a\\\\nb  + string`, async () => {\n      const schema = S.TemplateLiteral(\"a\\nb \", S.String)\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"a\\nb \")\n      await Util.assertions.decoding.succeed(schema, \"a\\nb c\")\n    })\n\n    it(`\"a\" + string + \"b\"`, async () => {\n      const schema = S.TemplateLiteral(\"a\", S.String, \"b\")\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"ab\")\n      await Util.assertions.decoding.succeed(schema, \"acb\")\n      await Util.assertions.decoding.succeed(schema, \"abb\")\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        \"Expected `a${string}b`, actual \\\"\\\"\"\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"a\",\n        \"Expected `a${string}b`, actual \\\"a\\\"\"\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"b\",\n        \"Expected `a${string}b`, actual \\\"b\\\"\"\n      )\n      await Util.assertions.encoding.succeed(schema, \"acb\", \"acb\")\n    })\n\n    it(`\"a\" + string + \"b\" + string`, async () => {\n      const schema = S.TemplateLiteral(\"a\", S.String, \"b\", S.String)\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"ab\")\n      await Util.assertions.decoding.succeed(schema, \"acb\")\n      await Util.assertions.decoding.succeed(schema, \"acbd\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        \"a\",\n        \"Expected `a${string}b${string}`, actual \\\"a\\\"\"\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"b\",\n        \"Expected `a${string}b${string}`, actual \\\"b\\\"\"\n      )\n    })\n\n    it(\"https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html\", async () => {\n      const EmailLocaleIDs = S.Literal(\"welcome_email\", \"email_heading\")\n      const FooterLocaleIDs = S.Literal(\"footer_title\", \"footer_sendoff\")\n      const schema = S.TemplateLiteral(S.Union(EmailLocaleIDs, FooterLocaleIDs), \"_id\")\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"welcome_email_id\")\n      await Util.assertions.decoding.succeed(schema, \"email_heading_id\")\n      await Util.assertions.decoding.succeed(schema, \"footer_title_id\")\n      await Util.assertions.decoding.succeed(schema, \"footer_sendoff_id\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        \"_id\",\n        `Expected \\`\\${\"welcome_email\" | \"email_heading\" | \"footer_title\" | \"footer_sendoff\"}_id\\`, actual \"_id\"`\n      )\n    })\n\n    it(`string + 0`, async () => {\n      const schema = S.TemplateLiteral(S.String, 0)\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"a0\")\n      await Util.assertions.decoding.fail(schema, \"a\", \"Expected `${string}0`, actual \\\"a\\\"\")\n    })\n\n    it(`string + true`, async () => {\n      const schema = S.TemplateLiteral(S.String, true)\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"atrue\")\n      await Util.assertions.decoding.fail(schema, \"a\", \"Expected `${string}true`, actual \\\"a\\\"\")\n    })\n\n    it(`string + null`, async () => {\n      const schema = S.TemplateLiteral(S.String, null)\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"anull\")\n      await Util.assertions.decoding.fail(schema, \"a\", \"Expected `${string}null`, actual \\\"a\\\"\")\n    })\n\n    it(`string + 1n`, async () => {\n      const schema = S.TemplateLiteral(S.String, 1n)\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"a1\")\n      await Util.assertions.decoding.fail(schema, \"a\", \"Expected `${string}1`, actual \\\"a\\\"\")\n    })\n\n    it(`string + (\"a\" | 0)`, async () => {\n      const schema = S.TemplateLiteral(S.String, S.Literal(\"a\", 0))\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"a0\")\n      await Util.assertions.decoding.succeed(schema, \"aa\")\n      await Util.assertions.decoding.fail(\n        schema,\n        \"b\",\n        `Expected \\`\\${string}\\${\"a\" | \"0\"}\\`, actual \"b\"`\n      )\n    })\n\n    it(`(string | 1) + (number | true)`, async () => {\n      const schema = S.TemplateLiteral(S.Union(S.String, S.Literal(1)), S.Union(S.Number, S.Literal(true)))\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"atrue\")\n      await Util.assertions.decoding.succeed(schema, \"-2\")\n      await Util.assertions.decoding.succeed(schema, \"10.1\")\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        `Expected \\`\\${string | \"1\"}\\${number | \"true\"}\\`, actual \"\"`\n      )\n    })\n\n    it(\"`c${`a${string}b` | \\\"e\\\"}d`\", async () => {\n      const schema = S.TemplateLiteral(\n        \"c\",\n        S.Union(S.TemplateLiteral(\"a\", S.String, \"b\"), S.Literal(\"e\")),\n        \"d\"\n      )\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"ced\")\n      await Util.assertions.decoding.succeed(schema, \"cabd\")\n      await Util.assertions.decoding.succeed(schema, \"casbd\")\n      await Util.assertions.decoding.succeed(schema, \"ca  bd\")\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        \"Expected `c${`a${string}b` | \\\"e\\\"}d`, actual \\\"\\\"\"\n      )\n    })\n\n    it(\"< + h + (1|2) + >\", async () => {\n      const schema = S.TemplateLiteral(\"<\", S.TemplateLiteral(\"h\", S.Literal(1, 2)), \">\")\n      expectProperty(schema)\n      await Util.assertions.decoding.succeed(schema, \"<h1>\")\n      await Util.assertions.decoding.succeed(schema, \"<h2>\")\n      await Util.assertions.decoding.fail(schema, \"<h3>\", \"Expected `<${`h${\\\"1\\\" | \\\"2\\\"}`}>`, actual \\\"<h3>\\\"\")\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/TemplateLiteralParser.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual, throws } from \"@effect/vitest/utils\"\nimport type * as array_ from \"effect/Array\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../TestUtils.js\"\n\ntype TemplateLiteralParameter = S.Schema.AnyNoContext | AST.LiteralValue\n\nconst expectPattern = (\n  params: array_.NonEmptyReadonlyArray<TemplateLiteralParameter>,\n  expectedPattern: string\n) => {\n  const ast = S.TemplateLiteral(...params).ast as AST.TemplateLiteral\n  strictEqual(AST.getTemplateLiteralCapturingRegExp(ast).source, expectedPattern)\n}\n\ndescribe(\"TemplateLiteralParser\", () => {\n  it(\"should throw on unsupported template literal spans\", () => {\n    throws(\n      () => S.TemplateLiteralParser(S.Boolean),\n      new Error(`Unsupported template literal span\nschema (BooleanKeyword): boolean`)\n    )\n\n    throws(\n      () => S.TemplateLiteralParser(S.Union(S.Boolean, S.SymbolFromSelf)),\n      new Error(`Unsupported template literal span\nschema (Union): boolean | symbol`)\n    )\n  })\n\n  it(\"getTemplateLiteralCapturingRegExp\", () => {\n    expectPattern([\"a\"], \"^(a)$\")\n    expectPattern([\"a\", \"b\"], \"^(a)(b)$\")\n    expectPattern([S.Literal(\"a\", \"b\"), \"c\"], \"^(a|b)(c)$\")\n    expectPattern([S.Literal(\"a\", \"b\"), \"c\", S.Literal(\"d\", \"e\")], \"^(a|b)(c)(d|e)$\")\n    expectPattern([S.Literal(\"a\", \"b\"), S.String, S.Literal(\"d\", \"e\")], \"^(a|b)([\\\\s\\\\S]*?)(d|e)$\")\n    expectPattern([\"a\", S.String], \"^(a)([\\\\s\\\\S]*?)$\")\n    expectPattern([\"a\", S.String, \"b\"], \"^(a)([\\\\s\\\\S]*?)(b)$\")\n    expectPattern(\n      [\"a\", S.String, \"b\", S.Number],\n      \"^(a)([\\\\s\\\\S]*?)(b)([+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?)$\"\n    )\n    expectPattern([\"a\", S.Number], \"^(a)([+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?)$\")\n    expectPattern([S.String, \"a\"], \"^([\\\\s\\\\S]*?)(a)$\")\n    expectPattern([S.Number, \"a\"], \"^([+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?)(a)$\")\n    expectPattern([\n      S.Union(S.String, S.Literal(1)),\n      S.Union(S.Number, S.Literal(true))\n    ], \"^([\\\\s\\\\S]*?|1)([+-]?\\\\d*\\\\.?\\\\d+(?:[Ee][+-]?\\\\d+)?|true)$\")\n    expectPattern([S.Union(S.Literal(\"a\", \"b\"), S.Literal(1, 2))], \"^(a|b|1|2)$\")\n    expectPattern([\n      \"c\",\n      S.Union(S.TemplateLiteral(\"a\", S.String, \"b\"), S.Literal(\"e\")),\n      \"d\"\n    ], \"^(c)(a[\\\\s\\\\S]*?b|e)(d)$\")\n    expectPattern([\"<\", S.TemplateLiteral(\"h\", S.Literal(1, 2)), \">\"], \"^(<)(h(?:1|2))(>)$\")\n    expectPattern(\n      [\"-\", S.Union(S.TemplateLiteral(\"a\", S.Literal(\"b\", \"c\")), S.TemplateLiteral(\"d\", S.Literal(\"e\", \"f\")))],\n      \"^(-)(a(?:b|c)|d(?:e|f))$\"\n    )\n  })\n\n  it(\"should expose the params\", () => {\n    const params = [\"/\", S.Int, \"/\", S.String] as const\n    const schema = S.TemplateLiteralParser(...params)\n    deepStrictEqual(schema.params, params)\n  })\n\n  describe(\"decoding\", () => {\n    it(`\"a\"`, async () => {\n      const schema = S.TemplateLiteralParser(\"a\")\n\n      await Util.assertions.decoding.succeed(schema, \"a\", [\"a\"])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        `(\\`a\\` <-> readonly [\"a\"])\n└─ Encoded side transformation failure\n   └─ Expected \\`a\\`, actual \"\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, [\"a\"], \"a\")\n    })\n\n    it(`\"a\" + \"b\"`, async () => {\n      const schema = S.TemplateLiteralParser(\"a\", \"b\")\n\n      await Util.assertions.decoding.succeed(schema, \"ab\", [\"a\", \"b\"])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"a\",\n        `(\\`ab\\` <-> readonly [\"a\", \"b\"])\n└─ Encoded side transformation failure\n   └─ Expected \\`ab\\`, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, [\"a\", \"b\"], \"ab\")\n    })\n\n    it(`Int + \"a\"`, async () => {\n      const schema = S.TemplateLiteralParser(S.Int, \"a\")\n\n      await Util.assertions.decoding.succeed(schema, \"1a\", [1, \"a\"])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"1.1a\",\n        `(\\`\\${number}a\\` <-> readonly [Int, \"a\"])\n└─ Type side transformation failure\n   └─ readonly [Int, \"a\"]\n      └─ [0]\n         └─ (NumberFromString <-> Int)\n            └─ Type side transformation failure\n               └─ Int\n                  └─ Predicate refinement failure\n                     └─ Expected an integer, actual 1.1`\n      )\n\n      await Util.assertions.encoding.succeed(schema, [1, \"a\"], \"1a\")\n      await Util.assertions.encoding.fail(\n        schema,\n        [1.1, \"a\"],\n        `(\\`\\${number}a\\` <-> readonly [Int, \"a\"])\n└─ Type side transformation failure\n   └─ readonly [Int, \"a\"]\n      └─ [0]\n         └─ (NumberFromString <-> Int)\n            └─ Type side transformation failure\n               └─ Int\n                  └─ Predicate refinement failure\n                     └─ Expected an integer, actual 1.1`\n      )\n    })\n\n    it(`NumberFromString + \"a\" + NonEmptyString`, async () => {\n      const schema = S.TemplateLiteralParser(S.NumberFromString, \"a\", S.NonEmptyString)\n\n      await Util.assertions.decoding.succeed(schema, \"100ab\", [100, \"a\", \"b\"])\n      await Util.assertions.decoding.succeed(schema, \"100ab23a\", [100, \"a\", \"b23a\"])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"-ab\",\n        `(\\`\\${string}a\\${string}\\` <-> readonly [NumberFromString, \"a\", NonEmptyString])\n└─ Type side transformation failure\n   └─ readonly [NumberFromString, \"a\", NonEmptyString]\n      └─ [0]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"-\" into a number`\n      )\n\n      await Util.assertions.encoding.succeed(schema, [100, \"a\", \"b\"], \"100ab\")\n      await Util.assertions.encoding.fail(\n        schema,\n        [100, \"a\", \"\"],\n        `(\\`\\${string}a\\${string}\\` <-> readonly [NumberFromString, \"a\", NonEmptyString])\n└─ Type side transformation failure\n   └─ readonly [NumberFromString, \"a\", NonEmptyString]\n      └─ [2]\n         └─ NonEmptyString\n            └─ Predicate refinement failure\n               └─ Expected a non empty string, actual \"\"`\n      )\n    })\n\n    it(\"1\", async () => {\n      const schema = S.TemplateLiteralParser(1)\n      await Util.assertions.decoding.succeed(schema, \"1\", [1])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"1a\",\n        `(\\`1\\` <-> readonly [1])\n└─ Encoded side transformation failure\n   └─ Expected \\`1\\`, actual \"1a\"`\n      )\n    })\n\n    it(\"Literal(1)\", async () => {\n      const schema = S.TemplateLiteralParser(S.Literal(1))\n      await Util.assertions.decoding.succeed(schema, \"1\", [1])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"1a\",\n        `(\\`1\\` <-> readonly [1])\n└─ Encoded side transformation failure\n   └─ Expected \\`1\\`, actual \"1a\"`\n      )\n    })\n\n    it(\"1n\", async () => {\n      const schema = S.TemplateLiteralParser(1n)\n      await Util.assertions.decoding.succeed(schema, \"1\", [1n])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"1a\",\n        `(\\`1\\` <-> readonly [1n])\n└─ Encoded side transformation failure\n   └─ Expected \\`1\\`, actual \"1a\"`\n      )\n    })\n\n    it(\"Literal(1n)\", async () => {\n      const schema = S.TemplateLiteralParser(S.Literal(1n))\n      await Util.assertions.decoding.succeed(schema, \"1\", [1n])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"1a\",\n        `(\\`1\\` <-> readonly [1n])\n└─ Encoded side transformation failure\n   └─ Expected \\`1\\`, actual \"1a\"`\n      )\n    })\n\n    it(\"true\", async () => {\n      const schema = S.TemplateLiteralParser(true)\n      await Util.assertions.decoding.succeed(schema, \"true\", [true])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"truea\",\n        `(\\`true\\` <-> readonly [true])\n└─ Encoded side transformation failure\n   └─ Expected \\`true\\`, actual \"truea\"`\n      )\n    })\n\n    it(\"Literal(true)\", async () => {\n      const schema = S.TemplateLiteralParser(S.Literal(true))\n      await Util.assertions.decoding.succeed(schema, \"true\", [true])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"truea\",\n        `(\\`true\\` <-> readonly [true])\n└─ Encoded side transformation failure\n   └─ Expected \\`true\\`, actual \"truea\"`\n      )\n    })\n\n    it(\"false\", async () => {\n      const schema = S.TemplateLiteralParser(false)\n      await Util.assertions.decoding.succeed(schema, \"false\", [false])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"falsea\",\n        `(\\`false\\` <-> readonly [false])\n└─ Encoded side transformation failure\n   └─ Expected \\`false\\`, actual \"falsea\"`\n      )\n    })\n\n    it(\"Literal(false)\", async () => {\n      const schema = S.TemplateLiteralParser(S.Literal(false))\n      await Util.assertions.decoding.succeed(schema, \"false\", [false])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"falsea\",\n        `(\\`false\\` <-> readonly [false])\n└─ Encoded side transformation failure\n   └─ Expected \\`false\\`, actual \"falsea\"`\n      )\n    })\n\n    it(\"null\", async () => {\n      const schema = S.TemplateLiteralParser(null)\n      await Util.assertions.decoding.succeed(schema, \"null\", [null])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"nulla\",\n        `(\\`null\\` <-> readonly [null])\n└─ Encoded side transformation failure\n   └─ Expected \\`null\\`, actual \"nulla\"`\n      )\n    })\n\n    it(\"Literal(null)\", async () => {\n      const schema = S.TemplateLiteralParser(S.Literal(null))\n      await Util.assertions.decoding.succeed(schema, \"null\", [null])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"nulla\",\n        `(\\`null\\` <-> readonly [null])\n└─ Encoded side transformation failure\n   └─ Expected \\`null\\`, actual \"nulla\"`\n      )\n    })\n\n    it(\"1 | 2\", async () => {\n      const schema = S.TemplateLiteralParser(S.Literal(1, 2))\n      await Util.assertions.decoding.succeed(schema, \"1\", [1])\n      await Util.assertions.decoding.succeed(schema, \"2\", [2])\n    })\n\n    it(`\"h\" + (1 | 2 | 3)`, async () => {\n      const schema = S.TemplateLiteralParser(\"h\", S.Literal(1, 2, 3))\n      await Util.assertions.decoding.succeed(schema, \"h1\", [\"h\", 1])\n    })\n\n    it(`\"c\" + (\\`a\\${string}b\\`|\"e\") + \"d\"`, async () => {\n      const schema = S.TemplateLiteralParser(\n        \"c\",\n        S.Union(S.TemplateLiteralParser(\"a\", S.NonEmptyString, \"b\"), S.Literal(\"e\")),\n        \"d\"\n      )\n      await Util.assertions.decoding.succeed(schema, \"ca bd\", [\"c\", [\"a\", \" \", \"b\"], \"d\"])\n      await Util.assertions.decoding.succeed(schema, \"ced\", [\"c\", \"e\", \"d\"])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"cabd\",\n        `(\\`c\\${\\`a\\${string}b\\` | \"e\"}d\\` <-> readonly [\"c\", (\\`a\\${string}b\\` <-> readonly [\"a\", NonEmptyString, \"b\"]) | \"e\", \"d\"])\n└─ Type side transformation failure\n   └─ readonly [\"c\", (\\`a\\${string}b\\` <-> readonly [\"a\", NonEmptyString, \"b\"]) | \"e\", \"d\"]\n      └─ [1]\n         └─ (\\`a\\${string}b\\` <-> readonly [\"a\", NonEmptyString, \"b\"]) | \"e\"\n            ├─ (\\`a\\${string}b\\` <-> readonly [\"a\", NonEmptyString, \"b\"])\n            │  └─ Type side transformation failure\n            │     └─ readonly [\"a\", NonEmptyString, \"b\"]\n            │        └─ [1]\n            │           └─ NonEmptyString\n            │              └─ Predicate refinement failure\n            │                 └─ Expected a non empty string, actual \"\"\n            └─ Expected \"e\", actual \"ab\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"ed\",\n        `(\\`c\\${\\`a\\${string}b\\` | \"e\"}d\\` <-> readonly [\"c\", (\\`a\\${string}b\\` <-> readonly [\"a\", NonEmptyString, \"b\"]) | \"e\", \"d\"])\n└─ Encoded side transformation failure\n   └─ Expected \\`c\\${\\`a\\${string}b\\` | \"e\"}d\\`, actual \"ed\"`\n      )\n    })\n\n    it(`\"c\" + (\\`a\\${number}b\\`|\"e\") + \"d\"`, async () => {\n      const schema = S.TemplateLiteralParser(\n        \"c\",\n        S.Union(S.TemplateLiteralParser(\"a\", S.Int, \"b\"), S.Literal(\"e\")),\n        \"d\"\n      )\n      await Util.assertions.decoding.succeed(schema, \"ced\", [\"c\", \"e\", \"d\"])\n      await Util.assertions.decoding.succeed(schema, \"ca1bd\", [\"c\", [\"a\", 1, \"b\"], \"d\"])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"ca1.1bd\",\n        `(\\`c\\${\\`a\\${number}b\\` | \"e\"}d\\` <-> readonly [\"c\", (\\`a\\${number}b\\` <-> readonly [\"a\", Int, \"b\"]) | \"e\", \"d\"])\n└─ Type side transformation failure\n   └─ readonly [\"c\", (\\`a\\${number}b\\` <-> readonly [\"a\", Int, \"b\"]) | \"e\", \"d\"]\n      └─ [1]\n         └─ (\\`a\\${number}b\\` <-> readonly [\"a\", Int, \"b\"]) | \"e\"\n            ├─ (\\`a\\${number}b\\` <-> readonly [\"a\", Int, \"b\"])\n            │  └─ Type side transformation failure\n            │     └─ readonly [\"a\", Int, \"b\"]\n            │        └─ [1]\n            │           └─ (NumberFromString <-> Int)\n            │              └─ Type side transformation failure\n            │                 └─ Int\n            │                    └─ Predicate refinement failure\n            │                       └─ Expected an integer, actual 1.1\n            └─ Expected \"e\", actual \"a1.1b\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"ca-bd\",\n        `(\\`c\\${\\`a\\${number}b\\` | \"e\"}d\\` <-> readonly [\"c\", (\\`a\\${number}b\\` <-> readonly [\"a\", Int, \"b\"]) | \"e\", \"d\"])\n└─ Encoded side transformation failure\n   └─ Expected \\`c\\${\\`a\\${number}b\\` | \"e\"}d\\`, actual \"ca-bd\"`\n      )\n    })\n\n    it(\"(`<${`h${\\\"1\\\" | \\\"2\\\"}`}>` <-> readonly [\\\"<\\\", `h${\\\"1\\\" | \\\"2\\\"}`, \\\">\\\"])\", async () => {\n      const schema = S.TemplateLiteralParser(\"<\", S.TemplateLiteral(\"h\", S.Literal(1, 2)), \">\")\n      await Util.assertions.decoding.succeed(schema, \"<h1>\", [\"<\", \"h1\", \">\"])\n      await Util.assertions.decoding.succeed(schema, \"<h2>\", [\"<\", \"h2\", \">\"])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"<h3>\",\n        `(\\`<\\${\\`h\\${\"1\" | \"2\"}\\`}>\\` <-> readonly [\"<\", \\`h\\${\"1\" | \"2\"}\\`, \">\"])\n└─ Encoded side transformation failure\n   └─ Expected \\`<\\${\\`h\\${\"1\" | \"2\"}\\`}>\\`, actual \"<h3>\"`\n      )\n    })\n\n    it(\"(`<${`h${\\\"1\\\" | \\\"2\\\"}`}>` <-> readonly [\\\"<\\\", `h${\\\"1\\\" | \\\"2\\\"}`, \\\">\\\"])\", async () => {\n      const schema = S.TemplateLiteralParser(\"<\", S.TemplateLiteralParser(\"h\", S.Literal(1, 2)), \">\")\n      await Util.assertions.decoding.succeed(schema, \"<h1>\", [\"<\", [\"h\", 1], \">\"])\n      await Util.assertions.decoding.succeed(schema, \"<h2>\", [\"<\", [\"h\", 2], \">\"])\n      await Util.assertions.decoding.fail(\n        schema,\n        \"<h3>\",\n        `(\\`<\\${\\`h\\${\"1\" | \"2\"}\\`}>\\` <-> readonly [\"<\", (\\`h\\${\"1\" | \"2\"}\\` <-> readonly [\"h\", 1 | 2]), \">\"])\n└─ Encoded side transformation failure\n   └─ Expected \\`<\\${\\`h\\${\"1\" | \"2\"}\\`}>\\`, actual \"<h3>\"`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Trimmed/Trimmed.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport { Option, Predicate } from \"effect\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Trimmed\", () => {\n  const schema = S.Trimmed\n\n  it(\"pattern in JSONSchemaAnnotation\", () => {\n    const annotation = AST.getJSONSchemaAnnotation(schema.ast)\n    if (Option.isSome(annotation) && \"pattern\" in annotation.value && Predicate.isString(annotation.value.pattern)) {\n      const regexp = new RegExp(annotation.value.pattern)\n      const is = (s: string) => regexp.test(s)\n      assertTrue(is(\"hello\"))\n      assertFalse(is(\" hello\"))\n      assertFalse(is(\"hello \"))\n      assertFalse(is(\" hello \"))\n      assertTrue(is(\"h\"))\n      assertFalse(is(\" a b\"))\n      assertFalse(is(\"a b \"))\n      assertTrue(is(\"a b\"))\n      assertTrue(is(\"a  b\"))\n      assertTrue(is(\"\"))\n      assertFalse(is(\"\\n\"))\n      assertTrue(is(\"a\\nb\"))\n      assertFalse(is(\"a\\nb \"))\n      assertFalse(is(\" a\\nb\"))\n    }\n  })\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"is\", () => {\n    const is = P.is(schema)\n    assertTrue(is(\"a\"))\n    assertTrue(is(\"\"))\n    assertFalse(is(\"a \"))\n    assertFalse(is(\" a\"))\n    assertFalse(is(\" a \"))\n    assertFalse(is(\" \"))\n    assertFalse(is(\"\\n\"))\n    assertTrue(is(\"a\\nb\"))\n    assertFalse(is(\"a\\nb \"))\n    assertFalse(is(\" a\\nb\"))\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.succeed(schema, \"\")\n    await Util.assertions.decoding.fail(\n      schema,\n      \"a \",\n      `Trimmed\n└─ Predicate refinement failure\n   └─ Expected a string with no leading or trailing whitespace, actual \"a \"`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \" a\",\n      `Trimmed\n└─ Predicate refinement failure\n   └─ Expected a string with no leading or trailing whitespace, actual \" a\"`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \" a \",\n      `Trimmed\n└─ Predicate refinement failure\n   └─ Expected a string with no leading or trailing whitespace, actual \" a \"`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, \"a\", \"a\")\n    await Util.assertions.encoding.succeed(schema, \"\", \"\")\n    await Util.assertions.encoding.fail(\n      schema,\n      \"a \",\n      `Trimmed\n└─ Predicate refinement failure\n   └─ Expected a string with no leading or trailing whitespace, actual \"a \"`\n    )\n    await Util.assertions.encoding.fail(\n      schema,\n      \" a\",\n      `Trimmed\n└─ Predicate refinement failure\n   └─ Expected a string with no leading or trailing whitespace, actual \" a\"`\n    )\n    await Util.assertions.encoding.fail(\n      schema,\n      \" a \",\n      `Trimmed\n└─ Predicate refinement failure\n   └─ Expected a string with no leading or trailing whitespace, actual \" a \"`\n    )\n  })\n\n  it(\"pretty\", () => {\n    Util.assertions.pretty(schema, \"a\", `\"a\"`)\n    Util.assertions.pretty(schema, \"\", `\"\"`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Tuple/Tuple.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Tuple\", () => {\n  it(\"should expose the elements\", () => {\n    const schema = S.Tuple(S.String, S.Number)\n    deepStrictEqual(schema.elements, [S.String, S.Number])\n  })\n\n  describe(\"decoding\", () => {\n    it(\"should use annotations to generate a more informative error message when an incorrect data type is provided\", async () => {\n      const schema = S.Tuple().annotations({ identifier: \"MyDataType\" })\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected MyDataType, actual null`\n      )\n    })\n\n    it(\"empty\", async () => {\n      const schema = S.Tuple()\n      await Util.assertions.decoding.succeed(schema, [])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected readonly [], actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        {},\n        `Expected readonly [], actual {}`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [undefined],\n        `readonly []\n└─ [0]\n   └─ is unexpected, expected: never`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1],\n        `readonly []\n└─ [0]\n   └─ is unexpected, expected: never`\n      )\n    })\n\n    it(\"element\", async () => {\n      const schema = S.Tuple(S.Number)\n      await Util.assertions.decoding.succeed(schema, [1])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected readonly [number], actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        `readonly [number]\n└─ [0]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [undefined],\n        `readonly [number]\n└─ [0]\n   └─ Expected number, actual undefined`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\"],\n        `readonly [number]\n└─ [0]\n   └─ Expected number, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, \"b\"],\n        `readonly [number]\n└─ [1]\n   └─ is unexpected, expected: 0`\n      )\n    })\n\n    it(\"element with undefined\", async () => {\n      const schema = S.Tuple(S.Union(S.Number, S.Undefined))\n      await Util.assertions.decoding.succeed(schema, [1])\n      await Util.assertions.decoding.succeed(schema, [undefined])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected readonly [number | undefined], actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        `readonly [number | undefined]\n└─ [0]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\"],\n        `readonly [number | undefined]\n└─ [0]\n   └─ number | undefined\n      ├─ Expected number, actual \"a\"\n      └─ Expected undefined, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, \"b\"],\n        `readonly [number | undefined]\n└─ [1]\n   └─ is unexpected, expected: 0`\n      )\n    })\n\n    it(\"optional element\", async () => {\n      const schema = S.Tuple(S.optionalElement(S.Number))\n      await Util.assertions.decoding.succeed(schema, [])\n      await Util.assertions.decoding.succeed(schema, [1])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected readonly [number?], actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\"],\n        `readonly [number?]\n└─ [0]\n   └─ Expected number, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, \"b\"],\n        `readonly [number?]\n└─ [1]\n   └─ is unexpected, expected: 0`\n      )\n    })\n\n    it(\"optional element with undefined\", async () => {\n      const schema = S.Tuple(S.optionalElement(S.Union(S.Number, S.Undefined)))\n      await Util.assertions.decoding.succeed(schema, [])\n      await Util.assertions.decoding.succeed(schema, [1])\n      await Util.assertions.decoding.succeed(schema, [undefined])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected readonly [number | undefined?], actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\"],\n        `readonly [number | undefined?]\n└─ [0]\n   └─ number | undefined\n      ├─ Expected number, actual \"a\"\n      └─ Expected undefined, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, \"b\"],\n        `readonly [number | undefined?]\n└─ [1]\n   └─ is unexpected, expected: 0`\n      )\n    })\n\n    it(\"element / optional element\", async () => {\n      const schema = S.Tuple(S.String, S.optionalElement(S.Number))\n      await Util.assertions.decoding.succeed(schema, [\"a\"])\n      await Util.assertions.decoding.succeed(schema, [\"a\", 1])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [1],\n        `readonly [string, number?]\n└─ [0]\n   └─ Expected string, actual 1`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\", \"b\"],\n        `readonly [string, number?]\n└─ [1]\n   └─ Expected number, actual \"b\"`\n      )\n    })\n\n    it(\"e + r\", async () => {\n      const schema = S.Tuple([S.String], S.Number)\n      await Util.assertions.decoding.succeed(schema, [\"a\"])\n      await Util.assertions.decoding.succeed(schema, [\"a\", 1])\n      await Util.assertions.decoding.succeed(schema, [\"a\", 1, 2])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        `readonly [string, ...number[]]\n└─ [0]\n   └─ is missing`\n      )\n    })\n\n    it(\"e? + r\", async () => {\n      const schema = S.Tuple([S.optionalElement(S.String)], S.Number)\n      await Util.assertions.decoding.succeed(schema, [])\n      await Util.assertions.decoding.succeed(schema, [\"a\"])\n      await Util.assertions.decoding.succeed(schema, [\"a\", 1])\n      await Util.assertions.decoding.succeed(schema, [\"a\", 1, 2])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [1],\n        `readonly [string?, ...number[]]\n└─ [0]\n   └─ Expected string, actual 1`\n      )\n    })\n\n    it(\"rest\", async () => {\n      const schema = S.Array(S.Number)\n      await Util.assertions.decoding.succeed(schema, [])\n      await Util.assertions.decoding.succeed(schema, [1])\n      await Util.assertions.decoding.succeed(schema, [1, 2])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\"],\n        `ReadonlyArray<number>\n└─ [0]\n   └─ Expected number, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, \"a\"],\n        `ReadonlyArray<number>\n└─ [1]\n   └─ Expected number, actual \"a\"`\n      )\n    })\n\n    it(\"rest / element\", async () => {\n      const schema = S.Tuple([], S.String, S.Number)\n      await Util.assertions.decoding.succeed(schema, [1])\n      await Util.assertions.decoding.succeed(schema, [\"a\", 1])\n      await Util.assertions.decoding.succeed(schema, [\"a\", \"b\", 1])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        `readonly [...string[], number]\n└─ [0]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\"],\n        `readonly [...string[], number]\n└─ [0]\n   └─ Expected number, actual \"a\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, 2],\n        `readonly [...string[], number]\n└─ [0]\n   └─ Expected string, actual 1`\n      )\n    })\n\n    it(\"element / rest / element\", async () => {\n      const schema = S.Tuple([S.String], S.Number, S.Boolean)\n      await Util.assertions.decoding.succeed(schema, [\"a\", true])\n      await Util.assertions.decoding.succeed(schema, [\"a\", 1, true])\n      await Util.assertions.decoding.succeed(schema, [\"a\", 1, 2, true])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [],\n        `readonly [string, ...number[], boolean]\n└─ [0]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\"],\n        `readonly [string, ...number[], boolean]\n└─ [1]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\", 1],\n        `readonly [string, ...number[], boolean]\n└─ [1]\n   └─ Expected boolean, actual 1`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [1, true],\n        `readonly [string, ...number[], boolean]\n└─ [0]\n   └─ Expected string, actual 1`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        [true],\n        `readonly [string, ...number[], boolean]\n└─ [1]\n   └─ is missing`\n      )\n    })\n\n    it(\"[String] + [Boolean, String, Number, Number] validates every post-rest index\", async () => {\n      const schema = S.Tuple([S.String], S.Boolean, S.String, S.NumberFromString, S.NumberFromString)\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\", true, \"b\", \"1\", \"x\"],\n        `readonly [string, ...boolean[], string, NumberFromString, NumberFromString]\n└─ [4]\n   └─ NumberFromString\n      └─ Transformation process failure\n         └─ Unable to decode \"x\" into a number`\n      )\n      await Util.assertions.decoding.succeed(schema, [\"a\", true, \"b\", \"1\", \"2\"], [\"a\", true, \"b\", 1, 2])\n    })\n  })\n\n  describe(\"encoding\", () => {\n    it(\"empty\", async () => {\n      const schema = S.Tuple()\n      await Util.assertions.encoding.succeed(schema, [], [])\n    })\n\n    it(\"element\", async () => {\n      const schema = S.Tuple(Util.NumberFromChar)\n      await Util.assertions.encoding.succeed(schema, [1], [\"1\"])\n      await Util.assertions.encoding.fail(\n        schema,\n        [10],\n        `readonly [NumberFromChar]\n└─ [0]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n      )\n      await Util.assertions.encoding.fail(\n        schema,\n        [1, \"b\"] as any,\n        `readonly [NumberFromChar]\n└─ [1]\n   └─ is unexpected, expected: 0`\n      )\n    })\n\n    it(\"element with undefined\", async () => {\n      const schema = S.Tuple(S.Union(Util.NumberFromChar, S.Undefined))\n      await Util.assertions.encoding.succeed(schema, [1], [\"1\"])\n      await Util.assertions.encoding.succeed(schema, [undefined], [undefined])\n      await Util.assertions.encoding.fail(\n        schema,\n        [1, \"b\"] as any,\n        `readonly [NumberFromChar | undefined]\n└─ [1]\n   └─ is unexpected, expected: 0`\n      )\n    })\n\n    it(\"optional element\", async () => {\n      const schema = S.Tuple(S.optionalElement(Util.NumberFromChar))\n      await Util.assertions.encoding.succeed(schema, [], [])\n      await Util.assertions.encoding.succeed(schema, [1], [\"1\"])\n      await Util.assertions.encoding.fail(\n        schema,\n        [10],\n        `readonly [NumberFromChar?]\n└─ [0]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n      )\n      await Util.assertions.encoding.fail(\n        schema,\n        [1, \"b\"] as any,\n        `readonly [NumberFromChar?]\n└─ [1]\n   └─ is unexpected, expected: 0`\n      )\n    })\n\n    it(\"optional element with undefined\", async () => {\n      const schema = S.Tuple(S.optionalElement(S.Union(Util.NumberFromChar, S.Undefined)))\n      await Util.assertions.encoding.succeed(schema, [], [])\n      await Util.assertions.encoding.succeed(schema, [1], [\"1\"])\n      await Util.assertions.encoding.succeed(schema, [undefined], [undefined])\n      await Util.assertions.encoding.fail(\n        schema,\n        [1, \"b\"] as any,\n        `readonly [NumberFromChar | undefined?]\n└─ [1]\n   └─ is unexpected, expected: 0`\n      )\n    })\n\n    it(\"element / optional element\", async () => {\n      const schema = S.Tuple(S.String, S.optionalElement(Util.NumberFromChar))\n      await Util.assertions.encoding.succeed(schema, [\"a\"], [\"a\"])\n      await Util.assertions.encoding.succeed(schema, [\"a\", 1], [\"a\", \"1\"])\n    })\n\n    it(\"e + r\", async () => {\n      const schema = S.Tuple([S.String], Util.NumberFromChar)\n      await Util.assertions.encoding.succeed(schema, [\"a\"], [\"a\"])\n      await Util.assertions.encoding.succeed(schema, [\"a\", 1], [\"a\", \"1\"])\n      await Util.assertions.encoding.succeed(schema, [\"a\", 1, 2], [\"a\", \"1\", \"2\"])\n    })\n\n    it(\"e? + r\", async () => {\n      const schema = S.Tuple([S.optionalElement(S.String)], Util.NumberFromChar)\n      await Util.assertions.encoding.succeed(schema, [], [])\n      await Util.assertions.encoding.succeed(schema, [\"a\"], [\"a\"])\n      await Util.assertions.encoding.succeed(schema, [\"a\", 1], [\"a\", \"1\"])\n      await Util.assertions.encoding.succeed(schema, [\"a\", 1, 2], [\"a\", \"1\", \"2\"])\n    })\n\n    it(\"rest\", async () => {\n      const schema = S.Array(Util.NumberFromChar)\n      await Util.assertions.encoding.succeed(schema, [], [])\n      await Util.assertions.encoding.succeed(schema, [1], [\"1\"])\n      await Util.assertions.encoding.succeed(schema, [1, 2], [\"1\", \"2\"])\n      await Util.assertions.encoding.fail(\n        schema,\n        [10],\n        `ReadonlyArray<NumberFromChar>\n└─ [0]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n      )\n    })\n\n    it(\"rest / element\", async () => {\n      const schema = S.Tuple([], S.String, Util.NumberFromChar)\n      await Util.assertions.encoding.succeed(schema, [1], [\"1\"])\n      await Util.assertions.encoding.succeed(schema, [\"a\", 1], [\"a\", \"1\"])\n      await Util.assertions.encoding.succeed(schema, [\"a\", \"b\", 1], [\"a\", \"b\", \"1\"])\n      await Util.assertions.encoding.fail(\n        schema,\n        [] as any,\n        `readonly [...string[], NumberFromChar]\n└─ [0]\n   └─ is missing`\n      )\n      await Util.assertions.encoding.fail(\n        schema,\n        [10],\n        `readonly [...string[], NumberFromChar]\n└─ [0]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n      )\n    })\n\n    it(\"element / rest / element\", async () => {\n      const schema = S.Tuple([S.String], Util.NumberFromChar, S.Boolean)\n      await Util.assertions.encoding.succeed(schema, [\"a\", true], [\"a\", true])\n      await Util.assertions.encoding.succeed(schema, [\"a\", 1, true], [\"a\", \"1\", true])\n      await Util.assertions.encoding.succeed(schema, [\"a\", 1, 2, true], [\"a\", \"1\", \"2\", true])\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/ULID.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"ULID\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.ULID)\n  })\n\n  it(\"Decoder\", async () => {\n    const schema = S.ULID\n    await Util.assertions.decoding.succeed(schema, \"01H4PGGGJVN2DKP2K1H7EH996V\")\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `ULID\n└─ Predicate refinement failure\n   └─ Expected a Universally Unique Lexicographically Sortable Identifier, actual \"\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/URL/URL.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"URL\", () => {\n  const schema = S.URL\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"arbitrary\", () => {\n    Util.assertions.arbitrary.validateGeneratedValues(S.URL)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"http://effect.website\",\n      new URL(\"http://effect.website\")\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"123\",\n      `URL\n└─ Transformation process failure\n   └─ Unable to decode \"123\" into a URL. Invalid URL`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      new URL(\"https://effecty.website\"),\n      \"https://effecty.website/\"\n    )\n  })\n\n  it(\"Pretty\", () => {\n    const input = \"https://effecty.website:443\"\n    const prettified = \"https://effecty.website/\"\n    Util.assertions.pretty(schema, new URL(input), prettified)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/URL/URLFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"URLFromSelf\", () => {\n  const schema = S.URLFromSelf\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"arbitrary\", () => {\n    Util.assertions.arbitrary.validateGeneratedValues(S.URLFromSelf)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      new URL(\"https://effect.website\"),\n      new URL(\"https://effect.website\")\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      new URL(\"https://effect.website\"),\n      new URL(\"https://effect.website\")\n    )\n  })\n\n  it(\"Pretty\", () => {\n    Util.assertions.pretty(schema, new URL(\"https://effect.website\"), `https://effect.website/`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/UUID.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"string/UUID\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.UUID)\n  })\n\n  it(\"Decoder\", async () => {\n    const schema = S.UUID\n    await Util.assertions.decoding.succeed(schema, \"123e4567-e89b-12d3-a456-426614174000\")\n    await Util.assertions.decoding.fail(\n      schema,\n      \"\",\n      `UUID\n└─ Predicate refinement failure\n   └─ Expected a Universally Unique Identifier, actual \"\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Uint8Array/Uint8Array.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Uint8Array > Uint8Array\", () => {\n  const schema = S.Uint8Array\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"isSchema\", () => {\n    assertTrue(S.isSchema(schema))\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, [0, 1, 2, 3], Uint8Array.from([0, 1, 2, 3]))\n    await Util.assertions.decoding.fail(\n      schema,\n      [12354],\n      `Uint8Array\n└─ Encoded side transformation failure\n   └─ an array of 8-bit unsigned integers to be decoded into a Uint8Array\n      └─ [0]\n         └─ Uint8\n            └─ Predicate refinement failure\n               └─ Expected a 8-bit unsigned integer, actual 12354`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(schema, Uint8Array.from([0, 1, 2, 3]), [0, 1, 2, 3])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Uint8Array/Uint8ArrayFromBase64.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Uint8ArrayFromBase64\", () => {\n  const schema = S.Uint8ArrayFromBase64\n  const encoder = new TextEncoder()\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"Zm9vYmFy\",\n      encoder.encode(\"foobar\")\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"Zm9vY\",\n      `Uint8ArrayFromBase64\n└─ Transformation process failure\n   └─ Length must be a multiple of 4, but is 5`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"Zm9vYmF-\",\n      `Uint8ArrayFromBase64\n└─ Transformation process failure\n   └─ Invalid character -`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"=Zm9vYmF\",\n      `Uint8ArrayFromBase64\n└─ Transformation process failure\n   └─ Found a '=' character, but it is not at the end`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      encoder.encode(\"foobar\"),\n      \"Zm9vYmFy\"\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Uint8Array/Uint8ArrayFromBase64Url.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Uint8ArrayFromBase64Url\", () => {\n  const schema = S.Uint8ArrayFromBase64Url\n  const encoder = new TextEncoder()\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"Zm9vYmFy\",\n      encoder.encode(\"foobar\")\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"Pj8-ZD_Dnw\",\n      encoder.encode(\">?>d?ß\")\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"Zm9vY\",\n      `Uint8ArrayFromBase64Url\n└─ Transformation process failure\n   └─ Length should be a multiple of 4, but is 5`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"Pj8/ZD+Dnw\",\n      `Uint8ArrayFromBase64Url\n└─ Transformation process failure\n   └─ Invalid input`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      encoder.encode(\"foobar\"),\n      \"Zm9vYmFy\"\n    )\n    await Util.assertions.encoding.succeed(\n      schema,\n      encoder.encode(\">?>d?ß\"),\n      \"Pj8-ZD_Dnw\"\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Uint8Array/Uint8ArrayFromHex.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Uint8ArrayFromHex\", () => {\n  const schema = S.Uint8ArrayFromHex\n  const encoder = new TextEncoder()\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(schema)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"0001020304050607\",\n      Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7])\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"f0f1f2f3f4f5f6f7\",\n      Uint8Array.from([0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7])\n    )\n    await Util.assertions.decoding.succeed(\n      schema,\n      \"67\",\n      encoder.encode(\"g\")\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"0\",\n      `Uint8ArrayFromHex\n└─ Transformation process failure\n   └─ Length must be a multiple of 2, but is 1`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"zd4aa\",\n      `Uint8ArrayFromHex\n└─ Transformation process failure\n   └─ Length must be a multiple of 2, but is 5`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      \"0\\x01\",\n      `Uint8ArrayFromHex\n└─ Transformation process failure\n   └─ Invalid input`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    await Util.assertions.encoding.succeed(\n      schema,\n      Uint8Array.from([0, 1, 2, 3, 4, 5, 6, 7]),\n      \"0001020304050607\"\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Uint8Array/Uint8ArrayFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Uint8Array > Uint8ArrayFromSelf\", () => {\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Uint8ArrayFromSelf)\n  })\n\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(S.Uint8ArrayFromSelf, new Uint8Array(), new Uint8Array())\n    await Util.assertions.decoding.fail(\n      S.Uint8ArrayFromSelf,\n      null,\n      `Expected Uint8ArrayFromSelf, actual null`\n    )\n  })\n\n  it(\"encoding\", async () => {\n    const u8arr = Uint8Array.from([0, 1, 2, 3])\n    await Util.assertions.encoding.succeed(S.Uint8ArrayFromSelf, u8arr, u8arr)\n  })\n\n  it(\"pretty\", () => {\n    const schema = S.Uint8ArrayFromSelf\n    Util.assertions.pretty(schema, Uint8Array.from([0, 1, 2, 3]), \"new Uint8Array([0,1,2,3])\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Union/Union.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Union\", () => {\n  it(\"should expose the union members\", () => {\n    const schema = S.Union(S.String, S.Number)\n    deepStrictEqual(schema.members, [S.String, S.Number])\n  })\n\n  it(\"should return a `Never` schema when no members are provided\", async () => {\n    const schema = S.Union()\n    await Util.assertions.decoding.fail(schema, 1, \"Expected never, actual 1\")\n  })\n\n  describe(\"decoding\", () => {\n    it(\"should use identifier annotations to generate informative error messages\", async () => {\n      const schema = S.Union(\n        S.Struct({ a: S.String }).annotations({ identifier: \"ID1\" }),\n        S.Struct({ a: S.String }).annotations({ identifier: \"ID2\" })\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `ID1 | ID2\n├─ Expected ID1, actual null\n└─ Expected ID2, actual null`\n      )\n    })\n\n    describe(\"discriminated unions\", () => {\n      describe(\"structs\", () => {\n        it(\"should handle discriminators for each struct\", async () => {\n          const schema = S.Union(\n            S.Struct({ a: S.Literal(1), c: S.String }).annotations({ identifier: \"ID1\" }),\n            S.Struct({ b: S.Literal(2), d: S.Number }).annotations({ identifier: \"ID2\" })\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            null,\n            `Expected ID1 | ID2, actual null`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            {},\n            `ID1 | ID2\n├─ ID1\n│  └─ [\"a\"]\n│     └─ is missing\n└─ ID2\n   └─ [\"b\"]\n      └─ is missing`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            { a: null },\n            `ID1 | ID2\n├─ ID1\n│  └─ [\"a\"]\n│     └─ Expected 1, actual null\n└─ ID2\n   └─ [\"b\"]\n      └─ is missing`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            { b: 3 },\n            `ID1 | ID2\n├─ ID1\n│  └─ [\"a\"]\n│     └─ is missing\n└─ ID2\n   └─ [\"b\"]\n      └─ Expected 2, actual 3`\n          )\n        })\n\n        it(\"should handle structs with multiple discriminators\", async () => {\n          const schema = S.Union(\n            S.Struct({ category: S.Literal(\"catA\"), tag: S.Literal(\"a\") }).annotations({ identifier: \"IDa\" }),\n            S.Struct({ category: S.Literal(\"catA\"), tag: S.Literal(\"b\") }).annotations({ identifier: \"IDb\" }),\n            S.Struct({ category: S.Literal(\"catA\"), tag: S.Literal(\"c\") }).annotations({ identifier: \"IDc\" })\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            null,\n            `Expected IDa | IDb | IDc, actual null`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            {},\n            `IDa | IDb | IDc\n├─ IDa\n│  └─ [\"category\"]\n│     └─ is missing\n└─ IDb | IDc\n   └─ [\"tag\"]\n      └─ is missing`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            { category: null },\n            `IDa | IDb | IDc\n├─ IDa\n│  └─ [\"category\"]\n│     └─ Expected \"catA\", actual null\n└─ IDb | IDc\n   └─ [\"tag\"]\n      └─ is missing`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            { tag: \"d\" },\n            `IDa | IDb | IDc\n├─ IDa\n│  └─ [\"category\"]\n│     └─ is missing\n└─ IDb | IDc\n   └─ [\"tag\"]\n      └─ Expected \"b\" | \"c\", actual \"d\"`\n          )\n        })\n\n        it(\"should handle nested unions\", async () => {\n          const a = S.Struct({ _tag: S.Literal(\"a\") }).annotations({ identifier: \"IDa\" })\n          const b = S.Struct({ _tag: S.Literal(\"b\") }).annotations({ identifier: \"IDb\" })\n          const A = S.Struct({ a: S.Literal(\"A\"), c: S.String }).annotations({ identifier: \"IDA\" })\n          const B = S.Struct({ b: S.Literal(\"B\"), d: S.Number }).annotations({ identifier: \"IDB\" })\n          const ab = S.Union(a, b).annotations({ identifier: \"IDab\" })\n          const AB = S.Union(A, B).annotations({ identifier: \"IDAB\" })\n          const schema = S.Union(ab, AB)\n          await Util.assertions.decoding.succeed(schema, { _tag: \"a\" })\n          await Util.assertions.decoding.succeed(schema, { _tag: \"b\" })\n          await Util.assertions.decoding.succeed(schema, { a: \"A\", c: \"c\" })\n          await Util.assertions.decoding.succeed(schema, { b: \"B\", d: 1 })\n          await Util.assertions.decoding.fail(\n            schema,\n            {},\n            `IDab | IDAB\n├─ IDab\n│  └─ { readonly _tag: \"a\" | \"b\" }\n│     └─ [\"_tag\"]\n│        └─ is missing\n└─ IDAB\n   ├─ IDA\n   │  └─ [\"a\"]\n   │     └─ is missing\n   └─ IDB\n      └─ [\"b\"]\n         └─ is missing`\n          )\n        })\n      })\n\n      describe(\"tuples\", () => {\n        it(\"should handle discriminators for each tuple\", async () => {\n          const schema = S.Union(\n            S.Tuple(S.Literal(\"a\"), S.String),\n            S.Tuple(S.Literal(\"b\"), S.Number)\n          ).annotations({ identifier: \"ID\" })\n\n          await Util.assertions.decoding.succeed(schema, [\"a\", \"s\"])\n          await Util.assertions.decoding.succeed(schema, [\"b\", 1])\n\n          await Util.assertions.decoding.fail(schema, null, `Expected ID, actual null`)\n          await Util.assertions.decoding.fail(\n            schema,\n            [],\n            `ID\n└─ { readonly 0: \"a\" | \"b\" }\n   └─ [\"0\"]\n      └─ is missing`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            [\"c\"],\n            `ID\n└─ { readonly 0: \"a\" | \"b\" }\n   └─ [\"0\"]\n      └─ Expected \"a\" | \"b\", actual \"c\"`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            [\"a\", 0],\n            `ID\n└─ readonly [\"a\", string]\n   └─ [1]\n      └─ Expected string, actual 0`\n          )\n        })\n\n        it(\"should handle tuples with multiple discriminators\", async () => {\n          const schema = S.Union(\n            S.Tuple(S.Literal(\"catA\"), S.Literal(\"a\"), S.String).annotations({ identifier: \"IDa\" }),\n            S.Tuple(S.Literal(\"catA\"), S.Literal(\"b\"), S.Number).annotations({ identifier: \"IDb\" }),\n            S.Tuple(S.Literal(\"catA\"), S.Literal(\"c\"), S.Boolean).annotations({ identifier: \"IDc\" })\n          ).annotations({ identifier: \"ID\" })\n\n          await Util.assertions.decoding.succeed(schema, [\"catA\", \"a\", \"s\"])\n          await Util.assertions.decoding.succeed(schema, [\"catA\", \"b\", 1])\n          await Util.assertions.decoding.succeed(schema, [\"catA\", \"c\", true])\n\n          await Util.assertions.decoding.fail(schema, null, `Expected ID, actual null`)\n          await Util.assertions.decoding.fail(\n            schema,\n            [],\n            `ID\n├─ IDa\n│  └─ [\"0\"]\n│     └─ is missing\n└─ IDb | IDc\n   └─ [\"1\"]\n      └─ is missing`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            [\"catB\"],\n            `ID\n├─ IDa\n│  └─ [\"0\"]\n│     └─ Expected \"catA\", actual \"catB\"\n└─ IDb | IDc\n   └─ [\"1\"]\n      └─ is missing`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            [\"catA\", \"c\"],\n            `ID\n├─ IDa\n│  └─ [2]\n│     └─ is missing\n└─ IDc\n   └─ [2]\n      └─ is missing`\n          )\n          await Util.assertions.decoding.fail(\n            schema,\n            [\"catA\", \"a\", 0],\n            `ID\n├─ IDb | IDc\n│  └─ [\"1\"]\n│     └─ Expected \"b\" | \"c\", actual \"a\"\n└─ IDa\n   └─ [2]\n      └─ Expected string, actual 0`\n          )\n        })\n\n        it(\"should handle discriminated tuple + tuple\", async () => {\n          const schema = S.Union(\n            S.Tuple(S.Literal(-1), S.Literal(0)).annotations({ identifier: \"ID1\" }),\n            S.Tuple(S.NonNegativeInt, S.NonNegativeInt).annotations({ identifier: \"ID2\" })\n          ).annotations({ identifier: \"ID\" })\n\n          await Util.assertions.decoding.fail(\n            schema,\n            null,\n            `ID\n├─ Expected ID1, actual null\n└─ Expected ID2, actual null`\n          )\n        })\n\n        it(\"should handle 2 discriminated tuples + a tuple\", async () => {\n          const schema = S.Union(\n            S.Tuple(S.Literal(-1), S.Literal(0)).annotations({ identifier: \"ID1\" }),\n            S.Tuple(S.Literal(1), S.Literal(0)).annotations({ identifier: \"ID2\" }),\n            S.Tuple(S.NonNegativeInt, S.NonNegativeInt).annotations({ identifier: \"ID3\" })\n          ).annotations({ identifier: \"ID\" })\n\n          await Util.assertions.decoding.fail(\n            schema,\n            [],\n            `ID\n├─ ID1 | ID2\n│  └─ [\"0\"]\n│     └─ is missing\n└─ ID3\n   └─ [0]\n      └─ is missing`\n          )\n        })\n      })\n    })\n  })\n\n  describe(\"encoding\", () => {\n    it(\"should encode all members\", async () => {\n      const schema = S.Union(S.String, Util.NumberFromChar)\n      await Util.assertions.encoding.succeed(schema, \"a\", \"a\")\n      await Util.assertions.encoding.succeed(schema, 1, \"1\")\n    })\n\n    it(\"should handle members with exact optional property signatures\", async () => {\n      const ab = S.Struct({ a: S.String, b: S.optionalWith(S.Number, { exact: true }) })\n      const ac = S.Struct({ a: S.String, c: S.optionalWith(S.Number, { exact: true }) })\n      const schema = S.Union(ab, ac)\n      await Util.assertions.encoding.succeed(\n        schema,\n        { a: \"a\", c: 1 },\n        { a: \"a\" }\n      )\n      await Util.assertions.encoding.succeed(\n        schema,\n        { a: \"a\", c: 1 },\n        { a: \"a\", c: 1 },\n        { parseOptions: Util.onExcessPropertyError }\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/UniqueSymbol/UniqueSymbolFromSelf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"UniqueSymbolFromSelf\", () => {\n  const a = Symbol.for(\"effect/Schema/test/a\")\n  const schema = S.UniqueSymbolFromSelf(a)\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, a)\n    await Util.assertions.decoding.succeed(schema, Symbol.for(\"effect/Schema/test/a\"))\n    await Util.assertions.decoding.fail(\n      schema,\n      \"Symbol(effect/Schema/test/a)\",\n      `Expected Symbol(effect/Schema/test/a), actual \"Symbol(effect/Schema/test/a)\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Unknown/Unknown.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Unknown\", () => {\n  const schema = S.Unknown\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, undefined)\n    await Util.assertions.decoding.succeed(schema, null)\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.succeed(schema, 1)\n    await Util.assertions.decoding.succeed(schema, true)\n    await Util.assertions.decoding.succeed(schema, [])\n    await Util.assertions.decoding.succeed(schema, {})\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/Void/Void.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../../TestUtils.js\"\n\ndescribe(\"Void\", () => {\n  const schema = S.Void\n  it(\"decoding\", async () => {\n    await Util.assertions.decoding.succeed(schema, undefined as any)\n    await Util.assertions.decoding.succeed(schema, null as any)\n    await Util.assertions.decoding.succeed(schema, \"a\" as any)\n    await Util.assertions.decoding.succeed(schema, 1 as any)\n    await Util.assertions.decoding.succeed(schema, true as any)\n    await Util.assertions.decoding.succeed(schema, [] as any)\n    await Util.assertions.decoding.succeed(schema, {} as any)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/annotations.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport type * as Pretty from \"effect/Pretty\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\".annotations()\", () => {\n  it(\"should return a Schema\", () => {\n    const schema = S.String.annotations({\n      [AST.TitleAnnotationId]: \"MyString\",\n      [AST.DescriptionAnnotationId]: \"a string\"\n    })\n    deepStrictEqual(schema.ast.annotations, {\n      [AST.TitleAnnotationId]: \"MyString\",\n      [AST.DescriptionAnnotationId]: \"a string\"\n    })\n    assertTrue(S.isSchema(schema))\n  })\n\n  it(\"title\", () => {\n    const schema = S.String.annotations({ title: \"MyString\" })\n    deepStrictEqual(schema.ast.annotations, {\n      [AST.TitleAnnotationId]: \"MyString\",\n      [AST.DescriptionAnnotationId]: \"a string\"\n    })\n    assertTrue(S.isSchema(schema))\n  })\n\n  it(\"description\", () => {\n    const schema = S.String.annotations({ description: \"description\" })\n    deepStrictEqual(schema.ast.annotations, {\n      [AST.DescriptionAnnotationId]: \"description\",\n      [AST.TitleAnnotationId]: \"string\"\n    })\n    assertTrue(S.isSchema(schema))\n  })\n\n  it(\"examples\", () => {\n    const schema = S.String.annotations({ examples: [\"example\"] })\n    deepStrictEqual(schema.ast.annotations, {\n      [AST.ExamplesAnnotationId]: [\"example\"],\n      [AST.TitleAnnotationId]: \"string\",\n      [AST.DescriptionAnnotationId]: \"a string\"\n    })\n    assertTrue(S.isSchema(schema))\n  })\n\n  it(\"default\", () => {\n    const schema = S.String.annotations({ default: \"a\" })\n    deepStrictEqual(schema.ast.annotations, {\n      [AST.DefaultAnnotationId]: \"a\",\n      [AST.TitleAnnotationId]: \"string\",\n      [AST.DescriptionAnnotationId]: \"a string\"\n    })\n    assertTrue(S.isSchema(schema))\n  })\n\n  it(\"documentation\", () => {\n    const schema = S.String.annotations({ documentation: \"documentation\" })\n    deepStrictEqual(schema.ast.annotations, {\n      [AST.DocumentationAnnotationId]: \"documentation\",\n      [AST.TitleAnnotationId]: \"string\",\n      [AST.DescriptionAnnotationId]: \"a string\"\n    })\n    assertTrue(S.isSchema(schema))\n  })\n\n  it(\"concurrency\", () => {\n    const schema = S.Struct({ a: S.String }).annotations({ concurrency: 1 })\n    deepStrictEqual(schema.ast.annotations, {\n      [AST.ConcurrencyAnnotationId]: 1\n    })\n  })\n\n  it(\"batching\", () => {\n    const schema = S.Struct({ a: S.String }).annotations({ batching: \"inherit\" })\n    deepStrictEqual(schema.ast.annotations, {\n      [AST.BatchingAnnotationId]: \"inherit\"\n    })\n  })\n\n  it(\"typeConstructor\", () => {\n    const schema = S.Struct({ a: S.String }).annotations({ typeConstructor: { _tag: \"MyTypeConstructor\" } })\n    deepStrictEqual(schema.ast.annotations, {\n      [AST.TypeConstructorAnnotationId]: { _tag: \"MyTypeConstructor\" }\n    })\n    deepStrictEqual(\n      AST.getTypeConstructorAnnotation(schema.ast),\n      Option.some({ _tag: \"MyTypeConstructor\" })\n    )\n  })\n\n  it(\"parseIssueTitle\", async () => {\n    const getOrderId = ({ actual }: ParseResult.ParseIssue) => {\n      if (S.is(S.Struct({ id: S.Number }))(actual)) {\n        return `Order with ID ${actual.id}`\n      }\n    }\n\n    const Order = S.Struct({\n      id: S.Number,\n      name: S.String,\n      totalPrice: S.Number\n    }).annotations({\n      identifier: \"Order\",\n      parseIssueTitle: getOrderId\n    })\n\n    await Util.assertions.decoding.fail(\n      Order,\n      {},\n      `Order\n└─ [\"id\"]\n   └─ is missing`\n    )\n    await Util.assertions.decoding.fail(\n      Order,\n      { id: 1 },\n      `Order with ID 1\n└─ [\"name\"]\n   └─ is missing`\n    )\n  })\n\n  it(\"message as annotation options\", async () => {\n    const schema =\n      // initial schema, a string\n      S.String\n        // add an error message for non-string values\n        .annotations({ message: () => \"not a string\" }).pipe(\n          // add a constraint to the schema, only non-empty strings are valid\n          S.nonEmptyString({ message: () => \"required\" }),\n          // add a constraint to the schema, only strings with a length less or equal than 10 are valid\n          S.maxLength(10, { message: (issue) => `${issue.actual} is too long` })\n        )\n\n    assertTrue(S.isSchema(schema))\n    await Util.assertions.decoding.fail(schema, null, \"not a string\")\n    await Util.assertions.decoding.fail(schema, \"\", \"required\")\n    await Util.assertions.decoding.succeed(schema, \"a\", \"a\")\n    await Util.assertions.decoding.fail(schema, \"aaaaaaaaaaaaaa\", \"aaaaaaaaaaaaaa is too long\")\n  })\n\n  it(\"pretty\", () => {\n    class A {\n      constructor(readonly a: string) {}\n    }\n    const prettyA = (): Pretty.Pretty<A> => (instance) => `new A(\"${instance.a}\")`\n    const schema = S.instanceOf(A, {\n      pretty: prettyA\n    })\n    Util.assertions.pretty(schema, new A(\"value\"), `new A(\"value\")`)\n  })\n})\n\ndeclare module \"effect/Schema\" {\n  namespace Annotations {\n    interface Schema<A> extends Doc<A> {\n      formName?: string\n    }\n  }\n}\n\nit(\"should support custom annotations\", () => {\n  const schema = S.String.annotations({ formName: \"a\" })\n  strictEqual(schema.ast.annotations[\"formName\"], \"a\")\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/asserts.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"asserts\", () => {\n  it(\"the returned error should be a ParseError\", () => {\n    const asserts: (u: unknown) => asserts u is string = S.asserts(S.String)\n    try {\n      asserts(1)\n    } catch (e) {\n      assertTrue(ParseResult.isParseError(e))\n    }\n  })\n\n  it(\"should respect outer/inner options\", () => {\n    const schema = S.Struct({ a: Util.NumberFromChar })\n    const input = { a: 1, b: \"b\" }\n    Util.assertions.parseError(\n      () => S.asserts(schema)(input, { onExcessProperty: \"error\" }),\n      `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    Util.assertions.parseError(\n      () => S.asserts(schema, { onExcessProperty: \"error\" })(input),\n      `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    strictEqual(S.asserts(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }), undefined)\n  })\n\n  describe(\"struct\", () => {\n    it(\"required property signature\", () => {\n      const schema = S.Struct({ a: Util.NumberFromChar })\n      Util.assertions.asserts.succeed(schema, { a: 1 })\n      Util.assertions.asserts.fail(\n        schema,\n        { a: null },\n        `{ readonly a: number }\n└─ [\"a\"]\n   └─ Expected number, actual null`\n      )\n    })\n\n    it(\"required property signature with undefined\", () => {\n      const schema = S.Struct({ a: S.Union(S.Number, S.Undefined) })\n      Util.assertions.asserts.succeed(schema, { a: 1 })\n      Util.assertions.asserts.succeed(schema, { a: undefined })\n      Util.assertions.asserts.succeed(schema, { a: 1, b: \"b\" })\n\n      Util.assertions.asserts.fail(\n        schema,\n        {},\n        `{ readonly a: number | undefined }\n└─ [\"a\"]\n   └─ is missing`\n      )\n      Util.assertions.asserts.fail(schema, null, `Expected { readonly a: number | undefined }, actual null`)\n      Util.assertions.asserts.fail(\n        schema,\n        { a: \"a\" },\n        `{ readonly a: number | undefined }\n└─ [\"a\"]\n   └─ number | undefined\n      ├─ Expected number, actual \"a\"\n      └─ Expected undefined, actual \"a\"`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/attachPropertySignature.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"attachPropertySignature\", () => {\n  it(\"string keys literal values\", async () => {\n    const Circle = S.Struct({ radius: S.Number })\n    const Square = S.Struct({ sideLength: S.Number })\n    const schema = S.Union(\n      Circle.pipe(S.attachPropertySignature(\"kind\", \"circle\")),\n      Square.pipe(S.attachPropertySignature(\"kind\", \"square\"))\n    )\n\n    await Util.assertions.decoding.succeed(schema, { radius: 10 }, { kind: \"circle\", radius: 10 })\n    await Util.assertions.encoding.succeed(schema, { kind: \"circle\", radius: 10 }, { radius: 10 })\n    await Util.assertions.decoding.succeed(schema, { sideLength: 10 }, { kind: \"square\", sideLength: 10 })\n    await Util.assertions.encoding.succeed(schema, { kind: \"square\", sideLength: 10 }, { sideLength: 10 })\n  })\n\n  it(\"symbol keys literal values\", async () => {\n    const Circle = S.Struct({ radius: S.Number })\n    const Square = S.Struct({ sideLength: S.Number })\n    const kind = Symbol.for(\"effect/Schema/test/kind\")\n    const schema = S.Union(\n      Circle.pipe(S.attachPropertySignature(kind, \"circle\")),\n      Square.pipe(S.attachPropertySignature(kind, \"square\"))\n    )\n\n    await Util.assertions.decoding.succeed(schema, { radius: 10 }, { [kind]: \"circle\", radius: 10 })\n    await Util.assertions.encoding.succeed(schema, { [kind]: \"circle\", radius: 10 }, { radius: 10 })\n    await Util.assertions.decoding.succeed(schema, { sideLength: 10 }, { [kind]: \"square\", sideLength: 10 })\n    await Util.assertions.encoding.succeed(schema, { [kind]: \"square\", sideLength: 10 }, { sideLength: 10 })\n  })\n\n  it(\"string keys unique symbols\", async () => {\n    const Circle = S.Struct({ radius: S.Number })\n    const Square = S.Struct({ sideLength: S.Number })\n    const kind = Symbol.for(\"effect/Schema/test/kind\")\n    const circle = Symbol.for(\"effect/Schema/test/circle\")\n    const square = Symbol.for(\"effect/Schema/test/square\")\n    const schema = S.Union(\n      Circle.pipe(S.attachPropertySignature(kind, circle)),\n      Square.pipe(S.attachPropertySignature(kind, square))\n    )\n\n    await Util.assertions.decoding.succeed(schema, { radius: 10 }, { [kind]: circle, radius: 10 })\n    await Util.assertions.encoding.succeed(schema, { [kind]: circle, radius: 10 }, { radius: 10 })\n    await Util.assertions.decoding.succeed(schema, { sideLength: 10 }, { [kind]: square, sideLength: 10 })\n    await Util.assertions.encoding.succeed(schema, { [kind]: square, sideLength: 10 }, { sideLength: 10 })\n  })\n\n  it(\"symbol keys unique symbols\", async () => {\n    const Circle = S.Struct({ radius: S.Number })\n    const Square = S.Struct({ sideLength: S.Number })\n    const circle = Symbol.for(\"effect/Schema/test/circle\")\n    const square = Symbol.for(\"effect/Schema/test/square\")\n    const schema = S.Union(\n      Circle.pipe(S.attachPropertySignature(\"kind\", circle)),\n      Square.pipe(S.attachPropertySignature(\"kind\", square))\n    )\n\n    await Util.assertions.decoding.succeed(schema, { radius: 10 }, { kind: circle, radius: 10 })\n    await Util.assertions.encoding.succeed(schema, { kind: circle, radius: 10 }, { radius: 10 })\n    await Util.assertions.decoding.succeed(schema, { sideLength: 10 }, { kind: square, sideLength: 10 })\n    await Util.assertions.encoding.succeed(schema, { kind: square, sideLength: 10 }, { sideLength: 10 })\n  })\n\n  it(\"should be compatible with extend\", async () => {\n    const schema = S.Struct({ a: S.String }).pipe(\n      S.attachPropertySignature(\"_tag\", \"b\"),\n      S.extend(S.Struct({ c: S.Number }))\n    )\n    await Util.assertions.decoding.succeed(schema, { a: \"a\", c: 1 }, { a: \"a\", c: 1, _tag: \"b\" as const })\n    await Util.assertions.encoding.succeed(schema, { a: \"a\", c: 1, _tag: \"b\" as const }, { a: \"a\", c: 1 })\n  })\n\n  it(\"with a transformation\", async () => {\n    const From = S.Struct({ radius: S.Number, _isVisible: S.optionalWith(S.Boolean, { exact: true }) })\n    const To = S.Struct({ radius: S.Number, _isVisible: S.Boolean })\n\n    const schema = S.transformOrFail(\n      From,\n      To,\n      {\n        strict: true,\n        decode: (input) => ParseResult.mapError(S.decodeUnknown(To)(input), (e) => e.issue),\n        encode: ({ _isVisible, ...rest }) => ParseResult.succeed(rest)\n      }\n    ).pipe(\n      S.attachPropertySignature(\"_tag\", \"Circle\")\n    )\n\n    await Util.assertions.decoding.succeed(schema, { radius: 10, _isVisible: true }, {\n      _tag: \"Circle\" as const,\n      _isVisible: true,\n      radius: 10\n    })\n    await Util.assertions.encoding.succeed(schema, {\n      _tag: \"Circle\" as const,\n      radius: 10,\n      _isVisible: true\n    }, {\n      radius: 10\n    })\n  })\n\n  it(\"annotations\", async () => {\n    const schema1 = S.Struct({\n      a: S.String\n    }).pipe(\n      S.attachPropertySignature(\"_tag\", \"a\", { identifier: \"AttachedProperty\" })\n    )\n    await Util.assertions.encoding.fail(\n      schema1,\n      null as any,\n      `({ readonly a: string } <-> AttachedProperty)\n└─ Type side transformation failure\n   └─ Expected AttachedProperty, actual null`\n    )\n    const schema2 = S.attachPropertySignature(\n      S.Struct({\n        a: S.String\n      }),\n      \"_tag\",\n      \"a\",\n      { identifier: \"AttachedProperty\" }\n    )\n    await Util.assertions.encoding.fail(\n      schema2,\n      null as any,\n      `({ readonly a: string } <-> AttachedProperty)\n└─ Type side transformation failure\n   └─ Expected AttachedProperty, actual null`\n    )\n  })\n\n  it(\"decoding error message\", async () => {\n    const schema = S.Struct({\n      a: S.String\n    }).pipe(\n      S.attachPropertySignature(\"_tag\", \"a\")\n    ).annotations({ identifier: \"AttachedProperty\" })\n    await Util.assertions.decoding.fail(\n      schema,\n      null,\n      `AttachedProperty\n└─ Encoded side transformation failure\n   └─ Expected { readonly a: string }, actual null`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/brand.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"brand\", () => {\n  it(\"toString\", () => {\n    strictEqual(String(S.String.pipe(S.brand(\"my-brand\"))), `string & Brand<\"my-brand\">`)\n  })\n\n  it(\"should expose the original schema as `from`\", () => {\n    const schema = S.String.pipe(S.brand(\"my-brand\"))\n    strictEqual(schema.from, S.String)\n  })\n\n  it(\"the constructor should validate the input by default\", () => {\n    const schema = S.NonEmptyString.pipe(S.brand(\"A\"))\n    Util.assertions.make.succeed(schema, \"a\")\n    Util.assertions.make.fail(\n      schema,\n      \"\",\n      `nonEmptyString & Brand<\"A\">\n└─ Predicate refinement failure\n   └─ Expected a non empty string, actual \"\"`\n    )\n  })\n\n  it(\"the constructor validation can be disabled\", () => {\n    const schema = S.NonEmptyString.pipe(S.brand(\"A\"))\n    strictEqual(schema.make(\"\", true), \"\")\n    strictEqual(schema.make(\"\", { disableValidation: true }), \"\")\n  })\n\n  describe(\"annotations\", () => {\n    it(\"using .annotations() twice\", () => {\n      const schema = S.Number.pipe(S.brand(\"A\"))\n      const annotatedSchema = schema.annotations({\n        description: \"description\"\n      }).annotations({ title: \"title\" })\n      deepStrictEqual(annotatedSchema.ast.annotations, {\n        [AST.BrandAnnotationId]: [\"A\"],\n        [AST.TitleAnnotationId]: \"title\",\n        [AST.DescriptionAnnotationId]: \"description\"\n      })\n    })\n\n    it(\"using .annotations() on a BrandSchema should return a BrandSchema\", () => {\n      const schema = S.Number.pipe(\n        S.int(),\n        S.brand(\"A\")\n      )\n      const annotatedSchema = schema.annotations({\n        description: \"description\"\n      }).annotations({ title: \"title\" })\n      strictEqual(typeof annotatedSchema.make, \"function\")\n    })\n\n    it(\"brand as string (1 brand)\", () => {\n      const schema = S.Number.pipe(\n        S.int(),\n        S.brand(\"A\", {\n          description: \"description\"\n        })\n      )\n      strictEqual(String(schema), `int & Brand<\"A\">`)\n\n      deepStrictEqual(schema.ast.annotations, {\n        [AST.SchemaIdAnnotationId]: S.IntSchemaId,\n        [AST.BrandAnnotationId]: [\"A\"],\n        [AST.TitleAnnotationId]: \"int\",\n        [AST.DescriptionAnnotationId]: \"description\",\n        [AST.JSONSchemaAnnotationId]: { type: \"integer\" }\n      })\n    })\n\n    it(\"brand as string (2 brands)\", () => {\n      const schema = S.Number.pipe(\n        S.int(),\n        S.brand(\"A\"),\n        S.brand(\"B\", {\n          description: \"description\"\n        })\n      )\n\n      strictEqual(String(schema), `int & Brand<\"A\"> & Brand<\"B\">`)\n\n      deepStrictEqual(schema.ast.annotations, {\n        [AST.SchemaIdAnnotationId]: S.IntSchemaId,\n        [AST.BrandAnnotationId]: [\"A\", \"B\"],\n        [AST.TitleAnnotationId]: \"int\",\n        [AST.DescriptionAnnotationId]: \"description\",\n        [AST.JSONSchemaAnnotationId]: { type: \"integer\" }\n      })\n    })\n\n    it(\"brand as symbol\", () => {\n      const A = Symbol.for(\"A\")\n      const B = Symbol.for(\"B\")\n      const schema = S.Number.pipe(\n        S.int(),\n        S.brand(A),\n        S.brand(B, {\n          description: \"description\"\n        })\n      )\n\n      strictEqual(String(schema), \"int & Brand<Symbol(A)> & Brand<Symbol(B)>\")\n\n      deepStrictEqual(schema.ast.annotations, {\n        [AST.SchemaIdAnnotationId]: S.IntSchemaId,\n        [AST.BrandAnnotationId]: [A, B],\n        [AST.TitleAnnotationId]: \"int\",\n        [AST.DescriptionAnnotationId]: \"description\",\n        [AST.JSONSchemaAnnotationId]: { type: \"integer\" }\n      })\n    })\n  })\n\n  it(\"composition\", () => {\n    const int = <A extends number, I>(self: S.Schema<A, I>) => self.pipe(S.int(), S.brand(\"Int\"))\n\n    const positive = <A extends number, I>(self: S.Schema<A, I>) => self.pipe(S.positive(), S.brand(\"Positive\"))\n\n    const PositiveInt = S.NumberFromString.pipe(int, positive)\n\n    const is = S.is(PositiveInt)\n    assertTrue(is(1))\n    assertFalse(is(-1))\n    assertFalse(is(1.2))\n  })\n\n  describe(\"decoding\", () => {\n    it(\"string brand\", async () => {\n      const schema = S.NumberFromString.pipe(\n        S.int(),\n        S.brand(\"Int\")\n      ).annotations({ identifier: \"IntegerFromString\" })\n      await Util.assertions.decoding.succeed(schema, \"1\", 1 as any)\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `IntegerFromString\n└─ From side refinement failure\n   └─ NumberFromString\n      └─ Encoded side transformation failure\n         └─ Expected string, actual null`\n      )\n    })\n\n    it(\"symbol brand\", async () => {\n      const Int = Symbol.for(\"Int\")\n      const schema = S.NumberFromString.pipe(\n        S.int(),\n        S.brand(Int)\n      ).annotations({ identifier: \"IntegerFromString\" })\n      await Util.assertions.decoding.succeed(schema, \"1\", 1 as any)\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `IntegerFromString\n└─ From side refinement failure\n   └─ NumberFromString\n      └─ Encoded side transformation failure\n         └─ Expected string, actual null`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/compose.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"compose\", async () => {\n  it(\"B = C\", async () => {\n    const schema1 = S.compose(S.split(\",\"), S.Array(S.NumberFromString))\n    await Util.assertions.decoding.succeed(schema1, \"1,2,3\", [1, 2, 3])\n    const schema2 = S.split(\",\").pipe(S.compose(S.Array(S.NumberFromString)))\n    await Util.assertions.decoding.succeed(schema2, \"1,2,3\", [1, 2, 3])\n  })\n\n  it(\"force decoding: (A U B) compose (B -> C)\", async () => {\n    const schema1 = S.compose(S.Union(S.String, S.Null), S.NumberFromString, { strict: false })\n    await Util.assertions.decoding.succeed(schema1, \"1\", 1)\n    await Util.assertions.decoding.fail(\n      schema1,\n      \"a\",\n      `(string | null <-> NumberFromString)\n└─ Type side transformation failure\n   └─ NumberFromString\n      └─ Transformation process failure\n         └─ Unable to decode \"a\" into a number`\n    )\n    await Util.assertions.decoding.fail(\n      schema1,\n      null,\n      `(string | null <-> NumberFromString)\n└─ Type side transformation failure\n   └─ NumberFromString\n      └─ Encoded side transformation failure\n         └─ Expected string, actual null`\n    )\n    const schema2 = S.Union(S.String, S.Null).pipe(\n      S.compose(S.NumberFromString, { strict: false })\n    )\n    await Util.assertions.decoding.succeed(schema2, \"1\", 1)\n    await Util.assertions.decoding.fail(\n      schema2,\n      \"a\",\n      `(string | null <-> NumberFromString)\n└─ Type side transformation failure\n   └─ NumberFromString\n      └─ Transformation process failure\n         └─ Unable to decode \"a\" into a number`\n    )\n    await Util.assertions.decoding.fail(\n      schema2,\n      null,\n      `(string | null <-> NumberFromString)\n└─ Type side transformation failure\n   └─ NumberFromString\n      └─ Encoded side transformation failure\n         └─ Expected string, actual null`\n    )\n  })\n\n  it(\"force encoding: (A -> B) compose (C U B)\", async () => {\n    const schema1 = S.compose(S.NumberFromString, S.Union(S.Number, S.Null), { strict: false })\n    await Util.assertions.encoding.succeed(schema1, 1, \"1\")\n    await Util.assertions.encoding.fail(\n      schema1,\n      null,\n      `(NumberFromString <-> number | null)\n└─ Encoded side transformation failure\n   └─ NumberFromString\n      └─ Type side transformation failure\n         └─ Expected number, actual null`\n    )\n    const schema2 = S.NumberFromString.pipe(\n      S.compose(S.Union(S.Number, S.Null), { strict: false })\n    )\n    await Util.assertions.encoding.succeed(schema2, 1, \"1\")\n    await Util.assertions.encoding.fail(\n      schema2,\n      null,\n      `(NumberFromString <-> number | null)\n└─ Encoded side transformation failure\n   └─ NumberFromString\n      └─ Type side transformation failure\n         └─ Expected number, actual null`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/decode.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"decode\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return an error on invalid values\", async () => {\n    await Util.assertions.effect.succeed(S.decode(schema)({ a: \"1\" }), { a: 1 })\n    await Util.assertions.effect.fail(\n      S.decode(schema)({ a: \"10\" }).pipe(Effect.mapError((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"a\"]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n    )\n  })\n\n  it(\"should respect outer/inner options\", async () => {\n    const input = { a: \"1\", b: \"b\" }\n    await Util.assertions.effect.fail(\n      S.decode(schema)(input, { onExcessProperty: \"error\" }).pipe(Effect.mapError((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.effect.fail(\n      S.decode(schema, { onExcessProperty: \"error\" })(input).pipe(Effect.mapError((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.effect.succeed(\n      S.decode(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }),\n      {\n        a: 1\n      }\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/decodeEither.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Either from \"effect/Either\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"decodeEither\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return an error on invalid values\", async () => {\n    Util.assertions.either.right(S.decodeEither(schema)({ a: \"1\" }), { a: 1 })\n    await Util.assertions.either.fail(\n      S.decodeEither(schema)({ a: \"10\" }).pipe(Either.mapLeft((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"a\"]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n    )\n  })\n\n  it(\"should return an error on async\", async () => {\n    await Util.assertions.either.fail(\n      S.decodeEither(Util.AsyncString)(\"a\").pipe(Either.mapLeft((e) => e.issue)),\n      `AsyncString\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n\n  it(\"should respect outer/inner options\", async () => {\n    const input = { a: \"1\", b: \"b\" }\n    await Util.assertions.either.fail(\n      S.decodeEither(schema)(input, { onExcessProperty: \"error\" }).pipe(Either.mapLeft((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.either.fail(\n      S.decodeEither(schema, { onExcessProperty: \"error\" })(input).pipe(Either.mapLeft((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    Util.assertions.either.right(\n      S.decodeEither(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }),\n      {\n        a: 1\n      }\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/decodeOption.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertSome } from \"@effect/vitest/utils\"\nimport { Schema as S } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"decodeOption\", () => {\n  it(\"should return none on async\", () => {\n    assertNone(S.decodeOption(Util.AsyncString)(\"a\"))\n  })\n\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return None on invalid values\", () => {\n    assertSome(S.decodeOption(schema)({ a: \"1\" }), { a: 1 })\n    assertNone(S.decodeOption(schema)({ a: \"10\" }))\n  })\n\n  it(\"should respect outer/inner options\", () => {\n    const input = { a: \"1\", b: \"b\" }\n    assertNone(S.decodeOption(schema)(input, { onExcessProperty: \"error\" }))\n    assertNone(S.decodeOption(schema, { onExcessProperty: \"error\" })(input))\n    assertSome(S.decodeOption(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }), { a: 1 })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/decodePromise.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"decodePromise\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return None on invalid values\", async () => {\n    deepStrictEqual(await S.decodePromise(schema)({ a: \"1\" }), { a: 1 })\n\n    await Util.assertions.promise.fail(\n      S.decodePromise(schema)({ a: \"10\" }),\n      `{ readonly a: NumberFromChar }\n└─ [\"a\"]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n    )\n  })\n\n  it(\"should respect outer/inner options\", async () => {\n    const input = { a: \"1\", b: \"b\" }\n\n    deepStrictEqual(\n      await S.decodePromise(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }),\n      { a: 1 }\n    )\n\n    await Util.assertions.promise.fail(\n      S.decodePromise(schema)(input, { onExcessProperty: \"error\" }),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.promise.fail(\n      S.decodePromise(schema, { onExcessProperty: \"error\" })(input),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/decodeSync.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"decodeSync\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should throw on invalid values\", () => {\n    deepStrictEqual(S.decodeSync(schema)({ a: \"1\" }), { a: 1 })\n    Util.assertions.parseError(\n      () => S.decodeSync(schema)({ a: \"10\" }),\n      `{ readonly a: NumberFromChar }\n└─ [\"a\"]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n    )\n  })\n\n  it(\"should throw on async\", () => {\n    Util.assertions.parseError(\n      () => S.decodeSync(Util.AsyncString)(\"a\"),\n      `AsyncString\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n\n  it(\"should respect outer/inner options\", () => {\n    const input = { a: \"1\", b: \"b\" }\n    Util.assertions.parseError(\n      () => S.decodeSync(schema)(input, { onExcessProperty: \"error\" }),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    Util.assertions.parseError(\n      () => S.decodeSync(schema, { onExcessProperty: \"error\" })(input),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    deepStrictEqual(S.decodeSync(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }), {\n      a: 1\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/decodeUnknownEither.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Either from \"effect/Either\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"decodeUnknownEither\", () => {\n  it(\"should return Left on async\", async () => {\n    await Util.assertions.either.fail(\n      S.decodeUnknownEither(Util.AsyncString)(\"a\").pipe(Either.mapLeft((e) => e.issue)),\n      `AsyncString\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/decodeUnknownOption.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone } from \"@effect/vitest/utils\"\nimport { Schema as S } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"decodeUnknownOption\", () => {\n  it(\"should return none on async\", () => {\n    assertNone(S.decodeUnknownOption(Util.AsyncString)(\"a\"))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/decodeUnknownPromise.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport { ParseResult, Schema } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"decodeUnknownPromise\", () => {\n  const schema = Schema.String\n\n  it(\"should resolve\", async () => {\n    deepStrictEqual(await Schema.decodeUnknownPromise(schema)(\"a\"), \"a\")\n    deepStrictEqual(await ParseResult.decodeUnknownPromise(schema)(\"a\"), \"a\")\n  })\n\n  it(\"should reject on invalid values\", async () => {\n    await Util.assertions.promise.fail(\n      Schema.decodeUnknownPromise(schema)(null),\n      `Expected string, actual null`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/decodeUnknownSync.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInclude, assertInstanceOf, strictEqual, throws } from \"@effect/vitest/utils\"\nimport { Effect, ParseResult, Predicate, Schema as S } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\nconst SyncEffectfulString = S.declare([], {\n  decode: () => (u, _, ast) =>\n    Predicate.isString(u) ? Effect.succeed(u) : Effect.fail(new ParseResult.Type(ast, u, \"not a string\")),\n  encode: () => (u, _, ast) =>\n    Predicate.isString(u) ? Effect.succeed(u) : Effect.fail(new ParseResult.Type(ast, u, \"not a string\"))\n}, { identifier: \"SyncEffectfulString\" })\n\ndescribe(\"decodeUnknownSync\", () => {\n  it(\"should return a ParseError when the input is invalid\", () => {\n    Util.assertions.parseError(() => S.decodeUnknownSync(S.String)(1), \"Expected string, actual 1\")\n  })\n\n  it(\"should decode synchronously even when the schema uses Effects\", () => {\n    strictEqual(S.decodeUnknownSync(SyncEffectfulString)(\"a\"), \"a\")\n    Util.assertions.parseError(() => {\n      S.decodeUnknownSync(SyncEffectfulString)(null)\n    }, \"not a string\")\n  })\n\n  it(\"should throw an error when the schema performs asynchronous work\", () => {\n    Util.assertions.parseError(\n      () => S.decodeUnknownSync(Util.AsyncString)(\"a\"),\n      `AsyncString\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n\n  it(\"should throw an error when required dependencies are missing\", () => {\n    throws(() => S.decodeUnknownSync(Util.DependencyString as any)(\"a\"), (err) => {\n      assertInstanceOf(err, ParseResult.ParseError)\n      assertInclude(err.message, \"Service not found: Name\")\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encode.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encode\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return an error on invalid values\", async () => {\n    await Util.assertions.effect.succeed(S.encode(schema)({ a: 1 }), { a: \"1\" })\n    await Util.assertions.effect.fail(\n      S.encode(schema)({ a: 10 }).pipe(Effect.mapError((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"a\"]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n    )\n  })\n\n  it(\"should respect outer/inner options\", async () => {\n    const input = { a: 1, b: \"b\" }\n    await Util.assertions.effect.fail(\n      S.encode(schema)(input, { onExcessProperty: \"error\" }).pipe(Effect.mapError((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.effect.fail(\n      S.encode(schema, { onExcessProperty: \"error\" })(input).pipe(Effect.mapError((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.effect.succeed(\n      S.encode(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }),\n      {\n        a: \"1\"\n      }\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encodeEither.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Either from \"effect/Either\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encodeEither\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return an error on invalid values\", async () => {\n    Util.assertions.either.right(S.encodeEither(schema)({ a: 1 }), { a: \"1\" })\n    await Util.assertions.either.fail(\n      S.encodeEither(schema)({ a: 10 }).pipe(Either.mapLeft((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"a\"]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n    )\n  })\n\n  it(\"should return an error on async\", async () => {\n    await Util.assertions.either.fail(\n      S.encodeEither(Util.AsyncString)(\"a\").pipe(Either.mapLeft((e) => e.issue)),\n      `AsyncString\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n\n  it(\"should respect outer/inner options\", async () => {\n    const input = { a: 1, b: \"b\" }\n    await Util.assertions.either.fail(\n      S.encodeEither(schema)(input, { onExcessProperty: \"error\" }).pipe(Either.mapLeft((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.either.fail(\n      S.encodeEither(schema, { onExcessProperty: \"error\" })(input).pipe(Either.mapLeft((e) => e.issue)),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    Util.assertions.either.right(\n      S.encodeEither(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }),\n      { a: \"1\" }\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encodeOption.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertSome } from \"@effect/vitest/utils\"\nimport { Schema as S } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encodeOption\", () => {\n  it(\"should return none on async\", () => {\n    assertNone(S.encodeOption(Util.AsyncString)(\"a\"))\n  })\n\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return None on invalid values\", () => {\n    assertSome(S.encodeOption(schema)({ a: 1 }), { a: \"1\" })\n    assertNone(S.encodeOption(schema)({ a: 10 }))\n  })\n\n  it(\"should respect outer/inner options\", () => {\n    const input = { a: 1, b: \"b\" }\n    assertNone(S.encodeOption(schema)(input, { onExcessProperty: \"error\" }))\n    assertNone(S.encodeOption(schema, { onExcessProperty: \"error\" })(input))\n    assertSome(S.encodeOption(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }), { a: \"1\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encodePromise.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encodePromise\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return None on invalid values\", async () => {\n    deepStrictEqual(await S.encodePromise(schema)({ a: 1 }), { a: \"1\" })\n\n    await Util.assertions.promise.fail(\n      S.encodePromise(schema)({ a: 10 }),\n      `{ readonly a: NumberFromChar }\n└─ [\"a\"]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n    )\n  })\n\n  it(\"should respect outer/inner options\", async () => {\n    const input = { a: 1, b: \"b\" }\n\n    deepStrictEqual(\n      await S.encodePromise(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }),\n      { a: \"1\" }\n    )\n\n    await Util.assertions.promise.fail(\n      S.encodePromise(schema)(input, { onExcessProperty: \"error\" }),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.promise.fail(\n      S.encodePromise(schema, { onExcessProperty: \"error\" })(input),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encodeSync.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encodeSync\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should throw on invalid values\", () => {\n    deepStrictEqual(S.encodeSync(schema)({ a: 1 }), { a: \"1\" })\n    Util.assertions.parseError(\n      () => S.encodeSync(schema)({ a: 10 }),\n      `{ readonly a: NumberFromChar }\n└─ [\"a\"]\n   └─ NumberFromChar\n      └─ Encoded side transformation failure\n         └─ Char\n            └─ Predicate refinement failure\n               └─ Expected a single character, actual \"10\"`\n    )\n  })\n\n  it(\"should throw on async\", () => {\n    Util.assertions.parseError(\n      () => S.encodeSync(Util.AsyncString)(\"a\"),\n      `AsyncString\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n\n  it(\"should respect outer/inner options\", () => {\n    const input = { a: 1, b: \"b\" }\n    Util.assertions.parseError(\n      () => S.encodeSync(schema)(input, { onExcessProperty: \"error\" }),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    Util.assertions.parseError(\n      () => S.encodeSync(schema, { onExcessProperty: \"error\" })(input),\n      `{ readonly a: NumberFromChar }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    deepStrictEqual(S.encodeSync(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }), {\n      a: \"1\"\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encodeUnknownEither.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Either from \"effect/Either\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encodeUnknownEither\", () => {\n  it(\"should return Left on async\", async () => {\n    await Util.assertions.either.fail(\n      S.encodeUnknownEither(Util.AsyncString)(\"a\").pipe(Either.mapLeft((e) => e.issue)),\n      `AsyncString\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encodeUnknownOption.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone } from \"@effect/vitest/utils\"\nimport { Schema as S } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encodeUnknownOption\", () => {\n  it(\"should return none on async\", () => {\n    assertNone(S.encodeUnknownOption(Util.AsyncString)(\"a\"))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encodeUnknownPromise.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport { ParseResult, Schema } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encodeUnknownPromise\", () => {\n  const schema = Schema.String\n\n  it(\"should resolve\", async () => {\n    deepStrictEqual(await Schema.encodeUnknownPromise(schema)(\"a\"), \"a\")\n    deepStrictEqual(await ParseResult.encodeUnknownPromise(schema)(\"a\"), \"a\")\n  })\n\n  it(\"should reject on invalid values\", async () => {\n    await Util.assertions.promise.fail(\n      Schema.encodeUnknownPromise(schema)(null),\n      `Expected string, actual null`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encodeUnknownSync.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encodeUnknownSync\", () => {\n  it(\"should throw on async\", () => {\n    Util.assertions.parseError(\n      () => S.encodeUnknownSync(Util.AsyncString)(\"a\"),\n      `AsyncString\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encodedBoundSchema.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encodedBoundSchema\", () => {\n  const StringTransformation = S.transform(\n    S.String.pipe(S.minLength(2)).annotations({ identifier: \"String2\" }),\n    S.String,\n    {\n      strict: true,\n      encode: (s) => s,\n      decode: (s) => s\n    }\n  ).annotations({ identifier: \"StringTransformation\" })\n\n  it(\"struct\", async () => {\n    const String3 = S.String.pipe(S.minLength(3)).annotations({ identifier: \"String3\" })\n\n    const schema = S.Struct({\n      a: S.Array(StringTransformation),\n      b: String3\n    }).annotations({ identifier: \"FullSchema\" })\n\n    const bound = S.encodedBoundSchema(schema)\n\n    await Util.assertions.decoding.succeed(bound, {\n      a: [\"ab\"],\n      b: \"abc\"\n    })\n\n    await Util.assertions.decoding.fail(\n      bound,\n      {\n        a: [\"a\"],\n        b: \"abc\"\n      },\n      `{ readonly a: ReadonlyArray<String2>; readonly b: String3 }\n└─ [\"a\"]\n   └─ ReadonlyArray<String2>\n      └─ [0]\n         └─ String2\n            └─ Predicate refinement failure\n               └─ Expected a string at least 2 character(s) long, actual \"a\"`\n    )\n\n    await Util.assertions.decoding.fail(\n      bound,\n      {\n        a: [\"ab\"],\n        b: \"ab\"\n      },\n      `{ readonly a: ReadonlyArray<String2>; readonly b: String3 }\n└─ [\"b\"]\n   └─ String3\n      └─ Predicate refinement failure\n         └─ Expected a string at least 3 character(s) long, actual \"ab\"`\n    )\n  })\n\n  describe(\"Stable filters\", () => {\n    describe(\"Array\", () => {\n      it(\"minItems\", async () => {\n        const schema = S.Array(StringTransformation).pipe(S.minItems(2))\n        const bound = S.encodedBoundSchema(schema)\n\n        await Util.assertions.decoding.succeed(bound, [\"ab\", \"cd\"])\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"a\"],\n          `minItems(2)\n└─ From side refinement failure\n   └─ ReadonlyArray<String2>\n      └─ [0]\n         └─ String2\n            └─ Predicate refinement failure\n               └─ Expected a string at least 2 character(s) long, actual \"a\"`\n        )\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"ab\"],\n          `minItems(2)\n└─ Predicate refinement failure\n   └─ Expected an array of at least 2 item(s), actual [\"ab\"]`\n        )\n      })\n\n      it(\"maxItems\", async () => {\n        const schema = S.Array(StringTransformation).pipe(S.maxItems(2))\n        const bound = S.encodedBoundSchema(schema)\n\n        await Util.assertions.decoding.succeed(bound, [\"ab\", \"cd\"])\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"a\"],\n          `maxItems(2)\n└─ From side refinement failure\n   └─ ReadonlyArray<String2>\n      └─ [0]\n         └─ String2\n            └─ Predicate refinement failure\n               └─ Expected a string at least 2 character(s) long, actual \"a\"`\n        )\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"ab\", \"cd\", \"ef\"],\n          `maxItems(2)\n└─ Predicate refinement failure\n   └─ Expected an array of at most 2 item(s), actual [\"ab\",\"cd\",\"ef\"]`\n        )\n      })\n\n      it(\"itemsCount\", async () => {\n        const schema = S.Array(StringTransformation).pipe(S.itemsCount(2))\n        const bound = S.encodedBoundSchema(schema)\n\n        await Util.assertions.decoding.succeed(bound, [\"ab\", \"cd\"])\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"a\"],\n          `itemsCount(2)\n└─ From side refinement failure\n   └─ ReadonlyArray<String2>\n      └─ [0]\n         └─ String2\n            └─ Predicate refinement failure\n               └─ Expected a string at least 2 character(s) long, actual \"a\"`\n        )\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"ab\"],\n          `itemsCount(2)\n└─ Predicate refinement failure\n   └─ Expected an array of exactly 2 item(s), actual [\"ab\"]`\n        )\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"ab\", \"cd\", \"ef\"],\n          `itemsCount(2)\n└─ Predicate refinement failure\n   └─ Expected an array of exactly 2 item(s), actual [\"ab\",\"cd\",\"ef\"]`\n        )\n      })\n    })\n\n    describe(\"NonEmptyArray\", () => {\n      it(\"minItems\", async () => {\n        const schema = S.NonEmptyArray(StringTransformation).pipe(S.minItems(2))\n        const bound = S.encodedBoundSchema(schema)\n\n        await Util.assertions.decoding.succeed(bound, [\"ab\", \"cd\"])\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"a\"],\n          `minItems(2)\n└─ From side refinement failure\n   └─ readonly [String2, ...String2[]]\n      └─ [0]\n         └─ String2\n            └─ Predicate refinement failure\n               └─ Expected a string at least 2 character(s) long, actual \"a\"`\n        )\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"ab\"],\n          `minItems(2)\n└─ Predicate refinement failure\n   └─ Expected an array of at least 2 item(s), actual [\"ab\"]`\n        )\n      })\n\n      it(\"maxItems\", async () => {\n        const schema = S.NonEmptyArray(StringTransformation).pipe(S.maxItems(2))\n        const bound = S.encodedBoundSchema(schema)\n\n        await Util.assertions.decoding.succeed(bound, [\"ab\", \"cd\"])\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"a\"],\n          `maxItems(2)\n└─ From side refinement failure\n   └─ readonly [String2, ...String2[]]\n      └─ [0]\n         └─ String2\n            └─ Predicate refinement failure\n               └─ Expected a string at least 2 character(s) long, actual \"a\"`\n        )\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"ab\", \"cd\", \"ef\"],\n          `maxItems(2)\n└─ Predicate refinement failure\n   └─ Expected an array of at most 2 item(s), actual [\"ab\",\"cd\",\"ef\"]`\n        )\n      })\n\n      it(\"itemsCount\", async () => {\n        const schema = S.NonEmptyArray(StringTransformation).pipe(S.itemsCount(2))\n        const bound = S.encodedBoundSchema(schema)\n\n        await Util.assertions.decoding.succeed(bound, [\"ab\", \"cd\"])\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"a\"],\n          `itemsCount(2)\n└─ From side refinement failure\n   └─ readonly [String2, ...String2[]]\n      └─ [0]\n         └─ String2\n            └─ Predicate refinement failure\n               └─ Expected a string at least 2 character(s) long, actual \"a\"`\n        )\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"ab\"],\n          `itemsCount(2)\n└─ Predicate refinement failure\n   └─ Expected an array of exactly 2 item(s), actual [\"ab\"]`\n        )\n        await Util.assertions.decoding.fail(\n          bound,\n          [\"ab\", \"cd\", \"ef\"],\n          `itemsCount(2)\n└─ Predicate refinement failure\n   └─ Expected an array of exactly 2 item(s), actual [\"ab\",\"cd\",\"ef\"]`\n        )\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/encodedSchema.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"encodedSchema\", () => {\n  it(\"suspend\", async () => {\n    interface I {\n      prop: I | string\n    }\n    interface A {\n      prop: A | number\n    }\n    const schema1 = S.Struct({\n      prop: S.Union(S.NumberFromString, S.suspend((): S.Schema<A, I> => schema1))\n    })\n    const from1 = S.encodedSchema(schema1)\n    await Util.assertions.decoding.succeed(from1, { prop: \"a\" })\n    await Util.assertions.decoding.succeed(from1, { prop: { prop: \"a\" } })\n\n    const schema2: S.Schema<A, I> = S.suspend( // intended outer suspend\n      () =>\n        S.Struct({\n          prop: S.Union(S.NumberFromString, schema1)\n        })\n    )\n    const from2 = S.encodedSchema(schema2)\n    await Util.assertions.decoding.succeed(from2, { prop: \"a\" })\n    await Util.assertions.decoding.succeed(from2, { prop: { prop: \"a\" } })\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.encodedSchema(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.fail(schema, null, \"Expected string, actual null\")\n    await Util.assertions.decoding.fail(schema, 1, \"Expected string, actual 1\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/equivalence.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual, throws } from \"@effect/vitest/utils\"\nimport * as A from \"effect/Arbitrary\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Data from \"effect/Data\"\nimport * as Either from \"effect/Either\"\nimport * as Equal from \"effect/Equal\"\nimport * as Equivalence from \"effect/Equivalence\"\nimport * as fc from \"effect/FastCheck\"\nimport * as Hash from \"effect/Hash\"\nimport * as Option from \"effect/Option\"\nimport { isUnknown } from \"effect/Predicate\"\nimport * as S from \"effect/Schema\"\n\n/**\n * Tests that the generated Eq is a valid Eq\n */\nexport const propertyType = <A, I>(\n  schema: S.Schema<A, I>,\n  params?: fc.Parameters<[A, ...Array<A>]>\n) => {\n  const arb = A.makeLazy(schema)(fc)\n  // console.log(fc.sample(arb, 10))\n  const equivalence = S.equivalence(schema)\n\n  const reflexivity = fc.property(arb, (a) => equivalence(a, a))\n  const symmetry = fc.property(arb, arb, (a, b) => equivalence(a, b) === equivalence(b, a))\n  const transitivity = fc.property(\n    arb,\n    arb,\n    arb,\n    (a, b, c) =>\n      /*\n        A logical implication is a relationship between two propositions that states that if the first proposition is true,\n        then the second proposition must also be true. In terms of booleans, a logical implication can be translated as:\n\n        (p → q) ≡ ¬p ∨ q\n      */\n      !(equivalence(a, b) && equivalence(b, c)) || equivalence(a, c)\n  )\n\n  fc.assert(reflexivity, params)\n  fc.assert(symmetry, params)\n  fc.assert(transitivity, params)\n}\n\nconst MyString = S.String.annotations({\n  equivalence: () => (a, b) => {\n    if (typeof a !== \"string\" || typeof b !== \"string\") {\n      throw new Error(\"invalid string provided to `string`\")\n    }\n    return a === b\n  }\n})\n\nconst MyNumber = S.JsonNumber.annotations({\n  equivalence: () => (a, b) => {\n    if (typeof a !== \"number\" || typeof b !== \"number\") {\n      throw new Error(\"invalid number provided to `number`\")\n    }\n    return a === b\n  }\n})\n\nconst MySymbol = S.SymbolFromSelf.annotations({\n  equivalence: () => (a, b) => {\n    if (typeof a !== \"symbol\" || typeof b !== \"symbol\") {\n      throw new Error(\"invalid symbol provided to `symbol`\")\n    }\n    return a === b\n  }\n})\n\ndescribe(\"equivalence\", () => {\n  it(\"the errors should display a path\", () => {\n    throws(\n      () => S.equivalence(S.Tuple(S.Never as any)),\n      new Error(`Unsupported schema\nat path: [0]\ndetails: Cannot build an Equivalence\nschema (NeverKeyword): never`)\n    )\n    throws(\n      () => S.equivalence(S.Struct({ a: S.Never as any })),\n      new Error(`Unsupported schema\nat path: [\"a\"]\ndetails: Cannot build an Equivalence\nschema (NeverKeyword): never`)\n    )\n  })\n\n  it(\"transformation\", () => {\n    const schema = S.NumberFromString\n    const equivalence = S.equivalence(schema)\n\n    assertTrue(equivalence(1, 1))\n\n    assertFalse(equivalence(1, 2))\n  })\n\n  it(\"S.equivalence(S.encodedSchema(schema))\", () => {\n    const schema = S.NumberFromString\n    const equivalence = S.equivalence(S.encodedSchema(schema))\n\n    assertTrue(equivalence(\"a\", \"a\"))\n\n    assertFalse(equivalence(\"a\", \"b\"))\n  })\n\n  it(\"never\", () => {\n    throws(\n      () => S.equivalence(S.Never),\n      new Error(`Unsupported schema\ndetails: Cannot build an Equivalence\nschema (NeverKeyword): never`)\n    )\n  })\n\n  it(\"string\", () => {\n    const schema = MyString\n    const equivalence = S.equivalence(schema)\n\n    assertTrue(equivalence(\"a\", \"a\"))\n\n    assertFalse(equivalence(\"a\", \"b\"))\n\n    // propertyType(schema)\n  })\n\n  it(\"Refinement\", () => {\n    const schema = S.NonEmptyString\n    const equivalence = S.equivalence(schema)\n\n    assertTrue(equivalence(\"a\", \"a\"))\n\n    assertFalse(equivalence(\"a\", \"b\"))\n\n    // propertyType(schema)\n  })\n\n  describe(\"declaration\", () => {\n    it(\"should return Equal.equals when an annotation doesn't exist\", () => {\n      const schema = S.declare(isUnknown)\n      const equivalence = S.equivalence(schema)\n      strictEqual(equivalence, Equal.equals)\n\n      const make = (id: number, s: string) => {\n        return {\n          [Hash.symbol]() {\n            return 0\n          },\n          [Equal.symbol](that: any) {\n            return that.id === id\n          },\n          id,\n          s\n        }\n      }\n\n      assertTrue(equivalence(make(1, \"a\"), make(1, \"a\")))\n      assertTrue(equivalence(make(1, \"a\"), make(1, \"b\")))\n      assertFalse(equivalence(make(1, \"a\"), make(2, \"a\")))\n    })\n\n    it(\"Chunk\", () => {\n      const schema = S.ChunkFromSelf(MyNumber)\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence(Chunk.empty(), Chunk.empty()))\n      assertTrue(equivalence(Chunk.make(1, 2, 3), Chunk.make(1, 2, 3)))\n\n      assertFalse(equivalence(Chunk.make(1, 2, 3), Chunk.make(1, 2)))\n      assertFalse(equivalence(Chunk.make(1, 2, 3), Chunk.make(1, 2, 4)))\n\n      // propertyType(schema)\n    })\n\n    it(\"Date\", () => {\n      const schema = S.DateFromSelf\n      const equivalence = S.equivalence(schema)\n      const now = new Date()\n\n      assertTrue(equivalence(now, now))\n      assertTrue(equivalence(new Date(0), new Date(0)))\n\n      assertFalse(equivalence(new Date(0), new Date(1)))\n\n      // propertyType(schema)\n    })\n\n    it(\"Data\", () => {\n      const schema = S.DataFromSelf(S.Struct({ a: MyString, b: MyNumber }))\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence(Data.struct({ a: \"ok\", b: 0 }), Data.struct({ a: \"ok\", b: 0 })))\n\n      // propertyType(schema)\n    })\n\n    it(\"Either\", () => {\n      const schema = S.EitherFromSelf({ left: MyString, right: MyNumber })\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence(Either.right(1), Either.right(1)))\n      assertTrue(equivalence(Either.left(\"a\"), Either.left(\"a\")))\n\n      assertFalse(equivalence(Either.right(1), Either.right(2)))\n      assertFalse(equivalence(Either.left(\"a\"), Either.left(\"b\")))\n\n      // propertyType(schema)\n    })\n\n    it(\"Option\", () => {\n      const schema = S.OptionFromSelf(MyNumber)\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence(Option.none(), Option.none()))\n      assertTrue(equivalence(Option.some(1), Option.some(1)))\n\n      assertFalse(equivalence(Option.some(1), Option.some(2)))\n\n      // propertyType(schema)\n    })\n\n    it(\"ReadonlySet\", () => {\n      const schema = S.ReadonlySetFromSelf(MyNumber)\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence(new Set(), new Set()))\n      assertTrue(equivalence(new Set([1, 2, 3]), new Set([1, 2, 3])))\n\n      assertFalse(equivalence(new Set([1, 2, 3]), new Set([1, 2])))\n\n      // propertyType(schema)\n    })\n\n    it(\"ReadonlyMap\", () => {\n      const schema = S.ReadonlyMapFromSelf({ key: MyString, value: MyNumber })\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence(new Map(), new Map()))\n      assertTrue(equivalence(new Map([[\"a\", 1], [\"b\", 2]]), new Map([[\"a\", 1], [\"b\", 2]])))\n\n      assertFalse(equivalence(new Map([[\"a\", 1], [\"b\", 2]]), new Map([[\"a\", 3], [\"b\", 2]])))\n      assertFalse(equivalence(new Map([[\"a\", 1], [\"b\", 2]]), new Map([[\"a\", 1], [\"b\", 4]])))\n\n      // propertyType(schema)\n    })\n\n    it(\"Uint8Array\", () => {\n      const schema = S.Uint8ArrayFromSelf\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence(new Uint8Array(), new Uint8Array()))\n      assertTrue(\n        equivalence(new Uint8Array([10, 20, 30, 40, 50]), new Uint8Array([10, 20, 30, 40, 50]))\n      )\n\n      assertFalse(\n        equivalence(new Uint8Array([10, 20, 30, 40, 50]), new Uint8Array([10, 20, 30, 30, 50]))\n      )\n\n      // propertyType(schema)\n    })\n\n    it(\"instanceOf\", () => {\n      const schema = S.instanceOf(URL, {\n        equivalence: () => Equivalence.make((a, b) => a.href === b.href)\n      })\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence(new URL(\"https://example.com/page\"), new URL(\"https://example.com/page\")))\n\n      assertFalse(equivalence(new URL(\"https://example.com/page\"), new URL(\"https://google.come\")))\n    })\n  })\n\n  describe(\"union\", () => {\n    it(\"primitives\", () => {\n      const schema = S.Union(MyString, MyNumber)\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence(\"a\", \"a\"))\n      assertTrue(equivalence(1, 1))\n\n      assertFalse(equivalence(\"a\", \"b\"))\n      assertFalse(equivalence(1, 2))\n\n      // propertyType(schema)\n    })\n\n    it(\"should fallback on the less precise equivalence\", () => {\n      const a = S.Struct({ a: MyString })\n      const ab = S.Struct({ a: MyString, b: S.Number })\n      const schema = S.Union(a, ab)\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence({ a: \"a\", b: 1 }, { a: \"a\", b: 1 }))\n      assertTrue(equivalence({ a: \"a\", b: 1 }, { a: \"a\", b: 2 }))\n\n      assertFalse(equivalence({ a: \"a\", b: 1 }, { a: \"c\", b: 1 }))\n\n      // propertyType(schema)\n    })\n\n    it(\"discriminated structs\", () => {\n      const schema = S.Union(\n        S.Struct({ tag: S.Literal(\"a\"), a: MyString }),\n        S.Struct({ tag: S.Literal(\"b\"), b: S.Number })\n      )\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence({ tag: \"a\", a: \"a\" }, { tag: \"a\", a: \"a\" }))\n      assertTrue(equivalence({ tag: \"b\", b: 1 }, { tag: \"b\", b: 1 }))\n\n      assertFalse(equivalence({ tag: \"a\", a: \"a\" }, { tag: \"a\", a: \"b\" }))\n      assertFalse(equivalence({ tag: \"b\", b: 1 }, { tag: \"b\", b: 2 }))\n      assertFalse(equivalence({ tag: \"a\", a: \"a\" }, { tag: \"b\", b: 1 }))\n    })\n\n    it(\"discriminated tuples\", () => {\n      const schema = S.Union(\n        S.Tuple(S.Literal(\"a\"), S.String),\n        S.Tuple(S.Literal(\"b\"), S.Number)\n      )\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence([\"a\", \"x\"], [\"a\", \"x\"]))\n      assertFalse(equivalence([\"a\", \"x\"], [\"a\", \"y\"]))\n\n      assertTrue(equivalence([\"b\", 1], [\"b\", 1]))\n      assertFalse(equivalence([\"b\", 1], [\"b\", 2]))\n\n      assertFalse(equivalence([\"a\", \"x\"], [\"b\", 1]))\n    })\n  })\n\n  describe(\"tuple\", () => {\n    it(\"empty\", () => {\n      const schema = S.Tuple()\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence([], []))\n    })\n\n    it(\"should fail on non-array inputs\", () => {\n      const schema = S.Tuple(S.String, S.Number)\n      const equivalence = S.equivalence(schema)\n      assertFalse(equivalence([\"a\", 1], null as never))\n    })\n\n    it(\"e\", () => {\n      const schema = S.Tuple(MyString, MyNumber)\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence([\"a\", 1], [\"a\", 1]))\n\n      assertFalse(equivalence([\"a\", 1], [\"b\", 1]))\n      assertFalse(equivalence([\"a\", 1], [\"a\", 2]))\n\n      // propertyType(schema)\n    })\n\n    it(\"e r\", () => {\n      const schema = S.Tuple([S.String], S.Number)\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence([\"a\"], [\"a\"]))\n      assertTrue(equivalence([\"a\", 1], [\"a\", 1]))\n      assertTrue(equivalence([\"a\", 1, 2], [\"a\", 1, 2]))\n\n      assertFalse(equivalence([\"a\", 1], [\"a\", 2]))\n      assertFalse(equivalence([\"a\", 1, 2], [\"a\", 1, 3]))\n\n      // propertyType(schema)\n    })\n\n    it(\"r\", () => {\n      const schema = S.Array(MyNumber)\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence([], []))\n      assertTrue(equivalence([1], [1]))\n      assertTrue(equivalence([1, 2], [1, 2]))\n\n      assertFalse(equivalence([1, 2], [1, 2, 3]))\n      assertFalse(equivalence([1, 2, 3], [1, 2]))\n\n      // propertyType(schema)\n    })\n\n    it(\"r e\", () => {\n      const schema = S.Tuple([], MyString, MyNumber)\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence([1], [1]))\n      assertTrue(equivalence([\"a\", 1], [\"a\", 1]))\n      assertTrue(equivalence([\"a\", \"b\", 1], [\"a\", \"b\", 1]))\n\n      assertFalse(equivalence([1], [2]))\n      assertFalse(equivalence([2], [1]))\n      assertFalse(equivalence([\"a\", \"b\", 1], [\"a\", \"c\", 1]))\n\n      // propertyType(schema)\n    })\n\n    describe(\"optional element support\", () => {\n      it(\"e?\", () => {\n        const schema = S.Tuple(S.optionalElement(MyString))\n        const equivalence = S.equivalence(schema)\n\n        assertTrue(equivalence([], []))\n        assertTrue(equivalence([\"a\"], [\"a\"]))\n\n        assertFalse(equivalence([\"a\"], [\"b\"]))\n        assertFalse(equivalence([], [\"a\"]))\n        assertFalse(equivalence([\"a\"], []))\n\n        // propertyType(schema)\n      })\n\n      it(\"e? e?\", () => {\n        const schema = S.Tuple(S.optionalElement(MyString), S.optionalElement(MyNumber))\n        const equivalence = S.equivalence(schema)\n\n        assertTrue(equivalence([], []))\n        assertTrue(equivalence([\"a\"], [\"a\"]))\n        assertTrue(equivalence([\"a\"], [\"a\"]))\n        assertTrue(equivalence([\"a\", 1], [\"a\", 1]))\n\n        assertFalse(equivalence([\"a\"], [\"b\"]))\n        assertFalse(equivalence([\"a\", 1], [\"a\", 2]))\n        assertFalse(equivalence([\"a\", 1], [\"a\"]))\n        assertFalse(equivalence([], [\"a\"]))\n        assertFalse(equivalence([\"a\"], []))\n\n        // propertyType(schema)\n      })\n\n      it(\"e e?\", () => {\n        const schema = S.Tuple(MyString, S.optionalElement(MyNumber))\n        const equivalence = S.equivalence(schema)\n\n        assertTrue(equivalence([\"a\"], [\"a\"]))\n        assertTrue(equivalence([\"a\", 1], [\"a\", 1]))\n\n        assertFalse(equivalence([\"a\", 1], [\"a\", 2]))\n        assertFalse(equivalence([\"a\"], [\"a\", 1]))\n        assertFalse(equivalence([\"a\", 1], [\"a\"]))\n\n        // propertyType(schema)\n      })\n\n      it(\"e? r\", () => {\n        const schema = S.Tuple([S.optionalElement(S.String)], S.Number)\n        const equivalence = S.equivalence(schema)\n\n        assertTrue(equivalence([], []))\n        assertTrue(equivalence([\"a\"], [\"a\"]))\n        assertTrue(equivalence([\"a\", 1], [\"a\", 1]))\n\n        assertFalse(equivalence([], [\"a\"]))\n        assertFalse(equivalence([\"a\"], []))\n        assertFalse(equivalence([\"a\"], [\"b\"]))\n        assertFalse(equivalence([\"a\", 1], [\"a\", 2]))\n\n        // propertyType(schema)\n      })\n    })\n  })\n\n  describe(\"struct\", () => {\n    it(\"empty\", () => {\n      const schema = S.Struct({})\n      const equivalence = S.equivalence(schema)\n\n      assertFalse(equivalence({}, {}))\n    })\n\n    it(\"should fail on non-record inputs\", () => {\n      const schema = S.Struct({ a: S.String })\n      const equivalence = S.equivalence(schema)\n      assertFalse(equivalence({ a: \"a\" }, 1 as never))\n    })\n\n    it(\"string keys\", () => {\n      const schema = S.Struct({ a: MyString, b: MyNumber })\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence({ a: \"a\", b: 1 }, { a: \"a\", b: 1 }))\n      // should ignore excess properties\n      const d = Symbol.for(\"effect/Schema/test/d\")\n      const excess = {\n        a: \"a\",\n        b: 1,\n        c: true,\n        [d]: \"d\"\n      }\n      assertTrue(equivalence({ a: \"a\", b: 1 }, excess))\n\n      assertFalse(equivalence({ a: \"a\", b: 1 }, { a: \"c\", b: 1 }))\n      assertFalse(equivalence({ a: \"a\", b: 1 }, { a: \"a\", b: 2 }))\n\n      // propertyType(schema)\n    })\n\n    it(\"symbol keys\", () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const b = Symbol.for(\"effect/Schema/test/b\")\n      const schema = S.Struct({ [a]: MyString, [b]: MyNumber })\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence({ [a]: \"a\", [b]: 1 }, { [a]: \"a\", [b]: 1 }))\n      // should ignore excess properties\n      const d = Symbol.for(\"effect/Schema/test/d\")\n      const excess = {\n        [a]: \"a\",\n        [b]: 1,\n        c: true,\n        [d]: \"d\"\n      }\n      assertTrue(equivalence({ [a]: \"a\", [b]: 1 }, excess))\n\n      assertFalse(equivalence({ [a]: \"a\", [b]: 1 }, { [a]: \"c\", [b]: 1 }))\n      assertFalse(equivalence({ [a]: \"a\", [b]: 1 }, { [a]: \"a\", [b]: 2 }))\n\n      // propertyType(schema)\n    })\n\n    it(\"exact optional property signature\", () => {\n      const schema = S.Struct({\n        a: S.optionalWith(MyString, { exact: true }),\n        b: S.optionalWith(S.Union(MyNumber, S.Undefined), { exact: true })\n      })\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence({ a: \"a\", b: 1 }, { a: \"a\", b: 1 }))\n      assertTrue(equivalence({ b: 1 }, { b: 1 }))\n      assertTrue(equivalence({ a: \"a\" }, { a: \"a\" }))\n      assertTrue(equivalence({ a: \"a\", b: undefined }, { a: \"a\", b: undefined }))\n\n      assertFalse(equivalence({ a: \"a\" }, { b: 1 }))\n      assertFalse(equivalence({ a: \"a\", b: 1 }, { a: \"a\" }))\n      assertFalse(equivalence({ a: \"a\", b: undefined }, { a: \"a\" }))\n      assertFalse(equivalence({ a: \"a\" }, { a: \"a\", b: 1 }))\n      assertFalse(equivalence({ a: \"a\" }, { a: \"a\", b: undefined }))\n      assertFalse(equivalence({ a: \"a\", b: 1 }, { a: \"c\", b: 1 }))\n      assertFalse(equivalence({ a: \"a\", b: 1 }, { a: \"a\", b: 2 }))\n\n      // propertyType(schema)\n    })\n  })\n\n  describe(\"record\", () => {\n    it(\"record(never, number)\", () => {\n      const schema = S.Record({ key: S.Never, value: MyNumber })\n      const equivalence = S.equivalence(schema)\n\n      const input = {}\n      assertTrue(equivalence(input, input))\n      assertFalse(equivalence({}, {}))\n    })\n\n    it(\"record(string, number)\", () => {\n      const schema = S.Record({ key: MyString, value: MyNumber })\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence({}, {}))\n      assertTrue(equivalence({ a: 1 }, { a: 1 }))\n      assertTrue(equivalence({ a: 1, b: 2 }, { a: 1, b: 2 }))\n      // should ignore symbol excess properties\n      const d = Symbol.for(\"effect/Schema/test/d\")\n      assertTrue(equivalence({ a: 1, b: 2 }, { a: 1, b: 2, [d]: \"d\" }))\n\n      assertFalse(equivalence({ a: 1 }, { a: 2 }))\n      assertFalse(equivalence({ a: 1, b: 2 }, { a: 1 }))\n      assertFalse(equivalence({ a: 1 }, { a: 1, b: 2 }))\n      assertFalse(equivalence({ a: 1 }, { b: 1 }))\n\n      // propertyType(schema)\n    })\n\n    it(\"record(symbol, number)\", () => {\n      const schema = S.Record({ key: MySymbol, value: MyNumber })\n      const equivalence = S.equivalence(schema)\n\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const b = Symbol.for(\"effect/Schema/test/b\")\n      assertTrue(equivalence({}, {}))\n      assertTrue(equivalence({ [a]: 1 }, { [a]: 1 }))\n      assertTrue(equivalence({ [a]: 1, [b]: 2 }, { [a]: 1, [b]: 2 }))\n      // should ignore string excess properties\n      const excess = { [a]: 1, [b]: 2, c: \"c\" }\n      assertTrue(equivalence({ [a]: 1, [b]: 2 }, excess))\n\n      assertFalse(equivalence({ [a]: 1 }, { [a]: 2 }))\n      assertFalse(equivalence({ [a]: 1, [b]: 2 }, { [a]: 1 }))\n      assertFalse(equivalence({ [a]: 1 }, { [a]: 1, [b]: 2 }))\n      assertFalse(equivalence({ [a]: 1 }, { [b]: 1 }))\n\n      // propertyType(schema)\n    })\n\n    it(\"struct record\", () => {\n      const schema = S.Struct({ a: MyString, b: MyString }, S.Record({ key: MyString, value: MyString }))\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence({ a: \"a\", b: \"b\" }, { a: \"a\", b: \"b\" }))\n      assertTrue(equivalence({ a: \"a\", b: \"b\", c: \"c\" }, { a: \"a\", b: \"b\", c: \"c\" }))\n\n      assertFalse(equivalence({ a: \"a\", b: \"b\" }, { a: \"c\", b: \"b\" }))\n      assertFalse(equivalence({ a: \"a\", b: \"b\" }, { a: \"a\", b: \"c\" }))\n      assertFalse(equivalence({ a: \"a\", b: \"b\", c: \"c1\" }, { a: \"a\", b: \"b\", c: \"c2\" }))\n\n      // propertyType(schema)\n    })\n\n    it(\"custom equivalence\", () => {\n      const schema = S.Struct({ a: MyString, b: MyString }).annotations({\n        equivalence: () => Equivalence.make((x, y) => x.a === y.a)\n      })\n      const equivalence = S.equivalence(schema)\n\n      assertTrue(equivalence({ a: \"a\", b: \"b\" }, { a: \"a\", b: \"b\" }))\n      assertTrue(equivalence({ a: \"a\", b: \"b\" }, { a: \"a\", b: \"c\" }))\n\n      assertFalse(equivalence({ a: \"a\", b: \"b\" }, { a: \"c\", b: \"b\" }))\n\n      // propertyType(schema)\n    })\n  })\n\n  describe(\"Suspend\", () => {\n    it(\"should support suspended schemas\", () => {\n      interface A {\n        readonly a: string\n        readonly as: ReadonlyArray<A>\n      }\n      const schema = S.Struct({\n        a: MyString,\n        as: S.Array(S.suspend((): S.Schema<A> => schema))\n      })\n\n      const equivalence = S.equivalence(schema)\n\n      const a1: A = { a: \"a1\", as: [] }\n      assertTrue(equivalence(a1, a1))\n      const a2: A = { a: \"a1\", as: [{ a: \"a2\", as: [] }] }\n      assertTrue(equivalence(a2, a2))\n      const a3: A = { a: \"a1\", as: [{ a: \"a2\", as: [] }, { a: \"a3\", as: [{ a: \"a4\", as: [] }] }] }\n      assertTrue(equivalence(a3, a3))\n\n      const a4: A = { a: \"a1\", as: [{ a: \"a2\", as: [] }, { a: \"a3\", as: [{ a: \"a4\", as: [] }] }] }\n      const a5: A = { a: \"a1\", as: [{ a: \"a2\", as: [] }, { a: \"a3\", as: [{ a: \"a5\", as: [] }] }] }\n      assertFalse(equivalence(a4, a5))\n\n      // propertyType(schema, { numRuns: 5 })\n    })\n\n    it(\"should support mutually suspended schemas\", () => {\n      interface Expression {\n        readonly type: \"expression\"\n        readonly value: number | Operation\n      }\n\n      interface Operation {\n        readonly type: \"operation\"\n        readonly operator: \"+\" | \"-\"\n        readonly left: Expression\n        readonly right: Expression\n      }\n\n      const Expression = S.Struct({\n        type: S.Literal(\"expression\"),\n        value: S.Union(MyNumber, S.suspend((): S.Schema<Operation> => Operation))\n      })\n\n      const Operation = S.Struct({\n        type: S.Literal(\"operation\"),\n        operator: S.Union(S.Literal(\"+\"), S.Literal(\"-\")),\n        left: Expression,\n        right: Expression\n      })\n\n      const equivalence = S.equivalence(Operation)\n\n      const a1: Operation = {\n        type: \"operation\",\n        operator: \"+\",\n        left: {\n          type: \"expression\",\n          value: 1\n        },\n        right: {\n          type: \"expression\",\n          value: {\n            type: \"operation\",\n            operator: \"-\",\n            left: {\n              type: \"expression\",\n              value: 3\n            },\n            right: {\n              type: \"expression\",\n              value: 2\n            }\n          }\n        }\n      }\n      assertTrue(equivalence(a1, a1))\n\n      const a2: Operation = {\n        type: \"operation\",\n        operator: \"+\",\n        left: {\n          type: \"expression\",\n          value: 1\n        },\n        right: {\n          type: \"expression\",\n          value: {\n            type: \"operation\",\n            operator: \"-\",\n            left: {\n              type: \"expression\",\n              value: 3\n            },\n            right: {\n              type: \"expression\",\n              value: 4\n            }\n          }\n        }\n      }\n      assertFalse(equivalence(a1, a2))\n\n      // propertyType(Operation, { numRuns: 5 })\n    })\n  })\n\n  describe(\"should handle annotations\", () => {\n    const expectHook = <A, I>(source: S.Schema<A, I>) => {\n      const schema = source.annotations({ equivalence: () => () => true })\n      const eq = S.equivalence(schema)\n      assertTrue(eq(\"a\" as any, \"b\" as any))\n    }\n\n    it(\"void\", () => {\n      expectHook(S.Void)\n    })\n\n    it(\"never\", () => {\n      expectHook(S.Never)\n    })\n\n    it(\"literal\", () => {\n      expectHook(S.Literal(\"a\"))\n    })\n\n    it(\"symbol\", () => {\n      expectHook(S.Symbol)\n    })\n\n    it(\"uniqueSymbolFromSelf\", () => {\n      expectHook(S.UniqueSymbolFromSelf(Symbol.for(\"effect/schema/test/a\")))\n    })\n\n    it(\"templateLiteral\", () => {\n      expectHook(S.TemplateLiteral(S.Literal(\"a\"), S.String, S.Literal(\"b\")))\n    })\n\n    it(\"undefined\", () => {\n      expectHook(S.Undefined)\n    })\n\n    it(\"unknown\", () => {\n      expectHook(S.Unknown)\n    })\n\n    it(\"any\", () => {\n      expectHook(S.Any)\n    })\n\n    it(\"object\", () => {\n      expectHook(S.Object)\n    })\n\n    it(\"string\", () => {\n      expectHook(S.String)\n    })\n\n    it(\"number\", () => {\n      expectHook(S.Number)\n    })\n\n    it(\"bigintFromSelf\", () => {\n      expectHook(S.BigIntFromSelf)\n    })\n\n    it(\"boolean\", () => {\n      expectHook(S.Boolean)\n    })\n\n    it(\"enums\", () => {\n      enum Fruits {\n        Apple,\n        Banana\n      }\n      expectHook(S.Enums(Fruits))\n    })\n\n    it(\"tuple\", () => {\n      expectHook(S.Tuple(S.String, S.Number))\n    })\n\n    it(\"struct\", () => {\n      expectHook(S.Struct({ a: S.String, b: S.Number }))\n    })\n\n    it(\"union\", () => {\n      expectHook(S.Union(S.String, S.Number))\n    })\n\n    it(\"suspend\", () => {\n      interface A {\n        readonly a: string\n        readonly as: ReadonlyArray<A>\n      }\n      const schema = S.Struct({\n        a: S.String,\n        as: S.Array(S.suspend((): S.Schema<A> => schema))\n      })\n      expectHook(schema)\n    })\n\n    it(\"refinement\", () => {\n      expectHook(S.Int)\n    })\n\n    it(\"transformation\", () => {\n      expectHook(S.NumberFromString)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/extend.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual, throws } from \"@effect/vitest/utils\"\nimport * as Arbitrary from \"effect/Arbitrary\"\nimport * as FastCheck from \"effect/FastCheck\"\nimport * as Schema from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../TestUtils.js\"\n\nconst assertExtend = (A: Schema.Schema.Any, B: Schema.Schema.Any, expected: readonly [string, string], options?: {\n  readonly skipFastCheck?: boolean | undefined\n}) => {\n  const AB = Schema.extend(A, B)\n  const BA = Schema.extend(B, A)\n  strictEqual(String(AB), expected[0], \"AB\")\n  strictEqual(String(BA), expected[1], \"BA\")\n  const arbAB = Arbitrary.make(AB)\n  const arbBA = Arbitrary.make(BA)\n  const isAB = Schema.is(AB)\n  const isBA = Schema.is(BA)\n  if (options?.skipFastCheck) {\n    return\n  }\n  FastCheck.assert(\n    FastCheck.property(arbAB, (ab) => isBA(ab)),\n    { numRuns: 10 }\n  )\n  FastCheck.assert(\n    FastCheck.property(arbBA, (ba) => isAB(ba)),\n    { numRuns: 10 }\n  )\n}\n\ndescribe(\"extend\", () => {\n  describe(\"String\", () => {\n    it(\"String & String\", () => {\n      const schema = Schema.extend(Schema.String, Schema.String)\n      deepStrictEqual(schema.ast, Schema.String.ast)\n    })\n\n    it(\"String & Literal\", () => {\n      const literal = Schema.Literal(\"a\")\n      const schema = Schema.extend(Schema.String, literal)\n      deepStrictEqual(schema.ast, literal.ast)\n    })\n\n    it(\"Literal & String\", () => {\n      const literal = Schema.Literal(\"a\")\n      const schema = Schema.extend(literal, Schema.String)\n      deepStrictEqual(schema.ast, literal.ast)\n    })\n\n    it(\"(String with annotations) & String\", () => {\n      const A = Schema.String.annotations({ identifier: \"A\" })\n      const schema = Schema.extend(A, Schema.String)\n      assertTrue(schema.ast === A.ast)\n    })\n\n    it(\"String & Refinement\", () => {\n      const schema = Schema.extend(\n        Schema.String,\n        Schema.String.pipe(Schema.startsWith(\"start:\"))\n      )\n      strictEqual(String(schema), `startsWith(\"start:\")`)\n      assertTrue(AST.isRefinement(schema.ast))\n      assertTrue(schema.ast.from === AST.stringKeyword)\n    })\n\n    it(\"String Branded Refinement & String Branded Refinement\", () => {\n      const startsWith = Schema.String.pipe(Schema.startsWith(\"start:\"), Schema.brand(\"start:\"))\n      const endsWith = Schema.String.pipe(Schema.endsWith(\":end\"), Schema.brand(\":end\"))\n      const schema = Schema.extend(startsWith, endsWith)\n      strictEqual(String(schema), `startsWith(\"start:\") & Brand<\"start:\"> & endsWith(\":end\") & Brand<\":end\">`)\n      deepStrictEqual(schema.ast.annotations[AST.BrandAnnotationId], [\":end\"])\n      assertTrue(AST.isRefinement(schema.ast))\n      const from = schema.ast.from\n      deepStrictEqual(from.annotations[AST.BrandAnnotationId], [\"start:\"])\n      assertTrue(AST.isRefinement(from))\n      const fromfrom = from.from\n      assertTrue(fromfrom === AST.stringKeyword)\n    })\n  })\n\n  describe(\"Number\", () => {\n    it(\"Number & Number\", () => {\n      const schema = Schema.extend(Schema.Number, Schema.Number)\n      deepStrictEqual(schema.ast, Schema.Number.ast)\n    })\n\n    it(\"Number & Literal\", () => {\n      const literal = Schema.Literal(1)\n      const schema = Schema.extend(Schema.Number, literal)\n      deepStrictEqual(schema.ast, literal.ast)\n    })\n\n    it(\"Literal & Number\", () => {\n      const literal = Schema.Literal(1)\n      const schema = Schema.extend(literal, Schema.Number)\n      deepStrictEqual(schema.ast, literal.ast)\n    })\n\n    it(\"(Number with annotations) & Number\", () => {\n      const A = Schema.Number.annotations({ identifier: \"A\" })\n      const schema = Schema.extend(A, Schema.Number)\n      assertTrue(schema.ast === A.ast)\n    })\n\n    it(\"Number & Refinement\", () => {\n      const schema = Schema.extend(\n        Schema.Number,\n        Schema.Number.pipe(Schema.greaterThan(0))\n      )\n      assertTrue(AST.isRefinement(schema.ast))\n      assertTrue(schema.ast.from === AST.numberKeyword)\n    })\n\n    it(\"Number Branded Refinement & Number Branded Refinement\", () => {\n      const gt0 = Schema.Number.pipe(Schema.greaterThan(0), Schema.brand(\"> 0\"))\n      const lt2 = Schema.Number.pipe(Schema.lessThan(2), Schema.brand(\"< 2\"))\n      const schema = Schema.extend(gt0, lt2)\n      strictEqual(String(schema.ast), `greaterThan(0) & Brand<\"> 0\"> & lessThan(2) & Brand<\"< 2\">`)\n      deepStrictEqual(schema.ast.annotations[AST.BrandAnnotationId], [\"< 2\"])\n      assertTrue(AST.isRefinement(schema.ast))\n      const from = schema.ast.from\n      deepStrictEqual(from.annotations[AST.BrandAnnotationId], [\"> 0\"])\n      assertTrue(AST.isRefinement(from))\n      const fromfrom = from.from\n      assertTrue(fromfrom === AST.numberKeyword)\n    })\n  })\n\n  describe(\"Boolean\", () => {\n    it(\"Boolean & Boolean\", () => {\n      const schema = Schema.extend(Schema.Boolean, Schema.Boolean)\n      deepStrictEqual(schema.ast, Schema.Boolean.ast)\n    })\n\n    it(\"Boolean & Literal\", () => {\n      const literal = Schema.Literal(true)\n      const schema = Schema.extend(Schema.Boolean, literal)\n      deepStrictEqual(schema.ast, literal.ast)\n    })\n\n    it(\"Literal & Boolean\", () => {\n      const literal = Schema.Literal(true)\n      const schema = Schema.extend(literal, Schema.Boolean)\n      deepStrictEqual(schema.ast, literal.ast)\n    })\n  })\n\n  describe(\"Struct\", () => {\n    it(\"Struct & Struct\", async () => {\n      const A = Schema.Struct({ a: Schema.String })\n      const B = Schema.Struct({ b: Schema.Number })\n      assertExtend(A, B, [\n        \"{ readonly a: string; readonly b: number }\",\n        \"{ readonly b: number; readonly a: string }\"\n      ])\n    })\n\n    it(\"Struct $ TypeLiteralTransformation\", async () => {\n      const A = Schema.Struct({ a: Schema.Number })\n      const B = Schema.Struct({\n        b: Schema.String,\n        c: Schema.optionalWith(Schema.String, { exact: true, default: () => \"\" })\n      })\n      assertExtend(A, B, [\n        \"({ readonly b: string; readonly c?: string; readonly a: number } <-> { readonly b: string; readonly c: string; readonly a: number })\",\n        \"({ readonly b: string; readonly c?: string; readonly a: number } <-> { readonly b: string; readonly c: string; readonly a: number })\"\n      ])\n    })\n\n    it(\"Struct & Union\", () => {\n      const A = Schema.Struct({ b: Schema.Boolean })\n      const B = Schema.Union(\n        Schema.Struct({ a: Schema.Literal(\"a\") }),\n        Schema.Struct({ a: Schema.Literal(\"b\") })\n      )\n      assertExtend(A, B, [\n        `{ readonly b: boolean; readonly a: \"a\" } | { readonly b: boolean; readonly a: \"b\" }`,\n        `{ readonly a: \"a\"; readonly b: boolean } | { readonly a: \"b\"; readonly b: boolean }`\n      ])\n    })\n\n    it(\"Struct & Record(string, string)\", async () => {\n      const A = Schema.Struct({ a: Schema.String })\n      const B = Schema.Record({ key: Schema.String, value: Schema.String })\n      assertExtend(A, B, [\n        `{ readonly a: string; readonly [x: string]: string }`,\n        `{ readonly a: string; readonly [x: string]: string }`\n      ])\n    })\n\n    it(\"Struct & Record(templateLiteral, string)\", async () => {\n      const A = Schema.Struct({ a: Schema.String })\n      const B = Schema.Record(\n        {\n          key: Schema.TemplateLiteral(\n            Schema.String,\n            Schema.Literal(\"-\"),\n            Schema.Number\n          ),\n          value: Schema.String\n        }\n      )\n      assertExtend(A, B, [\n        \"{ readonly a: string; readonly [x: `${string}-${number}`]: string }\",\n        \"{ readonly a: string; readonly [x: `${string}-${number}`]: string }\"\n      ])\n    })\n\n    it(\"Struct & Record(string, NumberFromChar)\", async () => {\n      const A = Schema.Struct({ a: Schema.Number })\n      const B = Schema.Record({ key: Schema.String, value: Util.NumberFromChar })\n      assertExtend(A, B, [\n        `{ readonly a: number; readonly [x: string]: NumberFromChar }`,\n        `{ readonly a: number; readonly [x: string]: NumberFromChar }`\n      ])\n    })\n\n    it(\"Struct & Record(symbol, NumberFromChar)\", async () => {\n      const A = Schema.Struct({ a: Schema.Number })\n      const B = Schema.Record({ key: Schema.SymbolFromSelf, value: Util.NumberFromChar })\n      assertExtend(A, B, [\n        `{ readonly a: number; readonly [x: symbol]: NumberFromChar }`,\n        `{ readonly a: number; readonly [x: symbol]: NumberFromChar }`\n      ])\n    })\n\n    it(\"Nested Struct & Nested Struct\", async () => {\n      const A = Schema.Struct({ a: Schema.Struct({ b: Schema.String }) })\n      const B = Schema.Struct({ a: Schema.Struct({ c: Schema.Number }) })\n      assertExtend(A, B, [\n        `{ readonly a: { readonly b: string; readonly c: number } }`,\n        `{ readonly a: { readonly c: number; readonly b: string } }`\n      ])\n    })\n\n    it(\"Nested Struct with refinements & Nested struct with refinements\", async () => {\n      const A = Schema.Struct({\n        nested: Schema.Struct({\n          same: Schema.String.pipe(Schema.startsWith(\"start:\")),\n          different1: Schema.String\n        })\n      })\n      const B = Schema.Struct({\n        nested: Schema.Struct({\n          same: Schema.String.pipe(Schema.endsWith(\":end\")),\n          different2: Schema.String\n        })\n      })\n      assertExtend(A, B, [\n        `{ readonly nested: { readonly same: startsWith(\"start:\") & endsWith(\":end\"); readonly different1: string; readonly different2: string } }`,\n        `{ readonly nested: { readonly same: endsWith(\":end\") & startsWith(\"start:\"); readonly different2: string; readonly different1: string } }`\n      ], { skipFastCheck: true })\n      const schema = Schema.extend(A, B)\n      await Util.assertions.decoding.succeed(\n        schema,\n        {\n          nested: {\n            same: \"start:5:end\",\n            different1: \"\",\n            different2: \"\"\n          }\n        }\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        {\n          nested: {\n            same: \"\",\n            different1: \"\",\n            different2: \"\"\n          }\n        },\n        `{ readonly nested: { readonly same: startsWith(\"start:\") & endsWith(\":end\"); readonly different1: string; readonly different2: string } }\n└─ [\"nested\"]\n   └─ { readonly same: startsWith(\"start:\") & endsWith(\":end\"); readonly different1: string; readonly different2: string }\n      └─ [\"same\"]\n         └─ startsWith(\"start:\") & endsWith(\":end\")\n            └─ From side refinement failure\n               └─ startsWith(\"start:\")\n                  └─ Predicate refinement failure\n                     └─ Expected a string starting with \"start:\", actual \"\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        {\n          nested: {\n            same: \"start:5\",\n            different1: \"\",\n            different2: \"\"\n          }\n        },\n        `{ readonly nested: { readonly same: startsWith(\"start:\") & endsWith(\":end\"); readonly different1: string; readonly different2: string } }\n└─ [\"nested\"]\n   └─ { readonly same: startsWith(\"start:\") & endsWith(\":end\"); readonly different1: string; readonly different2: string }\n      └─ [\"same\"]\n         └─ startsWith(\"start:\") & endsWith(\":end\")\n            └─ Predicate refinement failure\n               └─ Expected a string ending with \":end\", actual \"start:5\"`\n      )\n    })\n  })\n\n  describe(\"TypeLiteralTransformation\", () => {\n    it(\"TypeLiteralTransformation & Struct\", async () => {\n      const A = Schema.Struct({\n        a: Schema.optionalWith(Schema.String, { exact: true, default: () => \"\" }),\n        b: Schema.String\n      })\n      const B = Schema.Struct({ c: Schema.Number })\n      assertExtend(A, B, [\n        \"({ readonly a?: string; readonly b: string; readonly c: number } <-> { readonly a: string; readonly b: string; readonly c: number })\",\n        \"({ readonly a?: string; readonly b: string; readonly c: number } <-> { readonly a: string; readonly b: string; readonly c: number })\"\n      ])\n    })\n\n    it(\"TypeLiteralTransformation & Union\", async () => {\n      const A = Schema.Struct({\n        a: Schema.optionalWith(Schema.String, { default: () => \"default\" })\n      })\n      const B = Schema.Union(\n        Schema.Struct({ b: Schema.String }),\n        Schema.Struct({ c: Schema.String })\n      )\n      assertExtend(A, B, [\n        \"({ readonly a?: string | undefined; readonly b: string } <-> { readonly a: string; readonly b: string }) | ({ readonly a?: string | undefined; readonly c: string } <-> { readonly a: string; readonly c: string })\",\n        \"({ readonly a?: string | undefined; readonly b: string } <-> { readonly a: string; readonly b: string }) | ({ readonly a?: string | undefined; readonly c: string } <-> { readonly a: string; readonly c: string })\"\n      ])\n    })\n\n    it(\"TypeLiteralTransformation & Refinement\", async () => {\n      const A = Schema.Struct({\n        a: Schema.optionalWith(Schema.String, { default: () => \"default\" })\n      })\n      const B = Schema.Struct({ b: Schema.String }).pipe(Schema.filter(() => true))\n      assertExtend(A, B, [\n        \"{ ({ readonly a?: string | undefined; readonly b: string } <-> { readonly a: string; readonly b: string }) | filter }\",\n        \"{ ({ readonly a?: string | undefined; readonly b: string } <-> { readonly a: string; readonly b: string }) | filter }\"\n      ])\n    })\n\n    it(\"TypeLiteralTransformation & Suspend\", async () => {\n      const suspend = Schema.suspend(() => Schema.Struct({ b: Schema.String }))\n      const schema = Schema.extend(\n        Schema.Struct({\n          a: Schema.optionalWith(Schema.String, { default: () => \"default\" })\n        }),\n        suspend\n      )\n      strictEqual(\n        String((schema.ast as AST.Suspend).f()),\n        \"({ readonly a?: string | undefined; readonly b: string } <-> { readonly a: string; readonly b: string })\"\n      )\n    })\n\n    it(\"TypeLiteralTransformation & TypeLiteralTransformation\", async () => {\n      const A = Schema.Struct({\n        a: Schema.optionalWith(Schema.String, { exact: true, default: () => \"\" }),\n        b: Schema.String\n      })\n      const B = Schema.Struct({\n        c: Schema.optionalWith(Schema.Number, { exact: true, default: () => 0 }),\n        d: Schema.Boolean\n      })\n      assertExtend(A, B, [\n        \"({ readonly a?: string; readonly b: string; readonly c?: number; readonly d: boolean } <-> { readonly a: string; readonly b: string; readonly c: number; readonly d: boolean })\",\n        \"({ readonly c?: number; readonly d: boolean; readonly a?: string; readonly b: string } <-> { readonly c: number; readonly d: boolean; readonly a: string; readonly b: string })\"\n      ])\n    })\n  })\n\n  describe(\"FinalTransformation\", () => {\n    it(\"FinalTransformation & Struct\", async () => {\n      const A = Schema.Struct({\n        a: Schema.String\n      })\n\n      const B = Schema.Struct({\n        b: Schema.String\n      })\n\n      const C = Schema.Struct({\n        c: Schema.String\n      })\n\n      const AB = Schema.transform(A, B, {\n        strict: true,\n        decode: (a) => ({ b: a.a }),\n        encode: (b) => ({ a: b.b })\n      })\n\n      assertExtend(AB, C, [\n        \"({ readonly a: string; readonly c: string } <-> { readonly b: string; readonly c: string })\",\n        \"({ readonly a: string; readonly c: string } <-> { readonly b: string; readonly c: string })\"\n      ])\n    })\n  })\n\n  describe(\"ComposeTransformation\", () => {\n    it(\"ComposeTransformation & Struct\", async () => {\n      const A = Schema.Struct({\n        a: Schema.NumberFromString\n      })\n\n      const B = Schema.Struct({\n        a: Schema.Number\n      })\n\n      const AB = Schema.compose(A, B)\n\n      const C = Schema.Struct({\n        c: Schema.String\n      })\n\n      assertExtend(AB, C, [\n        \"({ readonly a: NumberFromString; readonly c: string } <-> { readonly a: number; readonly c: string })\",\n        \"({ readonly a: NumberFromString; readonly c: string } <-> { readonly a: number; readonly c: string })\"\n      ])\n\n      const schema = Schema.extend(AB, C)\n      await Util.assertions.decoding.succeed(\n        schema,\n        { a: \"1\", c: \"c\" },\n        { a: 1, c: \"c\" }\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\", c: \"c\" },\n        `({ readonly a: NumberFromString; readonly c: string } <-> { readonly a: number; readonly c: string })\n└─ Encoded side transformation failure\n   └─ { readonly a: NumberFromString; readonly c: string }\n      └─ [\"a\"]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n      )\n    })\n  })\n\n  describe(\"Union\", () => {\n    it(\"Union & Struct\", () => {\n      const A = Schema.Union(\n        Schema.Struct({ a: Schema.Literal(\"a\") }),\n        Schema.Struct({ b: Schema.Literal(\"b\") })\n      )\n      const B = Schema.Struct({ c: Schema.Boolean })\n      assertExtend(A, B, [\n        `{ readonly a: \"a\"; readonly c: boolean } | { readonly b: \"b\"; readonly c: boolean }`,\n        `{ readonly c: boolean; readonly a: \"a\" } | { readonly c: boolean; readonly b: \"b\" }`\n      ])\n    })\n\n    it(\"Union of structs with defaults & Union of structs with defaults\", async () => {\n      const A = Schema.Union(\n        Schema.Struct({\n          a: Schema.optionalWith(Schema.String, { exact: true, default: () => \"a\" }),\n          b: Schema.String\n        }),\n        Schema.Struct({\n          c: Schema.optionalWith(Schema.String, { exact: true, default: () => \"c\" }),\n          d: Schema.String\n        })\n      )\n      const B = Schema.Union(\n        Schema.Struct({\n          e: Schema.optionalWith(Schema.String, { exact: true, default: () => \"e\" }),\n          f: Schema.String\n        }),\n        Schema.Struct({\n          g: Schema.optionalWith(Schema.String, { exact: true, default: () => \"g\" }),\n          h: Schema.String\n        })\n      )\n      assertExtend(A, B, [\n        \"({ readonly a?: string; readonly b: string; readonly e?: string; readonly f: string } <-> { readonly a: string; readonly b: string; readonly e: string; readonly f: string }) | ({ readonly a?: string; readonly b: string; readonly g?: string; readonly h: string } <-> { readonly a: string; readonly b: string; readonly g: string; readonly h: string }) | ({ readonly c?: string; readonly d: string; readonly e?: string; readonly f: string } <-> { readonly c: string; readonly d: string; readonly e: string; readonly f: string }) | ({ readonly c?: string; readonly d: string; readonly g?: string; readonly h: string } <-> { readonly c: string; readonly d: string; readonly g: string; readonly h: string })\",\n        \"({ readonly e?: string; readonly f: string; readonly a?: string; readonly b: string } <-> { readonly e: string; readonly f: string; readonly a: string; readonly b: string }) | ({ readonly e?: string; readonly f: string; readonly c?: string; readonly d: string } <-> { readonly e: string; readonly f: string; readonly c: string; readonly d: string }) | ({ readonly g?: string; readonly h: string; readonly a?: string; readonly b: string } <-> { readonly g: string; readonly h: string; readonly a: string; readonly b: string }) | ({ readonly g?: string; readonly h: string; readonly c?: string; readonly d: string } <-> { readonly g: string; readonly h: string; readonly c: string; readonly d: string })\"\n      ])\n    })\n\n    it(\"Union & Union\", () => {\n      const A = Schema.Union(\n        Schema.Struct({ a: Schema.Literal(\"a\") }),\n        Schema.Struct({ a: Schema.Literal(\"b\") })\n      )\n      const B = Schema.Union(\n        Schema.Struct({ c: Schema.Boolean }),\n        Schema.Struct({ d: Schema.Number })\n      )\n      assertExtend(A, B, [\n        `{ readonly a: \"a\"; readonly c: boolean } | { readonly a: \"a\"; readonly d: number } | { readonly a: \"b\"; readonly c: boolean } | { readonly a: \"b\"; readonly d: number }`,\n        `{ readonly c: boolean; readonly a: \"a\" } | { readonly c: boolean; readonly a: \"b\" } | { readonly d: number; readonly a: \"a\" } | { readonly d: number; readonly a: \"b\" }`\n      ])\n    })\n\n    it(\"Nested Union & Struct\", () => {\n      const A = Schema.Union(\n        Schema.Union(\n          Schema.Struct({ a: Schema.Literal(\"a\") }),\n          Schema.Struct({ a: Schema.Literal(\"b\") })\n        ),\n        Schema.Struct({ b: Schema.Literal(\"b\") })\n      )\n      const B = Schema.Struct({ c: Schema.Boolean })\n      assertExtend(A, B, [\n        `{ readonly a: \"a\"; readonly c: boolean } | { readonly a: \"b\"; readonly c: boolean } | { readonly b: \"b\"; readonly c: boolean }`,\n        `{ readonly c: boolean; readonly a: \"a\" } | { readonly c: boolean; readonly a: \"b\" } | { readonly c: boolean; readonly b: \"b\" }`\n      ])\n    })\n  })\n\n  describe(\"Refinements\", () => {\n    it(\"Struct & Refinement\", async () => {\n      const A = Schema.Struct({ a: Schema.String })\n      const B = Schema.Struct({ b: Schema.Number }).pipe(\n        Schema.filter((input) => input.b > 0, { message: () => \"R filter\" })\n      )\n      assertExtend(A, B, [\n        `{ { readonly a: string; readonly b: number } | filter }`,\n        `{ { readonly b: number; readonly a: string } | filter }`\n      ])\n      const schema = Schema.extend(A, B)\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\", b: -1 },\n        `R filter`\n      )\n    })\n\n    it(\"Struct & Refinement (two filters)\", async () => {\n      const A = Schema.Struct({ a: Schema.String })\n      const B = Schema.Struct({ b: Schema.Number }).pipe(\n        Schema.filter((input) => input.b > 0, { message: () => \"filter1\" }),\n        Schema.filter((input) => input.b < 10, { message: () => \"filter2\" })\n      )\n      assertExtend(A, B, [\n        `{ { { readonly a: string; readonly b: number } | filter } | filter }`,\n        `{ { { readonly b: number; readonly a: string } | filter } | filter }`\n      ])\n      const schema = Schema.extend(A, B)\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\", b: -1 },\n        `filter1`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\", b: 11 },\n        `filter2`\n      )\n    })\n\n    it(\"Refinement & Refinement\", async () => {\n      const A = Schema.Struct({ a: Schema.String }).pipe(\n        Schema.filter((input) => input.a.length > 0, { message: () => \"R1 filter\" })\n      )\n      const B = Schema.Struct({ b: Schema.Number }).pipe(\n        Schema.filter((input) => input.b > 0, { message: () => \"R2 filter\" })\n      )\n      assertExtend(A, B, [\n        `{ { { readonly a: string; readonly b: number } | filter } | filter }`,\n        `{ { { readonly b: number; readonly a: string } | filter } | filter }`\n      ])\n      const schema = Schema.extend(A, B)\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"\", b: 1 },\n        `R1 filter`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\", b: -1 },\n        `R2 filter`\n      )\n    })\n\n    it(\"Union of structs & Refinement\", async () => {\n      const S1 = Schema.Struct({ a: Schema.String })\n      const S2 = Schema.Struct({ b: Schema.Number })\n      const B = Schema.Struct({ c: Schema.Boolean }).pipe(\n        Schema.filter((input) => input.c === true, { message: () => \"R filter\" })\n      )\n      const A = Schema.Union(S1, S2)\n      assertExtend(A, B, [\n        `{ { readonly a: string; readonly c: boolean } | filter } | { { readonly b: number; readonly c: boolean } | filter }`,\n        `{ { readonly c: boolean; readonly a: string } | filter } | { { readonly c: boolean; readonly b: number } | filter }`\n      ])\n\n      const schema = Schema.extend(A, B)\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\", c: false },\n        `{ { readonly a: string; readonly c: boolean } | filter } | { { readonly b: number; readonly c: boolean } | filter }\n├─ R filter\n└─ { { readonly b: number; readonly c: boolean } | filter }\n   └─ From side refinement failure\n      └─ { readonly b: number; readonly c: boolean }\n         └─ [\"b\"]\n            └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { b: 1, c: false },\n        `{ { readonly a: string; readonly c: boolean } | filter } | { { readonly b: number; readonly c: boolean } | filter }\n├─ { { readonly a: string; readonly c: boolean } | filter }\n│  └─ From side refinement failure\n│     └─ { readonly a: string; readonly c: boolean }\n│        └─ [\"a\"]\n│           └─ is missing\n└─ R filter`\n      )\n    })\n\n    it(\"Union of refinements & Refinement\", async () => {\n      const R1 = Schema.Struct({ a: Schema.String }).pipe(\n        Schema.filter((input) => input.a.length > 0, { message: () => \"R1 filter\" })\n      )\n      const R2 = Schema.Struct({ b: Schema.Number }).pipe(\n        Schema.filter((input) => input.b > 0, { message: () => \"R2 filter\" })\n      )\n      const B = Schema.Struct({ c: Schema.Boolean }).pipe(\n        Schema.filter((input) => input.c === true, { message: () => \"R3 filter\" })\n      )\n      const A = Schema.Union(R1, R2)\n      assertExtend(A, B, [\n        `{ { { readonly a: string; readonly c: boolean } | filter } | filter } | { { { readonly b: number; readonly c: boolean } | filter } | filter }`,\n        `{ { { readonly c: boolean; readonly a: string } | filter } | filter } | { { { readonly c: boolean; readonly b: number } | filter } | filter }`\n      ])\n      const schema = Schema.extend(A, B)\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"\", c: true },\n        `{ { { readonly a: string; readonly c: boolean } | filter } | filter } | { { { readonly b: number; readonly c: boolean } | filter } | filter }\n├─ R1 filter\n└─ { { { readonly b: number; readonly c: boolean } | filter } | filter }\n   └─ From side refinement failure\n      └─ { { readonly b: number; readonly c: boolean } | filter }\n         └─ From side refinement failure\n            └─ { readonly b: number; readonly c: boolean }\n               └─ [\"b\"]\n                  └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { b: -1, c: true },\n        `{ { { readonly a: string; readonly c: boolean } | filter } | filter } | { { { readonly b: number; readonly c: boolean } | filter } | filter }\n├─ { { { readonly a: string; readonly c: boolean } | filter } | filter }\n│  └─ From side refinement failure\n│     └─ { { readonly a: string; readonly c: boolean } | filter }\n│        └─ From side refinement failure\n│           └─ { readonly a: string; readonly c: boolean }\n│              └─ [\"a\"]\n│                 └─ is missing\n└─ R2 filter`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\", c: false },\n        `{ { { readonly a: string; readonly c: boolean } | filter } | filter } | { { { readonly b: number; readonly c: boolean } | filter } | filter }\n├─ R3 filter\n└─ { { { readonly b: number; readonly c: boolean } | filter } | filter }\n   └─ From side refinement failure\n      └─ { { readonly b: number; readonly c: boolean } | filter }\n         └─ From side refinement failure\n            └─ { readonly b: number; readonly c: boolean }\n               └─ [\"b\"]\n                  └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { b: 1, c: false },\n        `{ { { readonly a: string; readonly c: boolean } | filter } | filter } | { { { readonly b: number; readonly c: boolean } | filter } | filter }\n├─ { { { readonly a: string; readonly c: boolean } | filter } | filter }\n│  └─ From side refinement failure\n│     └─ { { readonly a: string; readonly c: boolean } | filter }\n│        └─ From side refinement failure\n│           └─ { readonly a: string; readonly c: boolean }\n│              └─ [\"a\"]\n│                 └─ is missing\n└─ R3 filter`\n      )\n    })\n  })\n\n  describe(\"Suspend\", () => {\n    it(\"List as union\", async () => {\n      type List = {\n        readonly type: \"nil\"\n      } | {\n        readonly type: \"cons\"\n        readonly tail: {\n          readonly value: number\n        } & List\n      }\n      const List = Schema.Union(\n        Schema.Struct({ type: Schema.Literal(\"nil\") }),\n        Schema.Struct({\n          type: Schema.Literal(\"cons\"),\n          tail: Schema.extend(\n            Schema.Struct({ value: Schema.Number }),\n            Schema.suspend((): Schema.Schema<List> => List)\n          )\n        })\n      )\n      strictEqual(\n        String(List),\n        `{ readonly type: \"nil\" } | { readonly type: \"cons\"; readonly tail: <suspended schema> }`\n      )\n      await Util.assertions.decoding.succeed(List, { type: \"nil\" })\n      await Util.assertions.decoding.succeed(List, { type: \"cons\", tail: { value: 1, type: \"nil\" } })\n      await Util.assertions.decoding.succeed(List, {\n        type: \"cons\",\n        tail: { value: 1, type: \"cons\", tail: { value: 2, type: \"nil\" } }\n      })\n      const decodeUnknownSync = Schema.decodeUnknownSync(List)\n      const arb = Arbitrary.make(List)\n      FastCheck.assert(\n        FastCheck.property(arb, (a) => {\n          decodeUnknownSync(a)\n        }),\n        { numRuns: 10 }\n      )\n    })\n  })\n\n  it(\"Errors\", () => {\n    throws(\n      () => Schema.String.pipe(Schema.extend(Schema.Number)),\n      new Error(`Unsupported schema or overlapping types\ndetails: cannot extend string with number`)\n    )\n    throws(\n      () =>\n        Schema.Record({ key: Schema.String, value: Schema.Number }).pipe(\n          Schema.extend(Schema.Record({ key: Schema.String, value: Schema.Boolean }))\n        ),\n      new Error(`Duplicate index signature\ndetails: string index signature`)\n    )\n    throws(\n      () =>\n        Schema.Record({ key: Schema.SymbolFromSelf, value: Schema.Number }).pipe(\n          Schema.extend(Schema.Record({ key: Schema.SymbolFromSelf, value: Schema.Boolean }))\n        ),\n      new Error(`Duplicate index signature\ndetails: symbol index signature`)\n    )\n    throws(\n      () =>\n        Schema.Record({ key: Schema.String, value: Schema.Number }).pipe(\n          Schema.extend(Schema.Record({ key: Schema.String.pipe(Schema.minLength(2)), value: Schema.Boolean }))\n        ),\n      new Error(`Duplicate index signature\ndetails: string index signature`)\n    )\n    throws(\n      () =>\n        Schema.extend(\n          Schema.Struct({ a: Schema.Struct({ b: Schema.String }) }),\n          Schema.Struct({ a: Schema.Struct({ b: Schema.Number }) })\n        ),\n      new Error(\n        `Unsupported schema or overlapping types\nat path: [\"a\"][\"b\"]\ndetails: cannot extend string with number`\n      )\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/filter.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"filter\", () => {\n  describe(\"error messages\", () => {\n    it(\"single refinement\", async () => {\n      const schema = S.Number.pipe(S.int())\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `int\n└─ From side refinement failure\n   └─ Expected number, actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        1.1,\n        `int\n└─ Predicate refinement failure\n   └─ Expected an integer, actual 1.1`\n      )\n    })\n\n    it(\"double refinement\", async () => {\n      const schema = S.Number.pipe(S.int(), S.positive())\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `int & positive\n└─ From side refinement failure\n   └─ int\n      └─ From side refinement failure\n         └─ Expected number, actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        1.1,\n        `int & positive\n└─ From side refinement failure\n   └─ int\n      └─ Predicate refinement failure\n         └─ Expected an integer, actual 1.1`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        -1,\n        `int & positive\n└─ Predicate refinement failure\n   └─ Expected a positive number, actual -1`\n      )\n    })\n\n    it(\"with an anonymous refinement\", async () => {\n      const schema = S.Number.pipe(S.filter(() => false), S.positive())\n      await Util.assertions.decoding.fail(\n        schema,\n        1,\n        `{ number | filter } & positive\n└─ From side refinement failure\n   └─ { number | filter }\n      └─ Predicate refinement failure\n         └─ Expected { number | filter }, actual 1`\n      )\n    })\n  })\n\n  it(\"annotation options\", () => {\n    const schema = S.String.pipe(\n      S.filter((s): s is string => s.length === 1, {\n        schemaId: Symbol.for(\"Char\"),\n        description: \"description\",\n        documentation: \"documentation\",\n        examples: [\"examples\"],\n        identifier: \"identifier\",\n        jsonSchema: { minLength: 1, maxLength: 1 },\n        title: \"title\"\n      })\n    )\n    deepStrictEqual(schema.ast.annotations, {\n      [AST.SchemaIdAnnotationId]: Symbol.for(\"Char\"),\n      [AST.DescriptionAnnotationId]: \"description\",\n      [AST.DocumentationAnnotationId]: \"documentation\",\n      [AST.ExamplesAnnotationId]: [\n        \"examples\"\n      ],\n      [AST.IdentifierAnnotationId]: \"identifier\",\n      [AST.JSONSchemaAnnotationId]: {\n        \"maxLength\": 1,\n        \"minLength\": 1\n      },\n      [AST.TitleAnnotationId]: \"title\"\n    })\n  })\n\n  it(\"the constructor should validate the input by default\", () => {\n    const schema = S.NonEmptyString\n    Util.assertions.make.succeed(schema, \"a\")\n    Util.assertions.make.fail(\n      schema,\n      \"\",\n      `NonEmptyString\n└─ Predicate refinement failure\n   └─ Expected a non empty string, actual \"\"`\n    )\n  })\n\n  it(\"the constructor validation can be disabled\", () => {\n    const schema = S.NonEmptyString\n    strictEqual(schema.make(\"\", true), \"\")\n    strictEqual(schema.make(\"\", { disableValidation: true }), \"\")\n  })\n\n  describe(\"ParseIssue overloading\", () => {\n    it(\"return a Type\", async () => {\n      const schema = S.Struct({ a: S.String, b: S.String }).pipe(\n        S.filter((o) => {\n          if (o.b !== o.a) {\n            return new ParseResult.Type(S.Literal(o.a).ast, o.b, `b should be equal to a's value (\"${o.a}\")`)\n          }\n        })\n      )\n\n      await Util.assertions.decoding.succeed(schema, { a: \"x\", b: \"x\" })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\", b: \"b\" },\n        `{ { readonly a: string; readonly b: string } | filter }\n└─ Predicate refinement failure\n   └─ b should be equal to a's value (\"a\")`\n      )\n    })\n\n    const ValidString = S.Trim.pipe(S.minLength(1, { message: () => \"ERROR_MIN_LENGTH\" }))\n    const Test = S.Struct({\n      a: S.Struct({\n        b: S.String,\n        c: ValidString\n      }),\n      d: S.Tuple(S.String, ValidString)\n    }).annotations({ identifier: \"Test\" })\n\n    it(\"return a Pointer\", async () => {\n      const schema = Test.pipe(S.filter((input) => {\n        if (input.a.b !== input.a.c) {\n          return new ParseResult.Pointer(\n            [\"a\", \"c\"],\n            input,\n            new ParseResult.Type(S.Literal(input.a.b).ast, input.a.c)\n          )\n        }\n        if (input.d[0] !== input.d[1]) {\n          return new ParseResult.Pointer(\n            [\"d\", 1],\n            input,\n            new ParseResult.Type(S.Literal(input.d[0]).ast, input.d[1])\n          )\n        }\n      }))\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \" \" }, d: [\"-\", \"-\"] },\n        `{ Test | filter }\n└─ From side refinement failure\n   └─ Test\n      └─ [\"a\"]\n         └─ { readonly b: string; readonly c: minLength(1) }\n            └─ [\"c\"]\n               └─ ERROR_MIN_LENGTH`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \"c\" }, d: [\"-\", \"-\"] },\n        `{ Test | filter }\n└─ Predicate refinement failure\n   └─ [\"a\"][\"c\"]\n      └─ Expected \"b\", actual \"c\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"-\", c: \"-\" }, d: [\"item0\", \"item1\"] },\n        `{ Test | filter }\n└─ Predicate refinement failure\n   └─ [\"d\"][1]\n      └─ Expected \"item0\", actual \"item1\"`\n      )\n    })\n\n    it(\"return a path and a message\", async () => {\n      const schema = Test.pipe(S.filter((input) => {\n        if (input.a.b !== input.a.c) {\n          return {\n            path: [\"a\", \"c\"],\n            message: \"FILTER1\"\n          }\n        }\n        if (input.d[0] !== input.d[1]) {\n          return {\n            path: [\"d\", 1],\n            message: \"FILTER2\"\n          }\n        }\n      }))\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \" \" }, d: [\"-\", \"-\"] },\n        `{ Test | filter }\n└─ From side refinement failure\n   └─ Test\n      └─ [\"a\"]\n         └─ { readonly b: string; readonly c: minLength(1) }\n            └─ [\"c\"]\n               └─ ERROR_MIN_LENGTH`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \"c\" }, d: [\"-\", \"-\"] },\n        `{ Test | filter }\n└─ Predicate refinement failure\n   └─ [\"a\"][\"c\"]\n      └─ FILTER1`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"-\", c: \"-\" }, d: [\"item0\", \"item1\"] },\n        `{ Test | filter }\n└─ Predicate refinement failure\n   └─ [\"d\"][1]\n      └─ FILTER2`\n      )\n    })\n\n    it(\"return many paths and messages\", async () => {\n      const schema = Test.pipe(S.filter((input) => {\n        const issues: Array<S.FilterIssue> = []\n        if (input.a.b !== input.a.c) {\n          issues.push({\n            path: [\"a\", \"c\"],\n            message: \"FILTER1\"\n          })\n        }\n        if (input.d[0] !== input.d[1]) {\n          issues.push({\n            path: [\"d\", 1],\n            message: \"FILTER2\"\n          })\n        }\n        return issues\n      }))\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \" \" }, d: [\"-\", \"-\"] },\n        `{ Test | filter }\n└─ From side refinement failure\n   └─ Test\n      └─ [\"a\"]\n         └─ { readonly b: string; readonly c: minLength(1) }\n            └─ [\"c\"]\n               └─ ERROR_MIN_LENGTH`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \"c\" }, d: [\"-\", \"-\"] },\n        `{ Test | filter }\n└─ Predicate refinement failure\n   └─ [\"a\"][\"c\"]\n      └─ FILTER1`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"-\", c: \"-\" }, d: [\"item0\", \"item1\"] },\n        `{ Test | filter }\n└─ Predicate refinement failure\n   └─ [\"d\"][1]\n      └─ FILTER2`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \"c\" }, d: [\"item0\", \"item1\"] },\n        `{ Test | filter }\n└─ Predicate refinement failure\n   └─ { Test | filter }\n      ├─ [\"a\"][\"c\"]\n      │  └─ FILTER1\n      └─ [\"d\"][1]\n         └─ FILTER2`\n      )\n    })\n  })\n\n  describe(\"Stable Filters\", () => {\n    describe(\"Array\", () => {\n      it(\"when the 'errors' option is set to 'all', stable filters should generate multiple errors\", async () => {\n        const schema = S.Struct({\n          tags: S.Array(S.String.pipe(S.minLength(2))).pipe(S.minItems(3))\n        })\n        await Util.assertions.decoding.fail(\n          schema,\n          { tags: [\"AB\", \"B\"] },\n          `{ readonly tags: minItems(3) }\n└─ [\"tags\"]\n   └─ minItems(3)\n      ├─ minItems(3)\n      │  └─ From side refinement failure\n      │     └─ ReadonlyArray<minLength(2)>\n      │        └─ [1]\n      │           └─ minLength(2)\n      │              └─ Predicate refinement failure\n      │                 └─ Expected a string at least 2 character(s) long, actual \"B\"\n      └─ minItems(3)\n         └─ Predicate refinement failure\n            └─ Expected an array of at least 3 item(s), actual [\"AB\",\"B\"]`,\n          { parseOptions: Util.ErrorsAll }\n        )\n        await Util.assertions.decoding.fail(\n          schema,\n          { tags: [\"AB\", \"B\"] },\n          `{ readonly tags: minItems(3) }\n└─ [\"tags\"]\n   └─ minItems(3)\n      └─ From side refinement failure\n         └─ ReadonlyArray<minLength(2)>\n            └─ [1]\n               └─ minLength(2)\n                  └─ Predicate refinement failure\n                     └─ Expected a string at least 2 character(s) long, actual \"B\"`\n        )\n      })\n\n      it(\"when the 'errors' option is set to 'all', stable filters should be applied only if the from part fails with a `Composite` issue\", async () => {\n        await Util.assertions.decoding.fail(\n          S.Struct({\n            tags: S.Array(S.String).pipe(S.minItems(1))\n          }),\n          {},\n          `{ readonly tags: minItems(1) }\n└─ [\"tags\"]\n   └─ is missing`,\n          { parseOptions: Util.ErrorsAll }\n        )\n        await Util.assertions.decoding.fail(\n          S.Struct({\n            tags: S.Array(S.String).pipe(S.minItems(1), S.maxItems(3))\n          }),\n          {},\n          `{ readonly tags: minItems(1) & maxItems(3) }\n└─ [\"tags\"]\n   └─ is missing`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n    })\n\n    describe(\"NonEmptyArray\", () => {\n      it(\"when the 'errors' option is set to 'all', stable filters should generate multiple errors\", async () => {\n        const schema = S.Struct({\n          tags: S.NonEmptyArray(S.String.pipe(S.minLength(2))).pipe(S.minItems(3))\n        })\n        await Util.assertions.decoding.fail(\n          schema,\n          { tags: [\"AB\", \"B\"] },\n          `{ readonly tags: minItems(3) }\n└─ [\"tags\"]\n   └─ minItems(3)\n      ├─ minItems(3)\n      │  └─ From side refinement failure\n      │     └─ readonly [minLength(2), ...minLength(2)[]]\n      │        └─ [1]\n      │           └─ minLength(2)\n      │              └─ Predicate refinement failure\n      │                 └─ Expected a string at least 2 character(s) long, actual \"B\"\n      └─ minItems(3)\n         └─ Predicate refinement failure\n            └─ Expected an array of at least 3 item(s), actual [\"AB\",\"B\"]`,\n          { parseOptions: Util.ErrorsAll }\n        )\n        await Util.assertions.decoding.fail(\n          schema,\n          { tags: [\"AB\", \"B\"] },\n          `{ readonly tags: minItems(3) }\n└─ [\"tags\"]\n   └─ minItems(3)\n      └─ From side refinement failure\n         └─ readonly [minLength(2), ...minLength(2)[]]\n            └─ [1]\n               └─ minLength(2)\n                  └─ Predicate refinement failure\n                     └─ Expected a string at least 2 character(s) long, actual \"B\"`\n        )\n      })\n\n      it(\"when the 'errors' option is set to 'all', stable filters should be applied only if the from part fails with a `Composite` issue\", async () => {\n        await Util.assertions.decoding.fail(\n          S.Struct({\n            tags: S.NonEmptyArray(S.String).pipe(S.minItems(1))\n          }),\n          {},\n          `{ readonly tags: minItems(1) }\n└─ [\"tags\"]\n   └─ is missing`,\n          { parseOptions: Util.ErrorsAll }\n        )\n        await Util.assertions.decoding.fail(\n          S.Struct({\n            tags: S.NonEmptyArray(S.String).pipe(S.minItems(1), S.maxItems(3))\n          }),\n          {},\n          `{ readonly tags: minItems(1) & maxItems(3) }\n└─ [\"tags\"]\n   └─ is missing`,\n          { parseOptions: Util.ErrorsAll }\n        )\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/filterEffect.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"filterEffect\", () => {\n  it(\"should expose the original schema as `from`\", () => {\n    const schema = S.filterEffect(S.String, () => Effect.succeed(true))\n    strictEqual(schema.from, S.String)\n    strictEqual(schema.to.ast, S.String.ast)\n  })\n\n  describe(\"ParseIssue overloading\", () => {\n    it(\"return a Type\", async () => {\n      const schema = S.filterEffect(S.Struct({ a: S.String, b: S.String }), (o) => {\n        if (o.b !== o.a) {\n          return Effect.succeed(\n            new ParseResult.Type(S.Literal(o.a).ast, o.b, `b should be equal to a's value (\"${o.a}\")`)\n          )\n        }\n        return Effect.succeed(true)\n      })\n\n      await Util.assertions.decoding.succeed(schema, { a: \"x\", b: \"x\" })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\", b: \"b\" },\n        `({ readonly a: string; readonly b: string } <-> { readonly a: string; readonly b: string })\n└─ Transformation process failure\n   └─ b should be equal to a's value (\"a\")`\n      )\n    })\n\n    const ValidString = S.Trim.pipe(S.minLength(1, { message: () => \"ERROR_MIN_LENGTH\" }))\n    const Test = S.Struct({\n      a: S.Struct({\n        b: S.String,\n        c: ValidString\n      }),\n      d: S.Tuple(S.String, ValidString)\n    }).annotations({ identifier: \"Test\" })\n\n    it(\"return a Pointer\", async () => {\n      const schema = Test.pipe(S.filterEffect((input) => {\n        if (input.a.b !== input.a.c) {\n          return Effect.succeed(\n            new ParseResult.Pointer(\n              [\"a\", \"c\"],\n              input,\n              new ParseResult.Type(S.Literal(input.a.b).ast, input.a.c)\n            )\n          )\n        }\n        if (input.d[0] !== input.d[1]) {\n          return Effect.succeed(\n            new ParseResult.Pointer(\n              [\"d\", 1],\n              input,\n              new ParseResult.Type(S.Literal(input.d[0]).ast, input.d[1])\n            )\n          )\n        }\n        return Effect.succeed(true)\n      }))\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \" \" }, d: [\"-\", \"-\"] },\n        `(Test <-> Test)\n└─ Encoded side transformation failure\n   └─ Test\n      └─ [\"a\"]\n         └─ { readonly b: string; readonly c: minLength(1) }\n            └─ [\"c\"]\n               └─ ERROR_MIN_LENGTH`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \"c\" }, d: [\"-\", \"-\"] },\n        `(Test <-> Test)\n└─ Transformation process failure\n   └─ [\"a\"][\"c\"]\n      └─ Expected \"b\", actual \"c\"`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"-\", c: \"-\" }, d: [\"item0\", \"item1\"] },\n        `(Test <-> Test)\n└─ Transformation process failure\n   └─ [\"d\"][1]\n      └─ Expected \"item0\", actual \"item1\"`\n      )\n    })\n\n    it(\"return a path and a message\", async () => {\n      const schema = Test.pipe(S.filterEffect((input) => {\n        if (input.a.b !== input.a.c) {\n          return Effect.succeed({\n            path: [\"a\", \"c\"],\n            message: \"FILTER1\"\n          })\n        }\n        if (input.d[0] !== input.d[1]) {\n          return Effect.succeed({\n            path: [\"d\", 1],\n            message: \"FILTER2\"\n          })\n        }\n        return Effect.succeed(true)\n      }))\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \" \" }, d: [\"-\", \"-\"] },\n        `(Test <-> Test)\n└─ Encoded side transformation failure\n   └─ Test\n      └─ [\"a\"]\n         └─ { readonly b: string; readonly c: minLength(1) }\n            └─ [\"c\"]\n               └─ ERROR_MIN_LENGTH`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \"c\" }, d: [\"-\", \"-\"] },\n        `(Test <-> Test)\n└─ Transformation process failure\n   └─ [\"a\"][\"c\"]\n      └─ FILTER1`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"-\", c: \"-\" }, d: [\"item0\", \"item1\"] },\n        `(Test <-> Test)\n└─ Transformation process failure\n   └─ [\"d\"][1]\n      └─ FILTER2`\n      )\n    })\n\n    it(\"return many paths and messages\", async () => {\n      const schema = Test.pipe(S.filterEffect((input) => {\n        const issues: Array<S.FilterIssue> = []\n        if (input.a.b !== input.a.c) {\n          issues.push({\n            path: [\"a\", \"c\"],\n            message: \"FILTER1\"\n          })\n        }\n        if (input.d[0] !== input.d[1]) {\n          issues.push({\n            path: [\"d\", 1],\n            message: \"FILTER2\"\n          })\n        }\n        return Effect.succeed(issues)\n      }))\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \" \" }, d: [\"-\", \"-\"] },\n        `(Test <-> Test)\n└─ Encoded side transformation failure\n   └─ Test\n      └─ [\"a\"]\n         └─ { readonly b: string; readonly c: minLength(1) }\n            └─ [\"c\"]\n               └─ ERROR_MIN_LENGTH`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \"c\" }, d: [\"-\", \"-\"] },\n        `(Test <-> Test)\n└─ Transformation process failure\n   └─ [\"a\"][\"c\"]\n      └─ FILTER1`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"-\", c: \"-\" }, d: [\"item0\", \"item1\"] },\n        `(Test <-> Test)\n└─ Transformation process failure\n   └─ [\"d\"][1]\n      └─ FILTER2`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: { b: \"b\", c: \"c\" }, d: [\"item0\", \"item1\"] },\n        `(Test <-> Test)\n└─ Transformation process failure\n   └─ (Test <-> Test)\n      ├─ [\"a\"][\"c\"]\n      │  └─ FILTER1\n      └─ [\"d\"][1]\n         └─ FILTER2`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/fromBrand.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as Brand from \"effect/Brand\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ntype Int = number & Brand.Brand<\"Int\">\nconst Int = Brand.refined<Int>(\n  (n) => Number.isSafeInteger(n),\n  (n) => Brand.error(`Expected ${n} to be an integer`)\n)\n\ntype Positive = number & Brand.Brand<\"Positive\">\nconst Positive = Brand.refined<Positive>(\n  (n) => n > 0,\n  (n) => Brand.error(`Expected ${n} to be positive`)\n)\n\ntype PositiveInt = Positive & Int\nconst PositiveInt = Brand.all(Int, Positive)\n\ntype Eur = number & Brand.Brand<\"Eur\">\nconst Eur = Brand.nominal<Eur>()\n\ndescribe(\"fromBrand\", () => {\n  it(\"make\", () => {\n    const schema = S.NumberFromString.pipe(S.fromBrand(PositiveInt)).annotations({ identifier: \"PositiveInt\" })\n    Util.assertions.make.succeed(schema, 1)\n    Util.assertions.make.fail(\n      schema,\n      -1,\n      `PositiveInt\n└─ Predicate refinement failure\n   └─ Expected -1 to be positive`\n    )\n  })\n\n  it(\"[internal] should expose the original schema as `from`\", () => {\n    // the from property is not exposed in the public API\n    const schema: any = S.Number.pipe(S.fromBrand(PositiveInt))\n    strictEqual(schema.from, S.Number)\n  })\n\n  it(\"test roundtrip consistency\", () => {\n    Util.assertions.testRoundtripConsistency(S.Number.pipe(S.fromBrand(Int))) // refined\n    Util.assertions.testRoundtripConsistency(S.Number.pipe(S.fromBrand(Eur))) // nominal\n  })\n\n  it(\"refined\", async () => {\n    const schema = S.Number.pipe(S.fromBrand(Brand.all(Positive, Int)))\n\n    await Util.assertions.decoding.fail(\n      schema,\n      -0.5,\n      `{ number | filter }\n└─ Predicate refinement failure\n   └─ Expected -0.5 to be positive, Expected -0.5 to be an integer`\n    )\n    Util.assertions.parseError(\n      () => S.decodeUnknownSync(schema)(-0.5),\n      `{ number | filter }\n└─ Predicate refinement failure\n   └─ Expected -0.5 to be positive, Expected -0.5 to be an integer`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      -1,\n      `{ number | filter }\n└─ Predicate refinement failure\n   └─ Expected -1 to be positive`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      0,\n      `{ number | filter }\n└─ Predicate refinement failure\n   └─ Expected 0 to be positive`\n    )\n    await Util.assertions.decoding.succeed(schema, 1, 1 as PositiveInt)\n    await Util.assertions.decoding.fail(\n      schema,\n      1.5,\n      `{ number | filter }\n└─ Predicate refinement failure\n   └─ Expected 1.5 to be an integer`\n    )\n    await Util.assertions.decoding.succeed(schema, 2, 2 as PositiveInt)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/getNumberIndexedAccess.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Duration from \"effect/Duration\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"getNumberIndexedAccess\", () => {\n  describe(\"Tuple\", () => {\n    it(\"decodes and encodes required elements in a tuple\", async () => {\n      const schema = S.getNumberIndexedAccess(S.Tuple(S.NumberFromString, S.DurationFromNanos))\n      await Util.assertions.decoding.succeed(schema, \"1\", 1)\n      await Util.assertions.decoding.succeed(schema, 1n, Duration.nanos(1n))\n      await Util.assertions.encoding.succeed(schema, 1, \"1\")\n      await Util.assertions.encoding.succeed(schema, Duration.nanos(1n), 1n)\n    })\n\n    it(\"decodes and encodes a tuple with an optional element\", async () => {\n      const schema = S.getNumberIndexedAccess(S.Tuple(S.NumberFromString, S.optionalElement(S.DurationFromNanos)))\n      await Util.assertions.decoding.succeed(schema, undefined)\n      await Util.assertions.decoding.succeed(schema, \"1\", 1)\n      await Util.assertions.decoding.succeed(schema, 1n, Duration.nanos(1n))\n      await Util.assertions.encoding.succeed(schema, undefined, undefined)\n      await Util.assertions.encoding.succeed(schema, 1, \"1\")\n      await Util.assertions.encoding.succeed(schema, Duration.nanos(1n), 1n)\n    })\n  })\n\n  it(\"Array\", async () => {\n    const schema = S.getNumberIndexedAccess(S.Array(S.NumberFromString))\n    await Util.assertions.decoding.succeed(schema, \"1\", 1)\n    await Util.assertions.encoding.succeed(schema, 1, \"1\")\n  })\n\n  it(\"Union\", async () => {\n    const schema = S.getNumberIndexedAccess(S.Union(S.Array(S.Number), S.Array(S.String)))\n    await Util.assertions.decoding.succeed(schema, \"a\")\n    await Util.assertions.decoding.succeed(schema, 1)\n    await Util.assertions.encoding.succeed(schema, \"a\", \"a\")\n    await Util.assertions.encoding.succeed(schema, 1, 1)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/instanceOf.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"instanceOf\", () => {\n  it(\"is\", () => {\n    const schema = S.instanceOf(Set)\n    const is = P.is(schema)\n    assertTrue(is(new Set()))\n    assertFalse(is(1))\n    assertFalse(is({}))\n  })\n\n  it(\"annotations\", () => {\n    const schema = S.instanceOf(Set, { description: \"my description\" })\n    strictEqual(schema.ast.annotations[AST.DescriptionAnnotationId], \"my description\")\n    deepStrictEqual(schema.ast.annotations[S.InstanceOfSchemaId], { constructor: Set })\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.instanceOf(Set)\n    await Util.assertions.decoding.succeed(schema, new Set())\n    await Util.assertions.decoding.fail(\n      schema,\n      1,\n      `Expected Set, actual 1`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      {},\n      `Expected Set, actual {}`\n    )\n  })\n\n  describe(\"pretty\", () => {\n    it(\"default\", () => {\n      const schema = S.instanceOf(Set)\n      Util.assertions.pretty(schema, new Set(), \"[object Set]\")\n    })\n\n    it(\"override\", () => {\n      const schema = S.instanceOf(Set, {\n        pretty: () => (set) => `new Set(${JSON.stringify(Array.from(set.values()))})`\n      })\n      Util.assertions.pretty(schema, new Set([1, 2, 3]), \"new Set([1,2,3])\")\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/is.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"is\", () => {\n  it(\"never\", () => {\n    const is = P.is(S.Never)\n    assertFalse(is(1))\n  })\n\n  it(\"string\", () => {\n    const is = P.is(S.String)\n    assertTrue(is(\"a\"))\n    assertFalse(is(1))\n  })\n\n  it(\"number\", () => {\n    const is = P.is(S.Number)\n    assertTrue(is(1))\n    assertTrue(is(NaN))\n    assertTrue(is(Infinity))\n    assertTrue(is(-Infinity))\n    assertFalse(is(\"a\"))\n  })\n\n  it(\"boolean\", () => {\n    const is = P.is(S.Boolean)\n    assertTrue(is(true))\n    assertTrue(is(false))\n    assertFalse(is(1))\n  })\n\n  it(\"bigint\", () => {\n    const is = P.is(S.BigIntFromSelf)\n    assertTrue(is(0n))\n    assertTrue(is(1n))\n    assertTrue(is(BigInt(\"1\")))\n    assertFalse(is(null))\n    assertFalse(is(1.2))\n  })\n\n  it(\"symbol\", () => {\n    const a = Symbol.for(\"effect/Schema/test/a\")\n    const is = P.is(S.SymbolFromSelf)\n    assertTrue(is(a))\n    assertFalse(is(\"effect/Schema/test/a\"))\n  })\n\n  it(\"object\", () => {\n    const is = P.is(S.Object)\n    assertTrue(is({}))\n    assertTrue(is([]))\n    assertFalse(is(null))\n    assertFalse(is(\"a\"))\n    assertFalse(is(1))\n    assertFalse(is(true))\n  })\n\n  it(\"literal 1 member\", () => {\n    const schema = S.Literal(1)\n    const is = P.is(schema)\n    assertTrue(is(1))\n    assertFalse(is(\"a\"))\n    assertFalse(is(null))\n  })\n\n  it(\"literal 2 members\", () => {\n    const schema = S.Literal(1, \"a\")\n    const is = P.is(schema)\n    assertTrue(is(1))\n    assertTrue(is(\"a\"))\n    assertFalse(is(null))\n  })\n\n  it(\"uniqueSymbolFromSelf\", () => {\n    const a = Symbol.for(\"effect/Schema/test/a\")\n    const schema = S.UniqueSymbolFromSelf(a)\n    const is = P.is(schema)\n    assertTrue(is(a))\n    assertTrue(is(Symbol.for(\"effect/Schema/test/a\")))\n    assertFalse(is(\"Symbol(effect/Schema/test/a)\"))\n  })\n\n  it(\"Numeric enums\", () => {\n    enum Fruits {\n      Apple,\n      Banana\n    }\n    const schema = S.Enums(Fruits)\n    const is = P.is(schema)\n    assertTrue(is(Fruits.Apple))\n    assertTrue(is(Fruits.Banana))\n    assertTrue(is(0))\n    assertTrue(is(1))\n    assertFalse(is(3))\n  })\n\n  it(\"String enums\", () => {\n    enum Fruits {\n      Apple = \"apple\",\n      Banana = \"banana\",\n      Cantaloupe = 0\n    }\n    const schema = S.Enums(Fruits)\n    const is = P.is(schema)\n    assertTrue(is(Fruits.Apple))\n    assertTrue(is(Fruits.Cantaloupe))\n    assertTrue(is(\"apple\"))\n    assertTrue(is(\"banana\"))\n    assertTrue(is(0))\n    assertFalse(is(\"Cantaloupe\"))\n  })\n\n  it(\"Const enums\", () => {\n    const Fruits = {\n      Apple: \"apple\",\n      Banana: \"banana\",\n      Cantaloupe: 3\n    } as const\n    const schema = S.Enums(Fruits)\n    const is = P.is(schema)\n    assertTrue(is(\"apple\"))\n    assertTrue(is(\"banana\"))\n    assertTrue(is(3))\n    assertFalse(is(\"Cantaloupe\"))\n  })\n\n  it(\"tuple. empty\", () => {\n    const schema = S.Tuple()\n    const is = P.is(schema)\n    assertTrue(is([]))\n\n    assertFalse(is(null))\n    assertFalse(is([undefined]))\n    assertFalse(is([1]))\n    assertFalse(is({}))\n  })\n\n  it(\"tuple. required element\", () => {\n    const schema = S.Tuple(S.Number)\n    const is = P.is(schema)\n    assertTrue(is([1]))\n\n    assertFalse(is(null))\n    assertFalse(is([]))\n    assertFalse(is([undefined]))\n    assertFalse(is([\"a\"]))\n    assertFalse(is([1, \"b\"]))\n  })\n\n  it(\"tuple. required element with undefined\", () => {\n    const schema = S.Tuple(S.Union(S.Number, S.Undefined))\n    const is = P.is(schema)\n    assertTrue(is([1]))\n    assertTrue(is([undefined]))\n\n    assertFalse(is(null))\n    assertFalse(is([]))\n    assertFalse(is([\"a\"]))\n    assertFalse(is([1, \"b\"]))\n  })\n\n  it(\"tuple. optional element\", () => {\n    const schema = S.Tuple(S.optionalElement(S.Number))\n    const is = P.is(schema)\n    assertTrue(is([]))\n    assertTrue(is([1]))\n\n    assertFalse(is(null))\n    assertFalse(is([\"a\"]))\n    assertFalse(is([undefined]))\n    assertFalse(is([1, \"b\"]))\n  })\n\n  it(\"tuple. optional element with undefined\", () => {\n    const schema = S.Tuple(S.optionalElement(S.Union(S.Number, S.Undefined)))\n    const is = P.is(schema)\n    assertTrue(is([]))\n    assertTrue(is([1]))\n    assertTrue(is([undefined]))\n\n    assertFalse(is(null))\n    assertFalse(is([\"a\"]))\n    assertFalse(is([1, \"b\"]))\n  })\n\n  it(\"tuple. e + e?\", () => {\n    const schema = S.Tuple(S.String, S.optionalElement(S.Number))\n    const is = P.is(schema)\n    assertTrue(is([\"a\"]))\n    assertTrue(is([\"a\", 1]))\n\n    assertFalse(is([1]))\n    assertFalse(is([\"a\", \"b\"]))\n  })\n\n  it(\"tuple. e + r\", () => {\n    const schema = S.Tuple([S.String], S.Number)\n    const is = P.is(schema)\n    assertTrue(is([\"a\"]))\n    assertTrue(is([\"a\", 1]))\n    assertTrue(is([\"a\", 1, 2]))\n\n    assertFalse(is([]))\n  })\n\n  it(\"tuple. e? + r\", () => {\n    const schema = S.Tuple([S.optionalElement(S.String)], S.Number)\n    const is = P.is(schema)\n    assertTrue(is([]))\n    assertTrue(is([\"a\"]))\n    assertTrue(is([\"a\", 1]))\n    assertTrue(is([\"a\", 1, 2]))\n\n    assertFalse(is([1]))\n  })\n\n  it(\"tuple. r\", () => {\n    const schema = S.Array(S.Number)\n    const is = P.is(schema)\n    assertTrue(is([]))\n    assertTrue(is([1]))\n    assertTrue(is([1, 2]))\n\n    assertFalse(is([\"a\"]))\n    assertFalse(is([1, \"a\"]))\n  })\n\n  it(\"tuple. r + e\", () => {\n    const schema = S.Tuple([], S.String, S.Number)\n    const is = P.is(schema)\n    assertTrue(is([1]))\n    assertTrue(is([\"a\", 1]))\n    assertTrue(is([\"a\", \"b\", 1]))\n\n    assertFalse(is([]))\n    assertFalse(is([\"a\"]))\n    assertFalse(is([1, 2]))\n  })\n\n  it(\"tuple. e + r + e\", () => {\n    const schema = S.Tuple([S.String], S.Number, S.Boolean)\n    const is = P.is(schema)\n    assertTrue(is([\"a\", true]))\n    assertTrue(is([\"a\", 1, true]))\n    assertTrue(is([\"a\", 1, 2, true]))\n\n    assertFalse(is([]))\n    assertFalse(is([\"a\"]))\n    assertFalse(is([true]))\n    assertFalse(is([\"a\", 1]))\n    assertFalse(is([1, true]))\n  })\n\n  it(\"struct. empty\", () => {\n    const schema = S.Struct({})\n    const is = P.is(schema)\n    assertTrue(is({}))\n    assertTrue(is({ a: 1 }))\n    assertTrue(is([]))\n\n    assertFalse(is(null))\n    assertFalse(is(undefined))\n  })\n\n  describe(\"struct\", () => {\n    it(\"required property signature\", () => {\n      const schema = S.Struct({ a: S.Number })\n      const is = P.is(schema)\n      assertTrue(is({ a: 1 }))\n      assertTrue(is({ a: 1, b: \"b\" }))\n\n      assertFalse(is(null))\n      assertFalse(is({}))\n      assertFalse(is({ a: undefined }))\n      assertFalse(is({ a: \"a\" }))\n    })\n\n    it(\"required property signature with undefined\", () => {\n      const schema = S.Struct({ a: S.Union(S.Number, S.Undefined) })\n      const is = P.is(schema)\n      assertTrue(is({ a: 1 }))\n      assertTrue(is({ a: undefined }))\n      assertTrue(is({ a: 1, b: \"b\" }))\n\n      assertFalse(is({}))\n      assertFalse(is(null))\n      assertFalse(is({ a: \"a\" }))\n    })\n\n    it(\"exact optional property signature\", () => {\n      const schema = S.Struct({ a: S.optionalWith(S.Number, { exact: true }) })\n      const is = P.is(schema)\n      assertTrue(is({}))\n      assertTrue(is({ a: 1 }))\n      assertTrue(is({ a: 1, b: \"b\" }))\n\n      assertFalse(is(null))\n      assertFalse(is({ a: \"a\" }))\n      assertFalse(is({ a: undefined }))\n    })\n\n    it(\"exact optional property signature with undefined\", () => {\n      const schema = S.Struct({ a: S.optionalWith(S.Union(S.Number, S.Undefined), { exact: true }) })\n      const is = P.is(schema)\n      assertTrue(is({}))\n      assertTrue(is({ a: 1 }))\n      assertTrue(is({ a: undefined }))\n      assertTrue(is({ a: 1, b: \"b\" }))\n\n      assertFalse(is(null))\n      assertFalse(is({ a: \"a\" }))\n    })\n  })\n\n  it(\"record(string, string)\", () => {\n    const a = Symbol.for(\"effect/Schema/test/a\")\n    const schema = S.Record({ key: S.String, value: S.String })\n    const is = P.is(schema)\n    assertFalse(is(null))\n    assertTrue(is({}))\n    assertTrue(is({ a: \"a\" }))\n    assertFalse(is({ a: 1 }))\n    assertTrue(is({ [a]: 1 }))\n    assertTrue(is({ a: \"a\", b: \"b\" }))\n    assertFalse(is({ a: \"a\", b: 1 }))\n    assertTrue(is({ [a]: 1, b: \"b\" }))\n  })\n\n  it(\"record(symbol, string)\", () => {\n    const a = Symbol.for(\"effect/Schema/test/a\")\n    const b = Symbol.for(\"effect/Schema/test/b\")\n    const schema = S.Record({ key: S.SymbolFromSelf, value: S.String })\n    const is = P.is(schema)\n    assertFalse(is(null))\n    assertTrue(is({}))\n    assertTrue(is({ [a]: \"a\" }))\n    assertFalse(is({ [a]: 1 }))\n    assertTrue(is({ a: 1 }))\n    assertTrue(is({ [a]: \"a\", [b]: \"b\" }))\n    assertFalse(is({ [a]: \"a\", [b]: 1 }))\n    assertTrue(is({ a: 1, [b]: \"b\" }))\n  })\n\n  it(\"record(never, number)\", () => {\n    const schema = S.Record({ key: S.Never, value: S.Number })\n    const is = P.is(schema)\n    assertTrue(is({}))\n    assertTrue(is({ a: 1 }))\n  })\n\n  it(\"record('a' | 'b', number)\", () => {\n    const schema = S.Record({ key: S.Union(S.Literal(\"a\"), S.Literal(\"b\")), value: S.Number })\n    const is = P.is(schema)\n    assertTrue(is({ a: 1, b: 2 }))\n\n    assertFalse(is({}))\n    assertFalse(is({ a: 1 }))\n    assertFalse(is({ b: 2 }))\n  })\n\n  it(\"record(keyof struct({ a, b }), number)\", () => {\n    const schema = S.Record({ key: S.keyof(S.Struct({ a: S.String, b: S.String })), value: S.Number })\n    const is = P.is(schema)\n    assertTrue(is({ a: 1, b: 2 }))\n\n    assertFalse(is({}))\n    assertFalse(is({ a: 1 }))\n    assertFalse(is({ b: 2 }))\n    assertFalse(is({ a: \"a\" }))\n  })\n\n  it(\"record(Symbol('a') | Symbol('b'), number)\", () => {\n    const a = Symbol.for(\"effect/Schema/test/a\")\n    const b = Symbol.for(\"effect/Schema/test/b\")\n    const schema = S.Record({ key: S.Union(S.UniqueSymbolFromSelf(a), S.UniqueSymbolFromSelf(b)), value: S.Number })\n    const is = P.is(schema)\n    assertTrue(is({ [a]: 1, [b]: 2 }))\n\n    assertFalse(is({}))\n    assertFalse(is({ a: 1 }))\n    assertFalse(is({ b: 2 }))\n  })\n\n  it(\"record(${string}-${string}, number)\", () => {\n    const schema = S.Record({ key: S.TemplateLiteral(S.String, S.Literal(\"-\"), S.String), value: S.Number })\n    const is = P.is(schema)\n    assertTrue(is({}))\n    assertTrue(is({ \"-\": 1 }))\n    assertTrue(is({ \"a-\": 1 }))\n    assertTrue(is({ \"-b\": 1 }))\n    assertTrue(is({ \"a-b\": 1 }))\n    assertTrue(is({ \"\": 1 }))\n    assertTrue(is({ \"a\": 1 }))\n    assertTrue(is({ \"a\": \"a\" }))\n\n    assertFalse(is({ \"-\": \"a\" }))\n    assertFalse(is({ \"a-\": \"a\" }))\n    assertFalse(is({ \"-b\": \"b\" }))\n    assertFalse(is({ \"a-b\": \"ab\" }))\n  })\n\n  it(\"record(minLength(2), number)\", () => {\n    const schema = S.Record({ key: S.String.pipe(S.minLength(2)), value: S.Number })\n    const is = P.is(schema)\n    assertTrue(is({}))\n    assertTrue(is({ \"a\": 1 }))\n    assertTrue(is({ \"a\": \"a\" }))\n    assertTrue(is({ \"aa\": 1 }))\n    assertTrue(is({ \"aaa\": 1 }))\n\n    assertFalse(is({ \"aa\": \"aa\" }))\n  })\n\n  it(\"record(${string}-${string}, number) & record(string, string | number)\", () => {\n    const schema = S.Struct(\n      {},\n      S.Record({ key: S.TemplateLiteral(S.String, S.Literal(\"-\"), S.String), value: S.Number }),\n      S.Record({ key: S.String, value: S.Union(S.String, S.Number) })\n    )\n    const is = P.is(schema)\n    assertTrue(is({}))\n    assertTrue(is({ \"a\": \"a\" }))\n    assertTrue(is({ \"a-\": 1 }))\n\n    assertFalse(is({ \"a-\": \"a\" }))\n    assertFalse(is({ \"a\": true }))\n  })\n\n  it(\"union\", () => {\n    const schema = S.Union(S.String, S.Number)\n    const is = P.is(schema)\n    assertFalse(is(null))\n    assertTrue(is(1))\n    assertTrue(is(\"a\"))\n  })\n\n  describe(\"suspend\", () => {\n    it(\"baseline\", () => {\n      interface Category {\n        readonly name: string\n        readonly categories: ReadonlyArray<Category>\n      }\n      const schema = S.Struct({\n        name: S.String,\n        categories: S.Array(S.suspend((): S.Schema<Category> => schema))\n      })\n      const is = P.is(schema)\n      assertTrue(is({ name: \"a\", categories: [] }))\n      assertTrue(\n        is({\n          name: \"a\",\n          categories: [{\n            name: \"b\",\n            categories: [{ name: \"c\", categories: [] }]\n          }]\n        })\n      )\n      assertFalse(is({ name: \"a\", categories: [1] }))\n    })\n\n    it(\"mutually suspended\", () => {\n      interface A {\n        readonly a: string\n        readonly bs: ReadonlyArray<B>\n      }\n      interface B {\n        readonly b: number\n        readonly as: ReadonlyArray<A>\n      }\n      const schemaA = S.Struct({\n        a: S.String,\n        bs: S.Array(S.suspend((): S.Schema<B> => schemaB))\n      })\n      const schemaB = S.Struct({\n        b: S.Number,\n        as: S.Array(S.suspend(() => schemaA))\n      })\n      const isA = P.is(schemaA)\n      assertTrue(isA({ a: \"a1\", bs: [] }))\n      assertTrue(isA({ a: \"a1\", bs: [{ b: 1, as: [] }] }))\n      assertTrue(\n        isA({ a: \"a1\", bs: [{ b: 1, as: [{ a: \"a2\", bs: [] }] }] })\n      )\n      assertFalse(\n        isA({ a: \"a1\", bs: [{ b: 1, as: [{ a: \"a2\", bs: [null] }] }] })\n      )\n    })\n  })\n\n  it(\"union\", () => {\n    const schema = S.Union(S.String, S.Number)\n    const is = P.is(schema)\n    assertFalse(is(null))\n    assertTrue(is(1))\n    assertTrue(is(\"a\"))\n  })\n\n  describe(\"rest\", () => {\n    it(\"baseline\", () => {\n      const schema = S.Tuple([S.String, S.Number], S.Boolean)\n      const is = P.is(schema)\n      assertTrue(is([\"a\", 1]))\n      assertTrue(is([\"a\", 1, true]))\n      assertTrue(is([\"a\", 1, true, false]))\n      assertFalse(is([\"a\", 1, true, \"a\"]))\n      assertFalse(is([\"a\", 1, true, \"a\", true]))\n    })\n  })\n\n  describe(\"extend\", () => {\n    it(\"struct\", () => {\n      const schema = S.Struct({ a: S.String }).pipe(\n        S.extend(S.Struct({ b: S.Number }))\n      )\n      const is = P.is(schema)\n      assertTrue(is({ a: \"a\", b: 1 }))\n\n      assertFalse(is({}))\n      assertFalse(is({ a: \"a\" }))\n    })\n\n    it(\"record(string, string)\", () => {\n      const schema = S.Struct({ a: S.String }, S.Record({ key: S.String, value: S.String }))\n      const is = P.is(schema)\n      assertTrue(is({ a: \"a\" }))\n      assertTrue(is({ a: \"a\", b: \"b\" }))\n\n      assertFalse(is({}))\n      assertFalse(is({ b: \"b\" }))\n      assertFalse(is({ a: 1 }))\n      assertFalse(is({ a: \"a\", b: 2 }))\n    })\n  })\n\n  it(\"nonEmptyString\", () => {\n    const schema = S.String.pipe(S.nonEmptyString())\n    const is = P.is(schema)\n    assertTrue(is(\"a\"))\n    assertTrue(is(\"aa\"))\n\n    assertFalse(is(\"\"))\n  })\n\n  it(\"should respect outer/inner options\", () => {\n    const schema = S.Struct({ a: Util.NumberFromChar })\n    const input = { a: 1, b: \"b\" }\n    assertFalse(S.is(schema)(input, { onExcessProperty: \"error\" }))\n    assertFalse(S.is(schema, { onExcessProperty: \"error\" })(input))\n    assertTrue(S.is(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/isSchema.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"isSchema\", () => {\n  it(\"Schema\", () => {\n    assertTrue(S.isSchema(S.String))\n    assertFalse(S.isSchema(S.parseJson))\n  })\n\n  it(\"BrandSchema\", () => {\n    assertTrue(S.isSchema(S.String.pipe(S.brand(\"my-brand\"))))\n  })\n\n  it(\"PropertySignature\", () => {\n    assertFalse(S.isSchema(S.propertySignature(S.String)))\n    assertFalse(S.isSchema(S.optionalWith(S.String, { exact: true })))\n    assertFalse(S.isSchema(S.optionalWith(S.String, { default: () => \"\" })))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/keyof.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, throws } from \"@effect/vitest/utils\"\nimport * as P from \"effect/ParseResult\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"keyof\", () => {\n  it(\"should unify string literals with string\", () => {\n    const schema = S.Struct({ a: S.String }, S.Record({ key: S.String, value: S.String }))\n    const keyof = S.keyof(schema)\n    deepStrictEqual(keyof.ast, S.String.ast)\n  })\n\n  it(\"should unify symbol literals with symbol\", () => {\n    const a = Symbol.for(\"effect/Schema/test/a\")\n    const schema = S.Struct({ [a]: S.String }, S.Record({ key: S.SymbolFromSelf, value: S.String }))\n    const keyof = S.keyof(schema)\n    deepStrictEqual(keyof.ast, S.SymbolFromSelf.ast)\n  })\n\n  describe(\"struct\", () => {\n    it(\"string keys\", () => {\n      const schema = S.Struct({\n        a: S.String,\n        b: S.Number\n      })\n      // type K = keyof S.Schema.Type<typeof schema> // \"a\" | \"b\"\n      const keyOf = S.keyof(schema)\n      const is = P.is(keyOf)\n      assertTrue(is(\"a\"))\n      assertTrue(is(\"b\"))\n      assertFalse(is(\"c\"))\n    })\n\n    it(\"symbol keys\", () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const b = Symbol.for(\"effect/Schema/test/b\")\n      const schema = S.Struct({\n        [a]: S.String,\n        [b]: S.Number\n      })\n      const keyOf = S.keyof(schema)\n      const is = P.is(keyOf)\n      assertTrue(is(a))\n      assertTrue(is(b))\n      assertFalse(is(\"a\"))\n      assertFalse(is(\"b\"))\n    })\n  })\n\n  describe(\"record\", () => {\n    it(\"string\", () => {\n      const schema = S.Record({ key: S.String, value: S.Number })\n      // type K = keyof S.Schema.Type<typeof schema> // string\n      deepStrictEqual(AST.keyof(schema.ast), S.String.ast)\n    })\n\n    it(\"symbol\", () => {\n      const schema = S.Record({ key: S.SymbolFromSelf, value: S.Number })\n      // type K = keyof S.Schema.Type<typeof schema> // symbol\n      deepStrictEqual(AST.keyof(schema.ast), S.SymbolFromSelf.ast)\n    })\n\n    it(\"template literal\", () => {\n      const schema = S.Record({ key: S.TemplateLiteral(S.Literal(\"a\"), S.String), value: S.Number })\n      // type K = keyof S.Schema.Type<typeof schema> // `a${string}`\n      deepStrictEqual(AST.keyof(schema.ast), S.TemplateLiteral(S.Literal(\"a\"), S.String).ast)\n    })\n  })\n\n  it(\"suspend\", () => {\n    interface Category {\n      readonly name: string\n      readonly categories: ReadonlyArray<Category>\n    }\n    const schema: S.Schema<Category> = S.suspend( // intended outer suspend\n      () =>\n        S.Struct({\n          name: S.String,\n          categories: S.Array(schema)\n        })\n    )\n    deepStrictEqual(AST.keyof(schema.ast), S.Literal(\"name\", \"categories\").ast)\n  })\n\n  describe(\"union\", () => {\n    it(\"union of structs\", () => {\n      const schema = S.Union(S.Struct({ a: S.String }), S.Struct({ a: S.Number }))\n      // type K = keyof S.Schema.Type<typeof schema> // \"a\"\n      deepStrictEqual(AST.keyof(schema.ast), S.Literal(\"a\").ast)\n    })\n\n    it(\"union of records\", () => {\n      const schema = S.Union(\n        S.Record({ key: S.String, value: S.Number }),\n        S.Record({ key: S.String, value: S.Boolean })\n      )\n      // type K = keyof S.Schema.Type<typeof schema> // string\n      deepStrictEqual(AST.keyof(schema.ast), S.String.ast)\n    })\n\n    it(\"union of structs and records\", () => {\n      const schema = S.Union(\n        S.Struct({ a: S.String }, S.Record({ key: S.String, value: S.Number })),\n        S.Struct({ a: S.Number }, S.Record({ key: S.String, value: S.Boolean }))\n      )\n      // type K = keyof S.Schema.Type<typeof schema> // string\n      deepStrictEqual(AST.keyof(schema.ast), S.String.ast)\n    })\n  })\n\n  it(\"should support Class\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String }) {}\n    // type K = keyof S.Schema.Type<typeof A> // \"a\"\n    deepStrictEqual(AST.keyof(A.ast), S.Literal(\"a\").ast)\n  })\n\n  it(\"should throw on unsupported schemas\", () => {\n    throws(\n      () => S.keyof(S.Option(S.String)),\n      new Error(`Unsupported schema\nschema (Declaration): Option<string>`)\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/mutable.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport { identity } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"mutable\", () => {\n  it(\"string\", () => {\n    deepStrictEqual(S.mutable(S.String).ast, S.String.ast)\n  })\n\n  it(\"struct\", () => {\n    const schema = S.mutable(S.Struct({ a: S.Number }))\n    deepStrictEqual(\n      schema.ast,\n      new AST.TypeLiteral([\n        new AST.PropertySignature(\"a\", S.Number.ast, false, false)\n      ], [])\n    )\n  })\n\n  it(\"record\", () => {\n    const schema = S.mutable(S.Record({ key: S.String, value: S.Number }))\n    deepStrictEqual(schema.ast, new AST.TypeLiteral([], [new AST.IndexSignature(S.String.ast, S.Number.ast, false)]))\n  })\n\n  it(\"array\", () => {\n    const schema = S.mutable(S.Array(S.String))\n    deepStrictEqual(schema.ast, new AST.TupleType([], [new AST.Type(S.String.ast)], false))\n  })\n\n  it(\"union\", () => {\n    const schema = S.mutable(S.Union(S.Struct({ a: S.Number }), S.Array(S.String)))\n    deepStrictEqual(\n      schema.ast,\n      AST.Union.make([\n        new AST.TypeLiteral([\n          new AST.PropertySignature(\"a\", S.Number.ast, false, false)\n        ], []),\n        new AST.TupleType([], [new AST.Type(S.String.ast)], false)\n      ])\n    )\n  })\n\n  it(\"refinement\", () => {\n    const schema = S.mutable(S.Array(S.String).pipe(S.maxItems(2)))\n    if (AST.isRefinement(schema.ast)) {\n      deepStrictEqual(schema.ast.from, new AST.TupleType([], [new AST.Type(S.String.ast)], false))\n    }\n  })\n\n  it(\"suspend\", () => {\n    const schema = S.mutable(S.suspend( // intended outer suspend\n      () => S.Array(S.String)\n    ))\n    if (AST.isSuspend(schema.ast)) {\n      deepStrictEqual(schema.ast.f(), new AST.TupleType([], [new AST.Type(S.String.ast)], false))\n    }\n  })\n\n  it(\"transformation\", () => {\n    const schema = S.mutable(\n      S.transform(S.Array(S.String), S.Array(S.String), { strict: true, decode: identity, encode: identity })\n    )\n    if (AST.isTransformation(schema.ast)) {\n      deepStrictEqual(schema.ast.from, new AST.TupleType([], [new AST.Type(S.String.ast)], false))\n      deepStrictEqual(schema.ast.to, new AST.TupleType([], [new AST.Type(S.String.ast)], false))\n    }\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/nonEmptyArray.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"nonEmptyArray\", () => {\n  it(\"should expose the value\", () => {\n    const schema = S.NonEmptyArray(S.String)\n    strictEqual(schema.value, S.String)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/omit.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, doesNotThrow, strictEqual } from \"@effect/vitest/utils\"\nimport { Schema as S, SchemaAST as AST } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"omit\", () => {\n  describe(\"omit specific tests\", () => {\n    it(\"Struct & Record\", () => {\n      const record = S.Record({ key: S.String, value: S.Union(S.String, S.Number) })\n      const schema = S.Struct(\n        { a: S.NumberFromString, b: S.Number },\n        record\n      )\n      const omitted = schema.pipe(S.omit(\"b\"))\n      Util.assertions.ast.equals(omitted, record)\n    })\n\n    describe(\"Record\", () => {\n      it(\"Record(string, number)\", () => {\n        const schema = S.Record({ key: S.String, value: S.Number })\n        const omitted = schema.pipe(S.omit(\"a\"))\n        Util.assertions.ast.equals(omitted, schema)\n      })\n\n      it(\"Record(symbol, number)\", () => {\n        const a = Symbol.for(\"effect/Schema/test/a\")\n        const schema = S.Record({ key: S.SymbolFromSelf, value: S.Number })\n        const omitted = schema.pipe(S.omit(a))\n        Util.assertions.ast.equals(omitted, schema)\n      })\n\n      it(\"Record(string, string) & Record(`a${string}`, number)\", async () => {\n        const schema = S.Struct(\n          {},\n          S.Record({ key: S.String, value: S.Union(S.String, S.Number) }),\n          S.Record({ key: S.TemplateLiteral(S.Literal(\"a\"), S.String), value: S.Number })\n        )\n        const omitted = schema.pipe(S.omit(\"a\"))\n        Util.assertions.ast.equals(omitted, S.Record({ key: S.String, value: S.Union(S.String, S.Number) }))\n      })\n    })\n\n    it(\"fromKey\", () => {\n      const schema = S.Struct({\n        a: S.String,\n        b: S.propertySignature(S.Number).pipe(S.fromKey(\"c\"))\n      })\n      const omitted = schema.pipe(S.omit(\"a\"))\n      const expected = S.Struct({\n        c: S.Number\n      }).pipe(S.rename({ c: \"b\" }))\n      Util.assertions.ast.equals(omitted, expected)\n    })\n\n    it(\"rename\", () => {\n      const schema = S.Struct({\n        a: S.String,\n        c: S.Number\n      }).pipe(S.rename({ c: \"b\" }))\n      const omitted = schema.pipe(S.omit(\"a\"))\n      const expected = S.Struct({\n        c: S.Number\n      }).pipe(S.rename({ c: \"b\" }))\n      Util.assertions.ast.equals(omitted, expected)\n    })\n  })\n\n  it(\"Refinement\", () => {\n    const schema = S.Struct({ a: S.NumberFromString, b: S.Number }).pipe(S.filter(() => true))\n    const omitted = schema.pipe(S.omit(\"b\"))\n    Util.assertions.ast.equals(omitted, S.Struct({ a: S.NumberFromString }))\n  })\n\n  describe(\"Struct\", () => {\n    it(\"required properties\", () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const schema = S.Struct({ [a]: S.String, b: S.NumberFromString, c: S.Boolean })\n      const omitted = schema.pipe(S.omit(\"c\"))\n      Util.assertions.ast.equals(omitted, S.Struct({ [a]: S.String, b: S.NumberFromString }))\n    })\n\n    it(\"optional property (exact)\", () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.String, { exact: true }),\n        b: S.NumberFromString,\n        c: S.Boolean\n      })\n      const omitted = schema.pipe(S.omit(\"c\"))\n      Util.assertions.ast.equals(\n        omitted,\n        S.Struct({ a: S.optionalWith(S.String, { exact: true }), b: S.NumberFromString })\n      )\n    })\n  })\n\n  it(\"Union\", () => {\n    const A = S.Struct({ a: S.String, b: S.Number })\n    const B = S.Struct({ a: S.Number, b: S.String })\n    const schema = S.Union(A, B)\n    const omitted = schema.pipe(S.omit(\"b\"))\n    Util.assertions.ast.equals(omitted, S.Struct({ a: S.Union(S.String, S.Number) }))\n  })\n\n  it(\"suspend\", async () => {\n    interface A {\n      readonly a: string\n      readonly as: ReadonlyArray<A>\n    }\n    const schema: S.Schema<A> = S.suspend( // intended outer suspend\n      () =>\n        S.Struct({\n          a: S.String,\n          as: S.Array(schema)\n        }).annotations({ identifier: \"A\" })\n    )\n    const omitted = schema.pipe(S.omit(\"a\"))\n    strictEqual(String(omitted), \"{ readonly as: ReadonlyArray<A> }\")\n    await Util.assertions.decoding.succeed(omitted, { as: [] })\n    await Util.assertions.decoding.succeed(omitted, { as: [{ a: \"a\", as: [] }] })\n\n    await Util.assertions.decoding.fail(\n      omitted,\n      { as: [{ as: [] }] },\n      `{ readonly as: ReadonlyArray<A> }\n└─ [\"as\"]\n   └─ ReadonlyArray<A>\n      └─ [0]\n         └─ A\n            └─ [\"a\"]\n               └─ is missing`\n    )\n  })\n\n  describe(\"Transformation\", () => {\n    it(\"ComposeTransformation\", () => {\n      const schema = S.compose(\n        S.Struct({ a: S.NumberFromString, b: S.Number }),\n        S.Struct({ a: S.Number, b: S.Number })\n      )\n      const omitted = schema.pipe(S.omit(\"b\"))\n      Util.assertions.ast.equals(omitted, S.compose(S.Struct({ a: S.NumberFromString }), S.Struct({ a: S.Number })))\n    })\n\n    describe(\"TypeLiteralTransformation\", () => {\n      it(\"omitting keys without associated PropertySignatureTransformations\", () => {\n        const schema = S.Struct({ a: S.optionalWith(S.NumberFromString, { default: () => 0 }), b: S.Number })\n        const omitted = schema.pipe(S.omit(\"b\"))\n        const ast = omitted.ast\n        assertTrue(AST.isTransformation(ast))\n        deepStrictEqual(ast.from, S.Struct({ a: S.optional(S.NumberFromString) }).ast)\n        deepStrictEqual(ast.to, S.Struct({ a: S.Number }).ast)\n        assertTrue(AST.isTransformation(schema.ast))\n        deepStrictEqual(ast.transformation, schema.ast.transformation)\n        doesNotThrow(() => omitted.pipe(S.extend(S.Struct({ c: S.Boolean }))))\n      })\n\n      it(\"omitting keys with associated PropertySignatureTransformations\", () => {\n        const schema = S.Struct({\n          a: S.optionalWith(S.NumberFromString, { default: () => 0 }),\n          b: S.NumberFromString\n        })\n        const omitted = schema.pipe(S.omit(\"a\"))\n        const ast = omitted.ast\n        assertTrue(AST.isTypeLiteral(ast))\n        deepStrictEqual(ast.propertySignatures, [\n          new AST.PropertySignature(\"b\", S.NumberFromString.ast, false, true)\n        ])\n        doesNotThrow(() => omitted.pipe(S.extend(S.Struct({ c: S.Boolean }))))\n      })\n    })\n\n    describe(\"SurrogateAnnotation\", () => {\n      it(\"a single Class\", () => {\n        class A extends S.Class<A>(\"A\")({ a: S.NumberFromString, b: S.Number }) {}\n        const schema = A\n        const omitted = schema.pipe(S.omit(\"b\"))\n        Util.assertions.ast.equals(omitted, S.Struct({ a: S.NumberFromString }))\n      })\n\n      it(\"a union of Classes\", () => {\n        class A extends S.Class<A>(\"A\")({ a: S.Number, b: S.String }) {}\n        class B extends S.Class<B>(\"B\")({ a: S.String, b: S.Number }) {}\n        const schema = S.Union(A, B)\n        const omitted = schema.pipe(S.omit(\"b\"))\n        Util.assertions.ast.equals(omitted, S.Struct({ a: S.Union(S.Number, S.String) }))\n      })\n    })\n  })\n\n  it(\"typeSchema(Class)\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String, b: S.NumberFromString }) {}\n    const schema = A\n    const omitted = schema.pipe(S.typeSchema, S.omit(\"a\"))\n    Util.assertions.ast.equals(omitted, S.Struct({ b: S.Number }))\n  })\n\n  it(\"Class\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String, b: S.NumberFromString }) {}\n    const schema = A\n    const omitted = schema.pipe(S.omit(\"a\"))\n    Util.assertions.ast.equals(omitted, S.Struct({ b: S.NumberFromString }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/optional.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"optional\", () => {\n  it(\"should expose a from property\", () => {\n    const schema = S.optional(S.String)\n    strictEqual(schema.from, S.String)\n  })\n\n  it(\"if the input is Schema.Undefined should not duplicate the schema\", () => {\n    const schema = S.optional(S.Undefined)\n    strictEqual((schema.ast as any as S.PropertySignatureDeclaration).type, S.Undefined.ast)\n  })\n\n  it(\"if the input is Schema.Never should include the input in the schema\", () => {\n    const schema = S.optional(S.Never)\n    strictEqual((schema.ast as any as S.PropertySignatureDeclaration).type, S.Undefined.ast)\n  })\n\n  it(\"should expose a from property after an annotations call\", () => {\n    const schema = S.optional(S.String).annotations({})\n    strictEqual(schema.from, S.String)\n  })\n\n  it(\"decoding / encoding\", async () => {\n    const schema = S.Struct({\n      a: S.optional(S.NumberFromString)\n    })\n    await Util.assertions.decoding.succeed(schema, {}, {})\n    await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: undefined })\n    await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: \"a\" },\n      `{ readonly a?: NumberFromString | undefined }\n└─ [\"a\"]\n   └─ NumberFromString | undefined\n      ├─ NumberFromString\n      │  └─ Transformation process failure\n      │     └─ Unable to decode \"a\" into a number\n      └─ Expected undefined, actual \"a\"`\n    )\n\n    await Util.assertions.encoding.succeed(schema, {}, {})\n    await Util.assertions.encoding.succeed(schema, { a: undefined }, { a: undefined })\n    await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: \"1\" })\n  })\n\n  it(\"Schema.Never as input\", async () => {\n    const schema = S.Struct({\n      a: S.optional(S.Never)\n    })\n    await Util.assertions.decoding.succeed(schema, {}, {})\n    await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: undefined })\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: \"a\" },\n      `{ readonly a?: undefined }\n└─ [\"a\"]\n   └─ Expected undefined, actual \"a\"`\n    )\n\n    await Util.assertions.encoding.succeed(schema, {}, {})\n    await Util.assertions.encoding.succeed(schema, { a: undefined }, { a: undefined })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/optionalElement.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"optionalElement\", () => {\n  it(\"toString\", () => {\n    strictEqual(String(S.optionalElement(S.String)), \"string?\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/optionalToRequired.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Option from \"effect/Option\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"optionalToRequired\", () => {\n  it(\"two transformation schemas\", async () => {\n    const ps = S.optionalToRequired(\n      S.NumberFromString,\n      S.BigIntFromNumber,\n      { decode: Option.getOrElse(() => 0), encode: Option.liftPredicate((n) => n !== 0) }\n    )\n    const schema = S.Struct({ a: ps })\n    await Util.assertions.decoding.succeed(schema, {}, { a: 0n })\n    await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1n })\n\n    await Util.assertions.encoding.succeed(schema, { a: 0n }, {})\n    await Util.assertions.encoding.succeed(schema, { a: 1n }, { a: \"1\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/optionalWith.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as O from \"effect/Option\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"optionalWith\", () => {\n  it(\"annotations\", async () => {\n    const schema = S.Struct({\n      a: S.optionalWith(S.NumberFromString, {\n        exact: true\n      }).annotations({ description: \"my description\" })\n    })\n    deepStrictEqual((schema.ast as any).propertySignatures[0].annotations, {\n      [AST.DescriptionAnnotationId]: \"my description\"\n    })\n  })\n\n  describe(\"{ exact: true }\", () => {\n    it(\"should expose a from property\", () => {\n      const schema = S.optionalWith(S.String, { exact: true })\n      strictEqual(schema.from, S.String)\n    })\n\n    it(\"should expose a from property after an annotations call\", () => {\n      const schema = S.optionalWith(S.String, { exact: true }).annotations({})\n      strictEqual(schema.from, S.String)\n    })\n\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { exact: true })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, {})\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `{ readonly a?: NumberFromString }\n└─ [\"a\"]\n   └─ NumberFromString\n      └─ Transformation process failure\n         └─ Unable to decode \"a\" into a number`\n      )\n\n      await Util.assertions.encoding.succeed(schema, {}, {})\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: \"1\" })\n    })\n\n    it(\"never\", async () => {\n      strictEqual(S.optionalWith(S.Never, { exact: true }).from.ast, AST.neverKeyword)\n      const schema = S.Struct({ a: S.optionalWith(S.Never, { exact: true }), b: S.Number })\n      await Util.assertions.decoding.succeed(schema, { b: 1 })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\", b: 1 },\n        `{ readonly a?: never; readonly b: number }\n└─ [\"a\"]\n   └─ Expected never, actual \"a\"`\n      )\n    })\n  })\n\n  describe(\"{ nullable: true }\", () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { nullable: true })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, {})\n      await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: undefined })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n      await Util.assertions.decoding.succeed(schema, { a: null }, {})\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | null | undefined\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            ├─ Expected null, actual \"a\"\n            └─ Expected undefined, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, {}, {})\n      await Util.assertions.encoding.succeed(schema, { a: undefined }, { a: undefined })\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: \"1\" })\n    })\n  })\n\n  describe(\"{ exact: true, nullable: true }\", () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { exact: true, nullable: true })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, {})\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n      await Util.assertions.decoding.succeed(schema, { a: null }, {})\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: undefined },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | null\n            ├─ NumberFromString\n            │  └─ Encoded side transformation failure\n            │     └─ Expected string, actual undefined\n            └─ Expected null, actual undefined`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | null\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            └─ Expected null, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, {}, {})\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: \"1\" })\n    })\n  })\n\n  describe(`optionalWith > { exact: true, as: \"Option\" }`, () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { exact: true, as: \"Option\" })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: O.some(1) })\n      await Util.assertions.decoding.fail(\n        schema,\n        {\n          a: \"a\"\n        },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: O.some(1) }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: O.none() }, {})\n    })\n  })\n\n  describe(`optionalWith > { exact: true, nullable: true, as: \"Option\" }`, () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { exact: true, nullable: true, as: \"Option\" })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: null }, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: O.some(1) })\n      await Util.assertions.decoding.fail(\n        schema,\n        {\n          a: \"a\"\n        },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | null\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            └─ Expected null, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: O.some(1) }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: O.none() }, {})\n    })\n  })\n\n  describe(`optionalWith > { exact: true, nullable: true, as: \"Option\", onNoneEncoding: () => O.some(null) }`, () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, {\n          exact: true,\n          nullable: true,\n          as: \"Option\",\n          onNoneEncoding: () => O.some(null)\n        })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: null }, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: O.some(1) })\n      await Util.assertions.decoding.fail(\n        schema,\n        {\n          a: \"a\"\n        },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | null\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            └─ Expected null, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: O.some(1) }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: O.none() }, { a: null })\n    })\n  })\n\n  describe(`optionalWith > { as: \"Option\" }`, () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({ a: S.optionalWith(S.NumberFromString, { as: \"Option\" }) })\n      await Util.assertions.decoding.succeed(schema, {}, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: O.some(1) })\n      await Util.assertions.decoding.fail(\n        schema,\n        {\n          a: \"a\"\n        },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | undefined\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            └─ Expected undefined, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: O.some(1) }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: O.none() }, {})\n    })\n  })\n\n  describe(`optionalWith > { nullable: true, as: \"Option\" }`, () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { nullable: true, as: \"Option\" })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: null }, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: O.some(1) })\n      await Util.assertions.decoding.fail(\n        schema,\n        {\n          a: \"a\"\n        },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | null | undefined\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            ├─ Expected null, actual \"a\"\n            └─ Expected undefined, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: O.some(1) }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: O.none() }, {})\n    })\n  })\n\n  describe(`optionalWith > { as: \"Option\", onNoneEncoding: () => O.some(undefined) }`, () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { as: \"Option\", onNoneEncoding: () => O.some(undefined) })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: O.some(1) })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: null },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | undefined\n            ├─ NumberFromString\n            │  └─ Encoded side transformation failure\n            │     └─ Expected string, actual null\n            └─ Expected undefined, actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        {\n          a: \"a\"\n        },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | undefined\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            └─ Expected undefined, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: O.some(1) }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: O.none() }, { a: undefined })\n    })\n  })\n\n  describe(`optionalWith > { nullable: true, as: \"Option\", onNoneEncoding: () => O.some(undefined) }`, () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { nullable: true, as: \"Option\", onNoneEncoding: () => O.some(undefined) })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: null }, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: O.some(1) })\n      await Util.assertions.decoding.fail(\n        schema,\n        {\n          a: \"a\"\n        },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | null | undefined\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            ├─ Expected null, actual \"a\"\n            └─ Expected undefined, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: O.some(1) }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: O.none() }, { a: undefined })\n    })\n  })\n\n  describe(`optionalWith > { nullable: true, as: \"Option\", onNoneEncoding: () => O.some(null) }`, () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { nullable: true, as: \"Option\", onNoneEncoding: () => O.some(null) })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: null }, { a: O.none() })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: O.some(1) })\n      await Util.assertions.decoding.fail(\n        schema,\n        {\n          a: \"a\"\n        },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | null | undefined\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            ├─ Expected null, actual \"a\"\n            └─ Expected undefined, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: O.some(1) }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: O.none() }, { a: null })\n    })\n  })\n\n  describe(\"{ exact: true, default: () => A }\", () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { exact: true, default: () => 0 })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: 0 })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"a\" into a number`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: 0 }, { a: \"0\" })\n    })\n\n    it(\"should apply the default to the default constructor\", () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { exact: true, default: () => 0 })\n      })\n      deepStrictEqual(schema.make({}), { a: 0 })\n    })\n  })\n\n  describe(\"{ default: () => A }\", () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { default: () => 0 })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: 0 })\n      await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: 0 })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | undefined\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            └─ Expected undefined, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: 0 }, { a: \"0\" })\n    })\n\n    it(\"should apply the default to the default constructor\", () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { default: () => 0 })\n      })\n      deepStrictEqual(schema.make({}), { a: 0 })\n    })\n  })\n\n  describe(\"{ nullable: true, default: () => A }\", () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { nullable: true, default: () => 0 })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: 0 })\n      await Util.assertions.decoding.succeed(schema, { a: null }, { a: 0 })\n      await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: 0 })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | null | undefined\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            ├─ Expected null, actual \"a\"\n            └─ Expected undefined, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: 0 }, { a: \"0\" })\n    })\n\n    it(\"should apply the default to the default constructor\", () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { nullable: true, default: () => 0 })\n      })\n      deepStrictEqual(schema.make({}), { a: 0 })\n    })\n  })\n\n  describe(\"{ exact: true, nullable: true, default: () => A }\", () => {\n    it(\"decoding / encoding\", async () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { exact: true, nullable: true, default: () => 0 })\n      })\n      await Util.assertions.decoding.succeed(schema, {}, { a: 0 })\n      await Util.assertions.decoding.succeed(schema, { a: null }, { a: 0 })\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a\" },\n        `(Struct (Encoded side) <-> Struct (Type side))\n└─ Encoded side transformation failure\n   └─ Struct (Encoded side)\n      └─ [\"a\"]\n         └─ NumberFromString | null\n            ├─ NumberFromString\n            │  └─ Transformation process failure\n            │     └─ Unable to decode \"a\" into a number\n            └─ Expected null, actual \"a\"`\n      )\n\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, { a: \"1\" })\n      await Util.assertions.encoding.succeed(schema, { a: 0 }, { a: \"0\" })\n    })\n\n    it(\"should apply the default to the default constructor\", () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.NumberFromString, { exact: true, nullable: true, default: () => 0 })\n      })\n      deepStrictEqual(schema.make({}), { a: 0 })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/parseJson.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Exit from \"effect/Exit\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\nconst isBun = \"Bun\" in globalThis\n\ndescribe(\"parseJson\", () => {\n  describe(\"parseJson()\", () => {\n    it(\"decoding\", async () => {\n      const schema = S.parseJson()\n      await Util.assertions.decoding.succeed(schema, \"{}\", {})\n      await Util.assertions.decoding.succeed(schema, `{\"a\":\"b\"}`, { \"a\": \"b\" })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `parseJson\n└─ Encoded side transformation failure\n   └─ Expected string, actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"\",\n        isBun ?\n          `parseJson\n└─ Transformation process failure\n    └─ JSON Parse error: Unexpected EOF` :\n          `parseJson\n└─ Transformation process failure\n   └─ Unexpected end of JSON input`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"a\",\n        isBun\n          ? `parseJson\n└─ Transformation process failure\n    └─ JSON Parse error: Unexpected identifier \"a\"`\n          : `parseJson\n└─ Transformation process failure\n   └─ Unexpected token 'a', \"a\" is not valid JSON`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        \"{\",\n        isBun\n          ? `parseJson\n└─ Transformation process failure\n    └─ JSON Parse error: Expected '}'`\n          : `parseJson\n└─ Transformation process failure\n   └─ Expected property name or '}' in JSON at position 1 (line 1 column 2)`\n      )\n    })\n\n    it(\"encoding\", async () => {\n      const schema = S.parseJson()\n      await Util.assertions.encoding.succeed(schema, \"a\", `\"a\"`)\n      await Util.assertions.encoding.succeed(schema, { a: \"b\" }, `{\"a\":\"b\"}`)\n\n      const bad: any = { a: 0 }\n      bad[\"a\"] = bad\n      await Util.assertions.encoding.fail(\n        schema,\n        bad,\n        isBun ?\n          `parseJson\n└─ Transformation process failure\n    └─ JSON.stringify cannot serialize cyclic structures.` :\n          `parseJson\n└─ Transformation process failure\n   └─ Converting circular structure to JSON\n    --> starting at object with constructor 'Object'\n    --- property 'a' closes the circle`\n      )\n    })\n  })\n\n  describe(\"parseJson(schema)\", () => {\n    it(\"decoding\", async () => {\n      const schema = S.parseJson(S.Struct({ a: S.NumberFromString }))\n      await Util.assertions.decoding.succeed(schema, `{\"a\":\"1\"}`, { a: 1 })\n      await Util.assertions.decoding.fail(\n        schema,\n        `{\"a\"}`,\n        isBun\n          ? `(parseJson <-> { readonly a: NumberFromString })\n└─ Encoded side transformation failure\n    └─ parseJson\n      └─ Transformation process failure\n          └─ JSON Parse error: Expected ':' before value in object property definition`\n          : `(parseJson <-> { readonly a: NumberFromString })\n└─ Encoded side transformation failure\n   └─ parseJson\n      └─ Transformation process failure\n         └─ Expected ':' after property name in JSON at position 4 (line 1 column 5)`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        `{\"a\":\"b\"}`,\n        `(parseJson <-> { readonly a: NumberFromString })\n└─ Type side transformation failure\n   └─ { readonly a: NumberFromString }\n      └─ [\"a\"]\n         └─ NumberFromString\n            └─ Transformation process failure\n               └─ Unable to decode \"b\" into a number`\n      )\n\n      await Util.assertions.decoding.succeed(schema.from, `{\"a\":\"1\"}`, { a: \"1\" })\n      await Util.assertions.decoding.succeed(schema.to, { a: \"1\" }, { a: 1 })\n    })\n\n    it(\"encoding\", async () => {\n      const schema = S.parseJson(S.Struct({ a: S.NumberFromString }))\n      await Util.assertions.encoding.succeed(schema, { a: 1 }, `{\"a\":\"1\"}`)\n    })\n\n    describe(\"roundtrip\", () => {\n      it(\"Exit\", async () => {\n        const schema = S.parseJson(S.Exit({ failure: S.Never, success: S.Void, defect: S.Defect }))\n        const encoding = S.encodeSync(schema)(Exit.void)\n        await Util.assertions.decoding.succeed(schema, encoding, Exit.void)\n      })\n    })\n  })\n\n  describe(\"parseJson(schema, options)\", () => {\n    it(\"reviver\", async () => {\n      const schema = S.parseJson(S.Struct({ a: S.Number, b: S.String }), {\n        reviver: (key, value) => key === \"a\" ? value + 1 : value\n      })\n      await Util.assertions.decoding.succeed(schema, `{\"a\":1,\"b\":\"b\"}`, { a: 2, b: \"b\" })\n    })\n\n    it(\"replacer\", async () => {\n      const schema = S.parseJson(S.Struct({ a: S.Number, b: S.String }), { replacer: [\"b\"] })\n      await Util.assertions.encoding.succeed(\n        schema,\n        { a: 1, b: \"b\" },\n        `{\"b\":\"b\"}`\n      )\n    })\n\n    it(\"space\", async () => {\n      const schema = S.parseJson(S.Struct({ a: S.Number }), { space: 2 })\n      await Util.assertions.encoding.succeed(\n        schema,\n        { a: 1 },\n        `{\n  \"a\": 1\n}`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/partial.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual, throws } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"partial\", () => {\n  it(\"Struct\", async () => {\n    const schema = S.partial(S.Struct({ a: S.Number }))\n    await Util.assertions.decoding.succeed(schema, {})\n    await Util.assertions.decoding.succeed(schema, { a: 1 })\n    await Util.assertions.decoding.succeed(schema, { a: undefined })\n\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: null },\n      `{ readonly a?: number | undefined }\n└─ [\"a\"]\n   └─ number | undefined\n      ├─ Expected number, actual null\n      └─ Expected undefined, actual null`\n    )\n  })\n\n  it(\"Record\", async () => {\n    const schema = S.partial(S.Record({ key: S.String, value: S.NumberFromString }))\n    await Util.assertions.decoding.succeed(schema, {}, {})\n    await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n    await Util.assertions.decoding.succeed(schema, { a: undefined })\n  })\n\n  describe(\"Tuple\", () => {\n    it(\"e\", async () => {\n      const schema = S.partial(S.Tuple(S.NumberFromString))\n      await Util.assertions.decoding.succeed(schema, [\"1\"], [1])\n      await Util.assertions.decoding.succeed(schema, [], [])\n      await Util.assertions.decoding.succeed(schema, [undefined])\n    })\n\n    it(\"e r\", async () => {\n      const schema = S.partial(S.Tuple([S.NumberFromString], S.NumberFromString))\n      await Util.assertions.decoding.succeed(schema, [\"1\"], [1])\n      await Util.assertions.decoding.succeed(schema, [], [])\n      await Util.assertions.decoding.succeed(schema, [\"1\", \"2\"], [1, 2])\n      await Util.assertions.decoding.succeed(schema, [\"1\", undefined], [1, undefined])\n      await Util.assertions.decoding.succeed(schema, [undefined])\n    })\n  })\n\n  it(\"Array\", async () => {\n    const schema = S.partial(S.Array(S.Number))\n    await Util.assertions.decoding.succeed(schema, [])\n    await Util.assertions.decoding.succeed(schema, [1])\n    await Util.assertions.decoding.succeed(schema, [undefined])\n\n    await Util.assertions.decoding.fail(\n      schema,\n      [\"a\"],\n      `ReadonlyArray<number | undefined>\n└─ [0]\n   └─ number | undefined\n      ├─ Expected number, actual \"a\"\n      └─ Expected undefined, actual \"a\"`\n    )\n  })\n\n  describe(\"unsupported schemas\", () => {\n    it(\"declarations should throw\", () => {\n      throws(\n        () => S.partial(S.OptionFromSelf(S.String)),\n        new Error(`Unsupported schema\nschema (Declaration): Option<string>`)\n      )\n    })\n\n    it(\"refinements should throw\", () => {\n      throws(\n        () => S.partial(S.String.pipe(S.minLength(2))),\n        new Error(`Unsupported schema\nschema (Refinement): minLength(2)`)\n      )\n    })\n\n    describe(\"Transformation\", () => {\n      it(\"should support property key renamings\", async () => {\n        const original = S.Struct({\n          a: S.String,\n          b: S.propertySignature(S.String).pipe(S.fromKey(\"c\"))\n        })\n        const schema = S.partial(original)\n        strictEqual(\n          S.format(schema),\n          \"({ readonly a?: string | undefined; readonly c?: string | undefined } <-> { readonly a?: string | undefined; readonly b?: string | undefined })\"\n        )\n        await Util.assertions.decoding.succeed(schema, {})\n        await Util.assertions.decoding.succeed(schema, { a: undefined })\n        await Util.assertions.decoding.succeed(schema, { c: undefined }, { b: undefined })\n        await Util.assertions.decoding.succeed(schema, { a: \"a\" })\n        await Util.assertions.decoding.succeed(schema, { c: \"b\" }, { b: \"b\" })\n        await Util.assertions.decoding.succeed(schema, { a: undefined, c: undefined }, { a: undefined, b: undefined })\n        await Util.assertions.decoding.succeed(schema, { a: \"a\", c: undefined }, { a: \"a\", b: undefined })\n        await Util.assertions.decoding.succeed(schema, { a: undefined, c: \"b\" }, { a: undefined, b: \"b\" })\n        await Util.assertions.decoding.succeed(schema, { a: \"a\", c: \"b\" }, { a: \"a\", b: \"b\" })\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/partialWith.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual, throws } from \"@effect/vitest/utils\"\nimport { identity } from \"effect/Function\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"partialWith\", () => {\n  describe(\"{ exact: true }\", () => {\n    it(\"Struct\", async () => {\n      const schema = S.partialWith(S.Struct({ a: S.Number }), { exact: true })\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { a: 1 })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: undefined },\n        `{ readonly a?: number }\n└─ [\"a\"]\n   └─ Expected number, actual undefined`\n      )\n    })\n\n    it(\"Record\", async () => {\n      const schema = S.partialWith(S.Record({ key: S.String, value: S.NumberFromString }), { exact: true })\n      await Util.assertions.decoding.succeed(schema, {}, {})\n      await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n      await Util.assertions.decoding.succeed(schema, { a: undefined })\n    })\n\n    describe(\"Tuple\", () => {\n      it(\"e\", async () => {\n        const schema = S.partialWith(S.Tuple(S.NumberFromString), { exact: true })\n        await Util.assertions.decoding.succeed(schema, [\"1\"], [1])\n        await Util.assertions.decoding.succeed(schema, [], [])\n\n        await Util.assertions.decoding.fail(\n          schema,\n          [undefined],\n          `readonly [NumberFromString?]\n└─ [0]\n   └─ NumberFromString\n      └─ Encoded side transformation failure\n         └─ Expected string, actual undefined`\n        )\n      })\n\n      it(\"e + r\", async () => {\n        const schema = S.partialWith(S.Tuple([S.NumberFromString], S.NumberFromString), { exact: true })\n        await Util.assertions.decoding.succeed(schema, [\"1\"], [1])\n        await Util.assertions.decoding.succeed(schema, [], [])\n        await Util.assertions.decoding.succeed(schema, [\"1\", \"2\"], [1, 2])\n        await Util.assertions.decoding.succeed(schema, [\"1\", undefined], [1, undefined])\n\n        await Util.assertions.decoding.fail(\n          schema,\n          [undefined],\n          `readonly [NumberFromString?, ...(NumberFromString | undefined)[]]\n└─ [0]\n   └─ NumberFromString\n      └─ Encoded side transformation failure\n         └─ Expected string, actual undefined`\n        )\n      })\n    })\n\n    it(\"Array\", async () => {\n      const schema = S.partialWith(S.Array(S.Number), { exact: true })\n      await Util.assertions.decoding.succeed(schema, [])\n      await Util.assertions.decoding.succeed(schema, [1])\n      await Util.assertions.decoding.succeed(schema, [undefined])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\"],\n        `ReadonlyArray<number | undefined>\n└─ [0]\n   └─ number | undefined\n      ├─ Expected number, actual \"a\"\n      └─ Expected undefined, actual \"a\"`\n      )\n    })\n\n    it(\"Union\", async () => {\n      const schema = S.partialWith(S.Union(S.Array(S.Number), S.String), { exact: true })\n      await Util.assertions.decoding.succeed(schema, \"a\")\n      await Util.assertions.decoding.succeed(schema, [])\n      await Util.assertions.decoding.succeed(schema, [1])\n      await Util.assertions.decoding.succeed(schema, [undefined])\n\n      await Util.assertions.decoding.fail(\n        schema,\n        [\"a\"],\n        `ReadonlyArray<number | undefined> | string\n├─ ReadonlyArray<number | undefined>\n│  └─ [0]\n│     └─ number | undefined\n│        ├─ Expected number, actual \"a\"\n│        └─ Expected undefined, actual \"a\"\n└─ Expected string, actual [\"a\"]`\n      )\n    })\n\n    it(\"suspend\", async () => {\n      interface A {\n        readonly a?: null | A\n      }\n      const schema: S.Schema<A> = S.partialWith(\n        S.suspend( // intended outer suspend\n          () =>\n            S.Struct({\n              a: S.Union(schema, S.Null)\n            })\n        ),\n        { exact: true }\n      )\n      await Util.assertions.decoding.succeed(schema, {})\n      await Util.assertions.decoding.succeed(schema, { a: null })\n      await Util.assertions.decoding.succeed(schema, { a: {} })\n      await Util.assertions.decoding.succeed(schema, { a: { a: null } })\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1 },\n        `{ readonly a?: <suspended schema> | null }\n└─ [\"a\"]\n   └─ <suspended schema> | null\n      ├─ Expected { readonly a?: <suspended schema> | null }, actual 1\n      └─ Expected null, actual 1`\n      )\n    })\n  })\n\n  describe(\"unsupported schemas\", () => {\n    it(\"declarations should throw\", () => {\n      throws(\n        () => S.partialWith(S.OptionFromSelf(S.String), { exact: true }),\n        new Error(`Unsupported schema\nschema (Declaration): Option<string>`)\n      )\n    })\n\n    it(\"refinements should throw\", () => {\n      throws(\n        () => S.partialWith(S.String.pipe(S.minLength(2)), { exact: true }),\n        new Error(`Unsupported schema\nschema (Refinement): minLength(2)`)\n      )\n    })\n\n    describe(\"Transformation\", () => {\n      it(\"should support property key renamings\", async () => {\n        const original = S.Struct({\n          a: S.String,\n          b: S.propertySignature(S.String).pipe(S.fromKey(\"c\"))\n        })\n        const schema = S.partialWith(original, { exact: true })\n        strictEqual(\n          S.format(schema),\n          \"({ readonly a?: string; readonly c?: string } <-> { readonly a?: string; readonly b?: string })\"\n        )\n        await Util.assertions.decoding.succeed(schema, {})\n        await Util.assertions.decoding.succeed(schema, { a: \"a\" })\n        await Util.assertions.decoding.succeed(schema, { c: \"b\" }, { b: \"b\" })\n        await Util.assertions.decoding.succeed(schema, { a: \"a\", c: \"b\" }, { a: \"a\", b: \"b\" })\n      })\n\n      it(\"transformations should throw\", () => {\n        throws(\n          () =>\n            S.partialWith(S.transform(S.String, S.String, { strict: true, decode: identity, encode: identity }), {\n              exact: true\n            }),\n          new Error(`Unsupported schema\nschema (Transformation): (string <-> string)`)\n        )\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/pick.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, doesNotThrow, strictEqual } from \"@effect/vitest/utils\"\nimport { Schema as S, SchemaAST as AST } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"pick\", () => {\n  it(\"Refinement\", () => {\n    const schema = S.Struct({ a: S.NumberFromString, b: S.Number }).pipe(S.filter(() => true))\n    const picked = schema.pipe(S.pick(\"a\"))\n    Util.assertions.ast.equals(picked, S.Struct({ a: S.NumberFromString }))\n  })\n\n  describe(\"Struct\", () => {\n    it(\"required properties\", () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const schema = S.Struct({ [a]: S.String, b: S.NumberFromString, c: S.Boolean })\n      const picked = schema.pipe(S.pick(a, \"b\"))\n      Util.assertions.ast.equals(picked, S.Struct({ [a]: S.String, b: S.NumberFromString }))\n    })\n\n    it(\"optional property (exact)\", () => {\n      const schema = S.Struct({\n        a: S.optionalWith(S.String, { exact: true }),\n        b: S.NumberFromString,\n        c: S.Boolean\n      })\n      const picked = schema.pipe(S.pick(\"a\", \"b\"))\n      Util.assertions.ast.equals(\n        picked,\n        S.Struct({ a: S.optionalWith(S.String, { exact: true }), b: S.NumberFromString })\n      )\n    })\n  })\n\n  it(\"Struct & Record\", () => {\n    const schema = S.Struct(\n      { a: S.NumberFromString, b: S.Number },\n      S.Record({ key: S.String, value: S.Union(S.String, S.Number) })\n    )\n    const picked = schema.pipe(S.pick(\"a\", \"c\"))\n    Util.assertions.ast.equals(picked, S.Struct({ a: S.NumberFromString, c: S.Union(S.String, S.Number) }))\n  })\n\n  describe(\"Record\", () => {\n    it(\"Record(string, number)\", () => {\n      const schema = S.Record({ key: S.String, value: S.Number })\n      const picked = schema.pipe(S.pick(\"a\", \"b\"))\n      Util.assertions.ast.equals(picked, S.Struct({ a: S.Number, b: S.Number }))\n    })\n\n    it(\"Record(symbol, number)\", () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const b = Symbol.for(\"effect/Schema/test/b\")\n      const schema = S.Record({ key: S.SymbolFromSelf, value: S.Number })\n      const picked = schema.pipe(S.pick(a, b))\n      Util.assertions.ast.equals(picked, S.Struct({ [a]: S.Number, [b]: S.Number }))\n    })\n\n    it(\"Record(string, string) & Record(`a${string}`, number)\", async () => {\n      const schema = S.Struct(\n        {},\n        S.Record({ key: S.String, value: S.Union(S.String, S.Number) }),\n        S.Record({ key: S.TemplateLiteral(S.Literal(\"a\"), S.String), value: S.Number })\n      )\n      const picked = schema.pipe(S.pick(\"a\", \"b\"))\n      Util.assertions.ast.equals(picked, S.Struct({ a: S.Number, b: S.Union(S.String, S.Number) }))\n    })\n  })\n\n  it(\"Union\", () => {\n    const A = S.Struct({ a: S.String, b: S.Number })\n    const B = S.Struct({ a: S.Number, b: S.String })\n    const schema = S.Union(A, B)\n    const picked = schema.pipe(S.pick(\"a\"))\n    Util.assertions.ast.equals(picked, S.Struct({ a: S.Union(S.String, S.Number) }))\n  })\n\n  it(\"suspend\", async () => {\n    interface A {\n      readonly a: string\n      readonly as: ReadonlyArray<A>\n    }\n    const schema: S.Schema<A> = S.suspend( // intended outer suspend\n      () =>\n        S.Struct({\n          a: S.String,\n          as: S.Array(schema)\n        }).annotations({ identifier: \"A\" })\n    )\n    const picked = schema.pipe(S.pick(\"as\"))\n    strictEqual(String(picked), \"{ readonly as: ReadonlyArray<A> }\")\n    await Util.assertions.decoding.succeed(picked, { as: [] })\n    await Util.assertions.decoding.succeed(picked, { as: [{ a: \"a\", as: [] }] })\n\n    await Util.assertions.decoding.fail(\n      picked,\n      { as: [{ as: [] }] },\n      `{ readonly as: ReadonlyArray<A> }\n└─ [\"as\"]\n   └─ ReadonlyArray<A>\n      └─ [0]\n         └─ A\n            └─ [\"a\"]\n               └─ is missing`\n    )\n  })\n\n  describe(\"Transformation\", () => {\n    it(\"ComposeTransformation\", () => {\n      const schema = S.compose(\n        S.Struct({ a: S.NumberFromString, b: S.Number }),\n        S.Struct({ a: S.Number, b: S.Number })\n      )\n      const picked = schema.pipe(S.pick(\"a\"))\n      Util.assertions.ast.equals(picked, S.compose(S.Struct({ a: S.NumberFromString }), S.Struct({ a: S.Number })))\n    })\n\n    describe(\"TypeLiteralTransformation\", () => {\n      it(\"picking keys with associated PropertySignatureTransformations\", () => {\n        const schema = S.Struct({ a: S.optionalWith(S.NumberFromString, { default: () => 0 }), b: S.Number })\n        const picked = schema.pipe(S.pick(\"a\"))\n        const ast = picked.ast\n        assertTrue(AST.isTransformation(ast))\n        deepStrictEqual(ast.from, S.Struct({ a: S.optional(S.NumberFromString) }).ast)\n        deepStrictEqual(ast.to, S.Struct({ a: S.Number }).ast)\n        assertTrue(AST.isTransformation(schema.ast))\n        deepStrictEqual(ast.transformation, schema.ast.transformation)\n        doesNotThrow(() => picked.pipe(S.extend(S.Struct({ c: S.Boolean }))))\n      })\n\n      it(\"picking keys without associated PropertySignatureTransformations\", () => {\n        const schema = S.Struct({ a: S.optionalWith(S.NumberFromString, { default: () => 0 }), b: S.NumberFromString })\n        const picked = schema.pipe(S.pick(\"b\"))\n        const ast = picked.ast\n        assertTrue(AST.isTypeLiteral(ast))\n        deepStrictEqual(ast.propertySignatures, [\n          new AST.PropertySignature(\"b\", S.NumberFromString.ast, false, true)\n        ])\n        doesNotThrow(() => picked.pipe(S.extend(S.Struct({ c: S.Boolean }))))\n      })\n    })\n\n    describe(\"SurrogateAnnotation\", () => {\n      it(\"a single Class\", () => {\n        class A extends S.Class<A>(\"A\")({ a: S.NumberFromString, b: S.Number }) {}\n        const schema = A\n        const picked = schema.pipe(S.pick(\"a\"))\n        Util.assertions.ast.equals(picked, S.Struct({ a: S.NumberFromString }))\n      })\n\n      it(\"a union of Classes\", () => {\n        class A extends S.Class<A>(\"A\")({ a: S.Number, b: S.String }) {}\n        class B extends S.Class<B>(\"B\")({ a: S.String, b: S.Number }) {}\n        const schema = S.Union(A, B)\n        const picked = schema.pipe(S.pick(\"a\"))\n        Util.assertions.ast.equals(picked, S.Struct({ a: S.Union(S.Number, S.String) }))\n      })\n    })\n  })\n\n  it(\"typeSchema(Class)\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String, b: S.NumberFromString }) {}\n    const schema = A\n    const picked = schema.pipe(S.typeSchema, S.pick(\"b\"))\n    Util.assertions.ast.equals(picked, S.Struct({ b: S.Number }))\n  })\n\n  it(\"Class\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String, b: S.NumberFromString }) {}\n    const schema = A\n    const picked = schema.pipe(S.pick(\"b\"))\n    Util.assertions.ast.equals(picked, S.Struct({ b: S.NumberFromString }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/pickLiteral.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"pickLiteral\", () => {\n  it(\"should return an unwrapped AST with exactly one literal\", () => {\n    deepStrictEqual(S.Literal(\"a\").pipe(S.pickLiteral(\"a\")).ast, new AST.Literal(\"a\"))\n  })\n\n  it(\"should return a union with more than one literal\", () => {\n    deepStrictEqual(\n      S.Literal(\"a\", \"b\", \"c\").pipe(S.pickLiteral(\"a\", \"b\")).ast,\n      AST.Union.make([new AST.Literal(\"a\"), new AST.Literal(\"b\")])\n    )\n  })\n\n  describe(\"decoding\", () => {\n    it(\"1 member\", async () => {\n      const schema = S.Literal(\"a\").pipe(S.pickLiteral(\"a\"))\n      await Util.assertions.decoding.succeed(schema, \"a\")\n\n      await Util.assertions.decoding.fail(schema, 1, `Expected \"a\", actual 1`)\n      await Util.assertions.decoding.fail(schema, null, `Expected \"a\", actual null`)\n    })\n\n    it(\"2 members\", async () => {\n      const schema = S.Literal(\"a\", \"b\", \"c\").pipe(S.pickLiteral(\"a\", \"b\"))\n\n      await Util.assertions.decoding.succeed(schema, \"a\")\n      await Util.assertions.decoding.succeed(schema, \"b\")\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `\"a\" | \"b\"\n├─ Expected \"a\", actual null\n└─ Expected \"b\", actual null`\n      )\n    })\n  })\n\n  it(\"encoding\", async () => {\n    const schema = S.Literal(null).pipe(S.pickLiteral(null))\n    await Util.assertions.encoding.succeed(schema, null, null)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/pipe.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"pipe\", () => {\n  it(\"schemas should be pipeable\", () => {\n    const int = <A extends number, I>(self: S.Schema<A, I>) => self.pipe(S.int(), S.brand(\"Int\"))\n\n    const positive = <A extends number, I>(self: S.Schema<A, I>) => self.pipe(S.positive(), S.brand(\"Positive\"))\n\n    const PositiveInt = S.NumberFromString.pipe(int, positive)\n\n    const is = S.is(PositiveInt)\n    assertTrue(is(1))\n    assertFalse(is(-1))\n    assertFalse(is(1.2))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/pluck.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"pluck\", () => {\n  describe(\"decoding\", () => {\n    it(\"struct (string keys)\", async () => {\n      const origin = S.Struct({ a: S.String, b: S.NumberFromString })\n      const schema = S.pluck(origin, \"a\")\n      await Util.assertions.decoding.succeed(schema, { a: \"a\", b: \"2\" }, \"a\")\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: 1, b: \"2\" },\n        `({ readonly a: string } <-> string)\n└─ Encoded side transformation failure\n   └─ { readonly a: string }\n      └─ [\"a\"]\n         └─ Expected string, actual 1`\n      )\n    })\n\n    it(\"struct (symbol keys)\", async () => {\n      const a = Symbol.for(\"effect/schema/test/a\")\n      const b = Symbol.for(\"effect/schema/test/b\")\n      const origin = S.Struct({ [a]: S.String, [b]: S.NumberFromString })\n      const schema = S.pluck(origin, a)\n      await Util.assertions.decoding.succeed(schema, { [a]: \"a\", [b]: \"2\" }, \"a\")\n      await Util.assertions.decoding.fail(\n        schema,\n        { [a]: 1, [b]: \"2\" },\n        `({ readonly Symbol(effect/schema/test/a): string } <-> string)\n└─ Encoded side transformation failure\n   └─ { readonly Symbol(effect/schema/test/a): string }\n      └─ [Symbol(effect/schema/test/a)]\n         └─ Expected string, actual 1`\n      )\n    })\n\n    it(\"struct with optional key\", async () => {\n      const origin = S.Struct({ a: S.optional(S.String), b: S.Number })\n      const schema = S.pluck(origin, \"a\")\n      await Util.assertions.decoding.succeed(schema, { b: 2 }, undefined)\n      await Util.assertions.decoding.succeed(schema, { a: undefined, b: 2 }, undefined)\n      await Util.assertions.decoding.succeed(schema, { a: \"a\", b: 2 }, \"a\")\n    })\n\n    it(\"union\", async () => {\n      const origin = S.Union(S.Struct({ _tag: S.Literal(\"A\") }), S.Struct({ _tag: S.Literal(\"B\") }))\n      const schema = S.pluck(origin, \"_tag\")\n      await Util.assertions.decoding.succeed(schema, { _tag: \"A\" }, \"A\")\n      await Util.assertions.decoding.succeed(schema, { _tag: \"B\" }, \"B\")\n      await Util.assertions.decoding.fail(\n        schema,\n        {},\n        `({ readonly _tag: \"A\" | \"B\" } <-> \"A\" | \"B\")\n└─ Encoded side transformation failure\n   └─ { readonly _tag: \"A\" | \"B\" }\n      └─ [\"_tag\"]\n         └─ is missing`\n      )\n    })\n  })\n\n  describe(\"encoding\", () => {\n    it(\"struct (string keys)\", async () => {\n      const origin = S.Struct({ a: S.NonEmptyString })\n      const schema = S.pluck(origin, \"a\")\n      await Util.assertions.encoding.succeed(schema, \"a\", { a: \"a\" })\n      await Util.assertions.encoding.fail(\n        schema,\n        \"\",\n        `({ readonly a: NonEmptyString } <-> NonEmptyString)\n└─ Type side transformation failure\n   └─ NonEmptyString\n      └─ Predicate refinement failure\n         └─ Expected a non empty string, actual \"\"`\n      )\n    })\n\n    it(\"struct (symbol keys)\", async () => {\n      const a = Symbol.for(\"effect/schema/test/a\")\n      const origin = S.Struct({ [a]: S.NonEmptyString })\n      const schema = S.pluck(origin, a)\n      await Util.assertions.encoding.succeed(schema, \"a\", { [a]: \"a\" })\n      await Util.assertions.encoding.fail(\n        schema,\n        \"\",\n        `({ readonly Symbol(effect/schema/test/a): NonEmptyString } <-> NonEmptyString)\n└─ Type side transformation failure\n   └─ NonEmptyString\n      └─ Predicate refinement failure\n         └─ Expected a non empty string, actual \"\"`\n      )\n    })\n  })\n\n  it(\"struct with optional key\", async () => {\n    const origin = S.Struct({ a: S.optional(S.String) })\n    const schema = S.pluck(origin, \"a\")\n    await Util.assertions.encoding.succeed(schema, undefined, {})\n    await Util.assertions.encoding.succeed(schema, \"a\", { a: \"a\" })\n  })\n\n  it(\"struct with exact optional key\", async () => {\n    const origin = S.Struct({ a: S.optionalWith(S.String, { exact: true }) })\n    const schema = S.pluck(origin, \"a\")\n    await Util.assertions.encoding.succeed(schema, undefined, {})\n    await Util.assertions.encoding.succeed(schema, \"a\", { a: \"a\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/rename.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"rename\", () => {\n  describe(\"Struct\", () => {\n    it(\"from string key to string key\", async () => {\n      const schema = S.Struct({ a: S.String, b: S.Number })\n      const renamed = S.rename(schema, { a: \"c\" })\n\n      await Util.assertions.decoding.succeed(renamed, { a: \"a\", b: 1 }, { c: \"a\", b: 1 })\n      await Util.assertions.encoding.succeed(renamed, { c: \"a\", b: 1 }, { a: \"a\", b: 1 })\n    })\n\n    it(\"from string key to symbol key\", async () => {\n      const c = Symbol.for(\"effect/Schema/test/c\")\n      const schema = S.Struct({ a: S.String, b: S.Number })\n      const renamed = S.rename(schema, { a: c })\n\n      await Util.assertions.decoding.succeed(renamed, { a: \"a\", b: 1 }, { [c]: \"a\", b: 1 })\n      await Util.assertions.encoding.succeed(renamed, { [c]: \"a\", b: 1 }, { a: \"a\", b: 1 })\n    })\n\n    it(\"from symbol key to string key\", async () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const schema = S.Struct({ [a]: S.String, b: S.Number })\n      const renamed = S.rename(schema, { [a]: \"c\" })\n\n      await Util.assertions.decoding.succeed(renamed, { [a]: \"a\", b: 1 }, { c: \"a\", b: 1 })\n      await Util.assertions.encoding.succeed(renamed, { c: \"a\", b: 1 }, { [a]: \"a\", b: 1 })\n    })\n\n    it(\"from symbol key to symbol key\", async () => {\n      const a = Symbol.for(\"effect/Schema/test/a\")\n      const c = Symbol.for(\"effect/Schema/test/c\")\n      const schema = S.Struct({ [a]: S.String, b: S.Number })\n      const renamed = S.rename(schema, { [a]: c })\n\n      await Util.assertions.decoding.succeed(renamed, { [a]: \"a\", b: 1 }, { [c]: \"a\", b: 1 })\n      await Util.assertions.encoding.succeed(renamed, { [c]: \"a\", b: 1 }, { [a]: \"a\", b: 1 })\n    })\n  })\n\n  it(\"Transform (renaming twice)\", async () => {\n    const schema = S.Struct({ a: S.String, b: S.Number })\n    const renamed = S.rename(schema, { a: \"c\" })\n    const renamed2 = S.rename(renamed, { c: \"d\" })\n\n    await Util.assertions.decoding.succeed(renamed2, { a: \"a\", b: 1 }, { d: \"a\", b: 1 })\n    await Util.assertions.encoding.succeed(renamed2, { d: \"a\", b: 1 }, { a: \"a\", b: 1 })\n  })\n\n  it(\"suspend\", async () => {\n    interface A {\n      readonly a: string\n      readonly as: ReadonlyArray<A>\n    }\n    const schema: S.Schema<A> = S.suspend( // intended outer suspend\n      () =>\n        S.Struct({\n          a: S.String,\n          as: S.Array(schema)\n        })\n    )\n    const renamed = S.rename(schema, { a: \"c\" })\n\n    await Util.assertions.decoding.succeed(renamed, { a: \"a1\", as: [{ a: \"a2\", as: [] }] }, {\n      c: \"a1\",\n      as: [{ a: \"a2\", as: [] }]\n    })\n    await Util.assertions.encoding.succeed(renamed, {\n      c: \"a1\",\n      as: [{ a: \"a2\", as: [] }]\n    }, { a: \"a1\", as: [{ a: \"a2\", as: [] }] })\n  })\n\n  it(\"pipe\", async () => {\n    const renamed = S.Struct({ a: S.String, b: S.Number }).pipe(\n      S.rename({ a: \"c\" })\n    )\n\n    await Util.assertions.decoding.succeed(renamed, { a: \"a\", b: 1 }, { c: \"a\", b: 1 })\n    await Util.assertions.encoding.succeed(renamed, { c: \"a\", b: 1 }, { a: \"a\", b: 1 })\n  })\n\n  it(\"should return the same ast if there are no mappings\", () => {\n    const schema = S.Struct({ a: S.String })\n    const renamed = S.rename(schema, {})\n    strictEqual(schema.ast, renamed.ast)\n  })\n\n  it(\"field transformation\", async () => {\n    const schema = S.Struct({ a: S.String, b: S.NumberFromString })\n    const renamed = S.rename(schema, { a: \"c\" })\n\n    await Util.assertions.decoding.succeed(renamed, { a: \"a\", b: \"1\" }, { c: \"a\", b: 1 })\n    await Util.assertions.encoding.succeed(renamed, { c: \"a\", b: 1 }, { a: \"a\", b: \"1\" })\n  })\n\n  it(\"union\", async () => {\n    const A = S.Struct({\n      ab: S.Number\n    })\n\n    const B = S.Struct({\n      ab: S.Null\n    })\n\n    const schema = S.Union(\n      A.pipe(S.attachPropertySignature(\"kind\", \"A\")),\n      B.pipe(S.attachPropertySignature(\"kind\", \"B\"))\n    )\n    const renamed = schema.pipe(S.rename({ ab: \"c\" }))\n    await Util.assertions.decoding.succeed(renamed, { ab: 1 }, { kind: \"A\", c: 1 })\n    await Util.assertions.decoding.succeed(renamed, { ab: null }, { kind: \"B\", c: null })\n\n    await Util.assertions.encoding.succeed(renamed, { kind: \"A\", c: 1 }, { ab: 1 })\n    await Util.assertions.encoding.succeed(renamed, { kind: \"B\", c: null }, { ab: null })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/required.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual, throws } from \"@effect/vitest/utils\"\nimport { identity } from \"effect/Function\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"required\", () => {\n  it(\"string\", () => {\n    strictEqual(S.required(S.String).ast, S.String.ast)\n  })\n\n  it(\"Struct\", async () => {\n    const schema = S.required(S.Struct({\n      a: S.optionalWith(S.NumberFromString.pipe(S.greaterThan(0)), { exact: true })\n    }))\n\n    await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1 })\n    await Util.assertions.decoding.fail(\n      schema,\n      {},\n      `{ readonly a: greaterThan(0) }\n└─ [\"a\"]\n   └─ is missing`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: \"-1\" },\n      `{ readonly a: greaterThan(0) }\n└─ [\"a\"]\n   └─ greaterThan(0)\n      └─ Predicate refinement failure\n         └─ Expected a positive number, actual -1`\n    )\n  })\n\n  describe(\"Tuple\", () => {\n    it(\"e?\", async () => {\n      // type A = readonly [string?]\n      // type B = Required<A>\n\n      const A = S.Tuple(S.optionalElement(S.NumberFromString))\n      const B = S.required(A)\n\n      await Util.assertions.decoding.succeed(B, [\"1\"], [1])\n      await Util.assertions.decoding.fail(\n        B,\n        [],\n        `readonly [NumberFromString]\n└─ [0]\n   └─ is missing`\n      )\n    })\n\n    it(\"e e?\", async () => {\n      // type A = readonly [number, string?]\n      // type B = Required<A>\n\n      const A = S.Tuple(S.NumberFromString, S.optionalElement(S.String))\n      const B = S.required(A)\n\n      await Util.assertions.decoding.succeed(B, [\"0\", \"\"], [0, \"\"])\n      await Util.assertions.decoding.fail(\n        B,\n        [\"0\"],\n        `readonly [NumberFromString, string]\n└─ [1]\n   └─ is missing`\n      )\n    })\n\n    it(\"e r e\", async () => {\n      // type A = readonly [string, ...Array<number>, boolean]\n      // type B = Required<A> // readonly [string, ...number[], boolean]\n\n      const A = S.Tuple([S.String], S.Number, S.Boolean)\n      const B = S.required(A)\n\n      await Util.assertions.decoding.succeed(B, [\"\", true], [\"\", true])\n      await Util.assertions.decoding.succeed(B, [\"\", 0, true])\n      await Util.assertions.decoding.succeed(B, [\"\", 0, 1, true])\n\n      await Util.assertions.decoding.fail(\n        B,\n        [],\n        `readonly [string, ...number[], boolean]\n└─ [0]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        B,\n        [\"\"],\n        `readonly [string, ...number[], boolean]\n└─ [1]\n   └─ is missing`\n      )\n    })\n\n    it(\"e r e e\", async () => {\n      // type A = readonly [string, ...Array<number>, boolean, boolean]\n      // type B = Required<A> // readonly [string, ...number[], boolean, boolean]\n\n      const A = S.Tuple([S.String], S.Number, S.Boolean, S.Boolean)\n      const B = S.required(A)\n\n      await Util.assertions.decoding.succeed(B, [\"\", 0, true, false])\n      await Util.assertions.decoding.succeed(B, [\"\", 0, 1, 2, 3, true, false])\n\n      await Util.assertions.decoding.fail(\n        B,\n        [],\n        `readonly [string, ...number[], boolean, boolean]\n└─ [0]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        B,\n        [\"\"],\n        `readonly [string, ...number[], boolean, boolean]\n└─ [1]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        B,\n        [\"\", true],\n        `readonly [string, ...number[], boolean, boolean]\n└─ [2]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        B,\n        [\"\", 0, true],\n        `readonly [string, ...number[], boolean, boolean]\n└─ [1]\n   └─ Expected boolean, actual 0`\n      )\n    })\n  })\n\n  it(\"Union\", async () => {\n    const schema = S.required(S.Union(\n      S.Struct({ a: S.optionalWith(S.String, { exact: true }) }),\n      S.Struct({ b: S.optionalWith(S.Number, { exact: true }) })\n    ))\n    await Util.assertions.decoding.succeed(schema, { a: \"a\" })\n    await Util.assertions.decoding.succeed(schema, { b: 1 })\n    await Util.assertions.decoding.fail(\n      schema,\n      {},\n      `{ readonly a: string } | { readonly b: number }\n├─ { readonly a: string }\n│  └─ [\"a\"]\n│     └─ is missing\n└─ { readonly b: number }\n   └─ [\"b\"]\n      └─ is missing`\n    )\n  })\n\n  it(\"suspend\", async () => {\n    interface A {\n      readonly a: null | A\n    }\n    const schema: S.Schema<A> = S.required(S.suspend( // intended outer suspend\n      () =>\n        S.Struct({\n          a: S.optionalWith(S.Union(schema, S.Null), { exact: true })\n        })\n    ))\n    await Util.assertions.decoding.succeed(schema, { a: null })\n    await Util.assertions.decoding.succeed(schema, { a: { a: null } })\n    await Util.assertions.decoding.fail(\n      schema,\n      {},\n      `{ readonly a: <suspended schema> | null }\n└─ [\"a\"]\n   └─ is missing`\n    )\n    await Util.assertions.decoding.fail(\n      schema,\n      { a: {} },\n      `{ readonly a: <suspended schema> | null }\n└─ [\"a\"]\n   └─ <suspended schema> | null\n      ├─ { readonly a: <suspended schema> | null }\n      │  └─ [\"a\"]\n      │     └─ is missing\n      └─ Expected null, actual {}`\n    )\n  })\n\n  describe(\"unsupported schemas\", () => {\n    it(\"declarations should throw\", async () => {\n      throws(\n        () => S.required(S.OptionFromSelf(S.String)),\n        new Error(`Unsupported schema\nschema (Declaration): Option<string>`)\n      )\n    })\n\n    it(\"refinements should throw\", async () => {\n      throws(\n        () => S.required(S.String.pipe(S.minLength(2))),\n        new Error(`Unsupported schema\nschema (Refinement): minLength(2)`)\n      )\n    })\n\n    describe(\"Transformation\", () => {\n      it(\"should support property key renamings\", () => {\n        const original = S.Struct({\n          a: S.String,\n          b: S.propertySignature(S.String).pipe(S.fromKey(\"c\"))\n        })\n        const schema = S.required(S.partial(original))\n        strictEqual(\n          S.format(schema),\n          \"({ readonly a: string | undefined; readonly c: string | undefined } <-> { readonly a: string | undefined; readonly b: string | undefined })\"\n        )\n      })\n\n      it(\"transformations should throw\", async () => {\n        throws(\n          () => S.required(S.transform(S.String, S.String, { strict: true, decode: identity, encode: identity })),\n          new Error(`Unsupported schema\nschema (Transformation): (string <-> string)`)\n        )\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/requiredToOptional.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Option from \"effect/Option\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"requiredToOptional\", () => {\n  it(\"two transformation schemas\", async () => {\n    const ps = S.requiredToOptional(\n      S.NumberFromString,\n      S.BigIntFromNumber,\n      { decode: Option.liftPredicate((n) => n !== 0), encode: Option.getOrElse(() => 0) }\n    )\n    const schema = S.Struct({ a: ps })\n    await Util.assertions.decoding.succeed(schema, { a: \"0\" }, {})\n    await Util.assertions.decoding.succeed(schema, { a: \"1\" }, { a: 1n })\n\n    await Util.assertions.encoding.succeed(schema, {}, { a: \"0\" })\n    await Util.assertions.encoding.succeed(schema, { a: 1n }, { a: \"1\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/standardSchemaV1.test.ts",
    "content": "import { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\nimport { Context, Effect, ParseResult, Predicate, Schema } from \"effect\"\nimport { describe, it } from \"vitest\"\nimport { AsyncString } from \"../TestUtils.js\"\n\nfunction validate<I, A>(\n  schema: StandardSchemaV1<I, A>,\n  input: unknown\n): StandardSchemaV1.Result<A> | Promise<StandardSchemaV1.Result<A>> {\n  return schema[\"~standard\"].validate(input)\n}\n\nconst isPromise = (value: unknown): value is Promise<unknown> => value instanceof Promise\n\nconst expectSuccess = async <A>(\n  result: StandardSchemaV1.Result<A>,\n  a: A\n) => {\n  deepStrictEqual(result, { value: a })\n}\n\nconst expectFailure = async <A>(\n  result: StandardSchemaV1.Result<A>,\n  issues: ReadonlyArray<StandardSchemaV1.Issue> | ((issues: ReadonlyArray<StandardSchemaV1.Issue>) => void)\n) => {\n  if (result.issues !== undefined) {\n    if (Predicate.isFunction(issues)) {\n      issues(result.issues)\n    } else {\n      deepStrictEqual(result.issues, issues)\n    }\n  } else {\n    throw new Error(\"Expected issues, got undefined\")\n  }\n}\n\nconst expectSyncSuccess = <I, A>(\n  schema: StandardSchemaV1<I, A>,\n  input: unknown,\n  a: A\n) => {\n  const result = validate(schema, input)\n  if (isPromise(result)) {\n    throw new Error(\"Expected value, got promise\")\n  } else {\n    expectSuccess(result, a)\n  }\n}\n\nconst expectAsyncSuccess = async <I, A>(\n  schema: StandardSchemaV1<I, A>,\n  input: unknown,\n  a: A\n) => {\n  const result = validate(schema, input)\n  if (isPromise(result)) {\n    expectSuccess(await result, a)\n  } else {\n    throw new Error(\"Expected promise, got value\")\n  }\n}\n\nconst expectSyncFailure = <I, A>(\n  schema: StandardSchemaV1<I, A>,\n  input: unknown,\n  issues: ReadonlyArray<StandardSchemaV1.Issue> | ((issues: ReadonlyArray<StandardSchemaV1.Issue>) => void)\n) => {\n  const result = validate(schema, input)\n  if (isPromise(result)) {\n    throw new Error(\"Expected value, got promise\")\n  } else {\n    expectFailure(result, issues)\n  }\n}\n\nconst expectAsyncFailure = async <I, A>(\n  schema: StandardSchemaV1<I, A>,\n  input: unknown,\n  issues: ReadonlyArray<StandardSchemaV1.Issue> | ((issues: ReadonlyArray<StandardSchemaV1.Issue>) => void)\n) => {\n  const result = validate(schema, input)\n  if (isPromise(result)) {\n    expectFailure(await result, issues)\n  } else {\n    throw new Error(\"Expected promise, got value\")\n  }\n}\n\nconst AsyncNonEmptyString = AsyncString.pipe(Schema.minLength(1))\n\ndescribe(\"standardSchemaV1\", () => {\n  it(\"should return a schema\", () => {\n    const schema = Schema.NumberFromString\n    const standardSchema = Schema.standardSchemaV1(schema)\n    assertTrue(Schema.isSchema(standardSchema))\n  })\n\n  it(\"sync decoding + sync issue formatting\", () => {\n    const schema = Schema.NonEmptyString\n    const standardSchema = Schema.standardSchemaV1(schema)\n    expectSyncSuccess(standardSchema, \"a\", \"a\")\n    expectSyncFailure(standardSchema, null, [\n      {\n        message: \"Expected string, actual null\",\n        path: []\n      }\n    ])\n    expectSyncFailure(standardSchema, \"\", [\n      {\n        message: `Expected a non empty string, actual \"\"`,\n        path: []\n      }\n    ])\n  })\n\n  it(\"sync decoding + sync custom message\", () => {\n    const schema = Schema.NonEmptyString.annotations({ message: () => Effect.succeed(\"my message\") })\n    const standardSchema = Schema.standardSchemaV1(schema)\n    expectSyncSuccess(standardSchema, \"a\", \"a\")\n    expectSyncFailure(standardSchema, null, [\n      {\n        message: \"Expected string, actual null\",\n        path: []\n      }\n    ])\n    expectSyncFailure(standardSchema, \"\", [\n      {\n        message: \"my message\",\n        path: []\n      }\n    ])\n  })\n\n  it(\"sync decoding + async custom message\", async () => {\n    const schema = Schema.NonEmptyString.annotations({\n      message: () => Effect.succeed(\"my message\").pipe(Effect.delay(\"10 millis\"))\n    })\n    const standardSchema = Schema.standardSchemaV1(schema)\n    expectSyncSuccess(standardSchema, \"a\", \"a\")\n    await expectAsyncFailure(standardSchema, null, [\n      {\n        message: \"Expected string, actual null\",\n        path: []\n      }\n    ])\n    await expectAsyncFailure(standardSchema, \"\", [\n      {\n        message: \"my message\",\n        path: []\n      }\n    ])\n  })\n\n  it(\"async decoding + sync issue formatting\", async () => {\n    const schema = AsyncNonEmptyString\n    const standardSchema = Schema.standardSchemaV1(schema)\n    await expectAsyncSuccess(standardSchema, \"a\", \"a\")\n    expectSyncFailure(standardSchema, null, [\n      {\n        message: \"Expected string, actual null\",\n        path: []\n      }\n    ])\n    await expectAsyncFailure(standardSchema, \"\", [\n      {\n        message: `Expected a string at least 1 character(s) long, actual \"\"`,\n        path: []\n      }\n    ])\n  })\n\n  it(\"async decoding + sync custom message\", async () => {\n    const schema = AsyncNonEmptyString.annotations({ message: () => Effect.succeed(\"my message\") })\n    const standardSchema = Schema.standardSchemaV1(schema)\n    await expectAsyncSuccess(standardSchema, \"a\", \"a\")\n    expectSyncFailure(standardSchema, null, [\n      {\n        message: \"Expected string, actual null\",\n        path: []\n      }\n    ])\n    await expectAsyncFailure(standardSchema, \"\", [\n      {\n        message: \"my message\",\n        path: []\n      }\n    ])\n  })\n\n  it(\"async decoding + async custom message\", async () => {\n    const schema = AsyncNonEmptyString.annotations({\n      message: () => Effect.succeed(\"my message\").pipe(Effect.delay(\"10 millis\"))\n    })\n    const standardSchema = Schema.standardSchemaV1(schema)\n    await expectAsyncSuccess(standardSchema, \"a\", \"a\")\n    await expectAsyncFailure(standardSchema, null, [\n      {\n        message: \"Expected string, actual null\",\n        path: []\n      }\n    ])\n    await expectAsyncFailure(standardSchema, \"\", [\n      {\n        message: \"my message\",\n        path: []\n      }\n    ])\n  })\n\n  describe(\"missing dependencies\", () => {\n    class MagicNumber extends Context.Tag(\"Min\")<MagicNumber, number>() {}\n\n    it(\"sync decoding should throw\", () => {\n      const DepString = Schema.transformOrFail(Schema.Number, Schema.Number, {\n        strict: true,\n        decode: (n) =>\n          Effect.gen(function*() {\n            const magicNumber = yield* MagicNumber\n            return n * magicNumber\n          }),\n        encode: ParseResult.succeed\n      })\n\n      const schema = DepString\n      const standardSchema = Schema.standardSchemaV1(schema as any)\n      expectSyncFailure(standardSchema, 1, (issues) => {\n        strictEqual(issues.length, 1)\n        deepStrictEqual(issues[0].path, undefined)\n        assertTrue(issues[0].message.includes(\"Service not found: Min\"))\n      })\n    })\n\n    it(\"async decoding should throw\", () => {\n      const DepString = Schema.transformOrFail(Schema.Number, Schema.Number, {\n        strict: true,\n        decode: (n) =>\n          Effect.gen(function*() {\n            const magicNumber = yield* MagicNumber\n            yield* Effect.sleep(\"10 millis\")\n            return n * magicNumber\n          }),\n        encode: ParseResult.succeed\n      })\n\n      const schema = DepString\n      const standardSchema = Schema.standardSchemaV1(schema as any)\n      expectSyncFailure(standardSchema, 1, (issues) => {\n        strictEqual(issues.length, 1)\n        deepStrictEqual(issues[0].path, undefined)\n        assertTrue(issues[0].message.includes(\"Service not found: Min\"))\n      })\n    })\n  })\n\n  it(\"sync decoding + sync all issues formatting\", () => {\n    const schema = Schema.Struct({\n      a: Schema.NonEmptyString,\n      b: Schema.NonEmptyString\n    })\n    const standardSchema = Schema.standardSchemaV1(schema)\n    expectSyncSuccess(standardSchema, {\n      a: \"a\",\n      b: \"b\"\n    }, {\n      a: \"a\",\n      b: \"b\"\n    })\n    expectSyncFailure(standardSchema, null, [\n      {\n        message: \"Expected { readonly a: NonEmptyString; readonly b: NonEmptyString }, actual null\",\n        path: []\n      }\n    ])\n    expectSyncFailure(standardSchema, \"\", [\n      {\n        message: `Expected { readonly a: NonEmptyString; readonly b: NonEmptyString }, actual \"\"`,\n        path: []\n      }\n    ])\n    expectSyncFailure(standardSchema, {\n      a: \"\",\n      b: \"\"\n    }, [\n      {\n        message: `Expected a non empty string, actual \"\"`,\n        path: [\"a\"]\n      },\n      {\n        message: `Expected a non empty string, actual \"\"`,\n        path: [\"b\"]\n      }\n    ])\n    expectSyncFailure(standardSchema, {\n      a: \"a\",\n      b: \"\"\n    }, [\n      {\n        message: `Expected a non empty string, actual \"\"`,\n        path: [\"b\"]\n      }\n    ])\n    expectSyncFailure(standardSchema, {\n      a: \"\",\n      b: \"b\"\n    }, [\n      {\n        message: `Expected a non empty string, actual \"\"`,\n        path: [\"a\"]\n      }\n    ])\n  })\n  it(\"sync decoding + sync first issue formatting\", () => {\n    const schema = Schema.Struct({\n      a: Schema.NonEmptyString,\n      b: Schema.NonEmptyString\n    })\n    const standardSchema = Schema.standardSchemaV1(schema, { errors: \"first\" })\n    expectSyncSuccess(standardSchema, {\n      a: \"a\",\n      b: \"b\"\n    }, {\n      a: \"a\",\n      b: \"b\"\n    })\n    expectSyncFailure(standardSchema, null, [\n      {\n        message: \"Expected { readonly a: NonEmptyString; readonly b: NonEmptyString }, actual null\",\n        path: []\n      }\n    ])\n    expectSyncFailure(standardSchema, \"\", [\n      {\n        message: `Expected { readonly a: NonEmptyString; readonly b: NonEmptyString }, actual \"\"`,\n        path: []\n      }\n    ])\n    expectSyncFailure(standardSchema, {\n      a: \"\",\n      b: \"\"\n    }, [\n      {\n        message: `Expected a non empty string, actual \"\"`,\n        path: [\"a\"]\n      }\n    ])\n    expectSyncFailure(standardSchema, {\n      a: \"a\",\n      b: \"\"\n    }, [\n      {\n        message: `Expected a non empty string, actual \"\"`,\n        path: [\"b\"]\n      }\n    ])\n    expectSyncFailure(standardSchema, {\n      a: \"\",\n      b: \"b\"\n    }, [\n      {\n        message: `Expected a non empty string, actual \"\"`,\n        path: [\"a\"]\n      }\n    ])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/suspend.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"suspend\", () => {\n  describe(\"toString\", () => {\n    it(\"outer suspend\", () => {\n      type A = readonly [number, A | null]\n      const schema: S.Schema<A> = S.suspend( // intended outer suspend\n        () => S.Tuple(S.Number, S.Union(schema, S.Literal(null)))\n      )\n      strictEqual(String(schema), \"<suspended schema>\")\n    })\n\n    it(\"should handle before initialization error\", () => {\n      const schema = S.suspend(() => string)\n      strictEqual(String(schema), \"<suspended schema>\")\n      const string = S.String\n    })\n  })\n\n  describe(\"decoding\", () => {\n    it(\"baseline\", async () => {\n      interface A {\n        readonly a: string\n        readonly as: ReadonlyArray<A>\n      }\n      const schema = S.Struct({\n        a: S.String,\n        as: S.Array(S.suspend((): S.Schema<A> => schema))\n      })\n\n      await Util.assertions.decoding.succeed(schema, { a: \"a1\", as: [] })\n      await Util.assertions.decoding.succeed(schema, { a: \"a1\", as: [{ a: \"a2\", as: [] }] })\n\n      await Util.assertions.decoding.fail(\n        schema,\n        null,\n        `Expected { readonly a: string; readonly as: ReadonlyArray<<suspended schema>> }, actual null`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a1\" },\n        `{ readonly a: string; readonly as: ReadonlyArray<<suspended schema>> }\n└─ [\"as\"]\n   └─ is missing`\n      )\n      await Util.assertions.decoding.fail(\n        schema,\n        { a: \"a1\", as: [{ a: \"a2\", as: [1] }] },\n        `{ readonly a: string; readonly as: ReadonlyArray<<suspended schema>> }\n└─ [\"as\"]\n   └─ ReadonlyArray<<suspended schema>>\n      └─ [0]\n         └─ { readonly a: string; readonly as: ReadonlyArray<<suspended schema>> }\n            └─ [\"as\"]\n               └─ ReadonlyArray<<suspended schema>>\n                  └─ [0]\n                     └─ Expected { readonly a: string; readonly as: ReadonlyArray<<suspended schema>> }, actual 1`\n      )\n    })\n\n    it(\"mutually suspended\", async () => {\n      interface Expression {\n        readonly type: \"expression\"\n        readonly value: number | Operation\n      }\n\n      interface Operation {\n        readonly type: \"operation\"\n        readonly operator: \"+\" | \"-\"\n        readonly left: Expression\n        readonly right: Expression\n      }\n\n      const Expression = S.Struct({\n        type: S.Literal(\"expression\"),\n        value: S.Union(S.Number, S.suspend((): S.Schema<Operation> => Operation))\n      })\n\n      const Operation = S.Struct({\n        type: S.Literal(\"operation\"),\n        operator: S.Union(S.Literal(\"+\"), S.Literal(\"-\")),\n        left: Expression,\n        right: Expression\n      })\n\n      const input = {\n        type: \"operation\",\n        operator: \"+\",\n        left: {\n          type: \"expression\",\n          value: {\n            type: \"operation\",\n            operator: \"-\",\n            left: {\n              type: \"expression\",\n              value: 2\n            },\n            right: {\n              type: \"expression\",\n              value: 3\n            }\n          }\n        },\n        right: {\n          type: \"expression\",\n          value: 1\n        }\n      }\n\n      await Util.assertions.decoding.succeed(Operation, input)\n    })\n  })\n\n  describe(\"encoding\", () => {\n    it(\"suspend\", async () => {\n      interface A {\n        readonly a: number\n        readonly as: ReadonlyArray<A>\n      }\n      interface FromA {\n        readonly a: string\n        readonly as: ReadonlyArray<FromA>\n      }\n      const schema = S.Struct({\n        a: Util.NumberFromChar,\n        as: S.Array(S.suspend((): S.Schema<A, FromA> => schema))\n      })\n      await Util.assertions.encoding.succeed(schema, { a: 1, as: [] }, { a: \"1\", as: [] })\n      await Util.assertions.encoding.succeed(schema, { a: 1, as: [{ a: 2, as: [] }] }, {\n        a: \"1\",\n        as: [{ a: \"2\", as: [] }]\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/transform.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Schema from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"transform\", () => {\n  it(\"should receive the fromI value other than the fromA value\", async () => {\n    const A = Schema.Struct({\n      a: Schema.NumberFromString\n    })\n\n    const B = Schema.Struct({\n      a: Schema.String,\n      b: Schema.NumberFromString\n    })\n\n    const AB = Schema.transform(B, A, {\n      strict: true,\n      decode: ({ a, b: _b }, i) => ({ a: a + i.b }),\n      encode: (i, a) => ({ ...i, b: a.a * 2 })\n    })\n\n    await Util.assertions.decoding.succeed(AB, { a: \"1\", b: \"2\" }, { a: 12 })\n    await Util.assertions.encoding.succeed(AB, { a: 2 }, { a: \"2\", b: \"4\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/transformLiterals.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"transformLiteral\", () => {\n  describe(\"Struct\", () => {\n    it(\"simple\", async () => {\n      const schema = S.transformLiteral(0, \"a\")\n\n      await Util.assertions.decoding.succeed(schema, 0, \"a\")\n      await Util.assertions.encoding.succeed(schema, \"a\", 0)\n    })\n  })\n})\n\ndescribe(\"transformLiterals\", () => {\n  describe(\"Struct\", () => {\n    it(\"simple\", async () => {\n      const schema = S.transformLiterals(\n        [0, \"a\"],\n        [1, \"b\"],\n        [2, \"c\"]\n      )\n\n      await Util.assertions.decoding.succeed(schema, 1, \"b\")\n      await Util.assertions.encoding.succeed(schema, \"b\", 1)\n    })\n\n    it(\"mixed types\", async () => {\n      const schema = S.transformLiterals(\n        [0, BigInt(0)],\n        [\"a\", true],\n        [null, false]\n      )\n\n      await Util.assertions.decoding.succeed(schema, 0, BigInt(0))\n      await Util.assertions.encoding.succeed(schema, BigInt(0), 0)\n      await Util.assertions.decoding.succeed(schema, \"a\", true)\n      await Util.assertions.encoding.succeed(schema, true, \"a\")\n      await Util.assertions.decoding.succeed(schema, null, false)\n      await Util.assertions.encoding.succeed(schema, false, null)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/transformOrFail.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as Schema from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"transformOrFail\", () => {\n  it(\"should receive the fromI value other than the fromA value\", async () => {\n    const A = Schema.Struct({\n      a: Schema.NumberFromString\n    })\n\n    const B = Schema.Struct({\n      a: Schema.String,\n      b: Schema.NumberFromString\n    })\n\n    const AB = Schema.transformOrFail(B, A, {\n      strict: true,\n      decode: ({ a, b: _b }, _options, _ast, i) => ParseResult.succeed({ a: a + i.b }),\n      encode: (i, _options, _ast, a) => ParseResult.succeed({ ...i, b: a.a * 2 })\n    })\n\n    await Util.assertions.decoding.succeed(AB, { a: \"1\", b: \"2\" }, { a: 12 })\n    await Util.assertions.encoding.succeed(AB, { a: 2 }, { a: \"2\", b: \"4\" })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/typeSchema.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"typeSchema\", () => {\n  it(\"transformation\", () => {\n    const schema = S.String.pipe(\n      S.transform(\n        S.Tuple(S.NumberFromString, S.NumberFromString),\n        { strict: true, decode: (s) => [s, s] as const, encode: ([s]) => s }\n      ),\n      S.typeSchema\n    )\n    deepStrictEqual(S.decodeUnknownSync(schema)([1, 2]), [1, 2])\n  })\n\n  it(\"refinement\", () => {\n    const schema = S.NumberFromString.pipe(\n      S.greaterThanOrEqualTo(1),\n      S.lessThanOrEqualTo(2),\n      S.typeSchema\n    )\n    assertFalse(S.is(schema)(0))\n    assertTrue(S.is(schema)(1))\n    assertTrue(S.is(schema)(2))\n    assertFalse(S.is(schema)(3))\n  })\n\n  it(\"suspend\", async () => {\n    interface I {\n      prop: I | string\n    }\n    interface A {\n      prop: A | number\n    }\n    const schema: S.Schema<A, I> = S.suspend( // intended outer suspend\n      () =>\n        S.Struct({\n          prop: S.Union(S.NumberFromString, schema)\n        })\n    )\n    const to = S.typeSchema(schema)\n    await Util.assertions.decoding.succeed(to, { prop: 1 })\n    await Util.assertions.decoding.succeed(to, { prop: { prop: 1 } })\n  })\n\n  it(\"decoding\", async () => {\n    const schema = S.typeSchema(S.NumberFromString)\n    await Util.assertions.decoding.succeed(schema, 1)\n    await Util.assertions.decoding.fail(schema, null, \"Expected number, actual null\")\n    await Util.assertions.decoding.fail(schema, \"a\", `Expected number, actual \"a\"`)\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/validate.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"validate\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return an error on invalid values\", async () => {\n    await Util.assertions.effect.succeed(S.validate(schema)({ a: 1 }), { a: 1 })\n    await Util.assertions.effect.fail(\n      S.validate(schema)({ a: null }).pipe(Effect.mapError((e) => e.issue)),\n      `{ readonly a: number }\n└─ [\"a\"]\n   └─ Expected number, actual null`\n    )\n  })\n\n  it(\"should respect outer/inner options\", async () => {\n    const input = { a: 1, b: \"b\" }\n    await Util.assertions.effect.fail(\n      S.validate(schema)(input, { onExcessProperty: \"error\" }).pipe(Effect.mapError((e) => e.issue)),\n      `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.effect.fail(\n      S.validate(schema, { onExcessProperty: \"error\" })(input).pipe(Effect.mapError((e) => e.issue)),\n      `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.effect.succeed(\n      S.validate(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }),\n      {\n        a: 1\n      }\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/validateEither.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Either from \"effect/Either\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"validateEither\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return an error on invalid values\", async () => {\n    Util.assertions.either.right(S.validateEither(schema)({ a: 1 }), { a: 1 })\n    await Util.assertions.either.fail(\n      S.validateEither(schema)({ a: null }).pipe(Either.mapLeft((e) => e.issue)),\n      `{ readonly a: number }\n└─ [\"a\"]\n   └─ Expected number, actual null`\n    )\n  })\n\n  it(\"should return an error on async\", async () => {\n    await Util.assertions.either.fail(\n      S.encodeEither(Util.AsyncDeclaration)(\"a\").pipe(Either.mapLeft((e) => e.issue)),\n      `AsyncDeclaration\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n\n  it(\"should respect outer/inner options\", async () => {\n    const input = { a: 1, b: \"b\" }\n    await Util.assertions.either.fail(\n      S.validateEither(schema)(input, { onExcessProperty: \"error\" }).pipe(Either.mapLeft((e) => e.issue)),\n      `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.either.fail(\n      S.validateEither(schema, { onExcessProperty: \"error\" })(input).pipe(Either.mapLeft((e) => e.issue)),\n      `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    Util.assertions.either.right(\n      S.validateEither(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }),\n      { a: 1 }\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/validateOption.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertSome } from \"@effect/vitest/utils\"\nimport { Schema as S } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"validateOption\", () => {\n  it(\"should return none on async\", () => {\n    assertNone(S.validateOption(Util.AsyncDeclaration)(\"a\"))\n  })\n\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should return None on invalid values\", () => {\n    assertSome(S.validateOption(schema)({ a: 1 }), { a: 1 })\n    assertNone(S.validateOption(schema)({ a: null }))\n  })\n\n  it(\"should respect outer/inner options\", () => {\n    const input = { a: 1, b: \"b\" }\n    assertNone(S.validateOption(schema)(input, { onExcessProperty: \"error\" }))\n    assertNone(S.validateOption(schema, { onExcessProperty: \"error\" })(input))\n    assertSome(S.validateOption(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }), { a: 1 })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/validatePromise.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport { ParseResult, Schema as S } from \"effect\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"validatePromise\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should reject on invalid values\", async () => {\n    deepStrictEqual(await S.validatePromise(schema)({ a: 1 }), { a: 1 })\n    deepStrictEqual(await ParseResult.validatePromise(schema)({ a: 1 }), { a: 1 })\n\n    await Util.assertions.promise.fail(\n      S.validatePromise(schema)({ a: null }),\n      `{ readonly a: number }\n└─ [\"a\"]\n   └─ Expected number, actual null`\n    )\n  })\n\n  it(\"should respect outer/inner options\", async () => {\n    const input = { a: 1, b: \"b\" }\n\n    deepStrictEqual(\n      await S.validatePromise(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }),\n      { a: 1 }\n    )\n\n    await Util.assertions.promise.fail(\n      S.validatePromise(schema)(input, { onExcessProperty: \"error\" }),\n      `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    await Util.assertions.promise.fail(\n      S.validatePromise(schema, { onExcessProperty: \"error\" })(input),\n      `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/validateSync.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"validateSync\", () => {\n  const schema = S.Struct({ a: Util.NumberFromChar })\n\n  it(\"should throw on invalid values\", () => {\n    deepStrictEqual(S.validateSync(schema)({ a: 1 }), { a: 1 })\n    Util.assertions.parseError(\n      () => S.validateSync(schema)({ a: null }),\n      `{ readonly a: number }\n└─ [\"a\"]\n   └─ Expected number, actual null`\n    )\n  })\n\n  it(\"should throw on async\", () => {\n    Util.assertions.parseError(\n      () => S.validateSync(Util.AsyncDeclaration)(\"a\"),\n      `AsyncDeclaration\n└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`\n    )\n  })\n\n  it(\"should respect outer/inner options\", () => {\n    const input = { a: 1, b: \"b\" }\n    Util.assertions.parseError(\n      () => S.validateSync(schema)(input, { onExcessProperty: \"error\" }),\n      `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    Util.assertions.parseError(\n      () => S.validateSync(schema, { onExcessProperty: \"error\" })(input),\n      `{ readonly a: number }\n└─ [\"b\"]\n   └─ is unexpected, expected: \"a\"`\n    )\n    deepStrictEqual(S.validateSync(schema, { onExcessProperty: \"error\" })(input, { onExcessProperty: \"ignore\" }), {\n      a: 1\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/withConstructorDefault.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"withConstructorDefault\", () => {\n  it(\"annotating a PropertySignatureDeclaration should repect existing defaultValues\", () => {\n    const prop: any = S.propertySignature(S.String).pipe(S.withConstructorDefault(() => \"\")).annotations({})\n    strictEqual(prop.ast.defaultValue(), \"\")\n  })\n\n  it(\"annotating a PropertySignatureTransformation should repect existing defaultValues\", () => {\n    const prop: any = S.optionalWith(S.String, { nullable: true }).pipe(S.withConstructorDefault(() => \"\")).annotations(\n      {}\n    )\n    strictEqual(prop.ast.to.defaultValue(), \"\")\n  })\n\n  it(\"using fromKey should repect existing defaultValues\", () => {\n    const prop: any = S.propertySignature(S.String).pipe(S.withConstructorDefault(() => \"\"), S.fromKey(\"a\"))\n    strictEqual(prop.ast.to.defaultValue(), \"\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Schema/withDecodingDefault.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"withDecodingDefault\", () => {\n  describe(\"PropertySignatureDeclaration\", () => {\n    it(\"optional\", async () => {\n      const prop = S.optional(S.String).pipe(S.withDecodingDefault(() => \"\"))\n      const schema = S.Struct({ a: prop })\n      await Util.assertions.decoding.succeed(schema, {}, { a: \"\" })\n      await Util.assertions.decoding.succeed(schema, { a: undefined }, { a: \"\" })\n      await Util.assertions.decoding.succeed(schema, { a: \"a\" })\n    })\n\n    it(\"optionalWith { exact: true }\", async () => {\n      const prop = S.optionalWith(S.String, { exact: true }).pipe(S.withDecodingDefault(() => \"\"))\n      const schema = S.Struct({ a: prop })\n      await Util.assertions.decoding.succeed(schema, {}, { a: \"\" })\n      await Util.assertions.decoding.succeed(schema, { a: \"a\" })\n    })\n\n    it(\"should prune undefined from the type\", () => {\n      const prop1 = S.optional(S.String).pipe(S.withDecodingDefault(() => \"\"))\n      strictEqual(String(prop1), `PropertySignature<\":\", string, never, \"?:\", string | undefined>`)\n\n      const prop2 = S.optional(S.NumberFromString).pipe(S.withDecodingDefault(() => 0))\n      strictEqual(String(prop2), `PropertySignature<\":\", number, never, \"?:\", NumberFromString | undefined>`)\n    })\n  })\n\n  describe(\"PropertySignatureTransformation\", () => {\n    it(\"optional\", async () => {\n      const prop = S.optional(S.String).pipe(S.fromKey(\"b\"), S.withDecodingDefault(() => \"\"))\n      const schema = S.Struct({ a: prop })\n      await Util.assertions.decoding.succeed(schema, {}, { a: \"\" })\n      await Util.assertions.decoding.succeed(schema, { b: undefined }, { a: \"\" })\n      await Util.assertions.decoding.succeed(schema, { b: \"a\" }, { a: \"a\" })\n    })\n\n    it(\"optionalWith { exact: true }\", async () => {\n      const prop = S.optionalWith(S.String, { exact: true }).pipe(\n        S.fromKey(\"b\"),\n        S.withDecodingDefault(() => \"\")\n      )\n      const schema = S.Struct({ a: prop })\n      await Util.assertions.decoding.succeed(schema, {}, { a: \"\" })\n      await Util.assertions.decoding.succeed(schema, { b: \"a\" }, { a: \"a\" })\n    })\n\n    it(\"should prune undefined from the type\", () => {\n      const prop1 = S.optional(S.String).pipe(S.fromKey(\"a\"), S.withDecodingDefault(() => \"\"))\n      strictEqual(String(prop1), `PropertySignature<\":\", string, \"a\", \"?:\", string | undefined>`)\n\n      const prop2 = S.optional(S.NumberFromString).pipe(S.fromKey(\"a\"), S.withDecodingDefault(() => 0))\n      strictEqual(String(prop2), `PropertySignature<\":\", number, \"a\", \"?:\", NumberFromString | undefined>`)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/IndexSignature.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { throws } from \"@effect/vitest/utils\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"AST.IndexSignature\", () => {\n  it(\"new IndexSignature should throw on unsupported ASTs\", () => {\n    throws(\n      () => new AST.IndexSignature(AST.booleanKeyword, AST.stringKeyword, true),\n      new Error(\n        `Unsupported index signature parameter\ndetails: An index signature parameter type must be \\`string\\`, \\`symbol\\`, a template literal type or a refinement of the previous types`\n      )\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/Refinement.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\n\ndescribe(\"AST.Refinement\", () => {\n  it(\"toString\", () => {\n    strictEqual(String(S.Number.pipe(S.filter(() => true))), \"{ number | filter }\")\n    strictEqual(String(S.Number.pipe(S.int())), \"int\")\n    strictEqual(String(S.Number.pipe(S.int(), S.positive())), \"int & positive\")\n    strictEqual(String(S.Int.pipe(S.positive())), \"Int & positive\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/Tuple.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual, throws } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"AST.Tuple\", () => {\n  it(\"toString\", () => {\n    strictEqual(String(S.Tuple(S.String, S.optionalElement(S.Number))), \"readonly [string, number?]\")\n  })\n\n  it(\"A required element cannot follow an optional element\", () => {\n    throws(\n      () =>\n        new AST.TupleType(\n          [new AST.OptionalType(AST.stringKeyword, true), new AST.OptionalType(AST.stringKeyword, false)],\n          [],\n          true\n        ),\n      new Error(`Invalid element\ndetails: A required element cannot follow an optional element. ts(1257)`)\n    )\n  })\n\n  it(\"A required rest element cannot follow an optional element\", () => {\n    throws(\n      () =>\n        new AST.TupleType(\n          [new AST.OptionalType(AST.stringKeyword, true)],\n          [new AST.Type(AST.stringKeyword), new AST.Type(AST.stringKeyword)],\n          true\n        ),\n      new Error(`Invalid element\ndetails: A required element cannot follow an optional element. ts(1257)`)\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/TypeLiteral.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual, throws } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"AST.TypeLiteral\", () => {\n  it(\"should throw on onvalid index signature parameters\", () => {\n    throws(\n      () => new AST.IndexSignature(S.NumberFromString.ast, AST.stringKeyword, true),\n      new Error(\n        `Unsupported index signature parameter\ndetails: An index signature parameter type must be \\`string\\`, \\`symbol\\`, a template literal type or a refinement of the previous types`\n      )\n    )\n  })\n\n  describe(\"toString\", () => {\n    it(\"Struct (immutable)\", () => {\n      strictEqual(S.Struct({ a: S.String, b: S.Number }).ast.toString(), `{ readonly a: string; readonly b: number }`)\n    })\n\n    it(\"Struct (mutable)\", () => {\n      strictEqual(S.mutable(S.Struct({ a: S.String, b: S.Number })).ast.toString(), `{ a: string; b: number }`)\n    })\n\n    it(\"Record (immutable)\", () => {\n      strictEqual(S.Record({ key: S.String, value: S.Number }).ast.toString(), `{ readonly [x: string]: number }`)\n    })\n\n    it(\"Record (mutable)\", () => {\n      strictEqual(S.mutable(S.Record({ key: S.String, value: S.Number })).ast.toString(), `{ [x: string]: number }`)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/TypeLiteralTransformation.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { throws } from \"@effect/vitest/utils\"\nimport { identity } from \"effect/Function\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"AST.TypeLiteralTransformation\", () => {\n  it(\"Duplicate property signature transformation\", () => {\n    throws(\n      () =>\n        new AST.TypeLiteralTransformation([\n          new AST.PropertySignatureTransformation(\"a\", \"b\", identity, identity),\n          new AST.PropertySignatureTransformation(\"a\", \"c\", identity, identity)\n        ]),\n      new Error(`Duplicate property signature transformation\ndetails: Duplicate key \"a\"`)\n    )\n    throws(\n      () =>\n        new AST.TypeLiteralTransformation([\n          new AST.PropertySignatureTransformation(\"a\", \"c\", identity, identity),\n          new AST.PropertySignatureTransformation(\"b\", \"c\", identity, identity)\n        ]),\n      new Error(`Duplicate property signature transformation\ndetails: Duplicate key \"c\"`)\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/Union.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"AST.Union\", () => {\n  it(\"flatten should un-nest union members\", () => {\n    const asts = AST.flatten([S.Union(S.Literal(\"a\", \"b\"), S.Literal(\"c\", \"d\")).ast])\n    strictEqual(asts.length, 4)\n  })\n\n  it(\"unify should remove never from members\", () => {\n    strictEqual(AST.Union.unify([AST.neverKeyword, AST.neverKeyword]), AST.neverKeyword)\n    strictEqual(AST.Union.unify([AST.neverKeyword, AST.stringKeyword]), AST.stringKeyword)\n    strictEqual(AST.Union.unify([AST.stringKeyword, AST.neverKeyword]), AST.stringKeyword)\n    deepStrictEqual(\n      AST.Union.unify([\n        AST.neverKeyword,\n        AST.stringKeyword,\n        AST.neverKeyword,\n        AST.numberKeyword\n      ]),\n      AST.Union.unify([AST.stringKeyword, AST.numberKeyword])\n    )\n  })\n\n  describe(\"toString\", () => {\n    it(\"string | number\", () => {\n      strictEqual(String(S.Union(S.String, S.Number)), \"string | number\")\n    })\n\n    it(\"should support suspended schemas\", () => {\n      interface A {\n        readonly a?: null | A | undefined\n      }\n      // intended outer suspend\n      const schema: S.Schema<A> = S.partial(\n        S.suspend(\n          () =>\n            S.Struct({\n              a: S.Union(S.Null, schema)\n            })\n        )\n      )\n      strictEqual(String(schema), \"<suspended schema>\")\n    })\n\n    it(\"descriptions of nested unions should be preserved\", () => {\n      const u = S.Union(S.String, S.Number)\n      const nested1 = u.annotations({ identifier: \"nested1\" })\n      const nested2 = u.annotations({ identifier: \"nested2\" })\n\n      strictEqual(String(u), \"string | number\")\n      strictEqual(String(S.Union(nested1, nested1)), \"nested1 | nested1\")\n      strictEqual(String(S.Union(nested1, S.String)), \"nested1 | string\")\n      strictEqual(String(S.Union(nested1, u)), \"nested1 | string | number\")\n      strictEqual(String(S.Union(nested1, nested2)), \"nested1 | nested2\")\n      strictEqual(String(S.Union(nested1, nested2, S.String)), \"nested1 | nested2 | string\")\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/annotations.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInstanceOf, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"annotations\", () => {\n  it(\"should add annotations\", () => {\n    const symA = Symbol.for(\"a\")\n    const ast = AST.annotations(AST.stringKeyword, { [symA]: \"A\" })\n    assertInstanceOf(ast, AST.StringKeyword)\n    deepStrictEqual(\n      ast,\n      new AST.StringKeyword({\n        [AST.TitleAnnotationId]: \"string\",\n        [AST.DescriptionAnnotationId]: \"a string\",\n        [symA]: \"A\"\n      })\n    )\n    deepStrictEqual(\n      AST.stringKeyword,\n      new AST.StringKeyword({\n        [AST.TitleAnnotationId]: \"string\",\n        [AST.DescriptionAnnotationId]: \"a string\"\n      })\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/encodedAST.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"encodedAST\", () => {\n  it(\"refinements\", () => {\n    const ast = S.String.pipe(S.minLength(2)).ast\n    const encodedAST = AST.encodedAST(ast)\n    strictEqual(encodedAST, S.String.ast)\n  })\n\n  describe(`should return the same reference if the AST doesn't represent a transformation`, () => {\n    it(\"declaration (true)\", () => {\n      const schema = S.OptionFromSelf(S.String)\n      assertTrue(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"declaration (false)\", () => {\n      const schema = S.OptionFromSelf(S.NumberFromString)\n      assertFalse(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"tuple (true)\", () => {\n      const schema = S.Tuple(S.String, S.Number)\n      assertTrue(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"tuple (false)\", () => {\n      const schema = S.Tuple(S.String, S.NumberFromString)\n      assertFalse(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"array (true)\", () => {\n      const schema = S.Array(S.Number)\n      assertTrue(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"array (false)\", () => {\n      const schema = S.Array(S.NumberFromString)\n      assertFalse(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"union (true)\", () => {\n      const schema = S.Union(S.String, S.Number)\n      assertTrue(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"union (false)\", () => {\n      const schema = S.Union(S.String, S.NumberFromString)\n      assertFalse(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"struct (true)\", () => {\n      const schema = S.Struct({ a: S.String, b: S.Number })\n      assertTrue(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"struct (false)\", () => {\n      const schema = S.Struct({ a: S.String, b: S.NumberFromString })\n      assertFalse(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"record (true)\", () => {\n      const schema = S.Record({ key: S.String, value: S.Number })\n      assertTrue(AST.encodedAST(schema.ast) === schema.ast)\n    })\n\n    it(\"record (false)\", () => {\n      const schema = S.Record({ key: S.String, value: S.NumberFromString })\n      assertFalse(AST.encodedAST(schema.ast) === schema.ast)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/encodedBoundAST.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"encodedBoundAST\", () => {\n  it(\"refinements\", () => {\n    const ast = S.String.pipe(S.minLength(2)).ast\n    const encodedAST = AST.encodedBoundAST(ast)\n    assertTrue(encodedAST === ast)\n  })\n\n  describe(`should return the same reference if the AST doesn't represent a transformation`, () => {\n    it(\"declaration (true)\", () => {\n      const schema = S.OptionFromSelf(S.String)\n      assertTrue(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"declaration (false)\", () => {\n      const schema = S.OptionFromSelf(S.NumberFromString)\n      assertFalse(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"tuple (true)\", () => {\n      const schema = S.Tuple(S.String, S.Number)\n      assertTrue(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"tuple (false)\", () => {\n      const schema = S.Tuple(S.String, S.NumberFromString)\n      assertFalse(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"array (true)\", () => {\n      const schema = S.Array(S.Number)\n      assertTrue(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"array (false)\", () => {\n      const schema = S.Array(S.NumberFromString)\n      assertFalse(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"union (true)\", () => {\n      const schema = S.Union(S.String, S.Number)\n      assertTrue(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"union (false)\", () => {\n      const schema = S.Union(S.String, S.NumberFromString)\n      assertFalse(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"struct (true)\", () => {\n      const schema = S.Struct({ a: S.String, b: S.Number })\n      assertTrue(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"struct (false)\", () => {\n      const schema = S.Struct({ a: S.String, b: S.NumberFromString })\n      assertFalse(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"record (true)\", () => {\n      const schema = S.Record({ key: S.String, value: S.Number })\n      assertTrue(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n\n    it(\"record (false)\", () => {\n      const schema = S.Record({ key: S.String, value: S.NumberFromString })\n      assertFalse(AST.encodedBoundAST(schema.ast) === schema.ast)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/equals.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"equals\", () => {\n  describe(\"TemplateLiteral\", () => {\n    it(`(\"a\" | \"b\") + string + (\"d\" | \"e\")`, () => {\n      const schema1 = S.TemplateLiteral(S.Literal(\"a\", \"b\"), S.String, S.Literal(\"d\", \"e\"))\n      const schema2 = S.TemplateLiteral(S.Literal(\"a\", \"b\"), S.String, S.Literal(\"d\", \"f\"))\n      assertTrue(AST.equals(schema1.ast, schema1.ast))\n      assertFalse(AST.equals(schema1.ast, schema2.ast))\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/getPropertySignatures.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"getPropertySignatures\", () => {\n  it(\"Struct\", () => {\n    const schema = S.Struct({ a: S.String, b: S.Number })\n    deepStrictEqual(AST.getPropertySignatures(schema.ast), [\n      new AST.PropertySignature(\"a\", S.String.ast, false, true),\n      new AST.PropertySignature(\"b\", S.Number.ast, false, true)\n    ])\n  })\n\n  it(\"Refinement\", () => {\n    const schema = S.Struct({ a: S.String, b: S.Number }).pipe(S.filter(() => true))\n    deepStrictEqual(AST.getPropertySignatures(schema.ast), [\n      new AST.PropertySignature(\"a\", S.String.ast, false, true),\n      new AST.PropertySignature(\"b\", S.Number.ast, false, true)\n    ])\n  })\n\n  it(\"suspend\", () => {\n    const schema = S.suspend(() => S.Struct({ a: S.String, b: S.Number }))\n    deepStrictEqual(AST.getPropertySignatures(schema.ast), [\n      new AST.PropertySignature(\"a\", S.String.ast, false, true),\n      new AST.PropertySignature(\"b\", S.Number.ast, false, true)\n    ])\n  })\n\n  it(\"Union\", () => {\n    const schema = S.Union(S.Struct({ _tag: S.Literal(\"A\") }), S.Struct({ _tag: S.Literal(\"B\") }))\n    deepStrictEqual(AST.getPropertySignatures(schema.ast), [\n      new AST.PropertySignature(\"_tag\", S.Literal(\"A\", \"B\").ast, false, true)\n    ])\n  })\n\n  it(\"Class\", () => {\n    class A extends S.Class<A>(\"A\")({ a: S.String, b: S.Number }) {}\n    const schema = A.pipe(S.typeSchema)\n    deepStrictEqual(AST.getPropertySignatures(schema.ast), [\n      new AST.PropertySignature(\"a\", S.String.ast, false, true),\n      new AST.PropertySignature(\"b\", S.Number.ast, false, true)\n    ])\n  })\n\n  it(\"Transformation (Struct with optionalWith default)\", () => {\n    const schema = S.Struct({\n      a: S.String,\n      b: S.optionalWith(S.Number, { default: () => 0 })\n    })\n    deepStrictEqual(AST.getPropertySignatures(schema.ast), [\n      new AST.PropertySignature(\"a\", S.String.ast, false, true),\n      new AST.PropertySignature(\"b\", S.Number.ast, false, true)\n    ])\n  })\n\n  it(\"Transformation (Struct with optionalWith as Option)\", () => {\n    const schema = S.Struct({\n      a: S.String,\n      b: S.optionalWith(S.Number, { as: \"Option\" })\n    })\n    const signatures = AST.getPropertySignatures(schema.ast)\n    deepStrictEqual(signatures.length, 2)\n    deepStrictEqual(signatures[0], new AST.PropertySignature(\"a\", S.String.ast, false, true))\n    deepStrictEqual(signatures[1].name, \"b\")\n    deepStrictEqual(signatures[1].isOptional, false)\n    deepStrictEqual(signatures[1].isReadonly, true)\n    // b's type on the decoded side is Option<number> (a Declaration AST)\n    deepStrictEqual(signatures[1].type._tag, \"Declaration\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/guards.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"guards\", () => {\n  it(\"isDeclaration\", () => {\n    assertTrue(AST.isDeclaration(S.OptionFromSelf(S.Number).ast))\n    assertFalse(AST.isDeclaration(S.Number.ast))\n  })\n\n  it(\"isTemplateLiteral\", () => {\n    assertTrue(AST.isTemplateLiteral(S.TemplateLiteral(S.Literal(\"a\"), S.String).ast))\n    assertFalse(AST.isTemplateLiteral(S.Number.ast))\n  })\n\n  it(\"isSuspend\", () => {\n    type A = readonly [number, A | null]\n    const schema: S.Schema<A> = S.suspend( // intended outer suspend\n      () => S.Tuple(S.Number, S.Union(schema, S.Literal(null)))\n    )\n    assertTrue(AST.isSuspend(schema.ast))\n    assertFalse(AST.isSuspend(S.Number.ast))\n  })\n\n  it(\"isTransform\", () => {\n    assertTrue(AST.isTransformation(S.Trim.ast))\n    assertFalse(AST.isTransformation(S.Number.ast))\n  })\n\n  it(\"isUndefinedKeyword\", () => {\n    assertTrue(AST.isUndefinedKeyword(S.Undefined.ast))\n    assertFalse(AST.isUndefinedKeyword(S.Number.ast))\n  })\n\n  it(\"isVoidKeyword\", () => {\n    assertTrue(AST.isVoidKeyword(S.Void.ast))\n    assertFalse(AST.isVoidKeyword(S.Unknown.ast))\n  })\n\n  it(\"isSymbolKeyword\", () => {\n    assertTrue(AST.isSymbolKeyword(S.SymbolFromSelf.ast))\n    assertFalse(AST.isSymbolKeyword(S.Unknown.ast))\n  })\n\n  it(\"isObjectKeyword\", () => {\n    assertTrue(AST.isObjectKeyword(S.Object.ast))\n    assertFalse(AST.isObjectKeyword(S.Unknown.ast))\n  })\n\n  it(\"isEnums\", () => {\n    enum Fruits {\n      Apple,\n      Banana\n    }\n    assertTrue(AST.isEnums(S.Enums(Fruits).ast))\n    assertFalse(AST.isEnums(S.Unknown.ast))\n  })\n\n  it(\"isNeverKeyword\", () => {\n    assertTrue(AST.isNeverKeyword(S.Never.ast))\n    assertFalse(AST.isNeverKeyword(S.Unknown.ast))\n  })\n\n  it(\"isUniqueSymbol\", () => {\n    assertTrue(AST.isUniqueSymbol(S.UniqueSymbolFromSelf(Symbol.for(\"effect/Schema/test/a\")).ast))\n    assertFalse(AST.isUniqueSymbol(S.Unknown.ast))\n  })\n\n  it(\"isUnknownKeyword\", () => {\n    assertTrue(AST.isUnknownKeyword(S.Unknown.ast))\n    assertFalse(AST.isUnknownKeyword(S.Any.ast))\n  })\n\n  it(\"isAnyKeyword\", () => {\n    assertTrue(AST.isAnyKeyword(S.Any.ast))\n    assertFalse(AST.isAnyKeyword(S.Unknown.ast))\n  })\n\n  it(\"isBooleanKeyword\", () => {\n    assertTrue(AST.isBooleanKeyword(S.Boolean.ast))\n    assertFalse(AST.isBooleanKeyword(S.Unknown.ast))\n  })\n\n  it(\"isBigIntKeyword\", () => {\n    assertTrue(AST.isBigIntKeyword(S.BigIntFromSelf.ast))\n    assertFalse(AST.isBigIntKeyword(S.Unknown.ast))\n  })\n\n  it(\"isParameter\", () => {\n    assertTrue(AST.isParameter(AST.stringKeyword))\n    assertTrue(AST.isParameter(AST.symbolKeyword))\n    assertTrue(AST.isParameter(S.TemplateLiteral(S.String, S.Literal(\"-\"), S.String).ast))\n    assertTrue(AST.isParameter(S.String.pipe(S.minLength(2)).ast))\n    assertTrue(AST.isParameter(S.TemplateLiteral(S.Literal(\"a\", \"b\"), S.Literal(\"c\")).ast))\n    assertFalse(AST.isParameter(S.Number.pipe(S.int()).ast))\n    assertFalse(AST.isParameter(S.NumberFromString.ast))\n    assertFalse(AST.isParameter(S.NumberFromString.pipe(S.int()).ast))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/mutable.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { identity } from \"effect\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\nconst expectSameReference = (schema: S.Schema.Any) => {\n  const mutable = AST.mutable(AST.isSuspend(schema.ast) ? schema.ast.f() : schema.ast)\n  const mutable2 = AST.mutable(mutable)\n  strictEqual(mutable, mutable2)\n}\n\ndescribe(\"mutable\", () => {\n  it(\"tuple\", () => {\n    expectSameReference(S.Tuple(S.String, S.Number))\n  })\n\n  it(\"struct\", () => {\n    expectSameReference(S.Struct({ a: S.String, b: S.Number }))\n  })\n\n  it(\"union\", () => {\n    expectSameReference(S.Union(S.String, S.Number))\n  })\n\n  it(\"suspend\", () => {\n    expectSameReference(S.suspend(() => S.Struct({ a: S.String, b: S.Number })))\n  })\n\n  it(\"refinement\", () => {\n    expectSameReference(S.Array(S.String).pipe(S.maxItems(2)))\n  })\n\n  it(\"transformation\", () => {\n    expectSameReference(\n      S.transform(S.Array(S.String), S.Array(S.String), { strict: true, decode: identity, encode: identity })\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/partial.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"partial\", () => {\n  describe(\"{ exact: false }\", () => {\n    it(\"struct\", () => {\n      // type A = { readonly a: string }\n      // type B = Partial<A>\n      const schema = S.partial(S.Struct({ a: S.String }))\n      const expected = S.Struct({ a: S.optional(S.String) })\n      deepStrictEqual(schema.ast, expected.ast)\n    })\n\n    describe(\"tuple\", () => {\n      it(\"e\", () => {\n        // type A = [string]\n        // type B = Partial<A>\n        const tuple = new AST.TupleType(\n          [new AST.OptionalType(AST.stringKeyword, false)],\n          [],\n          true\n        )\n        deepStrictEqual(\n          AST.partial(tuple),\n          new AST.TupleType([new AST.OptionalType(AST.orUndefined(AST.stringKeyword), true)], [], true)\n        )\n      })\n\n      it(\"e + r\", () => {\n        // type A = readonly [string, ...Array<number>]\n        // type B = Partial<A>\n        const tuple = new AST.TupleType(\n          [new AST.OptionalType(AST.stringKeyword, false)],\n          [new AST.Type(AST.numberKeyword)],\n          true\n        )\n        deepStrictEqual(\n          AST.partial(tuple),\n          new AST.TupleType(\n            [new AST.OptionalType(AST.orUndefined(AST.stringKeyword), true)],\n            [new AST.Type(AST.orUndefined(AST.numberKeyword))],\n            true\n          )\n        )\n      })\n\n      it(\"e + r + e\", () => {\n        // type A = readonly [string, ...Array<number>, boolean]\n        // type B = Partial<A>\n        const tuple = new AST.TupleType(\n          [new AST.OptionalType(AST.stringKeyword, false)],\n          [new AST.Type(AST.numberKeyword), new AST.Type(AST.booleanKeyword)],\n          true\n        )\n        deepStrictEqual(\n          AST.partial(tuple),\n          new AST.TupleType(\n            [new AST.OptionalType(AST.orUndefined(AST.stringKeyword), true)],\n            [\n              new AST.Type(AST.Union.make([AST.numberKeyword, AST.booleanKeyword, AST.undefinedKeyword]))\n            ],\n            true\n          )\n        )\n      })\n    })\n  })\n\n  describe(\"{ exact: true }\", () => {\n    it(\"struct\", () => {\n      // type A = { readonly a: string }\n      // type B = Partial<A>\n      const schema = S.partialWith(S.Struct({ a: S.String }), { exact: true })\n      const expected = S.Struct({ a: S.optionalWith(S.String, { exact: true }) })\n      deepStrictEqual(schema.ast, expected.ast)\n    })\n\n    describe(\"tuple\", () => {\n      it(\"e\", () => {\n        // type A = [string]\n        // type B = Partial<A>\n        const tuple = new AST.TupleType(\n          [new AST.OptionalType(AST.stringKeyword, false)],\n          [],\n          true\n        )\n        deepStrictEqual(\n          AST.partial(tuple, { exact: true }),\n          new AST.TupleType([new AST.OptionalType(AST.stringKeyword, true)], [], true)\n        )\n      })\n\n      it(\"e + r\", () => {\n        // type A = readonly [string, ...Array<number>]\n        // type B = Partial<A>\n        const tuple = new AST.TupleType(\n          [new AST.OptionalType(AST.stringKeyword, false)],\n          [new AST.Type(AST.numberKeyword)],\n          true\n        )\n        deepStrictEqual(\n          AST.partial(tuple, { exact: true }),\n          new AST.TupleType(\n            [new AST.OptionalType(AST.stringKeyword, true)],\n            [new AST.Type(AST.orUndefined(AST.numberKeyword))],\n            true\n          )\n        )\n      })\n\n      it(\"e + r + e\", () => {\n        // type A = readonly [string, ...Array<number>, boolean]\n        // type B = Partial<A>\n        const tuple = new AST.TupleType(\n          [new AST.OptionalType(AST.stringKeyword, false)],\n          [new AST.Type(AST.numberKeyword), new AST.Type(AST.booleanKeyword)],\n          true\n        )\n        deepStrictEqual(\n          AST.partial(tuple, { exact: true }),\n          new AST.TupleType(\n            [new AST.OptionalType(AST.stringKeyword, true)],\n            [\n              new AST.Type(AST.Union.make([AST.numberKeyword, AST.booleanKeyword, AST.undefinedKeyword]))\n            ],\n            true\n          )\n        )\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/record.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, throws } from \"@effect/vitest/utils\"\nimport * as AST from \"effect/SchemaAST\"\n\ndescribe(\"record\", () => {\n  it(\"should throw on unsupported keys\", () => {\n    throws(\n      () => AST.record(AST.undefinedKeyword, AST.numberKeyword),\n      new Error(`Unsupported key schema\nschema (UndefinedKeyword): undefined`)\n    )\n  })\n\n  it(\"should throw on unsupported literals\", () => {\n    throws(\n      () => AST.record(new AST.Literal(true), AST.numberKeyword),\n      new Error(`Unsupported literal\ndetails: literal value: true`)\n    )\n  })\n\n  it(\"should support numeric literals as keys\", () => {\n    deepStrictEqual(AST.record(new AST.Literal(1), AST.numberKeyword).propertySignatures, [\n      new AST.PropertySignature(1, AST.numberKeyword, false, true)\n    ])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/suspend.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport type * as AST from \"effect/SchemaAST\"\nimport * as Util from \"../TestUtils.js\"\n\ndescribe(\"AST.Suspend\", () => {\n  it(\"should memoize the thunk\", async () => {\n    let log = 0\n    interface A {\n      readonly a: string\n      readonly as: ReadonlyArray<A>\n    }\n    const schema = S.Struct({\n      a: S.String,\n      as: S.Array(S.suspend((): S.Schema<A> => {\n        log++\n        return schema\n      }))\n    })\n    await Util.assertions.decoding.succeed(schema, { a: \"a1\", as: [] })\n    await Util.assertions.decoding.succeed(schema, { a: \"a1\", as: [{ a: \"a2\", as: [] }] })\n    strictEqual(log, 1)\n  })\n\n  it(\"should memoize the AST\", () => {\n    type A = readonly [number, A | null]\n    const schema: S.Schema<A> = S.suspend( // intended outer suspend\n      () => S.Tuple(S.Number, S.Union(schema, S.Literal(null)))\n    )\n    const ast = schema.ast as AST.Suspend\n    assertTrue(ast.f() === ast.f())\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/typeAST.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Effect, Schema as S, SchemaAST as AST } from \"effect\"\n\ndescribe(\"typeAST\", () => {\n  describe(`should return the same reference if the AST doesn't represent a transformation`, () => {\n    it(\"declaration (true)\", () => {\n      const schema = S.OptionFromSelf(S.String)\n      assertTrue(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"declaration (false)\", () => {\n      const schema = S.OptionFromSelf(S.NumberFromString)\n      assertFalse(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"tuple (true)\", () => {\n      const schema = S.Tuple(S.String, S.Number)\n      assertTrue(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"tuple (false)\", () => {\n      const schema = S.Tuple(S.String, S.NumberFromString)\n      assertFalse(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"array (true)\", () => {\n      const schema = S.Array(S.Number)\n      assertTrue(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"array (false)\", () => {\n      const schema = S.Array(S.NumberFromString)\n      assertFalse(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"union (true)\", () => {\n      const schema = S.Union(S.String, S.Number)\n      assertTrue(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"union (false)\", () => {\n      const schema = S.Union(S.String, S.NumberFromString)\n      assertFalse(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"struct (true)\", () => {\n      const schema = S.Struct({ a: S.String, b: S.Number })\n      assertTrue(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"struct (false)\", () => {\n      const schema = S.Struct({ a: S.String, b: S.NumberFromString })\n      assertFalse(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"record (true)\", () => {\n      const schema = S.Record({ key: S.String, value: S.Number })\n      assertTrue(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"record (false)\", () => {\n      const schema = S.Record({ key: S.String, value: S.NumberFromString })\n      assertFalse(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"refinement (true)\", () => {\n      const schema = S.Number.pipe(S.filter((n) => n > 0))\n      assertTrue(AST.typeAST(schema.ast) === schema.ast)\n    })\n\n    it(\"refinement (false)\", () => {\n      const schema = S.NumberFromString.pipe(S.filter((n) => n > 0))\n      assertFalse(AST.typeAST(schema.ast) === schema.ast)\n    })\n  })\n\n  describe(\"Transformation\", () => {\n    it(\"should preserve whitelisted annotations\", () => {\n      const annotations: S.Annotations.GenericSchema<number> = {\n        title: \"title\",\n        description: \"description\",\n        documentation: \"documentation\",\n        identifier: \"id\",\n        message: () => \"message\",\n        schemaId: \"schemaId\",\n        concurrency: 6,\n        batching: true,\n        parseIssueTitle: () => \"parseIssueTitle\",\n        parseOptions: { onExcessProperty: \"error\" },\n        decodingFallback: () => Effect.succeed(7),\n        // whitelisted annotations\n        examples: [1, 2, 3],\n        default: 4,\n        jsonSchema: { type: \"object\" },\n        arbitrary: () => (fc) => fc.constant(5),\n        pretty: () => () => \"pretty\",\n        equivalence: () => () => true\n      }\n      const schema = S.transform(\n        S.Number,\n        S.Number.annotations({\n          title: \"original-title\",\n          description: \"original-description\"\n        }),\n        { decode: (n) => n, encode: (n) => n }\n      ).annotations(annotations)\n      deepStrictEqual(AST.typeAST(schema.ast).annotations, {\n        [AST.TitleAnnotationId]: \"original-title\",\n        [AST.DescriptionAnnotationId]: \"original-description\",\n        // whitelisted annotations\n        [AST.ExamplesAnnotationId]: annotations.examples,\n        [AST.DefaultAnnotationId]: annotations.default,\n        [AST.JSONSchemaAnnotationId]: annotations.jsonSchema,\n        [AST.ArbitraryAnnotationId]: annotations.arbitrary,\n        [AST.PrettyAnnotationId]: annotations.pretty,\n        [AST.EquivalenceAnnotationId]: annotations.equivalence\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaAST/unify.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as S from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\n\nconst expectUnify = (input: Array<S.Schema.All>, expected: Array<S.Schema.All>) => {\n  const actual = AST.unify(input.map((schema) => schema.ast))\n  deepStrictEqual(actual, expected.map((e) => e.ast))\n}\n\ndescribe(\"AST.unify\", () => {\n  it(\"should unify\", () => {\n    expectUnify([], [])\n\n    expectUnify([S.Any, S.String], [S.Any])\n    expectUnify([S.Any, S.Unknown], [S.Any])\n    expectUnify([S.Literal(\"a\"), S.Any], [S.Any])\n\n    expectUnify([S.Unknown, S.String], [S.Unknown])\n    expectUnify([S.Unknown, S.Literal(\"a\")], [S.Unknown])\n\n    expectUnify([S.Object, S.Object], [S.Object])\n    expectUnify([S.Object, S.Struct({ a: S.String })], [S.Object])\n    expectUnify([S.Object, S.Tuple(S.String)], [S.Object])\n    expectUnify([S.Object, S.String], [S.Object, S.String])\n\n    expectUnify([S.String, S.String], [S.String])\n    expectUnify([S.String, S.Number], [S.String, S.Number])\n\n    expectUnify([S.Literal(\"a\"), S.Literal(\"a\")], [S.Literal(\"a\")])\n    expectUnify([S.Literal(\"a\"), S.Literal(\"b\")], [S.Literal(\"a\"), S.Literal(\"b\")])\n    expectUnify([S.Literal(\"a\"), S.String], [S.String])\n    expectUnify([S.String, S.Literal(\"a\")], [S.String])\n    expectUnify([S.Literal(\"a\"), S.Literal(\"b\"), S.String], [S.String])\n    expectUnify([S.Literal(\"a\"), S.String, S.Literal(\"b\")], [S.String])\n\n    expectUnify([S.Literal(1), S.Literal(1)], [S.Literal(1)])\n    expectUnify([S.Literal(1), S.Literal(2)], [S.Literal(1), S.Literal(2)])\n    expectUnify([S.Literal(1), S.Number], [S.Number])\n\n    expectUnify([S.Literal(true), S.Literal(true)], [S.Literal(true)])\n    expectUnify([S.Literal(true), S.Literal(false)], [S.Literal(true), S.Literal(false)])\n    expectUnify([S.Literal(true), S.Boolean], [S.Boolean])\n\n    expectUnify([S.Literal(1n), S.Literal(1n)], [S.Literal(1n)])\n    expectUnify([S.Literal(1n), S.Literal(2n)], [S.Literal(1n), S.Literal(2n)])\n    expectUnify([S.Literal(1n), S.BigIntFromSelf], [S.BigIntFromSelf])\n\n    expectUnify([S.UniqueSymbolFromSelf(Symbol.for(\"a\")), S.UniqueSymbolFromSelf(Symbol.for(\"a\"))], [\n      S.UniqueSymbolFromSelf(Symbol.for(\"a\"))\n    ])\n    expectUnify([S.UniqueSymbolFromSelf(Symbol.for(\"a\")), S.SymbolFromSelf], [S.SymbolFromSelf])\n\n    expectUnify([S.Struct({}), S.Struct({})], [S.Struct({})])\n    expectUnify([S.Object, S.Struct({})], [S.Object, S.Struct({})])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaTest.ts",
    "content": "import type { SchemaAST } from \"effect\"\nimport {\n  Arbitrary,\n  Cause,\n  Context,\n  Effect,\n  Either,\n  FastCheck,\n  ParseResult,\n  Predicate,\n  Pretty,\n  Runtime,\n  Schema\n} from \"effect\"\n\n// Defines parameters for FastCheck that exclude typed properties\nexport type UntypedParameters = Omit<FastCheck.Parameters<any>, \"examples\" | \"reporter\" | \"asyncReporter\">\n\n// Configuration context for assertion behaviors\nexport class AssertConfig extends Context.Tag(\"AssertConfig\")<AssertConfig, {\n  readonly arbitrary?: {\n    readonly validateGeneratedValues?: {\n      readonly skip?: boolean | undefined\n      readonly params?: UntypedParameters | undefined\n    }\n  }\n  readonly testRoundtripConsistency?: {\n    readonly skip?: boolean | undefined\n    readonly params?: UntypedParameters | undefined\n  }\n}>() {}\n\n// Provides assertion utilities for testing\nexport class Assert extends Context.Tag(\"Assert\")<Assert, {\n  readonly deepStrictEqual: (actual: unknown, expected: unknown) => void\n  readonly strictEqual: (actual: unknown, expected: unknown, message?: string) => void\n  readonly throws: (thunk: () => void, error?: Error | ((u: unknown) => undefined)) => void\n  readonly fail: (message: string) => void\n}>() {}\n\n// Provides various assertions for Schema testing\nexport const assertions = Effect.gen(function*() {\n  const { deepStrictEqual, fail, strictEqual, throws } = yield* Assert\n  const config = yield* AssertConfig\n\n  function assertInstanceOf<C extends abstract new(...args: any) => any>(\n    value: unknown,\n    constructor: C,\n    message?: string,\n    ..._: Array<never>\n  ): asserts value is InstanceType<C> {\n    if (!(value instanceof constructor)) {\n      fail(message ?? `expected ${value} to be an instance of ${constructor}`)\n    }\n  }\n\n  const out = {\n    ast: {\n      equals: <A, I, R>(a: Schema.Schema<A, I, R>, b: Schema.Schema<A, I, R>) => {\n        deepStrictEqual(a.ast, b.ast)\n      }\n    },\n    make: {\n      /**\n       * Ensures that the given constructor produces the expected value.\n       */\n      succeed<const A, const B>(\n        // Destructure to verify that \"this\" type is bound\n        { make }: { readonly make: (a: A) => B },\n        input: A,\n        expected?: B\n      ) {\n        deepStrictEqual(make(input), expected ?? input)\n      },\n\n      /**\n       * Ensures that the given constructor throws the expected error.\n       */\n      fail<const A, const B>(\n        // Destructure to verify that \"this\" type is bound\n        { make }: { readonly make: (a: A) => B },\n        input: A,\n        message: string\n      ) {\n        out.parseError(() => make(input), message)\n      }\n    },\n\n    arbitrary: {\n      /**\n       * Verifies that the schema generates valid arbitrary values that satisfy\n       * the schema.\n       */\n      validateGeneratedValues<A, I, R>(schema: Schema.Schema<A, I, R>, options?: {\n        readonly params?: FastCheck.Parameters<[A]> | undefined\n      }) {\n        if (config.arbitrary?.validateGeneratedValues?.skip === true) {\n          return\n        }\n        const params = Predicate.isObject(config.arbitrary?.validateGeneratedValues)\n          ? { ...config.arbitrary?.validateGeneratedValues?.params, ...options?.params }\n          : options?.params\n        const is = Schema.is(schema)\n        const arb = Arbitrary.make(schema)\n        FastCheck.assert(FastCheck.property(arb, (a) => is(a)), params)\n      }\n    },\n\n    /**\n     * Verifies that the schema satisfies the roundtrip law: `decode(encode(a))`\n     * is equal to `a`.\n     */\n    testRoundtripConsistency<A, I>(schema: Schema.Schema<A, I, never>, options?: {\n      readonly ignoreEncodingErrors?: ((issue: ParseResult.ParseIssue) => boolean) | undefined\n      readonly params?: FastCheck.Parameters<[A]> | undefined\n    }) {\n      if (config.testRoundtripConsistency?.skip === true) {\n        return\n      }\n      const params = Predicate.isObject(config.testRoundtripConsistency?.params)\n        ? { ...config.testRoundtripConsistency?.params, ...options?.params }\n        : options?.params\n      const arb = Arbitrary.make(schema)\n      const is = Schema.is(schema)\n      const encode = ParseResult.encode(schema)\n      const decode = ParseResult.decode(schema)\n      FastCheck.assert(\n        FastCheck.property(arb, (a) => {\n          const roundtrip = encode(a).pipe(\n            Effect.mapError((issue) => [\"encoding\", issue] as const),\n            Effect.flatMap((i) => decode(i).pipe(Effect.mapError((issue) => [\"decoding\", issue] as const))),\n            Effect.either,\n            Effect.runSync\n          )\n          if (Either.isLeft(roundtrip)) {\n            if (roundtrip.left[0] === \"encoding\" && options?.ignoreEncodingErrors) {\n              return options.ignoreEncodingErrors(roundtrip.left[1])\n            }\n            return false\n          }\n          return is(roundtrip.right)\n        }),\n        params\n      )\n    },\n\n    decoding: {\n      /**\n       * Attempts to decode the given input using the provided schema. If the\n       * decoding is successful, the decoded value is compared to the expected\n       * value. Otherwise the test fails.\n       */\n      async succeed<const A, I>(\n        schema: Schema.Schema<A, I>,\n        input: unknown,\n        expected?: A,\n        options?: {\n          readonly parseOptions?: SchemaAST.ParseOptions | undefined\n        } | undefined\n      ) {\n        const decoded = ParseResult.decodeUnknown(schema)(input, options?.parseOptions)\n        return out.effect.succeed(\n          decoded,\n          arguments.length >= 3 ? // Account for `expected` being `undefined`\n            expected :\n            expected ?? input\n        )\n      },\n\n      /**\n       * Attempts to decode the given input using the provided schema. If the\n       * decoding fails, the error message is compared to the expected message.\n       * Otherwise the test fails.\n       */\n      async fail<A, I>(\n        schema: Schema.Schema<A, I>,\n        input: unknown,\n        message: string,\n        options?: {\n          readonly parseOptions?: SchemaAST.ParseOptions | undefined\n        } | undefined\n      ) {\n        const decoded = ParseResult.decodeUnknown(schema)(input, options?.parseOptions)\n        return out.effect.fail(decoded, message)\n      }\n    },\n\n    encoding: {\n      /**\n       * Attempts to encode the given input using the provided schema. If the\n       * decoding is successful, the decoded value is compared to the expected\n       * value. Otherwise the test fails.\n       */\n      async succeed<const A, const I>(\n        schema: Schema.Schema<A, I>,\n        input: A,\n        expected?: I,\n        options?: {\n          readonly parseOptions?: SchemaAST.ParseOptions | undefined\n        } | undefined\n      ) {\n        const encoded = ParseResult.encodeUnknown(schema)(input, options?.parseOptions)\n        return out.effect.succeed(\n          encoded,\n          arguments.length >= 3 ? // Account for `expected` being `undefined`\n            expected :\n            expected ?? input\n        )\n      },\n\n      /**\n       * Attempts to encode the given input using the provided schema. If the\n       * decoding fails, the error message is compared to the expected message.\n       * Otherwise the test fails.\n       */\n      async fail<const A, I>(\n        schema: Schema.Schema<A, I>,\n        input: A,\n        message: string,\n        options?: {\n          readonly parseOptions?: SchemaAST.ParseOptions | undefined\n        } | undefined\n      ) {\n        const encoded = ParseResult.encodeUnknown(schema)(input, options?.parseOptions)\n        return out.effect.fail(encoded, message)\n      }\n    },\n\n    promise: {\n      /**\n       * Ensures that the given promise rejects with a Fiber Failure containing the expected message.\n       *\n       * Useful to test `decodePromise` and `encodePromise`.\n       */\n      async fail<A>(promise: Promise<A>, message: string) {\n        try {\n          const a = await promise\n          throw new Error(`Promise didn't reject, got: ${a}`)\n        } catch (e: unknown) {\n          if (Runtime.isFiberFailure(e) && Cause.isCause(e[Runtime.FiberFailureCauseId])) {\n            const cause = e[Runtime.FiberFailureCauseId]\n            if (Cause.isFailType(cause) && Predicate.hasProperty(cause.error, \"message\")) {\n              return deepStrictEqual(cause.error.message, message)\n            }\n          }\n          throw new Error(`Unknown promise rejection: ${e}`)\n        }\n      }\n    },\n\n    effect: {\n      /**\n       * Verifies that the effect succeeds with the expected value.\n       */\n      async succeed<const A, E>(\n        effect: Effect.Effect<A, E>,\n        a: A\n      ) {\n        deepStrictEqual(await Effect.runPromise(Effect.either(effect)), Either.right(a))\n      },\n\n      /**\n       * Verifies that the effect fails with the expected message.\n       */\n      async fail<A>(\n        effect: Effect.Effect<A, ParseResult.ParseIssue>,\n        message: string\n      ) {\n        const effectWithMessage = Effect.gen(function*() {\n          const decoded = yield* Effect.either(effect)\n          if (Either.isLeft(decoded)) {\n            const message = yield* ParseResult.TreeFormatter.formatIssue(decoded.left)\n            return yield* Effect.fail(message)\n          }\n          return decoded.right\n        })\n        const result = await Effect.runPromise(Effect.either(effectWithMessage))\n        return out.either.left(result, message)\n      }\n    },\n\n    either: {\n      /**\n       * Verifies that the either is a `Right` with the expected value.\n       */\n      right<const R, L>(either: Either.Either<R, L>, right: R) {\n        if (Either.isRight(either)) {\n          deepStrictEqual(either.right, right)\n        } else {\n          // eslint-disable-next-line no-console\n          console.log(either.left)\n          fail(`expected a Right, got a Left: ${either.left}`)\n        }\n      },\n\n      /**\n       * Verifies that the either is a `Left` with the expected value.\n       */\n      left<R, const L>(either: Either.Either<R, L>, left: L) {\n        if (Either.isLeft(either)) {\n          deepStrictEqual(either.left, left)\n        } else {\n          // eslint-disable-next-line no-console\n          console.log(either.right)\n          fail(`expected a Left, got a Right: ${either.right}`)\n        }\n      },\n\n      /**\n       * Verifies that the either is a left with the expected value.\n       */\n      async fail<R>(either: Either.Either<R, ParseResult.ParseIssue>, message: string) {\n        const eitherWithMessage = Effect.gen(function*() {\n          const encoded = yield* Effect.either(either)\n          if (Either.isLeft(encoded)) {\n            const message = yield* ParseResult.TreeFormatter.formatIssue(encoded.left)\n            return yield* Effect.fail(message)\n          }\n          return encoded.right\n        })\n        const result = await Effect.runPromise(Effect.either(eitherWithMessage))\n        return out.either.left(result, message)\n      }\n    },\n\n    asserts: {\n      succeed<A, I, R>(schema: Schema.Schema<A, I, R>, input: unknown, options?: {\n        readonly parseOptions?: SchemaAST.ParseOptions | undefined\n      }) {\n        deepStrictEqual(Schema.asserts(schema, options?.parseOptions)(input), undefined)\n      },\n\n      fail<A, I, R>(\n        schema: Schema.Schema<A, I, R>,\n        input: unknown,\n        message: string,\n        options?: {\n          readonly parseOptions?: SchemaAST.ParseOptions | undefined\n        }\n      ) {\n        out.parseError(() => Schema.asserts(schema, options?.parseOptions)(input), message)\n      }\n    },\n\n    parseError(f: () => void, message: string) {\n      throws(f, (err) => {\n        assertInstanceOf(err, ParseResult.ParseError)\n        strictEqual(err.message, message)\n      })\n    },\n\n    pretty<A, I, R>(schema: Schema.Schema<A, I, R>, a: A, expected: string) {\n      const pretty = Pretty.make(schema)\n      strictEqual(pretty(a), expected)\n    }\n  }\n\n  return out\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/SchemaUserland.test.ts",
    "content": "/**\n * It contains a collection of user-defined APIs to keep track of what might break in the event of breaking changes.\n */\nimport { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Record, Schema, SchemaAST as AST } from \"effect\"\nimport * as Util from \"./TestUtils.js\"\n\nconst structTypeSchema = <Fields extends Schema.Struct.Fields>(\n  schema: Schema.Struct<Fields>\n): Schema.Struct<{ [K in keyof Fields]: Schema.Schema<Schema.Schema.Type<Fields[K]>> }> =>\n  Schema.Struct(Record.map(schema.fields, (field) => {\n    switch (field.ast._tag) {\n      case \"PropertySignatureDeclaration\":\n        return Schema.make(AST.typeAST(field.ast.type))\n      case \"PropertySignatureTransformation\":\n        return Schema.make(AST.typeAST(field.ast.to.type))\n      default:\n        return Schema.make(AST.typeAST(field.ast))\n    }\n  })) as any\n\ndescribe(\"SchemaUserland\", () => {\n  it(\"structTypeSchema\", () => {\n    // Discord: https://discordapp.com/channels/795981131316985866/847382157861060618/1266533881788502096\n    // goal: `Schema.typeSchema` for structs, retaining the type\n\n    //      v-- this must be a struct\n    const schema = structTypeSchema(Schema.Struct({\n      a: Schema.NumberFromString,\n      b: Schema.propertySignature(Schema.NumberFromString),\n      c: Schema.optionalWith(Schema.NumberFromString, { as: \"Option\" })\n    }))\n    deepStrictEqual(schema.fields.a.ast, Schema.Number.ast)\n    deepStrictEqual(schema.fields.b.ast, Schema.Number.ast)\n    const c = schema.fields.c.ast\n    strictEqual(c._tag, \"Declaration\")\n    deepStrictEqual((c as AST.Declaration).typeParameters, [Schema.Number.ast])\n  })\n\n  it(\"detect that a struct does not contain a specific field\", async () => {\n    // Discord: https://discordapp.com/channels/795981131316985866/847382157861060618/1268175268019830906\n    class A extends Schema.Class<A>(\"A\")(\n      Schema.Struct({\n        a: Schema.String,\n        b: Schema.propertySignature(\n          Schema.Array(Schema.Struct({\n            d: Schema.String\n          })).annotations({ parseOptions: { onExcessProperty: \"ignore\" } })\n        ).pipe(Schema.fromKey(\"c\"))\n      }).annotations({\n        parseOptions: { onExcessProperty: \"error\" }\n      })\n    ) {\n      readonly _tag = \"A\"\n    }\n    await Util.assertions.decoding.succeed(A, { a: \"a\", c: [{ d: \"d\" }] }, new A({ a: \"a\", b: [{ d: \"d\" }] }))\n    await Util.assertions.decoding.succeed(\n      A,\n      { a: \"a\", c: [{ d: \"d\", ignored: null }] },\n      new A({ a: \"a\", b: [{ d: \"d\" }] })\n    )\n    await Util.assertions.decoding.fail(\n      A,\n      { a: \"a\", c: [{ d: \"d\" }], not_allowed: null },\n      `(A (Encoded side) <-> A)\n└─ Encoded side transformation failure\n   └─ A (Encoded side)\n      └─ Encoded side transformation failure\n         └─ Struct (Encoded side)\n            └─ [\"not_allowed\"]\n               └─ is unexpected, expected: \"a\" | \"c\"`\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/Serializable.test.ts",
    "content": "import { describe, test } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Effect, Exit } from \"effect\"\nimport * as S from \"effect/Schema\"\n\nclass Person extends S.Class<Person>(\"Person\")({\n  id: S.Number,\n  name: S.String\n}) {}\n\nclass GetPersonById extends S.Class<GetPersonById>(\"GetPersonById\")({\n  id: S.Number\n}) {\n  get [S.symbolSerializable]() {\n    return GetPersonById\n  }\n  get [S.symbolWithResult]() {\n    return {\n      success: Person,\n      failure: S.String,\n      defect: S.Defect\n    }\n  }\n}\n\ndescribe(\"Serializable\", () => {\n  test(\"serialize\", () => {\n    const req = new GetPersonById({ id: 123 })\n    deepStrictEqual(Effect.runSync(S.serialize(req)), {\n      id: 123\n    })\n  })\n\n  test(\"deserialize\", () => {\n    const req = new GetPersonById({ id: 123 })\n    deepStrictEqual(\n      Effect.runSync(S.deserialize(req, {\n        id: 456\n      })),\n      new GetPersonById({ id: 456 })\n    )\n  })\n\n  test(\"serializeFailure\", () => {\n    const req = new GetPersonById({ id: 123 })\n    deepStrictEqual(\n      Effect.runSync(\n        S.serializeFailure(req, \"fail\")\n      ),\n      \"fail\"\n    )\n  })\n\n  test(\"serializeSuccess\", () => {\n    const req = new GetPersonById({ id: 123 })\n    deepStrictEqual(\n      Effect.runSync(\n        S.serializeSuccess(req, new Person({ id: 123, name: \"foo\" }))\n      ),\n      { id: 123, name: \"foo\" }\n    )\n  })\n\n  test(\"serializeExit\", () => {\n    const req = new GetPersonById({ id: 123 })\n    deepStrictEqual(\n      Effect.runSync(\n        S.serializeExit(req, Exit.succeed(new Person({ id: 123, name: \"foo\" })))\n      ),\n      { _tag: \"Success\", value: { id: 123, name: \"foo\" } }\n    )\n    deepStrictEqual(\n      Effect.runSync(\n        S.serializeExit(req, Exit.fail(\"fail\"))\n      ),\n      { _tag: \"Failure\", cause: { _tag: \"Fail\", error: \"fail\" } }\n    )\n  })\n\n  test(\"deserializeFailure\", () => {\n    const req = new GetPersonById({ id: 123 })\n    deepStrictEqual(\n      Effect.runSync(\n        S.deserializeFailure(req, \"fail\")\n      ),\n      \"fail\"\n    )\n  })\n\n  test(\"deserializeSuccess\", () => {\n    const req = new GetPersonById({ id: 123 })\n    deepStrictEqual(\n      Effect.runSync(\n        S.deserializeSuccess(req, { id: 123, name: \"foo\" })\n      ),\n      new Person({ id: 123, name: \"foo\" })\n    )\n  })\n\n  test(\"deserializeExit\", () => {\n    const req = new GetPersonById({ id: 123 })\n    deepStrictEqual(\n      Effect.runSync(\n        S.deserializeExit(req, { _tag: \"Success\", value: { id: 123, name: \"foo\" } })\n      ),\n      Exit.succeed(new Person({ id: 123, name: \"foo\" }))\n    )\n    deepStrictEqual(\n      Effect.runSync(\n        S.deserializeExit(req, {\n          _tag: \"Failure\",\n          cause: { _tag: \"Fail\", error: \"fail\" }\n        })\n      ),\n      Exit.fail(\"fail\")\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Schema/TestUtils.ts",
    "content": "import { deepStrictEqual, fail, strictEqual, throws } from \"@effect/vitest/utils\"\nimport { Context, Effect, ParseResult, Schema as S, SchemaAST as AST } from \"effect\"\nimport * as SchemaTest from \"./SchemaTest.js\"\n\nexport const assertions = Effect.runSync(\n  SchemaTest.assertions.pipe(\n    Effect.provideService(SchemaTest.Assert, {\n      deepStrictEqual,\n      strictEqual,\n      throws,\n      fail\n    }),\n    Effect.provideService(SchemaTest.AssertConfig, {\n      arbitrary: {\n        validateGeneratedValues: {\n          skip: false\n        }\n      },\n      testRoundtripConsistency: {\n        skip: false\n      }\n    })\n  )\n)\n\nexport const onExcessPropertyError: AST.ParseOptions = {\n  onExcessProperty: \"error\"\n}\n\nexport const onExcessPropertyPreserve: AST.ParseOptions = {\n  onExcessProperty: \"preserve\"\n}\n\nexport const ErrorsAll: AST.ParseOptions = {\n  errors: \"all\"\n}\n\nexport const NumberFromChar = S.Char.pipe(S.compose(S.NumberFromString)).annotations({\n  identifier: \"NumberFromChar\"\n})\n\nexport const AsyncDeclaration = S.declare(\n  [],\n  {\n    decode: () => (u) => Effect.andThen(Effect.sleep(\"10 millis\"), Effect.succeed(u)),\n    encode: () => (u) => Effect.andThen(Effect.sleep(\"10 millis\"), Effect.succeed(u))\n  },\n  {\n    identifier: \"AsyncDeclaration\"\n  }\n)\n\nexport const AsyncStringWithoutIdentifier = effectify(S.String)\nexport const AsyncString = effectify(S.String).annotations({ identifier: \"AsyncString\" })\n\nconst Name = Context.GenericTag<\"Name\", string>(\"Name\")\n\nexport const DependencyString = S.transformOrFail(\n  S.String,\n  S.String,\n  { strict: true, decode: (s) => Effect.andThen(Name, s), encode: (s) => Effect.andThen(Name, s) }\n).annotations({ identifier: \"DependencyString\" })\n\nexport const expectFields = (f1: S.Struct.Fields, f2: S.Struct.Fields) => {\n  const ks1 = Reflect.ownKeys(f1).sort().map((k) => [k, f1[k].ast.toString()])\n  const ks2 = Reflect.ownKeys(f2).sort().map((k) => [k, f2[k].ast.toString()])\n  deepStrictEqual(ks1, ks2)\n}\n\nexport const Defect = S.transform(S.String, S.Object, {\n  strict: true,\n  decode: (s) => ({ input: s }),\n  encode: (u) => JSON.stringify(u)\n})\n\nfunction effectifyDecode<R>(\n  decode: (\n    fromA: any,\n    options: AST.ParseOptions,\n    self: AST.Transformation,\n    fromI: any\n  ) => Effect.Effect<any, ParseResult.ParseIssue, R>\n): (\n  fromA: any,\n  options: AST.ParseOptions,\n  self: AST.Transformation,\n  fromI: any\n) => Effect.Effect<any, ParseResult.ParseIssue, R> {\n  return (fromA, options, ast, fromI) =>\n    ParseResult.flatMap(Effect.sleep(\"10 millis\"), () => decode(fromA, options, ast, fromI))\n}\n\nfunction effectifyAST(ast: AST.AST): AST.AST {\n  switch (ast._tag) {\n    case \"TupleType\":\n      return new AST.TupleType(\n        ast.elements.map((e) => new AST.OptionalType(effectifyAST(e.type), e.isOptional, e.annotations)),\n        ast.rest.map((annotatedAST) => new AST.Type(effectifyAST(annotatedAST.type), annotatedAST.annotations)),\n        ast.isReadonly,\n        ast.annotations\n      )\n    case \"TypeLiteral\":\n      return new AST.TypeLiteral(\n        ast.propertySignatures.map((p) =>\n          new AST.PropertySignature(p.name, effectifyAST(p.type), p.isOptional, p.isReadonly, p.annotations)\n        ),\n        ast.indexSignatures.map((is) => {\n          return new AST.IndexSignature(is.parameter, effectifyAST(is.type), is.isReadonly)\n        }),\n        ast.annotations\n      )\n    case \"Union\":\n      return AST.Union.make(ast.types.map((ast) => effectifyAST(ast)), ast.annotations)\n    case \"Suspend\":\n      return new AST.Suspend(() => effectifyAST(ast.f()), ast.annotations)\n    case \"Refinement\":\n      return new AST.Refinement(\n        effectifyAST(ast.from),\n        ast.filter,\n        ast.annotations\n      )\n    case \"Transformation\":\n      return new AST.Transformation(\n        effectifyAST(ast.from),\n        effectifyAST(ast.to),\n        new AST.FinalTransformation(\n          effectifyDecode(ParseResult.getFinalTransformation(ast.transformation, true)),\n          effectifyDecode(ParseResult.getFinalTransformation(ast.transformation, false))\n        ),\n        ast.annotations\n      )\n  }\n  const schema = S.make(ast)\n  const decode = S.decode(schema)\n  const encode = S.encode(schema)\n  return new AST.Transformation(\n    AST.encodedAST(ast),\n    AST.typeAST(ast),\n    new AST.FinalTransformation(\n      (a, options) =>\n        Effect.flatMap(Effect.sleep(\"10 millis\"), () => ParseResult.mapError(decode(a, options), (e) => e.issue)),\n      (a, options) =>\n        Effect.flatMap(Effect.sleep(\"10 millis\"), () => ParseResult.mapError(encode(a, options), (e) => e.issue))\n    )\n  )\n}\n\nfunction effectify<A, I>(schema: S.Schema<A, I, never>): S.Schema<A, I, never> {\n  return S.make(effectifyAST(schema.ast))\n}\n"
  },
  {
    "path": "packages/effect/test/Scope.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Deferred, Effect, identity, pipe, Ref, Scope } from \"effect\"\n\ntype Action = Acquire | Use | Release\n\nconst OP_ACQUIRE = 0 as const\ntype OP_ACQUIRE = typeof OP_ACQUIRE\n\nconst OP_USE = 1 as const\ntype OP_USE = typeof OP_USE\n\nconst OP_RELEASE = 2 as const\ntype OP_RELEASE = typeof OP_RELEASE\n\ninterface Acquire {\n  readonly op: OP_ACQUIRE\n  readonly id: number\n}\n\ninterface Use {\n  readonly op: OP_USE\n  readonly id: number\n}\n\ninterface Release {\n  readonly op: OP_RELEASE\n  readonly id: number\n}\n\nconst acquire = (id: number): Action => ({ op: OP_ACQUIRE, id })\nconst use = (id: number): Action => ({ op: OP_USE, id })\nconst release = (id: number): Action => ({ op: OP_RELEASE, id })\nconst isAcquire = (self: Action): self is Use => self.op === OP_ACQUIRE\nconst isUse = (self: Action): self is Use => self.op === OP_USE\nconst isRelease = (self: Action): self is Use => self.op === OP_RELEASE\n\nconst resource = (id: number, ref: Ref.Ref<ReadonlyArray<Action>>): Effect.Effect<number, never, Scope.Scope> => {\n  return pipe(\n    Ref.update(ref, (actions) => [...actions, acquire(id)]),\n    Effect.as(id),\n    Effect.uninterruptible,\n    Effect.ensuring(\n      Effect.scopeWith((scope) => scope.addFinalizer(() => Ref.update(ref, (actions) => [...actions, release(id)])))\n    )\n  )\n}\n\ndescribe(\"Scope\", () => {\n  it.effect(\"runs finalizers when the scope is closed\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<ReadonlyArray<Action>>([])\n      yield* Effect.scoped(pipe(\n        resource(1, ref),\n        Effect.flatMap((id) => Ref.update(ref, (actions) => [...actions, use(id)]))\n      ))\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(result, [acquire(1), use(1), release(1)])\n    }))\n  it.effect(\"runs finalizers in parallel\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<void>()\n      const result = yield* pipe(\n        Effect.addFinalizer(() => Deferred.succeed(deferred, void 0)),\n        Effect.zipRight(Effect.addFinalizer(() => Deferred.await(deferred)), {\n          concurrent: true,\n          concurrentFinalizers: true\n        }),\n        Effect.scoped,\n        Effect.asVoid\n      )\n      strictEqual(result, undefined)\n    }))\n  it.effect(\"runs finalizers in parallel when the scope is closed\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<ReadonlyArray<Action>>([])\n      yield* Effect.scoped(\n        pipe(\n          Effect.parallelFinalizers(resource(1, ref)),\n          Effect.zip(resource(2, ref), { concurrent: true, concurrentFinalizers: true }),\n          Effect.flatMap(([resource1, resource2]) =>\n            pipe(\n              Ref.update(ref, (actions) => [...actions, use(resource1)]),\n              Effect.zip(Ref.update(ref, (actions) => [...actions, use(resource2)]), { concurrent: true })\n            )\n          )\n        )\n      )\n      const result = yield* Ref.get(ref)\n      assertTrue(result.slice(0, 2).some((action) => isAcquire(action) && action.id === 1))\n      assertTrue(result.slice(0, 2).some((action) => isAcquire(action) && action.id === 2))\n      assertTrue(result.slice(2, 4).some((action) => isUse(action) && action.id === 1))\n      assertTrue(result.slice(2, 4).some((action) => isUse(action) && action.id === 2))\n      assertTrue(result.slice(4, 6).some((action) => isRelease(action) && action.id === 1))\n      assertTrue(result.slice(4, 6).some((action) => isRelease(action) && action.id === 2))\n    }))\n  it.effect(\"preserves order of nested sequential finalizers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<ReadonlyArray<Action>>([])\n      const left = Effect.sequentialFinalizers(pipe(resource(1, ref), Effect.zipRight(resource(2, ref))))\n      const right = Effect.sequentialFinalizers(pipe(resource(3, ref), Effect.zipRight(resource(4, ref))))\n      yield* Effect.scoped(Effect.parallelFinalizers(pipe(left, Effect.zip(right, { concurrent: true }))))\n      const actions = yield* Ref.get(ref)\n      const action1Index = actions.findIndex((action) => action.op === OP_RELEASE && action.id === 1)\n      const action2Index = actions.findIndex((action) => action.op === OP_RELEASE && action.id === 2)\n      const action3Index = actions.findIndex((action) => action.op === OP_RELEASE && action.id === 3)\n      const action4Index = actions.findIndex((action) => action.op === OP_RELEASE && action.id === 4)\n      assertTrue(action2Index < action1Index)\n      assertTrue(action4Index < action3Index)\n    }))\n  it.scoped(\"withEarlyRelease\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make<ReadonlyArray<Action>>([])\n      const left = resource(1, ref)\n      const right = Effect.withEarlyRelease(resource(2, ref))\n      yield* pipe(left, Effect.zipRight(pipe(right, Effect.flatMap(([release, _]) => release))))\n      const actions = yield* Ref.get(ref)\n      deepStrictEqual(actions[0], acquire(1))\n      deepStrictEqual(actions[1], acquire(2))\n      deepStrictEqual(actions[2], release(2))\n    }))\n  it.effect(\"using\", () =>\n    Effect.gen(function*() {\n      const ref1 = yield* Ref.make<ReadonlyArray<Action>>([])\n      const ref2 = yield* Ref.make<ReadonlyArray<Action>>([])\n      yield* pipe(\n        resource(1, ref1),\n        Effect.using(() =>\n          pipe(Ref.update(ref1, (actions) => [...actions, use(1)]), Effect.zipRight(resource(2, ref2)))\n        ),\n        Effect.zipRight(Ref.update(ref2, (actions) => [...actions, use(2)])),\n        Effect.scoped\n      )\n      const actions1 = yield* Ref.get(ref1)\n      const actions2 = yield* Ref.get(ref2)\n      deepStrictEqual(actions1, [acquire(1), use(1), release(1)])\n      deepStrictEqual(actions2, [acquire(2), use(2), release(2)])\n    }))\n  it.effect(\n    \".pipe\",\n    () =>\n      Effect.gen(function*() {\n        const scope = yield* Scope.make()\n        strictEqual(scope.pipe(identity), scope)\n      })\n  )\n})\n"
  },
  {
    "path": "packages/effect/test/ScopedCache.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertLeft,\n  assertNone,\n  assertRight,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual\n} from \"@effect/vitest/utils\"\nimport {\n  Array,\n  Cause,\n  Chunk,\n  Context,\n  Duration,\n  Effect,\n  Exit,\n  FastCheck as fc,\n  Fiber,\n  Hash,\n  HashMap,\n  identity,\n  pipe,\n  Ref,\n  Schedule,\n  Scope,\n  ScopedCache,\n  TestClock,\n  TestServices\n} from \"effect\"\nimport { dual } from \"effect/Function\"\nimport * as ObservableResource from \"./utils/cache/ObservableResource.js\"\nimport * as WatchableLookup from \"./utils/cache/WatchableLookup.js\"\n\nconst hash = dual<\n  (y: number) => (x: number) => number,\n  (x: number, y: number) => number\n>(2, (x, y) => Hash.number(x ^ y))\n\nconst hashEffect = dual<\n  (y: number) => (x: number) => Effect.Effect<number>,\n  (x: number, y: number) => Effect.Effect<number>\n>(2, (x, y) => Effect.sync(() => hash(x, y)))\n\ndescribe(\"ScopedCache\", () => {\n  it(\"cacheStats - should correctly keep track of cache size, hits and misses\", () =>\n    fc.assert(\n      fc.asyncProperty(fc.integer(), async (salt) => {\n        const program = Effect.gen(function*() {\n          const capacity = 10\n          const scopedCache = ScopedCache.make({\n            lookup: hashEffect(salt),\n            capacity,\n            timeToLive: Duration.infinity\n          })\n          const { hits, misses, size } = yield* pipe(\n            scopedCache,\n            Effect.flatMap((cache) =>\n              pipe(\n                Effect.forEach(\n                  Array.map(Array.range(1, capacity), (n) => (n / 2) | 0),\n                  (n) => Effect.scoped(Effect.zipRight(cache.get(n), Effect.void)),\n                  { concurrency: \"unbounded\", discard: true }\n                ),\n                Effect.flatMap(() => cache.cacheStats)\n              )\n            )\n          )\n          strictEqual(hits, 4)\n          strictEqual(misses, 6)\n          strictEqual(size, 6)\n        })\n        return Effect.runPromise(Effect.scoped(program))\n      })\n    ))\n\n  it.effect(\"invalidate - should properly remove and clean a resource from the cache\", () =>\n    Effect.gen(function*() {\n      const capacity = 100\n      const observablesResources = yield* (\n        Effect.forEach(\n          Array.range(0, capacity - 1),\n          () => ObservableResource.makeVoid()\n        )\n      )\n      const scopedCache = ScopedCache.make({\n        capacity,\n        timeToLive: Duration.infinity,\n        lookup: (key: number) => observablesResources[key].scoped\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        yield* (Effect.forEach(\n          Array.range(0, capacity - 1),\n          (n) => Effect.scoped(Effect.zipRight(cache.get(n), Effect.void)),\n          { concurrency: \"unbounded\", discard: true }\n        ))\n        yield* (cache.invalidate(42))\n        const cacheContainsKey42 = yield* (cache.contains(42))\n        const { hits, misses, size } = yield* (cache.cacheStats)\n        yield* (observablesResources[42].assertAcquiredOnceAndCleaned())\n        yield* (Effect.forEach(\n          pipe(\n            observablesResources,\n            Array.filter((_, index) => index !== 42)\n          ),\n          (observableResource) => observableResource.assertAcquiredOnceAndNotCleaned()\n        ))\n        assertFalse(cacheContainsKey42)\n        strictEqual(hits, 0)\n        strictEqual(misses, 100)\n        strictEqual(size, 99)\n      })))\n    }))\n\n  it.effect(\"invalidate - should not invalidate anything before effect is evaluated\", () =>\n    Effect.gen(function*() {\n      const observablesResource = yield* (ObservableResource.makeVoid())\n      const scopedCache = ScopedCache.make({\n        capacity: 4,\n        timeToLive: Duration.infinity,\n        lookup: () => observablesResource.scoped\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        yield* (Effect.scoped(Effect.zipRight(cache.get(void 0), Effect.void)))\n        const invalidateEffect = cache.invalidate(void 0)\n        const cacheContainsKey42BeforeInvalidate = yield* (cache.contains(void 0))\n        yield* (observablesResource.assertAcquiredOnceAndNotCleaned())\n        yield* (Effect.scoped(Effect.zipRight(cache.get(void 0), Effect.void)))\n        yield* invalidateEffect\n        const cacheContainsKey42AfterInvalidate = yield* (cache.contains(void 0))\n        yield* (observablesResource.assertAcquiredOnceAndCleaned())\n        assertTrue(cacheContainsKey42BeforeInvalidate)\n        assertFalse(cacheContainsKey42AfterInvalidate)\n      })))\n    }))\n\n  it.effect(\"invalidateAll - should properly remove and clean all resource from the cache\", () =>\n    Effect.gen(function*() {\n      const capacity = 100\n      const observablesResources = yield* (\n        Effect.forEach(\n          Array.range(0, capacity - 1),\n          () => ObservableResource.makeVoid()\n        )\n      )\n      const scopedCache = ScopedCache.make({\n        capacity,\n        timeToLive: Duration.infinity,\n        lookup: (key: number) => observablesResources[key].scoped\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        yield* (Effect.forEach(\n          Array.range(0, capacity - 1),\n          (n) => Effect.scoped(Effect.zipRight(cache.get(n), Effect.void)),\n          { concurrency: \"unbounded\", discard: true }\n        ))\n        yield* (cache.invalidateAll)\n        const contains = yield* pipe(\n          Effect.forEach(\n            Array.range(0, capacity - 1),\n            (n) => Effect.scoped(cache.contains(n)),\n            { concurrency: \"unbounded\" }\n          ),\n          Effect.map((_) => _.every(identity))\n        )\n        const { hits, misses, size } = yield* (cache.cacheStats)\n        yield* (Effect.forEach(\n          observablesResources,\n          (observableResource) => observableResource.assertAcquiredOnceAndCleaned()\n        ))\n        assertFalse(contains)\n        strictEqual(hits, 0)\n        strictEqual(misses, 100)\n        strictEqual(size, 0)\n      })))\n    }))\n\n  it.effect(\"get - should not put anything in the cache before the scoped effect returned by get is used\", () =>\n    Effect.gen(function*() {\n      const observablesResource = yield* (ObservableResource.makeVoid())\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.seconds(60),\n        lookup: () => observablesResource.scoped\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        yield* (observablesResource.assertNotAcquired())\n        // Not actually retreiving from the cache\n        // @effect-diagnostics-next-line floatingEffect:off\n        cache.get(void 0)\n        yield* (observablesResource.assertNotAcquired())\n        const contains = yield* (cache.contains(void 0))\n        assertFalse(contains)\n      })))\n    }))\n\n  it(\"get - when used sequentially, should properly call correct lookup\", () =>\n    fc.assert(fc.asyncProperty(fc.integer(), (salt) => {\n      const program = Effect.gen(function*() {\n        const scopedCache = ScopedCache.make({\n          capacity: 10,\n          timeToLive: Duration.infinity,\n          lookup: hashEffect(salt)\n        })\n        yield* (Effect.scoped(Effect.gen(function*() {\n          const cache = yield* scopedCache\n          const actual = yield* (\n            Effect.forEach(\n              Array.range(1, 10),\n              (n) => Effect.scoped(Effect.flatMap(cache.get(n), Effect.succeed))\n            )\n          )\n          const expected = Array.map(Array.range(1, 10), hash(salt))\n          deepStrictEqual(actual, expected)\n        })))\n      })\n      return Effect.runPromise(program)\n    })))\n\n  it(\"get - when used concurrently, should properly call correct lookup\", () =>\n    fc.assert(fc.asyncProperty(fc.integer(), (salt) => {\n      const program = Effect.gen(function*() {\n        const scopedCache = ScopedCache.make({\n          capacity: 10,\n          timeToLive: Duration.infinity,\n          lookup: hashEffect(salt)\n        })\n        yield* (Effect.scoped(Effect.gen(function*() {\n          const cache = yield* scopedCache\n          const actual = yield* (\n            Effect.forEach(\n              Array.range(1, 10),\n              (n) => Effect.scoped(Effect.flatMap(cache.get(n), Effect.succeed)),\n              { concurrency: \"unbounded\" }\n            )\n          )\n          const expected = Array.map(Array.range(1, 10), hash(salt))\n          deepStrictEqual(actual, expected)\n        })))\n      })\n      return Effect.runPromise(program)\n    })))\n\n  it(\"get - should clean and remove old resource to respect cache capacity\", () =>\n    fc.assert(fc.asyncProperty(fc.integer(), (salt) => {\n      const program = Effect.gen(function*() {\n        const scopedCache = ScopedCache.make({\n          capacity: 5,\n          timeToLive: Duration.infinity,\n          lookup: hashEffect(salt)\n        })\n        yield* (Effect.scoped(Effect.gen(function*() {\n          const cache = yield* scopedCache\n          const actual = yield* (\n            Effect.forEach(\n              Array.range(1, 10),\n              (n) => Effect.scoped(Effect.flatMap(cache.get(n), Effect.succeed))\n            )\n          )\n          const expected = Array.map(Array.range(1, 10), hash(salt))\n          const cacheStats = yield* (cache.cacheStats)\n          deepStrictEqual(actual, expected)\n          strictEqual(cacheStats.size, 5)\n        })))\n      })\n      return Effect.runPromise(program)\n    })))\n\n  it.effect(\"get - sequential use of the scoped effect returned by a single call to get should create only one resource\", () =>\n    Effect.gen(function*() {\n      const subResource = yield* (ObservableResource.makeVoid())\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.seconds(60),\n        lookup: (_: void) => subResource.scoped\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        yield* (subResource.assertNotAcquired())\n        const resourceScopedProxy = cache.get(void 0)\n        yield* (subResource.assertNotAcquired())\n        yield* (Effect.scoped(resourceScopedProxy))\n        yield* (subResource.assertAcquiredOnceAndNotCleaned())\n        yield* (Effect.scoped(resourceScopedProxy))\n        yield* (subResource.assertAcquiredOnceAndNotCleaned())\n      })))\n      yield* (subResource.assertAcquiredOnceAndCleaned())\n    }))\n\n  it.effect(\"get - sequential use should create only one resource\", () =>\n    Effect.gen(function*() {\n      const subResource = yield* (ObservableResource.makeVoid())\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.seconds(60),\n        lookup: (_: void) => subResource.scoped\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        yield* (subResource.assertNotAcquired())\n        yield* (Effect.scoped(cache.get(void 0)))\n        yield* (subResource.assertAcquiredOnceAndNotCleaned())\n        yield* (Effect.scoped(cache.get(void 0)))\n        yield* (subResource.assertAcquiredOnceAndNotCleaned())\n      })))\n      yield* (subResource.assertAcquiredOnceAndCleaned())\n    }))\n\n  it.effect(\"get - sequential use of a failing scoped effect should cache the error and immediately call the resource finalizer\", () =>\n    Effect.gen(function*() {\n      const watchableLookup = yield* (\n        WatchableLookup.makeEffect<void, never, Cause.RuntimeException>(() =>\n          Effect.fail(new Cause.RuntimeException(\"fail\"))\n        )\n      )\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.seconds(60),\n        lookup: (key: void) => watchableLookup(key)\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 0)))\n        const resourceScopedProxy = cache.get(void 0)\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 0)))\n        yield* (Effect.either(Effect.scoped(resourceScopedProxy)))\n        yield* (watchableLookup.assertAllCleanedForKey(void 0))\n        yield* (Effect.either(Effect.scoped(resourceScopedProxy)))\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 1)))\n      })))\n    }))\n\n  it.effect(\"get - concurrent use of the scoped effect returned by a single call to get should create only one resource\", () =>\n    Effect.gen(function*() {\n      const subResource = yield* (ObservableResource.makeVoid())\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.seconds(60),\n        lookup: (_: void) => subResource.scoped\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        const scoped = cache.get(void 0)\n        const scope1 = yield* (Scope.make())\n        const scope2 = yield* (Scope.make())\n        const acquire1 = Effect.provide(scoped, Context.make(Scope.Scope, scope1))\n        const release1: Scope.Scope.Finalizer = (exit) => Scope.close(scope1, exit)\n        const acquire2 = Effect.provide(scoped, Context.make(Scope.Scope, scope2))\n        const release2: Scope.Scope.Finalizer = (exit) => Scope.close(scope2, exit)\n        yield* (subResource.assertNotAcquired())\n        yield* acquire2\n        yield* (subResource.assertAcquiredOnceAndNotCleaned())\n        yield* acquire1\n        yield* (subResource.assertAcquiredOnceAndNotCleaned())\n        yield* (release2(Exit.void))\n        yield* (release1(Exit.void))\n        yield* (subResource.assertAcquiredOnceAndNotCleaned())\n      })))\n      yield* (subResource.assertAcquiredOnceAndCleaned())\n    }))\n\n  it.effect(\"get - concurrent use on a failing scoped effect should cache the error and immediately call the resource finalizer\", () =>\n    Effect.gen(function*() {\n      const watchableLookup = yield* (\n        WatchableLookup.makeEffect<void, never, Cause.RuntimeException>(() =>\n          Effect.fail(new Cause.RuntimeException(\"fail\"))\n        )\n      )\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.seconds(60),\n        lookup: (key: void) => watchableLookup(key)\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 0)))\n        const resourceScopedProxy = cache.get(void 0)\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 0)))\n        yield* (Effect.zip(\n          Effect.either(Effect.scoped(resourceScopedProxy)),\n          Effect.either(Effect.scoped(resourceScopedProxy)),\n          { concurrent: true }\n        ))\n        yield* (watchableLookup.assertAllCleanedForKey(void 0))\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 1)))\n      })))\n    }))\n\n  it.effect(\"get - when two scoped effects returned by two calls to get live longer than the cache, the resource should be cleaned only when it is not in use anymore\", () =>\n    Effect.gen(function*() {\n      const subResource = yield* (ObservableResource.makeVoid())\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.seconds(60),\n        lookup: (_: void) => subResource.scoped\n      })\n      const scope1 = yield* (Scope.make())\n      const scope2 = yield* (Scope.make())\n      const [release1, release2] = yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        yield* (Effect.provide(\n          cache.get(void 0),\n          Context.make(Scope.Scope, scope1)\n        ))\n        yield* (Effect.provide(\n          cache.get(void 0),\n          Context.make(Scope.Scope, scope2)\n        ))\n        const release1: Scope.Scope.Finalizer = (exit) => Scope.close(scope1, exit)\n        const release2: Scope.Scope.Finalizer = (exit) => Scope.close(scope2, exit)\n        return [release1, release2] as const\n      })))\n      yield* (subResource.assertAcquiredOnceAndNotCleaned())\n      yield* (release1(Exit.void))\n      yield* (subResource.assertAcquiredOnceAndNotCleaned())\n      yield* (release2(Exit.void))\n      yield* (subResource.assertAcquiredOnceAndCleaned())\n    }))\n\n  it.effect(\"get - when two scoped effects obtained by a single scoped effect returned by a single call to get live longer than the cache, the resource should be cleaned only when it is not in use anymore\", () =>\n    Effect.gen(function*() {\n      const subResource = yield* (ObservableResource.makeVoid())\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.seconds(60),\n        lookup: (_: void) => subResource.scoped\n      })\n      const scope1 = yield* (Scope.make())\n      const scope2 = yield* (Scope.make())\n      const [release1, release2] = yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        const scoped = cache.get(void 0)\n        yield* (Effect.provide(scoped, Context.make(Scope.Scope, scope1)))\n        yield* (Effect.provide(scoped, Context.make(Scope.Scope, scope2)))\n        const release1: Scope.Scope.Finalizer = (exit) => Scope.close(scope1, exit)\n        const release2: Scope.Scope.Finalizer = (exit) => Scope.close(scope2, exit)\n        return [release1, release2] as const\n      })))\n      yield* (subResource.assertAcquiredOnceAndNotCleaned())\n      yield* (release1(Exit.void))\n      yield* (subResource.assertAcquiredOnceAndNotCleaned())\n      yield* (release2(Exit.void))\n      yield* (subResource.assertAcquiredOnceAndCleaned())\n    }))\n\n  it(\"get - should clean old resources if the cache size is exceeded\", () => {\n    const arb = fc.integer({ min: 1, max: 5 }).chain((cacheSize) =>\n      fc.integer({ min: cacheSize, max: cacheSize + 3 })\n        .map((numCreatedKey) => [cacheSize, numCreatedKey] as const)\n    )\n    return fc.assert(fc.asyncProperty(arb, ([cacheSize, numCreatedKey]) => {\n      const program = Effect.gen(function*() {\n        const watchableLookup = yield* (WatchableLookup.make<number, void>(() => void 0))\n        const scopedCache = ScopedCache.make({\n          capacity: cacheSize,\n          timeToLive: Duration.seconds(60),\n          lookup: (key: number) => watchableLookup(key)\n        })\n        yield* (Effect.scoped(Effect.gen(function*() {\n          const cache = yield* scopedCache\n          yield* (\n            Effect.forEach(\n              Array.range(0, numCreatedKey - 1),\n              (key) => Effect.scoped(Effect.asVoid(cache.get(key))),\n              { discard: true }\n            )\n          )\n          const createdResources = yield* (watchableLookup.createdResources())\n          const cleanedAssertions = numCreatedKey - cacheSize - 1\n          const oldestResourceCleaned = cleanedAssertions <= 0\n            ? Array.empty()\n            : pipe(\n              Array.range(0, numCreatedKey - cacheSize - 1),\n              Array.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))),\n              Array.map((resource) => resource.assertAcquiredOnceAndCleaned())\n            )\n          yield* (Effect.all(oldestResourceCleaned, { discard: true }))\n          const newestResourceNotCleanedYet = pipe(\n            Array.range(numCreatedKey - cacheSize, numCreatedKey - 1),\n            Array.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))),\n            Array.map((resource) => resource.assertAcquiredOnceAndNotCleaned())\n          )\n          yield* (Effect.all(newestResourceNotCleanedYet, { discard: true }))\n        })))\n      })\n      return Effect.runPromise(program)\n    }))\n  })\n\n  it.effect(\"get - the scoped effect returned by get should recall lookup function if resource is too old and release the previous resource\", () =>\n    Effect.gen(function*() {\n      const watchableLookup = yield* (WatchableLookup.makeVoid())\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* (ScopedCache.make({\n          capacity: 10,\n          timeToLive: Duration.seconds(10),\n          lookup: (key: void) => watchableLookup(key)\n        }))\n        const scoped = cache.get(void 0)\n        yield* (Effect.scoped(Effect.asVoid(scoped)))\n        yield* (TestClock.adjust(Duration.seconds(5)))\n        yield* (Effect.scoped(Effect.asVoid(scoped)))\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 1)))\n        yield* (TestClock.adjust(Duration.seconds(4)))\n        yield* (Effect.scoped(Effect.asVoid(scoped)))\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 1)))\n        yield* (TestClock.adjust(Duration.seconds(2)))\n        yield* (Effect.scoped(Effect.asVoid(scoped)))\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 2)))\n        yield* (watchableLookup.assertFirstNCreatedResourcesCleaned(void 0, 1))\n      })))\n    }))\n\n  it.effect(\"get - should recall lookup function if resource is too old and release old resource when using the scoped effect multiple times\", () =>\n    Effect.gen(function*() {\n      const watchableLookup = yield* (WatchableLookup.makeVoid())\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* (ScopedCache.make({\n          capacity: 10,\n          timeToLive: Duration.seconds(10),\n          lookup: (key: void) => watchableLookup(key)\n        }))\n        const scoped = Effect.scoped(Effect.asVoid(cache.get(void 0)))\n        yield* scoped\n        yield* (TestClock.adjust(Duration.seconds(5)))\n        yield* scoped\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 1)))\n        yield* (TestClock.adjust(Duration.seconds(4)))\n        yield* scoped\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 1)))\n        yield* (TestClock.adjust(Duration.seconds(2)))\n        yield* scoped\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 2)))\n        yield* (watchableLookup.assertFirstNCreatedResourcesCleaned(void 0, 1))\n      })))\n    }))\n\n  it.effect(\"get - when resource is expired but still used it should wait until resource is not cleaned anymore to clean immediately\", () =>\n    Effect.gen(function*() {\n      const watchableLookup = yield* (WatchableLookup.makeVoid())\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* (ScopedCache.make({\n          capacity: 10,\n          timeToLive: Duration.seconds(10),\n          lookup: (key: void) => watchableLookup(key)\n        }))\n        const scope = yield* (Scope.make())\n        const acquire = Effect.provide(\n          cache.get(void 0),\n          Context.make(Scope.Scope, scope)\n        )\n        const release: Scope.Scope.Finalizer = (exit) => Scope.close(scope, exit)\n        yield* acquire\n        yield* (TestClock.adjust(Duration.seconds(11)))\n        yield* (Effect.scoped(Effect.asVoid(cache.get(void 0))))\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 2)))\n        const firstCreatedResource = yield* (watchableLookup.firstCreatedResource(void 0))\n        yield* (firstCreatedResource.assertAcquiredOnceAndNotCleaned())\n        yield* (release(Exit.void))\n        yield* (firstCreatedResource.assertAcquiredOnceAndCleaned())\n      })))\n    }))\n\n  it.effect(\"getOption - should return None if resource is not in cache\", () =>\n    Effect.scoped(Effect.gen(function*() {\n      const scopedCache = yield* (ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.infinity,\n        lookup: (i: number) => Effect.succeed(i)\n      }))\n      const option = yield* (scopedCache.getOption(1))\n      assertNone(option)\n    })))\n\n  it.effect(\"getOption - should return Some if pending\", () =>\n    Effect.scoped(Effect.gen(function*() {\n      const scopedCache = yield* (ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.infinity,\n        lookup: (i: number) => TestServices.provideLive(Effect.delay(Effect.succeed(i), Duration.millis(10)))\n      }))\n      yield* pipe(scopedCache.get(1), Effect.scoped, Effect.fork)\n      yield* (TestServices.provideLive(Effect.sleep(Duration.millis(5))))\n      const option = yield* pipe(scopedCache.getOption(1), Effect.scoped)\n      assertSome(option, 1)\n    })))\n\n  it.effect(\"getOptionComplete - should return None if pending\", () =>\n    Effect.scoped(Effect.gen(function*() {\n      const scopedCache = yield* (ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.infinity,\n        lookup: (i: number) => Effect.delay(Effect.succeed(i), Duration.millis(10))\n      }))\n      yield* pipe(scopedCache.get(1), Effect.scoped, Effect.fork)\n      yield* (TestClock.adjust(Duration.millis(9)))\n      const option = yield* pipe(scopedCache.getOptionComplete(1), Effect.scoped)\n      assertNone(option)\n    })))\n\n  it.effect(\"getOptionComplete - should return Some if complete\", () =>\n    Effect.scoped(Effect.gen(function*() {\n      const scopedCache = yield* (ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.infinity,\n        lookup: (i: number) => TestServices.provideLive(Effect.delay(Effect.succeed(i), Duration.millis(10)))\n      }))\n      yield* pipe(scopedCache.get(1), Effect.scoped)\n      const option = yield* pipe(scopedCache.getOptionComplete(1), Effect.scoped)\n      assertSome(option, 1)\n    })))\n\n  it.effect(\"refresh - should update the cache with a new value\", () =>\n    Effect.gen(function*() {\n      const inc = (n: number) => n * 10\n      const retrieve = (multiplier: Ref.Ref<number>) => (key: number) =>\n        pipe(\n          Ref.updateAndGet(multiplier, inc),\n          Effect.map((multiplier) => key * multiplier)\n        )\n      const seed = 1\n      const key = 123\n      const ref = yield* (Ref.make(seed))\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.infinity,\n        lookup: retrieve(ref)\n      })\n      const [val1, val2, val3] = yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        const val1 = yield* (cache.get(key))\n        yield* (cache.refresh(key))\n        const val2 = yield* (cache.get(key))\n        const val3 = yield* (cache.get(key))\n        return [val1, val2, val3] as const\n      })))\n      strictEqual(val2, val3)\n      strictEqual(val2, inc(val1))\n    }))\n\n  it.effect(\"refresh - should clean old resource when making a new one\", () =>\n    Effect.gen(function*() {\n      const watchableLookup = yield* (WatchableLookup.makeVoid())\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.infinity,\n        lookup: (key: void) => watchableLookup(key)\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        yield* (Effect.scoped(cache.get(void 0)))\n        yield* (cache.refresh(void 0))\n        const createdResources = yield* pipe(\n          watchableLookup.createdResources(),\n          Effect.map(HashMap.unsafeGet(void 0))\n        )\n        yield* (Chunk.unsafeHead(createdResources).assertAcquiredOnceAndCleaned())\n        yield* (Chunk.unsafeGet(createdResources, 1).assertAcquiredOnceAndNotCleaned())\n      })))\n    }))\n\n  it.effect(\"refresh - should update the cache with a new value even if the last get or refresh failed\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Must be a multiple of 3\")\n      const inc = (n: number) => n + 1\n      const retrieve = (number: Ref.Ref<number>) => (key: number) =>\n        pipe(\n          Ref.updateAndGet(number, inc),\n          Effect.flatMap((n) =>\n            n % 3 === 0\n              ? Effect.fail(error)\n              : Effect.succeed(key * n)\n          )\n        )\n      const seed = 2\n      const key = 1\n      const ref = yield* (Ref.make(seed))\n      const scopedCache = ScopedCache.make({\n        capacity: 1,\n        timeToLive: Duration.infinity,\n        lookup: retrieve(ref)\n      })\n      const result = yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        const failure1 = yield* (Effect.either(cache.get(key)))\n        yield* (cache.refresh(key))\n        const value1 = yield* (Effect.either(cache.get(key)))\n        yield* (cache.refresh(key))\n        const failure2 = yield* (Effect.either(cache.refresh(key)))\n        yield* (cache.refresh(key))\n        const value2 = yield* (Effect.either(cache.get(key)))\n        return { failure1, value1, failure2, value2 }\n      })))\n      assertLeft(result.failure1, error)\n      assertLeft(result.failure2, error)\n      assertRight(result.value1, 4)\n      assertRight(result.value2, 7)\n    }))\n\n  it.effect(\"refresh - should create and acquire subresource if the key doesn't exist in the cache\", () =>\n    Effect.gen(function*() {\n      const capacity = 100\n      const scopedCache = ScopedCache.make({\n        capacity,\n        timeToLive: Duration.infinity,\n        lookup: (_: number) => Effect.void\n      })\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* scopedCache\n        const count0 = yield* (cache.size)\n        yield* (Effect.forEach(Array.range(1, capacity), (key) => cache.refresh(key), { discard: true }))\n        const count1 = yield* (cache.size)\n        strictEqual(count0, 0)\n        strictEqual(count1, capacity)\n      })))\n    }))\n\n  it(\"refresh - should clean old resource if cache size is exceeded\", () => {\n    const arb = fc.integer({ min: 1, max: 5 }).chain((cacheSize) =>\n      fc.integer({ min: cacheSize, max: cacheSize + 3 })\n        .map((numCreatedKey) => [cacheSize, numCreatedKey] as const)\n    )\n    return fc.assert(fc.asyncProperty(arb, ([cacheSize, numCreatedKey]) => {\n      const program = Effect.gen(function*() {\n        const watchableLookup = yield* (WatchableLookup.make<number, void>(() => void 0))\n        const scopedCache = ScopedCache.make({\n          capacity: cacheSize,\n          timeToLive: Duration.seconds(60),\n          lookup: (key: number) => watchableLookup(key)\n        })\n        yield* (Effect.scoped(Effect.gen(function*() {\n          const cache = yield* scopedCache\n          yield* (Effect.forEach(\n            Array.range(0, numCreatedKey - 1),\n            (key) => cache.refresh(key),\n            { discard: true }\n          ))\n          const createdResources = yield* (watchableLookup.createdResources())\n          const cleanedAssertions = numCreatedKey - cacheSize - 1\n          const oldestResourceCleaned = cleanedAssertions <= 0\n            ? Array.empty()\n            : pipe(\n              Array.range(0, numCreatedKey - cacheSize - 1),\n              Array.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))),\n              Array.map((resource) => resource.assertAcquiredOnceAndCleaned())\n            )\n          yield* (Effect.all(oldestResourceCleaned, { discard: true }))\n          const newestResourceNotCleanedYet = pipe(\n            Array.range(numCreatedKey - cacheSize, numCreatedKey - 1),\n            Array.flatMap((key) => Chunk.toReadonlyArray(HashMap.unsafeGet(createdResources, key))),\n            Array.map((resource) => resource.assertAcquiredOnceAndNotCleaned())\n          )\n          yield* (Effect.all(newestResourceNotCleanedYet, { discard: true }))\n        })))\n      })\n      return Effect.runPromise(program)\n    }))\n  })\n\n  it.effect(\"refresh - should not clean the resource if it's not yet expired until the new resource is ready\", () =>\n    Effect.gen(function*() {\n      const watchableLookup = yield* (WatchableLookup.makeVoid())\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* (ScopedCache.make({\n          capacity: 10,\n          timeToLive: Duration.seconds(10),\n          lookup: watchableLookup\n        }))\n        yield* (Effect.scoped(Effect.asVoid(cache.get(void 0))))\n        yield* (TestClock.adjust(Duration.seconds(9)))\n        yield* (watchableLookup.lock())\n        const refreshFiber = yield* (Effect.fork(cache.refresh(void 0)))\n        yield* pipe(\n          watchableLookup.getCalledTimes(void 0),\n          Effect.repeat(pipe(\n            Schedule.recurWhile<number>((calledTimes) => calledTimes < 2),\n            Schedule.compose(Schedule.elapsed),\n            Schedule.whileOutput((elapsed) => Duration.lessThan(elapsed, Duration.millis(100)))\n          ))\n        )\n        yield* (TestServices.provideLive(Effect.sleep(Duration.millis(100))))\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 2)))\n        const firstCreatedResource = yield* (watchableLookup.firstCreatedResource(void 0))\n        yield* (firstCreatedResource.assertAcquiredOnceAndNotCleaned())\n        yield* (watchableLookup.unlock())\n        yield* (Fiber.join(refreshFiber))\n        yield* (firstCreatedResource.assertAcquiredOnceAndCleaned())\n      })))\n    }))\n\n  it.effect(\"refresh - should clean the resource if it's expired and not in used\", () =>\n    Effect.gen(function*() {\n      const watchableLookup = yield* (WatchableLookup.makeVoid())\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* (ScopedCache.make({\n          capacity: 10,\n          timeToLive: Duration.seconds(10),\n          lookup: watchableLookup\n        }))\n        yield* (Effect.scoped(Effect.asVoid(cache.get(void 0))))\n        yield* (TestClock.adjust(Duration.seconds(11)))\n        yield* (watchableLookup.lock())\n        const refreshFiber = yield* (Effect.fork(cache.refresh(void 0)))\n        yield* pipe(\n          watchableLookup.getCalledTimes(void 0),\n          Effect.repeat(pipe(\n            Schedule.recurWhile<number>((calledTimes) => calledTimes < 1),\n            Schedule.compose(Schedule.elapsed),\n            Schedule.whileOutput((elapsed) => Duration.lessThan(elapsed, Duration.millis(100)))\n          ))\n        )\n        yield* (TestServices.provideLive(Effect.sleep(Duration.millis(100))))\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 2)))\n        yield* (watchableLookup.assertFirstNCreatedResourcesCleaned(void 0, 1))\n        yield* (watchableLookup.unlock())\n        yield* (Fiber.join(refreshFiber))\n      })))\n    }))\n\n  it.effect(\"refresh - should wait to clean expired resource until it's not in use anymore\", () =>\n    Effect.gen(function*() {\n      const watchableLookup = yield* (WatchableLookup.makeVoid())\n      yield* (Effect.scoped(Effect.gen(function*() {\n        const cache = yield* (ScopedCache.make({\n          capacity: 10,\n          timeToLive: Duration.seconds(10),\n          lookup: watchableLookup\n        }))\n        const scope = yield* (Scope.make())\n        const acquire = Effect.provide(\n          cache.get(void 0),\n          Context.make(Scope.Scope, scope)\n        )\n        const release: Scope.Scope.Finalizer = (exit) => Scope.close(scope, exit)\n        yield* acquire\n        yield* (TestClock.adjust(Duration.seconds(11)))\n        yield* (cache.refresh(void 0))\n        yield* (watchableLookup.assertCalledTimes(void 0, (n) => strictEqual(n, 2)))\n        const firstCreatedResource = yield* (watchableLookup.firstCreatedResource(void 0))\n        yield* (firstCreatedResource.assertAcquiredOnceAndNotCleaned())\n        yield* (release(Exit.void))\n        yield* (firstCreatedResource.assertAcquiredOnceAndCleaned())\n      })))\n    }))\n  it.effect(\".pipe\", () =>\n    Effect.gen(function*() {\n      const cache = yield* pipe(\n        ScopedCache.make({\n          capacity: 10,\n          timeToLive: Duration.seconds(10),\n          lookup: () => Effect.void\n        }),\n        Effect.scoped\n      )\n      strictEqual(cache.pipe(identity), cache)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/ScopedRef.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport { Effect, identity, pipe, ScopedRef } from \"effect\"\nimport * as Counter from \"./utils/counter.js\"\n\ndescribe(\"ScopedRef\", () => {\n  it.scoped(\"single set\", () =>\n    Effect.gen(function*() {\n      const counter = yield* (Counter.make())\n      const ref = yield* (ScopedRef.make(() => 0))\n      yield* (ScopedRef.set(ref, counter.acquire()))\n      const result = yield* (ScopedRef.get(ref))\n      strictEqual(result, 1)\n    }))\n  it.scoped(\"dual set\", () =>\n    Effect.gen(function*() {\n      const counter = yield* (Counter.make())\n      const ref = yield* (ScopedRef.make(() => 0))\n      yield* pipe(\n        ScopedRef.set(ref, counter.acquire()),\n        Effect.zipRight(ScopedRef.set(ref, counter.acquire()))\n      )\n      const result = yield* (ScopedRef.get(ref))\n      strictEqual(result, 2)\n    }))\n  it.scoped(\"release on swap\", () =>\n    Effect.gen(function*() {\n      const counter = yield* (Counter.make())\n      const ref = yield* (ScopedRef.make(() => 0))\n      yield* pipe(\n        ScopedRef.set(ref, counter.acquire()),\n        Effect.zipRight(ScopedRef.set(ref, counter.acquire()))\n      )\n\n      const acquired = yield* (counter.acquired())\n      const released = yield* (counter.released())\n      strictEqual(acquired, 2)\n      strictEqual(released, 1)\n    }))\n  it.scoped(\"double release on double swap\", () =>\n    Effect.gen(function*() {\n      const counter = yield* (Counter.make())\n      const ref = yield* (ScopedRef.make(() => 0))\n      yield* (\n        pipe(\n          ScopedRef.set(ref, counter.acquire()),\n          Effect.zipRight(ScopedRef.set(ref, counter.acquire())),\n          Effect.zipRight(ScopedRef.set(ref, counter.acquire()))\n        )\n      )\n      const acquired = yield* (counter.acquired())\n      const released = yield* (counter.released())\n      strictEqual(acquired, 3)\n      strictEqual(released, 2)\n    }))\n  it.effect(\"full release\", () =>\n    Effect.gen(function*() {\n      const counter = yield* (Counter.make())\n      yield* pipe(\n        ScopedRef.make(() => 0),\n        Effect.flatMap((ref) =>\n          pipe(\n            ScopedRef.set(ref, counter.acquire()),\n            Effect.zipRight(ScopedRef.set(ref, counter.acquire())),\n            Effect.zipRight(ScopedRef.set(ref, counter.acquire()))\n          )\n        ),\n        Effect.scoped\n      )\n      const acquired = yield* (counter.acquired())\n      const released = yield* (counter.released())\n      strictEqual(acquired, 3)\n      strictEqual(released, 3)\n    }))\n  it.effect(\"full release\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Effect.scoped(ScopedRef.make(() => 0))\n      strictEqual(ref.pipe(identity), ref)\n    }))\n  it.scoped(\"subtype of Effect\", () =>\n    Effect.gen(function*() {\n      const ref = yield* ScopedRef.make(() => 0)\n      const result = yield* ref\n      strictEqual(result, 0)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/collecting.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { constTrue, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"collectAllN - respects the given limit\", () =>\n    Effect.gen(function*() {\n      const stream = pipe(\n        Stream.fromChunk(Chunk.make(1, 2, 3, 4)),\n        Stream.transduce(Sink.collectAllN<number>(3))\n      )\n      const result = yield* (Stream.runCollect(stream))\n      deepStrictEqual(\n        Array.from(Chunk.map(result, (chunk) => Array.from(chunk))),\n        [[1, 2, 3], [4]]\n      )\n    }))\n\n  it.effect(\"collectAllN - produces empty trailing chunks\", () =>\n    Effect.gen(function*() {\n      const stream = pipe(\n        Stream.fromChunk(Chunk.make(1, 2, 3, 4)),\n        Stream.transduce(Sink.collectAllN<number>(4))\n      )\n      const result = yield* (Stream.runCollect(stream))\n      deepStrictEqual(\n        Array.from(Chunk.map(result, (chunk) => Array.from(chunk))),\n        [[1, 2, 3, 4], []]\n      )\n    }))\n\n  it.effect(\"collectAllN - produces empty trailing chunks\", () =>\n    Effect.gen(function*() {\n      const stream = pipe(\n        Stream.fromChunk(Chunk.empty<number>()),\n        Stream.transduce(Sink.collectAllN<number>(3))\n      )\n      const result = yield* (Stream.runCollect(stream))\n      deepStrictEqual(\n        Array.from(Chunk.map(result, (chunk) => Array.from(chunk))),\n        [[]]\n      )\n    }))\n\n  it.effect(\"collectAllToSet\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 3, 4)\n      const result = yield* pipe(stream, Stream.run(Sink.collectAllToSet()))\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"collectAllToSetN - respects the given limit\", () =>\n    Effect.gen(function*() {\n      const stream = pipe(\n        Stream.fromChunks(Chunk.make(1, 2, 1), Chunk.make(2, 3, 3, 4)),\n        Stream.transduce(Sink.collectAllToSetN<number>(3))\n      )\n      const result = yield* (Stream.runCollect(stream))\n      deepStrictEqual(\n        Array.from(Chunk.map(result, (set) => Array.from(set))),\n        [[1, 2, 3], [4]]\n      )\n    }))\n\n  it.effect(\"collectAllToSetN - handles empty input\", () =>\n    Effect.gen(function*() {\n      const stream = pipe(\n        Stream.fromChunk(Chunk.empty<number>()),\n        Stream.transduce(Sink.collectAllToSetN<number>(3))\n      )\n      const result = yield* (Stream.runCollect(stream))\n      deepStrictEqual(\n        Array.from(Chunk.map(result, (set) => Array.from(set))),\n        [[]]\n      )\n    }))\n\n  it.effect(\"collectAllToMap\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(0, 9),\n        Stream.run(Sink.collectAllToMap(\n          (n) => n % 3,\n          (x, y) => x + y\n        ))\n      )\n      deepStrictEqual(\n        Array.from(result),\n        [[0, 18], [1, 12], [2, 15]]\n      )\n    }))\n\n  it.effect(\"collectAllToMapN - respects the given limit\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 1, 2, 2, 3, 2, 4, 5),\n        Stream.transduce(Sink.collectAllToMapN(\n          2,\n          (n) => n % 3,\n          (x, y) => x + y\n        )),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(Chunk.map(result, (chunk) => Array.from(chunk))),\n        [[[1, 2], [2, 4]], [[0, 3], [2, 2]], [[1, 4], [2, 5]]]\n      )\n    }))\n\n  it.effect(\"collectAllToMapN - collects as long as map size doesn't exceed the limit\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(Chunk.make(0, 1, 2), Chunk.make(3, 4, 5), Chunk.make(6, 7, 8, 9)),\n        Stream.transduce(Sink.collectAllToMapN(\n          3,\n          (n) => n % 3,\n          (x, y) => x + y\n        )),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(Chunk.map(result, (chunk) => Array.from(chunk))),\n        [[[0, 18], [1, 12], [2, 15]]]\n      )\n    }))\n\n  it.effect(\"collectAllToMapN - handles empty input\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunk(Chunk.empty<number>()),\n        Stream.transduce(Sink.collectAllToMapN(\n          3,\n          (n) => n % 3,\n          (x, y) => x + y\n        )),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(Chunk.map(result, (chunk) => Array.from(chunk))),\n        [[]]\n      )\n    }))\n\n  it.effect(\"collectAllUntil\", () =>\n    Effect.gen(function*() {\n      const sink = Sink.collectAllUntil<number>((n) => n > 4)\n      const input = Chunk.make(\n        Chunk.make(3, 4, 5, 6, 7, 2),\n        Chunk.empty<number>(),\n        Chunk.make(3, 4, 5, 6, 5, 4, 3, 2),\n        Chunk.empty<number>()\n      )\n      const result = yield* pipe(Stream.fromChunks(...input), Stream.transduce(sink), Stream.runCollect)\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[3, 4, 5], [6], [7], [2, 3, 4, 5], [6], [5], [4, 3, 2]]\n      )\n    }))\n\n  it.effect(\"collectAllUntilEffect\", () =>\n    Effect.gen(function*() {\n      const sink = Sink.collectAllUntilEffect((n: number) => Effect.succeed(n > 4))\n      const input = Chunk.make(\n        Chunk.make(3, 4, 5, 6, 7, 2),\n        Chunk.empty<number>(),\n        Chunk.make(3, 4, 5, 6, 5, 4, 3, 2),\n        Chunk.empty<number>()\n      )\n      const result = yield* pipe(Stream.fromChunks(...input), Stream.transduce(sink), Stream.runCollect)\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[3, 4, 5], [6], [7], [2, 3, 4, 5], [6], [5], [4, 3, 2]]\n      )\n    }))\n\n  it.effect(\"collectAllWhile\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.collectAllWhile<number>((n) => n < 5),\n        Sink.zipLeft(Sink.collectAllWhile<number>((n) => n >= 5))\n      )\n      const input = Chunk.make(\n        Chunk.make(3, 4, 5, 6, 7, 2),\n        Chunk.empty<number>(),\n        Chunk.make(3, 4, 5, 6, 5, 4, 3, 2),\n        Chunk.empty<number>()\n      )\n      const result = yield* pipe(Stream.fromChunks(...input), Stream.transduce(sink), Stream.runCollect)\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[3, 4], [2, 3, 4], [4, 3, 2]]\n      )\n    }))\n\n  it.effect(\"collectAllWhileEffect\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.collectAllWhileEffect((n: number) => Effect.succeed(n < 5)),\n        Sink.zipLeft(Sink.collectAllWhileEffect((n: number) => Effect.succeed(n >= 5)))\n      )\n      const input = Chunk.make(\n        Chunk.make(3, 4, 5, 6, 7, 2),\n        Chunk.empty<number>(),\n        Chunk.make(3, 4, 5, 6, 5, 4, 3, 2),\n        Chunk.empty<number>()\n      )\n      const result = yield* pipe(Stream.fromChunks(...input), Stream.transduce(sink), Stream.runCollect)\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[3, 4], [2, 3, 4], [4, 3, 2]]\n      )\n    }))\n\n  it.effect(\"collectAllWhileWith - example 1\", () =>\n    Effect.gen(function*() {\n      const program = (chunkSize: number) =>\n        pipe(\n          Stream.fromChunk(Chunk.range(1, 10)),\n          Stream.rechunk(chunkSize),\n          Stream.run(pipe(\n            Sink.sum,\n            Sink.collectAllWhileWith({\n              initial: -1,\n              while: (n) => n === n,\n              body: (acc, curr) => acc + curr\n            })\n          ))\n        )\n      const result1 = yield* (program(1))\n      const result2 = yield* (program(3))\n      const result3 = yield* (program(20))\n      strictEqual(result1, 54)\n      strictEqual(result2, 54)\n      strictEqual(result3, 54)\n    }))\n\n  it.effect(\"collectAllWhileWith - example 2\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.head<number>(),\n        Sink.collectAllWhileWith({\n          initial: Chunk.empty<number>(),\n          while: Option.match({\n            onNone: constTrue,\n            onSome: (n) => n < 5\n          }),\n          body: (acc, option) => Option.isSome(option) ? pipe(acc, Chunk.append(option.value)) : acc\n        })\n      )\n      const stream = Stream.fromChunk(Chunk.range(1, 100))\n      const result = yield* pipe(\n        stream,\n        Stream.concat(stream),\n        Stream.rechunk(3),\n        Stream.run(sink)\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/constructors.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport type * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Effectable from \"effect/Effectable\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport type * as MutableQueue from \"effect/MutableQueue\"\nimport type * as MutableRef from \"effect/MutableRef\"\nimport type * as Option from \"effect/Option\"\nimport { pipeArguments } from \"effect/Pipeable\"\nimport * as PubSub from \"effect/PubSub\"\nimport * as Queue from \"effect/Queue\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\nimport * as internalQueue from \"../../src/internal/queue.js\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"drain - fails if upstream fails\", () =>\n    Effect.gen(function*() {\n      const stream = pipe(\n        Stream.make(1),\n        Stream.mapEffect(() => Effect.fail(\"boom!\"))\n      )\n      const result = yield* pipe(stream, Stream.run(Sink.drain), Effect.exit)\n      deepStrictEqual(result, Exit.fail(\"boom!\"))\n    }))\n\n  it.effect(\"fromEffect\", () =>\n    Effect.gen(function*() {\n      const sink = Sink.fromEffect(Effect.succeed(\"ok\"))\n      const result = yield* pipe(Stream.make(1, 2, 3), Stream.run(sink))\n      deepStrictEqual(result, \"ok\")\n    }))\n\n  it.effect(\"fromQueue - should enqueue all elements\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (Queue.unbounded<number>())\n      yield* pipe(Stream.make(1, 2, 3), Stream.run(Sink.fromQueue(queue)))\n      const result = yield* (Queue.takeAll(queue))\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"fromQueueWithShutdown - should enqueue all elements and shutdown the queue\", () =>\n    Effect.gen(function*() {\n      const queue = yield* pipe(Queue.unbounded<number>(), Effect.map(createQueueSpy))\n      yield* pipe(Stream.make(1, 2, 3), Stream.run(Sink.fromQueue(queue, { shutdown: true })))\n      const enqueuedValues = yield* (Queue.takeAll(queue))\n      const isShutdown = yield* (Queue.isShutdown(queue))\n      deepStrictEqual(Array.from(enqueuedValues), [1, 2, 3])\n      assertTrue(isShutdown)\n    }))\n\n  it.effect(\"fromPubSub - should publish all elements\", () =>\n    Effect.gen(function*() {\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const pubsub = yield* (PubSub.unbounded<number>())\n      const fiber = yield* pipe(\n        PubSub.subscribe(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            Deferred.succeed(deferred1, void 0),\n            Effect.zipRight(Deferred.await(deferred2)),\n            Effect.zipRight(Queue.takeAll(subscription))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* (Deferred.await(deferred1))\n      yield* pipe(Stream.make(1, 2, 3), Stream.run(Sink.fromPubSub(pubsub)))\n      yield* (Deferred.succeed(deferred2, void 0))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"fromPubSub(_, { shutdown: true }) - should shutdown the pubsub\", () =>\n    Effect.gen(function*() {\n      const pubsub = yield* (PubSub.unbounded<number>())\n      yield* pipe(Stream.make(1, 2, 3), Stream.run(Sink.fromPubSub(pubsub, { shutdown: true })))\n      const isShutdown = yield* (PubSub.isShutdown(pubsub))\n      assertTrue(isShutdown)\n    }))\n})\n\nconst createQueueSpy = <A>(queue: Queue.Queue<A>): Queue.Queue<A> => new QueueSpy(queue)\n\nclass QueueSpy<A> extends Effectable.Class<A> implements Queue.Queue<A> {\n  readonly [Queue.DequeueTypeId] = internalQueue.dequeueVariance\n  readonly [Queue.EnqueueTypeId] = internalQueue.enqueueVariance\n  private isShutdownInternal = false\n  readonly queue: Queue.BackingQueue<A>\n  readonly shutdownFlag: MutableRef.MutableRef<boolean>\n  readonly shutdownHook: Deferred.Deferred<void, never>\n  readonly strategy: Queue.Strategy<A>\n  readonly takers: MutableQueue.MutableQueue<Deferred.Deferred<A, never>>\n\n  constructor(readonly backingQueue: Queue.Queue<A>) {\n    super()\n    this.queue = backingQueue.queue\n    this.shutdownFlag = backingQueue.shutdownFlag\n    this.shutdownHook = backingQueue.shutdownHook\n    this.strategy = backingQueue.strategy\n    this.takers = backingQueue.takers\n  }\n\n  commit() {\n    return this.take\n  }\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n\n  unsafeOffer(value: A): boolean {\n    return Queue.unsafeOffer(this.backingQueue, value)\n  }\n\n  offer(a: A) {\n    return Queue.offer(this.backingQueue, a)\n  }\n\n  offerAll(elements: Iterable<A>) {\n    return Queue.offerAll(this.backingQueue, elements)\n  }\n\n  capacity(): number {\n    return Queue.capacity(this.backingQueue)\n  }\n\n  get size(): Effect.Effect<number> {\n    return Queue.size(this.backingQueue)\n  }\n\n  unsafeSize(): Option.Option<number> {\n    return this.backingQueue.unsafeSize()\n  }\n\n  get awaitShutdown(): Effect.Effect<void> {\n    return Queue.awaitShutdown(this.backingQueue)\n  }\n\n  isActive(): boolean {\n    return !this.isShutdownInternal\n  }\n\n  get isShutdown(): Effect.Effect<boolean> {\n    return Effect.sync(() => this.isShutdownInternal)\n  }\n\n  get shutdown(): Effect.Effect<void> {\n    return Effect.sync(() => {\n      this.isShutdownInternal = true\n    })\n  }\n\n  get isFull(): Effect.Effect<boolean> {\n    return Queue.isFull(this.backingQueue)\n  }\n\n  get isEmpty(): Effect.Effect<boolean> {\n    return Queue.isEmpty(this.backingQueue)\n  }\n\n  get take(): Effect.Effect<A> {\n    return Queue.take(this.backingQueue)\n  }\n\n  get takeAll(): Effect.Effect<Chunk.Chunk<A>> {\n    return Queue.takeAll(this.backingQueue)\n  }\n\n  takeUpTo(max: number): Effect.Effect<Chunk.Chunk<A>> {\n    return Queue.takeUpTo(this.backingQueue, max)\n  }\n\n  takeBetween(min: number, max: number): Effect.Effect<Chunk.Chunk<A>> {\n    return Queue.takeBetween(this.backingQueue, min, max)\n  }\n\n  takeN(n: number): Effect.Effect<Chunk.Chunk<A>> {\n    return Queue.takeN(this.backingQueue, n)\n  }\n\n  poll(): Effect.Effect<Option.Option<A>> {\n    return Queue.poll(this.backingQueue)\n  }\n}\n"
  },
  {
    "path": "packages/effect/test/Sink/dropping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { pipe } from \"effect/Function\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"dropUntil\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4, 5, 1, 2, 3, 4, 5),\n        Stream.pipeThrough(Sink.dropUntil<number>((n) => n >= 3)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [4, 5, 1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"dropUntilEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4, 5, 1, 2, 3, 4, 5),\n        Stream.pipeThrough(Sink.dropUntilEffect((n) => Effect.succeed(n >= 3))),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [4, 5, 1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"dropUntilEffect - error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.concat(Stream.fail(\"Aie\")),\n        Stream.concat(Stream.make(5, 1, 2, 3, 4, 5)),\n        Stream.pipeThrough(Sink.dropUntilEffect((n) => Effect.succeed(n >= 2))),\n        Stream.either,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [Either.right(3), Either.left(\"Aie\")])\n    }))\n\n  it.effect(\"dropWhile\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4, 5, 1, 2, 3, 4, 5),\n        Stream.pipeThrough(Sink.dropWhile<number>((n) => n < 3)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [3, 4, 5, 1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"dropWhileEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4, 5, 1, 2, 3, 4, 5),\n        Stream.pipeThrough(Sink.dropWhileEffect((n) => Effect.succeed(n < 3))),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [3, 4, 5, 1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"dropWhileEffect - error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.concat(\n          Stream.make(1, 2, 3),\n          Stream.fail(\"Aie\")\n        ),\n        Stream.concat(Stream.make(5, 1, 2, 3, 4, 5)),\n        Stream.pipeThrough(Sink.dropWhileEffect((n) => Effect.succeed(n < 3))),\n        Stream.either,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [Either.right(3), Either.left(\"Aie\")])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/elements.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertSome, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"every\", () =>\n    Effect.gen(function*() {\n      const chunk = Chunk.make(1, 2, 3, 4, 5)\n      const predicate = (n: number) => n < 6\n      const result = yield* pipe(\n        Stream.fromChunk(chunk),\n        Stream.run(Sink.every(predicate))\n      )\n      assertTrue(result)\n    }))\n\n  it.effect(\"head\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(Chunk.range(1, 10), Chunk.range(1, 3), Chunk.range(2, 5)),\n        Stream.run(Sink.head())\n      )\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"last\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(Chunk.range(1, 10), Chunk.range(1, 3), Chunk.range(2, 5)),\n        Stream.run(Sink.last())\n      )\n      assertSome(result, 5)\n    }))\n\n  it.effect(\"take - repeats until the source is exhausted\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(\n          Chunk.make(1, 2),\n          Chunk.make(3, 4, 5),\n          Chunk.empty<number>(),\n          Chunk.make(6, 7),\n          Chunk.make(8, 9)\n        ),\n        Stream.run(Sink.collectAllFrom(Sink.take<number>(3)))\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2, 3], [4, 5, 6], [7, 8, 9], []]\n      )\n    }))\n\n  it.effect(\"some\", () =>\n    Effect.gen(function*() {\n      const chunk = Chunk.make(1, 2, 3, 4, 5)\n      const predicate = (n: number) => n === 3\n      const result = yield* pipe(\n        Stream.fromChunk(chunk),\n        Stream.run(Sink.some(predicate))\n      )\n      assertTrue(result)\n    }))\n\n  it.effect(\"sum\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(\n          Chunk.make(1, 2),\n          Chunk.make(3, 4, 5),\n          Chunk.empty<number>(),\n          Chunk.make(6, 7),\n          Chunk.make(8, 9)\n        ),\n        Stream.run(pipe(\n          Sink.collectAllFrom(Sink.sum),\n          Sink.map(Chunk.reduce(0, (x, y) => x + y))\n        ))\n      )\n      strictEqual(result, 45)\n    }))\n\n  it.effect(\"take\", () =>\n    Effect.gen(function*() {\n      const n = 4\n      const chunks = Chunk.make(\n        Chunk.make(1, 2),\n        Chunk.make(3, 4, 5),\n        Chunk.empty<number>(),\n        Chunk.make(6, 7),\n        Chunk.make(8, 9)\n      )\n      const [chunk, leftover] = yield* pipe(\n        Stream.fromChunks(...chunks),\n        Stream.peel(Sink.take<number>(n)),\n        Effect.flatMap(([chunk, stream]) =>\n          pipe(\n            Stream.runCollect(stream),\n            Effect.map((leftover) => [chunk, leftover] as const)\n          )\n        ),\n        Effect.scoped\n      )\n      deepStrictEqual(\n        Array.from(chunk),\n        Array.from(pipe(Chunk.flatten(chunks), Chunk.take(n)))\n      )\n      deepStrictEqual(\n        Array.from(leftover),\n        Array.from(pipe(Chunk.flatten(chunks), Chunk.drop(n)))\n      )\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/environment.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"contextWithSink\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<string>(\"string\")\n      const sink = pipe(\n        Sink.contextWithSink((env: Context.Context<string>) => Sink.succeed(pipe(env, Context.get(tag)))),\n        Sink.provideContext(pipe(Context.empty(), Context.add(tag, \"use this\")))\n      )\n      const result = yield* pipe(Stream.make(\"ignore this\"), Stream.run(sink))\n      strictEqual(result, \"use this\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/error-handling.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"propagates errors\", () =>\n    Effect.gen(function*() {\n      const ErrorStream = \"ErrorStream\" as const\n      const ErrorMapped = \"ErrorMapped\" as const\n      const ErrorSink = \"ErrorSink\" as const\n      const result = yield* pipe(\n        Stream.fail(ErrorStream),\n        Stream.mapError(() => ErrorMapped),\n        Stream.run(\n          pipe(\n            Sink.drain,\n            Sink.mapInputEffect((input: number) => Effect.try(() => input)),\n            Sink.mapError(() => ErrorSink)\n          )\n        ),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(ErrorMapped))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/filtering.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"filterInput\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(pipe(Sink.collectAll<number>(), Sink.filterInput((n) => n % 2 === 0)))\n      )\n      deepStrictEqual(Array.from(result), [2, 4, 6, 8])\n    }))\n\n  it.effect(\"filterInputEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(pipe(\n          Sink.collectAll<number>(),\n          Sink.filterInputEffect((n) => Effect.succeed(n % 2 === 0))\n        ))\n      )\n      deepStrictEqual(Array.from(result), [2, 4, 6, 8])\n    }))\n\n  it.effect(\"filterInputEffect - error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(pipe(\n          Sink.collectAll<number>(),\n          Sink.filterInputEffect(() => Effect.fail(\"fail\"))\n        )),\n        Effect.flip\n      )\n      strictEqual(result, \"fail\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/finalization.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"ensuring - happy path\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(false)\n      yield* pipe(\n        Stream.make(1, 2, 3, 4, 5),\n        Stream.run(pipe(Sink.drain, Sink.ensuring(Ref.set(ref, true))))\n      )\n      const result = yield* Ref.get(ref)\n      assertTrue(result)\n    }))\n\n  it.effect(\"ensuring - error\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(false)\n      yield* pipe(\n        Stream.fail(\"boom!\"),\n        Stream.run(pipe(Sink.drain, Sink.ensuring(Ref.set(ref, true)))),\n        Effect.ignore\n      )\n      const result = yield* Ref.get(ref)\n      assertTrue(result)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/folding.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { absurd, constTrue, pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"fold - empty\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.transduce(Sink.fold<number, number>(0, constTrue, (x, y) => x + y)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0])\n    }))\n\n  it.effect(\"fold - termination in the middle\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(Sink.fold<number, number>(0, (n) => n <= 5, (x, y) => x + y))\n      )\n      strictEqual(result, 6)\n    }))\n\n  it.effect(\"fold - immediate termination\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(Sink.fold<number, number>(0, (n) => n <= -1, (x, y) => x + y))\n      )\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"fold - no termination\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(Sink.fold<number, number>(0, (n) => n <= 500, (x, y) => x + y))\n      )\n      strictEqual(result, 45)\n    }))\n\n  it.effect(\"foldLeft equivalence with Chunk.reduce\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.range(1, 9)\n      const result1 = yield* pipe(stream, Stream.run(Sink.foldLeft(\"\", (s, n) => s + `${n}`)))\n      const result2 = yield* pipe(stream, Stream.runCollect, Effect.map(Chunk.reduce(\"\", (s, n) => s + `${n}`)))\n      strictEqual(result1, result2)\n    }))\n\n  it.effect(\"foldEffect - empty\", () =>\n    Effect.gen(function*() {\n      const sink = Sink.foldEffect(0, constTrue, (x, y: number) => Effect.succeed(x + y))\n      const result = yield* pipe(Stream.empty, Stream.transduce(sink), Stream.runCollect)\n      deepStrictEqual(Array.from(result), [0])\n    }))\n\n  it.effect(\"foldEffect - short circuits\", () =>\n    Effect.gen(function*() {\n      const empty: Stream.Stream<number> = Stream.empty\n      const single = Stream.make(1)\n      const double = Stream.make(1, 2)\n      const failed = Stream.fail(\"Ouch\")\n      const run = <E>(stream: Stream.Stream<number, E>) =>\n        pipe(\n          Ref.make(Chunk.empty<number>()),\n          Effect.flatMap((ref) =>\n            pipe(\n              stream,\n              Stream.transduce(Sink.foldEffect(\n                0,\n                constTrue,\n                (_, y: number) => pipe(Ref.update(ref, Chunk.append(y)), Effect.as(30))\n              )),\n              Stream.runCollect,\n              Effect.flatMap((exit) =>\n                pipe(\n                  Ref.get(ref),\n                  Effect.map((result) => [Array.from(exit), Array.from(result)])\n                )\n              )\n            )\n          ),\n          Effect.exit\n        )\n      const result1 = yield* run(empty)\n      const result2 = yield* run(single)\n      const result3 = yield* run(double)\n      const result4 = yield* run(failed)\n      deepStrictEqual(result1, Exit.succeed([[0], []]))\n      deepStrictEqual(result2, Exit.succeed([[30], [1]]))\n      deepStrictEqual(result3, Exit.succeed([[30], [1, 2]]))\n      deepStrictEqual(result4, Exit.fail(\"Ouch\"))\n    }))\n\n  it.effect(\"foldUntil\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 1, 1, 1, 1, 1),\n        Stream.transduce(Sink.foldUntil(0, 3, (x, y) => x + y)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [3, 3, 0])\n    }))\n\n  it.effect(\"foldUntilEffect\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 1, 1, 1, 1, 1),\n        Stream.transduce(Sink.foldUntilEffect(0, 3, (x, y) => Effect.succeed(x + y))),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [3, 3, 0])\n    }))\n\n  it.effect(\"foldWeighted\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 5, 2, 3),\n        Stream.transduce(Sink.foldWeighted({\n          initial: Chunk.empty<number>(),\n          maxCost: 12,\n          cost: (_, n) => n * 2,\n          body: (acc, curr) => pipe(acc, Chunk.append(curr))\n        })),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 5], [2, 3]]\n      )\n    }))\n\n  it.effect(\"foldWeightedDecompose - empty\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.transduce(Sink.foldWeightedDecompose({\n          initial: 0,\n          maxCost: 1_000,\n          cost: (_, n) => n,\n          decompose: Chunk.of,\n          body: (acc, curr) => acc + curr\n        })),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0])\n    }))\n\n  it.effect(\"foldWeightedDecompose - simple\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 5, 1),\n        Stream.transduce(Sink.foldWeightedDecompose({\n          initial: Chunk.empty<number>(),\n          maxCost: 4,\n          cost: (_, n) => n,\n          decompose: (n) => n > 1 ? Chunk.make(n - 1, 1) : Chunk.of(n),\n          body: (acc, curr) => pipe(acc, Chunk.append(curr))\n        })),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 3], [1, 1, 1]]\n      )\n    }))\n\n  it.effect(\"foldWeightedEffect\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 5, 2, 3),\n        Stream.transduce(Sink.foldWeightedEffect({\n          initial: Chunk.empty<number>(),\n          maxCost: 12,\n          cost: (_, n) => Effect.succeed(n * 2),\n          body: (acc, curr) => Effect.succeed(pipe(acc, Chunk.append(curr)))\n        })),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 5], [2, 3]]\n      )\n    }))\n\n  it.effect(\"foldWeightedDecomposeEffect - empty\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.transduce(Sink.foldWeightedDecomposeEffect({\n          initial: 0,\n          maxCost: 1_000,\n          cost: (_, n) => Effect.succeed(n),\n          decompose: (input) => Effect.succeed(Chunk.of(input)),\n          body: (acc, curr) => Effect.succeed(acc + curr)\n        })),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0])\n    }))\n\n  it.effect(\"foldWeightedDecomposeEffect - simple\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 5, 1),\n        Stream.transduce(Sink.foldWeightedDecomposeEffect({\n          initial: Chunk.empty<number>(),\n          maxCost: 4,\n          cost: (_, n) => Effect.succeed(n),\n          decompose: (n) => Effect.succeed(n > 1 ? Chunk.make(n - 1, 1) : Chunk.of(n)),\n          body: (acc, curr) => Effect.succeed(pipe(acc, Chunk.append(curr)))\n        })),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 3], [1, 1, 1]]\n      )\n    }))\n\n  it.effect(\"foldSink - handles leftovers\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.fail(\"boom\"),\n        Sink.foldSink({\n          onFailure: (err) =>\n            pipe(\n              Sink.collectAll<number>(),\n              Sink.map((chunk) => [Array.from(chunk), err] as const)\n            ),\n          onSuccess: (_) => absurd<Sink.Sink<readonly [Array<number>, string], number, never, string>>(_)\n        })\n      )\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.run(sink)\n      )\n      deepStrictEqual(result, [[1, 2, 3], \"boom\"])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/foreign.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Random from \"effect/Random\"\nimport type * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\nimport { unify } from \"effect/Unify\"\n\nconst runSink = <A, E, R>(sink: Sink.Sink<A, unknown, unknown, E, R>) => Stream.run(Effect.void, sink)\n\ndescribe(\"Channel.Foreign\", () => {\n  it.effect(\"Tag\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<number>(\"number\")\n      const result = yield* pipe(tag, runSink, Effect.provideService(tag, 10))\n      deepStrictEqual(result, 10)\n    }))\n\n  it.effect(\"Unify\", () =>\n    Effect.gen(function*() {\n      const unifiedEffect = unify((yield* (Random.nextInt)) > 1 ? Effect.succeed(0) : Effect.fail(1))\n      const unifiedExit = unify((yield* (Random.nextInt)) > 1 ? Exit.succeed(0) : Exit.fail(1))\n      const unifiedEither = unify((yield* (Random.nextInt)) > 1 ? Either.right(0) : Either.left(1))\n      const unifiedOption = unify((yield* (Random.nextInt)) > 1 ? Option.some(0) : Option.none())\n      deepStrictEqual(yield* (runSink(unifiedEffect)), 0)\n      deepStrictEqual(yield* (runSink(unifiedExit)), 0)\n      deepStrictEqual(yield* (runSink(unifiedEither)), 0)\n      deepStrictEqual(yield* (runSink(unifiedOption)), 0)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/mapping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"as\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(pipe(Sink.succeed(1), Sink.as(\"as\")))\n      )\n      strictEqual(result, \"as\")\n    }))\n\n  it.effect(\"mapInput - happy path\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.collectAll<number>(),\n        Sink.mapInput((input: string) => Number.parseInt(input))\n      )\n      const result = yield* pipe(Stream.make(\"1\", \"2\", \"3\"), Stream.run(sink))\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"mapInput - error\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.fail(\"Ouch\"),\n        Sink.mapInput((input: string) => Number.parseInt(input))\n      )\n      const result = yield* pipe(Stream.make(\"1\", \"2\", \"3\"), Stream.run(sink), Effect.either)\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"mapInputChunks - happy path\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.collectAll<number>(),\n        Sink.mapInputChunks<string, number>(Chunk.map((_) => Number.parseInt(_)))\n      )\n      const result = yield* pipe(Stream.make(\"1\", \"2\", \"3\"), Stream.run(sink))\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"mapInputChunks - error\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.fail(\"Ouch\"),\n        Sink.mapInputChunks<string, number>(Chunk.map(Number.parseInt))\n      )\n      const result = yield* pipe(Stream.make(\"1\", \"2\", \"3\"), Stream.run(sink), Effect.either)\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"mapInputEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.collectAll<number>(),\n        Sink.mapInputEffect((s: string) => Effect.try(() => Number.parseInt(s)))\n      )\n      const result = yield* pipe(Stream.make(\"1\", \"2\", \"3\"), Stream.run(sink))\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"mapInputEffect - error\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.fail(\"Ouch\"),\n        Sink.mapInputEffect((s: string) => Effect.try(() => Number.parseInt(s)))\n      )\n      const result = yield* pipe(Stream.make(\"1\", \"2\", \"3\"), Stream.run(sink), Effect.either)\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"mapInputEffect - error in transformation\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.collectAll<number>(),\n        Sink.mapInputEffect((s: string) =>\n          Effect.try(() => {\n            const result = Number.parseInt(s)\n            if (Number.isNaN(result)) {\n              throw new Cause.RuntimeException(`Cannot parse \"${s}\" to an integer`)\n            }\n            return result\n          })\n        )\n      )\n      const result = yield* pipe(Stream.make(\"1\", \"a\"), Stream.run(sink), Effect.flip)\n      deepStrictEqual(result.error, new Cause.RuntimeException(\"Cannot parse \\\"a\\\" to an integer\"))\n    }))\n\n  it.effect(\"mapInputChunksEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.collectAll<number>(),\n        Sink.mapInputChunksEffect((chunk: Chunk.Chunk<string>) =>\n          pipe(\n            chunk,\n            Effect.forEach((s) => Effect.try(() => Number.parseInt(s))),\n            Effect.map(Chunk.unsafeFromArray)\n          )\n        )\n      )\n      const result = yield* pipe(Stream.make(\"1\", \"2\", \"3\"), Stream.run(sink))\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"mapInputChunksEffect - error\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.fail(\"Ouch\"),\n        Sink.mapInputChunksEffect((chunk: Chunk.Chunk<string>) =>\n          pipe(\n            chunk,\n            Effect.forEach((s) => Effect.try(() => Number.parseInt(s))),\n            Effect.map(Chunk.unsafeFromArray)\n          )\n        )\n      )\n      const result = yield* pipe(Stream.make(\"1\", \"2\", \"3\"), Stream.run(sink), Effect.either)\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"mapInputChunksEffect - error in transformation\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.collectAll<number>(),\n        Sink.mapInputChunksEffect((chunk: Chunk.Chunk<string>) =>\n          pipe(\n            chunk,\n            Effect.forEach((s) =>\n              Effect.try(() => {\n                const result = Number.parseInt(s)\n                if (Number.isNaN(result)) {\n                  throw new Cause.RuntimeException(`Cannot parse \"${s}\" to an integer`)\n                }\n                return result\n              })\n            ),\n            Effect.map(Chunk.unsafeFromArray)\n          )\n        )\n      )\n      const result = yield* pipe(Stream.make(\"1\", \"a\"), Stream.run(sink), Effect.flip)\n      deepStrictEqual(result.error, new Cause.RuntimeException(\"Cannot parse \\\"a\\\" to an integer\"))\n    }))\n\n  it.effect(\"map\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(pipe(Sink.succeed(1), Sink.map((n) => `${n}`)))\n      )\n      strictEqual(result, \"1\")\n    }))\n\n  it.effect(\"mapEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(pipe(Sink.succeed(1), Sink.mapEffect((n) => Effect.succeed(n + 1))))\n      )\n      strictEqual(result, 2)\n    }))\n\n  it.effect(\"mapEffect - error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(pipe(Sink.succeed(1), Sink.mapEffect(() => Effect.fail(\"fail\")))),\n        Effect.flip\n      )\n      strictEqual(result, \"fail\")\n    }))\n\n  it.effect(\"mapError\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9),\n        Stream.run(pipe(Sink.fail(\"fail\"), Sink.mapError((s) => s + \"!\"))),\n        Effect.either\n      )\n      assertLeft(result, \"fail!\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/racing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { constVoid, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Random from \"effect/Random\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\nimport { unfoldEffect } from \"../utils/unfoldEffect.js\"\n\nconst findSink = <A>(a: A): Sink.Sink<A, A, A, void> =>\n  pipe(\n    Sink.fold<Option.Option<A>, A>(\n      Option.none(),\n      Option.isNone,\n      (_, v) => (a === v ? Option.some(a) : Option.none())\n    ),\n    Sink.mapEffect(Option.match({\n      onNone: () => Effect.failSync(constVoid),\n      onSome: Effect.succeed\n    }))\n  )\n\nconst sinkRaceLaw = <E, A, L>(\n  stream: Stream.Stream<A>,\n  sink1: Sink.Sink<A, A, L, E>,\n  sink2: Sink.Sink<A, A, L, E>\n): Effect.Effect<boolean> =>\n  pipe(\n    Effect.all({\n      result1: pipe(stream, Stream.run(sink1), Effect.either),\n      result2: pipe(stream, Stream.run(sink2), Effect.either),\n      result3: pipe(stream, Stream.run(pipe(sink1, Sink.raceBoth(sink2))), Effect.either)\n    }),\n    Effect.map(({ result1, result2, result3 }) =>\n      pipe(\n        result3,\n        Either.match({\n          onLeft: () => Either.isLeft(result1) || Either.isLeft(result2),\n          onRight: Either.match({\n            onLeft: (a) => Either.isRight(result1) && result1.right === a,\n            onRight: (a) => Either.isRight(result2) && result2.right === a\n          })\n        })\n      )\n    )\n  )\n\ndescribe(\"Sink\", () => {\n  it.effect(\"raceBoth\", () =>\n    Effect.gen(function*() {\n      const ints = yield* unfoldEffect(\n        0,\n        (n) =>\n          Effect.map(\n            Random.nextIntBetween(0, 10),\n            (i) => n <= 20 ? Option.some([i, n + 1] as const) : Option.none()\n          )\n      )\n      const success1 = yield* (Random.nextBoolean)\n      const success2 = yield* (Random.nextBoolean)\n      const chunk = pipe(\n        Chunk.unsafeFromArray(ints),\n        Chunk.appendAll(success1 ? Chunk.of(20) : Chunk.empty<number>()),\n        Chunk.appendAll(success2 ? Chunk.of(40) : Chunk.empty<number>())\n      )\n      const result = yield* (\n        sinkRaceLaw(\n          Stream.fromIterableEffect(Random.shuffle(chunk)),\n          findSink(20),\n          findSink(40)\n        )\n      )\n      assertTrue(result)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/refining.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"refineOrDie\", () =>\n    Effect.gen(function*() {\n      const exception = new Cause.RuntimeException()\n      const refinedTo = \"refined\"\n      const sink = pipe(\n        Sink.fail(exception),\n        Sink.refineOrDie((error) =>\n          Cause.isRuntimeException(error) ?\n            Option.some(refinedTo) :\n            Option.none()\n        )\n      )\n      const result = yield* pipe(Stream.make(1, 2, 3), Stream.run(sink), Effect.exit)\n      deepStrictEqual(result, Exit.fail(refinedTo))\n    }))\n\n  it.effect(\"refineOrDieWith - refines\", () =>\n    Effect.gen(function*() {\n      const exception = new Cause.RuntimeException()\n      const refinedTo = \"refined\"\n      const sink = pipe(\n        Sink.fail(exception),\n        Sink.refineOrDieWith((error) =>\n          Cause.isRuntimeException(error) ?\n            Option.some(refinedTo) :\n            Option.none(), (error) => error.message)\n      )\n      const result = yield* pipe(Stream.make(1, 2, 3), Stream.run(sink), Effect.exit)\n      deepStrictEqual(result, Exit.fail(refinedTo))\n    }))\n\n  it.effect(\"refineOrDieWith - dies\", () =>\n    Effect.gen(function*() {\n      const exception = new Cause.RuntimeException()\n      const refinedTo = \"refined\"\n      const sink = pipe(\n        Sink.fail(exception),\n        Sink.refineOrDieWith((error) =>\n          Cause.isIllegalArgumentException(error) ?\n            Option.some(refinedTo) :\n            Option.none(), (error) => error.message)\n      )\n      const result = yield* pipe(Stream.make(1, 2, 3), Stream.run(sink), Effect.exit)\n      deepStrictEqual(result, Exit.die(\"\"))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/scoping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"unwrapScoped - happy path\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const resource = Effect.acquireRelease(\n        Effect.succeed(100),\n        () => Ref.set(ref, true)\n      )\n      const sink = pipe(\n        resource,\n        Effect.map((n) =>\n          pipe(\n            Sink.count,\n            Sink.mapEffect((count) =>\n              pipe(\n                Ref.get(ref),\n                Effect.map((closed) => [count + n, closed] as const)\n              )\n            )\n          )\n        ),\n        Sink.unwrapScoped\n      )\n      const [result, state] = yield* pipe(Stream.make(1, 2, 3), Stream.run(sink))\n      const finalState = yield* (Ref.get(ref))\n      strictEqual(result, 103)\n      assertFalse(state)\n      assertTrue(finalState)\n    }))\n\n  it.effect(\"unwrapScoped - error\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const resource = Effect.acquireRelease(\n        Effect.succeed(100),\n        () => Ref.set(ref, true)\n      )\n      const sink = pipe(resource, Effect.as(Sink.succeed(\"ok\")), Sink.unwrapScoped)\n      const result = yield* pipe(Stream.fail(\"fail\"), Stream.run(sink))\n      const finalState = yield* (Ref.get(ref))\n      strictEqual(result, \"ok\")\n      assertTrue(finalState)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/sequencing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertSome, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"flatMap - empty input\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(Sink.head<number>(), Sink.flatMap(Sink.succeed))\n      const result = yield* pipe(Stream.empty, Stream.run(sink))\n      assertNone(result)\n    }))\n\n  it.effect(\"flatMap - non-empty input\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(Sink.head<number>(), Sink.flatMap(Sink.succeed))\n      const result = yield* pipe(Stream.make(1, 2, 3), Stream.run(sink))\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"flatMap - with leftovers\", () =>\n    Effect.gen(function*() {\n      const chunks = Chunk.make(\n        Chunk.make(1, 2),\n        Chunk.make(3, 4, 5),\n        Chunk.empty<number>(),\n        Chunk.make(7, 8, 9, 10)\n      )\n      const sink = pipe(\n        Sink.head<number>(),\n        Sink.flatMap((head) =>\n          pipe(\n            Sink.count,\n            Sink.map((count) => [head, count] as const)\n          )\n        )\n      )\n      const [option, count] = yield* pipe(Stream.fromChunks(...chunks), Stream.run(sink))\n      deepStrictEqual(option, Chunk.head(Chunk.flatten(chunks)))\n      strictEqual(\n        count + Option.match(option, {\n          onNone: () => 0,\n          onSome: () => 1\n        }),\n        pipe(chunks, Chunk.map(Chunk.size), Chunk.reduce(0, (a, b) => a + b))\n      )\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/traversing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Sink\", () => {\n  it.effect(\"findEffect - with head sink\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.head<number>(),\n        Sink.findEffect(Option.match({\n          onNone: () => Effect.succeed(false),\n          onSome: (n) => Effect.succeed(n >= 10)\n        }))\n      )\n      const result = yield* pipe(\n        [1, 3, 7, 20],\n        Effect.forEach((n) =>\n          pipe(\n            Stream.range(1, 99),\n            Stream.rechunk(n),\n            Stream.run(sink),\n            Effect.map((option) => Equal.equals(option, Option.some(Option.some(10))))\n          )\n        )\n      )\n      assertTrue(result.every(identity))\n    }))\n\n  it.effect(\"findEffect - take sink across multiple chunks\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.take<number>(4),\n        Sink.findEffect((chunk) => Effect.succeed(pipe(chunk, Chunk.reduce(0, (x, y) => x + y)) > 10))\n      )\n      const result = yield* pipe(\n        Stream.fromIterable(Chunk.range(1, 8)),\n        Stream.rechunk(2),\n        Stream.run(sink),\n        Effect.map(Option.getOrElse(() => Chunk.empty<number>()))\n      )\n      deepStrictEqual(Array.from(result), [5, 6, 7, 8])\n    }))\n\n  it.effect(\"findEffect - empty stream terminates with none\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.sum,\n        Sink.findEffect((n) => Effect.succeed(n > 0))\n      )\n      const result = yield* pipe(\n        Stream.fromIterable([]),\n        Stream.run(sink)\n      )\n      assertNone(result)\n    }))\n\n  it.effect(\"findEffect - unsatisfied condition terminates with none\", () =>\n    Effect.gen(function*() {\n      const sink = pipe(\n        Sink.head<number>(),\n        Sink.findEffect(Option.match({\n          onNone: () => Effect.succeed(false),\n          onSome: (n) => Effect.succeed(n >= 3)\n        }))\n      )\n      const result = yield* pipe(\n        Stream.fromIterable([1, 2]),\n        Stream.run(sink)\n      )\n      assertNone(result)\n    }))\n\n  it.effect(\"forEachWhile - handles leftovers\", () =>\n    Effect.gen(function*() {\n      const [result, value] = yield* pipe(\n        Stream.range(1, 4),\n        Stream.run(pipe(\n          Sink.forEachWhile((n: number) => Effect.succeed(n <= 3)),\n          Sink.collectLeftover\n        ))\n      )\n      strictEqual(result, undefined)\n      deepStrictEqual(Array.from(value), [4])\n    }))\n\n  it.effect(\"splitWhere - should split a stream on a predicate and run each part into the sink\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5, 6, 7, 8)\n      const result = yield* pipe(\n        stream,\n        Stream.transduce(pipe(Sink.collectAll<number>(), Sink.splitWhere((n) => n % 2 === 0))),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1], [2, 3], [4, 5], [6, 7], [8]]\n      )\n    }))\n\n  it.effect(\"splitWhere - should split a stream on a predicate and run each part into the sink, in several chunks\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.fromChunks(Chunk.make(1, 2, 3, 4), Chunk.make(5, 6, 7, 8))\n      const result = yield* pipe(\n        stream,\n        Stream.transduce(pipe(Sink.collectAll<number>(), Sink.splitWhere((n) => n % 2 === 0))),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1], [2, 3], [4, 5], [6, 7], [8]]\n      )\n    }))\n\n  it.effect(\"splitWhere - should not yield an empty sink if split on the first element\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5, 6, 7, 8)\n      const result = yield* pipe(\n        stream,\n        Stream.transduce(pipe(Sink.collectAll<number>(), Sink.splitWhere((n) => n % 2 !== 0))),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2], [3, 4], [5, 6], [7, 8]]\n      )\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Sink/zipping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertSome, assertTrue, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { constVoid, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Random from \"effect/Random\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\nimport { unfoldEffect } from \"../utils/unfoldEffect.js\"\n\nconst findSink = <A>(a: A): Sink.Sink<A, A, A, void> =>\n  pipe(\n    Sink.fold<Option.Option<A>, A>(\n      Option.none(),\n      Option.isNone,\n      (_, v) => (a === v ? Option.some(a) : Option.none())\n    ),\n    Sink.mapEffect(Option.match({\n      onNone: () => Effect.failSync(constVoid),\n      onSome: Effect.succeed\n    }))\n  )\n\nconst zipParLaw = <A, B, C, E>(\n  stream: Stream.Stream<A>,\n  sink1: Sink.Sink<B, A, A, E>,\n  sink2: Sink.Sink<C, A, A, E>\n): Effect.Effect<boolean> =>\n  pipe(\n    Effect.all({\n      zb: pipe(stream, Stream.run(sink1), Effect.either),\n      zc: pipe(stream, Stream.run(sink2), Effect.either),\n      zbc: pipe(stream, Stream.run(pipe(sink1, Sink.zip(sink2, { concurrent: true }))), Effect.either)\n    }),\n    Effect.map(({ zb, zbc, zc }) =>\n      Either.match(zbc, {\n        onLeft: (e) => (Either.isLeft(zb) && zb.left === e) || (Either.isLeft(zc) && zc.left === e),\n        onRight: ([b, c]) => Either.isRight(zb) && zb.right === b && Either.isRight(zc) && zc.right === c\n      })\n    )\n  )\n\ndescribe(\"Sink\", () => {\n  it.effect(\"zipParLeft\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.run(pipe(\n          Sink.head(),\n          Sink.zipLeft(Sink.succeed(\"hello\"), { concurrent: true })\n        ))\n      )\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"zipParRight\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.run(pipe(\n          Sink.head(),\n          Sink.zipRight(Sink.succeed(\"hello\"), { concurrent: true })\n        ))\n      )\n      strictEqual(result, \"hello\")\n    }))\n\n  it.effect(\"zipWithPar - coherence\", () =>\n    Effect.gen(function*() {\n      const ints = yield* (unfoldEffect(0, (n) =>\n        pipe(\n          Random.nextIntBetween(0, 10),\n          Effect.map((i) => n < 20 ? Option.some([i, n + 1] as const) : Option.none())\n        )))\n      const success1 = yield* (Random.nextBoolean)\n      const success2 = yield* (Random.nextBoolean)\n      const chunk = pipe(\n        Chunk.unsafeFromArray(ints),\n        Chunk.appendAll(success1 ? Chunk.of(20) : Chunk.empty<number>()),\n        Chunk.appendAll(success2 ? Chunk.of(40) : Chunk.empty<number>())\n      )\n      const result = yield* (\n        zipParLaw(\n          Stream.fromIterableEffect(Random.shuffle(chunk)),\n          findSink(20),\n          findSink(40)\n        )\n      )\n      assertTrue(result)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/SortedMap.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertNone, assertSome, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Equal, Hash, Number as Num, pipe, SortedMap as SM } from \"effect\"\n\nclass Key implements Equal.Equal {\n  constructor(readonly id: number) {}\n\n  [Hash.symbol](): number {\n    return Hash.hash(this.id)\n  }\n\n  [Equal.symbol](u: unknown): boolean {\n    return u instanceof Key && this.id === u.id\n  }\n}\n\nclass Value implements Equal.Equal {\n  constructor(readonly id: number) {}\n\n  [Hash.symbol](): number {\n    return Hash.hash(this.id)\n  }\n\n  [Equal.symbol](u: unknown): boolean {\n    return u instanceof Value && this.id === u.id\n  }\n}\n\nfunction key(n: number): Key {\n  return new Key(n)\n}\n\nfunction value(n: number): Value {\n  return new Value(n)\n}\n\nfunction makeSortedMap(...numbers: Array<readonly [number, number]>): SM.SortedMap<Key, Value> {\n  const entries = numbers.map(([k, v]) => [key(k), value(v)] as const)\n  return SM.fromIterable(entries, (self: Key, that: Key) => self.id > that.id ? 1 : self.id < that.id ? -1 : 0)\n}\n\nfunction makeNumericSortedMap(\n  ...numbers: Array<readonly [number, number]>\n): SM.SortedMap<number, number> {\n  return SM.fromIterable(numbers, (self: number, that: number) => self > that ? 1 : self < that ? -1 : 0)\n}\n\ndescribe(\"SortedMap\", () => {\n  it(\"toString\", () => {\n    const map = makeNumericSortedMap([0, 10], [1, 20], [2, 30])\n\n    strictEqual(\n      String(map),\n      `{\n  \"_id\": \"SortedMap\",\n  \"values\": [\n    [\n      0,\n      10\n    ],\n    [\n      1,\n      20\n    ],\n    [\n      2,\n      30\n    ]\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    const map = makeNumericSortedMap([0, 10], [1, 20], [2, 30])\n\n    deepStrictEqual(map.toJSON(), { _id: \"SortedMap\", values: [[0, 10], [1, 20], [2, 30]] })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n\n    const map = makeNumericSortedMap([0, 10], [1, 20], [2, 30])\n\n    deepStrictEqual(inspect(map), inspect({ _id: \"SortedMap\", values: [[0, 10], [1, 20], [2, 30]] }))\n  })\n\n  it(\"entries\", () => {\n    const map = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    const result = Array.from(map)\n\n    deepStrictEqual([\n      [key(0), value(10)],\n      [key(1), value(20)],\n      [key(2), value(30)]\n    ], result)\n  })\n\n  it(\"get\", () => {\n    const map = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    assertSome(pipe(map, SM.get(key(0))), value(10))\n    assertNone(pipe(map, SM.get(key(4))))\n  })\n\n  it(\"has\", () => {\n    const map = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    assertTrue(pipe(map, SM.has(key(0))))\n    assertFalse(pipe(map, SM.has(key(4))))\n  })\n\n  it(\"headOption\", () => {\n    const map1 = makeSortedMap([0, 10], [1, 20], [2, 30])\n    const map2 = SM.empty<number, number>(Num.Order)\n\n    assertSome(SM.headOption(map1), [key(0), value(10)])\n    assertNone(SM.headOption(map2))\n  })\n\n  it(\"lastOption\", () => {\n    const map1 = makeSortedMap([0, 10], [1, 20], [2, 30])\n    const map2 = SM.empty<number, number>(Num.Order)\n\n    assertSome(SM.lastOption(map1), [key(2), value(30)])\n    assertNone(SM.lastOption(map2))\n  })\n\n  it(\"isEmpty\", () => {\n    const map1 = makeSortedMap([0, 10], [1, 20], [2, 30])\n    const map2 = SM.empty<number, number>(Num.Order)\n\n    assertFalse(SM.isEmpty(map1))\n    assertTrue(SM.isEmpty(map2))\n  })\n\n  it(\"isNonEmpty\", () => {\n    const map1 = makeSortedMap([0, 10], [1, 20], [2, 30])\n    const map2 = SM.empty<number, number>(Num.Order)\n\n    assertTrue(SM.isNonEmpty(map1))\n    assertFalse(SM.isNonEmpty(map2))\n  })\n\n  it(\"map\", () => {\n    const map1 = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    const result1 = Array.from(pipe(map1, SM.map((value) => value.id)))\n\n    deepStrictEqual(\n      result1,\n      [\n        [key(0), 10],\n        [key(1), 20],\n        [key(2), 30]\n      ]\n    )\n\n    const map2 = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    const result2 = Array.from(pipe(map2, SM.map((key, value) => key.id + value.id)))\n\n    deepStrictEqual(\n      result2,\n      [\n        [key(0), 10],\n        [key(1), 21],\n        [key(2), 32]\n      ]\n    )\n  })\n\n  it(\"partition\", () => {\n    const map1 = makeSortedMap([1, 10], [2, 20], [3, 30], [4, 40], [5, 50])\n\n    const [excl, satisfying] = pipe(\n      map1,\n      SM.partition((member) => member.id <= 3)\n    )\n\n    deepStrictEqual(\n      Array.from(satisfying),\n      [\n        [key(1), value(10)],\n        [key(2), value(20)],\n        [key(3), value(30)]\n      ]\n    )\n    deepStrictEqual(\n      Array.from(excl),\n      [\n        [key(4), value(40)],\n        [key(5), value(50)]\n      ]\n    )\n\n    const [excl2, satisfying2] = pipe(\n      map1,\n      SM.partition((member) => member.id <= 6)\n    )\n\n    deepStrictEqual(\n      Array.from(satisfying2),\n      [\n        [key(1), value(10)],\n        [key(2), value(20)],\n        [key(3), value(30)],\n        [key(4), value(40)],\n        [key(5), value(50)]\n      ]\n    )\n\n    deepStrictEqual(\n      Array.from(excl2),\n      []\n    )\n\n    const [excl3, satisfying3] = pipe(\n      map1,\n      SM.partition((member) => member.id === 0)\n    )\n\n    deepStrictEqual(\n      Array.from(excl3),\n      [\n        [key(1), value(10)],\n        [key(2), value(20)],\n        [key(3), value(30)],\n        [key(4), value(40)],\n        [key(5), value(50)]\n      ]\n    )\n\n    deepStrictEqual(\n      Array.from(satisfying3),\n      []\n    )\n  })\n\n  it(\"reduce\", () => {\n    const map1 = makeSortedMap([0, 10], [1, 20], [2, 30])\n    const result1 = pipe(map1, SM.reduce(\"\", (acc, value) => acc + value.id))\n    strictEqual(result1, \"102030\")\n\n    const map2 = makeSortedMap([0, 10], [1, 20], [2, 30])\n    const result2 = pipe(map2, SM.reduce(\"\", (acc, value, key) => acc + key.id + value.id))\n    strictEqual(result2, \"010120230\")\n  })\n\n  it(\"remove\", () => {\n    const map = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    assertTrue(pipe(map, SM.has(key(0))))\n\n    const result1 = pipe(map, SM.remove(key(0)))\n\n    assertFalse(pipe(result1, SM.has(key(0))))\n  })\n\n  it(\"set\", () => {\n    const map = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    assertFalse(pipe(map, SM.has(key(4))))\n\n    const result1 = pipe(map, SM.set(key(4), value(40)))\n\n    assertTrue(pipe(result1, SM.has(key(4))))\n  })\n\n  it(\"size\", () => {\n    const map = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    strictEqual(SM.size(map), 3)\n  })\n\n  it(\"keys\", () => {\n    const map = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    const result = Array.from(SM.keys(map))\n\n    deepStrictEqual(result, [key(0), key(1), key(2)])\n  })\n\n  it(\"values\", () => {\n    const map = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    const result = Array.from(SM.values(map))\n\n    deepStrictEqual(result, [value(10), value(20), value(30)])\n  })\n\n  it(\"entries\", () => {\n    const map = makeSortedMap([0, 10], [1, 20], [2, 30])\n\n    const result = Array.from(SM.entries(map))\n\n    deepStrictEqual(result, [[key(0), value(10)], [key(1), value(20)], [key(2), value(30)]])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/SortedSet.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Equal, Hash, Order, pipe, SortedSet, String as Str } from \"effect\"\n\nclass Member implements Equal.Equal {\n  constructor(readonly id: string) {}\n\n  [Hash.symbol](): number {\n    return Hash.hash(this.id)\n  }\n\n  [Equal.symbol](u: unknown): boolean {\n    return u instanceof Member && this.id === u.id\n  }\n}\n\nconst OrdMember: Order.Order<Member> = pipe(Str.Order, Order.mapInput((member) => member.id))\n\nfunction makeNumericSortedSet(\n  ...numbers: Array<number>\n): SortedSet.SortedSet<number> {\n  return SortedSet.fromIterable(numbers, (self, that: number) => self > that ? 1 : self < that ? -1 : 0)\n}\n\ndescribe(\"SortedSet\", () => {\n  it(\"fromIterable\", () => {\n    deepStrictEqual(Array.from(SortedSet.fromIterable([\"c\", \"a\", \"b\"], Str.Order)), [\"a\", \"b\", \"c\"])\n    deepStrictEqual(Array.from(pipe([\"c\", \"a\", \"b\"], SortedSet.fromIterable(Str.Order))), [\"a\", \"b\", \"c\"])\n  })\n\n  it(\"is\", () => {\n    const set = makeNumericSortedSet(0, 1, 2)\n    const arr = Array.from(set)\n    assertTrue(SortedSet.isSortedSet(set))\n    assertFalse(SortedSet.isSortedSet(arr))\n  })\n\n  it(\"toString\", () => {\n    const set = makeNumericSortedSet(0, 1, 2)\n    strictEqual(\n      String(set),\n      `{\n  \"_id\": \"SortedSet\",\n  \"values\": [\n    0,\n    1,\n    2\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    const set = makeNumericSortedSet(0, 1, 2)\n    deepStrictEqual(set.toJSON(), { _id: \"SortedSet\", values: [0, 1, 2] })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n    const set = makeNumericSortedSet(0, 1, 2)\n    deepStrictEqual(inspect(set), inspect({ _id: \"SortedSet\", values: [0, 1, 2] }))\n  })\n\n  it(\"add\", () => {\n    const set = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\")),\n      SortedSet.add(new Member(\"worker_000001\"))\n    )\n\n    deepStrictEqual(\n      Array.from(set),\n      [\n        new Member(\"worker_000000\"),\n        new Member(\"worker_000001\"),\n        new Member(\"worker_000002\")\n      ]\n    )\n  })\n\n  it(\"difference\", () => {\n    const set1 = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const set2 = [\n      new Member(\"worker_000001\"),\n      new Member(\"worker_000002\"),\n      new Member(\"worker_000003\")\n    ]\n\n    const set3 = [\n      new Member(\"worker_000000\"),\n      new Member(\"worker_000001\"),\n      new Member(\"worker_000002\")\n    ]\n\n    deepStrictEqual(\n      Array.from(pipe(\n        set1,\n        SortedSet.difference(set2)\n      )),\n      [new Member(\"worker_000000\")]\n    )\n    deepStrictEqual(\n      Array.from(pipe(set1, SortedSet.difference(set3))),\n      []\n    )\n  })\n\n  it(\"every\", () => {\n    const isWorker = (member: Member) => member.id.indexOf(\"worker\") !== -1\n    const isWorker1 = (member: Member) => member.id === \"worker_000001\"\n    const set = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const result1 = pipe(set, SortedSet.every(isWorker))\n    const result2 = pipe(set, SortedSet.every(isWorker1))\n\n    assertTrue(result1)\n    assertFalse(result2)\n  })\n\n  it(\"some\", () => {\n    const isWorker1 = (member: Member) => member.id === \"worker_000001\"\n    const isWorker4 = (member: Member) => member.id === \"worker_000004\"\n    const set = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const result1 = pipe(set, SortedSet.some(isWorker1))\n    const result2 = pipe(set, SortedSet.some(isWorker4))\n\n    assertTrue(result1)\n    assertFalse(result2)\n  })\n\n  it(\"filter\", () => {\n    const isWorker1 = (member: Member) => member.id === \"worker_000001\"\n    const set = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const result = pipe(set, SortedSet.filter(isWorker1))\n\n    deepStrictEqual(Array.from(result), [new Member(\"worker_000001\")])\n  })\n\n  it(\"flatMap\", () => {\n    const set1 = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const set2 = [\n      new Member(\"worker_000001\"),\n      new Member(\"worker_000002\"),\n      new Member(\"worker_000003\")\n    ]\n\n    const result = pipe(set1, SortedSet.flatMap(OrdMember, (a) => [...set2, a]))\n\n    deepStrictEqual(\n      Array.from(result),\n      [\n        new Member(\"worker_000000\"),\n        new Member(\"worker_000001\"),\n        new Member(\"worker_000002\"),\n        new Member(\"worker_000003\")\n      ]\n    )\n  })\n\n  it(\"forEach\", () => {\n    const set1 = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const result: Array<string> = []\n\n    pipe(\n      set1,\n      SortedSet.forEach((member) => {\n        result.push(member.id)\n      })\n    )\n\n    deepStrictEqual(result, [\"worker_000000\", \"worker_000001\", \"worker_000002\"])\n  })\n\n  it(\"has\", () => {\n    const set = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    assertTrue(pipe(set, SortedSet.has(new Member(\"worker_000000\"))))\n    assertFalse(pipe(set, SortedSet.has(new Member(\"worker_000004\"))))\n  })\n\n  it(\"intersection\", () => {\n    const set1 = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const set2 = [\n      new Member(\"worker_000001\"),\n      new Member(\"worker_000002\"),\n      new Member(\"worker_000003\")\n    ]\n\n    const set3 = [\n      new Member(\"worker_000005\")\n    ]\n\n    const result1 = pipe(set1, SortedSet.intersection(set2))\n    const result2 = pipe(set1, SortedSet.intersection(set3))\n\n    deepStrictEqual(\n      Array.from(result1),\n      [\n        new Member(\"worker_000001\"),\n        new Member(\"worker_000002\")\n      ]\n    )\n    deepStrictEqual(Array.from(result2), [])\n  })\n\n  it(\"isSubset\", () => {\n    const set1 = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const set2 = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const set3 = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000005\"))\n    )\n\n    assertTrue(pipe(set2, SortedSet.isSubset(set1)))\n    assertFalse(pipe(set3, SortedSet.isSubset(set1)))\n  })\n\n  it(\"map\", () => {\n    const set = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const result = pipe(\n      set,\n      SortedSet.map(Str.Order, (member) => member.id.replace(/_\\d+/g, \"\"))\n    )\n\n    deepStrictEqual(Array.from(result), [\"worker\"])\n  })\n\n  it(\"partition\", () => {\n    const set = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\")),\n      SortedSet.add(new Member(\"worker_000003\"))\n    )\n\n    const result = pipe(\n      set,\n      SortedSet.partition((member) => member.id.endsWith(\"1\") || member.id.endsWith(\"3\"))\n    )\n\n    deepStrictEqual(\n      Array.from(result[0]),\n      [\n        new Member(\"worker_000000\"),\n        new Member(\"worker_000002\")\n      ]\n    )\n    deepStrictEqual(\n      Array.from(result[1]),\n      [\n        new Member(\"worker_000001\"),\n        new Member(\"worker_000003\")\n      ]\n    )\n  })\n\n  it(\"remove\", () => {\n    const set = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const result = pipe(set, SortedSet.remove(new Member(\"worker_000000\")))\n\n    deepStrictEqual(\n      Array.from(result),\n      [\n        new Member(\"worker_000001\"),\n        new Member(\"worker_000002\")\n      ]\n    )\n  })\n\n  it(\"size\", () => {\n    const set = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    strictEqual(SortedSet.size(set), 3)\n  })\n\n  it(\"toggle\", () => {\n    const member = new Member(\"worker_000000\")\n    let set = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    assertTrue(pipe(set, SortedSet.has(member)))\n\n    set = pipe(set, SortedSet.toggle(member))\n\n    assertFalse(pipe(set, SortedSet.has(member)))\n\n    set = pipe(set, SortedSet.toggle(member))\n\n    assertTrue(pipe(set, SortedSet.has(member)))\n  })\n\n  it(\"union\", () => {\n    const set1 = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000000\")),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\"))\n    )\n\n    const set2 = pipe(\n      SortedSet.empty(OrdMember),\n      SortedSet.add(new Member(\"worker_000001\")),\n      SortedSet.add(new Member(\"worker_000002\")),\n      SortedSet.add(new Member(\"worker_000003\"))\n    )\n\n    const set3: Array<Member> = []\n\n    const result1 = pipe(set1, SortedSet.union(set2))\n    const result2 = pipe(set1, SortedSet.union(set3))\n\n    deepStrictEqual(\n      Array.from(result1),\n      [\n        new Member(\"worker_000000\"),\n        new Member(\"worker_000001\"),\n        new Member(\"worker_000002\"),\n        new Member(\"worker_000003\")\n      ]\n    )\n    deepStrictEqual(result2, set1)\n  })\n\n  it(\"values\", () => {\n    const set = SortedSet.make(Str.Order)(\"c\", \"a\", \"b\")\n    const values = SortedSet.values(set)\n    deepStrictEqual(Array.from(values), [\"a\", \"b\", \"c\"])\n  })\n\n  it(\"pipe()\", () => {\n    strictEqual(SortedSet.make(Str.Order)(\"c\", \"a\", \"b\").pipe(SortedSet.size), 3)\n  })\n\n  it(\"Equal.symbol\", () => {\n    assertTrue(Equal.equals(SortedSet.empty(Str.Order), SortedSet.empty(Str.Order)))\n    const set1 = SortedSet.make(Str.Order)(\"c\", \"a\", \"b\")\n    const set2 = SortedSet.make(Str.Order)(\"c\", \"a\", \"b\")\n    const set3 = SortedSet.make(Str.Order)(\"d\", \"b\", \"a\")\n    assertTrue(Equal.equals(set1, set2))\n    assertTrue(Equal.equals(set2, set1))\n    assertFalse(Equal.equals(set1, set3))\n    assertFalse(Equal.equals(set3, set1))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/aggregation.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { constTrue, constVoid, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Queue from \"effect/Queue\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\nimport * as Take from \"effect/Take\"\nimport * as TestClock from \"effect/TestClock\"\nimport * as TestServices from \"effect/TestServices\"\nimport { chunkCoordination } from \"../utils/coordination.js\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"aggregate - simple example\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 1, 1, 1),\n        Stream.aggregate(\n          Sink.foldUntil(Chunk.empty<number>(), 3, Chunk.prepend)\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(Chunk.flatten(result)), [1, 1, 1, 1])\n      assertTrue(Array.from(result).every((chunk) => chunk.length <= 3))\n    }))\n\n  it.effect(\"aggregate - error propagation #1\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Boom\")\n      const result = yield* pipe(\n        Stream.make(1, 1, 1, 1),\n        Stream.aggregate(Sink.die(error)),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"aggregate - error propagation #2\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Boom\")\n      const result = yield* pipe(\n        Stream.make(1, 1),\n        Stream.aggregate(\n          Sink.foldLeftEffect(Chunk.empty(), () => Effect.die(error))\n        ),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"aggregate - interruption propagation #1\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<void>())\n      const ref = yield* (Ref.make(false))\n      const sink = Sink.foldEffect(Chunk.empty<number>(), constTrue, (acc, curr) => {\n        if (curr === 1) {\n          return Effect.succeed(Chunk.prepend(acc, curr))\n        }\n        return pipe(\n          Deferred.succeed(latch, void 0),\n          Effect.zipRight(Effect.never),\n          Effect.onInterrupt(() => Ref.set(ref, true))\n        )\n      })\n      const fiber = yield* pipe(\n        Stream.make(1, 1, 2),\n        Stream.aggregate(sink),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"aggregate - interruption propagation #2\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<void>())\n      const ref = yield* (Ref.make(false))\n      const sink = Sink.fromEffect(pipe(\n        Deferred.succeed(latch, void 0),\n        Effect.zipRight(Effect.never),\n        Effect.onInterrupt(() => Ref.set(ref, true))\n      ))\n      const fiber = yield* pipe(\n        Stream.make(1, 1, 2),\n        Stream.aggregate(sink),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"aggregate - leftover handling\", () =>\n    Effect.gen(function*() {\n      const input = [1, 2, 2, 3, 2, 3]\n      const result = yield* pipe(\n        Stream.fromIterable(input),\n        Stream.aggregate(Sink.foldWeighted({\n          initial: Chunk.empty<number>(),\n          maxCost: 4,\n          cost: (_, n) => n,\n          body: (acc, curr) => Chunk.append(acc, curr)\n        })),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(Chunk.flatten(result)), input)\n    }))\n\n  it.effect(\"aggregate - ZIO issue 6395\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.aggregate(Sink.collectAllN(2)),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2], [3]]\n      )\n    }))\n\n  // Explicitly uses live Clock\n  it.effect(\"issue from zio-kafka\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (Queue.unbounded<Take.Take<number>>())\n      const fiber = yield* pipe(\n        Stream.fromQueue(queue),\n        Stream.flattenTake,\n        Stream.aggregate(\n          Sink.foldLeft(Chunk.empty<number>(), (acc, n) => Chunk.append(acc, n))\n        ),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (TestServices.provideLive(Effect.sleep(Duration.seconds(1))))\n      yield* (Queue.offer(queue, Take.chunk(Chunk.make(1, 2, 3, 4, 5))))\n      yield* (TestServices.provideLive(Effect.sleep(Duration.seconds(1))))\n      yield* (Queue.offer(queue, Take.chunk(Chunk.make(6, 7, 8, 9, 10))))\n      yield* (TestServices.provideLive(Effect.sleep(Duration.seconds(1))))\n      yield* (Queue.offer(queue, Take.chunk(Chunk.make(11, 12, 13, 14, 15))))\n      yield* (Queue.offer(queue, Take.end))\n      const result = yield* pipe(\n        Fiber.join(fiber),\n        Effect.map(Chunk.filter(Chunk.isNonEmpty))\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]\n      )\n    }))\n\n  it.effect(\"aggregateWithin - child fiber handling\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* (chunkCoordination([\n        Chunk.of(1),\n        Chunk.of(2),\n        Chunk.of(3)\n      ]))\n      const fiber = yield* pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.map(Take.make),\n        Stream.tap(() => coordination.proceed),\n        Stream.flattenTake,\n        Stream.aggregateWithin(\n          Sink.last<number>(),\n          Schedule.fixed(Duration.millis(200))\n        ),\n        Stream.interruptWhen(Effect.never),\n        Stream.take(2),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.millis(100))),\n        Effect.zipRight(coordination.awaitNext),\n        Effect.repeatN(3)\n      )\n      const results = yield* pipe(Fiber.join(fiber), Effect.map(Chunk.compact))\n      deepStrictEqual(Array.from(results), [2, 3])\n    }))\n\n  it.effect(\"aggregateWithinEither - simple example\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 1, 1, 1, 2, 2),\n        Stream.aggregateWithinEither(\n          pipe(\n            Sink.fold(\n              [[] as Array<number>, true] as readonly [Array<number>, boolean],\n              (tuple) => tuple[1],\n              ([array], curr: number): readonly [Array<number>, boolean] => {\n                if (curr === 1) {\n                  return [[curr, ...array], true]\n                }\n                return [[curr, ...array], false]\n              }\n            ),\n            Sink.map((tuple) => tuple[0])\n          ),\n          Schedule.spaced(Duration.minutes(30))\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result),\n        [Either.right([2, 1, 1, 1, 1]), Either.right([2])]\n      )\n    }))\n\n  it.effect(\"aggregateWithinEither - fails fast\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (Queue.unbounded<number>())\n      yield* pipe(\n        Stream.range(1, 9),\n        Stream.tap((n) =>\n          pipe(\n            Effect.fail(\"Boom\"),\n            Effect.when(() => n === 6),\n            Effect.zipRight(Queue.offer(queue, n))\n          )\n        ),\n        Stream.aggregateWithinEither(\n          Sink.foldUntil(void 0, 5, constVoid),\n          Schedule.forever\n        ),\n        Stream.runDrain,\n        Effect.catchAll(() => Effect.succeed(void 0))\n      )\n      const result = yield* (Queue.takeAll(queue))\n      yield* (Queue.shutdown(queue))\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"aggregateWithinEither - error propagation #1\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Boom\")\n      const result = yield* pipe(\n        Stream.make(1, 1, 1, 1),\n        Stream.aggregateWithinEither(\n          Sink.die(error),\n          Schedule.spaced(Duration.minutes(30))\n        ),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"aggregateWithinEither - error propagation #2\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Boom\")\n      const result = yield* pipe(\n        Stream.make(1, 1),\n        Stream.aggregateWithinEither(\n          Sink.foldEffect(Chunk.empty<number>(), constTrue, () => Effect.die(error)),\n          Schedule.spaced(Duration.minutes(30))\n        ),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"aggregateWithinEither - interruption propagation #1\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<void>())\n      const ref = yield* (Ref.make(false))\n      const sink = Sink.foldEffect(Chunk.empty<number>(), constTrue, (acc, curr) => {\n        if (curr === 1) {\n          return Effect.succeed(Chunk.prepend(acc, curr))\n        }\n        return pipe(\n          Deferred.succeed(latch, void 0),\n          Effect.zipRight(Effect.never),\n          Effect.onInterrupt(() => Ref.set(ref, true))\n        )\n      })\n      const fiber = yield* pipe(\n        Stream.make(1, 1, 2),\n        Stream.aggregateWithinEither(sink, Schedule.spaced(Duration.minutes(30))),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"aggregateWithinEither - interruption propagation #2\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<void>())\n      const ref = yield* (Ref.make(false))\n      const sink = Sink.fromEffect(pipe(\n        Deferred.succeed(latch, void 0),\n        Effect.zipRight(Effect.never),\n        Effect.onInterrupt(() => Ref.set(ref, true))\n      ))\n      const fiber = yield* pipe(\n        Stream.make(1, 1, 2),\n        Stream.aggregateWithinEither(sink, Schedule.spaced(Duration.minutes(30))),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"aggregateWithinEither - leftover handling\", () =>\n    Effect.gen(function*() {\n      const input = [1, 2, 2, 3, 2, 3]\n      const fiber = yield* pipe(\n        Stream.fromIterable(input),\n        Stream.aggregateWithinEither(\n          Sink.foldWeighted({\n            initial: Chunk.empty<number>(),\n            maxCost: 4,\n            cost: (_, n) => n,\n            body: (acc, curr) => Chunk.append(acc, curr)\n          }),\n          Schedule.spaced(Duration.millis(100))\n        ),\n        Stream.filterMap((either) =>\n          Either.isRight(either) ?\n            Option.some(either.right) :\n            Option.none()\n        ),\n        Stream.runCollect,\n        Effect.map(Chunk.flatten),\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.minutes(31)))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), input)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/async.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"async\", () =>\n    Effect.gen(function*() {\n      const array = [1, 2, 3, 4, 5]\n      const result = yield* pipe(\n        Stream.async<number>((emit) => {\n          array.forEach((n) => {\n            emit(Effect.succeed(Chunk.of(n)))\n          })\n        }),\n        Stream.take(array.length),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), array)\n    }))\n\n  it.effect(\"async - with cleanup\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Stream.async<void>((emit) => {\n          emit.chunk(Chunk.of(void 0))\n          return Ref.set(ref, true)\n        }),\n        Stream.tap(() => Deferred.succeed(latch, void 0)),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"async - signals the end of the stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.async<number>((emit) => {\n          emit.end()\n          return Effect.void\n        }),\n        Stream.runCollect\n      )\n      assertTrue(Chunk.isEmpty(result))\n    }))\n\n  it.effect(\"async - handles errors\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.async<number, Cause.RuntimeException>((emit) => {\n          emit.fromEffect(Effect.fail(error))\n          return Effect.void\n        }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"async - handles defects\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.async<number, Cause.RuntimeException>(() => {\n          throw error\n        }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"async - backpressure\", () =>\n    Effect.gen(function*() {\n      const refCount = yield* (Ref.make(0))\n      const refDone = yield* (Ref.make(false))\n      const stream = Stream.async<number, Option.Option<never>>((emit) => {\n        Promise.all(\n          // 1st consumed by sink, 2-6 – in queue, 7th – back pressured\n          [1, 2, 3, 4, 5, 6, 7].map((n) =>\n            emit.fromEffectChunk(\n              pipe(\n                Ref.set(refCount, n),\n                Effect.zipRight(Effect.succeed(Chunk.of(1)))\n              )\n            )\n          )\n        ).then(() =>\n          emit.fromEffect(\n            pipe(\n              Ref.set(refDone, true),\n              Effect.zipRight(Effect.fail(Option.none()))\n            )\n          )\n        )\n        return Effect.void\n      }, 5)\n      const sink = pipe(Sink.take<number>(1), Sink.zipRight(Sink.never))\n      const fiber = yield* pipe(stream, Stream.run(sink), Effect.fork)\n      yield* pipe(Ref.get(refCount), Effect.repeat({ while: (n) => n !== 7 }))\n      const result = yield* (Ref.get(refDone))\n      yield* pipe(Fiber.interrupt(fiber), Effect.exit)\n      assertFalse(result)\n    }))\n\n  it.effect(\"asyncEffect - simple example\", () =>\n    Effect.gen(function*() {\n      const array = [1, 2, 3, 4, 5]\n      const latch = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Stream.asyncEffect<number>((emit) => {\n          array.forEach((n) => {\n            emit(Effect.succeed(Chunk.of(n)))\n          })\n          return pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.zipRight(Effect.void)\n          )\n        }),\n        Stream.take(array.length),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), array)\n    }))\n\n  it.effect(\"asyncEffect - handles errors\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.asyncEffect<number, Cause.RuntimeException>((emit) => {\n          emit.fromEffect(Effect.fail(error))\n          return Effect.void\n        }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"asyncEffect - handles defects\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.asyncEffect<number, Cause.RuntimeException>(() => {\n          throw error\n        }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"asyncEffect - signals the end of the stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.asyncEffect<number>((emit) => {\n          emit(Effect.fail(Option.none()))\n          return Effect.void\n        }),\n        Stream.runCollect\n      )\n      assertTrue(Chunk.isEmpty(result))\n    }))\n\n  it.effect(\"asyncEffect - backpressure\", () =>\n    Effect.gen(function*() {\n      const refCount = yield* (Ref.make(0))\n      const refDone = yield* (Ref.make(false))\n      const stream = Stream.asyncEffect<number, Option.Option<never>>((emit) => {\n        Promise.all(\n          // 1st consumed by sink, 2-6 – in queue, 7th – back pressured\n          [1, 2, 3, 4, 5, 6, 7].map((n) =>\n            emit.fromEffectChunk(\n              pipe(\n                Ref.set(refCount, n),\n                Effect.zipRight(Effect.succeed(Chunk.of(1)))\n              )\n            )\n          )\n        ).then(() =>\n          emit.fromEffect(\n            pipe(\n              Ref.set(refDone, true),\n              Effect.zipRight(Effect.fail(Option.none()))\n            )\n          )\n        )\n        return Effect.void\n      }, 5)\n      const sink = pipe(Sink.take<number>(1), Sink.zipRight(Sink.never))\n      const fiber = yield* pipe(stream, Stream.run(sink), Effect.fork)\n      yield* pipe(Ref.get(refCount), Effect.repeat({ while: (n) => n !== 7 }))\n      const result = yield* (Ref.get(refDone))\n      yield* (Fiber.interrupt(fiber))\n      assertFalse(result)\n    }))\n\n  // it.effect(\"asyncOption - signals the end of the stream\", () =>\n  //   Effect.gen(function*() {\n  //     const result = yield* (\n  //       Stream.asyncOption<number>((emit) => {\n  //         emit(Effect.fail(Option.none()))\n  //         return Option.none()\n  //       }),\n  //       Stream.runCollect\n  //     )\n  //     assertTrue(Chunk.isEmpty(result))\n  //   }))\n\n  // it.effect(\"asyncOption - some\", () =>\n  //   Effect.gen(function*() {\n  //     const chunk = Chunk.range(1, 5)\n  //     const result = yield* (\n  //       Stream.asyncOption<number>(() => Option.some(Stream.fromChunk(chunk))),\n  //       Stream.runCollect\n  //     )\n  //     deepStrictEqual(Array.from(result), Array.from(chunk))\n  //   }))\n\n  // it.effect(\"asyncOption - none\", () =>\n  //   Effect.gen(function*() {\n  //     const array = [1, 2, 3, 4, 5]\n  //     const result = yield* (\n  //       Stream.asyncOption<number>((emit) => {\n  //         array.forEach((n) => {\n  //           emit(Effect.succeed(Chunk.of(n)))\n  //         })\n  //         return Option.none()\n  //       }),\n  //       Stream.take(array.length),\n  //       Stream.runCollect\n  //     )\n  //     deepStrictEqual(Array.from(result), array)\n  //   }))\n\n  // it.effect(\"asyncOption - handles errors\", () =>\n  //   Effect.gen(function*() {\n  //     const error = new Cause.RuntimeException(\"boom\")\n  //     const result = yield* (\n  //       Stream.asyncOption<number, Cause.RuntimeException>((emit) => {\n  //         emit.fromEffect(Effect.fail(error))\n  //         return Option.none()\n  //       }),\n  //       Stream.runCollect,\n  //       Effect.exit\n  //     )\n  //     deepStrictEqual(result, Exit.fail(error))\n  //   }))\n\n  // it.effect(\"asyncOption - handles defects\", () =>\n  //   Effect.gen(function*() {\n  //     const error = new Cause.RuntimeException(\"boom\")\n  //     const result = yield* (\n  //       Stream.asyncOption<number, Cause.RuntimeException>(() => {\n  //         throw error\n  //       }),\n  //       Stream.runCollect,\n  //       Effect.exit\n  //     )\n  //     deepStrictEqual(result, Exit.die(error))\n  //   }))\n\n  // it.effect(\"asyncOption - backpressure\", () =>\n  //   Effect.gen(function*() {\n  //     const refCount = yield* (Ref.make(0))\n  //     const refDone = yield* (Ref.make(false))\n  //     const stream = Stream.asyncOption<number, Option.Option<never>>((emit) => {\n  //       Promise.all(\n  //         // 1st consumed by sink, 2-6 – in queue, 7th – back pressured\n  //         [1, 2, 3, 4, 5, 6, 7].map((n) =>\n  //           emit.fromEffectChunk(\n  //             pipe(\n  //               Ref.set(refCount, n),\n  //               Effect.zipRight(Effect.succeed(Chunk.of(1)))\n  //             )\n  //           )\n  //         )\n  //       ).then(() =>\n  //         emit.fromEffect(\n  //           pipe(\n  //             Ref.set(refDone, true),\n  //             Effect.zipRight(Effect.fail(Option.none()))\n  //           )\n  //         )\n  //       )\n  //       return Option.none()\n  //     }, 5)\n  //     const sink = pipe(Sink.take<number>(1), Sink.zipRight(Sink.never))\n  //     const fiber = yield* (stream, Stream.run(sink), Effect.fork)\n  //     yield* (Ref.get(refCount), Effect.repeat({ while: (n) => n !== 7 }))\n  //     const result = yield* (Ref.get(refDone))\n  //     yield* (Fiber.interrupt(fiber), Effect.exit)\n  //     assertFalse(result)\n  //   }))\n\n  it.effect(\"asyncScoped\", () =>\n    Effect.gen(function*() {\n      const array = [1, 2, 3, 4, 5]\n      const latch = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Stream.asyncScoped<number>((cb) => {\n          array.forEach((n) => {\n            cb(Effect.succeed(Chunk.of(n)))\n          })\n          return pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.asVoid\n          )\n        }),\n        Stream.take(array.length),\n        Stream.run(Sink.collectAll()),\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), array)\n    }))\n\n  it.effect(\"asyncScoped - signals the end of the stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.asyncScoped<number>((cb) => {\n          cb(Effect.fail(Option.none()))\n          return Effect.void\n        }),\n        Stream.runCollect\n      )\n      assertTrue(Chunk.isEmpty(result))\n    }))\n\n  it.effect(\"asyncScoped - handles errors\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.asyncScoped<number, Cause.RuntimeException>((cb) => {\n          cb(Effect.fail(Option.some(error)))\n          return Effect.void\n        }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"asyncScoped - handles defects\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.asyncScoped<number, Cause.RuntimeException>(() => {\n          throw error\n        }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"asyncScoped - backpressure\", () =>\n    Effect.gen(function*() {\n      const refCount = yield* (Ref.make(0))\n      const refDone = yield* (Ref.make(false))\n      const stream = Stream.asyncScoped<number, Option.Option<never>>((cb) => {\n        Promise.all(\n          // 1st consumed by sink, 2-6 – in queue, 7th – back pressured\n          [1, 2, 3, 4, 5, 6, 7].map((n) =>\n            cb(\n              pipe(\n                Ref.set(refCount, n),\n                Effect.zipRight(Effect.succeed(Chunk.of(1)))\n              )\n            )\n          )\n        ).then(() =>\n          cb(\n            pipe(\n              Ref.set(refDone, true),\n              Effect.zipRight(Effect.fail(Option.none()))\n            )\n          )\n        )\n        return Effect.void\n      }, 5)\n      const sink = pipe(Sink.take<number>(1), Sink.zipRight(Sink.never))\n      const fiber = yield* pipe(stream, Stream.run(sink), Effect.fork)\n      yield* pipe(Ref.get(refCount), Effect.repeat({ while: (n) => n !== 7 }))\n      const result = yield* (Ref.get(refDone))\n      yield* pipe(Fiber.interrupt(fiber), Effect.exit)\n      assertFalse(result)\n    }))\n\n  it.effect(\"asyncPush\", () =>\n    Effect.gen(function*() {\n      const array = [1, 2, 3, 4, 5]\n      const latch = yield* Deferred.make<void>()\n      const fiber = yield* Stream.asyncPush<number>((emit) => {\n        array.forEach((n) => {\n          emit.single(n)\n        })\n        return pipe(\n          Deferred.succeed(latch, void 0),\n          Effect.asVoid\n        )\n      }).pipe(\n        Stream.take(array.length),\n        Stream.run(Sink.collectAll()),\n        Effect.fork\n      )\n      yield* Deferred.await(latch)\n      const result = yield* Fiber.join(fiber)\n      deepStrictEqual(Array.from(result), array)\n    }))\n\n  it.effect(\"asyncPush - signals the end of the stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* Stream.asyncPush<number>((emit) => {\n        emit.end()\n        return Effect.void\n      }).pipe(Stream.runCollect)\n      assertTrue(Chunk.isEmpty(result))\n    }))\n\n  it.effect(\"asyncPush - handles errors\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* Stream.asyncPush<number, Cause.RuntimeException>((emit) => {\n        emit.fail(error)\n        return Effect.void\n      }).pipe(\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"asyncPush - handles defects\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* Stream.asyncPush<number, Cause.RuntimeException>(() => {\n        throw error\n      }).pipe(\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/broadcasting.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"broadcast - values\", () =>\n    Effect.gen(function*() {\n      const { result1, result2 } = yield* pipe(\n        Stream.range(0, 4),\n        Stream.broadcast(2, 12),\n        Effect.flatMap((streams) =>\n          Effect.all({\n            result1: Stream.runCollect(streams[0]),\n            result2: Stream.runCollect(streams[1])\n          })\n        ),\n        Effect.scoped\n      )\n      const expected = [0, 1, 2, 3, 4]\n      deepStrictEqual(Array.from(result1), expected)\n      deepStrictEqual(Array.from(result2), expected)\n    }))\n\n  it.effect(\"broadcast - errors\", () =>\n    Effect.gen(function*() {\n      const { result1, result2 } = yield* pipe(\n        Stream.make(0),\n        Stream.concat(Stream.fail(\"boom\")),\n        Stream.broadcast(2, 12),\n        Effect.flatMap((streams) =>\n          Effect.all({\n            result1: pipe(streams[0], Stream.runCollect, Effect.either),\n            result2: pipe(streams[1], Stream.runCollect, Effect.either)\n          })\n        ),\n        Effect.scoped\n      )\n      assertLeft(result1, \"boom\")\n      assertLeft(result2, \"boom\")\n    }))\n\n  it.effect(\"broadcast - backpressure\", () =>\n    Effect.gen(function*() {\n      const { result1, result2 } = yield* pipe(\n        Stream.range(0, 4),\n        Stream.flatMap(Stream.succeed),\n        Stream.broadcast(2, 2),\n        Effect.flatMap((streams) =>\n          Effect.gen(function*() {\n            const ref = yield* (Ref.make(Chunk.empty<number>()))\n            const latch = yield* (Deferred.make<void>())\n            const fiber = yield* pipe(\n              streams[0],\n              Stream.tap((n) =>\n                pipe(\n                  Ref.update(ref, Chunk.append(n)),\n                  Effect.zipRight(pipe(\n                    Deferred.succeed(latch, void 0),\n                    Effect.when(() => n === 1)\n                  ))\n                )\n              ),\n              Stream.runDrain,\n              Effect.fork\n            )\n            yield* (Deferred.await(latch))\n            const result1 = yield* (Ref.get(ref))\n            yield* (Stream.runDrain(streams[1]))\n            yield* (Fiber.await(fiber))\n            const result2 = yield* (Ref.get(ref))\n            return { result1, result2 }\n          })\n        ),\n        Effect.scoped\n      )\n      deepStrictEqual(Array.from(result1), [0, 1])\n      deepStrictEqual(Array.from(result2), [0, 1, 2, 3, 4])\n    }))\n\n  it.effect(\"broadcast - unsubscribe\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(0, 4),\n        Stream.broadcast(2, 2),\n        Effect.flatMap((streams) =>\n          pipe(\n            Stream.toPull(streams[0]),\n            Effect.ignore,\n            Effect.scoped,\n            Effect.zipRight(Stream.runCollect(streams[1]))\n          )\n        ),\n        Effect.scoped\n      )\n      deepStrictEqual(Array.from(result), [0, 1, 2, 3, 4])\n    }))\n\n  it.scoped(\"share sequenced\", () =>\n    Effect.gen(function*() {\n      const sharedStream = yield* Stream.fromSchedule(Schedule.spaced(\"1 seconds\")).pipe(\n        Stream.share({ capacity: 16 })\n      )\n\n      const firstFiber = yield* sharedStream.pipe(\n        Stream.take(1),\n        Stream.run(Sink.collectAll()),\n        Effect.map(Array.from),\n        Effect.fork\n      )\n\n      yield* TestClock.adjust(\"1 second\")\n\n      const first = yield* Fiber.join(firstFiber)\n      deepStrictEqual(first, [0])\n\n      const secondFiber = yield* sharedStream.pipe(\n        Stream.take(1),\n        Stream.run(Sink.collectAll()),\n        Effect.map(Array.from),\n        Effect.fork\n      )\n\n      yield* TestClock.adjust(\"1 second\")\n\n      const second = yield* Fiber.join(secondFiber)\n      deepStrictEqual(second, [0])\n    }))\n\n  it.scoped(\"share sequenced with idleTimeToLive\", () =>\n    Effect.gen(function*() {\n      const sharedStream = yield* Stream.fromSchedule(Schedule.spaced(\"1 seconds\")).pipe(\n        Stream.share({\n          capacity: 16,\n          idleTimeToLive: \"1 second\"\n        })\n      )\n\n      const firstFiber = yield* sharedStream.pipe(\n        Stream.take(1),\n        Stream.run(Sink.collectAll()),\n        Effect.map(Array.from),\n        Effect.fork\n      )\n\n      yield* TestClock.adjust(\"1 second\")\n\n      const first = yield* Fiber.join(firstFiber)\n      deepStrictEqual(first, [0])\n\n      const secondFiber = yield* sharedStream.pipe(\n        Stream.take(1),\n        Stream.run(Sink.collectAll()),\n        Effect.map(Array.from),\n        Effect.fork\n      )\n\n      yield* TestClock.adjust(\"1 second\")\n\n      const second = yield* Fiber.join(secondFiber)\n      deepStrictEqual(second, [1])\n    }))\n\n  it.scoped(\"share parallel\", () =>\n    Effect.gen(function*() {\n      const sharedStream = yield* Stream.fromSchedule(Schedule.spaced(\"1 seconds\")).pipe(\n        Stream.share({ capacity: 16 })\n      )\n\n      const fiber1 = yield* sharedStream.pipe(\n        Stream.take(1),\n        Stream.run(Sink.collectAll()),\n        Effect.map((x) => Array.from(x)),\n        Effect.fork\n      )\n      const fiber2 = yield* sharedStream.pipe(\n        Stream.take(2),\n        Stream.run(Sink.collectAll()),\n        Effect.map((x) => Array.from(x)),\n        Effect.fork\n      )\n\n      yield* TestClock.adjust(\"2 second\")\n      const [result1, result2] = yield* Fiber.joinAll([fiber1, fiber2])\n\n      deepStrictEqual(result1, [0])\n      deepStrictEqual(result2, [0, 1])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/buffering.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"buffer - maintains elements and ordering\", () =>\n    Effect.gen(function*() {\n      const chunks = Chunk.make(\n        Chunk.range(0, 3),\n        Chunk.range(2, 5),\n        Chunk.range(3, 7)\n      )\n      const result = yield* pipe(\n        Stream.fromChunks(...chunks),\n        Stream.buffer({ capacity: 2 }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(Chunk.flatten(chunks)))\n    }))\n\n  it.effect(\"buffer - buffers a stream with a failure\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.range(0, 9),\n        Stream.concat(Stream.fail(error)),\n        Stream.buffer({ capacity: 2 }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"buffer - fast producer progresses independently\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const latch = yield* (Deferred.make<void>())\n      const stream = pipe(\n        Stream.range(1, 4),\n        Stream.tap((n) =>\n          pipe(\n            Ref.update(ref, Chunk.append(n)),\n            Effect.zipRight(pipe(\n              Deferred.succeed(latch, void 0),\n              Effect.when(() => n === 4)\n            ))\n          )\n        ),\n        Stream.buffer({ capacity: 2 })\n      )\n      const result1 = yield* pipe(stream, Stream.take(2), Stream.runCollect)\n      yield* (Deferred.await(latch))\n      const result2 = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result1), [1, 2])\n      deepStrictEqual(Array.from(result2), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"bufferChunks - maintains elements and ordering\", () =>\n    Effect.gen(function*() {\n      const chunks = Chunk.make(\n        Chunk.range(0, 3),\n        Chunk.range(2, 5),\n        Chunk.range(3, 7)\n      )\n      const result = yield* pipe(\n        Stream.fromChunks(...chunks),\n        Stream.bufferChunks({ capacity: 2 }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(Chunk.flatten(chunks)))\n    }))\n\n  it.effect(\"bufferChunks - buffers a stream with a failure\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.range(0, 9),\n        Stream.concat(Stream.fail(error)),\n        Stream.bufferChunks({ capacity: 2 }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"bufferChunks - fast producer progresses independently\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const latch = yield* (Deferred.make<void>())\n      const stream = pipe(\n        Stream.range(1, 4),\n        Stream.tap((n) =>\n          pipe(\n            Ref.update(ref, Chunk.append(n)),\n            Effect.zipRight(pipe(\n              Deferred.succeed(latch, void 0),\n              Effect.when(() => n === 4)\n            ))\n          )\n        ),\n        Stream.bufferChunks({ capacity: 2 })\n      )\n      const result1 = yield* pipe(stream, Stream.take(2), Stream.runCollect)\n      yield* (Deferred.await(latch))\n      const result2 = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result1), [1, 2])\n      deepStrictEqual(Array.from(result2), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"bufferChunksDropping - buffers a stream with a failure\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.range(1, 1_000),\n        Stream.concat(Stream.fail(error)),\n        Stream.concat(Stream.range(1_001, 2_000)),\n        Stream.bufferChunks({ capacity: 2, strategy: \"dropping\" }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"bufferChunksDropping - fast producer progress independently\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const latch3 = yield* (Deferred.make<void>())\n      const latch4 = yield* (Deferred.make<void>())\n      const stream1 = pipe(\n        Stream.make(0),\n        Stream.concat(\n          pipe(\n            Stream.fromEffect(Deferred.await(latch1)),\n            Stream.flatMap(() =>\n              pipe(\n                Stream.range(1, 16),\n                Stream.rechunk(1),\n                Stream.ensuring(Deferred.succeed(latch2, void 0))\n              )\n            )\n          )\n        )\n      )\n      const stream2 = pipe(\n        Stream.fromEffect(Deferred.await(latch3)),\n        Stream.flatMap(() =>\n          pipe(\n            Stream.range(17, 24),\n            Stream.rechunk(1),\n            Stream.ensuring(Deferred.succeed(latch4, void 0))\n          )\n        )\n      )\n      const stream3 = Stream.make(-1)\n      const stream = pipe(\n        stream1,\n        Stream.concat(stream2),\n        Stream.concat(stream3),\n        Stream.bufferChunks({ capacity: 8, strategy: \"dropping\" })\n      )\n      const { result1, result2, result3 } = yield* pipe(\n        Stream.toPull(stream),\n        Effect.flatMap((pull) =>\n          Effect.gen(function*() {\n            const result1 = yield* pull\n            yield* (Deferred.succeed(latch1, void 0))\n            yield* (Deferred.await(latch2))\n            yield* pipe(\n              pull,\n              Effect.flatMap((chunk) => Ref.update(ref, Chunk.appendAll(chunk))),\n              Effect.repeatN(7)\n            )\n            const result2 = yield* (Ref.get(ref))\n            yield* (Deferred.succeed(latch3, void 0))\n            yield* (Deferred.await(latch4))\n            yield* pipe(\n              pull,\n              Effect.flatMap((chunk) => Ref.update(ref, Chunk.appendAll(chunk))),\n              Effect.repeatN(7)\n            )\n            const result3 = yield* (Ref.get(ref))\n            return { result1, result2, result3 }\n          })\n        ),\n        Effect.scoped\n      )\n      const expected1 = [0]\n      const expected2 = [1, 2, 3, 4, 5, 6, 7, 8]\n      const expected3 = [1, 2, 3, 4, 5, 6, 7, 8, 17, 18, 19, 20, 21, 22, 23, 24]\n      deepStrictEqual(Array.from(result1), expected1)\n      deepStrictEqual(Array.from(result2), expected2)\n      deepStrictEqual(Array.from(result3), expected3)\n    }))\n\n  it.effect(\"bufferChunksSliding - buffers a stream with a failure\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.range(1, 1_000),\n        Stream.concat(Stream.fail(error)),\n        Stream.concat(Stream.range(1_001, 2_000)),\n        Stream.bufferChunks({ capacity: 2, strategy: \"sliding\" }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"bufferChunksSliding - fast producer progress independently\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const latch3 = yield* (Deferred.make<void>())\n      const latch4 = yield* (Deferred.make<void>())\n      const latch5 = yield* (Deferred.make<void>())\n      const stream1 = pipe(\n        Stream.make(0),\n        Stream.concat(\n          pipe(\n            Stream.fromEffect(Deferred.await(latch1)),\n            Stream.flatMap(() =>\n              pipe(\n                Stream.range(1, 16),\n                Stream.rechunk(1),\n                Stream.ensuring(Deferred.succeed(latch2, void 0))\n              )\n            )\n          )\n        )\n      )\n      const stream2 = pipe(\n        Stream.fromEffect(Deferred.await(latch3)),\n        Stream.flatMap(() =>\n          pipe(\n            Stream.range(17, 25),\n            Stream.rechunk(1),\n            Stream.ensuring(Deferred.succeed(latch4, void 0))\n          )\n        )\n      )\n      const stream3 = pipe(\n        Stream.fromEffect(Deferred.await(latch5)),\n        Stream.flatMap(() => Stream.make(-1))\n      )\n      const stream = pipe(\n        stream1,\n        Stream.concat(stream2),\n        Stream.concat(stream3),\n        Stream.bufferChunks({ capacity: 8, strategy: \"sliding\" })\n      )\n      const { result1, result2, result3 } = yield* pipe(\n        Stream.toPull(stream),\n        Effect.flatMap((pull) =>\n          Effect.gen(function*() {\n            const result1 = yield* pull\n            yield* (Deferred.succeed(latch1, void 0))\n            yield* (Deferred.await(latch2))\n            yield* pipe(\n              pull,\n              Effect.flatMap((chunk) => Ref.update(ref, Chunk.appendAll(chunk))),\n              Effect.repeatN(7)\n            )\n            const result2 = yield* (Ref.get(ref))\n            yield* (Deferred.succeed(latch3, void 0))\n            yield* (Deferred.await(latch4))\n            yield* pipe(\n              pull,\n              Effect.flatMap((chunk) => Ref.update(ref, Chunk.appendAll(chunk))),\n              Effect.repeatN(7)\n            )\n            const result3 = yield* (Ref.get(ref))\n            return { result1, result2, result3 }\n          })\n        ),\n        Effect.scoped\n      )\n      const expected1 = [0]\n      const expected2 = [9, 10, 11, 12, 13, 14, 15, 16]\n      const expected3 = [9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25]\n      deepStrictEqual(Array.from(result1), expected1)\n      deepStrictEqual(Array.from(result2), expected2)\n      deepStrictEqual(Array.from(result3), expected3)\n    }))\n\n  it.effect(\"bufferDropping - buffers a stream with a failure\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.range(1, 1_000),\n        Stream.concat(Stream.fail(error)),\n        Stream.concat(Stream.range(1_000, 2_000)),\n        Stream.buffer({ capacity: 2, strategy: \"dropping\" }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"bufferDropping - fast producer progress independently\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const latch3 = yield* (Deferred.make<void>())\n      const latch4 = yield* (Deferred.make<void>())\n      const stream1 = pipe(\n        Stream.make(0),\n        Stream.concat(\n          pipe(\n            Stream.fromEffect(Deferred.await(latch1)),\n            Stream.flatMap(() =>\n              pipe(\n                Stream.range(1, 17),\n                Stream.rechunk(1),\n                Stream.ensuring(Deferred.succeed(latch2, void 0))\n              )\n            )\n          )\n        )\n      )\n      const stream2 = pipe(\n        Stream.fromEffect(Deferred.await(latch3)),\n        Stream.flatMap(() =>\n          pipe(\n            Stream.range(17, 24),\n            Stream.rechunk(1),\n            Stream.ensuring(Deferred.succeed(latch4, void 0))\n          )\n        )\n      )\n      const stream3 = Stream.make(-1)\n      const stream = pipe(\n        stream1,\n        Stream.concat(stream2),\n        Stream.concat(stream3),\n        Stream.buffer({ capacity: 8, strategy: \"dropping\" })\n      )\n      const { result1, result2, result3 } = yield* pipe(\n        Stream.toPull(stream),\n        Effect.flatMap((pull) =>\n          Effect.gen(function*() {\n            const result1 = yield* pull\n            yield* (Deferred.succeed(latch1, void 0))\n            yield* (Deferred.await(latch2))\n            yield* pipe(\n              pull,\n              Effect.flatMap((chunk) => Ref.update(ref, Chunk.appendAll(chunk))),\n              Effect.repeatN(7)\n            )\n            const result2 = yield* (Ref.get(ref))\n            yield* (Deferred.succeed(latch3, void 0))\n            yield* (Deferred.await(latch4))\n            yield* pipe(\n              pull,\n              Effect.flatMap((chunk) => Ref.update(ref, Chunk.appendAll(chunk))),\n              Effect.repeatN(7)\n            )\n            const result3 = yield* (Ref.get(ref))\n            return { result1, result2, result3 }\n          })\n        ),\n        Effect.scoped\n      )\n      const expected1 = [0]\n      const expected2 = [1, 2, 3, 4, 5, 6, 7, 8]\n      const expected3 = [1, 2, 3, 4, 5, 6, 7, 8, 17, 18, 19, 20, 21, 22, 23, 24]\n      deepStrictEqual(Array.from(result1), expected1)\n      deepStrictEqual(Array.from(result2), expected2)\n      deepStrictEqual(Array.from(result3), expected3)\n    }))\n\n  it.effect(\"bufferSliding - buffers a stream with a failure\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.range(1, 1_000),\n        Stream.concat(Stream.fail(error)),\n        Stream.concat(Stream.range(1_001, 2_000)),\n        Stream.buffer({ capacity: 2, strategy: \"sliding\" }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"bufferSliding - fast producer progress independently\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const latch3 = yield* (Deferred.make<void>())\n      const latch4 = yield* (Deferred.make<void>())\n      const stream1 = pipe(\n        Stream.make(0),\n        Stream.concat(\n          pipe(\n            Stream.fromEffect(Deferred.await(latch1)),\n            Stream.flatMap(() =>\n              pipe(\n                Stream.range(1, 16),\n                Stream.rechunk(1),\n                Stream.ensuring(Deferred.succeed(latch2, void 0))\n              )\n            )\n          )\n        )\n      )\n      const stream2 = pipe(\n        Stream.fromEffect(Deferred.await(latch3)),\n        Stream.flatMap(() =>\n          pipe(\n            Stream.range(17, 24),\n            Stream.rechunk(1),\n            Stream.ensuring(Deferred.succeed(latch4, void 0))\n          )\n        )\n      )\n      const stream3 = Stream.make(-1)\n      const stream = pipe(\n        stream1,\n        Stream.concat(stream2),\n        Stream.concat(stream3),\n        Stream.buffer({ capacity: 8, strategy: \"sliding\" })\n      )\n      const { result1, result2, result3 } = yield* pipe(\n        Stream.toPull(stream),\n        Effect.flatMap((pull) =>\n          Effect.gen(function*() {\n            const result1 = yield* pull\n            yield* (Deferred.succeed(latch1, void 0))\n            yield* (Deferred.await(latch2))\n            yield* pipe(\n              pull,\n              Effect.flatMap((chunk) => Ref.update(ref, Chunk.appendAll(chunk))),\n              Effect.repeatN(7)\n            )\n            const result2 = yield* (Ref.get(ref))\n            yield* (Deferred.succeed(latch3, void 0))\n            yield* (Deferred.await(latch4))\n            yield* pipe(\n              pull,\n              Effect.flatMap((chunk) => Ref.update(ref, Chunk.appendAll(chunk))),\n              Effect.repeatN(7)\n            )\n            const result3 = yield* (Ref.get(ref))\n            return { result1, result2, result3 }\n          })\n        ),\n        Effect.scoped\n      )\n      const expected1 = [0]\n      const expected2 = [9, 10, 11, 12, 13, 14, 15, 16]\n      const expected3 = [9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24, -1]\n      deepStrictEqual(Array.from(result1), expected1)\n      deepStrictEqual(Array.from(result2), expected2)\n      deepStrictEqual(Array.from(result3), expected3)\n    }))\n\n  it.effect(\"bufferSliding - propagates defects\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromEffect(Effect.dieMessage(\"boom\")),\n        Stream.buffer({ capacity: 1, strategy: \"sliding\" }),\n        Stream.runDrain,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(new Cause.RuntimeException(\"boom\")))\n    }))\n\n  it.effect(\"bufferUnbounded - buffers the stream\", () =>\n    Effect.gen(function*() {\n      const chunk = Chunk.range(0, 10)\n      const result = yield* pipe(\n        Stream.fromIterable(chunk),\n        Stream.buffer({ capacity: \"unbounded\" }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(chunk))\n    }))\n\n  it.effect(\"bufferUnbounded -  buffers a stream with a failure\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.range(0, 9),\n        Stream.concat(Stream.fail(error)),\n        Stream.buffer({ capacity: \"unbounded\" }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"bufferUnbounded - fast producer progress independently\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const latch = yield* (Deferred.make<void>())\n      const stream = pipe(\n        Stream.range(1, 999),\n        Stream.tap((n) =>\n          pipe(\n            Ref.update(ref, Chunk.append(n)),\n            Effect.zipRight(pipe(Deferred.succeed(latch, void 0), Effect.when(() => n === 999)))\n          )\n        ),\n        Stream.rechunk(999),\n        Stream.buffer({ capacity: \"unbounded\" })\n      )\n      const result1 = yield* pipe(stream, Stream.take(2), Stream.runCollect)\n      yield* (Deferred.await(latch))\n      const result2 = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result1), [1, 2])\n      deepStrictEqual(Array.from(result2), Array.from(Chunk.range(1, 999)))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/changing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"changes\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.range(0, 19)\n      const result = yield* pipe(\n        stream,\n        Stream.changes,\n        Stream.runCollect\n      )\n      const expected = yield* pipe(\n        stream,\n        Stream.runCollect,\n        Effect.map(Chunk.reduce(Chunk.empty<number>(), (acc, n) =>\n          acc.length === 0 || Chunk.unsafeGet(acc, 0) !== n ? Chunk.append(acc, n) : acc))\n      )\n      deepStrictEqual(Array.from(result), Array.from(expected))\n    }))\n\n  it.effect(\"changesWithEffect\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.range(0, 19)\n      const result = yield* pipe(\n        stream,\n        Stream.changesWithEffect((left, right) => Effect.succeed(left === right)),\n        Stream.runCollect\n      )\n      const expected = yield* pipe(\n        stream,\n        Stream.runCollect,\n        Effect.map(\n          Chunk.reduce(\n            Chunk.empty<number>(),\n            (acc, n) => acc.length === 0 || Chunk.unsafeGet(acc, 0) !== n ? Chunk.append(acc, n) : acc\n          )\n        )\n      )\n      deepStrictEqual(Array.from(result), Array.from(expected))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/collecting.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertRight, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"collect\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(Either.left(1), Either.right(2), Either.left(3)),\n        Stream.filterMap((either) =>\n          Either.isRight(either) ?\n            Option.some(either.right) :\n            Option.none()\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [2])\n    }))\n\n  it.effect(\"collectEffect - simple example\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(Either.left(1), Either.right(2), Either.left(3)),\n        Stream.filterMapEffect((either) =>\n          Either.isRight(either) ?\n            Option.some(Effect.succeed(either.right * 2)) :\n            Option.none()\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [4])\n    }))\n\n  it.effect(\"collectEffect - multiple chunks\", () =>\n    Effect.gen(function*() {\n      const chunks = Chunk.make(\n        Chunk.make(Either.left(1), Either.right(2)),\n        Chunk.make(Either.right(3), Either.left(4))\n      )\n      const result = yield* pipe(\n        Stream.fromChunks(...chunks),\n        Stream.filterMapEffect((either) =>\n          Either.isRight(either) ?\n            Option.some(Effect.succeed(either.right * 10)) :\n            Option.none()\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [20, 30])\n    }))\n\n  it.effect(\"collectEffect - handles failures\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(Either.left(1), Either.right(2), Either.left(3)),\n        Stream.filterMapEffect(() => Option.some(Effect.fail(\"Ouch\"))),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"collectEffect - laziness on chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.filterMapEffect((n) =>\n          n === 3 ?\n            Option.some(Effect.fail(\"boom\")) :\n            Option.some(Effect.succeed(n))\n        ),\n        Stream.either,\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result),\n        [Either.right(1), Either.right(2), Either.left(\"boom\")]\n      )\n    }))\n\n  it.effect(\"collectWhile - simple example\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(Option.some(1), Option.some(2), Option.none(), Option.some(4)),\n        Stream.filterMapWhile(identity),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2])\n    }))\n\n  it.effect(\"collectWhile - short circuits\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(Option.some(1)),\n        Stream.concat(Stream.fail(\"Ouch\")),\n        Stream.filterMapWhile((option) => Option.isNone(option) ? Option.some(1) : Option.none()),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertRight(result, void 0)\n    }))\n\n  it.effect(\"collectWhileEffect - simple example\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(Option.some(1), Option.some(2), Option.none(), Option.some(4)),\n        Stream.filterMapWhileEffect((option) =>\n          Option.isSome(option) ?\n            Option.some(Effect.succeed(option.value * 2)) :\n            Option.none()\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [2, 4])\n    }))\n\n  it.effect(\"collectWhileEffect - short circuits\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(Option.some(1)),\n        Stream.concat(Stream.fail(\"Ouch\")),\n        Stream.filterMapWhileEffect((option) =>\n          Option.isNone(option) ?\n            Option.some(Effect.succeed(1)) :\n            Option.none()\n        ),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertRight(result, void 0)\n    }))\n\n  it.effect(\"collectWhileEffect - fails\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(Option.some(1), Option.some(2), Option.none(), Option.some(3)),\n        Stream.filterMapWhileEffect(() => Option.some(Effect.fail(\"Ouch\"))),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"collectWhileEffect - laziness on chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4),\n        Stream.filterMapWhileEffect((n) =>\n          n === 3 ?\n            Option.some(Effect.fail(\"boom\")) :\n            Option.some(Effect.succeed(n))\n        ),\n        Stream.either,\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result),\n        [Either.right(1), Either.right(2), Either.left(\"boom\")]\n      )\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/concatenation.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"concat - simple example\", () =>\n    Effect.gen(function*() {\n      const stream1 = Stream.make(1, 2, 3)\n      const stream2 = Stream.make(4, 5, 6)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(\n          stream1,\n          Stream.runCollect,\n          Effect.zipWith(\n            pipe(stream2, Stream.runCollect),\n            (chunk1, chunk2) => pipe(chunk1, Chunk.appendAll(chunk2))\n          )\n        ),\n        result2: pipe(\n          stream1,\n          Stream.concat(stream2),\n          Stream.runCollect\n        )\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"concat - finalizer ordering\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<string>()))\n      yield* pipe(\n        Stream.finalizer(Ref.update(ref, Chunk.append(\"Second\"))),\n        Stream.concat(Stream.finalizer(Ref.update(ref, Chunk.append(\"First\")))),\n        Stream.runDrain\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [\"Second\", \"First\"])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/conditionals.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { constFalse, constTrue, constVoid, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"when - returns the stream if the condition is satisfied\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.when(constTrue), Stream.runCollect),\n        result2: Stream.runCollect(stream)\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"when - returns an empty stream if the condition is not satisfied\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4, 5),\n        Stream.when(constFalse),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"when - dies if the condition throws an exception\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.when(() => {\n          throw error\n        }),\n        Stream.runDrain,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"whenCase - returns the resulting stream if the given partial function is defined for the given value\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.whenCase(\n          () => Option.some(1),\n          (option) =>\n            Option.isSome(option) ?\n              Option.some(Stream.make(option.value)) :\n              Option.none()\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1])\n    }))\n\n  it.effect(\"whenCase - returns an empty stream if the given partial function is not defined for the given value\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.whenCase(\n          () => Option.none(),\n          (option) =>\n            Option.isSome(option) ?\n              Option.some(Stream.make(option.value)) :\n              Option.none()\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"whenCase - dies if evaluating the given value throws an exception\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.whenCase(\n          () => {\n            throw error\n          },\n          () => Option.some(Stream.empty)\n        ),\n        Stream.runDrain,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"whenCase - dies if the partial function throws an exception\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.whenCase(\n          constVoid,\n          (): Option.Option<Stream.Stream<void>> => {\n            throw error\n          }\n        ),\n        Stream.runDrain,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"whenCaseEffect - returns the resulting stream if the given partial function is defined for the given effectful value\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.succeed(Option.some(1)),\n        Stream.whenCaseEffect(\n          (option) =>\n            Option.isSome(option) ?\n              Option.some(Stream.make(option.value)) :\n              Option.none()\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1])\n    }))\n\n  it.effect(\"whenCaseEffect - returns an empty stream if the given partial function is not defined for the given effectful value\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Effect.succeed<Option.Option<number>>(Option.none()),\n        Stream.whenCaseEffect(\n          (option) =>\n            Option.isSome(option) ?\n              Option.some(Stream.make(option.value)) :\n              Option.none()\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"whenCaseEffect - fails if the effectful value is a failure\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Effect.fail(error),\n        Stream.whenCaseEffect(() => Option.some(Stream.empty)),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"whenCaseEffect - dies if the given partial function throws an exception\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Effect.void,\n        Stream.whenCaseEffect((): Option.Option<Stream.Stream<void>> => {\n          throw error\n        }),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"whenEffect - returns the stream if the effectful condition is satisfied\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4, 5),\n        Stream.whenEffect(Effect.succeed(true)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"whenEffect - returns an empty stream if the effectful condition is not satisfied\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4, 5),\n        Stream.whenEffect(Effect.succeed(false)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"whenEffect - fails if the effectful condition fails\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.whenEffect(Effect.fail(error)),\n        Stream.runDrain,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/constructors.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertLeft, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport * as fc from \"effect/FastCheck\"\nimport * as Fiber from \"effect/Fiber\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Queue from \"effect/Queue\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\nimport { chunkCoordination } from \"../utils/coordination.js\"\n\nconst chunkArb = <A>(\n  arb: fc.Arbitrary<A>,\n  constraints?: fc.ArrayConstraints\n): fc.Arbitrary<Chunk.Chunk<A>> => fc.array(arb, constraints).map(Chunk.fromIterable)\n\nconst grouped = <A>(arr: Array<A>, size: number): Array<Array<A>> => {\n  const builder: Array<Array<A>> = []\n  for (let i = 0; i < arr.length; i = i + size) {\n    builder.push(arr.slice(i, i + size))\n  }\n  return builder\n}\n\ndescribe(\"Stream\", () => {\n  it(\"concatAll\", () =>\n    fc.assert(fc.asyncProperty(fc.array(chunkArb(fc.integer())), async (chunks) => {\n      const stream = pipe(\n        Chunk.fromIterable(chunks),\n        Chunk.map(Stream.fromChunk),\n        Stream.concatAll\n      )\n      const actual = await Effect.runPromise(Stream.runCollect(stream))\n      const expected = Chunk.flatten(Chunk.fromIterable(chunks))\n      deepStrictEqual(Array.from(actual), Array.from(expected))\n    })))\n\n  it.effect(\"finalizer - happy path\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<string>()))\n      yield* pipe(\n        Stream.acquireRelease(\n          Ref.update(ref, Chunk.append(\"Acquire\")),\n          () => Ref.update(ref, Chunk.append(\"Release\"))\n        ),\n        Stream.flatMap(() => Stream.finalizer(Ref.update(ref, Chunk.append(\"Use\")))),\n        Stream.ensuring(Ref.update(ref, Chunk.append(\"Ensuring\"))),\n        Stream.runDrain\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [\"Acquire\", \"Use\", \"Release\", \"Ensuring\"])\n    }))\n\n  it.effect(\"finalizer - finalizer is not run if stream is not pulled\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      // @effect-diagnostics-next-line floatingEffect:off\n      yield* pipe(\n        Stream.finalizer(Ref.set(ref, true)),\n        Stream.toPull,\n        Effect.scoped\n      )\n      const result = yield* (Ref.get(ref))\n      assertFalse(result)\n    }))\n\n  it(\"fromChunk\", () =>\n    fc.assert(fc.asyncProperty(chunkArb(fc.integer()), async (chunk) => {\n      const stream = Stream.fromChunk(chunk)\n      const result = await Effect.runPromise(Stream.runCollect(stream))\n      deepStrictEqual(Array.from(result), Array.from(chunk))\n    })))\n\n  it(\"fromChunks\", () =>\n    fc.assert(fc.asyncProperty(fc.array(chunkArb(fc.integer())), async (chunks) => {\n      const stream = Stream.fromChunks(...chunks)\n      const result = await Effect.runPromise(Stream.runCollect(stream))\n      deepStrictEqual(\n        Array.from(result),\n        Array.from(Chunk.flatten(Chunk.fromIterable(chunks)))\n      )\n    })))\n\n  it.effect(\"fromChunks - discards empty chunks\", () =>\n    Effect.gen(function*() {\n      const chunks = [Chunk.of(1), Chunk.empty<number>(), Chunk.of(1)]\n      const result = yield* pipe(\n        Stream.fromChunks(...chunks),\n        Stream.toPull,\n        Effect.flatMap((pull) =>\n          pipe(\n            Chunk.range(1, 3),\n            Effect.forEach(() => pipe(Effect.either(pull), Effect.map(Either.map(Chunk.toReadonlyArray))))\n          )\n        ),\n        Effect.scoped\n      )\n      deepStrictEqual(Array.from(result), [\n        Either.right([1]),\n        Either.right([1]),\n        Either.left(Option.none())\n      ])\n    }))\n\n  it.effect(\"fromEffect - failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromEffect(Effect.fail(\"error\")),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"error\")\n    }))\n\n  it.effect(\"fromEffectOption - emit one element with success\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromEffectOption(Effect.succeed(5)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [5])\n    }))\n\n  it.effect(\"fromEffectOption - emit one element with failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromEffectOption(Effect.fail(Option.some(5))),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, 5)\n    }))\n\n  it.effect(\"fromEffectOption - do not emit any element\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromEffectOption(Effect.fail(Option.none())),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"fromSchedule\", () =>\n    Effect.gen(function*() {\n      const schedule = pipe(\n        Schedule.exponential(Duration.seconds(1)),\n        Schedule.zipLeft(Schedule.recurs(5))\n      )\n      const fiber = yield* pipe(\n        Stream.fromSchedule(schedule),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.seconds(62)))\n      const result = yield* (Fiber.join(fiber))\n      const expected = [\n        Duration.seconds(1),\n        Duration.seconds(2),\n        Duration.seconds(4),\n        Duration.seconds(8),\n        Duration.seconds(16)\n      ]\n      deepStrictEqual(Array.from(result), expected)\n    }))\n\n  it.effect(\"fromQueue - emits queued elements\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* (chunkCoordination([Chunk.make(1, 2)]))\n      const fiber = yield* pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.filterMapWhile(Exit.match({\n          onFailure: Option.none,\n          onSuccess: Option.some\n        })),\n        Stream.flattenChunks,\n        Stream.tap(() => coordination.proceed),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (coordination.offer)\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), [1, 2])\n    }))\n\n  it.effect(\"fromQueue - chunks up to the max chunk size\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (Queue.unbounded<number>())\n      yield* (Queue.offerAll(queue, [1, 2, 3, 4, 5, 6, 7]))\n      const result = yield* pipe(\n        Stream.fromQueue(queue, { maxChunkSize: 2 }),\n        Stream.mapChunks((chunk) => Chunk.of(Array.from(chunk))),\n        Stream.take(3),\n        Stream.runCollect\n      )\n      assertTrue(Array.from(result).every((array) => array.length <= 2))\n    }))\n\n  it.effect(\"fromAsyncIterable\", () =>\n    Effect.gen(function*() {\n      async function* asyncIterable() {\n        yield 1\n        yield 2\n        yield 3\n      }\n\n      const stream = Stream.fromAsyncIterable(asyncIterable(), identity)\n      const result = yield* (Stream.runCollect(stream))\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"fromReadableStream\", () =>\n    Effect.gen(function*() {\n      class FromReadableStreamError {\n        readonly _tag = \"FromReadableStreamError\"\n        constructor(readonly error: unknown) {}\n      }\n      class NumberSource implements UnderlyingDefaultSource<number> {\n        #counter = 0\n        pull(controller: ReadableStreamDefaultController<number>) {\n          controller.enqueue(this.#counter)\n          this.#counter = this.#counter + 1\n        }\n      }\n\n      const result = yield* pipe(\n        Stream.fromReadableStream({\n          evaluate: () => new ReadableStream(new NumberSource()),\n          onError: (error) => new FromReadableStreamError(error)\n        }),\n        Stream.take(10),\n        Stream.runCollect\n      )\n\n      deepStrictEqual(Array.from(result), Array.from({ length: 10 }, (_, i) => i))\n    }))\n\n  it.effect(\"iterate\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.iterate(1, (n) => n + 1),\n        Stream.take(10),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(Chunk.range(1, 10)))\n    }))\n\n  it.effect(\"range - includes both endpoints\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Stream.runCollect(Stream.range(1, 2)))\n      deepStrictEqual(Array.from(result), [1, 2])\n    }))\n\n  it.effect(\"range - two large ranges can be concatenated\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 1_000),\n        Stream.concat(Stream.range(1_001, 2_000)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(Chunk.range(1, 2000)))\n    }))\n\n  it.effect(\"range - two small ranges can be concatenated\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 10),\n        Stream.concat(Stream.range(11, 20)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(Chunk.range(1, 20)))\n    }))\n\n  it.effect(\"range - emits no values when start > end\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(2, 1),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"range - emits 1 value when start === end\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 1),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1])\n    }))\n\n  it.effect(\"range - emits values in chunks of chunkSize\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 9, 2),\n        Stream.mapChunks((chunk) => Chunk.make(pipe(chunk, Chunk.reduce(0, (x, y) => x + y)))),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result),\n        [1 + 2, 3 + 4, 5 + 6, 7 + 8, 9]\n      )\n    }))\n\n  it(\"rechunk\", () =>\n    fc.assert(\n      fc.asyncProperty(fc.array(chunkArb(fc.integer())), fc.integer({ min: 1, max: 100 }), async (chunks, n) => {\n        const stream = pipe(\n          Stream.fromChunks(...chunks),\n          Stream.rechunk(n),\n          Stream.mapChunks(Chunk.of)\n        )\n        const actual = await Effect.runPromise(Stream.runCollect(stream))\n        const expected = chunks.map((chunk) => Array.from(chunk)).flat()\n        deepStrictEqual(\n          Array.from(actual).map((chunk) => Array.from(chunk)),\n          grouped(expected, n)\n        )\n      })\n    ))\n\n  it.effect(\"unfold\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.unfold(0, (n) =>\n          n < 10 ?\n            Option.some([n, n + 1] as const) :\n            Option.none()),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(Chunk.range(0, 9)))\n    }))\n\n  it.effect(\"unfoldChunk\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.unfoldChunk(0, (n) =>\n          n < 10 ?\n            Option.some([Chunk.make(n, n + 1), n + 2] as const) :\n            Option.none()),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(Chunk.range(0, 9)))\n    }))\n\n  it.effect(\"unfoldChunkEffect\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.unfoldChunkEffect(0, (n) =>\n          n < 10 ?\n            Effect.succeed(Option.some([Chunk.make(n, n + 1), n + 2] as const)) :\n            Effect.succeed(Option.none())),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(Chunk.range(0, 9)))\n    }))\n\n  it.effect(\"unfoldEffect\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.unfoldEffect(0, (n) =>\n          n < 10 ?\n            Effect.succeed(Option.some([n, n + 1] as const)) :\n            Effect.succeed(Option.none())),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(Chunk.range(0, 9)))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/conversions.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Queue from \"effect/Queue\"\nimport * as Stream from \"effect/Stream\"\nimport * as Take from \"effect/Take\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"toQueue\", () =>\n    Effect.gen(function*() {\n      const chunk = Chunk.make(1, 2, 3)\n      const stream = pipe(\n        Stream.fromChunk(chunk),\n        Stream.flatMap(Stream.succeed)\n      )\n      const result = yield* pipe(\n        stream,\n        Stream.toQueue({ capacity: 1_000 }),\n        Effect.flatMap((queue) =>\n          pipe(\n            Queue.size(queue),\n            Effect.repeat({ while: (size) => size !== chunk.length + 1 }),\n            Effect.zipRight(Queue.takeAll(queue))\n          )\n        ),\n        Effect.scoped\n      )\n      const expected = pipe(\n        chunk,\n        Chunk.map(Take.of),\n        Chunk.append(Take.end)\n      )\n      deepStrictEqual(Array.from(result), Array.from(expected))\n    }))\n\n  it.effect(\"toQueueUnbounded\", () =>\n    Effect.gen(function*() {\n      const chunk = Chunk.make(1, 2, 3)\n      const stream = pipe(\n        Stream.fromChunk(chunk),\n        Stream.flatMap(Stream.succeed)\n      )\n      const result = yield* pipe(\n        Stream.toQueue(stream, { strategy: \"unbounded\" }),\n        Effect.flatMap((queue) =>\n          pipe(\n            Queue.size(queue),\n            Effect.repeat({ while: (size) => size !== chunk.length + 1 }),\n            Effect.zipRight(Queue.takeAll(queue))\n          )\n        ),\n        Effect.scoped\n      )\n      const expected = pipe(\n        chunk,\n        Chunk.map(Take.of),\n        Chunk.append(Take.end)\n      )\n      deepStrictEqual(Array.from(result), Array.from(expected))\n    }))\n\n  it.effect(\"toQueueOfElements - propagates defects\", () =>\n    Effect.gen(function*() {\n      const queue = yield* pipe(\n        Stream.dieMessage(\"die\"),\n        Stream.toQueueOfElements({ capacity: 1 }),\n        Effect.flatMap(Queue.take),\n        Effect.scoped\n      )\n      deepStrictEqual(queue, Exit.die(new Cause.RuntimeException(\"die\")))\n    }))\n\n  it(\"toAsyncIterable\", async () => {\n    const stream = Stream.make(1, 2, 3)\n    const results: Array<number> = []\n    for await (const result of Stream.toAsyncIterable(stream)) {\n      results.push(result)\n    }\n    deepStrictEqual(results, [1, 2, 3])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/distributing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { strictEqual } from \"@effect/vitest/utils\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { constTrue, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"distributedWithDynamic - ensures no race between subscription and stream end\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.distributedWithDynamic({\n          maximumLag: 1,\n          decide: () => Effect.succeed(constTrue)\n        }),\n        Effect.flatMap((add) => {\n          const subscribe = pipe(\n            add,\n            Effect.map(([_, queue]) =>\n              pipe(\n                Stream.fromQueue(queue),\n                Stream.filterMapWhile(Exit.match({\n                  onFailure: Option.none,\n                  onSuccess: Option.some\n                }))\n              )\n            ),\n            Stream.unwrap\n          )\n          return pipe(\n            Deferred.make<void>(),\n            Effect.flatMap((onEnd) =>\n              pipe(\n                subscribe,\n                Stream.ensuring(Deferred.succeed(onEnd, void 0)),\n                Stream.runDrain,\n                Effect.fork,\n                Effect.zipRight(Deferred.await(onEnd)),\n                Effect.zipRight(Stream.runDrain(subscribe))\n              )\n            )\n          )\n        }),\n        Effect.scoped\n      )\n      strictEqual(result, undefined)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/do-notation.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport * as Util from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { pipe } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\n\nconst expectRight = <R, L>(s: Stream.Stream<R, L>, expected: R) => {\n  Util.deepStrictEqual(Chunk.toArray(Effect.runSync(Stream.runCollect(Stream.either(s)))), [Either.right(expected)])\n}\n\nconst expectLeft = <R, L>(s: Stream.Stream<R, L>, expected: L) => {\n  Util.deepStrictEqual(Chunk.toArray(Effect.runSync(Stream.runCollect(Stream.either(s)))), [Either.left(expected)])\n}\n\ndescribe(\"do notation\", () => {\n  it(\"Do\", () => {\n    expectRight(Stream.Do, {})\n  })\n\n  it(\"bindTo\", () => {\n    expectRight(pipe(Stream.succeed(1), Stream.bindTo(\"a\")), { a: 1 })\n    expectLeft(pipe(Stream.fail(\"left\"), Stream.bindTo(\"a\")), \"left\")\n    expectRight(\n      pipe(\n        Stream.succeed(1),\n        Stream.bindTo(\"__proto__\"),\n        Stream.let(\"x\", () => 2)\n      ),\n      { x: 2, [\"__proto__\"]: 1 }\n    )\n  })\n\n  it(\"bind\", () => {\n    expectRight(pipe(Stream.succeed(1), Stream.bindTo(\"a\"), Stream.bind(\"b\", ({ a }) => Stream.succeed(a + 1))), {\n      a: 1,\n      b: 2\n    })\n    expectLeft(\n      pipe(Stream.succeed(1), Stream.bindTo(\"a\"), Stream.bind(\"b\", () => Stream.fail(\"left\"))),\n      \"left\"\n    )\n    expectLeft(\n      pipe(Stream.fail(\"left\"), Stream.bindTo(\"a\"), Stream.bind(\"b\", () => Stream.succeed(2))),\n      \"left\"\n    )\n    expectRight(\n      pipe(\n        Stream.succeed(1),\n        Stream.bindTo(\"a\"),\n        (x) =>\n          pipe(\n            x,\n            Stream.bind(\"__proto__\", ({ a }) => Stream.succeed(a + 1))\n          ) as Stream.Stream<{ a: number; __proto__: number }, unknown, never>,\n        Stream.bind(\"x\", () => Stream.succeed(2))\n      ),\n      { a: 1, x: 2, [\"__proto__\"]: 2 }\n    )\n  })\n\n  it(\"let\", () => {\n    expectRight(pipe(Stream.succeed(1), Stream.bindTo(\"a\"), Stream.let(\"b\", ({ a }) => a + 1)), { a: 1, b: 2 })\n    expectLeft(\n      pipe(Stream.fail(\"left\"), Stream.bindTo(\"a\"), Stream.let(\"b\", () => 2)),\n      \"left\"\n    )\n    expectRight(\n      pipe(\n        Stream.succeed(1),\n        Stream.bindTo(\"a\"),\n        Stream.let(\"__proto__\", ({ a }) => a + 1),\n        Stream.let(\"x\", ({ a }) => a + 2)\n      ),\n      { a: 1, x: 3, [\"__proto__\"]: 2 }\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/draining.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"drain - simple example\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      yield* pipe(\n        Stream.range(0, 9),\n        Stream.mapEffect((n) => Ref.update(ref, Chunk.append(n))),\n        Stream.drain,\n        Stream.runDrain\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), Array.from(Chunk.range(0, 9)))\n    }))\n\n  it.effect(\"drain - is not too eager\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const result1 = yield* pipe(\n        Stream.make(1),\n        Stream.tap((n) => Ref.set(ref, n)),\n        Stream.concat(Stream.fail(\"fail\")),\n        Stream.runDrain,\n        Effect.either\n      )\n      const result2 = yield* (Ref.get(ref))\n      assertLeft(result1, \"fail\")\n      strictEqual(result2, 1)\n    }))\n\n  it.effect(\"drainFork - runs the other stream in the background\", () =>\n    Effect.gen(function*() {\n      const latch = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        Stream.fromEffect(Deferred.await(latch)),\n        Stream.drainFork(Stream.fromEffect(Deferred.succeed(latch, void 0))),\n        Stream.runDrain\n      )\n      strictEqual(result, undefined)\n    }))\n\n  it.effect(\"drainFork - interrupts the background stream when the foreground exits\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.concat(Stream.drain(Stream.fromEffect(Deferred.await(latch)))),\n        Stream.drainFork(\n          pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.zipRight(Effect.never),\n            Effect.onInterrupt(() => Ref.set(ref, true)),\n            Stream.fromEffect\n          )\n        ),\n        Stream.runDrain\n      )\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"drainFork - fails the foreground stream if the background fails with a typed error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.never,\n        Stream.drainFork(Stream.fail(\"boom\")),\n        Stream.runDrain,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(\"boom\"))\n    }))\n\n  it.effect(\"drainFork - fails the foreground stream if the background fails with a defect\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.never,\n        Stream.drainFork(Stream.die(error)),\n        Stream.runDrain,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(error))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/dropping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertRight, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { constTrue, pipe } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"drop - simple example\", () =>\n    Effect.gen(function*() {\n      const n = 2\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.drop(n), Stream.runCollect),\n        result2: pipe(stream, Stream.runCollect, Effect.map(Chunk.drop(n)))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"drop - does not swallow errors\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fail(\"Ouch\"),\n        Stream.concat(Stream.make(1)),\n        Stream.drop(1),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"dropRight - simple example\", () =>\n    Effect.gen(function*() {\n      const n = 2\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.dropRight(n), Stream.runCollect),\n        result2: pipe(stream, Stream.runCollect, Effect.map(Chunk.dropRight(n)))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"dropRight - does not swallow errors\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.concat(Stream.fail(\"Ouch\")),\n        Stream.dropRight(1),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"dropUntil\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => n < 3\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.dropUntil(f), Stream.runCollect),\n        result2: pipe(\n          Stream.runCollect(stream),\n          Effect.map((chunk) => pipe(chunk, Chunk.dropWhile((n) => !f(n)), Chunk.drop(1)))\n        )\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"dropWhile\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => n < 3\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.dropWhile(f), Stream.runCollect),\n        result2: pipe(stream, Stream.runCollect, Effect.map(Chunk.dropWhile(f)))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"dropWhile - short circuits\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.concat(Stream.fail(\"Ouch\")),\n        Stream.take(1),\n        Stream.dropWhile(constTrue),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertRight(result, void 0)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/encoding.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"decodeText/encodeText round trip\", () =>\n    Effect.gen(function*() {\n      const items = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\"]\n      const encoded = yield* pipe(\n        Stream.fromIterable(items),\n        Stream.encodeText,\n        Stream.runCollect\n      )\n      strictEqual(encoded.length, 9)\n      const decoded = yield* pipe(\n        Stream.fromChunk(encoded),\n        Stream.decodeText(),\n        Stream.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(decoded), items)\n    }))\n\n  it.effect(\"decodeText handles multi-byte characters split across chunks\", () =>\n    Effect.gen(function*() {\n      // 🌍 is U+1F30D — four UTF-8 bytes: [0xF0, 0x9F, 0x8C, 0x8D]\n      const bytes = new TextEncoder().encode(\"🌍\")\n\n      // Split the bytes mid-character across two chunks\n      const stream = Stream.fromChunks(\n        Chunk.of(bytes.slice(0, 2)), // [0xF0, 0x9F]\n        Chunk.of(bytes.slice(2, 4)) // [0x8C, 0x8D]\n      )\n\n      const result = yield* pipe(\n        stream,\n        Stream.decodeText(),\n        Stream.mkString\n      )\n\n      strictEqual(result, \"🌍\")\n    }))\n\n  it.effect(\"decodeText handles mixed ASCII and multi-byte characters across chunks\", () =>\n    Effect.gen(function*() {\n      // \"Hello 🌍!\" encoded as UTF-8\n      const bytes = new TextEncoder().encode(\"Hello 🌍!\")\n\n      // Split in the middle of the emoji (after \"Hello \" + first 2 bytes of emoji)\n      const splitPoint = 6 + 2 // \"Hello \" is 6 bytes, then 2 of 4 emoji bytes\n      const stream = Stream.fromChunks(\n        Chunk.of(bytes.slice(0, splitPoint)),\n        Chunk.of(bytes.slice(splitPoint))\n      )\n\n      const result = yield* pipe(\n        stream,\n        Stream.decodeText(),\n        Stream.mkString\n      )\n\n      strictEqual(result, \"Hello 🌍!\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/environment.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Tracer from \"effect/Tracer\"\n\ninterface StringService {\n  readonly string: string\n}\n\nconst StringService = Context.GenericTag<StringService>(\"string\")\n\ndescribe(\"Stream\", () => {\n  it.effect(\"context\", () =>\n    Effect.gen(function*() {\n      const context = pipe(\n        Context.empty(),\n        Context.add(StringService, { string: \"test\" })\n      )\n      const result = yield* pipe(\n        Stream.context<StringService>(),\n        Stream.map(Context.get(StringService)),\n        Stream.provideContext(context),\n        Stream.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [{ string: \"test\" }])\n    }))\n\n  it.effect(\"contextWith\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        StringService,\n        Stream.provideContext(\n          pipe(\n            Context.empty(),\n            Context.add(StringService, { string: \"test\" })\n          )\n        ),\n        Stream.runHead,\n        Effect.flatten\n      )\n      deepStrictEqual(result, { string: \"test\" })\n    }))\n\n  it.effect(\"contextWithEffect - success\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.contextWithEffect((context: Context.Context<StringService>) =>\n          Effect.succeed(pipe(context, Context.get(StringService)))\n        ),\n        Stream.provideContext(\n          pipe(\n            Context.empty(),\n            Context.add(StringService, { string: \"test\" })\n          )\n        ),\n        Stream.runHead,\n        Effect.flatten\n      )\n      deepStrictEqual(result, { string: \"test\" })\n    }))\n\n  it.effect(\"contextWithEffect - fails\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.contextWithEffect((_: Context.Context<StringService>) => Effect.fail(\"boom\")),\n        Stream.provideContext(\n          pipe(\n            Context.empty(),\n            Context.add(StringService, { string: \"test\" })\n          )\n        ),\n        Stream.runHead,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(\"boom\"))\n    }))\n\n  it.effect(\"contextWithStream - success\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.contextWithStream((context: Context.Context<StringService>) =>\n          Stream.succeed(pipe(context, Context.get(StringService)))\n        ),\n        Stream.provideContext(\n          pipe(\n            Context.empty(),\n            Context.add(StringService, { string: \"test\" })\n          )\n        ),\n        Stream.runHead,\n        Effect.flatten\n      )\n      deepStrictEqual(result, { string: \"test\" })\n    }))\n\n  it.effect(\"contextWithStream - fails\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.contextWithStream((_: Context.Context<StringService>) => Stream.fail(\"boom\")),\n        Stream.provideContext(\n          pipe(\n            Context.empty(),\n            Context.add(StringService, { string: \"test\" })\n          )\n        ),\n        Stream.runHead,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(\"boom\"))\n    }))\n\n  it.effect(\"provide\", () =>\n    Effect.gen(function*() {\n      const stream = StringService\n      const layer = Layer.succeed(StringService, { string: \"test\" })\n      const result = yield* pipe(\n        stream,\n        Stream.provideLayer(layer),\n        Stream.map((s) => s.string),\n        Stream.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [\"test\"])\n    }))\n\n  it.effect(\"provideServiceStream\", () =>\n    Effect.gen(function*() {\n      const stream = StringService\n      const service = Stream.succeed<StringService>({ string: \"test\" })\n      const result = yield* pipe(\n        stream,\n        Stream.provideServiceStream(StringService, service),\n        Stream.map((s) => s.string),\n        Stream.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [\"test\"])\n    }))\n\n  it.effect(\"serviceWith\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.map(StringService, (service) => service.string),\n        Stream.provideLayer(Layer.succeed(StringService, { string: \"test\" })),\n        Stream.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [\"test\"])\n    }))\n\n  it.effect(\"serviceWithEffect\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.mapEffect(StringService, (service) => Effect.succeed(service.string)),\n        Stream.provideLayer(Layer.succeed(StringService, { string: \"test\" })),\n        Stream.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [\"test\"])\n    }))\n\n  it.effect(\"serviceWithStream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.flatMap(StringService, (service) => Stream.succeed(service.string)),\n        Stream.provideLayer(Layer.succeed(StringService, { string: \"test\" })),\n        Stream.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [\"test\"])\n    }))\n\n  it.effect(\"deep provide\", () =>\n    Effect.gen(function*() {\n      const messages: Array<string> = []\n      const effect = Effect.acquireRelease(\n        pipe(StringService, Effect.tap((s) => Effect.sync(() => messages.push(s.string)))),\n        () => pipe(StringService, Effect.tap((s) => Effect.sync(() => messages.push(s.string))))\n      )\n      const L0 = Layer.succeed(StringService, { string: \"test0\" })\n      const L1 = Layer.succeed(StringService, { string: \"test1\" })\n      const L2 = Layer.succeed(StringService, { string: \"test2\" })\n      const stream = pipe(\n        Stream.scoped(effect),\n        Stream.provideSomeLayer(L1),\n        Stream.concat(pipe(Stream.scoped(effect), Stream.provideSomeLayer(L2))),\n        Stream.provideSomeLayer(L0)\n      )\n      yield* (Stream.runDrain(stream))\n      deepStrictEqual(messages, [\"test1\", \"test1\", \"test2\", \"test2\"])\n    }))\n\n  it.effect(\"withSpan\", () =>\n    Effect.gen(function*() {\n      const spans = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.mapEffect((i) =>\n          Effect.withSpan(\n            Effect.currentSpan,\n            `span.${i}`\n          )\n        ),\n        Stream.withSpan(\"span\"),\n        Stream.runCollect,\n        Effect.map(Chunk.toReadonlyArray)\n      )\n      strictEqual(spans.length, 3)\n      deepStrictEqual(\n        pipe(\n          Array.map(spans, (s) => s.parent),\n          Array.getSomes,\n          Array.filter((s): s is Tracer.Span => s._tag === \"Span\"),\n          Array.map((s) => s.name)\n        ),\n        [\"span\", \"span\", \"span\"]\n      )\n      deepStrictEqual(Array.map(spans, (s) => s.name), [\"span.1\", \"span.2\", \"span.3\"])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/error-handling.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"absolve - happy path\", () =>\n    Effect.gen(function*() {\n      const chunk = Chunk.range(1, 10)\n      const result = yield* pipe(\n        chunk,\n        Chunk.map(Either.right),\n        Stream.fromIterable,\n        Stream.mapEffect(identity),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(chunk))\n    }))\n\n  it.effect(\"absolve - failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromIterable(pipe(Chunk.range(1, 10), Chunk.map(Either.right))),\n        Stream.concat(Stream.succeed(Either.left(\"Ouch\"))),\n        Stream.mapEffect(identity),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(\"Ouch\"))\n    }))\n\n  it.effect(\"absolve - round trip #1\", () =>\n    Effect.gen(function*() {\n      const xss = Stream.fromIterable(pipe(Chunk.range(1, 10), Chunk.map(Either.right)))\n      const stream = pipe(xss, Stream.concat(Stream.succeed(Either.left(\"Ouch\"))), Stream.concat(xss))\n      const { result1, result2 } = yield* (Effect.all({\n        result1: Stream.runCollect(stream),\n        result2: pipe(Stream.mapEffect(stream, identity), Stream.either, Stream.runCollect)\n      }))\n      deepStrictEqual(\n        Array.from(pipe(result1, Chunk.take(result2.length))),\n        Array.from(result2)\n      )\n    }))\n\n  it.effect(\"absolve - round trip #2\", () =>\n    Effect.gen(function*() {\n      const xss = Stream.fromIterable(pipe(Chunk.range(1, 10), Chunk.map(Either.right)))\n      const stream = pipe(xss, Stream.concat(Stream.fail(\"Ouch\")))\n      const { result1, result2 } = yield* (Effect.all({\n        result1: Effect.exit(Stream.runCollect(stream)),\n        result2: pipe(stream, Stream.either, Stream.mapEffect(identity), Stream.runCollect, Effect.exit)\n      }))\n      deepStrictEqual(result1, Exit.fail(\"Ouch\"))\n      deepStrictEqual(result2, Exit.fail(\"Ouch\"))\n    }))\n\n  it.effect(\"catchAllCause - recovery from errors\", () =>\n    Effect.gen(function*() {\n      const stream1 = pipe(Stream.make(1, 2), Stream.concat(Stream.fail(\"boom\")))\n      const stream2 = Stream.make(3, 4)\n      const result = yield* pipe(\n        stream1,\n        Stream.catchAllCause(() => stream2),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"catchAllCause - recovery from defects\", () =>\n    Effect.gen(function*() {\n      const stream1 = pipe(Stream.make(1, 2), Stream.concat(Stream.dieMessage(\"boom\")))\n      const stream2 = Stream.make(3, 4)\n      const result = yield* pipe(\n        stream1,\n        Stream.catchAllCause(() => stream2),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"catchAllCause - happy path\", () =>\n    Effect.gen(function*() {\n      const stream1 = Stream.make(1, 2)\n      const stream2 = Stream.make(3, 4)\n      const result = yield* pipe(\n        stream1,\n        Stream.catchAllCause(() => stream2),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2])\n    }))\n\n  it.effect(\"catchAllCause - executes finalizers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<string>()))\n      const stream1 = pipe(\n        Stream.make(1, 2),\n        Stream.concat(Stream.fail(\"boom\")),\n        Stream.ensuring(Ref.update(ref, Chunk.append(\"s1\")))\n      )\n      const stream2 = pipe(\n        Stream.make(1, 2),\n        Stream.concat(Stream.fail(\"boom\")),\n        Stream.ensuring(Ref.update(ref, Chunk.append(\"s2\")))\n      )\n      yield* pipe(\n        stream1,\n        Stream.catchAllCause(() => stream2),\n        Stream.runCollect,\n        Effect.exit\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [\"s1\", \"s2\"])\n    }))\n\n  it.effect(\"catchAllCause - releases all resources by the time the failover stream has started\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const stream = pipe(\n        Stream.finalizer(Ref.update(ref, Chunk.append(1))),\n        Stream.crossRight(Stream.finalizer(Ref.update(ref, Chunk.append(2)))),\n        Stream.crossRight(Stream.finalizer(Ref.update(ref, Chunk.append(3)))),\n        Stream.crossRight(Stream.fail(\"boom\"))\n      )\n      const result = yield* pipe(\n        Stream.drain(stream),\n        Stream.catchAllCause(() => Stream.fromEffect(Ref.get(ref))),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(Chunk.flatten(result)), [3, 2, 1])\n    }))\n\n  it.effect(\"catchAllCause - propagates the right Exit value to the failing stream (ZIO #3609)\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make<Exit.Exit<unknown, unknown>>(Exit.void))\n      yield* pipe(\n        Stream.acquireRelease(\n          Effect.void,\n          (_, exit) => Ref.set(ref, exit)\n        ),\n        Stream.flatMap(() => Stream.fail(\"boom\")),\n        Stream.either,\n        Stream.runDrain,\n        Effect.exit\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(result, Exit.fail(\"boom\"))\n    }))\n\n  it.effect(\"catchSome - recovery from some errors\", () =>\n    Effect.gen(function*() {\n      const stream1 = pipe(\n        Stream.make(1, 2),\n        Stream.concat(Stream.fail(\"boom\"))\n      )\n      const stream2 = Stream.make(3, 4)\n      const result = yield* pipe(\n        stream1,\n        Stream.catchSome((error) => error === \"boom\" ? Option.some(stream2) : Option.none()),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"catchSome - fails stream when partial function does not match\", () =>\n    Effect.gen(function*() {\n      const stream1 = pipe(\n        Stream.make(1, 2),\n        Stream.concat(Stream.fail(\"boom\"))\n      )\n      const stream2 = Stream.make(3, 4)\n      const result = yield* pipe(\n        stream1,\n        Stream.catchSome((error) => error === \"boomer\" ? Option.some(stream2) : Option.none()),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"boom\")\n    }))\n\n  it.effect(\"catchSomeCause - recovery from some errors\", () =>\n    Effect.gen(function*() {\n      const stream1 = pipe(\n        Stream.make(1, 2),\n        Stream.concat(Stream.failCause(Cause.fail(\"boom\")))\n      )\n      const stream2 = Stream.make(3, 4)\n      const result = yield* pipe(\n        stream1,\n        Stream.catchSomeCause((cause) =>\n          Cause.isFailType(cause) && cause.error === \"boom\" ?\n            Option.some(stream2) :\n            Option.none()\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"catchSomeCause - fails stream when partial function does not match\", () =>\n    Effect.gen(function*() {\n      const stream1 = pipe(\n        Stream.make(1, 2),\n        Stream.concat(Stream.fail(\"boom\"))\n      )\n      const stream2 = Stream.make(3, 4)\n      const result = yield* pipe(\n        stream1,\n        Stream.catchSomeCause((cause) =>\n          Cause.isEmpty(cause) ?\n            Option.some(stream2) :\n            Option.none()\n        ),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"boom\")\n    }))\n\n  it.effect(\"catchTag\", () =>\n    Effect.gen(function*() {\n      class ErrorA {\n        readonly _tag = \"ErrorA\"\n      }\n      class ErrorB {\n        readonly _tag = \"ErrorB\"\n      }\n\n      const result1 = yield* pipe(\n        Stream.fail(new ErrorA()),\n        Stream.catchTag(\"ErrorA\", () => Stream.make(1, 2)),\n        Stream.runCollect\n      )\n\n      const result2 = yield* pipe(\n        Stream.fail(new ErrorA()),\n        Stream.flatMap(() => Stream.fail(new ErrorB())),\n        Stream.catchTag(\"ErrorB\", () => Stream.make(1, 2)),\n        Stream.runCollect,\n        Effect.either\n      )\n\n      deepStrictEqual(Chunk.toReadonlyArray(result1), [1, 2])\n      assertTrue(Either.isLeft(result2) && result2.left._tag === \"ErrorA\")\n    }))\n\n  it.effect(\"onError\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const exit = yield* pipe(\n        Stream.fail(\"boom\"),\n        Stream.onError(() => Ref.set(ref, true)),\n        Stream.runDrain,\n        Effect.exit\n      )\n      const called = yield* (Ref.get(ref))\n      deepStrictEqual(exit, Exit.fail(\"boom\"))\n      assertTrue(called)\n    }))\n\n  it.effect(\"orElse\", () =>\n    Effect.gen(function*() {\n      const stream1 = pipe(\n        Stream.make(1, 2, 3),\n        Stream.concat(Stream.fail(\"boom\"))\n      )\n      const stream2 = Stream.make(4, 5, 6)\n      const result = yield* pipe(\n        stream1,\n        Stream.orElse(() => stream2),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4, 5, 6])\n    }))\n\n  it.effect(\"orElseEither\", () =>\n    Effect.gen(function*() {\n      const stream1 = pipe(\n        Stream.make(1),\n        Stream.concat(Stream.fail(\"boom\"))\n      )\n      const stream2 = Stream.make(2)\n      const result = yield* pipe(\n        stream1,\n        Stream.orElseEither(() => stream2),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [Either.left(1), Either.right(2)])\n    }))\n\n  it.effect(\"orElseFail\", () =>\n    Effect.gen(function*() {\n      const stream = pipe(Stream.succeed(1), Stream.concat(Stream.fail(\"boom\")))\n      const result = yield* pipe(\n        stream,\n        Stream.orElseFail(() => \"boomer\"),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"boomer\")\n    }))\n\n  it.effect(\"orElseIfEmpty - produce default value if stream is empty\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.orElseIfEmpty(() => 0),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0])\n    }))\n\n  it.effect(\"orElseIfEmpty - ignores default value when stream is not empty\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.orElseIfEmpty(() => 0),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1])\n    }))\n\n  it.effect(\"orElseIfEmptyStream - consume default stream if stream is empty\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.orElseIfEmptyStream(() => Stream.range(0, 4)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0, 1, 2, 3, 4])\n    }))\n\n  it.effect(\"orElseIfEmptyStream - should throw the correct error from the default stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.orElseIfEmptyStream(() => Stream.fail(\"Ouch\")),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"orElseSucceed\", () =>\n    Effect.gen(function*() {\n      const stream = pipe(Stream.succeed(1), Stream.concat(Stream.fail(\"boom\")))\n      const result = yield* pipe(\n        stream,\n        Stream.orElseSucceed(() => 2),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/filtering.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { pipe } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"filter\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => n % 2 === 0\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.filter(f), Stream.runCollect),\n        result2: pipe(stream, Stream.runCollect, Effect.map(Chunk.filter(f)))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"filterEffect - simple example\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => Effect.succeed(n % 2 === 0)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.filterEffect(f), Stream.runCollect),\n        result2: pipe(stream, Stream.runCollect, Effect.flatMap(Effect.filter(f)))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"filterEffect - laziness on chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.filterEffect((n) =>\n          n === 3 ?\n            Effect.fail(\"boom\") :\n            Effect.succeed(true)\n        ),\n        Stream.either,\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result),\n        [Either.right(1), Either.right(2), Either.left(\"boom\")]\n      )\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/finding.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"find\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => n === 4\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.find(f), Stream.runCollect),\n        result2: pipe(\n          stream,\n          Stream.runCollect,\n          Effect.map(Chunk.findFirst(f)),\n          Effect.map(Option.match({\n            onNone: () => Chunk.empty<number>(),\n            onSome: Chunk.of\n          }))\n        )\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"findEffect - simple example\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => Effect.succeed(n === 4)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.findEffect(f), Stream.runCollect),\n        result2: pipe(\n          Stream.runCollect(stream),\n          Effect.flatMap((chunk) =>\n            pipe(\n              Effect.findFirst(chunk, f),\n              Effect.map(Option.match({\n                onNone: () => Chunk.empty<number>(),\n                onSome: Chunk.of\n              }))\n            )\n          )\n        )\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"findEffect - throws correct error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.findEffect((n) =>\n          n === 3 ?\n            Effect.fail(\"boom\") :\n            Effect.succeed(false)\n        ),\n        Stream.either,\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result),\n        [Either.left(\"boom\")]\n      )\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/foreign.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertRight, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Random from \"effect/Random\"\nimport * as Stream from \"effect/Stream\"\nimport { unify } from \"effect/Unify\"\n\ndescribe(\"Stream.Foreign\", () => {\n  it.effect(\"Tag\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<number>(\"number\")\n      const result = yield* pipe(\n        tag,\n        Stream.runCollect,\n        Effect.map(Chunk.toReadonlyArray),\n        Effect.provideService(tag, 10)\n      )\n      deepStrictEqual(result, [10])\n    }))\n\n  it.effect(\"Unify\", () =>\n    Effect.gen(function*() {\n      const unifiedEffect = unify((yield* (Random.nextInt)) > 1 ? Effect.succeed(0) : Effect.fail(1))\n      const unifiedExit = unify((yield* (Random.nextInt)) > 1 ? Exit.succeed(0) : Exit.fail(1))\n      const unifiedEither = unify((yield* (Random.nextInt)) > 1 ? Either.right(0) : Either.left(1))\n      const unifiedOption = unify((yield* (Random.nextInt)) > 1 ? Option.some(0) : Option.none())\n      deepStrictEqual(Chunk.toReadonlyArray(yield* (Stream.runCollect(unifiedEffect))), [0])\n      deepStrictEqual(Chunk.toReadonlyArray(yield* (Stream.runCollect(unifiedExit))), [0])\n      deepStrictEqual(Chunk.toReadonlyArray(yield* (Stream.runCollect(unifiedEither))), [0])\n      deepStrictEqual(Chunk.toReadonlyArray(yield* (Stream.runCollect(unifiedOption))), [0])\n    }))\n\n  it.effect(\"Either.right\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<number>(\"number\")\n\n      const result = yield* pipe(\n        Either.right(10),\n        Stream.runCollect,\n        Effect.map(Chunk.toReadonlyArray),\n        Effect.provideService(tag, 10)\n      )\n      deepStrictEqual(result, [10])\n    }))\n\n  it.effect(\"Either.left\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<number>(\"number\")\n      const result = yield* pipe(\n        Either.left(10),\n        Stream.runCollect,\n        Effect.either,\n        Effect.provideService(tag, 10)\n      )\n      assertLeft(result, 10)\n    }))\n\n  it.effect(\"Option.some\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<number>(\"number\")\n      const result = yield* pipe(\n        Option.some(10),\n        Stream.runCollect,\n        Effect.map(Chunk.toReadonlyArray),\n        Effect.provideService(tag, 10)\n      )\n      deepStrictEqual(result, [10])\n    }))\n\n  it.effect(\"Option.none\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<number>(\"number\")\n      const result = yield* pipe(\n        Option.none(),\n        Stream.runCollect,\n        Effect.either,\n        Effect.provideService(tag, 10)\n      )\n      assertLeft(result, new Cause.NoSuchElementException())\n    }))\n\n  it.effect(\"Effect.fail\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<number>(\"number\")\n      const result = yield* pipe(\n        Effect.fail(\"ok\"),\n        Stream.runCollect,\n        Effect.either,\n        Effect.provideService(tag, 10)\n      )\n      assertLeft(result, \"ok\")\n    }))\n\n  it.effect(\"Effect.succeed\", () =>\n    Effect.gen(function*() {\n      const tag = Context.GenericTag<number>(\"number\")\n      const result = yield* pipe(\n        Effect.succeed(\"ok\"),\n        Stream.runCollect,\n        Effect.map(Chunk.toReadonlyArray),\n        Effect.either,\n        Effect.provideService(tag, 10)\n      )\n      assertRight(result, [\"ok\"])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/fromEventListener.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { Effect, pipe, Stream } from \"effect\"\n\nclass TestTarget extends EventTarget {\n  emit() {\n    this.dispatchEvent(new Event(\"test-event\"))\n  }\n}\n\ndescribe(\"Stream.fromEventListener\", () => {\n  it.effect(\"emitted count\", (ctx) =>\n    Effect.gen(function*() {\n      const target = new TestTarget()\n\n      const count = yield* pipe(\n        Stream.fromEventListener(target, \"test-event\"),\n        Stream.interruptWhen(Effect.sync(() => target.emit()).pipe(Effect.repeatN(2))),\n        Stream.runCount\n      )\n      ctx.expect(count).toEqual(3)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/getters.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"some\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.succeed(Option.some(1)),\n        Stream.concat(Stream.succeed(Option.none())),\n        Stream.some,\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, Option.none())\n    }))\n\n  it.effect(\"some\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.succeed(Option.some(1)),\n        Stream.concat(Stream.succeed(Option.none())),\n        Stream.someOrElse(() => -1),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, -1])\n    }))\n\n  it.effect(\"someOrFail\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.succeed(Option.some(1)),\n        Stream.concat(Stream.succeed(Option.none())),\n        Stream.someOrFail(() => -1),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, -1)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/grouping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as GroupBy from \"effect/GroupBy\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\nimport * as Handoff from \"../../src/internal/stream/handoff.js\"\nimport { chunkCoordination } from \"../utils/coordination.js\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"groupBy - values\", () =>\n    Effect.gen(function*() {\n      const words = pipe(\n        Chunk.makeBy(() => Chunk.range(0, 99))(100),\n        Chunk.flatten,\n        Chunk.map((n) => String(n))\n      )\n      const result = yield* pipe(\n        Stream.fromIterable(words),\n        Stream.groupByKey(identity, { bufferSize: 8192 }),\n        GroupBy.evaluate((key, stream) =>\n          pipe(\n            Stream.runCollect(stream),\n            Effect.map((leftover) => [key, leftover.length] as const),\n            Stream.fromEffect\n          )\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result),\n        Array.from({ length: 100 }, (_, i) => i).map((n) => [String(n), 100] as const)\n      )\n    }))\n\n  it.effect(\"groupBy - first\", () =>\n    Effect.gen(function*() {\n      const words = pipe(\n        Chunk.makeBy(() => Chunk.range(0, 99))(1_000),\n        Chunk.flatten,\n        Chunk.map((n) => String(n))\n      )\n      const result = yield* pipe(\n        Stream.fromIterable(words),\n        Stream.groupByKey(identity, { bufferSize: 1050 }),\n        GroupBy.first(2),\n        GroupBy.evaluate((key, stream) =>\n          pipe(\n            Stream.runCollect(stream),\n            Effect.map((leftover) => [key, leftover.length] as const),\n            Stream.fromEffect\n          )\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [[\"0\", 1_000], [\"1\", 1_000]])\n    }))\n\n  it.effect(\"groupBy - filter\", () =>\n    Effect.gen(function*() {\n      const words = Array.from({ length: 100 }, () => Array.from({ length: 100 }, (_, i) => i)).flat()\n      const result = yield* pipe(\n        Stream.fromIterable(words),\n        Stream.groupByKey(identity, { bufferSize: 1050 }),\n        GroupBy.filter((n) => n <= 5),\n        GroupBy.evaluate((key, stream) =>\n          pipe(\n            Stream.runCollect(stream),\n            Effect.map((leftover) => [key, leftover.length] as const),\n            Stream.fromEffect\n          )\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\n        [0, 100],\n        [1, 100],\n        [2, 100],\n        [3, 100],\n        [4, 100],\n        [5, 100]\n      ])\n    }))\n\n  it.effect(\"groupBy - outer errors\", () =>\n    Effect.gen(function*() {\n      const words = [\"abc\", \"test\", \"test\", \"foo\"]\n      const result = yield* pipe(\n        Stream.fromIterable(words),\n        Stream.concat(Stream.fail(\"boom\")),\n        Stream.groupByKey(identity),\n        GroupBy.evaluate((_, stream) => Stream.drain(stream)),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"boom\")\n    }))\n\n  it.effect(\"grouped - sanity check\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4, 5),\n        Stream.grouped(2),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2], [3, 4], [5]]\n      )\n    }))\n\n  it.effect(\"grouped - group size is correct\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(0, 99),\n        Stream.grouped(10),\n        Stream.map(Chunk.size),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result),\n        Array.from({ length: 10 }, () => 10)\n      )\n    }))\n\n  it.effect(\"grouped - does not emit empty chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromIterable(Chunk.empty<number>()),\n        Stream.grouped(5),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"grouped - emits elements properly when a failure occurs\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<Array<number>>()))\n      const streamChunks = Stream.fromChunks(Chunk.range(1, 4), Chunk.range(5, 7), Chunk.of(8))\n      const stream = pipe(\n        streamChunks,\n        Stream.concat(Stream.fail(\"Ouch\")),\n        Stream.grouped(3)\n      )\n      const either = yield* pipe(\n        stream,\n        Stream.mapEffect((chunk) => Ref.update(ref, Chunk.append(Array.from(chunk)))),\n        Stream.runCollect,\n        Effect.either\n      )\n      const result = yield* (Ref.get(ref))\n      assertLeft(either, \"Ouch\")\n      deepStrictEqual(Array.from(result), [[1, 2, 3], [4, 5, 6], [7, 8]])\n    }))\n\n  it.effect(\"groupedWithin - group based on time passed\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* (chunkCoordination([\n        Chunk.make(1, 2),\n        Chunk.make(3, 4),\n        Chunk.of(5)\n      ]))\n      const stream = pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.filterMapWhile(Exit.match({\n          onSuccess: Option.some,\n          onFailure: Option.none\n        })),\n        Stream.flattenChunks,\n        Stream.groupedWithin(10, Duration.seconds(2)),\n        Stream.tap(() => coordination.proceed)\n      )\n      const fiber = yield* (Effect.fork(Stream.runCollect(stream)))\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(2))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(2))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* (coordination.offer)\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2], [3, 4], [5]]\n      )\n    }))\n\n  it.effect(\"groupedWithin - group based on time passed (ZIO Issue #5013)\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* pipe(\n        Chunk.range(1, 29),\n        Chunk.map(Chunk.of),\n        chunkCoordination\n      )\n      const latch = yield* (Handoff.make<void>())\n      const ref = yield* (Ref.make(0))\n      const fiber = yield* pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.filterMapWhile(Exit.match({\n          onSuccess: Option.some,\n          onFailure: Option.none\n        })),\n        Stream.flattenChunks,\n        Stream.tap(() => coordination.proceed),\n        Stream.groupedWithin(10, Duration.seconds(3)),\n        Stream.tap((chunk) =>\n          pipe(\n            Ref.update(ref, (n) => n + chunk.length),\n            Effect.zipRight(pipe(latch, Handoff.offer<void>(void 0)))\n          )\n        ),\n        Stream.run(Sink.take(5)),\n        Effect.fork\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      const result1 = yield* pipe(\n        Handoff.take(latch),\n        Effect.zipRight(Ref.get(ref))\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      const result2 = yield* pipe(\n        Handoff.take(latch),\n        Effect.zipRight(Ref.get(ref))\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      const result3 = yield* pipe(\n        Handoff.take(latch),\n        Effect.zipRight(Ref.get(ref))\n      )\n      // This part is to make sure schedule clock is being restarted when the\n      // specified amount of elements has been reached.\n      yield* pipe(\n        TestClock.adjust(Duration.seconds(2)),\n        Effect.zipRight(\n          pipe(\n            coordination.offer,\n            Effect.zipRight(coordination.awaitNext),\n            Effect.repeatN(9)\n          )\n        )\n      )\n      const result4 = yield* pipe(\n        Handoff.take(latch),\n        Effect.zipRight(Ref.get(ref))\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(coordination.awaitNext),\n        Effect.zipRight(TestClock.adjust(Duration.seconds(2))),\n        Effect.zipRight(\n          pipe(\n            coordination.offer,\n            Effect.zipRight(coordination.awaitNext),\n            Effect.repeatN(8)\n          )\n        )\n      )\n      const result5 = yield* pipe(\n        Handoff.take(latch),\n        Effect.zipRight(Ref.get(ref))\n      )\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [\n          [1, 2, 3],\n          [4, 5, 6],\n          [7, 8, 9],\n          [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n          [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]\n        ]\n      )\n      strictEqual(result1, 3)\n      strictEqual(result2, 6)\n      strictEqual(result3, 9)\n      strictEqual(result4, 19)\n      strictEqual(result5, 29)\n    }))\n\n  it.effect(\"groupedWithin - group immediately when chunk size is reached\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4),\n        Stream.groupedWithin(2, Duration.seconds(10)),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2], [3, 4]]\n      )\n    }))\n\n  it.effect(\"groupAdjacentBy - one big chunk\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromIterable([\n          { code: 1, message: \"A\" },\n          { code: 1, message: \"B\" },\n          { code: 1, message: \"D\" },\n          { code: 2, message: \"C\" }\n        ]),\n        Stream.groupAdjacentBy((x) => x.code),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map(([, chunk]) => Array.from(chunk)),\n        [\n          [\n            { code: 1, message: \"A\" },\n            { code: 1, message: \"B\" },\n            { code: 1, message: \"D\" }\n          ],\n          [\n            { code: 2, message: \"C\" }\n          ]\n        ]\n      )\n    }))\n\n  it.effect(\"groupAdjacentBy - several single element chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(\n          Chunk.make({ code: 1, message: \"A\" }),\n          Chunk.make({ code: 1, message: \"B\" }),\n          Chunk.make({ code: 1, message: \"D\" }),\n          Chunk.make({ code: 2, message: \"C\" })\n        ),\n        Stream.groupAdjacentBy((x) => x.code),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map(([, chunk]) => Array.from(chunk)),\n        [\n          [\n            { code: 1, message: \"A\" },\n            { code: 1, message: \"B\" },\n            { code: 1, message: \"D\" }\n          ],\n          [\n            { code: 2, message: \"C\" }\n          ]\n        ]\n      )\n    }))\n\n  it.effect(\"groupAdjacentBy - group across chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(\n          Chunk.make({ code: 1, message: \"A\" }, { code: 1, message: \"B\" }),\n          Chunk.make({ code: 1, message: \"D\" }, { code: 2, message: \"C\" })\n        ),\n        Stream.groupAdjacentBy((x) => x.code),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map(([, chunk]) => Array.from(chunk)),\n        [\n          [\n            { code: 1, message: \"A\" },\n            { code: 1, message: \"B\" },\n            { code: 1, message: \"D\" }\n          ],\n          [\n            { code: 2, message: \"C\" }\n          ]\n        ]\n      )\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/halting.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertLeft, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Queue from \"effect/Queue\"\nimport * as Ref from \"effect/Ref\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\nimport { chunkCoordination } from \"../utils/coordination.js\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"haltWhen - halts after the current element\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const halt = yield* (Deferred.make<void>())\n      yield* pipe(\n        Deferred.await(latch),\n        Effect.onInterrupt(() => Ref.set(ref, true)),\n        Stream.fromEffect,\n        Stream.haltWhen(Deferred.await(halt)),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (Deferred.succeed(halt, void 0))\n      yield* (Deferred.succeed(latch, void 0))\n      const result = yield* (Ref.get(ref))\n      assertFalse(result)\n    }))\n\n  it.effect(\"haltWhen - propagates errors\", () =>\n    Effect.gen(function*() {\n      const halt = yield* (Deferred.make<void, string>())\n      yield* (Deferred.fail(halt, \"fail\"))\n      const result = yield* pipe(\n        Stream.make(0),\n        Stream.forever,\n        Stream.haltWhen(Deferred.await(halt)),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertLeft(result, \"fail\")\n    }))\n\n  it.effect(\"haltWhenDeferred - halts after the current element\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const halt = yield* (Deferred.make<void>())\n      yield* pipe(\n        Deferred.await(latch),\n        Effect.onInterrupt(() => Ref.set(ref, true)),\n        Stream.fromEffect,\n        Stream.haltWhenDeferred(halt),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (Deferred.succeed(halt, void 0))\n      yield* (Deferred.succeed(latch, void 0))\n      const result = yield* (Ref.get(ref))\n      assertFalse(result)\n    }))\n\n  it.effect(\"haltWhenDeferred - propagates errors\", () =>\n    Effect.gen(function*() {\n      const halt = yield* (Deferred.make<void, string>())\n      yield* (Deferred.fail(halt, \"fail\"))\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.haltWhenDeferred(halt),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertLeft(result, \"fail\")\n    }))\n\n  it.effect(\"haltAfter - halts after the given duration\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* (chunkCoordination([\n        Chunk.of(1),\n        Chunk.of(2),\n        Chunk.of(3),\n        Chunk.of(4)\n      ]))\n      const fiber = yield* pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.filterMapWhile(Exit.match({\n          onFailure: Option.none,\n          onSuccess: Option.some\n        })),\n        Stream.haltAfter(Duration.seconds(5)),\n        Stream.tap(() => coordination.proceed),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(3))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(3))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(3))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* (coordination.offer)\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1], [2], [3]]\n      )\n    }))\n\n  it.effect(\"haltAfter - will process first chunk\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (Queue.unbounded<number>())\n      const fiber = yield* pipe(\n        Stream.fromQueue(queue),\n        Stream.haltAfter(Duration.seconds(5)),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.seconds(6)))\n      yield* (Queue.offer(queue, 1))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), [1])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/interleaving.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"interleave\", () =>\n    Effect.gen(function*() {\n      const stream1 = Stream.make(2, 3)\n      const stream2 = Stream.make(5, 6, 7)\n      const result = yield* pipe(\n        stream1,\n        Stream.interleave(stream2),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [2, 5, 3, 6, 7])\n    }))\n\n  it.effect(\"interleaveWith\", () =>\n    Effect.gen(function*() {\n      const interleave = (\n        bools: Chunk.Chunk<boolean>,\n        numbers1: Chunk.Chunk<number>,\n        numbers2: Chunk.Chunk<number>\n      ): Chunk.Chunk<number> =>\n        pipe(\n          Chunk.head(bools),\n          Option.map((head) => {\n            if (head) {\n              if (Chunk.isNonEmpty(numbers1)) {\n                const head = pipe(numbers1, Chunk.unsafeGet(0))\n                const tail = pipe(numbers1, Chunk.drop(1))\n                return pipe(\n                  interleave(pipe(bools, Chunk.drop(1)), tail, numbers2),\n                  Chunk.prepend(head)\n                )\n              }\n              if (Chunk.isNonEmpty(numbers2)) {\n                return interleave(pipe(bools, Chunk.drop(1)), Chunk.empty<number>(), numbers2)\n              }\n              return Chunk.empty<number>()\n            }\n            if (Chunk.isNonEmpty(numbers2)) {\n              const head = pipe(numbers2, Chunk.unsafeGet(0))\n              const tail = pipe(numbers2, Chunk.drop(1))\n              return pipe(\n                interleave(pipe(bools, Chunk.drop(1)), numbers1, tail),\n                Chunk.prepend(head)\n              )\n            }\n            if (Chunk.isNonEmpty(numbers1)) {\n              return interleave(pipe(bools, Chunk.drop(1)), numbers1, Chunk.empty<number>())\n            }\n            return Chunk.empty<number>()\n          }),\n          Option.getOrElse(() => Chunk.empty<number>())\n        )\n      const boolStream = Stream.make(true, true, false, true, false)\n      const stream1 = Stream.make(1, 2, 3, 4, 5)\n      const stream2 = Stream.make(4, 5, 6, 7, 8)\n      const interleavedStream = yield* pipe(\n        stream1,\n        Stream.interleaveWith(stream2, boolStream),\n        Stream.runCollect\n      )\n      const bools = yield* (Stream.runCollect(boolStream))\n      const numbers1 = yield* (Stream.runCollect(stream1))\n      const numbers2 = yield* (Stream.runCollect(stream2))\n      const interleavedChunks = interleave(bools, numbers1, numbers2)\n      deepStrictEqual(Array.from(interleavedStream), Array.from(interleavedChunks))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/interrupting.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Schedule } from \"effect\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Queue from \"effect/Queue\"\nimport * as Ref from \"effect/Ref\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\nimport { chunkCoordination } from \"../utils/coordination.js\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"interruptWhen - preserves the scope of inner fibers\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* (Deferred.make<void>())\n      const queue1 = yield* (Queue.unbounded<Chunk.Chunk<number>>())\n      const queue2 = yield* (Queue.unbounded<Chunk.Chunk<number>>())\n      yield* (Queue.offer(queue1, Chunk.of(1)))\n      yield* (Queue.offer(queue2, Chunk.of(2)))\n      yield* pipe(Queue.offer(queue1, Chunk.of(3)), Effect.fork)\n      yield* pipe(Queue.offer(queue2, Chunk.of(4)), Effect.fork)\n      const stream1 = Stream.fromChunkQueue(queue1)\n      const stream2 = Stream.fromChunkQueue(queue2)\n      const stream = pipe(\n        stream1,\n        Stream.zipLatest(stream2),\n        Stream.interruptWhen(Deferred.await(deferred)),\n        Stream.take(3)\n      )\n      const result = yield* (Stream.runDrain(stream))\n      strictEqual(result, undefined)\n    }))\n\n  it.effect(\"interruptWhen - interrupts the current element\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const halt = yield* (Deferred.make<void>())\n      const started = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Stream.fromEffect(pipe(\n          Deferred.succeed(started, void 0),\n          Effect.zipRight(Deferred.await(latch)),\n          Effect.onInterrupt(() => Ref.set(ref, true))\n        )),\n        Stream.interruptWhen(Deferred.await(halt)),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* pipe(\n        Deferred.await(started),\n        Effect.zipRight(Deferred.succeed(halt, void 0))\n      )\n      yield* (Fiber.await(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"interruptWhen - propagates errors\", () =>\n    Effect.gen(function*() {\n      const halt = yield* (Deferred.make<never, string>())\n      yield* (Deferred.fail(halt, \"fail\"))\n      const result = yield* pipe(\n        Stream.never,\n        Stream.interruptWhen(Deferred.await(halt)),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertLeft(result, \"fail\")\n    }))\n\n  it.effect(\"interruptWhenDeferred - interrupts the current element\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const halt = yield* (Deferred.make<void>())\n      const started = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Stream.fromEffect(pipe(\n          Deferred.succeed(started, void 0),\n          Effect.zipRight(Deferred.await(latch)),\n          Effect.onInterrupt(() => Ref.set(ref, true))\n        )),\n        Stream.interruptWhenDeferred(halt),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* pipe(\n        Deferred.await(started),\n        Effect.zipRight(Deferred.succeed(halt, void 0))\n      )\n      yield* (Fiber.await(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"interruptWhenDeferred - propagates errors\", () =>\n    Effect.gen(function*() {\n      const halt = yield* (Deferred.make<never, string>())\n      yield* (Deferred.fail(halt, \"fail\"))\n      const result = yield* pipe(\n        Stream.never,\n        Stream.interruptWhenDeferred(halt),\n        Stream.runDrain,\n        Effect.either\n      )\n      assertLeft(result, \"fail\")\n    }))\n\n  it.effect(\"interruptAfter - halts after the given duration\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* (chunkCoordination([\n        Chunk.of(1),\n        Chunk.of(2),\n        Chunk.of(3),\n        Chunk.of(4)\n      ]))\n      const fiber = yield* pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.filterMapWhile(Exit.match({\n          onFailure: Option.none,\n          onSuccess: Option.some\n        })),\n        Stream.interruptAfter(Duration.seconds(5)),\n        Stream.tap(() => coordination.proceed),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(3))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(3))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* (coordination.offer)\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1], [2]]\n      )\n    }))\n\n  it.effect(\"interruptAfter - will process first chunk\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (Queue.unbounded<number>())\n      const fiber = yield* pipe(\n        Stream.fromQueue(queue),\n        Stream.interruptAfter(Duration.seconds(5)),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.seconds(6)))\n      yield* (Queue.offer(queue, 1))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"interruptWhen - interrupts the effect\", () =>\n    Effect.gen(function*() {\n      let interrupted = false\n      const effect = Effect.never.pipe(\n        Effect.onInterrupt(() =>\n          Effect.sync(() => {\n            interrupted = true\n          })\n        )\n      )\n\n      const fiber = yield* Stream.fromSchedule(Schedule.spaced(\"1 second\")).pipe(\n        Stream.interruptWhen(effect),\n        Stream.take(1),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* TestClock.adjust(\"1 seconds\")\n      yield* fiber.await\n\n      assertTrue(interrupted)\n    }))\n\n  it.effect(\"forked children are not interrupted early by interruptWhen\", () =>\n    Effect.gen(function*() {\n      const queue = yield* Queue.unbounded<string>()\n      const ref = yield* Ref.make(0)\n      yield* Stream.fromQueue(queue).pipe(\n        Stream.runForEach(() => Ref.update(ref, (n) => n + 1)),\n        Effect.fork,\n        Effect.as(Stream.concat(Stream.succeed(\"\"), Stream.never)),\n        Stream.unwrapScoped,\n        Stream.interruptWhen(Effect.never),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* Queue.offer(queue, \"message\").pipe(\n        Effect.forever,\n        Effect.fork\n      )\n      const result = yield* Ref.get(ref).pipe(\n        Effect.repeat({ until: (n) => n >= 10 })\n      )\n      strictEqual(result, 10)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/interspersing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"intersperse - several values\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4),\n        Stream.map(String),\n        Stream.intersperse(\".\"),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"1\", \".\", \"2\", \".\", \"3\", \".\", \"4\"])\n    }))\n\n  it.effect(\"intersperseAffixes - several values\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4),\n        Stream.map(String),\n        Stream.intersperseAffixes({ start: \"[\", middle: \".\", end: \"]\" }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"[\", \"1\", \".\", \"2\", \".\", \"3\", \".\", \"4\", \"]\"])\n    }))\n\n  it.effect(\"intersperse - single value\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.map(String),\n        Stream.intersperse(\".\"),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"1\"])\n    }))\n\n  it.effect(\"intersperseAffixes - single value\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.map(String),\n        Stream.intersperseAffixes({ start: \"[\", middle: \".\", end: \"]\" }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"[\", \"1\", \"]\"])\n    }))\n\n  it.effect(\"intersperse - several from repeat effect (ZIO #3729)\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.repeatEffect(Effect.succeed(42)),\n        Stream.map(String),\n        Stream.take(4),\n        Stream.intersperse(\".\"),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"42\", \".\", \"42\", \".\", \"42\", \".\", \"42\"])\n    }))\n\n  it.effect(\"intersperse - several from repeat effect chunk single element (ZIO #3729)\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.repeatEffectChunk(Effect.succeed(Chunk.of(42))),\n        Stream.map(String),\n        Stream.intersperse(\".\"),\n        Stream.take(4),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"42\", \".\", \"42\", \".\"])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/lifecycle.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"onStart\", () =>\n    Effect.gen(function*() {\n      let counter = 0\n      const result = yield* pipe(\n        Stream.make(1, 1),\n        Stream.onStart(Effect.sync(() => counter++)),\n        Stream.runCollect\n      )\n      strictEqual(counter, 1)\n      deepStrictEqual(Array.from(result), [1, 1])\n    }))\n\n  it.effect(\"onEnd\", () =>\n    Effect.gen(function*() {\n      let counter = 0\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.onEnd(Effect.sync(() => counter++)),\n        Stream.runCollect\n      )\n      strictEqual(counter, 1)\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/mapping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Queue from \"effect/Queue\"\nimport * as Ref from \"effect/Ref\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"map\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => n * 2\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.map(f), Stream.runCollect),\n        result2: pipe(Stream.runCollect(stream), Effect.map(Chunk.map(f)))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"mapAccum\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 1, 1),\n        Stream.mapAccum(0, (acc, curr) => [acc + curr, acc + curr]),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"mapAccumEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 1, 1),\n        Stream.mapAccumEffect(0, (acc, curr) => Effect.succeed([acc + curr, acc + curr])),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"mapAccumEffect - error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 1, 1),\n        Stream.mapAccumEffect(0, () => Effect.fail(\"Ouch\")),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"mapAccumEffect - laziness on chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.mapAccumEffect(void 0, (_, n) =>\n          n === 3 ?\n            Effect.fail(\"boom\") :\n            Effect.succeed([void 0, n] as const)),\n        Stream.either,\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result),\n        [Either.right(1), Either.right(2), Either.left(\"boom\")]\n      )\n    }))\n\n  it.effect(\"mapConcat\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => Chunk.of(n)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.mapConcat(f), Stream.runCollect),\n        result2: pipe(Stream.runCollect(stream), Effect.map(Chunk.flatMap((n) => f(n))))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"mapConcatChunk\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => Chunk.of(n)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.mapConcatChunk(f), Stream.runCollect),\n        result2: pipe(Stream.runCollect(stream), Effect.map(Chunk.flatMap((n) => f(n))))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"mapConcatChunkEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => Chunk.of(n)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.mapConcatChunkEffect((n) => Effect.succeed(f(n))), Stream.runCollect),\n        result2: pipe(Stream.runCollect(stream), Effect.map(Chunk.flatMap((n) => f(n))))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"mapConcatChunkEffect - error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.mapConcatChunkEffect(() => Effect.fail(\"Ouch\")),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"mapConcatEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const f = (n: number) => Chunk.of(n)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.mapConcatEffect((n) => Effect.succeed(f(n))), Stream.runCollect),\n        result2: pipe(Stream.runCollect(stream), Effect.map(Chunk.flatMap((n) => f(n))))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"mapConcatEffect - error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.mapConcatEffect(() => Effect.fail(\"Ouch\")),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"mapError\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fail(\"123\"),\n        Stream.mapError((n) => Number.parseInt(n)),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, 123)\n    }))\n\n  it.effect(\"mapErrorCause\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.failCause(Cause.fail(\"123\")),\n        Stream.mapErrorCause(Cause.map((s) => Number.parseInt(s))),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, 123)\n    }))\n\n  it.effect(\"mapEffect - Effect.forEach equivalence\", () =>\n    Effect.gen(function*() {\n      const chunk = Chunk.make(1, 2, 3, 4, 5)\n      const stream = Stream.fromIterable(chunk)\n      const f = (n: number) => Effect.succeed(n * 2)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.mapEffect(f), Stream.runCollect),\n        result2: pipe(chunk, Effect.forEach(f))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"mapEffect - laziness on chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.mapEffect((n) =>\n          n === 3 ?\n            Effect.fail(\"boom\") :\n            Effect.succeed(n)\n        ),\n        Stream.either,\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result),\n        [Either.right(1), Either.right(2), Either.left(\"boom\")]\n      )\n    }))\n\n  it.effect(\"mapEffectPar - Effect.forEachParN equivalence\", () =>\n    Effect.gen(function*() {\n      const concurrency = 8\n      const chunk = Chunk.make(1, 2, 3, 4, 5)\n      const stream = Stream.fromIterable(chunk)\n      const f = (n: number) => Effect.succeed(n * 2)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.mapEffect(f, { concurrency }), Stream.runCollect),\n        result2: Effect.forEach(chunk, f, { concurrency })\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"mapEffectPar - ordering when parallelism is 1\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (Queue.unbounded<number>())\n      yield* pipe(\n        Stream.range(0, 8),\n        Stream.mapEffect((n) => Queue.offer(queue, n), { concurrency: 1 }),\n        Stream.runDrain\n      )\n      const result = yield* (Queue.takeAll(queue))\n      deepStrictEqual(Array.from(result), [0, 1, 2, 3, 4, 5, 6, 7, 8])\n    }))\n\n  it.effect(\"mapEffectPar - interruption propagation\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Stream.make(void 0),\n        Stream.mapEffect(() =>\n          pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.zipRight(Effect.never),\n            Effect.onInterrupt(() => Ref.set(ref, true))\n          ), { concurrency: 2 }),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"mapEffectPar - guarantees ordering\", () =>\n    Effect.gen(function*() {\n      const n = 4096\n      const chunk = Chunk.make(1, 2, 3, 4, 5)\n      const stream = Stream.fromChunk(chunk)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.mapEffect(Effect.succeed), Stream.runCollect),\n        result2: pipe(stream, Stream.mapEffect(Effect.succeed, { concurrency: n }), Stream.runCollect)\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"mapEffectPar - awaits child fibers properly\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromIterable(Chunk.range(0, 10)),\n        Stream.interruptWhen(Effect.never),\n        Stream.mapEffect(() => pipe(Effect.succeed(1), Effect.repeatN(200)), { concurrency: 8 }),\n        Stream.runDrain,\n        Effect.exit\n      )\n      assertFalse(Exit.isInterrupted(result))\n    }))\n\n  it.effect(\"mapEffectPar - interrupts pending tasks when one of the tasks fails\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const latch1 = yield* (Deferred.make<void>())\n      const latch2 = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.mapEffect(\n          (n) =>\n            n === 1 ?\n              pipe(\n                Deferred.succeed(latch1, void 0),\n                Effect.zipRight(Effect.never),\n                Effect.onInterrupt(() => Ref.update(ref, (n) => n + 1))\n              ) :\n              n === 2 ?\n              pipe(\n                Deferred.succeed(latch2, void 0),\n                Effect.zipRight(Effect.never),\n                Effect.onInterrupt(() => Ref.update(ref, (n) => n + 1))\n              ) :\n              pipe(\n                Deferred.await(latch1),\n                Effect.zipRight(Deferred.await(latch1)),\n                Effect.zipRight(Effect.fail(\"boom\"))\n              ),\n          { concurrency: 3 }\n        ),\n        Stream.runDrain,\n        Effect.exit\n      )\n      const count = yield* (Ref.get(ref))\n      strictEqual(count, 2)\n      deepStrictEqual(result, Exit.fail(\"boom\"))\n    }))\n\n  it.effect(\"mapEffectPar - propagates the correct error with subsequent calls to mapEffectPar (ZIO #4514)\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromIterable(Chunk.range(1, 50)),\n        Stream.mapEffect((n) => n < 10 ? Effect.succeed(n) : Effect.fail(\"boom\"), { concurrency: 20 }),\n        Stream.mapEffect((n) => Effect.succeed(n), { concurrency: 20 }),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"boom\")\n    }))\n\n  it.effect(\"mapEffectPar - propagates the error of the original stream\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(\n        Stream.range(1, 10),\n        Stream.concat(Stream.fail(new Cause.RuntimeException(\"boom\"))),\n        Stream.mapEffect(() => Effect.sleep(Duration.seconds(1)), { concurrency: 2 }),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.seconds(5)))\n      const exit = yield* (Fiber.await(fiber))\n      deepStrictEqual(exit, Exit.fail(new Cause.RuntimeException(\"boom\")))\n    }))\n\n  it.effect(\"mapEffectParUnordered - mapping with failure is failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromIterable(Chunk.range(0, 3)),\n        Stream.mapEffect(() => Effect.fail(\"fail\"), { concurrency: 10, unordered: true }),\n        Stream.runDrain,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(\"fail\"))\n    }))\n\n  it.effect(\"mapEffect with key\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(\n        Stream.make(10, 20, 30, 40),\n        Stream.mapEffect((n) => Effect.delay(Effect.succeed(n), n), { key: identity }),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* TestClock.adjust(40)\n      const exit = fiber.unsafePoll()\n      assertTrue(Exit.isExit(exit))\n      assertTrue(Exit.isSuccess(exit))\n      deepStrictEqual(Chunk.toReadonlyArray(exit.value), [10, 20, 30, 40])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/merging.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { constVoid, pipe } from \"effect/Function\"\nimport * as HashSet from \"effect/HashSet\"\nimport * as Queue from \"effect/Queue\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\nimport * as TestServices from \"effect/TestServices\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"merge - slower stream\", () =>\n    Effect.gen(function*() {\n      const stream1 = Stream.make(1, 2, 3, 4)\n      const stream2 = Stream.tap(\n        Stream.make(5, 6, 7, 8),\n        () => TestServices.provideLive(Effect.sleep(Duration.millis(10)))\n      )\n      const result = yield* pipe(\n        Stream.merge(stream1, stream2),\n        Stream.runCollect\n      )\n      deepStrictEqual([...result], [1, 2, 3, 4, 5, 6, 7, 8])\n    }))\n\n  it.effect(\"mergeAll - short circuiting\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.mergeAll([Stream.never, Stream.make(1)], { concurrency: 2 }),\n        Stream.take(1),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1])\n    }))\n\n  it.effect(\"mergeWithTag\", (ctx) =>\n    Effect.gen(function*() {\n      const stream = Stream.mergeWithTag({\n        a: Stream.make(0),\n        b: Stream.make(\"\")\n      }, { concurrency: 1 })\n\n      const res = Chunk.toArray(yield* Stream.runCollect(stream))\n      ctx.expect(res).toEqual([\n        { _tag: \"a\", value: 0 },\n        { _tag: \"b\", value: \"\" }\n      ])\n    }))\n\n  it.effect(\"mergeHaltLeft - terminates as soon as the first stream terminates\", () =>\n    Effect.gen(function*() {\n      const queue1 = yield* (Queue.unbounded<number>())\n      const queue2 = yield* (Queue.unbounded<number>())\n      const stream1 = Stream.fromQueue(queue1)\n      const stream2 = Stream.fromQueue(queue2)\n      const fiber = yield* pipe(\n        stream1,\n        Stream.merge(stream2, { haltStrategy: \"left\" }),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* pipe(Queue.offer(queue1, 1), Effect.zipRight(TestClock.adjust(Duration.seconds(1))))\n      yield* pipe(Queue.offer(queue1, 2), Effect.zipRight(TestClock.adjust(Duration.seconds(1))))\n      yield* pipe(Queue.shutdown(queue1), Effect.zipRight(TestClock.adjust(Duration.seconds(1))))\n      yield* (Queue.offer(queue2, 3))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), [1, 2])\n    }))\n\n  it.effect(\"mergeHaltEither - interrupts pulling on finish\", () =>\n    Effect.gen(function*() {\n      const stream1 = Stream.make(1, 2, 3)\n      const stream2 = Stream.fromEffect(pipe(Effect.sleep(Duration.seconds(5)), Effect.as(4)))\n      const result = yield* pipe(\n        stream1,\n        Stream.merge(stream2, { haltStrategy: \"left\" }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"mergeHaltRight - terminates as soon as the second stream terminates\", () =>\n    Effect.gen(function*() {\n      const queue1 = yield* (Queue.unbounded<number>())\n      const queue2 = yield* (Queue.unbounded<number>())\n      const stream1 = Stream.fromQueue(queue1)\n      const stream2 = Stream.fromQueue(queue2)\n      const fiber = yield* pipe(\n        stream1,\n        Stream.merge(stream2, { haltStrategy: \"right\" }),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* pipe(Queue.offer(queue2, 1), Effect.zipRight(TestClock.adjust(Duration.seconds(1))))\n      yield* pipe(Queue.offer(queue2, 2), Effect.zipRight(TestClock.adjust(Duration.seconds(1))))\n      yield* pipe(Queue.shutdown(queue2), Effect.zipRight(TestClock.adjust(Duration.seconds(1))))\n      yield* (Queue.offer(queue1, 3))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), [1, 2])\n    }))\n\n  it.effect(\"mergeHaltEither - terminates as soon as either stream terminates\", () =>\n    Effect.gen(function*() {\n      const queue1 = yield* (Queue.unbounded<number>())\n      const queue2 = yield* (Queue.unbounded<number>())\n      const stream1 = Stream.fromQueue(queue1)\n      const stream2 = Stream.fromQueue(queue2)\n      const fiber = yield* pipe(\n        stream1,\n        Stream.merge(stream2, { haltStrategy: \"either\" }),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Queue.shutdown(queue1))\n      yield* (TestClock.adjust(Duration.seconds(1)))\n      yield* (Queue.offer(queue2, 1))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(Chunk.isEmpty(result))\n    }))\n\n  it.effect(\"merge - equivalence with set union\", () =>\n    Effect.gen(function*() {\n      const stream1 = Stream.make(1, 2, 3, 4)\n      const stream2 = Stream.make(5, 6, 7, 8)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(\n          stream1,\n          Stream.merge(stream2),\n          Stream.runCollect,\n          Effect.map(HashSet.fromIterable)\n        ),\n        result2: pipe(\n          Stream.runCollect(stream1),\n          Effect.zipWith(\n            Stream.runCollect(stream2),\n            (chunk1, chunk2) => pipe(chunk1, Chunk.appendAll(chunk2))\n          ),\n          Effect.map(HashSet.fromIterable)\n        )\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"merge - fails as soon as one stream fails\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.merge(Stream.fail(void 0)),\n        Stream.runCollect,\n        Effect.exit\n      )\n      assertTrue(Exit.isFailure(result))\n    }))\n\n  it.effect(\"mergeWith - prioritizes failures\", () =>\n    Effect.gen(function*() {\n      const stream1 = Stream.never\n      const stream2 = Stream.fail(\"Ouch\")\n      const result = yield* pipe(\n        stream1,\n        Stream.mergeWith(stream2, { onSelf: constVoid, onOther: constVoid }),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/pagination.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"paginate\", () =>\n    Effect.gen(function*() {\n      const s: readonly [number, Array<number>] = [0, [1, 2, 3]]\n      const result = yield* pipe(\n        Stream.paginate(s, ([n, nums]) =>\n          nums.length === 0 ?\n            [n, Option.none()] as const :\n            [n, Option.some([nums[0], nums.slice(1)] as const)] as const),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0, 1, 2, 3])\n    }))\n\n  it.effect(\"paginateEffect\", () =>\n    Effect.gen(function*() {\n      const s: readonly [number, Array<number>] = [0, [1, 2, 3]]\n      const result = yield* pipe(\n        Stream.paginateEffect(\n          s,\n          (\n            [n, nums]\n          ): Effect.Effect<readonly [number, Option.Option<readonly [number, Array<number>]>]> =>\n            nums.length === 0 ?\n              Effect.succeed([n, Option.none()]) :\n              Effect.succeed([n, Option.some([nums[0], nums.slice(1)])])\n        ),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0, 1, 2, 3])\n    }))\n\n  it.effect(\"paginateChunk\", () =>\n    Effect.gen(function*() {\n      const s: readonly [Chunk.Chunk<number>, Array<number>] = [Chunk.of(0), [1, 2, 3, 4, 5]]\n      const pageSize = 2\n      const result = yield* pipe(\n        Stream.paginateChunk(s, ([chunk, nums]) =>\n          nums.length === 0 ?\n            [chunk, Option.none()] as const :\n            [\n              chunk,\n              Option.some(\n                [\n                  Chunk.fromIterable(nums.slice(0, pageSize)),\n                  nums.slice(pageSize)\n                ] as const\n              )\n            ] as const),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0, 1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"paginateChunkEffect\", () =>\n    Effect.gen(function*() {\n      const s: readonly [Chunk.Chunk<number>, Array<number>] = [Chunk.of(0), [1, 2, 3, 4, 5]]\n      const pageSize = 2\n      const result = yield* pipe(\n        Stream.paginateChunkEffect(s, ([chunk, nums]) =>\n          nums.length === 0 ?\n            Effect.succeed([chunk, Option.none<readonly [Chunk.Chunk<number>, Array<number>]>()] as const) :\n            Effect.succeed(\n              [\n                chunk,\n                Option.some(\n                  [\n                    Chunk.fromIterable(nums.slice(0, pageSize)),\n                    nums.slice(pageSize)\n                  ] as const\n                )\n              ] as const\n            )),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0, 1, 2, 3, 4, 5])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/partitioning.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"partitionEither - allows repeated runs without hanging\", () =>\n    Effect.gen(function*() {\n      const stream = pipe(\n        Stream.fromIterable(Chunk.empty<number>()),\n        Stream.partitionEither((n) => Effect.succeed(n % 2 === 0 ? Either.left(n) : Either.right(n))),\n        Effect.map(([evens, odds]) => pipe(evens, Stream.mergeEither(odds))),\n        Effect.flatMap(Stream.runCollect),\n        Effect.scoped\n      )\n      const result = yield* pipe(\n        Effect.all(Array.from({ length: 100 }, () => stream)),\n        Effect.as(0)\n      )\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"partition - values\", () =>\n    Effect.gen(function*() {\n      const { result1, result2 } = yield* pipe(\n        Stream.range(0, 5),\n        Stream.partition((n) => n % 2 === 0),\n        Effect.flatMap(([odds, evens]) =>\n          Effect.all({\n            result1: Stream.runCollect(evens),\n            result2: Stream.runCollect(odds)\n          })\n        ),\n        Effect.scoped\n      )\n      deepStrictEqual(Array.from(result1), [0, 2, 4])\n      deepStrictEqual(Array.from(result2), [1, 3, 5])\n    }))\n\n  it.effect(\"partition - errors\", () =>\n    Effect.gen(function*() {\n      const { result1, result2 } = yield* pipe(\n        Stream.make(0),\n        Stream.concat(Stream.fail(\"boom\")),\n        Stream.partition((n) => n % 2 === 0),\n        Effect.flatMap(([evens, odds]) =>\n          Effect.all({\n            result1: Effect.either(Stream.runCollect(evens)),\n            result2: Effect.either(Stream.runCollect(odds))\n          })\n        ),\n        Effect.scoped\n      )\n      assertLeft(result1, \"boom\")\n      assertLeft(result2, \"boom\")\n    }))\n\n  it.effect(\"partition - backpressure\", () =>\n    Effect.gen(function*() {\n      const { result1, result2, result3 } = yield* pipe(\n        Stream.range(0, 5),\n        Stream.partition((n) => (n % 2 === 0), { bufferSize: 1 }),\n        Effect.flatMap(([odds, evens]) =>\n          Effect.gen(function*() {\n            const ref = yield* (Ref.make(Chunk.empty<number>()))\n            const latch = yield* (Deferred.make<void>())\n            const fiber = yield* pipe(\n              evens,\n              Stream.tap((n) =>\n                pipe(\n                  Ref.update(ref, Chunk.prepend(n)),\n                  Effect.zipRight(\n                    pipe(\n                      Deferred.succeed(latch, void 0),\n                      Effect.when(() => n === 2)\n                    )\n                  )\n                )\n              ),\n              Stream.runDrain,\n              Effect.fork\n            )\n            yield* (Deferred.await(latch))\n            const result1 = yield* (Ref.get(ref))\n            const result2 = yield* (Stream.runCollect(odds))\n            yield* (Fiber.await(fiber))\n            const result3 = yield* (Ref.get(ref))\n            return { result1, result2, result3 }\n          })\n        ),\n        Effect.scoped\n      )\n      deepStrictEqual(Array.from(result1), [2, 0])\n      deepStrictEqual(Array.from(result2), [1, 3, 5])\n      deepStrictEqual(Array.from(result3), [4, 2, 0])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/peeling.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { constTrue, pipe } from \"effect/Function\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"peel\", () =>\n    Effect.gen(function*() {\n      const sink = Sink.take<number>(3)\n      const [peeled, rest] = yield* pipe(\n        Stream.fromChunks(Chunk.range(1, 3), Chunk.range(4, 6)),\n        Stream.peel(sink),\n        Effect.flatMap(([peeled, rest]) =>\n          pipe(\n            Stream.runCollect(rest),\n            Effect.map((rest) => [peeled, rest])\n          )\n        ),\n        Effect.scoped\n      )\n      deepStrictEqual(Array.from(peeled), [1, 2, 3])\n      deepStrictEqual(Array.from(rest), [4, 5, 6])\n    }))\n\n  it.effect(\"peel - propagates errors\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.repeatEffect(Effect.fail(\"fail\"))\n      const sink = Sink.fold<Chunk.Chunk<number>, number>(\n        Chunk.empty(),\n        constTrue,\n        Chunk.append\n      )\n      const result = yield* pipe(\n        stream,\n        Stream.peel(sink),\n        Effect.exit,\n        Effect.scoped\n      )\n      deepStrictEqual(result, Exit.fail(\"fail\"))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/racing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"raceAll sync\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.raceAll(\n          Stream.make(0, 1, 2, 3),\n          Stream.make(4, 5, 6, 7),\n          Stream.make(7, 8, 9, 10)\n        ),\n        Stream.runCollect,\n        Effect.map(Chunk.toReadonlyArray)\n      )\n      deepStrictEqual(result, [0, 1, 2, 3])\n    }))\n\n  it.effect(\"raceAll async\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(\n        Stream.raceAll(\n          Stream.fromSchedule(Schedule.spaced(\"1 second\")),\n          Stream.fromSchedule(Schedule.spaced(\"2 second\"))\n        ),\n        Stream.take(5),\n        Stream.runCollect,\n        Effect.map(Chunk.toReadonlyArray),\n        Effect.fork\n      )\n      yield* TestClock.adjust(\"5 second\")\n      const result = yield* Fiber.join(fiber)\n      deepStrictEqual(result, [0, 1, 2, 3, 4])\n    }))\n\n  it.effect(\"raceAll combined async + sync\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.raceAll(\n          Stream.fromSchedule(Schedule.spaced(\"1 second\")),\n          Stream.make(0, 1, 2, 3)\n        ),\n        Stream.runCollect,\n        Effect.map(Chunk.toReadonlyArray)\n      )\n      deepStrictEqual(result, [0, 1, 2, 3])\n    }))\n\n  it.effect(\"raceAll combined sync + async\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.raceAll(\n          Stream.make(0, 1, 2, 3),\n          Stream.fromSchedule(Schedule.spaced(\"1 second\"))\n        ),\n        Stream.runCollect,\n        Effect.map(Chunk.toReadonlyArray)\n      )\n      deepStrictEqual(result, [0, 1, 2, 3])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/repeating.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Exit from \"effect/Exit\"\nimport * as fc from \"effect/FastCheck\"\nimport * as Fiber from \"effect/Fiber\"\nimport { constVoid, identity, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\nimport * as TestEnvironment from \"effect/TestContext\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"forever\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Stream.make(1),\n        Stream.forever,\n        Stream.runForEachWhile(() => Ref.modify(ref, (sum) => [sum >= 9 ? false : true, sum + 1] as const))\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 10)\n    }))\n\n  it.effect(\"repeat\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.repeat(Schedule.recurs(4)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 1, 1, 1, 1])\n    }))\n\n  it.effect(\"tick\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(\n        Stream.tick(\"10 millis\"),\n        Stream.take(2),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.millis(50)))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), [undefined, undefined])\n    }))\n\n  it.effect(\"repeat - short circuits\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const fiber = yield* pipe(\n        Stream.fromEffect(Ref.update(ref, Chunk.prepend(1))),\n        Stream.repeat(Schedule.spaced(Duration.millis(10))),\n        Stream.take(2),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.millis(50)))\n      yield* (Fiber.join(fiber))\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [1, 1])\n    }))\n\n  it.effect(\"repeat - Schedule.CurrentIterationMetadata\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<undefined | Schedule.IterationMetadata>()))\n      const fiber = yield* pipe(\n        Stream.fromEffect(\n          Schedule.CurrentIterationMetadata.pipe(\n            Effect.flatMap((currentIterationMetadata) => Ref.update(ref, Chunk.append(currentIterationMetadata)))\n          )\n        ),\n        Stream.repeat(Schedule.exponential(Duration.millis(10))),\n        Stream.runDrain,\n        Effect.fork\n      )\n\n      yield* (TestClock.adjust(Duration.millis(70)))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          input: undefined,\n          output: undefined,\n          now: 0,\n          recurrence: 0,\n          start: 0\n        },\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          input: undefined,\n          output: Duration.millis(10),\n          now: 0,\n          recurrence: 1,\n          start: 0\n        },\n        {\n          elapsed: Duration.millis(10),\n          elapsedSincePrevious: Duration.millis(10),\n          input: undefined,\n          output: Duration.millis(20),\n          now: 10,\n          recurrence: 2,\n          start: 0\n        },\n        {\n          elapsed: Duration.millis(30),\n          elapsedSincePrevious: Duration.millis(20),\n          input: undefined,\n          output: Duration.millis(40),\n          now: 30,\n          recurrence: 3,\n          start: 0\n        }\n      ])\n    }))\n\n  it.effect(\"repeat - does not swallow errors on a repetition\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const result = yield* pipe(\n        Stream.fromEffect(pipe(\n          Ref.getAndUpdate(ref, (n) => n + 1),\n          Effect.flatMap((n) => n <= 2 ? Effect.succeed(n) : Effect.fail(\"boom\"))\n        )),\n        Stream.repeat(Schedule.recurs(3)),\n        Stream.runDrain,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(\"boom\"))\n    }))\n\n  it.effect(\"repeatEither\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.repeatEither(Schedule.recurs(4)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\n        Either.right(1),\n        Either.right(1),\n        Either.left(0),\n        Either.right(1),\n        Either.left(1),\n        Either.right(1),\n        Either.left(2),\n        Either.right(1),\n        Either.left(3)\n      ])\n    }))\n\n  it.effect(\"repeatEffectOption - emit elements\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.repeatEffectOption(Effect.succeed(1)),\n        Stream.take(2),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 1])\n    }))\n\n  it.effect(\"repeatEffectOption - emit elements until pull fails with None\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const result = yield* pipe(\n        Stream.repeatEffectOption(\n          pipe(\n            Ref.updateAndGet(ref, (n) => n + 1),\n            Effect.flatMap((n) =>\n              n >= 5 ?\n                Effect.fail(Option.none()) :\n                Effect.succeed(n)\n            )\n          )\n        ),\n        Stream.take(10),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"repeatEffectOption - stops evaluating the effect once it fails with None\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Stream.repeatEffectOption(pipe(\n          Ref.updateAndGet(ref, (n) => n + 1),\n          Effect.zipRight(Effect.fail(Option.none()))\n        )),\n        Stream.toPull,\n        Effect.flatMap((pull) =>\n          pipe(\n            Effect.ignore(pull),\n            Effect.zipRight(Effect.ignore(pull))\n          )\n        ),\n        Effect.scoped\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"repeatEffectWithSchedule\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const fiber = yield* pipe(\n        Stream.repeatEffectWithSchedule(\n          Ref.update(ref, Chunk.append(1)),\n          Schedule.spaced(Duration.millis(10))\n        ),\n        Stream.take(2),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.millis(50)))\n      yield* (Fiber.join(fiber))\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [1, 1])\n    }), 10000)\n\n  it(\"repeatEffectWithSchedule - allow schedule to rely on effect value\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1, max: 100 }), async (length) => {\n      const effect = Effect.gen(function*() {\n        const ref = yield* (Ref.make(0))\n        const effect = pipe(\n          Ref.getAndUpdate(ref, (n) => n + 1),\n          Effect.filterOrFail(\n            (n) => n <= length + 1,\n            constVoid\n          )\n        )\n        const schedule = pipe(\n          Schedule.identity<number>(),\n          Schedule.whileOutput((n) => n < length)\n        )\n        const stream = Stream.repeatEffectWithSchedule(effect, schedule)\n        return yield* pipe(\n          Stream.runCollect(stream),\n          Effect.provide(TestEnvironment.TestContext)\n        )\n      })\n      const result = await Effect.runPromise(effect)\n      deepStrictEqual(Array.from(result), Array.from(Chunk.range(0, length)))\n    })))\n\n  it.effect(\"repeatEffectWithSchedule - should perform repetitions in addition to the first execution (one repetition)\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.repeatEffectWithSchedule(Effect.succeed(1), Schedule.once),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 1])\n    }))\n\n  it.effect(\"repeatEffectWithSchedule - should perform repetitions in addition to the first execution (zero repetitions)\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.repeatEffectWithSchedule(Effect.succeed(1), Schedule.stop),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1])\n    }))\n\n  it.effect(\"repeatEffectWithSchedule - emits before delaying according to the schedule\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const schedule = Schedule.spaced(Duration.seconds(1))\n      const fiber = yield* pipe(\n        Stream.repeatEffectWithSchedule(Effect.void, schedule),\n        Stream.tap(() => Ref.update(ref, (n) => n + 1)),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.seconds(0)))\n      const result1 = yield* (Ref.get(ref))\n      yield* (TestClock.adjust(Duration.seconds(1)))\n      const result2 = yield* (Ref.get(ref))\n      yield* (Fiber.interrupt(fiber))\n      strictEqual(result1, 1)\n      strictEqual(result2, 2)\n    }))\n\n  it.effect(\"repeatEither - short circuits\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const fiber = yield* pipe(\n        Stream.fromEffect(Ref.update(ref, Chunk.prepend(1))),\n        Stream.repeatEither(Schedule.spaced(Duration.millis(10))),\n        Stream.take(3), // take one of the schedule outputs\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.millis(50)))\n      yield* (Fiber.join(fiber))\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [1, 1])\n    }))\n\n  it.effect(\"repeatElements - simple\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(\"A\", \"B\", \"C\"),\n        Stream.repeatElements(Schedule.once),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"A\", \"A\", \"B\", \"B\", \"C\", \"C\"])\n    }))\n\n  it.effect(\"repeatElements - short circuits in a schedule\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(\"A\", \"B\", \"C\"),\n        Stream.repeatElements(Schedule.once),\n        Stream.take(4),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"A\", \"A\", \"B\", \"B\"])\n    }))\n\n  it.effect(\"repeatElements - short circuits after schedule\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(\"A\", \"B\", \"C\"),\n        Stream.repeatElements(Schedule.once),\n        Stream.take(3),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"A\", \"A\", \"B\"])\n    }))\n\n  it.effect(\"repeatElementsWith\", () =>\n    Effect.gen(function*() {\n      const schedule = pipe(\n        Schedule.recurs(0),\n        Schedule.zipRight(Schedule.fromFunction(() => 123))\n      )\n      const result = yield* pipe(\n        Stream.make(\"A\", \"B\", \"C\"),\n        Stream.repeatElementsWith(schedule, { onElement: identity, onSchedule: String }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"A\", \"123\", \"B\", \"123\", \"C\", \"123\"])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/retrying.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Clock from \"effect/Clock\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"retry - retries a failing stream\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(0)\n      const stream = pipe(\n        Stream.fromEffect(Ref.getAndUpdate(ref, (n) => n + 1)),\n        Stream.concat(Stream.fail(Option.none()))\n      )\n      const result = yield* pipe(\n        stream,\n        Stream.retry(Schedule.forever),\n        Stream.take(2),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.fromIterable(result), [0, 1])\n    }))\n\n  it.effect(\"retry - cleans up resources before restarting the stream\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(0)\n      const stream = pipe(\n        Effect.addFinalizer(() => Ref.getAndUpdate(ref, (n) => n + 1)),\n        Effect.as(\n          pipe(\n            Stream.fromEffect(Ref.get(ref)),\n            Stream.concat(Stream.fail(Option.none()))\n          )\n        ),\n        Stream.unwrapScoped\n      )\n      const result = yield* pipe(\n        stream,\n        Stream.retry(Schedule.forever),\n        Stream.take(2),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.fromIterable(result), [0, 1])\n    }))\n\n  it.effect(\"retry - retries a failing stream according to a schedule\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(Chunk.empty<number>())\n      const stream = pipe(\n        Stream.fromEffect(\n          pipe(\n            Clock.currentTimeMillis,\n            Effect.flatMap((n) => Ref.update(ref, Chunk.prepend(n)))\n          )\n        ),\n        Stream.flatMap(() => Stream.fail(Option.none()))\n      )\n      const fiber = yield* pipe(\n        stream,\n        Stream.retry(Schedule.exponential(Duration.seconds(1))),\n        Stream.take(3),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* TestClock.adjust(Duration.seconds(1))\n      yield* TestClock.adjust(Duration.seconds(2))\n      yield* Fiber.interrupt(fiber)\n      const result = yield* pipe(Ref.get(ref), Effect.map(Chunk.map((n) => new Date(n).getSeconds())))\n      deepStrictEqual(Array.fromIterable(result), [3, 1, 0])\n    }))\n\n  it.effect(\"retry - reset the schedule after a successful pull\", () =>\n    Effect.gen(function*() {\n      const times = yield* Ref.make(Chunk.empty<number>())\n      const ref = yield* Ref.make(0)\n      const effect = pipe(\n        Clock.currentTimeMillis,\n        Effect.flatMap((time) =>\n          pipe(\n            Ref.update(times, Chunk.prepend(time / 1000)),\n            Effect.zipRight(Ref.updateAndGet(ref, (n) => n + 1))\n          )\n        )\n      )\n      const stream = pipe(\n        Stream.fromEffect(effect),\n        Stream.flatMap((attempt) =>\n          attempt === 3 || attempt === 5 ?\n            Stream.succeed(attempt) :\n            Stream.fail(Option.none())\n        ),\n        Stream.forever\n      )\n      const fiber = yield* pipe(\n        stream,\n        Stream.retry(Schedule.exponential(Duration.seconds(1))),\n        Stream.take(2),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* TestClock.adjust(Duration.seconds(1))\n      yield* TestClock.adjust(Duration.seconds(2))\n      yield* TestClock.adjust(Duration.seconds(1))\n      yield* Fiber.join(fiber)\n      const result = yield* Ref.get(times)\n      deepStrictEqual(Array.fromIterable(result), [4, 3, 3, 1, 0])\n    }))\n\n  it.effect(\"retry - Schedule.CurrentIterationMetadata\", () =>\n    Effect.gen(function*() {\n      const iterationMetadata = yield* Ref.make(Chunk.empty<undefined | Schedule.IterationMetadata>())\n      const fiber = yield* pipe(\n        Stream.fail(1),\n        Stream.catchAll((x) =>\n          Effect.gen(function*() {\n            const currentIterationMetadata = yield* Schedule.CurrentIterationMetadata\n            yield* Ref.update(iterationMetadata, Chunk.append(currentIterationMetadata))\n            return yield* Effect.fail(x)\n          })\n        ),\n        Stream.retry(Schedule.exponential(Duration.seconds(1))),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* TestClock.adjust(Duration.seconds(7))\n      yield* Fiber.interrupt(fiber)\n      const result = yield* Ref.get(iterationMetadata)\n      deepStrictEqual(Array.fromIterable(result), [\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          input: undefined,\n          output: undefined,\n          now: 0,\n          recurrence: 0,\n          start: 0\n        },\n        {\n          elapsed: Duration.zero,\n          elapsedSincePrevious: Duration.zero,\n          input: 1,\n          output: Duration.millis(1000),\n          now: 0,\n          recurrence: 1,\n          start: 0\n        },\n        {\n          elapsed: Duration.seconds(1),\n          elapsedSincePrevious: Duration.seconds(1),\n          input: 1,\n          output: Duration.millis(2000),\n          now: 1000,\n          recurrence: 2,\n          start: 0\n        },\n        {\n          elapsed: Duration.seconds(3),\n          elapsedSincePrevious: Duration.seconds(2),\n          input: 1,\n          output: Duration.millis(4000),\n          now: 3000,\n          recurrence: 3,\n          start: 0\n        }\n      ])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/running.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertNone, assertSome, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"runFoldWhile\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 1, 1, 1, 1),\n        Stream.runFoldWhile(0, (n) => n < 3, (x, y) => x + y)\n      )\n      strictEqual(result, 3)\n    }))\n\n  it.effect(\"runForEach - with a small data set\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Stream.make(1, 1, 1, 1, 1),\n        Stream.runForEach((i) => Ref.update(ref, (n) => n + i))\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 5)\n    }))\n\n  it.effect(\"runForEach - with a bigger data set\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Stream.fromIterable(Array.from({ length: 1_000 }, () => 1)),\n        Stream.runForEach((i) => Ref.update(ref, (n) => n + i))\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 1_000)\n    }))\n\n  it.effect(\"runForEachWhile - with a small data set\", () =>\n    Effect.gen(function*() {\n      const expected = 3\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Stream.make(1, 1, 1, 1, 1, 1),\n        Stream.runForEachWhile((n) =>\n          Ref.modify(ref, (sum) =>\n            sum >= expected ?\n              [false, sum] as const :\n              [true, sum + n])\n        )\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, expected)\n    }))\n\n  it.effect(\"runForEachWhile - with a bigger data set\", () =>\n    Effect.gen(function*() {\n      const expected = 500\n      const ref = yield* (Ref.make(0))\n      yield* pipe(\n        Stream.fromIterable(Array.from({ length: 1_000 }, () => 1)),\n        Stream.runForEachWhile((n) =>\n          Ref.modify(ref, (sum) =>\n            sum >= expected ?\n              [false, sum] as const :\n              [true, sum + n] as const)\n        )\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, expected)\n    }))\n\n  it.effect(\"runForEachWhile - short circuits\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(true))\n      yield* pipe(\n        Stream.make(true, true, false),\n        Stream.concat(Stream.drain(Stream.fromEffect(Ref.set(ref, false)))),\n        Stream.runForEachWhile(Effect.succeed)\n      )\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"runHead - non-empty stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Stream.runHead(Stream.make(1, 2, 3, 4)))\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"runHead - empty stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* (Stream.runHead(Stream.empty))\n      assertNone(result)\n    }))\n\n  it.effect(\"runHead - pulls up to the first non-empty chunk\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const head = yield* pipe(\n        Stream.make(\n          Stream.drain(Stream.fromEffect(Ref.update(ref, Chunk.prepend(1)))),\n          Stream.drain(Stream.fromEffect(Ref.update(ref, Chunk.prepend(2)))),\n          Stream.make(1),\n          Stream.drain(Stream.fromEffect(Ref.update(ref, Chunk.prepend(3))))\n        ),\n        Stream.flatten(),\n        Stream.runHead\n      )\n      const result = yield* (Ref.get(ref))\n      assertSome(head, 1)\n      deepStrictEqual(Array.from(result), [2, 1])\n    }))\n\n  it.effect(\"runLast - non-empty stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4),\n        Stream.runLast\n      )\n      assertSome(result, 4)\n    }))\n\n  it.effect(\"runLast - empty stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Stream.empty, Stream.runLast)\n      assertNone(result)\n    }))\n\n  it.effect(\"runScoped - properly closes resources\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const resource = Effect.acquireRelease(\n        Effect.succeed(1),\n        () => Ref.set(ref, true)\n      )\n      const stream = pipe(Stream.scoped(resource), Stream.flatMap((a) => Stream.make(a, a, a)))\n      const [result, state] = yield* pipe(\n        stream,\n        Stream.runScoped(Sink.collectAll()),\n        Effect.flatMap((chunk) => pipe(Ref.get(ref), Effect.map((closed) => [chunk, closed] as const))),\n        Effect.scoped\n      )\n      const finalState = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [1, 1, 1])\n      assertFalse(state)\n      assertTrue(finalState)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/scanning.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"scan\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const { result1, result2 } = yield* Effect.all({\n        result1: pipe(stream, Stream.scan(0, (acc, curr) => acc + curr), Stream.runCollect),\n        result2: pipe(\n          Stream.runCollect(stream),\n          Effect.map((chunk) =>\n            pipe(\n              Chunk.toReadonlyArray(chunk),\n              Array.scan(0, (acc, curr) => acc + curr)\n            )\n          )\n        )\n      })\n      deepStrictEqual(Chunk.toReadonlyArray(result1), result2)\n    }))\n\n  it.effect(\"scanReduce\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const result = yield* pipe(\n        stream,\n        Stream.scanReduce<number, number>((acc, curr) => acc + curr),\n        Stream.runCollect\n      )\n      deepStrictEqual(Chunk.toReadonlyArray(result), [1, 3, 6, 10, 15])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/scheduling.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Clock from \"effect/Clock\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Fiber from \"effect/Fiber\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"schedule\", () =>\n    Effect.gen(function*() {\n      const start = yield* Clock.currentTimeMillis\n      const fiber = yield* pipe(\n        Stream.range(1, 8),\n        Stream.schedule(Schedule.fixed(Duration.millis(100))),\n        Stream.mapEffect((n) =>\n          pipe(\n            Clock.currentTimeMillis,\n            Effect.map((now) => [n, now - start] as const)\n          )\n        ),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* TestClock.adjust(Duration.millis(800))\n      const result = yield* Fiber.join(fiber)\n      deepStrictEqual(Array.from(result), [\n        [1, 100],\n        [2, 200],\n        [3, 300],\n        [4, 400],\n        [5, 500],\n        [6, 600],\n        [7, 700],\n        [8, 800]\n      ])\n    }))\n\n  it.effect(\"scheduleWith\", () =>\n    Effect.gen(function*() {\n      const schedule = pipe(\n        Schedule.recurs(2),\n        Schedule.zipRight(Schedule.fromFunction<string, string>(() => \"Done\"))\n      )\n      const result = yield* pipe(\n        Stream.make(\"A\", \"B\", \"C\", \"A\", \"B\", \"C\"),\n        Stream.scheduleWith(schedule, { onElement: (s) => s.toLowerCase(), onSchedule: identity }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"a\", \"b\", \"c\", \"Done\", \"a\", \"b\", \"c\", \"Done\"])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/scoping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertLeft, assertSome, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Array from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberId from \"effect/FiberId\"\nimport * as Ref from \"effect/Ref\"\nimport * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"acquireRelease - simple example\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(false)\n      const stream = Stream.acquireRelease(\n        Effect.succeed(Chunk.range(0, 2)),\n        () => Ref.set(ref, true)\n      ).pipe(Stream.flatMap(Stream.fromIterable))\n      const result = yield* Stream.runCollect(stream)\n      const released = yield* Ref.get(ref)\n      assertTrue(released)\n      deepStrictEqual(Chunk.toArray(result), [0, 1, 2])\n    }))\n\n  it.effect(\"acquireRelease - short circuits\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(false)\n      const stream = Stream.acquireRelease(\n        Effect.succeed(Chunk.range(0, 2)),\n        () => Ref.set(ref, true)\n      ).pipe(\n        Stream.flatMap(Stream.fromIterable),\n        Stream.take(2)\n      )\n      const result = yield* Stream.runCollect(stream)\n      const released = yield* Ref.get(ref)\n      assertTrue(released)\n      deepStrictEqual(Chunk.toArray(result), [0, 1])\n    }))\n\n  it.effect(\"acquireRelease - no acquisition when short circuiting\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(false)\n      const stream = Stream.make(1).pipe(\n        Stream.concat(\n          Stream.acquireRelease(\n            Ref.set(ref, true),\n            () => Effect.void\n          )\n        ),\n        Stream.take(0)\n      )\n      yield* Stream.runDrain(stream)\n      const result = yield* Ref.get(ref)\n      assertFalse(result)\n    }))\n\n  it.effect(\"acquireRelease - releases when there are defects\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(false)\n      yield* Stream.acquireRelease(\n        Effect.void,\n        () => Ref.set(ref, true)\n      ).pipe(\n        Stream.flatMap(() => Stream.fromEffect(Effect.dieMessage(\"boom\"))),\n        Stream.runDrain,\n        Effect.exit\n      )\n      const result = yield* Ref.get(ref)\n      assertTrue(result)\n    }))\n\n  it.effect(\"acquireRelease - flatMap associativity does not effect lifetime\", () =>\n    Effect.gen(function*() {\n      const leftAssoc = yield* Stream.acquireRelease(\n        Ref.make(true),\n        (ref) => Ref.set(ref, false)\n      ).pipe(\n        Stream.flatMap(Stream.succeed),\n        Stream.flatMap((ref) => Stream.fromEffect(Ref.get(ref))),\n        Stream.runCollect,\n        Effect.map(Chunk.head)\n      )\n      const rightAssoc = yield* Stream.acquireRelease(\n        Ref.make(true),\n        (ref) => Ref.set(ref, false)\n      ).pipe(\n        Stream.flatMap((ref) =>\n          Stream.succeed(ref).pipe(\n            Stream.flatMap((ref) => Stream.fromEffect(Ref.get(ref)))\n          )\n        ),\n        Stream.runCollect,\n        Effect.map(Chunk.head)\n      )\n      assertSome(leftAssoc, true)\n      assertSome(rightAssoc, true)\n    }))\n\n  it.effect(\"acquireRelease - propagates errors\", () =>\n    Effect.gen(function*() {\n      const result = yield* Stream.acquireRelease(\n        Effect.void,\n        () => Effect.dieMessage(\"die\")\n      ).pipe(\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.die(new Cause.RuntimeException(\"die\")))\n    }))\n\n  it.effect(\"ensuring\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(Chunk.empty<string>())\n      yield* Stream.acquireRelease(\n        Ref.update(ref, Chunk.append(\"Acquire\")),\n        () => Ref.update(ref, Chunk.append(\"Release\"))\n      ).pipe(\n        Stream.crossRight(Stream.fromEffect(Ref.update(ref, Chunk.append(\"Use\")))),\n        Stream.ensuring(Ref.update(ref, Chunk.append(\"Ensuring\"))),\n        Stream.runDrain\n      )\n      const result = yield* Ref.get(ref)\n      deepStrictEqual(Chunk.toArray(result), [\"Acquire\", \"Use\", \"Release\", \"Ensuring\"])\n    }))\n\n  it.effect(\"scoped - preserves the failure of an effect\", () =>\n    Effect.gen(function*() {\n      const result = yield* Stream.scoped(Effect.fail(\"fail\")).pipe(\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"fail\")\n    }))\n\n  it.effect(\"scoped - preserves the interruptibility of an effect\", () =>\n    Effect.gen(function*() {\n      const isInterruptible1 = yield* Effect.checkInterruptible(Effect.succeed).pipe(\n        Stream.scoped,\n        Stream.runHead\n      )\n      const isInterruptible2 = yield* Effect.uninterruptible(\n        Effect.checkInterruptible(Effect.succeed)\n      ).pipe(Stream.scoped, Stream.runHead)\n      assertSome(isInterruptible1, true)\n      assertSome(isInterruptible2, false)\n    }))\n\n  it(\"unwrapScoped\", async () => {\n    const awaiter = Deferred.unsafeMake<void>(FiberId.none)\n    const program = Effect.gen(function*() {\n      const stream = (deferred: Deferred.Deferred<void, never>, ref: Ref.Ref<ReadonlyArray<string>>) =>\n        Effect.acquireRelease(\n          Ref.update(ref, (array) => [...array, \"acquire outer\"]),\n          () => Ref.update(ref, (array) => [...array, \"release outer\"])\n        ).pipe(\n          Effect.zipRight(Deferred.succeed(deferred, void 0)),\n          Effect.zipRight(Deferred.await(awaiter)),\n          Effect.zipRight(Effect.succeed(Stream.make(1, 2, 3))),\n          Stream.unwrapScoped\n        )\n      const ref = yield* Ref.make<ReadonlyArray<string>>([])\n      const deferred = yield* Deferred.make<void>()\n      const fiber = yield* stream(deferred, ref).pipe(Stream.runDrain, Effect.fork)\n      yield* Deferred.await(deferred)\n      yield* Fiber.interrupt(fiber)\n      return yield* Ref.get(ref)\n    })\n    const result = await Effect.runPromise(program)\n    await Effect.runPromise(Deferred.succeed(awaiter, void 0))\n    deepStrictEqual(result, [\"acquire outer\", \"release outer\"])\n  })\n\n  it.effect(\"preserves the scope\", () =>\n    Effect.gen(function*() {\n      const ref = yield* Ref.make(Array.empty<string>())\n      const scope = yield* Scope.make()\n      yield* Stream.make(1, 2).pipe(\n        Stream.flatMap((i) =>\n          Stream.fromEffect(Effect.acquireRelease(\n            Ref.update(ref, Array.append(`Acquire: ${i}`)),\n            () => Ref.update(ref, Array.append(`Release: ${i}`))\n          )), { bufferSize: 1, concurrency: \"unbounded\" }),\n        Stream.runDrain,\n        Scope.extend(scope)\n      )\n      const before = yield* Ref.getAndSet(ref, Array.empty())\n      yield* Scope.close(scope, Exit.void)\n      const after = yield* Ref.get(ref)\n      deepStrictEqual(before, [\"Acquire: 1\", \"Acquire: 2\"])\n      deepStrictEqual(after, [\"Release: 2\", \"Release: 1\"])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/sequencing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport * as Take from \"effect/Take\"\n\nconst withPermitsScoped = (permits: number) => (semaphore: Effect.Semaphore) =>\n  Effect.acquireRelease(\n    semaphore.take(permits),\n    (n) => semaphore.release(n)\n  )\n\ndescribe(\"Stream\", () => {\n  it.effect(\"branchAfter - switches streams\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunk(Chunk.range(0, 5)),\n        Stream.branchAfter(1, (values) => {\n          if (Equal.equals(values, Chunk.make(0))) {\n            return Stream.identity<number>()\n          }\n          throw new Error(\"should have branched after 0\")\n        }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"branchAfter - emits data if less than n elements are collected\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunk(Chunk.range(1, 5)),\n        Stream.branchAfter(6, (chunk) => Stream.prepend(Stream.identity<number>(), chunk)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"branchAfter - applies the new stream once on remaining upstream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromIterable(Chunk.range(1, 5)),\n        Stream.rechunk(2),\n        Stream.branchAfter(1, (chunk) => Stream.prepend(Stream.identity<number>(), chunk)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"execute\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      yield* (Stream.runDrain(Stream.execute(Ref.set(ref, Chunk.fromIterable([1])))))\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [1])\n    }))\n\n  it.effect(\"flatMap - deep flatMap stack safety\", () =>\n    Effect.gen(function*() {\n      const fib = (n: number): Stream.Stream<number> =>\n        n <= 1 ?\n          Stream.succeed(n) :\n          pipe(\n            fib(n - 1),\n            Stream.flatMap((a) =>\n              pipe(\n                fib(n - 2),\n                Stream.flatMap((b) => Stream.succeed(a + b))\n              )\n            )\n          )\n      const result = yield* (Stream.runCollect(fib(10)))\n      deepStrictEqual(Array.from(result), [55])\n    }))\n\n  it.effect(\"flatMap - left identity\", () =>\n    Effect.gen(function*() {\n      const f = (n: number) => Stream.succeed(n * 2)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(Stream.make(1), Stream.flatMap(f), Stream.runCollect),\n        result2: Stream.runCollect(f(1))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"flatMap - right identity\", () =>\n    Effect.gen(function*() {\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(Stream.make(1), Stream.flatMap((n) => Stream.make(n)), Stream.runCollect),\n        result2: Stream.runCollect(Stream.make(1))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"flatMap - associativity\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.range(0, 4)\n      const f = (n: number) => Stream.succeed(n * 2)\n      const g = (n: number) => Stream.succeed(String(n))\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.flatMap(f), Stream.flatMap(g), Stream.runCollect),\n        result2: pipe(stream, Stream.flatMap((n) => pipe(f(n), Stream.flatMap(g))), Stream.runCollect)\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"flatMap - inner finalizers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const push = (n: number) => Ref.update(ref, Chunk.append(n))\n      const latch = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Stream.make(\n          Stream.acquireRelease(push(1), () => push(1)),\n          Stream.fromEffect(push(2)),\n          pipe(\n            Stream.acquireRelease(push(3), () => push(3)),\n            Stream.crossRight(Stream.fromEffect(pipe(\n              Deferred.succeed(latch, void 0),\n              Effect.zipRight(Effect.never)\n            )))\n          )\n        ),\n        Stream.flatMap(identity),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [1, 1, 2, 3, 3])\n    }))\n\n  it.effect(\"flatMap - finalizer ordering #1\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<string>()))\n      const push = (message: string) => Ref.update(ref, Chunk.append(message))\n      const chunks = Chunk.make(Chunk.of(void 0), Chunk.of(void 0))\n      yield* pipe(\n        Stream.acquireRelease(push(\"open 1\"), () => push(\"close 1\")),\n        Stream.flatMap(() =>\n          pipe(\n            Stream.fromChunks(...chunks),\n            Stream.tap(() => push(\"use 2\")),\n            Stream.ensuring(push(\"close 2\")),\n            Stream.flatMap(() =>\n              pipe(\n                Stream.acquireRelease(push(\"open 3\"), () => push(\"close 3\")),\n                Stream.flatMap(() =>\n                  pipe(\n                    Stream.fromChunks(...chunks),\n                    Stream.tap(() => push(\"use 4\")),\n                    Stream.ensuring(push(\"close 4\"))\n                  )\n                )\n              )\n            )\n          )\n        ),\n        Stream.runDrain\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [\n        \"open 1\",\n        \"use 2\",\n        \"open 3\",\n        \"use 4\",\n        \"use 4\",\n        \"close 4\",\n        \"close 3\",\n        \"use 2\",\n        \"open 3\",\n        \"use 4\",\n        \"use 4\",\n        \"close 4\",\n        \"close 3\",\n        \"close 2\",\n        \"close 1\"\n      ])\n    }))\n\n  it.effect(\"flatMap - finalizer ordering #2\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<string>()))\n      const push = (message: string) => Ref.update(ref, Chunk.append(message))\n      const chunks = Chunk.make(Chunk.of(1), Chunk.of(2))\n      yield* pipe(\n        Stream.fromChunks(...chunks),\n        Stream.tap(() => push(\"use 1\")),\n        Stream.flatMap(() => Stream.acquireRelease(push(\"open 2\"), () => push(\"close 2\"))),\n        Stream.runDrain\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [\n        \"use 1\",\n        \"open 2\",\n        \"close 2\",\n        \"use 1\",\n        \"open 2\",\n        \"close 2\"\n      ])\n    }))\n\n  it.effect(\"flatMap - exit signal\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const inner = pipe(\n        Stream.acquireRelease(Effect.void, (_, exit) =>\n          Exit.match(exit, {\n            onFailure: () => Ref.set(ref, true),\n            onSuccess: () => Effect.void\n          })),\n        Stream.flatMap(() => Stream.fail(\"Ouch\"))\n      )\n      yield* pipe(\n        Stream.succeed(void 0),\n        Stream.flatMap(() => inner),\n        Stream.runDrain,\n        Effect.either\n      )\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"flatMap - finalizers are registered in the proper order\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const push = (n: number) => Ref.update(ref, Chunk.prepend(n))\n      yield* pipe(\n        Stream.finalizer(push(1)),\n        Stream.flatMap(() => Stream.finalizer(push(2))),\n        Stream.toPull,\n        Effect.flatten,\n        Effect.scoped\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [1, 2])\n    }))\n\n  it.effect(\"flatMap - early release finalizer concatenation is preserved\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<number>()))\n      const push = (n: number) => Ref.update(ref, Chunk.prepend(n))\n      const stream = pipe(\n        Stream.finalizer(push(1)),\n        Stream.flatMap(() => Stream.finalizer(push(2)))\n      )\n      const result = yield* pipe(\n        Scope.make(),\n        Effect.flatMap((scope) =>\n          pipe(\n            Scope.extend(scope)(Stream.toPull(stream)),\n            Effect.flatMap((pull) =>\n              pipe(\n                pull,\n                Effect.zipRight(Scope.close(scope, Exit.void)),\n                Effect.zipRight(Ref.get(ref))\n              )\n            )\n          )\n        )\n      )\n      deepStrictEqual(Array.from(result), [1, 2])\n    }))\n\n  it.effect(\"flatMapPar - guarantee ordering\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.fromIterable([1, 2, 3, 4, 5])\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.flatMap((n) => Stream.make(n, n)), Stream.runCollect),\n        result2: pipe(stream, Stream.flatMap((n) => Stream.make(n, n), { concurrency: 2 }), Stream.runCollect)\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"flatMapPar - consistency with flatMap\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.fromIterable([1, 2, 3, 4, 5])\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(\n          stream,\n          Stream.flatMap((n) => Stream.make(n, n)),\n          Stream.runCollect\n        ),\n        result2: pipe(\n          stream,\n          Stream.flatMap((n) => Stream.make(n, n), { concurrency: 100 }),\n          Stream.runCollect\n        )\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"flatMapPar - interruption propagation\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Stream.make(void 0),\n        Stream.flatMap(() =>\n          pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.zipRight(Effect.never),\n            Effect.onInterrupt(() => Ref.set(ref, true)),\n            Stream.fromEffect\n          ), { concurrency: 2 }),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"flatMap - inner errors interrupt all fibers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        Stream.make(\n          Stream.fromEffect(\n            pipe(\n              Deferred.succeed(latch, void 0),\n              Effect.zipRight(Effect.never),\n              Effect.onInterrupt(() => Ref.set(ref, true))\n            )\n          ),\n          Stream.fromEffect(\n            pipe(\n              Deferred.await(latch),\n              Effect.zipRight(Effect.fail(\"Ouch\"))\n            )\n          )\n        ),\n        Stream.flatMap(identity, { concurrency: 2 }),\n        Stream.runDrain,\n        Effect.either\n      )\n      const cancelled = yield* (Ref.get(ref))\n      assertTrue(cancelled)\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"flatMapPar - outer errors interrupt all fiberrs\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        Stream.make(void 0),\n        Stream.concat(Stream.fromEffect(pipe(\n          Deferred.await(latch),\n          Effect.zipRight(Effect.fail(\"Ouch\"))\n        ))),\n        Stream.flatMap(() =>\n          pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.zipRight(Effect.never),\n            Effect.onInterrupt(() => Ref.set(ref, true)),\n            Stream.fromEffect\n          ), { concurrency: 2 }),\n        Stream.runDrain,\n        Effect.either\n      )\n      const cancelled = yield* (Ref.get(ref))\n      assertTrue(cancelled)\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"flatMapPar - inner defects interrupt all fibers\", () =>\n    Effect.gen(function*() {\n      const defect = new Cause.RuntimeException(\"Ouch\")\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        Stream.make(\n          Stream.fromEffect(pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.zipRight(Effect.never),\n            Effect.onInterrupt(() => Ref.set(ref, true))\n          )),\n          Stream.fromEffect(pipe(\n            Deferred.await(latch),\n            Effect.zipRight(Effect.die(defect))\n          ))\n        ),\n        Stream.flatMap(identity, { concurrency: 2 }),\n        Stream.runDrain,\n        Effect.exit\n      )\n      const cancelled = yield* (Ref.get(ref))\n      assertTrue(cancelled)\n      deepStrictEqual(result, Exit.die(defect))\n    }))\n\n  it.effect(\"flatMapPar - outer defects interrupt all fibers\", () =>\n    Effect.gen(function*() {\n      const defect = new Cause.RuntimeException(\"Ouch\")\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        Stream.make(void 0),\n        Stream.concat(Stream.fromEffect(pipe(\n          Deferred.await(latch),\n          Effect.zipRight(Effect.die(defect))\n        ))),\n        Stream.flatMap(() =>\n          pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.zipRight(Effect.never),\n            Effect.onInterrupt(() => Ref.set(ref, true)),\n            Stream.fromEffect\n          ), { concurrency: 2 }),\n        Stream.runDrain,\n        Effect.exit\n      )\n      const cancelled = yield* (Ref.get(ref))\n      assertTrue(cancelled)\n      deepStrictEqual(result, Exit.die(defect))\n    }))\n\n  it.effect(\"flatMapPar - finalizer ordering\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<string>()))\n      const push = (message: string) => Ref.update(ref, Chunk.append(message))\n      const inner = Stream.acquireRelease(push(\"Inner Acquire\"), () => push(\"Inner Release\"))\n      yield* pipe(\n        Stream.acquireRelease(\n          pipe(\n            push(\"Outer Acquire\"),\n            Effect.as(inner)\n          ),\n          () => push(\"Outer Release\")\n        ),\n        Stream.flatMap(identity, { concurrency: 2 }),\n        Stream.runDrain\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [\n        \"Outer Acquire\",\n        \"Inner Acquire\",\n        \"Inner Release\",\n        \"Outer Release\"\n      ])\n    }))\n\n  it.effect(\"flatMapParSwitch - guarantee ordering no parallelism\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const semaphore = yield* (Effect.makeSemaphore(1))\n      yield* pipe(\n        Stream.make(1, 2, 3, 4),\n        Stream.flatMap((n) => {\n          if (n > 3) {\n            return pipe(\n              Stream.acquireRelease(Effect.void, () => Ref.set(ref, true)),\n              Stream.flatMap(() => Stream.empty)\n            )\n          }\n          return pipe(\n            Stream.scoped(withPermitsScoped(1)(semaphore)),\n            Stream.flatMap(() => Stream.never)\n          )\n        }, { concurrency: 1, switch: true }),\n        Stream.runDrain\n      )\n      const result = yield* (semaphore.withPermits(1)(Ref.get(ref)))\n      assertTrue(result)\n    }))\n\n  it.effect(\"flatMapParSwitch - guarantee ordering with parallelism\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const semaphore = yield* (Effect.makeSemaphore(4))\n      yield* pipe(\n        Stream.range(1, 12),\n        Stream.flatMap((n) => {\n          if (n > 8) {\n            return pipe(\n              Stream.acquireRelease(\n                Effect.void,\n                () => Ref.update(ref, (n) => n + 1)\n              ),\n              Stream.flatMap(() => Stream.empty)\n            )\n          }\n          return pipe(\n            Stream.scoped(withPermitsScoped(1)(semaphore)),\n            Stream.flatMap(() => Stream.never)\n          )\n        }, { concurrency: 4, switch: true }),\n        Stream.runDrain\n      )\n      const result = yield* pipe(\n        Ref.get(ref),\n        semaphore.withPermits(4)\n      )\n      strictEqual(result, 4)\n    }))\n\n  it.effect(\"flatMapParSwitch - short circuiting\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(Stream.never, Stream.make(1)),\n        Stream.flatMap(identity, { concurrency: 2, switch: true }),\n        Stream.take(1),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1])\n    }))\n\n  it.effect(\"flatMapParSwitch - interruption propagation\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const fiber = yield* pipe(\n        Stream.make(void 0),\n        Stream.flatMap(() =>\n          pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.zipRight(Effect.never),\n            Effect.onInterrupt(() => Ref.set(ref, true)),\n            Stream.fromEffect\n          ), { switch: true }),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(latch))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n\n  it.effect(\"flatMapParSwitch - inner errors interrupt all fibers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        Stream.make(\n          Stream.fromEffect(\n            pipe(\n              Deferred.succeed(latch, void 0),\n              Effect.zipRight(Effect.never),\n              Effect.onInterrupt(() => Ref.set(ref, true))\n            )\n          ),\n          Stream.fromEffect(\n            pipe(\n              Deferred.await(latch),\n              Effect.zipRight(Effect.fail(\"Ouch\"))\n            )\n          )\n        ),\n        Stream.flatMap(identity, { concurrency: 2, switch: true }),\n        Stream.runDrain,\n        Effect.either\n      )\n      const cancelled = yield* (Ref.get(ref))\n      assertTrue(cancelled)\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"flatMapParSwitch - outer errors interrupt all fibers\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        Stream.make(void 0),\n        Stream.concat(Stream.fromEffect(pipe(\n          Deferred.await(latch),\n          Effect.zipRight(Effect.fail(\"Ouch\"))\n        ))),\n        Stream.flatMap(() =>\n          pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.zipRight(Effect.never),\n            Effect.onInterrupt(() => Ref.set(ref, true)),\n            Stream.fromEffect\n          ), { concurrency: 2, switch: true }),\n        Stream.runDrain,\n        Effect.either\n      )\n      const cancelled = yield* (Ref.get(ref))\n      assertTrue(cancelled)\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"flatMapParSwitch - inner defects interrupt all fibers\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        Stream.make(\n          Stream.fromEffect(\n            pipe(\n              Deferred.succeed(latch, void 0),\n              Effect.zipRight(Effect.never),\n              Effect.onInterrupt(() => Ref.set(ref, true))\n            )\n          ),\n          Stream.fromEffect(\n            pipe(\n              Deferred.await(latch),\n              Effect.zipRight(Effect.die(error))\n            )\n          )\n        ),\n        Stream.flatMap(identity, { concurrency: 2, switch: true }),\n        Stream.runDrain,\n        Effect.exit\n      )\n      const cancelled = yield* (Ref.get(ref))\n      assertTrue(cancelled)\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"flatMapParSwitch - outer defects interrupt all fibers\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"Ouch\")\n      const ref = yield* (Ref.make(false))\n      const latch = yield* (Deferred.make<void>())\n      const result = yield* pipe(\n        Stream.make(void 0),\n        Stream.concat(Stream.fromEffect(pipe(\n          Deferred.await(latch),\n          Effect.zipRight(Effect.die(error))\n        ))),\n        Stream.flatMap(() =>\n          pipe(\n            Deferred.succeed(latch, void 0),\n            Effect.zipRight(Effect.never),\n            Effect.onInterrupt(() => Ref.set(ref, true)),\n            Stream.fromEffect\n          ), { concurrency: 2, switch: true }),\n        Stream.runDrain,\n        Effect.exit\n      )\n      const cancelled = yield* (Ref.get(ref))\n      assertTrue(cancelled)\n      deepStrictEqual(result, Exit.die(error))\n    }))\n\n  it.effect(\"flatMapParSwitch - finalizer ordering\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<string>()))\n      const push = (message: string) => Ref.update(ref, Chunk.append(message))\n      const inner = Stream.acquireRelease(push(\"Inner Acquire\"), () => push(\"Inner Release\"))\n      yield* pipe(\n        Stream.acquireRelease(\n          pipe(\n            push(\"Outer Acquire\"),\n            Effect.as(inner)\n          ),\n          () => push(\"Outer Release\")\n        ),\n        Stream.flatMap(identity, { concurrency: 2, switch: true }),\n        Stream.runDrain\n      )\n      const result = yield* (Ref.get(ref))\n      deepStrictEqual(Array.from(result), [\n        \"Outer Acquire\",\n        \"Inner Acquire\",\n        \"Inner Release\",\n        \"Outer Release\"\n      ])\n    }))\n\n  it.effect(\"flattenChunks\", () =>\n    Effect.gen(function*() {\n      const chunks = Chunk.make(Chunk.make(1, 2), Chunk.make(3, 4), Chunk.make(5, 6))\n      const result = yield* pipe(\n        Stream.fromChunks(chunks),\n        Stream.flattenChunks,\n        Stream.chunks,\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        Array.from(chunks).map((chunk) => Array.from(chunk))\n      )\n    }))\n\n  it.effect(\"flattenExitOption - happy path\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(0, 9),\n        Stream.toQueue({ capacity: 1 }),\n        Effect.flatMap((queue) =>\n          pipe(\n            Stream.fromQueue(queue),\n            Stream.map((take) => take.exit),\n            Stream.flattenExitOption,\n            Stream.runCollect\n          )\n        ),\n        Effect.scoped\n      )\n      deepStrictEqual(\n        Array.from(Chunk.flatten(result)),\n        Array.from(Chunk.range(0, 9))\n      )\n    }))\n\n  it.effect(\"flattenExitOption - failure\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.range(0, 9),\n        Stream.concat(Stream.fail(error)),\n        Stream.toQueue({ capacity: 1 }),\n        Effect.flatMap((queue) =>\n          pipe(\n            Stream.fromQueue(queue),\n            Stream.map((take) => take.exit),\n            Stream.flattenExitOption,\n            Stream.runCollect\n          )\n        ),\n        Effect.scoped,\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(error))\n    }))\n\n  it.effect(\"flattenIterables\", () =>\n    Effect.gen(function*() {\n      const iterables = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n      const result = yield* pipe(\n        Stream.fromIterable(iterables),\n        Stream.flattenIterables,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), iterables.flatMap(identity))\n    }))\n\n  it.effect(\"flattenTake - happy path\", () =>\n    Effect.gen(function*() {\n      const chunks = Chunk.make(Chunk.range(0, 3), Chunk.range(4, 8))\n      const result = yield* pipe(\n        Stream.fromChunks(...chunks),\n        Stream.mapChunks((chunk) => Chunk.of(Take.chunk(chunk))),\n        Stream.flattenTake,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), Array.from(Chunk.flatten(chunks)))\n    }))\n\n  it.effect(\"flattenTake - stop collecting on Exit.Failure\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(\n          Take.chunk(Chunk.make(1, 2)),\n          Take.of(3),\n          Take.end\n        ),\n        Stream.flattenTake,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n    }))\n\n  it.effect(\"flattenTake - works with empty chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(\n          Take.chunk(Chunk.empty<number>()),\n          Take.chunk(Chunk.empty<number>())\n        ),\n        Stream.flattenTake,\n        Stream.runCollect\n      )\n      assertTrue(Chunk.isEmpty(result))\n    }))\n\n  it.effect(\"flattenTake - works with empty streams\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromIterable<Take.Take<never>>([]),\n        Stream.flattenTake,\n        Stream.runCollect\n      )\n      assertTrue(Chunk.isEmpty(result))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/sliding.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"sliding - returns a sliding window\", () =>\n    Effect.gen(function*() {\n      const stream0 = Stream.fromChunks(\n        Chunk.empty<number>(),\n        Chunk.make(1),\n        Chunk.empty<number>(),\n        Chunk.make(2, 3, 4, 5)\n      )\n      const stream1 = pipe(\n        Stream.empty,\n        Stream.concat(Stream.make(1)),\n        Stream.concat(Stream.empty),\n        Stream.concat(Stream.make(2)),\n        Stream.concat(Stream.make(3, 4, 5))\n      )\n      const stream2 = pipe(\n        Stream.make(1),\n        Stream.concat(Stream.empty),\n        Stream.concat(Stream.make(2)),\n        Stream.concat(Stream.empty),\n        Stream.concat(Stream.make(3, 4, 5))\n      )\n      const stream3 = pipe(\n        Stream.fromChunk(Chunk.make(1)),\n        Stream.concat(Stream.fromChunk(Chunk.make(2))),\n        Stream.concat(Stream.make(3, 4, 5))\n      )\n      const result1 = yield* pipe(\n        Stream.make(1, 2, 3, 4, 5),\n        Stream.sliding(2),\n        Stream.runCollect\n      )\n      const result2 = yield* pipe(\n        stream0,\n        Stream.sliding(2),\n        Stream.runCollect\n      )\n      const result3 = yield* pipe(\n        stream1,\n        Stream.sliding(2),\n        Stream.runCollect\n      )\n      const result4 = yield* pipe(\n        stream2,\n        Stream.sliding(2),\n        Stream.runCollect\n      )\n      const result5 = yield* pipe(\n        stream3,\n        Stream.sliding(2),\n        Stream.runCollect\n      )\n      const expected = [[1, 2], [2, 3], [3, 4], [4, 5]]\n      deepStrictEqual(Array.from(result1).map((chunk) => Array.from(chunk)), expected)\n      deepStrictEqual(Array.from(result2).map((chunk) => Array.from(chunk)), expected)\n      deepStrictEqual(Array.from(result3).map((chunk) => Array.from(chunk)), expected)\n      deepStrictEqual(Array.from(result4).map((chunk) => Array.from(chunk)), expected)\n      deepStrictEqual(Array.from(result5).map((chunk) => Array.from(chunk)), expected)\n    }))\n\n  it.effect(\"sliding - returns all elements if chunkSize is greater than the size of the stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(1, 5),\n        Stream.sliding(6),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result).map((chunk) => Array.from(chunk)), [[1, 2, 3, 4, 5]])\n    }))\n\n  it.effect(\"sliding - is mostly equivalent to ZStream#grouped when stepSize and chunkSize are equal\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.range(1, 5)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.slidingSize(3, 3), Stream.runCollect),\n        result2: pipe(stream, Stream.grouped(3), Stream.runCollect)\n      }))\n      deepStrictEqual(\n        Array.from(result1).map((chunk) => Array.from(chunk)),\n        Array.from(result2).map((chunk) => Array.from(chunk))\n      )\n    }))\n\n  it.effect(\"sliding - fails if upstream produces an error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.concat(Stream.fail(\"Ouch\")),\n        Stream.concat(Stream.make(4, 5)),\n        Stream.sliding(2),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"sliding - should return an empty chunk when the stream is empty\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Stream.empty, Stream.sliding(2), Stream.runCollect)\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"sliding - emits elements properly when a failure occurs\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(Chunk.empty<Chunk.Chunk<number>>()))\n      const streamChunks = Stream.fromChunks(\n        Chunk.range(1, 4),\n        Chunk.range(5, 7),\n        Chunk.of(8)\n      )\n      const stream = pipe(\n        streamChunks,\n        Stream.concat(Stream.fail(\"Ouch\")),\n        Stream.slidingSize(3, 3)\n      )\n      const either = yield* pipe(\n        stream,\n        Stream.mapEffect((chunk) => Ref.update(ref, Chunk.append(chunk))),\n        Stream.runCollect,\n        Effect.either\n      )\n      const result = yield* (Ref.get(ref))\n      assertLeft(either, \"Ouch\")\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2, 3], [4, 5, 6], [7, 8]]\n      )\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/splitting.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as fc from \"effect/FastCheck\"\nimport { pipe } from \"effect/Function\"\nimport * as Stream from \"effect/Stream\"\n\nconst weirdStringForSplitLines: fc.Arbitrary<ReadonlyArray<string>> = fc.array(\n  fc.string().filter((s) => s !== \"\\n\" && s !== \"\\r\")\n).map((strings) => {\n  if (strings.length > 0 && strings[strings.length - 1] === \"\") {\n    return [...strings, \"a\"]\n  }\n  return strings\n})\n\nconst testSplitLines = (\n  input: ReadonlyArray<Chunk.Chunk<string>>\n): Effect.Effect<readonly [ReadonlyArray<string>, ReadonlyArray<string>]> => {\n  const str = input.flatMap((chunk) => Chunk.toReadonlyArray(chunk).join(\"\")).join(\"\")\n  const expected = str.split(/\\r?\\n/)\n  return pipe(\n    Stream.fromChunks(...input),\n    Stream.splitLines,\n    Stream.runCollect,\n    Effect.map((chunk) => [expected, Chunk.toReadonlyArray(chunk)] as const)\n  )\n}\n\ndescribe(\"Stream\", () => {\n  it.effect(\"split - should split properly\", () =>\n    Effect.gen(function*() {\n      const chunks = Chunk.make(\n        Chunk.range(1, 2),\n        Chunk.range(3, 4),\n        Chunk.range(5, 6),\n        Chunk.make(7, 8, 9),\n        Chunk.of(10)\n      )\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(\n          Stream.range(0, 9),\n          Stream.split((n) => n % 4 === 0),\n          Stream.runCollect\n        ),\n        result2: pipe(\n          Stream.fromChunks(...chunks),\n          Stream.split((n) => n % 3 === 0),\n          Stream.runCollect\n        )\n      }))\n      deepStrictEqual(\n        Array.from(result1).map((chunk) => Array.from(chunk)),\n        [[1, 2, 3], [5, 6, 7], [9]]\n      )\n      deepStrictEqual(\n        Array.from(result2).map((chunk) => Array.from(chunk)),\n        [[1, 2], [4, 5], [7, 8], [10]]\n      )\n    }))\n\n  it.effect(\"split - is equivalent to identity when the predicate is not satisfied\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.range(1, 10)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.split((n) => n % 11 === 0), Stream.runCollect),\n        result2: pipe(\n          Stream.runCollect(stream),\n          Effect.map((chunk) => pipe(Chunk.of(chunk), Chunk.filter(Chunk.isNonEmpty)))\n        )\n      }))\n      deepStrictEqual(\n        Array.from(result1).map((chunk) => Array.from(chunk)),\n        [Array.from(Chunk.range(1, 10))]\n      )\n      deepStrictEqual(\n        Array.from(result1).map((chunk) => Array.from(chunk)),\n        Array.from(result2).map((chunk) => Array.from(chunk))\n      )\n    }))\n\n  it.effect(\"split - should output empty chunk when stream is empty\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.split((n: number) => n % 11 === 0),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"splitOnChunk - consecutive delimiter yields empty Chunk\", () =>\n    Effect.gen(function*() {\n      const input = Stream.make(\n        Chunk.make(1, 2),\n        Chunk.of(1),\n        Chunk.make(2, 1, 2, 3, 1, 2),\n        Chunk.make(1, 2)\n      )\n      const splitSequence = Chunk.make(1, 2)\n      const result = yield* pipe(\n        Stream.flattenChunks(input),\n        Stream.splitOnChunk(splitSequence),\n        Stream.map(Chunk.size),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0, 0, 0, 1, 0])\n    }))\n\n  it.effect(\"splitOnChunk - preserves data\", () =>\n    Effect.gen(function*() {\n      const splitSequence = Chunk.make(0, 1)\n      const stream = Stream.make(1, 1, 1, 1, 1, 1)\n      const result = yield* pipe(\n        stream,\n        Stream.splitOnChunk(splitSequence),\n        Stream.runCollect,\n        Effect.map(Chunk.flatten)\n      )\n      deepStrictEqual(Array.from(result), [1, 1, 1, 1, 1, 1])\n    }))\n\n  it.effect(\"splitOnChunk - handles leftovers\", () =>\n    Effect.gen(function*() {\n      const splitSequence = Chunk.make(0, 1)\n      const result = yield* pipe(\n        Stream.fromChunks(Chunk.make(1, 0, 2, 0, 1, 2), Chunk.of(2)),\n        Stream.splitOnChunk(splitSequence),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 0, 2], [2, 2]]\n      )\n    }))\n\n  it.effect(\"splitOnChunk - works\", () =>\n    Effect.gen(function*() {\n      const splitSequence = Chunk.make(0, 1)\n      const result = yield* pipe(\n        Stream.make(1, 2, 0, 1, 3, 4, 0, 1, 5, 6, 5, 6),\n        Stream.splitOnChunk(splitSequence),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2], [3, 4], [5, 6, 5, 6]]\n      )\n    }))\n\n  it.effect(\"splitOnChunk - works from Chunks\", () =>\n    Effect.gen(function*() {\n      const splitSequence = Chunk.make(0, 1)\n      const result = yield* pipe(\n        Stream.fromChunks(\n          Chunk.make(1, 2),\n          splitSequence,\n          Chunk.make(3, 4),\n          splitSequence,\n          Chunk.make(5, 6),\n          Chunk.make(5, 6)\n        ),\n        Stream.splitOnChunk(splitSequence),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2], [3, 4], [5, 6, 5, 6]]\n      )\n    }))\n\n  it.effect(\"splitOnChunk - single delimiter edge case\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(0),\n        Stream.splitOnChunk(Chunk.make(0)),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[]]\n      )\n    }))\n\n  it.effect(\"splitOnChunk - no delimiter in data\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(Chunk.make(1, 2), Chunk.make(1, 2), Chunk.make(1, 2)),\n        Stream.splitOnChunk(Chunk.make(1, 1)),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1, 2, 1, 2, 1, 2]]\n      )\n    }))\n\n  it.effect(\"splitOnChunk - delimiter on the boundary\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(Chunk.make(1, 2), Chunk.make(1, 2)),\n        Stream.splitOnChunk(Chunk.make(2, 1)),\n        Stream.runCollect\n      )\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[1], [2]]\n      )\n    }))\n\n  it(\"splitLines - preserves data\", () =>\n    fc.assert(fc.asyncProperty(weirdStringForSplitLines, async (lines) => {\n      const data = lines.join(\"\\n\")\n      const program = pipe(\n        Stream.fromChunk(Chunk.of(data)),\n        Stream.splitLines,\n        Stream.runCollect,\n        Effect.map((chunk) => Chunk.toReadonlyArray(chunk).join(\"\\n\"))\n      )\n      const result = await Effect.runPromise(program)\n      strictEqual(result, data)\n    })))\n\n  // it(\"splitLines - preserves data in chunks\", () =>\n  //   fc.asyncProperty(fc.property(weirdStringForSplitLines), async (lines) => {\n  //     const data =\n  //   })\n  // )\n  // //   test(\"preserves data in chunks\") {\n  // //     check(weirdStringGenForSplitLines) { xs =>\n  // //       val data = Chunk.fromIterable(xs.sliding(2, 2).toList.map(_.mkString(\"\\n\")))\n  // //       testSplitLines(Seq(data))\n  // //     }\n  // //   },\n\n  it.effect(\"splitLines - handles leftovers\", () =>\n    Effect.gen(function*() {\n      const chunks = [Chunk.of(\"abc\\nbc\")]\n      const [expected, result] = yield* (testSplitLines(chunks))\n      deepStrictEqual(expected, result)\n    }))\n\n  it.effect(\"splitLines - handles leftovers 2\", () =>\n    Effect.gen(function*() {\n      const chunks = [\n        Chunk.make(\"aa\", \"bb\"),\n        Chunk.make(\"\\nbbc\\n\", \"ddb\", \"bd\"),\n        Chunk.make(\"abc\", \"\\n\"),\n        Chunk.of(\"abc\")\n      ]\n      const [expected, result] = yield* (testSplitLines(chunks))\n      deepStrictEqual(expected, result)\n    }))\n\n  it.effect(\"splitLines - aggregates chunks\", () =>\n    Effect.gen(function*() {\n      const chunks = [Chunk.make(\"abc\", \"\\n\", \"bc\", \"\\n\", \"bcd\", \"bcd\")]\n      const [expected, result] = yield* (testSplitLines(chunks))\n      deepStrictEqual(expected, result)\n    }))\n\n  it.effect(\"splitLines - single newline edge case\", () =>\n    Effect.gen(function*() {\n      const chunks = [Chunk.of(\"\\n\")]\n      const [, result] = yield* (testSplitLines(chunks))\n      // JavaScript arrays split `\"\\n\"` into `[\"\", \"\"]`, so we manually assert\n      // that the output should be the empty string here\n      deepStrictEqual([\"\"], result)\n    }))\n\n  it.effect(\"splitLines - no newlines\", () =>\n    Effect.gen(function*() {\n      const chunks = [Chunk.make(\"abc\", \"abc\", \"abc\")]\n      const [expected, result] = yield* (testSplitLines(chunks))\n      deepStrictEqual(expected, result)\n    }))\n\n  it.effect(\"splitLines - \\\\r\\\\n on the boundary\", () =>\n    Effect.gen(function*() {\n      const chunks = [Chunk.make(\"abc\\r\", \"\\nabc\")]\n      const [expected, result] = yield* (testSplitLines(chunks))\n      deepStrictEqual(expected, result)\n    }))\n\n  it.effect(\"splitLines - ZIO issue #6360\", () =>\n    Effect.gen(function*() {\n      const chunks = [Chunk.make(\"AAAAABBBB#\\r\\r\\r\\n\", \"test\")]\n      const [_, result] = yield* (testSplitLines(chunks))\n      deepStrictEqual([\"AAAAABBBB#\\r\\r\", \"test\"], result)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/streamable.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as Stream from \"effect/Stream\"\nimport * as Streamable from \"effect/Streamable\"\n\ndescribe(\"Streamable\", () => {\n  it.effect(\n    \"allows creating custom Stream types\",\n    () =>\n      Effect.gen(function*() {\n        class MyStream extends Streamable.Class<number> {\n          toStream() {\n            return Stream.fromIterable([1, 2, 3])\n          }\n        }\n        const stream = new MyStream()\n\n        const values = Array.from(yield* Stream.runCollect(stream))\n\n        deepStrictEqual(values, [1, 2, 3])\n      })\n  )\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/taking.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { constFalse, pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"take\", () =>\n    Effect.gen(function*() {\n      const take = 3\n      const stream = Stream.range(1, 5)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.take(take), Stream.runCollect),\n        result2: pipe(Stream.runCollect(stream), Effect.map(Chunk.take(take)))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"take - short circuits\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const stream = pipe(\n        Stream.make(1),\n        Stream.concat(Stream.drain(Stream.fromEffect(Ref.set(ref, true)))),\n        Stream.take(0)\n      )\n      yield* (Stream.runDrain(stream))\n      const result = yield* (Ref.get(ref))\n      assertFalse(result)\n    }))\n\n  it.effect(\"take - taking 0 short circuits\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(Stream.never, Stream.take(0), Stream.runCollect)\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"take - taking 1 short circuits\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.concat(Stream.never),\n        Stream.take(1),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1])\n    }))\n\n  it.effect(\"takeRight\", () =>\n    Effect.gen(function*() {\n      const take = 3\n      const stream = Stream.range(1, 5)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.takeRight(take), Stream.runCollect),\n        result2: pipe(Stream.runCollect(stream), Effect.map(Chunk.takeRight(take)))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"takeUntil\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.range(1, 5)\n      const f = (n: number) => n % 3 === 0\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.takeUntil(f), Stream.runCollect),\n        result2: pipe(\n          Stream.runCollect(stream),\n          Effect.map((chunk) =>\n            pipe(\n              chunk,\n              Chunk.takeWhile((a) => !f(a)),\n              Chunk.appendAll(pipe(chunk, Chunk.dropWhile((a) => !f(a)), Chunk.take(1)))\n            )\n          )\n        )\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"takeUntilEffect\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.range(1, 5)\n      const f = (n: number) => Effect.succeed(n % 3 === 0)\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.takeUntilEffect(f), Stream.runCollect),\n        result2: pipe(\n          Stream.runCollect(stream),\n          Effect.flatMap((chunk) =>\n            pipe(\n              chunk,\n              Effect.takeWhile((a) => Effect.negate(f(a))),\n              Effect.map(Chunk.unsafeFromArray),\n              Effect.zipWith(\n                pipe(\n                  chunk,\n                  Effect.dropWhile((a) => Effect.negate(f(a))),\n                  Effect.map(Chunk.unsafeFromArray),\n                  Effect.map(Chunk.take(1))\n                ),\n                (chunk1, chunk2) => Chunk.appendAll(chunk1, chunk2)\n              )\n            )\n          )\n        )\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"takeUntilEffect - laziness on chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.takeUntilEffect((n) =>\n          n === 2 ?\n            Effect.fail(\"boom\") :\n            Effect.succeed(false)\n        ),\n        Stream.either,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [Either.right(1), Either.left(\"boom\")])\n    }))\n\n  it.effect(\"takeWhile\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.range(1, 5)\n      const f = (n: number) => n <= 3\n      const { result1, result2 } = yield* (Effect.all({\n        result1: pipe(stream, Stream.takeWhile(f), Stream.runCollect),\n        result2: pipe(Stream.runCollect(stream), Effect.map(Chunk.takeWhile(f)))\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"takeWhile - does not stop when hitting an empty chunk (ZIO #4272)\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(Chunk.of(1), Chunk.of(2), Chunk.of(3)),\n        Stream.mapChunks(Chunk.flatMap((n) =>\n          n === 2 ?\n            Chunk.empty<number>() :\n            Chunk.of(n)\n        )),\n        Stream.takeWhile((n) => n !== 4),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 3])\n    }))\n\n  it.effect(\"takeWhile - short circuits\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.concat(Stream.fail(\"Ouch\")),\n        Stream.takeWhile(constFalse),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/tapping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"tap\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const result = yield* pipe(\n        Stream.make(1, 1),\n        Stream.tap((i) => Ref.update(ref, (n) => i + n)),\n        Stream.runCollect\n      )\n      const sum = yield* (Ref.get(ref))\n      strictEqual(sum, 2)\n      deepStrictEqual(Array.from(result), [1, 1])\n    }))\n\n  it.effect(\"tap - laziness on chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.tap((n) => pipe(Effect.fail(\"error\"), Effect.when(() => n === 3))),\n        Stream.either,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\n        Either.right(1),\n        Either.right(2),\n        Either.left(\"error\")\n      ])\n    }))\n\n  it.effect(\"tapBoth - just tap values\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const values = Chunk.make(1, 1)\n      const result = yield* pipe(\n        Stream.fromChunk(values),\n        Stream.tapBoth({\n          onSuccess: (v) => Ref.update(ref, (_) => _ + v),\n          onFailure: (e) => Effect.die(`Unexpected attempt to tap an error ${e}`)\n        }),\n        Stream.runCollect\n      )\n\n      deepStrictEqual(Array.from(result), Array.from(values))\n      strictEqual(yield* (Ref.get(ref)), 2)\n    }))\n\n  it.effect(\"tapBoth - just tap an error\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(\"\"))\n      const result = yield* pipe(\n        Stream.fail(\"Ouch\"),\n        Stream.tapBoth({\n          onSuccess: (v) => Effect.die(`Unexpected attempt to tap a value ${v}`),\n          onFailure: (e) => Ref.update(ref, (_) => _ + e)\n        }),\n        Stream.runCollect,\n        Effect.either\n      )\n\n      assertLeft(result, \"Ouch\")\n      strictEqual(yield* (Ref.get(ref)), \"Ouch\")\n    }))\n\n  it.effect(\"tapBoth - tap values and then error\", () =>\n    Effect.gen(function*() {\n      const error = yield* (Ref.make(\"\"))\n      const sum = yield* (Ref.make(0))\n      const values = Chunk.make(1, 1)\n      const result = yield* pipe(\n        Stream.fromChunk(values),\n        Stream.concat(Stream.fail(\"Ouch\")),\n        Stream.tapBoth({\n          onSuccess: (v) => Ref.update(sum, (_) => _ + v),\n          onFailure: (e) => Ref.update(error, (_) => _ + e)\n        }),\n        Stream.runCollect,\n        Effect.either\n      )\n\n      assertLeft(result, \"Ouch\")\n      strictEqual(yield* (Ref.get(error)), \"Ouch\")\n      strictEqual(yield* (Ref.get(sum)), 2)\n    }))\n\n  it.effect(\"tapBoth - tap chunks lazily\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.tapBoth({\n          onSuccess: (n) =>\n            pipe(\n              Effect.fail(\"error\"),\n              Effect.when(() => n === 3)\n            ),\n          onFailure: () => Effect.void\n        }),\n        Stream.either,\n        Stream.runCollect\n      )\n\n      deepStrictEqual(Array.from(result), [\n        Either.right(1),\n        Either.right(2),\n        Either.left(\"error\")\n      ])\n    }))\n\n  it.effect(\"tapError\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(\"\"))\n      const result = yield* pipe(\n        Stream.make(1, 1),\n        Stream.concat(Stream.fail(\"Ouch\")),\n        Stream.tapError((e) => Ref.update(ref, (s) => s + e)),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"tapSink - sink that is done after stream\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const sink = Sink.forEach((i: number) => Ref.update(ref, (n) => i + n))\n      const result = yield* pipe(\n        Stream.make(1, 1, 2, 3, 5, 8),\n        Stream.tapSink(sink),\n        Stream.runCollect\n      )\n      const sum = yield* (Ref.get(ref))\n      strictEqual(sum, 20)\n      deepStrictEqual(Array.from(result), [1, 1, 2, 3, 5, 8])\n    }))\n\n  it.effect(\"tapSink - sink that is done before stream\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const sink = pipe(\n        Sink.take<number>(3),\n        Sink.map(Chunk.reduce(0, (x, y) => x + y)),\n        Sink.mapEffect((i) => Ref.update(ref, (n) => n + i))\n      )\n      const result = yield* pipe(\n        Stream.make(1, 1, 2, 3, 5, 8),\n        Stream.rechunk(1),\n        Stream.tapSink(sink),\n        Stream.runCollect\n      )\n      const sum = yield* (Ref.get(ref))\n      strictEqual(sum, 4)\n      deepStrictEqual(Array.from(result), [1, 1, 2, 3, 5, 8])\n    }))\n\n  it.effect(\"tapSink - sink that fails before stream\", () =>\n    Effect.gen(function*() {\n      const sink = Sink.fail(\"error\")\n      const result = yield* pipe(\n        Stream.never,\n        Stream.tapSink(sink),\n        Stream.runCollect,\n        Effect.flip\n      )\n      strictEqual(result, \"error\")\n    }))\n\n  it.effect(\"tapSink - does not read ahead\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(0))\n      const sink = Sink.forEach((i: number) => Ref.update(ref, (n) => i + n))\n      yield* pipe(\n        Stream.make(1, 2, 3, 4, 5),\n        Stream.rechunk(1),\n        Stream.forever,\n        Stream.tapSink(sink),\n        Stream.take(3),\n        Stream.runDrain\n      )\n      const result = yield* (Ref.get(ref))\n      strictEqual(result, 6)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/throttling.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFailure, assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Clock from \"effect/Clock\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Queue from \"effect/Queue\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\nimport { chunkCoordination } from \"../utils/coordination.js\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"throttleEnforce - free elements\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4),\n        Stream.throttle({ cost: () => 0, units: 0, duration: Duration.infinity, strategy: \"enforce\" }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"throttleEnforce - no bandwidth\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4),\n        Stream.throttle({ cost: () => 1, units: 0, duration: Duration.infinity, strategy: \"enforce\" }),\n        Stream.runCollect\n      )\n      assertTrue(Chunk.isEmpty(result))\n    }))\n\n  it.effect(\"throttleEnforce - refill bucket tokens\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(\n        Stream.fromSchedule(Schedule.spaced(Duration.millis(100))),\n        Stream.take(10),\n        Stream.throttle({ cost: () => 1, units: 1, duration: Duration.millis(200), strategy: \"enforce\" }),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* TestClock.adjust(Duration.seconds(1))\n      const result = yield* Fiber.join(fiber)\n      deepStrictEqual(Array.from(result), [0, 2, 4, 6, 8])\n    }))\n\n  it.effect(\"throttleShape\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (Queue.bounded<number>(10))\n      const fiber = yield* pipe(\n        Stream.fromQueue(queue),\n        Stream.throttle({\n          strategy: \"shape\",\n          cost: Chunk.reduce(0, (x, y) => x + y),\n          units: 1,\n          duration: Duration.seconds(1)\n        }),\n        Stream.toPull,\n        Effect.flatMap((pull) =>\n          Effect.gen(function*() {\n            yield* (Queue.offer(queue, 1))\n            const result1 = yield* pull\n            yield* (Queue.offer(queue, 2))\n            const result2 = yield* pull\n            yield* (Effect.sleep(Duration.seconds(4)))\n            yield* (Queue.offer(queue, 3))\n            const result3 = yield* pull\n            return [Array.from(result1), Array.from(result2), Array.from(result3)] as const\n          })\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.seconds(8)))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(result, [[1], [2], [3]])\n    }))\n\n  it.effect(\"throttleShape - infinite bandwidth\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (Queue.bounded<number>(10))\n      const result = yield* pipe(\n        Stream.fromQueue(queue),\n        Stream.throttle({\n          strategy: \"shape\",\n          cost: () => 100_000,\n          units: 1,\n          duration: Duration.zero\n        }),\n        Stream.toPull,\n        Effect.flatMap((pull) =>\n          Effect.gen(function*() {\n            yield* (Queue.offer(queue, 1))\n            const result1 = yield* pull\n            yield* (Queue.offer(queue, 2))\n            const result2 = yield* pull\n            const elapsed = yield* (Clock.currentTimeMillis)\n            return [Array.from(result1), Array.from(result2), elapsed] as const\n          })\n        ),\n        Effect.scoped\n      )\n      deepStrictEqual(result, [[1], [2], 0])\n    }))\n\n  it.effect(\"throttleShape - with burst\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (Queue.bounded<number>(10))\n      const fiber = yield* pipe(\n        Stream.fromQueue(queue),\n        Stream.throttle({\n          strategy: \"shape\",\n          cost: Chunk.reduce(0, (x, y) => x + y),\n          units: 1,\n          duration: Duration.seconds(1),\n          burst: 2\n        }),\n        Stream.toPull,\n        Effect.flatMap((pull) =>\n          Effect.gen(function*() {\n            yield* (Queue.offer(queue, 1))\n            const result1 = yield* pull\n            yield* (TestClock.adjust(Duration.seconds(2)))\n            yield* (Queue.offer(queue, 2))\n            const result2 = yield* pull\n            yield* (TestClock.adjust(Duration.seconds(4)))\n            yield* (Queue.offer(queue, 3))\n            const result3 = yield* pull\n            return [Array.from(result1), Array.from(result2), Array.from(result3)] as const\n          })\n        ),\n        Effect.scoped,\n        Effect.fork\n      )\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(result, [[1], [2], [3]])\n    }))\n\n  it.effect(\"throttleShape - free elements\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4),\n        Stream.throttle({\n          strategy: \"shape\",\n          cost: () => 0,\n          units: 1,\n          duration: Duration.infinity\n        }),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4])\n    }))\n\n  it.effect(\"debounce - should drop earlier chunks within waitTime\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* (chunkCoordination([\n        Chunk.of(1),\n        Chunk.make(3, 4),\n        Chunk.of(5),\n        Chunk.make(6, 7)\n      ]))\n      const stream = pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.filterMapWhile(Exit.match({\n          onSuccess: Option.some,\n          onFailure: Option.none\n        })),\n        Stream.debounce(Duration.seconds(1)),\n        Stream.tap(() => coordination.proceed)\n      )\n      const fiber = yield* pipe(stream, Stream.runCollect, Effect.fork)\n      yield* (Effect.fork(coordination.offer))\n      yield* pipe(\n        Effect.sleep(Duration.millis(500)),\n        Effect.zipRight(coordination.offer),\n        Effect.fork\n      )\n      yield* pipe(\n        Effect.sleep(Duration.seconds(2)),\n        Effect.zipRight(coordination.offer),\n        Effect.fork\n      )\n      yield* pipe(\n        Effect.sleep(Duration.millis(2500)),\n        Effect.zipRight(coordination.offer),\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.millis(3500)))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[3, 4], [6, 7]]\n      )\n    }))\n\n  it.effect(\"debounce - should take latest chunk within waitTime\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* (chunkCoordination([\n        Chunk.make(1, 2),\n        Chunk.make(3, 4),\n        Chunk.make(5, 6)\n      ]))\n      const stream = pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.filterMapWhile(Exit.match({ onSuccess: Option.some, onFailure: Option.none })),\n        Stream.debounce(Duration.seconds(1)),\n        Stream.tap(() => coordination.proceed)\n      )\n      const fiber = yield* pipe(stream, Stream.runCollect, Effect.fork)\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(coordination.offer),\n        Effect.zipRight(coordination.offer)\n      )\n      yield* (TestClock.adjust(Duration.seconds(1)))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[5, 6]]\n      )\n    }))\n\n  it.effect(\"debounce - should work properly with parallelization\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* (chunkCoordination([\n        Chunk.of(1),\n        Chunk.of(2),\n        Chunk.of(3)\n      ]))\n      const stream = pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.filterMapWhile(Exit.match({ onSuccess: Option.some, onFailure: Option.none })),\n        Stream.debounce(Duration.seconds(1)),\n        Stream.tap(() => coordination.proceed)\n      )\n      const fiber = yield* pipe(stream, Stream.runCollect, Effect.fork)\n      yield* (Effect.all([\n        coordination.offer,\n        coordination.offer,\n        coordination.offer\n      ], { concurrency: 3, discard: true }))\n      yield* (TestClock.adjust(Duration.seconds(1)))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(\n        Array.from(result).map((chunk) => Array.from(chunk)),\n        [[3]]\n      )\n    }))\n\n  it.effect(\"debounce - should handle empty chunks properly\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.schedule(Schedule.fixed(Duration.millis(500))),\n        Stream.debounce(Duration.seconds(1)),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.seconds(3)))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), [3])\n    }))\n\n  it.effect(\"debounce - should fail immediately\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromEffect(Effect.fail(Option.none())),\n        Stream.debounce(Duration.infinity),\n        Stream.runCollect,\n        Effect.exit\n      )\n      assertFailure(result, Cause.fail(Option.none()))\n    }))\n\n  it.effect(\"debounce - should work with empty streams\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.debounce(Duration.seconds(5)),\n        Stream.runCollect\n      )\n      assertTrue(Chunk.isEmpty(result))\n    }))\n\n  it.effect(\"debounce - should pick last element from every chunk\", () =>\n    Effect.gen(function*() {\n      const fiber = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.debounce(Duration.seconds(1)),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.seconds(1)))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), [3])\n    }))\n\n  it.effect(\"debounce - should interrupt fibers properly\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* (chunkCoordination([\n        Chunk.of(1),\n        Chunk.of(2),\n        Chunk.of(3)\n      ]))\n      const fiber = yield* pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.tap(() => coordination.proceed),\n        // TODO: remove\n        Stream.flatMap((exit) => Stream.fromEffectOption(Effect.suspend(() => exit))),\n        Stream.flattenChunks,\n        Stream.debounce(Duration.millis(200)),\n        Stream.interruptWhen(Effect.never),\n        Stream.take(1),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.millis(100))),\n        Effect.zipRight(coordination.awaitNext),\n        Effect.repeatN(3)\n      )\n      yield* (TestClock.adjust(Duration.millis(100)))\n      const result = yield* (Fiber.join(fiber))\n      deepStrictEqual(Array.from(result), [3])\n    }))\n\n  it.effect(\"debounce - should interrupt children fiber on stream interruption\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (Ref.make(false))\n      const fiber = yield* pipe(\n        Stream.fromEffect(Effect.void),\n        Stream.concat(Stream.fromEffect(pipe(\n          Effect.never,\n          Effect.onInterrupt(() => Ref.set(ref, true))\n        ))),\n        Stream.debounce(Duration.millis(800)),\n        Stream.runDrain,\n        Effect.fork\n      )\n      yield* (TestClock.adjust(Duration.minutes(1)))\n      yield* (Fiber.interrupt(fiber))\n      const result = yield* (Ref.get(ref))\n      assertTrue(result)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/timeouts.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Queue from \"effect/Queue\"\nimport * as Stream from \"effect/Stream\"\nimport * as TestClock from \"effect/TestClock\"\nimport { chunkCoordination } from \"../utils/coordination.js\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"timeout - succeed\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.succeed(1),\n        Stream.timeout(Duration.infinity),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1])\n    }))\n\n  it.effect(\"timeout - should end the stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(0, 4),\n        Stream.tap(() => Effect.sleep(Duration.infinity)),\n        Stream.timeout(Duration.zero),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it.effect(\"timeoutFail - succeed\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(0, 4),\n        Stream.tap(() => Effect.sleep(Duration.infinity)),\n        Stream.timeoutFail(() => false, Duration.zero),\n        Stream.runDrain,\n        Effect.map(() => true),\n        Effect.either\n      )\n      assertLeft(result, false)\n    }))\n\n  it.effect(\"timeoutFail - failures\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fail(\"original\"),\n        Stream.timeoutFail(() => \"timeout\", Duration.minutes(15)),\n        Stream.runDrain,\n        Effect.flip\n      )\n      deepStrictEqual(result, \"original\")\n    }))\n\n  it.effect(\"timeoutFailCause\", () =>\n    Effect.gen(function*() {\n      const error = new Cause.RuntimeException(\"boom\")\n      const result = yield* pipe(\n        Stream.range(0, 4),\n        Stream.tap(() => Effect.sleep(Duration.infinity)),\n        Stream.timeoutFailCause(() => Cause.die(error), Duration.zero),\n        Stream.runDrain,\n        Effect.sandbox,\n        Effect.either\n      )\n      assertLeft(result, Cause.die(error))\n    }))\n\n  it.effect(\"timeoutTo - succeed\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.range(0, 4),\n        Stream.timeoutTo(Duration.infinity, Stream.succeed(-1)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [0, 1, 2, 3, 4])\n    }))\n\n  it.effect(\"timeoutTo - should switch streams\", () =>\n    Effect.gen(function*() {\n      const coordination = yield* chunkCoordination([\n        Chunk.of(1),\n        Chunk.of(2),\n        Chunk.of(3)\n      ])\n      const fiber = yield* pipe(\n        Stream.fromQueue(coordination.queue),\n        Stream.filterMapWhile(Exit.match({ onSuccess: Option.some, onFailure: Option.none })),\n        Stream.flattenChunks,\n        Stream.timeoutTo(Duration.seconds(2), Stream.succeed(4)),\n        Stream.tap(() => coordination.proceed),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* pipe(\n        coordination.offer,\n        Effect.zipRight(TestClock.adjust(Duration.seconds(3))),\n        Effect.zipRight(coordination.awaitNext)\n      )\n      yield* coordination.offer\n      const result = yield* Fiber.join(fiber)\n      deepStrictEqual(Array.from(result), [1, 2, 4])\n    }))\n\n  it.effect(\"timeoutTo - should not apply timeout after switch\", () =>\n    Effect.gen(function*() {\n      const queue1 = yield* Queue.unbounded<number>()\n      const queue2 = yield* Queue.unbounded<number>()\n      const stream1 = Stream.fromQueue(queue1)\n      const stream2 = Stream.fromQueue(queue2)\n      const fiber = yield* pipe(\n        stream1,\n        Stream.timeoutTo(Duration.seconds(2), stream2),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* pipe(\n        Queue.offer(queue1, 1),\n        Effect.zipRight(TestClock.adjust(Duration.seconds(1)))\n      )\n      yield* pipe(\n        Queue.offer(queue1, 2),\n        Effect.zipRight(TestClock.adjust(Duration.seconds(3)))\n      )\n      yield* Queue.offer(queue1, 3)\n      yield* pipe(\n        Queue.offer(queue2, 4),\n        Effect.zipRight(TestClock.adjust(Duration.seconds(3)))\n      )\n      yield* pipe(\n        Queue.offer(queue2, 5),\n        Effect.zipRight(Queue.shutdown(queue2))\n      )\n      const result = yield* Fiber.join(fiber)\n      deepStrictEqual(Array.from(result), [1, 2, 4, 5])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/transducing.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, deepStrictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { constTrue, pipe } from \"effect/Function\"\nimport * as Sink from \"effect/Sink\"\nimport * as Stream from \"effect/Stream\"\n\ndescribe(\"Stream\", () => {\n  it.effect(\"transduce - simple example\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(\"1\", \"2\", \",\", \"3\", \"4\"),\n        Stream.transduce(\n          pipe(\n            Sink.collectAllWhile((char: string) => Number.isInteger(Number.parseInt(char))),\n            Sink.zipLeft(Sink.collectAllWhile((char: string) => !Number.isInteger(Number.parseInt(char))))\n          )\n        ),\n        Stream.map(Chunk.join(\"\")),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\"12\", \"34\"])\n    }))\n\n  it.effect(\"transduce - no remainder\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3, 4),\n        Stream.transduce(Sink.fold(100, (n) => n % 2 === 0, (acc, n) => acc + n)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [101, 105, 104])\n    }))\n\n  it.effect(\"transduce - with a sink that always signals more\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.transduce(Sink.fold(0, constTrue, (acc, n) => acc + n)),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [6])\n    }))\n\n  it.effect(\"transduce - propagates scope error\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.transduce(Sink.fail(\"Woops\")),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"Woops\")\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Stream/zipping.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertLeft, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as fc from \"effect/FastCheck\"\nimport * as Fiber from \"effect/Fiber\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Number from \"effect/Number\"\nimport * as Option from \"effect/Option\"\nimport * as Order from \"effect/Order\"\nimport * as Queue from \"effect/Queue\"\nimport * as Stream from \"effect/Stream\"\nimport * as Take from \"effect/Take\"\n\nconst chunkArb = <A>(\n  arb: fc.Arbitrary<A>,\n  constraints?: fc.ArrayConstraints\n): fc.Arbitrary<Chunk.Chunk<A>> => fc.array(arb, constraints).map(Chunk.unsafeFromArray)\n\nconst OrderByKey: Order.Order<readonly [number, number]> = pipe(\n  Number.Order,\n  Order.mapInput((tuple) => tuple[0])\n)\n\nexport const splitChunks = <A>(chunks: Chunk.Chunk<Chunk.Chunk<A>>): fc.Arbitrary<Chunk.Chunk<Chunk.Chunk<A>>> => {\n  const split = (chunks: Chunk.Chunk<Chunk.Chunk<A>>): fc.Arbitrary<Chunk.Chunk<Chunk.Chunk<A>>> =>\n    fc.integer({ min: 0, max: Math.max(chunks.length - 1, 0) }).chain((i) => {\n      const chunk = Chunk.unsafeGet(chunks, i)\n      return fc.integer({ min: 0, max: Math.max(chunk.length - 1, 0) }).map((j) => {\n        const [left, right] = pipe(chunk, Chunk.splitAt(j))\n        return pipe(\n          chunks,\n          Chunk.take(i),\n          Chunk.appendAll(Chunk.of(left)),\n          Chunk.appendAll(Chunk.of(right)),\n          Chunk.appendAll(pipe(chunks, Chunk.drop(i + 1)))\n        )\n      })\n    })\n  return fc.oneof(fc.constant(chunks), split(chunks).chain((chunks) => splitChunks(chunks)))\n}\n\ndescribe(\"Stream\", () => {\n  it(\"zipAllSortedByKeyWith\", () => {\n    const intArb = fc.integer({ min: 1, max: 100 })\n    const chunkArb = fc.array(fc.tuple(intArb, intArb)).map((entries) =>\n      pipe(Chunk.fromIterable(new Map(entries)), Chunk.sort(OrderByKey))\n    )\n    const chunksArb = chunkArb.chain((chunk) => splitChunks(Chunk.of(chunk)))\n    return fc.assert(fc.asyncProperty(chunksArb, chunksArb, async (as, bs) => {\n      const left = Stream.fromChunks(...as)\n      const right = Stream.fromChunks(...bs)\n      const actual = Stream.zipAllSortedByKeyWith(left, {\n        other: right,\n        onSelf: identity,\n        onOther: identity,\n        onBoth: (x, y) => x + y,\n        order: Number.Order\n      })\n      const expected = pipe(\n        Chunk.flatten(as),\n        Chunk.reduce(new Map(Array.from(Chunk.flatten(bs))), (map, [k, v]) =>\n          pipe(\n            Option.fromNullable(map.get(k)),\n            Option.match({\n              onNone: () => map.set(k, v),\n              onSome: (v1) => map.set(k, v + v1)\n            })\n          )),\n        Chunk.fromIterable,\n        Chunk.sort(OrderByKey)\n      )\n      const result = await Effect.runPromise(Stream.runCollect(actual))\n      deepStrictEqual(Array.from(result), Array.from(expected))\n    }))\n  })\n\n  it.effect(\"zip - does not pull too much when one of the streams is done\", () =>\n    Effect.gen(function*() {\n      const left = pipe(\n        Stream.fromChunks(Chunk.make(1, 2), Chunk.make(3, 4), Chunk.of(5)),\n        Stream.concat(Stream.fail(\"boom\"))\n      )\n      const right = Stream.fromChunks(Chunk.make(\"a\", \"b\"), Chunk.of(\"c\"))\n      const result = yield* pipe(left, Stream.zip(right), Stream.runCollect)\n      deepStrictEqual(Array.from(result), [[1, \"a\"], [2, \"b\"], [3, \"c\"]])\n    }))\n\n  it(\"zip - equivalence with Chunk.zip\", () =>\n    fc.assert(\n      fc.asyncProperty(fc.array(chunkArb(fc.integer())), fc.array(chunkArb(fc.integer())), async (left, right) => {\n        const stream = pipe(\n          Stream.fromChunks(...left),\n          Stream.zip(Stream.fromChunks(...right))\n        )\n        const expected = pipe(\n          Chunk.flatten(Chunk.unsafeFromArray(left)),\n          Chunk.zip(Chunk.flatten(Chunk.unsafeFromArray(right)))\n        )\n        const actual = await Effect.runPromise(Stream.runCollect(stream))\n        deepStrictEqual(Array.from(actual), Array.from(expected))\n      })\n    ))\n\n  it.effect(\"zip - terminate in uninterruptible region\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.zip(Stream.make(2)),\n        Stream.runDrain,\n        Effect.uninterruptible\n      )\n      strictEqual(result, undefined)\n    }))\n\n  it.effect(\"zipWith - prioritizes failures\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.never,\n        Stream.zipWith(Stream.fail(\"Ouch\"), () => Option.none()),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"zipWith - dies if one of the streams throws an exception\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1),\n        Stream.flatMap(() =>\n          Stream.sync(() => {\n            throw new Cause.RuntimeException(\"Ouch\")\n          })\n        ),\n        Stream.zip(Stream.make(1)),\n        Stream.runCollect,\n        Effect.exit\n      )\n      deepStrictEqual(\n        result,\n        Exit.failCause(Cause.die(new Cause.RuntimeException(\"Ouch\")))\n      )\n    }))\n\n  // TODO: handle Chunk.zipAllWith\n  // it(\"zipAllWith\", () =>\n  //   fc.assert(fc.asyncProperty(\n  //     fc.array(chunkArb(fc.integer()).filter((chunk) => chunk.length > 0)),\n  //     fc.array(chunkArb(fc.integer()).filter((chunk) => chunk.length > 0)),\n  //     async (left, right) => {\n  //       const stream = pipe(\n  //         Stream.fromChunks(...left),\n  //         Stream.map(Option.some),\n  //         Stream.zipAll(\n  //           pipe(Stream.fromChunks(...right), Stream.map(Option.some)),\n  //           Option.none() as Option.Option<number>,\n  //           Option.none() as Option.Option<number>\n  //         )\n  //       )\n  //       const actual = await Effect.runPromise(Stream.runCollect(stream))\n  //       const expected = pipe(\n  //         Chunk.flatten(Chunk.fromIterable(left)),\n  //         Chunk.zipAllWith(\n  //           Chunk.flatten(Chunk.fromIterable(right)),\n  //           (a, b) => [Option.some(a), Option.some(b)] as const,\n  //           (a) => [Option.some(a), Option.none()] as const,\n  //           (b) => [Option.none(), Option.some(b)] as const\n  //         )\n  //       )\n  //       deepStrictEqual(Array.from(actual), Array.from(expected))\n  //     }\n  //   )))\n\n  it.effect(\"zipAll - prioritizes failures\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.never,\n        Stream.zipAll({\n          other: Stream.fail(\"Ouch\"),\n          defaultSelf: Option.none(),\n          defaultOther: Option.none()\n        }),\n        Stream.runCollect,\n        Effect.either\n      )\n      assertLeft(result, \"Ouch\")\n    }))\n\n  it.effect(\"zipWithIndex\", () =>\n    Effect.gen(function*() {\n      const stream = Stream.make(1, 2, 3, 4, 5)\n      const { result1, result2 } = yield* Effect.all({\n        result1: Stream.runCollect(Stream.zipWithIndex(stream)),\n        result2: pipe(Stream.runCollect(stream), Effect.map(Chunk.map((a, i) => [a, i] as const)))\n      })\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    }))\n\n  it.effect(\"zipLatest\", () =>\n    Effect.gen(function*() {\n      const left = yield* Queue.unbounded<Chunk.Chunk<number>>()\n      const right = yield* Queue.unbounded<Chunk.Chunk<number>>()\n      const output = yield* Queue.bounded<Take.Take<readonly [number, number]>>(1)\n      yield* pipe(\n        Stream.fromChunkQueue(left),\n        Stream.zipLatest(Stream.fromChunkQueue(right)),\n        Stream.runIntoQueue(output),\n        Effect.fork\n      )\n      yield* Queue.offer(left, Chunk.make(0))\n      yield* Queue.offerAll(right, [Chunk.make(0), Chunk.make(1)])\n      const chunk1 = yield* pipe(\n        Queue.take(output),\n        Effect.flatMap(Take.done),\n        Effect.replicateEffect(2),\n        Effect.map(Chunk.unsafeFromArray),\n        Effect.map(Chunk.flatten)\n      )\n      yield* Queue.offerAll(left, [Chunk.make(1), Chunk.make(2)])\n      const chunk2 = yield* pipe(\n        Queue.take(output),\n        Effect.flatMap(Take.done),\n        Effect.replicateEffect(2),\n        Effect.map(Chunk.unsafeFromArray),\n        Effect.map(Chunk.flatten)\n      )\n      deepStrictEqual(Array.from(chunk1), [[0, 0], [0, 1]])\n      deepStrictEqual(Array.from(chunk2), [[1, 1], [2, 1]])\n    }))\n\n  it.effect(\"zipLatestWith - handles empty pulls properly\", () =>\n    Effect.gen(function*() {\n      const stream0 = Stream.fromChunks(\n        Chunk.empty<number>(),\n        Chunk.empty<number>(),\n        Chunk.make(2)\n      )\n      const stream1 = Stream.fromChunks(Chunk.make(1), Chunk.make(1))\n      const deferred = yield* Deferred.make<number>()\n      const latch = yield* Deferred.make<void>()\n      const fiber = yield* pipe(\n        stream0,\n        Stream.concat(Stream.fromEffect(Deferred.await(deferred))),\n        Stream.concat(Stream.make(2)),\n        Stream.zipLatestWith(\n          pipe(\n            Stream.make(1, 1),\n            Stream.ensuring(Deferred.succeed(latch, void 0)),\n            Stream.concat(stream1)\n          ),\n          (_, n) => n\n        ),\n        Stream.take(3),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* Deferred.await(latch)\n      yield* Deferred.succeed(deferred, 2)\n      const result = yield* Fiber.join(fiber)\n      deepStrictEqual(Array.from(result), [1, 1, 1])\n    }))\n\n  it.effect(\"zipLatestWith - handles empty pulls properly (JVM Only - LOL)\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.unfold(0, (n) =>\n          Option.some(\n            [\n              n < 3 ? Chunk.empty<number>() : Chunk.of(2),\n              n + 1\n            ] as const\n          )),\n        Stream.flattenChunks,\n        Stream.forever,\n        Stream.zipLatestWith(Stream.forever(Stream.make(1)), (_, n) => n),\n        Stream.take(3),\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [1, 1, 1])\n    }))\n\n  it(\"zipLatestWith - preserves partial ordering of stream elements\", () => {\n    const sortedChunkArb = chunkArb(fc.integer({ min: 1, max: 100 }))\n      .map(Chunk.sort(Number.Order))\n    const sortedChunksArb = sortedChunkArb.chain((chunk) => splitChunks(Chunk.of(chunk)))\n    return fc.assert(fc.asyncProperty(sortedChunksArb, sortedChunksArb, async (left, right) => {\n      const stream = pipe(\n        Stream.fromChunks(...left),\n        Stream.zipLatestWith(Stream.fromChunks(...right), (l, r) => l + r)\n      )\n      const result = await Effect.runPromise(Stream.runCollect(stream))\n      const [isSorted] = Chunk.isEmpty(result) ? [true] : pipe(\n        result,\n        Chunk.drop(1),\n        Chunk.reduce(\n          [true as boolean, pipe(result, Chunk.unsafeGet(0))] as const,\n          ([isSorted, last], curr) => [isSorted && last <= curr, curr] as const\n        )\n      )\n      assertTrue(isSorted)\n    }))\n  })\n\n  it.effect(\"zipWithNext\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.zipWithNext,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\n        [1, Option.some(2)],\n        [2, Option.some(3)],\n        [3, Option.none()]\n      ])\n    }))\n\n  it.effect(\"zipWithNext - should work with multiple chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(Chunk.of(1), Chunk.of(2), Chunk.of(3)),\n        Stream.zipWithNext,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\n        [1, Option.some(2)],\n        [2, Option.some(3)],\n        [3, Option.none()]\n      ])\n    }))\n\n  it.effect(\"zipWithNext - should work with an empty stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.zipWithNext,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it(\"zipWithNext - should output the same values as zipping with the tail plus the last element\", () =>\n    fc.assert(fc.asyncProperty(fc.array(chunkArb(fc.integer())), async (chunks) => {\n      const stream = Stream.fromChunks(...chunks)\n      const { result1, result2 } = await Effect.runPromise(Effect.all({\n        result1: pipe(\n          stream,\n          Stream.zipWithNext,\n          Stream.runCollect\n        ),\n        result2: Stream.runCollect(\n          Stream.zipAll(stream, {\n            other: Stream.map(Stream.drop(stream, 1), Option.some),\n            defaultSelf: 0,\n            defaultOther: Option.none()\n          })\n        )\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    })))\n\n  it.effect(\"zipWithPrevious - should zip with previous element for a single chunk\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.zipWithPrevious,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\n        [Option.none(), 1],\n        [Option.some(1), 2],\n        [Option.some(2), 3]\n      ])\n    }))\n\n  it.effect(\"zipWithPrevious - should work with multiple chunks\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.fromChunks(Chunk.of(1), Chunk.of(2), Chunk.of(3)),\n        Stream.zipWithPrevious,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\n        [Option.none(), 1],\n        [Option.some(1), 2],\n        [Option.some(2), 3]\n      ])\n    }))\n\n  it.effect(\"zipWithPrevious - should work with an empty stream\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.empty,\n        Stream.zipWithPrevious,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [])\n    }))\n\n  it(\"zipWithPrevious - should output same values as first element plus zipping with init\", () =>\n    fc.assert(fc.asyncProperty(fc.array(chunkArb(fc.integer())), async (chunks) => {\n      const stream = Stream.fromChunks(...chunks)\n      const { result1, result2 } = await Effect.runPromise(Effect.all({\n        result1: pipe(\n          stream,\n          Stream.zipWithPrevious,\n          Stream.runCollect\n        ),\n        result2: pipe(\n          Stream.make(Option.none()),\n          Stream.concat(pipe(stream, Stream.map(Option.some))),\n          Stream.zip(stream),\n          Stream.runCollect\n        )\n      }))\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    })))\n\n  it.effect(\"zipWithPreviousAndNext\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.make(1, 2, 3),\n        Stream.zipWithPreviousAndNext,\n        Stream.runCollect\n      )\n      deepStrictEqual(Array.from(result), [\n        [Option.none(), 1, Option.some(2)],\n        [Option.some(1), 2, Option.some(3)],\n        [Option.some(2), 3, Option.none()]\n      ])\n    }))\n\n  it(\"zipWithPreviousAndNext - should output same values as zipping with both previous and next element\", () =>\n    fc.assert(fc.asyncProperty(fc.array(chunkArb(fc.integer()), { minLength: 0, maxLength: 5 }), async (chunks) => {\n      const stream = Stream.fromChunks(...chunks)\n      const previous = pipe(\n        Stream.make(Option.none()),\n        Stream.concat(pipe(stream, Stream.map(Option.some)))\n      )\n      const next = pipe(\n        stream,\n        Stream.drop(1),\n        Stream.map(Option.some),\n        Stream.concat(Stream.make(Option.none()))\n      )\n      const { result1, result2 } = await pipe(\n        Effect.all({\n          result1: pipe(\n            stream,\n            Stream.zipWithPreviousAndNext,\n            Stream.runCollect\n          ),\n          result2: pipe(\n            previous,\n            Stream.zip(stream),\n            Stream.zipFlatten(next),\n            Stream.runCollect\n          )\n        }),\n        Effect.runPromise\n      )\n      deepStrictEqual(Array.from(result1), Array.from(result2))\n    })))\n\n  it.effect(\"zipLatestAll\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(\n        Stream.zipLatestAll(\n          Stream.make(1, 2, 3).pipe(Stream.rechunk(1)),\n          Stream.make(\"a\", \"b\", \"c\").pipe(Stream.rechunk(1)),\n          Stream.make(true, false, true).pipe(Stream.rechunk(1))\n        ),\n        Stream.runCollect,\n        Effect.map(Chunk.toReadonlyArray)\n      )\n      deepStrictEqual(result, [\n        [1, \"a\", true],\n        [2, \"a\", true],\n        [3, \"a\", true],\n        [3, \"b\", true],\n        [3, \"c\", true],\n        [3, \"c\", false],\n        [3, \"c\", true]\n      ])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/String.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertNone, assertSome, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Order, pipe, String as Str } from \"effect\"\n\ndescribe(\"String\", () => {\n  it(\"isString\", () => {\n    assertTrue(Str.isString(\"a\"))\n    assertFalse(Str.isString(1))\n    assertFalse(Str.isString(true))\n  })\n\n  it(\"empty\", () => {\n    strictEqual(Str.empty, \"\")\n  })\n\n  it(\"Equivalence\", () => {\n    assertTrue(Str.Equivalence(\"a\", \"a\"))\n    assertFalse(Str.Equivalence(\"a\", \"b\"))\n  })\n\n  it(\"Order\", () => {\n    const lessThan = Order.lessThan(Str.Order)\n    const lessThanOrEqualTo = Order.lessThanOrEqualTo(Str.Order)\n    assertTrue(pipe(\"a\", lessThan(\"b\")))\n    assertFalse(pipe(\"a\", lessThan(\"a\")))\n    assertTrue(pipe(\"a\", lessThanOrEqualTo(\"a\")))\n    assertFalse(pipe(\"b\", lessThan(\"a\")))\n    assertFalse(pipe(\"b\", lessThanOrEqualTo(\"a\")))\n  })\n\n  it(\"concat\", () => {\n    strictEqual(pipe(\"a\", Str.concat(\"b\")), \"ab\")\n  })\n\n  it(\"isEmpty\", () => {\n    assertTrue(Str.isEmpty(\"\"))\n    assertFalse(Str.isEmpty(\"a\"))\n  })\n\n  it(\"isNonEmpty\", () => {\n    assertFalse(Str.isNonEmpty(\"\"))\n    assertTrue(Str.isNonEmpty(\"a\"))\n  })\n\n  it(\"length\", () => {\n    strictEqual(Str.length(\"\"), 0)\n    strictEqual(Str.length(\"a\"), 1)\n    strictEqual(Str.length(\"aaa\"), 3)\n  })\n\n  it(\"toUpperCase\", () => {\n    strictEqual(Str.toUpperCase(\"a\"), \"A\")\n  })\n\n  it(\"toLowerCase\", () => {\n    strictEqual(Str.toLowerCase(\"A\"), \"a\")\n  })\n\n  it(\"capitalize\", () => {\n    strictEqual(Str.capitalize(\"\"), \"\")\n    strictEqual(Str.capitalize(\"abc\"), \"Abc\")\n  })\n\n  it(\"uncapitalize\", () => {\n    strictEqual(Str.uncapitalize(\"\"), \"\")\n    strictEqual(Str.uncapitalize(\"Abc\"), \"abc\")\n  })\n\n  it(\"replace\", () => {\n    strictEqual(pipe(\"abc\", Str.replace(\"b\", \"d\")), \"adc\")\n  })\n\n  it(\"split\", () => {\n    deepStrictEqual(pipe(\"abc\", Str.split(\"\")), [\"a\", \"b\", \"c\"])\n    deepStrictEqual(pipe(\"\", Str.split(\"\")), [\"\"])\n  })\n\n  it(\"trim\", () => {\n    strictEqual(pipe(\" a \", Str.trim), \"a\")\n  })\n\n  it(\"trimStart\", () => {\n    strictEqual(pipe(\" a \", Str.trimStart), \"a \")\n  })\n\n  it(\"trimEnd\", () => {\n    strictEqual(pipe(\" a \", Str.trimEnd), \" a\")\n  })\n\n  it(\"includes\", () => {\n    assertTrue(pipe(\"abc\", Str.includes(\"b\")))\n    assertFalse(pipe(\"abc\", Str.includes(\"d\")))\n    assertTrue(pipe(\"abc\", Str.includes(\"b\", 1)))\n    assertFalse(pipe(\"abc\", Str.includes(\"a\", 1)))\n  })\n\n  it(\"startsWith\", () => {\n    assertTrue(pipe(\"abc\", Str.startsWith(\"a\")))\n    assertFalse(pipe(\"bc\", Str.startsWith(\"a\")))\n    assertTrue(pipe(\"abc\", Str.startsWith(\"b\", 1)))\n    assertFalse(pipe(\"bc\", Str.startsWith(\"a\", 1)))\n  })\n\n  it(\"endsWith\", () => {\n    assertTrue(pipe(\"abc\", Str.endsWith(\"c\")))\n    assertFalse(pipe(\"ab\", Str.endsWith(\"c\")))\n    assertTrue(pipe(\"abc\", Str.endsWith(\"b\", 2)))\n    assertFalse(pipe(\"abc\", Str.endsWith(\"c\", 2)))\n  })\n\n  it(\"slice\", () => {\n    deepStrictEqual(pipe(\"abcd\", Str.slice(1, 3)), \"bc\")\n  })\n\n  it(\"charCodeAt\", () => {\n    assertSome(pipe(\"abc\", Str.charCodeAt(1)), 98)\n    assertNone(pipe(\"abc\", Str.charCodeAt(4)))\n  })\n\n  it(\"substring\", () => {\n    strictEqual(pipe(\"abcd\", Str.substring(1)), \"bcd\")\n    strictEqual(pipe(\"abcd\", Str.substring(1, 3)), \"bc\")\n  })\n\n  it(\"at\", () => {\n    assertSome(pipe(\"abc\", Str.at(1)), \"b\")\n    assertNone(pipe(\"abc\", Str.at(4)))\n  })\n\n  it(\"charAt\", () => {\n    assertSome(pipe(\"abc\", Str.charAt(1)), \"b\")\n    assertNone(pipe(\"abc\", Str.charAt(4)))\n  })\n\n  it(\"codePointAt\", () => {\n    assertSome(pipe(\"abc\", Str.codePointAt(1)), 98)\n    assertNone(pipe(\"abc\", Str.codePointAt(4)))\n  })\n\n  it(\"indexOf\", () => {\n    assertSome(pipe(\"abbbc\", Str.indexOf(\"b\")), 1)\n    assertNone(pipe(\"abbbc\", Str.indexOf(\"d\")))\n  })\n\n  it(\"lastIndexOf\", () => {\n    assertSome(pipe(\"abbbc\", Str.lastIndexOf(\"b\")), 3)\n    assertNone(pipe(\"abbbc\", Str.lastIndexOf(\"d\")))\n  })\n\n  it(\"localeCompare\", () => {\n    strictEqual(pipe(\"a\", Str.localeCompare(\"b\")), -1)\n    strictEqual(pipe(\"b\", Str.localeCompare(\"a\")), 1)\n    strictEqual(pipe(\"a\", Str.localeCompare(\"a\")), 0)\n  })\n\n  it(\"match\", () => {\n    assertSome(pipe(\"a\", Str.match(/a/)), \"a\".match(/a/))\n    assertNone(pipe(\"a\", Str.match(/b/)))\n  })\n\n  it(\"matchAll\", () => {\n    strictEqual(Array.from(pipe(\"apple, banana\", Str.matchAll(/a[pn]/g))).length, 3)\n    strictEqual(Array.from(pipe(\"apple, banana\", Str.matchAll(/c/g))).length, 0)\n  })\n\n  it(\"normalize\", () => {\n    const str = \"\\u1E9B\\u0323\"\n    strictEqual(pipe(str, Str.normalize()), \"\\u1E9B\\u0323\")\n    strictEqual(pipe(str, Str.normalize(\"NFC\")), \"\\u1E9B\\u0323\")\n    strictEqual(pipe(str, Str.normalize(\"NFD\")), \"\\u017F\\u0323\\u0307\")\n    strictEqual(pipe(str, Str.normalize(\"NFKC\")), \"\\u1E69\")\n    strictEqual(pipe(str, Str.normalize(\"NFKD\")), \"\\u0073\\u0323\\u0307\")\n  })\n\n  it(\"padEnd\", () => {\n    strictEqual(pipe(\"a\", Str.padEnd(5)), \"a    \")\n    strictEqual(pipe(\"a\", Str.padEnd(5, \"_\")), \"a____\")\n  })\n\n  it(\"padStart\", () => {\n    strictEqual(pipe(\"a\", Str.padStart(5)), \"    a\")\n    strictEqual(pipe(\"a\", Str.padStart(5, \"_\")), \"____a\")\n  })\n\n  it(\"repeat\", () => {\n    strictEqual(pipe(\"a\", Str.repeat(3)), \"aaa\")\n  })\n\n  it(\"replaceAll\", () => {\n    strictEqual(pipe(\"ababb\", Str.replaceAll(\"b\", \"c\")), \"acacc\")\n    strictEqual(pipe(\"ababb\", Str.replaceAll(/ba/g, \"cc\")), \"accbb\")\n  })\n\n  it(\"search\", () => {\n    assertSome(pipe(\"ababb\", Str.search(\"b\")), 1)\n    assertSome(pipe(\"ababb\", Str.search(/abb/)), 2)\n    assertNone(pipe(\"ababb\", Str.search(/c/)))\n  })\n\n  it(\"toLocaleLowerCase\", () => {\n    const locales = [\"tr\", \"TR\", \"tr-TR\", \"tr-u-co-search\", \"tr-x-turkish\"]\n    strictEqual(pipe(\"\\u0130\", Str.toLocaleLowerCase(locales)), \"i\")\n  })\n\n  it(\"toLocaleUpperCase\", () => {\n    const locales = [\"lt\", \"LT\", \"lt-LT\", \"lt-u-co-phonebk\", \"lt-x-lietuva\"]\n    strictEqual(pipe(\"i\\u0307\", Str.toLocaleUpperCase(locales)), \"I\")\n  })\n\n  describe(\"takeLeft\", () => {\n    it(\"should take the specified number of characters from the left side of a string\", () => {\n      strictEqual(Str.takeLeft(\"Hello, World!\", 7), \"Hello, \")\n    })\n\n    it(\"should return the string for `n` larger than the string length\", () => {\n      const string = \"Hello, World!\"\n      strictEqual(Str.takeLeft(string, 100), string)\n    })\n\n    it(\"should return the empty string for a negative `n`\", () => {\n      strictEqual(Str.takeLeft(\"Hello, World!\", -1), \"\")\n    })\n\n    it(\"should round down if `n` is a float\", () => {\n      strictEqual(Str.takeLeft(\"Hello, World!\", 5.5), \"Hello\")\n    })\n  })\n\n  describe(\"takeRight\", () => {\n    it(\"should take the specified number of characters from the right side of a string\", () => {\n      strictEqual(Str.takeRight(\"Hello, World!\", 7), \" World!\")\n    })\n\n    it(\"should return the string for `n` larger than the string length\", () => {\n      const string = \"Hello, World!\"\n      strictEqual(Str.takeRight(string, 100), string)\n    })\n\n    it(\"should return the empty string for a negative `n`\", () => {\n      strictEqual(Str.takeRight(\"Hello, World!\", -1), \"\")\n    })\n\n    it(\"should round down if `n` is a float\", () => {\n      strictEqual(Str.takeRight(\"Hello, World!\", 6.5), \"World!\")\n    })\n  })\n\n  describe(\"stripMargin\", () => {\n    it(\"should strip a leading prefix from each line\", () => {\n      const string = `|\n    |Hello,\n    |World!\n    |`\n      const result = Str.stripMargin(string)\n      strictEqual(result, \"\\nHello,\\nWorld!\\n\")\n    })\n\n    it(\"should strip a leading prefix from each line using a margin character\", () => {\n      const string = \"\\n$\\n    $Hello,\\r\\n    $World!\\n $\"\n      const result = Str.stripMarginWith(string, \"$\")\n      strictEqual(result, \"\\n\\nHello,\\r\\nWorld!\\n\")\n    })\n  })\n\n  describe(\"linesWithSeparators\", () => {\n    it(\"should split a string into lines with separators\", () => {\n      const string = \"\\n$\\n    $Hello,\\r\\n    $World!\\n $\"\n      const result = Str.linesWithSeparators(string)\n      deepStrictEqual(Array.from(result), [\"\\n\", \"$\\n\", \"    $Hello,\\r\\n\", \"    $World!\\n\", \" $\"])\n    })\n  })\n\n  describe(\"linesIterator\", () => {\n    it(\"should split a string into lines\", () => {\n      const string = \"\\n$\\n    $Hello,\\r\\n    $World!\\n $\"\n      const result = Str.linesIterator(string)\n      deepStrictEqual(Array.from(result), [\"\", \"$\", \"    $Hello,\", \"    $World!\", \" $\"])\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Struct.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Number, pipe, String, Struct } from \"effect\"\n\ndescribe(\"Struct\", () => {\n  it(\"pick\", () => {\n    deepStrictEqual(pipe({ a: \"a\", b: 1, c: true }, Struct.pick(\"a\", \"b\")), { a: \"a\", b: 1 })\n    deepStrictEqual(Struct.pick({ a: \"a\", b: 1, c: true }, \"a\", \"b\"), { a: \"a\", b: 1 })\n\n    const record1: Record<string, number> = {}\n    deepStrictEqual(pipe(record1, Struct.pick(\"a\", \"b\")), {})\n    const record2: Record<string, number> = { b: 1 }\n    deepStrictEqual(pipe(record2, Struct.pick(\"a\", \"b\")), { b: 1 })\n\n    const optionalStringStruct1: {\n      a?: string\n      b: number\n      c: boolean\n    } = { b: 1, c: true }\n    deepStrictEqual(pipe(optionalStringStruct1, Struct.pick(\"a\", \"b\")), { b: 1 })\n    const optionalStringStruct2: {\n      a?: string\n      b: number\n      c: boolean\n    } = { a: \"a\", b: 1, c: true }\n    deepStrictEqual(pipe(optionalStringStruct2, Struct.pick(\"a\", \"b\")), { a: \"a\", b: 1 })\n\n    const a = Symbol.for(\"a\")\n    const optionalSymbolStruct1: {\n      [a]?: string\n      b: number\n      c: boolean\n    } = { b: 1, c: true }\n    deepStrictEqual(pipe(optionalSymbolStruct1, Struct.pick(a, \"b\")), { b: 1 })\n    const optionalSymbolStruct2: {\n      [a]?: string\n      b: number\n      c: boolean\n    } = { [a]: \"a\", b: 1, c: true }\n    deepStrictEqual(pipe(optionalSymbolStruct2, Struct.pick(a, \"b\")), { [a]: \"a\", b: 1 })\n  })\n\n  it(\"omit\", () => {\n    deepStrictEqual(pipe({ a: \"a\", b: 1, c: true }, Struct.omit(\"c\")), { a: \"a\", b: 1 })\n    deepStrictEqual(Struct.omit({ a: \"a\", b: 1, c: true }, \"c\"), { a: \"a\", b: 1 })\n\n    const record1: Record<string, number> = {}\n    deepStrictEqual(pipe(record1, Struct.omit(\"a\", \"c\")), {})\n    const record2: Record<string, number> = { b: 1 }\n    deepStrictEqual(pipe(record2, Struct.omit(\"a\", \"c\")), { b: 1 })\n\n    const optionalStringStruct1: {\n      a?: string\n      b: number\n      c: boolean\n    } = { b: 1, c: true }\n    deepStrictEqual(pipe(optionalStringStruct1, Struct.omit(\"c\")), { b: 1 })\n    const optionalStringStruct2: {\n      a?: string\n      b: number\n      c: boolean\n    } = { a: \"a\", b: 1, c: true }\n    deepStrictEqual(pipe(optionalStringStruct2, Struct.omit(\"c\")), { a: \"a\", b: 1 })\n\n    const a = Symbol.for(\"a\")\n    const optionalSymbolStruct1: {\n      [a]?: string\n      b: number\n      c: boolean\n    } = { b: 1, c: true }\n    deepStrictEqual(pipe(optionalSymbolStruct1, Struct.omit(\"c\")), { b: 1 })\n    const optionalSymbolStruct2: {\n      [a]?: string\n      b: number\n      c: boolean\n    } = { [a]: \"a\", b: 1, c: true }\n    deepStrictEqual(pipe(optionalSymbolStruct2, Struct.omit(\"c\")), { [a]: \"a\", b: 1 })\n  })\n\n  it(\"evolve\", () => {\n    const res1 = pipe(\n      { a: \"a\", b: 1, c: true, d: \"extra\" },\n      Struct.evolve({\n        a: (s) => s.length,\n        b: (b) => b > 0,\n        c: (c) => !c\n      })\n    )\n\n    deepStrictEqual(res1, { a: 1, b: true, c: false, d: \"extra\" })\n\n    const x: Record<\"b\", number> = Object.create({ a: 1 })\n    x.b = 1\n    const res2 = pipe(x, Struct.evolve({ b: (b) => b > 0 }))\n\n    deepStrictEqual(res2, { b: true })\n\n    // dual\n    const res3 = Struct.evolve({ a: 1 }, { a: (x) => x > 0 })\n    deepStrictEqual(res3, { a: true })\n  })\n\n  it(\"struct\", () => {\n    const PersonEquivalence = Struct.getEquivalence({\n      name: String.Equivalence,\n      age: Number.Equivalence\n    })\n\n    deepStrictEqual(\n      PersonEquivalence({ name: \"John\", age: 25 }, { name: \"John\", age: 25 }),\n      true\n    )\n    deepStrictEqual(\n      PersonEquivalence({ name: \"John\", age: 25 }, { name: \"John\", age: 40 }),\n      false\n    )\n  })\n\n  it(\"get\", () => {\n    strictEqual(pipe({ a: 1 }, Struct.get(\"a\")), 1)\n    strictEqual(pipe({}, Struct.get(\"a\")), undefined)\n  })\n\n  it(\"entries\", () => {\n    const c = Symbol(\"c\")\n    // should not include symbol keys\n    deepStrictEqual(Struct.entries({ a: \"a\", b: 1, [c]: 2 }), [[\"a\", \"a\"], [\"b\", 1]])\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/SubscriptionRef.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport { Chunk, Deferred, Effect, Equal, Exit, Fiber, Number, pipe, Random, Stream, SubscriptionRef } from \"effect\"\n\ndescribe(\"SubscriptionRef\", () => {\n  it.effect(\"multiple subscribers can receive changes\", () =>\n    Effect.gen(function*() {\n      const subscriptionRef = yield* (SubscriptionRef.make(0))\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const subscriber1 = yield* pipe(\n        subscriptionRef.changes,\n        Stream.tap(() => Deferred.succeed(deferred1, void 0)),\n        Stream.take(3),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(deferred1))\n      yield* (SubscriptionRef.update(subscriptionRef, (n) => n + 1))\n      const subscriber2 = yield* pipe(\n        subscriptionRef.changes,\n        Stream.tap(() => Deferred.succeed(deferred2, void 0)),\n        Stream.take(2),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(deferred2))\n      yield* (SubscriptionRef.update(subscriptionRef, (n) => n + 1))\n      const result1 = yield* (Fiber.join(subscriber1))\n      const result2 = yield* (Fiber.join(subscriber2))\n      deepStrictEqual(Array.from(result1), [0, 1, 2])\n      deepStrictEqual(Array.from(result2), [1, 2])\n    }))\n\n  it.effect(\"subscriptions are interruptible\", () =>\n    Effect.gen(function*() {\n      const subscriptionRef = yield* (SubscriptionRef.make(0))\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const subscriber1 = yield* pipe(\n        subscriptionRef.changes,\n        Stream.tap(() => Deferred.succeed(deferred1, void 0)),\n        Stream.take(5),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(deferred1))\n      yield* (SubscriptionRef.update(subscriptionRef, (n) => n + 1))\n      const subscriber2 = yield* pipe(\n        subscriptionRef.changes,\n        Stream.tap(() => Deferred.succeed(deferred2, void 0)),\n        Stream.take(2),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(deferred2))\n      yield* (SubscriptionRef.update(subscriptionRef, (n) => n + 1))\n      const result1 = yield* (Fiber.interrupt(subscriber1))\n      const result2 = yield* (Fiber.join(subscriber2))\n      assertTrue(Exit.isInterrupted(result1))\n      deepStrictEqual(Array.from(result2), [1, 2])\n    }))\n\n  it.effect(\"concurrent subscribes and unsubscribes are handled correctly\", () =>\n    Effect.gen(function*() {\n      const subscriber = (subscriptionRef: SubscriptionRef.SubscriptionRef<number>) =>\n        pipe(\n          Random.nextIntBetween(0, 200),\n          Effect.flatMap((n) =>\n            pipe(\n              subscriptionRef.changes,\n              Stream.take(n),\n              Stream.runCollect\n            )\n          )\n        )\n      const subscriptionRef = yield* (SubscriptionRef.make(0))\n      const fiber = yield* pipe(\n        SubscriptionRef.update(subscriptionRef, (n) => n + 1),\n        Effect.forever,\n        Effect.fork\n      )\n      const result = yield* (\n        Effect.map(\n          Effect.all(\n            Array.from({ length: 2 }, () => subscriber(subscriptionRef)),\n            { concurrency: 2 }\n          ),\n          Chunk.unsafeFromArray\n        )\n      )\n      yield* (Fiber.interrupt(fiber))\n      const isSorted = Chunk.every(result, (chunk) => Equal.equals(chunk, Chunk.sort(chunk, Number.Order)))\n      assertTrue(isSorted)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Symbol.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue } from \"@effect/vitest/utils\"\nimport { Symbol as Sym } from \"effect\"\n\ndescribe(\"Symbol\", () => {\n  it(\"isSymbol\", () => {\n    assertTrue(Sym.isSymbol(Symbol.for(\"effect/test/a\")))\n    assertFalse(Sym.isSymbol(1n))\n    assertFalse(Sym.isSymbol(1))\n    assertFalse(Sym.isSymbol(\"a\"))\n    assertFalse(Sym.isSymbol(true))\n  })\n\n  it(\"Equivalence\", () => {\n    const eq = Sym.Equivalence\n    assertTrue(eq(Symbol.for(\"effect/test/a\"), Symbol.for(\"effect/test/a\")))\n    assertFalse(eq(Symbol.for(\"effect/test/a\"), Symbol.for(\"effect/test/b\")))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/SynchronizedRef.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Deferred, Effect, Exit, Fiber, Option, pipe, SynchronizedRef } from \"effect\"\n\nconst current = \"value\"\nconst update = \"new value\"\nconst failure = \"failure\"\n\ntype State = Active | Changed | Closed\n\ninterface Active {\n  readonly _tag: \"Active\"\n}\n\ninterface Changed {\n  readonly _tag: \"Changed\"\n}\n\ninterface Closed {\n  readonly _tag: \"Closed\"\n}\n\nexport const Active: State = { _tag: \"Active\" }\nexport const Changed: State = { _tag: \"Changed\" }\nexport const Closed: State = { _tag: \"Closed\" }\n\nconst isActive = (self: State): boolean => self._tag === \"Active\"\nconst isChanged = (self: State): boolean => self._tag === \"Changed\"\nconst isClosed = (self: State): boolean => self._tag === \"Closed\"\n\ndescribe(\"SynchronizedRef\", () => {\n  it.effect(\"get\", () =>\n    Effect.gen(function*() {\n      const result = yield* pipe(SynchronizedRef.make(current), Effect.flatMap(SynchronizedRef.get))\n      strictEqual(result, current)\n    }))\n  it.effect(\"getAndUpdateEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const ref = yield* SynchronizedRef.make(current)\n      const result1 = yield* SynchronizedRef.getAndUpdateEffect(ref, () => Effect.succeed(update))\n      const result2 = yield* ref\n      strictEqual(result1, current)\n      strictEqual(result2, update)\n    }))\n  it.effect(\"getAndUpdateEffect - with failure\", () =>\n    Effect.gen(function*() {\n      const ref = yield* SynchronizedRef.make(current)\n      const result = yield* pipe(SynchronizedRef.getAndUpdateEffect(ref, (_) => Effect.fail(failure)), Effect.exit)\n      deepStrictEqual(result, Exit.fail(failure))\n    }))\n  it.effect(\"getAndUpdateSomeEffect - happy path\", () =>\n    Effect.gen(function*() {\n      const ref = yield* SynchronizedRef.make<State>(Active)\n      const result1 = yield* (SynchronizedRef.getAndUpdateSomeEffect(ref, (state) =>\n        isClosed(state) ?\n          Option.some(Effect.succeed(Changed)) :\n          Option.none()))\n      const result2 = yield* SynchronizedRef.get(ref)\n      deepStrictEqual(result1, Active)\n      deepStrictEqual(result2, Active)\n    }))\n  it.effect(\"getAndUpdateSomeEffect - twice\", () =>\n    Effect.gen(function*() {\n      const ref = yield* SynchronizedRef.make<State>(Active)\n      const result1 = yield* SynchronizedRef.getAndUpdateSomeEffect(ref, (state) =>\n        isActive(state) ?\n          Option.some(Effect.succeed(Changed)) :\n          Option.none())\n      const result2 = yield* SynchronizedRef.getAndUpdateSomeEffect(ref, (state) =>\n        isClosed(state)\n          ? Option.some(Effect.succeed(Active))\n          : isChanged(state)\n          ? Option.some(Effect.succeed(Closed))\n          : Option.none())\n      const result3 = yield* ref\n      deepStrictEqual(result1, Active)\n      deepStrictEqual(result2, Changed)\n      deepStrictEqual(result3, Closed)\n    }))\n  it.effect(\"getAndUpdateSomeEffect - with failure\", () =>\n    Effect.gen(function*() {\n      const ref = yield* SynchronizedRef.make<State>(Active)\n      const result = yield* pipe(\n        SynchronizedRef.getAndUpdateSomeEffect(ref, (state) =>\n          isActive(state) ?\n            Option.some(Effect.fail(failure)) :\n            Option.none()),\n        Effect.exit\n      )\n      deepStrictEqual(result, Exit.fail(failure))\n    }))\n  it.effect(\"getAndUpdateSomeEffect - interrupt parent fiber and update\", () =>\n    Effect.gen(function*() {\n      const deferred = yield* Deferred.make<SynchronizedRef.SynchronizedRef<State>>()\n      const latch = yield* Deferred.make<void>()\n      const makeAndWait = Deferred.complete(deferred, SynchronizedRef.make<State>(Active)).pipe(\n        Effect.zipRight(Deferred.await(latch))\n      )\n      const fiber = yield* Effect.fork(makeAndWait)\n      const ref = yield* Deferred.await(deferred)\n      yield* Fiber.interrupt(fiber)\n      const result = yield* SynchronizedRef.updateAndGetEffect(ref, (_) => Effect.succeed(Closed))\n      deepStrictEqual(result, Closed)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/TArray.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport {\n  assertFalse,\n  assertLeft,\n  assertNone,\n  assertSome,\n  assertTrue,\n  deepStrictEqual,\n  strictEqual\n} from \"@effect/vitest/utils\"\nimport { Cause, Chunk, Effect, Exit, Fiber, identity, Number, Option, pipe, STM, TArray, TRef } from \"effect\"\nimport { constFalse, constTrue } from \"effect/Function\"\n\nconst largePrime = 223\n\nconst makeRepeats = (blocks: number, length: number): STM.STM<TArray.TArray<number>> =>\n  TArray.fromIterable(Array.from({ length: blocks * length }, (_, i) => (i % length) + 1))\n\nconst makeStair = (length: number): STM.STM<TArray.TArray<number>> =>\n  TArray.fromIterable(Array.from({ length }, (_, i) => i + 1))\n\nconst makeStairWithHoles = (length: number): STM.STM<TArray.TArray<Option.Option<number>>> =>\n  TArray.fromIterable(Array.from({ length }, (_, i) => i % 3 === 0 ? Option.none() : Option.some(i)))\n\nconst makeTArray = <A>(length: number, value: A): STM.STM<TArray.TArray<A>> =>\n  TArray.fromIterable(Array.from({ length }, () => value))\n\nconst valuesOf = <A>(array: TArray.TArray<A>): STM.STM<Array<A>> =>\n  pipe(array, TArray.reduce<Array<A>, A>([], (acc, a) => [...acc, a]))\n\ndescribe(\"TArray\", () => {\n  it.effect(\"collectFirst - finds and transforms correctly\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStairWithHoles(n))\n      const result = yield* (pipe(\n        array,\n        TArray.collectFirst((option) =>\n          Option.isSome(option) && option.value > 2 ?\n            Option.some(String(option.value)) :\n            Option.none()\n        )\n      ))\n      assertSome(result, \"4\")\n    }))\n\n  it.effect(\"collectFirst - succeeds for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeTArray<Option.Option<number>>(0, Option.none()))\n      const result = yield* (pipe(array, TArray.collectFirst(identity)))\n      assertNone(result)\n    }))\n\n  it.effect(\"collectFirst - fails to find absent\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStairWithHoles(n))\n      const result = yield* (pipe(\n        array,\n        TArray.collectFirst((option) =>\n          Option.isSome(option) && option.value > n ?\n            Option.some(String(option.value)) :\n            Option.none()\n        )\n      ))\n      assertNone(result)\n    }))\n\n  it.effect(\"collectFirst - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeStairWithHoles(n))\n      const fiber = yield* (pipe(\n        array,\n        TArray.collectFirst((option) =>\n          Option.isSome(option) && option.value % largePrime === 0 ?\n            Option.some(String(option.value)) :\n            Option.none()\n        ),\n        Effect.fork\n      ))\n      yield* (pipe(\n        Chunk.range(0, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, () => Option.some(1))))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(\n        (Option.isSome(result) && result.value === String(largePrime)) ||\n          Option.isNone(result)\n      )\n    }))\n\n  it.effect(\"collectFirstSTM - finds and transforms correctly\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStairWithHoles(n))\n      const result = yield* (pipe(\n        array,\n        TArray.collectFirstSTM((option) =>\n          Option.isSome(option) && option.value > 2 ?\n            Option.some(STM.succeed(String(option.value))) :\n            Option.none()\n        )\n      ))\n      assertSome(result, \"4\")\n    }))\n\n  it.effect(\"collectFirstSTM - succeeds for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeTArray<Option.Option<number>>(0, Option.none()))\n      const result = yield* (pipe(\n        array,\n        TArray.collectFirstSTM((option) =>\n          Option.isSome(option) ?\n            Option.some(STM.succeed(option.value)) :\n            Option.none()\n        )\n      ))\n      assertNone(result)\n    }))\n\n  it.effect(\"collectFirstSTM - fails to find absent\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStairWithHoles(n))\n      const result = yield* (pipe(\n        array,\n        TArray.collectFirstSTM((option) =>\n          Option.isSome(option) && option.value > n ?\n            Option.some(STM.succeed(String(option.value))) :\n            Option.none()\n        )\n      ))\n      assertNone(result)\n    }))\n\n  it.effect(\"collectFirstSTM - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeStairWithHoles(n))\n      const fiber = yield* (pipe(\n        array,\n        TArray.collectFirstSTM((option) =>\n          Option.isSome(option) && option.value % largePrime === 0 ?\n            Option.some(STM.succeed(String(option.value))) :\n            Option.none()\n        ),\n        Effect.fork\n      ))\n      yield* (pipe(\n        Chunk.range(0, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, () => Option.some(1))))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(\n        (Option.isSome(result) && result.value === String(largePrime)) ||\n          Option.isNone(result)\n      )\n    }))\n\n  it.effect(\"collectFirstSTM - fails on errors before result found\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStairWithHoles(n))\n      const result = yield* (pipe(\n        array,\n        TArray.collectFirstSTM((option) =>\n          Option.isSome(option) && option.value > 2 ?\n            Option.some(STM.succeed(String(option.value))) :\n            Option.some(STM.fail(\"boom\"))\n        ),\n        STM.flip\n      ))\n      strictEqual(result, \"boom\")\n    }))\n\n  it.effect(\"collectFirstSTM - succeeds on errors after result found\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStairWithHoles(n))\n      const result = yield* (pipe(\n        array,\n        TArray.collectFirstSTM((option) =>\n          Option.isSome(option) ?\n            option.value > 2 ?\n              Option.some(STM.succeed(String(option.value))) :\n              option.value === 7 ?\n              Option.some(STM.fail(\"boom\")) :\n              Option.none() :\n            Option.none()\n        )\n      ))\n      assertSome(result, \"4\")\n    }))\n\n  it.effect(\"contains - true when in the array\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.contains(3)))\n      assertTrue(result)\n    }))\n\n  it.effect(\"contains - false when not in the array\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.contains(n + 1)))\n      assertFalse(result)\n    }))\n\n  it.effect(\"contains - false for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.contains(0)))\n      assertFalse(result)\n    }))\n\n  it.effect(\"count - computes correct sum\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.count((n) => n % 2 === 0)))\n      strictEqual(result, 5)\n    }))\n\n  it.effect(\"count - zero when the predicate does not match\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.count((i) => i > n)))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"count - zero for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.count(constTrue)))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"countSTM - computes correct sum\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.countSTM((n) => STM.succeed(n % 2 === 0))))\n      strictEqual(result, 5)\n    }))\n\n  it.effect(\"countSTM - zero when the predicate does not match\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.countSTM((i) => STM.succeed(i > n))))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"countSTM - zero for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.countSTM(() => STM.succeed(true))))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"every - detects satisfaction\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.every((i) => i < n + 1)))\n      assertTrue(result)\n    }))\n\n  it.effect(\"every - detects lack of satisfaction\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.every((i) => i < n - 1)))\n      assertFalse(result)\n    }))\n\n  it.effect(\"every - detects lack of satisfaction\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.every(constFalse)))\n      assertTrue(result)\n    }))\n\n  it.effect(\"everySTM - detects satisfaction\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.everySTM((i) => STM.succeed(i < n + 1))))\n      assertTrue(result)\n    }))\n\n  it.effect(\"everySTM - detects lack of satisfaction\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.everySTM((i) => STM.succeed(i < n - 1))))\n      assertFalse(result)\n    }))\n\n  it.effect(\"everySTM - detects lack of satisfaction\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.everySTM(() => STM.succeed(false))))\n      assertTrue(result)\n    }))\n\n  it.effect(\"everySTM - fails for errors before counterexample\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.everySTM((n) => n === 4 ? STM.fail(\"boom\") : STM.succeed(n !== 5)),\n        STM.flip\n      ))\n      strictEqual(result, \"boom\")\n    }))\n\n  it.effect(\"everySTM - fails for errors after counterexample\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.everySTM((n) => n === 6 ? STM.fail(\"boom\") : STM.succeed(n === 5)),\n        STM.flip\n      ))\n      strictEqual(result, \"boom\")\n    }))\n\n  it.effect(\"get - happy path\", () =>\n    Effect.gen(function*() {\n      const result = yield* (pipe(\n        makeTArray(1, 42),\n        STM.flatMap(TArray.get(0))\n      ))\n      strictEqual(result, 42)\n    }))\n\n  it.effect(\"findFirst - is correct\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirst((n) => n % 5 === 0)))\n      assertSome(result, 5)\n    }))\n\n  it.effect(\"findFirst - succeeds for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.findFirst(constTrue)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirst - fails to find absent\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirst((i) => i > n)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirst - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeStair(n))\n      const fiber = yield* (pipe(\n        array,\n        TArray.findFirst((n) => n % largePrime === 0),\n        Effect.fork\n      ))\n      yield* (pipe(\n        Chunk.range(1, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, () => 1)))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(\n        (Option.isSome(result) && result.value === largePrime) ||\n          Option.isNone(result)\n      )\n    }))\n\n  it.effect(\"findFirstIndex - correct index if in array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findFirstIndex(2)))\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"findFirstIndex - none for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.findFirstIndex(1)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndex - none if absent\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findFirstIndex(4)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexFrom - correct index if in array, with offset\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findFirstIndexFrom(2, 2)))\n      assertSome(result, 4)\n    }))\n\n  it.effect(\"findFirstIndexFrom - none if absent after offset\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findFirstIndexFrom(1, 7)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexFrom - none for a negative offset\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findFirstIndexFrom(1, -1)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexFrom - none for an offset that is too large\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findFirstIndexFrom(1, 9)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWhere - determines the correct index\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhere((n) => n % 5 === 0)))\n      assertSome(result, 4)\n    }))\n\n  it.effect(\"findFirstIndexWhere - none for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.findFirstIndexWhere(constTrue)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWhere - none for empty array\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhere((i) => i > n)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWhere - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeStair(n))\n      const fiber = yield* (pipe(\n        array,\n        TArray.findFirstIndexWhere((n) => n % largePrime === 0),\n        Effect.fork\n      ))\n      yield* (pipe(\n        Chunk.range(0, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, () => 1)))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(\n        (Option.isSome(result) && result.value === largePrime - 1) ||\n          Option.isNone(result)\n      )\n    }))\n\n  it.effect(\"findFirstIndexWhereFrom - determines the correct index, with offset\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereFrom((n) => n % 2 === 0, 5)))\n      assertSome(result, 5)\n    }))\n\n  it.effect(\"findFirstIndexWhereFrom - none if absent after offset\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereFrom((n) => n % 7 === 0, 7)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWhereFrom - none for a negative offset\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereFrom(constTrue, -1)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWhereFrom - none for an offset that is too large\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereFrom(constTrue, n + 1)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWhereSTM - determines the correct index\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereSTM((n) => STM.succeed(n % 5 === 0))))\n      assertSome(result, 4)\n    }))\n\n  it.effect(\"findFirstIndexWhereSTM - none for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereSTM(() => STM.succeed(true))))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWhereSTM - none for empty array\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereSTM((i) => STM.succeed(i > n))))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWhereSTM - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeStair(n))\n      const fiber = yield* (pipe(\n        array,\n        TArray.findFirstIndexWhereSTM((n) => STM.succeed(n % largePrime === 0)),\n        Effect.fork\n      ))\n      yield* (pipe(\n        Chunk.range(0, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, () => 1)))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(\n        (Option.isSome(result) && result.value === largePrime - 1) ||\n          Option.isNone(result)\n      )\n    }))\n\n  it.effect(\"findFirstIndexWhereSTM - fails on errors before result found\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.findFirstIndexWhereSTM((n) => n === 4 ? STM.fail(\"boom\") : STM.succeed(n % 5 === 0)),\n        STM.flip\n      ))\n      strictEqual(result, \"boom\")\n    }))\n\n  it.effect(\"findFirstIndexWhereSTM - succeeds on errors after result found\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.findFirstIndexWhereSTM((n) => n === 6 ? STM.fail(\"boom\") : STM.succeed(n % 5 === 0))\n      ))\n      assertSome(result, 4)\n    }))\n\n  it.effect(\"findFirstIndexWhereFromSTM - determines the correct index, with offset\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereFromSTM((n) => STM.succeed(n % 2 === 0), 5)))\n      assertSome(result, 5)\n    }))\n\n  it.effect(\"findFirstIndexWhereFromSTM - none if absent after offset\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereFromSTM((n) => STM.succeed(n % 7 === 0), 7)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWhereFromSTM - none for a negative offset\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereFromSTM(() => STM.succeed(true), -1)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWherFromeSTM - none for an offset that is too large\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstIndexWhereFromSTM(() => STM.succeed(true), n + 1)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstIndexWhereFromSTM - succeeds when error excluded by offset\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.findFirstIndexWhereFromSTM((n) =>\n          n === 1\n            ? STM.fail(\"boom\")\n            : STM.succeed(n % 5 === 0), 2)\n      ))\n      assertSome(result, 4)\n    }))\n\n  it.effect(\"findFirstSTM - is correct\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstSTM((n) => STM.succeed(n % 5 === 0))))\n      assertSome(result, 5)\n    }))\n\n  it.effect(\"findFirstSTM - succeeds for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.findFirstSTM(() => STM.succeed(true))))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstSTM - fails to find absent\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findFirstSTM((i) => STM.succeed(i > n))))\n      assertNone(result)\n    }))\n\n  it.effect(\"findFirstSTM - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeStair(n))\n      const fiber = yield* (pipe(\n        array,\n        TArray.findFirstSTM((n) => STM.succeed(n % largePrime === 0)),\n        Effect.fork\n      ))\n      yield* (pipe(\n        Chunk.range(1, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, () => 1)))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(\n        (Option.isSome(result) && result.value === largePrime) ||\n          Option.isNone(result)\n      )\n    }))\n\n  it.effect(\"findFirstSTM - fails on errors before result found\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.findFirstSTM((n) => n === 4 ? STM.fail(\"boom\") : STM.succeed(n % 5 === 0)),\n        STM.flip\n      ))\n      strictEqual(result, \"boom\")\n    }))\n\n  it.effect(\"findFirstSTM - succeeds on errors after result found\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.findFirstSTM((n) => n === 6 ? STM.fail(\"boom\") : STM.succeed(n % 5 === 0))\n      ))\n      assertSome(result, 5)\n    }))\n\n  it.effect(\"findLast - is correct\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findLast((n) => n % 5 === 0)))\n      assertSome(result, 10)\n    }))\n\n  it.effect(\"findLast - succeeds for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.findLast(constTrue)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findLast - fails to find absent\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findLast((i) => i > n)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findLast - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeStair(n))\n      const fiber = yield* (pipe(\n        array,\n        TArray.findLast((n) => n % largePrime === 0),\n        Effect.fork\n      ))\n      yield* (pipe(\n        Chunk.range(1, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, () => 1)))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(\n        (Option.isSome(result) && result.value === largePrime) ||\n          Option.isNone(result)\n      )\n    }))\n\n  it.effect(\"findLastIndex - correct index if in array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findLastIndex(2)))\n      assertSome(result, 7)\n    }))\n\n  it.effect(\"findLastIndex - none for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.findLastIndex(1)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findLastIndex - none if absent\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findLastIndex(4)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findLastIndexFrom - correct index if in array, with limit\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findLastIndexFrom(2, 6)))\n      assertSome(result, 4)\n    }))\n\n  it.effect(\"findLastIndexFrom - none if absent before limit\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findLastIndexFrom(3, 1)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findLastIndexFrom - none for a negative limit\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findLastIndexFrom(2, -1)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findLastIndexFrom - none for a limit that is too large\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeRepeats(3, 3))\n      const result = yield* (pipe(array, TArray.findLastIndexFrom(2, 9)))\n      assertNone(result)\n    }))\n\n  it.effect(\"findLastSTM - is correct\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findLastSTM((n) => STM.succeed(n % 5 === 0))))\n      assertSome(result, 10)\n    }))\n\n  it.effect(\"findLastSTM - succeeds for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.findLastSTM(() => STM.succeed(true))))\n      assertNone(result)\n    }))\n\n  it.effect(\"findLastSTM - fails to find absent\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.findLastSTM((i) => STM.succeed(i > n))))\n      assertNone(result)\n    }))\n\n  it.effect(\"findLastSTM - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeStair(n))\n      const fiber = yield* (pipe(\n        array,\n        TArray.findLastSTM((n) => STM.succeed(n % largePrime === 0)),\n        Effect.fork\n      ))\n      yield* (pipe(\n        Chunk.range(1, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, () => 1)))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(\n        (Option.isSome(result) && result.value === largePrime) ||\n          Option.isNone(result)\n      )\n    }))\n\n  it.effect(\"findLastSTM - succeeds on errors before result found\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.findLastSTM((n) => n === 4 ? STM.fail(\"boom\") : STM.succeed(n % 7 === 0))\n      ))\n      assertSome(result, 7)\n    }))\n\n  it.effect(\"findLastSTM - fails on errors after result found\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.findLastSTM((n) => n === 8 ? STM.fail(\"boom\") : STM.succeed(n % 7 === 0)),\n        STM.flip\n      ))\n      strictEqual(result, \"boom\")\n    }))\n\n  it.effect(\"forEach - side-effect is transactional\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const ref = yield* (TRef.make(0))\n      const array = yield* (makeTArray(n, 1))\n      const fiber = yield* (pipe(\n        array,\n        TArray.forEach((n) => pipe(ref, TRef.update((i) => i + n))),\n        Effect.fork\n      ))\n      const result = yield* (TRef.get(ref))\n      yield* (Fiber.join(fiber))\n      assertTrue(result === 0 || result === n)\n    }))\n\n  it.effect(\"get - should fail when the index is out of bounds\", () =>\n    Effect.gen(function*() {\n      const result = yield* (pipe(\n        makeTArray(1, 42),\n        STM.flatMap(TArray.get(-1)),\n        Effect.exit\n      ))\n      deepStrictEqual(result, Exit.die(new Cause.RuntimeException(\"Index out of bounds\")))\n    }))\n\n  it.effect(\"headOption - retrieves the first item in the array\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (TArray.headOption(array))\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"headOption - is none for an empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (TArray.headOption(array))\n      assertNone(result)\n    }))\n\n  it.effect(\"lastOption - retrieves the last entry\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (TArray.lastOption(array))\n      assertSome(result, n)\n    }))\n\n  it.effect(\"lastOption - is none for an empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (TArray.lastOption(array))\n      assertNone(result)\n    }))\n\n  it.effect(\"maxOption - computes correct maximum\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.maxOption(Number.Order)))\n      assertSome(result, n)\n    }))\n\n  it.effect(\"maxOption - returns none for an empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.maxOption(Number.Order)))\n      assertNone(result)\n    }))\n\n  it.effect(\"minOption - computes correct minimum\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.minOption(Number.Order)))\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"minOption - returns none for an empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.maxOption(Number.Order)))\n      assertNone(result)\n    }))\n\n  it.effect(\"reduce - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeTArray(n, 0))\n      const fiber = yield* (pipe(array, TArray.reduce(0, (x, y) => x + y), Effect.fork))\n      yield* (pipe(\n        Chunk.range(0, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, (n) => n + 1)))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(result === 0 || result === n)\n    }))\n\n  it.effect(\"reduceOption - reduces correctly\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.reduceOption((x, y) => x + y)))\n      assertSome(result, (n * (n + 1)) / 2)\n    }))\n\n  it.effect(\"reduceOption - single entry\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeTArray(1, 1))\n      const result = yield* (pipe(array, TArray.reduceOption((x, y) => x + y)))\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"reduceOption - none for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.reduceOption((x, y) => x + y)))\n      assertNone(result)\n    }))\n\n  it.effect(\"reduceOption - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeStair(n))\n      const fiber = yield* (pipe(array, TArray.reduceOption((x, y) => x + y), Effect.fork))\n      yield* (pipe(\n        Chunk.range(0, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, () => 1)))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(\n        Option.isSome(result) &&\n          (result.value === (n * (n + 1)) / 2 || result.value === n)\n      )\n    }))\n\n  it.effect(\"reduceOptionSTM - reduces correctly\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.reduceOptionSTM((x, y) => STM.succeed(x + y))))\n      assertSome(result, (n * (n + 1)) / 2)\n    }))\n\n  it.effect(\"reduceOptionSTM - single entry\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeTArray(1, 1))\n      const result = yield* (pipe(array, TArray.reduceOptionSTM((x, y) => STM.succeed(x + y))))\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"reduceOptionSTM - none for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.reduceOptionSTM((x, y) => STM.succeed(x + y))))\n      assertNone(result)\n    }))\n\n  it.effect(\"reduceOptionSTM - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeStair(n))\n      const fiber = yield* (pipe(array, TArray.reduceOptionSTM((x, y) => STM.succeed(x + y)), Effect.fork))\n      yield* (pipe(\n        Chunk.range(0, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, () => 1)))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(\n        Option.isSome(result) &&\n          (result.value === (n * (n + 1)) / 2 || result.value === n)\n      )\n    }))\n\n  it.effect(\"reduceOptionSTM - fails on errors\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.reduceOptionSTM((x, y) => y === 4 ? STM.fail(\"boom\") : STM.succeed(x + y)),\n        STM.flip\n      ))\n      strictEqual(result, \"boom\")\n    }))\n\n  it.effect(\"reduceSTM - is atomic\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeTArray(n, 0))\n      const fiber = yield* (pipe(array, TArray.reduceSTM(0, (x, y) => STM.succeed(x + y)), Effect.fork))\n      yield* (pipe(\n        Chunk.range(0, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, (n) => n + 1)))\n      ))\n      const result = yield* (Fiber.join(fiber))\n      assertTrue(result === 0 || result === n)\n    }))\n\n  it.effect(\"reduceSTM - returns failures\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const failInTheMiddle = (acc: number, n: number): STM.STM<number, string> =>\n        acc === Math.floor(n / 2) ? STM.fail(\"boom\") : STM.succeed(acc + n)\n      const array = yield* (makeTArray(n, 1))\n      const result = yield* (pipe(array, TArray.reduceSTM(0, failInTheMiddle), STM.either))\n      assertLeft(result, \"boom\")\n    }))\n\n  it.effect(\"size - returns the correct size\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = TArray.size(array)\n      strictEqual(result, n)\n    }))\n\n  it.effect(\"some - detects satisfaction\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.some((n) => n % 2 === 0)))\n      assertTrue(result)\n    }))\n\n  it.effect(\"some - detects lack of satisfaction\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.some((n) => n % 11 === 0)))\n      assertFalse(result)\n    }))\n\n  it.effect(\"some - false for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.some(constTrue)))\n      assertFalse(result)\n    }))\n\n  it.effect(\"someSTM - detects satisfaction\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.someSTM((n) => STM.succeed(n % 2 === 0))))\n      assertTrue(result)\n    }))\n\n  it.effect(\"someSTM - detects lack of satisfaction\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(array, TArray.someSTM((n) => STM.succeed(n % 11 === 0))))\n      assertFalse(result)\n    }))\n\n  it.effect(\"someSTM - false for empty array\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.empty<number>())\n      const result = yield* (pipe(array, TArray.someSTM(() => STM.succeed(true))))\n      assertFalse(result)\n    }))\n\n  it.effect(\"someSTM - fails for errors before witness\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.someSTM((n) => n === 4 ? STM.fail(\"boom\") : STM.succeed(n === 5)),\n        STM.flip\n      ))\n      strictEqual(result, \"boom\")\n    }))\n\n  it.effect(\"someSTM - fails for errors after witness\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeStair(n))\n      const result = yield* (pipe(\n        array,\n        TArray.someSTM((n) => n === 6 ? STM.fail(\"boom\") : STM.succeed(n === 5)),\n        STM.flip\n      ))\n      strictEqual(result, \"boom\")\n    }))\n\n  it.effect(\"transform - updates values atomically\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeTArray(n, \"a\"))\n      const fiber = yield* (pipe(array, TArray.transform((s) => s + \"+b\"), Effect.fork))\n      yield* (pipe(\n        Chunk.range(0, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, (s) => s + \"+c\")))\n      ))\n      yield* (Fiber.join(fiber))\n      const first = yield* (pipe(array, TArray.get(0)))\n      const last = yield* (pipe(array, TArray.get(n - 1)))\n      assertTrue(\n        (first === \"a+b+c\" && last === \"a+b+c\") ||\n          (first === \"a+c+b\" && last === \"a+c+b\")\n      )\n    }))\n\n  it.effect(\"transformSTM - updates values atomically\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeTArray(n, \"a\"))\n      const fiber = yield* (pipe(array, TArray.transformSTM((s) => STM.succeed(s + \"+b\")), Effect.fork))\n      yield* (pipe(\n        Chunk.range(0, n - 1),\n        STM.forEach((n) => pipe(array, TArray.update(n, (s) => s + \"+c\")))\n      ))\n      yield* (Fiber.join(fiber))\n      const first = yield* (pipe(array, TArray.get(0)))\n      const last = yield* (pipe(array, TArray.get(n - 1)))\n      assertTrue(\n        (first === \"a+b+c\" && last === \"a+b+c\") ||\n          (first === \"a+c+b\" && last === \"a+c+b\")\n      )\n    }))\n\n  it.effect(\"transformSTM - updates all or nothing\", () =>\n    Effect.gen(function*() {\n      const n = 1_000\n      const array = yield* (makeTArray(n, 0))\n      yield* (pipe(array, TArray.update(Math.floor(n / 2), () => 1)))\n      const result = yield* (pipe(\n        array,\n        TArray.transformSTM((n) => n === 0 ? STM.succeed(42) : STM.fail(\"boom\")),\n        STM.either\n      ))\n      const first = yield* (pipe(array, TArray.get(0)))\n      strictEqual(first, 0)\n      assertLeft(result, \"boom\")\n    }))\n\n  it.effect(\"update - happy path\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeTArray(1, 42))\n      const result = yield* (pipe(\n        array,\n        TArray.update(0, (n) => -n),\n        STM.zipRight(valuesOf(array))\n      ))\n      deepStrictEqual(result, [-42])\n    }))\n\n  it.effect(\"update - dies with index out of bounds\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeTArray(1, 42))\n      const result = yield* (pipe(array, TArray.update(-1, identity), Effect.exit))\n      deepStrictEqual(result, Exit.die(new Cause.RuntimeException(\"Index out of bounds\")))\n    }))\n\n  it.effect(\"updateSTM - happy path\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeTArray(1, 42))\n      const result = yield* (pipe(\n        array,\n        TArray.updateSTM(0, (n) => STM.succeed(-n)),\n        STM.zipRight(valuesOf(array))\n      ))\n      deepStrictEqual(result, [-42])\n    }))\n\n  it.effect(\"updateSTM - dies with index out of bounds\", () =>\n    Effect.gen(function*() {\n      const array = yield* (makeTArray(1, 42))\n      const result = yield* (pipe(array, TArray.updateSTM(-1, (n) => STM.succeed(n)), Effect.exit))\n      deepStrictEqual(result, Exit.die(new Cause.RuntimeException(\"Index out of bounds\")))\n    }))\n\n  it.effect(\"updateSTM - handles failures\", () =>\n    Effect.gen(function*() {\n      const n = 10\n      const array = yield* (makeTArray(n, 0))\n      const result = yield* (pipe(\n        array,\n        TArray.updateSTM(0, (_: number) => STM.fail(\"boom\")),\n        STM.commit,\n        Effect.either\n      ))\n      assertLeft(result, \"boom\")\n    }))\n\n  it.effect(\"toChunk\", () =>\n    Effect.gen(function*() {\n      const array = yield* (TArray.make(1, 2, 3, 4, 5))\n      const result = yield* (TArray.toArray(array))\n      deepStrictEqual(Array.from(result), [1, 2, 3, 4, 5])\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/TMap.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertNone, assertSome, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Array, Chunk, Effect, Equal, Exit, FastCheck as fc, Hash, Option, pipe, STM, TMap } from \"effect\"\nimport { equivalentElements } from \"./utils/equals.js\"\n\nclass HashContainer implements Equal.Equal {\n  constructor(readonly i: number) {}\n  [Hash.symbol](): number {\n    return this.i\n  }\n  [Equal.symbol](that: unknown): boolean {\n    return that instanceof HashContainer && this.i === that.i\n  }\n}\n\nconst mapEntriesArb: fc.Arbitrary<Array<readonly [string, number]>> = fc.uniqueArray(fc.char())\n  .chain((keys) =>\n    fc.uniqueArray(fc.integer())\n      .map((values) => pipe(keys, Array.zip(values)))\n  )\n\ndescribe(\"TMap\", () => {\n  it.effect(\"empty\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.empty<string, number>(),\n        STM.flatMap(TMap.isEmpty)\n      )\n      const result = yield* (STM.commit(transaction))\n      assertTrue(result)\n    }))\n\n  it.effect(\"fromIterable\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.fromIterable([[\"a\", 1], [\"b\", 2], [\"c\", 2], [\"b\", 3]]),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [[\"a\", 1], [\"b\", 3], [\"c\", 2]])\n    }))\n\n  it.effect(\"get - existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"b\", 2]),\n        STM.flatMap(TMap.get(\"a\"))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"get - non-existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.empty<string, number>(),\n        STM.flatMap(TMap.get(\"a\"))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertNone(result)\n    }))\n\n  it.effect(\"getOrElse - existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"b\", 2]),\n        STM.flatMap(TMap.getOrElse(\"a\", () => 10))\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, 1)\n    }))\n\n  it.effect(\"getOrElse - non-existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.empty<string, number>(),\n        STM.flatMap(TMap.getOrElse(\"a\", () => 10))\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, 10)\n    }))\n\n  it.effect(\"has - existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"b\", 2]),\n        STM.flatMap(TMap.has(\"a\"))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertTrue(result)\n    }))\n\n  it.effect(\"has - non-existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.empty<string, number>(),\n        STM.flatMap(TMap.has(\"a\"))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertFalse(result)\n    }))\n\n  it(\"keys - collect all keys\", () =>\n    fc.assert(fc.asyncProperty(mapEntriesArb, async (entries) => {\n      const transaction = pipe(\n        TMap.fromIterable(entries),\n        STM.flatMap(TMap.keys)\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      const keys = entries.map((entry) => entry[0])\n      strictEqual(pipe(result, Array.differenceWith(equivalentElements())(keys)).length, 0)\n      strictEqual(pipe(keys, Array.differenceWith(equivalentElements())(result)).length, 0)\n    })))\n\n  it.effect(\"merge\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1]),\n        STM.flatMap((map) =>\n          STM.all({\n            result1: pipe(map, TMap.merge(\"a\", 2, (x, y) => x + y)),\n            result2: pipe(map, TMap.merge(\"b\", 2, (x, y) => x + y))\n          })\n        )\n      )\n      const { result1, result2 } = yield* (STM.commit(transaction))\n      strictEqual(result1, 3)\n      strictEqual(result2, 2)\n    }))\n\n  it.effect(\"reduce - non-empty map\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"b\", 2], [\"c\", 3]),\n        STM.flatMap(TMap.reduce(0, (acc, value) => acc + value))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 6)\n    }))\n\n  it.effect(\"reduce - empty map\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.empty<string, number>(),\n        STM.flatMap(TMap.reduce(0, (acc, value) => acc + value))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"reduceSTM - non-empty map\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"b\", 2], [\"c\", 3]),\n        STM.flatMap(TMap.reduceSTM(0, (acc, value) => STM.succeed(acc + value)))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 6)\n    }))\n\n  it.effect(\"reduceSTM - empty map\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.empty<string, number>(),\n        STM.flatMap(TMap.reduceSTM(0, (acc, value) => STM.succeed(acc + value)))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"remove - remove an existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"b\", 2]),\n        STM.tap(TMap.remove(\"a\")),\n        STM.flatMap(TMap.get(\"a\"))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertNone(result)\n    }))\n\n  it.effect(\"remove - remove an non-existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.empty<string, number>(),\n        STM.tap(TMap.remove(\"a\")),\n        STM.flatMap(TMap.get(\"a\"))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertNone(result)\n    }))\n\n  it.effect(\"removeIf\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const map = yield* (TMap.make([\"a\", 1], [\"aa\", 2], [\"aaa\", 3]))\n        const removed = yield* (pipe(map, TMap.removeIf((_, value) => value > 1)))\n        const a = yield* (pipe(map, TMap.has(\"a\")))\n        const aa = yield* (pipe(map, TMap.has(\"aa\")))\n        const aaa = yield* (pipe(map, TMap.has(\"aaa\")))\n        return [removed, a, aa, aaa] as const\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [[[\"aaa\", 3], [\"aa\", 2]], true, false, false])\n    }))\n\n  it.effect(\"removeIf > { discard: true }\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const map = yield* (TMap.make([\"a\", 1], [\"aa\", 2], [\"aaa\", 3]))\n        yield* (pipe(map, TMap.removeIf((key) => key === \"aa\", { discard: true })))\n        const a = yield* (pipe(map, TMap.has(\"a\")))\n        const aa = yield* (pipe(map, TMap.has(\"aa\")))\n        const aaa = yield* (pipe(map, TMap.has(\"aaa\")))\n        return [a, aa, aaa] as const\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [true, false, true])\n    }))\n\n  it.effect(\"retainIf\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const map = yield* (TMap.make([\"a\", 1], [\"aa\", 2], [\"aaa\", 3]))\n        const removed = yield* (pipe(map, TMap.retainIf((key) => key === \"aa\")))\n        const a = yield* (pipe(map, TMap.has(\"a\")))\n        const aa = yield* (pipe(map, TMap.has(\"aa\")))\n        const aaa = yield* (pipe(map, TMap.has(\"aaa\")))\n        return [removed, a, aa, aaa] as const\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [[[\"aaa\", 3], [\"a\", 1]], false, true, false])\n    }))\n\n  it.effect(\"retainIf > { discard: true }\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const map = yield* (TMap.make([\"a\", 1], [\"aa\", 2], [\"aaa\", 3]))\n        yield* (pipe(map, TMap.retainIf((key) => key === \"aa\", { discard: true })))\n        const a = yield* (pipe(map, TMap.has(\"a\")))\n        const aa = yield* (pipe(map, TMap.has(\"aa\")))\n        const aaa = yield* (pipe(map, TMap.has(\"aaa\")))\n        return [a, aa, aaa] as const\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [false, true, false])\n    }))\n\n  it.effect(\"set - adds new element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.empty<string, number>(),\n        STM.tap(TMap.set(\"a\", 1)),\n        STM.flatMap(TMap.get(\"a\"))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"set - overwrites an existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"b\", 2]),\n        STM.tap(TMap.set(\"a\", 10)),\n        STM.flatMap(TMap.get(\"a\"))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertSome(result, 10)\n    }))\n\n  it.effect(\"set - add many keys with negative hash codes\", () =>\n    Effect.gen(function*() {\n      const entries = Array.makeBy(1_000, (i) => i + 1)\n        .map((i) => [new HashContainer(i), i] as const)\n      const transaction = pipe(\n        TMap.empty<HashContainer, number>(),\n        STM.tap((map) => STM.all(entries.map((entry) => pipe(map, TMap.set(entry[0], entry[1]))))),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(pipe(result, Array.differenceWith(equivalentElements())(entries)).length, 0)\n      strictEqual(pipe(entries, Array.differenceWith(equivalentElements())(result)).length, 0)\n    }))\n\n  it.effect(\"setIfAbsent\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1]),\n        STM.tap(TMap.setIfAbsent(\"b\", 2)),\n        STM.tap(TMap.setIfAbsent(\"a\", 10)),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      const expected = [[\"a\", 1], [\"b\", 2]]\n      strictEqual(pipe(result, Array.differenceWith(equivalentElements())(expected)).length, 0)\n      strictEqual(pipe(expected, Array.differenceWith(equivalentElements())(result)).length, 0)\n    }))\n\n  it.effect(\"size\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.fromIterable([[\"a\", 1], [\"b\", 2]]),\n        STM.flatMap(TMap.size)\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 2)\n    }))\n\n  it(\"toChunk - collect all elements\", () =>\n    fc.assert(fc.asyncProperty(mapEntriesArb, async (entries) => {\n      const transaction = pipe(\n        TMap.fromIterable(entries),\n        STM.flatMap(TMap.toChunk)\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      assertTrue(Chunk.isChunk(result))\n      strictEqual(pipe(Chunk.toReadonlyArray(result), Array.differenceWith(equivalentElements())(entries)).length, 0)\n      strictEqual(pipe(entries, Array.differenceWith(equivalentElements())(Chunk.toReadonlyArray(result))).length, 0)\n    })))\n\n  it(\"toReadonlyArray - collect all elements\", () =>\n    fc.assert(fc.asyncProperty(mapEntriesArb, async (entries) => {\n      const transaction = pipe(\n        TMap.fromIterable(entries),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      strictEqual(pipe(result, Array.differenceWith(equivalentElements())(entries)).length, 0)\n      strictEqual(pipe(entries, Array.differenceWith(equivalentElements())(result)).length, 0)\n    })))\n\n  it(\"toMap - collect all elements\", () =>\n    fc.assert(fc.asyncProperty(mapEntriesArb, async (entries) => {\n      const transaction = pipe(\n        TMap.fromIterable(entries),\n        STM.flatMap(TMap.toMap)\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      strictEqual(pipe(Array.fromIterable(result), Array.differenceWith(equivalentElements())(entries)).length, 0)\n      strictEqual(pipe(entries, Array.differenceWith(equivalentElements())(Array.fromIterable(result))).length, 0)\n    })))\n\n  it.effect(\"transform\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"aa\", 2], [\"aaa\", 3]),\n        STM.tap((map) => TMap.transform(map, (key, value) => [key.replaceAll(\"a\", \"b\"), value * 2])),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      const expected = [[\"b\", 2], [\"bb\", 4], [\"bbb\", 6]]\n      strictEqual(pipe(result, Array.differenceWith(equivalentElements())(expected)).length, 0)\n      strictEqual(pipe(expected, Array.differenceWith(equivalentElements())(result)).length, 0)\n    }))\n\n  it.effect(\"transform - handles keys with negative hash codes\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([new HashContainer(-1), 1], [new HashContainer(-2), 2], [new HashContainer(-3), 3]),\n        STM.tap((map) => TMap.transform(map, (key, value) => [new HashContainer(key.i * -2), value * 2])),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      const expected = [[new HashContainer(2), 2], [new HashContainer(4), 4], [new HashContainer(6), 6]]\n      strictEqual(pipe(result, Array.differenceWith(equivalentElements())(expected)).length, 0)\n      strictEqual(pipe(expected, Array.differenceWith(equivalentElements())(result)).length, 0)\n    }))\n\n  it.effect(\"transform - and shrink\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"aa\", 2], [\"aaa\", 3]),\n        STM.tap((map) => TMap.transform(map, (_, value) => [\"key\", value * 2])),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [[\"key\", 6]])\n    }))\n\n  it.effect(\"transformSTM\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"aa\", 2], [\"aaa\", 3]),\n        STM.tap((map) => TMap.transformSTM(map, (key, value) => STM.succeed([key.replaceAll(\"a\", \"b\"), value * 2]))),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      const expected = [[\"b\", 2], [\"bb\", 4], [\"bbb\", 6]]\n      strictEqual(pipe(result, Array.differenceWith(equivalentElements())(expected)).length, 0)\n      strictEqual(pipe(expected, Array.differenceWith(equivalentElements())(result)).length, 0)\n    }))\n\n  it.effect(\"transformSTM - and shrink\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"aa\", 2], [\"aaa\", 3]),\n        STM.tap((map) => TMap.transformSTM(map, (_, value) => STM.succeed([\"key\", value * 2]))),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [[\"key\", 6]])\n    }))\n\n  it.effect(\"transformValues\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"aa\", 2], [\"aaa\", 3]),\n        STM.tap((map) => TMap.transformValues(map, (value) => value * 2)),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      const expected = [[\"a\", 2], [\"aa\", 4], [\"aaa\", 6]]\n      strictEqual(pipe(result, Array.differenceWith(equivalentElements())(expected)).length, 0)\n      strictEqual(pipe(expected, Array.differenceWith(equivalentElements())(result)).length, 0)\n    }))\n\n  it.effect(\"transformValues - parallel\", () =>\n    Effect.gen(function*() {\n      const map = yield* (TMap.make([\"a\", 0]))\n      const effect = pipe(\n        map,\n        TMap.transformValues((n) => n + 1),\n        STM.commit,\n        Effect.repeatN(999)\n      )\n      yield* (Effect.replicateEffect(effect, 2))\n      const result = yield* (pipe(map, TMap.get(\"a\")))\n      assertSome(result, 2_000)\n    }))\n\n  it.effect(\"transformValuesSTM\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TMap.make([\"a\", 1], [\"aa\", 2], [\"aaa\", 3]),\n        STM.tap((map) => TMap.transformValuesSTM(map, (value) => STM.succeed(value * 2))),\n        STM.flatMap(TMap.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      const expected = [[\"a\", 2], [\"aa\", 4], [\"aaa\", 6]]\n      strictEqual(pipe(result, Array.differenceWith(equivalentElements())(expected)).length, 0)\n      strictEqual(pipe(expected, Array.differenceWith(equivalentElements())(result)).length, 0)\n    }))\n\n  it.effect(\"updateWith\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const map = yield* (TMap.make([\"a\", 1], [\"b\", 2]))\n        yield* (pipe(map, TMap.updateWith(\"a\", Option.map((n) => n + 1))))\n        yield* (pipe(map, TMap.updateWith<string, number>(\"b\", () => Option.none())))\n        yield* (pipe(map, TMap.updateWith(\"c\", () => Option.some(3))))\n        yield* (pipe(map, TMap.updateWith<string, number>(\"d\", () => Option.none())))\n        return yield* (TMap.toArray(map))\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [[\"a\", 2], [\"c\", 3]])\n    }))\n\n  it(\"values - collect all values\", () =>\n    fc.assert(fc.asyncProperty(mapEntriesArb, async (entries) => {\n      const transaction = pipe(\n        TMap.fromIterable(entries),\n        STM.flatMap(TMap.values)\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      const values = entries.map((entry) => entry[1])\n      strictEqual(pipe(result, Array.differenceWith(equivalentElements())(values)).length, 0)\n      strictEqual(pipe(values, Array.differenceWith(equivalentElements())(result)).length, 0)\n    })))\n\n  it.effect(\"avoid issues due to race conditions (ZIO Issue #4648)\", () =>\n    Effect.gen(function*() {\n      const keys = Array.range(0, 10)\n      const map = yield* (TMap.fromIterable(Array.map(keys, (n, i) => [n, i])))\n      const result = yield* (pipe(\n        Effect.forEach(keys, (key) =>\n          pipe(\n            TMap.remove(map, key),\n            STM.commit,\n            Effect.fork,\n            Effect.zipRight(TMap.toChunk(map)),\n            Effect.asVoid\n          ), { discard: true }),\n        Effect.exit\n      ))\n      deepStrictEqual(result, Exit.void)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/TPriorityQueue.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport {\n  Array as Arr,\n  Effect,\n  FastCheck as fc,\n  Number as number,\n  Option,\n  Order,\n  pipe,\n  STM,\n  TPriorityQueue\n} from \"effect\"\nimport { equivalentElements } from \"./utils/equals.js\"\n\ninterface Event {\n  readonly time: number\n  readonly description: string\n}\n\nconst orderByTime: Order.Order<Event> = pipe(\n  number.Order,\n  Order.mapInput((event) => event.time)\n)\n\nconst eventArb: fc.Arbitrary<Event> = fc.tuple(\n  fc.integer({ min: -10, max: 10 }),\n  fc.asciiString({ minLength: 1 })\n).map(([time, description]) => ({ time, description }))\n\nconst eventsArb: fc.Arbitrary<Array<Event>> = fc.array(eventArb)\n\nconst predicateArb: fc.Arbitrary<(event: Event) => boolean> = fc.func(fc.boolean()).map((f) => (e: Event) => f(e))\n\ndescribe(\"TPriorityQueue\", () => {\n  it(\"isEmpty\", () =>\n    fc.assert(fc.asyncProperty(eventsArb, async (events) => {\n      const transaction = pipe(\n        TPriorityQueue.empty<Event>(orderByTime),\n        STM.tap(TPriorityQueue.offerAll(events)),\n        STM.flatMap(TPriorityQueue.isEmpty)\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      strictEqual(result, events.length === 0)\n    })))\n\n  it(\"isNonEmpty\", () =>\n    fc.assert(fc.asyncProperty(eventsArb, async (events) => {\n      const transaction = pipe(\n        TPriorityQueue.empty<Event>(orderByTime),\n        STM.tap(TPriorityQueue.offerAll(events)),\n        STM.flatMap(TPriorityQueue.isNonEmpty)\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      strictEqual(result, events.length > 0)\n    })))\n\n  it(\"offerAll and takeAll\", () =>\n    fc.assert(fc.asyncProperty(eventsArb, async (events) => {\n      const transaction = pipe(\n        TPriorityQueue.empty<Event>(orderByTime),\n        STM.tap(TPriorityQueue.offerAll(events)),\n        STM.flatMap(TPriorityQueue.takeAll),\n        STM.map((chunk) => Array.from(chunk))\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      strictEqual(pipe(result, Arr.differenceWith(equivalentElements())(events)).length, 0)\n      strictEqual(pipe(events, Arr.differenceWith(equivalentElements())(result)).length, 0)\n      deepStrictEqual(result, pipe(result, Arr.sort(orderByTime)))\n    })))\n\n  it(\"removeIf\", () =>\n    fc.assert(fc.asyncProperty(eventsArb, predicateArb, async (events, f) => {\n      const transaction = pipe(\n        TPriorityQueue.fromIterable(orderByTime)(events),\n        STM.tap(TPriorityQueue.removeIf(f)),\n        STM.flatMap(TPriorityQueue.toArray)\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      const filtered = Arr.filter(events, (a) => !f(a))\n      strictEqual(Arr.differenceWith(equivalentElements())(result, filtered).length, 0)\n      strictEqual(Arr.differenceWith(equivalentElements())(filtered, result).length, 0)\n      deepStrictEqual(result, Arr.sort(orderByTime)(result))\n    })))\n\n  it(\"retainIf\", () =>\n    fc.assert(fc.asyncProperty(eventsArb, predicateArb, async (events, f) => {\n      const transaction = pipe(\n        TPriorityQueue.fromIterable(orderByTime)(events),\n        STM.tap(TPriorityQueue.retainIf(f)),\n        STM.flatMap(TPriorityQueue.toArray)\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      const filtered = Arr.filter(events, f)\n      strictEqual(Arr.differenceWith(equivalentElements())(result, filtered).length, 0)\n      strictEqual(Arr.differenceWith(equivalentElements())(filtered, result).length, 0)\n      deepStrictEqual(result, Arr.sort(orderByTime)(result))\n    })))\n\n  it(\"take\", () =>\n    fc.assert(fc.asyncProperty(eventsArb, async (events) => {\n      const transaction = pipe(\n        TPriorityQueue.fromIterable(orderByTime)(events),\n        STM.flatMap((queue) =>\n          STM.all(pipe(\n            TPriorityQueue.take(queue),\n            STM.replicate(events.length)\n          ))\n        ),\n        STM.map((chunk) => Array.from(chunk))\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      strictEqual(pipe(result, Arr.differenceWith(equivalentElements())(events)).length, 0)\n      strictEqual(pipe(events, Arr.differenceWith(equivalentElements())(result)).length, 0)\n      deepStrictEqual(result, pipe(result, Arr.sort(orderByTime)))\n    })))\n\n  it(\"takeOption\", () =>\n    fc.assert(\n      fc.asyncProperty(eventsArb.filter((events) => events.length > 0), async (events) => {\n        const transaction = pipe(\n          TPriorityQueue.fromIterable(orderByTime)(events),\n          STM.flatMap((queue) =>\n            pipe(\n              TPriorityQueue.takeOption(queue),\n              STM.tap(() => TPriorityQueue.takeAll(queue)),\n              STM.flatMap((left) =>\n                pipe(\n                  TPriorityQueue.takeOption(queue),\n                  STM.map((right) => [left, right] as const)\n                )\n              )\n            )\n          )\n        )\n        const result = await Effect.runPromise(STM.commit(transaction))\n        assertTrue(Option.isSome(result[0]))\n        assertTrue(Option.isNone(result[1]))\n      })\n    ))\n\n  it(\"takeUpTo\", () =>\n    fc.assert(\n      fc.asyncProperty(\n        eventsArb.chain((events) => fc.tuple(fc.constant(events), fc.integer({ min: 0, max: events.length }))),\n        async ([events, n]) => {\n          const transaction = pipe(\n            TPriorityQueue.fromIterable(orderByTime)(events),\n            STM.flatMap((queue) =>\n              pipe(\n                queue,\n                TPriorityQueue.takeUpTo(n),\n                STM.flatMap((left) =>\n                  pipe(\n                    TPriorityQueue.takeAll(queue),\n                    STM.map((right) => [...left, ...right])\n                  )\n                )\n              )\n            )\n          )\n          const result = await Effect.runPromise(STM.commit(transaction))\n          strictEqual(pipe(result, Arr.differenceWith(equivalentElements())(events)).length, 0)\n          strictEqual(pipe(events, Arr.differenceWith(equivalentElements())(result)).length, 0)\n          deepStrictEqual(result, pipe(result, Arr.sort(orderByTime)))\n        }\n      )\n    ))\n\n  it(\"toChunk\", () =>\n    fc.assert(fc.asyncProperty(eventsArb, async (events) => {\n      const transaction = pipe(\n        TPriorityQueue.fromIterable(orderByTime)(events),\n        STM.flatMap(TPriorityQueue.toChunk),\n        STM.map((chunk) => Array.from(chunk))\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      strictEqual(pipe(result, Arr.differenceWith(equivalentElements())(events)).length, 0)\n      strictEqual(pipe(events, Arr.differenceWith(equivalentElements())(result)).length, 0)\n      deepStrictEqual(result, pipe(result, Arr.sort(orderByTime)))\n    })))\n\n  it(\"toReadonlyArray\", () =>\n    fc.assert(fc.asyncProperty(eventsArb, async (events) => {\n      const transaction = pipe(\n        TPriorityQueue.fromIterable(orderByTime)(events),\n        STM.flatMap(TPriorityQueue.toArray)\n      )\n      const result = await Effect.runPromise(STM.commit(transaction))\n      strictEqual(pipe(result, Arr.differenceWith(equivalentElements())(events)).length, 0)\n      strictEqual(pipe(events, Arr.differenceWith(equivalentElements())(result)).length, 0)\n      deepStrictEqual(result, pipe(result, Arr.sort(orderByTime)))\n    })))\n})\n"
  },
  {
    "path": "packages/effect/test/TPubSub.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport {\n  Array as Arr,\n  Deferred,\n  Effect,\n  FastCheck as fc,\n  Fiber,\n  Number as number,\n  pipe,\n  STM,\n  TPubSub,\n  TQueue\n} from \"effect\"\n\nconst sort: (array: ReadonlyArray<number>) => ReadonlyArray<number> = Arr.sort(number.Order)\n\ndescribe(\"TPubSub\", () => {\n  it(\"sequential publishers and subscribers - with one publisher and one subscriber\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer()), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.bounded<number>(n))\n        const subscriber = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(Deferred.await(deferred2)),\n              Effect.zipRight(pipe(\n                as.slice(0, n),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (pipe(\n          as.slice(0, n),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n)))\n        ))\n        yield* (pipe(deferred2, Deferred.succeed<void>(void 0)))\n        return yield* (Fiber.join(subscriber))\n      })\n      const result = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result), as.slice(0, n))\n    })))\n\n  it(\"sequential publishers and subscribers - with one publisher and two subscribers\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer()), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const deferred3 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.bounded<number>(n))\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(Deferred.await(deferred3)),\n              Effect.zipRight(pipe(\n                as.slice(0, n),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(Deferred.await(deferred3)),\n              Effect.zipRight(pipe(\n                as.slice(0, n),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(\n          as.slice(0, n),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n)))\n        ))\n        yield* (pipe(deferred3, Deferred.succeed<void>(void 0)))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result1), as.slice(0, n))\n      deepStrictEqual(Array.from(result2), as.slice(0, n))\n    })))\n\n  it(\"concurrent publishers and subscribers - one to one\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer()), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.bounded<number>(n))\n        const subscriber = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(as.slice(0, n), Effect.forEach(() => TQueue.take(subscription))))\n            )\n          ),\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred))\n        yield* (pipe(\n          as.slice(0, n),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        return yield* (Fiber.join(subscriber))\n      })\n      const result = await Effect.runPromise(Effect.scoped(program))\n      deepStrictEqual(Array.from(result), as.slice(0, n))\n    })))\n\n  it(\"concurrent publishers and subscribers - one to many\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer()), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.bounded<number>(n))\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(as.slice(0, n), Effect.forEach(() => TQueue.take(subscription))))\n            )\n          ),\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(as.slice(0, n), Effect.forEach(() => TQueue.take(subscription))))\n            )\n          ),\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(\n          as.slice(0, n),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(Effect.scoped(program))\n      deepStrictEqual(Array.from(result1), as.slice(0, n))\n      deepStrictEqual(Array.from(result2), as.slice(0, n))\n    })))\n\n  it(\"concurrent publishers and subscribers - many to many\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer({ min: 1 })), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.bounded<number>(n * 2))\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                [...as, ...as].slice(0, n * 2),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                [...as, ...as].slice(0, n * 2),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(\n          as.slice(0, n),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        yield* (pipe(\n          as.slice(0, n).map((n) => n !== 0 ? -n : n),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(program)\n      deepStrictEqual(\n        Array.from(result1).filter((n) => n > 0),\n        as.slice(0, n)\n      )\n      deepStrictEqual(\n        Array.from(result1).filter((n) => n < 0),\n        as.slice(0, n).map((n) => -n)\n      )\n      deepStrictEqual(\n        Array.from(result2).filter((n) => n > 0),\n        as.slice(0, n)\n      )\n      deepStrictEqual(\n        Array.from(result2).filter((n) => n < 0),\n        as.slice(0, n).map((n) => -n)\n      )\n    })))\n\n  it(\"back pressure - one to one\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer({ min: 1 })), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.bounded<number>(n))\n        const subscriber = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(as, Effect.forEach(() => TQueue.take(subscription))))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred))\n        yield* (pipe(as, Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n        return yield* (Fiber.join(subscriber))\n      })\n      const result = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result), as)\n    })))\n\n  it(\"back pressure - one to many\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer({ min: 1 })), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.bounded<number>(n))\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(as, Effect.forEach(() => TQueue.take(subscription))))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(as, Effect.forEach(() => TQueue.take(subscription))))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(as, Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result1), as)\n      deepStrictEqual(Array.from(result2), as)\n    })))\n\n  it(\"back pressure - many to many\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer({ min: 1 })), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.bounded<number>(n * 2))\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                [...as, ...as],\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                [...as, ...as],\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(\n          as,\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        yield* (pipe(\n          as.map((n) => -n),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result1).filter((n) => n > 0), as)\n      deepStrictEqual(Array.from(result1).filter((n) => n < 0), as.map((n) => -n))\n      deepStrictEqual(Array.from(result2).filter((n) => n > 0), as)\n      deepStrictEqual(Array.from(result2).filter((n) => n < 0), as.map((n) => -n))\n    })))\n\n  it(\"dropping - one to one\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer({ min: 1 })), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.dropping<number>(n))\n        const subscriber = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                as.slice(0, n),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred))\n        yield* (pipe(as, Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n        return yield* (Fiber.join(subscriber))\n      })\n      const result = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result), as.slice(0, n))\n    })))\n\n  it(\"dropping - one to many\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer({ min: 1 })), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.dropping<number>(n))\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                as.slice(0, n),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                as.slice(0, n),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(as, Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result1), as.slice(0, n))\n      deepStrictEqual(Array.from(result2), as.slice(0, n))\n    })))\n\n  it(\"dropping - many to many\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer({ min: 1 })), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.dropping<number>(n * 2))\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                [...as, ...as].slice(0, n * 2),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                [...as, ...as].slice(0, n * 2),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(\n          as,\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        yield* (pipe(\n          as.map((n) => -n),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(program)\n      deepStrictEqual(\n        Array.from(result1).filter((n) => n > 0),\n        as.slice(0, Array.from(result1).filter((n) => n > 0).length)\n      )\n      deepStrictEqual(\n        Array.from(result1).filter((n) => n < 0),\n        as.slice(0, n).map((n) => -n).slice(0, Array.from(result1).filter((n) => n < 0).length)\n      )\n      deepStrictEqual(\n        Array.from(result2).filter((n) => n > 0),\n        as.slice(0, Array.from(result2).filter((n) => n > 0).length)\n      )\n      deepStrictEqual(\n        Array.from(result2).filter((n) => n < 0),\n        as.slice(0, n).map((n) => -n).slice(0, Array.from(result2).filter((n) => n < 0).length)\n      )\n    })))\n\n  it(\"sliding - one to one\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer({ min: 1 })), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.sliding<number>(n))\n        const subscriber = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                as.slice(0, n),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred))\n        const publisher = yield* (pipe(sort(as), Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n        yield* (Fiber.join(publisher))\n        return yield* (Fiber.join(subscriber))\n      })\n      const result = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result), sort(Array.from(result)))\n    })))\n\n  it(\"sliding - one to many\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer({ min: 1 })), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.sliding<number>(n))\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                as.slice(0, n),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                as.slice(0, n),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(sort(as), Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result1), sort(Array.from(result1)))\n      deepStrictEqual(Array.from(result2), sort(Array.from(result2)))\n    })))\n\n  it(\"sliding - many to many\", () =>\n    fc.assert(fc.asyncProperty(fc.integer({ min: 1 }), fc.array(fc.integer({ min: 1 })), async (n, as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.sliding<number>(n * 2))\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                [...as, ...as].slice(0, n * 2),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                [...as, ...as].slice(0, n * 2),\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(\n          sort(as),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        yield* (pipe(\n          sort(as.map((n) => -n)),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(program)\n      deepStrictEqual(\n        Array.from(result1).filter((n) => n > 0),\n        sort(Array.from(result1).filter((n) => n > 0))\n      )\n      deepStrictEqual(\n        Array.from(result1).filter((n) => n < 0),\n        sort(Array.from(result1).filter((n) => n < 0))\n      )\n      deepStrictEqual(\n        Array.from(result2).filter((n) => n > 0),\n        sort(Array.from(result2).filter((n) => n > 0))\n      )\n      deepStrictEqual(\n        Array.from(result2).filter((n) => n < 0),\n        sort(Array.from(result2).filter((n) => n < 0))\n      )\n    })))\n\n  it(\"unbounded - one to one\", () =>\n    fc.assert(fc.asyncProperty(fc.array(fc.integer({ min: 1 })), async (as) => {\n      const program = Effect.gen(function*() {\n        const deferred = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.unbounded<number>())\n        const subscriber = yield* (pipe(\n          STM.commit(TPubSub.subscribe(pubsub)),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(as, Effect.forEach(() => TQueue.take(subscription))))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred))\n        yield* (pipe(as, Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n        return yield* (Fiber.join(subscriber))\n      })\n      const result = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result), as)\n    })))\n\n  it(\"unbounded - one to many\", () =>\n    fc.assert(fc.asyncProperty(fc.array(fc.integer({ min: 1 })), async (as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.unbounded<number>())\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(as, Effect.forEach(() => TQueue.take(subscription))))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(as, Effect.forEach(() => TQueue.take(subscription))))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(as, Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result1), as)\n      deepStrictEqual(Array.from(result2), as)\n    })))\n\n  it(\"unbounded - many to many\", () =>\n    fc.assert(fc.asyncProperty(fc.array(fc.integer({ min: 1 })), async (as) => {\n      const program = Effect.gen(function*() {\n        const deferred1 = yield* (Deferred.make<void>())\n        const deferred2 = yield* (Deferred.make<void>())\n        const pubsub = yield* (TPubSub.unbounded<number>())\n        const subscriber1 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred1,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                [...as, ...as],\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        const subscriber2 = yield* (pipe(\n          TPubSub.subscribeScoped(pubsub),\n          Effect.flatMap((subscription) =>\n            pipe(\n              deferred2,\n              Deferred.succeed<void>(void 0),\n              Effect.zipRight(pipe(\n                [...as, ...as],\n                Effect.forEach(() => TQueue.take(subscription))\n              ))\n            )\n          ),\n          Effect.scoped,\n          Effect.fork\n        ))\n        yield* (Deferred.await(deferred1))\n        yield* (Deferred.await(deferred2))\n        yield* (pipe(\n          as,\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        yield* (pipe(\n          as.map((n) => -n),\n          Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))),\n          Effect.fork\n        ))\n        const result1 = yield* (Fiber.join(subscriber1))\n        const result2 = yield* (Fiber.join(subscriber2))\n        return { result1, result2 }\n      })\n      const { result1, result2 } = await Effect.runPromise(program)\n      deepStrictEqual(Array.from(result1).filter((n) => n > 0), as)\n      deepStrictEqual(Array.from(result1).filter((n) => n < 0), as.map((n) => -n))\n      deepStrictEqual(Array.from(result2).filter((n) => n > 0), as)\n      deepStrictEqual(Array.from(result2).filter((n) => n < 0), as.map((n) => -n))\n    })))\n\n  it.effect(\"unbounded - undefined/null values\", () =>\n    Effect.gen(function*() {\n      const as = [null, undefined, null, undefined]\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const pubsub = yield* (TPubSub.unbounded<null | undefined>())\n      const subscriber1 = yield* (pipe(\n        TPubSub.subscribeScoped(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            deferred1,\n            Deferred.succeed<void>(void 0),\n            Effect.zipRight(pipe(as, Effect.forEach(() => TQueue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      ))\n      const subscriber2 = yield* (pipe(\n        TPubSub.subscribeScoped(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            deferred2,\n            Deferred.succeed<void>(void 0),\n            Effect.zipRight(pipe(as, Effect.forEach(() => TQueue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      ))\n      yield* (Deferred.await(deferred1))\n      yield* (Deferred.await(deferred2))\n      yield* (pipe(as, Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n      const result1 = yield* (Fiber.join(subscriber1))\n      const result2 = yield* (Fiber.join(subscriber2))\n      deepStrictEqual(result1, as)\n      deepStrictEqual(result2, as)\n    }))\n\n  it.effect(\"bounded - undefined/null values\", () =>\n    Effect.gen(function*() {\n      const as = [null, undefined]\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const pubsub = yield* (TPubSub.bounded<null | undefined>(2))\n      const subscriber1 = yield* (pipe(\n        TPubSub.subscribeScoped(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            deferred1,\n            Deferred.succeed<void>(void 0),\n            Effect.zipRight(pipe(as, Effect.forEach(() => TQueue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      ))\n      const subscriber2 = yield* (pipe(\n        TPubSub.subscribeScoped(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            deferred2,\n            Deferred.succeed<void>(void 0),\n            Effect.zipRight(pipe(as, Effect.forEach(() => TQueue.take(subscription))))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      ))\n      yield* (Deferred.await(deferred1))\n      yield* (Deferred.await(deferred2))\n      yield* (pipe(as, Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n      const result1 = yield* (Fiber.join(subscriber1))\n      const result2 = yield* (Fiber.join(subscriber2))\n      deepStrictEqual(result1, as)\n      deepStrictEqual(result2, as)\n    }))\n\n  it.effect(\"dropping - undefined/null values\", () =>\n    Effect.gen(function*() {\n      const as = [null, undefined, null, undefined]\n      const n = 2\n      const deferred = yield* (Deferred.make<void>())\n      const pubsub = yield* (TPubSub.dropping<null | undefined>(n))\n      const subscriber = yield* (pipe(\n        TPubSub.subscribeScoped(pubsub),\n        Effect.flatMap((subscription) =>\n          pipe(\n            deferred,\n            Deferred.succeed<void>(void 0),\n            Effect.zipRight(pipe(\n              as.slice(0, n),\n              Effect.forEach(() => TQueue.take(subscription))\n            ))\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      ))\n      yield* (Deferred.await(deferred))\n      yield* (pipe(as, Effect.forEach((n) => pipe(pubsub, TPubSub.publish(n))), Effect.fork))\n      const result = yield* (Fiber.join(subscriber))\n      deepStrictEqual(result, as.slice(0, n))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/TQueue.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertNone, assertSome, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Effect, pipe, STM, TQueue } from \"effect\"\n\ndescribe(\"TQueue\", () => {\n  it.effect(\"bounded\", () =>\n    Effect.gen(function*() {\n      const capacity = 5\n      const result = yield* (pipe(TQueue.bounded(capacity), STM.map(TQueue.capacity)))\n      strictEqual(result, capacity)\n    }))\n\n  it.effect(\"unbounded\", () =>\n    Effect.gen(function*() {\n      const result = yield* (pipe(\n        TQueue.unbounded(),\n        STM.map(TQueue.capacity),\n        STM.commit\n      ))\n      strictEqual(result, Number.MAX_SAFE_INTEGER)\n    }))\n\n  it.effect(\"offer & take\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.bounded<number>(5))\n      yield* (pipe(queue, TQueue.offer(1)))\n      yield* (pipe(queue, TQueue.offer(2)))\n      yield* (pipe(queue, TQueue.offer(3)))\n      const result1 = yield* (TQueue.take(queue))\n      const result2 = yield* (TQueue.take(queue))\n      const result3 = yield* (TQueue.take(queue))\n      strictEqual(result1, 1)\n      strictEqual(result2, 2)\n      strictEqual(result3, 3)\n    }))\n\n  it.effect(\"offer & take undefined\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.bounded<undefined>(5))\n      yield* (pipe(queue, TQueue.offer(undefined)))\n      yield* (pipe(queue, TQueue.offer(undefined)))\n      const result1 = yield* (TQueue.take(queue))\n      const result2 = yield* (TQueue.take(queue))\n      strictEqual(result1, undefined)\n      strictEqual(result2, undefined)\n    }))\n\n  it.effect(\"offerAll & takeAll\", () =>\n    Effect.gen(function*() {\n      const array = [1, 2, 3, 4, 5]\n      const queue = yield* (TQueue.bounded<number>(5))\n      yield* (pipe(queue, TQueue.offerAll(array)))\n      const result = yield* (TQueue.takeAll(queue))\n      deepStrictEqual(Array.from(result), array)\n    }))\n\n  it.effect(\"takeUpTo\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.bounded<number>(5))\n      yield* (pipe(queue, TQueue.offerAll([1, 2, 3, 4, 5])))\n      const result = yield* (pipe(queue, TQueue.takeUpTo(3)))\n      const size = yield* (TQueue.size(queue))\n      deepStrictEqual(Array.from(result), [1, 2, 3])\n      strictEqual(size, 2)\n    }))\n\n  it.effect(\"takeUpTo - larger than queue\", () =>\n    Effect.gen(function*() {\n      const array = [1, 2, 3, 4, 5]\n      const queue = yield* (TQueue.bounded<number>(5))\n      yield* (pipe(queue, TQueue.offerAll(array)))\n      const result = yield* (pipe(queue, TQueue.takeUpTo(7)))\n      const size = yield* (TQueue.size(queue))\n      deepStrictEqual(Array.from(result), array)\n      strictEqual(size, 0)\n    }))\n\n  it.effect(\"poll\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.bounded<number>(5))\n      yield* (pipe(queue, TQueue.offerAll([1, 2, 3])))\n      const result = yield* (TQueue.poll(queue))\n      assertSome(result, 1)\n    }))\n\n  it.effect(\"poll undefined\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.bounded<undefined>(5))\n      yield* (pipe(queue, TQueue.offerAll([undefined, undefined, undefined])))\n      const result = yield* (TQueue.poll(queue))\n      assertSome(result, undefined)\n    }))\n\n  it.effect(\"poll - empty queue\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.bounded<number>(5))\n      const result = yield* (TQueue.poll(queue))\n      assertNone(result)\n    }))\n\n  it.effect(\"seek\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.bounded<number>(5))\n      yield* (pipe(queue, TQueue.offerAll([1, 2, 3, 4, 5])))\n      const result = yield* (pipe(queue, TQueue.seek((n) => n === 3)))\n      const size = yield* (TQueue.size(queue))\n      strictEqual(result, 3)\n      strictEqual(size, 2)\n    }))\n\n  it.effect(\"size\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.unbounded<number>())\n      yield* (pipe(queue, TQueue.offerAll([1, 2, 3, 4, 5])))\n      const result = yield* (TQueue.size(queue))\n      strictEqual(result, 5)\n    }))\n\n  it.effect(\"peek\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.unbounded<number>())\n      yield* (pipe(queue, TQueue.offerAll([1, 2, 3, 4, 5])))\n      const result = yield* (TQueue.peek(queue))\n      const size = yield* (TQueue.size(queue))\n      strictEqual(result, 1)\n      strictEqual(size, 5)\n    }))\n\n  it.effect(\"peekOption\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.unbounded<number>())\n      yield* (pipe(queue, TQueue.offerAll([1, 2, 3, 4, 5])))\n      const result = yield* (TQueue.peekOption(queue))\n      const size = yield* (TQueue.size(queue))\n      assertSome(result, 1)\n      strictEqual(size, 5)\n    }))\n\n  it.effect(\"peekOption - empty queu\", () =>\n    Effect.gen(function*() {\n      const queue = yield* (TQueue.unbounded<number>())\n      const result = yield* (TQueue.peekOption(queue))\n      assertNone(result)\n    }))\n\n  it.effect(\"isEmpty\", () =>\n    Effect.gen(function*() {\n      const queue1 = yield* (TQueue.unbounded<number>())\n      const queue2 = yield* (TQueue.unbounded<number>())\n      yield* (pipe(queue1, TQueue.offerAll([1, 2, 3, 4, 5])))\n      const result1 = yield* (TQueue.isEmpty(queue1))\n      const result2 = yield* (TQueue.isEmpty(queue2))\n      assertFalse(result1)\n      assertTrue(result2)\n    }))\n\n  it.effect(\"isFull\", () =>\n    Effect.gen(function*() {\n      const queue1 = yield* (TQueue.bounded<number>(5))\n      const queue2 = yield* (TQueue.bounded<number>(5))\n      yield* (pipe(queue1, TQueue.offerAll([1, 2, 3, 4, 5])))\n      const result1 = yield* (TQueue.isFull(queue1))\n      const result2 = yield* (TQueue.isFull(queue2))\n      assertTrue(result1)\n      assertFalse(result2)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/TRandom.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as fc from \"effect/FastCheck\"\nimport { pipe } from \"effect/Function\"\nimport * as STM from \"effect/STM\"\nimport * as TRandom from \"effect/TRandom\"\n\nconst floatsArb: fc.Arbitrary<readonly [number, number]> = fc.tuple(\n  fc.float({ noDefaultInfinity: true, noNaN: true }),\n  fc.float({ noDefaultInfinity: true, noNaN: true })\n)\n  .filter(([a, b]) => a !== b)\n  .map(([a, b]) => b > a ? [a, b] : [b, a])\n\nconst intsArb: fc.Arbitrary<readonly [number, number]> = fc.tuple(fc.integer(), fc.integer())\n  .filter(([a, b]) => a !== b)\n  .map(([a, b]) => b > a ? [a, b] : [b, a])\n\ndescribe(\"TRandom\", () => {\n  it(\"nextIntBetween - generates integers in the specified range\", () =>\n    fc.assert(fc.asyncProperty(intsArb, async ([min, max]) => {\n      const result = await pipe(\n        STM.commit(TRandom.nextRange(min, max)),\n        Effect.provide(TRandom.live),\n        Effect.runPromise\n      )\n      assertTrue(result >= min)\n      assertTrue(result < max)\n    })))\n\n  it(\"nextRange - generates numbers in the specified range\", () =>\n    fc.assert(fc.asyncProperty(floatsArb, async ([min, max]) => {\n      const result = await pipe(\n        STM.commit(TRandom.nextRange(min, max)),\n        Effect.provide(TRandom.live),\n        Effect.runPromise\n      )\n      assertTrue(result >= min)\n      assertTrue(result < max)\n    })))\n})\n"
  },
  {
    "path": "packages/effect/test/TReentrantLock.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, strictEqual } from \"@effect/vitest/utils\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as STM from \"effect/STM\"\nimport * as TReentrantLock from \"effect/TReentrantLock\"\n\nconst pollSchedule = <E, A>(): Schedule.Schedule<Option.Option<Exit.Exit<E, A>>, Option.Option<Exit.Exit<E, A>>> =>\n  pipe(\n    Schedule.recurs(100),\n    Schedule.zipRight(\n      pipe(\n        Schedule.identity<Option.Option<Exit.Exit<E, A>>>(),\n        Schedule.whileOutput(Option.isNone)\n      )\n    )\n  )\n\ndescribe(\"TReentrantLock\", () => {\n  it.effect(\"one read lock\", () =>\n    Effect.gen(function*() {\n      const lock = yield* (TReentrantLock.make)\n      const result = yield* (pipe(\n        TReentrantLock.readLock(lock),\n        Effect.flatMap(Effect.succeed),\n        Effect.scoped\n      ))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"two read locks from the same fiber\", () =>\n    Effect.gen(function*() {\n      const lock = yield* (TReentrantLock.make)\n      const result = yield* (pipe(\n        TReentrantLock.readLock(lock),\n        Effect.flatMap(() =>\n          pipe(\n            TReentrantLock.readLock(lock),\n            Effect.flatMap(Effect.succeed),\n            Effect.scoped\n          )\n        ),\n        Effect.scoped\n      ))\n      strictEqual(result, 2)\n    }))\n\n  it.effect(\"two read locks from different fibers\", () =>\n    Effect.gen(function*() {\n      const lock = yield* (TReentrantLock.make)\n      const rLatch = yield* (Deferred.make<void>())\n      const mLatch = yield* (Deferred.make<void>())\n      const wLatch = yield* (Deferred.make<void>())\n      yield* (pipe(\n        TReentrantLock.readLock(lock),\n        Effect.flatMap((count) =>\n          pipe(\n            mLatch,\n            Deferred.succeed<void>(void 0),\n            Effect.zipRight(Deferred.await(rLatch)),\n            Effect.as(count)\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      ))\n      yield* (Deferred.await(mLatch))\n      const fiber = yield* (pipe(\n        TReentrantLock.readLock(lock),\n        Effect.flatMap((count) =>\n          pipe(\n            wLatch,\n            Deferred.succeed<void>(void 0),\n            Effect.as(count)\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      ))\n      yield* (Deferred.await(wLatch))\n      const result = yield* (Fiber.join(fiber))\n      strictEqual(result, 1)\n    }))\n\n  it.effect(\"one write lock, then one read lock, different fibers\", () =>\n    Effect.gen(function*() {\n      const lock = yield* (TReentrantLock.make)\n      const rLatch = yield* (Deferred.make<void>())\n      const mLatch = yield* (Deferred.make<void>())\n      const wLatch = yield* (Deferred.make<void>())\n      yield* (pipe(\n        TReentrantLock.writeLock(lock),\n        Effect.flatMap((count) =>\n          pipe(\n            rLatch,\n            Deferred.succeed<void>(void 0),\n            Effect.zipRight(Deferred.await(wLatch)),\n            Effect.as(count)\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      ))\n      yield* (Deferred.await(rLatch))\n      const fiber = yield* (pipe(\n        mLatch,\n        Deferred.succeed<void>(void 0),\n        Effect.zipRight(Effect.scoped(TReentrantLock.readLock(lock))),\n        Effect.fork\n      ))\n      yield* (Deferred.await(mLatch))\n      const locks = yield* (pipe(\n        TReentrantLock.readLocks(lock),\n        STM.zipWith(TReentrantLock.writeLocks(lock), (x, y) => x + y),\n        STM.commit\n      ))\n      const option = yield* (pipe(\n        Fiber.poll(fiber),\n        Effect.repeat(pollSchedule())\n      ))\n      yield* (pipe(wLatch, Deferred.succeed<void>(void 0)))\n      const readerCount = yield* (Fiber.join(fiber))\n      strictEqual(locks, 1)\n      assertNone(option)\n      strictEqual(readerCount, 1)\n    }))\n\n  it.effect(\"write lock followed by read lock from the same fiber\", () =>\n    Effect.gen(function*() {\n      const lock = yield* (TReentrantLock.make)\n      const ref = yield* (Ref.make(0))\n      const readerCount = yield* (pipe(\n        TReentrantLock.writeLock(lock),\n        Effect.flatMap(() =>\n          pipe(\n            TReentrantLock.readLock(lock),\n            Effect.flatMap((count) =>\n              pipe(\n                STM.commit(TReentrantLock.writeLocks(lock)),\n                Effect.flatMap((n) => pipe(ref, Ref.set(n))),\n                Effect.as(count)\n              )\n            ),\n            Effect.scoped\n          )\n        ),\n        Effect.scoped\n      ))\n      const writerCount = yield* (Ref.get(ref))\n      strictEqual(readerCount, 1)\n      strictEqual(writerCount, 1)\n    }))\n\n  it.effect(\"upgrade read lock to write lock from the same fiber\", () =>\n    Effect.gen(function*() {\n      const lock = yield* (TReentrantLock.make)\n      const ref = yield* (Ref.make(0))\n      const readerCount = yield* (pipe(\n        TReentrantLock.readLock(lock),\n        Effect.flatMap(() =>\n          pipe(\n            TReentrantLock.writeLock(lock),\n            Effect.flatMap((count) =>\n              pipe(\n                TReentrantLock.writeLocks(lock),\n                Effect.flatMap((n) => pipe(ref, Ref.set(n))),\n                Effect.as(count)\n              )\n            ),\n            Effect.scoped\n          )\n        ),\n        Effect.scoped\n      ))\n      const writerCount = yield* (Ref.get(ref))\n      strictEqual(readerCount, 1)\n      strictEqual(writerCount, 1)\n    }))\n\n  it.effect(\"read to writer upgrade with other readers\", () =>\n    Effect.gen(function*() {\n      const lock = yield* (TReentrantLock.make)\n      const rLatch = yield* (Deferred.make<void>())\n      const mLatch = yield* (Deferred.make<void>())\n      const wLatch = yield* (Deferred.make<void>())\n      yield* (pipe(\n        TReentrantLock.readLock(lock),\n        Effect.flatMap((count) =>\n          pipe(\n            mLatch,\n            Deferred.succeed<void>(void 0),\n            Effect.zipRight(Deferred.await(rLatch)),\n            Effect.as(count)\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      ))\n      yield* (Deferred.await(mLatch))\n      const fiber = yield* (pipe(\n        TReentrantLock.readLock(lock),\n        Effect.flatMap(() =>\n          pipe(\n            wLatch,\n            Deferred.succeed<void>(void 0),\n            Effect.zipRight(\n              pipe(\n                TReentrantLock.writeLock(lock),\n                Effect.flatMap(Effect.succeed),\n                Effect.scoped\n              )\n            )\n          )\n        ),\n        Effect.scoped,\n        Effect.fork\n      ))\n      yield* (Deferred.await(wLatch))\n      const option = yield* (pipe(Fiber.poll(fiber), Effect.repeat(pollSchedule())))\n      yield* (pipe(rLatch, Deferred.succeed<void>(void 0)))\n      const count = yield* (Fiber.join(fiber))\n      assertNone(option)\n      strictEqual(count, 1)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/TSet.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertFalse, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as STM from \"effect/STM\"\nimport * as TSet from \"effect/TSet\"\n\ndescribe(\"TSet\", () => {\n  it.effect(\"add - new element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.empty<number>(),\n        STM.tap(TSet.add(1)),\n        STM.flatMap(TSet.toReadonlySet)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, new Set([1]))\n    }))\n\n  it.effect(\"add - duplicate element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1),\n        STM.tap(TSet.add(1)),\n        STM.flatMap(TSet.toReadonlySet)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, new Set([1]))\n    }))\n\n  it.effect(\"difference\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const set1 = yield* (TSet.make(1, 2, 3))\n        const set2 = yield* (TSet.make(1, 4, 5))\n        yield* (pipe(set1, TSet.difference(set2)))\n        return yield* (TSet.toArray(set1))\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [2, 3])\n    }))\n\n  it.effect(\"empty\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.empty<number>(),\n        STM.flatMap(TSet.isEmpty)\n      )\n      const result = yield* (STM.commit(transaction))\n      assertTrue(result)\n    }))\n\n  it.effect(\"fromIterable\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.fromIterable([1, 2, 2, 3]),\n        STM.flatMap(TSet.toReadonlySet)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, new Set([1, 2, 3]))\n    }))\n\n  it.effect(\"has - existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2, 3, 4),\n        STM.flatMap(TSet.has(1))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertTrue(result)\n    }))\n\n  it.effect(\"has - non-existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.empty<number>(),\n        STM.flatMap(TSet.has(1))\n      )\n      const result = yield* (STM.commit(transaction))\n      assertFalse(result)\n    }))\n\n  it.effect(\"intersection\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const set1 = yield* (TSet.make(1, 2, 3))\n        const set2 = yield* (TSet.make(1, 4, 5))\n        yield* (pipe(set1, TSet.intersection(set2)))\n        return yield* (TSet.toArray(set1))\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [1])\n    }))\n\n  it.effect(\"make\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2, 2, 3),\n        STM.flatMap(TSet.toReadonlySet)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, new Set([1, 2, 3]))\n    }))\n\n  it.effect(\"reduce - non-empty set\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2, 3),\n        STM.flatMap(TSet.reduce(0, (x, y) => x + y))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 6)\n    }))\n\n  it.effect(\"reduce - empty set\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.empty<number>(),\n        STM.flatMap(TSet.reduce(0, (x, y) => x + y))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"reduceSTM - non-empty set\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2, 3),\n        STM.flatMap(TSet.reduceSTM(0, (x, y) => STM.succeed(x + y)))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 6)\n    }))\n\n  it.effect(\"reduceSTM - empty set\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.empty<number>(),\n        STM.flatMap(TSet.reduceSTM(0, (x, y) => STM.succeed(x + y)))\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 0)\n    }))\n\n  it.effect(\"remove - existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2),\n        STM.tap(TSet.remove(1)),\n        STM.flatMap(TSet.toReadonlySet)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, new Set([2]))\n    }))\n\n  it.effect(\"remove - non-existing element\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2),\n        STM.tap(TSet.remove(3)),\n        STM.flatMap(TSet.toReadonlySet)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, new Set([1, 2]))\n    }))\n\n  it.effect(\"retainIf\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const set = yield* (TSet.make(\"a\", \"aa\", \"aaa\"))\n        const removed = yield* (pipe(set, TSet.retainIf((s) => s === \"aa\")))\n        const a = yield* (pipe(set, TSet.has(\"a\")))\n        const aa = yield* (pipe(set, TSet.has(\"aa\")))\n        const aaa = yield* (pipe(set, TSet.has(\"aaa\")))\n        return [Array.from(removed), a, aa, aaa]\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [[\"aaa\", \"a\"], false, true, false])\n    }))\n\n  it.effect(\"retainIf > { discard: true }\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const set = yield* (TSet.make(\"a\", \"aa\", \"aaa\"))\n        yield* (pipe(set, TSet.retainIf((s) => s === \"aa\", { discard: true })))\n        const a = yield* (pipe(set, TSet.has(\"a\")))\n        const aa = yield* (pipe(set, TSet.has(\"aa\")))\n        const aaa = yield* (pipe(set, TSet.has(\"aaa\")))\n        return [a, aa, aaa]\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [false, true, false])\n    }))\n\n  it.effect(\"removeIf\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const set = yield* (TSet.make(\"a\", \"aa\", \"aaa\"))\n        const removed = yield* (pipe(set, TSet.removeIf((s) => s === \"aa\")))\n        const a = yield* (pipe(set, TSet.has(\"a\")))\n        const aa = yield* (pipe(set, TSet.has(\"aa\")))\n        const aaa = yield* (pipe(set, TSet.has(\"aaa\")))\n        return [Array.from(removed), a, aa, aaa]\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [[\"aa\"], true, false, true])\n    }))\n\n  it.effect(\"removeIf > { discard: true }\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const set = yield* (TSet.make(\"a\", \"aa\", \"aaa\"))\n        yield* (pipe(set, TSet.removeIf((s) => s === \"aa\", { discard: true })))\n        const a = yield* (pipe(set, TSet.has(\"a\")))\n        const aa = yield* (pipe(set, TSet.has(\"aa\")))\n        const aaa = yield* (pipe(set, TSet.has(\"aaa\")))\n        return [a, aa, aaa]\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [true, false, true])\n    }))\n\n  it.effect(\"transform\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2, 3),\n        STM.tap((set) => TSet.transform(set, (n) => n * 2)),\n        STM.flatMap(TSet.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [2, 4, 6])\n    }))\n\n  it.effect(\"transform - and shrink\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2, 3),\n        STM.tap(TSet.transform(() => 1)),\n        STM.flatMap(TSet.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [1])\n    }))\n\n  it.effect(\"transformSTM\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2, 3),\n        STM.tap((set) => TSet.transformSTM(set, (n) => STM.succeed(n * 2))),\n        STM.flatMap(TSet.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [2, 4, 6])\n    }))\n\n  it.effect(\"transformSTM - and shrink\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2, 3),\n        STM.tap(TSet.transformSTM(() => STM.succeed(1))),\n        STM.flatMap(TSet.toArray)\n      )\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [1])\n    }))\n\n  it.effect(\"size\", () =>\n    Effect.gen(function*() {\n      const transaction = pipe(\n        TSet.make(1, 2, 3, 4),\n        STM.flatMap(TSet.size)\n      )\n      const result = yield* (STM.commit(transaction))\n      strictEqual(result, 4)\n    }))\n\n  it.effect(\"union\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const set1 = yield* (TSet.make(1, 2, 3))\n        const set2 = yield* (TSet.make(1, 4, 5))\n        yield* (pipe(set1, TSet.union(set2)))\n        return yield* (TSet.toArray(set1))\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, [1, 2, 3, 4, 5])\n    }))\n\n  it.effect(\"toChunk\", () =>\n    Effect.gen(function*() {\n      const transaction = STM.gen(function*() {\n        const set = yield* (TSet.make(1, 2, 3))\n        return yield* (TSet.toChunk(set))\n      })\n      const result = yield* (STM.commit(transaction))\n      deepStrictEqual(result, Chunk.make(1, 2, 3))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/TSubscriptionRef.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertTrue, deepStrictEqual } from \"@effect/vitest/utils\"\nimport {\n  Chunk,\n  Deferred,\n  Effect,\n  Equal,\n  Exit,\n  Fiber,\n  Number,\n  pipe,\n  Random,\n  STM,\n  Stream,\n  TSubscriptionRef\n} from \"effect\"\n\ndescribe.concurrent(\"TSubscriptionRef\", () => {\n  it.effect(\"only emits comitted values\", () =>\n    Effect.gen(function*() {\n      const subscriptionRef = yield* (TSubscriptionRef.make(0))\n\n      const transaction = pipe(\n        TSubscriptionRef.update(subscriptionRef, (n) => n + 1),\n        STM.tap(() => TSubscriptionRef.update(subscriptionRef, (n) => n + 1))\n      )\n\n      const subscriber = yield* (pipe(\n        TSubscriptionRef.changesStream(subscriptionRef),\n        Stream.take(1),\n        Stream.runCollect,\n        Effect.fork\n      ))\n      // stream doesn't work properly without a yield, it will drop values\n      yield* (Effect.yieldNow())\n      yield* (STM.commit(transaction))\n      yield* (Effect.yieldNow())\n      const result = yield* (Fiber.join(subscriber))\n\n      deepStrictEqual(Array.from(result), [2])\n    }))\n\n  it.effect(\"emits every comitted value\", () =>\n    Effect.gen(function*() {\n      const subscriptionRef = yield* (TSubscriptionRef.make(0))\n\n      const transaction = pipe(\n        TSubscriptionRef.update(subscriptionRef, (n) => n + 1),\n        STM.commit,\n        // stream doesn't work properly without a yield, it will drop the first value without this\n        Effect.tap(() => Effect.yieldNow()),\n        Effect.flatMap(() => TSubscriptionRef.update(subscriptionRef, (n) => n + 1))\n      )\n\n      const subscriber = yield* (pipe(\n        TSubscriptionRef.changesStream(subscriptionRef),\n        Stream.take(2),\n        Stream.runCollect,\n        Effect.fork\n      ))\n      // stream doesn't work properly without a yield, it will drop the first value without this\n      yield* (Effect.yieldNow())\n      yield* transaction\n      const result = yield* (Fiber.join(subscriber))\n\n      deepStrictEqual(Array.from(result), [1, 2])\n    }))\n\n  it.effect(\"multiple subscribers can receive committed values\", () =>\n    Effect.gen(function*() {\n      const subscriptionRef = yield* (TSubscriptionRef.make(0))\n      const deferred1 = yield* (Deferred.make<void, never>())\n      const deferred2 = yield* (Deferred.make<void, never>())\n      const subscriber1 = yield* (pipe(\n        TSubscriptionRef.changesStream(subscriptionRef),\n        Stream.tap(() => Deferred.succeed<void, never>(deferred1, void 0)),\n        Stream.take(3),\n        Stream.runCollect,\n        Effect.fork\n      ))\n      yield* (Deferred.await(deferred1))\n      yield* (TSubscriptionRef.update(subscriptionRef, (n) => n + 1))\n      const subscriber2 = yield* (pipe(\n        TSubscriptionRef.changesStream(subscriptionRef),\n        Stream.tap(() => Deferred.succeed<void, never>(deferred2, void 0)),\n        Stream.take(2),\n        Stream.runCollect,\n        Effect.fork\n      ))\n      yield* (Deferred.await(deferred2))\n      yield* (TSubscriptionRef.update(subscriptionRef, (n) => n + 1))\n      const result1 = yield* (Fiber.join(subscriber1))\n      const result2 = yield* (Fiber.join(subscriber2))\n      deepStrictEqual(Array.from(result1), [0, 1, 2])\n      deepStrictEqual(Array.from(result2), [1, 2])\n    }))\n\n  it.effect(\"subscriptions are interruptible\", () =>\n    Effect.gen(function*() {\n      const ref = yield* (TSubscriptionRef.make(0))\n      const deferred1 = yield* (Deferred.make<void>())\n      const deferred2 = yield* (Deferred.make<void>())\n      const subscriber1 = yield* pipe(\n        TSubscriptionRef.changesStream(ref),\n        Stream.tap(() => Deferred.succeed(deferred1, void 0)),\n        Stream.take(5),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(deferred1))\n      yield* (TSubscriptionRef.update(ref, (n) => n + 1))\n      const subscriber2 = yield* pipe(\n        TSubscriptionRef.changesStream(ref),\n        Stream.tap(() => Deferred.succeed(deferred2, void 0)),\n        Stream.take(2),\n        Stream.runCollect,\n        Effect.fork\n      )\n      yield* (Deferred.await(deferred2))\n      yield* (TSubscriptionRef.update(ref, (n) => n + 1))\n      const result1 = yield* (Fiber.interrupt(subscriber1))\n      const result2 = yield* (Fiber.join(subscriber2))\n      assertTrue(Exit.isInterrupted(result1))\n      deepStrictEqual(Array.from(result2), [1, 2])\n    }))\n\n  it.effect(\"concurrent subscribes and unsubscribes are handled correctly\", () =>\n    Effect.gen(function*() {\n      const subscriber = (subscriptionRef: TSubscriptionRef.TSubscriptionRef<number>) =>\n        pipe(\n          Random.nextIntBetween(0, 200),\n          Effect.flatMap((n) =>\n            pipe(\n              TSubscriptionRef.changesStream(subscriptionRef),\n              Stream.take(n),\n              Stream.runCollect\n            )\n          )\n        )\n      const ref = yield* (TSubscriptionRef.make(0))\n      const fiber = yield* pipe(\n        TSubscriptionRef.update(ref, (n) => n + 1),\n        Effect.forever,\n        Effect.fork\n      )\n      const result = yield* (\n        Effect.map(\n          Effect.all(\n            Array.from({ length: 2 }, () => subscriber(ref)),\n            { concurrency: 2 }\n          ),\n          Chunk.unsafeFromArray\n        )\n      )\n      yield* (Fiber.interrupt(fiber))\n      const isSorted = Chunk.every(result, (chunk) => Equal.equals(chunk, Chunk.sort(chunk, Number.Order)))\n      assertTrue(isSorted)\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/TestClock.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual } from \"@effect/vitest/utils\"\nimport { DateTime, Effect, TestClock } from \"effect\"\n\ndescribe(\"TestClock\", () => {\n  describe(\"setTime\", () => {\n    const arbitraryDateTime = DateTime.unsafeMake(\"2023-12-31T11:00:00.000Z\")\n    it.effect(\"should set the current Date using an Instant\", () =>\n      Effect.gen(function*() {\n        yield* TestClock.setTime(arbitraryDateTime.epochMillis)\n        const now = yield* DateTime.now\n        deepStrictEqual(now, arbitraryDateTime)\n      }))\n    it.effect(\"should set the current time using a DateTime\", () =>\n      Effect.gen(function*() {\n        yield* TestClock.setTime(arbitraryDateTime)\n        const now = yield* DateTime.now\n        deepStrictEqual(now, arbitraryDateTime)\n      }))\n    it.effect(\"should set the current time using a Date\", () =>\n      Effect.gen(function*() {\n        yield* TestClock.setTime(DateTime.toDate(arbitraryDateTime))\n        const now = yield* DateTime.now\n        deepStrictEqual(now, arbitraryDateTime)\n      }))\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Tracer.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertInclude, assertNone, assertTrue, deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { Cause, Context, Duration, Effect, Fiber, FiberId, Layer, Option, pipe, TestClock, Tracer } from \"effect\"\nimport type { Span } from \"effect/Tracer\"\nimport type { NativeSpan } from \"../src/internal/tracer.js\"\n\ndescribe(\"Tracer\", () => {\n  it.effect(\"includes trace when errored\", () =>\n    Effect.gen(function*() {\n      let maybeSpan: undefined | Span\n      const getSpan = Effect.functionWithSpan({\n        body: (_id: string) =>\n          Effect.currentSpan.pipe(Effect.flatMap((span) => {\n            maybeSpan = span\n            return Effect.fail(\"error\")\n          })),\n        options: (id) => ({\n          name: `span-${id}`,\n          attributes: { id }\n        })\n      })\n      yield* Effect.flip(getSpan(\"fail\"))\n      assertTrue(maybeSpan !== undefined)\n      assertInclude(maybeSpan!.attributes.get(\"code.stacktrace\") as string, \"Tracer.test.ts:22:26\")\n    }))\n\n  it.effect(\"captures stack\", () =>\n    Effect.gen(function*() {\n      const cause = yield* Effect.die(new Error(\"boom\")).pipe(\n        Effect.withSpan(\"C\", { context: Tracer.DisablePropagation.context(true) }),\n        Effect.sandbox,\n        Effect.flip\n      )\n      assertInclude(Cause.pretty(cause), \"Tracer.test.ts:29:39\")\n    }))\n\n  describe(\"withSpan\", () => {\n    it.effect(\"no parent\", () =>\n      Effect.gen(function*() {\n        const span = yield* Effect.withSpan(\"A\")(Effect.currentSpan)\n        deepStrictEqual(span.name, \"A\")\n        assertNone(span.parent)\n        strictEqual(span.attributes.get(\"code.stacktrace\"), undefined)\n      }))\n\n    it.effect(\"parent\", () =>\n      Effect.gen(function*() {\n        const span = yield* (\n          Effect.withSpan(\"B\")(\n            Effect.withSpan(\"A\")(Effect.currentSpan)\n          )\n        )\n\n        deepStrictEqual(span.name, \"A\")\n        deepStrictEqual(Option.map(span.parent, (span) => (span as Span).name), Option.some(\"B\"))\n      }))\n\n    it.effect(\"parent when root is set\", () =>\n      Effect.gen(function*() {\n        const span = yield* (\n          Effect.withSpan(\"B\")(Effect.withSpan(\"A\", { root: true })(Effect.currentSpan))\n        )\n\n        deepStrictEqual(span.name, \"A\")\n        assertNone(span.parent)\n      }))\n\n    it.effect(\"external parent\", () =>\n      Effect.gen(function*() {\n        const span = yield* (\n          Effect.withSpan(\"A\", {\n            parent: {\n              _tag: \"ExternalSpan\",\n              spanId: \"000\",\n              traceId: \"111\",\n              sampled: true,\n              context: Context.empty()\n            }\n          })(Effect.currentSpan)\n        )\n        deepStrictEqual(span.name, \"A\")\n        deepStrictEqual(Option.map(span.parent, (span) => span.spanId), Option.some(\"000\"))\n      }))\n\n    it.effect(\"correct time\", () =>\n      Effect.gen(function*() {\n        const spanFiber = yield* (\n          Effect.fork(Effect.withSpan(\"A\")(Effect.delay(Duration.seconds(1))(Effect.currentSpan)))\n        )\n\n        yield* (TestClock.adjust(Duration.seconds(2)))\n\n        const span = yield* (Fiber.join(spanFiber))\n\n        deepStrictEqual(span.name, \"A\")\n        deepStrictEqual(span.status.startTime, 0n)\n        deepStrictEqual((span.status as any)[\"endTime\"], 1000000000n)\n        deepStrictEqual(span.status._tag, \"Ended\")\n      }))\n  })\n\n  it.effect(\"annotateSpans\", () =>\n    Effect.gen(function*() {\n      const span = yield* (\n        Effect.annotateSpans(\n          Effect.withSpan(\"A\")(Effect.currentSpan),\n          \"key\",\n          \"value\"\n        )\n      )\n\n      deepStrictEqual(span.name, \"A\")\n      assertNone(span.parent)\n      deepStrictEqual(span.attributes.get(\"key\"), \"value\")\n    }))\n\n  it.effect(\"annotateSpans record\", () =>\n    Effect.gen(function*() {\n      const span = yield* (\n        Effect.annotateSpans(\n          Effect.withSpan(\"A\")(Effect.currentSpan),\n          { key: \"value\", key2: \"value2\" }\n        )\n      )\n\n      deepStrictEqual(span.attributes.get(\"key\"), \"value\")\n      deepStrictEqual(span.attributes.get(\"key2\"), \"value2\")\n    }))\n\n  it.effect(\"logger\", () =>\n    Effect.gen(function*() {\n      yield* (TestClock.adjust(Duration.millis(0.01)))\n\n      const [span, fiberId] = yield* pipe(\n        Effect.log(\"event\"),\n        Effect.zipRight(Effect.all([Effect.currentSpan, Effect.fiberId])),\n        Effect.withSpan(\"A\")\n      )\n\n      deepStrictEqual(span.name, \"A\")\n      assertNone(span.parent)\n      deepStrictEqual((span as NativeSpan).events, [[\"event\", 10000n, {\n        \"effect.fiberId\": FiberId.threadName(fiberId),\n        \"effect.logLevel\": \"INFO\"\n      }]])\n    }))\n\n  it.effect(\"withTracerTiming false\", () =>\n    Effect.gen(function*() {\n      yield* (TestClock.adjust(Duration.millis(1)))\n\n      const span = yield* pipe(\n        Effect.withSpan(\"A\")(Effect.currentSpan),\n        Effect.withTracerTiming(false)\n      )\n\n      deepStrictEqual(span.status.startTime, 0n)\n    }))\n\n  it.effect(\"useSpanScoped\", () =>\n    Effect.gen(function*() {\n      const span = yield* Effect.scoped(Effect.makeSpanScoped(\"A\"))\n      deepStrictEqual(span.status._tag, \"Ended\")\n      strictEqual(span.attributes.get(\"code.stacktrace\"), undefined)\n    }))\n\n  it.effect(\"annotateCurrentSpan\", () =>\n    Effect.gen(function*() {\n      yield* (Effect.annotateCurrentSpan(\"key\", \"value\"))\n      const span = yield* (Effect.currentSpan)\n      deepStrictEqual(span.attributes.get(\"key\"), \"value\")\n    }).pipe(\n      Effect.withSpan(\"A\")\n    ))\n\n  it.effect(\"withParentSpan\", () =>\n    Effect.gen(function*() {\n      const span = yield* (Effect.currentSpan)\n      deepStrictEqual(\n        span.parent.pipe(\n          Option.map((_) => _.spanId)\n        ),\n        Option.some(\"456\")\n      )\n    }).pipe(\n      Effect.withSpan(\"A\"),\n      Effect.withParentSpan({\n        _tag: \"ExternalSpan\",\n        traceId: \"123\",\n        spanId: \"456\",\n        sampled: true,\n        context: Context.empty()\n      })\n    ))\n\n  it.effect(\"Layer.parentSpan\", () =>\n    Effect.gen(function*() {\n      const span = yield* Effect.makeSpan(\"child\")\n      const parent = yield* Option.filter(span.parent, (span): span is Span => span._tag === \"Span\")\n      deepStrictEqual(parent.name, \"parent\")\n      strictEqual(span.attributes.get(\"code.stacktrace\"), undefined)\n      strictEqual(parent.attributes.get(\"code.stacktrace\"), undefined)\n    }).pipe(\n      Effect.provide(Layer.unwrapScoped(\n        Effect.map(\n          Effect.makeSpanScoped(\"parent\"),\n          (span) => Layer.parentSpan(span)\n        )\n      ))\n    ))\n\n  it.effect(\"Layer.span\", () =>\n    Effect.gen(function*() {\n      const span = yield* Effect.makeSpan(\"child\")\n      const parent = span.parent.pipe(\n        Option.filter((span): span is Span => span._tag === \"Span\"),\n        Option.getOrThrow\n      )\n      strictEqual(parent.name, \"parent\")\n      strictEqual(parent.attributes.get(\"code.stacktrace\"), undefined)\n    }).pipe(\n      Effect.provide(Layer.span(\"parent\"))\n    ))\n\n  it.effect(\"Layer.span onEnd\", () =>\n    Effect.gen(function*() {\n      let onEndCalled = false\n      const span = yield* pipe(\n        Effect.currentSpan,\n        Effect.provide(Layer.span(\"span\", {\n          onEnd: (span, _exit) =>\n            Effect.sync(() => {\n              strictEqual(span.name, \"span\")\n              onEndCalled = true\n            })\n        }))\n      )\n      strictEqual(span.name, \"span\")\n      strictEqual(onEndCalled, true)\n    }))\n\n  it.effect(\"linkSpans\", () =>\n    Effect.gen(function*() {\n      const childA = yield* (Effect.makeSpan(\"childA\"))\n      const childB = yield* (Effect.makeSpan(\"childB\"))\n      const currentSpan = yield* pipe(\n        Effect.currentSpan,\n        Effect.withSpan(\"A\", { links: [{ _tag: \"SpanLink\", span: childB, attributes: {} }] }),\n        Effect.linkSpans(childA)\n      )\n      deepStrictEqual(\n        currentSpan.links.map((_) => _.span),\n        [childA, childB]\n      )\n    }))\n\n  it.effect(\"Layer.withSpan\", () =>\n    Effect.gen(function*() {\n      let onEndCalled = false\n      const layer = Layer.effectDiscard(Effect.gen(function*() {\n        const span = yield* Effect.currentSpan\n        strictEqual(span.name, \"span\")\n        strictEqual(span.attributes.get(\"code.stacktrace\"), undefined)\n      })).pipe(\n        Layer.withSpan(\"span\", {\n          onEnd: (span, _exit) =>\n            Effect.sync(() => {\n              strictEqual(span.name, \"span\")\n              onEndCalled = true\n            })\n        })\n      )\n\n      const span = yield* pipe(Effect.currentSpan, Effect.provide(layer), Effect.option)\n\n      assertNone(span)\n      strictEqual(onEndCalled, true)\n    }))\n})\n\nit.effect(\"withTracerEnabled\", () =>\n  Effect.gen(function*() {\n    const span = yield* pipe(\n      Effect.currentSpan,\n      Effect.withSpan(\"A\"),\n      Effect.withTracerEnabled(false)\n    )\n    const spanB = yield* pipe(\n      Effect.currentSpan,\n      Effect.withSpan(\"B\"),\n      Effect.withTracerEnabled(true)\n    )\n\n    deepStrictEqual(span.name, \"A\")\n    deepStrictEqual(span.spanId, \"noop\")\n    deepStrictEqual(spanB.name, \"B\")\n  }))\n\ndescribe(\"Tracer.DisablePropagation\", () => {\n  it.effect(\"creates noop span\", () =>\n    Effect.gen(function*() {\n      const span = yield* Effect.currentSpan.pipe(\n        Effect.withSpan(\"A\", { context: Tracer.DisablePropagation.context(true) })\n      )\n      const spanB = yield* Effect.currentSpan.pipe(\n        Effect.withSpan(\"B\")\n      )\n\n      deepStrictEqual(span.name, \"A\")\n      deepStrictEqual(span.spanId, \"noop\")\n      deepStrictEqual(spanB.name, \"B\")\n    }))\n\n  it.effect(\"isnt used as parent span\", () =>\n    Effect.gen(function*() {\n      const span = yield* Effect.currentSpan.pipe(\n        Effect.withSpan(\"child\"),\n        Effect.withSpan(\"disabled\", { context: Tracer.DisablePropagation.context(true) }),\n        Effect.withSpan(\"parent\")\n      )\n      strictEqual(span.name, \"child\")\n      assertTrue(span.parent._tag === \"Some\" && span.parent.value._tag === \"Span\")\n      strictEqual(span.parent.value.name, \"parent\")\n    }))\n})\n\ndescribe(\"functionWithSpan\", () => {\n  const getSpan = Effect.functionWithSpan({\n    body: (_id: string) => Effect.currentSpan,\n    options: (id) => ({\n      name: `span-${id}`,\n      attributes: { id }\n    })\n  })\n\n  it.effect(\"no parent\", () =>\n    Effect.gen(function*() {\n      const span = yield* getSpan(\"A\")\n      deepStrictEqual(span.name, \"span-A\")\n      assertNone(span.parent)\n      strictEqual(span.attributes.get(\"code.stacktrace\"), undefined)\n    }))\n\n  it.effect(\"parent\", () =>\n    Effect.gen(function*() {\n      const span = yield* Effect.withSpan(\"B\")(getSpan(\"A\"))\n      deepStrictEqual(span.name, \"span-A\")\n      deepStrictEqual(Option.map(span.parent, (span) => (span as Span).name), Option.some(\"B\"))\n    }))\n})\n"
  },
  {
    "path": "packages/effect/test/Trie.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { assertNone, assertSome, deepStrictEqual, strictEqual, throws } from \"@effect/vitest/utils\"\nimport * as Equal from \"effect/Equal\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Trie from \"effect/Trie\"\n\ndescribe(\"Trie\", () => {\n  it(\"toString\", () => {\n    const trie = pipe(\n      Trie.empty<number>(),\n      Trie.insert(\"a\", 0),\n      Trie.insert(\"b\", 1)\n    )\n\n    strictEqual(\n      String(trie),\n      `{\n  \"_id\": \"Trie\",\n  \"values\": [\n    [\n      \"a\",\n      0\n    ],\n    [\n      \"b\",\n      1\n    ]\n  ]\n}`\n    )\n  })\n\n  it(\"toJSON\", () => {\n    const trie = pipe(\n      Trie.empty<number>(),\n      Trie.insert(\"a\", 0),\n      Trie.insert(\"b\", 1)\n    )\n\n    deepStrictEqual(trie.toJSON(), { _id: \"Trie\", values: [[\"a\", 0], [\"b\", 1]] })\n  })\n\n  it(\"inspect\", () => {\n    if (typeof window !== \"undefined\") {\n      return\n    }\n    // eslint-disable-next-line @typescript-eslint/no-require-imports\n    const { inspect } = require(\"node:util\")\n\n    const trie = pipe(\n      Trie.empty<number>(),\n      Trie.insert(\"a\", 0),\n      Trie.insert(\"b\", 1)\n    )\n\n    deepStrictEqual(inspect(trie), inspect({ _id: \"Trie\", values: [[\"a\", 0], [\"b\", 1]] }))\n  })\n\n  it(\"iterable empty\", () => {\n    const trie = Trie.empty<string>()\n\n    strictEqual(Trie.size(trie), 0)\n    deepStrictEqual(Array.from(trie), [])\n  })\n\n  it(\"insert\", () => {\n    const trie1 = Trie.empty<number>().pipe(\n      Trie.insert(\"call\", 0)\n    )\n\n    const trie2 = trie1.pipe(Trie.insert(\"me\", 1))\n    const trie3 = trie2.pipe(Trie.insert(\"mind\", 2))\n    const trie4 = trie3.pipe(Trie.insert(\"mid\", 3))\n\n    deepStrictEqual(Array.from(trie1), [[\"call\", 0]])\n    deepStrictEqual(Array.from(trie2), [[\"call\", 0], [\"me\", 1]])\n    deepStrictEqual(Array.from(trie3), [[\"call\", 0], [\"me\", 1], [\"mind\", 2]])\n    deepStrictEqual(Array.from(trie4), [[\"call\", 0], [\"me\", 1], [\"mid\", 3], [\"mind\", 2]])\n  })\n\n  it(\"fromIterable empty\", () => {\n    const iterable: Array<[string, number]> = []\n    const trie = Trie.fromIterable(iterable)\n    deepStrictEqual(Array.from(trie), iterable)\n  })\n\n  it(\"make\", () => {\n    const trie = Trie.make([\"ca\", 0], [\"me\", 1])\n    deepStrictEqual(Array.from(trie), [[\"ca\", 0], [\"me\", 1]])\n    strictEqual(Equal.equals(Trie.fromIterable([[\"ca\", 0], [\"me\", 1]]), trie), true)\n  })\n\n  it(\"fromIterable [1]\", () => {\n    const iterable: Array<[string, number]> = [[\"ca\", 0], [\"me\", 1]]\n    const trie = Trie.fromIterable(iterable)\n    deepStrictEqual(Array.from(trie), iterable)\n    strictEqual(Equal.equals(Trie.make([\"ca\", 0], [\"me\", 1]), trie), true)\n  })\n\n  it(\"fromIterable [2]\", () => {\n    const iterable: Array<readonly [string, number]> = [[\"call\", 0], [\"me\", 1], [\"mind\", 2], [\"mid\", 3]]\n    const trie = Trie.fromIterable(iterable)\n    deepStrictEqual(Array.from(trie), [[\"call\", 0], [\"me\", 1], [\"mid\", 3], [\"mind\", 2]])\n  })\n\n  it(\"fromIterable [3]\", () => {\n    const iterable: Array<[string, number]> = [[\"a\", 0], [\"b\", 1]]\n    const trie = Trie.fromIterable(iterable)\n    deepStrictEqual(Array.from(trie), iterable)\n  })\n\n  it(\"fromIterable [4]\", () => {\n    const iterable: Array<[string, number]> = [[\"a\", 0]]\n    const trie = Trie.fromIterable(iterable)\n    deepStrictEqual(Array.from(trie), iterable)\n  })\n\n  it(\"fromIterable [5]\", () => {\n    const iterable: Array<[string, number]> = [[\"shells\", 0], [\"she\", 1]]\n    const trie = Trie.fromIterable(iterable)\n    deepStrictEqual(Array.from(trie), [[\"she\", 1], [\"shells\", 0]])\n  })\n\n  it(\"size\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"a\", 0),\n      Trie.insert(\"b\", 1)\n    )\n\n    strictEqual(Trie.size(trie), 2)\n  })\n\n  it(\"isEmpty\", () => {\n    const trie = Trie.empty<number>()\n    const trie1 = trie.pipe(Trie.insert(\"ma\", 0))\n    strictEqual(Trie.isEmpty(trie), true)\n    strictEqual(Trie.isEmpty(trie1), false)\n  })\n\n  it(\"get [1]\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"call\", 0),\n      Trie.insert(\"me\", 1),\n      Trie.insert(\"mind\", 2),\n      Trie.insert(\"mid\", 3)\n    )\n    assertSome(Trie.get(trie, \"call\"), 0)\n    assertSome(Trie.get(trie, \"me\"), 1)\n    assertSome(Trie.get(trie, \"mind\"), 2)\n    assertSome(Trie.get(trie, \"mid\"), 3)\n    assertNone(Trie.get(trie, \"cale\"))\n    assertNone(Trie.get(trie, \"ma\"))\n    assertNone(Trie.get(trie, \"midn\"))\n    assertNone(Trie.get(trie, \"mea\"))\n  })\n\n  it(\"get [2]\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"she\", 2)\n    )\n\n    assertNone(Trie.get(trie, \"sell\"))\n    assertSome(Trie.get(trie, \"sells\"), 1)\n    assertNone(Trie.get(trie, \"shell\"))\n    assertSome(Trie.get(trie, \"she\"), 2)\n  })\n\n  it(\"has\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"call\", 0),\n      Trie.insert(\"me\", 1),\n      Trie.insert(\"mind\", 2),\n      Trie.insert(\"mid\", 3)\n    )\n    strictEqual(Trie.has(trie, \"call\"), true)\n    strictEqual(Trie.has(trie, \"me\"), true)\n    strictEqual(Trie.has(trie, \"mind\"), true)\n    strictEqual(Trie.has(trie, \"mid\"), true)\n    strictEqual(Trie.has(trie, \"cale\"), false)\n    strictEqual(Trie.has(trie, \"ma\"), false)\n    strictEqual(Trie.has(trie, \"midn\"), false)\n    strictEqual(Trie.has(trie, \"mea\"), false)\n  })\n\n  it(\"unsafeGet\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"call\", 0),\n      Trie.insert(\"me\", 1)\n    )\n    throws(() => Trie.unsafeGet(trie, \"mae\"))\n  })\n\n  it(\"remove\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"call\", 0),\n      Trie.insert(\"me\", 1),\n      Trie.insert(\"mind\", 2),\n      Trie.insert(\"mid\", 3)\n    )\n\n    const trie1 = trie.pipe(Trie.remove(\"call\"))\n    const trie2 = trie1.pipe(Trie.remove(\"mea\"))\n\n    deepStrictEqual(Trie.get(trie, \"call\"), Option.some(0))\n    deepStrictEqual(Trie.get(trie1, \"call\"), Option.none())\n    deepStrictEqual(Trie.get(trie2, \"call\"), Option.none())\n\n    deepStrictEqual(Array.from(trie), [[\"call\", 0], [\"me\", 1], [\"mid\", 3], [\"mind\", 2]])\n    deepStrictEqual(Array.from(trie1), [[\"me\", 1], [\"mid\", 3], [\"mind\", 2]])\n    deepStrictEqual(Array.from(trie2), [[\"me\", 1], [\"mid\", 3], [\"mind\", 2]])\n  })\n\n  it(\"keys\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"cab\", 0),\n      Trie.insert(\"abc\", 1),\n      Trie.insert(\"bca\", 2)\n    )\n\n    const result = Array.from(Trie.keys(trie))\n    deepStrictEqual(result, [\"abc\", \"bca\", \"cab\"])\n  })\n\n  it(\"keys alphabetical order\", () => {\n    const trie = Trie.make(\n      [\"abc\", 0],\n      [\"bac\", 0],\n      [\"b\", 0],\n      [\"ca\", 0],\n      [\"cac\", 0],\n      [\"c\", 0],\n      [\"abb\", 0],\n      [\"ba\", 0],\n      [\"a\", 0],\n      [\"bca\", 0],\n      [\"cab\", 0],\n      [\"dca\", 0],\n      [\"ab\", 0],\n      [\"adc\", 0]\n    )\n\n    const result = Array.from(Trie.keys(trie))\n    deepStrictEqual(result, [\n      \"a\",\n      \"ab\",\n      \"abb\",\n      \"abc\",\n      \"adc\",\n      \"b\",\n      \"ba\",\n      \"bac\",\n      \"bca\",\n      \"c\",\n      \"ca\",\n      \"cab\",\n      \"cac\",\n      \"dca\"\n    ])\n  })\n\n  it(\"values\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"call\", 0),\n      Trie.insert(\"me\", 1),\n      Trie.insert(\"and\", 2)\n    )\n\n    const result = Array.from(Trie.values(trie))\n    deepStrictEqual(result, [2, 0, 1])\n  })\n\n  it(\"entries\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"call\", 0),\n      Trie.insert(\"me\", 1)\n    )\n\n    const result = Array.from(Trie.entries(trie))\n    deepStrictEqual(result, [[\"call\", 0], [\"me\", 1]])\n  })\n\n  it(\"toEntries\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"call\", 0),\n      Trie.insert(\"me\", 1)\n    )\n\n    const result = Trie.toEntries(trie)\n    deepStrictEqual(result, [[\"call\", 0], [\"me\", 1]])\n  })\n\n  it(\"keysWithPrefix\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"she\", 0),\n      Trie.insert(\"shells\", 1),\n      Trie.insert(\"sea\", 2),\n      Trie.insert(\"sells\", 3),\n      Trie.insert(\"by\", 4),\n      Trie.insert(\"the\", 5),\n      Trie.insert(\"sea\", 6),\n      Trie.insert(\"shore\", 7)\n    )\n\n    const result = Array.from(Trie.keysWithPrefix(trie, \"she\"))\n    deepStrictEqual(result, [\"she\", \"shells\"])\n  })\n\n  it(\"valuesWithPrefix\", () => {\n    const trie = pipe(\n      Trie.empty<number>(),\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"sea\", 2),\n      Trie.insert(\"she\", 3)\n    )\n\n    const result = Array.from(Trie.valuesWithPrefix(trie, \"she\"))\n    deepStrictEqual(result, [3, 0])\n  })\n\n  it(\"entriesWithPrefix\", () => {\n    const trie = pipe(\n      Trie.empty<number>(),\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"sea\", 2),\n      Trie.insert(\"she\", 3)\n    )\n\n    const result = Array.from(Trie.entriesWithPrefix(trie, \"she\"))\n    deepStrictEqual(result, [[\"she\", 3], [\"shells\", 0]])\n  })\n\n  it(\"toEntriesWithPrefix\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"sea\", 2),\n      Trie.insert(\"she\", 3)\n    )\n\n    const result = Trie.toEntriesWithPrefix(trie, \"she\")\n    deepStrictEqual(result, [[\"she\", 3], [\"shells\", 0]])\n  })\n\n  it(\"longestPrefixOf\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"she\", 2)\n    )\n\n    deepStrictEqual(Trie.longestPrefixOf(trie, \"sell\"), Option.none())\n    deepStrictEqual(Trie.longestPrefixOf(trie, \"sells\"), Option.some([\"sells\", 1]))\n    deepStrictEqual(Trie.longestPrefixOf(trie, \"shell\"), Option.some([\"she\", 2]))\n    deepStrictEqual(Trie.longestPrefixOf(trie, \"shellsort\"), Option.some([\"shells\", 0]))\n  })\n\n  it(\"map\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"she\", 2)\n    )\n\n    const trieMapV = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 1),\n      Trie.insert(\"sells\", 2),\n      Trie.insert(\"she\", 3)\n    )\n\n    const trieMapK = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 6),\n      Trie.insert(\"sells\", 5),\n      Trie.insert(\"she\", 3)\n    )\n\n    strictEqual(Equal.equals(Trie.map(trie, (v) => v + 1), trieMapV), true)\n    strictEqual(Equal.equals(Trie.map(trie, (_, k) => k.length), trieMapK), true)\n  })\n\n  it(\"filter\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"she\", 2)\n    )\n\n    const trieMapV = Trie.empty<number>().pipe(\n      Trie.insert(\"she\", 2)\n    )\n\n    const trieMapK = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1)\n    )\n\n    strictEqual(Equal.equals(Trie.filter(trie, (v) => v > 1), trieMapV), true)\n    strictEqual(Equal.equals(Trie.filter(trie, (_, k) => k.length > 3), trieMapK), true)\n  })\n\n  it(\"filterMap\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"she\", 2)\n    )\n\n    const trieMapV = Trie.empty<number>().pipe(\n      Trie.insert(\"she\", 2)\n    )\n\n    const trieMapK = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1)\n    )\n\n    strictEqual(Equal.equals(Trie.filterMap(trie, (v) => v > 1 ? Option.some(v) : Option.none()), trieMapV), true)\n    strictEqual(\n      Equal.equals(Trie.filterMap(trie, (v, k) => k.length > 3 ? Option.some(v) : Option.none()), trieMapK),\n      true\n    )\n  })\n\n  it(\"compact\", () => {\n    const trie = Trie.empty<Option.Option<number>>().pipe(\n      Trie.insert(\"shells\", Option.some(0)),\n      Trie.insert(\"sells\", Option.none()),\n      Trie.insert(\"she\", Option.some(2))\n    )\n\n    const trieMapV = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"she\", 2)\n    )\n\n    strictEqual(Equal.equals(Trie.compact(trie), trieMapV), true)\n  })\n\n  it(\"modify\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"she\", 2)\n    )\n\n    deepStrictEqual(trie.pipe(Trie.modify(\"she\", (v) => v + 10), Trie.get(\"she\")), Option.some(12))\n    strictEqual(Equal.equals(trie.pipe(Trie.modify(\"me\", (v) => v)), trie), true)\n  })\n\n  it(\"removeMany\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"she\", 2)\n    )\n\n    strictEqual(\n      Equal.equals(trie.pipe(Trie.removeMany([\"she\", \"sells\"])), Trie.empty<number>().pipe(Trie.insert(\"shells\", 0))),\n      true\n    )\n  })\n\n  it(\"insertMany\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"she\", 2)\n    )\n\n    const trieInsert = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insertMany(\n        [[\"sells\", 1], [\"she\", 2]]\n      )\n    )\n\n    strictEqual(\n      Equal.equals(trie, trieInsert),\n      true\n    )\n  })\n\n  it(\"reduce\", () => {\n    const trie = Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"she\", 2)\n    )\n\n    strictEqual(\n      trie.pipe(\n        Trie.reduce(0, (acc, n) => acc + n)\n      ),\n      3\n    )\n    strictEqual(\n      trie.pipe(\n        Trie.reduce(10, (acc, n) => acc + n)\n      ),\n      13\n    )\n    strictEqual(\n      trie.pipe(\n        Trie.reduce(\"\", (acc, _, key) => acc + key)\n      ),\n      \"sellssheshells\"\n    )\n  })\n\n  it(\"forEach\", () => {\n    let value = 0\n\n    Trie.empty<number>().pipe(\n      Trie.insert(\"shells\", 0),\n      Trie.insert(\"sells\", 1),\n      Trie.insert(\"she\", 2),\n      Trie.forEach((n, key) => {\n        value += n + key.length\n      })\n    )\n\n    strictEqual(value, 17)\n  })\n\n  it(\"Equal.symbol\", () => {\n    strictEqual(\n      Equal.equals(Trie.empty<number>(), Trie.empty<number>()),\n      true\n    )\n    strictEqual(\n      Equal.equals(\n        Trie.make([\"call\", 0], [\"me\", 1]),\n        Trie.make([\"call\", 0], [\"me\", 1])\n      ),\n      true\n    )\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/Tuple.test.ts",
    "content": "import { describe, it } from \"@effect/vitest\"\nimport { deepStrictEqual, strictEqual } from \"@effect/vitest/utils\"\nimport { pipe, Tuple } from \"effect\"\n\ndescribe(\"Tuple\", () => {\n  it(\"make\", () => {\n    deepStrictEqual(Tuple.make(\"a\", 1, true), [\"a\", 1, true])\n  })\n\n  it(\"appendElement\", () => {\n    deepStrictEqual(pipe(Tuple.make(\"a\", 1), Tuple.appendElement(true)), [\"a\", 1, true])\n  })\n\n  it(\"getFirst\", () => {\n    strictEqual(Tuple.getFirst(Tuple.make(\"a\", 1)), \"a\")\n  })\n\n  it(\"getSecond\", () => {\n    strictEqual(Tuple.getSecond(Tuple.make(\"a\", 1)), 1)\n  })\n\n  it(\"mapBoth\", () => {\n    deepStrictEqual(\n      Tuple.mapBoth(Tuple.make(\"a\", 1), {\n        onFirst: (s) => s + \"!\",\n        onSecond: (n) => n * 2\n      }),\n      [\"a!\", 2]\n    )\n  })\n\n  it(\"map\", () => {\n    deepStrictEqual(Tuple.map([\"a\", 1, false], (x) => x.toString().toUpperCase()), [\"A\", \"1\", \"FALSE\"])\n  })\n\n  it(\"swap\", () => {\n    deepStrictEqual(Tuple.swap(Tuple.make(\"a\", 1)), [1, \"a\"])\n  })\n\n  it(\"at\", () => {\n    deepStrictEqual(Tuple.at([1, \"hello\", true], 1), \"hello\")\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/assertions.test.ts",
    "content": "import { Cause, Option } from \"effect\"\nimport * as assert from \"node:assert\"\nimport { assert as vassert, describe, expect, it } from \"vitest\"\nimport * as Util from \"./util.js\"\n\n// where `fails: false` there is a problem with the assertion library\n\ndescribe(\"node:assert\", () => {\n  describe(\"Option\", () => {\n    describe(\"none vs some\", () => {\n      it(\"deepStrictEqual\", { fails: true }, () => {\n        assert.deepStrictEqual(Option.none(), Option.some(2))\n      })\n    })\n  })\n\n  describe(\"Cause\", () => {\n    describe(\"sequential vs parallel\", () => {\n      it(\"deepStrictEqual\", { fails: true }, () => {\n        assert.deepStrictEqual(Cause.sequential(Cause.empty, Cause.empty), Cause.parallel(Cause.empty, Cause.empty))\n      })\n    })\n  })\n})\n\ndescribe(\"vitest assert\", () => {\n  describe(\"Option\", () => {\n    describe(\"none vs some\", () => {\n      it(\"deepStrictEqual\", { fails: false }, () => {\n        vassert.deepStrictEqual(Option.none(), Option.some(2))\n      })\n    })\n  })\n\n  describe(\"Cause\", () => {\n    describe(\"sequential vs parallel\", () => {\n      it(\"deepStrictEqual\", { fails: true }, () => {\n        vassert.deepStrictEqual(Cause.sequential(Cause.empty, Cause.empty), Cause.parallel(Cause.empty, Cause.empty))\n      })\n    })\n  })\n})\n\ndescribe(\"expect\", () => {\n  describe(\"Option\", () => {\n    describe(\"none vs some\", () => {\n      it(\"toEqual\", { fails: true }, () => {\n        expect(Option.none()).toEqual(Option.some(1))\n      })\n\n      it(\"toStrictEqual\", { fails: true }, () => {\n        expect(Option.none()).toStrictEqual(Option.some(1))\n      })\n    })\n  })\n\n  describe(\"Cause\", () => {\n    describe(\"sequential vs parallel\", () => {\n      it(\"toEqual\", { fails: false }, () => {\n        expect(Cause.sequential(Cause.empty, Cause.empty)).toEqual(Cause.parallel(Cause.empty, Cause.empty))\n      })\n\n      it(\"toStrictEqual\", { fails: false }, () => {\n        expect(Cause.sequential(Cause.empty, Cause.empty)).toStrictEqual(Cause.parallel(Cause.empty, Cause.empty))\n      })\n    })\n  })\n})\n\ndescribe(\"utils\", () => {\n  it(\"assertInstanceOf\", () => {\n    Util.assertInstanceOf(new Error(), Error)\n    Util.throws(() => Util.assertInstanceOf(1, Error), (err) => {\n      Util.assertTrue(err instanceof Error)\n      Util.strictEqual(err.message, \"expected 1 to be an instance of Error\")\n    })\n  })\n\n  it(\"assertInclude\", () => {\n    Util.assertInclude(\"abc\", \"b\")\n    Util.throws(() => Util.assertInclude(undefined, \"a\"), (err) => {\n      Util.assertTrue(err instanceof Error)\n      Util.strictEqual(\n        err.message,\n        `Expected\n\nundefined\n\nto include\n\na`\n      )\n    })\n  })\n\n  it(\"assertMatch\", () => {\n    Util.assertMatch(\"abc\", /b/)\n    Util.throws(() => Util.assertMatch(\"a\", /b/), (err) => {\n      Util.assertTrue(err instanceof Error)\n      Util.strictEqual(\n        err.message,\n        `Expected\n\na\n\nto match\n\n/b/`\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/effect/test/util.ts",
    "content": "import type { Cause } from \"effect\"\nimport { Either, Equal, Exit, Option, Predicate } from \"effect\"\nimport * as assert from \"node:assert\"\nimport { assert as vassert } from \"vitest\"\n\n// ----------------------------\n// Primitives\n// ----------------------------\n\n/**\n * Throws an `AssertionError` with the provided error message.\n */\nexport function fail(message: string) {\n  assert.fail(message)\n}\n\nexport function deepStrictEqual<A>(actual: A, expected: A, message?: string, ..._: Array<never>) {\n  assert.deepStrictEqual(actual, expected, message)\n}\n\nexport function notDeepStrictEqual<A>(actual: A, expected: A, message?: string, ..._: Array<never>) {\n  assert.notDeepStrictEqual(actual, expected, message)\n}\n\nexport function strictEqual<A>(actual: A, expected: A, message?: string, ..._: Array<never>) {\n  assert.strictEqual(actual, expected, message)\n}\n\n/**\n * Asserts that `actual` is equal to `expected` using the `Equal.equals` trait.\n */\nexport function assertEquals<A>(actual: A, expected: A, message?: string, ..._: Array<never>) {\n  if (!Equal.equals(actual, expected)) {\n    deepStrictEqual(actual, expected, message) // show diff\n    fail(message ?? \"Expected values to be Equal.equals\")\n  }\n}\n\nexport function doesNotThrow(thunk: () => void, message?: string, ..._: Array<never>) {\n  assert.doesNotThrow(thunk, message)\n}\n\n// ----------------------------\n// Derived\n// ----------------------------\n\n/**\n * Asserts that `value` is an instance of `constructor`.\n */\nexport function assertInstanceOf<C extends abstract new(...args: any) => any>(\n  value: unknown,\n  constructor: C,\n  message?: string,\n  ..._: Array<never>\n): asserts value is InstanceType<C> {\n  // @ts-ignore\n  vassert.instanceOf(value, constructor, message)\n}\n\nexport function assertTrue(self: unknown, message?: string, ..._: Array<never>): asserts self {\n  strictEqual(self, true, message)\n}\n\nexport function assertFalse(self: boolean, message?: string, ..._: Array<never>) {\n  strictEqual(self, false, message)\n}\n\nexport function assertInclude(actual: string | undefined, expected: string, ..._: Array<never>) {\n  if (Predicate.isString(expected)) {\n    if (!actual?.includes(expected)) {\n      fail(`Expected\\n\\n${actual}\\n\\nto include\\n\\n${expected}`)\n    }\n  }\n}\n\nexport function assertMatch(actual: string, regexp: RegExp, ..._: Array<never>) {\n  if (!regexp.test(actual)) {\n    fail(`Expected\\n\\n${actual}\\n\\nto match\\n\\n${regexp}`)\n  }\n}\n\nexport function throws(thunk: () => void, error?: Error | ((u: unknown) => undefined), ..._: Array<never>) {\n  try {\n    thunk()\n    fail(\"Expected to throw an error\")\n  } catch (e) {\n    if (error !== undefined) {\n      if (Predicate.isFunction(error)) {\n        error(e)\n      } else {\n        deepStrictEqual(e, error)\n      }\n    }\n  }\n}\n\nexport async function throwsAsync(\n  thunk: () => Promise<void>,\n  error?: Error | ((u: unknown) => undefined),\n  ..._: Array<never>\n) {\n  try {\n    await thunk()\n    fail(\"Expected to throw an error\")\n  } catch (e) {\n    if (error !== undefined) {\n      if (Predicate.isFunction(error)) {\n        error(e)\n      } else {\n        deepStrictEqual(e, error)\n      }\n    }\n  }\n}\n\n// ----------------------------\n// Option\n// ----------------------------\n\nexport function assertNone<A>(option: Option.Option<A>, ..._: Array<never>): asserts option is Option.None<never> {\n  deepStrictEqual(option, Option.none())\n}\n\nexport function assertSome<A>(\n  option: Option.Option<A>,\n  expected: A,\n  ..._: Array<never>\n): asserts option is Option.Some<A> {\n  deepStrictEqual(option, Option.some(expected))\n}\n\n// ----------------------------\n// Either\n// ----------------------------\n\nexport function assertLeft<R, L>(\n  either: Either.Either<R, L>,\n  expected: L,\n  ..._: Array<never>\n): asserts either is Either.Left<L, never> {\n  deepStrictEqual(either, Either.left(expected))\n}\n\nexport function assertRight<R, L>(\n  either: Either.Either<R, L>,\n  expected: R,\n  ..._: Array<never>\n): asserts either is Either.Right<never, R> {\n  deepStrictEqual(either, Either.right(expected))\n}\n\n// ----------------------------\n// Exit\n// ----------------------------\n\nexport function assertFailure<A, E>(\n  exit: Exit.Exit<A, E>,\n  expected: Cause.Cause<E>,\n  ..._: Array<never>\n): asserts exit is Exit.Failure<never, E> {\n  deepStrictEqual(exit, Exit.failCause(expected))\n}\n\nexport function assertSuccess<A, E>(\n  exit: Exit.Exit<A, E>,\n  expected: A,\n  ..._: Array<never>\n): asserts exit is Exit.Success<A, never> {\n  deepStrictEqual(exit, Exit.succeed(expected))\n}\n"
  },
  {
    "path": "packages/effect/test/utils/cache/ObservableResource.ts",
    "content": "import { strictEqual } from \"@effect/vitest/utils\"\nimport * as Effect from \"effect/Effect\"\nimport * as ExecutionStrategy from \"effect/ExecutionStrategy\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport * as Scope from \"effect/Scope\"\n\nexport interface ObservableResource<E, V> {\n  readonly scoped: Effect.Effect<V, E, Scope.Scope>\n  assertNotAcquired(): Effect.Effect<void>\n  assertAcquiredOnceAndCleaned(): Effect.Effect<void>\n  assertAcquiredOnceAndNotCleaned(): Effect.Effect<void>\n}\n\nclass ObservableResourceImpl<E, V> implements ObservableResource<E, V> {\n  constructor(\n    readonly scoped: Effect.Effect<V, E, Scope.Scope>,\n    readonly getState: Effect.Effect<readonly [number, number]>\n  ) {}\n\n  assertNotAcquired(): Effect.Effect<void> {\n    return Effect.map(this.getState, ([numAcquisition, numCleaned]) => {\n      strictEqual(numAcquisition, 0, \"Resource acquired when it should not have\")\n      strictEqual(numCleaned, 0, \"Resource cleaned when it should not have\")\n    })\n  }\n\n  assertAcquiredOnceAndCleaned(): Effect.Effect<void> {\n    return Effect.map(this.getState, ([numAcquisition, numCleaned]) => {\n      strictEqual(numAcquisition, 1, \"Resource not acquired once\")\n      strictEqual(numCleaned, 1, \"Resource not cleaned when it should have\")\n    })\n  }\n\n  assertAcquiredOnceAndNotCleaned(): Effect.Effect<void> {\n    return Effect.map(this.getState, ([numAcquisition, numCleaned]) => {\n      strictEqual(numAcquisition, 1, \"Resource not acquired once\")\n      strictEqual(numCleaned, 0, \"Resource cleaned when it should not have\")\n    })\n  }\n}\n\nexport const makeVoid = (): Effect.Effect<ObservableResource<never, void>> => make(void 0)\n\nexport const make = <V>(value: V): Effect.Effect<ObservableResource<never, V>> => makeEffect(Effect.succeed(value))\n\nexport const makeEffect = <V, E>(\n  effect: Effect.Effect<V, E>\n): Effect.Effect<ObservableResource<E, V>> =>\n  pipe(\n    Effect.zip(Ref.make(0), Ref.make(0)),\n    Effect.map(([resourceAcquisitionCount, resourceAcquisitionReleasing]) => {\n      const getState = Effect.zip(\n        Ref.get(resourceAcquisitionCount),\n        Ref.get(resourceAcquisitionReleasing)\n      )\n      const scoped = Effect.uninterruptibleMask((restore) =>\n        Effect.gen(function*() {\n          const parent = yield* Effect.scope\n          const child = yield* Scope.fork(parent, ExecutionStrategy.sequential)\n          yield* Ref.update(resourceAcquisitionCount, (n) => n + 1)\n          yield* Scope.addFinalizer(child, Ref.update(resourceAcquisitionReleasing, (n) => n + 1))\n          return yield* Effect.acquireReleaseInterruptible(\n            restore(effect),\n            (exit) => Scope.close(child, exit)\n          )\n        })\n      )\n      return new ObservableResourceImpl(scoped, getState)\n    })\n  )\n"
  },
  {
    "path": "packages/effect/test/utils/cache/WatchableLookup.ts",
    "content": "import { assertTrue } from \"@effect/vitest/utils\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as HashMap from \"effect/HashMap\"\nimport * as Option from \"effect/Option\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport type * as Scope from \"effect/Scope\"\nimport * as TestServices from \"effect/TestServices\"\nimport * as ObservableResource from \"./ObservableResource.js\"\n\nexport interface WatchableLookup<Key, Value, Error = never> {\n  (key: Key): Effect.Effect<Value, Error, Scope.Scope>\n  lock: () => Effect.Effect<void>\n  unlock: () => Effect.Effect<void>\n  createdResources: () => Effect.Effect<\n    HashMap.HashMap<Key, Chunk.Chunk<ObservableResource.ObservableResource<Error, Value>>>\n  >\n  firstCreatedResource: (key: Key) => Effect.Effect<ObservableResource.ObservableResource<Error, Value>>\n  getCalledTimes: (key: Key) => Effect.Effect<number>\n  resourcesCleaned: (\n    resources: Iterable<ObservableResource.ObservableResource<Error, Value>>\n  ) => Effect.Effect<void>\n  assertCalledTimes: (key: Key, sizeAssertion: (value: number) => void) => Effect.Effect<void>\n  assertFirstNCreatedResourcesCleaned: (key: Key, n: number) => Effect.Effect<void>\n  assertAllCleaned: () => Effect.Effect<void>\n  assertAllCleanedForKey: (key: Key) => Effect.Effect<void>\n  assertAtLeastOneResourceNotCleanedForKey: (key: Key) => Effect.Effect<void>\n}\n\nexport const make = <Key, Value>(\n  concreteLookup: (key: Key) => Value\n): Effect.Effect<WatchableLookup<Key, Value>> => makeEffect((key) => Effect.succeed(concreteLookup(key)))\n\nexport const makeVoid = (): Effect.Effect<WatchableLookup<void, void>> => make<void, void>((_: void) => void 0)\n\nexport const makeEffect = <Key, Value, Error = never>(\n  concreteLookup: (key: Key) => Effect.Effect<Value, Error>\n): Effect.Effect<WatchableLookup<Key, Value, Error>> =>\n  Effect.map(\n    Effect.zip(\n      Ref.make(false),\n      Ref.make(HashMap.empty<Key, Chunk.Chunk<ObservableResource.ObservableResource<Error, Value>>>())\n    ),\n    ([blocked, resources]): WatchableLookup<Key, Value, Error> => {\n      function lookup(key: Key): Effect.Effect<Value, Error, Scope.Scope> {\n        return Effect.flatten(Effect.gen(function*() {\n          const observableResource = yield* ObservableResource.makeEffect(concreteLookup(key))\n          yield* Ref.update(resources, (resourceMap) => {\n            const newResource = pipe(\n              HashMap.get(resourceMap, key),\n              Option.getOrElse(() => Chunk.empty<ObservableResource.ObservableResource<Error, Value>>()),\n              Chunk.append(observableResource)\n            )\n            return HashMap.set(resourceMap, key, newResource)\n          })\n          const schedule = Schedule.intersect(\n            Schedule.recurWhile<boolean>(identity),\n            Schedule.exponential(Duration.millis(10), 2.0)\n          )\n          yield* pipe(\n            Ref.get(blocked),\n            Effect.repeat(schedule),\n            TestServices.provideLive\n          )\n          return observableResource.scoped\n        }))\n      }\n      const lock = () => Ref.set(blocked, true)\n      const unlock = () => Ref.set(blocked, false)\n      const createdResources = () => Ref.get(resources)\n      const firstCreatedResource = (key: Key) =>\n        Effect.map(\n          Ref.get(resources),\n          (map) => Chunk.unsafeHead(HashMap.unsafeGet(map, key))\n        )\n      const getCalledTimes = (key: Key) =>\n        Effect.map(\n          createdResources(),\n          (map) =>\n            Option.match(HashMap.get(map, key), {\n              onNone: () => 0,\n              onSome: Chunk.size\n            })\n        )\n      const resourcesCleaned = (resources: Iterable<ObservableResource.ObservableResource<Error, Value>>) =>\n        Effect.forEach(resources, (resource) => Effect.suspend(() => resource.assertAcquiredOnceAndCleaned()))\n      const assertCalledTimes = (key: Key, sizeAssertion: (value: number) => void) =>\n        Effect.flatMap(getCalledTimes(key), (n) => Effect.sync(() => sizeAssertion(n)))\n      const assertFirstNCreatedResourcesCleaned = (key: Key, n: number) =>\n        Effect.flatMap(createdResources(), (resources) =>\n          resourcesCleaned(pipe(\n            HashMap.get(resources, key),\n            Option.match({\n              onNone: () => Chunk.empty<ObservableResource.ObservableResource<Error, Value>>(),\n              onSome: Chunk.take(n)\n            })\n          )))\n      const assertAllCleaned = () =>\n        Effect.flatMap(createdResources(), (resources) =>\n          resourcesCleaned(\n            Chunk.flatten(Chunk.unsafeFromArray(HashMap.toValues(resources)))\n          ))\n      const assertAllCleanedForKey = (key: Key) =>\n        Effect.flatMap(createdResources(), (resources) =>\n          resourcesCleaned(pipe(HashMap.get(resources, key), Option.getOrElse(() => Chunk.empty()))))\n      const assertAtLeastOneResourceNotCleanedForKey = (key: Key) =>\n        Effect.flatMap(createdResources(), (resources) => {\n          const resourcesForKey = pipe(\n            HashMap.get(resources, key),\n            Option.getOrElse(() =>\n              Chunk.empty()\n            )\n          )\n          return pipe(\n            Effect.reduce(resourcesForKey, false, (acc, resource) =>\n              pipe(\n                Effect.suspend(() => resource.assertAcquiredOnceAndNotCleaned()),\n                Effect.isSuccess,\n                Effect.map((isSuccess) => acc || isSuccess)\n              )),\n            Effect.map((atLeastOneNotCleaned) => Effect.sync(() => assertTrue(atLeastOneNotCleaned)))\n          )\n        })\n      return Object.assign(lookup, {\n        lock,\n        unlock,\n        createdResources,\n        firstCreatedResource,\n        getCalledTimes,\n        resourcesCleaned,\n        assertCalledTimes,\n        assertFirstNCreatedResourcesCleaned,\n        assertAllCleaned,\n        assertAllCleanedForKey,\n        assertAtLeastOneResourceNotCleanedForKey\n      })\n    }\n  )\n"
  },
  {
    "path": "packages/effect/test/utils/cause.ts",
    "content": "import * as Cause from \"effect/Cause\"\nimport * as fc from \"effect/FastCheck\"\nimport * as FiberId from \"effect/FiberId\"\n\nexport const causesArb = <E>(\n  n: number,\n  error: fc.Arbitrary<E>,\n  defect: fc.Arbitrary<unknown>\n): fc.Arbitrary<Cause.Cause<E>> => {\n  const fiberId: fc.Arbitrary<FiberId.FiberId> = fc.tuple(\n    fc.integer(),\n    fc.integer()\n  ).map(([a, b]) => FiberId.make(a, b))\n\n  const empty = fc.constant(Cause.empty)\n  const failure = error.map(Cause.fail)\n  const die = defect.map(Cause.die)\n  const interrupt = fiberId.map(Cause.interrupt)\n\n  const sequential = (n: number): fc.Arbitrary<Cause.Cause<E>> => {\n    return fc.integer({ min: 1, max: n - 1 }).chain((i) =>\n      causesN(i).chain((left) => causesN(n - i).map((right) => Cause.sequential(left, right)))\n    )\n  }\n\n  const parallel = (n: number): fc.Arbitrary<Cause.Cause<E>> => {\n    return fc.integer({ min: 1, max: n - 1 }).chain((i) =>\n      causesN(i).chain((left) => causesN(n - i).map((right) => Cause.parallel(left, right)))\n    )\n  }\n\n  const causesN = (n: number): fc.Arbitrary<Cause.Cause<E>> => {\n    if (n === 1) {\n      return fc.oneof(empty, failure, die, interrupt)\n    }\n    return fc.oneof(sequential(n), parallel(n))\n  }\n\n  return causesN(n)\n}\n\nexport const causes: fc.Arbitrary<Cause.Cause<string>> = causesArb(\n  1,\n  fc.string(),\n  fc.string().map((message) => new Error(message))\n)\n\nexport const errors: fc.Arbitrary<string> = fc.string()\n\nexport const errorCauseFunctions: fc.Arbitrary<(s: string) => Cause.Cause<string>> = fc.func(causes)\n\nexport const equalCauses: fc.Arbitrary<\n  readonly [Cause.Cause<string>, Cause.Cause<string>]\n> = fc.tuple(causes, causes, causes)\n  .chain(([a, b, c]) => {\n    const causeCases: ReadonlyArray<readonly [Cause.Cause<string>, Cause.Cause<string>]> = [\n      [a, a],\n      [\n        Cause.sequential(Cause.sequential(a, b), c),\n        Cause.sequential(a, Cause.sequential(b, c))\n      ],\n      [\n        Cause.sequential(a, Cause.parallel(b, c)),\n        Cause.parallel(Cause.sequential(a, b), Cause.sequential(a, c))\n      ],\n      [\n        Cause.parallel(Cause.parallel(a, b), c),\n        Cause.parallel(a, Cause.parallel(b, c))\n      ],\n      [\n        Cause.parallel(Cause.sequential(a, c), Cause.sequential(b, c)),\n        Cause.sequential(Cause.parallel(a, b), c)\n      ],\n      [\n        Cause.parallel(a, b),\n        Cause.parallel(b, a)\n      ],\n      [a, Cause.sequential(a, Cause.empty)],\n      [a, Cause.parallel(a, Cause.empty)]\n    ]\n    return fc.integer({ min: 0, max: causeCases.length - 1 }).map((i) => causeCases[i])\n  })\n"
  },
  {
    "path": "packages/effect/test/utils/coordination.ts",
    "content": "import * as Chunk from \"effect/Chunk\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Queue from \"effect/Queue\"\nimport * as Ref from \"effect/Ref\"\n\nexport interface ChunkCoordination<A> {\n  readonly queue: Queue.Queue<Exit.Exit<Chunk.Chunk<A>, Option.Option<never>>>\n  readonly offer: Effect.Effect<void>\n  readonly proceed: Effect.Effect<void>\n  readonly awaitNext: Effect.Effect<void>\n}\n\nexport const chunkCoordination = <A>(\n  _chunks: Iterable<Chunk.Chunk<A>>\n): Effect.Effect<ChunkCoordination<A>> =>\n  Effect.gen(function*() {\n    const chunks = Chunk.fromIterable(_chunks)\n    const queue = yield* Queue.unbounded<Exit.Exit<Chunk.Chunk<A>, Option.Option<never>>>()\n    const ps = yield* Queue.unbounded<void>()\n    const ref = yield* Ref.make<Chunk.Chunk<Chunk.Chunk<Exit.Exit<Chunk.Chunk<A>, Option.Option<never>>>>>(\n      pipe(\n        chunks,\n        Chunk.dropRight(1),\n        Chunk.map((chunk) => Chunk.of(Exit.succeed(chunk))),\n        Chunk.appendAll(\n          pipe(\n            Chunk.last(chunks),\n            Option.map((chunk) =>\n              Chunk.unsafeFromArray<Exit.Exit<Chunk.Chunk<A>, Option.Option<never>>>([\n                Exit.succeed(chunk),\n                Exit.fail(Option.none())\n              ])\n            ),\n            Option.match({\n              onNone: () => Chunk.empty<Chunk.Chunk<Exit.Exit<Chunk.Chunk<A>, Option.Option<never>>>>(),\n              onSome: Chunk.of\n            })\n          )\n        )\n      )\n    )\n    return {\n      queue,\n      offer: pipe(\n        Ref.modify(ref, (chunk) => {\n          if (Chunk.isEmpty(chunk)) {\n            return [Chunk.empty(), Chunk.empty()]\n          }\n          return [Chunk.unsafeHead(chunk), Chunk.drop(1)(chunk)]\n        }),\n        Effect.flatMap((chunks) => Queue.offerAll(queue, chunks)),\n        Effect.asVoid\n      ),\n      proceed: pipe(Queue.offer(ps, void 0), Effect.asVoid),\n      awaitNext: Queue.take(ps)\n    }\n  })\n"
  },
  {
    "path": "packages/effect/test/utils/counter.ts",
    "content": "import * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\nimport type * as Scope from \"effect/Scope\"\n\ninterface Counter {\n  acquire(): Effect.Effect<number, never, Scope.Scope>\n  incrementAcquire(): Effect.Effect<number>\n  incrementRelease(): Effect.Effect<number>\n  acquired(): Effect.Effect<number>\n  released(): Effect.Effect<number>\n}\n\nclass CounterImpl implements Counter {\n  constructor(readonly ref: Ref.Ref<readonly [number, number]>) {}\n\n  acquire(): Effect.Effect<number, never, Scope.Scope> {\n    return pipe(\n      this.incrementAcquire(),\n      Effect.zipRight(Effect.addFinalizer(() => this.incrementRelease())),\n      Effect.zipRight(this.acquired()),\n      Effect.uninterruptible\n    )\n  }\n\n  incrementAcquire(): Effect.Effect<number> {\n    return Ref.modify(this.ref, ([acquire, release]) => [acquire + 1, [acquire + 1, release] as const] as const)\n  }\n\n  incrementRelease(): Effect.Effect<number> {\n    return Ref.modify(this.ref, ([acquire, release]) => [release + 1, [acquire, release + 1] as const] as const)\n  }\n\n  acquired(): Effect.Effect<number> {\n    return pipe(\n      Ref.get(this.ref),\n      Effect.map((tuple) => tuple[0])\n    )\n  }\n\n  released(): Effect.Effect<number> {\n    return pipe(\n      Ref.get(this.ref),\n      Effect.map((tuple) => tuple[1])\n    )\n  }\n}\n\nexport const make = (): Effect.Effect<Counter> => {\n  return pipe(\n    Ref.make([0, 0]),\n    Effect.map((ref) => new CounterImpl(ref as any))\n  )\n}\n"
  },
  {
    "path": "packages/effect/test/utils/equals.ts",
    "content": "import * as Equal from \"effect/Equal\"\nimport type * as Equivalence from \"effect/Equivalence\"\n\nexport const equivalentElements = <A>(): Equivalence.Equivalence<A> => (x, y) => {\n  if (Array.isArray(x) && Array.isArray(y)) {\n    if (x.length === y.length) {\n      return x.every((v, i) => Equal.equals(v, y[i]))\n    }\n  }\n  return Equal.equals(x, y)\n}\n"
  },
  {
    "path": "packages/effect/test/utils/latch.ts",
    "content": "import * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Ref from \"effect/Ref\"\n\nexport const withLatch = <A, E, R>(\n  f: (release: Effect.Effect<void>) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => {\n  return pipe(\n    Deferred.make<void>(),\n    Effect.flatMap((latch) =>\n      pipe(f(pipe(Deferred.succeed(latch, void 0), Effect.asVoid)), Effect.zipLeft(Deferred.await(latch)))\n    )\n  )\n}\n\nexport const withLatchAwait = <A, E, R>(\n  f: (release: Effect.Effect<void>, wait: Effect.Effect<void>) => Effect.Effect<A, E, R>\n): Effect.Effect<A, E, R> => {\n  return Effect.gen(function*() {\n    const ref = yield* Ref.make(true)\n    const latch = yield* Deferred.make<void>()\n    const result = yield* f(\n      pipe(Deferred.succeed(latch, void 0), Effect.asVoid),\n      Effect.uninterruptibleMask((restore) =>\n        pipe(Ref.set(ref, false), Effect.zipRight(restore(Deferred.await(latch))))\n      )\n    )\n    yield* Deferred.await(latch).pipe(Effect.whenEffect(Ref.get(ref)))\n    return result\n  })\n}\n"
  },
  {
    "path": "packages/effect/test/utils/unfoldEffect.ts",
    "content": "import * as Effect from \"effect/Effect\"\nimport * as List from \"effect/List\"\nimport * as Option from \"effect/Option\"\n\nexport const unfoldEffect = <A, S, E, R>(\n  s: S,\n  f: (s: S) => Effect.Effect<Option.Option<readonly [A, S]>, E, R>\n): Effect.Effect<ReadonlyArray<A>, E, R> =>\n  Effect.map(\n    unfoldEffectLoop(s, f, List.empty()),\n    (list) => Array.from(List.reverse(list))\n  )\n\nconst unfoldEffectLoop = <A, S, E, R>(\n  s: S,\n  f: (s: S) => Effect.Effect<Option.Option<readonly [A, S]>, E, R>,\n  acc: List.List<A>\n): Effect.Effect<List.List<A>, E, R> =>\n  Effect.flatMap(f(s), (option) => {\n    if (Option.isSome(option)) {\n      return unfoldEffectLoop(option.value[1], f, List.prepend(acc, option.value[0]))\n    } else {\n      return Effect.succeed(acc)\n    }\n  })\n"
  },
  {
    "path": "packages/effect/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"compilerOptions\": {\n    \"types\": [\"node\"],\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true\n  }\n}\n"
  },
  {
    "path": "packages/effect/tsconfig.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/effect/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"compilerOptions\": {\n    \"types\": [\"node\"],\n    \"outDir\": \"build/src\",\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\"\n  }\n}\n"
  },
  {
    "path": "packages/effect/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../vitest/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"types\": [\"node\"],\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"outDir\": \"build/test\" // Some packages import test files from `effect`, hence we need to emit `d.ts` files here.\n  }\n}\n"
  },
  {
    "path": "packages/effect/vitest.config.ts",
    "content": "import { mergeConfig, type ViteUserConfig } from \"vitest/config\"\nimport shared from \"../../vitest.shared.js\"\n\nconst config: ViteUserConfig = {\n  test: {\n    coverage: {\n      reporter: [\"html\"],\n      include: [\"src/Schema.ts\"]\n    }\n  }\n}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/experimental/CHANGELOG.md",
    "content": "# @effect/experimental\n\n## 0.60.0\n\n### Patch Changes\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n  - @effect/platform@0.96.0\n\n## 0.59.0\n\n### Patch Changes\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n  - @effect/platform@0.95.0\n\n## 0.58.0\n\n### Patch Changes\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n  - @effect/platform@0.94.0\n\n## 0.57.11\n\n### Patch Changes\n\n- [#5864](https://github.com/Effect-TS/effect/pull/5864) [`ebe2e52`](https://github.com/Effect-TS/effect/commit/ebe2e5278420d4b2bf30113a3b0a5ed68382d870) Thanks @mattiamanzati! - Ensure Devtools Tracer does not cut off span options\n\n- Updated dependencies [[`3f9bbfe`](https://github.com/Effect-TS/effect/commit/3f9bbfe9ef78303ecc6817b68ec9671f4d42d249)]:\n  - effect@3.19.9\n\n## 0.57.10\n\n### Patch Changes\n\n- [#5847](https://github.com/Effect-TS/effect/pull/5847) [`96c9537`](https://github.com/Effect-TS/effect/commit/96c9537f73a87a651c348488bdce7efbfd8360d1) Thanks @tim-smart! - ensure PersistedQueue memory driver removes items\n\n## 0.57.9\n\n### Patch Changes\n\n- [#5837](https://github.com/Effect-TS/effect/pull/5837) [`811852a`](https://github.com/Effect-TS/effect/commit/811852a61868136bb7b3367450f02e5a8fb8a3f9) Thanks @tim-smart! - support idempotent offers to PersistedQueue\n\n## 0.57.8\n\n### Patch Changes\n\n- [#5829](https://github.com/Effect-TS/effect/pull/5829) [`7b2cd37`](https://github.com/Effect-TS/effect/commit/7b2cd374cbc8b7a2e800926082febf54173c9e49) Thanks @tim-smart! - reset redis staging area on a schedule for PersistedQueue\n\n## 0.57.7\n\n### Patch Changes\n\n- [#5820](https://github.com/Effect-TS/effect/pull/5820) [`c379c45`](https://github.com/Effect-TS/effect/commit/c379c45777cea3ec8c985d55f597902813bd3ae2) Thanks @tim-smart! - ensure redis PersistedQueue removes stale pending items on reset\n\n- Updated dependencies [[`f03b8e5`](https://github.com/Effect-TS/effect/commit/f03b8e55f12019cc855a1306e9cbfc7611a9e281)]:\n  - effect@3.19.8\n\n## 0.57.6\n\n### Patch Changes\n\n- [#5816](https://github.com/Effect-TS/effect/pull/5816) [`a9206ce`](https://github.com/Effect-TS/effect/commit/a9206ceee64daf3b12a778b60ee2bfdede748c57) Thanks @tim-smart! - add dynamic batch size to PersistedQueue based on pending takers\n\n## 0.57.5\n\n### Patch Changes\n\n- [#5808](https://github.com/Effect-TS/effect/pull/5808) [`7b23d9a`](https://github.com/Effect-TS/effect/commit/7b23d9a812d5c100d9d9af16bd50251ea2f91b4b) Thanks @tim-smart! - add PersistedQueue module\n\n## 0.57.4\n\n### Patch Changes\n\n- [#5773](https://github.com/Effect-TS/effect/pull/5773) [`9283499`](https://github.com/Effect-TS/effect/commit/9283499a1c1e6caa9cc9090c8419e8d49b575cd8) Thanks @tim-smart! - add RateLimiter helpers `makeWithRateLimiter` and `makeSleep`\n\n## 0.57.3\n\n### Patch Changes\n\n- [#5763](https://github.com/Effect-TS/effect/pull/5763) [`1df657e`](https://github.com/Effect-TS/effect/commit/1df657e4688f602262d854947c15634849f2ba98) Thanks @tim-smart! - fix RateLimiter fixed window alogrithim\n\n## 0.57.2\n\n### Patch Changes\n\n- [#5761](https://github.com/Effect-TS/effect/pull/5761) [`1deeb6a`](https://github.com/Effect-TS/effect/commit/1deeb6a58cde29e99f57c56d9adcdcda7ac610d0) Thanks @tim-smart! - fix partial window calulation for fixed window rate limiter\n\n- Updated dependencies [[`e144f02`](https://github.com/Effect-TS/effect/commit/e144f02c93258f0bb37bd10ee9849f2836914e2f)]:\n  - @effect/platform@0.93.3\n\n## 0.57.1\n\n### Patch Changes\n\n- [#5731](https://github.com/Effect-TS/effect/pull/5731) [`796a3b5`](https://github.com/Effect-TS/effect/commit/796a3b5aa3f6e0bd85583cc59f39bc059403345a) Thanks @tim-smart! - add persisted RateLimiter to @effect/experimental\n\n## 0.57.0\n\n### Patch Changes\n\n- Updated dependencies [[`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - effect@3.19.0\n  - @effect/platform@0.93.0\n\n## 0.56.0\n\n### Patch Changes\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2)]:\n  - effect@3.18.0\n  - @effect/platform@0.92.0\n\n## 0.55.0\n\n### Patch Changes\n\n- Updated dependencies [[`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a)]:\n  - @effect/platform@0.91.0\n\n## 0.54.6\n\n### Patch Changes\n\n- [#5385](https://github.com/Effect-TS/effect/pull/5385) [`9951993`](https://github.com/Effect-TS/effect/commit/995199396ee7031033bea1a9c890a6db066e870a) Thanks @tim-smart! - add setMany to ResultPersistence\n\n## 0.54.5\n\n### Patch Changes\n\n- [#5365](https://github.com/Effect-TS/effect/pull/5365) [`b254747`](https://github.com/Effect-TS/effect/commit/b254747d478d451f3a04dac2f9050bd89176fd19) Thanks @tim-smart! - only trigger Reactivity invalidation on successful mutation\n\n## 0.54.4\n\n### Patch Changes\n\n- [#5342](https://github.com/Effect-TS/effect/pull/5342) [`a9554ea`](https://github.com/Effect-TS/effect/commit/a9554ea53a4524b773426571338d14f1c1046d18) Thanks @tim-smart! - add Reactivity accessor apis\n\n- [#5344](https://github.com/Effect-TS/effect/pull/5344) [`1765ca8`](https://github.com/Effect-TS/effect/commit/1765ca8dddde47a7602083c46898b07a80c3cd28) Thanks @tim-smart! - add Reactivity.unsafeRegister\n\n## 0.54.3\n\n### Patch Changes\n\n- [#5307](https://github.com/Effect-TS/effect/pull/5307) [`1f028e5`](https://github.com/Effect-TS/effect/commit/1f028e5d286fdfdc12357a3da3955c9446ce7a0c) Thanks @tim-smart! - locally provide EventLog service where possible\n\n- Updated dependencies [[`7d7c55d`](https://github.com/Effect-TS/effect/commit/7d7c55dadeea2f9de16e60abff124085733e1953)]:\n  - effect@3.17.4\n\n## 0.54.2\n\n### Patch Changes\n\n- [#5299](https://github.com/Effect-TS/effect/pull/5299) [`0138aa5`](https://github.com/Effect-TS/effect/commit/0138aa5fdf1af8bc206809201cebd75a865fa020) Thanks @tim-smart! - use base64 for EventLog.Identity strings\n\n## 0.54.1\n\n### Patch Changes\n\n- [#5286](https://github.com/Effect-TS/effect/pull/5286) [`ffc17c6`](https://github.com/Effect-TS/effect/commit/ffc17c6d129adb898946d543b772af951b97e08d) Thanks @tim-smart! - add EventLog.layerIdentityKvs\n\n## 0.54.0\n\n### Patch Changes\n\n- Updated dependencies [[`7813640`](https://github.com/Effect-TS/effect/commit/7813640279d9e3a3e7fc0a29bfb5c6d5fb3c270f)]:\n  - @effect/platform@0.90.0\n\n## 0.53.0\n\n### Patch Changes\n\n- Updated dependencies [[`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9), [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104), [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63), [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c), [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989), [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636), [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2), [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d)]:\n  - effect@3.17.0\n  - @effect/platform@0.89.0\n\n## 0.52.2\n\n### Patch Changes\n\n- [#5219](https://github.com/Effect-TS/effect/pull/5219) [`d720f10`](https://github.com/Effect-TS/effect/commit/d720f1072770fa08ff81990e4f938f75a2399337) Thanks @tim-smart! - optimize experimental dataLoader\n\n## 0.52.1\n\n### Patch Changes\n\n- [#5211](https://github.com/Effect-TS/effect/pull/5211) [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48) Thanks @mattiamanzati! - Removed some unnecessary single-arg pipe calls\n\n- Updated dependencies [[`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec), [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38), [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48)]:\n  - effect@3.16.14\n  - @effect/platform@0.88.1\n\n## 0.52.0\n\n### Patch Changes\n\n- Updated dependencies [[`27206d7`](https://github.com/Effect-TS/effect/commit/27206d7f0558d7fe28de57bf54f1d0cc83acc92e), [`dbabf5e`](https://github.com/Effect-TS/effect/commit/dbabf5e76fa63b050d2b6c466713c7dc59f07d3c)]:\n  - @effect/platform@0.88.0\n\n## 0.51.14\n\n### Patch Changes\n\n- Updated dependencies [[`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7), [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db)]:\n  - effect@3.16.13\n  - @effect/platform@0.87.13\n\n## 0.51.13\n\n### Patch Changes\n\n- Updated dependencies [[`32ba77a`](https://github.com/Effect-TS/effect/commit/32ba77ae304d2161362a73e8b61965332626cf2d), [`d5e25b2`](https://github.com/Effect-TS/effect/commit/d5e25b237f05670ee42b386cb40b2cb448fc11d7)]:\n  - @effect/platform@0.87.12\n\n## 0.51.12\n\n### Patch Changes\n\n- Updated dependencies [[`001392b`](https://github.com/Effect-TS/effect/commit/001392ba8bfcad101bb034348a7415012fb12f72), [`7bfb099`](https://github.com/Effect-TS/effect/commit/7bfb099cb5528511b8d63045c4fbb4dc9cb18528)]:\n  - @effect/platform@0.87.11\n\n## 0.51.11\n\n### Patch Changes\n\n- Updated dependencies [[`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0), [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0)]:\n  - @effect/platform@0.87.10\n\n## 0.51.10\n\n### Patch Changes\n\n- Updated dependencies [[`54514a2`](https://github.com/Effect-TS/effect/commit/54514a2f53166de27ad7e756dbf12194691fd4af)]:\n  - @effect/platform@0.87.9\n\n## 0.51.9\n\n### Patch Changes\n\n- Updated dependencies [[`4ce4f82`](https://github.com/Effect-TS/effect/commit/4ce4f824f6fdef492be1d35c05a490ffce518c89)]:\n  - @effect/platform@0.87.8\n\n## 0.51.8\n\n### Patch Changes\n\n- Updated dependencies [[`a9b617f`](https://github.com/Effect-TS/effect/commit/a9b617f125171ed76cd79ab46d7a924daf3b0e70), [`7e26e86`](https://github.com/Effect-TS/effect/commit/7e26e86524abcc93713d6ad7eee486638c98f7c2)]:\n  - @effect/platform@0.87.7\n\n## 0.51.7\n\n### Patch Changes\n\n- Updated dependencies [[`905da99`](https://github.com/Effect-TS/effect/commit/905da996aad665057b4ca6dba1a4af44fb8835bd)]:\n  - effect@3.16.12\n  - @effect/platform@0.87.6\n\n## 0.51.6\n\n### Patch Changes\n\n- [#5144](https://github.com/Effect-TS/effect/pull/5144) [`96c1292`](https://github.com/Effect-TS/effect/commit/96c129262835410b311a51d0bf7f58b8f6fc9a12) Thanks @tim-smart! - simplify VariantSchema Class types\n\n## 0.51.5\n\n### Patch Changes\n\n- Updated dependencies [[`2fd8676`](https://github.com/Effect-TS/effect/commit/2fd8676c803cd40000dfc3231f5daecaa0e0ebd2)]:\n  - @effect/platform@0.87.5\n\n## 0.51.4\n\n### Patch Changes\n\n- Updated dependencies [[`e82a4fd`](https://github.com/Effect-TS/effect/commit/e82a4fd60f6528d08cef1a4aba0abe0d3ba741ad)]:\n  - @effect/platform@0.87.4\n\n## 0.51.3\n\n### Patch Changes\n\n- Updated dependencies [[`1b6e396`](https://github.com/Effect-TS/effect/commit/1b6e396d699f3cbbc56b68f99055cf746529bb9e)]:\n  - @effect/platform@0.87.3\n\n## 0.51.2\n\n### Patch Changes\n\n- Updated dependencies [[`4fea68c`](https://github.com/Effect-TS/effect/commit/4fea68ca7a25a3c39a1ab68b3885534513ab0c81), [`b927954`](https://github.com/Effect-TS/effect/commit/b9279543cf5688dd8a577af80456959c615217d0), [`99590a6`](https://github.com/Effect-TS/effect/commit/99590a6ca9128eb1ede265b6670b655311995614), [`6c3e24c`](https://github.com/Effect-TS/effect/commit/6c3e24c2308f7d4a29b8f4270ab81bca22ac6bb4)]:\n  - @effect/platform@0.87.2\n  - effect@3.16.11\n\n## 0.51.1\n\n### Patch Changes\n\n- Updated dependencies [[`faad30e`](https://github.com/Effect-TS/effect/commit/faad30ec8742916be59f9db642d0fc98225b636c)]:\n  - effect@3.16.10\n  - @effect/platform@0.87.1\n\n## 0.51.0\n\n### Patch Changes\n\n- Updated dependencies [[`b5bac9a`](https://github.com/Effect-TS/effect/commit/b5bac9ac2913fcd11b02322624f03b544eef53ba)]:\n  - @effect/platform@0.87.0\n\n## 0.50.0\n\n### Patch Changes\n\n- Updated dependencies [[`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`c23d25c`](https://github.com/Effect-TS/effect/commit/c23d25c3e7c541f1f63b28484d8c461d86c67e99), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07)]:\n  - effect@3.16.9\n  - @effect/platform@0.86.0\n\n## 0.49.2\n\n### Patch Changes\n\n- Updated dependencies [[`914a191`](https://github.com/Effect-TS/effect/commit/914a191e7cb6341a3d0e965bccd27c336cf22e44)]:\n  - @effect/platform@0.85.2\n\n## 0.49.1\n\n### Patch Changes\n\n- Updated dependencies [[`8cb98d5`](https://github.com/Effect-TS/effect/commit/8cb98d53e68330228287ce2a2e0d8a4c86bcab3b), [`db2dd3c`](https://github.com/Effect-TS/effect/commit/db2dd3c3a8a77d791eae19e66153527e1cde4e6e)]:\n  - effect@3.16.8\n  - @effect/platform@0.85.1\n\n## 0.49.0\n\n### Patch Changes\n\n- Updated dependencies [[`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e)]:\n  - @effect/platform@0.85.0\n\n## 0.48.12\n\n### Patch Changes\n\n- Updated dependencies [[`1bb0d8a`](https://github.com/Effect-TS/effect/commit/1bb0d8ab96782e99434356266b38251554ea0294)]:\n  - effect@3.16.7\n  - @effect/platform@0.84.11\n\n## 0.48.11\n\n### Patch Changes\n\n- Updated dependencies [[`a5f7595`](https://github.com/Effect-TS/effect/commit/a5f75956ef9a15a83c416517ef493f0ee2f5ee8a), [`a02470c`](https://github.com/Effect-TS/effect/commit/a02470c75579e91525a25adb3f21b3650d042fdd), [`bf369b2`](https://github.com/Effect-TS/effect/commit/bf369b2902a0e0b195d957c18b9efd180942cf8b), [`f891d45`](https://github.com/Effect-TS/effect/commit/f891d45adffdafd3f94a2eca23faa354e3a409a8)]:\n  - effect@3.16.6\n  - @effect/platform@0.84.10\n\n## 0.48.10\n\n### Patch Changes\n\n- Updated dependencies [[`bf418ef`](https://github.com/Effect-TS/effect/commit/bf418ef14a0f2ec965535793d5cea8fa8ba177ac)]:\n  - effect@3.16.5\n  - @effect/platform@0.84.9\n\n## 0.48.9\n\n### Patch Changes\n\n- Updated dependencies [[`8b9db77`](https://github.com/Effect-TS/effect/commit/8b9db7742846af0f58fd8e8b7acb7f4f5ff487ec)]:\n  - @effect/platform@0.84.8\n\n## 0.48.8\n\n### Patch Changes\n\n- Updated dependencies [[`74ab9a0`](https://github.com/Effect-TS/effect/commit/74ab9a0a9e16d6e019369d256e1e24175c8bc3f3), [`770008e`](https://github.com/Effect-TS/effect/commit/770008eca3aad2899a2ed951236e575793294b28)]:\n  - effect@3.16.4\n  - @effect/platform@0.84.7\n\n## 0.48.7\n\n### Patch Changes\n\n- [#4978](https://github.com/Effect-TS/effect/pull/4978) [`a2d57c9`](https://github.com/Effect-TS/effect/commit/a2d57c9ac596445009ca12859b78e00e5d89b936) Thanks @mattiamanzati! - Fix Machine initialize R argument\n\n## 0.48.6\n\n### Patch Changes\n\n- Updated dependencies [[`ceea77a`](https://github.com/Effect-TS/effect/commit/ceea77a13055f145520f763e3fce5b8ff15d728f)]:\n  - @effect/platform@0.84.6\n\n## 0.48.5\n\n### Patch Changes\n\n- Updated dependencies [[`ec52c6a`](https://github.com/Effect-TS/effect/commit/ec52c6a2211e76972462b15b9d5a9d6d56761b7a)]:\n  - @effect/platform@0.84.5\n\n## 0.48.4\n\n### Patch Changes\n\n- Updated dependencies [[`87722fc`](https://github.com/Effect-TS/effect/commit/87722fce693a9b49284bbddbf82d30714c688261), [`36217ee`](https://github.com/Effect-TS/effect/commit/36217eeb1337edd9ac3f9a635b80a6385d22ae8f)]:\n  - effect@3.16.3\n  - @effect/platform@0.84.4\n\n## 0.48.3\n\n### Patch Changes\n\n- Updated dependencies [[`ab7684f`](https://github.com/Effect-TS/effect/commit/ab7684f1c2a0671bf091f255d220e3a4cc7f528e)]:\n  - @effect/platform@0.84.3\n\n## 0.48.2\n\n### Patch Changes\n\n- Updated dependencies [[`0ddf148`](https://github.com/Effect-TS/effect/commit/0ddf148a247aa87af043d276b8453a714a400897)]:\n  - effect@3.16.2\n  - @effect/platform@0.84.2\n\n## 0.48.1\n\n### Patch Changes\n\n- Updated dependencies [[`71174d0`](https://github.com/Effect-TS/effect/commit/71174d09691314a9b6b66189e456fd21e3eb6543), [`d615e6e`](https://github.com/Effect-TS/effect/commit/d615e6e5b944f6fd5e627e31752c7ca7e4e1c17d)]:\n  - @effect/platform@0.84.1\n  - effect@3.16.1\n\n## 0.48.0\n\n### Patch Changes\n\n- Updated dependencies [[`ee0bd5d`](https://github.com/Effect-TS/effect/commit/ee0bd5d24864752c54cb359f67a67dd903971ec4), [`5189800`](https://github.com/Effect-TS/effect/commit/51898004e11766b8cf6d95e960b636f6d5db79ec), [`58bfeaa`](https://github.com/Effect-TS/effect/commit/58bfeaa64ded8c88f772b184311c0c0dbac10960), [`194d748`](https://github.com/Effect-TS/effect/commit/194d7486943f56f3267ef415395ac220a4b3e634), [`918c9ea`](https://github.com/Effect-TS/effect/commit/918c9ea1a57facb154f0fb26792021f337054dee), [`9198e6f`](https://github.com/Effect-TS/effect/commit/9198e6fcc1a3ff4fefb3363004de558d8de01f40), [`2a370bf`](https://github.com/Effect-TS/effect/commit/2a370bf625fdeede5659721468eb0d527e403279), [`58ccb91`](https://github.com/Effect-TS/effect/commit/58ccb91328c8df5d49808b673738bc09df355201), [`fd47834`](https://github.com/Effect-TS/effect/commit/fd478348203fa89462b0a1d067ce4de034353df4)]:\n  - effect@3.16.0\n  - @effect/platform@0.84.0\n\n## 0.47.0\n\n### Patch Changes\n\n- Updated dependencies [[`5522520`](https://github.com/Effect-TS/effect/commit/55225206ab9af0ad60b1c0654690a8a096d625cd), [`cc5bb2b`](https://github.com/Effect-TS/effect/commit/cc5bb2b918a9450a975f702dabcea891bda382cb)]:\n  - @effect/platform@0.83.0\n  - effect@3.15.5\n\n## 0.46.8\n\n### Patch Changes\n\n- Updated dependencies [[`0617b9d`](https://github.com/Effect-TS/effect/commit/0617b9dc365f1963b36949ad7f9023ab6eb94524)]:\n  - @effect/platform@0.82.8\n\n## 0.46.7\n\n### Patch Changes\n\n- Updated dependencies [[`f570554`](https://github.com/Effect-TS/effect/commit/f57055459524587b041340577dad85476bb35f81), [`78047e8`](https://github.com/Effect-TS/effect/commit/78047e8dfc8005b66f87afe50bb95981fea51561), [`c20b95a`](https://github.com/Effect-TS/effect/commit/c20b95a99ffe452b4774c844d397a905f713b6d6), [`94ada43`](https://github.com/Effect-TS/effect/commit/94ada430928d5685bdbef513e87562c20774a3a2)]:\n  - effect@3.15.4\n  - @effect/platform@0.82.7\n\n## 0.46.6\n\n### Patch Changes\n\n- Updated dependencies [[`618903b`](https://github.com/Effect-TS/effect/commit/618903ba9ae96e2bfe6ee31f61c4359b915f2a36)]:\n  - @effect/platform@0.82.6\n\n## 0.46.5\n\n### Patch Changes\n\n- Updated dependencies [[`7764a07`](https://github.com/Effect-TS/effect/commit/7764a07d960c60df81f14e1dc949518f4bbe494a), [`4577f54`](https://github.com/Effect-TS/effect/commit/4577f548d67273e576cdde423bdd34a4b910766a), [`30a0d9c`](https://github.com/Effect-TS/effect/commit/30a0d9cb51c84290d51b1361d72ff5cee33c13c7)]:\n  - @effect/platform@0.82.5\n  - effect@3.15.3\n\n## 0.46.4\n\n### Patch Changes\n\n- Updated dependencies [[`d45e8a8`](https://github.com/Effect-TS/effect/commit/d45e8a8ac8227192f504e39e6d04fdcf4fb1d225), [`d13b68e`](https://github.com/Effect-TS/effect/commit/d13b68e3a9456d0bfee9bca8273a7b44a9c69087)]:\n  - @effect/platform@0.82.4\n\n## 0.46.3\n\n### Patch Changes\n\n- Updated dependencies [[`b8722b8`](https://github.com/Effect-TS/effect/commit/b8722b817e2306fe8c8245f3f9e32d85b824b961), [`a328f4b`](https://github.com/Effect-TS/effect/commit/a328f4b4fe717dd53e5b04a30f387433c32f7328)]:\n  - effect@3.15.2\n  - @effect/platform@0.82.3\n\n## 0.46.2\n\n### Patch Changes\n\n- Updated dependencies [[`739a3d4`](https://github.com/Effect-TS/effect/commit/739a3d4a4565915fe2e690003f4f9085cb4422fc)]:\n  - @effect/platform@0.82.2\n\n## 0.46.1\n\n### Patch Changes\n\n- Updated dependencies [[`787ce70`](https://github.com/Effect-TS/effect/commit/787ce7042e35b657963473c6efe47752868cd811), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348)]:\n  - effect@3.15.1\n  - @effect/platform@0.82.1\n\n## 0.46.0\n\n### Patch Changes\n\n- Updated dependencies [[`c654595`](https://github.com/Effect-TS/effect/commit/c65459587b51da140b78098e81fdbfece65d53e2), [`d9f5dea`](https://github.com/Effect-TS/effect/commit/d9f5deae0f02f5de2b9fcb1cca8b142ba4bc2bba), [`49aa723`](https://github.com/Effect-TS/effect/commit/49aa7236a15e13f818c86edbca08c4af67c8dfaf), [`74c14d0`](https://github.com/Effect-TS/effect/commit/74c14d01d0cb48cf517a1b6e29a373a96ed0ff5b), [`e4f49b6`](https://github.com/Effect-TS/effect/commit/e4f49b66857e01b74ab6a9a0bc7132f44cd04cbb), [`6f02224`](https://github.com/Effect-TS/effect/commit/6f02224b3fc46a682ad2defb1a260841956c6780), [`1dcfd41`](https://github.com/Effect-TS/effect/commit/1dcfd41ff96abd706901293a00c1893cb29dd8fd), [`b21ab16`](https://github.com/Effect-TS/effect/commit/b21ab16b6f773e7ec4369db4e752c35e719f7870), [`fcf1822`](https://github.com/Effect-TS/effect/commit/fcf1822f98fcda60351d64e9d2c2c13563d7e6db), [`0061dd1`](https://github.com/Effect-TS/effect/commit/0061dd140740165e91569a684cce27a77b23229e), [`8421e6e`](https://github.com/Effect-TS/effect/commit/8421e6e49332bca8f96f482dfd48680e238b3a89), [`a9b3fb7`](https://github.com/Effect-TS/effect/commit/a9b3fb78abcfdb525318a956fd02fcadeb56143e), [`fa10f56`](https://github.com/Effect-TS/effect/commit/fa10f56b96bd9af070ba99ebc3279aa93954261e)]:\n  - effect@3.15.0\n  - @effect/platform@0.82.0\n\n## 0.45.1\n\n### Patch Changes\n\n- Updated dependencies [[`24a9ebb`](https://github.com/Effect-TS/effect/commit/24a9ebbb5af598f0bfd6ecc45307e528043fe011)]:\n  - effect@3.14.22\n  - @effect/platform@0.81.1\n\n## 0.45.0\n\n### Patch Changes\n\n- Updated dependencies [[`672920f`](https://github.com/Effect-TS/effect/commit/672920f85da8abd5f9d4ad85e29248a2aca57ed8)]:\n  - @effect/platform@0.81.0\n\n## 0.44.21\n\n### Patch Changes\n\n- Updated dependencies [[`2f3b7d4`](https://github.com/Effect-TS/effect/commit/2f3b7d4e1fa1ef8790b0ca4da22eb88872ee31df)]:\n  - effect@3.14.21\n  - @effect/platform@0.80.21\n\n## 0.44.20\n\n### Patch Changes\n\n- Updated dependencies [[`17e2f30`](https://github.com/Effect-TS/effect/commit/17e2f3091408cf0fca9414d4af3bdf7b2765b378)]:\n  - effect@3.14.20\n  - @effect/platform@0.80.20\n\n## 0.44.19\n\n### Patch Changes\n\n- Updated dependencies [[`056a910`](https://github.com/Effect-TS/effect/commit/056a910d0a0b8b00b0dc9df4a070466b2b5c2f6c), [`e25e7bb`](https://github.com/Effect-TS/effect/commit/e25e7bbc1797733916f48f501425d9f2ef310d9f), [`3273d57`](https://github.com/Effect-TS/effect/commit/3273d572c2b3175a842677f19efeea4cd65ab016)]:\n  - effect@3.14.19\n  - @effect/platform@0.80.19\n\n## 0.44.18\n\n### Patch Changes\n\n- Updated dependencies [[`b1164d4`](https://github.com/Effect-TS/effect/commit/b1164d49a1dfdf299e9971367b6fc6be4df0ddff)]:\n  - effect@3.14.18\n  - @effect/platform@0.80.18\n\n## 0.44.17\n\n### Patch Changes\n\n- Updated dependencies [[`0b54681`](https://github.com/Effect-TS/effect/commit/0b54681cd89245e211d8f49272be0f1bf2f81813), [`41a59d5`](https://github.com/Effect-TS/effect/commit/41a59d5916a296b12b0d5ead9e859e05f40b4cce)]:\n  - effect@3.14.17\n  - @effect/platform@0.80.17\n\n## 0.44.16\n\n### Patch Changes\n\n- Updated dependencies [[`ee14444`](https://github.com/Effect-TS/effect/commit/ee144441021ec77039e43396eaf90714687bb495), [`f1c8583`](https://github.com/Effect-TS/effect/commit/f1c8583f8c3ea9415f813795ca2940a897c9ba9a)]:\n  - effect@3.14.16\n  - @effect/platform@0.80.16\n\n## 0.44.15\n\n### Patch Changes\n\n- Updated dependencies [[`239cc99`](https://github.com/Effect-TS/effect/commit/239cc995ce645946210a3c3d2cb52bd3547c0687), [`8b6c947`](https://github.com/Effect-TS/effect/commit/8b6c947eaa8e45a67ecb3c37d45cd27f3e41d165), [`c50a63b`](https://github.com/Effect-TS/effect/commit/c50a63bbecb9f560b9cae349c447eed877d1b9b6)]:\n  - effect@3.14.15\n  - @effect/platform@0.80.15\n\n## 0.44.14\n\n### Patch Changes\n\n- Updated dependencies [[`6ed8d15`](https://github.com/Effect-TS/effect/commit/6ed8d1589beb181d30abc79afebdaabc1d101538)]:\n  - effect@3.14.14\n  - @effect/platform@0.80.14\n\n## 0.44.13\n\n### Patch Changes\n\n- Updated dependencies [[`ee77788`](https://github.com/Effect-TS/effect/commit/ee77788747e7ebbde6bfa88256cde49dbbad3608), [`5fce6ba`](https://github.com/Effect-TS/effect/commit/5fce6ba19c3cc63cc0104e737e581ad989dedbf0), [`570e45f`](https://github.com/Effect-TS/effect/commit/570e45f8cb936e42ec48f67f21bb2b7252f36c0c)]:\n  - effect@3.14.13\n  - @effect/platform@0.80.13\n\n## 0.44.12\n\n### Patch Changes\n\n- Updated dependencies [[`c2ad9ee`](https://github.com/Effect-TS/effect/commit/c2ad9ee9f3c4c743390edf35ed9e85a20be33811), [`9c68654`](https://github.com/Effect-TS/effect/commit/9c686542b6eb3ea188cb70673ef2e41223633e89)]:\n  - effect@3.14.12\n  - @effect/platform@0.80.12\n\n## 0.44.11\n\n### Patch Changes\n\n- Updated dependencies [[`e536127`](https://github.com/Effect-TS/effect/commit/e536127c1e6f2fb3a542c73ae919435a629a346b)]:\n  - effect@3.14.11\n  - @effect/platform@0.80.11\n\n## 0.44.10\n\n### Patch Changes\n\n- Updated dependencies [[`bc7efa3`](https://github.com/Effect-TS/effect/commit/bc7efa3b031bb25e1ed3c8f2d3fb5e8da166cadc)]:\n  - effect@3.14.10\n  - @effect/platform@0.80.10\n\n## 0.44.9\n\n### Patch Changes\n\n- Updated dependencies [[`d78249f`](https://github.com/Effect-TS/effect/commit/d78249f0b67f63cf4baf806ff090cba33293daf0)]:\n  - effect@3.14.9\n  - @effect/platform@0.80.9\n\n## 0.44.8\n\n### Patch Changes\n\n- Updated dependencies [[`b3a2d32`](https://github.com/Effect-TS/effect/commit/b3a2d32772e6f7f20eacf2e18128e99324c4d378)]:\n  - effect@3.14.8\n  - @effect/platform@0.80.8\n\n## 0.44.7\n\n### Patch Changes\n\n- Updated dependencies [[`b542a4b`](https://github.com/Effect-TS/effect/commit/b542a4bf195be0c9af1523e1ba96c953decc4d25)]:\n  - effect@3.14.7\n  - @effect/platform@0.80.7\n\n## 0.44.6\n\n### Patch Changes\n\n- Updated dependencies [[`47618c1`](https://github.com/Effect-TS/effect/commit/47618c1ad84ebcc5a51133a3fff5aa5012d49d45), [`6077882`](https://github.com/Effect-TS/effect/commit/60778824a4794336c33807801f813f8751d1c7e4)]:\n  - effect@3.14.6\n  - @effect/platform@0.80.6\n\n## 0.44.5\n\n### Patch Changes\n\n- Updated dependencies [[`40dbfef`](https://github.com/Effect-TS/effect/commit/40dbfeff239b6e567706752114f31b2fce7de4e3), [`85fba81`](https://github.com/Effect-TS/effect/commit/85fba815ac07eb13d4227a69ac76a18e4b94df18), [`5a5ebdd`](https://github.com/Effect-TS/effect/commit/5a5ebdddfaddd259538b4599a6676281faca778e)]:\n  - effect@3.14.5\n  - @effect/platform@0.80.5\n\n## 0.44.4\n\n### Patch Changes\n\n- Updated dependencies [[`e4ba2c6`](https://github.com/Effect-TS/effect/commit/e4ba2c66a878e81b5e295d6d49aaf724b80a28ef)]:\n  - effect@3.14.4\n  - @effect/platform@0.80.4\n\n## 0.44.3\n\n### Patch Changes\n\n- Updated dependencies [[`37aa8e1`](https://github.com/Effect-TS/effect/commit/37aa8e137725a902e70cd1e468ea98b873aa5056), [`34f03d6`](https://github.com/Effect-TS/effect/commit/34f03d66875f21f266f102223a03cd14c2ed6ea6)]:\n  - effect@3.14.3\n  - @effect/platform@0.80.3\n\n## 0.44.2\n\n### Patch Changes\n\n- Updated dependencies [[`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`0a3e3e1`](https://github.com/Effect-TS/effect/commit/0a3e3e18eea5e0d1882f1a6c906198e6ef226a41)]:\n  - effect@3.14.2\n  - @effect/platform@0.80.2\n\n## 0.44.1\n\n### Patch Changes\n\n- Updated dependencies [[`4a274fe`](https://github.com/Effect-TS/effect/commit/4a274fe9f623182b6b902827e0e83bd89ca3b05c)]:\n  - effect@3.14.1\n  - @effect/platform@0.80.1\n\n## 0.44.0\n\n### Minor Changes\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce) Thanks @tim-smart! - move the MsgPack, Ndjson & ChannelSchema modules to @effect/platform\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`3131f8f`](https://github.com/Effect-TS/effect/commit/3131f8fd12ba9eb31b90fa2f42bf88b12309133c) Thanks @tim-smart! - refactor of @effect/cluster packages\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce) Thanks @tim-smart! - Move SocketServer modules to @effect/platform\n\n### Patch Changes\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce) Thanks @tim-smart! - use unhandled error log level for SocketServer errors\n\n- Updated dependencies [[`1f47e4e`](https://github.com/Effect-TS/effect/commit/1f47e4e12546ab691b29bfb7b5128bb17b93baa5), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`3131f8f`](https://github.com/Effect-TS/effect/commit/3131f8fd12ba9eb31b90fa2f42bf88b12309133c), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`04dff2d`](https://github.com/Effect-TS/effect/commit/04dff2d01ac68c260f29a6d4743381825c353c86), [`c7fac0c`](https://github.com/Effect-TS/effect/commit/c7fac0cd7eadcd5cc0c3a987051c5b57ad271638), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`ffaa3f3`](https://github.com/Effect-TS/effect/commit/ffaa3f3969df26610fcc02ad537340641d44e803), [`ab957c1`](https://github.com/Effect-TS/effect/commit/ab957c1fee714868f56c7ab4e802b9d449e9b666), [`35db9ce`](https://github.com/Effect-TS/effect/commit/35db9ce228f1416c8abacc6dc9c36fbd0f33ef0f), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`cf77ea9`](https://github.com/Effect-TS/effect/commit/cf77ea9ab4fc89e66a43f682a9926ccdee6c57ed), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`baaab60`](https://github.com/Effect-TS/effect/commit/baaab60b737f35dfab8e4a21bce28a195d19e899)]:\n  - effect@3.14.0\n  - @effect/platform@0.80.0\n\n## 0.43.4\n\n### Patch Changes\n\n- Updated dependencies [[`5662363`](https://github.com/Effect-TS/effect/commit/566236361e270e575ef1cbf308ad1967c82a362c), [`5f1fd15`](https://github.com/Effect-TS/effect/commit/5f1fd15308ab154791580059b89877d19a2055c2), [`8bb1460`](https://github.com/Effect-TS/effect/commit/8bb1460c824f66f0f25ebd899c5e74e388089c37)]:\n  - @effect/platform@0.79.4\n  - @effect/platform-node@0.75.4\n\n## 0.43.3\n\n### Patch Changes\n\n- Updated dependencies [[`0c4803f`](https://github.com/Effect-TS/effect/commit/0c4803fcc69262d11a97ce49d0e9b4288df0651f), [`6f65ac4`](https://github.com/Effect-TS/effect/commit/6f65ac4eac1489cd6ea390e18b0908670722adad)]:\n  - effect@3.13.12\n  - @effect/platform@0.79.3\n  - @effect/platform-node@0.75.3\n\n## 0.43.2\n\n### Patch Changes\n\n- Updated dependencies [[`fad8cca`](https://github.com/Effect-TS/effect/commit/fad8cca9bbfcc2eaeb44b97c15dbe0a1eda75315), [`4296293`](https://github.com/Effect-TS/effect/commit/4296293049414d0cf2d915a26c552b09f946b9a0), [`9c241ab`](https://github.com/Effect-TS/effect/commit/9c241abe47ccf7a5257b98a4a64a63054a12741d), [`082b0c1`](https://github.com/Effect-TS/effect/commit/082b0c1b9f4252bcdd69608f2e4a9226f953ac3f), [`be12983`](https://github.com/Effect-TS/effect/commit/be12983bc7e7537b41cd8910fc4eb7d1da56ab07), [`de88127`](https://github.com/Effect-TS/effect/commit/de88127a5a5906ccece98af74787b5ae0e65e431)]:\n  - effect@3.13.11\n  - @effect/platform@0.79.2\n  - @effect/platform-node@0.75.2\n\n## 0.43.1\n\n### Patch Changes\n\n- Updated dependencies [[`527c964`](https://github.com/Effect-TS/effect/commit/527c9645229f5be9714a7e60a38a9e753c4bbfb1)]:\n  - effect@3.13.10\n  - @effect/platform@0.79.1\n  - @effect/platform-node@0.75.1\n\n## 0.43.0\n\n### Patch Changes\n\n- Updated dependencies [[`bbdc279`](https://github.com/Effect-TS/effect/commit/bbdc2795a461cb2d1fe19b2669526a6ef590c3d4), [`88fe129`](https://github.com/Effect-TS/effect/commit/88fe12923740765c0335a6e6203fdcc6a463edca), [`d630249`](https://github.com/Effect-TS/effect/commit/d630249426113088abe8b382db4f14d80f2160c2), [`2976e52`](https://github.com/Effect-TS/effect/commit/2976e52538d9dc9ffdcbc84d4ac748cff9305971)]:\n  - @effect/platform-node@0.75.0\n  - @effect/platform@0.79.0\n  - effect@3.13.9\n\n## 0.42.1\n\n### Patch Changes\n\n- Updated dependencies [[`c65d336`](https://github.com/Effect-TS/effect/commit/c65d3362d07ec815ff3b46278314e8a31706ddc2), [`22d2ebb`](https://github.com/Effect-TS/effect/commit/22d2ebb4b11f5a44351a4736e65da391a3b647d0)]:\n  - effect@3.13.8\n  - @effect/platform@0.78.1\n  - @effect/platform-node@0.74.1\n\n## 0.42.0\n\n### Patch Changes\n\n- Updated dependencies [[`c5bcf53`](https://github.com/Effect-TS/effect/commit/c5bcf53b7cb49dacffdd2a6cd8eb48cc452b417e)]:\n  - @effect/platform@0.78.0\n  - @effect/platform-node@0.74.0\n\n## 0.41.7\n\n### Patch Changes\n\n- Updated dependencies [[`840cc73`](https://github.com/Effect-TS/effect/commit/840cc7329908db7ca693ef47b07d4f845c29cadd), [`99fcbf7`](https://github.com/Effect-TS/effect/commit/99fcbf712d40a90ac5c8843237d26914146d7312), [`9bf8a74`](https://github.com/Effect-TS/effect/commit/9bf8a74b967f18d931743dd5196af326c9118e9c), [`87ba23c`](https://github.com/Effect-TS/effect/commit/87ba23c41c193503ed0c612b0d32d0b253794c64), [`f910880`](https://github.com/Effect-TS/effect/commit/f91088069057f3b4529753f5bc5532b028d726df), [`0d01480`](https://github.com/Effect-TS/effect/commit/0d014803e4f688f74386a80abd65485e1a319244)]:\n  - @effect/platform@0.77.7\n  - effect@3.13.7\n  - @effect/platform-node@0.73.7\n\n## 0.41.6\n\n### Patch Changes\n\n- Updated dependencies [[`3154ce4`](https://github.com/Effect-TS/effect/commit/3154ce4692fa18b804982158d3c4c8a8a5fae386)]:\n  - effect@3.13.6\n  - @effect/platform@0.77.6\n  - @effect/platform-node@0.73.6\n\n## 0.41.5\n\n### Patch Changes\n\n- Updated dependencies [[`367bb35`](https://github.com/Effect-TS/effect/commit/367bb35f4c2a254e1fb211d96db2474a7aed9020), [`6cf11c3`](https://github.com/Effect-TS/effect/commit/6cf11c3a75773ceec2877c85ddc760f381f0866d), [`a0acec8`](https://github.com/Effect-TS/effect/commit/a0acec851f72e19466363d24b9cc218acd00006a)]:\n  - effect@3.13.5\n  - @effect/platform@0.77.5\n  - @effect/platform-node@0.73.5\n\n## 0.41.4\n\n### Patch Changes\n\n- Updated dependencies [[`e0746f9`](https://github.com/Effect-TS/effect/commit/e0746f9aa398b69c6542e375910683bf17f49f46), [`17d9e89`](https://github.com/Effect-TS/effect/commit/17d9e89f9851663bdbb6c1e685601d97806114a4)]:\n  - @effect/platform@0.77.4\n  - effect@3.13.4\n  - @effect/platform-node@0.73.4\n\n## 0.41.3\n\n### Patch Changes\n\n- Updated dependencies [[`cc5588d`](https://github.com/Effect-TS/effect/commit/cc5588df07f9103513547cb429ce041b9436a8bd), [`623c8cd`](https://github.com/Effect-TS/effect/commit/623c8cd053ed6ee3d353aaa8778d484670fca2bb), [`00b4eb1`](https://github.com/Effect-TS/effect/commit/00b4eb1ece12a16e222e6220965bb4024d6752ac), [`f2aee98`](https://github.com/Effect-TS/effect/commit/f2aee989b0a600900ce83e7f460d02908620c80f), [`fb798eb`](https://github.com/Effect-TS/effect/commit/fb798eb9061f1191badc017d1aa649360254da20), [`2251b15`](https://github.com/Effect-TS/effect/commit/2251b1528810bb695b37ce388b653cec0c5bf80c), [`2e15c1e`](https://github.com/Effect-TS/effect/commit/2e15c1e33648add0b29fe274fbcb7294b7515085), [`a4979db`](https://github.com/Effect-TS/effect/commit/a4979db021aef16e731be64df196b72088fc4376), [`b74255a`](https://github.com/Effect-TS/effect/commit/b74255a304ad49d60bedb1a260fd697f370af27a), [`d7f6a5c`](https://github.com/Effect-TS/effect/commit/d7f6a5c7d26c1963dcd864ca62360d20d08c7b49), [`9dd8979`](https://github.com/Effect-TS/effect/commit/9dd8979e940915b1cc1b1f264f3d019c77a65a02), [`477b488`](https://github.com/Effect-TS/effect/commit/477b488284f47c5469d7fba3e4065fb7e3b6556e), [`10932cb`](https://github.com/Effect-TS/effect/commit/10932cbf58fc721ada631cebec42f773ce96d3cc), [`9f6c784`](https://github.com/Effect-TS/effect/commit/9f6c78468b3b5e9ebfc38ffdfb70702901ee977b), [`2c639ec`](https://github.com/Effect-TS/effect/commit/2c639ecee332de4266e36022c989c35ae4e02105), [`886aaa8`](https://github.com/Effect-TS/effect/commit/886aaa81e06dfd3cd9391e8ea987d8cd5ada1124)]:\n  - effect@3.13.3\n  - @effect/platform@0.77.3\n  - @effect/platform-node@0.73.3\n\n## 0.41.2\n\n### Patch Changes\n\n- Updated dependencies [[`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f), [`3e7ce97`](https://github.com/Effect-TS/effect/commit/3e7ce97f8a41756a039cf635d0b3d9a75d781097), [`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f)]:\n  - effect@3.13.2\n  - @effect/platform@0.77.2\n  - @effect/platform-node@0.73.2\n\n## 0.41.1\n\n### Patch Changes\n\n- Updated dependencies [[`b56a211`](https://github.com/Effect-TS/effect/commit/b56a2110569fd0ec0b57ac137743e926d49f51cc)]:\n  - effect@3.13.1\n  - @effect/platform@0.77.1\n  - @effect/platform-node@0.73.1\n\n## 0.41.0\n\n### Patch Changes\n\n- Updated dependencies [[`8baef83`](https://github.com/Effect-TS/effect/commit/8baef83e7ff0b7bc0738b680e1ef013065386cff), [`655bfe2`](https://github.com/Effect-TS/effect/commit/655bfe29e44cc3f0fb9b4e53038f50b891c188df), [`d90cbc2`](https://github.com/Effect-TS/effect/commit/d90cbc274e2742d18671fe65aa4764c057eb6cba), [`75632bd`](https://github.com/Effect-TS/effect/commit/75632bd44b8025101d652ccbaeef898c7086c91c), [`c874a2e`](https://github.com/Effect-TS/effect/commit/c874a2e4b17e9d71904ca8375bb77b020975cb1d), [`bf865e5`](https://github.com/Effect-TS/effect/commit/bf865e5833f77fd8f6c06944ca9d507b54488301), [`f98b2b7`](https://github.com/Effect-TS/effect/commit/f98b2b7592cf20f9d85313e7f1e964cb65878138), [`de8ce92`](https://github.com/Effect-TS/effect/commit/de8ce924923eaa4e1b761a97eb45ec967389f3d5), [`cf8b2dd`](https://github.com/Effect-TS/effect/commit/cf8b2dd112f8e092ed99d78fd728db0f91c29050), [`db426a5`](https://github.com/Effect-TS/effect/commit/db426a5fb41ab84d18e3c8753a7329b4de544245), [`6862444`](https://github.com/Effect-TS/effect/commit/6862444094906ad4f2cb077ff3b9cc0b73880c8c), [`5fc8a90`](https://github.com/Effect-TS/effect/commit/5fc8a90ba46a5fd9f3b643f0b5aeadc69d717339), [`546a492`](https://github.com/Effect-TS/effect/commit/546a492e60eb2b8b048a489a474b934ea0877005), [`65c4796`](https://github.com/Effect-TS/effect/commit/65c47966ce39055f02cf5c808daabb3ea6442b0b), [`9760fdc`](https://github.com/Effect-TS/effect/commit/9760fdc37bdaef9da8b150e46b86ddfbe2ad9221), [`5b471e7`](https://github.com/Effect-TS/effect/commit/5b471e7d4317e8ee5d72bbbd3e0c9775160949ab), [`4f810cc`](https://github.com/Effect-TS/effect/commit/4f810cc2770e9f1f266851d2cb6257112c12af49)]:\n  - effect@3.13.0\n  - @effect/platform@0.77.0\n  - @effect/platform-node@0.73.0\n\n## 0.40.1\n\n### Patch Changes\n\n- Updated dependencies [[`4018eae`](https://github.com/Effect-TS/effect/commit/4018eaed2733241676ddb8c52416f463a8c32e35), [`543d36d`](https://github.com/Effect-TS/effect/commit/543d36d1a11452560b01ab966a82529ad5fee8c9), [`c407726`](https://github.com/Effect-TS/effect/commit/c407726f79df4a567a9631cddd8effaa16b3535d), [`f70a65a`](https://github.com/Effect-TS/effect/commit/f70a65ac80c6635d80b12beaf4d32a9cc59fa143), [`ba409f6`](https://github.com/Effect-TS/effect/commit/ba409f69c41aeaa29e475c0630735726eaf4dbac), [`3d2e356`](https://github.com/Effect-TS/effect/commit/3d2e3565e8a43d1bdb5daee8db3b90f56d71d859)]:\n  - effect@3.12.12\n  - @effect/platform@0.76.1\n  - @effect/platform-node@0.72.1\n\n## 0.40.0\n\n### Patch Changes\n\n- Updated dependencies [[`b6a032f`](https://github.com/Effect-TS/effect/commit/b6a032f07bffa020a848c813881879395134fa20), [`42ddd5f`](https://github.com/Effect-TS/effect/commit/42ddd5f144ce9f9d94a036679ebbd626446d37f5), [`2fe447c`](https://github.com/Effect-TS/effect/commit/2fe447c6354d334f9c591b8a8481818f5f0e797e), [`2473ad5`](https://github.com/Effect-TS/effect/commit/2473ad5cf23582e3a41338091fa526ffe611288d)]:\n  - effect@3.12.11\n  - @effect/platform-node@0.72.0\n  - @effect/platform@0.76.0\n\n## 0.39.4\n\n### Patch Changes\n\n- Updated dependencies [[`e30f132`](https://github.com/Effect-TS/effect/commit/e30f132c336c9d0760bad39f82a55c7ce5159eb7), [`33fa667`](https://github.com/Effect-TS/effect/commit/33fa667c2623be1026e1ccee91bd44f73b09020a), [`87f5f28`](https://github.com/Effect-TS/effect/commit/87f5f2842e4196cb88d13f10f443ff0567e82832), [`7d57ecd`](https://github.com/Effect-TS/effect/commit/7d57ecdaf5da2345ebbf9c22df50317578bde0f5), [`4dbd170`](https://github.com/Effect-TS/effect/commit/4dbd170538e8fb7a36aa7c469c6f93b6c7000091)]:\n  - effect@3.12.10\n  - @effect/platform@0.75.4\n  - @effect/platform-node@0.71.4\n\n## 0.39.3\n\n### Patch Changes\n\n- Updated dependencies [[`1b4a4e9`](https://github.com/Effect-TS/effect/commit/1b4a4e904ef5227ec7d9114d4e417eca19eed940)]:\n  - effect@3.12.9\n  - @effect/platform@0.75.3\n  - @effect/platform-node@0.71.3\n\n## 0.39.2\n\n### Patch Changes\n\n- Updated dependencies [[`59b3cfb`](https://github.com/Effect-TS/effect/commit/59b3cfbbd5713dd9475998e95fad5534c0b21466), [`766113c`](https://github.com/Effect-TS/effect/commit/766113c0ea3512cdb887650ead8ba314236e22ee), [`bb05fb8`](https://github.com/Effect-TS/effect/commit/bb05fb83457355b1ca567228a9e041edfb6fd85d), [`712277f`](https://github.com/Effect-TS/effect/commit/712277f949052a24b46e4aa234063a6abf395c90), [`f269122`](https://github.com/Effect-TS/effect/commit/f269122508693b111142994dd48698ddc75f3d69), [`8f6006a`](https://github.com/Effect-TS/effect/commit/8f6006a610fb6d6c7b8d14209a7323338a8964ff), [`62934fc`](https://github.com/Effect-TS/effect/commit/62934fc61ae870b0e86ef0711c2852743adee9db), [`c45b559`](https://github.com/Effect-TS/effect/commit/c45b5592b5fd1189a5c932cfe05bd7d5f6d68508), [`430c846`](https://github.com/Effect-TS/effect/commit/430c846cbac05b187e3d24ac8dfee0cf22506f7c), [`7b03057`](https://github.com/Effect-TS/effect/commit/7b03057507d2dab5e6793beb9c578dedaaeb15fe), [`a9c94c8`](https://github.com/Effect-TS/effect/commit/a9c94c807755610831211a686d2fad849ab38eb4), [`107e6f0`](https://github.com/Effect-TS/effect/commit/107e6f0557a1e2d3b0dce25d62fa1e2601521752), [`c9175ae`](https://github.com/Effect-TS/effect/commit/c9175aef41cb1e3b689d0ac0a4f53d8107376b58), [`65c11b9`](https://github.com/Effect-TS/effect/commit/65c11b9266ec9447c31c26fe3ed35c73bd3b81fd), [`e386d2f`](https://github.com/Effect-TS/effect/commit/e386d2f1b3ab3ac2c14ee76de11f5963d32a3df4), [`9172efb`](https://github.com/Effect-TS/effect/commit/9172efba98bc6a82353e6ec2af61ac08f038ba64)]:\n  - @effect/platform@0.75.2\n  - effect@3.12.8\n  - @effect/platform-node@0.71.2\n\n## 0.39.1\n\n### Patch Changes\n\n- Updated dependencies [[`8dff1d1`](https://github.com/Effect-TS/effect/commit/8dff1d1bff76cdba643cad7f0bf864300f08bc61)]:\n  - effect@3.12.7\n  - @effect/platform@0.75.1\n  - @effect/platform-node@0.71.1\n\n## 0.39.0\n\n### Minor Changes\n\n- [#4306](https://github.com/Effect-TS/effect/pull/4306) [`5e43ce5`](https://github.com/Effect-TS/effect/commit/5e43ce50bae116865906112e7f88d390739d778b) Thanks @tim-smart! - eliminate Scope by default in some layer apis\n\n### Patch Changes\n\n- Updated dependencies [[`5e43ce5`](https://github.com/Effect-TS/effect/commit/5e43ce50bae116865906112e7f88d390739d778b), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`76eb7d0`](https://github.com/Effect-TS/effect/commit/76eb7d0fbce3c009c8f77e84c178cb15bbed9709), [`8b4e75d`](https://github.com/Effect-TS/effect/commit/8b4e75d35daea807c447ca760948a717aa66bb52), [`fc5e0f0`](https://github.com/Effect-TS/effect/commit/fc5e0f0d357a0051cfa01c1ede83ffdd3cb41ab1), [`004fd2b`](https://github.com/Effect-TS/effect/commit/004fd2bbd1459e64fb1b57f02eeb791ca5ea1ea5), [`b2a31be`](https://github.com/Effect-TS/effect/commit/b2a31be85c35d891351ce4f9a2cc93ece0c257f6), [`5514d05`](https://github.com/Effect-TS/effect/commit/5514d05b5cd586ff5868b8bd41c959e95e6c33cd), [`bf5f0ae`](https://github.com/Effect-TS/effect/commit/bf5f0ae9daa0170471678e22585e8ec14ce667bb), [`3b19bcf`](https://github.com/Effect-TS/effect/commit/3b19bcfd3aaadb6c9253428622df524537c8e626), [`b064b3b`](https://github.com/Effect-TS/effect/commit/b064b3b293615fd268cc5a5647d0981eb67750b8), [`eb264ed`](https://github.com/Effect-TS/effect/commit/eb264ed8a6e8c92a9dc7006f766c6ca2e5d29e03), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`f474678`](https://github.com/Effect-TS/effect/commit/f474678bf10b8f1c80e3dc096ddc7ecf20b2b23e), [`ee187d0`](https://github.com/Effect-TS/effect/commit/ee187d098007a402844c94d04f0cd8f07695377a)]:\n  - @effect/platform@0.75.0\n  - effect@3.12.6\n  - @effect/platform-node@0.71.0\n\n## 0.38.0\n\n### Minor Changes\n\n- [#3978](https://github.com/Effect-TS/effect/pull/3978) [`bd0d489`](https://github.com/Effect-TS/effect/commit/bd0d4892b098bc4c589444af9f50259c2c02ec0f) Thanks @tim-smart! - improve defaults for VariantSchema.Overrideable\n\n### Patch Changes\n\n- [#3978](https://github.com/Effect-TS/effect/pull/3978) [`bd0d489`](https://github.com/Effect-TS/effect/commit/bd0d4892b098bc4c589444af9f50259c2c02ec0f) Thanks @tim-smart! - add experimental EventLog modules\n\n- Updated dependencies [[`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8653072`](https://github.com/Effect-TS/effect/commit/86530720d7a03e118d2c5a8bf5a997cee7e7f3d6), [`507d546`](https://github.com/Effect-TS/effect/commit/507d546bd49db31000425fb5da88c434e4291bea), [`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8db239b`](https://github.com/Effect-TS/effect/commit/8db239b9c869a3707f6566b9d9dbdf53c4df03fc), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`3179a9f`](https://github.com/Effect-TS/effect/commit/3179a9f65d23369a6a9a1f80f7750566dd28df22), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e), [`1fcbe55`](https://github.com/Effect-TS/effect/commit/1fcbe55345042d8468f6a98c84081bd00b6bcf5a), [`d9a63d9`](https://github.com/Effect-TS/effect/commit/d9a63d9d385653865954cac895065360d54cc56b), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e)]:\n  - effect@3.12.5\n  - @effect/platform@0.74.0\n  - @effect/platform-node@0.70.0\n\n## 0.37.1\n\n### Patch Changes\n\n- Updated dependencies [[`5b50ea4`](https://github.com/Effect-TS/effect/commit/5b50ea4a10cf9acd51f9624b2474d9d5ded74019), [`c170a68`](https://github.com/Effect-TS/effect/commit/c170a68b6266100774461fcd6c0e0fabb60112f2), [`a66c2eb`](https://github.com/Effect-TS/effect/commit/a66c2eb473245092cd41f04c2eb2b7b02cf53718), [`c9e5e1b`](https://github.com/Effect-TS/effect/commit/c9e5e1be17c0c84d3d4e2abc3c60215cdb56bbbe), [`7b3d58d`](https://github.com/Effect-TS/effect/commit/7b3d58d7aec2152ec282460871d3e9de45ed254d)]:\n  - effect@3.12.4\n  - @effect/platform@0.73.1\n  - @effect/platform-node@0.69.1\n\n## 0.37.0\n\n### Patch Changes\n\n- Updated dependencies [[`d7dac48`](https://github.com/Effect-TS/effect/commit/d7dac48a477cdfeec509dbe9f33fce6a1b02b63d), [`c110032`](https://github.com/Effect-TS/effect/commit/c110032322450a8824ba38ae24335a538cd2ce9a), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`23ac740`](https://github.com/Effect-TS/effect/commit/23ac740c7dd4610b7d265c2071b88b0968419e9a), [`8cd7319`](https://github.com/Effect-TS/effect/commit/8cd7319b6568bfc7a30ca16c104d189e37eac3a0)]:\n  - effect@3.12.3\n  - @effect/platform@0.73.0\n  - @effect/platform-node@0.69.0\n\n## 0.36.2\n\n### Patch Changes\n\n- Updated dependencies [[`734af82`](https://github.com/Effect-TS/effect/commit/734af82138e78b9c57a8355b1c6b80e80d38b222), [`b63c780`](https://github.com/Effect-TS/effect/commit/b63c78010893101520448ddda7019c487cf7eedd), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`f852cb0`](https://github.com/Effect-TS/effect/commit/f852cb02040ea2f165e9b449615b8b1366add5d5), [`7276ae2`](https://github.com/Effect-TS/effect/commit/7276ae21062896adbb7508ac5b2dece95316322f), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a), [`c640d77`](https://github.com/Effect-TS/effect/commit/c640d77b33ad417876f4e8ffe8574ee6cbe5607f), [`0def088`](https://github.com/Effect-TS/effect/commit/0def0887cfdb6755729a64dfd52b3b9f46b0576c)]:\n  - effect@3.12.2\n  - @effect/platform@0.72.2\n  - @effect/platform-node@0.68.2\n\n## 0.36.1\n\n### Patch Changes\n\n- Updated dependencies [[`302b57d`](https://github.com/Effect-TS/effect/commit/302b57d2cbf9b9ccc17450945aeebfb33cfe8d43), [`0988083`](https://github.com/Effect-TS/effect/commit/0988083d4594938590df5a287e5b27d38526dd07), [`8b46be6`](https://github.com/Effect-TS/effect/commit/8b46be6a3b8160362ab5ea9171c5e6932505125c), [`bfe8027`](https://github.com/Effect-TS/effect/commit/bfe802734b450a4b4ee069d1125dd37995db2bff), [`16dd657`](https://github.com/Effect-TS/effect/commit/16dd657033d8afac2ffea567b3c8bb27c9b249b6), [`39db211`](https://github.com/Effect-TS/effect/commit/39db211414e90c8db8fdad7dc8ce5b4661bcfaef)]:\n  - effect@3.12.1\n  - @effect/platform@0.72.1\n  - @effect/platform-node@0.68.1\n\n## 0.36.0\n\n### Patch Changes\n\n- Updated dependencies [[`abb22a4`](https://github.com/Effect-TS/effect/commit/abb22a429b9c52c31e84856294f175d2064a9b4d), [`f369a89`](https://github.com/Effect-TS/effect/commit/f369a89e98bc682969803b9304adaf4557bb36c2), [`642376c`](https://github.com/Effect-TS/effect/commit/642376c63fd7d78754db991631a4d50a5dc79aa3), [`3d2b7a7`](https://github.com/Effect-TS/effect/commit/3d2b7a7e942a7157afae5b1cdbc6f3fef116428e), [`ef64c6f`](https://github.com/Effect-TS/effect/commit/ef64c6fec0d47da573c04230dde9ea729366d871), [`73f9c6f`](https://github.com/Effect-TS/effect/commit/73f9c6f2ff091512cf904cc54ab59965b86e87c8), [`17cb451`](https://github.com/Effect-TS/effect/commit/17cb4514590e8a86263f7aed009f24da8a237342), [`d801820`](https://github.com/Effect-TS/effect/commit/d80182060c2ee945d7e0e4728812abf9465a0d6a), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1), [`c11f3a6`](https://github.com/Effect-TS/effect/commit/c11f3a60a05c3b5fc8e7ce90136728154dc505b0), [`618f7e0`](https://github.com/Effect-TS/effect/commit/618f7e092a1011e5090dca1e69b5e9285689654b), [`c0ba834`](https://github.com/Effect-TS/effect/commit/c0ba834d1995cf5a8b250e4780fd43f3e3881151), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1)]:\n  - effect@3.12.0\n  - @effect/platform@0.72.0\n  - @effect/platform-node@0.68.0\n\n## 0.35.3\n\n### Patch Changes\n\n- Updated dependencies [[`39457d4`](https://github.com/Effect-TS/effect/commit/39457d4897d9bc7df8af5c05d352866bbeae82eb), [`a475cc2`](https://github.com/Effect-TS/effect/commit/a475cc25fd7c9f26b27a8e98f8fbe43cc9e6ee3e), [`199214e`](https://github.com/Effect-TS/effect/commit/199214e21c616d8a0ccd7ed5f92e944e6c580193), [`b3c160d`](https://github.com/Effect-TS/effect/commit/b3c160d7a1fdfc2d3fb2440530f1ab80efc65133)]:\n  - effect@3.11.10\n  - @effect/platform@0.71.7\n  - @effect/platform-node@0.67.3\n\n## 0.35.2\n\n### Patch Changes\n\n- Updated dependencies [[`1c08a0b`](https://github.com/Effect-TS/effect/commit/1c08a0b8505badcffb4d9cade5a746ea90c9557e), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd)]:\n  - effect@3.11.9\n  - @effect/platform@0.71.6\n  - @effect/platform-node@0.67.2\n\n## 0.35.1\n\n### Patch Changes\n\n- Updated dependencies [[`05d71f8`](https://github.com/Effect-TS/effect/commit/05d71f85622305705d8316817694a09762e60865), [`e66b920`](https://github.com/Effect-TS/effect/commit/e66b9205f25ab425d30640886eb3fb2c4715bc26)]:\n  - @effect/platform@0.71.5\n  - @effect/platform-node@0.67.1\n\n## 0.35.0\n\n### Patch Changes\n\n- Updated dependencies [[`909181a`](https://github.com/Effect-TS/effect/commit/909181a9ce9052a80432ccf52187e0723004bf7f), [`909181a`](https://github.com/Effect-TS/effect/commit/909181a9ce9052a80432ccf52187e0723004bf7f), [`011e2b6`](https://github.com/Effect-TS/effect/commit/011e2b604e2e61e7b788243b0aab105fd301ec7f), [`1a6b52d`](https://github.com/Effect-TS/effect/commit/1a6b52dcf020d36e38a7bc90b648152cf5a8ccba)]:\n  - @effect/platform@0.71.4\n  - @effect/platform-node@0.67.0\n  - effect@3.11.8\n\n## 0.34.3\n\n### Patch Changes\n\n- Updated dependencies [[`6984508`](https://github.com/Effect-TS/effect/commit/6984508c87f1bd91213b44c19b25ab5e2dcc1ce0), [`883639c`](https://github.com/Effect-TS/effect/commit/883639cc8ce47757f1cd39439391a8028c0812fe)]:\n  - @effect/platform@0.71.3\n  - @effect/platform-node@0.66.3\n\n## 0.34.2\n\n### Patch Changes\n\n- Updated dependencies [[`2408616`](https://github.com/Effect-TS/effect/commit/24086163b60b09cc6d0885bd565ef080dcbe866b), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`8d978c5`](https://github.com/Effect-TS/effect/commit/8d978c53f6fcc98d9d645ecba3e4b55d4297dd36), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e)]:\n  - effect@3.11.7\n  - @effect/platform@0.71.2\n  - @effect/platform-node@0.66.2\n\n## 0.34.1\n\n### Patch Changes\n\n- Updated dependencies [[`1d3df5b`](https://github.com/Effect-TS/effect/commit/1d3df5bc4324e88a392c348db35fd9d029c7b25e)]:\n  - @effect/platform@0.71.1\n  - @effect/platform-node@0.66.1\n\n## 0.34.0\n\n### Patch Changes\n\n- Updated dependencies [[`662d1ce`](https://github.com/Effect-TS/effect/commit/662d1ce6fb7da384a95888d5b2bb5605bdf3208d), [`c99a0f3`](https://github.com/Effect-TS/effect/commit/c99a0f376d049d3793ed33e146d9873b8a5e5b78), [`11fc401`](https://github.com/Effect-TS/effect/commit/11fc401f436f99bf4be95f56d50b0e4bdfe5edea), [`c99a0f3`](https://github.com/Effect-TS/effect/commit/c99a0f376d049d3793ed33e146d9873b8a5e5b78), [`31c62d8`](https://github.com/Effect-TS/effect/commit/31c62d83cbdcf9850a8b5331faa239601c60f78a)]:\n  - effect@3.11.6\n  - @effect/platform@0.71.0\n  - @effect/platform-node@0.66.0\n\n## 0.33.7\n\n### Patch Changes\n\n- [#4114](https://github.com/Effect-TS/effect/pull/4114) [`ef70ffc`](https://github.com/Effect-TS/effect/commit/ef70ffc417ec035ede40c62b7316e447cc7c1932) Thanks @tim-smart! - ensure Reactivity events aren't missed\n\n- Updated dependencies [[`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`22905cf`](https://github.com/Effect-TS/effect/commit/22905cf5addfb1ff3d2a6135c52036be958ae911), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`1e59e4f`](https://github.com/Effect-TS/effect/commit/1e59e4fd778da18296812a2a32f36ca8ae50f60d), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`8d914e5`](https://github.com/Effect-TS/effect/commit/8d914e504e7a22d0ea628e8af265ee450ff9530f), [`03bb00f`](https://github.com/Effect-TS/effect/commit/03bb00faa74f9e168a54a8cc0828a664fbb1ab05), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`14e1149`](https://github.com/Effect-TS/effect/commit/14e1149f1af5a022f06eb8c2e4ba9fec17fe7426), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8)]:\n  - effect@3.11.5\n  - @effect/platform@0.70.7\n  - @effect/platform-node@0.65.7\n\n## 0.33.6\n\n### Patch Changes\n\n- Updated dependencies [[`9a5b8e3`](https://github.com/Effect-TS/effect/commit/9a5b8e36d184bd4967a88752cb6e755e1be263af)]:\n  - @effect/platform@0.70.6\n  - @effect/platform-node@0.65.6\n\n## 0.33.5\n\n### Patch Changes\n\n- [#4087](https://github.com/Effect-TS/effect/pull/4087) [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2) Thanks @tim-smart! - remove Socket write indirection\n\n- Updated dependencies [[`415f4c9`](https://github.com/Effect-TS/effect/commit/415f4c98321868531727a83cbaad70164f5e4c40), [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f), [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f)]:\n  - @effect/platform@0.70.5\n  - effect@3.11.4\n  - @effect/platform-node@0.65.5\n\n## 0.33.4\n\n### Patch Changes\n\n- Updated dependencies [[`90906f7`](https://github.com/Effect-TS/effect/commit/90906f7f154b12c7182e8f39e3c55ef3937db857), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`343b6aa`](https://github.com/Effect-TS/effect/commit/343b6aa6ac4a74276bfc7c63ccbf4a1d72bc1bed), [`afba339`](https://github.com/Effect-TS/effect/commit/afba339adc11dad56b5a3b7ca94487e58f34d613)]:\n  - effect@3.11.3\n  - @effect/platform@0.70.4\n  - @effect/platform-node@0.65.4\n\n## 0.33.3\n\n### Patch Changes\n\n- Updated dependencies [[`7044730`](https://github.com/Effect-TS/effect/commit/70447306be1aeeb7d87c230b2a96ec87b993ede9)]:\n  - @effect/platform@0.70.3\n  - @effect/platform-node@0.65.3\n\n## 0.33.2\n\n### Patch Changes\n\n- Updated dependencies [[`01cee56`](https://github.com/Effect-TS/effect/commit/01cee560b58d94b24cc20e98083251b73e658b41), [`c2249ea`](https://github.com/Effect-TS/effect/commit/c2249ea13fd98ab7d9aa628787931356d8ec2860), [`1358aa5`](https://github.com/Effect-TS/effect/commit/1358aa5326eaa85ef13ee8d1fed0b4a4288ed3eb), [`1de3fe7`](https://github.com/Effect-TS/effect/commit/1de3fe7d1cbafd6391eaa38c2300b99e332cc2aa)]:\n  - effect@3.11.2\n  - @effect/platform-node@0.65.2\n  - @effect/platform@0.70.2\n\n## 0.33.1\n\n### Patch Changes\n\n- Updated dependencies [[`dd8a2d8`](https://github.com/Effect-TS/effect/commit/dd8a2d8e80d33b16719fc69361eaedf0b59d4620), [`a71bfef`](https://github.com/Effect-TS/effect/commit/a71bfef46f5061bb2502a61a333638a987b62273)]:\n  - effect@3.11.1\n  - @effect/platform@0.70.1\n  - @effect/platform-node@0.65.1\n\n## 0.33.0\n\n### Patch Changes\n\n- Updated dependencies [[`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`6e69493`](https://github.com/Effect-TS/effect/commit/6e694930048bbaf98110f35f41566aeb9752d471), [`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`5eff3f6`](https://github.com/Effect-TS/effect/commit/5eff3f6fa3aae7e86948a62cbfd63b8d6c3bdf92), [`d9fe79b`](https://github.com/Effect-TS/effect/commit/d9fe79bb5a3fe105d8e7a3bc2922a8ad936a5d10), [`251d189`](https://github.com/Effect-TS/effect/commit/251d189420bbba71990574e91098c499065f9a9b), [`5a259f3`](https://github.com/Effect-TS/effect/commit/5a259f3711b4369f55d885b568bdb21136155261), [`b4ce4ea`](https://github.com/Effect-TS/effect/commit/b4ce4ea7fd514a7e572f2dcd879c98f334981b0e), [`15fcc5a`](https://github.com/Effect-TS/effect/commit/15fcc5a0ea4bbf40ab48fa6a04fdda74f76f4c07), [`9bc9a47`](https://github.com/Effect-TS/effect/commit/9bc9a476800dc645903c888a68bb1d3baa3383c6), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb), [`1e2747c`](https://github.com/Effect-TS/effect/commit/1e2747c63a4820d1459cbbc88c71212983bd68bd), [`9264162`](https://github.com/Effect-TS/effect/commit/9264162a82783a651776fb7b87604564a63e7070), [`e0b9b09`](https://github.com/Effect-TS/effect/commit/e0b9b09e70c386b2da17d1f0a15b0511861c89e8), [`c36f3b9`](https://github.com/Effect-TS/effect/commit/c36f3b95df5ce9d71b66f22f26ce12eda8d3e848), [`672bde5`](https://github.com/Effect-TS/effect/commit/672bde5bec51c7d6f9862828e6a654cb2cb6f93d), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb)]:\n  - effect@3.11.0\n  - @effect/platform-node@0.65.0\n  - @effect/platform@0.70.0\n\n## 0.32.17\n\n### Patch Changes\n\n- Updated dependencies [[`3069614`](https://github.com/Effect-TS/effect/commit/30696149271129fc618f6f2ccd1d8f2f6c0f9cd7), [`09a5e52`](https://github.com/Effect-TS/effect/commit/09a5e522fd9b221f05d85b1d1c8a740d4973c302)]:\n  - effect@3.10.20\n  - @effect/platform@0.69.32\n  - @effect/platform-node@0.64.34\n\n## 0.32.16\n\n### Patch Changes\n\n- Updated dependencies [[`e6d4a37`](https://github.com/Effect-TS/effect/commit/e6d4a37c1d7e657b5ea44063a1cf586808228fe5)]:\n  - @effect/platform-node@0.64.33\n  - @effect/platform@0.69.31\n\n## 0.32.15\n\n### Patch Changes\n\n- [#4029](https://github.com/Effect-TS/effect/pull/4029) [`5e17400`](https://github.com/Effect-TS/effect/commit/5e1740017cb97026e7f583c5fe71847c606df388) Thanks @gcanti! - Avoid \"Cannot access 'ParentSpan' before initialization\" error during module initialization\n\n## 0.32.14\n\n### Patch Changes\n\n- Updated dependencies [[`270f199`](https://github.com/Effect-TS/effect/commit/270f199b31810fd643e4c22818698adcbdb5d396)]:\n  - @effect/platform-node@0.64.32\n  - @effect/platform@0.69.30\n\n## 0.32.13\n\n### Patch Changes\n\n- [#4021](https://github.com/Effect-TS/effect/pull/4021) [`e9dfea3`](https://github.com/Effect-TS/effect/commit/e9dfea3f394444ebd8929e5cfe05ce740cf84d6e) Thanks @tim-smart! - add .reactive method to SqlClient interface\n\n- Updated dependencies [[`24cc35e`](https://github.com/Effect-TS/effect/commit/24cc35e26d6ed4a076470bc687ffd99cc50991b3)]:\n  - @effect/platform-node@0.64.31\n  - @effect/platform@0.69.29\n\n## 0.32.12\n\n### Patch Changes\n\n- [#4007](https://github.com/Effect-TS/effect/pull/4007) [`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1) Thanks @gcanti! - Wrap JSDoc @example tags with a TypeScript fence, closes #4002\n\n- Updated dependencies [[`edd72be`](https://github.com/Effect-TS/effect/commit/edd72be57b904d60c9cbffc2537901821a9da537), [`a3e2771`](https://github.com/Effect-TS/effect/commit/a3e277170a1f7cf61fd629acb60304c7e81d9498), [`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1), [`54addee`](https://github.com/Effect-TS/effect/commit/54addee438a644bf010646c52042c7b89c5fc0a7), [`a9e00e4`](https://github.com/Effect-TS/effect/commit/a9e00e43f0b5dd22c1f9d5b78be6383daea09c20)]:\n  - @effect/platform@0.69.28\n  - @effect/platform-node@0.64.30\n  - effect@3.10.19\n\n## 0.32.11\n\n### Patch Changes\n\n- Updated dependencies [[`af409cf`](https://github.com/Effect-TS/effect/commit/af409cf1d2ff973be11cc079ea373eaeedca25de), [`beaccae`](https://github.com/Effect-TS/effect/commit/beaccae2d15931e9fe475fb50a0b3638243fe3f7)]:\n  - effect@3.10.18\n  - @effect/platform@0.69.27\n  - @effect/platform-node@0.64.29\n\n## 0.32.10\n\n### Patch Changes\n\n- Updated dependencies [[`c963886`](https://github.com/Effect-TS/effect/commit/c963886d5817986fcbd6bfa4ddf50aca8b6c8184), [`42c4ce6`](https://github.com/Effect-TS/effect/commit/42c4ce6f8d8c7d847e97757650a8ad9419a829d7)]:\n  - @effect/platform@0.69.26\n  - effect@3.10.17\n  - @effect/platform-node@0.64.28\n\n## 0.32.9\n\n### Patch Changes\n\n- Updated dependencies [[`320557a`](https://github.com/Effect-TS/effect/commit/320557ab18d13c5e22fc7dc0d2a157eae461012f), [`4dca30c`](https://github.com/Effect-TS/effect/commit/4dca30cfcdafe4542e236489f71d6f171a5b4e38), [`1d99867`](https://github.com/Effect-TS/effect/commit/1d998671be3cd11043f232822e91dd8c98fccfa9), [`6dae414`](https://github.com/Effect-TS/effect/commit/6dae4147991a97ec14a99289bd25fadae7541e8d), [`6b0d737`](https://github.com/Effect-TS/effect/commit/6b0d737078bf63b97891e6bc47affc04b28f9cf7), [`d8356aa`](https://github.com/Effect-TS/effect/commit/d8356aad428a0c2290db52380220f81d9ec94232), [`7b93dd6`](https://github.com/Effect-TS/effect/commit/7b93dd622e2ab79c7072d79d0d9611e446202201)]:\n  - @effect/platform@0.69.25\n  - effect@3.10.16\n  - @effect/platform-node@0.64.27\n\n## 0.32.8\n\n### Patch Changes\n\n- Updated dependencies [[`3cc6514`](https://github.com/Effect-TS/effect/commit/3cc6514d2dd64e010cb760cc29bfce98c349bb10)]:\n  - @effect/platform@0.69.24\n  - @effect/platform-node@0.64.26\n\n## 0.32.7\n\n### Patch Changes\n\n- Updated dependencies [[`3aff4d3`](https://github.com/Effect-TS/effect/commit/3aff4d38837c213bb2987973dc4b98febb9f92d2)]:\n  - @effect/platform@0.69.23\n  - @effect/platform-node@0.64.25\n\n## 0.32.6\n\n### Patch Changes\n\n- [#3937](https://github.com/Effect-TS/effect/pull/3937) [`4e9e256`](https://github.com/Effect-TS/effect/commit/4e9e256e9f0b4a9e9b202d3bb703b5a4622e75cb) Thanks @tim-smart! - add Reactivity module to experimental\n\n- Updated dependencies [[`8398b32`](https://github.com/Effect-TS/effect/commit/8398b3208242a88239d4449910b7baf923cfe3b6), [`72e55b7`](https://github.com/Effect-TS/effect/commit/72e55b7c610784fcebdbadc592c876e23e76a986)]:\n  - effect@3.10.15\n  - @effect/platform@0.69.22\n  - @effect/platform-node@0.64.24\n\n## 0.32.5\n\n### Patch Changes\n\n- Updated dependencies [[`f983946`](https://github.com/Effect-TS/effect/commit/f9839467b4cad6e788297764ef9f9f0b9fd203f9), [`2d8a750`](https://github.com/Effect-TS/effect/commit/2d8a75081eb83a0a81f817fdf6f428369c5064ab)]:\n  - effect@3.10.14\n  - @effect/platform@0.69.21\n  - @effect/platform-node@0.64.23\n\n## 0.32.4\n\n### Patch Changes\n\n- Updated dependencies [[`995bbdf`](https://github.com/Effect-TS/effect/commit/995bbdffea2e332f203cd5b474cd6a1c77dfa6ae)]:\n  - effect@3.10.13\n  - @effect/platform@0.69.20\n  - @effect/platform-node@0.64.22\n\n## 0.32.3\n\n### Patch Changes\n\n- Updated dependencies [[`eb8c52d`](https://github.com/Effect-TS/effect/commit/eb8c52d8b4c5e067ebf0a81eb742f5822e6439b5)]:\n  - @effect/platform-node@0.64.21\n  - @effect/platform@0.69.19\n\n## 0.32.2\n\n### Patch Changes\n\n- Updated dependencies [[`a0584ec`](https://github.com/Effect-TS/effect/commit/a0584ece92ed784bfb139e9c5a699f02d1e71c2d), [`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6), [`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6)]:\n  - @effect/platform@0.69.18\n  - @effect/platform-node@0.64.20\n  - effect@3.10.12\n\n## 0.32.1\n\n### Patch Changes\n\n- Updated dependencies [[`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a), [`8240b1c`](https://github.com/Effect-TS/effect/commit/8240b1c10d45312fc863cb679b1a1e8441af0c1a), [`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a), [`a2bd4df`](https://github.com/Effect-TS/effect/commit/a2bd4dfa3d9a28a7d02ee177baf173c92a4dee7b)]:\n  - effect@3.10.11\n  - @effect/platform@0.69.17\n  - @effect/platform-node@0.64.19\n\n## 0.32.0\n\n### Minor Changes\n\n- [#3896](https://github.com/Effect-TS/effect/pull/3896) [`12b3275`](https://github.com/Effect-TS/effect/commit/12b32753afbf252d156ff613f9e88662b160a7e5) Thanks @tim-smart! - simplify DevTool/Server module\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/platform-node@0.64.18\n\n## 0.31.0\n\n### Minor Changes\n\n- [#3893](https://github.com/Effect-TS/effect/pull/3893) [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28) Thanks @tim-smart! - simplify SocketServer api\n\n- [#3893](https://github.com/Effect-TS/effect/pull/3893) [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28) Thanks @tim-smart! - use Mailbox for DevTools implementation\n\n### Patch Changes\n\n- Updated dependencies [[`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`b631f40`](https://github.com/Effect-TS/effect/commit/b631f40abbe649b2a089764585b5c39f6a695ac6), [`7d89650`](https://github.com/Effect-TS/effect/commit/7d8965036cd2ea435c8441ffec3345488baebf85)]:\n  - effect@3.10.10\n  - @effect/platform@0.69.16\n  - @effect/platform-node@0.64.17\n\n## 0.30.16\n\n### Patch Changes\n\n- Updated dependencies [[`8a30e1d`](https://github.com/Effect-TS/effect/commit/8a30e1dfa3a7103bf5414fc6a7fca3088d8c8c00)]:\n  - @effect/platform-node@0.64.16\n  - @effect/platform@0.69.15\n\n## 0.30.15\n\n### Patch Changes\n\n- [#3882](https://github.com/Effect-TS/effect/pull/3882) [`257ab1b`](https://github.com/Effect-TS/effect/commit/257ab1b539fa6e930b7ae2583a188376372200d7) Thanks @tim-smart! - simplify Socket internal code\n\n- Updated dependencies [[`a123e80`](https://github.com/Effect-TS/effect/commit/a123e80f111a625428a5b5622b7f55ee1073566b), [`bd5fcd3`](https://github.com/Effect-TS/effect/commit/bd5fcd3e6b603b1e505af90d6a00627c8eca6d41), [`0289d3b`](https://github.com/Effect-TS/effect/commit/0289d3b6391031d00329365bab9791b355031fe3), [`7386b71`](https://github.com/Effect-TS/effect/commit/7386b710e5be570e17f468928a6ed19d549a3e12), [`07c493a`](https://github.com/Effect-TS/effect/commit/07c493a598e096c7810cd06def8cfa43493c46b1), [`257ab1b`](https://github.com/Effect-TS/effect/commit/257ab1b539fa6e930b7ae2583a188376372200d7), [`4211a23`](https://github.com/Effect-TS/effect/commit/4211a2355bb3af3f0e756e2aae9d293379f25662)]:\n  - effect@3.10.9\n  - @effect/platform-node@0.64.15\n  - @effect/platform@0.69.14\n\n## 0.30.14\n\n### Patch Changes\n\n- [#3875](https://github.com/Effect-TS/effect/pull/3875) [`6f86821`](https://github.com/Effect-TS/effect/commit/6f8682184ac7a7e8eec61c93b028af034c2c7254) Thanks @tim-smart! - fix DevTools error logging\n\n- Updated dependencies [[`68b5c9e`](https://github.com/Effect-TS/effect/commit/68b5c9e44f34192cef26e1cadda5e661a027df41), [`9c9928d`](https://github.com/Effect-TS/effect/commit/9c9928dfeacd9ac33dc37eb0ca3d7d8c39175ada), [`6306e66`](https://github.com/Effect-TS/effect/commit/6306e6656092b350d4ede5746da6f245ec9f7e07), [`361c7f3`](https://github.com/Effect-TS/effect/commit/361c7f39a2c10ede9324847c3d3ba192a6f9b20a)]:\n  - effect@3.10.8\n  - @effect/platform@0.69.13\n  - @effect/platform-node@0.64.14\n\n## 0.30.13\n\n### Patch Changes\n\n- Updated dependencies [[`33f5b9f`](https://github.com/Effect-TS/effect/commit/33f5b9ffaebea4f1bd0e391b44c41fb6230e743a), [`50f0281`](https://github.com/Effect-TS/effect/commit/50f0281b0d2116726b8927a6217622d5f394f3e4)]:\n  - effect@3.10.7\n  - @effect/platform@0.69.12\n  - @effect/platform-node@0.64.13\n\n## 0.30.12\n\n### Patch Changes\n\n- Updated dependencies [[`ce1c21f`](https://github.com/Effect-TS/effect/commit/ce1c21ffc11902ac9ab453a51904207859d38552), [`81ddd45`](https://github.com/Effect-TS/effect/commit/81ddd45fc074b98206fafab416d9a5a28b31e07a)]:\n  - effect@3.10.6\n  - @effect/platform@0.69.11\n  - @effect/platform-node@0.64.12\n\n## 0.30.11\n\n### Patch Changes\n\n- Updated dependencies [[`3a6d757`](https://github.com/Effect-TS/effect/commit/3a6d757badeebe00d8ef4d67530d073c8264dcfa), [`59d813a`](https://github.com/Effect-TS/effect/commit/59d813aa4973d1115cfc70cc3667508335f49693)]:\n  - effect@3.10.5\n  - @effect/platform@0.69.10\n  - @effect/platform-node@0.64.11\n\n## 0.30.10\n\n### Patch Changes\n\n- Updated dependencies [[`2367708`](https://github.com/Effect-TS/effect/commit/2367708be449f9526a2047e321302d7bfb16f18e)]:\n  - @effect/platform@0.69.9\n  - effect@3.10.4\n  - @effect/platform-node@0.64.10\n\n## 0.30.9\n\n### Patch Changes\n\n- Updated dependencies [[`522f7c5`](https://github.com/Effect-TS/effect/commit/522f7c518a5acfb55ef96d6796869f002cc3eaf8)]:\n  - @effect/platform@0.69.8\n  - @effect/platform-node@0.64.9\n\n## 0.30.8\n\n### Patch Changes\n\n- Updated dependencies [[`690d6c5`](https://github.com/Effect-TS/effect/commit/690d6c54d2145adb0af545c447db7d4755bf3c6b), [`b9423d8`](https://github.com/Effect-TS/effect/commit/b9423d8bf8181a2389fdbce1e3c14ac6fe8d54f5), [`279fe3a`](https://github.com/Effect-TS/effect/commit/279fe3a7168fe84e520c2cc88ba189a15f03a2bc)]:\n  - @effect/platform@0.69.7\n  - effect@3.10.3\n  - @effect/platform-node@0.64.8\n\n## 0.30.7\n\n### Patch Changes\n\n- Updated dependencies [[`714e119`](https://github.com/Effect-TS/effect/commit/714e11945e45e5a2554ee058e6c43f82a8e309cf), [`c1afd55`](https://github.com/Effect-TS/effect/commit/c1afd55c54e61f9c432823d21b3d016f79160a37), [`42cd72a`](https://github.com/Effect-TS/effect/commit/42cd72a44ca9593e4d81fbb50e8111625fd0fb81)]:\n  - effect@3.10.2\n  - @effect/platform@0.69.6\n  - @effect/platform-node@0.64.7\n\n## 0.30.6\n\n### Patch Changes\n\n- [#3818](https://github.com/Effect-TS/effect/pull/3818) [`9604d6b`](https://github.com/Effect-TS/effect/commit/9604d6b616435103dafea8b53637a9d1450b4750) Thanks @tim-smart! - wait for connection in DevTools client with 1s timeout\n\n- Updated dependencies [[`9604d6b`](https://github.com/Effect-TS/effect/commit/9604d6b616435103dafea8b53637a9d1450b4750)]:\n  - effect@3.10.1\n  - @effect/platform@0.69.5\n  - @effect/platform-node@0.64.6\n\n## 0.30.5\n\n### Patch Changes\n\n- Updated dependencies [[`c86b1d7`](https://github.com/Effect-TS/effect/commit/c86b1d7cd47b66df190ef9775a475467c1abdbd6)]:\n  - @effect/platform@0.69.4\n  - @effect/platform-node@0.64.5\n\n## 0.30.4\n\n### Patch Changes\n\n- Updated dependencies [[`d5fba63`](https://github.com/Effect-TS/effect/commit/d5fba6391e1005e374aa0238f13edfbd65848313), [`1eb2c30`](https://github.com/Effect-TS/effect/commit/1eb2c30ba064398db5790e376dedcfad55b7b005), [`02d413e`](https://github.com/Effect-TS/effect/commit/02d413e7b6bc1c64885969c37cc3e4e690c94d7d)]:\n  - @effect/platform@0.69.3\n  - @effect/platform-node@0.64.4\n\n## 0.30.3\n\n### Patch Changes\n\n- Updated dependencies [[`e7afc47`](https://github.com/Effect-TS/effect/commit/e7afc47ce83e381c3f4aed2b2974e3b3d86a2340)]:\n  - @effect/platform@0.69.2\n  - @effect/platform-node@0.64.3\n\n## 0.30.2\n\n### Patch Changes\n\n- Updated dependencies [[`a4aa34a`](https://github.com/Effect-TS/effect/commit/a4aa34a0c32b79f7c95f3eb36ee69a8e8e23684c)]:\n  - @effect/platform-node@0.64.2\n\n## 0.30.1\n\n### Patch Changes\n\n- Updated dependencies [[`7564f56`](https://github.com/Effect-TS/effect/commit/7564f56bb2844cf39d2b0d2d9e93cf9b2205e9a8), [`7564f56`](https://github.com/Effect-TS/effect/commit/7564f56bb2844cf39d2b0d2d9e93cf9b2205e9a8)]:\n  - @effect/platform@0.69.1\n  - @effect/platform-node@0.64.1\n\n## 0.30.0\n\n### Patch Changes\n\n- [#3764](https://github.com/Effect-TS/effect/pull/3764) [`6d9de6b`](https://github.com/Effect-TS/effect/commit/6d9de6b871c5c08e6509a4e830c3d74758faa198) Thanks @tim-smart! - add identifiers to VariantSchema variants\n\n- Updated dependencies [[`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`6d9de6b`](https://github.com/Effect-TS/effect/commit/6d9de6b871c5c08e6509a4e830c3d74758faa198), [`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`c79c4c1`](https://github.com/Effect-TS/effect/commit/c79c4c178390fe61ff6dda88c9e058862349343a), [`38d30f0`](https://github.com/Effect-TS/effect/commit/38d30f08b8da62f9c3e308b9250738cb8d17bdb5), [`5821ce3`](https://github.com/Effect-TS/effect/commit/5821ce3455b47d25e0a40cae6ce22af9db5fa556)]:\n  - effect@3.10.0\n  - @effect/platform@0.69.0\n  - @effect/platform-node@0.64.0\n\n## 0.29.6\n\n### Patch Changes\n\n- Updated dependencies [[`382556f`](https://github.com/Effect-TS/effect/commit/382556f8930780c0634de681077706113a8c8239), [`97cb014`](https://github.com/Effect-TS/effect/commit/97cb0145114b2cd2f378e98f6c4ff5bf2c1865f5)]:\n  - @effect/schema@0.75.5\n  - @effect/platform@0.68.6\n  - @effect/platform-node@0.63.6\n\n## 0.29.5\n\n### Patch Changes\n\n- Updated dependencies [[`2036402`](https://github.com/Effect-TS/effect/commit/20364020b8b75a684791aa93d90626758023e9e9)]:\n  - @effect/platform@0.68.5\n  - @effect/platform-node@0.63.5\n\n## 0.29.4\n\n### Patch Changes\n\n- Updated dependencies [[`1b1ef29`](https://github.com/Effect-TS/effect/commit/1b1ef29ae302322f69dc938f9337aa97b4c63266)]:\n  - @effect/platform@0.68.4\n  - @effect/platform-node@0.63.4\n\n## 0.29.3\n\n### Patch Changes\n\n- Updated dependencies [[`61a99b2`](https://github.com/Effect-TS/effect/commit/61a99b2bf9d757870ef0c2ec9d4c877cdd364a3d), [`8c33087`](https://github.com/Effect-TS/effect/commit/8c330879425e80bed2f65e407cd59e991f0d7bec), [`3bcdfb3`](https://github.com/Effect-TS/effect/commit/3bcdfb3b6453959f449b075130e2db941653f722)]:\n  - effect@3.9.2\n  - @effect/platform-node@0.63.3\n  - @effect/platform@0.68.3\n  - @effect/schema@0.75.4\n\n## 0.29.2\n\n### Patch Changes\n\n- [#3631](https://github.com/Effect-TS/effect/pull/3631) [`bd160a4`](https://github.com/Effect-TS/effect/commit/bd160a4f714b0f1cb5867e458fd70f9131b060d6) Thanks @tim-smart! - add Sse module to experimental, for parsing server-side-events\n\n- Updated dependencies [[`360ec14`](https://github.com/Effect-TS/effect/commit/360ec14dd4102c526aef7433a8881ad4d9beab75)]:\n  - @effect/schema@0.75.3\n  - @effect/platform@0.68.2\n  - @effect/platform-node@0.63.2\n\n## 0.29.1\n\n### Patch Changes\n\n- Updated dependencies [[`b75ac5d`](https://github.com/Effect-TS/effect/commit/b75ac5d0909115507bedc90f18f2d34deb217769)]:\n  - @effect/platform@0.68.1\n  - @effect/platform-node@0.63.1\n\n## 0.29.0\n\n### Patch Changes\n\n- Updated dependencies [[`f02b354`](https://github.com/Effect-TS/effect/commit/f02b354ab5b0451143b82bb73dc866be29adec85), [`90ceeab`](https://github.com/Effect-TS/effect/commit/90ceeab3a04051b740af18c8af8bd73ee8ec6363), [`90ceeab`](https://github.com/Effect-TS/effect/commit/90ceeab3a04051b740af18c8af8bd73ee8ec6363), [`90ceeab`](https://github.com/Effect-TS/effect/commit/90ceeab3a04051b740af18c8af8bd73ee8ec6363)]:\n  - @effect/schema@0.75.2\n  - @effect/platform-node@0.63.0\n  - @effect/platform@0.68.0\n\n## 0.28.1\n\n### Patch Changes\n\n- Updated dependencies [[`3b2ad1d`](https://github.com/Effect-TS/effect/commit/3b2ad1d58a2e33dc1a72b7037396bd25ca1702a9)]:\n  - @effect/platform@0.67.1\n  - effect@3.9.1\n  - @effect/schema@0.75.1\n  - @effect/platform-node@0.62.1\n\n## 0.28.0\n\n### Patch Changes\n\n- Updated dependencies [[`ff3d1aa`](https://github.com/Effect-TS/effect/commit/ff3d1aab290b4d1173b2dfc7e4c76abb4babdc16), [`0ba66f2`](https://github.com/Effect-TS/effect/commit/0ba66f2451641fd6990e02ec1ed01c014db9dab0), [`bf77f51`](https://github.com/Effect-TS/effect/commit/bf77f51b323c383224ebf08adf77a7a6e8c9b3cd), [`016f9ad`](https://github.com/Effect-TS/effect/commit/016f9ad931a4b3d09a34e5caf13d87c5b8e9c984), [`0779681`](https://github.com/Effect-TS/effect/commit/07796813f07de035719728733096ba64ce333469), [`534129f`](https://github.com/Effect-TS/effect/commit/534129f8113ce1a8ec50828083e16da9c86326c6), [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda), [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03), [`9237ac6`](https://github.com/Effect-TS/effect/commit/9237ac69bc07de5b3b60076a0ad2921c21de7457), [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03), [`5b36494`](https://github.com/Effect-TS/effect/commit/5b364942e9a9003fdb8217324f8a2d8369c969da), [`c716adb`](https://github.com/Effect-TS/effect/commit/c716adb250ebbea1d1048d818ef7fed4f621d186), [`4986391`](https://github.com/Effect-TS/effect/commit/49863919cd8628c962a712fb1df30d2983820933), [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda), [`d1387ae`](https://github.com/Effect-TS/effect/commit/d1387aebd1ff01bbebde26be46d488956e4daef6)]:\n  - effect@3.9.0\n  - @effect/platform@0.67.0\n  - @effect/schema@0.75.0\n  - @effect/platform-node@0.62.0\n\n## 0.27.4\n\n### Patch Changes\n\n- Updated dependencies [[`88e85db`](https://github.com/Effect-TS/effect/commit/88e85db34bd402526e27a323e950d053fa34d232), [`f40da15`](https://github.com/Effect-TS/effect/commit/f40da15fbeb7c491840b8f409d47de79720891c3), [`8e94585`](https://github.com/Effect-TS/effect/commit/8e94585abe62753bf3af28bfae77926a7c570ac3), [`83887ca`](https://github.com/Effect-TS/effect/commit/83887ca1b1793916913d8550a4db4450cd14a044), [`5266b6c`](https://github.com/Effect-TS/effect/commit/5266b6cd86d76c3886da041c8829bca04b1a3110), [`cdead5c`](https://github.com/Effect-TS/effect/commit/cdead5c9cfd54dc6c4f215d9732f654c4a12e991), [`f40da15`](https://github.com/Effect-TS/effect/commit/f40da15fbeb7c491840b8f409d47de79720891c3), [`766a8af`](https://github.com/Effect-TS/effect/commit/766a8af307b414aca3648d91c4eab7493a5ec862)]:\n  - effect@3.8.5\n  - @effect/platform@0.66.3\n  - @effect/platform-node@0.61.4\n  - @effect/schema@0.74.2\n\n## 0.27.3\n\n### Patch Changes\n\n- Updated dependencies []:\n  - @effect/platform-node@0.61.3\n\n## 0.27.2\n\n### Patch Changes\n\n- [#3676](https://github.com/Effect-TS/effect/pull/3676) [`0a68746`](https://github.com/Effect-TS/effect/commit/0a68746c89651c364db2ee8c72dcfe552e1782ea) Thanks @tomglaize! - Add VariantSchema fieldFromKey utility to rename the encoded side of a field by variant.\n\n  Example usage:\n\n  ```ts\n  import { Schema } from \"@effect/schema\"\n  import { VariantSchema } from \"@effect/experimental\"\n\n  const { Class, fieldFromKey } = VariantSchema.make({\n    variants: [\"domain\", \"json\"],\n    defaultVariant: \"domain\"\n  })\n\n  class User extends Class<User>(\"User\")({\n    id: Schema.Int,\n    firstName: Schema.String.pipe(fieldFromKey({ json: \"first_name\" }))\n  }) {}\n\n  console.log(\n    Schema.encodeSync(User.json)({\n      id: 1,\n      firstName: \"Bob\"\n    })\n  )\n  /*\n  { id: 1, first_name: 'Bob' }\n  */\n  ```\n\n- Updated dependencies [[`734eae6`](https://github.com/Effect-TS/effect/commit/734eae654f215e4adca457d04d2a1728b1a55c83), [`fd83d0e`](https://github.com/Effect-TS/effect/commit/fd83d0e548feff9ea2d53d370a0b626c4a1d940e), [`4509656`](https://github.com/Effect-TS/effect/commit/45096569d50262275ee984f44c456f5c83b62683), [`ad7e1de`](https://github.com/Effect-TS/effect/commit/ad7e1de948745c0751bfdac96671028ff4b7a727), [`090e41c`](https://github.com/Effect-TS/effect/commit/090e41c636d720b1c7d89684a739855765ed4382), [`090e41c`](https://github.com/Effect-TS/effect/commit/090e41c636d720b1c7d89684a739855765ed4382)]:\n  - @effect/schema@0.74.1\n  - @effect/platform@0.66.2\n  - effect@3.8.4\n  - @effect/platform-node@0.61.2\n\n## 0.27.1\n\n### Patch Changes\n\n- Updated dependencies [[`3812788`](https://github.com/Effect-TS/effect/commit/3812788d79caaab8f559a62fd443018a04ac5647)]:\n  - @effect/platform@0.66.1\n  - @effect/platform-node@0.61.1\n\n## 0.27.0\n\n### Patch Changes\n\n- Updated dependencies [[`de48aa5`](https://github.com/Effect-TS/effect/commit/de48aa54e98d97722a8a4c2c8f9e1fe1d4560ea2)]:\n  - @effect/schema@0.74.0\n  - @effect/platform-node@0.61.0\n  - @effect/platform@0.66.0\n\n## 0.26.6\n\n### Patch Changes\n\n- Updated dependencies [[`321b201`](https://github.com/Effect-TS/effect/commit/321b201adcb6bbbeb806b3467dd0b4cf063ccda8), [`bb5ec6b`](https://github.com/Effect-TS/effect/commit/bb5ec6b4b6a6f537394596c5a596faf52cb2aef4)]:\n  - @effect/platform@0.65.5\n  - effect@3.8.3\n  - @effect/platform-node@0.60.5\n  - @effect/schema@0.73.4\n\n## 0.26.5\n\n### Patch Changes\n\n- Updated dependencies [[`e6440a7`](https://github.com/Effect-TS/effect/commit/e6440a74fb3f12f6422ed794c07cb44af91cbacc)]:\n  - @effect/schema@0.73.3\n  - @effect/platform@0.65.4\n  - @effect/platform-node@0.60.4\n\n## 0.26.4\n\n### Patch Changes\n\n- [#3632](https://github.com/Effect-TS/effect/pull/3632) [`b86b47d`](https://github.com/Effect-TS/effect/commit/b86b47d57ca30e1c3587a134a4c79aaf7bfa8980) Thanks @tim-smart! - fix assignability of ChannelSchema apis\n\n## 0.26.3\n\n### Patch Changes\n\n- Updated dependencies [[`f0d8ef1`](https://github.com/Effect-TS/effect/commit/f0d8ef1ce97ec2a87b09b3e24150cfeab85d6e2f)]:\n  - effect@3.8.2\n  - @effect/platform@0.65.3\n  - @effect/platform-node@0.60.3\n  - @effect/schema@0.73.2\n\n## 0.26.2\n\n### Patch Changes\n\n- Updated dependencies [[`10bf621`](https://github.com/Effect-TS/effect/commit/10bf6213f36d8ddb00f058a4609b85220f3d8334), [`f56ab78`](https://github.com/Effect-TS/effect/commit/f56ab785cbee0c1c43bd2c182c35602f486f61f0), [`ae36fa6`](https://github.com/Effect-TS/effect/commit/ae36fa68f754eeab9a54b6dc0f8b44db513aa2b6)]:\n  - effect@3.8.1\n  - @effect/schema@0.73.1\n  - @effect/platform@0.65.2\n  - @effect/platform-node@0.60.2\n\n## 0.26.1\n\n### Patch Changes\n\n- Updated dependencies [[`e44c5f2`](https://github.com/Effect-TS/effect/commit/e44c5f228215738fe4e75023c7461bf9521249cb)]:\n  - @effect/platform@0.65.1\n  - @effect/platform-node@0.60.1\n\n## 0.26.0\n\n### Patch Changes\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`f1b5b3c`](https://github.com/Effect-TS/effect/commit/f1b5b3c36230f177cf01f1b5a5e9a06b8039e9ed) Thanks @tim-smart! - add string variants to Ndjson apis\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`f1b5b3c`](https://github.com/Effect-TS/effect/commit/f1b5b3c36230f177cf01f1b5a5e9a06b8039e9ed) Thanks @tim-smart! - make sure DevTools sends final messsages\n\n- Updated dependencies [[`fcfa6ee`](https://github.com/Effect-TS/effect/commit/fcfa6ee30ffd07d998bf22799357bf58580a116f), [`bb9931b`](https://github.com/Effect-TS/effect/commit/bb9931b62e249a3b801f2cb9d097aec0c8511af7), [`5798f76`](https://github.com/Effect-TS/effect/commit/5798f7619529de33e5ba06f551806f68fedc19db), [`5f0bfa1`](https://github.com/Effect-TS/effect/commit/5f0bfa17205398d4e4818bfbcf9e1b505b3b1fc5), [`7fdf9d9`](https://github.com/Effect-TS/effect/commit/7fdf9d9aa1e2c1c125cbf87991e6efbf4abb7b07), [`812a4e8`](https://github.com/Effect-TS/effect/commit/812a4e86e2d1aa23b477ef5829aa0e5c07784936), [`6a128f6`](https://github.com/Effect-TS/effect/commit/6a128f63f9b41fec2db70790b3bbb96cb9afa1ab), [`273565e`](https://github.com/Effect-TS/effect/commit/273565e7901639e8d0541930ab715aea9c80fbaa), [`adf7d7a`](https://github.com/Effect-TS/effect/commit/adf7d7a7dfce3a7021e9f3b0d847dc85be89d754), [`569a801`](https://github.com/Effect-TS/effect/commit/569a8017ef0a0bc203e4312867cbdd37b0effbd7), [`aa1fa53`](https://github.com/Effect-TS/effect/commit/aa1fa5301e886b9657c8eb0d38cb87cef92a8305), [`02f6b06`](https://github.com/Effect-TS/effect/commit/02f6b0660e12bee1069532a9cc18d3ab855257be), [`12b893e`](https://github.com/Effect-TS/effect/commit/12b893e63cc6dfada4aca7773b4783940e2edf25), [`bbad27e`](https://github.com/Effect-TS/effect/commit/bbad27ec0a90860593f759405caa877e7f4a655f), [`7041393`](https://github.com/Effect-TS/effect/commit/7041393cff132e96566d3f36da0483a6ff6195e4), [`e0d21a5`](https://github.com/Effect-TS/effect/commit/e0d21a54c8323728fbb75a32f4820a9996257809), [`adf7d7a`](https://github.com/Effect-TS/effect/commit/adf7d7a7dfce3a7021e9f3b0d847dc85be89d754), [`007289a`](https://github.com/Effect-TS/effect/commit/007289a52d5877f8e90e2dacf38171ff9bf603fd), [`42a8f99`](https://github.com/Effect-TS/effect/commit/42a8f99740eefdaf2c4544d2c345313f97547a36), [`eebfd29`](https://github.com/Effect-TS/effect/commit/eebfd29633fd5d38b505c5c0842036f61f05e913), [`040703d`](https://github.com/Effect-TS/effect/commit/040703d0e100cd5511e52d812c15492414262b5e)]:\n  - effect@3.8.0\n  - @effect/schema@0.73.0\n  - @effect/platform@0.65.0\n  - @effect/platform-node@0.60.0\n\n## 0.25.2\n\n### Patch Changes\n\n- Updated dependencies [[`35a0f81`](https://github.com/Effect-TS/effect/commit/35a0f813141652d696461cd5d19fd146adaf85be), [`8261c5a`](https://github.com/Effect-TS/effect/commit/8261c5ae6fe86872292ec1fc1a58ab9cea2f5f51)]:\n  - effect@3.7.3\n  - @effect/platform@0.64.1\n  - @effect/platform-node@0.59.1\n  - @effect/schema@0.72.4\n\n## 0.25.1\n\n### Patch Changes\n\n- [#3574](https://github.com/Effect-TS/effect/pull/3574) [`ce86193`](https://github.com/Effect-TS/effect/commit/ce86193546fd4cf5682df6cef0ab1d486136cc15) Thanks @tim-smart! - fix VariantSchema variant validation\n\n## 0.25.0\n\n### Patch Changes\n\n- Updated dependencies [[`f6acb71`](https://github.com/Effect-TS/effect/commit/f6acb71b17a0e6b0d449e7f661c9e2c3d335fcac), [`90ac8f6`](https://github.com/Effect-TS/effect/commit/90ac8f6f6053a2e4498f8b0cc56fe12777d02e1a), [`90ac8f6`](https://github.com/Effect-TS/effect/commit/90ac8f6f6053a2e4498f8b0cc56fe12777d02e1a), [`3791e24`](https://github.com/Effect-TS/effect/commit/3791e241636b1dfe924a56f380ebc9a7ff0827a9), [`3791e24`](https://github.com/Effect-TS/effect/commit/3791e241636b1dfe924a56f380ebc9a7ff0827a9)]:\n  - @effect/schema@0.72.3\n  - @effect/platform-node@0.59.0\n  - @effect/platform@0.64.0\n\n## 0.24.4\n\n### Patch Changes\n\n- [#3557](https://github.com/Effect-TS/effect/pull/3557) [`c969f74`](https://github.com/Effect-TS/effect/commit/c969f74f6111e852fc55c126d2ee384cba718878) Thanks @tim-smart! - add ChannelSchema module to /experimental, for integrating /schema with Channels\n\n## 0.24.3\n\n### Patch Changes\n\n- Updated dependencies [[`4a701c4`](https://github.com/Effect-TS/effect/commit/4a701c406da032563fedae459536c00ae5cfe3c7)]:\n  - @effect/platform@0.63.3\n  - @effect/platform-node@0.58.3\n\n## 0.24.2\n\n### Patch Changes\n\n- Updated dependencies [[`8a601d7`](https://github.com/Effect-TS/effect/commit/8a601d7a1f8ffe52ac9e6d67e9282a1495fe59c9), [`353ba19`](https://github.com/Effect-TS/effect/commit/353ba19f9b2b9e959f0a00d058c6d40a4bc02db7)]:\n  - effect@3.7.2\n  - @effect/platform@0.63.2\n  - @effect/platform-node@0.58.2\n  - @effect/schema@0.72.2\n\n## 0.24.1\n\n### Patch Changes\n\n- Updated dependencies [[`79859e7`](https://github.com/Effect-TS/effect/commit/79859e71040d8edf1868b8530b90c650f4321eff), [`f6a469c`](https://github.com/Effect-TS/effect/commit/f6a469c190b9f00eee5ea0cd4d5912a0ef8b46f5), [`dcb9ec0`](https://github.com/Effect-TS/effect/commit/dcb9ec0db443894dd204d87450f779c44b9ad7f1), [`79aa6b1`](https://github.com/Effect-TS/effect/commit/79aa6b136e1f29b36f34e88cb2ff162bff2bb4ed)]:\n  - effect@3.7.1\n  - @effect/platform@0.63.1\n  - @effect/platform-node@0.58.1\n  - @effect/schema@0.72.1\n\n## 0.24.0\n\n### Patch Changes\n\n- Updated dependencies [[`db89601`](https://github.com/Effect-TS/effect/commit/db89601ee9c1050c4e762b7bd7ec65a6a2799dfe), [`2f456cc`](https://github.com/Effect-TS/effect/commit/2f456cce5012b9fcb6b4e039190d527813b75b92), [`8745e41`](https://github.com/Effect-TS/effect/commit/8745e41ed96e3765dc6048efc2a9afbe05c8a1e9), [`e557838`](https://github.com/Effect-TS/effect/commit/e55783886b046d3c5f33447f455f9ccf2fa75922), [`d6e7e40`](https://github.com/Effect-TS/effect/commit/d6e7e40b1e2ad0c59aa02f07344d28601b14ebdc), [`8356321`](https://github.com/Effect-TS/effect/commit/8356321598da04bd77c1001f45a4e447bec5591d), [`192f2eb`](https://github.com/Effect-TS/effect/commit/192f2ebb2c4ddbf4bfd8baedd32140b2376868f4), [`718cb70`](https://github.com/Effect-TS/effect/commit/718cb70038629a6d58d02e407760e341f7c94474), [`e9d0310`](https://github.com/Effect-TS/effect/commit/e9d03107acbf204d9304f3e8aea0816b7d3c7dfb), [`6bf28f7`](https://github.com/Effect-TS/effect/commit/6bf28f7e3b1e5e0608ff567205fea0581d11666f)]:\n  - effect@3.7.0\n  - @effect/platform@0.63.0\n  - @effect/platform-node@0.58.0\n  - @effect/schema@0.72.0\n\n## 0.23.7\n\n### Patch Changes\n\n- Updated dependencies [[`e809286`](https://github.com/Effect-TS/effect/commit/e8092865900608c4df7a6b7991b1c13cc1e4ca2d)]:\n  - effect@3.6.8\n  - @effect/platform@0.62.5\n  - @effect/platform-node@0.57.5\n  - @effect/schema@0.71.4\n\n## 0.23.6\n\n### Patch Changes\n\n- Updated dependencies [[`e7a65e3`](https://github.com/Effect-TS/effect/commit/e7a65e3c6a08636bbfce3d3af3098bf28474364d), [`50ec889`](https://github.com/Effect-TS/effect/commit/50ec8897a49b7d1fe84f63107f89d543c52f3dfc)]:\n  - @effect/platform@0.62.4\n  - effect@3.6.7\n  - @effect/platform-node@0.57.4\n  - @effect/schema@0.71.3\n\n## 0.23.5\n\n### Patch Changes\n\n- Updated dependencies [[`f960bf4`](https://github.com/Effect-TS/effect/commit/f960bf45239e9badac6e0ad3a602f4174cd7bbdf), [`46a575f`](https://github.com/Effect-TS/effect/commit/46a575f48a05457b782fb21f7827d338c9b59320)]:\n  - effect@3.6.6\n  - @effect/platform@0.62.3\n  - @effect/platform-node@0.57.3\n  - @effect/schema@0.71.2\n\n## 0.23.4\n\n### Patch Changes\n\n- [#3487](https://github.com/Effect-TS/effect/pull/3487) [`00670d0`](https://github.com/Effect-TS/effect/commit/00670d0f8dfda42150c640e3e949e1f8ad3bdaed) Thanks @tim-smart! - ensure VariantSchema preserves opaque types\n\n- [#3488](https://github.com/Effect-TS/effect/pull/3488) [`8dd3959`](https://github.com/Effect-TS/effect/commit/8dd3959e967ca2b38ba601d94a80f1c50e9445e0) Thanks @tim-smart! - move VariantSchema.extract to factory, and copy type level behaviour\n\n- [#3482](https://github.com/Effect-TS/effect/pull/3482) [`dba570a`](https://github.com/Effect-TS/effect/commit/dba570a8e9554958626e5a8ec9ca556345b1bfd2) Thanks @tim-smart! - make VariantSchema constructor apis internal\n\n- [#3493](https://github.com/Effect-TS/effect/pull/3493) [`f2c8dbb`](https://github.com/Effect-TS/effect/commit/f2c8dbb77e196c9a36cb3bf2ae3b82ce68e9874d) Thanks @tim-smart! - add VariantSchema.Union constructor\n\n- [#3478](https://github.com/Effect-TS/effect/pull/3478) [`da52556`](https://github.com/Effect-TS/effect/commit/da52556cfe5a3b35d21563dfdbdde2146d74d3e1) Thanks @tim-smart! - Add VariantSchema.fieldEvolve api\n\n- Updated dependencies [[`413994c`](https://github.com/Effect-TS/effect/commit/413994c9792f16d9d57cca3ae6eb254bf93bd261), [`14a47a8`](https://github.com/Effect-TS/effect/commit/14a47a8c1f3cff2186b8fe7a919a1d773888fb5b), [`0c09841`](https://github.com/Effect-TS/effect/commit/0c0984173be3d58f050b300a1a8aa89d76ba49ae)]:\n  - @effect/platform@0.62.2\n  - effect@3.6.5\n  - @effect/platform-node@0.57.2\n  - @effect/schema@0.71.1\n\n## 0.23.3\n\n### Patch Changes\n\n- [#3471](https://github.com/Effect-TS/effect/pull/3471) [`c3446d3`](https://github.com/Effect-TS/effect/commit/c3446d3e57b0cbfe9341d6f2aebf5f5d6fefefe3) Thanks @tim-smart! - add VariantSchema.Overrideable, for creating fields with optional defaults\n\n- Updated dependencies [[`9efe0e5`](https://github.com/Effect-TS/effect/commit/9efe0e5b57ac557399be620822c21cc6e9add285)]:\n  - @effect/platform@0.62.1\n  - @effect/platform-node@0.57.1\n\n## 0.23.2\n\n### Patch Changes\n\n- [#3467](https://github.com/Effect-TS/effect/pull/3467) [`cfcfbdf`](https://github.com/Effect-TS/effect/commit/cfcfbdfe586b011a5edc28083fd5391edeee0023) Thanks @tim-smart! - add VariantSchema.fields for accessing the fields\n\n## 0.23.1\n\n### Patch Changes\n\n- [#3455](https://github.com/Effect-TS/effect/pull/3455) [`e9da539`](https://github.com/Effect-TS/effect/commit/e9da5396bba99b2ddc20c97c7955154e6da4cab5) Thanks @tim-smart! - add VariantSchema module to experimental\n\n  The `VariantSchema` module can be used to schemas with multiple variants.\n\n  ```ts\n  import { VariantSchema } from \"@effect/experimental\"\n  import { Schema } from \"@effect/schema\"\n  import { DateTime } from \"effect\"\n\n  export const { Class, Field, Struct } = VariantSchema.factory({\n    variants: [\"database\", \"api\"],\n    defaultVariant: \"database\"\n  })\n\n  class User extends Class<User>(\"User\")({\n    id: Schema.Number,\n    createdAt: Field({\n      database: Schema.DateTimeUtc.pipe(\n        Schema.optionalWith({ default: DateTime.unsafeNow })\n      ),\n      api: Schema.DateTimeUtc\n    }),\n    updateAt: Field({\n      database: Schema.DateTimeUtc.pipe(\n        Schema.optionalWith({ default: DateTime.unsafeNow })\n      ),\n      api: Schema.DateTimeUtc\n    })\n  }) {}\n\n  // the class will use the `defaultVariant` fields\n  const user = new User({ id: 1 })\n  user.createdAt\n  user.updateAt\n\n  // access the `Schema.Struct` variants as static props\n  User.database\n  User.api\n  ```\n\n## 0.23.0\n\n### Patch Changes\n\n- [#3450](https://github.com/Effect-TS/effect/pull/3450) [`0e42a8f`](https://github.com/Effect-TS/effect/commit/0e42a8f045ecb1fd3d080edf3d49fef16a9b0ca1) Thanks @tim-smart! - update dependencies\n\n- Updated dependencies [[`c1987e2`](https://github.com/Effect-TS/effect/commit/c1987e25c8f5c48bdc9ad223d7a6f2c32f93f5a1), [`8295281`](https://github.com/Effect-TS/effect/commit/8295281ae9bd7441e680402540bf3c8682ec417b), [`c940df6`](https://github.com/Effect-TS/effect/commit/c940df63800bf3c4396d91cf28ec34938642fd2c), [`00b6c6d`](https://github.com/Effect-TS/effect/commit/00b6c6d4001f5de728b7d990a1b14560b4961a63), [`1ceed14`](https://github.com/Effect-TS/effect/commit/1ceed149dc64f4874e64b5cf2f954eba0a5a1f12), [`f8d95a6`](https://github.com/Effect-TS/effect/commit/f8d95a61ad0762147933c5c32bb6d7237e18eef4), [`0e42a8f`](https://github.com/Effect-TS/effect/commit/0e42a8f045ecb1fd3d080edf3d49fef16a9b0ca1)]:\n  - @effect/schema@0.71.0\n  - effect@3.6.4\n  - @effect/platform@0.62.0\n  - @effect/platform-node@0.57.0\n\n## 0.22.6\n\n### Patch Changes\n\n- Updated dependencies [[`04adcac`](https://github.com/Effect-TS/effect/commit/04adcace913e6fc483df266874a68005e9e04ccf)]:\n  - effect@3.6.3\n  - @effect/platform@0.61.8\n  - @effect/platform-node@0.56.9\n  - @effect/schema@0.70.4\n\n## 0.22.5\n\n### Patch Changes\n\n- Updated dependencies [[`17245a4`](https://github.com/Effect-TS/effect/commit/17245a4e783c19dee51529600b3b40f164fa59bc), [`630d40e`](https://github.com/Effect-TS/effect/commit/630d40eaa7eb4d2f8b6705b16d4f426bc28a7d09), [`630d40e`](https://github.com/Effect-TS/effect/commit/630d40eaa7eb4d2f8b6705b16d4f426bc28a7d09)]:\n  - @effect/platform@0.61.7\n  - @effect/platform-node@0.56.8\n\n## 0.22.4\n\n### Patch Changes\n\n- Updated dependencies [[`99ad841`](https://github.com/Effect-TS/effect/commit/99ad8415293a82d08bd7043c563b29e2b468ca74), [`d829b57`](https://github.com/Effect-TS/effect/commit/d829b576357f2e3b203ab7e107a1492de903a106), [`fd4b2f6`](https://github.com/Effect-TS/effect/commit/fd4b2f6516b325740dde615f1cf0229edf13ca0c)]:\n  - @effect/schema@0.70.3\n  - @effect/platform@0.61.6\n  - effect@3.6.2\n  - @effect/platform-node@0.56.7\n\n## 0.22.3\n\n### Patch Changes\n\n- Updated dependencies [[`76b0496`](https://github.com/Effect-TS/effect/commit/76b0496ff9d7670e3f4c07ae924d30ed7f613cee)]:\n  - @effect/platform-node@0.56.6\n\n## 0.22.2\n\n### Patch Changes\n\n- Updated dependencies [[`056b710`](https://github.com/Effect-TS/effect/commit/056b7108978e70612176c23991916f678d947f38), [`056b710`](https://github.com/Effect-TS/effect/commit/056b7108978e70612176c23991916f678d947f38)]:\n  - @effect/platform-node@0.56.5\n  - @effect/platform@0.61.5\n\n## 0.22.1\n\n### Patch Changes\n\n- [#3420](https://github.com/Effect-TS/effect/pull/3420) [`fb18738`](https://github.com/Effect-TS/effect/commit/fb18738e7f0586eec2b3e658c94c3fd932e70427) Thanks @tim-smart! - properly interrupt DevTools client during finalization\n\n## 0.22.0\n\n### Minor Changes\n\n- [#3417](https://github.com/Effect-TS/effect/pull/3417) [`5b0a98d`](https://github.com/Effect-TS/effect/commit/5b0a98de7998a8a22b54e5e6bd8d0e1ab988a0e7) Thanks @tim-smart! - remove TimeToLive trait in favour of `timeToLive` options\n\n## 0.21.4\n\n### Patch Changes\n\n- Updated dependencies [[`e7cb109`](https://github.com/Effect-TS/effect/commit/e7cb109d0754207024a64d55b6bd2a674dd8ed7d)]:\n  - @effect/platform@0.61.4\n  - @effect/platform-node@0.56.4\n\n## 0.21.3\n\n### Patch Changes\n\n- Updated dependencies [[`510a34d`](https://github.com/Effect-TS/effect/commit/510a34d4cc5d2f51347a53847f6c7db84d2b17c6), [`fb9f786`](https://github.com/Effect-TS/effect/commit/fb9f7867f0c895e63f9ef23e8d0941248c42179d), [`45dbb9f`](https://github.com/Effect-TS/effect/commit/45dbb9ffeaf93d9e4df99d0cd4920e41ba9a3978)]:\n  - effect@3.6.1\n  - @effect/platform@0.61.3\n  - @effect/platform-node@0.56.3\n  - @effect/schema@0.70.2\n\n## 0.21.2\n\n### Patch Changes\n\n- [#3394](https://github.com/Effect-TS/effect/pull/3394) [`5c3a4d0`](https://github.com/Effect-TS/effect/commit/5c3a4d005c79efab0be928b22e37f436bc93b2ad) Thanks @tim-smart! - ensure DevTools client is shutdown\n\n- Updated dependencies [[`3dce357`](https://github.com/Effect-TS/effect/commit/3dce357efe4a4451d7d29859d08ac11713999b1a), [`657fc48`](https://github.com/Effect-TS/effect/commit/657fc48bb32daf2dc09c9335b3cbc3152bcbdd3b)]:\n  - @effect/schema@0.70.1\n  - @effect/platform@0.61.2\n  - @effect/platform-node@0.56.2\n\n## 0.21.1\n\n### Patch Changes\n\n- Updated dependencies [[`11223bf`](https://github.com/Effect-TS/effect/commit/11223bf9cbf5b822e0bf9a9fb2b35b2ad88af692)]:\n  - @effect/platform@0.61.1\n  - @effect/platform-node@0.56.1\n\n## 0.21.0\n\n### Patch Changes\n\n- Updated dependencies [[`1e0fe80`](https://github.com/Effect-TS/effect/commit/1e0fe802b36c257971296617473ce0abe730e8dc), [`8135294`](https://github.com/Effect-TS/effect/commit/8135294b591ea94fde7e6f94a504608f0e630520), [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987), [`3845646`](https://github.com/Effect-TS/effect/commit/3845646828e98f3c7cda1217f6cfe5f642ac0603), [`2d09078`](https://github.com/Effect-TS/effect/commit/2d09078c5948b37fc2f79ef858fe4ca3e4814085), [`4bce5a0`](https://github.com/Effect-TS/effect/commit/4bce5a0274203550ccf117d830721891b0a3d182), [`4ddbff0`](https://github.com/Effect-TS/effect/commit/4ddbff0bb4e3ffddfeb509c59835b83245fb975e), [`e74cc38`](https://github.com/Effect-TS/effect/commit/e74cc38cb420a320c4d7ef98180f19d452a8b316), [`bb069b4`](https://github.com/Effect-TS/effect/commit/bb069b49ef291c532a02c1e8e74271f6d1bb32ec), [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987), [`7d02174`](https://github.com/Effect-TS/effect/commit/7d02174af3bcbf054e5cdddb821c91d0f47e8285)]:\n  - effect@3.6.0\n  - @effect/schema@0.70.0\n  - @effect/platform@0.61.0\n  - @effect/platform-node@0.56.0\n\n## 0.20.4\n\n### Patch Changes\n\n- Updated dependencies [[`7c0da50`](https://github.com/Effect-TS/effect/commit/7c0da5050d30cb804f4eacb15995d0fb7f3a28d2), [`2fc0ff4`](https://github.com/Effect-TS/effect/commit/2fc0ff4c59c25977018f6ac70ced99b04a8c7b2b), [`6359644`](https://github.com/Effect-TS/effect/commit/635964446323cf55d4060559337e710e4a24496e), [`f262665`](https://github.com/Effect-TS/effect/commit/f262665c2773492c01e5dd0e8d6db235aafaaad8), [`7f41e42`](https://github.com/Effect-TS/effect/commit/7f41e428830bf3043b8be0d28dcd235d5747c942), [`9bbe7a6`](https://github.com/Effect-TS/effect/commit/9bbe7a681430ebf5c10167bb7140ba3742e46bb7), [`f566fd1`](https://github.com/Effect-TS/effect/commit/f566fd1d7eea531a0d981dd24037f14a603a1273)]:\n  - @effect/schema@0.69.3\n  - effect@3.5.9\n  - @effect/platform@0.60.3\n  - @effect/platform-node@0.55.3\n\n## 0.20.3\n\n### Patch Changes\n\n- Updated dependencies [[`eb4d014`](https://github.com/Effect-TS/effect/commit/eb4d014c559e1b4c95b3fb9295fe77593c17ed7a), [`1ba640c`](https://github.com/Effect-TS/effect/commit/1ba640c702f187a866023bf043c26e25cce941ef), [`c8c71bd`](https://github.com/Effect-TS/effect/commit/c8c71bd20eb87d23133dac6156b83bb08941597c), [`a26ce58`](https://github.com/Effect-TS/effect/commit/a26ce581ca7d407e1e81439b58c8045b3fa65231), [`fc20f73`](https://github.com/Effect-TS/effect/commit/fc20f73c69e577981cb64714de2adc97e1004dae)]:\n  - @effect/platform@0.60.2\n  - effect@3.5.8\n  - @effect/platform-node@0.55.2\n  - @effect/schema@0.69.2\n\n## 0.20.2\n\n### Patch Changes\n\n- Updated dependencies [[`f241154`](https://github.com/Effect-TS/effect/commit/f241154added5d91e95866c39481f09cdb13bd4d)]:\n  - @effect/schema@0.69.1\n  - @effect/platform@0.60.1\n  - @effect/platform-node@0.55.1\n\n## 0.20.1\n\n### Patch Changes\n\n- [#3325](https://github.com/Effect-TS/effect/pull/3325) [`b2b02cb`](https://github.com/Effect-TS/effect/commit/b2b02cbd0268478e856b0976aa4aa20f6918171f) Thanks @IMax153! - ensure `DevTools` client flushes requests on interrupt\n\n## 0.20.0\n\n### Patch Changes\n\n- Updated dependencies [[`20807a4`](https://github.com/Effect-TS/effect/commit/20807a45edeb4334e903dca5d708cd62a71702d8)]:\n  - @effect/schema@0.69.0\n  - @effect/platform@0.60.0\n  - @effect/platform-node@0.55.0\n\n## 0.19.4\n\n### Patch Changes\n\n- [#3310](https://github.com/Effect-TS/effect/pull/3310) [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc) Thanks @fubhy! - Added additional pure annotations to improve tree-shakeability\n\n- Updated dependencies [[`3afcc93`](https://github.com/Effect-TS/effect/commit/3afcc93413a3d910beb69e4ce9ae120e4adaffd5), [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc), [`6921c4f`](https://github.com/Effect-TS/effect/commit/6921c4fb8c45badff09b493043b85ca71302b560)]:\n  - effect@3.5.7\n  - @effect/platform@0.59.3\n  - @effect/platform-node@0.54.4\n  - @effect/schema@0.68.27\n\n## 0.19.3\n\n### Patch Changes\n\n- Updated dependencies [[`f0285d3`](https://github.com/Effect-TS/effect/commit/f0285d3af6a18829123bc1818331c67206becbc4), [`8ec4955`](https://github.com/Effect-TS/effect/commit/8ec49555ed3b3c98093fa4d135a4c57a3f16ebd1), [`3ac2d76`](https://github.com/Effect-TS/effect/commit/3ac2d76048da09e876cf6c3aee3397febd843fe9), [`cc327a1`](https://github.com/Effect-TS/effect/commit/cc327a1bccd22a4ee27ec7e58b53205e93b23e2c), [`4bfe4fb`](https://github.com/Effect-TS/effect/commit/4bfe4fb5c82f597c9beea9baa92e772593598b60), [`2b14d18`](https://github.com/Effect-TS/effect/commit/2b14d181462cad8359da4fa6bc6dfda0f742c398)]:\n  - @effect/schema@0.68.26\n  - effect@3.5.6\n  - @effect/platform@0.59.2\n  - @effect/platform-node@0.54.3\n\n## 0.19.2\n\n### Patch Changes\n\n- Updated dependencies [[`a9d7800`](https://github.com/Effect-TS/effect/commit/a9d7800f6a253192b653d77778b0674f39b1ca39), [`fcecff7`](https://github.com/Effect-TS/effect/commit/fcecff7f7e12b295a252f124861b801c73072151), [`adbf753`](https://github.com/Effect-TS/effect/commit/adbf75340a9db15dc5cadc66e911a8978a195a65), [`adbf753`](https://github.com/Effect-TS/effect/commit/adbf75340a9db15dc5cadc66e911a8978a195a65)]:\n  - effect@3.5.5\n  - @effect/platform@0.59.1\n  - @effect/platform-node@0.54.2\n  - @effect/schema@0.68.25\n\n## 0.19.1\n\n### Patch Changes\n\n- Updated dependencies [[`07db4ac`](https://github.com/Effect-TS/effect/commit/07db4ac8da9d07ce31bd62470a73e362a4291a0c)]:\n  - @effect/platform-node@0.54.1\n\n## 0.19.0\n\n### Minor Changes\n\n- [#3260](https://github.com/Effect-TS/effect/pull/3260) [`53c0db0`](https://github.com/Effect-TS/effect/commit/53c0db06872d5b5edea2a706e83249908385325c) Thanks @tim-smart! - replace /platform RefailError with use of the \"cause\" property\n\n### Patch Changes\n\n- [#3253](https://github.com/Effect-TS/effect/pull/3253) [`ed0dde4`](https://github.com/Effect-TS/effect/commit/ed0dde4888e6f1a97ad5bba06b755d26a6a1c52e) Thanks @tim-smart! - update dependencies\n\n- [#3259](https://github.com/Effect-TS/effect/pull/3259) [`5be9cc0`](https://github.com/Effect-TS/effect/commit/5be9cc044025a9541b9b7acefa2d3fc05fa1301b) Thanks @IMax153! - allow unpacking newline delimited JSON to ignore empty lines\n\n- Updated dependencies [[`53c0db0`](https://github.com/Effect-TS/effect/commit/53c0db06872d5b5edea2a706e83249908385325c), [`ed0dde4`](https://github.com/Effect-TS/effect/commit/ed0dde4888e6f1a97ad5bba06b755d26a6a1c52e), [`ada68b3`](https://github.com/Effect-TS/effect/commit/ada68b3e61c67907c2a281c024c84d818186ca4c), [`ca775ce`](https://github.com/Effect-TS/effect/commit/ca775cec53baebc1a43d9b8852a3ac6726178498), [`5be9cc0`](https://github.com/Effect-TS/effect/commit/5be9cc044025a9541b9b7acefa2d3fc05fa1301b), [`203658f`](https://github.com/Effect-TS/effect/commit/203658f8001c132b25764ab70344b171683b554c), [`eb1c4d4`](https://github.com/Effect-TS/effect/commit/eb1c4d44e54b9d8d201a366d1ff94face2a6dcd3)]:\n  - @effect/platform-node@0.54.0\n  - @effect/platform@0.59.0\n  - effect@3.5.4\n  - @effect/schema@0.68.24\n\n## 0.18.1\n\n### Patch Changes\n\n- Updated dependencies [[`edb0da3`](https://github.com/Effect-TS/effect/commit/edb0da383746d760f35d8582f5fb0cc0eeca9217), [`edb0da3`](https://github.com/Effect-TS/effect/commit/edb0da383746d760f35d8582f5fb0cc0eeca9217), [`a1db40a`](https://github.com/Effect-TS/effect/commit/a1db40a650ab842e778654f0d88e80f2ef4fd6f3), [`c8d3fb0`](https://github.com/Effect-TS/effect/commit/c8d3fb0fe23585f6efb724af51fbab3ba1ad6e83), [`dabd028`](https://github.com/Effect-TS/effect/commit/dabd028decf9b7983ca16ebe0f48c05c11a84b68), [`786b2ab`](https://github.com/Effect-TS/effect/commit/786b2ab29d525c877bb84035dac9e2d6499339d1), [`fc57354`](https://github.com/Effect-TS/effect/commit/fc573547d41667016fce05eaee75960fcc6dce4d)]:\n  - effect@3.5.3\n  - @effect/schema@0.68.23\n  - @effect/platform@0.58.27\n  - @effect/platform-node@0.53.26\n\n## 0.18.0\n\n### Minor Changes\n\n- [#3233](https://github.com/Effect-TS/effect/pull/3233) [`cb9f8a1`](https://github.com/Effect-TS/effect/commit/cb9f8a1ef656170a79bccdb73e4588ab4243b287) Thanks @tim-smart! - revert PrimaryKey fallback in /experimental Persistence\n\n### Patch Changes\n\n- Updated dependencies [[`639208e`](https://github.com/Effect-TS/effect/commit/639208eeb8a44622994f832bc2d45d06ab636bc8), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5)]:\n  - effect@3.5.2\n  - @effect/platform@0.58.26\n  - @effect/platform-node@0.53.25\n  - @effect/schema@0.68.22\n\n## 0.17.27\n\n### Patch Changes\n\n- Updated dependencies [[`0623fca`](https://github.com/Effect-TS/effect/commit/0623fca41679b0e3c5a10dd0f8985f91670bd721)]:\n  - @effect/platform@0.58.25\n  - @effect/platform-node@0.53.24\n\n## 0.17.26\n\n### Patch Changes\n\n- Updated dependencies [[`55fdd76`](https://github.com/Effect-TS/effect/commit/55fdd761ee95afd73b6a892c13fee92b36c02837)]:\n  - effect@3.5.1\n  - @effect/platform@0.58.24\n  - @effect/platform-node@0.53.23\n  - @effect/schema@0.68.21\n\n## 0.17.25\n\n### Patch Changes\n\n- Updated dependencies [[`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`5ab348f`](https://github.com/Effect-TS/effect/commit/5ab348f265db3d283aa091ddca6d2d49137c16f2), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`3e04bf8`](https://github.com/Effect-TS/effect/commit/3e04bf8a7127e956cadb7684a8f4c661df57663b), [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`4626de5`](https://github.com/Effect-TS/effect/commit/4626de59c25b384216faa0be87bf0b8cd36357d0), [`f01e7db`](https://github.com/Effect-TS/effect/commit/f01e7db317827255d7901f523f2e28b43298e8df), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6), [`ac71f37`](https://github.com/Effect-TS/effect/commit/ac71f378f2413e5aa91c95f649ffe898d6a26114), [`8432360`](https://github.com/Effect-TS/effect/commit/8432360ce68614a419bb328083a4109d0fc8aa93), [`e4bf1bf`](https://github.com/Effect-TS/effect/commit/e4bf1bf2b4a970eacd77c9b77b5ea8c68bc84498), [`13cb861`](https://github.com/Effect-TS/effect/commit/13cb861a5eded15c55c6cdcf6a8acde8320367a6), [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6), [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3), [`9f66825`](https://github.com/Effect-TS/effect/commit/9f66825f1fce0fe8d10420c285f7dc4c71e8af8d)]:\n  - effect@3.5.0\n  - @effect/platform@0.58.23\n  - @effect/platform-node@0.53.22\n  - @effect/schema@0.68.20\n\n## 0.17.24\n\n### Patch Changes\n\n- Updated dependencies [[`7af137c`](https://github.com/Effect-TS/effect/commit/7af137c9433f6e74959b3887561ec1e6f12e10ee), [`ee4b3dc`](https://github.com/Effect-TS/effect/commit/ee4b3dc5f68d19dc3ae1c2d12901c5b8ffbebabb), [`366f2ee`](https://github.com/Effect-TS/effect/commit/366f2ee3fb6f712a44e8f84fc188612e5ecc016d), [`366f2ee`](https://github.com/Effect-TS/effect/commit/366f2ee3fb6f712a44e8f84fc188612e5ecc016d), [`097d25c`](https://github.com/Effect-TS/effect/commit/097d25cb5d13c049e01789651be56b09620186ef)]:\n  - effect@3.4.9\n  - @effect/platform-node@0.53.21\n  - @effect/platform@0.58.22\n  - @effect/schema@0.68.19\n\n## 0.17.23\n\n### Patch Changes\n\n- Updated dependencies [[`5d5cc6c`](https://github.com/Effect-TS/effect/commit/5d5cc6cfd7d63b07081290fb189b364999201fc5), [`a435e0f`](https://github.com/Effect-TS/effect/commit/a435e0fc5378b33a49bcec92ee235df6f16a2419), [`b5554db`](https://github.com/Effect-TS/effect/commit/b5554db36c4dd6f64fa5e6a62a29b2759c54217a), [`359ff8a`](https://github.com/Effect-TS/effect/commit/359ff8aa2e4e6389bf56d759baa804e2a7674a16), [`a9c4fb3`](https://github.com/Effect-TS/effect/commit/a9c4fb3bf3c6e92cd1c142b0605fddf7eb3c697c), [`f7534b9`](https://github.com/Effect-TS/effect/commit/f7534b94cba06b143a3d4f29275d92874a939559)]:\n  - @effect/schema@0.68.18\n  - effect@3.4.8\n  - @effect/platform@0.58.21\n  - @effect/platform-node@0.53.20\n\n## 0.17.22\n\n### Patch Changes\n\n- Updated dependencies [[`15967cf`](https://github.com/Effect-TS/effect/commit/15967cf18931fb6ede3083eb687a8dfff371cc56), [`2328e17`](https://github.com/Effect-TS/effect/commit/2328e17577112db17c29b7756942a0ff64a70ee0), [`a5737d6`](https://github.com/Effect-TS/effect/commit/a5737d6db2b921605c332eabbc5402ee3d17357b)]:\n  - @effect/schema@0.68.17\n  - effect@3.4.7\n  - @effect/platform@0.58.20\n  - @effect/platform-node@0.53.19\n\n## 0.17.21\n\n### Patch Changes\n\n- [#3158](https://github.com/Effect-TS/effect/pull/3158) [`c3e3ed6`](https://github.com/Effect-TS/effect/commit/c3e3ed64911385fdcfb734c5756bcb2f865df147) Thanks @tim-smart! - drop requirement of PrimaryKey in /experimental Persistence\n\n## 0.17.20\n\n### Patch Changes\n\n- [#3150](https://github.com/Effect-TS/effect/pull/3150) [`271ec23`](https://github.com/Effect-TS/effect/commit/271ec23adb09169a054040d2b47cf54564c8283a) Thanks @tim-smart! - remove console.log from Redis persistence\n\n## 0.17.19\n\n### Patch Changes\n\n- [#3149](https://github.com/Effect-TS/effect/pull/3149) [`cb22726`](https://github.com/Effect-TS/effect/commit/cb2272656881aa5878a1c3fc0b12d8fbc66eb63c) Thanks @tim-smart! - add PersistedCache module to /experimental\n\n- Updated dependencies [[`d006cec`](https://github.com/Effect-TS/effect/commit/d006cec022e8524dbfd6dc6df751fe4c86b10042), [`cb22726`](https://github.com/Effect-TS/effect/commit/cb2272656881aa5878a1c3fc0b12d8fbc66eb63c), [`e911cfd`](https://github.com/Effect-TS/effect/commit/e911cfdc79418462d7e9000976fded15ea6b738d)]:\n  - @effect/schema@0.68.16\n  - @effect/platform@0.58.19\n  - @effect/platform-node@0.53.18\n\n## 0.17.18\n\n### Patch Changes\n\n- [#3138](https://github.com/Effect-TS/effect/pull/3138) [`422a2ee`](https://github.com/Effect-TS/effect/commit/422a2ee597320cd8ce4b53fe449a1b73806ebf1a) Thanks @tim-smart! - log DevTool's errors at debug level\n\n- Updated dependencies [[`7f8900a`](https://github.com/Effect-TS/effect/commit/7f8900a1de9addeb0d371103a2c5c2aa3e4ff95e)]:\n  - @effect/platform@0.58.18\n  - @effect/platform-node@0.53.17\n\n## 0.17.17\n\n### Patch Changes\n\n- Updated dependencies [[`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`34faeb6`](https://github.com/Effect-TS/effect/commit/34faeb6305ba52af4d6f8bdd2e633bb6a5a7a35b), [`33735b1`](https://github.com/Effect-TS/effect/commit/33735b16b41bd26929d8f4754c190925db6323b7), [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`139d4b3`](https://github.com/Effect-TS/effect/commit/139d4b39fb3bff2eeaa7c0c809c581da42425a83)]:\n  - effect@3.4.6\n  - @effect/schema@0.68.15\n  - @effect/platform@0.58.17\n  - @effect/platform-node@0.53.16\n\n## 0.17.16\n\n### Patch Changes\n\n- Updated dependencies [[`61e5964`](https://github.com/Effect-TS/effect/commit/61e59640fd993216cca8ace0ac8abd9104e213ce)]:\n  - @effect/schema@0.68.14\n  - @effect/platform@0.58.16\n  - @effect/platform-node@0.53.15\n\n## 0.17.15\n\n### Patch Changes\n\n- Updated dependencies [[`cb76bcb`](https://github.com/Effect-TS/effect/commit/cb76bcb2f8858a90db4f785efee262cea1b9844e), [`baa90df`](https://github.com/Effect-TS/effect/commit/baa90df9663f5f37d7b6814dad25142d53dbc720)]:\n  - @effect/schema@0.68.13\n  - @effect/platform@0.58.15\n  - @effect/platform-node@0.53.14\n\n## 0.17.14\n\n### Patch Changes\n\n- [#3110](https://github.com/Effect-TS/effect/pull/3110) [`296a9e2`](https://github.com/Effect-TS/effect/commit/296a9e24b536678c0623016b1f51653f2f2c4fe8) Thanks @tim-smart! - fix deadlock in @effect/experimental dataLoader\n\n## 0.17.13\n\n### Patch Changes\n\n- Updated dependencies [[`52a87c7`](https://github.com/Effect-TS/effect/commit/52a87c7a0b9536398deaf8ec507e53a82c607219), [`6d2280e`](https://github.com/Effect-TS/effect/commit/6d2280e9497c95cb0e965ca462c825345074eedf)]:\n  - @effect/platform@0.58.14\n  - @effect/platform-node@0.53.13\n\n## 0.17.12\n\n### Patch Changes\n\n- Updated dependencies [[`a047af9`](https://github.com/Effect-TS/effect/commit/a047af99447dfffc729e9c8ef0ca143537927e91), [`dbd53ea`](https://github.com/Effect-TS/effect/commit/dbd53ea363c71a24449cb068251054c3a1acf864), [`d990544`](https://github.com/Effect-TS/effect/commit/d9905444b9e800850cb65899114ca0e502e68fe8)]:\n  - effect@3.4.5\n  - @effect/platform@0.58.13\n  - @effect/schema@0.68.12\n  - @effect/platform-node@0.53.12\n\n## 0.17.11\n\n### Patch Changes\n\n- Updated dependencies [[`74e0ad2`](https://github.com/Effect-TS/effect/commit/74e0ad23b4c36f41b7fd10856b20f8b701bc4044), [`74e0ad2`](https://github.com/Effect-TS/effect/commit/74e0ad23b4c36f41b7fd10856b20f8b701bc4044), [`72638e3`](https://github.com/Effect-TS/effect/commit/72638e3d99f0e93a24febf6c225256ce92d4a20b), [`d7dde2b`](https://github.com/Effect-TS/effect/commit/d7dde2b4af08b37af859d4c327c1f5c6f00cf9d9), [`9b2fc3b`](https://github.com/Effect-TS/effect/commit/9b2fc3b9dfd304a2bd0508ef2313cfc54357be0c), [`d71c192`](https://github.com/Effect-TS/effect/commit/d71c192b89fd1162423acddc5fd3d6270fbf2ef6)]:\n  - @effect/platform@0.58.12\n  - effect@3.4.4\n  - @effect/schema@0.68.11\n  - @effect/platform-node@0.53.11\n\n## 0.17.10\n\n### Patch Changes\n\n- Updated dependencies [[`a5b95b5`](https://github.com/Effect-TS/effect/commit/a5b95b548284e4798654ae7ce6883fa49108f0ea), [`5e29579`](https://github.com/Effect-TS/effect/commit/5e29579187cb8420ea4930b3999fec984f8999f4)]:\n  - @effect/platform@0.58.11\n  - @effect/platform-node@0.53.10\n\n## 0.17.9\n\n### Patch Changes\n\n- [#3079](https://github.com/Effect-TS/effect/pull/3079) [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd) Thanks @tim-smart! - update dependencies\n\n- [#3079](https://github.com/Effect-TS/effect/pull/3079) [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd) Thanks @tim-smart! - update to typescript 5.5\n\n- Updated dependencies [[`a48ee84`](https://github.com/Effect-TS/effect/commit/a48ee845ac21bbde9baf938af9e97a98322211c9), [`c342739`](https://github.com/Effect-TS/effect/commit/c3427396226e1ad7b95b40595a23f9bdff3e3365), [`8898e5e`](https://github.com/Effect-TS/effect/commit/8898e5e238622f6337583d91ee23609c1f5ccdf7), [`a48ee84`](https://github.com/Effect-TS/effect/commit/a48ee845ac21bbde9baf938af9e97a98322211c9), [`a48ee84`](https://github.com/Effect-TS/effect/commit/a48ee845ac21bbde9baf938af9e97a98322211c9), [`ff78636`](https://github.com/Effect-TS/effect/commit/ff786367c522975f40f0f179a0ecdfcfab7ecbdb), [`c86bd4e`](https://github.com/Effect-TS/effect/commit/c86bd4e134c23146c216f9ff97e03781d55991b6), [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd), [`ab3180f`](https://github.com/Effect-TS/effect/commit/ab3180f827041d0ea3b2d72254a1a8683e99e056), [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd)]:\n  - @effect/platform@0.58.10\n  - effect@3.4.3\n  - @effect/platform-node@0.53.9\n  - @effect/schema@0.68.10\n\n## 0.17.8\n\n### Patch Changes\n\n- Updated dependencies [[`0b47fdf`](https://github.com/Effect-TS/effect/commit/0b47fdfe449f42de89e0e88b61ae5140f629e5c4)]:\n  - @effect/schema@0.68.9\n  - @effect/platform@0.58.9\n  - @effect/platform-node@0.53.8\n\n## 0.17.7\n\n### Patch Changes\n\n- Updated dependencies [[`192261b`](https://github.com/Effect-TS/effect/commit/192261b2aec94e9913ceed83683fdcfbc9fca66f), [`3da1497`](https://github.com/Effect-TS/effect/commit/3da1497b5c9cc886d300258bc928fd68a4fefe6f)]:\n  - @effect/schema@0.68.8\n  - effect@3.4.2\n  - @effect/platform@0.58.8\n  - @effect/platform-node@0.53.7\n\n## 0.17.6\n\n### Patch Changes\n\n- Updated dependencies [[`027004a`](https://github.com/Effect-TS/effect/commit/027004a897f654791e75faa28eefb50dd0244b6e)]:\n  - @effect/platform@0.58.7\n  - @effect/platform-node@0.53.6\n\n## 0.17.5\n\n### Patch Changes\n\n- Updated dependencies [[`66a1910`](https://github.com/Effect-TS/effect/commit/66a19109ff90c4252123b8809b8c8a74681dba6a), [`2e8e252`](https://github.com/Effect-TS/effect/commit/2e8e2520cac712f0eb644553bd476429ebd674e4)]:\n  - effect@3.4.1\n  - @effect/platform@0.58.6\n  - @effect/platform-node@0.53.5\n  - @effect/schema@0.68.7\n\n## 0.17.4\n\n### Patch Changes\n\n- Updated dependencies [[`37a07a2`](https://github.com/Effect-TS/effect/commit/37a07a2d8d1ce09ab965c0ada84a3fae9a6aba05)]:\n  - @effect/platform@0.58.5\n  - @effect/platform-node@0.53.4\n\n## 0.17.3\n\n### Patch Changes\n\n- Updated dependencies [[`b77fb0a`](https://github.com/Effect-TS/effect/commit/b77fb0a811ec1ad0e794917077c9a90824515db8)]:\n  - @effect/platform@0.58.4\n  - @effect/platform-node@0.53.3\n\n## 0.17.2\n\n### Patch Changes\n\n- Updated dependencies [[`530fa9e`](https://github.com/Effect-TS/effect/commit/530fa9e36b8532589b948fc4faa37593f36b7f42)]:\n  - @effect/schema@0.68.6\n  - @effect/platform@0.58.3\n  - @effect/platform-node@0.53.2\n\n## 0.17.1\n\n### Patch Changes\n\n- Updated dependencies [[`1d62815`](https://github.com/Effect-TS/effect/commit/1d62815a50f34115606940ffa397442d75a20c81)]:\n  - @effect/schema@0.68.5\n  - @effect/platform@0.58.2\n  - @effect/platform-node@0.53.1\n\n## 0.17.0\n\n### Minor Changes\n\n- [#3036](https://github.com/Effect-TS/effect/pull/3036) [`5a248aa`](https://github.com/Effect-TS/effect/commit/5a248aa5ab2db3f7131ebc79bb9871a76de57973) Thanks @tim-smart! - remove dependency on /platform-node from DevTools\n\n### Patch Changes\n\n- Updated dependencies [[`5a248aa`](https://github.com/Effect-TS/effect/commit/5a248aa5ab2db3f7131ebc79bb9871a76de57973), [`5a248aa`](https://github.com/Effect-TS/effect/commit/5a248aa5ab2db3f7131ebc79bb9871a76de57973)]:\n  - @effect/platform@0.58.1\n  - @effect/platform-node@0.53.0\n\n## 0.16.34\n\n### Patch Changes\n\n- Updated dependencies [[`c0ce180`](https://github.com/Effect-TS/effect/commit/c0ce180861ad0938053c0e6145e813fa6404df3b), [`63dd0c3`](https://github.com/Effect-TS/effect/commit/63dd0c3af45876c1caad7d03356c74daf551c628), [`61707b6`](https://github.com/Effect-TS/effect/commit/61707b6ffc7397c2ba0dce22512b44955724f60f), [`9c1b5b3`](https://github.com/Effect-TS/effect/commit/9c1b5b39e6c19604ce834f072a114ad392c50a06), [`a35faf8`](https://github.com/Effect-TS/effect/commit/a35faf8d116f94899bfc03feab33b004c8ddfdf7), [`ff73c0c`](https://github.com/Effect-TS/effect/commit/ff73c0cacd66132bfad2e5211b3eae347729c667), [`984d516`](https://github.com/Effect-TS/effect/commit/984d516ccd9412dc41188f6a46b748dd20dd5848), [`8c3b8a2`](https://github.com/Effect-TS/effect/commit/8c3b8a2ce208eab753b6206a51605a424f104e98), [`017e2f9`](https://github.com/Effect-TS/effect/commit/017e2f9b371ce24ea4945e5d7390c934ad3c39cf), [`91bf8a2`](https://github.com/Effect-TS/effect/commit/91bf8a2e9d1959393b3cf7366cc1d584d3e666b7), [`c6a4a26`](https://github.com/Effect-TS/effect/commit/c6a4a266606575fd2c7165940c4072ad4c57d01f)]:\n  - effect@3.4.0\n  - @effect/platform-node@0.52.0\n  - @effect/platform@0.58.0\n  - @effect/schema@0.68.4\n\n## 0.16.33\n\n### Patch Changes\n\n- Updated dependencies [[`3ba7ea1`](https://github.com/Effect-TS/effect/commit/3ba7ea1c3c2923e85bf2f17e41176f8f8796d203)]:\n  - @effect/platform@0.57.8\n  - @effect/platform-node@0.51.17\n\n## 0.16.32\n\n### Patch Changes\n\n- Updated dependencies [[`d473800`](https://github.com/Effect-TS/effect/commit/d47380012c3241d7287b66968d33a2414275ce7b)]:\n  - @effect/schema@0.68.3\n  - @effect/platform@0.57.7\n  - @effect/platform-node@0.51.16\n\n## 0.16.31\n\n### Patch Changes\n\n- Updated dependencies [[`eb341b3`](https://github.com/Effect-TS/effect/commit/eb341b3eb34ad64499371bc08b7f59e429979d8a)]:\n  - @effect/schema@0.68.2\n  - @effect/platform@0.57.6\n  - @effect/platform-node@0.51.15\n\n## 0.16.30\n\n### Patch Changes\n\n- Updated dependencies [[`b8ea6aa`](https://github.com/Effect-TS/effect/commit/b8ea6aa479006358042b4256ee0a1c5cfbe57acb)]:\n  - @effect/platform@0.57.5\n  - @effect/platform-node@0.51.14\n\n## 0.16.29\n\n### Patch Changes\n\n- Updated dependencies [[`b51e266`](https://github.com/Effect-TS/effect/commit/b51e26662b879b55d2c5164b7c97742739aa9446), [`6c89408`](https://github.com/Effect-TS/effect/commit/6c89408cd7b9204ec4c5828a46cd5312d8afb5e7)]:\n  - @effect/schema@0.68.1\n  - effect@3.3.5\n  - @effect/platform@0.57.4\n  - @effect/platform-node@0.51.13\n\n## 0.16.28\n\n### Patch Changes\n\n- Updated dependencies [[`f6c7977`](https://github.com/Effect-TS/effect/commit/f6c79772e632c440b7e5221bb75f0ef9d3c3b005), [`a67b8fe`](https://github.com/Effect-TS/effect/commit/a67b8fe2ace08419424811b5f0d9a5378eaea352)]:\n  - @effect/schema@0.68.0\n  - effect@3.3.4\n  - @effect/platform@0.57.3\n  - @effect/platform-node@0.51.12\n\n## 0.16.27\n\n### Patch Changes\n\n- Updated dependencies [[`3b15e1b`](https://github.com/Effect-TS/effect/commit/3b15e1b505c0b0e62a03b4a3605d42a9932cc99c), [`06ede85`](https://github.com/Effect-TS/effect/commit/06ede85d6e84710e6622463be95ff3927fb30dad), [`3a750b2`](https://github.com/Effect-TS/effect/commit/3a750b25b1ed92094a7f7ebc332a6bcfb212871b), [`7204ca5`](https://github.com/Effect-TS/effect/commit/7204ca5761c2b1d27999a624db23aa10b6e0504d)]:\n  - @effect/schema@0.67.24\n  - effect@3.3.3\n  - @effect/platform@0.57.2\n  - @effect/platform-node@0.51.11\n\n## 0.16.26\n\n### Patch Changes\n\n- [#2980](https://github.com/Effect-TS/effect/pull/2980) [`7f987a3`](https://github.com/Effect-TS/effect/commit/7f987a30f1e9332d44ca23e1b2b9aec102214e58) Thanks @tim-smart! - improve dataLoader concurrency when max batch size is hit\n\n- Updated dependencies [[`2ee4f2b`](https://github.com/Effect-TS/effect/commit/2ee4f2be7fd63074a9cbac6dcdfb533b6683533a), [`07e12ec`](https://github.com/Effect-TS/effect/commit/07e12ecdb0e20b9763bd9e9058e567a7c8862efc), [`3572646`](https://github.com/Effect-TS/effect/commit/3572646d5e0804f85bc7f64633fb95722533f9dd), [`1aed347`](https://github.com/Effect-TS/effect/commit/1aed347a125ed3847ec90863424810d6759cbc85), [`df4bf4b`](https://github.com/Effect-TS/effect/commit/df4bf4b62e7b316c6647da0271fc5544a84e7ba2), [`f085f92`](https://github.com/Effect-TS/effect/commit/f085f92dfa204afb41823ffc27d437225137643d), [`9b3b4ac`](https://github.com/Effect-TS/effect/commit/9b3b4ac639d98aae33883926bece1e31fa280d22)]:\n  - @effect/schema@0.67.23\n  - @effect/platform@0.57.1\n  - effect@3.3.2\n  - @effect/platform-node@0.51.10\n\n## 0.16.25\n\n### Patch Changes\n\n- Updated dependencies [[`eb98c5b`](https://github.com/Effect-TS/effect/commit/eb98c5b79ab50aa0cde239bd4e660dd19dbab612), [`184fed8`](https://github.com/Effect-TS/effect/commit/184fed83ac36cba05a75a5a8013f740f9f696e3b), [`4d3fbe8`](https://github.com/Effect-TS/effect/commit/4d3fbe82e8cec13ccd0cd0b2096deac6818fb59a), [`6068e07`](https://github.com/Effect-TS/effect/commit/6068e073d4cc8b3c8583583fd5eb3efe43f7d5ba), [`3a77e20`](https://github.com/Effect-TS/effect/commit/3a77e209783933bac3aaddba1b05ff6a9ac72b36), [`d79ca17`](https://github.com/Effect-TS/effect/commit/d79ca17d9fa432571c69714776cab5cf8fef9c34)]:\n  - effect@3.3.1\n  - @effect/platform@0.57.0\n  - @effect/schema@0.67.22\n  - @effect/platform-node@0.51.9\n\n## 0.16.24\n\n### Patch Changes\n\n- Updated dependencies [[`2b9ddfc`](https://github.com/Effect-TS/effect/commit/2b9ddfcbac505d98551e764a43923854907ca5c1), [`1f4ac00`](https://github.com/Effect-TS/effect/commit/1f4ac00a91c336c9c9c9b8c3ed9ceb9920ebc9bd), [`9305b76`](https://github.com/Effect-TS/effect/commit/9305b764cceeae4f16564435ae7172f79c2bf822), [`0f40d98`](https://github.com/Effect-TS/effect/commit/0f40d989da10f68df3ecd72b36849401ad679bfb), [`188f0a5`](https://github.com/Effect-TS/effect/commit/188f0a5c57ed0d7c9e5852e0c1c998f1b95810a1), [`b761ef0`](https://github.com/Effect-TS/effect/commit/b761ef00eaf6c67b7ffe34798b98aae5347ab376), [`b53f69b`](https://github.com/Effect-TS/effect/commit/b53f69bff1452a487b21198cd83961f844e02d36), [`0f40d98`](https://github.com/Effect-TS/effect/commit/0f40d989da10f68df3ecd72b36849401ad679bfb), [`5bd549e`](https://github.com/Effect-TS/effect/commit/5bd549e4bd7144727db438ecca6b8dc9b3ef7e22), [`67f160a`](https://github.com/Effect-TS/effect/commit/67f160a213de0219a565d4bf653b3cbf24f58e8f), [`67f160a`](https://github.com/Effect-TS/effect/commit/67f160a213de0219a565d4bf653b3cbf24f58e8f)]:\n  - @effect/platform@0.56.0\n  - effect@3.3.0\n  - @effect/schema@0.67.21\n  - @effect/platform-node@0.51.8\n\n## 0.16.23\n\n### Patch Changes\n\n- Updated dependencies [[`4c6bc7f`](https://github.com/Effect-TS/effect/commit/4c6bc7f190c142dc9db70b365a2bf30715a98e62), [`a67d602`](https://github.com/Effect-TS/effect/commit/a67d60276f96cd20b76145b4cee13efca6c6158a)]:\n  - @effect/schema@0.67.20\n  - @effect/platform@0.55.7\n  - @effect/platform-node@0.51.7\n\n## 0.16.22\n\n### Patch Changes\n\n- Updated dependencies [[`8c5d280`](https://github.com/Effect-TS/effect/commit/8c5d280c0402284a4e58372867a15a431cb99461), [`6ba6d26`](https://github.com/Effect-TS/effect/commit/6ba6d269f5891e6b11aa35c5281dde4bf3273004), [`cd7496b`](https://github.com/Effect-TS/effect/commit/cd7496ba214eabac2e3c297f513fcbd5b11f0e91), [`3f28bf2`](https://github.com/Effect-TS/effect/commit/3f28bf274333611906175446b772243f34f1b6d5), [`5817820`](https://github.com/Effect-TS/effect/commit/58178204a770d1a78c06945ef438f9fffbb50afa), [`349a036`](https://github.com/Effect-TS/effect/commit/349a036ffb08351481c060655660a6ccf26473de), [`799aa20`](https://github.com/Effect-TS/effect/commit/799aa20b4f618736ba33a5297fda90a75d4c26c6)]:\n  - effect@3.2.9\n  - @effect/schema@0.67.19\n  - @effect/platform@0.55.6\n  - @effect/platform-node@0.51.6\n\n## 0.16.21\n\n### Patch Changes\n\n- Updated dependencies [[`a0dd1c1`](https://github.com/Effect-TS/effect/commit/a0dd1c1ede2a1e856ecb0e67826ec992016fef97)]:\n  - @effect/schema@0.67.18\n  - @effect/platform@0.55.5\n  - @effect/platform-node@0.51.5\n\n## 0.16.20\n\n### Patch Changes\n\n- Updated dependencies [[`d9d22e7`](https://github.com/Effect-TS/effect/commit/d9d22e7c4d5e31d5b46644c729b027796e467c16), [`3c080f7`](https://github.com/Effect-TS/effect/commit/3c080f74b2e2290edb6143c3aa01026e57f87a2a), [`3c080f7`](https://github.com/Effect-TS/effect/commit/3c080f74b2e2290edb6143c3aa01026e57f87a2a), [`7d6d875`](https://github.com/Effect-TS/effect/commit/7d6d8750077d9c8379f37240745240d7f3b7a4f8), [`70cda70`](https://github.com/Effect-TS/effect/commit/70cda704e8e31c80737b95121c8199e726ea132f), [`fb91f17`](https://github.com/Effect-TS/effect/commit/fb91f17098b48497feca9ec976feb87e4a82451b)]:\n  - @effect/schema@0.67.17\n  - effect@3.2.8\n  - @effect/platform@0.55.4\n  - @effect/platform-node@0.51.4\n\n## 0.16.19\n\n### Patch Changes\n\n- Updated dependencies [[`5745886`](https://github.com/Effect-TS/effect/commit/57458869859943410221ccc87f8cecfba7c79d92), [`6801fca`](https://github.com/Effect-TS/effect/commit/6801fca44366be3ee1b6b99f54bd4f38a1b5e4f4)]:\n  - @effect/schema@0.67.16\n  - effect@3.2.7\n  - @effect/platform@0.55.3\n  - @effect/platform-node@0.51.3\n\n## 0.16.18\n\n### Patch Changes\n\n- Updated dependencies [[`2c2280b`](https://github.com/Effect-TS/effect/commit/2c2280b98a11fc002663c55792a4fa5781cd5fb6), [`e2740fc`](https://github.com/Effect-TS/effect/commit/e2740fc4e212ba85a90541e8c8d85b0bcd5c2e7c), [`cc8ac50`](https://github.com/Effect-TS/effect/commit/cc8ac5080daba8622ca2ff5dab5c37ddfab732ba), [`60fe3d5`](https://github.com/Effect-TS/effect/commit/60fe3d5fb2be168dd35c6d0cb8ac8f55deb30fc0)]:\n  - @effect/platform@0.55.2\n  - @effect/schema@0.67.15\n  - effect@3.2.6\n  - @effect/platform-node@0.51.2\n\n## 0.16.17\n\n### Patch Changes\n\n- Updated dependencies [[`c5846e9`](https://github.com/Effect-TS/effect/commit/c5846e99137e9eb02efd31865e26f49f0d2c7c03)]:\n  - @effect/schema@0.67.14\n  - @effect/platform-node@0.51.1\n  - @effect/platform@0.55.1\n\n## 0.16.16\n\n### Patch Changes\n\n- Updated dependencies [[`608b01f`](https://github.com/Effect-TS/effect/commit/608b01fc342dbae2a642b308a67b84ead530ecea), [`031c712`](https://github.com/Effect-TS/effect/commit/031c7122a24ac42e48d6a434646b4f5d279d7442), [`a44e532`](https://github.com/Effect-TS/effect/commit/a44e532cf3a6a498b12a5aacf8124aa267e24ba0), [`5133ca9`](https://github.com/Effect-TS/effect/commit/5133ca9dc4b8da0e28951316da9ab55dfbe0fbb9)]:\n  - effect@3.2.5\n  - @effect/platform@0.55.0\n  - @effect/platform-node@0.51.0\n  - @effect/schema@0.67.13\n\n## 0.16.15\n\n### Patch Changes\n\n- Updated dependencies [[`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3), [`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3), [`f8038ca`](https://github.com/Effect-TS/effect/commit/f8038cadd5f50d397469e5fdbc70dd8f69671f50), [`e376641`](https://github.com/Effect-TS/effect/commit/e3766411b60ebb45d31e9c9d94efa099121d4d58), [`c07e0ce`](https://github.com/Effect-TS/effect/commit/c07e0cea8ce165887e2c9dfa5d669eba9b2fb798), [`e313a01`](https://github.com/Effect-TS/effect/commit/e313a01b7e80f6cb7704055a190e5623c9d22c6d), [`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3)]:\n  - effect@3.2.4\n  - @effect/platform@0.54.0\n  - @effect/platform-node@0.50.0\n  - @effect/schema@0.67.12\n\n## 0.16.14\n\n### Patch Changes\n\n- [#2803](https://github.com/Effect-TS/effect/pull/2803) [`5af633e`](https://github.com/Effect-TS/effect/commit/5af633eb5ff6560a64d87263d1692bb9c75f7b3c) Thanks @tim-smart! - update dependencies\n\n- Updated dependencies [[`5af633e`](https://github.com/Effect-TS/effect/commit/5af633eb5ff6560a64d87263d1692bb9c75f7b3c), [`45578e8`](https://github.com/Effect-TS/effect/commit/45578e8faa80ae33d23e08f6f19467f818b7788f)]:\n  - @effect/platform-node@0.49.14\n  - @effect/schema@0.67.11\n  - effect@3.2.3\n  - @effect/platform@0.53.14\n\n## 0.16.13\n\n### Patch Changes\n\n- Updated dependencies [[`7cc8020`](https://github.com/Effect-TS/effect/commit/7cc802018395804ae2fbce20f610bb7ff6081c00), [`5d9266e`](https://github.com/Effect-TS/effect/commit/5d9266e8c740746ac9e186c3df6090a1b57fbe2a), [`9f8122e`](https://github.com/Effect-TS/effect/commit/9f8122e78884ab47c5e5f364d86eee1d1543cc61), [`6a6f670`](https://github.com/Effect-TS/effect/commit/6a6f6706b8613c8c7c10971b8d81a0f9e440a6f2), [`c1eaef9`](https://github.com/Effect-TS/effect/commit/c1eaef910420dae416923d172ee58d219e921d0f), [`78ffc27`](https://github.com/Effect-TS/effect/commit/78ffc27ee3fa708433c25fa118c53d38d90d08bc)]:\n  - @effect/platform-node@0.49.13\n  - effect@3.2.2\n  - @effect/platform@0.53.13\n  - @effect/schema@0.67.10\n\n## 0.16.12\n\n### Patch Changes\n\n- Updated dependencies [[`5432fff`](https://github.com/Effect-TS/effect/commit/5432fff7c9a69d43910426c1053ebfc3b73ebed6)]:\n  - @effect/schema@0.67.9\n  - @effect/platform@0.53.12\n  - @effect/platform-node@0.49.12\n\n## 0.16.11\n\n### Patch Changes\n\n- Updated dependencies [[`c1e991d`](https://github.com/Effect-TS/effect/commit/c1e991dd5ba87901cd0e05697a8b4a267e7e954a)]:\n  - effect@3.2.1\n  - @effect/platform@0.53.11\n  - @effect/platform-node@0.49.11\n  - @effect/schema@0.67.8\n\n## 0.16.10\n\n### Patch Changes\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e) Thanks [@tim-smart](https://github.com/tim-smart)! - capture stack trace for tracing spans\n\n- Updated dependencies [[`146cadd`](https://github.com/Effect-TS/effect/commit/146cadd9d004634a3ff85c480bf92cf975c853e2), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`963b4e7`](https://github.com/Effect-TS/effect/commit/963b4e7ac87e2468feb6a344f7ab4ee4ad711198), [`64c9414`](https://github.com/Effect-TS/effect/commit/64c9414e960e82058ca09bbb3976d6fbef303a8e), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`2cbb76b`](https://github.com/Effect-TS/effect/commit/2cbb76bb52500a3f4bf27d1c91482518cbea56d7), [`870c5fa`](https://github.com/Effect-TS/effect/commit/870c5fa52cd61e745e8e828d38c3f09f00737553), [`146cadd`](https://github.com/Effect-TS/effect/commit/146cadd9d004634a3ff85c480bf92cf975c853e2), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`64c9414`](https://github.com/Effect-TS/effect/commit/64c9414e960e82058ca09bbb3976d6fbef303a8e)]:\n  - effect@3.2.0\n  - @effect/platform@0.53.10\n  - @effect/platform-node@0.49.10\n  - @effect/schema@0.67.7\n\n## 0.16.9\n\n### Patch Changes\n\n- Updated dependencies [[`17da864`](https://github.com/Effect-TS/effect/commit/17da864e4a6f80becdb82db7dece2ba583bfdda3), [`17fc22e`](https://github.com/Effect-TS/effect/commit/17fc22e132593c5caa563705a4748ba0f04a853c), [`810f222`](https://github.com/Effect-TS/effect/commit/810f222268792b13067c7a7bf317b93a9bb8917b), [`596aaea`](https://github.com/Effect-TS/effect/commit/596aaea022648b2e06fb1ec22f1652043d6fe64e), [`ff0efa0`](https://github.com/Effect-TS/effect/commit/ff0efa0a1415a41d4a4312a16cf7a63def86db3f)]:\n  - @effect/schema@0.67.6\n  - @effect/platform@0.53.9\n  - effect@3.1.6\n  - @effect/platform-node@0.49.9\n\n## 0.16.8\n\n### Patch Changes\n\n- Updated dependencies [[`9c514de`](https://github.com/Effect-TS/effect/commit/9c514de28152696edff008324d2d7e67d55afd56)]:\n  - @effect/schema@0.67.5\n  - @effect/platform@0.53.8\n  - @effect/platform-node@0.49.8\n\n## 0.16.7\n\n### Patch Changes\n\n- Updated dependencies [[`ee08593`](https://github.com/Effect-TS/effect/commit/ee0859398ecc2589cab0d017bef6a17e00c34dfd), [`da6d7d8`](https://github.com/Effect-TS/effect/commit/da6d7d845246e9d04631d64fa7694944b6010d09)]:\n  - @effect/schema@0.67.4\n  - @effect/platform@0.53.7\n  - @effect/platform-node@0.49.7\n\n## 0.16.6\n\n### Patch Changes\n\n- [#2750](https://github.com/Effect-TS/effect/pull/2750) [`6ac4847`](https://github.com/Effect-TS/effect/commit/6ac48479447c01a4f35d655552af93e47e562610) Thanks [@tim-smart](https://github.com/tim-smart)! - fix memory leak in Socket's\n\n- Updated dependencies [[`6ac4847`](https://github.com/Effect-TS/effect/commit/6ac48479447c01a4f35d655552af93e47e562610), [`6ac4847`](https://github.com/Effect-TS/effect/commit/6ac48479447c01a4f35d655552af93e47e562610)]:\n  - @effect/platform@0.53.6\n  - effect@3.1.5\n  - @effect/platform-node@0.49.6\n  - @effect/schema@0.67.3\n\n## 0.16.5\n\n### Patch Changes\n\n- Updated dependencies [[`89a3afb`](https://github.com/Effect-TS/effect/commit/89a3afbe191c83b84b17bfaa95519aff0749afbe), [`992c8e2`](https://github.com/Effect-TS/effect/commit/992c8e21535db9f0c66e81d32fee8af56a96274f)]:\n  - @effect/schema@0.67.2\n  - @effect/platform@0.53.5\n  - @effect/platform-node@0.49.5\n\n## 0.16.4\n\n### Patch Changes\n\n- Updated dependencies [[`e41e911`](https://github.com/Effect-TS/effect/commit/e41e91122fa6dd12fc81e50dcad0db891be67146)]:\n  - effect@3.1.4\n  - @effect/platform@0.53.4\n  - @effect/platform-node@0.49.4\n  - @effect/schema@0.67.1\n\n## 0.16.3\n\n### Patch Changes\n\n- Updated dependencies [[`d7e4997`](https://github.com/Effect-TS/effect/commit/d7e49971fe97b7ee5fb7991f3f5ac4d627a26338)]:\n  - @effect/schema@0.67.0\n  - @effect/platform@0.53.3\n  - @effect/platform-node@0.49.3\n\n## 0.16.2\n\n### Patch Changes\n\n- Updated dependencies [[`1f6dc96`](https://github.com/Effect-TS/effect/commit/1f6dc96f51c7bb9c8d11415358308604ba7c7c8e), [`1f6dc96`](https://github.com/Effect-TS/effect/commit/1f6dc96f51c7bb9c8d11415358308604ba7c7c8e)]:\n  - @effect/platform-node@0.49.2\n  - effect@3.1.3\n  - @effect/platform@0.53.2\n  - @effect/schema@0.66.16\n\n## 0.16.1\n\n### Patch Changes\n\n- Updated dependencies [[`121d6d9`](https://github.com/Effect-TS/effect/commit/121d6d93755138c7510ba3ab4f0019ec0cb91890)]:\n  - @effect/schema@0.66.15\n  - @effect/platform@0.53.1\n  - @effect/platform-node@0.49.1\n\n## 0.16.0\n\n### Minor Changes\n\n- [#2703](https://github.com/Effect-TS/effect/pull/2703) [`d57fbbb`](https://github.com/Effect-TS/effect/commit/d57fbbbd6c466936213a671fc3cd2390064f864e) Thanks [@tim-smart](https://github.com/tim-smart)! - replace isows with WebSocketConstructor service in @effect/platform/Socket\n\n  You now have to provide a WebSocketConstructor implementation to the `Socket.makeWebSocket` api.\n\n  ```ts\n  import * as Socket from \"@effect/platform/Socket\"\n  import * as NodeSocket from \"@effect/platform-node/NodeSocket\"\n  import { Effect } from \"effect\"\n\n  Socket.makeWebSocket(\"ws://localhost:8080\").pipe(\n    Effect.provide(NodeSocket.layerWebSocketConstructor) // use \"ws\" npm package\n  )\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`d57fbbb`](https://github.com/Effect-TS/effect/commit/d57fbbbd6c466936213a671fc3cd2390064f864e)]:\n  - @effect/platform-node@0.49.0\n  - @effect/platform@0.53.0\n\n## 0.15.18\n\n### Patch Changes\n\n- Updated dependencies [[`5866c62`](https://github.com/Effect-TS/effect/commit/5866c621d7eb4cc84e4ba972bfdfd219734cd45d)]:\n  - @effect/platform@0.52.3\n  - @effect/platform-node@0.48.4\n\n## 0.15.17\n\n### Patch Changes\n\n- [#2679](https://github.com/Effect-TS/effect/pull/2679) [`2e1cdf6`](https://github.com/Effect-TS/effect/commit/2e1cdf67d141281288fffe9a5c10d1379a800513) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure all type ids are annotated with `unique symbol`\n\n- Updated dependencies [[`e4b82d2`](https://github.com/Effect-TS/effect/commit/e4b82d239bf0974173b5d687b45d1b1899be615f), [`2e1cdf6`](https://github.com/Effect-TS/effect/commit/2e1cdf67d141281288fffe9a5c10d1379a800513)]:\n  - @effect/platform-node@0.48.3\n  - @effect/platform@0.52.2\n  - effect@3.1.2\n  - @effect/schema@0.66.14\n\n## 0.15.16\n\n### Patch Changes\n\n- Updated dependencies [[`e5e56d1`](https://github.com/Effect-TS/effect/commit/e5e56d138dbed3204636f605229c6685f89659fc)]:\n  - effect@3.1.1\n  - @effect/platform@0.52.1\n  - @effect/platform-node@0.48.2\n  - @effect/schema@0.66.13\n\n## 0.15.15\n\n### Patch Changes\n\n- Updated dependencies [[`9deab0a`](https://github.com/Effect-TS/effect/commit/9deab0aec9e99501f9441843e34df9afa10c5be9), [`7719b8a`](https://github.com/Effect-TS/effect/commit/7719b8a7350c14e952ffe685bfd5308773b3e271)]:\n  - @effect/platform@0.52.0\n  - @effect/platform-node@0.48.1\n\n## 0.15.14\n\n### Patch Changes\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`a023f28`](https://github.com/Effect-TS/effect/commit/a023f28336f3865687d9a30c1883e36909906d85) Thanks [@github-actions](https://github.com/apps/github-actions)! - set span `kind` where applicable\n\n- Updated dependencies [[`c3c12c6`](https://github.com/Effect-TS/effect/commit/c3c12c6625633fe80e79f9db75a3b8cf8ca8b11d), [`ba64ea6`](https://github.com/Effect-TS/effect/commit/ba64ea6757810c5e74cad3863a7d19d4d38af66b), [`b5de2d2`](https://github.com/Effect-TS/effect/commit/b5de2d2ce5b1afe8be90827bf898a95cec40eb2b), [`a1c7ab8`](https://github.com/Effect-TS/effect/commit/a1c7ab8ffedacd18c1fc784f4ff5844f79498b83), [`a023f28`](https://github.com/Effect-TS/effect/commit/a023f28336f3865687d9a30c1883e36909906d85), [`0ec93cb`](https://github.com/Effect-TS/effect/commit/0ec93cb4f166e7401c171c2f8e8276ce958d9a57), [`1c9454d`](https://github.com/Effect-TS/effect/commit/1c9454d532eae79b9f759aea77f59332cc6d18ed), [`a023f28`](https://github.com/Effect-TS/effect/commit/a023f28336f3865687d9a30c1883e36909906d85), [`92d56db`](https://github.com/Effect-TS/effect/commit/92d56dbb3f33e36636c2a2f1030c56492e39cf4d)]:\n  - effect@3.1.0\n  - @effect/platform-node@0.48.0\n  - @effect/platform@0.51.0\n  - @effect/schema@0.66.12\n\n## 0.15.13\n\n### Patch Changes\n\n- [#2656](https://github.com/Effect-TS/effect/pull/2656) [`557707b`](https://github.com/Effect-TS/effect/commit/557707bc9e5f230c8964d2757012075c34339b5c) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n- Updated dependencies [[`16039a0`](https://github.com/Effect-TS/effect/commit/16039a08f04f11545e2fdf40952788a8f9cef04f), [`557707b`](https://github.com/Effect-TS/effect/commit/557707bc9e5f230c8964d2757012075c34339b5c), [`d1d33e1`](https://github.com/Effect-TS/effect/commit/d1d33e10b25109f44b5ab1c6e4d778a59c0d3eeb), [`f4ed306`](https://github.com/Effect-TS/effect/commit/f4ed3068a70b50302d078a30d18ca3cfd2bc679c), [`661004f`](https://github.com/Effect-TS/effect/commit/661004f4bf5f8b25f5a0678c21a3a822188ce461), [`e79cb83`](https://github.com/Effect-TS/effect/commit/e79cb83d3b19098bc40a3012e2a059b8426306c2)]:\n  - @effect/platform@0.50.8\n  - @effect/platform-node@0.47.8\n  - effect@3.0.8\n  - @effect/schema@0.66.11\n\n## 0.15.12\n\n### Patch Changes\n\n- Updated dependencies [[`18de56b`](https://github.com/Effect-TS/effect/commit/18de56b4a6b6d1f99230dfabf9147d59ea4dd759)]:\n  - effect@3.0.7\n  - @effect/platform@0.50.7\n  - @effect/platform-node@0.47.7\n  - @effect/schema@0.66.10\n\n## 0.15.11\n\n### Patch Changes\n\n- [#2626](https://github.com/Effect-TS/effect/pull/2626) [`027418e`](https://github.com/Effect-TS/effect/commit/027418edaa6aa6c0ae4861b95832827b45adace4) Thanks [@fubhy](https://github.com/fubhy)! - Reintroduce custom `NoInfer` type\n\n- [#2609](https://github.com/Effect-TS/effect/pull/2609) [`ac1898e`](https://github.com/Effect-TS/effect/commit/ac1898eb7bc96880f911c276048e2ea3d6fe9c50) Thanks [@patroza](https://github.com/patroza)! - change: BatchedRequestResolver works with NonEmptyArray\n\n- Updated dependencies [[`ffe4f4e`](https://github.com/Effect-TS/effect/commit/ffe4f4e95db35fff6869e360b072e3837befa0a1), [`027418e`](https://github.com/Effect-TS/effect/commit/027418edaa6aa6c0ae4861b95832827b45adace4), [`ac1898e`](https://github.com/Effect-TS/effect/commit/ac1898eb7bc96880f911c276048e2ea3d6fe9c50), [`ffe4f4e`](https://github.com/Effect-TS/effect/commit/ffe4f4e95db35fff6869e360b072e3837befa0a1), [`8206529`](https://github.com/Effect-TS/effect/commit/8206529d6a7bbf3e3c6f670afb0381e83176736e)]:\n  - effect@3.0.6\n  - @effect/schema@0.66.9\n  - @effect/platform@0.50.6\n  - @effect/platform-node@0.47.6\n\n## 0.15.10\n\n### Patch Changes\n\n- Updated dependencies [[`6222404`](https://github.com/Effect-TS/effect/commit/62224044678751829ed2f128e05133a91c6b0569), [`868ed2a`](https://github.com/Effect-TS/effect/commit/868ed2a8fe94ee7f4206a6070f29dcf2a5ba1dc3)]:\n  - effect@3.0.5\n  - @effect/platform@0.50.5\n  - @effect/platform-node@0.47.5\n  - @effect/schema@0.66.8\n\n## 0.15.9\n\n### Patch Changes\n\n- Updated dependencies [[`dd41c6c`](https://github.com/Effect-TS/effect/commit/dd41c6c725b1c1c980683275d8fa69779902187e), [`9a24667`](https://github.com/Effect-TS/effect/commit/9a246672008a2b668d43fbfd2fe5508c54b2b920)]:\n  - @effect/schema@0.66.7\n  - effect@3.0.4\n  - @effect/platform@0.50.4\n  - @effect/platform-node@0.47.4\n\n## 0.15.8\n\n### Patch Changes\n\n- Updated dependencies [[`9dfc156`](https://github.com/Effect-TS/effect/commit/9dfc156dc13fb4da9c777aae3acece4b5ecf0064), [`80271bd`](https://github.com/Effect-TS/effect/commit/80271bdc648e9efa659ce66b2c255754a6a1a8b0), [`b3b51a2`](https://github.com/Effect-TS/effect/commit/b3b51a2ea0c6ab92a363db46ebaa7e1176d089f5), [`e4ba97d`](https://github.com/Effect-TS/effect/commit/e4ba97d060c16bdf4e3b5bd5db6777f121a6768c)]:\n  - @effect/schema@0.66.6\n  - @effect/platform@0.50.3\n  - @effect/platform-node@0.47.3\n\n## 0.15.7\n\n### Patch Changes\n\n- Updated dependencies [[`b3fe829`](https://github.com/Effect-TS/effect/commit/b3fe829e8b12726afe94086b5375968f41a26411), [`a58b7de`](https://github.com/Effect-TS/effect/commit/a58b7deb8bb1d3b0dd636decf5d16f115f37eb72), [`d90e8c3`](https://github.com/Effect-TS/effect/commit/d90e8c3090cbc78e2bc7b51c974df66ffefacdfa)]:\n  - @effect/schema@0.66.5\n  - @effect/platform@0.50.2\n  - @effect/platform-node@0.47.2\n\n## 0.15.6\n\n### Patch Changes\n\n- Updated dependencies [[`773b8e0`](https://github.com/Effect-TS/effect/commit/773b8e01521e8fa7c38ff15d92d21d6fd6dad56f)]:\n  - @effect/schema@0.66.4\n  - @effect/platform@0.50.1\n  - @effect/platform-node@0.47.1\n\n## 0.15.5\n\n### Patch Changes\n\n- Updated dependencies [[`6f38dff`](https://github.com/Effect-TS/effect/commit/6f38dff41ffa34532cc2f25b90446550c5730bb6), [`a7b4b84`](https://github.com/Effect-TS/effect/commit/a7b4b84bd5a25f51aba922f9259c3a58c98c6a4e), [`a3b0e6c`](https://github.com/Effect-TS/effect/commit/a3b0e6c490772e6d44b5d98dcf2729c4d5310ecc), [`6f38dff`](https://github.com/Effect-TS/effect/commit/6f38dff41ffa34532cc2f25b90446550c5730bb6)]:\n  - @effect/platform-node@0.47.0\n  - @effect/platform@0.50.0\n  - effect@3.0.3\n  - @effect/schema@0.66.3\n\n## 0.15.4\n\n### Patch Changes\n\n- [#2562](https://github.com/Effect-TS/effect/pull/2562) [`2cecdbd`](https://github.com/Effect-TS/effect/commit/2cecdbd1cf30befce4e84796ccd953ea55ecfb86) Thanks [@fubhy](https://github.com/fubhy)! - Added provenance publishing\n\n- Updated dependencies [[`2cecdbd`](https://github.com/Effect-TS/effect/commit/2cecdbd1cf30befce4e84796ccd953ea55ecfb86)]:\n  - @effect/platform-node@0.46.4\n  - @effect/platform@0.49.4\n  - effect@3.0.2\n  - @effect/schema@0.66.2\n\n## 0.15.3\n\n### Patch Changes\n\n- Updated dependencies [[`8d39d65`](https://github.com/Effect-TS/effect/commit/8d39d6554af548228ad767112ce2e0b1f68fa8e1)]:\n  - @effect/platform@0.49.3\n  - @effect/platform-node@0.46.3\n\n## 0.15.2\n\n### Patch Changes\n\n- Updated dependencies [[`5ef0a1a`](https://github.com/Effect-TS/effect/commit/5ef0a1ae9b773fa2481550cb0d43ff7a0e03cd44)]:\n  - @effect/platform@0.49.2\n  - @effect/platform-node@0.46.2\n\n## 0.15.1\n\n### Patch Changes\n\n- [#2555](https://github.com/Effect-TS/effect/pull/2555) [`8edacca`](https://github.com/Effect-TS/effect/commit/8edacca37f8e37c01a63fec332b06d9361efaa7b) Thanks [@tim-smart](https://github.com/tim-smart)! - prevent use of `Array` as import name to solve bundler issues\n\n- Updated dependencies [[`3da0cfa`](https://github.com/Effect-TS/effect/commit/3da0cfa12c407fd930dc480be1ecc9217a8058f8), [`570e8d8`](https://github.com/Effect-TS/effect/commit/570e8d87e7c0e9ad4cd2686462fdb9b4812f7716), [`b2b5d66`](https://github.com/Effect-TS/effect/commit/b2b5d6626b18eb5289f364ffab5240e84b04d085), [`87c5687`](https://github.com/Effect-TS/effect/commit/87c5687de0782dab177b7861217fa3b040046282), [`8edacca`](https://github.com/Effect-TS/effect/commit/8edacca37f8e37c01a63fec332b06d9361efaa7b)]:\n  - effect@3.0.1\n  - @effect/schema@0.66.1\n  - @effect/platform@0.49.1\n  - @effect/platform-node@0.46.1\n\n## 0.15.0\n\n### Minor Changes\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`5a2314b`](https://github.com/Effect-TS/effect/commit/5a2314b70ec79c2c02b51cef45a5ddec8327daa1) Thanks [@github-actions](https://github.com/apps/github-actions)! - replace use of `unit` terminology with `void`\n\n  For all the data types.\n\n  ```ts\n  Effect.unit // => Effect.void\n  Stream.unit // => Stream.void\n\n  // etc\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`2fb7d9c`](https://github.com/Effect-TS/effect/commit/2fb7d9ca15037ff62a578bb9fe5732da5f4f317d) Thanks [@github-actions](https://github.com/apps/github-actions)! - Release Effect 3.0 🎉\n\n### Patch Changes\n\n- [#2529](https://github.com/Effect-TS/effect/pull/2529) [`78b767c`](https://github.com/Effect-TS/effect/commit/78b767c2b1625186e17131761a0edbac25d21850) Thanks [@fubhy](https://github.com/fubhy)! - Renamed `ReadonlyArray` and `ReadonlyRecord` modules for better discoverability.\n\n- Updated dependencies [[`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`d50a652`](https://github.com/Effect-TS/effect/commit/d50a652479f4d1d64f48da05c79fa847e6e51548), [`9aeae46`](https://github.com/Effect-TS/effect/commit/9aeae461fdf9265389cf3dfe4e428b037215ba5f), [`9a3bd47`](https://github.com/Effect-TS/effect/commit/9a3bd47ebd0750c7e498162734f6d21895de0cb2), [`6c6087a`](https://github.com/Effect-TS/effect/commit/6c6087a4a897b64252346426660782d31c13f769), [`6460414`](https://github.com/Effect-TS/effect/commit/6460414351a45fb8e0a457c63f3653422efee766), [`cf69f46`](https://github.com/Effect-TS/effect/commit/cf69f46690058d71eeada03cfb40dc744573e9e4), [`cf69f46`](https://github.com/Effect-TS/effect/commit/cf69f46690058d71eeada03cfb40dc744573e9e4), [`e542371`](https://github.com/Effect-TS/effect/commit/e542371981f8b4b484979feaad8a25b1f45e2df0), [`be9d025`](https://github.com/Effect-TS/effect/commit/be9d025e42355260ace02dd135851a8935a4deba), [`78b767c`](https://github.com/Effect-TS/effect/commit/78b767c2b1625186e17131761a0edbac25d21850), [`aa4a3b5`](https://github.com/Effect-TS/effect/commit/aa4a3b550da1c1020265ac389ed3f309388994a2), [`1499974`](https://github.com/Effect-TS/effect/commit/14999741d2e19c1747f6a7e19d68977f6429cdb8), [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`5c2b561`](https://github.com/Effect-TS/effect/commit/5c2b5614f583b88784ed68126ae939832fb3c092), [`6c6087a`](https://github.com/Effect-TS/effect/commit/6c6087a4a897b64252346426660782d31c13f769), [`a18f594`](https://github.com/Effect-TS/effect/commit/a18f5948f1439a147232448b2c443472fda0eceb), [`1499974`](https://github.com/Effect-TS/effect/commit/14999741d2e19c1747f6a7e19d68977f6429cdb8), [`2f96d93`](https://github.com/Effect-TS/effect/commit/2f96d938b90f8c19377583279e3c7afd9b509c50), [`5a2314b`](https://github.com/Effect-TS/effect/commit/5a2314b70ec79c2c02b51cef45a5ddec8327daa1), [`25d74f8`](https://github.com/Effect-TS/effect/commit/25d74f8c4d2dd4a9e5ec57ce2f20d36dedd25343), [`6c6087a`](https://github.com/Effect-TS/effect/commit/6c6087a4a897b64252346426660782d31c13f769), [`271b79f`](https://github.com/Effect-TS/effect/commit/271b79fc0b66a6c11e07a8779ff8800493a7eac2), [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`2fb7d9c`](https://github.com/Effect-TS/effect/commit/2fb7d9ca15037ff62a578bb9fe5732da5f4f317d), [`53d1c2a`](https://github.com/Effect-TS/effect/commit/53d1c2a77559081fbb89667e343346375c6d6650), [`e7e1bbe`](https://github.com/Effect-TS/effect/commit/e7e1bbe68486fdf31c8f84b0880522d39adcaad3), [`10c169e`](https://github.com/Effect-TS/effect/commit/10c169eadc874e91b4defca3f467b4e6a50fd8f3), [`6424181`](https://github.com/Effect-TS/effect/commit/64241815fe6a939e91e6947253e7dceea1306aa8)]:\n  - effect@3.0.0\n  - @effect/schema@0.66.0\n  - @effect/platform-node@0.46.0\n  - @effect/platform@0.49.0\n\n## 0.14.14\n\n### Patch Changes\n\n- Updated dependencies [[`b79cc59`](https://github.com/Effect-TS/effect/commit/b79cc59dbe64b9a0a7742dc9100a9d36c8e46b72)]:\n  - @effect/platform-node@0.45.31\n  - @effect/platform@0.48.29\n\n## 0.14.13\n\n### Patch Changes\n\n- [#2472](https://github.com/Effect-TS/effect/pull/2472) [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55) Thanks [@tim-smart](https://github.com/tim-smart)! - add Subscribable trait / module\n\n  Subscribable represents a resource that has a current value and can be subscribed to for updates.\n\n  The following data types are subscribable:\n  - A `SubscriptionRef`\n  - An `Actor` from the experimental `Machine` module\n\n- [#2472](https://github.com/Effect-TS/effect/pull/2472) [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55) Thanks [@tim-smart](https://github.com/tim-smart)! - add Readable module / trait\n\n  `Readable` is a common interface for objects that can be read from using a `get`\n  Effect.\n\n  For example, `Ref`'s implement `Readable`:\n\n  ```ts\n  import { Effect, Readable, Ref } from \"effect\"\n  import assert from \"assert\"\n\n  Effect.gen(function* (_) {\n    const ref = yield* _(Ref.make(123))\n    assert(Readable.isReadable(ref))\n\n    const result = yield* _(ref.get)\n    assert(result === 123)\n  })\n  ```\n\n- Updated dependencies [[`0aee906`](https://github.com/Effect-TS/effect/commit/0aee906f034539344db6fbac08919de3e28eccde), [`41c8102`](https://github.com/Effect-TS/effect/commit/41c810228b1a50e4b41f19e735d7c62fe8d36871), [`4c37001`](https://github.com/Effect-TS/effect/commit/4c370013417e18c4f564818de1341a8fccb43b4c), [`776ef2b`](https://github.com/Effect-TS/effect/commit/776ef2bb66db9aa9f68b7beab14f6986f9c1288b), [`217147e`](https://github.com/Effect-TS/effect/commit/217147ea67c5c42c96f024775c41e5b070f81e4c), [`8a69b4e`](https://github.com/Effect-TS/effect/commit/8a69b4ef6a3a06d2e21fe2e11a626038beefb4e1), [`90776ec`](https://github.com/Effect-TS/effect/commit/90776ec8e8671d835b65fc33ead1de6c864b81b9), [`b3acf47`](https://github.com/Effect-TS/effect/commit/b3acf47f9c9dfae1c99377aa906097aaa2d47d44), [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55), [`232c353`](https://github.com/Effect-TS/effect/commit/232c353c2e6f743f38e57639ee30e324ffa9c2a9), [`0d3231a`](https://github.com/Effect-TS/effect/commit/0d3231a195202635ecc0bf6bbf6a08fc017d0d69), [`0ca835c`](https://github.com/Effect-TS/effect/commit/0ca835cbac8e69072a93ace83b534219faba24e8), [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55), [`da22adc`](https://github.com/Effect-TS/effect/commit/da22adc6507563876f1c416fd22a5f9206cc1395), [`d590094`](https://github.com/Effect-TS/effect/commit/d5900943489ec1e0891836aeafb5ce99fb9c75c7), [`c22b019`](https://github.com/Effect-TS/effect/commit/c22b019e5eaf9d3a937a3d99cadbb8f8e9116a70), [`e983740`](https://github.com/Effect-TS/effect/commit/e9837401145605aff5bc2ec7e73004f397c5d2d1), [`e3e0924`](https://github.com/Effect-TS/effect/commit/e3e09247d46a35430fc60e4aa4032cc50814f212)]:\n  - @effect/schema@0.65.0\n  - effect@2.4.19\n  - @effect/platform-node@0.45.30\n  - @effect/platform@0.48.28\n\n## 0.14.12\n\n### Patch Changes\n\n- Updated dependencies [[`c6dd3c6`](https://github.com/Effect-TS/effect/commit/c6dd3c6909cafe05adc8450c5a499260e17e60d3), [`672f137`](https://github.com/Effect-TS/effect/commit/672f13747ddf6dac3ba304fd4511b1df44ab566d), [`42b3651`](https://github.com/Effect-TS/effect/commit/42b36519f356bae9258a1ea1d416e2902b973e85), [`672f137`](https://github.com/Effect-TS/effect/commit/672f13747ddf6dac3ba304fd4511b1df44ab566d)]:\n  - @effect/platform@0.48.27\n  - @effect/schema@0.64.20\n  - @effect/platform-node@0.45.29\n\n## 0.14.11\n\n### Patch Changes\n\n- Updated dependencies [[`365a486`](https://github.com/Effect-TS/effect/commit/365a4865de5e47ce09f4cfd51fc0f67438f82a57)]:\n  - @effect/platform@0.48.26\n  - @effect/platform-node@0.45.28\n\n## 0.14.10\n\n### Patch Changes\n\n- Updated dependencies [[`dadc690`](https://github.com/Effect-TS/effect/commit/dadc6906121c512bc32be22b52adbd1ada834594), [`58f66fe`](https://github.com/Effect-TS/effect/commit/58f66fecd4e646c6c8f10995df9faab17022eb8f), [`3cad21d`](https://github.com/Effect-TS/effect/commit/3cad21daa5d2332d33692498c87b7ffff979e304), [`d209171`](https://github.com/Effect-TS/effect/commit/d2091714a786820ebae4bef04a9d67d25dd08e88)]:\n  - effect@2.4.18\n  - @effect/schema@0.64.19\n  - @effect/platform@0.48.25\n  - @effect/platform-node@0.45.27\n\n## 0.14.9\n\n### Patch Changes\n\n- Updated dependencies [[`9c6a500`](https://github.com/Effect-TS/effect/commit/9c6a5001b467b6255c68a922f4b6e8d692b63d01), [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`607b2e7`](https://github.com/Effect-TS/effect/commit/607b2e7a7fd9318c57acf4e50ec61747eea74ad7), [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`35ad0ba`](https://github.com/Effect-TS/effect/commit/35ad0ba9f3ba27c60453620e514b980f819f92af), [`8206caf`](https://github.com/Effect-TS/effect/commit/8206caf7c2d22c68be4313318b61cfdacf6222b6), [`7ddd654`](https://github.com/Effect-TS/effect/commit/7ddd65415b65ccb654ad04f4dbefe39402f15117), [`7ddd654`](https://github.com/Effect-TS/effect/commit/7ddd65415b65ccb654ad04f4dbefe39402f15117), [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`f456ba2`](https://github.com/Effect-TS/effect/commit/f456ba273bae21a6dcf8c966c50c97b5f0897d9f)]:\n  - @effect/platform@0.48.24\n  - effect@2.4.17\n  - @effect/platform-node@0.45.26\n  - @effect/schema@0.64.18\n\n## 0.14.8\n\n### Patch Changes\n\n- Updated dependencies [[`5170ce7`](https://github.com/Effect-TS/effect/commit/5170ce708c606283e8a30d273950f1a21c7eddc2), [`63a1df2`](https://github.com/Effect-TS/effect/commit/63a1df2e4de3766f48f15676fbd0360ab9c27816), [`5170ce7`](https://github.com/Effect-TS/effect/commit/5170ce708c606283e8a30d273950f1a21c7eddc2), [`62a7f23`](https://github.com/Effect-TS/effect/commit/62a7f23937c0dfaca67a7b2f055b85cfde25ed11), [`7cc2b41`](https://github.com/Effect-TS/effect/commit/7cc2b41d6c551fdca2590b06681c5ad9832aba46), [`74a5dae`](https://github.com/Effect-TS/effect/commit/74a5daed0e65b32a36e026bfcf66d02269cb967a), [`8b46fde`](https://github.com/Effect-TS/effect/commit/8b46fdebf2c075a74cd2cd29dfb69531d20fc154)]:\n  - @effect/platform@0.48.23\n  - effect@2.4.16\n  - @effect/schema@0.64.17\n  - @effect/platform-node@0.45.25\n\n## 0.14.7\n\n### Patch Changes\n\n- Updated dependencies [[`a31917a`](https://github.com/Effect-TS/effect/commit/a31917aa4b05b1189b7a8e0bedb60bb3d49262ad), [`4cd2bed`](https://github.com/Effect-TS/effect/commit/4cd2bedf978f864bddd289d1c524c8e868bf587b), [`6cc6267`](https://github.com/Effect-TS/effect/commit/6cc6267026d9bfb1a9882cddf534787327e86ec1)]:\n  - @effect/schema@0.64.16\n  - @effect/platform@0.48.22\n  - @effect/platform-node@0.45.24\n\n## 0.14.6\n\n### Patch Changes\n\n- [#2421](https://github.com/Effect-TS/effect/pull/2421) [`c34eb3e`](https://github.com/Effect-TS/effect/commit/c34eb3ecae1bc858bd17207b5c82935acc7a95d9) Thanks [@tim-smart](https://github.com/tim-smart)! - don't persist items with a TimeToLive of zero\n\n- Updated dependencies [[`d7688c0`](https://github.com/Effect-TS/effect/commit/d7688c0c72717fe7876c871567f6946dabfc0546), [`b3a4fac`](https://github.com/Effect-TS/effect/commit/b3a4face2acaca422f0b0530436e8f13129f3b3a), [`5ded019`](https://github.com/Effect-TS/effect/commit/5ded019970169e3c1f2a375d0876b95fb1ff67f5)]:\n  - effect@2.4.15\n  - @effect/schema@0.64.15\n  - @effect/platform@0.48.21\n  - @effect/platform-node@0.45.23\n\n## 0.14.5\n\n### Patch Changes\n\n- Updated dependencies [[`4789083`](https://github.com/Effect-TS/effect/commit/4789083283bdaec456982d614ebc4a496ea0e7f7), [`4789083`](https://github.com/Effect-TS/effect/commit/4789083283bdaec456982d614ebc4a496ea0e7f7)]:\n  - @effect/platform-node@0.45.22\n  - @effect/platform@0.48.20\n\n## 0.14.4\n\n### Patch Changes\n\n- Updated dependencies [[`fb7285e`](https://github.com/Effect-TS/effect/commit/fb7285e8d6a70527df7137a6a3efdd03ae61cb8b)]:\n  - @effect/platform-node@0.45.21\n  - @effect/platform@0.48.19\n\n## 0.14.3\n\n### Patch Changes\n\n- Updated dependencies [[`26435ec`](https://github.com/Effect-TS/effect/commit/26435ecfa06569dc18d1801ccf38213a43b7c334), [`a76e5e1`](https://github.com/Effect-TS/effect/commit/a76e5e131a35c88a72771fb745df08f60fbc0e18), [`6180c0c`](https://github.com/Effect-TS/effect/commit/6180c0cc51dee785cfce72220a52c9fc3b9bf9aa)]:\n  - @effect/platform-node@0.45.20\n  - @effect/platform@0.48.18\n  - @effect/schema@0.64.14\n  - effect@2.4.14\n\n## 0.14.2\n\n### Patch Changes\n\n- Updated dependencies [[`47a8f1b`](https://github.com/Effect-TS/effect/commit/47a8f1b644d8294692d92cacd3c8c7543edbfabe), [`8c9abe2`](https://github.com/Effect-TS/effect/commit/8c9abe2b35c46d8891d4b2c14ff9eb46302a14f3), [`8c9abe2`](https://github.com/Effect-TS/effect/commit/8c9abe2b35c46d8891d4b2c14ff9eb46302a14f3), [`3336287`](https://github.com/Effect-TS/effect/commit/3336287ff55a25e56d759b83847bfaa21c40f499), [`54b7c00`](https://github.com/Effect-TS/effect/commit/54b7c0077fa784ad2646b812d6a44641f672edcd), [`3336287`](https://github.com/Effect-TS/effect/commit/3336287ff55a25e56d759b83847bfaa21c40f499), [`47a8f1b`](https://github.com/Effect-TS/effect/commit/47a8f1b644d8294692d92cacd3c8c7543edbfabe)]:\n  - @effect/platform@0.48.17\n  - @effect/platform-node@0.45.19\n  - effect@2.4.13\n  - @effect/schema@0.64.13\n\n## 0.14.1\n\n### Patch Changes\n\n- [#2385](https://github.com/Effect-TS/effect/pull/2385) [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87) Thanks [@tim-smart](https://github.com/tim-smart)! - update typescript to 5.4\n\n- Updated dependencies [[`9392de6`](https://github.com/Effect-TS/effect/commit/9392de6baa6861662abc2bd3171897145f5ea073), [`75a8d16`](https://github.com/Effect-TS/effect/commit/75a8d16247cc14860cdd7fd948ef542c50c2d55e), [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87), [`9392de6`](https://github.com/Effect-TS/effect/commit/9392de6baa6861662abc2bd3171897145f5ea073), [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87), [`d17a427`](https://github.com/Effect-TS/effect/commit/d17a427c4427972fb55c45a058780716dc408631)]:\n  - @effect/schema@0.64.12\n  - @effect/platform-node@0.45.18\n  - @effect/platform@0.48.16\n  - effect@2.4.12\n\n## 0.14.0\n\n### Minor Changes\n\n- [#2383](https://github.com/Effect-TS/effect/pull/2383) [`317b5b8`](https://github.com/Effect-TS/effect/commit/317b5b8e8c8c2207469b3ebfcf72bf3a9f7cbc60) Thanks [@tim-smart](https://github.com/tim-smart)! - add TimeToLive support to Persistence module\n\n### Patch Changes\n\n- [#2384](https://github.com/Effect-TS/effect/pull/2384) [`2f488c4`](https://github.com/Effect-TS/effect/commit/2f488c436de52576562803c57ebc132ef40ccdd8) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n- [#2383](https://github.com/Effect-TS/effect/pull/2383) [`317b5b8`](https://github.com/Effect-TS/effect/commit/317b5b8e8c8c2207469b3ebfcf72bf3a9f7cbc60) Thanks [@tim-smart](https://github.com/tim-smart)! - add TimeToLive module to @effect/experimental\n\n  A trait for attaching expiry information to objects.\n\n  ```ts\n  import * as TimeToLive from \"@effect/experimental\"\n  import { Duration, Exit } from \"effect\"\n\n  class User {\n    [TimeToLive.symbol](exit: Exit.Exit<unknown, unknown>) {\n      return Exit.isSuccess(exit) ? Duration.seconds(60) : Duration.zero\n    }\n  }\n  ```\n\n- [#2383](https://github.com/Effect-TS/effect/pull/2383) [`317b5b8`](https://github.com/Effect-TS/effect/commit/317b5b8e8c8c2207469b3ebfcf72bf3a9f7cbc60) Thanks [@tim-smart](https://github.com/tim-smart)! - add Redis Persistence module\n\n- Updated dependencies [[`2f488c4`](https://github.com/Effect-TS/effect/commit/2f488c436de52576562803c57ebc132ef40ccdd8), [`37ca592`](https://github.com/Effect-TS/effect/commit/37ca592a4101ad90adbf8c8b3f727faf3110cae5), [`317b5b8`](https://github.com/Effect-TS/effect/commit/317b5b8e8c8c2207469b3ebfcf72bf3a9f7cbc60)]:\n  - @effect/platform-node@0.45.17\n  - effect@2.4.11\n  - @effect/schema@0.64.11\n  - @effect/platform@0.48.15\n\n## 0.13.10\n\n### Patch Changes\n\n- Updated dependencies [[`9bab1f9`](https://github.com/Effect-TS/effect/commit/9bab1f9fa5b999740755e4e82485cb77c638643a), [`9bbde5b`](https://github.com/Effect-TS/effect/commit/9bbde5be9a0168d1c2a0308bfc27167ed62f3968)]:\n  - effect@2.4.10\n  - @effect/platform@0.48.14\n  - @effect/platform-node@0.45.16\n  - @effect/schema@0.64.10\n\n## 0.13.9\n\n### Patch Changes\n\n- Updated dependencies [[`dc7e497`](https://github.com/Effect-TS/effect/commit/dc7e49720df416870a7483f48adc40aeb23fe32d), [`ffaf7c3`](https://github.com/Effect-TS/effect/commit/ffaf7c36514f88496cdd2fdfdf0bc7ba5a2e5cd4)]:\n  - @effect/schema@0.64.9\n  - @effect/platform@0.48.13\n  - @effect/platform-node@0.45.15\n\n## 0.13.8\n\n### Patch Changes\n\n- Updated dependencies [[`e0af20e`](https://github.com/Effect-TS/effect/commit/e0af20ec5f6d0b19d66c5ebf610969d55bfc6c22)]:\n  - @effect/schema@0.64.8\n  - @effect/platform@0.48.12\n  - @effect/platform-node@0.45.14\n\n## 0.13.7\n\n### Patch Changes\n\n- Updated dependencies [[`0f6c7b4`](https://github.com/Effect-TS/effect/commit/0f6c7b426eb3432f60e3a17f8cd92ceac91597bf)]:\n  - @effect/platform@0.48.11\n  - @effect/platform-node@0.45.13\n\n## 0.13.6\n\n### Patch Changes\n\n- [#2355](https://github.com/Effect-TS/effect/pull/2355) [`151b785`](https://github.com/Effect-TS/effect/commit/151b7850fa60b066c2bc62602a0ea510ae76c1fa) Thanks [@jrmdayn](https://github.com/jrmdayn)! - Add clear api to remove all items of a result persistence\n\n- Updated dependencies [[`71fd528`](https://github.com/Effect-TS/effect/commit/71fd5287500f9ce155a7d9f0df6ee3e0ac3aeb99)]:\n  - @effect/platform-node@0.45.12\n  - @effect/platform@0.48.10\n  - effect@2.4.9\n  - @effect/schema@0.64.7\n\n## 0.13.5\n\n### Patch Changes\n\n- [#2352](https://github.com/Effect-TS/effect/pull/2352) [`63f8372`](https://github.com/Effect-TS/effect/commit/63f83722b137e2ab7fdf8ef947c65ed107221353) Thanks [@tim-smart](https://github.com/tim-smart)! - remove use of `__proto__`\n\n- Updated dependencies [[`595140a`](https://github.com/Effect-TS/effect/commit/595140a13bda09bf22c669196440868e8a274599), [`5f5fcd9`](https://github.com/Effect-TS/effect/commit/5f5fcd969ae30ed6fe61d566a571498d9e895e16), [`bb0b69e`](https://github.com/Effect-TS/effect/commit/bb0b69e519698c7c76aa68217de423c78ad16566), [`7a45ad0`](https://github.com/Effect-TS/effect/commit/7a45ad0a5f715d64a69b28a8ee3573e5f86909c3), [`5c3b1cc`](https://github.com/Effect-TS/effect/commit/5c3b1ccba182d0f636a973729f9c6bfb12539dc8), [`6f7dfc9`](https://github.com/Effect-TS/effect/commit/6f7dfc9637bd641beb93b14e027dcfcb5d2c8feb), [`88b8583`](https://github.com/Effect-TS/effect/commit/88b85838e03d4f33036f9d16c9c00a487fa99bd8), [`cb20824`](https://github.com/Effect-TS/effect/commit/cb20824416cbf251188395d0aad3622e3a5d7ff2), [`6b20bad`](https://github.com/Effect-TS/effect/commit/6b20badebb3a7ca4d38857753e8ecaa09d02ccfb), [`4e64e9b`](https://github.com/Effect-TS/effect/commit/4e64e9b9876de6bfcbabe39e18a91a08e5f3fbb0), [`3851a02`](https://github.com/Effect-TS/effect/commit/3851a022c481006aec1db36651e4b4fd727aa742), [`5f5fcd9`](https://github.com/Effect-TS/effect/commit/5f5fcd969ae30ed6fe61d566a571498d9e895e16), [`814e5b8`](https://github.com/Effect-TS/effect/commit/814e5b828f68210b9e8f336fd6ac688646835dd9), [`a45a525`](https://github.com/Effect-TS/effect/commit/a45a525e7ccf07704dff1666f1e390282b5bac91)]:\n  - @effect/schema@0.64.6\n  - effect@2.4.8\n  - @effect/platform@0.48.9\n  - @effect/platform-node@0.45.11\n\n## 0.13.4\n\n### Patch Changes\n\n- Updated dependencies [[`69d27bb`](https://github.com/Effect-TS/effect/commit/69d27bb633884b6b50f9c3d9e95c29f09b4860b5), [`d0f56c6`](https://github.com/Effect-TS/effect/commit/d0f56c68e604b1cf8dd4e761a3f3cf3631b3cec1)]:\n  - @effect/platform@0.48.8\n  - @effect/schema@0.64.5\n  - @effect/platform-node@0.45.10\n\n## 0.13.3\n\n### Patch Changes\n\n- Updated dependencies [[`f908948`](https://github.com/Effect-TS/effect/commit/f908948fd05771a670c0b746e2dd9caa9408ef83)]:\n  - @effect/platform@0.48.7\n  - @effect/platform-node@0.45.9\n\n## 0.13.2\n\n### Patch Changes\n\n- Updated dependencies [[`eb93283`](https://github.com/Effect-TS/effect/commit/eb93283985913d7b04ca750e36ac8513e7b6cef6)]:\n  - effect@2.4.7\n  - @effect/platform@0.48.6\n  - @effect/platform-node@0.45.8\n  - @effect/schema@0.64.4\n\n## 0.13.1\n\n### Patch Changes\n\n- Updated dependencies [[`e006e4a`](https://github.com/Effect-TS/effect/commit/e006e4a538c97bae6ca1efa74802159e8a688fcb)]:\n  - @effect/platform@0.48.5\n  - @effect/platform-node@0.45.7\n\n## 0.13.0\n\n### Minor Changes\n\n- [#2323](https://github.com/Effect-TS/effect/pull/2323) [`d6d3f4e`](https://github.com/Effect-TS/effect/commit/d6d3f4ea4c81031876c4e58a016225cc2f5a81ea) Thanks [@tim-smart](https://github.com/tim-smart)! - remove tag argument for Machine serializable procedures\n\n## 0.12.3\n\n### Patch Changes\n\n- Updated dependencies [[`cfef6ec`](https://github.com/Effect-TS/effect/commit/cfef6ecd1fe801cec1a3cbfb7f064fc394b0ad73)]:\n  - @effect/schema@0.64.3\n  - @effect/platform@0.48.4\n  - @effect/platform-node@0.45.6\n\n## 0.12.2\n\n### Patch Changes\n\n- [#2316](https://github.com/Effect-TS/effect/pull/2316) [`7b64c66`](https://github.com/Effect-TS/effect/commit/7b64c662ed7ba6e88146a9cba5b3f46c7213f921) Thanks [@tim-smart](https://github.com/tim-smart)! - support Infinity in DevTools metrics schema\n\n## 0.12.1\n\n### Patch Changes\n\n- Updated dependencies [[`c362e06`](https://github.com/Effect-TS/effect/commit/c362e066550252d5a9fcbc31a4b34d0e17c50699), [`83ddd6f`](https://github.com/Effect-TS/effect/commit/83ddd6f41029724b2cbd144cf309463967ed1164)]:\n  - @effect/platform@0.48.3\n  - @effect/platform-node@0.45.5\n\n## 0.12.0\n\n### Minor Changes\n\n- [#2311](https://github.com/Effect-TS/effect/pull/2311) [`9971186`](https://github.com/Effect-TS/effect/commit/99711862722188fbb5ed3ee75126ad5edf13f72f) Thanks [@tim-smart](https://github.com/tim-smart)! - propogate channel Done type in MsgPack module apis\n\n- [#2311](https://github.com/Effect-TS/effect/pull/2311) [`9971186`](https://github.com/Effect-TS/effect/commit/99711862722188fbb5ed3ee75126ad5edf13f72f) Thanks [@tim-smart](https://github.com/tim-smart)! - use Ndson for DevTools protocol (instead of msgpack)\n\n### Patch Changes\n\n- [#2311](https://github.com/Effect-TS/effect/pull/2311) [`9971186`](https://github.com/Effect-TS/effect/commit/99711862722188fbb5ed3ee75126ad5edf13f72f) Thanks [@tim-smart](https://github.com/tim-smart)! - add Ndjson module to experimental\n\n  Allows you to encode + decode \"new line delimited json\"\n\n- Updated dependencies [[`89748c9`](https://github.com/Effect-TS/effect/commit/89748c90b36cb5eb880a9ab9323b252338dee848), [`4f35a7e`](https://github.com/Effect-TS/effect/commit/4f35a7e7c4eba598924aff24d1158b9056bb24be), [`9971186`](https://github.com/Effect-TS/effect/commit/99711862722188fbb5ed3ee75126ad5edf13f72f)]:\n  - @effect/schema@0.64.2\n  - @effect/platform@0.48.2\n  - effect@2.4.6\n  - @effect/platform-node@0.45.4\n\n## 0.11.1\n\n### Patch Changes\n\n- Updated dependencies [[`d10f876`](https://github.com/Effect-TS/effect/commit/d10f876cd98da275bc5dc5750a91a7fc95e97541), [`743ae6d`](https://github.com/Effect-TS/effect/commit/743ae6d12b249f0b35b31b65b2f7ec91d83ee387), [`a75bc48`](https://github.com/Effect-TS/effect/commit/a75bc48e0e3278d0f70665fedecc5ae7ec447e24), [`bce21c5`](https://github.com/Effect-TS/effect/commit/bce21c5ded2177114666ba229bd5029fa000dee3), [`c7d3036`](https://github.com/Effect-TS/effect/commit/c7d303630b7f0825cb2e584557c5767a67214d9f)]:\n  - @effect/schema@0.64.1\n  - effect@2.4.5\n  - @effect/platform@0.48.1\n  - @effect/platform-node@0.45.3\n\n## 0.11.0\n\n### Minor Changes\n\n- [#2279](https://github.com/Effect-TS/effect/pull/2279) [`bdff193`](https://github.com/Effect-TS/effect/commit/bdff193365dd9ec2863573b08eb960aa8dee5c93) Thanks [@gcanti](https://github.com/gcanti)! - - `src/DevTools/Domain.ts`\n  - use `OptionEncoded` in `SpanFrom`\n  - `src/Machine.ts`\n    - use `ExitEncoded` in `SerializableActor` and `boot`\n\n### Patch Changes\n\n- Updated dependencies [[`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949), [`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949), [`1cb7f9c`](https://github.com/Effect-TS/effect/commit/1cb7f9cff7c2272a32fc7a324d87b02e2cd8a2f5), [`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949), [`817a04c`](https://github.com/Effect-TS/effect/commit/817a04cb2df0f4140984dc97eb3e1bb14a6c4a38), [`d90a99d`](https://github.com/Effect-TS/effect/commit/d90a99d03d074adc7cd2533f15419138264da5a2), [`dd05faa`](https://github.com/Effect-TS/effect/commit/dd05faa621555ef3585ecd914ac13ecd89b710f4), [`509be1a`](https://github.com/Effect-TS/effect/commit/509be1a0817118489750cf028523134677e44a8a), [`1cb7f9c`](https://github.com/Effect-TS/effect/commit/1cb7f9cff7c2272a32fc7a324d87b02e2cd8a2f5), [`dd05faa`](https://github.com/Effect-TS/effect/commit/dd05faa621555ef3585ecd914ac13ecd89b710f4), [`e7ca973`](https://github.com/Effect-TS/effect/commit/e7ca973c5430ae60716701e58bedd4632ff971fd), [`a1f44cb`](https://github.com/Effect-TS/effect/commit/a1f44cb5112713ff9a3ac3d91a63a2c99d6b7fc1), [`d910dd2`](https://github.com/Effect-TS/effect/commit/d910dd2ca1e8e5aa2f09d9bf3694ede745758f99), [`e7ca973`](https://github.com/Effect-TS/effect/commit/e7ca973c5430ae60716701e58bedd4632ff971fd), [`802674b`](https://github.com/Effect-TS/effect/commit/802674b379b7559ad3ff09b33388891445a9e48b), [`bdff193`](https://github.com/Effect-TS/effect/commit/bdff193365dd9ec2863573b08eb960aa8dee5c93)]:\n  - @effect/schema@0.64.0\n  - effect@2.4.4\n  - @effect/platform@0.48.0\n  - @effect/platform-node@0.45.2\n\n## 0.10.1\n\n### Patch Changes\n\n- [#2274](https://github.com/Effect-TS/effect/pull/2274) [`8b552a2`](https://github.com/Effect-TS/effect/commit/8b552a28a3843c5057af342b8bc1534ed804a23d) Thanks [@tim-smart](https://github.com/tim-smart)! - improve Persistence error messages\n\n- Updated dependencies [[`0680545`](https://github.com/Effect-TS/effect/commit/068054540f19bb23a79c7c021ed8b2fe34f3e19f), [`20e63fb`](https://github.com/Effect-TS/effect/commit/20e63fb9207210f3fe2d136ec40d0a2dbff3225e), [`20e63fb`](https://github.com/Effect-TS/effect/commit/20e63fb9207210f3fe2d136ec40d0a2dbff3225e)]:\n  - @effect/platform-node@0.45.1\n  - @effect/platform@0.47.1\n  - effect@2.4.3\n  - @effect/schema@0.63.4\n\n## 0.10.0\n\n### Minor Changes\n\n- [#2261](https://github.com/Effect-TS/effect/pull/2261) [`fa9663c`](https://github.com/Effect-TS/effect/commit/fa9663cb854ca03dba672d7857ecff84f1140c9e) Thanks [@tim-smart](https://github.com/tim-smart)! - move Socket module to platform\n\n### Patch Changes\n\n- [#2246](https://github.com/Effect-TS/effect/pull/2246) [`5234a9a`](https://github.com/Effect-TS/effect/commit/5234a9aa26f4f1732f423dc89c32ac679d065543) Thanks [@tim-smart](https://github.com/tim-smart)! - add support for SpanEvent's to DevTools protocol\n\n- [#2254](https://github.com/Effect-TS/effect/pull/2254) [`98b921a`](https://github.com/Effect-TS/effect/commit/98b921a1cf1c099db02e21b19f11e8ec02b908b5) Thanks [@tim-smart](https://github.com/tim-smart)! - send a final metrics snapshot on DevTools shutdown\n\n- [#2256](https://github.com/Effect-TS/effect/pull/2256) [`f82875f`](https://github.com/Effect-TS/effect/commit/f82875f4e2baca2ddacf5e4fc7efcc9c1ee14f16) Thanks [@tim-smart](https://github.com/tim-smart)! - add Machine module to experimental\n\n  The Machine module can be used to create effectful state machines. Here is an\n  example of a machine that sends emails:\n\n  ```ts\n  import { Machine } from \"@effect/experimental\"\n  import { runMain } from \"@effect/platform-node/NodeRuntime\"\n  import { Data, Effect, List, Request, Schedule } from \"effect\"\n\n  class SendError extends Data.TaggedError(\"SendError\")<{\n    readonly email: string\n    readonly reason: string\n  }> {}\n\n  class SendEmail extends Request.TaggedClass(\"SendEmail\")<\n    void,\n    SendError,\n    {\n      readonly email: string\n      readonly message: string\n    }\n  > {}\n\n  class ProcessEmail extends Request.TaggedClass(\"ProcessEmail\")<\n    void,\n    never,\n    {}\n  > {}\n\n  class Shutdown extends Request.TaggedClass(\"Shutdown\")<void, never, {}> {}\n\n  const mailer = Machine.makeWith<List.List<SendEmail>>()((_, previous) =>\n    Effect.gen(function* (_) {\n      const ctx = yield* _(Machine.MachineContext)\n      const state = previous ?? List.empty()\n\n      if (List.isCons(state)) {\n        yield* _(\n          ctx.unsafeSend(new ProcessEmail()),\n          Effect.replicateEffect(List.size(state))\n        )\n      }\n\n      return Machine.procedures.make(state).pipe(\n        Machine.procedures.addPrivate<ProcessEmail>()(\n          \"ProcessEmail\",\n          ({ state }) =>\n            Effect.gen(function* (_) {\n              if (List.isNil(state)) {\n                return [void 0, state]\n              }\n              const req = state.head\n              yield* _(\n                Effect.log(`Sending email to ${req.email}`),\n                Effect.delay(500)\n              )\n              return [void 0, state.tail]\n            })\n        ),\n        Machine.procedures.add<SendEmail>()(\"SendEmail\", (ctx) =>\n          ctx\n            .send(new ProcessEmail())\n            .pipe(Effect.as([void 0, List.append(ctx.state, ctx.request)]))\n        ),\n        Machine.procedures.add<Shutdown>()(\"Shutdown\", () =>\n          Effect.log(\"Shutting down\").pipe(Effect.zipRight(Effect.interrupt))\n        )\n      )\n    })\n  ).pipe(Machine.retry(Schedule.forever))\n\n  Effect.gen(function* (_) {\n    const actor = yield* _(Machine.boot(mailer))\n    yield* _(\n      actor.send(\n        new SendEmail({ email: \"test@example.com\", message: \"Hello, World!\" })\n      )\n    )\n    yield* _(\n      actor.send(\n        new SendEmail({ email: \"test@example.com\", message: \"Hello, World!\" })\n      )\n    )\n    yield* _(\n      actor.send(\n        new SendEmail({ email: \"test@example.com\", message: \"Hello, World!\" })\n      )\n    )\n    yield* _(actor.send(new Shutdown()))\n  }).pipe(Effect.scoped, runMain)\n  ```\n\n- Updated dependencies [[`e03811e`](https://github.com/Effect-TS/effect/commit/e03811e80c93e986e6348b3b67ac2ed6d5fefff0), [`ac41d84`](https://github.com/Effect-TS/effect/commit/ac41d84776484cdce8165b7ca2c9c9b6377eee2d), [`0f3d99c`](https://github.com/Effect-TS/effect/commit/0f3d99c27521ec6b221b644a0fffc79199c3acca), [`6137533`](https://github.com/Effect-TS/effect/commit/613753300c7705518ab1fea2f370b032851c2750), [`f373529`](https://github.com/Effect-TS/effect/commit/f373529999f4b8bc92b634f6ea14f19271388eed), [`1bf9f31`](https://github.com/Effect-TS/effect/commit/1bf9f31f07667de677673f7c29a4e7a26ebad3c8), [`e3ff789`](https://github.com/Effect-TS/effect/commit/e3ff789226f89e71eb28ca38ce79f90af6a03f1a), [`6137533`](https://github.com/Effect-TS/effect/commit/613753300c7705518ab1fea2f370b032851c2750), [`507ba40`](https://github.com/Effect-TS/effect/commit/507ba4060ff043c1a8d541dae723fa6940633b00), [`4064ea0`](https://github.com/Effect-TS/effect/commit/4064ea04e0b3fa23108ee471cd89ab2482b2f6e5), [`e466afe`](https://github.com/Effect-TS/effect/commit/e466afe32f2de598ceafd8982bd0cfbd388e5671), [`465be79`](https://github.com/Effect-TS/effect/commit/465be7926afe98169837d8a4ed5ebc059a732d21), [`f373529`](https://github.com/Effect-TS/effect/commit/f373529999f4b8bc92b634f6ea14f19271388eed), [`de74eb8`](https://github.com/Effect-TS/effect/commit/de74eb80a79eebde5ff645033765e7a617e92f27), [`d8e6940`](https://github.com/Effect-TS/effect/commit/d8e694040f67da6fefc0f5c98fc8e15c0b48822e), [`fa9663c`](https://github.com/Effect-TS/effect/commit/fa9663cb854ca03dba672d7857ecff84f1140c9e), [`fa9663c`](https://github.com/Effect-TS/effect/commit/fa9663cb854ca03dba672d7857ecff84f1140c9e)]:\n  - effect@2.4.2\n  - @effect/platform@0.47.0\n  - @effect/schema@0.63.3\n  - @effect/platform-node@0.45.0\n\n## 0.9.20\n\n### Patch Changes\n\n- Updated dependencies [[`a4a0006`](https://github.com/Effect-TS/effect/commit/a4a0006c7f19fc261df5cda16963d73457e4d6ac), [`7535080`](https://github.com/Effect-TS/effect/commit/7535080f2e2f9859711031161600c01807cc43ea), [`39f583e`](https://github.com/Effect-TS/effect/commit/39f583eaeb29eecd6eaec3b113b24d9d413153df), [`f428198`](https://github.com/Effect-TS/effect/commit/f428198725d4b9e304ecd5ff8bad8f92d871dbe3), [`0a37676`](https://github.com/Effect-TS/effect/commit/0a37676aa0eb2a21e17af2e6df9f81f52bbc8831), [`bd1d7ac`](https://github.com/Effect-TS/effect/commit/bd1d7ac75eea57a94d5e2d8e1edccb3136e84899), [`c035972`](https://github.com/Effect-TS/effect/commit/c035972dfabdd3cb3372b5ab468aa2fd0d808f4d), [`6f503b7`](https://github.com/Effect-TS/effect/commit/6f503b774d893bf2af34f66202e270d8c45d5f31)]:\n  - effect@2.4.1\n  - @effect/platform@0.46.3\n  - @effect/schema@0.63.2\n  - @effect/platform-node@0.44.11\n\n## 0.9.19\n\n### Patch Changes\n\n- Updated dependencies [[`5d30853`](https://github.com/Effect-TS/effect/commit/5d308534cac6f187227185393c0bac9eb27f90ab), [`6e350ed`](https://github.com/Effect-TS/effect/commit/6e350ed611feb0341e00aafd3c3905cd5ba53f07)]:\n  - @effect/schema@0.63.1\n  - @effect/platform@0.46.2\n  - @effect/platform-node@0.44.10\n\n## 0.9.18\n\n### Patch Changes\n\n- Updated dependencies [[`aa6556f`](https://github.com/Effect-TS/effect/commit/aa6556f007117caea84d6965aa30846a11879e9d)]:\n  - @effect/platform@0.46.1\n  - @effect/platform-node@0.44.9\n\n## 0.9.17\n\n### Patch Changes\n\n- Updated dependencies [[`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2), [`489fcf3`](https://github.com/Effect-TS/effect/commit/489fcf363ff2b2a953166b740cb9a62d7fc2a101), [`7d9c3bf`](https://github.com/Effect-TS/effect/commit/7d9c3bff6c18d451e0e4781042945ec5c7be1b9f), [`d8d278b`](https://github.com/Effect-TS/effect/commit/d8d278b2efb2966947029885e01f7b68348a021f), [`14c5711`](https://github.com/Effect-TS/effect/commit/14c57110078f0862b8da5c7a2c5d980f54447484), [`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2), [`54ddbb7`](https://github.com/Effect-TS/effect/commit/54ddbb720aeeb657537b01ae221cdcd5e919c1a6), [`b9cb3a9`](https://github.com/Effect-TS/effect/commit/b9cb3a9c9bfdd75536bd70b4e8b557c12d4923ff), [`585fcce`](https://github.com/Effect-TS/effect/commit/585fcce162d0f07a48d7cd984a9b722966fbebbe), [`93b412d`](https://github.com/Effect-TS/effect/commit/93b412d4a9ed762dc9fa5807e51fad0fc78a614a), [`55b26a6`](https://github.com/Effect-TS/effect/commit/55b26a6342b4826f1116e7a1eb660118c274458e), [`136ef40`](https://github.com/Effect-TS/effect/commit/136ef40fe4a394abfa5c6a7ec103eea57251423e), [`a025b12`](https://github.com/Effect-TS/effect/commit/a025b121235ba01cfce8d62a775491880c575561), [`2097739`](https://github.com/Effect-TS/effect/commit/20977393d2383bff709304e81ec7d51cafd57108), [`f24ac9f`](https://github.com/Effect-TS/effect/commit/f24ac9f0c2c520add58f09fbdcec5defda03bd52)]:\n  - effect@2.4.0\n  - @effect/platform@0.46.0\n  - @effect/schema@0.63.0\n  - @effect/platform-node@0.44.8\n\n## 0.9.16\n\n### Patch Changes\n\n- [#2187](https://github.com/Effect-TS/effect/pull/2187) [`e6d36c0`](https://github.com/Effect-TS/effect/commit/e6d36c0813d836f17eabb6a9c7849baffca12dbf) Thanks [@tim-smart](https://github.com/tim-smart)! - update development dependencies\n\n- Updated dependencies [[`5ad2eec`](https://github.com/Effect-TS/effect/commit/5ad2eece0280b6db6a749d25cac1dcf6d33659a9), [`e6d36c0`](https://github.com/Effect-TS/effect/commit/e6d36c0813d836f17eabb6a9c7849baffca12dbf)]:\n  - effect@2.3.8\n  - @effect/platform-node@0.44.7\n  - @effect/schema@0.62.9\n  - @effect/platform@0.45.6\n\n## 0.9.15\n\n### Patch Changes\n\n- Updated dependencies [[`6daf084`](https://github.com/Effect-TS/effect/commit/6daf0845de008772011db8d7c75b7c37a6b4d334)]:\n  - @effect/platform@0.45.5\n  - @effect/platform-node@0.44.6\n\n## 0.9.14\n\n### Patch Changes\n\n- [#2163](https://github.com/Effect-TS/effect/pull/2163) [`ca2b411`](https://github.com/Effect-TS/effect/commit/ca2b411e3c11ddb19d2321c7266049b7f4115617) Thanks [@IMax153](https://github.com/IMax153)! - Fix the order in which the experimental data-loader's internal worker enables interruptibility\n\n- Updated dependencies [[`bc8404d`](https://github.com/Effect-TS/effect/commit/bc8404d54fd42072d200c0399cb39672837afa9f), [`abcb7d9`](https://github.com/Effect-TS/effect/commit/abcb7d983a4a85b43b7175e952f5b331b9019aea), [`2c5cbcd`](https://github.com/Effect-TS/effect/commit/2c5cbcd1161b4f40dab184999291e817314107de), [`6565916`](https://github.com/Effect-TS/effect/commit/6565916ef254bf910e47d25fd0ef55e7cb420241), [`abcb7d9`](https://github.com/Effect-TS/effect/commit/abcb7d983a4a85b43b7175e952f5b331b9019aea)]:\n  - effect@2.3.7\n  - @effect/platform@0.45.4\n  - @effect/platform-node@0.44.5\n  - @effect/schema@0.62.8\n\n## 0.9.13\n\n### Patch Changes\n\n- Updated dependencies [[`09532a8`](https://github.com/Effect-TS/effect/commit/09532a86b7d0cc23557c89158f0342753dfce4b0)]:\n  - @effect/platform@0.45.3\n  - @effect/platform-node@0.44.4\n\n## 0.9.12\n\n### Patch Changes\n\n- Updated dependencies [[`f612749`](https://github.com/Effect-TS/effect/commit/f612749ddfff40cadef3387100135f2cb9a4a9f3)]:\n  - @effect/platform-node@0.44.3\n\n## 0.9.11\n\n### Patch Changes\n\n- Updated dependencies [[`b1163b2`](https://github.com/Effect-TS/effect/commit/b1163b2bd67b65bafbbb39fc4c67576e5cbaf444), [`b46b869`](https://github.com/Effect-TS/effect/commit/b46b869e59a6da5aa235a9fcc25e1e0d24e9e8f8), [`dbff62c`](https://github.com/Effect-TS/effect/commit/dbff62c3026054350a671f6210058ec5844c285e), [`de1b226`](https://github.com/Effect-TS/effect/commit/de1b226282b5ab6c2809dd93f3bdb066f24a1333), [`a663390`](https://github.com/Effect-TS/effect/commit/a66339090ae7b960f8a8b90a0dcdc505de5aaf3e), [`ff88f80`](https://github.com/Effect-TS/effect/commit/ff88f808c4ed9947a148045849e7410b00acad0a), [`11be07b`](https://github.com/Effect-TS/effect/commit/11be07bf65d82cfdf994cdb9d8ca937f995cb4f0), [`c568645`](https://github.com/Effect-TS/effect/commit/c5686451c87d26382135a1c63b00ef171bb24f62), [`88835e5`](https://github.com/Effect-TS/effect/commit/88835e575a0bfbeff9a3696a332f32192c940e12), [`e572b07`](https://github.com/Effect-TS/effect/commit/e572b076e9b4369d9cc8e55414006eef376c93d9), [`e787a57`](https://github.com/Effect-TS/effect/commit/e787a5772e30d8b840cb98b49d36996e7d659a6c), [`b415577`](https://github.com/Effect-TS/effect/commit/b415577f6c576073733929c858e5aac27b6d5880), [`ff8046f`](https://github.com/Effect-TS/effect/commit/ff8046f57dfd073eba60ce6d3144ab060fbf93ce), [`44c3b43`](https://github.com/Effect-TS/effect/commit/44c3b43653e64d7e425d39815d8ff405acec9b99)]:\n  - effect@2.3.6\n  - @effect/schema@0.62.7\n  - @effect/platform@0.45.2\n  - @effect/platform-node@0.44.2\n\n## 0.9.10\n\n### Patch Changes\n\n- Updated dependencies [[`65895ab`](https://github.com/Effect-TS/effect/commit/65895ab982e0917ac92f0827e387e7cf61be1e69)]:\n  - @effect/platform@0.45.1\n  - @effect/platform-node@0.44.1\n\n## 0.9.9\n\n### Patch Changes\n\n- Updated dependencies [[`2b62548`](https://github.com/Effect-TS/effect/commit/2b6254845882f399636d24223c483e5489e3cff4)]:\n  - @effect/platform-node@0.44.0\n  - @effect/platform@0.45.0\n\n## 0.9.8\n\n### Patch Changes\n\n- Updated dependencies [[`aef2b8b`](https://github.com/Effect-TS/effect/commit/aef2b8bb636ada07224dc9cf491bebe622c1aeda), [`b881365`](https://github.com/Effect-TS/effect/commit/b8813650355322ea2fc1fbaa4f846bd87a7a05f3), [`7eecb1c`](https://github.com/Effect-TS/effect/commit/7eecb1c6cebe36550df3cca85a46867adbcaa2ca)]:\n  - @effect/schema@0.62.6\n  - effect@2.3.5\n  - @effect/platform@0.44.7\n  - @effect/platform-node@0.43.7\n\n## 0.9.7\n\n### Patch Changes\n\n- [#2115](https://github.com/Effect-TS/effect/pull/2115) [`ec78c95`](https://github.com/Effect-TS/effect/commit/ec78c9566bcbe55222a3ba676ed196d5528f1b7b) Thanks [@tim-smart](https://github.com/tim-smart)! - fix Persistence KeyValueStore adapter\n\n## 0.9.6\n\n### Patch Changes\n\n- Updated dependencies [[`17bda66`](https://github.com/Effect-TS/effect/commit/17bda66431c999a546920c10adb205e6c8bea7d1)]:\n  - effect@2.3.4\n  - @effect/platform@0.44.6\n  - @effect/platform-node@0.43.6\n  - @effect/schema@0.62.5\n\n## 0.9.5\n\n### Patch Changes\n\n- Updated dependencies [[`1c6d18b`](https://github.com/Effect-TS/effect/commit/1c6d18b422b0bd800f2ed036dba9cb78db296c03), [`13d3266`](https://github.com/Effect-TS/effect/commit/13d3266f331f7aa49b55dd244d4e749a82255274), [`a344b42`](https://github.com/Effect-TS/effect/commit/a344b420862f71532a28c72f00b7ba54776d744d)]:\n  - @effect/schema@0.62.4\n  - @effect/platform@0.44.5\n  - @effect/platform-node@0.43.5\n\n## 0.9.4\n\n### Patch Changes\n\n- [#2106](https://github.com/Effect-TS/effect/pull/2106) [`b7d9a55`](https://github.com/Effect-TS/effect/commit/b7d9a55ebb3db5c1d64a2c75c5b1f12ebe1faf39) Thanks [@tim-smart](https://github.com/tim-smart)! - don't require tags for Persistence keys\n\n- Updated dependencies [[`efd41d8`](https://github.com/Effect-TS/effect/commit/efd41d8131c3d90867608969ef7c4eef490eb5e6), [`0f83515`](https://github.com/Effect-TS/effect/commit/0f83515a9c01d13c7c15a3f026e02d22c3c6bb7f), [`0f83515`](https://github.com/Effect-TS/effect/commit/0f83515a9c01d13c7c15a3f026e02d22c3c6bb7f)]:\n  - effect@2.3.3\n  - @effect/platform@0.44.4\n  - @effect/platform-node@0.43.4\n  - @effect/schema@0.62.3\n\n## 0.9.3\n\n### Patch Changes\n\n- Updated dependencies [[`6654f5f`](https://github.com/Effect-TS/effect/commit/6654f5f0f6b9d97165ede5e04ca16776e2599328), [`2eb11b4`](https://github.com/Effect-TS/effect/commit/2eb11b47752cedf233ef4c4395d9c4efc9b9e180), [`56c09bd`](https://github.com/Effect-TS/effect/commit/56c09bd369279a6a7785209d172739935818cba6), [`71aa5b1`](https://github.com/Effect-TS/effect/commit/71aa5b1c180dcb8b53aefe232d12a97bd06b5447), [`1700af8`](https://github.com/Effect-TS/effect/commit/1700af8af1131602887da721914c8562b6342393)]:\n  - effect@2.3.2\n  - @effect/platform@0.44.3\n  - @effect/platform-node@0.43.3\n  - @effect/schema@0.62.2\n\n## 0.9.2\n\n### Patch Changes\n\n- Updated dependencies [[`29739dd`](https://github.com/Effect-TS/effect/commit/29739dde8e6232824d49c4c7f8856de245249c5c)]:\n  - @effect/platform@0.44.2\n  - @effect/platform-node@0.43.2\n\n## 0.9.1\n\n### Patch Changes\n\n- Updated dependencies [[`b5a8215`](https://github.com/Effect-TS/effect/commit/b5a8215ee2a97a8865d69ee55ce1b9835948c922)]:\n  - effect@2.3.1\n  - @effect/platform@0.44.1\n  - @effect/platform-node@0.43.1\n  - @effect/schema@0.62.1\n\n## 0.9.0\n\n### Minor Changes\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c) Thanks [@github-actions](https://github.com/apps/github-actions)! - With this change we now require a string key to be provided for all tags and renames the dear old `Tag` to `GenericTag`, so when previously you could do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  interface Service {\n    readonly _: unique symbol\n  }\n  const Service = Context.Tag<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >()\n  ```\n\n  you are now mandated to do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  interface Service {\n    readonly _: unique symbol\n  }\n  const Service = Context.GenericTag<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >(\"Service\")\n  ```\n\n  This makes by default all tags globals and ensures better debuggaility when unexpected errors arise.\n\n  Furthermore we introduce a new way of constructing tags that should be considered the new default:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  class Service extends Context.Tag(\"Service\")<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >() {}\n\n  const program = Effect.flatMap(Service, ({ number }) => number).pipe(\n    Effect.flatMap((_) => Effect.log(`number: ${_}`))\n  )\n  ```\n\n  this will use \"Service\" as the key and will create automatically an opaque identifier (the class) to be used at the type level, it does something similar to the above in a single shot.\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`1a77f72`](https://github.com/Effect-TS/effect/commit/1a77f72cdaf43d6cdc91b6060f82832edcdbbcb3) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Effect` type parameters order from `Effect<R, E, A>` to `Effect<A, E = never, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`a34dbdc`](https://github.com/Effect-TS/effect/commit/a34dbdc1552c73c1b612676f262a0c735ce444a7) Thanks [@github-actions](https://github.com/apps/github-actions)! - - Schema: change type parameters order from `Schema<R, I, A>` to `Schema<A, I = A, R = never>`\n  - Serializable: change type parameters order from `Serializable<R, I, A>` to `Serializable<A, I, R>`\n  - Class: change type parameters order from `Class<R, I, A, C, Self, Inherited>` to `Class<A, I, R, C, Self, Inherited>`\n  - PropertySignature: change type parameters order from `PropertySignature<R, From, FromIsOptional, To, ToIsOptional>` to `PropertySignature<From, FromIsOptional, To, ToIsOptional, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`b1e2086`](https://github.com/Effect-TS/effect/commit/b1e2086ea8bf410e4ad75d71c0760825924e8f9f) Thanks [@github-actions](https://github.com/apps/github-actions)! - remove re-exports from platform packages\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c) Thanks [@github-actions](https://github.com/apps/github-actions)! - This change enables `Effect.serviceConstants` and `Effect.serviceMembers` to access any constant in the service, not only the effects, namely it is now possible to do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n\n  class NumberRepo extends Context.TagClass(\"NumberRepo\")<\n    NumberRepo,\n    {\n      readonly numbers: Array<number>\n    }\n  >() {\n    static numbers = Effect.serviceConstants(NumberRepo).numbers\n  }\n  ```\n\n### Patch Changes\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`2131a8c`](https://github.com/Effect-TS/effect/commit/2131a8cfd2b7570ace56591fd7da4b3a856ab531) Thanks [@github-actions](https://github.com/apps/github-actions)! - encode per chunk in MsgPack.pack/unpack\n\n- Updated dependencies [[`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`b1e2086`](https://github.com/Effect-TS/effect/commit/b1e2086ea8bf410e4ad75d71c0760825924e8f9f), [`4cd6e14`](https://github.com/Effect-TS/effect/commit/4cd6e144945b6c398f5f5abe3471ff7fb3372bfd), [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`c77f635`](https://github.com/Effect-TS/effect/commit/c77f635f8a26ca6d83cb569d911f8eee79033fd9), [`e343a74`](https://github.com/Effect-TS/effect/commit/e343a74843dd9edf879417fa94cb51de7ed5b402), [`acf1894`](https://github.com/Effect-TS/effect/commit/acf1894f45945dbe5c39451e36aabb4b5092f257), [`9dc04c8`](https://github.com/Effect-TS/effect/commit/9dc04c88a2ea9c68122cb2632a76f0f4be40329a), [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c), [`1a77f72`](https://github.com/Effect-TS/effect/commit/1a77f72cdaf43d6cdc91b6060f82832edcdbbcb3), [`af47aa3`](https://github.com/Effect-TS/effect/commit/af47aa37196ad542c9c23a4896d8ef98147e1205), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`c986f0e`](https://github.com/Effect-TS/effect/commit/c986f0e0ce4d22ba08177ed351152718479ab63c), [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`70dde23`](https://github.com/Effect-TS/effect/commit/70dde238f81125e353fd7bde5fc24ecd8969bf97), [`a34dbdc`](https://github.com/Effect-TS/effect/commit/a34dbdc1552c73c1b612676f262a0c735ce444a7), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`81b7425`](https://github.com/Effect-TS/effect/commit/81b7425320cbbe2a6cf547a3e3ab3549cdba14cf), [`b1e2086`](https://github.com/Effect-TS/effect/commit/b1e2086ea8bf410e4ad75d71c0760825924e8f9f), [`02c3461`](https://github.com/Effect-TS/effect/commit/02c34615d02f91269ea04036d0306fccf4e39e18), [`0e56e99`](https://github.com/Effect-TS/effect/commit/0e56e998ab9815c4d096c239a553cb86a0f99af9), [`8b0ded9`](https://github.com/Effect-TS/effect/commit/8b0ded9f10ba0d96fcb9af24eff2dbd9341f85e3), [`8dd83e8`](https://github.com/Effect-TS/effect/commit/8dd83e854bfcaa6dab876994c5f813dcfb486c28), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e), [`d75f6fe`](https://github.com/Effect-TS/effect/commit/d75f6fe6499deb0a5ee9ec94af3b5fd4eb03a2d0), [`7356e5c`](https://github.com/Effect-TS/effect/commit/7356e5cc16e9d70f18c02dee1dcb4ad539fd130a), [`3077cde`](https://github.com/Effect-TS/effect/commit/3077cde08a60246821a940964a84dd7f7c8b9f54), [`be19ce0`](https://github.com/Effect-TS/effect/commit/be19ce0b8bdf1fac80bb8d7e0b06a86986b47409), [`4a5d01a`](https://github.com/Effect-TS/effect/commit/4a5d01a409e9b6dd53893e65f8e5c9247f568021), [`78f47ab`](https://github.com/Effect-TS/effect/commit/78f47abfe3cb0a8bbde818b1c5fc603270538b47), [`6361ee2`](https://github.com/Effect-TS/effect/commit/6361ee2e83bdfead24045c3d058a7298efc18113), [`52e5d20`](https://github.com/Effect-TS/effect/commit/52e5d2077582bf51f25861c7139fc920c2c24166), [`c6137ec`](https://github.com/Effect-TS/effect/commit/c6137ec62c6b5542d5062ae1a3c936cb915dee22), [`86f665d`](https://github.com/Effect-TS/effect/commit/86f665d7bd25ba0a3f046a2384798378310dcf0c), [`f5ae081`](https://github.com/Effect-TS/effect/commit/f5ae08195e68e76faeac258c565d79da4e01e7d6), [`4a5d01a`](https://github.com/Effect-TS/effect/commit/4a5d01a409e9b6dd53893e65f8e5c9247f568021), [`60686f5`](https://github.com/Effect-TS/effect/commit/60686f5c38bef1b93a3a0dda9b6596d46aceab03), [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e), [`56b8691`](https://github.com/Effect-TS/effect/commit/56b86916bf3da18002f3655d859dbc487eb5a6de), [`8ee2931`](https://github.com/Effect-TS/effect/commit/8ee293159b4f7cb7af8558287a0a047f3a69743d), [`6727474`](https://github.com/Effect-TS/effect/commit/672747497490a30d36dd49c06db19aabf09dc7f0), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e)]:\n  - effect@2.3.0\n  - @effect/platform@0.44.0\n  - @effect/schema@0.62.0\n  - @effect/platform-node@0.43.0\n\n## 0.8.10\n\n### Patch Changes\n\n- Updated dependencies [[`3ddfdbf`](https://github.com/Effect-TS/effect/commit/3ddfdbf914edea536aef207cec6695f33496258c), [`3ddfdbf`](https://github.com/Effect-TS/effect/commit/3ddfdbf914edea536aef207cec6695f33496258c)]:\n  - effect@2.2.5\n  - @effect/platform@0.43.11\n  - @effect/platform-node@0.42.11\n  - @effect/schema@0.61.7\n\n## 0.8.9\n\n### Patch Changes\n\n- Updated dependencies [[`d0b911c`](https://github.com/Effect-TS/effect/commit/d0b911c75f284c7aa87f25aa96926e6bde7690d0), [`330e1a4`](https://github.com/Effect-TS/effect/commit/330e1a4e2c1fc0af6c80c80c81dd38c3e50fab78), [`6928a2b`](https://github.com/Effect-TS/effect/commit/6928a2b0bae86a4bdfbece0aa32924207c2d5a70), [`296bc1c`](https://github.com/Effect-TS/effect/commit/296bc1c9d24986d299d2669115d584cb27b73c60)]:\n  - effect@2.2.4\n  - @effect/platform@0.43.10\n  - @effect/schema@0.61.6\n  - @effect/platform-node@0.42.10\n\n## 0.8.8\n\n### Patch Changes\n\n- Updated dependencies [[`1b841a9`](https://github.com/Effect-TS/effect/commit/1b841a91fed86825cd2867cf1e68e41d8ff26b4e)]:\n  - @effect/platform@0.43.9\n  - @effect/platform-node@0.42.9\n\n## 0.8.7\n\n### Patch Changes\n\n- Updated dependencies [[`32bf796`](https://github.com/Effect-TS/effect/commit/32bf796c3e5db1b2b68e8b1b20db664295991643)]:\n  - @effect/platform@0.43.8\n  - @effect/platform-node@0.42.8\n\n## 0.8.6\n\n### Patch Changes\n\n- Updated dependencies [[`cde08f3`](https://github.com/Effect-TS/effect/commit/cde08f354ed2ff2921d1d98bd539c7d65a2ddd73)]:\n  - @effect/platform@0.43.7\n  - @effect/platform-node@0.42.7\n\n## 0.8.5\n\n### Patch Changes\n\n- Updated dependencies [[`c96bb17`](https://github.com/Effect-TS/effect/commit/c96bb17043e2cec1eaeb319614a4c2904d876beb)]:\n  - @effect/platform@0.43.6\n  - @effect/platform-node@0.42.6\n\n## 0.8.4\n\n### Patch Changes\n\n- Updated dependencies [[`f1ff44b`](https://github.com/Effect-TS/effect/commit/f1ff44b58cdb1886b38681e8fedc309eb9ac6853), [`13785cf`](https://github.com/Effect-TS/effect/commit/13785cf4a5082d8d9cf8d7c991141dee0d2b4d31)]:\n  - @effect/schema@0.61.5\n  - @effect/platform@0.43.5\n  - @effect/platform-node@0.42.5\n\n## 0.8.3\n\n### Patch Changes\n\n- [#1999](https://github.com/Effect-TS/effect/pull/1999) [`78f5921`](https://github.com/Effect-TS/effect/commit/78f59211502ded6fcbe15a49d6fde941cccc9d52) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure forked fibers are interruptible\n\n- Updated dependencies [[`22794e0`](https://github.com/Effect-TS/effect/commit/22794e0ba00e40281f30a22fa84412003c24877d), [`f73e6c0`](https://github.com/Effect-TS/effect/commit/f73e6c033fb0729a9cfa5eb4bc39f79d3126e247), [`6bf02c7`](https://github.com/Effect-TS/effect/commit/6bf02c70fe10a04d1b34d6666f95416e42a6225a), [`78f5921`](https://github.com/Effect-TS/effect/commit/78f59211502ded6fcbe15a49d6fde941cccc9d52)]:\n  - effect@2.2.3\n  - @effect/schema@0.61.4\n  - @effect/platform-node@0.42.4\n  - @effect/platform@0.43.4\n\n## 0.8.2\n\n### Patch Changes\n\n- Updated dependencies [[`9863e2f`](https://github.com/Effect-TS/effect/commit/9863e2fb3561dc019965aeccd6584a418fc8b401)]:\n  - @effect/schema@0.61.3\n  - @effect/platform@0.43.3\n  - @effect/platform-node@0.42.3\n\n## 0.8.1\n\n### Patch Changes\n\n- Updated dependencies [[`64f710a`](https://github.com/Effect-TS/effect/commit/64f710aa49dec6ffcd33ee23438d0774f5489733)]:\n  - @effect/schema@0.61.2\n  - @effect/platform@0.43.2\n  - @effect/platform-node@0.42.2\n\n## 0.8.0\n\n### Minor Changes\n\n- [#1985](https://github.com/Effect-TS/effect/pull/1985) [`634af60`](https://github.com/Effect-TS/effect/commit/634af60a2f9d407f42357edc29ca4c14a005fdf9) Thanks [@tim-smart](https://github.com/tim-smart)! - add lmdb implementation of persistence\n\n## 0.7.2\n\n### Patch Changes\n\n- Updated dependencies [[`c7550f9`](https://github.com/Effect-TS/effect/commit/c7550f96e1006eee832ce5025bf0c197a65935ea), [`8d1f6e4`](https://github.com/Effect-TS/effect/commit/8d1f6e4bb13e221804fb1762ef19e02bcefc8f61), [`d404561`](https://github.com/Effect-TS/effect/commit/d404561e47ec2fa5f68709a308ee5d2ee959141d), [`7b84a3c`](https://github.com/Effect-TS/effect/commit/7b84a3c7e4b9c8dc02294b0e3cc3ae3becea977b), [`1a84dee`](https://github.com/Effect-TS/effect/commit/1a84dee0e9ddbfaf2610e4d7c00c7020c427171a), [`ac30bf4`](https://github.com/Effect-TS/effect/commit/ac30bf4cd53de0663784f65ae6bee8279333df97)]:\n  - @effect/schema@0.61.1\n  - effect@2.2.2\n  - @effect/platform@0.43.1\n  - @effect/platform-node@0.42.1\n\n## 0.7.1\n\n### Patch Changes\n\n- [#1968](https://github.com/Effect-TS/effect/pull/1968) [`fdf7b0e`](https://github.com/Effect-TS/effect/commit/fdf7b0e6647419fb70e18be64b60e652de42e97d) Thanks [@IMax153](https://github.com/IMax153)! - ensure data-loader worker fiber can be interrupted if forked in an uninterruptible region\n\n## 0.7.0\n\n### Minor Changes\n\n- [#1922](https://github.com/Effect-TS/effect/pull/1922) [`62b40e8`](https://github.com/Effect-TS/effect/commit/62b40e8479371d6663c0255aaca56a1ae0d59764) Thanks [@gcanti](https://github.com/gcanti)! - add context tracking to Schema, closes #1873\n\n### Patch Changes\n\n- Updated dependencies [[`84da31f`](https://github.com/Effect-TS/effect/commit/84da31f0643e8651b9d311b30526b1e4edfbdfb8), [`62b40e8`](https://github.com/Effect-TS/effect/commit/62b40e8479371d6663c0255aaca56a1ae0d59764), [`645bea2`](https://github.com/Effect-TS/effect/commit/645bea2551129f94a5b0e38347e28067dee531bb), [`62b40e8`](https://github.com/Effect-TS/effect/commit/62b40e8479371d6663c0255aaca56a1ae0d59764)]:\n  - effect@2.2.1\n  - @effect/schema@0.61.0\n  - @effect/platform-node@0.42.0\n  - @effect/platform@0.43.0\n\n## 0.6.11\n\n### Patch Changes\n\n- Updated dependencies [[`202befc`](https://github.com/Effect-TS/effect/commit/202befc2ecbeb117c4fa85ef9b12a3d3a48273d2), [`fe05ad7`](https://github.com/Effect-TS/effect/commit/fe05ad7bcb3b88d47800ab69ebf53641023676f1), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`10df798`](https://github.com/Effect-TS/effect/commit/10df798639e556f9d88265ef7fc3cf8a3bbe3874)]:\n  - effect@2.2.0\n  - @effect/platform@0.42.7\n  - @effect/platform-node@0.41.8\n  - @effect/schema@0.60.7\n\n## 0.6.10\n\n### Patch Changes\n\n- Updated dependencies [[`21b9edd`](https://github.com/Effect-TS/effect/commit/21b9edde464f7c5624ef54ad1b5e264204a37625)]:\n  - effect@2.1.2\n  - @effect/platform@0.42.6\n  - @effect/platform-node@0.41.7\n  - @effect/schema@0.60.6\n\n## 0.6.9\n\n### Patch Changes\n\n- Updated dependencies [[`3bf67cf`](https://github.com/Effect-TS/effect/commit/3bf67cf64ff27ffaa811b07751875cb161ac3385)]:\n  - @effect/schema@0.60.5\n  - @effect/platform@0.42.5\n  - @effect/platform-node@0.41.6\n\n## 0.6.8\n\n### Patch Changes\n\n- Updated dependencies [[`0d1af1e`](https://github.com/Effect-TS/effect/commit/0d1af1e38c11b94e152beaccd0ff7569a1b3f5b7), [`0d1af1e`](https://github.com/Effect-TS/effect/commit/0d1af1e38c11b94e152beaccd0ff7569a1b3f5b7), [`a222524`](https://github.com/Effect-TS/effect/commit/a2225247e9de2e013d287320790fde88c081dbbd)]:\n  - @effect/schema@0.60.4\n  - effect@2.1.1\n  - @effect/platform@0.42.4\n  - @effect/platform-node@0.41.5\n\n## 0.6.7\n\n### Patch Changes\n\n- Updated dependencies [[`d543221`](https://github.com/Effect-TS/effect/commit/d5432213e91ab620aa66e0fd92a6593134d18940), [`2530d47`](https://github.com/Effect-TS/effect/commit/2530d470b0ad5df7e636921eedfb1cbe42821f94), [`f493929`](https://github.com/Effect-TS/effect/commit/f493929ab88d2ea137ca5fbff70bdc6c9d804d80), [`5911fa9`](https://github.com/Effect-TS/effect/commit/5911fa9c9440dd3bc1ee38542bcd15f8c75a4637)]:\n  - @effect/schema@0.60.3\n  - @effect/platform@0.42.3\n  - @effect/platform-node@0.41.4\n\n## 0.6.6\n\n### Patch Changes\n\n- [#1926](https://github.com/Effect-TS/effect/pull/1926) [`169bc30`](https://github.com/Effect-TS/effect/commit/169bc3011ef8001fb75d844a46d8b7954131451b) Thanks [@tim-smart](https://github.com/tim-smart)! - use sliding queue for DevTools client\n\n## 0.6.5\n\n### Patch Changes\n\n- Updated dependencies [[`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02)]:\n  - effect@2.1.0\n  - @effect/platform@0.42.2\n  - @effect/platform-node@0.41.3\n  - @effect/schema@0.60.2\n\n## 0.6.4\n\n### Patch Changes\n\n- Updated dependencies [[`f7f19f6`](https://github.com/Effect-TS/effect/commit/f7f19f66a5fa349baa2412c1f9f15111c437df09)]:\n  - effect@2.0.5\n  - @effect/platform@0.42.1\n  - @effect/platform-node@0.41.2\n  - @effect/schema@0.60.1\n\n## 0.6.3\n\n### Patch Changes\n\n- Updated dependencies [[`ec2bdfa`](https://github.com/Effect-TS/effect/commit/ec2bdfae2da717f28147b9d6820d3494cb240945), [`687e02e`](https://github.com/Effect-TS/effect/commit/687e02e7d84dc06957844160761fda90929470ab), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`540b294`](https://github.com/Effect-TS/effect/commit/540b2941dd0a81e9688311583ce7e2e140d6e7a5), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`a3f96d6`](https://github.com/Effect-TS/effect/commit/a3f96d615b8b3e238dbfa01ef713c87e6f4532be), [`71ed54c`](https://github.com/Effect-TS/effect/commit/71ed54c3fbb1ead5da2776bc6207050cb073ada4), [`0c397e7`](https://github.com/Effect-TS/effect/commit/0c397e762008a0de40c7526c9d99ff2cfe4f7a6a), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`b557a10`](https://github.com/Effect-TS/effect/commit/b557a10b773e321bea77fc4951f0ef171dd193c9), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`74b9094`](https://github.com/Effect-TS/effect/commit/74b90940e571c73a6b76cafa88ffb8a1c949cb4c), [`337e80f`](https://github.com/Effect-TS/effect/commit/337e80f69bc36966f889c439b819db2f84cae496), [`25adce7`](https://github.com/Effect-TS/effect/commit/25adce7ae76ce834096dca1ed70a60ad1a349217), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`48a3d40`](https://github.com/Effect-TS/effect/commit/48a3d40aed0f923f567b8911dade732ff472d981)]:\n  - @effect/schema@0.60.0\n  - effect@2.0.4\n  - @effect/platform-node@0.41.1\n  - @effect/platform@0.42.0\n\n## 0.6.2\n\n### Patch Changes\n\n- Updated dependencies [[`5b46e99`](https://github.com/Effect-TS/effect/commit/5b46e996d30e2497eb23095e2c21eee04438edf5), [`87f7ef2`](https://github.com/Effect-TS/effect/commit/87f7ef28a3c27e2e4f2fcfa465f85bb2a45a3d6b), [`1d3a06b`](https://github.com/Effect-TS/effect/commit/1d3a06bb58ad1ac123ae8f9d42b4345f9c9c53c0), [`210d27e`](https://github.com/Effect-TS/effect/commit/210d27e999e066ea9b907301150c65f9ff080b39), [`1d3a06b`](https://github.com/Effect-TS/effect/commit/1d3a06bb58ad1ac123ae8f9d42b4345f9c9c53c0)]:\n  - @effect/schema@0.59.1\n  - effect@2.0.3\n  - @effect/platform-node@0.41.0\n  - @effect/platform@0.41.0\n\n## 0.6.1\n\n### Patch Changes\n\n- Updated dependencies [[`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f), [`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f), [`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f), [`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f)]:\n  - @effect/schema@0.59.0\n  - @effect/platform@0.40.4\n  - @effect/platform-node@0.40.4\n\n## 0.6.0\n\n### Minor Changes\n\n- [#1842](https://github.com/Effect-TS/effect/pull/1842) [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c) Thanks [@fubhy](https://github.com/fubhy)! - Schema: refactor `ParseResult` module:\n  - add `Union` issue, and replace `UnionMember` with `Union`\n  - add `Tuple` issue, and replace `Index` with `Tuple`\n  - add `TypeLiteral` issue\n  - add `Transform` issue\n  - add `Refinement` issue\n  - add `ast` field to `Member`\n  - rename `UnionMember` to `Member`\n  - `Type`: rename `expected` to `ast`\n  - `ParseError` replace `errors` field with `error` field and refactor `parseError` constructor accordingly\n  - `Index` replace `errors` field with `error` field\n  - `Key` replace `errors` field with `error` field\n  - `Member` replace `errors` field with `error` field\n  - `ParseError` replace `errors` field with `error` field\n  - make `ParseError` a `Data.TaggedError`\n  - `Forbidden`: add `actual` field\n\n### Patch Changes\n\n- Updated dependencies [[`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`a904a73`](https://github.com/Effect-TS/effect/commit/a904a739459bfd0fa7844b00b902d2fa984fb014), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`92c0322`](https://github.com/Effect-TS/effect/commit/92c0322a58bf7e5b8dbb602186030839e89df5af), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c)]:\n  - @effect/schema@0.58.0\n  - @effect/platform-node@0.40.3\n  - @effect/platform@0.40.3\n\n## 0.5.6\n\n### Patch Changes\n\n- Updated dependencies [[`4c90c54`](https://github.com/Effect-TS/effect/commit/4c90c54d87c91f75f3ad114926cdf3b0c25df091), [`d5a1949`](https://github.com/Effect-TS/effect/commit/d5a19499aac7c1d147674a35ac69992177c7536c), [`d3d3bda`](https://github.com/Effect-TS/effect/commit/d3d3bda74c794153def9027e0c40896e72cd5d14)]:\n  - @effect/platform@0.40.2\n  - effect@2.0.2\n  - @effect/platform-node@0.40.2\n  - @effect/schema@0.57.2\n\n## 0.5.5\n\n### Patch Changes\n\n- Updated dependencies [[`16bd87d`](https://github.com/Effect-TS/effect/commit/16bd87d32611b966dc42ea4fc979764f97a49071)]:\n  - effect@2.0.1\n  - @effect/platform@0.40.1\n  - @effect/platform-node@0.40.1\n  - @effect/schema@0.57.1\n\n## 0.5.4\n\n### Patch Changes\n\n- [#1849](https://github.com/Effect-TS/effect/pull/1849) [`389a8b1`](https://github.com/Effect-TS/effect/commit/389a8b1c7fbbb1e024dfaf56f13dc2c99dc2af9b) Thanks [@fubhy](https://github.com/fubhy)! - Add `/experimental` package\n\n- Updated dependencies [[`d987daa`](https://github.com/Effect-TS/effect/commit/d987daafaddd43b6ade74916a08236c19ea0a9fa), [`7b5eaa3`](https://github.com/Effect-TS/effect/commit/7b5eaa3838c79bf4bdccf91b94d61bbc38a2ec95), [`0724211`](https://github.com/Effect-TS/effect/commit/072421149c36010748ff6b6ee19c15c6cffefe09), [`9f2bc5a`](https://github.com/Effect-TS/effect/commit/9f2bc5a19e0b678a0a85e84daac290922b0fd57d), [`04fb8b4`](https://github.com/Effect-TS/effect/commit/04fb8b428b19bba85a2c79910c5e363340d074e7), [`d0471ca`](https://github.com/Effect-TS/effect/commit/d0471ca7b544746674b9e1750202da72b0a21233), [`bcf0900`](https://github.com/Effect-TS/effect/commit/bcf0900b58f449262556f80bff21e771a37272aa), [`99d22cb`](https://github.com/Effect-TS/effect/commit/99d22cbee13cc2111a4a634cbe73b9b7d7fd88c7), [`6299b84`](https://github.com/Effect-TS/effect/commit/6299b84c11e5d1fe79fa538df8935018c7613747), [`c0aeb5e`](https://github.com/Effect-TS/effect/commit/c0aeb5e302869bcd7d7627f8cc5b630d07c12d10), [`693b8f3`](https://github.com/Effect-TS/effect/commit/693b8f3a3dfd43ae61f0d9292cdf356be7329f2f)]:\n  - @effect/platform-node@0.40.0\n  - @effect/platform@0.40.0\n  - @effect/schema@0.57.0\n  - effect@2.0.0\n\n## 0.5.3\n\n### Patch Changes\n\n- [#42](https://github.com/Effect-TS/experimental/pull/42) [`fcf22ce`](https://github.com/Effect-TS/experimental/commit/fcf22ce465439ee276fea654cb4e4b97393df6c6) Thanks [@tim-smart](https://github.com/tim-smart)! - switch to handler api for socket and socket server\n\n## 0.5.2\n\n### Patch Changes\n\n- [#40](https://github.com/Effect-TS/experimental/pull/40) [`04b8b17`](https://github.com/Effect-TS/experimental/commit/04b8b17715ae35ef774109be0f2b86f9d6390792) Thanks [@tim-smart](https://github.com/tim-smart)! - add source to SocketServer sockets\n\n## 0.5.1\n\n### Patch Changes\n\n- [#37](https://github.com/Effect-TS/experimental/pull/37) [`9659fbe`](https://github.com/Effect-TS/experimental/commit/9659fbe13bec5270b0cc5e8035a89cfb17d4b6af) Thanks [@tim-smart](https://github.com/tim-smart)! - fix use of timeout\n\n## 0.5.0\n\n### Minor Changes\n\n- [#35](https://github.com/Effect-TS/experimental/pull/35) [`c9366db`](https://github.com/Effect-TS/experimental/commit/c9366db09b15b802a6272b6e81c5cfd2c7507595) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.4.0\n\n### Minor Changes\n\n- [#33](https://github.com/Effect-TS/experimental/pull/33) [`d716090`](https://github.com/Effect-TS/experimental/commit/d716090f539b56d5093a82a10dd5fd6b2b369e86) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.3.2\n\n### Patch Changes\n\n- [#31](https://github.com/Effect-TS/experimental/pull/31) [`216e3d3`](https://github.com/Effect-TS/experimental/commit/216e3d31867124d2d38676b526830f4a4c7d7c5d) Thanks [@tim-smart](https://github.com/tim-smart)! - update /platform\n\n## 0.3.1\n\n### Patch Changes\n\n- [#29](https://github.com/Effect-TS/experimental/pull/29) [`7f346ac`](https://github.com/Effect-TS/experimental/commit/7f346ac95ad2b31e07f1494e8c78e66b2e1bdb40) Thanks [@tim-smart](https://github.com/tim-smart)! - add metrics to dev tools\n\n## 0.3.0\n\n### Minor Changes\n\n- [#27](https://github.com/Effect-TS/experimental/pull/27) [`6618248`](https://github.com/Effect-TS/experimental/commit/6618248e0f2f4aec2330aa9092bf05b55c763164) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.2.8\n\n### Patch Changes\n\n- [#25](https://github.com/Effect-TS/experimental/pull/25) [`e8d5e6d`](https://github.com/Effect-TS/experimental/commit/e8d5e6d5fdc529d55bd3e3c6d9a4bc59dedd5060) Thanks [@tim-smart](https://github.com/tim-smart)! - fix server interrupt\n\n## 0.2.7\n\n### Patch Changes\n\n- [#23](https://github.com/Effect-TS/experimental/pull/23) [`fc89b83`](https://github.com/Effect-TS/experimental/commit/fc89b8351386bef64638b3880d7383f6a7e6dee3) Thanks [@tim-smart](https://github.com/tim-smart)! - seperate DevTools modules\n\n## 0.2.6\n\n### Patch Changes\n\n- [#20](https://github.com/Effect-TS/experimental/pull/20) [`963f717`](https://github.com/Effect-TS/experimental/commit/963f717d4c9f231660f9145185b957edfd30abbd) Thanks [@tim-smart](https://github.com/tim-smart)! - add websocket server\n\n## 0.2.5\n\n### Patch Changes\n\n- [#18](https://github.com/Effect-TS/experimental/pull/18) [`26e8dca`](https://github.com/Effect-TS/experimental/commit/26e8dcaf850ae362bc554422241aed5d4ad88e10) Thanks [@tim-smart](https://github.com/tim-smart)! - remove duplicate onmessage in ws\n\n- [#18](https://github.com/Effect-TS/experimental/pull/18) [`26e8dca`](https://github.com/Effect-TS/experimental/commit/26e8dcaf850ae362bc554422241aed5d4ad88e10) Thanks [@tim-smart](https://github.com/tim-smart)! - add DevTools module\n\n- [#18](https://github.com/Effect-TS/experimental/pull/18) [`26e8dca`](https://github.com/Effect-TS/experimental/commit/26e8dcaf850ae362bc554422241aed5d4ad88e10) Thanks [@tim-smart](https://github.com/tim-smart)! - add SocketServer.run\n\n## 0.2.4\n\n### Patch Changes\n\n- [#16](https://github.com/Effect-TS/experimental/pull/16) [`56f4f76`](https://github.com/Effect-TS/experimental/commit/56f4f76cb6391d8d30a7bc654b9e6bfbcfa7961e) Thanks [@tim-smart](https://github.com/tim-smart)! - add SocketServer module\n\n- [#16](https://github.com/Effect-TS/experimental/pull/16) [`56f4f76`](https://github.com/Effect-TS/experimental/commit/56f4f76cb6391d8d30a7bc654b9e6bfbcfa7961e) Thanks [@tim-smart](https://github.com/tim-smart)! - add run to Socket to make it retryable\n\n## 0.2.3\n\n### Patch Changes\n\n- [#13](https://github.com/Effect-TS/experimental/pull/13) [`8ffa6e1`](https://github.com/Effect-TS/experimental/commit/8ffa6e1afa0ec9f672cbbba3bb680f3126bab7ec) Thanks [@tim-smart](https://github.com/tim-smart)! - add WebSocket\n\n## 0.2.2\n\n### Patch Changes\n\n- [#11](https://github.com/Effect-TS/experimental/pull/11) [`3a83e5a`](https://github.com/Effect-TS/experimental/commit/3a83e5af3f38f676abccd532e69289aaf0cebceb) Thanks [@tim-smart](https://github.com/tim-smart)! - refactor Socket api\n\n## 0.2.1\n\n### Patch Changes\n\n- [#9](https://github.com/Effect-TS/experimental/pull/9) [`b7f0163`](https://github.com/Effect-TS/experimental/commit/b7f0163d4b98f14705e8b810521ed800d4d2874a) Thanks [@tim-smart](https://github.com/tim-smart)! - add support for platform key value store\n\n## 0.2.0\n\n### Minor Changes\n\n- [#8](https://github.com/Effect-TS/experimental/pull/8) [`a39bfc5`](https://github.com/Effect-TS/experimental/commit/a39bfc5ba19fe9e574b7063e5c98bae8944bae4b) Thanks [@tim-smart](https://github.com/tim-smart)! - use Schema/Serializable for peristence\n\n## 0.1.1\n\n### Patch Changes\n\n- [#3](https://github.com/Effect-TS/experimental/pull/3) [`7ab9e0b`](https://github.com/Effect-TS/experimental/commit/7ab9e0b3f015f271210c75c90c76f294918d786c) Thanks [@tim-smart](https://github.com/tim-smart)! - add Socket module\n\n- [#3](https://github.com/Effect-TS/experimental/pull/3) [`7ab9e0b`](https://github.com/Effect-TS/experimental/commit/7ab9e0b3f015f271210c75c90c76f294918d786c) Thanks [@tim-smart](https://github.com/tim-smart)! - add MsgPack module\n\n## 0.1.0\n\n### Minor Changes\n\n- [#1](https://github.com/Effect-TS/experimental/pull/1) [`ff79b4b`](https://github.com/Effect-TS/experimental/commit/ff79b4bda01acfc5753c44e812ac36852130d4d8) Thanks [@tim-smart](https://github.com/tim-smart)! - add RequestResolver & Persistance\n"
  },
  {
    "path": "packages/experimental/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023-present The Contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/experimental/README.md",
    "content": "# `@effect/experimental`\n\n## Documentation\n\n- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/experimental).\n"
  },
  {
    "path": "packages/experimental/docgen.json",
    "content": "{\n  \"$schema\": \"../../node_modules/@effect/docgen/schema.json\",\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/experimental/src/\",\n  \"exclude\": [\"src/internal/**/*.ts\"]\n}\n"
  },
  {
    "path": "packages/experimental/examples/dev-tools.ts",
    "content": "import * as DevTools from \"@effect/experimental/DevTools\"\nimport { NodeRuntime, NodeSocket } from \"@effect/platform-node\"\nimport { Effect, Layer } from \"effect\"\n\nconst program = Effect.log(\"Hello!\").pipe(\n  Effect.delay(2000),\n  Effect.withSpan(\"Hi\", { attributes: { foo: \"bar\" } }),\n  Effect.forever\n)\n\nprogram.pipe(\n  Effect.provide(\n    DevTools.layerWebSocket().pipe(\n      Layer.provide(NodeSocket.layerWebSocketConstructor)\n    )\n  ),\n  NodeRuntime.runMain\n)\n"
  },
  {
    "path": "packages/experimental/examples/machine.ts",
    "content": "import { Machine } from \"@effect/experimental\"\nimport { runMain } from \"@effect/platform-node/NodeRuntime\"\nimport { Data, Effect, List, pipe, Request, Schedule } from \"effect\"\n\nclass SendError extends Data.TaggedError(\"SendError\")<{\n  readonly email: string\n  readonly reason: string\n}> {}\n\nclass SendEmail extends Request.TaggedClass(\"SendEmail\")<\n  void,\n  SendError,\n  {\n    readonly email: string\n    readonly message: string\n  }\n> {}\n\nclass ProcessEmail extends Request.TaggedClass(\"ProcessEmail\")<\n  void,\n  never,\n  {}\n> {}\n\nclass Shutdown extends Request.TaggedClass(\"Shutdown\")<\n  void,\n  never,\n  {}\n> {}\n\nconst mailer = Machine.makeWith<List.List<SendEmail>>()((_, previous) =>\n  Effect.gen(function*() {\n    const ctx = yield* Machine.MachineContext\n    const state = previous ?? List.empty()\n\n    if (List.isCons(state)) {\n      yield* ctx.unsafeSend(new ProcessEmail()).pipe(Effect.replicateEffect(List.size(state)))\n    }\n\n    return Machine.procedures.make(state).pipe(\n      Machine.procedures.addPrivate<ProcessEmail>()(\"ProcessEmail\", ({ state }) =>\n        Effect.gen(function*() {\n          if (List.isNil(state)) {\n            return [void 0, state]\n          }\n          const req = state.head\n          yield* Effect.log(`Sending email to ${req.email}`).pipe(Effect.delay(500))\n          return [void 0, state.tail]\n        })),\n      Machine.procedures.add<SendEmail>()(\"SendEmail\", (ctx) =>\n        ctx.send(new ProcessEmail()).pipe(\n          Effect.as([void 0, List.append(ctx.state, ctx.request)])\n        )),\n      Machine.procedures.add<Shutdown>()(\"Shutdown\", () =>\n        Effect.log(\"Shutting down\").pipe(\n          Effect.zipRight(Effect.interrupt)\n        ))\n    )\n  })\n).pipe(\n  Machine.retry(Schedule.forever)\n)\n\nconst program = Effect.gen(function*() {\n  const actor = yield* Machine.boot(mailer)\n  yield* actor.send(new SendEmail({ email: \"test@example.com\", message: \"Hello, World!\" }))\n  yield* actor.send(new SendEmail({ email: \"test@example.com\", message: \"Hello, World!\" }))\n  yield* actor.send(new SendEmail({ email: \"test@example.com\", message: \"Hello, World!\" }))\n  yield* actor.send(new Shutdown())\n})\n\npipe(\n  program,\n  Effect.scoped,\n  runMain\n)\n"
  },
  {
    "path": "packages/experimental/examples/rate-limiter.ts",
    "content": "import { RateLimiter } from \"@effect/experimental\"\nimport * as RedisRateLimiter from \"@effect/experimental/RateLimiter/Redis\"\nimport { NodeRuntime } from \"@effect/platform-node\"\nimport { Effect, Layer } from \"effect\"\n\n// create a RateLimiter layer using Redis as the backing store.\n//\n// You can also use RateLimiter.layerStoreMemory for an in-memory store.\nconst RateLimiterLayer = RateLimiter.layer.pipe(\n  Layer.provide(RedisRateLimiter.layerStore({\n    host: \"localhost\",\n    port: 6379\n  }))\n)\n\nEffect.gen(function*() {\n  const limiter = yield* RateLimiter.RateLimiter\n\n  // the `consume` effect will attempt to consume a token from the rate limiter.\n  //\n  // When `onExceeded` is set to \"delay\", the effect will return the time to\n  // wait for the token to become available.\n  const consume = limiter.consume({\n    algorithm: \"token-bucket\",\n    onExceeded: \"delay\",\n    window: \"10 seconds\",\n    limit: 5,\n    key: \"user-123\"\n  })\n\n  // `consume` returns the metadata about the rate limiting operation.\n  //\n  // ```\n  // {\n  //   delay: { _id: 'Duration', _tag: 'Millis', millis: 0 },\n  //   limit: 5,\n  //   remaining: 4,\n  //   resetAfter: { _id: 'Duration', _tag: 'Millis', millis: 2000 }\n  // }\n  // ```\n  console.log(yield* consume)\n\n  // If `onExceeded` is set to \"fail\", the effect will fail with a\n  // RateLimiter.RateLimitExceeded error when the limit is exceeded.\n  yield* limiter.consume({\n    algorithm: \"token-bucket\",\n    onExceeded: \"fail\",\n    window: \"10 seconds\",\n    limit: 5,\n    key: \"user-123\"\n  })\n\n  // You can also use `RateLimiter.makeWithRateLimiter` to access a function\n  // that applies rate limiting to an effect.\n  const withRateLimiter = yield* RateLimiter.makeWithRateLimiter\n\n  yield* Effect.log(\"Attempting rate limited operation\").pipe(\n    withRateLimiter({\n      algorithm: \"token-bucket\",\n      onExceeded: \"delay\",\n      window: \"10 seconds\",\n      limit: 5,\n      key: \"user-123\"\n    })\n  )\n}).pipe(\n  Effect.provide(RateLimiterLayer),\n  NodeRuntime.runMain\n)\n"
  },
  {
    "path": "packages/experimental/examples/redis/docker-compose.yaml",
    "content": "services:\n  redis:\n    image: redis:alpine\n    ports:\n      - \"6379:6379\"\n"
  },
  {
    "path": "packages/experimental/examples/redis/resolver.ts",
    "content": "import * as Redis from \"@effect/experimental/Persistence/Redis\"\nimport { persisted } from \"@effect/experimental/RequestResolver\"\nimport { runMain } from \"@effect/platform-node/NodeRuntime\"\nimport { Array, Effect, Exit, pipe, PrimaryKey, RequestResolver, Schema } from \"effect\"\n\nclass User extends Schema.Class<User>(\"User\")({\n  id: Schema.Number,\n  name: Schema.String\n}) {}\n\nclass GetUserById extends Schema.TaggedRequest<GetUserById>()(\"GetUserById\", {\n  failure: Schema.String,\n  success: User,\n  payload: {\n    id: Schema.Number\n  }\n}) {\n  [PrimaryKey.symbol]() {\n    return `GetUserById:${this.id}`\n  }\n}\n\nconst program = Effect.gen(function*() {\n  const resolver = yield* RequestResolver.fromEffectTagged<GetUserById>()({\n    GetUserById: (reqs) => {\n      console.log(\"uncached requests\", reqs.length)\n      return Effect.forEach(reqs, (req) => Effect.succeed(new User({ id: req.id, name: \"John\" })))\n    }\n  }).pipe(persisted({\n    storeId: \"users\",\n    timeToLive: (_req, exit) => Exit.isSuccess(exit) ? 30000 : 0\n  }))\n\n  const users = yield* Effect.forEach(Array.range(1, 5), (id) => Effect.request(new GetUserById({ id }), resolver), {\n    batching: true\n  })\n\n  console.log(users)\n})\n\npipe(\n  program,\n  Effect.scoped,\n  Effect.provide(Redis.layerResult({})),\n  runMain\n)\n"
  },
  {
    "path": "packages/experimental/examples/serializable-machine.ts",
    "content": "import { Machine } from \"@effect/experimental\"\nimport { runMain } from \"@effect/platform-node/NodeRuntime\"\nimport { Effect, List, pipe, Schedule, Schema } from \"effect\"\n\nclass SendError extends Schema.TaggedError<SendError>()(\n  \"SendError\",\n  {\n    email: Schema.String,\n    reason: Schema.String\n  }\n) {}\n\nclass SendEmail extends Schema.TaggedRequest<SendEmail>()(\n  \"SendEmail\",\n  {\n    failure: SendError,\n    success: Schema.Void,\n    payload: {\n      email: Schema.String,\n      message: Schema.String\n    }\n  }\n) {}\n\nclass ProcessEmail extends Schema.TaggedRequest<ProcessEmail>()(\n  \"ProcessEmail\",\n  { failure: Schema.Never, success: Schema.Void, payload: {} }\n) {}\n\nclass Shutdown extends Schema.TaggedRequest<Shutdown>()(\n  \"Shutdown\",\n  { failure: Schema.Never, success: Schema.Void, payload: {} }\n) {}\n\nconst mailer = Machine.makeSerializable({\n  state: Schema.List(SendEmail)\n}, (_, previous) =>\n  Effect.gen(function*() {\n    const ctx = yield* Machine.MachineContext\n    const state = previous ?? List.empty()\n\n    if (List.isCons(state)) {\n      yield* ctx.unsafeSend(new ProcessEmail()).pipe(Effect.replicateEffect(List.size(state)))\n    }\n\n    return Machine.serializable.make(state).pipe(\n      Machine.serializable.addPrivate(ProcessEmail, ({ state }) =>\n        Effect.gen(function*() {\n          if (List.isNil(state)) {\n            return [void 0, state]\n          }\n          const req = state.head\n          yield* Effect.log(`Sending email to ${req.email}`).pipe(Effect.delay(500))\n          return [void 0, state.tail]\n        })),\n      Machine.serializable.add(SendEmail, (ctx) =>\n        ctx.send(new ProcessEmail()).pipe(\n          Effect.as([void 0, List.append(ctx.state, ctx.request)])\n        )),\n      Machine.serializable.add(Shutdown, () =>\n        Effect.log(\"Shutting down\").pipe(\n          Effect.zipRight(Effect.interrupt)\n        ))\n    )\n  })).pipe(\n    Machine.retry(Schedule.forever)\n  )\n\nconst program = Effect.gen(function*() {\n  const actor = yield* Machine.boot(mailer)\n  yield* actor.send(new SendEmail({ email: \"test@example.com\", message: \"Hello, World!\" }))\n  yield* actor.send(new SendEmail({ email: \"test@example.com\", message: \"Hello, World!\" }))\n  yield* actor.send(new SendEmail({ email: \"test@example.com\", message: \"Hello, World!\" }))\n  yield* actor.send(new Shutdown())\n})\n\npipe(\n  program,\n  Effect.scoped,\n  runMain\n)\n"
  },
  {
    "path": "packages/experimental/package.json",
    "content": "{\n  \"name\": \"@effect/experimental\",\n  \"version\": \"0.60.0\",\n  \"type\": \"module\",\n  \"license\": \"MIT\",\n  \"description\": \"Experimental modules for the Effect ecosystem\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/experimental\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"keywords\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"dependencies\": {\n    \"uuid\": \"^11.0.3\"\n  },\n  \"peerDependencies\": {\n    \"@effect/platform\": \"workspace:^\",\n    \"effect\": \"workspace:^\",\n    \"ioredis\": \"^5\",\n    \"lmdb\": \"^3\"\n  },\n  \"peerDependenciesMeta\": {\n    \"ioredis\": {\n      \"optional\": true\n    },\n    \"lmdb\": {\n      \"optional\": true\n    }\n  },\n  \"devDependencies\": {\n    \"@cloudflare/workers-types\": \"^4.20250515.0\",\n    \"@effect/platform-node\": \"workspace:^\",\n    \"@testcontainers/redis\": \"^11.8.1\",\n    \"@types/ws\": \"^8.18.1\",\n    \"ioredis\": \"^5.6.1\",\n    \"lmdb\": \"^3.3.0\"\n  }\n}\n"
  },
  {
    "path": "packages/experimental/src/DevTools/Client.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Ndjson from \"@effect/platform/Ndjson\"\nimport * as Socket from \"@effect/platform/Socket\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as Metric from \"effect/Metric\"\nimport * as MetricState from \"effect/MetricState\"\nimport * as Schedule from \"effect/Schedule\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport * as Tracer from \"effect/Tracer\"\nimport * as Domain from \"./Domain.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface ClientImpl {\n  readonly unsafeAddSpan: (_: Domain.Span | Domain.SpanEvent) => void\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Client {\n  readonly _: unique symbol\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const Client = Context.GenericTag<Client, ClientImpl>(\"@effect/experimental/DevTools/Client\")\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: Effect.Effect<ClientImpl, never, Scope.Scope | Socket.Socket> = Effect.gen(function*() {\n  const socket = yield* Socket.Socket\n  const requests = yield* Mailbox.make<Domain.Request>()\n\n  function metricsSnapshot(): Domain.MetricsSnapshot {\n    const snapshot = Metric.unsafeSnapshot()\n    const metrics: Array<Domain.Metric> = []\n\n    for (let i = 0, len = snapshot.length; i < len; i++) {\n      const metricPair = snapshot[i]\n      if (MetricState.isCounterState(metricPair.metricState)) {\n        metrics.push({\n          _tag: \"Counter\",\n          name: metricPair.metricKey.name,\n          description: metricPair.metricKey.description,\n          tags: metricPair.metricKey.tags,\n          state: metricPair.metricState\n        })\n      } else if (MetricState.isGaugeState(metricPair.metricState)) {\n        metrics.push({\n          _tag: \"Gauge\",\n          name: metricPair.metricKey.name,\n          description: metricPair.metricKey.description,\n          tags: metricPair.metricKey.tags,\n          state: metricPair.metricState\n        })\n      } else if (MetricState.isHistogramState(metricPair.metricState)) {\n        metrics.push({\n          _tag: \"Histogram\",\n          name: metricPair.metricKey.name,\n          description: metricPair.metricKey.description,\n          tags: metricPair.metricKey.tags,\n          state: metricPair.metricState\n        })\n      } else if (MetricState.isSummaryState(metricPair.metricState)) {\n        metrics.push({\n          _tag: \"Summary\",\n          name: metricPair.metricKey.name,\n          description: metricPair.metricKey.description,\n          tags: metricPair.metricKey.tags,\n          state: metricPair.metricState\n        })\n      } else if (MetricState.isFrequencyState(metricPair.metricState)) {\n        metrics.push({\n          _tag: \"Frequency\",\n          name: metricPair.metricKey.name,\n          description: metricPair.metricKey.description,\n          tags: metricPair.metricKey.tags,\n          state: {\n            occurrences: Object.fromEntries(metricPair.metricState.occurrences.entries())\n          }\n        })\n      }\n    }\n\n    return {\n      _tag: \"MetricsSnapshot\",\n      metrics\n    }\n  }\n\n  const connected = yield* Deferred.make<void>()\n\n  yield* Mailbox.toStream(requests).pipe(\n    Stream.pipeThroughChannel(\n      Ndjson.duplexSchemaString(Socket.toChannelString(socket), {\n        inputSchema: Domain.Request,\n        outputSchema: Domain.Response\n      })\n    ),\n    Stream.runForEach((req) => {\n      Deferred.unsafeDone(connected, Exit.void)\n      switch (req._tag) {\n        case \"MetricsRequest\": {\n          return requests.offer(metricsSnapshot())\n        }\n        case \"Pong\": {\n          return Effect.void\n        }\n      }\n    }),\n    Effect.tapErrorCause(Effect.logDebug),\n    Effect.retry(Schedule.spaced(\"1 seconds\")),\n    Effect.forkScoped,\n    Effect.uninterruptible\n  )\n\n  yield* Effect.addFinalizer(() =>\n    requests.offer(metricsSnapshot()).pipe(\n      Effect.zipRight(Effect.fiberIdWith((id) => requests.failCause(Cause.interrupt(id))))\n    )\n  )\n  yield* requests.offer({ _tag: \"Ping\" }).pipe(\n    Effect.delay(\"3 seconds\"),\n    Effect.forever,\n    Effect.forkScoped,\n    Effect.interruptible\n  )\n\n  yield* Deferred.await(connected).pipe(\n    Effect.timeoutOption(\"1 second\")\n  )\n\n  return Client.of({\n    unsafeAddSpan: (request) => requests.unsafeOffer(request)\n  })\n}).pipe(\n  Effect.annotateLogs({\n    package: \"@effect/experimental\",\n    module: \"DevTools\",\n    service: \"Client\"\n  })\n)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer.Layer<Client, never, Socket.Socket> = Layer.scoped(Client, make)\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeTracer: Effect.Effect<Tracer.Tracer, never, Client> = Effect.gen(function*() {\n  const client = yield* Client\n  const currentTracer = yield* Effect.tracer\n\n  return Tracer.make({\n    span(name, parent, context, links, startTime, kind, options) {\n      const span = currentTracer.span(name, parent, context, links, startTime, kind, options)\n      client.unsafeAddSpan(span)\n      const oldEvent = span.event\n      span.event = function(this: any, name, startTime, attributes) {\n        client.unsafeAddSpan({\n          _tag: \"SpanEvent\",\n          traceId: span.traceId,\n          spanId: span.spanId,\n          name,\n          startTime,\n          attributes: attributes || {}\n        })\n        return oldEvent.call(this, name, startTime, attributes)\n      }\n      const oldEnd = span.end\n      span.end = function(this: any) {\n        client.unsafeAddSpan(span)\n        return oldEnd.apply(this, arguments as any)\n      }\n      return span\n    },\n    context: currentTracer.context\n  })\n}).pipe(\n  Effect.annotateLogs({\n    package: \"@effect/experimental\",\n    module: \"DevTools\",\n    service: \"Tracer\"\n  })\n)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerTracer: Layer.Layer<never, never, Socket.Socket> = pipe(\n  makeTracer,\n  Effect.map(Layer.setTracer),\n  Layer.unwrapEffect,\n  Layer.provide(layer)\n)\n"
  },
  {
    "path": "packages/experimental/src/DevTools/Domain.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { Option } from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const SpanStatusStarted = Schema.Struct({\n  _tag: Schema.Literal(\"Started\"),\n  startTime: Schema.BigInt\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const SpanStatusEnded = Schema.Struct({\n  _tag: Schema.Literal(\"Ended\"),\n  startTime: Schema.BigInt,\n  endTime: Schema.BigInt\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const SpanStatus = Schema.Union(SpanStatusStarted, SpanStatusEnded)\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const ExternalSpan = Schema.Struct({\n  _tag: Schema.Literal(\"ExternalSpan\"),\n  spanId: Schema.String,\n  traceId: Schema.String,\n  sampled: Schema.Boolean\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport interface ExternalSpanFrom extends Schema.Schema.Encoded<typeof ExternalSpan> {}\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport interface ExternalSpan extends Schema.Schema.Type<typeof ExternalSpan> {}\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Span: Schema.Schema<Span, SpanFrom> = Schema.Struct({\n  _tag: Schema.Literal(\"Span\"),\n  spanId: Schema.String,\n  traceId: Schema.String,\n  name: Schema.String,\n  sampled: Schema.Boolean,\n  attributes: Schema.ReadonlyMap({ key: Schema.String, value: Schema.Unknown }),\n  status: SpanStatus,\n  parent: Schema.Option(\n    Schema.suspend(() => ParentSpan)\n      // add a title annotation to avoid \"Cannot access 'ParentSpan' before initialization\" error during module initialization\n      .annotations({ title: \"ParentSpan\" })\n  )\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const SpanEvent: Schema.Schema<\n  SpanEvent,\n  {\n    readonly _tag: \"SpanEvent\"\n    readonly spanId: string\n    readonly traceId: string\n    readonly name: string\n    readonly attributes: { readonly [x: string]: unknown }\n    readonly startTime: string\n  }\n> = Schema.Struct({\n  _tag: Schema.Literal(\"SpanEvent\"),\n  traceId: Schema.String,\n  spanId: Schema.String,\n  name: Schema.String,\n  startTime: Schema.BigInt,\n  attributes: Schema.Record({ key: Schema.String, value: Schema.Unknown })\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const ParentSpan = Schema.Union(Span, ExternalSpan)\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport type ParentSpanFrom = SpanFrom | ExternalSpanFrom\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport type ParentSpan = Span | ExternalSpan\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport interface SpanFrom {\n  readonly _tag: \"Span\"\n  readonly spanId: string\n  readonly traceId: string\n  readonly name: string\n  readonly sampled: boolean\n  readonly attributes: ReadonlyArray<readonly [string, unknown]>\n  readonly parent: Schema.OptionEncoded<ParentSpanFrom>\n  readonly status: {\n    readonly _tag: \"Started\"\n    readonly startTime: string\n  } | {\n    readonly _tag: \"Ended\"\n    readonly startTime: string\n    readonly endTime: string\n  }\n}\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport interface Span {\n  readonly _tag: \"Span\"\n  readonly spanId: string\n  readonly traceId: string\n  readonly name: string\n  readonly sampled: boolean\n  readonly attributes: ReadonlyMap<string, unknown>\n  readonly parent: Option<ParentSpan>\n  readonly status: {\n    readonly _tag: \"Started\"\n    readonly startTime: bigint\n  } | {\n    readonly _tag: \"Ended\"\n    readonly startTime: bigint\n    readonly endTime: bigint\n  }\n}\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport interface SpanEvent {\n  readonly _tag: \"SpanEvent\"\n  readonly spanId: string\n  readonly traceId: string\n  readonly name: string\n  readonly attributes: { readonly [x: string]: unknown }\n  readonly startTime: bigint\n}\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Ping = Schema.Struct({\n  _tag: Schema.Literal(\"Ping\")\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Pong = Schema.Struct({\n  _tag: Schema.Literal(\"Pong\")\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const MetricsRequest = Schema.Struct({\n  _tag: Schema.Literal(\"MetricsRequest\")\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const MetricLabel = Schema.Struct({\n  key: Schema.String,\n  value: Schema.String\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const metric = <Tag extends string, S, IS, R>(tag: Tag, state: Schema.Schema<S, IS, R>) =>\n  Schema.Struct({\n    _tag: Schema.Literal(tag),\n    name: Schema.String,\n    description: Schema.optionalWith(Schema.String, { as: \"Option\" }),\n    tags: Schema.Array(MetricLabel),\n    state\n  })\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Counter = metric(\n  \"Counter\",\n  Schema.Struct({\n    count: Schema.Union(Schema.Number, Schema.BigInt)\n  })\n)\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Frequency = metric(\n  \"Frequency\",\n  Schema.Struct({\n    occurrences: Schema.Record({ key: Schema.String, value: Schema.Number })\n  })\n)\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Gauge = metric(\n  \"Gauge\",\n  Schema.Struct({\n    value: Schema.Union(Schema.Number, Schema.BigInt)\n  })\n)\n\nconst numberOrInfinity = Schema.transform(\n  Schema.Union(Schema.Number, Schema.Null),\n  Schema.Number,\n  {\n    strict: true,\n    decode: (i) => i === null ? Number.POSITIVE_INFINITY : i,\n    encode: (i) => Number.isFinite(i) ? i : null\n  }\n)\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Histogram = metric(\n  \"Histogram\",\n  Schema.Struct({\n    buckets: Schema.Array(Schema.Tuple(\n      numberOrInfinity,\n      Schema.Number\n    )),\n    count: Schema.Number,\n    min: Schema.Number,\n    max: Schema.Number,\n    sum: Schema.Number\n  })\n)\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Summary = metric(\n  \"Summary\",\n  Schema.Struct({\n    error: Schema.Number,\n    quantiles: Schema.Array(Schema.Tuple(Schema.Number, Schema.Option(Schema.Number))),\n    count: Schema.Number,\n    min: Schema.Number,\n    max: Schema.Number,\n    sum: Schema.Number\n  })\n)\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Metric = Schema.Union(Counter, Frequency, Gauge, Histogram, Summary)\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport type Metric = Schema.Schema.Type<typeof Metric>\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport type MetricFrom = Schema.Schema.Encoded<typeof Metric>\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const MetricsSnapshot = Schema.Struct({\n  _tag: Schema.Literal(\"MetricsSnapshot\"),\n  metrics: Schema.Array(Metric)\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport type MetricsSnapshot = Schema.Schema.Type<typeof MetricsSnapshot>\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport type MetricsSnapshotFrom = Schema.Schema.Encoded<typeof MetricsSnapshot>\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Request = Schema.Union(Ping, Span, SpanEvent, MetricsSnapshot)\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport type Request = Schema.Schema.Type<typeof Request>\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport declare namespace Request {\n  /**\n   * @since 1.0.0\n   * @category schemas\n   */\n  export type WithoutPing = Exclude<Request, { readonly _tag: \"Ping\" }>\n}\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const Response = Schema.Union(Pong, MetricsRequest)\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport type Response = Schema.Schema.Type<typeof Response>\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport declare namespace Response {\n  /**\n   * @since 1.0.0\n   * @category schemas\n   */\n  export type WithoutPong = Exclude<Response, { readonly _tag: \"Pong\" }>\n}\n"
  },
  {
    "path": "packages/experimental/src/DevTools/Server.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Ndjson from \"@effect/platform/Ndjson\"\nimport * as Socket from \"@effect/platform/Socket\"\nimport * as SocketServer from \"@effect/platform/SocketServer\"\nimport * as Effect from \"effect/Effect\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as Stream from \"effect/Stream\"\nimport * as Domain from \"./Domain.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Client {\n  readonly queue: Mailbox.ReadonlyMailbox<Domain.Request.WithoutPing>\n  readonly request: (_: Domain.Response.WithoutPong) => Effect.Effect<void>\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const run = Effect.fnUntraced(function*<R, E, _>(handle: (client: Client) => Effect.Effect<_, E, R>) {\n  const server = yield* SocketServer.SocketServer\n  return yield* server.run((socket) =>\n    Effect.gen(function*() {\n      const responses = yield* Mailbox.make<Domain.Response>()\n      const requests = yield* Mailbox.make<Domain.Request.WithoutPing>()\n\n      const client: Client = {\n        queue: requests,\n        request: (res) => responses.offer(res)\n      }\n\n      yield* Mailbox.toStream(responses).pipe(\n        Stream.pipeThroughChannel(\n          Ndjson.duplexSchemaString(Socket.toChannelString(socket), {\n            inputSchema: Domain.Response,\n            outputSchema: Domain.Request\n          })\n        ),\n        Stream.runForEach((req) =>\n          req._tag === \"Ping\"\n            ? responses.offer({ _tag: \"Pong\" })\n            : requests.offer(req)\n        ),\n        Effect.ensuring(Effect.zipRight(responses.shutdown, requests.shutdown)),\n        Effect.fork\n      )\n\n      yield* handle(client)\n    })\n  )\n})\n"
  },
  {
    "path": "packages/experimental/src/DevTools.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Socket from \"@effect/platform/Socket\"\nimport * as Layer from \"effect/Layer\"\nimport * as Client from \"./DevTools/Client.js\"\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerSocket: Layer.Layer<never, never, Socket.Socket> = Client.layerTracer\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerWebSocket = (url = \"ws://localhost:34437\"): Layer.Layer<never, never, Socket.WebSocketConstructor> =>\n  Client.layerTracer.pipe(\n    Layer.provide(Socket.layerWebSocket(url))\n  )\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer = (url = \"ws://localhost:34437\"): Layer.Layer<never> =>\n  layerWebSocket(url).pipe(\n    Layer.provide(Socket.layerWebSocketConstructorGlobal)\n  )\n"
  },
  {
    "path": "packages/experimental/src/Event.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as MsgPack from \"@effect/platform/MsgPack\"\nimport { pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/experimental/Event\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isEvent = (u: unknown): u is Event<any, any, any, any> => Predicate.hasProperty(u, TypeId)\n\n/**\n * Represents an event in an EventLog.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface Event<\n  out Tag extends string,\n  in out Payload extends Schema.Schema.Any = typeof Schema.Void,\n  in out Success extends Schema.Schema.Any = typeof Schema.Void,\n  in out Error extends Schema.Schema.All = typeof Schema.Never\n> {\n  readonly [TypeId]: TypeId\n  readonly tag: Tag\n  readonly primaryKey: (payload: Schema.Schema.Type<Payload>) => string\n  readonly payload: Payload\n  readonly payloadMsgPack: MsgPack.schema<Payload>\n  readonly success: Success\n  readonly error: Error\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface EventHandler<in out Tag extends string> {\n  readonly _: unique symbol\n  readonly tag: Tag\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace Event {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Any {\n    readonly [TypeId]: TypeId\n    readonly tag: string\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface AnyWithProps extends Event<string, Schema.Schema.Any, Schema.Schema.Any, Schema.Schema.Any> {}\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ToService<A> = A extends Event<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error\n  > ? EventHandler<_Tag> :\n    never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Tag<A> = A extends Event<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error\n  > ? _Tag :\n    never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ErrorSchema<A extends Any> = A extends Event<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error\n  > ? _Error\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Error<A extends Any> = Schema.Schema.Type<ErrorSchema<A>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type AddError<A extends Any, Error extends Schema.Schema.Any> = A extends Event<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error\n  > ? Event<_Tag, _Payload, _Success, _Error | Error>\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type PayloadSchema<A extends Any> = A extends Event<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error\n  > ? _Payload\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Payload<A extends Any> = Schema.Schema.Type<PayloadSchema<A>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type TaggedPayload<A extends Any> = A extends Event<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error\n  > ? {\n      readonly _tag: _Tag\n      readonly payload: Schema.Schema.Type<_Payload>\n    }\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type SuccessSchema<A extends Any> = A extends Event<\n    infer _Tag,\n    infer _Payload,\n    infer _Success,\n    infer _Error\n  > ? _Success\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Success<A extends Any> = Schema.Schema.Type<SuccessSchema<A>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Context<A> = A extends Event<\n    infer _Name,\n    infer _Payload,\n    infer _Success,\n    infer _Error\n  > ? Schema.Schema.Context<_Payload> | Schema.Schema.Context<_Success> | Schema.Schema.Context<_Error>\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type WithTag<Events extends Any, Tag extends string> = Extract<Events, { readonly tag: Tag }>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ExcludeTag<Events extends Any, Tag extends string> = Exclude<Events, { readonly tag: Tag }>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type PayloadWithTag<Events extends Any, Tag extends string> = Payload<WithTag<Events, Tag>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type SuccessWithTag<Events extends Any, Tag extends string> = Success<WithTag<Events, Tag>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ErrorWithTag<Events extends Any, Tag extends string> = Error<WithTag<Events, Tag>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ContextWithTag<Events extends Any, Tag extends string> = Context<WithTag<Events, Tag>>\n}\n\nconst Proto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <\n  Tag extends string,\n  Payload extends Schema.Schema.Any = typeof Schema.Void,\n  Success extends Schema.Schema.Any = typeof Schema.Void,\n  Error extends Schema.Schema.All = typeof Schema.Never\n>(options: {\n  readonly tag: Tag\n  readonly primaryKey: (payload: Schema.Schema.Type<Payload>) => string\n  readonly payload?: Payload\n  readonly success?: Success\n  readonly error?: Error\n}): Event<Tag, Payload, Success, Error> =>\n  Object.assign(Object.create(Proto), {\n    tag: options.tag,\n    primaryKey: options.primaryKey,\n    payload: options.payload ?? Schema.Void,\n    payloadMsgPack: MsgPack.schema(options.payload ?? Schema.Void),\n    success: options.success ?? Schema.Void,\n    error: options.error ?? Schema.Never\n  })\n"
  },
  {
    "path": "packages/experimental/src/EventGroup.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as HttpApiSchema from \"@effect/platform/HttpApiSchema\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Record from \"effect/Record\"\nimport type * as Schema from \"effect/Schema\"\nimport type { Event } from \"./Event.js\"\nimport * as EventApi from \"./Event.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/experimental/EventGroup\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isEventGroup = (u: unknown): u is EventGroup.Any => Predicate.hasProperty(u, TypeId)\n\n/**\n * An `EventGroup` is a collection of `Event`s. You can use an `EventGroup` to\n * represent a portion of your domain.\n *\n * The events can be implemented later using the `EventLogBuilder.group` api.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface EventGroup<\n  out Events extends Event.Any = never\n> extends Pipeable {\n  new(_: never): {}\n\n  readonly [TypeId]: TypeId\n  readonly events: Record.ReadonlyRecord<string, Events>\n\n  /**\n   * Add an `Event` to the `EventGroup`.\n   */\n  add<\n    Tag extends string,\n    Payload extends Schema.Schema.Any = typeof Schema.Void,\n    Success extends Schema.Schema.Any = typeof Schema.Void,\n    Error extends Schema.Schema.All = typeof Schema.Never\n  >(options: {\n    readonly tag: Tag\n    readonly primaryKey: (payload: Schema.Schema.Type<Payload>) => string\n    readonly payload?: Payload\n    readonly success?: Success\n    readonly error?: Error\n  }): EventGroup<Events | Event<Tag, Payload, Success, Error>>\n\n  /**\n   * Add an error schema to all the events in the `EventGroup`.\n   */\n  addError<Error extends Schema.Schema.Any>(error: Error): EventGroup<Event.AddError<Events, Error>>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace EventGroup {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Any {\n    readonly [TypeId]: TypeId\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type AnyWithProps = EventGroup<Event.AnyWithProps>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ToService<A> = A extends EventGroup<infer _Events> ? Event.ToService<_Events>\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Events<Group> = Group extends EventGroup<infer _Events> ? _Events\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Context<Group> = Event.Context<Events<Group>>\n}\n\nconst Proto = {\n  [TypeId]: TypeId,\n  add(this: EventGroup.AnyWithProps, options: {\n    readonly tag: string\n    readonly primaryKey: (payload: Schema.Schema.Any) => string\n    readonly payload?: Schema.Schema.Any\n    readonly success?: Schema.Schema.Any\n    readonly error?: Schema.Schema.All\n  }) {\n    return makeProto({\n      events: {\n        ...this.events,\n        [options.tag]: EventApi.make(options)\n      }\n    })\n  },\n  addError(this: EventGroup.AnyWithProps, error: Schema.Schema.Any) {\n    return makeProto({\n      events: Record.map(this.events, (event) =>\n        EventApi.make({\n          ...event,\n          error: HttpApiSchema.UnionUnify(event.error, error)\n        }))\n    })\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makeProto = <\n  Events extends Event.Any\n>(options: {\n  readonly events: Record.ReadonlyRecord<string, Events>\n}): EventGroup<Events> => {\n  function EventGroup() {}\n  Object.setPrototypeOf(EventGroup, Proto)\n  return Object.assign(EventGroup, options) as any\n}\n\n/**\n * An `EventGroup` is a collection of `Event`s. You can use an `EventGroup` to\n * represent a portion of your domain.\n *\n * The events can be implemented later using the `EventLog.group` api.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: EventGroup<never> = makeProto({ events: Record.empty() })\n"
  },
  {
    "path": "packages/experimental/src/EventJournal.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as MsgPack from \"@effect/platform/MsgPack\"\nimport * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as PubSub from \"effect/PubSub\"\nimport type * as Queue from \"effect/Queue\"\nimport * as Schema from \"effect/Schema\"\nimport type { Scope } from \"effect/Scope\"\nimport * as Uuid from \"uuid\"\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport class EventJournal extends Context.Tag(\"@effect/experimental/EventJournal\")<\n  EventJournal,\n  {\n    /**\n     * Read all the entries in the journal.\n     */\n    readonly entries: Effect.Effect<ReadonlyArray<Entry>, EventJournalError>\n\n    /**\n     * Write an event to the journal, performing an effect before committing the\n     * event.\n     */\n    readonly write: <A, E, R>(options: {\n      readonly event: string\n      readonly primaryKey: string\n      readonly payload: Uint8Array\n      readonly effect: (entry: Entry) => Effect.Effect<A, E, R>\n    }) => Effect.Effect<A, EventJournalError | E, R>\n\n    /**\n     * Write events from a remote source to the journal.\n     */\n    readonly writeFromRemote: (\n      options: {\n        readonly remoteId: RemoteId\n        readonly entries: ReadonlyArray<RemoteEntry>\n        readonly compact?:\n          | ((uncommitted: ReadonlyArray<RemoteEntry>) => Effect.Effect<\n            ReadonlyArray<[compacted: ReadonlyArray<Entry>, remoteEntries: ReadonlyArray<RemoteEntry>]>,\n            EventJournalError\n          >)\n          | undefined\n        readonly effect: (options: {\n          readonly entry: Entry\n          readonly conflicts: ReadonlyArray<Entry>\n        }) => Effect.Effect<void, EventJournalError>\n      }\n    ) => Effect.Effect<void, EventJournalError>\n\n    /**\n     * Return the uncommitted entries for a remote source.\n     */\n    readonly withRemoteUncommited: <A, E, R>(\n      remoteId: RemoteId,\n      f: (entries: ReadonlyArray<Entry>) => Effect.Effect<A, E, R>\n    ) => Effect.Effect<A, EventJournalError | E, R>\n\n    /**\n     * Retrieve the last known sequence number for a remote source.\n     */\n    readonly nextRemoteSequence: (remoteId: RemoteId) => Effect.Effect<number, EventJournalError>\n\n    /**\n     * The entries added to the local journal.\n     */\n    readonly changes: Effect.Effect<Queue.Dequeue<Entry>, never, Scope>\n\n    /**\n     * Remove all data\n     */\n    readonly destroy: Effect.Effect<void, EventJournalError>\n  }\n>() {}\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport const ErrorTypeId: unique symbol = Symbol.for(\"@effect/experimental/EventJournal/ErrorId\")\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport type ErrorTypeId = typeof ErrorTypeId\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport class EventJournalError\n  extends Schema.TaggedClass<EventJournalError>(\"@effect/experimental/EventJournal/Error\")(\"EventJournalError\", {\n    method: Schema.String,\n    cause: Schema.Defect\n  })\n{\n  /**\n   * @since 1.0.0\n   */\n  readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId\n}\n\n/**\n * @since 1.0.0\n * @category remote\n */\nexport const RemoteIdTypeId: unique symbol = Symbol.for(\"@effect/experimental/EventJournal/RemoteId\")\n\n/**\n * @since 1.0.0\n * @category remote\n */\nexport const RemoteId = Schema.Uint8ArrayFromSelf.pipe(Schema.brand(RemoteIdTypeId))\n\n/**\n * @since 1.0.0\n * @category remote\n */\nexport type RemoteId = typeof RemoteId.Type\n\n/**\n * @since 1.0.0\n * @category remote\n */\nexport const makeRemoteId = (): RemoteId => Uuid.v4({}, new Uint8Array(16)) as RemoteId\n\n/**\n * @since 1.0.0\n * @category entry\n */\nexport const EntryIdTypeId: unique symbol = Symbol.for(\"@effect/experimental/EventJournal/EntryId\")\n\n/**\n * @since 1.0.0\n * @category entry\n */\nexport const EntryId = Schema.Uint8ArrayFromSelf.pipe(Schema.brand(EntryIdTypeId))\n\n/**\n * @since 1.0.0\n * @category entry\n */\nexport type EntryId = typeof EntryId.Type\n\n/**\n * @since 1.0.0\n * @category entry\n */\nexport const makeEntryId = (options: { msecs?: number } = {}): EntryId => {\n  return Uuid.v7(options, new Uint8Array(16)) as EntryId\n}\n\n/**\n * @since 1.0.0\n * @category entry\n */\nexport const entryIdMillis = (entryId: EntryId): number => {\n  const bytes = new Uint8Array(8)\n  bytes.set(entryId.subarray(0, 6), 2)\n  return Number(new DataView(bytes.buffer).getBigUint64(0))\n}\n\n/**\n * @since 1.0.0\n * @category entry\n */\nexport class Entry extends Schema.Class<Entry>(\"@effect/experimental/EventJournal/Entry\")({\n  id: EntryId,\n  event: Schema.String,\n  primaryKey: Schema.String,\n  payload: Schema.Uint8ArrayFromSelf\n}) {\n  /**\n   * @since 1.0.0\n   */\n  static arrayMsgPack = Schema.Array(MsgPack.schema(Entry))\n\n  /**\n   * @since 1.0.0\n   */\n  static encodeArray = Schema.encode(Entry.arrayMsgPack)\n\n  /**\n   * @since 1.0.0\n   */\n  static decodeArray = Schema.decode(Entry.arrayMsgPack)\n\n  /**\n   * @since 1.0.0\n   */\n  get idString(): string {\n    return Uuid.stringify(this.id)\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  get createdAtMillis(): number {\n    return entryIdMillis(this.id)\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  get createdAt(): DateTime.Utc {\n    return DateTime.unsafeMake(this.createdAtMillis)\n  }\n}\n\n/**\n * @since 1.0.0\n * @category entry\n */\nexport class RemoteEntry extends Schema.Class<RemoteEntry>(\"@effect/experimental/EventJournal/RemoteEntry\")({\n  remoteSequence: Schema.Number,\n  entry: Entry\n}) {}\n\n/**\n * @since 1.0.0\n * @category memory\n */\nexport const makeMemory: Effect.Effect<typeof EventJournal.Service> = Effect.gen(function*() {\n  const journal: Array<Entry> = []\n  const byId = new Map<string, Entry>()\n  const remotes = new Map<string, { sequence: number; missing: Array<Entry> }>()\n  const pubsub = yield* PubSub.unbounded<Entry>()\n\n  const ensureRemote = (remoteId: RemoteId) => {\n    const remoteIdString = Uuid.stringify(remoteId)\n    let remote = remotes.get(remoteIdString)\n    if (remote) return remote\n    remote = { sequence: 0, missing: journal.slice() }\n    remotes.set(remoteIdString, remote)\n    return remote\n  }\n\n  return EventJournal.of({\n    entries: Effect.sync(() => journal.slice()),\n    write({ effect, event, payload, primaryKey }) {\n      return Effect.acquireUseRelease(\n        Effect.sync(() =>\n          new Entry({\n            id: makeEntryId(),\n            event,\n            primaryKey,\n            payload\n          }, { disableValidation: true })\n        ),\n        effect,\n        (entry, exit) =>\n          Effect.suspend(() => {\n            if (exit._tag === \"Failure\" || byId.has(entry.idString)) return Effect.void\n            journal.push(entry)\n            byId.set(entry.idString, entry)\n            remotes.forEach((remote) => {\n              remote.missing.push(entry)\n            })\n            return pubsub.publish(entry)\n          })\n      )\n    },\n    writeFromRemote: (options) =>\n      Effect.gen(function*() {\n        const remote = ensureRemote(options.remoteId)\n        const uncommittedRemotes: Array<RemoteEntry> = []\n        const uncommitted: Array<Entry> = []\n        for (const remoteEntry of options.entries) {\n          if (byId.has(remoteEntry.entry.idString)) {\n            if (remoteEntry.remoteSequence > remote.sequence) {\n              remote.sequence = remoteEntry.remoteSequence\n            }\n            continue\n          }\n          uncommittedRemotes.push(remoteEntry)\n          uncommitted.push(remoteEntry.entry)\n        }\n\n        const brackets = options.compact\n          ? yield* options.compact(uncommittedRemotes)\n          : [[uncommitted, uncommittedRemotes]] as const\n\n        for (const [compacted, remoteEntries] of brackets) {\n          for (const originEntry of compacted) {\n            const entryMillis = entryIdMillis(originEntry.id)\n            const conflicts: Array<Entry> = []\n            for (let i = journal.length - 1; i >= -1; i--) {\n              const entry = journal[i]\n              if (entry !== undefined && entry.createdAtMillis > entryMillis) {\n                continue\n              }\n              for (let j = i + 2; j < journal.length; j++) {\n                const entry = journal[j]!\n                if (entry.event === originEntry.event && entry.primaryKey === originEntry.primaryKey) {\n                  conflicts.push(entry)\n                }\n              }\n              yield* options.effect({ entry: originEntry, conflicts })\n              break\n            }\n          }\n          for (let j = 0; j < remoteEntries.length; j++) {\n            const remoteEntry = remoteEntries[j]\n            journal.push(remoteEntry.entry)\n            if (remoteEntry.remoteSequence > remote.sequence) {\n              remote.sequence = remoteEntry.remoteSequence\n            }\n          }\n          journal.sort((a, b) => a.createdAtMillis - b.createdAtMillis)\n        }\n      }),\n    withRemoteUncommited: (remoteId, f) =>\n      Effect.acquireUseRelease(\n        Effect.sync(() => ensureRemote(remoteId).missing.slice()),\n        f,\n        (entries, exit) =>\n          Effect.sync(() => {\n            if (exit._tag === \"Failure\") return\n            const last = entries[entries.length - 1]\n            if (!last) return\n            const remote = ensureRemote(remoteId)\n            for (let i = remote.missing.length - 1; i >= 0; i--) {\n              if (remote.missing[i].id === last.id) {\n                remote.missing = remote.missing.slice(i + 1)\n                break\n              }\n            }\n          })\n      ),\n    nextRemoteSequence: (remoteId) => Effect.sync(() => ensureRemote(remoteId).sequence),\n    changes: PubSub.subscribe(pubsub),\n    destroy: Effect.sync(() => {\n      journal.length = 0\n      byId.clear()\n      remotes.clear()\n    })\n  })\n})\n\n/**\n * @since 1.0.0\n * @category memory\n */\nexport const layerMemory: Layer.Layer<EventJournal> = Layer.effect(EventJournal, makeMemory)\n\n/**\n * @since 1.0.0\n * @category indexed db\n */\nexport const makeIndexedDb = (options?: {\n  readonly database?: string\n}): Effect.Effect<typeof EventJournal.Service, EventJournalError, Scope> =>\n  Effect.gen(function*() {\n    const database = options?.database ?? \"effect_event_journal\"\n    const openRequest = indexedDB.open(database, 1)\n    openRequest.onupgradeneeded = () => {\n      const db = openRequest.result\n\n      const entries = db.createObjectStore(\"entries\", { keyPath: \"id\" })\n      entries.createIndex(\"id\", \"id\", { unique: true })\n      entries.createIndex(\"event\", \"event\")\n\n      const remotes = db.createObjectStore(\"remotes\", { keyPath: [\"remoteId\", \"entryId\"] })\n      remotes.createIndex(\"id\", [\"remoteId\", \"entryId\"], { unique: true })\n      remotes.createIndex(\"sequence\", [\"remoteId\", \"sequence\"], { unique: true })\n\n      const remoteEntryId = db.createObjectStore(\"remoteEntryId\", { keyPath: [\"remoteId\"] })\n      remoteEntryId.createIndex(\"id\", \"remoteId\", { unique: true })\n    }\n    const db = yield* Effect.acquireRelease(\n      idbReq(\"open\", () => openRequest),\n      (db) => Effect.sync(() => db.close())\n    )\n\n    const pubsub = yield* PubSub.unbounded<Entry>()\n\n    return EventJournal.of({\n      entries: idbReq(\n        \"entries\",\n        () =>\n          db.transaction(\"entries\", \"readonly\")\n            .objectStore(\"entries\")\n            .index(\"id\")\n            .getAll()\n      ).pipe(\n        Effect.flatMap((_) =>\n          decodeEntryIdbArray(_).pipe(\n            Effect.mapError((cause) => new EventJournalError({ method: \"entries\", cause }))\n          )\n        )\n      ),\n      write: ({ effect, event, payload, primaryKey }) =>\n        Effect.uninterruptibleMask((restore) => {\n          const entry = new Entry({\n            id: makeEntryId(),\n            event,\n            primaryKey,\n            payload\n          }, { disableValidation: true })\n          return restore(effect(entry)).pipe(\n            Effect.zipLeft(idbReq(\n              \"write\",\n              () =>\n                db\n                  .transaction(\"entries\", \"readwrite\")\n                  .objectStore(\"entries\")\n                  .put(encodeEntryIdb(entry))\n            )),\n            Effect.zipLeft(pubsub.publish(entry))\n          )\n        }),\n      writeFromRemote: (options) =>\n        Effect.gen(function*() {\n          const uncommitted: Array<Entry> = []\n          const uncommittedRemotes: Array<RemoteEntry> = []\n\n          yield* Effect.async<void, EventJournalError>((resume) => {\n            const tx = db.transaction([\"entries\", \"remotes\"], \"readwrite\")\n            const entries = tx.objectStore(\"entries\")\n            const remotes = tx.objectStore(\"remotes\")\n            const iterator = options.entries[Symbol.iterator]()\n            const handleNext = (state: IteratorResult<RemoteEntry, void>) => {\n              if (state.done) return\n              const remoteEntry = state.value\n              const entry = remoteEntry.entry\n              entries.get(entry.id).onsuccess = (event) => {\n                if ((event.target as any).result) {\n                  remotes.put({\n                    remoteId: options.remoteId,\n                    entryId: remoteEntry.entry.id,\n                    sequence: remoteEntry.remoteSequence\n                  })\n                  handleNext(iterator.next())\n                  return\n                }\n                uncommitted.push(entry)\n                uncommittedRemotes.push(remoteEntry)\n                handleNext(iterator.next())\n              }\n            }\n            handleNext(iterator.next())\n            tx.oncomplete = () => resume(Effect.void)\n            tx.onerror = () =>\n              resume(Effect.fail(new EventJournalError({ method: \"writeFromRemote\", cause: tx.error })))\n            return Effect.sync(() => tx.abort())\n          })\n\n          const brackets = options.compact\n            ? yield* options.compact(uncommittedRemotes)\n            : [[uncommitted, uncommittedRemotes]] as const\n\n          for (const [compacted, remoteEntries] of brackets) {\n            for (const originEntry of compacted) {\n              const conflicts: Array<Entry> = []\n              yield* Effect.async<void, EventJournalError>((resume) => {\n                const tx = db.transaction(\"entries\", \"readonly\")\n                const entries = tx.objectStore(\"entries\")\n                const cursorRequest = entries.index(\"id\").openCursor(\n                  IDBKeyRange.lowerBound(originEntry.id, true),\n                  \"next\"\n                )\n                cursorRequest.onsuccess = () => {\n                  const cursor = cursorRequest.result!\n                  if (!cursor) return\n                  const decodedEntry = decodeEntryIdb(cursor.value)\n                  if (\n                    decodedEntry.event === originEntry.event &&\n                    decodedEntry.primaryKey === originEntry.primaryKey\n                  ) {\n                    conflicts.push(decodedEntry)\n                  }\n                  cursor.continue()\n                }\n                tx.oncomplete = () => resume(Effect.void)\n                tx.onerror = () =>\n                  resume(Effect.fail(new EventJournalError({ method: \"writeFromRemote\", cause: tx.error })))\n                return Effect.sync(() => tx.abort())\n              })\n\n              yield* options.effect({ entry: originEntry, conflicts })\n            }\n\n            yield* Effect.async<void, EventJournalError>((resume) => {\n              const tx = db.transaction([\"entries\", \"remotes\"], \"readwrite\")\n              const entries = tx.objectStore(\"entries\")\n              const remotes = tx.objectStore(\"remotes\")\n              for (const remoteEntry of remoteEntries) {\n                entries.add(encodeEntryIdb(remoteEntry.entry))\n                remotes.put({\n                  remoteId: options.remoteId,\n                  entryId: remoteEntry.entry.id,\n                  sequence: remoteEntry.remoteSequence\n                })\n              }\n              tx.oncomplete = () => resume(Effect.void)\n              tx.onerror = () =>\n                resume(Effect.fail(new EventJournalError({ method: \"writeFromRemote\", cause: tx.error })))\n              return Effect.sync(() => tx.abort())\n            })\n          }\n        }),\n      withRemoteUncommited: (remoteId, f) =>\n        Effect.async<Array<Entry>, EventJournalError>((resume) => {\n          const entries: Array<Entry> = []\n          const tx = db.transaction([\"entries\", \"remotes\", \"remoteEntryId\"], \"readwrite\")\n\n          const entriesStore = tx.objectStore(\"entries\")\n          const remotesStore = tx.objectStore(\"remotes\")\n          const remoteEntryIdStore = tx.objectStore(\"remoteEntryId\")\n\n          remoteEntryIdStore.get(remoteId).onsuccess = (event) => {\n            const startEntryId = (event.target as any).result?.entryId\n            const entryCursor = entriesStore.index(\"id\").openCursor(\n              startEntryId ? IDBKeyRange.lowerBound(startEntryId, true) : null,\n              \"next\"\n            )\n            entryCursor.onsuccess = () => {\n              const cursor = entryCursor.result\n              if (!cursor) return\n              const entry = decodeEntryIdb(cursor.value)\n              remotesStore.get([remoteId, entry.id]).onsuccess = (event) => {\n                if (!(event.target as any).result) entries.push(entry)\n                cursor.continue()\n              }\n            }\n          }\n\n          tx.oncomplete = () => resume(Effect.succeed(entries))\n          tx.onerror = () =>\n            resume(Effect.fail(new EventJournalError({ method: \"withRemoteUncommited\", cause: tx.error })))\n          return Effect.sync(() => tx.abort())\n        }).pipe(\n          Effect.flatMap((entries) => {\n            if (entries.length === 0) return f(entries)\n            const entryId = entries[entries.length - 1].id\n            return Effect.uninterruptibleMask((restore) =>\n              restore(f(entries)).pipe(\n                Effect.zipLeft(idbReq(\"withRemoteUncommited\", () =>\n                  db.transaction(\"remoteEntryId\", \"readwrite\").objectStore(\"remoteEntryId\").put({\n                    remoteId,\n                    entryId\n                  })))\n              )\n            )\n          })\n        ),\n      nextRemoteSequence: (remoteId) =>\n        Effect.async<number, EventJournalError>((resume) => {\n          const tx = db.transaction(\"remotes\", \"readonly\")\n          let sequence = 0\n          const cursorRequest = tx.objectStore(\"remotes\").index(\"sequence\").openCursor(\n            IDBKeyRange.bound([remoteId, 0], [remoteId, Infinity]),\n            \"prev\"\n          )\n          cursorRequest.onsuccess = () => {\n            const cursor = cursorRequest.result\n            if (!cursor) return\n            sequence = cursor.value.sequence + 1\n          }\n          tx.oncomplete = () => resume(Effect.succeed(sequence))\n          tx.onerror = () =>\n            resume(Effect.fail(new EventJournalError({ method: \"nextRemoteSequence\", cause: tx.error })))\n          return Effect.sync(() => tx.abort())\n        }),\n      changes: PubSub.subscribe(pubsub),\n      destroy: Effect.sync(() => {\n        indexedDB.deleteDatabase(database)\n      })\n    })\n  })\n\nconst decodeEntryIdb = Schema.decodeSync(Entry)\nconst encodeEntryIdb = Schema.encodeSync(Entry)\nconst EntryIdbArray = Schema.Array(Entry)\nconst decodeEntryIdbArray = Schema.decodeUnknown(EntryIdbArray)\n\n/**\n * @since 1.0.0\n * @category indexed db\n */\nexport const layerIndexedDb = (options?: {\n  readonly database?: string\n}): Layer.Layer<EventJournal, EventJournalError> =>\n  Layer.scoped(\n    EventJournal,\n    makeIndexedDb(options)\n  )\n\nconst idbReq = <T>(method: string, evaluate: () => IDBRequest<T>) =>\n  Effect.async<T, EventJournalError>((resume) => {\n    const request = evaluate()\n    if (request.readyState === \"done\") {\n      resume(Effect.succeed(request.result))\n      return\n    }\n    request.onsuccess = () => resume(Effect.succeed(request.result))\n    request.onerror = () => resume(Effect.fail(new EventJournalError({ method, cause: request.error })))\n  })\n"
  },
  {
    "path": "packages/experimental/src/EventLog.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Error from \"@effect/platform/Error\"\nimport * as KeyValueStore from \"@effect/platform/KeyValueStore\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberMap from \"effect/FiberMap\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Queue from \"effect/Queue\"\nimport type * as Record from \"effect/Record\"\nimport * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport type { Scope } from \"effect/Scope\"\nimport type { Covariant } from \"effect/Types\"\nimport type { Event } from \"./Event.js\"\nimport type { EventGroup } from \"./EventGroup.js\"\nimport type { EventJournalError, RemoteEntry, RemoteId } from \"./EventJournal.js\"\nimport { Entry, EventJournal, makeEntryId } from \"./EventJournal.js\"\nimport { type EventLogRemote } from \"./EventLogRemote.js\"\nimport * as Reactivity from \"./Reactivity.js\"\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const SchemaTypeId: unique symbol = Symbol.for(\"@effect/experimental/EventLog/EventLogSchema\")\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport type SchemaTypeId = typeof SchemaTypeId\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const isEventLogSchema = (u: unknown): u is EventLogSchema<any> => Predicate.hasProperty(u, SchemaTypeId)\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport interface EventLogSchema<Groups extends EventGroup.Any> {\n  new(_: never): {}\n  readonly [SchemaTypeId]: SchemaTypeId\n  readonly groups: ReadonlyArray<Groups>\n}\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schema = <Groups extends ReadonlyArray<EventGroup.Any>>(\n  ...groups: Groups\n): EventLogSchema<Groups[number]> => {\n  function EventLog() {}\n  EventLog[SchemaTypeId] = SchemaTypeId\n  EventLog.groups = groups\n  return EventLog as any\n}\n\n/**\n * @since 1.0.0\n * @category handlers\n */\nexport const HandlersTypeId: unique symbol = Symbol.for(\"@effect/experimental/EventLog/Handlers\")\n\n/**\n * @since 1.0.0\n * @category handlers\n */\nexport type HandlersTypeId = typeof HandlersTypeId\n\n/**\n * Represents a handled `EventGroup`.\n *\n * @since 1.0.0\n * @category handlers\n */\nexport interface Handlers<\n  R,\n  Events extends Event.Any = never\n> extends Pipeable {\n  readonly [HandlersTypeId]: {\n    _Endpoints: Covariant<Events>\n  }\n  readonly group: EventGroup.AnyWithProps\n  readonly handlers: Record.ReadonlyRecord<string, Handlers.Item<R>>\n  readonly context: Context.Context<any>\n\n  /**\n   * Add the implementation for an `Event` to a `Handlers` group.\n   */\n  handle<Tag extends Events[\"tag\"], R1>(\n    name: Tag,\n    handler: (\n      options: {\n        readonly payload: Event.PayloadWithTag<Events, Tag>\n        readonly entry: Entry\n        readonly conflicts: Array<{\n          readonly entry: Entry\n          readonly payload: Event.PayloadWithTag<Events, Tag>\n        }>\n      }\n    ) => Effect.Effect<Event.SuccessWithTag<Events, Tag>, Event.ErrorWithTag<Events, Tag>, R1>\n  ): Handlers<\n    R | R1,\n    Event.ExcludeTag<Events, Tag>\n  >\n}\n\n/**\n * @since 1.0.0\n * @category handlers\n */\nexport declare namespace Handlers {\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export interface Any {\n    readonly [HandlersTypeId]: any\n  }\n\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export type Item<R> = {\n    readonly event: Event.AnyWithProps\n    readonly context: Context.Context<any>\n    readonly handler: (options: {\n      readonly payload: any\n      readonly entry: Entry\n      readonly conflicts: Array<{\n        readonly entry: Entry\n        readonly payload: any\n      }>\n    }) => Effect.Effect<any, R>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export type ValidateReturn<A> = A extends (\n    | Handlers<\n      infer _R,\n      infer _Events\n    >\n    | Effect.Effect<\n      Handlers<\n        infer _R,\n        infer _Events\n      >,\n      infer _EX,\n      infer _RX\n    >\n  ) ? [_Events] extends [never] ? A\n    : `Event not handled: ${Event.Tag<_Events>}` :\n    `Must return the implemented handlers`\n\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export type Error<A> = A extends Effect.Effect<\n    Handlers<\n      infer _R,\n      infer _Events\n    >,\n    infer _EX,\n    infer _RX\n  > ? _EX :\n    never\n\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export type Context<A> = A extends Handlers<\n    infer _R,\n    infer _Events\n  > ? _R | Event.Context<_Events> :\n    A extends Effect.Effect<\n      Handlers<\n        infer _R,\n        infer _Events\n      >,\n      infer _EX,\n      infer _RX\n    > ? _R | _RX | Event.Context<_Events> :\n    never\n}\n\nconst handlersProto = {\n  [HandlersTypeId]: {\n    _Endpoints: identity\n  },\n  handle<Tag extends string, R1>(\n    this: Handlers<any, any>,\n    tag: Tag,\n    handler: (payload: any) => Effect.Effect<any, R1>\n  ): Handlers<any, any> {\n    return makeHandlers({\n      group: this.group,\n      context: this.context,\n      handlers: {\n        ...this.handlers,\n        [tag]: {\n          event: this.group.events[tag],\n          context: this.context,\n          handler\n        }\n      }\n    })\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makeHandlers = <Events extends Event.Any>(options: {\n  readonly group: EventGroup.AnyWithProps\n  readonly handlers: Record.ReadonlyRecord<string, Handlers.Item<any>>\n  readonly context: Context.Context<any>\n}): Handlers<never, Events> => Object.assign(Object.create(handlersProto), options)\n\n/**\n * @since 1.0.0\n * @category handlers\n */\nexport const group = <Events extends Event.Any, Return>(\n  group: EventGroup<Events>,\n  f: (handlers: Handlers<never, Events>) => Handlers.ValidateReturn<Return>\n): Layer.Layer<Event.ToService<Events>, Handlers.Error<Return>, Exclude<Handlers.Context<Return>, Scope>> =>\n  Effect.gen(function*() {\n    const context = yield* Effect.context<Handlers.Context<Return>>()\n    const result = f(makeHandlers({\n      group: group as any,\n      handlers: {},\n      context\n    }))\n    const handlers = Effect.isEffect(result) ? yield* (result as any as Effect.Effect<any>) : result\n    const registry = yield* Registry\n    yield* registry.add(handlers)\n  }).pipe(\n    Layer.scopedDiscard,\n    Layer.provide(Registry.layer)\n  ) as any\n\n/**\n * @since 1.0.0\n * @category compaction\n */\nexport const groupCompaction = <Events extends Event.Any, R>(\n  group: EventGroup<Events>,\n  effect: (options: {\n    readonly primaryKey: string\n    readonly entries: Array<Entry>\n    readonly events: Array<Event.TaggedPayload<Events>>\n    readonly write: <Tag extends Event.Tag<Events>>(\n      tag: Tag,\n      payload: Event.PayloadWithTag<Events, Tag>\n    ) => Effect.Effect<void>\n  }) => Effect.Effect<void, never, R>\n): Layer.Layer<never, never, Identity | EventJournal | R | Event.Context<Events>> =>\n  Effect.gen(function*() {\n    const log = yield* EventLog\n    const context = yield* Effect.context<R | Event.Context<Events>>()\n\n    yield* log.registerCompaction({\n      events: Object.keys(group.events),\n      effect: Effect.fnUntraced(function*({ entries, write }) {\n        const writePayload = (timestamp: number, tag: string, payload: any) =>\n          Effect.gen(function*() {\n            const event = group.events[tag] as any as Event.AnyWithProps\n            const entry = new Entry({\n              id: makeEntryId({ msecs: timestamp }),\n              event: tag,\n              payload: yield* (Schema.encode(event.payloadMsgPack)(payload).pipe(\n                Effect.locally(FiberRef.currentContext, context),\n                Effect.orDie\n              ) as Effect.Effect<Uint8Array>),\n              primaryKey: event.primaryKey(payload)\n            }, { disableValidation: true })\n            yield* write(entry)\n          })\n\n        const byPrimaryKey = new Map<\n          string,\n          {\n            readonly entries: Array<Entry>\n            readonly taggedPayloads: Array<{\n              readonly _tag: string\n              readonly payload: any\n            }>\n          }\n        >()\n        for (const entry of entries) {\n          const payload =\n            yield* (Schema.decodeUnknown((group.events[entry.event] as any).payloadMsgPack)(entry.payload).pipe(\n              Effect.locally(FiberRef.currentContext, context)\n            ) as Effect.Effect<any>)\n\n          if (byPrimaryKey.has(entry.primaryKey)) {\n            const record = byPrimaryKey.get(entry.primaryKey)!\n            record.entries.push(entry)\n            record.taggedPayloads.push({\n              _tag: entry.event,\n              payload\n            })\n          } else {\n            byPrimaryKey.set(entry.primaryKey, {\n              entries: [entry],\n              taggedPayloads: [{ _tag: entry.event, payload }]\n            })\n          }\n        }\n\n        for (const [primaryKey, { entries, taggedPayloads }] of byPrimaryKey) {\n          yield* (effect({\n            primaryKey,\n            entries,\n            events: taggedPayloads as any,\n            write(tag, payload) {\n              return writePayload(entries[0].createdAtMillis, tag, payload)\n            }\n          }).pipe(\n            Effect.locally(FiberRef.currentContext, context)\n          ) as Effect.Effect<void>)\n        }\n      })\n    })\n  }).pipe(\n    Layer.scopedDiscard,\n    Layer.provide(layerEventLog)\n  )\n\n/**\n * @since 1.0.0\n * @category reactivity\n */\nexport const groupReactivity = <Events extends Event.Any>(\n  group: EventGroup<Events>,\n  keys:\n    | { readonly [Tag in Event.Tag<Events>]?: ReadonlyArray<string> }\n    | ReadonlyArray<string>\n): Layer.Layer<never, never, Identity | EventJournal> =>\n  Effect.gen(function*() {\n    const log = yield* EventLog\n    if (!Array.isArray(keys)) {\n      yield* log.registerReactivity(keys as any)\n      return\n    }\n    const obj: Record<string, ReadonlyArray<string>> = {}\n    for (const tag in group.events) {\n      obj[tag] = keys\n    }\n    yield* log.registerReactivity(obj)\n  }).pipe(\n    Layer.scopedDiscard,\n    Layer.provide(layerEventLog)\n  )\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport class Registry extends Context.Tag(\"@effect/experimental/EventLog/Registry\")<\n  Registry,\n  {\n    readonly add: (handlers: Handlers.Any) => Effect.Effect<void>\n    readonly handlers: Effect.Effect<Record.ReadonlyRecord<string, Handlers.Item<any>>>\n  }\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static layer = Layer.sync(Registry, () => {\n    const items: Record<string, Handlers.Item<any>> = {}\n\n    return {\n      add: (handlers: Handlers<any, never>) =>\n        Effect.sync(() => {\n          for (const tag in handlers.handlers) {\n            items[tag] = handlers.handlers[tag]\n          }\n        }),\n      handlers: Effect.sync(() => items)\n    } as any\n  })\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport class Identity extends Context.Tag(\"@effect/experimental/EventLog/Identity\")<Identity, {\n  readonly publicKey: string\n  readonly privateKey: Redacted.Redacted<Uint8Array>\n}>() {\n  /**\n   * @since 1.0.0\n   */\n  static makeRandom() {\n    return Identity.of({\n      publicKey: crypto.randomUUID(),\n      privateKey: Redacted.make(crypto.getRandomValues(new Uint8Array(32)))\n    })\n  }\n  /**\n   * @since 1.0.0\n   */\n  static readonly Schema = Schema.Struct({\n    publicKey: Schema.String,\n    privateKey: Schema.Redacted(Schema.Uint8ArrayFromBase64)\n  })\n  /**\n   * @since 1.0.0\n   */\n  static readonly SchemaFromString = Schema.StringFromBase64Url.pipe(\n    Schema.compose(Schema.parseJson(this.Schema))\n  )\n\n  /**\n   * @since 1.0.0\n   */\n  static decodeString = (s: string): Identity[\"Type\"] => Schema.decodeSync(Identity.SchemaFromString)(s)\n  /**\n   * @since 1.0.0\n   */\n  static encodeString = (identity: Identity[\"Type\"]): string => Schema.encodeSync(Identity.SchemaFromString)(identity)\n}\n\n/**\n * Generates a random `Identity` and stores it in a `KeyValueStore`.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerIdentityKvs = (options: {\n  readonly key: string\n}): Layer.Layer<Identity, ParseResult.ParseError | Error.PlatformError, KeyValueStore.KeyValueStore> =>\n  Layer.effect(\n    Identity,\n    Effect.gen(function*() {\n      const store = (yield* KeyValueStore.KeyValueStore).forSchema(Identity.Schema)\n      const current = yield* store.get(options.key)\n      if (Option.isSome(current)) {\n        return current.value\n      }\n      const identity = Identity.makeRandom()\n      yield* store.set(options.key, identity)\n      return identity\n    })\n  )\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport class EventLog extends Context.Tag(\"@effect/experimental/EventLog/EventLog\")<EventLog, {\n  readonly write: <Groups extends EventGroup.Any, Tag extends Event.Tag<EventGroup.Events<Groups>>>(options: {\n    readonly schema: EventLogSchema<Groups>\n    readonly event: Tag\n    readonly payload: Event.PayloadWithTag<EventGroup.Events<Groups>, Tag>\n  }) => Effect.Effect<\n    Event.SuccessWithTag<EventGroup.Events<Groups>, Tag>,\n    Event.ErrorWithTag<EventGroup.Events<Groups>, Tag> | EventJournalError\n  >\n  readonly registerRemote: (remote: EventLogRemote) => Effect.Effect<void, never, Scope>\n  readonly registerCompaction: (options: {\n    readonly events: ReadonlyArray<string>\n    readonly effect: (options: {\n      readonly entries: ReadonlyArray<Entry>\n      readonly write: (entry: Entry) => Effect.Effect<void>\n    }) => Effect.Effect<void>\n  }) => Effect.Effect<void, never, Scope>\n  readonly registerReactivity: (keys: Record<string, ReadonlyArray<string>>) => Effect.Effect<void, never, Scope>\n  readonly entries: Effect.Effect<ReadonlyArray<Entry>, EventJournalError>\n  readonly destroy: Effect.Effect<void, EventJournalError>\n}>() {}\n\nconst make = Effect.gen(function*() {\n  const identity = yield* Identity\n  const registry = yield* Registry\n  const journal = yield* EventJournal\n  const handlers = yield* registry.handlers\n  const remotes = yield* FiberMap.make<RemoteId>()\n  const compactors = new Map<string, {\n    readonly events: ReadonlySet<string>\n    readonly effect: (options: {\n      readonly entries: ReadonlyArray<Entry>\n      readonly write: (entry: Entry) => Effect.Effect<void>\n    }) => Effect.Effect<void>\n  }>()\n  const journalSemaphore = yield* Effect.makeSemaphore(1)\n\n  const reactivity = yield* Reactivity.Reactivity\n  const reactivityKeys: Record<string, ReadonlyArray<string>> = {}\n\n  const runRemote = Effect.fnUntraced(\n    function*(remote: EventLogRemote) {\n      const startSequence = yield* journal.nextRemoteSequence(remote.id)\n      const changes = yield* remote.changes(identity, startSequence)\n\n      yield* changes.takeAll.pipe(\n        Effect.flatMap(([entries]) =>\n          journal.writeFromRemote({\n            remoteId: remote.id,\n            entries: Chunk.toReadonlyArray(entries),\n            compact: compactors.size > 0 ?\n              Effect.fnUntraced(function*(remoteEntries) {\n                let unprocessed = remoteEntries as Array<RemoteEntry>\n                const brackets: Array<[Array<Entry>, Array<RemoteEntry>]> = []\n                let uncompacted: Array<Entry> = []\n                let uncompactedRemote: Array<RemoteEntry> = []\n                while (true) {\n                  let i = 0\n                  for (; i < unprocessed.length; i++) {\n                    const remoteEntry = unprocessed[i]\n                    if (!compactors.has(remoteEntry.entry.event)) {\n                      uncompacted.push(remoteEntry.entry)\n                      uncompactedRemote.push(remoteEntry)\n                      continue\n                    }\n                    if (uncompacted.length > 0) {\n                      brackets.push([uncompacted, uncompactedRemote])\n                      uncompacted = []\n                      uncompactedRemote = []\n                    }\n                    const compactor = compactors.get(remoteEntry.entry.event)!\n                    const entry = remoteEntry.entry\n                    const entries = [entry]\n                    const remoteEntries = [remoteEntry]\n                    const compacted: Array<Entry> = []\n                    const currentEntries = unprocessed\n                    unprocessed = []\n                    for (let j = i + 1; j < currentEntries.length; j++) {\n                      const nextRemoteEntry = currentEntries[j]\n                      if (!compactor.events.has(nextRemoteEntry.entry.event)) {\n                        unprocessed.push(nextRemoteEntry)\n                        continue\n                      }\n                      entries.push(nextRemoteEntry.entry)\n                      remoteEntries.push(nextRemoteEntry)\n                    }\n                    yield* compactor.effect({\n                      entries,\n                      write(entry) {\n                        return Effect.sync(() => {\n                          compacted.push(entry)\n                        })\n                      }\n                    })\n                    brackets.push([compacted, remoteEntries])\n                    break\n                  }\n                  if (i === unprocessed.length) {\n                    brackets.push([unprocessed.map((_) => _.entry), unprocessed])\n                    break\n                  }\n                }\n                return brackets\n              }) :\n              undefined,\n            effect: Effect.fnUntraced(\n              function*({ conflicts, entry }) {\n                const handler = handlers[entry.event]\n                if (!handler) {\n                  return yield* Effect.logDebug(`Event handler not found for: \"${entry.event}\"`)\n                }\n                const decodePayload = Schema.decode(\n                  handlers[entry.event].event.payloadMsgPack as unknown as Schema.Schema<any>\n                )\n                const decodedConflicts: Array<{ entry: Entry; payload: any }> = new Array(conflicts.length)\n                for (let i = 0; i < conflicts.length; i++) {\n                  decodedConflicts[i] = {\n                    entry: conflicts[i],\n                    payload: yield* decodePayload(conflicts[i].payload)\n                  }\n                }\n                yield* handler.handler({\n                  payload: yield* decodePayload(entry.payload),\n                  entry,\n                  conflicts: decodedConflicts\n                })\n                if (reactivityKeys[entry.event]) {\n                  for (const key of reactivityKeys[entry.event]) {\n                    reactivity.unsafeInvalidate({\n                      [key]: [entry.primaryKey]\n                    })\n                  }\n                }\n              },\n              Effect.catchAllCause(Effect.log),\n              (effect, { entry }) =>\n                Effect.annotateLogs(effect, {\n                  service: \"EventLog\",\n                  effect: \"writeFromRemote\",\n                  entryId: entry.idString\n                })\n            )\n          }).pipe(journalSemaphore.withPermits(1))\n        ),\n        Effect.catchAllCause(Effect.log),\n        Effect.forever,\n        Effect.annotateLogs({\n          service: \"EventLog\",\n          effect: \"runRemote consume\"\n        }),\n        Effect.fork\n      )\n\n      const write = journal.withRemoteUncommited(remote.id, (entries) => remote.write(identity, entries))\n      yield* Effect.addFinalizer(() => Effect.ignore(write))\n      yield* write\n      return yield* Queue.takeBetween(yield* journal.changes, 1, Number.MAX_SAFE_INTEGER).pipe(\n        Effect.zipRight(Effect.sleep(500)),\n        Effect.zipRight(write),\n        Effect.catchAllCause(Effect.log),\n        Effect.forever\n      )\n    },\n    Effect.scoped,\n    Effect.provideService(Identity, identity),\n    Effect.interruptible\n  )\n\n  const writeHandler = Effect.fnUntraced(function*(handler: Handlers.Item<any>, options: {\n    readonly schema: EventLogSchema<any>\n    readonly event: string\n    readonly payload: any\n  }) {\n    const payload = yield* Effect.orDie(\n      Schema.encode(handlers[options.event].event.payloadMsgPack as unknown as Schema.Schema<Uint8Array>)(\n        options.payload\n      )\n    )\n    return yield* journalSemaphore.withPermits(1)(journal.write({\n      event: options.event,\n      primaryKey: handler.event.primaryKey(options.payload),\n      payload,\n      effect: (entry) =>\n        Effect.tap(\n          handler.handler({\n            payload: options.payload,\n            entry,\n            conflicts: []\n          }),\n          () => {\n            if (reactivityKeys[entry.event]) {\n              for (const key of reactivityKeys[entry.event]) {\n                reactivity.unsafeInvalidate({\n                  [key]: [entry.primaryKey]\n                })\n              }\n            }\n          }\n        )\n    }))\n  }, (effect, handler) => Effect.mapInputContext(effect, (context) => Context.merge(handler.context, context)))\n\n  return EventLog.of({\n    write: (options: {\n      readonly schema: EventLogSchema<any>\n      readonly event: string\n      readonly payload: any\n    }) => {\n      const handler = handlers[options.event]\n      if (handler === undefined) {\n        return Effect.die(`Event handler not found for: \"${options.event}\"`)\n      }\n      return writeHandler(handler, options) as any\n    },\n    entries: journal.entries,\n    registerRemote: (remote) =>\n      Effect.acquireRelease(\n        FiberMap.run(remotes, remote.id, runRemote(remote)),\n        () => FiberMap.remove(remotes, remote.id)\n      ),\n    registerCompaction: (options) =>\n      Effect.acquireRelease(\n        Effect.sync(() => {\n          const events = new Set(options.events)\n          const compactor = {\n            events,\n            effect: options.effect\n          }\n          for (const event of options.events) {\n            compactors.set(event, compactor)\n          }\n        }),\n        () =>\n          Effect.sync(() => {\n            for (const event of options.events) {\n              compactors.delete(event)\n            }\n          })\n      ),\n    registerReactivity: (keys) =>\n      Effect.sync(() => {\n        Object.assign(reactivityKeys, keys)\n      }),\n    destroy: journal.destroy\n  })\n})\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerEventLog: Layer.Layer<EventLog, never, EventJournal | Identity> = Layer.scoped(EventLog, make).pipe(\n  Layer.provide([Registry.layer, Reactivity.layer])\n)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer = <Groups extends EventGroup.Any>(_schema: EventLogSchema<Groups>): Layer.Layer<\n  EventLog,\n  never,\n  EventGroup.ToService<Groups> | EventJournal | Identity\n> => layerEventLog as any\n\n/**\n * @since 1.0.0\n * @category client\n */\nexport const makeClient = <Groups extends EventGroup.Any>(\n  schema: EventLogSchema<Groups>\n): Effect.Effect<\n  (<Tag extends Event.Tag<EventGroup.Events<Groups>>>(\n    event: Tag,\n    payload: Event.PayloadWithTag<EventGroup.Events<Groups>, Tag>\n  ) => Effect.Effect<\n    Event.SuccessWithTag<EventGroup.Events<Groups>, Tag>,\n    Event.ErrorWithTag<EventGroup.Events<Groups>, Tag> | EventJournalError\n  >),\n  never,\n  EventLog\n> =>\n  Effect.gen(function*() {\n    const log = yield* EventLog\n\n    return <Tag extends Event.Tag<EventGroup.Events<Groups>>>(\n      event: Tag,\n      payload: Event.PayloadWithTag<EventGroup.Events<Groups>, Tag>\n    ): Effect.Effect<\n      Event.SuccessWithTag<EventGroup.Events<Groups>, Tag>,\n      Event.ErrorWithTag<EventGroup.Events<Groups>, Tag> | EventJournalError\n    > => log.write({ schema, event, payload })\n  })\n"
  },
  {
    "path": "packages/experimental/src/EventLogEncryption.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport { Entry, EntryId, RemoteEntry } from \"./EventJournal.js\"\nimport type { Identity } from \"./EventLog.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport const EncryptedEntry = Schema.Struct({\n  entryId: EntryId,\n  encryptedEntry: Schema.Uint8ArrayFromSelf\n})\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface EncryptedRemoteEntry extends Schema.Schema.Type<typeof EncryptedRemoteEntry> {}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport const EncryptedRemoteEntry = Schema.Struct({\n  sequence: Schema.Number,\n  iv: Schema.Uint8ArrayFromSelf,\n  entryId: EntryId,\n  encryptedEntry: Schema.Uint8ArrayFromSelf\n})\n\n/**\n * @since 1.0.0\n * @category encrytion\n */\nexport class EventLogEncryption extends Context.Tag(\"@effect/experimental/EventLogEncryption\")<\n  EventLogEncryption,\n  {\n    readonly encrypt: (\n      identity: typeof Identity.Service,\n      entries: ReadonlyArray<Entry>\n    ) => Effect.Effect<{\n      readonly iv: Uint8Array\n      readonly encryptedEntries: ReadonlyArray<Uint8Array>\n    }>\n    readonly decrypt: (\n      identity: typeof Identity.Service,\n      entries: ReadonlyArray<EncryptedRemoteEntry>\n    ) => Effect.Effect<Array<RemoteEntry>>\n    readonly sha256String: (data: Uint8Array) => Effect.Effect<string>\n    readonly sha256: (data: Uint8Array) => Effect.Effect<Uint8Array>\n  }\n>() {}\n\n/**\n * @since 1.0.0\n * @category encrytion\n */\nexport const makeEncryptionSubtle = (crypto: Crypto): Effect.Effect<typeof EventLogEncryption.Service> =>\n  Effect.sync(() => {\n    const keyCache = new WeakMap<typeof Identity.Service, CryptoKey>()\n    const getKey = (identity: typeof Identity.Service) =>\n      Effect.suspend(() => {\n        if (keyCache.has(identity)) {\n          return Effect.succeed(keyCache.get(identity)!)\n        }\n        return Effect.promise(() =>\n          crypto.subtle.importKey(\n            \"raw\",\n            Redacted.value(identity.privateKey),\n            \"AES-GCM\",\n            true,\n            [\"encrypt\", \"decrypt\"]\n          )\n        ).pipe(\n          Effect.tap((key) => {\n            keyCache.set(identity, key)\n          })\n        )\n      })\n\n    return EventLogEncryption.of({\n      encrypt: (identity, entries) =>\n        Effect.gen(function*() {\n          const data = yield* Effect.orDie(Entry.encodeArray(entries))\n          const key = yield* getKey(identity)\n          const iv = crypto.getRandomValues(new Uint8Array(12))\n          const encryptedEntries = yield* Effect.promise(() =>\n            Promise.all(\n              data.map((entry) => crypto.subtle.encrypt({ name: \"AES-GCM\", iv, tagLength: 128 }, key, entry))\n            )\n          )\n          return {\n            iv,\n            encryptedEntries: encryptedEntries.map((entry) => new Uint8Array(entry))\n          }\n        }),\n      decrypt: (identity, entries) =>\n        Effect.gen(function*() {\n          const key = yield* getKey(identity)\n          const decryptedData = (yield* Effect.promise(() =>\n            Promise.all(entries.map((data) =>\n              crypto.subtle.decrypt(\n                { name: \"AES-GCM\", iv: data.iv, tagLength: 128 },\n                key,\n                data.encryptedEntry\n              )\n            ))\n          )).map((buffer) => new Uint8Array(buffer))\n          const decoded = yield* Effect.orDie(Entry.decodeArray(decryptedData))\n          return decoded.map((entry, i) => new RemoteEntry({ remoteSequence: entries[i].sequence, entry }))\n        }),\n      sha256: (data) =>\n        Effect.promise(() => crypto.subtle.digest(\"SHA-256\", data)).pipe(\n          Effect.map((hash) => new Uint8Array(hash))\n        ),\n      sha256String: (data) =>\n        Effect.map(\n          Effect.promise(() => crypto.subtle.digest(\"SHA-256\", data)),\n          (hash) => {\n            const hashArray = Array.from(new Uint8Array(hash))\n            const hashHex = hashArray\n              .map((bytes) => bytes.toString(16).padStart(2, \"0\"))\n              .join(\"\")\n            return hashHex\n          }\n        )\n    })\n  })\n\n/**\n * @since 1.0.0\n * @category encrytion\n */\nexport const layerSubtle: Layer.Layer<EventLogEncryption> = Layer.suspend(() =>\n  Layer.effect(EventLogEncryption, makeEncryptionSubtle(globalThis.crypto))\n)\n"
  },
  {
    "path": "packages/experimental/src/EventLogRemote.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as MsgPack from \"@effect/platform/MsgPack\"\nimport * as Socket from \"@effect/platform/Socket\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Layer from \"effect/Layer\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as RcMap from \"effect/RcMap\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Schema from \"effect/Schema\"\nimport * as Scope from \"effect/Scope\"\nimport type { Entry } from \"./EventJournal.js\"\nimport { RemoteEntry, RemoteId } from \"./EventJournal.js\"\nimport type { Identity } from \"./EventLog.js\"\nimport { EventLog } from \"./EventLog.js\"\nimport { EncryptedEntry, EncryptedRemoteEntry, EventLogEncryption, layerSubtle } from \"./EventLogEncryption.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface EventLogRemote {\n  readonly id: RemoteId\n  readonly changes: (\n    identity: typeof Identity.Service,\n    startSequence: number\n  ) => Effect.Effect<Mailbox.ReadonlyMailbox<RemoteEntry>, never, Scope.Scope>\n  readonly write: (identity: typeof Identity.Service, entries: ReadonlyArray<Entry>) => Effect.Effect<void>\n}\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport class Hello extends Schema.TaggedClass<Hello>(\"@effect/experimental/EventLogRemote/Hello\")(\"Hello\", {\n  remoteId: RemoteId\n}) {}\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport class ChunkedMessage\n  extends Schema.TaggedClass<ChunkedMessage>(\"@effect/experimental/EventLogRemote/ChunkedMessage\")(\"ChunkedMessage\", {\n    id: Schema.Number,\n    part: Schema.Tuple(Schema.Number, Schema.Number),\n    data: Schema.Uint8ArrayFromSelf\n  })\n{\n  /**\n   * @since 1.0.0\n   */\n  static split(id: number, data: Uint8Array): ReadonlyArray<ChunkedMessage> {\n    const parts = Math.ceil(data.byteLength / constChunkSize)\n    const result: Array<ChunkedMessage> = new Array(parts)\n    for (let i = 0; i < parts; i++) {\n      const start = i * constChunkSize\n      const end = Math.min((i + 1) * constChunkSize, data.byteLength)\n      result[i] = new ChunkedMessage({ id, part: [i, parts], data: data.subarray(start, end) })\n    }\n    return result\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  static join(\n    map: Map<number, {\n      readonly parts: Array<Uint8Array>\n      count: number\n      bytes: number\n    }>,\n    part: ChunkedMessage\n  ): Uint8Array | undefined {\n    const [index, total] = part.part\n    let entry = map.get(part.id)\n    if (!entry) {\n      entry = {\n        parts: new Array(total),\n        count: 0,\n        bytes: 0\n      }\n      map.set(part.id, entry)\n    }\n    entry.parts[index] = part.data\n    entry.count++\n    entry.bytes += part.data.byteLength\n    if (entry.count !== total) {\n      return\n    }\n    const data = new Uint8Array(entry.bytes)\n    let offset = 0\n    for (const part of entry.parts) {\n      data.set(part, offset)\n      offset += part.byteLength\n    }\n    map.delete(part.id)\n    return data\n  }\n}\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport class WriteEntries\n  extends Schema.TaggedClass<WriteEntries>(\"@effect/experimental/EventLogRemote/WriteEntries\")(\"WriteEntries\", {\n    publicKey: Schema.String,\n    id: Schema.Number,\n    iv: Schema.Uint8ArrayFromSelf,\n    encryptedEntries: Schema.Array(EncryptedEntry)\n  })\n{}\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport class Ack extends Schema.TaggedClass<Ack>(\"@effect/experimental/EventLogRemote/Ack\")(\"Ack\", {\n  id: Schema.Number,\n  sequenceNumbers: Schema.Array(Schema.Number)\n}) {}\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport class RequestChanges\n  extends Schema.TaggedClass<RequestChanges>(\"@effect/experimental/EventLogRemote/RequestChanges\")(\"RequestChanges\", {\n    publicKey: Schema.String,\n    startSequence: Schema.Number\n  })\n{}\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport class Changes extends Schema.TaggedClass<Changes>(\"@effect/experimental/EventLogRemote/Changes\")(\"Changes\", {\n  publicKey: Schema.String,\n  entries: Schema.Array(EncryptedRemoteEntry)\n}) {}\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport class StopChanges\n  extends Schema.TaggedClass<StopChanges>(\"@effect/experimental/EventLogRemote/StopChanges\")(\"StopChanges\", {\n    publicKey: Schema.String\n  })\n{}\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport class Ping extends Schema.TaggedClass<Ping>(\"@effect/experimental/EventLogRemote/Ping\")(\"Ping\", {\n  id: Schema.Number\n}) {}\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport class Pong extends Schema.TaggedClass<Pong>(\"@effect/experimental/EventLogRemote/Pong\")(\"Pong\", {\n  id: Schema.Number\n}) {}\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport const ProtocolRequest = Schema.Union(\n  WriteEntries,\n  RequestChanges,\n  StopChanges,\n  ChunkedMessage,\n  Ping\n)\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport const ProtocolRequestMsgPack = MsgPack.schema(ProtocolRequest)\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport const decodeRequest = Schema.decodeSync(ProtocolRequestMsgPack)\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport const encodeRequest = Schema.encodeSync(ProtocolRequestMsgPack)\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport const ProtocolResponse = Schema.Union(\n  Hello,\n  Ack,\n  Changes,\n  ChunkedMessage,\n  Pong\n)\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport const ProtocolResponseMsgPack = MsgPack.schema(ProtocolResponse)\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport const decodeResponse = Schema.decodeSync(ProtocolResponseMsgPack)\n\n/**\n * @since 1.0.0\n * @category protocol\n */\nexport const encodeResponse = Schema.encodeSync(ProtocolResponseMsgPack)\n\n/**\n * @since 1.0.0\n * @category change\n */\nexport class RemoteAdditions\n  extends Schema.TaggedClass<RemoteAdditions>(\"@effect/experimental/EventLogRemote/RemoveAdditions\")(\n    \"RemoveAdditions\",\n    { entries: Schema.Array(RemoteEntry) }\n  )\n{}\n\nconst constChunkSize = 512_000\n\n/**\n * @since 1.0.0\n * @category construtors\n */\nexport const fromSocket = (options?: {\n  readonly disablePing?: boolean\n}): Effect.Effect<\n  void,\n  never,\n  Scope.Scope | EventLog | EventLogEncryption | Socket.Socket\n> =>\n  Effect.gen(function*() {\n    const log = yield* EventLog\n    const socket = yield* Socket.Socket\n    const encryption = yield* EventLogEncryption\n    const scope = yield* Effect.scope\n    const writeRaw = yield* socket.writer\n\n    function* writeGen(request: typeof ProtocolRequest.Type) {\n      const data = encodeRequest(request)\n      if (request._tag !== \"WriteEntries\" || data.byteLength <= constChunkSize) {\n        return yield* writeRaw(data)\n      }\n      const id = request.id\n      for (const part of ChunkedMessage.split(id, data)) {\n        yield* writeRaw(encodeRequest(part))\n      }\n    }\n\n    const write = (request: typeof ProtocolRequest.Type) => Effect.gen(() => writeGen(request))\n\n    yield* Effect.gen(function*() {\n      let pendingCounter = 0\n      const pending = new Map<number, {\n        readonly entries: ReadonlyArray<Entry>\n        readonly deferred: Deferred.Deferred<void>\n        readonly publicKey: string\n      }>()\n      const chunks = new Map<number, {\n        readonly parts: Array<Uint8Array>\n        count: number\n        bytes: number\n      }>()\n\n      const subscriptions = yield* RcMap.make({\n        lookup: (publicKey: string) =>\n          Effect.acquireRelease(\n            Mailbox.make<RemoteEntry>(),\n            (mailbox) =>\n              Effect.zipRight(\n                mailbox.shutdown,\n                Effect.ignoreLogged(write(new StopChanges({ publicKey })))\n              )\n          )\n      })\n      const identities = new WeakMap<any, typeof Identity.Service>()\n      const badPing = yield* Deferred.make<never, Error>()\n\n      let latestPing = 0\n      let latestPong = 0\n\n      if (options?.disablePing !== true) {\n        yield* Effect.suspend(() => {\n          if (latestPing !== latestPong) {\n            return Deferred.fail(badPing, new Error(\"Ping timeout\"))\n          }\n          return write(new Ping({ id: ++latestPing }))\n        }).pipe(\n          Effect.delay(10000),\n          Effect.forever,\n          Effect.fork,\n          Effect.interruptible\n        )\n      }\n\n      function handleMessage(res: typeof ProtocolResponse.Type) {\n        switch (res._tag) {\n          case \"Hello\": {\n            return log.registerRemote({\n              id: res.remoteId,\n              write: (identity, entries) =>\n                Effect.gen(function*() {\n                  const encrypted = yield* encryption.encrypt(identity, entries)\n                  const deferred = yield* Deferred.make<void>()\n                  const id = pendingCounter++\n                  pending.set(id, {\n                    entries,\n                    deferred,\n                    publicKey: identity.publicKey\n                  })\n                  yield* Effect.orDie(write(\n                    new WriteEntries({\n                      publicKey: identity.publicKey,\n                      id,\n                      iv: encrypted.iv,\n                      encryptedEntries: encrypted.encryptedEntries.map((encryptedEntry, i) => ({\n                        entryId: entries[i].id,\n                        encryptedEntry\n                      }))\n                    })\n                  ))\n                  yield* Deferred.await(deferred)\n                }),\n              changes: (identity, startSequence) =>\n                Effect.gen(function*() {\n                  const mailbox = yield* RcMap.get(subscriptions, identity.publicKey)\n                  identities.set(mailbox, identity)\n                  yield* Effect.orDie(write(\n                    new RequestChanges({\n                      publicKey: identity.publicKey,\n                      startSequence\n                    })\n                  ))\n                  return mailbox\n                })\n            }).pipe(Scope.extend(scope))\n          }\n          case \"Ack\": {\n            return Effect.gen(function*() {\n              const entry = pending.get(res.id)\n              if (!entry) return\n              pending.delete(res.id)\n              const { deferred, entries, publicKey } = entry\n              const remoteEntries = res.sequenceNumbers.map((sequenceNumber, i) => {\n                const entry = entries[i]\n                return new RemoteEntry({\n                  remoteSequence: sequenceNumber,\n                  entry\n                })\n              })\n              const mailbox = yield* RcMap.get(subscriptions, publicKey)\n              yield* mailbox.offerAll(remoteEntries)\n              yield* Deferred.done(deferred, Exit.void)\n            })\n          }\n          case \"Pong\": {\n            latestPong = res.id\n            if (res.id === latestPing) {\n              return\n            }\n            return Effect.fail(new Error(\"Pong id mismatch\"))\n          }\n          case \"Changes\": {\n            return Effect.gen(function*() {\n              const mailbox = yield* RcMap.get(subscriptions, res.publicKey)\n              const identity = identities.get(mailbox)!\n              const entries = yield* encryption.decrypt(identity, res.entries)\n              yield* mailbox.offerAll(entries)\n            }).pipe(Effect.scoped)\n          }\n          case \"ChunkedMessage\": {\n            const data = ChunkedMessage.join(chunks, res)\n            if (!data) return\n            return handleMessage(decodeResponse(data))\n          }\n        }\n      }\n\n      return yield* socket.run((data) => handleMessage(decodeResponse(data))).pipe(\n        Effect.raceFirst(Deferred.await(badPing))\n      )\n    }).pipe(\n      Effect.scoped,\n      Effect.tapErrorCause(Effect.logDebug),\n      Effect.retry({\n        schedule: Schedule.exponential(100).pipe(\n          Schedule.union(Schedule.spaced(5000))\n        )\n      }),\n      Effect.annotateLogs({\n        service: \"EventLogRemote\",\n        method: \"fromSocket\"\n      }),\n      Effect.forkScoped,\n      Effect.interruptible\n    )\n  })\n\n/**\n * @since 1.0.0\n * @category construtors\n */\nexport const fromWebSocket = (\n  url: string,\n  options?: {\n    readonly disablePing?: boolean\n  }\n): Effect.Effect<void, never, Scope.Scope | EventLogEncryption | EventLog | Socket.WebSocketConstructor> =>\n  Effect.gen(function*() {\n    const socket = yield* Socket.makeWebSocket(url)\n    return yield* fromSocket(options).pipe(\n      Effect.provideService(Socket.Socket, socket)\n    )\n  })\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerWebSocket = (\n  url: string,\n  options?: {\n    readonly disablePing?: boolean\n  }\n): Layer.Layer<\n  never,\n  never,\n  | Socket.WebSocketConstructor\n  | EventLog\n  | EventLogEncryption\n> => Layer.scopedDiscard(fromWebSocket(url, options))\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerWebSocketBrowser = (\n  url: string,\n  options?: {\n    readonly disablePing?: boolean\n  }\n): Layer.Layer<never, never, EventLog> =>\n  layerWebSocket(url, options).pipe(\n    Layer.provide([layerSubtle, Socket.layerWebSocketConstructorGlobal])\n  )\n"
  },
  {
    "path": "packages/experimental/src/EventLogServer/Cloudflare.ts",
    "content": "/**\n * @since 1.0.0\n */\n/// <reference types=\"@cloudflare/workers-types\" />\nimport { DurableObject } from \"cloudflare:workers\"\nimport * as Cause from \"effect/Cause\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Layer from \"effect/Layer\"\nimport * as ManagedRuntime from \"effect/ManagedRuntime\"\nimport { RemoteId } from \"../EventJournal.js\"\nimport type { EncryptedRemoteEntry } from \"../EventLogEncryption.js\"\nimport * as EventLogRemote from \"../EventLogRemote.js\"\nimport * as EventLogServer from \"../EventLogServer.js\"\n\n/**\n * @since 1.0.0\n * @category DurableObject\n */\nexport abstract class EventLogDurableObject extends DurableObject {\n  /**\n   * @since 1.0.0\n   */\n  readonly runtime: ManagedRuntime.ManagedRuntime<EventLogServer.Storage, never>\n\n  constructor(options: {\n    readonly ctx: DurableObjectState\n    readonly env: unknown\n    readonly storageLayer: Layer.Layer<EventLogServer.Storage>\n  }) {\n    super(options.ctx, options.env)\n    this.ctx.setHibernatableWebSocketEventTimeout(5000)\n    this.runtime = ManagedRuntime.make(options.storageLayer)\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {\n    return this.handleRequest(\n      ws,\n      EventLogRemote.decodeRequest(\n        message instanceof ArrayBuffer\n          ? new Uint8Array(message)\n          : new TextEncoder().encode(message)\n      )\n    )\n  }\n\n  private chunks = new Map<\n    number,\n    {\n      readonly parts: Array<Uint8Array>\n      count: number\n      bytes: number\n    }\n  >()\n  /**\n   * @since 1.0.0\n   */\n  private async handleRequest(\n    ws: WebSocket,\n    request: typeof EventLogRemote.ProtocolRequest.Type\n  ): Promise<void> {\n    switch (request._tag) {\n      case \"WriteEntries\": {\n        return Effect.gen(this, function*() {\n          const storage = yield* EventLogServer.Storage\n          const entries = request.encryptedEntries.map(\n            ({ encryptedEntry, entryId }) =>\n              new EventLogServer.PersistedEntry({\n                entryId,\n                iv: request.iv,\n                encryptedEntry\n              })\n          )\n          const encryptedEntries = yield* storage.write(\n            request.publicKey,\n            entries\n          )\n          ws.send(\n            EventLogRemote.encodeResponse(\n              new EventLogRemote.Ack({\n                id: request.id,\n                sequenceNumbers: encryptedEntries.map((_) => _.sequence)\n              })\n            )\n          )\n          const changes = this.encodeChanges(\n            request.publicKey,\n            encryptedEntries\n          )\n          for (const peer of this.ctx.getWebSockets()) {\n            if (peer === ws) continue\n            for (const change of changes) {\n              peer.send(change)\n            }\n          }\n        }).pipe(this.runtime.runPromise)\n      }\n      case \"ChunkedMessage\": {\n        const data = EventLogRemote.ChunkedMessage.join(this.chunks, request)\n        if (!data) return\n        return this.handleRequest(ws, EventLogRemote.decodeRequest(data))\n      }\n      case \"RequestChanges\": {\n        return Effect.gen(this, function*() {\n          const storage = yield* EventLogServer.Storage\n          const entries = yield* storage.entries(\n            request.publicKey,\n            request.startSequence\n          )\n          if (entries.length === 0) return\n          const changes = this.encodeChanges(request.publicKey, entries)\n          for (const change of changes) {\n            ws.send(change)\n          }\n        }).pipe(this.runtime.runPromise)\n      }\n    }\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  private encodeChanges(\n    publicKey: string,\n    entries: ReadonlyArray<EncryptedRemoteEntry>\n  ): ReadonlyArray<Uint8Array> {\n    let changes = [\n      EventLogRemote.encodeResponse(\n        new EventLogRemote.Changes({\n          publicKey,\n          entries\n        })\n      )\n    ]\n    if (changes[0].byteLength > 512_000) {\n      changes = EventLogRemote.ChunkedMessage.split(\n        Math.floor(Math.random() * 1_000_000_000),\n        changes[0]\n      ).map((_) => EventLogRemote.encodeResponse(_))\n    }\n    return changes\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  webSocketError(_ws: WebSocket, error: Error): void {\n    this.runtime.runFork(Effect.logWarning(Cause.fail(error)))\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  webSocketClose(_ws: WebSocket, code: number, reason: string): void {\n    this.runtime.runFork(Effect.logWarning(\"WebSocket closed\", { code, reason }))\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  async fetch(): Promise<Response> {\n    const webSocketPair = new WebSocketPair()\n    const [client, server] = Object.values(webSocketPair)\n\n    this.ctx.acceptWebSocket(server)\n\n    EventLogServer.Storage.pipe(\n      Effect.flatMap((_) => _.getId),\n      Effect.tap((remoteId) => {\n        server.send(\n          EventLogRemote.encodeResponse(\n            new EventLogRemote.Hello({\n              remoteId: RemoteId.make(remoteId)\n            })\n          )\n        )\n      }),\n      this.runtime.runFork\n    )\n\n    return new Response(null, {\n      status: 101,\n      webSocket: client\n    })\n  }\n}\n"
  },
  {
    "path": "packages/experimental/src/EventLogServer.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as HttpServerError from \"@effect/platform/HttpServerError\"\nimport * as HttpServerRequest from \"@effect/platform/HttpServerRequest\"\nimport * as HttpServerResponse from \"@effect/platform/HttpServerResponse\"\nimport * as MsgPack from \"@effect/platform/MsgPack\"\nimport type * as Socket from \"@effect/platform/Socket\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberMap from \"effect/FiberMap\"\nimport * as Layer from \"effect/Layer\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as PubSub from \"effect/PubSub\"\nimport * as RcMap from \"effect/RcMap\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Uuid from \"uuid\"\nimport type { RemoteId } from \"./EventJournal.js\"\nimport { EntryId, makeRemoteId } from \"./EventJournal.js\"\nimport { EncryptedRemoteEntry } from \"./EventLogEncryption.js\"\nimport type { ProtocolRequest, ProtocolResponse } from \"./EventLogRemote.js\"\nimport { Ack, Changes, ChunkedMessage, decodeRequest, encodeResponse, Hello, Pong } from \"./EventLogRemote.js\"\n\nconst constChunkSize = 512_000\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeHandler: Effect.Effect<\n  (socket: Socket.Socket) => Effect.Effect<void, Socket.SocketError, Scope.Scope>,\n  never,\n  Storage\n> = Effect.gen(function*() {\n  const storage = yield* Storage\n  const remoteId = yield* storage.getId\n  let chunkId = 0\n\n  function* handler(socket: Socket.Socket) {\n    const subscriptions = yield* FiberMap.make<string>()\n    const writeRaw = yield* socket.writer\n    const chunks = new Map<number, {\n      readonly parts: Array<Uint8Array>\n      count: number\n      bytes: number\n    }>()\n    let latestSequence = -1\n\n    function* writeGen(response: typeof ProtocolResponse.Type) {\n      const data = encodeResponse(response)\n      if (response._tag !== \"Changes\" || data.byteLength <= constChunkSize) {\n        return yield* writeRaw(data)\n      }\n      const id = chunkId++\n      for (const part of ChunkedMessage.split(id, data)) {\n        yield* writeRaw(encodeResponse(part))\n      }\n    }\n    const write = (response: typeof ProtocolResponse.Type) => Effect.gen(() => writeGen(response))\n\n    yield* Effect.fork(write(new Hello({ remoteId })))\n\n    function handleRequest(request: typeof ProtocolRequest.Type) {\n      switch (request._tag) {\n        case \"Ping\": {\n          return write(new Pong({ id: request.id }))\n        }\n        case \"WriteEntries\": {\n          if (request.encryptedEntries.length === 0) {\n            return write(\n              new Ack({\n                id: request.id,\n                sequenceNumbers: []\n              })\n            )\n          }\n          return Effect.gen(function*() {\n            const entries = request.encryptedEntries.map(({ encryptedEntry, entryId }) =>\n              new PersistedEntry({\n                entryId,\n                iv: request.iv,\n                encryptedEntry\n              })\n            )\n            const encrypted = yield* storage.write(request.publicKey, entries)\n            latestSequence = encrypted[encrypted.length - 1].sequence\n            return yield* write(\n              new Ack({\n                id: request.id,\n                sequenceNumbers: encrypted.map((e) => e.sequence)\n              })\n            )\n          })\n        }\n        case \"RequestChanges\": {\n          return Effect.gen(function*() {\n            const changes = yield* storage.changes(request.publicKey, request.startSequence)\n            return yield* changes.takeAll.pipe(\n              Effect.flatMap(function([entries]) {\n                const latestEntries: Array<EncryptedRemoteEntry> = []\n                for (const entry of entries) {\n                  if (entry.sequence <= latestSequence) continue\n                  latestEntries.push(entry)\n                  latestSequence = entry.sequence\n                }\n                if (latestEntries.length === 0) return Effect.void\n                return write(\n                  new Changes({\n                    publicKey: request.publicKey,\n                    entries: Chunk.toReadonlyArray(entries)\n                  })\n                )\n              }),\n              Effect.forever\n            )\n          }).pipe(\n            Effect.scoped,\n            FiberMap.run(subscriptions, request.publicKey)\n          )\n        }\n        case \"StopChanges\": {\n          return FiberMap.remove(subscriptions, request.publicKey)\n        }\n        case \"ChunkedMessage\": {\n          const data = ChunkedMessage.join(chunks, request)\n          if (!data) return\n          return handleRequest(decodeRequest(data))\n        }\n      }\n    }\n\n    yield* socket.run((data) => handleRequest(decodeRequest(data))).pipe(Effect.catchAllCause(Effect.logDebug))\n  }\n\n  return (socket) =>\n    Effect.gen(() => handler(socket)).pipe(Effect.annotateLogs({\n      module: \"EventLogServer\"\n    }))\n})\n\n/**\n * @since 1.0.0\n * @category websockets\n */\nexport const makeHandlerHttp: Effect.Effect<\n  Effect.Effect<\n    HttpServerResponse.HttpServerResponse,\n    HttpServerError.RequestError | Socket.SocketError,\n    HttpServerRequest.HttpServerRequest | Scope.Scope\n  >,\n  never,\n  Storage\n> = Effect.gen(function*() {\n  const handler = yield* makeHandler\n\n  return Effect.gen(function*() {\n    const request = yield* HttpServerRequest.HttpServerRequest\n    const socket = yield* request.upgrade\n    yield* handler(socket)\n    return HttpServerResponse.empty()\n  }).pipe(Effect.annotateLogs({\n    module: \"EventLogServer\"\n  }))\n})\n\n/**\n * @since 1.0.0\n * @category storage\n */\nexport class PersistedEntry extends Schema.Class<PersistedEntry>(\"@effect/experimental/EventLogServer/PersistedEntry\")({\n  entryId: EntryId,\n  iv: Schema.Uint8ArrayFromSelf,\n  encryptedEntry: Schema.Uint8ArrayFromSelf\n}) {\n  /**\n   * @since 1.0.0\n   */\n  static fromMsgPack = MsgPack.schema(PersistedEntry)\n\n  /**\n   * @since 1.0.0\n   */\n  static encode = Schema.encodeSync(this.fromMsgPack)\n\n  /**\n   * @since 1.0.0\n   */\n  get entryIdString(): string {\n    return Uuid.stringify(this.entryId)\n  }\n}\n\n/**\n * @since 1.0.0\n * @category storage\n */\nexport class Storage extends Context.Tag(\"@effect/experimental/EventLogServer/Storage\")<\n  Storage,\n  {\n    readonly getId: Effect.Effect<RemoteId>\n    readonly write: (\n      publicKey: string,\n      entries: ReadonlyArray<PersistedEntry>\n    ) => Effect.Effect<ReadonlyArray<EncryptedRemoteEntry>>\n    readonly entries: (\n      publicKey: string,\n      startSequence: number\n    ) => Effect.Effect<ReadonlyArray<EncryptedRemoteEntry>>\n    readonly changes: (\n      publicKey: string,\n      startSequence: number\n    ) => Effect.Effect<Mailbox.ReadonlyMailbox<EncryptedRemoteEntry>, never, Scope.Scope>\n  }\n>() {}\n\n/**\n * @since 1.0.0\n * @category storage\n */\nexport const makeStorageMemory: Effect.Effect<typeof Storage.Service, never, Scope.Scope> = Effect.gen(function*() {\n  const knownIds = new Map<string, number>()\n  const journals = new Map<string, Array<EncryptedRemoteEntry>>()\n  const remoteId = makeRemoteId()\n  const ensureJournal = (publicKey: string) => {\n    let journal = journals.get(publicKey)\n    if (journal) return journal\n    journal = []\n    journals.set(publicKey, journal)\n    return journal\n  }\n  const pubsubs = yield* RcMap.make({\n    lookup: (_publicKey: string) =>\n      Effect.acquireRelease(\n        PubSub.unbounded<EncryptedRemoteEntry>(),\n        PubSub.shutdown\n      ),\n    idleTimeToLive: 60000\n  })\n\n  return Storage.of({\n    getId: Effect.succeed(remoteId),\n    write: (publicKey, entries) =>\n      Effect.gen(function*() {\n        const active = yield* RcMap.keys(pubsubs)\n        const pubsub = active.includes(publicKey) ? yield* RcMap.get(pubsubs, publicKey) : undefined\n        const journal = ensureJournal(publicKey)\n        const encryptedEntries: Array<EncryptedRemoteEntry> = []\n        for (const entry of entries) {\n          const idString = entry.entryIdString\n          if (knownIds.has(idString)) continue\n          const encrypted = EncryptedRemoteEntry.make({\n            sequence: journal.length,\n            entryId: entry.entryId,\n            iv: entry.iv,\n            encryptedEntry: entry.encryptedEntry\n          })\n          encryptedEntries.push(encrypted)\n          knownIds.set(idString, encrypted.sequence)\n          journal.push(encrypted)\n          pubsub?.unsafeOffer(encrypted)\n        }\n        return encryptedEntries\n      }).pipe(Effect.scoped),\n    entries: (publicKey, startSequence) => Effect.sync(() => ensureJournal(publicKey).slice(startSequence)),\n    changes: (publicKey, startSequence) =>\n      Effect.gen(function*() {\n        const mailbox = yield* Mailbox.make<EncryptedRemoteEntry>()\n        const pubsub = yield* RcMap.get(pubsubs, publicKey)\n        const queue = yield* pubsub.subscribe\n        yield* mailbox.offerAll(ensureJournal(publicKey).slice(startSequence))\n        yield* queue.takeBetween(1, Number.MAX_SAFE_INTEGER).pipe(\n          Effect.tap((chunk) => mailbox.offerAll(chunk)),\n          Effect.forever,\n          Effect.forkScoped,\n          Effect.interruptible\n        )\n        return mailbox\n      })\n  })\n})\n\n/**\n * @since 1.0.0\n * @category storage\n */\nexport const layerStorageMemory: Layer.Layer<Storage> = Layer.scoped(Storage, makeStorageMemory)\n"
  },
  {
    "path": "packages/experimental/src/Machine/Procedure.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Deferred from \"effect/Deferred\"\nimport type * as Effect from \"effect/Effect\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport type { Request } from \"effect/Request\"\nimport type * as Schema from \"effect/Schema\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/experimental/Machine/Procedure\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface TaggedRequest<Tag extends string, A, E> extends Request<A, E> {\n  readonly _tag: Tag\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace TaggedRequest {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Any =\n    | TaggedRequest<string, any, any>\n    | TaggedRequest<string, any, never>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Procedure<Request extends TaggedRequest.Any, State, R> extends Pipeable {\n  readonly [TypeId]: TypeId\n  readonly tag: Request[\"_tag\"]\n  readonly handler: Handler<Request, State, any, R>\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const SerializableTypeId: unique symbol = Symbol.for(\"@effect/experimental/Machine/SerializableProcedure\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type SerializableTypeId = typeof SerializableTypeId\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isSerializable = (u: unknown): u is SerializableProcedure<any, any, any> =>\n  Predicate.hasProperty(u, SerializableTypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface SerializableProcedure<Request extends Schema.TaggedRequest.All, State, R>\n  extends Procedure<Request, State, R>\n{\n  readonly [SerializableTypeId]: SerializableTypeId\n  readonly schema: Schema.Schema<Request, unknown>\n}\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport const NoReply = Symbol.for(\"@effect/experimental/Machine/Procedure/NoReply\")\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport type NoReply = typeof NoReply\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Handler<\n  Request extends TaggedRequest.Any,\n  State,\n  Requests extends TaggedRequest.Any,\n  R\n> = (\n  context: Procedure.Context<Requests | Request, Request, State>\n) => Effect.Effect<\n  readonly [response: Request.Success<Request> | NoReply, state: State],\n  Request.Error<Request>,\n  R\n>\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace Procedure {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface BaseContext {\n    readonly fork: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<void, never, R>\n    readonly forkOne: {\n      (id: string): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<void, never, R>\n      <A, E, R>(effect: Effect.Effect<A, E, R>, id: string): Effect.Effect<void, never, R>\n    }\n    readonly forkReplace: {\n      (id: string): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<void, never, R>\n      <A, E, R>(effect: Effect.Effect<A, E, R>, id: string): Effect.Effect<void, never, R>\n    }\n    readonly unsafeSend: <Req extends TaggedRequest.Any>(request: Req) => Effect.Effect<void>\n    readonly unsafeSendAwait: <Req extends TaggedRequest.Any>(request: Req) => Effect.Effect<\n      Request.Success<Req>,\n      Request.Error<Req>\n    >\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface ContextProto<Requests extends TaggedRequest.Any, State> extends BaseContext {\n    readonly send: <Req extends Requests>(request: Req) => Effect.Effect<void>\n    readonly sendAwait: <Req extends Requests>(request: Req) => Effect.Effect<\n      Request.Success<Req>,\n      Request.Error<Req>\n    >\n    readonly forkWith: {\n      (state: State): <A, E, R>(\n        effect: Effect.Effect<A, E, R>\n      ) => Effect.Effect<readonly [void, State], never, R>\n      <A, E, R>(\n        effect: Effect.Effect<A, E, R>,\n        state: State\n      ): Effect.Effect<readonly [void, State], never, R>\n    }\n    readonly forkOneWith: {\n      (\n        id: string,\n        state: State\n      ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<readonly [void, State], never, R>\n      <A, E, R>(\n        effect: Effect.Effect<A, E, R>,\n        id: string,\n        state: State\n      ): Effect.Effect<readonly [void, State], never, R>\n    }\n    readonly forkReplaceWith: {\n      (\n        id: string,\n        state: State\n      ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<readonly [void, State], never, R>\n      <A, E, R>(\n        effect: Effect.Effect<A, E, R>,\n        id: string,\n        state: State\n      ): Effect.Effect<readonly [void, State], never, R>\n    }\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Context<Requests extends TaggedRequest.Any, Request extends TaggedRequest.Any, State>\n    extends ContextProto<Requests, State>\n  {\n    readonly request: Request\n    readonly state: State\n    readonly deferred: Deferred.Deferred<\n      Request.Success<Request>,\n      Request.Error<Request>\n    >\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type InferRequest<P> = P extends Procedure<infer Req, infer _, infer _> ? Req : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type InferContext<P> = P extends Procedure<infer _, infer _, infer R> ? R : never\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <Requests extends TaggedRequest.Any, State>() =>\n<Req extends TaggedRequest.Any>() =>\n<R>(\n  tag: Req[\"_tag\"],\n  handler: Handler<Req, State, Requests, R>\n): Procedure<Req, State, R> => ({\n  [TypeId]: TypeId,\n  handler,\n  tag,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n})\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeSerializable = <\n  Requests extends TaggedRequest.Any,\n  State\n>() =>\n<\n  Req extends Schema.TaggedRequest.All,\n  IS,\n  R,\n  RS\n>(\n  schema: Schema.Schema<Req, IS, RS> & { readonly _tag: Req[\"_tag\"] },\n  handler: Handler<Req, State, Requests, R>\n): SerializableProcedure<Req, State, R | Schema.SerializableWithResult.Context<Req>> => ({\n  [TypeId]: TypeId,\n  [SerializableTypeId]: SerializableTypeId,\n  schema: schema as any,\n  handler,\n  tag: schema._tag,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n})\n"
  },
  {
    "path": "packages/experimental/src/Machine/ProcedureList.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Effect from \"effect/Effect\"\nimport * as Effectable from \"effect/Effectable\"\nimport { dual } from \"effect/Function\"\nimport type * as Types from \"effect/Types\"\nimport * as Procedure from \"./Procedure.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/experimental/Machine/ProcedureList\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface ProcedureList<\n  State,\n  Public extends Procedure.TaggedRequest.Any,\n  Private extends Procedure.TaggedRequest.Any,\n  R\n> extends Effect.Effect<ProcedureList<State, Public, Private, R>> {\n  readonly [TypeId]: TypeId\n  readonly initialState: State\n  readonly public: ReadonlyArray<Procedure.Procedure<Public, State, R>>\n  readonly private: ReadonlyArray<Procedure.Procedure<Private, State, R>>\n  readonly identifier: string\n}\n\nconst Proto = {\n  ...Effectable.CommitPrototype,\n  [TypeId]: TypeId,\n  commit() {\n    return Effect.succeed(this)\n  }\n}\n\nconst makeProto = <State, Public extends Procedure.TaggedRequest.Any, Private extends Procedure.TaggedRequest.Any, R>(\n  options: {\n    readonly initialState: State\n    readonly public: ReadonlyArray<Procedure.Procedure<Public, State, R>>\n    readonly private: ReadonlyArray<Procedure.Procedure<Private, State, R>>\n    readonly identifier: string\n  }\n): ProcedureList<State, Public, Private, R> => Object.assign(Object.create(Proto), options)\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <State>(initialState: State, options?: {\n  readonly identifier?: string\n}): ProcedureList<State, never, never, never> =>\n  makeProto({\n    initialState,\n    public: [],\n    private: [],\n    identifier: options?.identifier ?? \"Unknown\"\n  })\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const addProcedure: {\n  <\n    Req extends Procedure.TaggedRequest.Any,\n    State,\n    R2\n  >(\n    procedure: Procedure.Procedure<Req, State, R2>\n  ): <\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R\n  >(\n    self: ProcedureList<State, Public, Private, R>\n  ) => ProcedureList<State, Req | Public, Private, R | R2>\n  <\n    State,\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R,\n    Req extends Procedure.TaggedRequest.Any,\n    R2\n  >(\n    self: ProcedureList<State, Public, Private, R>,\n    procedure: Procedure.Procedure<Req, State, R2>\n  ): ProcedureList<State, Req | Public, Private, R | R2>\n} = dual(\n  2,\n  <\n    State,\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R,\n    Req extends Procedure.TaggedRequest.Any,\n    R2\n  >(\n    self: ProcedureList<State, Public, Private, R>,\n    procedure: Procedure.Procedure<Req, State, R2>\n  ): ProcedureList<State, Req | Public, Private, R | R2> =>\n    makeProto({\n      ...self,\n      public: [...self.public, procedure] as any\n    })\n)\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const addProcedurePrivate: {\n  <\n    Req extends Procedure.TaggedRequest.Any,\n    State,\n    R2\n  >(\n    procedure: Procedure.Procedure<Req, State, R2>\n  ): <\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R\n  >(\n    self: ProcedureList<State, Public, Private, R>\n  ) => ProcedureList<State, Public, Private | Req, R | R2>\n  <\n    State,\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R,\n    Req extends Procedure.TaggedRequest.Any,\n    R2\n  >(\n    self: ProcedureList<State, Public, Private, R>,\n    procedure: Procedure.Procedure<Req, State, R2>\n  ): ProcedureList<State, Public, Private | Req, R | R2>\n} = dual(\n  2,\n  <\n    State,\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R,\n    Req extends Procedure.TaggedRequest.Any,\n    R2\n  >(\n    self: ProcedureList<State, Public, Private, R>,\n    procedure: Procedure.Procedure<Req, State, R2>\n  ): ProcedureList<State, Public, Private | Req, R | R2> =>\n    makeProto({\n      ...self,\n      private: [...self.private, procedure] as any\n    })\n)\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const add = <Req extends Procedure.TaggedRequest.Any>(): {\n  <\n    State,\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R2\n  >(\n    tag: Req[\"_tag\"],\n    handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n  ): <R>(\n    self: ProcedureList<State, Public, Private, R>\n  ) => ProcedureList<State, Req | Public, Private, R | R2>\n  <\n    State,\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R,\n    R2\n  >(\n    self: ProcedureList<State, Public, Private, R>,\n    tag: Req[\"_tag\"],\n    handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n  ): ProcedureList<State, Req | Public, Private, R | R2>\n} =>\n  dual(\n    3,\n    <\n      State,\n      Public extends Procedure.TaggedRequest.Any,\n      Private extends Procedure.TaggedRequest.Any,\n      R,\n      R2\n    >(\n      self: ProcedureList<State, Public, Private, R>,\n      tag: Req[\"_tag\"],\n      handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n    ): ProcedureList<State, Req | Public, Private, R | R2> =>\n      addProcedure(self, Procedure.make<any, any>()<Req>()(tag, handler))\n  )\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const addPrivate = <Req extends Procedure.TaggedRequest.Any>(): {\n  <\n    State,\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R2\n  >(\n    tag: Req[\"_tag\"],\n    handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n  ): <R>(\n    self: ProcedureList<State, Public, Private, R>\n  ) => ProcedureList<State, Public, Private | Req, R | R2>\n  <\n    State,\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R,\n    R2\n  >(\n    self: ProcedureList<State, Public, Private, R>,\n    tag: Req[\"_tag\"],\n    handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n  ): ProcedureList<State, Public, Private | Req, R | R2>\n} =>\n  dual(\n    3,\n    <\n      State,\n      Public extends Procedure.TaggedRequest.Any,\n      Private extends Procedure.TaggedRequest.Any,\n      R,\n      R2\n    >(\n      self: ProcedureList<State, Public, Private, R>,\n      tag: Req[\"_tag\"],\n      handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n    ): ProcedureList<State, Public, Private | Req, R | R2> =>\n      addProcedurePrivate(self, Procedure.make<any, any>()<Req>()(tag, handler))\n  )\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withInitialState: {\n  <State>(\n    initialState: Types.NoInfer<State>\n  ): <Public extends Procedure.TaggedRequest.Any, Private extends Procedure.TaggedRequest.Any, R>(\n    self: ProcedureList<State, Public, Private, R>\n  ) => ProcedureList<State, Public, Private, R>\n  <State, Public extends Procedure.TaggedRequest.Any, Private extends Procedure.TaggedRequest.Any, R>(\n    self: ProcedureList<State, Public, Private, R>,\n    initialState: Types.NoInfer<State>\n  ): ProcedureList<State, Public, Private, R>\n} = dual(2, <State, Public extends Procedure.TaggedRequest.Any, Private extends Procedure.TaggedRequest.Any, R>(\n  self: ProcedureList<State, Public, Private, R>,\n  initialState: Types.NoInfer<State>\n): ProcedureList<State, Public, Private, R> => makeProto({ ...self, initialState }))\n"
  },
  {
    "path": "packages/experimental/src/Machine/SerializableProcedureList.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Effect from \"effect/Effect\"\nimport { dual } from \"effect/Function\"\nimport type * as Schema from \"effect/Schema\"\nimport type * as Types from \"effect/Types\"\nimport * as Procedure from \"./Procedure.js\"\nimport * as ProcedureList from \"./ProcedureList.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface SerializableProcedureList<\n  State,\n  Public extends Schema.TaggedRequest.All,\n  Private extends Schema.TaggedRequest.All,\n  R\n> extends Effect.Effect<SerializableProcedureList<State, Public, Private, R>> {\n  readonly [ProcedureList.TypeId]: ProcedureList.TypeId\n  readonly initialState: State\n  readonly public: ReadonlyArray<Procedure.SerializableProcedure<Public, State, R>>\n  readonly private: ReadonlyArray<Procedure.SerializableProcedure<Private, State, R>>\n  readonly identifier: string\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: <State>(\n  initialState: State,\n  options?: {\n    readonly identifier?: string\n  }\n) => SerializableProcedureList<State, never, never, never> = ProcedureList.make as any\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const add: {\n  <\n    Req extends Schema.TaggedRequest.All,\n    I,\n    ReqR,\n    State,\n    Public extends Schema.TaggedRequest.All,\n    Private extends Schema.TaggedRequest.All,\n    R2\n  >(\n    schema: Schema.Schema<Req, I, ReqR> & { readonly _tag: Req[\"_tag\"] },\n    handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n  ): <R>(\n    self: SerializableProcedureList<State, Public, Private, R>\n  ) => SerializableProcedureList<\n    State,\n    Req | Public,\n    Private,\n    R | R2 | Schema.SerializableWithResult.Context<Req>\n  >\n  <\n    State,\n    Public extends Schema.TaggedRequest.All,\n    Private extends Schema.TaggedRequest.All,\n    R,\n    Req extends Schema.TaggedRequest.All,\n    I,\n    ReqR,\n    R2\n  >(\n    self: SerializableProcedureList<State, Public, Private, R>,\n    schema: Schema.Schema<Req, I, ReqR> & { readonly _tag: Req[\"_tag\"] },\n    handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n  ): SerializableProcedureList<State, Req | Public, Private, R | R2 | Schema.SerializableWithResult.Context<Req>>\n} = dual(\n  3,\n  <\n    State,\n    Public extends Schema.TaggedRequest.All,\n    Private extends Schema.TaggedRequest.All,\n    R,\n    Req extends Schema.TaggedRequest.All,\n    I,\n    ReqR,\n    R2\n  >(\n    self: SerializableProcedureList<State, Public, Private, R>,\n    schema: Schema.Schema<Req, I, ReqR> & { readonly _tag: Req[\"_tag\"] },\n    handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n  ): SerializableProcedureList<\n    State,\n    Req | Public,\n    Private,\n    R | R2 | Schema.SerializableWithResult.Context<Req>\n  > => ProcedureList.addProcedure(self, Procedure.makeSerializable<any, any>()(schema, handler)) as any\n)\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const addPrivate: {\n  <\n    Req extends Schema.TaggedRequest.All,\n    I,\n    ReqR,\n    State,\n    Public extends Schema.TaggedRequest.All,\n    Private extends Schema.TaggedRequest.All,\n    R2\n  >(\n    schema: Schema.Schema<Req, I, ReqR> & { readonly _tag: Req[\"_tag\"] },\n    handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n  ): <R>(\n    self: SerializableProcedureList<State, Public, Private, R>\n  ) => SerializableProcedureList<\n    State,\n    Public,\n    Private | Req,\n    R | R2 | Schema.SerializableWithResult.Context<Req>\n  >\n  <\n    State,\n    Public extends Schema.TaggedRequest.All,\n    Private extends Schema.TaggedRequest.All,\n    R,\n    Req extends Schema.TaggedRequest.All,\n    I,\n    ReqR,\n    R2\n  >(\n    self: SerializableProcedureList<State, Public, Private, R>,\n    schema: Schema.Schema<Req, I, ReqR> & { readonly _tag: Req[\"_tag\"] },\n    handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n  ): SerializableProcedureList<State, Public, Private | Req, R | R2 | Schema.SerializableWithResult.Context<Req>>\n} = dual(\n  3,\n  <\n    State,\n    Public extends Schema.TaggedRequest.All,\n    Private extends Schema.TaggedRequest.All,\n    R,\n    Req extends Schema.TaggedRequest.All,\n    I,\n    ReqR,\n    R2\n  >(\n    self: SerializableProcedureList<State, Public, Private, R>,\n    schema: Schema.Schema<Req, I, ReqR> & { readonly _tag: Req[\"_tag\"] },\n    handler: Procedure.Handler<Req, Types.NoInfer<State>, Types.NoInfer<Public> | Types.NoInfer<Private>, R2>\n  ): SerializableProcedureList<\n    State,\n    Public,\n    Private | Req,\n    R | R2 | Schema.SerializableWithResult.Context<Req>\n  > => ProcedureList.addProcedurePrivate(self, Procedure.makeSerializable<any, any>()(schema, handler)) as any\n)\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const withInitialState: {\n  <State>(\n    initialState: Types.NoInfer<State>\n  ): <Public extends Schema.TaggedRequest.All, Private extends Schema.TaggedRequest.All, R>(\n    self: SerializableProcedureList<State, Public, Private, R>\n  ) => SerializableProcedureList<State, Public, Private, R>\n  <State, Public extends Schema.TaggedRequest.All, Private extends Schema.TaggedRequest.All, R>(\n    self: SerializableProcedureList<State, Public, Private, R>,\n    initialState: Types.NoInfer<State>\n  ): SerializableProcedureList<State, Public, Private, R>\n} = ProcedureList.withInitialState as any\n"
  },
  {
    "path": "packages/experimental/src/Machine.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Arr from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberMap from \"effect/FiberMap\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport * as FiberRefs from \"effect/FiberRefs\"\nimport * as FiberSet from \"effect/FiberSet\"\nimport { dual, identity, pipe } from \"effect/Function\"\nimport { globalValue } from \"effect/GlobalValue\"\nimport * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport { pipeArguments } from \"effect/Pipeable\"\nimport * as PubSub from \"effect/PubSub\"\nimport * as Queue from \"effect/Queue\"\nimport * as Readable from \"effect/Readable\"\nimport type { Request } from \"effect/Request\"\nimport type * as Schedule from \"effect/Schedule\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport * as Subscribable from \"effect/Subscribable\"\nimport * as Tracer from \"effect/Tracer\"\nimport * as Procedure from \"./Machine/Procedure.js\"\nimport type { ProcedureList } from \"./Machine/ProcedureList.js\"\nimport type { SerializableProcedureList } from \"./Machine/SerializableProcedureList.js\"\n\n/**\n * @since 1.0.0\n * @category procedures\n */\nexport * as procedures from \"./Machine/ProcedureList.js\"\n\n/**\n * @since 1.0.0\n * @category procedures\n */\nexport * as serializable from \"./Machine/SerializableProcedureList.js\"\n\nexport {\n  /**\n   * @since 1.0.0\n   * @category symbols\n   */\n  NoReply\n} from \"./Machine/Procedure.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/experimental/Machine\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Machine<\n  State,\n  Public extends Procedure.TaggedRequest.Any,\n  Private extends Procedure.TaggedRequest.Any,\n  Input,\n  InitErr,\n  R\n> extends Pipeable {\n  readonly [TypeId]: TypeId\n  readonly initialize: Machine.Initialize<Input, State, Public, Private, R, InitErr, R>\n  readonly retryPolicy: Schedule.Schedule<unknown, InitErr | MachineDefect, R> | undefined\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const SerializableTypeId: unique symbol = Symbol.for(\"@effect/experimental/Machine/Serializable\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type SerializableTypeId = typeof SerializableTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface SerializableMachine<\n  State,\n  Public extends Schema.TaggedRequest.All,\n  Private extends Schema.TaggedRequest.All,\n  Input,\n  InitErr,\n  R,\n  SR\n> extends\n  Machine<\n    State,\n    Public,\n    Private,\n    Input,\n    InitErr,\n    R\n  >\n{\n  readonly [SerializableTypeId]: SerializableTypeId\n  readonly schemaInput: Schema.Schema<Input, unknown, SR>\n  readonly schemaState: Schema.Schema<State, unknown, SR>\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const ActorTypeId: unique symbol = Symbol.for(\"@effect/experimental/Machine/Actor\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type ActorTypeId = typeof ActorTypeId\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport class MachineDefect extends Schema.TaggedError<MachineDefect>()(\"MachineDefect\", {\n  cause: Schema.Defect\n}) {\n  /**\n   * @since 1.0.0\n   */\n  static wrap<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, MachineDefect, R> {\n    return Effect.catchAllCause(\n      Effect.orDie(effect),\n      (cause) => Effect.fail(new MachineDefect({ cause: Cause.squash(cause) }))\n    )\n  }\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport class MachineContext extends Context.Tag(\"@effect/experimental/Machine/Context\")<\n  MachineContext,\n  Procedure.Procedure.BaseContext\n>() {}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace Machine {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Any =\n    | Machine<any, any, any, any, any, any>\n    | Machine<any, any, any, any, never, any>\n    | Machine<any, never, any, any, never, any>\n    | Machine<any, any, never, any, never, any>\n    | Machine<any, never, never, any, never, any>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Initialize<\n    Input,\n    State,\n    Public extends Procedure.TaggedRequest.Any,\n    Private extends Procedure.TaggedRequest.Any,\n    R,\n    E,\n    InitR\n  > = (\n    input: Input,\n    previousState?: State | undefined\n  ) => Effect.Effect<ProcedureList<State, Public, Private, R>, E, InitR>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type InitializeSerializable<\n    Input,\n    State,\n    Public extends Schema.TaggedRequest.All,\n    Private extends Schema.TaggedRequest.All,\n    R,\n    E,\n    InitR\n  > = (\n    input: Input,\n    previousState?: State | undefined\n  ) => Effect.Effect<SerializableProcedureList<State, Public, Private, R>, E, InitR>\n\n  /**\n   * @since 1.0.0\n   */\n  export type Public<M> = M extends Machine<infer _S, infer Public, infer _Pr, infer _I, infer _IE, infer _R> ? Public\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type Private<M> = M extends Machine<infer _S, infer _Pu, infer Private, infer _I, infer _IE, infer _R> ?\n    Private\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type State<M> = M extends Machine<infer State, infer _Pu, infer _Pr, infer _I, infer _IE, infer _R> ? State\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type InitError<M> = M extends Machine<infer _S, infer _Pu, infer _Pr, infer _I, infer InitErr, infer _R> ?\n    InitErr\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type Context<M> = M extends Machine<infer _S, infer _Pu, infer _Pr, infer _I, infer _IE, infer R> ? R\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type Input<M> = M extends Machine<infer _S, infer _Pu, infer _Pr, infer Input, infer _IE, infer _R> ? Input\n    : never\n\n  /**\n   * @since 1.0.0\n   */\n  export type AddContext<M, R, E = never> = M extends SerializableMachine<\n    infer State,\n    infer Public,\n    infer Private,\n    infer Input,\n    infer InitErr,\n    infer R2,\n    infer SR\n  > ? SerializableMachine<\n      State,\n      Public,\n      Private,\n      Input,\n      InitErr | E,\n      R | R2,\n      SR\n    > :\n    M extends Machine<infer State, infer Public, infer Private, infer Input, infer InitErr, infer R2> ? Machine<\n        State,\n        Public,\n        Private,\n        Input,\n        InitErr | E,\n        R | R2\n      > :\n    never\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Actor<M extends Machine.Any> extends Subscribable.Subscribable<Machine.State<M>> {\n  readonly [ActorTypeId]: ActorTypeId\n  readonly machine: M\n  readonly input: Machine.Input<M>\n  readonly send: <Req extends Machine.Public<M>>(request: Req) => Effect.Effect<\n    Request.Success<Req>,\n    Request.Error<Req>\n  >\n  readonly join: Effect.Effect<never, Machine.InitError<M> | MachineDefect>\n}\n\nconst ActorProto = {\n  [ActorTypeId]: ActorTypeId,\n  [Readable.TypeId]: Readable.TypeId,\n  [Subscribable.TypeId]: Subscribable.TypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface SerializableActor<M extends Machine.Any> extends Actor<M> {\n  readonly sendUnknown: (request: unknown) => Effect.Effect<\n    Schema.ExitEncoded<unknown, unknown, unknown>,\n    ParseResult.ParseError\n  >\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: {\n  <State, Public extends Procedure.TaggedRequest.Any, Private extends Procedure.TaggedRequest.Any, InitErr, R>(\n    initialize: Effect.Effect<ProcedureList<State, Public, Private, R>, InitErr, R>\n  ): Machine<State, Public, Private, void, InitErr, Exclude<R, Scope.Scope | MachineContext>>\n  <State, Public extends Procedure.TaggedRequest.Any, Private extends Procedure.TaggedRequest.Any, Input, InitErr, R>(\n    initialize: Machine.Initialize<Input, State, Public, Private, R, InitErr, R>\n  ): Machine<State, Public, Private, Input, InitErr, Exclude<R, Scope.Scope | MachineContext>>\n} = <State, Public extends Procedure.TaggedRequest.Any, Private extends Procedure.TaggedRequest.Any, Input, InitErr, R>(\n  initialize:\n    | Machine.Initialize<Input, State, Public, Private, R, InitErr, R>\n    | Effect.Effect<ProcedureList<State, Public, Private, R>, InitErr, R>\n): Machine<State, Public, Private, Input, InitErr, Exclude<R, Scope.Scope | MachineContext>> => ({\n  [TypeId]: TypeId,\n  initialize: Effect.isEffect(initialize) ? (() => initialize) : initialize as any,\n  retryPolicy: undefined,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n})\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeWith = <State, Input = void>(): {\n  <Public extends Procedure.TaggedRequest.Any, Private extends Procedure.TaggedRequest.Any, InitErr, R>(\n    initialize: Effect.Effect<ProcedureList<State, Public, Private, R>, InitErr, R>\n  ): Machine<State, Public, Private, void, InitErr, Exclude<R, Scope.Scope | MachineContext>>\n  <Public extends Procedure.TaggedRequest.Any, Private extends Procedure.TaggedRequest.Any, InitErr, R>(\n    initialize: Machine.Initialize<Input, State, Public, Private, R, InitErr, R>\n  ): Machine<State, Public, Private, Input, InitErr, Exclude<R, Scope.Scope | MachineContext>>\n} => make\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeSerializable: {\n  <\n    State,\n    IS,\n    RS,\n    Public extends Schema.TaggedRequest.All,\n    Private extends Schema.TaggedRequest.All,\n    InitErr,\n    R\n  >(\n    options: {\n      readonly state: Schema.Schema<State, IS, RS>\n      readonly input?: undefined\n    },\n    initialize:\n      | Effect.Effect<SerializableProcedureList<State, Public, Private, R>, InitErr, R>\n      | Machine.InitializeSerializable<void, State, Public, Private, R, InitErr, R>\n  ): SerializableMachine<State, Public, Private, void, InitErr, Exclude<R, Scope.Scope | MachineContext>, RS>\n  <\n    State,\n    IS,\n    RS,\n    Input,\n    II,\n    RI,\n    Public extends Schema.TaggedRequest.All,\n    Private extends Schema.TaggedRequest.All,\n    InitErr,\n    R\n  >(\n    options: {\n      readonly state: Schema.Schema<State, IS, RS>\n      readonly input: Schema.Schema<Input, II, RI>\n    },\n    initialize: Machine.InitializeSerializable<Input, State, Public, Private, R, InitErr, R>\n  ): SerializableMachine<State, Public, Private, Input, InitErr, Exclude<R, Scope.Scope | MachineContext>, RS | RI>\n} = <\n  State,\n  IS,\n  RS,\n  Input,\n  II,\n  RI,\n  Public extends Schema.TaggedRequest.All,\n  Private extends Schema.TaggedRequest.All,\n  InitErr,\n  R\n>(\n  options: {\n    readonly state: Schema.Schema<State, IS, RS>\n    readonly input?: Schema.Schema<Input, II, RI> | undefined\n  },\n  initialize:\n    | Machine.InitializeSerializable<Input, State, Public, Private, R, InitErr, R>\n    | Effect.Effect<SerializableProcedureList<State, Public, Private, R>, InitErr, R>\n): SerializableMachine<State, Public, Private, Input, InitErr, Exclude<R, Scope.Scope | MachineContext>, RS | RI> => (({\n  [TypeId]: TypeId,\n  [SerializableTypeId]: SerializableTypeId,\n  initialize: Effect.isEffect(initialize) ? (() => initialize) : initialize as any,\n  identifier: \"SerializableMachine\",\n  retryPolicy: undefined,\n  schemaInput: options.input as any,\n  schemaState: options.state as any,\n\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}) as any)\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const retry: {\n  <M extends Machine.Any, Out, In extends Machine.InitError<M> | MachineDefect, R>(\n    policy: Schedule.Schedule<Out, In, R>\n  ): (self: M) => Machine.AddContext<M, R>\n  <M extends Machine.Any, Out, In extends Machine.InitError<M> | MachineDefect, R>(\n    self: M,\n    policy: Schedule.Schedule<Out, In, R>\n  ): Machine.AddContext<M, R>\n} = dual(2, <M extends Machine.Any, Out, In extends Machine.InitError<M> | MachineDefect, R>(\n  self: M,\n  retryPolicy: Schedule.Schedule<Out, In, R>\n): Machine.AddContext<M, R> => (({\n  ...self,\n  retryPolicy\n}) as any))\n\n/**\n * @since 1.0.0\n * @category tracing\n */\nexport const currentTracingEnabled: FiberRef.FiberRef<boolean> = globalValue(\n  \"@effect/experimental/Machine/currentTracingEnabled\",\n  () => FiberRef.unsafeMake(true)\n)\n\n/**\n * @since 1.0.0\n * @category tracing\n */\nexport const withTracingEnabled: {\n  (enabled: boolean): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(effect: Effect.Effect<A, E, R>, enabled: boolean): Effect.Effect<A, E, R>\n} = dual(\n  2,\n  <A, E, R>(self: Effect.Effect<A, E, R>, enabled: boolean) => Effect.locally(self, currentTracingEnabled, enabled)\n)\n\n/**\n * @since 1.0.0\n * @category runtime\n */\nexport const boot = <\n  M extends Machine.Any\n>(\n  self: M,\n  ...[input, options]: [Machine.Input<M>] extends [void] ? [\n      input?: Machine.Input<M>,\n      options?: { readonly previousState?: Machine.State<M> }\n    ] :\n    [\n      input: Machine.Input<M>,\n      options?: { readonly previousState?: Machine.State<M> }\n    ]\n): Effect.Effect<\n  M extends { readonly [SerializableTypeId]: SerializableTypeId } ? SerializableActor<M> : Actor<M>,\n  never,\n  Machine.Context<M> | Scope.Scope\n> =>\n  Effect.gen(function*() {\n    const context = yield* Effect.context<Machine.Context<M>>()\n    const requests = yield* Queue.unbounded<\n      readonly [\n        Procedure.TaggedRequest.Any,\n        Deferred.Deferred<any, any>,\n        Tracer.AnySpan | undefined,\n        addSpans: boolean\n      ]\n    >()\n    const pubsub = yield* Effect.acquireRelease(\n      PubSub.unbounded<Machine.State<M>>(),\n      PubSub.shutdown\n    )\n    const latch = yield* Deferred.make<void>()\n\n    let currentState: Machine.State<M> = undefined as any\n    let runState: {\n      readonly identifier: string\n      readonly publicTags: Set<string>\n      readonly decodeRequest: (u: unknown) => Effect.Effect<Machine.Public<M>, ParseResult.ParseError>\n    } = {\n      identifier: \"Unknown\",\n      publicTags: new Set<string>(),\n      decodeRequest: undefined as any\n    }\n\n    const requestContext = <R extends Machine.Public<M>>(request: R) =>\n      Effect.sync(() => {\n        const fiber = Option.getOrThrow(Fiber.getCurrentFiber())\n        const fiberRefs = fiber.getFiberRefs()\n        const context = FiberRefs.getOrDefault(fiberRefs, FiberRef.currentContext)\n\n        const deferred = Deferred.unsafeMake<Request.Success<R>, Request.Error<R>>(fiber.id())\n        const span: Tracer.AnySpan | undefined = context.unsafeMap.get(Tracer.ParentSpan.key)\n        const addSpans = FiberRefs.getOrDefault(fiberRefs, currentTracingEnabled)\n\n        return [request, deferred, span, addSpans] as const\n      })\n\n    const send = <R extends Machine.Public<M>>(request: R) =>\n      Effect.flatMap(\n        requestContext(request),\n        (item) => {\n          if (!item[3]) {\n            return Queue.offer(requests, item).pipe(\n              Effect.zipRight(Deferred.await(item[1])),\n              Effect.onInterrupt(() => Deferred.interrupt(item[1]))\n            )\n          }\n          const [, deferred, span] = item\n          return Effect.useSpan(`Machine.send ${request._tag}`, {\n            parent: span,\n            attributes: {\n              \"effect.machine\": runState.identifier,\n              ...request\n            },\n            kind: \"client\",\n            captureStackTrace: false\n          }, (span) =>\n            Queue.offer(requests, [request, deferred, span, true]).pipe(\n              Effect.zipRight(Deferred.await(deferred)),\n              Effect.onInterrupt(() => Deferred.interrupt(deferred))\n            ))\n        }\n      )\n\n    const sendIgnore = <R extends Machine.Public<M>>(request: R) =>\n      Effect.flatMap(\n        requestContext(request),\n        (item) => {\n          if (!item[3]) {\n            return Queue.offer(requests, item)\n          }\n          const [, deferred, span] = item\n          return Effect.useSpan(`Machine.sendIgnore ${request._tag}`, {\n            parent: span,\n            attributes: {\n              \"effect.machine\": runState.identifier,\n              ...request\n            },\n            kind: \"client\",\n            captureStackTrace: false\n          }, (span) => Queue.offer(requests, [request, deferred, span, true]))\n        }\n      )\n\n    const sendExternal = <R extends Machine.Public<M>>(request: R) =>\n      Effect.suspend(() =>\n        runState.publicTags.has(request._tag)\n          ? send(request)\n          : Effect.die(`Request ${request._tag} marked as internal`)\n      )\n\n    const sendUnknown = (u: unknown) =>\n      Effect.suspend(() =>\n        runState.decodeRequest(u).pipe(\n          Effect.flatMap((req) =>\n            Effect.flatMap(\n              Effect.exit(send(req)),\n              (exit) => Schema.serializeExit(req, exit)\n            )\n          ),\n          Effect.provide(context)\n        )\n      ) as Effect.Effect<Schema.ExitEncoded<unknown, unknown, unknown>, ParseResult.ParseError>\n\n    const publishState = (newState: Machine.State<M>) => {\n      if (currentState !== newState) {\n        currentState = newState\n        return PubSub.publish(pubsub, newState)\n      }\n      return Effect.void\n    }\n\n    const run = Effect.gen(function*() {\n      const fiberSet = yield* FiberSet.make<any, MachineDefect>()\n      const fiberMap = yield* FiberMap.make<string, any, MachineDefect>()\n\n      const fork = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n        Effect.asVoid(FiberSet.run(fiberSet, MachineDefect.wrap(effect)))\n      const forkWith: {\n        (state: Machine.State<M>): <A, E, R>(\n          effect: Effect.Effect<A, E, R>\n        ) => Effect.Effect<readonly [void, Machine.State<M>], never, R>\n        <A, E, R>(\n          effect: Effect.Effect<A, E, R>,\n          state: Machine.State<M>\n        ): Effect.Effect<readonly [void, Machine.State<M>], never, R>\n      } = dual(2, <A, E, R>(\n        effect: Effect.Effect<A, E, R>,\n        state: Machine.State<M>\n      ): Effect.Effect<readonly [void, Machine.State<M>], never, R> =>\n        Effect.map(fork(effect), (_) => [_, state] as const))\n\n      const forkReplace: {\n        (id: string): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<void, never, R>\n        <A, E, R>(effect: Effect.Effect<A, E, R>, id: string): Effect.Effect<void, never, R>\n      } = dual(2, <A, E, R>(effect: Effect.Effect<A, E, R>, id: string): Effect.Effect<void, never, R> =>\n        Effect.asVoid(\n          FiberMap.run(fiberMap, id, MachineDefect.wrap(effect))\n        ))\n      const forkReplaceWith: {\n        (\n          id: string,\n          state: Machine.State<M>\n        ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<readonly [void, Machine.State<M>], never, R>\n        <A, E, R>(\n          effect: Effect.Effect<A, E, R>,\n          id: string,\n          state: Machine.State<M>\n        ): Effect.Effect<readonly [void, Machine.State<M>], never, R>\n      } = dual(3, <A, E, R>(\n        effect: Effect.Effect<A, E, R>,\n        id: string,\n        state: Machine.State<M>\n      ): Effect.Effect<readonly [void, Machine.State<M>], never, R> =>\n        Effect.map(forkReplace(effect, id), (_) => [_, state] as const))\n\n      const forkOne: {\n        (id: string): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<void, never, R>\n        <A, E, R>(effect: Effect.Effect<A, E, R>, id: string): Effect.Effect<void, never, R>\n      } = dual(2, <A, E, R>(effect: Effect.Effect<A, E, R>, id: string): Effect.Effect<void, never, R> =>\n        Effect.asVoid(FiberMap.run(fiberMap, id, MachineDefect.wrap(effect), { onlyIfMissing: true })))\n\n      const forkOneWith: {\n        (\n          id: string,\n          state: Machine.State<M>\n        ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<readonly [void, Machine.State<M>], never, R>\n        <A, E, R>(\n          effect: Effect.Effect<A, E, R>,\n          id: string,\n          state: Machine.State<M>\n        ): Effect.Effect<readonly [void, Machine.State<M>], never, R>\n      } = dual(3, <A, E, R>(\n        effect: Effect.Effect<A, E, R>,\n        id: string,\n        state: Machine.State<M>\n      ): Effect.Effect<readonly [void, Machine.State<M>], never, R> =>\n        Effect.map(\n          forkOne(effect, id),\n          (_) =>\n            [_, state] as const\n        ))\n\n      const contextProto: Procedure.Procedure.ContextProto<Machine.Public<M>, Machine.State<M>> = {\n        sendAwait: send,\n        send: sendIgnore,\n        unsafeSend: sendIgnore as any,\n        unsafeSendAwait: send as any,\n        fork,\n        forkWith,\n        forkOne,\n        forkOneWith,\n        forkReplace,\n        forkReplaceWith\n      }\n\n      const procedures = yield* pipe(\n        self.initialize(input, currentState ?? options?.previousState) as Effect.Effect<\n          SerializableProcedureList<Machine.State<M>, Machine.Public<M>, Machine.Private<M>, never>,\n          Machine.InitError<M>\n        >,\n        Effect.provideService(MachineContext, contextProto)\n      )\n      const procedureMap: Record<\n        string,\n        Procedure.Procedure<any, Machine.State<M>, Machine.Context<M>>\n      > = Object.fromEntries(\n        procedures.private.map((p) => [p.tag, p]).concat(\n          procedures.public.map((p) => [p.tag, p])\n        )\n      )\n\n      runState = {\n        identifier: procedures.identifier,\n        publicTags: new Set(procedures.public.map((p) =>\n          p.tag\n        )),\n        decodeRequest: Schema.decodeUnknown(\n          Schema.Union(\n            ...Arr.filter(\n              procedures.public,\n              Procedure.isSerializable\n            ).map((p) => p.schema)\n          )\n        )\n      }\n      yield* publishState(procedures.initialState)\n      yield* Deferred.succeed(latch, void 0)\n\n      const process = pipe(\n        Queue.take(requests),\n        Effect.flatMap(([request, deferred, span, addSpan]) =>\n          Effect.flatMap(Deferred.isDone(deferred), (done) => {\n            if (done) {\n              return Effect.void\n            }\n\n            const procedure = procedureMap[request._tag]\n            if (procedure === undefined) {\n              return Deferred.die(deferred, `Unknown request ${request._tag}`)\n            }\n            const context = Object.create(contextProto)\n            context.state = currentState\n            context.request = request\n            context.deferred = deferred\n\n            let handler = Effect.matchCauseEffect(\n              procedure.handler(context),\n              {\n                onFailure: (e) => {\n                  if (Cause.isFailure(e)) {\n                    return Deferred.failCause(deferred, e)\n                  }\n                  // defects kill the actor\n                  return Effect.zipRight(\n                    Deferred.failCause(deferred, e),\n                    Effect.failCause(e)\n                  )\n                },\n                onSuccess: ([response, newState]) => {\n                  if (response === Procedure.NoReply) {\n                    return publishState(newState)\n                  }\n                  return Effect.zipRight(\n                    publishState(newState),\n                    Deferred.succeed(deferred, response)\n                  )\n                }\n              }\n            )\n            if (addSpan) {\n              handler = Effect.withSpan(handler, `Machine.process ${request._tag}`, {\n                kind: \"server\",\n                parent: span,\n                attributes: {\n                  \"effect.machine\": runState.identifier\n                },\n                captureStackTrace: false\n              })\n            } else if (span !== undefined) {\n              handler = Effect.provideService(handler, Tracer.ParentSpan, span)\n            }\n\n            return handler\n          })\n        ),\n        Effect.forever,\n        Effect.provideService(MachineContext, contextProto)\n      )\n\n      yield* pipe(\n        Effect.all([\n          process,\n          FiberSet.join(fiberSet),\n          FiberMap.join(fiberMap)\n        ], { concurrency: \"unbounded\", discard: true }),\n        Effect.onExit((exit) => {\n          if (exit._tag === \"Success\") return Effect.die(\"absurd\")\n          return Effect.flatMap(\n            Queue.takeAll(requests),\n            Effect.forEach(([, deferred]) => Deferred.failCause(deferred, exit.cause))\n          )\n        }),\n        Effect.tapErrorCause((cause) =>\n          FiberRef.getWith(\n            FiberRef.unhandledErrorLogLevel,\n            Option.match({\n              onNone: () => Effect.void,\n              onSome: (level) =>\n                Effect.log(`Unhandled Machine (${runState.identifier}) failure`, cause).pipe(\n                  Effect.locally(FiberRef.currentLogLevel, level)\n                )\n            })\n          )\n        ),\n        Effect.catchAllDefect((cause) => Effect.fail(new MachineDefect({ cause })))\n      )\n    }).pipe(Effect.scoped) as Effect.Effect<\n      never,\n      MachineDefect | Machine.InitError<M>\n    >\n\n    const fiber = yield* pipe(\n      run,\n      self.retryPolicy ?\n        Effect.retry(self.retryPolicy) :\n        identity,\n      Effect.forkScoped,\n      Effect.interruptible\n    )\n\n    yield* Deferred.await(latch)\n\n    return identity<SerializableActor<M>>(Object.assign(Object.create(ActorProto), {\n      machine: self,\n      input: input!,\n      get: Effect.sync(() => currentState),\n      changes: Stream.concat(\n        Stream.sync(() => currentState),\n        Stream.fromPubSub(pubsub)\n      ),\n      send: sendExternal,\n      sendUnknown,\n      join: Fiber.join(fiber)\n    })) as any\n  })\n\n/**\n * @since 1.0.0\n * @category runtime\n */\nexport const snapshot = <\n  State,\n  Public extends Schema.TaggedRequest.All,\n  Private extends Schema.TaggedRequest.All,\n  Input,\n  InitErr,\n  R,\n  SR\n>(\n  self: Actor<\n    SerializableMachine<\n      State,\n      Public,\n      Private,\n      Input,\n      InitErr,\n      R,\n      SR\n    >\n  >\n): Effect.Effect<[input: unknown, state: unknown], ParseResult.ParseError, SR> =>\n  Effect.zip(\n    Schema.encode(self.machine.schemaInput)(self.input),\n    Effect.flatMap(self.get, Schema.encode(self.machine.schemaState))\n  )\n\n/**\n * @since 1.0.0\n * @category runtime\n */\nexport const restore = <\n  State,\n  Public extends Schema.TaggedRequest.All,\n  Private extends Schema.TaggedRequest.All,\n  Input,\n  InitErr,\n  R,\n  SR\n>(\n  self: SerializableMachine<\n    State,\n    Public,\n    Private,\n    Input,\n    InitErr,\n    R,\n    SR\n  >,\n  snapshot: readonly [input: unknown, state: unknown]\n): Effect.Effect<\n  Actor<\n    SerializableMachine<\n      State,\n      Public,\n      Private,\n      Input,\n      InitErr,\n      R,\n      SR\n    >\n  >,\n  ParseResult.ParseError,\n  R | SR\n> =>\n  Effect.flatMap(\n    Schema.decodeUnknown(Schema.Tuple(self.schemaInput, self.schemaState))(snapshot),\n    ([input, previousState]) => (boot as any)(self, input, { previousState })\n  )\n"
  },
  {
    "path": "packages/experimental/src/PersistedCache.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Cache from \"effect/Cache\"\nimport * as Data from \"effect/Data\"\nimport type * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport { identity, pipe } from \"effect/Function\"\nimport * as Hash from \"effect/Hash\"\nimport * as Option from \"effect/Option\"\nimport type * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Tracer from \"effect/Tracer\"\nimport * as Persistence from \"./Persistence.js\"\n\nclass CacheRequest<K extends Persistence.ResultPersistence.KeyAny> extends Data.Class<{\n  readonly key: K\n  readonly span: Option.Option<Tracer.AnySpan>\n}> {\n  [Equal.symbol](that: CacheRequest<K>): boolean {\n    return Equal.equals(this.key, that.key)\n  }\n  [Hash.symbol]() {\n    return Hash.hash(this.key)\n  }\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface PersistedCache<K extends Persistence.ResultPersistence.KeyAny> {\n  readonly get: (\n    key: K\n  ) => Effect.Effect<\n    Schema.WithResult.Success<K>,\n    Schema.WithResult.Failure<K> | Persistence.PersistenceError\n  >\n  readonly invalidate: (key: K) => Effect.Effect<void, Persistence.PersistenceError>\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <K extends Persistence.ResultPersistence.KeyAny, R>(options: {\n  readonly storeId: string\n  readonly lookup: (key: K) => Effect.Effect<Schema.WithResult.Success<K>, Schema.WithResult.Failure<K>, R>\n  readonly timeToLive: (...args: Persistence.ResultPersistence.TimeToLiveArgs<K>) => Duration.DurationInput\n  readonly inMemoryCapacity?: number | undefined\n  readonly inMemoryTTL?: Duration.DurationInput | undefined\n}): Effect.Effect<\n  PersistedCache<K>,\n  never,\n  Schema.SerializableWithResult.Context<K> | R | Persistence.ResultPersistence | Scope.Scope\n> =>\n  Persistence.ResultPersistence.pipe(\n    Effect.flatMap((_) =>\n      _.make({\n        storeId: options.storeId,\n        timeToLive: options.timeToLive as any\n      })\n    ),\n    Effect.bindTo(\"store\"),\n    Effect.bind(\"inMemoryCache\", ({ store }) =>\n      Cache.make({\n        lookup: (request: CacheRequest<K>) => {\n          const effect: Effect.Effect<\n            Schema.WithResult.Success<K>,\n            Schema.WithResult.Failure<K> | Persistence.PersistenceError,\n            Schema.SerializableWithResult.Context<K> | R\n          > = pipe(\n            store.get(request.key as any),\n            Effect.flatMap(Option.match({\n              onNone: () =>\n                options.lookup(request.key).pipe(\n                  Effect.exit,\n                  Effect.tap((exit) => store.set(request.key as any, exit)),\n                  Effect.flatten\n                ),\n              onSome: identity\n            }))\n          ) as any\n          return request.span._tag === \"Some\" ? Effect.withParentSpan(effect, request.span.value) : effect\n        },\n        capacity: options.inMemoryCapacity ?? 64,\n        timeToLive: options.inMemoryTTL ?? 10_000\n      })),\n    Effect.map(({ inMemoryCache, store }) =>\n      identity<PersistedCache<K>>({\n        get: (key) =>\n          Effect.serviceOption(Tracer.ParentSpan).pipe(\n            Effect.flatMap((span) => inMemoryCache.get(new CacheRequest({ key, span })))\n          ),\n        invalidate: (key) =>\n          store.remove(key as any).pipe(\n            Effect.zipRight(inMemoryCache.invalidate(new CacheRequest({ key, span: Option.none() })))\n          )\n      })\n    )\n  )\n"
  },
  {
    "path": "packages/experimental/src/PersistedQueue/Redis.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Cause from \"effect/Cause\"\nimport * as Config from \"effect/Config\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Layer from \"effect/Layer\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport * as MutableRef from \"effect/MutableRef\"\nimport * as Option from \"effect/Option\"\nimport * as RcMap from \"effect/RcMap\"\nimport * as Schedule from \"effect/Schedule\"\nimport type { RedisOptions } from \"ioredis\"\nimport { Redis } from \"ioredis\"\nimport * as PersistedQueue from \"../PersistedQueue.js\"\n\ninterface RedisWithQueue extends Redis {\n  offer(\n    keyQueue: string,\n    keyIds: string,\n    id: string,\n    payload: string\n  ): Promise<void>\n  resetQueue(\n    keyQueue: string,\n    keyPending: string,\n    prefix: string\n  ): Promise<void>\n  requeue(\n    keyQueue: string,\n    keyPending: string,\n    keyLock: string,\n    id: string,\n    payload: string\n  ): Promise<void>\n  take(\n    keyQueue: string,\n    keyPending: string,\n    prefix: string,\n    workerId: string,\n    batchSize: number,\n    pttl: number\n  ): Promise<Array<string> | null>\n  complete(\n    keyPending: string,\n    keyLock: string,\n    id: string\n  ): Promise<void>\n  failed(\n    keyPending: string,\n    keyLock: string,\n    keyFailed: string,\n    id: string,\n    payload: string\n  ): Promise<void>\n}\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.fnUntraced(function*(\n  options: RedisOptions & {\n    readonly prefix?: string | undefined\n    readonly pollInterval?: Duration.DurationInput | undefined\n    readonly lockRefreshInterval?: Duration.DurationInput | undefined\n    readonly lockExpiration?: Duration.DurationInput | undefined\n  }\n) {\n  const pollInterval = options.pollInterval ? Duration.decode(options.pollInterval) : Duration.seconds(1)\n\n  const redis = yield* Effect.acquireRelease(\n    Effect.sync(() => new Redis(options) as RedisWithQueue),\n    (redis) => Effect.promise(() => redis.quit())\n  )\n\n  redis.defineCommand(\"offer\", {\n    lua: `\nlocal key_queue = KEYS[1]\nlocal key_ids = KEYS[2]\nlocal id = ARGV[1]\nlocal payload = ARGV[2]\n\nlocal result = redis.call(\"SADD\", key_ids, id)\nif result == 1 then\n  redis.call(\"RPUSH\", key_queue, payload)\nend\n`,\n    numberOfKeys: 2,\n    readOnly: false\n  })\n\n  redis.defineCommand(\"resetQueue\", {\n    lua: `\nlocal key_queue = KEYS[1]\nlocal key_pending = KEYS[2]\nlocal prefix = ARGV[1]\n\nlocal entries = redis.call(\"HGETALL\", key_pending)\nfor id, payload in pairs(entries) do\n  local lock_key = prefix .. id .. \":lock\"\n  local exists = redis.call(\"EXISTS\", lock_key)\n  if exists == 0 then\n    redis.call(\"RPUSH\", key_queue, payload)\n    redis.call(\"HDEL\", key_pending, id)\n  end\nend\n`,\n    numberOfKeys: 2,\n    readOnly: false\n  })\n\n  redis.defineCommand(\"requeue\", {\n    lua: `\nlocal key_queue = KEYS[1]\nlocal key_pending = KEYS[2]\nlocal key_lock = KEYS[3]\nlocal id = ARGV[1]\nlocal payload = ARGV[2]\n\nredis.call(\"DEL\", key_lock)\nredis.call(\"HDEL\", key_pending, id)\nredis.call(\"RPUSH\", key_queue, payload)\n`,\n    numberOfKeys: 3,\n    readOnly: false\n  })\n\n  redis.defineCommand(\"complete\", {\n    lua: `\nlocal key_pending = KEYS[1]\nlocal key_lock = KEYS[2]\nlocal id = ARGV[1]\n\nredis.call(\"DEL\", key_lock)\nredis.call(\"HDEL\", key_pending, id)\n`,\n    numberOfKeys: 2,\n    readOnly: false\n  })\n\n  redis.defineCommand(\"failed\", {\n    lua: `\nlocal key_pending = KEYS[1]\nlocal key_lock = KEYS[2]\nlocal key_failed = KEYS[3]\nlocal id = ARGV[1]\nlocal payload = ARGV[2]\n\nredis.call(\"DEL\", key_lock)\nredis.call(\"HDEL\", key_pending, id)\nredis.call(\"RPUSH\", key_failed, payload)\n`,\n    numberOfKeys: 2,\n    readOnly: false\n  })\n\n  redis.defineCommand(\"take\", {\n    lua: `\nlocal key_queue = KEYS[1]\nlocal key_pending = KEYS[2]\nlocal prefix = ARGV[1]\nlocal worker_id = ARGV[2]\nlocal batch_size = tonumber(ARGV[3])\nlocal pttl = ARGV[4]\n\nlocal payloads = redis.call(\"LPOP\", key_queue, batch_size)\nif not payloads then\n  return nil\nend\n\nfor i, payload in ipairs(payloads) do\n  local id = cjson.decode(payload).id\n  local key_lock = prefix .. id .. \":lock\"\n  redis.call(\"SET\", key_lock, worker_id, \"PX\", pttl)\n  redis.call(\"HSET\", key_pending, id, payload)\nend\n\nreturn payloads\n`,\n    numberOfKeys: 2,\n    readOnly: false\n  })\n\n  const lockRefreshMillis = options.lockRefreshInterval ? Duration.toMillis(options.lockRefreshInterval) : 30_000\n  const lockExpirationMillis = options.lockExpiration ? Duration.toMillis(options.lockExpiration) : 90_000\n  const prefix = options.prefix ?? \"effectq:\"\n  const keyQueue = (name: string) => `${prefix}${name}`\n  const keyLock = (id: string) => `${prefix}${id}:lock`\n  const keyPending = (name: string) => `${prefix}${name}:pending`\n  const keyFailed = (name: string) => `${prefix}${name}:failed`\n  const workerId = crypto.randomUUID()\n\n  type Element = {\n    readonly id: string\n    readonly element: unknown\n    attempts: number\n    lastFailure?: string\n  }\n\n  const mailboxes = yield* RcMap.make({\n    lookup: Effect.fnUntraced(function*(name: string) {\n      const queueKey = keyQueue(name)\n      const pendingKey = keyPending(name)\n      const mailbox = yield* Mailbox.make<Element>()\n      const takers = MutableRef.make(0)\n      const pollLatch = Effect.unsafeMakeLatch()\n      const takenLatch = Effect.unsafeMakeLatch()\n\n      yield* Effect.addFinalizer(() =>\n        Effect.flatMap(\n          mailbox.clear,\n          (elements) =>\n            elements.length === 0\n              ? Effect.void\n              : Effect.promise(() =>\n                Promise.all(Array.from(elements, (element) =>\n                  redis.requeue(\n                    queueKey,\n                    pendingKey,\n                    keyLock(element.id),\n                    element.id,\n                    JSON.stringify(element)\n                  )))\n              )\n        )\n      )\n\n      yield* Effect.sync(() => {\n        redis.resetQueue(queueKey, pendingKey, prefix)\n      }).pipe(\n        Effect.andThen(Effect.sleep(lockRefreshMillis)),\n        Effect.forever,\n        Effect.forkScoped,\n        Effect.interruptible\n      )\n\n      const poll = (size: number) =>\n        Effect.promise(() =>\n          redis.take(\n            queueKey,\n            pendingKey,\n            prefix,\n            workerId,\n            size,\n            lockExpirationMillis\n          )\n        )\n\n      yield* Effect.gen(function*() {\n        while (true) {\n          yield* pollLatch.await\n          yield* Effect.yieldNow()\n          const results = takers.current === 0 ? null : yield* poll(takers.current)\n          if (results === null) {\n            yield* Effect.sleep(pollInterval)\n            continue\n          }\n          takenLatch.unsafeClose()\n          yield* mailbox.offerAll(results.map((json) => JSON.parse(json)))\n          yield* takenLatch.await\n          yield* Effect.yieldNow()\n        }\n      }).pipe(\n        Effect.sandbox,\n        Effect.retry(Schedule.spaced(500)),\n        Effect.forkScoped,\n        Effect.interruptible\n      )\n\n      return { mailbox, takers, pollLatch, takenLatch } as const\n    }),\n    idleTimeToLive: Duration.seconds(30)\n  })\n\n  const activeLockKeys = new Set<string>()\n\n  yield* Effect.gen(function*() {\n    while (true) {\n      yield* Effect.sleep(lockRefreshMillis)\n      activeLockKeys.forEach((key) => {\n        redis.pexpire(key, lockExpirationMillis)\n      })\n    }\n  }).pipe(\n    Effect.forkScoped,\n    Effect.interruptible,\n    Effect.annotateLogs({\n      package: \"@effect/experimental\",\n      module: \"PersistedQueue/Redis\",\n      fiber: \"refreshLocks\"\n    })\n  )\n\n  return PersistedQueue.PersistedQueueStore.of({\n    offer: ({ element, id, isCustomId, name }) =>\n      Effect.tryPromise({\n        try: (): Promise<any> =>\n          isCustomId\n            ? redis.offer(\n              `${prefix}${name}`,\n              `${prefix}${name}:ids`,\n              id,\n              JSON.stringify({ id, element, attempts: 0 })\n            )\n            : redis.lpush(`${prefix}${name}`, JSON.stringify({ id, element, attempts: 0 })),\n        catch: (cause) =>\n          new PersistedQueue.PersistedQueueError({\n            message: \"Failed to offer element to persisted queue\",\n            cause\n          })\n      }),\n    take: (options) =>\n      Effect.uninterruptibleMask((restore) =>\n        RcMap.get(mailboxes, options.name).pipe(\n          Effect.flatMap(({ mailbox, pollLatch, takenLatch, takers }) => {\n            takers.current++\n            if (takers.current === 1) {\n              pollLatch.unsafeOpen()\n            }\n            return Effect.tap(restore(mailbox.take as Effect.Effect<Element>), () => {\n              takers.current--\n              if (takers.current === 0) {\n                pollLatch.unsafeClose()\n                takenLatch.unsafeOpen()\n              } else if (Option.getOrUndefined(mailbox.unsafeSize()) === 0) {\n                takenLatch.unsafeOpen()\n              }\n            })\n          }),\n          Effect.scoped,\n          Effect.tap((element) => {\n            const lock = keyLock(element.id)\n            activeLockKeys.add(lock)\n            return Effect.addFinalizer(Exit.match({\n              onFailure: (cause) => {\n                activeLockKeys.delete(lock)\n                const nextAttempts = element.attempts + 1\n                if (nextAttempts >= options.maxAttempts) {\n                  return Effect.promise(() =>\n                    redis.failed(\n                      keyPending(options.name),\n                      lock,\n                      keyFailed(options.name),\n                      element.id,\n                      JSON.stringify({\n                        ...element,\n                        lastFailure: Cause.pretty(cause, { renderErrorCause: true }),\n                        attempts: nextAttempts\n                      })\n                    )\n                  )\n                }\n                return Effect.promise(() =>\n                  redis.requeue(\n                    keyQueue(options.name),\n                    keyPending(options.name),\n                    lock,\n                    element.id,\n                    JSON.stringify(\n                      Cause.isInterruptedOnly(cause)\n                        ? element\n                        : {\n                          ...element,\n                          lastFailure: Cause.pretty(cause, { renderErrorCause: true }),\n                          attempts: nextAttempts\n                        }\n                    )\n                  )\n                )\n              },\n              onSuccess: () => {\n                activeLockKeys.delete(lock)\n                return Effect.promise(() =>\n                  redis.complete(\n                    keyPending(options.name),\n                    lock,\n                    element.id\n                  )\n                )\n              }\n            }))\n          })\n        )\n      )\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerStore = (\n  options: RedisOptions & {\n    readonly prefix?: string | undefined\n    readonly pollInterval?: Duration.DurationInput | undefined\n    readonly lockRefreshInterval?: Duration.DurationInput | undefined\n    readonly lockExpiration?: Duration.DurationInput | undefined\n  }\n) => Layer.scoped(PersistedQueue.PersistedQueueStore, make(options))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerStoreConfig = (\n  options: Config.Config.Wrap<RedisOptions & { readonly prefix?: string | undefined }>\n) => Layer.scoped(PersistedQueue.PersistedQueueStore, Effect.flatMap(Config.unwrap(options), make))\n"
  },
  {
    "path": "packages/experimental/src/PersistedQueue.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Iterable from \"effect/Iterable\"\nimport * as Layer from \"effect/Layer\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport * as Schema from \"effect/Schema\"\nimport * as Scope from \"effect/Scope\"\n\n/**\n * @since 1.0.0\n * @category Type IDs\n */\nexport const TypeId: TypeId = \"~@effect/experimental/PersistedQueue\"\n\n/**\n * @since 1.0.0\n * @category Type IDs\n */\nexport type TypeId = \"~@effect/experimental/PersistedQueue\"\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface PersistedQueue<in out A, out R = never> {\n  readonly [TypeId]: TypeId\n\n  /**\n   * Adds an element to the queue. Returns the id of the enqueued element.\n   *\n   * If an element with the same id already exists in the queue, it will not be\n   * added again.\n   */\n  readonly offer: (value: A, options?: {\n    readonly id: string | undefined\n  }) => Effect.Effect<string, PersistedQueueError | ParseResult.ParseError, R>\n\n  /**\n   * Takes an element from the queue.\n   * If the queue is empty, it will wait until an element is available.\n   *\n   * If the returned effect succeeds, the element is marked as processed,\n   * otherwise it will be retried according to the provided options.\n   *\n   * By default, max attempts is set to 10.\n   */\n  readonly take: <XA, XE, XR>(\n    f: (value: A, metadata: {\n      readonly id: string\n      readonly attempts: number\n    }) => Effect.Effect<XA, XE, XR>,\n    options?: {\n      readonly maxAttempts?: number | undefined\n    }\n  ) => Effect.Effect<XA, XE | PersistedQueueError | ParseResult.ParseError, R | XR>\n}\n\n/**\n * @since 1.0.0\n * @category Factory\n */\nexport class PersistedQueueFactory extends Context.Tag(\"@effect/experimental/PersistedQueue/PersistedQueueFactory\")<\n  PersistedQueueFactory,\n  {\n    readonly make: <A, I, R>(options: {\n      readonly name: string\n      readonly schema: Schema.Schema<A, I, R>\n    }) => Effect.Effect<PersistedQueue<A, R>>\n  }\n>() {}\n\n/**\n * @since 1.0.0\n * @category Accessors\n */\nexport const make = <A, I, R>(options: {\n  readonly name: string\n  readonly schema: Schema.Schema<A, I, R>\n}): Effect.Effect<PersistedQueue<A, R>, never, PersistedQueueFactory> =>\n  Effect.flatMap(\n    PersistedQueueFactory,\n    (factory) => factory.make(options)\n  )\n\n/**\n * @since 1.0.0\n * @category Factory\n */\nexport const makeFactory = Effect.gen(function*() {\n  const store = yield* PersistedQueueStore\n\n  return PersistedQueueFactory.of({\n    make<A, I, R>(options: {\n      readonly name: string\n      readonly schema: Schema.Schema<A, I, R>\n    }) {\n      const encodeUnknown = Schema.encodeUnknown(options.schema)\n      const decodeUnknown = Schema.decodeUnknown(options.schema)\n\n      return Effect.succeed<PersistedQueue<A, R>>({\n        [TypeId]: TypeId,\n        offer: (value, opts) =>\n          Effect.flatMap(\n            encodeUnknown(value),\n            (element) => {\n              const id = opts?.id ?? crypto.randomUUID()\n              return Effect.as(\n                store.offer({\n                  name: options.name,\n                  id,\n                  element,\n                  isCustomId: opts?.id !== undefined\n                }),\n                id\n              )\n            }\n          ),\n        take: (f, opts) =>\n          Effect.uninterruptibleMask(Effect.fnUntraced(function*(restore) {\n            const scope = yield* Scope.make()\n            const item = yield* store.take({\n              name: options.name,\n              maxAttempts: opts?.maxAttempts ?? 10\n            }).pipe(\n              Scope.extend(scope),\n              restore\n            )\n            const exit = yield* decodeUnknown(item.element).pipe(\n              Effect.flatMap((value) => f(value, { id: item.id, attempts: item.attempts })),\n              restore,\n              Effect.exit\n            )\n            yield* Scope.close(scope, exit)\n            return yield* exit\n          }))\n      })\n    }\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Factory\n */\nexport const layer: Layer.Layer<\n  PersistedQueueFactory,\n  never,\n  PersistedQueueStore\n> = Layer.effect(PersistedQueueFactory, makeFactory)\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport const ErrorTypeId: ErrorTypeId = \"~@effect/experimental/PersistedQueue/PersistedQueueError\"\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport type ErrorTypeId = \"~@effect/experimental/PersistedQueue/PersistedQueueError\"\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport class PersistedQueueError extends Schema.TaggedError<PersistedQueueError>(\n  \"@effect/experimental/PersistedQueue/PersistedQueueError\"\n)(\"PersistedQueueError\", {\n  message: Schema.String,\n  cause: Schema.optional(Schema.Defect)\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId\n}\n\n/**\n * @since 1.0.0\n * @category Store\n */\nexport class PersistedQueueStore extends Context.Tag(\"@effect/experimental/PersistedQueue/PersistedQueueStore\")<\n  PersistedQueueStore,\n  {\n    readonly offer: (\n      options: {\n        readonly name: string\n        readonly id: string\n        readonly element: unknown\n        readonly isCustomId: boolean\n      }\n    ) => Effect.Effect<void, PersistedQueueError>\n\n    readonly take: (options: {\n      readonly name: string\n      readonly maxAttempts: number\n    }) => Effect.Effect<\n      {\n        readonly id: string\n        readonly attempts: number\n        readonly element: unknown\n      },\n      PersistedQueueError,\n      Scope.Scope\n    >\n  }\n>() {}\n\n/**\n * @since 1.0.0\n * @category Store\n */\nexport const layerStoreMemory: Layer.Layer<\n  PersistedQueueStore\n> = Layer.sync(PersistedQueueStore, () => {\n  type Entry = {\n    readonly id: string\n    attempts: number\n    readonly element: unknown\n  }\n  const ids = new Set<string>()\n  const queues = new Map<string, {\n    latch: Effect.Latch\n    items: Set<Entry>\n  }>()\n  const getOrCreateQueue = (name: string) => {\n    let queue = queues.get(name)\n    if (!queue) {\n      queue = {\n        latch: Effect.unsafeMakeLatch(false),\n        items: new Set()\n      }\n      queues.set(name, queue)\n    }\n    return queue\n  }\n\n  return PersistedQueueStore.of({\n    offer: (options) =>\n      Effect.sync(() => {\n        if (ids.has(options.id)) return\n        ids.add(options.id)\n        const queue = getOrCreateQueue(options.name)\n        queue.items.add({ id: options.id, attempts: 0, element: options.element })\n        queue.latch.unsafeOpen()\n      }),\n    take: Effect.fnUntraced(function*(options) {\n      const queue = getOrCreateQueue(options.name)\n      while (true) {\n        yield* queue.latch.await\n        const item = Iterable.unsafeHead(queue.items)\n        queue.items.delete(item)\n        if (queue.items.size === 0) {\n          queue.latch.unsafeClose()\n        }\n        yield* Effect.addFinalizer((exit) => {\n          if (exit._tag === \"Success\") {\n            return Effect.void\n          } else if (!Exit.isInterrupted(exit)) {\n            item.attempts += 1\n          }\n          if (item.attempts >= options.maxAttempts) {\n            return Effect.void\n          }\n          queue.items.add(item)\n          queue.latch.unsafeOpen()\n          return Effect.void\n        })\n        return item\n      }\n    })\n  })\n})\n"
  },
  {
    "path": "packages/experimental/src/Persistence/Lmdb.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Arr from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Lmdb from \"lmdb\"\nimport * as Persistence from \"../Persistence.js\"\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = (options: Lmdb.RootDatabaseOptionsWithPath) =>\n  Effect.gen(function*() {\n    const lmdb = yield* Effect.acquireRelease(\n      Effect.sync(() => Lmdb.open(options)),\n      (lmdb) => Effect.promise(() => lmdb.close())\n    )\n\n    return Persistence.BackingPersistence.of({\n      [Persistence.BackingPersistenceTypeId]: Persistence.BackingPersistenceTypeId,\n      make: (storeId) =>\n        Effect.gen(function*() {\n          const clock = yield* Effect.clock\n          const store = yield* Effect.acquireRelease(\n            Effect.sync(() => lmdb.openDB({ name: storeId })),\n            (store) => Effect.promise(() => store.close())\n          )\n          const valueToOption = (key: string, _: any) => {\n            if (!Arr.isArray(_)) return Option.none()\n            const [value, expires] = _ as [unknown, number | null]\n            if (expires !== null && expires <= clock.unsafeCurrentTimeMillis()) {\n              store.remove(key)\n              return Option.none()\n            }\n            return Option.some(value)\n          }\n          return identity<Persistence.BackingPersistenceStore>({\n            get: (key) =>\n              Effect.try({\n                try: () => valueToOption(key, store.get(key)),\n                catch: (error) => Persistence.PersistenceBackingError.make(\"get\", error)\n              }),\n            getMany: (keys) =>\n              Effect.map(\n                Effect.tryPromise({\n                  try: () => store.getMany(keys),\n                  catch: (error) => Persistence.PersistenceBackingError.make(\"getMany\", error)\n                }),\n                Arr.map((value, i) => valueToOption(keys[i], value))\n              ),\n            set: (key, value, ttl) =>\n              Effect.tryPromise({\n                try: () => store.put(key, [value, Persistence.unsafeTtlToExpires(clock, ttl)]),\n                catch: (error) => Persistence.PersistenceBackingError.make(\"set\", error)\n              }),\n            setMany: (entries) =>\n              Effect.tryPromise({\n                try: () =>\n                  Promise.all(entries.map(([key, value, ttl]) =>\n                    store.put(key, [value, Persistence.unsafeTtlToExpires(clock, ttl)])\n                  )),\n                catch: (error) =>\n                  Persistence.PersistenceBackingError.make(\"setMany\", error)\n              }),\n            remove: (key) =>\n              Effect.tryPromise({\n                try: () => store.remove(key),\n                catch: (error) => Persistence.PersistenceBackingError.make(\"remove\", error)\n              }),\n            clear: Effect.tryPromise({\n              try: () => store.clearAsync(),\n              catch: (error) => Persistence.PersistenceBackingError.make(\"clear\", error)\n            })\n          })\n        })\n    })\n  })\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer = (\n  options: Lmdb.RootDatabaseOptionsWithPath\n): Layer.Layer<Persistence.BackingPersistence> =>\n  Layer.scoped(\n    Persistence.BackingPersistence,\n    make(options)\n  )\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerResult = (\n  options: Lmdb.RootDatabaseOptionsWithPath\n): Layer.Layer<Persistence.ResultPersistence> =>\n  Persistence.layerResult.pipe(\n    Layer.provide(layer(options))\n  )\n"
  },
  {
    "path": "packages/experimental/src/Persistence/Redis.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Arr from \"effect/Array\"\nimport * as Config from \"effect/Config\"\nimport type { ConfigError } from \"effect/ConfigError\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport type { RedisOptions } from \"ioredis\"\nimport { Redis } from \"ioredis\"\nimport * as Persistence from \"../Persistence.js\"\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = Effect.fnUntraced(function*(options: RedisOptions) {\n  const redis = yield* Effect.acquireRelease(\n    Effect.sync(() => new Redis(options)),\n    (redis) => Effect.promise(() => redis.quit())\n  )\n  return Persistence.BackingPersistence.of({\n    [Persistence.BackingPersistenceTypeId]: Persistence.BackingPersistenceTypeId,\n    make: (prefix) =>\n      Effect.sync(() => {\n        const prefixed = (key: string) => `${prefix}:${key}`\n        const parse = (method: string) => (str: string | null) => {\n          if (str === null) {\n            return Effect.succeedNone\n          }\n          return Effect.try({\n            try: () => Option.some(JSON.parse(str)),\n            catch: (error) => Persistence.PersistenceBackingError.make(method, error)\n          })\n        }\n        return identity<Persistence.BackingPersistenceStore>({\n          get: (key) =>\n            Effect.flatMap(\n              Effect.tryPromise({\n                try: () => redis.get(prefixed(key)),\n                catch: (error) => Persistence.PersistenceBackingError.make(\"get\", error)\n              }),\n              parse(\"get\")\n            ),\n          getMany: (keys) =>\n            Effect.flatMap(\n              Effect.tryPromise({\n                try: () => redis.mget(keys.map(prefixed)),\n                catch: (error) => Persistence.PersistenceBackingError.make(\"getMany\", error)\n              }),\n              Effect.forEach(parse(\"getMany\"))\n            ),\n          set: (key, value, ttl) =>\n            Effect.tryMapPromise(\n              Effect.try({\n                try: () => JSON.stringify(value),\n                catch: (error) => Persistence.PersistenceBackingError.make(\"set\", error)\n              }),\n              {\n                try: (value) =>\n                  ttl._tag === \"None\"\n                    ? redis.set(prefixed(key), value)\n                    : redis.set(prefixed(key), value, \"PX\", Duration.toMillis(ttl.value)),\n                catch: (error) => Persistence.PersistenceBackingError.make(\"set\", error)\n              }\n            ),\n          setMany: (entries) =>\n            Effect.suspend(() => {\n              const sets = new Map<string, string>()\n              const expires = Arr.empty<[string, number]>()\n              for (const [key, value, ttl] of entries) {\n                const pkey = prefixed(key)\n                sets.set(pkey, JSON.stringify(value))\n                if (Option.isSome(ttl)) {\n                  expires.push([pkey, Duration.toMillis(ttl.value)])\n                }\n              }\n              const multi = redis.multi()\n              multi.mset(sets)\n              for (const [key, ms] of expires) {\n                multi.pexpire(key, ms)\n              }\n              return Effect.tryPromise({\n                try: () => multi.exec(),\n                catch: (error) => Persistence.PersistenceBackingError.make(\"setMany\", error)\n              })\n            }),\n          remove: (key) =>\n            Effect.tryPromise({\n              try: () => redis.del(prefixed(key)),\n              catch: (error) => Persistence.PersistenceBackingError.make(\"remove\", error)\n            }),\n          clear: Effect.tryPromise({\n            try: () => redis.keys(`${prefix}:*`).then((keys) => redis.del(keys)),\n            catch: (error) => Persistence.PersistenceBackingError.make(\"clear\", error)\n          })\n        })\n      })\n  })\n})\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer = (\n  options: RedisOptions\n): Layer.Layer<Persistence.BackingPersistence> =>\n  Layer.scoped(\n    Persistence.BackingPersistence,\n    make(options)\n  )\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerConfig = (\n  options: Config.Config.Wrap<RedisOptions>\n): Layer.Layer<Persistence.BackingPersistence, ConfigError> =>\n  Layer.scoped(\n    Persistence.BackingPersistence,\n    Effect.flatMap(Config.unwrap(options), make)\n  )\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerResult = (\n  options: RedisOptions\n): Layer.Layer<Persistence.ResultPersistence> =>\n  Persistence.layerResult.pipe(\n    Layer.provide(layer(options))\n  )\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerResultConfig = (\n  options: Config.Config.Wrap<RedisOptions>\n): Layer.Layer<Persistence.ResultPersistence, ConfigError> =>\n  Persistence.layerResult.pipe(\n    Layer.provide(layerConfig(options))\n  )\n"
  },
  {
    "path": "packages/experimental/src/Persistence.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport { TypeIdError } from \"@effect/platform/Error\"\nimport * as KeyValueStore from \"@effect/platform/KeyValueStore\"\nimport * as Arr from \"effect/Array\"\nimport type * as Clock from \"effect/Clock\"\nimport * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Exit from \"effect/Exit\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as PrimaryKey from \"effect/PrimaryKey\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const ErrorTypeId: unique symbol = Symbol.for(\"@effect/experimental/PersistenceError\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type ErrorTypeId = typeof ErrorTypeId\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport type PersistenceError = PersistenceParseError | PersistenceBackingError\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport class PersistenceParseError extends TypeIdError(ErrorTypeId, \"PersistenceError\")<{\n  readonly reason: \"ParseError\"\n  readonly method: string\n  readonly error: ParseResult.ParseError[\"issue\"]\n}> {\n  /**\n   * @since 1.0.0\n   */\n  static make(method: string, error: ParseResult.ParseError[\"issue\"]) {\n    return new PersistenceParseError({ reason: \"ParseError\", method, error })\n  }\n\n  get message() {\n    return ParseResult.TreeFormatter.formatIssueSync(this.error)\n  }\n}\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport class PersistenceBackingError extends TypeIdError(ErrorTypeId, \"PersistenceError\")<{\n  readonly reason: \"BackingError\"\n  readonly method: string\n  readonly cause: unknown\n}> {\n  /**\n   * @since 1.0.0\n   */\n  static make(method: string, cause: unknown) {\n    return new PersistenceBackingError({ reason: \"BackingError\", method, cause })\n  }\n\n  get message() {\n    return this.reason\n  }\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const BackingPersistenceTypeId: unique symbol = Symbol.for(\"@effect/experimental/BackingPersistence\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type BackingPersistenceTypeId = typeof BackingPersistenceTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface BackingPersistence {\n  readonly [BackingPersistenceTypeId]: BackingPersistenceTypeId\n  readonly make: (storeId: string) => Effect.Effect<BackingPersistenceStore, never, Scope.Scope>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface BackingPersistenceStore {\n  readonly get: (key: string) => Effect.Effect<Option.Option<unknown>, PersistenceError>\n  readonly getMany: (key: Array<string>) => Effect.Effect<Array<Option.Option<unknown>>, PersistenceError>\n  readonly set: (\n    key: string,\n    value: unknown,\n    ttl: Option.Option<Duration.Duration>\n  ) => Effect.Effect<void, PersistenceError>\n  readonly setMany: (\n    entries: ReadonlyArray<readonly [key: string, value: unknown, ttl: Option.Option<Duration.Duration>]>\n  ) => Effect.Effect<void, PersistenceError>\n  readonly remove: (key: string) => Effect.Effect<void, PersistenceError>\n  readonly clear: Effect.Effect<void, PersistenceError>\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const BackingPersistence: Context.Tag<BackingPersistence, BackingPersistence> = Context.GenericTag<\n  BackingPersistence\n>(\n  \"@effect/experimental/BackingPersistence\"\n)\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const ResultPersistenceTypeId: unique symbol = Symbol.for(\"@effect/experimental/ResultPersistence\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type ResultPersistenceTypeId = typeof ResultPersistenceTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface ResultPersistence {\n  readonly [ResultPersistenceTypeId]: ResultPersistenceTypeId\n  readonly make: (options: {\n    readonly storeId: string\n    readonly timeToLive?: (key: ResultPersistence.KeyAny, exit: Exit.Exit<unknown, unknown>) => Duration.DurationInput\n  }) => Effect.Effect<ResultPersistenceStore, never, Scope.Scope>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface ResultPersistenceStore {\n  readonly get: <R, IE, E, IA, A>(\n    key: ResultPersistence.Key<R, IE, E, IA, A>\n  ) => Effect.Effect<Option.Option<Exit.Exit<A, E>>, PersistenceError, R>\n  readonly getMany: <R, IE, E, IA, A>(\n    key: ReadonlyArray<ResultPersistence.Key<R, IE, E, IA, A>>\n  ) => Effect.Effect<Array<Option.Option<Exit.Exit<A, E>>>, PersistenceError, R>\n  readonly set: <R, IE, E, IA, A>(\n    key: ResultPersistence.Key<R, IE, E, IA, A>,\n    value: Exit.Exit<A, E>\n  ) => Effect.Effect<void, PersistenceError, R>\n  readonly setMany: <R, IE, E, IA, A>(\n    entries: Iterable<readonly [ResultPersistence.Key<R, IE, E, IA, A>, Exit.Exit<A, E>]>\n  ) => Effect.Effect<void, PersistenceError, R>\n  readonly remove: <R, IE, E, IA, A>(\n    key: ResultPersistence.Key<R, IE, E, IA, A>\n  ) => Effect.Effect<void, PersistenceError>\n  readonly clear: Effect.Effect<void, PersistenceError>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Persistable<A extends Schema.Schema.Any, E extends Schema.Schema.All> extends\n  Schema.WithResult<\n    A[\"Type\"],\n    A[\"Encoded\"],\n    E[\"Type\"],\n    E[\"Encoded\"],\n    A[\"Context\"] | E[\"Context\"]\n  >,\n  PrimaryKey.PrimaryKey\n{}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace ResultPersistence {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Key<R, IE, E, IA, A> extends Schema.WithResult<A, IA, E, IE, R>, PrimaryKey.PrimaryKey {}\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type KeyAny = Persistable<any, any>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type TimeToLiveArgs<A> = A extends infer K\n    ? K extends Persistable<infer _A, infer _E> ? [request: K, exit: Exit.Exit<_A[\"Type\"], _E[\"Type\"]>]\n    : never\n    : never\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const ResultPersistence: Context.Tag<ResultPersistence, ResultPersistence> = Context.GenericTag<\n  ResultPersistence\n>(\n  \"@effect/experimental/ResultPersistence\"\n)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerResult = Layer.effect(\n  ResultPersistence,\n  Effect.gen(function*() {\n    const backing = yield* BackingPersistence\n    return ResultPersistence.of({\n      [ResultPersistenceTypeId]: ResultPersistenceTypeId,\n      make: (options) =>\n        Effect.gen(function*() {\n          const storage = yield* backing.make(options.storeId)\n          const timeToLive = options.timeToLive ?? (() => Duration.infinity)\n          const parse = <R, IE, E, IA, A>(\n            method: string,\n            key: ResultPersistence.Key<R, IE, E, IA, A>,\n            value: unknown\n          ) =>\n            Effect.mapError(\n              Schema.deserializeExit(key, value),\n              (_) => PersistenceParseError.make(method, _.issue)\n            )\n          const encode = <R, IE, E, IA, A>(\n            method: string,\n            key: ResultPersistence.Key<R, IE, E, IA, A>,\n            value: Exit.Exit<A, E>\n          ) =>\n            Effect.mapError(\n              Schema.serializeExit(key, value),\n              (_) => PersistenceParseError.make(method, _.issue)\n            )\n          const makeKey = <R, IE, E, IA, A>(\n            key: ResultPersistence.Key<R, IE, E, IA, A>\n          ) => key[PrimaryKey.symbol]()\n\n          return identity<ResultPersistenceStore>({\n            get: (key) =>\n              Effect.flatMap(\n                storage.get(makeKey(key)),\n                Option.match({\n                  onNone: () => Effect.succeedNone,\n                  onSome: (_) => Effect.asSome(parse(\"get\", key, _))\n                })\n              ),\n            getMany: (keys) =>\n              Effect.flatMap(\n                storage.getMany(keys.map(makeKey)),\n                Effect.forEach((result, i) => {\n                  const key = keys[i]\n                  return Option.match(result, {\n                    onNone: () => Effect.succeedNone,\n                    onSome: (_) =>\n                      parse(\"getMany\", key, _).pipe(\n                        Effect.tapError((_) => storage.remove(makeKey(keys[i]))),\n                        Effect.option\n                      )\n                  })\n                })\n              ),\n            set: (key, value) => {\n              const ttl = Duration.decode(timeToLive(key, value))\n              if (Duration.isZero(ttl)) {\n                return Effect.void\n              }\n              return encode(\"set\", key, value).pipe(\n                Effect.flatMap((encoded) =>\n                  storage.set(makeKey(key), encoded, Duration.isFinite(ttl) ? Option.some(ttl) : Option.none())\n                )\n              )\n            },\n            setMany: Effect.fnUntraced(function*(entries) {\n              const encodedEntries = Arr.empty<readonly [string, unknown, Option.Option<Duration.Duration>]>()\n              for (const [key, value] of entries) {\n                const ttl = Duration.decode(timeToLive(key, value))\n                if (Duration.isZero(ttl)) continue\n                const encoded = yield* encode(\"setMany\", key, value)\n                encodedEntries.push([makeKey(key), encoded, Duration.isFinite(ttl) ? Option.some(ttl) : Option.none()])\n              }\n              if (encodedEntries.length === 0) return\n              return yield* storage.setMany(encodedEntries).pipe(\n                Effect.catchAll((error) => Effect.fail(PersistenceBackingError.make(\"setMany\", error)))\n              )\n            }),\n            remove: (key) => storage.remove(makeKey(key)),\n            clear: storage.clear\n          })\n        })\n    })\n  })\n)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerMemory: Layer.Layer<BackingPersistence> = Layer.sync(\n  BackingPersistence,\n  () => {\n    const stores = new Map<string, Map<string, readonly [unknown, expires: number | null]>>()\n    const getStore = (storeId: string) => {\n      let store = stores.get(storeId)\n      if (store === undefined) {\n        store = new Map<string, readonly [unknown, expires: number | null]>()\n        stores.set(storeId, store)\n      }\n      return store\n    }\n    return BackingPersistence.of({\n      [BackingPersistenceTypeId]: BackingPersistenceTypeId,\n      make: (storeId) =>\n        Effect.map(Effect.clock, (clock) => {\n          const map = getStore(storeId)\n          const unsafeGet = (key: string): Option.Option<unknown> => {\n            const value = map.get(key)\n            if (value === undefined) {\n              return Option.none()\n            } else if (value[1] !== null && value[1] <= clock.unsafeCurrentTimeMillis()) {\n              map.delete(key)\n              return Option.none()\n            }\n            return Option.some(value[0])\n          }\n          return identity<BackingPersistenceStore>({\n            get: (key) => Effect.sync(() => unsafeGet(key)),\n            getMany: (keys) => Effect.sync(() => keys.map(unsafeGet)),\n            set: (key, value, ttl) => Effect.sync(() => map.set(key, [value, unsafeTtlToExpires(clock, ttl)])),\n            setMany: (entries) =>\n              Effect.sync(() => {\n                for (const [key, value, ttl] of entries) {\n                  map.set(key, [value, unsafeTtlToExpires(clock, ttl)])\n                }\n              }),\n            remove: (key) => Effect.sync(() => map.delete(key)),\n            clear: Effect.sync(() => map.clear())\n          })\n        })\n    })\n  }\n)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerKeyValueStore: Layer.Layer<BackingPersistence, never, KeyValueStore.KeyValueStore> = Layer.effect(\n  BackingPersistence,\n  Effect.gen(function*() {\n    const backing = yield* KeyValueStore.KeyValueStore\n    return BackingPersistence.of({\n      [BackingPersistenceTypeId]: BackingPersistenceTypeId,\n      make: (storeId) =>\n        Effect.map(Effect.clock, (clock) => {\n          const store = KeyValueStore.prefix(backing, storeId)\n          const get = (method: string, key: string) =>\n            Effect.flatMap(\n              Effect.mapError(\n                store.get(key),\n                (error) => PersistenceBackingError.make(method, error)\n              ),\n              Option.match({\n                onNone: () => Effect.succeedNone,\n                onSome: (s) =>\n                  Effect.flatMap(\n                    Effect.try({\n                      try: () => JSON.parse(s),\n                      catch: (error) => PersistenceBackingError.make(method, error)\n                    }),\n                    (_) => {\n                      if (!Array.isArray(_)) return Effect.succeedNone\n                      const [value, expires] = _ as [unknown, number | null]\n                      if (expires !== null && expires <= clock.unsafeCurrentTimeMillis()) {\n                        return Effect.as(Effect.ignore(store.remove(key)), Option.none())\n                      }\n                      return Effect.succeed(Option.some(value))\n                    }\n                  )\n              })\n            )\n          return identity<BackingPersistenceStore>({\n            get: (key) => get(\"get\", key),\n            getMany: (keys) => Effect.forEach(keys, (key) => get(\"getMany\", key), { concurrency: \"unbounded\" }),\n            set: (key, value, ttl) =>\n              Effect.flatMap(\n                Effect.try({\n                  try: () => JSON.stringify([value, unsafeTtlToExpires(clock, ttl)]),\n                  catch: (error) => PersistenceBackingError.make(\"set\", error)\n                }),\n                (u) =>\n                  Effect.mapError(\n                    store.set(key, u),\n                    (error) => PersistenceBackingError.make(\"set\", error)\n                  )\n              ),\n            setMany: (entries) =>\n              Effect.forEach(entries, ([key, value, ttl]) => {\n                const expires = unsafeTtlToExpires(clock, ttl)\n                if (expires === null) return Effect.void\n                const encoded = JSON.stringify([value, expires])\n                return store.set(key, encoded)\n              }, { concurrency: \"unbounded\", discard: true }).pipe(\n                Effect.mapError((error) => PersistenceBackingError.make(\"setMany\", error))\n              ),\n            remove: (key) =>\n              Effect.mapError(\n                store.remove(key),\n                (error) => PersistenceBackingError.make(\"remove\", error)\n              ),\n            clear: Effect.mapError(store.clear, (error) => PersistenceBackingError.make(\"clear\", error))\n          })\n        })\n    })\n  })\n)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerResultMemory: Layer.Layer<ResultPersistence> = layerResult.pipe(\n  Layer.provide(layerMemory)\n)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerResultKeyValueStore: Layer.Layer<ResultPersistence, never, KeyValueStore.KeyValueStore> = layerResult\n  .pipe(\n    Layer.provide(layerKeyValueStore)\n  )\n\n/**\n * @since 1.0.0\n */\nexport const unsafeTtlToExpires = (clock: Clock.Clock, ttl: Option.Option<Duration.Duration>): number | null =>\n  ttl._tag === \"None\" ? null : clock.unsafeCurrentTimeMillis() + Duration.toMillis(ttl.value)\n"
  },
  {
    "path": "packages/experimental/src/RateLimiter/Redis.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Config from \"effect/Config\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport type { RedisOptions } from \"ioredis\"\nimport { Redis } from \"ioredis\"\nimport * as RateLimiter from \"../RateLimiter.js\"\n\ninterface RedisWithRateLimiting extends Redis {\n  fixedWindow(key: string, tokens: number, refillMillis: number, limit?: number): Promise<[number, number]>\n  tokenBucket(\n    key: string,\n    tokens: number,\n    refillMillis: number,\n    limit: number,\n    now: number,\n    overflow: 0 | 1\n  ): Promise<number>\n}\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = Effect.fnUntraced(function*(\n  options: RedisOptions & {\n    readonly prefix?: string | undefined\n  }\n) {\n  const prefix = options.prefix ?? \"ratelimiter:\"\n  const redis = yield* Effect.acquireRelease(\n    Effect.sync(() => new Redis(options) as RedisWithRateLimiting),\n    (redis) => Effect.promise(() => redis.quit())\n  )\n\n  redis.defineCommand(\"fixedWindow\", {\n    lua: `\nlocal key = KEYS[1]\nlocal tokens = tonumber(ARGV[1])\nlocal refillms = tonumber(ARGV[2])\nlocal limit = tonumber(ARGV[3])\nlocal current = tonumber(redis.call(\"GET\", key))\n\nif not current then\n  local nextpttl = refillms * tokens\n  redis.call(\"SET\", key, tokens, \"PX\", nextpttl)\n  return { tokens, nextpttl }\nend\n\nlocal currentpttl = tonumber(redis.call(\"PTTL\", key) or \"0\")\nlocal next = current + tokens\nif limit and next > limit then\n  return { next, currentpttl }\nend\n\nlocal nextpttl = currentpttl + (refillms * tokens)\nredis.call(\"SET\", key, next, \"PX\", nextpttl)\nreturn { next, nextpttl }\n`,\n    numberOfKeys: 1,\n    readOnly: false\n  })\n\n  redis.defineCommand(\"tokenBucket\", {\n    lua: `\nlocal key = KEYS[1]\nlocal last_refill_key = key .. \":refill\"\nlocal tokens = tonumber(ARGV[1])\nlocal refill_ms = tonumber(ARGV[2])\nlocal limit = tonumber(ARGV[3])\nlocal now = tonumber(ARGV[4])\nlocal overflow = ARGV[5] == \"1\"\nlocal current = tonumber(redis.call(\"GET\", key))\nlocal last_refill = tonumber(redis.call(\"GET\", last_refill_key))\n\nif not current then\n  current = limit\n  last_refill = now\n  redis.call(\"SET\", key, current)\n  redis.call(\"SET\", last_refill_key, last_refill)\nend\n\nlocal elapsed = now - last_refill\nlocal refill_amount = math.floor(elapsed / refill_ms)\nif refill_amount > 0 then\n  current = math.min(current + refill_amount, limit)\n  last_refill = last_refill + (refill_amount * refill_ms)\n  redis.call(\"SET\", last_refill_key, last_refill)\nend\n\nlocal next = current - tokens\nif next < 0 and not overflow then\n  redis.call(\"SET\", key, current)\n  return next\nend\n\nredis.call(\"SET\", key, next)\nreturn next\n`,\n    numberOfKeys: 1,\n    readOnly: false\n  })\n\n  return RateLimiter.RateLimiterStore.of({\n    fixedWindow(options) {\n      const key = `${prefix}${options.key}`\n      const refillMillis = Duration.toMillis(options.refillRate)\n      return Effect.tryPromise({\n        try: () => redis.fixedWindow(key, options.tokens, refillMillis, options.limit),\n        catch: (cause) =>\n          new RateLimiter.RateLimitStoreError({\n            message: `Failed to execute fixedWindow rate limiting command`,\n            cause\n          })\n      })\n    },\n    tokenBucket(options) {\n      const key = `${prefix}${options.key}`\n      const refillMillis = Duration.toMillis(options.refillRate)\n      return Effect.clockWith((clock) =>\n        Effect.tryPromise({\n          try: () =>\n            redis.tokenBucket(\n              key,\n              options.tokens,\n              refillMillis,\n              options.limit,\n              clock.unsafeCurrentTimeMillis(),\n              options.allowOverflow ? 1 : 0\n            ),\n          catch: (cause) =>\n            new RateLimiter.RateLimitStoreError({\n              message: `Failed to execute tokenBucket rate limiting command`,\n              cause\n            })\n        })\n      )\n    }\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerStore = (options: RedisOptions & { readonly prefix?: string | undefined }) =>\n  Layer.scoped(RateLimiter.RateLimiterStore, make(options))\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layerStoreConfig = (\n  options: Config.Config.Wrap<RedisOptions & { readonly prefix?: string | undefined }>\n) => Layer.scoped(RateLimiter.RateLimiterStore, Effect.flatMap(Config.unwrap(options), make))\n"
  },
  {
    "path": "packages/experimental/src/RateLimiter.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\n\n/**\n * @since 1.0.0\n * @category Type IDs\n */\nexport const TypeId: TypeId = \"~@effect/experimental/RateLimiter\"\n\n/**\n * @since 1.0.0\n * @category Type IDs\n */\nexport type TypeId = \"~@effect/experimental/RateLimiter\"\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface RateLimiter {\n  readonly [TypeId]: TypeId\n\n  readonly consume: (options: {\n    readonly algorithm?: \"fixed-window\" | \"token-bucket\" | undefined\n    readonly onExceeded?: \"delay\" | \"fail\" | undefined\n    readonly window: Duration.DurationInput\n    readonly limit: number\n    readonly key: string\n    readonly tokens?: number | undefined\n  }) => Effect.Effect<ConsumeResult, RateLimiterError>\n}\n\n/**\n * @since 1.0.0\n * @category Tags\n */\nexport const RateLimiter: Context.Tag<RateLimiter, RateLimiter> = Context.GenericTag<RateLimiter>(TypeId)\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make: Effect.Effect<\n  RateLimiter,\n  never,\n  RateLimiterStore\n> = Effect.gen(function*() {\n  const store = yield* RateLimiterStore\n\n  return identity<RateLimiter>({\n    [TypeId]: TypeId,\n    consume(options) {\n      const tokens = options.tokens ?? 1\n      const onExceeded = options.onExceeded ?? \"fail\"\n      const algorithm = options.algorithm ?? \"fixed-window\"\n      const window = Duration.decode(options.window)\n      const windowMillis = Duration.toMillis(window)\n      const refillRate = Duration.unsafeDivide(window, options.limit)\n      const refillRateMillis = Duration.toMillis(refillRate)\n\n      if (tokens > options.limit) {\n        return onExceeded === \"fail\"\n          ? Effect.fail(\n            new RateLimitExceeded({\n              key: options.key,\n              retryAfter: window,\n              limit: options.limit,\n              remaining: 0\n            })\n          )\n          : Effect.succeed<ConsumeResult>({\n            delay: window,\n            limit: options.limit,\n            remaining: 0,\n            resetAfter: window\n          })\n      }\n\n      if (algorithm === \"fixed-window\") {\n        return Effect.flatMap(\n          store.fixedWindow({\n            key: options.key,\n            tokens,\n            refillRate,\n            limit: onExceeded === \"fail\" ? options.limit : undefined\n          }),\n          ([count, ttl]) => {\n            if (onExceeded === \"fail\") {\n              const remaining = options.limit - count\n              if (remaining < 0) {\n                return Effect.fail(\n                  new RateLimitExceeded({\n                    key: options.key,\n                    retryAfter: Duration.millis(ttl),\n                    limit: options.limit,\n                    remaining: 0\n                  })\n                )\n              }\n              return Effect.succeed<ConsumeResult>({\n                delay: Duration.zero,\n                limit: options.limit,\n                remaining,\n                resetAfter: Duration.millis(ttl)\n              })\n            }\n            const ttlTotal = count * refillRateMillis\n            const elapsed = ttlTotal - ttl\n            const windowNumber = Math.floor((count - 1) / options.limit)\n            const remaining = (windowNumber * windowMillis) - elapsed\n            const delay = remaining <= 0 ? Duration.zero : Duration.millis(remaining)\n            return Effect.succeed<ConsumeResult>({\n              delay,\n              limit: options.limit,\n              remaining: options.limit - count,\n              resetAfter: Duration.times(window, Math.ceil(ttl / windowMillis))\n            })\n          }\n        )\n      }\n\n      return Effect.flatMap(\n        store.tokenBucket({\n          key: options.key,\n          tokens,\n          limit: options.limit,\n          refillRate,\n          allowOverflow: onExceeded === \"delay\"\n        }),\n        (remaining) => {\n          if (onExceeded === \"fail\") {\n            if (remaining < 0) {\n              return Effect.fail(\n                new RateLimitExceeded({\n                  key: options.key,\n                  retryAfter: Duration.times(refillRate, -remaining),\n                  limit: options.limit,\n                  remaining: 0\n                })\n              )\n            }\n            return Effect.succeed<ConsumeResult>({\n              delay: Duration.zero,\n              limit: options.limit,\n              remaining,\n              resetAfter: Duration.times(refillRate, options.limit - remaining)\n            })\n          }\n          if (remaining >= 0) {\n            return Effect.succeed<ConsumeResult>({\n              delay: Duration.zero,\n              limit: options.limit,\n              remaining,\n              resetAfter: Duration.times(refillRate, options.limit - remaining)\n            })\n          }\n          return Effect.succeed<ConsumeResult>({\n            delay: Duration.times(refillRate, -remaining),\n            limit: options.limit,\n            remaining,\n            resetAfter: Duration.times(refillRate, options.limit - remaining)\n          })\n        }\n      )\n    }\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer: Layer.Layer<\n  RateLimiter,\n  never,\n  RateLimiterStore\n> = Layer.effect(RateLimiter, make)\n\n/**\n * Access a function that applies rate limiting to an effect.\n *\n * ```ts\n * import { RateLimiter } from \"@effect/experimental\"\n * import { Effect } from \"effect\"\n *\n * Effect.gen(function*() {\n *   // Access the `withLimiter` function from the RateLimiter module\n *   const withLimiter = yield* RateLimiter.makeWithRateLimiter\n *\n *   // Apply a rate limiter to an effect\n *   yield* Effect.log(\"Making a request with rate limiting\").pipe(\n *     withLimiter({\n *       key: \"some-key\",\n *       limit: 10,\n *       onExceeded: \"delay\",\n *       window: \"5 seconds\",\n *       algorithm: \"fixed-window\"\n *     })\n *   )\n * })\n * ```\n *\n * @since 1.0.0\n * @category Accessors\n */\nexport const makeWithRateLimiter: Effect.Effect<\n  ((options: {\n    readonly algorithm?: \"fixed-window\" | \"token-bucket\" | undefined\n    readonly onExceeded?: \"delay\" | \"fail\" | undefined\n    readonly window: Duration.DurationInput\n    readonly limit: number\n    readonly key: string\n    readonly tokens?: number | undefined\n  }) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E | RateLimiterError, R>),\n  never,\n  RateLimiter\n> = Effect.map(\n  RateLimiter,\n  (limiter) => (options) => (effect) =>\n    Effect.flatMap(limiter.consume(options), ({ delay }) => {\n      if (Duration.isZero(delay)) return effect\n      return Effect.delay(effect, delay)\n    })\n)\n\n/**\n * Access a function that sleeps when the rate limit is exceeded.\n *\n * ```ts\n * import { RateLimiter } from \"@effect/experimental\"\n * import { Effect } from \"effect\"\n *\n * export default Effect.gen(function*() {\n *   // Access the `sleep` function from the RateLimiter module\n *   const sleep = yield* RateLimiter.makeSleep\n *\n *   // Use the `sleep` function with specific rate limiting parameters.\n *   // This will only sleep if the rate limit has been exceeded.\n *   yield* sleep({\n *     key: \"some-key\",\n *     limit: 10,\n *     window: \"5 seconds\",\n *     algorithm: \"fixed-window\"\n *   })\n * })\n * ```\n *\n * @since 1.0.0\n * @category Accessors\n */\nexport const makeSleep: Effect.Effect<\n  ((options: {\n    readonly algorithm?: \"fixed-window\" | \"token-bucket\" | undefined\n    readonly window: Duration.DurationInput\n    readonly limit: number\n    readonly key: string\n    readonly tokens?: number | undefined\n  }) => Effect.Effect<ConsumeResult, RateLimitStoreError>),\n  never,\n  RateLimiter\n> = Effect.map(\n  RateLimiter,\n  (limiter) => (options) =>\n    Effect.flatMap(\n      limiter.consume({\n        ...options,\n        onExceeded: \"delay\"\n      }) as Effect.Effect<ConsumeResult, RateLimitStoreError>,\n      (result) => {\n        if (Duration.isZero(result.delay)) return Effect.succeed(result)\n        return Effect.as(Effect.sleep(result.delay), result)\n      }\n    )\n)\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport const ErrorTypeId: ErrorTypeId = \"~@effect/experimental/RateLimiter/RateLimiterError\"\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport type ErrorTypeId = \"~@effect/experimental/RateLimiter/RateLimiterError\"\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport class RateLimitExceeded extends Schema.TaggedError<RateLimitExceeded>(\n  \"@effect/experimental/RateLimiter/RateLimitExceeded\"\n)(\"RateLimiterError\", {\n  retryAfter: Schema.DurationFromMillis,\n  key: Schema.String,\n  limit: Schema.Number,\n  remaining: Schema.Number\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId\n\n  /**\n   * @since 1.0.0\n   */\n  readonly reason = \"Exceeded\"\n\n  /**\n   * @since 1.0.0\n   */\n  get message(): string {\n    return `Rate limit exceeded`\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport class RateLimitStoreError extends Schema.TaggedError<RateLimitStoreError>(\n  \"@effect/experimental/RateLimiter/RateLimitStoreError\"\n)(\"RateLimiterError\", {\n  message: Schema.String,\n  cause: Schema.optional(Schema.Defect)\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId\n\n  /**\n   * @since 1.0.0\n   */\n  readonly reason = \"StoreError\"\n}\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport const RateLimiterError = Schema.Union(RateLimitExceeded, RateLimitStoreError)\n\n/**\n * @since 1.0.0\n * @category Errors\n */\nexport type RateLimiterError = RateLimitExceeded | RateLimitStoreError\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface ConsumeResult {\n  /**\n   * The amount of delay to wait before making the next request, when the rate\n   * limiter is using the \"delay\" `onExceeded` strategy.\n   *\n   * It will be Duration.zero if the request is allowed immediately.\n   */\n  readonly delay: Duration.Duration\n\n  /**\n   * The maximum number of requests allowed in the current window.\n   */\n  readonly limit: number\n\n  /**\n   * The number of remaining requests in the current window.\n   */\n  readonly remaining: number\n\n  /**\n   * The time until the rate limit fully resets.\n   */\n  readonly resetAfter: Duration.Duration\n}\n\n/**\n * @since 1.0.0\n * @category RateLimiterStore\n */\nexport class RateLimiterStore extends Context.Tag(\"@effect/experimental/RateLimiter/RateLimiterStore\")<\n  RateLimiterStore,\n  {\n    /**\n     * Returns the token count *after* taking the specified `tokens` and time to\n     * live for the `key`.\n     *\n     * If `limit` is provided, the number of taken tokens will be capped at the\n     * limit.\n     *\n     * In the case the limit is exceeded, the returned count will be greater\n     * than the limit, but the TTL will not be updated.\n     */\n    readonly fixedWindow: (options: {\n      readonly key: string\n      readonly tokens: number\n      readonly refillRate: Duration.Duration\n      readonly limit: number | undefined\n    }) => Effect.Effect<readonly [count: number, ttl: number], RateLimiterError>\n\n    /**\n     * Returns the current remaining tokens for the `key` after consuming the\n     * specified amount of tokens.\n     *\n     * If `allowOverflow` is true, the number of tokens can drop below zero.\n     *\n     * In the case of no overflow, the returned token count will only be\n     * negative if the requested tokens exceed the available tokens, but the\n     * real token count will not be persisted below zero.\n     */\n    readonly tokenBucket: (options: {\n      readonly key: string\n      readonly tokens: number\n      readonly limit: number\n      readonly refillRate: Duration.Duration\n      readonly allowOverflow: boolean\n    }) => Effect.Effect<number, RateLimiterError>\n  }\n>() {}\n\n/**\n * @since 1.0.0\n * @category RateLimiterStore\n */\nexport const layerStoreMemory: Layer.Layer<\n  RateLimiterStore\n> = Layer.sync(RateLimiterStore, () => {\n  const fixedCounters = new Map<string, { count: number; expiresAt: number }>()\n  const tokenBuckets = new Map<string, { tokens: number; lastRefill: number }>()\n\n  return RateLimiterStore.of({\n    fixedWindow: (options) =>\n      Effect.clockWith((clock) =>\n        Effect.sync(() => {\n          const refillRateMillis = Duration.toMillis(options.refillRate)\n          const now = clock.unsafeCurrentTimeMillis()\n          let counter = fixedCounters.get(options.key)\n          if (!counter || counter.expiresAt <= now) {\n            counter = { count: 0, expiresAt: now }\n            fixedCounters.set(options.key, counter)\n          }\n          if (options.limit && counter.count + options.tokens > options.limit) {\n            return [counter.count + options.tokens, counter.expiresAt - now] as const\n          }\n          counter.count += options.tokens\n          counter.expiresAt += refillRateMillis * options.tokens\n          return [counter.count, counter.expiresAt - now] as const\n        })\n      ),\n    tokenBucket: (options) =>\n      Effect.clockWith((clock) =>\n        Effect.sync(() => {\n          const refillRateMillis = Duration.toMillis(options.refillRate)\n          const now = clock.unsafeCurrentTimeMillis()\n          let bucket = tokenBuckets.get(options.key)\n          if (!bucket) {\n            bucket = { tokens: options.limit, lastRefill: now }\n            tokenBuckets.set(options.key, bucket)\n          } else {\n            const elapsed = now - bucket.lastRefill\n            const tokensToAdd = Math.floor(elapsed / refillRateMillis)\n            if (tokensToAdd > 0) {\n              bucket.tokens = Math.min(options.limit, bucket.tokens + tokensToAdd)\n              bucket.lastRefill += tokensToAdd * refillRateMillis\n            }\n          }\n\n          const newTokenCount = bucket.tokens - options.tokens\n          if (options.allowOverflow || newTokenCount >= 0) {\n            bucket.tokens = newTokenCount\n          }\n          return newTokenCount\n        })\n      )\n  })\n})\n"
  },
  {
    "path": "packages/experimental/src/Reactivity.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as FiberHandle from \"effect/FiberHandle\"\nimport { dual } from \"effect/Function\"\nimport * as Hash from \"effect/Hash\"\nimport * as Layer from \"effect/Layer\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport type { ReadonlyRecord } from \"effect/Record\"\nimport * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport class Reactivity extends Context.Tag(\"@effect/experimental/Reactivity\")<\n  Reactivity,\n  Reactivity.Service\n>() {}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = Effect.sync(() => {\n  const handlers = new Map<number | string, Set<() => void>>()\n\n  const unsafeInvalidate = (keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>): void => {\n    if (Array.isArray(keys)) {\n      for (let i = 0; i < keys.length; i++) {\n        const set = handlers.get(stringOrHash(keys[i]))\n        if (set === undefined) continue\n        for (const run of set) run()\n      }\n    } else {\n      const record = keys as ReadonlyRecord<string, Array<unknown>>\n      for (const key in record) {\n        const hashes = idHashes(key, record[key])\n        for (let i = 0; i < hashes.length; i++) {\n          const set = handlers.get(hashes[i])\n          if (set === undefined) continue\n          for (const run of set) run()\n        }\n\n        const set = handlers.get(key)\n        if (set !== undefined) {\n          for (const run of set) run()\n        }\n      }\n    }\n  }\n\n  const invalidate = (\n    keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n  ): Effect.Effect<void> => Effect.sync(() => unsafeInvalidate(keys))\n\n  const mutation = <A, E, R>(\n    keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>,\n    effect: Effect.Effect<A, E, R>\n  ): Effect.Effect<A, E, R> => Effect.zipLeft(effect, invalidate(keys))\n\n  const unsafeRegister = (\n    keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>,\n    handler: () => void\n  ): () => void => {\n    const resolvedKeys = Array.isArray(keys) ? keys.map(stringOrHash) : recordHashes(keys as any)\n    for (let i = 0; i < resolvedKeys.length; i++) {\n      let set = handlers.get(resolvedKeys[i])\n      if (set === undefined) {\n        set = new Set()\n        handlers.set(resolvedKeys[i], set)\n      }\n      set.add(handler)\n    }\n    return () => {\n      for (let i = 0; i < resolvedKeys.length; i++) {\n        const set = handlers.get(resolvedKeys[i])!\n        set.delete(handler)\n        if (set.size === 0) {\n          handlers.delete(resolvedKeys[i])\n        }\n      }\n    }\n  }\n\n  const query = <A, E, R>(\n    keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>,\n    effect: Effect.Effect<A, E, R>\n  ): Effect.Effect<Mailbox.ReadonlyMailbox<A, E>, never, R | Scope.Scope> =>\n    Effect.gen(function*() {\n      const scope = yield* Effect.scope\n      const results = yield* Mailbox.make<A, E>()\n      const runFork = yield* FiberHandle.makeRuntime<R>()\n\n      let running = false\n      let pending = false\n      const handleExit = (exit: Exit.Exit<A, E>) => {\n        if (exit._tag === \"Failure\") {\n          results.unsafeDone(Exit.failCause(exit.cause))\n        } else {\n          results.unsafeOffer(exit.value)\n        }\n        if (pending) {\n          pending = false\n          runFork(effect).addObserver(handleExit)\n        } else {\n          running = false\n        }\n      }\n\n      function run() {\n        if (running) {\n          pending = true\n          return\n        }\n        running = true\n        runFork(effect).addObserver(handleExit)\n      }\n\n      const cancel = unsafeRegister(keys, run)\n      yield* Scope.addFinalizer(scope, Effect.sync(cancel))\n      run()\n\n      return results as Mailbox.ReadonlyMailbox<A, E>\n    })\n\n  const stream = <A, E, R>(\n    tables: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>,\n    effect: Effect.Effect<A, E, R>\n  ): Stream.Stream<A, E, Exclude<R, Scope.Scope>> =>\n    query(tables, effect).pipe(\n      Effect.map(Mailbox.toStream),\n      Stream.unwrapScoped\n    )\n\n  return Reactivity.of({ mutation, query, stream, unsafeInvalidate, invalidate, unsafeRegister })\n})\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const mutation: {\n  (\n    keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n  ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R | Reactivity>\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n  ): Effect.Effect<A, E, R | Reactivity>\n} = dual(2, <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n  keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n): Effect.Effect<A, E, R | Reactivity> => Effect.flatMap(Reactivity, (r) => r.mutation(keys, effect)))\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const query: {\n  (\n    keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n  ): <A, E, R>(\n    effect: Effect.Effect<A, E, R>\n  ) => Effect.Effect<Mailbox.ReadonlyMailbox<A, E>, never, R | Scope.Scope | Reactivity>\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n  ): Effect.Effect<Mailbox.ReadonlyMailbox<A, E>, never, R | Scope.Scope | Reactivity>\n} = dual(2, <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n  keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n): Effect.Effect<Mailbox.ReadonlyMailbox<A, E>, never, R | Scope.Scope | Reactivity> =>\n  Effect.flatMap(Reactivity, (r) => r.query(keys, effect)))\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const stream: {\n  (\n    keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n  ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Stream.Stream<A, E, Exclude<R, Scope.Scope> | Reactivity>\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n  ): Stream.Stream<A, E, Exclude<R, Scope.Scope> | Reactivity>\n} = dual(2, <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n  keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n): Stream.Stream<A, E, Exclude<R, Scope.Scope> | Reactivity> =>\n  Reactivity.pipe(\n    Effect.flatMap((r) => r.query(keys, effect)),\n    Effect.map(Mailbox.toStream),\n    Stream.unwrapScoped\n  ))\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const invalidate = (\n  keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n): Effect.Effect<void, never, Reactivity> => Effect.flatMap(Reactivity, (r) => r.invalidate(keys))\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer.Layer<Reactivity> = Layer.scoped(Reactivity, make)\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport declare namespace Reactivity {\n  /**\n   * @since 1.0.0\n   * @category model\n   */\n  export interface Service {\n    readonly unsafeInvalidate: (keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>) => void\n    readonly unsafeRegister: (\n      keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>,\n      handler: () => void\n    ) => () => void\n    readonly invalidate: (\n      keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>\n    ) => Effect.Effect<void>\n    readonly mutation: <A, E, R>(\n      keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>,\n      effect: Effect.Effect<A, E, R>\n    ) => Effect.Effect<A, E, R>\n    readonly query: <A, E, R>(\n      keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>,\n      effect: Effect.Effect<A, E, R>\n    ) => Effect.Effect<Mailbox.ReadonlyMailbox<A, E>, never, R | Scope.Scope>\n    readonly stream: <A, E, R>(\n      keys: ReadonlyArray<unknown> | ReadonlyRecord<string, ReadonlyArray<unknown>>,\n      effect: Effect.Effect<A, E, R>\n    ) => Stream.Stream<A, E, Exclude<R, Scope.Scope>>\n  }\n}\n\nfunction stringOrHash(u: unknown): string | number {\n  return typeof u === \"string\" ? u : Hash.hash(u)\n}\n\nconst idHashes = (keyHash: number | string, ids: ReadonlyArray<unknown>): ReadonlyArray<string> => {\n  const hashes: Array<string> = new Array(ids.length)\n  for (let i = 0; i < ids.length; i++) {\n    hashes[i] = `${keyHash}:${stringOrHash(ids[i])}`\n  }\n  return hashes\n}\n\nconst recordHashes = (record: ReadonlyRecord<string, ReadonlyArray<unknown>>): ReadonlyArray<string> => {\n  const hashes: Array<string> = []\n  for (const key in record) {\n    hashes.push(key)\n    for (const idHash of idHashes(key, record[key])) {\n      hashes.push(idHash)\n    }\n  }\n  return hashes\n}\n"
  },
  {
    "path": "packages/experimental/src/RequestResolver.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Arr from \"effect/Array\"\nimport type * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Either from \"effect/Either\"\nimport * as Fiber from \"effect/Fiber\"\nimport { dual, pipe } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Request from \"effect/Request\"\nimport * as RequestResolver from \"effect/RequestResolver\"\nimport * as Runtime from \"effect/Runtime\"\nimport type * as Schema from \"effect/Schema\"\nimport * as Scope from \"effect/Scope\"\nimport * as Persistence from \"./Persistence.js\"\n\ninterface DataLoaderItem<A extends Request.Request<any, any>> {\n  readonly request: A\n  readonly resume: (effect: Effect.Effect<Request.Request.Success<A>, Request.Request.Error<A>>) => void\n}\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const dataLoader = dual<\n  (options: {\n    readonly window: Duration.DurationInput\n    readonly maxBatchSize?: number\n  }) => <A extends Request.Request<any, any>>(\n    self: RequestResolver.RequestResolver<A, never>\n  ) => Effect.Effect<RequestResolver.RequestResolver<A, never>, never, Scope.Scope>,\n  <A extends Request.Request<any, any>>(\n    self: RequestResolver.RequestResolver<A, never>,\n    options: {\n      readonly window: Duration.DurationInput\n      readonly maxBatchSize?: number\n    }\n  ) => Effect.Effect<RequestResolver.RequestResolver<A, never>, never, Scope.Scope>\n>(\n  2,\n  Effect.fnUntraced(function*<\n    A extends Request.Request<any, any>\n  >(self: RequestResolver.RequestResolver<A, never>, options: {\n    readonly window: Duration.DurationInput\n    readonly maxBatchSize?: number\n  }) {\n    const maxSize = options.maxBatchSize ?? Infinity\n    const scope = yield* Effect.scope\n    const runtime = yield* Effect.runtime<never>().pipe(\n      Effect.interruptible\n    )\n    const runFork = Runtime.runFork(runtime)\n\n    let batch = new Set<DataLoaderItem<A>>()\n    const process = (items: Iterable<DataLoaderItem<A>>) =>\n      Effect.withRequestCaching(\n        Effect.forEach(\n          items,\n          ({ request, resume }) =>\n            Effect.request(request, self).pipe(\n              Effect.exit,\n              Effect.map(resume)\n            ),\n          { batching: true, discard: true }\n        ),\n        false\n      )\n    const delayedProcess = Effect.sleep(options.window).pipe(\n      Effect.flatMap(() => {\n        const currentBatch = batch\n        batch = new Set()\n        fiber = undefined\n        return process(currentBatch)\n      })\n    )\n\n    let fiber: Fiber.RuntimeFiber<void> | undefined\n    yield* Scope.addFinalizer(scope, Effect.suspend(() => fiber ? Fiber.interrupt(fiber) : Effect.void))\n\n    return RequestResolver.fromEffect((request: A) =>\n      Effect.async<Request.Request.Success<A>, Request.Request.Error<A>>((resume) => {\n        const item: DataLoaderItem<A> = { request, resume }\n        batch.add(item)\n        if (batch.size >= maxSize) {\n          const currentBatch = batch\n          batch = new Set()\n          if (fiber) {\n            const parent = Option.getOrThrow(Fiber.getCurrentFiber())\n            fiber.unsafeInterruptAsFork(parent.id())\n            fiber = undefined\n          }\n          runFork(process(currentBatch))\n        } else if (!fiber) {\n          fiber = runFork(delayedProcess)\n        }\n\n        return Effect.sync(() => {\n          batch.delete(item)\n        })\n      })\n    )\n  })\n)\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport interface PersistedRequest<R, IE, E, IA, A> extends Request.Request<A, E>, Schema.WithResult<A, IA, E, IE, R> {}\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport declare namespace PersistedRequest {\n  /**\n   * @since 1.0.0\n   * @category model\n   */\n  export type Any = PersistedRequest<any, any, any, any, any> | PersistedRequest<any, never, never, any, any>\n}\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const persisted: {\n  <Req extends PersistedRequest.Any>(options: {\n    readonly storeId: string\n    readonly timeToLive: (...args: Persistence.ResultPersistence.TimeToLiveArgs<Req>) => Duration.DurationInput\n  }): (\n    self: RequestResolver.RequestResolver<Req, never>\n  ) => Effect.Effect<\n    RequestResolver.RequestResolver<Req, Schema.WithResult.Context<Req>>,\n    never,\n    Persistence.ResultPersistence | Scope.Scope\n  >\n  <Req extends PersistedRequest.Any>(\n    self: RequestResolver.RequestResolver<Req, never>,\n    options: {\n      readonly storeId: string\n      readonly timeToLive: (...args: Persistence.ResultPersistence.TimeToLiveArgs<Req>) => Duration.DurationInput\n    }\n  ): Effect.Effect<\n    RequestResolver.RequestResolver<Req, Schema.WithResult.Context<Req>>,\n    never,\n    Persistence.ResultPersistence | Scope.Scope\n  >\n} = dual(2, <Req extends PersistedRequest.Any>(\n  self: RequestResolver.RequestResolver<Req, never>,\n  options: {\n    readonly storeId: string\n    readonly timeToLive: (...args: Persistence.ResultPersistence.TimeToLiveArgs<Req>) => Duration.DurationInput\n  }\n): Effect.Effect<\n  RequestResolver.RequestResolver<Req, Schema.WithResult.Context<Req>>,\n  never,\n  Persistence.ResultPersistence | Scope.Scope\n> =>\n  Effect.gen(function*() {\n    const storage = yield* (yield* Persistence.ResultPersistence).make({\n      storeId: options.storeId,\n      timeToLive: options.timeToLive as any\n    })\n\n    const partition = (requests: ReadonlyArray<Req>) =>\n      storage.getMany(requests as any).pipe(\n        Effect.map(\n          Arr.partitionMap((_, i) =>\n            Option.match(_, {\n              onNone: () => Either.left(requests[i]),\n              onSome: (_) => Either.right([requests[i], _] as const)\n            })\n          )\n        ),\n        Effect.orElseSucceed(() => [requests, []] as const)\n      )\n\n    const set = (\n      request: Req,\n      result: Request.Request.Result<Req>\n    ): Effect.Effect<void, never, any> => Effect.ignoreLogged(storage.set(request as any, result))\n\n    return RequestResolver.makeBatched((requests: Arr.NonEmptyArray<Req>) =>\n      Effect.flatMap(partition(requests), ([remaining, results]) => {\n        const completeCached = Effect.forEach(\n          results,\n          ([request, result]) => Request.complete(request, result as any) as Effect.Effect<void>,\n          { discard: true }\n        )\n        const completeUncached = pipe(\n          Effect.forEach(\n            remaining,\n            (request) => Effect.exit(Effect.request(request, self)),\n            { batching: true }\n          ),\n          Effect.flatMap((results) =>\n            Effect.forEach(\n              results,\n              (result, i) => {\n                const request = remaining[i]\n                return Effect.zipRight(\n                  set(request, result as any),\n                  Request.complete(request, result as any)\n                )\n              },\n              { discard: true }\n            )\n          ),\n          Effect.withRequestCaching(false)\n        )\n        return Effect.zipRight(completeCached, completeUncached)\n      })\n    )\n  }))\n"
  },
  {
    "path": "packages/experimental/src/Sse.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Channel from \"effect/Channel\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Data from \"effect/Data\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Mailbox from \"effect/Mailbox\"\nimport { hasProperty } from \"effect/Predicate\"\nimport type * as AsyncInput from \"effect/SingleProducerAsyncInput\"\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeChannel = <IE, Done>(options?: {\n  readonly bufferSize?: number\n}): Channel.Channel<\n  Chunk.Chunk<Event>,\n  Chunk.Chunk<string>,\n  IE,\n  IE,\n  void,\n  Done\n> => {\n  const events = Mailbox.make<Event, IE | Retry>(options?.bufferSize ?? 16).pipe(\n    Effect.map((mailbox) => {\n      let events: Array<Event> = []\n      let retry: Retry | undefined\n      const parser = makeParser((event) => {\n        switch (event._tag) {\n          case \"Retry\":\n            return (retry = event)\n          case \"Event\":\n            return events.push(event)\n        }\n      })\n      const input: AsyncInput.AsyncInputProducer<\n        IE,\n        Chunk.Chunk<string>,\n        Done\n      > = {\n        awaitRead() {\n          return Effect.void\n        },\n        emit(chunks) {\n          Chunk.forEach(chunks, parser.feed)\n          const toEmit = events\n          events = []\n          return retry\n            ? Effect.zipRight(mailbox.offerAll(toEmit), mailbox.fail(retry))\n            : mailbox.offerAll(toEmit)\n        },\n        error(cause) {\n          return mailbox.failCause(cause)\n        },\n        done(_) {\n          return mailbox.end\n        }\n      }\n      return Channel.embedInput(Mailbox.toChannel(mailbox), input)\n    }),\n    Channel.unwrap\n  )\n\n  const withRetry: Channel.Channel<\n    Chunk.Chunk<Event>,\n    Chunk.Chunk<string>,\n    IE,\n    IE,\n    void,\n    Done\n  > = Channel.catchAll(events, (error) =>\n    Retry.is(error) ?\n      Effect.sleep(error.duration).pipe(\n        Effect.as(withRetry),\n        Channel.unwrap\n      ) :\n      Channel.fail(error))\n\n  return withRetry\n}\n\n/**\n * Create a SSE parser.\n *\n * Adapted from https://github.com/rexxars/eventsource-parser under MIT license.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport function makeParser(onParse: (event: AnyEvent) => void): Parser {\n  // Processing state\n  let isFirstChunk: boolean\n  let buffer: string\n  let startingPosition: number\n  let startingFieldLength: number\n\n  // Event state\n  let eventId: string | undefined\n  let lastEventId: string | undefined\n  let eventName: string | undefined\n  let data: string\n\n  reset()\n  return { feed, reset }\n\n  function reset(): void {\n    isFirstChunk = true\n    buffer = \"\"\n    startingPosition = 0\n    startingFieldLength = -1\n\n    eventId = undefined\n    eventName = undefined\n    data = \"\"\n  }\n\n  function feed(chunk: string): void {\n    buffer = buffer ? buffer + chunk : chunk\n\n    // Strip any UTF8 byte order mark (BOM) at the start of the stream.\n    // Note that we do not strip any non - UTF8 BOM, as eventsource streams are\n    // always decoded as UTF8 as per the specification.\n    if (isFirstChunk && hasBom(buffer)) {\n      buffer = buffer.slice(BOM.length)\n    }\n\n    isFirstChunk = false\n\n    // Set up chunk-specific processing state\n    const length = buffer.length\n    let position = 0\n    let discardTrailingNewline = false\n\n    // Read the current buffer byte by byte\n    while (position < length) {\n      // EventSource allows for carriage return + line feed, which means we\n      // need to ignore a linefeed character if the previous character was a\n      // carriage return\n      // @todo refactor to reduce nesting, consider checking previous byte?\n      // @todo but consider multiple chunks etc\n      if (discardTrailingNewline) {\n        if (buffer[position] === \"\\n\") {\n          ++position\n        }\n        discardTrailingNewline = false\n      }\n\n      let lineLength = -1\n      let fieldLength = startingFieldLength\n      let character: string\n\n      for (let index = startingPosition; lineLength < 0 && index < length; ++index) {\n        character = buffer[index]\n        if (character === \":\" && fieldLength < 0) {\n          fieldLength = index - position\n        } else if (character === \"\\r\") {\n          discardTrailingNewline = true\n          lineLength = index - position\n        } else if (character === \"\\n\") {\n          lineLength = index - position\n        }\n      }\n\n      if (lineLength < 0) {\n        startingPosition = length - position\n        startingFieldLength = fieldLength\n        break\n      } else {\n        startingPosition = 0\n        startingFieldLength = -1\n      }\n\n      parseEventStreamLine(buffer, position, fieldLength, lineLength)\n\n      position += lineLength + 1\n    }\n\n    if (position === length) {\n      // If we consumed the entire buffer to read the event, reset the buffer\n      buffer = \"\"\n    } else if (position > 0) {\n      // If there are bytes left to process, set the buffer to the unprocessed\n      // portion of the buffer only\n      buffer = buffer.slice(position)\n    }\n  }\n\n  function parseEventStreamLine(\n    lineBuffer: string,\n    index: number,\n    fieldLength: number,\n    lineLength: number\n  ) {\n    if (lineLength === 0) {\n      // We reached the last line of this event\n      if (data.length > 0) {\n        onParse({\n          _tag: \"Event\",\n          id: eventId,\n          event: eventName ?? \"message\",\n          data: data.slice(0, -1) // remove trailing newline\n        })\n        data = \"\"\n        eventId = undefined\n      }\n      eventName = undefined\n      return\n    }\n\n    const noValue = fieldLength < 0\n    const field = lineBuffer.slice(index, index + (noValue ? lineLength : fieldLength))\n    let step = 0\n\n    if (noValue) {\n      step = lineLength\n    } else if (lineBuffer[index + fieldLength + 1] === \" \") {\n      step = fieldLength + 2\n    } else {\n      step = fieldLength + 1\n    }\n\n    const position = index + step\n    const valueLength = lineLength - step\n    const value = lineBuffer.slice(position, position + valueLength).toString()\n\n    if (field === \"data\") {\n      data += value ? `${value}\\n` : \"\\n\"\n    } else if (field === \"event\") {\n      eventName = value\n    } else if (field === \"id\" && !value.includes(\"\\u0000\")) {\n      eventId = value\n      lastEventId = value\n    } else if (field === \"retry\") {\n      const retry = parseInt(value, 10)\n      if (!Number.isNaN(retry)) {\n        onParse(new Retry({ duration: Duration.millis(retry), lastEventId }))\n      }\n    }\n  }\n}\n\nconst BOM = [239, 187, 191]\n\nfunction hasBom(buffer: string) {\n  return BOM.every((charCode: number, index: number) => buffer.charCodeAt(index) === charCode)\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Parser {\n  feed(chunk: string): void\n  reset(): void\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Encoder {\n  write(event: AnyEvent): string\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Event {\n  readonly _tag: \"Event\"\n  readonly event: string\n  readonly id: string | undefined\n  readonly data: string\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface EventEncoded {\n  readonly event: string\n  readonly id: string | undefined\n  readonly data: string\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const RetryTypeId: unique symbol = Symbol.for(\"@effect/experimental/Sse/Retry\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type RetryTypeId = typeof RetryTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport class Retry extends Data.TaggedClass(\"Retry\")<{\n  readonly duration: Duration.Duration\n  readonly lastEventId: string | undefined\n}> {\n  /**\n   * @since 1.0.0\n   */\n  readonly [RetryTypeId]: RetryTypeId = RetryTypeId\n  /**\n   * @since 1.0.0\n   */\n  static is(u: unknown): u is Retry {\n    return hasProperty(u, RetryTypeId)\n  }\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type AnyEvent = Event | Retry\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const encoder: Encoder = {\n  write(event: AnyEvent): string {\n    switch (event._tag) {\n      case \"Event\": {\n        let data = \"\"\n        if (event.id !== undefined) {\n          data += `id: ${event.id}\\n`\n        }\n        if (event.event !== \"message\") {\n          data += `event: ${event.event}\\n`\n        }\n        if (event.data !== \"\") {\n          data += `data: ${event.data.replace(/\\n/g, \"\\ndata: \")}\\n`\n        }\n        return data + \"\\n\"\n      }\n      case \"Retry\": {\n        return `retry: ${Duration.toMillis(event.duration)}\\n\\n`\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "packages/experimental/src/VariantSchema.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { Brand } from \"effect/Brand\"\nimport type * as Effect from \"effect/Effect\"\nimport { constUndefined, dual } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as AST from \"effect/SchemaAST\"\nimport * as Struct_ from \"effect/Struct\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/experimental/VariantSchema\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\nconst cacheSymbol = Symbol.for(\"@effect/experimental/VariantSchema/cache\")\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Struct<in out A extends Field.Fields> extends Pipeable {\n  readonly [TypeId]: A\n  /** @internal */\n  [cacheSymbol]?: Record<string, Schema.Schema.All>\n}\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isStruct = (u: unknown): u is Struct<any> => Predicate.hasProperty(u, TypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace Struct {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Any = { readonly [TypeId]: any }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Fields = {\n    readonly [key: string]:\n      | Schema.Schema.All\n      | Schema.PropertySignature.All\n      | Field<any>\n      | Struct<any>\n      | undefined\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Validate<A, Variant extends string> = {\n    readonly [K in keyof A]: A[K] extends { readonly [TypeId]: infer _ } ? Validate<A[K], Variant> :\n      A[K] extends Field<infer Config> ? [keyof Config] extends [Variant] ? {} : \"field must have valid variants\"\n      : {}\n  }\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const FieldTypeId: unique symbol = Symbol.for(\n  \"@effect/experimental/VariantSchema/Field\"\n)\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type FieldTypeId = typeof FieldTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Field<in out A extends Field.Config> extends Pipeable {\n  readonly [FieldTypeId]: FieldTypeId\n  readonly schemas: A\n}\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isField = (u: unknown): u is Field<any> => Predicate.hasProperty(u, FieldTypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace Field {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Any = { readonly [FieldTypeId]: FieldTypeId }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  type ValueAny = Schema.Schema.All | Schema.PropertySignature.All\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Config = {\n    readonly [key: string]: Schema.Schema.All | Schema.PropertySignature.All | undefined\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ConfigWithKeys<K extends string> = {\n    readonly [P in K]?: Schema.Schema.All | Schema.PropertySignature.All\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Fields = {\n    readonly [key: string]:\n      | Schema.Schema.All\n      | Schema.PropertySignature.All\n      | Field<any>\n      | Struct<any>\n      | undefined\n  }\n}\n\n/**\n * @since 1.0.0\n * @category extractors\n */\nexport type ExtractFields<V extends string, Fields extends Struct.Fields, IsDefault = false> = {\n  readonly [\n    K in keyof Fields as [Fields[K]] extends [Field<infer Config>] ? V extends keyof Config ? K\n      : never\n      : K\n  ]: [Fields[K]] extends [Struct<infer _>] ? Extract<V, Fields[K], IsDefault>\n    : [Fields[K]] extends [Field<infer Config>]\n      ? [Config[V]] extends [Schema.Schema.All | Schema.PropertySignature.All] ? Config[V]\n      : never\n    : [Fields[K]] extends [Schema.Schema.All | Schema.PropertySignature.All] ? Fields[K]\n    : never\n}\n\n/**\n * @since 1.0.0\n * @category extractors\n */\nexport type Extract<V extends string, A extends Struct<any>, IsDefault = false> = [A] extends [\n  Struct<infer Fields>\n] ?\n  IsDefault extends true\n    ? [A] extends [Schema.Schema.Any] ? A : Schema.Struct<Schema.Simplify<ExtractFields<V, Fields>>>\n  : Schema.Struct<Schema.Simplify<ExtractFields<V, Fields>>>\n  : never\n\nconst extract: {\n  <V extends string, const IsDefault extends boolean = false>(\n    variant: V,\n    options?: {\n      readonly isDefault?: IsDefault | undefined\n    }\n  ): <A extends Struct<any>>(self: A) => Extract<V, A, IsDefault>\n  <V extends string, A extends Struct<any>, const IsDefault extends boolean = false>(self: A, variant: V, options?: {\n    readonly isDefault?: IsDefault | undefined\n  }): Extract<V, A, IsDefault>\n} = dual(\n  (args) => isStruct(args[0]),\n  <V extends string, A extends Struct<any>>(\n    self: A,\n    variant: V,\n    options?: {\n      readonly isDefault?: boolean | undefined\n    }\n  ): Extract<V, A> => {\n    const cache = self[cacheSymbol] ?? (self[cacheSymbol] = {})\n    const cacheKey = options?.isDefault === true ? \"__default\" : variant\n    if (cache[cacheKey] !== undefined) {\n      return cache[cacheKey] as any\n    }\n    const fields: Record<string, any> = {}\n    for (const key of Object.keys(self[TypeId])) {\n      const value = self[TypeId][key]\n      if (TypeId in value) {\n        if (options?.isDefault === true && Schema.isSchema(value)) {\n          fields[key] = value\n        } else {\n          fields[key] = extract(value, variant)\n        }\n      } else if (FieldTypeId in value) {\n        if (variant in value.schemas) {\n          fields[key] = value.schemas[variant]\n        }\n      } else {\n        fields[key] = value\n      }\n    }\n    return cache[cacheKey] = Schema.Struct(fields) as any\n  }\n)\n\n/**\n * @category accessors\n * @since 1.0.0\n */\nexport const fields = <A extends Struct<any>>(self: A): A[TypeId] => self[TypeId]\n\ntype RequiredKeys<T> = {\n  [K in keyof T]-?: {} extends Pick<T, K> ? never : K\n}[keyof T]\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Class<\n  Self,\n  Fields extends Struct.Fields,\n  SchemaFields extends Schema.Struct.Fields,\n  A,\n  I,\n  R,\n  C\n> extends Schema.Schema<Self, Schema.Simplify<I>, R>, Struct<Schema.Simplify<Fields>> {\n  new(\n    props: RequiredKeys<C> extends never ? void | Schema.Simplify<C>\n      : Schema.Simplify<C>,\n    options?: {\n      readonly disableValidation?: boolean\n    }\n  ): A\n\n  readonly ast: AST.Transformation\n\n  make<Args extends Array<any>, X>(\n    this: { new(...args: Args): X },\n    ...args: Args\n  ): X\n\n  annotations(\n    annotations: Schema.Annotations.Schema<Self>\n  ): Schema.SchemaClass<Self, I, R>\n\n  readonly identifier: string\n  readonly fields: Schema.Simplify<SchemaFields>\n}\n\ntype ClassFromFields<\n  Self,\n  Fields extends Struct.Fields,\n  SchemaFields extends Schema.Struct.Fields\n> = Class<\n  Self,\n  Fields,\n  SchemaFields,\n  Schema.Struct.Type<SchemaFields>,\n  Schema.Struct.Encoded<SchemaFields>,\n  Schema.Struct.Context<SchemaFields>,\n  Schema.Struct.Constructor<SchemaFields>\n>\n\ntype MissingSelfGeneric<Params extends string = \"\"> =\n  `Missing \\`Self\\` generic - use \\`class Self extends Class<Self>()(${Params}{ ... })\\``\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Union<Members extends ReadonlyArray<Struct<any>>> extends\n  Schema.Union<\n    {\n      readonly [K in keyof Members]: [Members[K]] extends [Schema.Schema.All] ? Members[K] : never\n    }\n  >\n{}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace Union {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Variants<Members extends ReadonlyArray<Struct<any>>, Variants extends string> = {\n    readonly [Variant in Variants]: Schema.Union<\n      {\n        [K in keyof Members]: Extract<Variant, Members[K]>\n      }\n    >\n  }\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface fromKey<S extends Schema.Schema.All, Key extends string> extends\n  Schema.PropertySignature<\n    \":\",\n    Schema.Schema.Type<S>,\n    Key,\n    \":\",\n    Schema.Schema.Encoded<S>,\n    false,\n    Schema.Schema.Context<S>\n  >\n{}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace fromKey {\n  /**\n   * @since 1.0.0\n   */\n  export type Rename<S, Key extends string> = S extends Schema.PropertySignature<\n    infer _TypeToken,\n    infer _Type,\n    infer _Key,\n    infer _EncodedToken,\n    infer _Encoded,\n    infer _HasDefault,\n    infer _R\n  > ? Schema.PropertySignature<_TypeToken, _Type, Key, _EncodedToken, _Encoded, _HasDefault, _R>\n    : S extends Schema.Schema.All ? fromKey<S, Key>\n    : never\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <\n  const Variants extends ReadonlyArray<string>,\n  const Default extends Variants[number]\n>(options: {\n  readonly variants: Variants\n  readonly defaultVariant: Default\n}): {\n  readonly Struct: <const A extends Struct.Fields>(\n    fields: A & Struct.Validate<A, Variants[number]>\n  ) => Struct<A>\n  readonly Field: <const A extends Field.ConfigWithKeys<Variants[number]>>(\n    config: A & { readonly [K in Exclude<keyof A, Variants[number]>]: never }\n  ) => Field<A>\n  readonly FieldOnly: <const Keys extends ReadonlyArray<Variants[number]>>(\n    ...keys: Keys\n  ) => <S extends Schema.Schema.All | Schema.PropertySignature.All>(\n    schema: S\n  ) => Field<{ readonly [K in Keys[number]]: S }>\n  readonly FieldExcept: <const Keys extends ReadonlyArray<Variants[number]>>(\n    ...keys: Keys\n  ) => <S extends Schema.Schema.All | Schema.PropertySignature.All>(\n    schema: S\n  ) => Field<{ readonly [K in Exclude<Variants[number], Keys[number]>]: S }>\n  readonly fieldEvolve: {\n    <\n      Self extends Field<any> | Field.ValueAny,\n      const Mapping\n        extends (Self extends Field<infer S> ? { readonly [K in keyof S]?: (variant: S[K]) => Field.ValueAny }\n          : { readonly [K in Variants[number]]?: (variant: Self) => Field.ValueAny })\n    >(f: Mapping): (self: Self) => Field<\n      Self extends Field<infer S> ? {\n          readonly [K in keyof S]: K extends keyof Mapping\n            ? Mapping[K] extends (arg: any) => any ? ReturnType<Mapping[K]> : S[K]\n            : S[K]\n        } :\n        {\n          readonly [K in Variants[number]]: K extends keyof Mapping\n            ? Mapping[K] extends (arg: any) => any ? ReturnType<Mapping[K]> : Self\n            : Self\n        }\n    >\n    <\n      Self extends Field<any> | Field.ValueAny,\n      const Mapping extends (Self extends Field<infer S> ? {\n          readonly [K in keyof S]?: (variant: S[K]) => Field.ValueAny\n        }\n        : { readonly [K in Variants[number]]?: (variant: Self) => Field.ValueAny })\n    >(self: Self, f: Mapping): Field<\n      Self extends Field<infer S> ? {\n          readonly [K in keyof S]: K extends keyof Mapping\n            ? Mapping[K] extends (arg: any) => any ? ReturnType<Mapping[K]> : S[K]\n            : S[K]\n        } :\n        {\n          readonly [K in Variants[number]]: K extends keyof Mapping\n            ? Mapping[K] extends (arg: any) => any ? ReturnType<Mapping[K]> : Self\n            : Self\n        }\n    >\n  }\n  readonly fieldFromKey: {\n    <\n      Self extends Field<any> | Field.ValueAny,\n      const Mapping extends (Self extends Field<infer S> ? { readonly [K in keyof S]?: string }\n        : { readonly [K in Variants[number]]?: string })\n    >(\n      mapping: Mapping\n    ): (self: Self) => Field<\n      Self extends Field<infer S> ? {\n          readonly [K in keyof S]: K extends keyof Mapping ?\n            Mapping[K] extends string ? fromKey.Rename<S[K], Mapping[K]>\n            : S[K] :\n            S[K]\n        } :\n        {\n          readonly [K in Variants[number]]: K extends keyof Mapping ?\n            Mapping[K] extends string ? fromKey.Rename<Self, Mapping[K]>\n            : Self :\n            Self\n        }\n    >\n    <\n      Self extends Field<any> | Field.ValueAny,\n      const Mapping extends (Self extends Field<infer S> ? { readonly [K in keyof S]?: string }\n        : { readonly [K in Variants[number]]?: string })\n    >(\n      self: Self,\n      mapping: Mapping\n    ): Field<\n      Self extends Field<infer S> ? {\n          readonly [K in keyof S]: K extends keyof Mapping ?\n            Mapping[K] extends string ? fromKey.Rename<S[K], Mapping[K]>\n            : S[K] :\n            S[K]\n        } :\n        {\n          readonly [K in Variants[number]]: K extends keyof Mapping ?\n            Mapping[K] extends string ? fromKey.Rename<Self, Mapping[K]>\n            : Self :\n            Self\n        }\n    >\n  }\n  readonly Class: <Self = never>(\n    identifier: string\n  ) => <const Fields extends Struct.Fields>(\n    fields: Fields & Struct.Validate<Fields, Variants[number]>,\n    annotations?: Schema.Annotations.Schema<Self>\n  ) => [Self] extends [never] ? MissingSelfGeneric\n    :\n      & ClassFromFields<\n        Self,\n        Fields,\n        ExtractFields<Default, Fields, true>\n      >\n      & {\n        readonly [V in Variants[number]]: Extract<V, Struct<Fields>>\n      }\n  readonly Union: <const Members extends ReadonlyArray<Struct<any>>>(\n    ...members: Members\n  ) => Union<Members> & Union.Variants<Members, Variants[number]>\n  readonly extract: {\n    <V extends Variants[number]>(\n      variant: V\n    ): <A extends Struct<any>>(self: A) => Extract<V, A, V extends Default ? true : false>\n    <V extends Variants[number], A extends Struct<any>>(\n      self: A,\n      variant: V\n    ): Extract<V, A, V extends Default ? true : false>\n  }\n} => {\n  function Class<Self>(identifier: string) {\n    return function(\n      fields: Struct.Fields,\n      annotations?: Schema.Annotations.Schema<Self>\n    ) {\n      const variantStruct = Struct(fields)\n      const schema = extract(variantStruct, options.defaultVariant, {\n        isDefault: true\n      })\n      class Base extends Schema.Class<any>(identifier)(schema.fields, annotations) {\n        static [TypeId] = fields\n      }\n      for (const variant of options.variants) {\n        Object.defineProperty(Base, variant, {\n          value: extract(variantStruct, variant).annotations({\n            identifier: `${identifier}.${variant}`,\n            title: `${identifier}.${variant}`\n          })\n        })\n      }\n      return Base\n    }\n  }\n  function FieldOnly<Keys extends Variants>(...keys: Keys) {\n    return function<S extends Schema.Schema.All | Schema.PropertySignature.All>(schema: S) {\n      const obj: Record<string, S> = {}\n      for (const key of keys) {\n        obj[key] = schema\n      }\n      return Field(obj)\n    }\n  }\n  function FieldExcept<Keys extends Variants>(...keys: Keys) {\n    return function<S extends Schema.Schema.All | Schema.PropertySignature.All>(schema: S) {\n      const obj: Record<string, S> = {}\n      for (const variant of options.variants) {\n        if (!keys.includes(variant)) {\n          obj[variant] = schema\n        }\n      }\n      return Field(obj)\n    }\n  }\n  function UnionVariants(...members: ReadonlyArray<Struct<any>>) {\n    return Union(members, options.variants)\n  }\n  const fieldEvolve = dual(\n    2,\n    (\n      self: Field<any> | Schema.Schema.All | Schema.PropertySignature.All,\n      f: Record<string, (schema: Field.ValueAny) => Field.ValueAny>\n    ): Field<any> => {\n      const field = isField(self) ? self : Field(Object.fromEntries(\n        options.variants.map((variant) => [variant, self])\n      ))\n      return Field(Struct_.evolve(field.schemas, f))\n    }\n  )\n  const fieldFromKey = dual(\n    2,\n    (\n      self:\n        | Field<{\n          readonly [key: string]: Schema.Schema.All | Schema.PropertySignature.Any | undefined\n        }>\n        | Schema.Schema.All\n        | Schema.PropertySignature.Any,\n      mapping: Record<string, string>\n    ): Field<any> => {\n      const obj: Record<string, any> = {}\n      if (isField(self)) {\n        for (const [key, schema] of Object.entries(self.schemas)) {\n          obj[key] = mapping[key] !== undefined ? renameFieldValue(schema as any, mapping[key]) : schema\n        }\n      } else {\n        for (const key of options.variants) {\n          obj[key] = mapping[key] !== undefined ? renameFieldValue(self as any, mapping[key]) : self\n        }\n      }\n      return Field(obj)\n    }\n  )\n  const extractVariants = dual(\n    2,\n    (self: Struct<any>, variant: string): any =>\n      extract(self, variant, {\n        isDefault: variant === options.defaultVariant\n      })\n  )\n  return {\n    Struct,\n    Field,\n    FieldOnly,\n    FieldExcept,\n    Class,\n    Union: UnionVariants,\n    fieldEvolve,\n    fieldFromKey,\n    extract: extractVariants\n  } as any\n}\n\n/**\n * @since 1.0.0\n * @category overrideable\n */\nexport const Override = <A>(value: A): A & Brand<\"Override\"> => value as any\n\n/**\n * @since 1.0.0\n * @category overrideable\n */\nexport interface Overrideable<To, From, R = never>\n  extends Schema.PropertySignature<\":\", (To & Brand<\"Override\">) | undefined, never, \":\", From, true, R>\n{}\n\n/**\n * @since 1.0.0\n * @category overrideable\n */\nexport const Overrideable = <From, IFrom, RFrom, To, ITo, R>(\n  from: Schema.Schema<From, IFrom, RFrom>,\n  to: Schema.Schema<To, ITo>,\n  options: {\n    readonly generate: (_: Option.Option<ITo>) => Effect.Effect<From, ParseResult.ParseIssue, R>\n    readonly decode?: Schema.Schema<ITo, From>\n    readonly constructorDefault?: () => To\n  }\n): Overrideable<To, IFrom, RFrom | R> =>\n  Schema.transformOrFail(\n    from,\n    Schema.Union(Schema.Undefined, to as Schema.brand<Schema.Schema<To, ITo>, \"Override\">),\n    {\n      decode: (_) => options.decode ? ParseResult.decode(options.decode)(_) : ParseResult.succeed(undefined),\n      encode: (dt) => options.generate(dt === undefined ? Option.none() : Option.some(dt))\n    }\n  ).pipe(Schema.propertySignature, Schema.withConstructorDefault(options.constructorDefault ?? constUndefined as any))\n\nconst StructProto = {\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst Struct = <const A extends Field.Fields>(fields: A): Struct<A> => {\n  const self = Object.create(StructProto)\n  self[TypeId] = fields\n  return self\n}\n\nconst FieldProto = {\n  [FieldTypeId]: FieldTypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst Field = <const A extends Field.Config>(schemas: A): Field<A> => {\n  const self = Object.create(FieldProto)\n  self.schemas = schemas\n  return self\n}\n\nconst Union = <Members extends ReadonlyArray<Struct<any>>, Variants extends ReadonlyArray<string>>(\n  members: Members,\n  variants: Variants\n) => {\n  class VariantUnion extends (Schema.Union(...members.filter((member) => Schema.isSchema(member))) as any) {}\n  for (const variant of variants) {\n    Object.defineProperty(VariantUnion, variant, {\n      value: Schema.Union(...members.map((member) => extract(member, variant)))\n    })\n  }\n  return VariantUnion\n}\n\nconst renameFieldValue = <F extends Schema.Schema.All | Schema.PropertySignature.Any>(\n  self: F,\n  key: string\n) =>\n  Schema.isPropertySignature(self)\n    ? Schema.fromKey(self, key)\n    : Schema.fromKey(Schema.propertySignature(self), key)\n"
  },
  {
    "path": "packages/experimental/src/index.ts",
    "content": "/**\n * @since 1.0.0\n */\nexport * as DevTools from \"./DevTools.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Event from \"./Event.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EventGroup from \"./EventGroup.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EventJournal from \"./EventJournal.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EventLog from \"./EventLog.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EventLogEncryption from \"./EventLogEncryption.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EventLogRemote from \"./EventLogRemote.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as EventLogServer from \"./EventLogServer.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Machine from \"./Machine.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as PersistedCache from \"./PersistedCache.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as PersistedQueue from \"./PersistedQueue.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Persistence from \"./Persistence.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as RateLimiter from \"./RateLimiter.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Reactivity from \"./Reactivity.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as RequestResolver from \"./RequestResolver.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Sse from \"./Sse.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as VariantSchema from \"./VariantSchema.js\"\n"
  },
  {
    "path": "packages/experimental/test/Machine.test.ts",
    "content": "import * as DevTools from \"@effect/experimental/DevTools\"\nimport * as Machine from \"@effect/experimental/Machine\"\nimport { assert, describe, test } from \"@effect/vitest\"\nimport { Cause, Chunk, Context, Deferred, Effect, Exit, Layer, Schema, Stream } from \"effect\"\n\nclass Increment\n  extends Schema.TaggedRequest<Increment>()(\"Increment\", { failure: Schema.Never, success: Schema.Number, payload: {} })\n{}\nclass Decrement\n  extends Schema.TaggedRequest<Decrement>()(\"Decrement\", { failure: Schema.Never, success: Schema.Number, payload: {} })\n{}\nclass IncrementBy extends Schema.TaggedRequest<IncrementBy>()(\"IncrementBy\", {\n  failure: Schema.Never,\n  success: Schema.Number,\n  payload: {\n    number: Schema.Number\n  }\n}) {}\nclass DelayedIncrementBy extends Schema.TaggedRequest<DelayedIncrementBy>()(\"DelayedIncrementBy\", {\n  failure: Schema.Never,\n  success: Schema.Void,\n  payload: {\n    delay: Schema.Positive,\n    number: Schema.Number\n  }\n}) {}\nclass Multiply\n  extends Schema.TaggedRequest<Multiply>()(\"Multiply\", { failure: Schema.Never, success: Schema.Number, payload: {} })\n{}\n\nclass FailBackground extends Schema.TaggedRequest<FailBackground>()(\"FailBackground\", {\n  failure: Schema.Never,\n  success: Schema.Void,\n  payload: {}\n}) {}\n\nconst counter = Machine.makeWith<number, number>()(\n  (input, previous) =>\n    Machine.procedures.make(previous ?? input, {\n      identifier: `Counter(${input})`\n    }).pipe(\n      Machine.procedures.add<Increment>()(\"Increment\", ({ state }) =>\n        Effect.sync(() => {\n          const count = state + 1\n          return [count, count]\n        })),\n      Machine.procedures.add<Decrement>()(\"Decrement\", ({ state }) =>\n        Effect.sync(() => {\n          const count = state - 1\n          return [count, count]\n        })),\n      Machine.procedures.add<IncrementBy>()(\"IncrementBy\", ({ request, state }) =>\n        Effect.sync(() => {\n          const count = state + request.number\n          return [count, count]\n        })),\n      Machine.procedures.add<FailBackground>()(\n        \"FailBackground\",\n        ({ forkWith, state }) => forkWith(Effect.fail(\"error\"), state)\n      )\n    )\n)\n\nconst counterSerializable = Machine.makeSerializable(\n  { state: Schema.NumberFromString, input: Schema.Number },\n  (input, previous) =>\n    Machine.serializable.make(previous ?? input, {\n      identifier: `Counter(${input})`\n    }).pipe(\n      Machine.serializable.add(Increment, ({ state }) =>\n        Effect.sync(() => {\n          const count = state + 1\n          return [count, count]\n        })),\n      Machine.serializable.add(Decrement, ({ state }) =>\n        Effect.sync(() => {\n          const count = state - 1\n          return [count, count]\n        })),\n      Machine.serializable.add(IncrementBy, ({ request, state }) =>\n        Effect.sync(() => {\n          const count = state + request.number\n          return [count, count]\n        })),\n      Machine.serializable.add(\n        FailBackground,\n        ({ forkWith, state }) => forkWith(Effect.fail(\"error\"), state)\n      )\n    )\n)\n\nconst delayedCounter = Machine.makeWith<number, number>()(\n  (input, previous) =>\n    Machine.procedures.make(previous ?? input, {\n      identifier: `Counter(${input})`\n    }).pipe(\n      Machine.procedures.addPrivate<IncrementBy>()(\"IncrementBy\", ({ request, state }) =>\n        Effect.sync(() => {\n          const count = state + request.number\n          return [count, count]\n        })),\n      Machine.procedures.add<DelayedIncrementBy>()(\n        \"DelayedIncrementBy\",\n        ({ forkWith, request, sendAwait, state }) =>\n          sendAwait(new IncrementBy({ number: request.number })).pipe(\n            Effect.delay(request.delay),\n            forkWith(state)\n          )\n      )\n    )\n)\n\nclass Multiplier extends Context.Tag(\"Multiplier\")<Multiplier, number>() {\n  static Live = Layer.succeed(this, 2)\n}\n\nconst withContext = Machine.make(\n  (input: number, previous?: number) =>\n    Effect.gen(function*() {\n      const multiplier = yield* Multiplier\n      return Machine.procedures.make(previous ?? input).pipe(\n        Machine.procedures.add<Multiply>()(\"Multiply\", ({ state }) =>\n          Effect.sync(() => {\n            const count = state * multiplier\n            return [count, count]\n          }))\n      )\n    })\n)\n\nconst timerLoop = Machine.make(\n  Effect.gen(function*() {\n    const { unsafeSend } = yield* Machine.MachineContext\n\n    // queue initial message\n    yield* unsafeSend(new Increment())\n\n    return Machine.procedures.make(0).pipe(\n      Machine.procedures.addPrivate<Increment>()(\n        \"Increment\",\n        (ctx) =>\n          ctx.send(new Increment()).pipe(\n            Effect.delay(20),\n            ctx.forkOne(\"timer\"),\n            Effect.as([ctx.state + 1, ctx.state + 1])\n          )\n      )\n    )\n  })\n)\n\nconst deferReply = Machine.make(\n  Machine.procedures.make(0).pipe(\n    Machine.procedures.add<Increment>()(\n      \"Increment\",\n      (ctx) => {\n        const count = ctx.state + 1\n        return Deferred.succeed(ctx.deferred, count).pipe(\n          Effect.delay(10),\n          ctx.fork,\n          Effect.as([Machine.NoReply, count])\n        )\n      }\n    )\n  )\n)\n\ndescribe(\"Machine\", () => {\n  test(\"counter\", () =>\n    Effect.gen(function*() {\n      yield* Effect.sleep(500) // wait for DevTools\n\n      const booted = yield* Machine.boot(counter, 0)\n      yield* Effect.sleep(10)\n      assert.strictEqual(yield* booted.get, 0)\n      assert.strictEqual(yield* booted.send(new Increment()), 1)\n      assert.strictEqual(yield* booted.send(new Increment()), 2)\n      assert.strictEqual(yield* booted.send(new IncrementBy({ number: 2 })), 4)\n      assert.strictEqual(yield* booted.send(new Decrement()), 3)\n      assert.strictEqual(yield* booted.send(new FailBackground()), undefined)\n      const cause = yield* booted.join.pipe(Effect.sandbox, Effect.flip)\n      const failure = Cause.failures(cause).pipe(Chunk.unsafeHead)\n      assert.deepStrictEqual(failure.cause, \"error\")\n    }).pipe(Effect.scoped, Machine.withTracingEnabled(true), Effect.provide(DevTools.layer()), Effect.runPromise))\n\n  test(\"init context\", () =>\n    Effect.gen(function*() {\n      const booted = yield* Machine.boot(withContext, 20)\n      assert.strictEqual(yield* booted.get, 20)\n      assert.strictEqual(yield* booted.send(new Multiply()), 40)\n    }).pipe(\n      Effect.scoped,\n      Effect.provide(Multiplier.Live),\n      Effect.runPromise\n    ))\n\n  test(\"forkWithState\", () =>\n    Effect.gen(function*() {\n      const booted = yield* Machine.boot(delayedCounter, 2)\n      assert.strictEqual(yield* booted.get, 2)\n      assert.deepStrictEqual(\n        // @ts-expect-error\n        yield* booted.send(new IncrementBy({ number: 2 })).pipe(Effect.exit),\n        Exit.die(\"Request IncrementBy marked as internal\")\n      )\n      assert.strictEqual(yield* booted.send(new DelayedIncrementBy({ number: 2, delay: 10 })), undefined)\n      assert.strictEqual(yield* booted.get, 2)\n      yield* Effect.sleep(10)\n      assert.strictEqual(yield* booted.get, 4)\n    }).pipe(Effect.scoped, Effect.runPromise))\n\n  test(\"changes\", () =>\n    Effect.gen(function*() {\n      const booted = yield* Machine.boot(counter, 0)\n      const results: Array<number> = []\n      yield* booted.changes.pipe(\n        Stream.runForEach((i) =>\n          Effect.sync(() => {\n            results.push(i)\n          })\n        ),\n        Effect.fork\n      )\n      yield* Effect.sleep(0)\n      assert.strictEqual(yield* booted.send(new Increment()), 1)\n      assert.strictEqual(yield* booted.send(new Increment()), 2)\n      assert.strictEqual(yield* booted.send(new Increment()), 3)\n\n      assert.deepStrictEqual(results, [0, 1, 2, 3])\n    }).pipe(Effect.scoped, Effect.runPromise))\n\n  test(\"unsafeSend initializer\", () =>\n    Effect.gen(function*() {\n      const actor = yield* Machine.boot(timerLoop)\n      const results = yield* actor.changes.pipe(\n        Stream.take(5),\n        Stream.runCollect\n      )\n      assert.deepStrictEqual(Chunk.toReadonlyArray(results), [0, 1, 2, 3, 4])\n    }).pipe(Effect.scoped, Effect.runPromise))\n\n  test(\"NoReply\", () =>\n    Effect.gen(function*() {\n      const actor = yield* Machine.boot(deferReply)\n      assert.strictEqual(yield* actor.send(new Increment()), 1)\n    }).pipe(Effect.scoped, Effect.runPromise))\n})\n\ndescribe(\"SerializableMachine\", () => {\n  test(\"counter\", () =>\n    Effect.gen(function*() {\n      const actor = yield* Machine.boot(counterSerializable, 10)\n\n      assert.strictEqual(yield* actor.get, 10)\n      assert.strictEqual(yield* actor.send(new Increment()), 11)\n      assert.strictEqual(yield* actor.send(new Increment()), 12)\n      assert.deepStrictEqual(yield* actor.sendUnknown({ _tag: \"Decrement\" }), {\n        _tag: \"Success\",\n        value: 11\n      })\n      const snapshot = yield* Machine.snapshot(actor)\n      assert.deepStrictEqual(snapshot, [10, \"11\"])\n\n      const restored = yield* Machine.restore(counterSerializable, snapshot)\n      assert.strictEqual(yield* restored.get, 11)\n    }).pipe(Effect.scoped, Effect.runPromise))\n})\n"
  },
  {
    "path": "packages/experimental/test/PersistedCache.test.ts",
    "content": "import * as PersistedCache from \"@effect/experimental/PersistedCache\"\nimport * as Persistence from \"@effect/experimental/Persistence\"\nimport { KeyValueStore } from \"@effect/platform\"\nimport { assert, describe, it } from \"@effect/vitest\"\nimport { Effect, Exit, Layer, Option, PrimaryKey, Schema } from \"effect\"\n\nclass User extends Schema.Class<User>(\"User\")({\n  id: Schema.Number,\n  name: Schema.String\n}) {}\n\nclass TTLRequest extends Schema.TaggedRequest<TTLRequest>()(\"TTLRequest\", {\n  failure: Schema.String,\n  success: User,\n  payload: {\n    id: Schema.Number\n  }\n}) implements Persistence.Persistable<typeof User, typeof Schema.String> {\n  [PrimaryKey.symbol]() {\n    return `TTLRequest:${this.id}`\n  }\n}\n\ndescribe(\"PersistedCache\", () => {\n  const testsuite = (storeId: \"memory\" | \"kvs\", layer: Layer.Layer<Persistence.ResultPersistence, unknown>) =>\n    it.scoped(storeId, () =>\n      Effect.gen(function*() {\n        const persistence = yield* Persistence.ResultPersistence\n        const store = yield* persistence.make({ storeId: \"users\" })\n        let invocations = 0\n        let cache = yield* PersistedCache.make({\n          storeId: \"users\",\n          lookup: (req: TTLRequest) =>\n            Effect.sync(() => {\n              invocations++\n              return new User({ id: req.id, name: \"John\" })\n            }),\n          timeToLive: (_req, _exit) => 5000\n        })\n        const user = yield* cache.get(new TTLRequest({ id: 1 }))\n        assert.deepStrictEqual(user, new User({ id: 1, name: \"John\" }))\n        assert.deepStrictEqual(\n          yield* store.get(new TTLRequest({ id: 1 })),\n          Option.some(Exit.succeed(new User({ id: 1, name: \"John\" })))\n        )\n        assert.strictEqual(invocations, 1)\n        assert.deepStrictEqual(yield* cache.get(new TTLRequest({ id: 1 })), new User({ id: 1, name: \"John\" }))\n        assert.strictEqual(invocations, 1)\n\n        cache = yield* PersistedCache.make({\n          storeId: \"users\",\n          lookup: (req: TTLRequest) =>\n            Effect.sync(() => {\n              invocations++\n              return new User({ id: req.id, name: \"John\" })\n            }),\n          timeToLive: (_req, _exit) => 5000\n        })\n        assert.deepStrictEqual(yield* cache.get(new TTLRequest({ id: 1 })), new User({ id: 1, name: \"John\" }))\n        assert.strictEqual(invocations, 1)\n      }).pipe(Effect.provide(layer)))\n\n  testsuite(\"memory\", Persistence.layerResultMemory)\n  testsuite(\"kvs\", Persistence.layerResultKeyValueStore.pipe(Layer.provide(KeyValueStore.layerMemory)))\n})\n"
  },
  {
    "path": "packages/experimental/test/PersistedQueue.test.ts",
    "content": "import { PersistedQueue } from \"@effect/experimental\"\nimport * as RedisPersistedQueue from \"@effect/experimental/PersistedQueue/Redis\"\nimport { assert, it } from \"@effect/vitest\"\nimport { Effect, Fiber, Layer, Schema, TestClock, TestServices } from \"effect\"\nimport { RedisContainer } from \"./utils/redis.js\"\n\nconst layerMemory = PersistedQueue.layer.pipe(\n  Layer.provide(PersistedQueue.layerStoreMemory)\n)\n\nconst layerRedis = PersistedQueue.layer.pipe(\n  Layer.provide(Layer.unwrapEffect(Effect.gen(function*() {\n    const container = yield* RedisContainer\n    return RedisPersistedQueue.layerStore({\n      host: container.getHost(),\n      port: container.getMappedPort(6379)\n    })\n  }))),\n  Layer.provide(RedisContainer.layer)\n)\n;([\n  [\"Memory\", layerMemory],\n  [\"Redis\", layerRedis]\n] as const).forEach(([name, layer]) => {\n  it.layer(layer, { timeout: \"30 seconds\" })(`PersistedQueue (${name})`, (it) => {\n    it.effect(\"offer + take\", () =>\n      Effect.gen(function*() {\n        const queue = yield* PersistedQueue.make({\n          name: \"test-queue-a\",\n          schema: Item\n        })\n\n        yield* queue.offer({ n: 42n })\n        yield* queue.take(Effect.fnUntraced(function*(value) {\n          assert.strictEqual(value.n, 42n)\n        }))\n      }))\n\n    it.effect(\"interrupt\", () =>\n      Effect.gen(function*() {\n        const queue = yield* PersistedQueue.make({\n          name: \"test-queue-b\",\n          schema: Item\n        })\n\n        yield* queue.offer({ n: 42n })\n\n        const latch = Effect.unsafeMakeLatch()\n        const fiber = yield* queue.take(Effect.fnUntraced(function*(_value) {\n          yield* latch.open\n          return yield* Effect.never\n        })).pipe(Effect.fork)\n\n        const fiber2 = yield* queue.take((val) => Effect.succeed(val)).pipe(Effect.fork)\n\n        yield* latch.await\n\n        // allow some real time to pass to ensure the second take is really\n        // waiting\n        yield* TestClock.adjust(1000)\n        yield* Effect.sleep(1000).pipe(\n          TestServices.provideLive\n        )\n        assert.isNull(fiber2.unsafePoll())\n\n        yield* Fiber.interrupt(fiber)\n\n        yield* TestClock.adjust(1000)\n\n        assert.strictEqual((yield* Fiber.join(fiber2)).n, 42n)\n      }))\n\n    it.effect(\"failure\", () =>\n      Effect.gen(function*() {\n        const queue = yield* PersistedQueue.make({\n          name: \"test-queue-c\",\n          schema: Item\n        })\n\n        yield* queue.offer({ n: 42n })\n\n        const error = yield* queue.take(() => Effect.fail(\"boom\")).pipe(Effect.flip)\n        assert.strictEqual(error, \"boom\")\n\n        const value = yield* queue.take((val, { attempts }) => {\n          assert.strictEqual(attempts, 1)\n          return Effect.succeed(val)\n        })\n        assert.strictEqual(value.n, 42n)\n      }))\n\n    it.effect(\"idempotent offer\", () =>\n      Effect.gen(function*() {\n        const queue = yield* PersistedQueue.make({\n          name: \"idempotent-offer\",\n          schema: Item\n        })\n\n        yield* queue.offer({ n: 42n }, { id: \"custom-id\" })\n        yield* queue.offer({ n: 42n }, { id: \"custom-id\" })\n        yield* queue.take(Effect.fnUntraced(function*(value) {\n          assert.strictEqual(value.n, 42n)\n        }))\n        const fiber = yield* queue.take(Effect.fnUntraced(function*(value) {\n          assert.strictEqual(value.n, 42n)\n        })).pipe(Effect.fork)\n\n        yield* TestClock.adjust(1000)\n        yield* Effect.sleep(1000).pipe(\n          TestServices.provideLive\n        )\n\n        assert.isNull(fiber.unsafePoll())\n      }))\n  })\n})\n\nconst Item = Schema.Struct({\n  n: Schema.BigInt\n})\n"
  },
  {
    "path": "packages/experimental/test/RateLimiter.test.ts",
    "content": "import { RateLimiter } from \"@effect/experimental\"\nimport { assert, describe, expect, it } from \"@effect/vitest\"\nimport { Effect } from \"effect\"\nimport * as Duration from \"effect/Duration\"\nimport * as TestClock from \"effect/TestClock\"\n\ndescribe(\"RateLimiter\", () => {\n  describe(\"fixed-window\", () => {\n    it.effect(\"onExceeded delay\", () =>\n      Effect.gen(function*() {\n        const limiter = yield* RateLimiter.make\n        const consume = limiter.consume({\n          algorithm: \"fixed-window\",\n          onExceeded: \"delay\",\n          window: \"1 minute\",\n          limit: 5,\n          tokens: 1,\n          key: \"a\"\n        })\n        yield* Effect.repeatN(consume, 3) // 1 + 3\n        let result = yield* consume // 5\n        expect(result.delay).toEqual(Duration.zero)\n        result = yield* consume // 6\n        expect(result.delay).toEqual(Duration.minutes(1))\n\n        yield* Effect.repeatN(consume, 2) // 7,8,9\n        result = yield* consume // 10\n        expect(result.delay).toEqual(Duration.minutes(1))\n        result = yield* consume // 11\n        expect(result.delay).toEqual(Duration.minutes(2))\n\n        yield* TestClock.adjust(Duration.seconds(30))\n\n        result = yield* consume // 12\n        expect(result.delay).toEqual(Duration.seconds(90))\n\n        yield* TestClock.adjust(Duration.seconds(45))\n\n        result = yield* consume // 13\n        expect(result.delay).toEqual(Duration.seconds(45))\n      }).pipe(\n        Effect.provide(RateLimiter.layerStoreMemory)\n      ))\n\n    it.effect(\"onExceeded fail\", () =>\n      Effect.gen(function*() {\n        const limiter = yield* RateLimiter.make\n        const consume = limiter.consume({\n          algorithm: \"fixed-window\",\n          onExceeded: \"fail\",\n          window: \"1 minute\",\n          limit: 5,\n          tokens: 1,\n          key: \"a\"\n        })\n        yield* Effect.repeatN(consume, 3)\n        let result = yield* consume\n        expect(result.delay).toEqual(Duration.zero)\n        let error = yield* Effect.flip(consume)\n        assert(error.reason === \"Exceeded\")\n        expect(error.retryAfter).toEqual(Duration.minutes(1))\n        expect(error.remaining).toEqual(0)\n\n        yield* TestClock.adjust(Duration.seconds(30))\n\n        error = yield* Effect.flip(consume)\n        assert(error.reason === \"Exceeded\")\n        expect(error.retryAfter).toEqual(Duration.seconds(30))\n        expect(error.remaining).toEqual(0)\n\n        yield* TestClock.adjust(Duration.seconds(30))\n\n        result = yield* consume\n        expect(result.delay).toEqual(Duration.zero)\n        expect(result.remaining).toEqual(4)\n      }).pipe(\n        Effect.provide(RateLimiter.layerStoreMemory)\n      ))\n  })\n\n  describe(\"token-bucket\", () => {\n    it.effect(\"onExceeded delay\", () =>\n      Effect.gen(function*() {\n        const limiter = yield* RateLimiter.make\n        const consume = limiter.consume({\n          algorithm: \"token-bucket\",\n          onExceeded: \"delay\",\n          window: \"1 minute\",\n          limit: 5,\n          tokens: 1,\n          key: \"a\"\n        })\n        const refillRate = Duration.unsafeDivide(Duration.minutes(1), 5)\n        yield* Effect.repeatN(consume, 3) // 1 + 3\n        let result = yield* consume // 5\n        expect(result.delay).toEqual(Duration.zero)\n        result = yield* consume // 6\n        expect(result.delay).toEqual(refillRate)\n        result = yield* consume // 7\n        expect(result.delay).toEqual(Duration.times(refillRate, 2))\n\n        yield* TestClock.adjust(Duration.minutes(1)) // 2\n\n        result = yield* consume // 3\n        expect(result.delay).toEqual(Duration.zero)\n        expect(result.remaining).toEqual(2)\n      }).pipe(\n        Effect.provide(RateLimiter.layerStoreMemory)\n      ))\n\n    it.effect(\"onExceeded fail\", () =>\n      Effect.gen(function*() {\n        const limiter = yield* RateLimiter.make\n        const consume = limiter.consume({\n          algorithm: \"token-bucket\",\n          onExceeded: \"fail\",\n          window: \"1 minute\",\n          limit: 5,\n          tokens: 1,\n          key: \"a\"\n        })\n        const refillRate = Duration.unsafeDivide(Duration.minutes(1), 5)\n        yield* Effect.repeatN(consume, 3)\n        let result = yield* consume\n        expect(result.delay).toEqual(Duration.zero)\n        const error = yield* Effect.flip(consume)\n        assert(error.reason === \"Exceeded\")\n        expect(error.retryAfter).toEqual(Duration.seconds(12))\n        expect(error.remaining).toEqual(0)\n\n        yield* TestClock.adjust(Duration.times(refillRate, 3))\n\n        result = yield* consume\n        expect(result.delay).toEqual(Duration.zero)\n        expect(result.remaining).toEqual(2)\n      }).pipe(\n        Effect.provide(RateLimiter.layerStoreMemory)\n      ))\n  })\n})\n"
  },
  {
    "path": "packages/experimental/test/RequestResolver.test.ts",
    "content": "import * as Persistence from \"@effect/experimental/Persistence\"\nimport * as RequestResolverX from \"@effect/experimental/RequestResolver\"\nimport { KeyValueStore } from \"@effect/platform\"\nimport { assert, describe, it } from \"@effect/vitest\"\nimport { Array, Effect, Exit, Layer, PrimaryKey, Request, RequestResolver, Schema, TestClock } from \"effect\"\nimport type { NonEmptyArray } from \"effect/Array\"\n\nclass User extends Schema.Class<User>(\"User\")({\n  id: Schema.Number,\n  name: Schema.String\n}) {}\n\nclass MyRequest extends Schema.TaggedRequest<MyRequest>()(\"MyRequest\", {\n  failure: Schema.String,\n  success: User,\n  payload: {\n    id: Schema.Number\n  }\n}) {\n  [PrimaryKey.symbol]() {\n    return `MyRequest:${this.id}`\n  }\n}\n\nclass TTLRequest extends Schema.TaggedRequest<TTLRequest>()(\"TTLRequest\", {\n  failure: Schema.String,\n  success: User,\n  payload: {\n    id: Schema.Number\n  }\n}) {\n  [PrimaryKey.symbol]() {\n    return `TTLRequest:${this.id}`\n  }\n  // [TimeToLive.symbol](exit: Exit.Exit<User, string>) {\n  //   return Exit.isSuccess(exit) ? 5000 : 1\n  // }\n}\n\ndescribe(\"RequestResolver\", () => {\n  describe(\"persisted\", () => {\n    const testsuite = (\n      storeId: \"memory\" | \"kvs\" | \"lmdb\",\n      layer: Layer.Layer<Persistence.ResultPersistence, unknown>\n    ) =>\n      it.effect(storeId, () =>\n        Effect.gen(function*() {\n          let count = 0\n          const baseResolver = RequestResolver.makeBatched((reqs: NonEmptyArray<MyRequest | TTLRequest>) => {\n            count += reqs.length\n            return Effect.forEach(reqs, (req) => {\n              if (req.id === -1) return Request.fail(req, \"not found\")\n              return Request.succeed(req, new User({ id: req.id, name: \"John\" }))\n            }, { discard: true })\n          })\n          const persisted = yield* RequestResolverX.persisted(baseResolver, {\n            storeId,\n            timeToLive: (_req, exit) => Exit.isSuccess(exit) ? 5000 : 1\n          })\n          let users = yield* Effect.forEach(\n            Array.range(1, 5),\n            (id) => Effect.request(new MyRequest({ id }), persisted),\n            {\n              batching: true\n            }\n          )\n          assert.strictEqual(count, 5)\n          assert.strictEqual(users.length, 5)\n          users = yield* Effect.forEach(Array.range(1, 5), (id) => Effect.request(new MyRequest({ id }), persisted), {\n            batching: true\n          })\n          assert.strictEqual(count, 5)\n          assert.strictEqual(users.length, 5)\n\n          // ttl\n          let results = yield* Effect.forEach(\n            Array.range(-1, 3),\n            (id) => Effect.exit(Effect.request(new TTLRequest({ id }), persisted)),\n            {\n              batching: true\n            }\n          )\n\n          assert.strictEqual(count, 10)\n          assert.strictEqual(results.length, 5)\n          assert(Exit.isFailure(results[0]))\n          assert(Exit.isSuccess(results[1]))\n\n          results = yield* Effect.forEach(\n            Array.range(-1, 3),\n            (id) => Effect.exit(Effect.request(new TTLRequest({ id }), persisted)),\n            {\n              batching: true\n            }\n          )\n          assert.strictEqual(count, 10)\n          assert.strictEqual(results.length, 5)\n\n          yield* TestClock.adjust(1)\n\n          results = yield* Effect.forEach(\n            Array.range(-1, 3),\n            (id) => Effect.exit(Effect.request(new TTLRequest({ id }), persisted)),\n            {\n              batching: true\n            }\n          )\n          assert.strictEqual(count, 11)\n          assert.strictEqual(results.length, 5)\n\n          yield* TestClock.adjust(5000)\n\n          results = yield* Effect.forEach(\n            Array.range(-1, 3),\n            (id) => Effect.exit(Effect.request(new TTLRequest({ id }), persisted)),\n            {\n              batching: true\n            }\n          )\n          assert.strictEqual(count, 16)\n          assert.strictEqual(results.length, 5)\n\n          // clear\n          const persistence = yield* Persistence.ResultPersistence\n          const store = yield* persistence.make({ storeId })\n          yield* store.clear\n\n          users = yield* Effect.forEach(Array.range(1, 5), (id) => Effect.request(new MyRequest({ id }), persisted), {\n            batching: true\n          })\n          assert.strictEqual(count, 21)\n          assert.strictEqual(users.length, 5)\n        }).pipe(Effect.scoped, Effect.provide(layer)))\n\n    testsuite(\"memory\", Persistence.layerResultMemory)\n    testsuite(\"kvs\", Persistence.layerResultKeyValueStore.pipe(Layer.provide(KeyValueStore.layerMemory)))\n    // testsuite(\n    //   \"lmdb\",\n    //   Effect.gen(function*(_) {\n    //     const fs = yield* _(FileSystem.FileSystem)\n    //     const dir = yield* _(fs.makeTempDirectoryScoped())\n    //     return PersistenceLmdb.layerResult({ path: dir })\n    //   }).pipe(Layer.unwrapScoped, Layer.provide(NodeContext.layer))\n    // )\n  })\n})\n"
  },
  {
    "path": "packages/experimental/test/utils/extend.ts",
    "content": "import * as V from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\n\nexport type API = V.API\n\nexport const it: API = V.it\n\nexport const effect = (() => {\n  const f = <E, A>(\n    name: string,\n    self: () => Effect.Effect<A, E>,\n    timeout = 5_000\n  ) => {\n    return it(\n      name,\n      () =>\n        pipe(\n          Effect.suspend(self),\n          Effect.runPromise\n        ),\n      timeout\n    )\n  }\n  return Object.assign(f, {\n    skip: <E, A>(\n      name: string,\n      self: () => Effect.Effect<A, E>,\n      timeout = 5_000\n    ) => {\n      return it.skip(\n        name,\n        () =>\n          pipe(\n            Effect.suspend(self),\n            Effect.runPromise\n          ),\n        timeout\n      )\n    },\n    only: <E, A>(\n      name: string,\n      self: () => Effect.Effect<A, E>,\n      timeout = 5_000\n    ) => {\n      return it.only(\n        name,\n        () =>\n          pipe(\n            Effect.suspend(self),\n            Effect.runPromise\n          ),\n        timeout\n      )\n    }\n  })\n})()\n"
  },
  {
    "path": "packages/experimental/test/utils/redis.ts",
    "content": "import type { StartedRedisContainer } from \"@testcontainers/redis\"\nimport * as Redis from \"@testcontainers/redis\"\nimport { Context, Data, Effect, Layer } from \"effect\"\n\nexport class ContainerError extends Data.TaggedError(\"ContainerError\")<{\n  cause: unknown\n}> {}\n\nexport class RedisContainer extends Context.Tag(\"test/RedisContainer\")<\n  RedisContainer,\n  StartedRedisContainer\n>() {\n  static layer = Layer.scoped(\n    this,\n    Effect.acquireRelease(\n      Effect.tryPromise({\n        try: () => new Redis.RedisContainer(\"redis\").start(),\n        catch: (cause) => new ContainerError({ cause })\n      }),\n      (container) => Effect.promise(() => container.stop())\n    )\n  )\n}\n"
  },
  {
    "path": "packages/experimental/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"references\": [\n    { \"path\": \"../effect/tsconfig.build.json\" },\n    { \"path\": \"../platform/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true\n  }\n}\n"
  },
  {
    "path": "packages/experimental/tsconfig.examples.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"examples\"],\n  \"references\": [\n    { \"path\": \"tsconfig.build.json\" },\n    { \"path\": \"../platform-node/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/examples.tsbuildinfo\",\n    \"rootDir\": \"examples\",\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "packages/experimental/tsconfig.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" },\n    { \"path\": \"tsconfig.examples.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/experimental/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"references\": [\n    { \"path\": \"../effect/tsconfig.src.json\" },\n    { \"path\": \"../platform/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\",\n    \"outDir\": \"build/src\"\n  }\n}\n"
  },
  {
    "path": "packages/experimental/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../vitest/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "packages/experimental/vitest.config.ts",
    "content": "import { mergeConfig, type ViteUserConfig } from \"vitest/config\"\nimport shared from \"../../vitest.shared.js\"\n\nconst config: ViteUserConfig = {}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/opentelemetry/CHANGELOG.md",
    "content": "# @effect/opentelemetry\n\n## 0.63.0\n\n### Patch Changes\n\n- [#5780](https://github.com/Effect-TS/effect/pull/5780) [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb) Thanks @mikearnaldi! - Add logs to first propagated span, in the following case before this fix the log would not be added to the `p` span because `Effect.fn` adds a fake span for the purpose of adding a stack frame.\n\n  ```ts\n  import { Effect } from \"effect\"\n\n  const f = Effect.fn(function* () {\n    yield* Effect.logWarning(\"FooBar\")\n    return yield* Effect.fail(\"Oops\")\n  })\n\n  const p = f().pipe(Effect.withSpan(\"p\"))\n  ```\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n  - @effect/platform@0.96.0\n\n## 0.62.0\n\n### Patch Changes\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n  - @effect/platform@0.95.0\n\n## 0.61.0\n\n### Minor Changes\n\n- [#5927](https://github.com/Effect-TS/effect/pull/5927) [`f4972ed`](https://github.com/Effect-TS/effect/commit/f4972eda6c3179070d0167a30985b760afa0a9f9) Thanks @davidgoli! - Add protobuf protocol support for OTLP exporters\n\n  This introduces an `OtlpSerialization` service for choosing between JSON and Protobuf encoding.\n\n  **Breaking changes:**\n  - `Otlp.layer` now requires an `OtlpSerialization` layer to be provided for\n    the desired encoding format.\n\n  **JSON encoding:**\n\n  ```typescript\n  import { Layer } from \"effect\"\n  import { Otlp, OtlpSerialization } from \"@effect/opentelemetry\"\n\n  // Option 1: Explicit JSON layer\n  const layer = Otlp.layerJson({\n    baseUrl: \"http://localhost:4318\",\n    resource: { serviceName: \"my-service\" }\n  })\n\n  // Option 2: Use `layer` and provide OtlpSerialization JSON layer\n  const layer = Otlp.layer({\n    baseUrl: \"http://localhost:4318\",\n    resource: { serviceName: \"my-service\" }\n  }).pipe(Layer.provide(OtlpSerialization.layerJson))\n  ```\n\n  **Protobuf encoding:**\n\n  ```typescript\n  import { Otlp } from \"@effect/opentelemetry\"\n\n  // Simply use layerProtobuf for protobuf encoding\n  const layer = Otlp.layerProtobuf({\n    baseUrl: \"http://localhost:4318\",\n    resource: { serviceName: \"my-service\" }\n  })\n  ```\n\n- [#5952](https://github.com/Effect-TS/effect/pull/5952) [`4725a7e`](https://github.com/Effect-TS/effect/commit/4725a7eceac8b8b66ee55bbd975e1adab67df271) Thanks @clayroach! - Make @opentelemetry/sdk-trace-node and @opentelemetry/sdk-trace-web required peer dependencies instead of optional. This fixes module resolution errors when importing from the main entry point.\n\n### Patch Changes\n\n- [#5929](https://github.com/Effect-TS/effect/pull/5929) [`abdab5c`](https://github.com/Effect-TS/effect/commit/abdab5cc4ede8272799f86caa6557a8a9674ab37) Thanks @schickling! - Fix `Span.addEvent` to correctly handle the 2-argument overload with attributes.\n\n  Previously, calling `span.addEvent(\"name\", { foo: \"bar\" })` would throw `TypeError: {} is not iterable` because the implementation incorrectly treated the attributes object as a `TimeInput`. The fix adds proper runtime type discrimination to distinguish between `TimeInput` (number, Date, or HrTime tuple) and `Attributes` (plain object).\n\n- Updated dependencies [[`7e925ea`](https://github.com/Effect-TS/effect/commit/7e925eae4a9db556bcbf7e8b6a762ccf8588aa3b), [`118e7a4`](https://github.com/Effect-TS/effect/commit/118e7a4af5b86f6d707a40d3b03157b6bf5827e7), [`d7e75d6`](https://github.com/Effect-TS/effect/commit/d7e75d6d15294bbcd7ac49a0e9005848379ea86f), [`4860d1e`](https://github.com/Effect-TS/effect/commit/4860d1e09b436061ea4aeca07605a669793560fc)]:\n  - effect@3.19.15\n  - @effect/platform@0.94.2\n\n## 0.60.0\n\n### Patch Changes\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n  - @effect/platform@0.94.0\n\n## 0.59.3\n\n### Patch Changes\n\n- [#5890](https://github.com/Effect-TS/effect/pull/5890) [`03355c1`](https://github.com/Effect-TS/effect/commit/03355c1470705168e79ca62f57a30f236cc8033d) Thanks @schickling! - Fix `Tracer.currentOtelSpan` to work with OTLP module\n\n  `currentOtelSpan` now works with both the official OpenTelemetry SDK and the lightweight OTLP module. When using OTLP, it returns a wrapper that conforms to the OpenTelemetry Span interface.\n\n  Closes #5889\n\n- Updated dependencies [[`a6dfca9`](https://github.com/Effect-TS/effect/commit/a6dfca93b676eeffe4db64945b01e2004b395cb8), [`a0a84d8`](https://github.com/Effect-TS/effect/commit/a0a84d8df05d18023ffcb1f60af91d14c2b8db57)]:\n  - effect@3.19.12\n  - @effect/platform@0.93.8\n\n## 0.59.2\n\n### Patch Changes\n\n- [#5863](https://github.com/Effect-TS/effect/pull/5863) [`5be3b6a`](https://github.com/Effect-TS/effect/commit/5be3b6add400dcf281475dbefbfede5b69c63940) Thanks @mikearnaldi! - Widen @opentelemetry/sdk-logs peer dependency range\n\n- Updated dependencies [[`3f9bbfe`](https://github.com/Effect-TS/effect/commit/3f9bbfe9ef78303ecc6817b68ec9671f4d42d249)]:\n  - effect@3.19.9\n\n## 0.59.1\n\n### Patch Changes\n\n- [#5735](https://github.com/Effect-TS/effect/pull/5735) [`973c90a`](https://github.com/Effect-TS/effect/commit/973c90af48a43a48070a56128f8ce0d0b98afbab) Thanks @tim-smart! - convert bigints to string for opentelemetry attributes\n\n## 0.59.0\n\n### Patch Changes\n\n- Updated dependencies [[`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - effect@3.19.0\n  - @effect/platform@0.93.0\n\n## 0.58.0\n\n### Minor Changes\n\n- [#5302](https://github.com/Effect-TS/effect/pull/5302) [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137) Thanks @mikearnaldi! - Automatically set otel parent when present as external span\n\n### Patch Changes\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2)]:\n  - effect@3.18.0\n  - @effect/platform@0.92.0\n\n## 0.57.0\n\n### Patch Changes\n\n- Updated dependencies [[`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a)]:\n  - @effect/platform@0.91.0\n\n## 0.56.6\n\n### Patch Changes\n\n- [#5485](https://github.com/Effect-TS/effect/pull/5485) [`f8b8d3d`](https://github.com/Effect-TS/effect/commit/f8b8d3db1a3a53069a134eaad9f4fb42117193c7) Thanks @tim-smart! - fix traceFlags propagation when set to 0\n\n- Updated dependencies [[`333be04`](https://github.com/Effect-TS/effect/commit/333be046b50e8300f5cb70b871448e0628b7b37c)]:\n  - @effect/platform@0.90.8\n\n## 0.56.5\n\n### Patch Changes\n\n- [#5444](https://github.com/Effect-TS/effect/pull/5444) [`8f8c401`](https://github.com/Effect-TS/effect/commit/8f8c4011f4b90c540c08efd2e850fe7b265e098c) Thanks @mikearnaldi! - Propagate spanId and traceId to otel logs\n\n## 0.56.4\n\n### Patch Changes\n\n- [#5413](https://github.com/Effect-TS/effect/pull/5413) [`2965aa7`](https://github.com/Effect-TS/effect/commit/2965aa7cff54d7155f291f97b0154486176e81be) Thanks @IMax153! - Remove @opentelemetry/semantic-conventions from Effect-native OTLP modules\n\n- Updated dependencies [[`84bc300`](https://github.com/Effect-TS/effect/commit/84bc3003b42ad51210e9e1248efd04c5d0e3dd1e), [`fef9771`](https://github.com/Effect-TS/effect/commit/fef9771eab24af6415be946df0c9f64eba01cef7)]:\n  - effect@3.17.8\n  - @effect/platform@0.90.5\n\n## 0.56.3\n\n### Patch Changes\n\n- [#5397](https://github.com/Effect-TS/effect/pull/5397) [`0e46e24`](https://github.com/Effect-TS/effect/commit/0e46e24c24e9edb8bf2e29835a94013e9c34d034) Thanks @IMax153! - Avoid issues with ESM builds by removing dependency on `@opentelemetry/semantic-conventions`\n\n- Updated dependencies [[`8c7bb52`](https://github.com/Effect-TS/effect/commit/8c7bb52dc78850be72566decba6222870e3733d0), [`0e46e24`](https://github.com/Effect-TS/effect/commit/0e46e24c24e9edb8bf2e29835a94013e9c34d034)]:\n  - @effect/platform@0.90.4\n\n## 0.56.2\n\n### Patch Changes\n\n- [#5380](https://github.com/Effect-TS/effect/pull/5380) [`1689874`](https://github.com/Effect-TS/effect/commit/168987408de9270b15802e7d6cc0ec42a57452d5) Thanks @tim-smart! - temporarily disable otlp exporter if endpoint can't be reached\n\n## 0.56.1\n\n### Patch Changes\n\n- [#5334](https://github.com/Effect-TS/effect/pull/5334) [`6df2620`](https://github.com/Effect-TS/effect/commit/6df262086342cb215877863e85b0562e2780a2d5) Thanks @johtso! - improve baseUrl handling in Otlp constructor\n\n## 0.56.0\n\n### Patch Changes\n\n- [#5257](https://github.com/Effect-TS/effect/pull/5257) [`d070f2e`](https://github.com/Effect-TS/effect/commit/d070f2e7d51da490ed64ce06652f4ae119fae331) Thanks @jrmdayn! - use URL constructor for joining url's in Otlp.layer\n\n- Updated dependencies [[`7813640`](https://github.com/Effect-TS/effect/commit/7813640279d9e3a3e7fc0a29bfb5c6d5fb3c270f)]:\n  - @effect/platform@0.90.0\n\n## 0.55.0\n\n### Patch Changes\n\n- Updated dependencies [[`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9), [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104), [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63), [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c), [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989), [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636), [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2), [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d)]:\n  - effect@3.17.0\n  - @effect/platform@0.89.0\n\n## 0.54.1\n\n### Patch Changes\n\n- [#5192](https://github.com/Effect-TS/effect/pull/5192) [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38) Thanks @nikelborm! - Updated deprecated OTel Resource attributes names and values.\n\n  Many of the attributes have undergone the process of deprecation not once, but twice. Most of the constants holding attribute names have been renamed. These are minor changes.\n\n  Additionally, there were numerous changes to the attribute keys themselves. These changes can be considered major.\n\n  In the `@opentelemetry/semantic-conventions` package, new attributes having ongoing discussion about them are going through a process called incubation, until a consensus about their necessity and form is reached. Otel team [recommends](https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv) devs to copy them directly into their code. Luckily, it's not necessary because all of the new attribute names and values came out of this process (some of them were changed again) and are now considered stable.\n\n  ## Reasoning for minor version bump\n\n  | Package                    | Major attribute changes                                                       | Major value changes               |\n  | -------------------------- | ----------------------------------------------------------------------------- | --------------------------------- |\n  | Clickhouse client          | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             |                                   |\n  | MsSQL client               | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             | `mssql` -> `microsoft.sql_server` |\n  | MySQL client               | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             |                                   |\n  | Pg client                  | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             |                                   |\n  | Bun SQLite client          | `db.system` -> `db.system.name`                                               |                                   |\n  | Node SQLite client         | `db.system` -> `db.system.name`                                               |                                   |\n  | React.Native SQLite client | `db.system` -> `db.system.name`                                               |                                   |\n  | Wasm SQLite client         | `db.system` -> `db.system.name`                                               |                                   |\n  | SQLite Do client           | `db.system` -> `db.system.name`                                               |                                   |\n  | LibSQL client              | `db.system` -> `db.system.name`                                               |                                   |\n  | D1 client                  | `db.system` -> `db.system.name`                                               |                                   |\n  | Kysely client              | `db.statement` -> `db.query.text`                                             |                                   |\n  | @effect/sql                | `db.statement` -> `db.query.text` <br/> `db.operation` -> `db.operation.name` |                                   |\n\n- Updated dependencies [[`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec), [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38), [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48)]:\n  - effect@3.16.14\n  - @effect/platform@0.88.1\n\n## 0.54.0\n\n### Patch Changes\n\n- Updated dependencies [[`27206d7`](https://github.com/Effect-TS/effect/commit/27206d7f0558d7fe28de57bf54f1d0cc83acc92e), [`dbabf5e`](https://github.com/Effect-TS/effect/commit/dbabf5e76fa63b050d2b6c466713c7dc59f07d3c)]:\n  - @effect/platform@0.88.0\n\n## 0.53.14\n\n### Patch Changes\n\n- Updated dependencies [[`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7), [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db)]:\n  - effect@3.16.13\n  - @effect/platform@0.87.13\n\n## 0.53.13\n\n### Patch Changes\n\n- Updated dependencies [[`32ba77a`](https://github.com/Effect-TS/effect/commit/32ba77ae304d2161362a73e8b61965332626cf2d), [`d5e25b2`](https://github.com/Effect-TS/effect/commit/d5e25b237f05670ee42b386cb40b2cb448fc11d7)]:\n  - @effect/platform@0.87.12\n\n## 0.53.12\n\n### Patch Changes\n\n- Updated dependencies [[`001392b`](https://github.com/Effect-TS/effect/commit/001392ba8bfcad101bb034348a7415012fb12f72), [`7bfb099`](https://github.com/Effect-TS/effect/commit/7bfb099cb5528511b8d63045c4fbb4dc9cb18528)]:\n  - @effect/platform@0.87.11\n\n## 0.53.11\n\n### Patch Changes\n\n- Updated dependencies [[`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0), [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0)]:\n  - @effect/platform@0.87.10\n\n## 0.53.10\n\n### Patch Changes\n\n- Updated dependencies [[`54514a2`](https://github.com/Effect-TS/effect/commit/54514a2f53166de27ad7e756dbf12194691fd4af)]:\n  - @effect/platform@0.87.9\n\n## 0.53.9\n\n### Patch Changes\n\n- Updated dependencies [[`4ce4f82`](https://github.com/Effect-TS/effect/commit/4ce4f824f6fdef492be1d35c05a490ffce518c89)]:\n  - @effect/platform@0.87.8\n\n## 0.53.8\n\n### Patch Changes\n\n- [#5161](https://github.com/Effect-TS/effect/pull/5161) [`03f4e8c`](https://github.com/Effect-TS/effect/commit/03f4e8cdb25f43e5ecddf9ba3627105d7e957185) Thanks @tim-smart! - load otel attributes from Config in Otlp modules\n\n## 0.53.7\n\n### Patch Changes\n\n- Updated dependencies [[`a9b617f`](https://github.com/Effect-TS/effect/commit/a9b617f125171ed76cd79ab46d7a924daf3b0e70), [`7e26e86`](https://github.com/Effect-TS/effect/commit/7e26e86524abcc93713d6ad7eee486638c98f7c2)]:\n  - @effect/platform@0.87.7\n\n## 0.53.6\n\n### Patch Changes\n\n- Updated dependencies [[`905da99`](https://github.com/Effect-TS/effect/commit/905da996aad665057b4ca6dba1a4af44fb8835bd)]:\n  - effect@3.16.12\n  - @effect/platform@0.87.6\n\n## 0.53.5\n\n### Patch Changes\n\n- Updated dependencies [[`2fd8676`](https://github.com/Effect-TS/effect/commit/2fd8676c803cd40000dfc3231f5daecaa0e0ebd2)]:\n  - @effect/platform@0.87.5\n\n## 0.53.4\n\n### Patch Changes\n\n- Updated dependencies [[`e82a4fd`](https://github.com/Effect-TS/effect/commit/e82a4fd60f6528d08cef1a4aba0abe0d3ba741ad)]:\n  - @effect/platform@0.87.4\n\n## 0.53.3\n\n### Patch Changes\n\n- Updated dependencies [[`1b6e396`](https://github.com/Effect-TS/effect/commit/1b6e396d699f3cbbc56b68f99055cf746529bb9e)]:\n  - @effect/platform@0.87.3\n\n## 0.53.2\n\n### Patch Changes\n\n- Updated dependencies [[`4fea68c`](https://github.com/Effect-TS/effect/commit/4fea68ca7a25a3c39a1ab68b3885534513ab0c81), [`b927954`](https://github.com/Effect-TS/effect/commit/b9279543cf5688dd8a577af80456959c615217d0), [`99590a6`](https://github.com/Effect-TS/effect/commit/99590a6ca9128eb1ede265b6670b655311995614), [`6c3e24c`](https://github.com/Effect-TS/effect/commit/6c3e24c2308f7d4a29b8f4270ab81bca22ac6bb4)]:\n  - @effect/platform@0.87.2\n  - effect@3.16.11\n\n## 0.53.1\n\n### Patch Changes\n\n- [#5107](https://github.com/Effect-TS/effect/pull/5107) [`c1a9c9d`](https://github.com/Effect-TS/effect/commit/c1a9c9d0c32ea25e890bf0e3aea23fa8d05b4d4f) Thanks @tim-smart! - add option to exclude log spans from OtlpLogger\n\n- Updated dependencies [[`faad30e`](https://github.com/Effect-TS/effect/commit/faad30ec8742916be59f9db642d0fc98225b636c)]:\n  - effect@3.16.10\n  - @effect/platform@0.87.1\n\n## 0.53.0\n\n### Patch Changes\n\n- Updated dependencies [[`b5bac9a`](https://github.com/Effect-TS/effect/commit/b5bac9ac2913fcd11b02322624f03b544eef53ba)]:\n  - @effect/platform@0.87.0\n\n## 0.52.0\n\n### Patch Changes\n\n- Updated dependencies [[`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`c23d25c`](https://github.com/Effect-TS/effect/commit/c23d25c3e7c541f1f63b28484d8c461d86c67e99), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07)]:\n  - effect@3.16.9\n  - @effect/platform@0.86.0\n\n## 0.51.2\n\n### Patch Changes\n\n- Updated dependencies [[`914a191`](https://github.com/Effect-TS/effect/commit/914a191e7cb6341a3d0e965bccd27c336cf22e44)]:\n  - @effect/platform@0.85.2\n\n## 0.51.1\n\n### Patch Changes\n\n- Updated dependencies [[`8cb98d5`](https://github.com/Effect-TS/effect/commit/8cb98d53e68330228287ce2a2e0d8a4c86bcab3b), [`db2dd3c`](https://github.com/Effect-TS/effect/commit/db2dd3c3a8a77d791eae19e66153527e1cde4e6e)]:\n  - effect@3.16.8\n  - @effect/platform@0.85.1\n\n## 0.51.0\n\n### Patch Changes\n\n- Updated dependencies [[`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e), [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e)]:\n  - @effect/platform@0.85.0\n\n## 0.50.11\n\n### Patch Changes\n\n- Updated dependencies [[`1bb0d8a`](https://github.com/Effect-TS/effect/commit/1bb0d8ab96782e99434356266b38251554ea0294)]:\n  - effect@3.16.7\n  - @effect/platform@0.84.11\n\n## 0.50.10\n\n### Patch Changes\n\n- Updated dependencies [[`a5f7595`](https://github.com/Effect-TS/effect/commit/a5f75956ef9a15a83c416517ef493f0ee2f5ee8a), [`a02470c`](https://github.com/Effect-TS/effect/commit/a02470c75579e91525a25adb3f21b3650d042fdd), [`bf369b2`](https://github.com/Effect-TS/effect/commit/bf369b2902a0e0b195d957c18b9efd180942cf8b), [`f891d45`](https://github.com/Effect-TS/effect/commit/f891d45adffdafd3f94a2eca23faa354e3a409a8)]:\n  - effect@3.16.6\n  - @effect/platform@0.84.10\n\n## 0.50.9\n\n### Patch Changes\n\n- Updated dependencies [[`bf418ef`](https://github.com/Effect-TS/effect/commit/bf418ef14a0f2ec965535793d5cea8fa8ba177ac)]:\n  - effect@3.16.5\n  - @effect/platform@0.84.9\n\n## 0.50.8\n\n### Patch Changes\n\n- Updated dependencies [[`8b9db77`](https://github.com/Effect-TS/effect/commit/8b9db7742846af0f58fd8e8b7acb7f4f5ff487ec)]:\n  - @effect/platform@0.84.8\n\n## 0.50.7\n\n### Patch Changes\n\n- Updated dependencies [[`74ab9a0`](https://github.com/Effect-TS/effect/commit/74ab9a0a9e16d6e019369d256e1e24175c8bc3f3), [`770008e`](https://github.com/Effect-TS/effect/commit/770008eca3aad2899a2ed951236e575793294b28)]:\n  - effect@3.16.4\n  - @effect/platform@0.84.7\n\n## 0.50.6\n\n### Patch Changes\n\n- Updated dependencies [[`ceea77a`](https://github.com/Effect-TS/effect/commit/ceea77a13055f145520f763e3fce5b8ff15d728f)]:\n  - @effect/platform@0.84.6\n\n## 0.50.5\n\n### Patch Changes\n\n- Updated dependencies [[`ec52c6a`](https://github.com/Effect-TS/effect/commit/ec52c6a2211e76972462b15b9d5a9d6d56761b7a)]:\n  - @effect/platform@0.84.5\n\n## 0.50.4\n\n### Patch Changes\n\n- Updated dependencies [[`87722fc`](https://github.com/Effect-TS/effect/commit/87722fce693a9b49284bbddbf82d30714c688261), [`36217ee`](https://github.com/Effect-TS/effect/commit/36217eeb1337edd9ac3f9a635b80a6385d22ae8f)]:\n  - effect@3.16.3\n  - @effect/platform@0.84.4\n\n## 0.50.3\n\n### Patch Changes\n\n- Updated dependencies [[`ab7684f`](https://github.com/Effect-TS/effect/commit/ab7684f1c2a0671bf091f255d220e3a4cc7f528e)]:\n  - @effect/platform@0.84.3\n\n## 0.50.2\n\n### Patch Changes\n\n- Updated dependencies [[`0ddf148`](https://github.com/Effect-TS/effect/commit/0ddf148a247aa87af043d276b8453a714a400897)]:\n  - effect@3.16.2\n  - @effect/platform@0.84.2\n\n## 0.50.1\n\n### Patch Changes\n\n- Updated dependencies [[`71174d0`](https://github.com/Effect-TS/effect/commit/71174d09691314a9b6b66189e456fd21e3eb6543), [`d615e6e`](https://github.com/Effect-TS/effect/commit/d615e6e5b944f6fd5e627e31752c7ca7e4e1c17d)]:\n  - @effect/platform@0.84.1\n  - effect@3.16.1\n\n## 0.50.0\n\n### Patch Changes\n\n- Updated dependencies [[`ee0bd5d`](https://github.com/Effect-TS/effect/commit/ee0bd5d24864752c54cb359f67a67dd903971ec4), [`5189800`](https://github.com/Effect-TS/effect/commit/51898004e11766b8cf6d95e960b636f6d5db79ec), [`58bfeaa`](https://github.com/Effect-TS/effect/commit/58bfeaa64ded8c88f772b184311c0c0dbac10960), [`194d748`](https://github.com/Effect-TS/effect/commit/194d7486943f56f3267ef415395ac220a4b3e634), [`918c9ea`](https://github.com/Effect-TS/effect/commit/918c9ea1a57facb154f0fb26792021f337054dee), [`9198e6f`](https://github.com/Effect-TS/effect/commit/9198e6fcc1a3ff4fefb3363004de558d8de01f40), [`2a370bf`](https://github.com/Effect-TS/effect/commit/2a370bf625fdeede5659721468eb0d527e403279), [`58ccb91`](https://github.com/Effect-TS/effect/commit/58ccb91328c8df5d49808b673738bc09df355201), [`fd47834`](https://github.com/Effect-TS/effect/commit/fd478348203fa89462b0a1d067ce4de034353df4)]:\n  - effect@3.16.0\n  - @effect/platform@0.84.0\n\n## 0.49.0\n\n### Patch Changes\n\n- Updated dependencies [[`5522520`](https://github.com/Effect-TS/effect/commit/55225206ab9af0ad60b1c0654690a8a096d625cd), [`cc5bb2b`](https://github.com/Effect-TS/effect/commit/cc5bb2b918a9450a975f702dabcea891bda382cb)]:\n  - @effect/platform@0.83.0\n  - effect@3.15.5\n\n## 0.48.8\n\n### Patch Changes\n\n- Updated dependencies [[`0617b9d`](https://github.com/Effect-TS/effect/commit/0617b9dc365f1963b36949ad7f9023ab6eb94524)]:\n  - @effect/platform@0.82.8\n\n## 0.48.7\n\n### Patch Changes\n\n- Updated dependencies [[`f570554`](https://github.com/Effect-TS/effect/commit/f57055459524587b041340577dad85476bb35f81), [`78047e8`](https://github.com/Effect-TS/effect/commit/78047e8dfc8005b66f87afe50bb95981fea51561), [`c20b95a`](https://github.com/Effect-TS/effect/commit/c20b95a99ffe452b4774c844d397a905f713b6d6), [`94ada43`](https://github.com/Effect-TS/effect/commit/94ada430928d5685bdbef513e87562c20774a3a2)]:\n  - effect@3.15.4\n  - @effect/platform@0.82.7\n\n## 0.48.6\n\n### Patch Changes\n\n- Updated dependencies [[`618903b`](https://github.com/Effect-TS/effect/commit/618903ba9ae96e2bfe6ee31f61c4359b915f2a36)]:\n  - @effect/platform@0.82.6\n\n## 0.48.5\n\n### Patch Changes\n\n- Updated dependencies [[`7764a07`](https://github.com/Effect-TS/effect/commit/7764a07d960c60df81f14e1dc949518f4bbe494a), [`4577f54`](https://github.com/Effect-TS/effect/commit/4577f548d67273e576cdde423bdd34a4b910766a), [`30a0d9c`](https://github.com/Effect-TS/effect/commit/30a0d9cb51c84290d51b1361d72ff5cee33c13c7)]:\n  - @effect/platform@0.82.5\n  - effect@3.15.3\n\n## 0.48.4\n\n### Patch Changes\n\n- Updated dependencies [[`d45e8a8`](https://github.com/Effect-TS/effect/commit/d45e8a8ac8227192f504e39e6d04fdcf4fb1d225), [`d13b68e`](https://github.com/Effect-TS/effect/commit/d13b68e3a9456d0bfee9bca8273a7b44a9c69087)]:\n  - @effect/platform@0.82.4\n\n## 0.48.3\n\n### Patch Changes\n\n- Updated dependencies [[`b8722b8`](https://github.com/Effect-TS/effect/commit/b8722b817e2306fe8c8245f3f9e32d85b824b961), [`a328f4b`](https://github.com/Effect-TS/effect/commit/a328f4b4fe717dd53e5b04a30f387433c32f7328)]:\n  - effect@3.15.2\n  - @effect/platform@0.82.3\n\n## 0.48.2\n\n### Patch Changes\n\n- Updated dependencies [[`739a3d4`](https://github.com/Effect-TS/effect/commit/739a3d4a4565915fe2e690003f4f9085cb4422fc)]:\n  - @effect/platform@0.82.2\n\n## 0.48.1\n\n### Patch Changes\n\n- Updated dependencies [[`787ce70`](https://github.com/Effect-TS/effect/commit/787ce7042e35b657963473c6efe47752868cd811), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348)]:\n  - effect@3.15.1\n  - @effect/platform@0.82.1\n\n## 0.48.0\n\n### Patch Changes\n\n- Updated dependencies [[`c654595`](https://github.com/Effect-TS/effect/commit/c65459587b51da140b78098e81fdbfece65d53e2), [`d9f5dea`](https://github.com/Effect-TS/effect/commit/d9f5deae0f02f5de2b9fcb1cca8b142ba4bc2bba), [`49aa723`](https://github.com/Effect-TS/effect/commit/49aa7236a15e13f818c86edbca08c4af67c8dfaf), [`74c14d0`](https://github.com/Effect-TS/effect/commit/74c14d01d0cb48cf517a1b6e29a373a96ed0ff5b), [`e4f49b6`](https://github.com/Effect-TS/effect/commit/e4f49b66857e01b74ab6a9a0bc7132f44cd04cbb), [`6f02224`](https://github.com/Effect-TS/effect/commit/6f02224b3fc46a682ad2defb1a260841956c6780), [`1dcfd41`](https://github.com/Effect-TS/effect/commit/1dcfd41ff96abd706901293a00c1893cb29dd8fd), [`b21ab16`](https://github.com/Effect-TS/effect/commit/b21ab16b6f773e7ec4369db4e752c35e719f7870), [`fcf1822`](https://github.com/Effect-TS/effect/commit/fcf1822f98fcda60351d64e9d2c2c13563d7e6db), [`0061dd1`](https://github.com/Effect-TS/effect/commit/0061dd140740165e91569a684cce27a77b23229e), [`8421e6e`](https://github.com/Effect-TS/effect/commit/8421e6e49332bca8f96f482dfd48680e238b3a89), [`a9b3fb7`](https://github.com/Effect-TS/effect/commit/a9b3fb78abcfdb525318a956fd02fcadeb56143e), [`fa10f56`](https://github.com/Effect-TS/effect/commit/fa10f56b96bd9af070ba99ebc3279aa93954261e)]:\n  - effect@3.15.0\n  - @effect/platform@0.82.0\n\n## 0.47.1\n\n### Patch Changes\n\n- Updated dependencies [[`24a9ebb`](https://github.com/Effect-TS/effect/commit/24a9ebbb5af598f0bfd6ecc45307e528043fe011)]:\n  - effect@3.14.22\n  - @effect/platform@0.81.1\n\n## 0.47.0\n\n### Patch Changes\n\n- Updated dependencies [[`672920f`](https://github.com/Effect-TS/effect/commit/672920f85da8abd5f9d4ad85e29248a2aca57ed8)]:\n  - @effect/platform@0.81.0\n\n## 0.46.18\n\n### Patch Changes\n\n- Updated dependencies [[`2f3b7d4`](https://github.com/Effect-TS/effect/commit/2f3b7d4e1fa1ef8790b0ca4da22eb88872ee31df)]:\n  - effect@3.14.21\n  - @effect/platform@0.80.21\n\n## 0.46.17\n\n### Patch Changes\n\n- Updated dependencies [[`17e2f30`](https://github.com/Effect-TS/effect/commit/17e2f3091408cf0fca9414d4af3bdf7b2765b378)]:\n  - effect@3.14.20\n  - @effect/platform@0.80.20\n\n## 0.46.16\n\n### Patch Changes\n\n- Updated dependencies [[`056a910`](https://github.com/Effect-TS/effect/commit/056a910d0a0b8b00b0dc9df4a070466b2b5c2f6c), [`e25e7bb`](https://github.com/Effect-TS/effect/commit/e25e7bbc1797733916f48f501425d9f2ef310d9f), [`3273d57`](https://github.com/Effect-TS/effect/commit/3273d572c2b3175a842677f19efeea4cd65ab016)]:\n  - effect@3.14.19\n  - @effect/platform@0.80.19\n\n## 0.46.15\n\n### Patch Changes\n\n- Updated dependencies [[`b1164d4`](https://github.com/Effect-TS/effect/commit/b1164d49a1dfdf299e9971367b6fc6be4df0ddff)]:\n  - effect@3.14.18\n  - @effect/platform@0.80.18\n\n## 0.46.14\n\n### Patch Changes\n\n- [#4808](https://github.com/Effect-TS/effect/pull/4808) [`b5b7da3`](https://github.com/Effect-TS/effect/commit/b5b7da31998dac258677fb51225800f313a87c86) Thanks @tim-smart! - add a shutdownTimeout option to the @effect/opentelemetry exporters\n\n- Updated dependencies [[`0b54681`](https://github.com/Effect-TS/effect/commit/0b54681cd89245e211d8f49272be0f1bf2f81813), [`41a59d5`](https://github.com/Effect-TS/effect/commit/41a59d5916a296b12b0d5ead9e859e05f40b4cce)]:\n  - effect@3.14.17\n  - @effect/platform@0.80.17\n\n## 0.46.13\n\n### Patch Changes\n\n- Updated dependencies [[`ee14444`](https://github.com/Effect-TS/effect/commit/ee144441021ec77039e43396eaf90714687bb495), [`f1c8583`](https://github.com/Effect-TS/effect/commit/f1c8583f8c3ea9415f813795ca2940a897c9ba9a)]:\n  - effect@3.14.16\n  - @effect/platform@0.80.16\n\n## 0.46.12\n\n### Patch Changes\n\n- Updated dependencies [[`239cc99`](https://github.com/Effect-TS/effect/commit/239cc995ce645946210a3c3d2cb52bd3547c0687), [`8b6c947`](https://github.com/Effect-TS/effect/commit/8b6c947eaa8e45a67ecb3c37d45cd27f3e41d165), [`c50a63b`](https://github.com/Effect-TS/effect/commit/c50a63bbecb9f560b9cae349c447eed877d1b9b6)]:\n  - effect@3.14.15\n  - @effect/platform@0.80.15\n\n## 0.46.11\n\n### Patch Changes\n\n- Updated dependencies [[`6ed8d15`](https://github.com/Effect-TS/effect/commit/6ed8d1589beb181d30abc79afebdaabc1d101538)]:\n  - effect@3.14.14\n  - @effect/platform@0.80.14\n\n## 0.46.10\n\n### Patch Changes\n\n- Updated dependencies [[`ee77788`](https://github.com/Effect-TS/effect/commit/ee77788747e7ebbde6bfa88256cde49dbbad3608), [`5fce6ba`](https://github.com/Effect-TS/effect/commit/5fce6ba19c3cc63cc0104e737e581ad989dedbf0), [`570e45f`](https://github.com/Effect-TS/effect/commit/570e45f8cb936e42ec48f67f21bb2b7252f36c0c)]:\n  - effect@3.14.13\n  - @effect/platform@0.80.13\n\n## 0.46.9\n\n### Patch Changes\n\n- [#4772](https://github.com/Effect-TS/effect/pull/4772) [`082e615`](https://github.com/Effect-TS/effect/commit/082e6157493f2ba4c943620cdaf858cbfefd7df6) Thanks @tim-smart! - include error cause in otel exception.stacktrace\n\n## 0.46.8\n\n### Patch Changes\n\n- Updated dependencies [[`c2ad9ee`](https://github.com/Effect-TS/effect/commit/c2ad9ee9f3c4c743390edf35ed9e85a20be33811), [`9c68654`](https://github.com/Effect-TS/effect/commit/9c686542b6eb3ea188cb70673ef2e41223633e89)]:\n  - effect@3.14.12\n  - @effect/platform@0.80.12\n\n## 0.46.7\n\n### Patch Changes\n\n- [#4760](https://github.com/Effect-TS/effect/pull/4760) [`43b22df`](https://github.com/Effect-TS/effect/commit/43b22df02f9504ef17b3462c2305f4e89e190763) Thanks @tim-smart! - disable tracer for Otlp http client\n\n- Updated dependencies [[`e536127`](https://github.com/Effect-TS/effect/commit/e536127c1e6f2fb3a542c73ae919435a629a346b)]:\n  - effect@3.14.11\n  - @effect/platform@0.80.11\n\n## 0.46.6\n\n### Patch Changes\n\n- Updated dependencies [[`bc7efa3`](https://github.com/Effect-TS/effect/commit/bc7efa3b031bb25e1ed3c8f2d3fb5e8da166cadc)]:\n  - effect@3.14.10\n  - @effect/platform@0.80.10\n\n## 0.46.5\n\n### Patch Changes\n\n- [#4740](https://github.com/Effect-TS/effect/pull/4740) [`b7a64c9`](https://github.com/Effect-TS/effect/commit/b7a64c90bbd7fcdedb56a2bcb1e080a3323d7699) Thanks @tim-smart! - add Otlp module to @effect/opentelemetry\n\n  This module allows you to setup an exporter for Traces, Metrics & Logs with one\n  Layer.\n\n  It also has no dependency on the @opentelemetry libraries, so you don't need to\n  add any additional deps to your package.json.\n\n  ```ts\n  import * as Otlp from \"@effect/opentelemetry/Otlp\"\n  import * as FetchHttpClient from \"@effect/platform/FetchHttpClient\"\n  import { Effect, Layer, Schedule } from \"effect\"\n\n  // Includes an Effect Tracer, Logger & Metric exporter\n  const Observability = Otlp.layer({\n    baseUrl: \"http://localhost:4318\",\n    resource: {\n      serviceName: \"my-service\"\n    }\n  }).pipe(Layer.provide(FetchHttpClient.layer))\n  ```\n\n- [#4740](https://github.com/Effect-TS/effect/pull/4740) [`b7a64c9`](https://github.com/Effect-TS/effect/commit/b7a64c90bbd7fcdedb56a2bcb1e080a3323d7699) Thanks @tim-smart! - add Effect native OtlpMetrics & OtlpLogger\n\n- Updated dependencies [[`d78249f`](https://github.com/Effect-TS/effect/commit/d78249f0b67f63cf4baf806ff090cba33293daf0)]:\n  - effect@3.14.9\n  - @effect/platform@0.80.9\n\n## 0.46.4\n\n### Patch Changes\n\n- [#4732](https://github.com/Effect-TS/effect/pull/4732) [`049f0ec`](https://github.com/Effect-TS/effect/commit/049f0ec78e9e9333daaeab67e6182632684e5310) Thanks @tim-smart! - include cause in otel exceptions\n\n## 0.46.3\n\n### Patch Changes\n\n- [#4730](https://github.com/Effect-TS/effect/pull/4730) [`d36ccc0`](https://github.com/Effect-TS/effect/commit/d36ccc0c3ce79d2f4214fc5341272812aefaca0e) Thanks @tim-smart! - adjust otel export when max batch size is reached\n\n## 0.46.2\n\n### Patch Changes\n\n- [#4727](https://github.com/Effect-TS/effect/pull/4727) [`46a64bd`](https://github.com/Effect-TS/effect/commit/46a64bd30b69176d6d2ca99823a4de02b3dcf40c) Thanks @tim-smart! - add effect native otlp exporter\n\n## 0.46.1\n\n### Patch Changes\n\n- Updated dependencies [[`b3a2d32`](https://github.com/Effect-TS/effect/commit/b3a2d32772e6f7f20eacf2e18128e99324c4d378)]:\n  - effect@3.14.8\n\n## 0.46.0\n\n### Minor Changes\n\n- [#4696](https://github.com/Effect-TS/effect/pull/4696) [`f367477`](https://github.com/Effect-TS/effect/commit/f3674777fcd4c1797ac1b46be48c3ad2d6321cfc) Thanks @titouancreach! - update otel peer dependencies to ^2.0.0 and fix breaking changes\n\n### Patch Changes\n\n- Updated dependencies [[`b542a4b`](https://github.com/Effect-TS/effect/commit/b542a4bf195be0c9af1523e1ba96c953decc4d25)]:\n  - effect@3.14.7\n\n## 0.45.6\n\n### Patch Changes\n\n- Updated dependencies [[`47618c1`](https://github.com/Effect-TS/effect/commit/47618c1ad84ebcc5a51133a3fff5aa5012d49d45), [`6077882`](https://github.com/Effect-TS/effect/commit/60778824a4794336c33807801f813f8751d1c7e4)]:\n  - effect@3.14.6\n\n## 0.45.5\n\n### Patch Changes\n\n- Updated dependencies [[`40dbfef`](https://github.com/Effect-TS/effect/commit/40dbfeff239b6e567706752114f31b2fce7de4e3), [`5a5ebdd`](https://github.com/Effect-TS/effect/commit/5a5ebdddfaddd259538b4599a6676281faca778e)]:\n  - effect@3.14.5\n\n## 0.45.4\n\n### Patch Changes\n\n- Updated dependencies [[`e4ba2c6`](https://github.com/Effect-TS/effect/commit/e4ba2c66a878e81b5e295d6d49aaf724b80a28ef)]:\n  - effect@3.14.4\n\n## 0.45.3\n\n### Patch Changes\n\n- Updated dependencies [[`37aa8e1`](https://github.com/Effect-TS/effect/commit/37aa8e137725a902e70cd1e468ea98b873aa5056), [`34f03d6`](https://github.com/Effect-TS/effect/commit/34f03d66875f21f266f102223a03cd14c2ed6ea6)]:\n  - effect@3.14.3\n\n## 0.45.2\n\n### Patch Changes\n\n- Updated dependencies [[`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`0a3e3e1`](https://github.com/Effect-TS/effect/commit/0a3e3e18eea5e0d1882f1a6c906198e6ef226a41)]:\n  - effect@3.14.2\n\n## 0.45.1\n\n### Patch Changes\n\n- Updated dependencies [[`4a274fe`](https://github.com/Effect-TS/effect/commit/4a274fe9f623182b6b902827e0e83bd89ca3b05c)]:\n  - effect@3.14.1\n\n## 0.45.0\n\n### Minor Changes\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`04dff2d`](https://github.com/Effect-TS/effect/commit/04dff2d01ac68c260f29a6d4743381825c353c86) Thanks @tim-smart! - add Tracer Span.addLinks, for dynamically linking spans\n\n### Patch Changes\n\n- Updated dependencies [[`1f47e4e`](https://github.com/Effect-TS/effect/commit/1f47e4e12546ab691b29bfb7b5128bb17b93baa5), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`04dff2d`](https://github.com/Effect-TS/effect/commit/04dff2d01ac68c260f29a6d4743381825c353c86), [`c7fac0c`](https://github.com/Effect-TS/effect/commit/c7fac0cd7eadcd5cc0c3a987051c5b57ad271638), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`ffaa3f3`](https://github.com/Effect-TS/effect/commit/ffaa3f3969df26610fcc02ad537340641d44e803), [`ab957c1`](https://github.com/Effect-TS/effect/commit/ab957c1fee714868f56c7ab4e802b9d449e9b666), [`35db9ce`](https://github.com/Effect-TS/effect/commit/35db9ce228f1416c8abacc6dc9c36fbd0f33ef0f), [`cf77ea9`](https://github.com/Effect-TS/effect/commit/cf77ea9ab4fc89e66a43f682a9926ccdee6c57ed), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`baaab60`](https://github.com/Effect-TS/effect/commit/baaab60b737f35dfab8e4a21bce28a195d19e899)]:\n  - effect@3.14.0\n\n## 0.44.12\n\n### Patch Changes\n\n- Updated dependencies [[`0c4803f`](https://github.com/Effect-TS/effect/commit/0c4803fcc69262d11a97ce49d0e9b4288df0651f), [`6f65ac4`](https://github.com/Effect-TS/effect/commit/6f65ac4eac1489cd6ea390e18b0908670722adad)]:\n  - effect@3.13.12\n\n## 0.44.11\n\n### Patch Changes\n\n- Updated dependencies [[`fad8cca`](https://github.com/Effect-TS/effect/commit/fad8cca9bbfcc2eaeb44b97c15dbe0a1eda75315), [`4296293`](https://github.com/Effect-TS/effect/commit/4296293049414d0cf2d915a26c552b09f946b9a0), [`9c241ab`](https://github.com/Effect-TS/effect/commit/9c241abe47ccf7a5257b98a4a64a63054a12741d), [`082b0c1`](https://github.com/Effect-TS/effect/commit/082b0c1b9f4252bcdd69608f2e4a9226f953ac3f), [`be12983`](https://github.com/Effect-TS/effect/commit/be12983bc7e7537b41cd8910fc4eb7d1da56ab07), [`de88127`](https://github.com/Effect-TS/effect/commit/de88127a5a5906ccece98af74787b5ae0e65e431)]:\n  - effect@3.13.11\n\n## 0.44.10\n\n### Patch Changes\n\n- Updated dependencies [[`527c964`](https://github.com/Effect-TS/effect/commit/527c9645229f5be9714a7e60a38a9e753c4bbfb1)]:\n  - effect@3.13.10\n\n## 0.44.9\n\n### Patch Changes\n\n- Updated dependencies [[`2976e52`](https://github.com/Effect-TS/effect/commit/2976e52538d9dc9ffdcbc84d4ac748cff9305971)]:\n  - effect@3.13.9\n\n## 0.44.8\n\n### Patch Changes\n\n- Updated dependencies [[`c65d336`](https://github.com/Effect-TS/effect/commit/c65d3362d07ec815ff3b46278314e8a31706ddc2), [`22d2ebb`](https://github.com/Effect-TS/effect/commit/22d2ebb4b11f5a44351a4736e65da391a3b647d0)]:\n  - effect@3.13.8\n\n## 0.44.7\n\n### Patch Changes\n\n- Updated dependencies [[`840cc73`](https://github.com/Effect-TS/effect/commit/840cc7329908db7ca693ef47b07d4f845c29cadd), [`9bf8a74`](https://github.com/Effect-TS/effect/commit/9bf8a74b967f18d931743dd5196af326c9118e9c), [`87ba23c`](https://github.com/Effect-TS/effect/commit/87ba23c41c193503ed0c612b0d32d0b253794c64)]:\n  - effect@3.13.7\n\n## 0.44.6\n\n### Patch Changes\n\n- Updated dependencies [[`3154ce4`](https://github.com/Effect-TS/effect/commit/3154ce4692fa18b804982158d3c4c8a8a5fae386)]:\n  - effect@3.13.6\n\n## 0.44.5\n\n### Patch Changes\n\n- Updated dependencies [[`367bb35`](https://github.com/Effect-TS/effect/commit/367bb35f4c2a254e1fb211d96db2474a7aed9020), [`6cf11c3`](https://github.com/Effect-TS/effect/commit/6cf11c3a75773ceec2877c85ddc760f381f0866d), [`a0acec8`](https://github.com/Effect-TS/effect/commit/a0acec851f72e19466363d24b9cc218acd00006a)]:\n  - effect@3.13.5\n\n## 0.44.4\n\n### Patch Changes\n\n- Updated dependencies [[`17d9e89`](https://github.com/Effect-TS/effect/commit/17d9e89f9851663bdbb6c1e685601d97806114a4)]:\n  - effect@3.13.4\n\n## 0.44.3\n\n### Patch Changes\n\n- Updated dependencies [[`cc5588d`](https://github.com/Effect-TS/effect/commit/cc5588df07f9103513547cb429ce041b9436a8bd), [`623c8cd`](https://github.com/Effect-TS/effect/commit/623c8cd053ed6ee3d353aaa8778d484670fca2bb), [`00b4eb1`](https://github.com/Effect-TS/effect/commit/00b4eb1ece12a16e222e6220965bb4024d6752ac), [`f2aee98`](https://github.com/Effect-TS/effect/commit/f2aee989b0a600900ce83e7f460d02908620c80f), [`fb798eb`](https://github.com/Effect-TS/effect/commit/fb798eb9061f1191badc017d1aa649360254da20), [`2251b15`](https://github.com/Effect-TS/effect/commit/2251b1528810bb695b37ce388b653cec0c5bf80c), [`2e15c1e`](https://github.com/Effect-TS/effect/commit/2e15c1e33648add0b29fe274fbcb7294b7515085), [`a4979db`](https://github.com/Effect-TS/effect/commit/a4979db021aef16e731be64df196b72088fc4376), [`b74255a`](https://github.com/Effect-TS/effect/commit/b74255a304ad49d60bedb1a260fd697f370af27a), [`d7f6a5c`](https://github.com/Effect-TS/effect/commit/d7f6a5c7d26c1963dcd864ca62360d20d08c7b49), [`9dd8979`](https://github.com/Effect-TS/effect/commit/9dd8979e940915b1cc1b1f264f3d019c77a65a02), [`477b488`](https://github.com/Effect-TS/effect/commit/477b488284f47c5469d7fba3e4065fb7e3b6556e), [`10932cb`](https://github.com/Effect-TS/effect/commit/10932cbf58fc721ada631cebec42f773ce96d3cc), [`9f6c784`](https://github.com/Effect-TS/effect/commit/9f6c78468b3b5e9ebfc38ffdfb70702901ee977b), [`2c639ec`](https://github.com/Effect-TS/effect/commit/2c639ecee332de4266e36022c989c35ae4e02105), [`886aaa8`](https://github.com/Effect-TS/effect/commit/886aaa81e06dfd3cd9391e8ea987d8cd5ada1124)]:\n  - effect@3.13.3\n\n## 0.44.2\n\n### Patch Changes\n\n- Updated dependencies [[`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f)]:\n  - effect@3.13.2\n\n## 0.44.1\n\n### Patch Changes\n\n- Updated dependencies [[`b56a211`](https://github.com/Effect-TS/effect/commit/b56a2110569fd0ec0b57ac137743e926d49f51cc)]:\n  - effect@3.13.1\n\n## 0.44.0\n\n### Patch Changes\n\n- Updated dependencies [[`8baef83`](https://github.com/Effect-TS/effect/commit/8baef83e7ff0b7bc0738b680e1ef013065386cff), [`655bfe2`](https://github.com/Effect-TS/effect/commit/655bfe29e44cc3f0fb9b4e53038f50b891c188df), [`d90cbc2`](https://github.com/Effect-TS/effect/commit/d90cbc274e2742d18671fe65aa4764c057eb6cba), [`75632bd`](https://github.com/Effect-TS/effect/commit/75632bd44b8025101d652ccbaeef898c7086c91c), [`c874a2e`](https://github.com/Effect-TS/effect/commit/c874a2e4b17e9d71904ca8375bb77b020975cb1d), [`bf865e5`](https://github.com/Effect-TS/effect/commit/bf865e5833f77fd8f6c06944ca9d507b54488301), [`f98b2b7`](https://github.com/Effect-TS/effect/commit/f98b2b7592cf20f9d85313e7f1e964cb65878138), [`de8ce92`](https://github.com/Effect-TS/effect/commit/de8ce924923eaa4e1b761a97eb45ec967389f3d5), [`cf8b2dd`](https://github.com/Effect-TS/effect/commit/cf8b2dd112f8e092ed99d78fd728db0f91c29050), [`db426a5`](https://github.com/Effect-TS/effect/commit/db426a5fb41ab84d18e3c8753a7329b4de544245), [`6862444`](https://github.com/Effect-TS/effect/commit/6862444094906ad4f2cb077ff3b9cc0b73880c8c), [`5fc8a90`](https://github.com/Effect-TS/effect/commit/5fc8a90ba46a5fd9f3b643f0b5aeadc69d717339), [`546a492`](https://github.com/Effect-TS/effect/commit/546a492e60eb2b8b048a489a474b934ea0877005), [`65c4796`](https://github.com/Effect-TS/effect/commit/65c47966ce39055f02cf5c808daabb3ea6442b0b), [`9760fdc`](https://github.com/Effect-TS/effect/commit/9760fdc37bdaef9da8b150e46b86ddfbe2ad9221), [`5b471e7`](https://github.com/Effect-TS/effect/commit/5b471e7d4317e8ee5d72bbbd3e0c9775160949ab), [`4f810cc`](https://github.com/Effect-TS/effect/commit/4f810cc2770e9f1f266851d2cb6257112c12af49)]:\n  - effect@3.13.0\n\n## 0.43.2\n\n### Patch Changes\n\n- Updated dependencies [[`4018eae`](https://github.com/Effect-TS/effect/commit/4018eaed2733241676ddb8c52416f463a8c32e35), [`543d36d`](https://github.com/Effect-TS/effect/commit/543d36d1a11452560b01ab966a82529ad5fee8c9), [`f70a65a`](https://github.com/Effect-TS/effect/commit/f70a65ac80c6635d80b12beaf4d32a9cc59fa143), [`ba409f6`](https://github.com/Effect-TS/effect/commit/ba409f69c41aeaa29e475c0630735726eaf4dbac), [`3d2e356`](https://github.com/Effect-TS/effect/commit/3d2e3565e8a43d1bdb5daee8db3b90f56d71d859)]:\n  - effect@3.12.12\n\n## 0.43.1\n\n### Patch Changes\n\n- Updated dependencies [[`b6a032f`](https://github.com/Effect-TS/effect/commit/b6a032f07bffa020a848c813881879395134fa20), [`42ddd5f`](https://github.com/Effect-TS/effect/commit/42ddd5f144ce9f9d94a036679ebbd626446d37f5), [`2fe447c`](https://github.com/Effect-TS/effect/commit/2fe447c6354d334f9c591b8a8481818f5f0e797e)]:\n  - effect@3.12.11\n\n## 0.43.0\n\n### Minor Changes\n\n- [#4371](https://github.com/Effect-TS/effect/pull/4371) [`57d1623`](https://github.com/Effect-TS/effect/commit/57d1623d78883a7e3efd00a5ccf4c2ae8273e222) Thanks @jpowersdev! - Add `LoggerProvider` support from `@opentelemetry/sdk-logs` to `@effect/opentelemetry`.\n\n### Patch Changes\n\n- [#4371](https://github.com/Effect-TS/effect/pull/4371) [`57d1623`](https://github.com/Effect-TS/effect/commit/57d1623d78883a7e3efd00a5ccf4c2ae8273e222) Thanks @jpowersdev! - Use Resource.layerFromEnv by default in NodeSdk.layer\n\n- Updated dependencies [[`e30f132`](https://github.com/Effect-TS/effect/commit/e30f132c336c9d0760bad39f82a55c7ce5159eb7), [`33fa667`](https://github.com/Effect-TS/effect/commit/33fa667c2623be1026e1ccee91bd44f73b09020a), [`87f5f28`](https://github.com/Effect-TS/effect/commit/87f5f2842e4196cb88d13f10f443ff0567e82832), [`4dbd170`](https://github.com/Effect-TS/effect/commit/4dbd170538e8fb7a36aa7c469c6f93b6c7000091)]:\n  - effect@3.12.10\n\n## 0.42.9\n\n### Patch Changes\n\n- Updated dependencies [[`1b4a4e9`](https://github.com/Effect-TS/effect/commit/1b4a4e904ef5227ec7d9114d4e417eca19eed940)]:\n  - effect@3.12.9\n\n## 0.42.8\n\n### Patch Changes\n\n- [#4380](https://github.com/Effect-TS/effect/pull/4380) [`c45b559`](https://github.com/Effect-TS/effect/commit/c45b5592b5fd1189a5c932cfe05bd7d5f6d68508) Thanks @fubhy! - Fixed module imports\n\n- Updated dependencies [[`766113c`](https://github.com/Effect-TS/effect/commit/766113c0ea3512cdb887650ead8ba314236e22ee), [`712277f`](https://github.com/Effect-TS/effect/commit/712277f949052a24b46e4aa234063a6abf395c90), [`f269122`](https://github.com/Effect-TS/effect/commit/f269122508693b111142994dd48698ddc75f3d69), [`430c846`](https://github.com/Effect-TS/effect/commit/430c846cbac05b187e3d24ac8dfee0cf22506f7c), [`7b03057`](https://github.com/Effect-TS/effect/commit/7b03057507d2dab5e6793beb9c578dedaaeb15fe), [`a9c94c8`](https://github.com/Effect-TS/effect/commit/a9c94c807755610831211a686d2fad849ab38eb4), [`107e6f0`](https://github.com/Effect-TS/effect/commit/107e6f0557a1e2d3b0dce25d62fa1e2601521752), [`65c11b9`](https://github.com/Effect-TS/effect/commit/65c11b9266ec9447c31c26fe3ed35c73bd3b81fd), [`e386d2f`](https://github.com/Effect-TS/effect/commit/e386d2f1b3ab3ac2c14ee76de11f5963d32a3df4), [`9172efb`](https://github.com/Effect-TS/effect/commit/9172efba98bc6a82353e6ec2af61ac08f038ba64)]:\n  - effect@3.12.8\n\n## 0.42.7\n\n### Patch Changes\n\n- Updated dependencies [[`8dff1d1`](https://github.com/Effect-TS/effect/commit/8dff1d1bff76cdba643cad7f0bf864300f08bc61)]:\n  - effect@3.12.7\n\n## 0.42.6\n\n### Patch Changes\n\n- Updated dependencies [[`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`8b4e75d`](https://github.com/Effect-TS/effect/commit/8b4e75d35daea807c447ca760948a717aa66bb52), [`fc5e0f0`](https://github.com/Effect-TS/effect/commit/fc5e0f0d357a0051cfa01c1ede83ffdd3cb41ab1), [`004fd2b`](https://github.com/Effect-TS/effect/commit/004fd2bbd1459e64fb1b57f02eeb791ca5ea1ea5), [`b2a31be`](https://github.com/Effect-TS/effect/commit/b2a31be85c35d891351ce4f9a2cc93ece0c257f6), [`5514d05`](https://github.com/Effect-TS/effect/commit/5514d05b5cd586ff5868b8bd41c959e95e6c33cd), [`bf5f0ae`](https://github.com/Effect-TS/effect/commit/bf5f0ae9daa0170471678e22585e8ec14ce667bb), [`3b19bcf`](https://github.com/Effect-TS/effect/commit/3b19bcfd3aaadb6c9253428622df524537c8e626), [`b064b3b`](https://github.com/Effect-TS/effect/commit/b064b3b293615fd268cc5a5647d0981eb67750b8), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`f474678`](https://github.com/Effect-TS/effect/commit/f474678bf10b8f1c80e3dc096ddc7ecf20b2b23e), [`ee187d0`](https://github.com/Effect-TS/effect/commit/ee187d098007a402844c94d04f0cd8f07695377a)]:\n  - effect@3.12.6\n\n## 0.42.5\n\n### Patch Changes\n\n- Updated dependencies [[`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`507d546`](https://github.com/Effect-TS/effect/commit/507d546bd49db31000425fb5da88c434e4291bea), [`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8db239b`](https://github.com/Effect-TS/effect/commit/8db239b9c869a3707f6566b9d9dbdf53c4df03fc), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`3179a9f`](https://github.com/Effect-TS/effect/commit/3179a9f65d23369a6a9a1f80f7750566dd28df22), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e), [`1fcbe55`](https://github.com/Effect-TS/effect/commit/1fcbe55345042d8468f6a98c84081bd00b6bcf5a), [`d9a63d9`](https://github.com/Effect-TS/effect/commit/d9a63d9d385653865954cac895065360d54cc56b)]:\n  - effect@3.12.5\n\n## 0.42.4\n\n### Patch Changes\n\n- Updated dependencies [[`5b50ea4`](https://github.com/Effect-TS/effect/commit/5b50ea4a10cf9acd51f9624b2474d9d5ded74019), [`c170a68`](https://github.com/Effect-TS/effect/commit/c170a68b6266100774461fcd6c0e0fabb60112f2), [`a66c2eb`](https://github.com/Effect-TS/effect/commit/a66c2eb473245092cd41f04c2eb2b7b02cf53718)]:\n  - effect@3.12.4\n\n## 0.42.3\n\n### Patch Changes\n\n- Updated dependencies [[`d7dac48`](https://github.com/Effect-TS/effect/commit/d7dac48a477cdfeec509dbe9f33fce6a1b02b63d), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5)]:\n  - effect@3.12.3\n\n## 0.42.2\n\n### Patch Changes\n\n- Updated dependencies [[`734af82`](https://github.com/Effect-TS/effect/commit/734af82138e78b9c57a8355b1c6b80e80d38b222), [`b63c780`](https://github.com/Effect-TS/effect/commit/b63c78010893101520448ddda7019c487cf7eedd), [`c640d77`](https://github.com/Effect-TS/effect/commit/c640d77b33ad417876f4e8ffe8574ee6cbe5607f), [`0def088`](https://github.com/Effect-TS/effect/commit/0def0887cfdb6755729a64dfd52b3b9f46b0576c)]:\n  - effect@3.12.2\n\n## 0.42.1\n\n### Patch Changes\n\n- Updated dependencies [[`302b57d`](https://github.com/Effect-TS/effect/commit/302b57d2cbf9b9ccc17450945aeebfb33cfe8d43), [`0988083`](https://github.com/Effect-TS/effect/commit/0988083d4594938590df5a287e5b27d38526dd07), [`8b46be6`](https://github.com/Effect-TS/effect/commit/8b46be6a3b8160362ab5ea9171c5e6932505125c), [`bfe8027`](https://github.com/Effect-TS/effect/commit/bfe802734b450a4b4ee069d1125dd37995db2bff), [`16dd657`](https://github.com/Effect-TS/effect/commit/16dd657033d8afac2ffea567b3c8bb27c9b249b6), [`39db211`](https://github.com/Effect-TS/effect/commit/39db211414e90c8db8fdad7dc8ce5b4661bcfaef)]:\n  - effect@3.12.1\n\n## 0.42.0\n\n### Patch Changes\n\n- Updated dependencies [[`abb22a4`](https://github.com/Effect-TS/effect/commit/abb22a429b9c52c31e84856294f175d2064a9b4d), [`f369a89`](https://github.com/Effect-TS/effect/commit/f369a89e98bc682969803b9304adaf4557bb36c2), [`642376c`](https://github.com/Effect-TS/effect/commit/642376c63fd7d78754db991631a4d50a5dc79aa3), [`3d2b7a7`](https://github.com/Effect-TS/effect/commit/3d2b7a7e942a7157afae5b1cdbc6f3fef116428e), [`73f9c6f`](https://github.com/Effect-TS/effect/commit/73f9c6f2ff091512cf904cc54ab59965b86e87c8), [`17cb451`](https://github.com/Effect-TS/effect/commit/17cb4514590e8a86263f7aed009f24da8a237342), [`d801820`](https://github.com/Effect-TS/effect/commit/d80182060c2ee945d7e0e4728812abf9465a0d6a), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1), [`c11f3a6`](https://github.com/Effect-TS/effect/commit/c11f3a60a05c3b5fc8e7ce90136728154dc505b0), [`618f7e0`](https://github.com/Effect-TS/effect/commit/618f7e092a1011e5090dca1e69b5e9285689654b), [`c0ba834`](https://github.com/Effect-TS/effect/commit/c0ba834d1995cf5a8b250e4780fd43f3e3881151), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1)]:\n  - effect@3.12.0\n\n## 0.41.8\n\n### Patch Changes\n\n- Updated dependencies [[`39457d4`](https://github.com/Effect-TS/effect/commit/39457d4897d9bc7df8af5c05d352866bbeae82eb), [`a475cc2`](https://github.com/Effect-TS/effect/commit/a475cc25fd7c9f26b27a8e98f8fbe43cc9e6ee3e), [`199214e`](https://github.com/Effect-TS/effect/commit/199214e21c616d8a0ccd7ed5f92e944e6c580193), [`b3c160d`](https://github.com/Effect-TS/effect/commit/b3c160d7a1fdfc2d3fb2440530f1ab80efc65133)]:\n  - effect@3.11.10\n\n## 0.41.7\n\n### Patch Changes\n\n- Updated dependencies [[`1c08a0b`](https://github.com/Effect-TS/effect/commit/1c08a0b8505badcffb4d9cade5a746ea90c9557e), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd)]:\n  - effect@3.11.9\n\n## 0.41.6\n\n### Patch Changes\n\n- Updated dependencies [[`1a6b52d`](https://github.com/Effect-TS/effect/commit/1a6b52dcf020d36e38a7bc90b648152cf5a8ccba)]:\n  - effect@3.11.8\n\n## 0.41.5\n\n### Patch Changes\n\n- Updated dependencies [[`2408616`](https://github.com/Effect-TS/effect/commit/24086163b60b09cc6d0885bd565ef080dcbe866b), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`8d978c5`](https://github.com/Effect-TS/effect/commit/8d978c53f6fcc98d9d645ecba3e4b55d4297dd36), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e)]:\n  - effect@3.11.7\n\n## 0.41.4\n\n### Patch Changes\n\n- Updated dependencies [[`662d1ce`](https://github.com/Effect-TS/effect/commit/662d1ce6fb7da384a95888d5b2bb5605bdf3208d), [`31c62d8`](https://github.com/Effect-TS/effect/commit/31c62d83cbdcf9850a8b5331faa239601c60f78a)]:\n  - effect@3.11.6\n\n## 0.41.3\n\n### Patch Changes\n\n- Updated dependencies [[`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`22905cf`](https://github.com/Effect-TS/effect/commit/22905cf5addfb1ff3d2a6135c52036be958ae911), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`1e59e4f`](https://github.com/Effect-TS/effect/commit/1e59e4fd778da18296812a2a32f36ca8ae50f60d), [`8d914e5`](https://github.com/Effect-TS/effect/commit/8d914e504e7a22d0ea628e8af265ee450ff9530f), [`03bb00f`](https://github.com/Effect-TS/effect/commit/03bb00faa74f9e168a54a8cc0828a664fbb1ab05), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`14e1149`](https://github.com/Effect-TS/effect/commit/14e1149f1af5a022f06eb8c2e4ba9fec17fe7426), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8)]:\n  - effect@3.11.5\n\n## 0.41.2\n\n### Patch Changes\n\n- Updated dependencies [[`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f)]:\n  - effect@3.11.4\n\n## 0.41.1\n\n### Patch Changes\n\n- Updated dependencies [[`90906f7`](https://github.com/Effect-TS/effect/commit/90906f7f154b12c7182e8f39e3c55ef3937db857), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`343b6aa`](https://github.com/Effect-TS/effect/commit/343b6aa6ac4a74276bfc7c63ccbf4a1d72bc1bed), [`afba339`](https://github.com/Effect-TS/effect/commit/afba339adc11dad56b5a3b7ca94487e58f34d613)]:\n  - effect@3.11.3\n\n## 0.41.0\n\n### Minor Changes\n\n- [#4070](https://github.com/Effect-TS/effect/pull/4070) [`ac662f4`](https://github.com/Effect-TS/effect/commit/ac662f44646bb3370528e76b0545cf485bcf659c) Thanks @tim-smart! - ensure opentelemetry tags have unique identifiers\n\n### Patch Changes\n\n- [#4070](https://github.com/Effect-TS/effect/pull/4070) [`ac662f4`](https://github.com/Effect-TS/effect/commit/ac662f44646bb3370528e76b0545cf485bcf659c) Thanks @tim-smart! - expose Otel Tracer in Tracer layers\n\n## 0.40.2\n\n### Patch Changes\n\n- Updated dependencies [[`01cee56`](https://github.com/Effect-TS/effect/commit/01cee560b58d94b24cc20e98083251b73e658b41)]:\n  - effect@3.11.2\n\n## 0.40.1\n\n### Patch Changes\n\n- Updated dependencies [[`dd8a2d8`](https://github.com/Effect-TS/effect/commit/dd8a2d8e80d33b16719fc69361eaedf0b59d4620), [`a71bfef`](https://github.com/Effect-TS/effect/commit/a71bfef46f5061bb2502a61a333638a987b62273)]:\n  - effect@3.11.1\n\n## 0.40.0\n\n### Patch Changes\n\n- Updated dependencies [[`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`6e69493`](https://github.com/Effect-TS/effect/commit/6e694930048bbaf98110f35f41566aeb9752d471), [`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`5eff3f6`](https://github.com/Effect-TS/effect/commit/5eff3f6fa3aae7e86948a62cbfd63b8d6c3bdf92), [`d9fe79b`](https://github.com/Effect-TS/effect/commit/d9fe79bb5a3fe105d8e7a3bc2922a8ad936a5d10), [`251d189`](https://github.com/Effect-TS/effect/commit/251d189420bbba71990574e91098c499065f9a9b), [`5a259f3`](https://github.com/Effect-TS/effect/commit/5a259f3711b4369f55d885b568bdb21136155261), [`b4ce4ea`](https://github.com/Effect-TS/effect/commit/b4ce4ea7fd514a7e572f2dcd879c98f334981b0e), [`15fcc5a`](https://github.com/Effect-TS/effect/commit/15fcc5a0ea4bbf40ab48fa6a04fdda74f76f4c07), [`9bc9a47`](https://github.com/Effect-TS/effect/commit/9bc9a476800dc645903c888a68bb1d3baa3383c6), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb), [`1e2747c`](https://github.com/Effect-TS/effect/commit/1e2747c63a4820d1459cbbc88c71212983bd68bd), [`9264162`](https://github.com/Effect-TS/effect/commit/9264162a82783a651776fb7b87604564a63e7070), [`e0b9b09`](https://github.com/Effect-TS/effect/commit/e0b9b09e70c386b2da17d1f0a15b0511861c89e8), [`c36f3b9`](https://github.com/Effect-TS/effect/commit/c36f3b95df5ce9d71b66f22f26ce12eda8d3e848), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb)]:\n  - effect@3.11.0\n\n## 0.39.20\n\n### Patch Changes\n\n- Updated dependencies [[`3069614`](https://github.com/Effect-TS/effect/commit/30696149271129fc618f6f2ccd1d8f2f6c0f9cd7), [`09a5e52`](https://github.com/Effect-TS/effect/commit/09a5e522fd9b221f05d85b1d1c8a740d4973c302)]:\n  - effect@3.10.20\n\n## 0.39.19\n\n### Patch Changes\n\n- Updated dependencies [[`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1), [`54addee`](https://github.com/Effect-TS/effect/commit/54addee438a644bf010646c52042c7b89c5fc0a7)]:\n  - effect@3.10.19\n\n## 0.39.18\n\n### Patch Changes\n\n- Updated dependencies [[`af409cf`](https://github.com/Effect-TS/effect/commit/af409cf1d2ff973be11cc079ea373eaeedca25de)]:\n  - effect@3.10.18\n\n## 0.39.17\n\n### Patch Changes\n\n- Updated dependencies [[`42c4ce6`](https://github.com/Effect-TS/effect/commit/42c4ce6f8d8c7d847e97757650a8ad9419a829d7)]:\n  - effect@3.10.17\n\n## 0.39.16\n\n### Patch Changes\n\n- Updated dependencies [[`4dca30c`](https://github.com/Effect-TS/effect/commit/4dca30cfcdafe4542e236489f71d6f171a5b4e38), [`1d99867`](https://github.com/Effect-TS/effect/commit/1d998671be3cd11043f232822e91dd8c98fccfa9), [`6dae414`](https://github.com/Effect-TS/effect/commit/6dae4147991a97ec14a99289bd25fadae7541e8d), [`6b0d737`](https://github.com/Effect-TS/effect/commit/6b0d737078bf63b97891e6bc47affc04b28f9cf7), [`d8356aa`](https://github.com/Effect-TS/effect/commit/d8356aad428a0c2290db52380220f81d9ec94232)]:\n  - effect@3.10.16\n\n## 0.39.15\n\n### Patch Changes\n\n- Updated dependencies [[`8398b32`](https://github.com/Effect-TS/effect/commit/8398b3208242a88239d4449910b7baf923cfe3b6), [`72e55b7`](https://github.com/Effect-TS/effect/commit/72e55b7c610784fcebdbadc592c876e23e76a986)]:\n  - effect@3.10.15\n\n## 0.39.14\n\n### Patch Changes\n\n- Updated dependencies [[`f983946`](https://github.com/Effect-TS/effect/commit/f9839467b4cad6e788297764ef9f9f0b9fd203f9), [`2d8a750`](https://github.com/Effect-TS/effect/commit/2d8a75081eb83a0a81f817fdf6f428369c5064ab)]:\n  - effect@3.10.14\n\n## 0.39.13\n\n### Patch Changes\n\n- Updated dependencies [[`995bbdf`](https://github.com/Effect-TS/effect/commit/995bbdffea2e332f203cd5b474cd6a1c77dfa6ae)]:\n  - effect@3.10.13\n\n## 0.39.12\n\n### Patch Changes\n\n- Updated dependencies [[`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6)]:\n  - effect@3.10.12\n\n## 0.39.11\n\n### Patch Changes\n\n- Updated dependencies [[`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a)]:\n  - effect@3.10.11\n\n## 0.39.10\n\n### Patch Changes\n\n- Updated dependencies [[`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`b631f40`](https://github.com/Effect-TS/effect/commit/b631f40abbe649b2a089764585b5c39f6a695ac6)]:\n  - effect@3.10.10\n\n## 0.39.9\n\n### Patch Changes\n\n- Updated dependencies [[`a123e80`](https://github.com/Effect-TS/effect/commit/a123e80f111a625428a5b5622b7f55ee1073566b), [`bd5fcd3`](https://github.com/Effect-TS/effect/commit/bd5fcd3e6b603b1e505af90d6a00627c8eca6d41), [`0289d3b`](https://github.com/Effect-TS/effect/commit/0289d3b6391031d00329365bab9791b355031fe3), [`7386b71`](https://github.com/Effect-TS/effect/commit/7386b710e5be570e17f468928a6ed19d549a3e12), [`4211a23`](https://github.com/Effect-TS/effect/commit/4211a2355bb3af3f0e756e2aae9d293379f25662)]:\n  - effect@3.10.9\n\n## 0.39.8\n\n### Patch Changes\n\n- [#3874](https://github.com/Effect-TS/effect/pull/3874) [`c348b4a`](https://github.com/Effect-TS/effect/commit/c348b4abf07b3dec4ba9bb64ec38615e87e1b195) Thanks @jbmusso! - Fix WebSdk.layer not properly infering when passing an evaluate argument of type Effect\n\n- Updated dependencies [[`68b5c9e`](https://github.com/Effect-TS/effect/commit/68b5c9e44f34192cef26e1cadda5e661a027df41), [`9c9928d`](https://github.com/Effect-TS/effect/commit/9c9928dfeacd9ac33dc37eb0ca3d7d8c39175ada), [`6306e66`](https://github.com/Effect-TS/effect/commit/6306e6656092b350d4ede5746da6f245ec9f7e07), [`361c7f3`](https://github.com/Effect-TS/effect/commit/361c7f39a2c10ede9324847c3d3ba192a6f9b20a)]:\n  - effect@3.10.8\n\n## 0.39.7\n\n### Patch Changes\n\n- Updated dependencies [[`33f5b9f`](https://github.com/Effect-TS/effect/commit/33f5b9ffaebea4f1bd0e391b44c41fb6230e743a), [`50f0281`](https://github.com/Effect-TS/effect/commit/50f0281b0d2116726b8927a6217622d5f394f3e4)]:\n  - effect@3.10.7\n\n## 0.39.6\n\n### Patch Changes\n\n- Updated dependencies [[`ce1c21f`](https://github.com/Effect-TS/effect/commit/ce1c21ffc11902ac9ab453a51904207859d38552)]:\n  - effect@3.10.6\n\n## 0.39.5\n\n### Patch Changes\n\n- Updated dependencies [[`3a6d757`](https://github.com/Effect-TS/effect/commit/3a6d757badeebe00d8ef4d67530d073c8264dcfa), [`59d813a`](https://github.com/Effect-TS/effect/commit/59d813aa4973d1115cfc70cc3667508335f49693)]:\n  - effect@3.10.5\n\n## 0.39.4\n\n### Patch Changes\n\n- Updated dependencies [[`2367708`](https://github.com/Effect-TS/effect/commit/2367708be449f9526a2047e321302d7bfb16f18e)]:\n  - effect@3.10.4\n\n## 0.39.3\n\n### Patch Changes\n\n- Updated dependencies [[`b9423d8`](https://github.com/Effect-TS/effect/commit/b9423d8bf8181a2389fdbce1e3c14ac6fe8d54f5)]:\n  - effect@3.10.3\n\n## 0.39.2\n\n### Patch Changes\n\n- Updated dependencies [[`714e119`](https://github.com/Effect-TS/effect/commit/714e11945e45e5a2554ee058e6c43f82a8e309cf), [`c1afd55`](https://github.com/Effect-TS/effect/commit/c1afd55c54e61f9c432823d21b3d016f79160a37)]:\n  - effect@3.10.2\n\n## 0.39.1\n\n### Patch Changes\n\n- Updated dependencies [[`9604d6b`](https://github.com/Effect-TS/effect/commit/9604d6b616435103dafea8b53637a9d1450b4750)]:\n  - effect@3.10.1\n\n## 0.39.0\n\n### Patch Changes\n\n- Updated dependencies [[`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`c79c4c1`](https://github.com/Effect-TS/effect/commit/c79c4c178390fe61ff6dda88c9e058862349343a), [`38d30f0`](https://github.com/Effect-TS/effect/commit/38d30f08b8da62f9c3e308b9250738cb8d17bdb5), [`5821ce3`](https://github.com/Effect-TS/effect/commit/5821ce3455b47d25e0a40cae6ce22af9db5fa556)]:\n  - effect@3.10.0\n\n## 0.38.2\n\n### Patch Changes\n\n- Updated dependencies [[`61a99b2`](https://github.com/Effect-TS/effect/commit/61a99b2bf9d757870ef0c2ec9d4c877cdd364a3d)]:\n  - effect@3.9.2\n\n## 0.38.1\n\n### Patch Changes\n\n- Updated dependencies [[`3b2ad1d`](https://github.com/Effect-TS/effect/commit/3b2ad1d58a2e33dc1a72b7037396bd25ca1702a9)]:\n  - effect@3.9.1\n\n## 0.38.0\n\n### Minor Changes\n\n- [#3737](https://github.com/Effect-TS/effect/pull/3737) [`6fc1e02`](https://github.com/Effect-TS/effect/commit/6fc1e020623dc10ece26572350db6ef824f8734d) Thanks @tim-smart! - remove Tracer.withActiveSpan\n\n### Patch Changes\n\n- [#3737](https://github.com/Effect-TS/effect/pull/3737) [`6fc1e02`](https://github.com/Effect-TS/effect/commit/6fc1e020623dc10ece26572350db6ef824f8734d) Thanks @tim-smart! - add Tracer.withSpanContext\n\n  This api is useful for attaching a parent span to an Effect from an opentelemetry\n  span outside of Effect.\n\n  ```typescript\n  import { Effect } from \"effect\"\n  import { Tracer } from \"@effect/opentelemetry\"\n  import * as OtelApi from \"@opentelemetry/api\"\n\n  await OtelApi.trace.getTracer(\"test\").startActiveSpan(\n    \"otel-span\",\n    {\n      root: true\n    },\n    async (span) => {\n      try {\n        await Effect.runPromise(\n          Effect.log(\"inside otel parent span\").pipe(\n            Tracer.withSpanContext(span.spanContext())\n          )\n        )\n      } finally {\n        span.end()\n      }\n    }\n  )\n  ```\n\n- Updated dependencies [[`ff3d1aa`](https://github.com/Effect-TS/effect/commit/ff3d1aab290b4d1173b2dfc7e4c76abb4babdc16), [`0ba66f2`](https://github.com/Effect-TS/effect/commit/0ba66f2451641fd6990e02ec1ed01c014db9dab0), [`bf77f51`](https://github.com/Effect-TS/effect/commit/bf77f51b323c383224ebf08adf77a7a6e8c9b3cd), [`016f9ad`](https://github.com/Effect-TS/effect/commit/016f9ad931a4b3d09a34e5caf13d87c5b8e9c984), [`0779681`](https://github.com/Effect-TS/effect/commit/07796813f07de035719728733096ba64ce333469), [`534129f`](https://github.com/Effect-TS/effect/commit/534129f8113ce1a8ec50828083e16da9c86326c6), [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda), [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03), [`9237ac6`](https://github.com/Effect-TS/effect/commit/9237ac69bc07de5b3b60076a0ad2921c21de7457), [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03), [`5b36494`](https://github.com/Effect-TS/effect/commit/5b364942e9a9003fdb8217324f8a2d8369c969da), [`c716adb`](https://github.com/Effect-TS/effect/commit/c716adb250ebbea1d1048d818ef7fed4f621d186), [`4986391`](https://github.com/Effect-TS/effect/commit/49863919cd8628c962a712fb1df30d2983820933), [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda), [`d1387ae`](https://github.com/Effect-TS/effect/commit/d1387aebd1ff01bbebde26be46d488956e4daef6)]:\n  - effect@3.9.0\n\n## 0.37.6\n\n### Patch Changes\n\n- Updated dependencies [[`88e85db`](https://github.com/Effect-TS/effect/commit/88e85db34bd402526e27a323e950d053fa34d232), [`83887ca`](https://github.com/Effect-TS/effect/commit/83887ca1b1793916913d8550a4db4450cd14a044), [`5266b6c`](https://github.com/Effect-TS/effect/commit/5266b6cd86d76c3886da041c8829bca04b1a3110), [`cdead5c`](https://github.com/Effect-TS/effect/commit/cdead5c9cfd54dc6c4f215d9732f654c4a12e991), [`766a8af`](https://github.com/Effect-TS/effect/commit/766a8af307b414aca3648d91c4eab7493a5ec862)]:\n  - effect@3.8.5\n\n## 0.37.5\n\n### Patch Changes\n\n- [#3705](https://github.com/Effect-TS/effect/pull/3705) [`534abce`](https://github.com/Effect-TS/effect/commit/534abce3c9455ee2612f51d2d1449b4e0510fbe4) Thanks @Schniz! - add withActiveSpan function to attach Effect to current Span\n\n  This function allows you to connect the Effect spans into a parent span\n  that was created outside of Effect, using the OpenTelemetry context propagation:\n\n  ```ts\n  Effect.gen(function* () {\n    yield* Effect.sleep(\"100 millis\").pipe(Effect.withSpan(\"sleep\"))\n    yield* Console.log(\"done\")\n  }).pipe(\n    Effect.withSpan(\"program\"),\n    // This connects child spans to the current OpenTelemetry context\n    Tracer.withActiveSpan\n  )\n  ```\n\n## 0.37.4\n\n### Patch Changes\n\n- Updated dependencies [[`4509656`](https://github.com/Effect-TS/effect/commit/45096569d50262275ee984f44c456f5c83b62683)]:\n  - effect@3.8.4\n\n## 0.37.3\n\n### Patch Changes\n\n- [#3644](https://github.com/Effect-TS/effect/pull/3644) [`bb5ec6b`](https://github.com/Effect-TS/effect/commit/bb5ec6b4b6a6f537394596c5a596faf52cb2aef4) Thanks @tim-smart! - fix encoding of logs to tracer span events\n\n- Updated dependencies [[`bb5ec6b`](https://github.com/Effect-TS/effect/commit/bb5ec6b4b6a6f537394596c5a596faf52cb2aef4)]:\n  - effect@3.8.3\n\n## 0.37.2\n\n### Patch Changes\n\n- Updated dependencies [[`f0d8ef1`](https://github.com/Effect-TS/effect/commit/f0d8ef1ce97ec2a87b09b3e24150cfeab85d6e2f)]:\n  - effect@3.8.2\n\n## 0.37.1\n\n### Patch Changes\n\n- Updated dependencies [[`10bf621`](https://github.com/Effect-TS/effect/commit/10bf6213f36d8ddb00f058a4609b85220f3d8334), [`ae36fa6`](https://github.com/Effect-TS/effect/commit/ae36fa68f754eeab9a54b6dc0f8b44db513aa2b6)]:\n  - effect@3.8.1\n\n## 0.37.0\n\n### Minor Changes\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`007289a`](https://github.com/Effect-TS/effect/commit/007289a52d5877f8e90e2dacf38171ff9bf603fd) Thanks @mikearnaldi! - Cache some fiber references in the runtime to optimize reading in hot-paths\n\n### Patch Changes\n\n- Updated dependencies [[`fcfa6ee`](https://github.com/Effect-TS/effect/commit/fcfa6ee30ffd07d998bf22799357bf58580a116f), [`bb9931b`](https://github.com/Effect-TS/effect/commit/bb9931b62e249a3b801f2cb9d097aec0c8511af7), [`5798f76`](https://github.com/Effect-TS/effect/commit/5798f7619529de33e5ba06f551806f68fedc19db), [`5f0bfa1`](https://github.com/Effect-TS/effect/commit/5f0bfa17205398d4e4818bfbcf9e1b505b3b1fc5), [`812a4e8`](https://github.com/Effect-TS/effect/commit/812a4e86e2d1aa23b477ef5829aa0e5c07784936), [`273565e`](https://github.com/Effect-TS/effect/commit/273565e7901639e8d0541930ab715aea9c80fbaa), [`569a801`](https://github.com/Effect-TS/effect/commit/569a8017ef0a0bc203e4312867cbdd37b0effbd7), [`aa1fa53`](https://github.com/Effect-TS/effect/commit/aa1fa5301e886b9657c8eb0d38cb87cef92a8305), [`02f6b06`](https://github.com/Effect-TS/effect/commit/02f6b0660e12bee1069532a9cc18d3ab855257be), [`12b893e`](https://github.com/Effect-TS/effect/commit/12b893e63cc6dfada4aca7773b4783940e2edf25), [`bbad27e`](https://github.com/Effect-TS/effect/commit/bbad27ec0a90860593f759405caa877e7f4a655f), [`adf7d7a`](https://github.com/Effect-TS/effect/commit/adf7d7a7dfce3a7021e9f3b0d847dc85be89d754), [`007289a`](https://github.com/Effect-TS/effect/commit/007289a52d5877f8e90e2dacf38171ff9bf603fd), [`42a8f99`](https://github.com/Effect-TS/effect/commit/42a8f99740eefdaf2c4544d2c345313f97547a36), [`eebfd29`](https://github.com/Effect-TS/effect/commit/eebfd29633fd5d38b505c5c0842036f61f05e913), [`040703d`](https://github.com/Effect-TS/effect/commit/040703d0e100cd5511e52d812c15492414262b5e)]:\n  - effect@3.8.0\n\n## 0.36.3\n\n### Patch Changes\n\n- Updated dependencies [[`35a0f81`](https://github.com/Effect-TS/effect/commit/35a0f813141652d696461cd5d19fd146adaf85be)]:\n  - effect@3.7.3\n\n## 0.36.2\n\n### Patch Changes\n\n- Updated dependencies [[`8a601d7`](https://github.com/Effect-TS/effect/commit/8a601d7a1f8ffe52ac9e6d67e9282a1495fe59c9), [`353ba19`](https://github.com/Effect-TS/effect/commit/353ba19f9b2b9e959f0a00d058c6d40a4bc02db7)]:\n  - effect@3.7.2\n\n## 0.36.1\n\n### Patch Changes\n\n- Updated dependencies [[`79859e7`](https://github.com/Effect-TS/effect/commit/79859e71040d8edf1868b8530b90c650f4321eff), [`f6a469c`](https://github.com/Effect-TS/effect/commit/f6a469c190b9f00eee5ea0cd4d5912a0ef8b46f5), [`dcb9ec0`](https://github.com/Effect-TS/effect/commit/dcb9ec0db443894dd204d87450f779c44b9ad7f1), [`79aa6b1`](https://github.com/Effect-TS/effect/commit/79aa6b136e1f29b36f34e88cb2ff162bff2bb4ed)]:\n  - effect@3.7.1\n\n## 0.36.0\n\n### Patch Changes\n\n- Updated dependencies [[`db89601`](https://github.com/Effect-TS/effect/commit/db89601ee9c1050c4e762b7bd7ec65a6a2799dfe), [`2f456cc`](https://github.com/Effect-TS/effect/commit/2f456cce5012b9fcb6b4e039190d527813b75b92), [`8745e41`](https://github.com/Effect-TS/effect/commit/8745e41ed96e3765dc6048efc2a9afbe05c8a1e9), [`e557838`](https://github.com/Effect-TS/effect/commit/e55783886b046d3c5f33447f455f9ccf2fa75922), [`d6e7e40`](https://github.com/Effect-TS/effect/commit/d6e7e40b1e2ad0c59aa02f07344d28601b14ebdc), [`8356321`](https://github.com/Effect-TS/effect/commit/8356321598da04bd77c1001f45a4e447bec5591d), [`192f2eb`](https://github.com/Effect-TS/effect/commit/192f2ebb2c4ddbf4bfd8baedd32140b2376868f4), [`718cb70`](https://github.com/Effect-TS/effect/commit/718cb70038629a6d58d02e407760e341f7c94474), [`e9d0310`](https://github.com/Effect-TS/effect/commit/e9d03107acbf204d9304f3e8aea0816b7d3c7dfb), [`6bf28f7`](https://github.com/Effect-TS/effect/commit/6bf28f7e3b1e5e0608ff567205fea0581d11666f)]:\n  - effect@3.7.0\n\n## 0.35.8\n\n### Patch Changes\n\n- Updated dependencies [[`e809286`](https://github.com/Effect-TS/effect/commit/e8092865900608c4df7a6b7991b1c13cc1e4ca2d)]:\n  - effect@3.6.8\n\n## 0.35.7\n\n### Patch Changes\n\n- Updated dependencies [[`50ec889`](https://github.com/Effect-TS/effect/commit/50ec8897a49b7d1fe84f63107f89d543c52f3dfc)]:\n  - effect@3.6.7\n\n## 0.35.6\n\n### Patch Changes\n\n- Updated dependencies [[`f960bf4`](https://github.com/Effect-TS/effect/commit/f960bf45239e9badac6e0ad3a602f4174cd7bbdf), [`46a575f`](https://github.com/Effect-TS/effect/commit/46a575f48a05457b782fb21f7827d338c9b59320)]:\n  - effect@3.6.6\n\n## 0.35.5\n\n### Patch Changes\n\n- Updated dependencies [[`14a47a8`](https://github.com/Effect-TS/effect/commit/14a47a8c1f3cff2186b8fe7a919a1d773888fb5b), [`0c09841`](https://github.com/Effect-TS/effect/commit/0c0984173be3d58f050b300a1a8aa89d76ba49ae)]:\n  - effect@3.6.5\n\n## 0.35.4\n\n### Patch Changes\n\n- Updated dependencies [[`8295281`](https://github.com/Effect-TS/effect/commit/8295281ae9bd7441e680402540bf3c8682ec417b), [`c940df6`](https://github.com/Effect-TS/effect/commit/c940df63800bf3c4396d91cf28ec34938642fd2c), [`00b6c6d`](https://github.com/Effect-TS/effect/commit/00b6c6d4001f5de728b7d990a1b14560b4961a63), [`f8d95a6`](https://github.com/Effect-TS/effect/commit/f8d95a61ad0762147933c5c32bb6d7237e18eef4)]:\n  - effect@3.6.4\n\n## 0.35.3\n\n### Patch Changes\n\n- Updated dependencies [[`04adcac`](https://github.com/Effect-TS/effect/commit/04adcace913e6fc483df266874a68005e9e04ccf)]:\n  - effect@3.6.3\n\n## 0.35.2\n\n### Patch Changes\n\n- Updated dependencies [[`fd4b2f6`](https://github.com/Effect-TS/effect/commit/fd4b2f6516b325740dde615f1cf0229edf13ca0c)]:\n  - effect@3.6.2\n\n## 0.35.1\n\n### Patch Changes\n\n- Updated dependencies [[`510a34d`](https://github.com/Effect-TS/effect/commit/510a34d4cc5d2f51347a53847f6c7db84d2b17c6), [`45dbb9f`](https://github.com/Effect-TS/effect/commit/45dbb9ffeaf93d9e4df99d0cd4920e41ba9a3978)]:\n  - effect@3.6.1\n\n## 0.35.0\n\n### Patch Changes\n\n- Updated dependencies [[`1e0fe80`](https://github.com/Effect-TS/effect/commit/1e0fe802b36c257971296617473ce0abe730e8dc), [`8135294`](https://github.com/Effect-TS/effect/commit/8135294b591ea94fde7e6f94a504608f0e630520), [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987), [`3845646`](https://github.com/Effect-TS/effect/commit/3845646828e98f3c7cda1217f6cfe5f642ac0603), [`2d09078`](https://github.com/Effect-TS/effect/commit/2d09078c5948b37fc2f79ef858fe4ca3e4814085), [`4bce5a0`](https://github.com/Effect-TS/effect/commit/4bce5a0274203550ccf117d830721891b0a3d182), [`4ddbff0`](https://github.com/Effect-TS/effect/commit/4ddbff0bb4e3ffddfeb509c59835b83245fb975e), [`e74cc38`](https://github.com/Effect-TS/effect/commit/e74cc38cb420a320c4d7ef98180f19d452a8b316), [`bb069b4`](https://github.com/Effect-TS/effect/commit/bb069b49ef291c532a02c1e8e74271f6d1bb32ec), [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987), [`7d02174`](https://github.com/Effect-TS/effect/commit/7d02174af3bcbf054e5cdddb821c91d0f47e8285)]:\n  - effect@3.6.0\n\n## 0.34.42\n\n### Patch Changes\n\n- Updated dependencies [[`6359644`](https://github.com/Effect-TS/effect/commit/635964446323cf55d4060559337e710e4a24496e), [`7f41e42`](https://github.com/Effect-TS/effect/commit/7f41e428830bf3043b8be0d28dcd235d5747c942), [`f566fd1`](https://github.com/Effect-TS/effect/commit/f566fd1d7eea531a0d981dd24037f14a603a1273)]:\n  - effect@3.5.9\n\n## 0.34.41\n\n### Patch Changes\n\n- Updated dependencies [[`1ba640c`](https://github.com/Effect-TS/effect/commit/1ba640c702f187a866023bf043c26e25cce941ef), [`c8c71bd`](https://github.com/Effect-TS/effect/commit/c8c71bd20eb87d23133dac6156b83bb08941597c), [`a26ce58`](https://github.com/Effect-TS/effect/commit/a26ce581ca7d407e1e81439b58c8045b3fa65231)]:\n  - effect@3.5.8\n\n## 0.34.40\n\n### Patch Changes\n\n- [#3310](https://github.com/Effect-TS/effect/pull/3310) [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc) Thanks @fubhy! - Added additional pure annotations to improve tree-shakeability\n\n- Updated dependencies [[`3afcc93`](https://github.com/Effect-TS/effect/commit/3afcc93413a3d910beb69e4ce9ae120e4adaffd5), [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc)]:\n  - effect@3.5.7\n\n## 0.34.39\n\n### Patch Changes\n\n- Updated dependencies [[`cc327a1`](https://github.com/Effect-TS/effect/commit/cc327a1bccd22a4ee27ec7e58b53205e93b23e2c), [`4bfe4fb`](https://github.com/Effect-TS/effect/commit/4bfe4fb5c82f597c9beea9baa92e772593598b60), [`2b14d18`](https://github.com/Effect-TS/effect/commit/2b14d181462cad8359da4fa6bc6dfda0f742c398)]:\n  - effect@3.5.6\n\n## 0.34.38\n\n### Patch Changes\n\n- Updated dependencies [[`a9d7800`](https://github.com/Effect-TS/effect/commit/a9d7800f6a253192b653d77778b0674f39b1ca39)]:\n  - effect@3.5.5\n\n## 0.34.37\n\n### Patch Changes\n\n- [#3254](https://github.com/Effect-TS/effect/pull/3254) [`1b45236`](https://github.com/Effect-TS/effect/commit/1b4523699f91bc1e04ce30de1c007f0c0cf6e214) Thanks @tim-smart! - force flush otel provider before calling shutdown\n\n- Updated dependencies [[`ed0dde4`](https://github.com/Effect-TS/effect/commit/ed0dde4888e6f1a97ad5bba06b755d26a6a1c52e), [`ca775ce`](https://github.com/Effect-TS/effect/commit/ca775cec53baebc1a43d9b8852a3ac6726178498), [`5be9cc0`](https://github.com/Effect-TS/effect/commit/5be9cc044025a9541b9b7acefa2d3fc05fa1301b), [`203658f`](https://github.com/Effect-TS/effect/commit/203658f8001c132b25764ab70344b171683b554c), [`eb1c4d4`](https://github.com/Effect-TS/effect/commit/eb1c4d44e54b9d8d201a366d1ff94face2a6dcd3)]:\n  - effect@3.5.4\n\n## 0.34.36\n\n### Patch Changes\n\n- Updated dependencies [[`edb0da3`](https://github.com/Effect-TS/effect/commit/edb0da383746d760f35d8582f5fb0cc0eeca9217), [`c8d3fb0`](https://github.com/Effect-TS/effect/commit/c8d3fb0fe23585f6efb724af51fbab3ba1ad6e83), [`dabd028`](https://github.com/Effect-TS/effect/commit/dabd028decf9b7983ca16ebe0f48c05c11a84b68), [`786b2ab`](https://github.com/Effect-TS/effect/commit/786b2ab29d525c877bb84035dac9e2d6499339d1), [`fc57354`](https://github.com/Effect-TS/effect/commit/fc573547d41667016fce05eaee75960fcc6dce4d)]:\n  - effect@3.5.3\n\n## 0.34.35\n\n### Patch Changes\n\n- Updated dependencies [[`639208e`](https://github.com/Effect-TS/effect/commit/639208eeb8a44622994f832bc2d45d06ab636bc8), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5)]:\n  - effect@3.5.2\n\n## 0.34.34\n\n### Patch Changes\n\n- Updated dependencies [[`55fdd76`](https://github.com/Effect-TS/effect/commit/55fdd761ee95afd73b6a892c13fee92b36c02837)]:\n  - effect@3.5.1\n\n## 0.34.33\n\n### Patch Changes\n\n- Updated dependencies [[`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`5ab348f`](https://github.com/Effect-TS/effect/commit/5ab348f265db3d283aa091ddca6d2d49137c16f2), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`3e04bf8`](https://github.com/Effect-TS/effect/commit/3e04bf8a7127e956cadb7684a8f4c661df57663b), [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`4626de5`](https://github.com/Effect-TS/effect/commit/4626de59c25b384216faa0be87bf0b8cd36357d0), [`f01e7db`](https://github.com/Effect-TS/effect/commit/f01e7db317827255d7901f523f2e28b43298e8df), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6), [`ac71f37`](https://github.com/Effect-TS/effect/commit/ac71f378f2413e5aa91c95f649ffe898d6a26114), [`8432360`](https://github.com/Effect-TS/effect/commit/8432360ce68614a419bb328083a4109d0fc8aa93), [`e4bf1bf`](https://github.com/Effect-TS/effect/commit/e4bf1bf2b4a970eacd77c9b77b5ea8c68bc84498), [`13cb861`](https://github.com/Effect-TS/effect/commit/13cb861a5eded15c55c6cdcf6a8acde8320367a6), [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6), [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3), [`9f66825`](https://github.com/Effect-TS/effect/commit/9f66825f1fce0fe8d10420c285f7dc4c71e8af8d)]:\n  - effect@3.5.0\n\n## 0.34.32\n\n### Patch Changes\n\n- Updated dependencies [[`7af137c`](https://github.com/Effect-TS/effect/commit/7af137c9433f6e74959b3887561ec1e6f12e10ee), [`ee4b3dc`](https://github.com/Effect-TS/effect/commit/ee4b3dc5f68d19dc3ae1c2d12901c5b8ffbebabb), [`097d25c`](https://github.com/Effect-TS/effect/commit/097d25cb5d13c049e01789651be56b09620186ef)]:\n  - effect@3.4.9\n\n## 0.34.31\n\n### Patch Changes\n\n- Updated dependencies [[`a435e0f`](https://github.com/Effect-TS/effect/commit/a435e0fc5378b33a49bcec92ee235df6f16a2419), [`b5554db`](https://github.com/Effect-TS/effect/commit/b5554db36c4dd6f64fa5e6a62a29b2759c54217a), [`a9c4fb3`](https://github.com/Effect-TS/effect/commit/a9c4fb3bf3c6e92cd1c142b0605fddf7eb3c697c)]:\n  - effect@3.4.8\n\n## 0.34.30\n\n### Patch Changes\n\n- Updated dependencies [[`a5737d6`](https://github.com/Effect-TS/effect/commit/a5737d6db2b921605c332eabbc5402ee3d17357b)]:\n  - effect@3.4.7\n\n## 0.34.29\n\n### Patch Changes\n\n- Updated dependencies [[`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`33735b1`](https://github.com/Effect-TS/effect/commit/33735b16b41bd26929d8f4754c190925db6323b7), [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`139d4b3`](https://github.com/Effect-TS/effect/commit/139d4b39fb3bff2eeaa7c0c809c581da42425a83)]:\n  - effect@3.4.6\n\n## 0.34.28\n\n### Patch Changes\n\n- Updated dependencies [[`a047af9`](https://github.com/Effect-TS/effect/commit/a047af99447dfffc729e9c8ef0ca143537927e91)]:\n  - effect@3.4.5\n\n## 0.34.27\n\n### Patch Changes\n\n- Updated dependencies [[`72638e3`](https://github.com/Effect-TS/effect/commit/72638e3d99f0e93a24febf6c225256ce92d4a20b), [`d7dde2b`](https://github.com/Effect-TS/effect/commit/d7dde2b4af08b37af859d4c327c1f5c6f00cf9d9), [`9b2fc3b`](https://github.com/Effect-TS/effect/commit/9b2fc3b9dfd304a2bd0508ef2313cfc54357be0c)]:\n  - effect@3.4.4\n\n## 0.34.26\n\n### Patch Changes\n\n- [#3079](https://github.com/Effect-TS/effect/pull/3079) [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd) Thanks @tim-smart! - update dependencies\n\n- [#3079](https://github.com/Effect-TS/effect/pull/3079) [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd) Thanks @tim-smart! - update to typescript 5.5\n\n- Updated dependencies [[`c342739`](https://github.com/Effect-TS/effect/commit/c3427396226e1ad7b95b40595a23f9bdff3e3365), [`8898e5e`](https://github.com/Effect-TS/effect/commit/8898e5e238622f6337583d91ee23609c1f5ccdf7), [`ff78636`](https://github.com/Effect-TS/effect/commit/ff786367c522975f40f0f179a0ecdfcfab7ecbdb), [`c86bd4e`](https://github.com/Effect-TS/effect/commit/c86bd4e134c23146c216f9ff97e03781d55991b6), [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd)]:\n  - effect@3.4.3\n\n## 0.34.25\n\n### Patch Changes\n\n- Updated dependencies [[`3da1497`](https://github.com/Effect-TS/effect/commit/3da1497b5c9cc886d300258bc928fd68a4fefe6f)]:\n  - effect@3.4.2\n\n## 0.34.24\n\n### Patch Changes\n\n- Updated dependencies [[`66a1910`](https://github.com/Effect-TS/effect/commit/66a19109ff90c4252123b8809b8c8a74681dba6a)]:\n  - effect@3.4.1\n\n## 0.34.23\n\n### Patch Changes\n\n- Updated dependencies [[`c0ce180`](https://github.com/Effect-TS/effect/commit/c0ce180861ad0938053c0e6145e813fa6404df3b), [`61707b6`](https://github.com/Effect-TS/effect/commit/61707b6ffc7397c2ba0dce22512b44955724f60f), [`9c1b5b3`](https://github.com/Effect-TS/effect/commit/9c1b5b39e6c19604ce834f072a114ad392c50a06), [`a35faf8`](https://github.com/Effect-TS/effect/commit/a35faf8d116f94899bfc03feab33b004c8ddfdf7), [`ff73c0c`](https://github.com/Effect-TS/effect/commit/ff73c0cacd66132bfad2e5211b3eae347729c667), [`984d516`](https://github.com/Effect-TS/effect/commit/984d516ccd9412dc41188f6a46b748dd20dd5848), [`8c3b8a2`](https://github.com/Effect-TS/effect/commit/8c3b8a2ce208eab753b6206a51605a424f104e98), [`017e2f9`](https://github.com/Effect-TS/effect/commit/017e2f9b371ce24ea4945e5d7390c934ad3c39cf), [`91bf8a2`](https://github.com/Effect-TS/effect/commit/91bf8a2e9d1959393b3cf7366cc1d584d3e666b7), [`c6a4a26`](https://github.com/Effect-TS/effect/commit/c6a4a266606575fd2c7165940c4072ad4c57d01f)]:\n  - effect@3.4.0\n\n## 0.34.22\n\n### Patch Changes\n\n- Updated dependencies [[`6c89408`](https://github.com/Effect-TS/effect/commit/6c89408cd7b9204ec4c5828a46cd5312d8afb5e7)]:\n  - effect@3.3.5\n\n## 0.34.21\n\n### Patch Changes\n\n- Updated dependencies [[`a67b8fe`](https://github.com/Effect-TS/effect/commit/a67b8fe2ace08419424811b5f0d9a5378eaea352)]:\n  - effect@3.3.4\n\n## 0.34.20\n\n### Patch Changes\n\n- Updated dependencies [[`06ede85`](https://github.com/Effect-TS/effect/commit/06ede85d6e84710e6622463be95ff3927fb30dad), [`7204ca5`](https://github.com/Effect-TS/effect/commit/7204ca5761c2b1d27999a624db23aa10b6e0504d)]:\n  - effect@3.3.3\n\n## 0.34.19\n\n### Patch Changes\n\n- Updated dependencies [[`3572646`](https://github.com/Effect-TS/effect/commit/3572646d5e0804f85bc7f64633fb95722533f9dd), [`1aed347`](https://github.com/Effect-TS/effect/commit/1aed347a125ed3847ec90863424810d6759cbc85), [`df4bf4b`](https://github.com/Effect-TS/effect/commit/df4bf4b62e7b316c6647da0271fc5544a84e7ba2), [`f085f92`](https://github.com/Effect-TS/effect/commit/f085f92dfa204afb41823ffc27d437225137643d)]:\n  - effect@3.3.2\n\n## 0.34.18\n\n### Patch Changes\n\n- Updated dependencies [[`eb98c5b`](https://github.com/Effect-TS/effect/commit/eb98c5b79ab50aa0cde239bd4e660dd19dbab612), [`184fed8`](https://github.com/Effect-TS/effect/commit/184fed83ac36cba05a75a5a8013f740f9f696e3b), [`6068e07`](https://github.com/Effect-TS/effect/commit/6068e073d4cc8b3c8583583fd5eb3efe43f7d5ba), [`3a77e20`](https://github.com/Effect-TS/effect/commit/3a77e209783933bac3aaddba1b05ff6a9ac72b36)]:\n  - effect@3.3.1\n\n## 0.34.17\n\n### Patch Changes\n\n- Updated dependencies [[`1f4ac00`](https://github.com/Effect-TS/effect/commit/1f4ac00a91c336c9c9c9b8c3ed9ceb9920ebc9bd), [`9305b76`](https://github.com/Effect-TS/effect/commit/9305b764cceeae4f16564435ae7172f79c2bf822), [`0f40d98`](https://github.com/Effect-TS/effect/commit/0f40d989da10f68df3ecd72b36849401ad679bfb), [`b761ef0`](https://github.com/Effect-TS/effect/commit/b761ef00eaf6c67b7ffe34798b98aae5347ab376), [`b53f69b`](https://github.com/Effect-TS/effect/commit/b53f69bff1452a487b21198cd83961f844e02d36), [`0f40d98`](https://github.com/Effect-TS/effect/commit/0f40d989da10f68df3ecd72b36849401ad679bfb), [`5bd549e`](https://github.com/Effect-TS/effect/commit/5bd549e4bd7144727db438ecca6b8dc9b3ef7e22), [`67f160a`](https://github.com/Effect-TS/effect/commit/67f160a213de0219a565d4bf653b3cbf24f58e8f)]:\n  - effect@3.3.0\n\n## 0.34.16\n\n### Patch Changes\n\n- Updated dependencies [[`8c5d280`](https://github.com/Effect-TS/effect/commit/8c5d280c0402284a4e58372867a15a431cb99461), [`6ba6d26`](https://github.com/Effect-TS/effect/commit/6ba6d269f5891e6b11aa35c5281dde4bf3273004), [`3f28bf2`](https://github.com/Effect-TS/effect/commit/3f28bf274333611906175446b772243f34f1b6d5), [`5817820`](https://github.com/Effect-TS/effect/commit/58178204a770d1a78c06945ef438f9fffbb50afa)]:\n  - effect@3.2.9\n\n## 0.34.15\n\n### Patch Changes\n\n- Updated dependencies [[`fb91f17`](https://github.com/Effect-TS/effect/commit/fb91f17098b48497feca9ec976feb87e4a82451b)]:\n  - effect@3.2.8\n\n## 0.34.14\n\n### Patch Changes\n\n- Updated dependencies [[`6801fca`](https://github.com/Effect-TS/effect/commit/6801fca44366be3ee1b6b99f54bd4f38a1b5e4f4)]:\n  - effect@3.2.7\n\n## 0.34.13\n\n### Patch Changes\n\n- Updated dependencies [[`cc8ac50`](https://github.com/Effect-TS/effect/commit/cc8ac5080daba8622ca2ff5dab5c37ddfab732ba)]:\n  - effect@3.2.6\n\n## 0.34.12\n\n### Patch Changes\n\n- Updated dependencies [[`608b01f`](https://github.com/Effect-TS/effect/commit/608b01fc342dbae2a642b308a67b84ead530ecea), [`031c712`](https://github.com/Effect-TS/effect/commit/031c7122a24ac42e48d6a434646b4f5d279d7442), [`a44e532`](https://github.com/Effect-TS/effect/commit/a44e532cf3a6a498b12a5aacf8124aa267e24ba0)]:\n  - effect@3.2.5\n\n## 0.34.11\n\n### Patch Changes\n\n- Updated dependencies [[`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3), [`e313a01`](https://github.com/Effect-TS/effect/commit/e313a01b7e80f6cb7704055a190e5623c9d22c6d)]:\n  - effect@3.2.4\n\n## 0.34.10\n\n### Patch Changes\n\n- Updated dependencies [[`45578e8`](https://github.com/Effect-TS/effect/commit/45578e8faa80ae33d23e08f6f19467f818b7788f)]:\n  - effect@3.2.3\n\n## 0.34.9\n\n### Patch Changes\n\n- Updated dependencies [[`5d9266e`](https://github.com/Effect-TS/effect/commit/5d9266e8c740746ac9e186c3df6090a1b57fbe2a), [`9f8122e`](https://github.com/Effect-TS/effect/commit/9f8122e78884ab47c5e5f364d86eee1d1543cc61), [`6a6f670`](https://github.com/Effect-TS/effect/commit/6a6f6706b8613c8c7c10971b8d81a0f9e440a6f2)]:\n  - effect@3.2.2\n\n## 0.34.8\n\n### Patch Changes\n\n- Updated dependencies [[`c1e991d`](https://github.com/Effect-TS/effect/commit/c1e991dd5ba87901cd0e05697a8b4a267e7e954a)]:\n  - effect@3.2.1\n\n## 0.34.7\n\n### Patch Changes\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e) Thanks [@tim-smart](https://github.com/tim-smart)! - properly record exceptions in otel spans\n\n- Updated dependencies [[`146cadd`](https://github.com/Effect-TS/effect/commit/146cadd9d004634a3ff85c480bf92cf975c853e2), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`963b4e7`](https://github.com/Effect-TS/effect/commit/963b4e7ac87e2468feb6a344f7ab4ee4ad711198), [`64c9414`](https://github.com/Effect-TS/effect/commit/64c9414e960e82058ca09bbb3976d6fbef303a8e), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`2cbb76b`](https://github.com/Effect-TS/effect/commit/2cbb76bb52500a3f4bf27d1c91482518cbea56d7), [`870c5fa`](https://github.com/Effect-TS/effect/commit/870c5fa52cd61e745e8e828d38c3f09f00737553), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`64c9414`](https://github.com/Effect-TS/effect/commit/64c9414e960e82058ca09bbb3976d6fbef303a8e)]:\n  - effect@3.2.0\n\n## 0.34.6\n\n### Patch Changes\n\n- Updated dependencies [[`17fc22e`](https://github.com/Effect-TS/effect/commit/17fc22e132593c5caa563705a4748ba0f04a853c), [`810f222`](https://github.com/Effect-TS/effect/commit/810f222268792b13067c7a7bf317b93a9bb8917b), [`596aaea`](https://github.com/Effect-TS/effect/commit/596aaea022648b2e06fb1ec22f1652043d6fe64e)]:\n  - effect@3.1.6\n\n## 0.34.5\n\n### Patch Changes\n\n- [#2736](https://github.com/Effect-TS/effect/pull/2736) [`40c2b1d`](https://github.com/Effect-TS/effect/commit/40c2b1d9234bcfc9ab4039282b621ca092f800cd) Thanks [@patroza](https://github.com/patroza)! - update otel dependencies\n\n- Updated dependencies [[`6ac4847`](https://github.com/Effect-TS/effect/commit/6ac48479447c01a4f35d655552af93e47e562610)]:\n  - effect@3.1.5\n\n## 0.34.4\n\n### Patch Changes\n\n- Updated dependencies [[`e41e911`](https://github.com/Effect-TS/effect/commit/e41e91122fa6dd12fc81e50dcad0db891be67146)]:\n  - effect@3.1.4\n\n## 0.34.3\n\n### Patch Changes\n\n- Updated dependencies [[`1f6dc96`](https://github.com/Effect-TS/effect/commit/1f6dc96f51c7bb9c8d11415358308604ba7c7c8e)]:\n  - effect@3.1.3\n\n## 0.34.2\n\n### Patch Changes\n\n- Updated dependencies [[`2e1cdf6`](https://github.com/Effect-TS/effect/commit/2e1cdf67d141281288fffe9a5c10d1379a800513)]:\n  - effect@3.1.2\n\n## 0.34.1\n\n### Patch Changes\n\n- Updated dependencies [[`e5e56d1`](https://github.com/Effect-TS/effect/commit/e5e56d138dbed3204636f605229c6685f89659fc)]:\n  - effect@3.1.1\n\n## 0.34.0\n\n### Minor Changes\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`a023f28`](https://github.com/Effect-TS/effect/commit/a023f28336f3865687d9a30c1883e36909906d85) Thanks [@github-actions](https://github.com/apps/github-actions)! - add `kind` property to `Tracer.Span`\n\n  This can be used to specify what kind of service created the span.\n\n### Patch Changes\n\n- Updated dependencies [[`c3c12c6`](https://github.com/Effect-TS/effect/commit/c3c12c6625633fe80e79f9db75a3b8cf8ca8b11d), [`ba64ea6`](https://github.com/Effect-TS/effect/commit/ba64ea6757810c5e74cad3863a7d19d4d38af66b), [`b5de2d2`](https://github.com/Effect-TS/effect/commit/b5de2d2ce5b1afe8be90827bf898a95cec40eb2b), [`a1c7ab8`](https://github.com/Effect-TS/effect/commit/a1c7ab8ffedacd18c1fc784f4ff5844f79498b83), [`a023f28`](https://github.com/Effect-TS/effect/commit/a023f28336f3865687d9a30c1883e36909906d85), [`1c9454d`](https://github.com/Effect-TS/effect/commit/1c9454d532eae79b9f759aea77f59332cc6d18ed), [`92d56db`](https://github.com/Effect-TS/effect/commit/92d56dbb3f33e36636c2a2f1030c56492e39cf4d)]:\n  - effect@3.1.0\n\n## 0.33.5\n\n### Patch Changes\n\n- [#2656](https://github.com/Effect-TS/effect/pull/2656) [`557707b`](https://github.com/Effect-TS/effect/commit/557707bc9e5f230c8964d2757012075c34339b5c) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n- Updated dependencies [[`557707b`](https://github.com/Effect-TS/effect/commit/557707bc9e5f230c8964d2757012075c34339b5c), [`f4ed306`](https://github.com/Effect-TS/effect/commit/f4ed3068a70b50302d078a30d18ca3cfd2bc679c), [`661004f`](https://github.com/Effect-TS/effect/commit/661004f4bf5f8b25f5a0678c21a3a822188ce461), [`e79cb83`](https://github.com/Effect-TS/effect/commit/e79cb83d3b19098bc40a3012e2a059b8426306c2)]:\n  - effect@3.0.8\n\n## 0.33.4\n\n### Patch Changes\n\n- Updated dependencies [[`18de56b`](https://github.com/Effect-TS/effect/commit/18de56b4a6b6d1f99230dfabf9147d59ea4dd759)]:\n  - effect@3.0.7\n\n## 0.33.3\n\n### Patch Changes\n\n- [#2623](https://github.com/Effect-TS/effect/pull/2623) [`8492f5b`](https://github.com/Effect-TS/effect/commit/8492f5b944459fc966807202eccc9b7802799e6f) Thanks [@tim-smart](https://github.com/tim-smart)! - allow for multiple otel span processors & metric readers\n\n- Updated dependencies [[`ffe4f4e`](https://github.com/Effect-TS/effect/commit/ffe4f4e95db35fff6869e360b072e3837befa0a1), [`027418e`](https://github.com/Effect-TS/effect/commit/027418edaa6aa6c0ae4861b95832827b45adace4), [`ac1898e`](https://github.com/Effect-TS/effect/commit/ac1898eb7bc96880f911c276048e2ea3d6fe9c50), [`ffe4f4e`](https://github.com/Effect-TS/effect/commit/ffe4f4e95db35fff6869e360b072e3837befa0a1)]:\n  - effect@3.0.6\n\n## 0.33.2\n\n### Patch Changes\n\n- Updated dependencies [[`6222404`](https://github.com/Effect-TS/effect/commit/62224044678751829ed2f128e05133a91c6b0569), [`868ed2a`](https://github.com/Effect-TS/effect/commit/868ed2a8fe94ee7f4206a6070f29dcf2a5ba1dc3)]:\n  - effect@3.0.5\n\n## 0.33.1\n\n### Patch Changes\n\n- Updated dependencies [[`9a24667`](https://github.com/Effect-TS/effect/commit/9a246672008a2b668d43fbfd2fe5508c54b2b920)]:\n  - effect@3.0.4\n\n## 0.33.0\n\n### Minor Changes\n\n- [#2572](https://github.com/Effect-TS/effect/pull/2572) [`c8c798a`](https://github.com/Effect-TS/effect/commit/c8c798a46a193fa678194b31fe2af99048fe71e0) Thanks [@nickrttn](https://github.com/nickrttn)! - Update @opentelemetry/\\* peer dependencies to ensure allowed versions include used imports\n\n### Patch Changes\n\n- [#2575](https://github.com/Effect-TS/effect/pull/2575) [`d2ebe0e`](https://github.com/Effect-TS/effect/commit/d2ebe0e48aae248ac014fb976fa2d7bf3038394d) Thanks [@tim-smart](https://github.com/tim-smart)! - add otel Resource.layerFromEnv, for constructing a resource from env variables\n\n## 0.32.3\n\n### Patch Changes\n\n- Updated dependencies [[`a7b4b84`](https://github.com/Effect-TS/effect/commit/a7b4b84bd5a25f51aba922f9259c3a58c98c6a4e)]:\n  - effect@3.0.3\n\n## 0.32.2\n\n### Patch Changes\n\n- [#2562](https://github.com/Effect-TS/effect/pull/2562) [`2cecdbd`](https://github.com/Effect-TS/effect/commit/2cecdbd1cf30befce4e84796ccd953ea55ecfb86) Thanks [@fubhy](https://github.com/fubhy)! - Added provenance publishing\n\n- Updated dependencies [[`2cecdbd`](https://github.com/Effect-TS/effect/commit/2cecdbd1cf30befce4e84796ccd953ea55ecfb86)]:\n  - effect@3.0.2\n\n## 0.32.1\n\n### Patch Changes\n\n- [#2555](https://github.com/Effect-TS/effect/pull/2555) [`8edacca`](https://github.com/Effect-TS/effect/commit/8edacca37f8e37c01a63fec332b06d9361efaa7b) Thanks [@tim-smart](https://github.com/tim-smart)! - prevent use of `Array` as import name to solve bundler issues\n\n- Updated dependencies [[`3da0cfa`](https://github.com/Effect-TS/effect/commit/3da0cfa12c407fd930dc480be1ecc9217a8058f8), [`570e8d8`](https://github.com/Effect-TS/effect/commit/570e8d87e7c0e9ad4cd2686462fdb9b4812f7716), [`8edacca`](https://github.com/Effect-TS/effect/commit/8edacca37f8e37c01a63fec332b06d9361efaa7b)]:\n  - effect@3.0.1\n\n## 0.32.0\n\n### Minor Changes\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`5a2314b`](https://github.com/Effect-TS/effect/commit/5a2314b70ec79c2c02b51cef45a5ddec8327daa1) Thanks [@github-actions](https://github.com/apps/github-actions)! - replace use of `unit` terminology with `void`\n\n  For all the data types.\n\n  ```ts\n  Effect.unit // => Effect.void\n  Stream.unit // => Stream.void\n\n  // etc\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`2fb7d9c`](https://github.com/Effect-TS/effect/commit/2fb7d9ca15037ff62a578bb9fe5732da5f4f317d) Thanks [@github-actions](https://github.com/apps/github-actions)! - Release Effect 3.0 🎉\n\n### Patch Changes\n\n- [#2529](https://github.com/Effect-TS/effect/pull/2529) [`78b767c`](https://github.com/Effect-TS/effect/commit/78b767c2b1625186e17131761a0edbac25d21850) Thanks [@fubhy](https://github.com/fubhy)! - Renamed `ReadonlyArray` and `ReadonlyRecord` modules for better discoverability.\n\n- Updated dependencies [[`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`d50a652`](https://github.com/Effect-TS/effect/commit/d50a652479f4d1d64f48da05c79fa847e6e51548), [`9a3bd47`](https://github.com/Effect-TS/effect/commit/9a3bd47ebd0750c7e498162734f6d21895de0cb2), [`be9d025`](https://github.com/Effect-TS/effect/commit/be9d025e42355260ace02dd135851a8935a4deba), [`78b767c`](https://github.com/Effect-TS/effect/commit/78b767c2b1625186e17131761a0edbac25d21850), [`1499974`](https://github.com/Effect-TS/effect/commit/14999741d2e19c1747f6a7e19d68977f6429cdb8), [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`5c2b561`](https://github.com/Effect-TS/effect/commit/5c2b5614f583b88784ed68126ae939832fb3c092), [`a18f594`](https://github.com/Effect-TS/effect/commit/a18f5948f1439a147232448b2c443472fda0eceb), [`1499974`](https://github.com/Effect-TS/effect/commit/14999741d2e19c1747f6a7e19d68977f6429cdb8), [`2f96d93`](https://github.com/Effect-TS/effect/commit/2f96d938b90f8c19377583279e3c7afd9b509c50), [`5a2314b`](https://github.com/Effect-TS/effect/commit/5a2314b70ec79c2c02b51cef45a5ddec8327daa1), [`271b79f`](https://github.com/Effect-TS/effect/commit/271b79fc0b66a6c11e07a8779ff8800493a7eac2), [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`2fb7d9c`](https://github.com/Effect-TS/effect/commit/2fb7d9ca15037ff62a578bb9fe5732da5f4f317d), [`53d1c2a`](https://github.com/Effect-TS/effect/commit/53d1c2a77559081fbb89667e343346375c6d6650), [`e7e1bbe`](https://github.com/Effect-TS/effect/commit/e7e1bbe68486fdf31c8f84b0880522d39adcaad3), [`10c169e`](https://github.com/Effect-TS/effect/commit/10c169eadc874e91b4defca3f467b4e6a50fd8f3), [`6424181`](https://github.com/Effect-TS/effect/commit/64241815fe6a939e91e6947253e7dceea1306aa8)]:\n  - effect@3.0.0\n\n## 0.31.29\n\n### Patch Changes\n\n- Updated dependencies [[`41c8102`](https://github.com/Effect-TS/effect/commit/41c810228b1a50e4b41f19e735d7c62fe8d36871), [`776ef2b`](https://github.com/Effect-TS/effect/commit/776ef2bb66db9aa9f68b7beab14f6986f9c1288b), [`217147e`](https://github.com/Effect-TS/effect/commit/217147ea67c5c42c96f024775c41e5b070f81e4c), [`90776ec`](https://github.com/Effect-TS/effect/commit/90776ec8e8671d835b65fc33ead1de6c864b81b9), [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55), [`232c353`](https://github.com/Effect-TS/effect/commit/232c353c2e6f743f38e57639ee30e324ffa9c2a9), [`0ca835c`](https://github.com/Effect-TS/effect/commit/0ca835cbac8e69072a93ace83b534219faba24e8), [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55), [`e983740`](https://github.com/Effect-TS/effect/commit/e9837401145605aff5bc2ec7e73004f397c5d2d1), [`e3e0924`](https://github.com/Effect-TS/effect/commit/e3e09247d46a35430fc60e4aa4032cc50814f212)]:\n  - effect@2.4.19\n\n## 0.31.28\n\n### Patch Changes\n\n- Updated dependencies [[`dadc690`](https://github.com/Effect-TS/effect/commit/dadc6906121c512bc32be22b52adbd1ada834594)]:\n  - effect@2.4.18\n\n## 0.31.27\n\n### Patch Changes\n\n- Updated dependencies [[`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`607b2e7`](https://github.com/Effect-TS/effect/commit/607b2e7a7fd9318c57acf4e50ec61747eea74ad7), [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`8206caf`](https://github.com/Effect-TS/effect/commit/8206caf7c2d22c68be4313318b61cfdacf6222b6), [`7ddd654`](https://github.com/Effect-TS/effect/commit/7ddd65415b65ccb654ad04f4dbefe39402f15117), [`7ddd654`](https://github.com/Effect-TS/effect/commit/7ddd65415b65ccb654ad04f4dbefe39402f15117), [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`f456ba2`](https://github.com/Effect-TS/effect/commit/f456ba273bae21a6dcf8c966c50c97b5f0897d9f)]:\n  - effect@2.4.17\n\n## 0.31.26\n\n### Patch Changes\n\n- [#2433](https://github.com/Effect-TS/effect/pull/2433) [`ee10a50`](https://github.com/Effect-TS/effect/commit/ee10a50da859abf7154636d6d3e59511f0e0f590) Thanks [@vecerek](https://github.com/vecerek)! - Exports an empty NodeSDK layer suitable for incremental adoption and unit testing purposes\n\n- Updated dependencies [[`5170ce7`](https://github.com/Effect-TS/effect/commit/5170ce708c606283e8a30d273950f1a21c7eddc2)]:\n  - effect@2.4.16\n\n## 0.31.25\n\n### Patch Changes\n\n- Updated dependencies [[`d7688c0`](https://github.com/Effect-TS/effect/commit/d7688c0c72717fe7876c871567f6946dabfc0546), [`b3a4fac`](https://github.com/Effect-TS/effect/commit/b3a4face2acaca422f0b0530436e8f13129f3b3a)]:\n  - effect@2.4.15\n\n## 0.31.24\n\n### Patch Changes\n\n- Updated dependencies [[`6180c0c`](https://github.com/Effect-TS/effect/commit/6180c0cc51dee785cfce72220a52c9fc3b9bf9aa)]:\n  - effect@2.4.14\n\n## 0.31.23\n\n### Patch Changes\n\n- Updated dependencies [[`3336287`](https://github.com/Effect-TS/effect/commit/3336287ff55a25e56d759b83847bfaa21c40f499), [`54b7c00`](https://github.com/Effect-TS/effect/commit/54b7c0077fa784ad2646b812d6a44641f672edcd), [`3336287`](https://github.com/Effect-TS/effect/commit/3336287ff55a25e56d759b83847bfaa21c40f499)]:\n  - effect@2.4.13\n\n## 0.31.22\n\n### Patch Changes\n\n- [#2385](https://github.com/Effect-TS/effect/pull/2385) [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87) Thanks [@tim-smart](https://github.com/tim-smart)! - update typescript to 5.4\n\n- Updated dependencies [[`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87)]:\n  - effect@2.4.12\n\n## 0.31.21\n\n### Patch Changes\n\n- [#2384](https://github.com/Effect-TS/effect/pull/2384) [`2f488c4`](https://github.com/Effect-TS/effect/commit/2f488c436de52576562803c57ebc132ef40ccdd8) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n- Updated dependencies [[`2f488c4`](https://github.com/Effect-TS/effect/commit/2f488c436de52576562803c57ebc132ef40ccdd8), [`37ca592`](https://github.com/Effect-TS/effect/commit/37ca592a4101ad90adbf8c8b3f727faf3110cae5), [`317b5b8`](https://github.com/Effect-TS/effect/commit/317b5b8e8c8c2207469b3ebfcf72bf3a9f7cbc60)]:\n  - effect@2.4.11\n\n## 0.31.20\n\n### Patch Changes\n\n- [#2375](https://github.com/Effect-TS/effect/pull/2375) [`9bab1f9`](https://github.com/Effect-TS/effect/commit/9bab1f9fa5b999740755e4e82485cb77c638643a) Thanks [@tim-smart](https://github.com/tim-smart)! - Make @effect/opentelemetry metrics conform to the spec\n  - Metric labels add new data points instead of completely new metric data\n  - Start times are determined from the first occurrence of a metric\n\n- Updated dependencies [[`9bab1f9`](https://github.com/Effect-TS/effect/commit/9bab1f9fa5b999740755e4e82485cb77c638643a), [`9bbde5b`](https://github.com/Effect-TS/effect/commit/9bbde5be9a0168d1c2a0308bfc27167ed62f3968)]:\n  - effect@2.4.10\n\n## 0.31.19\n\n### Patch Changes\n\n- Updated dependencies [[`71fd528`](https://github.com/Effect-TS/effect/commit/71fd5287500f9ce155a7d9f0df6ee3e0ac3aeb99)]:\n  - effect@2.4.9\n\n## 0.31.18\n\n### Patch Changes\n\n- Updated dependencies [[`bb0b69e`](https://github.com/Effect-TS/effect/commit/bb0b69e519698c7c76aa68217de423c78ad16566), [`6b20bad`](https://github.com/Effect-TS/effect/commit/6b20badebb3a7ca4d38857753e8ecaa09d02ccfb), [`4e64e9b`](https://github.com/Effect-TS/effect/commit/4e64e9b9876de6bfcbabe39e18a91a08e5f3fbb0), [`3851a02`](https://github.com/Effect-TS/effect/commit/3851a022c481006aec1db36651e4b4fd727aa742), [`5f5fcd9`](https://github.com/Effect-TS/effect/commit/5f5fcd969ae30ed6fe61d566a571498d9e895e16), [`814e5b8`](https://github.com/Effect-TS/effect/commit/814e5b828f68210b9e8f336fd6ac688646835dd9)]:\n  - effect@2.4.8\n\n## 0.31.17\n\n### Patch Changes\n\n- Updated dependencies [[`eb93283`](https://github.com/Effect-TS/effect/commit/eb93283985913d7b04ca750e36ac8513e7b6cef6)]:\n  - effect@2.4.7\n\n## 0.31.16\n\n### Patch Changes\n\n- Updated dependencies [[`4f35a7e`](https://github.com/Effect-TS/effect/commit/4f35a7e7c4eba598924aff24d1158b9056bb24be), [`9971186`](https://github.com/Effect-TS/effect/commit/99711862722188fbb5ed3ee75126ad5edf13f72f)]:\n  - effect@2.4.6\n\n## 0.31.15\n\n### Patch Changes\n\n- Updated dependencies [[`bce21c5`](https://github.com/Effect-TS/effect/commit/bce21c5ded2177114666ba229bd5029fa000dee3), [`c7d3036`](https://github.com/Effect-TS/effect/commit/c7d303630b7f0825cb2e584557c5767a67214d9f)]:\n  - effect@2.4.5\n\n## 0.31.14\n\n### Patch Changes\n\n- Updated dependencies [[`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949), [`817a04c`](https://github.com/Effect-TS/effect/commit/817a04cb2df0f4140984dc97eb3e1bb14a6c4a38), [`d90a99d`](https://github.com/Effect-TS/effect/commit/d90a99d03d074adc7cd2533f15419138264da5a2), [`dd05faa`](https://github.com/Effect-TS/effect/commit/dd05faa621555ef3585ecd914ac13ecd89b710f4), [`dd05faa`](https://github.com/Effect-TS/effect/commit/dd05faa621555ef3585ecd914ac13ecd89b710f4), [`802674b`](https://github.com/Effect-TS/effect/commit/802674b379b7559ad3ff09b33388891445a9e48b)]:\n  - effect@2.4.4\n\n## 0.31.13\n\n### Patch Changes\n\n- Updated dependencies [[`20e63fb`](https://github.com/Effect-TS/effect/commit/20e63fb9207210f3fe2d136ec40d0a2dbff3225e), [`20e63fb`](https://github.com/Effect-TS/effect/commit/20e63fb9207210f3fe2d136ec40d0a2dbff3225e)]:\n  - effect@2.4.3\n\n## 0.31.12\n\n### Patch Changes\n\n- Updated dependencies [[`e03811e`](https://github.com/Effect-TS/effect/commit/e03811e80c93e986e6348b3b67ac2ed6d5fefff0), [`ac41d84`](https://github.com/Effect-TS/effect/commit/ac41d84776484cdce8165b7ca2c9c9b6377eee2d), [`6137533`](https://github.com/Effect-TS/effect/commit/613753300c7705518ab1fea2f370b032851c2750), [`f373529`](https://github.com/Effect-TS/effect/commit/f373529999f4b8bc92b634f6ea14f19271388eed), [`1bf9f31`](https://github.com/Effect-TS/effect/commit/1bf9f31f07667de677673f7c29a4e7a26ebad3c8), [`e3ff789`](https://github.com/Effect-TS/effect/commit/e3ff789226f89e71eb28ca38ce79f90af6a03f1a), [`6137533`](https://github.com/Effect-TS/effect/commit/613753300c7705518ab1fea2f370b032851c2750), [`507ba40`](https://github.com/Effect-TS/effect/commit/507ba4060ff043c1a8d541dae723fa6940633b00), [`e466afe`](https://github.com/Effect-TS/effect/commit/e466afe32f2de598ceafd8982bd0cfbd388e5671), [`f373529`](https://github.com/Effect-TS/effect/commit/f373529999f4b8bc92b634f6ea14f19271388eed), [`de74eb8`](https://github.com/Effect-TS/effect/commit/de74eb80a79eebde5ff645033765e7a617e92f27)]:\n  - effect@2.4.2\n\n## 0.31.11\n\n### Patch Changes\n\n- Updated dependencies [[`a4a0006`](https://github.com/Effect-TS/effect/commit/a4a0006c7f19fc261df5cda16963d73457e4d6ac), [`0a37676`](https://github.com/Effect-TS/effect/commit/0a37676aa0eb2a21e17af2e6df9f81f52bbc8831), [`6f503b7`](https://github.com/Effect-TS/effect/commit/6f503b774d893bf2af34f66202e270d8c45d5f31)]:\n  - effect@2.4.1\n\n## 0.31.10\n\n### Patch Changes\n\n- Updated dependencies [[`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2), [`489fcf3`](https://github.com/Effect-TS/effect/commit/489fcf363ff2b2a953166b740cb9a62d7fc2a101), [`7d9c3bf`](https://github.com/Effect-TS/effect/commit/7d9c3bff6c18d451e0e4781042945ec5c7be1b9f), [`d8d278b`](https://github.com/Effect-TS/effect/commit/d8d278b2efb2966947029885e01f7b68348a021f), [`14c5711`](https://github.com/Effect-TS/effect/commit/14c57110078f0862b8da5c7a2c5d980f54447484), [`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2), [`b9cb3a9`](https://github.com/Effect-TS/effect/commit/b9cb3a9c9bfdd75536bd70b4e8b557c12d4923ff), [`585fcce`](https://github.com/Effect-TS/effect/commit/585fcce162d0f07a48d7cd984a9b722966fbebbe), [`93b412d`](https://github.com/Effect-TS/effect/commit/93b412d4a9ed762dc9fa5807e51fad0fc78a614a), [`55b26a6`](https://github.com/Effect-TS/effect/commit/55b26a6342b4826f1116e7a1eb660118c274458e), [`a025b12`](https://github.com/Effect-TS/effect/commit/a025b121235ba01cfce8d62a775491880c575561), [`2097739`](https://github.com/Effect-TS/effect/commit/20977393d2383bff709304e81ec7d51cafd57108)]:\n  - effect@2.4.0\n\n## 0.31.9\n\n### Patch Changes\n\n- [#2187](https://github.com/Effect-TS/effect/pull/2187) [`e6d36c0`](https://github.com/Effect-TS/effect/commit/e6d36c0813d836f17eabb6a9c7849baffca12dbf) Thanks [@tim-smart](https://github.com/tim-smart)! - update development dependencies\n\n- Updated dependencies [[`5ad2eec`](https://github.com/Effect-TS/effect/commit/5ad2eece0280b6db6a749d25cac1dcf6d33659a9), [`e6d36c0`](https://github.com/Effect-TS/effect/commit/e6d36c0813d836f17eabb6a9c7849baffca12dbf)]:\n  - effect@2.3.8\n\n## 0.31.8\n\n### Patch Changes\n\n- Updated dependencies [[`bc8404d`](https://github.com/Effect-TS/effect/commit/bc8404d54fd42072d200c0399cb39672837afa9f), [`2c5cbcd`](https://github.com/Effect-TS/effect/commit/2c5cbcd1161b4f40dab184999291e817314107de), [`6565916`](https://github.com/Effect-TS/effect/commit/6565916ef254bf910e47d25fd0ef55e7cb420241)]:\n  - effect@2.3.7\n\n## 0.31.7\n\n### Patch Changes\n\n- Updated dependencies [[`b1163b2`](https://github.com/Effect-TS/effect/commit/b1163b2bd67b65bafbbb39fc4c67576e5cbaf444), [`b46b869`](https://github.com/Effect-TS/effect/commit/b46b869e59a6da5aa235a9fcc25e1e0d24e9e8f8), [`de1b226`](https://github.com/Effect-TS/effect/commit/de1b226282b5ab6c2809dd93f3bdb066f24a1333), [`a663390`](https://github.com/Effect-TS/effect/commit/a66339090ae7b960f8a8b90a0dcdc505de5aaf3e), [`ff88f80`](https://github.com/Effect-TS/effect/commit/ff88f808c4ed9947a148045849e7410b00acad0a), [`11be07b`](https://github.com/Effect-TS/effect/commit/11be07bf65d82cfdf994cdb9d8ca937f995cb4f0), [`c568645`](https://github.com/Effect-TS/effect/commit/c5686451c87d26382135a1c63b00ef171bb24f62), [`88835e5`](https://github.com/Effect-TS/effect/commit/88835e575a0bfbeff9a3696a332f32192c940e12), [`b415577`](https://github.com/Effect-TS/effect/commit/b415577f6c576073733929c858e5aac27b6d5880), [`ff8046f`](https://github.com/Effect-TS/effect/commit/ff8046f57dfd073eba60ce6d3144ab060fbf93ce)]:\n  - effect@2.3.6\n\n## 0.31.6\n\n### Patch Changes\n\n- [#2131](https://github.com/Effect-TS/effect/pull/2131) [`9ee4de0`](https://github.com/Effect-TS/effect/commit/9ee4de01bb7edeefaa20cdd470e85f3c539d858f) Thanks [@tim-smart](https://github.com/tim-smart)! - ignore errors when attempting to shutdown otel\n\n## 0.31.5\n\n### Patch Changes\n\n- Updated dependencies [[`b881365`](https://github.com/Effect-TS/effect/commit/b8813650355322ea2fc1fbaa4f846bd87a7a05f3)]:\n  - effect@2.3.5\n\n## 0.31.4\n\n### Patch Changes\n\n- Updated dependencies [[`17bda66`](https://github.com/Effect-TS/effect/commit/17bda66431c999a546920c10adb205e6c8bea7d1)]:\n  - effect@2.3.4\n\n## 0.31.3\n\n### Patch Changes\n\n- Updated dependencies [[`efd41d8`](https://github.com/Effect-TS/effect/commit/efd41d8131c3d90867608969ef7c4eef490eb5e6), [`0f83515`](https://github.com/Effect-TS/effect/commit/0f83515a9c01d13c7c15a3f026e02d22c3c6bb7f), [`0f83515`](https://github.com/Effect-TS/effect/commit/0f83515a9c01d13c7c15a3f026e02d22c3c6bb7f)]:\n  - effect@2.3.3\n\n## 0.31.2\n\n### Patch Changes\n\n- Updated dependencies [[`6654f5f`](https://github.com/Effect-TS/effect/commit/6654f5f0f6b9d97165ede5e04ca16776e2599328), [`2eb11b4`](https://github.com/Effect-TS/effect/commit/2eb11b47752cedf233ef4c4395d9c4efc9b9e180), [`56c09bd`](https://github.com/Effect-TS/effect/commit/56c09bd369279a6a7785209d172739935818cba6), [`71aa5b1`](https://github.com/Effect-TS/effect/commit/71aa5b1c180dcb8b53aefe232d12a97bd06b5447), [`1700af8`](https://github.com/Effect-TS/effect/commit/1700af8af1131602887da721914c8562b6342393)]:\n  - effect@2.3.2\n\n## 0.31.1\n\n### Patch Changes\n\n- Updated dependencies [[`b5a8215`](https://github.com/Effect-TS/effect/commit/b5a8215ee2a97a8865d69ee55ce1b9835948c922)]:\n  - effect@2.3.1\n\n## 0.31.0\n\n### Minor Changes\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c) Thanks [@github-actions](https://github.com/apps/github-actions)! - With this change we now require a string key to be provided for all tags and renames the dear old `Tag` to `GenericTag`, so when previously you could do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  interface Service {\n    readonly _: unique symbol\n  }\n  const Service = Context.Tag<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >()\n  ```\n\n  you are now mandated to do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  interface Service {\n    readonly _: unique symbol\n  }\n  const Service = Context.GenericTag<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >(\"Service\")\n  ```\n\n  This makes by default all tags globals and ensures better debuggaility when unexpected errors arise.\n\n  Furthermore we introduce a new way of constructing tags that should be considered the new default:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  class Service extends Context.Tag(\"Service\")<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >() {}\n\n  const program = Effect.flatMap(Service, ({ number }) => number).pipe(\n    Effect.flatMap((_) => Effect.log(`number: ${_}`))\n  )\n  ```\n\n  this will use \"Service\" as the key and will create automatically an opaque identifier (the class) to be used at the type level, it does something similar to the above in a single shot.\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`1a77f72`](https://github.com/Effect-TS/effect/commit/1a77f72cdaf43d6cdc91b6060f82832edcdbbcb3) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Effect` type parameters order from `Effect<R, E, A>` to `Effect<A, E = never, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c) Thanks [@github-actions](https://github.com/apps/github-actions)! - This change enables `Effect.serviceConstants` and `Effect.serviceMembers` to access any constant in the service, not only the effects, namely it is now possible to do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n\n  class NumberRepo extends Context.TagClass(\"NumberRepo\")<\n    NumberRepo,\n    {\n      readonly numbers: Array<number>\n    }\n  >() {\n    static numbers = Effect.serviceConstants(NumberRepo).numbers\n  }\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`c77f635`](https://github.com/Effect-TS/effect/commit/c77f635f8a26ca6d83cb569d911f8eee79033fd9), [`e343a74`](https://github.com/Effect-TS/effect/commit/e343a74843dd9edf879417fa94cb51de7ed5b402), [`acf1894`](https://github.com/Effect-TS/effect/commit/acf1894f45945dbe5c39451e36aabb4b5092f257), [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c), [`1a77f72`](https://github.com/Effect-TS/effect/commit/1a77f72cdaf43d6cdc91b6060f82832edcdbbcb3), [`c986f0e`](https://github.com/Effect-TS/effect/commit/c986f0e0ce4d22ba08177ed351152718479ab63c), [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`70dde23`](https://github.com/Effect-TS/effect/commit/70dde238f81125e353fd7bde5fc24ecd8969bf97), [`81b7425`](https://github.com/Effect-TS/effect/commit/81b7425320cbbe2a6cf547a3e3ab3549cdba14cf), [`02c3461`](https://github.com/Effect-TS/effect/commit/02c34615d02f91269ea04036d0306fccf4e39e18), [`0e56e99`](https://github.com/Effect-TS/effect/commit/0e56e998ab9815c4d096c239a553cb86a0f99af9), [`8b0ded9`](https://github.com/Effect-TS/effect/commit/8b0ded9f10ba0d96fcb9af24eff2dbd9341f85e3), [`8dd83e8`](https://github.com/Effect-TS/effect/commit/8dd83e854bfcaa6dab876994c5f813dcfb486c28), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e), [`d75f6fe`](https://github.com/Effect-TS/effect/commit/d75f6fe6499deb0a5ee9ec94af3b5fd4eb03a2d0), [`7356e5c`](https://github.com/Effect-TS/effect/commit/7356e5cc16e9d70f18c02dee1dcb4ad539fd130a), [`3077cde`](https://github.com/Effect-TS/effect/commit/3077cde08a60246821a940964a84dd7f7c8b9f54), [`be19ce0`](https://github.com/Effect-TS/effect/commit/be19ce0b8bdf1fac80bb8d7e0b06a86986b47409), [`4a5d01a`](https://github.com/Effect-TS/effect/commit/4a5d01a409e9b6dd53893e65f8e5c9247f568021), [`78f47ab`](https://github.com/Effect-TS/effect/commit/78f47abfe3cb0a8bbde818b1c5fc603270538b47), [`52e5d20`](https://github.com/Effect-TS/effect/commit/52e5d2077582bf51f25861c7139fc920c2c24166), [`c6137ec`](https://github.com/Effect-TS/effect/commit/c6137ec62c6b5542d5062ae1a3c936cb915dee22), [`f5ae081`](https://github.com/Effect-TS/effect/commit/f5ae08195e68e76faeac258c565d79da4e01e7d6), [`4a5d01a`](https://github.com/Effect-TS/effect/commit/4a5d01a409e9b6dd53893e65f8e5c9247f568021), [`60686f5`](https://github.com/Effect-TS/effect/commit/60686f5c38bef1b93a3a0dda9b6596d46aceab03), [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e), [`8ee2931`](https://github.com/Effect-TS/effect/commit/8ee293159b4f7cb7af8558287a0a047f3a69743d), [`6727474`](https://github.com/Effect-TS/effect/commit/672747497490a30d36dd49c06db19aabf09dc7f0), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e)]:\n  - effect@2.3.0\n\n## 0.30.14\n\n### Patch Changes\n\n- Updated dependencies [[`3ddfdbf`](https://github.com/Effect-TS/effect/commit/3ddfdbf914edea536aef207cec6695f33496258c), [`3ddfdbf`](https://github.com/Effect-TS/effect/commit/3ddfdbf914edea536aef207cec6695f33496258c)]:\n  - effect@2.2.5\n\n## 0.30.13\n\n### Patch Changes\n\n- Updated dependencies [[`d0b911c`](https://github.com/Effect-TS/effect/commit/d0b911c75f284c7aa87f25aa96926e6bde7690d0), [`330e1a4`](https://github.com/Effect-TS/effect/commit/330e1a4e2c1fc0af6c80c80c81dd38c3e50fab78), [`6928a2b`](https://github.com/Effect-TS/effect/commit/6928a2b0bae86a4bdfbece0aa32924207c2d5a70), [`296bc1c`](https://github.com/Effect-TS/effect/commit/296bc1c9d24986d299d2669115d584cb27b73c60)]:\n  - effect@2.2.4\n\n## 0.30.12\n\n### Patch Changes\n\n- Updated dependencies [[`22794e0`](https://github.com/Effect-TS/effect/commit/22794e0ba00e40281f30a22fa84412003c24877d), [`f73e6c0`](https://github.com/Effect-TS/effect/commit/f73e6c033fb0729a9cfa5eb4bc39f79d3126e247)]:\n  - effect@2.2.3\n\n## 0.30.11\n\n### Patch Changes\n\n- Updated dependencies [[`d404561`](https://github.com/Effect-TS/effect/commit/d404561e47ec2fa5f68709a308ee5d2ee959141d), [`7b84a3c`](https://github.com/Effect-TS/effect/commit/7b84a3c7e4b9c8dc02294b0e3cc3ae3becea977b)]:\n  - effect@2.2.2\n\n## 0.30.10\n\n### Patch Changes\n\n- Updated dependencies [[`84da31f`](https://github.com/Effect-TS/effect/commit/84da31f0643e8651b9d311b30526b1e4edfbdfb8), [`645bea2`](https://github.com/Effect-TS/effect/commit/645bea2551129f94a5b0e38347e28067dee531bb)]:\n  - effect@2.2.1\n\n## 0.30.9\n\n### Patch Changes\n\n- Updated dependencies [[`202befc`](https://github.com/Effect-TS/effect/commit/202befc2ecbeb117c4fa85ef9b12a3d3a48273d2), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`10df798`](https://github.com/Effect-TS/effect/commit/10df798639e556f9d88265ef7fc3cf8a3bbe3874)]:\n  - effect@2.2.0\n\n## 0.30.8\n\n### Patch Changes\n\n- Updated dependencies [[`21b9edd`](https://github.com/Effect-TS/effect/commit/21b9edde464f7c5624ef54ad1b5e264204a37625)]:\n  - effect@2.1.2\n\n## 0.30.7\n\n### Patch Changes\n\n- Updated dependencies [[`a222524`](https://github.com/Effect-TS/effect/commit/a2225247e9de2e013d287320790fde88c081dbbd)]:\n  - effect@2.1.1\n\n## 0.30.6\n\n### Patch Changes\n\n- Updated dependencies [[`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02)]:\n  - effect@2.1.0\n\n## 0.30.5\n\n### Patch Changes\n\n- Updated dependencies [[`f7f19f6`](https://github.com/Effect-TS/effect/commit/f7f19f66a5fa349baa2412c1f9f15111c437df09)]:\n  - effect@2.0.5\n\n## 0.30.4\n\n### Patch Changes\n\n- Updated dependencies [[`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`540b294`](https://github.com/Effect-TS/effect/commit/540b2941dd0a81e9688311583ce7e2e140d6e7a5), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`a3f96d6`](https://github.com/Effect-TS/effect/commit/a3f96d615b8b3e238dbfa01ef713c87e6f4532be), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`25adce7`](https://github.com/Effect-TS/effect/commit/25adce7ae76ce834096dca1ed70a60ad1a349217), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51)]:\n  - effect@2.0.4\n\n## 0.30.3\n\n### Patch Changes\n\n- Updated dependencies [[`87f7ef2`](https://github.com/Effect-TS/effect/commit/87f7ef28a3c27e2e4f2fcfa465f85bb2a45a3d6b), [`1d3a06b`](https://github.com/Effect-TS/effect/commit/1d3a06bb58ad1ac123ae8f9d42b4345f9c9c53c0)]:\n  - effect@2.0.3\n\n## 0.30.2\n\n### Patch Changes\n\n- Updated dependencies [[`d5a1949`](https://github.com/Effect-TS/effect/commit/d5a19499aac7c1d147674a35ac69992177c7536c)]:\n  - effect@2.0.2\n\n## 0.30.1\n\n### Patch Changes\n\n- Updated dependencies [[`16bd87d`](https://github.com/Effect-TS/effect/commit/16bd87d32611b966dc42ea4fc979764f97a49071)]:\n  - effect@2.0.1\n\n## 0.30.0\n\n### Minor Changes\n\n- [`d0471ca`](https://github.com/Effect-TS/effect/commit/d0471ca7b544746674b9e1750202da72b0a21233) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Switch to monorepo structure\n\n- [#1846](https://github.com/Effect-TS/effect/pull/1846) [`693b8f3`](https://github.com/Effect-TS/effect/commit/693b8f3a3dfd43ae61f0d9292cdf356be7329f2f) Thanks [@fubhy](https://github.com/fubhy)! - Enabled `exactOptionalPropertyTypes` throughout\n\n### Patch Changes\n\n- [`d987daa`](https://github.com/Effect-TS/effect/commit/d987daafaddd43b6ade74916a08236c19ea0a9fa) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Switch effect dependency to caret\n\n- [#1847](https://github.com/Effect-TS/effect/pull/1847) [`bcf0900`](https://github.com/Effect-TS/effect/commit/bcf0900b58f449262556f80bff21e771a37272aa) Thanks [@fubhy](https://github.com/fubhy)! - Avoid inline creation & spreading of objects and arrays\n\n- Updated dependencies [[`d987daa`](https://github.com/Effect-TS/effect/commit/d987daafaddd43b6ade74916a08236c19ea0a9fa), [`7b5eaa3`](https://github.com/Effect-TS/effect/commit/7b5eaa3838c79bf4bdccf91b94d61bbc38a2ec95), [`0724211`](https://github.com/Effect-TS/effect/commit/072421149c36010748ff6b6ee19c15c6cffefe09), [`9f2bc5a`](https://github.com/Effect-TS/effect/commit/9f2bc5a19e0b678a0a85e84daac290922b0fd57d), [`04fb8b4`](https://github.com/Effect-TS/effect/commit/04fb8b428b19bba85a2c79910c5e363340d074e7), [`d0471ca`](https://github.com/Effect-TS/effect/commit/d0471ca7b544746674b9e1750202da72b0a21233), [`bcf0900`](https://github.com/Effect-TS/effect/commit/bcf0900b58f449262556f80bff21e771a37272aa), [`6299b84`](https://github.com/Effect-TS/effect/commit/6299b84c11e5d1fe79fa538df8935018c7613747)]:\n  - effect@2.0.0\n\n## 0.29.0\n\n### Minor Changes\n\n- [#106](https://github.com/Effect-TS/opentelemetry/pull/106) [`d0fb6b6`](https://github.com/Effect-TS/opentelemetry/commit/d0fb6b6aa18c9c0021cda1a421492c8ba1cb5400) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.28.0\n\n### Minor Changes\n\n- [#104](https://github.com/Effect-TS/opentelemetry/pull/104) [`29484a9`](https://github.com/Effect-TS/opentelemetry/commit/29484a979e1a72e5099cf935f3f2c75624e58f5c) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.27.0\n\n### Minor Changes\n\n- [#102](https://github.com/Effect-TS/opentelemetry/pull/102) [`056e416`](https://github.com/Effect-TS/opentelemetry/commit/056e416edf7fda5bce8ff89a05672c894c47a332) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.26.0\n\n### Minor Changes\n\n- [#100](https://github.com/Effect-TS/opentelemetry/pull/100) [`091e0e5`](https://github.com/Effect-TS/opentelemetry/commit/091e0e57342b09bcf58c91b8f4628c5d2e74b039) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.25.1\n\n### Patch Changes\n\n- [#98](https://github.com/Effect-TS/opentelemetry/pull/98) [`93b6fab`](https://github.com/Effect-TS/opentelemetry/commit/93b6fabe6167ceb15ea35e86d8539a8117d0e203) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.25.0\n\n### Minor Changes\n\n- [#96](https://github.com/Effect-TS/opentelemetry/pull/96) [`63b82a3`](https://github.com/Effect-TS/opentelemetry/commit/63b82a3768ec47a5b38ff2b0dc61c24c226c0e5f) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n### Patch Changes\n\n- [#96](https://github.com/Effect-TS/opentelemetry/pull/96) [`63b82a3`](https://github.com/Effect-TS/opentelemetry/commit/63b82a3768ec47a5b38ff2b0dc61c24c226c0e5f) Thanks [@tim-smart](https://github.com/tim-smart)! - accept Effect's for sdk constructors\n\n## 0.24.0\n\n### Minor Changes\n\n- [#94](https://github.com/Effect-TS/opentelemetry/pull/94) [`e1afffc`](https://github.com/Effect-TS/opentelemetry/commit/e1afffccee1638c42db0d61fc3dd47ee728cbf21) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.23.0\n\n### Minor Changes\n\n- [#92](https://github.com/Effect-TS/opentelemetry/pull/92) [`0a39315`](https://github.com/Effect-TS/opentelemetry/commit/0a39315de29d79488ab808db12f75ddf50098a79) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.22.1\n\n### Patch Changes\n\n- [#89](https://github.com/Effect-TS/opentelemetry/pull/89) [`97db04d`](https://github.com/Effect-TS/opentelemetry/commit/97db04dae7d7f5e97b79fff8ecd4e32c0486ec67) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.22.0\n\n### Minor Changes\n\n- [#86](https://github.com/Effect-TS/opentelemetry/pull/86) [`ac41f21`](https://github.com/Effect-TS/opentelemetry/commit/ac41f21b691299d1472f0ecfacca9ba274b71afb) Thanks [@fubhy](https://github.com/fubhy)! - Switch to peer dependencies\n\n- [#88](https://github.com/Effect-TS/opentelemetry/pull/88) [`10be3aa`](https://github.com/Effect-TS/opentelemetry/commit/10be3aa6ded8a028eec1a46830ab68bceaf41ca3) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.21.1\n\n### Patch Changes\n\n- [#84](https://github.com/Effect-TS/opentelemetry/pull/84) [`6553dac`](https://github.com/Effect-TS/opentelemetry/commit/6553dac0c28523e1e09bd5628159688a1aa7b00b) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.21.0\n\n### Minor Changes\n\n- [#82](https://github.com/Effect-TS/opentelemetry/pull/82) [`8e1b9f6`](https://github.com/Effect-TS/opentelemetry/commit/8e1b9f6509e108cc145313bc7dea8f4d1629cc53) Thanks [@tim-smart](https://github.com/tim-smart)! - add Resource config to sdk layers\n\n- [#83](https://github.com/Effect-TS/opentelemetry/pull/83) [`fab878b`](https://github.com/Effect-TS/opentelemetry/commit/fab878bbd99e9c7163f87ba5ef40986b3cb33eaf) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n- [#79](https://github.com/Effect-TS/opentelemetry/pull/79) [`fca35c8`](https://github.com/Effect-TS/opentelemetry/commit/fca35c8cec7760b6e172fdb9890972f36dc2ebc5) Thanks [@tim-smart](https://github.com/tim-smart)! - use scoped TracerProvider\n\n- [#79](https://github.com/Effect-TS/opentelemetry/pull/79) [`fca35c8`](https://github.com/Effect-TS/opentelemetry/commit/fca35c8cec7760b6e172fdb9890972f36dc2ebc5) Thanks [@tim-smart](https://github.com/tim-smart)! - update Sdk apis\n\n### Patch Changes\n\n- [#79](https://github.com/Effect-TS/opentelemetry/pull/79) [`fca35c8`](https://github.com/Effect-TS/opentelemetry/commit/fca35c8cec7760b6e172fdb9890972f36dc2ebc5) Thanks [@tim-smart](https://github.com/tim-smart)! - add WebSdk module\n\n## 0.20.0\n\n### Minor Changes\n\n- [#77](https://github.com/Effect-TS/opentelemetry/pull/77) [`03d1e6a`](https://github.com/Effect-TS/opentelemetry/commit/03d1e6ad53e125528f1093da7c2ac6b4007c4d6d) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.19.0\n\n### Minor Changes\n\n- [#75](https://github.com/Effect-TS/opentelemetry/pull/75) [`706479f`](https://github.com/Effect-TS/opentelemetry/commit/706479fcb2e31f0ed057038abbf17a47a966fba3) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.18.0\n\n### Minor Changes\n\n- [#72](https://github.com/Effect-TS/opentelemetry/pull/72) [`9e563ef`](https://github.com/Effect-TS/opentelemetry/commit/9e563ef249b0b556c03b7c3e1d9872ef9c54c8b3) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n- [#74](https://github.com/Effect-TS/opentelemetry/pull/74) [`fe93fd2`](https://github.com/Effect-TS/opentelemetry/commit/fe93fd2b3e641563425fe38b56efb8c750018f02) Thanks [@tim-smart](https://github.com/tim-smart)! - use lazy arg for node sdk layer config\n\n## 0.17.0\n\n### Minor Changes\n\n- [#70](https://github.com/Effect-TS/opentelemetry/pull/70) [`f1b1d03`](https://github.com/Effect-TS/opentelemetry/commit/f1b1d039b686a2a5733cc19b0fca3a3f7abaf2d8) Thanks [@gcanti](https://github.com/gcanti)! - update effect\n\n## 0.16.0\n\n### Minor Changes\n\n- [#68](https://github.com/Effect-TS/opentelemetry/pull/68) [`6340117`](https://github.com/Effect-TS/opentelemetry/commit/6340117165cd08a36c0178cb6b48e5db86e745ea) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.15.1\n\n### Patch Changes\n\n- [#66](https://github.com/Effect-TS/opentelemetry/pull/66) [`09cf96b`](https://github.com/Effect-TS/opentelemetry/commit/09cf96b7fd29f38bcbb1fa16f736fc2f42f1a75f) Thanks [@tim-smart](https://github.com/tim-smart)! - fix root spans\n\n## 0.15.0\n\n### Minor Changes\n\n- [#64](https://github.com/Effect-TS/opentelemetry/pull/64) [`4b0608e`](https://github.com/Effect-TS/opentelemetry/commit/4b0608e50b9ab6406bf69ec12ae1d138bebe5497) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.14.0\n\n### Minor Changes\n\n- [#61](https://github.com/Effect-TS/opentelemetry/pull/61) [`7d1898b`](https://github.com/Effect-TS/opentelemetry/commit/7d1898b7efbab4aa6a7e43999591629cb67f80bd) Thanks [@tim-smart](https://github.com/tim-smart)! - switch to preconstruct for builds\n\n## 0.13.1\n\n### Patch Changes\n\n- [#57](https://github.com/Effect-TS/opentelemetry/pull/57) [`d857912`](https://github.com/Effect-TS/opentelemetry/commit/d857912359f0a842ac56bb6cfdee97b1badde479) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.13.0\n\n### Minor Changes\n\n- [#55](https://github.com/Effect-TS/opentelemetry/pull/55) [`1ae529d`](https://github.com/Effect-TS/opentelemetry/commit/1ae529d310e79bd703a6060589dfe919bbe2b2c4) Thanks [@tim-smart](https://github.com/tim-smart)! - update to effect package\n\n## 0.12.0\n\n### Minor Changes\n\n- [#54](https://github.com/Effect-TS/opentelemetry/pull/54) [`2af42ea`](https://github.com/Effect-TS/opentelemetry/commit/2af42ea90abde92c6c3832e585389c6697f487b3) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n### Patch Changes\n\n- [#52](https://github.com/Effect-TS/opentelemetry/pull/52) [`c9dcaf5`](https://github.com/Effect-TS/opentelemetry/commit/c9dcaf562bf8bd4567ec1355ee0744c3ddbb4e3f) Thanks [@tim-smart](https://github.com/tim-smart)! - makeExternalSpan is now compatible with the span context interface\n\n- [#52](https://github.com/Effect-TS/opentelemetry/pull/52) [`c9dcaf5`](https://github.com/Effect-TS/opentelemetry/commit/c9dcaf562bf8bd4567ec1355ee0744c3ddbb4e3f) Thanks [@tim-smart](https://github.com/tim-smart)! - add currentOtelSpan accessor\n\n## 0.11.1\n\n### Patch Changes\n\n- [#50](https://github.com/Effect-TS/opentelemetry/pull/50) [`70f551a`](https://github.com/Effect-TS/opentelemetry/commit/70f551afa76109dc4ab8ad76c55995cd67f2ef86) Thanks [@tim-smart](https://github.com/tim-smart)! - expose otel tracer with tag + layer\n\n## 0.11.0\n\n### Minor Changes\n\n- [#48](https://github.com/Effect-TS/opentelemetry/pull/48) [`2487f92`](https://github.com/Effect-TS/opentelemetry/commit/2487f92a6dccfc87666fced4a37df60aebb38f9d) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io\n\n## 0.10.0\n\n### Minor Changes\n\n- [#46](https://github.com/Effect-TS/opentelemetry/pull/46) [`fcd35a7`](https://github.com/Effect-TS/opentelemetry/commit/fcd35a76db860d9f8999f294d0b1add3f9d65a99) Thanks [@tim-smart](https://github.com/tim-smart)! - remove Metric labels\n\n- [#46](https://github.com/Effect-TS/opentelemetry/pull/46) [`fcd35a7`](https://github.com/Effect-TS/opentelemetry/commit/fcd35a76db860d9f8999f294d0b1add3f9d65a99) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.9.1\n\n### Patch Changes\n\n- [#9](https://github.com/Effect-TS/opentelemetry/pull/9) [`3a3e25f`](https://github.com/Effect-TS/opentelemetry/commit/3a3e25fd153bc70a2be500f1c9c69002e238ed7a) Thanks [@tim-smart](https://github.com/tim-smart)! - add Metrics module\n\n## 0.9.0\n\n### Minor Changes\n\n- [#44](https://github.com/Effect-TS/opentelemetry/pull/44) [`d0a845d`](https://github.com/Effect-TS/opentelemetry/commit/d0a845da6e409718951834ad6d5681e5dfb4acbc) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n### Patch Changes\n\n- [#41](https://github.com/Effect-TS/opentelemetry/pull/41) [`271984d`](https://github.com/Effect-TS/opentelemetry/commit/271984d7a56096810d51a31bad652b501b854445) Thanks [@tim-smart](https://github.com/tim-smart)! - use peer deps for /data, /io and @opentelemetry/api\n\n- [#43](https://github.com/Effect-TS/opentelemetry/pull/43) [`80faed0`](https://github.com/Effect-TS/opentelemetry/commit/80faed049abf6c57f35d4545f9d6499014783aeb) Thanks [@tim-smart](https://github.com/tim-smart)! - update build tools\n\n## 0.8.2\n\n### Patch Changes\n\n- [#39](https://github.com/Effect-TS/opentelemetry/pull/39) [`4345aa6`](https://github.com/Effect-TS/opentelemetry/commit/4345aa606b82d0690859359fb47074d365b4a729) Thanks [@tim-smart](https://github.com/tim-smart)! - set status.interrupted attribute on interruption\n\n## 0.8.1\n\n### Patch Changes\n\n- [#37](https://github.com/Effect-TS/opentelemetry/pull/37) [`843a017`](https://github.com/Effect-TS/opentelemetry/commit/843a017515fc0546f60a742a9b8ab860edbeac22) Thanks [@tim-smart](https://github.com/tim-smart)! - add additional info to interrupted spans\n\n## 0.8.0\n\n### Minor Changes\n\n- [#35](https://github.com/Effect-TS/opentelemetry/pull/35) [`c7e4387`](https://github.com/Effect-TS/opentelemetry/commit/c7e438784bb3396e529ccd4bb751aa48e579ba2c) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io - support for links\n\n## 0.7.1\n\n### Patch Changes\n\n- [#32](https://github.com/Effect-TS/opentelemetry/pull/32) [`d66c490`](https://github.com/Effect-TS/opentelemetry/commit/d66c4906a78606549bcbbc852cd36a6626473a10) Thanks [@tim-smart](https://github.com/tim-smart)! - remove name from makeExternalSpan\n\n## 0.7.0\n\n### Minor Changes\n\n- [#30](https://github.com/Effect-TS/opentelemetry/pull/30) [`3b2e776`](https://github.com/Effect-TS/opentelemetry/commit/3b2e77600709e2dbc0a7bca158c1604d7b027427) Thanks [@tim-smart](https://github.com/tim-smart)! - update /data and /io\n\n## 0.6.0\n\n### Minor Changes\n\n- [#28](https://github.com/Effect-TS/opentelemetry/pull/28) [`933eafa`](https://github.com/Effect-TS/opentelemetry/commit/933eafa22317e6f946ef0bab66ab5426092b9bf1) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io and /data\n\n## 0.5.0\n\n### Minor Changes\n\n- [#26](https://github.com/Effect-TS/opentelemetry/pull/26) [`365a7d2`](https://github.com/Effect-TS/opentelemetry/commit/365a7d2c85180f3491b433aa617ee213ccc1e855) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io\n\n## 0.4.0\n\n### Minor Changes\n\n- [#24](https://github.com/Effect-TS/opentelemetry/pull/24) [`bc689b0`](https://github.com/Effect-TS/opentelemetry/commit/bc689b06680700d6025556e2cefec9213002dc17) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io and /data\n\n## 0.3.1\n\n### Patch Changes\n\n- [#22](https://github.com/Effect-TS/opentelemetry/pull/22) [`d78883d`](https://github.com/Effect-TS/opentelemetry/commit/d78883d12471150a626698e9432a100abf730e97) Thanks [@tim-smart](https://github.com/tim-smart)! - move node-sdk to dependencies\n\n## 0.3.0\n\n### Minor Changes\n\n- [#20](https://github.com/Effect-TS/opentelemetry/pull/20) [`347904e`](https://github.com/Effect-TS/opentelemetry/commit/347904e5330b0c1ce1d809dbb4aeea1fd22f4231) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io and /data\n\n### Patch Changes\n\n- [#20](https://github.com/Effect-TS/opentelemetry/pull/20) [`347904e`](https://github.com/Effect-TS/opentelemetry/commit/347904e5330b0c1ce1d809dbb4aeea1fd22f4231) Thanks [@tim-smart](https://github.com/tim-smart)! - add supervisor for correctly setting otel context for fiber executions\n\n## 0.2.0\n\n### Minor Changes\n\n- [#18](https://github.com/Effect-TS/opentelemetry/pull/18) [`867195a`](https://github.com/Effect-TS/opentelemetry/commit/867195a3622d2678e684bc84959bbe7e3ada9c3c) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io\n  - adds support for nanosecond precision in timing\n  - add `makeExternalSpan` utility for creating parent spans\n\n## 0.1.3\n\n### Patch Changes\n\n- [#16](https://github.com/Effect-TS/opentelemetry/pull/16) [`fa067d9`](https://github.com/Effect-TS/opentelemetry/commit/fa067d9cfa173a18e00dc9d9d19048af26c09ef3) Thanks [@tim-smart](https://github.com/tim-smart)! - add helper for constructing NodeSdk config\n\n## 0.1.2\n\n### Patch Changes\n\n- [#14](https://github.com/Effect-TS/opentelemetry/pull/14) [`31653b4`](https://github.com/Effect-TS/opentelemetry/commit/31653b4ba6daa91bb74fd0b8b2a42b60e4b2c25e) Thanks [@tim-smart](https://github.com/tim-smart)! - make NodeSdk config an Effect\n\n## 0.1.1\n\n### Patch Changes\n\n- [#12](https://github.com/Effect-TS/opentelemetry/pull/12) [`0bc9ca2`](https://github.com/Effect-TS/opentelemetry/commit/0bc9ca2cccf252608a1a91a13554e901d345e5e1) Thanks [@tim-smart](https://github.com/tim-smart)! - add /Resource module\n\n## 0.1.0\n\n### Minor Changes\n\n- [#8](https://github.com/Effect-TS/opentelemetry/pull/8) [`acc90fd`](https://github.com/Effect-TS/opentelemetry/commit/acc90fd41175a99bbe148c97518a4e312c72b92a) Thanks [@tim-smart](https://github.com/tim-smart)! - implement /io/Tracer\n\n### Patch Changes\n\n- [#10](https://github.com/Effect-TS/opentelemetry/pull/10) [`f9d9045`](https://github.com/Effect-TS/opentelemetry/commit/f9d90459ba47a30edbf56edc33d024bd73f335f1) Thanks [@tim-smart](https://github.com/tim-smart)! - add NodeSdk module\n"
  },
  {
    "path": "packages/opentelemetry/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2020-present The Contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/opentelemetry/README.md",
    "content": "# `@effect/opentelemetry`\n\n## Documentation\n\n- **API Reference**: [View the full documentation](https://effect-ts.github.io/effect/docs/opentelemetry).\n"
  },
  {
    "path": "packages/opentelemetry/docgen.json",
    "content": "{\n  \"$schema\": \"../../node_modules/@effect/docgen/schema.json\",\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/opentelemetry/src/\",\n  \"exclude\": [\n    \"src/internal/**/*.ts\"\n  ]\n}\n"
  },
  {
    "path": "packages/opentelemetry/examples/index.ts",
    "content": "import * as NodeSdk from \"@effect/opentelemetry/NodeSdk\"\nimport { ConsoleSpanExporter, SimpleSpanProcessor } from \"@opentelemetry/sdk-trace-base\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\n\nconst NodeSdkLive = NodeSdk.layer(() => ({\n  resource: {\n    serviceName: \"example\"\n  },\n  spanProcessor: new SimpleSpanProcessor(new ConsoleSpanExporter())\n}))\n\nconst program = pipe(\n  Effect.log(\"Hello\"),\n  Effect.withSpan(\"c\"),\n  Effect.withSpan(\"b\"),\n  Effect.withSpan(\"a\")\n)\n\npipe(\n  program,\n  Effect.provide(NodeSdkLive),\n  Effect.catchAllCause(Effect.logError),\n  Effect.runFork\n)\n"
  },
  {
    "path": "packages/opentelemetry/examples/metrics.ts",
    "content": "import * as NodeSdk from \"@effect/opentelemetry/NodeSdk\"\nimport { PrometheusExporter } from \"@opentelemetry/exporter-prometheus\"\nimport { millis, seconds } from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Metric from \"effect/Metric\"\n\nconst counter = Metric.counter(\"count\", {\n  description: \"An example counter\"\n})\n\nconst incrementCounter = pipe(\n  Metric.increment(counter),\n  Effect.delay(seconds(1)),\n  Effect.forever\n)\n\nconst timer = Metric.timer(\"timer\")\n\nconst timerLoop = pipe(\n  Effect.randomWith((_) => _.nextRange(1, 1000)),\n  Effect.flatMap((_) => Effect.sleep(millis(_))),\n  Metric.trackDuration(timer),\n  Effect.forever\n)\n\nconst freq = Metric.frequency(\"freq\")\nconst labels = [\n  \"cake\",\n  \"pie\",\n  \"cookie\",\n  \"brownie\",\n  \"muffin\"\n]\n\nconst freqLoop = Effect.randomWith((_) => _.nextIntBetween(0, labels.length)).pipe(\n  Effect.flatMap((_) => Metric.update(freq, labels[_])),\n  Effect.zipRight(Effect.sleep(\"1 seconds\")),\n  Effect.forever\n)\n\nconst summary = Metric.summary({\n  name: \"summary\",\n  maxAge: \"1 days\",\n  maxSize: 1000,\n  error: 0.01,\n  quantiles: [0.1, 0.5, 0.9]\n})\n\nconst summaryLoop = Effect.randomWith((_) => _.nextRange(100, 1000)).pipe(\n  Metric.trackSuccess(summary),\n  Effect.zipRight(Effect.sleep(\"10 millis\")),\n  Effect.forever\n)\n\nconst spawner = Effect.randomWith((_) => _.nextIntBetween(500, 1500)).pipe(\n  Effect.flatMap((_) => Effect.fork(Effect.sleep(_))),\n  Effect.flatMap((_) => _.await),\n  Effect.forever\n)\n\nconst program = Effect.gen(function*() {\n  yield* Effect.fork(incrementCounter)\n  yield* Effect.fork(timerLoop)\n  yield* Effect.fork(freqLoop)\n  yield* Effect.fork(summaryLoop)\n  yield* Effect.fork(spawner)\n})\n\nconst MetricsLive = NodeSdk.layer(() => ({\n  resource: {\n    serviceName: \"example\"\n  },\n  metricReader: new PrometheusExporter({ port: 9464 })\n}))\n\npipe(\n  program,\n  Effect.awaitAllChildren,\n  Effect.provide(MetricsLive),\n  Effect.catchAllCause(Effect.logError),\n  Effect.runFork\n)\n"
  },
  {
    "path": "packages/opentelemetry/examples/native-exporter.ts",
    "content": "import * as Otlp from \"@effect/opentelemetry/Otlp\"\nimport * as FetchHttpClient from \"@effect/platform/FetchHttpClient\"\nimport { Effect, Layer, Schedule } from \"effect\"\nimport * as Logger from \"effect/Logger\"\nimport * as LogLevel from \"effect/LogLevel\"\n\nconst Observability = Otlp.layerJson({\n  baseUrl: \"http://localhost:4318\",\n  resource: {\n    serviceName: \"my-service\"\n  }\n}).pipe(Layer.provide(FetchHttpClient.layer))\n\nconst program = Effect.log(\"Hello\").pipe(\n  Effect.withSpan(\"c\"),\n  Effect.withSpan(\"b\"),\n  Effect.withSpan(\"a\"),\n  Effect.schedule(Schedule.spaced(1000)),\n  Effect.annotateSpans(\"working\", true)\n)\n\nconst failingProgram = Effect.fail(new Error(\"Failing program\")).pipe(\n  Effect.withSpan(\"d\")\n)\n\nprogram.pipe(\n  Effect.andThen(failingProgram),\n  Effect.provide(Observability),\n  Effect.catchAllCause(Effect.logError),\n  Logger.withMinimumLogLevel(LogLevel.All),\n  Effect.runFork\n)\n"
  },
  {
    "path": "packages/opentelemetry/examples/otlp-exporter.ts",
    "content": "import * as NodeSdk from \"@effect/opentelemetry/NodeSdk\"\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-http\"\nimport { BatchSpanProcessor } from \"@opentelemetry/sdk-trace-base\"\nimport { seconds } from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\n\nconst NodeSdkLive = NodeSdk.layer(() => ({\n  resource: {\n    serviceName: \"example\"\n  },\n  spanProcessor: new BatchSpanProcessor(\n    new OTLPTraceExporter({\n      url: \"http://localhost:4318/v1/traces\"\n    })\n  )\n}))\n\nconst program = pipe(\n  Effect.log(\"Hello\"),\n  Effect.withSpan(\"c\"),\n  Effect.withSpan(\"b\"),\n  Effect.withSpan(\"a\"),\n  Effect.repeatN(50),\n  Effect.annotateSpans(\"working\", true)\n)\n\npipe(\n  Effect.delay(program, seconds(1)),\n  Effect.provide(NodeSdkLive),\n  Effect.catchAllCause(Effect.logError),\n  Effect.runFork\n)\n"
  },
  {
    "path": "packages/opentelemetry/package.json",
    "content": "{\n  \"name\": \"@effect/opentelemetry\",\n  \"version\": \"0.63.0\",\n  \"type\": \"module\",\n  \"license\": \"MIT\",\n  \"description\": \"OpenTelemetry integration for Effect\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/opentelemetry\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"opentelemetry\",\n    \"observability\",\n    \"tracing\",\n    \"metrics\",\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"keywords\": [\n    \"opentelemetry\",\n    \"observability\",\n    \"tracing\",\n    \"metrics\",\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"peerDependencies\": {\n    \"@effect/platform\": \"workspace:^\",\n    \"@opentelemetry/api\": \"^1.9\",\n    \"@opentelemetry/resources\": \"^2.0.0\",\n    \"@opentelemetry/sdk-logs\": \">=0.203.0 <0.300.0\",\n    \"@opentelemetry/sdk-metrics\": \"^2.0.0\",\n    \"@opentelemetry/sdk-trace-base\": \"^2.0.0\",\n    \"@opentelemetry/sdk-trace-node\": \"^2.0.0\",\n    \"@opentelemetry/sdk-trace-web\": \"^2.0.0\",\n    \"@opentelemetry/semantic-conventions\": \"^1.33.0\",\n    \"effect\": \"workspace:^\"\n  },\n  \"devDependencies\": {\n    \"@effect/platform\": \"workspace:^\",\n    \"@opentelemetry/api\": \"^1.9.0\",\n    \"@opentelemetry/context-async-hooks\": \"^2.2.0\",\n    \"@opentelemetry/exporter-metrics-otlp-http\": \"0.208.0\",\n    \"@opentelemetry/exporter-prometheus\": \"^0.208.0\",\n    \"@opentelemetry/exporter-trace-otlp-http\": \"^0.208.0\",\n    \"@opentelemetry/otlp-exporter-base\": \"^0.208.0\",\n    \"@opentelemetry/resources\": \"^2.2.0\",\n    \"@opentelemetry/sdk-logs\": \"^0.208.0\",\n    \"@opentelemetry/sdk-metrics\": \"^2.2.0\",\n    \"@opentelemetry/sdk-trace-base\": \"^2.2.0\",\n    \"@opentelemetry/sdk-trace-node\": \"^2.2.0\",\n    \"@opentelemetry/sdk-trace-web\": \"^2.2.0\",\n    \"@opentelemetry/semantic-conventions\": \"^1.38.0\"\n  }\n}\n"
  },
  {
    "path": "packages/opentelemetry/src/Logger.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Otel from \"@opentelemetry/sdk-logs\"\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport * as Arr from \"effect/Array\"\nimport * as Context from \"effect/Context\"\nimport type { DurationInput } from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberId from \"effect/FiberId\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport * as FiberRefs from \"effect/FiberRefs\"\nimport * as Layer from \"effect/Layer\"\nimport * as Logger from \"effect/Logger\"\nimport * as Tracer from \"effect/Tracer\"\nimport { unknownToAttributeValue } from \"./internal/utils.js\"\nimport { Resource } from \"./Resource.js\"\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport class OtelLoggerProvider extends Context.Tag(\"@effect/opentelemetry/Logger/OtelLoggerProvider\")<\n  OtelLoggerProvider,\n  Otel.LoggerProvider\n>() {}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: Effect.Effect<\n  Logger.Logger<unknown, void>,\n  never,\n  OtelLoggerProvider\n> = Effect.gen(function*() {\n  const loggerProvider = yield* OtelLoggerProvider\n  const clock = yield* Effect.clock\n  const otelLogger = loggerProvider.getLogger(\"@effect/opentelemetry\")\n\n  return Logger.make((options) => {\n    const now = options.date.getTime()\n\n    const attributes: Record<string, any> = {\n      fiberId: FiberId.threadName(options.fiberId)\n    }\n\n    const maybeSpan = Context.getOption(\n      FiberRefs.getOrDefault(options.context, FiberRef.currentContext),\n      Tracer.ParentSpan\n    )\n\n    if (maybeSpan._tag === \"Some\") {\n      attributes.spanId = maybeSpan.value.spanId\n      attributes.traceId = maybeSpan.value.traceId\n    }\n\n    for (const [key, value] of options.annotations) {\n      attributes[key] = unknownToAttributeValue(value)\n    }\n    for (const span of options.spans) {\n      attributes[`logSpan.${span.label}`] = `${now - span.startTime}ms`\n    }\n\n    const message = Arr.ensure(options.message).map(unknownToAttributeValue)\n    otelLogger.emit({\n      body: message.length === 1 ? message[0] : message,\n      severityText: options.logLevel.label,\n      severityNumber: options.logLevel.ordinal,\n      timestamp: options.date,\n      observedTimestamp: clock.unsafeCurrentTimeMillis(),\n      attributes\n    })\n  })\n})\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerLoggerAdd: Layer.Layer<\n  never,\n  never,\n  OtelLoggerProvider\n> = Logger.addEffect(make)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerLoggerReplace: Layer.Layer<\n  never,\n  never,\n  OtelLoggerProvider\n> = Logger.replaceEffect(Logger.defaultLogger, make)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerLoggerProvider = (\n  processor: Otel.LogRecordProcessor | NonEmptyReadonlyArray<Otel.LogRecordProcessor>,\n  config?: Omit<Otel.LoggerProviderConfig, \"resource\"> & {\n    readonly shutdownTimeout?: DurationInput | undefined\n  }\n): Layer.Layer<OtelLoggerProvider, never, Resource> =>\n  Layer.scoped(\n    OtelLoggerProvider,\n    Effect.flatMap(Resource, (resource) =>\n      Effect.acquireRelease(\n        Effect.sync(() =>\n          new Otel.LoggerProvider({\n            ...(config ?? undefined),\n            processors: Arr.ensure(processor),\n            resource\n          })\n        ),\n        (provider) =>\n          Effect.promise(\n            () => provider.forceFlush().then(() => provider.shutdown())\n          ).pipe(\n            Effect.ignoreLogged,\n            Effect.interruptible,\n            Effect.timeoutOption(config?.shutdownTimeout ?? 3000)\n          )\n      ))\n  )\n"
  },
  {
    "path": "packages/opentelemetry/src/Metrics.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { MetricProducer, MetricReader } from \"@opentelemetry/sdk-metrics\"\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport type { DurationInput } from \"effect/Duration\"\nimport type * as Effect from \"effect/Effect\"\nimport type { LazyArg } from \"effect/Function\"\nimport type { Layer } from \"effect/Layer\"\nimport type * as Scope from \"effect/Scope\"\nimport * as internal from \"./internal/metrics.js\"\nimport type { Resource } from \"./Resource.js\"\n\n/**\n * @since 1.0.0\n * @category producer\n */\nexport const makeProducer: Effect.Effect<MetricProducer, never, Resource> = internal.makeProducer\n\n/**\n * @since 1.0.0\n * @category producer\n */\nexport const registerProducer: (\n  self: MetricProducer,\n  metricReader: LazyArg<MetricReader | NonEmptyReadonlyArray<MetricReader>>\n) => Effect.Effect<Array<any>, never, Scope.Scope> = internal.registerProducer\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer: (\n  evaluate: LazyArg<MetricReader | NonEmptyReadonlyArray<MetricReader>>,\n  options?: {\n    readonly shutdownTimeout?:\n      | DurationInput\n      | undefined\n  }\n) => Layer<never, never, Resource> = internal.layer\n"
  },
  {
    "path": "packages/opentelemetry/src/NodeSdk.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as OtelApi from \"@opentelemetry/api\"\nimport type { LoggerProviderConfig, LogRecordProcessor } from \"@opentelemetry/sdk-logs\"\nimport type { MetricReader } from \"@opentelemetry/sdk-metrics\"\nimport type { SpanProcessor, TracerConfig } from \"@opentelemetry/sdk-trace-base\"\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\"\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport type { DurationInput } from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport { constant, type LazyArg } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport { isNonEmpty } from \"./internal/utils.js\"\nimport * as Logger from \"./Logger.js\"\nimport * as Metrics from \"./Metrics.js\"\nimport * as Resource from \"./Resource.js\"\nimport * as Tracer from \"./Tracer.js\"\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport interface Configuration {\n  readonly spanProcessor?: SpanProcessor | ReadonlyArray<SpanProcessor> | undefined\n  readonly tracerConfig?: Omit<TracerConfig, \"resource\"> | undefined\n  readonly metricReader?: MetricReader | ReadonlyArray<MetricReader> | undefined\n  readonly logRecordProcessor?: LogRecordProcessor | ReadonlyArray<LogRecordProcessor> | undefined\n  readonly loggerProviderConfig?: Omit<LoggerProviderConfig, \"resource\"> | undefined\n  readonly resource?: {\n    readonly serviceName: string\n    readonly serviceVersion?: string\n    readonly attributes?: OtelApi.Attributes\n  } | undefined\n  readonly shutdownTimeout?: DurationInput | undefined\n}\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerTracerProvider = (\n  processor: SpanProcessor | NonEmptyReadonlyArray<SpanProcessor>,\n  config?: Omit<TracerConfig, \"resource\"> & {\n    readonly shutdownTimeout?: DurationInput | undefined\n  }\n): Layer.Layer<Tracer.OtelTracerProvider, never, Resource.Resource> =>\n  Layer.scoped(\n    Tracer.OtelTracerProvider,\n    Effect.flatMap(\n      Resource.Resource,\n      (resource) =>\n        Effect.acquireRelease(\n          Effect.sync(() => {\n            const provider = new NodeTracerProvider({\n              ...(config ?? undefined),\n              resource,\n              spanProcessors: Array.isArray(processor) ? (processor as any) : [processor]\n            })\n            return provider\n          }),\n          (provider) =>\n            Effect.promise(() => provider.forceFlush().then(() => provider.shutdown())).pipe(\n              Effect.ignoreLogged,\n              Effect.interruptible,\n              Effect.timeoutOption(config?.shutdownTimeout ?? 3000)\n            )\n        )\n    )\n  )\n\n/**\n * @since 1.0.0\n * @category layer\n */\nexport const layer: {\n  (evaluate: LazyArg<Configuration>): Layer.Layer<Resource.Resource>\n  <R, E>(evaluate: Effect.Effect<Configuration, E, R>): Layer.Layer<Resource.Resource, E, R>\n} = (\n  evaluate: LazyArg<Configuration> | Effect.Effect<Configuration, any, any>\n): Layer.Layer<Resource.Resource> =>\n  Layer.unwrapEffect(\n    Effect.map(\n      Effect.isEffect(evaluate)\n        ? evaluate as Effect.Effect<Configuration>\n        : Effect.sync(evaluate),\n      (config) => {\n        const ResourceLive = Resource.layerFromEnv(config.resource && Resource.configToAttributes(config.resource))\n\n        const TracerLive = isNonEmpty(config.spanProcessor)\n          ? Layer.provide(\n            Tracer.layer,\n            layerTracerProvider(config.spanProcessor, {\n              ...config.tracerConfig,\n              shutdownTimeout: config.shutdownTimeout\n            })\n          )\n          : Layer.empty\n\n        const MetricsLive = isNonEmpty(config.metricReader)\n          ? Metrics.layer(constant(config.metricReader), config)\n          : Layer.empty\n\n        const LoggerLive = isNonEmpty(config.logRecordProcessor)\n          ? Layer.provide(\n            Logger.layerLoggerAdd,\n            Logger.layerLoggerProvider(config.logRecordProcessor, {\n              ...config.loggerProviderConfig,\n              shutdownTimeout: config.shutdownTimeout\n            })\n          )\n          : Layer.empty\n\n        return Layer.mergeAll(TracerLive, MetricsLive, LoggerLive).pipe(\n          Layer.provideMerge(ResourceLive)\n        )\n      }\n    )\n  )\n\n/**\n * @since 2.0.0\n * @category layer\n */\nexport const layerEmpty: Layer.Layer<Resource.Resource> = Resource.layerEmpty\n"
  },
  {
    "path": "packages/opentelemetry/src/Otlp.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Headers from \"@effect/platform/Headers\"\nimport type * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport type * as Duration from \"effect/Duration\"\nimport { flow } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport type * as Logger from \"effect/Logger\"\nimport type * as Tracer from \"effect/Tracer\"\nimport * as OtlpLogger from \"./OtlpLogger.js\"\nimport * as OtlpMetrics from \"./OtlpMetrics.js\"\nimport * as OtlpSerialization from \"./OtlpSerialization.js\"\nimport * as OtlpTracer from \"./OtlpTracer.js\"\n\n/**\n * Creates an OTLP layer.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly baseUrl: string\n  readonly resource?: {\n    readonly serviceName?: string | undefined\n    readonly serviceVersion?: string | undefined\n    readonly attributes?: Record<string, unknown>\n  }\n  readonly headers?: Headers.Input | undefined\n  readonly maxBatchSize?: number | undefined\n  readonly replaceLogger?: Logger.Logger<any, any> | undefined\n  readonly tracerContext?: (<X>(f: () => X, span: Tracer.AnySpan) => X) | undefined\n  readonly loggerExportInterval?: Duration.DurationInput | undefined\n  readonly loggerExcludeLogSpans?: boolean | undefined\n  readonly metricsExportInterval?: Duration.DurationInput | undefined\n  readonly tracerExportInterval?: Duration.DurationInput | undefined\n  readonly shutdownTimeout?: Duration.DurationInput | undefined\n}): Layer.Layer<never, never, HttpClient.HttpClient | OtlpSerialization.OtlpSerialization> => {\n  const baseReq = HttpClientRequest.get(options.baseUrl)\n  const url = (path: string) => HttpClientRequest.appendUrl(baseReq, path).url\n  return Layer.mergeAll(\n    OtlpLogger.layer({\n      replaceLogger: options.replaceLogger,\n      url: url(\"/v1/logs\"),\n      resource: options.resource,\n      headers: options.headers,\n      exportInterval: options.loggerExportInterval,\n      maxBatchSize: options.maxBatchSize,\n      shutdownTimeout: options.shutdownTimeout,\n      excludeLogSpans: options.loggerExcludeLogSpans\n    }),\n    OtlpMetrics.layer({\n      url: url(\"/v1/metrics\"),\n      resource: options.resource,\n      headers: options.headers,\n      exportInterval: options.metricsExportInterval,\n      shutdownTimeout: options.shutdownTimeout\n    }),\n    OtlpTracer.layer({\n      url: url(\"/v1/traces\"),\n      resource: options.resource,\n      headers: options.headers,\n      exportInterval: options.tracerExportInterval,\n      maxBatchSize: options.maxBatchSize,\n      context: options.tracerContext,\n      shutdownTimeout: options.shutdownTimeout\n    })\n  )\n}\n\n/**\n * Creates an OTLP layer with JSON serialization.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layerJson: (options: {\n  readonly baseUrl: string\n  readonly resource?: {\n    readonly serviceName?: string | undefined\n    readonly serviceVersion?: string | undefined\n    readonly attributes?: Record<string, unknown>\n  }\n  readonly headers?: Headers.Input | undefined\n  readonly maxBatchSize?: number | undefined\n  readonly replaceLogger?: Logger.Logger<any, any> | undefined\n  readonly tracerContext?: (<X>(f: () => X, span: Tracer.AnySpan) => X) | undefined\n  readonly loggerExportInterval?: Duration.DurationInput | undefined\n  readonly loggerExcludeLogSpans?: boolean | undefined\n  readonly metricsExportInterval?: Duration.DurationInput | undefined\n  readonly tracerExportInterval?: Duration.DurationInput | undefined\n  readonly shutdownTimeout?: Duration.DurationInput | undefined\n}) => Layer.Layer<never, never, HttpClient.HttpClient> = flow(layer, Layer.provide(OtlpSerialization.layerJson))\n\n/**\n * Creates an OTLP layer with Protobuf serialization.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layerProtobuf: (options: {\n  readonly baseUrl: string\n  readonly resource?: {\n    readonly serviceName?: string | undefined\n    readonly serviceVersion?: string | undefined\n    readonly attributes?: Record<string, unknown>\n  }\n  readonly headers?: Headers.Input | undefined\n  readonly maxBatchSize?: number | undefined\n  readonly replaceLogger?: Logger.Logger<any, any> | undefined\n  readonly tracerContext?: (<X>(f: () => X, span: Tracer.AnySpan) => X) | undefined\n  readonly loggerExportInterval?: Duration.DurationInput | undefined\n  readonly loggerExcludeLogSpans?: boolean | undefined\n  readonly metricsExportInterval?: Duration.DurationInput | undefined\n  readonly tracerExportInterval?: Duration.DurationInput | undefined\n  readonly shutdownTimeout?: Duration.DurationInput | undefined\n}) => Layer.Layer<never, never, HttpClient.HttpClient> = flow(layer, Layer.provide(OtlpSerialization.layerProtobuf))\n"
  },
  {
    "path": "packages/opentelemetry/src/OtlpLogger.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Headers from \"@effect/platform/Headers\"\nimport type * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as Arr from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberId from \"effect/FiberId\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport * as FiberRefs from \"effect/FiberRefs\"\nimport type * as Layer from \"effect/Layer\"\nimport * as Logger from \"effect/Logger\"\nimport type * as LogLevel from \"effect/LogLevel\"\nimport * as Option from \"effect/Option\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Tracer from \"effect/Tracer\"\nimport * as Exporter from \"./internal/otlpExporter.js\"\nimport type { AnyValue, Fixed64, KeyValue, Resource } from \"./OtlpResource.js\"\nimport * as OtlpResource from \"./OtlpResource.js\"\nimport { OtlpSerialization } from \"./OtlpSerialization.js\"\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make: (\n  options: {\n    readonly url: string\n    readonly resource?: {\n      readonly serviceName?: string | undefined\n      readonly serviceVersion?: string | undefined\n      readonly attributes?: Record<string, unknown>\n    } | undefined\n    readonly headers?: Headers.Input | undefined\n    readonly exportInterval?: Duration.DurationInput | undefined\n    readonly maxBatchSize?: number | undefined\n    readonly shutdownTimeout?: Duration.DurationInput | undefined\n    readonly excludeLogSpans?: boolean | undefined\n  }\n) => Effect.Effect<\n  Logger.Logger<unknown, void>,\n  never,\n  HttpClient.HttpClient | OtlpSerialization | Scope.Scope\n> = Effect.fnUntraced(function*(options) {\n  const otelResource = yield* OtlpResource.fromConfig(options.resource)\n  const scope: IInstrumentationScope = {\n    name: OtlpResource.unsafeServiceName(otelResource)\n  }\n  const serialization = yield* OtlpSerialization\n\n  const exporter = yield* Exporter.make({\n    label: \"OtlpLogger\",\n    url: options.url,\n    headers: options.headers,\n    maxBatchSize: options.maxBatchSize ?? 1000,\n    exportInterval: options.exportInterval ?? Duration.seconds(1),\n    body(data) {\n      const body: IExportLogsServiceRequest = {\n        resourceLogs: [{\n          resource: otelResource,\n          scopeLogs: [{\n            scope,\n            logRecords: data\n          }]\n        }]\n      }\n      return serialization.logs(body)\n    },\n    shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n  })\n\n  const opts = {\n    excludeLogSpans: options.excludeLogSpans ?? false\n  }\n  return Logger.make((options) => {\n    exporter.push(makeLogRecord(options, opts))\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly url: string\n  readonly resource?: {\n    readonly serviceName?: string | undefined\n    readonly serviceVersion?: string | undefined\n    readonly attributes?: Record<string, unknown>\n  } | undefined\n  readonly replaceLogger?: Logger.Logger<any, any> | undefined\n  readonly headers?: Headers.Input | undefined\n  readonly exportInterval?: Duration.DurationInput | undefined\n  readonly maxBatchSize?: number | undefined\n  readonly shutdownTimeout?: Duration.DurationInput | undefined\n  readonly excludeLogSpans?: boolean | undefined\n}): Layer.Layer<never, never, HttpClient.HttpClient | OtlpSerialization> =>\n  options.replaceLogger ? Logger.replaceScoped(options.replaceLogger, make(options)) : Logger.addScoped(make(options))\n\n// internal\n\nconst makeLogRecord = (options: Logger.Logger.Options<unknown>, opts: {\n  readonly excludeLogSpans: boolean\n}): ILogRecord => {\n  const now = options.date.getTime()\n  const nanosString = `${now}000000`\n\n  const attributes = OtlpResource.entriesToAttributes(options.annotations)\n  attributes.push({\n    key: \"fiberId\",\n    value: { stringValue: FiberId.threadName(options.fiberId) }\n  })\n  if (!opts.excludeLogSpans) {\n    for (const span of options.spans) {\n      attributes.push({\n        key: `logSpan.${span.label}`,\n        value: { stringValue: `${now - span.startTime}ms` }\n      })\n    }\n  }\n  if (!Cause.isEmpty(options.cause)) {\n    attributes.push({\n      key: \"log.error\",\n      value: { stringValue: Cause.pretty(options.cause, { renderErrorCause: true }) }\n    })\n  }\n\n  const message = Arr.ensure(options.message)\n  const maybeSpan = Context.getOption(\n    FiberRefs.getOrDefault(options.context, FiberRef.currentContext),\n    Tracer.ParentSpan\n  )\n\n  const logRecord: ILogRecord = {\n    severityNumber: logLevelToSeverityNumber(options.logLevel),\n    severityText: options.logLevel.label,\n    timeUnixNano: nanosString,\n    observedTimeUnixNano: nanosString,\n    attributes,\n    body: OtlpResource.unknownToAttributeValue(message.length === 1 ? message[0] : message),\n    droppedAttributesCount: 0\n  }\n\n  if (Option.isSome(maybeSpan)) {\n    logRecord.traceId = maybeSpan.value.traceId\n    logRecord.spanId = maybeSpan.value.spanId\n  }\n\n  return logRecord\n}\n\n/** Properties of an ExportLogsServiceRequest. */\ninterface IExportLogsServiceRequest {\n  /** ExportLogsServiceRequest resourceLogs */\n  resourceLogs?: Array<IResourceLogs>\n}\n\n/** Properties of an InstrumentationScope. */\ninterface IInstrumentationScope {\n  /** InstrumentationScope name */\n  name: string\n  /** InstrumentationScope version */\n  version?: string\n  /** InstrumentationScope attributes */\n  attributes?: Array<KeyValue>\n  /** InstrumentationScope droppedAttributesCount */\n  droppedAttributesCount?: number\n}\n/** Properties of a ResourceLogs. */\ninterface IResourceLogs {\n  /** ResourceLogs resource */\n  resource?: Resource\n  /** ResourceLogs scopeLogs */\n  scopeLogs: Array<IScopeLogs>\n  /** ResourceLogs schemaUrl */\n  schemaUrl?: string\n}\n/** Properties of an ScopeLogs. */\ninterface IScopeLogs {\n  /** IScopeLogs scope */\n  scope?: IInstrumentationScope\n  /** IScopeLogs logRecords */\n  logRecords?: Array<ILogRecord>\n  /** IScopeLogs schemaUrl */\n  schemaUrl?: string | null\n}\n/** Properties of a LogRecord. */\ninterface ILogRecord {\n  /** LogRecord timeUnixNano */\n  timeUnixNano: Fixed64\n  /** LogRecord observedTimeUnixNano */\n  observedTimeUnixNano: Fixed64\n  /** LogRecord severityNumber */\n  severityNumber?: ESeverityNumber\n  /** LogRecord severityText */\n  severityText?: string\n  /** LogRecord body */\n  body?: AnyValue\n  /** LogRecord attributes */\n  attributes: Array<KeyValue>\n  /** LogRecord droppedAttributesCount */\n  droppedAttributesCount: number\n  /** LogRecord flags */\n  flags?: number\n  /** LogRecord traceId */\n  traceId?: string | Uint8Array\n  /** LogRecord spanId */\n  spanId?: string | Uint8Array\n}\n\nconst logLevelToSeverityNumber = (logLevel: LogLevel.LogLevel): ESeverityNumber => {\n  switch (logLevel._tag) {\n    case \"Trace\":\n      return ESeverityNumber.SEVERITY_NUMBER_TRACE\n    case \"Debug\":\n      return ESeverityNumber.SEVERITY_NUMBER_DEBUG\n    case \"Info\":\n      return ESeverityNumber.SEVERITY_NUMBER_INFO\n    case \"Warning\":\n      return ESeverityNumber.SEVERITY_NUMBER_WARN\n    case \"Error\":\n      return ESeverityNumber.SEVERITY_NUMBER_ERROR\n    case \"Fatal\":\n      return ESeverityNumber.SEVERITY_NUMBER_FATAL\n    default:\n      return ESeverityNumber.SEVERITY_NUMBER_UNSPECIFIED\n  }\n}\n\n/**\n * Numerical value of the severity, normalized to values described in Log Data Model.\n */\nconst enum ESeverityNumber {\n  /** Unspecified. Do NOT use as default */\n  SEVERITY_NUMBER_UNSPECIFIED = 0,\n  SEVERITY_NUMBER_TRACE = 1,\n  SEVERITY_NUMBER_TRACE2 = 2,\n  SEVERITY_NUMBER_TRACE3 = 3,\n  SEVERITY_NUMBER_TRACE4 = 4,\n  SEVERITY_NUMBER_DEBUG = 5,\n  SEVERITY_NUMBER_DEBUG2 = 6,\n  SEVERITY_NUMBER_DEBUG3 = 7,\n  SEVERITY_NUMBER_DEBUG4 = 8,\n  SEVERITY_NUMBER_INFO = 9,\n  SEVERITY_NUMBER_INFO2 = 10,\n  SEVERITY_NUMBER_INFO3 = 11,\n  SEVERITY_NUMBER_INFO4 = 12,\n  SEVERITY_NUMBER_WARN = 13,\n  SEVERITY_NUMBER_WARN2 = 14,\n  SEVERITY_NUMBER_WARN3 = 15,\n  SEVERITY_NUMBER_WARN4 = 16,\n  SEVERITY_NUMBER_ERROR = 17,\n  SEVERITY_NUMBER_ERROR2 = 18,\n  SEVERITY_NUMBER_ERROR3 = 19,\n  SEVERITY_NUMBER_ERROR4 = 20,\n  SEVERITY_NUMBER_FATAL = 21,\n  SEVERITY_NUMBER_FATAL2 = 22,\n  SEVERITY_NUMBER_FATAL3 = 23,\n  SEVERITY_NUMBER_FATAL4 = 24\n}\n"
  },
  {
    "path": "packages/opentelemetry/src/OtlpMetrics.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Headers from \"@effect/platform/Headers\"\nimport type * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as Arr from \"effect/Array\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Metric from \"effect/Metric\"\nimport type * as MetricKey from \"effect/MetricKey\"\nimport * as MetricState from \"effect/MetricState\"\nimport * as Option from \"effect/Option\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Exporter from \"./internal/otlpExporter.js\"\nimport type { Fixed64, KeyValue } from \"./OtlpResource.js\"\nimport * as OtlpResource from \"./OtlpResource.js\"\nimport { OtlpSerialization } from \"./OtlpSerialization.js\"\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make: (options: {\n  readonly url: string\n  readonly resource?: {\n    readonly serviceName?: string | undefined\n    readonly serviceVersion?: string | undefined\n    readonly attributes?: Record<string, unknown>\n  } | undefined\n  readonly headers?: Headers.Input | undefined\n  readonly exportInterval?: Duration.DurationInput | undefined\n  readonly shutdownTimeout?: Duration.DurationInput | undefined\n}) => Effect.Effect<\n  void,\n  never,\n  HttpClient.HttpClient | OtlpSerialization | Scope.Scope\n> = Effect.fnUntraced(function*(options) {\n  const clock = yield* Effect.clock\n  const startTime = String(clock.unsafeCurrentTimeNanos())\n\n  const resource = yield* OtlpResource.fromConfig(options.resource)\n  const metricsScope: IInstrumentationScope = {\n    name: OtlpResource.unsafeServiceName(resource)\n  }\n  const serialization = yield* OtlpSerialization\n\n  const snapshot = () => {\n    const snapshot = Metric.unsafeSnapshot()\n    const nowNanos = clock.unsafeCurrentTimeNanos()\n    const nowTime = String(nowNanos)\n    const metricData: Array<IMetric> = []\n    const metricDataByName = new Map<string, IMetric>()\n    const addMetricData = (data: IMetric) => {\n      metricData.push(data)\n      metricDataByName.set(data.name, data)\n    }\n\n    for (let i = 0, len = snapshot.length; i < len; i++) {\n      const { metricKey, metricState } = snapshot[i]\n      let unit = \"1\"\n      const attributes = Arr.reduce(metricKey.tags, [], (acc: Array<KeyValue>, label) => {\n        if (label.key === \"unit\" || label.key === \"time_unit\") {\n          unit = label.value\n        }\n        acc.push({ key: label.key, value: { stringValue: label.value } })\n        return acc\n      })\n\n      if (MetricState.isCounterState(metricState)) {\n        const dataPoint: INumberDataPoint = {\n          attributes,\n          startTimeUnixNano: startTime,\n          timeUnixNano: nowTime\n        }\n        if (typeof metricState.count === \"bigint\") {\n          dataPoint.asInt = Number(metricState.count)\n        } else {\n          dataPoint.asDouble = metricState.count\n        }\n        if (metricDataByName.has(metricKey.name)) {\n          metricDataByName.get(metricKey.name)!.sum!.dataPoints.push(dataPoint)\n        } else {\n          const key = metricKey as MetricKey.MetricKey.Counter<any>\n          addMetricData({\n            name: metricKey.name,\n            description: getOrEmpty(key.description),\n            unit,\n            sum: {\n              aggregationTemporality: EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE,\n              isMonotonic: key.keyType.incremental,\n              dataPoints: [dataPoint]\n            }\n          })\n        }\n      } else if (MetricState.isGaugeState(metricState)) {\n        const dataPoint: INumberDataPoint = {\n          attributes,\n          startTimeUnixNano: startTime,\n          timeUnixNano: nowTime\n        }\n        if (typeof metricState.value === \"bigint\") {\n          dataPoint.asInt = Number(metricState.value)\n        } else {\n          dataPoint.asDouble = metricState.value\n        }\n        if (metricDataByName.has(metricKey.name)) {\n          metricDataByName.get(metricKey.name)!.gauge!.dataPoints.push(dataPoint)\n        } else {\n          addMetricData({\n            name: metricKey.name,\n            description: getOrEmpty(metricKey.description),\n            unit,\n            gauge: {\n              dataPoints: [dataPoint]\n            }\n          })\n        }\n      } else if (MetricState.isHistogramState(metricState)) {\n        const size = metricState.buckets.length\n        const buckets = {\n          boundaries: Arr.allocate(size - 1) as Array<number>,\n          counts: Arr.allocate(size) as Array<number>\n        }\n        let i = 0\n        let prev = 0\n        for (const [boundary, value] of metricState.buckets) {\n          if (i < size - 1) {\n            buckets.boundaries[i] = boundary\n          }\n          buckets.counts[i] = value - prev\n          prev = value\n          i++\n        }\n        const dataPoint: IHistogramDataPoint = {\n          attributes,\n          startTimeUnixNano: startTime,\n          timeUnixNano: nowTime,\n          count: metricState.count,\n          min: metricState.min,\n          max: metricState.max,\n          sum: metricState.sum,\n          bucketCounts: buckets.counts,\n          explicitBounds: buckets.boundaries\n        }\n\n        if (metricDataByName.has(metricKey.name)) {\n          metricDataByName.get(metricKey.name)!.histogram!.dataPoints.push(dataPoint)\n        } else {\n          addMetricData({\n            name: metricKey.name,\n            description: getOrEmpty(metricKey.description),\n            unit,\n            histogram: {\n              aggregationTemporality: EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE,\n              dataPoints: [dataPoint]\n            }\n          })\n        }\n      } else if (MetricState.isFrequencyState(metricState)) {\n        const dataPoints: Array<INumberDataPoint> = []\n        for (const [freqKey, value] of metricState.occurrences) {\n          dataPoints.push({\n            attributes: [...attributes, { key: \"key\", value: { stringValue: freqKey } }],\n            startTimeUnixNano: startTime,\n            timeUnixNano: nowTime,\n            asInt: value\n          })\n        }\n        if (metricDataByName.has(metricKey.name)) {\n          // eslint-disable-next-line no-restricted-syntax\n          metricDataByName.get(metricKey.name)!.sum!.dataPoints.push(...dataPoints)\n        } else {\n          addMetricData({\n            name: metricKey.name,\n            description: getOrEmpty(metricKey.description),\n            unit,\n            sum: {\n              aggregationTemporality: EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE,\n              isMonotonic: true,\n              dataPoints\n            }\n          })\n        }\n      } else if (MetricState.isSummaryState(metricState)) {\n        const dataPoints: Array<INumberDataPoint> = [{\n          attributes: [...attributes, { key: \"quantile\", value: { stringValue: \"min\" } }],\n          startTimeUnixNano: startTime,\n          timeUnixNano: nowTime,\n          asDouble: metricState.min\n        }]\n        for (const [quantile, value] of metricState.quantiles) {\n          dataPoints.push({\n            attributes: [...attributes, { key: \"quantile\", value: { stringValue: quantile.toString() } }],\n            startTimeUnixNano: startTime,\n            timeUnixNano: nowTime,\n            asDouble: value._tag === \"Some\" ? value.value : 0\n          })\n        }\n        dataPoints.push({\n          attributes: [...attributes, { key: \"quantile\", value: { stringValue: \"max\" } }],\n          startTimeUnixNano: startTime,\n          timeUnixNano: nowTime,\n          asDouble: metricState.max\n        })\n        const countDataPoint: INumberDataPoint = {\n          attributes,\n          startTimeUnixNano: startTime,\n          timeUnixNano: nowTime,\n          asInt: metricState.count\n        }\n        const sumDataPoint: INumberDataPoint = {\n          attributes,\n          startTimeUnixNano: startTime,\n          timeUnixNano: nowTime,\n          asDouble: metricState.sum\n        }\n\n        if (metricDataByName.has(`${metricKey.name}_quantiles`)) {\n          // eslint-disable-next-line no-restricted-syntax\n          metricDataByName.get(`${metricKey.name}_quantiles`)!.sum!.dataPoints.push(...dataPoints)\n          metricDataByName.get(`${metricKey.name}_count`)!.sum!.dataPoints.push(countDataPoint)\n          metricDataByName.get(`${metricKey.name}_sum`)!.sum!.dataPoints.push(sumDataPoint)\n        } else {\n          addMetricData({\n            name: `${metricKey.name}_quantiles`,\n            description: getOrEmpty(metricKey.description),\n            unit,\n            sum: {\n              aggregationTemporality: EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE,\n              isMonotonic: false,\n              dataPoints\n            }\n          })\n          addMetricData({\n            name: `${metricKey.name}_count`,\n            description: getOrEmpty(metricKey.description),\n            unit: \"1\",\n            sum: {\n              aggregationTemporality: EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE,\n              isMonotonic: true,\n              dataPoints: [countDataPoint]\n            }\n          })\n          addMetricData({\n            name: `${metricKey.name}_sum`,\n            description: getOrEmpty(metricKey.description),\n            unit: \"1\",\n            sum: {\n              aggregationTemporality: EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE,\n              isMonotonic: true,\n              dataPoints: [sumDataPoint]\n            }\n          })\n        }\n      }\n    }\n\n    const body: IExportMetricsServiceRequest = {\n      resourceMetrics: [{\n        resource,\n        scopeMetrics: [{\n          scope: metricsScope,\n          metrics: metricData\n        }]\n      }]\n    }\n\n    return serialization.metrics(body)\n  }\n\n  yield* Exporter.make({\n    label: \"OtlpMetrics\",\n    url: options.url,\n    headers: options.headers,\n    maxBatchSize: \"disabled\",\n    exportInterval: options.exportInterval ?? Duration.seconds(10),\n    body: snapshot,\n    shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly url: string\n  readonly resource?: {\n    readonly serviceName?: string | undefined\n    readonly serviceVersion?: string | undefined\n    readonly attributes?: Record<string, unknown>\n  } | undefined\n  readonly headers?: Headers.Input | undefined\n  readonly exportInterval?: Duration.DurationInput | undefined\n  readonly shutdownTimeout?: Duration.DurationInput | undefined\n}): Layer.Layer<never, never, HttpClient.HttpClient | OtlpSerialization> => Layer.scopedDiscard(make(options))\n\n// internal\n\nconst getOrEmpty = Option.getOrElse(() => \"\")\n\n/** Properties of an InstrumentationScope. */\ninterface IInstrumentationScope {\n  /** InstrumentationScope name */\n  name: string\n  /** InstrumentationScope version */\n  version?: string\n  /** InstrumentationScope attributes */\n  attributes?: Array<KeyValue>\n  /** InstrumentationScope droppedAttributesCount */\n  droppedAttributesCount?: number\n}\n\n/** Properties of an ExportMetricsServiceRequest. */\ninterface IExportMetricsServiceRequest {\n  /** ExportMetricsServiceRequest resourceMetrics */\n  resourceMetrics: Array<IResourceMetrics>\n}\n/** Properties of a ResourceMetrics. */\ninterface IResourceMetrics {\n  /** ResourceMetrics resource */\n  resource?: OtlpResource.Resource\n  /** ResourceMetrics scopeMetrics */\n  scopeMetrics: Array<IScopeMetrics>\n  /** ResourceMetrics schemaUrl */\n  schemaUrl?: string\n}\n/** Properties of an IScopeMetrics. */\ninterface IScopeMetrics {\n  /** ScopeMetrics scope */\n  scope?: IInstrumentationScope\n  /** ScopeMetrics metrics */\n  metrics: Array<IMetric>\n  /** ScopeMetrics schemaUrl */\n  schemaUrl?: string\n}\n/** Properties of a Metric. */\ninterface IMetric {\n  /** Metric name */\n  name: string\n  /** Metric description */\n  description?: string\n  /** Metric unit */\n  unit?: string\n  /** Metric gauge */\n  gauge?: IGauge\n  /** Metric sum */\n  sum?: ISum\n  /** Metric histogram */\n  histogram?: IHistogram\n  /** Metric exponentialHistogram */\n  exponentialHistogram?: IExponentialHistogram\n  /** Metric summary */\n  summary?: ISummary\n}\n/** Properties of a Gauge. */\ninterface IGauge {\n  /** Gauge dataPoints */\n  dataPoints: Array<INumberDataPoint>\n}\n/** Properties of a Sum. */\ninterface ISum {\n  /** Sum dataPoints */\n  dataPoints: Array<INumberDataPoint>\n  /** Sum aggregationTemporality */\n  aggregationTemporality: EAggregationTemporality\n  /** Sum isMonotonic */\n  isMonotonic: boolean\n}\n/** Properties of a Histogram. */\ninterface IHistogram {\n  /** Histogram dataPoints */\n  dataPoints: Array<IHistogramDataPoint>\n  /** Histogram aggregationTemporality */\n  aggregationTemporality?: EAggregationTemporality\n}\n/** Properties of an ExponentialHistogram. */\ninterface IExponentialHistogram {\n  /** ExponentialHistogram dataPoints */\n  dataPoints: Array<IExponentialHistogramDataPoint>\n  /** ExponentialHistogram aggregationTemporality */\n  aggregationTemporality?: EAggregationTemporality\n}\n/** Properties of a Summary. */\ninterface ISummary {\n  /** Summary dataPoints */\n  dataPoints: Array<ISummaryDataPoint>\n}\n/** Properties of a NumberDataPoint. */\ninterface INumberDataPoint {\n  /** NumberDataPoint attributes */\n  attributes: Array<KeyValue>\n  /** NumberDataPoint startTimeUnixNano */\n  startTimeUnixNano?: Fixed64\n  /** NumberDataPoint timeUnixNano */\n  timeUnixNano?: Fixed64\n  /** NumberDataPoint asDouble */\n  asDouble?: number | null\n  /** NumberDataPoint asInt */\n  asInt?: number\n  /** NumberDataPoint exemplars */\n  exemplars?: Array<IExemplar>\n  /** NumberDataPoint flags */\n  flags?: number\n}\n/** Properties of a HistogramDataPoint. */\ninterface IHistogramDataPoint {\n  /** HistogramDataPoint attributes */\n  attributes?: Array<KeyValue>\n  /** HistogramDataPoint startTimeUnixNano */\n  startTimeUnixNano?: Fixed64\n  /** HistogramDataPoint timeUnixNano */\n  timeUnixNano?: Fixed64\n  /** HistogramDataPoint count */\n  count?: number\n  /** HistogramDataPoint sum */\n  sum?: number\n  /** HistogramDataPoint bucketCounts */\n  bucketCounts?: Array<number>\n  /** HistogramDataPoint explicitBounds */\n  explicitBounds?: Array<number>\n  /** HistogramDataPoint exemplars */\n  exemplars?: Array<IExemplar>\n  /** HistogramDataPoint flags */\n  flags?: number\n  /** HistogramDataPoint min */\n  min?: number\n  /** HistogramDataPoint max */\n  max?: number\n}\n/** Properties of an ExponentialHistogramDataPoint. */\ninterface IExponentialHistogramDataPoint {\n  /** ExponentialHistogramDataPoint attributes */\n  attributes?: Array<KeyValue>\n  /** ExponentialHistogramDataPoint startTimeUnixNano */\n  startTimeUnixNano?: Fixed64\n  /** ExponentialHistogramDataPoint timeUnixNano */\n  timeUnixNano?: Fixed64\n  /** ExponentialHistogramDataPoint count */\n  count?: number\n  /** ExponentialHistogramDataPoint sum */\n  sum?: number\n  /** ExponentialHistogramDataPoint scale */\n  scale?: number\n  /** ExponentialHistogramDataPoint zeroCount */\n  zeroCount?: number\n  /** ExponentialHistogramDataPoint positive */\n  positive?: IBuckets\n  /** ExponentialHistogramDataPoint negative */\n  negative?: IBuckets\n  /** ExponentialHistogramDataPoint flags */\n  flags?: number\n  /** ExponentialHistogramDataPoint exemplars */\n  exemplars?: Array<IExemplar>\n  /** ExponentialHistogramDataPoint min */\n  min?: number\n  /** ExponentialHistogramDataPoint max */\n  max?: number\n}\n/** Properties of a SummaryDataPoint. */\ninterface ISummaryDataPoint {\n  /** SummaryDataPoint attributes */\n  attributes?: Array<KeyValue>\n  /** SummaryDataPoint startTimeUnixNano */\n  startTimeUnixNano?: number\n  /** SummaryDataPoint timeUnixNano */\n  timeUnixNano?: string\n  /** SummaryDataPoint count */\n  count?: number\n  /** SummaryDataPoint sum */\n  sum?: number\n  /** SummaryDataPoint quantileValues */\n  quantileValues?: Array<IValueAtQuantile>\n  /** SummaryDataPoint flags */\n  flags?: number\n}\n/** Properties of a ValueAtQuantile. */\ninterface IValueAtQuantile {\n  /** ValueAtQuantile quantile */\n  quantile?: number\n  /** ValueAtQuantile value */\n  value?: number\n}\n/** Properties of a Buckets. */\ninterface IBuckets {\n  /** Buckets offset */\n  offset?: number\n  /** Buckets bucketCounts */\n  bucketCounts?: Array<number>\n}\n/** Properties of an Exemplar. */\ninterface IExemplar {\n  /** Exemplar filteredAttributes */\n  filteredAttributes?: Array<KeyValue>\n  /** Exemplar timeUnixNano */\n  timeUnixNano?: string\n  /** Exemplar asDouble */\n  asDouble?: number\n  /** Exemplar asInt */\n  asInt?: number\n  /** Exemplar spanId */\n  spanId?: string | Uint8Array\n  /** Exemplar traceId */\n  traceId?: string | Uint8Array\n}\n/**\n * AggregationTemporality defines how a metric aggregator reports aggregated\n * values. It describes how those values relate to the time interval over\n * which they are aggregated.\n */\nconst enum EAggregationTemporality {\n  AGGREGATION_TEMPORALITY_UNSPECIFIED = 0,\n  /** DELTA is an AggregationTemporality for a metric aggregator which reports\n    changes since last report time. Successive metrics contain aggregation of\n    values from continuous and non-overlapping intervals.\n\n    The values for a DELTA metric are based only on the time interval\n    associated with one measurement cycle. There is no dependency on\n    previous measurements like is the case for CUMULATIVE metrics.\n\n    For example, consider a system measuring the number of requests that\n    it receives and reports the sum of these requests every second as a\n    DELTA metric:\n\n    1. The system starts receiving at time=t_0.\n    2. A request is received, the system measures 1 request.\n    3. A request is received, the system measures 1 request.\n    4. A request is received, the system measures 1 request.\n    5. The 1 second collection cycle ends. A metric is exported for the\n        number of requests received over the interval of time t_0 to\n        t_0+1 with a value of 3.\n    6. A request is received, the system measures 1 request.\n    7. A request is received, the system measures 1 request.\n    8. The 1 second collection cycle ends. A metric is exported for the\n        number of requests received over the interval of time t_0+1 to\n        t_0+2 with a value of 2. */\n  AGGREGATION_TEMPORALITY_DELTA = 1,\n  /** CUMULATIVE is an AggregationTemporality for a metric aggregator which\n    reports changes since a fixed start time. This means that current values\n    of a CUMULATIVE metric depend on all previous measurements since the\n    start time. Because of this, the sender is required to retain this state\n    in some form. If this state is lost or invalidated, the CUMULATIVE metric\n    values MUST be reset and a new fixed start time following the last\n    reported measurement time sent MUST be used.\n\n    For example, consider a system measuring the number of requests that\n    it receives and reports the sum of these requests every second as a\n    CUMULATIVE metric:\n\n    1. The system starts receiving at time=t_0.\n    2. A request is received, the system measures 1 request.\n    3. A request is received, the system measures 1 request.\n    4. A request is received, the system measures 1 request.\n    5. The 1 second collection cycle ends. A metric is exported for the\n        number of requests received over the interval of time t_0 to\n        t_0+1 with a value of 3.\n    6. A request is received, the system measures 1 request.\n    7. A request is received, the system measures 1 request.\n    8. The 1 second collection cycle ends. A metric is exported for the\n        number of requests received over the interval of time t_0 to\n        t_0+2 with a value of 5.\n    9. The system experiences a fault and loses state.\n    10. The system recovers and resumes receiving at time=t_1.\n    11. A request is received, the system measures 1 request.\n    12. The 1 second collection cycle ends. A metric is exported for the\n        number of requests received over the interval of time t_1 to\n        t_0+1 with a value of 1.\n\n    Note: Even though, when reporting changes since last report time, using\n    CUMULATIVE is valid, it is not recommended. This may cause problems for\n    systems that do not use start_time to determine when the aggregation\n    value was reset (e.g. Prometheus). */\n  AGGREGATION_TEMPORALITY_CUMULATIVE = 2\n}\n"
  },
  {
    "path": "packages/opentelemetry/src/OtlpResource.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Arr from \"effect/Array\"\nimport * as Config from \"effect/Config\"\nimport * as Effect from \"effect/Effect\"\nimport * as Inspectable from \"effect/Inspectable\"\n\nconst ATTR_SERVICE_NAME = \"service.name\"\nconst ATTR_SERVICE_VERSION = \"service.version\"\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface Resource {\n  /** Resource attributes */\n  attributes: Array<KeyValue>\n  /** Resource droppedAttributesCount */\n  droppedAttributesCount: number\n}\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make = (options: {\n  readonly serviceName: string\n  readonly serviceVersion?: string | undefined\n  readonly attributes?: Record<string, unknown> | undefined\n}): Resource => {\n  const resourceAttributes = options.attributes\n    ? entriesToAttributes(Object.entries(options.attributes))\n    : []\n  resourceAttributes.push({\n    key: ATTR_SERVICE_NAME,\n    value: {\n      stringValue: options.serviceName\n    }\n  })\n  if (options.serviceVersion) {\n    resourceAttributes.push({\n      key: ATTR_SERVICE_VERSION,\n      value: {\n        stringValue: options.serviceVersion\n      }\n    })\n  }\n\n  return {\n    attributes: resourceAttributes,\n    droppedAttributesCount: 0\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const fromConfig: (\n  options?: {\n    readonly serviceName?: string | undefined\n    readonly serviceVersion?: string | undefined\n    readonly attributes?: Record<string, unknown> | undefined\n  } | undefined\n) => Effect.Effect<Resource> = Effect.fnUntraced(function*(options?: {\n  readonly serviceName?: string | undefined\n  readonly serviceVersion?: string | undefined\n  readonly attributes?: Record<string, unknown> | undefined\n}) {\n  const attributes = yield* Config.string(\"OTEL_RESOURCE_ATTRIBUTES\").pipe(\n    Config.map((s) => {\n      const attrs = s.split(\",\")\n      return Arr.reduce(attrs, {} as Record<string, string>, (acc, attr) => {\n        const parts = attr.split(\"=\")\n        if (parts.length !== 2) {\n          return acc\n        }\n        acc[parts[0].trim()] = parts[1].trim()\n        return acc\n      })\n    }),\n    Config.withDefault({}),\n    Effect.map((envAttrs) => ({\n      ...envAttrs,\n      ...options?.attributes\n    }))\n  )\n  const serviceName = options?.serviceName ?? attributes[ATTR_SERVICE_NAME] as string ??\n    (yield* Config.string(\"OTEL_SERVICE_NAME\"))\n  const serviceVersion = options?.serviceVersion ?? attributes[ATTR_SERVICE_VERSION] as string ??\n    (yield* Config.string(\"OTEL_SERVICE_VERSION\").pipe(Config.withDefault(undefined)))\n  return make({\n    serviceName,\n    serviceVersion,\n    attributes\n  })\n}, Effect.orDie)\n\n/**\n * @since 1.0.0\n * @category Attributes\n */\nexport const unsafeServiceName = (resource: Resource): string => {\n  const serviceNameAttribute = resource.attributes.find(\n    (attr) => attr.key === ATTR_SERVICE_NAME\n  )\n  if (!serviceNameAttribute || !serviceNameAttribute.value.stringValue) {\n    throw new Error(\"Resource does not contain a service name\")\n  }\n  return serviceNameAttribute.value.stringValue\n}\n\n/**\n * @since 1.0.0\n * @category Attributes\n */\nexport const entriesToAttributes = (entries: Iterable<[string, unknown]>): Array<KeyValue> => {\n  const attributes: Array<KeyValue> = []\n  for (const [key, value] of entries) {\n    attributes.push({\n      key,\n      value: unknownToAttributeValue(value)\n    })\n  }\n  return attributes\n}\n\n/**\n * @since 1.0.0\n * @category Attributes\n */\nexport const unknownToAttributeValue = (value: unknown): AnyValue => {\n  if (Array.isArray(value)) {\n    return {\n      arrayValue: {\n        values: value.map(unknownToAttributeValue)\n      }\n    }\n  }\n  switch (typeof value) {\n    case \"string\":\n      return {\n        stringValue: value\n      }\n    case \"bigint\":\n      return {\n        intValue: Number(value)\n      }\n    case \"number\":\n      return Number.isInteger(value)\n        ? {\n          intValue: value\n        }\n        : {\n          doubleValue: value\n        }\n    case \"boolean\":\n      return {\n        boolValue: value\n      }\n    default:\n      return {\n        stringValue: Inspectable.toStringUnknown(value)\n      }\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface KeyValue {\n  /** KeyValue key */\n  key: string\n  /** KeyValue value */\n  value: AnyValue\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface AnyValue {\n  /** AnyValue stringValue */\n  stringValue?: string | null\n  /** AnyValue boolValue */\n  boolValue?: boolean | null\n  /** AnyValue intValue */\n  intValue?: number | null\n  /** AnyValue doubleValue */\n  doubleValue?: number | null\n  /** AnyValue arrayValue */\n  arrayValue?: ArrayValue\n  /** AnyValue kvlistValue */\n  kvlistValue?: KeyValueList\n  /** AnyValue bytesValue */\n  bytesValue?: Uint8Array\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface ArrayValue {\n  /** ArrayValue values */\n  values: Array<AnyValue>\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface KeyValueList {\n  /** KeyValueList values */\n  values: Array<KeyValue>\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport interface LongBits {\n  low: number\n  high: number\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type Fixed64 = LongBits | string | number\n"
  },
  {
    "path": "packages/opentelemetry/src/OtlpSerialization.ts",
    "content": "/**\n * OtlpSerialization service for tree-shakable protobuf support.\n *\n * This module provides the `OtlpSerialization` service that abstracts the\n * encoding of OTLP telemetry data to HttpBody.\n *\n * @since 1.0.0\n */\nimport * as HttpBody from \"@effect/platform/HttpBody\"\nimport * as Context from \"effect/Context\"\nimport * as Layer from \"effect/Layer\"\nimport * as OtlpProtobuf from \"./internal/otlpProtobuf.js\"\n\n/**\n * @since 1.0.0\n * @category Tags\n */\nexport class OtlpSerialization extends Context.Tag(\"@effect/opentelemetry/OtlpSerialization\")<\n  OtlpSerialization,\n  {\n    /**\n     * Encodes trace data for transmission.\n     */\n    readonly traces: (data: unknown) => HttpBody.HttpBody\n    /**\n     * Encodes metrics data for transmission.\n     */\n    readonly metrics: (data: unknown) => HttpBody.HttpBody\n    /**\n     * Encodes logs data for transmission.\n     */\n    readonly logs: (data: unknown) => HttpBody.HttpBody\n  }\n>() {}\n\n/**\n * JSON serializer layer for OTLP telemetry data.\n *\n * It encodes telemetry data as JSON with `application/json` content type.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layerJson: Layer.Layer<OtlpSerialization> = Layer.succeed(OtlpSerialization, {\n  traces: (data) => HttpBody.unsafeJson(data),\n  metrics: (data) => HttpBody.unsafeJson(data),\n  logs: (data) => HttpBody.unsafeJson(data)\n})\n\n/**\n * Protobuf serializer layer for OTLP telemetry data.\n *\n * This serializer encodes telemetry data using Protocol Buffers binary\n * format with `application/x-protobuf` content type. It provides more\n * efficient wire format compared to JSON.\n *\n * @since 1.0.0\n * @category Layers\n */\nexport const layerProtobuf: Layer.Layer<OtlpSerialization> = Layer.succeed(OtlpSerialization, {\n  traces: (data) => HttpBody.uint8Array(OtlpProtobuf.encodeTracesData(data as any), \"application/x-protobuf\"),\n  metrics: (data) => HttpBody.uint8Array(OtlpProtobuf.encodeMetricsData(data as any), \"application/x-protobuf\"),\n  logs: (data) => HttpBody.uint8Array(OtlpProtobuf.encodeLogsData(data as any), \"application/x-protobuf\")\n})\n"
  },
  {
    "path": "packages/opentelemetry/src/OtlpTracer.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Headers from \"@effect/platform/Headers\"\nimport type * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as Cause from \"effect/Cause\"\nimport type * as Context from \"effect/Context\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Exit from \"effect/Exit\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Tracer from \"effect/Tracer\"\nimport type { ExtractTag } from \"effect/Types\"\nimport * as Exporter from \"./internal/otlpExporter.js\"\nimport type { KeyValue, Resource } from \"./OtlpResource.js\"\nimport { entriesToAttributes } from \"./OtlpResource.js\"\nimport * as OtlpResource from \"./OtlpResource.js\"\nimport { OtlpSerialization } from \"./OtlpSerialization.js\"\n\nconst ATTR_EXCEPTION_TYPE = \"exception.type\"\nconst ATTR_EXCEPTION_MESSAGE = \"exception.message\"\nconst ATTR_EXCEPTION_STACKTRACE = \"exception.stacktrace\"\n\n/**\n * @since 1.0.0\n * @category Constructors\n */\nexport const make: (\n  options: {\n    readonly url: string\n    readonly resource?: {\n      readonly serviceName?: string | undefined\n      readonly serviceVersion?: string | undefined\n      readonly attributes?: Record<string, unknown>\n    } | undefined\n    readonly headers?: Headers.Input | undefined\n    readonly exportInterval?: Duration.DurationInput | undefined\n    readonly maxBatchSize?: number | undefined\n    readonly context?: (<X>(f: () => X, span: Tracer.AnySpan) => X) | undefined\n    readonly shutdownTimeout?: Duration.DurationInput | undefined\n  }\n) => Effect.Effect<\n  Tracer.Tracer,\n  never,\n  HttpClient.HttpClient | OtlpSerialization | Scope.Scope\n> = Effect.fnUntraced(function*(options) {\n  const otelResource = yield* OtlpResource.fromConfig(options.resource)\n  const scope: Scope = {\n    name: OtlpResource.unsafeServiceName(otelResource)\n  }\n  const serialization = yield* OtlpSerialization\n\n  const exporter = yield* Exporter.make({\n    label: \"OtlpTracer\",\n    url: options.url,\n    headers: options.headers,\n    exportInterval: options.exportInterval ?? Duration.seconds(5),\n    maxBatchSize: options.maxBatchSize ?? 1000,\n    body(spans) {\n      const data: TraceData = {\n        resourceSpans: [{\n          resource: otelResource,\n          scopeSpans: [{\n            scope,\n            spans\n          }]\n        }]\n      }\n      return serialization.traces(data)\n    },\n    shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n  })\n\n  const exportFn = (span: SpanImpl) => {\n    exporter.push(makeOtlpSpan(span))\n  }\n\n  return Tracer.make({\n    span(name, parent, context, links, startTime, kind) {\n      return makeSpan({\n        name,\n        parent,\n        context,\n        status: {\n          _tag: \"Started\",\n          startTime\n        },\n        attributes: new Map(),\n        links,\n        sampled: true,\n        kind,\n        export: exportFn\n      })\n    },\n    context: options.context ?\n      function(f, fiber) {\n        if (fiber.currentSpan === undefined) {\n          return f()\n        }\n        return options.context!(f, fiber.currentSpan)\n      } :\n      defaultContext\n  })\n})\n\n/**\n * @since 1.0.0\n * @category Layers\n */\nexport const layer = (options: {\n  readonly url: string\n  readonly resource?: {\n    readonly serviceName?: string | undefined\n    readonly serviceVersion?: string | undefined\n    readonly attributes?: Record<string, unknown>\n  } | undefined\n  readonly headers?: Headers.Input | undefined\n  readonly exportInterval?: Duration.DurationInput | undefined\n  readonly maxBatchSize?: number | undefined\n  readonly context?: (<X>(f: () => X, span: Tracer.AnySpan) => X) | undefined\n  readonly shutdownTimeout?: Duration.DurationInput | undefined\n}): Layer.Layer<never, never, HttpClient.HttpClient | OtlpSerialization> =>\n  Layer.unwrapScoped(Effect.map(make(options), Layer.setTracer))\n\n// internal\n\nfunction defaultContext<X>(f: () => X, _: any): X {\n  return f()\n}\n\ninterface SpanImpl extends Tracer.Span {\n  readonly export: (span: SpanImpl) => void\n  readonly attributes: Map<string, unknown>\n  readonly links: Array<Tracer.SpanLink>\n  readonly events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown> | undefined]>\n  status: Tracer.SpanStatus\n}\n\nconst SpanProto = {\n  _tag: \"Span\",\n  end(this: SpanImpl, endTime: bigint, exit: Exit.Exit<unknown, unknown>) {\n    this.status = {\n      _tag: \"Ended\",\n      startTime: this.status.startTime,\n      endTime,\n      exit\n    }\n    this.export(this)\n  },\n  attribute(this: SpanImpl, key: string, value: unknown) {\n    this.attributes.set(key, value)\n  },\n  event(this: SpanImpl, name: string, startTime: bigint, attributes?: Record<string, unknown>) {\n    this.events.push([name, startTime, attributes])\n  },\n  addLinks(this: SpanImpl, links: ReadonlyArray<Tracer.SpanLink>) {\n    // eslint-disable-next-line no-restricted-syntax\n    this.links.push(...links)\n  }\n}\n\nconst makeSpan = (options: {\n  readonly name: string\n  readonly parent: Option.Option<Tracer.AnySpan>\n  readonly context: Context.Context<never>\n  readonly status: Tracer.SpanStatus\n  readonly attributes: ReadonlyMap<string, unknown>\n  readonly links: ReadonlyArray<Tracer.SpanLink>\n  readonly sampled: boolean\n  readonly kind: Tracer.SpanKind\n  readonly export: (span: SpanImpl) => void\n}): SpanImpl => {\n  const self = Object.assign(Object.create(SpanProto), options)\n  if (Option.isSome(self.parent)) {\n    self.traceId = self.parent.value.traceId\n  } else {\n    self.traceId = generateId(32)\n  }\n  self.spanId = generateId(16)\n  self.events = []\n  return self\n}\n\nconst generateId = (len: number): string => {\n  const chars = \"0123456789abcdef\"\n  let result = \"\"\n  for (let i = 0; i < len; i++) {\n    result += chars[Math.floor(Math.random() * chars.length)]\n  }\n  return result\n}\n\nconst makeOtlpSpan = (self: SpanImpl): OtlpSpan => {\n  const status = self.status as ExtractTag<Tracer.SpanStatus, \"Ended\">\n  const attributes = entriesToAttributes(self.attributes.entries())\n  const events = self.events.map(([name, startTime, attributes]) => ({\n    name,\n    timeUnixNano: String(startTime),\n    attributes: attributes\n      ? entriesToAttributes(Object.entries(attributes))\n      : [],\n    droppedAttributesCount: 0\n  }))\n  let otelStatus: Status\n\n  if (status.exit._tag === \"Success\") {\n    otelStatus = constOtelStatusSuccess\n  } else if (Cause.isInterruptedOnly(status.exit.cause)) {\n    otelStatus = {\n      code: StatusCode.Ok,\n      message: Cause.pretty(status.exit.cause)\n    }\n  } else {\n    const errors = Cause.prettyErrors(status.exit.cause)\n    const firstError = errors[0]\n    otelStatus = {\n      code: StatusCode.Error\n    }\n    attributes.push({\n      key: \"span.label\",\n      value: { stringValue: \"⚠︎ Interrupted\" }\n    }, {\n      key: \"status.interrupted\",\n      value: { boolValue: true }\n    })\n    if (firstError) {\n      otelStatus.message = firstError.message\n      events.push({\n        name: \"exception\",\n        timeUnixNano: String(status.endTime),\n        droppedAttributesCount: 0,\n        attributes: [\n          {\n            \"key\": ATTR_EXCEPTION_TYPE,\n            \"value\": {\n              \"stringValue\": firstError.name\n            }\n          },\n          {\n            \"key\": ATTR_EXCEPTION_MESSAGE,\n            \"value\": {\n              \"stringValue\": firstError.message\n            }\n          },\n          {\n            \"key\": ATTR_EXCEPTION_STACKTRACE,\n            \"value\": {\n              \"stringValue\": Cause.pretty(status.exit.cause, { renderErrorCause: true })\n            }\n          }\n        ]\n      })\n    }\n  }\n\n  return {\n    traceId: self.traceId,\n    spanId: self.spanId,\n    parentSpanId: Option.isSome(self.parent) ? self.parent.value.spanId : undefined,\n    name: self.name,\n    kind: SpanKind[self.kind],\n    startTimeUnixNano: String(status.startTime),\n    endTimeUnixNano: String(status.endTime),\n    attributes,\n    droppedAttributesCount: 0,\n    events,\n    droppedEventsCount: 0,\n    status: otelStatus,\n    links: self.links.map((link) => ({\n      traceId: link.span.traceId,\n      spanId: link.span.spanId,\n      attributes: entriesToAttributes(Object.entries(link.attributes)),\n      droppedAttributesCount: 0\n    })),\n    droppedLinksCount: 0\n  }\n}\n\ninterface TraceData {\n  readonly resourceSpans: Array<ResourceSpan>\n}\n\ninterface ResourceSpan {\n  readonly resource: Resource\n  readonly scopeSpans: Array<ScopeSpan>\n}\n\ninterface ScopeSpan {\n  readonly scope: Scope\n  readonly spans: Array<OtlpSpan>\n}\n\ninterface Scope {\n  readonly name: string\n}\n\ninterface OtlpSpan {\n  readonly traceId: string\n  readonly spanId: string\n  readonly parentSpanId: string | undefined\n  readonly name: string\n  readonly kind: number\n  readonly startTimeUnixNano: string\n  readonly endTimeUnixNano: string\n  readonly attributes: Array<KeyValue>\n  readonly droppedAttributesCount: number\n  readonly events: Array<Event>\n  readonly droppedEventsCount: number\n  readonly status: Status\n  readonly links: Array<Link>\n  readonly droppedLinksCount: number\n}\n\ninterface Event {\n  readonly attributes: Array<KeyValue>\n  readonly name: string\n  readonly timeUnixNano: string\n  readonly droppedAttributesCount: number\n}\n\ninterface Link {\n  readonly attributes: Array<KeyValue>\n  readonly spanId: string\n  readonly traceId: string\n  readonly droppedAttributesCount: number\n}\n\ninterface Status {\n  readonly code: StatusCode\n  message?: string\n}\n\nconst enum StatusCode {\n  Unset = 0,\n  Ok = 1,\n  Error = 2\n}\n\nenum SpanKind {\n  unspecified = 0,\n  internal = 1,\n  server = 2,\n  client = 3,\n  producer = 4,\n  consumer = 5\n}\n\nconst constOtelStatusSuccess: Status = {\n  code: StatusCode.Ok\n}\n"
  },
  {
    "path": "packages/opentelemetry/src/Resource.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as OtelApi from \"@opentelemetry/api\"\nimport * as Resources from \"@opentelemetry/resources\"\nimport * as OtelSemConv from \"@opentelemetry/semantic-conventions\"\nimport * as Arr from \"effect/Array\"\nimport * as Config from \"effect/Config\"\nimport { GenericTag } from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { pipe } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\n\n/**\n * @since 1.0.0\n * @category identifier\n */\nexport interface Resource {\n  readonly _: unique symbol\n}\n\n/**\n * @since 1.0.0\n * @category tag\n */\nexport const Resource = GenericTag<Resource, Resources.Resource>(\"@effect/opentelemetry/Resource\")\n\n/**\n * @since 1.0.0\n * @category layer\n */\nexport const layer = (config: {\n  readonly serviceName: string\n  readonly serviceVersion?: string\n  readonly attributes?: OtelApi.Attributes\n}) =>\n  Layer.succeed(\n    Resource,\n    Resources.resourceFromAttributes(configToAttributes(config))\n  )\n\n/**\n * @since 1.0.0\n * @category config\n */\nexport const configToAttributes = (options: {\n  readonly serviceName: string\n  readonly serviceVersion?: string\n  readonly attributes?: OtelApi.Attributes\n}): Record<string, string> => {\n  const attributes: Record<string, string> = {\n    ...(options.attributes ?? undefined),\n    [OtelSemConv.ATTR_SERVICE_NAME]: options.serviceName,\n    [OtelSemConv.ATTR_TELEMETRY_SDK_NAME]: \"@effect/opentelemetry\",\n    [OtelSemConv.ATTR_TELEMETRY_SDK_LANGUAGE]: typeof (globalThis as any).document === \"undefined\"\n      ? OtelSemConv.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS\n      : OtelSemConv.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS\n  }\n  if (options.serviceVersion) {\n    attributes[OtelSemConv.ATTR_SERVICE_VERSION] = options.serviceVersion\n  }\n  return attributes\n}\n\n/**\n * @since 1.0.0\n * @category layer\n */\nexport const layerFromEnv = (\n  additionalAttributes?:\n    | OtelApi.Attributes\n    | undefined\n): Layer.Layer<Resource> =>\n  Layer.effect(\n    Resource,\n    Effect.gen(function*() {\n      const serviceName = yield* pipe(Config.string(\"OTEL_SERVICE_NAME\"), Config.option, Effect.orDie)\n      const attributes = yield* pipe(\n        Config.string(\"OTEL_RESOURCE_ATTRIBUTES\"),\n        Config.withDefault(\"\"),\n        Config.map((s) => {\n          const attrs = s.split(\",\")\n          return Arr.reduce(attrs, {} as OtelApi.Attributes, (acc, attr) => {\n            const parts = attr.split(\"=\")\n            if (parts.length !== 2) {\n              return acc\n            }\n            acc[parts[0].trim()] = parts[1].trim()\n            return acc\n          })\n        }),\n        Effect.orDie\n      )\n      if (serviceName._tag === \"Some\") {\n        attributes[OtelSemConv.ATTR_SERVICE_NAME] = serviceName.value\n      }\n      if (additionalAttributes) {\n        Object.assign(attributes, additionalAttributes)\n      }\n      return Resources.resourceFromAttributes(attributes)\n    })\n  )\n\n/**\n * @since 2.0.0\n * @category layer\n */\nexport const layerEmpty = Layer.succeed(\n  Resource,\n  Resources.emptyResource()\n)\n"
  },
  {
    "path": "packages/opentelemetry/src/Tracer.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Otel from \"@opentelemetry/api\"\nimport type { NoSuchElementException } from \"effect/Cause\"\nimport type { Tag } from \"effect/Context\"\nimport type { Effect } from \"effect/Effect\"\nimport type { Layer } from \"effect/Layer\"\nimport type { ExternalSpan, ParentSpan, Tracer as EffectTracer } from \"effect/Tracer\"\nimport * as internal from \"./internal/tracer.js\"\nimport type { Resource } from \"./Resource.js\"\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: Effect<EffectTracer, never, OtelTracer> = internal.make\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeExternalSpan: (\n  options: {\n    readonly traceId: string\n    readonly spanId: string\n    readonly traceFlags?: number | undefined\n    readonly traceState?: string | Otel.TraceState | undefined\n  }\n) => ExternalSpan = internal.makeExternalSpan\n\n/**\n * Get the current OpenTelemetry span.\n *\n * Works with both the official OpenTelemetry API (via `Tracer.layer`, `NodeSdk.layer`, etc.)\n * and the lightweight OTLP module (`OtlpTracer.layer`).\n *\n * When using OTLP, the returned span is a wrapper that conforms to the\n * OpenTelemetry `Span` interface.\n *\n * @since 1.0.0\n * @category accessors\n */\nexport const currentOtelSpan: Effect<Otel.Span, NoSuchElementException> = internal.currentOtelSpan\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerWithoutOtelTracer: Layer<never, never, OtelTracer> = internal.layerWithoutOtelTracer\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer<OtelTracer, never, Resource | OtelTracerProvider> = internal.layer\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerGlobal: Layer<OtelTracer, never, Resource> = internal.layerGlobal\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerTracer: Layer<OtelTracer, never, Resource | OtelTracerProvider> = internal.layerTracer\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerGlobalTracer: Layer<OtelTracer, never, Resource> = internal.layerGlobalTracer\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport interface OtelTracerProvider {\n  readonly _: unique symbol\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const OtelTracerProvider: Tag<OtelTracerProvider, Otel.TracerProvider> = internal.TracerProvider\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport interface OtelTracer {\n  readonly _: unique symbol\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const OtelTracer: Tag<OtelTracer, Otel.Tracer> = internal.Tracer\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport interface OtelTraceFlags {\n  readonly _: unique symbol\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const OtelTraceFlags: Tag<OtelTraceFlags, Otel.TraceFlags> = internal.traceFlagsTag\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport interface OtelTraceState {\n  readonly _: unique symbol\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const OtelTraceState: Tag<OtelTraceState, Otel.TraceState> = internal.traceStateTag\n\n/**\n * Set the effect's parent span from the given opentelemetry `SpanContext`.\n *\n * This is handy when you set up OpenTelemetry outside of Effect and want to\n * attach to a parent span.\n *\n * @since 1.0.0\n * @category propagation\n */\nexport const withSpanContext: {\n  (\n    spanContext: Otel.SpanContext\n  ): <A, E, R>(\n    effect: Effect<A, E, R>\n  ) => Effect<A, E, Exclude<R, ParentSpan>>\n  <A, E, R>(\n    effect: Effect<A, E, R>,\n    spanContext: Otel.SpanContext\n  ): Effect<A, E, Exclude<R, ParentSpan>>\n} = internal.withSpanContext\n"
  },
  {
    "path": "packages/opentelemetry/src/WebSdk.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as OtelApi from \"@opentelemetry/api\"\nimport type { LoggerProviderConfig, LogRecordProcessor } from \"@opentelemetry/sdk-logs\"\nimport type { MetricReader } from \"@opentelemetry/sdk-metrics\"\nimport type { SpanProcessor, TracerConfig } from \"@opentelemetry/sdk-trace-base\"\nimport { WebTracerProvider } from \"@opentelemetry/sdk-trace-web\"\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport * as Effect from \"effect/Effect\"\nimport { constant, type LazyArg } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport { isNonEmpty } from \"./internal/utils.js\"\nimport * as Logger from \"./Logger.js\"\nimport * as Metrics from \"./Metrics.js\"\nimport * as Resource from \"./Resource.js\"\nimport * as Tracer from \"./Tracer.js\"\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport interface Configuration {\n  readonly spanProcessor?: SpanProcessor | ReadonlyArray<SpanProcessor> | undefined\n  readonly tracerConfig?: Omit<TracerConfig, \"resource\">\n  readonly metricReader?: MetricReader | ReadonlyArray<MetricReader> | undefined\n  readonly logRecordProcessor?: LogRecordProcessor | ReadonlyArray<LogRecordProcessor> | undefined\n  readonly loggerProviderConfig?: Omit<LoggerProviderConfig, \"resource\"> | undefined\n  readonly resource: {\n    readonly serviceName: string\n    readonly serviceVersion?: string\n    readonly attributes?: OtelApi.Attributes\n  }\n}\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerTracerProvider = (\n  processor: SpanProcessor | NonEmptyReadonlyArray<SpanProcessor>,\n  config?: Omit<TracerConfig, \"resource\">\n): Layer.Layer<Tracer.OtelTracerProvider, never, Resource.Resource> =>\n  Layer.scoped(\n    Tracer.OtelTracerProvider,\n    Effect.flatMap(\n      Resource.Resource,\n      (resource) =>\n        Effect.acquireRelease(\n          Effect.sync(() => {\n            const provider = new WebTracerProvider({\n              ...(config ?? undefined),\n              resource,\n              spanProcessors: Array.isArray(processor) ? (processor as any) : [processor]\n            })\n            return provider\n          }),\n          (provider) => Effect.ignoreLogged(Effect.promise(() => provider.forceFlush().then(() => provider.shutdown())))\n        )\n    )\n  )\n\n/**\n * @since 1.0.0\n * @category layer\n */\nexport const layer: {\n  (evaluate: LazyArg<Configuration>): Layer.Layer<Resource.Resource>\n  <E, R>(evaluate: Effect.Effect<Configuration, E, R>): Layer.Layer<Resource.Resource, E, R>\n} = (\n  evaluate: LazyArg<Configuration> | Effect.Effect<Configuration, any, any>\n): Layer.Layer<Resource.Resource> =>\n  Layer.unwrapEffect(\n    Effect.map(\n      Effect.isEffect(evaluate)\n        ? evaluate as Effect.Effect<Configuration>\n        : Effect.sync(evaluate),\n      (config) => {\n        const ResourceLive = Resource.layer(config.resource)\n\n        const TracerLive = isNonEmpty(config.spanProcessor)\n          ? Layer.provide(Tracer.layer, layerTracerProvider(config.spanProcessor, config.tracerConfig))\n          : Layer.empty\n\n        const LoggerLive = isNonEmpty(config.logRecordProcessor)\n          ? Layer.provide(\n            Logger.layerLoggerAdd,\n            Logger.layerLoggerProvider(config.logRecordProcessor, config.loggerProviderConfig)\n          )\n          : Layer.empty\n\n        const MetricsLive = isNonEmpty(config.metricReader)\n          ? Metrics.layer(constant(config.metricReader))\n          : Layer.empty\n\n        return Layer.mergeAll(TracerLive, MetricsLive, LoggerLive).pipe(\n          Layer.provideMerge(ResourceLive)\n        )\n      }\n    )\n  )\n"
  },
  {
    "path": "packages/opentelemetry/src/index.ts",
    "content": "/**\n * @since 1.0.0\n */\nexport * as Logger from \"./Logger.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Metrics from \"./Metrics.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as NodeSdk from \"./NodeSdk.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Otlp from \"./Otlp.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OtlpLogger from \"./OtlpLogger.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OtlpMetrics from \"./OtlpMetrics.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OtlpResource from \"./OtlpResource.js\"\n\n/**\n * OtlpSerialization service for tree-shakable protobuf support.\n *\n * This module provides the `OtlpSerialization` service that abstracts the\n * encoding of OTLP telemetry data to HttpBody.\n *\n * @since 1.0.0\n */\nexport * as OtlpSerialization from \"./OtlpSerialization.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as OtlpTracer from \"./OtlpTracer.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Resource from \"./Resource.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as Tracer from \"./Tracer.js\"\n\n/**\n * @since 1.0.0\n */\nexport * as WebSdk from \"./WebSdk.js\"\n"
  },
  {
    "path": "packages/opentelemetry/src/internal/metrics.ts",
    "content": "import type { HrTime } from \"@opentelemetry/api\"\nimport { ValueType } from \"@opentelemetry/api\"\nimport type * as Resources from \"@opentelemetry/resources\"\nimport type {\n  CollectionResult,\n  DataPoint,\n  Histogram,\n  MetricCollectOptions,\n  MetricData,\n  MetricProducer,\n  MetricReader\n} from \"@opentelemetry/sdk-metrics\"\nimport { AggregationTemporality, DataPointType, InstrumentType } from \"@opentelemetry/sdk-metrics\"\nimport type { InstrumentDescriptor } from \"@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js\"\nimport * as Arr from \"effect/Array\"\nimport type { DurationInput } from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport type { LazyArg } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Metric from \"effect/Metric\"\nimport type * as MetricKey from \"effect/MetricKey\"\nimport * as MetricKeyType from \"effect/MetricKeyType\"\nimport * as MetricState from \"effect/MetricState\"\nimport * as Option from \"effect/Option\"\nimport * as Resource from \"../Resource.js\"\n\nconst sdkName = \"@effect/opentelemetry/Metrics\"\n\ntype MetricDataWithInstrumentDescriptor = MetricData & {\n  readonly descriptor: InstrumentDescriptor\n}\n\n/** @internal */\nexport class MetricProducerImpl implements MetricProducer {\n  constructor(readonly resource: Resources.Resource) {}\n\n  startTimes = new Map<string, HrTime>()\n\n  startTimeFor(name: string, hrTime: HrTime) {\n    if (this.startTimes.has(name)) {\n      return this.startTimes.get(name)!\n    }\n    this.startTimes.set(name, hrTime)\n    return hrTime\n  }\n\n  collect(_options?: MetricCollectOptions): Promise<CollectionResult> {\n    const snapshot = Metric.unsafeSnapshot()\n    const hrTimeNow = currentHrTime()\n    const metricData: Array<MetricData> = []\n    const metricDataByName = new Map<string, MetricData>()\n    const addMetricData = (data: MetricDataWithInstrumentDescriptor) => {\n      metricData.push(data)\n      metricDataByName.set(data.descriptor.name, data)\n    }\n\n    for (let i = 0, len = snapshot.length; i < len; i++) {\n      const { metricKey, metricState } = snapshot[i]\n      const attributes = Arr.reduce(metricKey.tags, {}, (acc: Record<string, string>, label) => {\n        acc[label.key] = label.value\n        return acc\n      })\n      const descriptor = descriptorFromKey(metricKey, attributes)\n      const startTime = this.startTimeFor(descriptor.name, hrTimeNow)\n\n      if (MetricState.isCounterState(metricState)) {\n        const dataPoint: DataPoint<number> = {\n          startTime,\n          endTime: hrTimeNow,\n          attributes,\n          value: Number(metricState.count)\n        }\n        if (metricDataByName.has(descriptor.name)) {\n          metricDataByName.get(descriptor.name)!.dataPoints.push(dataPoint as any)\n        } else {\n          addMetricData({\n            dataPointType: DataPointType.SUM,\n            descriptor,\n            isMonotonic: descriptor.type === InstrumentType.COUNTER,\n            aggregationTemporality: AggregationTemporality.CUMULATIVE,\n            dataPoints: [dataPoint]\n          })\n        }\n      } else if (MetricState.isGaugeState(metricState)) {\n        const dataPoint: DataPoint<number> = {\n          startTime,\n          endTime: hrTimeNow,\n          attributes,\n          value: Number(metricState.value)\n        }\n        if (metricDataByName.has(descriptor.name)) {\n          metricDataByName.get(descriptor.name)!.dataPoints.push(dataPoint as any)\n        } else {\n          addMetricData({\n            dataPointType: DataPointType.GAUGE,\n            descriptor,\n            aggregationTemporality: AggregationTemporality.CUMULATIVE,\n            dataPoints: [dataPoint]\n          })\n        }\n      } else if (MetricState.isHistogramState(metricState)) {\n        const size = metricState.buckets.length\n        const buckets = {\n          boundaries: Arr.allocate(size - 1) as Array<number>,\n          counts: Arr.allocate(size) as Array<number>\n        }\n        let i = 0\n        let prev = 0\n        for (const [boundary, value] of metricState.buckets) {\n          if (i < size - 1) {\n            buckets.boundaries[i] = boundary\n          }\n          buckets.counts[i] = value - prev\n          prev = value\n          i++\n        }\n        const dataPoint: DataPoint<Histogram> = {\n          startTime,\n          endTime: hrTimeNow,\n          attributes,\n          value: {\n            buckets,\n            count: metricState.count,\n            min: metricState.min,\n            max: metricState.max,\n            sum: metricState.sum\n          }\n        }\n\n        if (metricDataByName.has(descriptor.name)) {\n          metricDataByName.get(descriptor.name)!.dataPoints.push(dataPoint as any)\n        } else {\n          addMetricData({\n            dataPointType: DataPointType.HISTOGRAM,\n            descriptor,\n            aggregationTemporality: AggregationTemporality.CUMULATIVE,\n            dataPoints: [dataPoint]\n          })\n        }\n      } else if (MetricState.isFrequencyState(metricState)) {\n        const dataPoints: Array<DataPoint<number>> = []\n        for (const [freqKey, value] of metricState.occurrences) {\n          dataPoints.push({\n            startTime,\n            endTime: hrTimeNow,\n            attributes: {\n              ...attributes,\n              key: freqKey\n            },\n            value\n          })\n        }\n        if (metricDataByName.has(descriptor.name)) {\n          // eslint-disable-next-line no-restricted-syntax\n          metricDataByName.get(descriptor.name)!.dataPoints.push(...dataPoints as any)\n        } else {\n          addMetricData({\n            dataPointType: DataPointType.SUM,\n            descriptor: descriptorFromKey(metricKey, attributes),\n            aggregationTemporality: AggregationTemporality.CUMULATIVE,\n            isMonotonic: true,\n            dataPoints\n          })\n        }\n      } else if (MetricState.isSummaryState(metricState)) {\n        const dataPoints: Array<DataPoint<number>> = [{\n          startTime,\n          endTime: hrTimeNow,\n          attributes: { ...attributes, quantile: \"min\" },\n          value: metricState.min\n        }]\n        for (const [quantile, value] of metricState.quantiles) {\n          dataPoints.push({\n            startTime,\n            endTime: hrTimeNow,\n            attributes: { ...attributes, quantile: quantile.toString() },\n            value: value._tag === \"Some\" ? value.value : 0\n          })\n        }\n        dataPoints.push({\n          startTime,\n          endTime: hrTimeNow,\n          attributes: { ...attributes, quantile: \"max\" },\n          value: metricState.max\n        })\n        const countDataPoint: DataPoint<number> = {\n          startTime,\n          endTime: hrTimeNow,\n          attributes,\n          value: metricState.count\n        }\n        const sumDataPoint: DataPoint<number> = {\n          startTime,\n          endTime: hrTimeNow,\n          attributes,\n          value: metricState.sum\n        }\n\n        if (metricDataByName.has(`${descriptor.name}_quantiles`)) {\n          // eslint-disable-next-line no-restricted-syntax\n          metricDataByName.get(`${descriptor.name}_quantiles`)!.dataPoints.push(...dataPoints as any)\n          metricDataByName.get(`${descriptor.name}_count`)!.dataPoints.push(countDataPoint as any)\n          metricDataByName.get(`${descriptor.name}_sum`)!.dataPoints.push(sumDataPoint as any)\n        } else {\n          addMetricData({\n            dataPointType: DataPointType.SUM,\n            descriptor: descriptorFromKey(metricKey, attributes, \"quantiles\"),\n            aggregationTemporality: AggregationTemporality.CUMULATIVE,\n            isMonotonic: false,\n            dataPoints\n          })\n          addMetricData({\n            dataPointType: DataPointType.SUM,\n            descriptor: {\n              ...descriptorMeta(metricKey, \"count\"),\n              unit: \"1\",\n              type: InstrumentType.COUNTER,\n              valueType: ValueType.INT\n            },\n            aggregationTemporality: AggregationTemporality.CUMULATIVE,\n            isMonotonic: true,\n            dataPoints: [countDataPoint]\n          })\n          addMetricData({\n            dataPointType: DataPointType.SUM,\n            descriptor: {\n              ...descriptorMeta(metricKey, \"sum\"),\n              unit: \"1\",\n              type: InstrumentType.COUNTER,\n              valueType: ValueType.DOUBLE\n            },\n            aggregationTemporality: AggregationTemporality.CUMULATIVE,\n            isMonotonic: true,\n            dataPoints: [sumDataPoint]\n          })\n        }\n      }\n    }\n\n    return Promise.resolve({\n      resourceMetrics: {\n        resource: this.resource,\n        scopeMetrics: [{\n          scope: { name: sdkName },\n          metrics: metricData\n        }]\n      },\n      errors: []\n    })\n  }\n}\n\nconst descriptorMeta = (\n  metricKey: MetricKey.MetricKey.Untyped,\n  suffix?: string\n) => ({\n  name: suffix ? `${metricKey.name}_${suffix}` : metricKey.name,\n  description: Option.getOrElse(metricKey.description, () => \"\"),\n  advice: {}\n})\n\nconst descriptorFromKey = (\n  metricKey: MetricKey.MetricKey.Untyped,\n  tags: Record<string, string>,\n  suffix?: string\n): InstrumentDescriptor => ({\n  ...descriptorMeta(metricKey, suffix),\n  unit: tags.unit ?? tags.time_unit ?? \"1\",\n  type: instrumentTypeFromKey(metricKey),\n  valueType: \"bigint\" in metricKey.keyType && metricKey.keyType.bigint === true ? ValueType.INT : ValueType.DOUBLE\n})\n\nconst instrumentTypeFromKey = (key: MetricKey.MetricKey.Untyped): InstrumentType => {\n  if (MetricKeyType.isHistogramKey(key.keyType)) {\n    return InstrumentType.HISTOGRAM\n  } else if (MetricKeyType.isGaugeKey(key.keyType)) {\n    return InstrumentType.OBSERVABLE_GAUGE\n  } else if (MetricKeyType.isFrequencyKey(key.keyType)) {\n    return InstrumentType.COUNTER\n  } else if (MetricKeyType.isCounterKey(key.keyType) && key.keyType.incremental) {\n    return InstrumentType.COUNTER\n  }\n\n  return InstrumentType.UP_DOWN_COUNTER\n}\n\nconst currentHrTime = (): HrTime => {\n  const now = Date.now()\n  return [Math.floor(now / 1000), (now % 1000) * 1000000]\n}\n\n/** @internal */\nexport const makeProducer = Effect.map(\n  Resource.Resource,\n  (resource): MetricProducer => new MetricProducerImpl(resource)\n)\n\n/** @internal */\nexport const registerProducer = (\n  self: MetricProducer,\n  metricReader: LazyArg<MetricReader | Arr.NonEmptyReadonlyArray<MetricReader>>,\n  options?: {\n    readonly shutdownTimeout?: DurationInput | undefined\n  }\n) =>\n  Effect.acquireRelease(\n    Effect.sync(() => {\n      const reader = metricReader()\n      const readers: Array<MetricReader> = Array.isArray(reader) ? reader : [reader] as any\n      readers.forEach((reader) => reader.setMetricProducer(self))\n      return readers\n    }),\n    (readers) =>\n      Effect.promise(() =>\n        Promise.all(\n          readers.map((reader) => reader.shutdown())\n        )\n      ).pipe(\n        Effect.ignoreLogged,\n        Effect.interruptible,\n        Effect.timeoutOption(options?.shutdownTimeout ?? 3000)\n      )\n  )\n\n/** @internal */\nexport const layer = (evaluate: LazyArg<MetricReader | Arr.NonEmptyReadonlyArray<MetricReader>>, options?: {\n  readonly shutdownTimeout?: DurationInput | undefined\n}) =>\n  Layer.scopedDiscard(Effect.flatMap(\n    makeProducer,\n    (producer) => registerProducer(producer, evaluate, options)\n  ))\n"
  },
  {
    "path": "packages/opentelemetry/src/internal/otlpExporter.ts",
    "content": "import * as Headers from \"@effect/platform/Headers\"\nimport type * as HttpBody from \"@effect/platform/HttpBody\"\nimport * as HttpClient from \"@effect/platform/HttpClient\"\nimport * as HttpClientError from \"@effect/platform/HttpClientError\"\nimport * as HttpClientRequest from \"@effect/platform/HttpClientRequest\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberSet from \"effect/FiberSet\"\nimport * as Num from \"effect/Number\"\nimport * as Option from \"effect/Option\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Scope from \"effect/Scope\"\n\nconst policy = Schedule.forever.pipe(\n  Schedule.passthrough,\n  Schedule.addDelay((error) => {\n    if (\n      HttpClientError.isHttpClientError(error)\n      && error._tag === \"ResponseError\"\n      && error.response.status === 429\n    ) {\n      const retryAfter = Option.fromNullable(error.response.headers[\"retry-after\"]).pipe(\n        Option.flatMap(Num.parse),\n        Option.getOrElse(() => 5)\n      )\n      return Duration.seconds(retryAfter)\n    }\n    return Duration.seconds(1)\n  })\n)\n\n/** @internal */\nexport const make: (\n  options: {\n    readonly url: string\n    readonly headers: Headers.Input | undefined\n    readonly label: string\n    readonly exportInterval: Duration.DurationInput\n    readonly maxBatchSize: number | \"disabled\"\n    readonly body: (data: Array<any>) => HttpBody.HttpBody\n    readonly shutdownTimeout: Duration.DurationInput\n  }\n) => Effect.Effect<\n  { readonly push: (data: unknown) => void },\n  never,\n  HttpClient.HttpClient | Scope.Scope\n> = Effect.fnUntraced(function*(options) {\n  const clock = yield* Effect.clock\n  const scope = yield* Effect.scope\n  const exportInterval = Duration.decode(options.exportInterval)\n  let disabledUntil: number | undefined = undefined\n\n  const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient).pipe(\n    HttpClient.retryTransient({ schedule: policy, times: 3 })\n  )\n\n  let headers = Headers.unsafeFromRecord({\n    \"user-agent\": `effect-opentelemetry-${options.label}/0.0.0`\n  })\n  if (options.headers) {\n    headers = Headers.merge(Headers.fromInput(options.headers), headers)\n  }\n\n  const request = HttpClientRequest.post(options.url, { headers })\n  let buffer: Array<any> = []\n  const runExport = Effect.suspend(() => {\n    if (disabledUntil !== undefined && clock.unsafeCurrentTimeMillis() < disabledUntil) {\n      return Effect.void\n    } else if (disabledUntil !== undefined) {\n      disabledUntil = undefined\n    }\n    const items = buffer\n    if (options.maxBatchSize !== \"disabled\") {\n      if (buffer.length === 0) {\n        return Effect.void\n      }\n      buffer = []\n    }\n    const body = options.body(items)\n    const requestWithBody = HttpClientRequest.setBody(request, body)\n\n    return client.execute(requestWithBody).pipe(\n      Effect.asVoid,\n      Effect.withTracerEnabled(false)\n    )\n  }).pipe(\n    Effect.catchAllCause((cause) => {\n      if (disabledUntil !== undefined) return Effect.void\n      disabledUntil = clock.unsafeCurrentTimeMillis() + Duration.toMillis(\"1 minute\")\n      return Effect.logDebug(`Disabling ${options.label} for 60 seconds`, cause)\n    })\n  )\n\n  yield* Scope.addFinalizer(\n    scope,\n    runExport.pipe(\n      Effect.ignore,\n      Effect.interruptible,\n      Effect.timeoutOption(options.shutdownTimeout)\n    )\n  )\n\n  yield* Effect.sleep(exportInterval).pipe(\n    Effect.zipRight(runExport),\n    Effect.forever,\n    Effect.annotateLogs({\n      package: \"@effect/opentelemetry\",\n      module: options.label\n    }),\n    Effect.forkIn(scope),\n    Effect.interruptible\n  )\n\n  const runFork = yield* FiberSet.makeRuntime().pipe(\n    Effect.interruptible\n  )\n  return {\n    push(data) {\n      if (disabledUntil !== undefined) return\n      buffer.push(data)\n      if (options.maxBatchSize !== \"disabled\" && buffer.length >= options.maxBatchSize) {\n        runFork(runExport)\n      }\n    }\n  }\n})\n"
  },
  {
    "path": "packages/opentelemetry/src/internal/otlpProtobuf.ts",
    "content": "/**\n * OTLP Protobuf encoding for traces, metrics, and logs.\n *\n * Implements the protobuf wire format according to:\n * https://github.com/open-telemetry/opentelemetry-proto\n *\n * @internal\n */\n\nimport type { AnyValue, KeyValue, Resource } from \"../OtlpResource.js\"\nimport * as Proto from \"./protobuf.js\"\n\n// Common types (opentelemetry.proto.common.v1)\n\n/**\n * Encodes an AnyValue message.\n *\n * message AnyValue {\n *   oneof value {\n *     string string_value = 1;\n *     bool bool_value = 2;\n *     int64 int_value = 3;\n *     double double_value = 4;\n *     ArrayValue array_value = 5;\n *     KeyValueList kvlist_value = 6;\n *     bytes bytes_value = 7;\n *   }\n * }\n */\nexport const encodeAnyValue = (value: AnyValue): Uint8Array => {\n  if (value.stringValue !== undefined && value.stringValue !== null) {\n    return Proto.stringField(1, value.stringValue)\n  }\n  if (value.boolValue !== undefined && value.boolValue !== null) {\n    return Proto.boolField(2, value.boolValue)\n  }\n  if (value.intValue !== undefined && value.intValue !== null) {\n    return Proto.varintField(3, BigInt(value.intValue))\n  }\n  if (value.doubleValue !== undefined && value.doubleValue !== null) {\n    return Proto.doubleField(4, value.doubleValue)\n  }\n  if (value.arrayValue !== undefined) {\n    return Proto.messageField(5, encodeArrayValue(value.arrayValue))\n  }\n  if (value.kvlistValue !== undefined) {\n    return Proto.messageField(6, encodeKeyValueList(value.kvlistValue))\n  }\n  if (value.bytesValue !== undefined) {\n    return Proto.lengthDelimitedField(7, value.bytesValue)\n  }\n  return new Uint8Array(0)\n}\n\n/**\n * Encodes an ArrayValue message.\n *\n * message ArrayValue {\n *   repeated AnyValue values = 1;\n * }\n */\nexport const encodeArrayValue = (value: { values: ReadonlyArray<AnyValue> }): Uint8Array =>\n  Proto.repeatedField(1, value.values, encodeAnyValue)\n\n/**\n * Encodes a KeyValueList message.\n *\n * message KeyValueList {\n *   repeated KeyValue values = 1;\n * }\n */\nexport const encodeKeyValueList = (value: { values: ReadonlyArray<KeyValue> }): Uint8Array =>\n  Proto.repeatedField(1, value.values, encodeKeyValue)\n\n/**\n * Encodes a KeyValue message.\n *\n * message KeyValue {\n *   string key = 1;\n *   AnyValue value = 2;\n * }\n */\nexport const encodeKeyValue = (kv: KeyValue): Uint8Array =>\n  Proto.concat(\n    Proto.stringField(1, kv.key),\n    Proto.messageField(2, encodeAnyValue(kv.value))\n  )\n\n/**\n * Encodes an InstrumentationScope message.\n *\n * message InstrumentationScope {\n *   string name = 1;\n *   string version = 2;\n *   repeated KeyValue attributes = 3;\n *   uint32 dropped_attributes_count = 4;\n * }\n */\nexport const encodeInstrumentationScope = (scope: {\n  readonly name: string\n  readonly version?: string\n  readonly attributes?: ReadonlyArray<KeyValue>\n  readonly droppedAttributesCount?: number\n}): Uint8Array =>\n  Proto.concat(\n    Proto.stringField(1, scope.name),\n    Proto.optionalStringField(2, scope.version),\n    scope.attributes ? Proto.repeatedField(3, scope.attributes, encodeKeyValue) : new Uint8Array(0),\n    scope.droppedAttributesCount ? Proto.varintField(4, scope.droppedAttributesCount) : new Uint8Array(0)\n  )\n\n// Resource types (opentelemetry.proto.resource.v1)\n\n/**\n * Encodes a Resource message.\n *\n * message Resource {\n *   repeated KeyValue attributes = 1;\n *   uint32 dropped_attributes_count = 2;\n * }\n */\nexport const encodeResource = (resource: Resource): Uint8Array =>\n  Proto.concat(\n    Proto.repeatedField(1, resource.attributes, encodeKeyValue),\n    resource.droppedAttributesCount > 0\n      ? Proto.varintField(2, resource.droppedAttributesCount)\n      : new Uint8Array(0)\n  )\n\n// Trace types (opentelemetry.proto.trace.v1)\n\n/**\n * Status code enum\n */\nexport const StatusCode = {\n  Unset: 0,\n  Ok: 1,\n  Error: 2\n} as const\n\n/**\n * SpanKind enum\n */\nexport const SpanKind = {\n  Unspecified: 0,\n  Internal: 1,\n  Server: 2,\n  Client: 3,\n  Producer: 4,\n  Consumer: 5\n} as const\n\n/**\n * Encodes a Status message.\n *\n * message Status {\n *   string message = 2;\n *   StatusCode code = 3;\n * }\n */\nexport const encodeStatus = (status: {\n  readonly code: number\n  readonly message?: string\n}): Uint8Array =>\n  Proto.concat(\n    Proto.optionalStringField(2, status.message),\n    Proto.varintField(3, status.code)\n  )\n\n/**\n * Encodes an Event message.\n *\n * message Event {\n *   fixed64 time_unix_nano = 1;\n *   string name = 2;\n *   repeated KeyValue attributes = 3;\n *   uint32 dropped_attributes_count = 4;\n * }\n */\nexport const encodeEvent = (event: {\n  readonly timeUnixNano: string\n  readonly name: string\n  readonly attributes: ReadonlyArray<KeyValue>\n  readonly droppedAttributesCount: number\n}): Uint8Array =>\n  Proto.concat(\n    Proto.fixed64Field(1, BigInt(event.timeUnixNano)),\n    Proto.stringField(2, event.name),\n    Proto.repeatedField(3, event.attributes, encodeKeyValue),\n    event.droppedAttributesCount > 0\n      ? Proto.varintField(4, event.droppedAttributesCount)\n      : new Uint8Array(0)\n  )\n\n/**\n * Encodes a Link message.\n *\n * message Link {\n *   bytes trace_id = 1;\n *   bytes span_id = 2;\n *   string trace_state = 3;\n *   repeated KeyValue attributes = 4;\n *   uint32 dropped_attributes_count = 5;\n *   fixed32 flags = 6;\n * }\n */\nexport const encodeLink = (link: {\n  readonly traceId: string\n  readonly spanId: string\n  readonly traceState?: string\n  readonly attributes: ReadonlyArray<KeyValue>\n  readonly droppedAttributesCount: number\n  readonly flags?: number\n}): Uint8Array =>\n  Proto.concat(\n    Proto.bytesFieldFromHex(1, link.traceId),\n    Proto.bytesFieldFromHex(2, link.spanId),\n    Proto.optionalStringField(3, link.traceState),\n    Proto.repeatedField(4, link.attributes, encodeKeyValue),\n    link.droppedAttributesCount > 0\n      ? Proto.varintField(5, link.droppedAttributesCount)\n      : new Uint8Array(0),\n    link.flags !== undefined ? Proto.fixed32Field(6, link.flags) : new Uint8Array(0)\n  )\n\n/**\n * Encodes a Span message.\n *\n * message Span {\n *   bytes trace_id = 1;\n *   bytes span_id = 2;\n *   string trace_state = 3;\n *   bytes parent_span_id = 4;\n *   string name = 5;\n *   SpanKind kind = 6;\n *   fixed64 start_time_unix_nano = 7;\n *   fixed64 end_time_unix_nano = 8;\n *   repeated KeyValue attributes = 9;\n *   uint32 dropped_attributes_count = 10;\n *   repeated Event events = 11;\n *   uint32 dropped_events_count = 12;\n *   repeated Link links = 13;\n *   uint32 dropped_links_count = 14;\n *   Status status = 15;\n *   fixed32 flags = 16;\n * }\n */\nexport const encodeSpan = (span: {\n  readonly traceId: string\n  readonly spanId: string\n  readonly traceState?: string\n  readonly parentSpanId?: string\n  readonly name: string\n  readonly kind: number\n  readonly startTimeUnixNano: string\n  readonly endTimeUnixNano: string\n  readonly attributes: ReadonlyArray<KeyValue>\n  readonly droppedAttributesCount: number\n  readonly events: ReadonlyArray<{\n    readonly timeUnixNano: string\n    readonly name: string\n    readonly attributes: ReadonlyArray<KeyValue>\n    readonly droppedAttributesCount: number\n  }>\n  readonly droppedEventsCount: number\n  readonly links: ReadonlyArray<{\n    readonly traceId: string\n    readonly spanId: string\n    readonly traceState?: string\n    readonly attributes: ReadonlyArray<KeyValue>\n    readonly droppedAttributesCount: number\n    readonly flags?: number\n  }>\n  readonly droppedLinksCount: number\n  readonly status: {\n    readonly code: number\n    readonly message?: string\n  }\n  readonly flags?: number\n}): Uint8Array =>\n  Proto.concat(\n    Proto.bytesFieldFromHex(1, span.traceId),\n    Proto.bytesFieldFromHex(2, span.spanId),\n    Proto.optionalStringField(3, span.traceState),\n    span.parentSpanId !== undefined\n      ? Proto.bytesFieldFromHex(4, span.parentSpanId)\n      : new Uint8Array(0),\n    Proto.stringField(5, span.name),\n    Proto.varintField(6, span.kind),\n    Proto.fixed64Field(7, BigInt(span.startTimeUnixNano)),\n    Proto.fixed64Field(8, BigInt(span.endTimeUnixNano)),\n    Proto.repeatedField(9, span.attributes, encodeKeyValue),\n    span.droppedAttributesCount > 0\n      ? Proto.varintField(10, span.droppedAttributesCount)\n      : new Uint8Array(0),\n    Proto.repeatedField(11, span.events, encodeEvent),\n    span.droppedEventsCount > 0\n      ? Proto.varintField(12, span.droppedEventsCount)\n      : new Uint8Array(0),\n    Proto.repeatedField(13, span.links, encodeLink),\n    span.droppedLinksCount > 0\n      ? Proto.varintField(14, span.droppedLinksCount)\n      : new Uint8Array(0),\n    Proto.messageField(15, encodeStatus(span.status)),\n    span.flags !== undefined ? Proto.fixed32Field(16, span.flags) : new Uint8Array(0)\n  )\n\n/**\n * Encodes a ScopeSpans message.\n *\n * message ScopeSpans {\n *   InstrumentationScope scope = 1;\n *   repeated Span spans = 2;\n *   string schema_url = 3;\n * }\n */\nexport const encodeScopeSpans = (scopeSpans: {\n  readonly scope: { readonly name: string; readonly version?: string }\n  readonly spans: ReadonlyArray<Parameters<typeof encodeSpan>[0]>\n  readonly schemaUrl?: string\n}): Uint8Array =>\n  Proto.concat(\n    Proto.messageField(1, encodeInstrumentationScope(scopeSpans.scope)),\n    Proto.repeatedField(2, scopeSpans.spans, encodeSpan),\n    Proto.optionalStringField(3, scopeSpans.schemaUrl)\n  )\n\n/**\n * Encodes a ResourceSpans message.\n *\n * message ResourceSpans {\n *   Resource resource = 1;\n *   repeated ScopeSpans scope_spans = 2;\n *   string schema_url = 3;\n * }\n */\nexport const encodeResourceSpans = (resourceSpans: {\n  readonly resource: Resource\n  readonly scopeSpans: ReadonlyArray<Parameters<typeof encodeScopeSpans>[0]>\n  readonly schemaUrl?: string\n}): Uint8Array =>\n  Proto.concat(\n    Proto.messageField(1, encodeResource(resourceSpans.resource)),\n    Proto.repeatedField(2, resourceSpans.scopeSpans, encodeScopeSpans),\n    Proto.optionalStringField(3, resourceSpans.schemaUrl)\n  )\n\n/**\n * Encodes a TracesData message (top-level export request).\n *\n * message TracesData {\n *   repeated ResourceSpans resource_spans = 1;\n * }\n */\nexport const encodeTracesData = (tracesData: {\n  readonly resourceSpans: ReadonlyArray<Parameters<typeof encodeResourceSpans>[0]>\n}): Uint8Array => Proto.repeatedField(1, tracesData.resourceSpans, encodeResourceSpans)\n\n// Metrics types (opentelemetry.proto.metrics.v1)\n\n/**\n * AggregationTemporality enum\n */\nexport const AggregationTemporality = {\n  Unspecified: 0,\n  Delta: 1,\n  Cumulative: 2\n} as const\n\n/**\n * Encodes a NumberDataPoint message.\n *\n * message NumberDataPoint {\n *   repeated KeyValue attributes = 7;\n *   fixed64 start_time_unix_nano = 2;\n *   fixed64 time_unix_nano = 3;\n *   oneof value {\n *     double as_double = 4;\n *     sfixed64 as_int = 6;\n *   }\n *   repeated Exemplar exemplars = 5;\n *   uint32 flags = 8;\n * }\n */\nexport const encodeNumberDataPoint = (point: {\n  readonly attributes: ReadonlyArray<KeyValue>\n  readonly startTimeUnixNano: string\n  readonly timeUnixNano: string\n  readonly asDouble?: number | undefined\n  readonly asInt?: string | number | bigint | undefined\n  readonly flags?: number | undefined\n}): Uint8Array =>\n  Proto.concat(\n    Proto.fixed64Field(2, BigInt(point.startTimeUnixNano)),\n    Proto.fixed64Field(3, BigInt(point.timeUnixNano)),\n    point.asDouble !== undefined\n      ? Proto.doubleField(4, point.asDouble)\n      : new Uint8Array(0),\n    point.asInt !== undefined\n      ? Proto.fixed64Field(6, BigInt(point.asInt))\n      : new Uint8Array(0),\n    Proto.repeatedField(7, point.attributes, encodeKeyValue),\n    point.flags !== undefined ? Proto.varintField(8, point.flags) : new Uint8Array(0)\n  )\n\n/**\n * Encodes a HistogramDataPoint message.\n *\n * message HistogramDataPoint {\n *   repeated KeyValue attributes = 9;\n *   fixed64 start_time_unix_nano = 2;\n *   fixed64 time_unix_nano = 3;\n *   fixed64 count = 4;\n *   optional double sum = 5;\n *   repeated fixed64 bucket_counts = 6;\n *   repeated double explicit_bounds = 7;\n *   optional double min = 11;\n *   optional double max = 12;\n *   uint32 flags = 10;\n * }\n */\nexport const encodeHistogramDataPoint = (point: {\n  readonly attributes: ReadonlyArray<KeyValue>\n  readonly startTimeUnixNano: string\n  readonly timeUnixNano: string\n  readonly count: string | number | bigint\n  readonly sum?: number | undefined\n  readonly bucketCounts: ReadonlyArray<string | number | bigint>\n  readonly explicitBounds: ReadonlyArray<number>\n  readonly min?: number | undefined\n  readonly max?: number | undefined\n  readonly flags?: number | undefined\n}): Uint8Array => {\n  // Pack bucket counts as repeated fixed64\n  const bucketCountsEncoded = Proto.concat(\n    ...point.bucketCounts.map((count) => Proto.fixed64Field(6, BigInt(count)))\n  )\n  // Pack explicit bounds as repeated double\n  const explicitBoundsEncoded = Proto.concat(\n    ...point.explicitBounds.map((bound) => Proto.doubleField(7, bound))\n  )\n  return Proto.concat(\n    Proto.fixed64Field(2, BigInt(point.startTimeUnixNano)),\n    Proto.fixed64Field(3, BigInt(point.timeUnixNano)),\n    Proto.fixed64Field(4, BigInt(point.count)),\n    point.sum !== undefined ? Proto.doubleField(5, point.sum) : new Uint8Array(0),\n    bucketCountsEncoded,\n    explicitBoundsEncoded,\n    Proto.repeatedField(9, point.attributes, encodeKeyValue),\n    point.flags !== undefined ? Proto.varintField(10, point.flags) : new Uint8Array(0),\n    point.min !== undefined ? Proto.doubleField(11, point.min) : new Uint8Array(0),\n    point.max !== undefined ? Proto.doubleField(12, point.max) : new Uint8Array(0)\n  )\n}\n\n/**\n * Encodes a Gauge message.\n *\n * message Gauge {\n *   repeated NumberDataPoint data_points = 1;\n * }\n */\nexport const encodeGauge = (gauge: {\n  readonly dataPoints: ReadonlyArray<Parameters<typeof encodeNumberDataPoint>[0]>\n}): Uint8Array => Proto.repeatedField(1, gauge.dataPoints, encodeNumberDataPoint)\n\n/**\n * Encodes a Sum message.\n *\n * message Sum {\n *   repeated NumberDataPoint data_points = 1;\n *   AggregationTemporality aggregation_temporality = 2;\n *   bool is_monotonic = 3;\n * }\n */\nexport const encodeSum = (sum: {\n  readonly dataPoints: ReadonlyArray<Parameters<typeof encodeNumberDataPoint>[0]>\n  readonly aggregationTemporality: number\n  readonly isMonotonic: boolean\n}): Uint8Array =>\n  Proto.concat(\n    Proto.repeatedField(1, sum.dataPoints, encodeNumberDataPoint),\n    Proto.varintField(2, sum.aggregationTemporality),\n    Proto.boolField(3, sum.isMonotonic)\n  )\n\n/**\n * Encodes a Histogram message.\n *\n * message Histogram {\n *   repeated HistogramDataPoint data_points = 1;\n *   AggregationTemporality aggregation_temporality = 2;\n * }\n */\nexport const encodeHistogram = (histogram: {\n  readonly dataPoints: ReadonlyArray<Parameters<typeof encodeHistogramDataPoint>[0]>\n  readonly aggregationTemporality: number\n}): Uint8Array =>\n  Proto.concat(\n    Proto.repeatedField(1, histogram.dataPoints, encodeHistogramDataPoint),\n    Proto.varintField(2, histogram.aggregationTemporality)\n  )\n\n/**\n * Encodes a Metric message.\n *\n * message Metric {\n *   string name = 1;\n *   string description = 2;\n *   string unit = 3;\n *   oneof data {\n *     Gauge gauge = 5;\n *     Sum sum = 7;\n *     Histogram histogram = 9;\n *     ExponentialHistogram exponential_histogram = 10;\n *     Summary summary = 11;\n *   }\n * }\n */\nexport const encodeMetric = (metric: {\n  readonly name: string\n  readonly description?: string | undefined\n  readonly unit?: string | undefined\n  readonly gauge?: Parameters<typeof encodeGauge>[0] | undefined\n  readonly sum?: Parameters<typeof encodeSum>[0] | undefined\n  readonly histogram?: Parameters<typeof encodeHistogram>[0] | undefined\n}): Uint8Array =>\n  Proto.concat(\n    Proto.stringField(1, metric.name),\n    Proto.optionalStringField(2, metric.description),\n    Proto.optionalStringField(3, metric.unit),\n    metric.gauge !== undefined\n      ? Proto.messageField(5, encodeGauge(metric.gauge))\n      : new Uint8Array(0),\n    metric.sum !== undefined\n      ? Proto.messageField(7, encodeSum(metric.sum))\n      : new Uint8Array(0),\n    metric.histogram !== undefined\n      ? Proto.messageField(9, encodeHistogram(metric.histogram))\n      : new Uint8Array(0)\n  )\n\n/**\n * Encodes a ScopeMetrics message.\n *\n * message ScopeMetrics {\n *   InstrumentationScope scope = 1;\n *   repeated Metric metrics = 2;\n *   string schema_url = 3;\n * }\n */\nexport const encodeScopeMetrics = (scopeMetrics: {\n  readonly scope: { readonly name: string; readonly version?: string }\n  readonly metrics: ReadonlyArray<Parameters<typeof encodeMetric>[0]>\n  readonly schemaUrl?: string\n}): Uint8Array =>\n  Proto.concat(\n    Proto.messageField(1, encodeInstrumentationScope(scopeMetrics.scope)),\n    Proto.repeatedField(2, scopeMetrics.metrics, encodeMetric),\n    Proto.optionalStringField(3, scopeMetrics.schemaUrl)\n  )\n\n/**\n * Encodes a ResourceMetrics message.\n *\n * message ResourceMetrics {\n *   Resource resource = 1;\n *   repeated ScopeMetrics scope_metrics = 2;\n *   string schema_url = 3;\n * }\n */\nexport const encodeResourceMetrics = (resourceMetrics: {\n  readonly resource: Resource\n  readonly scopeMetrics: ReadonlyArray<Parameters<typeof encodeScopeMetrics>[0]>\n  readonly schemaUrl?: string\n}): Uint8Array =>\n  Proto.concat(\n    Proto.messageField(1, encodeResource(resourceMetrics.resource)),\n    Proto.repeatedField(2, resourceMetrics.scopeMetrics, encodeScopeMetrics),\n    Proto.optionalStringField(3, resourceMetrics.schemaUrl)\n  )\n\n/**\n * Encodes a MetricsData message (top-level export request).\n *\n * message MetricsData {\n *   repeated ResourceMetrics resource_metrics = 1;\n * }\n */\nexport const encodeMetricsData = (metricsData: {\n  readonly resourceMetrics: ReadonlyArray<Parameters<typeof encodeResourceMetrics>[0]>\n}): Uint8Array => Proto.repeatedField(1, metricsData.resourceMetrics, encodeResourceMetrics)\n\n// Logs types (opentelemetry.proto.logs.v1)\n\n/**\n * SeverityNumber enum\n */\nexport const SeverityNumber = {\n  Unspecified: 0,\n  Trace: 1,\n  Trace2: 2,\n  Trace3: 3,\n  Trace4: 4,\n  Debug: 5,\n  Debug2: 6,\n  Debug3: 7,\n  Debug4: 8,\n  Info: 9,\n  Info2: 10,\n  Info3: 11,\n  Info4: 12,\n  Warn: 13,\n  Warn2: 14,\n  Warn3: 15,\n  Warn4: 16,\n  Error: 17,\n  Error2: 18,\n  Error3: 19,\n  Error4: 20,\n  Fatal: 21,\n  Fatal2: 22,\n  Fatal3: 23,\n  Fatal4: 24\n} as const\n\n/**\n * Encodes a LogRecord message.\n *\n * message LogRecord {\n *   fixed64 time_unix_nano = 1;\n *   fixed64 observed_time_unix_nano = 11;\n *   SeverityNumber severity_number = 2;\n *   string severity_text = 3;\n *   AnyValue body = 5;\n *   repeated KeyValue attributes = 6;\n *   uint32 dropped_attributes_count = 7;\n *   fixed32 flags = 8;\n *   bytes trace_id = 9;\n *   bytes span_id = 10;\n * }\n */\nexport const encodeLogRecord = (record: {\n  readonly timeUnixNano: string\n  readonly observedTimeUnixNano?: string | undefined\n  readonly severityNumber?: number | undefined\n  readonly severityText?: string | undefined\n  readonly body?: AnyValue | undefined\n  readonly attributes: ReadonlyArray<KeyValue>\n  readonly droppedAttributesCount?: number | undefined\n  readonly flags?: number | undefined\n  readonly traceId?: string | undefined\n  readonly spanId?: string | undefined\n}): Uint8Array =>\n  Proto.concat(\n    Proto.fixed64Field(1, BigInt(record.timeUnixNano)),\n    record.severityNumber !== undefined\n      ? Proto.varintField(2, record.severityNumber)\n      : new Uint8Array(0),\n    Proto.optionalStringField(3, record.severityText),\n    record.body !== undefined\n      ? Proto.messageField(5, encodeAnyValue(record.body))\n      : new Uint8Array(0),\n    Proto.repeatedField(6, record.attributes, encodeKeyValue),\n    record.droppedAttributesCount !== undefined && record.droppedAttributesCount > 0\n      ? Proto.varintField(7, record.droppedAttributesCount)\n      : new Uint8Array(0),\n    record.flags !== undefined ? Proto.fixed32Field(8, record.flags) : new Uint8Array(0),\n    record.traceId !== undefined && record.traceId !== \"\"\n      ? Proto.bytesFieldFromHex(9, record.traceId)\n      : new Uint8Array(0),\n    record.spanId !== undefined && record.spanId !== \"\"\n      ? Proto.bytesFieldFromHex(10, record.spanId)\n      : new Uint8Array(0),\n    record.observedTimeUnixNano !== undefined\n      ? Proto.fixed64Field(11, BigInt(record.observedTimeUnixNano))\n      : new Uint8Array(0)\n  )\n\n/**\n * Encodes a ScopeLogs message.\n *\n * message ScopeLogs {\n *   InstrumentationScope scope = 1;\n *   repeated LogRecord log_records = 2;\n *   string schema_url = 3;\n * }\n */\nexport const encodeScopeLogs = (scopeLogs: {\n  readonly scope: { readonly name: string; readonly version?: string }\n  readonly logRecords: ReadonlyArray<Parameters<typeof encodeLogRecord>[0]>\n  readonly schemaUrl?: string\n}): Uint8Array =>\n  Proto.concat(\n    Proto.messageField(1, encodeInstrumentationScope(scopeLogs.scope)),\n    Proto.repeatedField(2, scopeLogs.logRecords, encodeLogRecord),\n    Proto.optionalStringField(3, scopeLogs.schemaUrl)\n  )\n\n/**\n * Encodes a ResourceLogs message.\n *\n * message ResourceLogs {\n *   Resource resource = 1;\n *   repeated ScopeLogs scope_logs = 2;\n *   string schema_url = 3;\n * }\n */\nexport const encodeResourceLogs = (resourceLogs: {\n  readonly resource: Resource\n  readonly scopeLogs: ReadonlyArray<Parameters<typeof encodeScopeLogs>[0]>\n  readonly schemaUrl?: string\n}): Uint8Array =>\n  Proto.concat(\n    Proto.messageField(1, encodeResource(resourceLogs.resource)),\n    Proto.repeatedField(2, resourceLogs.scopeLogs, encodeScopeLogs),\n    Proto.optionalStringField(3, resourceLogs.schemaUrl)\n  )\n\n/**\n * Encodes a LogsData message (top-level export request).\n *\n * message LogsData {\n *   repeated ResourceLogs resource_logs = 1;\n * }\n */\nexport const encodeLogsData = (logsData: {\n  readonly resourceLogs: ReadonlyArray<Parameters<typeof encodeResourceLogs>[0]>\n}): Uint8Array => Proto.repeatedField(1, logsData.resourceLogs, encodeResourceLogs)\n"
  },
  {
    "path": "packages/opentelemetry/src/internal/protobuf.ts",
    "content": "/**\n * Low-level protobuf wire format encoding utilities.\n *\n * Protobuf wire types:\n * - 0: Varint (int32, int64, uint32, uint64, sint32, sint64, bool, enum)\n * - 1: 64-bit (fixed64, sfixed64, double)\n * - 2: Length-delimited (string, bytes, embedded messages, packed repeated fields)\n * - 5: 32-bit (fixed32, sfixed32, float)\n *\n * @internal\n */\n\nconst enum WireType {\n  Varint = 0,\n  Fixed64 = 1,\n  LengthDelimited = 2,\n  Fixed32 = 5\n}\n\n/**\n * Encodes a field tag (field number + wire type)\n */\nconst encodeTag = (fieldNumber: number, wireType: WireType): number => (fieldNumber << 3) | wireType\n\n/**\n * Encodes a varint (variable-length integer)\n */\nexport const encodeVarint = (value: number | bigint): Uint8Array => {\n  const bytes: Array<number> = []\n  let n = typeof value === \"bigint\" ? value : BigInt(value)\n  while (n > 0x7fn) {\n    bytes.push(Number(n & 0x7fn) | 0x80)\n    n >>= 7n\n  }\n  bytes.push(Number(n))\n  return new Uint8Array(bytes)\n}\n\n/**\n * Encodes a signed varint using ZigZag encoding\n */\nexport const encodeSint = (value: number | bigint): Uint8Array => {\n  const n = typeof value === \"bigint\" ? value : BigInt(value)\n  const zigzag = (n << 1n) ^ (n >> 63n)\n  return encodeVarint(zigzag)\n}\n\n/**\n * Encodes a 64-bit fixed value (little-endian)\n */\nexport const encodeFixed64 = (value: bigint): Uint8Array => {\n  const bytes = new Uint8Array(8)\n  const view = new DataView(bytes.buffer)\n  view.setBigUint64(0, value, true)\n  return bytes\n}\n\n/**\n * Encodes a 32-bit fixed value (little-endian)\n */\nexport const encodeFixed32 = (value: number): Uint8Array => {\n  const bytes = new Uint8Array(4)\n  const view = new DataView(bytes.buffer)\n  view.setUint32(0, value, true)\n  return bytes\n}\n\n/**\n * Encodes a double (64-bit float, little-endian)\n */\nexport const encodeDouble = (value: number): Uint8Array => {\n  const bytes = new Uint8Array(8)\n  const view = new DataView(bytes.buffer)\n  view.setFloat64(0, value, true)\n  return bytes\n}\n\n/**\n * Encodes a string to UTF-8 bytes\n */\nexport const encodeString = (value: string): Uint8Array => new TextEncoder().encode(value)\n\n/**\n * Encodes bytes as a hex string to Uint8Array\n */\nexport const encodeHexBytes = (hex: string): Uint8Array => {\n  const bytes = new Uint8Array(hex.length / 2)\n  for (let i = 0; i < hex.length; i += 2) {\n    bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16)\n  }\n  return bytes\n}\n\n/**\n * Concatenates multiple Uint8Arrays\n */\nexport const concat = (...arrays: Array<Uint8Array>): Uint8Array => {\n  const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0)\n  const result = new Uint8Array(totalLength)\n  let offset = 0\n  for (const arr of arrays) {\n    result.set(arr, offset)\n    offset += arr.length\n  }\n  return result\n}\n\n// Field encoders\n\n/**\n * Encodes a varint field\n */\nexport const varintField = (fieldNumber: number, value: number | bigint): Uint8Array =>\n  concat(\n    encodeVarint(encodeTag(fieldNumber, WireType.Varint)),\n    encodeVarint(value)\n  )\n\n/**\n * Encodes a sint field (ZigZag encoded)\n */\nexport const sintField = (fieldNumber: number, value: number | bigint): Uint8Array =>\n  concat(\n    encodeVarint(encodeTag(fieldNumber, WireType.Varint)),\n    encodeSint(value)\n  )\n\n/**\n * Encodes a bool field\n */\nexport const boolField = (fieldNumber: number, value: boolean): Uint8Array => varintField(fieldNumber, value ? 1 : 0)\n\n/**\n * Encodes a fixed64 field\n */\nexport const fixed64Field = (fieldNumber: number, value: bigint): Uint8Array =>\n  concat(\n    encodeVarint(encodeTag(fieldNumber, WireType.Fixed64)),\n    encodeFixed64(value)\n  )\n\n/**\n * Encodes a fixed32 field\n */\nexport const fixed32Field = (fieldNumber: number, value: number): Uint8Array =>\n  concat(\n    encodeVarint(encodeTag(fieldNumber, WireType.Fixed32)),\n    encodeFixed32(value)\n  )\n\n/**\n * Encodes a double field\n */\nexport const doubleField = (fieldNumber: number, value: number): Uint8Array =>\n  concat(\n    encodeVarint(encodeTag(fieldNumber, WireType.Fixed64)),\n    encodeDouble(value)\n  )\n\n/**\n * Encodes a length-delimited field (bytes, string, embedded message)\n */\nexport const lengthDelimitedField = (fieldNumber: number, value: Uint8Array): Uint8Array =>\n  concat(\n    encodeVarint(encodeTag(fieldNumber, WireType.LengthDelimited)),\n    encodeVarint(value.length),\n    value\n  )\n\n/**\n * Encodes a string field\n */\nexport const stringField = (fieldNumber: number, value: string): Uint8Array =>\n  lengthDelimitedField(fieldNumber, encodeString(value))\n\n/**\n * Encodes a bytes field from hex string\n */\nexport const bytesFieldFromHex = (fieldNumber: number, hex: string): Uint8Array =>\n  lengthDelimitedField(fieldNumber, encodeHexBytes(hex))\n\n/**\n * Encodes an embedded message field\n */\nexport const messageField = (fieldNumber: number, message: Uint8Array): Uint8Array =>\n  lengthDelimitedField(fieldNumber, message)\n\n/**\n * Encodes repeated fields\n */\nexport const repeatedField = <T>(\n  fieldNumber: number,\n  values: ReadonlyArray<T>,\n  encode: (value: T) => Uint8Array\n): Uint8Array => concat(...values.map((v) => messageField(fieldNumber, encode(v))))\n\n/**\n * Encodes repeated varint fields (not packed)\n */\nexport const repeatedVarintField = (\n  fieldNumber: number,\n  values: ReadonlyArray<number | bigint>\n): Uint8Array => concat(...values.map((v) => varintField(fieldNumber, v)))\n\n/**\n * Helper to conditionally encode an optional field\n */\nexport const optionalField = <T>(\n  value: T | undefined,\n  encode: (v: T) => Uint8Array\n): Uint8Array => value !== undefined ? encode(value) : new Uint8Array(0)\n\n/**\n * Helper to conditionally encode a string field if non-empty\n */\nexport const optionalStringField = (\n  fieldNumber: number,\n  value: string | undefined\n): Uint8Array => value !== undefined && value !== \"\" ? stringField(fieldNumber, value) : new Uint8Array(0)\n"
  },
  {
    "path": "packages/opentelemetry/src/internal/tracer.ts",
    "content": "import * as OtelApi from \"@opentelemetry/api\"\nimport * as OtelSemConv from \"@opentelemetry/semantic-conventions\"\nimport * as Cause from \"effect/Cause\"\nimport type * as Clock from \"effect/Clock\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { constTrue, dual } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as EffectTracer from \"effect/Tracer\"\nimport { Resource } from \"../Resource.js\"\nimport type { OtelTraceFlags, OtelTracer, OtelTracerProvider, OtelTraceState } from \"../Tracer.js\"\nimport { nanosToHrTime, recordToAttributes, unknownToAttributeValue } from \"./utils.js\"\n\nconst OtelSpanTypeId = Symbol.for(\"@effect/opentelemetry/Tracer/OtelSpan\")\n\nconst kindMap = {\n  \"internal\": OtelApi.SpanKind.INTERNAL,\n  \"client\": OtelApi.SpanKind.CLIENT,\n  \"server\": OtelApi.SpanKind.SERVER,\n  \"producer\": OtelApi.SpanKind.PRODUCER,\n  \"consumer\": OtelApi.SpanKind.CONSUMER\n}\n\nconst getOtelParent = (tracer: OtelApi.TraceAPI, otelContext: OtelApi.Context, context: Context.Context<never>) => {\n  const active = tracer.getSpan(otelContext)\n  const otelParent = active ? active.spanContext() : undefined\n  return otelParent\n    ? Option.some(\n      EffectTracer.externalSpan({\n        spanId: otelParent.spanId,\n        traceId: otelParent.traceId,\n        sampled: (otelParent.traceFlags & 1) === 1,\n        context\n      })\n    )\n    : Option.none()\n}\n\n/** @internal */\nexport class OtelSpan implements EffectTracer.Span {\n  readonly [OtelSpanTypeId]: typeof OtelSpanTypeId\n  readonly _tag = \"Span\"\n\n  readonly span: OtelApi.Span\n  readonly spanId: string\n  readonly traceId: string\n  readonly attributes = new Map<string, unknown>()\n  readonly sampled: boolean\n  readonly parent: Option.Option<EffectTracer.AnySpan>\n  status: EffectTracer.SpanStatus\n\n  constructor(\n    contextApi: OtelApi.ContextAPI,\n    traceApi: OtelApi.TraceAPI,\n    tracer: OtelApi.Tracer,\n    readonly name: string,\n    effectParent: Option.Option<EffectTracer.AnySpan>,\n    readonly context: Context.Context<never>,\n    readonly links: Array<EffectTracer.SpanLink>,\n    startTime: bigint,\n    readonly kind: EffectTracer.SpanKind,\n    options?: EffectTracer.SpanOptions\n  ) {\n    this[OtelSpanTypeId] = OtelSpanTypeId\n    const active = contextApi.active()\n    this.parent = effectParent._tag === \"Some\"\n      ? effectParent\n      : (options?.root !== true)\n      ? getOtelParent(traceApi, active, context)\n      : Option.none()\n    this.span = tracer.startSpan(\n      name,\n      {\n        startTime: nanosToHrTime(startTime),\n        links: links.length > 0\n          ? links.map((link) => ({\n            context: makeSpanContext(link.span),\n            attributes: recordToAttributes(link.attributes)\n          }))\n          : undefined as any,\n        kind: kindMap[this.kind]\n      },\n      this.parent._tag === \"Some\"\n        ? populateContext(active, this.parent.value, context)\n        : OtelApi.trace.deleteSpan(active)\n    )\n    const spanContext = this.span.spanContext()\n    this.spanId = spanContext.spanId\n    this.traceId = spanContext.traceId\n    this.status = {\n      _tag: \"Started\",\n      startTime\n    }\n    this.sampled = (spanContext.traceFlags & OtelApi.TraceFlags.SAMPLED) === OtelApi.TraceFlags.SAMPLED\n  }\n\n  attribute(key: string, value: unknown) {\n    this.span.setAttribute(key, unknownToAttributeValue(value))\n    this.attributes.set(key, value)\n  }\n\n  addLinks(links: ReadonlyArray<EffectTracer.SpanLink>): void {\n    // eslint-disable-next-line no-restricted-syntax\n    this.links.push(...links)\n    this.span.addLinks(links.map((link) => ({\n      context: makeSpanContext(link.span),\n      attributes: recordToAttributes(link.attributes)\n    })))\n  }\n\n  end(endTime: bigint, exit: Exit.Exit<unknown, unknown>) {\n    const hrTime = nanosToHrTime(endTime)\n    this.status = {\n      _tag: \"Ended\",\n      endTime,\n      exit,\n      startTime: this.status.startTime\n    }\n\n    if (exit._tag === \"Success\") {\n      this.span.setStatus({ code: OtelApi.SpanStatusCode.OK })\n    } else {\n      if (Cause.isInterruptedOnly(exit.cause)) {\n        this.span.setStatus({\n          code: OtelApi.SpanStatusCode.OK,\n          message: Cause.pretty(exit.cause)\n        })\n        this.span.setAttribute(\"span.label\", \"⚠︎ Interrupted\")\n        this.span.setAttribute(\"status.interrupted\", true)\n      } else {\n        const firstError = Cause.prettyErrors(exit.cause)[0]\n        if (firstError) {\n          firstError.stack = Cause.pretty(exit.cause, { renderErrorCause: true })\n          this.span.recordException(firstError, hrTime)\n          this.span.setStatus({\n            code: OtelApi.SpanStatusCode.ERROR,\n            message: firstError.message\n          })\n        } else {\n          // empty cause means no error\n          this.span.setStatus({ code: OtelApi.SpanStatusCode.OK })\n        }\n      }\n    }\n    this.span.end(hrTime)\n  }\n\n  event(name: string, startTime: bigint, attributes?: Record<string, unknown>) {\n    this.span.addEvent(\n      name,\n      attributes ? recordToAttributes(attributes) : undefined,\n      nanosToHrTime(startTime)\n    )\n  }\n}\n\n/** @internal */\nexport const TracerProvider = Context.GenericTag<OtelTracerProvider, OtelApi.TracerProvider>(\n  \"@effect/opentelemetry/Tracer/OtelTracerProvider\"\n)\n\n/** @internal */\nexport const Tracer = Context.GenericTag<OtelTracer, OtelApi.Tracer>(\"@effect/opentelemetry/Tracer/OtelTracer\")\n\n/** @internal */\nexport const make = Effect.map(Tracer, (tracer) =>\n  EffectTracer.make({\n    span(name, parent, context, links, startTime, kind, options) {\n      return new OtelSpan(\n        OtelApi.context,\n        OtelApi.trace,\n        tracer,\n        name,\n        parent,\n        context,\n        links.slice(),\n        startTime,\n        kind,\n        options\n      )\n    },\n    context(execution, fiber) {\n      const currentSpan = fiber.currentSpan\n\n      if (currentSpan === undefined) {\n        return execution()\n      }\n\n      return OtelApi.context.with(\n        populateContext(OtelApi.context.active(), currentSpan),\n        execution\n      )\n    }\n  }))\n\n/** @internal */\nexport const traceFlagsTag = Context.GenericTag<OtelTraceFlags, OtelApi.TraceFlags>(\n  \"@effect/opentelemetry/Tracer/OtelTraceFlags\"\n)\n\n/** @internal */\nexport const traceStateTag = Context.GenericTag<OtelTraceState, OtelApi.TraceState>(\n  \"@effect/opentelemetry/Tracer/OtelTraceState\"\n)\n\n/** @internal */\nexport const makeExternalSpan = (options: {\n  readonly traceId: string\n  readonly spanId: string\n  readonly traceFlags?: number | undefined\n  readonly traceState?: string | OtelApi.TraceState | undefined\n}): EffectTracer.ExternalSpan => {\n  let context = Context.empty()\n\n  if (options.traceFlags !== undefined) {\n    context = Context.add(context, traceFlagsTag, options.traceFlags)\n  }\n\n  if (typeof options.traceState === \"string\") {\n    context = Option.match(createTraceState(options.traceState), {\n      onNone: () => context,\n      onSome: (traceState) => Context.add(context, traceStateTag, traceState)\n    })\n  } else if (options.traceState) {\n    context = Context.add(context, traceStateTag, options.traceState)\n  }\n\n  return {\n    _tag: \"ExternalSpan\",\n    traceId: options.traceId,\n    spanId: options.spanId,\n    sampled: options.traceFlags !== undefined\n      ? (options.traceFlags & OtelApi.TraceFlags.SAMPLED) === OtelApi.TraceFlags.SAMPLED\n      : true,\n    context\n  }\n}\n\nconst makeOtelSpan = (span: EffectTracer.Span, clock: Clock.Clock): OtelApi.Span => {\n  const spanContext: OtelApi.SpanContext = {\n    traceId: span.traceId,\n    spanId: span.spanId,\n    traceFlags: span.sampled ? OtelApi.TraceFlags.SAMPLED : OtelApi.TraceFlags.NONE,\n    isRemote: false\n  }\n\n  let exit = Exit.void\n\n  const self: OtelApi.Span = {\n    spanContext: () => spanContext,\n    setAttribute(key, value) {\n      span.attribute(key, value)\n      return self\n    },\n    setAttributes(attributes) {\n      for (const [key, value] of Object.entries(attributes)) {\n        span.attribute(key, value)\n      }\n      return self\n    },\n    addEvent(name) {\n      let attributes: OtelApi.Attributes | undefined = undefined\n      let startTime: OtelApi.TimeInput | undefined = undefined\n      if (arguments.length === 3) {\n        attributes = arguments[1]\n        startTime = arguments[2]\n      } else if (arguments.length === 2) {\n        const arg1 = arguments[1]\n        if (isTimeInput(arg1)) {\n          startTime = arg1\n        } else {\n          attributes = arg1\n        }\n      }\n      span.event(name, convertOtelTimeInput(startTime, clock), attributes)\n      return self\n    },\n    addLink(link) {\n      span.addLinks([{\n        _tag: \"SpanLink\",\n        span: makeExternalSpan(link.context),\n        attributes: link.attributes ?? {}\n      }])\n      return self\n    },\n    addLinks(links) {\n      span.addLinks(links.map((link) => ({\n        _tag: \"SpanLink\",\n        span: makeExternalSpan(link.context),\n        attributes: link.attributes ?? {}\n      })))\n      return self\n    },\n    setStatus(status) {\n      exit = OtelApi.SpanStatusCode.ERROR\n        ? Exit.die(status.message ?? \"Unknown error\")\n        : Exit.void\n      return self\n    },\n    updateName: () => self,\n    end(endTime) {\n      const time = convertOtelTimeInput(endTime, clock)\n      span.end(time, exit)\n      return self\n    },\n    isRecording: constTrue,\n    recordException(exception, timeInput) {\n      const time = convertOtelTimeInput(timeInput, clock)\n      const cause = Cause.fail(exception)\n      const error = Cause.prettyErrors(cause)[0]\n      span.event(error.message, time, {\n        \"exception.type\": error.name,\n        \"exception.message\": error.message,\n        \"exception.stacktrace\": error.stack ?? \"\"\n      })\n    }\n  }\n  return self\n}\n\nconst bigint1e6 = BigInt(1_000_000)\nconst bigint1e9 = BigInt(1_000_000_000)\n\n/** Distinguishes TimeInput (number | Date | [number, number]) from Attributes (plain object) */\nconst isTimeInput = (u: unknown): u is OtelApi.TimeInput =>\n  typeof u === \"number\" ||\n  u instanceof Date ||\n  (Array.isArray(u) && u.length === 2 && typeof u[0] === \"number\" && typeof u[1] === \"number\")\n\nconst convertOtelTimeInput = (input: OtelApi.TimeInput | undefined, clock: Clock.Clock): bigint => {\n  if (input === undefined) {\n    return clock.unsafeCurrentTimeNanos()\n  } else if (typeof input === \"number\") {\n    return BigInt(Math.round(input * 1_000_000))\n  } else if (input instanceof Date) {\n    return BigInt(input.getTime()) * bigint1e6\n  }\n  const [seconds, nanos] = input\n  return BigInt(seconds) * bigint1e9 + BigInt(nanos)\n}\n\n/** @internal */\nexport const currentOtelSpan: Effect.Effect<OtelApi.Span, Cause.NoSuchElementException> = Effect.clockWith((clock) =>\n  Effect.map(Effect.currentSpan, (span): OtelApi.Span => {\n    if (OtelSpanTypeId in span) {\n      return (span as OtelSpan).span\n    }\n    return makeOtelSpan(span, clock)\n  })\n)\n\n/** @internal */\nexport const layerGlobalProvider = Layer.sync(\n  TracerProvider,\n  () => OtelApi.trace.getTracerProvider()\n)\n\n/** @internal */\nexport const layerTracer = Layer.effect(\n  Tracer,\n  Effect.flatMap(\n    Effect.zip(Resource, TracerProvider),\n    ([resource, provider]) =>\n      Effect.sync(() =>\n        provider.getTracer(\n          resource.attributes[OtelSemConv.ATTR_SERVICE_NAME] as string,\n          resource.attributes[OtelSemConv.ATTR_SERVICE_VERSION] as string\n        )\n      )\n  )\n)\n\n/** @internal */\nexport const layerGlobalTracer = layerTracer.pipe(\n  Layer.provide(layerGlobalProvider)\n)\n\n/** @internal */\nexport const layerGlobal = Layer.unwrapEffect(Effect.map(make, Layer.setTracer)).pipe(\n  Layer.provideMerge(layerGlobalTracer)\n)\n\n/** @internal */\nexport const layerWithoutOtelTracer = Layer.unwrapEffect(Effect.map(make, Layer.setTracer))\n\n/** @internal */\nexport const layer = layerWithoutOtelTracer.pipe(\n  Layer.provideMerge(layerTracer)\n)\n\n// -------------------------------------------------------------------------------------\n// utils\n// -------------------------------------------------------------------------------------\n\nconst createTraceState = Option.liftThrowable(OtelApi.createTraceState)\n\nconst populateContext = (\n  otelContext: OtelApi.Context,\n  span: EffectTracer.AnySpan,\n  context?: Context.Context<never>\n): OtelApi.Context =>\n  span instanceof OtelSpan ?\n    OtelApi.trace.setSpan(otelContext, span.span) :\n    OtelApi.trace.setSpanContext(otelContext, makeSpanContext(span, context))\n\nconst makeSpanContext = (span: EffectTracer.AnySpan, context?: Context.Context<never>): OtelApi.SpanContext => ({\n  spanId: span.spanId,\n  traceId: span.traceId,\n  isRemote: span._tag === \"ExternalSpan\",\n  traceFlags: Option.getOrElse(\n    context ?\n      extractTraceTag(span, context, traceFlagsTag) :\n      Context.getOption(span.context, traceFlagsTag),\n    () => OtelApi.TraceFlags.SAMPLED\n  ),\n  traceState: Option.getOrUndefined(\n    context ?\n      extractTraceTag(span, context, traceStateTag) :\n      Context.getOption(span.context, traceStateTag)\n  ) as OtelApi.TraceState\n})\n\nconst extractTraceTag = <I, S>(\n  parent: EffectTracer.AnySpan,\n  context: Context.Context<never>,\n  tag: Context.Tag<I, S>\n) =>\n  Option.orElse(\n    Context.getOption(context, tag),\n    () => Context.getOption(parent.context, tag)\n  )\n\n/** @internal */\nexport const withSpanContext = dual<\n  (\n    spanContext: OtelApi.SpanContext\n  ) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, EffectTracer.ParentSpan>>,\n  <A, E, R>(\n    effect: Effect.Effect<A, E, R>,\n    spanContext: OtelApi.SpanContext\n  ) => Effect.Effect<A, E, Exclude<R, EffectTracer.ParentSpan>>\n>(2, <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n  spanContext: OtelApi.SpanContext\n): Effect.Effect<A, E, Exclude<R, EffectTracer.ParentSpan>> =>\n  Effect.withParentSpan(effect, makeExternalSpan(spanContext)))\n"
  },
  {
    "path": "packages/opentelemetry/src/internal/utils.ts",
    "content": "import type * as OtelApi from \"@opentelemetry/api\"\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport * as Inspectable from \"effect/Inspectable\"\n\nconst bigint1e9 = 1_000_000_000n\n\n/** @internal */\nexport const nanosToHrTime = (timestamp: bigint): OtelApi.HrTime => {\n  return [Number(timestamp / bigint1e9), Number(timestamp % bigint1e9)]\n}\n\n/** @internal */\nexport const recordToAttributes = (value: Record<string, unknown>): OtelApi.Attributes =>\n  Object.entries(value).reduce((acc, [key, value]) => {\n    acc[key] = unknownToAttributeValue(value)\n    return acc\n  }, {} as OtelApi.Attributes)\n\n/** @internal */\nexport const unknownToAttributeValue = (value: unknown): OtelApi.AttributeValue => {\n  if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n    return value\n  } else if (typeof value === \"bigint\") {\n    return value.toString()\n  }\n  return Inspectable.toStringUnknown(value)\n}\n\n/** @internal */\nexport const isNonEmpty = <A>(a: A | ReadonlyArray<A> | undefined): a is A | NonEmptyReadonlyArray<A> =>\n  a !== undefined && !(Array.isArray(a) && a.length === 0)\n"
  },
  {
    "path": "packages/opentelemetry/test/Logger.test.ts",
    "content": "import * as NodeSdk from \"@effect/opentelemetry/NodeSdk\"\nimport * as it from \"@effect/vitest\"\nimport { InMemoryLogRecordExporter, SimpleLogRecordProcessor } from \"@opentelemetry/sdk-logs\"\nimport * as Effect from \"effect/Effect\"\nimport { describe, expect } from \"vitest\"\n\ndescribe(\"Logger\", () => {\n  describe(\"provided\", () => {\n    const exporter = new InMemoryLogRecordExporter()\n\n    const TracingLive = NodeSdk.layer(Effect.sync(() => ({\n      resource: {\n        serviceName: \"test\"\n      },\n      logRecordProcessor: [new SimpleLogRecordProcessor(exporter)]\n    })))\n\n    it.effect(\"emits log records\", () =>\n      Effect.provide(\n        Effect.gen(function*() {\n          yield* Effect.log(\"test\").pipe(\n            Effect.repeatN(9)\n          )\n\n          expect(exporter.getFinishedLogRecords()).toHaveLength(10)\n        }),\n        TracingLive\n      ))\n  })\n\n  describe(\"not provided\", () => {\n    const exporter = new InMemoryLogRecordExporter()\n\n    const TracingLive = NodeSdk.layer(Effect.sync(() => ({\n      resource: {\n        serviceName: \"test\"\n      }\n    })))\n\n    it.effect(\"withSpan\", () =>\n      Effect.provide(\n        Effect.gen(function*() {\n          yield* Effect.log(\"test\")\n\n          expect(exporter.getFinishedLogRecords()).toHaveLength(0)\n        }),\n        TracingLive\n      ))\n  })\n})\n"
  },
  {
    "path": "packages/opentelemetry/test/Metrics.test.ts",
    "content": "import { assert, describe, it } from \"@effect/vitest\"\nimport { ValueType } from \"@opentelemetry/api\"\nimport { resourceFromAttributes } from \"@opentelemetry/resources\"\nimport * as Effect from \"effect/Effect\"\nimport * as Metric from \"effect/Metric\"\nimport * as internal from \"../src/internal/metrics.js\"\n\nconst findMetric = (metrics: any, name: string) =>\n  metrics.resourceMetrics.scopeMetrics[0].metrics.find((_: any) => _.descriptor.name === name)\n\ndescribe(\"Metrics\", () => {\n  it.effect(\"gauge\", () =>\n    Effect.gen(function*() {\n      const resource = resourceFromAttributes({\n        name: \"test\",\n        version: \"1.0.0\"\n      })\n      const producer = new internal.MetricProducerImpl(resource)\n      const gauge = Metric.gauge(\"rps\")\n\n      yield* Metric.set(gauge, 10).pipe(Effect.tagMetrics(\"key\", \"value\"), Effect.tagMetrics(\"unit\", \"requests\"))\n      yield* Metric.set(gauge, 10).pipe(Effect.tagMetrics(\"key\", \"value\"))\n      yield* Metric.set(gauge, 20).pipe(Effect.tagMetrics(\"key\", \"value\"))\n\n      const results = yield* Effect.promise(() => producer.collect())\n      const object = JSON.parse(JSON.stringify(results))\n      assert.deepEqual(object.resourceMetrics.resource._rawAttributes, [\n        [\"name\", \"test\"],\n        [\"version\", \"1.0.0\"]\n      ])\n      assert.equal(object.resourceMetrics.scopeMetrics.length, 1)\n      const metric = findMetric(object, \"rps\")\n      assert.deepEqual(metric, {\n        \"dataPointType\": 2,\n        \"descriptor\": {\n          \"advice\": {},\n          \"name\": \"rps\",\n          \"description\": \"\",\n          \"unit\": \"requests\",\n          \"type\": \"OBSERVABLE_GAUGE\",\n          \"valueType\": ValueType.DOUBLE\n        },\n        \"aggregationTemporality\": 1,\n        \"dataPoints\": [\n          {\n            \"startTime\": metric.dataPoints[0].startTime,\n            \"endTime\": metric.dataPoints[0].endTime,\n            \"attributes\": {\n              \"unit\": \"requests\",\n              \"key\": \"value\"\n            },\n            \"value\": 10\n          },\n          {\n            \"startTime\": metric.dataPoints[0].startTime,\n            \"endTime\": metric.dataPoints[0].endTime,\n            \"attributes\": {\n              \"key\": \"value\"\n            },\n            \"value\": 20\n          }\n        ]\n      })\n    }))\n\n  it.effect(\"gauge bigint\", () =>\n    Effect.gen(function*() {\n      const producer = new internal.MetricProducerImpl(\n        resourceFromAttributes({\n          name: \"test\",\n          version: \"1.0.0\"\n        })\n      )\n      const gauge = Metric.gauge(\"rps-bigint\", { bigint: true })\n\n      yield* Metric.set(gauge, 10n).pipe(Effect.tagMetrics(\"key\", \"value\"), Effect.tagMetrics(\"unit\", \"requests\"))\n      yield* Metric.set(gauge, 10n).pipe(Effect.tagMetrics(\"key\", \"value\"))\n      yield* Metric.set(gauge, 20n).pipe(Effect.tagMetrics(\"key\", \"value\"))\n\n      const results = yield* Effect.promise(() => producer.collect())\n      const object = JSON.parse(JSON.stringify(results))\n      assert.deepEqual(object.resourceMetrics.resource._rawAttributes, [\n        [\"name\", \"test\"],\n        [\"version\", \"1.0.0\"]\n      ])\n      assert.equal(object.resourceMetrics.scopeMetrics.length, 1)\n      const metric = findMetric(object, \"rps-bigint\")\n      assert.deepEqual(metric, {\n        \"dataPointType\": 2,\n        \"descriptor\": {\n          \"advice\": {},\n          \"name\": \"rps-bigint\",\n          \"description\": \"\",\n          \"unit\": \"requests\",\n          \"type\": \"OBSERVABLE_GAUGE\",\n          \"valueType\": ValueType.INT\n        },\n        \"aggregationTemporality\": 1,\n        \"dataPoints\": [\n          {\n            \"startTime\": metric.dataPoints[0].startTime,\n            \"endTime\": metric.dataPoints[0].endTime,\n            \"attributes\": {\n              \"unit\": \"requests\",\n              \"key\": \"value\"\n            },\n            \"value\": 10\n          },\n          {\n            \"startTime\": metric.dataPoints[0].startTime,\n            \"endTime\": metric.dataPoints[0].endTime,\n            \"attributes\": {\n              \"key\": \"value\"\n            },\n            \"value\": 20\n          }\n        ]\n      })\n    }))\n\n  it.effect(\"counter\", () =>\n    Effect.gen(function*() {\n      const producer = new internal.MetricProducerImpl(\n        resourceFromAttributes({\n          name: \"test\",\n          version: \"1.0.0\"\n        })\n      )\n      const counter = Metric.counter(\"counter\", { description: \"Example\" })\n\n      yield* Metric.increment(counter).pipe(Effect.tagMetrics(\"key\", \"value\"), Effect.tagMetrics(\"unit\", \"requests\"))\n      yield* Metric.increment(counter).pipe(Effect.tagMetrics(\"key\", \"value\"))\n      yield* Metric.increment(counter).pipe(Effect.tagMetrics(\"key\", \"value\"))\n\n      const results = yield* Effect.promise(() => producer.collect())\n      const object = JSON.parse(JSON.stringify(results))\n      assert.deepEqual(object.resourceMetrics.resource._rawAttributes, [\n        [\"name\", \"test\"],\n        [\"version\", \"1.0.0\"]\n      ])\n      assert.equal(object.resourceMetrics.scopeMetrics.length, 1)\n      const metric = findMetric(object, \"counter\")\n      assert.deepEqual(metric, {\n        \"dataPointType\": 3,\n        \"descriptor\": {\n          \"advice\": {},\n          \"name\": \"counter\",\n          \"description\": \"Example\",\n          \"unit\": \"requests\",\n          \"type\": \"UP_DOWN_COUNTER\",\n          \"valueType\": ValueType.DOUBLE\n        },\n        \"isMonotonic\": false,\n        \"aggregationTemporality\": 1,\n        \"dataPoints\": [\n          {\n            \"startTime\": metric.dataPoints[0].startTime,\n            \"endTime\": metric.dataPoints[0].endTime,\n            \"attributes\": {\n              \"unit\": \"requests\",\n              \"key\": \"value\"\n            },\n            \"value\": 1\n          },\n          {\n            \"startTime\": metric.dataPoints[0].startTime,\n            \"endTime\": metric.dataPoints[0].endTime,\n            \"attributes\": {\n              \"key\": \"value\"\n            },\n            \"value\": 2\n          }\n        ]\n      })\n    }))\n\n  it.effect(\"counter-inc\", () =>\n    Effect.gen(function*() {\n      const producer = new internal.MetricProducerImpl(\n        resourceFromAttributes({\n          name: \"test\",\n          version: \"1.0.0\"\n        })\n      )\n      const counter = Metric.counter(\"counter-inc\", {\n        description: \"Example\",\n        incremental: true\n      })\n\n      yield* Metric.increment(counter).pipe(Effect.tagMetrics(\"key\", \"value\"), Effect.tagMetrics(\"unit\", \"requests\"))\n      yield* Metric.increment(counter).pipe(Effect.tagMetrics(\"key\", \"value\"))\n      yield* Metric.increment(counter).pipe(Effect.tagMetrics(\"key\", \"value\"))\n\n      const results = yield* Effect.promise(() => producer.collect())\n      const object = JSON.parse(JSON.stringify(results))\n      assert.deepEqual(object.resourceMetrics.resource._rawAttributes, [\n        [\"name\", \"test\"],\n        [\"version\", \"1.0.0\"]\n      ])\n      assert.equal(object.resourceMetrics.scopeMetrics.length, 1)\n      const metric = findMetric(object, \"counter-inc\")\n      assert.deepEqual(metric, {\n        \"dataPointType\": 3,\n        \"descriptor\": {\n          \"advice\": {},\n          \"name\": \"counter-inc\",\n          \"description\": \"Example\",\n          \"unit\": \"requests\",\n          \"type\": \"COUNTER\",\n          \"valueType\": ValueType.DOUBLE\n        },\n        \"isMonotonic\": true,\n        \"aggregationTemporality\": 1,\n        \"dataPoints\": [\n          {\n            \"startTime\": metric.dataPoints[0].startTime,\n            \"endTime\": metric.dataPoints[0].endTime,\n            \"attributes\": {\n              \"unit\": \"requests\",\n              \"key\": \"value\"\n            },\n            \"value\": 1\n          },\n          {\n            \"startTime\": metric.dataPoints[0].startTime,\n            \"endTime\": metric.dataPoints[0].endTime,\n            \"attributes\": {\n              \"key\": \"value\"\n            },\n            \"value\": 2\n          }\n        ]\n      })\n    }))\n\n  it.effect(\"counter-bigint\", () =>\n    Effect.gen(function*() {\n      const producer = new internal.MetricProducerImpl(\n        resourceFromAttributes({\n          name: \"test\",\n          version: \"1.0.0\"\n        })\n      )\n      const counter = Metric.counter(\"counter-bigint\", {\n        description: \"Example\",\n        incremental: true,\n        bigint: true\n      })\n\n      yield* Metric.increment(counter).pipe(Effect.tagMetrics(\"key\", \"value\"), Effect.tagMetrics(\"unit\", \"requests\"))\n      yield* Metric.increment(counter).pipe(Effect.tagMetrics(\"key\", \"value\"))\n      yield* Metric.increment(counter).pipe(Effect.tagMetrics(\"key\", \"value\"))\n\n      const results = yield* Effect.promise(() => producer.collect())\n      const object = JSON.parse(JSON.stringify(results))\n      assert.deepEqual(object.resourceMetrics.resource._rawAttributes, [\n        [\"name\", \"test\"],\n        [\"version\", \"1.0.0\"]\n      ])\n      assert.equal(object.resourceMetrics.scopeMetrics.length, 1)\n      const metric = findMetric(object, \"counter-bigint\")\n      assert.deepEqual(metric, {\n        \"dataPointType\": 3,\n        \"descriptor\": {\n          \"advice\": {},\n          \"name\": \"counter-bigint\",\n          \"description\": \"Example\",\n          \"unit\": \"requests\",\n          \"type\": \"COUNTER\",\n          \"valueType\": ValueType.INT\n        },\n        \"isMonotonic\": true,\n        \"aggregationTemporality\": 1,\n        \"dataPoints\": [\n          {\n            \"startTime\": metric.dataPoints[0].startTime,\n            \"endTime\": metric.dataPoints[0].endTime,\n            \"attributes\": {\n              \"unit\": \"requests\",\n              \"key\": \"value\"\n            },\n            \"value\": 1\n          },\n          {\n            \"startTime\": metric.dataPoints[0].startTime,\n            \"endTime\": metric.dataPoints[0].endTime,\n            \"attributes\": {\n              \"key\": \"value\"\n            },\n            \"value\": 2\n          }\n        ]\n      })\n    }))\n})\n"
  },
  {
    "path": "packages/opentelemetry/test/OtlpSerialization.test.ts",
    "content": "import { assert, describe, expect, it } from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport * as OtlpSerialization from \"../src/OtlpSerialization.js\"\n\ndescribe(\"OtlpSerialization override behavior\", () => {\n  it.effect(\"json roundtrip\", () =>\n    Effect.gen(function*() {\n      const serialization = yield* OtlpSerialization.OtlpSerialization\n      const body = serialization.traces({ test: \"data\" })\n      assert(body._tag === \"Uint8Array\")\n      expect(body.contentType).toBe(\"application/json\")\n      const result = JSON.parse(new TextDecoder().decode(body.body))\n      expect(result).toEqual({ test: \"data\" })\n    }).pipe(Effect.provide(OtlpSerialization.layerJson)))\n\n  it.effect(\"protobuf layer provides protobuf HttpBody\", () =>\n    Effect.gen(function*() {\n      const serialization = yield* OtlpSerialization.OtlpSerialization\n      const body = serialization.traces({ resourceSpans: [] })\n      expect(body.contentType).toBe(\"application/x-protobuf\")\n    }).pipe(Effect.provide(OtlpSerialization.layerProtobuf)))\n})\n"
  },
  {
    "path": "packages/opentelemetry/test/Protobuf.test.ts",
    "content": "import { describe, expect, it } from \"@effect/vitest\"\nimport * as Effect from \"effect/Effect\"\nimport * as OtlpProtobuf from \"../src/internal/otlpProtobuf.js\"\nimport * as Proto from \"../src/internal/protobuf.js\"\nimport * as OtlpSerialization from \"../src/OtlpSerialization.js\"\n\ndescribe(\"Protobuf encoding\", () => {\n  describe(\"primitives\", () => {\n    it(\"encodeVarint small values\", () => {\n      // 0 encodes to [0]\n      expect(Proto.encodeVarint(0)).toEqual(new Uint8Array([0]))\n      // 1 encodes to [1]\n      expect(Proto.encodeVarint(1)).toEqual(new Uint8Array([1]))\n      // 127 encodes to [127] (single byte max)\n      expect(Proto.encodeVarint(127)).toEqual(new Uint8Array([127]))\n      // 128 encodes to [128, 1] (requires continuation bit)\n      expect(Proto.encodeVarint(128)).toEqual(new Uint8Array([128, 1]))\n      // 300 encodes to [172, 2]\n      expect(Proto.encodeVarint(300)).toEqual(new Uint8Array([172, 2]))\n    })\n\n    it(\"encodeVarint large values\", () => {\n      // 16384 = 0x4000 encodes to [128, 128, 1]\n      expect(Proto.encodeVarint(16384)).toEqual(new Uint8Array([128, 128, 1]))\n    })\n\n    it(\"encodeFixed64\", () => {\n      const result = Proto.encodeFixed64(BigInt(\"1234567890123456789\"))\n      expect(result.length).toBe(8)\n      // Little-endian encoding\n      const view = new DataView(result.buffer)\n      expect(view.getBigUint64(0, true)).toBe(BigInt(\"1234567890123456789\"))\n    })\n\n    it(\"encodeFixed32\", () => {\n      const result = Proto.encodeFixed32(0x12345678)\n      expect(result.length).toBe(4)\n      const view = new DataView(result.buffer)\n      expect(view.getUint32(0, true)).toBe(0x12345678)\n    })\n\n    it(\"encodeDouble\", () => {\n      const result = Proto.encodeDouble(3.14159)\n      expect(result.length).toBe(8)\n      const view = new DataView(result.buffer)\n      expect(view.getFloat64(0, true)).toBeCloseTo(3.14159)\n    })\n\n    it(\"encodeString\", () => {\n      const result = Proto.encodeString(\"hello\")\n      expect(result).toEqual(new Uint8Array([104, 101, 108, 108, 111]))\n    })\n\n    it(\"encodeHexBytes\", () => {\n      const result = Proto.encodeHexBytes(\"deadbeef\")\n      expect(result).toEqual(new Uint8Array([0xde, 0xad, 0xbe, 0xef]))\n    })\n\n    it(\"concat\", () => {\n      const a = new Uint8Array([1, 2, 3])\n      const b = new Uint8Array([4, 5])\n      const c = new Uint8Array([6])\n      const result = Proto.concat(a, b, c)\n      expect(result).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6]))\n    })\n  })\n\n  describe(\"field encoders\", () => {\n    it(\"varintField\", () => {\n      // field 1, value 150\n      // tag = (1 << 3) | 0 = 8\n      // value = 150 = [150, 1] (as varint)\n      const result = Proto.varintField(1, 150)\n      expect(result).toEqual(new Uint8Array([8, 150, 1]))\n    })\n\n    it(\"boolField\", () => {\n      // field 2, true\n      // tag = (2 << 3) | 0 = 16\n      const trueResult = Proto.boolField(2, true)\n      expect(trueResult).toEqual(new Uint8Array([16, 1]))\n\n      const falseResult = Proto.boolField(2, false)\n      expect(falseResult).toEqual(new Uint8Array([16, 0]))\n    })\n\n    it(\"stringField\", () => {\n      // field 1, value \"hi\"\n      // tag = (1 << 3) | 2 = 10 (length-delimited)\n      // length = 2\n      // data = [104, 105]\n      const result = Proto.stringField(1, \"hi\")\n      expect(result).toEqual(new Uint8Array([10, 2, 104, 105]))\n    })\n\n    it(\"fixed64Field\", () => {\n      // field 1, wire type 1 (64-bit)\n      // tag = (1 << 3) | 1 = 9\n      const result = Proto.fixed64Field(1, BigInt(1))\n      expect(result[0]).toBe(9)\n      expect(result.length).toBe(9) // 1 tag + 8 data\n    })\n\n    it(\"messageField\", () => {\n      // field 2, embedded message [1, 2, 3]\n      // tag = (2 << 3) | 2 = 18 (length-delimited)\n      // length = 3\n      const result = Proto.messageField(2, new Uint8Array([1, 2, 3]))\n      expect(result).toEqual(new Uint8Array([18, 3, 1, 2, 3]))\n    })\n  })\n\n  describe(\"OTLP types\", () => {\n    it(\"encodeAnyValue - string\", () => {\n      const result = OtlpProtobuf.encodeAnyValue({ stringValue: \"test\" })\n      // field 1 (string_value), length-delimited\n      // tag = (1 << 3) | 2 = 10\n      expect(result[0]).toBe(10)\n      expect(result[1]).toBe(4) // length\n    })\n\n    it(\"encodeAnyValue - bool\", () => {\n      const result = OtlpProtobuf.encodeAnyValue({ boolValue: true })\n      // field 2 (bool_value), varint\n      // tag = (2 << 3) | 0 = 16\n      expect(result).toEqual(new Uint8Array([16, 1]))\n    })\n\n    it(\"encodeAnyValue - int\", () => {\n      const result = OtlpProtobuf.encodeAnyValue({ intValue: 42 })\n      // field 3 (int_value), varint\n      // tag = (3 << 3) | 0 = 24\n      expect(result[0]).toBe(24)\n    })\n\n    it(\"encodeAnyValue - double\", () => {\n      const result = OtlpProtobuf.encodeAnyValue({ doubleValue: 3.14 })\n      // field 4 (double_value), 64-bit\n      // tag = (4 << 3) | 1 = 33\n      expect(result[0]).toBe(33)\n      expect(result.length).toBe(9) // 1 tag + 8 data\n    })\n\n    it(\"encodeKeyValue\", () => {\n      const result = OtlpProtobuf.encodeKeyValue({\n        key: \"test\",\n        value: { stringValue: \"value\" }\n      })\n      // Should contain field 1 (key) and field 2 (value)\n      expect(result.length).toBeGreaterThan(0)\n      // First byte should be tag for field 1 string\n      expect(result[0]).toBe(10) // (1 << 3) | 2 = 10\n    })\n\n    it(\"encodeResource\", () => {\n      const result = OtlpProtobuf.encodeResource({\n        attributes: [\n          { key: \"service.name\", value: { stringValue: \"test-service\" } }\n        ],\n        droppedAttributesCount: 0\n      })\n      // Should encode attributes as repeated field 1\n      expect(result.length).toBeGreaterThan(0)\n    })\n\n    it(\"encodeStatus\", () => {\n      const okStatus = OtlpProtobuf.encodeStatus({ code: OtlpProtobuf.StatusCode.Ok })\n      expect(okStatus.length).toBeGreaterThan(0)\n\n      const errorStatus = OtlpProtobuf.encodeStatus({\n        code: OtlpProtobuf.StatusCode.Error,\n        message: \"test error\"\n      })\n      expect(errorStatus.length).toBeGreaterThan(okStatus.length)\n    })\n\n    it(\"encodeSpan\", () => {\n      const result = OtlpProtobuf.encodeSpan({\n        traceId: \"0123456789abcdef0123456789abcdef\",\n        spanId: \"0123456789abcdef\",\n        name: \"test-span\",\n        kind: OtlpProtobuf.SpanKind.Internal,\n        startTimeUnixNano: \"1000000000\",\n        endTimeUnixNano: \"2000000000\",\n        attributes: [\n          { key: \"test.attr\", value: { stringValue: \"value\" } }\n        ],\n        droppedAttributesCount: 0,\n        events: [],\n        droppedEventsCount: 0,\n        links: [],\n        droppedLinksCount: 0,\n        status: { code: OtlpProtobuf.StatusCode.Ok }\n      })\n      expect(result.length).toBeGreaterThan(0)\n      // Should be a valid protobuf message\n      // Verify it starts with field 1 (trace_id) bytes\n      expect(result[0]).toBe(10) // (1 << 3) | 2 = 10 (length-delimited)\n    })\n\n    it(\"encodeTracesData\", () => {\n      const result = OtlpProtobuf.encodeTracesData({\n        resourceSpans: [{\n          resource: {\n            attributes: [\n              { key: \"service.name\", value: { stringValue: \"test\" } }\n            ],\n            droppedAttributesCount: 0\n          },\n          scopeSpans: [{\n            scope: { name: \"test-scope\" },\n            spans: [{\n              traceId: \"0123456789abcdef0123456789abcdef\",\n              spanId: \"0123456789abcdef\",\n              name: \"test-span\",\n              kind: OtlpProtobuf.SpanKind.Server,\n              startTimeUnixNano: \"1000000000000000000\",\n              endTimeUnixNano: \"2000000000000000000\",\n              attributes: [],\n              droppedAttributesCount: 0,\n              events: [],\n              droppedEventsCount: 0,\n              links: [],\n              droppedLinksCount: 0,\n              status: { code: OtlpProtobuf.StatusCode.Ok }\n            }]\n          }]\n        }]\n      })\n      expect(result.length).toBeGreaterThan(0)\n    })\n\n    it(\"encodeMetricsData\", () => {\n      const result = OtlpProtobuf.encodeMetricsData({\n        resourceMetrics: [{\n          resource: {\n            attributes: [\n              { key: \"service.name\", value: { stringValue: \"test\" } }\n            ],\n            droppedAttributesCount: 0\n          },\n          scopeMetrics: [{\n            scope: { name: \"test-scope\" },\n            metrics: [{\n              name: \"test.counter\",\n              description: \"A test counter\",\n              unit: \"1\",\n              sum: {\n                dataPoints: [{\n                  attributes: [],\n                  startTimeUnixNano: \"1000000000000000000\",\n                  timeUnixNano: \"2000000000000000000\",\n                  asInt: \"42\"\n                }],\n                aggregationTemporality: OtlpProtobuf.AggregationTemporality.Cumulative,\n                isMonotonic: true\n              }\n            }]\n          }]\n        }]\n      })\n      expect(result.length).toBeGreaterThan(0)\n    })\n\n    it(\"encodeLogsData\", () => {\n      const result = OtlpProtobuf.encodeLogsData({\n        resourceLogs: [{\n          resource: {\n            attributes: [\n              { key: \"service.name\", value: { stringValue: \"test\" } }\n            ],\n            droppedAttributesCount: 0\n          },\n          scopeLogs: [{\n            scope: { name: \"test-scope\" },\n            logRecords: [{\n              timeUnixNano: \"1000000000000000000\",\n              severityNumber: OtlpProtobuf.SeverityNumber.Info,\n              severityText: \"INFO\",\n              body: { stringValue: \"Test log message\" },\n              attributes: [\n                { key: \"log.key\", value: { stringValue: \"log.value\" } }\n              ],\n              droppedAttributesCount: 0\n            }]\n          }]\n        }]\n      })\n      expect(result.length).toBeGreaterThan(0)\n    })\n  })\n\n  describe(\"edge cases\", () => {\n    it(\"handles empty arrays\", () => {\n      const result = OtlpProtobuf.encodeTracesData({\n        resourceSpans: []\n      })\n      // Empty repeated field should produce empty output\n      expect(result.length).toBe(0)\n    })\n\n    it(\"handles optional fields\", () => {\n      const result = OtlpProtobuf.encodeSpan({\n        traceId: \"0123456789abcdef0123456789abcdef\",\n        spanId: \"0123456789abcdef\",\n        name: \"test\",\n        kind: OtlpProtobuf.SpanKind.Internal,\n        startTimeUnixNano: \"0\",\n        endTimeUnixNano: \"0\",\n        attributes: [],\n        droppedAttributesCount: 0,\n        events: [],\n        droppedEventsCount: 0,\n        links: [],\n        droppedLinksCount: 0,\n        status: { code: OtlpProtobuf.StatusCode.Unset }\n      })\n      expect(result.length).toBeGreaterThan(0)\n    })\n\n    it(\"handles special characters in strings\", () => {\n      const result = OtlpProtobuf.encodeAnyValue({\n        stringValue: \"hello\\nworld\\t\\r\\n\"\n      })\n      expect(result.length).toBeGreaterThan(0)\n    })\n\n    it(\"handles unicode strings\", () => {\n      const result = OtlpProtobuf.encodeAnyValue({\n        stringValue: \"hello\"\n      })\n      expect(result.length).toBeGreaterThan(0)\n    })\n\n    it(\"handles large numbers\", () => {\n      const result = Proto.encodeVarint(BigInt(\"9223372036854775807\"))\n      expect(result.length).toBe(9) // Max varint size for 64-bit\n    })\n  })\n\n  describe(\"OtlpSerialization\", () => {\n    const sampleTracesData = {\n      resourceSpans: [{\n        resource: {\n          attributes: [{ key: \"service.name\", value: { stringValue: \"test\" } }],\n          droppedAttributesCount: 0\n        },\n        scopeSpans: [{\n          scope: { name: \"test-scope\" },\n          spans: [{\n            traceId: \"0123456789abcdef0123456789abcdef\",\n            spanId: \"0123456789abcdef\",\n            name: \"test-span\",\n            kind: 1,\n            startTimeUnixNano: \"1000000000000000000\",\n            endTimeUnixNano: \"2000000000000000000\",\n            attributes: [],\n            droppedAttributesCount: 0,\n            events: [],\n            droppedEventsCount: 0,\n            links: [],\n            droppedLinksCount: 0,\n            status: { code: 1 }\n          }]\n        }]\n      }]\n    }\n\n    it.effect(\"json serializer returns HttpBody with json content type\", () =>\n      Effect.gen(function*() {\n        const serialization = yield* OtlpSerialization.OtlpSerialization\n        const body = serialization.traces(sampleTracesData)\n        expect(body.contentType).toBe(\"application/json\")\n      }).pipe(Effect.provide(OtlpSerialization.layerJson)))\n\n    it.effect(\"protobuf serializer returns HttpBody with protobuf content type\", () =>\n      Effect.gen(function*() {\n        const serialization = yield* OtlpSerialization.OtlpSerialization\n        const body = serialization.traces(sampleTracesData)\n        expect(body.contentType).toBe(\"application/x-protobuf\")\n      }).pipe(Effect.provide(OtlpSerialization.layerProtobuf)))\n  })\n})\n"
  },
  {
    "path": "packages/opentelemetry/test/Tracer.test.ts",
    "content": "import * as NodeSdk from \"@effect/opentelemetry/NodeSdk\"\nimport * as OtlpSerialization from \"@effect/opentelemetry/OtlpSerialization\"\nimport * as OtlpTracer from \"@effect/opentelemetry/OtlpTracer\"\nimport * as Tracer from \"@effect/opentelemetry/Tracer\"\nimport { HttpClient } from \"@effect/platform\"\nimport { assert, describe, expect, it } from \"@effect/vitest\"\nimport * as OtelApi from \"@opentelemetry/api\"\nimport { AsyncHooksContextManager } from \"@opentelemetry/context-async-hooks\"\nimport { InMemorySpanExporter, SimpleSpanProcessor } from \"@opentelemetry/sdk-trace-base\"\nimport * as Console from \"effect/Console\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport * as Layer from \"effect/Layer\"\nimport * as Runtime from \"effect/Runtime\"\nimport { OtelSpan } from \"../src/internal/tracer.js\"\n\nclass Exporter extends Effect.Service<Exporter>()(\"Exporter\", {\n  effect: Effect.sync(() => ({ exporter: new InMemorySpanExporter() }))\n}) {}\n\nconst TracingLive = Layer.unwrapEffect(Effect.gen(function*() {\n  const { exporter } = yield* Exporter\n\n  return NodeSdk.layer(Effect.sync(() => ({\n    resource: {\n      serviceName: \"test\"\n    },\n    spanProcessor: [new SimpleSpanProcessor(exporter)]\n  })))\n})).pipe(Layer.provideMerge(Exporter.Default))\n\n// needed to test context propagation\nconst contextManager = new AsyncHooksContextManager()\nOtelApi.context.setGlobalContextManager(contextManager)\n\ndescribe(\"Tracer\", () => {\n  describe(\"provided\", () => {\n    it.effect(\"withSpan\", () =>\n      Effect.provide(\n        Effect.withSpan(\"ok\")(\n          Effect.gen(function*() {\n            const span = yield* Effect.currentSpan\n            expect(span).instanceOf(OtelSpan)\n          })\n        ),\n        TracingLive\n      ))\n\n    it.effect(\"withSpan links\", () =>\n      Effect.gen(function*() {\n        const linkedSpan = yield* Effect.makeSpanScoped(\"B\")\n        const span = yield* Effect.currentSpan.pipe(\n          Effect.withSpan(\"A\"),\n          Effect.linkSpans(linkedSpan)\n        )\n        assert(span instanceof OtelSpan)\n        expect(span.links.length).toBe(1)\n      }).pipe(\n        Effect.scoped,\n        Effect.provide(TracingLive)\n      ))\n\n    it.effect(\"supervisor sets context\", () =>\n      Effect.provide(\n        Effect.withSpan(\"ok\")(\n          Effect.sync(() => {\n            expect(OtelApi.trace.getSpan(OtelApi.context.active())).toBeDefined()\n          })\n        ),\n        TracingLive\n      ))\n\n    it.effect(\"supervisor sets context generator\", () =>\n      Effect.gen(function*() {\n        yield* Effect.yieldNow()\n        expect(OtelApi.trace.getSpan(OtelApi.context.active())).toBeDefined()\n      }).pipe(\n        Effect.withSpan(\"ok\"),\n        Effect.provide(TracingLive)\n      ))\n\n    it.effect(\"currentOtelSpan\", () =>\n      Effect.provide(\n        Effect.withSpan(\"ok\")(\n          Effect.gen(function*() {\n            const span = yield* Effect.currentSpan\n            const otelSpan = yield* Tracer.currentOtelSpan\n            expect((span as OtelSpan).span).toBe(otelSpan)\n          })\n        ),\n        TracingLive\n      ))\n\n    it.scoped(\"withSpanContext\", () =>\n      Effect.gen(function*() {\n        const effect = Effect.gen(function*() {\n          const span = yield* Effect.currentParentSpan\n          assert(span._tag === \"Span\")\n          const parent = yield* span.parent\n          return parent\n        }).pipe(Effect.withSpan(\"child\"))\n\n        const runtime = yield* Effect.runtime()\n\n        yield* Effect.promise(async () => {\n          await OtelApi.trace.getTracer(\"test\").startActiveSpan(\"otel-span\", {\n            root: true,\n            attributes: { \"root\": \"yes\" }\n          }, async (span) => {\n            try {\n              const parent = await Runtime.runPromise(\n                runtime,\n                Tracer.withSpanContext(\n                  effect,\n                  span.spanContext()\n                )\n              )\n              const { spanId, traceId } = span.spanContext()\n              expect(parent).toMatchObject({\n                spanId,\n                traceId\n              })\n            } finally {\n              span.end()\n            }\n          })\n        })\n      }).pipe(Effect.provide(TracingLive)))\n  })\n\n  describe(\"not provided\", () => {\n    it.effect(\"withSpan\", () =>\n      Effect.withSpan(\"ok\")(\n        Effect.gen(function*() {\n          const span = yield* Effect.currentSpan\n          expect(span).not.instanceOf(OtelSpan)\n        })\n      ))\n  })\n\n  describe(\"OTLP tracer\", () => {\n    const MockHttpClient = Layer.succeed(\n      HttpClient.HttpClient,\n      HttpClient.make(() => Effect.die(\"mock http client\"))\n    )\n    const OtlpTracingLive = OtlpTracer.layer({\n      url: \"http://localhost:4318/v1/traces\",\n      resource: {\n        serviceName: \"test-otlp\"\n      }\n    }).pipe(Layer.provide(MockHttpClient), Layer.provide(OtlpSerialization.layerJson))\n\n    it.effect(\"currentOtelSpan works with OTLP tracer\", () =>\n      Effect.provide(\n        Effect.withSpan(\"ok\")(\n          Effect.gen(function*() {\n            const span = yield* Effect.currentSpan\n            const otelSpan = yield* Tracer.currentOtelSpan\n            const spanContext = otelSpan.spanContext()\n            expect(spanContext.traceId).toBe(span.traceId)\n            expect(spanContext.spanId).toBe(span.spanId)\n            expect(spanContext.traceFlags).toBe(OtelApi.TraceFlags.SAMPLED)\n            expect(spanContext.isRemote).toBe(false)\n            expect(otelSpan.isRecording()).toBe(true)\n\n            // it should proxy attribute changes\n            otelSpan.setAttribute(\"key\", \"value\")\n            expect(span.attributes.get(\"key\")).toEqual(\"value\")\n          })\n        ),\n        OtlpTracingLive\n      ))\n\n    it.effect(\"addEvent with attributes (2-arg overload) does not throw\", () =>\n      Effect.provide(\n        Effect.withSpan(\"root\")(\n          Effect.gen(function*() {\n            const otelSpan = yield* Tracer.currentOtelSpan\n            expect(() => otelSpan.addEvent(\"test-event\", { foo: \"bar\", count: 42 })).not.toThrow()\n          })\n        ),\n        OtlpTracingLive\n      ))\n\n    it.effect(\"addEvent with HrTime tuple (2-arg overload) does not throw\", () =>\n      Effect.provide(\n        Effect.withSpan(\"root\")(\n          Effect.gen(function*() {\n            const otelSpan = yield* Tracer.currentOtelSpan\n            expect(() => otelSpan.addEvent(\"test-event\", [1, 2])).not.toThrow()\n          })\n        ),\n        OtlpTracingLive\n      ))\n\n    it.effect(\"addEvent with number timestamp (2-arg overload) does not throw\", () =>\n      Effect.provide(\n        Effect.withSpan(\"root\")(\n          Effect.gen(function*() {\n            const otelSpan = yield* Tracer.currentOtelSpan\n            expect(() => otelSpan.addEvent(\"test-event\", Date.now())).not.toThrow()\n          })\n        ),\n        OtlpTracingLive\n      ))\n\n    it.effect(\"addEvent with Date timestamp (2-arg overload) does not throw\", () =>\n      Effect.provide(\n        Effect.withSpan(\"root\")(\n          Effect.gen(function*() {\n            const otelSpan = yield* Tracer.currentOtelSpan\n            expect(() => otelSpan.addEvent(\"test-event\", new Date())).not.toThrow()\n          })\n        ),\n        OtlpTracingLive\n      ))\n\n    it.effect(\"addEvent with name only (1-arg) does not throw\", () =>\n      Effect.provide(\n        Effect.withSpan(\"root\")(\n          Effect.gen(function*() {\n            const otelSpan = yield* Tracer.currentOtelSpan\n            expect(() => otelSpan.addEvent(\"test-event\")).not.toThrow()\n          })\n        ),\n        OtlpTracingLive\n      ))\n\n    it.effect(\"addEvent with attributes and timestamp (3-arg overload) does not throw\", () =>\n      Effect.provide(\n        Effect.withSpan(\"root\")(\n          Effect.gen(function*() {\n            const otelSpan = yield* Tracer.currentOtelSpan\n            expect(() => otelSpan.addEvent(\"test-event\", { foo: \"bar\" }, Date.now())).not.toThrow()\n          })\n        ),\n        OtlpTracingLive\n      ))\n  })\n\n  describe(\"Log Attributes\", () => {\n    it.effect(\"propagates attributes with Effect.fnUntraced\", () =>\n      Effect.gen(function*() {\n        const f = Effect.fnUntraced(function*() {\n          yield* Effect.logWarning(\"FooBar\")\n          return yield* Effect.fail(\"Oops\")\n        })\n\n        const p = f().pipe(Effect.withSpan(\"p\"))\n\n        yield* Effect.ignore(p)\n\n        const { exporter } = yield* Exporter\n\n        assert.isNotEmpty(exporter.getFinishedSpans()[0].events.filter((_) => _.name === \"FooBar\"))\n        assert.isNotEmpty(exporter.getFinishedSpans()[0].events.filter((_) => _.name === \"exception\"))\n      }).pipe(Effect.provide(TracingLive)))\n\n    it.effect(\"propagates attributes with Effect.fn(name)\", () =>\n      Effect.gen(function*() {\n        const f = Effect.fn(\"f\")(function*() {\n          yield* Effect.logWarning(\"FooBar\")\n          return yield* Effect.fail(\"Oops\")\n        })\n\n        const p = f().pipe(Effect.withSpan(\"p\"))\n\n        yield* Effect.ignore(p)\n\n        const { exporter } = yield* Exporter\n\n        assert.isNotEmpty(exporter.getFinishedSpans()[0].events.filter((_) => _.name === \"FooBar\"))\n        assert.isNotEmpty(exporter.getFinishedSpans()[0].events.filter((_) => _.name === \"exception\"))\n      }).pipe(Effect.provide(TracingLive)))\n\n    it.effect(\"propagates attributes with Effect.fn\", () =>\n      Effect.gen(function*() {\n        const f = Effect.fn(function*() {\n          yield* Effect.logWarning(\"FooBar\")\n          return yield* Effect.fail(\"Oops\")\n        })\n\n        const p = f().pipe(Effect.withSpan(\"p\"))\n\n        yield* Effect.ignore(p)\n\n        const { exporter } = yield* Exporter\n\n        yield* Console.log(Array.from(yield* FiberRef.get(FiberRef.currentLoggers)))\n\n        assert.isNotEmpty(exporter.getFinishedSpans()[0].events.filter((_) => _.name === \"FooBar\"))\n        assert.isNotEmpty(exporter.getFinishedSpans()[0].events.filter((_) => _.name === \"exception\"))\n      }).pipe(Effect.provide(TracingLive)))\n  })\n})\n"
  },
  {
    "path": "packages/opentelemetry/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.src.json\",\n  \"references\": [\n    { \"path\": \"../effect/tsconfig.build.json\" },\n    { \"path\": \"../platform/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/build.tsbuildinfo\",\n    \"outDir\": \"build/esm\",\n    \"declarationDir\": \"build/dts\",\n    \"stripInternal\": true\n  }\n}\n"
  },
  {
    "path": "packages/opentelemetry/tsconfig.examples.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"examples\"],\n  \"references\": [\n    { \"path\": \"tsconfig.build.json\" },\n    { \"path\": \"../effect/tsconfig.build.json\" },\n    { \"path\": \"../platform-node/tsconfig.build.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/examples.tsbuildinfo\",\n    \"rootDir\": \"examples\",\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "packages/opentelemetry/tsconfig.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"tsconfig.test.json\" },\n    { \"path\": \"tsconfig.examples.json\" }\n  ]\n}\n"
  },
  {
    "path": "packages/opentelemetry/tsconfig.src.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"src\"],\n  \"references\": [\n    { \"path\": \"../effect/tsconfig.src.json\" },\n    { \"path\": \"../platform/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/src.tsbuildinfo\",\n    \"rootDir\": \"src\",\n    \"outDir\": \"build/src\"\n  }\n}\n"
  },
  {
    "path": "packages/opentelemetry/tsconfig.test.json",
    "content": "{\n  \"extends\": \"../../tsconfig.base.json\",\n  \"include\": [\"test\"],\n  \"references\": [\n    { \"path\": \"tsconfig.src.json\" },\n    { \"path\": \"../vitest/tsconfig.src.json\" }\n  ],\n  \"compilerOptions\": {\n    \"tsBuildInfoFile\": \".tsbuildinfo/test.tsbuildinfo\",\n    \"rootDir\": \"test\",\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "packages/opentelemetry/vitest.config.ts",
    "content": "import { mergeConfig, type ViteUserConfig } from \"vitest/config\"\nimport shared from \"../../vitest.shared.js\"\n\nconst config: ViteUserConfig = {}\n\nexport default mergeConfig(shared, config)\n"
  },
  {
    "path": "packages/platform/CHANGELOG.md",
    "content": "# @effect/platform\n\n## 0.96.0\n\n### Patch Changes\n\n- Updated dependencies [[`f7bb09b`](https://github.com/Effect-TS/effect/commit/f7bb09b022f195d1f2b3c23d49e74b011ec5d109), [`bd7552a`](https://github.com/Effect-TS/effect/commit/bd7552a19cc0ed575507ac6cc0879a57e24ebd31), [`ad1a7eb`](https://github.com/Effect-TS/effect/commit/ad1a7eb7f6bebaf91c80be2443ac0439226d0098), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb), [`0d32048`](https://github.com/Effect-TS/effect/commit/0d32048f9836e2b23a6ba3ec5f43f0a000bb92fb)]:\n  - effect@3.21.0\n\n## 0.95.0\n\n### Patch Changes\n\n- Updated dependencies [[`fc82e81`](https://github.com/Effect-TS/effect/commit/fc82e81448bd9136a37580139ce46a2c61b11b54), [`82996bc`](https://github.com/Effect-TS/effect/commit/82996bce8debffcb44feb98bb862cf2662bd56b7), [`4d97a61`](https://github.com/Effect-TS/effect/commit/4d97a61a15b9dd6a0eece65b8f0c035e16d42ada), [`f6b0960`](https://github.com/Effect-TS/effect/commit/f6b0960bf3184109920dfed16ee7dfd7d67bc0f2), [`8798a84`](https://github.com/Effect-TS/effect/commit/8798a843218e6c0c0d3a8eee83360880e370b4da)]:\n  - effect@3.20.0\n\n## 0.94.5\n\n### Patch Changes\n\n- [#6050](https://github.com/Effect-TS/effect/pull/6050) [`d67c708`](https://github.com/Effect-TS/effect/commit/d67c7089ba8616b2d48ef7324312267a2a6f310a) Thanks @tim-smart! - Backport Effect 4 `contentType` support for `HttpBody` JSON / URL-encoded constructors and `HttpServerResponse` JSON / URL-encoded helpers.\n\n- Updated dependencies [[`a8c436f`](https://github.com/Effect-TS/effect/commit/a8c436f7004cc2a8ce2daec589ea7256b91c324f)]:\n  - effect@3.19.17\n\n## 0.94.4\n\n### Patch Changes\n\n- [#6035](https://github.com/Effect-TS/effect/pull/6035) [`22d9d27`](https://github.com/Effect-TS/effect/commit/22d9d27bc007db86d9e4748c17324fab5f950c7d) Thanks @tim-smart! - Fix `HttpServerError.causeResponse` to prefer 499 when a client abort interrupt is present.\n\n## 0.94.3\n\n### Patch Changes\n\n- [#6021](https://github.com/Effect-TS/effect/pull/6021) [`0023c19`](https://github.com/Effect-TS/effect/commit/0023c19c63c402c050d496817ba92aceea7f25b7) Thanks @codewithkenzo! - Fix `HttpClientRequest.appendUrl` to properly join URL paths.\n\n  Previously, `appendUrl` used simple string concatenation which could produce invalid URLs:\n\n  ```typescript\n  // Before (broken):\n  appendUrl(\"https://api.example.com/v1\", \"users\")\n  // Result: \"https://api.example.com/v1users\" (missing slash!)\n  ```\n\n  Now it ensures proper path joining:\n\n  ```typescript\n  // After (fixed):\n  appendUrl(\"https://api.example.com/v1\", \"users\")\n  // Result: \"https://api.example.com/v1/users\"\n  ```\n\n- [#6019](https://github.com/Effect-TS/effect/pull/6019) [`9a96b87`](https://github.com/Effect-TS/effect/commit/9a96b87a33a75ebc277c585e60758ab4409c0d9e) Thanks @codewithkenzo! - Fix `retryTransient` to use correct transient status codes\n\n  Changed `isTransientResponse` from `status >= 429` to an explicit allowlist (408, 429, 500, 502, 503, 504). This correctly excludes 501 (Not Implemented) and 505+ permanent errors, while including 408 (Request Timeout) which was previously missed.\n\n  Also aligned response retry behavior with v4: the `while` predicate now only applies to error retries, not response retries. Response retries are determined solely by `isTransientResponse`. This matches the semantic intent since `while` is typed for errors, not responses.\n\n  Fixes #5995\n\n- Updated dependencies [[`e71889f`](https://github.com/Effect-TS/effect/commit/e71889f35b081d13b7da2c04d2f81d6933056b49)]:\n  - effect@3.19.16\n\n## 0.94.2\n\n### Patch Changes\n\n- [#5977](https://github.com/Effect-TS/effect/pull/5977) [`118e7a4`](https://github.com/Effect-TS/effect/commit/118e7a4af5b86f6d707a40d3b03157b6bf5827e7) Thanks @scotttrinh! - Added `rows` and `isTTY` properties to `Terminal`\n\n- Updated dependencies [[`7e925ea`](https://github.com/Effect-TS/effect/commit/7e925eae4a9db556bcbf7e8b6a762ccf8588aa3b), [`d7e75d6`](https://github.com/Effect-TS/effect/commit/d7e75d6d15294bbcd7ac49a0e9005848379ea86f), [`4860d1e`](https://github.com/Effect-TS/effect/commit/4860d1e09b436061ea4aeca07605a669793560fc)]:\n  - effect@3.19.15\n\n## 0.94.1\n\n### Patch Changes\n\n- [#5936](https://github.com/Effect-TS/effect/pull/5936) [`65e9e35`](https://github.com/Effect-TS/effect/commit/65e9e35157cbdfb40826ddad34555c4ebcf7c0b0) Thanks @schickling! - Document subtle CORS middleware `allowedHeaders` behavior: when empty array (default), it reflects back the client's `Access-Control-Request-Headers` (permissive), and when non-empty array, it only allows specified headers (restrictive). Added comprehensive JSDoc with examples.\n\n- [#5940](https://github.com/Effect-TS/effect/pull/5940) [`ee69cd7`](https://github.com/Effect-TS/effect/commit/ee69cd796feb3d8d1046f52edd8950404cd4ed0e) Thanks @kitlangton! - HttpServerResponse: fix `fromWeb` to preserve Content-Type header when response has a body\n\n  Previously, when converting a web `Response` to an `HttpServerResponse` via `fromWeb`, the `Content-Type` header was not passed to `Body.stream()`, causing it to default to `application/octet-stream`. This affected any code using `HttpApp.fromWebHandler` to wrap web handlers, as JSON responses would incorrectly have their Content-Type set to `application/octet-stream` instead of `application/json`.\n\n- Updated dependencies [[`488d6e8`](https://github.com/Effect-TS/effect/commit/488d6e870eda3dfc137f4940bb69416f61ed8fe3)]:\n  - effect@3.19.14\n\n## 0.94.0\n\n### Minor Changes\n\n- [#5917](https://github.com/Effect-TS/effect/pull/5917) [`ff7053f`](https://github.com/Effect-TS/effect/commit/ff7053f6d8508567b6145239f97aacc5773b0c53) Thanks @tim-smart! - support non-errors in HttpClient.retryTransient\n\n### Patch Changes\n\n- Updated dependencies [[`77eeb86`](https://github.com/Effect-TS/effect/commit/77eeb86ddf208e51ec25932af83d52d3b4700371), [`287c32c`](https://github.com/Effect-TS/effect/commit/287c32c9f10da8e96f2b9ef8424316189d9ad4b3)]:\n  - effect@3.19.13\n\n## 0.93.8\n\n### Patch Changes\n\n- [#5902](https://github.com/Effect-TS/effect/pull/5902) [`a0a84d8`](https://github.com/Effect-TS/effect/commit/a0a84d8df05d18023ffcb1f60af91d14c2b8db57) Thanks @tim-smart! - add HttpApp.fromWebHandler\n\n- Updated dependencies [[`a6dfca9`](https://github.com/Effect-TS/effect/commit/a6dfca93b676eeffe4db64945b01e2004b395cb8)]:\n  - effect@3.19.12\n\n## 0.93.7\n\n### Patch Changes\n\n- [#5896](https://github.com/Effect-TS/effect/pull/5896) [`65bff45`](https://github.com/Effect-TS/effect/commit/65bff451fc54d47b32995b3bc898ccc5f8b1beb6) Thanks @tim-smart! - add basic apis for converting to web Request/Response\n\n## 0.93.6\n\n### Patch Changes\n\n- [#5835](https://github.com/Effect-TS/effect/pull/5835) [`25d1cb6`](https://github.com/Effect-TS/effect/commit/25d1cb60aadf8f8fdf9a4aad3dbaa31e1ca3b70d) Thanks @tim-smart! - consider clean http interrupts as successful responses\n\n## 0.93.5\n\n### Patch Changes\n\n- [#5818](https://github.com/Effect-TS/effect/pull/5818) [`ebfbbd6`](https://github.com/Effect-TS/effect/commit/ebfbbd62e1daf235d1f25b825d80ae4880408df3) Thanks @KhraksMamtsov! - Support `HttpApiError` unification\n\n## 0.93.4\n\n### Patch Changes\n\n- [#5797](https://github.com/Effect-TS/effect/pull/5797) [`8ebd29e`](https://github.com/Effect-TS/effect/commit/8ebd29ec10976222c200901d9b72779af743e6d5) Thanks @tim-smart! - use original status code if headers have already been sent\n\n## 0.93.3\n\n### Patch Changes\n\n- [#5759](https://github.com/Effect-TS/effect/pull/5759) [`e144f02`](https://github.com/Effect-TS/effect/commit/e144f02c93258f0bb37bd10ee9849f2836914e2f) Thanks @rohovskoi! - fix scalar configuration and types\n\n## 0.93.2\n\n### Patch Changes\n\n- [#5737](https://github.com/Effect-TS/effect/pull/5737) [`2bb8242`](https://github.com/Effect-TS/effect/commit/2bb8242cb094e516665116707b798fc8e2bc5837) Thanks @tim-smart! - ensure HttpApiScalar source is tree-shakable\n\n## 0.93.1\n\n### Patch Changes\n\n- [#5728](https://github.com/Effect-TS/effect/pull/5728) [`1961185`](https://github.com/Effect-TS/effect/commit/1961185e502459a188216f319a38c3dfe30fc6f0) Thanks @kitlangton! - Fix UrlParams.setAll overwrite semantics\n\n## 0.93.0\n\n### Patch Changes\n\n- [#5606](https://github.com/Effect-TS/effect/pull/5606) [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433) Thanks @tim-smart! - expose Layer output in HttpLayerRouter.serve\n\n- Updated dependencies [[`3c15d5f`](https://github.com/Effect-TS/effect/commit/3c15d5f99fb8d8470a00c5a33d9ba3cac89dfe4c), [`3863fa8`](https://github.com/Effect-TS/effect/commit/3863fa89f61e63e5529fd961e37333bddf7db64a), [`2a03c76`](https://github.com/Effect-TS/effect/commit/2a03c76c2781ca7e9e228e838eab2eb0d0795b1d), [`24a1685`](https://github.com/Effect-TS/effect/commit/24a1685c70a9ed157468650f95a5c3da3f2c2433)]:\n  - effect@3.19.0\n\n## 0.92.1\n\n### Patch Changes\n\n- [#5588](https://github.com/Effect-TS/effect/pull/5588) [`f6987c0`](https://github.com/Effect-TS/effect/commit/f6987c04ebf1386dc37729dfea1631ce364a5a96) Thanks @wmaurer! - add additional predicate typings for HttpMiddleware.cors allowOrigins\n\n## 0.92.0\n\n### Patch Changes\n\n- [#5302](https://github.com/Effect-TS/effect/pull/5302) [`c60956e`](https://github.com/Effect-TS/effect/commit/c60956e18fe20841d39d0127c8c488af657ab936) Thanks @OliverJAsh! - Adjust `xForwardedHeaders` middleware to always use `x-forwarded-for`\n\n- Updated dependencies [[`1c6ab74`](https://github.com/Effect-TS/effect/commit/1c6ab74b314b2b6df8bb1b1a0cb9527ceda0e3fa), [`70fe803`](https://github.com/Effect-TS/effect/commit/70fe803469db3355ffbf8359b52c351f1c2dc137), [`c296e32`](https://github.com/Effect-TS/effect/commit/c296e32554143b84ae8987046984e1cf1852417c), [`a098ddf`](https://github.com/Effect-TS/effect/commit/a098ddfc551f5aa0a7c36f9b4928372a64d4d9f2)]:\n  - effect@3.18.0\n\n## 0.91.1\n\n### Patch Changes\n\n- [#5552](https://github.com/Effect-TS/effect/pull/5552) [`ffa494c`](https://github.com/Effect-TS/effect/commit/ffa494cbc3e62039502b09718b0a9d5e0fb4e04c) Thanks @tim-smart! - allow predicates for HttpMiddleware.cors allowOrigins\n\n## 0.91.0\n\n### Minor Changes\n\n- [#5549](https://github.com/Effect-TS/effect/pull/5549) [`d4d86a8`](https://github.com/Effect-TS/effect/commit/d4d86a81f02b94e09fce8004ce2c5369c505ca5a) Thanks @tim-smart! - remove msgpackr re-exports\n\n## 0.90.10\n\n### Patch Changes\n\n- [#5517](https://github.com/Effect-TS/effect/pull/5517) [`de07e58`](https://github.com/Effect-TS/effect/commit/de07e5805496b80226ba6a5efc2b4c05e1aba4b8) Thanks @tim-smart! - add onOpen option to Socket.run\n\n## 0.90.9\n\n### Patch Changes\n\n- [#5492](https://github.com/Effect-TS/effect/pull/5492) [`0421c8c`](https://github.com/Effect-TS/effect/commit/0421c8ce2ee614ae46b5684c850ab6aab8fa02e9) Thanks @tim-smart! - provide http span to global middleware\n\n## 0.90.8\n\n### Patch Changes\n\n- [#5481](https://github.com/Effect-TS/effect/pull/5481) [`333be04`](https://github.com/Effect-TS/effect/commit/333be046b50e8300f5cb70b871448e0628b7b37c) Thanks @jpowersdev! - Allow user to set extension of file created using `FileSystem.makeTempFile`\n\n## 0.90.7\n\n### Patch Changes\n\n- [#5466](https://github.com/Effect-TS/effect/pull/5466) [`75dffc8`](https://github.com/Effect-TS/effect/commit/75dffc877b1fa8c95fc026747b9060b7eba44232) Thanks @tim-smart! - ensure HttpApiClient adds encoding contentType to headers\n\n## 0.90.6\n\n### Patch Changes\n\n- [#5418](https://github.com/Effect-TS/effect/pull/5418) [`7ad7b3c`](https://github.com/Effect-TS/effect/commit/7ad7b3c7de299d8d37bfcbe23b2717b7732d490b) Thanks @tim-smart! - exclude layer services from HttpLayerRouter.toWebHandler request context\n\n## 0.90.5\n\n### Patch Changes\n\n- [#5410](https://github.com/Effect-TS/effect/pull/5410) [`fef9771`](https://github.com/Effect-TS/effect/commit/fef9771eab24af6415be946df0c9f64eba01cef7) Thanks @beeman! - export isQuitExection function from @effect/platform/Terminal\n\n- Updated dependencies [[`84bc300`](https://github.com/Effect-TS/effect/commit/84bc3003b42ad51210e9e1248efd04c5d0e3dd1e)]:\n  - effect@3.17.8\n\n## 0.90.4\n\n### Patch Changes\n\n- [#5402](https://github.com/Effect-TS/effect/pull/5402) [`8c7bb52`](https://github.com/Effect-TS/effect/commit/8c7bb52dc78850be72566decba6222870e3733d0) Thanks @tim-smart! - abort HttpClientResponse.stream regardless of how stream ends\n\n- [#5397](https://github.com/Effect-TS/effect/pull/5397) [`0e46e24`](https://github.com/Effect-TS/effect/commit/0e46e24c24e9edb8bf2e29835a94013e9c34d034) Thanks @IMax153! - Avoid issues with ESM builds by removing dependency on `@opentelemetry/semantic-conventions`\n\n## 0.90.3\n\n### Patch Changes\n\n- [#5391](https://github.com/Effect-TS/effect/pull/5391) [`786867b`](https://github.com/Effect-TS/effect/commit/786867b1a443d4965aae4b4fd6391aaa85b6573a) Thanks @tim-smart! - support multiple HttpLayerRouter.addHttpApi\n\n## 0.90.2\n\n### Patch Changes\n\n- [#5357](https://github.com/Effect-TS/effect/pull/5357) [`99302f4`](https://github.com/Effect-TS/effect/commit/99302f4233029ba3f4446f284d01af501cf1f4d6) Thanks @nounder! - Add `HttpServerResponse.expireCookie`\n\n## 0.90.1\n\n### Patch Changes\n\n- [#5355](https://github.com/Effect-TS/effect/pull/5355) [`27a4e02`](https://github.com/Effect-TS/effect/commit/27a4e0285226cc0c084d19b5cdc4db1f38227559) Thanks @nounder! - Use `302 Found` status in `HttpServerResponse.redirect` as default\n\n## 0.90.0\n\n### Minor Changes\n\n- [#5258](https://github.com/Effect-TS/effect/pull/5258) [`7813640`](https://github.com/Effect-TS/effect/commit/7813640279d9e3a3e7fc0a29bfb5c6d5fb3c270f) Thanks @kitlangton! - Changes Terminal.readInput to return a ReadonlyMailbox of events\n\n  This allows for more efficient handling of input events, as well as ensuring\n  events are not lost.\n\n## 0.89.0\n\n### Patch Changes\n\n- Updated dependencies [[`40c3c87`](https://github.com/Effect-TS/effect/commit/40c3c875f724264312b43002859c82bed9ad0df9), [`ed2c74a`](https://github.com/Effect-TS/effect/commit/ed2c74ae8fa4ea0dd06ea84a3e58cd32e6916104), [`073a1b8`](https://github.com/Effect-TS/effect/commit/073a1b8be5dbfa87454393ee7346f5bc36a4fd63), [`f382e99`](https://github.com/Effect-TS/effect/commit/f382e99e409838a879246250fc3994b9bf5b3c2c), [`e8c7ba5`](https://github.com/Effect-TS/effect/commit/e8c7ba5fd3eb0c3ae3039fc24c09d69391987989), [`7e10415`](https://github.com/Effect-TS/effect/commit/7e1041599ade25103428703f5d2dfd7378a09636), [`e9bdece`](https://github.com/Effect-TS/effect/commit/e9bdececdc24f60a246be5055eca71a0d49ea7f2), [`8d95eb0`](https://github.com/Effect-TS/effect/commit/8d95eb0356b1d1736204836c275d201a547d208d)]:\n  - effect@3.17.0\n\n## 0.88.2\n\n### Patch Changes\n\n- [#5234](https://github.com/Effect-TS/effect/pull/5234) [`de513d9`](https://github.com/Effect-TS/effect/commit/de513d9abb8311998ca7016635f53be0ac766472) Thanks @tim-smart! - ensure duplicate paths are a defect in HttpApi\n\n## 0.88.1\n\n### Patch Changes\n\n- [#5192](https://github.com/Effect-TS/effect/pull/5192) [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38) Thanks @nikelborm! - Updated deprecated OTel Resource attributes names and values.\n\n  Many of the attributes have undergone the process of deprecation not once, but twice. Most of the constants holding attribute names have been renamed. These are minor changes.\n\n  Additionally, there were numerous changes to the attribute keys themselves. These changes can be considered major.\n\n  In the `@opentelemetry/semantic-conventions` package, new attributes having ongoing discussion about them are going through a process called incubation, until a consensus about their necessity and form is reached. Otel team [recommends](https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv) devs to copy them directly into their code. Luckily, it's not necessary because all of the new attribute names and values came out of this process (some of them were changed again) and are now considered stable.\n\n  ## Reasoning for minor version bump\n\n  | Package                    | Major attribute changes                                                       | Major value changes               |\n  | -------------------------- | ----------------------------------------------------------------------------- | --------------------------------- |\n  | Clickhouse client          | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             |                                   |\n  | MsSQL client               | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             | `mssql` -> `microsoft.sql_server` |\n  | MySQL client               | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             |                                   |\n  | Pg client                  | `db.system` -> `db.system.name` <br/> `db.name` -> `db.namespace`             |                                   |\n  | Bun SQLite client          | `db.system` -> `db.system.name`                                               |                                   |\n  | Node SQLite client         | `db.system` -> `db.system.name`                                               |                                   |\n  | React.Native SQLite client | `db.system` -> `db.system.name`                                               |                                   |\n  | Wasm SQLite client         | `db.system` -> `db.system.name`                                               |                                   |\n  | SQLite Do client           | `db.system` -> `db.system.name`                                               |                                   |\n  | LibSQL client              | `db.system` -> `db.system.name`                                               |                                   |\n  | D1 client                  | `db.system` -> `db.system.name`                                               |                                   |\n  | Kysely client              | `db.statement` -> `db.query.text`                                             |                                   |\n  | @effect/sql                | `db.statement` -> `db.query.text` <br/> `db.operation` -> `db.operation.name` |                                   |\n\n- [#5211](https://github.com/Effect-TS/effect/pull/5211) [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48) Thanks @mattiamanzati! - Removed some unnecessary single-arg pipe calls\n\n- Updated dependencies [[`f5dfabf`](https://github.com/Effect-TS/effect/commit/f5dfabf51ba481a4468c1509c537314978ef6cec), [`17a5ea8`](https://github.com/Effect-TS/effect/commit/17a5ea8fa29785fe6e4c9480f2a2e9c8c59f3f38), [`d25f22b`](https://github.com/Effect-TS/effect/commit/d25f22be7598abe977caf6cdac3b0dd78b438c48)]:\n  - effect@3.16.14\n\n## 0.88.0\n\n### Minor Changes\n\n- [#5208](https://github.com/Effect-TS/effect/pull/5208) [`dbabf5e`](https://github.com/Effect-TS/effect/commit/dbabf5e76fa63b050d2b6c466713c7dc59f07d3c) Thanks @tim-smart! - consolidate Http web handler layer apis\n\n### Patch Changes\n\n- [#5206](https://github.com/Effect-TS/effect/pull/5206) [`27206d7`](https://github.com/Effect-TS/effect/commit/27206d7f0558d7fe28de57bf54f1d0cc83acc92e) Thanks @tim-smart! - lazily build HttpLayerRouter web handlers\n\n## 0.87.13\n\n### Patch Changes\n\n- Updated dependencies [[`c1c05a8`](https://github.com/Effect-TS/effect/commit/c1c05a8242fb5df7445b4a12387a60eac7726eb7), [`81fe4a2`](https://github.com/Effect-TS/effect/commit/81fe4a2c81d5e30e180a60e68c52016a27b350db)]:\n  - effect@3.16.13\n\n## 0.87.12\n\n### Patch Changes\n\n- [#5177](https://github.com/Effect-TS/effect/pull/5177) [`32ba77a`](https://github.com/Effect-TS/effect/commit/32ba77ae304d2161362a73e8b61965332626cf2d) Thanks @johtso! - Fix KeyValueStore.make type mismatch\n\n- [#5174](https://github.com/Effect-TS/effect/pull/5174) [`d5e25b2`](https://github.com/Effect-TS/effect/commit/d5e25b237f05670ee42b386cb40b2cb448fc11d7) Thanks @schickling! - feat(platform): add recursive option to FileSystem.watch\n\n  Added a `recursive` option to `FileSystem.watch` that allows watching for changes in subdirectories. When set to `true`, the watcher will monitor changes in all nested directories.\n\n  Note: The recursive option is only supported on macOS and Windows. On other platforms, it will be ignored.\n\n  Example:\n\n  ```ts\n  import { FileSystem } from \"@effect/platform\"\n  import { Effect, Stream } from \"effect\"\n\n  Effect.gen(function* () {\n    const fs = yield* FileSystem.FileSystem\n\n    // Watch directory and all subdirectories\n    yield* fs\n      .watch(\"src\", { recursive: true })\n      .pipe(Stream.runForEach(console.log))\n  })\n  ```\n\n## 0.87.11\n\n### Patch Changes\n\n- [#5184](https://github.com/Effect-TS/effect/pull/5184) [`001392b`](https://github.com/Effect-TS/effect/commit/001392ba8bfcad101bb034348a7415012fb12f72) Thanks @tim-smart! - ensure HttpApiClient schemas are composed correctly\n\n- [#5181](https://github.com/Effect-TS/effect/pull/5181) [`7bfb099`](https://github.com/Effect-TS/effect/commit/7bfb099cb5528511b8d63045c4fbb4dc9cb18528) Thanks @tim-smart! - update find-my-way-ts\n\n## 0.87.10\n\n### Patch Changes\n\n- [#5175](https://github.com/Effect-TS/effect/pull/5175) [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0) Thanks @tim-smart! - rename HttpLayerRouter.Type to Request\n\n- [#5175](https://github.com/Effect-TS/effect/pull/5175) [`678318d`](https://github.com/Effect-TS/effect/commit/678318d2e88233156b006acda56c2d138ee3ffa0) Thanks @tim-smart! - propagate headers to HttpServerResponse.raw(Response)\n\n## 0.87.9\n\n### Patch Changes\n\n- [#5170](https://github.com/Effect-TS/effect/pull/5170) [`54514a2`](https://github.com/Effect-TS/effect/commit/54514a2f53166de27ad7e756dbf12194691fd4af) Thanks @tim-smart! - add HttpLayerRouter.toWebHandler\n\n## 0.87.8\n\n### Patch Changes\n\n- [#5166](https://github.com/Effect-TS/effect/pull/5166) [`4ce4f82`](https://github.com/Effect-TS/effect/commit/4ce4f824f6fdef492be1d35c05a490ffce518c89) Thanks @tim-smart! - add global middleware to HttpLayerRouter\n\n## 0.87.7\n\n### Patch Changes\n\n- [#5153](https://github.com/Effect-TS/effect/pull/5153) [`a9b617f`](https://github.com/Effect-TS/effect/commit/a9b617f125171ed76cd79ab46d7a924daf3b0e70) Thanks @thewilkybarkid! - Fix UrlParams.toRecord when there's a **proto** key\n\n- [#5159](https://github.com/Effect-TS/effect/pull/5159) [`7e26e86`](https://github.com/Effect-TS/effect/commit/7e26e86524abcc93713d6ad7eee486638c98f7c2) Thanks @tim-smart! - add HttpLayerRouter.add & addAll apis\n\n## 0.87.6\n\n### Patch Changes\n\n- Updated dependencies [[`905da99`](https://github.com/Effect-TS/effect/commit/905da996aad665057b4ca6dba1a4af44fb8835bd)]:\n  - effect@3.16.12\n\n## 0.87.5\n\n### Patch Changes\n\n- [#5142](https://github.com/Effect-TS/effect/pull/5142) [`2fd8676`](https://github.com/Effect-TS/effect/commit/2fd8676c803cd40000dfc3231f5daecaa0e0ebd2) Thanks @tim-smart! - improve type safety of HttpLayerRouter.middleware error handling\n\n## 0.87.4\n\n### Patch Changes\n\n- [#5137](https://github.com/Effect-TS/effect/pull/5137) [`e82a4fd`](https://github.com/Effect-TS/effect/commit/e82a4fd60f6528d08cef1a4aba0abe0d3ba741ad) Thanks @tim-smart! - move HttpLayerRouter request errors to Layer error channel\n\n## 0.87.3\n\n### Patch Changes\n\n- [#5128](https://github.com/Effect-TS/effect/pull/5128) [`1b6e396`](https://github.com/Effect-TS/effect/commit/1b6e396d699f3cbbc56b68f99055cf746529bb9e) Thanks @tim-smart! - attach http request scope to stream lifetime for stream responses\n\n## 0.87.2\n\n### Patch Changes\n\n- [#5111](https://github.com/Effect-TS/effect/pull/5111) [`4fea68c`](https://github.com/Effect-TS/effect/commit/4fea68ca7a25a3c39a1ab68b3885534513ab0c81) Thanks @mlegenhausen! - `HttpRouter.mountApp` prefix matching fixed\n\n- [#5117](https://github.com/Effect-TS/effect/pull/5117) [`b927954`](https://github.com/Effect-TS/effect/commit/b9279543cf5688dd8a577af80456959c615217d0) Thanks @tim-smart! - add HttpLayerRouter module\n\n  The experimental HttpLayerRouter module provides a simplified way to create HTTP servers.\n\n  You can read more in the /platform README:\n\n  https://github.com/Effect-TS/effect/blob/main/packages/platform/README.md#httplayerrouter\n\n- Updated dependencies [[`99590a6`](https://github.com/Effect-TS/effect/commit/99590a6ca9128eb1ede265b6670b655311995614), [`6c3e24c`](https://github.com/Effect-TS/effect/commit/6c3e24c2308f7d4a29b8f4270ab81bca22ac6bb4)]:\n  - effect@3.16.11\n\n## 0.87.1\n\n### Patch Changes\n\n- Updated dependencies [[`faad30e`](https://github.com/Effect-TS/effect/commit/faad30ec8742916be59f9db642d0fc98225b636c)]:\n  - effect@3.16.10\n\n## 0.87.0\n\n### Minor Changes\n\n- [#5087](https://github.com/Effect-TS/effect/pull/5087) [`b5bac9a`](https://github.com/Effect-TS/effect/commit/b5bac9ac2913fcd11b02322624f03b544eef53ba) Thanks @tim-smart! - add HttpApiClient.makeWith, for supporting passing in HttpClient with errors and requirements\n\n## 0.86.0\n\n### Minor Changes\n\n- [#5081](https://github.com/Effect-TS/effect/pull/5081) [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07) Thanks @tim-smart! - use Context.Reference for Multipart configuration\n\n### Patch Changes\n\n- [#5081](https://github.com/Effect-TS/effect/pull/5081) [`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07) Thanks @tim-smart! - allow configuring multipart limits in HttpApiSchema.Multipart\n\n- Updated dependencies [[`5137c70`](https://github.com/Effect-TS/effect/commit/5137c703461d8d3b363c112140a6e7f798241d07), [`c23d25c`](https://github.com/Effect-TS/effect/commit/c23d25c3e7c541f1f63b28484d8c461d86c67e99)]:\n  - effect@3.16.9\n\n## 0.85.2\n\n### Patch Changes\n\n- [#5053](https://github.com/Effect-TS/effect/pull/5053) [`914a191`](https://github.com/Effect-TS/effect/commit/914a191e7cb6341a3d0e965bccd27c336cf22e44) Thanks @tim-smart! - fix retrieval of HttpApiSchema.param annotations\n\n## 0.85.1\n\n### Patch Changes\n\n- Updated dependencies [[`8cb98d5`](https://github.com/Effect-TS/effect/commit/8cb98d53e68330228287ce2a2e0d8a4c86bcab3b), [`db2dd3c`](https://github.com/Effect-TS/effect/commit/db2dd3c3a8a77d791eae19e66153527e1cde4e6e)]:\n  - effect@3.16.8\n\n## 0.85.0\n\n### Minor Changes\n\n- [#5042](https://github.com/Effect-TS/effect/pull/5042) [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e) Thanks @tim-smart! - HttpApiBuilder .handleRaw no longer parses the request body\n\n### Patch Changes\n\n- [#5042](https://github.com/Effect-TS/effect/pull/5042) [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e) Thanks @tim-smart! - allow return HttpServerResponse from HttpApiBuilder .handle\n\n- [#5042](https://github.com/Effect-TS/effect/pull/5042) [`93687dd`](https://github.com/Effect-TS/effect/commit/93687ddbb25ce3b324cd2b83d2ccff225e97307e) Thanks @tim-smart! - add HttpApiSchema.MultipartStream\n\n## 0.84.11\n\n### Patch Changes\n\n- Updated dependencies [[`1bb0d8a`](https://github.com/Effect-TS/effect/commit/1bb0d8ab96782e99434356266b38251554ea0294)]:\n  - effect@3.16.7\n\n## 0.84.10\n\n### Patch Changes\n\n- [#5032](https://github.com/Effect-TS/effect/pull/5032) [`bf369b2`](https://github.com/Effect-TS/effect/commit/bf369b2902a0e0b195d957c18b9efd180942cf8b) Thanks @tim-smart! - allow property signatures in HttpApiSchema.param\n\n- Updated dependencies [[`a5f7595`](https://github.com/Effect-TS/effect/commit/a5f75956ef9a15a83c416517ef493f0ee2f5ee8a), [`a02470c`](https://github.com/Effect-TS/effect/commit/a02470c75579e91525a25adb3f21b3650d042fdd), [`f891d45`](https://github.com/Effect-TS/effect/commit/f891d45adffdafd3f94a2eca23faa354e3a409a8)]:\n  - effect@3.16.6\n\n## 0.84.9\n\n### Patch Changes\n\n- Updated dependencies [[`bf418ef`](https://github.com/Effect-TS/effect/commit/bf418ef14a0f2ec965535793d5cea8fa8ba177ac)]:\n  - effect@3.16.5\n\n## 0.84.8\n\n### Patch Changes\n\n- [#4996](https://github.com/Effect-TS/effect/pull/4996) [`8b9db77`](https://github.com/Effect-TS/effect/commit/8b9db7742846af0f58fd8e8b7acb7f4f5ff487ec) Thanks @tim-smart! - allow literals in HttpApiSchema.param\n\n## 0.84.7\n\n### Patch Changes\n\n- Updated dependencies [[`74ab9a0`](https://github.com/Effect-TS/effect/commit/74ab9a0a9e16d6e019369d256e1e24175c8bc3f3), [`770008e`](https://github.com/Effect-TS/effect/commit/770008eca3aad2899a2ed951236e575793294b28)]:\n  - effect@3.16.4\n\n## 0.84.6\n\n### Patch Changes\n\n- [#4975](https://github.com/Effect-TS/effect/pull/4975) [`ceea77a`](https://github.com/Effect-TS/effect/commit/ceea77a13055f145520f763e3fce5b8ff15d728f) Thanks @tim-smart! - allow wrapping a web Response with HttpServerResponse.raw on some platforms\n\n## 0.84.5\n\n### Patch Changes\n\n- [#4964](https://github.com/Effect-TS/effect/pull/4964) [`ec52c6a`](https://github.com/Effect-TS/effect/commit/ec52c6a2211e76972462b15b9d5a9d6d56761b7a) Thanks @tim-smart! - ensure HttpApi security middleware cache is not shared\n\n## 0.84.4\n\n### Patch Changes\n\n- Updated dependencies [[`87722fc`](https://github.com/Effect-TS/effect/commit/87722fce693a9b49284bbddbf82d30714c688261), [`36217ee`](https://github.com/Effect-TS/effect/commit/36217eeb1337edd9ac3f9a635b80a6385d22ae8f)]:\n  - effect@3.16.3\n\n## 0.84.3\n\n### Patch Changes\n\n- [#4941](https://github.com/Effect-TS/effect/pull/4941) [`ab7684f`](https://github.com/Effect-TS/effect/commit/ab7684f1c2a0671bf091f255d220e3a4cc7f528e) Thanks @tim-smart! - decode HttpApiClient response from ArrayBuffer\n\n## 0.84.2\n\n### Patch Changes\n\n- Updated dependencies [[`0ddf148`](https://github.com/Effect-TS/effect/commit/0ddf148a247aa87af043d276b8453a714a400897)]:\n  - effect@3.16.2\n\n## 0.84.1\n\n### Patch Changes\n\n- [#4936](https://github.com/Effect-TS/effect/pull/4936) [`71174d0`](https://github.com/Effect-TS/effect/commit/71174d09691314a9b6b66189e456fd21e3eb6543) Thanks @mattiamanzati! - Escape JSON Schema $id for empty struct\n\n- Updated dependencies [[`71174d0`](https://github.com/Effect-TS/effect/commit/71174d09691314a9b6b66189e456fd21e3eb6543), [`d615e6e`](https://github.com/Effect-TS/effect/commit/d615e6e5b944f6fd5e627e31752c7ca7e4e1c17d)]:\n  - effect@3.16.1\n\n## 0.84.0\n\n### Patch Changes\n\n- Updated dependencies [[`ee0bd5d`](https://github.com/Effect-TS/effect/commit/ee0bd5d24864752c54cb359f67a67dd903971ec4), [`5189800`](https://github.com/Effect-TS/effect/commit/51898004e11766b8cf6d95e960b636f6d5db79ec), [`58bfeaa`](https://github.com/Effect-TS/effect/commit/58bfeaa64ded8c88f772b184311c0c0dbac10960), [`194d748`](https://github.com/Effect-TS/effect/commit/194d7486943f56f3267ef415395ac220a4b3e634), [`918c9ea`](https://github.com/Effect-TS/effect/commit/918c9ea1a57facb154f0fb26792021f337054dee), [`9198e6f`](https://github.com/Effect-TS/effect/commit/9198e6fcc1a3ff4fefb3363004de558d8de01f40), [`2a370bf`](https://github.com/Effect-TS/effect/commit/2a370bf625fdeede5659721468eb0d527e403279), [`58ccb91`](https://github.com/Effect-TS/effect/commit/58ccb91328c8df5d49808b673738bc09df355201), [`fd47834`](https://github.com/Effect-TS/effect/commit/fd478348203fa89462b0a1d067ce4de034353df4)]:\n  - effect@3.16.0\n\n## 0.83.0\n\n### Minor Changes\n\n- [#4932](https://github.com/Effect-TS/effect/pull/4932) [`5522520`](https://github.com/Effect-TS/effect/commit/55225206ab9af0ad60b1c0654690a8a096d625cd) Thanks @tim-smart! - refactor PlatformError and make it a schema\n\n### Patch Changes\n\n- Updated dependencies [[`cc5bb2b`](https://github.com/Effect-TS/effect/commit/cc5bb2b918a9450a975f702dabcea891bda382cb)]:\n  - effect@3.15.5\n\n## 0.82.8\n\n### Patch Changes\n\n- [#4927](https://github.com/Effect-TS/effect/pull/4927) [`0617b9d`](https://github.com/Effect-TS/effect/commit/0617b9dc365f1963b36949ad7f9023ab6eb94524) Thanks @fubhy! - Fix package internal imports\n\n## 0.82.7\n\n### Patch Changes\n\n- [#4921](https://github.com/Effect-TS/effect/pull/4921) [`c20b95a`](https://github.com/Effect-TS/effect/commit/c20b95a99ffe452b4774c844d397a905f713b6d6) Thanks @tim-smart! - update /platform dependencies\n\n- [#4916](https://github.com/Effect-TS/effect/pull/4916) [`94ada43`](https://github.com/Effect-TS/effect/commit/94ada430928d5685bdbef513e87562c20774a3a2) Thanks @mattiamanzati! - Fix missing encoding of path parameters in HttpApiClient\n\n- Updated dependencies [[`f570554`](https://github.com/Effect-TS/effect/commit/f57055459524587b041340577dad85476bb35f81), [`78047e8`](https://github.com/Effect-TS/effect/commit/78047e8dfc8005b66f87afe50bb95981fea51561)]:\n  - effect@3.15.4\n\n## 0.82.6\n\n### Patch Changes\n\n- [#4855](https://github.com/Effect-TS/effect/pull/4855) [`618903b`](https://github.com/Effect-TS/effect/commit/618903ba9ae96e2bfe6ee31f61c4359b915f2a36) Thanks @gcanti! - Enhance OpenAPI documentation handling by adding safe serialization and HTML escaping functions. This prevents script injection and ensures valid JSON output in the Swagger UI\n\n## 0.82.5\n\n### Patch Changes\n\n- [#4912](https://github.com/Effect-TS/effect/pull/4912) [`7764a07`](https://github.com/Effect-TS/effect/commit/7764a07d960c60df81f14e1dc949518f4bbe494a) Thanks @tim-smart! - add HttpClient.withScope, for tying the lifetime of the request to a Scope\n\n- [#4909](https://github.com/Effect-TS/effect/pull/4909) [`30a0d9c`](https://github.com/Effect-TS/effect/commit/30a0d9cb51c84290d51b1361d72ff5cee33c13c7) Thanks @tim-smart! - add HttpClientRequest.toUrl\n\n- Updated dependencies [[`4577f54`](https://github.com/Effect-TS/effect/commit/4577f548d67273e576cdde423bdd34a4b910766a)]:\n  - effect@3.15.3\n\n## 0.82.4\n\n### Patch Changes\n\n- [#4896](https://github.com/Effect-TS/effect/pull/4896) [`d45e8a8`](https://github.com/Effect-TS/effect/commit/d45e8a8ac8227192f504e39e6d04fdcf4fb1d225) Thanks @seniorkonung! - Handle `Respondable` defects in `toResponseOrElseDefect`\n\n- [#4890](https://github.com/Effect-TS/effect/pull/4890) [`d13b68e`](https://github.com/Effect-TS/effect/commit/d13b68e3a9456d0bfee9bca8273a7b44a9c69087) Thanks @KhraksMamtsov! - `Url.setPassword` supports `Redacted<string>` values\n\n## 0.82.3\n\n### Patch Changes\n\n- [#4889](https://github.com/Effect-TS/effect/pull/4889) [`a328f4b`](https://github.com/Effect-TS/effect/commit/a328f4b4fe717dd53e5b04a30f387433c32f7328) Thanks @tim-smart! - add HttpBody.formDataRecord\n\n- Updated dependencies [[`b8722b8`](https://github.com/Effect-TS/effect/commit/b8722b817e2306fe8c8245f3f9e32d85b824b961)]:\n  - effect@3.15.2\n\n## 0.82.2\n\n### Patch Changes\n\n- [#4882](https://github.com/Effect-TS/effect/pull/4882) [`739a3d4`](https://github.com/Effect-TS/effect/commit/739a3d4a4565915fe2e690003f4f9085cb4422fc) Thanks @tim-smart! - remove content headers for FormData bodies\n\n## 0.82.1\n\n### Patch Changes\n\n- Updated dependencies [[`787ce70`](https://github.com/Effect-TS/effect/commit/787ce7042e35b657963473c6efe47752868cd811), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348), [`1269641`](https://github.com/Effect-TS/effect/commit/1269641a99ae43069f7648ff79ffe8729b54b348)]:\n  - effect@3.15.1\n\n## 0.82.0\n\n### Minor Changes\n\n- [#4641](https://github.com/Effect-TS/effect/pull/4641) [`a9b3fb7`](https://github.com/Effect-TS/effect/commit/a9b3fb78abcfdb525318a956fd02fcadeb56143e) Thanks @thewilkybarkid! - Allow removing multiple Headers\n\n### Patch Changes\n\n- Updated dependencies [[`c654595`](https://github.com/Effect-TS/effect/commit/c65459587b51da140b78098e81fdbfece65d53e2), [`d9f5dea`](https://github.com/Effect-TS/effect/commit/d9f5deae0f02f5de2b9fcb1cca8b142ba4bc2bba), [`49aa723`](https://github.com/Effect-TS/effect/commit/49aa7236a15e13f818c86edbca08c4af67c8dfaf), [`74c14d0`](https://github.com/Effect-TS/effect/commit/74c14d01d0cb48cf517a1b6e29a373a96ed0ff5b), [`e4f49b6`](https://github.com/Effect-TS/effect/commit/e4f49b66857e01b74ab6a9a0bc7132f44cd04cbb), [`6f02224`](https://github.com/Effect-TS/effect/commit/6f02224b3fc46a682ad2defb1a260841956c6780), [`1dcfd41`](https://github.com/Effect-TS/effect/commit/1dcfd41ff96abd706901293a00c1893cb29dd8fd), [`b21ab16`](https://github.com/Effect-TS/effect/commit/b21ab16b6f773e7ec4369db4e752c35e719f7870), [`fcf1822`](https://github.com/Effect-TS/effect/commit/fcf1822f98fcda60351d64e9d2c2c13563d7e6db), [`0061dd1`](https://github.com/Effect-TS/effect/commit/0061dd140740165e91569a684cce27a77b23229e), [`8421e6e`](https://github.com/Effect-TS/effect/commit/8421e6e49332bca8f96f482dfd48680e238b3a89), [`fa10f56`](https://github.com/Effect-TS/effect/commit/fa10f56b96bd9af070ba99ebc3279aa93954261e)]:\n  - effect@3.15.0\n\n## 0.81.1\n\n### Patch Changes\n\n- Updated dependencies [[`24a9ebb`](https://github.com/Effect-TS/effect/commit/24a9ebbb5af598f0bfd6ecc45307e528043fe011)]:\n  - effect@3.14.22\n\n## 0.81.0\n\n### Minor Changes\n\n- [#4842](https://github.com/Effect-TS/effect/pull/4842) [`672920f`](https://github.com/Effect-TS/effect/commit/672920f85da8abd5f9d4ad85e29248a2aca57ed8) Thanks @tim-smart! - allow overriding http span names\n\n  ```ts\n  import { FetchHttpClient, HttpClient } from \"@effect/platform\"\n  import { NodeRuntime } from \"@effect/platform-node\"\n  import { Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    const client = (yield* HttpClient.HttpClient).pipe(\n      // Customize the span names for this HttpClient\n      HttpClient.withSpanNameGenerator(\n        (request) => `http.client ${request.method} ${request.url}`\n      )\n    )\n\n    yield* client.get(\"https://jsonplaceholder.typicode.com/posts/1\")\n  }).pipe(Effect.provide(FetchHttpClient.layer), NodeRuntime.runMain)\n  ```\n\n  And for a server:\n\n  ```ts\n  import {\n    HttpMiddleware,\n    HttpRouter,\n    HttpServer,\n    HttpServerResponse\n  } from \"@effect/platform\"\n  import { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\n  import { Layer } from \"effect\"\n  import { createServer } from \"http\"\n\n  HttpRouter.empty.pipe(\n    HttpRouter.get(\"/\", HttpServerResponse.empty()),\n    HttpServer.serve(),\n    // Customize the span names for this HttpApp\n    HttpMiddleware.withSpanNameGenerator((request) => `GET ${request.url}`),\n    Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })),\n    Layer.launch,\n    NodeRuntime.runMain\n  )\n  ```\n\n## 0.80.21\n\n### Patch Changes\n\n- Updated dependencies [[`2f3b7d4`](https://github.com/Effect-TS/effect/commit/2f3b7d4e1fa1ef8790b0ca4da22eb88872ee31df)]:\n  - effect@3.14.21\n\n## 0.80.20\n\n### Patch Changes\n\n- Updated dependencies [[`17e2f30`](https://github.com/Effect-TS/effect/commit/17e2f3091408cf0fca9414d4af3bdf7b2765b378)]:\n  - effect@3.14.20\n\n## 0.80.19\n\n### Patch Changes\n\n- [#4821](https://github.com/Effect-TS/effect/pull/4821) [`e25e7bb`](https://github.com/Effect-TS/effect/commit/e25e7bbc1797733916f48f501425d9f2ef310d9f) Thanks @seniorkonung! - Ensure HttpApp defects are always 500\n\n- Updated dependencies [[`056a910`](https://github.com/Effect-TS/effect/commit/056a910d0a0b8b00b0dc9df4a070466b2b5c2f6c), [`3273d57`](https://github.com/Effect-TS/effect/commit/3273d572c2b3175a842677f19efeea4cd65ab016)]:\n  - effect@3.14.19\n\n## 0.80.18\n\n### Patch Changes\n\n- Updated dependencies [[`b1164d4`](https://github.com/Effect-TS/effect/commit/b1164d49a1dfdf299e9971367b6fc6be4df0ddff)]:\n  - effect@3.14.18\n\n## 0.80.17\n\n### Patch Changes\n\n- Updated dependencies [[`0b54681`](https://github.com/Effect-TS/effect/commit/0b54681cd89245e211d8f49272be0f1bf2f81813), [`41a59d5`](https://github.com/Effect-TS/effect/commit/41a59d5916a296b12b0d5ead9e859e05f40b4cce)]:\n  - effect@3.14.17\n\n## 0.80.16\n\n### Patch Changes\n\n- [#4803](https://github.com/Effect-TS/effect/pull/4803) [`f1c8583`](https://github.com/Effect-TS/effect/commit/f1c8583f8c3ea9415f813795ca2940a897c9ba9a) Thanks @tim-smart! - expose uninteruptible option to HttpApiBuilder .handle apis\n\n- Updated dependencies [[`ee14444`](https://github.com/Effect-TS/effect/commit/ee144441021ec77039e43396eaf90714687bb495)]:\n  - effect@3.14.16\n\n## 0.80.15\n\n### Patch Changes\n\n- Updated dependencies [[`239cc99`](https://github.com/Effect-TS/effect/commit/239cc995ce645946210a3c3d2cb52bd3547c0687), [`8b6c947`](https://github.com/Effect-TS/effect/commit/8b6c947eaa8e45a67ecb3c37d45cd27f3e41d165), [`c50a63b`](https://github.com/Effect-TS/effect/commit/c50a63bbecb9f560b9cae349c447eed877d1b9b6)]:\n  - effect@3.14.15\n\n## 0.80.14\n\n### Patch Changes\n\n- Updated dependencies [[`6ed8d15`](https://github.com/Effect-TS/effect/commit/6ed8d1589beb181d30abc79afebdaabc1d101538)]:\n  - effect@3.14.14\n\n## 0.80.13\n\n### Patch Changes\n\n- Updated dependencies [[`ee77788`](https://github.com/Effect-TS/effect/commit/ee77788747e7ebbde6bfa88256cde49dbbad3608), [`5fce6ba`](https://github.com/Effect-TS/effect/commit/5fce6ba19c3cc63cc0104e737e581ad989dedbf0), [`570e45f`](https://github.com/Effect-TS/effect/commit/570e45f8cb936e42ec48f67f21bb2b7252f36c0c)]:\n  - effect@3.14.13\n\n## 0.80.12\n\n### Patch Changes\n\n- Updated dependencies [[`c2ad9ee`](https://github.com/Effect-TS/effect/commit/c2ad9ee9f3c4c743390edf35ed9e85a20be33811), [`9c68654`](https://github.com/Effect-TS/effect/commit/9c686542b6eb3ea188cb70673ef2e41223633e89)]:\n  - effect@3.14.12\n\n## 0.80.11\n\n### Patch Changes\n\n- Updated dependencies [[`e536127`](https://github.com/Effect-TS/effect/commit/e536127c1e6f2fb3a542c73ae919435a629a346b)]:\n  - effect@3.14.11\n\n## 0.80.10\n\n### Patch Changes\n\n- Updated dependencies [[`bc7efa3`](https://github.com/Effect-TS/effect/commit/bc7efa3b031bb25e1ed3c8f2d3fb5e8da166cadc)]:\n  - effect@3.14.10\n\n## 0.80.9\n\n### Patch Changes\n\n- Updated dependencies [[`d78249f`](https://github.com/Effect-TS/effect/commit/d78249f0b67f63cf4baf806ff090cba33293daf0)]:\n  - effect@3.14.9\n\n## 0.80.8\n\n### Patch Changes\n\n- Updated dependencies [[`b3a2d32`](https://github.com/Effect-TS/effect/commit/b3a2d32772e6f7f20eacf2e18128e99324c4d378)]:\n  - effect@3.14.8\n\n## 0.80.7\n\n### Patch Changes\n\n- Updated dependencies [[`b542a4b`](https://github.com/Effect-TS/effect/commit/b542a4bf195be0c9af1523e1ba96c953decc4d25)]:\n  - effect@3.14.7\n\n## 0.80.6\n\n### Patch Changes\n\n- Updated dependencies [[`47618c1`](https://github.com/Effect-TS/effect/commit/47618c1ad84ebcc5a51133a3fff5aa5012d49d45), [`6077882`](https://github.com/Effect-TS/effect/commit/60778824a4794336c33807801f813f8751d1c7e4)]:\n  - effect@3.14.6\n\n## 0.80.5\n\n### Patch Changes\n\n- [#4642](https://github.com/Effect-TS/effect/pull/4642) [`85fba81`](https://github.com/Effect-TS/effect/commit/85fba815ac07eb13d4227a69ac76a18e4b94df18) Thanks @nounder! - Fix options in `HttpServerResponse.raw`\n\n- Updated dependencies [[`40dbfef`](https://github.com/Effect-TS/effect/commit/40dbfeff239b6e567706752114f31b2fce7de4e3), [`5a5ebdd`](https://github.com/Effect-TS/effect/commit/5a5ebdddfaddd259538b4599a6676281faca778e)]:\n  - effect@3.14.5\n\n## 0.80.4\n\n### Patch Changes\n\n- Updated dependencies [[`e4ba2c6`](https://github.com/Effect-TS/effect/commit/e4ba2c66a878e81b5e295d6d49aaf724b80a28ef)]:\n  - effect@3.14.4\n\n## 0.80.3\n\n### Patch Changes\n\n- Updated dependencies [[`37aa8e1`](https://github.com/Effect-TS/effect/commit/37aa8e137725a902e70cd1e468ea98b873aa5056), [`34f03d6`](https://github.com/Effect-TS/effect/commit/34f03d66875f21f266f102223a03cd14c2ed6ea6)]:\n  - effect@3.14.3\n\n## 0.80.2\n\n### Patch Changes\n\n- Updated dependencies [[`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`f87991b`](https://github.com/Effect-TS/effect/commit/f87991b6d8a2edfaf90b01cebda4b466992ae865), [`0a3e3e1`](https://github.com/Effect-TS/effect/commit/0a3e3e18eea5e0d1882f1a6c906198e6ef226a41)]:\n  - effect@3.14.2\n\n## 0.80.1\n\n### Patch Changes\n\n- Updated dependencies [[`4a274fe`](https://github.com/Effect-TS/effect/commit/4a274fe9f623182b6b902827e0e83bd89ca3b05c)]:\n  - effect@3.14.1\n\n## 0.80.0\n\n### Minor Changes\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`3131f8f`](https://github.com/Effect-TS/effect/commit/3131f8fd12ba9eb31b90fa2f42bf88b12309133c) Thanks @tim-smart! - refactor of @effect/cluster packages\n\n### Patch Changes\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce) Thanks @tim-smart! - move the MsgPack, Ndjson & ChannelSchema modules to @effect/platform\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce) Thanks @tim-smart! - add HttpRouter.Tag.serve api\n\n- [#4469](https://github.com/Effect-TS/effect/pull/4469) [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce) Thanks @tim-smart! - Move SocketServer modules to @effect/platform\n\n- Updated dependencies [[`1f47e4e`](https://github.com/Effect-TS/effect/commit/1f47e4e12546ab691b29bfb7b5128bb17b93baa5), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`04dff2d`](https://github.com/Effect-TS/effect/commit/04dff2d01ac68c260f29a6d4743381825c353c86), [`c7fac0c`](https://github.com/Effect-TS/effect/commit/c7fac0cd7eadcd5cc0c3a987051c5b57ad271638), [`aba2d1d`](https://github.com/Effect-TS/effect/commit/aba2d1d831ea149481bd4dd755528c0afa8239ce), [`ffaa3f3`](https://github.com/Effect-TS/effect/commit/ffaa3f3969df26610fcc02ad537340641d44e803), [`ab957c1`](https://github.com/Effect-TS/effect/commit/ab957c1fee714868f56c7ab4e802b9d449e9b666), [`35db9ce`](https://github.com/Effect-TS/effect/commit/35db9ce228f1416c8abacc6dc9c36fbd0f33ef0f), [`cf77ea9`](https://github.com/Effect-TS/effect/commit/cf77ea9ab4fc89e66a43f682a9926ccdee6c57ed), [`26dd75f`](https://github.com/Effect-TS/effect/commit/26dd75f276a0d8a63eab313bd5a167d5072c9780), [`baaab60`](https://github.com/Effect-TS/effect/commit/baaab60b737f35dfab8e4a21bce28a195d19e899)]:\n  - effect@3.14.0\n\n## 0.79.4\n\n### Patch Changes\n\n- [#4592](https://github.com/Effect-TS/effect/pull/4592) [`5662363`](https://github.com/Effect-TS/effect/commit/566236361e270e575ef1cbf308ad1967c82a362c) Thanks @tim-smart! - support nested records in UrlParams module\n\n- [#4615](https://github.com/Effect-TS/effect/pull/4615) [`5f1fd15`](https://github.com/Effect-TS/effect/commit/5f1fd15308ab154791580059b89877d19a2055c2) Thanks @KhraksMamtsov! - - Relax `Url.setPort` constraint\n  - Use `URL | ...` for `baseUrl` in `HttpApiClient.make`\n\n- [#4614](https://github.com/Effect-TS/effect/pull/4614) [`8bb1460`](https://github.com/Effect-TS/effect/commit/8bb1460c824f66f0f25ebd899c5e74e388089c37) Thanks @gcanti! - HttpApiEndpoint: add missing `head` and `options` constructors, closes #4613.\n\n## 0.79.3\n\n### Patch Changes\n\n- Updated dependencies [[`0c4803f`](https://github.com/Effect-TS/effect/commit/0c4803fcc69262d11a97ce49d0e9b4288df0651f), [`6f65ac4`](https://github.com/Effect-TS/effect/commit/6f65ac4eac1489cd6ea390e18b0908670722adad)]:\n  - effect@3.13.12\n\n## 0.79.2\n\n### Patch Changes\n\n- Updated dependencies [[`fad8cca`](https://github.com/Effect-TS/effect/commit/fad8cca9bbfcc2eaeb44b97c15dbe0a1eda75315), [`4296293`](https://github.com/Effect-TS/effect/commit/4296293049414d0cf2d915a26c552b09f946b9a0), [`9c241ab`](https://github.com/Effect-TS/effect/commit/9c241abe47ccf7a5257b98a4a64a63054a12741d), [`082b0c1`](https://github.com/Effect-TS/effect/commit/082b0c1b9f4252bcdd69608f2e4a9226f953ac3f), [`be12983`](https://github.com/Effect-TS/effect/commit/be12983bc7e7537b41cd8910fc4eb7d1da56ab07), [`de88127`](https://github.com/Effect-TS/effect/commit/de88127a5a5906ccece98af74787b5ae0e65e431)]:\n  - effect@3.13.11\n\n## 0.79.1\n\n### Patch Changes\n\n- Updated dependencies [[`527c964`](https://github.com/Effect-TS/effect/commit/527c9645229f5be9714a7e60a38a9e753c4bbfb1)]:\n  - effect@3.13.10\n\n## 0.79.0\n\n### Minor Changes\n\n- [#4573](https://github.com/Effect-TS/effect/pull/4573) [`88fe129`](https://github.com/Effect-TS/effect/commit/88fe12923740765c0335a6e6203fdcc6a463edca) Thanks @tim-smart! - remove Scope from HttpClient requirements\n\n  Before:\n\n  ```ts\n  import { HttpClient } from \"@effect/platform\"\n  import { Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    const client = yield* HttpClient.HttpClient\n    const response = yield* client.get(\"https://api.github.com/users/octocat\")\n    return yield* response.json\n  }).pipe(Effect.scoped)\n  ```\n\n  After:\n\n  ```ts\n  import { HttpClient } from \"@effect/platform\"\n  import { Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    const client = yield* HttpClient.HttpClient\n    const response = yield* client.get(\"https://api.github.com/users/octocat\")\n    return yield* response.json\n  }) // no need to add Effect.scoped\n  ```\n\n### Patch Changes\n\n- [#4583](https://github.com/Effect-TS/effect/pull/4583) [`d630249`](https://github.com/Effect-TS/effect/commit/d630249426113088abe8b382db4f14d80f2160c2) Thanks @tim-smart! - support Layer.launch when using WorkerRunner\n\n- Updated dependencies [[`2976e52`](https://github.com/Effect-TS/effect/commit/2976e52538d9dc9ffdcbc84d4ac748cff9305971)]:\n  - effect@3.13.9\n\n## 0.78.1\n\n### Patch Changes\n\n- Updated dependencies [[`c65d336`](https://github.com/Effect-TS/effect/commit/c65d3362d07ec815ff3b46278314e8a31706ddc2), [`22d2ebb`](https://github.com/Effect-TS/effect/commit/22d2ebb4b11f5a44351a4736e65da391a3b647d0)]:\n  - effect@3.13.8\n\n## 0.78.0\n\n### Minor Changes\n\n- [#4562](https://github.com/Effect-TS/effect/pull/4562) [`c5bcf53`](https://github.com/Effect-TS/effect/commit/c5bcf53b7cb49dacffdd2a6cd8eb48cc452b417e) Thanks @tim-smart! - expose ParseError in HttpApiClient\n\n## 0.77.7\n\n### Patch Changes\n\n- [#4540](https://github.com/Effect-TS/effect/pull/4540) [`840cc73`](https://github.com/Effect-TS/effect/commit/840cc7329908db7ca693ef47b07d4f845c29cadd) Thanks @gcanti! - Add `additionalPropertiesStrategy` option to `OpenApi.fromApi`, closes #4531.\n\n  This update introduces the `additionalPropertiesStrategy` option in `OpenApi.fromApi`, allowing control over how additional properties are handled in the generated OpenAPI schema.\n  - When `\"strict\"` (default), additional properties are disallowed (`\"additionalProperties\": false`).\n  - When `\"allow\"`, additional properties are allowed (`\"additionalProperties\": true`), making APIs more flexible.\n\n  The `additionalPropertiesStrategy` option has also been added to:\n  - `JSONSchema.fromAST`\n  - `OpenApiJsonSchema.makeWithDefs`\n\n  **Example**\n\n  ```ts\n  import {\n    HttpApi,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    OpenApi\n  } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const api = HttpApi.make(\"api\").add(\n    HttpApiGroup.make(\"group\").add(\n      HttpApiEndpoint.get(\"get\", \"/\").addSuccess(\n        Schema.Struct({ a: Schema.String })\n      )\n    )\n  )\n\n  const schema = OpenApi.fromApi(api, {\n    additionalPropertiesStrategy: \"allow\"\n  })\n\n  console.log(JSON.stringify(schema, null, 2))\n  /*\n  {\n    \"openapi\": \"3.1.0\",\n    \"info\": {\n      \"title\": \"Api\",\n      \"version\": \"0.0.1\"\n    },\n    \"paths\": {\n      \"/\": {\n        \"get\": {\n          \"tags\": [\n            \"group\"\n          ],\n          \"operationId\": \"group.get\",\n          \"parameters\": [],\n          \"security\": [],\n          \"responses\": {\n            \"200\": {\n              \"description\": \"Success\",\n              \"content\": {\n                \"application/json\": {\n                  \"schema\": {\n                    \"type\": \"object\",\n                    \"required\": [\n                      \"a\"\n                    ],\n                    \"properties\": {\n                      \"a\": {\n                        \"type\": \"string\"\n                      }\n                    },\n                    \"additionalProperties\": true\n                  }\n                }\n              }\n            },\n            \"400\": {\n              \"description\": \"The request did not match the expected schema\",\n              \"content\": {\n                \"application/json\": {\n                  \"schema\": {\n                    \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    },\n    \"components\": {\n      \"schemas\": {\n        \"HttpApiDecodeError\": {\n          \"type\": \"object\",\n          \"required\": [\n            \"issues\",\n            \"message\",\n            \"_tag\"\n          ],\n          \"properties\": {\n            \"issues\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"$ref\": \"#/components/schemas/Issue\"\n              }\n            },\n            \"message\": {\n              \"type\": \"string\"\n            },\n            \"_tag\": {\n              \"type\": \"string\",\n              \"enum\": [\n                \"HttpApiDecodeError\"\n              ]\n            }\n          },\n          \"additionalProperties\": true,\n          \"description\": \"The request did not match the expected schema\"\n        },\n        \"Issue\": {\n          \"type\": \"object\",\n          \"required\": [\n            \"_tag\",\n            \"path\",\n            \"message\"\n          ],\n          \"properties\": {\n            \"_tag\": {\n              \"type\": \"string\",\n              \"enum\": [\n                \"Pointer\",\n                \"Unexpected\",\n                \"Missing\",\n                \"Composite\",\n                \"Refinement\",\n                \"Transformation\",\n                \"Type\",\n                \"Forbidden\"\n              ],\n              \"description\": \"The tag identifying the type of parse issue\"\n            },\n            \"path\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"$ref\": \"#/components/schemas/PropertyKey\"\n              },\n              \"description\": \"The path to the property where the issue occurred\"\n            },\n            \"message\": {\n              \"type\": \"string\",\n              \"description\": \"A descriptive message explaining the issue\"\n            }\n          },\n          \"additionalProperties\": true,\n          \"description\": \"Represents an error encountered while parsing a value to match the schema\"\n        },\n        \"PropertyKey\": {\n          \"anyOf\": [\n            {\n              \"type\": \"string\"\n            },\n            {\n              \"type\": \"number\"\n            },\n            {\n              \"type\": \"object\",\n              \"required\": [\n                \"_tag\",\n                \"key\"\n              ],\n              \"properties\": {\n                \"_tag\": {\n                  \"type\": \"string\",\n                  \"enum\": [\n                    \"symbol\"\n                  ]\n                },\n                \"key\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"additionalProperties\": true,\n              \"description\": \"an object to be decoded into a globally shared symbol\"\n            }\n          ]\n        }\n      },\n      \"securitySchemes\": {}\n    },\n    \"security\": [],\n    \"tags\": [\n      {\n        \"name\": \"group\"\n      }\n    ]\n  }\n  */\n  ```\n\n- [#4541](https://github.com/Effect-TS/effect/pull/4541) [`9bf8a74`](https://github.com/Effect-TS/effect/commit/9bf8a74b967f18d931743dd5196af326c9118e9c) Thanks @fubhy! - Disallowed excess properties for various function options\n\n- [#4559](https://github.com/Effect-TS/effect/pull/4559) [`f910880`](https://github.com/Effect-TS/effect/commit/f91088069057f3b4529753f5bc5532b028d726df) Thanks @tim-smart! - add additional properties options to HttpApiBuilder.middlewareOpenApi\n\n- [#4493](https://github.com/Effect-TS/effect/pull/4493) [`0d01480`](https://github.com/Effect-TS/effect/commit/0d014803e4f688f74386a80abd65485e1a319244) Thanks @leonitousconforti! - FetchHttpClient merge headers from request and requestInit\n\n- Updated dependencies [[`840cc73`](https://github.com/Effect-TS/effect/commit/840cc7329908db7ca693ef47b07d4f845c29cadd), [`9bf8a74`](https://github.com/Effect-TS/effect/commit/9bf8a74b967f18d931743dd5196af326c9118e9c), [`87ba23c`](https://github.com/Effect-TS/effect/commit/87ba23c41c193503ed0c612b0d32d0b253794c64)]:\n  - effect@3.13.7\n\n## 0.77.6\n\n### Patch Changes\n\n- Updated dependencies [[`3154ce4`](https://github.com/Effect-TS/effect/commit/3154ce4692fa18b804982158d3c4c8a8a5fae386)]:\n  - effect@3.13.6\n\n## 0.77.5\n\n### Patch Changes\n\n- Updated dependencies [[`367bb35`](https://github.com/Effect-TS/effect/commit/367bb35f4c2a254e1fb211d96db2474a7aed9020), [`6cf11c3`](https://github.com/Effect-TS/effect/commit/6cf11c3a75773ceec2877c85ddc760f381f0866d), [`a0acec8`](https://github.com/Effect-TS/effect/commit/a0acec851f72e19466363d24b9cc218acd00006a)]:\n  - effect@3.13.5\n\n## 0.77.4\n\n### Patch Changes\n\n- [#4525](https://github.com/Effect-TS/effect/pull/4525) [`e0746f9`](https://github.com/Effect-TS/effect/commit/e0746f9aa398b69c6542e375910683bf17f49f46) Thanks @anderssjoberg97! - Fix w3c traceparent header parsing\n\n- Updated dependencies [[`17d9e89`](https://github.com/Effect-TS/effect/commit/17d9e89f9851663bdbb6c1e685601d97806114a4)]:\n  - effect@3.13.4\n\n## 0.77.3\n\n### Patch Changes\n\n- Updated dependencies [[`cc5588d`](https://github.com/Effect-TS/effect/commit/cc5588df07f9103513547cb429ce041b9436a8bd), [`623c8cd`](https://github.com/Effect-TS/effect/commit/623c8cd053ed6ee3d353aaa8778d484670fca2bb), [`00b4eb1`](https://github.com/Effect-TS/effect/commit/00b4eb1ece12a16e222e6220965bb4024d6752ac), [`f2aee98`](https://github.com/Effect-TS/effect/commit/f2aee989b0a600900ce83e7f460d02908620c80f), [`fb798eb`](https://github.com/Effect-TS/effect/commit/fb798eb9061f1191badc017d1aa649360254da20), [`2251b15`](https://github.com/Effect-TS/effect/commit/2251b1528810bb695b37ce388b653cec0c5bf80c), [`2e15c1e`](https://github.com/Effect-TS/effect/commit/2e15c1e33648add0b29fe274fbcb7294b7515085), [`a4979db`](https://github.com/Effect-TS/effect/commit/a4979db021aef16e731be64df196b72088fc4376), [`b74255a`](https://github.com/Effect-TS/effect/commit/b74255a304ad49d60bedb1a260fd697f370af27a), [`d7f6a5c`](https://github.com/Effect-TS/effect/commit/d7f6a5c7d26c1963dcd864ca62360d20d08c7b49), [`9dd8979`](https://github.com/Effect-TS/effect/commit/9dd8979e940915b1cc1b1f264f3d019c77a65a02), [`477b488`](https://github.com/Effect-TS/effect/commit/477b488284f47c5469d7fba3e4065fb7e3b6556e), [`10932cb`](https://github.com/Effect-TS/effect/commit/10932cbf58fc721ada631cebec42f773ce96d3cc), [`9f6c784`](https://github.com/Effect-TS/effect/commit/9f6c78468b3b5e9ebfc38ffdfb70702901ee977b), [`2c639ec`](https://github.com/Effect-TS/effect/commit/2c639ecee332de4266e36022c989c35ae4e02105), [`886aaa8`](https://github.com/Effect-TS/effect/commit/886aaa81e06dfd3cd9391e8ea987d8cd5ada1124)]:\n  - effect@3.13.3\n\n## 0.77.2\n\n### Patch Changes\n\n- [#4456](https://github.com/Effect-TS/effect/pull/4456) [`3e7ce97`](https://github.com/Effect-TS/effect/commit/3e7ce97f8a41756a039cf635d0b3d9a75d781097) Thanks @tim-smart! - ensure key for header security is lower case\n\n- [#4472](https://github.com/Effect-TS/effect/pull/4472) [`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f) Thanks @gcanti! - Add support for `Schema.Enums` in `HttpApiBuilder.isSingleStringType`, closes #4471.\n\n- Updated dependencies [[`31be72a`](https://github.com/Effect-TS/effect/commit/31be72ada118cb84a942e67b1663263f8db74a9f)]:\n  - effect@3.13.2\n\n## 0.77.1\n\n### Patch Changes\n\n- Updated dependencies [[`b56a211`](https://github.com/Effect-TS/effect/commit/b56a2110569fd0ec0b57ac137743e926d49f51cc)]:\n  - effect@3.13.1\n\n## 0.77.0\n\n### Patch Changes\n\n- Updated dependencies [[`8baef83`](https://github.com/Effect-TS/effect/commit/8baef83e7ff0b7bc0738b680e1ef013065386cff), [`655bfe2`](https://github.com/Effect-TS/effect/commit/655bfe29e44cc3f0fb9b4e53038f50b891c188df), [`d90cbc2`](https://github.com/Effect-TS/effect/commit/d90cbc274e2742d18671fe65aa4764c057eb6cba), [`75632bd`](https://github.com/Effect-TS/effect/commit/75632bd44b8025101d652ccbaeef898c7086c91c), [`c874a2e`](https://github.com/Effect-TS/effect/commit/c874a2e4b17e9d71904ca8375bb77b020975cb1d), [`bf865e5`](https://github.com/Effect-TS/effect/commit/bf865e5833f77fd8f6c06944ca9d507b54488301), [`f98b2b7`](https://github.com/Effect-TS/effect/commit/f98b2b7592cf20f9d85313e7f1e964cb65878138), [`de8ce92`](https://github.com/Effect-TS/effect/commit/de8ce924923eaa4e1b761a97eb45ec967389f3d5), [`cf8b2dd`](https://github.com/Effect-TS/effect/commit/cf8b2dd112f8e092ed99d78fd728db0f91c29050), [`db426a5`](https://github.com/Effect-TS/effect/commit/db426a5fb41ab84d18e3c8753a7329b4de544245), [`6862444`](https://github.com/Effect-TS/effect/commit/6862444094906ad4f2cb077ff3b9cc0b73880c8c), [`5fc8a90`](https://github.com/Effect-TS/effect/commit/5fc8a90ba46a5fd9f3b643f0b5aeadc69d717339), [`546a492`](https://github.com/Effect-TS/effect/commit/546a492e60eb2b8b048a489a474b934ea0877005), [`65c4796`](https://github.com/Effect-TS/effect/commit/65c47966ce39055f02cf5c808daabb3ea6442b0b), [`9760fdc`](https://github.com/Effect-TS/effect/commit/9760fdc37bdaef9da8b150e46b86ddfbe2ad9221), [`5b471e7`](https://github.com/Effect-TS/effect/commit/5b471e7d4317e8ee5d72bbbd3e0c9775160949ab), [`4f810cc`](https://github.com/Effect-TS/effect/commit/4f810cc2770e9f1f266851d2cb6257112c12af49)]:\n  - effect@3.13.0\n\n## 0.76.1\n\n### Patch Changes\n\n- [#4444](https://github.com/Effect-TS/effect/pull/4444) [`c407726`](https://github.com/Effect-TS/effect/commit/c407726f79df4a567a9631cddd8effaa16b3535d) Thanks @gcanti! - HttpApiBuilder: URL parameters are now automatically converted to arrays when needed, closes #4442.\n\n  **Example**\n\n  ```ts\n  import {\n    HttpApi,\n    HttpApiBuilder,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    HttpMiddleware,\n    HttpServer\n  } from \"@effect/platform\"\n  import { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\n  import { Effect, Layer, Schema } from \"effect\"\n  import { createServer } from \"node:http\"\n\n  const api = HttpApi.make(\"api\").add(\n    HttpApiGroup.make(\"group\").add(\n      HttpApiEndpoint.get(\"get\", \"/\")\n        .addSuccess(Schema.String)\n        .setUrlParams(\n          Schema.Struct({\n            param: Schema.NonEmptyArray(Schema.String)\n          })\n        )\n    )\n  )\n\n  const usersGroupLive = HttpApiBuilder.group(api, \"group\", (handlers) =>\n    handlers.handle(\"get\", (req) =>\n      Effect.succeed(req.urlParams.param.join(\", \"))\n    )\n  )\n\n  const MyApiLive = HttpApiBuilder.api(api).pipe(Layer.provide(usersGroupLive))\n\n  const HttpLive = HttpApiBuilder.serve(HttpMiddleware.logger).pipe(\n    Layer.provide(MyApiLive),\n    HttpServer.withLogAddress,\n    Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n  )\n\n  Layer.launch(HttpLive).pipe(NodeRuntime.runMain)\n  ```\n\n  Previously, if a query parameter was defined as a `NonEmptyArray` (an array that requires at least one element), providing a single value would cause a parsing error.\n\n  For example, this worked fine:\n\n  ```sh\n  curl \"http://localhost:3000/?param=1&param=2\"\n  ```\n\n  But this would fail:\n\n  ```sh\n  curl \"http://localhost:3000/?param=1\"\n  ```\n\n  Resulting in an error because `\"1\"` was treated as a string instead of an array.\n\n  With this update, single values are automatically wrapped in an array, so they match the expected schema without requiring manual fixes.\n\n- Updated dependencies [[`4018eae`](https://github.com/Effect-TS/effect/commit/4018eaed2733241676ddb8c52416f463a8c32e35), [`543d36d`](https://github.com/Effect-TS/effect/commit/543d36d1a11452560b01ab966a82529ad5fee8c9), [`f70a65a`](https://github.com/Effect-TS/effect/commit/f70a65ac80c6635d80b12beaf4d32a9cc59fa143), [`ba409f6`](https://github.com/Effect-TS/effect/commit/ba409f69c41aeaa29e475c0630735726eaf4dbac), [`3d2e356`](https://github.com/Effect-TS/effect/commit/3d2e3565e8a43d1bdb5daee8db3b90f56d71d859)]:\n  - effect@3.12.12\n\n## 0.76.0\n\n### Minor Changes\n\n- [#4429](https://github.com/Effect-TS/effect/pull/4429) [`2473ad5`](https://github.com/Effect-TS/effect/commit/2473ad5cf23582e3a41338091fa526ffe611288d) Thanks @tim-smart! - run platform workers in a Scope, send errors or termination to a CloseLatch\n\n### Patch Changes\n\n- Updated dependencies [[`b6a032f`](https://github.com/Effect-TS/effect/commit/b6a032f07bffa020a848c813881879395134fa20), [`42ddd5f`](https://github.com/Effect-TS/effect/commit/42ddd5f144ce9f9d94a036679ebbd626446d37f5), [`2fe447c`](https://github.com/Effect-TS/effect/commit/2fe447c6354d334f9c591b8a8481818f5f0e797e)]:\n  - effect@3.12.11\n\n## 0.75.4\n\n### Patch Changes\n\n- [#4416](https://github.com/Effect-TS/effect/pull/4416) [`7d57ecd`](https://github.com/Effect-TS/effect/commit/7d57ecdaf5da2345ebbf9c22df50317578bde0f5) Thanks @tim-smart! - add HttpServerResponse.mergeCookies\n\n- Updated dependencies [[`e30f132`](https://github.com/Effect-TS/effect/commit/e30f132c336c9d0760bad39f82a55c7ce5159eb7), [`33fa667`](https://github.com/Effect-TS/effect/commit/33fa667c2623be1026e1ccee91bd44f73b09020a), [`87f5f28`](https://github.com/Effect-TS/effect/commit/87f5f2842e4196cb88d13f10f443ff0567e82832), [`4dbd170`](https://github.com/Effect-TS/effect/commit/4dbd170538e8fb7a36aa7c469c6f93b6c7000091)]:\n  - effect@3.12.10\n\n## 0.75.3\n\n### Patch Changes\n\n- Updated dependencies [[`1b4a4e9`](https://github.com/Effect-TS/effect/commit/1b4a4e904ef5227ec7d9114d4e417eca19eed940)]:\n  - effect@3.12.9\n\n## 0.75.2\n\n### Patch Changes\n\n- [#4334](https://github.com/Effect-TS/effect/pull/4334) [`59b3cfb`](https://github.com/Effect-TS/effect/commit/59b3cfbbd5713dd9475998e95fad5534c0b21466) Thanks @gcanti! - Cookies: `unsafeMakeCookie` and `unsafeSetAll` now throw a more informative error instead of a generic one\n\n- [#4360](https://github.com/Effect-TS/effect/pull/4360) [`bb05fb8`](https://github.com/Effect-TS/effect/commit/bb05fb83457355b1ca567228a9e041edfb6fd85d) Thanks @IMax153! - Ensure that nested configuration values can be properly loaded from an env file\n\n- [#4353](https://github.com/Effect-TS/effect/pull/4353) [`8f6006a`](https://github.com/Effect-TS/effect/commit/8f6006a610fb6d6c7b8d14209a7323338a8964ff) Thanks @tim-smart! - fix HttpServerRequest.arrayBuffer for bun & web handlers\n\n- [#4380](https://github.com/Effect-TS/effect/pull/4380) [`c45b559`](https://github.com/Effect-TS/effect/commit/c45b5592b5fd1189a5c932cfe05bd7d5f6d68508) Thanks @fubhy! - Fixed module imports\n\n- [#4345](https://github.com/Effect-TS/effect/pull/4345) [`c9175ae`](https://github.com/Effect-TS/effect/commit/c9175aef41cb1e3b689d0ac0a4f53d8107376b58) Thanks @ethanniser! - Addition of `sync` property to `FileSystem.File` representing the `fsync` syscall.\n\n- Updated dependencies [[`766113c`](https://github.com/Effect-TS/effect/commit/766113c0ea3512cdb887650ead8ba314236e22ee), [`712277f`](https://github.com/Effect-TS/effect/commit/712277f949052a24b46e4aa234063a6abf395c90), [`f269122`](https://github.com/Effect-TS/effect/commit/f269122508693b111142994dd48698ddc75f3d69), [`430c846`](https://github.com/Effect-TS/effect/commit/430c846cbac05b187e3d24ac8dfee0cf22506f7c), [`7b03057`](https://github.com/Effect-TS/effect/commit/7b03057507d2dab5e6793beb9c578dedaaeb15fe), [`a9c94c8`](https://github.com/Effect-TS/effect/commit/a9c94c807755610831211a686d2fad849ab38eb4), [`107e6f0`](https://github.com/Effect-TS/effect/commit/107e6f0557a1e2d3b0dce25d62fa1e2601521752), [`65c11b9`](https://github.com/Effect-TS/effect/commit/65c11b9266ec9447c31c26fe3ed35c73bd3b81fd), [`e386d2f`](https://github.com/Effect-TS/effect/commit/e386d2f1b3ab3ac2c14ee76de11f5963d32a3df4), [`9172efb`](https://github.com/Effect-TS/effect/commit/9172efba98bc6a82353e6ec2af61ac08f038ba64)]:\n  - effect@3.12.8\n\n## 0.75.1\n\n### Patch Changes\n\n- Updated dependencies [[`8dff1d1`](https://github.com/Effect-TS/effect/commit/8dff1d1bff76cdba643cad7f0bf864300f08bc61)]:\n  - effect@3.12.7\n\n## 0.75.0\n\n### Minor Changes\n\n- [#4306](https://github.com/Effect-TS/effect/pull/4306) [`5e43ce5`](https://github.com/Effect-TS/effect/commit/5e43ce50bae116865906112e7f88d390739d778b) Thanks @tim-smart! - eliminate Scope by default in some layer apis\n\n### Patch Changes\n\n- [#4304](https://github.com/Effect-TS/effect/pull/4304) [`76eb7d0`](https://github.com/Effect-TS/effect/commit/76eb7d0fbce3c009c8f77e84c178cb15bbed9709) Thanks @tim-smart! - ensure toWebHandler context argument is a Context before using it\n\n  Fixes issues with next.js where they supply a different second argument to request handlers\n\n- [#4286](https://github.com/Effect-TS/effect/pull/4286) [`eb264ed`](https://github.com/Effect-TS/effect/commit/eb264ed8a6e8c92a9dc7006f766c6ca2e5d29e03) Thanks @thewilkybarkid! - Fix following relative locations\n\n- Updated dependencies [[`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`8b4e75d`](https://github.com/Effect-TS/effect/commit/8b4e75d35daea807c447ca760948a717aa66bb52), [`fc5e0f0`](https://github.com/Effect-TS/effect/commit/fc5e0f0d357a0051cfa01c1ede83ffdd3cb41ab1), [`004fd2b`](https://github.com/Effect-TS/effect/commit/004fd2bbd1459e64fb1b57f02eeb791ca5ea1ea5), [`b2a31be`](https://github.com/Effect-TS/effect/commit/b2a31be85c35d891351ce4f9a2cc93ece0c257f6), [`5514d05`](https://github.com/Effect-TS/effect/commit/5514d05b5cd586ff5868b8bd41c959e95e6c33cd), [`bf5f0ae`](https://github.com/Effect-TS/effect/commit/bf5f0ae9daa0170471678e22585e8ec14ce667bb), [`3b19bcf`](https://github.com/Effect-TS/effect/commit/3b19bcfd3aaadb6c9253428622df524537c8e626), [`b064b3b`](https://github.com/Effect-TS/effect/commit/b064b3b293615fd268cc5a5647d0981eb67750b8), [`289c13b`](https://github.com/Effect-TS/effect/commit/289c13b38e8e35b214d46d385d05dead176c87cd), [`f474678`](https://github.com/Effect-TS/effect/commit/f474678bf10b8f1c80e3dc096ddc7ecf20b2b23e), [`ee187d0`](https://github.com/Effect-TS/effect/commit/ee187d098007a402844c94d04f0cd8f07695377a)]:\n  - effect@3.12.6\n\n## 0.74.0\n\n### Minor Changes\n\n- [#4264](https://github.com/Effect-TS/effect/pull/4264) [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e) Thanks @gcanti! - Add support for symbols in the `Issue` definition within `platform/HttpApiError`.\n\n### Patch Changes\n\n- [#4277](https://github.com/Effect-TS/effect/pull/4277) [`8653072`](https://github.com/Effect-TS/effect/commit/86530720d7a03e118d2c5a8bf5a997cee7e7f3d6) Thanks @tim-smart! - simplify HttpApi path regex for parameters\n\n  HttpApi path parameters now only support the following syntax:\n\n  `:parameterName`\n\n  Conditional parameters are no longer supported (i.e. using `?` etc after the\n  parameter name).\n\n- Updated dependencies [[`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`507d546`](https://github.com/Effect-TS/effect/commit/507d546bd49db31000425fb5da88c434e4291bea), [`a8b0ddb`](https://github.com/Effect-TS/effect/commit/a8b0ddb84710054799fc8f57485b95d00093ada1), [`8db239b`](https://github.com/Effect-TS/effect/commit/8db239b9c869a3707f6566b9d9dbdf53c4df03fc), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`84a0911`](https://github.com/Effect-TS/effect/commit/84a091181634c3a022c94234cec7764a3aeef1be), [`3179a9f`](https://github.com/Effect-TS/effect/commit/3179a9f65d23369a6a9a1f80f7750566dd28df22), [`6cb9b76`](https://github.com/Effect-TS/effect/commit/6cb9b766396d0b2ed995cf26957359713efd202e), [`1fcbe55`](https://github.com/Effect-TS/effect/commit/1fcbe55345042d8468f6a98c84081bd00b6bcf5a), [`d9a63d9`](https://github.com/Effect-TS/effect/commit/d9a63d9d385653865954cac895065360d54cc56b)]:\n  - effect@3.12.5\n\n## 0.73.1\n\n### Patch Changes\n\n- [#4250](https://github.com/Effect-TS/effect/pull/4250) [`c9e5e1b`](https://github.com/Effect-TS/effect/commit/c9e5e1be17c0c84d3d4e2abc3c60215cdb56bbbe) Thanks @thewilkybarkid! - Add isHttpMethod refinement\n\n- [#4225](https://github.com/Effect-TS/effect/pull/4225) [`7b3d58d`](https://github.com/Effect-TS/effect/commit/7b3d58d7aec2152ec282460871d3e9de45ed254d) Thanks @thewilkybarkid! - Add HttpClient.tapError\n\n- Updated dependencies [[`5b50ea4`](https://github.com/Effect-TS/effect/commit/5b50ea4a10cf9acd51f9624b2474d9d5ded74019), [`c170a68`](https://github.com/Effect-TS/effect/commit/c170a68b6266100774461fcd6c0e0fabb60112f2), [`a66c2eb`](https://github.com/Effect-TS/effect/commit/a66c2eb473245092cd41f04c2eb2b7b02cf53718)]:\n  - effect@3.12.4\n\n## 0.73.0\n\n### Minor Changes\n\n- [#4245](https://github.com/Effect-TS/effect/pull/4245) [`c110032`](https://github.com/Effect-TS/effect/commit/c110032322450a8824ba38ae24335a538cd2ce9a) Thanks @gcanti! - Update `HttpApi` to remove wildcard support for better OpenAPI compatibility.\n\n  The `HttpApi*` modules previously reused the following type from `HttpRouter`:\n\n  ```ts\n  type PathInput = `/${string}` | \"*\"\n  ```\n\n  However, the `\"*\"` wildcard value was not handled correctly, as OpenAPI does not support wildcards.\n\n  This has been updated to use a more specific type:\n\n  ```ts\n  type PathSegment = `/${string}`\n  ```\n\n  This change ensures better alignment with OpenAPI specifications and eliminates potential issues related to unsupported wildcard paths.\n\n- [#4237](https://github.com/Effect-TS/effect/pull/4237) [`23ac740`](https://github.com/Effect-TS/effect/commit/23ac740c7dd4610b7d265c2071b88b0968419e9a) Thanks @gcanti! - Make `OpenApiSpec` mutable to make handling it more convenient.\n\n### Patch Changes\n\n- [#4177](https://github.com/Effect-TS/effect/pull/4177) [`8cd7319`](https://github.com/Effect-TS/effect/commit/8cd7319b6568bfc7a30ca16c104d189e37eac3a0) Thanks @KhraksMamtsov! - `Url` module has been introduced:\n  - immutable setters with dual-function api\n  - integration with `UrlParams`\n\n- Updated dependencies [[`d7dac48`](https://github.com/Effect-TS/effect/commit/d7dac48a477cdfeec509dbe9f33fce6a1b02b63d), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5), [`1d7fd2b`](https://github.com/Effect-TS/effect/commit/1d7fd2b7ee8eeecc912d27adf76ed897db236dc5)]:\n  - effect@3.12.3\n\n## 0.72.2\n\n### Patch Changes\n\n- [#4226](https://github.com/Effect-TS/effect/pull/4226) [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a) Thanks @gcanti! - Ensure the encoding kind of success responses is respected in the OpenAPI spec.\n\n  Before\n\n  When generating an OpenAPI spec for a request with a success schema of type `HttpApiSchema.Text()``, the response content type was incorrectly set to \"application/json\" instead of \"text/plain\".\n\n  ```ts\n  import {\n    HttpApi,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    HttpApiSchema,\n    OpenApi\n  } from \"@effect/platform\"\n\n  const api = HttpApi.make(\"api\").add(\n    HttpApiGroup.make(\"group\").add(\n      HttpApiEndpoint.get(\"get\", \"/\").addSuccess(HttpApiSchema.Text())\n    )\n  )\n\n  const spec = OpenApi.fromApi(api)\n\n  console.log(JSON.stringify(spec.paths, null, 2))\n  /*\n  Output:\n  {\n    \"/\": {\n      \"get\": {\n        \"tags\": [\n          \"group\"\n        ],\n        \"operationId\": \"group.get\",\n        \"parameters\": [],\n        \"security\": [],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"a string\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"The request did not match the expected schema\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  */\n  ```\n\n  After\n\n  ```diff\n  import {\n    HttpApi,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    HttpApiSchema,\n    OpenApi\n  } from \"@effect/platform\"\n\n  const api = HttpApi.make(\"api\").add(\n    HttpApiGroup.make(\"group\").add(\n      HttpApiEndpoint.get(\"get\", \"/\").addSuccess(HttpApiSchema.Text())\n    )\n  )\n\n  const spec = OpenApi.fromApi(api)\n\n  console.log(JSON.stringify(spec.paths, null, 2))\n  /*\n  Output:\n  {\n    \"/\": {\n      \"get\": {\n        \"tags\": [\n          \"group\"\n        ],\n        \"operationId\": \"group.get\",\n        \"parameters\": [],\n        \"security\": [],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"a string\",\n            \"content\": {\n  -            \"application/json\": {\n  +            \"text/plain\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"The request did not match the expected schema\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  */\n  ```\n\n- [#4234](https://github.com/Effect-TS/effect/pull/4234) [`f852cb0`](https://github.com/Effect-TS/effect/commit/f852cb02040ea2f165e9b449615b8b1366add5d5) Thanks @gcanti! - Deduplicate errors in `OpenApi.fromApi`.\n\n  When multiple identical errors were added to the same endpoint, group, or API, they were all included in the generated OpenAPI specification, leading to redundant entries in the `anyOf` array for error schemas.\n\n  Identical errors are now deduplicated in the OpenAPI specification. This ensures that each error schema is included only once, simplifying the generated spec and improving readability.\n\n  **Before**\n\n  ```ts\n  import {\n    HttpApi,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    OpenApi\n  } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const err = Schema.String.annotations({ identifier: \"err\" })\n  const api = HttpApi.make(\"api\")\n    .add(\n      HttpApiGroup.make(\"group1\")\n        .add(\n          HttpApiEndpoint.get(\"get1\", \"/1\")\n            .addSuccess(Schema.String)\n            .addError(err)\n            .addError(err)\n        )\n        .addError(err)\n        .addError(err)\n    )\n    .addError(err)\n    .addError(err)\n\n  const spec = OpenApi.fromApi(api)\n\n  console.log(JSON.stringify(spec.paths, null, 2))\n  /*\n  Output:\n  {\n    \"/1\": {\n      \"get\": {\n        \"tags\": [\n          \"group1\"\n        ],\n        \"operationId\": \"group1.get1\",\n        \"parameters\": [],\n        \"security\": [],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"a string\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"The request did not match the expected schema\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                }\n              }\n            }\n          },\n          \"500\": {\n            \"description\": \"a string\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": \"schema\": {\n                  \"anyOf\": [\n                    {\n                      \"$ref\": \"#/components/schemas/err\"\n                    },\n                    {\n                      \"$ref\": \"#/components/schemas/err\"\n                    },\n                    {\n                      \"$ref\": \"#/components/schemas/err\"\n                    }\n                  ]\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  */\n  ```\n\n  **After**\n\n  ```ts\n  import {\n    HttpApi,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    OpenApi\n  } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const err = Schema.String.annotations({ identifier: \"err\" })\n  const api = HttpApi.make(\"api\")\n    .add(\n      HttpApiGroup.make(\"group1\")\n        .add(\n          HttpApiEndpoint.get(\"get1\", \"/1\")\n            .addSuccess(Schema.String)\n            .addError(err)\n            .addError(err)\n        )\n        .addError(err)\n        .addError(err)\n    )\n    .addError(err)\n    .addError(err)\n\n  const spec = OpenApi.fromApi(api)\n\n  console.log(JSON.stringify(spec.paths, null, 2))\n  /*\n  Output:\n  {\n    \"/1\": {\n      \"get\": {\n        \"tags\": [\n          \"group1\"\n        ],\n        \"operationId\": \"group1.get1\",\n        \"parameters\": [],\n        \"security\": [],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"a string\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"The request did not match the expected schema\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                }\n              }\n            }\n          },\n          \"500\": {\n            \"description\": \"a string\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/err\"\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  */\n  ```\n\n- [#4233](https://github.com/Effect-TS/effect/pull/4233) [`7276ae2`](https://github.com/Effect-TS/effect/commit/7276ae21062896adbb7508ac5b2dece95316322f) Thanks @gcanti! - Ensure the encoding kind of error responses is respected in the OpenAPI spec.\n\n  Before\n\n  When generating an OpenAPI spec for a request with an error schema of type `HttpApiSchema.Text()``, the response content type was incorrectly set to \"application/json\" instead of \"text/plain\".\n\n  ```ts\n  import {\n    HttpApi,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    HttpApiSchema,\n    OpenApi\n  } from \"@effect/platform\"\n\n  const api = HttpApi.make(\"api\").add(\n    HttpApiGroup.make(\"group\").add(\n      HttpApiEndpoint.get(\"get\", \"/\").addError(HttpApiSchema.Text())\n    )\n  )\n\n  const spec = OpenApi.fromApi(api)\n\n  console.log(JSON.stringify(spec.paths, null, 2))\n  /*\n  Output:\n  {\n    \"/\": {\n      \"get\": {\n        \"tags\": [\n          \"group\"\n        ],\n        \"operationId\": \"group.get\",\n        \"parameters\": [],\n        \"security\": [],\n        \"responses\": {\n          \"204\": {\n            \"description\": \"Success\"\n          },\n          \"400\": {\n            \"description\": \"The request did not match the expected schema\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                }\n              }\n            }\n          },\n          \"500\": {\n            \"description\": \"a string\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  */\n  ```\n\n  After\n\n  ```diff\n  import { HttpApi, HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from \"@effect/platform\"\n\n  const api = HttpApi.make(\"api\").add(\n    HttpApiGroup.make(\"group\").add(\n      HttpApiEndpoint.get(\"get\", \"/\").addError(HttpApiSchema.Text())\n    )\n  )\n\n  const spec = OpenApi.fromApi(api)\n\n  console.log(JSON.stringify(spec.paths, null, 2))\n  /*\n  Output:\n  {\n    \"/\": {\n      \"get\": {\n        \"tags\": [\n          \"group\"\n        ],\n        \"operationId\": \"group.get\",\n        \"parameters\": [],\n        \"security\": [],\n        \"responses\": {\n          \"204\": {\n            \"description\": \"Success\"\n          },\n          \"400\": {\n            \"description\": \"The request did not match the expected schema\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                }\n              }\n            }\n          },\n          \"500\": {\n            \"description\": \"a string\",\n            \"content\": {\n  +            \"text/plain\": {\n  -            \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  */\n  ```\n\n- [#4226](https://github.com/Effect-TS/effect/pull/4226) [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a) Thanks @gcanti! - Add missing `deprecated` key to `OpenApi.annotations` API.\n\n- [#4226](https://github.com/Effect-TS/effect/pull/4226) [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a) Thanks @gcanti! - Fix: Prevent request body from being added to the OpenAPI spec for GET methods in `OpenApi.fromApi`.\n\n  When creating a `GET` endpoint with a request payload, the `requestBody` was incorrectly added to the OpenAPI specification, which is invalid for `GET` methods.\n\n  Before\n\n  ```ts\n  import {\n    HttpApi,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    OpenApi\n  } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const api = HttpApi.make(\"api\").add(\n    HttpApiGroup.make(\"group\").add(\n      HttpApiEndpoint.get(\"get\", \"/\")\n        .addSuccess(Schema.String)\n        .setPayload(\n          Schema.Struct({\n            a: Schema.String\n          })\n        )\n    )\n  )\n\n  const spec = OpenApi.fromApi(api)\n\n  console.log(JSON.stringify(spec.paths, null, 2))\n  /*\n  Output:\n  {\n    \"/\": {\n      \"get\": {\n        \"tags\": [\n          \"group\"\n        ],\n        \"operationId\": \"group.get\",\n        \"parameters\": [\n          {\n            \"name\": \"a\",\n            \"in\": \"query\",\n            \"schema\": {\n              \"type\": \"string\"\n            },\n            \"required\": true\n          }\n        ],\n        \"security\": [],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"a string\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"The request did not match the expected schema\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                }\n              }\n            }\n          }\n        },\n        \"requestBody\": {\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"a\"\n                ],\n                \"properties\": {\n                  \"a\": {\n                    \"type\": \"string\"\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            }\n          },\n          \"required\": true\n        }\n      }\n    }\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import {\n    HttpApi,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    OpenApi\n  } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const api = HttpApi.make(\"api\").add(\n    HttpApiGroup.make(\"group\").add(\n      HttpApiEndpoint.get(\"get\", \"/\")\n        .addSuccess(Schema.String)\n        .setPayload(\n          Schema.Struct({\n            a: Schema.String\n          })\n        )\n    )\n  )\n\n  const spec = OpenApi.fromApi(api)\n\n  console.log(JSON.stringify(spec.paths, null, 2))\n  /*\n  Output:\n  {\n    \"/\": {\n      \"get\": {\n        \"tags\": [\n          \"group\"\n        ],\n        \"operationId\": \"group.get\",\n        \"parameters\": [\n          {\n            \"name\": \"a\",\n            \"in\": \"query\",\n            \"schema\": {\n              \"type\": \"string\"\n            },\n            \"required\": true\n          }\n        ],\n        \"security\": [],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"a string\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"The request did not match the expected schema\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n  */\n  ```\n\n- [#4226](https://github.com/Effect-TS/effect/pull/4226) [`212e784`](https://github.com/Effect-TS/effect/commit/212e78475f527147ec27c090bd13f789f55add7a) Thanks @gcanti! - Add `\"application/x-www-form-urlencoded\"` to `OpenApiSpecContentType` type as it is generated by the system when using `HttpApiSchema.withEncoding({ kind: \"UrlParams\" })`\n\n  **Example**\n\n  ```ts\n  import {\n    HttpApi,\n    HttpApiEndpoint,\n    HttpApiGroup,\n    HttpApiSchema,\n    OpenApi\n  } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const api = HttpApi.make(\"api\").add(\n    HttpApiGroup.make(\"group\").add(\n      HttpApiEndpoint.post(\"post\", \"/\")\n        .addSuccess(Schema.String)\n        .setPayload(\n          Schema.Struct({ foo: Schema.String }).pipe(\n            HttpApiSchema.withEncoding({ kind: \"UrlParams\" })\n          )\n        )\n    )\n  )\n\n  const spec = OpenApi.fromApi(api)\n\n  console.log(JSON.stringify(spec.paths, null, 2))\n  /*\n  Output:\n  {\n    \"/\": {\n      \"post\": {\n        \"tags\": [\n          \"group\"\n        ],\n        \"operationId\": \"group.post\",\n        \"parameters\": [],\n        \"security\": [],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"a string\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"The request did not match the expected schema\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                }\n              }\n            }\n          }\n        },\n        \"requestBody\": {\n          \"content\": {\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"type\": \"object\",\n                \"required\": [\n                  \"foo\"\n                ],\n                \"properties\": {\n                  \"foo\": {\n                    \"type\": \"string\"\n                  }\n                },\n                \"additionalProperties\": false\n              }\n            }\n          },\n          \"required\": true\n        }\n      }\n    }\n  }\n  */\n  ```\n\n- Updated dependencies [[`734af82`](https://github.com/Effect-TS/effect/commit/734af82138e78b9c57a8355b1c6b80e80d38b222), [`b63c780`](https://github.com/Effect-TS/effect/commit/b63c78010893101520448ddda7019c487cf7eedd), [`c640d77`](https://github.com/Effect-TS/effect/commit/c640d77b33ad417876f4e8ffe8574ee6cbe5607f), [`0def088`](https://github.com/Effect-TS/effect/commit/0def0887cfdb6755729a64dfd52b3b9f46b0576c)]:\n  - effect@3.12.2\n\n## 0.72.1\n\n### Patch Changes\n\n- Updated dependencies [[`302b57d`](https://github.com/Effect-TS/effect/commit/302b57d2cbf9b9ccc17450945aeebfb33cfe8d43), [`0988083`](https://github.com/Effect-TS/effect/commit/0988083d4594938590df5a287e5b27d38526dd07), [`8b46be6`](https://github.com/Effect-TS/effect/commit/8b46be6a3b8160362ab5ea9171c5e6932505125c), [`bfe8027`](https://github.com/Effect-TS/effect/commit/bfe802734b450a4b4ee069d1125dd37995db2bff), [`16dd657`](https://github.com/Effect-TS/effect/commit/16dd657033d8afac2ffea567b3c8bb27c9b249b6), [`39db211`](https://github.com/Effect-TS/effect/commit/39db211414e90c8db8fdad7dc8ce5b4661bcfaef)]:\n  - effect@3.12.1\n\n## 0.72.0\n\n### Minor Changes\n\n- [#4068](https://github.com/Effect-TS/effect/pull/4068) [`ef64c6f`](https://github.com/Effect-TS/effect/commit/ef64c6fec0d47da573c04230dde9ea729366d871) Thanks @tim-smart! - remove generics from HttpClient tag service\n\n  Instead you can now use `HttpClient.With<E, R>` to specify the error and\n  requirement types.\n\n### Patch Changes\n\n- Updated dependencies [[`abb22a4`](https://github.com/Effect-TS/effect/commit/abb22a429b9c52c31e84856294f175d2064a9b4d), [`f369a89`](https://github.com/Effect-TS/effect/commit/f369a89e98bc682969803b9304adaf4557bb36c2), [`642376c`](https://github.com/Effect-TS/effect/commit/642376c63fd7d78754db991631a4d50a5dc79aa3), [`3d2b7a7`](https://github.com/Effect-TS/effect/commit/3d2b7a7e942a7157afae5b1cdbc6f3fef116428e), [`73f9c6f`](https://github.com/Effect-TS/effect/commit/73f9c6f2ff091512cf904cc54ab59965b86e87c8), [`17cb451`](https://github.com/Effect-TS/effect/commit/17cb4514590e8a86263f7aed009f24da8a237342), [`d801820`](https://github.com/Effect-TS/effect/commit/d80182060c2ee945d7e0e4728812abf9465a0d6a), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1), [`c11f3a6`](https://github.com/Effect-TS/effect/commit/c11f3a60a05c3b5fc8e7ce90136728154dc505b0), [`618f7e0`](https://github.com/Effect-TS/effect/commit/618f7e092a1011e5090dca1e69b5e9285689654b), [`c0ba834`](https://github.com/Effect-TS/effect/commit/c0ba834d1995cf5a8b250e4780fd43f3e3881151), [`e1eeb2d`](https://github.com/Effect-TS/effect/commit/e1eeb2d7064b3870041dab142f3057970699bbf1)]:\n  - effect@3.12.0\n\n## 0.71.7\n\n### Patch Changes\n\n- Updated dependencies [[`39457d4`](https://github.com/Effect-TS/effect/commit/39457d4897d9bc7df8af5c05d352866bbeae82eb), [`a475cc2`](https://github.com/Effect-TS/effect/commit/a475cc25fd7c9f26b27a8e98f8fbe43cc9e6ee3e), [`199214e`](https://github.com/Effect-TS/effect/commit/199214e21c616d8a0ccd7ed5f92e944e6c580193), [`b3c160d`](https://github.com/Effect-TS/effect/commit/b3c160d7a1fdfc2d3fb2440530f1ab80efc65133)]:\n  - effect@3.11.10\n\n## 0.71.6\n\n### Patch Changes\n\n- Updated dependencies [[`1c08a0b`](https://github.com/Effect-TS/effect/commit/1c08a0b8505badcffb4d9cade5a746ea90c9557e), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd), [`1ce703b`](https://github.com/Effect-TS/effect/commit/1ce703b041bbd7560c5c437c9b9be48f027937fd)]:\n  - effect@3.11.9\n\n## 0.71.5\n\n### Patch Changes\n\n- [#4154](https://github.com/Effect-TS/effect/pull/4154) [`05d71f8`](https://github.com/Effect-TS/effect/commit/05d71f85622305705d8316817694a09762e60865) Thanks @thewilkybarkid! - Support URL objects in HttpServerResponse.redirect\n\n- [#4157](https://github.com/Effect-TS/effect/pull/4157) [`e66b920`](https://github.com/Effect-TS/effect/commit/e66b9205f25ab425d30640886eb3fb2c4715bc26) Thanks @tim-smart! - ensure WebSocket's are always closed with an explicit code\n\n## 0.71.4\n\n### Patch Changes\n\n- [#4152](https://github.com/Effect-TS/effect/pull/4152) [`909181a`](https://github.com/Effect-TS/effect/commit/909181a9ce9052a80432ccf52187e0723004bf7f) Thanks @tim-smart! - accept Headers.Input in HttpServerResponse constructors\n\n- [#4152](https://github.com/Effect-TS/effect/pull/4152) [`909181a`](https://github.com/Effect-TS/effect/commit/909181a9ce9052a80432ccf52187e0723004bf7f) Thanks @tim-smart! - add HttpServerResponse.redirect api\n\n- Updated dependencies [[`1a6b52d`](https://github.com/Effect-TS/effect/commit/1a6b52dcf020d36e38a7bc90b648152cf5a8ccba)]:\n  - effect@3.11.8\n\n## 0.71.3\n\n### Patch Changes\n\n- [#4147](https://github.com/Effect-TS/effect/pull/4147) [`6984508`](https://github.com/Effect-TS/effect/commit/6984508c87f1bd91213b44c19b25ab5e2dcc1ce0) Thanks @tim-smart! - ensure HttpApi union schemas don't transfer non-api related annotations\n\n- [#4145](https://github.com/Effect-TS/effect/pull/4145) [`883639c`](https://github.com/Effect-TS/effect/commit/883639cc8ce47757f1cd39439391a8028c0812fe) Thanks @tim-smart! - ensure HttpApi preserves referential equality of error schemas\n\n## 0.71.2\n\n### Patch Changes\n\n- [#4138](https://github.com/Effect-TS/effect/pull/4138) [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e) Thanks @gcanti! - JSONSchema: handle the `nullable` keyword for OpenAPI target, closes #4075.\n\n  Before\n\n  ```ts\n  import { OpenApiJsonSchema } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const schema = Schema.NullOr(Schema.String)\n\n  console.log(JSON.stringify(OpenApiJsonSchema.make(schema), null, 2))\n  /*\n  {\n    \"anyOf\": [\n      {\n        \"type\": \"string\"\n      },\n      {\n        \"enum\": [\n          null\n        ]\n      }\n    ]\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { OpenApiJsonSchema } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  const schema = Schema.NullOr(Schema.String)\n\n  console.log(JSON.stringify(OpenApiJsonSchema.make(schema), null, 2))\n  /*\n  {\n    \"type\": \"string\",\n    \"nullable\": true\n  }\n  */\n  ```\n\n- [#4128](https://github.com/Effect-TS/effect/pull/4128) [`8d978c5`](https://github.com/Effect-TS/effect/commit/8d978c53f6fcc98d9d645ecba3e4b55d4297dd36) Thanks @gcanti! - JSONSchema: add `type` for homogeneous enum schemas, closes #4127\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Literal(\"a\", \"b\")\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"enum\": [\n      \"a\",\n      \"b\"\n    ]\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Literal(\"a\", \"b\")\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"enum\": [\n      \"a\",\n      \"b\"\n    ]\n  }\n  */\n  ```\n\n- [#4138](https://github.com/Effect-TS/effect/pull/4138) [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e) Thanks @gcanti! - JSONSchema: use `{ \"type\": \"null\" }` to represent the `null` literal\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.NullOr(Schema.String)\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"anyOf\": [\n      {\n        \"type\": \"string\"\n      },\n      {\n        \"enum\": [\n          null\n        ]\n      }\n    ]\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.NullOr(Schema.String)\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"anyOf\": [\n      {\n        \"type\": \"string\"\n      },\n      {\n        \"type\": \"null\"\n      }\n    ]\n  }\n  */\n  ```\n\n- Updated dependencies [[`2408616`](https://github.com/Effect-TS/effect/commit/24086163b60b09cc6d0885bd565ef080dcbe866b), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`8d978c5`](https://github.com/Effect-TS/effect/commit/8d978c53f6fcc98d9d645ecba3e4b55d4297dd36), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e), [`cec0b4d`](https://github.com/Effect-TS/effect/commit/cec0b4d152ef660be2ccdb0927255f2471436e6e)]:\n  - effect@3.11.7\n\n## 0.71.1\n\n### Patch Changes\n\n- [#4132](https://github.com/Effect-TS/effect/pull/4132) [`1d3df5b`](https://github.com/Effect-TS/effect/commit/1d3df5bc4324e88a392c348db35fd9d029c7b25e) Thanks @tim-smart! - allow passing Context to HttpApp web handlers\n\n  This allows you to pass request-scoped data to your handlers.\n\n  ```ts\n  import { Context, Effect } from \"effect\"\n  import { HttpApp, HttpServerResponse } from \"@effect/platform\"\n\n  class Env extends Context.Reference<Env>()(\"Env\", {\n    defaultValue: () => ({ foo: \"bar\" })\n  }) {}\n\n  const handler = HttpApp.toWebHandler(\n    Effect.gen(function* () {\n      const env = yield* Env\n      return yield* HttpServerResponse.json(env)\n    })\n  )\n\n  const response = await handler(\n    new Request(\"http://localhost:3000/\"),\n    Env.context({ foo: \"baz\" })\n  )\n\n  assert.deepStrictEqual(await response.json(), {\n    foo: \"baz\"\n  })\n  ```\n\n## 0.71.0\n\n### Minor Changes\n\n- [#4129](https://github.com/Effect-TS/effect/pull/4129) [`c99a0f3`](https://github.com/Effect-TS/effect/commit/c99a0f376d049d3793ed33e146d9873b8a5e5b78) Thanks @tim-smart! - replace HttpApi.empty with HttpApi.make(identifier)\n\n  This ensures if you have multiple HttpApi instances, the HttpApiGroup's are\n  implemented correctly.\n\n  ```ts\n  import { HttpApi } from \"@effect/platform\"\n\n  // Before\n  class Api extends HttpApi.empty.add(...) {}\n\n  // After\n  class Api extends HttpApi.make(\"api\").add(...) {}\n  ```\n\n### Patch Changes\n\n- [#4130](https://github.com/Effect-TS/effect/pull/4130) [`11fc401`](https://github.com/Effect-TS/effect/commit/11fc401f436f99bf4be95f56d50b0e4bdfe5edea) Thanks @tim-smart! - add predefined empty errors to HttpApiError\n\n- [#4129](https://github.com/Effect-TS/effect/pull/4129) [`c99a0f3`](https://github.com/Effect-TS/effect/commit/c99a0f376d049d3793ed33e146d9873b8a5e5b78) Thanks @tim-smart! - add OpenApi annotation for exluding parts of the api from the spec\n\n- Updated dependencies [[`662d1ce`](https://github.com/Effect-TS/effect/commit/662d1ce6fb7da384a95888d5b2bb5605bdf3208d), [`31c62d8`](https://github.com/Effect-TS/effect/commit/31c62d83cbdcf9850a8b5331faa239601c60f78a)]:\n  - effect@3.11.6\n\n## 0.70.7\n\n### Patch Changes\n\n- [#4111](https://github.com/Effect-TS/effect/pull/4111) [`22905cf`](https://github.com/Effect-TS/effect/commit/22905cf5addfb1ff3d2a6135c52036be958ae911) Thanks @gcanti! - JSONSchema: merge refinement fragments instead of just overwriting them.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  export const schema = Schema.String.pipe(\n    Schema.startsWith(\"a\"), // <= overwritten!\n    Schema.endsWith(\"c\")\n  )\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"description\": \"a string ending with \\\"c\\\"\",\n    \"pattern\": \"^.*c$\" // <= overwritten!\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  export const schema = Schema.String.pipe(\n    Schema.startsWith(\"a\"), // <= preserved!\n    Schema.endsWith(\"c\")\n  )\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"type\": \"string\",\n    \"description\": \"a string ending with \\\"c\\\"\",\n    \"pattern\": \"^.*c$\",\n    \"allOf\": [\n      {\n        \"pattern\": \"^a\" // <= preserved!\n      }\n    ],\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\"\n  }\n  */\n  ```\n\n- [#4019](https://github.com/Effect-TS/effect/pull/4019) [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8) Thanks @gcanti! - OpenApiJsonSchema: Use the experimental `JSONSchema.fromAST` API for implementation.\n\n- Updated dependencies [[`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`22905cf`](https://github.com/Effect-TS/effect/commit/22905cf5addfb1ff3d2a6135c52036be958ae911), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`1e59e4f`](https://github.com/Effect-TS/effect/commit/1e59e4fd778da18296812a2a32f36ca8ae50f60d), [`8d914e5`](https://github.com/Effect-TS/effect/commit/8d914e504e7a22d0ea628e8af265ee450ff9530f), [`03bb00f`](https://github.com/Effect-TS/effect/commit/03bb00faa74f9e168a54a8cc0828a664fbb1ab05), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`14e1149`](https://github.com/Effect-TS/effect/commit/14e1149f1af5a022f06eb8c2e4ba9fec17fe7426), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8), [`9f5a6f7`](https://github.com/Effect-TS/effect/commit/9f5a6f701bf7ba31adccd1f1bcfa8ab5614c9be8)]:\n  - effect@3.11.5\n\n## 0.70.6\n\n### Patch Changes\n\n- [#4097](https://github.com/Effect-TS/effect/pull/4097) [`9a5b8e3`](https://github.com/Effect-TS/effect/commit/9a5b8e36d184bd4967a88752cb6e755e1be263af) Thanks @tim-smart! - handle WebSocket's that emit ArrayBuffer instead of Uint8Array\n\n## 0.70.5\n\n### Patch Changes\n\n- [#4091](https://github.com/Effect-TS/effect/pull/4091) [`415f4c9`](https://github.com/Effect-TS/effect/commit/415f4c98321868531727a83cbaad70164f5e4c40) Thanks @ryskajakub! - http api param inherits description from schema\n\n- [#4087](https://github.com/Effect-TS/effect/pull/4087) [`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2) Thanks @tim-smart! - remove Socket write indirection\n\n- Updated dependencies [[`518b258`](https://github.com/Effect-TS/effect/commit/518b258a8a67ecd332a9252c35cc060f8368dee2), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f), [`6e323a3`](https://github.com/Effect-TS/effect/commit/6e323a36faaee46b328c8e3cf60a76b3aff9907f)]:\n  - effect@3.11.4\n\n## 0.70.4\n\n### Patch Changes\n\n- Updated dependencies [[`90906f7`](https://github.com/Effect-TS/effect/commit/90906f7f154b12c7182e8f39e3c55ef3937db857), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`3862cd3`](https://github.com/Effect-TS/effect/commit/3862cd3c7f6a542ed65fb81255b3bd696ce2f567), [`343b6aa`](https://github.com/Effect-TS/effect/commit/343b6aa6ac4a74276bfc7c63ccbf4a1d72bc1bed), [`afba339`](https://github.com/Effect-TS/effect/commit/afba339adc11dad56b5a3b7ca94487e58f34d613)]:\n  - effect@3.11.3\n\n## 0.70.3\n\n### Patch Changes\n\n- [#4065](https://github.com/Effect-TS/effect/pull/4065) [`7044730`](https://github.com/Effect-TS/effect/commit/70447306be1aeeb7d87c230b2a96ec87b993ede9) Thanks @KhraksMamtsov! - Ensure the uniqueness of the parameters at the type level\n\n  ```ts\n  import { HttpApiEndpoint, HttpApiSchema } from \"@effect/platform\"\n  import { Schema } from \"effect\"\n\n  HttpApiEndpoint.get(\n    \"test\"\n  )`/${HttpApiSchema.param(\"id\", Schema.NumberFromString)}/${\n    // @ts-expect-error: Argument of type 'Param<\"id\", typeof NumberFromString>' is not assignable to parameter of type '\"Duplicate param :id\"'\n    HttpApiSchema.param(\"id\", Schema.NumberFromString)\n  }`\n  ```\n\n## 0.70.2\n\n### Patch Changes\n\n- [#4064](https://github.com/Effect-TS/effect/pull/4064) [`c2249ea`](https://github.com/Effect-TS/effect/commit/c2249ea13fd98ab7d9aa628787931356d8ec2860) Thanks @tim-smart! - HttpApi OpenApi adjustments\n  - Allow using transform annotation on endpoints & groups\n  - Preserve descriptions for \"empty\" schemas\n\n- [#4055](https://github.com/Effect-TS/effect/pull/4055) [`1358aa5`](https://github.com/Effect-TS/effect/commit/1358aa5326eaa85ef13ee8d1fed0b4a4288ed3eb) Thanks @thewilkybarkid! - Allow creating a route for all methods\n\n- [#4062](https://github.com/Effect-TS/effect/pull/4062) [`1de3fe7`](https://github.com/Effect-TS/effect/commit/1de3fe7d1cbafd6391eaa38c2300b99e332cc2aa) Thanks @tim-smart! - simplify HttpApiClient param regex\n\n- Updated dependencies [[`01cee56`](https://github.com/Effect-TS/effect/commit/01cee560b58d94b24cc20e98083251b73e658b41)]:\n  - effect@3.11.2\n\n## 0.70.1\n\n### Patch Changes\n\n- Updated dependencies [[`dd8a2d8`](https://github.com/Effect-TS/effect/commit/dd8a2d8e80d33b16719fc69361eaedf0b59d4620), [`a71bfef`](https://github.com/Effect-TS/effect/commit/a71bfef46f5061bb2502a61a333638a987b62273)]:\n  - effect@3.11.1\n\n## 0.70.0\n\n### Minor Changes\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`672bde5`](https://github.com/Effect-TS/effect/commit/672bde5bec51c7d6f9862828e6a654cb2cb6f93d) Thanks @tim-smart! - support array of values in /platform url param schemas\n\n### Patch Changes\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`5eff3f6`](https://github.com/Effect-TS/effect/commit/5eff3f6fa3aae7e86948a62cbfd63b8d6c3bdf92) Thanks @tim-smart! - fix multipart support for bun http server\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`b4ce4ea`](https://github.com/Effect-TS/effect/commit/b4ce4ea7fd514a7e572f2dcd879c98f334981b0e) Thanks @SandroMaglione! - New methods `extractAll` and `extractSchema` to `UrlParams` (added `Schema.BooleanFromString`).\n\n- [#3835](https://github.com/Effect-TS/effect/pull/3835) [`1e2747c`](https://github.com/Effect-TS/effect/commit/1e2747c63a4820d1459cbbc88c71212983bd68bd) Thanks @KhraksMamtsov! - - JSONSchema module\n  - add `format?: string` optional field to `JsonSchema7String` interface\n  - Schema module\n    - add custom json schema annotation to `UUID` schema including `format: \"uuid\"`\n  - OpenApiJsonSchema module\n    - add `format?: string` optional field to `String` and ` Numeric` interfaces\n- Updated dependencies [[`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`6e69493`](https://github.com/Effect-TS/effect/commit/6e694930048bbaf98110f35f41566aeb9752d471), [`147434b`](https://github.com/Effect-TS/effect/commit/147434b03d5e1fd692dd9f126e5ab0910f3b76d3), [`5eff3f6`](https://github.com/Effect-TS/effect/commit/5eff3f6fa3aae7e86948a62cbfd63b8d6c3bdf92), [`d9fe79b`](https://github.com/Effect-TS/effect/commit/d9fe79bb5a3fe105d8e7a3bc2922a8ad936a5d10), [`251d189`](https://github.com/Effect-TS/effect/commit/251d189420bbba71990574e91098c499065f9a9b), [`5a259f3`](https://github.com/Effect-TS/effect/commit/5a259f3711b4369f55d885b568bdb21136155261), [`b4ce4ea`](https://github.com/Effect-TS/effect/commit/b4ce4ea7fd514a7e572f2dcd879c98f334981b0e), [`15fcc5a`](https://github.com/Effect-TS/effect/commit/15fcc5a0ea4bbf40ab48fa6a04fdda74f76f4c07), [`9bc9a47`](https://github.com/Effect-TS/effect/commit/9bc9a476800dc645903c888a68bb1d3baa3383c6), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb), [`1e2747c`](https://github.com/Effect-TS/effect/commit/1e2747c63a4820d1459cbbc88c71212983bd68bd), [`9264162`](https://github.com/Effect-TS/effect/commit/9264162a82783a651776fb7b87604564a63e7070), [`e0b9b09`](https://github.com/Effect-TS/effect/commit/e0b9b09e70c386b2da17d1f0a15b0511861c89e8), [`c36f3b9`](https://github.com/Effect-TS/effect/commit/c36f3b95df5ce9d71b66f22f26ce12eda8d3e848), [`aadb8a4`](https://github.com/Effect-TS/effect/commit/aadb8a48d2cba197c06ec9996505510e48e4e5cb)]:\n  - effect@3.11.0\n\n## 0.69.32\n\n### Patch Changes\n\n- Updated dependencies [[`3069614`](https://github.com/Effect-TS/effect/commit/30696149271129fc618f6f2ccd1d8f2f6c0f9cd7), [`09a5e52`](https://github.com/Effect-TS/effect/commit/09a5e522fd9b221f05d85b1d1c8a740d4973c302)]:\n  - effect@3.10.20\n\n## 0.69.31\n\n### Patch Changes\n\n- [#4035](https://github.com/Effect-TS/effect/pull/4035) [`e6d4a37`](https://github.com/Effect-TS/effect/commit/e6d4a37c1d7e657b5ea44063a1cf586808228fe5) Thanks @tim-smart! - add template literal api for defining HttpApiEndpoint path schema\n\n## 0.69.30\n\n### Patch Changes\n\n- [#4025](https://github.com/Effect-TS/effect/pull/4025) [`270f199`](https://github.com/Effect-TS/effect/commit/270f199b31810fd643e4c22818698adcbdb5d396) Thanks @tim-smart! - update OpenApi version to 3.1.0\n\n## 0.69.29\n\n### Patch Changes\n\n- [#4024](https://github.com/Effect-TS/effect/pull/4024) [`24cc35e`](https://github.com/Effect-TS/effect/commit/24cc35e26d6ed4a076470bc687ffd99cc50991b3) Thanks @tim-smart! - improve HttpApi handling of payload encoding types\n\n## 0.69.28\n\n### Patch Changes\n\n- [#4017](https://github.com/Effect-TS/effect/pull/4017) [`edd72be`](https://github.com/Effect-TS/effect/commit/edd72be57b904d60c9cbffc2537901821a9da537) Thanks @tim-smart! - try encode defects that match an Error schema in HttpApi\n\n- [#4014](https://github.com/Effect-TS/effect/pull/4014) [`a3e2771`](https://github.com/Effect-TS/effect/commit/a3e277170a1f7cf61fd629acb60304c7e81d9498) Thanks @tim-smart! - consider TimeoutException a transient error in HttpClient.retryTransient\n\n- [#4007](https://github.com/Effect-TS/effect/pull/4007) [`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1) Thanks @gcanti! - Wrap JSDoc @example tags with a TypeScript fence, closes #4002\n\n- [#4016](https://github.com/Effect-TS/effect/pull/4016) [`a9e00e4`](https://github.com/Effect-TS/effect/commit/a9e00e43f0b5dd22c1f9d5b78be6383daea09c20) Thanks @tim-smart! - allow using HttpApiSchema.Multipart in a union\n\n- Updated dependencies [[`944025b`](https://github.com/Effect-TS/effect/commit/944025bc5ce139f4a85846aa689bf30ec06a8ec1), [`54addee`](https://github.com/Effect-TS/effect/commit/54addee438a644bf010646c52042c7b89c5fc0a7)]:\n  - effect@3.10.19\n\n## 0.69.27\n\n### Patch Changes\n\n- [#4005](https://github.com/Effect-TS/effect/pull/4005) [`beaccae`](https://github.com/Effect-TS/effect/commit/beaccae2d15931e9fe475fb50a0b3638243fe3f7) Thanks @tim-smart! - fix HttpApiBuilder.middleware when used multiple times\n\n- Updated dependencies [[`af409cf`](https://github.com/Effect-TS/effect/commit/af409cf1d2ff973be11cc079ea373eaeedca25de)]:\n  - effect@3.10.18\n\n## 0.69.26\n\n### Patch Changes\n\n- [#3977](https://github.com/Effect-TS/effect/pull/3977) [`c963886`](https://github.com/Effect-TS/effect/commit/c963886d5817986fcbd6bfa4ddf50aca8b6c8184) Thanks @KhraksMamtsov! - `HttpApiClient.group` & `HttpApiClient.endpoint` have been added\n  This makes it possible to create `HttpApiClient` for some part of the `HttpApi`\n  This eliminates the need to provide all the dependencies for the entire `HttpApi` - but only those necessary for its specific part to work\n- Updated dependencies [[`42c4ce6`](https://github.com/Effect-TS/effect/commit/42c4ce6f8d8c7d847e97757650a8ad9419a829d7)]:\n  - effect@3.10.17\n\n## 0.69.25\n\n### Patch Changes\n\n- [#3968](https://github.com/Effect-TS/effect/pull/3968) [`320557a`](https://github.com/Effect-TS/effect/commit/320557ab18d13c5e22fc7dc0d2a157eae461012f) Thanks @KhraksMamtsov! - `OpenApi.Transform` annotation has been added\n\n  This customization point allows you to transform the generated specification in an arbitrary way\n\n  ```ts\n  class Api extends HttpApi.empty\n    .annotateContext(OpenApi.annotations({\n      title: \"API\",\n      summary: \"test api summary\",\n      transform: (openApiSpec) => ({\n        ...openApiSpec,\n        tags: [...openApiSpec.tags ?? [], {\n          name: \"Tag from OpenApi.Transform annotation\"\n        }]\n      })\n    }))\n  ```\n\n- [#3962](https://github.com/Effect-TS/effect/pull/3962) [`7b93dd6`](https://github.com/Effect-TS/effect/commit/7b93dd622e2ab79c7072d79d0d9611e446202201) Thanks @KhraksMamtsov! - fix HttpApiGroup.addError signature\n\n- Updated dependencies [[`4dca30c`](https://github.com/Effect-TS/effect/commit/4dca30cfcdafe4542e236489f71d6f171a5b4e38), [`1d99867`](https://github.com/Effect-TS/effect/commit/1d998671be3cd11043f232822e91dd8c98fccfa9), [`6dae414`](https://github.com/Effect-TS/effect/commit/6dae4147991a97ec14a99289bd25fadae7541e8d), [`6b0d737`](https://github.com/Effect-TS/effect/commit/6b0d737078bf63b97891e6bc47affc04b28f9cf7), [`d8356aa`](https://github.com/Effect-TS/effect/commit/d8356aad428a0c2290db52380220f81d9ec94232)]:\n  - effect@3.10.16\n\n## 0.69.24\n\n### Patch Changes\n\n- [#3939](https://github.com/Effect-TS/effect/pull/3939) [`3cc6514`](https://github.com/Effect-TS/effect/commit/3cc6514d2dd64e010cb760cc29bfce98c349bb10) Thanks @KhraksMamtsov! - Added the ability to annotate the `HttpApi` with additional schemas\n  Which will be taken into account when generating `components.schemas` section of `OpenApi` schema\n\n  ```ts\n  import { Schema } from \"effect\"\n  import { HttpApi } from \"@effect/platform\"\n\n  HttpApi.empty.annotate(HttpApi.AdditionalSchemas, [\n    Schema.Struct({\n      contentType: Schema.String,\n      length: Schema.Int\n    }).annotations({\n      identifier: \"ComponentsSchema\"\n    })\n  ])\n  /**\n   {\n    \"openapi\": \"3.0.3\",\n    ...\n    \"components\": {\n      \"schemas\": {\n        \"ComponentsSchema\": {...},\n        ...\n    },\n    ...\n    }\n   */\n  ```\n\n## 0.69.23\n\n### Patch Changes\n\n- [#3944](https://github.com/Effect-TS/effect/pull/3944) [`3aff4d3`](https://github.com/Effect-TS/effect/commit/3aff4d38837c213bb2987973dc4b98febb9f92d2) Thanks @KhraksMamtsov! - `OpenApi.Summary` & `OpenApi.Deprecated` annotations have been added\n\n## 0.69.22\n\n### Patch Changes\n\n- Updated dependencies [[`8398b32`](https://github.com/Effect-TS/effect/commit/8398b3208242a88239d4449910b7baf923cfe3b6), [`72e55b7`](https://github.com/Effect-TS/effect/commit/72e55b7c610784fcebdbadc592c876e23e76a986)]:\n  - effect@3.10.15\n\n## 0.69.21\n\n### Patch Changes\n\n- Updated dependencies [[`f983946`](https://github.com/Effect-TS/effect/commit/f9839467b4cad6e788297764ef9f9f0b9fd203f9), [`2d8a750`](https://github.com/Effect-TS/effect/commit/2d8a75081eb83a0a81f817fdf6f428369c5064ab)]:\n  - effect@3.10.14\n\n## 0.69.20\n\n### Patch Changes\n\n- Updated dependencies [[`995bbdf`](https://github.com/Effect-TS/effect/commit/995bbdffea2e332f203cd5b474cd6a1c77dfa6ae)]:\n  - effect@3.10.13\n\n## 0.69.19\n\n### Patch Changes\n\n- [#3908](https://github.com/Effect-TS/effect/pull/3908) [`eb8c52d`](https://github.com/Effect-TS/effect/commit/eb8c52d8b4c5e067ebf0a81eb742f5822e6439b5) Thanks @tim-smart! - use plain js data structures for HttpApi properties\n\n## 0.69.18\n\n### Patch Changes\n\n- [#3906](https://github.com/Effect-TS/effect/pull/3906) [`a0584ec`](https://github.com/Effect-TS/effect/commit/a0584ece92ed784bfb139e9c5a699f02d1e71c2d) Thanks @tim-smart! - ensure Socket send queue is not ended\n\n- [#3904](https://github.com/Effect-TS/effect/pull/3904) [`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6) Thanks @tim-smart! - improve platform/Worker shutdown and logging\n\n- Updated dependencies [[`dd14efe`](https://github.com/Effect-TS/effect/commit/dd14efe0ace255f571273aae876adea96267d7e6)]:\n  - effect@3.10.12\n\n## 0.69.17\n\n### Patch Changes\n\n- [#3898](https://github.com/Effect-TS/effect/pull/3898) [`8240b1c`](https://github.com/Effect-TS/effect/commit/8240b1c10d45312fc863cb679b1a1e8441af0c1a) Thanks @mattphillips! - Fixed handling of basic auth header values\n\n- [#3903](https://github.com/Effect-TS/effect/pull/3903) [`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a) Thanks @tim-smart! - add HttpApi.addHttpApi method, for merging two HttpApi instances\n\n- Updated dependencies [[`5eef499`](https://github.com/Effect-TS/effect/commit/5eef4998b6ccb7a5404d9e4fef85e57fa35fbb8a)]:\n  - effect@3.10.11\n\n## 0.69.16\n\n### Patch Changes\n\n- [#3893](https://github.com/Effect-TS/effect/pull/3893) [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28) Thanks @tim-smart! - refactor Socket internal code\n\n- [#3892](https://github.com/Effect-TS/effect/pull/3892) [`7d89650`](https://github.com/Effect-TS/effect/commit/7d8965036cd2ea435c8441ffec3345488baebf85) Thanks @tim-smart! - simplify HttpApiClient implementation\n\n- Updated dependencies [[`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`cd720ae`](https://github.com/Effect-TS/effect/commit/cd720aedf7f2571edec0843d6a633e84e4832b28), [`b631f40`](https://github.com/Effect-TS/effect/commit/b631f40abbe649b2a089764585b5c39f6a695ac6)]:\n  - effect@3.10.10\n\n## 0.69.15\n\n### Patch Changes\n\n- [#3885](https://github.com/Effect-TS/effect/pull/3885) [`8a30e1d`](https://github.com/Effect-TS/effect/commit/8a30e1dfa3a7103bf5414fc6a7fca3088d8c8c00) Thanks @tim-smart! - simplify HttpApiBuilder handler logic\n\n## 0.69.14\n\n### Patch Changes\n\n- [#3884](https://github.com/Effect-TS/effect/pull/3884) [`07c493a`](https://github.com/Effect-TS/effect/commit/07c493a598e096c7810cd06def8cfa43493c46b1) Thanks @tim-smart! - add withResponse option to HttpApiClient methods\n\n- [#3882](https://github.com/Effect-TS/effect/pull/3882) [`257ab1b`](https://github.com/Effect-TS/effect/commit/257ab1b539fa6e930b7ae2583a188376372200d7) Thanks @tim-smart! - simplify Socket internal code\n\n- Updated dependencies [[`a123e80`](https://github.com/Effect-TS/effect/commit/a123e80f111a625428a5b5622b7f55ee1073566b), [`bd5fcd3`](https://github.com/Effect-TS/effect/commit/bd5fcd3e6b603b1e505af90d6a00627c8eca6d41), [`0289d3b`](https://github.com/Effect-TS/effect/commit/0289d3b6391031d00329365bab9791b355031fe3), [`7386b71`](https://github.com/Effect-TS/effect/commit/7386b710e5be570e17f468928a6ed19d549a3e12), [`4211a23`](https://github.com/Effect-TS/effect/commit/4211a2355bb3af3f0e756e2aae9d293379f25662)]:\n  - effect@3.10.9\n\n## 0.69.13\n\n### Patch Changes\n\n- Updated dependencies [[`68b5c9e`](https://github.com/Effect-TS/effect/commit/68b5c9e44f34192cef26e1cadda5e661a027df41), [`9c9928d`](https://github.com/Effect-TS/effect/commit/9c9928dfeacd9ac33dc37eb0ca3d7d8c39175ada), [`6306e66`](https://github.com/Effect-TS/effect/commit/6306e6656092b350d4ede5746da6f245ec9f7e07), [`361c7f3`](https://github.com/Effect-TS/effect/commit/361c7f39a2c10ede9324847c3d3ba192a6f9b20a)]:\n  - effect@3.10.8\n\n## 0.69.12\n\n### Patch Changes\n\n- Updated dependencies [[`33f5b9f`](https://github.com/Effect-TS/effect/commit/33f5b9ffaebea4f1bd0e391b44c41fb6230e743a), [`50f0281`](https://github.com/Effect-TS/effect/commit/50f0281b0d2116726b8927a6217622d5f394f3e4)]:\n  - effect@3.10.7\n\n## 0.69.11\n\n### Patch Changes\n\n- [#3856](https://github.com/Effect-TS/effect/pull/3856) [`81ddd45`](https://github.com/Effect-TS/effect/commit/81ddd45fc074b98206fafab416d9a5a28b31e07a) Thanks @KhraksMamtsov! - Integration with [Scalar](https://scalar.com/) has been implemented\n\n- Updated dependencies [[`ce1c21f`](https://github.com/Effect-TS/effect/commit/ce1c21ffc11902ac9ab453a51904207859d38552)]:\n  - effect@3.10.6\n\n## 0.69.10\n\n### Patch Changes\n\n- Updated dependencies [[`3a6d757`](https://github.com/Effect-TS/effect/commit/3a6d757badeebe00d8ef4d67530d073c8264dcfa), [`59d813a`](https://github.com/Effect-TS/effect/commit/59d813aa4973d1115cfc70cc3667508335f49693)]:\n  - effect@3.10.5\n\n## 0.69.9\n\n### Patch Changes\n\n- [#3842](https://github.com/Effect-TS/effect/pull/3842) [`2367708`](https://github.com/Effect-TS/effect/commit/2367708be449f9526a2047e321302d7bfb16f18e) Thanks @gcanti! - add support for `Schema.OptionFromUndefinedOr` in JSON Schema generation, closes #3839\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.OptionFromUndefinedOr(Schema.Number)\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  throws:\n  Error: Missing annotation\n  at path: [\"a\"]\n  details: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\n  schema (UndefinedKeyword): undefined\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"effect\"\n\n  const schema = Schema.Struct({\n    a: Schema.OptionFromUndefinedOr(Schema.Number)\n  })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  Output:\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"required\": [],\n    \"properties\": {\n      \"a\": {\n        \"type\": \"number\"\n      }\n    },\n    \"additionalProperties\": false\n  }\n  */\n  ```\n\n- Updated dependencies [[`2367708`](https://github.com/Effect-TS/effect/commit/2367708be449f9526a2047e321302d7bfb16f18e)]:\n  - effect@3.10.4\n\n## 0.69.8\n\n### Patch Changes\n\n- [#3837](https://github.com/Effect-TS/effect/pull/3837) [`522f7c5`](https://github.com/Effect-TS/effect/commit/522f7c518a5acfb55ef96d6796869f002cc3eaf8) Thanks @tim-smart! - eliminate HttpApiEndpoint context in .handle\n\n## 0.69.7\n\n### Patch Changes\n\n- [#3836](https://github.com/Effect-TS/effect/pull/3836) [`690d6c5`](https://github.com/Effect-TS/effect/commit/690d6c54d2145adb0af545c447db7d4755bf3c6b) Thanks @tim-smart! - add HttpApiBuilder.handler, for defining a single handler\n\n- [#3831](https://github.com/Effect-TS/effect/pull/3831) [`279fe3a`](https://github.com/Effect-TS/effect/commit/279fe3a7168fe84e520c2cc88ba189a15f03a2bc) Thanks @tim-smart! - ensure parent annotations take precedence over surrogate annotations\n\n- Updated dependencies [[`b9423d8`](https://github.com/Effect-TS/effect/commit/b9423d8bf8181a2389fdbce1e3c14ac6fe8d54f5)]:\n  - effect@3.10.3\n\n## 0.69.6\n\n### Patch Changes\n\n- [#3826](https://github.com/Effect-TS/effect/pull/3826) [`42cd72a`](https://github.com/Effect-TS/effect/commit/42cd72a44ca9593e4d81fbb50e8111625fd0fb81) Thanks @juliusmarminge! - ensure requests & responses have headers redacted when inspecting\n\n- Updated dependencies [[`714e119`](https://github.com/Effect-TS/effect/commit/714e11945e45e5a2554ee058e6c43f82a8e309cf), [`c1afd55`](https://github.com/Effect-TS/effect/commit/c1afd55c54e61f9c432823d21b3d016f79160a37)]:\n  - effect@3.10.2\n\n## 0.69.5\n\n### Patch Changes\n\n- Updated dependencies [[`9604d6b`](https://github.com/Effect-TS/effect/commit/9604d6b616435103dafea8b53637a9d1450b4750)]:\n  - effect@3.10.1\n\n## 0.69.4\n\n### Patch Changes\n\n- [#3816](https://github.com/Effect-TS/effect/pull/3816) [`c86b1d7`](https://github.com/Effect-TS/effect/commit/c86b1d7cd47b66df190ef9775a475467c1abdbd6) Thanks @tim-smart! - allow Request.signal to be missing in .toWebHandler apis\n\n## 0.69.3\n\n### Patch Changes\n\n- [#3814](https://github.com/Effect-TS/effect/pull/3814) [`d5fba63`](https://github.com/Effect-TS/effect/commit/d5fba6391e1005e374aa0238f13edfbd65848313) Thanks @tim-smart! - cache OpenApi schema generation\n\n- [#3813](https://github.com/Effect-TS/effect/pull/3813) [`1eb2c30`](https://github.com/Effect-TS/effect/commit/1eb2c30ba064398db5790e376dedcfad55b7b005) Thanks @KhraksMamtsov! - Add support for bearer format OpenApi annotation\n\n- [#3811](https://github.com/Effect-TS/effect/pull/3811) [`02d413e`](https://github.com/Effect-TS/effect/commit/02d413e7b6bc1c64885969c37cc3e4e690c94d7d) Thanks @KhraksMamtsov! - A bug related to the format of the security schema keys has been fixed. According to the OpenAPI specification, it must match the regular expression` ^[a-zA-Z0-9.-_]+# @effect/platform\n\n## 0.69.2\n\n### Patch Changes\n\n- [#3808](https://github.com/Effect-TS/effect/pull/3808) [`e7afc47`](https://github.com/Effect-TS/effect/commit/e7afc47ce83e381c3f4aed2b2974e3b3d86a2340) Thanks @tim-smart! - ensure HttpMiddleware is only initialized once\n\n## 0.69.1\n\n### Patch Changes\n\n- [#3802](https://github.com/Effect-TS/effect/pull/3802) [`7564f56`](https://github.com/Effect-TS/effect/commit/7564f56bb2844cf39d2b0d2d9e93cf9b2205e9a8) Thanks @tim-smart! - simplify HttpApiMiddleware.TagClass type\n\n- [#3802](https://github.com/Effect-TS/effect/pull/3802) [`7564f56`](https://github.com/Effect-TS/effect/commit/7564f56bb2844cf39d2b0d2d9e93cf9b2205e9a8) Thanks @tim-smart! - add HttpServer.layerContext to platform-node/bun\n\n## 0.69.0\n\n### Minor Changes\n\n- [#3764](https://github.com/Effect-TS/effect/pull/3764) [`6d9de6b`](https://github.com/Effect-TS/effect/commit/6d9de6b871c5c08e6509a4e830c3d74758faa198) Thanks @tim-smart! - HttpApi second revision\n  - `HttpApi`, `HttpApiGroup` & `HttpApiEndpoint` now use a chainable api instead\n    of a pipeable api.\n  - `HttpApiMiddleware` module has been added, with a updated way of defining\n    security middleware.\n  - You can now add multiple success schemas\n  - A url search parameter schema has been added\n  - Error schemas now support `HttpApiSchema` encoding apis\n  - `toWebHandler` has been simplified\n\n  For more information, see the [README](https://github.com/Effect-TS/effect/blob/main/packages/platform/README.md#http-api).\n\n- [#3764](https://github.com/Effect-TS/effect/pull/3764) [`5821ce3`](https://github.com/Effect-TS/effect/commit/5821ce3455b47d25e0a40cae6ce22af9db5fa556) Thanks @patroza! - feat: implement Redactable. Used by Headers to not log sensitive information\n\n### Patch Changes\n\n- Updated dependencies [[`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`4a01828`](https://github.com/Effect-TS/effect/commit/4a01828b66d6213e9bbe18979c893b13f7bb29bf), [`c79c4c1`](https://github.com/Effect-TS/effect/commit/c79c4c178390fe61ff6dda88c9e058862349343a), [`38d30f0`](https://github.com/Effect-TS/effect/commit/38d30f08b8da62f9c3e308b9250738cb8d17bdb5), [`5821ce3`](https://github.com/Effect-TS/effect/commit/5821ce3455b47d25e0a40cae6ce22af9db5fa556)]:\n  - effect@3.10.0\n\n## 0.68.6\n\n### Patch Changes\n\n- Updated dependencies [[`382556f`](https://github.com/Effect-TS/effect/commit/382556f8930780c0634de681077706113a8c8239), [`97cb014`](https://github.com/Effect-TS/effect/commit/97cb0145114b2cd2f378e98f6c4ff5bf2c1865f5)]:\n  - @effect/schema@0.75.5\n\n## 0.68.5\n\n### Patch Changes\n\n- [#3784](https://github.com/Effect-TS/effect/pull/3784) [`2036402`](https://github.com/Effect-TS/effect/commit/20364020b8b75a684791aa93d90626758023e9e9) Thanks @patroza! - fix HttpMiddleware circular import\n\n## 0.68.4\n\n### Patch Changes\n\n- [#3780](https://github.com/Effect-TS/effect/pull/3780) [`1b1ef29`](https://github.com/Effect-TS/effect/commit/1b1ef29ae302322f69dc938f9337aa97b4c63266) Thanks @tim-smart! - ensure cors middleware also affects error responses\n\n## 0.68.3\n\n### Patch Changes\n\n- [#3769](https://github.com/Effect-TS/effect/pull/3769) [`8c33087`](https://github.com/Effect-TS/effect/commit/8c330879425e80bed2f65e407cd59e991f0d7bec) Thanks @tim-smart! - add support for WebSocket protocols option\n\n- Updated dependencies [[`61a99b2`](https://github.com/Effect-TS/effect/commit/61a99b2bf9d757870ef0c2ec9d4c877cdd364a3d)]:\n  - effect@3.9.2\n  - @effect/schema@0.75.4\n\n## 0.68.2\n\n### Patch Changes\n\n- Updated dependencies [[`360ec14`](https://github.com/Effect-TS/effect/commit/360ec14dd4102c526aef7433a8881ad4d9beab75)]:\n  - @effect/schema@0.75.3\n\n## 0.68.1\n\n### Patch Changes\n\n- [#3743](https://github.com/Effect-TS/effect/pull/3743) [`b75ac5d`](https://github.com/Effect-TS/effect/commit/b75ac5d0909115507bedc90f18f2d34deb217769) Thanks @sukovanej! - Add support for `ConfigProvider` based on .env files.\n\n  ```ts\n  import { PlatformConfigProvider } from \"@effect/platform\"\n  import { NodeContext } from \"@effect/platform-node\"\n  import { Config } from \"effect\"\n\n  Effect.gen(function* () {\n    const config = yield* Config.all({\n      api_url: Config.string(\"API_URL\"),\n      api_key: Config.string(\"API_KEY\")\n    })\n\n    console.log(`Api config: ${config}`)\n  }).pipe(\n    Effect.provide(\n      PlatformConfigProvider.layerDotEnvAdd(\".env\").pipe(\n        Layer.provide(NodeContext.layer)\n      )\n    )\n  )\n  ```\n\n## 0.68.0\n\n### Minor Changes\n\n- [#3756](https://github.com/Effect-TS/effect/pull/3756) [`90ceeab`](https://github.com/Effect-TS/effect/commit/90ceeab3a04051b740af18c8af8bd73ee8ec6363) Thanks @tim-smart! - remove HttpClient.Service type\n\n- [#3756](https://github.com/Effect-TS/effect/pull/3756) [`90ceeab`](https://github.com/Effect-TS/effect/commit/90ceeab3a04051b740af18c8af8bd73ee8ec6363) Thanks @tim-smart! - constrain HttpClient success type to HttpClientResponse\n\n- [#3756](https://github.com/Effect-TS/effect/pull/3756) [`90ceeab`](https://github.com/Effect-TS/effect/commit/90ceeab3a04051b740af18c8af8bd73ee8ec6363) Thanks @tim-smart! - add HttpClient accessor apis\n\n  These apis allow you to easily send requests without first accessing the `HttpClient` service.\n\n  Below is an example of using the `get` accessor api to send a GET request:\n\n  ```ts\n  import { FetchHttpClient, HttpClient } from \"@effect/platform\"\n  import { Effect } from \"effect\"\n\n  const program = HttpClient.get(\n    \"https://jsonplaceholder.typicode.com/posts/1\"\n  ).pipe(\n    Effect.andThen((response) => response.json),\n    Effect.scoped,\n    Effect.provide(FetchHttpClient.layer)\n  )\n\n  Effect.runPromise(program)\n  /*\n  Output:\n  {\n    userId: 1,\n    id: 1,\n    title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',\n    body: 'quia et suscipit\\n' +\n      'suscipit recusandae consequuntur expedita et cum\\n' +\n      'reprehenderit molestiae ut ut quas totam\\n' +\n      'nostrum rerum est autem sunt rem eveniet architecto'\n  }\n  */\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`f02b354`](https://github.com/Effect-TS/effect/commit/f02b354ab5b0451143b82bb73dc866be29adec85)]:\n  - @effect/schema@0.75.2\n\n## 0.67.1\n\n### Patch Changes\n\n- [#3740](https://github.com/Effect-TS/effect/pull/3740) [`3b2ad1d`](https://github.com/Effect-TS/effect/commit/3b2ad1d58a2e33dc1a72b7037396bd25ca1702a9) Thanks @tim-smart! - revert deno Inspectable changes\n\n- Updated dependencies [[`3b2ad1d`](https://github.com/Effect-TS/effect/commit/3b2ad1d58a2e33dc1a72b7037396bd25ca1702a9)]:\n  - effect@3.9.1\n  - @effect/schema@0.75.1\n\n## 0.67.0\n\n### Minor Changes\n\n- [#3620](https://github.com/Effect-TS/effect/pull/3620) [`0ba66f2`](https://github.com/Effect-TS/effect/commit/0ba66f2451641fd6990e02ec1ed01c014db9dab0) Thanks @tim-smart! - add deno support to Inspectable\n\n### Patch Changes\n\n- Updated dependencies [[`ff3d1aa`](https://github.com/Effect-TS/effect/commit/ff3d1aab290b4d1173b2dfc7e4c76abb4babdc16), [`0ba66f2`](https://github.com/Effect-TS/effect/commit/0ba66f2451641fd6990e02ec1ed01c014db9dab0), [`bf77f51`](https://github.com/Effect-TS/effect/commit/bf77f51b323c383224ebf08adf77a7a6e8c9b3cd), [`016f9ad`](https://github.com/Effect-TS/effect/commit/016f9ad931a4b3d09a34e5caf13d87c5b8e9c984), [`0779681`](https://github.com/Effect-TS/effect/commit/07796813f07de035719728733096ba64ce333469), [`534129f`](https://github.com/Effect-TS/effect/commit/534129f8113ce1a8ec50828083e16da9c86326c6), [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda), [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03), [`9237ac6`](https://github.com/Effect-TS/effect/commit/9237ac69bc07de5b3b60076a0ad2921c21de7457), [`be0451c`](https://github.com/Effect-TS/effect/commit/be0451c149b6618af79cb839cdf04af2db1efb03), [`5b36494`](https://github.com/Effect-TS/effect/commit/5b364942e9a9003fdb8217324f8a2d8369c969da), [`c716adb`](https://github.com/Effect-TS/effect/commit/c716adb250ebbea1d1048d818ef7fed4f621d186), [`4986391`](https://github.com/Effect-TS/effect/commit/49863919cd8628c962a712fb1df30d2983820933), [`d75140c`](https://github.com/Effect-TS/effect/commit/d75140c7a664ceda43142d999f4ff8dcd36d6dda), [`d1387ae`](https://github.com/Effect-TS/effect/commit/d1387aebd1ff01bbebde26be46d488956e4daef6)]:\n  - effect@3.9.0\n  - @effect/schema@0.75.0\n\n## 0.66.3\n\n### Patch Changes\n\n- [#3736](https://github.com/Effect-TS/effect/pull/3736) [`f40da15`](https://github.com/Effect-TS/effect/commit/f40da15fbeb7c491840b8f409d47de79720891c3) Thanks @tim-smart! - add HttpClientResponse.filterStatus apis\n\n- [#3732](https://github.com/Effect-TS/effect/pull/3732) [`8e94585`](https://github.com/Effect-TS/effect/commit/8e94585abe62753bf3af28bfae77926a7c570ac3) Thanks @sukovanej! - Fix: handle `Blob` message data from a websocket.\n\n- [#3736](https://github.com/Effect-TS/effect/pull/3736) [`f40da15`](https://github.com/Effect-TS/effect/commit/f40da15fbeb7c491840b8f409d47de79720891c3) Thanks @tim-smart! - add HttpClient.retryTransient api\n\n- Updated dependencies [[`88e85db`](https://github.com/Effect-TS/effect/commit/88e85db34bd402526e27a323e950d053fa34d232), [`83887ca`](https://github.com/Effect-TS/effect/commit/83887ca1b1793916913d8550a4db4450cd14a044), [`5266b6c`](https://github.com/Effect-TS/effect/commit/5266b6cd86d76c3886da041c8829bca04b1a3110), [`cdead5c`](https://github.com/Effect-TS/effect/commit/cdead5c9cfd54dc6c4f215d9732f654c4a12e991), [`766a8af`](https://github.com/Effect-TS/effect/commit/766a8af307b414aca3648d91c4eab7493a5ec862)]:\n  - effect@3.8.5\n  - @effect/schema@0.74.2\n\n## 0.66.2\n\n### Patch Changes\n\n- [#3667](https://github.com/Effect-TS/effect/pull/3667) [`fd83d0e`](https://github.com/Effect-TS/effect/commit/fd83d0e548feff9ea2d53d370a0b626c4a1d940e) Thanks @gcanti! - Remove default json schema annotations from string, number and boolean.\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"@effect/schema\"\n\n  const schema = Schema.String.annotations({ examples: [\"a\", \"b\"] })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"description\": \"a string\",\n    \"title\": \"string\",\n    \"examples\": [\n      \"a\",\n      \"b\"\n    ]\n  }\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"@effect/schema\"\n\n  const schema = Schema.String.annotations({ examples: [\"a\", \"b\"] })\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"examples\": [\n      \"a\",\n      \"b\"\n    ]\n  }\n  */\n  ```\n\n- [#3672](https://github.com/Effect-TS/effect/pull/3672) [`090e41c`](https://github.com/Effect-TS/effect/commit/090e41c636d720b1c7d89684a739855765ed4382) Thanks @gcanti! - JSON Schema: handle refinements where the 'from' part includes a transformation, closes #3662\n\n  Before\n\n  ```ts\n  import { JSONSchema, Schema } from \"@effect/schema\"\n\n  const schema = Schema.Date\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  throws\n  Error: Missing annotation\n  details: Generating a JSON Schema for this schema requires a \"jsonSchema\" annotation\n  schema (Refinement): Date\n  */\n  ```\n\n  After\n\n  ```ts\n  import { JSONSchema, Schema } from \"@effect/schema\"\n\n  const schema = Schema.Date\n\n  console.log(JSON.stringify(JSONSchema.make(schema), null, 2))\n  /*\n  {\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"string\",\n    \"description\": \"a string that will be parsed into a Date\"\n  }\n  */\n  ```\n\n- Updated dependencies [[`734eae6`](https://github.com/Effect-TS/effect/commit/734eae654f215e4adca457d04d2a1728b1a55c83), [`fd83d0e`](https://github.com/Effect-TS/effect/commit/fd83d0e548feff9ea2d53d370a0b626c4a1d940e), [`4509656`](https://github.com/Effect-TS/effect/commit/45096569d50262275ee984f44c456f5c83b62683), [`ad7e1de`](https://github.com/Effect-TS/effect/commit/ad7e1de948745c0751bfdac96671028ff4b7a727), [`090e41c`](https://github.com/Effect-TS/effect/commit/090e41c636d720b1c7d89684a739855765ed4382), [`090e41c`](https://github.com/Effect-TS/effect/commit/090e41c636d720b1c7d89684a739855765ed4382)]:\n  - @effect/schema@0.74.1\n  - effect@3.8.4\n\n## 0.66.1\n\n### Patch Changes\n\n- [#3664](https://github.com/Effect-TS/effect/pull/3664) [`3812788`](https://github.com/Effect-TS/effect/commit/3812788d79caaab8f559a62fd443018a04ac5647) Thanks @tim-smart! - add OpenApiJsonSchema module\n\n## 0.66.0\n\n### Patch Changes\n\n- Updated dependencies [[`de48aa5`](https://github.com/Effect-TS/effect/commit/de48aa54e98d97722a8a4c2c8f9e1fe1d4560ea2)]:\n  - @effect/schema@0.74.0\n\n## 0.65.5\n\n### Patch Changes\n\n- [#3640](https://github.com/Effect-TS/effect/pull/3640) [`321b201`](https://github.com/Effect-TS/effect/commit/321b201adcb6bbbeb806b3467dd0b4cf063ccda8) Thanks @tim-smart! - use HttpClientRequest.originalUrl for search params parser\n\n- Updated dependencies [[`bb5ec6b`](https://github.com/Effect-TS/effect/commit/bb5ec6b4b6a6f537394596c5a596faf52cb2aef4)]:\n  - effect@3.8.3\n  - @effect/schema@0.73.4\n\n## 0.65.4\n\n### Patch Changes\n\n- Updated dependencies [[`e6440a7`](https://github.com/Effect-TS/effect/commit/e6440a74fb3f12f6422ed794c07cb44af91cbacc)]:\n  - @effect/schema@0.73.3\n\n## 0.65.3\n\n### Patch Changes\n\n- Updated dependencies [[`f0d8ef1`](https://github.com/Effect-TS/effect/commit/f0d8ef1ce97ec2a87b09b3e24150cfeab85d6e2f)]:\n  - effect@3.8.2\n  - @effect/schema@0.73.2\n\n## 0.65.2\n\n### Patch Changes\n\n- Updated dependencies [[`10bf621`](https://github.com/Effect-TS/effect/commit/10bf6213f36d8ddb00f058a4609b85220f3d8334), [`f56ab78`](https://github.com/Effect-TS/effect/commit/f56ab785cbee0c1c43bd2c182c35602f486f61f0), [`ae36fa6`](https://github.com/Effect-TS/effect/commit/ae36fa68f754eeab9a54b6dc0f8b44db513aa2b6)]:\n  - effect@3.8.1\n  - @effect/schema@0.73.1\n\n## 0.65.1\n\n### Patch Changes\n\n- [#3614](https://github.com/Effect-TS/effect/pull/3614) [`e44c5f2`](https://github.com/Effect-TS/effect/commit/e44c5f228215738fe4e75023c7461bf9521249cb) Thanks @tim-smart! - accept Redacted in HttpClientRequest.basicAuth/bearerToken\n\n## 0.65.0\n\n### Minor Changes\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`7041393`](https://github.com/Effect-TS/effect/commit/7041393cff132e96566d3f36da0483a6ff6195e4) Thanks @tim-smart! - refactor /platform HttpClient\n\n  #### HttpClient.fetch removed\n\n  The `HttpClient.fetch` client implementation has been removed. Instead, you can\n  access a `HttpClient` using the corresponding `Context.Tag`.\n\n  ```ts\n  import { FetchHttpClient, HttpClient } from \"@effect/platform\"\n  import { Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    const client = yield* HttpClient.HttpClient\n\n    // make a get request\n    yield* client.get(\"https://jsonplaceholder.typicode.com/todos/1\")\n  }).pipe(\n    Effect.scoped,\n    // the fetch client has been moved to the `FetchHttpClient` module\n    Effect.provide(FetchHttpClient.layer)\n  )\n  ```\n\n  #### `HttpClient` interface now uses methods\n\n  Instead of being a function that returns the response, the `HttpClient`\n  interface now uses methods to make requests.\n\n  Some shorthand methods have been added to the `HttpClient` interface to make\n  less complex requests easier.\n\n  ```ts\n  import {\n    FetchHttpClient,\n    HttpClient,\n    HttpClientRequest\n  } from \"@effect/platform\"\n  import { Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    const client = yield* HttpClient.HttpClient\n\n    // make a get request\n    yield* client.get(\"https://jsonplaceholder.typicode.com/todos/1\")\n    // make a post request\n    yield* client.post(\"https://jsonplaceholder.typicode.com/todos\")\n\n    // execute a request instance\n    yield* client.execute(\n      HttpClientRequest.get(\"https://jsonplaceholder.typicode.com/todos/1\")\n    )\n  })\n  ```\n\n  #### Scoped `HttpClientResponse` helpers removed\n\n  The `HttpClientResponse` helpers that also supplied the `Scope` have been removed.\n\n  Instead, you can use the `HttpClientResponse` methods directly, and explicitly\n  add a `Effect.scoped` to the pipeline.\n\n  ```ts\n  import { FetchHttpClient, HttpClient } from \"@effect/platform\"\n  import { Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    const client = yield* HttpClient.HttpClient\n\n    yield* client.get(\"https://jsonplaceholder.typicode.com/todos/1\").pipe(\n      Effect.flatMap((response) => response.json),\n      Effect.scoped // supply the `Scope`\n    )\n  })\n  ```\n\n  #### Some apis have been renamed\n\n  Including the `HttpClientRequest` body apis, which is to make them more\n  discoverable.\n\n### Patch Changes\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`812a4e8`](https://github.com/Effect-TS/effect/commit/812a4e86e2d1aa23b477ef5829aa0e5c07784936) Thanks @tim-smart! - add Logger.prettyLoggerDefault, to prevent duplicate pretty loggers\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`6a128f6`](https://github.com/Effect-TS/effect/commit/6a128f63f9b41fec2db70790b3bbb96cb9afa1ab) Thanks @tim-smart! - ensure FetchHttpClient always attempts to send a request body\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`adf7d7a`](https://github.com/Effect-TS/effect/commit/adf7d7a7dfce3a7021e9f3b0d847dc85be89d754) Thanks @tim-smart! - use Mailbox for Workers, Socket & Rpc\n\n- [#3541](https://github.com/Effect-TS/effect/pull/3541) [`e0d21a5`](https://github.com/Effect-TS/effect/commit/e0d21a54c8323728fbb75a32f4820a9996257809) Thanks @fubhy! - Added refinement overloads to `HttpClient.filterOrFail` and `HttpClient.filterOrElse`\n\n- Updated dependencies [[`fcfa6ee`](https://github.com/Effect-TS/effect/commit/fcfa6ee30ffd07d998bf22799357bf58580a116f), [`bb9931b`](https://github.com/Effect-TS/effect/commit/bb9931b62e249a3b801f2cb9d097aec0c8511af7), [`5798f76`](https://github.com/Effect-TS/effect/commit/5798f7619529de33e5ba06f551806f68fedc19db), [`5f0bfa1`](https://github.com/Effect-TS/effect/commit/5f0bfa17205398d4e4818bfbcf9e1b505b3b1fc5), [`7fdf9d9`](https://github.com/Effect-TS/effect/commit/7fdf9d9aa1e2c1c125cbf87991e6efbf4abb7b07), [`812a4e8`](https://github.com/Effect-TS/effect/commit/812a4e86e2d1aa23b477ef5829aa0e5c07784936), [`273565e`](https://github.com/Effect-TS/effect/commit/273565e7901639e8d0541930ab715aea9c80fbaa), [`569a801`](https://github.com/Effect-TS/effect/commit/569a8017ef0a0bc203e4312867cbdd37b0effbd7), [`aa1fa53`](https://github.com/Effect-TS/effect/commit/aa1fa5301e886b9657c8eb0d38cb87cef92a8305), [`02f6b06`](https://github.com/Effect-TS/effect/commit/02f6b0660e12bee1069532a9cc18d3ab855257be), [`12b893e`](https://github.com/Effect-TS/effect/commit/12b893e63cc6dfada4aca7773b4783940e2edf25), [`bbad27e`](https://github.com/Effect-TS/effect/commit/bbad27ec0a90860593f759405caa877e7f4a655f), [`adf7d7a`](https://github.com/Effect-TS/effect/commit/adf7d7a7dfce3a7021e9f3b0d847dc85be89d754), [`007289a`](https://github.com/Effect-TS/effect/commit/007289a52d5877f8e90e2dacf38171ff9bf603fd), [`42a8f99`](https://github.com/Effect-TS/effect/commit/42a8f99740eefdaf2c4544d2c345313f97547a36), [`eebfd29`](https://github.com/Effect-TS/effect/commit/eebfd29633fd5d38b505c5c0842036f61f05e913), [`040703d`](https://github.com/Effect-TS/effect/commit/040703d0e100cd5511e52d812c15492414262b5e)]:\n  - effect@3.8.0\n  - @effect/schema@0.73.0\n\n## 0.64.1\n\n### Patch Changes\n\n- [#3582](https://github.com/Effect-TS/effect/pull/3582) [`8261c5a`](https://github.com/Effect-TS/effect/commit/8261c5ae6fe86872292ec1fc1a58ab9cea2f5f51) Thanks @gcanti! - add missing `encoding` argument to `Command.streamLines`\n\n- Updated dependencies [[`35a0f81`](https://github.com/Effect-TS/effect/commit/35a0f813141652d696461cd5d19fd146adaf85be)]:\n  - effect@3.7.3\n  - @effect/schema@0.72.4\n\n## 0.64.0\n\n### Minor Changes\n\n- [#3565](https://github.com/Effect-TS/effect/pull/3565) [`90ac8f6`](https://github.com/Effect-TS/effect/commit/90ac8f6f6053a2e4498f8b0cc56fe12777d02e1a) Thanks @tim-smart! - move Etag implementation to /platform\n\n### Patch Changes\n\n- [#3565](https://github.com/Effect-TS/effect/pull/3565) [`90ac8f6`](https://github.com/Effect-TS/effect/commit/90ac8f6f6053a2e4498f8b0cc56fe12777d02e1a) Thanks @tim-smart! - add HttpApiBuilder.toWebHandler api\n\n- [#3567](https://github.com/Effect-TS/effect/pull/3567) [`3791e24`](https://github.com/Effect-TS/effect/commit/3791e241636b1dfe924a56f380ebc9a7ff0827a9) Thanks @tim-smart! - reduce boxing in Socket.toChannel implementation\n\n- [#3567](https://github.com/Effect-TS/effect/pull/3567) [`3791e24`](https://github.com/Effect-TS/effect/commit/3791e241636b1dfe924a56f380ebc9a7ff0827a9) Thanks @tim-smart! - add Socket.toChannelString api\n\n- Updated dependencies [[`f6acb71`](https://github.com/Effect-TS/effect/commit/f6acb71b17a0e6b0d449e7f661c9e2c3d335fcac)]:\n  - @effect/schema@0.72.3\n\n## 0.63.3\n\n### Patch Changes\n\n- [#3550](https://github.com/Effect-TS/effect/pull/3550) [`4a701c4`](https://github.com/Effect-TS/effect/commit/4a701c406da032563fedae459536c00ae5cfe3c7) Thanks @tim-smart! - ensure Socket.toChannel fiber is attached to Scope\n\n## 0.63.2\n\n### Patch Changes\n\n- Updated dependencies [[`8a601d7`](https://github.com/Effect-TS/effect/commit/8a601d7a1f8ffe52ac9e6d67e9282a1495fe59c9), [`353ba19`](https://github.com/Effect-TS/effect/commit/353ba19f9b2b9e959f0a00d058c6d40a4bc02db7)]:\n  - effect@3.7.2\n  - @effect/schema@0.72.2\n\n## 0.63.1\n\n### Patch Changes\n\n- Updated dependencies [[`79859e7`](https://github.com/Effect-TS/effect/commit/79859e71040d8edf1868b8530b90c650f4321eff), [`f6a469c`](https://github.com/Effect-TS/effect/commit/f6a469c190b9f00eee5ea0cd4d5912a0ef8b46f5), [`dcb9ec0`](https://github.com/Effect-TS/effect/commit/dcb9ec0db443894dd204d87450f779c44b9ad7f1), [`79aa6b1`](https://github.com/Effect-TS/effect/commit/79aa6b136e1f29b36f34e88cb2ff162bff2bb4ed)]:\n  - effect@3.7.1\n  - @effect/schema@0.72.1\n\n## 0.63.0\n\n### Patch Changes\n\n- [#3410](https://github.com/Effect-TS/effect/pull/3410) [`6bf28f7`](https://github.com/Effect-TS/effect/commit/6bf28f7e3b1e5e0608ff567205fea0581d11666f) Thanks @tim-smart! - add HttpApi modules\n\n  The `HttpApi` family of modules provide a declarative way to define HTTP APIs.\n\n  For more infomation see the README.md for the /platform package:<br />\n  https://github.com/Effect-TS/effect/blob/main/packages/platform/README.md\n\n- Updated dependencies [[`db89601`](https://github.com/Effect-TS/effect/commit/db89601ee9c1050c4e762b7bd7ec65a6a2799dfe), [`2f456cc`](https://github.com/Effect-TS/effect/commit/2f456cce5012b9fcb6b4e039190d527813b75b92), [`8745e41`](https://github.com/Effect-TS/effect/commit/8745e41ed96e3765dc6048efc2a9afbe05c8a1e9), [`e557838`](https://github.com/Effect-TS/effect/commit/e55783886b046d3c5f33447f455f9ccf2fa75922), [`d6e7e40`](https://github.com/Effect-TS/effect/commit/d6e7e40b1e2ad0c59aa02f07344d28601b14ebdc), [`8356321`](https://github.com/Effect-TS/effect/commit/8356321598da04bd77c1001f45a4e447bec5591d), [`192f2eb`](https://github.com/Effect-TS/effect/commit/192f2ebb2c4ddbf4bfd8baedd32140b2376868f4), [`718cb70`](https://github.com/Effect-TS/effect/commit/718cb70038629a6d58d02e407760e341f7c94474), [`e9d0310`](https://github.com/Effect-TS/effect/commit/e9d03107acbf204d9304f3e8aea0816b7d3c7dfb), [`6bf28f7`](https://github.com/Effect-TS/effect/commit/6bf28f7e3b1e5e0608ff567205fea0581d11666f)]:\n  - effect@3.7.0\n  - @effect/schema@0.72.0\n\n## 0.62.5\n\n### Patch Changes\n\n- Updated dependencies [[`e809286`](https://github.com/Effect-TS/effect/commit/e8092865900608c4df7a6b7991b1c13cc1e4ca2d)]:\n  - effect@3.6.8\n  - @effect/schema@0.71.4\n\n## 0.62.4\n\n### Patch Changes\n\n- [#3506](https://github.com/Effect-TS/effect/pull/3506) [`e7a65e3`](https://github.com/Effect-TS/effect/commit/e7a65e3c6a08636bbfce3d3af3098bf28474364d) Thanks @tim-smart! - use Logger.pretty for runMain, and support dual usage\n\n- Updated dependencies [[`50ec889`](https://github.com/Effect-TS/effect/commit/50ec8897a49b7d1fe84f63107f89d543c52f3dfc)]:\n  - effect@3.6.7\n  - @effect/schema@0.71.3\n\n## 0.62.3\n\n### Patch Changes\n\n- Updated dependencies [[`f960bf4`](https://github.com/Effect-TS/effect/commit/f960bf45239e9badac6e0ad3a602f4174cd7bbdf), [`46a575f`](https://github.com/Effect-TS/effect/commit/46a575f48a05457b782fb21f7827d338c9b59320)]:\n  - effect@3.6.6\n  - @effect/schema@0.71.2\n\n## 0.62.2\n\n### Patch Changes\n\n- [#3494](https://github.com/Effect-TS/effect/pull/3494) [`413994c`](https://github.com/Effect-TS/effect/commit/413994c9792f16d9d57cca3ae6eb254bf93bd261) Thanks @tim-smart! - add binary support to KeyValueStore\n\n- Updated dependencies [[`14a47a8`](https://github.com/Effect-TS/effect/commit/14a47a8c1f3cff2186b8fe7a919a1d773888fb5b), [`0c09841`](https://github.com/Effect-TS/effect/commit/0c0984173be3d58f050b300a1a8aa89d76ba49ae)]:\n  - effect@3.6.5\n  - @effect/schema@0.71.1\n\n## 0.62.1\n\n### Patch Changes\n\n- [#3469](https://github.com/Effect-TS/effect/pull/3469) [`9efe0e5`](https://github.com/Effect-TS/effect/commit/9efe0e5b57ac557399be620822c21cc6e9add285) Thanks @tim-smart! - respond with 404 for NoSuchElementException in HttpServerRespondable\n\n## 0.62.0\n\n### Patch Changes\n\n- [#3454](https://github.com/Effect-TS/effect/pull/3454) [`5dcb401`](https://github.com/Effect-TS/effect/commit/5dcb401bfc52a5c8f8934b1f95adf0ad515277d6) Thanks @tim-smart! - add HttpRouter.currentRouterConfig fiber ref\n\n- [#3450](https://github.com/Effect-TS/effect/pull/3450) [`0e42a8f`](https://github.com/Effect-TS/effect/commit/0e42a8f045ecb1fd3d080edf3d49fef16a9b0ca1) Thanks @tim-smart! - update dependencies\n\n- Updated dependencies [[`c1987e2`](https://github.com/Effect-TS/effect/commit/c1987e25c8f5c48bdc9ad223d7a6f2c32f93f5a1), [`8295281`](https://github.com/Effect-TS/effect/commit/8295281ae9bd7441e680402540bf3c8682ec417b), [`c940df6`](https://github.com/Effect-TS/effect/commit/c940df63800bf3c4396d91cf28ec34938642fd2c), [`00b6c6d`](https://github.com/Effect-TS/effect/commit/00b6c6d4001f5de728b7d990a1b14560b4961a63), [`1ceed14`](https://github.com/Effect-TS/effect/commit/1ceed149dc64f4874e64b5cf2f954eba0a5a1f12), [`f8d95a6`](https://github.com/Effect-TS/effect/commit/f8d95a61ad0762147933c5c32bb6d7237e18eef4), [`0e42a8f`](https://github.com/Effect-TS/effect/commit/0e42a8f045ecb1fd3d080edf3d49fef16a9b0ca1)]:\n  - @effect/schema@0.71.0\n  - effect@3.6.4\n\n## 0.61.8\n\n### Patch Changes\n\n- Updated dependencies [[`04adcac`](https://github.com/Effect-TS/effect/commit/04adcace913e6fc483df266874a68005e9e04ccf)]:\n  - effect@3.6.3\n  - @effect/schema@0.70.4\n\n## 0.61.7\n\n### Patch Changes\n\n- [#3437](https://github.com/Effect-TS/effect/pull/3437) [`17245a4`](https://github.com/Effect-TS/effect/commit/17245a4e783c19dee51529600b3b40f164fa59bc) Thanks @tim-smart! - add Cookies.get/getValue apis\n\n- [#3439](https://github.com/Effect-TS/effect/pull/3439) [`630d40e`](https://github.com/Effect-TS/effect/commit/630d40eaa7eb4d2f8b6705b16d4f426bc28a7d09) Thanks @sukovanej! - Add `HttpRouter.concatAll`.\n\n- [#3439](https://github.com/Effect-TS/effect/pull/3439) [`630d40e`](https://github.com/Effect-TS/effect/commit/630d40eaa7eb4d2f8b6705b16d4f426bc28a7d09) Thanks @sukovanej! - Fix `HttpRouter.concat` - add mounts from both routers.\n\n## 0.61.6\n\n### Patch Changes\n\n- [#3436](https://github.com/Effect-TS/effect/pull/3436) [`d829b57`](https://github.com/Effect-TS/effect/commit/d829b576357f2e3b203ab7e107a1492de903a106) Thanks @tim-smart! - remove host from HttpServerRequest url's\n\n- Updated dependencies [[`99ad841`](https://github.com/Effect-TS/effect/commit/99ad8415293a82d08bd7043c563b29e2b468ca74), [`fd4b2f6`](https://github.com/Effect-TS/effect/commit/fd4b2f6516b325740dde615f1cf0229edf13ca0c)]:\n  - @effect/schema@0.70.3\n  - effect@3.6.2\n\n## 0.61.5\n\n### Patch Changes\n\n- [#3409](https://github.com/Effect-TS/effect/pull/3409) [`056b710`](https://github.com/Effect-TS/effect/commit/056b7108978e70612176c23991916f678d947f38) Thanks @sukovanej! - Add `HttpClient.layerTest`.\n\n## 0.61.4\n\n### Patch Changes\n\n- [#3414](https://github.com/Effect-TS/effect/pull/3414) [`e7cb109`](https://github.com/Effect-TS/effect/commit/e7cb109d0754207024a64d55b6bd2a674dd8ed7d) Thanks @tim-smart! - ensure broken HttpMiddleware that doesn't fail responds\n\n## 0.61.3\n\n### Patch Changes\n\n- [#3408](https://github.com/Effect-TS/effect/pull/3408) [`fb9f786`](https://github.com/Effect-TS/effect/commit/fb9f7867f0c895e63f9ef23e8d0941248c42179d) Thanks @tim-smart! - ensure failure in HttpMiddleware results in a response\n\n- Updated dependencies [[`510a34d`](https://github.com/Effect-TS/effect/commit/510a34d4cc5d2f51347a53847f6c7db84d2b17c6), [`45dbb9f`](https://github.com/Effect-TS/effect/commit/45dbb9ffeaf93d9e4df99d0cd4920e41ba9a3978)]:\n  - effect@3.6.1\n  - @effect/schema@0.70.2\n\n## 0.61.2\n\n### Patch Changes\n\n- Updated dependencies [[`3dce357`](https://github.com/Effect-TS/effect/commit/3dce357efe4a4451d7d29859d08ac11713999b1a), [`657fc48`](https://github.com/Effect-TS/effect/commit/657fc48bb32daf2dc09c9335b3cbc3152bcbdd3b)]:\n  - @effect/schema@0.70.1\n\n## 0.61.1\n\n### Patch Changes\n\n- [#3384](https://github.com/Effect-TS/effect/pull/3384) [`11223bf`](https://github.com/Effect-TS/effect/commit/11223bf9cbf5b822e0bf9a9fb2b35b2ad88af692) Thanks @tim-smart! - use type alias for HttpApp\n\n## 0.61.0\n\n### Patch Changes\n\n- [#3380](https://github.com/Effect-TS/effect/pull/3380) [`7d02174`](https://github.com/Effect-TS/effect/commit/7d02174af3bcbf054e5cdddb821c91d0f47e8285) Thanks @fubhy! - Changed various function signatures to return `Array` instead of `ReadonlyArray`\n\n- Updated dependencies [[`1e0fe80`](https://github.com/Effect-TS/effect/commit/1e0fe802b36c257971296617473ce0abe730e8dc), [`8135294`](https://github.com/Effect-TS/effect/commit/8135294b591ea94fde7e6f94a504608f0e630520), [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987), [`3845646`](https://github.com/Effect-TS/effect/commit/3845646828e98f3c7cda1217f6cfe5f642ac0603), [`2d09078`](https://github.com/Effect-TS/effect/commit/2d09078c5948b37fc2f79ef858fe4ca3e4814085), [`4bce5a0`](https://github.com/Effect-TS/effect/commit/4bce5a0274203550ccf117d830721891b0a3d182), [`4ddbff0`](https://github.com/Effect-TS/effect/commit/4ddbff0bb4e3ffddfeb509c59835b83245fb975e), [`e74cc38`](https://github.com/Effect-TS/effect/commit/e74cc38cb420a320c4d7ef98180f19d452a8b316), [`bb069b4`](https://github.com/Effect-TS/effect/commit/bb069b49ef291c532a02c1e8e74271f6d1bb32ec), [`cd255a4`](https://github.com/Effect-TS/effect/commit/cd255a48872d8fb924cf713ef73f0883a9cc6987), [`7d02174`](https://github.com/Effect-TS/effect/commit/7d02174af3bcbf054e5cdddb821c91d0f47e8285)]:\n  - effect@3.6.0\n  - @effect/schema@0.70.0\n\n## 0.60.3\n\n### Patch Changes\n\n- Updated dependencies [[`7c0da50`](https://github.com/Effect-TS/effect/commit/7c0da5050d30cb804f4eacb15995d0fb7f3a28d2), [`2fc0ff4`](https://github.com/Effect-TS/effect/commit/2fc0ff4c59c25977018f6ac70ced99b04a8c7b2b), [`6359644`](https://github.com/Effect-TS/effect/commit/635964446323cf55d4060559337e710e4a24496e), [`f262665`](https://github.com/Effect-TS/effect/commit/f262665c2773492c01e5dd0e8d6db235aafaaad8), [`7f41e42`](https://github.com/Effect-TS/effect/commit/7f41e428830bf3043b8be0d28dcd235d5747c942), [`9bbe7a6`](https://github.com/Effect-TS/effect/commit/9bbe7a681430ebf5c10167bb7140ba3742e46bb7), [`f566fd1`](https://github.com/Effect-TS/effect/commit/f566fd1d7eea531a0d981dd24037f14a603a1273)]:\n  - @effect/schema@0.69.3\n  - effect@3.5.9\n\n## 0.60.2\n\n### Patch Changes\n\n- [#3339](https://github.com/Effect-TS/effect/pull/3339) [`eb4d014`](https://github.com/Effect-TS/effect/commit/eb4d014c559e1b4c95b3fb9295fe77593c17ed7a) Thanks @fubhy! - Fixed various search params related function signatures (`Array => ReadonlyArray`)\n\n- [#3353](https://github.com/Effect-TS/effect/pull/3353) [`fc20f73`](https://github.com/Effect-TS/effect/commit/fc20f73c69e577981cb64714de2adc97e1004dae) Thanks @tim-smart! - wait for worker ready latch before sending initial message\n\n- Updated dependencies [[`1ba640c`](https://github.com/Effect-TS/effect/commit/1ba640c702f187a866023bf043c26e25cce941ef), [`c8c71bd`](https://github.com/Effect-TS/effect/commit/c8c71bd20eb87d23133dac6156b83bb08941597c), [`a26ce58`](https://github.com/Effect-TS/effect/commit/a26ce581ca7d407e1e81439b58c8045b3fa65231)]:\n  - effect@3.5.8\n  - @effect/schema@0.69.2\n\n## 0.60.1\n\n### Patch Changes\n\n- Updated dependencies [[`f241154`](https://github.com/Effect-TS/effect/commit/f241154added5d91e95866c39481f09cdb13bd4d)]:\n  - @effect/schema@0.69.1\n\n## 0.60.0\n\n### Patch Changes\n\n- Updated dependencies [[`20807a4`](https://github.com/Effect-TS/effect/commit/20807a45edeb4334e903dca5d708cd62a71702d8)]:\n  - @effect/schema@0.69.0\n\n## 0.59.3\n\n### Patch Changes\n\n- [#3310](https://github.com/Effect-TS/effect/pull/3310) [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc) Thanks @fubhy! - Added additional pure annotations to improve tree-shakeability\n\n- Updated dependencies [[`3afcc93`](https://github.com/Effect-TS/effect/commit/3afcc93413a3d910beb69e4ce9ae120e4adaffd5), [`99bddcf`](https://github.com/Effect-TS/effect/commit/99bddcfb3d6eab4d489d055404e26ad81afe52fc), [`6921c4f`](https://github.com/Effect-TS/effect/commit/6921c4fb8c45badff09b493043b85ca71302b560)]:\n  - effect@3.5.7\n  - @effect/schema@0.68.27\n\n## 0.59.2\n\n### Patch Changes\n\n- Updated dependencies [[`f0285d3`](https://github.com/Effect-TS/effect/commit/f0285d3af6a18829123bc1818331c67206becbc4), [`8ec4955`](https://github.com/Effect-TS/effect/commit/8ec49555ed3b3c98093fa4d135a4c57a3f16ebd1), [`3ac2d76`](https://github.com/Effect-TS/effect/commit/3ac2d76048da09e876cf6c3aee3397febd843fe9), [`cc327a1`](https://github.com/Effect-TS/effect/commit/cc327a1bccd22a4ee27ec7e58b53205e93b23e2c), [`4bfe4fb`](https://github.com/Effect-TS/effect/commit/4bfe4fb5c82f597c9beea9baa92e772593598b60), [`2b14d18`](https://github.com/Effect-TS/effect/commit/2b14d181462cad8359da4fa6bc6dfda0f742c398)]:\n  - @effect/schema@0.68.26\n  - effect@3.5.6\n\n## 0.59.1\n\n### Patch Changes\n\n- [#3278](https://github.com/Effect-TS/effect/pull/3278) [`fcecff7`](https://github.com/Effect-TS/effect/commit/fcecff7f7e12b295a252f124861b801c73072151) Thanks @tim-smart! - ensure /platform HttpApp.toWebHandler runs Stream's with the current runtime\n\n  Also add runtime options to HttpServerResponse.toWeb\n\n- [#3281](https://github.com/Effect-TS/effect/pull/3281) [`adbf753`](https://github.com/Effect-TS/effect/commit/adbf75340a9db15dc5cadc66e911a8978a195a65) Thanks @tim-smart! - drop path-browserify dependency\n\n- [#3281](https://github.com/Effect-TS/effect/pull/3281) [`adbf753`](https://github.com/Effect-TS/effect/commit/adbf75340a9db15dc5cadc66e911a8978a195a65) Thanks @tim-smart! - drop fast-querystring dependency\n\n- Updated dependencies [[`a9d7800`](https://github.com/Effect-TS/effect/commit/a9d7800f6a253192b653d77778b0674f39b1ca39)]:\n  - effect@3.5.5\n  - @effect/schema@0.68.25\n\n## 0.59.0\n\n### Minor Changes\n\n- [#3260](https://github.com/Effect-TS/effect/pull/3260) [`53c0db0`](https://github.com/Effect-TS/effect/commit/53c0db06872d5b5edea2a706e83249908385325c) Thanks @tim-smart! - replace /platform RefailError with use of the \"cause\" property\n\n- [#3255](https://github.com/Effect-TS/effect/pull/3255) [`ada68b3`](https://github.com/Effect-TS/effect/commit/ada68b3e61c67907c2a281c024c84d818186ca4c) Thanks @tim-smart! - refactor & simplify /platform backing workers\n\n  Improves worker performance by 2x\n\n### Patch Changes\n\n- Updated dependencies [[`ed0dde4`](https://github.com/Effect-TS/effect/commit/ed0dde4888e6f1a97ad5bba06b755d26a6a1c52e), [`ca775ce`](https://github.com/Effect-TS/effect/commit/ca775cec53baebc1a43d9b8852a3ac6726178498), [`5be9cc0`](https://github.com/Effect-TS/effect/commit/5be9cc044025a9541b9b7acefa2d3fc05fa1301b), [`203658f`](https://github.com/Effect-TS/effect/commit/203658f8001c132b25764ab70344b171683b554c), [`eb1c4d4`](https://github.com/Effect-TS/effect/commit/eb1c4d44e54b9d8d201a366d1ff94face2a6dcd3)]:\n  - effect@3.5.4\n  - @effect/schema@0.68.24\n\n## 0.58.27\n\n### Patch Changes\n\n- [#3241](https://github.com/Effect-TS/effect/pull/3241) [`a1db40a`](https://github.com/Effect-TS/effect/commit/a1db40a650ab842e778654f0d88e80f2ef4fd6f3) Thanks @tim-smart! - ensure interrupts are handled in WorkerRunner\n\n- Updated dependencies [[`edb0da3`](https://github.com/Effect-TS/effect/commit/edb0da383746d760f35d8582f5fb0cc0eeca9217), [`edb0da3`](https://github.com/Effect-TS/effect/commit/edb0da383746d760f35d8582f5fb0cc0eeca9217), [`c8d3fb0`](https://github.com/Effect-TS/effect/commit/c8d3fb0fe23585f6efb724af51fbab3ba1ad6e83), [`dabd028`](https://github.com/Effect-TS/effect/commit/dabd028decf9b7983ca16ebe0f48c05c11a84b68), [`786b2ab`](https://github.com/Effect-TS/effect/commit/786b2ab29d525c877bb84035dac9e2d6499339d1), [`fc57354`](https://github.com/Effect-TS/effect/commit/fc573547d41667016fce05eaee75960fcc6dce4d)]:\n  - effect@3.5.3\n  - @effect/schema@0.68.23\n\n## 0.58.26\n\n### Patch Changes\n\n- Updated dependencies [[`639208e`](https://github.com/Effect-TS/effect/commit/639208eeb8a44622994f832bc2d45d06ab636bc8), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5), [`6684b4c`](https://github.com/Effect-TS/effect/commit/6684b4c27d77a7fcc7af2e261a450edf971b62b5)]:\n  - effect@3.5.2\n  - @effect/schema@0.68.22\n\n## 0.58.25\n\n### Patch Changes\n\n- [#3223](https://github.com/Effect-TS/effect/pull/3223) [`0623fca`](https://github.com/Effect-TS/effect/commit/0623fca41679b0e3c5a10dd0f8985f91670bd721) Thanks @tim-smart! - improve /platform/WorkerError messages\n\n## 0.58.24\n\n### Patch Changes\n\n- Updated dependencies [[`55fdd76`](https://github.com/Effect-TS/effect/commit/55fdd761ee95afd73b6a892c13fee92b36c02837)]:\n  - effect@3.5.1\n  - @effect/schema@0.68.21\n\n## 0.58.23\n\n### Patch Changes\n\n- Updated dependencies [[`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`5ab348f`](https://github.com/Effect-TS/effect/commit/5ab348f265db3d283aa091ddca6d2d49137c16f2), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`3e04bf8`](https://github.com/Effect-TS/effect/commit/3e04bf8a7127e956cadb7684a8f4c661df57663b), [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3), [`a1f5b83`](https://github.com/Effect-TS/effect/commit/a1f5b831a1bc7535988b370d68d0b3eb1123e0ce), [`4626de5`](https://github.com/Effect-TS/effect/commit/4626de59c25b384216faa0be87bf0b8cd36357d0), [`f01e7db`](https://github.com/Effect-TS/effect/commit/f01e7db317827255d7901f523f2e28b43298e8df), [`60bc3d0`](https://github.com/Effect-TS/effect/commit/60bc3d0867b13e48b24dc22604b4dd2e7b2c1ca4), [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6), [`ac71f37`](https://github.com/Effect-TS/effect/commit/ac71f378f2413e5aa91c95f649ffe898d6a26114), [`8432360`](https://github.com/Effect-TS/effect/commit/8432360ce68614a419bb328083a4109d0fc8aa93), [`e4bf1bf`](https://github.com/Effect-TS/effect/commit/e4bf1bf2b4a970eacd77c9b77b5ea8c68bc84498), [`13cb861`](https://github.com/Effect-TS/effect/commit/13cb861a5eded15c55c6cdcf6a8acde8320367a6), [`79d2d91`](https://github.com/Effect-TS/effect/commit/79d2d91464d95dde0e9444d43e7a7f309f05d6e6), [`e7fc45f`](https://github.com/Effect-TS/effect/commit/e7fc45f0c7002aafdaec7878149ac064cd104ea3), [`9f66825`](https://github.com/Effect-TS/effect/commit/9f66825f1fce0fe8d10420c285f7dc4c71e8af8d)]:\n  - effect@3.5.0\n  - @effect/schema@0.68.20\n\n## 0.58.22\n\n### Patch Changes\n\n- [#3209](https://github.com/Effect-TS/effect/pull/3209) [`366f2ee`](https://github.com/Effect-TS/effect/commit/366f2ee3fb6f712a44e8f84fc188612e5ecc016d) Thanks @tim-smart! - simplify /platform http response handling\n\n- [#3209](https://github.com/Effect-TS/effect/pull/3209) [`366f2ee`](https://github.com/Effect-TS/effect/commit/366f2ee3fb6f712a44e8f84fc188612e5ecc016d) Thanks @tim-smart! - support middleware in HttpApp web handler apis\n\n- Updated dependencies [[`7af137c`](https://github.com/Effect-TS/effect/commit/7af137c9433f6e74959b3887561ec1e6f12e10ee), [`ee4b3dc`](https://github.com/Effect-TS/effect/commit/ee4b3dc5f68d19dc3ae1c2d12901c5b8ffbebabb), [`097d25c`](https://github.com/Effect-TS/effect/commit/097d25cb5d13c049e01789651be56b09620186ef)]:\n  - effect@3.4.9\n  - @effect/schema@0.68.19\n\n## 0.58.21\n\n### Patch Changes\n\n- Updated dependencies [[`5d5cc6c`](https://github.com/Effect-TS/effect/commit/5d5cc6cfd7d63b07081290fb189b364999201fc5), [`a435e0f`](https://github.com/Effect-TS/effect/commit/a435e0fc5378b33a49bcec92ee235df6f16a2419), [`b5554db`](https://github.com/Effect-TS/effect/commit/b5554db36c4dd6f64fa5e6a62a29b2759c54217a), [`359ff8a`](https://github.com/Effect-TS/effect/commit/359ff8aa2e4e6389bf56d759baa804e2a7674a16), [`a9c4fb3`](https://github.com/Effect-TS/effect/commit/a9c4fb3bf3c6e92cd1c142b0605fddf7eb3c697c), [`f7534b9`](https://github.com/Effect-TS/effect/commit/f7534b94cba06b143a3d4f29275d92874a939559)]:\n  - @effect/schema@0.68.18\n  - effect@3.4.8\n\n## 0.58.20\n\n### Patch Changes\n\n- Updated dependencies [[`15967cf`](https://github.com/Effect-TS/effect/commit/15967cf18931fb6ede3083eb687a8dfff371cc56), [`2328e17`](https://github.com/Effect-TS/effect/commit/2328e17577112db17c29b7756942a0ff64a70ee0), [`a5737d6`](https://github.com/Effect-TS/effect/commit/a5737d6db2b921605c332eabbc5402ee3d17357b)]:\n  - @effect/schema@0.68.17\n  - effect@3.4.7\n\n## 0.58.19\n\n### Patch Changes\n\n- Updated dependencies [[`d006cec`](https://github.com/Effect-TS/effect/commit/d006cec022e8524dbfd6dc6df751fe4c86b10042), [`cb22726`](https://github.com/Effect-TS/effect/commit/cb2272656881aa5878a1c3fc0b12d8fbc66eb63c), [`e911cfd`](https://github.com/Effect-TS/effect/commit/e911cfdc79418462d7e9000976fded15ea6b738d)]:\n  - @effect/schema@0.68.16\n\n## 0.58.18\n\n### Patch Changes\n\n- [#3136](https://github.com/Effect-TS/effect/pull/3136) [`7f8900a`](https://github.com/Effect-TS/effect/commit/7f8900a1de9addeb0d371103a2c5c2aa3e4ff95e) Thanks @tim-smart! - support undefined in http request schema apis\n\n## 0.58.17\n\n### Patch Changes\n\n- Updated dependencies [[`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`34faeb6`](https://github.com/Effect-TS/effect/commit/34faeb6305ba52af4d6f8bdd2e633bb6a5a7a35b), [`33735b1`](https://github.com/Effect-TS/effect/commit/33735b16b41bd26929d8f4754c190925db6323b7), [`5c0ceb0`](https://github.com/Effect-TS/effect/commit/5c0ceb00826cce9e50bf9d41d83e191d5352c030), [`139d4b3`](https://github.com/Effect-TS/effect/commit/139d4b39fb3bff2eeaa7c0c809c581da42425a83)]:\n  - effect@3.4.6\n  - @effect/schema@0.68.15\n\n## 0.58.16\n\n### Patch Changes\n\n- Updated dependencies [[`61e5964`](https://github.com/Effect-TS/effect/commit/61e59640fd993216cca8ace0ac8abd9104e213ce)]:\n  - @effect/schema@0.68.14\n\n## 0.58.15\n\n### Patch Changes\n\n- [#3123](https://github.com/Effect-TS/effect/pull/3123) [`baa90df`](https://github.com/Effect-TS/effect/commit/baa90df9663f5f37d7b6814dad25142d53dbc720) Thanks @tim-smart! - add HttpClient.followRedirects api\n\n- Updated dependencies [[`cb76bcb`](https://github.com/Effect-TS/effect/commit/cb76bcb2f8858a90db4f785efee262cea1b9844e)]:\n  - @effect/schema@0.68.13\n\n## 0.58.14\n\n### Patch Changes\n\n- [#3104](https://github.com/Effect-TS/effect/pull/3104) [`52a87c7`](https://github.com/Effect-TS/effect/commit/52a87c7a0b9536398deaf8ec507e53a82c607219) Thanks @tim-smart! - remove the stack from HttpServerError.RouteNotFound\n\n- [#3109](https://github.com/Effect-TS/effect/pull/3109) [`6d2280e`](https://github.com/Effect-TS/effect/commit/6d2280e9497c95cb0e965ca462c825345074eedf) Thanks @tim-smart! - fix assignability of HttpMiddleware in HttpRouter.use\n\n## 0.58.13\n\n### Patch Changes\n\n- [#3102](https://github.com/Effect-TS/effect/pull/3102) [`dbd53ea`](https://github.com/Effect-TS/effect/commit/dbd53ea363c71a24449cb068251054c3a1acf864) Thanks @tim-smart! - filter undefined from UrlParams Input\n\n- Updated dependencies [[`a047af9`](https://github.com/Effect-TS/effect/commit/a047af99447dfffc729e9c8ef0ca143537927e91), [`d990544`](https://github.com/Effect-TS/effect/commit/d9905444b9e800850cb65899114ca0e502e68fe8)]:\n  - effect@3.4.5\n  - @effect/schema@0.68.12\n\n## 0.58.12\n\n### Patch Changes\n\n- [#3094](https://github.com/Effect-TS/effect/pull/3094) [`74e0ad2`](https://github.com/Effect-TS/effect/commit/74e0ad23b4c36f41b7fd10856b20f8b701bc4044) Thanks @tim-smart! - add mount apis to HttpRouter.Service\n\n- [#3094](https://github.com/Effect-TS/effect/pull/3094) [`74e0ad2`](https://github.com/Effect-TS/effect/commit/74e0ad23b4c36f41b7fd10856b20f8b701bc4044) Thanks @tim-smart! - add HttpRouter.DefaultServices to all HttpRouter.Tag's\n\n- Updated dependencies [[`72638e3`](https://github.com/Effect-TS/effect/commit/72638e3d99f0e93a24febf6c225256ce92d4a20b), [`d7dde2b`](https://github.com/Effect-TS/effect/commit/d7dde2b4af08b37af859d4c327c1f5c6f00cf9d9), [`9b2fc3b`](https://github.com/Effect-TS/effect/commit/9b2fc3b9dfd304a2bd0508ef2313cfc54357be0c), [`d71c192`](https://github.com/Effect-TS/effect/commit/d71c192b89fd1162423acddc5fd3d6270fbf2ef6)]:\n  - effect@3.4.4\n  - @effect/schema@0.68.11\n\n## 0.58.11\n\n### Patch Changes\n\n- [#3091](https://github.com/Effect-TS/effect/pull/3091) [`a5b95b5`](https://github.com/Effect-TS/effect/commit/a5b95b548284e4798654ae7ce6883fa49108f0ea) Thanks @tim-smart! - add some common services to HttpRouter.Default\n\n- [#3090](https://github.com/Effect-TS/effect/pull/3090) [`5e29579`](https://github.com/Effect-TS/effect/commit/5e29579187cb8420ea4930b3999fec984f8999f4) Thanks @tim-smart! - add HttpServerRequest.toURL api\n\n  To try retreive the full URL for the request.\n\n## 0.58.10\n\n### Patch Changes\n\n- [#3088](https://github.com/Effect-TS/effect/pull/3088) [`a48ee84`](https://github.com/Effect-TS/effect/commit/a48ee845ac21bbde9baf938af9e97a98322211c9) Thanks @tim-smart! - add HttpServerRespondable trait\n\n  This trait allows you to define how a value should be responded to in an HTTP\n  server.\n\n  You can it for both errors and success values.\n\n  ```ts\n  import { Schema } from \"@effect/schema\"\n  import {\n    HttpRouter,\n    HttpServerRespondable,\n    HttpServerResponse\n  } from \"@effect/platform\"\n\n  class User extends Schema.Class<User>(\"User\")({\n    name: Schema.String\n  }) {\n    [HttpServerRespondable.symbol]() {\n      return HttpServerResponse.schemaJson(User)(this)\n    }\n  }\n\n  class MyError extends Schema.TaggedError<MyError>()(\"MyError\", {\n    message: Schema.String\n  }) {\n    [HttpServerRespondable.symbol]() {\n      return HttpServerResponse.schemaJson(MyError)(this, { status: 403 })\n    }\n  }\n\n  HttpRouter.empty.pipe(\n    // responds with `{ \"name\": \"test\" }`\n    HttpRouter.get(\"/user\", Effect.succeed(new User({ name: \"test\" }))),\n    // responds with a 403 status, and `{ \"_tag\": \"MyError\", \"message\": \"boom\" }`\n    HttpRouter.get(\"/fail\", new MyError({ message: \"boom\" }))\n  )\n  ```\n\n- [#3088](https://github.com/Effect-TS/effect/pull/3088) [`a48ee84`](https://github.com/Effect-TS/effect/commit/a48ee845ac21bbde9baf938af9e97a98322211c9) Thanks @tim-smart! - swap type parameters for HttpRouter.Tag, so request context comes first\n\n- [#3088](https://github.com/Effect-TS/effect/pull/3088) [`a48ee84`](https://github.com/Effect-TS/effect/commit/a48ee845ac21bbde9baf938af9e97a98322211c9) Thanks @tim-smart! - add HttpRouter.Default, a default instance of HttpRouter.Tag\n\n- [#3089](https://github.com/Effect-TS/effect/pull/3089) [`ab3180f`](https://github.com/Effect-TS/effect/commit/ab3180f827041d0ea3b2d72254a1a8683e99e056) Thanks @tim-smart! - add HttpClientResponse.matchStatus\\* apis\n\n  Which allows you to pattern match on the status code of a response.\n\n  ```ts\n  HttpClientRequest.get(\"/todos/1\").pipe(\n    HttpClient.fetch,\n    HttpClientResponse.matchStatusScoped({\n      \"2xx\": (_response) => Effect.succeed(\"ok\"),\n      404: (_response) => Effect.fail(\"not found\"),\n      orElse: (_response) => Effect.fail(\"boom\")\n    })\n  )\n  ```\n\n- [#3079](https://github.com/Effect-TS/effect/pull/3079) [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd) Thanks @tim-smart! - update to typescript 5.5\n\n- Updated dependencies [[`c342739`](https://github.com/Effect-TS/effect/commit/c3427396226e1ad7b95b40595a23f9bdff3e3365), [`8898e5e`](https://github.com/Effect-TS/effect/commit/8898e5e238622f6337583d91ee23609c1f5ccdf7), [`ff78636`](https://github.com/Effect-TS/effect/commit/ff786367c522975f40f0f179a0ecdfcfab7ecbdb), [`c86bd4e`](https://github.com/Effect-TS/effect/commit/c86bd4e134c23146c216f9ff97e03781d55991b6), [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd), [`bbdd365`](https://github.com/Effect-TS/effect/commit/bbdd36567706c94cdec45bacea825941c347b6cd)]:\n  - effect@3.4.3\n  - @effect/schema@0.68.10\n\n## 0.58.9\n\n### Patch Changes\n\n- Updated dependencies [[`0b47fdf`](https://github.com/Effect-TS/effect/commit/0b47fdfe449f42de89e0e88b61ae5140f629e5c4)]:\n  - @effect/schema@0.68.9\n\n## 0.58.8\n\n### Patch Changes\n\n- Updated dependencies [[`192261b`](https://github.com/Effect-TS/effect/commit/192261b2aec94e9913ceed83683fdcfbc9fca66f), [`3da1497`](https://github.com/Effect-TS/effect/commit/3da1497b5c9cc886d300258bc928fd68a4fefe6f)]:\n  - @effect/schema@0.68.8\n  - effect@3.4.2\n\n## 0.58.7\n\n### Patch Changes\n\n- [#3064](https://github.com/Effect-TS/effect/pull/3064) [`027004a`](https://github.com/Effect-TS/effect/commit/027004a897f654791e75faa28eefb50dd0244b6e) Thanks @tim-smart! - add HttpRouter.Tag.unwrap api\n\n## 0.58.6\n\n### Patch Changes\n\n- [#3059](https://github.com/Effect-TS/effect/pull/3059) [`2e8e252`](https://github.com/Effect-TS/effect/commit/2e8e2520cac712f0eb644553bd476429ebd674e4) Thanks @tim-smart! - add Layer based api for creating HttpRouter's\n\n  ```ts\n  import {\n    HttpMiddleware,\n    HttpRouter,\n    HttpServer,\n    HttpServerResponse\n  } from \"@effect/platform\"\n  import { BunHttpServer, BunRuntime } from \"@effect/platform-bun\"\n  import { Effect, Layer } from \"effect\"\n\n  // create your router Context.Tag\n  class UserRouter extends HttpRouter.Tag(\"UserRouter\")<UserRouter>() {}\n\n  // create routes with the `.use` api.\n  // There is also `.useScoped`\n  const GetUsers = UserRouter.use((router) =>\n    Effect.gen(function* () {\n      yield* router.get(\"/\", HttpServerResponse.text(\"got users\"))\n    })\n  )\n\n  const CreateUser = UserRouter.use((router) =>\n    Effect.gen(function* () {\n      yield* router.post(\"/\", HttpServerResponse.text(\"created user\"))\n    })\n  )\n\n  const AllRoutes = Layer.mergeAll(GetUsers, CreateUser)\n\n  const ServerLive = BunHttpServer.layer({ port: 3000 })\n\n  // access the router with the `.router` api, to create your server\n  const HttpLive = Layer.unwrapEffect(\n    Effect.gen(function* () {\n      return HttpServer.serve(yield* UserRouter.router, HttpMiddleware.logger)\n    })\n  ).pipe(\n    Layer.provide(UserRouter.Live),\n    Layer.provide(AllRoutes),\n    Layer.provide(ServerLive)\n  )\n\n  BunRuntime.runMain(Layer.launch(HttpLive))\n  ```\n\n- Updated dependencies [[`66a1910`](https://github.com/Effect-TS/effect/commit/66a19109ff90c4252123b8809b8c8a74681dba6a)]:\n  - effect@3.4.1\n  - @effect/schema@0.68.7\n\n## 0.58.5\n\n### Patch Changes\n\n- [#3053](https://github.com/Effect-TS/effect/pull/3053) [`37a07a2`](https://github.com/Effect-TS/effect/commit/37a07a2d8d1ce09ab965c0ada84a3fae9a6aba05) Thanks @tim-smart! - coerce primitive types in UrlParams input\n\n## 0.58.4\n\n### Patch Changes\n\n- [#3051](https://github.com/Effect-TS/effect/pull/3051) [`b77fb0a`](https://github.com/Effect-TS/effect/commit/b77fb0a811ec1ad0e794917077c9a90824515db8) Thanks @tim-smart! - add HttpMiddleware.cors\n\n## 0.58.3\n\n### Patch Changes\n\n- Updated dependencies [[`530fa9e`](https://github.com/Effect-TS/effect/commit/530fa9e36b8532589b948fc4faa37593f36b7f42)]:\n  - @effect/schema@0.68.6\n\n## 0.58.2\n\n### Patch Changes\n\n- Updated dependencies [[`1d62815`](https://github.com/Effect-TS/effect/commit/1d62815a50f34115606940ffa397442d75a20c81)]:\n  - @effect/schema@0.68.5\n\n## 0.58.1\n\n### Patch Changes\n\n- [#3036](https://github.com/Effect-TS/effect/pull/3036) [`5a248aa`](https://github.com/Effect-TS/effect/commit/5a248aa5ab2db3f7131ebc79bb9871a76de57973) Thanks @tim-smart! - add Socket.fromTransformStream\n\n## 0.58.0\n\n### Minor Changes\n\n- [#2938](https://github.com/Effect-TS/effect/pull/2938) [`63dd0c3`](https://github.com/Effect-TS/effect/commit/63dd0c3af45876c1caad7d03356c74daf551c628) Thanks @tim-smart! - restructure platform http to use flattened modules\n\n  Instead of using the previous re-exports, you now use the modules directly.\n\n  Before:\n\n  ```ts\n  import { HttpClient } from \"@effect/platform\"\n\n  HttpClient.request.get(\"/\").pipe(HttpClient.client.fetchOk)\n  ```\n\n  After:\n\n  ```ts\n  import { HttpClient, HttpClientRequest } from \"@effect/platform\"\n\n  HttpClientRequest.get(\"/\").pipe(HttpClient.fetchOk)\n  ```\n\n### Patch Changes\n\n- Updated dependencies [[`c0ce180`](https://github.com/Effect-TS/effect/commit/c0ce180861ad0938053c0e6145e813fa6404df3b), [`61707b6`](https://github.com/Effect-TS/effect/commit/61707b6ffc7397c2ba0dce22512b44955724f60f), [`9c1b5b3`](https://github.com/Effect-TS/effect/commit/9c1b5b39e6c19604ce834f072a114ad392c50a06), [`a35faf8`](https://github.com/Effect-TS/effect/commit/a35faf8d116f94899bfc03feab33b004c8ddfdf7), [`ff73c0c`](https://github.com/Effect-TS/effect/commit/ff73c0cacd66132bfad2e5211b3eae347729c667), [`984d516`](https://github.com/Effect-TS/effect/commit/984d516ccd9412dc41188f6a46b748dd20dd5848), [`8c3b8a2`](https://github.com/Effect-TS/effect/commit/8c3b8a2ce208eab753b6206a51605a424f104e98), [`017e2f9`](https://github.com/Effect-TS/effect/commit/017e2f9b371ce24ea4945e5d7390c934ad3c39cf), [`91bf8a2`](https://github.com/Effect-TS/effect/commit/91bf8a2e9d1959393b3cf7366cc1d584d3e666b7), [`c6a4a26`](https://github.com/Effect-TS/effect/commit/c6a4a266606575fd2c7165940c4072ad4c57d01f)]:\n  - effect@3.4.0\n  - @effect/schema@0.68.4\n\n## 0.57.8\n\n### Patch Changes\n\n- [#3030](https://github.com/Effect-TS/effect/pull/3030) [`3ba7ea1`](https://github.com/Effect-TS/effect/commit/3ba7ea1c3c2923e85bf2f17e41176f8f8796d203) Thanks @tim-smart! - update find-my-way-ts & multipasta\n\n## 0.57.7\n\n### Patch Changes\n\n- Updated dependencies [[`d473800`](https://github.com/Effect-TS/effect/commit/d47380012c3241d7287b66968d33a2414275ce7b)]:\n  - @effect/schema@0.68.3\n\n## 0.57.6\n\n### Patch Changes\n\n- Updated dependencies [[`eb341b3`](https://github.com/Effect-TS/effect/commit/eb341b3eb34ad64499371bc08b7f59e429979d8a)]:\n  - @effect/schema@0.68.2\n\n## 0.57.5\n\n### Patch Changes\n\n- [#3021](https://github.com/Effect-TS/effect/pull/3021) [`b8ea6aa`](https://github.com/Effect-TS/effect/commit/b8ea6aa479006358042b4256ee0a1c5cfbe57acb) Thanks @tim-smart! - update find-my-way-ts to fix vercel edge support\n\n## 0.57.4\n\n### Patch Changes\n\n- Updated dependencies [[`b51e266`](https://github.com/Effect-TS/effect/commit/b51e26662b879b55d2c5164b7c97742739aa9446), [`6c89408`](https://github.com/Effect-TS/effect/commit/6c89408cd7b9204ec4c5828a46cd5312d8afb5e7)]:\n  - @effect/schema@0.68.1\n  - effect@3.3.5\n\n## 0.57.3\n\n### Patch Changes\n\n- Updated dependencies [[`f6c7977`](https://github.com/Effect-TS/effect/commit/f6c79772e632c440b7e5221bb75f0ef9d3c3b005), [`a67b8fe`](https://github.com/Effect-TS/effect/commit/a67b8fe2ace08419424811b5f0d9a5378eaea352)]:\n  - @effect/schema@0.68.0\n  - effect@3.3.4\n\n## 0.57.2\n\n### Patch Changes\n\n- Updated dependencies [[`3b15e1b`](https://github.com/Effect-TS/effect/commit/3b15e1b505c0b0e62a03b4a3605d42a9932cc99c), [`06ede85`](https://github.com/Effect-TS/effect/commit/06ede85d6e84710e6622463be95ff3927fb30dad), [`3a750b2`](https://github.com/Effect-TS/effect/commit/3a750b25b1ed92094a7f7ebc332a6bcfb212871b), [`7204ca5`](https://github.com/Effect-TS/effect/commit/7204ca5761c2b1d27999a624db23aa10b6e0504d)]:\n  - @effect/schema@0.67.24\n  - effect@3.3.3\n\n## 0.57.1\n\n### Patch Changes\n\n- [#2988](https://github.com/Effect-TS/effect/pull/2988) [`07e12ec`](https://github.com/Effect-TS/effect/commit/07e12ecdb0e20b9763bd9e9058e567a7c8862efc) Thanks @tim-smart! - refactor Socket to use do notation\n\n- Updated dependencies [[`2ee4f2b`](https://github.com/Effect-TS/effect/commit/2ee4f2be7fd63074a9cbac6dcdfb533b6683533a), [`3572646`](https://github.com/Effect-TS/effect/commit/3572646d5e0804f85bc7f64633fb95722533f9dd), [`1aed347`](https://github.com/Effect-TS/effect/commit/1aed347a125ed3847ec90863424810d6759cbc85), [`df4bf4b`](https://github.com/Effect-TS/effect/commit/df4bf4b62e7b316c6647da0271fc5544a84e7ba2), [`f085f92`](https://github.com/Effect-TS/effect/commit/f085f92dfa204afb41823ffc27d437225137643d), [`9b3b4ac`](https://github.com/Effect-TS/effect/commit/9b3b4ac639d98aae33883926bece1e31fa280d22)]:\n  - @effect/schema@0.67.23\n  - effect@3.3.2\n\n## 0.57.0\n\n### Minor Changes\n\n- [#2966](https://github.com/Effect-TS/effect/pull/2966) [`4d3fbe8`](https://github.com/Effect-TS/effect/commit/4d3fbe82e8cec13ccd0cd0b2096deac6818fb59a) Thanks @tim-smart! - fix KeyValueStore for react native by making constructors lazy\n\n### Patch Changes\n\n- Updated dependencies [[`eb98c5b`](https://github.com/Effect-TS/effect/commit/eb98c5b79ab50aa0cde239bd4e660dd19dbab612), [`184fed8`](https://github.com/Effect-TS/effect/commit/184fed83ac36cba05a75a5a8013f740f9f696e3b), [`6068e07`](https://github.com/Effect-TS/effect/commit/6068e073d4cc8b3c8583583fd5eb3efe43f7d5ba), [`3a77e20`](https://github.com/Effect-TS/effect/commit/3a77e209783933bac3aaddba1b05ff6a9ac72b36), [`d79ca17`](https://github.com/Effect-TS/effect/commit/d79ca17d9fa432571c69714776cab5cf8fef9c34)]:\n  - effect@3.3.1\n  - @effect/schema@0.67.22\n\n## 0.56.0\n\n### Minor Changes\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`2b9ddfc`](https://github.com/Effect-TS/effect/commit/2b9ddfcbac505d98551e764a43923854907ca5c1) Thanks @tim-smart! - support new Pool options in /platform WorkerPool\n\n- [#2837](https://github.com/Effect-TS/effect/pull/2837) [`188f0a5`](https://github.com/Effect-TS/effect/commit/188f0a5c57ed0d7c9e5852e0c1c998f1b95810a1) Thanks @tim-smart! - parse URL instances when creating client requests\n\n### Patch Changes\n\n- Updated dependencies [[`1f4ac00`](https://github.com/Effect-TS/effect/commit/1f4ac00a91c336c9c9c9b8c3ed9ceb9920ebc9bd), [`9305b76`](https://github.com/Effect-TS/effect/commit/9305b764cceeae4f16564435ae7172f79c2bf822), [`0f40d98`](https://github.com/Effect-TS/effect/commit/0f40d989da10f68df3ecd72b36849401ad679bfb), [`b761ef0`](https://github.com/Effect-TS/effect/commit/b761ef00eaf6c67b7ffe34798b98aae5347ab376), [`b53f69b`](https://github.com/Effect-TS/effect/commit/b53f69bff1452a487b21198cd83961f844e02d36), [`0f40d98`](https://github.com/Effect-TS/effect/commit/0f40d989da10f68df3ecd72b36849401ad679bfb), [`5bd549e`](https://github.com/Effect-TS/effect/commit/5bd549e4bd7144727db438ecca6b8dc9b3ef7e22), [`67f160a`](https://github.com/Effect-TS/effect/commit/67f160a213de0219a565d4bf653b3cbf24f58e8f), [`67f160a`](https://github.com/Effect-TS/effect/commit/67f160a213de0219a565d4bf653b3cbf24f58e8f)]:\n  - effect@3.3.0\n  - @effect/schema@0.67.21\n\n## 0.55.7\n\n### Patch Changes\n\n- [#2931](https://github.com/Effect-TS/effect/pull/2931) [`a67d602`](https://github.com/Effect-TS/effect/commit/a67d60276f96cd20b76145b4cee13efca6c6158a) Thanks @tim-smart! - ensure pre-response handler is checked after running the user-provided http app\n\n- Updated dependencies [[`4c6bc7f`](https://github.com/Effect-TS/effect/commit/4c6bc7f190c142dc9db70b365a2bf30715a98e62)]:\n  - @effect/schema@0.67.20\n\n## 0.55.6\n\n### Patch Changes\n\n- [#2903](https://github.com/Effect-TS/effect/pull/2903) [`799aa20`](https://github.com/Effect-TS/effect/commit/799aa20b4f618736ba33a5297fda90a75d4c26c6) Thanks @rocwang! - # Make baseUrl() more defensive in @effect/platform\n\n  Sometimes, third party code may patch a missing global `location` to accommodate for non-browser JavaScript\n  runtimes, e.g. Cloudflare Workers,\n  Deno. [Such patch](https://github.com/jamsinclair/jSquash/pull/21/files#diff-322ca97cdcdd0d3b85c20a7d5cac703a2f9f3766fc762f98b9f6a9d4c5063ca3R21-R23)\n  might not yield a fully valid `location`. This could\n  break `baseUrl()`, which is called by `makeUrl()`.\n\n  For example, the following code would log `Invalid URL: '/api/v1/users' with base 'NaN'`.\n\n  ```js\n  import { makeUrl } from \"@effect/platform/Http/UrlParams\"\n\n  globalThis.location = { href: \"\" }\n\n  const url = makeUrl(\"/api/v1/users\", [])\n\n  // This would log \"Invalid URL: '/api/v1/users' with base 'NaN'\",\n  // because location.origin + location.pathname return NaN in baseUrl()\n  console.log(url.left.message)\n  ```\n\n  Arguably, this is not an issue of Effect per se, but it's better to be defensive and handle such cases gracefully.\n  So this change does that by checking if `location.orign` and `location.pathname` are available before accessing them.\n\n- Updated dependencies [[`8c5d280`](https://github.com/Effect-TS/effect/commit/8c5d280c0402284a4e58372867a15a431cb99461), [`6ba6d26`](https://github.com/Effect-TS/effect/commit/6ba6d269f5891e6b11aa35c5281dde4bf3273004), [`cd7496b`](https://github.com/Effect-TS/effect/commit/cd7496ba214eabac2e3c297f513fcbd5b11f0e91), [`3f28bf2`](https://github.com/Effect-TS/effect/commit/3f28bf274333611906175446b772243f34f1b6d5), [`5817820`](https://github.com/Effect-TS/effect/commit/58178204a770d1a78c06945ef438f9fffbb50afa), [`349a036`](https://github.com/Effect-TS/effect/commit/349a036ffb08351481c060655660a6ccf26473de)]:\n  - effect@3.2.9\n  - @effect/schema@0.67.19\n\n## 0.55.5\n\n### Patch Changes\n\n- Updated dependencies [[`a0dd1c1`](https://github.com/Effect-TS/effect/commit/a0dd1c1ede2a1e856ecb0e67826ec992016fef97)]:\n  - @effect/schema@0.67.18\n\n## 0.55.4\n\n### Patch Changes\n\n- Updated dependencies [[`d9d22e7`](https://github.com/Effect-TS/effect/commit/d9d22e7c4d5e31d5b46644c729b027796e467c16), [`3c080f7`](https://github.com/Effect-TS/effect/commit/3c080f74b2e2290edb6143c3aa01026e57f87a2a), [`3c080f7`](https://github.com/Effect-TS/effect/commit/3c080f74b2e2290edb6143c3aa01026e57f87a2a), [`7d6d875`](https://github.com/Effect-TS/effect/commit/7d6d8750077d9c8379f37240745240d7f3b7a4f8), [`70cda70`](https://github.com/Effect-TS/effect/commit/70cda704e8e31c80737b95121c8199e726ea132f), [`fb91f17`](https://github.com/Effect-TS/effect/commit/fb91f17098b48497feca9ec976feb87e4a82451b)]:\n  - @effect/schema@0.67.17\n  - effect@3.2.8\n\n## 0.55.3\n\n### Patch Changes\n\n- Updated dependencies [[`5745886`](https://github.com/Effect-TS/effect/commit/57458869859943410221ccc87f8cecfba7c79d92), [`6801fca`](https://github.com/Effect-TS/effect/commit/6801fca44366be3ee1b6b99f54bd4f38a1b5e4f4)]:\n  - @effect/schema@0.67.16\n  - effect@3.2.7\n\n## 0.55.2\n\n### Patch Changes\n\n- [#2737](https://github.com/Effect-TS/effect/pull/2737) [`2c2280b`](https://github.com/Effect-TS/effect/commit/2c2280b98a11fc002663c55792a4fa5781cd5fb6) Thanks @jessekelly881! - added KeyValueStore.layerStorage to wrap instances of the `Storage` type.\n\n- Updated dependencies [[`e2740fc`](https://github.com/Effect-TS/effect/commit/e2740fc4e212ba85a90541e8c8d85b0bcd5c2e7c), [`cc8ac50`](https://github.com/Effect-TS/effect/commit/cc8ac5080daba8622ca2ff5dab5c37ddfab732ba), [`60fe3d5`](https://github.com/Effect-TS/effect/commit/60fe3d5fb2be168dd35c6d0cb8ac8f55deb30fc0)]:\n  - @effect/schema@0.67.15\n  - effect@3.2.6\n\n## 0.55.1\n\n### Patch Changes\n\n- Updated dependencies [[`c5846e9`](https://github.com/Effect-TS/effect/commit/c5846e99137e9eb02efd31865e26f49f0d2c7c03)]:\n  - @effect/schema@0.67.14\n\n## 0.55.0\n\n### Minor Changes\n\n- [#2835](https://github.com/Effect-TS/effect/pull/2835) [`5133ca9`](https://github.com/Effect-TS/effect/commit/5133ca9dc4b8da0e28951316da9ab55dfbe0fbb9) Thanks @tim-smart! - remove pool resizing in platform workers to enable concurrent access\n\n### Patch Changes\n\n- Updated dependencies [[`608b01f`](https://github.com/Effect-TS/effect/commit/608b01fc342dbae2a642b308a67b84ead530ecea), [`031c712`](https://github.com/Effect-TS/effect/commit/031c7122a24ac42e48d6a434646b4f5d279d7442), [`a44e532`](https://github.com/Effect-TS/effect/commit/a44e532cf3a6a498b12a5aacf8124aa267e24ba0)]:\n  - effect@3.2.5\n  - @effect/schema@0.67.13\n\n## 0.54.0\n\n### Minor Changes\n\n- [#2801](https://github.com/Effect-TS/effect/pull/2801) [`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3) Thanks @tim-smart! - remove `permits` from workers, to prevent issues with pool resizing\n\n- [#2801](https://github.com/Effect-TS/effect/pull/2801) [`c07e0ce`](https://github.com/Effect-TS/effect/commit/c07e0cea8ce165887e2c9dfa5d669eba9b2fb798) Thanks @gcanti! - Revise the ordering of type parameters within the `SchemaStore` interface to enhance consistency\n\n### Patch Changes\n\n- [#2801](https://github.com/Effect-TS/effect/pull/2801) [`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3) Thanks @tim-smart! - ensure worker pool construction errors are reported during creation\n\n- Updated dependencies [[`1af94df`](https://github.com/Effect-TS/effect/commit/1af94df6b74aeb4f6ebcbe80e074b4cb252e62e3), [`f8038ca`](https://github.com/Effect-TS/effect/commit/f8038cadd5f50d397469e5fdbc70dd8f69671f50), [`e376641`](https://github.com/Effect-TS/effect/commit/e3766411b60ebb45d31e9c9d94efa099121d4d58), [`e313a01`](https://github.com/Effect-TS/effect/commit/e313a01b7e80f6cb7704055a190e5623c9d22c6d)]:\n  - effect@3.2.4\n  - @effect/schema@0.67.12\n\n## 0.53.14\n\n### Patch Changes\n\n- Updated dependencies [[`5af633e`](https://github.com/Effect-TS/effect/commit/5af633eb5ff6560a64d87263d1692bb9c75f7b3c), [`45578e8`](https://github.com/Effect-TS/effect/commit/45578e8faa80ae33d23e08f6f19467f818b7788f)]:\n  - @effect/schema@0.67.11\n  - effect@3.2.3\n\n## 0.53.13\n\n### Patch Changes\n\n- [#2784](https://github.com/Effect-TS/effect/pull/2784) [`c1eaef9`](https://github.com/Effect-TS/effect/commit/c1eaef910420dae416923d172ee58d219e921d0f) Thanks @gcanti! - Update the definition of `Handler` to utilize `App.Default`\n\n- Updated dependencies [[`5d9266e`](https://github.com/Effect-TS/effect/commit/5d9266e8c740746ac9e186c3df6090a1b57fbe2a), [`9f8122e`](https://github.com/Effect-TS/effect/commit/9f8122e78884ab47c5e5f364d86eee1d1543cc61), [`6a6f670`](https://github.com/Effect-TS/effect/commit/6a6f6706b8613c8c7c10971b8d81a0f9e440a6f2), [`78ffc27`](https://github.com/Effect-TS/effect/commit/78ffc27ee3fa708433c25fa118c53d38d90d08bc)]:\n  - effect@3.2.2\n  - @effect/schema@0.67.10\n\n## 0.53.12\n\n### Patch Changes\n\n- Updated dependencies [[`5432fff`](https://github.com/Effect-TS/effect/commit/5432fff7c9a69d43910426c1053ebfc3b73ebed6)]:\n  - @effect/schema@0.67.9\n\n## 0.53.11\n\n### Patch Changes\n\n- Updated dependencies [[`c1e991d`](https://github.com/Effect-TS/effect/commit/c1e991dd5ba87901cd0e05697a8b4a267e7e954a)]:\n  - effect@3.2.1\n  - @effect/schema@0.67.8\n\n## 0.53.10\n\n### Patch Changes\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`146cadd`](https://github.com/Effect-TS/effect/commit/146cadd9d004634a3ff85c480bf92cf975c853e2) Thanks [@tim-smart](https://github.com/tim-smart)! - Run client request stream with a current runtime.\n\n- [#2778](https://github.com/Effect-TS/effect/pull/2778) [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e) Thanks [@tim-smart](https://github.com/tim-smart)! - capture stack trace for tracing spans\n\n- Updated dependencies [[`146cadd`](https://github.com/Effect-TS/effect/commit/146cadd9d004634a3ff85c480bf92cf975c853e2), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`963b4e7`](https://github.com/Effect-TS/effect/commit/963b4e7ac87e2468feb6a344f7ab4ee4ad711198), [`64c9414`](https://github.com/Effect-TS/effect/commit/64c9414e960e82058ca09bbb3976d6fbef303a8e), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`2cbb76b`](https://github.com/Effect-TS/effect/commit/2cbb76bb52500a3f4bf27d1c91482518cbea56d7), [`870c5fa`](https://github.com/Effect-TS/effect/commit/870c5fa52cd61e745e8e828d38c3f09f00737553), [`7135748`](https://github.com/Effect-TS/effect/commit/713574813a0f64085db0b5240ba39e7a0a7c137e), [`64c9414`](https://github.com/Effect-TS/effect/commit/64c9414e960e82058ca09bbb3976d6fbef303a8e)]:\n  - effect@3.2.0\n  - @effect/schema@0.67.7\n\n## 0.53.9\n\n### Patch Changes\n\n- [#2761](https://github.com/Effect-TS/effect/pull/2761) [`17fc22e`](https://github.com/Effect-TS/effect/commit/17fc22e132593c5caa563705a4748ba0f04a853c) Thanks [@KhraksMamtsov](https://github.com/KhraksMamtsov)! - Add `{ once: true }` to all `\"abort\"` event listeners for `AbortController` to automatically remove handlers after execution\n\n- Updated dependencies [[`17da864`](https://github.com/Effect-TS/effect/commit/17da864e4a6f80becdb82db7dece2ba583bfdda3), [`17fc22e`](https://github.com/Effect-TS/effect/commit/17fc22e132593c5caa563705a4748ba0f04a853c), [`810f222`](https://github.com/Effect-TS/effect/commit/810f222268792b13067c7a7bf317b93a9bb8917b), [`596aaea`](https://github.com/Effect-TS/effect/commit/596aaea022648b2e06fb1ec22f1652043d6fe64e), [`ff0efa0`](https://github.com/Effect-TS/effect/commit/ff0efa0a1415a41d4a4312a16cf7a63def86db3f)]:\n  - @effect/schema@0.67.6\n  - effect@3.1.6\n\n## 0.53.8\n\n### Patch Changes\n\n- Updated dependencies [[`9c514de`](https://github.com/Effect-TS/effect/commit/9c514de28152696edff008324d2d7e67d55afd56)]:\n  - @effect/schema@0.67.5\n\n## 0.53.7\n\n### Patch Changes\n\n- Updated dependencies [[`ee08593`](https://github.com/Effect-TS/effect/commit/ee0859398ecc2589cab0d017bef6a17e00c34dfd), [`da6d7d8`](https://github.com/Effect-TS/effect/commit/da6d7d845246e9d04631d64fa7694944b6010d09)]:\n  - @effect/schema@0.67.4\n\n## 0.53.6\n\n### Patch Changes\n\n- [#2750](https://github.com/Effect-TS/effect/pull/2750) [`6ac4847`](https://github.com/Effect-TS/effect/commit/6ac48479447c01a4f35d655552af93e47e562610) Thanks [@tim-smart](https://github.com/tim-smart)! - fix memory leak in Socket's\n\n- Updated dependencies [[`6ac4847`](https://github.com/Effect-TS/effect/commit/6ac48479447c01a4f35d655552af93e47e562610)]:\n  - effect@3.1.5\n  - @effect/schema@0.67.3\n\n## 0.53.5\n\n### Patch Changes\n\n- Updated dependencies [[`89a3afb`](https://github.com/Effect-TS/effect/commit/89a3afbe191c83b84b17bfaa95519aff0749afbe), [`992c8e2`](https://github.com/Effect-TS/effect/commit/992c8e21535db9f0c66e81d32fee8af56a96274f)]:\n  - @effect/schema@0.67.2\n\n## 0.53.4\n\n### Patch Changes\n\n- Updated dependencies [[`e41e911`](https://github.com/Effect-TS/effect/commit/e41e91122fa6dd12fc81e50dcad0db891be67146)]:\n  - effect@3.1.4\n  - @effect/schema@0.67.1\n\n## 0.53.3\n\n### Patch Changes\n\n- Updated dependencies [[`d7e4997`](https://github.com/Effect-TS/effect/commit/d7e49971fe97b7ee5fb7991f3f5ac4d627a26338)]:\n  - @effect/schema@0.67.0\n\n## 0.53.2\n\n### Patch Changes\n\n- Updated dependencies [[`1f6dc96`](https://github.com/Effect-TS/effect/commit/1f6dc96f51c7bb9c8d11415358308604ba7c7c8e)]:\n  - effect@3.1.3\n  - @effect/schema@0.66.16\n\n## 0.53.1\n\n### Patch Changes\n\n- Updated dependencies [[`121d6d9`](https://github.com/Effect-TS/effect/commit/121d6d93755138c7510ba3ab4f0019ec0cb91890)]:\n  - @effect/schema@0.66.15\n\n## 0.53.0\n\n### Minor Changes\n\n- [#2703](https://github.com/Effect-TS/effect/pull/2703) [`d57fbbb`](https://github.com/Effect-TS/effect/commit/d57fbbbd6c466936213a671fc3cd2390064f864e) Thanks [@tim-smart](https://github.com/tim-smart)! - replace isows with WebSocketConstructor service in @effect/platform/Socket\n\n  You now have to provide a WebSocketConstructor implementation to the `Socket.makeWebSocket` api.\n\n  ```ts\n  import * as Socket from \"@effect/platform/Socket\"\n  import * as NodeSocket from \"@effect/platform-node/NodeSocket\"\n  import { Effect } from \"effect\"\n\n  Socket.makeWebSocket(\"ws://localhost:8080\").pipe(\n    Effect.provide(NodeSocket.layerWebSocketConstructor) // use \"ws\" npm package\n  )\n  ```\n\n## 0.52.3\n\n### Patch Changes\n\n- [#2698](https://github.com/Effect-TS/effect/pull/2698) [`5866c62`](https://github.com/Effect-TS/effect/commit/5866c621d7eb4cc84e4ba972bfdfd219734cd45d) Thanks [@tim-smart](https://github.com/tim-smart)! - fix http ServerResponse cookie apis\n\n## 0.52.2\n\n### Patch Changes\n\n- [#2679](https://github.com/Effect-TS/effect/pull/2679) [`2e1cdf6`](https://github.com/Effect-TS/effect/commit/2e1cdf67d141281288fffe9a5c10d1379a800513) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure all type ids are annotated with `unique symbol`\n\n- Updated dependencies [[`2e1cdf6`](https://github.com/Effect-TS/effect/commit/2e1cdf67d141281288fffe9a5c10d1379a800513)]:\n  - effect@3.1.2\n  - @effect/schema@0.66.14\n\n## 0.52.1\n\n### Patch Changes\n\n- Updated dependencies [[`e5e56d1`](https://github.com/Effect-TS/effect/commit/e5e56d138dbed3204636f605229c6685f89659fc)]:\n  - effect@3.1.1\n  - @effect/schema@0.66.13\n\n## 0.52.0\n\n### Minor Changes\n\n- [#2669](https://github.com/Effect-TS/effect/pull/2669) [`9deab0a`](https://github.com/Effect-TS/effect/commit/9deab0aec9e99501f9441843e34df9afa10c5be9) Thanks [@tim-smart](https://github.com/tim-smart)! - move http search params apis to ServerRequest module\n\n  If you want to access the search params for a request, you can now use the `Http.request.ParsedSearchParams` tag.\n\n  ```ts\n  import * as Http from \"@effect/platform/HttpServer\"\n  import { Effect } from \"effect\"\n\n  Effect.gen(function* () {\n    const searchParams = yield* Http.request.ParsedSearchParams\n    console.log(searchParams)\n  })\n  ```\n\n  The schema method has also been moved to the `ServerRequest` module. It is now available as `Http.request.schemaSearchParams`.\n\n### Patch Changes\n\n- [#2672](https://github.com/Effect-TS/effect/pull/2672) [`7719b8a`](https://github.com/Effect-TS/effect/commit/7719b8a7350c14e952ffe685bfd5308773b3e271) Thanks [@tim-smart](https://github.com/tim-smart)! - allow http client trace propagation to be controlled\n\n  To disable trace propagation:\n\n  ```ts\n  import { HttpClient as Http } from \"@effect/platform\"\n\n  Http.request\n    .get(\"https://example.com\")\n    .pipe(Http.client.fetchOk, Http.client.withTracerPropagation(false))\n  ```\n\n## 0.51.0\n\n### Minor Changes\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`0ec93cb`](https://github.com/Effect-TS/effect/commit/0ec93cb4f166e7401c171c2f8e8276ce958d9a57) Thanks [@github-actions](https://github.com/apps/github-actions)! - \\* capitalised Http.multipart.FileSchema and Http.multipart.FilesSchema\n  - exported Http.multipart.FileSchema\n  - added Http.multipart.SingleFileSchema\n\n### Patch Changes\n\n- [#2543](https://github.com/Effect-TS/effect/pull/2543) [`a023f28`](https://github.com/Effect-TS/effect/commit/a023f28336f3865687d9a30c1883e36909906d85) Thanks [@github-actions](https://github.com/apps/github-actions)! - set span `kind` where applicable\n\n- Updated dependencies [[`c3c12c6`](https://github.com/Effect-TS/effect/commit/c3c12c6625633fe80e79f9db75a3b8cf8ca8b11d), [`ba64ea6`](https://github.com/Effect-TS/effect/commit/ba64ea6757810c5e74cad3863a7d19d4d38af66b), [`b5de2d2`](https://github.com/Effect-TS/effect/commit/b5de2d2ce5b1afe8be90827bf898a95cec40eb2b), [`a1c7ab8`](https://github.com/Effect-TS/effect/commit/a1c7ab8ffedacd18c1fc784f4ff5844f79498b83), [`a023f28`](https://github.com/Effect-TS/effect/commit/a023f28336f3865687d9a30c1883e36909906d85), [`1c9454d`](https://github.com/Effect-TS/effect/commit/1c9454d532eae79b9f759aea77f59332cc6d18ed), [`92d56db`](https://github.com/Effect-TS/effect/commit/92d56dbb3f33e36636c2a2f1030c56492e39cf4d)]:\n  - effect@3.1.0\n  - @effect/schema@0.66.12\n\n## 0.50.8\n\n### Patch Changes\n\n- [#2650](https://github.com/Effect-TS/effect/pull/2650) [`16039a0`](https://github.com/Effect-TS/effect/commit/16039a08f04f11545e2fdf40952788a8f9cef04f) Thanks [@tim-smart](https://github.com/tim-smart)! - improve error messages for Http.client.filterStatus\\*\n\n- [#2648](https://github.com/Effect-TS/effect/pull/2648) [`d1d33e1`](https://github.com/Effect-TS/effect/commit/d1d33e10b25109f44b5ab1c6e4d778a59c0d3eeb) Thanks [@floydspace](https://github.com/floydspace)! - Fixed import path for type import.\n\n- Updated dependencies [[`557707b`](https://github.com/Effect-TS/effect/commit/557707bc9e5f230c8964d2757012075c34339b5c), [`f4ed306`](https://github.com/Effect-TS/effect/commit/f4ed3068a70b50302d078a30d18ca3cfd2bc679c), [`661004f`](https://github.com/Effect-TS/effect/commit/661004f4bf5f8b25f5a0678c21a3a822188ce461), [`e79cb83`](https://github.com/Effect-TS/effect/commit/e79cb83d3b19098bc40a3012e2a059b8426306c2)]:\n  - effect@3.0.8\n  - @effect/schema@0.66.11\n\n## 0.50.7\n\n### Patch Changes\n\n- Updated dependencies [[`18de56b`](https://github.com/Effect-TS/effect/commit/18de56b4a6b6d1f99230dfabf9147d59ea4dd759)]:\n  - effect@3.0.7\n  - @effect/schema@0.66.10\n\n## 0.50.6\n\n### Patch Changes\n\n- Updated dependencies [[`ffe4f4e`](https://github.com/Effect-TS/effect/commit/ffe4f4e95db35fff6869e360b072e3837befa0a1), [`027418e`](https://github.com/Effect-TS/effect/commit/027418edaa6aa6c0ae4861b95832827b45adace4), [`ac1898e`](https://github.com/Effect-TS/effect/commit/ac1898eb7bc96880f911c276048e2ea3d6fe9c50), [`ffe4f4e`](https://github.com/Effect-TS/effect/commit/ffe4f4e95db35fff6869e360b072e3837befa0a1), [`8206529`](https://github.com/Effect-TS/effect/commit/8206529d6a7bbf3e3c6f670afb0381e83176736e)]:\n  - effect@3.0.6\n  - @effect/schema@0.66.9\n\n## 0.50.5\n\n### Patch Changes\n\n- Updated dependencies [[`6222404`](https://github.com/Effect-TS/effect/commit/62224044678751829ed2f128e05133a91c6b0569), [`868ed2a`](https://github.com/Effect-TS/effect/commit/868ed2a8fe94ee7f4206a6070f29dcf2a5ba1dc3)]:\n  - effect@3.0.5\n  - @effect/schema@0.66.8\n\n## 0.50.4\n\n### Patch Changes\n\n- Updated dependencies [[`dd41c6c`](https://github.com/Effect-TS/effect/commit/dd41c6c725b1c1c980683275d8fa69779902187e), [`9a24667`](https://github.com/Effect-TS/effect/commit/9a246672008a2b668d43fbfd2fe5508c54b2b920)]:\n  - @effect/schema@0.66.7\n  - effect@3.0.4\n\n## 0.50.3\n\n### Patch Changes\n\n- [#2589](https://github.com/Effect-TS/effect/pull/2589) [`b3b51a2`](https://github.com/Effect-TS/effect/commit/b3b51a2ea0c6ab92a363db46ebaa7e1176d089f5) Thanks [@tim-smart](https://github.com/tim-smart)! - redact some common sensitive http headers names in traces\n\n- Updated dependencies [[`9dfc156`](https://github.com/Effect-TS/effect/commit/9dfc156dc13fb4da9c777aae3acece4b5ecf0064), [`80271bd`](https://github.com/Effect-TS/effect/commit/80271bdc648e9efa659ce66b2c255754a6a1a8b0), [`e4ba97d`](https://github.com/Effect-TS/effect/commit/e4ba97d060c16bdf4e3b5bd5db6777f121a6768c)]:\n  - @effect/schema@0.66.6\n\n## 0.50.2\n\n### Patch Changes\n\n- Updated dependencies [[`b3fe829`](https://github.com/Effect-TS/effect/commit/b3fe829e8b12726afe94086b5375968f41a26411), [`a58b7de`](https://github.com/Effect-TS/effect/commit/a58b7deb8bb1d3b0dd636decf5d16f115f37eb72), [`d90e8c3`](https://github.com/Effect-TS/effect/commit/d90e8c3090cbc78e2bc7b51c974df66ffefacdfa)]:\n  - @effect/schema@0.66.5\n\n## 0.50.1\n\n### Patch Changes\n\n- Updated dependencies [[`773b8e0`](https://github.com/Effect-TS/effect/commit/773b8e01521e8fa7c38ff15d92d21d6fd6dad56f)]:\n  - @effect/schema@0.66.4\n\n## 0.50.0\n\n### Minor Changes\n\n- [#2567](https://github.com/Effect-TS/effect/pull/2567) [`6f38dff`](https://github.com/Effect-TS/effect/commit/6f38dff41ffa34532cc2f25b90446550c5730bb6) Thanks [@tim-smart](https://github.com/tim-smart)! - add URL & AbortSignal to Http.client.makeDefault\n\n### Patch Changes\n\n- [#2567](https://github.com/Effect-TS/effect/pull/2567) [`6f38dff`](https://github.com/Effect-TS/effect/commit/6f38dff41ffa34532cc2f25b90446550c5730bb6) Thanks [@tim-smart](https://github.com/tim-smart)! - add more span attributes to http traces\n\n- [#2565](https://github.com/Effect-TS/effect/pull/2565) [`a3b0e6c`](https://github.com/Effect-TS/effect/commit/a3b0e6c490772e6d44b5d98dcf2729c4d5310ecc) Thanks [@tim-smart](https://github.com/tim-smart)! - add Http.response.void helper, for creating a http request that returns void\n\n- Updated dependencies [[`a7b4b84`](https://github.com/Effect-TS/effect/commit/a7b4b84bd5a25f51aba922f9259c3a58c98c6a4e)]:\n  - effect@3.0.3\n  - @effect/schema@0.66.3\n\n## 0.49.4\n\n### Patch Changes\n\n- [#2562](https://github.com/Effect-TS/effect/pull/2562) [`2cecdbd`](https://github.com/Effect-TS/effect/commit/2cecdbd1cf30befce4e84796ccd953ea55ecfb86) Thanks [@fubhy](https://github.com/fubhy)! - Added provenance publishing\n\n- Updated dependencies [[`2cecdbd`](https://github.com/Effect-TS/effect/commit/2cecdbd1cf30befce4e84796ccd953ea55ecfb86)]:\n  - effect@3.0.2\n  - @effect/schema@0.66.2\n\n## 0.49.3\n\n### Patch Changes\n\n- [#2558](https://github.com/Effect-TS/effect/pull/2558) [`8d39d65`](https://github.com/Effect-TS/effect/commit/8d39d6554af548228ad767112ce2e0b1f68fa8e1) Thanks [@tim-smart](https://github.com/tim-smart)! - add no-op FileSystem constructor for testing\n\n## 0.49.2\n\n### Patch Changes\n\n- [#2556](https://github.com/Effect-TS/effect/pull/2556) [`5ef0a1a`](https://github.com/Effect-TS/effect/commit/5ef0a1ae9b773fa2481550cb0d43ff7a0e03cd44) Thanks [@tim-smart](https://github.com/tim-smart)! - fix Command stdin being closed too early\n\n## 0.49.1\n\n### Patch Changes\n\n- [#2542](https://github.com/Effect-TS/effect/pull/2542) [`87c5687`](https://github.com/Effect-TS/effect/commit/87c5687de0782dab177b7861217fa3b040046282) Thanks [@tim-smart](https://github.com/tim-smart)! - allow fs.watch backend to be customized\n\n  If you want to use the @parcel/watcher backend, you now need to provide it to\n  your effects.\n\n  ```ts\n  import { Layer } from \"effect\"\n  import { FileSystem } from \"@effect/platform\"\n  import { NodeFileSystem } from \"@effect/platform-node\"\n  import * as ParcelWatcher from \"@effect/platform-node/NodeFileSystem/ParcelWatcher\"\n\n  // create a Layer that uses the ParcelWatcher backend\n  NodeFileSystem.layer.pipe(Layer.provide(ParcelWatcher.layer))\n  ```\n\n- [#2555](https://github.com/Effect-TS/effect/pull/2555) [`8edacca`](https://github.com/Effect-TS/effect/commit/8edacca37f8e37c01a63fec332b06d9361efaa7b) Thanks [@tim-smart](https://github.com/tim-smart)! - prevent use of `Array` as import name to solve bundler issues\n\n- Updated dependencies [[`3da0cfa`](https://github.com/Effect-TS/effect/commit/3da0cfa12c407fd930dc480be1ecc9217a8058f8), [`570e8d8`](https://github.com/Effect-TS/effect/commit/570e8d87e7c0e9ad4cd2686462fdb9b4812f7716), [`b2b5d66`](https://github.com/Effect-TS/effect/commit/b2b5d6626b18eb5289f364ffab5240e84b04d085), [`8edacca`](https://github.com/Effect-TS/effect/commit/8edacca37f8e37c01a63fec332b06d9361efaa7b)]:\n  - effect@3.0.1\n  - @effect/schema@0.66.1\n\n## 0.49.0\n\n### Minor Changes\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`cf69f46`](https://github.com/Effect-TS/effect/commit/cf69f46690058d71eeada03cfb40dc744573e9e4) Thanks [@github-actions](https://github.com/apps/github-actions)! - make Http.middleware.withTracerDisabledWhen a Layer api\n\n  And add Http.middleware.withTracerDisabledWhenEffect to operate on Effect's.\n\n  Usage is now:\n\n  ```ts\n  import * as Http from \"@effect/platform/HttpServer\"\n\n  Http.router.empty.pipe(\n    Http.router.get(\"/health\"),\n    Http.server.serve(),\n    Http.middleware.withTracerDisabledWhen(\n      (request) => request.url === \"/no-tracing\"\n    )\n  )\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`aa4a3b5`](https://github.com/Effect-TS/effect/commit/aa4a3b550da1c1020265ac389ed3f309388994a2) Thanks [@github-actions](https://github.com/apps/github-actions)! - Swap type parameters in /platform data types\n\n  A codemod has been released to make migration easier:\n\n  ```\n  npx @effect/codemod platform-0.49 src/**/*\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`6c6087a`](https://github.com/Effect-TS/effect/commit/6c6087a4a897b64252346426660782d31c13f769) Thanks [@github-actions](https://github.com/apps/github-actions)! - rename auto-scoped ClientResponse apis from *Effect to *Scoped\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`5a2314b`](https://github.com/Effect-TS/effect/commit/5a2314b70ec79c2c02b51cef45a5ddec8327daa1) Thanks [@github-actions](https://github.com/apps/github-actions)! - replace use of `unit` terminology with `void`\n\n  For all the data types.\n\n  ```ts\n  Effect.unit // => Effect.void\n  Stream.unit // => Stream.void\n\n  // etc\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`6c6087a`](https://github.com/Effect-TS/effect/commit/6c6087a4a897b64252346426660782d31c13f769) Thanks [@github-actions](https://github.com/apps/github-actions)! - move fetch options to a FiberRef\n\n  This change makes adjusting options to fetch more composable. You can now do:\n\n  ```ts\n  import { pipe } from \"effect\"\n  import * as Http from \"@effect/platform/HttpClient\"\n\n  pipe(\n    Http.request.get(\"https://example.com\"),\n    Http.client.fetchOk,\n    Http.client.withFetchOptions({ credentials: \"include\" }),\n    Http.response.text\n  )\n  ```\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`2fb7d9c`](https://github.com/Effect-TS/effect/commit/2fb7d9ca15037ff62a578bb9fe5732da5f4f317d) Thanks [@github-actions](https://github.com/apps/github-actions)! - Release Effect 3.0 🎉\n\n### Patch Changes\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`6460414`](https://github.com/Effect-TS/effect/commit/6460414351a45fb8e0a457c63f3653422efee766) Thanks [@github-actions](https://github.com/apps/github-actions)! - properly handle multiple ports in SharedWorker\n\n- [#2207](https://github.com/Effect-TS/effect/pull/2207) [`cf69f46`](https://github.com/Effect-TS/effect/commit/cf69f46690058d71eeada03cfb40dc744573e9e4) Thanks [@github-actions](https://github.com/apps/github-actions)! - add Http.middleware.withTracerDisabledForUrls\n\n  Allows you to disable the http server tracer for the given urls:\n\n  ```ts\n  import * as Http from \"@effect/platform/HttpServer\"\n\n  Http.router.empty.pipe(\n    Http.router.get(\"/health\"),\n    Http.server.serve(),\n    Http.middleware.withTracerDisabledForUrls([\"/health\"])\n  )\n  ```\n\n- [#2529](https://github.com/Effect-TS/effect/pull/2529) [`78b767c`](https://github.com/Effect-TS/effect/commit/78b767c2b1625186e17131761a0edbac25d21850) Thanks [@fubhy](https://github.com/fubhy)! - Renamed `ReadonlyArray` and `ReadonlyRecord` modules for better discoverability.\n\n- [#2514](https://github.com/Effect-TS/effect/pull/2514) [`25d74f8`](https://github.com/Effect-TS/effect/commit/25d74f8c4d2dd4a9e5ec57ce2f20d36dedd25343) Thanks [@rocwang](https://github.com/rocwang)! - Fix UrlParams.makeUrl when globalThis.location is set to `undefined`\n\n- Updated dependencies [[`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`d50a652`](https://github.com/Effect-TS/effect/commit/d50a652479f4d1d64f48da05c79fa847e6e51548), [`9aeae46`](https://github.com/Effect-TS/effect/commit/9aeae461fdf9265389cf3dfe4e428b037215ba5f), [`9a3bd47`](https://github.com/Effect-TS/effect/commit/9a3bd47ebd0750c7e498162734f6d21895de0cb2), [`e542371`](https://github.com/Effect-TS/effect/commit/e542371981f8b4b484979feaad8a25b1f45e2df0), [`be9d025`](https://github.com/Effect-TS/effect/commit/be9d025e42355260ace02dd135851a8935a4deba), [`78b767c`](https://github.com/Effect-TS/effect/commit/78b767c2b1625186e17131761a0edbac25d21850), [`1499974`](https://github.com/Effect-TS/effect/commit/14999741d2e19c1747f6a7e19d68977f6429cdb8), [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`5c2b561`](https://github.com/Effect-TS/effect/commit/5c2b5614f583b88784ed68126ae939832fb3c092), [`a18f594`](https://github.com/Effect-TS/effect/commit/a18f5948f1439a147232448b2c443472fda0eceb), [`1499974`](https://github.com/Effect-TS/effect/commit/14999741d2e19c1747f6a7e19d68977f6429cdb8), [`2f96d93`](https://github.com/Effect-TS/effect/commit/2f96d938b90f8c19377583279e3c7afd9b509c50), [`5a2314b`](https://github.com/Effect-TS/effect/commit/5a2314b70ec79c2c02b51cef45a5ddec8327daa1), [`271b79f`](https://github.com/Effect-TS/effect/commit/271b79fc0b66a6c11e07a8779ff8800493a7eac2), [`1b5f0c7`](https://github.com/Effect-TS/effect/commit/1b5f0c77e7fd477a0026071e82129a948227f4b3), [`2fb7d9c`](https://github.com/Effect-TS/effect/commit/2fb7d9ca15037ff62a578bb9fe5732da5f4f317d), [`53d1c2a`](https://github.com/Effect-TS/effect/commit/53d1c2a77559081fbb89667e343346375c6d6650), [`e7e1bbe`](https://github.com/Effect-TS/effect/commit/e7e1bbe68486fdf31c8f84b0880522d39adcaad3), [`10c169e`](https://github.com/Effect-TS/effect/commit/10c169eadc874e91b4defca3f467b4e6a50fd8f3), [`6424181`](https://github.com/Effect-TS/effect/commit/64241815fe6a939e91e6947253e7dceea1306aa8)]:\n  - effect@3.0.0\n  - @effect/schema@0.66.0\n\n## 0.48.29\n\n### Patch Changes\n\n- [#2517](https://github.com/Effect-TS/effect/pull/2517) [`b79cc59`](https://github.com/Effect-TS/effect/commit/b79cc59dbe64b9a0a7742dc9100a9d36c8e46b72) Thanks [@tim-smart](https://github.com/tim-smart)! - add uninterruptible option to http routes, for marking a route as uninterruptible\n\n## 0.48.28\n\n### Patch Changes\n\n- [#2515](https://github.com/Effect-TS/effect/pull/2515) [`d590094`](https://github.com/Effect-TS/effect/commit/d5900943489ec1e0891836aeafb5ce99fb9c75c7) Thanks [@tim-smart](https://github.com/tim-smart)! - add Http.router.uninterruptible, for marking a route as uninterruptible\n\n- Updated dependencies [[`0aee906`](https://github.com/Effect-TS/effect/commit/0aee906f034539344db6fbac08919de3e28eccde), [`41c8102`](https://github.com/Effect-TS/effect/commit/41c810228b1a50e4b41f19e735d7c62fe8d36871), [`4c37001`](https://github.com/Effect-TS/effect/commit/4c370013417e18c4f564818de1341a8fccb43b4c), [`776ef2b`](https://github.com/Effect-TS/effect/commit/776ef2bb66db9aa9f68b7beab14f6986f9c1288b), [`217147e`](https://github.com/Effect-TS/effect/commit/217147ea67c5c42c96f024775c41e5b070f81e4c), [`8a69b4e`](https://github.com/Effect-TS/effect/commit/8a69b4ef6a3a06d2e21fe2e11a626038beefb4e1), [`90776ec`](https://github.com/Effect-TS/effect/commit/90776ec8e8671d835b65fc33ead1de6c864b81b9), [`b3acf47`](https://github.com/Effect-TS/effect/commit/b3acf47f9c9dfae1c99377aa906097aaa2d47d44), [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55), [`232c353`](https://github.com/Effect-TS/effect/commit/232c353c2e6f743f38e57639ee30e324ffa9c2a9), [`0d3231a`](https://github.com/Effect-TS/effect/commit/0d3231a195202635ecc0bf6bbf6a08fc017d0d69), [`0ca835c`](https://github.com/Effect-TS/effect/commit/0ca835cbac8e69072a93ace83b534219faba24e8), [`8709856`](https://github.com/Effect-TS/effect/commit/870985694ae985c3cb9360ad8a25c60e6f785f55), [`c22b019`](https://github.com/Effect-TS/effect/commit/c22b019e5eaf9d3a937a3d99cadbb8f8e9116a70), [`e983740`](https://github.com/Effect-TS/effect/commit/e9837401145605aff5bc2ec7e73004f397c5d2d1), [`e3e0924`](https://github.com/Effect-TS/effect/commit/e3e09247d46a35430fc60e4aa4032cc50814f212)]:\n  - @effect/schema@0.65.0\n  - effect@2.4.19\n\n## 0.48.27\n\n### Patch Changes\n\n- [#2479](https://github.com/Effect-TS/effect/pull/2479) [`c6dd3c6`](https://github.com/Effect-TS/effect/commit/c6dd3c6909cafe05adc8450c5a499260e17e60d3) Thanks [@tim-smart](https://github.com/tim-smart)! - Make the file tree provider the fallback in PlatformConfigProvider.layerFileTreeAdd\n\n- [#2486](https://github.com/Effect-TS/effect/pull/2486) [`672f137`](https://github.com/Effect-TS/effect/commit/672f13747ddf6dac3ba304fd4511b1df44ab566d) Thanks [@tim-smart](https://github.com/tim-smart)! - accept string as a valid Socket input\n\n- [#2486](https://github.com/Effect-TS/effect/pull/2486) [`672f137`](https://github.com/Effect-TS/effect/commit/672f13747ddf6dac3ba304fd4511b1df44ab566d) Thanks [@tim-smart](https://github.com/tim-smart)! - add Socket.runRaw to handle strings directly\n\n- Updated dependencies [[`42b3651`](https://github.com/Effect-TS/effect/commit/42b36519f356bae9258a1ea1d416e2902b973e85)]:\n  - @effect/schema@0.64.20\n\n## 0.48.26\n\n### Patch Changes\n\n- [#2477](https://github.com/Effect-TS/effect/pull/2477) [`365a486`](https://github.com/Effect-TS/effect/commit/365a4865de5e47ce09f4cfd51fc0f67438f82a57) Thanks [@tim-smart](https://github.com/tim-smart)! - add PlatformConfigProvider module\n\n  It contains a file tree provider, that can be used to read config values from a file tree.\n\n  For example, if you have a file tree like this:\n\n  ```\n  config/\n    secret\n    nested/\n      value\n  ```\n\n  You could do the following:\n\n  ```ts\n  import { PlatformConfigProvider } from \"@effect/platform\"\n  import { NodeContext } from \"@effect/platform-node\"\n  import { Config, Effect, Layer } from \"effect\"\n\n  const ConfigProviderLive = PlatformConfigProvider.layerFileTree({\n    rootDirectory: `/config`\n  }).pipe(Layer.provide(NodeContext.layer))\n\n  Effect.gen(function* (_) {\n    const secret = yield* _(Config.secret(\"secret\"))\n    const value = yield* _(Config.string(\"value\"), Config.nested(\"nested\"))\n  }).pipe(Effect.provide(ConfigProviderLive))\n  ```\n\n## 0.48.25\n\n### Patch Changes\n\n- [#2469](https://github.com/Effect-TS/effect/pull/2469) [`d209171`](https://github.com/Effect-TS/effect/commit/d2091714a786820ebae4bef04a9d67d25dd08e88) Thanks [@tim-smart](https://github.com/tim-smart)! - replace isomorphic-ws with isows\n\n- Updated dependencies [[`dadc690`](https://github.com/Effect-TS/effect/commit/dadc6906121c512bc32be22b52adbd1ada834594), [`58f66fe`](https://github.com/Effect-TS/effect/commit/58f66fecd4e646c6c8f10995df9faab17022eb8f), [`3cad21d`](https://github.com/Effect-TS/effect/commit/3cad21daa5d2332d33692498c87b7ffff979e304)]:\n  - effect@2.4.18\n  - @effect/schema@0.64.19\n\n## 0.48.24\n\n### Patch Changes\n\n- [#2427](https://github.com/Effect-TS/effect/pull/2427) [`9c6a500`](https://github.com/Effect-TS/effect/commit/9c6a5001b467b6255c68a922f4b6e8d692b63d01) Thanks [@devmatteini](https://github.com/devmatteini)! - add force option to FileSystem.remove\n\n- [#2463](https://github.com/Effect-TS/effect/pull/2463) [`35ad0ba`](https://github.com/Effect-TS/effect/commit/35ad0ba9f3ba27c60453620e514b980f819f92af) Thanks [@tim-smart](https://github.com/tim-smart)! - fix exact optional properties type errors\n\n- Updated dependencies [[`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`607b2e7`](https://github.com/Effect-TS/effect/commit/607b2e7a7fd9318c57acf4e50ec61747eea74ad7), [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`8206caf`](https://github.com/Effect-TS/effect/commit/8206caf7c2d22c68be4313318b61cfdacf6222b6), [`7ddd654`](https://github.com/Effect-TS/effect/commit/7ddd65415b65ccb654ad04f4dbefe39402f15117), [`7ddd654`](https://github.com/Effect-TS/effect/commit/7ddd65415b65ccb654ad04f4dbefe39402f15117), [`8fdfda6`](https://github.com/Effect-TS/effect/commit/8fdfda6618be848c01b399d13bc05a9a3adfb613), [`f456ba2`](https://github.com/Effect-TS/effect/commit/f456ba273bae21a6dcf8c966c50c97b5f0897d9f)]:\n  - effect@2.4.17\n  - @effect/schema@0.64.18\n\n## 0.48.23\n\n### Patch Changes\n\n- [#2445](https://github.com/Effect-TS/effect/pull/2445) [`5170ce7`](https://github.com/Effect-TS/effect/commit/5170ce708c606283e8a30d273950f1a21c7eddc2) Thanks [@vecerek](https://github.com/vecerek)! - Add support for W3C Trace Context propagation\n\n- [#2454](https://github.com/Effect-TS/effect/pull/2454) [`63a1df2`](https://github.com/Effect-TS/effect/commit/63a1df2e4de3766f48f15676fbd0360ab9c27816) Thanks [@tim-smart](https://github.com/tim-smart)! - add support for binary data with XHR client\n\n- [#2450](https://github.com/Effect-TS/effect/pull/2450) [`74a5dae`](https://github.com/Effect-TS/effect/commit/74a5daed0e65b32a36e026bfcf66d02269cb967a) Thanks [@vecerek](https://github.com/vecerek)! - Platform: auto-instrument HTTP client\n\n- Updated dependencies [[`5170ce7`](https://github.com/Effect-TS/effect/commit/5170ce708c606283e8a30d273950f1a21c7eddc2), [`62a7f23`](https://github.com/Effect-TS/effect/commit/62a7f23937c0dfaca67a7b2f055b85cfde25ed11), [`7cc2b41`](https://github.com/Effect-TS/effect/commit/7cc2b41d6c551fdca2590b06681c5ad9832aba46), [`8b46fde`](https://github.com/Effect-TS/effect/commit/8b46fdebf2c075a74cd2cd29dfb69531d20fc154)]:\n  - effect@2.4.16\n  - @effect/schema@0.64.17\n\n## 0.48.22\n\n### Patch Changes\n\n- Updated dependencies [[`a31917a`](https://github.com/Effect-TS/effect/commit/a31917aa4b05b1189b7a8e0bedb60bb3d49262ad), [`4cd2bed`](https://github.com/Effect-TS/effect/commit/4cd2bedf978f864bddd289d1c524c8e868bf587b), [`6cc6267`](https://github.com/Effect-TS/effect/commit/6cc6267026d9bfb1a9882cddf534787327e86ec1)]:\n  - @effect/schema@0.64.16\n\n## 0.48.21\n\n### Patch Changes\n\n- Updated dependencies [[`d7688c0`](https://github.com/Effect-TS/effect/commit/d7688c0c72717fe7876c871567f6946dabfc0546), [`b3a4fac`](https://github.com/Effect-TS/effect/commit/b3a4face2acaca422f0b0530436e8f13129f3b3a), [`5ded019`](https://github.com/Effect-TS/effect/commit/5ded019970169e3c1f2a375d0876b95fb1ff67f5)]:\n  - effect@2.4.15\n  - @effect/schema@0.64.15\n\n## 0.48.20\n\n### Patch Changes\n\n- [#2413](https://github.com/Effect-TS/effect/pull/2413) [`4789083`](https://github.com/Effect-TS/effect/commit/4789083283bdaec456982d614ebc4a496ea0e7f7) Thanks [@tim-smart](https://github.com/tim-smart)! - make /platform ClientRequest implement Effect\n\n  ClientRequest now implements `Effect<ClientResponse, HttpClientError, Client.Default | Scope>`\n\n  This makes it easier to quickly create a request and execute it in a single line.\n\n  ```ts\n  import * as Http from \"@effect/platform/HttpClient\"\n\n  Http.request\n    .get(\"https://jsonplaceholder.typicode.com/todos/1\")\n    .pipe(Http.response.json)\n  ```\n\n- [#2413](https://github.com/Effect-TS/effect/pull/2413) [`4789083`](https://github.com/Effect-TS/effect/commit/4789083283bdaec456982d614ebc4a496ea0e7f7) Thanks [@tim-smart](https://github.com/tim-smart)! - prevent unhandled errors in undici http client\n\n## 0.48.19\n\n### Patch Changes\n\n- [#2411](https://github.com/Effect-TS/effect/pull/2411) [`fb7285e`](https://github.com/Effect-TS/effect/commit/fb7285e8d6a70527df7137a6a3efdd03ae61cb8b) Thanks [@tim-smart](https://github.com/tim-smart)! - fix broken imports in /platform\n\n## 0.48.18\n\n### Patch Changes\n\n- [#2410](https://github.com/Effect-TS/effect/pull/2410) [`26435ec`](https://github.com/Effect-TS/effect/commit/26435ecfa06569dc18d1801ccf38213a43b7c334) Thanks [@tim-smart](https://github.com/tim-smart)! - add undici http client to @effect/platform-node\n\n- Updated dependencies [[`a76e5e1`](https://github.com/Effect-TS/effect/commit/a76e5e131a35c88a72771fb745df08f60fbc0e18), [`6180c0c`](https://github.com/Effect-TS/effect/commit/6180c0cc51dee785cfce72220a52c9fc3b9bf9aa)]:\n  - @effect/schema@0.64.14\n  - effect@2.4.14\n\n## 0.48.17\n\n### Patch Changes\n\n- [#2400](https://github.com/Effect-TS/effect/pull/2400) [`47a8f1b`](https://github.com/Effect-TS/effect/commit/47a8f1b644d8294692d92cacd3c8c7543edbfabe) Thanks [@tim-smart](https://github.com/tim-smart)! - expose Schema ParseOptions in /platform schema apis\n\n- [#2403](https://github.com/Effect-TS/effect/pull/2403) [`8c9abe2`](https://github.com/Effect-TS/effect/commit/8c9abe2b35c46d8891d4b2c14ff9eb46302a14f3) Thanks [@tim-smart](https://github.com/tim-smart)! - use ReadonlyRecord for storing cookies\n\n- [#2403](https://github.com/Effect-TS/effect/pull/2403) [`8c9abe2`](https://github.com/Effect-TS/effect/commit/8c9abe2b35c46d8891d4b2c14ff9eb46302a14f3) Thanks [@tim-smart](https://github.com/tim-smart)! - add set-cookie headers in Http.response.toWeb\n\n- [#2400](https://github.com/Effect-TS/effect/pull/2400) [`47a8f1b`](https://github.com/Effect-TS/effect/commit/47a8f1b644d8294692d92cacd3c8c7543edbfabe) Thanks [@tim-smart](https://github.com/tim-smart)! - add .schemaJson / .schemaNoBody to http router apis\n\n- Updated dependencies [[`3336287`](https://github.com/Effect-TS/effect/commit/3336287ff55a25e56d759b83847bfaa21c40f499), [`54b7c00`](https://github.com/Effect-TS/effect/commit/54b7c0077fa784ad2646b812d6a44641f672edcd), [`3336287`](https://github.com/Effect-TS/effect/commit/3336287ff55a25e56d759b83847bfaa21c40f499)]:\n  - effect@2.4.13\n  - @effect/schema@0.64.13\n\n## 0.48.16\n\n### Patch Changes\n\n- [#2387](https://github.com/Effect-TS/effect/pull/2387) [`75a8d16`](https://github.com/Effect-TS/effect/commit/75a8d16247cc14860cdd7fd948ef542c50c2d55e) Thanks [@tim-smart](https://github.com/tim-smart)! - add Cookies module to /platform http\n\n  To add cookies to a http response:\n\n  ```ts\n  import * as Http from \"@effect/platform/HttpServer\"\n\n  Http.response.empty().pipe(\n    Http.response.setCookies([\n      [\"name\", \"value\"],\n      [\"foo\", \"bar\", { httpOnly: true }]\n    ])\n  )\n  ```\n\n  You can also use cookies with the http client:\n\n  ```ts\n  import * as Http from \"@effect/platform/HttpClient\"\n  import { Effect, Ref } from \"effect\"\n\n  Effect.gen(function* (_) {\n    const ref = yield* _(Ref.make(Http.cookies.empty))\n    const defaultClient = yield* _(Http.client.Client)\n    const clientWithCookies = defaultClient.pipe(\n      Http.client.withCookiesRef(ref),\n      Http.client.filterStatusOk\n    )\n\n    // cookies will be stored in the ref and sent in any subsequent requests\n    yield* _(\n      Http.request.get(\"https://www.google.com/\"),\n      clientWithCookies,\n      Effect.scoped\n    )\n  })\n  ```\n\n- [#2385](https://github.com/Effect-TS/effect/pull/2385) [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87) Thanks [@tim-smart](https://github.com/tim-smart)! - update typescript to 5.4\n\n- Updated dependencies [[`9392de6`](https://github.com/Effect-TS/effect/commit/9392de6baa6861662abc2bd3171897145f5ea073), [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87), [`9392de6`](https://github.com/Effect-TS/effect/commit/9392de6baa6861662abc2bd3171897145f5ea073), [`3307729`](https://github.com/Effect-TS/effect/commit/3307729de162a033fa9caa8e14c111013dcf0d87), [`d17a427`](https://github.com/Effect-TS/effect/commit/d17a427c4427972fb55c45a058780716dc408631)]:\n  - @effect/schema@0.64.12\n  - effect@2.4.12\n\n## 0.48.15\n\n### Patch Changes\n\n- Updated dependencies [[`2f488c4`](https://github.com/Effect-TS/effect/commit/2f488c436de52576562803c57ebc132ef40ccdd8), [`37ca592`](https://github.com/Effect-TS/effect/commit/37ca592a4101ad90adbf8c8b3f727faf3110cae5), [`317b5b8`](https://github.com/Effect-TS/effect/commit/317b5b8e8c8c2207469b3ebfcf72bf3a9f7cbc60)]:\n  - effect@2.4.11\n  - @effect/schema@0.64.11\n\n## 0.48.14\n\n### Patch Changes\n\n- Updated dependencies [[`9bab1f9`](https://github.com/Effect-TS/effect/commit/9bab1f9fa5b999740755e4e82485cb77c638643a), [`9bbde5b`](https://github.com/Effect-TS/effect/commit/9bbde5be9a0168d1c2a0308bfc27167ed62f3968)]:\n  - effect@2.4.10\n  - @effect/schema@0.64.10\n\n## 0.48.13\n\n### Patch Changes\n\n- Updated dependencies [[`dc7e497`](https://github.com/Effect-TS/effect/commit/dc7e49720df416870a7483f48adc40aeb23fe32d), [`ffaf7c3`](https://github.com/Effect-TS/effect/commit/ffaf7c36514f88496cdd2fdfdf0bc7ba5a2e5cd4)]:\n  - @effect/schema@0.64.9\n\n## 0.48.12\n\n### Patch Changes\n\n- Updated dependencies [[`e0af20e`](https://github.com/Effect-TS/effect/commit/e0af20ec5f6d0b19d66c5ebf610969d55bfc6c22)]:\n  - @effect/schema@0.64.8\n\n## 0.48.11\n\n### Patch Changes\n\n- [#2360](https://github.com/Effect-TS/effect/pull/2360) [`0f6c7b4`](https://github.com/Effect-TS/effect/commit/0f6c7b426eb3432f60e3a17f8cd92ceac91597bf) Thanks [@tim-smart](https://github.com/tim-smart)! - add support for watching single files\n\n## 0.48.10\n\n### Patch Changes\n\n- [#2357](https://github.com/Effect-TS/effect/pull/2357) [`71fd528`](https://github.com/Effect-TS/effect/commit/71fd5287500f9ce155a7d9f0df6ee3e0ac3aeb99) Thanks [@tim-smart](https://github.com/tim-smart)! - make more data types in /platform implement Inspectable\n\n- Updated dependencies [[`71fd528`](https://github.com/Effect-TS/effect/commit/71fd5287500f9ce155a7d9f0df6ee3e0ac3aeb99)]:\n  - effect@2.4.9\n  - @effect/schema@0.64.7\n\n## 0.48.9\n\n### Patch Changes\n\n- Updated dependencies [[`595140a`](https://github.com/Effect-TS/effect/commit/595140a13bda09bf22c669196440868e8a274599), [`5f5fcd9`](https://github.com/Effect-TS/effect/commit/5f5fcd969ae30ed6fe61d566a571498d9e895e16), [`bb0b69e`](https://github.com/Effect-TS/effect/commit/bb0b69e519698c7c76aa68217de423c78ad16566), [`7a45ad0`](https://github.com/Effect-TS/effect/commit/7a45ad0a5f715d64a69b28a8ee3573e5f86909c3), [`5c3b1cc`](https://github.com/Effect-TS/effect/commit/5c3b1ccba182d0f636a973729f9c6bfb12539dc8), [`6f7dfc9`](https://github.com/Effect-TS/effect/commit/6f7dfc9637bd641beb93b14e027dcfcb5d2c8feb), [`88b8583`](https://github.com/Effect-TS/effect/commit/88b85838e03d4f33036f9d16c9c00a487fa99bd8), [`cb20824`](https://github.com/Effect-TS/effect/commit/cb20824416cbf251188395d0aad3622e3a5d7ff2), [`6b20bad`](https://github.com/Effect-TS/effect/commit/6b20badebb3a7ca4d38857753e8ecaa09d02ccfb), [`4e64e9b`](https://github.com/Effect-TS/effect/commit/4e64e9b9876de6bfcbabe39e18a91a08e5f3fbb0), [`3851a02`](https://github.com/Effect-TS/effect/commit/3851a022c481006aec1db36651e4b4fd727aa742), [`5f5fcd9`](https://github.com/Effect-TS/effect/commit/5f5fcd969ae30ed6fe61d566a571498d9e895e16), [`814e5b8`](https://github.com/Effect-TS/effect/commit/814e5b828f68210b9e8f336fd6ac688646835dd9), [`a45a525`](https://github.com/Effect-TS/effect/commit/a45a525e7ccf07704dff1666f1e390282b5bac91)]:\n  - @effect/schema@0.64.6\n  - effect@2.4.8\n\n## 0.48.8\n\n### Patch Changes\n\n- [#2334](https://github.com/Effect-TS/effect/pull/2334) [`69d27bb`](https://github.com/Effect-TS/effect/commit/69d27bb633884b6b50f9c3d9e95c29f09b4860b5) Thanks [@tim-smart](https://github.com/tim-smart)! - add .watch method to /platform FileSystem\n\n  It can be used to listen for file system events. Example:\n\n  ```ts\n  import { FileSystem } from \"@effect/platform\"\n  import { NodeFileSystem, NodeRuntime } from \"@effect/platform-node\"\n  import { Console, Effect, Stream } from \"effect\"\n\n  Effect.gen(function* (_) {\n    const fs = yield* _(FileSystem.FileSystem)\n    yield* _(fs.watch(\"./\"), Stream.runForEach(Console.log))\n  }).pipe(Effect.provide(NodeFileSystem.layer), NodeRuntime.runMain)\n  ```\n\n- Updated dependencies [[`d0f56c6`](https://github.com/Effect-TS/effect/commit/d0f56c68e604b1cf8dd4e761a3f3cf3631b3cec1)]:\n  - @effect/schema@0.64.5\n\n## 0.48.7\n\n### Patch Changes\n\n- [#2330](https://github.com/Effect-TS/effect/pull/2330) [`f908948`](https://github.com/Effect-TS/effect/commit/f908948fd05771a670c0b746e2dd9caa9408ef83) Thanks [@tim-smart](https://github.com/tim-smart)! - use Deferred.unsafeDone for websocket onclose + onerror\n\n## 0.48.6\n\n### Patch Changes\n\n- Updated dependencies [[`eb93283`](https://github.com/Effect-TS/effect/commit/eb93283985913d7b04ca750e36ac8513e7b6cef6)]:\n  - effect@2.4.7\n  - @effect/schema@0.64.4\n\n## 0.48.5\n\n### Patch Changes\n\n- [#2325](https://github.com/Effect-TS/effect/pull/2325) [`e006e4a`](https://github.com/Effect-TS/effect/commit/e006e4a538c97bae6ca1efa74802159e8a688fcb) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure Socket fibers are interruptible\n\n## 0.48.4\n\n### Patch Changes\n\n- Updated dependencies [[`cfef6ec`](https://github.com/Effect-TS/effect/commit/cfef6ecd1fe801cec1a3cbfb7f064fc394b0ad73)]:\n  - @effect/schema@0.64.3\n\n## 0.48.3\n\n### Patch Changes\n\n- [#2314](https://github.com/Effect-TS/effect/pull/2314) [`c362e06`](https://github.com/Effect-TS/effect/commit/c362e066550252d5a9fcbc31a4b34d0e17c50699) Thanks [@tim-smart](https://github.com/tim-smart)! - prevent unhandled fiber errors in Sockets\n\n- [#2262](https://github.com/Effect-TS/effect/pull/2262) [`83ddd6f`](https://github.com/Effect-TS/effect/commit/83ddd6f41029724b2cbd144cf309463967ed1164) Thanks [@thewilkybarkid](https://github.com/thewilkybarkid)! - Don't log an empty message when responding to a request\n\n## 0.48.2\n\n### Patch Changes\n\n- [#2290](https://github.com/Effect-TS/effect/pull/2290) [`4f35a7e`](https://github.com/Effect-TS/effect/commit/4f35a7e7c4eba598924aff24d1158b9056bb24be) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Remove function renaming from internals, introduce new cutpoint strategy\n\n- Updated dependencies [[`89748c9`](https://github.com/Effect-TS/effect/commit/89748c90b36cb5eb880a9ab9323b252338dee848), [`4f35a7e`](https://github.com/Effect-TS/effect/commit/4f35a7e7c4eba598924aff24d1158b9056bb24be), [`9971186`](https://github.com/Effect-TS/effect/commit/99711862722188fbb5ed3ee75126ad5edf13f72f)]:\n  - @effect/schema@0.64.2\n  - effect@2.4.6\n\n## 0.48.1\n\n### Patch Changes\n\n- Updated dependencies [[`d10f876`](https://github.com/Effect-TS/effect/commit/d10f876cd98da275bc5dc5750a91a7fc95e97541), [`743ae6d`](https://github.com/Effect-TS/effect/commit/743ae6d12b249f0b35b31b65b2f7ec91d83ee387), [`a75bc48`](https://github.com/Effect-TS/effect/commit/a75bc48e0e3278d0f70665fedecc5ae7ec447e24), [`bce21c5`](https://github.com/Effect-TS/effect/commit/bce21c5ded2177114666ba229bd5029fa000dee3), [`c7d3036`](https://github.com/Effect-TS/effect/commit/c7d303630b7f0825cb2e584557c5767a67214d9f)]:\n  - @effect/schema@0.64.1\n  - effect@2.4.5\n\n## 0.48.0\n\n### Minor Changes\n\n- [#2287](https://github.com/Effect-TS/effect/pull/2287) [`a1f44cb`](https://github.com/Effect-TS/effect/commit/a1f44cb5112713ff9a3ac3d91a63a2c99d6b7fc1) Thanks [@tim-smart](https://github.com/tim-smart)! - add option to /platform runMain to disable error reporting\n\n- [#2279](https://github.com/Effect-TS/effect/pull/2279) [`bdff193`](https://github.com/Effect-TS/effect/commit/bdff193365dd9ec2863573b08eb960aa8dee5c93) Thanks [@gcanti](https://github.com/gcanti)! - - `src/Worker.ts`\n  - use `CauseEncoded` in `Worker` namespace\n  - `src/WorkerError.ts`\n    - use `CauseEncoded` in `Cause`\n\n### Patch Changes\n\n- [#2284](https://github.com/Effect-TS/effect/pull/2284) [`1cb7f9c`](https://github.com/Effect-TS/effect/commit/1cb7f9cff7c2272a32fc7a324d87b02e2cd8a2f5) Thanks [@tim-smart](https://github.com/tim-smart)! - use Schema.declare for http multipart PersistedFile schema\n\n- [#2283](https://github.com/Effect-TS/effect/pull/2283) [`509be1a`](https://github.com/Effect-TS/effect/commit/509be1a0817118489750cf028523134677e44a8a) Thanks [@tim-smart](https://github.com/tim-smart)! - add SocketCloseError with additional metadata\n\n- [#2284](https://github.com/Effect-TS/effect/pull/2284) [`1cb7f9c`](https://github.com/Effect-TS/effect/commit/1cb7f9cff7c2272a32fc7a324d87b02e2cd8a2f5) Thanks [@tim-smart](https://github.com/tim-smart)! - add more http multipart data type refinements\n\n- [#2281](https://github.com/Effect-TS/effect/pull/2281) [`e7ca973`](https://github.com/Effect-TS/effect/commit/e7ca973c5430ae60716701e58bedd4632ff971fd) Thanks [@tim-smart](https://github.com/tim-smart)! - add OpenTimeout error to websocket client\n\n- [#2286](https://github.com/Effect-TS/effect/pull/2286) [`d910dd2`](https://github.com/Effect-TS/effect/commit/d910dd2ca1e8e5aa2f09d9bf3694ede745758f99) Thanks [@tim-smart](https://github.com/tim-smart)! - allow optional fields in http form schemas\n\n- [#2281](https://github.com/Effect-TS/effect/pull/2281) [`e7ca973`](https://github.com/Effect-TS/effect/commit/e7ca973c5430ae60716701e58bedd4632ff971fd) Thanks [@tim-smart](https://github.com/tim-smart)! - support closing a Socket by writing a CloseEvent\n\n- Updated dependencies [[`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949), [`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949), [`5d47ee0`](https://github.com/Effect-TS/effect/commit/5d47ee0855e492532085b6092879b1b952d84949), [`817a04c`](https://github.com/Effect-TS/effect/commit/817a04cb2df0f4140984dc97eb3e1bb14a6c4a38), [`d90a99d`](https://github.com/Effect-TS/effect/commit/d90a99d03d074adc7cd2533f15419138264da5a2), [`dd05faa`](https://github.com/Effect-TS/effect/commit/dd05faa621555ef3585ecd914ac13ecd89b710f4), [`dd05faa`](https://github.com/Effect-TS/effect/commit/dd05faa621555ef3585ecd914ac13ecd89b710f4), [`802674b`](https://github.com/Effect-TS/effect/commit/802674b379b7559ad3ff09b33388891445a9e48b)]:\n  - @effect/schema@0.64.0\n  - effect@2.4.4\n\n## 0.47.1\n\n### Patch Changes\n\n- [#2276](https://github.com/Effect-TS/effect/pull/2276) [`0680545`](https://github.com/Effect-TS/effect/commit/068054540f19bb23a79c7c021ed8b2fe34f3e19f) Thanks [@tim-smart](https://github.com/tim-smart)! - improve /platform error messages\n\n- Updated dependencies [[`20e63fb`](https://github.com/Effect-TS/effect/commit/20e63fb9207210f3fe2d136ec40d0a2dbff3225e), [`20e63fb`](https://github.com/Effect-TS/effect/commit/20e63fb9207210f3fe2d136ec40d0a2dbff3225e)]:\n  - effect@2.4.3\n  - @effect/schema@0.63.4\n\n## 0.47.0\n\n### Minor Changes\n\n- [#2261](https://github.com/Effect-TS/effect/pull/2261) [`fa9663c`](https://github.com/Effect-TS/effect/commit/fa9663cb854ca03dba672d7857ecff84f1140c9e) Thanks [@tim-smart](https://github.com/tim-smart)! - move Socket module to platform\n\n### Patch Changes\n\n- [#2267](https://github.com/Effect-TS/effect/pull/2267) [`0f3d99c`](https://github.com/Effect-TS/effect/commit/0f3d99c27521ec6b221b644a0fffc79199c3acca) Thanks [@tim-smart](https://github.com/tim-smart)! - propogate Socket handler errors to .run Effect\n\n- [#2269](https://github.com/Effect-TS/effect/pull/2269) [`4064ea0`](https://github.com/Effect-TS/effect/commit/4064ea04e0b3fa23108ee471cd89ab2482b2f6e5) Thanks [@jessekelly881](https://github.com/jessekelly881)! - added PlatformLogger module, for writing logs to a file\n\n  If you wanted to write logfmt logs to a file, you can do the following:\n\n  ```ts\n  import { PlatformLogger } from \"@effect/platform\"\n  import { NodeFileSystem, NodeRuntime } from \"@effect/platform-node\"\n  import { Effect, Layer, Logger } from \"effect\"\n\n  const fileLogger = Logger.logfmtLogger.pipe(PlatformLogger.toFile(\"log.txt\"))\n  const LoggerLive = Logger.replaceScoped(\n    Logger.defaultLogger,\n    fileLogger\n  ).pipe(Layer.provide(NodeFileSystem.layer))\n\n  Effect.log(\"a\").pipe(\n    Effect.zipRight(Effect.log(\"b\")),\n    Effect.zipRight(Effect.log(\"c\")),\n    Effect.provide(LoggerLive),\n    NodeRuntime.runMain\n  )\n  ```\n\n- [#2261](https://github.com/Effect-TS/effect/pull/2261) [`fa9663c`](https://github.com/Effect-TS/effect/commit/fa9663cb854ca03dba672d7857ecff84f1140c9e) Thanks [@tim-smart](https://github.com/tim-smart)! - add websocket support to platform http server\n\n  You can use the `Http.request.upgrade*` apis to access the `Socket` for the request.\n\n  Here is an example server that handles websockets on the `/ws` path:\n\n  ```ts\n  import { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\n  import * as Http from \"@effect/platform/HttpServer\"\n  import { Console, Effect, Layer, Schedule, Stream } from \"effect\"\n  import { createServer } from \"node:http\"\n\n  const ServerLive = NodeHttpServer.server.layer(() => createServer(), {\n    port: 3000\n  })\n\n  const HttpLive = Http.router.empty.pipe(\n    Http.router.get(\n      \"/ws\",\n      Effect.gen(function* (_) {\n        yield* _(\n          Stream.fromSchedule(Schedule.spaced(1000)),\n          Stream.map(JSON.stringify),\n          Stream.encodeText,\n          Stream.pipeThroughChannel(Http.request.upgradeChannel()),\n          Stream.decodeText(),\n          Stream.runForEach(Console.log)\n        )\n        return Http.response.empty()\n      })\n    ),\n    Http.server.serve(Http.middleware.logger),\n    Http.server.withLogAddress,\n    Layer.provide(ServerLive)\n  )\n\n  NodeRuntime.runMain(Layer.launch(HttpLive))\n  ```\n\n- Updated dependencies [[`e03811e`](https://github.com/Effect-TS/effect/commit/e03811e80c93e986e6348b3b67ac2ed6d5fefff0), [`ac41d84`](https://github.com/Effect-TS/effect/commit/ac41d84776484cdce8165b7ca2c9c9b6377eee2d), [`6137533`](https://github.com/Effect-TS/effect/commit/613753300c7705518ab1fea2f370b032851c2750), [`f373529`](https://github.com/Effect-TS/effect/commit/f373529999f4b8bc92b634f6ea14f19271388eed), [`1bf9f31`](https://github.com/Effect-TS/effect/commit/1bf9f31f07667de677673f7c29a4e7a26ebad3c8), [`e3ff789`](https://github.com/Effect-TS/effect/commit/e3ff789226f89e71eb28ca38ce79f90af6a03f1a), [`6137533`](https://github.com/Effect-TS/effect/commit/613753300c7705518ab1fea2f370b032851c2750), [`507ba40`](https://github.com/Effect-TS/effect/commit/507ba4060ff043c1a8d541dae723fa6940633b00), [`e466afe`](https://github.com/Effect-TS/effect/commit/e466afe32f2de598ceafd8982bd0cfbd388e5671), [`465be79`](https://github.com/Effect-TS/effect/commit/465be7926afe98169837d8a4ed5ebc059a732d21), [`f373529`](https://github.com/Effect-TS/effect/commit/f373529999f4b8bc92b634f6ea14f19271388eed), [`de74eb8`](https://github.com/Effect-TS/effect/commit/de74eb80a79eebde5ff645033765e7a617e92f27), [`d8e6940`](https://github.com/Effect-TS/effect/commit/d8e694040f67da6fefc0f5c98fc8e15c0b48822e)]:\n  - effect@2.4.2\n  - @effect/schema@0.63.3\n\n## 0.46.3\n\n### Patch Changes\n\n- [#2231](https://github.com/Effect-TS/effect/pull/2231) [`7535080`](https://github.com/Effect-TS/effect/commit/7535080f2e2f9859711031161600c01807cc43ea) Thanks [@tim-smart](https://github.com/tim-smart)! - add option to include prefix when mounting an http app to a router\n\n  By default the prefix is removed. For example:\n\n  ```ts\n  // Here a request to `/child/hello` will be mapped to `/hello`\n  Http.router.mountApp(\"/child\", httpApp)\n\n  // Here a request to `/child/hello` will be mapped to `/child/hello`\n  Http.router.mountApp(\"/child\", httpApp, { includePrefix: true })\n  ```\n\n- [#2232](https://github.com/Effect-TS/effect/pull/2232) [`bd1d7ac`](https://github.com/Effect-TS/effect/commit/bd1d7ac75eea57a94d5e2d8e1edccb3136e84899) Thanks [@tim-smart](https://github.com/tim-smart)! - use less aggressive type exclusion in http router apis\n\n- Updated dependencies [[`a4a0006`](https://github.com/Effect-TS/effect/commit/a4a0006c7f19fc261df5cda16963d73457e4d6ac), [`39f583e`](https://github.com/Effect-TS/effect/commit/39f583eaeb29eecd6eaec3b113b24d9d413153df), [`f428198`](https://github.com/Effect-TS/effect/commit/f428198725d4b9e304ecd5ff8bad8f92d871dbe3), [`0a37676`](https://github.com/Effect-TS/effect/commit/0a37676aa0eb2a21e17af2e6df9f81f52bbc8831), [`c035972`](https://github.com/Effect-TS/effect/commit/c035972dfabdd3cb3372b5ab468aa2fd0d808f4d), [`6f503b7`](https://github.com/Effect-TS/effect/commit/6f503b774d893bf2af34f66202e270d8c45d5f31)]:\n  - effect@2.4.1\n  - @effect/schema@0.63.2\n\n## 0.46.2\n\n### Patch Changes\n\n- Updated dependencies [[`5d30853`](https://github.com/Effect-TS/effect/commit/5d308534cac6f187227185393c0bac9eb27f90ab), [`6e350ed`](https://github.com/Effect-TS/effect/commit/6e350ed611feb0341e00aafd3c3905cd5ba53f07)]:\n  - @effect/schema@0.63.1\n\n## 0.46.1\n\n### Patch Changes\n\n- [#2196](https://github.com/Effect-TS/effect/pull/2196) [`aa6556f`](https://github.com/Effect-TS/effect/commit/aa6556f007117caea84d6965aa30846a11879e9d) Thanks [@tim-smart](https://github.com/tim-smart)! - handle defects in worker runner\n\n## 0.46.0\n\n### Minor Changes\n\n- [#2101](https://github.com/Effect-TS/effect/pull/2101) [`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2) Thanks [@github-actions](https://github.com/apps/github-actions)! - add key type to ReadonlyRecord\n\n### Patch Changes\n\n- Updated dependencies [[`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2), [`489fcf3`](https://github.com/Effect-TS/effect/commit/489fcf363ff2b2a953166b740cb9a62d7fc2a101), [`7d9c3bf`](https://github.com/Effect-TS/effect/commit/7d9c3bff6c18d451e0e4781042945ec5c7be1b9f), [`d8d278b`](https://github.com/Effect-TS/effect/commit/d8d278b2efb2966947029885e01f7b68348a021f), [`14c5711`](https://github.com/Effect-TS/effect/commit/14c57110078f0862b8da5c7a2c5d980f54447484), [`5de7be5`](https://github.com/Effect-TS/effect/commit/5de7be5beca2e963b503e6029dcc3217848187d2), [`54ddbb7`](https://github.com/Effect-TS/effect/commit/54ddbb720aeeb657537b01ae221cdcd5e919c1a6), [`b9cb3a9`](https://github.com/Effect-TS/effect/commit/b9cb3a9c9bfdd75536bd70b4e8b557c12d4923ff), [`585fcce`](https://github.com/Effect-TS/effect/commit/585fcce162d0f07a48d7cd984a9b722966fbebbe), [`93b412d`](https://github.com/Effect-TS/effect/commit/93b412d4a9ed762dc9fa5807e51fad0fc78a614a), [`55b26a6`](https://github.com/Effect-TS/effect/commit/55b26a6342b4826f1116e7a1eb660118c274458e), [`136ef40`](https://github.com/Effect-TS/effect/commit/136ef40fe4a394abfa5c6a7ec103eea57251423e), [`a025b12`](https://github.com/Effect-TS/effect/commit/a025b121235ba01cfce8d62a775491880c575561), [`2097739`](https://github.com/Effect-TS/effect/commit/20977393d2383bff709304e81ec7d51cafd57108), [`f24ac9f`](https://github.com/Effect-TS/effect/commit/f24ac9f0c2c520add58f09fbdcec5defda03bd52)]:\n  - effect@2.4.0\n  - @effect/schema@0.63.0\n\n## 0.45.6\n\n### Patch Changes\n\n- [#2187](https://github.com/Effect-TS/effect/pull/2187) [`e6d36c0`](https://github.com/Effect-TS/effect/commit/e6d36c0813d836f17eabb6a9c7849baffca12dbf) Thanks [@tim-smart](https://github.com/tim-smart)! - update development dependencies\n\n- Updated dependencies [[`5ad2eec`](https://github.com/Effect-TS/effect/commit/5ad2eece0280b6db6a749d25cac1dcf6d33659a9), [`e6d36c0`](https://github.com/Effect-TS/effect/commit/e6d36c0813d836f17eabb6a9c7849baffca12dbf)]:\n  - effect@2.3.8\n  - @effect/schema@0.62.9\n\n## 0.45.5\n\n### Patch Changes\n\n- [#2177](https://github.com/Effect-TS/effect/pull/2177) [`6daf084`](https://github.com/Effect-TS/effect/commit/6daf0845de008772011db8d7c75b7c37a6b4d334) Thanks [@tim-smart](https://github.com/tim-smart)! - support Arrays in platform Template module\n\n## 0.45.4\n\n### Patch Changes\n\n- [#2174](https://github.com/Effect-TS/effect/pull/2174) [`abcb7d9`](https://github.com/Effect-TS/effect/commit/abcb7d983a4a85b43b7175e952f5b331b9019aea) Thanks [@tim-smart](https://github.com/tim-smart)! - add ServerResponse.html/htmlStream api\n\n  It uses the Template module to create html responses\n\n  Example:\n\n  ```ts\n  import { Effect } from \"effect\"\n  import * as Http from \"@effect/platform/HttpServer\"\n\n  Http.response.html`<html>${Effect.succeed(123)}</html>`\n  ```\n\n- [#2174](https://github.com/Effect-TS/effect/pull/2174) [`abcb7d9`](https://github.com/Effect-TS/effect/commit/abcb7d983a4a85b43b7175e952f5b331b9019aea) Thanks [@tim-smart](https://github.com/tim-smart)! - add Template module to platform\n\n  The Template module can be used to create effectful text templates.\n\n  Example:\n\n  ```ts\n  import { Effect } from \"effect\"\n  import { Template } from \"@effect/platform\"\n\n  const t = Template.make`<html>${Effect.succeed(123)}</html>`\n\n  Effect.runSync(t) // returns \"<html>123</html>\"\n  ```\n\n- Updated dependencies [[`bc8404d`](https://github.com/Effect-TS/effect/commit/bc8404d54fd42072d200c0399cb39672837afa9f), [`2c5cbcd`](https://github.com/Effect-TS/effect/commit/2c5cbcd1161b4f40dab184999291e817314107de), [`6565916`](https://github.com/Effect-TS/effect/commit/6565916ef254bf910e47d25fd0ef55e7cb420241)]:\n  - effect@2.3.7\n  - @effect/schema@0.62.8\n\n## 0.45.3\n\n### Patch Changes\n\n- [#2152](https://github.com/Effect-TS/effect/pull/2152) [`09532a8`](https://github.com/Effect-TS/effect/commit/09532a86b7d0cc23557c89158f0342753dfce4b0) Thanks [@tim-smart](https://github.com/tim-smart)! - fix incorrect removal of scope in Client.schemaFunction\n\n## 0.45.2\n\n### Patch Changes\n\n- [#2122](https://github.com/Effect-TS/effect/pull/2122) [`44c3b43`](https://github.com/Effect-TS/effect/commit/44c3b43653e64d7e425d39815d8ff405acec9b99) Thanks [@thewilkybarkid](https://github.com/thewilkybarkid)! - Add a way to redact HTTP headers\n\n- Updated dependencies [[`b1163b2`](https://github.com/Effect-TS/effect/commit/b1163b2bd67b65bafbbb39fc4c67576e5cbaf444), [`b46b869`](https://github.com/Effect-TS/effect/commit/b46b869e59a6da5aa235a9fcc25e1e0d24e9e8f8), [`dbff62c`](https://github.com/Effect-TS/effect/commit/dbff62c3026054350a671f6210058ec5844c285e), [`de1b226`](https://github.com/Effect-TS/effect/commit/de1b226282b5ab6c2809dd93f3bdb066f24a1333), [`a663390`](https://github.com/Effect-TS/effect/commit/a66339090ae7b960f8a8b90a0dcdc505de5aaf3e), [`ff88f80`](https://github.com/Effect-TS/effect/commit/ff88f808c4ed9947a148045849e7410b00acad0a), [`11be07b`](https://github.com/Effect-TS/effect/commit/11be07bf65d82cfdf994cdb9d8ca937f995cb4f0), [`c568645`](https://github.com/Effect-TS/effect/commit/c5686451c87d26382135a1c63b00ef171bb24f62), [`88835e5`](https://github.com/Effect-TS/effect/commit/88835e575a0bfbeff9a3696a332f32192c940e12), [`e572b07`](https://github.com/Effect-TS/effect/commit/e572b076e9b4369d9cc8e55414006eef376c93d9), [`e787a57`](https://github.com/Effect-TS/effect/commit/e787a5772e30d8b840cb98b49d36996e7d659a6c), [`b415577`](https://github.com/Effect-TS/effect/commit/b415577f6c576073733929c858e5aac27b6d5880), [`ff8046f`](https://github.com/Effect-TS/effect/commit/ff8046f57dfd073eba60ce6d3144ab060fbf93ce)]:\n  - effect@2.3.6\n  - @effect/schema@0.62.7\n\n## 0.45.1\n\n### Patch Changes\n\n- [#2133](https://github.com/Effect-TS/effect/pull/2133) [`65895ab`](https://github.com/Effect-TS/effect/commit/65895ab982e0917ac92f0827e387e7cf61be1e69) Thanks [@tim-smart](https://github.com/tim-smart)! - use Schema.TaggedError for worker errors\n\n## 0.45.0\n\n### Minor Changes\n\n- [#2119](https://github.com/Effect-TS/effect/pull/2119) [`2b62548`](https://github.com/Effect-TS/effect/commit/2b6254845882f399636d24223c483e5489e3cff4) Thanks [@tim-smart](https://github.com/tim-smart)! - add Scope to Http client\n\n  This change adds a scope to the default http client, ensuring connections are\n  cleaned up if you abort the request at any point.\n\n  Some response helpers have been added to reduce the noise.\n\n  ```ts\n  import * as Http from \"@effect/platform/HttpClient\"\n  import { Effect } from \"effect\"\n\n  // instead of\n  Http.request.get(\"/\").pipe(\n    Http.client.fetchOk(),\n    Effect.flatMap((_) => _.json),\n    Effect.scoped\n  )\n\n  // you can do\n  Http.request.get(\"/\").pipe(Http.client.fetchOk(), Http.response.json)\n\n  // other helpers include\n  Http.response.text\n  Http.response.stream\n  Http.response.arrayBuffer\n  Http.response.urlParamsBody\n  Http.response.formData\n  Http.response.schema * Effect\n  ```\n\n## 0.44.7\n\n### Patch Changes\n\n- Updated dependencies [[`aef2b8b`](https://github.com/Effect-TS/effect/commit/aef2b8bb636ada07224dc9cf491bebe622c1aeda), [`b881365`](https://github.com/Effect-TS/effect/commit/b8813650355322ea2fc1fbaa4f846bd87a7a05f3), [`7eecb1c`](https://github.com/Effect-TS/effect/commit/7eecb1c6cebe36550df3cca85a46867adbcaa2ca)]:\n  - @effect/schema@0.62.6\n  - effect@2.3.5\n\n## 0.44.6\n\n### Patch Changes\n\n- Updated dependencies [[`17bda66`](https://github.com/Effect-TS/effect/commit/17bda66431c999a546920c10adb205e6c8bea7d1)]:\n  - effect@2.3.4\n  - @effect/schema@0.62.5\n\n## 0.44.5\n\n### Patch Changes\n\n- Updated dependencies [[`1c6d18b`](https://github.com/Effect-TS/effect/commit/1c6d18b422b0bd800f2ed036dba9cb78db296c03), [`13d3266`](https://github.com/Effect-TS/effect/commit/13d3266f331f7aa49b55dd244d4e749a82255274), [`a344b42`](https://github.com/Effect-TS/effect/commit/a344b420862f71532a28c72f00b7ba54776d744d)]:\n  - @effect/schema@0.62.4\n\n## 0.44.4\n\n### Patch Changes\n\n- Updated dependencies [[`efd41d8`](https://github.com/Effect-TS/effect/commit/efd41d8131c3d90867608969ef7c4eef490eb5e6), [`0f83515`](https://github.com/Effect-TS/effect/commit/0f83515a9c01d13c7c15a3f026e02d22c3c6bb7f), [`0f83515`](https://github.com/Effect-TS/effect/commit/0f83515a9c01d13c7c15a3f026e02d22c3c6bb7f)]:\n  - effect@2.3.3\n  - @effect/schema@0.62.3\n\n## 0.44.3\n\n### Patch Changes\n\n- Updated dependencies [[`6654f5f`](https://github.com/Effect-TS/effect/commit/6654f5f0f6b9d97165ede5e04ca16776e2599328), [`2eb11b4`](https://github.com/Effect-TS/effect/commit/2eb11b47752cedf233ef4c4395d9c4efc9b9e180), [`56c09bd`](https://github.com/Effect-TS/effect/commit/56c09bd369279a6a7785209d172739935818cba6), [`71aa5b1`](https://github.com/Effect-TS/effect/commit/71aa5b1c180dcb8b53aefe232d12a97bd06b5447), [`1700af8`](https://github.com/Effect-TS/effect/commit/1700af8af1131602887da721914c8562b6342393)]:\n  - effect@2.3.2\n  - @effect/schema@0.62.2\n\n## 0.44.2\n\n### Patch Changes\n\n- [#2091](https://github.com/Effect-TS/effect/pull/2091) [`29739dd`](https://github.com/Effect-TS/effect/commit/29739dde8e6232824d49c4c7f8856de245249c5c) Thanks [@tim-smart](https://github.com/tim-smart)! - improve type extraction for Router.fromIterable\n\n## 0.44.1\n\n### Patch Changes\n\n- Updated dependencies [[`b5a8215`](https://github.com/Effect-TS/effect/commit/b5a8215ee2a97a8865d69ee55ce1b9835948c922)]:\n  - effect@2.3.1\n  - @effect/schema@0.62.1\n\n## 0.44.0\n\n### Minor Changes\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c) Thanks [@github-actions](https://github.com/apps/github-actions)! - With this change we now require a string key to be provided for all tags and renames the dear old `Tag` to `GenericTag`, so when previously you could do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  interface Service {\n    readonly _: unique symbol\n  }\n  const Service = Context.Tag<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >()\n  ```\n\n  you are now mandated to do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  interface Service {\n    readonly _: unique symbol\n  }\n  const Service = Context.GenericTag<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >(\"Service\")\n  ```\n\n  This makes by default all tags globals and ensures better debuggaility when unexpected errors arise.\n\n  Furthermore we introduce a new way of constructing tags that should be considered the new default:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n  class Service extends Context.Tag(\"Service\")<\n    Service,\n    {\n      number: Effect.Effect<never, never, number>\n    }\n  >() {}\n\n  const program = Effect.flatMap(Service, ({ number }) => number).pipe(\n    Effect.flatMap((_) => Effect.log(`number: ${_}`))\n  )\n  ```\n\n  this will use \"Service\" as the key and will create automatically an opaque identifier (the class) to be used at the type level, it does something similar to the above in a single shot.\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`1a77f72`](https://github.com/Effect-TS/effect/commit/1a77f72cdaf43d6cdc91b6060f82832edcdbbcb3) Thanks [@github-actions](https://github.com/apps/github-actions)! - change `Effect` type parameters order from `Effect<R, E, A>` to `Effect<A, E = never, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`af47aa3`](https://github.com/Effect-TS/effect/commit/af47aa37196ad542c9c23a4896d8ef98147e1205) Thanks [@github-actions](https://github.com/apps/github-actions)! - move where platform worker spawn function is provided\n\n  With this change, the point in which you provide the spawn function moves closer\n  to the edge, where you provide platform specific implementation.\n\n  This seperates even more platform concerns from your business logic. Example:\n\n  ```ts\n  import { Worker } from \"@effect/platform\"\n  import { BrowserWorker } from \"@effect/platform-browser\"\n  import { Effect } from \"effect\"\n\n  Worker.makePool({ ... }).pipe(\n    Effect.provide(BrowserWorker.layer(() => new globalThis.Worker(...)))\n  )\n  ```\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`a34dbdc`](https://github.com/Effect-TS/effect/commit/a34dbdc1552c73c1b612676f262a0c735ce444a7) Thanks [@github-actions](https://github.com/apps/github-actions)! - - Schema: change type parameters order from `Schema<R, I, A>` to `Schema<A, I = A, R = never>`\n  - Serializable: change type parameters order from `Serializable<R, I, A>` to `Serializable<A, I, R>`\n  - Class: change type parameters order from `Class<R, I, A, C, Self, Inherited>` to `Class<A, I, R, C, Self, Inherited>`\n  - PropertySignature: change type parameters order from `PropertySignature<R, From, FromIsOptional, To, ToIsOptional>` to `PropertySignature<From, FromIsOptional, To, ToIsOptional, R = never>`\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`b1e2086`](https://github.com/Effect-TS/effect/commit/b1e2086ea8bf410e4ad75d71c0760825924e8f9f) Thanks [@github-actions](https://github.com/apps/github-actions)! - remove re-exports from platform packages\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`02c3461`](https://github.com/Effect-TS/effect/commit/02c34615d02f91269ea04036d0306fccf4e39e18) Thanks [@github-actions](https://github.com/apps/github-actions)! - With this change we remove the `Data.Data` type and we make `Equal.Equal` & `Hash.Hash` implicit traits.\n\n  The main reason is that `Data.Data<A>` was structurally equivalent to `A & Equal.Equal` but extending `Equal.Equal` doesn't mean that the equality is implemented by-value, so the type was simply adding noise without gaining any level of safety.\n\n  The module `Data` remains unchanged at the value level, all the functions previously available are supposed to work in exactly the same manner.\n\n  At the type level instead the functions return `Readonly` variants, so for example we have:\n\n  ```ts\n  import { Data } from \"effect\"\n\n  const obj = Data.struct({\n    a: 0,\n    b: 1\n  })\n  ```\n\n  will have the `obj` typed as:\n\n  ```ts\n  declare const obj: {\n    readonly a: number\n    readonly b: number\n  }\n  ```\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`6361ee2`](https://github.com/Effect-TS/effect/commit/6361ee2e83bdfead24045c3d058a7298efc18113) Thanks [@github-actions](https://github.com/apps/github-actions)! - fix for encoding of Transferable schemas\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`86f665d`](https://github.com/Effect-TS/effect/commit/86f665d7bd25ba0a3f046a2384798378310dcf0c) Thanks [@github-actions](https://github.com/apps/github-actions)! - use Context for collecting tranferables\n\n  This changes the platform Transferable module to use Effect context to collect\n  tranferables when using schemas with workers etc.\n\n  You can now use a tranferable data type anywhere in your schema without having\n  to wrap the outermost schema:\n\n  ```ts\n  import { Transferable } from \"@effect/platform\"\n  import { Schema } from \"@effect/schema\"\n\n  const structWithTransferable = Schema.struct({\n    data: Transferable.Uint8Array\n  })\n  ```\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c) Thanks [@github-actions](https://github.com/apps/github-actions)! - This change enables `Effect.serviceConstants` and `Effect.serviceMembers` to access any constant in the service, not only the effects, namely it is now possible to do:\n\n  ```ts\n  import { Effect, Context } from \"effect\"\n\n  class NumberRepo extends Context.TagClass(\"NumberRepo\")<\n    NumberRepo,\n    {\n      readonly numbers: Array<number>\n    }\n  >() {\n    static numbers = Effect.serviceConstants(NumberRepo).numbers\n  }\n  ```\n\n### Patch Changes\n\n- [#2006](https://github.com/Effect-TS/effect/pull/2006) [`b1e2086`](https://github.com/Effect-TS/effect/commit/b1e2086ea8bf410e4ad75d71c0760825924e8f9f) Thanks [@github-actions](https://github.com/apps/github-actions)! - add server address apis\n\n- Updated dependencies [[`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`4cd6e14`](https://github.com/Effect-TS/effect/commit/4cd6e144945b6c398f5f5abe3471ff7fb3372bfd), [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`c77f635`](https://github.com/Effect-TS/effect/commit/c77f635f8a26ca6d83cb569d911f8eee79033fd9), [`e343a74`](https://github.com/Effect-TS/effect/commit/e343a74843dd9edf879417fa94cb51de7ed5b402), [`acf1894`](https://github.com/Effect-TS/effect/commit/acf1894f45945dbe5c39451e36aabb4b5092f257), [`9dc04c8`](https://github.com/Effect-TS/effect/commit/9dc04c88a2ea9c68122cb2632a76f0f4be40329a), [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c), [`1a77f72`](https://github.com/Effect-TS/effect/commit/1a77f72cdaf43d6cdc91b6060f82832edcdbbcb3), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`c986f0e`](https://github.com/Effect-TS/effect/commit/c986f0e0ce4d22ba08177ed351152718479ab63c), [`96bcee2`](https://github.com/Effect-TS/effect/commit/96bcee21021aecd8ffd86440a2c9be353c4668e3), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`70dde23`](https://github.com/Effect-TS/effect/commit/70dde238f81125e353fd7bde5fc24ecd8969bf97), [`a34dbdc`](https://github.com/Effect-TS/effect/commit/a34dbdc1552c73c1b612676f262a0c735ce444a7), [`d3f9f4d`](https://github.com/Effect-TS/effect/commit/d3f9f4d4032b1131c62f4ddb21a4583e4e8d7c18), [`81b7425`](https://github.com/Effect-TS/effect/commit/81b7425320cbbe2a6cf547a3e3ab3549cdba14cf), [`02c3461`](https://github.com/Effect-TS/effect/commit/02c34615d02f91269ea04036d0306fccf4e39e18), [`0e56e99`](https://github.com/Effect-TS/effect/commit/0e56e998ab9815c4d096c239a553cb86a0f99af9), [`8b0ded9`](https://github.com/Effect-TS/effect/commit/8b0ded9f10ba0d96fcb9af24eff2dbd9341f85e3), [`8dd83e8`](https://github.com/Effect-TS/effect/commit/8dd83e854bfcaa6dab876994c5f813dcfb486c28), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e), [`d75f6fe`](https://github.com/Effect-TS/effect/commit/d75f6fe6499deb0a5ee9ec94af3b5fd4eb03a2d0), [`7356e5c`](https://github.com/Effect-TS/effect/commit/7356e5cc16e9d70f18c02dee1dcb4ad539fd130a), [`3077cde`](https://github.com/Effect-TS/effect/commit/3077cde08a60246821a940964a84dd7f7c8b9f54), [`be19ce0`](https://github.com/Effect-TS/effect/commit/be19ce0b8bdf1fac80bb8d7e0b06a86986b47409), [`4a5d01a`](https://github.com/Effect-TS/effect/commit/4a5d01a409e9b6dd53893e65f8e5c9247f568021), [`78f47ab`](https://github.com/Effect-TS/effect/commit/78f47abfe3cb0a8bbde818b1c5fc603270538b47), [`52e5d20`](https://github.com/Effect-TS/effect/commit/52e5d2077582bf51f25861c7139fc920c2c24166), [`c6137ec`](https://github.com/Effect-TS/effect/commit/c6137ec62c6b5542d5062ae1a3c936cb915dee22), [`f5ae081`](https://github.com/Effect-TS/effect/commit/f5ae08195e68e76faeac258c565d79da4e01e7d6), [`4a5d01a`](https://github.com/Effect-TS/effect/commit/4a5d01a409e9b6dd53893e65f8e5c9247f568021), [`60686f5`](https://github.com/Effect-TS/effect/commit/60686f5c38bef1b93a3a0dda9b6596d46aceab03), [`9a2d1c1`](https://github.com/Effect-TS/effect/commit/9a2d1c1468ea0789b34767ad683da074f061ea9c), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e), [`56b8691`](https://github.com/Effect-TS/effect/commit/56b86916bf3da18002f3655d859dbc487eb5a6de), [`8ee2931`](https://github.com/Effect-TS/effect/commit/8ee293159b4f7cb7af8558287a0a047f3a69743d), [`6727474`](https://github.com/Effect-TS/effect/commit/672747497490a30d36dd49c06db19aabf09dc7f0), [`5127afe`](https://github.com/Effect-TS/effect/commit/5127afec1c519e0a3d7460844a9101a96272f29e)]:\n  - effect@2.3.0\n  - @effect/schema@0.62.0\n\n## 0.43.11\n\n### Patch Changes\n\n- Updated dependencies [[`3ddfdbf`](https://github.com/Effect-TS/effect/commit/3ddfdbf914edea536aef207cec6695f33496258c), [`3ddfdbf`](https://github.com/Effect-TS/effect/commit/3ddfdbf914edea536aef207cec6695f33496258c)]:\n  - effect@2.2.5\n  - @effect/schema@0.61.7\n\n## 0.43.10\n\n### Patch Changes\n\n- [#2057](https://github.com/Effect-TS/effect/pull/2057) [`6928a2b`](https://github.com/Effect-TS/effect/commit/6928a2b0bae86a4bdfbece0aa32924207c2d5a70) Thanks [@joepjoosten](https://github.com/joepjoosten)! - Fix for possible stack overflow errors when using Array.push with spread operator arguments\n\n- Updated dependencies [[`d0b911c`](https://github.com/Effect-TS/effect/commit/d0b911c75f284c7aa87f25aa96926e6bde7690d0), [`330e1a4`](https://github.com/Effect-TS/effect/commit/330e1a4e2c1fc0af6c80c80c81dd38c3e50fab78), [`6928a2b`](https://github.com/Effect-TS/effect/commit/6928a2b0bae86a4bdfbece0aa32924207c2d5a70), [`296bc1c`](https://github.com/Effect-TS/effect/commit/296bc1c9d24986d299d2669115d584cb27b73c60)]:\n  - effect@2.2.4\n  - @effect/schema@0.61.6\n\n## 0.43.9\n\n### Patch Changes\n\n- [#2039](https://github.com/Effect-TS/effect/pull/2039) [`1b841a9`](https://github.com/Effect-TS/effect/commit/1b841a91fed86825cd2867cf1e68e41d8ff26b4e) Thanks [@tim-smart](https://github.com/tim-smart)! - fix ClientRequest.make signature (generic was unused)\n\n## 0.43.8\n\n### Patch Changes\n\n- [#2037](https://github.com/Effect-TS/effect/pull/2037) [`32bf796`](https://github.com/Effect-TS/effect/commit/32bf796c3e5db1b2b68e8b1b20db664295991643) Thanks [@tim-smart](https://github.com/tim-smart)! - remove overloads from ClientRequest.make\n\n  This makes it easier to programatically create client request instances:\n\n  ```\n  import * as Http from \"@effect/platform/HttpClient\"\n\n  declare const method: \"GET\" | \"POST\"\n  declare const url: string\n\n  Http.request.make(method)(url)\n  ```\n\n## 0.43.7\n\n### Patch Changes\n\n- [#2020](https://github.com/Effect-TS/effect/pull/2020) [`cde08f3`](https://github.com/Effect-TS/effect/commit/cde08f354ed2ff2921d1d98bd539c7d65a2ddd73) Thanks [@tim-smart](https://github.com/tim-smart)! - use Proxy for platform schema Transferable\n\n## 0.43.6\n\n### Patch Changes\n\n- [#2016](https://github.com/Effect-TS/effect/pull/2016) [`c96bb17`](https://github.com/Effect-TS/effect/commit/c96bb17043e2cec1eaeb319614a4c2904d876beb) Thanks [@thewilkybarkid](https://github.com/thewilkybarkid)! - Support URL objects in client requests\n\n## 0.43.5\n\n### Patch Changes\n\n- Updated dependencies [[`f1ff44b`](https://github.com/Effect-TS/effect/commit/f1ff44b58cdb1886b38681e8fedc309eb9ac6853), [`13785cf`](https://github.com/Effect-TS/effect/commit/13785cf4a5082d8d9cf8d7c991141dee0d2b4d31)]:\n  - @effect/schema@0.61.5\n\n## 0.43.4\n\n### Patch Changes\n\n- [#1999](https://github.com/Effect-TS/effect/pull/1999) [`78f5921`](https://github.com/Effect-TS/effect/commit/78f59211502ded6fcbe15a49d6fde941cccc9d52) Thanks [@tim-smart](https://github.com/tim-smart)! - ensure forked fibers are interruptible\n\n- Updated dependencies [[`22794e0`](https://github.com/Effect-TS/effect/commit/22794e0ba00e40281f30a22fa84412003c24877d), [`f73e6c0`](https://github.com/Effect-TS/effect/commit/f73e6c033fb0729a9cfa5eb4bc39f79d3126e247), [`6bf02c7`](https://github.com/Effect-TS/effect/commit/6bf02c70fe10a04d1b34d6666f95416e42a6225a)]:\n  - effect@2.2.3\n  - @effect/schema@0.61.4\n\n## 0.43.3\n\n### Patch Changes\n\n- Updated dependencies [[`9863e2f`](https://github.com/Effect-TS/effect/commit/9863e2fb3561dc019965aeccd6584a418fc8b401)]:\n  - @effect/schema@0.61.3\n\n## 0.43.2\n\n### Patch Changes\n\n- Updated dependencies [[`64f710a`](https://github.com/Effect-TS/effect/commit/64f710aa49dec6ffcd33ee23438d0774f5489733)]:\n  - @effect/schema@0.61.2\n\n## 0.43.1\n\n### Patch Changes\n\n- Updated dependencies [[`c7550f9`](https://github.com/Effect-TS/effect/commit/c7550f96e1006eee832ce5025bf0c197a65935ea), [`8d1f6e4`](https://github.com/Effect-TS/effect/commit/8d1f6e4bb13e221804fb1762ef19e02bcefc8f61), [`d404561`](https://github.com/Effect-TS/effect/commit/d404561e47ec2fa5f68709a308ee5d2ee959141d), [`7b84a3c`](https://github.com/Effect-TS/effect/commit/7b84a3c7e4b9c8dc02294b0e3cc3ae3becea977b), [`1a84dee`](https://github.com/Effect-TS/effect/commit/1a84dee0e9ddbfaf2610e4d7c00c7020c427171a), [`ac30bf4`](https://github.com/Effect-TS/effect/commit/ac30bf4cd53de0663784f65ae6bee8279333df97)]:\n  - @effect/schema@0.61.1\n  - effect@2.2.2\n\n## 0.43.0\n\n### Minor Changes\n\n- [#1922](https://github.com/Effect-TS/effect/pull/1922) [`62b40e8`](https://github.com/Effect-TS/effect/commit/62b40e8479371d6663c0255aaca56a1ae0d59764) Thanks [@gcanti](https://github.com/gcanti)! - add context tracking to Schema, closes #1873\n\n### Patch Changes\n\n- Updated dependencies [[`84da31f`](https://github.com/Effect-TS/effect/commit/84da31f0643e8651b9d311b30526b1e4edfbdfb8), [`62b40e8`](https://github.com/Effect-TS/effect/commit/62b40e8479371d6663c0255aaca56a1ae0d59764), [`645bea2`](https://github.com/Effect-TS/effect/commit/645bea2551129f94a5b0e38347e28067dee531bb), [`62b40e8`](https://github.com/Effect-TS/effect/commit/62b40e8479371d6663c0255aaca56a1ae0d59764)]:\n  - effect@2.2.1\n  - @effect/schema@0.61.0\n\n## 0.42.7\n\n### Patch Changes\n\n- [#1959](https://github.com/Effect-TS/effect/pull/1959) [`fe05ad7`](https://github.com/Effect-TS/effect/commit/fe05ad7bcb3b88d47800ab69ebf53641023676f1) Thanks [@tim-smart](https://github.com/tim-smart)! - fix ClientRequest stream bodies\n\n- Updated dependencies [[`202befc`](https://github.com/Effect-TS/effect/commit/202befc2ecbeb117c4fa85ef9b12a3d3a48273d2), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`ee4ff8a`](https://github.com/Effect-TS/effect/commit/ee4ff8a943141fcf2877af92c5877ee87a989fb9), [`10df798`](https://github.com/Effect-TS/effect/commit/10df798639e556f9d88265ef7fc3cf8a3bbe3874)]:\n  - effect@2.2.0\n  - @effect/schema@0.60.7\n\n## 0.42.6\n\n### Patch Changes\n\n- Updated dependencies [[`21b9edd`](https://github.com/Effect-TS/effect/commit/21b9edde464f7c5624ef54ad1b5e264204a37625)]:\n  - effect@2.1.2\n  - @effect/schema@0.60.6\n\n## 0.42.5\n\n### Patch Changes\n\n- Updated dependencies [[`3bf67cf`](https://github.com/Effect-TS/effect/commit/3bf67cf64ff27ffaa811b07751875cb161ac3385)]:\n  - @effect/schema@0.60.5\n\n## 0.42.4\n\n### Patch Changes\n\n- Updated dependencies [[`0d1af1e`](https://github.com/Effect-TS/effect/commit/0d1af1e38c11b94e152beaccd0ff7569a1b3f5b7), [`0d1af1e`](https://github.com/Effect-TS/effect/commit/0d1af1e38c11b94e152beaccd0ff7569a1b3f5b7), [`a222524`](https://github.com/Effect-TS/effect/commit/a2225247e9de2e013d287320790fde88c081dbbd)]:\n  - @effect/schema@0.60.4\n  - effect@2.1.1\n\n## 0.42.3\n\n### Patch Changes\n\n- Updated dependencies [[`d543221`](https://github.com/Effect-TS/effect/commit/d5432213e91ab620aa66e0fd92a6593134d18940), [`2530d47`](https://github.com/Effect-TS/effect/commit/2530d470b0ad5df7e636921eedfb1cbe42821f94), [`f493929`](https://github.com/Effect-TS/effect/commit/f493929ab88d2ea137ca5fbff70bdc6c9d804d80), [`5911fa9`](https://github.com/Effect-TS/effect/commit/5911fa9c9440dd3bc1ee38542bcd15f8c75a4637)]:\n  - @effect/schema@0.60.3\n\n## 0.42.2\n\n### Patch Changes\n\n- [#1919](https://github.com/Effect-TS/effect/pull/1919) [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02) Thanks [@github-actions](https://github.com/apps/github-actions)! - Improve Effect.retry options\n\n- Updated dependencies [[`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02), [`05c44b3`](https://github.com/Effect-TS/effect/commit/05c44b30662554dde50b70bad79f13ae895fda02)]:\n  - effect@2.1.0\n  - @effect/schema@0.60.2\n\n## 0.42.1\n\n### Patch Changes\n\n- Updated dependencies [[`f7f19f6`](https://github.com/Effect-TS/effect/commit/f7f19f66a5fa349baa2412c1f9f15111c437df09)]:\n  - effect@2.0.5\n  - @effect/schema@0.60.1\n\n## 0.42.0\n\n### Minor Changes\n\n- [#1895](https://github.com/Effect-TS/effect/pull/1895) [`48a3d40`](https://github.com/Effect-TS/effect/commit/48a3d40aed0f923f567b8911dade732ff472d981) Thanks [@tim-smart](https://github.com/tim-smart)! - make worker initial message type safe\n\n### Patch Changes\n\n- Updated dependencies [[`ec2bdfa`](https://github.com/Effect-TS/effect/commit/ec2bdfae2da717f28147b9d6820d3494cb240945), [`687e02e`](https://github.com/Effect-TS/effect/commit/687e02e7d84dc06957844160761fda90929470ab), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`540b294`](https://github.com/Effect-TS/effect/commit/540b2941dd0a81e9688311583ce7e2e140d6e7a5), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`a3f96d6`](https://github.com/Effect-TS/effect/commit/a3f96d615b8b3e238dbfa01ef713c87e6f4532be), [`0c397e7`](https://github.com/Effect-TS/effect/commit/0c397e762008a0de40c7526c9d99ff2cfe4f7a6a), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`b557a10`](https://github.com/Effect-TS/effect/commit/b557a10b773e321bea77fc4951f0ef171dd193c9), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`8eec87e`](https://github.com/Effect-TS/effect/commit/8eec87e311ce55281a98517e6df0ef103b43e8a8), [`74b9094`](https://github.com/Effect-TS/effect/commit/74b90940e571c73a6b76cafa88ffb8a1c949cb4c), [`337e80f`](https://github.com/Effect-TS/effect/commit/337e80f69bc36966f889c439b819db2f84cae496), [`25adce7`](https://github.com/Effect-TS/effect/commit/25adce7ae76ce834096dca1ed70a60ad1a349217), [`536c1df`](https://github.com/Effect-TS/effect/commit/536c1dfb7833961dfb2fbd6bcd2dbdfa2f208d51)]:\n  - @effect/schema@0.60.0\n  - effect@2.0.4\n\n## 0.41.0\n\n### Minor Changes\n\n- [#1885](https://github.com/Effect-TS/effect/pull/1885) [`1d3a06b`](https://github.com/Effect-TS/effect/commit/1d3a06bb58ad1ac123ae8f9d42b4345f9c9c53c0) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - lift worker shutdown to /platform implementation\n\n### Patch Changes\n\n- [#1885](https://github.com/Effect-TS/effect/pull/1885) [`1d3a06b`](https://github.com/Effect-TS/effect/commit/1d3a06bb58ad1ac123ae8f9d42b4345f9c9c53c0) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Avoid killing all fibers on interrupt\n\n- Updated dependencies [[`5b46e99`](https://github.com/Effect-TS/effect/commit/5b46e996d30e2497eb23095e2c21eee04438edf5), [`87f7ef2`](https://github.com/Effect-TS/effect/commit/87f7ef28a3c27e2e4f2fcfa465f85bb2a45a3d6b), [`210d27e`](https://github.com/Effect-TS/effect/commit/210d27e999e066ea9b907301150c65f9ff080b39), [`1d3a06b`](https://github.com/Effect-TS/effect/commit/1d3a06bb58ad1ac123ae8f9d42b4345f9c9c53c0)]:\n  - @effect/schema@0.59.1\n  - effect@2.0.3\n\n## 0.40.4\n\n### Patch Changes\n\n- Updated dependencies [[`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f), [`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f), [`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f), [`c4b84f7`](https://github.com/Effect-TS/effect/commit/c4b84f724ae809f3450d71c3ea5d629205fc479f)]:\n  - @effect/schema@0.59.0\n\n## 0.40.3\n\n### Patch Changes\n\n- [#1879](https://github.com/Effect-TS/effect/pull/1879) [`92c0322`](https://github.com/Effect-TS/effect/commit/92c0322a58bf7e5b8dbb602186030839e89df5af) Thanks [@tim-smart](https://github.com/tim-smart)! - add http Multiplex module\n\n- Updated dependencies [[`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`a904a73`](https://github.com/Effect-TS/effect/commit/a904a739459bfd0fa7844b00b902d2fa984fb014), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c), [`7b2f874`](https://github.com/Effect-TS/effect/commit/7b2f8743d96753c3e24ac4cc6715a4a7f4a2ca0c)]:\n  - @effect/schema@0.58.0\n\n## 0.40.2\n\n### Patch Changes\n\n- [#1870](https://github.com/Effect-TS/effect/pull/1870) [`4c90c54`](https://github.com/Effect-TS/effect/commit/4c90c54d87c91f75f3ad114926cdf3b0c25df091) Thanks [@tim-smart](https://github.com/tim-smart)! - support context propogation in platform workers\n\n- [#1869](https://github.com/Effect-TS/effect/pull/1869) [`d3d3bda`](https://github.com/Effect-TS/effect/commit/d3d3bda74c794153def9027e0c40896e72cd5d14) Thanks [@tim-smart](https://github.com/tim-smart)! - don't add Transferable to schema types\n\n- Updated dependencies [[`d5a1949`](https://github.com/Effect-TS/effect/commit/d5a19499aac7c1d147674a35ac69992177c7536c)]:\n  - effect@2.0.2\n  - @effect/schema@0.57.2\n\n## 0.40.1\n\n### Patch Changes\n\n- Updated dependencies [[`16bd87d`](https://github.com/Effect-TS/effect/commit/16bd87d32611b966dc42ea4fc979764f97a49071)]:\n  - effect@2.0.1\n  - @effect/schema@0.57.1\n\n## 0.40.0\n\n### Minor Changes\n\n- [`d0471ca`](https://github.com/Effect-TS/effect/commit/d0471ca7b544746674b9e1750202da72b0a21233) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Switch to monorepo structure\n\n- [#1846](https://github.com/Effect-TS/effect/pull/1846) [`693b8f3`](https://github.com/Effect-TS/effect/commit/693b8f3a3dfd43ae61f0d9292cdf356be7329f2f) Thanks [@fubhy](https://github.com/fubhy)! - Enabled `exactOptionalPropertyTypes` throughout\n\n### Patch Changes\n\n- [`d987daa`](https://github.com/Effect-TS/effect/commit/d987daafaddd43b6ade74916a08236c19ea0a9fa) Thanks [@mikearnaldi](https://github.com/mikearnaldi)! - Switch effect dependency to caret\n\n- [#1848](https://github.com/Effect-TS/effect/pull/1848) [`04fb8b4`](https://github.com/Effect-TS/effect/commit/04fb8b428b19bba85a2c79910c5e363340d074e7) Thanks [@fubhy](https://github.com/fubhy)! - Avoid default parameter initilization\n\n- [#1847](https://github.com/Effect-TS/effect/pull/1847) [`bcf0900`](https://github.com/Effect-TS/effect/commit/bcf0900b58f449262556f80bff21e771a37272aa) Thanks [@fubhy](https://github.com/fubhy)! - Avoid inline creation & spreading of objects and arrays\n\n- [#1799](https://github.com/Effect-TS/effect/pull/1799) [`c0aeb5e`](https://github.com/Effect-TS/effect/commit/c0aeb5e302869bcd7d7627f8cc5b630d07c12d10) Thanks [@tim-smart](https://github.com/tim-smart)! - add Route to RouteContext\n\n- Updated dependencies [[`d987daa`](https://github.com/Effect-TS/effect/commit/d987daafaddd43b6ade74916a08236c19ea0a9fa), [`7b5eaa3`](https://github.com/Effect-TS/effect/commit/7b5eaa3838c79bf4bdccf91b94d61bbc38a2ec95), [`0724211`](https://github.com/Effect-TS/effect/commit/072421149c36010748ff6b6ee19c15c6cffefe09), [`9f2bc5a`](https://github.com/Effect-TS/effect/commit/9f2bc5a19e0b678a0a85e84daac290922b0fd57d), [`04fb8b4`](https://github.com/Effect-TS/effect/commit/04fb8b428b19bba85a2c79910c5e363340d074e7), [`d0471ca`](https://github.com/Effect-TS/effect/commit/d0471ca7b544746674b9e1750202da72b0a21233), [`bcf0900`](https://github.com/Effect-TS/effect/commit/bcf0900b58f449262556f80bff21e771a37272aa), [`6299b84`](https://github.com/Effect-TS/effect/commit/6299b84c11e5d1fe79fa538df8935018c7613747)]:\n  - @effect/schema@0.57.0\n  - effect@2.0.0\n\n## 0.39.0\n\n### Minor Changes\n\n- [#369](https://github.com/Effect-TS/platform/pull/369) [`5d5f62b`](https://github.com/Effect-TS/platform/commit/5d5f62b03ffdbca0a986d968e1dbb45886dfa827) Thanks [@tim-smart](https://github.com/tim-smart)! - rename server FormData module to Multipart\n\n- [#372](https://github.com/Effect-TS/platform/pull/372) [`15784c9`](https://github.com/Effect-TS/platform/commit/15784c920dcae40f328bb45ac850987135207365) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n- [#373](https://github.com/Effect-TS/platform/pull/373) [`b042ba5`](https://github.com/Effect-TS/platform/commit/b042ba5ae78a1eed592e543c233fe3040d6a60da) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n- [#371](https://github.com/Effect-TS/platform/pull/371) [`49fb154`](https://github.com/Effect-TS/platform/commit/49fb15439f18701321db8ded839243b9dd8de71a) Thanks [@tim-smart](https://github.com/tim-smart)! - rename schemaBodyMultipartJson to schemaBodyFormJson & support url forms\n\n## 0.38.0\n\n### Minor Changes\n\n- [#367](https://github.com/Effect-TS/platform/pull/367) [`7d1584b`](https://github.com/Effect-TS/platform/commit/7d1584b23d464651c206201ff304c6eb4bebfc3a) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.37.8\n\n### Patch Changes\n\n- [#363](https://github.com/Effect-TS/platform/pull/363) [`e2c545a`](https://github.com/Effect-TS/platform/commit/e2c545a328c2bccbba661540a8835b10bce4b438) Thanks [@tim-smart](https://github.com/tim-smart)! - fix schemaNoBody type\n\n- [#366](https://github.com/Effect-TS/platform/pull/366) [`1d6bf73`](https://github.com/Effect-TS/platform/commit/1d6bf730dad0a6bbb282f436ec7d5870de76ca3a) Thanks [@tim-smart](https://github.com/tim-smart)! - add Scope to every http request\n\n- [#365](https://github.com/Effect-TS/platform/pull/365) [`3351136`](https://github.com/Effect-TS/platform/commit/335113601c238104eb2e331d26b5e463bde80dff) Thanks [@tim-smart](https://github.com/tim-smart)! - respond with 503 on server induced interrupt\n\n## 0.37.7\n\n### Patch Changes\n\n- [#361](https://github.com/Effect-TS/platform/pull/361) [`df3af6b`](https://github.com/Effect-TS/platform/commit/df3af6be61572bab15004bbca2c5739d8206f3c3) Thanks [@tim-smart](https://github.com/tim-smart)! - fix headers type for schemaJson\n\n## 0.37.6\n\n### Patch Changes\n\n- [#359](https://github.com/Effect-TS/platform/pull/359) [`6dbc587`](https://github.com/Effect-TS/platform/commit/6dbc587868d2703ad9a4c9995cb9dacdfc29c364) Thanks [@tim-smart](https://github.com/tim-smart)! - use branded type for Headers\n\n- [#359](https://github.com/Effect-TS/platform/pull/359) [`6dbc587`](https://github.com/Effect-TS/platform/commit/6dbc587868d2703ad9a4c9995cb9dacdfc29c364) Thanks [@tim-smart](https://github.com/tim-smart)! - change UrlParams to ReadonlyArray\n\n## 0.37.5\n\n### Patch Changes\n\n- [#354](https://github.com/Effect-TS/platform/pull/354) [`190bc84`](https://github.com/Effect-TS/platform/commit/190bc84b137a729a38b6812e220085b3d12cb124) Thanks [@tim-smart](https://github.com/tim-smart)! - add Layer support to SerializedWorker\n\n## 0.37.4\n\n### Patch Changes\n\n- [#352](https://github.com/Effect-TS/platform/pull/352) [`1c02a35`](https://github.com/Effect-TS/platform/commit/1c02a35df2f34601b547e17ddeab98236e10f77d) Thanks [@tim-smart](https://github.com/tim-smart)! - interrupt all fibers on worker interrupt\n\n- [#352](https://github.com/Effect-TS/platform/pull/352) [`1c02a35`](https://github.com/Effect-TS/platform/commit/1c02a35df2f34601b547e17ddeab98236e10f77d) Thanks [@tim-smart](https://github.com/tim-smart)! - interrupt workers on all failures\n\n## 0.37.3\n\n### Patch Changes\n\n- [#350](https://github.com/Effect-TS/platform/pull/350) [`b30e5e3`](https://github.com/Effect-TS/platform/commit/b30e5e3874f22037f92253037fff6952f537ee40) Thanks [@tim-smart](https://github.com/tim-smart)! - add decode option to worker runner\n\n## 0.37.2\n\n### Patch Changes\n\n- [#348](https://github.com/Effect-TS/platform/pull/348) [`28edc60`](https://github.com/Effect-TS/platform/commit/28edc60d2fcd30160529c677a9ffd786775e534b) Thanks [@tim-smart](https://github.com/tim-smart)! - add layer worker runner apis\n\n## 0.37.1\n\n### Patch Changes\n\n- [#344](https://github.com/Effect-TS/platform/pull/344) [`5b7cdbd`](https://github.com/Effect-TS/platform/commit/5b7cdbdf8ded48903a9f39df800fd7a22f73f0f7) Thanks [@tim-smart](https://github.com/tim-smart)! - support error and output transfers in worker runners\n\n- [#344](https://github.com/Effect-TS/platform/pull/344) [`5b7cdbd`](https://github.com/Effect-TS/platform/commit/5b7cdbdf8ded48903a9f39df800fd7a22f73f0f7) Thanks [@tim-smart](https://github.com/tim-smart)! - support initialMessage in workers\n\n- [#344](https://github.com/Effect-TS/platform/pull/344) [`5b7cdbd`](https://github.com/Effect-TS/platform/commit/5b7cdbdf8ded48903a9f39df800fd7a22f73f0f7) Thanks [@tim-smart](https://github.com/tim-smart)! - add Schema transforms to Transferable\n\n- [#344](https://github.com/Effect-TS/platform/pull/344) [`5b7cdbd`](https://github.com/Effect-TS/platform/commit/5b7cdbdf8ded48903a9f39df800fd7a22f73f0f7) Thanks [@tim-smart](https://github.com/tim-smart)! - make worker encoding return Effects\n\n## 0.37.0\n\n### Minor Changes\n\n- [#341](https://github.com/Effect-TS/platform/pull/341) [`649f57f`](https://github.com/Effect-TS/platform/commit/649f57fdf557eed5f8405a4a4553dfc47fd8d4b1) Thanks [@tim-smart](https://github.com/tim-smart)! - use peer deps for /platform-\\*\n\n- [#341](https://github.com/Effect-TS/platform/pull/341) [`649f57f`](https://github.com/Effect-TS/platform/commit/649f57fdf557eed5f8405a4a4553dfc47fd8d4b1) Thanks [@tim-smart](https://github.com/tim-smart)! - replace http router with find-my-way-ts\n\n## 0.36.0\n\n### Minor Changes\n\n- [#338](https://github.com/Effect-TS/platform/pull/338) [`7eaa8e5`](https://github.com/Effect-TS/platform/commit/7eaa8e52b18d408688e7b4909bcf016b0c04e80a) Thanks [@tim-smart](https://github.com/tim-smart)! - change http serve api to return immediately\n\n- [#338](https://github.com/Effect-TS/platform/pull/338) [`7eaa8e5`](https://github.com/Effect-TS/platform/commit/7eaa8e52b18d408688e7b4909bcf016b0c04e80a) Thanks [@tim-smart](https://github.com/tim-smart)! - Http.server.serve now returns a Layer\n\n### Patch Changes\n\n- [#338](https://github.com/Effect-TS/platform/pull/338) [`7eaa8e5`](https://github.com/Effect-TS/platform/commit/7eaa8e52b18d408688e7b4909bcf016b0c04e80a) Thanks [@tim-smart](https://github.com/tim-smart)! - add Http.server.serveEffect\n\n## 0.35.0\n\n### Minor Changes\n\n- [#335](https://github.com/Effect-TS/platform/pull/335) [`4f0166e`](https://github.com/Effect-TS/platform/commit/4f0166ee2241bd9b71739c98d428b5809313e46e) Thanks [@tim-smart](https://github.com/tim-smart)! - remove index module from /platform\n\n### Patch Changes\n\n- [#335](https://github.com/Effect-TS/platform/pull/335) [`4f0166e`](https://github.com/Effect-TS/platform/commit/4f0166ee2241bd9b71739c98d428b5809313e46e) Thanks [@tim-smart](https://github.com/tim-smart)! - add SerializedWorker\n\n## 0.34.0\n\n### Minor Changes\n\n- [#331](https://github.com/Effect-TS/platform/pull/331) [`db1ca18`](https://github.com/Effect-TS/platform/commit/db1ca18725f9dd4be1c36ddc80faa3aa53c10eb7) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.33.1\n\n### Patch Changes\n\n- [#326](https://github.com/Effect-TS/platform/pull/326) [`162aa91`](https://github.com/Effect-TS/platform/commit/162aa915934112983c543a6be2a9d7091b86fac9) Thanks [@tim-smart](https://github.com/tim-smart)! - add Router.schemaSearchParams/schemaPathParams\n\n## 0.33.0\n\n### Minor Changes\n\n- [#321](https://github.com/Effect-TS/platform/pull/321) [`16a5bca`](https://github.com/Effect-TS/platform/commit/16a5bca2bd4aed570ce95233a0e47350010d031f) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n### Patch Changes\n\n- [#319](https://github.com/Effect-TS/platform/pull/319) [`425365e`](https://github.com/Effect-TS/platform/commit/425365ebc40c52a6e2a4bff865c3a982ce74f4ed) Thanks [@IMax153](https://github.com/IMax153)! - add Terminal.readLine to read input line-by-line from the terminal\n\n- [#319](https://github.com/Effect-TS/platform/pull/319) [`425365e`](https://github.com/Effect-TS/platform/commit/425365ebc40c52a6e2a4bff865c3a982ce74f4ed) Thanks [@IMax153](https://github.com/IMax153)! - make Terminal.columns an Effect to account for resizing the terminal\n\n## 0.32.2\n\n### Patch Changes\n\n- [#312](https://github.com/Effect-TS/platform/pull/312) [`cc1f588`](https://github.com/Effect-TS/platform/commit/cc1f5886bf4188e0128b64b9e2a67f789680cab0) Thanks [@tim-smart](https://github.com/tim-smart)! - scope commands to prevent process leaks\n\n## 0.32.1\n\n### Patch Changes\n\n- [#310](https://github.com/Effect-TS/platform/pull/310) [`14239fb`](https://github.com/Effect-TS/platform/commit/14239fb11ae45db1a02d9ba883d0412a9c9e6343) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.32.0\n\n### Minor Changes\n\n- [#307](https://github.com/Effect-TS/platform/pull/307) [`746f969`](https://github.com/Effect-TS/platform/commit/746f9692e2f7133dcb413e0eea08ac7b6b97a9bd) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n### Patch Changes\n\n- [#304](https://github.com/Effect-TS/platform/pull/304) [`92e56a1`](https://github.com/Effect-TS/platform/commit/92e56a1f844f28f26621a1887cc4da045039066d) Thanks [@tim-smart](https://github.com/tim-smart)! - allow fetch function to be replaced\n\n- [#304](https://github.com/Effect-TS/platform/pull/304) [`92e56a1`](https://github.com/Effect-TS/platform/commit/92e56a1f844f28f26621a1887cc4da045039066d) Thanks [@tim-smart](https://github.com/tim-smart)! - add HttpClient.mapInputRequest apis\n\n## 0.31.2\n\n### Patch Changes\n\n- [#298](https://github.com/Effect-TS/platform/pull/298) [`7a46ec6`](https://github.com/Effect-TS/platform/commit/7a46ec679e2d4718919c407d0c6c5f0fdc35e62d) Thanks [@tim-smart](https://github.com/tim-smart)! - add .toWebHandler\\* to Http/App\n\n## 0.31.1\n\n### Patch Changes\n\n- [#292](https://github.com/Effect-TS/platform/pull/292) [`b712491`](https://github.com/Effect-TS/platform/commit/b71249168eb4623de8dbd28cd0102be688f5caa3) Thanks [@tim-smart](https://github.com/tim-smart)! - add ability to disable http tracer with predicate\n\n## 0.31.0\n\n### Minor Changes\n\n- [#291](https://github.com/Effect-TS/platform/pull/291) [`5a677f1`](https://github.com/Effect-TS/platform/commit/5a677f1062d7373e21839dfa51db26beef15dca4) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n### Patch Changes\n\n- [#289](https://github.com/Effect-TS/platform/pull/289) [`624855f`](https://github.com/Effect-TS/platform/commit/624855f635162b2c1232429253477d0805e02657) Thanks [@tim-smart](https://github.com/tim-smart)! - update deps\n\n## 0.30.6\n\n### Patch Changes\n\n- [#287](https://github.com/Effect-TS/platform/pull/287) [`d5d0932`](https://github.com/Effect-TS/platform/commit/d5d093219cde4f51afb9251d9ba4270fc70be0c1) Thanks [@tim-smart](https://github.com/tim-smart)! - expose ServerResponse.setStatus\n\n## 0.30.5\n\n### Patch Changes\n\n- [#277](https://github.com/Effect-TS/platform/pull/277) [`36e449c`](https://github.com/Effect-TS/platform/commit/36e449c95fab80dc54505cef2071dcbecce35b4f) Thanks [@tim-smart](https://github.com/tim-smart)! - wait for ready latch in worker\n\n## 0.30.4\n\n### Patch Changes\n\n- [#275](https://github.com/Effect-TS/platform/pull/275) [`e28989e`](https://github.com/Effect-TS/platform/commit/e28989ebd1813cec7ce68f7dd8718f2254e05cad) Thanks [@tim-smart](https://github.com/tim-smart)! - add stack to WorkerError\n\n## 0.30.3\n\n### Patch Changes\n\n- [#272](https://github.com/Effect-TS/platform/pull/272) [`1a055ac`](https://github.com/Effect-TS/platform/commit/1a055ac959faf12e9c57768b20babea12b1f7d2d) Thanks [@tim-smart](https://github.com/tim-smart)! - add WorkerError to send api\n\n## 0.30.2\n\n### Patch Changes\n\n- [#270](https://github.com/Effect-TS/platform/pull/270) [`3257fd5`](https://github.com/Effect-TS/platform/commit/3257fd52016af5a38c135de5f0aa33aac7de2538) Thanks [@tim-smart](https://github.com/tim-smart)! - update multipasta\n\n## 0.30.1\n\n### Patch Changes\n\n- [#268](https://github.com/Effect-TS/platform/pull/268) [`58f5ccc`](https://github.com/Effect-TS/platform/commit/58f5ccc07d74abe6820debc0179665e5ef76b5c4) Thanks [@tim-smart](https://github.com/tim-smart)! - update deps\n\n## 0.30.0\n\n### Minor Changes\n\n- [#267](https://github.com/Effect-TS/platform/pull/267) [`3d38b40`](https://github.com/Effect-TS/platform/commit/3d38b40a939e32c6c0e8b62dd53a844a6f389182) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.29.1\n\n### Patch Changes\n\n- [#263](https://github.com/Effect-TS/platform/pull/263) [`2bbe692`](https://github.com/Effect-TS/platform/commit/2bbe6928aa5e6929e58877ba236547310bca7e2b) Thanks [@tim-smart](https://github.com/tim-smart)! - fix fieldMimeTypes fiber ref\n\n## 0.29.0\n\n### Minor Changes\n\n- [#250](https://github.com/Effect-TS/platform/pull/250) [`6e18090`](https://github.com/Effect-TS/platform/commit/6e18090db4686cd5564ab9dc3d8771d7b3ad97fa) Thanks [@tim-smart](https://github.com/tim-smart)! - updated FormData model and apis\n\n## 0.28.4\n\n### Patch Changes\n\n- [#260](https://github.com/Effect-TS/platform/pull/260) [`8f5e6a2`](https://github.com/Effect-TS/platform/commit/8f5e6a2f2ced4408b0b311b0456828855e1cb958) Thanks [@IMax153](https://github.com/IMax153)! - expose available terminal columns from the Terminal service\n\n## 0.28.3\n\n### Patch Changes\n\n- [#258](https://github.com/Effect-TS/platform/pull/258) [`9f79c1f`](https://github.com/Effect-TS/platform/commit/9f79c1f5278e60b3bcbd59f08e20189bcb25a84e) Thanks [@IMax153](https://github.com/IMax153)! - fix context identifier for Terminal service\n\n## 0.28.2\n\n### Patch Changes\n\n- [#255](https://github.com/Effect-TS/platform/pull/255) [`fea76da`](https://github.com/Effect-TS/platform/commit/fea76da05190a65912911bd5b6f9cc0bef3b2edc) Thanks [@IMax153](https://github.com/IMax153)! - add basic Terminal interface for prompting user input\n\n## 0.28.1\n\n### Patch Changes\n\n- [#253](https://github.com/Effect-TS/platform/pull/253) [`43d2e29`](https://github.com/Effect-TS/platform/commit/43d2e2984fe88b39e907f45f089206ed88ad52d1) Thanks [@fubhy](https://github.com/fubhy)! - Update dependencies\n\n## 0.28.0\n\n### Minor Changes\n\n- [#251](https://github.com/Effect-TS/platform/pull/251) [`05fef78`](https://github.com/Effect-TS/platform/commit/05fef784ac975059fb6335576feadc7f34644314) Thanks [@fubhy](https://github.com/fubhy)! - Re-added exports for http module\n\n## 0.27.4\n\n### Patch Changes\n\n- [#248](https://github.com/Effect-TS/platform/pull/248) [`8a4b1c1`](https://github.com/Effect-TS/platform/commit/8a4b1c14808d9815eb93a5b10d8a5b26c4dd027b) Thanks [@IMax153](https://github.com/IMax153)! - allow for specifying that a Command should be run in a shell\n\n## 0.27.3\n\n### Patch Changes\n\n- [#243](https://github.com/Effect-TS/platform/pull/243) [`1ac0a42`](https://github.com/Effect-TS/platform/commit/1ac0a4208184ef1d23d5ad41a7f0e32bc4d80d85) Thanks [@tim-smart](https://github.com/tim-smart)! - fix worker interruption\n\n## 0.27.2\n\n### Patch Changes\n\n- [#241](https://github.com/Effect-TS/platform/pull/241) [`e2aa7cd`](https://github.com/Effect-TS/platform/commit/e2aa7cd606a735809fbf79327cfebc009e89d84d) Thanks [@tim-smart](https://github.com/tim-smart)! - decrease bun worker close timeout\n\n## 0.27.1\n\n### Patch Changes\n\n- [#239](https://github.com/Effect-TS/platform/pull/239) [`4d94b9d`](https://github.com/Effect-TS/platform/commit/4d94b9d30adba2bf4f6f6e1d4cd735e6362667c5) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.27.0\n\n### Minor Changes\n\n- [#237](https://github.com/Effect-TS/platform/pull/237) [`1f79ed6`](https://github.com/Effect-TS/platform/commit/1f79ed6b4d2ee9ae2b59c4536854566c579e77c4) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.26.7\n\n### Patch Changes\n\n- [#235](https://github.com/Effect-TS/platform/pull/235) [`6e14c02`](https://github.com/Effect-TS/platform/commit/6e14c02db668f380bb92f19037685fe40592a8fe) Thanks [@tim-smart](https://github.com/tim-smart)! - fix for hanging worker shutdown\n\n## 0.26.6\n\n### Patch Changes\n\n- [#233](https://github.com/Effect-TS/platform/pull/233) [`71947e0`](https://github.com/Effect-TS/platform/commit/71947e0e0aa9dccf9aad6f63dd98a6b6c89f23b4) Thanks [@tim-smart](https://github.com/tim-smart)! - fix worker scope hanging on close\n\n## 0.26.5\n\n### Patch Changes\n\n- [#231](https://github.com/Effect-TS/platform/pull/231) [`a3cbba4`](https://github.com/Effect-TS/platform/commit/a3cbba4a0fa0f1ef99a6d7e54f5ab46c6813ef00) Thanks [@tim-smart](https://github.com/tim-smart)! - add onCreate and broadcast to pool options\n\n## 0.26.4\n\n### Patch Changes\n\n- [#229](https://github.com/Effect-TS/platform/pull/229) [`4661a8c`](https://github.com/Effect-TS/platform/commit/4661a8c63a13cc6630d5f3cbac90f4ff1d096e09) Thanks [@tim-smart](https://github.com/tim-smart)! - type worker runner success as never\n\n- [#229](https://github.com/Effect-TS/platform/pull/229) [`4661a8c`](https://github.com/Effect-TS/platform/commit/4661a8c63a13cc6630d5f3cbac90f4ff1d096e09) Thanks [@tim-smart](https://github.com/tim-smart)! - disable worker pool scaling\n\n## 0.26.3\n\n### Patch Changes\n\n- [#227](https://github.com/Effect-TS/platform/pull/227) [`abb6baa`](https://github.com/Effect-TS/platform/commit/abb6baa61346580f97d2ab91b84a7342b5becc60) Thanks [@patroza](https://github.com/patroza)! - feat: cache the reading of text/urlParamsBody/formData bodies so they can be reused\n\n## 0.26.2\n\n### Patch Changes\n\n- [#219](https://github.com/Effect-TS/platform/pull/219) [`f37f58c`](https://github.com/Effect-TS/platform/commit/f37f58ca21c1d5dfedc40c01cde0ffbc954d7e32) Thanks [@tim-smart](https://github.com/tim-smart)! - fix encode / transfers for effect workers\n\n## 0.26.1\n\n### Patch Changes\n\n- [#217](https://github.com/Effect-TS/platform/pull/217) [`7471ac1`](https://github.com/Effect-TS/platform/commit/7471ac139f3c6867cd0d228ec54e88abd1384f5c) Thanks [@tim-smart](https://github.com/tim-smart)! - add encode option to Worker & WorkerRunner\n\n## 0.26.0\n\n### Minor Changes\n\n- [#215](https://github.com/Effect-TS/platform/pull/215) [`59da2a6`](https://github.com/Effect-TS/platform/commit/59da2a6877e219b2ca0433aeeecab4ad7487816b) Thanks [@tim-smart](https://github.com/tim-smart)! - seperate request processing in http client\n\n## 0.25.1\n\n### Patch Changes\n\n- [#213](https://github.com/Effect-TS/platform/pull/213) [`38a49eb`](https://github.com/Effect-TS/platform/commit/38a49eb6ea99ef773007a98ec262898207c8f3c7) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.25.0\n\n### Minor Changes\n\n- [#211](https://github.com/Effect-TS/platform/pull/211) [`9ec45cb`](https://github.com/Effect-TS/platform/commit/9ec45cba6b7d5016079ccad9357934f12afe8750) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.24.0\n\n### Minor Changes\n\n- [#209](https://github.com/Effect-TS/platform/pull/209) [`9c51aa1`](https://github.com/Effect-TS/platform/commit/9c51aa18beb7fd34023863ca069d3dde372765d8) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.23.1\n\n### Patch Changes\n\n- [#206](https://github.com/Effect-TS/platform/pull/206) [`b47639b`](https://github.com/Effect-TS/platform/commit/b47639b1df021beb075469921e9ef7a08c174555) Thanks [@tim-smart](https://github.com/tim-smart)! - small stream improvements\n\n- [#208](https://github.com/Effect-TS/platform/pull/208) [`41f8a65`](https://github.com/Effect-TS/platform/commit/41f8a650238bfbac5b8e18d58a431c3605b71aa5) Thanks [@tim-smart](https://github.com/tim-smart)! - add Http.middleware.withLoggerDisabled\n\n## 0.23.0\n\n### Minor Changes\n\n- [#204](https://github.com/Effect-TS/platform/pull/204) [`ee0c08f`](https://github.com/Effect-TS/platform/commit/ee0c08fd9828eae32696da1bde33d50a3ad9edf3) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.22.1\n\n### Patch Changes\n\n- [#194](https://github.com/Effect-TS/platform/pull/194) [`79b71d8`](https://github.com/Effect-TS/platform/commit/79b71d8cb3aa6520b2dcb7930850b423174e04b2) Thanks [@tim-smart](https://github.com/tim-smart)! - add Worker & WorkerRunner modules\n\n## 0.22.0\n\n### Minor Changes\n\n- [#199](https://github.com/Effect-TS/platform/pull/199) [`1e94b15`](https://github.com/Effect-TS/platform/commit/1e94b1588e51df20f9c4fc4871b246048751506c) Thanks [@tim-smart](https://github.com/tim-smart)! - enable tracing by default\n\n## 0.21.0\n\n### Minor Changes\n\n- [#193](https://github.com/Effect-TS/platform/pull/193) [`9ec4b1d`](https://github.com/Effect-TS/platform/commit/9ec4b1d284caa1c4f19a58c46ed7c25fb10d39a5) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n### Patch Changes\n\n- [#191](https://github.com/Effect-TS/platform/pull/191) [`2711aea`](https://github.com/Effect-TS/platform/commit/2711aea855936c82c282e61fbc6d2f1a1ab6778a) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.20.0\n\n### Minor Changes\n\n- [#189](https://github.com/Effect-TS/platform/pull/189) [`b07f8cd`](https://github.com/Effect-TS/platform/commit/b07f8cd50ef44d577aa981a532025aedb364df13) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.19.0\n\n### Minor Changes\n\n- [#184](https://github.com/Effect-TS/platform/pull/184) [`903b599`](https://github.com/Effect-TS/platform/commit/903b5995bb407c399846e6b75e47e53098b2c80d) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n### Patch Changes\n\n- [#186](https://github.com/Effect-TS/platform/pull/186) [`a3bcda4`](https://github.com/Effect-TS/platform/commit/a3bcda4c2c6655ab86769cca60bece5eb64f866e) Thanks [@tim-smart](https://github.com/tim-smart)! - add pre response handlers to http\n\n## 0.18.7\n\n### Patch Changes\n\n- [#179](https://github.com/Effect-TS/platform/pull/179) [`843488f`](https://github.com/Effect-TS/platform/commit/843488f79b253518f131693faf2955f5c795a1bc) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.18.6\n\n### Patch Changes\n\n- [#177](https://github.com/Effect-TS/platform/pull/177) [`7e4e2a5`](https://github.com/Effect-TS/platform/commit/7e4e2a5d815c677e4eb6adb2c6e9369414a79384) Thanks [@tim-smart](https://github.com/tim-smart)! - add ClientResponse.schemaNoBody\n\n- [#175](https://github.com/Effect-TS/platform/pull/175) [`d1c2b38`](https://github.com/Effect-TS/platform/commit/d1c2b38cbb1189249c0bfd47582e00ff771428e3) Thanks [@tim-smart](https://github.com/tim-smart)! - make ServerResponse an Effect\n\n## 0.18.5\n\n### Patch Changes\n\n- [#171](https://github.com/Effect-TS/platform/pull/171) [`fbbcaa9`](https://github.com/Effect-TS/platform/commit/fbbcaa9b1d4f48f204072a802fb11bcb29813664) Thanks [@tim-smart](https://github.com/tim-smart)! - remove preserveModules patch for preconstruct\n\n## 0.18.4\n\n### Patch Changes\n\n- [#169](https://github.com/Effect-TS/platform/pull/169) [`bd8778d`](https://github.com/Effect-TS/platform/commit/bd8778d1a534f28cab4b326bb25c086fafed8101) Thanks [@tim-smart](https://github.com/tim-smart)! - fix nested modules\n\n## 0.18.3\n\n### Patch Changes\n\n- [#167](https://github.com/Effect-TS/platform/pull/167) [`7027589`](https://github.com/Effect-TS/platform/commit/7027589d6dde621065eb8834a2b1ba4d3adc943b) Thanks [@tim-smart](https://github.com/tim-smart)! - build with preconstruct\n\n## 0.18.2\n\n### Patch Changes\n\n- [#165](https://github.com/Effect-TS/platform/pull/165) [`7e3a741`](https://github.com/Effect-TS/platform/commit/7e3a74197325566df47f9b4459e518eea0762d13) Thanks [@fubhy](https://github.com/fubhy)! - Fix peer deps version range\n\n## 0.18.1\n\n### Patch Changes\n\n- [#163](https://github.com/Effect-TS/platform/pull/163) [`c957232`](https://github.com/Effect-TS/platform/commit/c9572328ee37f44e93e933da622b21df414bf5c6) Thanks [@tim-smart](https://github.com/tim-smart)! - update effect\n\n## 0.18.0\n\n### Minor Changes\n\n- [#160](https://github.com/Effect-TS/platform/pull/160) [`c2dc0ab`](https://github.com/Effect-TS/platform/commit/c2dc0abb20b073fd19e38b4e61a08b1edee0f37f) Thanks [@fubhy](https://github.com/fubhy)! - update to effect package\n\n## 0.17.1\n\n### Patch Changes\n\n- [#158](https://github.com/Effect-TS/platform/pull/158) [`9b10bf3`](https://github.com/Effect-TS/platform/commit/9b10bf394106ba0bafd8440dc0b3fba30a5cc1ea) Thanks [@tim-smart](https://github.com/tim-smart)! - add client transform apis\n\n## 0.17.0\n\n### Minor Changes\n\n- [#156](https://github.com/Effect-TS/platform/pull/156) [`e6c4101`](https://github.com/Effect-TS/platform/commit/e6c41011e5420d90c543dd25d87036d4150f3e85) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.16.1\n\n### Patch Changes\n\n- [#148](https://github.com/Effect-TS/platform/pull/148) [`492f0e7`](https://github.com/Effect-TS/platform/commit/492f0e700e939ded6ff17eeca4d50a9e1ce59219) Thanks [@tim-smart](https://github.com/tim-smart)! - add IncomingMessage.remoteAddress\n\n## 0.16.0\n\n### Minor Changes\n\n- [#145](https://github.com/Effect-TS/platform/pull/145) [`d0522be`](https://github.com/Effect-TS/platform/commit/d0522be6f824571d83be8c6aa16a3d7caa1b3447) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n### Patch Changes\n\n- [#144](https://github.com/Effect-TS/platform/pull/144) [`6583ad4`](https://github.com/Effect-TS/platform/commit/6583ad4ef5b718620c873208bb11196d35733034) Thanks [@tim-smart](https://github.com/tim-smart)! - b3 header propagation in http client and server\n\n## 0.15.2\n\n### Patch Changes\n\n- [#131](https://github.com/Effect-TS/platform/pull/131) [`06e27ce`](https://github.com/Effect-TS/platform/commit/06e27ce29553ea8d0a234b941fa1de1a51996fbf) Thanks [@jessekelly881](https://github.com/jessekelly881)! - add Clipboard module to /platform-browser\n\n## 0.15.1\n\n### Patch Changes\n\n- [#138](https://github.com/Effect-TS/platform/pull/138) [`2b2f658`](https://github.com/Effect-TS/platform/commit/2b2f6583a7e589a4c7ab8c22bec390ef755f54c3) Thanks [@tim-smart](https://github.com/tim-smart)! - remove Router.WithoutProvided\n\n## 0.15.0\n\n### Minor Changes\n\n- [#135](https://github.com/Effect-TS/platform/pull/135) [`99f2a49`](https://github.com/Effect-TS/platform/commit/99f2a49c614a5b80646f6600a170609fe7e38025) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.14.1\n\n### Patch Changes\n\n- [#133](https://github.com/Effect-TS/platform/pull/133) [`1d2c403`](https://github.com/Effect-TS/platform/commit/1d2c4033af11f18ba09f53dcfdf8b3fc399bd22f) Thanks [@tim-smart](https://github.com/tim-smart)! - add http platform abstraction\n\n- [#133](https://github.com/Effect-TS/platform/pull/133) [`1d2c403`](https://github.com/Effect-TS/platform/commit/1d2c4033af11f18ba09f53dcfdf8b3fc399bd22f) Thanks [@tim-smart](https://github.com/tim-smart)! - handle HEAD requests\n\n## 0.14.0\n\n### Minor Changes\n\n- [#130](https://github.com/Effect-TS/platform/pull/130) [`2713c4f`](https://github.com/Effect-TS/platform/commit/2713c4f766f5493303221772368710a09033658d) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.13.16\n\n### Patch Changes\n\n- [#125](https://github.com/Effect-TS/platform/pull/125) [`eb54e53`](https://github.com/Effect-TS/platform/commit/eb54e53d95e7b863d8ffdff9de12b0abd462b217) Thanks [@tim-smart](https://github.com/tim-smart)! - restruture platform-node for platform-bun reuse\n\n## 0.13.15\n\n### Patch Changes\n\n- [#123](https://github.com/Effect-TS/platform/pull/123) [`07089a8`](https://github.com/Effect-TS/platform/commit/07089a877fd72b2c1b30016f92af162bbb6ff2c8) Thanks [@tim-smart](https://github.com/tim-smart)! - add ClientResponse.schemaJson\n\n## 0.13.14\n\n### Patch Changes\n\n- [#120](https://github.com/Effect-TS/platform/pull/120) [`9cda8c9`](https://github.com/Effect-TS/platform/commit/9cda8c9ce78d5a9c841a828df20401a0dc07b747) Thanks [@tim-smart](https://github.com/tim-smart)! - add KeyValueStore.SchemaStore\n\n- [#111](https://github.com/Effect-TS/platform/pull/111) [`6e96703`](https://github.com/Effect-TS/platform/commit/6e96703186f38bd481bffa906e0f99dee89b8e7e) Thanks [@jessekelly881](https://github.com/jessekelly881)! - add KeyValueStore module\n\n- [#120](https://github.com/Effect-TS/platform/pull/120) [`9cda8c9`](https://github.com/Effect-TS/platform/commit/9cda8c9ce78d5a9c841a828df20401a0dc07b747) Thanks [@tim-smart](https://github.com/tim-smart)! - add KeyValueStore.prefix\n\n## 0.13.13\n\n### Patch Changes\n\n- [#117](https://github.com/Effect-TS/platform/pull/117) [`ee7e365`](https://github.com/Effect-TS/platform/commit/ee7e365eafd8b62bab5bc32dd94e3f1190f6e7d6) Thanks [@tim-smart](https://github.com/tim-smart)! - add support for File web api to http\n\n## 0.13.12\n\n### Patch Changes\n\n- [#115](https://github.com/Effect-TS/platform/pull/115) [`4cba795`](https://github.com/Effect-TS/platform/commit/4cba79529426483775782f2384b2194ff57f1279) Thanks [@tim-smart](https://github.com/tim-smart)! - add Router.WithoutProvided\n\n## 0.13.11\n\n### Patch Changes\n\n- [#113](https://github.com/Effect-TS/platform/pull/113) [`5945805`](https://github.com/Effect-TS/platform/commit/59458051ad3885d23c4657369a9a46015f4e569c) Thanks [@tim-smart](https://github.com/tim-smart)! - try to remove route context and requests from Router context\n\n## 0.13.10\n\n### Patch Changes\n\n- [#109](https://github.com/Effect-TS/platform/pull/109) [`7031ec0`](https://github.com/Effect-TS/platform/commit/7031ec030a45a306f4fda4d3ed80796f98a7758e) Thanks [@tim-smart](https://github.com/tim-smart)! - remove Body.EffectBody\n\n## 0.13.9\n\n### Patch Changes\n\n- [#106](https://github.com/Effect-TS/platform/pull/106) [`df3dbcf`](https://github.com/Effect-TS/platform/commit/df3dbcf468d10dca8cdb219478bb0a23bc66da0c) Thanks [@tim-smart](https://github.com/tim-smart)! - add count to http log span\n\n## 0.13.8\n\n### Patch Changes\n\n- [#99](https://github.com/Effect-TS/platform/pull/99) [`e42c3f5`](https://github.com/Effect-TS/platform/commit/e42c3f5103b7361b5162a3e9280759ecd690295f) Thanks [@tim-smart](https://github.com/tim-smart)! - add ClientRequest.bearerToken\n\n- [#105](https://github.com/Effect-TS/platform/pull/105) [`127c8f5`](https://github.com/Effect-TS/platform/commit/127c8f50f69d5cf7e4a50241fca70923f71f61a2) Thanks [@tim-smart](https://github.com/tim-smart)! - add more form data limit config\n\n## 0.13.7\n\n### Patch Changes\n\n- [#97](https://github.com/Effect-TS/platform/pull/97) [`e5c91eb`](https://github.com/Effect-TS/platform/commit/e5c91eb541a6f97cb759ba39732cf08b0ae4c248) Thanks [@tim-smart](https://github.com/tim-smart)! - rename IncomingMessage.urlParams to urlParamsBody\n\n## 0.13.6\n\n### Patch Changes\n\n- [#94](https://github.com/Effect-TS/platform/pull/94) [`cd3b15e`](https://github.com/Effect-TS/platform/commit/cd3b15e0cb223d2788d383caaa7c0dbc06073dc1) Thanks [@tim-smart](https://github.com/tim-smart)! - only use mime module in ServerResponse\n\n## 0.13.5\n\n### Patch Changes\n\n- [#92](https://github.com/Effect-TS/platform/pull/92) [`a034383`](https://github.com/Effect-TS/platform/commit/a0343838bad8f37ab7fb6031084a6514103eba2b) Thanks [@tim-smart](https://github.com/tim-smart)! - fix mime import\n\n## 0.13.4\n\n### Patch Changes\n\n- [#90](https://github.com/Effect-TS/platform/pull/90) [`05d1765`](https://github.com/Effect-TS/platform/commit/05d1765a0606abce8a3c3d026bdcd5d8b3c64936) Thanks [@tim-smart](https://github.com/tim-smart)! - rename Router.transform to Router.use\n\n- [#89](https://github.com/Effect-TS/platform/pull/89) [`30025cb`](https://github.com/Effect-TS/platform/commit/30025cbd773b4ded89ffdb20a523a4350eb0452e) Thanks [@tim-smart](https://github.com/tim-smart)! - add etag generation for http file responses\n\n## 0.13.3\n\n### Patch Changes\n\n- [#86](https://github.com/Effect-TS/platform/pull/86) [`6dfc5b0`](https://github.com/Effect-TS/platform/commit/6dfc5b0fbec0e8a057a26c009f19c9951e4b3ba4) Thanks [@tim-smart](https://github.com/tim-smart)! - add router combinators\n\n- [#88](https://github.com/Effect-TS/platform/pull/88) [`d7fffeb`](https://github.com/Effect-TS/platform/commit/d7fffeb38a1c40ad3847e4e5b966f58939d1ba83) Thanks [@tim-smart](https://github.com/tim-smart)! - remove Middleware.compose\n\n## 0.13.2\n\n### Patch Changes\n\n- [#83](https://github.com/Effect-TS/platform/pull/83) [`ce5e086`](https://github.com/Effect-TS/platform/commit/ce5e0869390d571d21f854b6c1073bf10136e602) Thanks [@tim-smart](https://github.com/tim-smart)! - update deps\n\n- [#81](https://github.com/Effect-TS/platform/pull/81) [`c1ec2ba`](https://github.com/Effect-TS/platform/commit/c1ec2bab2b1c134c49a82fd5dbb741b0df3d1cd9) Thanks [@tim-smart](https://github.com/tim-smart)! - use ReadonlyRecord for headers\n\n- [#83](https://github.com/Effect-TS/platform/pull/83) [`ce5e086`](https://github.com/Effect-TS/platform/commit/ce5e0869390d571d21f854b6c1073bf10136e602) Thanks [@tim-smart](https://github.com/tim-smart)! - performance tweaks\n\n## 0.13.1\n\n### Patch Changes\n\n- [#79](https://github.com/Effect-TS/platform/pull/79) [`3544c17`](https://github.com/Effect-TS/platform/commit/3544c17f5778ab47cb4019b6458b2543d572629a) Thanks [@TylorS](https://github.com/TylorS)! - Attempt to derive content-type from headers\n\n## 0.13.0\n\n### Minor Changes\n\n- [#77](https://github.com/Effect-TS/platform/pull/77) [`e97d80b`](https://github.com/Effect-TS/platform/commit/e97d80bd69646195a65ea6dfe13c6af19589d2cf) Thanks [@tim-smart](https://github.com/tim-smart)! - remove Console module\n\n## 0.12.1\n\n### Patch Changes\n\n- [#75](https://github.com/Effect-TS/platform/pull/75) [`d23ff14`](https://github.com/Effect-TS/platform/commit/d23ff14756796e945307ccfdf65252d47f99b7aa) Thanks [@tim-smart](https://github.com/tim-smart)! - add size helpers\n\n## 0.12.0\n\n### Minor Changes\n\n- [#71](https://github.com/Effect-TS/platform/pull/71) [`139de2e`](https://github.com/Effect-TS/platform/commit/139de2e18adcf6661609909ec6afd44abe4cb1a9) Thanks [@tim-smart](https://github.com/tim-smart)! - add HttpServer module\n\n### Patch Changes\n\n- [#71](https://github.com/Effect-TS/platform/pull/71) [`139de2e`](https://github.com/Effect-TS/platform/commit/139de2e18adcf6661609909ec6afd44abe4cb1a9) Thanks [@tim-smart](https://github.com/tim-smart)! - add SizeInput type\n\n## 0.11.5\n\n### Patch Changes\n\n- [#69](https://github.com/Effect-TS/platform/pull/69) [`0eb7df0`](https://github.com/Effect-TS/platform/commit/0eb7df0e2cbfb96986c3bbee4650c4036a97b1d2) Thanks [@tim-smart](https://github.com/tim-smart)! - have Command & Client implement Pipeable\n\n## 0.11.4\n\n### Patch Changes\n\n- [#67](https://github.com/Effect-TS/platform/pull/67) [`c41a166`](https://github.com/Effect-TS/platform/commit/c41a16614bc4daff05956b84a6bcd01cbb5836dd) Thanks [@tim-smart](https://github.com/tim-smart)! - add node implementation of http client\n\n## 0.11.3\n\n### Patch Changes\n\n- [#64](https://github.com/Effect-TS/platform/pull/64) [`6f2d011`](https://github.com/Effect-TS/platform/commit/6f2d011ce917d74d14b0375525f5c9805f8e44fe) Thanks [@tim-smart](https://github.com/tim-smart)! - fix ClientRequest jsonBody types\n\n## 0.11.2\n\n### Patch Changes\n\n- [#62](https://github.com/Effect-TS/platform/pull/62) [`3d44256`](https://github.com/Effect-TS/platform/commit/3d442560fee94a0c8f01f936a3f7c5b5e1ac8fc2) Thanks [@tim-smart](https://github.com/tim-smart)! - improve http client options type\n\n## 0.11.1\n\n### Patch Changes\n\n- [#38](https://github.com/Effect-TS/platform/pull/38) [`f70a121`](https://github.com/Effect-TS/platform/commit/f70a121b2fc9d1052434863c41657d353d21fb26) Thanks [@tim-smart](https://github.com/tim-smart)! - add HttpClient module\n\n## 0.11.0\n\n### Minor Changes\n\n- [#59](https://github.com/Effect-TS/platform/pull/59) [`b2f7bc0`](https://github.com/Effect-TS/platform/commit/b2f7bc0fe7310d861d52da03fefd9bc91852e5f9) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n### Patch Changes\n\n- [#58](https://github.com/Effect-TS/platform/pull/58) [`f61aa57`](https://github.com/Effect-TS/platform/commit/f61aa57a915ee221fdf5259cbaf1e4fe208e01b8) Thanks [@tim-smart](https://github.com/tim-smart)! - update build tools\n\n- [#56](https://github.com/Effect-TS/platform/pull/56) [`efcf469`](https://github.com/Effect-TS/platform/commit/efcf469da368770b2f321043a8e0e33f079c169b) Thanks [@tim-smart](https://github.com/tim-smart)! - switch to peerDependencies\n\n## 0.10.4\n\n### Patch Changes\n\n- [#55](https://github.com/Effect-TS/platform/pull/55) [`67caeff`](https://github.com/Effect-TS/platform/commit/67caeffb5343b4ce428aa3c6b393feb383667fef) Thanks [@tim-smart](https://github.com/tim-smart)! - add labels to Tags\n\n- [#46](https://github.com/Effect-TS/platform/pull/46) [`4a4d0af`](https://github.com/Effect-TS/platform/commit/4a4d0af4832f543fc53b2ba5c9fc9739bbc78f2e) Thanks [@fubhy](https://github.com/fubhy)! - add seek method to file handles\n\n- [#54](https://github.com/Effect-TS/platform/pull/54) [`b3950e1`](https://github.com/Effect-TS/platform/commit/b3950e1373673ae492106fe0cb76bcd32fbe5a2b) Thanks [@tim-smart](https://github.com/tim-smart)! - add writeFileString\n\n## 0.10.3\n\n### Patch Changes\n\n- [#51](https://github.com/Effect-TS/platform/pull/51) [`9163d96`](https://github.com/Effect-TS/platform/commit/9163d96717a832e9dbf2bdd262d73034fcbe92e9) Thanks [@tim-smart](https://github.com/tim-smart)! - revert exists change\n\n## 0.10.2\n\n### Patch Changes\n\n- [#49](https://github.com/Effect-TS/platform/pull/49) [`44eaaf5`](https://github.com/Effect-TS/platform/commit/44eaaf5c182dc70c73b7da9687e9c0a81daea86c) Thanks [@tim-smart](https://github.com/tim-smart)! - fix exists catching wrong error\n\n## 0.10.1\n\n### Patch Changes\n\n- [#47](https://github.com/Effect-TS/platform/pull/47) [`24b56d5`](https://github.com/Effect-TS/platform/commit/24b56d5d6afa40df072e2db37ebd71df538e66ac) Thanks [@tim-smart](https://github.com/tim-smart)! - add exists and readFileString to FileSystem\n\n## 0.10.0\n\n### Minor Changes\n\n- [#41](https://github.com/Effect-TS/platform/pull/41) [`68cbdca`](https://github.com/Effect-TS/platform/commit/68cbdca7e9da509c212d44101ab61c3bcf1354ad) Thanks [@tim-smart](https://github.com/tim-smart)! - update /data, /io and /stream\n\n## 0.9.0\n\n### Minor Changes\n\n- [#39](https://github.com/Effect-TS/platform/pull/39) [`3012e28`](https://github.com/Effect-TS/platform/commit/3012e289272d383fdae16af6b3ba396dec290b77) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.8.0\n\n### Minor Changes\n\n- [#36](https://github.com/Effect-TS/platform/pull/36) [`b82cbcc`](https://github.com/Effect-TS/platform/commit/b82cbcc56789c014f0a50c505497239ec220f4fd) Thanks [@tim-smart](https://github.com/tim-smart)! - update dependencies\n\n## 0.7.0\n\n### Minor Changes\n\n- [#34](https://github.com/Effect-TS/platform/pull/34) [`601d045`](https://github.com/Effect-TS/platform/commit/601d04526ad0a2e3285de509fdf86c7b6809a547) Thanks [@tim-smart](https://github.com/tim-smart)! - update /stream\n\n## 0.6.0\n\n### Minor Changes\n\n- [#32](https://github.com/Effect-TS/platform/pull/32) [`ee94eae`](https://github.com/Effect-TS/platform/commit/ee94eae46aee327baf0c6960befa6c35154fa35b) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io and /data\n\n## 0.5.0\n\n### Minor Changes\n\n- [#28](https://github.com/Effect-TS/platform/pull/28) [`f3d73f5`](https://github.com/Effect-TS/platform/commit/f3d73f587ad9b528bb1e37cf44e4928d913f56dd) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io\n\n## 0.4.0\n\n### Minor Changes\n\n- [#26](https://github.com/Effect-TS/platform/pull/26) [`834e1a7`](https://github.com/Effect-TS/platform/commit/834e1a793365f4deb742814d9cd6df9faae9d0c2) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io and /data\n\n## 0.3.0\n\n### Minor Changes\n\n- [#22](https://github.com/Effect-TS/platform/pull/22) [`645f10f`](https://github.com/Effect-TS/platform/commit/645f10f6d6a8600e369f068b22f3c2ef5169e867) Thanks [@tim-smart](https://github.com/tim-smart)! - update /io and /data\n\n## 0.2.0\n\n### Minor Changes\n\n- [#20](https://github.com/Effect-TS/platform/pull/20) [`756ccbe`](https://github.com/Effect-TS/platform/commit/756ccbe002f2e00c02b88aac126c2bc5b17a5769) Thanks [@IMax153](https://github.com/IMax153)! - upgrade to `@effect/data@0.13.5`, `@effect/io@0.31.3`, and `@effect/stream@0.25.1`\n\n## 0.1.0\n\n### Minor Changes\n\n- [#13](https://github.com/Effect-TS/platform/pull/13) [`b95c25f`](https://github.com/Effect-TS/platform/commit/b95c25f619b8e5ebf915f675f63de01accb1a8b8) Thanks [@tim-smart](https://github.com/tim-smart)! - initial release\n"
  },
  {
    "path": "packages/platform/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 Effectful Technologies Inc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "packages/platform/README.md",
    "content": "# Introduction\n\nWelcome to the documentation for `@effect/platform`, a library designed for creating platform-independent abstractions (Node.js, Bun, browsers).\n\n> [!WARNING]\n> This documentation focuses on **unstable modules**. For stable modules, refer to the [official website documentation](https://effect.website/docs/guides/platform/introduction).\n\n# Running Your Main Program with runMain\n\nDocs for `runMain` have been moved to the [official website](https://effect.website/docs/platform/runtime/).\n\n# HTTP API\n\n## Overview\n\nThe `HttpApi*` modules offer a flexible and declarative way to define HTTP APIs.\n\nTo define an API, create a set of `HttpEndpoint`s. Each endpoint is described by a path, a method, and schemas for the request and response.\n\nCollections of endpoints are grouped in an `HttpApiGroup`, and multiple groups can be merged into a complete `HttpApi`.\n\n```\nHttpApi\n├── HttpGroup\n│   ├── HttpEndpoint\n│   └── HttpEndpoint\n└── HttpGroup\n    ├── HttpEndpoint\n    ├── HttpEndpoint\n    └── HttpEndpoint\n```\n\nOnce your API is defined, the same definition can be reused for multiple purposes:\n\n- **Starting a Server**: Use the API definition to implement and serve endpoints.\n- **Generating Documentation**: Create a Swagger page to document the API.\n- **Deriving a Client**: Generate a fully-typed client for your API.\n\nBenefits of a Single API Definition:\n\n- **Consistency**: A single definition ensures the server, documentation, and client remain aligned.\n- **Reduced Maintenance**: Changes to the API are reflected across all related components.\n- **Simplified Workflow**: Avoids duplication by consolidating API details in one place.\n\n## Hello World\n\n### Defining and Implementing an API\n\nThis example demonstrates how to define and implement a simple API with a single endpoint that returns a string response. The structure of the API is as follows:\n\n```\nHttpApi (\"MyApi)\n└── HttpGroup (\"Greetings\")\n    └── HttpEndpoint (\"hello-world\")\n```\n\n**Example** (Hello World Definition)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { Effect, Layer, Schema } from \"effect\"\nimport { createServer } from \"node:http\"\n\n// Define our API with one group named \"Greetings\" and one endpoint called \"hello-world\"\nconst MyApi = HttpApi.make(\"MyApi\").add(\n  HttpApiGroup.make(\"Greetings\").add(\n    HttpApiEndpoint.get(\"hello-world\")`/`.addSuccess(Schema.String)\n  )\n)\n\n// Implement the \"Greetings\" group\nconst GreetingsLive = HttpApiBuilder.group(MyApi, \"Greetings\", (handlers) =>\n  handlers.handle(\"hello-world\", () => Effect.succeed(\"Hello, World!\"))\n)\n\n// Provide the implementation for the API\nconst MyApiLive = HttpApiBuilder.api(MyApi).pipe(Layer.provide(GreetingsLive))\n\n// Set up the server using NodeHttpServer on port 3000\nconst ServerLive = HttpApiBuilder.serve().pipe(\n  Layer.provide(MyApiLive),\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n)\n\n// Launch the server\nLayer.launch(ServerLive).pipe(NodeRuntime.runMain)\n```\n\nAfter running the code, open a browser and navigate to http://localhost:3000. The server will respond with:\n\n```\nHello, World!\n```\n\n### Serving The Auto Generated Swagger Documentation\n\nYou can enhance your API by adding auto-generated Swagger documentation using the `HttpApiSwagger` module. This makes it easier for developers to explore and interact with your API.\n\nTo include Swagger in your server setup, provide the `HttpApiSwagger.layer` when configuring the server.\n\n**Example** (Serving Swagger Documentation)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSwagger\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { Effect, Layer, Schema } from \"effect\"\nimport { createServer } from \"node:http\"\n\nconst MyApi = HttpApi.make(\"MyApi\").add(\n  HttpApiGroup.make(\"Greetings\").add(\n    HttpApiEndpoint.get(\"hello-world\")`/`.addSuccess(Schema.String)\n  )\n)\n\nconst GreetingsLive = HttpApiBuilder.group(MyApi, \"Greetings\", (handlers) =>\n  handlers.handle(\"hello-world\", () => Effect.succeed(\"Hello, World!\"))\n)\n\nconst MyApiLive = HttpApiBuilder.api(MyApi).pipe(Layer.provide(GreetingsLive))\n\nconst ServerLive = HttpApiBuilder.serve().pipe(\n  // Provide the Swagger layer so clients can access auto-generated docs\n  Layer.provide(HttpApiSwagger.layer()),\n  Layer.provide(MyApiLive),\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n)\n\nLayer.launch(ServerLive).pipe(NodeRuntime.runMain)\n```\n\nAfter running the server, open your browser and navigate to http://localhost:3000/docs.\n\nThis URL will display the Swagger documentation, allowing you to explore the API's endpoints, request parameters, and response structures interactively.\n\n![Swagger Documentation](./images/swagger-hello-world.png)\n\n### Deriving a Client\n\nOnce you have defined your API, you can generate a client to interact with it using the `HttpApiClient` module. This allows you to call your API endpoints without manually handling HTTP requests.\n\n**Example** (Deriving and Using a Client)\n\n```ts\nimport {\n  FetchHttpClient,\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiClient,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSwagger\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { Effect, Layer, Schema } from \"effect\"\nimport { createServer } from \"node:http\"\n\nconst MyApi = HttpApi.make(\"MyApi\").add(\n  HttpApiGroup.make(\"Greetings\").add(\n    HttpApiEndpoint.get(\"hello-world\")`/`.addSuccess(Schema.String)\n  )\n)\n\nconst GreetingsLive = HttpApiBuilder.group(MyApi, \"Greetings\", (handlers) =>\n  handlers.handle(\"hello-world\", () => Effect.succeed(\"Hello, World!\"))\n)\n\nconst MyApiLive = HttpApiBuilder.api(MyApi).pipe(Layer.provide(GreetingsLive))\n\nconst ServerLive = HttpApiBuilder.serve().pipe(\n  Layer.provide(HttpApiSwagger.layer()),\n  Layer.provide(MyApiLive),\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n)\n\nLayer.launch(ServerLive).pipe(NodeRuntime.runMain)\n\n// Create a program that derives and uses the client\nconst program = Effect.gen(function* () {\n  // Derive the client\n  const client = yield* HttpApiClient.make(MyApi, {\n    baseUrl: \"http://localhost:3000\"\n  })\n  // Call the \"hello-world\" endpoint\n  const hello = yield* client.Greetings[\"hello-world\"]()\n  console.log(hello)\n})\n\n// Provide a Fetch-based HTTP client and run the program\nEffect.runFork(program.pipe(Effect.provide(FetchHttpClient.layer)))\n// Output: Hello, World!\n```\n\n## Defining a HttpApiEndpoint\n\nAn `HttpApiEndpoint` represents a single endpoint in your API. Each endpoint is defined with a name, path, HTTP method, and optional schemas for requests and responses. This allows you to describe the structure and behavior of your API.\n\nBelow is an example of a simple CRUD API for managing users, which includes the following endpoints:\n\n- `GET /users` - Retrieve all users.\n- `GET /users/:userId` - Retrieve a specific user by ID.\n- `POST /users` - Create a new user.\n- `DELETE /users/:userId` - Delete a user by ID.\n- `PATCH /users/:userId` - Update a user by ID.\n\n### GET\n\nThe `HttpApiEndpoint.get` method allows you to define a GET endpoint by specifying its name, path, and optionally, a schema for the response.\n\nTo define the structure of successful responses, use the `.addSuccess` method. If no schema is provided, the default response status is `204 No Content`.\n\n**Example** (Defining a GET Endpoint to Retrieve All Users)\n\n```ts\nimport { HttpApiEndpoint } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\n// Define a schema representing a User entity\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\n// Define the \"getUsers\" endpoint, returning a list of users\nconst getUsers = HttpApiEndpoint\n  //      ┌─── Endpoint name\n  //      │            ┌─── Endpoint path\n  //      ▼            ▼\n  .get(\"getUsers\", \"/users\")\n  // Define the success schema for the response (optional).\n  // If no response schema is specified, the default response is `204 No Content`.\n  .addSuccess(Schema.Array(User))\n```\n\n### Path Parameters\n\nPath parameters allow you to include dynamic segments in your endpoint's path. There are two ways to define path parameters in your API.\n\n#### Using setPath\n\nThe `setPath` method allows you to explicitly define path parameters by associating them with a schema.\n\n**Example** (Defining Parameters with setPath)\n\n```ts\nimport { HttpApiEndpoint } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\n// Define a GET endpoint with a path parameter \":id\"\nconst getUser = HttpApiEndpoint.get(\"getUser\", \"/user/:id\")\n  .setPath(\n    Schema.Struct({\n      // Define a schema for the \"id\" path parameter\n      id: Schema.NumberFromString\n    })\n  )\n  .addSuccess(User)\n```\n\n#### Using Template Strings\n\nYou can also define path parameters by embedding them in a template string with the help of `HttpApiSchema.param`.\n\n**Example** (Defining Parameters using a Template String)\n\n```ts\nimport { HttpApiEndpoint, HttpApiSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\n// Create a path parameter using HttpApiSchema.param\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\n// Define the GET endpoint using a template string\nconst getUser = HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`.addSuccess(\n  User\n)\n```\n\n### POST\n\nThe `HttpApiEndpoint.post` method is used to define an endpoint for creating resources. You can specify a schema for the request body (payload) and a schema for the successful response.\n\n**Example** (Defining a POST Endpoint with Payload and Success Schemas)\n\n```ts\nimport { HttpApiEndpoint } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\n// Define a schema for the user object\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\n// Define a POST endpoint for creating a new user\nconst createUser = HttpApiEndpoint.post(\"createUser\", \"/users\")\n  // Define the request body schema (payload)\n  .setPayload(\n    Schema.Struct({\n      name: Schema.String\n    })\n  )\n  // Define the schema for a successful response\n  .addSuccess(User)\n```\n\n### DELETE\n\nThe `HttpApiEndpoint.del` method is used to define an endpoint for deleting a resource.\n\n**Example** (Defining a DELETE Endpoint with Path Parameters)\n\n```ts\nimport { HttpApiEndpoint, HttpApiSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\n// Define a path parameter for the user ID\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\n// Define a DELETE endpoint to delete a user by ID\nconst deleteUser = HttpApiEndpoint.del(\"deleteUser\")`/users/${idParam}`\n```\n\n### PATCH\n\nThe `HttpApiEndpoint.patch` method is used to define an endpoint for partially updating a resource. This method allows you to specify a schema for the request payload and a schema for the successful response.\n\n**Example** (Defining a PATCH Endpoint for Updating a User)\n\n```ts\nimport { HttpApiEndpoint, HttpApiSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\n// Define a schema for the user object\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\n// Define a path parameter for the user ID\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\n// Define a PATCH endpoint to update a user's name by ID\nconst updateUser = HttpApiEndpoint.patch(\"updateUser\")`/users/${idParam}`\n  // Specify the schema for the request payload\n  .setPayload(\n    Schema.Struct({\n      name: Schema.String // Only the name can be updated\n    })\n  )\n  // Specify the schema for a successful response\n  .addSuccess(User)\n```\n\n### Catch-All Endpoints\n\nThe path can also be `\"*\"` to match any incoming path. This is useful for defining a catch-all endpoint to handle unmatched routes or provide a fallback response.\n\n**Example** (Defining a Catch-All Endpoint)\n\n```ts\nimport { HttpApiEndpoint } from \"@effect/platform\"\n\nconst catchAll = HttpApiEndpoint.get(\"catchAll\", \"*\")\n```\n\n### Setting URL Parameters\n\nThe `setUrlParams` method allows you to define the structure of URL parameters for an endpoint. You can specify the schema for each parameter and include metadata such as descriptions to provide additional context.\n\n**Example** (Defining URL Parameters with Metadata)\n\n```ts\nimport { HttpApiEndpoint } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst getUsers = HttpApiEndpoint.get(\"getUsers\", \"/users\")\n  // Specify the URL parameters schema\n  .setUrlParams(\n    Schema.Struct({\n      // Parameter \"page\" for pagination\n      page: Schema.NumberFromString,\n      // Parameter \"sort\" for sorting options with an added description\n      sort: Schema.String.annotations({\n        description: \"Sorting criteria (e.g., 'name', 'date')\"\n      })\n    })\n  )\n  .addSuccess(Schema.Array(User))\n```\n\n#### Defining an Array of Values for a URL Parameter\n\nWhen defining a URL parameter that accepts multiple values, you can use the `Schema.Array` combinator. This allows the parameter to handle an array of items, with each item adhering to a specified schema.\n\n**Example** (Defining an Array of String Values for a URL Parameter)\n\n```ts\nimport { HttpApi, HttpApiEndpoint, HttpApiGroup } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst api = HttpApi.make(\"myApi\").add(\n  HttpApiGroup.make(\"group\").add(\n    HttpApiEndpoint.get(\"get\", \"/\")\n      .setUrlParams(\n        Schema.Struct({\n          // Define \"a\" as an array of strings\n          a: Schema.Array(Schema.String)\n        })\n      )\n      .addSuccess(Schema.String)\n  )\n)\n```\n\nYou can test this endpoint by passing an array of values in the query string. For example:\n\n```sh\ncurl \"http://localhost:3000/?a=1&a=2\"\n```\n\nThe query string sends two values (`1` and `2`) for the `a` parameter. The server will process and validate these values according to the schema.\n\n### Status Codes\n\nBy default, the success status code is `200 OK`. You can change it by annotating the schema with a custom status.\n\n**Example** (Defining a GET Endpoint with a custom status code)\n\n```ts\nimport { HttpApiEndpoint } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst getUsers = HttpApiEndpoint.get(\"getUsers\", \"/users\")\n  // Override the default success status\n  .addSuccess(Schema.Array(User), { status: 206 })\n```\n\n### Handling Multipart Requests\n\nTo support file uploads, you can use the `HttpApiSchema.Multipart` API. This allows you to define an endpoint's payload schema as a multipart request, specifying the structure of the data, including file uploads, with the `Multipart` module.\n\n**Example** (Defining an Endpoint for File Uploads)\n\nIn this example, the `HttpApiSchema.Multipart` function marks the payload as a multipart request. The `files` field uses `Multipart.FilesSchema` to handle uploaded file data automatically.\n\n```ts\nimport { HttpApiEndpoint, HttpApiSchema, Multipart } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst upload = HttpApiEndpoint.post(\"upload\", \"/users/upload\").setPayload(\n  // Specify that the payload is a multipart request\n  HttpApiSchema.Multipart(\n    Schema.Struct({\n      // Define a \"files\" field to handle file uploads\n      files: Multipart.FilesSchema\n    })\n  ).addSuccess(Schema.String)\n)\n```\n\nYou can test this endpoint by sending a multipart request with a file upload. For example:\n\n```sh\necho \"Sample file content\" | curl -X POST -F \"files=@-\" http://localhost:3000/users/upload\n```\n\n### Changing the Request Encoding\n\nBy default, API requests are encoded as JSON. If your application requires a different format, you can customize the request encoding using the `HttpApiSchema.withEncoding` method. This allows you to define the encoding type and content type of the request.\n\n**Example** (Customizing Request Encoding)\n\n```ts\nimport { HttpApiEndpoint, HttpApiSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst createUser = HttpApiEndpoint.post(\"createUser\", \"/users\")\n  // Set the request payload as a string encoded with URL parameters\n  .setPayload(\n    Schema.Struct({\n      a: Schema.String // Parameter \"a\" must be a string\n    })\n      // Specify the encoding as URL parameters\n      .pipe(HttpApiSchema.withEncoding({ kind: \"UrlParams\" }))\n  )\n```\n\n### Changing the Response Encoding\n\nBy default, API responses are encoded as JSON. If your application requires a different format, you can customize the encoding using the `HttpApiSchema.withEncoding` API. This method lets you define the type and content type of the response.\n\n**Example** (Returning Data as `text/csv`)\n\n```ts\nimport { HttpApiEndpoint, HttpApiSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst csv = HttpApiEndpoint.get(\"csv\")`/users/csv`\n  // Set the success response as a string with CSV encoding\n  .addSuccess(\n    Schema.String.pipe(\n      HttpApiSchema.withEncoding({\n        // Specify the type of the response\n        kind: \"Text\",\n        // Define the content type as text/csv\n        contentType: \"text/csv\"\n      })\n    )\n  )\n```\n\n### Setting Request Headers\n\nUse `HttpApiEndpoint.setHeaders` to declare a single, cumulative schema that describes all expected request headers.\nProvide one struct schema where each header name maps to its validator, and you can attach metadata such as descriptions.\n\n> [!IMPORTANT]\n> All headers are normalized to lowercase. Always use lowercase keys in the headers schema.\n\n**Example** (Describe and validate custom headers)\n\n```ts\nimport { HttpApiEndpoint } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\n// Model for successful responses\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst getUsers = HttpApiEndpoint.get(\"getUsers\", \"/users\")\n  // Describe the headers the endpoint expects\n  .setHeaders(\n    // Declare a single struct schema for all headers\n    // Header keys MUST be lowercase in the schema\n    Schema.Struct({\n      // This header must be a string\n      \"x-api-key\": Schema.String,\n\n      // A human-friendly description is useful for generated docs (e.g. OpenAPI)\n      \"x-request-id\": Schema.String.annotations({\n        description: \"Unique identifier for the request\"\n      })\n    })\n  )\n  // Successful response: an array of User\n  .addSuccess(Schema.Array(User))\n```\n\nYou can test the endpoint by sending the headers:\n\n```sh\ncurl -H \"X-API-Key: 1234567890\" -H \"X-Request-ID: 1234567890\" http://localhost:3000/users\n```\n\nThe server validates these headers against the declared schema before handling the request.\n\n## Defining a HttpApiGroup\n\nYou can group related endpoints under a single entity by using `HttpApiGroup.make`. This can help organize your code and provide a clearer structure for your API.\n\n**Example** (Creating a Group for User-Related Endpoints)\n\n```ts\nimport { HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst getUsers = HttpApiEndpoint.get(\"getUsers\", \"/users\").addSuccess(\n  Schema.Array(User)\n)\n\nconst getUser = HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`.addSuccess(\n  User\n)\n\nconst createUser = HttpApiEndpoint.post(\"createUser\", \"/users\")\n  .setPayload(\n    Schema.Struct({\n      name: Schema.String\n    })\n  )\n  .addSuccess(User)\n\nconst deleteUser = HttpApiEndpoint.del(\"deleteUser\")`/users/${idParam}`\n\nconst updateUser = HttpApiEndpoint.patch(\"updateUser\")`/users/${idParam}`\n  .setPayload(\n    Schema.Struct({\n      name: Schema.String\n    })\n  )\n  .addSuccess(User)\n\n// Group all user-related endpoints\nconst usersGroup = HttpApiGroup.make(\"users\")\n  .add(getUsers)\n  .add(getUser)\n  .add(createUser)\n  .add(deleteUser)\n  .add(updateUser)\n```\n\nIf you would like to create a more opaque type for the group, you can extend `HttpApiGroup` with a class.\n\n**Example** (Creating a Group with an Opaque Type)\n\n```ts\n// Create an opaque class extending HttpApiGroup\nclass UsersGroup extends HttpApiGroup.make(\"users\").add(getUsers).add(getUser) {\n  // Additional endpoints or methods can be added here\n}\n```\n\n## Creating the Top-Level HttpApi\n\nAfter defining your groups, you can combine them into one `HttpApi` representing your entire set of endpoints.\n\n**Example** (Combining Groups into a Top-Level API)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSchema\n} from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst getUsers = HttpApiEndpoint.get(\"getUsers\", \"/users\").addSuccess(\n  Schema.Array(User)\n)\n\nconst getUser = HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`.addSuccess(\n  User\n)\n\nconst createUser = HttpApiEndpoint.post(\"createUser\", \"/users\")\n  .setPayload(\n    Schema.Struct({\n      name: Schema.String\n    })\n  )\n  .addSuccess(User)\n\nconst deleteUser = HttpApiEndpoint.del(\"deleteUser\")`/users/${idParam}`\n\nconst updateUser = HttpApiEndpoint.patch(\"updateUser\")`/users/${idParam}`\n  .setPayload(\n    Schema.Struct({\n      name: Schema.String\n    })\n  )\n  .addSuccess(User)\n\nconst usersGroup = HttpApiGroup.make(\"users\")\n  .add(getUsers)\n  .add(getUser)\n  .add(createUser)\n  .add(deleteUser)\n  .add(updateUser)\n\n// Combine the groups into one API\nconst api = HttpApi.make(\"myApi\").add(usersGroup)\n\n// Alternatively, create an opaque class for your API\nclass MyApi extends HttpApi.make(\"myApi\").add(usersGroup) {}\n```\n\n## Adding errors\n\nError responses allow your API to handle different failure scenarios. These responses can be defined at various levels:\n\n- **Endpoint-level errors**: Use `HttpApiEndpoint.addError` to add errors specific to an endpoint.\n- **Group-level errors**: Use `HttpApiGroup.addError` to add errors applicable to all endpoints in a group.\n- **API-level errors**: Use `HttpApi.addError` to define errors that apply to every endpoint in the API.\n\nGroup-level and API-level errors are useful for handling shared issues like authentication failures, especially when managed through middleware.\n\n**Example** (Defining Error Responses for Endpoints and Groups)\n\n```ts\nimport { HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\n// Define error schemas\nclass UserNotFound extends Schema.TaggedError<UserNotFound>()(\n  \"UserNotFound\",\n  {}\n) {}\n\nclass Unauthorized extends Schema.TaggedError<Unauthorized>()(\n  \"Unauthorized\",\n  {}\n) {}\n\nconst getUsers = HttpApiEndpoint.get(\"getUsers\", \"/users\").addSuccess(\n  Schema.Array(User)\n)\n\nconst getUser = HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`\n  .addSuccess(User)\n  // Add a 404 error response for this endpoint\n  .addError(UserNotFound, { status: 404 })\n\nconst usersGroup = HttpApiGroup.make(\"users\")\n  .add(getUsers)\n  .add(getUser)\n  // ...etc...\n  // Add a 401 error response for the entire group\n  .addError(Unauthorized, { status: 401 })\n```\n\nYou can assign multiple error responses to a single endpoint by calling `HttpApiEndpoint.addError` multiple times. This is useful when different types of errors might occur for a single operation.\n\n**Example** (Adding Multiple Errors to an Endpoint)\n\n```ts\nconst deleteUser = HttpApiEndpoint.del(\"deleteUser\")`/users/${idParam}`\n  // Add a 404 error response for when the user is not found\n  .addError(UserNotFound, { status: 404 })\n  // Add a 401 error response for unauthorized access\n  .addError(Unauthorized, { status: 401 })\n```\n\n### Predefined Empty Error Types\n\nThe `HttpApiError` module provides a set of predefined empty error types that you can use in your endpoints. These error types help standardize common HTTP error responses, such as `404 Not Found` or `401 Unauthorized`. Using these predefined types simplifies error handling and ensures consistency across your API.\n\n**Example** (Adding a Predefined Error to an Endpoint)\n\n```ts\nimport { HttpApiEndpoint, HttpApiError, HttpApiSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst getUser = HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`\n  .addSuccess(User)\n  .addError(HttpApiError.NotFound)\n```\n\n| Name                  | Status | Description                                                                                        |\n| --------------------- | ------ | -------------------------------------------------------------------------------------------------- |\n| `HttpApiDecodeError`  | 400    | Represents an error where the request did not match the expected schema. Includes detailed issues. |\n| `BadRequest`          | 400    | Indicates that the request was malformed or invalid.                                               |\n| `Unauthorized`        | 401    | Indicates that authentication is required but missing or invalid.                                  |\n| `Forbidden`           | 403    | Indicates that the client does not have permission to access the requested resource.               |\n| `NotFound`            | 404    | Indicates that the requested resource could not be found.                                          |\n| `MethodNotAllowed`    | 405    | Indicates that the HTTP method used is not allowed for the requested resource.                     |\n| `NotAcceptable`       | 406    | Indicates that the requested resource cannot be delivered in a format acceptable to the client.    |\n| `RequestTimeout`      | 408    | Indicates that the server timed out waiting for the client request.                                |\n| `Conflict`            | 409    | Indicates a conflict in the request, such as conflicting data.                                     |\n| `Gone`                | 410    | Indicates that the requested resource is no longer available and will not return.                  |\n| `InternalServerError` | 500    | Indicates an unexpected server error occurred.                                                     |\n| `NotImplemented`      | 501    | Indicates that the requested functionality is not implemented on the server.                       |\n| `ServiceUnavailable`  | 503    | Indicates that the server is temporarily unavailable, often due to maintenance or overload.        |\n\n## Prefixing\n\nPrefixes can be added to endpoints, groups, or an entire API to simplify the management of common paths. This is especially useful when defining multiple related endpoints that share a common base URL.\n\n**Example** (Using Prefixes for Common Path Management)\n\n```ts\nimport { HttpApi, HttpApiEndpoint, HttpApiGroup } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst api = HttpApi.make(\"api\")\n  .add(\n    HttpApiGroup.make(\"group\")\n      .add(\n        HttpApiEndpoint.get(\"getRoot\", \"/\")\n          .addSuccess(Schema.String)\n          // Prefix for this endpoint\n          .prefix(\"/endpointPrefix\")\n      )\n      .add(HttpApiEndpoint.get(\"getA\", \"/a\").addSuccess(Schema.String))\n      // Prefix for all endpoints in the group\n      .prefix(\"/groupPrefix\")\n  )\n  // Prefix for the entire API\n  .prefix(\"/apiPrefix\")\n```\n\n## Implementing a Server\n\nAfter defining your API, you can implement a server to handle its endpoints. The `HttpApiBuilder` module provides tools to help you connect your API's structure to the logic that serves requests.\n\nHere, we will create a simple example with a `getUser` endpoint organized within a `users` group.\n\n**Example** (Defining the `users` Group and API)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSchema\n} from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst usersGroup = HttpApiGroup.make(\"users\").add(\n  HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`.addSuccess(User)\n)\n\nconst api = HttpApi.make(\"myApi\").add(usersGroup)\n```\n\n### Implementing a HttpApiGroup\n\nThe `HttpApiBuilder.group` API is used to implement a specific group of endpoints within an `HttpApi` definition. It requires the following inputs:\n\n| Input                             | Description                                                             |\n| --------------------------------- | ----------------------------------------------------------------------- |\n| The complete `HttpApi` definition | The overall API structure that includes the group you are implementing. |\n| The name of the group             | The specific group you are focusing on within the API.                  |\n| A function to add handlers        | A function that defines how each endpoint in the group is handled.      |\n\nEach endpoint in the group is connected to its logic using the `HttpApiBuilder.handle` method, which maps the endpoint's definition to its corresponding implementation.\n\nThe `HttpApiBuilder.group` API produces a `Layer` that can later be provided to the server implementation.\n\n**Example** (Implementing a Group with Endpoint Logic)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSchema\n} from \"@effect/platform\"\nimport { DateTime, Effect, Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst usersGroup = HttpApiGroup.make(\"users\").add(\n  HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`.addSuccess(User)\n)\n\nconst api = HttpApi.make(\"myApi\").add(usersGroup)\n\n// --------------------------------------------\n// Implementation\n// --------------------------------------------\n\n//      ┌─── Layer<HttpApiGroup.ApiGroup<\"myApi\", \"users\">>\n//      ▼\nconst usersGroupLive =\n  //                    ┌─── The Whole API\n  //                    │      ┌─── The Group you are implementing\n  //                    ▼      ▼\n  HttpApiBuilder.group(api, \"users\", (handlers) =>\n    handlers.handle(\n      //  ┌─── The Endpoint you are implementing\n      //  ▼\n      \"getUser\",\n      // Provide the handler logic for the endpoint.\n      // The parameters & payload are passed to the handler function.\n      ({ path: { id } }) =>\n        Effect.succeed(\n          // Return a mock user object with the provided ID\n          {\n            id,\n            name: \"John Doe\",\n            createdAt: DateTime.unsafeNow()\n          }\n        )\n    )\n  )\n```\n\nUsing `HttpApiBuilder.group`, you connect the structure of your API to its logic, enabling you to focus on each endpoint's functionality in isolation. Each handler receives the parameters and payload for the request, making it easy to process input and generate a response.\n\n### Using Services Inside a HttpApiGroup\n\nIf your handlers need to use services, you can easily integrate them because the `HttpApiBuilder.group` API allows you to return an `Effect`. This ensures that external services can be accessed and utilized directly within your handlers.\n\n**Example** (Using Services in a Group Implementation)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSchema\n} from \"@effect/platform\"\nimport { Context, Effect, Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst usersGroup = HttpApiGroup.make(\"users\").add(\n  HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`.addSuccess(User)\n)\n\nconst api = HttpApi.make(\"myApi\").add(usersGroup)\n\n// --------------------------------------------\n// Implementation\n// --------------------------------------------\n\ntype User = typeof User.Type\n\n// Define the UsersRepository service\nclass UsersRepository extends Context.Tag(\"UsersRepository\")<\n  UsersRepository,\n  {\n    readonly findById: (id: number) => Effect.Effect<User>\n  }\n>() {}\n\n// Implement the `users` group with access to the UsersRepository service\n//\n//      ┌─── Layer<HttpApiGroup.ApiGroup<\"myApi\", \"users\">, never, UsersRepository>\n//      ▼\nconst usersGroupLive = HttpApiBuilder.group(api, \"users\", (handlers) =>\n  Effect.gen(function* () {\n    // Access the UsersRepository service\n    const repository = yield* UsersRepository\n    return handlers.handle(\"getUser\", ({ path: { id } }) =>\n      repository.findById(id)\n    )\n  })\n)\n```\n\n### Implementing a HttpApi\n\nOnce all your groups are implemented, you can create a top-level implementation to combine them into a unified API. This is done using the `HttpApiBuilder.api` API, which generates a `Layer`. You then use `Layer.provide` to include the implementations of all the groups into the top-level `HttpApi`.\n\n**Example** (Combining Group Implementations into a Top-Level API)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSchema\n} from \"@effect/platform\"\nimport { DateTime, Effect, Layer, Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst usersGroup = HttpApiGroup.make(\"users\").add(\n  HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`.addSuccess(User)\n)\n\nconst api = HttpApi.make(\"myApi\").add(usersGroup)\n\nconst usersGroupLive = HttpApiBuilder.group(api, \"users\", (handlers) =>\n  handlers.handle(\"getUser\", ({ path: { id } }) =>\n    Effect.succeed({\n      id,\n      name: \"John Doe\",\n      createdAt: DateTime.unsafeNow()\n    })\n  )\n)\n\n// Combine all group implementations into the top-level API\n//\n//      ┌─── Layer<HttpApi.Api, never, never>\n//      ▼\nconst MyApiLive = HttpApiBuilder.api(api).pipe(Layer.provide(usersGroupLive))\n```\n\n### Serving the API\n\nYou can serve your API using the `HttpApiBuilder.serve` function. This utility builds an `HttpApp` from an `HttpApi` instance and uses an `HttpServer` to handle requests. Middleware can be added to customize or enhance the server's behavior.\n\n**Example** (Setting Up and Serving an API with Middleware)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSchema,\n  HttpMiddleware,\n  HttpServer\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { DateTime, Effect, Layer, Schema } from \"effect\"\nimport { createServer } from \"node:http\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst usersGroup = HttpApiGroup.make(\"users\").add(\n  HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`.addSuccess(User)\n)\n\nconst api = HttpApi.make(\"myApi\").add(usersGroup)\n\nconst usersGroupLive = HttpApiBuilder.group(api, \"users\", (handlers) =>\n  handlers.handle(\"getUser\", ({ path: { id } }) =>\n    Effect.succeed({\n      id,\n      name: \"John Doe\",\n      createdAt: DateTime.unsafeNow()\n    })\n  )\n)\n\nconst MyApiLive = HttpApiBuilder.api(api).pipe(Layer.provide(usersGroupLive))\n\n// Configure and serve the API\nconst HttpLive = HttpApiBuilder.serve(HttpMiddleware.logger).pipe(\n  // Add CORS middleware to handle cross-origin requests\n  Layer.provide(HttpApiBuilder.middlewareCors()),\n  // Provide the API implementation\n  Layer.provide(MyApiLive),\n  // Log the server's listening address\n  HttpServer.withLogAddress,\n  // Set up the Node.js HTTP server\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n)\n\n// Launch the server\nLayer.launch(HttpLive).pipe(NodeRuntime.runMain)\n```\n\n### Accessing the HttpServerRequest\n\nIn some cases, you may need to access details about the incoming `HttpServerRequest` within an endpoint handler. The HttpServerRequest module provides access to the request object, allowing you to inspect properties such as the HTTP method or headers.\n\n**Example** (Accessing the Request Object in a GET Endpoint)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpMiddleware,\n  HttpServer\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { Effect, Layer, Schema } from \"effect\"\nimport { createServer } from \"node:http\"\n\nconst api = HttpApi.make(\"myApi\").add(\n  HttpApiGroup.make(\"group\").add(\n    HttpApiEndpoint.get(\"get\", \"/\").addSuccess(Schema.String)\n  )\n)\n\nconst groupLive = HttpApiBuilder.group(api, \"group\", (handlers) =>\n  handlers.handle(\"get\", ({ request }) =>\n    Effect.gen(function* () {\n      // Log the HTTP method for demonstration purposes\n      console.log(request.method)\n\n      // Return a response\n      return \"Hello, World!\"\n    })\n  )\n)\n\nconst MyApiLive = HttpApiBuilder.api(api).pipe(Layer.provide(groupLive))\n\nconst HttpLive = HttpApiBuilder.serve(HttpMiddleware.logger).pipe(\n  Layer.provide(HttpApiBuilder.middlewareCors()),\n  Layer.provide(MyApiLive),\n  HttpServer.withLogAddress,\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n)\n\nLayer.launch(HttpLive).pipe(NodeRuntime.runMain)\n```\n\n### Streaming Requests\n\nStreaming requests allow you to send large or continuous data streams to the server. In this example, we define an API that accepts a stream of binary data and decodes it into a string.\n\n**Example** (Handling Streaming Requests)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSchema,\n  HttpMiddleware,\n  HttpServer\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { Effect, Layer, Schema } from \"effect\"\nimport { createServer } from \"node:http\"\n\nconst api = HttpApi.make(\"myApi\").add(\n  HttpApiGroup.make(\"group\").add(\n    HttpApiEndpoint.post(\"acceptStream\", \"/stream\")\n      // Define the payload as a Uint8Array with a specific encoding\n      .setPayload(\n        Schema.Uint8ArrayFromSelf.pipe(\n          HttpApiSchema.withEncoding({\n            kind: \"Uint8Array\",\n            contentType: \"application/octet-stream\"\n          })\n        )\n      )\n      .addSuccess(Schema.String)\n  )\n)\n\nconst groupLive = HttpApiBuilder.group(api, \"group\", (handlers) =>\n  handlers.handle(\"acceptStream\", (req) =>\n    // Decode the incoming binary data into a string\n    Effect.succeed(new TextDecoder().decode(req.payload))\n  )\n)\n\nconst MyApiLive = HttpApiBuilder.api(api).pipe(Layer.provide(groupLive))\n\nconst HttpLive = HttpApiBuilder.serve(HttpMiddleware.logger).pipe(\n  Layer.provide(HttpApiBuilder.middlewareCors()),\n  Layer.provide(MyApiLive),\n  HttpServer.withLogAddress,\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n)\n\nLayer.launch(HttpLive).pipe(NodeRuntime.runMain)\n```\n\nYou can test the streaming request using `curl` or any tool that supports sending binary data. For example:\n\n```sh\necho \"abc\" | curl -X POST 'http://localhost:3000/stream' --data-binary @- -H \"Content-Type: application/octet-stream\"\n# Output: abc\n```\n\n### Streaming Responses\n\nTo handle streaming responses in your API, you can return a raw `HttpServerResponse`. The `HttpServerResponse.stream` function is designed to return a continuous stream of data as the response.\n\n**Example** (Implementing a Streaming Endpoint)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSchema,\n  HttpMiddleware,\n  HttpServer,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { Layer, Schedule, Schema, Stream } from \"effect\"\nimport { createServer } from \"node:http\"\n\n// Define the API with a single streaming endpoint\nconst api = HttpApi.make(\"myApi\").add(\n  HttpApiGroup.make(\"group\").add(\n    HttpApiEndpoint.get(\"getStream\", \"/stream\").addSuccess(\n      Schema.String.pipe(\n        HttpApiSchema.withEncoding({\n          kind: \"Text\",\n          contentType: \"application/octet-stream\"\n        })\n      )\n    )\n  )\n)\n\n// Simulate a stream of data\nconst stream = Stream.make(\"a\", \"b\", \"c\").pipe(\n  Stream.schedule(Schedule.spaced(\"500 millis\")),\n  Stream.map((s) => new TextEncoder().encode(s))\n)\n\nconst groupLive = HttpApiBuilder.group(api, \"group\", (handlers) =>\n  handlers.handle(\"getStream\", () => HttpServerResponse.stream(stream))\n)\n\nconst MyApiLive = HttpApiBuilder.api(api).pipe(Layer.provide(groupLive))\n\nconst HttpLive = HttpApiBuilder.serve(HttpMiddleware.logger).pipe(\n  Layer.provide(HttpApiBuilder.middlewareCors()),\n  Layer.provide(MyApiLive),\n  HttpServer.withLogAddress,\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n)\n\nLayer.launch(HttpLive).pipe(NodeRuntime.runMain)\n```\n\nYou can test the streaming response using `curl` or any similar HTTP client that supports streaming:\n\n```sh\ncurl 'http://localhost:3000/stream' --no-buffer\n```\n\nThe response will stream data (`a`, `b`, `c`) with a 500ms interval between each item.\n\n## Middlewares\n\n### Defining Middleware\n\nThe `HttpApiMiddleware` module allows you to add middleware to your API. Middleware can enhance your API by introducing features like logging, authentication, or additional error handling.\n\nYou can define middleware using the `HttpApiMiddleware.Tag` class, which lets you specify:\n\n| Option     | Description                                                                                                                                                                                                                     |\n| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `failure`  | A schema that describes any errors the middleware might return.                                                                                                                                                                 |\n| `provides` | A `Context.Tag` representing the resource or data the middleware will provide to subsequent handlers.                                                                                                                           |\n| `security` | Definitions from `HttpApiSecurity` that the middleware will implement, such as authentication mechanisms.                                                                                                                       |\n| `optional` | A boolean indicating whether the request should continue if the middleware fails with an expected error. When `optional` is set to `true`, the `provides` and `failure` options do not affect the final error type or handlers. |\n\n**Example** (Defining a Logger Middleware)\n\n```ts\nimport {\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiMiddleware,\n  HttpApiSchema\n} from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\n// Define a schema for errors returned by the logger middleware\nclass LoggerError extends Schema.TaggedError<LoggerError>()(\n  \"LoggerError\",\n  {}\n) {}\n\n// Extend the HttpApiMiddleware.Tag class to define the logger middleware tag\nclass Logger extends HttpApiMiddleware.Tag<Logger>()(\"Http/Logger\", {\n  // Optionally define the error schema for the middleware\n  failure: LoggerError\n}) {}\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst usersGroup = HttpApiGroup.make(\"users\")\n  .add(\n    HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`\n      .addSuccess(User)\n      // Apply the middleware to a single endpoint\n      .middleware(Logger)\n  )\n  // Or apply the middleware to the entire group\n  .middleware(Logger)\n```\n\n### Implementing HttpApiMiddleware\n\nOnce you have defined your `HttpApiMiddleware`, you can implement it as a `Layer`. This allows the middleware to be applied to specific API groups or endpoints, enabling modular and reusable behavior.\n\n**Example** (Implementing and Using Logger Middleware)\n\n```ts\nimport { HttpApiMiddleware, HttpServerRequest } from \"@effect/platform\"\nimport { Effect, Layer } from \"effect\"\n\nclass Logger extends HttpApiMiddleware.Tag<Logger>()(\"Http/Logger\") {}\n\nconst LoggerLive = Layer.effect(\n  Logger,\n  Effect.gen(function* () {\n    yield* Effect.log(\"creating Logger middleware\")\n\n    // Middleware implementation as an Effect\n    // that can access the `HttpServerRequest` context.\n    return Effect.gen(function* () {\n      const request = yield* HttpServerRequest.HttpServerRequest\n      yield* Effect.log(`Request: ${request.method} ${request.url}`)\n    })\n  })\n)\n```\n\nAfter implementing the middleware, you can attach it to your API groups or specific endpoints using the `Layer` APIs.\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiMiddleware,\n  HttpApiSchema,\n  HttpServerRequest\n} from \"@effect/platform\"\nimport { DateTime, Effect, Layer, Schema } from \"effect\"\n\n// Define a schema for errors returned by the logger middleware\nclass LoggerError extends Schema.TaggedError<LoggerError>()(\n  \"LoggerError\",\n  {}\n) {}\n\n// Extend the HttpApiMiddleware.Tag class to define the logger middleware tag\nclass Logger extends HttpApiMiddleware.Tag<Logger>()(\"Http/Logger\", {\n  // Optionally define the error schema for the middleware\n  failure: LoggerError\n}) {}\n\nconst LoggerLive = Layer.effect(\n  Logger,\n  Effect.gen(function* () {\n    yield* Effect.log(\"creating Logger middleware\")\n\n    // Middleware implementation as an Effect\n    // that can access the `HttpServerRequest` context.\n    return Effect.gen(function* () {\n      const request = yield* HttpServerRequest.HttpServerRequest\n      yield* Effect.log(`Request: ${request.method} ${request.url}`)\n    })\n  })\n)\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst usersGroup = HttpApiGroup.make(\"users\")\n  .add(\n    HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`\n      .addSuccess(User)\n      // Apply the middleware to a single endpoint\n      .middleware(Logger)\n  )\n  // Or apply the middleware to the entire group\n  .middleware(Logger)\n\nconst api = HttpApi.make(\"myApi\").add(usersGroup)\n\nconst usersGroupLive = HttpApiBuilder.group(api, \"users\", (handlers) =>\n  handlers.handle(\"getUser\", (req) =>\n    Effect.succeed({\n      id: req.path.id,\n      name: \"John Doe\",\n      createdAt: DateTime.unsafeNow()\n    })\n  )\n).pipe(\n  // Provide the Logger middleware to the group\n  Layer.provide(LoggerLive)\n)\n```\n\n### Defining security middleware\n\nThe `HttpApiSecurity` module enables you to add security annotations to your API. These annotations specify the type of authorization required to access specific endpoints.\n\nSupported authorization types include:\n\n| Authorization Type       | Description                                                      |\n| ------------------------ | ---------------------------------------------------------------- |\n| `HttpApiSecurity.apiKey` | API key authorization via headers, query parameters, or cookies. |\n| `HttpApiSecurity.basic`  | HTTP Basic authentication.                                       |\n| `HttpApiSecurity.bearer` | Bearer token authentication.                                     |\n\nThese security annotations can be used alongside `HttpApiMiddleware` to create middleware that protects your API endpoints.\n\n**Example** (Defining Security Middleware)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiMiddleware,\n  HttpApiSchema,\n  HttpApiSecurity\n} from \"@effect/platform\"\nimport { Context, Schema } from \"effect\"\n\n// Define a schema for the \"User\"\nclass User extends Schema.Class<User>(\"User\")({ id: Schema.Number }) {}\n\n// Define a schema for the \"Unauthorized\" error\nclass Unauthorized extends Schema.TaggedError<Unauthorized>()(\n  \"Unauthorized\",\n  {},\n  // Specify the HTTP status code for unauthorized errors\n  HttpApiSchema.annotations({ status: 401 })\n) {}\n\n// Define a Context.Tag for the authenticated user\nclass CurrentUser extends Context.Tag(\"CurrentUser\")<CurrentUser, User>() {}\n\n// Create the Authorization middleware\nclass Authorization extends HttpApiMiddleware.Tag<Authorization>()(\n  \"Authorization\",\n  {\n    // Define the error schema for unauthorized access\n    failure: Unauthorized,\n    // Specify the resource this middleware will provide\n    provides: CurrentUser,\n    // Add security definitions\n    security: {\n      // ┌─── Custom name for the security definition\n      // ▼\n      myBearer: HttpApiSecurity.bearer\n      // Additional security definitions can be added here.\n      // They will attempt to be resolved in the order they are defined.\n    }\n  }\n) {}\n\nconst api = HttpApi.make(\"api\")\n  .add(\n    HttpApiGroup.make(\"group\")\n      .add(\n        HttpApiEndpoint.get(\"get\", \"/\")\n          .addSuccess(Schema.String)\n          // Apply the middleware to a single endpoint\n          .middleware(Authorization)\n      )\n      // Or apply the middleware to the entire group\n      .middleware(Authorization)\n  )\n  // Or apply the middleware to the entire API\n  .middleware(Authorization)\n```\n\n### Implementing HttpApiSecurity middleware\n\nWhen using `HttpApiSecurity` in your middleware, the implementation involves creating a `Layer` with security handlers tailored to your requirements. Below is an example demonstrating how to implement middleware for `HttpApiSecurity.bearer` authentication.\n\n**Example** (Implementing Bearer Token Authentication Middleware)\n\n```ts\nimport {\n  HttpApiMiddleware,\n  HttpApiSchema,\n  HttpApiSecurity\n} from \"@effect/platform\"\nimport { Context, Effect, Layer, Redacted, Schema } from \"effect\"\n\nclass User extends Schema.Class<User>(\"User\")({ id: Schema.Number }) {}\n\nclass Unauthorized extends Schema.TaggedError<Unauthorized>()(\n  \"Unauthorized\",\n  {},\n  HttpApiSchema.annotations({ status: 401 })\n) {}\n\nclass CurrentUser extends Context.Tag(\"CurrentUser\")<CurrentUser, User>() {}\n\nclass Authorization extends HttpApiMiddleware.Tag<Authorization>()(\n  \"Authorization\",\n  {\n    failure: Unauthorized,\n    provides: CurrentUser,\n    security: {\n      myBearer: HttpApiSecurity.bearer\n    }\n  }\n) {}\n\nconst AuthorizationLive = Layer.effect(\n  Authorization,\n  Effect.gen(function* () {\n    yield* Effect.log(\"creating Authorization middleware\")\n\n    // Return the security handlers for the middleware\n    return {\n      // Define the handler for the Bearer token\n      // The Bearer token is redacted for security\n      myBearer: (bearerToken) =>\n        Effect.gen(function* () {\n          yield* Effect.log(\n            \"checking bearer token\",\n            Redacted.value(bearerToken)\n          )\n          // Return a mock User object as the CurrentUser\n          return new User({ id: 1 })\n        })\n    }\n  })\n)\n```\n\n### Adding Descriptions to Security Definitions\n\nThe `HttpApiSecurity.annotate` function allows you to add metadata, such as a description, to your security definitions. This metadata is displayed in the Swagger documentation, making it easier for developers to understand your API's security requirements.\n\n**Example** (Adding a Description to a Bearer Token Security Definition)\n\n```ts\nimport {\n  HttpApiMiddleware,\n  HttpApiSchema,\n  HttpApiSecurity,\n  OpenApi\n} from \"@effect/platform\"\nimport { Context, Schema } from \"effect\"\n\nclass User extends Schema.Class<User>(\"User\")({ id: Schema.Number }) {}\n\nclass Unauthorized extends Schema.TaggedError<Unauthorized>()(\n  \"Unauthorized\",\n  {},\n  HttpApiSchema.annotations({ status: 401 })\n) {}\n\nclass CurrentUser extends Context.Tag(\"CurrentUser\")<CurrentUser, User>() {}\n\nclass Authorization extends HttpApiMiddleware.Tag<Authorization>()(\n  \"Authorization\",\n  {\n    failure: Unauthorized,\n    provides: CurrentUser,\n    security: {\n      myBearer: HttpApiSecurity.bearer.pipe(\n        // Add a description to the security definition\n        HttpApiSecurity.annotate(OpenApi.Description, \"my description\")\n      )\n    }\n  }\n) {}\n```\n\n### Setting HttpApiSecurity cookies\n\nTo set a security cookie from within a handler, you can use the `HttpApiBuilder.securitySetCookie` API. This method sets a cookie with default properties, including the `HttpOnly` and `Secure` flags, ensuring the cookie is not accessible via JavaScript and is transmitted over secure connections.\n\n**Example** (Setting a Security Cookie in a Login Handler)\n\n```ts\n// Define the security configuration for an API key stored in a cookie\nconst security = HttpApiSecurity.apiKey({\n   // Specify that the API key is stored in a cookie\n  in: \"cookie\"\n   // Define the cookie name,\n  key: \"token\"\n})\n\nconst UsersApiLive = HttpApiBuilder.group(MyApi, \"users\", (handlers) =>\n  handlers.handle(\"login\", () =>\n    // Set the security cookie with a redacted value\n    HttpApiBuilder.securitySetCookie(security, Redacted.make(\"keep me secret\"))\n  )\n)\n```\n\n## Serving Swagger documentation\n\nYou can add Swagger documentation to your API using the `HttpApiSwagger` module. This integration provides an interactive interface for developers to explore and test your API. To enable Swagger, you simply provide the `HttpApiSwagger.layer` to your server implementation.\n\n**Example** (Adding Swagger Documentation to an API)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSchema,\n  HttpApiSwagger,\n  HttpMiddleware,\n  HttpServer\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { DateTime, Effect, Layer, Schema } from \"effect\"\nimport { createServer } from \"node:http\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst usersGroup = HttpApiGroup.make(\"users\").add(\n  HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`.addSuccess(User)\n)\n\nconst api = HttpApi.make(\"myApi\").add(usersGroup)\n\nconst usersGroupLive = HttpApiBuilder.group(api, \"users\", (handlers) =>\n  handlers.handle(\"getUser\", ({ path: { id } }) =>\n    Effect.succeed({\n      id,\n      name: \"John Doe\",\n      createdAt: DateTime.unsafeNow()\n    })\n  )\n)\n\nconst MyApiLive = HttpApiBuilder.api(api).pipe(Layer.provide(usersGroupLive))\n\nconst HttpLive = HttpApiBuilder.serve(HttpMiddleware.logger).pipe(\n  // Add the Swagger documentation layer\n  Layer.provide(\n    HttpApiSwagger.layer({\n      // Specify the Swagger documentation path.\n      // \"/docs\" is the default path.\n      path: \"/docs\"\n    })\n  ),\n  Layer.provide(HttpApiBuilder.middlewareCors()),\n  Layer.provide(MyApiLive),\n  HttpServer.withLogAddress,\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n)\n\nLayer.launch(HttpLive).pipe(NodeRuntime.runMain)\n```\n\n![Swagger Documentation](./images/swagger-myapi.png)\n\n### Adding OpenAPI Annotations\n\nYou can add OpenAPI annotations to your API to include metadata such as titles, descriptions, and more. These annotations help generate richer API documentation.\n\n#### HttpApi\n\nBelow is a list of available annotations for a top-level `HttpApi`. They can be added using the `.annotate` method:\n\n| Annotation                  | Description                                                                                                        |\n| --------------------------- | ------------------------------------------------------------------------------------------------------------------ |\n| `HttpApi.AdditionalSchemas` | Adds custom schemas to the final OpenAPI specification. Only schemas with an `identifier` annotation are included. |\n| `OpenApi.Description`       | Sets a general description for the API.                                                                            |\n| `OpenApi.License`           | Defines the license used by the API.                                                                               |\n| `OpenApi.Summary`           | Provides a brief summary of the API.                                                                               |\n| `OpenApi.Servers`           | Lists server URLs and optional metadata such as variables.                                                         |\n| `OpenApi.Override`          | Merges the supplied fields into the resulting specification.                                                       |\n| `OpenApi.Transform`         | Allows you to modify the final specification with a custom function.                                               |\n\n**Example** (Annotating the Top-Level API)\n\n```ts\nimport { HttpApi, OpenApi } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst api = HttpApi.make(\"api\")\n  // Provide additional schemas\n  .annotate(HttpApi.AdditionalSchemas, [\n    Schema.String.annotations({ identifier: \"MyString\" })\n  ])\n  // Add a description\n  .annotate(OpenApi.Description, \"my description\")\n  // Set license information\n  .annotate(OpenApi.License, { name: \"MIT\", url: \"http://example.com\" })\n  // Provide a summary\n  .annotate(OpenApi.Summary, \"my summary\")\n  // Define servers\n  .annotate(OpenApi.Servers, [\n    {\n      url: \"http://example.com\",\n      description: \"example\",\n      variables: { a: { default: \"b\", enum: [\"c\"], description: \"d\" } }\n    }\n  ])\n  // Override parts of the generated specification\n  .annotate(OpenApi.Override, {\n    tags: [{ name: \"a\", description: \"a-description\" }]\n  })\n  // Apply a transform function to the final specification\n  .annotate(OpenApi.Transform, (spec) => ({\n    ...spec,\n    tags: [...spec.tags, { name: \"b\", description: \"b-description\" }]\n  }))\n\n// Generate the OpenAPI specification from the annotated API\nconst spec = OpenApi.fromApi(api)\n\nconsole.log(JSON.stringify(spec, null, 2))\n/*\nOutput:\n{\n  \"openapi\": \"3.1.0\",\n  \"info\": {\n    \"title\": \"Api\",\n    \"version\": \"0.0.1\",\n    \"description\": \"my description\",\n    \"license\": {\n      \"name\": \"MIT\",\n      \"url\": \"http://example.com\"\n    },\n    \"summary\": \"my summary\"\n  },\n  \"paths\": {},\n  \"tags\": [\n    { \"name\": \"a\", \"description\": \"a-description\" },\n    { \"name\": \"b\", \"description\": \"b-description\" }\n  ],\n  \"components\": {\n    \"schemas\": {\n      \"MyString\": {\n        \"type\": \"string\"\n      }\n    },\n    \"securitySchemes\": {}\n  },\n  \"security\": [],\n  \"servers\": [\n    {\n      \"url\": \"http://example.com\",\n      \"description\": \"example\",\n      \"variables\": {\n        \"a\": {\n          \"default\": \"b\",\n          \"enum\": [\n            \"c\"\n          ],\n          \"description\": \"d\"\n        }\n      }\n    }\n  ]\n}\n*/\n```\n\n#### HttpApiGroup\n\nThe following annotations can be added to an `HttpApiGroup`:\n\n| Annotation             | Description                                                           |\n| ---------------------- | --------------------------------------------------------------------- |\n| `OpenApi.Description`  | Sets a description for this group.                                    |\n| `OpenApi.ExternalDocs` | Provides external documentation links for the group.                  |\n| `OpenApi.Override`     | Merges specified fields into the resulting specification.             |\n| `OpenApi.Transform`    | Lets you modify the final group specification with a custom function. |\n| `OpenApi.Exclude`      | Excludes the group from the final OpenAPI specification.              |\n\n**Example** (Annotating a Group)\n\n```ts\nimport { HttpApi, HttpApiGroup, OpenApi } from \"@effect/platform\"\n\nconst api = HttpApi.make(\"api\")\n  .add(\n    HttpApiGroup.make(\"group\")\n      // Add a description for the group\n      .annotate(OpenApi.Description, \"my description\")\n      // Provide external documentation links\n      .annotate(OpenApi.ExternalDocs, {\n        url: \"http://example.com\",\n        description: \"example\"\n      })\n      // Override parts of the final output\n      .annotate(OpenApi.Override, { name: \"my name\" })\n      // Transform the final specification for this group\n      .annotate(OpenApi.Transform, (spec) => ({\n        ...spec,\n        name: spec.name + \"-transformed\"\n      }))\n  )\n  .add(\n    HttpApiGroup.make(\"excluded\")\n      // Exclude the group from the final specification\n      .annotate(OpenApi.Exclude, true)\n  )\n\n// Generate the OpenAPI spec\nconst spec = OpenApi.fromApi(api)\n\nconsole.log(JSON.stringify(spec, null, 2))\n/*\nOutput:\n{\n  \"openapi\": \"3.1.0\",\n  \"info\": {\n    \"title\": \"Api\",\n    \"version\": \"0.0.1\"\n  },\n  \"paths\": {},\n  \"tags\": [\n    {\n      \"name\": \"my name-transformed\",\n      \"description\": \"my description\",\n      \"externalDocs\": {\n        \"url\": \"http://example.com\",\n        \"description\": \"example\"\n      }\n    }\n  ],\n  \"components\": {\n    \"schemas\": {},\n    \"securitySchemes\": {}\n  },\n  \"security\": []\n}\n*/\n```\n\n#### HttpApiEndpoint\n\nFor an `HttpApiEndpoint`, you can use the following annotations:\n\n| Annotation             | Description                                                                 |\n| ---------------------- | --------------------------------------------------------------------------- |\n| `OpenApi.Description`  | Adds a description for this endpoint.                                       |\n| `OpenApi.Summary`      | Provides a short summary of the endpoint's purpose.                         |\n| `OpenApi.Deprecated`   | Marks the endpoint as deprecated.                                           |\n| `OpenApi.ExternalDocs` | Supplies external documentation links for the endpoint.                     |\n| `OpenApi.Override`     | Merges specified fields into the resulting specification for this endpoint. |\n| `OpenApi.Transform`    | Lets you modify the final endpoint specification with a custom function.    |\n| `OpenApi.Exclude`      | Excludes the endpoint from the final OpenAPI specification.                 |\n\n**Example** (Annotating an Endpoint)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  OpenApi\n} from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst api = HttpApi.make(\"api\").add(\n  HttpApiGroup.make(\"group\")\n    .add(\n      HttpApiEndpoint.get(\"get\", \"/\")\n        .addSuccess(Schema.String)\n        // Add a description\n        .annotate(OpenApi.Description, \"my description\")\n        // Provide a summary\n        .annotate(OpenApi.Summary, \"my summary\")\n        // Mark the endpoint as deprecated\n        .annotate(OpenApi.Deprecated, true)\n        // Provide external documentation\n        .annotate(OpenApi.ExternalDocs, {\n          url: \"http://example.com\",\n          description: \"example\"\n        })\n    )\n    .add(\n      HttpApiEndpoint.get(\"excluded\", \"/excluded\")\n        .addSuccess(Schema.String)\n        // Exclude this endpoint from the final specification\n        .annotate(OpenApi.Exclude, true)\n    )\n)\n\n// Generate the OpenAPI spec\nconst spec = OpenApi.fromApi(api)\n\nconsole.log(JSON.stringify(spec, null, 2))\n/*\nOutput:\n{\n  \"openapi\": \"3.1.0\",\n  \"info\": {\n    \"title\": \"Api\",\n    \"version\": \"0.0.1\"\n  },\n  \"paths\": {\n    \"/\": {\n      \"get\": {\n        \"tags\": [\n          \"group\"\n        ],\n        \"operationId\": \"my operationId-transformed\",\n        \"parameters\": [],\n        \"security\": [],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"a string\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"The request did not match the expected schema\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n                }\n              }\n            }\n          }\n        },\n        \"description\": \"my description\",\n        \"summary\": \"my summary\",\n        \"deprecated\": true,\n        \"externalDocs\": {\n          \"url\": \"http://example.com\",\n          \"description\": \"example\"\n        }\n      }\n    }\n  },\n  ...\n}\n*/\n```\n\nThe default response description is \"Success\". You can override this by annotating the schema.\n\n**Example** (Defining a custom response description)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  OpenApi\n} from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n}).annotations({ identifier: \"User\" })\n\nconst api = HttpApi.make(\"api\").add(\n  HttpApiGroup.make(\"group\").add(\n    HttpApiEndpoint.get(\"getUsers\", \"/users\").addSuccess(\n      Schema.Array(User).annotations({\n        description: \"Returns an array of users\"\n      })\n    )\n  )\n)\n\nconst spec = OpenApi.fromApi(api)\n\nconsole.log(JSON.stringify(spec.paths, null, 2))\n/*\nOutput:\n{\n  \"/users\": {\n    \"get\": {\n      \"tags\": [\n        \"group\"\n      ],\n      \"operationId\": \"group.getUsers\",\n      \"parameters\": [],\n      \"security\": [],\n      \"responses\": {\n        \"200\": {\n          \"description\": \"Returns an array of users\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                },\n                \"description\": \"Returns an array of users\"\n              }\n            }\n          }\n        },\n        \"400\": {\n          \"description\": \"The request did not match the expected schema\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n*/\n```\n\n### Top Level Groups\n\nWhen a group is marked as `topLevel`, the operation IDs of its endpoints do not include the group name as a prefix. This is helpful when you want to group endpoints under a shared tag without adding a redundant prefix to their operation IDs.\n\n**Example** (Using a Top-Level Group)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  OpenApi\n} from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst api = HttpApi.make(\"api\").add(\n  // Mark the group as top-level\n  HttpApiGroup.make(\"group\", { topLevel: true }).add(\n    HttpApiEndpoint.get(\"get\", \"/\").addSuccess(Schema.String)\n  )\n)\n\n// Generate the OpenAPI spec\nconst spec = OpenApi.fromApi(api)\n\nconsole.log(JSON.stringify(spec.paths, null, 2))\n/*\nOutput:\n{\n  \"/\": {\n    \"get\": {\n      \"tags\": [\n        \"group\"\n      ],\n      \"operationId\": \"get\", // The operation ID is not prefixed with \"group\"\n      \"parameters\": [],\n      \"security\": [],\n      \"responses\": {\n        \"200\": {\n          \"description\": \"a string\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"type\": \"string\"\n              }\n            }\n          }\n        },\n        \"400\": {\n          \"description\": \"The request did not match the expected schema\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/HttpApiDecodeError\"\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n*/\n```\n\n## Deriving a Client\n\nAfter defining your API, you can derive a client that interacts with the server. The `HttpApiClient` module simplifies the process by providing tools to generate a client based on your API definition.\n\n**Example** (Deriving and Using a Client)\n\nThis example demonstrates how to create a client for an API and use it to call an endpoint.\n\n```ts\nimport {\n  FetchHttpClient,\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiClient,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSchema,\n  HttpApiSwagger,\n  HttpMiddleware,\n  HttpServer\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { DateTime, Effect, Layer, Schema } from \"effect\"\nimport { createServer } from \"node:http\"\n\nconst User = Schema.Struct({\n  id: Schema.Number,\n  name: Schema.String,\n  createdAt: Schema.DateTimeUtc\n})\n\nconst idParam = HttpApiSchema.param(\"id\", Schema.NumberFromString)\n\nconst usersGroup = HttpApiGroup.make(\"users\").add(\n  HttpApiEndpoint.get(\"getUser\")`/user/${idParam}`.addSuccess(User)\n)\n\nconst api = HttpApi.make(\"myApi\").add(usersGroup)\n\nconst usersGroupLive = HttpApiBuilder.group(api, \"users\", (handlers) =>\n  handlers.handle(\"getUser\", ({ path: { id } }) =>\n    Effect.succeed({\n      id,\n      name: \"John Doe\",\n      createdAt: DateTime.unsafeNow()\n    })\n  )\n)\n\nconst MyApiLive = HttpApiBuilder.api(api).pipe(Layer.provide(usersGroupLive))\n\nconst HttpLive = HttpApiBuilder.serve(HttpMiddleware.logger).pipe(\n  Layer.provide(HttpApiSwagger.layer()),\n  Layer.provide(HttpApiBuilder.middlewareCors()),\n  Layer.provide(MyApiLive),\n  HttpServer.withLogAddress,\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 }))\n)\n\nLayer.launch(HttpLive).pipe(NodeRuntime.runMain)\n\n// Create a program that derives and uses the client\nconst program = Effect.gen(function* () {\n  // Derive the client\n  const client = yield* HttpApiClient.make(api, {\n    baseUrl: \"http://localhost:3000\"\n  })\n  // Call the `getUser` endpoint\n  const user = yield* client.users.getUser({ path: { id: 1 } })\n  console.log(user)\n})\n\n// Provide a Fetch-based HTTP client and run the program\nEffect.runFork(program.pipe(Effect.provide(FetchHttpClient.layer)))\n/*\nExample Output:\nUser {\n  id: 1,\n  name: 'John Doe',\n  createdAt: DateTime.Utc(2025-01-04T15:14:49.562Z)\n}\n*/\n```\n\n### Top Level Groups\n\nWhen a group is marked as `topLevel`, the methods on the client are not nested under the group name. This can simplify client usage by providing direct access to the endpoint methods.\n\n**Example** (Using a Top-Level Group in the Client)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiClient,\n  HttpApiEndpoint,\n  HttpApiGroup\n} from \"@effect/platform\"\nimport { Effect, Schema } from \"effect\"\n\nconst api = HttpApi.make(\"api\").add(\n  // Mark the group as top-level\n  HttpApiGroup.make(\"group\", { topLevel: true }).add(\n    HttpApiEndpoint.get(\"get\", \"/\").addSuccess(Schema.String)\n  )\n)\n\nconst program = Effect.gen(function* () {\n  const client = yield* HttpApiClient.make(api, {\n    baseUrl: \"http://localhost:3000\"\n  })\n  // The `get` method is not nested under the \"group\" name\n  const user = yield* client.get()\n  console.log(user)\n})\n```\n\n## Converting to a Web Handler\n\nYou can convert your `HttpApi` implementation into a web handler using the `HttpApiBuilder.toWebHandler` API. This approach enables you to serve your API through a custom server setup.\n\n**Example** (Creating and Serving a Web Handler)\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiSwagger,\n  HttpServer\n} from \"@effect/platform\"\nimport { Effect, Layer, Schema } from \"effect\"\nimport * as http from \"node:http\"\n\nconst api = HttpApi.make(\"myApi\").add(\n  HttpApiGroup.make(\"group\").add(\n    HttpApiEndpoint.get(\"get\", \"/\").addSuccess(Schema.String)\n  )\n)\n\nconst groupLive = HttpApiBuilder.group(api, \"group\", (handlers) =>\n  handlers.handle(\"get\", () => Effect.succeed(\"Hello, world!\"))\n)\n\nconst MyApiLive = HttpApiBuilder.api(api).pipe(Layer.provide(groupLive))\n\nconst SwaggerLayer = HttpApiSwagger.layer().pipe(Layer.provide(MyApiLive))\n\n// Convert the API to a web handler\nconst { dispose, handler } = HttpApiBuilder.toWebHandler(\n  Layer.mergeAll(MyApiLive, SwaggerLayer, HttpServer.layerContext)\n)\n\n// Serving the handler using a custom HTTP server\nhttp\n  .createServer(async (req, res) => {\n    const url = `http://${req.headers.host}${req.url}`\n    const init: RequestInit = {\n      method: req.method!\n    }\n\n    const response = await handler(new Request(url, init))\n\n    res.writeHead(\n      response.status,\n      response.statusText,\n      Object.fromEntries(response.headers.entries())\n    )\n    const responseBody = await response.arrayBuffer()\n    res.end(Buffer.from(responseBody))\n  })\n  .listen(3000, () => {\n    console.log(\"Server running at http://localhost:3000/\")\n  })\n  .on(\"close\", () => {\n    dispose()\n  })\n```\n\n# HTTP Client\n\n## Overview\n\nThe `@effect/platform/HttpClient*` modules provide a way to send HTTP requests,\nhandle responses, and abstract over the differences between platforms.\n\nThe `HttpClient` interface has a set of methods for sending requests:\n\n- `.execute` - takes a [HttpClientRequest](#httpclientrequest) and returns a `HttpClientResponse`\n- `.{get, del, head, options, patch, post, put}` - convenience methods for creating a request and\n  executing it in one step\n\nTo access the `HttpClient`, you can use the `HttpClient.HttpClient` [tag](https://effect.website/docs/guides/context-management/services).\nThis will give you access to a `HttpClient` instance.\n\n**Example: Retrieving JSON Data (GET)**\n\n```ts\nimport { FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { Effect } from \"effect\"\n\nconst program = Effect.gen(function* () {\n  // Access HttpClient\n  const client = yield* HttpClient.HttpClient\n\n  // Create and execute a GET request\n  const response = yield* client.get(\n    \"https://jsonplaceholder.typicode.com/posts/1\"\n  )\n\n  const json = yield* response.json\n\n  console.log(json)\n}).pipe(\n  // Provide the HttpClient\n  Effect.provide(FetchHttpClient.layer)\n)\n\nEffect.runPromise(program)\n/*\nOutput:\n{\n  userId: 1,\n  id: 1,\n  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',\n  body: 'quia et suscipit\\n' +\n    'suscipit recusandae consequuntur expedita et cum\\n' +\n    'reprehenderit molestiae ut ut quas totam\\n' +\n    'nostrum rerum est autem sunt rem eveniet architecto'\n}\n*/\n```\n\n**Example: Retrieving JSON Data with accessor apis (GET)**\n\nThe `HttpClient` module also provides a set of accessor apis that allow you to\neasily send requests without first accessing the `HttpClient` service.\n\nBelow is an example of using the `get` accessor api to send a GET request:\n\n(The following examples will continue to use the `HttpClient` service approach).\n\n```ts\nimport { FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { Effect } from \"effect\"\n\nconst program = HttpClient.get(\n  \"https://jsonplaceholder.typicode.com/posts/1\"\n).pipe(\n  Effect.andThen((response) => response.json),\n  Effect.provide(FetchHttpClient.layer)\n)\n\nEffect.runPromise(program)\n/*\nOutput:\n{\n  userId: 1,\n  id: 1,\n  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',\n  body: 'quia et suscipit\\n' +\n    'suscipit recusandae consequuntur expedita et cum\\n' +\n    'reprehenderit molestiae ut ut quas totam\\n' +\n    'nostrum rerum est autem sunt rem eveniet architecto'\n}\n*/\n```\n\n**Example: Creating and Executing a Custom Request**\n\nUsing [HttpClientRequest](#httpclientrequest), you can create and then execute a request. This is useful for customizing the request further.\n\n```ts\nimport {\n  FetchHttpClient,\n  HttpClient,\n  HttpClientRequest\n} from \"@effect/platform\"\nimport { Effect } from \"effect\"\n\nconst program = Effect.gen(function* () {\n  // Access HttpClient\n  const client = yield* HttpClient.HttpClient\n\n  // Create a GET request\n  const req = HttpClientRequest.get(\n    \"https://jsonplaceholder.typicode.com/posts/1\"\n  )\n\n  // Optionally customize the request\n\n  // Execute the request and get the response\n  const response = yield* client.execute(req)\n\n  const json = yield* response.json\n\n  console.log(json)\n}).pipe(\n  // Provide the HttpClient\n  Effect.provide(FetchHttpClient.layer)\n)\n\nEffect.runPromise(program)\n/*\nOutput:\n{\n  userId: 1,\n  id: 1,\n  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',\n  body: 'quia et suscipit\\n' +\n    'suscipit recusandae consequuntur expedita et cum\\n' +\n    'reprehenderit molestiae ut ut quas totam\\n' +\n    'nostrum rerum est autem sunt rem eveniet architecto'\n}\n*/\n```\n\n## Customize a HttpClient\n\nThe `HttpClient` module allows you to customize the client in various ways. For instance, you can log details of a request before execution using the `tapRequest` function.\n\n**Example: Tapping**\n\n```ts\nimport { FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { Console, Effect } from \"effect\"\n\nconst program = Effect.gen(function* () {\n  const client = (yield* HttpClient.HttpClient).pipe(\n    // Log the request before fetching\n    HttpClient.tapRequest(Console.log)\n  )\n\n  const response = yield* client.get(\n    \"https://jsonplaceholder.typicode.com/posts/1\"\n  )\n\n  const json = yield* response.json\n\n  console.log(json)\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\nEffect.runPromise(program)\n/*\nOutput:\n{\n  _id: '@effect/platform/HttpClientRequest',\n  method: 'GET',\n  url: 'https://jsonplaceholder.typicode.com/posts/1',\n  urlParams: [],\n  hash: { _id: 'Option', _tag: 'None' },\n  headers: Object <[Object: null prototype]> {},\n  body: { _id: '@effect/platform/HttpBody', _tag: 'Empty' }\n}\n{\n  userId: 1,\n  id: 1,\n  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',\n  body: 'quia et suscipit\\n' +\n    'suscipit recusandae consequuntur expedita et cum\\n' +\n    'reprehenderit molestiae ut ut quas totam\\n' +\n    'nostrum rerum est autem sunt rem eveniet architecto'\n}\n*/\n```\n\n**Operations Summary**\n\n| Operation                | Description                                                                             |\n| ------------------------ | --------------------------------------------------------------------------------------- |\n| `get`,`post`,`put`...    | Send a request without first accessing the `HttpClient` service.                        |\n| `filterOrElse`           | Filters the result of a response, or runs an alternative effect if the predicate fails. |\n| `filterOrFail`           | Filters the result of a response, or throws an error if the predicate fails.            |\n| `filterStatus`           | Filters responses by HTTP status code.                                                  |\n| `filterStatusOk`         | Filters responses that return a 2xx status code.                                        |\n| `followRedirects`        | Follows HTTP redirects up to a specified number of times.                               |\n| `mapRequest`             | Appends a transformation of the request object before sending it.                       |\n| `mapRequestEffect`       | Appends an effectful transformation of the request object before sending it.            |\n| `mapRequestInput`        | Prepends a transformation of the request object before sending it.                      |\n| `mapRequestInputEffect`  | Prepends an effectful transformation of the request object before sending it.           |\n| `retry`                  | Retries the request based on a provided schedule or policy.                             |\n| `tap`                    | Performs an additional effect after a successful request.                               |\n| `tapRequest`             | Performs an additional effect on the request before sending it.                         |\n| `withCookiesRef`         | Associates a `Ref` of cookies with the client for handling cookies across requests.     |\n| `withTracerDisabledWhen` | Disables tracing for specific requests based on a provided predicate.                   |\n| `withTracerPropagation`  | Enables or disables tracing propagation for the request.                                |\n\n### Mapping Requests\n\nNote that `mapRequest` and `mapRequestEffect` add transformations at the end of the request chain, while `mapRequestInput` and `mapRequestInputEffect` apply transformations at the start:\n\n```ts\nimport { FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { Effect } from \"effect\"\n\nconst program = Effect.gen(function* () {\n  const client = (yield* HttpClient.HttpClient).pipe(\n    // Append transformation\n    HttpClient.mapRequest((req) => {\n      console.log(1)\n      return req\n    }),\n    // Another append transformation\n    HttpClient.mapRequest((req) => {\n      console.log(2)\n      return req\n    }),\n    // Prepend transformation, this executes first\n    HttpClient.mapRequestInput((req) => {\n      console.log(3)\n      return req\n    })\n  )\n\n  const response = yield* client.get(\n    \"https://jsonplaceholder.typicode.com/posts/1\"\n  )\n\n  const json = yield* response.json\n\n  console.log(json)\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\nEffect.runPromise(program)\n/*\nOutput:\n3\n1\n2\n{\n  userId: 1,\n  id: 1,\n  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',\n  body: 'quia et suscipit\\n' +\n    'suscipit recusandae consequuntur expedita et cum\\n' +\n    'reprehenderit molestiae ut ut quas totam\\n' +\n    'nostrum rerum est autem sunt rem eveniet architecto'\n}\n*/\n```\n\n### Persisting Cookies\n\nYou can manage cookies across requests using the `HttpClient.withCookiesRef` function, which associates a reference to a `Cookies` object with the client.\n\n```ts\nimport { Cookies, FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { Effect, Ref } from \"effect\"\n\nconst program = Effect.gen(function* () {\n  // Create a reference to store cookies\n  const ref = yield* Ref.make(Cookies.empty)\n\n  // Access the HttpClient and associate the cookies reference with it\n  const client = (yield* HttpClient.HttpClient).pipe(\n    HttpClient.withCookiesRef(ref)\n  )\n\n  // Make a GET request to the specified URL\n  yield* client.get(\"https://www.google.com/\")\n\n  // Log the keys of the cookies stored in the reference\n  console.log(Object.keys((yield* ref).cookies))\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\nEffect.runPromise(program)\n// Output: [ 'SOCS', 'AEC', '__Secure-ENID' ]\n```\n\n## RequestInit Options\n\nYou can customize the `FetchHttpClient` by passing `RequestInit` options to configure aspects of the HTTP requests, such as credentials, headers, and more.\n\nIn this example, we customize the `FetchHttpClient` to include credentials with every request:\n\n```ts\nimport { FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { Effect, Layer } from \"effect\"\n\nconst CustomFetchLive = FetchHttpClient.layer.pipe(\n  Layer.provide(\n    Layer.succeed(FetchHttpClient.RequestInit, {\n      credentials: \"include\"\n    })\n  )\n)\n\nconst program = Effect.gen(function* () {\n  const client = yield* HttpClient.HttpClient\n  const response = yield* client.get(\n    \"https://jsonplaceholder.typicode.com/posts/1\"\n  )\n  const json = yield* response.json\n  console.log(json)\n}).pipe(Effect.provide(CustomFetchLive))\n```\n\n## Create a Custom HttpClient\n\nYou can create a custom `HttpClient` using the `HttpClient.make` function. This allows you to simulate or mock server responses within your application.\n\n```ts\nimport { HttpClient, HttpClientResponse } from \"@effect/platform\"\nimport { Effect, Layer } from \"effect\"\n\nconst myClient = HttpClient.make((req) =>\n  Effect.succeed(\n    HttpClientResponse.fromWeb(\n      req,\n      // Simulate a response from a server\n      new Response(\n        JSON.stringify({\n          userId: 1,\n          id: 1,\n          title: \"title...\",\n          body: \"body...\"\n        })\n      )\n    )\n  )\n)\n\nconst program = Effect.gen(function* () {\n  const client = yield* HttpClient.HttpClient\n  const response = yield* client.get(\n    \"https://jsonplaceholder.typicode.com/posts/1\"\n  )\n  const json = yield* response.json\n  console.log(json)\n}).pipe(\n  // Provide the HttpClient\n  Effect.provide(Layer.succeed(HttpClient.HttpClient, myClient))\n)\n\nEffect.runPromise(program)\n/*\nOutput:\n{ userId: 1, id: 1, title: 'title...', body: 'body...' }\n*/\n```\n\n## HttpClientRequest\n\n### Overview\n\nYou can create a `HttpClientRequest` using the following provided constructors:\n\n| Constructor                 | Description               |\n| --------------------------- | ------------------------- |\n| `HttpClientRequest.del`     | Create a DELETE request   |\n| `HttpClientRequest.get`     | Create a GET request      |\n| `HttpClientRequest.head`    | Create a HEAD request     |\n| `HttpClientRequest.options` | Create an OPTIONS request |\n| `HttpClientRequest.patch`   | Create a PATCH request    |\n| `HttpClientRequest.post`    | Create a POST request     |\n| `HttpClientRequest.put`     | Create a PUT request      |\n\n### Setting Headers\n\nWhen making HTTP requests, sometimes you need to include additional information in the request headers. You can set headers using the `setHeader` function for a single header or `setHeaders` for multiple headers simultaneously.\n\n```ts\nimport { HttpClientRequest } from \"@effect/platform\"\n\nconst req = HttpClientRequest.get(\"https://api.example.com/data\").pipe(\n  // Setting a single header\n  HttpClientRequest.setHeader(\"Authorization\", \"Bearer your_token_here\"),\n  // Setting multiple headers\n  HttpClientRequest.setHeaders({\n    \"Content-Type\": \"application/json; charset=UTF-8\",\n    \"Custom-Header\": \"CustomValue\"\n  })\n)\n\nconsole.log(JSON.stringify(req.headers, null, 2))\n/*\nOutput:\n{\n  \"authorization\": \"Bearer your_token_here\",\n  \"content-type\": \"application/json; charset=UTF-8\",\n  \"custom-header\": \"CustomValue\"\n}\n*/\n```\n\n### basicAuth\n\nTo include basic authentication in your HTTP request, you can use the `basicAuth` method provided by `HttpClientRequest`.\n\n```ts\nimport { HttpClientRequest } from \"@effect/platform\"\n\nconst req = HttpClientRequest.get(\"https://api.example.com/data\").pipe(\n  HttpClientRequest.basicAuth(\"your_username\", \"your_password\")\n)\n\nconsole.log(JSON.stringify(req.headers, null, 2))\n/*\nOutput:\n{\n  \"authorization\": \"Basic eW91cl91c2VybmFtZTp5b3VyX3Bhc3N3b3Jk\"\n}\n*/\n```\n\n### bearerToken\n\nTo include a Bearer token in your HTTP request, use the `bearerToken` method provided by `HttpClientRequest`.\n\n```ts\nimport { HttpClientRequest } from \"@effect/platform\"\n\nconst req = HttpClientRequest.get(\"https://api.example.com/data\").pipe(\n  HttpClientRequest.bearerToken(\"your_token\")\n)\n\nconsole.log(JSON.stringify(req.headers, null, 2))\n/*\nOutput:\n{\n  \"authorization\": \"Bearer your_token\"\n}\n*/\n```\n\n### accept\n\nTo specify the media types that are acceptable for the response, use the `accept` method provided by `HttpClientRequest`.\n\n```ts\nimport { HttpClientRequest } from \"@effect/platform\"\n\nconst req = HttpClientRequest.get(\"https://api.example.com/data\").pipe(\n  HttpClientRequest.accept(\"application/xml\")\n)\n\nconsole.log(JSON.stringify(req.headers, null, 2))\n/*\nOutput:\n{\n  \"accept\": \"application/xml\"\n}\n*/\n```\n\n### acceptJson\n\nTo indicate that the client accepts JSON responses, use the `acceptJson` method provided by `HttpClientRequest`.\n\n```ts\nimport { HttpClientRequest } from \"@effect/platform\"\n\nconst req = HttpClientRequest.get(\"https://api.example.com/data\").pipe(\n  HttpClientRequest.acceptJson\n)\n\nconsole.log(JSON.stringify(req.headers, null, 2))\n/*\nOutput:\n{\n  \"accept\": \"application/json\"\n}\n*/\n```\n\n## GET\n\n### Converting the Response\n\nThe `HttpClientResponse` provides several methods to convert a response into different formats.\n\n**Example: Converting to JSON**\n\n```ts\nimport { FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect } from \"effect\"\n\nconst getPostAsJson = Effect.gen(function* () {\n  const client = yield* HttpClient.HttpClient\n  const response = yield* client.get(\n    \"https://jsonplaceholder.typicode.com/posts/1\"\n  )\n  return yield* response.json\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\ngetPostAsJson.pipe(\n  Effect.andThen((post) => Console.log(typeof post, post)),\n  NodeRuntime.runMain\n)\n/*\nOutput:\nobject {\n  userId: 1,\n  id: 1,\n  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',\n  body: 'quia et suscipit\\n' +\n    'suscipit recusandae consequuntur expedita et cum\\n' +\n    'reprehenderit molestiae ut ut quas totam\\n' +\n    'nostrum rerum est autem sunt rem eveniet architecto'\n}\n*/\n```\n\n**Example: Converting to Text**\n\n```ts\nimport { FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect } from \"effect\"\n\nconst getPostAsText = Effect.gen(function* () {\n  const client = yield* HttpClient.HttpClient\n  const response = yield* client.get(\n    \"https://jsonplaceholder.typicode.com/posts/1\"\n  )\n  return yield* response.text\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\ngetPostAsText.pipe(\n  Effect.andThen((post) => Console.log(typeof post, post)),\n  NodeRuntime.runMain\n)\n/*\nOutput:\nstring {\n  userId: 1,\n  id: 1,\n  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',\n  body: 'quia et suscipit\\n' +\n    'suscipit recusandae consequuntur expedita et cum\\n' +\n    'reprehenderit molestiae ut ut quas totam\\n' +\n    'nostrum rerum est autem sunt rem eveniet architecto'\n}\n*/\n```\n\n**Methods Summary**\n\n| Method          | Description                           |\n| --------------- | ------------------------------------- |\n| `arrayBuffer`   | Convert to `ArrayBuffer`              |\n| `formData`      | Convert to `FormData`                 |\n| `json`          | Convert to JSON                       |\n| `stream`        | Convert to a `Stream` of `Uint8Array` |\n| `text`          | Convert to text                       |\n| `urlParamsBody` | Convert to `UrlParams`                |\n\n### Decoding Data with Schemas\n\nA common use case when fetching data is to validate the received format. For this purpose, the `HttpClientResponse` module is integrated with `effect/Schema`.\n\n```ts\nimport {\n  FetchHttpClient,\n  HttpClient,\n  HttpClientResponse\n} from \"@effect/platform\"\nimport { NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect, Schema } from \"effect\"\n\nconst Post = Schema.Struct({\n  id: Schema.Number,\n  title: Schema.String\n})\n\nconst getPostAndValidate = Effect.gen(function* () {\n  const client = yield* HttpClient.HttpClient\n  const response = yield* client.get(\n    \"https://jsonplaceholder.typicode.com/posts/1\"\n  )\n  return yield* HttpClientResponse.schemaBodyJson(Post)(response)\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\ngetPostAndValidate.pipe(Effect.andThen(Console.log), NodeRuntime.runMain)\n/*\nOutput:\n{\n  id: 1,\n  title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit'\n}\n*/\n```\n\nIn this example, we define a schema for a post object with properties `id` and `title`. Then, we fetch the data and validate it against this schema using `HttpClientResponse.schemaBodyJson`. Finally, we log the validated post object.\n\n### Filtering And Error Handling\n\nIt's important to note that `HttpClient.get` doesn't consider non-`200` status codes as errors by default. This design choice allows for flexibility in handling different response scenarios. For instance, you might have a schema union where the status code serves as the discriminator, enabling you to define a schema that encompasses all possible response cases.\n\nYou can use `HttpClient.filterStatusOk` to ensure only `2xx` responses are treated as successes.\n\nIn this example, we attempt to fetch a non-existent page and don't receive any error:\n\n```ts\nimport { FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect } from \"effect\"\n\nconst getText = Effect.gen(function* () {\n  const client = yield* HttpClient.HttpClient\n  const response = yield* client.get(\n    \"https://jsonplaceholder.typicode.com/non-existing-page\"\n  )\n  return yield* response.text\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\ngetText.pipe(Effect.andThen(Console.log), NodeRuntime.runMain)\n/*\nOutput:\n{}\n*/\n```\n\nHowever, if we use `HttpClient.filterStatusOk`, an error is logged:\n\n```ts\nimport { FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect } from \"effect\"\n\nconst getText = Effect.gen(function* () {\n  const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk)\n  const response = yield* client.get(\n    \"https://jsonplaceholder.typicode.com/non-existing-page\"\n  )\n  return yield* response.text\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\ngetText.pipe(Effect.andThen(Console.log), NodeRuntime.runMain)\n/*\nOutput:\n[17:37:59.923] ERROR (#0):\n  ResponseError: StatusCode: non 2xx status code (404 GET https://jsonplaceholder.typicode.com/non-existing-page)\n      ... stack trace ...\n*/\n```\n\n## POST\n\nTo make a POST request, you can use the `HttpClientRequest.post` function provided by the `HttpClientRequest` module. Here's an example of how to create and send a POST request:\n\n```ts\nimport {\n  FetchHttpClient,\n  HttpClient,\n  HttpClientRequest\n} from \"@effect/platform\"\nimport { NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect } from \"effect\"\n\nconst addPost = Effect.gen(function* () {\n  const client = yield* HttpClient.HttpClient\n  return yield* HttpClientRequest.post(\n    \"https://jsonplaceholder.typicode.com/posts\"\n  ).pipe(\n    HttpClientRequest.bodyJson({\n      title: \"foo\",\n      body: \"bar\",\n      userId: 1\n    }),\n    Effect.flatMap(client.execute),\n    Effect.flatMap((res) => res.json)\n  )\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\naddPost.pipe(Effect.andThen(Console.log), NodeRuntime.runMain)\n/*\nOutput:\n{ title: 'foo', body: 'bar', userId: 1, id: 101 }\n*/\n```\n\nIf you need to send data in a format other than JSON, such as plain text, you can use different APIs provided by `HttpClientRequest`.\n\nIn the following example, we send the data as text:\n\n```ts\nimport {\n  FetchHttpClient,\n  HttpClient,\n  HttpClientRequest\n} from \"@effect/platform\"\nimport { NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect } from \"effect\"\n\nconst addPost = Effect.gen(function* () {\n  const client = yield* HttpClient.HttpClient\n  return yield* HttpClientRequest.post(\n    \"https://jsonplaceholder.typicode.com/posts\"\n  ).pipe(\n    HttpClientRequest.bodyText(\n      JSON.stringify({\n        title: \"foo\",\n        body: \"bar\",\n        userId: 1\n      }),\n      \"application/json; charset=UTF-8\"\n    ),\n    client.execute,\n    Effect.flatMap((res) => res.json)\n  )\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\naddPost.pipe(Effect.andThen(Console.log), NodeRuntime.runMain)\n/*\nOutput:\n{ title: 'foo', body: 'bar', userId: 1, id: 101 }\n*/\n```\n\n### Decoding Data with Schemas\n\nA common use case when fetching data is to validate the received format. For this purpose, the `HttpClientResponse` module is integrated with `effect/Schema`.\n\n```ts\nimport {\n  FetchHttpClient,\n  HttpClient,\n  HttpClientRequest,\n  HttpClientResponse\n} from \"@effect/platform\"\nimport { NodeRuntime } from \"@effect/platform-node\"\nimport { Console, Effect, Schema } from \"effect\"\n\nconst Post = Schema.Struct({\n  id: Schema.Number,\n  title: Schema.String\n})\n\nconst addPost = Effect.gen(function* () {\n  const client = yield* HttpClient.HttpClient\n  return yield* HttpClientRequest.post(\n    \"https://jsonplaceholder.typicode.com/posts\"\n  ).pipe(\n    HttpClientRequest.bodyText(\n      JSON.stringify({\n        title: \"foo\",\n        body: \"bar\",\n        userId: 1\n      }),\n      \"application/json; charset=UTF-8\"\n    ),\n    client.execute,\n    Effect.flatMap(HttpClientResponse.schemaBodyJson(Post))\n  )\n}).pipe(Effect.provide(FetchHttpClient.layer))\n\naddPost.pipe(Effect.andThen(Console.log), NodeRuntime.runMain)\n/*\nOutput:\n{ id: 101, title: 'foo' }\n*/\n```\n\n## Testing\n\n### Injecting Fetch\n\nTo test HTTP requests, you can inject a mock fetch implementation.\n\n```ts\nimport { FetchHttpClient, HttpClient } from \"@effect/platform\"\nimport { Effect, Layer } from \"effect\"\nimport * as assert from \"node:assert\"\n\n// Mock fetch implementation\nconst FetchTest = Layer.succeed(FetchHttpClient.Fetch, () =>\n  Promise.resolve(new Response(\"not found\", { status: 404 }))\n)\n\nconst TestLayer = FetchHttpClient.layer.pipe(Layer.provide(FetchTest))\n\nconst program = Effect.gen(function* () {\n  const client = yield* HttpClient.HttpClient\n\n  return yield* client\n    .get(\"https://www.google.com/\")\n    .pipe(Effect.flatMap((res) => res.text))\n})\n\n// Test\nEffect.gen(function* () {\n  const response = yield* program\n  assert.equal(response, \"not found\")\n}).pipe(Effect.provide(TestLayer), Effect.runPromise)\n```\n\n# HTTP Server\n\n## Overview\n\nThis section provides a simplified explanation of key concepts within the `@effect/platform` TypeScript library, focusing on components used to build HTTP servers. Understanding these terms and their relationships helps in structuring and managing server applications effectively.\n\n### Core Concepts\n\n- **HttpApp**: This is an `Effect` which results in a value `A`. It can utilize `ServerRequest` to produce the outcome `A`. Essentially, an `HttpApp` represents an application component that handles HTTP requests and generates responses based on those requests.\n\n- **Default** (HttpApp): A special type of `HttpApp` that specifically produces a `ServerResponse` as its output `A`. This is the most common form of application where each interaction is expected to result in an HTTP response.\n\n- **Server**: A construct that takes a `Default` app and converts it into an `Effect`. This serves as the execution layer where the `Default` app is operated, handling incoming requests and serving responses.\n\n- **Router**: A type of `Default` app where the possible error outcome is `RouteNotFound`. Routers are used to direct incoming requests to appropriate handlers based on the request path and method.\n\n- **Handler**: Another form of `Default` app, which has access to both `RouteContext` and `ServerRequest.ParsedSearchParams`. Handlers are specific functions designed to process requests and generate responses.\n\n- **Middleware**: Functions that transform a `Default` app into another `Default` app. Middleware can be used to modify requests, responses, or handle tasks like logging, authentication, and more. Middleware can be applied in two ways:\n  - On a `Router` using `router.use: Handler -> Default` which applies the middleware to specific routes.\n  - On a `Server` using `server.serve: () -> Layer | Middleware -> Layer` which applies the middleware globally to all routes handled by the server.\n\n### Applying Concepts\n\nThese components are designed to work together in a modular and flexible way, allowing developers to build complex server applications with reusable components. Here's how you might typically use these components in a project:\n\n1. **Create Handlers**: Define functions that process specific types of requests (e.g., GET, POST) and return responses.\n\n2. **Set Up Routers**: Organize handlers into routers, where each router manages a subset of application routes.\n\n3. **Apply Middleware**: Enhance routers or entire servers with middleware to add extra functionality like error handling or request logging.\n\n4. **Initialize the Server**: Wrap the main router with server functionality, applying any server-wide middleware, and start listening for requests.\n\n## Getting Started\n\n### Hello world example\n\nIn this example, we will create a simple HTTP server that listens on port `3000`. The server will respond with \"Hello World!\" when a request is made to the root URL (/) and return a `500` error for all other paths.\n\nNode.js Example\n\n```ts\nimport { HttpRouter, HttpServer, HttpServerResponse } from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { Layer } from \"effect\"\nimport { createServer } from \"node:http\"\n\n// Define the router with a single route for the root URL\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/\", HttpServerResponse.text(\"Hello World\"))\n)\n\n// Set up the application server with logging\nconst app = router.pipe(HttpServer.serve(), HttpServer.withLogAddress)\n\n// Specify the port\nconst port = 3000\n\n// Create a server layer with the specified port\nconst ServerLive = NodeHttpServer.layer(() => createServer(), { port })\n\n// Run the application\nNodeRuntime.runMain(Layer.launch(Layer.provide(app, ServerLive)))\n\n/*\nOutput:\ntimestamp=... level=INFO fiber=#0 message=\"Listening on http://localhost:3000\"\n*/\n```\n\n> [!NOTE]\n> The `HttpServer.withLogAddress` middleware logs the address and port where the server is listening, helping to confirm that the server is running correctly and accessible on the expected endpoint.\n\nBun Example\n\n```ts\nimport { HttpRouter, HttpServer, HttpServerResponse } from \"@effect/platform\"\nimport { BunHttpServer, BunRuntime } from \"@effect/platform-bun\"\nimport { Layer } from \"effect\"\n\n// Define the router with a single route for the root URL\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/\", HttpServerResponse.text(\"Hello World\"))\n)\n\n// Set up the application server with logging\nconst app = router.pipe(HttpServer.serve(), HttpServer.withLogAddress)\n\n// Specify the port\nconst port = 3000\n\n// Create a server layer with the specified port\nconst ServerLive = BunHttpServer.layer({ port })\n\n// Run the application\nBunRuntime.runMain(Layer.launch(Layer.provide(app, ServerLive)))\n\n/*\nOutput:\ntimestamp=... level=INFO fiber=#0 message=\"Listening on http://localhost:3000\"\n*/\n```\n\nTo avoid boilerplate code for the final server setup, we'll use a helper function from the `listen.ts` file:\n\nNode.js Example\n\n```ts\nimport type { HttpPlatform, HttpServer } from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { Layer } from \"effect\"\nimport { createServer } from \"node:http\"\n\nexport const listen = (\n  app: Layer.Layer<\n    never,\n    never,\n    HttpPlatform.HttpPlatform | HttpServer.HttpServer\n  >,\n  port: number\n) =>\n  NodeRuntime.runMain(\n    Layer.launch(\n      Layer.provide(\n        app,\n        NodeHttpServer.layer(() => createServer(), { port })\n      )\n    )\n  )\n```\n\nBun Example\n\n```ts\nimport type { HttpPlatform, HttpServer } from \"@effect/platform\"\nimport { BunHttpServer, BunRuntime } from \"@effect/platform-bun\"\nimport { Layer } from \"effect\"\n\nexport const listen = (\n  app: Layer.Layer<\n    never,\n    never,\n    HttpPlatform.HttpPlatform | HttpServer.HttpServer\n  >,\n  port: number\n) =>\n  BunRuntime.runMain(\n    Layer.launch(Layer.provide(app, BunHttpServer.layer({ port })))\n  )\n```\n\n### Basic routing\n\nRouting refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).\n\nRoute definition takes the following structure:\n\n```\nrouter.pipe(HttpRouter.METHOD(PATH, HANDLER))\n```\n\nWhere:\n\n- **router** is an instance of `Router` (`import type { Router } from \"@effect/platform/Http/Router\"`).\n- **METHOD** is an HTTP request method, in lowercase (e.g., get, post, put, del).\n- **PATH** is the path on the server (e.g., \"/\", \"/user\").\n- **HANDLER** is the action that gets executed when the route is matched.\n\nThe following examples illustrate defining simple routes.\n\nRespond with `\"Hello World!\"` on the homepage:\n\n```ts\nrouter.pipe(HttpRouter.get(\"/\", HttpServerResponse.text(\"Hello World\")))\n```\n\nRespond to POST request on the root route (/), the application's home page:\n\n```ts\nrouter.pipe(HttpRouter.post(\"/\", HttpServerResponse.text(\"Got a POST request\")))\n```\n\nRespond to a PUT request to the `/user` route:\n\n```ts\nrouter.pipe(\n  HttpRouter.put(\"/user\", HttpServerResponse.text(\"Got a PUT request at /user\"))\n)\n```\n\nRespond to a DELETE request to the `/user` route:\n\n```ts\nrouter.pipe(\n  HttpRouter.del(\n    \"/user\",\n    HttpServerResponse.text(\"Got a DELETE request at /user\")\n  )\n)\n```\n\n### Serving static files\n\nTo serve static files such as images, CSS files, and JavaScript files, use the `HttpServerResponse.file` built-in action.\n\n```ts\nimport { HttpRouter, HttpServer, HttpServerResponse } from \"@effect/platform\"\nimport { listen } from \"./listen.js\"\n\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/\", HttpServerResponse.file(\"index.html\"))\n)\n\nconst app = router.pipe(HttpServer.serve())\n\nlisten(app, 3000)\n```\n\nCreate an `index.html` file in your project directory:\n\n```html filename=\"index.html\"\n<!doctype html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n    <title>index.html</title>\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n  </head>\n  <body>\n    index.html\n  </body>\n</html>\n```\n\n## Routing\n\nRouting refers to how an application's endpoints (URIs) respond to client requests.\n\nYou define routing using methods of the `HttpRouter` object that correspond to HTTP methods; for example, `HttpRouter.get()` to handle GET requests and `HttpRouter.post` to handle POST requests. You can also use `HttpRouter.all()` to handle all HTTP methods.\n\nThese routing methods specify a `Route.Handler` called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified handler.\n\nThe following code is an example of a very basic route.\n\n```ts\n// respond with \"hello world\" when a GET request is made to the homepage\nHttpRouter.get(\"/\", HttpServerResponse.text(\"Hello World\"))\n```\n\n### Route methods\n\nA route method is derived from one of the HTTP methods, and is attached to an instance of the `HttpRouter` object.\n\nThe following code is an example of routes that are defined for the GET and the POST methods to the root of the app.\n\n```ts\n// GET method route\nHttpRouter.get(\"/\", HttpServerResponse.text(\"GET request to the homepage\"))\n\n// POST method route\nHttpRouter.post(\"/\", HttpServerResponse.text(\"POST request to the homepage\"))\n```\n\n`HttpRouter` supports methods that correspond to all HTTP request methods: `get`, `post`, and so on.\n\nThere is a special routing method, `HttpRouter.all()`, used to load middleware functions at a path for **all** HTTP request methods. For example, the following handler is executed for requests to the route “/secret” whether using GET, POST, PUT, DELETE.\n\n```ts\nHttpRouter.all(\n  \"/secret\",\n  HttpServerResponse.empty().pipe(\n    Effect.tap(Console.log(\"Accessing the secret section ...\"))\n  )\n)\n```\n\n### Route paths\n\nRoute paths, when combined with a request method, define the endpoints where requests can be made. Route paths can be specified as strings according to the following type:\n\n```ts\ntype PathInput = `/${string}` | \"*\"\n```\n\n> [!NOTE]\n> Query strings are not part of the route path.\n\nHere are some examples of route paths based on strings.\n\nThis route path will match requests to the root route, /.\n\n```ts\nHttpRouter.get(\"/\", HttpServerResponse.text(\"root\"))\n```\n\nThis route path will match requests to `/user`.\n\n```ts\nHttpRouter.get(\"/user\", HttpServerResponse.text(\"user\"))\n```\n\nThis route path matches requests to any path starting with `/user` (e.g., `/user`, `/users`, etc.)\n\n```ts\nHttpRouter.get(\n  \"/user*\",\n  Effect.map(HttpServerRequest.HttpServerRequest, (req) =>\n    HttpServerResponse.text(req.url)\n  )\n)\n```\n\n### Route parameters\n\nRoute parameters are named URL segments that are used to capture the values specified at their position in the URL. By using a schema the captured values are populated in an object, with the name of the route parameter specified in the path as their respective keys.\n\nRoute parameters are named segments in a URL that capture the values specified at those positions. These captured values are stored in an object, with the parameter names used as keys.\n\nFor example:\n\n```\nRoute path: /users/:userId/books/:bookId\nRequest URL: http://localhost:3000/users/34/books/8989\nparams: { \"userId\": \"34\", \"bookId\": \"8989\" }\n```\n\nTo define routes with parameters, include the parameter names in the path and use a schema to validate and parse these parameters, as shown below.\n\n```ts\nimport { HttpRouter, HttpServer, HttpServerResponse } from \"@effect/platform\"\nimport { Effect, Schema } from \"effect\"\nimport { listen } from \"./listen.js\"\n\n// Define the schema for route parameters\nconst Params = Schema.Struct({\n  userId: Schema.String,\n  bookId: Schema.String\n})\n\n// Create a router with a route that captures parameters\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\n    \"/users/:userId/books/:bookId\",\n    HttpRouter.schemaPathParams(Params).pipe(\n      Effect.flatMap((params) => HttpServerResponse.json(params))\n    )\n  )\n)\n\nconst app = router.pipe(HttpServer.serve())\n\nlisten(app, 3000)\n```\n\n### Response methods\n\nThe methods on `HttpServerResponse` object in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.\n\n| Method       | Description                    |\n| ------------ | ------------------------------ |\n| **empty**    | Sends an empty response.       |\n| **formData** | Sends form data.               |\n| **html**     | Sends an HTML response.        |\n| **raw**      | Sends a raw response.          |\n| **setBody**  | Sets the body of the response. |\n| **stream**   | Sends a streaming response.    |\n| **text**     | Sends a plain text response.   |\n\n### Router\n\nUse the `HttpRouter` object to create modular, mountable route handlers. A `Router` instance is a complete middleware and routing system, often referred to as a \"mini-app.\"\n\nThe following example shows how to create a router as a module, define some routes, and mount the router module on a path in the main app.\n\nCreate a file named `birds.ts` in your app directory with the following content:\n\n```ts\nimport { HttpRouter, HttpServerResponse } from \"@effect/platform\"\n\nexport const birds = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/\", HttpServerResponse.text(\"Birds home page\")),\n  HttpRouter.get(\"/about\", HttpServerResponse.text(\"About birds\"))\n)\n```\n\nIn your main application file, load the router module and mount it.\n\n```ts\nimport { HttpRouter, HttpServer } from \"@effect/platform\"\nimport { birds } from \"./birds.js\"\nimport { listen } from \"./listen.js\"\n\n// Create the main router and mount the birds router\nconst router = HttpRouter.empty.pipe(HttpRouter.mount(\"/birds\", birds))\n\nconst app = router.pipe(HttpServer.serve())\n\nlisten(app, 3000)\n```\n\nWhen you run this code, your application will be able to handle requests to `/birds` and `/birds/about`, serving the respective responses defined in the `birds` router module.\n\n## Writing Middleware\n\nIn this section, we'll build a simple \"Hello World\" application and demonstrate how to add three middleware functions: `myLogger` for logging, `requestTime` for displaying request timestamps, and `validateCookies` for validating incoming cookies.\n\n### Example Application\n\nHere is an example of a basic \"Hello World\" application with middleware.\n\n### Middleware `myLogger`\n\nThis middleware logs \"LOGGED\" whenever a request passes through it.\n\n```ts\nconst myLogger = HttpMiddleware.make((app) =>\n  Effect.gen(function* () {\n    console.log(\"LOGGED\")\n    return yield* app\n  })\n)\n```\n\nTo use the middleware, add it to the router using `HttpRouter.use()`:\n\n```ts\nimport {\n  HttpMiddleware,\n  HttpRouter,\n  HttpServer,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { Effect } from \"effect\"\nimport { listen } from \"./listen.js\"\n\nconst myLogger = HttpMiddleware.make((app) =>\n  Effect.gen(function* () {\n    console.log(\"LOGGED\")\n    return yield* app\n  })\n)\n\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/\", HttpServerResponse.text(\"Hello World\"))\n)\n\nconst app = router.pipe(HttpRouter.use(myLogger), HttpServer.serve())\n\nlisten(app, 3000)\n```\n\nWith this setup, every request to the app will log \"LOGGED\" to the terminal. Middleware execute in the order they are loaded.\n\n### Middleware `requestTime`\n\nNext, we'll create a middleware that records the timestamp of each HTTP request and provides it via a service called `RequestTime`.\n\n```ts\nclass RequestTime extends Context.Tag(\"RequestTime\")<RequestTime, number>() {}\n\nconst requestTime = HttpMiddleware.make((app) =>\n  Effect.gen(function* () {\n    return yield* app.pipe(Effect.provideService(RequestTime, Date.now()))\n  })\n)\n```\n\nUpdate the app to use this middleware and display the timestamp in the response:\n\n```ts\nimport {\n  HttpMiddleware,\n  HttpRouter,\n  HttpServer,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { Context, Effect } from \"effect\"\nimport { listen } from \"./listen.js\"\n\nclass RequestTime extends Context.Tag(\"RequestTime\")<RequestTime, number>() {}\n\nconst requestTime = HttpMiddleware.make((app) =>\n  Effect.gen(function* () {\n    return yield* app.pipe(Effect.provideService(RequestTime, Date.now()))\n  })\n)\n\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\n    \"/\",\n    Effect.gen(function* () {\n      const requestTime = yield* RequestTime\n      const responseText = `Hello World<br/><small>Requested at: ${requestTime}</small>`\n      return yield* HttpServerResponse.html(responseText)\n    })\n  )\n)\n\nconst app = router.pipe(HttpRouter.use(requestTime), HttpServer.serve())\n\nlisten(app, 3000)\n```\n\nNow, when you make a request to the root path, the response will include the timestamp of the request.\n\n### Middleware `validateCookies`\n\nFinally, we'll create a middleware that validates incoming cookies. If the cookies are invalid, it sends a 400 response.\n\nHere's an example that validates cookies using an external service:\n\n```ts\nclass CookieError {\n  readonly _tag = \"CookieError\"\n}\n\nconst externallyValidateCookie = (testCookie: string | undefined) =>\n  testCookie && testCookie.length > 0\n    ? Effect.succeed(testCookie)\n    : Effect.fail(new CookieError())\n\nconst cookieValidator = HttpMiddleware.make((app) =>\n  Effect.gen(function* () {\n    const req = yield* HttpServerRequest.HttpServerRequest\n    yield* externallyValidateCookie(req.cookies.testCookie)\n    return yield* app\n  }).pipe(\n    Effect.catchTag(\"CookieError\", () =>\n      HttpServerResponse.text(\"Invalid cookie\")\n    )\n  )\n)\n```\n\nUpdate the app to use the `cookieValidator` middleware:\n\n```ts\nimport {\n  HttpMiddleware,\n  HttpRouter,\n  HttpServer,\n  HttpServerRequest,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { Effect } from \"effect\"\nimport { listen } from \"./listen.js\"\n\nclass CookieError {\n  readonly _tag = \"CookieError\"\n}\n\nconst externallyValidateCookie = (testCookie: string | undefined) =>\n  testCookie && testCookie.length > 0\n    ? Effect.succeed(testCookie)\n    : Effect.fail(new CookieError())\n\nconst cookieValidator = HttpMiddleware.make((app) =>\n  Effect.gen(function* () {\n    const req = yield* HttpServerRequest.HttpServerRequest\n    yield* externallyValidateCookie(req.cookies.testCookie)\n    return yield* app\n  }).pipe(\n    Effect.catchTag(\"CookieError\", () =>\n      HttpServerResponse.text(\"Invalid cookie\")\n    )\n  )\n)\n\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/\", HttpServerResponse.text(\"Hello World\"))\n)\n\nconst app = router.pipe(HttpRouter.use(cookieValidator), HttpServer.serve())\n\nlisten(app, 3000)\n```\n\nTest the middleware with the following commands:\n\n```sh\ncurl -i http://localhost:3000\ncurl -i http://localhost:3000 --cookie \"testCookie=myvalue\"\ncurl -i http://localhost:3000 --cookie \"testCookie=\"\n```\n\nThis setup validates the `testCookie` and returns \"Invalid cookie\" if the validation fails, or \"Hello World\" if it passes.\n\n## Applying Middleware in Your Application\n\nMiddleware functions are powerful tools that allow you to modify the request-response cycle. Middlewares can be applied at various levels to achieve different scopes of influence:\n\n- **Route Level**: Apply middleware to individual routes.\n- **Router Level**: Apply middleware to a group of routes within a single router.\n- **Server Level**: Apply middleware across all routes managed by a server.\n\n### Applying Middleware at the Route Level\n\nAt the route level, middlewares are applied to specific endpoints, allowing for targeted modifications or enhancements such as logging, authentication, or parameter validation for a particular route.\n\n**Example**\n\nHere's a practical example showing how to apply middleware at the route level:\n\n```ts\nimport {\n  HttpMiddleware,\n  HttpRouter,\n  HttpServer,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { Effect } from \"effect\"\nimport { listen } from \"./listen.js\"\n\n// Middleware constructor that logs the name of the middleware\nconst withMiddleware = (name: string) =>\n  HttpMiddleware.make((app) =>\n    Effect.gen(function* () {\n      console.log(name) // Log the middleware name when the route is accessed\n      return yield* app // Continue with the original application flow\n    })\n  )\n\nconst router = HttpRouter.empty.pipe(\n  // Applying middleware to route \"/a\"\n  HttpRouter.get(\"/a\", HttpServerResponse.text(\"a\").pipe(withMiddleware(\"M1\"))),\n  // Applying middleware to route \"/b\"\n  HttpRouter.get(\"/b\", HttpServerResponse.text(\"b\").pipe(withMiddleware(\"M2\")))\n)\n\nconst app = router.pipe(HttpServer.serve())\n\nlisten(app, 3000)\n```\n\n**Testing the Middleware**\n\nYou can test the middleware by making requests to the respective routes and observing the console output:\n\n```sh\n# Test route /a\ncurl -i http://localhost:3000/a\n# Expected console output: M1\n\n# Test route /b\ncurl -i http://localhost:3000/b\n# Expected console output: M2\n```\n\n### Applying Middleware at the Router Level\n\nApplying middleware at the router level is an efficient way to manage common functionalities across multiple routes within your application. Middleware can handle tasks such as logging, authentication, and response modifications before reaching the actual route handlers.\n\n**Example**\n\nHere's how you can structure and apply middleware across different routers using the `@effect/platform` library:\n\n```ts\nimport {\n  HttpMiddleware,\n  HttpRouter,\n  HttpServer,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { Effect } from \"effect\"\nimport { listen } from \"./listen.js\"\n\n// Middleware constructor that logs the name of the middleware\nconst withMiddleware = (name: string) =>\n  HttpMiddleware.make((app) =>\n    Effect.gen(function* () {\n      console.log(name) // Log the middleware name when a route is accessed\n      return yield* app // Continue with the original application flow\n    })\n  )\n\n// Define Router1 with specific routes\nconst router1 = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/a\", HttpServerResponse.text(\"a\")), // Middleware M4, M3, M1 will apply\n  HttpRouter.get(\"/b\", HttpServerResponse.text(\"b\")), // Middleware M4, M3, M1 will apply\n  // Apply Middleware at the router level\n  HttpRouter.use(withMiddleware(\"M1\")),\n  HttpRouter.get(\"/c\", HttpServerResponse.text(\"c\")) // Middleware M4, M3 will apply\n)\n\n// Define Router2 with specific routes\nconst router2 = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/d\", HttpServerResponse.text(\"d\")), // Middleware M4, M2 will apply\n  HttpRouter.get(\"/e\", HttpServerResponse.text(\"e\")), // Middleware M4, M2 will apply\n  HttpRouter.get(\"/f\", HttpServerResponse.text(\"f\")), // Middleware M4, M2 will apply\n  // Apply Middleware at the router level\n  HttpRouter.use(withMiddleware(\"M2\"))\n)\n\n// Main router combining Router1 and Router2\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.mount(\"/r1\", router1),\n  // Apply Middleware affecting all routes under /r1\n  HttpRouter.use(withMiddleware(\"M3\")),\n  HttpRouter.get(\"/g\", HttpServerResponse.text(\"g\")), // Only Middleware M4 will apply\n  HttpRouter.mount(\"/r2\", router2),\n  // Apply Middleware affecting all routes\n  HttpRouter.use(withMiddleware(\"M4\"))\n)\n\n// Configure the application with the server middleware\nconst app = router.pipe(HttpServer.serve())\n\nlisten(app, 3000)\n```\n\n**Testing the Middleware**\n\nTo ensure that the middleware is working as expected, you can test it by making HTTP requests to the defined routes and checking the console output for middleware logs:\n\n```sh\n# Test route /a under router1\ncurl -i http://localhost:3000/r1/a\n# Expected console output: M4 M3 M1\n\n# Test route /c under router1\ncurl -i http://localhost:3000/r1/c\n# Expected console output: M4 M3\n\n# Test route /d under router2\ncurl -i http://localhost:3000/r2/d\n# Expected console output: M4 M2\n\n# Test route /g under the main router\ncurl -i http://localhost:3000/g\n# Expected console output: M4\n```\n\n### Applying Middleware at the Server Level\n\nApplying middleware at the server level allows you to introduce certain functionalities, such as logging, authentication, or general request processing, that affect every request handled by the server. This ensures that all incoming requests, regardless of the route, pass through the applied middleware, making it an essential feature for global error handling, logging, or authentication.\n\n**Example**\n\n```ts\nimport {\n  HttpMiddleware,\n  HttpRouter,\n  HttpServer,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { Effect } from \"effect\"\nimport { listen } from \"./listen.js\"\n\n// Middleware constructor that logs the name of the middleware\nconst withMiddleware = (name: string) =>\n  HttpMiddleware.make((app) =>\n    Effect.gen(function* () {\n      console.log(name) // Log the middleware name when the route is accessed\n      return yield* app // Continue with the original application flow\n    })\n  )\n\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/a\", HttpServerResponse.text(\"a\").pipe(withMiddleware(\"M1\"))),\n  HttpRouter.get(\"/b\", HttpServerResponse.text(\"b\")),\n  HttpRouter.use(withMiddleware(\"M2\")),\n  HttpRouter.get(\"/\", HttpServerResponse.text(\"root\"))\n)\n\nconst app = router.pipe(HttpServer.serve(withMiddleware(\"M3\")))\n\nlisten(app, 3000)\n```\n\n**Testing the Middleware**\n\nTo confirm the middleware is functioning as intended, you can send HTTP requests to the defined routes and check the console for middleware logs:\n\n```sh\n# Test route /a and observe the middleware logs\ncurl -i http://localhost:3000/a\n# Expected console output: M3 M2 M1  - Middleware M3 (server-level), M2 (router-level), and M1 (route-level) apply.\n\n# Test route /b and observe the middleware logs\ncurl -i http://localhost:3000/b\n# Expected console output: M3 M2  - Middleware M3 (server-level) and M2 (router-level) apply.\n\n# Test route / and observe the middleware logs\ncurl -i http://localhost:3000/\n# Expected console output: M3 M2  - Middleware M3 (server-level) and M2 (router-level) apply.\n```\n\n### Applying Multiple Middlewares\n\nMiddleware functions are simply functions that transform a `Default` app into another `Default` app. This flexibility allows for stacking multiple middleware functions, much like composing functions in functional programming. The `flow` function from the `Effect` library facilitates this by enabling function composition.\n\n**Example**\n\n```ts\nimport {\n  HttpMiddleware,\n  HttpRouter,\n  HttpServer,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { Effect, flow } from \"effect\"\nimport { listen } from \"./listen.js\"\n\n// Middleware constructor that logs the middleware's name when a route is accessed\nconst withMiddleware = (name: string) =>\n  HttpMiddleware.make((app) =>\n    Effect.gen(function* () {\n      console.log(name) // Log the middleware name\n      return yield* app // Continue with the original application flow\n    })\n  )\n\n// Setup routes and apply multiple middlewares using flow for function composition\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\n    \"/a\",\n    HttpServerResponse.text(\"a\").pipe(\n      flow(withMiddleware(\"M1\"), withMiddleware(\"M2\"))\n    )\n  ),\n  HttpRouter.get(\"/b\", HttpServerResponse.text(\"b\")),\n  // Apply combined middlewares to the entire router\n  HttpRouter.use(flow(withMiddleware(\"M3\"), withMiddleware(\"M4\"))),\n  HttpRouter.get(\"/\", HttpServerResponse.text(\"root\"))\n)\n\n// Apply combined middlewares at the server level\nconst app = router.pipe(\n  HttpServer.serve(flow(withMiddleware(\"M5\"), withMiddleware(\"M6\")))\n)\n\nlisten(app, 3000)\n```\n\n**Testing the Middleware Composition**\n\nTo verify that the middleware is functioning as expected, you can send HTTP requests to the routes and check the console for the expected middleware log output:\n\n```sh\n# Test route /a to see the output from multiple middleware layers\ncurl -i http://localhost:3000/a\n# Expected console output: M6 M5 M4 M3 M2 M1\n\n# Test route /b where fewer middleware are applied\ncurl -i http://localhost:3000/b\n# Expected console output: M6 M5 M4 M3\n\n# Test the root route to confirm top-level middleware application\ncurl -i http://localhost:3000/\n# Expected console output: M6 M5\n```\n\n## Built-in middleware\n\n### Middleware Summary\n\n| Middleware            | Description                                                                                                                       |\n| --------------------- | --------------------------------------------------------------------------------------------------------------------------------- |\n| **Logger**            | Provides detailed logging of all requests and responses, aiding in debugging and monitoring application activities.               |\n| **xForwardedHeaders** | Manages `X-Forwarded-*` headers to accurately maintain client information such as IP addresses and host names in proxy scenarios. |\n\n### logger\n\nThe `HttpMiddleware.logger` middleware enables logging for your entire application, providing insights into each request and response. Here's how to set it up:\n\n```ts\nimport {\n  HttpMiddleware,\n  HttpRouter,\n  HttpServer,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { listen } from \"./listen.js\"\n\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/\", HttpServerResponse.text(\"Hello World\"))\n)\n\n// Apply the logger middleware globally\nconst app = router.pipe(HttpServer.serve(HttpMiddleware.logger))\n\nlisten(app, 3000)\n/*\ncurl -i http://localhost:3000\ntimestamp=... level=INFO fiber=#0 message=\"Listening on http://0.0.0.0:3000\"\ntimestamp=... level=INFO fiber=#19 message=\"Sent HTTP response\" http.span.1=8ms http.status=200 http.method=GET http.url=/\ntimestamp=... level=INFO fiber=#20 cause=\"RouteNotFound: GET /favicon.ico not found\n    at ...\n    at http.server GET\" http.span.2=4ms http.status=500 http.method=GET http.url=/favicon.ico\n*/\n```\n\nTo disable the logger for specific routes, you can use `HttpMiddleware.withLoggerDisabled`:\n\n```ts\nimport {\n  HttpMiddleware,\n  HttpRouter,\n  HttpServer,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { listen } from \"./listen.js\"\n\n// Create the router with routes that will and will not have logging\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/\", HttpServerResponse.text(\"Hello World\")),\n  HttpRouter.get(\n    \"/no-logger\",\n    HttpServerResponse.text(\"no-logger\").pipe(HttpMiddleware.withLoggerDisabled)\n  )\n)\n\n// Apply the logger middleware globally\nconst app = router.pipe(HttpServer.serve(HttpMiddleware.logger))\n\nlisten(app, 3000)\n/*\ncurl -i http://localhost:3000/no-logger\ntimestamp=2024-05-19T09:53:29.877Z level=INFO fiber=#0 message=\"Listening on http://0.0.0.0:3000\"\n*/\n```\n\n### xForwardedHeaders\n\nThis middleware handles `X-Forwarded-*` headers, useful when your app is behind a reverse proxy or load balancer and you need to retrieve the original client's IP and host information.\n**WARNING:** The `X-Forwarded-*` headers are untrustworthy when no trusted reverse proxy or load balancer is between the client and server.\n\n```ts\nimport {\n  HttpMiddleware,\n  HttpRouter,\n  HttpServer,\n  HttpServerRequest,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { Effect } from \"effect\"\nimport { listen } from \"./listen.js\"\n\n// Create a router and a route that logs request headers and remote address\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\n    \"/\",\n    Effect.gen(function* () {\n      const req = yield* HttpServerRequest.HttpServerRequest\n      console.log(req.headers)\n      console.log(req.remoteAddress)\n      return yield* HttpServerResponse.text(\"Hello World\")\n    })\n  )\n)\n\n// Set up the server with xForwardedHeaders middleware\nconst app = router.pipe(HttpServer.serve(HttpMiddleware.xForwardedHeaders))\n\nlisten(app, 3000)\n/*\ncurl -H \"X-Forwarded-Host: 192.168.1.1\" -H \"X-Forwarded-For: 192.168.1.1\" http://localhost:3000\ntimestamp=... level=INFO fiber=#0 message=\"Listening on http://0.0.0.0:3000\"\n{\n  host: '192.168.1.1',\n  'user-agent': 'curl/8.6.0',\n  accept: '*\\/*',\n  'x-forwarded-host': '192.168.1.1',\n  'x-forwarded-for': '192.168.1.1'\n}\n{ _id: 'Option', _tag: 'Some', value: '192.168.1.1' }\n*/\n```\n\n## Error Handling\n\n### Catching Errors\n\nBelow is an example illustrating how to catch and manage errors that occur during the execution of route handlers:\n\n```ts\nimport { HttpRouter, HttpServer, HttpServerResponse } from \"@effect/platform\"\nimport { Effect } from \"effect\"\nimport { listen } from \"./listen.js\"\n\n// Define routes that might throw errors or fail\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\n    \"/throw\",\n    Effect.sync(() => {\n      throw new Error(\"BROKEN\") // This will intentionally throw an error\n    })\n  ),\n  HttpRouter.get(\"/fail\", Effect.fail(\"Uh oh!\")) // This will intentionally fail\n)\n\n// Configure the application to handle different types of errors\nconst app = router.pipe(\n  Effect.catchTags({\n    RouteNotFound: () =>\n      HttpServerResponse.text(\"Route Not Found\", { status: 404 })\n  }),\n  Effect.catchAllCause((cause) =>\n    HttpServerResponse.text(cause.toString(), { status: 500 })\n  ),\n  HttpServer.serve()\n)\n\nlisten(app, 3000)\n```\n\nYou can test the error handling setup with `curl` commands by trying to access routes that trigger errors:\n\n```sh\n# Accessing a route that does not exist\ncurl -i http://localhost:3000/nonexistent\n\n# Accessing the route that throws an error\ncurl -i http://localhost:3000/throw\n\n# Accessing the route that fails\ncurl -i http://localhost:3000/fail\n```\n\n## Validations\n\nValidation is a critical aspect of handling HTTP requests to ensure that the data your server receives is as expected. We'll explore how to validate headers and cookies using the `@effect/platform` and `effect/Schema` libraries, which provide structured and robust methods for these tasks.\n\n### Headers\n\nHeaders often contain important information needed by your application, such as content types, authentication tokens, or session data. Validating these headers ensures that your application can trust and correctly process the information it receives.\n\n```ts\nimport {\n  HttpRouter,\n  HttpServer,\n  HttpServerRequest,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { Effect, Schema } from \"effect\"\nimport { listen } from \"./listen.js\"\n\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\n    \"/\",\n    Effect.gen(function* () {\n      // Define the schema for expected headers and validate them\n      const headers = yield* HttpServerRequest.schemaHeaders(\n        Schema.Struct({ test: Schema.String })\n      )\n      return yield* HttpServerResponse.text(\"header: \" + headers.test)\n    }).pipe(\n      // Handle parsing errors\n      Effect.catchTag(\"ParseError\", (e) =>\n        HttpServerResponse.text(`Invalid header: ${e.message}`)\n      )\n    )\n  )\n)\n\nconst app = router.pipe(HttpServer.serve())\n\nlisten(app, 3000)\n```\n\nYou can test header validation using the following `curl` commands:\n\n```sh\n# Request without the required header\ncurl -i http://localhost:3000\n\n# Request with the valid header\ncurl -i -H \"test: myvalue\" http://localhost:3000\n```\n\n### Cookies\n\nCookies are commonly used to maintain session state or user preferences. Validating cookies ensures that the data they carry is intact and as expected, enhancing security and application integrity.\n\nHere's how you can validate cookies received in HTTP requests:\n\n```ts\nimport {\n  Cookies,\n  HttpRouter,\n  HttpServer,\n  HttpServerRequest,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { Effect, Schema } from \"effect\"\nimport { listen } from \"./listen.js\"\n\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\n    \"/\",\n    Effect.gen(function* () {\n      const cookies = yield* HttpServerRequest.schemaCookies(\n        Schema.Struct({ test: Schema.String })\n      )\n      return yield* HttpServerResponse.text(\"cookie: \" + cookies.test)\n    }).pipe(\n      Effect.catchTag(\"ParseError\", (e) =>\n        HttpServerResponse.text(`Invalid cookie: ${e.message}`)\n      )\n    )\n  )\n)\n\nconst app = router.pipe(HttpServer.serve())\n\nlisten(app, 3000)\n```\n\nValidate the cookie handling with the following `curl` commands:\n\n```sh\n# Request without any cookies\ncurl -i http://localhost:3000\n\n# Request with the valid cookie\ncurl -i http://localhost:3000 --cookie \"test=myvalue\"\n```\n\n## ServerRequest\n\n### How do I get the raw request?\n\nThe native request object depends on the platform you are using, and it is not directly modeled in `@effect/platform`. Instead, you need to refer to the specific platform package you are working with, such as `@effect/platform-node` or `@effect/platform-bun`.\n\nHere is an example using Node.js:\n\n```ts\nimport {\n  HttpRouter,\n  HttpServer,\n  HttpServerRequest,\n  HttpServerResponse\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeHttpServerRequest } from \"@effect/platform-node\"\nimport { Effect } from \"effect\"\nimport { listen } from \"./listen.js\"\n\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\n    \"/\",\n    Effect.gen(function* () {\n      const req = yield* HttpServerRequest.HttpServerRequest\n      const raw = NodeHttpServerRequest.toIncomingMessage(req)\n      console.log(raw)\n      return HttpServerResponse.empty()\n    })\n  )\n)\n\nlisten(HttpServer.serve(router), 3000)\n```\n\n## Conversions\n\n### toWebHandler\n\nThe `toWebHandler` function converts a `Default` (i.e. a type of `HttpApp` that specifically produces a `ServerResponse` as its output) into a web handler that can process `Request` objects and return `Response` objects.\n\n```ts\nimport { HttpApp, HttpRouter, HttpServerResponse } from \"@effect/platform\"\n\n// Define the router with some routes\nconst router = HttpRouter.empty.pipe(\n  HttpRouter.get(\"/\", HttpServerResponse.text(\"content 1\")),\n  HttpRouter.get(\"/foo\", HttpServerResponse.text(\"content 2\"))\n)\n\n// Convert the router to a web handler\n// const handler: (request: Request) => Promise<Response>\nconst handler = HttpApp.toWebHandler(router)\n\n// Test the handler with a request\nconst response = await handler(new Request(\"http://localhost:3000/foo\"))\nconsole.log(await response.text()) // Output: content 2\n```\n\n# Url\n\nThe `Url` module provides utilities for constructing and working with `URL` objects in a functional style. It includes:\n\n- A safe constructor for parsing URLs from strings.\n- Functions for immutably updating `URL` properties like `host`, `href`, and `search`.\n- Tools for reading and modifying URL parameters using the `UrlParams` module.\n- A focus on immutability, creating new `URL` instances for every change.\n\n## Creating a URL\n\n### fromString\n\nThis function takes a string and attempts to parse it into a `URL` object. If the string is invalid, it returns an `Either.Left` containing an `IllegalArgumentException` with the error details. Otherwise, it returns an `Either.Right` containing the parsed `URL`.\n\nYou can optionally provide a `base` parameter to resolve relative URLs. When supplied, the function treats the input `url` as relative to the `base`.\n\n**Example** (Parsing a URL with Optional Base)\n\n```ts\nimport { Url } from \"@effect/platform\"\nimport { Either } from \"effect\"\n\n// Parse an absolute URL\n//\n//      ┌─── Either<URL, IllegalArgumentException>\n//      ▼\nconst parsed = Url.fromString(\"https://example.com/path\")\n\nif (Either.isRight(parsed)) {\n  console.log(\"Parsed URL:\", parsed.right.toString())\n} else {\n  console.log(\"Error:\", parsed.left.message)\n}\n// Output: Parsed URL: https://example.com/path\n\n// Parse a relative URL with a base\nconst relativeParsed = Url.fromString(\"/relative-path\", \"https://example.com\")\n\nif (Either.isRight(relativeParsed)) {\n  console.log(\"Parsed relative URL:\", relativeParsed.right.toString())\n} else {\n  console.log(\"Error:\", relativeParsed.left.message)\n}\n// Output: Parsed relative URL: https://example.com/relative-path\n```\n\n## Immutably Changing URL Properties\n\nThe `Url` module offers a set of functions for updating properties of a `URL` object without modifying the original instance. These functions create and return a new `URL` with the specified updates, preserving the immutability of the original.\n\n### Available Setters\n\n| Setter        | Description                                               |\n| ------------- | --------------------------------------------------------- |\n| `setHash`     | Updates the hash fragment of the URL.                     |\n| `setHost`     | Updates the host (domain and port) of the URL.            |\n| `setHostname` | Updates the domain of the URL without modifying the port. |\n| `setHref`     | Replaces the entire URL string.                           |\n| `setPassword` | Updates the password used for authentication.             |\n| `setPathname` | Updates the path of the URL.                              |\n| `setPort`     | Updates the port of the URL.                              |\n| `setProtocol` | Updates the protocol (e.g., `http`, `https`).             |\n| `setSearch`   | Updates the query string of the URL.                      |\n| `setUsername` | Updates the username used for authentication.             |\n\n**Example** (Using Setters to Modify URL Properties)\n\n```ts\nimport { Url } from \"@effect/platform\"\nimport { pipe } from \"effect\"\n\nconst myUrl = new URL(\"https://example.com\")\n\n// Changing protocol, host, and port\nconst newUrl = pipe(\n  myUrl,\n  Url.setProtocol(\"http:\"),\n  Url.setHost(\"google.com\"),\n  Url.setPort(\"8080\")\n)\n\nconsole.log(\"Original:\", myUrl.toString())\n// Output: Original: https://example.com/\n\nconsole.log(\"New:\", newUrl.toString())\n// Output: New: http://google.com:8080/\n```\n\n### mutate\n\nFor more advanced modifications, use the `mutate` function. It clones the original `URL` object and applies a callback to the clone, allowing multiple updates at once.\n\n**Example** (Applying Multiple Changes with `mutate`)\n\n```ts\nimport { Url } from \"@effect/platform\"\n\nconst myUrl = new URL(\"https://example.com\")\n\nconst mutatedUrl = Url.mutate(myUrl, (url) => {\n  url.username = \"user\"\n  url.password = \"pass\"\n})\n\nconsole.log(\"Mutated:\", mutatedUrl.toString())\n// Output: Mutated: https://user:pass@example.com/\n```\n\n## Reading and Writing URL Parameters\n\nThe `Url` module provides utilities for working with URL query parameters. These utilities allow you to read existing parameters and write new ones, all while maintaining immutability. This functionality is supported by the `UrlParams` module.\n\nYou can extract the query parameters from a `URL` object using the `urlParams` function.\n\nTo modify or add query parameters, use the `setUrlParams` function. This function creates a new `URL` with the updated query string.\n\n**Example** (Reading and Writing Parameters)\n\n```ts\nimport { Url, UrlParams } from \"@effect/platform\"\n\nconst myUrl = new URL(\"https://example.com?foo=bar\")\n\n// Read parameters\nconst params = Url.urlParams(myUrl)\n\nconsole.log(params)\n// Output: [ [ 'foo', 'bar' ] ]\n\n// Write parameters\nconst updatedUrl = Url.setUrlParams(\n  myUrl,\n  UrlParams.fromInput([[\"key\", \"value\"]])\n)\n\nconsole.log(updatedUrl.toString())\n// Output: https://example.com/?key=value\n```\n\n### Modifying URL Parameters\n\nThe `modifyUrlParams` function allows you to read, modify, and overwrite URL parameters in a single operation.\n\n**Example** (Appending a Parameter to a URL)\n\n```ts\nimport { Url, UrlParams } from \"@effect/platform\"\n\nconst myUrl = new URL(\"https://example.com?foo=bar\")\n\nconst changedUrl = Url.modifyUrlParams(myUrl, UrlParams.append(\"key\", \"value\"))\n\nconsole.log(changedUrl.toString())\n// Output: https://example.com/?foo=bar&key=value\n```\n\n# OpenApiJsonSchema\n\nThe `OpenApiJsonSchema` module provides utilities to transform `Schema` objects into JSON schemas that comply with the OpenAPI Specification. These utilities are especially helpful for generating OpenAPI documentation or working with tools that require OpenAPI-compliant schemas.\n\n## Creating a JSON Schema from a Schema\n\nThis module enables you to convert `Schema` objects into OpenAPI-compatible JSON schemas, making it easy to integrate with tools like Swagger or other OpenAPI-based frameworks.\n\n**Example** (Generating a JSON Schema from a String Schema)\n\n```ts\nimport { OpenApiJsonSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\nconst schema = Schema.String\n\n// Convert the schema to OpenAPI JSON Schema\nconst openApiSchema = OpenApiJsonSchema.make(schema)\n\nconsole.log(JSON.stringify(openApiSchema, null, 2))\n/*\nOutput:\n{\n  \"type\": \"string\"\n}\n*/\n```\n\n## Differences from JSONSchema\n\nThe `OpenApiJsonSchema` module differs from the `JSONSchema` module in several ways. These differences are tailored to align with the OpenAPI Specification.\n\n### `$schema` Property Omission\n\nOpenAPI schemas do not include the `$schema` property, while JSON schemas do.\n\n**Example** (Comparison of `$schema` Property)\n\n```ts\nimport { OpenApiJsonSchema } from \"@effect/platform\"\nimport { JSONSchema, Schema } from \"effect\"\n\nconst schema = Schema.String\n\nconst openApiSchema = OpenApiJsonSchema.make(schema)\nconst jsonSchema = JSONSchema.make(schema)\n\nconsole.log(JSON.stringify(openApiSchema, null, 2))\n/*\nOutput:\n{\n  \"type\": \"string\"\n}\n*/\n\nconsole.log(JSON.stringify(jsonSchema, null, 2))\n/*\nOutput:\n{\n  \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n  \"type\": \"string\"\n}\n*/\n```\n\n### Handling of `null` Values\n\nOpenAPI does not support `{ \"type\": \"null\" }`. Instead, it uses an `enum` containing `null` to represent nullable values.\n\n**Example** (Representation of `null` Values)\n\n```ts\nimport { OpenApiJsonSchema } from \"@effect/platform\"\nimport { JSONSchema, Schema } from \"effect\"\n\nconst schema = Schema.Null\n\nconst openApiSchema = OpenApiJsonSchema.make(schema)\nconst jsonSchema = JSONSchema.make(schema)\n\nconsole.log(JSON.stringify(openApiSchema, null, 2))\n/*\nOutput:\n{\n  \"enum\": [\n    null\n  ]\n}\n*/\n\nconsole.log(JSON.stringify(jsonSchema, null, 2))\n/*\nOutput:\n{\n  \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n  \"type\": \"null\"\n}\n*/\n```\n\n### Nullable Values\n\nOpenAPI uses the `nullable` property to indicate that a value can be `null`, whereas JSON schemas use an `anyOf` structure.\n\n**Example** (Nullable Property Representation)\n\n```ts\nimport { OpenApiJsonSchema } from \"@effect/platform\"\nimport { JSONSchema, Schema } from \"effect\"\n\nconst schema = Schema.NullOr(Schema.String)\n\nconst openApiSchema = OpenApiJsonSchema.make(schema)\nconst jsonSchema = JSONSchema.make(schema)\n\nconsole.log(JSON.stringify(openApiSchema, null, 2))\n/*\nOutput:\n{\n  \"type\": \"string\",\n  \"nullable\": true\n}\n*/\n\nconsole.log(JSON.stringify(jsonSchema, null, 2))\n/*\nOutput:\n{\n  \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n  \"anyOf\": [\n    {\n      \"type\": \"string\"\n    },\n    {\n      \"type\": \"null\"\n    }\n  ]\n}\n*/\n```\n\n### `contentSchema` Support\n\nOpenAPI schemas include a `contentSchema` property, which allows you to describe the structure of the content for a media type (e.g., `application/json`). This feature is not available in JSON schemas (Draft 7), making `contentSchema` particularly useful for defining structured payloads in OpenAPI documentation.\n\n**Note**: Use `contentSchema` to define the internal structure of media types like `application/json` in OpenAPI specifications. This property provides clarity and detail for tools and users interacting with the API, especially when handling structured payloads.\n\n**Example** (Defining a Schema with `contentSchema` for JSON Content)\n\n```ts\nimport { OpenApiJsonSchema } from \"@effect/platform\"\nimport { JSONSchema, Schema } from \"effect\"\n\n// Define a schema for parsing JSON content\nconst schema = Schema.parseJson(Schema.Struct({ a: Schema.String }))\n\nconst openApiSchema = OpenApiJsonSchema.make(schema)\nconst jsonSchema = JSONSchema.make(schema)\n\nconsole.log(JSON.stringify(openApiSchema, null, 2))\n/*\nOutput:\n{\n  \"type\": \"string\",\n  \"contentMediaType\": \"application/json\",\n  \"contentSchema\": {\n    \"type\": \"object\",\n    \"required\": [\n      \"a\"\n    ],\n    \"properties\": {\n      \"a\": {\n        \"type\": \"string\"\n      }\n    },\n    \"additionalProperties\": false\n  }\n}\n*/\n\nconsole.log(JSON.stringify(jsonSchema, null, 2))\n/*\nOutput:\n{\n  \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n  \"type\": \"object\",\n  \"required\": [\n    \"a\"\n  ],\n  \"properties\": {\n    \"a\": {\n      \"type\": \"string\"\n    }\n  },\n  \"additionalProperties\": false\n}\n*/\n```\n\n### makeWithDefs\n\nThe `makeWithDefs` function generates OpenAPI-compatible JSON schemas and collects schema definitions in a shared object. This is especially useful for consolidating multiple schemas into a single OpenAPI specification, enabling schema reuse across your API.\n\n**Example** (Generating OpenAPI Schema with Definitions)\n\n```ts\nimport { OpenApiJsonSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\n// Define a schema with an identifier annotation\nconst schema = Schema.Struct({ a: Schema.String }).annotations({\n  identifier: \"MyStruct\"\n})\n\n// Create a definitions object\nconst defs = {}\n\n// Generate the OpenAPI schema while collecting definitions\nconst openApiSchema = OpenApiJsonSchema.makeWithDefs(schema, { defs })\n\nconsole.log(JSON.stringify(openApiSchema, null, 2))\n/*\nOutput:\n{\n  \"$ref\": \"#/components/schemas/MyStruct\"\n}\n*/\n\nconsole.log(JSON.stringify(defs, null, 2))\n/*\nOutput:\n{\n  \"MyStruct\": {\n    \"type\": \"object\",\n    \"required\": [\n      \"a\"\n    ],\n    \"properties\": {\n      \"a\": {\n        \"type\": \"string\"\n      }\n    },\n    \"additionalProperties\": false\n  }\n}\n*/\n```\n\n**Example** (Combining Multiple Schemas into One OpenAPI Specification)\n\n```ts\nimport { OpenApiJsonSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\n\n// Define multiple schemas with unique identifiers\nconst schema1 = Schema.Struct({ a: Schema.String }).annotations({\n  identifier: \"MyStruct1\"\n})\nconst schema2 = Schema.Struct({ b: Schema.Number }).annotations({\n  identifier: \"MyStruct2\"\n})\n\n// Create a shared definitions object\nconst defs = {}\n\n// Use `makeWithDefs` to generate schemas for API paths\nconst paths = {\n  paths: {\n    \"/path1\": {\n      get: {\n        responses: {\n          \"200\": {\n            content: {\n              \"application/json\": {\n                schema: OpenApiJsonSchema.makeWithDefs(schema1, { defs })\n              }\n            }\n          }\n        }\n      }\n    },\n    \"/path2\": {\n      get: {\n        responses: {\n          \"200\": {\n            content: {\n              \"application/json\": {\n                schema: OpenApiJsonSchema.makeWithDefs(schema2, { defs })\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n\n// Combine paths and definitions into a single OpenAPI schema\nconst openApiSchema = {\n  components: {\n    schemas: defs\n  },\n  paths\n}\n\nconsole.log(JSON.stringify(openApiSchema, null, 2))\n/*\nOutput:\n{\n  \"components\": {\n    \"schemas\": {\n      \"MyStruct1\": {\n        \"type\": \"object\",\n        \"required\": [\n          \"a\"\n        ],\n        \"properties\": {\n          \"a\": {\n            \"type\": \"string\"\n          }\n        },\n        \"additionalProperties\": false\n      },\n      \"MyStruct2\": {\n        \"type\": \"object\",\n        \"required\": [\n          \"b\"\n        ],\n        \"properties\": {\n          \"b\": {\n            \"type\": \"number\"\n          }\n        },\n        \"additionalProperties\": false\n      }\n    }\n  },\n  \"paths\": {\n    \"paths\": {\n      \"/path1\": {\n        \"get\": {\n          \"responses\": {\n            \"200\": {\n              \"content\": {\n                \"application/json\": {\n                  \"schema\": {\n                    \"$ref\": \"#/components/schemas/MyStruct1\"\n                  }\n                }\n              }\n            }\n          }\n        }\n      },\n      \"/path2\": {\n        \"get\": {\n          \"responses\": {\n            \"200\": {\n              \"content\": {\n                \"application/json\": {\n                  \"schema\": {\n                    \"$ref\": \"#/components/schemas/MyStruct2\"\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n*/\n```\n\n# HttpLayerRouter\n\nThe experimental `HttpLayerRouter` module provides a simplified way to create HTTP servers.\nIt aims to simplify the process of defining routes and registering other HTTP\nservices like `HttpApi` or `RpcServer`'s.\n\n## Registering routes\n\n```ts\nimport * as NodeHttpServer from \"@effect/platform-node/NodeHttpServer\"\nimport * as NodeRuntime from \"@effect/platform-node/NodeRuntime\"\nimport * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\nimport * as HttpServerResponse from \"@effect/platform/HttpServerResponse\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport { createServer } from \"http\"\n\n// Here is how you can register a simple GET route\nconst HelloRoute = Layer.effectDiscard(\n  Effect.gen(function* () {\n    // First, we need to access the `HttpRouter` service\n    const router = yield* HttpLayerRouter.HttpRouter\n\n    // Then, we can add a new route to the router\n    yield* router.add(\"GET\", \"/hello\", HttpServerResponse.text(\"Hello, World!\"))\n  })\n)\n\n// You can also use the `HttpLayerRouter.use` function to register a route\nconst GoodbyeRoute = HttpLayerRouter.use(\n  Effect.fn(function* (router) {\n    // The `router` parameter is the `HttpRouter` service\n    yield* router.add(\n      \"GET\",\n      \"/goodbye\",\n      HttpServerResponse.text(\"Goodbye, World!\")\n    )\n  })\n)\n// Or use `HttpLayerRouter.add/addAll` for simple routes\nconst SimpleRoute = HttpLayerRouter.add(\n  \"GET\",\n  \"/simple\",\n  HttpServerResponse.text(\"Simply fantastic!\")\n)\n\nconst AllRoutes = Layer.mergeAll(HelloRoute, GoodbyeRoute, SimpleRoute)\n\n// To start the server, we use `HttpLayerRouter.serve` with the routes layer\nHttpLayerRouter.serve(AllRoutes).pipe(\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })),\n  Layer.launch,\n  NodeRuntime.runMain\n)\n```\n\n## Applying middleware\n\n```ts\nimport * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\nimport * as HttpMiddleware from \"@effect/platform/HttpMiddleware\"\nimport * as HttpServerResponse from \"@effect/platform/HttpServerResponse\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\n\n// Here is a service that we want to provide to every HTTP request\nclass CurrentSession extends Context.Tag(\"CurrentSession\")<\n  CurrentSession,\n  {\n    readonly token: string\n  }\n>() {}\n\n// Using the `HttpLayerRouter.middleware` function, we can create a middleware\n// that provides the `CurrentSession` service to every HTTP request.\nconst SessionMiddleware = HttpLayerRouter.middleware<{\n  provides: CurrentSession\n}>()(\n  Effect.gen(function* () {\n    yield* Effect.log(\"SessionMiddleware initialized\")\n\n    return (httpEffect) =>\n      Effect.provideService(httpEffect, CurrentSession, {\n        token: \"dummy-token\"\n      })\n  })\n)\n\n// And here is an example of global middleware, that modifies the HTTP response.\n// Global middleware directly returns a `Layer`.\nconst CorsMiddleware = HttpLayerRouter.middleware(HttpMiddleware.cors(), {\n  global: true\n})\n// You can also use `HttpLayerRouter.cors()` to create a CORS middleware\n\nconst HelloRoute = HttpLayerRouter.add(\n  \"GET\",\n  \"/hello\",\n  Effect.gen(function* () {\n    // We can now access the `CurrentSession` service in our route handler\n    const session = yield* CurrentSession\n    return HttpServerResponse.text(\n      `Hello, World! Your session token is: ${session.token}`\n    )\n  })\n).pipe(\n  // We can provide the `SessionMiddleware.layer` to the `HelloRoute` layer\n  Layer.provide(SessionMiddleware.layer),\n  // And we can also provide the `CorsMiddleware` layer to handle CORS\n  Layer.provide(CorsMiddleware)\n)\n```\n\n## Interdependent middleware\n\nIf middleware depends on another middleware, you can use the `.combine` api to\ncombine them.\n\n```ts\nimport * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\nimport * as HttpServerResponse from \"@effect/platform/HttpServerResponse\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\n\nclass CurrentSession extends Context.Tag(\"CurrentSession\")<\n  CurrentSession,\n  {\n    readonly token: string\n  }\n>() {}\n\nconst SessionMiddleware = HttpLayerRouter.middleware<{\n  provides: CurrentSession\n}>()(\n  Effect.gen(function* () {\n    yield* Effect.log(\"SessionMiddleware initialized\")\n\n    return (httpEffect) =>\n      Effect.provideService(httpEffect, CurrentSession, {\n        token: \"dummy-token\"\n      })\n  })\n)\n\n// Here is a middleware that uses the `CurrentSession` service\nconst LogMiddleware = HttpLayerRouter.middleware(\n  Effect.gen(function* () {\n    yield* Effect.log(\"LogMiddleware initialized\")\n\n    return Effect.fn(function* (httpEffect) {\n      const session = yield* CurrentSession\n      yield* Effect.log(`Current session token: ${session.token}`)\n      return yield* httpEffect\n    })\n  })\n)\n\n// We can then use the .combine method to combine the middlewares\nconst LogAndSessionMiddleware = LogMiddleware.combine(SessionMiddleware)\n\nconst HelloRoute = HttpLayerRouter.add(\n  \"GET\",\n  \"/hello\",\n  Effect.gen(function* () {\n    const session = yield* CurrentSession\n    return HttpServerResponse.text(\n      `Hello, World! Your session token is: ${session.token}`\n    )\n  })\n).pipe(Layer.provide(LogAndSessionMiddleware.layer))\n```\n\n## Registering a HttpApi\n\n```ts\nimport {\n  HttpApi,\n  HttpApiBuilder,\n  HttpApiEndpoint,\n  HttpApiGroup,\n  HttpApiScalar,\n  HttpLayerRouter\n} from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { Effect, Layer } from \"effect\"\nimport { createServer } from \"http\"\n\n// First, we define our HttpApi\nclass MyApi extends HttpApi.make(\"api\").add(\n  HttpApiGroup.make(\"users\")\n    .add(HttpApiEndpoint.get(\"me\", \"/me\"))\n    .prefix(\"/users\")\n) {}\n\n// Implement the handlers for the API\nconst UsersApiLayer = HttpApiBuilder.group(MyApi, \"users\", (handers) =>\n  handers.handle(\"me\", () => Effect.void)\n)\n\n// Use `HttpLayerRouter.addHttpApi` to register the API with the router\nconst HttpApiRoutes = HttpLayerRouter.addHttpApi(MyApi, {\n  openapiPath: \"/docs/openapi.json\"\n}).pipe(\n  // Provide the api handlers layer\n  Layer.provide(UsersApiLayer)\n)\n\n// Create a /docs route for the API documentation\nconst DocsRoute = HttpApiScalar.layerHttpLayerRouter({\n  api: MyApi,\n  path: \"/docs\"\n})\n\n// Finally, we merge all routes and serve them using the Node HTTP server\nconst AllRoutes = Layer.mergeAll(HttpApiRoutes, DocsRoute).pipe(\n  Layer.provide(HttpLayerRouter.cors())\n)\n\nHttpLayerRouter.serve(AllRoutes).pipe(\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })),\n  Layer.launch,\n  NodeRuntime.runMain\n)\n```\n\n## Registering a RpcServer\n\n```ts\nimport { HttpLayerRouter } from \"@effect/platform\"\nimport { NodeHttpServer, NodeRuntime } from \"@effect/platform-node\"\nimport { Rpc, RpcGroup, RpcSerialization, RpcServer } from \"@effect/rpc\"\nimport { Effect, Layer, Schema } from \"effect\"\nimport { createServer } from \"http\"\n\nexport class User extends Schema.Class<User>(\"User\")({\n  id: Schema.String,\n  name: Schema.String\n}) {}\n\n// Define a group of RPCs\nexport class UserRpcs extends RpcGroup.make(\n  Rpc.make(\"UserById\", {\n    success: User,\n    error: Schema.String, // Indicates that errors, if any, will be returned as strings\n    payload: {\n      id: Schema.String\n    }\n  })\n) {}\n\nconst UserHandlers = UserRpcs.toLayer({\n  UserById: ({ id }) => Effect.succeed(new User({ id, name: \"John Doe\" }))\n})\n\n// Use `HttpLayerRouter` to register the rpc server\nconst RpcRoute = RpcServer.layerHttpRouter({\n  group: UserRpcs,\n  path: \"/rpc\"\n}).pipe(\n  Layer.provide(UserHandlers),\n  Layer.provide(RpcSerialization.layerJson),\n  Layer.provide(HttpLayerRouter.cors()) // provide CORS middleware\n)\n\n// Start the HTTP server with the RPC route\nHttpLayerRouter.serve(RpcRoute).pipe(\n  Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })),\n  Layer.launch,\n  NodeRuntime.runMain\n)\n```\n\n## Create a web handler\n\n```ts\nimport * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\nimport * as HttpServerResponse from \"@effect/platform/HttpServerResponse\"\nimport * as Effect from \"effect/Effect\"\n\nconst HelloRoute = HttpLayerRouter.use(\n  Effect.fn(function* (router) {\n    yield* router.add(\n      \"GET\",\n      \"/hello\",\n      HttpServerResponse.text(\"Hellow, World!\")\n    )\n  })\n)\n\nconst { dispose, handler } = HttpLayerRouter.toWebHandler(HelloRoute)\n\n// When the process is interrupted, we want to clean up resources\nprocess.on(\"SIGINT\", () => {\n  dispose().then(\n    () => {\n      process.exit(0)\n    },\n    () => {\n      process.exit(1)\n    }\n  )\n})\n\n// Use the handler in your server setup\nexport { handler }\n```\n"
  },
  {
    "path": "packages/platform/docgen.json",
    "content": "{\n  \"$schema\": \"../../node_modules/@effect/docgen/schema.json\",\n  \"srcLink\": \"https://github.com/Effect-TS/effect/tree/main/packages/platform/src/\",\n  \"exclude\": [\"src/internal/**/*.ts\"],\n  \"examplesCompilerOptions\": {\n    \"noEmit\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"Bundler\",\n    \"module\": \"ES2022\",\n    \"target\": \"ES2022\",\n    \"lib\": [\"ES2022\", \"DOM\", \"DOM.Iterable\"],\n    \"paths\": {\n      \"effect\": [\"../../../effect/src/index.js\"],\n      \"effect/*\": [\"../../../effect/src/*.js\"],\n      \"@effect/cluster\": [\"../../../cluster/src/index.js\"],\n      \"@effect/cluster/*\": [\"../../../cluster/src/*.js\"],\n      \"@effect/experimental\": [\"../../../experimental/src/index.js\"],\n      \"@effect/experimental/*\": [\"../../../experimental/src/*.js\"],\n      \"@effect/platform\": [\"../../../platform/src/index.js\"],\n      \"@effect/platform/*\": [\"../../../platform/src/*.js\"],\n      \"@effect/platform-node\": [\"../../../platform-node/src/index.js\"],\n      \"@effect/platform-node/*\": [\"../../../platform-node/src/*.js\"],\n      \"@effect/platform-node-shared\": [\n        \"../../../platform-node-shared/src/index.js\"\n      ],\n      \"@effect/platform-node-shared/*\": [\n        \"../../../platform-node-shared/src/*.js\"\n      ],\n      \"@effect/rpc\": [\"../../../rpc/src/index.js\"],\n      \"@effect/rpc/*\": [\"../../../rpc/src/*.js\"],\n      \"@effect/sql\": [\"../../../sql/src/index.js\"],\n      \"@effect/sql/*\": [\"../../../sql/src/*.js\"]\n    }\n  }\n}\n"
  },
  {
    "path": "packages/platform/dtslint/HttpApiClient.tst.ts",
    "content": "import type { HttpApiError, HttpClientError } from \"@effect/platform\"\nimport { HttpApi, HttpApiClient, HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpClient } from \"@effect/platform\"\nimport type { Schema } from \"effect\"\nimport { Effect } from \"effect\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const ApiError: Schema.Schema<\"ApiError\", \"ApiErrorEncoded\", \"ApiErrorR\">\n\ndeclare const Group1Error: Schema.Schema<\"Group1Error\", \"Group1ErrorEncoded\", \"Group1ErrorR\">\ndeclare const EndpointAError: Schema.Schema<\"EndpointAError\", \"EndpointAErrorEncoded\", \"EndpointAErrorR\">\ndeclare const EndpointASuccess: Schema.Schema<\"EndpointASuccess\", \"EndpointASuccessEncoded\", \"EndpointASuccessR\">\ndeclare const EndpointBError: Schema.Schema<\"EndpointBError\", \"EndpointBErrorEncoded\", \"EndpointBErrorR\">\ndeclare const EndpointBSuccess: Schema.Schema<\"EndpointBSuccess\", \"EndpointBSuccessEncoded\", \"EndpointBSuccessR\">\n\ndeclare const EndpointASecurityError: Schema.Schema<\n  \"EndpointASecurityError\",\n  \"EndpointASecurityErrorEncoded\",\n  \"EndpointASecurityErrorR\"\n>\nclass EndpointASecurity extends HttpApiMiddleware.Tag<EndpointASecurity>()(\"EndpointASecurity\", {\n  failure: EndpointASecurityError\n}) {}\ndeclare const EndpointBSecurityError: Schema.Schema<\n  \"EndpointBSecurityError\",\n  \"EndpointBSecurityErrorEncoded\",\n  \"EndpointBSecurityErrorR\"\n>\nclass EndpointBSecurity extends HttpApiMiddleware.Tag<EndpointBSecurity>()(\"EndpointBSecurity\", {\n  failure: EndpointBSecurityError\n}) {}\ndeclare const Group1SecurityError: Schema.Schema<\n  \"Group1SecurityError\",\n  \"Group1SecurityErrorEncoded\",\n  \"Group1SecurityErrorR\"\n>\nclass Group1Security extends HttpApiMiddleware.Tag<Group1Security>()(\"Group1Security\", {\n  failure: Group1SecurityError\n}) {}\ndeclare const ApiSecurityError: Schema.Schema<\n  \"ApiSecurityError\",\n  \"ApiSecurityErrorEncoded\",\n  \"ApiSecurityErrorR\"\n>\nclass ApiSecurity extends HttpApiMiddleware.Tag<ApiSecurity>()(\"ApiSecurity\", {\n  failure: ApiSecurityError\n}) {}\n\nconst EndpointA = HttpApiEndpoint.post(\"EndpointA\", \"/endpoint_a\")\n  .middleware(EndpointASecurity)\n  .addError(EndpointAError)\n  .addSuccess(EndpointASuccess)\nconst EndpointB = HttpApiEndpoint.post(\"EndpointB\", \"/endpoint_b\")\n  .middleware(EndpointBSecurity)\n  .addError(EndpointBError)\n  .addSuccess(EndpointBSuccess)\n\nconst Group1 = HttpApiGroup.make(\"Group1\")\n  .middleware(Group1Security)\n  .addError(Group1Error)\n  .add(EndpointA)\n  .add(EndpointB)\n\ndeclare const Group2Error: Schema.Schema<\"Group2Error\", \"Group2ErrorEncoded\", \"Group2ErrorR\">\ndeclare const EndpointCError: Schema.Schema<\"EndpointCError\", \"EndpointCErrorEncoded\", \"EndpointCErrorR\">\ndeclare const EndpointCSuccess: Schema.Schema<\"EndpointCSuccess\", \"EndpointCSuccessEncoded\", \"EndpointCSuccessR\">\n\nconst EndpointC = HttpApiEndpoint.post(\"EndpointC\", \"/endpoint_c\")\n  .addError(EndpointCError)\n  .addSuccess(EndpointCSuccess)\nconst Group2 = HttpApiGroup.make(\"Group2\")\n  .addError(Group2Error)\n  .add(EndpointC)\n\nconst TestApi = HttpApi.make(\"test\")\n  .middleware(ApiSecurity)\n  .addError(ApiError)\n  .add(Group1)\n  .add(Group2)\n\ndescribe(\"HttpApiClient\", () => {\n  it(\"endpoint\", () => {\n    Effect.gen(function*() {\n      const clientEndpointEffect = HttpApiClient.endpoint(TestApi, {\n        httpClient: yield* HttpClient.HttpClient,\n        group: \"Group1\",\n        endpoint: \"EndpointA\"\n      })\n      expect<Effect.Effect.Error<typeof clientEndpointEffect>>().type.toBe<never>()\n      expect<Effect.Effect.Context<typeof clientEndpointEffect>>().type.toBe<\n        | \"ApiErrorR\"\n        | \"Group1ErrorR\"\n        | \"EndpointAErrorR\"\n        | \"EndpointASuccessR\"\n        | \"EndpointASecurityErrorR\"\n        | \"Group1SecurityErrorR\"\n        | \"ApiSecurityErrorR\"\n      >()\n\n      const clientEndpoint = yield* clientEndpointEffect\n\n      expect(clientEndpoint({ withResponse: false })).type.toBe<\n        Effect.Effect<\n          \"EndpointASuccess\",\n          | \"ApiError\"\n          | \"Group1Error\"\n          | \"EndpointAError\"\n          | \"EndpointASecurityError\"\n          | \"Group1SecurityError\"\n          | \"ApiSecurityError\"\n          | HttpApiError.HttpApiDecodeError\n          | HttpClientError.HttpClientError\n          | ParseError\n        >\n      >()\n    })\n  })\n\n  it(\"group\", () => {\n    Effect.gen(function*() {\n      const clientGroupEffect = HttpApiClient.group(TestApi, {\n        httpClient: yield* HttpClient.HttpClient,\n        group: \"Group1\"\n      })\n\n      expect<Effect.Effect.Error<typeof clientGroupEffect>>().type.toBe<never>()\n\n      expect<Effect.Effect.Context<typeof clientGroupEffect>>().type.toBe<\n        | \"ApiErrorR\"\n        | \"Group1ErrorR\"\n        | \"EndpointAErrorR\"\n        | \"EndpointASuccessR\"\n        | \"EndpointBErrorR\"\n        | \"EndpointBSuccessR\"\n        | \"EndpointASecurityErrorR\"\n        | \"EndpointBSecurityErrorR\"\n        | \"Group1SecurityErrorR\"\n        | \"ApiSecurityErrorR\"\n      >()\n\n      const clientGroup = yield* clientGroupEffect\n\n      expect(clientGroup.EndpointA({ withResponse: false })).type.toBe<\n        Effect.Effect<\n          \"EndpointASuccess\",\n          | \"ApiError\"\n          | \"Group1Error\"\n          | \"EndpointAError\"\n          | \"EndpointASecurityError\"\n          | \"Group1SecurityError\"\n          | \"ApiSecurityError\"\n          | HttpApiError.HttpApiDecodeError\n          | HttpClientError.HttpClientError\n          | ParseError\n        >\n      >()\n    })\n  })\n\n  it(\"make\", () => {\n    Effect.gen(function*() {\n      const clientApiEffect = HttpApiClient.make(TestApi)\n\n      expect<Effect.Effect.Error<typeof clientApiEffect>>().type.toBe<never>()\n\n      expect<Effect.Effect.Context<typeof clientApiEffect>>().type.toBe<\n        | \"ApiErrorR\"\n        | \"Group1ErrorR\"\n        | \"EndpointAErrorR\"\n        | \"EndpointASuccessR\"\n        | \"EndpointBErrorR\"\n        | \"EndpointBSuccessR\"\n        | \"EndpointASecurityErrorR\"\n        | \"EndpointBSecurityErrorR\"\n        | \"Group1SecurityErrorR\"\n        | \"ApiSecurityErrorR\"\n        | \"Group2ErrorR\"\n        | \"EndpointCErrorR\"\n        | \"EndpointCSuccessR\"\n        | HttpClient.HttpClient\n      >()\n\n      const clientApi = yield* clientApiEffect\n\n      expect(clientApi.Group1.EndpointA({ withResponse: false })).type.toBe<\n        Effect.Effect<\n          \"EndpointASuccess\",\n          | \"ApiError\"\n          | \"Group1Error\"\n          | \"EndpointAError\"\n          | \"EndpointASecurityError\"\n          | \"Group1SecurityError\"\n          | \"ApiSecurityError\"\n          | HttpApiError.HttpApiDecodeError\n          | HttpClientError.HttpClientError\n          | ParseError\n        >\n      >()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/platform/dtslint/HttpApiEndpoint.tst.ts",
    "content": "/* eslint @typescript-eslint/no-unused-expressions: \"off\" */\n\nimport { HttpApiEndpoint, HttpApiSchema } from \"@effect/platform\"\nimport { Schema } from \"effect\"\nimport { describe, it } from \"tstyche\"\n\ndescribe(\"HttpApiEndpoint\", () => {\n  it(\"should prevent duplicated params\", () => {\n    HttpApiEndpoint.get(\"test\")`/${HttpApiSchema.param(\"id\", Schema.NumberFromString)}/${\n      // @ts-expect-error: Argument of type 'Param<\"id\", typeof NumberFromString>' is not assignable to parameter of type '\"Duplicate param: id\"'\n      HttpApiSchema.param(\"id\", Schema.NumberFromString)}`\n  })\n})\n"
  },
  {
    "path": "packages/platform/dtslint/HttpRouter.tst.ts",
    "content": "import { HttpRouter } from \"@effect/platform\"\nimport { describe, expect, it } from \"tstyche\"\n\ndeclare const router1: HttpRouter.HttpRouter<\"E1\", \"R1\">\ndeclare const router2: HttpRouter.HttpRouter<\"E2\", \"R2\">\ndeclare const router3: HttpRouter.HttpRouter<\"E3\", \"R3\">\n\ndescribe(\"HttpApiRouter\", () => {\n  it(\"concatAll\", () => {\n    expect(HttpRouter.concatAll(router1, router2, router3)).type.toBe<\n      HttpRouter.HttpRouter<\"E1\" | \"E2\" | \"E3\", \"R1\" | \"R2\" | \"R3\">\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/platform/dtslint/tsconfig.json",
    "content": "{\n  \"extends\": \"../../../tsconfig.base.json\",\n  \"include\": [\".\"],\n  \"references\": [\n    { \"path\": \"../tsconfig.src.json\" },\n  ],\n  \"compilerOptions\": {\n    \"incremental\": false,\n    \"composite\": false,\n    \"noUnusedLocals\": false,\n    \"plugins\": [\n      {\n        \"name\": \"@effect/language-server\",\n        \"diagnostics\": false\n      }\n    ]\n  }\n}\n"
  },
  {
    "path": "packages/platform/package.json",
    "content": "{\n  \"name\": \"@effect/platform\",\n  \"type\": \"module\",\n  \"version\": \"0.96.0\",\n  \"license\": \"MIT\",\n  \"description\": \"Unified interfaces for common platform-specific services\",\n  \"homepage\": \"https://effect.website\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/Effect-TS/effect.git\",\n    \"directory\": \"packages/platform\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/Effect-TS/effect/issues\"\n  },\n  \"tags\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"keywords\": [\n    \"typescript\",\n    \"algebraic-data-types\",\n    \"functional-programming\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\",\n    \"provenance\": true,\n    \"directory\": \"dist\",\n    \"linkDirectory\": false\n  },\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": \"./src/index.ts\",\n    \"./*\": \"./src/*.ts\",\n    \"./internal/*\": null\n  },\n  \"scripts\": {\n    \"codegen\": \"build-utils prepare-v3\",\n    \"build\": \"pnpm build-esm && pnpm build-annotate && pnpm build-cjs && build-utils pack-v3\",\n    \"build-esm\": \"tsc -b tsconfig.build.json\",\n    \"build-cjs\": \"babel build/esm --plugins @babel/transform-export-namespace-from --plugins @babel/transform-modules-commonjs --out-dir build/cjs --source-maps\",\n    \"build-annotate\": \"babel build/esm --plugins annotate-pure-calls --out-dir build/esm --source-maps\",\n    \"test-types\": \"tstyche\",\n    \"check\": \"tsc -b tsconfig.json\",\n    \"test\": \"vitest\",\n    \"coverage\": \"vitest --coverage\"\n  },\n  \"dependencies\": {\n    \"find-my-way-ts\": \"^0.1.6\",\n    \"msgpackr\": \"^1.11.4\",\n    \"multipasta\": \"^0.2.7\"\n  },\n  \"peerDependencies\": {\n    \"effect\": \"workspace:^\"\n  },\n  \"devDependencies\": {\n    \"ajv\": \"^8.17.1\",\n    \"effect\": \"workspace:^\"\n  }\n}\n"
  },
  {
    "path": "packages/platform/src/ChannelSchema.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Cause from \"effect/Cause\"\nimport * as Channel from \"effect/Channel\"\nimport type * as Chunk from \"effect/Chunk\"\nimport { dual, pipe } from \"effect/Function\"\nimport type { ParseError } from \"effect/ParseResult\"\nimport * as Schema from \"effect/Schema\"\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const encode = <A, I, R>(\n  schema: Schema.Schema<A, I, R>\n) =>\n<IE = never, Done = unknown>(): Channel.Channel<\n  Chunk.Chunk<I>,\n  Chunk.Chunk<A>,\n  IE | ParseError,\n  IE,\n  Done,\n  Done,\n  R\n> => {\n  const encode = Schema.encode(Schema.ChunkFromSelf(schema))\n  const loop: Channel.Channel<Chunk.Chunk<I>, Chunk.Chunk<A>, IE | ParseError, IE, Done, Done, R> = Channel\n    .readWithCause({\n      onInput: (input: Chunk.Chunk<A>) =>\n        Channel.zipRight(\n          Channel.flatMap(encode(input), Channel.write),\n          loop\n        ),\n      onFailure: (cause: Cause.Cause<IE>) => Channel.failCause(cause),\n      onDone: Channel.succeed\n    })\n  return loop\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const encodeUnknown: <A, I, R>(\n  schema: Schema.Schema<A, I, R>\n) => <IE = never, Done = unknown>() => Channel.Channel<\n  Chunk.Chunk<unknown>,\n  Chunk.Chunk<A>,\n  IE | ParseError,\n  IE,\n  Done,\n  Done,\n  R\n> = encode as any\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const decode = <A, I, R>(\n  schema: Schema.Schema<A, I, R>\n) =>\n<IE = never, Done = unknown>(): Channel.Channel<\n  Chunk.Chunk<A>,\n  Chunk.Chunk<I>,\n  ParseError | IE,\n  IE,\n  Done,\n  Done,\n  R\n> => {\n  const decode = Schema.decode(Schema.ChunkFromSelf(schema))\n  const loop: Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<I>, ParseError | IE, IE, Done, Done, R> = Channel\n    .readWithCause({\n      onInput(chunk: Chunk.Chunk<I>) {\n        return decode(chunk).pipe(\n          Channel.flatMap(Channel.write),\n          Channel.zipRight(loop)\n        )\n      },\n      onFailure(cause: Cause.Cause<IE>) {\n        return Channel.failCause(cause)\n      },\n      onDone(done: Done) {\n        return Channel.succeed(done)\n      }\n    })\n  return loop\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const decodeUnknown: <A, I, R>(\n  schema: Schema.Schema<A, I, R>\n) => <IE = never, Done = unknown>() => Channel.Channel<\n  Chunk.Chunk<A>,\n  Chunk.Chunk<any>,\n  ParseError | IE,\n  IE,\n  Done,\n  Done,\n  R\n> = decode as any\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const duplex: {\n  <IA, II, IR, OA, OI, OR>(options: {\n    readonly inputSchema: Schema.Schema<IA, II, IR>\n    readonly outputSchema: Schema.Schema<OA, OI, OR>\n  }): <R, InErr, OutErr, OutDone, InDone>(\n    self: Channel.Channel<\n      Chunk.Chunk<OI>,\n      Chunk.Chunk<II>,\n      OutErr,\n      ParseError | InErr,\n      OutDone,\n      InDone,\n      R\n    >\n  ) => Channel.Channel<\n    Chunk.Chunk<OA>,\n    Chunk.Chunk<IA>,\n    ParseError | OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    R | IR | OR\n  >\n  <R, InErr, OutErr, OutDone, InDone, IA, II, IR, OA, OI, OR>(\n    self: Channel.Channel<\n      Chunk.Chunk<OI>,\n      Chunk.Chunk<II>,\n      OutErr,\n      ParseError | InErr,\n      OutDone,\n      InDone,\n      R\n    >,\n    options: {\n      readonly inputSchema: Schema.Schema<IA, II, IR>\n      readonly outputSchema: Schema.Schema<OA, OI, OR>\n    }\n  ): Channel.Channel<\n    Chunk.Chunk<OA>,\n    Chunk.Chunk<IA>,\n    ParseError | OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    R | IR | OR\n  >\n} = dual(2, <R, InErr, OutErr, OutDone, InDone, IA, II, IR, OA, OI, OR>(\n  self: Channel.Channel<\n    Chunk.Chunk<OI>,\n    Chunk.Chunk<II>,\n    OutErr,\n    ParseError | InErr,\n    OutDone,\n    InDone,\n    R\n  >,\n  options: {\n    readonly inputSchema: Schema.Schema<IA, II, IR>\n    readonly outputSchema: Schema.Schema<OA, OI, OR>\n  }\n): Channel.Channel<\n  Chunk.Chunk<OA>,\n  Chunk.Chunk<IA>,\n  ParseError | OutErr,\n  InErr,\n  OutDone,\n  InDone,\n  R | IR | OR\n> => {\n  const decode = Schema.decode(Schema.ChunkFromSelf(options.outputSchema))\n  return pipe(\n    encode(options.inputSchema)<InErr, InDone>(),\n    Channel.pipeTo(self),\n    Channel.mapOutEffect(decode)\n  )\n})\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const duplexUnknown: {\n  <IA, II, IR, OA, OI, OR>(options: {\n    readonly inputSchema: Schema.Schema<IA, II, IR>\n    readonly outputSchema: Schema.Schema<OA, OI, OR>\n  }): <R, InErr, OutErr, OutDone, InDone>(\n    self: Channel.Channel<\n      Chunk.Chunk<unknown>,\n      Chunk.Chunk<any>,\n      OutErr,\n      ParseError | InErr,\n      OutDone,\n      InDone,\n      R\n    >\n  ) => Channel.Channel<\n    Chunk.Chunk<OA>,\n    Chunk.Chunk<IA>,\n    ParseError | OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    R | IR | OR\n  >\n  <R, InErr, OutErr, OutDone, InDone, IA, II, IR, OA, OI, OR>(\n    self: Channel.Channel<\n      Chunk.Chunk<unknown>,\n      Chunk.Chunk<any>,\n      OutErr,\n      ParseError | InErr,\n      OutDone,\n      InDone,\n      R\n    >,\n    options: {\n      readonly inputSchema: Schema.Schema<IA, II, IR>\n      readonly outputSchema: Schema.Schema<OA, OI, OR>\n    }\n  ): Channel.Channel<\n    Chunk.Chunk<OA>,\n    Chunk.Chunk<IA>,\n    ParseError | OutErr,\n    InErr,\n    OutDone,\n    InDone,\n    R | IR | OR\n  >\n} = duplex as any\n"
  },
  {
    "path": "packages/platform/src/Command.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport type { Effect } from \"effect/Effect\"\nimport type { HashMap } from \"effect/HashMap\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport type { Option } from \"effect/Option\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport type { Scope } from \"effect/Scope\"\nimport type { Sink } from \"effect/Sink\"\nimport type { Stream } from \"effect/Stream\"\nimport type { CommandExecutor, ExitCode, Process } from \"./CommandExecutor.js\"\nimport type { PlatformError } from \"./Error.js\"\nimport * as internal from \"./internal/command.js\"\n\n/**\n * @since 1.0.0\n */\nexport const CommandTypeId: unique symbol = internal.CommandTypeId\n\n/**\n * @since 1.0.0\n */\nexport type CommandTypeId = typeof CommandTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Command = StandardCommand | PipedCommand\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Command {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Proto extends Pipeable, Inspectable {\n    readonly [CommandTypeId]: CommandTypeId\n    readonly _tag: string\n  }\n  /**\n   * Configures the pipe that is established between the parent and child\n   * processes' `stdin` stream.\n   *\n   * @since 1.0.0\n   * @category models\n   */\n  export type Input = CommandInput\n  /**\n   * Configures the pipes that are established between the parent and child\n   * processes `stderr` and `stdout` streams.\n   *\n   * @since 1.0.0\n   * @category models\n   */\n  export type Output = CommandOutput\n}\n\n/**\n * Configures the pipe that is established between the parent and child\n * processes' `stdin` stream.\n *\n * Defaults to \"pipe\"\n *\n * @since 1.0.0\n * @category models\n */\nexport type CommandInput = \"inherit\" | \"pipe\" | Stream<Uint8Array, PlatformError>\n\n/**\n * Configures the pipes that are established between the parent and child\n * processes `stderr` and `stdout` streams.\n *\n * Defaults to \"pipe\"\n *\n * @since 1.0.0\n * @category models\n */\nexport type CommandOutput = \"inherit\" | \"pipe\" | Sink<Uint8Array, Uint8Array>\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface StandardCommand extends Command.Proto {\n  readonly _tag: \"StandardCommand\"\n  readonly command: string\n  readonly args: ReadonlyArray<string>\n  readonly env: HashMap<string, string>\n  readonly cwd: Option<string>\n  readonly shell: boolean | string\n  readonly stdin: Command.Input\n  readonly stdout: Command.Output\n  readonly stderr: Command.Output\n  readonly gid: Option<number>\n  readonly uid: Option<number>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface PipedCommand extends Command.Proto {\n  readonly _tag: \"PipedCommand\"\n  readonly left: Command\n  readonly right: Command\n}\n\n/**\n * Returns `true` if the specified value is a `Command`, otherwise returns\n * `false`.\n *\n * @since 1.0.0\n * @category refinements\n */\nexport const isCommand: (u: unknown) => u is Command = internal.isCommand\n\n/**\n * Specify the environment variables that will be used when running this command.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const env: {\n  (environment: Record<string, string | undefined>): (self: Command) => Command\n  (self: Command, environment: Record<string, string | undefined>): Command\n} = internal.env\n\n/**\n * Returns the exit code of the command after the process has completed\n * execution.\n *\n * @since 1.0.0\n * @category execution\n */\nexport const exitCode: (self: Command) => Effect<ExitCode, PlatformError, CommandExecutor> = internal.exitCode\n\n/**\n * Feed a string to standard input (default encoding of UTF-8).\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const feed: {\n  (input: string): (self: Command) => Command\n  (self: Command, input: string): Command\n} = internal.feed\n\n/**\n * Flatten this command to a non-empty array of standard commands.\n *\n * For a `StandardCommand`, this simply returns a `1` element array\n * For a `PipedCommand`, all commands in the pipe will be extracted out into\n * a array from left to right\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const flatten: (self: Command) => NonEmptyReadonlyArray<StandardCommand> = internal.flatten\n\n/**\n * Runs the command returning the output as an array of lines with the specified\n * encoding.\n *\n * @since 1.0.0\n * @category execution\n */\nexport const lines: (command: Command, encoding?: string) => Effect<Array<string>, PlatformError, CommandExecutor> =\n  internal.lines\n\n/**\n * Create a command with the specified process name and an optional list of\n * arguments.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make: (command: string, ...args: Array<string>) => Command = internal.make\n\n/**\n * Pipe one command to another command from left to right.\n *\n * Conceptually, the equivalent of piping one shell command to another:\n *\n * ```sh\n * command1 | command2\n * ```\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const pipeTo: {\n  (into: Command): (self: Command) => Command\n  (self: Command, into: Command): Command\n} = internal.pipeTo\n\n/**\n * Allows for specifying whether or not a `Command` should be run inside a\n * shell.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const runInShell: {\n  (shell: string | boolean): (self: Command) => Command\n  (self: Command, shell: string | boolean): Command\n} = internal.runInShell\n\n/**\n * Start running the command and return a handle to the running process.\n *\n * @since 1.0.0\n * @category execution\n */\nexport const start: (command: Command) => Effect<Process, PlatformError, CommandExecutor | Scope> = internal.start\n\n/**\n * Start running the command and return the output as a `Stream`.\n *\n * @since 1.0.0\n * @category execution\n */\nexport const stream: (command: Command) => Stream<Uint8Array, PlatformError, CommandExecutor> = internal.stream\n\n/**\n * Runs the command returning the output as an stream of lines with the\n * specified encoding.\n *\n * @since 1.0.0\n * @category execution\n */\nexport const streamLines: (command: Command, encoding?: string) => Stream<string, PlatformError, CommandExecutor> =\n  internal.streamLines\n\n/**\n * Runs the command returning the entire output as a string with the\n * specified encoding.\n *\n * If an encoding is not specified, the encoding will default to `utf-8`.\n *\n * @since 1.0.0\n * @category execution\n */\nexport const string: {\n  (encoding?: string): (command: Command) => Effect<string, PlatformError, CommandExecutor>\n  (command: Command, encoding?: string): Effect<string, PlatformError, CommandExecutor>\n} = internal.string\n\n/**\n * Specify the standard error stream for a command.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const stderr: {\n  (stderr: Command.Output): (self: Command) => Command\n  (self: Command, stderr: Command.Output): Command\n} = internal.stderr\n\n/**\n * Specify the standard input stream for a command.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const stdin: {\n  (stdin: Command.Input): (self: Command) => Command\n  (self: Command, stdin: Command.Input): Command\n} = internal.stdin\n\n/**\n * Specify the standard output stream for a command.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const stdout: {\n  (stdout: Command.Output): (self: Command) => Command\n  (self: Command, stdout: Command.Output): Command\n} = internal.stdout\n\n/**\n * Set the working directory that will be used when this command will be run.\n *\n * For piped commands, the working directory of each command will be set to the\n * specified working directory.\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const workingDirectory: {\n  (cwd: string): (self: Command) => Command\n  (self: Command, cwd: string): Command\n} = internal.workingDirectory\n"
  },
  {
    "path": "packages/platform/src/CommandExecutor.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Brand from \"effect/Brand\"\nimport type { Tag } from \"effect/Context\"\nimport type { Effect } from \"effect/Effect\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport type { Scope } from \"effect/Scope\"\nimport type { Sink } from \"effect/Sink\"\nimport type { Stream } from \"effect/Stream\"\nimport type { Command } from \"./Command.js\"\nimport type { PlatformError } from \"./Error.js\"\nimport * as internal from \"./internal/commandExecutor.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface CommandExecutor {\n  readonly [TypeId]: TypeId\n\n  /**\n   * Returns the exit code of the command after the process has completed\n   * execution.\n   */\n  readonly exitCode: (command: Command) => Effect<ExitCode, PlatformError>\n  /**\n   * Start running the command and return a handle to the running process.\n   */\n  readonly start: (command: Command) => Effect<Process, PlatformError, Scope>\n  /**\n   * Runs the command returning the entire output as a string with the\n   * specified encoding.\n   *\n   * If an encoding is not specified, the encoding will default to `utf-8`.\n   */\n  readonly string: (command: Command, encoding?: string) => Effect<string, PlatformError>\n  /**\n   * Runs the command returning the entire output as an array of lines.\n   *\n   * If an encoding is not specified, the encoding will default to `utf-8`.\n   */\n  readonly lines: (command: Command, encoding?: string) => Effect<Array<string>, PlatformError>\n  /**\n   * Runs the command returning the output as a `Stream`.\n   */\n  readonly stream: (command: Command) => Stream<Uint8Array, PlatformError>\n  /**\n   * Runs the command returning the output as a `Stream` of lines.\n   */\n  readonly streamLines: (command: Command, encoding?: string) => Stream<string, PlatformError>\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const CommandExecutor: Tag<CommandExecutor, CommandExecutor> = internal.CommandExecutor\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport const ProcessTypeId: unique symbol = internal.ProcessTypeId\n\n/**\n * @since 1.0.0\n * @category symbols\n */\nexport type ProcessTypeId = typeof ProcessTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Process extends Inspectable {\n  readonly [ProcessTypeId]: ProcessTypeId\n  /**\n   * The process identifier.\n   */\n  readonly pid: ProcessId\n  /**\n   * Waits for the process to exit and returns the `ExitCode` of the command\n   * that was run.\n   */\n  readonly exitCode: Effect<ExitCode, PlatformError>\n  /**\n   * Returns `true` if the process is still running, otherwise returns `false`.\n   */\n  readonly isRunning: Effect<boolean, PlatformError>\n  /**\n   * Kills the running process with the provided signal.\n   *\n   * If no signal is provided, the signal will defaults to `SIGTERM`.\n   */\n  readonly kill: (signal?: Signal) => Effect<void, PlatformError>\n  /**\n   * The standard error stream of the process.\n   */\n  readonly stderr: Stream<Uint8Array, PlatformError>\n  /**\n   * The standard input sink of the process.\n   */\n  readonly stdin: Sink<void, Uint8Array, never, PlatformError>\n  /**\n   * The standard output stream of the process.\n   */\n  readonly stdout: Stream<Uint8Array, PlatformError>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type ProcessId = Brand.Branded<number, \"ProcessId\">\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Process {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Id = ProcessId\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Signal =\n  | \"SIGABRT\"\n  | \"SIGALRM\"\n  | \"SIGBUS\"\n  | \"SIGCHLD\"\n  | \"SIGCONT\"\n  | \"SIGFPE\"\n  | \"SIGHUP\"\n  | \"SIGILL\"\n  | \"SIGINT\"\n  | \"SIGIO\"\n  | \"SIGIOT\"\n  | \"SIGKILL\"\n  | \"SIGPIPE\"\n  | \"SIGPOLL\"\n  | \"SIGPROF\"\n  | \"SIGPWR\"\n  | \"SIGQUIT\"\n  | \"SIGSEGV\"\n  | \"SIGSTKFLT\"\n  | \"SIGSTOP\"\n  | \"SIGSYS\"\n  | \"SIGTERM\"\n  | \"SIGTRAP\"\n  | \"SIGTSTP\"\n  | \"SIGTTIN\"\n  | \"SIGTTOU\"\n  | \"SIGUNUSED\"\n  | \"SIGURG\"\n  | \"SIGUSR1\"\n  | \"SIGUSR2\"\n  | \"SIGVTALRM\"\n  | \"SIGWINCH\"\n  | \"SIGXCPU\"\n  | \"SIGXFSZ\"\n  | \"SIGBREAK\"\n  | \"SIGLOST\"\n  | \"SIGINFO\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type ExitCode = Brand.Branded<number, \"ExitCode\">\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const ExitCode: Brand.Brand.Constructor<ExitCode> = internal.ExitCode\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const ProcessId: Brand.Brand.Constructor<Process.Id> = internal.ProcessId\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeExecutor: (\n  start: (command: Command) => Effect<Process, PlatformError, Scope>\n) => CommandExecutor = internal.makeExecutor\n"
  },
  {
    "path": "packages/platform/src/Cookies.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Duration from \"effect/Duration\"\nimport * as Either from \"effect/Either\"\nimport { dual, identity } from \"effect/Function\"\nimport * as Inspectable from \"effect/Inspectable\"\nimport * as Option from \"effect/Option\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Record from \"effect/Record\"\nimport type * as Types from \"effect/Types\"\nimport { TypeIdError } from \"./Error.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/Cookies\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isCookies = (u: unknown): u is Cookies => Predicate.hasProperty(u, TypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Cookies extends Pipeable, Inspectable.Inspectable {\n  readonly [TypeId]: TypeId\n  readonly cookies: Record.ReadonlyRecord<string, Cookie>\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const CookieTypeId: unique symbol = Symbol.for(\"@effect/platform/Cookies/Cookie\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type CookieTypeId = typeof CookieTypeId\n\n/**\n * @since 1.0.0\n * @category cookie\n */\nexport interface Cookie extends Inspectable.Inspectable {\n  readonly [CookieTypeId]: CookieTypeId\n  readonly name: string\n  readonly value: string\n  readonly valueEncoded: string\n  readonly options?: {\n    readonly domain?: string | undefined\n    readonly expires?: Date | undefined\n    readonly maxAge?: Duration.DurationInput | undefined\n    readonly path?: string | undefined\n    readonly priority?: \"low\" | \"medium\" | \"high\" | undefined\n    readonly httpOnly?: boolean | undefined\n    readonly secure?: boolean | undefined\n    readonly partitioned?: boolean | undefined\n    readonly sameSite?: \"lax\" | \"strict\" | \"none\" | undefined\n  } | undefined\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const ErrorTypeId: unique symbol = Symbol.for(\"@effect/platform/Cookies/CookieError\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type ErrorTypeId = typeof ErrorTypeId\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport class CookiesError extends TypeIdError(ErrorTypeId, \"CookieError\")<{\n  readonly reason: \"InvalidName\" | \"InvalidValue\" | \"InvalidDomain\" | \"InvalidPath\" | \"InfinityMaxAge\"\n}> {\n  get message() {\n    return this.reason\n  }\n}\n\nconst Proto: Omit<Cookies, \"cookies\"> = {\n  [TypeId]: TypeId,\n  ...Inspectable.BaseProto,\n  toJSON(this: Cookies) {\n    return {\n      _id: \"@effect/platform/Cookies\",\n      cookies: Record.map(this.cookies, (cookie) => cookie.toJSON())\n    }\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\n/**\n * Create a Cookies object from an Iterable\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fromReadonlyRecord = (cookies: Record.ReadonlyRecord<string, Cookie>): Cookies => {\n  const self = Object.create(Proto)\n  self.cookies = cookies\n  return self\n}\n\n/**\n * Create a Cookies object from an Iterable\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fromIterable = (cookies: Iterable<Cookie>): Cookies => {\n  const record: Record<string, Cookie> = {}\n  for (const cookie of cookies) {\n    record[cookie.name] = cookie\n  }\n  return fromReadonlyRecord(record)\n}\n\n/**\n * Create a Cookies object from a set of Set-Cookie headers\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const fromSetCookie = (headers: Iterable<string> | string): Cookies => {\n  const arrayHeaders = typeof headers === \"string\" ? [headers] : headers\n  const cookies: Array<Cookie> = []\n  for (const header of arrayHeaders) {\n    const cookie = parseSetCookie(header.trim())\n    if (Option.isSome(cookie)) {\n      cookies.push(cookie.value)\n    }\n  }\n\n  return fromIterable(cookies)\n}\n\nfunction parseSetCookie(header: string): Option.Option<Cookie> {\n  const parts = header.split(\";\").map((_) => _.trim()).filter((_) => _ !== \"\")\n  if (parts.length === 0) {\n    return Option.none()\n  }\n\n  const firstEqual = parts[0].indexOf(\"=\")\n  if (firstEqual === -1) {\n    return Option.none()\n  }\n  const name = parts[0].slice(0, firstEqual)\n  if (!fieldContentRegExp.test(name)) {\n    return Option.none()\n  }\n\n  const valueEncoded = parts[0].slice(firstEqual + 1)\n  const value = tryDecodeURIComponent(valueEncoded)\n\n  if (parts.length === 1) {\n    return Option.some(Object.assign(Object.create(CookieProto), {\n      name,\n      value,\n      valueEncoded\n    }))\n  }\n\n  const options: Types.Mutable<Cookie[\"options\"]> = {}\n\n  for (let i = 1; i < parts.length; i++) {\n    const part = parts[i]\n    const equalIndex = part.indexOf(\"=\")\n    const key = equalIndex === -1 ? part : part.slice(0, equalIndex).trim()\n    const value = equalIndex === -1 ? undefined : part.slice(equalIndex + 1).trim()\n\n    switch (key.toLowerCase()) {\n      case \"domain\": {\n        if (value === undefined) {\n          break\n        }\n        const domain = value.trim().replace(/^\\./, \"\")\n        if (domain) {\n          options.domain = domain\n        }\n        break\n      }\n      case \"expires\": {\n        if (value === undefined) {\n          break\n        }\n        const date = new Date(value)\n        if (!isNaN(date.getTime())) {\n          options.expires = date\n        }\n        break\n      }\n      case \"max-age\": {\n        if (value === undefined) {\n          break\n        }\n        const maxAge = parseInt(value, 10)\n        if (!isNaN(maxAge)) {\n          options.maxAge = Duration.seconds(maxAge)\n        }\n        break\n      }\n      case \"path\": {\n        if (value === undefined) {\n          break\n        }\n        if (value[0] === \"/\") {\n          options.path = value\n        }\n        break\n      }\n      case \"priority\": {\n        if (value === undefined) {\n          break\n        }\n        switch (value.toLowerCase()) {\n          case \"low\":\n            options.priority = \"low\"\n            break\n          case \"medium\":\n            options.priority = \"medium\"\n            break\n          case \"high\":\n            options.priority = \"high\"\n            break\n        }\n        break\n      }\n      case \"httponly\": {\n        options.httpOnly = true\n        break\n      }\n      case \"secure\": {\n        options.secure = true\n        break\n      }\n      case \"partitioned\": {\n        options.partitioned = true\n        break\n      }\n      case \"samesite\": {\n        if (value === undefined) {\n          break\n        }\n        switch (value.toLowerCase()) {\n          case \"lax\":\n            options.sameSite = \"lax\"\n            break\n          case \"strict\":\n            options.sameSite = \"strict\"\n            break\n          case \"none\":\n            options.sameSite = \"none\"\n            break\n        }\n        break\n      }\n    }\n  }\n\n  return Option.some(Object.assign(Object.create(CookieProto), {\n    name,\n    value,\n    valueEncoded,\n    options: Object.keys(options).length > 0 ? options : undefined\n  }))\n}\n\n/**\n * An empty Cookies object\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: Cookies = fromIterable([])\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isEmpty = (self: Cookies): boolean => Record.isEmptyRecord(self.cookies)\n\n// eslint-disable-next-line no-control-regex\nconst fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/\n\nconst CookieProto = {\n  [CookieTypeId]: CookieTypeId,\n  ...Inspectable.BaseProto,\n  toJSON(this: Cookie) {\n    return {\n      _id: \"@effect/platform/Cookies/Cookie\",\n      name: this.name,\n      value: this.value,\n      options: this.options\n    }\n  }\n}\n\n/**\n * Create a new cookie\n *\n * @since 1.0.0\n * @category constructors\n */\nexport function makeCookie(\n  name: string,\n  value: string,\n  options?: Cookie[\"options\"] | undefined\n): Either.Either<Cookie, CookiesError> {\n  if (!fieldContentRegExp.test(name)) {\n    return Either.left(new CookiesError({ reason: \"InvalidName\" }))\n  }\n  const encodedValue = encodeURIComponent(value)\n  if (encodedValue && !fieldContentRegExp.test(encodedValue)) {\n    return Either.left(new CookiesError({ reason: \"InvalidValue\" }))\n  }\n\n  if (options !== undefined) {\n    if (options.domain !== undefined && !fieldContentRegExp.test(options.domain)) {\n      return Either.left(new CookiesError({ reason: \"InvalidDomain\" }))\n    }\n\n    if (options.path !== undefined && !fieldContentRegExp.test(options.path)) {\n      return Either.left(new CookiesError({ reason: \"InvalidPath\" }))\n    }\n\n    if (options.maxAge !== undefined && !Duration.isFinite(Duration.decode(options.maxAge))) {\n      return Either.left(new CookiesError({ reason: \"InfinityMaxAge\" }))\n    }\n  }\n\n  return Either.right(Object.assign(Object.create(CookieProto), {\n    name,\n    value,\n    valueEncoded: encodedValue,\n    options\n  }))\n}\n\n/**\n * Create a new cookie, throwing an error if invalid\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const unsafeMakeCookie = (\n  name: string,\n  value: string,\n  options?: Cookie[\"options\"] | undefined\n): Cookie => Either.getOrThrowWith(makeCookie(name, value, options), identity)\n\n/**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const setCookie: {\n  (cookie: Cookie): (self: Cookies) => Cookies\n  (\n    self: Cookies,\n    cookie: Cookie\n  ): Cookies\n} = dual(\n  2,\n  (self: Cookies, cookie: Cookie) =>\n    fromReadonlyRecord(Record.set(\n      self.cookies,\n      cookie.name,\n      cookie\n    ))\n)\n\n/**\n * Add multiple cookies to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const setAllCookie: {\n  (cookies: Iterable<Cookie>): (self: Cookies) => Cookies\n  (\n    self: Cookies,\n    cookies: Iterable<Cookie>\n  ): Cookies\n} = dual(2, (self: Cookies, cookies: Iterable<Cookie>) => {\n  const record = { ...self.cookies }\n  for (const cookie of cookies) {\n    record[cookie.name] = cookie\n  }\n  return fromReadonlyRecord(record)\n})\n\n/**\n * Combine two Cookies objects, removing duplicates from the first\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const merge: {\n  (that: Cookies): (self: Cookies) => Cookies\n  (\n    self: Cookies,\n    that: Cookies\n  ): Cookies\n} = dual(2, (self: Cookies, that: Cookies) =>\n  fromReadonlyRecord({\n    ...self.cookies,\n    ...that.cookies\n  }))\n\n/**\n * Remove a cookie by name\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const remove: {\n  (name: string): (self: Cookies) => Cookies\n  (\n    self: Cookies,\n    name: string\n  ): Cookies\n} = dual(2, (self: Cookies, name: string) => fromReadonlyRecord(Record.remove(self.cookies, name)))\n\n/**\n * Get a cookie from a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const get: {\n  (name: string): (self: Cookies) => Option.Option<Cookie>\n  (self: Cookies, name: string): Option.Option<Cookie>\n} = dual(\n  (args) => isCookies(args[0]),\n  (self: Cookies, name: string): Option.Option<Cookie> => Record.get(self.cookies, name)\n)\n\n/**\n * Get a cookie from a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const getValue: {\n  (name: string): (self: Cookies) => Option.Option<string>\n  (self: Cookies, name: string): Option.Option<string>\n} = dual(\n  (args) => isCookies(args[0]),\n  (self: Cookies, name: string): Option.Option<string> =>\n    Option.map(Record.get(self.cookies, name), (cookie) => cookie.value)\n)\n\n/**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const set: {\n  (\n    name: string,\n    value: string,\n    options?: Cookie[\"options\"]\n  ): (self: Cookies) => Either.Either<Cookies, CookiesError>\n  (\n    self: Cookies,\n    name: string,\n    value: string,\n    options?: Cookie[\"options\"]\n  ): Either.Either<Cookies, CookiesError>\n} = dual(\n  (args) => isCookies(args[0]),\n  (self: Cookies, name: string, value: string, options?: Cookie[\"options\"]) =>\n    Either.map(\n      makeCookie(name, value, options),\n      (cookie) => fromReadonlyRecord(Record.set(self.cookies, name, cookie))\n    )\n)\n\n/**\n * Add a cookie to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const unsafeSet: {\n  (\n    name: string,\n    value: string,\n    options?: Cookie[\"options\"]\n  ): (self: Cookies) => Cookies\n  (\n    self: Cookies,\n    name: string,\n    value: string,\n    options?: Cookie[\"options\"]\n  ): Cookies\n} = dual(\n  (args) => isCookies(args[0]),\n  (self: Cookies, name: string, value: string, options?: Cookie[\"options\"]) =>\n    fromReadonlyRecord(Record.set(\n      self.cookies,\n      name,\n      unsafeMakeCookie(name, value, options)\n    ))\n)\n\n/**\n * Add multiple cookies to a Cookies object\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const setAll: {\n  (\n    cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n  ): (self: Cookies) => Either.Either<Cookies, CookiesError>\n  (\n    self: Cookies,\n    cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n  ): Either.Either<Cookies, CookiesError>\n} = dual(\n  2,\n  (\n    self: Cookies,\n    cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n  ): Either.Either<Cookies, CookiesError> => {\n    const record: Record<string, Cookie> = { ...self.cookies }\n    for (const [name, value, options] of cookies) {\n      const either = makeCookie(name, value, options)\n      if (Either.isLeft(either)) {\n        return either as Either.Left<CookiesError, never>\n      }\n      record[name] = either.right\n    }\n    return Either.right(fromReadonlyRecord(record))\n  }\n)\n\n/**\n * Add multiple cookies to a Cookies object, throwing an error if invalid\n *\n * @since 1.0.0\n * @category combinators\n */\nexport const unsafeSetAll: {\n  (\n    cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n  ): (self: Cookies) => Cookies\n  (\n    self: Cookies,\n    cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n  ): Cookies\n} = dual(\n  2,\n  (\n    self: Cookies,\n    cookies: Iterable<readonly [name: string, value: string, options?: Cookie[\"options\"]]>\n  ): Cookies => Either.getOrThrowWith(setAll(self, cookies), identity)\n)\n\n/**\n * Serialize a cookie into a string\n *\n * Adapted from https://github.com/fastify/fastify-cookie under MIT License\n *\n * @since 1.0.0\n * @category encoding\n */\nexport function serializeCookie(self: Cookie): string {\n  let str = self.name + \"=\" + self.valueEncoded\n\n  if (self.options === undefined) {\n    return str\n  }\n  const options = self.options\n\n  if (options.maxAge !== undefined) {\n    const maxAge = Duration.toSeconds(options.maxAge)\n    str += \"; Max-Age=\" + Math.trunc(maxAge)\n  }\n\n  if (options.domain !== undefined) {\n    str += \"; Domain=\" + options.domain\n  }\n\n  if (options.path !== undefined) {\n    str += \"; Path=\" + options.path\n  }\n\n  if (options.priority !== undefined) {\n    switch (options.priority) {\n      case \"low\":\n        str += \"; Priority=Low\"\n        break\n      case \"medium\":\n        str += \"; Priority=Medium\"\n        break\n      case \"high\":\n        str += \"; Priority=High\"\n        break\n    }\n  }\n\n  if (options.expires !== undefined) {\n    str += \"; Expires=\" + options.expires.toUTCString()\n  }\n\n  if (options.httpOnly) {\n    str += \"; HttpOnly\"\n  }\n\n  if (options.secure) {\n    str += \"; Secure\"\n  }\n\n  // Draft implementation to support Chrome from 2024-Q1 forward.\n  // See https://datatracker.ietf.org/doc/html/draft-cutler-httpbis-partitioned-cookies#section-2.1\n  if (options.partitioned) {\n    str += \"; Partitioned\"\n  }\n\n  if (options.sameSite !== undefined) {\n    switch (options.sameSite) {\n      case \"lax\":\n        str += \"; SameSite=Lax\"\n        break\n      case \"strict\":\n        str += \"; SameSite=Strict\"\n        break\n      case \"none\":\n        str += \"; SameSite=None\"\n        break\n    }\n  }\n\n  return str\n}\n\n/**\n * Serialize a Cookies object into a Cookie header\n *\n * @since 1.0.0\n * @category encoding\n */\nexport const toCookieHeader = (self: Cookies): string =>\n  Object.values(self.cookies).map((cookie) => `${cookie.name}=${cookie.valueEncoded}`).join(\"; \")\n\n/**\n * To record\n *\n * @since 1.0.0\n * @category encoding\n */\nexport const toRecord = (self: Cookies): Record<string, string> => {\n  const record: Record<string, string> = {}\n  const cookies = Object.values(self.cookies)\n  for (let index = 0; index < cookies.length; index++) {\n    const cookie = cookies[index]\n    record[cookie.name] = cookie.value\n  }\n  return record\n}\n\n/**\n * Serialize a Cookies object into Headers object containing one or more Set-Cookie headers\n *\n * @since 1.0.0\n * @category encoding\n */\nexport const toSetCookieHeaders = (self: Cookies): Array<string> => Object.values(self.cookies).map(serializeCookie)\n\n/**\n * Parse a cookie header into a record of key-value pairs\n *\n * Adapted from https://github.com/fastify/fastify-cookie under MIT License\n *\n * @since 1.0.0\n * @category decoding\n */\nexport function parseHeader(header: string): Record<string, string> {\n  const result: Record<string, string> = {}\n\n  const strLen = header.length\n  let pos = 0\n  let terminatorPos = 0\n\n  while (true) {\n    if (terminatorPos === strLen) break\n    terminatorPos = header.indexOf(\";\", pos)\n    if (terminatorPos === -1) terminatorPos = strLen // This is the last pair\n\n    let eqIdx = header.indexOf(\"=\", pos)\n    if (eqIdx === -1) break // No key-value pairs left\n    if (eqIdx > terminatorPos) {\n      // Malformed key-value pair\n      pos = terminatorPos + 1\n      continue\n    }\n\n    const key = header.substring(pos, eqIdx++).trim()\n    if (result[key] === undefined) {\n      const val = header.charCodeAt(eqIdx) === 0x22\n        ? header.substring(eqIdx + 1, terminatorPos - 1).trim()\n        : header.substring(eqIdx, terminatorPos).trim()\n\n      result[key] = !(val.indexOf(\"%\") === -1)\n        ? tryDecodeURIComponent(val)\n        : val\n    }\n\n    pos = terminatorPos + 1\n  }\n\n  return result\n}\n\nconst tryDecodeURIComponent = (str: string): string => {\n  try {\n    return decodeURIComponent(str)\n  } catch {\n    return str\n  }\n}\n"
  },
  {
    "path": "packages/platform/src/Error.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Cause from \"effect/Cause\"\nimport * as Data from \"effect/Data\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type { Simplify } from \"effect/Types\"\n\n/**\n * @since 1.0.0\n * @category type id\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/Error\")\n\n/**\n * @since 1.0.0\n * @category type id\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isPlatformError = (u: unknown): u is PlatformError => Predicate.hasProperty(u, TypeId)\n\n/**\n * @since 1.0.0\n * @category error\n */\nexport const TypeIdError = <const TypeId extends symbol, const Tag extends string>(\n  typeId: TypeId,\n  tag: Tag\n): new<A extends Record<string, any>>(\n  args: Simplify<A>\n) =>\n  & Cause.YieldableError\n  & Record<TypeId, TypeId>\n  & { readonly _tag: Tag }\n  & Readonly<A> =>\n{\n  class Base extends Data.Error<{}> {\n    readonly _tag = tag\n  }\n  ;(Base.prototype as any)[typeId] = typeId\n  ;(Base.prototype as any).name = tag\n  return Base as any\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport const Module = Schema.Literal(\n  \"Clipboard\",\n  \"Command\",\n  \"FileSystem\",\n  \"KeyValueStore\",\n  \"Path\",\n  \"Stream\",\n  \"Terminal\"\n)\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport class BadArgument extends Schema.TaggedError<BadArgument>(\"@effect/platform/Error/BadArgument\")(\"BadArgument\", {\n  module: Module,\n  method: Schema.String,\n  description: Schema.optional(Schema.String),\n  cause: Schema.optional(Schema.Defect)\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId]: typeof TypeId = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  get message(): string {\n    return `${this.module}.${this.method}${this.description ? `: ${this.description}` : \"\"}`\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Model\n */\nexport const SystemErrorReason = Schema.Literal(\n  \"AlreadyExists\",\n  \"BadResource\",\n  \"Busy\",\n  \"InvalidData\",\n  \"NotFound\",\n  \"PermissionDenied\",\n  \"TimedOut\",\n  \"UnexpectedEof\",\n  \"Unknown\",\n  \"WouldBlock\",\n  \"WriteZero\"\n)\n\n/**\n * @since 1.0.0\n * @category Model\n */\nexport type SystemErrorReason = typeof SystemErrorReason.Type\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport class SystemError extends Schema.TaggedError<SystemError>(\"@effect/platform/Error/SystemError\")(\"SystemError\", {\n  reason: SystemErrorReason,\n  module: Module,\n  method: Schema.String,\n  description: Schema.optional(Schema.String),\n  syscall: Schema.optional(Schema.String),\n  pathOrDescriptor: Schema.optional(Schema.Union(Schema.String, Schema.Number)),\n  cause: Schema.optional(Schema.Defect)\n}) {\n  /**\n   * @since 1.0.0\n   */\n  readonly [TypeId]: typeof TypeId = TypeId\n\n  /**\n   * @since 1.0.0\n   */\n  get message(): string {\n    return `${this.reason}: ${this.module}.${this.method}${\n      this.pathOrDescriptor !== undefined ? ` (${this.pathOrDescriptor})` : \"\"\n    }${this.description ? `: ${this.description}` : \"\"}`\n  }\n}\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport type PlatformError = BadArgument | SystemError\n\n/**\n * @since 1.0.0\n * @category Models\n */\nexport const PlatformError: Schema.Union<[\n  typeof BadArgument,\n  typeof SystemError\n]> = Schema.Union(BadArgument, SystemError)\n"
  },
  {
    "path": "packages/platform/src/Etag.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Context from \"effect/Context\"\nimport type * as Effect from \"effect/Effect\"\nimport type { Layer } from \"effect/Layer\"\nimport type * as FileSystem from \"./FileSystem.js\"\nimport type * as Body from \"./HttpBody.js\"\nimport * as internal from \"./internal/etag.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Etag = Weak | Strong\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Weak {\n  readonly _tag: \"Weak\"\n  readonly value: string\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Strong {\n  readonly _tag: \"Strong\"\n  readonly value: string\n}\n\n/**\n * @since 1.0.0\n * @category convertions\n */\nexport const toString: (self: Etag) => string = internal.toString\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const GeneratorTypeId: unique symbol = internal.GeneratorTypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type GeneratorTypeId = typeof GeneratorTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Generator {\n  readonly [GeneratorTypeId]: GeneratorTypeId\n  readonly fromFileInfo: (info: FileSystem.File.Info) => Effect.Effect<Etag>\n  readonly fromFileWeb: (file: Body.HttpBody.FileLike) => Effect.Effect<Etag>\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const Generator: Context.Tag<Generator, Generator> = internal.tag\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer<Generator> = internal.layer\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerWeak: Layer<Generator> = internal.layerWeak\n"
  },
  {
    "path": "packages/platform/src/FetchHttpClient.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport type * as Layer from \"effect/Layer\"\nimport type { HttpClient } from \"./HttpClient.js\"\nimport * as internal from \"./internal/fetchHttpClient.js\"\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport class Fetch extends Context.Tag(internal.fetchTagKey)<Fetch, typeof globalThis.fetch>() {}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport class RequestInit extends Context.Tag(internal.requestInitTagKey)<RequestInit, globalThis.RequestInit>() {}\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer: Layer.Layer<HttpClient> = internal.layer\n"
  },
  {
    "path": "packages/platform/src/FileSystem.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Brand from \"effect/Brand\"\nimport type { Tag } from \"effect/Context\"\nimport * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport type * as Effect from \"effect/Effect\"\nimport type { Layer } from \"effect/Layer\"\nimport type { Option } from \"effect/Option\"\nimport type { Scope } from \"effect/Scope\"\nimport type { Sink } from \"effect/Sink\"\nimport type { Stream } from \"effect/Stream\"\nimport type { PlatformError } from \"./Error.js\"\nimport * as internal from \"./internal/fileSystem.js\"\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport interface FileSystem {\n  /**\n   * Check if a file can be accessed.\n   * You can optionally specify the level of access to check for.\n   */\n  readonly access: (\n    path: string,\n    options?: AccessFileOptions\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Copy a file or directory from `fromPath` to `toPath`.\n   *\n   * Equivalent to `cp -r`.\n   */\n  readonly copy: (\n    fromPath: string,\n    toPath: string,\n    options?: CopyOptions\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Copy a file from `fromPath` to `toPath`.\n   */\n  readonly copyFile: (\n    fromPath: string,\n    toPath: string\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Change the permissions of a file.\n   */\n  readonly chmod: (\n    path: string,\n    mode: number\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Change the owner and group of a file.\n   */\n  readonly chown: (\n    path: string,\n    uid: number,\n    gid: number\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Check if a path exists.\n   */\n  readonly exists: (\n    path: string\n  ) => Effect.Effect<boolean, PlatformError>\n  /**\n   * Create a hard link from `fromPath` to `toPath`.\n   */\n  readonly link: (\n    fromPath: string,\n    toPath: string\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Create a directory at `path`. You can optionally specify the mode and\n   * whether to recursively create nested directories.\n   */\n  readonly makeDirectory: (\n    path: string,\n    options?: MakeDirectoryOptions\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Create a temporary directory.\n   *\n   * By default the directory will be created inside the system's default\n   * temporary directory, but you can specify a different location by setting\n   * the `directory` option.\n   *\n   * You can also specify a prefix for the directory name by setting the\n   * `prefix` option.\n   */\n  readonly makeTempDirectory: (\n    options?: MakeTempDirectoryOptions\n  ) => Effect.Effect<string, PlatformError>\n  /**\n   * Create a temporary directory inside a scope.\n   *\n   * Functionally equivalent to `makeTempDirectory`, but the directory will be\n   * automatically deleted when the scope is closed.\n   */\n  readonly makeTempDirectoryScoped: (\n    options?: MakeTempDirectoryOptions\n  ) => Effect.Effect<string, PlatformError, Scope>\n  /**\n   * Create a temporary file.\n   * The directory creation is functionally equivalent to `makeTempDirectory`.\n   * The file name will be a randomly generated string.\n   */\n  readonly makeTempFile: (\n    options?: MakeTempFileOptions\n  ) => Effect.Effect<string, PlatformError>\n  /**\n   * Create a temporary file inside a scope.\n   *\n   * Functionally equivalent to `makeTempFile`, but the file will be\n   * automatically deleted when the scope is closed.\n   */\n  readonly makeTempFileScoped: (\n    options?: MakeTempFileOptions\n  ) => Effect.Effect<string, PlatformError, Scope>\n  /**\n   * Open a file at `path` with the specified `options`.\n   *\n   * The file handle will be automatically closed when the scope is closed.\n   */\n  readonly open: (\n    path: string,\n    options?: OpenFileOptions\n  ) => Effect.Effect<File, PlatformError, Scope>\n  /**\n   * List the contents of a directory.\n   *\n   * You can recursively list the contents of nested directories by setting the\n   * `recursive` option.\n   */\n  readonly readDirectory: (\n    path: string,\n    options?: ReadDirectoryOptions\n  ) => Effect.Effect<Array<string>, PlatformError>\n  /**\n   * Read the contents of a file.\n   */\n  readonly readFile: (\n    path: string\n  ) => Effect.Effect<Uint8Array, PlatformError>\n  /**\n   * Read the contents of a file.\n   */\n  readonly readFileString: (\n    path: string,\n    encoding?: string\n  ) => Effect.Effect<string, PlatformError>\n  /**\n   * Read the destination of a symbolic link.\n   */\n  readonly readLink: (\n    path: string\n  ) => Effect.Effect<string, PlatformError>\n  /**\n   * Resolve a path to its canonicalized absolute pathname.\n   */\n  readonly realPath: (\n    path: string\n  ) => Effect.Effect<string, PlatformError>\n  /**\n   * Remove a file or directory.\n   */\n  readonly remove: (\n    path: string,\n    options?: RemoveOptions\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Rename a file or directory.\n   */\n  readonly rename: (\n    oldPath: string,\n    newPath: string\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Create a writable `Sink` for the specified `path`.\n   */\n  readonly sink: (\n    path: string,\n    options?: SinkOptions\n  ) => Sink<void, Uint8Array, never, PlatformError>\n  /**\n   * Get information about a file at `path`.\n   */\n  readonly stat: (\n    path: string\n  ) => Effect.Effect<File.Info, PlatformError>\n  /**\n   * Create a readable `Stream` for the specified `path`.\n   *\n   * Changing the `bufferSize` option will change the internal buffer size of\n   * the stream. It defaults to `4`.\n   *\n   * The `chunkSize` option will change the size of the chunks emitted by the\n   * stream. It defaults to 64kb.\n   *\n   * Changing `offset` and `bytesToRead` will change the offset and the number\n   * of bytes to read from the file.\n   */\n  readonly stream: (\n    path: string,\n    options?: StreamOptions\n  ) => Stream<Uint8Array, PlatformError>\n  /**\n   * Create a symbolic link from `fromPath` to `toPath`.\n   */\n  readonly symlink: (\n    fromPath: string,\n    toPath: string\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Truncate a file to a specified length. If the `length` is not specified,\n   * the file will be truncated to length `0`.\n   */\n  readonly truncate: (\n    path: string,\n    length?: SizeInput\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Change the file system timestamps of the file at `path`.\n   */\n  readonly utimes: (\n    path: string,\n    atime: Date | number,\n    mtime: Date | number\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Watch a directory or file for changes.\n   *\n   * By default, only changes to the direct children of the directory are reported.\n   * Set the `recursive` option to `true` to watch for changes in subdirectories as well.\n   *\n   * Note: The `recursive` option behavior depends on the backend implementation:\n   * - When using the default Node.js `fs.watch()` backend: The `recursive`\n   *   option is supported on all platforms (Node.js v20+).\n   * - When using `@parcel/watcher` (via `NodeFileSystem/ParcelWatcher` layer):\n   *   Watching is always recursive on all platforms. This option is ignored.\n   */\n  readonly watch: (path: string, options?: WatchOptions) => Stream<WatchEvent, PlatformError>\n  /**\n   * Write data to a file at `path`.\n   */\n  readonly writeFile: (\n    path: string,\n    data: Uint8Array,\n    options?: WriteFileOptions\n  ) => Effect.Effect<void, PlatformError>\n  /**\n   * Write a string to a file at `path`.\n   */\n  readonly writeFileString: (\n    path: string,\n    data: string,\n    options?: WriteFileStringOptions\n  ) => Effect.Effect<void, PlatformError>\n}\n\n/**\n * Represents a size in bytes.\n *\n * @since 1.0.0\n * @category sizes\n */\nexport type Size = Brand.Branded<bigint, \"Size\">\n\n/**\n * Represents a size in bytes.\n *\n * @since 1.0.0\n * @category sizes\n */\nexport type SizeInput = bigint | number | Size\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const Size: (bytes: SizeInput) => Size = internal.Size\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const KiB: (n: number) => Size = internal.KiB\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const MiB: (n: number) => Size = internal.MiB\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const GiB: (n: number) => Size = internal.GiB\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const TiB: (n: number) => Size = internal.TiB\n\n/**\n * @since 1.0.0\n * @category sizes\n */\nexport const PiB: (n: number) => Size = internal.PiB\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport type OpenFlag =\n  | \"r\"\n  | \"r+\"\n  | \"w\"\n  | \"wx\"\n  | \"w+\"\n  | \"wx+\"\n  | \"a\"\n  | \"ax\"\n  | \"a+\"\n  | \"ax+\"\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface AccessFileOptions {\n  readonly ok?: boolean\n  readonly readable?: boolean\n  readonly writable?: boolean\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface MakeDirectoryOptions {\n  readonly recursive?: boolean\n  readonly mode?: number\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface CopyOptions {\n  readonly overwrite?: boolean\n  readonly preserveTimestamps?: boolean\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface MakeTempDirectoryOptions {\n  readonly directory?: string\n  readonly prefix?: string\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface MakeTempFileOptions {\n  readonly directory?: string\n  readonly prefix?: string\n  readonly suffix?: string\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface OpenFileOptions {\n  readonly flag?: OpenFlag\n  readonly mode?: number\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface ReadDirectoryOptions {\n  readonly recursive?: boolean\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface RemoveOptions {\n  /**\n   * When `true`, you can recursively remove nested directories.\n   */\n  readonly recursive?: boolean\n  /**\n   * When `true`, exceptions will be ignored if `path` does not exist.\n   */\n  readonly force?: boolean\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface SinkOptions extends OpenFileOptions {}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface StreamOptions {\n  readonly bufferSize?: number\n  readonly bytesToRead?: SizeInput\n  readonly chunkSize?: SizeInput\n  readonly offset?: SizeInput\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface WriteFileOptions {\n  readonly flag?: OpenFlag\n  readonly mode?: number\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface WriteFileStringOptions {\n  readonly flag?: OpenFlag\n  readonly mode?: number\n}\n\n/**\n * @since 1.0.0\n * @category options\n */\nexport interface WatchOptions {\n  /**\n   * When `true`, the watcher will also watch for changes in subdirectories.\n   */\n  readonly recursive?: boolean\n}\n\n/**\n * @since 1.0.0\n * @category tag\n */\nexport const FileSystem: Tag<FileSystem, FileSystem> = internal.tag\n\n/**\n * @since 1.0.0\n * @category constructor\n */\nexport const make: (\n  impl: Omit<FileSystem, \"exists\" | \"readFileString\" | \"stream\" | \"sink\" | \"writeFileString\">\n) => FileSystem = internal.make\n\n/**\n * Create a no-op file system that can be used for testing.\n *\n * @since 1.0.0\n * @category constructor\n */\nexport const makeNoop: (fileSystem: Partial<FileSystem>) => FileSystem = internal.makeNoop\n\n/**\n * Create a no-op file system that can be used for testing.\n *\n * @since 1.0.0\n * @category layers\n */\nexport const layerNoop: (fileSystem: Partial<FileSystem>) => Layer<FileSystem> = internal.layerNoop\n\n/**\n * @since 1.0.0\n * @category type id\n */\nexport const FileTypeId: unique symbol = Symbol.for(\n  \"@effect/platform/FileSystem/File\"\n)\n\n/**\n * @since 1.0.0\n * @category type id\n */\nexport type FileTypeId = typeof FileTypeId\n\n/**\n * @since 1.0.0\n * @category guard\n */\nexport const isFile = (u: unknown): u is File => typeof u === \"object\" && u !== null && FileTypeId in u\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport interface File {\n  readonly [FileTypeId]: FileTypeId\n  readonly fd: File.Descriptor\n  readonly stat: Effect.Effect<File.Info, PlatformError>\n  readonly seek: (offset: SizeInput, from: SeekMode) => Effect.Effect<void>\n  readonly sync: Effect.Effect<void, PlatformError>\n  readonly read: (buffer: Uint8Array) => Effect.Effect<Size, PlatformError>\n  readonly readAlloc: (size: SizeInput) => Effect.Effect<Option<Uint8Array>, PlatformError>\n  readonly truncate: (length?: SizeInput) => Effect.Effect<void, PlatformError>\n  readonly write: (buffer: Uint8Array) => Effect.Effect<Size, PlatformError>\n  readonly writeAll: (buffer: Uint8Array) => Effect.Effect<void, PlatformError>\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace File {\n  /**\n   * @since 1.0.0\n   * @category model\n   */\n  export type Descriptor = Brand.Branded<number, \"FileDescriptor\">\n\n  /**\n   * @since 1.0.0\n   * @category model\n   */\n  export type Type =\n    | \"File\"\n    | \"Directory\"\n    | \"SymbolicLink\"\n    | \"BlockDevice\"\n    | \"CharacterDevice\"\n    | \"FIFO\"\n    | \"Socket\"\n    | \"Unknown\"\n\n  /**\n   * @since 1.0.0\n   * @category model\n   */\n  export interface Info {\n    readonly type: Type\n    readonly mtime: Option<Date>\n    readonly atime: Option<Date>\n    readonly birthtime: Option<Date>\n    readonly dev: number\n    readonly ino: Option<number>\n    readonly mode: number\n    readonly nlink: Option<number>\n    readonly uid: Option<number>\n    readonly gid: Option<number>\n    readonly rdev: Option<number>\n    readonly size: Size\n    readonly blksize: Option<Size>\n    readonly blocks: Option<number>\n  }\n}\n\n/**\n * @since 1.0.0\n * @category constructor\n */\nexport const FileDescriptor = Brand.nominal<File.Descriptor>()\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport type SeekMode = \"start\" | \"current\"\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport type WatchEvent = WatchEvent.Create | WatchEvent.Update | WatchEvent.Remove\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport declare namespace WatchEvent {\n  /**\n   * @since 1.0.0\n   * @category model\n   */\n  export interface Create {\n    readonly _tag: \"Create\"\n    readonly path: string\n  }\n\n  /**\n   * @since 1.0.0\n   * @category model\n   */\n  export interface Update {\n    readonly _tag: \"Update\"\n    readonly path: string\n  }\n\n  /**\n   * @since 1.0.0\n   * @category model\n   */\n  export interface Remove {\n    readonly _tag: \"Remove\"\n    readonly path: string\n  }\n}\n\n/**\n * @since 1.0.0\n * @category constructor\n */\nexport const WatchEventCreate: Data.Case.Constructor<WatchEvent.Create, \"_tag\"> = Data.tagged<WatchEvent.Create>(\n  \"Create\"\n)\n\n/**\n * @since 1.0.0\n * @category constructor\n */\nexport const WatchEventUpdate: Data.Case.Constructor<WatchEvent.Update, \"_tag\"> = Data.tagged<WatchEvent.Update>(\n  \"Update\"\n)\n\n/**\n * @since 1.0.0\n * @category constructor\n */\nexport const WatchEventRemove: Data.Case.Constructor<WatchEvent.Remove, \"_tag\"> = Data.tagged<WatchEvent.Remove>(\n  \"Remove\"\n)\n\n/**\n * @since 1.0.0\n * @category file watcher\n */\nexport class WatchBackend extends Context.Tag(\"@effect/platform/FileSystem/WatchBackend\")<\n  WatchBackend,\n  {\n    readonly register: (\n      path: string,\n      stat: File.Info,\n      options?: WatchOptions\n    ) => Option<Stream<WatchEvent, PlatformError>>\n  }\n>() {\n}\n"
  },
  {
    "path": "packages/platform/src/Headers.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as FiberRef from \"effect/FiberRef\"\nimport * as FiberRefs from \"effect/FiberRefs\"\nimport { dual, identity } from \"effect/Function\"\nimport { globalValue } from \"effect/GlobalValue\"\nimport { type Redactable, symbolRedactable } from \"effect/Inspectable\"\nimport type * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Record from \"effect/Record\"\nimport * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport * as String from \"effect/String\"\nimport type { Mutable } from \"effect/Types\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const HeadersTypeId: unique symbol = Symbol.for(\"@effect/platform/Headers\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type HeadersTypeId = typeof HeadersTypeId\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isHeaders = (u: unknown): u is Headers => Predicate.hasProperty(u, HeadersTypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Headers extends Redactable {\n  readonly [HeadersTypeId]: HeadersTypeId\n  readonly [key: string]: string\n}\n\nconst Proto = Object.assign(Object.create(null), {\n  [HeadersTypeId]: HeadersTypeId,\n  [symbolRedactable](\n    this: Headers,\n    fiberRefs: FiberRefs.FiberRefs\n  ): Record<string, string | Redacted.Redacted<string>> {\n    return redact(this, FiberRefs.getOrDefault(fiberRefs, currentRedactedNames))\n  }\n})\n\nconst make = (input: Record.ReadonlyRecord<string, string>): Mutable<Headers> =>\n  Object.assign(Object.create(Proto), input) as Headers\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const schemaFromSelf: Schema.Schema<Headers> = Schema.declare(isHeaders, {\n  typeConstructor: { _tag: \"effect/platform/Headers\" },\n  identifier: \"Headers\",\n  equivalence: () => Record.getEquivalence(String.Equivalence)\n})\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport const schema: Schema.Schema<Headers, Record.ReadonlyRecord<string, string>> = Schema\n  .transform(\n    Schema.Record({ key: Schema.String, value: Schema.String }),\n    schemaFromSelf,\n    { strict: true, decode: (record) => fromInput(record), encode: identity }\n  )\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Input =\n  | Record.ReadonlyRecord<string, string | ReadonlyArray<string> | undefined>\n  | Iterable<readonly [string, string]>\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: Headers = Object.create(Proto)\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fromInput: (input?: Input) => Headers = (input) => {\n  if (input === undefined) {\n    return empty\n  } else if (Symbol.iterator in input) {\n    const out: Record<string, string> = Object.create(Proto)\n    for (const [k, v] of input) {\n      out[k.toLowerCase()] = v\n    }\n    return out as Headers\n  }\n  const out: Record<string, string> = Object.create(Proto)\n  for (const [k, v] of Object.entries(input)) {\n    if (Array.isArray(v)) {\n      out[k.toLowerCase()] = v.join(\", \")\n    } else if (v !== undefined) {\n      out[k.toLowerCase()] = v as string\n    }\n  }\n  return out as Headers\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const unsafeFromRecord = (input: Record.ReadonlyRecord<string, string>): Headers =>\n  Object.setPrototypeOf(input, Proto) as Headers\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const has: {\n  (key: string): (self: Headers) => boolean\n  (self: Headers, key: string): boolean\n} = dual<\n  (key: string) => (self: Headers) => boolean,\n  (self: Headers, key: string) => boolean\n>(2, (self, key) => key.toLowerCase() in self)\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const get: {\n  (key: string): (self: Headers) => Option.Option<string>\n  (self: Headers, key: string): Option.Option<string>\n} = dual<\n  (key: string) => (self: Headers) => Option.Option<string>,\n  (self: Headers, key: string) => Option.Option<string>\n>(2, (self, key) => Record.get(self as Record<string, string>, key.toLowerCase()))\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const set: {\n  (key: string, value: string): (self: Headers) => Headers\n  (self: Headers, key: string, value: string): Headers\n} = dual<\n  (key: string, value: string) => (self: Headers) => Headers,\n  (self: Headers, key: string, value: string) => Headers\n>(3, (self, key, value) => {\n  const out = make(self)\n  out[key.toLowerCase()] = value\n  return out\n})\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setAll: {\n  (headers: Input): (self: Headers) => Headers\n  (self: Headers, headers: Input): Headers\n} = dual<\n  (headers: Input) => (self: Headers) => Headers,\n  (self: Headers, headers: Input) => Headers\n>(2, (self, headers) =>\n  make({\n    ...self,\n    ...fromInput(headers)\n  }))\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const merge: {\n  (headers: Headers): (self: Headers) => Headers\n  (self: Headers, headers: Headers): Headers\n} = dual<\n  (headers: Headers) => (self: Headers) => Headers,\n  (self: Headers, headers: Headers) => Headers\n>(2, (self, headers) => {\n  const out = make(self)\n  Object.assign(out, headers)\n  return out\n})\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const remove: {\n  (key: string | RegExp | ReadonlyArray<string | RegExp>): (self: Headers) => Headers\n  (self: Headers, key: string | RegExp | ReadonlyArray<string | RegExp>): Headers\n} = dual<\n  (key: string | RegExp | ReadonlyArray<string | RegExp>) => (self: Headers) => Headers,\n  (self: Headers, key: string | RegExp | ReadonlyArray<string | RegExp>) => Headers\n>(2, (self, key) => {\n  const out = make(self)\n  const modify = (key: string | RegExp) => {\n    if (typeof key === \"string\") {\n      const k = key.toLowerCase()\n      if (k in self) {\n        delete out[k]\n      }\n    } else {\n      for (const name in self) {\n        if (key.test(name)) {\n          delete out[name]\n        }\n      }\n    }\n  }\n  if (Array.isArray(key)) {\n    for (let i = 0; i < key.length; i++) {\n      modify(key[i])\n    }\n  } else {\n    modify(key as string | RegExp)\n  }\n  return out\n})\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const redact: {\n  (\n    key: string | RegExp | ReadonlyArray<string | RegExp>\n  ): (self: Headers) => Record<string, string | Redacted.Redacted>\n  (\n    self: Headers,\n    key: string | RegExp | ReadonlyArray<string | RegExp>\n  ): Record<string, string | Redacted.Redacted>\n} = dual(\n  2,\n  (\n    self: Headers,\n    key: string | RegExp | ReadonlyArray<string | RegExp>\n  ): Record<string, string | Redacted.Redacted> => {\n    const out: Record<string, string | Redacted.Redacted> = { ...self }\n    const modify = (key: string | RegExp) => {\n      if (typeof key === \"string\") {\n        const k = key.toLowerCase()\n        if (k in self) {\n          out[k] = Redacted.make(self[k])\n        }\n      } else {\n        for (const name in self) {\n          if (key.test(name)) {\n            out[name] = Redacted.make(self[name])\n          }\n        }\n      }\n    }\n    if (Array.isArray(key)) {\n      for (let i = 0; i < key.length; i++) {\n        modify(key[i])\n      }\n    } else {\n      modify(key as string | RegExp)\n    }\n    return out\n  }\n)\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const currentRedactedNames: FiberRef.FiberRef<ReadonlyArray<string | RegExp>> = globalValue(\n  \"@effect/platform/Headers/currentRedactedNames\",\n  () =>\n    FiberRef.unsafeMake<ReadonlyArray<string | RegExp>>([\n      \"authorization\",\n      \"cookie\",\n      \"set-cookie\",\n      \"x-api-key\"\n    ])\n)\n"
  },
  {
    "path": "packages/platform/src/HttpApi.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Option from \"effect/Option\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Record from \"effect/Record\"\nimport type * as Schema from \"effect/Schema\"\nimport * as AST from \"effect/SchemaAST\"\nimport type { Mutable } from \"effect/Types\"\nimport type * as HttpApiEndpoint from \"./HttpApiEndpoint.js\"\nimport { HttpApiDecodeError } from \"./HttpApiError.js\"\nimport type * as HttpApiGroup from \"./HttpApiGroup.js\"\nimport type * as HttpApiMiddleware from \"./HttpApiMiddleware.js\"\nimport * as HttpApiSchema from \"./HttpApiSchema.js\"\nimport type { HttpMethod } from \"./HttpMethod.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/HttpApi\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isHttpApi = (u: unknown): u is HttpApi.Any => Predicate.hasProperty(u, TypeId)\n\n/**\n * An `HttpApi` is a collection of `HttpApiEndpoint`s. You can use an `HttpApi` to\n * represent a portion of your domain.\n *\n * The endpoints can be implemented later using the `HttpApiBuilder.make` api.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface HttpApi<\n  out Id extends string,\n  out Groups extends HttpApiGroup.HttpApiGroup.Any = never,\n  in out E = never,\n  out R = never\n> extends Pipeable {\n  new(_: never): {}\n  readonly [TypeId]: TypeId\n  readonly identifier: Id\n  readonly groups: Record.ReadonlyRecord<string, Groups>\n  readonly annotations: Context.Context<never>\n  readonly errorSchema: Schema.Schema<E, unknown, R>\n  readonly middlewares: ReadonlySet<HttpApiMiddleware.TagClassAny>\n\n  /**\n   * Add a `HttpApiGroup` to the `HttpApi`.\n   */\n  add<A extends HttpApiGroup.HttpApiGroup.Any>(group: A): HttpApi<Id, Groups | A, E, R>\n  /**\n   * Add another `HttpApi` to the `HttpApi`.\n   */\n  addHttpApi<Id2 extends string, Groups2 extends HttpApiGroup.HttpApiGroup.Any, E2, R2>(\n    api: HttpApi<Id2, Groups2, E2, R2>\n  ): HttpApi<\n    Id,\n    Groups | HttpApiGroup.HttpApiGroup.AddContext<Groups2, R2>,\n    E | E2,\n    R\n  >\n  /**\n   * Add an global error to the `HttpApi`.\n   */\n  addError<A, I, RX>(\n    schema: Schema.Schema<A, I, RX>,\n    annotations?: {\n      readonly status?: number | undefined\n    }\n  ): HttpApi<Id, Groups, E | A, R | RX>\n  /**\n   * Prefix all endpoints in the `HttpApi`.\n   */\n  prefix(prefix: HttpApiEndpoint.PathSegment): HttpApi<Id, Groups, E, R>\n  /**\n   * Add a middleware to a `HttpApi`. It will be applied to all endpoints in the\n   * `HttpApi`.\n   */\n  middleware<I extends HttpApiMiddleware.HttpApiMiddleware.AnyId, S>(\n    middleware: Context.Tag<I, S>\n  ): HttpApi<\n    Id,\n    Groups,\n    E | HttpApiMiddleware.HttpApiMiddleware.Error<I>,\n    R | I | HttpApiMiddleware.HttpApiMiddleware.ErrorContext<I>\n  >\n  /**\n   * Annotate the `HttpApi`.\n   */\n  annotate<I, S>(tag: Context.Tag<I, S>, value: S): HttpApi<Id, Groups, E, R>\n  /**\n   * Annotate the `HttpApi` with a Context.\n   */\n  annotateContext<I>(context: Context.Context<I>): HttpApi<Id, Groups, E, R>\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport class Api extends Context.Tag(\"@effect/platform/HttpApi/Api\")<\n  Api,\n  {\n    readonly api: HttpApi<string, HttpApiGroup.HttpApiGroup.AnyWithProps>\n    readonly context: Context.Context<never>\n  }\n>() {}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace HttpApi {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Any {\n    readonly [TypeId]: TypeId\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type AnyWithProps = HttpApi<string, HttpApiGroup.HttpApiGroup.AnyWithProps, any, any>\n}\n\nconst Proto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  add(\n    this: HttpApi.AnyWithProps,\n    group: HttpApiGroup.HttpApiGroup.AnyWithProps\n  ) {\n    return makeProto({\n      identifier: this.identifier,\n      groups: Record.set(this.groups, group.identifier, group),\n      errorSchema: this.errorSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    })\n  },\n  addHttpApi(\n    this: HttpApi.AnyWithProps,\n    api: HttpApi.AnyWithProps\n  ) {\n    const newGroups = { ...this.groups }\n    for (const key in api.groups) {\n      const newGroup: Mutable<HttpApiGroup.HttpApiGroup.AnyWithProps> = api.groups[key].annotateContext(Context.empty())\n      newGroup.annotations = Context.merge(api.annotations, newGroup.annotations)\n      newGroup.middlewares = new Set([...api.middlewares, ...newGroup.middlewares])\n      newGroups[key] = newGroup as any\n    }\n    return makeProto({\n      identifier: this.identifier,\n      groups: newGroups,\n      errorSchema: HttpApiSchema.UnionUnify(this.errorSchema, api.errorSchema),\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    })\n  },\n  addError(\n    this: HttpApi.AnyWithProps,\n    schema: Schema.Schema.Any,\n    annotations?: { readonly status?: number }\n  ) {\n    return makeProto({\n      identifier: this.identifier,\n      groups: this.groups,\n      errorSchema: HttpApiSchema.UnionUnify(\n        this.errorSchema,\n        annotations?.status\n          ? schema.annotations(HttpApiSchema.annotations({ status: annotations.status }))\n          : schema\n      ),\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    })\n  },\n  prefix(this: HttpApi.AnyWithProps, prefix: HttpApiEndpoint.PathSegment) {\n    return makeProto({\n      identifier: this.identifier,\n      groups: Record.map(this.groups, (group) => group.prefix(prefix)),\n      errorSchema: this.errorSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    })\n  },\n  middleware(this: HttpApi.AnyWithProps, tag: HttpApiMiddleware.TagClassAny) {\n    return makeProto({\n      identifier: this.identifier,\n      groups: this.groups,\n      errorSchema: HttpApiSchema.UnionUnify(this.errorSchema, tag.failure),\n      annotations: this.annotations,\n      middlewares: new Set([...this.middlewares, tag])\n    })\n  },\n  annotate(this: HttpApi.AnyWithProps, tag: Context.Tag<any, any>, value: any) {\n    return makeProto({\n      identifier: this.identifier,\n      groups: this.groups,\n      errorSchema: this.errorSchema,\n      annotations: Context.add(this.annotations, tag, value),\n      middlewares: this.middlewares\n    })\n  },\n  annotateContext(this: HttpApi.AnyWithProps, context: Context.Context<any>) {\n    return makeProto({\n      identifier: this.identifier,\n      groups: this.groups,\n      errorSchema: this.errorSchema,\n      annotations: Context.merge(this.annotations, context),\n      middlewares: this.middlewares\n    })\n  }\n}\n\nconst makeProto = <Id extends string, Groups extends HttpApiGroup.HttpApiGroup.Any, E, I, R>(\n  options: {\n    readonly identifier: Id\n    readonly groups: Record.ReadonlyRecord<string, Groups>\n    readonly errorSchema: Schema.Schema<E, I, R>\n    readonly annotations: Context.Context<never>\n    readonly middlewares: ReadonlySet<HttpApiMiddleware.TagClassAny>\n  }\n): HttpApi<Id, Groups, E, R> => {\n  function HttpApi() {}\n  Object.setPrototypeOf(HttpApi, Proto)\n  HttpApi.groups = options.groups\n  HttpApi.errorSchema = options.errorSchema\n  HttpApi.annotations = options.annotations\n  HttpApi.middlewares = options.middlewares\n  return HttpApi as any\n}\n\n/**\n * An `HttpApi` is a collection of `HttpApiEndpoint`s. You can use an `HttpApi` to\n * represent a portion of your domain.\n *\n * The endpoints can be implemented later using the `HttpApiBuilder.make` api.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <const Id extends string>(identifier: Id): HttpApi<Id, never, HttpApiDecodeError> =>\n  makeProto({\n    identifier,\n    groups: new Map() as any,\n    errorSchema: HttpApiDecodeError,\n    annotations: Context.empty(),\n    middlewares: new Set()\n  })\n\n/**\n * Extract metadata from an `HttpApi`, which can be used to generate documentation\n * or other tooling.\n *\n * See the `OpenApi` & `HttpApiClient` modules for examples of how to use this function.\n *\n * @since 1.0.0\n * @category reflection\n */\nexport const reflect = <Id extends string, Groups extends HttpApiGroup.HttpApiGroup.Any, Error, R>(\n  self: HttpApi<Id, Groups, Error, R>,\n  options: {\n    readonly predicate?: Predicate.Predicate<{\n      readonly endpoint: HttpApiEndpoint.HttpApiEndpoint.AnyWithProps\n      readonly group: HttpApiGroup.HttpApiGroup.AnyWithProps\n    }>\n    readonly onGroup: (options: {\n      readonly group: HttpApiGroup.HttpApiGroup.AnyWithProps\n      readonly mergedAnnotations: Context.Context<never>\n    }) => void\n    readonly onEndpoint: (options: {\n      readonly group: HttpApiGroup.HttpApiGroup.AnyWithProps\n      readonly endpoint: HttpApiEndpoint.HttpApiEndpoint<string, HttpMethod>\n      readonly mergedAnnotations: Context.Context<never>\n      readonly middleware: ReadonlySet<HttpApiMiddleware.TagClassAny>\n      readonly payloads: ReadonlyMap<string, {\n        readonly encoding: HttpApiSchema.Encoding\n        readonly ast: AST.AST\n      }>\n      readonly successes: ReadonlyMap<number, {\n        readonly ast: Option.Option<AST.AST>\n        readonly description: Option.Option<string>\n      }>\n      readonly errors: ReadonlyMap<number, {\n        readonly ast: Option.Option<AST.AST>\n        readonly description: Option.Option<string>\n      }>\n    }) => void\n  }\n) => {\n  const apiErrors = extractMembers(self.errorSchema.ast, new Map(), HttpApiSchema.getStatusErrorAST)\n  const groups = Object.values(self.groups) as any as Array<HttpApiGroup.HttpApiGroup.AnyWithProps>\n  for (const group of groups) {\n    const groupErrors = extractMembers(group.errorSchema.ast, apiErrors, HttpApiSchema.getStatusErrorAST)\n    const groupAnnotations = Context.merge(self.annotations, group.annotations)\n    options.onGroup({\n      group,\n      mergedAnnotations: groupAnnotations\n    })\n    const endpoints = Object.values(group.endpoints) as Iterable<HttpApiEndpoint.HttpApiEndpoint<string, HttpMethod>>\n    for (const endpoint of endpoints) {\n      if (\n        options.predicate && !options.predicate({\n          endpoint,\n          group\n        } as any)\n      ) continue\n\n      const errors = extractMembers(endpoint.errorSchema.ast, groupErrors, HttpApiSchema.getStatusErrorAST)\n      options.onEndpoint({\n        group,\n        endpoint,\n        middleware: new Set([...group.middlewares, ...endpoint.middlewares]),\n        mergedAnnotations: Context.merge(groupAnnotations, endpoint.annotations),\n        payloads: endpoint.payloadSchema._tag === \"Some\" ? extractPayloads(endpoint.payloadSchema.value.ast) : emptyMap,\n        successes: extractMembers(endpoint.successSchema.ast, new Map(), HttpApiSchema.getStatusSuccessAST),\n        errors\n      })\n    }\n  }\n}\n\n// -------------------------------------------------------------------------------------\n\nconst emptyMap = new Map<never, never>()\n\nconst extractMembers = (\n  ast: AST.AST,\n  inherited: ReadonlyMap<number, {\n    readonly ast: Option.Option<AST.AST>\n    readonly description: Option.Option<string>\n  }>,\n  getStatus: (ast: AST.AST) => number\n): ReadonlyMap<number, {\n  readonly ast: Option.Option<AST.AST>\n  readonly description: Option.Option<string>\n}> => {\n  const members = new Map(inherited)\n  function process(type: AST.AST) {\n    if (AST.isNeverKeyword(type)) {\n      return\n    }\n    const annotations = HttpApiSchema.extractAnnotations(ast.annotations)\n    // Avoid changing the reference unless necessary\n    // Otherwise, deduplication of the ASTs below will not be possible\n    if (!Record.isEmptyRecord(annotations)) {\n      type = AST.annotations(type, {\n        ...annotations,\n        ...type.annotations\n      })\n    }\n    const status = getStatus(type)\n    const emptyDecodeable = HttpApiSchema.getEmptyDecodeable(type)\n    const current = members.get(status)\n    members.set(\n      status,\n      {\n        description: (current ? current.description : Option.none()).pipe(\n          Option.orElse(() => getDescriptionOrIdentifier(type))\n        ),\n        ast: (current ? current.ast : Option.none()).pipe(\n          // Deduplicate the ASTs\n          Option.map((current) => HttpApiSchema.UnionUnifyAST(current, type)),\n          Option.orElse(() =>\n            !emptyDecodeable && AST.isVoidKeyword(AST.encodedAST(type)) ? Option.none() : Option.some(type)\n          )\n        )\n      }\n    )\n  }\n\n  HttpApiSchema.extractUnionTypes(ast).forEach(process)\n  return members\n}\n\nconst extractPayloads = (topAst: AST.AST): ReadonlyMap<string, {\n  readonly encoding: HttpApiSchema.Encoding\n  readonly ast: AST.AST\n}> => {\n  const members = new Map<string, {\n    encoding: HttpApiSchema.Encoding\n    ast: AST.AST\n  }>()\n  function process(ast: AST.AST) {\n    if (ast._tag === \"NeverKeyword\") {\n      return\n    }\n    ast = AST.annotations(ast, {\n      ...HttpApiSchema.extractAnnotations(topAst.annotations),\n      ...ast.annotations\n    })\n    const encoding = HttpApiSchema.getEncoding(ast)\n    const contentType = HttpApiSchema.getMultipart(ast) || HttpApiSchema.getMultipartStream(ast)\n      ? \"multipart/form-data\"\n      : encoding.contentType\n    const current = members.get(contentType)\n    if (current === undefined) {\n      members.set(contentType, {\n        encoding,\n        ast\n      })\n    } else {\n      current.ast = AST.Union.make([current.ast, ast])\n    }\n  }\n  if (topAst._tag === \"Union\") {\n    for (const type of topAst.types) {\n      process(type)\n    }\n  } else {\n    process(topAst)\n  }\n  return members\n}\n\nconst getDescriptionOrIdentifier = (ast: AST.PropertySignature | AST.AST): Option.Option<string> => {\n  const annotations = \"to\" in ast ?\n    {\n      ...ast.to.annotations,\n      ...ast.annotations\n    } :\n    ast.annotations\n  return Option.fromNullable(annotations[AST.DescriptionAnnotationId] ?? annotations[AST.IdentifierAnnotationId] as any)\n}\n\n/**\n * Adds additional schemas to components/schemas.\n * The provided schemas must have a `identifier` annotation.\n *\n * @since 1.0.0\n * @category tags\n */\nexport class AdditionalSchemas extends Context.Tag(\"@effect/platform/HttpApi/AdditionalSchemas\")<\n  AdditionalSchemas,\n  ReadonlyArray<Schema.Schema.All>\n>() {}\n"
  },
  {
    "path": "packages/platform/src/HttpApiBuilder.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Cause from \"effect/Cause\"\nimport * as Chunk from \"effect/Chunk\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Fiber from \"effect/Fiber\"\nimport { constFalse, identity } from \"effect/Function\"\nimport { globalValue } from \"effect/GlobalValue\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport type * as Predicate from \"effect/Predicate\"\nimport type { ReadonlyRecord } from \"effect/Record\"\nimport * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport type * as AST from \"effect/SchemaAST\"\nimport type { Scope } from \"effect/Scope\"\nimport type { Covariant, NoInfer } from \"effect/Types\"\nimport { unify } from \"effect/Unify\"\nimport type { Cookie } from \"./Cookies.js\"\nimport type { FileSystem } from \"./FileSystem.js\"\nimport * as HttpApi from \"./HttpApi.js\"\nimport type * as HttpApiEndpoint from \"./HttpApiEndpoint.js\"\nimport { HttpApiDecodeError } from \"./HttpApiError.js\"\nimport type * as HttpApiGroup from \"./HttpApiGroup.js\"\nimport * as HttpApiMiddleware from \"./HttpApiMiddleware.js\"\nimport * as HttpApiSchema from \"./HttpApiSchema.js\"\nimport type * as HttpApiSecurity from \"./HttpApiSecurity.js\"\nimport * as HttpApp from \"./HttpApp.js\"\nimport * as HttpMethod from \"./HttpMethod.js\"\nimport * as HttpMiddleware from \"./HttpMiddleware.js\"\nimport * as HttpRouter from \"./HttpRouter.js\"\nimport * as HttpServer from \"./HttpServer.js\"\nimport * as HttpServerRequest from \"./HttpServerRequest.js\"\nimport * as HttpServerResponse from \"./HttpServerResponse.js\"\nimport * as Multipart from \"./Multipart.js\"\nimport * as OpenApi from \"./OpenApi.js\"\nimport type { Path } from \"./Path.js\"\nimport * as UrlParams from \"./UrlParams.js\"\n\n/**\n * The router that the API endpoints are attached to.\n *\n * @since 1.0.0\n * @category router\n */\nexport class Router extends HttpRouter.Tag(\"@effect/platform/HttpApiBuilder/Router\")<Router>() {}\n\n/**\n * Create a top-level `HttpApi` layer.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const api = <Id extends string, Groups extends HttpApiGroup.HttpApiGroup.Any, E, R>(\n  api: HttpApi.HttpApi<Id, Groups, E, R>\n): Layer.Layer<\n  HttpApi.Api,\n  never,\n  HttpApiGroup.HttpApiGroup.ToService<Id, Groups> | R | HttpApiGroup.HttpApiGroup.ErrorContext<Groups>\n> =>\n  Layer.effect(\n    HttpApi.Api,\n    Effect.map(Effect.context(), (context) => ({ api: api as any, context }))\n  )\n\n/**\n * Build an `HttpApp` from an `HttpApi` instance, and serve it using an\n * `HttpServer`.\n *\n * Optionally, you can provide a middleware function that will be applied to\n * the `HttpApp` before serving.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const serve = <R = never>(\n  middleware?: (httpApp: HttpApp.Default) => HttpApp.Default<never, R>\n): Layer.Layer<\n  never,\n  never,\n  | HttpServer.HttpServer\n  | HttpRouter.HttpRouter.DefaultServices\n  | Exclude<R, Scope | HttpServerRequest.HttpServerRequest>\n  | HttpApi.Api\n> =>\n  httpApp.pipe(\n    Effect.map((app) => HttpServer.serve(app as any, middleware!)),\n    Layer.unwrapEffect,\n    Layer.provide([Router.Live, Middleware.layer])\n  )\n\n/**\n * Construct an `HttpApp` from an `HttpApi` instance.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const httpApp: Effect.Effect<\n  HttpApp.Default<never, HttpRouter.HttpRouter.DefaultServices>,\n  never,\n  Router | HttpApi.Api | Middleware\n> = Effect.gen(function*() {\n  const { api, context } = yield* HttpApi.Api\n  const middleware = makeMiddlewareMap(api.middlewares, context)\n  const router = applyMiddleware(middleware, yield* HttpRouter.toHttpApp(yield* Router.router))\n  const apiMiddlewareService = yield* Middleware\n  const apiMiddleware = yield* apiMiddlewareService.retrieve\n  const errorSchema = makeErrorSchema(api as any)\n  const encodeError = Schema.encodeUnknown(errorSchema)\n  return router.pipe(\n    apiMiddleware,\n    Effect.catchAllCause((cause) =>\n      Effect.matchEffect(Effect.provide(encodeError(Cause.squash(cause)), context), {\n        onFailure: () => Effect.failCause(cause),\n        onSuccess: Effect.succeed\n      })\n    )\n  ) as any\n})\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const buildMiddleware: <Id extends string, Groups extends HttpApiGroup.HttpApiGroup.Any, E, R>(\n  api: HttpApi.HttpApi<Id, Groups, E, R>\n) => Effect.Effect<\n  (\n    effect: Effect.Effect<HttpServerResponse.HttpServerResponse, unknown>\n  ) => Effect.Effect<HttpServerResponse.HttpServerResponse, unknown, never>\n> = Effect.fnUntraced(\n  function*<Id extends string, Groups extends HttpApiGroup.HttpApiGroup.Any, E, R>(\n    api: HttpApi.HttpApi<Id, Groups, E, R>\n  ) {\n    const context = yield* Effect.context<never>()\n    const middlewareMap = makeMiddlewareMap(api.middlewares, context)\n    const errorSchema = makeErrorSchema(api as any)\n    const encodeError = Schema.encodeUnknown(errorSchema)\n    return (effect: Effect.Effect<HttpServerResponse.HttpServerResponse, unknown>) =>\n      Effect.catchAllCause(\n        applyMiddleware(middlewareMap, effect),\n        (cause) =>\n          Effect.matchEffect(Effect.provide(encodeError(Cause.squash(cause)), context), {\n            onFailure: () => Effect.failCause(cause),\n            onSuccess: Effect.succeed\n          })\n      )\n  }\n)\n\n/**\n * Construct an http web handler from an `HttpApi` instance.\n *\n * **Example**\n *\n * ```ts\n * import { HttpApi, HttpApiBuilder, HttpServer } from \"@effect/platform\"\n * import { Layer } from \"effect\"\n *\n * class MyApi extends HttpApi.make(\"api\") {}\n *\n * const MyApiLive = HttpApiBuilder.api(MyApi)\n *\n * const { dispose, handler } = HttpApiBuilder.toWebHandler(\n *   Layer.mergeAll(\n *     MyApiLive,\n *     // you could also use NodeHttpServer.layerContext, depending on your\n *     // server's platform\n *     HttpServer.layerContext\n *   )\n * )\n * ```\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const toWebHandler = <LA, LE>(\n  layer: Layer.Layer<LA | HttpApi.Api | HttpRouter.HttpRouter.DefaultServices, LE>,\n  options?: {\n    readonly middleware?: (\n      httpApp: HttpApp.Default\n    ) => HttpApp.Default<\n      never,\n      HttpApi.Api | Router | HttpRouter.HttpRouter.DefaultServices\n    >\n    readonly memoMap?: Layer.MemoMap\n  }\n): {\n  readonly handler: (request: Request, context?: Context.Context<never> | undefined) => Promise<Response>\n  readonly dispose: () => Promise<void>\n} => {\n  const layerMerged = Layer.mergeAll(layer, Router.Live, Middleware.layer)\n  return HttpApp.toWebHandlerLayerWith(layerMerged, {\n    memoMap: options?.memoMap,\n    middleware: options?.middleware as any,\n    toHandler: (r) => Effect.provide(httpApp, r)\n  })\n}\n\n/**\n * @since 1.0.0\n * @category handlers\n */\nexport const HandlersTypeId: unique symbol = Symbol.for(\"@effect/platform/HttpApiBuilder/Handlers\")\n\n/**\n * @since 1.0.0\n * @category handlers\n */\nexport type HandlersTypeId = typeof HandlersTypeId\n\n/**\n * Represents a handled `HttpApi`.\n *\n * @since 1.0.0\n * @category handlers\n */\nexport interface Handlers<\n  E,\n  Provides,\n  R,\n  Endpoints extends HttpApiEndpoint.HttpApiEndpoint.Any = never\n> extends Pipeable {\n  readonly [HandlersTypeId]: {\n    _Endpoints: Covariant<Endpoints>\n  }\n  readonly group: HttpApiGroup.HttpApiGroup.AnyWithProps\n  readonly handlers: Chunk.Chunk<Handlers.Item<E, R>>\n\n  /**\n   * Add the implementation for an `HttpApiEndpoint` to a `Handlers` group.\n   */\n  handle<Name extends HttpApiEndpoint.HttpApiEndpoint.Name<Endpoints>, R1>(\n    name: Name,\n    handler: HttpApiEndpoint.HttpApiEndpoint.HandlerWithName<Endpoints, Name, E, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): Handlers<\n    E,\n    Provides,\n    | R\n    | Exclude<\n      HttpApiEndpoint.HttpApiEndpoint.ExcludeProvided<\n        Endpoints,\n        Name,\n        R1 | HttpApiEndpoint.HttpApiEndpoint.ContextWithName<Endpoints, Name>\n      >,\n      Provides\n    >,\n    HttpApiEndpoint.HttpApiEndpoint.ExcludeName<Endpoints, Name>\n  >\n\n  /**\n   * Add the implementation for an `HttpApiEndpoint` to a `Handlers` group.\n   * This version of the api allows you to return the full response object.\n   */\n  handleRaw<Name extends HttpApiEndpoint.HttpApiEndpoint.Name<Endpoints>, R1>(\n    name: Name,\n    handler: HttpApiEndpoint.HttpApiEndpoint.HandlerRawWithName<Endpoints, Name, E, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): Handlers<\n    E,\n    Provides,\n    | R\n    | Exclude<\n      HttpApiEndpoint.HttpApiEndpoint.ExcludeProvided<\n        Endpoints,\n        Name,\n        R1 | HttpApiEndpoint.HttpApiEndpoint.ContextWithName<Endpoints, Name>\n      >,\n      Provides\n    >,\n    HttpApiEndpoint.HttpApiEndpoint.ExcludeName<Endpoints, Name>\n  >\n}\n\n/**\n * @since 1.0.0\n * @category handlers\n */\nexport declare namespace Handlers {\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export interface Any {\n    readonly [HandlersTypeId]: any\n  }\n\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export type Middleware<E, R, E1, R1> = (self: HttpRouter.Route.Middleware<E, R>) => HttpApp.Default<E1, R1>\n\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export type Item<E, R> = {\n    readonly endpoint: HttpApiEndpoint.HttpApiEndpoint.Any\n    readonly handler: HttpApiEndpoint.HttpApiEndpoint.Handler<any, E, R>\n    readonly withFullRequest: boolean\n    readonly uninterruptible: boolean\n  }\n\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export type FromGroup<\n    ApiError,\n    ApiR,\n    Group extends HttpApiGroup.HttpApiGroup.Any\n  > = Handlers<\n    | ApiError\n    | HttpApiGroup.HttpApiGroup.Error<Group>,\n    | HttpApiMiddleware.HttpApiMiddleware.ExtractProvides<ApiR>\n    | HttpApiGroup.HttpApiGroup.Provides<Group>,\n    never,\n    HttpApiGroup.HttpApiGroup.Endpoints<Group>\n  >\n\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export type ValidateReturn<A> = A extends (\n    | Handlers<\n      infer _E,\n      infer _Provides,\n      infer _R,\n      infer _Endpoints\n    >\n    | Effect.Effect<\n      Handlers<\n        infer _E,\n        infer _Provides,\n        infer _R,\n        infer _Endpoints\n      >,\n      infer _EX,\n      infer _RX\n    >\n  ) ? [_Endpoints] extends [never] ? A\n    : `Endpoint not handled: ${HttpApiEndpoint.HttpApiEndpoint.Name<_Endpoints>}` :\n    `Must return the implemented handlers`\n\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export type Error<A> = A extends Effect.Effect<\n    Handlers<\n      infer _E,\n      infer _Provides,\n      infer _R,\n      infer _Endpoints\n    >,\n    infer _EX,\n    infer _RX\n  > ? _EX :\n    never\n\n  /**\n   * @since 1.0.0\n   * @category handlers\n   */\n  export type Context<A> = A extends Handlers<\n    infer _E,\n    infer _Provides,\n    infer _R,\n    infer _Endpoints\n  > ? _R :\n    A extends Effect.Effect<\n      Handlers<\n        infer _E,\n        infer _Provides,\n        infer _R,\n        infer _Endpoints\n      >,\n      infer _EX,\n      infer _RX\n    > ? _R | _RX :\n    never\n}\n\nconst HandlersProto = {\n  [HandlersTypeId]: {\n    _Endpoints: identity\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  handle(\n    this: Handlers<any, any, any, HttpApiEndpoint.HttpApiEndpoint.Any>,\n    name: string,\n    handler: HttpApiEndpoint.HttpApiEndpoint.Handler<any, any, any>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ) {\n    const endpoint = this.group.endpoints[name]\n    return makeHandlers({\n      group: this.group,\n      handlers: Chunk.append(this.handlers, {\n        endpoint,\n        handler,\n        withFullRequest: false,\n        uninterruptible: options?.uninterruptible ?? false\n      }) as any\n    })\n  },\n  handleRaw(\n    this: Handlers<any, any, any, HttpApiEndpoint.HttpApiEndpoint.Any>,\n    name: string,\n    handler: HttpApiEndpoint.HttpApiEndpoint.Handler<any, any, any>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ) {\n    const endpoint = this.group.endpoints[name]\n    return makeHandlers({\n      group: this.group,\n      handlers: Chunk.append(this.handlers, {\n        endpoint,\n        handler,\n        withFullRequest: true,\n        uninterruptible: options?.uninterruptible ?? false\n      }) as any\n    })\n  }\n}\n\nconst makeHandlers = <E, Provides, R, Endpoints extends HttpApiEndpoint.HttpApiEndpoint.Any>(\n  options: {\n    readonly group: HttpApiGroup.HttpApiGroup.Any\n    readonly handlers: Chunk.Chunk<Handlers.Item<E, R>>\n  }\n): Handlers<E, Provides, R, Endpoints> => {\n  const self = Object.create(HandlersProto)\n  self.group = options.group\n  self.handlers = options.handlers\n  return self\n}\n\n/**\n * Create a `Layer` that will implement all the endpoints in an `HttpApi`.\n *\n * An unimplemented `Handlers` instance is passed to the `build` function, which\n * you can use to add handlers to the group.\n *\n * You can implement endpoints using the `handlers.handle` api.\n *\n * @since 1.0.0\n * @category handlers\n */\nexport const group = <\n  ApiId extends string,\n  Groups extends HttpApiGroup.HttpApiGroup.Any,\n  ApiError,\n  ApiR,\n  const Name extends HttpApiGroup.HttpApiGroup.Name<Groups>,\n  Return\n>(\n  api: HttpApi.HttpApi<ApiId, Groups, ApiError, ApiR>,\n  groupName: Name,\n  build: (\n    handlers: Handlers.FromGroup<ApiError, ApiR, HttpApiGroup.HttpApiGroup.WithName<Groups, Name>>\n  ) => Handlers.ValidateReturn<Return>\n): Layer.Layer<\n  HttpApiGroup.ApiGroup<ApiId, Name>,\n  Handlers.Error<Return>,\n  Exclude<\n    | Handlers.Context<Return>\n    | HttpApiGroup.HttpApiGroup.MiddlewareWithName<Groups, Name>,\n    Scope\n  >\n> =>\n  Router.use((router) =>\n    Effect.gen(function*() {\n      const context = yield* Effect.context<any>()\n      const group = api.groups[groupName]!\n      const result = build(makeHandlers({ group, handlers: Chunk.empty() }))\n      const handlers: Handlers<any, any, any> = Effect.isEffect(result)\n        ? (yield* result as Effect.Effect<any, any, any>)\n        : result\n      const groupMiddleware = makeMiddlewareMap((group as any).middlewares, context)\n      const routes: Array<HttpRouter.Route<any, any>> = []\n      for (const item of handlers.handlers) {\n        const middleware = makeMiddlewareMap((item as any).endpoint.middlewares, context, groupMiddleware)\n        routes.push(handlerToRoute(\n          item.endpoint,\n          middleware,\n          function(request) {\n            return Effect.mapInputContext(\n              item.handler(request),\n              (input) => Context.merge(context, input)\n            )\n          },\n          item.withFullRequest,\n          item.uninterruptible\n        ))\n      }\n      yield* router.concat(HttpRouter.fromIterable(routes))\n    })\n  ) as any\n\n/**\n * Create a `Handler` for a single endpoint.\n *\n * @since 1.0.0\n * @category handlers\n */\nexport const handler = <\n  ApiId extends string,\n  Groups extends HttpApiGroup.HttpApiGroup.Any,\n  ApiError,\n  ApiR,\n  const GroupName extends Groups[\"identifier\"],\n  const Name extends HttpApiGroup.HttpApiGroup.EndpointsWithName<Groups, GroupName>[\"name\"],\n  R\n>(\n  _api: HttpApi.HttpApi<ApiId, Groups, ApiError, ApiR>,\n  _groupName: GroupName,\n  _name: Name,\n  f: HttpApiEndpoint.HttpApiEndpoint.HandlerWithName<\n    HttpApiGroup.HttpApiGroup.EndpointsWithName<Groups, GroupName>,\n    Name,\n    | ApiError\n    | HttpApiGroup.HttpApiGroup.ErrorWithName<Groups, GroupName>,\n    R\n  >\n): HttpApiEndpoint.HttpApiEndpoint.HandlerWithName<\n  HttpApiGroup.HttpApiGroup.EndpointsWithName<Groups, GroupName>,\n  Name,\n  | ApiError\n  | HttpApiGroup.HttpApiGroup.ErrorWithName<Groups, GroupName>,\n  R\n> => f\n\n// internal\n\nconst requestPayload = (\n  request: HttpServerRequest.HttpServerRequest,\n  urlParams: ReadonlyRecord<string, string | Array<string>>,\n  multipartLimits: Option.Option<Multipart.withLimits.Options>\n): Effect.Effect<\n  unknown,\n  never,\n  | FileSystem\n  | Path\n  | Scope\n> => {\n  if (!HttpMethod.hasBody(request.method)) {\n    return Effect.succeed(urlParams)\n  }\n  const contentType = request.headers[\"content-type\"]\n    ? request.headers[\"content-type\"].toLowerCase().trim()\n    : \"application/json\"\n  if (contentType.includes(\"application/json\")) {\n    return Effect.orDie(request.json)\n  } else if (contentType.includes(\"multipart/form-data\")) {\n    return Effect.orDie(Option.match(multipartLimits, {\n      onNone: () => request.multipart,\n      onSome: (limits) => Multipart.withLimits(request.multipart, limits)\n    }))\n  } else if (contentType.includes(\"x-www-form-urlencoded\")) {\n    return Effect.map(Effect.orDie(request.urlParamsBody), UrlParams.toRecord)\n  } else if (contentType.startsWith(\"text/\")) {\n    return Effect.orDie(request.text)\n  }\n  return Effect.map(Effect.orDie(request.arrayBuffer), (buffer) => new Uint8Array(buffer))\n}\n\ntype MiddlewareMap = Map<string, {\n  readonly tag: HttpApiMiddleware.TagClassAny\n  readonly effect: Effect.Effect<any, any, any>\n}>\n\nconst makeMiddlewareMap = (\n  middleware: ReadonlySet<HttpApiMiddleware.TagClassAny>,\n  context: Context.Context<never>,\n  initial?: MiddlewareMap\n): MiddlewareMap => {\n  const map = new Map<string, {\n    readonly tag: HttpApiMiddleware.TagClassAny\n    readonly effect: Effect.Effect<any, any, any>\n  }>(initial)\n  middleware.forEach((tag) => {\n    map.set(tag.key, {\n      tag,\n      effect: Context.unsafeGet(context, tag as any)\n    })\n  })\n  return map\n}\n\nfunction isSingleStringType(ast: AST.AST, key?: PropertyKey): boolean {\n  switch (ast._tag) {\n    case \"StringKeyword\":\n    case \"Literal\":\n    case \"TemplateLiteral\":\n    case \"Enums\":\n      return true\n    case \"TypeLiteral\": {\n      if (key !== undefined) {\n        const ps = ast.propertySignatures.find((ps) => ps.name === key)\n        return ps !== undefined\n          ? isSingleStringType(ps.type, key)\n          : ast.indexSignatures.some((is) => Schema.is(Schema.make(is.parameter))(key) && isSingleStringType(is.type))\n      }\n      return false\n    }\n    case \"Union\":\n      return ast.types.some((type) => isSingleStringType(type, key))\n    case \"Suspend\":\n      return isSingleStringType(ast.f(), key)\n    case \"Refinement\":\n    case \"Transformation\":\n      return isSingleStringType(ast.from, key)\n  }\n  return false\n}\n\n/**\n * Normalizes the url parameters so that if a key is expected to be an array,\n * a single string value is wrapped in an array.\n *\n * @internal\n */\nexport function normalizeUrlParams(\n  params: ReadonlyRecord<string, string | Array<string>>,\n  ast: AST.AST\n): ReadonlyRecord<string, string | Array<string>> {\n  const out: Record<string, string | Array<string>> = {}\n  for (const key in params) {\n    const value = params[key]\n    out[key] = Array.isArray(value) || isSingleStringType(ast, key) ? value : [value]\n  }\n  return out\n}\n\nconst handlerToRoute = (\n  endpoint_: HttpApiEndpoint.HttpApiEndpoint.Any,\n  middleware: MiddlewareMap,\n  handler: HttpApiEndpoint.HttpApiEndpoint.Handler<any, any, any>,\n  isFullRequest: boolean,\n  uninterruptible: boolean\n): HttpRouter.Route<any, any> => {\n  const endpoint = endpoint_ as HttpApiEndpoint.HttpApiEndpoint.AnyWithProps\n  const isMultipartStream = endpoint.payloadSchema.pipe(\n    Option.map(({ ast }) => HttpApiSchema.getMultipartStream(ast) !== undefined),\n    Option.getOrElse(constFalse)\n  )\n  const multipartLimits = endpoint.payloadSchema.pipe(\n    Option.flatMapNullable(({ ast }) => HttpApiSchema.getMultipart(ast) || HttpApiSchema.getMultipartStream(ast))\n  )\n  const decodePath = Option.map(endpoint.pathSchema, Schema.decodeUnknown)\n  const decodePayload = isFullRequest || isMultipartStream\n    ? Option.none()\n    : Option.map(endpoint.payloadSchema, Schema.decodeUnknown)\n  const decodeHeaders = Option.map(endpoint.headersSchema, Schema.decodeUnknown)\n  const encodeSuccess = Schema.encode(makeSuccessSchema(endpoint.successSchema))\n  return HttpRouter.makeRoute(\n    endpoint.method,\n    endpoint.path,\n    applyMiddleware(\n      middleware,\n      Effect.gen(function*() {\n        const fiber = Option.getOrThrow(Fiber.getCurrentFiber())\n        const context = fiber.currentContext\n        const httpRequest = Context.unsafeGet(context, HttpServerRequest.HttpServerRequest)\n        const routeContext = Context.unsafeGet(context, HttpRouter.RouteContext)\n        const urlParams = Context.unsafeGet(context, HttpServerRequest.ParsedSearchParams)\n        const request: any = { request: httpRequest }\n        if (decodePath._tag === \"Some\") {\n          request.path = yield* decodePath.value(routeContext.params)\n        }\n        if (decodePayload._tag === \"Some\") {\n          request.payload = yield* Effect.flatMap(\n            requestPayload(httpRequest, urlParams, multipartLimits),\n            decodePayload.value\n          )\n        } else if (isMultipartStream) {\n          request.payload = Option.match(multipartLimits, {\n            onNone: () => httpRequest.multipartStream,\n            onSome: (limits) => Multipart.withLimitsStream(httpRequest.multipartStream, limits)\n          })\n        }\n        if (decodeHeaders._tag === \"Some\") {\n          request.headers = yield* decodeHeaders.value(httpRequest.headers)\n        }\n        if (endpoint.urlParamsSchema._tag === \"Some\") {\n          const schema = endpoint.urlParamsSchema.value\n          request.urlParams = yield* Schema.decodeUnknown(schema)(normalizeUrlParams(urlParams, schema.ast))\n        }\n        const response = yield* handler(request)\n        return HttpServerResponse.isServerResponse(response) ? response : yield* encodeSuccess(response)\n      }).pipe(\n        Effect.catchIf(ParseResult.isParseError, HttpApiDecodeError.refailParseError)\n      )\n    ),\n    { uninterruptible }\n  )\n}\n\nconst applyMiddleware = <A extends Effect.Effect<any, any, any>>(\n  middleware: MiddlewareMap,\n  handler: A\n) => {\n  for (const entry of middleware.values()) {\n    const effect = HttpApiMiddleware.SecurityTypeId in entry.tag ? makeSecurityMiddleware(entry as any) : entry.effect\n    if (entry.tag.optional) {\n      const previous = handler\n      handler = Effect.matchEffect(effect, {\n        onFailure: () => previous,\n        onSuccess: entry.tag.provides !== undefined\n          ? (value) => Effect.provideService(previous, entry.tag.provides as any, value)\n          : (_) => previous\n      }) as any\n    } else {\n      handler = entry.tag.provides !== undefined\n        ? Effect.provideServiceEffect(handler, entry.tag.provides as any, effect) as any\n        : Effect.zipRight(effect, handler) as any\n    }\n  }\n  return handler\n}\n\nconst securityMiddlewareCache = globalValue<WeakMap<any, Effect.Effect<any, any, any>>>(\n  \"securityMiddlewareCache\",\n  () => new WeakMap()\n)\n\nconst makeSecurityMiddleware = (\n  entry: {\n    readonly tag: HttpApiMiddleware.TagClassSecurityAny\n    readonly effect: Record<string, (_: any) => Effect.Effect<any, any>>\n  }\n): Effect.Effect<any, any, any> => {\n  if (securityMiddlewareCache.has(entry)) {\n    return securityMiddlewareCache.get(entry)!\n  }\n\n  let effect: Effect.Effect<any, any, any> | undefined\n  for (const [key, security] of Object.entries(entry.tag.security)) {\n    const decode = securityDecode(security)\n    const handler = entry.effect[key]\n    const middleware = Effect.flatMap(decode, handler)\n    effect = effect === undefined ? middleware : Effect.catchAll(effect, () => middleware)\n  }\n  if (effect === undefined) {\n    effect = Effect.void\n  }\n  securityMiddlewareCache.set(entry, effect)\n  return effect\n}\n\nconst responseSchema = Schema.declare(HttpServerResponse.isServerResponse)\n\nconst makeSuccessSchema = (\n  schema: Schema.Schema.Any\n): Schema.Schema<unknown, HttpServerResponse.HttpServerResponse> => {\n  const schemas = new Set<Schema.Schema.Any>()\n  HttpApiSchema.deunionize(schemas, schema)\n  return Schema.Union(...Array.from(schemas, toResponseSuccess)) as any\n}\n\nconst makeErrorSchema = (\n  api: HttpApi.HttpApi.AnyWithProps\n): Schema.Schema<unknown, HttpServerResponse.HttpServerResponse> => {\n  const schemas = new Set<Schema.Schema.Any>()\n  HttpApiSchema.deunionize(schemas, api.errorSchema)\n  for (const group of Object.values(api.groups)) {\n    for (const endpoint of Object.values(group.endpoints)) {\n      HttpApiSchema.deunionize(schemas, endpoint.errorSchema)\n    }\n    HttpApiSchema.deunionize(schemas, group.errorSchema)\n  }\n  return Schema.Union(...Array.from(schemas, toResponseError)) as any\n}\n\nconst decodeForbidden = <A>(_: A, __: AST.ParseOptions, ast: AST.Transformation) =>\n  ParseResult.fail(new ParseResult.Forbidden(ast, _, \"Encode only schema\"))\n\nconst toResponseSchema = (getStatus: (ast: AST.AST) => number) => {\n  const cache = new WeakMap<AST.AST, Schema.Schema.All>()\n  const schemaToResponse = (\n    data: any,\n    _: AST.ParseOptions,\n    ast: AST.Transformation\n  ): Effect.Effect<HttpServerResponse.HttpServerResponse, ParseResult.ParseIssue> => {\n    const isEmpty = HttpApiSchema.isVoid(ast.to)\n    const status = getStatus(ast.to)\n    if (isEmpty) {\n      return HttpServerResponse.empty({ status })\n    }\n    const encoding = HttpApiSchema.getEncoding(ast.to)\n    switch (encoding.kind) {\n      case \"Json\": {\n        return Effect.mapError(\n          HttpServerResponse.json(data, {\n            status,\n            contentType: encoding.contentType\n          }),\n          (error) => new ParseResult.Type(ast, error, \"Could not encode to JSON\")\n        )\n      }\n      case \"Text\": {\n        return ParseResult.succeed(HttpServerResponse.text(data as any, {\n          status,\n          contentType: encoding.contentType\n        }))\n      }\n      case \"Uint8Array\": {\n        return ParseResult.succeed(HttpServerResponse.uint8Array(data as any, {\n          status,\n          contentType: encoding.contentType\n        }))\n      }\n      case \"UrlParams\": {\n        return ParseResult.succeed(HttpServerResponse.urlParams(data as any, {\n          status,\n          contentType: encoding.contentType\n        }))\n      }\n    }\n  }\n  return <A, I, R>(schema: Schema.Schema<A, I, R>): Schema.Schema<A, HttpServerResponse.HttpServerResponse, R> => {\n    if (cache.has(schema.ast)) {\n      return cache.get(schema.ast)! as any\n    }\n    const transform = Schema.transformOrFail(responseSchema, schema, {\n      decode: decodeForbidden,\n      encode: schemaToResponse\n    })\n    cache.set(transform.ast, transform)\n    return transform\n  }\n}\n\nconst toResponseSuccess = toResponseSchema(HttpApiSchema.getStatusSuccessAST)\nconst toResponseError = toResponseSchema(HttpApiSchema.getStatusErrorAST)\n\n// ----------------------------------------------------------------------------\n// Global middleware\n// ----------------------------------------------------------------------------\n\n/**\n * @since 1.0.0\n * @category middleware\n */\nexport class Middleware extends Context.Tag(\"@effect/platform/HttpApiBuilder/Middleware\")<\n  Middleware,\n  {\n    readonly add: (middleware: HttpMiddleware.HttpMiddleware) => Effect.Effect<void>\n    readonly retrieve: Effect.Effect<HttpMiddleware.HttpMiddleware>\n  }\n>() {\n  /**\n   * @since 1.0.0\n   */\n  static readonly layer = Layer.sync(Middleware, () => {\n    let middleware: HttpMiddleware.HttpMiddleware = identity\n    return Middleware.of({\n      add: (f) =>\n        Effect.sync(() => {\n          const prev = middleware\n          middleware = (app) => f(prev(app))\n        }),\n      retrieve: Effect.sync(() => middleware)\n    })\n  })\n}\n\n/**\n * @since 1.0.0\n * @category global\n */\nexport type MiddlewareFn<Error, R = HttpRouter.HttpRouter.Provided> = (\n  httpApp: HttpApp.Default\n) => HttpApp.Default<Error, R>\n\nconst middlewareAdd = (\n  middleware: HttpMiddleware.HttpMiddleware\n): Effect.Effect<void, never, Middleware> =>\n  Effect.gen(function*() {\n    const context = yield* Effect.context<never>()\n    const service = yield* Middleware\n    yield* service.add((httpApp) =>\n      Effect.mapInputContext(middleware(httpApp), (input) => Context.merge(context, input))\n    )\n  })\n\nconst middlewareAddNoContext = (\n  middleware: HttpMiddleware.HttpMiddleware\n): Effect.Effect<void, never, Middleware> =>\n  Effect.gen(function*() {\n    const service = yield* Middleware\n    yield* service.add(middleware)\n  })\n\n/**\n * Create an `HttpApi` level middleware `Layer`.\n *\n * @since 1.0.0\n * @category middleware\n */\nexport const middleware: {\n  <EX = never, RX = never>(\n    middleware: MiddlewareFn<never> | Effect.Effect<MiddlewareFn<never>, EX, RX>,\n    options?: {\n      readonly withContext?: false | undefined\n    }\n  ): Layer.Layer<never, EX, Exclude<RX, Scope>>\n  <R, EX = never, RX = never>(\n    middleware: MiddlewareFn<never, R> | Effect.Effect<MiddlewareFn<never, R>, EX, RX>,\n    options: {\n      readonly withContext: true\n    }\n  ): Layer.Layer<never, EX, Exclude<HttpRouter.HttpRouter.ExcludeProvided<R> | RX, Scope>>\n  <ApiId extends string, Groups extends HttpApiGroup.HttpApiGroup.Any, Error, ErrorR, EX = never, RX = never>(\n    api: HttpApi.HttpApi<ApiId, Groups, Error, ErrorR>,\n    middleware: MiddlewareFn<NoInfer<Error>> | Effect.Effect<MiddlewareFn<NoInfer<Error>>, EX, RX>,\n    options?: {\n      readonly withContext?: false | undefined\n    }\n  ): Layer.Layer<never, EX, Exclude<RX, Scope>>\n  <ApiId extends string, Groups extends HttpApiGroup.HttpApiGroup.Any, Error, ErrorR, R, EX = never, RX = never>(\n    api: HttpApi.HttpApi<ApiId, Groups, Error, ErrorR>,\n    middleware: MiddlewareFn<NoInfer<Error>, R> | Effect.Effect<MiddlewareFn<NoInfer<Error>, R>, EX, RX>,\n    options: {\n      readonly withContext: true\n    }\n  ): Layer.Layer<never, EX, Exclude<HttpRouter.HttpRouter.ExcludeProvided<R> | RX, Scope>>\n} = (\n  ...args: [\n    middleware: MiddlewareFn<any, any> | Effect.Effect<MiddlewareFn<any, any>, any, any>,\n    options?: {\n      readonly withContext?: boolean | undefined\n    } | undefined\n  ] | [\n    api: HttpApi.HttpApi.Any,\n    middleware: MiddlewareFn<any, any> | Effect.Effect<MiddlewareFn<any, any>, any, any>,\n    options?: {\n      readonly withContext?: boolean | undefined\n    } | undefined\n  ]\n): any => {\n  const apiFirst = HttpApi.isHttpApi(args[0])\n  const withContext = apiFirst ? args[2]?.withContext === true : (args as any)[1]?.withContext === true\n  const add = withContext ? middlewareAdd : middlewareAddNoContext\n  const middleware = apiFirst ? args[1] : args[0]\n  return (Effect.isEffect(middleware)\n    ? Layer.scopedDiscard(Effect.flatMap(middleware as any, add))\n    : Layer.scopedDiscard(add(middleware as any))).pipe(Layer.provide(Middleware.layer))\n}\n\n/**\n * A CORS middleware layer that can be provided to the `HttpApiBuilder.serve` layer.\n *\n * @since 1.0.0\n * @category middleware\n */\nexport const middlewareCors = (\n  options?: {\n    readonly allowedOrigins?: ReadonlyArray<string> | Predicate.Predicate<string> | undefined\n    readonly allowedMethods?: ReadonlyArray<string> | undefined\n    readonly allowedHeaders?: ReadonlyArray<string> | undefined\n    readonly exposedHeaders?: ReadonlyArray<string> | undefined\n    readonly maxAge?: number | undefined\n    readonly credentials?: boolean | undefined\n  } | undefined\n): Layer.Layer<never> => middleware(HttpMiddleware.cors(options))\n\n/**\n * A middleware that adds an openapi.json endpoint to the API.\n *\n * @since 1.0.0\n * @category middleware\n */\nexport const middlewareOpenApi = (\n  options?: {\n    readonly path?: HttpApiEndpoint.PathSegment | undefined\n    readonly additionalPropertiesStrategy?: OpenApi.AdditionalPropertiesStrategy | undefined\n  } | undefined\n): Layer.Layer<never, never, HttpApi.Api> =>\n  Router.use((router) =>\n    Effect.gen(function*() {\n      const { api } = yield* HttpApi.Api\n      const spec = OpenApi.fromApi(api, {\n        additionalPropertiesStrategy: options?.additionalPropertiesStrategy\n      })\n      const response = yield* HttpServerResponse.json(spec).pipe(\n        Effect.orDie\n      )\n      yield* router.get(options?.path ?? \"/openapi.json\", Effect.succeed(response))\n    })\n  )\n\nconst bearerLen = `Bearer `.length\nconst basicLen = `Basic `.length\n\n/**\n * @since 1.0.0\n * @category security\n */\nexport const securityDecode = <Security extends HttpApiSecurity.HttpApiSecurity>(\n  self: Security\n): Effect.Effect<\n  HttpApiSecurity.HttpApiSecurity.Type<Security>,\n  never,\n  HttpServerRequest.HttpServerRequest | HttpServerRequest.ParsedSearchParams\n> => {\n  switch (self._tag) {\n    case \"Bearer\": {\n      return Effect.map(\n        HttpServerRequest.HttpServerRequest,\n        (request) => Redacted.make((request.headers.authorization ?? \"\").slice(bearerLen)) as any\n      )\n    }\n    case \"ApiKey\": {\n      const key = self.in === \"header\" ? self.key.toLowerCase() : self.key\n      const schema = Schema.Struct({\n        [key]: Schema.String\n      })\n      const decode = unify(\n        self.in === \"query\"\n          ? HttpServerRequest.schemaSearchParams(schema)\n          : self.in === \"cookie\"\n          ? HttpServerRequest.schemaCookies(schema)\n          : HttpServerRequest.schemaHeaders(schema)\n      )\n      return Effect.match(decode, {\n        onFailure: () => Redacted.make(\"\") as any,\n        onSuccess: (match) => Redacted.make(match[key])\n      })\n    }\n    case \"Basic\": {\n      const empty: HttpApiSecurity.HttpApiSecurity.Type<Security> = {\n        username: \"\",\n        password: Redacted.make(\"\")\n      } as any\n      return HttpServerRequest.HttpServerRequest.pipe(\n        Effect.flatMap((request) => Encoding.decodeBase64String((request.headers.authorization ?? \"\").slice(basicLen))),\n        Effect.match({\n          onFailure: () => empty,\n          onSuccess: (header) => {\n            const parts = header.split(\":\")\n            if (parts.length !== 2) {\n              return empty\n            }\n            return {\n              username: parts[0],\n              password: Redacted.make(parts[1])\n            } as any\n          }\n        })\n      )\n    }\n  }\n}\n\n/**\n * Set a cookie from an `HttpApiSecurity.HttpApiKey` instance.\n *\n * You can use this api before returning a response from an endpoint handler.\n *\n * ```ts skip-type-checking\n * handlers.handle(\n *   \"authenticate\",\n *   (_) => HttpApiBuilder.securitySetCookie(security, \"secret123\")\n * )\n * ```\n *\n * @since 1.0.0\n * @category middleware\n */\nexport const securitySetCookie = (\n  self: HttpApiSecurity.ApiKey,\n  value: string | Redacted.Redacted,\n  options?: Cookie[\"options\"]\n): Effect.Effect<void> => {\n  const stringValue = typeof value === \"string\" ? value : Redacted.value(value)\n  return HttpApp.appendPreResponseHandler((_req, response) =>\n    Effect.orDie(\n      HttpServerResponse.setCookie(response, self.key, stringValue, {\n        secure: true,\n        httpOnly: true,\n        ...options\n      })\n    )\n  )\n}\n"
  },
  {
    "path": "packages/platform/src/HttpApiClient.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport { identity } from \"effect/Function\"\nimport { globalValue } from \"effect/GlobalValue\"\nimport * as Option from \"effect/Option\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport type * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as AST from \"effect/SchemaAST\"\nimport type { Simplify } from \"effect/Types\"\nimport * as HttpApi from \"./HttpApi.js\"\nimport type { HttpApiEndpoint } from \"./HttpApiEndpoint.js\"\nimport type { HttpApiGroup } from \"./HttpApiGroup.js\"\nimport type * as HttpApiMiddleware from \"./HttpApiMiddleware.js\"\nimport * as HttpApiSchema from \"./HttpApiSchema.js\"\nimport * as HttpBody from \"./HttpBody.js\"\nimport * as HttpClient from \"./HttpClient.js\"\nimport * as HttpClientError from \"./HttpClientError.js\"\nimport * as HttpClientRequest from \"./HttpClientRequest.js\"\nimport * as HttpClientResponse from \"./HttpClientResponse.js\"\nimport * as HttpMethod from \"./HttpMethod.js\"\nimport * as UrlParams from \"./UrlParams.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Client<Groups extends HttpApiGroup.Any, E, R> = Simplify<\n  & {\n    readonly [Group in Extract<Groups, { readonly topLevel: false }> as HttpApiGroup.Name<Group>]: Client.Group<\n      Group,\n      Group[\"identifier\"],\n      E,\n      R\n    >\n  }\n  & {\n    readonly [Method in Client.TopLevelMethods<Groups, E, R> as Method[0]]: Method[1]\n  }\n>\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace Client {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Group<Groups extends HttpApiGroup.Any, GroupName extends Groups[\"identifier\"], E, R> =\n    [HttpApiGroup.WithName<Groups, GroupName>] extends\n      [HttpApiGroup<infer _GroupName, infer _Endpoints, infer _GroupError, infer _GroupErrorR>] ? {\n        readonly [Endpoint in _Endpoints as HttpApiEndpoint.Name<Endpoint>]: Method<\n          Endpoint,\n          E,\n          _GroupError,\n          R\n        >\n      } :\n      never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Method<Endpoint, E, GroupError, R> = [Endpoint] extends [\n    HttpApiEndpoint<\n      infer _Name,\n      infer _Method,\n      infer _Path,\n      infer _UrlParams,\n      infer _Payload,\n      infer _Headers,\n      infer _Success,\n      infer _Error,\n      infer _R,\n      infer _RE\n    >\n  ] ? <WithResponse extends boolean = false>(\n      request: Simplify<HttpApiEndpoint.ClientRequest<_Path, _UrlParams, _Payload, _Headers, WithResponse>>\n    ) => Effect.Effect<\n      WithResponse extends true ? [_Success, HttpClientResponse.HttpClientResponse] : _Success,\n      _Error | GroupError | E | HttpClientError.HttpClientError | ParseResult.ParseError,\n      R\n    > :\n    never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type TopLevelMethods<Groups extends HttpApiGroup.Any, E, R> =\n    Extract<Groups, { readonly topLevel: true }> extends\n      HttpApiGroup<infer _Id, infer _Endpoints, infer _Error, infer _ErrorR, infer _TopLevel> ?\n      _Endpoints extends infer Endpoint ? [HttpApiEndpoint.Name<Endpoint>, Method<Endpoint, E, _Error, R>]\n      : never :\n      never\n}\n\n/**\n * @internal\n */\nconst makeClient = <ApiId extends string, Groups extends HttpApiGroup.Any, ApiError, ApiR, E, R>(\n  api: HttpApi.HttpApi<ApiId, Groups, ApiError, ApiR>,\n  options: {\n    readonly httpClient: HttpClient.HttpClient.With<E, R>\n    readonly predicate?: Predicate.Predicate<{\n      readonly endpoint: HttpApiEndpoint.AnyWithProps\n      readonly group: HttpApiGroup.AnyWithProps\n    }>\n    readonly onGroup?: (options: {\n      readonly group: HttpApiGroup.AnyWithProps\n      readonly mergedAnnotations: Context.Context<never>\n    }) => void\n    readonly onEndpoint: (options: {\n      readonly group: HttpApiGroup.AnyWithProps\n      readonly endpoint: HttpApiEndpoint<string, HttpMethod.HttpMethod>\n      readonly mergedAnnotations: Context.Context<never>\n      readonly middleware: ReadonlySet<HttpApiMiddleware.TagClassAny>\n      readonly successes: ReadonlyMap<number, {\n        readonly ast: Option.Option<AST.AST>\n        readonly description: Option.Option<string>\n      }>\n      readonly errors: ReadonlyMap<number, {\n        readonly ast: Option.Option<AST.AST>\n        readonly description: Option.Option<string>\n      }>\n      readonly endpointFn: Function\n    }) => void\n    readonly transformResponse?:\n      | ((effect: Effect.Effect<unknown, unknown>) => Effect.Effect<unknown, unknown>)\n      | undefined\n    readonly baseUrl?: URL | string | undefined\n  }\n): Effect.Effect<\n  void,\n  never,\n  HttpApiMiddleware.HttpApiMiddleware.Without<ApiR | HttpApiGroup.ClientContext<Groups>>\n> =>\n  Effect.gen(function*() {\n    const context = yield* Effect.context<any>()\n    const httpClient = options.httpClient.pipe(\n      options?.baseUrl === undefined\n        ? identity\n        : HttpClient.mapRequest(\n          HttpClientRequest.prependUrl(options.baseUrl.toString())\n        )\n    )\n    HttpApi.reflect(api as any, {\n      predicate: options?.predicate,\n      onGroup(onGroupOptions) {\n        options.onGroup?.(onGroupOptions)\n      },\n      onEndpoint(onEndpointOptions) {\n        const { endpoint, errors, successes } = onEndpointOptions\n        const makeUrl = compilePath(endpoint.path)\n        const decodeMap: Record<\n          number | \"orElse\",\n          (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<any, any>\n        > = { orElse: statusOrElse }\n        const decodeResponse = HttpClientResponse.matchStatus(decodeMap)\n        errors.forEach(({ ast }, status) => {\n          if (ast._tag === \"None\") {\n            decodeMap[status] = statusCodeError\n            return\n          }\n          const decode = schemaToResponse(ast.value)\n          decodeMap[status] = (response) => Effect.flatMap(decode(response), Effect.fail)\n        })\n        successes.forEach(({ ast }, status) => {\n          decodeMap[status] = ast._tag === \"None\" ? responseAsVoid : schemaToResponse(ast.value)\n        })\n        const encodePath = endpoint.pathSchema.pipe(\n          Option.map(Schema.encodeUnknown)\n        )\n        const encodePayloadBody = endpoint.payloadSchema.pipe(\n          Option.map((schema) => {\n            if (HttpMethod.hasBody(endpoint.method)) {\n              return Schema.encodeUnknown(payloadSchemaBody(schema as any))\n            }\n            return Schema.encodeUnknown(schema)\n          })\n        )\n        const encodeHeaders = endpoint.headersSchema.pipe(\n          Option.map(Schema.encodeUnknown)\n        )\n        const encodeUrlParams = endpoint.urlParamsSchema.pipe(\n          Option.map(Schema.encodeUnknown)\n        )\n        const endpointFn = Effect.fnUntraced(function*(request: {\n          readonly path: any\n          readonly urlParams: any\n          readonly payload: any\n          readonly headers: any\n          readonly withResponse?: boolean\n        }) {\n          let httpRequest = HttpClientRequest.make(endpoint.method)(endpoint.path)\n          if (request && request.path) {\n            const encodedPathParams = encodePath._tag === \"Some\"\n              ? yield* encodePath.value(request.path)\n              : request.path\n            httpRequest = HttpClientRequest.setUrl(httpRequest, makeUrl(encodedPathParams))\n          }\n          if (request && request.payload instanceof FormData) {\n            httpRequest = HttpClientRequest.bodyFormData(httpRequest, request.payload)\n          } else if (encodePayloadBody._tag === \"Some\") {\n            if (HttpMethod.hasBody(endpoint.method)) {\n              const body = (yield* encodePayloadBody.value(request.payload)) as HttpBody.HttpBody\n              httpRequest = HttpClientRequest.setBody(httpRequest, body)\n            } else {\n              const urlParams = (yield* encodePayloadBody.value(request.payload)) as Record<string, string>\n              httpRequest = HttpClientRequest.setUrlParams(httpRequest, urlParams)\n            }\n          }\n          if (encodeHeaders._tag === \"Some\") {\n            httpRequest = HttpClientRequest.setHeaders(\n              httpRequest,\n              (yield* encodeHeaders.value(request.headers)) as any\n            )\n          }\n          if (encodeUrlParams._tag === \"Some\") {\n            httpRequest = HttpClientRequest.appendUrlParams(\n              httpRequest,\n              (yield* encodeUrlParams.value(request.urlParams)) as any\n            )\n          }\n          const response = yield* httpClient.execute(httpRequest)\n          const value = yield* (options.transformResponse === undefined\n            ? decodeResponse(response)\n            : options.transformResponse(decodeResponse(response)))\n          return request?.withResponse === true ? [value, response] : value\n        }, Effect.mapInputContext((input) => Context.merge(context, input)))\n\n        options.onEndpoint({\n          ...onEndpointOptions,\n          endpointFn\n        })\n      }\n    })\n  })\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <ApiId extends string, Groups extends HttpApiGroup.Any, ApiError, ApiR>(\n  api: HttpApi.HttpApi<ApiId, Groups, ApiError, ApiR>,\n  options?: {\n    readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n    readonly transformResponse?:\n      | ((effect: Effect.Effect<unknown, unknown>) => Effect.Effect<unknown, unknown>)\n      | undefined\n    readonly baseUrl?: URL | string | undefined\n  }\n): Effect.Effect<\n  Simplify<Client<Groups, ApiError, never>>,\n  never,\n  HttpApiMiddleware.HttpApiMiddleware.Without<ApiR | HttpApiGroup.ClientContext<Groups>> | HttpClient.HttpClient\n> =>\n  Effect.flatMap(HttpClient.HttpClient, (httpClient) =>\n    makeWith(api, {\n      ...options,\n      httpClient: options?.transformClient ? options.transformClient(httpClient) : httpClient\n    }))\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeWith = <ApiId extends string, Groups extends HttpApiGroup.Any, ApiError, ApiR, E, R>(\n  api: HttpApi.HttpApi<ApiId, Groups, ApiError, ApiR>,\n  options: {\n    readonly httpClient: HttpClient.HttpClient.With<E, R>\n    readonly transformResponse?:\n      | ((effect: Effect.Effect<unknown, unknown>) => Effect.Effect<unknown, unknown>)\n      | undefined\n    readonly baseUrl?: URL | string | undefined\n  }\n): Effect.Effect<\n  Simplify<Client<Groups, ApiError | E, R>>,\n  never,\n  HttpApiMiddleware.HttpApiMiddleware.Without<ApiR | HttpApiGroup.ClientContext<Groups>>\n> => {\n  const client: Record<string, Record<string, any>> = {}\n  return makeClient(api, {\n    ...options,\n    onGroup({ group }) {\n      if (group.topLevel) return\n      client[group.identifier] = {}\n    },\n    onEndpoint({ endpoint, endpointFn, group }) {\n      ;(group.topLevel ? client : client[group.identifier])[endpoint.name] = endpointFn\n    }\n  }).pipe(Effect.map(() => client)) as any\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const group = <\n  ApiId extends string,\n  Groups extends HttpApiGroup.Any,\n  ApiError,\n  ApiR,\n  const GroupName extends HttpApiGroup.Name<Groups>,\n  E,\n  R\n>(\n  api: HttpApi.HttpApi<ApiId, Groups, ApiError, ApiR>,\n  options: {\n    readonly group: GroupName\n    readonly httpClient: HttpClient.HttpClient.With<E, R>\n    readonly transformResponse?:\n      | ((effect: Effect.Effect<unknown, unknown>) => Effect.Effect<unknown, unknown>)\n      | undefined\n    readonly baseUrl?: URL | string | undefined\n  }\n): Effect.Effect<\n  Client.Group<Groups, GroupName, ApiError | E, R>,\n  never,\n  HttpApiMiddleware.HttpApiMiddleware.Without<\n    | ApiR\n    | HttpApiGroup.ClientContext<\n      HttpApiGroup.WithName<Groups, GroupName>\n    >\n  >\n> => {\n  const client: Record<string, any> = {}\n  return makeClient(api, {\n    ...options,\n    predicate: ({ group }) => group.identifier === options.group,\n    onEndpoint({ endpoint, endpointFn }) {\n      client[endpoint.name] = endpointFn\n    }\n  }).pipe(Effect.map(() => client)) as any\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const endpoint = <\n  ApiId extends string,\n  Groups extends HttpApiGroup.Any,\n  ApiError,\n  ApiR,\n  const GroupName extends HttpApiGroup.Name<Groups>,\n  const EndpointName extends HttpApiEndpoint.Name<HttpApiGroup.EndpointsWithName<Groups, GroupName>>,\n  E,\n  R\n>(\n  api: HttpApi.HttpApi<ApiId, Groups, ApiError, ApiR>,\n  options: {\n    readonly group: GroupName\n    readonly endpoint: EndpointName\n    readonly httpClient: HttpClient.HttpClient.With<E, R>\n    readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined\n    readonly transformResponse?:\n      | ((effect: Effect.Effect<unknown, unknown>) => Effect.Effect<unknown, unknown>)\n      | undefined\n    readonly baseUrl?: URL | string | undefined\n  }\n): Effect.Effect<\n  Client.Method<\n    HttpApiEndpoint.WithName<HttpApiGroup.Endpoints<HttpApiGroup.WithName<Groups, GroupName>>, EndpointName>,\n    HttpApiGroup.Error<HttpApiGroup.WithName<Groups, GroupName>>,\n    ApiError | E,\n    R\n  >,\n  never,\n  HttpApiMiddleware.HttpApiMiddleware.Without<\n    | ApiR\n    | HttpApiGroup.Context<HttpApiGroup.WithName<Groups, GroupName>>\n    | HttpApiEndpoint.ContextWithName<HttpApiGroup.EndpointsWithName<Groups, GroupName>, EndpointName>\n    | HttpApiEndpoint.ErrorContextWithName<HttpApiGroup.EndpointsWithName<Groups, GroupName>, EndpointName>\n  >\n> => {\n  let client: any = undefined\n  return makeClient(api, {\n    ...options,\n    predicate: ({ endpoint, group }) => group.identifier === options.group && endpoint.name === options.endpoint,\n    onEndpoint({ endpointFn }) {\n      client = endpointFn\n    }\n  }).pipe(Effect.map(() => client)) as any\n}\n\n// ----------------------------------------------------------------------------\n\nconst paramsRegex = /:(\\w+)\\??/g\n\nconst compilePath = (path: string) => {\n  const segments = path.split(paramsRegex)\n  const len = segments.length\n  if (len === 1) {\n    return (_: any) => path\n  }\n  return (params: Record<string, string>) => {\n    let url = segments[0]\n    for (let i = 1; i < len; i++) {\n      if (i % 2 === 0) {\n        url += segments[i]\n      } else {\n        url += params[segments[i]]\n      }\n    }\n    return url\n  }\n}\n\nconst schemaToResponse = (\n  ast: AST.AST\n): (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<any, any> => {\n  const encoding = HttpApiSchema.getEncoding(ast)\n  const decode = Schema.decode(schemaFromArrayBuffer(ast, encoding))\n  return (response) => Effect.flatMap(response.arrayBuffer, decode)\n}\n\nconst Uint8ArrayFromArrayBuffer = Schema.transform(\n  Schema.Unknown as Schema.Schema<ArrayBuffer>,\n  Schema.Uint8ArrayFromSelf,\n  {\n    decode(fromA) {\n      return new Uint8Array(fromA)\n    },\n    encode(arr) {\n      return arr.byteLength === arr.buffer.byteLength ?\n        arr.buffer :\n        arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength)\n    }\n  }\n)\n\nconst StringFromArrayBuffer = Schema.transform(\n  Schema.Unknown as Schema.Schema<ArrayBuffer>,\n  Schema.String,\n  {\n    decode(fromA) {\n      return new TextDecoder().decode(fromA)\n    },\n    encode(toI) {\n      const arr = new TextEncoder().encode(toI)\n      return arr.byteLength === arr.buffer.byteLength ?\n        arr.buffer :\n        arr.buffer.slice(arr.byteOffset, arr.byteOffset + arr.byteLength)\n    }\n  }\n)\n\nconst parseJsonOrVoid = Schema.transformOrFail(\n  Schema.String,\n  Schema.Unknown,\n  {\n    strict: true,\n    decode: (i, _, ast) => {\n      if (i === \"\") return ParseResult.succeed(void 0)\n      return ParseResult.try({\n        try: () => JSON.parse(i),\n        catch: () => new ParseResult.Type(ast, i, \"Could not parse JSON\")\n      })\n    },\n    encode: (a, _, ast) => {\n      if (a === undefined) return ParseResult.succeed(\"\")\n      return ParseResult.try({\n        try: () => JSON.stringify(a),\n        catch: () => new ParseResult.Type(ast, a, \"Could not encode as JSON\")\n      })\n    }\n  }\n)\n\nconst parseJsonArrayBuffer = Schema.compose(StringFromArrayBuffer, parseJsonOrVoid)\n\nconst schemaFromArrayBuffer = (\n  ast: AST.AST,\n  encoding: HttpApiSchema.Encoding\n): Schema.Schema<any, ArrayBuffer> => {\n  if (ast._tag === \"Union\") {\n    return Schema.Union(...ast.types.map((ast) => schemaFromArrayBuffer(ast, HttpApiSchema.getEncoding(ast, encoding))))\n  }\n  const schema = Schema.make(ast)\n  switch (encoding.kind) {\n    case \"Json\": {\n      return Schema.compose(parseJsonArrayBuffer, schema)\n    }\n    case \"UrlParams\": {\n      return Schema.compose(StringFromArrayBuffer, UrlParams.schemaParse(schema as any)) as any\n    }\n    case \"Uint8Array\": {\n      return Schema.compose(Uint8ArrayFromArrayBuffer, schema)\n    }\n    case \"Text\": {\n      return Schema.compose(StringFromArrayBuffer, schema)\n    }\n  }\n}\n\nconst statusOrElse = (response: HttpClientResponse.HttpClientResponse) =>\n  Effect.fail(\n    new HttpClientError.ResponseError({\n      reason: \"Decode\",\n      request: response.request,\n      response\n    })\n  )\n\nconst statusCodeError = (response: HttpClientResponse.HttpClientResponse) =>\n  Effect.fail(\n    new HttpClientError.ResponseError({\n      reason: \"StatusCode\",\n      request: response.request,\n      response\n    })\n  )\n\nconst responseAsVoid = (_response: HttpClientResponse.HttpClientResponse) => Effect.void\n\nconst HttpBodyFromSelf = Schema.declare(HttpBody.isHttpBody)\n\nconst payloadSchemaBody = (schema: Schema.Schema.All): Schema.Schema<any, HttpBody.HttpBody> => {\n  const members = schema.ast._tag === \"Union\" ? schema.ast.types : [schema.ast]\n  return Schema.Union(...members.map(bodyFromPayload)) as any\n}\n\nconst bodyFromPayloadCache = globalValue(\n  \"@effect/platform/HttpApiClient/bodyFromPayloadCache\",\n  () => new WeakMap<AST.AST, Schema.Schema.Any>()\n)\n\nconst bodyFromPayload = (ast: AST.AST) => {\n  if (bodyFromPayloadCache.has(ast)) {\n    return bodyFromPayloadCache.get(ast)!\n  }\n  const schema = Schema.make(ast)\n  const encoding = HttpApiSchema.getEncoding(ast)\n  const transform = Schema.transformOrFail(\n    HttpBodyFromSelf,\n    schema,\n    {\n      decode(fromA, _, ast) {\n        return ParseResult.fail(new ParseResult.Forbidden(ast, fromA, \"encode only schema\"))\n      },\n      encode(toI, _, ast) {\n        switch (encoding.kind) {\n          case \"Json\": {\n            try {\n              return ParseResult.succeed(HttpBody.text(JSON.stringify(toI), encoding.contentType))\n            } catch {\n              return ParseResult.fail(new ParseResult.Type(ast, toI, \"Could not encode as JSON\"))\n            }\n          }\n          case \"Text\": {\n            if (typeof toI !== \"string\") {\n              return ParseResult.fail(new ParseResult.Type(ast, toI, \"Expected a string\"))\n            }\n            return ParseResult.succeed(HttpBody.text(toI, encoding.contentType))\n          }\n          case \"UrlParams\": {\n            return ParseResult.succeed(HttpBody.urlParams(UrlParams.fromInput(toI as any)))\n          }\n          case \"Uint8Array\": {\n            if (!(toI instanceof Uint8Array)) {\n              return ParseResult.fail(new ParseResult.Type(ast, toI, \"Expected a Uint8Array\"))\n            }\n            return ParseResult.succeed(HttpBody.uint8Array(toI, encoding.contentType))\n          }\n        }\n      }\n    }\n  )\n  bodyFromPayloadCache.set(ast, transform)\n  return transform\n}\n"
  },
  {
    "path": "packages/platform/src/HttpApiEndpoint.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type { Brand } from \"effect/Brand\"\nimport * as Context from \"effect/Context\"\nimport type { Effect } from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Stream from \"effect/Stream\"\nimport type * as Types from \"effect/Types\"\nimport type * as HttpApiMiddleware from \"./HttpApiMiddleware.js\"\nimport * as HttpApiSchema from \"./HttpApiSchema.js\"\nimport type { HttpMethod } from \"./HttpMethod.js\"\nimport * as HttpRouter from \"./HttpRouter.js\"\nimport type { HttpServerRequest } from \"./HttpServerRequest.js\"\nimport type { HttpServerResponse } from \"./HttpServerResponse.js\"\nimport type * as Multipart from \"./Multipart.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/HttpApiEndpoint\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isHttpApiEndpoint = (u: unknown): u is HttpApiEndpoint<any, any, any> => Predicate.hasProperty(u, TypeId)\n\n/**\n * Represents a path segment. A path segment is a string that represents a\n * segment of a URL path.\n *\n * @since 1.0.0\n * @category models\n */\nexport type PathSegment = `/${string}`\n\n/**\n * Represents an API endpoint. An API endpoint is mapped to a single route on\n * the underlying `HttpRouter`.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface HttpApiEndpoint<\n  out Name extends string,\n  out Method extends HttpMethod,\n  in out Path = never,\n  in out UrlParams = never,\n  in out Payload = never,\n  in out Headers = never,\n  in out Success = void,\n  in out Error = never,\n  out R = never,\n  out RE = never\n> extends Pipeable {\n  readonly [TypeId]: TypeId\n  readonly name: Name\n  readonly path: PathSegment\n  readonly method: Method\n  readonly pathSchema: Option.Option<Schema.Schema<Path, unknown, R>>\n  readonly urlParamsSchema: Option.Option<Schema.Schema<UrlParams, unknown, R>>\n  readonly payloadSchema: Option.Option<Schema.Schema<Payload, unknown, R>>\n  readonly headersSchema: Option.Option<Schema.Schema<Headers, unknown, R>>\n  readonly successSchema: Schema.Schema<Success, unknown, R>\n  readonly errorSchema: Schema.Schema<Error, unknown, RE>\n  readonly annotations: Context.Context<never>\n  readonly middlewares: ReadonlySet<HttpApiMiddleware.TagClassAny>\n\n  /**\n   * Add a schema for the success response of the endpoint. The status code\n   * will be inferred from the schema, otherwise it will default to 200.\n   */\n  addSuccess<S extends Schema.Schema.Any>(\n    schema: S,\n    annotations?: {\n      readonly status?: number | undefined\n    }\n  ): HttpApiEndpoint<\n    Name,\n    Method,\n    Path,\n    UrlParams,\n    Payload,\n    Headers,\n    Exclude<Success, void> | Schema.Schema.Type<S>,\n    Error,\n    R | Schema.Schema.Context<S>,\n    RE\n  >\n\n  /**\n   * Add an error response schema to the endpoint. The status code\n   * will be inferred from the schema, otherwise it will default to 500.\n   */\n  addError<E extends Schema.Schema.Any>(\n    schema: E,\n    annotations?: {\n      readonly status?: number | undefined\n    }\n  ): HttpApiEndpoint<\n    Name,\n    Method,\n    Path,\n    UrlParams,\n    Payload,\n    Headers,\n    Success,\n    Error | Schema.Schema.Type<E>,\n    R,\n    RE | Schema.Schema.Context<E>\n  >\n\n  /**\n   * Set the schema for the request body of the endpoint. The schema will be\n   * used to validate the request body before the handler is called.\n   *\n   * For endpoints with no request body, the payload will use the url search\n   * parameters.\n   *\n   * You can set a multipart schema to handle file uploads by using the\n   * `HttpApiSchema.Multipart` combinator.\n   */\n  setPayload<P extends Schema.Schema.Any>(\n    schema: P & HttpApiEndpoint.ValidatePayload<Method, P>\n  ): HttpApiEndpoint<\n    Name,\n    Method,\n    Path,\n    UrlParams,\n    Schema.Schema.Type<P>,\n    Headers,\n    Success,\n    Error,\n    R | Schema.Schema.Context<P>,\n    RE\n  >\n\n  /**\n   * Set the schema for the path parameters of the endpoint. The schema will be\n   * used to validate the path parameters before the handler is called.\n   */\n  setPath<Path extends Schema.Schema.Any>(\n    schema: Path & HttpApiEndpoint.ValidatePath<Path>\n  ): HttpApiEndpoint<\n    Name,\n    Method,\n    Schema.Schema.Type<Path>,\n    UrlParams,\n    Payload,\n    Headers,\n    Success,\n    Error,\n    R | Schema.Schema.Context<Path>,\n    RE\n  >\n\n  /**\n   * Set the schema for the url search parameters of the endpoint.\n   */\n  setUrlParams<UrlParams extends Schema.Schema.Any>(\n    schema: UrlParams & HttpApiEndpoint.ValidateUrlParams<UrlParams>\n  ): HttpApiEndpoint<\n    Name,\n    Method,\n    Path,\n    Schema.Schema.Type<UrlParams>,\n    Payload,\n    Headers,\n    Success,\n    Error,\n    R | Schema.Schema.Context<Path>,\n    RE\n  >\n\n  /**\n   * Set the schema for the headers of the endpoint. The schema will be\n   * used to validate the headers before the handler is called.\n   */\n  setHeaders<H extends Schema.Schema.Any>(\n    schema: H & HttpApiEndpoint.ValidateHeaders<H>\n  ): HttpApiEndpoint<\n    Name,\n    Method,\n    Path,\n    UrlParams,\n    Payload,\n    Schema.Schema.Type<H>,\n    Success,\n    Error,\n    R | Schema.Schema.Context<H>,\n    RE\n  >\n\n  /**\n   * Add a prefix to the path of the endpoint.\n   */\n  prefix(\n    prefix: PathSegment\n  ): HttpApiEndpoint<Name, Method, Path, UrlParams, Payload, Headers, Success, Error, R, RE>\n\n  /**\n   * Add an `HttpApiMiddleware` to the endpoint.\n   */\n  middleware<I extends HttpApiMiddleware.HttpApiMiddleware.AnyId, S>(middleware: Context.Tag<I, S>): HttpApiEndpoint<\n    Name,\n    Method,\n    Path,\n    UrlParams,\n    Payload,\n    Headers,\n    Success,\n    Error | HttpApiMiddleware.HttpApiMiddleware.Error<I>,\n    R | I,\n    RE | HttpApiMiddleware.HttpApiMiddleware.ErrorContext<I>\n  >\n\n  /**\n   * Add an annotation on the endpoint.\n   */\n  annotate<I, S>(\n    tag: Context.Tag<I, S>,\n    value: S\n  ): HttpApiEndpoint<Name, Method, Path, UrlParams, Payload, Headers, Success, Error, R, RE>\n\n  /**\n   * Merge the annotations of the endpoint with the provided context.\n   */\n  annotateContext<I>(\n    context: Context.Context<I>\n  ): HttpApiEndpoint<Name, Method, Path, UrlParams, Payload, Headers, Success, Error, R, RE>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace HttpApiEndpoint {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Any extends Pipeable {\n    readonly [TypeId]: TypeId\n    readonly name: string\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface AnyWithProps extends HttpApiEndpoint<string, HttpMethod, any, any, any, any, any, any, any> {}\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Name<Endpoint> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? _Name\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Success<Endpoint extends Any> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? _Success\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Error<Endpoint extends Any> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? _Error\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type PathParsed<Endpoint extends Any> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? _Path\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type UrlParams<Endpoint extends Any> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? _UrlParams\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Payload<Endpoint extends Any> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? _Payload\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Headers<Endpoint extends Any> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? _Headers\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Request<Endpoint extends Any> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ?\n      & ([_Path] extends [never] ? {} : { readonly path: _Path })\n      & ([_UrlParams] extends [never] ? {} : { readonly urlParams: _UrlParams })\n      & ([_Payload] extends [never] ? {}\n        : _Payload extends Brand<HttpApiSchema.MultipartStreamTypeId> ?\n          { readonly payload: Stream.Stream<Multipart.Part, Multipart.MultipartError> }\n        : { readonly payload: _Payload })\n      & ([_Headers] extends [never] ? {} : { readonly headers: _Headers })\n      & { readonly request: HttpServerRequest }\n    : {}\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type RequestRaw<Endpoint extends Any> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ?\n      & ([_Path] extends [never] ? {} : { readonly path: _Path })\n      & ([_UrlParams] extends [never] ? {} : { readonly urlParams: _UrlParams })\n      & ([_Headers] extends [never] ? {} : { readonly headers: _Headers })\n      & { readonly request: HttpServerRequest }\n    : {}\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ClientRequest<Path, UrlParams, Payload, Headers, WithResponse extends boolean> = (\n    & ([Path] extends [void] ? {} : { readonly path: Path })\n    & ([UrlParams] extends [never] ? {} : { readonly urlParams: UrlParams })\n    & ([Headers] extends [never] ? {} : { readonly headers: Headers })\n    & ([Payload] extends [never] ? {}\n      : Payload extends infer P ?\n        P extends Brand<HttpApiSchema.MultipartTypeId> | Brand<HttpApiSchema.MultipartStreamTypeId>\n          ? { readonly payload: FormData }\n        : { readonly payload: P }\n      : { readonly payload: Payload })\n  ) extends infer Req ? keyof Req extends never ? (void | { readonly withResponse?: WithResponse }) :\n    Req & { readonly withResponse?: WithResponse } :\n    void\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Context<Endpoint> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? _R\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ErrorContext<Endpoint> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? _RE\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Handler<Endpoint extends Any, E, R> = (\n    request: Types.Simplify<Request<Endpoint>>\n  ) => Effect<Success<Endpoint> | HttpServerResponse, Error<Endpoint> | E, R>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type HandlerRaw<Endpoint extends Any, E, R> = (\n    request: Types.Simplify<RequestRaw<Endpoint>>\n  ) => Effect<Success<Endpoint> | HttpServerResponse, Error<Endpoint> | E, R>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type WithName<Endpoints extends Any, Name extends string> = Extract<Endpoints, { readonly name: Name }>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ExcludeName<Endpoints extends Any, Name extends string> = Exclude<Endpoints, { readonly name: Name }>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type HandlerWithName<Endpoints extends Any, Name extends string, E, R> = Handler<\n    WithName<Endpoints, Name>,\n    E,\n    R\n  >\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type HandlerRawWithName<Endpoints extends Any, Name extends string, E, R> = HandlerRaw<\n    WithName<Endpoints, Name>,\n    E,\n    R\n  >\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type SuccessWithName<Endpoints extends Any, Name extends string> = Success<WithName<Endpoints, Name>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ErrorWithName<Endpoints extends Any, Name extends string> = Error<WithName<Endpoints, Name>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ContextWithName<Endpoints extends Any, Name extends string> = Context<WithName<Endpoints, Name>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ErrorContextWithName<Endpoints extends Any, Name extends string> = ErrorContext<WithName<Endpoints, Name>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ExcludeProvided<Endpoints extends Any, Name extends string, R> = Exclude<\n    R,\n    | HttpRouter.HttpRouter.DefaultServices\n    | HttpRouter.HttpRouter.Provided\n    | HttpApiMiddleware.HttpApiMiddleware.ExtractProvides<ContextWithName<Endpoints, Name>>\n  >\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ValidatePath<S extends Schema.Schema.Any> = S extends Schema.Schema<infer _A, infer _I, infer _R>\n    ? [_I] extends [Readonly<Record<string, string | undefined>>] ? {}\n    : `Path schema must be encodeable to strings`\n    : {}\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ValidateUrlParams<S extends Schema.Schema.Any> = S extends Schema.Schema<infer _A, infer _I, infer _R>\n    ? [_I] extends [Readonly<Record<string, string | ReadonlyArray<string> | undefined>>] ? {}\n    : `UrlParams schema must be encodeable to strings`\n    : {}\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ValidateHeaders<S extends Schema.Schema.Any> = S extends Schema.Schema<infer _A, infer _I, infer _R>\n    ? [_I] extends [Readonly<Record<string, string | undefined>>] ? {}\n    : `Headers schema must be encodeable to strings`\n    : {}\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ValidatePayload<Method extends HttpMethod, P extends Schema.Schema.Any> = Method extends\n    HttpMethod.NoBody ?\n    P extends Schema.Schema<infer _A, infer _I, infer _R>\n      ? [_I] extends [Readonly<Record<string, string | ReadonlyArray<string> | undefined>>] ? {}\n      : `'${Method}' payload must be encodeable to strings`\n    : {}\n    : {}\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ValidateParams<\n    Schemas extends ReadonlyArray<Schema.Schema.Any | Schema.PropertySignature.Any>,\n    Prev extends (Schema.Schema.Any | Schema.PropertySignature.Any) = never\n  > = Schemas extends [\n    infer Head extends (Schema.Schema.Any | Schema.PropertySignature.Any),\n    ...infer Tail extends ReadonlyArray<Schema.Schema.Any | Schema.PropertySignature.Any>\n  ] ? [\n      Head extends HttpApiSchema.Param<infer _Name, infer _S>\n        ? HttpApiSchema.Param<_Name, any> extends Prev ? `Duplicate param: ${_Name}`\n        : [Schema.Schema.Encoded<Head> & {}] extends [string] ? Head\n        : `Must be encodeable to string: ${_Name}` :\n        Head,\n      ...ValidateParams<Tail, Prev | Head>\n    ]\n    : Schemas\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type AddError<Endpoint extends Any, E, R> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? HttpApiEndpoint<\n      _Name,\n      _Method,\n      _Path,\n      _UrlParams,\n      _Payload,\n      _Headers,\n      _Success,\n      _Error | E,\n      _R,\n      _RE | R\n    > :\n    never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type AddContext<Endpoint extends Any, R> = Endpoint extends HttpApiEndpoint<\n    infer _Name,\n    infer _Method,\n    infer _Path,\n    infer _UrlParams,\n    infer _Payload,\n    infer _Headers,\n    infer _Success,\n    infer _Error,\n    infer _R,\n    infer _RE\n  > ? HttpApiEndpoint<\n      _Name,\n      _Method,\n      _Path,\n      _UrlParams,\n      _Payload,\n      _Headers,\n      _Success,\n      _Error | HttpApiMiddleware.HttpApiMiddleware.Error<R>,\n      _R | R,\n      _RE | HttpApiMiddleware.HttpApiMiddleware.ErrorContext<R>\n    > :\n    never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type PathEntries<Schemas extends ReadonlyArray<Schema.Schema.Any | Schema.PropertySignature.Any>> =\n    Extract<keyof Schemas, string> extends infer K ?\n      K extends keyof Schemas ? Schemas[K] extends HttpApiSchema.Param<infer _Name, infer _S> ? [_Name, _S] :\n        Schemas[K] extends (Schema.Schema.Any | Schema.PropertySignature.Any) ? [K, Schemas[K]]\n        : never\n      : never\n      : never\n\n  type OptionalTypePropertySignature =\n    | Schema.PropertySignature<\"?:\", any, PropertyKey, Schema.PropertySignature.Token, any, boolean, unknown>\n    | Schema.PropertySignature<\"?:\", any, PropertyKey, Schema.PropertySignature.Token, never, boolean, unknown>\n    | Schema.PropertySignature<\"?:\", never, PropertyKey, Schema.PropertySignature.Token, any, boolean, unknown>\n    | Schema.PropertySignature<\"?:\", never, PropertyKey, Schema.PropertySignature.Token, never, boolean, unknown>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ExtractPath<Schemas extends ReadonlyArray<Schema.Schema.Any | Schema.PropertySignature.Any>> =\n    Schema.Simplify<\n      & {\n        readonly [\n          Entry in Extract<PathEntries<Schemas>, [any, OptionalTypePropertySignature]> as Entry[0]\n        ]?: Schema.Schema.Type<Entry[1]>\n      }\n      & {\n        readonly [\n          Entry in Exclude<PathEntries<Schemas>, [any, OptionalTypePropertySignature]> as Entry[0]\n        ]: Schema.Schema.Type<Entry[1]>\n      }\n    >\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Constructor<Name extends string, Method extends HttpMethod> = <\n    const Schemas extends ReadonlyArray<Schema.Schema.Any | Schema.PropertySignature.Any>\n  >(\n    segments: TemplateStringsArray,\n    ...schemas: ValidateParams<Schemas>\n  ) => HttpApiEndpoint<\n    Name,\n    Method,\n    Schemas[\"length\"] extends 0 ? never : Types.Simplify<ExtractPath<Schemas>>,\n    never,\n    never,\n    never,\n    void,\n    never,\n    Schema.Schema.Context<Schemas[number]>\n  >\n}\n\nconst Proto = {\n  [TypeId]: TypeId,\n  pipe() {\n    return pipeArguments(this, arguments)\n  },\n  addSuccess(\n    this: HttpApiEndpoint.AnyWithProps,\n    schema: Schema.Schema.Any,\n    annotations?: { readonly status?: number }\n  ) {\n    schema = annotations?.status ?\n      schema.annotations(HttpApiSchema.annotations({ status: annotations.status })) :\n      schema\n    return makeProto({\n      ...this,\n      successSchema: this.successSchema === HttpApiSchema.NoContent ?\n        schema :\n        HttpApiSchema.UnionUnify(this.successSchema, schema)\n    })\n  },\n  addError(this: HttpApiEndpoint.AnyWithProps, schema: Schema.Schema.Any, annotations?: { readonly status?: number }) {\n    return makeProto({\n      ...this,\n      errorSchema: HttpApiSchema.UnionUnify(\n        this.errorSchema,\n        annotations?.status ? schema.annotations(HttpApiSchema.annotations({ status: annotations.status })) : schema\n      )\n    })\n  },\n  setPayload(this: HttpApiEndpoint.AnyWithProps, schema: Schema.Schema.Any) {\n    return makeProto({\n      ...this,\n      payloadSchema: Option.some(schema)\n    })\n  },\n  setPath(this: HttpApiEndpoint.AnyWithProps, schema: Schema.Schema.Any) {\n    return makeProto({\n      ...this,\n      pathSchema: Option.some(schema)\n    })\n  },\n  setUrlParams(this: HttpApiEndpoint.AnyWithProps, schema: Schema.Schema.Any) {\n    return makeProto({\n      ...this,\n      urlParamsSchema: Option.some(schema)\n    })\n  },\n  setHeaders(this: HttpApiEndpoint.AnyWithProps, schema: Schema.Schema.Any) {\n    return makeProto({\n      ...this,\n      headersSchema: Option.some(schema)\n    })\n  },\n  prefix(this: HttpApiEndpoint.AnyWithProps, prefix: PathSegment) {\n    return makeProto({\n      ...this,\n      path: HttpRouter.prefixPath(this.path, prefix) as PathSegment\n    })\n  },\n  middleware(this: HttpApiEndpoint.AnyWithProps, middleware: HttpApiMiddleware.TagClassAny) {\n    return makeProto({\n      ...this,\n      errorSchema: HttpApiSchema.UnionUnify(this.errorSchema, middleware.failure),\n      middlewares: new Set([...this.middlewares, middleware])\n    })\n  },\n  annotate(this: HttpApiEndpoint.AnyWithProps, tag: Context.Tag<any, any>, value: any) {\n    return makeProto({\n      ...this,\n      annotations: Context.add(this.annotations, tag, value)\n    })\n  },\n  annotateContext(this: HttpApiEndpoint.AnyWithProps, context: Context.Context<any>) {\n    return makeProto({\n      ...this,\n      annotations: Context.merge(this.annotations, context)\n    })\n  }\n}\n\nconst makeProto = <\n  Name extends string,\n  Method extends HttpMethod,\n  Path,\n  UrlParams,\n  Payload,\n  Headers,\n  Success,\n  Error,\n  R,\n  RE\n>(options: {\n  readonly name: Name\n  readonly path: PathSegment\n  readonly method: Method\n  readonly pathSchema: Option.Option<Schema.Schema<Path, unknown, R>>\n  readonly urlParamsSchema: Option.Option<Schema.Schema<UrlParams, unknown, R>>\n  readonly payloadSchema: Option.Option<Schema.Schema<Payload, unknown, R>>\n  readonly headersSchema: Option.Option<Schema.Schema<Headers, unknown, R>>\n  readonly successSchema: Schema.Schema<Success, unknown, R>\n  readonly errorSchema: Schema.Schema<Error, unknown, RE>\n  readonly annotations: Context.Context<never>\n  readonly middlewares: ReadonlySet<HttpApiMiddleware.TagClassAny>\n}): HttpApiEndpoint<Name, Method, Path, Payload, Headers, Success, Error, R, RE> =>\n  Object.assign(Object.create(Proto), options)\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <Method extends HttpMethod>(method: Method): {\n  <const Name extends string>(name: Name): HttpApiEndpoint.Constructor<Name, Method>\n  <const Name extends string>(name: Name, path: PathSegment): HttpApiEndpoint<Name, Method>\n} =>\n  ((name: string, ...args: [PathSegment]) => {\n    if (args.length === 1) {\n      return makeProto({\n        name,\n        path: args[0],\n        method,\n        pathSchema: Option.none(),\n        urlParamsSchema: Option.none(),\n        payloadSchema: Option.none(),\n        headersSchema: Option.none(),\n        successSchema: HttpApiSchema.NoContent as any,\n        errorSchema: Schema.Never as any,\n        annotations: Context.empty(),\n        middlewares: new Set()\n      })\n    }\n    return (\n      segments: TemplateStringsArray,\n      ...schemas: ReadonlyArray<Schema.Schema.Any | Schema.PropertySignature.Any>\n    ) => {\n      let path = segments[0].replace(\":\", \"::\") as PathSegment\n      let pathSchema = Option.none<Schema.Schema.Any>()\n      if (schemas.length > 0) {\n        const obj: Record<string, Schema.Schema.Any | Schema.PropertySignature.Any> = {}\n        for (let i = 0; i < schemas.length; i++) {\n          const schema = schemas[i]\n          const key = HttpApiSchema.getParam(schema.ast) ?? String(i)\n          const optional = schema.ast._tag === \"PropertySignatureTransformation\" && schema.ast.from.isOptional ||\n            schema.ast._tag === \"PropertySignatureDeclaration\" && schema.ast.isOptional\n          obj[key] = schema\n          path += `:${key}${optional ? \"?\" : \"\"}${segments[i + 1].replace(\":\", \"::\")}`\n        }\n        pathSchema = Option.some(Schema.Struct(obj))\n      }\n      return makeProto({\n        name,\n        path,\n        method,\n        pathSchema,\n        urlParamsSchema: Option.none(),\n        payloadSchema: Option.none(),\n        headersSchema: Option.none(),\n        successSchema: HttpApiSchema.NoContent as any,\n        errorSchema: Schema.Never as any,\n        annotations: Context.empty(),\n        middlewares: new Set()\n      })\n    }\n  }) as any\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const get: {\n  <const Name extends string>(name: Name): HttpApiEndpoint.Constructor<Name, \"GET\">\n  <const Name extends string>(\n    name: Name,\n    path: PathSegment\n  ): HttpApiEndpoint<Name, \"GET\">\n} = make(\"GET\")\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const post: {\n  <const Name extends string>(name: Name): HttpApiEndpoint.Constructor<Name, \"POST\">\n  <const Name extends string>(\n    name: Name,\n    path: PathSegment\n  ): HttpApiEndpoint<Name, \"POST\">\n} = make(\"POST\")\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const put: {\n  <const Name extends string>(name: Name): HttpApiEndpoint.Constructor<Name, \"PUT\">\n  <const Name extends string>(\n    name: Name,\n    path: PathSegment\n  ): HttpApiEndpoint<Name, \"PUT\">\n} = make(\"PUT\")\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const patch: {\n  <const Name extends string>(name: Name): HttpApiEndpoint.Constructor<Name, \"PATCH\">\n  <const Name extends string>(\n    name: Name,\n    path: PathSegment\n  ): HttpApiEndpoint<Name, \"PATCH\">\n} = make(\"PATCH\")\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const del: {\n  <const Name extends string>(name: Name): HttpApiEndpoint.Constructor<Name, \"DELETE\">\n  <const Name extends string>(\n    name: Name,\n    path: PathSegment\n  ): HttpApiEndpoint<Name, \"DELETE\">\n} = make(\"DELETE\")\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const head: {\n  <const Name extends string>(name: Name): HttpApiEndpoint.Constructor<Name, \"HEAD\">\n  <const Name extends string>(\n    name: Name,\n    path: PathSegment\n  ): HttpApiEndpoint<Name, \"HEAD\">\n} = make(\"HEAD\")\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const options: {\n  <const Name extends string>(name: Name): HttpApiEndpoint.Constructor<Name, \"OPTIONS\">\n  <const Name extends string>(\n    name: Name,\n    path: PathSegment\n  ): HttpApiEndpoint<Name, \"OPTIONS\">\n} = make(\"OPTIONS\")\n"
  },
  {
    "path": "packages/platform/src/HttpApiError.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Effect from \"effect/Effect\"\nimport * as ParseResult from \"effect/ParseResult\"\nimport * as Schema from \"effect/Schema\"\nimport * as HttpApiSchema from \"./HttpApiSchema.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/HttpApiError\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category schemas\n */\nexport class Issue extends Schema.ArrayFormatterIssue.annotations({\n  identifier: \"Issue\",\n  description: \"Represents an error encountered while parsing a value to match the schema\"\n}) {}\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport class HttpApiDecodeError extends Schema.TaggedError<HttpApiDecodeError>()(\n  \"HttpApiDecodeError\",\n  {\n    issues: Schema.Array(Issue),\n    message: Schema.String\n  },\n  HttpApiSchema.annotations({\n    status: 400,\n    description: \"The request did not match the expected schema\"\n  })\n) {\n  /**\n   * @since 1.0.0\n   */\n  static fromParseError(error: ParseResult.ParseError): Effect.Effect<HttpApiDecodeError> {\n    return ParseResult.ArrayFormatter.formatError(error).pipe(\n      Effect.zip(ParseResult.TreeFormatter.formatError(error)),\n      Effect.map(([issues, message]) => new HttpApiDecodeError({ issues, message }))\n    )\n  }\n  /**\n   * @since 1.0.0\n   */\n  static refailParseError(error: ParseResult.ParseError): Effect.Effect<never, HttpApiDecodeError> {\n    return Effect.flatMap(HttpApiDecodeError.fromParseError(error), Effect.fail)\n  }\n}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class BadRequest extends HttpApiSchema.EmptyError<BadRequest>()({\n  tag: \"BadRequest\",\n  status: 400\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class Unauthorized extends HttpApiSchema.EmptyError<Unauthorized>()({\n  tag: \"Unauthorized\",\n  status: 401\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class Forbidden extends HttpApiSchema.EmptyError<Forbidden>()({\n  tag: \"Forbidden\",\n  status: 403\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class NotFound extends HttpApiSchema.EmptyError<NotFound>()({\n  tag: \"NotFound\",\n  status: 404\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class MethodNotAllowed extends HttpApiSchema.EmptyError<MethodNotAllowed>()({\n  tag: \"MethodNotAllowed\",\n  status: 405\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class NotAcceptable extends HttpApiSchema.EmptyError<NotAcceptable>()({\n  tag: \"NotAcceptable\",\n  status: 406\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class RequestTimeout extends HttpApiSchema.EmptyError<RequestTimeout>()({\n  tag: \"RequestTimeout\",\n  status: 408\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class Conflict extends HttpApiSchema.EmptyError<Conflict>()({\n  tag: \"Conflict\",\n  status: 409\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class Gone extends HttpApiSchema.EmptyError<Gone>()({\n  tag: \"Gone\",\n  status: 410\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class InternalServerError extends HttpApiSchema.EmptyError<InternalServerError>()({\n  tag: \"InternalServerError\",\n  status: 500\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class NotImplemented extends HttpApiSchema.EmptyError<NotImplemented>()({\n  tag: \"NotImplemented\",\n  status: 501\n}) {}\n\n/**\n * @since 1.0.0\n * @category empty errors\n */\nexport class ServiceUnavailable extends HttpApiSchema.EmptyError<ServiceUnavailable>()({\n  tag: \"ServiceUnavailable\",\n  status: 503\n}) {}\n"
  },
  {
    "path": "packages/platform/src/HttpApiGroup.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport { type Pipeable, pipeArguments } from \"effect/Pipeable\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Record from \"effect/Record\"\nimport * as Schema from \"effect/Schema\"\nimport type * as HttpApiEndpoint from \"./HttpApiEndpoint.js\"\nimport type { HttpApiDecodeError } from \"./HttpApiError.js\"\nimport type * as HttpApiMiddleware from \"./HttpApiMiddleware.js\"\nimport * as HttpApiSchema from \"./HttpApiSchema.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/HttpApiGroup\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isHttpApiGroup = (u: unknown): u is HttpApiGroup.Any => Predicate.hasProperty(u, TypeId)\n\n/**\n * An `HttpApiGroup` is a collection of `HttpApiEndpoint`s. You can use an `HttpApiGroup` to\n * represent a portion of your domain.\n *\n * The endpoints can be implemented later using the `HttpApiBuilder.group` api.\n *\n * @since 1.0.0\n * @category models\n */\nexport interface HttpApiGroup<\n  out Id extends string,\n  out Endpoints extends HttpApiEndpoint.HttpApiEndpoint.Any = never,\n  in out Error = HttpApiDecodeError,\n  out R = never,\n  out TopLevel extends (true | false) = false\n> extends Pipeable {\n  new(_: never): {}\n  readonly [TypeId]: TypeId\n  readonly identifier: Id\n  readonly topLevel: TopLevel\n  readonly endpoints: Record.ReadonlyRecord<string, Endpoints>\n  readonly errorSchema: Schema.Schema<Error, unknown, R>\n  readonly annotations: Context.Context<never>\n  readonly middlewares: ReadonlySet<HttpApiMiddleware.TagClassAny>\n\n  /**\n   * Add an `HttpApiEndpoint` to an `HttpApiGroup`.\n   */\n  add<A extends HttpApiEndpoint.HttpApiEndpoint.Any>(\n    endpoint: A\n  ): HttpApiGroup<Id, Endpoints | A, Error, R, TopLevel>\n\n  /**\n   * Add an error schema to an `HttpApiGroup`, which is shared by all endpoints in the\n   * group.\n   */\n  addError<A, I, RX>(\n    schema: Schema.Schema<A, I, RX>,\n    annotations?: {\n      readonly status?: number | undefined\n    }\n  ): HttpApiGroup<Id, Endpoints, Error | A, R | RX, TopLevel>\n\n  /**\n   * Add a path prefix to all endpoints in an `HttpApiGroup`. Note that this will only\n   * add the prefix to the endpoints before this api is called.\n   */\n  prefix(prefix: HttpApiEndpoint.PathSegment): HttpApiGroup<Id, Endpoints, Error, R, TopLevel>\n\n  /**\n   * Add an `HttpApiMiddleware` to the `HttpApiGroup`.\n   *\n   * It will be applied to all endpoints in the group.\n   */\n  middleware<I extends HttpApiMiddleware.HttpApiMiddleware.AnyId, S>(middleware: Context.Tag<I, S>): HttpApiGroup<\n    Id,\n    Endpoints,\n    Error | HttpApiMiddleware.HttpApiMiddleware.Error<I>,\n    R | I | HttpApiMiddleware.HttpApiMiddleware.ErrorContext<I>,\n    TopLevel\n  >\n\n  /**\n   * Add an `HttpApiMiddleware` to each endpoint in the `HttpApiGroup`.\n   *\n   * Endpoints added after this api is called will not have the middleware\n   * applied.\n   */\n  middlewareEndpoints<I extends HttpApiMiddleware.HttpApiMiddleware.AnyId, S>(\n    middleware: Context.Tag<I, S>\n  ): HttpApiGroup<\n    Id,\n    HttpApiEndpoint.HttpApiEndpoint.AddContext<Endpoints, I>,\n    Error,\n    R,\n    TopLevel\n  >\n\n  /**\n   * Merge the annotations of an `HttpApiGroup` with a new context.\n   */\n  annotateContext<I>(context: Context.Context<I>): HttpApiGroup<Id, Endpoints, Error, R, TopLevel>\n\n  /**\n   * Add an annotation to an `HttpApiGroup`.\n   */\n  annotate<I, S>(tag: Context.Tag<I, S>, value: S): HttpApiGroup<Id, Endpoints, Error, R, TopLevel>\n\n  /**\n   * For each endpoint in an `HttpApiGroup`, update the annotations with a new\n   * context.\n   *\n   * Note that this will only update the annotations before this api is called.\n   */\n  annotateEndpointsContext<I>(context: Context.Context<I>): HttpApiGroup<Id, Endpoints, Error, R, TopLevel>\n\n  /**\n   * For each endpoint in an `HttpApiGroup`, add an annotation.\n   *\n   * Note that this will only add the annotation to the endpoints before this api\n   * is called.\n   */\n  annotateEndpoints<I, S>(tag: Context.Tag<I, S>, value: S): HttpApiGroup<Id, Endpoints, Error, R, TopLevel>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface ApiGroup<ApiId extends string, Name extends string> {\n  readonly _: unique symbol\n  readonly apiId: ApiId\n  readonly name: Name\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace HttpApiGroup {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Any {\n    readonly [TypeId]: TypeId\n    readonly identifier: string\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type AnyWithProps = HttpApiGroup<string, HttpApiEndpoint.HttpApiEndpoint.AnyWithProps, any, any, boolean>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ToService<ApiId extends string, A> = A extends\n    HttpApiGroup<infer Name, infer _Endpoints, infer _Error, infer _R, infer _TopLevel> ? ApiGroup<ApiId, Name>\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type WithName<Group, Name extends string> = Extract<Group, { readonly identifier: Name }>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Name<Group> = Group extends\n    HttpApiGroup<infer _Name, infer _Endpoints, infer _Error, infer _R, infer _TopLevel> ? _Name\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Endpoints<Group> = Group extends\n    HttpApiGroup<infer _Name, infer _Endpoints, infer _Error, infer _R, infer _TopLevel> ? _Endpoints\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type EndpointsWithName<Group extends Any, Name extends string> = Endpoints<WithName<Group, Name>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Error<Group> = Group extends\n    HttpApiGroup<infer _Name, infer _Endpoints, infer _Error, infer _R, infer _TopLevel> ? _Error\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type AddContext<Group, R> = [R] extends [never] ? Group :\n    Group extends HttpApiGroup<infer _Name, infer _Endpoints, infer _Error, infer _R, infer _TopLevel> ?\n      HttpApiGroup<_Name, _Endpoints, _Error, _R | R, _TopLevel>\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Provides<Group extends Any> = HttpApiMiddleware.HttpApiMiddleware.ExtractProvides<Middleware<Group>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ErrorWithName<Group extends Any, Name extends string> = Error<WithName<Group, Name>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Context<Group> = Group extends\n    HttpApiGroup<infer _Name, infer _Endpoints, infer _Error, infer _R, infer _TopLevel> ?\n    HttpApiMiddleware.HttpApiMiddleware.Without<_R> :\n    never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Middleware<Group> = Group extends\n    HttpApiGroup<infer _Name, infer _Endpoints, infer _Error, infer _R, infer _TopLevel> ?\n    HttpApiMiddleware.HttpApiMiddleware.Only<_R> :\n    never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ClientContext<Group> = Group extends\n    HttpApiGroup<infer _Name, infer _Endpoints, infer _Error, infer _R, infer _TopLevel> ?\n      | _R\n      | HttpApiEndpoint.HttpApiEndpoint.Context<_Endpoints>\n      | HttpApiEndpoint.HttpApiEndpoint.ErrorContext<_Endpoints>\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ErrorContext<Group> = Group extends\n    HttpApiGroup<infer _Name, infer _Endpoints, infer _Error, infer _R, infer _TopLevel>\n    ? HttpApiMiddleware.HttpApiMiddleware.Without<_R> | HttpApiEndpoint.HttpApiEndpoint.ErrorContext<_Endpoints>\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ContextWithName<Group extends Any, Name extends string> = Context<WithName<Group, Name>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type MiddlewareWithName<Group extends Any, Name extends string> = Middleware<\n    WithName<Group, Name>\n  >\n}\n\nconst Proto = {\n  [TypeId]: TypeId,\n  add<A extends HttpApiEndpoint.HttpApiEndpoint.AnyWithProps>(this: HttpApiGroup.AnyWithProps, endpoint: A) {\n    return makeProto({\n      identifier: this.identifier,\n      topLevel: this.topLevel,\n      endpoints: {\n        ...this.endpoints,\n        [endpoint.name]: endpoint\n      },\n      errorSchema: this.errorSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    })\n  },\n  addError<A, I, R>(\n    this: HttpApiGroup.AnyWithProps,\n    schema: Schema.Schema<A, I, R>,\n    annotations?: { readonly status?: number }\n  ) {\n    return makeProto({\n      identifier: this.identifier,\n      topLevel: this.topLevel,\n      endpoints: this.endpoints,\n      errorSchema: HttpApiSchema.UnionUnify(\n        this.errorSchema,\n        annotations?.status ? schema.annotations(HttpApiSchema.annotations({ status: annotations.status })) : schema\n      ),\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    })\n  },\n  prefix(this: HttpApiGroup.AnyWithProps, prefix: HttpApiEndpoint.PathSegment) {\n    return makeProto({\n      identifier: this.identifier,\n      topLevel: this.topLevel,\n      endpoints: Record.map(this.endpoints, (endpoint) => endpoint.prefix(prefix)),\n      errorSchema: this.errorSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    })\n  },\n  middleware(this: HttpApiGroup.AnyWithProps, middleware: HttpApiMiddleware.TagClassAny) {\n    return makeProto({\n      identifier: this.identifier,\n      topLevel: this.topLevel,\n      endpoints: this.endpoints,\n      errorSchema: HttpApiSchema.UnionUnify(this.errorSchema, middleware.failure),\n      annotations: this.annotations,\n      middlewares: new Set([...this.middlewares, middleware])\n    })\n  },\n  middlewareEndpoints(this: HttpApiGroup.AnyWithProps, middleware: HttpApiMiddleware.TagClassAny) {\n    return makeProto({\n      identifier: this.identifier,\n      topLevel: this.topLevel,\n      endpoints: Record.map(this.endpoints, (endpoint) => endpoint.middleware(middleware)),\n      errorSchema: this.errorSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    })\n  },\n  annotateContext<I>(this: HttpApiGroup.AnyWithProps, context: Context.Context<I>) {\n    return makeProto({\n      identifier: this.identifier,\n      topLevel: this.topLevel,\n      endpoints: this.endpoints,\n      errorSchema: this.errorSchema,\n      annotations: Context.merge(this.annotations, context),\n      middlewares: this.middlewares\n    })\n  },\n  annotate<I, S>(this: HttpApiGroup.AnyWithProps, tag: Context.Tag<I, S>, value: S) {\n    return makeProto({\n      identifier: this.identifier,\n      topLevel: this.topLevel,\n      endpoints: this.endpoints,\n      errorSchema: this.errorSchema,\n      annotations: Context.add(this.annotations, tag, value),\n      middlewares: this.middlewares\n    })\n  },\n  annotateEndpointsContext<I>(this: HttpApiGroup.AnyWithProps, context: Context.Context<I>) {\n    return makeProto({\n      identifier: this.identifier,\n      topLevel: this.topLevel,\n      endpoints: Record.map(this.endpoints, (endpoint) => endpoint.annotateContext(context)),\n      errorSchema: this.errorSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    })\n  },\n  annotateEndpoints<I, S>(this: HttpApiGroup.AnyWithProps, tag: Context.Tag<I, S>, value: S) {\n    return makeProto({\n      identifier: this.identifier,\n      topLevel: this.topLevel,\n      endpoints: Record.map(this.endpoints, (endpoint) => endpoint.annotate(tag, value)),\n      errorSchema: this.errorSchema,\n      annotations: this.annotations,\n      middlewares: this.middlewares\n    })\n  },\n  pipe() {\n    return pipeArguments(this, arguments)\n  }\n}\n\nconst makeProto = <\n  Id extends string,\n  Endpoints extends HttpApiEndpoint.HttpApiEndpoint.Any,\n  Error,\n  R,\n  TopLevel extends (true | false)\n>(options: {\n  readonly identifier: Id\n  readonly topLevel: TopLevel\n  readonly endpoints: Record.ReadonlyRecord<string, Endpoints>\n  readonly errorSchema: Schema.Schema<Error, unknown, R>\n  readonly annotations: Context.Context<never>\n  readonly middlewares: ReadonlySet<HttpApiMiddleware.TagClassAny>\n}): HttpApiGroup<Id, Endpoints, Error, R, TopLevel> => {\n  function HttpApiGroup() {}\n  Object.setPrototypeOf(HttpApiGroup, Proto)\n  return Object.assign(HttpApiGroup, options) as any\n}\n\n/**\n * An `HttpApiGroup` is a collection of `HttpApiEndpoint`s. You can use an `HttpApiGroup` to\n * represent a portion of your domain.\n *\n * The endpoints can be implemented later using the `HttpApiBuilder.group` api.\n *\n * @since 1.0.0\n * @category constructors\n */\nexport const make = <const Id extends string, const TopLevel extends (true | false) = false>(identifier: Id, options?: {\n  readonly topLevel?: TopLevel | undefined\n}): HttpApiGroup<Id, never, never, never, TopLevel> =>\n  makeProto({\n    identifier,\n    topLevel: options?.topLevel ?? false as any,\n    endpoints: Record.empty(),\n    errorSchema: Schema.Never as any,\n    annotations: Context.empty(),\n    middlewares: new Set()\n  })\n"
  },
  {
    "path": "packages/platform/src/HttpApiMiddleware.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Context from \"effect/Context\"\nimport type * as Effect from \"effect/Effect\"\nimport { hasProperty } from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type { Mutable, Simplify } from \"effect/Types\"\nimport type * as HttpApiSecurity from \"./HttpApiSecurity.js\"\nimport type * as HttpRouter from \"./HttpRouter.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/HttpApiMiddleware\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const SecurityTypeId: unique symbol = Symbol.for(\"@effect/platform/HttpApiMiddleware/Security\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type SecurityTypeId = typeof SecurityTypeId\n\n/**\n * @since 1.0.0\n * @category guards\n */\nexport const isSecurity = (u: TagClassAny): u is TagClassSecurityAny => hasProperty(u, SecurityTypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HttpApiMiddleware<Provides, E> extends Effect.Effect<Provides, E, HttpRouter.HttpRouter.Provided> {}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type HttpApiMiddlewareSecurity<Security extends Record<string, HttpApiSecurity.HttpApiSecurity>, Provides, E> = {\n  readonly [K in keyof Security]: (\n    _: HttpApiSecurity.HttpApiSecurity.Type<Security[K]>\n  ) => Effect.Effect<Provides, E, HttpRouter.HttpRouter.Provided>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace HttpApiMiddleware {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Any {\n    readonly [TypeId]: TypeId\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface AnyId {\n    readonly [TypeId]: {\n      readonly provides: any\n    }\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Provides<A> = A extends { readonly [TypeId]: { readonly provides: infer P } } ? P : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ExtractProvides<A> = Provides<Only<A>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Error<A> = A extends { readonly [TypeId]: { readonly failure: infer E } } ? E : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type ErrorContext<A> = A extends { readonly [TypeId]: { readonly failureContext: infer R } } ? R : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Only<R> = Extract<R, AnyId>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Without<R> = Exclude<R, AnyId>\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type TagClass<\n  Self,\n  Name extends string,\n  Options\n> = Options extends { readonly security: Record<string, HttpApiSecurity.HttpApiSecurity> } ? TagClass.BaseSecurity<\n    Self,\n    Name,\n    Options,\n    Simplify<\n      HttpApiMiddlewareSecurity<\n        Options[\"security\"],\n        TagClass.Service<Options>,\n        TagClass.FailureService<Options>\n      >\n    >,\n    Options[\"security\"]\n  >\n  : TagClass.Base<\n    Self,\n    Name,\n    Options,\n    HttpApiMiddleware<\n      TagClass.Service<Options>,\n      TagClass.FailureService<Options>\n    >\n  >\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport declare namespace TagClass {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Provides<Options> = Options extends {\n    readonly provides: Context.Tag<any, any>\n    readonly optional?: false\n  } ? Context.Tag.Identifier<Options[\"provides\"]>\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Service<Options> = Options extends { readonly provides: Context.Tag<any, any> }\n    ? Context.Tag.Service<Options[\"provides\"]>\n    : void\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type FailureSchema<Options> = Options extends\n    { readonly failure: Schema.Schema.All; readonly optional?: false } ? Options[\"failure\"]\n    : typeof Schema.Never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Failure<Options> = Options extends\n    { readonly failure: Schema.Schema<infer _A, infer _I, infer _R>; readonly optional?: false } ? _A\n    : never\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type FailureContext<Options> = Schema.Schema.Context<FailureSchema<Options>>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type FailureService<Options> = Optional<Options> extends true ? unknown : Failure<Options>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Optional<Options> = Options extends { readonly optional: true } ? true : false\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Base<Self, Name extends string, Options, Service> extends Context.Tag<Self, Service> {\n    new(_: never):\n      & Context.TagClassShape<Name, Service>\n      & {\n        readonly [TypeId]: {\n          readonly provides: Provides<Options>\n          readonly failure: Failure<Options>\n          readonly failureContext: FailureContext<Options>\n        }\n      }\n    readonly [TypeId]: TypeId\n    readonly optional: Optional<Options>\n    readonly failure: FailureSchema<Options>\n    readonly provides: Options extends { readonly provides: Context.Tag<any, any> } ? Options[\"provides\"]\n      : undefined\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface BaseSecurity<\n    Self,\n    Name extends string,\n    Options,\n    Service,\n    Security extends Record<string, HttpApiSecurity.HttpApiSecurity>\n  > extends Base<Self, Name, Options, Service> {\n    readonly [SecurityTypeId]: SecurityTypeId\n    readonly security: Security\n  }\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface TagClassAny extends Context.Tag<any, HttpApiMiddleware.Any> {\n  readonly [TypeId]: TypeId\n  readonly optional: boolean\n  readonly provides?: Context.Tag<any, any>\n  readonly failure: Schema.Schema.All\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface TagClassSecurityAny extends TagClassAny {\n  readonly [SecurityTypeId]: SecurityTypeId\n  readonly security: Record<string, HttpApiSecurity.HttpApiSecurity>\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const Tag = <Self>(): <\n  const Name extends string,\n  const Options extends {\n    readonly optional?: boolean\n    readonly failure?: Schema.Schema.All\n    readonly provides?: Context.Tag<any, any>\n    readonly security?: Record<string, HttpApiSecurity.HttpApiSecurity>\n  }\n>(\n  id: Name,\n  options?: Options | undefined\n) => TagClass<Self, Name, Options> =>\n(\n  id: string,\n  options?: {\n    readonly optional?: boolean\n    readonly security?: Record<string, HttpApiSecurity.HttpApiSecurity>\n    readonly failure?: Schema.Schema.All\n    readonly provides?: Context.Tag<any, any>\n  }\n) => {\n  const Err = globalThis.Error as any\n  const limit = Err.stackTraceLimit\n  Err.stackTraceLimit = 2\n  const creationError = new Err()\n  Err.stackTraceLimit = limit\n\n  function TagClass() {}\n  const TagClass_ = TagClass as any as Mutable<TagClassSecurityAny>\n  Object.setPrototypeOf(TagClass, Object.getPrototypeOf(Context.GenericTag<Self, any>(id)))\n  TagClass.key = id\n  Object.defineProperty(TagClass, \"stack\", {\n    get() {\n      return creationError.stack\n    }\n  })\n  TagClass_[TypeId] = TypeId\n  TagClass_.failure = options?.optional === true || options?.failure === undefined ? Schema.Never : options.failure\n  if (options?.provides) {\n    TagClass_.provides = options.provides\n  }\n  TagClass_.optional = options?.optional ?? false\n  if (options?.security) {\n    if (Object.keys(options.security).length === 0) {\n      throw new Error(\"HttpApiMiddleware.Tag: security object must not be empty\")\n    }\n    TagClass_[SecurityTypeId] = SecurityTypeId\n    TagClass_.security = options.security\n  }\n  return TagClass as any\n}\n"
  },
  {
    "path": "packages/platform/src/HttpApiScalar.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport { Api } from \"./HttpApi.js\"\nimport type * as HttpApi from \"./HttpApi.js\"\nimport { Router } from \"./HttpApiBuilder.js\"\nimport * as HttpLayerRouter from \"./HttpLayerRouter.js\"\nimport * as HttpServerResponse from \"./HttpServerResponse.js\"\nimport * as Html from \"./internal/html.js\"\nimport * as internal from \"./internal/httpApiScalar.js\"\nimport * as OpenApi from \"./OpenApi.js\"\n\n/**\n * @since 1.0.0\n * @category model\n */\nexport type ScalarThemeId =\n  | \"alternate\"\n  | \"default\"\n  | \"moon\"\n  | \"purple\"\n  | \"solarized\"\n  | \"bluePlanet\"\n  | \"saturn\"\n  | \"kepler\"\n  | \"mars\"\n  | \"deepSpace\"\n  | \"laserwave\"\n  | \"none\"\n\n/**\n * @see https://github.com/scalar/scalar/blob/main/documentation/configuration.md\n *\n * @since 1.0.0\n * @category model\n */\nexport type ScalarConfig = {\n  /** A string to use one of the color presets */\n  theme?: ScalarThemeId\n  /** The layout to use for the references */\n  layout?: \"modern\" | \"classic\"\n  /** URL to a request proxy for the API client */\n  proxyUrl?: string\n  /** Whether to show the sidebar */\n  showSidebar?: boolean\n  /**\n   * Whether to show models in the sidebar, search, and content.\n   *\n   * Default: `false`\n   */\n  hideModels?: boolean\n  /**\n   * Whether to show the “Test Request” button\n   *\n   * Default: `false`\n   */\n  hideTestRequestButton?: boolean\n  /**\n   * Whether to show the sidebar search bar\n   *\n   * Default: `false`\n   */\n  hideSearch?: boolean\n  /** Whether dark mode is on or off initially (light mode) */\n  darkMode?: boolean\n  /** forceDarkModeState makes it always this state no matter what*/\n  forceDarkModeState?: \"dark\" | \"light\"\n  /** Whether to show the dark mode toggle */\n  hideDarkModeToggle?: boolean\n  /**\n   * Path to a favicon image\n   *\n   * Default: `undefined`\n   * Example: '/favicon.svg'\n   */\n  favicon?: string\n  /** Custom CSS to be added to the page */\n  customCss?: string\n  /**\n   * The baseServerURL is used when the spec servers are relative paths and we are using SSR.\n   * On the client we can grab the window.location.origin but on the server we need\n   * to use this prop.\n   *\n   * Default: `undefined`\n   * Example: 'http://localhost:3000'\n   */\n  baseServerURL?: string\n  /**\n   * We’re using Inter and JetBrains Mono as the default fonts. If you want to use your own fonts, set this to false.\n   *\n   * Default: `true`\n   */\n  withDefaultFonts?: boolean\n  /**\n   * By default we only open the relevant tag based on the url, however if you want all the tags open by default then set this configuration option :)\n   *\n   * Default: `false`\n   */\n  defaultOpenAllTags?: boolean\n}\n\nconst makeHandler = (options: {\n  readonly api: HttpApi.HttpApi.Any\n  readonly source: {\n    readonly _tag: \"Cdn\"\n    readonly version?: string | undefined\n  } | {\n    readonly _tag: \"Inline\"\n    readonly source: string\n  }\n  readonly scalar?: ScalarConfig\n}) => {\n  const spec = OpenApi.fromApi(options.api as any)\n\n  const source = options?.source\n\n  const scalarConfig = {\n    _integration: \"html\",\n    ...options?.scalar\n  }\n\n  const response = HttpServerResponse.html(`<!doctype html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <title>${Html.escape(spec.info.title)}</title>\n    ${\n    !spec.info.description\n      ? \"\"\n      : `<meta name=\"description\" content=\"${Html.escape(spec.info.description)}\"/>`\n  }\n    ${\n    !spec.info.description\n      ? \"\"\n      : `<meta name=\"og:description\" content=\"${Html.escape(spec.info.description)}\"/>`\n  }\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1\" />\n  </head>\n  <body>\n    <script id=\"api-reference\" type=\"application/json\">\n      ${Html.escapeJson(spec)}\n    </script>\n    <script>\n      document.getElementById('api-reference').dataset.configuration = JSON.stringify(${Html.escapeJson(scalarConfig)})\n    </script>\n    ${\n    source._tag === \"Cdn\"\n      ? `<script src=\"${`https://cdn.jsdelivr.net/npm/@scalar/api-reference@${\n        source.version ?? \"latest\"\n      }/dist/browser/standalone.min.js`}\" crossorigin></script>`\n      : `<script>${source.source}</script>`\n  }\n  </body>\n</html>`)\n\n  return Effect.succeed(response)\n}\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layer = (options?: {\n  readonly path?: `/${string}` | undefined\n  readonly scalar?: ScalarConfig\n}): Layer.Layer<never, never, Api> =>\n  Router.use(Effect.fnUntraced(function*(router) {\n    const { api } = yield* Api\n    const handler = makeHandler({\n      ...options,\n      api,\n      source: {\n        _tag: \"Inline\",\n        source: internal.javascript\n      }\n    })\n    yield* router.get(options?.path ?? \"/docs\", handler)\n  }))\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerCdn = (options?: {\n  readonly path?: `/${string}` | undefined\n  readonly scalar?: ScalarConfig\n  readonly version?: string | undefined\n}): Layer.Layer<never, never, Api> =>\n  Router.use(Effect.fnUntraced(function*(router) {\n    const { api } = yield* Api\n    const handler = makeHandler({\n      ...options,\n      api,\n      source: {\n        _tag: \"Cdn\",\n        version: options?.version\n      }\n    })\n    yield* router.get(options?.path ?? \"/docs\", handler)\n  }))\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerHttpLayerRouter: (\n  options: {\n    readonly api: HttpApi.HttpApi.Any\n    readonly path: `/${string}`\n    readonly scalar?: ScalarConfig\n  }\n) => Layer.Layer<\n  never,\n  never,\n  HttpLayerRouter.HttpRouter\n> = Effect.fnUntraced(function*(options: {\n  readonly api: HttpApi.HttpApi.Any\n  readonly path: `/${string}`\n  readonly scalar?: ScalarConfig\n}) {\n  const router = yield* HttpLayerRouter.HttpRouter\n  const handler = makeHandler({\n    ...options,\n    source: {\n      _tag: \"Inline\",\n      source: internal.javascript\n    }\n  })\n  yield* router.add(\"GET\", options.path, handler)\n}, Layer.effectDiscard)\n\n/**\n * @since 1.0.0\n * @category layers\n */\nexport const layerHttpLayerRouterCdn: (\n  options: {\n    readonly api: HttpApi.HttpApi.Any\n    readonly path: `/${string}`\n    readonly version?: string | undefined\n    readonly scalar?: ScalarConfig\n  }\n) => Layer.Layer<\n  never,\n  never,\n  HttpLayerRouter.HttpRouter\n> = Effect.fnUntraced(function*(options: {\n  readonly api: HttpApi.HttpApi.Any\n  readonly path: `/${string}`\n  readonly version?: string | undefined\n  readonly scalar?: ScalarConfig\n}) {\n  const router = yield* HttpLayerRouter.HttpRouter\n  const handler = makeHandler({\n    ...options,\n    source: {\n      _tag: \"Cdn\",\n      version: options?.version\n    }\n  })\n  yield* router.add(\"GET\", options.path, handler)\n}, Layer.effectDiscard)\n"
  },
  {
    "path": "packages/platform/src/HttpApp.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport type * as FiberRef from \"effect/FiberRef\"\nimport * as GlobalValue from \"effect/GlobalValue\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Runtime from \"effect/Runtime\"\nimport * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Types from \"effect/Types\"\nimport { unify } from \"effect/Unify\"\nimport * as HttpBody from \"./HttpBody.js\"\nimport type { HttpMiddleware } from \"./HttpMiddleware.js\"\nimport * as ServerError from \"./HttpServerError.js\"\nimport * as ServerRequest from \"./HttpServerRequest.js\"\nimport * as ServerResponse from \"./HttpServerResponse.js\"\nimport * as internal from \"./internal/httpApp.js\"\nimport * as internalMiddleware from \"./internal/httpMiddleware.js\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type HttpApp<A = ServerResponse.HttpServerResponse, E = never, R = never> = Effect.Effect<\n  A,\n  E,\n  R | ServerRequest.HttpServerRequest\n>\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type Default<E = never, R = never> = HttpApp<ServerResponse.HttpServerResponse, E, R>\n\nconst handledSymbol = Symbol.for(\"@effect/platform/HttpApp/handled\")\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const toHandled = <E, R, _, EH, RH>(\n  self: Default<E, R>,\n  handleResponse: (\n    request: ServerRequest.HttpServerRequest,\n    response: ServerResponse.HttpServerResponse\n  ) => Effect.Effect<_, EH, RH>,\n  middleware?: HttpMiddleware | undefined\n): Effect.Effect<void, never, Exclude<R | RH | ServerRequest.HttpServerRequest, Scope.Scope>> => {\n  const responded = Effect.withFiberRuntime<\n    ServerResponse.HttpServerResponse,\n    E | EH | ServerError.ResponseError,\n    R | RH | ServerRequest.HttpServerRequest\n  >((fiber) =>\n    Effect.flatMap(self, (response) => {\n      const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n      const handler = fiber.getFiberRef(currentPreResponseHandlers)\n      if (handler._tag === \"None\") {\n        ;(request as any)[handledSymbol] = true\n        return Effect.as(handleResponse(request, response), response)\n      }\n      return Effect.tap(handler.value(request, response), (response) => {\n        ;(request as any)[handledSymbol] = true\n        return handleResponse(request, response)\n      })\n    })\n  )\n\n  const withErrorHandling = Effect.catchAllCause(\n    responded,\n    (cause) =>\n      Effect.withFiberRuntime<\n        ServerResponse.HttpServerResponse,\n        E | EH | ServerError.ResponseError,\n        ServerRequest.HttpServerRequest | RH\n      >((fiber) =>\n        Effect.flatMap(ServerError.causeResponse(cause), ([response, cause]) => {\n          const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n          const handler = fiber.getFiberRef(currentPreResponseHandlers)\n          if (handler._tag === \"None\") {\n            ;(request as any)[handledSymbol] = true\n            return Effect.zipRight(\n              handleResponse(request, response),\n              Cause.isEmptyType(cause) ? Effect.succeed(response) : Effect.failCause(cause)\n            )\n          }\n          return Effect.zipRight(\n            Effect.tap(handler.value(request, response), (response) => {\n              ;(request as any)[handledSymbol] = true\n              return handleResponse(request, response)\n            }),\n            Cause.isEmptyType(cause) ? Effect.succeed(response) : Effect.failCause(cause)\n          )\n        })\n      )\n  )\n\n  const withMiddleware = unify(\n    middleware === undefined ?\n      internalMiddleware.tracer(withErrorHandling) :\n      Effect.matchCauseEffect(internalMiddleware.tracer(middleware(withErrorHandling)), {\n        onFailure: (cause): Effect.Effect<void, EH, RH> =>\n          Effect.withFiberRuntime((fiber) => {\n            const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n            if (handledSymbol in request) {\n              return Effect.void\n            }\n            return Effect.matchCauseEffect(ServerError.causeResponse(cause), {\n              onFailure: (_cause) => handleResponse(request, ServerResponse.empty({ status: 500 })),\n              onSuccess: ([response]) => handleResponse(request, response)\n            })\n          }),\n        onSuccess: (response): Effect.Effect<void, EH, RH> =>\n          Effect.withFiberRuntime((fiber) => {\n            const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n            return handledSymbol in request ? Effect.void : handleResponse(request, response)\n          })\n      })\n  )\n\n  return Effect.uninterruptible(scoped(withMiddleware)) as any\n}\n\n/**\n * If you want to finalize the http request scope elsewhere, you can use this\n * function to eject from the default scope closure.\n *\n * @since 1.0.0\n * @category Scope\n */\nexport const ejectDefaultScopeClose = (scope: Scope.Scope): void => {\n  ejectedScopes.add(scope)\n}\n\n/**\n * @since 1.0.0\n * @category Scope\n */\nexport const unsafeEjectStreamScope = (\n  response: ServerResponse.HttpServerResponse\n): ServerResponse.HttpServerResponse => {\n  if (response.body._tag !== \"Stream\") {\n    return response\n  }\n  const fiber = Option.getOrThrow(Fiber.getCurrentFiber())\n  const scope = Context.unsafeGet(fiber.currentContext, Scope.Scope) as Scope.CloseableScope\n  ejectDefaultScopeClose(scope)\n  return ServerResponse.setBody(\n    response,\n    HttpBody.stream(\n      Stream.ensuring(response.body.stream, Scope.close(scope, Exit.void)),\n      response.body.contentType,\n      response.body.contentLength\n    )\n  )\n}\n\nconst ejectedScopes = GlobalValue.globalValue(\n  \"@effect/platform/HttpApp/ejectedScopes\",\n  () => new WeakSet<Scope.Scope>()\n)\n\nconst scoped = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n  Effect.flatMap(Scope.make(), (scope) =>\n    Effect.onExit(Scope.extend(effect, scope), (exit) => {\n      if (ejectedScopes.has(scope)) {\n        return Effect.void\n      }\n      return Scope.close(scope, exit)\n    }))\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type PreResponseHandler = (\n  request: ServerRequest.HttpServerRequest,\n  response: ServerResponse.HttpServerResponse\n) => Effect.Effect<ServerResponse.HttpServerResponse, ServerError.ResponseError>\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const currentPreResponseHandlers: FiberRef.FiberRef<Option.Option<PreResponseHandler>> =\n  internal.currentPreResponseHandlers\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const appendPreResponseHandler: (handler: PreResponseHandler) => Effect.Effect<void> =\n  internal.appendPreResponseHandler\n\n/**\n * @since 1.0.0\n * @category fiber refs\n */\nexport const withPreResponseHandler = internal.withPreResponseHandler\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWebHandlerRuntime = <R>(runtime: Runtime.Runtime<R>) => {\n  const httpRuntime: Types.Mutable<Runtime.Runtime<R>> = Runtime.make(runtime)\n  const run = Runtime.runFork(httpRuntime)\n  return <E>(self: Default<E, R | Scope.Scope>, middleware?: HttpMiddleware | undefined) => {\n    const resolveSymbol = Symbol.for(\"@effect/platform/HttpApp/resolve\")\n    const httpApp = toHandled(self, (request, response) => {\n      response = unsafeEjectStreamScope(response)\n      ;(request as any)[resolveSymbol](\n        ServerResponse.toWeb(response, { withoutBody: request.method === \"HEAD\", runtime })\n      )\n      return Effect.void\n    }, middleware)\n    return (request: Request, context?: Context.Context<never> | undefined): Promise<Response> =>\n      new Promise((resolve) => {\n        const contextMap = new Map<string, any>(runtime.context.unsafeMap)\n        if (Context.isContext(context)) {\n          for (const [key, value] of context.unsafeMap) {\n            contextMap.set(key, value)\n          }\n        }\n        const httpServerRequest = ServerRequest.fromWeb(request)\n        contextMap.set(ServerRequest.HttpServerRequest.key, httpServerRequest)\n        ;(httpServerRequest as any)[resolveSymbol] = resolve\n        httpRuntime.context = Context.unsafeMake(contextMap)\n        const fiber = run(httpApp as any)\n        request.signal?.addEventListener(\"abort\", () => {\n          fiber.unsafeInterruptAsFork(ServerError.clientAbortFiberId)\n        }, { once: true })\n      })\n  }\n}\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWebHandler: <E>(\n  self: Default<E, Scope.Scope>,\n  middleware?: HttpMiddleware | undefined\n) => (request: Request, context?: Context.Context<never> | undefined) => Promise<Response> = toWebHandlerRuntime(\n  Runtime.defaultRuntime\n)\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWebHandlerLayerWith = <E, R, RE, EX>(\n  layer: Layer.Layer<R, RE>,\n  options: {\n    readonly toHandler: (\n      runtime: Runtime.Runtime<R>\n    ) => Effect.Effect<\n      Effect.Effect<ServerResponse.HttpServerResponse, E, R | Scope.Scope | ServerRequest.HttpServerRequest>,\n      EX\n    >\n    readonly middleware?: HttpMiddleware | undefined\n    readonly memoMap?: Layer.MemoMap | undefined\n  }\n): {\n  readonly dispose: () => Promise<void>\n  readonly handler: (request: Request, context?: Context.Context<never> | undefined) => Promise<Response>\n} => {\n  const scope = Effect.runSync(Scope.make())\n  const dispose = () => Effect.runPromise(Scope.close(scope, Exit.void))\n\n  let handlerCache: ((request: Request, context?: Context.Context<never> | undefined) => Promise<Response>) | undefined\n  let handlerPromise:\n    | Promise<(request: Request, context?: Context.Context<never> | undefined) => Promise<Response>>\n    | undefined\n  function handler(request: Request, context?: Context.Context<never> | undefined): Promise<Response> {\n    if (handlerCache) {\n      return handlerCache(request, context)\n    }\n    handlerPromise ??= Effect.gen(function*() {\n      const runtime = yield* (options.memoMap\n        ? Layer.toRuntimeWithMemoMap(layer, options.memoMap)\n        : Layer.toRuntime(layer))\n      return handlerCache = toWebHandlerRuntime(runtime)(\n        yield* options.toHandler(runtime),\n        options.middleware\n      )\n    }).pipe(\n      Scope.extend(scope),\n      Effect.runPromise\n    )\n    return handlerPromise.then((f) => f(request, context))\n  }\n  return { dispose, handler } as const\n}\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWebHandlerLayer = <E, R, RE>(\n  self: Default<E, R | Scope.Scope>,\n  layer: Layer.Layer<R, RE>,\n  options?: {\n    readonly memoMap?: Layer.MemoMap | undefined\n    readonly middleware?: HttpMiddleware | undefined\n  }\n): {\n  readonly dispose: () => Promise<void>\n  readonly handler: (request: Request, context?: Context.Context<never> | undefined) => Promise<Response>\n} =>\n  toWebHandlerLayerWith(layer, {\n    ...options,\n    toHandler: () => Effect.succeed(self)\n  })\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const fromWebHandler = (\n  handler: (request: Request) => Promise<Response>\n): Default<ServerError.HttpServerError> =>\n  Effect.async((resume, signal) => {\n    const fiber = Option.getOrThrow(Fiber.getCurrentFiber())\n    const request = Context.unsafeGet(fiber.currentContext, ServerRequest.HttpServerRequest)\n    const requestResult = ServerRequest.toWebEither(request, {\n      signal,\n      runtime: Runtime.make({\n        context: fiber.currentContext,\n        fiberRefs: fiber.getFiberRefs(),\n        runtimeFlags: Runtime.defaultRuntimeFlags\n      })\n    })\n    if (requestResult._tag === \"Left\") {\n      return resume(Effect.fail(requestResult.left))\n    }\n    handler(requestResult.right).then(\n      (response) => resume(Effect.succeed(ServerResponse.fromWeb(response))),\n      (cause) =>\n        resume(Effect.fail(\n          new ServerError.RequestError({\n            cause,\n            request,\n            reason: \"Transport\",\n            description: \"HttpApp.fromWebHandler: Error in handler\"\n          })\n        ))\n    )\n  })\n"
  },
  {
    "path": "packages/platform/src/HttpBody.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Effect from \"effect/Effect\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport * as Predicate from \"effect/Predicate\"\nimport type * as Schema from \"effect/Schema\"\nimport type * as Stream_ from \"effect/Stream\"\nimport type * as PlatformError from \"./Error.js\"\nimport type * as FileSystem from \"./FileSystem.js\"\nimport * as internal from \"./internal/httpBody.js\"\nimport type * as UrlParams from \"./UrlParams.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category refinements\n */\nexport const isHttpBody = (u: unknown): u is HttpBody => Predicate.hasProperty(u, TypeId)\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type HttpBody = Empty | Raw | Uint8Array | FormData | Stream\n\n/**\n * @since 1.0.0\n */\nexport declare namespace HttpBody {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface Proto extends Inspectable {\n    readonly [TypeId]: TypeId\n    readonly _tag: string\n    readonly contentType?: string | undefined\n    readonly contentLength?: number | undefined\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface FileLike {\n    readonly name: string\n    readonly lastModified: number\n    readonly size: number\n    readonly stream: () => unknown\n    readonly type: string\n  }\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const ErrorTypeId: unique symbol = internal.ErrorTypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type ErrorTypeId = typeof ErrorTypeId\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport interface HttpBodyError {\n  readonly [ErrorTypeId]: ErrorTypeId\n  readonly _tag: \"HttpBodyError\"\n  readonly reason: ErrorReason\n}\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport const HttpBodyError: (reason: ErrorReason) => HttpBodyError = internal.HttpBodyError\n\n/**\n * @since 1.0.0\n * @category errors\n */\nexport type ErrorReason = {\n  readonly _tag: \"JsonError\"\n  readonly error: unknown\n} | {\n  readonly _tag: \"SchemaError\"\n  readonly error: ParseResult.ParseError\n}\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Empty extends HttpBody.Proto {\n  readonly _tag: \"Empty\"\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: Empty = internal.empty\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Raw extends HttpBody.Proto {\n  readonly _tag: \"Raw\"\n  readonly body: unknown\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const raw: (\n  body: unknown,\n  options?: {\n    readonly contentType?: string | undefined\n    readonly contentLength?: number | undefined\n  } | undefined\n) => Raw = internal.raw\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Uint8Array extends HttpBody.Proto {\n  readonly _tag: \"Uint8Array\"\n  readonly body: globalThis.Uint8Array\n  readonly contentType: string\n  readonly contentLength: number\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const uint8Array: (body: globalThis.Uint8Array, contentType?: string) => Uint8Array = internal.uint8Array\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const text: (body: string, contentType?: string) => Uint8Array = internal.text\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const unsafeJson: (body: unknown, contentType?: string) => Uint8Array = internal.unsafeJson\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const json: (body: unknown, contentType?: string) => Effect.Effect<Uint8Array, HttpBodyError> = internal.json\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const jsonSchema: <A, I, R>(\n  schema: Schema.Schema<A, I, R>\n) => (body: A, contentType?: string) => Effect.Effect<Uint8Array, HttpBodyError, R> = internal.jsonSchema\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const urlParams: (urlParams: UrlParams.UrlParams, contentType?: string) => Uint8Array = internal.urlParams\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface FormData extends HttpBody.Proto {\n  readonly _tag: \"FormData\"\n  readonly formData: globalThis.FormData\n}\n\n/**\n * @since 1.0.0\n * @category FormData\n */\nexport const formData: (body: globalThis.FormData) => FormData = internal.formData\n\n/**\n * @since 1.0.0\n * @category FormData\n */\nexport type FormDataInput = Record<string, FormDataCoercible | ReadonlyArray<FormDataCoercible>>\n\n/**\n * @since 1.0.0\n * @category FormData\n */\nexport type FormDataCoercible = string | number | boolean | File | Blob | null | undefined\n\n/**\n * @since 1.0.0\n * @category FormData\n */\nexport const formDataRecord: (entries: FormDataInput) => FormData = internal.formDataRecord\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Stream extends HttpBody.Proto {\n  readonly _tag: \"Stream\"\n  readonly stream: Stream_.Stream<globalThis.Uint8Array, unknown>\n  readonly contentType: string\n  readonly contentLength?: number | undefined\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const stream: (\n  body: Stream_.Stream<globalThis.Uint8Array, unknown>,\n  contentType?: string,\n  contentLength?: number\n) => Stream = internal.stream\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const file: (\n  path: string,\n  options?: FileSystem.StreamOptions & { readonly contentType?: string }\n) => Effect.Effect<Stream, PlatformError.PlatformError, FileSystem.FileSystem> = internal.file\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fileInfo: (\n  path: string,\n  info: FileSystem.File.Info,\n  options?: FileSystem.StreamOptions & { readonly contentType?: string }\n) => Effect.Effect<Stream, PlatformError.PlatformError, FileSystem.FileSystem> = internal.fileInfo\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fileWeb: (file: HttpBody.FileLike) => Stream = internal.fileWeb\n"
  },
  {
    "path": "packages/platform/src/HttpClient.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Context from \"effect/Context\"\nimport type * as Effect from \"effect/Effect\"\nimport type { RuntimeFiber } from \"effect/Fiber\"\nimport type * as FiberRef from \"effect/FiberRef\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport type { Layer } from \"effect/Layer\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport type * as Predicate from \"effect/Predicate\"\nimport type { Ref } from \"effect/Ref\"\nimport type * as Schedule from \"effect/Schedule\"\nimport type { Scope } from \"effect/Scope\"\nimport type { NoExcessProperties, NoInfer } from \"effect/Types\"\nimport type { Cookies } from \"./Cookies.js\"\nimport type * as Error from \"./HttpClientError.js\"\nimport type * as ClientRequest from \"./HttpClientRequest.js\"\nimport type * as ClientResponse from \"./HttpClientResponse.js\"\nimport * as internal from \"./internal/httpClient.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HttpClient extends HttpClient.With<Error.HttpClientError> {}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace HttpClient {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface With<E, R = never> extends Pipeable, Inspectable {\n    readonly [TypeId]: TypeId\n    readonly execute: (\n      request: ClientRequest.HttpClientRequest\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n\n    readonly get: (\n      url: string | URL,\n      options?: ClientRequest.Options.NoBody\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n    readonly head: (\n      url: string | URL,\n      options?: ClientRequest.Options.NoBody\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n    readonly post: (\n      url: string | URL,\n      options?: ClientRequest.Options.NoUrl\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n    readonly patch: (\n      url: string | URL,\n      options?: ClientRequest.Options.NoUrl\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n    readonly put: (\n      url: string | URL,\n      options?: ClientRequest.Options.NoUrl\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n    readonly del: (\n      url: string | URL,\n      options?: ClientRequest.Options.NoUrl\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n    readonly options: (\n      url: string | URL,\n      options?: ClientRequest.Options.NoUrl\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Preprocess<E, R> = (\n    request: ClientRequest.HttpClientRequest\n  ) => Effect.Effect<ClientRequest.HttpClientRequest, E, R>\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export type Postprocess<E = never, R = never> = (\n    request: Effect.Effect<ClientRequest.HttpClientRequest, E, R>\n  ) => Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n}\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const HttpClient: Context.Tag<HttpClient, HttpClient> = internal.tag\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const execute: (\n  request: ClientRequest.HttpClientRequest\n) => Effect.Effect<ClientResponse.HttpClientResponse, Error.HttpClientError, HttpClient> = internal.execute\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const get: (\n  url: string | URL,\n  options?: ClientRequest.Options.NoBody | undefined\n) => Effect.Effect<\n  ClientResponse.HttpClientResponse,\n  Error.HttpClientError,\n  HttpClient\n> = internal.get\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const head: (\n  url: string | URL,\n  options?: ClientRequest.Options.NoBody | undefined\n) => Effect.Effect<\n  ClientResponse.HttpClientResponse,\n  Error.HttpClientError,\n  HttpClient\n> = internal.head\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const post: (\n  url: string | URL,\n  options?: ClientRequest.Options.NoUrl | undefined\n) => Effect.Effect<\n  ClientResponse.HttpClientResponse,\n  Error.HttpClientError,\n  HttpClient\n> = internal.post\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const patch: (\n  url: string | URL,\n  options?: ClientRequest.Options.NoUrl | undefined\n) => Effect.Effect<\n  ClientResponse.HttpClientResponse,\n  Error.HttpClientError,\n  HttpClient\n> = internal.patch\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const put: (\n  url: string | URL,\n  options?: ClientRequest.Options.NoUrl | undefined\n) => Effect.Effect<\n  ClientResponse.HttpClientResponse,\n  Error.HttpClientError,\n  HttpClient\n> = internal.put\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const del: (\n  url: string | URL,\n  options?: ClientRequest.Options.NoUrl | undefined\n) => Effect.Effect<\n  ClientResponse.HttpClientResponse,\n  Error.HttpClientError,\n  HttpClient\n> = internal.del\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const options: (\n  url: string | URL,\n  options?: ClientRequest.Options.NoUrl | undefined\n) => Effect.Effect<\n  ClientResponse.HttpClientResponse,\n  Error.HttpClientError,\n  HttpClient\n> = internal.options\n\n/**\n * @since 1.0.0\n * @category error handling\n */\nexport const catchAll: {\n  <E, E2, R2>(\n    f: (e: E) => Effect.Effect<ClientResponse.HttpClientResponse, E2, R2>\n  ): <R>(self: HttpClient.With<E, R>) => HttpClient.With<E2, R2 | R>\n  <E, R, A2, E2, R2>(\n    self: HttpClient.With<E, R>,\n    f: (e: E) => Effect.Effect<A2, E2, R2>\n  ): HttpClient.With<E2, R | R2>\n} = internal.catchAll\n\n/**\n * @since 1.0.0\n * @category error handling\n */\nexport const catchTag: {\n  <K extends E extends { _tag: string } ? E[\"_tag\"] : never, E, E1, R1>(\n    tag: K,\n    f: (e: Extract<E, { _tag: K }>) => Effect.Effect<ClientResponse.HttpClientResponse, E1, R1>\n  ): <R>(self: HttpClient.With<E, R>) => HttpClient.With<E1 | Exclude<E, { _tag: K }>, R1 | R>\n  <R, E, K extends E extends { _tag: string } ? E[\"_tag\"] : never, R1, E1>(\n    self: HttpClient.With<E, R>,\n    tag: K,\n    f: (e: Extract<E, { _tag: K }>) => Effect.Effect<ClientResponse.HttpClientResponse, E1, R1>\n  ): HttpClient.With<E1 | Exclude<E, { _tag: K }>, R1 | R>\n} = internal.catchTag\n\n/**\n * @since 1.0.0\n * @category error handling\n */\nexport const catchTags: {\n  <\n    E,\n    Cases extends\n      & {\n        [K in Extract<E, { _tag: string }>[\"_tag\"]]+?: (\n          error: Extract<E, { _tag: K }>\n        ) => Effect.Effect<ClientResponse.HttpClientResponse, any, any>\n      }\n      & (unknown extends E ? {} : { [K in Exclude<keyof Cases, Extract<E, { _tag: string }>[\"_tag\"]>]: never })\n  >(\n    cases: Cases\n  ): <R>(\n    self: HttpClient.With<E, R>\n  ) => HttpClient.With<\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect.Effect<any, infer E, any> ? E : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect.Effect<any, any, infer R> ? R : never\n    }[keyof Cases]\n  >\n  <\n    E extends { _tag: string },\n    R,\n    Cases extends\n      & {\n        [K in Extract<E, { _tag: string }>[\"_tag\"]]+?: (\n          error: Extract<E, { _tag: K }>\n        ) => Effect.Effect<ClientResponse.HttpClientResponse, any, any>\n      }\n      & (unknown extends E ? {} : { [K in Exclude<keyof Cases, Extract<E, { _tag: string }>[\"_tag\"]>]: never })\n  >(\n    self: HttpClient.With<E, R>,\n    cases: Cases\n  ): HttpClient.With<\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect.Effect<any, infer E, any> ? E : never\n    }[keyof Cases],\n    | R\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect.Effect<any, any, infer R> ? R : never\n    }[keyof Cases]\n  >\n} = internal.catchTags\n\n/**\n * Filters the result of a response, or runs an alternative effect if the predicate fails.\n *\n * @since 1.0.0\n * @category filters\n */\nexport const filterOrElse: {\n  <E2, R2>(\n    predicate: Predicate.Predicate<ClientResponse.HttpClientResponse>,\n    orElse: (response: ClientResponse.HttpClientResponse) => Effect.Effect<ClientResponse.HttpClientResponse, E2, R2>\n  ): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E2 | E, R2 | R>\n  <E, R, E2, R2>(\n    self: HttpClient.With<E, R>,\n    predicate: Predicate.Predicate<ClientResponse.HttpClientResponse>,\n    orElse: (response: ClientResponse.HttpClientResponse) => Effect.Effect<ClientResponse.HttpClientResponse, E2, R2>\n  ): HttpClient.With<E2 | E, R2 | R>\n} = internal.filterOrElse\n\n/**\n * Filters the result of a response, or throws an error if the predicate fails.\n *\n * @since 1.0.0\n * @category filters\n */\nexport const filterOrFail: {\n  <E2>(\n    predicate: Predicate.Predicate<ClientResponse.HttpClientResponse>,\n    orFailWith: (response: ClientResponse.HttpClientResponse) => E2\n  ): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E2 | E, R>\n  <E, R, E2>(\n    self: HttpClient.With<E, R>,\n    predicate: Predicate.Predicate<ClientResponse.HttpClientResponse>,\n    orFailWith: (response: ClientResponse.HttpClientResponse) => E2\n  ): HttpClient.With<E2 | E, R>\n} = internal.filterOrFail\n\n/**\n * Filters responses by HTTP status code.\n *\n * @since 1.0.0\n * @category filters\n */\nexport const filterStatus: {\n  (f: (status: number) => boolean): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E | Error.ResponseError, R>\n  <E, R>(self: HttpClient.With<E, R>, f: (status: number) => boolean): HttpClient.With<E | Error.ResponseError, R>\n} = internal.filterStatus\n\n/**\n * Filters responses that return a 2xx status code.\n *\n * @since 1.0.0\n * @category filters\n */\nexport const filterStatusOk: <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E | Error.ResponseError, R> =\n  internal.filterStatusOk\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeWith: <E2, R2, E, R>(\n  postprocess: (\n    request: Effect.Effect<ClientRequest.HttpClientRequest, E2, R2>\n  ) => Effect.Effect<ClientResponse.HttpClientResponse, E, R>,\n  preprocess: HttpClient.Preprocess<E2, R2>\n) => HttpClient.With<E, R> = internal.makeWith\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: (\n  f: (\n    request: ClientRequest.HttpClientRequest,\n    url: URL,\n    signal: AbortSignal,\n    fiber: RuntimeFiber<ClientResponse.HttpClientResponse, Error.HttpClientError>\n  ) => Effect.Effect<ClientResponse.HttpClientResponse, Error.HttpClientError>\n) => HttpClient = internal.make\n\n/**\n * @since 1.0.0\n * @category mapping & sequencing\n */\nexport const transform: {\n  <E, R, E1, R1>(\n    f: (\n      effect: Effect.Effect<ClientResponse.HttpClientResponse, E, R>,\n      request: ClientRequest.HttpClientRequest\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E1, R1>\n  ): (self: HttpClient.With<E, R>) => HttpClient.With<E | E1, R | R1>\n  <E, R, E1, R1>(\n    self: HttpClient.With<E, R>,\n    f: (\n      effect: Effect.Effect<ClientResponse.HttpClientResponse, E, R>,\n      request: ClientRequest.HttpClientRequest\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E1, R1>\n  ): HttpClient.With<E | E1, R | R1>\n} = internal.transform\n\n/**\n * @since 1.0.0\n * @category mapping & sequencing\n */\nexport const transformResponse: {\n  <E, R, E1, R1>(\n    f: (\n      effect: Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E1, R1>\n  ): (self: HttpClient.With<E, R>) => HttpClient.With<E1, R1>\n  <E, R, E1, R1>(\n    self: HttpClient.With<E, R>,\n    f: (\n      effect: Effect.Effect<ClientResponse.HttpClientResponse, E, R>\n    ) => Effect.Effect<ClientResponse.HttpClientResponse, E1, R1>\n  ): HttpClient.With<E1, R1>\n} = internal.transformResponse\n\n/**\n * Appends a transformation of the request object before sending it.\n *\n * @since 1.0.0\n * @category mapping & sequencing\n */\nexport const mapRequest: {\n  (\n    f: (a: ClientRequest.HttpClientRequest) => ClientRequest.HttpClientRequest\n  ): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E, R>\n  <E, R>(\n    self: HttpClient.With<E, R>,\n    f: (a: ClientRequest.HttpClientRequest) => ClientRequest.HttpClientRequest\n  ): HttpClient.With<E, R>\n} = internal.mapRequest\n\n/**\n * Appends an effectful transformation of the request object before sending it.\n *\n * @since 1.0.0\n * @category mapping & sequencing\n */\nexport const mapRequestEffect: {\n  <E2, R2>(\n    f: (a: ClientRequest.HttpClientRequest) => Effect.Effect<ClientRequest.HttpClientRequest, E2, R2>\n  ): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E | E2, R | R2>\n  <E, R, E2, R2>(\n    self: HttpClient.With<E, R>,\n    f: (a: ClientRequest.HttpClientRequest) => Effect.Effect<ClientRequest.HttpClientRequest, E2, R2>\n  ): HttpClient.With<E | E2, R | R2>\n} = internal.mapRequestEffect\n\n/**\n * Prepends a transformation of the request object before sending it.\n *\n * @since 1.0.0\n * @category mapping & sequencing\n */\nexport const mapRequestInput: {\n  (\n    f: (a: ClientRequest.HttpClientRequest) => ClientRequest.HttpClientRequest\n  ): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E, R>\n  <E, R>(\n    self: HttpClient.With<E, R>,\n    f: (a: ClientRequest.HttpClientRequest) => ClientRequest.HttpClientRequest\n  ): HttpClient.With<E, R>\n} = internal.mapRequestInput\n\n/**\n * Prepends an effectful transformation of the request object before sending it.\n *\n * @since 1.0.0\n * @category mapping & sequencing\n */\nexport const mapRequestInputEffect: {\n  <E2, R2>(\n    f: (a: ClientRequest.HttpClientRequest) => Effect.Effect<ClientRequest.HttpClientRequest, E2, R2>\n  ): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E | E2, R | R2>\n  <E, R, E2, R2>(\n    self: HttpClient.With<E, R>,\n    f: (a: ClientRequest.HttpClientRequest) => Effect.Effect<ClientRequest.HttpClientRequest, E2, R2>\n  ): HttpClient.With<E | E2, R | R2>\n} = internal.mapRequestInputEffect\n\n/**\n * @since 1.0.0\n * @category error handling\n */\nexport declare namespace Retry {\n  /**\n   * @since 1.0.0\n   * @category error handling\n   */\n  export type Return<R, E, O extends NoExcessProperties<Effect.Retry.Options<E>, O>> = HttpClient.With<\n    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer _R> } ? E\n      : O extends { until: Predicate.Refinement<E, infer E2> } ? E2\n      : E)\n    | (O extends { while: (...args: Array<any>) => Effect.Effect<infer _A, infer E, infer _R> } ? E : never)\n    | (O extends { until: (...args: Array<any>) => Effect.Effect<infer _A, infer E, infer _R> } ? E : never),\n    | R\n    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer R> } ? R : never)\n    | (O extends { while: (...args: Array<any>) => Effect.Effect<infer _A, infer _E, infer R> } ? R : never)\n    | (O extends { until: (...args: Array<any>) => Effect.Effect<infer _A, infer _E, infer R> } ? R : never)\n  > extends infer Z ? Z : never\n}\n\n/**\n * Retries the request based on a provided schedule or policy.\n *\n * @since 1.0.0\n * @category error handling\n */\nexport const retry: {\n  <E, O extends NoExcessProperties<Effect.Retry.Options<E>, O>>(\n    options: O\n  ): <R>(self: HttpClient.With<E, R>) => Retry.Return<R, E, O>\n  <B, E, R1>(\n    policy: Schedule.Schedule<B, NoInfer<E>, R1>\n  ): <R>(self: HttpClient.With<E, R>) => HttpClient.With<E, R1 | R>\n  <E, R, O extends NoExcessProperties<Effect.Retry.Options<E>, O>>(\n    self: HttpClient.With<E, R>,\n    options: O\n  ): Retry.Return<R, E, O>\n  <E, R, B, R1>(\n    self: HttpClient.With<E, R>,\n    policy: Schedule.Schedule<B, E, R1>\n  ): HttpClient.With<E, R1 | R>\n} = internal.retry\n\n/**\n * Retries common transient errors, such as rate limiting, timeouts or network issues.\n *\n * Specifying a `while` predicate allows you to consider other errors as\n * transient.\n *\n * @since 1.0.0\n * @category error handling\n */\nexport const retryTransient: {\n  <\n    B,\n    E,\n    R1 = never,\n    const Mode extends \"errors-only\" | \"response-only\" | \"both\" = never,\n    Input = \"errors-only\" extends Mode ? E\n      : \"response-only\" extends Mode ? ClientResponse.HttpClientResponse\n      : ClientResponse.HttpClientResponse | E\n  >(\n    options: {\n      readonly mode?: Mode | undefined\n      readonly while?: Predicate.Predicate<NoInfer<E>>\n      readonly schedule?: Schedule.Schedule<B, NoInfer<Input>, R1>\n      readonly times?: number\n    } | Schedule.Schedule<B, NoInfer<Input>, R1>\n  ): <R>(self: HttpClient.With<E, R>) => HttpClient.With<E, R1 | R>\n  <\n    E,\n    R,\n    B,\n    R1 = never,\n    const Mode extends \"errors-only\" | \"response-only\" | \"both\" = never,\n    Input = \"errors-only\" extends Mode ? E\n      : \"response-only\" extends Mode ? ClientResponse.HttpClientResponse\n      : ClientResponse.HttpClientResponse | E\n  >(\n    self: HttpClient.With<E, R>,\n    options: {\n      readonly mode?: Mode | undefined\n      readonly while?: Predicate.Predicate<NoInfer<E>>\n      readonly schedule?: Schedule.Schedule<B, NoInfer<Input>, R1>\n      readonly times?: number\n    } | Schedule.Schedule<B, NoInfer<Input>, R1>\n  ): HttpClient.With<E, R1 | R>\n} = internal.retryTransient\n\n/**\n * Performs an additional effect after a successful request.\n *\n * @since 1.0.0\n * @category mapping & sequencing\n */\nexport const tap: {\n  <_, E2, R2>(\n    f: (response: ClientResponse.HttpClientResponse) => Effect.Effect<_, E2, R2>\n  ): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E | E2, R | R2>\n  <E, R, _, E2, R2>(\n    self: HttpClient.With<E, R>,\n    f: (response: ClientResponse.HttpClientResponse) => Effect.Effect<_, E2, R2>\n  ): HttpClient.With<E | E2, R | R2>\n} = internal.tap\n\n/**\n * Performs an additional effect after an unsuccessful request.\n *\n * @since 1.0.0\n * @category mapping & sequencing\n */\nexport const tapError: {\n  <_, E, E2, R2>(\n    f: (e: NoInfer<E>) => Effect.Effect<_, E2, R2>\n  ): <R>(self: HttpClient.With<E, R>) => HttpClient.With<E | E2, R | R2>\n  <E, R, _, E2, R2>(\n    self: HttpClient.With<E, R>,\n    f: (e: NoInfer<E>) => Effect.Effect<_, E2, R2>\n  ): HttpClient.With<E | E2, R | R2>\n} = internal.tapError\n\n/**\n * Performs an additional effect on the request before sending it.\n *\n * @since 1.0.0\n * @category mapping & sequencing\n */\nexport const tapRequest: {\n  <_, E2, R2>(\n    f: (a: ClientRequest.HttpClientRequest) => Effect.Effect<_, E2, R2>\n  ): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E | E2, R | R2>\n  <E, R, _, E2, R2>(\n    self: HttpClient.With<E, R>,\n    f: (a: ClientRequest.HttpClientRequest) => Effect.Effect<_, E2, R2>\n  ): HttpClient.With<E | E2, R | R2>\n} = internal.tapRequest\n\n/**\n * Associates a `Ref` of cookies with the client for handling cookies across requests.\n *\n * @since 1.0.0\n * @category cookies\n */\nexport const withCookiesRef: {\n  (ref: Ref<Cookies>): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E, R>\n  <E, R>(self: HttpClient.With<E, R>, ref: Ref<Cookies>): HttpClient.With<E, R>\n} = internal.withCookiesRef\n\n/**\n * Follows HTTP redirects up to a specified number of times.\n *\n * @since 1.0.0\n * @category redirects\n */\nexport const followRedirects: {\n  (maxRedirects?: number | undefined): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E, R>\n  <E, R>(self: HttpClient.With<E, R>, maxRedirects?: number | undefined): HttpClient.With<E, R>\n} = internal.followRedirects\n\n/**\n * @since 1.0.0\n * @category Tracing\n */\nexport const currentTracerDisabledWhen: FiberRef.FiberRef<Predicate.Predicate<ClientRequest.HttpClientRequest>> =\n  internal.currentTracerDisabledWhen\n\n/**\n * Disables tracing for specific requests based on a provided predicate.\n *\n * @since 1.0.0\n * @category Tracing\n */\nexport const withTracerDisabledWhen: {\n  (\n    predicate: Predicate.Predicate<ClientRequest.HttpClientRequest>\n  ): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E, R>\n  <E, R>(\n    self: HttpClient.With<E, R>,\n    predicate: Predicate.Predicate<ClientRequest.HttpClientRequest>\n  ): HttpClient.With<E, R>\n} = internal.withTracerDisabledWhen\n\n/**\n * @since 1.0.0\n * @category Tracing\n */\nexport const currentTracerPropagation: FiberRef.FiberRef<boolean> = internal.currentTracerPropagation\n\n/**\n * Enables or disables tracing propagation for the request.\n *\n * @since 1.0.0\n * @category Tracing\n */\nexport const withTracerPropagation: {\n  (enabled: boolean): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E, R>\n  <E, R>(self: HttpClient.With<E, R>, enabled: boolean): HttpClient.With<E, R>\n} = internal.withTracerPropagation\n\n/**\n * @since 1.0.0\n */\nexport const layerMergedContext: <E, R>(\n  effect: Effect.Effect<HttpClient, E, R>\n) => Layer<HttpClient, E, R> = internal.layerMergedContext\n\n/**\n * @since 1.0.0\n * @category Tracing\n */\nexport interface SpanNameGenerator {\n  readonly _: unique symbol\n}\n\n/**\n * @since 1.0.0\n * @category Tracing\n */\nexport const SpanNameGenerator: Context.Reference<\n  SpanNameGenerator,\n  (request: ClientRequest.HttpClientRequest) => string\n> = internal.SpanNameGenerator\n\n/**\n * Customizes the span names for tracing.\n *\n * ```ts\n * import { FetchHttpClient, HttpClient } from \"@effect/platform\"\n * import { NodeRuntime } from \"@effect/platform-node\"\n * import { Effect } from \"effect\"\n *\n * Effect.gen(function* () {\n *   const client = (yield* HttpClient.HttpClient).pipe(\n *     // Customize the span names for this HttpClient\n *     HttpClient.withSpanNameGenerator(\n *       (request) => `http.client ${request.method} ${request.url}`\n *     )\n *   )\n *\n *   yield* client.get(\"https://jsonplaceholder.typicode.com/posts/1\")\n * }).pipe(Effect.provide(FetchHttpClient.layer), NodeRuntime.runMain)\n * ```\n *\n * @since 1.0.0\n * @category Tracing\n */\nexport const withSpanNameGenerator: {\n  (\n    f: (request: ClientRequest.HttpClientRequest) => string\n  ): <E, R>(self: HttpClient.With<E, R>) => HttpClient.With<E, R>\n  <E, R>(self: HttpClient.With<E, R>, f: (request: ClientRequest.HttpClientRequest) => string): HttpClient.With<E, R>\n} = internal.withSpanNameGenerator\n\n/**\n * Ties the lifetime of the `HttpClientRequest` to a `Scope`.\n *\n * @since 1.0.0\n * @category Scope\n */\nexport const withScope: <E, R>(\n  self: HttpClient.With<E, R>\n) => HttpClient.With<E, R | Scope> = internal.withScope\n"
  },
  {
    "path": "packages/platform/src/HttpClientRequest.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Effect from \"effect/Effect\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport type * as Option from \"effect/Option\"\nimport type { Pipeable } from \"effect/Pipeable\"\nimport type { Redacted } from \"effect/Redacted\"\nimport type * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport type * as Stream from \"effect/Stream\"\nimport type * as PlatformError from \"./Error.js\"\nimport type * as FileSystem from \"./FileSystem.js\"\nimport type * as Headers from \"./Headers.js\"\nimport type * as Body from \"./HttpBody.js\"\nimport type { HttpMethod } from \"./HttpMethod.js\"\nimport * as internal from \"./internal/httpClientRequest.js\"\nimport type * as UrlParams from \"./UrlParams.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/HttpClientRequest\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HttpClientRequest extends Inspectable, Pipeable {\n  readonly [TypeId]: TypeId\n  readonly method: HttpMethod\n  readonly url: string\n  readonly urlParams: UrlParams.UrlParams\n  readonly hash: Option.Option<string>\n  readonly headers: Headers.Headers\n  readonly body: Body.HttpBody\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Options {\n  readonly method?: HttpMethod | undefined\n  readonly url?: string | URL | undefined\n  readonly urlParams?: UrlParams.Input | undefined\n  readonly hash?: string | undefined\n  readonly headers?: Headers.Input | undefined\n  readonly body?: Body.HttpBody | undefined\n  readonly accept?: string | undefined\n  readonly acceptJson?: boolean | undefined\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Options {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface NoBody extends Omit<Options, \"method\" | \"url\" | \"body\"> {}\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface NoUrl extends Omit<Options, \"method\" | \"url\"> {}\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: <M extends HttpMethod>(\n  method: M\n) => (\n  url: string | URL,\n  options?: (M extends \"GET\" | \"HEAD\" ? Options.NoBody : Options.NoUrl) | undefined\n) => HttpClientRequest = internal.make\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const get: (url: string | URL, options?: Options.NoBody) => HttpClientRequest = internal.get\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const post: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = internal.post\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const patch: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = internal.patch\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const put: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = internal.put\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const del: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = internal.del\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const head: (url: string | URL, options?: Options.NoBody) => HttpClientRequest = internal.head\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const options: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = internal.options\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const modify: {\n  (options: Options): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, options: Options): HttpClientRequest\n} = internal.modify\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setMethod: {\n  (method: HttpMethod): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, method: HttpMethod): HttpClientRequest\n} = internal.setMethod\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setHeader: {\n  (key: string, value: string): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, key: string, value: string): HttpClientRequest\n} = internal.setHeader\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setHeaders: {\n  (input: Headers.Input): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, input: Headers.Input): HttpClientRequest\n} = internal.setHeaders\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const basicAuth: {\n  (username: string | Redacted, password: string | Redacted): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, username: string | Redacted, password: string | Redacted): HttpClientRequest\n} = internal.basicAuth\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bearerToken: {\n  (token: string | Redacted): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, token: string | Redacted): HttpClientRequest\n} = internal.bearerToken\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const accept: {\n  (mediaType: string): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, mediaType: string): HttpClientRequest\n} = internal.accept\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const acceptJson: (self: HttpClientRequest) => HttpClientRequest = internal.acceptJson\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setUrl: {\n  (url: string | URL): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, url: string | URL): HttpClientRequest\n} = internal.setUrl\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const prependUrl: {\n  (path: string): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, path: string): HttpClientRequest\n} = internal.prependUrl\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const appendUrl: {\n  (path: string): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, path: string): HttpClientRequest\n} = internal.appendUrl\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const updateUrl: {\n  (f: (url: string) => string): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, f: (url: string) => string): HttpClientRequest\n} = internal.updateUrl\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setUrlParam: {\n  (key: string, value: string): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, key: string, value: string): HttpClientRequest\n} = internal.setUrlParam\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setUrlParams: {\n  (input: UrlParams.Input): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest\n} = internal.setUrlParams\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const appendUrlParam: {\n  (key: string, value: string): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, key: string, value: string): HttpClientRequest\n} = internal.appendUrlParam\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const appendUrlParams: {\n  (input: UrlParams.Input): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest\n} = internal.appendUrlParams\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setHash: {\n  (hash: string): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, hash: string): HttpClientRequest\n} = internal.setHash\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const removeHash: (self: HttpClientRequest) => HttpClientRequest = internal.removeHash\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const toUrl: (self: HttpClientRequest) => Option.Option<URL> = internal.toUrl\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setBody: {\n  (body: Body.HttpBody): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, body: Body.HttpBody): HttpClientRequest\n} = internal.setBody\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bodyUint8Array: {\n  (body: Uint8Array, contentType?: string): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, body: Uint8Array, contentType?: string): HttpClientRequest\n} = internal.bodyUint8Array\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bodyText: {\n  (body: string, contentType?: string): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, body: string, contentType?: string): HttpClientRequest\n} = internal.bodyText\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bodyJson: {\n  (body: unknown): (self: HttpClientRequest) => Effect.Effect<HttpClientRequest, Body.HttpBodyError>\n  (self: HttpClientRequest, body: unknown): Effect.Effect<HttpClientRequest, Body.HttpBodyError>\n} = internal.bodyJson\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bodyUnsafeJson: {\n  (body: unknown): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, body: unknown): HttpClientRequest\n} = internal.bodyUnsafeJson\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const schemaBodyJson: <A, I, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: ParseOptions | undefined\n) => {\n  (body: A): (self: HttpClientRequest) => Effect.Effect<HttpClientRequest, Body.HttpBodyError, R>\n  (self: HttpClientRequest, body: A): Effect.Effect<HttpClientRequest, Body.HttpBodyError, R>\n} = internal.schemaBodyJson\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bodyUrlParams: {\n  (input: UrlParams.Input): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest\n} = internal.bodyUrlParams\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bodyFormData: {\n  (body: FormData): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, body: FormData): HttpClientRequest\n} = internal.bodyFormData\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bodyFormDataRecord: {\n  (entries: Body.FormDataInput): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, entries: Body.FormDataInput): HttpClientRequest\n} = internal.bodyFormDataRecord\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bodyStream: {\n  (\n    body: Stream.Stream<Uint8Array, unknown>,\n    options?: { readonly contentType?: string | undefined; readonly contentLength?: number | undefined } | undefined\n  ): (self: HttpClientRequest) => HttpClientRequest\n  (\n    self: HttpClientRequest,\n    body: Stream.Stream<Uint8Array, unknown>,\n    options?: { readonly contentType?: string | undefined; readonly contentLength?: number | undefined } | undefined\n  ): HttpClientRequest\n} = internal.bodyStream\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bodyFile: {\n  (\n    path: string,\n    options?: FileSystem.StreamOptions & { readonly contentType?: string }\n  ): (self: HttpClientRequest) => Effect.Effect<HttpClientRequest, PlatformError.PlatformError, FileSystem.FileSystem>\n  (\n    self: HttpClientRequest,\n    path: string,\n    options?: FileSystem.StreamOptions & { readonly contentType?: string }\n  ): Effect.Effect<HttpClientRequest, PlatformError.PlatformError, FileSystem.FileSystem>\n} = internal.bodyFile\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const bodyFileWeb: {\n  (file: Body.HttpBody.FileLike): (self: HttpClientRequest) => HttpClientRequest\n  (self: HttpClientRequest, file: Body.HttpBody.FileLike): HttpClientRequest\n} = internal.bodyFileWeb\n"
  },
  {
    "path": "packages/platform/src/HttpClientResponse.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Effect from \"effect/Effect\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport type * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport type * as Stream from \"effect/Stream\"\nimport type { Unify } from \"effect/Unify\"\nimport type * as Cookies from \"./Cookies.js\"\nimport type * as Error from \"./HttpClientError.js\"\nimport type * as ClientRequest from \"./HttpClientRequest.js\"\nimport type * as IncomingMessage from \"./HttpIncomingMessage.js\"\nimport * as internal from \"./internal/httpClientResponse.js\"\n\nexport {\n  /**\n   * @since 1.0.0\n   * @category schema\n   */\n  schemaBodyJson,\n  /**\n   * @since 1.0.0\n   * @category schema\n   */\n  schemaBodyUrlParams,\n  /**\n   * @since 1.0.0\n   * @category schema\n   */\n  schemaHeaders\n} from \"./HttpIncomingMessage.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HttpClientResponse extends IncomingMessage.HttpIncomingMessage<Error.ResponseError> {\n  readonly [TypeId]: TypeId\n  readonly request: ClientRequest.HttpClientRequest\n  readonly status: number\n  readonly cookies: Cookies.Cookies\n  readonly formData: Effect.Effect<FormData, Error.ResponseError>\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fromWeb: (request: ClientRequest.HttpClientRequest, source: Response) => HttpClientResponse =\n  internal.fromWeb\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaJson: <\n  R,\n  I extends {\n    readonly status?: number | undefined\n    readonly headers?: Readonly<Record<string, string>> | undefined\n    readonly body?: unknown\n  },\n  A\n>(\n  schema: Schema.Schema<A, I, R>,\n  options?: ParseOptions | undefined\n) => (self: HttpClientResponse) => Effect.Effect<A, Error.ResponseError | ParseResult.ParseError, R> =\n  internal.schemaJson\n\n/**\n * @since 1.0.0\n * @category schema\n */\nexport const schemaNoBody: <\n  R,\n  I extends {\n    readonly status?: number | undefined\n    readonly headers?: Readonly<Record<string, string>> | undefined\n  },\n  A\n>(\n  schema: Schema.Schema<A, I, R>,\n  options?: ParseOptions | undefined\n) => (self: HttpClientResponse) => Effect.Effect<A, ParseResult.ParseError, R> = internal.schemaNoBody\n\n/**\n * @since 1.0.0\n * @category accessors\n */\nexport const stream: <E, R>(\n  effect: Effect.Effect<HttpClientResponse, E, R>\n) => Stream.Stream<Uint8Array, Error.ResponseError | E, R> = internal.stream\n\n/**\n * @since 1.0.0\n * @category pattern matching\n */\nexport const matchStatus: {\n  <\n    const Cases extends {\n      readonly [status: number]: (_: HttpClientResponse) => any\n      readonly \"2xx\"?: (_: HttpClientResponse) => any\n      readonly \"3xx\"?: (_: HttpClientResponse) => any\n      readonly \"4xx\"?: (_: HttpClientResponse) => any\n      readonly \"5xx\"?: (_: HttpClientResponse) => any\n      readonly orElse: (_: HttpClientResponse) => any\n    }\n  >(cases: Cases): (self: HttpClientResponse) => Cases[keyof Cases] extends (_: any) => infer R ? Unify<R> : never\n  <\n    const Cases extends {\n      readonly [status: number]: (_: HttpClientResponse) => any\n      readonly \"2xx\"?: (_: HttpClientResponse) => any\n      readonly \"3xx\"?: (_: HttpClientResponse) => any\n      readonly \"4xx\"?: (_: HttpClientResponse) => any\n      readonly \"5xx\"?: (_: HttpClientResponse) => any\n      readonly orElse: (_: HttpClientResponse) => any\n    }\n  >(self: HttpClientResponse, cases: Cases): Cases[keyof Cases] extends (_: any) => infer R ? Unify<R> : never\n} = internal.matchStatus\n\n/**\n * @since 1.0.0\n * @category filters\n */\nexport const filterStatus: {\n  (f: (status: number) => boolean): (self: HttpClientResponse) => Effect.Effect<HttpClientResponse, Error.ResponseError>\n  (self: HttpClientResponse, f: (status: number) => boolean): Effect.Effect<HttpClientResponse, Error.ResponseError>\n} = internal.filterStatus\n\n/**\n * @since 1.0.0\n * @category filters\n */\nexport const filterStatusOk: (self: HttpClientResponse) => Effect.Effect<HttpClientResponse, Error.ResponseError> =\n  internal.filterStatusOk\n"
  },
  {
    "path": "packages/platform/src/HttpLayerRouter.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport * as HttpServerRequest from \"@effect/platform/HttpServerRequest\"\nimport * as HttpServerResponse from \"@effect/platform/HttpServerResponse\"\nimport * as Arr from \"effect/Array\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as FiberRef from \"effect/FiberRef\"\nimport { compose, constant, dual, identity } from \"effect/Function\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport type * as Predicate from \"effect/Predicate\"\nimport * as Scope from \"effect/Scope\"\nimport * as Tracer from \"effect/Tracer\"\nimport type * as Types from \"effect/Types\"\nimport * as FindMyWay from \"find-my-way-ts\"\nimport type * as Etag from \"./Etag.js\"\nimport type { FileSystem } from \"./FileSystem.js\"\nimport type * as HttpApi from \"./HttpApi.js\"\nimport * as HttpApiBuilder from \"./HttpApiBuilder.js\"\nimport type * as HttpApiGroup from \"./HttpApiGroup.js\"\nimport * as HttpApp from \"./HttpApp.js\"\nimport type * as HttpMethod from \"./HttpMethod.js\"\nimport * as HttpMiddleware from \"./HttpMiddleware.js\"\nimport type { HttpPlatform } from \"./HttpPlatform.js\"\nimport { RouteContext, RouteContextTypeId } from \"./HttpRouter.js\"\nimport * as HttpServer from \"./HttpServer.js\"\nimport * as HttpServerError from \"./HttpServerError.js\"\nimport * as OpenApi from \"./OpenApi.js\"\nimport type { Path } from \"./Path.js\"\n\n/**\n * @since 1.0.0\n * @category Re-exports\n */\nexport * as FindMyWay from \"find-my-way-ts\"\n\n/**\n * @since 1.0.0\n * @category HttpRouter\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/HttpLayerRouter/HttpRouter\")\n\n/**\n * @since 1.0.0\n * @category HttpRouter\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category HttpRouter\n */\nexport interface HttpRouter {\n  readonly [TypeId]: TypeId\n\n  readonly prefixed: (prefix: string) => HttpRouter\n\n  readonly add: <E, R>(\n    method: \"*\" | \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\",\n    path: PathInput,\n    handler:\n      | Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>\n      | ((request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>),\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ) => Effect.Effect<\n    void,\n    never,\n    Request.From<\"Requires\", Exclude<R, Provided>> | Request.From<\"Error\", E>\n  >\n\n  readonly addAll: <const Routes extends ReadonlyArray<Route<any, any>>>(\n    routes: Routes\n  ) => Effect.Effect<\n    void,\n    never,\n    | Request.From<\"Requires\", Exclude<Route.Context<Routes[number]>, Provided>>\n    | Request.From<\"Error\", Route.Error<Routes[number]>>\n  >\n\n  readonly addGlobalMiddleware: <E, R>(\n    middleware:\n      & ((\n        effect: Effect.Effect<HttpServerResponse.HttpServerResponse, unhandled>\n      ) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>)\n      & (unhandled extends E ? unknown : \"You cannot handle any errors\")\n  ) => Effect.Effect<\n    void,\n    never,\n    | Request.From<\"GlobalRequires\", Exclude<R, GlobalProvided>>\n    | Request.From<\"GlobalError\", Exclude<E, unhandled>>\n  >\n\n  readonly asHttpEffect: () => Effect.Effect<\n    HttpServerResponse.HttpServerResponse,\n    unknown,\n    HttpServerRequest.HttpServerRequest | Scope.Scope\n  >\n}\n\n/**\n * @since 1.0.0\n * @category HttpRouter\n */\nexport const HttpRouter: Context.Tag<HttpRouter, HttpRouter> = Context.GenericTag<HttpRouter>(\n  \"@effect/platform/HttpLayerRouter\"\n)\n\n/**\n * @since 1.0.0\n * @category HttpRouter\n */\nexport const make = Effect.gen(function*() {\n  const router = FindMyWay.make<Route<any, never>>(yield* RouterConfig)\n  const middleware = new Set<middleware.Fn>()\n\n  const addAll = <const Routes extends ReadonlyArray<Route<any, any>>>(\n    routes: Routes\n  ): Effect.Effect<\n    void,\n    never,\n    | Request.From<\"Requires\", Exclude<Route.Context<Routes[number]>, Provided>>\n    | Request.From<\"Error\", Route.Error<Routes[number]>>\n  > =>\n    Effect.contextWith((context: Context.Context<never>) => {\n      const middleware = getMiddleware(context)\n      const applyMiddleware = (effect: Effect.Effect<HttpServerResponse.HttpServerResponse>) => {\n        for (let i = 0; i < middleware.length; i++) {\n          effect = middleware[i](effect)\n        }\n        return effect\n      }\n      for (let i = 0; i < routes.length; i++) {\n        const route = middleware.length === 0 ? routes[i] : makeRoute({\n          ...routes[i],\n          handler: applyMiddleware(routes[i].handler as Effect.Effect<HttpServerResponse.HttpServerResponse>)\n        })\n        if (route.method === \"*\") {\n          router.all(route.path, route as any)\n        } else {\n          router.on(route.method, route.path, route as any)\n        }\n      }\n    })\n\n  return HttpRouter.of({\n    [TypeId]: TypeId,\n    prefixed(this: HttpRouter, prefix: string) {\n      return HttpRouter.of({\n        ...this,\n        prefixed: (newPrefix: string) => this.prefixed(prefixPath(prefix, newPrefix)),\n        addAll: (routes) => addAll(routes.map(prefixRoute(prefix))) as any,\n        add: (method, path, handler, options) =>\n          addAll([\n            makeRoute({\n              method,\n              path: prefixPath(path, prefix) as PathInput,\n              handler: Effect.isEffect(handler)\n                ? handler\n                : Effect.flatMap(HttpServerRequest.HttpServerRequest, handler),\n              uninterruptible: options?.uninterruptible ?? false,\n              prefix: Option.some(prefix)\n            })\n          ])\n      })\n    },\n    addAll,\n    add: (method, path, handler, options) => addAll([route(method, path, handler, options)]),\n    addGlobalMiddleware: (middleware_) =>\n      Effect.sync(() => {\n        middleware.add(middleware_ as any)\n      }),\n    asHttpEffect() {\n      let handler = Effect.withFiberRuntime<HttpServerResponse.HttpServerResponse, unknown>((fiber) => {\n        const contextMap = new Map(fiber.currentContext.unsafeMap)\n        const request = contextMap.get(HttpServerRequest.HttpServerRequest.key) as HttpServerRequest.HttpServerRequest\n        let result = router.find(request.method, request.url)\n        if (result === undefined && request.method === \"HEAD\") {\n          result = router.find(\"GET\", request.url)\n        }\n        if (result === undefined) {\n          return Effect.fail(new HttpServerError.RouteNotFound({ request }))\n        }\n        const route = result.handler\n        if (route.prefix._tag === \"Some\") {\n          contextMap.set(HttpServerRequest.HttpServerRequest.key, sliceRequestUrl(request, route.prefix.value))\n        }\n        contextMap.set(HttpServerRequest.ParsedSearchParams.key, result.searchParams)\n        contextMap.set(RouteContext.key, {\n          [RouteContextTypeId]: RouteContextTypeId,\n          route,\n          params: result.params\n        })\n\n        const span = contextMap.get(Tracer.ParentSpan.key) as Tracer.Span | undefined\n        if (span && span._tag === \"Span\") {\n          span.attribute(\"http.route\", route.path)\n        }\n        return Effect.locally(\n          (route.uninterruptible ?\n            route.handler :\n            Effect.interruptible(route.handler)) as Effect.Effect<\n              HttpServerResponse.HttpServerResponse,\n              unknown\n            >,\n          FiberRef.currentContext,\n          Context.unsafeMake(contextMap)\n        )\n      })\n      if (middleware.size === 0) return handler\n      for (const fn of Arr.reverse(middleware)) {\n        handler = fn(handler as any)\n      }\n      return handler\n    }\n  })\n})\n\nfunction sliceRequestUrl(request: HttpServerRequest.HttpServerRequest, prefix: string) {\n  const prefexLen = prefix.length\n  return request.modify({ url: request.url.length <= prefexLen ? \"/\" : request.url.slice(prefexLen) })\n}\n\n/**\n * @since 1.0.0\n * @category Configuration\n */\nexport class RouterConfig extends Context.Reference<RouterConfig>()(\"@effect/platform/HttpLayerRouter/RouterConfig\", {\n  defaultValue: constant<Partial<FindMyWay.RouterConfig>>({})\n}) {}\n\nexport {\n  /**\n   * @since 1.0.0\n   * @category Route context\n   */\n  params,\n  /**\n   * @since 1.0.0\n   * @category Route context\n   */\n  RouteContext,\n  /**\n   * @since 1.0.0\n   * @category Route context\n   */\n  schemaJson,\n  /**\n   * @since 1.0.0\n   * @category Route context\n   */\n  schemaNoBody,\n  /**\n   * @since 1.0.0\n   * @category Route context\n   */\n  schemaParams,\n  /**\n   * @since 1.0.0\n   * @category Route context\n   */\n  schemaPathParams\n} from \"./HttpRouter.js\"\n\n/**\n * A helper function that is the equivalent of:\n *\n * ```ts\n * import * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\n * import * as Effect from \"effect/Effect\"\n * import * as Layer from \"effect/Layer\"\n *\n * const MyRoute = Layer.scopedDiscard(Effect.gen(function*() {\n *   const router = yield* HttpLayerRouter.HttpRouter\n *\n *   // then use `yield* router.add(...)` to add a route\n * }))\n * ```\n *\n * @since 1.0.0\n * @category HttpRouter\n */\nexport const use = <A, E, R>(\n  f: (router: HttpRouter) => Effect.Effect<A, E, R>\n): Layer.Layer<never, E, HttpRouter | Exclude<R, Scope.Scope>> => Layer.scopedDiscard(Effect.flatMap(HttpRouter, f))\n\n/**\n * Create a layer that adds a single route to the HTTP router.\n *\n * ```ts\n * import * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\n * import * as HttpServerResponse from \"@effect/platform/HttpServerResponse\"\n *\n * const Route = HttpLayerRouter.add(\"GET\", \"/hello\", HttpServerResponse.text(\"Hello, World!\"))\n * ```\n *\n * @since 1.0.0\n * @category HttpRouter\n */\nexport const add = <E, R>(\n  method: \"*\" | \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\",\n  path: PathInput,\n  handler:\n    | Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>\n    | ((request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>),\n  options?: {\n    readonly uninterruptible?: boolean | undefined\n  }\n): Layer.Layer<never, never, HttpRouter | Request.From<\"Requires\", Exclude<R, Provided>> | Request.From<\"Error\", E>> =>\n  use((router) => router.add(method, path, handler, options))\n\n/**\n * Create a layer that adds multiple routes to the HTTP router.\n *\n * ```ts\n * import * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\n * import * as HttpServerResponse from \"@effect/platform/HttpServerResponse\"\n *\n * const Routes = HttpLayerRouter.addAll([\n *   HttpLayerRouter.route(\"GET\", \"/hello\", HttpServerResponse.text(\"Hello, World!\"))\n * ])\n * ```\n *\n * @since 1.0.0\n * @category HttpRouter\n */\nexport const addAll = <Routes extends ReadonlyArray<Route<any, any>>, EX = never, RX = never>(\n  routes: Routes | Effect.Effect<Routes, EX, RX>,\n  options?: {\n    readonly prefix?: string | undefined\n  }\n): Layer.Layer<\n  never,\n  EX,\n  | HttpRouter\n  | Exclude<RX, Scope.Scope>\n  | Request.From<\"Requires\", Exclude<Route.Context<Routes[number]>, Provided>>\n  | Request.From<\"Error\", Route.Error<Routes[number]>>\n> =>\n  Layer.scopedDiscard(Effect.gen(function*() {\n    const toAdd = Effect.isEffect(routes) ? yield* routes : routes\n    let router = yield* HttpRouter\n    if (options?.prefix) {\n      router = router.prefixed(options.prefix)\n    }\n    yield* router.addAll(toAdd)\n  }))\n\n/**\n * @since 1.0.0\n * @category HttpRouter\n */\nexport const layer: Layer.Layer<HttpRouter> = Layer.effect(HttpRouter, make)\n\n/**\n * @since 1.0.0\n * @category HttpRouter\n */\nexport const toHttpEffect = <A, E, R>(\n  appLayer: Layer.Layer<A, E, R>\n): Effect.Effect<\n  Effect.Effect<\n    HttpServerResponse.HttpServerResponse,\n    Request.Only<\"Error\", R> | Request.Only<\"GlobalRequires\", R> | HttpServerError.RouteNotFound,\n    Scope.Scope | HttpServerRequest.HttpServerRequest | Request.Only<\"Requires\", R> | Request.Only<\"GlobalRequires\", R>\n  >,\n  Request.Without<E>,\n  Exclude<Request.Without<R>, HttpRouter> | Scope.Scope\n> =>\n  Effect.gen(function*() {\n    const scope = yield* Effect.scope\n    const memoMap = yield* Layer.CurrentMemoMap\n    const context = yield* Layer.buildWithMemoMap(\n      Layer.provideMerge(appLayer, layer),\n      memoMap,\n      scope\n    )\n    const router = Context.get(context, HttpRouter)\n    return router.asHttpEffect()\n  }) as any\n\n/**\n * @since 1.0.0\n * @category Route\n */\nexport const RouteTypeId: unique symbol = Symbol.for(\"@effect/platform/HttpLayerRouter/Route\")\n\n/**\n * @since 1.0.0\n * @category Route\n */\nexport type RouteTypeId = typeof RouteTypeId\n\n/**\n * @since 1.0.0\n * @category Route\n */\nexport interface Route<E = never, R = never> {\n  readonly [RouteTypeId]: RouteTypeId\n  readonly method: HttpMethod.HttpMethod | \"*\"\n  readonly path: PathInput\n  readonly handler: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>\n  readonly uninterruptible: boolean\n  readonly prefix: Option.Option<string>\n}\n\n/**\n * @since 1.0.0\n * @category Route\n */\nexport declare namespace Route {\n  /**\n   * @since 1.0.0\n   * @category Route\n   */\n  export type Error<R extends Route<any, any>> = R extends Route<infer E, infer _R> ? E : never\n\n  /**\n   * @since 1.0.0\n   * @category Route\n   */\n  export type Context<T extends Route<any, any>> = T extends Route<infer _E, infer R> ? R : never\n}\n\nconst makeRoute = <E, R>(options: {\n  readonly method: HttpMethod.HttpMethod | \"*\"\n  readonly path: PathInput\n  readonly handler: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>\n  readonly uninterruptible?: boolean | undefined\n  readonly prefix?: Option.Option<string> | undefined\n}): Route<E, Exclude<R, Provided>> =>\n  ({\n    ...options,\n    uninterruptible: options.uninterruptible ?? false,\n    prefix: options.prefix ?? Option.none(),\n    [RouteTypeId]: RouteTypeId\n  }) as Route<E, Exclude<R, Provided>>\n\n/**\n * @since 1.0.0\n * @category Route\n */\nexport const route = <E, R>(\n  method: \"*\" | \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\" | \"OPTIONS\",\n  path: PathInput,\n  handler:\n    | Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>\n    | ((request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>),\n  options?: {\n    readonly uninterruptible?: boolean | undefined\n  }\n): Route<E, Exclude<R, Provided>> =>\n  makeRoute({\n    ...options,\n    method,\n    path,\n    handler: Effect.isEffect(handler) ? handler : Effect.flatMap(HttpServerRequest.HttpServerRequest, handler),\n    uninterruptible: options?.uninterruptible ?? false\n  })\n\n/**\n * @since 1.0.0\n * @category PathInput\n */\nexport type PathInput = `/${string}` | \"*\"\n\nconst removeTrailingSlash = (\n  path: PathInput\n): PathInput => (path.endsWith(\"/\") ? path.slice(0, -1) : path) as any\n\n/**\n * @since 1.0.0\n * @category PathInput\n */\nexport const prefixPath: {\n  (prefix: string): (self: string) => string\n  (self: string, prefix: string): string\n} = dual(2, (self: string, prefix: string) => {\n  prefix = removeTrailingSlash(prefix as PathInput)\n  return self === \"/\" ? prefix : prefix + self\n})\n\n/**\n * @since 1.0.0\n * @category Route\n */\nexport const prefixRoute: {\n  (prefix: string): <E, R>(self: Route<E, R>) => Route<E, R>\n  <E, R>(self: Route<E, R>, prefix: string): Route<E, R>\n} = dual(2, <E, R>(self: Route<E, R>, prefix: string): Route<E, R> =>\n  makeRoute({\n    ...self,\n    path: prefixPath(self.path, prefix) as PathInput,\n    prefix: Option.match(self.prefix, {\n      onNone: () => Option.some(prefix as string),\n      onSome: (existingPrefix) => Option.some(prefixPath(existingPrefix, prefix) as string)\n    })\n  }))\n\n/**\n * Represents a request-level dependency, that needs to be provided by\n * middleware.\n *\n * @since 1.0.0\n * @category Request types\n */\nexport interface Request<Kind extends string, T> {\n  readonly _: unique symbol\n  readonly kind: Kind\n  readonly type: T\n}\n\n/**\n * @since 1.0.0\n * @category Request types\n */\nexport declare namespace Request {\n  /**\n   * @since 1.0.0\n   * @category Request types\n   */\n  export type From<Kind extends string, R> = R extends infer T ? Request<Kind, T> : never\n\n  /**\n   * @since 1.0.0\n   * @category Request types\n   */\n  export type Only<Kind extends string, A> = A extends Request<Kind, infer T> ? T : never\n\n  /**\n   * @since 1.0.0\n   * @category Request types\n   */\n  export type Without<A> = A extends Request<infer _Kind, infer _> ? never : A\n}\n\n/**\n * Services provided by the HTTP router, which are available in the\n * request context.\n *\n * @since 1.0.0\n * @category Request types\n */\nexport type Provided =\n  | HttpServerRequest.HttpServerRequest\n  | Scope.Scope\n  | HttpServerRequest.ParsedSearchParams\n  | RouteContext\n\n/**\n * Services provided to global middleware.\n *\n * @since 1.0.0\n * @category Request types\n */\nexport type GlobalProvided =\n  | HttpServerRequest.HttpServerRequest\n  | Scope.Scope\n\n/**\n * @since 1.0.0\n * @category Middleware\n */\nexport const MiddlewareTypeId: unique symbol = Symbol.for(\"@effect/platform/HttpLayerRouter/Middleware\")\n\n/**\n * @since 1.0.0\n * @category Middleware\n */\nexport type MiddlewareTypeId = typeof MiddlewareTypeId\n\n/**\n * A pseudo-error type that represents an error that should be not handled by\n * the middleware.\n *\n * @since 1.0.0\n * @category Middleware\n */\nexport interface unhandled {\n  readonly _: unique symbol\n}\n\n/**\n * @since 1.0.0\n * @category Middleware\n */\nexport interface Middleware<\n  Config extends {\n    provides: any\n    handles: any\n    error: any\n    requires: any\n    layerError: any\n    layerRequires: any\n  }\n> {\n  readonly [MiddlewareTypeId]: Config\n\n  readonly layer: [Config[\"requires\"]] extends [never] ? Layer.Layer<\n      Request.From<\"Requires\", Config[\"provides\"]>,\n      Config[\"layerError\"],\n      | Config[\"layerRequires\"]\n      | Request.From<\"Requires\", Config[\"requires\"]>\n      | Request.From<\"Error\", Config[\"error\"]>\n    >\n    : \"Need to .combine(middleware) that satisfy the missing request dependencies\"\n\n  readonly combine: <\n    Config2 extends {\n      provides: any\n      handles: any\n      error: any\n      requires: any\n      layerError: any\n      layerRequires: any\n    }\n  >(other: Middleware<Config2>) => Middleware<{\n    provides: Config2[\"provides\"] | Config[\"provides\"]\n    handles: Config2[\"handles\"] | Config[\"handles\"]\n    error: Config2[\"error\"] | Exclude<Config[\"error\"], Config2[\"handles\"]>\n    requires: Exclude<Config[\"requires\"], Config2[\"provides\"]> | Config2[\"requires\"]\n    layerError: Config[\"layerError\"] | Config2[\"layerError\"]\n    layerRequires: Config[\"layerRequires\"] | Config2[\"layerRequires\"]\n  }>\n}\n\n/**\n * Create a middleware layer that can be used to modify requests and responses.\n *\n * By default, the middleware only affects the routes that it is provided to.\n *\n * If you want to create a middleware that applies globally to all routes, pass\n * the `global` option as `true`.\n *\n * ```ts\n * import * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\n * import * as HttpMiddleware from \"@effect/platform/HttpMiddleware\"\n * import * as HttpServerResponse from \"@effect/platform/HttpServerResponse\"\n * import * as Context from \"effect/Context\"\n * import * as Effect from \"effect/Effect\"\n * import * as Layer from \"effect/Layer\"\n *\n * // Here we are defining a CORS middleware\n * const CorsMiddleware = HttpLayerRouter.middleware(HttpMiddleware.cors()).layer\n * // You can also use HttpLayerRouter.cors() to create a CORS middleware\n *\n * class CurrentSession extends Context.Tag(\"CurrentSession\")<CurrentSession, {\n *   readonly token: string\n * }>() {}\n *\n * // You can create middleware that provides a service to the HTTP requests.\n * const SessionMiddleware = HttpLayerRouter.middleware<{\n *   provides: CurrentSession\n * }>()(\n *   Effect.gen(function*() {\n *     yield* Effect.log(\"SessionMiddleware initialized\")\n *\n *     return (httpEffect) =>\n *       Effect.provideService(httpEffect, CurrentSession, {\n *         token: \"dummy-token\"\n *       })\n *   })\n * ).layer\n *\n * Effect.gen(function*() {\n *   const router = yield* HttpLayerRouter.HttpRouter\n *   yield* router.add(\n *     \"GET\",\n *     \"/hello\",\n *     Effect.gen(function*() {\n *       // Requests can now access the current session\n *       const session = yield* CurrentSession\n *       return HttpServerResponse.text(`Hello, World! Your token is ${session.token}`)\n *     })\n *   )\n * }).pipe(\n *   Layer.effectDiscard,\n *   // Provide the SessionMiddleware & CorsMiddleware to some routes\n *   Layer.provide([SessionMiddleware, CorsMiddleware])\n * )\n * ```\n *\n * @since 1.0.0\n * @category Middleware\n */\nexport const middleware:\n  & middleware.Make<never, never>\n  & (<\n    Config extends {\n      provides?: any\n      handles?: any\n    } = {}\n  >() => middleware.Make<\n    Config extends { provides: infer R } ? R : never,\n    Config extends { handles: infer E } ? E : never\n  >) = function() {\n    if (arguments.length === 0) {\n      return makeMiddleware as any\n    }\n    return makeMiddleware(arguments[0], arguments[1]) as any\n  }\n\nconst makeMiddleware = (middleware: any, options?: {\n  readonly global?: boolean | undefined\n}) =>\n  options?.global ?\n    Layer.scopedDiscard(Effect.gen(function*() {\n      const router = yield* HttpRouter\n      const fn = Effect.isEffect(middleware) ? yield* middleware : middleware\n      yield* router.addGlobalMiddleware(fn)\n    }))\n    : new MiddlewareImpl(\n      Effect.isEffect(middleware) ?\n        Layer.scopedContext(Effect.map(middleware, (fn) => Context.unsafeMake(new Map([[fnContextKey, fn]])))) :\n        Layer.succeedContext(Context.unsafeMake(new Map([[fnContextKey, middleware]]))) as any\n    )\n\nlet middlewareId = 0\nconst fnContextKey = \"@effect/platform/HttpLayerRouter/MiddlewareFn\"\n\nclass MiddlewareImpl<\n  Config extends {\n    provides: any\n    handles: any\n    error: any\n    requires: any\n    layerError: any\n    layerRequires: any\n  }\n> implements Middleware<Config> {\n  readonly [MiddlewareTypeId]: Config = {} as any\n\n  constructor(\n    readonly layerFn: Layer.Layer<never>,\n    readonly dependencies?: Layer.Layer<any, any, any>\n  ) {\n    const contextKey = `@effect/platform/HttpLayerRouter/Middleware-${++middlewareId}` as const\n    this.layer = Layer.scopedContext(Effect.gen(this, function*() {\n      const context = yield* Effect.context<Scope.Scope>()\n      const stack = [context.unsafeMap.get(fnContextKey)]\n      if (this.dependencies) {\n        const memoMap = yield* Layer.CurrentMemoMap\n        const scope = Context.get(context, Scope.Scope)\n        const depsContext = yield* Layer.buildWithMemoMap(this.dependencies, memoMap, scope)\n        // eslint-disable-next-line no-restricted-syntax\n        stack.push(...getMiddleware(depsContext))\n      }\n      return Context.unsafeMake<never>(new Map([[contextKey, stack]]))\n    })).pipe(Layer.provide(this.layerFn))\n  }\n\n  layer: any\n\n  combine<\n    Config2 extends {\n      provides: any\n      handles: any\n      error: any\n      requires: any\n      layerError: any\n      layerRequires: any\n    }\n  >(other: Middleware<Config2>): Middleware<any> {\n    return new MiddlewareImpl(\n      this.layerFn,\n      this.dependencies ? Layer.provideMerge(this.dependencies, other.layer as any) : other.layer as any\n    ) as any\n  }\n}\n\nconst middlewareCache = new WeakMap<Context.Context<never>, any>()\nconst getMiddleware = (context: Context.Context<never>): Array<middleware.Fn> => {\n  let arr = middlewareCache.get(context)\n  if (arr) return arr\n  const topLevel = Arr.empty<Array<middleware.Fn>>()\n  let maxLength = 0\n  for (const [key, value] of context.unsafeMap) {\n    if (key.startsWith(\"@effect/platform/HttpLayerRouter/Middleware-\")) {\n      topLevel.push(value)\n      if (value.length > maxLength) {\n        maxLength = value.length\n      }\n    }\n  }\n  if (topLevel.length === 0) {\n    arr = []\n  } else {\n    const middleware = new Set<middleware.Fn>()\n    for (let i = maxLength - 1; i >= 0; i--) {\n      for (const arr of topLevel) {\n        if (i < arr.length) {\n          middleware.add(arr[i])\n        }\n      }\n    }\n    arr = Arr.fromIterable(middleware).reverse()\n  }\n  middlewareCache.set(context, arr)\n  return arr\n}\n\n/**\n * @since 1.0.0\n * @category Middleware\n */\nexport declare namespace middleware {\n  /**\n   * @since 1.0.0\n   * @category Middleware\n   */\n  export type Make<Provides = never, Handles = never> = {\n    <E, R, EX, RX, const Global extends boolean = false>(\n      middleware: Effect.Effect<\n        (\n          effect: Effect.Effect<\n            HttpServerResponse.HttpServerResponse,\n            Types.NoInfer<Handles | unhandled>,\n            Types.NoInfer<Provides>\n          >\n        ) =>\n          & Effect.Effect<\n            HttpServerResponse.HttpServerResponse,\n            E,\n            R\n          >\n          & (unhandled extends E ? unknown : \"You must only handle the configured errors\"),\n        EX,\n        RX\n      >,\n      options?: {\n        readonly global?: Global | undefined\n      }\n    ): Global extends true ? Layer.Layer<\n        | Request.From<\"Requires\", Provides>\n        | Request.From<\"Error\", Handles>\n        | Request.From<\"GlobalRequires\", Provides>\n        | Request.From<\"GlobalError\", Handles>,\n        EX,\n        | HttpRouter\n        | Exclude<RX, Scope.Scope>\n        | Request.From<\"GlobalRequires\", Exclude<R, GlobalProvided>>\n        | Request.From<\"GlobalError\", Exclude<E, unhandled>>\n      > :\n      Middleware<{\n        provides: Provides\n        handles: Handles\n        error: Exclude<E, unhandled>\n        requires: Exclude<R, Provided>\n        layerError: EX\n        layerRequires: Exclude<RX, Scope.Scope>\n      }>\n    <E, R, const Global extends boolean = false>(\n      middleware:\n        & ((\n          effect: Effect.Effect<\n            HttpServerResponse.HttpServerResponse,\n            Types.NoInfer<Handles | unhandled>,\n            Types.NoInfer<Provides>\n          >\n        ) => Effect.Effect<\n          HttpServerResponse.HttpServerResponse,\n          E,\n          R\n        >)\n        & (unhandled extends E ? unknown : \"You must only handle the configured errors\"),\n      options?: {\n        readonly global?: Global | undefined\n      }\n    ): Global extends true ? Layer.Layer<\n        | Request.From<\"Requires\", Provides>\n        | Request.From<\"Error\", Handles>\n        | Request.From<\"GlobalRequires\", Provides>\n        | Request.From<\"GlobalError\", Handles>,\n        never,\n        | HttpRouter\n        | Request.From<\"GlobalRequires\", Exclude<R, GlobalProvided>>\n        | Request.From<\"GlobalError\", Exclude<E, unhandled>>\n      > :\n      Middleware<{\n        provides: Provides\n        handles: Handles\n        error: Exclude<E, unhandled>\n        requires: Exclude<R, Provided>\n        layerError: never\n        layerRequires: never\n      }>\n  }\n\n  /**\n   * @since 1.0.0\n   * @category Middleware\n   */\n  export type Fn = (\n    effect: Effect.Effect<HttpServerResponse.HttpServerResponse>\n  ) => Effect.Effect<HttpServerResponse.HttpServerResponse>\n}\n\n/**\n * A middleware that applies CORS headers to the HTTP response.\n *\n * @since 1.0.0\n * @category Middleware\n */\nexport const cors = (\n  options?: {\n    readonly allowedOrigins?: ReadonlyArray<string> | Predicate.Predicate<string> | undefined\n    readonly allowedMethods?: ReadonlyArray<string> | undefined\n    readonly allowedHeaders?: ReadonlyArray<string> | undefined\n    readonly exposedHeaders?: ReadonlyArray<string> | undefined\n    readonly maxAge?: number | undefined\n    readonly credentials?: boolean | undefined\n  } | undefined\n): Layer.Layer<never, never, HttpRouter> => middleware(HttpMiddleware.cors(options), { global: true })\n\n/**\n * A middleware that disables the logger for some routes.\n *\n * ```ts\n * import * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\n * import * as HttpServerResponse from \"@effect/platform/HttpServerResponse\"\n * import * as Layer from \"effect/Layer\"\n *\n * const Route = HttpLayerRouter.add(\"GET\", \"/hello\", HttpServerResponse.text(\"Hello, World!\")).pipe(\n *   // disable the logger for this route\n *   Layer.provide(HttpLayerRouter.disableLogger)\n * )\n * ```\n *\n * @since 1.0.0\n * @category Middleware\n */\nexport const disableLogger: Layer.Layer<never> = middleware(HttpMiddleware.withLoggerDisabled).layer\n\n/**\n * ```ts\n * import * as NodeHttpServer from \"@effect/platform-node/NodeHttpServer\"\n * import * as NodeRuntime from \"@effect/platform-node/NodeRuntime\"\n * import * as HttpApi from \"@effect/platform/HttpApi\"\n * import * as HttpApiBuilder from \"@effect/platform/HttpApiBuilder\"\n * import * as HttpApiEndpoint from \"@effect/platform/HttpApiEndpoint\"\n * import * as HttpApiGroup from \"@effect/platform/HttpApiGroup\"\n * import * as HttpApiScalar from \"@effect/platform/HttpApiScalar\"\n * import * as HttpLayerRouter from \"@effect/platform/HttpLayerRouter\"\n * import * as HttpMiddleware from \"@effect/platform/HttpMiddleware\"\n * import * as Effect from \"effect/Effect\"\n * import * as Layer from \"effect/Layer\"\n * import { createServer } from \"http\"\n *\n * // First, we define our HttpApi\n * class MyApi extends HttpApi.make(\"api\").add(\n *   HttpApiGroup.make(\"users\").add(\n *     HttpApiEndpoint.get(\"me\", \"/me\")\n *   ).prefix(\"/users\")\n * ) {}\n *\n * // Implement the handlers for the API\n * const UsersApiLayer = HttpApiBuilder.group(MyApi, \"users\", (handers) => handers.handle(\"me\", () => Effect.void))\n *\n * // Use `HttpLayerRouter.addHttpApi` to register the API with the router\n * const HttpApiRoutes = HttpLayerRouter.addHttpApi(MyApi, {\n *   openapiPath: \"/docs/openapi.json\"\n * }).pipe(\n *   // Provide the api handlers layer\n *   Layer.provide(UsersApiLayer)\n * )\n *\n * // Create a /docs route for the API documentation\n * const DocsRoute = HttpApiScalar.layerHttpLayerRouter({\n *   api: MyApi,\n *   path: \"/docs\"\n * })\n *\n * const CorsMiddleware = HttpLayerRouter.middleware(HttpMiddleware.cors())\n * // You can also use HttpLayerRouter.cors() to create a CORS middleware\n *\n * // Finally, we merge all routes and serve them using the Node HTTP server\n * const AllRoutes = Layer.mergeAll(\n *   HttpApiRoutes,\n *   DocsRoute\n * ).pipe(\n *   Layer.provide(CorsMiddleware.layer)\n * )\n *\n * HttpLayerRouter.serve(AllRoutes).pipe(\n *   Layer.provide(NodeHttpServer.layer(createServer, { port: 3000 })),\n *   Layer.launch,\n *   NodeRuntime.runMain\n * )\n * ```\n *\n * @since 1.0.0\n * @category HttpApi\n */\nexport const addHttpApi = <Id extends string, Groups extends HttpApiGroup.HttpApiGroup.Any, E, R>(\n  api: HttpApi.HttpApi<Id, Groups, E, R>,\n  options?: {\n    readonly openapiPath?: `/${string}` | undefined\n  }\n): Layer.Layer<\n  never,\n  never,\n  | Etag.Generator\n  | HttpRouter\n  | FileSystem\n  | HttpPlatform\n  | Path\n  | R\n  | HttpApiGroup.HttpApiGroup.ToService<Id, Groups>\n  | HttpApiGroup.HttpApiGroup.ErrorContext<Groups>\n> => {\n  const ApiMiddleware = middleware(HttpApiBuilder.buildMiddleware(api)).layer as Layer.Layer<never>\n  return HttpApiBuilder.Router.unwrap(Effect.fnUntraced(function*(router_) {\n    const router = yield* HttpRouter\n    let existing = existingRoutesMap.get(router)\n    if (!existing) {\n      existing = new Set()\n      existingRoutesMap.set(router, existing)\n    }\n    const context = yield* Effect.context<\n      | Etag.Generator\n      | HttpRouter\n      | FileSystem\n      | HttpPlatform\n      | Path\n    >()\n    const routes = Arr.empty<Route<any, any>>()\n    for (const route of router_.routes) {\n      if (existing.has(route)) {\n        continue\n      }\n      existing.add(route)\n      routes.push(makeRoute({\n        ...route as any,\n        handler: Effect.provide(route.handler, context)\n      }))\n    }\n\n    yield* (router.addAll(routes) as Effect.Effect<void>)\n\n    if (options?.openapiPath) {\n      const spec = OpenApi.fromApi(api)\n      yield* router.add(\"GET\", options.openapiPath, Effect.succeed(HttpServerResponse.unsafeJson(spec)))\n    }\n  }, Layer.effectDiscard)).pipe(\n    Layer.provide(ApiMiddleware)\n  )\n}\n\nconst existingRoutesMap = new WeakMap<HttpRouter, Set<any>>()\n\n/**\n * Serves the provided application layer as an HTTP server.\n *\n * @since 1.0.0\n * @category Server\n */\nexport const serve = <A, E, R, HE, HR = Request.Only<\"Requires\", R> | Request.Only<\"GlobalRequires\", R>>(\n  appLayer: Layer.Layer<A, E, R>,\n  options?: {\n    readonly routerConfig?: Partial<FindMyWay.RouterConfig> | undefined\n    readonly disableLogger?: boolean | undefined\n    readonly disableListenLog?: boolean\n    /**\n     * Middleware to apply to the HTTP server.\n     *\n     * NOTE: This middleware is applied to the entire HTTP server chain,\n     * including the sending of the response. This means that modifications\n     * to the response **WILL NOT** be reflected in the final response sent to the\n     * client.\n     *\n     * Use HttpLayerRouter.middleware to create middleware that can modify the\n     * response.\n     */\n    readonly middleware?: (\n      effect: Effect.Effect<\n        HttpServerResponse.HttpServerResponse,\n        Request.Only<\"Error\", R> | Request.Only<\"GlobalError\", R> | HttpServerError.RouteNotFound,\n        | Scope.Scope\n        | HttpServerRequest.HttpServerRequest\n        | Request.Only<\"Requires\", R>\n        | Request.Only<\"GlobalRequires\", R>\n      >\n    ) => Effect.Effect<HttpServerResponse.HttpServerResponse, HE, HR>\n  }\n): Layer.Layer<\n  A,\n  Request.Without<E>,\n  HttpServer.HttpServer | Exclude<Request.Without<R> | Exclude<HR, GlobalProvided>, HttpRouter>\n> => {\n  let middleware: any = options?.middleware\n  if (options?.disableLogger !== true) {\n    middleware = middleware ? compose(middleware, HttpMiddleware.logger) : HttpMiddleware.logger\n  }\n  const RouterLayer = options?.routerConfig\n    ? Layer.provide(layer, Layer.succeed(RouterConfig, options.routerConfig))\n    : layer\n  return Effect.gen(function*() {\n    const router = yield* HttpRouter\n    const handler = router.asHttpEffect()\n    return middleware ? HttpServer.serve(handler, middleware) : HttpServer.serve(handler)\n  }).pipe(\n    Layer.unwrapScoped,\n    Layer.provideMerge(appLayer),\n    Layer.provide(RouterLayer),\n    options?.disableListenLog ? identity : HttpServer.withLogAddress\n  ) as any\n}\n\n/**\n * @since 1.0.0\n * @category Server\n */\nexport const toWebHandler = <\n  A,\n  E,\n  R extends\n    | HttpRouter\n    | Request<\"Requires\", any>\n    | Request<\"GlobalRequires\", any>\n    | Request<\"Error\", any>\n    | Request<\"GlobalError\", any>,\n  HE,\n  HR = Exclude<Request.Only<\"Requires\", R> | Request.Only<\"GlobalRequires\", R>, A>\n>(\n  appLayer: Layer.Layer<A, E, R>,\n  options?: {\n    readonly memoMap?: Layer.MemoMap | undefined\n    readonly routerConfig?: Partial<FindMyWay.RouterConfig> | undefined\n    readonly disableLogger?: boolean | undefined\n    /**\n     * Middleware to apply to the HTTP server.\n     *\n     * NOTE: This middleware is applied to the entire HTTP server chain,\n     * including the sending of the response. This means that modifications\n     * to the response **WILL NOT** be reflected in the final response sent to the\n     * client.\n     *\n     * Use HttpLayerRouter.middleware to create middleware that can modify the\n     * response.\n     */\n    readonly middleware?: (\n      effect: Effect.Effect<\n        HttpServerResponse.HttpServerResponse,\n        Request.Only<\"Error\", R> | Request.Only<\"GlobalError\", R> | HttpServerError.RouteNotFound,\n        | Scope.Scope\n        | HttpServerRequest.HttpServerRequest\n        | Request.Only<\"Requires\", R>\n        | Request.Only<\"GlobalRequires\", R>\n      >\n    ) => Effect.Effect<HttpServerResponse.HttpServerResponse, HE, HR>\n  }\n): {\n  readonly handler: [HR] extends [never]\n    ? ((request: globalThis.Request, context?: Context.Context<never> | undefined) => Promise<Response>)\n    : ((request: globalThis.Request, context: Context.Context<HR>) => Promise<Response>)\n  readonly dispose: () => Promise<void>\n} => {\n  let middleware: any = options?.middleware\n  if (options?.disableLogger !== true) {\n    middleware = middleware ? compose(middleware, HttpMiddleware.logger) : HttpMiddleware.logger\n  }\n  const RouterLayer: Layer.Layer<HttpRouter | A, E> = Layer.provideMerge(\n    appLayer,\n    options?.routerConfig\n      ? Layer.provide(layer, Layer.succeed(RouterConfig, options.routerConfig))\n      : layer\n  ) as any\n  return HttpApp.toWebHandlerLayerWith(RouterLayer, {\n    toHandler: (r) => Effect.succeed(Context.get(r.context, HttpRouter).asHttpEffect()),\n    middleware,\n    memoMap: options?.memoMap\n  })\n}\n"
  },
  {
    "path": "packages/platform/src/HttpMultiplex.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Effect from \"effect/Effect\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport type * as App from \"./HttpApp.js\"\nimport type * as Error from \"./HttpServerError.js\"\nimport type * as ServerRequest from \"./HttpServerRequest.js\"\nimport * as internal from \"./internal/httpMultiplex.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HttpMultiplex<E = never, R = never> extends App.Default<E | Error.RouteNotFound, R>, Inspectable {\n  readonly [TypeId]: TypeId\n  readonly apps: ReadonlyArray<\n    readonly [\n      predicate: (request: ServerRequest.HttpServerRequest) => Effect.Effect<boolean, E, R>,\n      app: App.Default<E, R>\n    ]\n  >\n}\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: HttpMultiplex<never> = internal.empty\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const make: <E, R>(\n  apps: Iterable<\n    readonly [\n      predicate: (request: ServerRequest.HttpServerRequest) => Effect.Effect<boolean, E, R>,\n      app: App.Default<E, R>\n    ]\n  >\n) => HttpMultiplex<E, R> = internal.make\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const add: {\n  <E2, R2, E3, R3>(\n    predicate: (request: ServerRequest.HttpServerRequest) => Effect.Effect<boolean, E2, R2>,\n    app: App.Default<E3, R3>\n  ): <E, R>(self: HttpMultiplex<E, R>) => HttpMultiplex<E2 | E3 | E, R2 | R3 | R>\n  <E, R, E2, R2, E3, R3>(\n    self: HttpMultiplex<E, R>,\n    predicate: (request: ServerRequest.HttpServerRequest) => Effect.Effect<boolean, E2, R2>,\n    app: App.Default<E3, R3>\n  ): HttpMultiplex<E | E2 | E3, R | R2 | R3>\n} = internal.add\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const headerExact: {\n  <E2, R2>(\n    header: string,\n    value: string,\n    app: App.Default<E2, R2>\n  ): <E, R>(self: HttpMultiplex<E, R>) => HttpMultiplex<E2 | E, R2 | R>\n  <E, R, E2, R2>(\n    self: HttpMultiplex<E, R>,\n    header: string,\n    value: string,\n    app: App.Default<E2, R2>\n  ): HttpMultiplex<E | E2, R | R2>\n} = internal.headerExact\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const headerRegex: {\n  <E2, R2>(\n    header: string,\n    regex: RegExp,\n    app: App.Default<E2, R2>\n  ): <E, R>(self: HttpMultiplex<E, R>) => HttpMultiplex<E2 | E, R2 | R>\n  <E, R, E2, R2>(\n    self: HttpMultiplex<E, R>,\n    header: string,\n    regex: RegExp,\n    app: App.Default<E2, R2>\n  ): HttpMultiplex<E | E2, R | R2>\n} = internal.headerRegex\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const headerStartsWith: {\n  <E2, R2>(\n    header: string,\n    prefix: string,\n    app: App.Default<E2, R2>\n  ): <E, R>(self: HttpMultiplex<E, R>) => HttpMultiplex<E2 | E, R2 | R>\n  <E, R, E2, R2>(\n    self: HttpMultiplex<E, R>,\n    header: string,\n    prefix: string,\n    app: App.Default<E2, R2>\n  ): HttpMultiplex<E | E2, R | R2>\n} = internal.headerStartsWith\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const headerEndsWith: {\n  <E2, R2>(\n    header: string,\n    suffix: string,\n    app: App.Default<E2, R2>\n  ): <E, R>(self: HttpMultiplex<E, R>) => HttpMultiplex<E2 | E, R2 | R>\n  <E, R, E2, R2>(\n    self: HttpMultiplex<E, R>,\n    header: string,\n    suffix: string,\n    app: App.Default<E2, R2>\n  ): HttpMultiplex<E | E2, R | R2>\n} = internal.headerEndsWith\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const hostExact: {\n  <E2, R2>(host: string, app: App.Default<E2, R2>): <E, R>(self: HttpMultiplex<E, R>) => HttpMultiplex<E2 | E, R2 | R>\n  <E, R, E2, R2>(self: HttpMultiplex<E, R>, host: string, app: App.Default<E2, R2>): HttpMultiplex<E | E2, R | R2>\n} = internal.hostExact\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const hostRegex: {\n  <E2, R2>(regex: RegExp, app: App.Default<E2, R2>): <E, R>(self: HttpMultiplex<E, R>) => HttpMultiplex<E2 | E, R2 | R>\n  <E, R, E2, R2>(self: HttpMultiplex<E, R>, regex: RegExp, app: App.Default<E2, R2>): HttpMultiplex<E | E2, R | R2>\n} = internal.hostRegex\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const hostStartsWith: {\n  <E2, R2>(prefix: string, app: App.Default<E2, R2>): <E, R>(self: HttpMultiplex<E, R>) => HttpMultiplex<E2 | E, R2 | R>\n  <E, R, E2, R2>(self: HttpMultiplex<E, R>, prefix: string, app: App.Default<E2, R2>): HttpMultiplex<E | E2, R | R2>\n} = internal.hostStartsWith\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const hostEndsWith: {\n  <E2, R2>(suffix: string, app: App.Default<E2, R2>): <E, R>(self: HttpMultiplex<E, R>) => HttpMultiplex<E2 | E, R2 | R>\n  <E, R, E2, R2>(self: HttpMultiplex<E, R>, suffix: string, app: App.Default<E2, R2>): HttpMultiplex<E | E2, R | R2>\n} = internal.hostEndsWith\n"
  },
  {
    "path": "packages/platform/src/HttpRouter.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Cause from \"effect/Cause\"\nimport type * as Chunk from \"effect/Chunk\"\nimport type * as Context from \"effect/Context\"\nimport type * as Effect from \"effect/Effect\"\nimport type { FiberRef } from \"effect/FiberRef\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport type * as Layer from \"effect/Layer\"\nimport type * as Option from \"effect/Option\"\nimport type * as ParseResult from \"effect/ParseResult\"\nimport type * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport type * as Scope from \"effect/Scope\"\nimport type { RouterConfig } from \"find-my-way-ts\"\nimport type * as Etag from \"./Etag.js\"\nimport type { FileSystem } from \"./FileSystem.js\"\nimport type * as App from \"./HttpApp.js\"\nimport type * as Method from \"./HttpMethod.js\"\nimport type * as Middleware from \"./HttpMiddleware.js\"\nimport type * as Platform from \"./HttpPlatform.js\"\nimport type * as HttpServer from \"./HttpServer.js\"\nimport type * as Error from \"./HttpServerError.js\"\nimport type * as ServerRequest from \"./HttpServerRequest.js\"\nimport type * as Respondable from \"./HttpServerRespondable.js\"\nimport type * as ServerResponse from \"./HttpServerResponse.js\"\nimport * as internal from \"./internal/httpRouter.js\"\nimport type { Path } from \"./Path.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = internal.TypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HttpRouter<E = never, R = never>\n  extends App.Default<E | Error.RouteNotFound, Exclude<R, RouteContext>>, Inspectable\n{\n  readonly [TypeId]: TypeId\n  readonly routes: Chunk.Chunk<Route<E, R>>\n  readonly mounts: Chunk.Chunk<\n    readonly [\n      prefix: string,\n      httpApp: App.Default<E, R>,\n      options?: { readonly includePrefix?: boolean | undefined } | undefined\n    ]\n  >\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace HttpRouter {\n  /**\n   * @since 1.0.0\n   */\n  export type Provided = RouteContext | ServerRequest.HttpServerRequest | ServerRequest.ParsedSearchParams | Scope.Scope\n\n  /**\n   * @since 1.0.0\n   */\n  export type ExcludeProvided<A> = Exclude<A, Provided>\n\n  /**\n   * @since 1.0.0\n   */\n  export interface Service<E, R> {\n    readonly router: Effect.Effect<HttpRouter<E, R>>\n    readonly addRoute: (route: Route<E, R>) => Effect.Effect<void>\n    readonly all: (\n      path: PathInput,\n      handler: Route.Handler<E, R | Provided>,\n      options?: { readonly uninterruptible?: boolean | undefined } | undefined\n    ) => Effect.Effect<void>\n    readonly get: (\n      path: PathInput,\n      handler: Route.Handler<E, R | Provided>,\n      options?: { readonly uninterruptible?: boolean | undefined } | undefined\n    ) => Effect.Effect<void>\n    readonly post: (\n      path: PathInput,\n      handler: Route.Handler<E, R | Provided>,\n      options?: { readonly uninterruptible?: boolean | undefined } | undefined\n    ) => Effect.Effect<void>\n    readonly put: (\n      path: PathInput,\n      handler: Route.Handler<E, R | Provided>,\n      options?: { readonly uninterruptible?: boolean | undefined } | undefined\n    ) => Effect.Effect<void>\n    readonly patch: (\n      path: PathInput,\n      handler: Route.Handler<E, R | Provided>,\n      options?: { readonly uninterruptible?: boolean | undefined } | undefined\n    ) => Effect.Effect<void>\n    readonly del: (\n      path: PathInput,\n      handler: Route.Handler<E, R | Provided>,\n      options?: { readonly uninterruptible?: boolean | undefined } | undefined\n    ) => Effect.Effect<void>\n    readonly head: (\n      path: PathInput,\n      handler: Route.Handler<E, R | Provided>,\n      options?: { readonly uninterruptible?: boolean | undefined } | undefined\n    ) => Effect.Effect<void>\n    readonly options: (\n      path: PathInput,\n      handler: Route.Handler<E, R | Provided>,\n      options?: { readonly uninterruptible?: boolean | undefined } | undefined\n    ) => Effect.Effect<void>\n    readonly mount: (\n      path: `/${string}`,\n      router: HttpRouter<E, R>\n    ) => Effect.Effect<void>\n    readonly mountApp: (\n      path: `/${string}`,\n      router: App.Default<E, R>,\n      options?: { readonly includePrefix?: boolean | undefined } | undefined\n    ) => Effect.Effect<void>\n    readonly concat: (router: HttpRouter<E, R>) => Effect.Effect<void>\n  }\n\n  /**\n   * @since 1.0.0\n   */\n  export type DefaultServices = Platform.HttpPlatform | Etag.Generator | FileSystem | Path\n\n  /**\n   * @since 1.0.0\n   */\n  export interface TagClass<Self, Name extends string, E, R> extends Context.Tag<Self, Service<E, R>> {\n    new(_: never): Context.TagClassShape<Name, Service<E, R>>\n    readonly Live: Layer.Layer<Self>\n    readonly router: Effect.Effect<HttpRouter<E, R>, never, Self>\n    readonly use: <XA, XE, XR>(\n      f: (router: Service<E, R>) => Effect.Effect<XA, XE, XR>\n    ) => Layer.Layer<never, XE, Exclude<XR, Scope.Scope>>\n    readonly unwrap: <XA, XE, XR>(f: (router: HttpRouter<E, R>) => Layer.Layer<XA, XE, XR>) => Layer.Layer<XA, XE, XR>\n    readonly serve: <E = never, R = never>(\n      middleware?: Middleware.HttpMiddleware.Applied<App.Default, E, R>\n    ) => Layer.Layer<\n      never,\n      never,\n      HttpServer.HttpServer | Exclude<R, ServerRequest.HttpServerRequest | Scope.Scope>\n    >\n  }\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const RouteTypeId: unique symbol = internal.RouteTypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type RouteTypeId = typeof RouteTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport type PathInput = `/${string}` | \"*\"\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Route<E = never, R = never> extends Inspectable {\n  readonly [RouteTypeId]: RouteTypeId\n  readonly method: Method.HttpMethod | \"*\"\n  readonly path: PathInput\n  readonly handler: Route.Handler<E, R>\n  readonly prefix: Option.Option<string>\n  readonly uninterruptible: boolean\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Route {\n  /**\n   * @since 1.0.0\n   */\n  export type Handler<E, R> = App.HttpApp<\n    Respondable.Respondable,\n    E,\n    R | RouteContext | ServerRequest.ParsedSearchParams\n  >\n\n  /**\n   * @since 1.0.0\n   */\n  export type Middleware<E, R> = App.HttpApp<\n    ServerResponse.HttpServerResponse,\n    E,\n    R | RouteContext | ServerRequest.ParsedSearchParams\n  >\n}\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const RouteContextTypeId: unique symbol = internal.RouteContextTypeId\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type RouteContextTypeId = typeof RouteContextTypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface RouteContext {\n  readonly [RouteContextTypeId]: RouteContextTypeId\n  readonly params: Readonly<Record<string, string | undefined>>\n  readonly route: Route<unknown, unknown>\n}\n\n/**\n * @since 1.0.0\n * @category route context\n */\nexport const RouteContext: Context.Tag<RouteContext, RouteContext> = internal.RouteContext\n\n/**\n * @since 1.0.0\n * @category route context\n */\nexport const params: Effect.Effect<\n  Readonly<Record<string, string | undefined>>,\n  never,\n  RouteContext\n> = internal.params\n\n/**\n * @since 1.0.0\n * @category route context\n */\nexport const schemaJson: <\n  R,\n  I extends Partial<{\n    readonly method: Method.HttpMethod\n    readonly url: string\n    readonly cookies: Readonly<Record<string, string | undefined>>\n    readonly headers: Readonly<Record<string, string | undefined>>\n    readonly pathParams: Readonly<Record<string, string | undefined>>\n    readonly searchParams: Readonly<Record<string, string | ReadonlyArray<string> | undefined>>\n    readonly body: any\n  }>,\n  A\n>(\n  schema: Schema.Schema<A, I, R>,\n  options?: ParseOptions | undefined\n) => Effect.Effect<\n  A,\n  Error.RequestError | ParseResult.ParseError,\n  RouteContext | R | ServerRequest.HttpServerRequest | ServerRequest.ParsedSearchParams\n> = internal.schemaJson\n\n/**\n * @since 1.0.0\n * @category route context\n */\nexport const schemaNoBody: <\n  R,\n  I extends Partial<\n    {\n      readonly method: Method.HttpMethod\n      readonly url: string\n      readonly cookies: Readonly<Record<string, string | undefined>>\n      readonly headers: Readonly<Record<string, string | undefined>>\n      readonly pathParams: Readonly<Record<string, string | undefined>>\n      readonly searchParams: Readonly<Record<string, string | ReadonlyArray<string> | undefined>>\n    }\n  >,\n  A\n>(\n  schema: Schema.Schema<A, I, R>,\n  options?: ParseOptions | undefined\n) => Effect.Effect<\n  A,\n  ParseResult.ParseError,\n  R | RouteContext | ServerRequest.HttpServerRequest | ServerRequest.ParsedSearchParams\n> = internal.schemaNoBody\n\n/**\n * @since 1.0.0\n * @category route context\n */\nexport const schemaParams: <A, I extends Readonly<Record<string, string | ReadonlyArray<string> | undefined>>, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: ParseOptions | undefined\n) => Effect.Effect<A, ParseResult.ParseError, R | RouteContext | ServerRequest.ParsedSearchParams> =\n  internal.schemaParams\n\n/**\n * @since 1.0.0\n * @category route context\n */\nexport const schemaPathParams: <A, I extends Readonly<Record<string, string | undefined>>, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: ParseOptions | undefined\n) => Effect.Effect<A, ParseResult.ParseError, R | RouteContext> = internal.schemaPathParams\n\n/**\n * @since 1.0.0\n * @category router config\n */\nexport const currentRouterConfig: FiberRef<Partial<RouterConfig>> = internal.currentRouterConfig\n\n/**\n * @since 1.0.0\n * @category router config\n */\nexport const withRouterConfig: {\n  (config: Partial<RouterConfig>): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>\n  <A, E, R>(effect: Effect.Effect<A, E, R>, config: Partial<RouterConfig>): Effect.Effect<A, E, R>\n} = internal.withRouterConfig\n\n/**\n * @since 1.0.0\n * @category router config\n */\nexport const setRouterConfig: (config: Partial<RouterConfig>) => Layer.Layer<never> = internal.setRouterConfig\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: HttpRouter = internal.empty\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fromIterable: <R extends Route<any, any>>(\n  routes: Iterable<R>\n) => HttpRouter<R extends Route<infer E, infer _> ? E : never, R extends Route<infer _, infer Env> ? Env : never> =\n  internal.fromIterable\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const makeRoute: <E, R>(\n  method: Method.HttpMethod | \"*\",\n  path: PathInput,\n  handler: Route.Handler<E, R>,\n  options?: { readonly prefix?: string | undefined; readonly uninterruptible?: boolean | undefined } | undefined\n) => Route<E, HttpRouter.ExcludeProvided<R>> = internal.makeRoute\n\n/**\n * @since 1.0.0\n * @category utils\n */\nexport const prefixPath: {\n  (prefix: string): (self: string) => string\n  (self: string, prefix: string): string\n} = internal.prefixPath\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const prefixAll: {\n  (prefix: PathInput): <E, R>(self: HttpRouter<E, R>) => HttpRouter<E, R>\n  <E, R>(self: HttpRouter<E, R>, prefix: PathInput): HttpRouter<E, R>\n} = internal.prefixAll\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const append: {\n  <R1, E1>(\n    route: Route<E1, R1>\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<\n    E1 | E,\n    R | HttpRouter.ExcludeProvided<R1>\n  >\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    route: Route<E1, R1>\n  ): HttpRouter<\n    E | E1,\n    R | HttpRouter.ExcludeProvided<R1>\n  >\n} = internal.append\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const concat: {\n  <R1, E1>(that: HttpRouter<E1, R1>): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<E1 | E, R1 | R>\n  <E, R, R1, E1>(self: HttpRouter<E, R>, that: HttpRouter<E1, R1>): HttpRouter<\n    E | E1,\n    R | R1\n  >\n} = internal.concat\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const concatAll: <Routers extends ReadonlyArray<HttpRouter<unknown, unknown>>>(\n  ...routers: Routers\n) => [Routers[number]] extends [HttpRouter<infer E, infer R>] ? HttpRouter<E, R> : never = internal.concatAll\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const mount: {\n  <R1, E1>(path: `/${string}`, that: HttpRouter<E1, R1>): <E, R>(self: HttpRouter<E, R>) => HttpRouter<E1 | E, R1 | R>\n  <E, R, E1, R1>(self: HttpRouter<E, R>, path: `/${string}`, that: HttpRouter<E1, R1>): HttpRouter<E | E1, R | R1>\n} = internal.mount\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const mountApp: {\n  <R1, E1>(\n    path: `/${string}`,\n    that: App.Default<E1, R1>,\n    options?: { readonly includePrefix?: boolean | undefined } | undefined\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<\n    E1 | E,\n    | HttpRouter.ExcludeProvided<R1>\n    | HttpRouter.ExcludeProvided<R>\n  >\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    path: `/${string}`,\n    that: App.Default<E1, R1>,\n    options?: { readonly includePrefix?: boolean | undefined } | undefined\n  ): HttpRouter<\n    E | E1,\n    | HttpRouter.ExcludeProvided<R>\n    | HttpRouter.ExcludeProvided<R1>\n  >\n} = internal.mountApp\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const route: (\n  method: Method.HttpMethod | \"*\"\n) => {\n  <R1, E1>(\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<E1 | E, R | Exclude<R1, ServerRequest.HttpServerRequest | RouteContext | Scope.Scope>>\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): HttpRouter<E | E1, R | Exclude<R1, ServerRequest.HttpServerRequest | RouteContext | Scope.Scope>>\n} = internal.route\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const all: {\n  <R1, E1>(\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<\n    E1 | E,\n    R | HttpRouter.ExcludeProvided<R1>\n  >\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): HttpRouter<\n    E | E1,\n    R | HttpRouter.ExcludeProvided<R1>\n  >\n} = internal.all\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const get: {\n  <R1, E1>(\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<E1 | E, R | HttpRouter.ExcludeProvided<R1>>\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): HttpRouter<E | E1, R | HttpRouter.ExcludeProvided<R1>>\n} = internal.get\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const post: {\n  <R1, E1>(\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<E1 | E, R | HttpRouter.ExcludeProvided<R1>>\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): HttpRouter<E | E1, R | HttpRouter.ExcludeProvided<R1>>\n} = internal.post\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const patch: {\n  <R1, E1>(\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<E1 | E, R | HttpRouter.ExcludeProvided<R1>>\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): HttpRouter<E | E1, R | HttpRouter.ExcludeProvided<R1>>\n} = internal.patch\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const put: {\n  <R1, E1>(\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<E1 | E, R | HttpRouter.ExcludeProvided<R1>>\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): HttpRouter<E | E1, R | HttpRouter.ExcludeProvided<R1>>\n} = internal.put\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const del: {\n  <R1, E1>(\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<E1 | E, R | HttpRouter.ExcludeProvided<R1>>\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): HttpRouter<E | E1, R | HttpRouter.ExcludeProvided<R1>>\n} = internal.del\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const head: {\n  <R1, E1>(\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<E1 | E, R | HttpRouter.ExcludeProvided<R1>>\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): HttpRouter<E | E1, R | HttpRouter.ExcludeProvided<R1>>\n} = internal.head\n\n/**\n * @since 1.0.0\n * @category routing\n */\nexport const options: {\n  <R1, E1>(\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<E1 | E, R | HttpRouter.ExcludeProvided<R1>>\n  <E, R, E1, R1>(\n    self: HttpRouter<E, R>,\n    path: PathInput,\n    handler: Route.Handler<E1, R1>,\n    options?: { readonly uninterruptible?: boolean | undefined } | undefined\n  ): HttpRouter<E | E1, R | HttpRouter.ExcludeProvided<R1>>\n} = internal.options\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const use: {\n  <E, R, R1, E1>(\n    f: (self: Route.Middleware<E, R>) => App.Default<E1, R1>\n  ): (self: HttpRouter<E, R>) => HttpRouter<E1, HttpRouter.ExcludeProvided<R1>>\n  <E, R, R1, E1>(\n    self: HttpRouter<E, R>,\n    f: (self: Route.Middleware<E, R>) => App.Default<E1, R1>\n  ): HttpRouter<E1, HttpRouter.ExcludeProvided<R1>>\n} = internal.use\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const transform: {\n  <E, R, R1, E1>(\n    f: (self: Route.Handler<E, R>) => App.HttpApp<Respondable.Respondable, E1, R1>\n  ): (self: HttpRouter<E, R>) => HttpRouter<E1, HttpRouter.ExcludeProvided<R1>>\n  <E, R, R1, E1>(\n    self: HttpRouter<E, R>,\n    f: (self: Route.Handler<E, R>) => App.HttpApp<Respondable.Respondable, E1, R1>\n  ): HttpRouter<E1, HttpRouter.ExcludeProvided<R1>>\n} = internal.transform\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const catchAll: {\n  <E, E2, R2>(\n    f: (e: E) => Route.Handler<E2, R2>\n  ): <R>(self: HttpRouter<E, R>) => HttpRouter<E2, R | HttpRouter.ExcludeProvided<R2>>\n  <E, R, E2, R2>(\n    self: HttpRouter<E, R>,\n    f: (e: E) => Route.Handler<E2, R2>\n  ): HttpRouter<E2, R | HttpRouter.ExcludeProvided<R2>>\n} = internal.catchAll\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const catchAllCause: {\n  <E, E2, R2>(\n    f: (e: Cause.Cause<E>) => Route.Handler<E2, R2>\n  ): <R>(self: HttpRouter<E, R>) => HttpRouter<E2, R | HttpRouter.ExcludeProvided<R2>>\n  <E, R, E2, R2>(\n    self: HttpRouter<E, R>,\n    f: (e: Cause.Cause<E>) => Route.Handler<E2, R2>\n  ): HttpRouter<E2, R | HttpRouter.ExcludeProvided<R2>>\n} = internal.catchAllCause\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const catchTag: {\n  <K extends E extends { _tag: string } ? E[\"_tag\"] : never, E, E1, R1>(\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Route.Handler<E1, R1>\n  ): <R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<E1 | Exclude<E, { _tag: K }>, R | HttpRouter.ExcludeProvided<R1>>\n  <E, R, K extends E extends { _tag: string } ? E[\"_tag\"] : never, E1, R1>(\n    self: HttpRouter<E, R>,\n    k: K,\n    f: (e: Extract<E, { _tag: K }>) => Route.Handler<E1, R1>\n  ): HttpRouter<E1 | Exclude<E, { _tag: K }>, R | HttpRouter.ExcludeProvided<R1>>\n} = internal.catchTag\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const catchTags: {\n  <\n    E,\n    Cases extends E extends { _tag: string }\n      ? { [K in E[\"_tag\"]]+?: ((error: Extract<E, { _tag: K }>) => Route.Handler<any, any>) | undefined }\n      : {}\n  >(\n    cases: Cases\n  ): <R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect.Effect<any, infer E, any> ? E : never\n    }[keyof Cases],\n    | R\n    | HttpRouter.ExcludeProvided<\n      {\n        [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect.Effect<any, any, infer R> ? R : never\n      }[keyof Cases]\n    >\n  >\n  <\n    R,\n    E,\n    Cases extends E extends { _tag: string }\n      ? { [K in E[\"_tag\"]]+?: ((error: Extract<E, { _tag: K }>) => Route.Handler<any, any>) | undefined } :\n      {}\n  >(\n    self: HttpRouter<E, R>,\n    cases: Cases\n  ): HttpRouter<\n    | Exclude<E, { _tag: keyof Cases }>\n    | {\n      [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect.Effect<any, infer E, any> ? E : never\n    }[keyof Cases],\n    | R\n    | HttpRouter.ExcludeProvided<\n      {\n        [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect.Effect<any, any, infer R> ? R : never\n      }[keyof Cases]\n    >\n  >\n} = internal.catchTags\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const provideService: {\n  <T extends Context.Tag<any, any>>(\n    tag: T,\n    service: Context.Tag.Service<T>\n  ): <E, R>(self: HttpRouter<E, R>) => HttpRouter<E, Exclude<R, Context.Tag.Identifier<T>>>\n  <E, R, T extends Context.Tag<any, any>>(\n    self: HttpRouter<E, R>,\n    tag: T,\n    service: Context.Tag.Service<T>\n  ): HttpRouter<E, Exclude<R, Context.Tag.Identifier<T>>>\n} = internal.provideService\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const provideServiceEffect: {\n  <T extends Context.Tag<any, any>, R1, E1>(\n    tag: T,\n    effect: Effect.Effect<Context.Tag.Service<T>, E1, R1>\n  ): <E, R>(\n    self: HttpRouter<E, R>\n  ) => HttpRouter<\n    E1 | E,\n    | Exclude<R, Context.Tag.Identifier<T>>\n    | Exclude<HttpRouter.ExcludeProvided<R1>, Context.Tag.Identifier<T>>\n  >\n  <E, R, T extends Context.Tag<any, any>, R1, E1>(\n    self: HttpRouter<E, R>,\n    tag: T,\n    effect: Effect.Effect<Context.Tag.Service<T>, E1, R1>\n  ): HttpRouter<\n    E | E1,\n    | Exclude<R, Context.Tag.Identifier<T>>\n    | Exclude<HttpRouter.ExcludeProvided<R1>, Context.Tag.Identifier<T>>\n  >\n} = internal.provideServiceEffect\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport const Tag: <const Name extends string>(\n  id: Name\n) => <Self, R = never, E = unknown>() => HttpRouter.TagClass<Self, Name, E, R | HttpRouter.DefaultServices> =\n  internal.Tag\n\n/**\n * @since 1.0.0\n * @category tags\n */\nexport class Default extends Tag(\"@effect/platform/HttpRouter/Default\")<Default>() {}\n\n/**\n * @since 1.0.0\n * @category utils\n */\nexport const toHttpApp: <E, R>(self: HttpRouter<E, R>) => Effect.Effect<App.Default<E | Error.RouteNotFound, R>> =\n  internal.toHttpApp\n"
  },
  {
    "path": "packages/platform/src/HttpServerResponse.ts",
    "content": "/**\n * @since 1.0.0\n */\nimport type * as Effect from \"effect/Effect\"\nimport type { Inspectable } from \"effect/Inspectable\"\nimport type * as Runtime from \"effect/Runtime\"\nimport type * as Schema from \"effect/Schema\"\nimport type { ParseOptions } from \"effect/SchemaAST\"\nimport * as Stream from \"effect/Stream\"\nimport type { Cookie, CookiesError } from \"./Cookies.js\"\nimport * as Cookies from \"./Cookies.js\"\nimport type * as PlatformError from \"./Error.js\"\nimport type * as FileSystem from \"./FileSystem.js\"\nimport type * as Headers from \"./Headers.js\"\nimport * as Body from \"./HttpBody.js\"\nimport type * as Platform from \"./HttpPlatform.js\"\nimport type { Respondable } from \"./HttpServerRespondable.js\"\nimport * as internal from \"./internal/httpServerResponse.js\"\nimport type * as Template from \"./Template.js\"\nimport type * as UrlParams from \"./UrlParams.js\"\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport const TypeId: unique symbol = Symbol.for(\"@effect/platform/HttpServerResponse\")\n\n/**\n * @since 1.0.0\n * @category type ids\n */\nexport type TypeId = typeof TypeId\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface HttpServerResponse extends Effect.Effect<HttpServerResponse>, Inspectable, Respondable {\n  readonly [TypeId]: TypeId\n  readonly status: number\n  readonly statusText?: string | undefined\n  readonly headers: Headers.Headers\n  readonly cookies: Cookies.Cookies\n  readonly body: Body.HttpBody\n}\n\n/**\n * @since 1.0.0\n * @category models\n */\nexport interface Options {\n  readonly status?: number | undefined\n  readonly statusText?: string | undefined\n  readonly headers?: Headers.Input | undefined\n  readonly cookies?: Cookies.Cookies | undefined\n  readonly contentType?: string | undefined\n  readonly contentLength?: number | undefined\n}\n\n/**\n * @since 1.0.0\n */\nexport declare namespace Options {\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface WithContent extends Omit<Options, \"contentType\" | \"contentLength\"> {}\n\n  /**\n   * @since 1.0.0\n   * @category models\n   */\n  export interface WithContentType extends Omit<Options, \"contentLength\"> {}\n}\n\n/**\n * @since 1.0.0\n */\nexport const isServerResponse: (u: unknown) => u is HttpServerResponse = internal.isServerResponse\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const empty: (options?: Options.WithContent | undefined) => HttpServerResponse = internal.empty\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const redirect: (location: string | URL, options?: Options.WithContentType | undefined) => HttpServerResponse =\n  internal.redirect\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const uint8Array: (body: Uint8Array, options?: Options.WithContentType | undefined) => HttpServerResponse =\n  internal.uint8Array\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const text: (body: string, options?: Options.WithContentType | undefined) => HttpServerResponse = internal.text\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const html: {\n  <A extends ReadonlyArray<Template.Interpolated>>(\n    strings: TemplateStringsArray,\n    ...args: A\n  ): Effect.Effect<HttpServerResponse, Template.Interpolated.Error<A[number]>, Template.Interpolated.Context<A[number]>>\n  (html: string): HttpServerResponse\n} = internal.html\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const htmlStream: <A extends ReadonlyArray<Template.InterpolatedWithStream>>(\n  strings: TemplateStringsArray,\n  ...args: A\n) => Effect.Effect<HttpServerResponse, never, Template.Interpolated.Context<A[number]>> = internal.htmlStream\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const json: (\n  body: unknown,\n  options?: Options.WithContentType | undefined\n) => Effect.Effect<HttpServerResponse, Body.HttpBodyError> = internal.json\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const schemaJson: <A, I, R>(\n  schema: Schema.Schema<A, I, R>,\n  options?: ParseOptions | undefined\n) => (\n  body: A,\n  options?: Options.WithContentType | undefined\n) => Effect.Effect<HttpServerResponse, Body.HttpBodyError, R> = internal.schemaJson\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const unsafeJson: (body: unknown, options?: Options.WithContentType | undefined) => HttpServerResponse =\n  internal.unsafeJson\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const urlParams: (body: UrlParams.Input, options?: Options.WithContentType | undefined) => HttpServerResponse =\n  internal.urlParams\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const raw: (body: unknown, options?: Options | undefined) => HttpServerResponse = internal.raw\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const formData: (body: FormData, options?: Options.WithContent | undefined) => HttpServerResponse =\n  internal.formData\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const stream: <E>(\n  body: Stream.Stream<Uint8Array, E, never>,\n  options?: Options | undefined\n) => HttpServerResponse = internal.stream\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const file: (\n  path: string,\n  options?: (Options & FileSystem.StreamOptions) | undefined\n) => Effect.Effect<HttpServerResponse, PlatformError.PlatformError, Platform.HttpPlatform> = internal.file\n\n/**\n * @since 1.0.0\n * @category constructors\n */\nexport const fileWeb: (\n  file: Body.HttpBody.FileLike,\n  options?: (Options.WithContent & FileSystem.StreamOptions) | undefined\n) => Effect.Effect<HttpServerResponse, never, Platform.HttpPlatform> = internal.fileWeb\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setHeader: {\n  (key: string, value: string): (self: HttpServerResponse) => HttpServerResponse\n  (self: HttpServerResponse, key: string, value: string): HttpServerResponse\n} = internal.setHeader\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setHeaders: {\n  (input: Headers.Input): (self: HttpServerResponse) => HttpServerResponse\n  (self: HttpServerResponse, input: Headers.Input): HttpServerResponse\n} = internal.setHeaders\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const removeCookie: {\n  (name: string): (self: HttpServerResponse) => HttpServerResponse\n  (self: HttpServerResponse, name: string): HttpServerResponse\n} = internal.removeCookie\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const expireCookie: {\n  (\n    name: string,\n    options?: Omit<Cookie[\"options\"], \"expires\" | \"maxAge\">\n  ): (self: HttpServerResponse) => HttpServerResponse\n  (\n    self: HttpServerResponse,\n    name: string,\n    options?: Omit<Cookie[\"options\"], \"expires\" | \"maxAge\">\n  ): HttpServerResponse\n} = internal.expireCookie\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const replaceCookies: {\n  (cookies: Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse\n  (self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse\n} = internal.replaceCookies\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setCookie: {\n  (\n    name: string,\n    value: string,\n    options?: Cookie[\"options\"]\n  ): (\n    self: HttpServerResponse\n  ) => Effect.Effect<\n    HttpServerResponse,\n    CookiesError\n  >\n  (\n    self: HttpServerResponse,\n    name: string,\n    value: string,\n    options?: Cookie[\"options\"]\n  ): Effect.Effect<\n    HttpServerResponse,\n    CookiesError\n  >\n} = internal.setCookie\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const unsafeSetCookie: {\n  (\n    name: string,\n    value: string,\n    options?: Cookie[\"options\"]\n  ): (self: HttpServerResponse) => HttpServerResponse\n  (\n    self: HttpServerResponse,\n    name: string,\n    value: string,\n    options?: Cookie[\"options\"]\n  ): HttpServerResponse\n} = internal.unsafeSetCookie\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const updateCookies: {\n  (f: (cookies: Cookies.Cookies) => Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse\n  (self: HttpServerResponse, f: (cookies: Cookies.Cookies) => Cookies.Cookies): HttpServerResponse\n} = internal.updateCookies\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const mergeCookies: {\n  (cookies: Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse\n  (self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse\n} = internal.mergeCookies\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setCookies: {\n  (\n    cookies: Iterable<\n      readonly [\n        name: string,\n        value: string,\n        options?: Cookie[\"options\"]\n      ]\n    >\n  ): (self: HttpServerResponse) => Effect.Effect<HttpServerResponse, CookiesError, never>\n  (\n    self: HttpServerResponse,\n    cookies: Iterable<\n      readonly [\n        name: string,\n        value: string,\n        options?: Cookie[\"options\"]\n      ]\n    >\n  ): Effect.Effect<HttpServerResponse, CookiesError, never>\n} = internal.setCookies\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const unsafeSetCookies: {\n  (\n    cookies: Iterable<\n      readonly [\n        name: string,\n        value: string,\n        options?: Cookie[\"options\"]\n      ]\n    >\n  ): (self: HttpServerResponse) => HttpServerResponse\n  (\n    self: HttpServerResponse,\n    cookies: Iterable<\n      readonly [\n        name: string,\n        value: string,\n        options?: Cookie[\"options\"]\n      ]\n    >\n  ): HttpServerResponse\n} = internal.unsafeSetCookies\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setBody: {\n  (body: Body.HttpBody): (self: HttpServerResponse) => HttpServerResponse\n  (self: HttpServerResponse, body: Body.HttpBody): HttpServerResponse\n} = internal.setBody\n\n/**\n * @since 1.0.0\n * @category combinators\n */\nexport const setStatus: {\n  (status: number, statusText?: string | undefined): (self: HttpServerResponse) => HttpServerResponse\n  (self: HttpServerResponse, status: number, statusText?: string | undefined): HttpServerResponse\n} = internal.setStatus\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const toWeb: (\n  response: HttpServerResponse,\n  options?: {\n    readonly withoutBody?: boolean | undefined\n    readonly runtime?: Runtime.Runtime<never> | undefined\n  }\n) => Response = internal.toWeb\n\n/**\n * @since 1.0.0\n * @category conversions\n */\nexport const fromWeb = (response: Response): HttpServerResponse => {\n  const headers = new globalThis.Headers(response.headers)\n  const setCookieHeaders = headers.getSetCookie()\n  headers.delete(\"set-cookie\")\n  let self = empty({\n    status: response.status,\n    statusText: response.statusText,\n    headers: headers as any,\n    cookies: Cookies.fromSetCookie(setCookieHeaders)\n  })\n  if (response.body) {\n    const contentType = headers.get(\"content-type\")\n    self = setBody(\n      self,\n      Body.stream(\n        Stream.fromReadableStream({\n          evaluate: () => response.body!,\n          onError: (e) => e\n        }),\n        contentType ?? undefined\n      )\n    )\n  }\n  return self\n}\n"
  }
]